lxd-2.0.11/0000755061062106075000000000000013172163435013475 5ustar stgraberdomain adminslxd-2.0.11/dist/0000755061062106075000000000000013172163304014433 5ustar stgraberdomain adminslxd-2.0.11/dist/src/0000755061062106075000000000000013172163312015221 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/0000755061062106075000000000000013172163312017256 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/0000755061062106075000000000000013172163420017525 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/0000755061062106075000000000000013172163421020344 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/windows/0000755061062106075000000000000013172163421022036 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/windows/zsyscall_windows.go0000644061062106075000000023625213172163421026015 0ustar stgraberdomain admins// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT package windows import ( "syscall" "unsafe" ) var _ unsafe.Pointer // Do the interface allocations only once for common // Errno values. const ( errnoERROR_IO_PENDING = 997 ) var ( errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) ) // errnoErr returns common boxed Errno values, to prevent // allocations at runtime. func errnoErr(e syscall.Errno) error { switch e { case 0: return nil case errnoERROR_IO_PENDING: return errERROR_IO_PENDING } // TODO: add more here, after collecting data on the common // error values see on Windows. (perhaps when running // all.bat?) return e } var ( modadvapi32 = NewLazySystemDLL("advapi32.dll") modkernel32 = NewLazySystemDLL("kernel32.dll") modshell32 = NewLazySystemDLL("shell32.dll") modmswsock = NewLazySystemDLL("mswsock.dll") modcrypt32 = NewLazySystemDLL("crypt32.dll") modws2_32 = NewLazySystemDLL("ws2_32.dll") moddnsapi = NewLazySystemDLL("dnsapi.dll") modiphlpapi = NewLazySystemDLL("iphlpapi.dll") modsecur32 = NewLazySystemDLL("secur32.dll") modnetapi32 = NewLazySystemDLL("netapi32.dll") moduserenv = NewLazySystemDLL("userenv.dll") procRegisterEventSourceW = modadvapi32.NewProc("RegisterEventSourceW") procDeregisterEventSource = modadvapi32.NewProc("DeregisterEventSource") procReportEventW = modadvapi32.NewProc("ReportEventW") procOpenSCManagerW = modadvapi32.NewProc("OpenSCManagerW") procCloseServiceHandle = modadvapi32.NewProc("CloseServiceHandle") procCreateServiceW = modadvapi32.NewProc("CreateServiceW") procOpenServiceW = modadvapi32.NewProc("OpenServiceW") procDeleteService = modadvapi32.NewProc("DeleteService") procStartServiceW = modadvapi32.NewProc("StartServiceW") procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus") procControlService = modadvapi32.NewProc("ControlService") procStartServiceCtrlDispatcherW = modadvapi32.NewProc("StartServiceCtrlDispatcherW") procSetServiceStatus = modadvapi32.NewProc("SetServiceStatus") procChangeServiceConfigW = modadvapi32.NewProc("ChangeServiceConfigW") procQueryServiceConfigW = modadvapi32.NewProc("QueryServiceConfigW") procChangeServiceConfig2W = modadvapi32.NewProc("ChangeServiceConfig2W") procQueryServiceConfig2W = modadvapi32.NewProc("QueryServiceConfig2W") procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW") procGetLastError = modkernel32.NewProc("GetLastError") procLoadLibraryW = modkernel32.NewProc("LoadLibraryW") procLoadLibraryExW = modkernel32.NewProc("LoadLibraryExW") procFreeLibrary = modkernel32.NewProc("FreeLibrary") procGetProcAddress = modkernel32.NewProc("GetProcAddress") procGetVersion = modkernel32.NewProc("GetVersion") procFormatMessageW = modkernel32.NewProc("FormatMessageW") procExitProcess = modkernel32.NewProc("ExitProcess") procCreateFileW = modkernel32.NewProc("CreateFileW") procReadFile = modkernel32.NewProc("ReadFile") procWriteFile = modkernel32.NewProc("WriteFile") procSetFilePointer = modkernel32.NewProc("SetFilePointer") procCloseHandle = modkernel32.NewProc("CloseHandle") procGetStdHandle = modkernel32.NewProc("GetStdHandle") procSetStdHandle = modkernel32.NewProc("SetStdHandle") procFindFirstFileW = modkernel32.NewProc("FindFirstFileW") procFindNextFileW = modkernel32.NewProc("FindNextFileW") procFindClose = modkernel32.NewProc("FindClose") procGetFileInformationByHandle = modkernel32.NewProc("GetFileInformationByHandle") procGetCurrentDirectoryW = modkernel32.NewProc("GetCurrentDirectoryW") procSetCurrentDirectoryW = modkernel32.NewProc("SetCurrentDirectoryW") procCreateDirectoryW = modkernel32.NewProc("CreateDirectoryW") procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW") procDeleteFileW = modkernel32.NewProc("DeleteFileW") procMoveFileW = modkernel32.NewProc("MoveFileW") procMoveFileExW = modkernel32.NewProc("MoveFileExW") procGetComputerNameW = modkernel32.NewProc("GetComputerNameW") procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW") procSetEndOfFile = modkernel32.NewProc("SetEndOfFile") procGetSystemTimeAsFileTime = modkernel32.NewProc("GetSystemTimeAsFileTime") procGetSystemTimePreciseAsFileTime = modkernel32.NewProc("GetSystemTimePreciseAsFileTime") procGetTimeZoneInformation = modkernel32.NewProc("GetTimeZoneInformation") procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") procPostQueuedCompletionStatus = modkernel32.NewProc("PostQueuedCompletionStatus") procCancelIo = modkernel32.NewProc("CancelIo") procCancelIoEx = modkernel32.NewProc("CancelIoEx") procCreateProcessW = modkernel32.NewProc("CreateProcessW") procOpenProcess = modkernel32.NewProc("OpenProcess") procTerminateProcess = modkernel32.NewProc("TerminateProcess") procGetExitCodeProcess = modkernel32.NewProc("GetExitCodeProcess") procGetStartupInfoW = modkernel32.NewProc("GetStartupInfoW") procGetCurrentProcess = modkernel32.NewProc("GetCurrentProcess") procGetProcessTimes = modkernel32.NewProc("GetProcessTimes") procDuplicateHandle = modkernel32.NewProc("DuplicateHandle") procWaitForSingleObject = modkernel32.NewProc("WaitForSingleObject") procGetTempPathW = modkernel32.NewProc("GetTempPathW") procCreatePipe = modkernel32.NewProc("CreatePipe") procGetFileType = modkernel32.NewProc("GetFileType") procCryptAcquireContextW = modadvapi32.NewProc("CryptAcquireContextW") procCryptReleaseContext = modadvapi32.NewProc("CryptReleaseContext") procCryptGenRandom = modadvapi32.NewProc("CryptGenRandom") procGetEnvironmentStringsW = modkernel32.NewProc("GetEnvironmentStringsW") procFreeEnvironmentStringsW = modkernel32.NewProc("FreeEnvironmentStringsW") procGetEnvironmentVariableW = modkernel32.NewProc("GetEnvironmentVariableW") procSetEnvironmentVariableW = modkernel32.NewProc("SetEnvironmentVariableW") procSetFileTime = modkernel32.NewProc("SetFileTime") procGetFileAttributesW = modkernel32.NewProc("GetFileAttributesW") procSetFileAttributesW = modkernel32.NewProc("SetFileAttributesW") procGetFileAttributesExW = modkernel32.NewProc("GetFileAttributesExW") procGetCommandLineW = modkernel32.NewProc("GetCommandLineW") procCommandLineToArgvW = modshell32.NewProc("CommandLineToArgvW") procLocalFree = modkernel32.NewProc("LocalFree") procSetHandleInformation = modkernel32.NewProc("SetHandleInformation") procFlushFileBuffers = modkernel32.NewProc("FlushFileBuffers") procGetFullPathNameW = modkernel32.NewProc("GetFullPathNameW") procGetLongPathNameW = modkernel32.NewProc("GetLongPathNameW") procGetShortPathNameW = modkernel32.NewProc("GetShortPathNameW") procCreateFileMappingW = modkernel32.NewProc("CreateFileMappingW") procMapViewOfFile = modkernel32.NewProc("MapViewOfFile") procUnmapViewOfFile = modkernel32.NewProc("UnmapViewOfFile") procFlushViewOfFile = modkernel32.NewProc("FlushViewOfFile") procVirtualLock = modkernel32.NewProc("VirtualLock") procVirtualUnlock = modkernel32.NewProc("VirtualUnlock") procVirtualAlloc = modkernel32.NewProc("VirtualAlloc") procVirtualFree = modkernel32.NewProc("VirtualFree") procVirtualProtect = modkernel32.NewProc("VirtualProtect") procTransmitFile = modmswsock.NewProc("TransmitFile") procReadDirectoryChangesW = modkernel32.NewProc("ReadDirectoryChangesW") procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW") procCertOpenStore = modcrypt32.NewProc("CertOpenStore") procCertEnumCertificatesInStore = modcrypt32.NewProc("CertEnumCertificatesInStore") procCertAddCertificateContextToStore = modcrypt32.NewProc("CertAddCertificateContextToStore") procCertCloseStore = modcrypt32.NewProc("CertCloseStore") procCertGetCertificateChain = modcrypt32.NewProc("CertGetCertificateChain") procCertFreeCertificateChain = modcrypt32.NewProc("CertFreeCertificateChain") procCertCreateCertificateContext = modcrypt32.NewProc("CertCreateCertificateContext") procCertFreeCertificateContext = modcrypt32.NewProc("CertFreeCertificateContext") procCertVerifyCertificateChainPolicy = modcrypt32.NewProc("CertVerifyCertificateChainPolicy") procRegOpenKeyExW = modadvapi32.NewProc("RegOpenKeyExW") procRegCloseKey = modadvapi32.NewProc("RegCloseKey") procRegQueryInfoKeyW = modadvapi32.NewProc("RegQueryInfoKeyW") procRegEnumKeyExW = modadvapi32.NewProc("RegEnumKeyExW") procRegQueryValueExW = modadvapi32.NewProc("RegQueryValueExW") procGetCurrentProcessId = modkernel32.NewProc("GetCurrentProcessId") procGetConsoleMode = modkernel32.NewProc("GetConsoleMode") procSetConsoleMode = modkernel32.NewProc("SetConsoleMode") procGetConsoleScreenBufferInfo = modkernel32.NewProc("GetConsoleScreenBufferInfo") procWriteConsoleW = modkernel32.NewProc("WriteConsoleW") procReadConsoleW = modkernel32.NewProc("ReadConsoleW") procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot") procProcess32FirstW = modkernel32.NewProc("Process32FirstW") procProcess32NextW = modkernel32.NewProc("Process32NextW") procDeviceIoControl = modkernel32.NewProc("DeviceIoControl") procCreateSymbolicLinkW = modkernel32.NewProc("CreateSymbolicLinkW") procCreateHardLinkW = modkernel32.NewProc("CreateHardLinkW") procGetCurrentThreadId = modkernel32.NewProc("GetCurrentThreadId") procCreateEventW = modkernel32.NewProc("CreateEventW") procCreateEventExW = modkernel32.NewProc("CreateEventExW") procOpenEventW = modkernel32.NewProc("OpenEventW") procSetEvent = modkernel32.NewProc("SetEvent") procResetEvent = modkernel32.NewProc("ResetEvent") procPulseEvent = modkernel32.NewProc("PulseEvent") procWSAStartup = modws2_32.NewProc("WSAStartup") procWSACleanup = modws2_32.NewProc("WSACleanup") procWSAIoctl = modws2_32.NewProc("WSAIoctl") procsocket = modws2_32.NewProc("socket") procsetsockopt = modws2_32.NewProc("setsockopt") procgetsockopt = modws2_32.NewProc("getsockopt") procbind = modws2_32.NewProc("bind") procconnect = modws2_32.NewProc("connect") procgetsockname = modws2_32.NewProc("getsockname") procgetpeername = modws2_32.NewProc("getpeername") proclisten = modws2_32.NewProc("listen") procshutdown = modws2_32.NewProc("shutdown") procclosesocket = modws2_32.NewProc("closesocket") procAcceptEx = modmswsock.NewProc("AcceptEx") procGetAcceptExSockaddrs = modmswsock.NewProc("GetAcceptExSockaddrs") procWSARecv = modws2_32.NewProc("WSARecv") procWSASend = modws2_32.NewProc("WSASend") procWSARecvFrom = modws2_32.NewProc("WSARecvFrom") procWSASendTo = modws2_32.NewProc("WSASendTo") procgethostbyname = modws2_32.NewProc("gethostbyname") procgetservbyname = modws2_32.NewProc("getservbyname") procntohs = modws2_32.NewProc("ntohs") procgetprotobyname = modws2_32.NewProc("getprotobyname") procDnsQuery_W = moddnsapi.NewProc("DnsQuery_W") procDnsRecordListFree = moddnsapi.NewProc("DnsRecordListFree") procDnsNameCompare_W = moddnsapi.NewProc("DnsNameCompare_W") procGetAddrInfoW = modws2_32.NewProc("GetAddrInfoW") procFreeAddrInfoW = modws2_32.NewProc("FreeAddrInfoW") procGetIfEntry = modiphlpapi.NewProc("GetIfEntry") procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo") procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") procWSAEnumProtocolsW = modws2_32.NewProc("WSAEnumProtocolsW") procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses") procGetACP = modkernel32.NewProc("GetACP") procMultiByteToWideChar = modkernel32.NewProc("MultiByteToWideChar") procTranslateNameW = modsecur32.NewProc("TranslateNameW") procGetUserNameExW = modsecur32.NewProc("GetUserNameExW") procNetUserGetInfo = modnetapi32.NewProc("NetUserGetInfo") procNetGetJoinInformation = modnetapi32.NewProc("NetGetJoinInformation") procNetApiBufferFree = modnetapi32.NewProc("NetApiBufferFree") procLookupAccountSidW = modadvapi32.NewProc("LookupAccountSidW") procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") procConvertStringSidToSidW = modadvapi32.NewProc("ConvertStringSidToSidW") procGetLengthSid = modadvapi32.NewProc("GetLengthSid") procCopySid = modadvapi32.NewProc("CopySid") procAllocateAndInitializeSid = modadvapi32.NewProc("AllocateAndInitializeSid") procFreeSid = modadvapi32.NewProc("FreeSid") procEqualSid = modadvapi32.NewProc("EqualSid") procOpenProcessToken = modadvapi32.NewProc("OpenProcessToken") procGetTokenInformation = modadvapi32.NewProc("GetTokenInformation") procGetUserProfileDirectoryW = moduserenv.NewProc("GetUserProfileDirectoryW") ) func RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procRegisterEventSourceW.Addr(), 2, uintptr(unsafe.Pointer(uncServerName)), uintptr(unsafe.Pointer(sourceName)), 0) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func DeregisterEventSource(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procDeregisterEventSource.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) { r1, _, e1 := syscall.Syscall9(procReportEventW.Addr(), 9, uintptr(log), uintptr(etype), uintptr(category), uintptr(eventId), uintptr(usrSId), uintptr(numStrings), uintptr(dataSize), uintptr(unsafe.Pointer(strings)), uintptr(unsafe.Pointer(rawData))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procOpenSCManagerW.Addr(), 3, uintptr(unsafe.Pointer(machineName)), uintptr(unsafe.Pointer(databaseName)), uintptr(access)) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CloseServiceHandle(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procCloseServiceHandle.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) { r0, _, e1 := syscall.Syscall15(procCreateServiceW.Addr(), 13, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(unsafe.Pointer(displayName)), uintptr(access), uintptr(srvType), uintptr(startType), uintptr(errCtl), uintptr(unsafe.Pointer(pathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), 0, 0) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procOpenServiceW.Addr(), 3, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(access)) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func DeleteService(service Handle) (err error) { r1, _, e1 := syscall.Syscall(procDeleteService.Addr(), 1, uintptr(service), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) { r1, _, e1 := syscall.Syscall(procStartServiceW.Addr(), 3, uintptr(service), uintptr(numArgs), uintptr(unsafe.Pointer(argVectors))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) { r1, _, e1 := syscall.Syscall(procQueryServiceStatus.Addr(), 2, uintptr(service), uintptr(unsafe.Pointer(status)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) { r1, _, e1 := syscall.Syscall(procControlService.Addr(), 3, uintptr(service), uintptr(control), uintptr(unsafe.Pointer(status))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) { r1, _, e1 := syscall.Syscall(procStartServiceCtrlDispatcherW.Addr(), 1, uintptr(unsafe.Pointer(serviceTable)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) { r1, _, e1 := syscall.Syscall(procSetServiceStatus.Addr(), 2, uintptr(service), uintptr(unsafe.Pointer(serviceStatus)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) { r1, _, e1 := syscall.Syscall12(procChangeServiceConfigW.Addr(), 11, uintptr(service), uintptr(serviceType), uintptr(startType), uintptr(errorControl), uintptr(unsafe.Pointer(binaryPathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), uintptr(unsafe.Pointer(displayName)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) { r1, _, e1 := syscall.Syscall6(procQueryServiceConfigW.Addr(), 4, uintptr(service), uintptr(unsafe.Pointer(serviceConfig)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) { r1, _, e1 := syscall.Syscall(procChangeServiceConfig2W.Addr(), 3, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(info))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) { r1, _, e1 := syscall.Syscall6(procQueryServiceConfig2W.Addr(), 5, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(buff)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) { r1, _, e1 := syscall.Syscall12(procEnumServicesStatusExW.Addr(), 10, uintptr(mgr), uintptr(infoLevel), uintptr(serviceType), uintptr(serviceState), uintptr(unsafe.Pointer(services)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), uintptr(unsafe.Pointer(servicesReturned)), uintptr(unsafe.Pointer(resumeHandle)), uintptr(unsafe.Pointer(groupName)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetLastError() (lasterr error) { r0, _, _ := syscall.Syscall(procGetLastError.Addr(), 0, 0, 0, 0) if r0 != 0 { lasterr = syscall.Errno(r0) } return } func LoadLibrary(libname string) (handle Handle, err error) { var _p0 *uint16 _p0, err = syscall.UTF16PtrFromString(libname) if err != nil { return } return _LoadLibrary(_p0) } func _LoadLibrary(libname *uint16) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procLoadLibraryW.Addr(), 1, uintptr(unsafe.Pointer(libname)), 0, 0) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) { var _p0 *uint16 _p0, err = syscall.UTF16PtrFromString(libname) if err != nil { return } return _LoadLibraryEx(_p0, zero, flags) } func _LoadLibraryEx(libname *uint16, zero Handle, flags uintptr) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procLoadLibraryExW.Addr(), 3, uintptr(unsafe.Pointer(libname)), uintptr(zero), uintptr(flags)) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func FreeLibrary(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procFreeLibrary.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetProcAddress(module Handle, procname string) (proc uintptr, err error) { var _p0 *byte _p0, err = syscall.BytePtrFromString(procname) if err != nil { return } return _GetProcAddress(module, _p0) } func _GetProcAddress(module Handle, procname *byte) (proc uintptr, err error) { r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), uintptr(unsafe.Pointer(procname)), 0) proc = uintptr(r0) if proc == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetVersion() (ver uint32, err error) { r0, _, e1 := syscall.Syscall(procGetVersion.Addr(), 0, 0, 0, 0) ver = uint32(r0) if ver == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) { var _p0 *uint16 if len(buf) > 0 { _p0 = &buf[0] } r0, _, e1 := syscall.Syscall9(procFormatMessageW.Addr(), 7, uintptr(flags), uintptr(msgsrc), uintptr(msgid), uintptr(langid), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(args)), 0, 0) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ExitProcess(exitcode uint32) { syscall.Syscall(procExitProcess.Addr(), 1, uintptr(exitcode), 0, 0) return } func CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) { r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) handle = Handle(r0) if handle == InvalidHandle { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) { var _p0 *byte if len(buf) > 0 { _p0 = &buf[0] } r1, _, e1 := syscall.Syscall6(procReadFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) { var _p0 *byte if len(buf) > 0 { _p0 = &buf[0] } r1, _, e1 := syscall.Syscall6(procWriteFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) { r0, _, e1 := syscall.Syscall6(procSetFilePointer.Addr(), 4, uintptr(handle), uintptr(lowoffset), uintptr(unsafe.Pointer(highoffsetptr)), uintptr(whence), 0, 0) newlowoffset = uint32(r0) if newlowoffset == 0xffffffff { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CloseHandle(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procCloseHandle.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetStdHandle(stdhandle uint32) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procGetStdHandle.Addr(), 1, uintptr(stdhandle), 0, 0) handle = Handle(r0) if handle == InvalidHandle { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetStdHandle(stdhandle uint32, handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procFindFirstFileW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(data)), 0) handle = Handle(r0) if handle == InvalidHandle { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func findNextFile1(handle Handle, data *win32finddata1) (err error) { r1, _, e1 := syscall.Syscall(procFindNextFileW.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(data)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func FindClose(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procFindClose.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) { r1, _, e1 := syscall.Syscall(procGetFileInformationByHandle.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(data)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procGetCurrentDirectoryW.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetCurrentDirectory(path *uint16) (err error) { r1, _, e1 := syscall.Syscall(procSetCurrentDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) { r1, _, e1 := syscall.Syscall(procCreateDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(sa)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func RemoveDirectory(path *uint16) (err error) { r1, _, e1 := syscall.Syscall(procRemoveDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func DeleteFile(path *uint16) (err error) { r1, _, e1 := syscall.Syscall(procDeleteFileW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func MoveFile(from *uint16, to *uint16) (err error) { r1, _, e1 := syscall.Syscall(procMoveFileW.Addr(), 2, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) { r1, _, e1 := syscall.Syscall(procMoveFileExW.Addr(), 3, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), uintptr(flags)) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetComputerName(buf *uint16, n *uint32) (err error) { r1, _, e1 := syscall.Syscall(procGetComputerNameW.Addr(), 2, uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) { r1, _, e1 := syscall.Syscall(procGetComputerNameExW.Addr(), 3, uintptr(nametype), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetEndOfFile(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procSetEndOfFile.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetSystemTimeAsFileTime(time *Filetime) { syscall.Syscall(procGetSystemTimeAsFileTime.Addr(), 1, uintptr(unsafe.Pointer(time)), 0, 0) return } func GetSystemTimePreciseAsFileTime(time *Filetime) { syscall.Syscall(procGetSystemTimePreciseAsFileTime.Addr(), 1, uintptr(unsafe.Pointer(time)), 0, 0) return } func GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) { r0, _, e1 := syscall.Syscall(procGetTimeZoneInformation.Addr(), 1, uintptr(unsafe.Pointer(tzi)), 0, 0) rc = uint32(r0) if rc == 0xffffffff { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error) { r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(filehandle), uintptr(cphandle), uintptr(key), uintptr(threadcnt), 0, 0) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error) { r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(cphandle), uintptr(unsafe.Pointer(qty)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(overlapped)), uintptr(timeout), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.Syscall6(procPostQueuedCompletionStatus.Addr(), 4, uintptr(cphandle), uintptr(qty), uintptr(key), uintptr(unsafe.Pointer(overlapped)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CancelIo(s Handle) (err error) { r1, _, e1 := syscall.Syscall(procCancelIo.Addr(), 1, uintptr(s), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CancelIoEx(s Handle, o *Overlapped) (err error) { r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(s), uintptr(unsafe.Pointer(o)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) { var _p0 uint32 if inheritHandles { _p0 = 1 } else { _p0 = 0 } r1, _, e1 := syscall.Syscall12(procCreateProcessW.Addr(), 10, uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func OpenProcess(da uint32, inheritHandle bool, pid uint32) (handle Handle, err error) { var _p0 uint32 if inheritHandle { _p0 = 1 } else { _p0 = 0 } r0, _, e1 := syscall.Syscall(procOpenProcess.Addr(), 3, uintptr(da), uintptr(_p0), uintptr(pid)) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func TerminateProcess(handle Handle, exitcode uint32) (err error) { r1, _, e1 := syscall.Syscall(procTerminateProcess.Addr(), 2, uintptr(handle), uintptr(exitcode), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) { r1, _, e1 := syscall.Syscall(procGetExitCodeProcess.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(exitcode)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetStartupInfo(startupInfo *StartupInfo) (err error) { r1, _, e1 := syscall.Syscall(procGetStartupInfoW.Addr(), 1, uintptr(unsafe.Pointer(startupInfo)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetCurrentProcess() (pseudoHandle Handle, err error) { r0, _, e1 := syscall.Syscall(procGetCurrentProcess.Addr(), 0, 0, 0, 0) pseudoHandle = Handle(r0) if pseudoHandle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) { r1, _, e1 := syscall.Syscall6(procGetProcessTimes.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(creationTime)), uintptr(unsafe.Pointer(exitTime)), uintptr(unsafe.Pointer(kernelTime)), uintptr(unsafe.Pointer(userTime)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) { var _p0 uint32 if bInheritHandle { _p0 = 1 } else { _p0 = 0 } r1, _, e1 := syscall.Syscall9(procDuplicateHandle.Addr(), 7, uintptr(hSourceProcessHandle), uintptr(hSourceHandle), uintptr(hTargetProcessHandle), uintptr(unsafe.Pointer(lpTargetHandle)), uintptr(dwDesiredAccess), uintptr(_p0), uintptr(dwOptions), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) { r0, _, e1 := syscall.Syscall(procWaitForSingleObject.Addr(), 2, uintptr(handle), uintptr(waitMilliseconds), 0) event = uint32(r0) if event == 0xffffffff { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procGetTempPathW.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) { r1, _, e1 := syscall.Syscall6(procCreatePipe.Addr(), 4, uintptr(unsafe.Pointer(readhandle)), uintptr(unsafe.Pointer(writehandle)), uintptr(unsafe.Pointer(sa)), uintptr(size), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetFileType(filehandle Handle) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procGetFileType.Addr(), 1, uintptr(filehandle), 0, 0) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) { r1, _, e1 := syscall.Syscall6(procCryptAcquireContextW.Addr(), 5, uintptr(unsafe.Pointer(provhandle)), uintptr(unsafe.Pointer(container)), uintptr(unsafe.Pointer(provider)), uintptr(provtype), uintptr(flags), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CryptReleaseContext(provhandle Handle, flags uint32) (err error) { r1, _, e1 := syscall.Syscall(procCryptReleaseContext.Addr(), 2, uintptr(provhandle), uintptr(flags), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) { r1, _, e1 := syscall.Syscall(procCryptGenRandom.Addr(), 3, uintptr(provhandle), uintptr(buflen), uintptr(unsafe.Pointer(buf))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetEnvironmentStrings() (envs *uint16, err error) { r0, _, e1 := syscall.Syscall(procGetEnvironmentStringsW.Addr(), 0, 0, 0, 0) envs = (*uint16)(unsafe.Pointer(r0)) if envs == nil { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func FreeEnvironmentStrings(envs *uint16) (err error) { r1, _, e1 := syscall.Syscall(procFreeEnvironmentStringsW.Addr(), 1, uintptr(unsafe.Pointer(envs)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procGetEnvironmentVariableW.Addr(), 3, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(size)) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetEnvironmentVariable(name *uint16, value *uint16) (err error) { r1, _, e1 := syscall.Syscall(procSetEnvironmentVariableW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(value)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) { r1, _, e1 := syscall.Syscall6(procSetFileTime.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(ctime)), uintptr(unsafe.Pointer(atime)), uintptr(unsafe.Pointer(wtime)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetFileAttributes(name *uint16) (attrs uint32, err error) { r0, _, e1 := syscall.Syscall(procGetFileAttributesW.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) attrs = uint32(r0) if attrs == INVALID_FILE_ATTRIBUTES { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetFileAttributes(name *uint16, attrs uint32) (err error) { r1, _, e1 := syscall.Syscall(procSetFileAttributesW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(attrs), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) { r1, _, e1 := syscall.Syscall(procGetFileAttributesExW.Addr(), 3, uintptr(unsafe.Pointer(name)), uintptr(level), uintptr(unsafe.Pointer(info))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetCommandLine() (cmd *uint16) { r0, _, _ := syscall.Syscall(procGetCommandLineW.Addr(), 0, 0, 0, 0) cmd = (*uint16)(unsafe.Pointer(r0)) return } func CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) { r0, _, e1 := syscall.Syscall(procCommandLineToArgvW.Addr(), 2, uintptr(unsafe.Pointer(cmd)), uintptr(unsafe.Pointer(argc)), 0) argv = (*[8192]*[8192]uint16)(unsafe.Pointer(r0)) if argv == nil { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func LocalFree(hmem Handle) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procLocalFree.Addr(), 1, uintptr(hmem), 0, 0) handle = Handle(r0) if handle != 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) { r1, _, e1 := syscall.Syscall(procSetHandleInformation.Addr(), 3, uintptr(handle), uintptr(mask), uintptr(flags)) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func FlushFileBuffers(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procFlushFileBuffers.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) { r0, _, e1 := syscall.Syscall6(procGetFullPathNameW.Addr(), 4, uintptr(unsafe.Pointer(path)), uintptr(buflen), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(fname)), 0, 0) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procGetLongPathNameW.Addr(), 3, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(buf)), uintptr(buflen)) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procGetShortPathNameW.Addr(), 3, uintptr(unsafe.Pointer(longpath)), uintptr(unsafe.Pointer(shortpath)), uintptr(buflen)) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) { r0, _, e1 := syscall.Syscall6(procCreateFileMappingW.Addr(), 6, uintptr(fhandle), uintptr(unsafe.Pointer(sa)), uintptr(prot), uintptr(maxSizeHigh), uintptr(maxSizeLow), uintptr(unsafe.Pointer(name))) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error) { r0, _, e1 := syscall.Syscall6(procMapViewOfFile.Addr(), 5, uintptr(handle), uintptr(access), uintptr(offsetHigh), uintptr(offsetLow), uintptr(length), 0) addr = uintptr(r0) if addr == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func UnmapViewOfFile(addr uintptr) (err error) { r1, _, e1 := syscall.Syscall(procUnmapViewOfFile.Addr(), 1, uintptr(addr), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func FlushViewOfFile(addr uintptr, length uintptr) (err error) { r1, _, e1 := syscall.Syscall(procFlushViewOfFile.Addr(), 2, uintptr(addr), uintptr(length), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func VirtualLock(addr uintptr, length uintptr) (err error) { r1, _, e1 := syscall.Syscall(procVirtualLock.Addr(), 2, uintptr(addr), uintptr(length), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func VirtualUnlock(addr uintptr, length uintptr) (err error) { r1, _, e1 := syscall.Syscall(procVirtualUnlock.Addr(), 2, uintptr(addr), uintptr(length), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) { r0, _, e1 := syscall.Syscall6(procVirtualAlloc.Addr(), 4, uintptr(address), uintptr(size), uintptr(alloctype), uintptr(protect), 0, 0) value = uintptr(r0) if value == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) { r1, _, e1 := syscall.Syscall(procVirtualFree.Addr(), 3, uintptr(address), uintptr(size), uintptr(freetype)) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) { r1, _, e1 := syscall.Syscall6(procVirtualProtect.Addr(), 4, uintptr(address), uintptr(size), uintptr(newprotect), uintptr(unsafe.Pointer(oldprotect)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) { r1, _, e1 := syscall.Syscall9(procTransmitFile.Addr(), 7, uintptr(s), uintptr(handle), uintptr(bytesToWrite), uintptr(bytsPerSend), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transmitFileBuf)), uintptr(flags), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) { var _p0 uint32 if watchSubTree { _p0 = 1 } else { _p0 = 0 } r1, _, e1 := syscall.Syscall9(procReadDirectoryChangesW.Addr(), 8, uintptr(handle), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(_p0), uintptr(mask), uintptr(unsafe.Pointer(retlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) { r0, _, e1 := syscall.Syscall(procCertOpenSystemStoreW.Addr(), 2, uintptr(hprov), uintptr(unsafe.Pointer(name)), 0) store = Handle(r0) if store == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) { r0, _, e1 := syscall.Syscall6(procCertOpenStore.Addr(), 5, uintptr(storeProvider), uintptr(msgAndCertEncodingType), uintptr(cryptProv), uintptr(flags), uintptr(para), 0) handle = Handle(r0) if handle == InvalidHandle { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) { r0, _, e1 := syscall.Syscall(procCertEnumCertificatesInStore.Addr(), 2, uintptr(store), uintptr(unsafe.Pointer(prevContext)), 0) context = (*CertContext)(unsafe.Pointer(r0)) if context == nil { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) { r1, _, e1 := syscall.Syscall6(procCertAddCertificateContextToStore.Addr(), 4, uintptr(store), uintptr(unsafe.Pointer(certContext)), uintptr(addDisposition), uintptr(unsafe.Pointer(storeContext)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertCloseStore(store Handle, flags uint32) (err error) { r1, _, e1 := syscall.Syscall(procCertCloseStore.Addr(), 2, uintptr(store), uintptr(flags), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) { r1, _, e1 := syscall.Syscall9(procCertGetCertificateChain.Addr(), 8, uintptr(engine), uintptr(unsafe.Pointer(leaf)), uintptr(unsafe.Pointer(time)), uintptr(additionalStore), uintptr(unsafe.Pointer(para)), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(chainCtx)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertFreeCertificateChain(ctx *CertChainContext) { syscall.Syscall(procCertFreeCertificateChain.Addr(), 1, uintptr(unsafe.Pointer(ctx)), 0, 0) return } func CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) { r0, _, e1 := syscall.Syscall(procCertCreateCertificateContext.Addr(), 3, uintptr(certEncodingType), uintptr(unsafe.Pointer(certEncoded)), uintptr(encodedLen)) context = (*CertContext)(unsafe.Pointer(r0)) if context == nil { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertFreeCertificateContext(ctx *CertContext) (err error) { r1, _, e1 := syscall.Syscall(procCertFreeCertificateContext.Addr(), 1, uintptr(unsafe.Pointer(ctx)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) { r1, _, e1 := syscall.Syscall6(procCertVerifyCertificateChainPolicy.Addr(), 4, uintptr(policyOID), uintptr(unsafe.Pointer(chain)), uintptr(unsafe.Pointer(para)), uintptr(unsafe.Pointer(status)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) { r0, _, _ := syscall.Syscall6(procRegOpenKeyExW.Addr(), 5, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(options), uintptr(desiredAccess), uintptr(unsafe.Pointer(result)), 0) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func RegCloseKey(key Handle) (regerrno error) { r0, _, _ := syscall.Syscall(procRegCloseKey.Addr(), 1, uintptr(key), 0, 0) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) { r0, _, _ := syscall.Syscall12(procRegQueryInfoKeyW.Addr(), 12, uintptr(key), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(subkeysLen)), uintptr(unsafe.Pointer(maxSubkeyLen)), uintptr(unsafe.Pointer(maxClassLen)), uintptr(unsafe.Pointer(valuesLen)), uintptr(unsafe.Pointer(maxValueNameLen)), uintptr(unsafe.Pointer(maxValueLen)), uintptr(unsafe.Pointer(saLen)), uintptr(unsafe.Pointer(lastWriteTime))) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) { r0, _, _ := syscall.Syscall9(procRegEnumKeyExW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(lastWriteTime)), 0) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) { r0, _, _ := syscall.Syscall6(procRegQueryValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen))) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func getCurrentProcessId() (pid uint32) { r0, _, _ := syscall.Syscall(procGetCurrentProcessId.Addr(), 0, 0, 0, 0) pid = uint32(r0) return } func GetConsoleMode(console Handle, mode *uint32) (err error) { r1, _, e1 := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(mode)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetConsoleMode(console Handle, mode uint32) (err error) { r1, _, e1 := syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(console), uintptr(mode), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) { r1, _, e1 := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(info)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) { r1, _, e1 := syscall.Syscall6(procWriteConsoleW.Addr(), 5, uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(towrite), uintptr(unsafe.Pointer(written)), uintptr(unsafe.Pointer(reserved)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) { r1, _, e1 := syscall.Syscall6(procReadConsoleW.Addr(), 5, uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(toread), uintptr(unsafe.Pointer(read)), uintptr(unsafe.Pointer(inputControl)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procCreateToolhelp32Snapshot.Addr(), 2, uintptr(flags), uintptr(processId), 0) handle = Handle(r0) if handle == InvalidHandle { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) { r1, _, e1 := syscall.Syscall(procProcess32FirstW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(procEntry)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) { r1, _, e1 := syscall.Syscall(procProcess32NextW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(procEntry)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.Syscall9(procDeviceIoControl.Addr(), 8, uintptr(handle), uintptr(ioControlCode), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferSize), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferSize), uintptr(unsafe.Pointer(bytesReturned)), uintptr(unsafe.Pointer(overlapped)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) { r1, _, e1 := syscall.Syscall(procCreateSymbolicLinkW.Addr(), 3, uintptr(unsafe.Pointer(symlinkfilename)), uintptr(unsafe.Pointer(targetfilename)), uintptr(flags)) if r1&0xff == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) { r1, _, e1 := syscall.Syscall(procCreateHardLinkW.Addr(), 3, uintptr(unsafe.Pointer(filename)), uintptr(unsafe.Pointer(existingfilename)), uintptr(reserved)) if r1&0xff == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetCurrentThreadId() (id uint32) { r0, _, _ := syscall.Syscall(procGetCurrentThreadId.Addr(), 0, 0, 0, 0) id = uint32(r0) return } func CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) { r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(manualReset), uintptr(initialState), uintptr(unsafe.Pointer(name)), 0, 0) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) { r0, _, e1 := syscall.Syscall6(procCreateEventExW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(desiredAccess), 0, 0) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) { var _p0 uint32 if inheritHandle { _p0 = 1 } else { _p0 = 0 } r0, _, e1 := syscall.Syscall(procOpenEventW.Addr(), 3, uintptr(desiredAccess), uintptr(_p0), uintptr(unsafe.Pointer(name))) handle = Handle(r0) if handle == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func SetEvent(event Handle) (err error) { r1, _, e1 := syscall.Syscall(procSetEvent.Addr(), 1, uintptr(event), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ResetEvent(event Handle) (err error) { r1, _, e1 := syscall.Syscall(procResetEvent.Addr(), 1, uintptr(event), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func PulseEvent(event Handle) (err error) { r1, _, e1 := syscall.Syscall(procPulseEvent.Addr(), 1, uintptr(event), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WSAStartup(verreq uint32, data *WSAData) (sockerr error) { r0, _, _ := syscall.Syscall(procWSAStartup.Addr(), 2, uintptr(verreq), uintptr(unsafe.Pointer(data)), 0) if r0 != 0 { sockerr = syscall.Errno(r0) } return } func WSACleanup() (err error) { r1, _, e1 := syscall.Syscall(procWSACleanup.Addr(), 0, 0, 0, 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) { r1, _, e1 := syscall.Syscall9(procWSAIoctl.Addr(), 9, uintptr(s), uintptr(iocc), uintptr(unsafe.Pointer(inbuf)), uintptr(cbif), uintptr(unsafe.Pointer(outbuf)), uintptr(cbob), uintptr(unsafe.Pointer(cbbr)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine)) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func socket(af int32, typ int32, protocol int32) (handle Handle, err error) { r0, _, e1 := syscall.Syscall(procsocket.Addr(), 3, uintptr(af), uintptr(typ), uintptr(protocol)) handle = Handle(r0) if handle == InvalidHandle { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) { r1, _, e1 := syscall.Syscall6(procsetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(optlen), 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) { r1, _, e1 := syscall.Syscall6(procgetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(unsafe.Pointer(optlen)), 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func bind(s Handle, name unsafe.Pointer, namelen int32) (err error) { r1, _, e1 := syscall.Syscall(procbind.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func connect(s Handle, name unsafe.Pointer, namelen int32) (err error) { r1, _, e1 := syscall.Syscall(procconnect.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) { r1, _, e1 := syscall.Syscall(procgetsockname.Addr(), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) { r1, _, e1 := syscall.Syscall(procgetpeername.Addr(), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func listen(s Handle, backlog int32) (err error) { r1, _, e1 := syscall.Syscall(proclisten.Addr(), 2, uintptr(s), uintptr(backlog), 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func shutdown(s Handle, how int32) (err error) { r1, _, e1 := syscall.Syscall(procshutdown.Addr(), 2, uintptr(s), uintptr(how), 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func Closesocket(s Handle) (err error) { r1, _, e1 := syscall.Syscall(procclosesocket.Addr(), 1, uintptr(s), 0, 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.Syscall9(procAcceptEx.Addr(), 8, uintptr(ls), uintptr(as), uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(overlapped)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) { syscall.Syscall9(procGetAcceptExSockaddrs.Addr(), 8, uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(lrsa)), uintptr(unsafe.Pointer(lrsalen)), uintptr(unsafe.Pointer(rrsa)), uintptr(unsafe.Pointer(rrsalen)), 0) return } func WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) { r1, _, e1 := syscall.Syscall9(procWSARecv.Addr(), 7, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0, 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) { r1, _, e1 := syscall.Syscall9(procWSASend.Addr(), 7, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0, 0) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) { r1, _, e1 := syscall.Syscall9(procWSARecvFrom.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) { r1, _, e1 := syscall.Syscall9(procWSASendTo.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(to)), uintptr(tolen), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) if r1 == socket_error { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetHostByName(name string) (h *Hostent, err error) { var _p0 *byte _p0, err = syscall.BytePtrFromString(name) if err != nil { return } return _GetHostByName(_p0) } func _GetHostByName(name *byte) (h *Hostent, err error) { r0, _, e1 := syscall.Syscall(procgethostbyname.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) h = (*Hostent)(unsafe.Pointer(r0)) if h == nil { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetServByName(name string, proto string) (s *Servent, err error) { var _p0 *byte _p0, err = syscall.BytePtrFromString(name) if err != nil { return } var _p1 *byte _p1, err = syscall.BytePtrFromString(proto) if err != nil { return } return _GetServByName(_p0, _p1) } func _GetServByName(name *byte, proto *byte) (s *Servent, err error) { r0, _, e1 := syscall.Syscall(procgetservbyname.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(proto)), 0) s = (*Servent)(unsafe.Pointer(r0)) if s == nil { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func Ntohs(netshort uint16) (u uint16) { r0, _, _ := syscall.Syscall(procntohs.Addr(), 1, uintptr(netshort), 0, 0) u = uint16(r0) return } func GetProtoByName(name string) (p *Protoent, err error) { var _p0 *byte _p0, err = syscall.BytePtrFromString(name) if err != nil { return } return _GetProtoByName(_p0) } func _GetProtoByName(name *byte) (p *Protoent, err error) { r0, _, e1 := syscall.Syscall(procgetprotobyname.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0) p = (*Protoent)(unsafe.Pointer(r0)) if p == nil { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) { var _p0 *uint16 _p0, status = syscall.UTF16PtrFromString(name) if status != nil { return } return _DnsQuery(_p0, qtype, options, extra, qrs, pr) } func _DnsQuery(name *uint16, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) { r0, _, _ := syscall.Syscall6(procDnsQuery_W.Addr(), 6, uintptr(unsafe.Pointer(name)), uintptr(qtype), uintptr(options), uintptr(unsafe.Pointer(extra)), uintptr(unsafe.Pointer(qrs)), uintptr(unsafe.Pointer(pr))) if r0 != 0 { status = syscall.Errno(r0) } return } func DnsRecordListFree(rl *DNSRecord, freetype uint32) { syscall.Syscall(procDnsRecordListFree.Addr(), 2, uintptr(unsafe.Pointer(rl)), uintptr(freetype), 0) return } func DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) { r0, _, _ := syscall.Syscall(procDnsNameCompare_W.Addr(), 2, uintptr(unsafe.Pointer(name1)), uintptr(unsafe.Pointer(name2)), 0) same = r0 != 0 return } func GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) { r0, _, _ := syscall.Syscall6(procGetAddrInfoW.Addr(), 4, uintptr(unsafe.Pointer(nodename)), uintptr(unsafe.Pointer(servicename)), uintptr(unsafe.Pointer(hints)), uintptr(unsafe.Pointer(result)), 0, 0) if r0 != 0 { sockerr = syscall.Errno(r0) } return } func FreeAddrInfoW(addrinfo *AddrinfoW) { syscall.Syscall(procFreeAddrInfoW.Addr(), 1, uintptr(unsafe.Pointer(addrinfo)), 0, 0) return } func GetIfEntry(pIfRow *MibIfRow) (errcode error) { r0, _, _ := syscall.Syscall(procGetIfEntry.Addr(), 1, uintptr(unsafe.Pointer(pIfRow)), 0, 0) if r0 != 0 { errcode = syscall.Errno(r0) } return } func GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) { r0, _, _ := syscall.Syscall(procGetAdaptersInfo.Addr(), 2, uintptr(unsafe.Pointer(ai)), uintptr(unsafe.Pointer(ol)), 0) if r0 != 0 { errcode = syscall.Errno(r0) } return } func SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) { r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(handle), uintptr(flags), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) { r0, _, e1 := syscall.Syscall(procWSAEnumProtocolsW.Addr(), 3, uintptr(unsafe.Pointer(protocols)), uintptr(unsafe.Pointer(protocolBuffer)), uintptr(unsafe.Pointer(bufferLength))) n = int32(r0) if n == -1 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) { r0, _, _ := syscall.Syscall6(procGetAdaptersAddresses.Addr(), 5, uintptr(family), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(adapterAddresses)), uintptr(unsafe.Pointer(sizePointer)), 0) if r0 != 0 { errcode = syscall.Errno(r0) } return } func GetACP() (acp uint32) { r0, _, _ := syscall.Syscall(procGetACP.Addr(), 0, 0, 0, 0) acp = uint32(r0) return } func MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) { r0, _, e1 := syscall.Syscall6(procMultiByteToWideChar.Addr(), 6, uintptr(codePage), uintptr(dwFlags), uintptr(unsafe.Pointer(str)), uintptr(nstr), uintptr(unsafe.Pointer(wchar)), uintptr(nwchar)) nwrite = int32(r0) if nwrite == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) { r1, _, e1 := syscall.Syscall6(procTranslateNameW.Addr(), 5, uintptr(unsafe.Pointer(accName)), uintptr(accNameFormat), uintptr(desiredNameFormat), uintptr(unsafe.Pointer(translatedName)), uintptr(unsafe.Pointer(nSize)), 0) if r1&0xff == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) { r1, _, e1 := syscall.Syscall(procGetUserNameExW.Addr(), 3, uintptr(nameFormat), uintptr(unsafe.Pointer(nameBuffre)), uintptr(unsafe.Pointer(nSize))) if r1&0xff == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) { r0, _, _ := syscall.Syscall6(procNetUserGetInfo.Addr(), 4, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(unsafe.Pointer(buf)), 0, 0) if r0 != 0 { neterr = syscall.Errno(r0) } return } func NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) { r0, _, _ := syscall.Syscall(procNetGetJoinInformation.Addr(), 3, uintptr(unsafe.Pointer(server)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(bufType))) if r0 != 0 { neterr = syscall.Errno(r0) } return } func NetApiBufferFree(buf *byte) (neterr error) { r0, _, _ := syscall.Syscall(procNetApiBufferFree.Addr(), 1, uintptr(unsafe.Pointer(buf)), 0, 0) if r0 != 0 { neterr = syscall.Errno(r0) } return } func LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) { r1, _, e1 := syscall.Syscall9(procLookupAccountSidW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) { r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use)), 0, 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) { r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(stringSid)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) { r1, _, e1 := syscall.Syscall(procConvertStringSidToSidW.Addr(), 2, uintptr(unsafe.Pointer(stringSid)), uintptr(unsafe.Pointer(sid)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetLengthSid(sid *SID) (len uint32) { r0, _, _ := syscall.Syscall(procGetLengthSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) len = uint32(r0) return } func CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) { r1, _, e1 := syscall.Syscall(procCopySid.Addr(), 3, uintptr(destSidLen), uintptr(unsafe.Pointer(destSid)), uintptr(unsafe.Pointer(srcSid))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) { r1, _, e1 := syscall.Syscall12(procAllocateAndInitializeSid.Addr(), 11, uintptr(unsafe.Pointer(identAuth)), uintptr(subAuth), uintptr(subAuth0), uintptr(subAuth1), uintptr(subAuth2), uintptr(subAuth3), uintptr(subAuth4), uintptr(subAuth5), uintptr(subAuth6), uintptr(subAuth7), uintptr(unsafe.Pointer(sid)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func FreeSid(sid *SID) (err error) { r1, _, e1 := syscall.Syscall(procFreeSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) if r1 != 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) { r0, _, _ := syscall.Syscall(procEqualSid.Addr(), 2, uintptr(unsafe.Pointer(sid1)), uintptr(unsafe.Pointer(sid2)), 0) isEqual = r0 != 0 return } func OpenProcessToken(h Handle, access uint32, token *Token) (err error) { r1, _, e1 := syscall.Syscall(procOpenProcessToken.Addr(), 3, uintptr(h), uintptr(access), uintptr(unsafe.Pointer(token))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetTokenInformation(t Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) { r1, _, e1 := syscall.Syscall6(procGetTokenInformation.Addr(), 5, uintptr(t), uintptr(infoClass), uintptr(unsafe.Pointer(info)), uintptr(infoLen), uintptr(unsafe.Pointer(returnedLen)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) { r1, _, e1 := syscall.Syscall(procGetUserProfileDirectoryW.Addr(), 3, uintptr(t), uintptr(unsafe.Pointer(dir)), uintptr(unsafe.Pointer(dirLen))) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } lxd-2.0.11/dist/src/golang.org/x/sys/windows/types_windows_amd64.go0000644061062106075000000000073613172163421026304 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows type WSAData struct { Version uint16 HighVersion uint16 MaxSockets uint16 MaxUdpDg uint16 VendorInfo *byte Description [WSADESCRIPTION_LEN + 1]byte SystemStatus [WSASYS_STATUS_LEN + 1]byte } type Servent struct { Name *byte Aliases **byte Proto *byte Port uint16 } lxd-2.0.11/dist/src/golang.org/x/sys/windows/types_windows_386.go0000644061062106075000000000073613172163421025711 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows type WSAData struct { Version uint16 HighVersion uint16 Description [WSADESCRIPTION_LEN + 1]byte SystemStatus [WSASYS_STATUS_LEN + 1]byte MaxSockets uint16 MaxUdpDg uint16 VendorInfo *byte } type Servent struct { Name *byte Aliases **byte Port uint16 Proto *byte } lxd-2.0.11/dist/src/golang.org/x/sys/windows/types_windows.go0000644061062106075000000007547513172163421025325 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows import "syscall" const ( // Windows errors. ERROR_FILE_NOT_FOUND syscall.Errno = 2 ERROR_PATH_NOT_FOUND syscall.Errno = 3 ERROR_ACCESS_DENIED syscall.Errno = 5 ERROR_NO_MORE_FILES syscall.Errno = 18 ERROR_HANDLE_EOF syscall.Errno = 38 ERROR_NETNAME_DELETED syscall.Errno = 64 ERROR_FILE_EXISTS syscall.Errno = 80 ERROR_BROKEN_PIPE syscall.Errno = 109 ERROR_BUFFER_OVERFLOW syscall.Errno = 111 ERROR_INSUFFICIENT_BUFFER syscall.Errno = 122 ERROR_MOD_NOT_FOUND syscall.Errno = 126 ERROR_PROC_NOT_FOUND syscall.Errno = 127 ERROR_ALREADY_EXISTS syscall.Errno = 183 ERROR_ENVVAR_NOT_FOUND syscall.Errno = 203 ERROR_MORE_DATA syscall.Errno = 234 ERROR_OPERATION_ABORTED syscall.Errno = 995 ERROR_IO_PENDING syscall.Errno = 997 ERROR_SERVICE_SPECIFIC_ERROR syscall.Errno = 1066 ERROR_NOT_FOUND syscall.Errno = 1168 ERROR_PRIVILEGE_NOT_HELD syscall.Errno = 1314 WSAEACCES syscall.Errno = 10013 WSAECONNRESET syscall.Errno = 10054 ) const ( // Invented values to support what package os expects. O_RDONLY = 0x00000 O_WRONLY = 0x00001 O_RDWR = 0x00002 O_CREAT = 0x00040 O_EXCL = 0x00080 O_NOCTTY = 0x00100 O_TRUNC = 0x00200 O_NONBLOCK = 0x00800 O_APPEND = 0x00400 O_SYNC = 0x01000 O_ASYNC = 0x02000 O_CLOEXEC = 0x80000 ) const ( // More invented values for signals SIGHUP = Signal(0x1) SIGINT = Signal(0x2) SIGQUIT = Signal(0x3) SIGILL = Signal(0x4) SIGTRAP = Signal(0x5) SIGABRT = Signal(0x6) SIGBUS = Signal(0x7) SIGFPE = Signal(0x8) SIGKILL = Signal(0x9) SIGSEGV = Signal(0xb) SIGPIPE = Signal(0xd) SIGALRM = Signal(0xe) SIGTERM = Signal(0xf) ) var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "bus error", 8: "floating point exception", 9: "killed", 10: "user defined signal 1", 11: "segmentation fault", 12: "user defined signal 2", 13: "broken pipe", 14: "alarm clock", 15: "terminated", } const ( GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 GENERIC_EXECUTE = 0x20000000 GENERIC_ALL = 0x10000000 FILE_LIST_DIRECTORY = 0x00000001 FILE_APPEND_DATA = 0x00000004 FILE_WRITE_ATTRIBUTES = 0x00000100 FILE_SHARE_READ = 0x00000001 FILE_SHARE_WRITE = 0x00000002 FILE_SHARE_DELETE = 0x00000004 FILE_ATTRIBUTE_READONLY = 0x00000001 FILE_ATTRIBUTE_HIDDEN = 0x00000002 FILE_ATTRIBUTE_SYSTEM = 0x00000004 FILE_ATTRIBUTE_DIRECTORY = 0x00000010 FILE_ATTRIBUTE_ARCHIVE = 0x00000020 FILE_ATTRIBUTE_NORMAL = 0x00000080 FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 INVALID_FILE_ATTRIBUTES = 0xffffffff CREATE_NEW = 1 CREATE_ALWAYS = 2 OPEN_EXISTING = 3 OPEN_ALWAYS = 4 TRUNCATE_EXISTING = 5 FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 FILE_FLAG_OVERLAPPED = 0x40000000 HANDLE_FLAG_INHERIT = 0x00000001 STARTF_USESTDHANDLES = 0x00000100 STARTF_USESHOWWINDOW = 0x00000001 DUPLICATE_CLOSE_SOURCE = 0x00000001 DUPLICATE_SAME_ACCESS = 0x00000002 STD_INPUT_HANDLE = -10 & (1<<32 - 1) STD_OUTPUT_HANDLE = -11 & (1<<32 - 1) STD_ERROR_HANDLE = -12 & (1<<32 - 1) FILE_BEGIN = 0 FILE_CURRENT = 1 FILE_END = 2 LANG_ENGLISH = 0x09 SUBLANG_ENGLISH_US = 0x01 FORMAT_MESSAGE_ALLOCATE_BUFFER = 256 FORMAT_MESSAGE_IGNORE_INSERTS = 512 FORMAT_MESSAGE_FROM_STRING = 1024 FORMAT_MESSAGE_FROM_HMODULE = 2048 FORMAT_MESSAGE_FROM_SYSTEM = 4096 FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192 FORMAT_MESSAGE_MAX_WIDTH_MASK = 255 MAX_PATH = 260 MAX_LONG_PATH = 32768 MAX_COMPUTERNAME_LENGTH = 15 TIME_ZONE_ID_UNKNOWN = 0 TIME_ZONE_ID_STANDARD = 1 TIME_ZONE_ID_DAYLIGHT = 2 IGNORE = 0 INFINITE = 0xffffffff WAIT_TIMEOUT = 258 WAIT_ABANDONED = 0x00000080 WAIT_OBJECT_0 = 0x00000000 WAIT_FAILED = 0xFFFFFFFF CREATE_NEW_PROCESS_GROUP = 0x00000200 CREATE_UNICODE_ENVIRONMENT = 0x00000400 PROCESS_TERMINATE = 1 PROCESS_QUERY_INFORMATION = 0x00000400 SYNCHRONIZE = 0x00100000 FILE_MAP_COPY = 0x01 FILE_MAP_WRITE = 0x02 FILE_MAP_READ = 0x04 FILE_MAP_EXECUTE = 0x20 CTRL_C_EVENT = 0 CTRL_BREAK_EVENT = 1 // Windows reserves errors >= 1<<29 for application use. APPLICATION_ERROR = 1 << 29 ) const ( // flags for CreateToolhelp32Snapshot TH32CS_SNAPHEAPLIST = 0x01 TH32CS_SNAPPROCESS = 0x02 TH32CS_SNAPTHREAD = 0x04 TH32CS_SNAPMODULE = 0x08 TH32CS_SNAPMODULE32 = 0x10 TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD TH32CS_INHERIT = 0x80000000 ) const ( // filters for ReadDirectoryChangesW FILE_NOTIFY_CHANGE_FILE_NAME = 0x001 FILE_NOTIFY_CHANGE_DIR_NAME = 0x002 FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x004 FILE_NOTIFY_CHANGE_SIZE = 0x008 FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010 FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x020 FILE_NOTIFY_CHANGE_CREATION = 0x040 FILE_NOTIFY_CHANGE_SECURITY = 0x100 ) const ( // do not reorder FILE_ACTION_ADDED = iota + 1 FILE_ACTION_REMOVED FILE_ACTION_MODIFIED FILE_ACTION_RENAMED_OLD_NAME FILE_ACTION_RENAMED_NEW_NAME ) const ( // wincrypt.h PROV_RSA_FULL = 1 PROV_RSA_SIG = 2 PROV_DSS = 3 PROV_FORTEZZA = 4 PROV_MS_EXCHANGE = 5 PROV_SSL = 6 PROV_RSA_SCHANNEL = 12 PROV_DSS_DH = 13 PROV_EC_ECDSA_SIG = 14 PROV_EC_ECNRA_SIG = 15 PROV_EC_ECDSA_FULL = 16 PROV_EC_ECNRA_FULL = 17 PROV_DH_SCHANNEL = 18 PROV_SPYRUS_LYNKS = 20 PROV_RNG = 21 PROV_INTEL_SEC = 22 PROV_REPLACE_OWF = 23 PROV_RSA_AES = 24 CRYPT_VERIFYCONTEXT = 0xF0000000 CRYPT_NEWKEYSET = 0x00000008 CRYPT_DELETEKEYSET = 0x00000010 CRYPT_MACHINE_KEYSET = 0x00000020 CRYPT_SILENT = 0x00000040 CRYPT_DEFAULT_CONTAINER_OPTIONAL = 0x00000080 USAGE_MATCH_TYPE_AND = 0 USAGE_MATCH_TYPE_OR = 1 X509_ASN_ENCODING = 0x00000001 PKCS_7_ASN_ENCODING = 0x00010000 CERT_STORE_PROV_MEMORY = 2 CERT_STORE_ADD_ALWAYS = 4 CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004 CERT_TRUST_NO_ERROR = 0x00000000 CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001 CERT_TRUST_IS_REVOKED = 0x00000004 CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008 CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010 CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020 CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040 CERT_TRUST_IS_CYCLIC = 0x00000080 CERT_TRUST_INVALID_EXTENSION = 0x00000100 CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200 CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400 CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800 CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000 CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000 CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000 CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000 CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000 CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000 CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000 CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000 CERT_CHAIN_POLICY_BASE = 1 CERT_CHAIN_POLICY_AUTHENTICODE = 2 CERT_CHAIN_POLICY_AUTHENTICODE_TS = 3 CERT_CHAIN_POLICY_SSL = 4 CERT_CHAIN_POLICY_BASIC_CONSTRAINTS = 5 CERT_CHAIN_POLICY_NT_AUTH = 6 CERT_CHAIN_POLICY_MICROSOFT_ROOT = 7 CERT_CHAIN_POLICY_EV = 8 CERT_E_EXPIRED = 0x800B0101 CERT_E_ROLE = 0x800B0103 CERT_E_PURPOSE = 0x800B0106 CERT_E_UNTRUSTEDROOT = 0x800B0109 CERT_E_CN_NO_MATCH = 0x800B010F AUTHTYPE_CLIENT = 1 AUTHTYPE_SERVER = 2 ) var ( OID_PKIX_KP_SERVER_AUTH = []byte("1.3.6.1.5.5.7.3.1\x00") OID_SERVER_GATED_CRYPTO = []byte("1.3.6.1.4.1.311.10.3.3\x00") OID_SGC_NETSCAPE = []byte("2.16.840.1.113730.4.1\x00") ) // Invented values to support what package os expects. type Timeval struct { Sec int32 Usec int32 } func (tv *Timeval) Nanoseconds() int64 { return (int64(tv.Sec)*1e6 + int64(tv.Usec)) * 1e3 } func NsecToTimeval(nsec int64) (tv Timeval) { tv.Sec = int32(nsec / 1e9) tv.Usec = int32(nsec % 1e9 / 1e3) return } type SecurityAttributes struct { Length uint32 SecurityDescriptor uintptr InheritHandle uint32 } type Overlapped struct { Internal uintptr InternalHigh uintptr Offset uint32 OffsetHigh uint32 HEvent Handle } type FileNotifyInformation struct { NextEntryOffset uint32 Action uint32 FileNameLength uint32 FileName uint16 } type Filetime struct { LowDateTime uint32 HighDateTime uint32 } // Nanoseconds returns Filetime ft in nanoseconds // since Epoch (00:00:00 UTC, January 1, 1970). func (ft *Filetime) Nanoseconds() int64 { // 100-nanosecond intervals since January 1, 1601 nsec := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime) // change starting time to the Epoch (00:00:00 UTC, January 1, 1970) nsec -= 116444736000000000 // convert into nanoseconds nsec *= 100 return nsec } func NsecToFiletime(nsec int64) (ft Filetime) { // convert into 100-nanosecond nsec /= 100 // change starting time to January 1, 1601 nsec += 116444736000000000 // split into high / low ft.LowDateTime = uint32(nsec & 0xffffffff) ft.HighDateTime = uint32(nsec >> 32 & 0xffffffff) return ft } type Win32finddata struct { FileAttributes uint32 CreationTime Filetime LastAccessTime Filetime LastWriteTime Filetime FileSizeHigh uint32 FileSizeLow uint32 Reserved0 uint32 Reserved1 uint32 FileName [MAX_PATH - 1]uint16 AlternateFileName [13]uint16 } // This is the actual system call structure. // Win32finddata is what we committed to in Go 1. type win32finddata1 struct { FileAttributes uint32 CreationTime Filetime LastAccessTime Filetime LastWriteTime Filetime FileSizeHigh uint32 FileSizeLow uint32 Reserved0 uint32 Reserved1 uint32 FileName [MAX_PATH]uint16 AlternateFileName [14]uint16 } func copyFindData(dst *Win32finddata, src *win32finddata1) { dst.FileAttributes = src.FileAttributes dst.CreationTime = src.CreationTime dst.LastAccessTime = src.LastAccessTime dst.LastWriteTime = src.LastWriteTime dst.FileSizeHigh = src.FileSizeHigh dst.FileSizeLow = src.FileSizeLow dst.Reserved0 = src.Reserved0 dst.Reserved1 = src.Reserved1 // The src is 1 element bigger than dst, but it must be NUL. copy(dst.FileName[:], src.FileName[:]) copy(dst.AlternateFileName[:], src.AlternateFileName[:]) } type ByHandleFileInformation struct { FileAttributes uint32 CreationTime Filetime LastAccessTime Filetime LastWriteTime Filetime VolumeSerialNumber uint32 FileSizeHigh uint32 FileSizeLow uint32 NumberOfLinks uint32 FileIndexHigh uint32 FileIndexLow uint32 } const ( GetFileExInfoStandard = 0 GetFileExMaxInfoLevel = 1 ) type Win32FileAttributeData struct { FileAttributes uint32 CreationTime Filetime LastAccessTime Filetime LastWriteTime Filetime FileSizeHigh uint32 FileSizeLow uint32 } // ShowWindow constants const ( // winuser.h SW_HIDE = 0 SW_NORMAL = 1 SW_SHOWNORMAL = 1 SW_SHOWMINIMIZED = 2 SW_SHOWMAXIMIZED = 3 SW_MAXIMIZE = 3 SW_SHOWNOACTIVATE = 4 SW_SHOW = 5 SW_MINIMIZE = 6 SW_SHOWMINNOACTIVE = 7 SW_SHOWNA = 8 SW_RESTORE = 9 SW_SHOWDEFAULT = 10 SW_FORCEMINIMIZE = 11 ) type StartupInfo struct { Cb uint32 _ *uint16 Desktop *uint16 Title *uint16 X uint32 Y uint32 XSize uint32 YSize uint32 XCountChars uint32 YCountChars uint32 FillAttribute uint32 Flags uint32 ShowWindow uint16 _ uint16 _ *byte StdInput Handle StdOutput Handle StdErr Handle } type ProcessInformation struct { Process Handle Thread Handle ProcessId uint32 ThreadId uint32 } type ProcessEntry32 struct { Size uint32 Usage uint32 ProcessID uint32 DefaultHeapID uintptr ModuleID uint32 Threads uint32 ParentProcessID uint32 PriClassBase int32 Flags uint32 ExeFile [MAX_PATH]uint16 } type Systemtime struct { Year uint16 Month uint16 DayOfWeek uint16 Day uint16 Hour uint16 Minute uint16 Second uint16 Milliseconds uint16 } type Timezoneinformation struct { Bias int32 StandardName [32]uint16 StandardDate Systemtime StandardBias int32 DaylightName [32]uint16 DaylightDate Systemtime DaylightBias int32 } // Socket related. const ( AF_UNSPEC = 0 AF_UNIX = 1 AF_INET = 2 AF_INET6 = 23 AF_NETBIOS = 17 SOCK_STREAM = 1 SOCK_DGRAM = 2 SOCK_RAW = 3 SOCK_SEQPACKET = 5 IPPROTO_IP = 0 IPPROTO_IPV6 = 0x29 IPPROTO_TCP = 6 IPPROTO_UDP = 17 SOL_SOCKET = 0xffff SO_REUSEADDR = 4 SO_KEEPALIVE = 8 SO_DONTROUTE = 16 SO_BROADCAST = 32 SO_LINGER = 128 SO_RCVBUF = 0x1002 SO_SNDBUF = 0x1001 SO_UPDATE_ACCEPT_CONTEXT = 0x700b SO_UPDATE_CONNECT_CONTEXT = 0x7010 IOC_OUT = 0x40000000 IOC_IN = 0x80000000 IOC_VENDOR = 0x18000000 IOC_INOUT = IOC_IN | IOC_OUT IOC_WS2 = 0x08000000 SIO_GET_EXTENSION_FUNCTION_POINTER = IOC_INOUT | IOC_WS2 | 6 SIO_KEEPALIVE_VALS = IOC_IN | IOC_VENDOR | 4 SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12 // cf. http://support.microsoft.com/default.aspx?scid=kb;en-us;257460 IP_TOS = 0x3 IP_TTL = 0x4 IP_MULTICAST_IF = 0x9 IP_MULTICAST_TTL = 0xa IP_MULTICAST_LOOP = 0xb IP_ADD_MEMBERSHIP = 0xc IP_DROP_MEMBERSHIP = 0xd IPV6_V6ONLY = 0x1b IPV6_UNICAST_HOPS = 0x4 IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_LOOP = 0xb IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd SOMAXCONN = 0x7fffffff TCP_NODELAY = 1 SHUT_RD = 0 SHUT_WR = 1 SHUT_RDWR = 2 WSADESCRIPTION_LEN = 256 WSASYS_STATUS_LEN = 128 ) type WSABuf struct { Len uint32 Buf *byte } // Invented values to support what package os expects. const ( S_IFMT = 0x1f000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXUSR = 0x40 ) const ( FILE_TYPE_CHAR = 0x0002 FILE_TYPE_DISK = 0x0001 FILE_TYPE_PIPE = 0x0003 FILE_TYPE_REMOTE = 0x8000 FILE_TYPE_UNKNOWN = 0x0000 ) type Hostent struct { Name *byte Aliases **byte AddrType uint16 Length uint16 AddrList **byte } type Protoent struct { Name *byte Aliases **byte Proto uint16 } const ( DNS_TYPE_A = 0x0001 DNS_TYPE_NS = 0x0002 DNS_TYPE_MD = 0x0003 DNS_TYPE_MF = 0x0004 DNS_TYPE_CNAME = 0x0005 DNS_TYPE_SOA = 0x0006 DNS_TYPE_MB = 0x0007 DNS_TYPE_MG = 0x0008 DNS_TYPE_MR = 0x0009 DNS_TYPE_NULL = 0x000a DNS_TYPE_WKS = 0x000b DNS_TYPE_PTR = 0x000c DNS_TYPE_HINFO = 0x000d DNS_TYPE_MINFO = 0x000e DNS_TYPE_MX = 0x000f DNS_TYPE_TEXT = 0x0010 DNS_TYPE_RP = 0x0011 DNS_TYPE_AFSDB = 0x0012 DNS_TYPE_X25 = 0x0013 DNS_TYPE_ISDN = 0x0014 DNS_TYPE_RT = 0x0015 DNS_TYPE_NSAP = 0x0016 DNS_TYPE_NSAPPTR = 0x0017 DNS_TYPE_SIG = 0x0018 DNS_TYPE_KEY = 0x0019 DNS_TYPE_PX = 0x001a DNS_TYPE_GPOS = 0x001b DNS_TYPE_AAAA = 0x001c DNS_TYPE_LOC = 0x001d DNS_TYPE_NXT = 0x001e DNS_TYPE_EID = 0x001f DNS_TYPE_NIMLOC = 0x0020 DNS_TYPE_SRV = 0x0021 DNS_TYPE_ATMA = 0x0022 DNS_TYPE_NAPTR = 0x0023 DNS_TYPE_KX = 0x0024 DNS_TYPE_CERT = 0x0025 DNS_TYPE_A6 = 0x0026 DNS_TYPE_DNAME = 0x0027 DNS_TYPE_SINK = 0x0028 DNS_TYPE_OPT = 0x0029 DNS_TYPE_DS = 0x002B DNS_TYPE_RRSIG = 0x002E DNS_TYPE_NSEC = 0x002F DNS_TYPE_DNSKEY = 0x0030 DNS_TYPE_DHCID = 0x0031 DNS_TYPE_UINFO = 0x0064 DNS_TYPE_UID = 0x0065 DNS_TYPE_GID = 0x0066 DNS_TYPE_UNSPEC = 0x0067 DNS_TYPE_ADDRS = 0x00f8 DNS_TYPE_TKEY = 0x00f9 DNS_TYPE_TSIG = 0x00fa DNS_TYPE_IXFR = 0x00fb DNS_TYPE_AXFR = 0x00fc DNS_TYPE_MAILB = 0x00fd DNS_TYPE_MAILA = 0x00fe DNS_TYPE_ALL = 0x00ff DNS_TYPE_ANY = 0x00ff DNS_TYPE_WINS = 0xff01 DNS_TYPE_WINSR = 0xff02 DNS_TYPE_NBSTAT = 0xff01 ) const ( DNS_INFO_NO_RECORDS = 0x251D ) const ( // flags inside DNSRecord.Dw DnsSectionQuestion = 0x0000 DnsSectionAnswer = 0x0001 DnsSectionAuthority = 0x0002 DnsSectionAdditional = 0x0003 ) type DNSSRVData struct { Target *uint16 Priority uint16 Weight uint16 Port uint16 Pad uint16 } type DNSPTRData struct { Host *uint16 } type DNSMXData struct { NameExchange *uint16 Preference uint16 Pad uint16 } type DNSTXTData struct { StringCount uint16 StringArray [1]*uint16 } type DNSRecord struct { Next *DNSRecord Name *uint16 Type uint16 Length uint16 Dw uint32 Ttl uint32 Reserved uint32 Data [40]byte } const ( TF_DISCONNECT = 1 TF_REUSE_SOCKET = 2 TF_WRITE_BEHIND = 4 TF_USE_DEFAULT_WORKER = 0 TF_USE_SYSTEM_THREAD = 16 TF_USE_KERNEL_APC = 32 ) type TransmitFileBuffers struct { Head uintptr HeadLength uint32 Tail uintptr TailLength uint32 } const ( IFF_UP = 1 IFF_BROADCAST = 2 IFF_LOOPBACK = 4 IFF_POINTTOPOINT = 8 IFF_MULTICAST = 16 ) const SIO_GET_INTERFACE_LIST = 0x4004747F // TODO(mattn): SockaddrGen is union of sockaddr/sockaddr_in/sockaddr_in6_old. // will be fixed to change variable type as suitable. type SockaddrGen [24]byte type InterfaceInfo struct { Flags uint32 Address SockaddrGen BroadcastAddress SockaddrGen Netmask SockaddrGen } type IpAddressString struct { String [16]byte } type IpMaskString IpAddressString type IpAddrString struct { Next *IpAddrString IpAddress IpAddressString IpMask IpMaskString Context uint32 } const MAX_ADAPTER_NAME_LENGTH = 256 const MAX_ADAPTER_DESCRIPTION_LENGTH = 128 const MAX_ADAPTER_ADDRESS_LENGTH = 8 type IpAdapterInfo struct { Next *IpAdapterInfo ComboIndex uint32 AdapterName [MAX_ADAPTER_NAME_LENGTH + 4]byte Description [MAX_ADAPTER_DESCRIPTION_LENGTH + 4]byte AddressLength uint32 Address [MAX_ADAPTER_ADDRESS_LENGTH]byte Index uint32 Type uint32 DhcpEnabled uint32 CurrentIpAddress *IpAddrString IpAddressList IpAddrString GatewayList IpAddrString DhcpServer IpAddrString HaveWins bool PrimaryWinsServer IpAddrString SecondaryWinsServer IpAddrString LeaseObtained int64 LeaseExpires int64 } const MAXLEN_PHYSADDR = 8 const MAX_INTERFACE_NAME_LEN = 256 const MAXLEN_IFDESCR = 256 type MibIfRow struct { Name [MAX_INTERFACE_NAME_LEN]uint16 Index uint32 Type uint32 Mtu uint32 Speed uint32 PhysAddrLen uint32 PhysAddr [MAXLEN_PHYSADDR]byte AdminStatus uint32 OperStatus uint32 LastChange uint32 InOctets uint32 InUcastPkts uint32 InNUcastPkts uint32 InDiscards uint32 InErrors uint32 InUnknownProtos uint32 OutOctets uint32 OutUcastPkts uint32 OutNUcastPkts uint32 OutDiscards uint32 OutErrors uint32 OutQLen uint32 DescrLen uint32 Descr [MAXLEN_IFDESCR]byte } type CertContext struct { EncodingType uint32 EncodedCert *byte Length uint32 CertInfo uintptr Store Handle } type CertChainContext struct { Size uint32 TrustStatus CertTrustStatus ChainCount uint32 Chains **CertSimpleChain LowerQualityChainCount uint32 LowerQualityChains **CertChainContext HasRevocationFreshnessTime uint32 RevocationFreshnessTime uint32 } type CertSimpleChain struct { Size uint32 TrustStatus CertTrustStatus NumElements uint32 Elements **CertChainElement TrustListInfo uintptr HasRevocationFreshnessTime uint32 RevocationFreshnessTime uint32 } type CertChainElement struct { Size uint32 CertContext *CertContext TrustStatus CertTrustStatus RevocationInfo *CertRevocationInfo IssuanceUsage *CertEnhKeyUsage ApplicationUsage *CertEnhKeyUsage ExtendedErrorInfo *uint16 } type CertRevocationInfo struct { Size uint32 RevocationResult uint32 RevocationOid *byte OidSpecificInfo uintptr HasFreshnessTime uint32 FreshnessTime uint32 CrlInfo uintptr // *CertRevocationCrlInfo } type CertTrustStatus struct { ErrorStatus uint32 InfoStatus uint32 } type CertUsageMatch struct { Type uint32 Usage CertEnhKeyUsage } type CertEnhKeyUsage struct { Length uint32 UsageIdentifiers **byte } type CertChainPara struct { Size uint32 RequestedUsage CertUsageMatch RequstedIssuancePolicy CertUsageMatch URLRetrievalTimeout uint32 CheckRevocationFreshnessTime uint32 RevocationFreshnessTime uint32 CacheResync *Filetime } type CertChainPolicyPara struct { Size uint32 Flags uint32 ExtraPolicyPara uintptr } type SSLExtraCertChainPolicyPara struct { Size uint32 AuthType uint32 Checks uint32 ServerName *uint16 } type CertChainPolicyStatus struct { Size uint32 Error uint32 ChainIndex uint32 ElementIndex uint32 ExtraPolicyStatus uintptr } const ( // do not reorder HKEY_CLASSES_ROOT = 0x80000000 + iota HKEY_CURRENT_USER HKEY_LOCAL_MACHINE HKEY_USERS HKEY_PERFORMANCE_DATA HKEY_CURRENT_CONFIG HKEY_DYN_DATA KEY_QUERY_VALUE = 1 KEY_SET_VALUE = 2 KEY_CREATE_SUB_KEY = 4 KEY_ENUMERATE_SUB_KEYS = 8 KEY_NOTIFY = 16 KEY_CREATE_LINK = 32 KEY_WRITE = 0x20006 KEY_EXECUTE = 0x20019 KEY_READ = 0x20019 KEY_WOW64_64KEY = 0x0100 KEY_WOW64_32KEY = 0x0200 KEY_ALL_ACCESS = 0xf003f ) const ( // do not reorder REG_NONE = iota REG_SZ REG_EXPAND_SZ REG_BINARY REG_DWORD_LITTLE_ENDIAN REG_DWORD_BIG_ENDIAN REG_LINK REG_MULTI_SZ REG_RESOURCE_LIST REG_FULL_RESOURCE_DESCRIPTOR REG_RESOURCE_REQUIREMENTS_LIST REG_QWORD_LITTLE_ENDIAN REG_DWORD = REG_DWORD_LITTLE_ENDIAN REG_QWORD = REG_QWORD_LITTLE_ENDIAN ) type AddrinfoW struct { Flags int32 Family int32 Socktype int32 Protocol int32 Addrlen uintptr Canonname *uint16 Addr uintptr Next *AddrinfoW } const ( AI_PASSIVE = 1 AI_CANONNAME = 2 AI_NUMERICHOST = 4 ) type GUID struct { Data1 uint32 Data2 uint16 Data3 uint16 Data4 [8]byte } var WSAID_CONNECTEX = GUID{ 0x25a207b9, 0xddf3, 0x4660, [8]byte{0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}, } const ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1 FILE_SKIP_SET_EVENT_ON_HANDLE = 2 ) const ( WSAPROTOCOL_LEN = 255 MAX_PROTOCOL_CHAIN = 7 BASE_PROTOCOL = 1 LAYERED_PROTOCOL = 0 XP1_CONNECTIONLESS = 0x00000001 XP1_GUARANTEED_DELIVERY = 0x00000002 XP1_GUARANTEED_ORDER = 0x00000004 XP1_MESSAGE_ORIENTED = 0x00000008 XP1_PSEUDO_STREAM = 0x00000010 XP1_GRACEFUL_CLOSE = 0x00000020 XP1_EXPEDITED_DATA = 0x00000040 XP1_CONNECT_DATA = 0x00000080 XP1_DISCONNECT_DATA = 0x00000100 XP1_SUPPORT_BROADCAST = 0x00000200 XP1_SUPPORT_MULTIPOINT = 0x00000400 XP1_MULTIPOINT_CONTROL_PLANE = 0x00000800 XP1_MULTIPOINT_DATA_PLANE = 0x00001000 XP1_QOS_SUPPORTED = 0x00002000 XP1_UNI_SEND = 0x00008000 XP1_UNI_RECV = 0x00010000 XP1_IFS_HANDLES = 0x00020000 XP1_PARTIAL_MESSAGE = 0x00040000 XP1_SAN_SUPPORT_SDP = 0x00080000 PFL_MULTIPLE_PROTO_ENTRIES = 0x00000001 PFL_RECOMMENDED_PROTO_ENTRY = 0x00000002 PFL_HIDDEN = 0x00000004 PFL_MATCHES_PROTOCOL_ZERO = 0x00000008 PFL_NETWORKDIRECT_PROVIDER = 0x00000010 ) type WSAProtocolInfo struct { ServiceFlags1 uint32 ServiceFlags2 uint32 ServiceFlags3 uint32 ServiceFlags4 uint32 ProviderFlags uint32 ProviderId GUID CatalogEntryId uint32 ProtocolChain WSAProtocolChain Version int32 AddressFamily int32 MaxSockAddr int32 MinSockAddr int32 SocketType int32 Protocol int32 ProtocolMaxOffset int32 NetworkByteOrder int32 SecurityScheme int32 MessageSize uint32 ProviderReserved uint32 ProtocolName [WSAPROTOCOL_LEN + 1]uint16 } type WSAProtocolChain struct { ChainLen int32 ChainEntries [MAX_PROTOCOL_CHAIN]uint32 } type TCPKeepalive struct { OnOff uint32 Time uint32 Interval uint32 } type symbolicLinkReparseBuffer struct { SubstituteNameOffset uint16 SubstituteNameLength uint16 PrintNameOffset uint16 PrintNameLength uint16 Flags uint32 PathBuffer [1]uint16 } type mountPointReparseBuffer struct { SubstituteNameOffset uint16 SubstituteNameLength uint16 PrintNameOffset uint16 PrintNameLength uint16 PathBuffer [1]uint16 } type reparseDataBuffer struct { ReparseTag uint32 ReparseDataLength uint16 Reserved uint16 // GenericReparseBuffer reparseBuffer byte } const ( FSCTL_GET_REPARSE_POINT = 0x900A8 MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024 IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 IO_REPARSE_TAG_SYMLINK = 0xA000000C SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1 ) const ( ComputerNameNetBIOS = 0 ComputerNameDnsHostname = 1 ComputerNameDnsDomain = 2 ComputerNameDnsFullyQualified = 3 ComputerNamePhysicalNetBIOS = 4 ComputerNamePhysicalDnsHostname = 5 ComputerNamePhysicalDnsDomain = 6 ComputerNamePhysicalDnsFullyQualified = 7 ComputerNameMax = 8 ) const ( MOVEFILE_REPLACE_EXISTING = 0x1 MOVEFILE_COPY_ALLOWED = 0x2 MOVEFILE_DELAY_UNTIL_REBOOT = 0x4 MOVEFILE_WRITE_THROUGH = 0x8 MOVEFILE_CREATE_HARDLINK = 0x10 MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20 ) const GAA_FLAG_INCLUDE_PREFIX = 0x00000010 const ( IF_TYPE_OTHER = 1 IF_TYPE_ETHERNET_CSMACD = 6 IF_TYPE_ISO88025_TOKENRING = 9 IF_TYPE_PPP = 23 IF_TYPE_SOFTWARE_LOOPBACK = 24 IF_TYPE_ATM = 37 IF_TYPE_IEEE80211 = 71 IF_TYPE_TUNNEL = 131 IF_TYPE_IEEE1394 = 144 ) type SocketAddress struct { Sockaddr *syscall.RawSockaddrAny SockaddrLength int32 } type IpAdapterUnicastAddress struct { Length uint32 Flags uint32 Next *IpAdapterUnicastAddress Address SocketAddress PrefixOrigin int32 SuffixOrigin int32 DadState int32 ValidLifetime uint32 PreferredLifetime uint32 LeaseLifetime uint32 OnLinkPrefixLength uint8 } type IpAdapterAnycastAddress struct { Length uint32 Flags uint32 Next *IpAdapterAnycastAddress Address SocketAddress } type IpAdapterMulticastAddress struct { Length uint32 Flags uint32 Next *IpAdapterMulticastAddress Address SocketAddress } type IpAdapterDnsServerAdapter struct { Length uint32 Reserved uint32 Next *IpAdapterDnsServerAdapter Address SocketAddress } type IpAdapterPrefix struct { Length uint32 Flags uint32 Next *IpAdapterPrefix Address SocketAddress PrefixLength uint32 } type IpAdapterAddresses struct { Length uint32 IfIndex uint32 Next *IpAdapterAddresses AdapterName *byte FirstUnicastAddress *IpAdapterUnicastAddress FirstAnycastAddress *IpAdapterAnycastAddress FirstMulticastAddress *IpAdapterMulticastAddress FirstDnsServerAddress *IpAdapterDnsServerAdapter DnsSuffix *uint16 Description *uint16 FriendlyName *uint16 PhysicalAddress [syscall.MAX_ADAPTER_ADDRESS_LENGTH]byte PhysicalAddressLength uint32 Flags uint32 Mtu uint32 IfType uint32 OperStatus uint32 Ipv6IfIndex uint32 ZoneIndices [16]uint32 FirstPrefix *IpAdapterPrefix /* more fields might be present here. */ } const ( IfOperStatusUp = 1 IfOperStatusDown = 2 IfOperStatusTesting = 3 IfOperStatusUnknown = 4 IfOperStatusDormant = 5 IfOperStatusNotPresent = 6 IfOperStatusLowerLayerDown = 7 ) // Console related constants used for the mode parameter to SetConsoleMode. See // https://docs.microsoft.com/en-us/windows/console/setconsolemode for details. const ( ENABLE_PROCESSED_INPUT = 0x1 ENABLE_LINE_INPUT = 0x2 ENABLE_ECHO_INPUT = 0x4 ENABLE_WINDOW_INPUT = 0x8 ENABLE_MOUSE_INPUT = 0x10 ENABLE_INSERT_MODE = 0x20 ENABLE_QUICK_EDIT_MODE = 0x40 ENABLE_EXTENDED_FLAGS = 0x80 ENABLE_AUTO_POSITION = 0x100 ENABLE_VIRTUAL_TERMINAL_INPUT = 0x200 ENABLE_PROCESSED_OUTPUT = 0x1 ENABLE_WRAP_AT_EOL_OUTPUT = 0x2 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 DISABLE_NEWLINE_AUTO_RETURN = 0x8 ENABLE_LVB_GRID_WORLDWIDE = 0x10 ) type Coord struct { X int16 Y int16 } type SmallRect struct { Left int16 Top int16 Right int16 Bottom int16 } // Used with GetConsoleScreenBuffer to retreive information about a console // screen buffer. See // https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str // for details. type ConsoleScreenBufferInfo struct { Size Coord CursorPosition Coord Attributes uint16 Window SmallRect MaximumWindowSize Coord } lxd-2.0.11/dist/src/golang.org/x/sys/windows/syscall_windows_test.go0000644061062106075000000000545113172163421026655 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows_test import ( "io/ioutil" "os" "path/filepath" "syscall" "testing" "unsafe" "golang.org/x/sys/windows" ) func TestWin32finddata(t *testing.T) { dir, err := ioutil.TempDir("", "go-build") if err != nil { t.Fatalf("failed to create temp directory: %v", err) } defer os.RemoveAll(dir) path := filepath.Join(dir, "long_name.and_extension") f, err := os.Create(path) if err != nil { t.Fatalf("failed to create %v: %v", path, err) } f.Close() type X struct { fd windows.Win32finddata got byte pad [10]byte // to protect ourselves } var want byte = 2 // it is unlikely to have this character in the filename x := X{got: want} pathp, _ := windows.UTF16PtrFromString(path) h, err := windows.FindFirstFile(pathp, &(x.fd)) if err != nil { t.Fatalf("FindFirstFile failed: %v", err) } err = windows.FindClose(h) if err != nil { t.Fatalf("FindClose failed: %v", err) } if x.got != want { t.Fatalf("memory corruption: want=%d got=%d", want, x.got) } } func TestFormatMessage(t *testing.T) { dll := windows.MustLoadDLL("pdh.dll") pdhOpenQuery := func(datasrc *uint16, userdata uint32, query *windows.Handle) (errno uintptr) { r0, _, _ := syscall.Syscall(dll.MustFindProc("PdhOpenQueryW").Addr(), 3, uintptr(unsafe.Pointer(datasrc)), uintptr(userdata), uintptr(unsafe.Pointer(query))) return r0 } pdhCloseQuery := func(query windows.Handle) (errno uintptr) { r0, _, _ := syscall.Syscall(dll.MustFindProc("PdhCloseQuery").Addr(), 1, uintptr(query), 0, 0) return r0 } var q windows.Handle name, err := windows.UTF16PtrFromString("no_such_source") if err != nil { t.Fatal(err) } errno := pdhOpenQuery(name, 0, &q) if errno == 0 { pdhCloseQuery(q) t.Fatal("PdhOpenQuery succeeded, but expected to fail.") } const flags uint32 = syscall.FORMAT_MESSAGE_FROM_HMODULE | syscall.FORMAT_MESSAGE_ARGUMENT_ARRAY | syscall.FORMAT_MESSAGE_IGNORE_INSERTS buf := make([]uint16, 300) _, err = windows.FormatMessage(flags, uintptr(dll.Handle), uint32(errno), 0, buf, nil) if err != nil { t.Fatal("FormatMessage for handle=%x and errno=%x failed: %v", dll.Handle, errno, err) } } func abort(funcname string, err error) { panic(funcname + " failed: " + err.Error()) } func ExampleLoadLibrary() { h, err := windows.LoadLibrary("kernel32.dll") if err != nil { abort("LoadLibrary", err) } defer windows.FreeLibrary(h) proc, err := windows.GetProcAddress(h, "GetVersion") if err != nil { abort("GetProcAddress", err) } r, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0, 0) major := byte(r) minor := uint8(r >> 8) build := uint16(r >> 16) print("windows version ", major, ".", minor, " (Build ", build, ")\n") } lxd-2.0.11/dist/src/golang.org/x/sys/windows/syscall_windows.go0000644061062106075000000011407313172163421025617 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Windows system calls. package windows import ( errorspkg "errors" "sync" "syscall" "unicode/utf16" "unsafe" ) type Handle uintptr const InvalidHandle = ^Handle(0) // StringToUTF16 is deprecated. Use UTF16FromString instead. // If s contains a NUL byte this function panics instead of // returning an error. func StringToUTF16(s string) []uint16 { a, err := UTF16FromString(s) if err != nil { panic("windows: string with NUL passed to StringToUTF16") } return a } // UTF16FromString returns the UTF-16 encoding of the UTF-8 string // s, with a terminating NUL added. If s contains a NUL byte at any // location, it returns (nil, syscall.EINVAL). func UTF16FromString(s string) ([]uint16, error) { for i := 0; i < len(s); i++ { if s[i] == 0 { return nil, syscall.EINVAL } } return utf16.Encode([]rune(s + "\x00")), nil } // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s, // with a terminating NUL removed. func UTF16ToString(s []uint16) string { for i, v := range s { if v == 0 { s = s[0:i] break } } return string(utf16.Decode(s)) } // StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead. // If s contains a NUL byte this function panics instead of // returning an error. func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] } // UTF16PtrFromString returns pointer to the UTF-16 encoding of // the UTF-8 string s, with a terminating NUL added. If s // contains a NUL byte at any location, it returns (nil, syscall.EINVAL). func UTF16PtrFromString(s string) (*uint16, error) { a, err := UTF16FromString(s) if err != nil { return nil, err } return &a[0], nil } func Getpagesize() int { return 4096 } // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention. // This is useful when interoperating with Windows code requiring callbacks. func NewCallback(fn interface{}) uintptr { return syscall.NewCallback(fn) } // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention. // This is useful when interoperating with Windows code requiring callbacks. func NewCallbackCDecl(fn interface{}) uintptr { return syscall.NewCallbackCDecl(fn) } // windows api calls //sys GetLastError() (lasterr error) //sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW //sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW //sys FreeLibrary(handle Handle) (err error) //sys GetProcAddress(module Handle, procname string) (proc uintptr, err error) //sys GetVersion() (ver uint32, err error) //sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW //sys ExitProcess(exitcode uint32) //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW //sys ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) //sys WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) //sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff] //sys CloseHandle(handle Handle) (err error) //sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle] //sys SetStdHandle(stdhandle uint32, handle Handle) (err error) //sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW //sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW //sys FindClose(handle Handle) (err error) //sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) //sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW //sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW //sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW //sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW //sys DeleteFile(path *uint16) (err error) = DeleteFileW //sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW //sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW //sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW //sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW //sys SetEndOfFile(handle Handle) (err error) //sys GetSystemTimeAsFileTime(time *Filetime) //sys GetSystemTimePreciseAsFileTime(time *Filetime) //sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff] //sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error) //sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error) //sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error) //sys CancelIo(s Handle) (err error) //sys CancelIoEx(s Handle, o *Overlapped) (err error) //sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW //sys OpenProcess(da uint32, inheritHandle bool, pid uint32) (handle Handle, err error) //sys TerminateProcess(handle Handle, exitcode uint32) (err error) //sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) //sys GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW //sys GetCurrentProcess() (pseudoHandle Handle, err error) //sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) //sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) //sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] //sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW //sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) //sys GetFileType(filehandle Handle) (n uint32, err error) //sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW //sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext //sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom //sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW //sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW //sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW //sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW //sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) //sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW //sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW //sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW //sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW //sys CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW //sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0] //sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) //sys FlushFileBuffers(handle Handle) (err error) //sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW //sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW //sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW //sys CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) = kernel32.CreateFileMappingW //sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error) //sys UnmapViewOfFile(addr uintptr) (err error) //sys FlushViewOfFile(addr uintptr, length uintptr) (err error) //sys VirtualLock(addr uintptr, length uintptr) (err error) //sys VirtualUnlock(addr uintptr, length uintptr) (err error) //sys VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc //sys VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree //sys VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect //sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile //sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW //sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW //sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) [failretval==InvalidHandle] = crypt32.CertOpenStore //sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore //sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore //sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore //sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain //sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain //sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext //sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext //sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy //sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW //sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey //sys RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW //sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW //sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW //sys getCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId //sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode //sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode //sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo //sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW //sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW //sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot //sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW //sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW //sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL. //sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW //sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW //sys GetCurrentThreadId() (id uint32) //sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) = kernel32.CreateEventW //sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) = kernel32.CreateEventExW //sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW //sys SetEvent(event Handle) (err error) = kernel32.SetEvent //sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent //sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent // syscall interface implementation for other packages // GetProcAddressByOrdinal retrieves the address of the exported // function from module by ordinal. func GetProcAddressByOrdinal(module Handle, ordinal uintptr) (proc uintptr, err error) { r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), ordinal, 0) proc = uintptr(r0) if proc == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } func Exit(code int) { ExitProcess(uint32(code)) } func makeInheritSa() *SecurityAttributes { var sa SecurityAttributes sa.Length = uint32(unsafe.Sizeof(sa)) sa.InheritHandle = 1 return &sa } func Open(path string, mode int, perm uint32) (fd Handle, err error) { if len(path) == 0 { return InvalidHandle, ERROR_FILE_NOT_FOUND } pathp, err := UTF16PtrFromString(path) if err != nil { return InvalidHandle, err } var access uint32 switch mode & (O_RDONLY | O_WRONLY | O_RDWR) { case O_RDONLY: access = GENERIC_READ case O_WRONLY: access = GENERIC_WRITE case O_RDWR: access = GENERIC_READ | GENERIC_WRITE } if mode&O_CREAT != 0 { access |= GENERIC_WRITE } if mode&O_APPEND != 0 { access &^= GENERIC_WRITE access |= FILE_APPEND_DATA } sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE) var sa *SecurityAttributes if mode&O_CLOEXEC == 0 { sa = makeInheritSa() } var createmode uint32 switch { case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL): createmode = CREATE_NEW case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC): createmode = CREATE_ALWAYS case mode&O_CREAT == O_CREAT: createmode = OPEN_ALWAYS case mode&O_TRUNC == O_TRUNC: createmode = TRUNCATE_EXISTING default: createmode = OPEN_EXISTING } h, e := CreateFile(pathp, access, sharemode, sa, createmode, FILE_ATTRIBUTE_NORMAL, 0) return h, e } func Read(fd Handle, p []byte) (n int, err error) { var done uint32 e := ReadFile(fd, p, &done, nil) if e != nil { if e == ERROR_BROKEN_PIPE { // NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin return 0, nil } return 0, e } if raceenabled { if done > 0 { raceWriteRange(unsafe.Pointer(&p[0]), int(done)) } raceAcquire(unsafe.Pointer(&ioSync)) } return int(done), nil } func Write(fd Handle, p []byte) (n int, err error) { if raceenabled { raceReleaseMerge(unsafe.Pointer(&ioSync)) } var done uint32 e := WriteFile(fd, p, &done, nil) if e != nil { return 0, e } if raceenabled && done > 0 { raceReadRange(unsafe.Pointer(&p[0]), int(done)) } return int(done), nil } var ioSync int64 func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) { var w uint32 switch whence { case 0: w = FILE_BEGIN case 1: w = FILE_CURRENT case 2: w = FILE_END } hi := int32(offset >> 32) lo := int32(offset) // use GetFileType to check pipe, pipe can't do seek ft, _ := GetFileType(fd) if ft == FILE_TYPE_PIPE { return 0, syscall.EPIPE } rlo, e := SetFilePointer(fd, lo, &hi, w) if e != nil { return 0, e } return int64(hi)<<32 + int64(rlo), nil } func Close(fd Handle) (err error) { return CloseHandle(fd) } var ( Stdin = getStdHandle(STD_INPUT_HANDLE) Stdout = getStdHandle(STD_OUTPUT_HANDLE) Stderr = getStdHandle(STD_ERROR_HANDLE) ) func getStdHandle(stdhandle uint32) (fd Handle) { r, _ := GetStdHandle(stdhandle) CloseOnExec(r) return r } const ImplementsGetwd = true func Getwd() (wd string, err error) { b := make([]uint16, 300) n, e := GetCurrentDirectory(uint32(len(b)), &b[0]) if e != nil { return "", e } return string(utf16.Decode(b[0:n])), nil } func Chdir(path string) (err error) { pathp, err := UTF16PtrFromString(path) if err != nil { return err } return SetCurrentDirectory(pathp) } func Mkdir(path string, mode uint32) (err error) { pathp, err := UTF16PtrFromString(path) if err != nil { return err } return CreateDirectory(pathp, nil) } func Rmdir(path string) (err error) { pathp, err := UTF16PtrFromString(path) if err != nil { return err } return RemoveDirectory(pathp) } func Unlink(path string) (err error) { pathp, err := UTF16PtrFromString(path) if err != nil { return err } return DeleteFile(pathp) } func Rename(oldpath, newpath string) (err error) { from, err := UTF16PtrFromString(oldpath) if err != nil { return err } to, err := UTF16PtrFromString(newpath) if err != nil { return err } return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING) } func ComputerName() (name string, err error) { var n uint32 = MAX_COMPUTERNAME_LENGTH + 1 b := make([]uint16, n) e := GetComputerName(&b[0], &n) if e != nil { return "", e } return string(utf16.Decode(b[0:n])), nil } func Ftruncate(fd Handle, length int64) (err error) { curoffset, e := Seek(fd, 0, 1) if e != nil { return e } defer Seek(fd, curoffset, 0) _, e = Seek(fd, length, 0) if e != nil { return e } e = SetEndOfFile(fd) if e != nil { return e } return nil } func Gettimeofday(tv *Timeval) (err error) { var ft Filetime GetSystemTimeAsFileTime(&ft) *tv = NsecToTimeval(ft.Nanoseconds()) return nil } func Pipe(p []Handle) (err error) { if len(p) != 2 { return syscall.EINVAL } var r, w Handle e := CreatePipe(&r, &w, makeInheritSa(), 0) if e != nil { return e } p[0] = r p[1] = w return nil } func Utimes(path string, tv []Timeval) (err error) { if len(tv) != 2 { return syscall.EINVAL } pathp, e := UTF16PtrFromString(path) if e != nil { return e } h, e := CreateFile(pathp, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) if e != nil { return e } defer Close(h) a := NsecToFiletime(tv[0].Nanoseconds()) w := NsecToFiletime(tv[1].Nanoseconds()) return SetFileTime(h, nil, &a, &w) } func UtimesNano(path string, ts []Timespec) (err error) { if len(ts) != 2 { return syscall.EINVAL } pathp, e := UTF16PtrFromString(path) if e != nil { return e } h, e := CreateFile(pathp, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) if e != nil { return e } defer Close(h) a := NsecToFiletime(TimespecToNsec(ts[0])) w := NsecToFiletime(TimespecToNsec(ts[1])) return SetFileTime(h, nil, &a, &w) } func Fsync(fd Handle) (err error) { return FlushFileBuffers(fd) } func Chmod(path string, mode uint32) (err error) { if mode == 0 { return syscall.EINVAL } p, e := UTF16PtrFromString(path) if e != nil { return e } attrs, e := GetFileAttributes(p) if e != nil { return e } if mode&S_IWRITE != 0 { attrs &^= FILE_ATTRIBUTE_READONLY } else { attrs |= FILE_ATTRIBUTE_READONLY } return SetFileAttributes(p, attrs) } func LoadGetSystemTimePreciseAsFileTime() error { return procGetSystemTimePreciseAsFileTime.Find() } func LoadCancelIoEx() error { return procCancelIoEx.Find() } func LoadSetFileCompletionNotificationModes() error { return procSetFileCompletionNotificationModes.Find() } // net api calls const socket_error = uintptr(^uint32(0)) //sys WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup //sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup //sys WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl //sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket //sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt //sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt //sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind //sys connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect //sys getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname //sys getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername //sys listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen //sys shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown //sys Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket //sys AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx //sys GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs //sys WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv //sys WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend //sys WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecvFrom //sys WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASendTo //sys GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname //sys GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname //sys Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs //sys GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname //sys DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W //sys DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree //sys DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W //sys GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW //sys FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW //sys GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry //sys GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo //sys SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes //sys WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW //sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses //sys GetACP() (acp uint32) = kernel32.GetACP //sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar // For testing: clients can set this flag to force // creation of IPv6 sockets to return EAFNOSUPPORT. var SocketDisableIPv6 bool type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type Sockaddr interface { sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs } type SockaddrInet4 struct { Port int Addr [4]byte raw RawSockaddrInet4 } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, syscall.EINVAL } sa.raw.Family = AF_INET p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil } type SockaddrInet6 struct { Port int ZoneId uint32 Addr [16]byte raw RawSockaddrInet6 } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, syscall.EINVAL } sa.raw.Family = AF_INET6 p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) sa.raw.Scope_id = sa.ZoneId for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil } type SockaddrUnix struct { Name string } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) { // TODO(brainman): implement SockaddrUnix.sockaddr() return nil, 0, syscall.EWINDOWS } func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) { switch rsa.Addr.Family { case AF_UNIX: return nil, syscall.EWINDOWS case AF_INET: pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) sa := new(SockaddrInet4) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil case AF_INET6: pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) sa := new(SockaddrInet6) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) sa.ZoneId = pp.Scope_id for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil } return nil, syscall.EAFNOSUPPORT } func Socket(domain, typ, proto int) (fd Handle, err error) { if domain == AF_INET6 && SocketDisableIPv6 { return InvalidHandle, syscall.EAFNOSUPPORT } return socket(int32(domain), int32(typ), int32(proto)) } func SetsockoptInt(fd Handle, level, opt int, value int) (err error) { v := int32(value) return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v))) } func Bind(fd Handle, sa Sockaddr) (err error) { ptr, n, err := sa.sockaddr() if err != nil { return err } return bind(fd, ptr, n) } func Connect(fd Handle, sa Sockaddr) (err error) { ptr, n, err := sa.sockaddr() if err != nil { return err } return connect(fd, ptr, n) } func Getsockname(fd Handle) (sa Sockaddr, err error) { var rsa RawSockaddrAny l := int32(unsafe.Sizeof(rsa)) if err = getsockname(fd, &rsa, &l); err != nil { return } return rsa.Sockaddr() } func Getpeername(fd Handle) (sa Sockaddr, err error) { var rsa RawSockaddrAny l := int32(unsafe.Sizeof(rsa)) if err = getpeername(fd, &rsa, &l); err != nil { return } return rsa.Sockaddr() } func Listen(s Handle, n int) (err error) { return listen(s, int32(n)) } func Shutdown(fd Handle, how int) (err error) { return shutdown(fd, int32(how)) } func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) { rsa, l, err := to.sockaddr() if err != nil { return err } return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine) } func LoadGetAddrInfo() error { return procGetAddrInfoW.Find() } var connectExFunc struct { once sync.Once addr uintptr err error } func LoadConnectEx() error { connectExFunc.once.Do(func() { var s Handle s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) if connectExFunc.err != nil { return } defer CloseHandle(s) var n uint32 connectExFunc.err = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, (*byte)(unsafe.Pointer(&WSAID_CONNECTEX)), uint32(unsafe.Sizeof(WSAID_CONNECTEX)), (*byte)(unsafe.Pointer(&connectExFunc.addr)), uint32(unsafe.Sizeof(connectExFunc.addr)), &n, nil, 0) }) return connectExFunc.err } func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error { err := LoadConnectEx() if err != nil { return errorspkg.New("failed to find ConnectEx: " + err.Error()) } ptr, n, err := sa.sockaddr() if err != nil { return err } return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped) } // Invented structures to support what package os expects. type Rusage struct { CreationTime Filetime ExitTime Filetime KernelTime Filetime UserTime Filetime } type WaitStatus struct { ExitCode uint32 } func (w WaitStatus) Exited() bool { return true } func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) } func (w WaitStatus) Signal() Signal { return -1 } func (w WaitStatus) CoreDump() bool { return false } func (w WaitStatus) Stopped() bool { return false } func (w WaitStatus) Continued() bool { return false } func (w WaitStatus) StopSignal() Signal { return -1 } func (w WaitStatus) Signaled() bool { return false } func (w WaitStatus) TrapCause() int { return -1 } // Timespec is an invented structure on Windows, but here for // consistency with the corresponding package for other operating systems. type Timespec struct { Sec int64 Nsec int64 } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } // TODO(brainman): fix all needed for net func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS } func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) { return 0, nil, syscall.EWINDOWS } func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) { return syscall.EWINDOWS } func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS } // The Linger struct is wrong but we only noticed after Go 1. // sysLinger is the real system call structure. // BUG(brainman): The definition of Linger is not appropriate for direct use // with Setsockopt and Getsockopt. // Use SetsockoptLinger instead. type Linger struct { Onoff int32 Linger int32 } type sysLinger struct { Onoff uint16 Linger uint16 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } func GetsockoptInt(fd Handle, level, opt int) (int, error) { return -1, syscall.EWINDOWS } func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) { sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)} return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys))) } func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4) } func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq))) } func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { return syscall.EWINDOWS } func Getpid() (pid int) { return int(getCurrentProcessId()) } func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) { // NOTE(rsc): The Win32finddata struct is wrong for the system call: // the two paths are each one uint16 short. Use the correct struct, // a win32finddata1, and then copy the results out. // There is no loss of expressivity here, because the final // uint16, if it is used, is supposed to be a NUL, and Go doesn't need that. // For Go 1.1, we might avoid the allocation of win32finddata1 here // by adding a final Bug [2]uint16 field to the struct and then // adjusting the fields in the result directly. var data1 win32finddata1 handle, err = findFirstFile1(name, &data1) if err == nil { copyFindData(data, &data1) } return } func FindNextFile(handle Handle, data *Win32finddata) (err error) { var data1 win32finddata1 err = findNextFile1(handle, &data1) if err == nil { copyFindData(data, &data1) } return } func getProcessEntry(pid int) (*ProcessEntry32, error) { snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) if err != nil { return nil, err } defer CloseHandle(snapshot) var procEntry ProcessEntry32 procEntry.Size = uint32(unsafe.Sizeof(procEntry)) if err = Process32First(snapshot, &procEntry); err != nil { return nil, err } for { if procEntry.ProcessID == uint32(pid) { return &procEntry, nil } err = Process32Next(snapshot, &procEntry) if err != nil { return nil, err } } } func Getppid() (ppid int) { pe, err := getProcessEntry(Getpid()) if err != nil { return -1 } return int(pe.ParentProcessID) } // TODO(brainman): fix all needed for os func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS } func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS } func Symlink(path, link string) (err error) { return syscall.EWINDOWS } func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS } func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS } func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS } func Getuid() (uid int) { return -1 } func Geteuid() (euid int) { return -1 } func Getgid() (gid int) { return -1 } func Getegid() (egid int) { return -1 } func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS } type Signal int func (s Signal) Signal() {} func (s Signal) String() string { if 0 <= s && int(s) < len(signals) { str := signals[s] if str != "" { return str } } return "signal " + itoa(int(s)) } func LoadCreateSymbolicLink() error { return procCreateSymbolicLinkW.Find() } // Readlink returns the destination of the named symbolic link. func Readlink(path string, buf []byte) (n int, err error) { fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0) if err != nil { return -1, err } defer CloseHandle(fd) rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE) var bytesReturned uint32 err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil) if err != nil { return -1, err } rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0])) var s string switch rdb.ReparseTag { case IO_REPARSE_TAG_SYMLINK: data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2]) case IO_REPARSE_TAG_MOUNT_POINT: data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2]) default: // the path is not a symlink or junction but another type of reparse // point return -1, syscall.ENOENT } n = copy(buf, []byte(s)) return n, nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/syscall_test.go0000644061062106075000000000263113172163421025100 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package windows_test import ( "syscall" "testing" "golang.org/x/sys/windows" ) func testSetGetenv(t *testing.T, key, value string) { err := windows.Setenv(key, value) if err != nil { t.Fatalf("Setenv failed to set %q: %v", value, err) } newvalue, found := windows.Getenv(key) if !found { t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) } if newvalue != value { t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) } } func TestEnv(t *testing.T) { testSetGetenv(t, "TESTENV", "AVALUE") // make sure TESTENV gets set to "", not deleted testSetGetenv(t, "TESTENV", "") } func TestGetProcAddressByOrdinal(t *testing.T) { // Attempt calling shlwapi.dll:IsOS, resolving it by ordinal, as // suggested in // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773795.aspx h, err := windows.LoadLibrary("shlwapi.dll") if err != nil { t.Fatalf("Failed to load shlwapi.dll: %s", err) } procIsOS, err := windows.GetProcAddressByOrdinal(h, 437) if err != nil { t.Fatalf("Could not find shlwapi.dll:IsOS by ordinal: %s", err) } const OS_NT = 1 r, _, _ := syscall.Syscall(procIsOS, 1, OS_NT, 0, 0) if r == 0 { t.Error("shlwapi.dll:IsOS(OS_NT) returned 0, expected non-zero value") } } lxd-2.0.11/dist/src/golang.org/x/sys/windows/syscall.go0000644061062106075000000000454713172163421024051 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // Package windows contains an interface to the low-level operating system // primitives. OS details vary depending on the underlying system, and // by default, godoc will display the OS-specific documentation for the current // system. If you want godoc to display syscall documentation for another // system, set $GOOS and $GOARCH to the desired system. For example, if // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS // to freebsd and $GOARCH to arm. // The primary use of this package is inside other packages that provide a more // portable interface to the system, such as "os", "time" and "net". Use // those packages rather than this one if you can. // For details of the functions and data types in this package consult // the manuals for the appropriate operating system. // These calls return err == nil to indicate success; otherwise // err represents an operating system error describing the failure and // holds a value of type syscall.Errno. package windows // import "golang.org/x/sys/windows" import ( "syscall" ) // ByteSliceFromString returns a NUL-terminated slice of bytes // containing the text of s. If s contains a NUL byte at any // location, it returns (nil, syscall.EINVAL). func ByteSliceFromString(s string) ([]byte, error) { for i := 0; i < len(s); i++ { if s[i] == 0 { return nil, syscall.EINVAL } } a := make([]byte, len(s)+1) copy(a, s) return a, nil } // BytePtrFromString returns a pointer to a NUL-terminated array of // bytes containing the text of s. If s contains a NUL byte at any // location, it returns (nil, syscall.EINVAL). func BytePtrFromString(s string) (*byte, error) { a, err := ByteSliceFromString(s) if err != nil { return nil, err } return &a[0], nil } // Single-word zero for use when we need a valid pointer to 0 bytes. // See mksyscall.pl. var _zero uintptr func (ts *Timespec) Unix() (sec int64, nsec int64) { return int64(ts.Sec), int64(ts.Nsec) } func (tv *Timeval) Unix() (sec int64, nsec int64) { return int64(tv.Sec), int64(tv.Usec) * 1000 } func (ts *Timespec) Nano() int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func (tv *Timeval) Nano() int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/0000755061062106075000000000000013172163421022631 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/sys_amd64.s0000644061062106075000000000200713172163421024625 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // func servicemain(argc uint32, argv **uint16) TEXT ·servicemain(SB),7,$0 MOVL CX, ·sArgc(SB) MOVL DX, ·sArgv(SB) SUBQ $32, SP // stack for the first 4 syscall params MOVQ ·sName(SB), CX MOVQ $·servicectlhandler(SB), DX // BUG(pastarmovj): Figure out a way to pass in context in R8. MOVQ ·cRegisterServiceCtrlHandlerExW(SB), AX CALL AX CMPQ AX, $0 JE exit MOVQ AX, ·ssHandle(SB) MOVQ ·goWaitsH(SB), CX MOVQ ·cSetEvent(SB), AX CALL AX MOVQ ·cWaitsH(SB), CX MOVQ $4294967295, DX MOVQ ·cWaitForSingleObject(SB), AX CALL AX exit: ADDQ $32, SP RET // I do not know why, but this seems to be the only way to call // ctlHandlerProc on Windows 7. // func ·servicectlhandler(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr { TEXT ·servicectlhandler(SB),7,$0 MOVQ ·ctlHandlerExProc(SB), AX JMP AX lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/sys_386.s0000644061062106075000000000233113172163421024232 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // func servicemain(argc uint32, argv **uint16) TEXT ·servicemain(SB),7,$0 MOVL argc+0(FP), AX MOVL AX, ·sArgc(SB) MOVL argv+4(FP), AX MOVL AX, ·sArgv(SB) PUSHL BP PUSHL BX PUSHL SI PUSHL DI SUBL $12, SP MOVL ·sName(SB), AX MOVL AX, (SP) MOVL $·servicectlhandler(SB), AX MOVL AX, 4(SP) MOVL $0, 8(SP) MOVL ·cRegisterServiceCtrlHandlerExW(SB), AX MOVL SP, BP CALL AX MOVL BP, SP CMPL AX, $0 JE exit MOVL AX, ·ssHandle(SB) MOVL ·goWaitsH(SB), AX MOVL AX, (SP) MOVL ·cSetEvent(SB), AX MOVL SP, BP CALL AX MOVL BP, SP MOVL ·cWaitsH(SB), AX MOVL AX, (SP) MOVL $-1, AX MOVL AX, 4(SP) MOVL ·cWaitForSingleObject(SB), AX MOVL SP, BP CALL AX MOVL BP, SP exit: ADDL $12, SP POPL DI POPL SI POPL BX POPL BP MOVL 0(SP), CX ADDL $12, SP JMP CX // I do not know why, but this seems to be the only way to call // ctlHandlerProc on Windows 7. // func servicectlhandler(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr { TEXT ·servicectlhandler(SB),7,$0 MOVL ·ctlHandlerExProc(SB), CX JMP CX lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/svc_test.go0000644061062106075000000000511613172163421025015 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package svc_test import ( "io/ioutil" "os" "os/exec" "path/filepath" "testing" "time" "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/mgr" ) func getState(t *testing.T, s *mgr.Service) svc.State { status, err := s.Query() if err != nil { t.Fatalf("Query(%s) failed: %s", s.Name, err) } return status.State } func testState(t *testing.T, s *mgr.Service, want svc.State) { have := getState(t, s) if have != want { t.Fatalf("%s state is=%d want=%d", s.Name, have, want) } } func waitState(t *testing.T, s *mgr.Service, want svc.State) { for i := 0; ; i++ { have := getState(t, s) if have == want { return } if i > 10 { t.Fatalf("%s state is=%d, waiting timeout", s.Name, have) } time.Sleep(300 * time.Millisecond) } } func TestExample(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode - it modifies system services") } const name = "myservice" m, err := mgr.Connect() if err != nil { t.Fatalf("SCM connection failed: %s", err) } defer m.Disconnect() dir, err := ioutil.TempDir("", "svc") if err != nil { t.Fatalf("failed to create temp directory: %v", err) } defer os.RemoveAll(dir) exepath := filepath.Join(dir, "a.exe") o, err := exec.Command("go", "build", "-o", exepath, "golang.org/x/sys/windows/svc/example").CombinedOutput() if err != nil { t.Fatalf("failed to build service program: %v\n%v", err, string(o)) } s, err := m.OpenService(name) if err == nil { err = s.Delete() if err != nil { s.Close() t.Fatalf("Delete failed: %s", err) } s.Close() } s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: "my service"}, "is", "auto-started") if err != nil { t.Fatalf("CreateService(%s) failed: %v", name, err) } defer s.Close() testState(t, s, svc.Stopped) err = s.Start("is", "manual-started") if err != nil { t.Fatalf("Start(%s) failed: %s", s.Name, err) } waitState(t, s, svc.Running) time.Sleep(1 * time.Second) // testing deadlock from issues 4. _, err = s.Control(svc.Interrogate) if err != nil { t.Fatalf("Control(%s) failed: %s", s.Name, err) } _, err = s.Control(svc.Interrogate) if err != nil { t.Fatalf("Control(%s) failed: %s", s.Name, err) } time.Sleep(1 * time.Second) _, err = s.Control(svc.Stop) if err != nil { t.Fatalf("Control(%s) failed: %s", s.Name, err) } waitState(t, s, svc.Stopped) err = s.Delete() if err != nil { t.Fatalf("Delete failed: %s", err) } } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/service.go0000644061062106075000000002514013172163421024622 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // Package svc provides everything required to build Windows service. // package svc import ( "errors" "runtime" "syscall" "unsafe" "golang.org/x/sys/windows" ) // State describes service execution state (Stopped, Running and so on). type State uint32 const ( Stopped = State(windows.SERVICE_STOPPED) StartPending = State(windows.SERVICE_START_PENDING) StopPending = State(windows.SERVICE_STOP_PENDING) Running = State(windows.SERVICE_RUNNING) ContinuePending = State(windows.SERVICE_CONTINUE_PENDING) PausePending = State(windows.SERVICE_PAUSE_PENDING) Paused = State(windows.SERVICE_PAUSED) ) // Cmd represents service state change request. It is sent to a service // by the service manager, and should be actioned upon by the service. type Cmd uint32 const ( Stop = Cmd(windows.SERVICE_CONTROL_STOP) Pause = Cmd(windows.SERVICE_CONTROL_PAUSE) Continue = Cmd(windows.SERVICE_CONTROL_CONTINUE) Interrogate = Cmd(windows.SERVICE_CONTROL_INTERROGATE) Shutdown = Cmd(windows.SERVICE_CONTROL_SHUTDOWN) ParamChange = Cmd(windows.SERVICE_CONTROL_PARAMCHANGE) NetBindAdd = Cmd(windows.SERVICE_CONTROL_NETBINDADD) NetBindRemove = Cmd(windows.SERVICE_CONTROL_NETBINDREMOVE) NetBindEnable = Cmd(windows.SERVICE_CONTROL_NETBINDENABLE) NetBindDisable = Cmd(windows.SERVICE_CONTROL_NETBINDDISABLE) DeviceEvent = Cmd(windows.SERVICE_CONTROL_DEVICEEVENT) HardwareProfileChange = Cmd(windows.SERVICE_CONTROL_HARDWAREPROFILECHANGE) PowerEvent = Cmd(windows.SERVICE_CONTROL_POWEREVENT) SessionChange = Cmd(windows.SERVICE_CONTROL_SESSIONCHANGE) ) // Accepted is used to describe commands accepted by the service. // Note that Interrogate is always accepted. type Accepted uint32 const ( AcceptStop = Accepted(windows.SERVICE_ACCEPT_STOP) AcceptShutdown = Accepted(windows.SERVICE_ACCEPT_SHUTDOWN) AcceptPauseAndContinue = Accepted(windows.SERVICE_ACCEPT_PAUSE_CONTINUE) AcceptParamChange = Accepted(windows.SERVICE_ACCEPT_PARAMCHANGE) AcceptNetBindChange = Accepted(windows.SERVICE_ACCEPT_NETBINDCHANGE) AcceptHardwareProfileChange = Accepted(windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE) AcceptPowerEvent = Accepted(windows.SERVICE_ACCEPT_POWEREVENT) AcceptSessionChange = Accepted(windows.SERVICE_ACCEPT_SESSIONCHANGE) ) // Status combines State and Accepted commands to fully describe running service. type Status struct { State State Accepts Accepted CheckPoint uint32 // used to report progress during a lengthy operation WaitHint uint32 // estimated time required for a pending operation, in milliseconds } // ChangeRequest is sent to the service Handler to request service status change. type ChangeRequest struct { Cmd Cmd EventType uint32 EventData uintptr CurrentStatus Status } // Handler is the interface that must be implemented to build Windows service. type Handler interface { // Execute will be called by the package code at the start of // the service, and the service will exit once Execute completes. // Inside Execute you must read service change requests from r and // act accordingly. You must keep service control manager up to date // about state of your service by writing into s as required. // args contains service name followed by argument strings passed // to the service. // You can provide service exit code in exitCode return parameter, // with 0 being "no error". You can also indicate if exit code, // if any, is service specific or not by using svcSpecificEC // parameter. Execute(args []string, r <-chan ChangeRequest, s chan<- Status) (svcSpecificEC bool, exitCode uint32) } var ( // These are used by asm code. goWaitsH uintptr cWaitsH uintptr ssHandle uintptr sName *uint16 sArgc uintptr sArgv **uint16 ctlHandlerExProc uintptr cSetEvent uintptr cWaitForSingleObject uintptr cRegisterServiceCtrlHandlerExW uintptr ) func init() { k := syscall.MustLoadDLL("kernel32.dll") cSetEvent = k.MustFindProc("SetEvent").Addr() cWaitForSingleObject = k.MustFindProc("WaitForSingleObject").Addr() a := syscall.MustLoadDLL("advapi32.dll") cRegisterServiceCtrlHandlerExW = a.MustFindProc("RegisterServiceCtrlHandlerExW").Addr() } // The HandlerEx prototype also has a context pointer but since we don't use // it at start-up time we don't have to pass it over either. type ctlEvent struct { cmd Cmd eventType uint32 eventData uintptr errno uint32 } // service provides access to windows service api. type service struct { name string h windows.Handle cWaits *event goWaits *event c chan ctlEvent handler Handler } func newService(name string, handler Handler) (*service, error) { var s service var err error s.name = name s.c = make(chan ctlEvent) s.handler = handler s.cWaits, err = newEvent() if err != nil { return nil, err } s.goWaits, err = newEvent() if err != nil { s.cWaits.Close() return nil, err } return &s, nil } func (s *service) close() error { s.cWaits.Close() s.goWaits.Close() return nil } type exitCode struct { isSvcSpecific bool errno uint32 } func (s *service) updateStatus(status *Status, ec *exitCode) error { if s.h == 0 { return errors.New("updateStatus with no service status handle") } var t windows.SERVICE_STATUS t.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS t.CurrentState = uint32(status.State) if status.Accepts&AcceptStop != 0 { t.ControlsAccepted |= windows.SERVICE_ACCEPT_STOP } if status.Accepts&AcceptShutdown != 0 { t.ControlsAccepted |= windows.SERVICE_ACCEPT_SHUTDOWN } if status.Accepts&AcceptPauseAndContinue != 0 { t.ControlsAccepted |= windows.SERVICE_ACCEPT_PAUSE_CONTINUE } if status.Accepts&AcceptParamChange != 0 { t.ControlsAccepted |= windows.SERVICE_ACCEPT_PARAMCHANGE } if status.Accepts&AcceptNetBindChange != 0 { t.ControlsAccepted |= windows.SERVICE_ACCEPT_NETBINDCHANGE } if status.Accepts&AcceptHardwareProfileChange != 0 { t.ControlsAccepted |= windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE } if status.Accepts&AcceptPowerEvent != 0 { t.ControlsAccepted |= windows.SERVICE_ACCEPT_POWEREVENT } if status.Accepts&AcceptSessionChange != 0 { t.ControlsAccepted |= windows.SERVICE_ACCEPT_SESSIONCHANGE } if ec.errno == 0 { t.Win32ExitCode = windows.NO_ERROR t.ServiceSpecificExitCode = windows.NO_ERROR } else if ec.isSvcSpecific { t.Win32ExitCode = uint32(windows.ERROR_SERVICE_SPECIFIC_ERROR) t.ServiceSpecificExitCode = ec.errno } else { t.Win32ExitCode = ec.errno t.ServiceSpecificExitCode = windows.NO_ERROR } t.CheckPoint = status.CheckPoint t.WaitHint = status.WaitHint return windows.SetServiceStatus(s.h, &t) } const ( sysErrSetServiceStatusFailed = uint32(syscall.APPLICATION_ERROR) + iota sysErrNewThreadInCallback ) func (s *service) run() { s.goWaits.Wait() s.h = windows.Handle(ssHandle) argv := (*[100]*int16)(unsafe.Pointer(sArgv))[:sArgc] args := make([]string, len(argv)) for i, a := range argv { args[i] = syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(a))[:]) } cmdsToHandler := make(chan ChangeRequest) changesFromHandler := make(chan Status) exitFromHandler := make(chan exitCode) go func() { ss, errno := s.handler.Execute(args, cmdsToHandler, changesFromHandler) exitFromHandler <- exitCode{ss, errno} }() status := Status{State: Stopped} ec := exitCode{isSvcSpecific: true, errno: 0} var outch chan ChangeRequest inch := s.c var cmd Cmd var evtype uint32 var evdata uintptr loop: for { select { case r := <-inch: if r.errno != 0 { ec.errno = r.errno break loop } inch = nil outch = cmdsToHandler cmd = r.cmd evtype = r.eventType evdata = r.eventData case outch <- ChangeRequest{cmd, evtype, evdata, status}: inch = s.c outch = nil case c := <-changesFromHandler: err := s.updateStatus(&c, &ec) if err != nil { // best suitable error number ec.errno = sysErrSetServiceStatusFailed if err2, ok := err.(syscall.Errno); ok { ec.errno = uint32(err2) } break loop } status = c case ec = <-exitFromHandler: break loop } } s.updateStatus(&Status{State: Stopped}, &ec) s.cWaits.Set() } func newCallback(fn interface{}) (cb uintptr, err error) { defer func() { r := recover() if r == nil { return } cb = 0 switch v := r.(type) { case string: err = errors.New(v) case error: err = v default: err = errors.New("unexpected panic in syscall.NewCallback") } }() return syscall.NewCallback(fn), nil } // BUG(brainman): There is no mechanism to run multiple services // inside one single executable. Perhaps, it can be overcome by // using RegisterServiceCtrlHandlerEx Windows api. // Run executes service name by calling appropriate handler function. func Run(name string, handler Handler) error { runtime.LockOSThread() tid := windows.GetCurrentThreadId() s, err := newService(name, handler) if err != nil { return err } ctlHandler := func(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr { e := ctlEvent{cmd: Cmd(ctl), eventType: evtype, eventData: evdata} // We assume that this callback function is running on // the same thread as Run. Nowhere in MS documentation // I could find statement to guarantee that. So putting // check here to verify, otherwise things will go bad // quickly, if ignored. i := windows.GetCurrentThreadId() if i != tid { e.errno = sysErrNewThreadInCallback } s.c <- e // Always return NO_ERROR (0) for now. return 0 } var svcmain uintptr getServiceMain(&svcmain) t := []windows.SERVICE_TABLE_ENTRY{ {syscall.StringToUTF16Ptr(s.name), svcmain}, {nil, 0}, } goWaitsH = uintptr(s.goWaits.h) cWaitsH = uintptr(s.cWaits.h) sName = t[0].ServiceName ctlHandlerExProc, err = newCallback(ctlHandler) if err != nil { return err } go s.run() err = windows.StartServiceCtrlDispatcher(&t[0]) if err != nil { return err } return nil } // StatusHandle returns service status handle. It is safe to call this function // from inside the Handler.Execute because then it is guaranteed to be set. // This code will have to change once multiple services are possible per process. func StatusHandle() windows.Handle { return windows.Handle(ssHandle) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/security.go0000644061062106075000000000302113172163421025023 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package svc import ( "unsafe" "golang.org/x/sys/windows" ) func allocSid(subAuth0 uint32) (*windows.SID, error) { var sid *windows.SID err := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY, 1, subAuth0, 0, 0, 0, 0, 0, 0, 0, &sid) if err != nil { return nil, err } return sid, nil } // IsAnInteractiveSession determines if calling process is running interactively. // It queries the process token for membership in the Interactive group. // http://stackoverflow.com/questions/2668851/how-do-i-detect-that-my-application-is-running-as-service-or-in-an-interactive-s func IsAnInteractiveSession() (bool, error) { interSid, err := allocSid(windows.SECURITY_INTERACTIVE_RID) if err != nil { return false, err } defer windows.FreeSid(interSid) serviceSid, err := allocSid(windows.SECURITY_SERVICE_RID) if err != nil { return false, err } defer windows.FreeSid(serviceSid) t, err := windows.OpenCurrentProcessToken() if err != nil { return false, err } defer t.Close() gs, err := t.GetTokenGroups() if err != nil { return false, err } p := unsafe.Pointer(&gs.Groups[0]) groups := (*[2 << 20]windows.SIDAndAttributes)(p)[:gs.GroupCount] for _, g := range groups { if windows.EqualSid(g.Sid, interSid) { return true, nil } if windows.EqualSid(g.Sid, serviceSid) { return false, nil } } return false, nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/mgr/0000755061062106075000000000000013172163421023416 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/mgr/service.go0000644061062106075000000000337713172163421025417 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package mgr import ( "syscall" "golang.org/x/sys/windows" "golang.org/x/sys/windows/svc" ) // TODO(brainman): Use EnumDependentServices to enumerate dependent services. // Service is used to access Windows service. type Service struct { Name string Handle windows.Handle } // Delete marks service s for deletion from the service control manager database. func (s *Service) Delete() error { return windows.DeleteService(s.Handle) } // Close relinquish access to the service s. func (s *Service) Close() error { return windows.CloseServiceHandle(s.Handle) } // Start starts service s. // args will be passed to svc.Handler.Execute. func (s *Service) Start(args ...string) error { var p **uint16 if len(args) > 0 { vs := make([]*uint16, len(args)) for i := range vs { vs[i] = syscall.StringToUTF16Ptr(args[i]) } p = &vs[0] } return windows.StartService(s.Handle, uint32(len(args)), p) } // Control sends state change request c to the servce s. func (s *Service) Control(c svc.Cmd) (svc.Status, error) { var t windows.SERVICE_STATUS err := windows.ControlService(s.Handle, uint32(c), &t) if err != nil { return svc.Status{}, err } return svc.Status{ State: svc.State(t.CurrentState), Accepts: svc.Accepted(t.ControlsAccepted), }, nil } // Query returns current status of service s. func (s *Service) Query() (svc.Status, error) { var t windows.SERVICE_STATUS err := windows.QueryServiceStatus(s.Handle, &t) if err != nil { return svc.Status{}, err } return svc.Status{ State: svc.State(t.CurrentState), Accepts: svc.Accepted(t.ControlsAccepted), }, nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/mgr/mgr_test.go0000644061062106075000000000750413172163421025577 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package mgr_test import ( "os" "path/filepath" "sort" "strings" "syscall" "testing" "time" "golang.org/x/sys/windows/svc/mgr" ) func TestOpenLanManServer(t *testing.T) { m, err := mgr.Connect() if err != nil { if errno, ok := err.(syscall.Errno); ok && errno == syscall.ERROR_ACCESS_DENIED { t.Skip("Skipping test: we don't have rights to manage services.") } t.Fatalf("SCM connection failed: %s", err) } defer m.Disconnect() s, err := m.OpenService("LanmanServer") if err != nil { t.Fatalf("OpenService(lanmanserver) failed: %s", err) } defer s.Close() _, err = s.Config() if err != nil { t.Fatalf("Config failed: %s", err) } } func install(t *testing.T, m *mgr.Mgr, name, exepath string, c mgr.Config) { // Sometimes it takes a while for the service to get // removed after previous test run. for i := 0; ; i++ { s, err := m.OpenService(name) if err != nil { break } s.Close() if i > 10 { t.Fatalf("service %s already exists", name) } time.Sleep(300 * time.Millisecond) } s, err := m.CreateService(name, exepath, c) if err != nil { t.Fatalf("CreateService(%s) failed: %v", name, err) } defer s.Close() } func depString(d []string) string { if len(d) == 0 { return "" } for i := range d { d[i] = strings.ToLower(d[i]) } ss := sort.StringSlice(d) ss.Sort() return strings.Join([]string(ss), " ") } func testConfig(t *testing.T, s *mgr.Service, should mgr.Config) mgr.Config { is, err := s.Config() if err != nil { t.Fatalf("Config failed: %s", err) } if should.DisplayName != is.DisplayName { t.Fatalf("config mismatch: DisplayName is %q, but should have %q", is.DisplayName, should.DisplayName) } if should.StartType != is.StartType { t.Fatalf("config mismatch: StartType is %v, but should have %v", is.StartType, should.StartType) } if should.Description != is.Description { t.Fatalf("config mismatch: Description is %q, but should have %q", is.Description, should.Description) } if depString(should.Dependencies) != depString(is.Dependencies) { t.Fatalf("config mismatch: Dependencies is %v, but should have %v", is.Dependencies, should.Dependencies) } return is } func remove(t *testing.T, s *mgr.Service) { err := s.Delete() if err != nil { t.Fatalf("Delete failed: %s", err) } } func TestMyService(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode - it modifies system services") } const name = "myservice" m, err := mgr.Connect() if err != nil { if errno, ok := err.(syscall.Errno); ok && errno == syscall.ERROR_ACCESS_DENIED { t.Skip("Skipping test: we don't have rights to manage services.") } t.Fatalf("SCM connection failed: %s", err) } defer m.Disconnect() c := mgr.Config{ StartType: mgr.StartDisabled, DisplayName: "my service", Description: "my service is just a test", Dependencies: []string{"LanmanServer", "W32Time"}, } exename := os.Args[0] exepath, err := filepath.Abs(exename) if err != nil { t.Fatalf("filepath.Abs(%s) failed: %s", exename, err) } install(t, m, name, exepath, c) s, err := m.OpenService(name) if err != nil { t.Fatalf("service %s is not installed", name) } defer s.Close() c.BinaryPathName = exepath c = testConfig(t, s, c) c.StartType = mgr.StartManual err = s.UpdateConfig(c) if err != nil { t.Fatalf("UpdateConfig failed: %v", err) } testConfig(t, s, c) svcnames, err := m.ListServices() if err != nil { t.Fatalf("ListServices failed: %v", err) } var myserviceIsInstalled bool for _, sn := range svcnames { if sn == name { myserviceIsInstalled = true break } } if !myserviceIsInstalled { t.Errorf("ListServices failed to find %q service", name) } remove(t, s) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/mgr/mgr.go0000644061062106075000000001054713172163421024541 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // Package mgr can be used to manage Windows service programs. // It can be used to install and remove them. It can also start, // stop and pause them. The package can query / change current // service state and config parameters. // package mgr import ( "syscall" "unicode/utf16" "unsafe" "golang.org/x/sys/windows" ) // Mgr is used to manage Windows service. type Mgr struct { Handle windows.Handle } // Connect establishes a connection to the service control manager. func Connect() (*Mgr, error) { return ConnectRemote("") } // ConnectRemote establishes a connection to the // service control manager on computer named host. func ConnectRemote(host string) (*Mgr, error) { var s *uint16 if host != "" { s = syscall.StringToUTF16Ptr(host) } h, err := windows.OpenSCManager(s, nil, windows.SC_MANAGER_ALL_ACCESS) if err != nil { return nil, err } return &Mgr{Handle: h}, nil } // Disconnect closes connection to the service control manager m. func (m *Mgr) Disconnect() error { return windows.CloseServiceHandle(m.Handle) } func toPtr(s string) *uint16 { if len(s) == 0 { return nil } return syscall.StringToUTF16Ptr(s) } // toStringBlock terminates strings in ss with 0, and then // concatenates them together. It also adds extra 0 at the end. func toStringBlock(ss []string) *uint16 { if len(ss) == 0 { return nil } t := "" for _, s := range ss { if s != "" { t += s + "\x00" } } if t == "" { return nil } t += "\x00" return &utf16.Encode([]rune(t))[0] } // CreateService installs new service name on the system. // The service will be executed by running exepath binary. // Use config c to specify service parameters. // Any args will be passed as command-line arguments when // the service is started; these arguments are distinct from // the arguments passed to Service.Start or via the "Start // parameters" field in the service's Properties dialog box. func (m *Mgr) CreateService(name, exepath string, c Config, args ...string) (*Service, error) { if c.StartType == 0 { c.StartType = StartManual } if c.ErrorControl == 0 { c.ErrorControl = ErrorNormal } if c.ServiceType == 0 { c.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS } s := syscall.EscapeArg(exepath) for _, v := range args { s += " " + syscall.EscapeArg(v) } h, err := windows.CreateService(m.Handle, toPtr(name), toPtr(c.DisplayName), windows.SERVICE_ALL_ACCESS, c.ServiceType, c.StartType, c.ErrorControl, toPtr(s), toPtr(c.LoadOrderGroup), nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), toPtr(c.Password)) if err != nil { return nil, err } if c.Description != "" { err = updateDescription(h, c.Description) if err != nil { return nil, err } } return &Service{Name: name, Handle: h}, nil } // OpenService retrieves access to service name, so it can // be interrogated and controlled. func (m *Mgr) OpenService(name string) (*Service, error) { h, err := windows.OpenService(m.Handle, syscall.StringToUTF16Ptr(name), windows.SERVICE_ALL_ACCESS) if err != nil { return nil, err } return &Service{Name: name, Handle: h}, nil } // ListServices enumerates services in the specified // service control manager database m. // If the caller does not have the SERVICE_QUERY_STATUS // access right to a service, the service is silently // omitted from the list of services returned. func (m *Mgr) ListServices() ([]string, error) { var err error var bytesNeeded, servicesReturned uint32 var buf []byte for { var p *byte if len(buf) > 0 { p = &buf[0] } err = windows.EnumServicesStatusEx(m.Handle, windows.SC_ENUM_PROCESS_INFO, windows.SERVICE_WIN32, windows.SERVICE_STATE_ALL, p, uint32(len(buf)), &bytesNeeded, &servicesReturned, nil, nil) if err == nil { break } if err != syscall.ERROR_MORE_DATA { return nil, err } if bytesNeeded <= uint32(len(buf)) { return nil, err } buf = make([]byte, bytesNeeded) } if servicesReturned == 0 { return nil, nil } services := (*[1 << 20]windows.ENUM_SERVICE_STATUS_PROCESS)(unsafe.Pointer(&buf[0]))[:servicesReturned] var names []string for _, s := range services { name := syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(s.ServiceName))[:]) names = append(names, name) } return names, nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/mgr/config.go0000644061062106075000000000754313172163421025223 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package mgr import ( "syscall" "unicode/utf16" "unsafe" "golang.org/x/sys/windows" ) const ( // Service start types. StartManual = windows.SERVICE_DEMAND_START // the service must be started manually StartAutomatic = windows.SERVICE_AUTO_START // the service will start by itself whenever the computer reboots StartDisabled = windows.SERVICE_DISABLED // the service cannot be started // The severity of the error, and action taken, // if this service fails to start. ErrorCritical = windows.SERVICE_ERROR_CRITICAL ErrorIgnore = windows.SERVICE_ERROR_IGNORE ErrorNormal = windows.SERVICE_ERROR_NORMAL ErrorSevere = windows.SERVICE_ERROR_SEVERE ) // TODO(brainman): Password is not returned by windows.QueryServiceConfig, not sure how to get it. type Config struct { ServiceType uint32 StartType uint32 ErrorControl uint32 BinaryPathName string // fully qualified path to the service binary file, can also include arguments for an auto-start service LoadOrderGroup string TagId uint32 Dependencies []string ServiceStartName string // name of the account under which the service should run DisplayName string Password string Description string } func toString(p *uint16) string { if p == nil { return "" } return syscall.UTF16ToString((*[4096]uint16)(unsafe.Pointer(p))[:]) } func toStringSlice(ps *uint16) []string { if ps == nil { return nil } r := make([]string, 0) for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(ps)); true; i++ { if p[i] == 0 { // empty string marks the end if i <= from { break } r = append(r, string(utf16.Decode(p[from:i]))) from = i + 1 } } return r } // Config retrieves service s configuration paramteres. func (s *Service) Config() (Config, error) { var p *windows.QUERY_SERVICE_CONFIG n := uint32(1024) for { b := make([]byte, n) p = (*windows.QUERY_SERVICE_CONFIG)(unsafe.Pointer(&b[0])) err := windows.QueryServiceConfig(s.Handle, p, n, &n) if err == nil { break } if err.(syscall.Errno) != syscall.ERROR_INSUFFICIENT_BUFFER { return Config{}, err } if n <= uint32(len(b)) { return Config{}, err } } var p2 *windows.SERVICE_DESCRIPTION n = uint32(1024) for { b := make([]byte, n) p2 = (*windows.SERVICE_DESCRIPTION)(unsafe.Pointer(&b[0])) err := windows.QueryServiceConfig2(s.Handle, windows.SERVICE_CONFIG_DESCRIPTION, &b[0], n, &n) if err == nil { break } if err.(syscall.Errno) != syscall.ERROR_INSUFFICIENT_BUFFER { return Config{}, err } if n <= uint32(len(b)) { return Config{}, err } } return Config{ ServiceType: p.ServiceType, StartType: p.StartType, ErrorControl: p.ErrorControl, BinaryPathName: toString(p.BinaryPathName), LoadOrderGroup: toString(p.LoadOrderGroup), TagId: p.TagId, Dependencies: toStringSlice(p.Dependencies), ServiceStartName: toString(p.ServiceStartName), DisplayName: toString(p.DisplayName), Description: toString(p2.Description), }, nil } func updateDescription(handle windows.Handle, desc string) error { d := windows.SERVICE_DESCRIPTION{toPtr(desc)} return windows.ChangeServiceConfig2(handle, windows.SERVICE_CONFIG_DESCRIPTION, (*byte)(unsafe.Pointer(&d))) } // UpdateConfig updates service s configuration parameters. func (s *Service) UpdateConfig(c Config) error { err := windows.ChangeServiceConfig(s.Handle, c.ServiceType, c.StartType, c.ErrorControl, toPtr(c.BinaryPathName), toPtr(c.LoadOrderGroup), nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), toPtr(c.Password), toPtr(c.DisplayName)) if err != nil { return err } return updateDescription(s.Handle, c.Description) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/go13.go0000644061062106075000000000153713172163421023737 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // +build go1.3 package svc import "unsafe" const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const // Should be a built-in for unsafe.Pointer? func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { return unsafe.Pointer(uintptr(p) + x) } // funcPC returns the entry PC of the function f. // It assumes that f is a func value. Otherwise the behavior is undefined. func funcPC(f interface{}) uintptr { return **(**uintptr)(add(unsafe.Pointer(&f), ptrSize)) } // from sys_386.s and sys_amd64.s func servicectlhandler(ctl uint32) uintptr func servicemain(argc uint32, argv **uint16) func getServiceMain(r *uintptr) { *r = funcPC(servicemain) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/go12.go0000644061062106075000000000040113172163421023723 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // +build !go1.3 package svc // from go12.c func getServiceMain(r *uintptr) lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/go12.c0000644061062106075000000000076113172163421023551 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // +build !go1.3 // copied from pkg/runtime typedef unsigned int uint32; typedef unsigned long long int uint64; #ifdef _64BIT typedef uint64 uintptr; #else typedef uint32 uintptr; #endif // from sys_386.s or sys_amd64.s void ·servicemain(void); void ·getServiceMain(uintptr *r) { *r = (uintptr)·servicemain; } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/example/0000755061062106075000000000000013172163421024264 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/example/service.go0000644061062106075000000000375313172163421026263 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package main import ( "fmt" "time" "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/debug" "golang.org/x/sys/windows/svc/eventlog" ) var elog debug.Log type myservice struct{} func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) { const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue changes <- svc.Status{State: svc.StartPending} fasttick := time.Tick(500 * time.Millisecond) slowtick := time.Tick(2 * time.Second) tick := fasttick changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} loop: for { select { case <-tick: beep() elog.Info(1, "beep") case c := <-r: switch c.Cmd { case svc.Interrogate: changes <- c.CurrentStatus // Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4 time.Sleep(100 * time.Millisecond) changes <- c.CurrentStatus case svc.Stop, svc.Shutdown: break loop case svc.Pause: changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted} tick = slowtick case svc.Continue: changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} tick = fasttick default: elog.Error(1, fmt.Sprintf("unexpected control request #%d", c)) } } } changes <- svc.Status{State: svc.StopPending} return } func runService(name string, isDebug bool) { var err error if isDebug { elog = debug.New(name) } else { elog, err = eventlog.Open(name) if err != nil { return } } defer elog.Close() elog.Info(1, fmt.Sprintf("starting %s service", name)) run := svc.Run if isDebug { run = debug.Run } err = run(name, &myservice{}) if err != nil { elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err)) return } elog.Info(1, fmt.Sprintf("%s service stopped", name)) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/example/manage.go0000644061062106075000000000256413172163421026052 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package main import ( "fmt" "time" "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/mgr" ) func startService(name string) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() err = s.Start("is", "manual-started") if err != nil { return fmt.Errorf("could not start service: %v", err) } return nil } func controlService(name string, c svc.Cmd, to svc.State) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() status, err := s.Control(c) if err != nil { return fmt.Errorf("could not send control=%d: %v", c, err) } timeout := time.Now().Add(10 * time.Second) for status.State != to { if timeout.Before(time.Now()) { return fmt.Errorf("timeout waiting for service to go to state=%d", to) } time.Sleep(300 * time.Millisecond) status, err = s.Query() if err != nil { return fmt.Errorf("could not retrieve service status: %v", err) } } return nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/example/main.go0000644061062106075000000000335113172163421025541 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // Example service program that beeps. // // The program demonstrates how to create Windows service and // install / remove it on a computer. It also shows how to // stop / start / pause / continue any service, and how to // write to event log. It also shows how to use debug // facilities available in debug package. // package main import ( "fmt" "log" "os" "strings" "golang.org/x/sys/windows/svc" ) func usage(errmsg string) { fmt.Fprintf(os.Stderr, "%s\n\n"+ "usage: %s \n"+ " where is one of\n"+ " install, remove, debug, start, stop, pause or continue.\n", errmsg, os.Args[0]) os.Exit(2) } func main() { const svcName = "myservice" isIntSess, err := svc.IsAnInteractiveSession() if err != nil { log.Fatalf("failed to determine if we are running in an interactive session: %v", err) } if !isIntSess { runService(svcName, false) return } if len(os.Args) < 2 { usage("no command specified") } cmd := strings.ToLower(os.Args[1]) switch cmd { case "debug": runService(svcName, true) return case "install": err = installService(svcName, "my service") case "remove": err = removeService(svcName) case "start": err = startService(svcName) case "stop": err = controlService(svcName, svc.Stop, svc.Stopped) case "pause": err = controlService(svcName, svc.Pause, svc.Paused) case "continue": err = controlService(svcName, svc.Continue, svc.Running) default: usage(fmt.Sprintf("invalid command %s", cmd)) } if err != nil { log.Fatalf("failed to %s %s: %v", cmd, svcName, err) } return } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/example/install.go0000644061062106075000000000345313172163421026266 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package main import ( "fmt" "os" "path/filepath" "golang.org/x/sys/windows/svc/eventlog" "golang.org/x/sys/windows/svc/mgr" ) func exePath() (string, error) { prog := os.Args[0] p, err := filepath.Abs(prog) if err != nil { return "", err } fi, err := os.Stat(p) if err == nil { if !fi.Mode().IsDir() { return p, nil } err = fmt.Errorf("%s is directory", p) } if filepath.Ext(p) == "" { p += ".exe" fi, err := os.Stat(p) if err == nil { if !fi.Mode().IsDir() { return p, nil } err = fmt.Errorf("%s is directory", p) } } return "", err } func installService(name, desc string) error { exepath, err := exePath() if err != nil { return err } m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err == nil { s.Close() return fmt.Errorf("service %s already exists", name) } s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: desc}, "is", "auto-started") if err != nil { return err } defer s.Close() err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info) if err != nil { s.Delete() return fmt.Errorf("SetupEventLogSource() failed: %s", err) } return nil } func removeService(name string) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("service %s is not installed", name) } defer s.Close() err = s.Delete() if err != nil { return err } err = eventlog.Remove(name) if err != nil { return fmt.Errorf("RemoveEventLogSource() failed: %s", err) } return nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/example/beep.go0000644061062106075000000000073513172163421025533 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package main import ( "syscall" ) // BUG(brainman): MessageBeep Windows api is broken on Windows 7, // so this example does not beep when runs as service on Windows 7. var ( beepFunc = syscall.MustLoadDLL("user32.dll").MustFindProc("MessageBeep") ) func beep() { beepFunc.Call(0xffffffff) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/eventlog/0000755061062106075000000000000013172163421024454 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/eventlog/log_test.go0000644061062106075000000000204513172163421026624 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package eventlog_test import ( "testing" "golang.org/x/sys/windows/svc/eventlog" ) func TestLog(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode - it modifies system logs") } const name = "mylog" const supports = eventlog.Error | eventlog.Warning | eventlog.Info err := eventlog.InstallAsEventCreate(name, supports) if err != nil { t.Fatalf("Install failed: %s", err) } defer func() { err = eventlog.Remove(name) if err != nil { t.Fatalf("Remove failed: %s", err) } }() l, err := eventlog.Open(name) if err != nil { t.Fatalf("Open failed: %s", err) } defer l.Close() err = l.Info(1, "info") if err != nil { t.Fatalf("Info failed: %s", err) } err = l.Warning(2, "warning") if err != nil { t.Fatalf("Warning failed: %s", err) } err = l.Error(3, "error") if err != nil { t.Fatalf("Error failed: %s", err) } } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/eventlog/log.go0000644061062106075000000000377113172163421025574 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // Package eventlog implements access to Windows event log. // package eventlog import ( "errors" "syscall" "golang.org/x/sys/windows" ) // Log provides access to the system log. type Log struct { Handle windows.Handle } // Open retrieves a handle to the specified event log. func Open(source string) (*Log, error) { return OpenRemote("", source) } // OpenRemote does the same as Open, but on different computer host. func OpenRemote(host, source string) (*Log, error) { if source == "" { return nil, errors.New("Specify event log source") } var s *uint16 if host != "" { s = syscall.StringToUTF16Ptr(host) } h, err := windows.RegisterEventSource(s, syscall.StringToUTF16Ptr(source)) if err != nil { return nil, err } return &Log{Handle: h}, nil } // Close closes event log l. func (l *Log) Close() error { return windows.DeregisterEventSource(l.Handle) } func (l *Log) report(etype uint16, eid uint32, msg string) error { ss := []*uint16{syscall.StringToUTF16Ptr(msg)} return windows.ReportEvent(l.Handle, etype, 0, eid, 0, 1, 0, &ss[0], nil) } // Info writes an information event msg with event id eid to the end of event log l. // When EventCreate.exe is used, eid must be between 1 and 1000. func (l *Log) Info(eid uint32, msg string) error { return l.report(windows.EVENTLOG_INFORMATION_TYPE, eid, msg) } // Warning writes an warning event msg with event id eid to the end of event log l. // When EventCreate.exe is used, eid must be between 1 and 1000. func (l *Log) Warning(eid uint32, msg string) error { return l.report(windows.EVENTLOG_WARNING_TYPE, eid, msg) } // Error writes an error event msg with event id eid to the end of event log l. // When EventCreate.exe is used, eid must be between 1 and 1000. func (l *Log) Error(eid uint32, msg string) error { return l.report(windows.EVENTLOG_ERROR_TYPE, eid, msg) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/eventlog/install.go0000644061062106075000000000444513172163421026460 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package eventlog import ( "errors" "golang.org/x/sys/windows" "golang.org/x/sys/windows/registry" ) const ( // Log levels. Info = windows.EVENTLOG_INFORMATION_TYPE Warning = windows.EVENTLOG_WARNING_TYPE Error = windows.EVENTLOG_ERROR_TYPE ) const addKeyName = `SYSTEM\CurrentControlSet\Services\EventLog\Application` // Install modifies PC registry to allow logging with an event source src. // It adds all required keys and values to the event log registry key. // Install uses msgFile as the event message file. If useExpandKey is true, // the event message file is installed as REG_EXPAND_SZ value, // otherwise as REG_SZ. Use bitwise of log.Error, log.Warning and // log.Info to specify events supported by the new event source. func Install(src, msgFile string, useExpandKey bool, eventsSupported uint32) error { appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.CREATE_SUB_KEY) if err != nil { return err } defer appkey.Close() sk, alreadyExist, err := registry.CreateKey(appkey, src, registry.SET_VALUE) if err != nil { return err } defer sk.Close() if alreadyExist { return errors.New(addKeyName + `\` + src + " registry key already exists") } err = sk.SetDWordValue("CustomSource", 1) if err != nil { return err } if useExpandKey { err = sk.SetExpandStringValue("EventMessageFile", msgFile) } else { err = sk.SetStringValue("EventMessageFile", msgFile) } if err != nil { return err } err = sk.SetDWordValue("TypesSupported", eventsSupported) if err != nil { return err } return nil } // InstallAsEventCreate is the same as Install, but uses // %SystemRoot%\System32\EventCreate.exe as the event message file. func InstallAsEventCreate(src string, eventsSupported uint32) error { return Install(src, "%SystemRoot%\\System32\\EventCreate.exe", true, eventsSupported) } // Remove deletes all registry elements installed by the correspondent Install. func Remove(src string) error { appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.SET_VALUE) if err != nil { return err } defer appkey.Close() return registry.DeleteKey(appkey, src) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/event.go0000644061062106075000000000172313172163421024304 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package svc import ( "errors" "golang.org/x/sys/windows" ) // event represents auto-reset, initially non-signaled Windows event. // It is used to communicate between go and asm parts of this package. type event struct { h windows.Handle } func newEvent() (*event, error) { h, err := windows.CreateEvent(nil, 0, 0, nil) if err != nil { return nil, err } return &event{h: h}, nil } func (e *event) Close() error { return windows.CloseHandle(e.h) } func (e *event) Set() error { return windows.SetEvent(e.h) } func (e *event) Wait() error { s, err := windows.WaitForSingleObject(e.h, windows.INFINITE) switch s { case windows.WAIT_OBJECT_0: break case windows.WAIT_FAILED: return err default: return errors.New("unexpected result from WaitForSingleObject") } return nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/debug/0000755061062106075000000000000013172163421023717 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/debug/service.go0000644061062106075000000000176513172163421025717 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // Package debug provides facilities to execute svc.Handler on console. // package debug import ( "os" "os/signal" "syscall" "golang.org/x/sys/windows/svc" ) // Run executes service name by calling appropriate handler function. // The process is running on console, unlike real service. Use Ctrl+C to // send "Stop" command to your service. func Run(name string, handler svc.Handler) error { cmds := make(chan svc.ChangeRequest) changes := make(chan svc.Status) sig := make(chan os.Signal) signal.Notify(sig) go func() { status := svc.Status{State: svc.Stopped} for { select { case <-sig: cmds <- svc.ChangeRequest{svc.Stop, 0, 0, status} case status = <-changes: } } }() _, errno := handler.Execute([]string{name}, cmds, changes) if errno != 0 { return syscall.Errno(errno) } return nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/svc/debug/log.go0000644061062106075000000000263213172163421025032 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package debug import ( "os" "strconv" ) // Log interface allows different log implementations to be used. type Log interface { Close() error Info(eid uint32, msg string) error Warning(eid uint32, msg string) error Error(eid uint32, msg string) error } // ConsoleLog provides access to the console. type ConsoleLog struct { Name string } // New creates new ConsoleLog. func New(source string) *ConsoleLog { return &ConsoleLog{Name: source} } // Close closes console log l. func (l *ConsoleLog) Close() error { return nil } func (l *ConsoleLog) report(kind string, eid uint32, msg string) error { s := l.Name + "." + kind + "(" + strconv.Itoa(int(eid)) + "): " + msg + "\n" _, err := os.Stdout.Write([]byte(s)) return err } // Info writes an information event msg with event id eid to the console l. func (l *ConsoleLog) Info(eid uint32, msg string) error { return l.report("info", eid, msg) } // Warning writes an warning event msg with event id eid to the console l. func (l *ConsoleLog) Warning(eid uint32, msg string) error { return l.report("warn", eid, msg) } // Error writes an error event msg with event id eid to the console l. func (l *ConsoleLog) Error(eid uint32, msg string) error { return l.report("error", eid, msg) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/str.go0000644061062106075000000000076713172163421023207 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package windows func itoa(val int) string { // do it here rather than with fmt to avoid dependency if val < 0 { return "-" + itoa(-val) } var buf [32]byte // big enough for int64 i := len(buf) - 1 for val >= 10 { buf[i] = byte(val%10 + '0') i-- val /= 10 } buf[i] = byte(val + '0') return string(buf[i:]) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/service.go0000644061062106075000000001515013172163421024027 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package windows const ( SC_MANAGER_CONNECT = 1 SC_MANAGER_CREATE_SERVICE = 2 SC_MANAGER_ENUMERATE_SERVICE = 4 SC_MANAGER_LOCK = 8 SC_MANAGER_QUERY_LOCK_STATUS = 16 SC_MANAGER_MODIFY_BOOT_CONFIG = 32 SC_MANAGER_ALL_ACCESS = 0xf003f ) //sys OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenSCManagerW const ( SERVICE_KERNEL_DRIVER = 1 SERVICE_FILE_SYSTEM_DRIVER = 2 SERVICE_ADAPTER = 4 SERVICE_RECOGNIZER_DRIVER = 8 SERVICE_WIN32_OWN_PROCESS = 16 SERVICE_WIN32_SHARE_PROCESS = 32 SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS SERVICE_INTERACTIVE_PROCESS = 256 SERVICE_DRIVER = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER SERVICE_TYPE_ALL = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER | SERVICE_INTERACTIVE_PROCESS SERVICE_BOOT_START = 0 SERVICE_SYSTEM_START = 1 SERVICE_AUTO_START = 2 SERVICE_DEMAND_START = 3 SERVICE_DISABLED = 4 SERVICE_ERROR_IGNORE = 0 SERVICE_ERROR_NORMAL = 1 SERVICE_ERROR_SEVERE = 2 SERVICE_ERROR_CRITICAL = 3 SC_STATUS_PROCESS_INFO = 0 SERVICE_STOPPED = 1 SERVICE_START_PENDING = 2 SERVICE_STOP_PENDING = 3 SERVICE_RUNNING = 4 SERVICE_CONTINUE_PENDING = 5 SERVICE_PAUSE_PENDING = 6 SERVICE_PAUSED = 7 SERVICE_NO_CHANGE = 0xffffffff SERVICE_ACCEPT_STOP = 1 SERVICE_ACCEPT_PAUSE_CONTINUE = 2 SERVICE_ACCEPT_SHUTDOWN = 4 SERVICE_ACCEPT_PARAMCHANGE = 8 SERVICE_ACCEPT_NETBINDCHANGE = 16 SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 32 SERVICE_ACCEPT_POWEREVENT = 64 SERVICE_ACCEPT_SESSIONCHANGE = 128 SERVICE_CONTROL_STOP = 1 SERVICE_CONTROL_PAUSE = 2 SERVICE_CONTROL_CONTINUE = 3 SERVICE_CONTROL_INTERROGATE = 4 SERVICE_CONTROL_SHUTDOWN = 5 SERVICE_CONTROL_PARAMCHANGE = 6 SERVICE_CONTROL_NETBINDADD = 7 SERVICE_CONTROL_NETBINDREMOVE = 8 SERVICE_CONTROL_NETBINDENABLE = 9 SERVICE_CONTROL_NETBINDDISABLE = 10 SERVICE_CONTROL_DEVICEEVENT = 11 SERVICE_CONTROL_HARDWAREPROFILECHANGE = 12 SERVICE_CONTROL_POWEREVENT = 13 SERVICE_CONTROL_SESSIONCHANGE = 14 SERVICE_ACTIVE = 1 SERVICE_INACTIVE = 2 SERVICE_STATE_ALL = 3 SERVICE_QUERY_CONFIG = 1 SERVICE_CHANGE_CONFIG = 2 SERVICE_QUERY_STATUS = 4 SERVICE_ENUMERATE_DEPENDENTS = 8 SERVICE_START = 16 SERVICE_STOP = 32 SERVICE_PAUSE_CONTINUE = 64 SERVICE_INTERROGATE = 128 SERVICE_USER_DEFINED_CONTROL = 256 SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL SERVICE_RUNS_IN_SYSTEM_PROCESS = 1 SERVICE_CONFIG_DESCRIPTION = 1 SERVICE_CONFIG_FAILURE_ACTIONS = 2 NO_ERROR = 0 SC_ENUM_PROCESS_INFO = 0 ) type SERVICE_STATUS struct { ServiceType uint32 CurrentState uint32 ControlsAccepted uint32 Win32ExitCode uint32 ServiceSpecificExitCode uint32 CheckPoint uint32 WaitHint uint32 } type SERVICE_TABLE_ENTRY struct { ServiceName *uint16 ServiceProc uintptr } type QUERY_SERVICE_CONFIG struct { ServiceType uint32 StartType uint32 ErrorControl uint32 BinaryPathName *uint16 LoadOrderGroup *uint16 TagId uint32 Dependencies *uint16 ServiceStartName *uint16 DisplayName *uint16 } type SERVICE_DESCRIPTION struct { Description *uint16 } type SERVICE_STATUS_PROCESS struct { ServiceType uint32 CurrentState uint32 ControlsAccepted uint32 Win32ExitCode uint32 ServiceSpecificExitCode uint32 CheckPoint uint32 WaitHint uint32 ProcessId uint32 ServiceFlags uint32 } type ENUM_SERVICE_STATUS_PROCESS struct { ServiceName *uint16 DisplayName *uint16 ServiceStatusProcess SERVICE_STATUS_PROCESS } //sys CloseServiceHandle(handle Handle) (err error) = advapi32.CloseServiceHandle //sys CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) [failretval==0] = advapi32.CreateServiceW //sys OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenServiceW //sys DeleteService(service Handle) (err error) = advapi32.DeleteService //sys StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) = advapi32.StartServiceW //sys QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) = advapi32.QueryServiceStatus //sys ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) = advapi32.ControlService //sys StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) = advapi32.StartServiceCtrlDispatcherW //sys SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) = advapi32.SetServiceStatus //sys ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) = advapi32.ChangeServiceConfigW //sys QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfigW //sys ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) = advapi32.ChangeServiceConfig2W //sys QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfig2W //sys EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) = advapi32.EnumServicesStatusExW lxd-2.0.11/dist/src/golang.org/x/sys/windows/security_windows.go0000644061062106075000000003065513172163421026017 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows import ( "syscall" "unsafe" ) const ( STANDARD_RIGHTS_REQUIRED = 0xf0000 STANDARD_RIGHTS_READ = 0x20000 STANDARD_RIGHTS_WRITE = 0x20000 STANDARD_RIGHTS_EXECUTE = 0x20000 STANDARD_RIGHTS_ALL = 0x1F0000 ) const ( NameUnknown = 0 NameFullyQualifiedDN = 1 NameSamCompatible = 2 NameDisplay = 3 NameUniqueId = 6 NameCanonical = 7 NameUserPrincipal = 8 NameCanonicalEx = 9 NameServicePrincipal = 10 NameDnsDomain = 12 ) // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL. // http://blogs.msdn.com/b/drnick/archive/2007/12/19/windows-and-upn-format-credentials.aspx //sys TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.TranslateNameW //sys GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.GetUserNameExW // TranslateAccountName converts a directory service // object name from one format to another. func TranslateAccountName(username string, from, to uint32, initSize int) (string, error) { u, e := UTF16PtrFromString(username) if e != nil { return "", e } n := uint32(50) for { b := make([]uint16, n) e = TranslateName(u, from, to, &b[0], &n) if e == nil { return UTF16ToString(b[:n]), nil } if e != ERROR_INSUFFICIENT_BUFFER { return "", e } if n <= uint32(len(b)) { return "", e } } } const ( // do not reorder NetSetupUnknownStatus = iota NetSetupUnjoined NetSetupWorkgroupName NetSetupDomainName ) type UserInfo10 struct { Name *uint16 Comment *uint16 UsrComment *uint16 FullName *uint16 } //sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo //sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation //sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree const ( // do not reorder SidTypeUser = 1 + iota SidTypeGroup SidTypeDomain SidTypeAlias SidTypeWellKnownGroup SidTypeDeletedAccount SidTypeInvalid SidTypeUnknown SidTypeComputer SidTypeLabel ) type SidIdentifierAuthority struct { Value [6]byte } var ( SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}} SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}} SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}} SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}} SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}} SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}} SECURITY_MANDATORY_LABEL_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 16}} ) const ( SECURITY_NULL_RID = 0 SECURITY_WORLD_RID = 0 SECURITY_LOCAL_RID = 0 SECURITY_CREATOR_OWNER_RID = 0 SECURITY_CREATOR_GROUP_RID = 1 SECURITY_DIALUP_RID = 1 SECURITY_NETWORK_RID = 2 SECURITY_BATCH_RID = 3 SECURITY_INTERACTIVE_RID = 4 SECURITY_LOGON_IDS_RID = 5 SECURITY_SERVICE_RID = 6 SECURITY_LOCAL_SYSTEM_RID = 18 SECURITY_BUILTIN_DOMAIN_RID = 32 SECURITY_PRINCIPAL_SELF_RID = 10 SECURITY_CREATOR_OWNER_SERVER_RID = 0x2 SECURITY_CREATOR_GROUP_SERVER_RID = 0x3 SECURITY_LOGON_IDS_RID_COUNT = 0x3 SECURITY_ANONYMOUS_LOGON_RID = 0x7 SECURITY_PROXY_RID = 0x8 SECURITY_ENTERPRISE_CONTROLLERS_RID = 0x9 SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID SECURITY_AUTHENTICATED_USER_RID = 0xb SECURITY_RESTRICTED_CODE_RID = 0xc SECURITY_NT_NON_UNIQUE_RID = 0x15 ) //sys LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountSidW //sys LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountNameW //sys ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW //sys ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) = advapi32.ConvertStringSidToSidW //sys GetLengthSid(sid *SID) (len uint32) = advapi32.GetLengthSid //sys CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) = advapi32.CopySid //sys AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) = advapi32.AllocateAndInitializeSid //sys FreeSid(sid *SID) (err error) [failretval!=0] = advapi32.FreeSid //sys EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) = advapi32.EqualSid // The security identifier (SID) structure is a variable-length // structure used to uniquely identify users or groups. type SID struct{} // StringToSid converts a string-format security identifier // sid into a valid, functional sid. func StringToSid(s string) (*SID, error) { var sid *SID p, e := UTF16PtrFromString(s) if e != nil { return nil, e } e = ConvertStringSidToSid(p, &sid) if e != nil { return nil, e } defer LocalFree((Handle)(unsafe.Pointer(sid))) return sid.Copy() } // LookupSID retrieves a security identifier sid for the account // and the name of the domain on which the account was found. // System specify target computer to search. func LookupSID(system, account string) (sid *SID, domain string, accType uint32, err error) { if len(account) == 0 { return nil, "", 0, syscall.EINVAL } acc, e := UTF16PtrFromString(account) if e != nil { return nil, "", 0, e } var sys *uint16 if len(system) > 0 { sys, e = UTF16PtrFromString(system) if e != nil { return nil, "", 0, e } } n := uint32(50) dn := uint32(50) for { b := make([]byte, n) db := make([]uint16, dn) sid = (*SID)(unsafe.Pointer(&b[0])) e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType) if e == nil { return sid, UTF16ToString(db), accType, nil } if e != ERROR_INSUFFICIENT_BUFFER { return nil, "", 0, e } if n <= uint32(len(b)) { return nil, "", 0, e } } } // String converts sid to a string format // suitable for display, storage, or transmission. func (sid *SID) String() (string, error) { var s *uint16 e := ConvertSidToStringSid(sid, &s) if e != nil { return "", e } defer LocalFree((Handle)(unsafe.Pointer(s))) return UTF16ToString((*[256]uint16)(unsafe.Pointer(s))[:]), nil } // Len returns the length, in bytes, of a valid security identifier sid. func (sid *SID) Len() int { return int(GetLengthSid(sid)) } // Copy creates a duplicate of security identifier sid. func (sid *SID) Copy() (*SID, error) { b := make([]byte, sid.Len()) sid2 := (*SID)(unsafe.Pointer(&b[0])) e := CopySid(uint32(len(b)), sid2, sid) if e != nil { return nil, e } return sid2, nil } // LookupAccount retrieves the name of the account for this sid // and the name of the first domain on which this sid is found. // System specify target computer to search for. func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error) { var sys *uint16 if len(system) > 0 { sys, err = UTF16PtrFromString(system) if err != nil { return "", "", 0, err } } n := uint32(50) dn := uint32(50) for { b := make([]uint16, n) db := make([]uint16, dn) e := LookupAccountSid(sys, sid, &b[0], &n, &db[0], &dn, &accType) if e == nil { return UTF16ToString(b), UTF16ToString(db), accType, nil } if e != ERROR_INSUFFICIENT_BUFFER { return "", "", 0, e } if n <= uint32(len(b)) { return "", "", 0, e } } } const ( // do not reorder TOKEN_ASSIGN_PRIMARY = 1 << iota TOKEN_DUPLICATE TOKEN_IMPERSONATE TOKEN_QUERY TOKEN_QUERY_SOURCE TOKEN_ADJUST_PRIVILEGES TOKEN_ADJUST_GROUPS TOKEN_ADJUST_DEFAULT TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY TOKEN_WRITE = STANDARD_RIGHTS_WRITE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE ) const ( // do not reorder TokenUser = 1 + iota TokenGroups TokenPrivileges TokenOwner TokenPrimaryGroup TokenDefaultDacl TokenSource TokenType TokenImpersonationLevel TokenStatistics TokenRestrictedSids TokenSessionId TokenGroupsAndPrivileges TokenSessionReference TokenSandBoxInert TokenAuditPolicy TokenOrigin TokenElevationType TokenLinkedToken TokenElevation TokenHasRestrictions TokenAccessInformation TokenVirtualizationAllowed TokenVirtualizationEnabled TokenIntegrityLevel TokenUIAccess TokenMandatoryPolicy TokenLogonSid MaxTokenInfoClass ) type SIDAndAttributes struct { Sid *SID Attributes uint32 } type Tokenuser struct { User SIDAndAttributes } type Tokenprimarygroup struct { PrimaryGroup *SID } type Tokengroups struct { GroupCount uint32 Groups [1]SIDAndAttributes } //sys OpenProcessToken(h Handle, access uint32, token *Token) (err error) = advapi32.OpenProcessToken //sys GetTokenInformation(t Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) = advapi32.GetTokenInformation //sys GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) = userenv.GetUserProfileDirectoryW // An access token contains the security information for a logon session. // The system creates an access token when a user logs on, and every // process executed on behalf of the user has a copy of the token. // The token identifies the user, the user's groups, and the user's // privileges. The system uses the token to control access to securable // objects and to control the ability of the user to perform various // system-related operations on the local computer. type Token Handle // OpenCurrentProcessToken opens the access token // associated with current process. func OpenCurrentProcessToken() (Token, error) { p, e := GetCurrentProcess() if e != nil { return 0, e } var t Token e = OpenProcessToken(p, TOKEN_QUERY, &t) if e != nil { return 0, e } return t, nil } // Close releases access to access token. func (t Token) Close() error { return CloseHandle(Handle(t)) } // getInfo retrieves a specified type of information about an access token. func (t Token) getInfo(class uint32, initSize int) (unsafe.Pointer, error) { n := uint32(initSize) for { b := make([]byte, n) e := GetTokenInformation(t, class, &b[0], uint32(len(b)), &n) if e == nil { return unsafe.Pointer(&b[0]), nil } if e != ERROR_INSUFFICIENT_BUFFER { return nil, e } if n <= uint32(len(b)) { return nil, e } } } // GetTokenUser retrieves access token t user account information. func (t Token) GetTokenUser() (*Tokenuser, error) { i, e := t.getInfo(TokenUser, 50) if e != nil { return nil, e } return (*Tokenuser)(i), nil } // GetTokenGroups retrieves group accounts associated with access token t. func (t Token) GetTokenGroups() (*Tokengroups, error) { i, e := t.getInfo(TokenGroups, 50) if e != nil { return nil, e } return (*Tokengroups)(i), nil } // GetTokenPrimaryGroup retrieves access token t primary group information. // A pointer to a SID structure representing a group that will become // the primary group of any objects created by a process using this access token. func (t Token) GetTokenPrimaryGroup() (*Tokenprimarygroup, error) { i, e := t.getInfo(TokenPrimaryGroup, 50) if e != nil { return nil, e } return (*Tokenprimarygroup)(i), nil } // GetUserProfileDirectory retrieves path to the // root directory of the access token t user's profile. func (t Token) GetUserProfileDirectory() (string, error) { n := uint32(100) for { b := make([]uint16, n) e := GetUserProfileDirectory(t, &b[0], &n) if e == nil { return UTF16ToString(b), nil } if e != ERROR_INSUFFICIENT_BUFFER { return "", e } if n <= uint32(len(b)) { return "", e } } } lxd-2.0.11/dist/src/golang.org/x/sys/windows/registry/0000755061062106075000000000000013172163421023706 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/windows/registry/zsyscall_windows.go0000644061062106075000000001062113172163421027653 0ustar stgraberdomain admins// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT package registry import ( "syscall" "unsafe" "golang.org/x/sys/windows" ) var _ unsafe.Pointer // Do the interface allocations only once for common // Errno values. const ( errnoERROR_IO_PENDING = 997 ) var ( errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) ) // errnoErr returns common boxed Errno values, to prevent // allocations at runtime. func errnoErr(e syscall.Errno) error { switch e { case 0: return nil case errnoERROR_IO_PENDING: return errERROR_IO_PENDING } // TODO: add more here, after collecting data on the common // error values see on Windows. (perhaps when running // all.bat?) return e } var ( modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") modkernel32 = windows.NewLazySystemDLL("kernel32.dll") procRegCreateKeyExW = modadvapi32.NewProc("RegCreateKeyExW") procRegDeleteKeyW = modadvapi32.NewProc("RegDeleteKeyW") procRegSetValueExW = modadvapi32.NewProc("RegSetValueExW") procRegEnumValueW = modadvapi32.NewProc("RegEnumValueW") procRegDeleteValueW = modadvapi32.NewProc("RegDeleteValueW") procRegLoadMUIStringW = modadvapi32.NewProc("RegLoadMUIStringW") procRegConnectRegistryW = modadvapi32.NewProc("RegConnectRegistryW") procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW") ) func regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) { r0, _, _ := syscall.Syscall9(procRegCreateKeyExW.Addr(), 9, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desired), uintptr(unsafe.Pointer(sa)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition))) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) { r0, _, _ := syscall.Syscall(procRegDeleteKeyW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(subkey)), 0) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) { r0, _, _ := syscall.Syscall6(procRegSetValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(valueName)), uintptr(reserved), uintptr(vtype), uintptr(unsafe.Pointer(buf)), uintptr(bufsize)) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) { r0, _, _ := syscall.Syscall9(procRegEnumValueW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)), 0) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) { r0, _, _ := syscall.Syscall(procRegDeleteValueW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(name)), 0) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) { r0, _, _ := syscall.Syscall9(procRegLoadMUIStringW.Addr(), 7, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(unsafe.Pointer(buflenCopied)), uintptr(flags), uintptr(unsafe.Pointer(dir)), 0, 0) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func regConnectRegistry(machinename *uint16, key syscall.Handle, result *syscall.Handle) (regerrno error) { r0, _, _ := syscall.Syscall(procRegConnectRegistryW.Addr(), 3, uintptr(unsafe.Pointer(machinename)), uintptr(key), uintptr(unsafe.Pointer(result))) if r0 != 0 { regerrno = syscall.Errno(r0) } return } func expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procExpandEnvironmentStringsW.Addr(), 3, uintptr(unsafe.Pointer(src)), uintptr(unsafe.Pointer(dst)), uintptr(size)) n = uint32(r0) if n == 0 { if e1 != 0 { err = errnoErr(e1) } else { err = syscall.EINVAL } } return } lxd-2.0.11/dist/src/golang.org/x/sys/windows/registry/value.go0000644061062106075000000002661313172163421025361 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package registry import ( "errors" "io" "syscall" "unicode/utf16" "unsafe" ) const ( // Registry value types. NONE = 0 SZ = 1 EXPAND_SZ = 2 BINARY = 3 DWORD = 4 DWORD_BIG_ENDIAN = 5 LINK = 6 MULTI_SZ = 7 RESOURCE_LIST = 8 FULL_RESOURCE_DESCRIPTOR = 9 RESOURCE_REQUIREMENTS_LIST = 10 QWORD = 11 ) var ( // ErrShortBuffer is returned when the buffer was too short for the operation. ErrShortBuffer = syscall.ERROR_MORE_DATA // ErrNotExist is returned when a registry key or value does not exist. ErrNotExist = syscall.ERROR_FILE_NOT_FOUND // ErrUnexpectedType is returned by Get*Value when the value's type was unexpected. ErrUnexpectedType = errors.New("unexpected key value type") ) // GetValue retrieves the type and data for the specified value associated // with an open key k. It fills up buffer buf and returns the retrieved // byte count n. If buf is too small to fit the stored value it returns // ErrShortBuffer error along with the required buffer size n. // If no buffer is provided, it returns true and actual buffer size n. // If no buffer is provided, GetValue returns the value's type only. // If the value does not exist, the error returned is ErrNotExist. // // GetValue is a low level function. If value's type is known, use the appropriate // Get*Value function instead. func (k Key) GetValue(name string, buf []byte) (n int, valtype uint32, err error) { pname, err := syscall.UTF16PtrFromString(name) if err != nil { return 0, 0, err } var pbuf *byte if len(buf) > 0 { pbuf = (*byte)(unsafe.Pointer(&buf[0])) } l := uint32(len(buf)) err = syscall.RegQueryValueEx(syscall.Handle(k), pname, nil, &valtype, pbuf, &l) if err != nil { return int(l), valtype, err } return int(l), valtype, nil } func (k Key) getValue(name string, buf []byte) (date []byte, valtype uint32, err error) { p, err := syscall.UTF16PtrFromString(name) if err != nil { return nil, 0, err } var t uint32 n := uint32(len(buf)) for { err = syscall.RegQueryValueEx(syscall.Handle(k), p, nil, &t, (*byte)(unsafe.Pointer(&buf[0])), &n) if err == nil { return buf[:n], t, nil } if err != syscall.ERROR_MORE_DATA { return nil, 0, err } if n <= uint32(len(buf)) { return nil, 0, err } buf = make([]byte, n) } } // GetStringValue retrieves the string value for the specified // value name associated with an open key k. It also returns the value's type. // If value does not exist, GetStringValue returns ErrNotExist. // If value is not SZ or EXPAND_SZ, it will return the correct value // type and ErrUnexpectedType. func (k Key) GetStringValue(name string) (val string, valtype uint32, err error) { data, typ, err2 := k.getValue(name, make([]byte, 64)) if err2 != nil { return "", typ, err2 } switch typ { case SZ, EXPAND_SZ: default: return "", typ, ErrUnexpectedType } if len(data) == 0 { return "", typ, nil } u := (*[1 << 29]uint16)(unsafe.Pointer(&data[0]))[:] return syscall.UTF16ToString(u), typ, nil } // GetMUIStringValue retrieves the localized string value for // the specified value name associated with an open key k. // If the value name doesn't exist or the localized string value // can't be resolved, GetMUIStringValue returns ErrNotExist. // GetMUIStringValue panics if the system doesn't support // regLoadMUIString; use LoadRegLoadMUIString to check if // regLoadMUIString is supported before calling this function. func (k Key) GetMUIStringValue(name string) (string, error) { pname, err := syscall.UTF16PtrFromString(name) if err != nil { return "", err } buf := make([]uint16, 1024) var buflen uint32 var pdir *uint16 err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir) if err == syscall.ERROR_FILE_NOT_FOUND { // Try fallback path // Try to resolve the string value using the system directory as // a DLL search path; this assumes the string value is of the form // @[path]\dllname,-strID but with no path given, e.g. @tzres.dll,-320. // This approach works with tzres.dll but may have to be revised // in the future to allow callers to provide custom search paths. var s string s, err = ExpandString("%SystemRoot%\\system32\\") if err != nil { return "", err } pdir, err = syscall.UTF16PtrFromString(s) if err != nil { return "", err } err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir) } for err == syscall.ERROR_MORE_DATA { // Grow buffer if needed if buflen <= uint32(len(buf)) { break // Buffer not growing, assume race; break } buf = make([]uint16, buflen) err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir) } if err != nil { return "", err } return syscall.UTF16ToString(buf), nil } // ExpandString expands environment-variable strings and replaces // them with the values defined for the current user. // Use ExpandString to expand EXPAND_SZ strings. func ExpandString(value string) (string, error) { if value == "" { return "", nil } p, err := syscall.UTF16PtrFromString(value) if err != nil { return "", err } r := make([]uint16, 100) for { n, err := expandEnvironmentStrings(p, &r[0], uint32(len(r))) if err != nil { return "", err } if n <= uint32(len(r)) { u := (*[1 << 29]uint16)(unsafe.Pointer(&r[0]))[:] return syscall.UTF16ToString(u), nil } r = make([]uint16, n) } } // GetStringsValue retrieves the []string value for the specified // value name associated with an open key k. It also returns the value's type. // If value does not exist, GetStringsValue returns ErrNotExist. // If value is not MULTI_SZ, it will return the correct value // type and ErrUnexpectedType. func (k Key) GetStringsValue(name string) (val []string, valtype uint32, err error) { data, typ, err2 := k.getValue(name, make([]byte, 64)) if err2 != nil { return nil, typ, err2 } if typ != MULTI_SZ { return nil, typ, ErrUnexpectedType } if len(data) == 0 { return nil, typ, nil } p := (*[1 << 29]uint16)(unsafe.Pointer(&data[0]))[:len(data)/2] if len(p) == 0 { return nil, typ, nil } if p[len(p)-1] == 0 { p = p[:len(p)-1] // remove terminating null } val = make([]string, 0, 5) from := 0 for i, c := range p { if c == 0 { val = append(val, string(utf16.Decode(p[from:i]))) from = i + 1 } } return val, typ, nil } // GetIntegerValue retrieves the integer value for the specified // value name associated with an open key k. It also returns the value's type. // If value does not exist, GetIntegerValue returns ErrNotExist. // If value is not DWORD or QWORD, it will return the correct value // type and ErrUnexpectedType. func (k Key) GetIntegerValue(name string) (val uint64, valtype uint32, err error) { data, typ, err2 := k.getValue(name, make([]byte, 8)) if err2 != nil { return 0, typ, err2 } switch typ { case DWORD: if len(data) != 4 { return 0, typ, errors.New("DWORD value is not 4 bytes long") } return uint64(*(*uint32)(unsafe.Pointer(&data[0]))), DWORD, nil case QWORD: if len(data) != 8 { return 0, typ, errors.New("QWORD value is not 8 bytes long") } return uint64(*(*uint64)(unsafe.Pointer(&data[0]))), QWORD, nil default: return 0, typ, ErrUnexpectedType } } // GetBinaryValue retrieves the binary value for the specified // value name associated with an open key k. It also returns the value's type. // If value does not exist, GetBinaryValue returns ErrNotExist. // If value is not BINARY, it will return the correct value // type and ErrUnexpectedType. func (k Key) GetBinaryValue(name string) (val []byte, valtype uint32, err error) { data, typ, err2 := k.getValue(name, make([]byte, 64)) if err2 != nil { return nil, typ, err2 } if typ != BINARY { return nil, typ, ErrUnexpectedType } return data, typ, nil } func (k Key) setValue(name string, valtype uint32, data []byte) error { p, err := syscall.UTF16PtrFromString(name) if err != nil { return err } if len(data) == 0 { return regSetValueEx(syscall.Handle(k), p, 0, valtype, nil, 0) } return regSetValueEx(syscall.Handle(k), p, 0, valtype, &data[0], uint32(len(data))) } // SetDWordValue sets the data and type of a name value // under key k to value and DWORD. func (k Key) SetDWordValue(name string, value uint32) error { return k.setValue(name, DWORD, (*[4]byte)(unsafe.Pointer(&value))[:]) } // SetQWordValue sets the data and type of a name value // under key k to value and QWORD. func (k Key) SetQWordValue(name string, value uint64) error { return k.setValue(name, QWORD, (*[8]byte)(unsafe.Pointer(&value))[:]) } func (k Key) setStringValue(name string, valtype uint32, value string) error { v, err := syscall.UTF16FromString(value) if err != nil { return err } buf := (*[1 << 29]byte)(unsafe.Pointer(&v[0]))[:len(v)*2] return k.setValue(name, valtype, buf) } // SetStringValue sets the data and type of a name value // under key k to value and SZ. The value must not contain a zero byte. func (k Key) SetStringValue(name, value string) error { return k.setStringValue(name, SZ, value) } // SetExpandStringValue sets the data and type of a name value // under key k to value and EXPAND_SZ. The value must not contain a zero byte. func (k Key) SetExpandStringValue(name, value string) error { return k.setStringValue(name, EXPAND_SZ, value) } // SetStringsValue sets the data and type of a name value // under key k to value and MULTI_SZ. The value strings // must not contain a zero byte. func (k Key) SetStringsValue(name string, value []string) error { ss := "" for _, s := range value { for i := 0; i < len(s); i++ { if s[i] == 0 { return errors.New("string cannot have 0 inside") } } ss += s + "\x00" } v := utf16.Encode([]rune(ss + "\x00")) buf := (*[1 << 29]byte)(unsafe.Pointer(&v[0]))[:len(v)*2] return k.setValue(name, MULTI_SZ, buf) } // SetBinaryValue sets the data and type of a name value // under key k to value and BINARY. func (k Key) SetBinaryValue(name string, value []byte) error { return k.setValue(name, BINARY, value) } // DeleteValue removes a named value from the key k. func (k Key) DeleteValue(name string) error { return regDeleteValue(syscall.Handle(k), syscall.StringToUTF16Ptr(name)) } // ReadValueNames returns the value names of key k. // The parameter n controls the number of returned names, // analogous to the way os.File.Readdirnames works. func (k Key) ReadValueNames(n int) ([]string, error) { ki, err := k.Stat() if err != nil { return nil, err } names := make([]string, 0, ki.ValueCount) buf := make([]uint16, ki.MaxValueNameLen+1) // extra room for terminating null character loopItems: for i := uint32(0); ; i++ { if n > 0 { if len(names) == n { return names, nil } } l := uint32(len(buf)) for { err := regEnumValue(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil) if err == nil { break } if err == syscall.ERROR_MORE_DATA { // Double buffer size and try again. l = uint32(2 * len(buf)) buf = make([]uint16, l) continue } if err == _ERROR_NO_MORE_ITEMS { break loopItems } return names, err } names = append(names, syscall.UTF16ToString(buf[:l])) } if n > len(names) { return names, io.EOF } return names, nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/registry/syscall.go0000644061062106075000000000321013172163421025703 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package registry import "syscall" const ( _REG_OPTION_NON_VOLATILE = 0 _REG_CREATED_NEW_KEY = 1 _REG_OPENED_EXISTING_KEY = 2 _ERROR_NO_MORE_ITEMS syscall.Errno = 259 ) func LoadRegLoadMUIString() error { return procRegLoadMUIStringW.Find() } //sys regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) = advapi32.RegCreateKeyExW //sys regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) = advapi32.RegDeleteKeyW //sys regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) = advapi32.RegSetValueExW //sys regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegEnumValueW //sys regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) = advapi32.RegDeleteValueW //sys regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) = advapi32.RegLoadMUIStringW //sys regConnectRegistry(machinename *uint16, key syscall.Handle, result *syscall.Handle) (regerrno error) = advapi32.RegConnectRegistryW //sys expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW lxd-2.0.11/dist/src/golang.org/x/sys/windows/registry/registry_test.go0000644061062106075000000005215513172163421027154 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package registry_test import ( "bytes" "crypto/rand" "os" "syscall" "testing" "time" "unsafe" "golang.org/x/sys/windows/registry" ) func randKeyName(prefix string) string { const numbers = "0123456789" buf := make([]byte, 10) rand.Read(buf) for i, b := range buf { buf[i] = numbers[b%byte(len(numbers))] } return prefix + string(buf) } func TestReadSubKeyNames(t *testing.T) { k, err := registry.OpenKey(registry.CLASSES_ROOT, "TypeLib", registry.ENUMERATE_SUB_KEYS|registry.QUERY_VALUE) if err != nil { t.Fatal(err) } defer k.Close() names, err := k.ReadSubKeyNames(-1) if err != nil { t.Fatal(err) } var foundStdOle bool for _, name := range names { // Every PC has "stdole 2.0 OLE Automation" library installed. if name == "{00020430-0000-0000-C000-000000000046}" { foundStdOle = true } } if !foundStdOle { t.Fatal("could not find stdole 2.0 OLE Automation") } } func TestCreateOpenDeleteKey(t *testing.T) { k, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) if err != nil { t.Fatal(err) } defer k.Close() testKName := randKeyName("TestCreateOpenDeleteKey_") testK, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY) if err != nil { t.Fatal(err) } defer testK.Close() if exist { t.Fatalf("key %q already exists", testKName) } testKAgain, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY) if err != nil { t.Fatal(err) } defer testKAgain.Close() if !exist { t.Fatalf("key %q should already exist", testKName) } testKOpened, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS) if err != nil { t.Fatal(err) } defer testKOpened.Close() err = registry.DeleteKey(k, testKName) if err != nil { t.Fatal(err) } testKOpenedAgain, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS) if err == nil { defer testKOpenedAgain.Close() t.Fatalf("key %q should already been deleted", testKName) } if err != registry.ErrNotExist { t.Fatalf(`unexpected error ("not exist" expected): %v`, err) } } func equalStringSlice(a, b []string) bool { if len(a) != len(b) { return false } if a == nil { return true } for i := range a { if a[i] != b[i] { return false } } return true } type ValueTest struct { Type uint32 Name string Value interface{} WillFail bool } var ValueTests = []ValueTest{ {Type: registry.SZ, Name: "String1", Value: ""}, {Type: registry.SZ, Name: "String2", Value: "\000", WillFail: true}, {Type: registry.SZ, Name: "String3", Value: "Hello World"}, {Type: registry.SZ, Name: "String4", Value: "Hello World\000", WillFail: true}, {Type: registry.EXPAND_SZ, Name: "ExpString1", Value: ""}, {Type: registry.EXPAND_SZ, Name: "ExpString2", Value: "\000", WillFail: true}, {Type: registry.EXPAND_SZ, Name: "ExpString3", Value: "Hello World"}, {Type: registry.EXPAND_SZ, Name: "ExpString4", Value: "Hello\000World", WillFail: true}, {Type: registry.EXPAND_SZ, Name: "ExpString5", Value: "%PATH%"}, {Type: registry.EXPAND_SZ, Name: "ExpString6", Value: "%NO_SUCH_VARIABLE%"}, {Type: registry.EXPAND_SZ, Name: "ExpString7", Value: "%PATH%;."}, {Type: registry.BINARY, Name: "Binary1", Value: []byte{}}, {Type: registry.BINARY, Name: "Binary2", Value: []byte{1, 2, 3}}, {Type: registry.BINARY, Name: "Binary3", Value: []byte{3, 2, 1, 0, 1, 2, 3}}, {Type: registry.DWORD, Name: "Dword1", Value: uint64(0)}, {Type: registry.DWORD, Name: "Dword2", Value: uint64(1)}, {Type: registry.DWORD, Name: "Dword3", Value: uint64(0xff)}, {Type: registry.DWORD, Name: "Dword4", Value: uint64(0xffff)}, {Type: registry.QWORD, Name: "Qword1", Value: uint64(0)}, {Type: registry.QWORD, Name: "Qword2", Value: uint64(1)}, {Type: registry.QWORD, Name: "Qword3", Value: uint64(0xff)}, {Type: registry.QWORD, Name: "Qword4", Value: uint64(0xffff)}, {Type: registry.QWORD, Name: "Qword5", Value: uint64(0xffffff)}, {Type: registry.QWORD, Name: "Qword6", Value: uint64(0xffffffff)}, {Type: registry.MULTI_SZ, Name: "MultiString1", Value: []string{"a", "b", "c"}}, {Type: registry.MULTI_SZ, Name: "MultiString2", Value: []string{"abc", "", "cba"}}, {Type: registry.MULTI_SZ, Name: "MultiString3", Value: []string{""}}, {Type: registry.MULTI_SZ, Name: "MultiString4", Value: []string{"abcdef"}}, {Type: registry.MULTI_SZ, Name: "MultiString5", Value: []string{"\000"}, WillFail: true}, {Type: registry.MULTI_SZ, Name: "MultiString6", Value: []string{"a\000b"}, WillFail: true}, {Type: registry.MULTI_SZ, Name: "MultiString7", Value: []string{"ab", "\000", "cd"}, WillFail: true}, {Type: registry.MULTI_SZ, Name: "MultiString8", Value: []string{"\000", "cd"}, WillFail: true}, {Type: registry.MULTI_SZ, Name: "MultiString9", Value: []string{"ab", "\000"}, WillFail: true}, } func setValues(t *testing.T, k registry.Key) { for _, test := range ValueTests { var err error switch test.Type { case registry.SZ: err = k.SetStringValue(test.Name, test.Value.(string)) case registry.EXPAND_SZ: err = k.SetExpandStringValue(test.Name, test.Value.(string)) case registry.MULTI_SZ: err = k.SetStringsValue(test.Name, test.Value.([]string)) case registry.BINARY: err = k.SetBinaryValue(test.Name, test.Value.([]byte)) case registry.DWORD: err = k.SetDWordValue(test.Name, uint32(test.Value.(uint64))) case registry.QWORD: err = k.SetQWordValue(test.Name, test.Value.(uint64)) default: t.Fatalf("unsupported type %d for %s value", test.Type, test.Name) } if test.WillFail { if err == nil { t.Fatalf("setting %s value %q should fail, but succeeded", test.Name, test.Value) } } else { if err != nil { t.Fatal(err) } } } } func enumerateValues(t *testing.T, k registry.Key) { names, err := k.ReadValueNames(-1) if err != nil { t.Error(err) return } haveNames := make(map[string]bool) for _, n := range names { haveNames[n] = false } for _, test := range ValueTests { wantFound := !test.WillFail _, haveFound := haveNames[test.Name] if wantFound && !haveFound { t.Errorf("value %s is not found while enumerating", test.Name) } if haveFound && !wantFound { t.Errorf("value %s is found while enumerating, but expected to fail", test.Name) } if haveFound { delete(haveNames, test.Name) } } for n, v := range haveNames { t.Errorf("value %s (%v) is found while enumerating, but has not been cretaed", n, v) } } func testErrNotExist(t *testing.T, name string, err error) { if err == nil { t.Errorf("%s value should not exist", name) return } if err != registry.ErrNotExist { t.Errorf("reading %s value should return 'not exist' error, but got: %s", name, err) return } } func testErrUnexpectedType(t *testing.T, test ValueTest, gottype uint32, err error) { if err == nil { t.Errorf("GetXValue(%q) should not succeed", test.Name) return } if err != registry.ErrUnexpectedType { t.Errorf("reading %s value should return 'unexpected key value type' error, but got: %s", test.Name, err) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } } func testGetStringValue(t *testing.T, k registry.Key, test ValueTest) { got, gottype, err := k.GetStringValue(test.Name) if err != nil { t.Errorf("GetStringValue(%s) failed: %v", test.Name, err) return } if got != test.Value { t.Errorf("want %s value %q, got %q", test.Name, test.Value, got) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } if gottype == registry.EXPAND_SZ { _, err = registry.ExpandString(got) if err != nil { t.Errorf("ExpandString(%s) failed: %v", got, err) return } } } func testGetIntegerValue(t *testing.T, k registry.Key, test ValueTest) { got, gottype, err := k.GetIntegerValue(test.Name) if err != nil { t.Errorf("GetIntegerValue(%s) failed: %v", test.Name, err) return } if got != test.Value.(uint64) { t.Errorf("want %s value %v, got %v", test.Name, test.Value, got) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } } func testGetBinaryValue(t *testing.T, k registry.Key, test ValueTest) { got, gottype, err := k.GetBinaryValue(test.Name) if err != nil { t.Errorf("GetBinaryValue(%s) failed: %v", test.Name, err) return } if !bytes.Equal(got, test.Value.([]byte)) { t.Errorf("want %s value %v, got %v", test.Name, test.Value, got) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } } func testGetStringsValue(t *testing.T, k registry.Key, test ValueTest) { got, gottype, err := k.GetStringsValue(test.Name) if err != nil { t.Errorf("GetStringsValue(%s) failed: %v", test.Name, err) return } if !equalStringSlice(got, test.Value.([]string)) { t.Errorf("want %s value %#v, got %#v", test.Name, test.Value, got) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } } func testGetValue(t *testing.T, k registry.Key, test ValueTest, size int) { if size <= 0 { return } // read data with no buffer gotsize, gottype, err := k.GetValue(test.Name, nil) if err != nil { t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err) return } if gotsize != size { t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } // read data with short buffer gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size-1)) if err == nil { t.Errorf("GetValue(%s, [%d]byte) should fail, but succeeded", test.Name, size-1) return } if err != registry.ErrShortBuffer { t.Errorf("reading %s value should return 'short buffer' error, but got: %s", test.Name, err) return } if gotsize != size { t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } // read full data gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size)) if err != nil { t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err) return } if gotsize != size { t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } // check GetValue returns ErrNotExist as required _, _, err = k.GetValue(test.Name+"_not_there", make([]byte, size)) if err == nil { t.Errorf("GetValue(%q) should not succeed", test.Name) return } if err != registry.ErrNotExist { t.Errorf("GetValue(%q) should return 'not exist' error, but got: %s", test.Name, err) return } } func testValues(t *testing.T, k registry.Key) { for _, test := range ValueTests { switch test.Type { case registry.SZ, registry.EXPAND_SZ: if test.WillFail { _, _, err := k.GetStringValue(test.Name) testErrNotExist(t, test.Name, err) } else { testGetStringValue(t, k, test) _, gottype, err := k.GetIntegerValue(test.Name) testErrUnexpectedType(t, test, gottype, err) // Size of utf16 string in bytes is not perfect, // but correct for current test values. // Size also includes terminating 0. testGetValue(t, k, test, (len(test.Value.(string))+1)*2) } _, _, err := k.GetStringValue(test.Name + "_string_not_created") testErrNotExist(t, test.Name+"_string_not_created", err) case registry.DWORD, registry.QWORD: testGetIntegerValue(t, k, test) _, gottype, err := k.GetBinaryValue(test.Name) testErrUnexpectedType(t, test, gottype, err) _, _, err = k.GetIntegerValue(test.Name + "_int_not_created") testErrNotExist(t, test.Name+"_int_not_created", err) size := 8 if test.Type == registry.DWORD { size = 4 } testGetValue(t, k, test, size) case registry.BINARY: testGetBinaryValue(t, k, test) _, gottype, err := k.GetStringsValue(test.Name) testErrUnexpectedType(t, test, gottype, err) _, _, err = k.GetBinaryValue(test.Name + "_byte_not_created") testErrNotExist(t, test.Name+"_byte_not_created", err) testGetValue(t, k, test, len(test.Value.([]byte))) case registry.MULTI_SZ: if test.WillFail { _, _, err := k.GetStringsValue(test.Name) testErrNotExist(t, test.Name, err) } else { testGetStringsValue(t, k, test) _, gottype, err := k.GetStringValue(test.Name) testErrUnexpectedType(t, test, gottype, err) size := 0 for _, s := range test.Value.([]string) { size += len(s) + 1 // nil terminated } size += 1 // extra nil at the end size *= 2 // count bytes, not uint16 testGetValue(t, k, test, size) } _, _, err := k.GetStringsValue(test.Name + "_strings_not_created") testErrNotExist(t, test.Name+"_strings_not_created", err) default: t.Errorf("unsupported type %d for %s value", test.Type, test.Name) continue } } } func testStat(t *testing.T, k registry.Key) { subk, _, err := registry.CreateKey(k, "subkey", registry.CREATE_SUB_KEY) if err != nil { t.Error(err) return } defer subk.Close() defer registry.DeleteKey(k, "subkey") ki, err := k.Stat() if err != nil { t.Error(err) return } if ki.SubKeyCount != 1 { t.Error("key must have 1 subkey") } if ki.MaxSubKeyLen != 6 { t.Error("key max subkey name length must be 6") } if ki.ValueCount != 24 { t.Errorf("key must have 24 values, but is %d", ki.ValueCount) } if ki.MaxValueNameLen != 12 { t.Errorf("key max value name length must be 10, but is %d", ki.MaxValueNameLen) } if ki.MaxValueLen != 38 { t.Errorf("key max value length must be 38, but is %d", ki.MaxValueLen) } if mt, ct := ki.ModTime(), time.Now(); ct.Sub(mt) > 100*time.Millisecond { t.Errorf("key mod time is not close to current time: mtime=%v current=%v delta=%v", mt, ct, ct.Sub(mt)) } } func deleteValues(t *testing.T, k registry.Key) { for _, test := range ValueTests { if test.WillFail { continue } err := k.DeleteValue(test.Name) if err != nil { t.Error(err) continue } } names, err := k.ReadValueNames(-1) if err != nil { t.Error(err) return } if len(names) != 0 { t.Errorf("some values remain after deletion: %v", names) } } func TestValues(t *testing.T) { softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) if err != nil { t.Fatal(err) } defer softwareK.Close() testKName := randKeyName("TestValues_") k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE) if err != nil { t.Fatal(err) } defer k.Close() if exist { t.Fatalf("key %q already exists", testKName) } defer registry.DeleteKey(softwareK, testKName) setValues(t, k) enumerateValues(t, k) testValues(t, k) testStat(t, k) deleteValues(t, k) } func walkKey(t *testing.T, k registry.Key, kname string) { names, err := k.ReadValueNames(-1) if err != nil { t.Fatalf("reading value names of %s failed: %v", kname, err) } for _, name := range names { _, valtype, err := k.GetValue(name, nil) if err != nil { t.Fatalf("reading value type of %s of %s failed: %v", name, kname, err) } switch valtype { case registry.NONE: case registry.SZ: _, _, err := k.GetStringValue(name) if err != nil { t.Error(err) } case registry.EXPAND_SZ: s, _, err := k.GetStringValue(name) if err != nil { t.Error(err) } _, err = registry.ExpandString(s) if err != nil { t.Error(err) } case registry.DWORD, registry.QWORD: _, _, err := k.GetIntegerValue(name) if err != nil { t.Error(err) } case registry.BINARY: _, _, err := k.GetBinaryValue(name) if err != nil { t.Error(err) } case registry.MULTI_SZ: _, _, err := k.GetStringsValue(name) if err != nil { t.Error(err) } case registry.FULL_RESOURCE_DESCRIPTOR, registry.RESOURCE_LIST, registry.RESOURCE_REQUIREMENTS_LIST: // TODO: not implemented default: t.Fatalf("value type %d of %s of %s failed: %v", valtype, name, kname, err) } } names, err = k.ReadSubKeyNames(-1) if err != nil { t.Fatalf("reading sub-keys of %s failed: %v", kname, err) } for _, name := range names { func() { subk, err := registry.OpenKey(k, name, registry.ENUMERATE_SUB_KEYS|registry.QUERY_VALUE) if err != nil { if err == syscall.ERROR_ACCESS_DENIED { // ignore error, if we are not allowed to access this key return } t.Fatalf("opening sub-keys %s of %s failed: %v", name, kname, err) } defer subk.Close() walkKey(t, subk, kname+`\`+name) }() } } func TestWalkFullRegistry(t *testing.T) { if testing.Short() { t.Skip("skipping long running test in short mode") } walkKey(t, registry.CLASSES_ROOT, "CLASSES_ROOT") walkKey(t, registry.CURRENT_USER, "CURRENT_USER") walkKey(t, registry.LOCAL_MACHINE, "LOCAL_MACHINE") walkKey(t, registry.USERS, "USERS") walkKey(t, registry.CURRENT_CONFIG, "CURRENT_CONFIG") } func TestExpandString(t *testing.T) { got, err := registry.ExpandString("%PATH%") if err != nil { t.Fatal(err) } want := os.Getenv("PATH") if got != want { t.Errorf("want %q string expanded, got %q", want, got) } } func TestInvalidValues(t *testing.T) { softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) if err != nil { t.Fatal(err) } defer softwareK.Close() testKName := randKeyName("TestInvalidValues_") k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE) if err != nil { t.Fatal(err) } defer k.Close() if exist { t.Fatalf("key %q already exists", testKName) } defer registry.DeleteKey(softwareK, testKName) var tests = []struct { Type uint32 Name string Data []byte }{ {registry.DWORD, "Dword1", nil}, {registry.DWORD, "Dword2", []byte{1, 2, 3}}, {registry.QWORD, "Qword1", nil}, {registry.QWORD, "Qword2", []byte{1, 2, 3}}, {registry.QWORD, "Qword3", []byte{1, 2, 3, 4, 5, 6, 7}}, {registry.MULTI_SZ, "MultiString1", nil}, {registry.MULTI_SZ, "MultiString2", []byte{0}}, {registry.MULTI_SZ, "MultiString3", []byte{'a', 'b', 0}}, {registry.MULTI_SZ, "MultiString4", []byte{'a', 0, 0, 'b', 0}}, {registry.MULTI_SZ, "MultiString5", []byte{'a', 0, 0}}, } for _, test := range tests { err := k.SetValue(test.Name, test.Type, test.Data) if err != nil { t.Fatalf("SetValue for %q failed: %v", test.Name, err) } } for _, test := range tests { switch test.Type { case registry.DWORD, registry.QWORD: value, valType, err := k.GetIntegerValue(test.Name) if err == nil { t.Errorf("GetIntegerValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value) } case registry.MULTI_SZ: value, valType, err := k.GetStringsValue(test.Name) if err == nil { if len(value) != 0 { t.Errorf("GetStringsValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value) } } default: t.Errorf("unsupported type %d for %s value", test.Type, test.Name) } } } func TestGetMUIStringValue(t *testing.T) { if err := registry.LoadRegLoadMUIString(); err != nil { t.Skip("regLoadMUIString not supported; skipping") } if err := procGetDynamicTimeZoneInformation.Find(); err != nil { t.Skipf("%s not supported; skipping", procGetDynamicTimeZoneInformation.Name) } var dtzi DynamicTimezoneinformation if _, err := GetDynamicTimeZoneInformation(&dtzi); err != nil { t.Fatal(err) } tzKeyName := syscall.UTF16ToString(dtzi.TimeZoneKeyName[:]) timezoneK, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\`+tzKeyName, registry.READ) if err != nil { t.Fatal(err) } defer timezoneK.Close() type testType struct { name string want string } var tests = []testType{ {"MUI_Std", syscall.UTF16ToString(dtzi.StandardName[:])}, } if dtzi.DynamicDaylightTimeDisabled == 0 { tests = append(tests, testType{"MUI_Dlt", syscall.UTF16ToString(dtzi.DaylightName[:])}) } for _, test := range tests { got, err := timezoneK.GetMUIStringValue(test.name) if err != nil { t.Error("GetMUIStringValue:", err) } if got != test.want { t.Errorf("GetMUIStringValue: %s: Got %q, want %q", test.name, got, test.want) } } } type DynamicTimezoneinformation struct { Bias int32 StandardName [32]uint16 StandardDate syscall.Systemtime StandardBias int32 DaylightName [32]uint16 DaylightDate syscall.Systemtime DaylightBias int32 TimeZoneKeyName [128]uint16 DynamicDaylightTimeDisabled uint8 } var ( kernel32DLL = syscall.NewLazyDLL("kernel32") procGetDynamicTimeZoneInformation = kernel32DLL.NewProc("GetDynamicTimeZoneInformation") ) func GetDynamicTimeZoneInformation(dtzi *DynamicTimezoneinformation) (rc uint32, err error) { r0, _, e1 := syscall.Syscall(procGetDynamicTimeZoneInformation.Addr(), 1, uintptr(unsafe.Pointer(dtzi)), 0, 0) rc = uint32(r0) if rc == 0xffffffff { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } lxd-2.0.11/dist/src/golang.org/x/sys/windows/registry/mksyscall.go0000644061062106075000000000042713172163421026242 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package registry //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go syscall.go lxd-2.0.11/dist/src/golang.org/x/sys/windows/registry/key.go0000644061062106075000000001400513172163421025025 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // Package registry provides access to the Windows registry. // // Here is a simple example, opening a registry key and reading a string value from it. // // k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE) // if err != nil { // log.Fatal(err) // } // defer k.Close() // // s, _, err := k.GetStringValue("SystemRoot") // if err != nil { // log.Fatal(err) // } // fmt.Printf("Windows system root is %q\n", s) // package registry import ( "io" "syscall" "time" ) const ( // Registry key security and access rights. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724878.aspx // for details. ALL_ACCESS = 0xf003f CREATE_LINK = 0x00020 CREATE_SUB_KEY = 0x00004 ENUMERATE_SUB_KEYS = 0x00008 EXECUTE = 0x20019 NOTIFY = 0x00010 QUERY_VALUE = 0x00001 READ = 0x20019 SET_VALUE = 0x00002 WOW64_32KEY = 0x00200 WOW64_64KEY = 0x00100 WRITE = 0x20006 ) // Key is a handle to an open Windows registry key. // Keys can be obtained by calling OpenKey; there are // also some predefined root keys such as CURRENT_USER. // Keys can be used directly in the Windows API. type Key syscall.Handle const ( // Windows defines some predefined root keys that are always open. // An application can use these keys as entry points to the registry. // Normally these keys are used in OpenKey to open new keys, // but they can also be used anywhere a Key is required. CLASSES_ROOT = Key(syscall.HKEY_CLASSES_ROOT) CURRENT_USER = Key(syscall.HKEY_CURRENT_USER) LOCAL_MACHINE = Key(syscall.HKEY_LOCAL_MACHINE) USERS = Key(syscall.HKEY_USERS) CURRENT_CONFIG = Key(syscall.HKEY_CURRENT_CONFIG) PERFORMANCE_DATA = Key(syscall.HKEY_PERFORMANCE_DATA) ) // Close closes open key k. func (k Key) Close() error { return syscall.RegCloseKey(syscall.Handle(k)) } // OpenKey opens a new key with path name relative to key k. // It accepts any open key, including CURRENT_USER and others, // and returns the new key and an error. // The access parameter specifies desired access rights to the // key to be opened. func OpenKey(k Key, path string, access uint32) (Key, error) { p, err := syscall.UTF16PtrFromString(path) if err != nil { return 0, err } var subkey syscall.Handle err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey) if err != nil { return 0, err } return Key(subkey), nil } // OpenRemoteKey opens a predefined registry key on another // computer pcname. The key to be opened is specified by k, but // can only be one of LOCAL_MACHINE, PERFORMANCE_DATA or USERS. // If pcname is "", OpenRemoteKey returns local computer key. func OpenRemoteKey(pcname string, k Key) (Key, error) { var err error var p *uint16 if pcname != "" { p, err = syscall.UTF16PtrFromString(`\\` + pcname) if err != nil { return 0, err } } var remoteKey syscall.Handle err = regConnectRegistry(p, syscall.Handle(k), &remoteKey) if err != nil { return 0, err } return Key(remoteKey), nil } // ReadSubKeyNames returns the names of subkeys of key k. // The parameter n controls the number of returned names, // analogous to the way os.File.Readdirnames works. func (k Key) ReadSubKeyNames(n int) ([]string, error) { ki, err := k.Stat() if err != nil { return nil, err } names := make([]string, 0, ki.SubKeyCount) buf := make([]uint16, ki.MaxSubKeyLen+1) // extra room for terminating zero byte loopItems: for i := uint32(0); ; i++ { if n > 0 { if len(names) == n { return names, nil } } l := uint32(len(buf)) for { err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil) if err == nil { break } if err == syscall.ERROR_MORE_DATA { // Double buffer size and try again. l = uint32(2 * len(buf)) buf = make([]uint16, l) continue } if err == _ERROR_NO_MORE_ITEMS { break loopItems } return names, err } names = append(names, syscall.UTF16ToString(buf[:l])) } if n > len(names) { return names, io.EOF } return names, nil } // CreateKey creates a key named path under open key k. // CreateKey returns the new key and a boolean flag that reports // whether the key already existed. // The access parameter specifies the access rights for the key // to be created. func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) { var h syscall.Handle var d uint32 err = regCreateKeyEx(syscall.Handle(k), syscall.StringToUTF16Ptr(path), 0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d) if err != nil { return 0, false, err } return Key(h), d == _REG_OPENED_EXISTING_KEY, nil } // DeleteKey deletes the subkey path of key k and its values. func DeleteKey(k Key, path string) error { return regDeleteKey(syscall.Handle(k), syscall.StringToUTF16Ptr(path)) } // A KeyInfo describes the statistics of a key. It is returned by Stat. type KeyInfo struct { SubKeyCount uint32 MaxSubKeyLen uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte ValueCount uint32 MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte MaxValueLen uint32 // longest data component among the key's values, in bytes lastWriteTime syscall.Filetime } // ModTime returns the key's last write time. func (ki *KeyInfo) ModTime() time.Time { return time.Unix(0, ki.lastWriteTime.Nanoseconds()) } // Stat retrieves information about the open key k. func (k Key) Stat() (*KeyInfo, error) { var ki KeyInfo err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil, &ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount, &ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime) if err != nil { return nil, err } return &ki, nil } lxd-2.0.11/dist/src/golang.org/x/sys/windows/registry/export_test.go0000644061062106075000000000046713172163421026624 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package registry func (k Key) SetValue(name string, valtype uint32, data []byte) error { return k.setValue(name, valtype, data) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/race0.go0000644061062106075000000000070313172163421023357 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows,!race package windows import ( "unsafe" ) const raceenabled = false func raceAcquire(addr unsafe.Pointer) { } func raceReleaseMerge(addr unsafe.Pointer) { } func raceReadRange(addr unsafe.Pointer, len int) { } func raceWriteRange(addr unsafe.Pointer, len int) { } lxd-2.0.11/dist/src/golang.org/x/sys/windows/race.go0000644061062106075000000000111413172163421023274 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows,race package windows import ( "runtime" "unsafe" ) const raceenabled = true func raceAcquire(addr unsafe.Pointer) { runtime.RaceAcquire(addr) } func raceReleaseMerge(addr unsafe.Pointer) { runtime.RaceReleaseMerge(addr) } func raceReadRange(addr unsafe.Pointer, len int) { runtime.RaceReadRange(addr, len) } func raceWriteRange(addr unsafe.Pointer, len int) { runtime.RaceWriteRange(addr, len) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/mksyscall.go0000644061062106075000000000051213172163421024365 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go lxd-2.0.11/dist/src/golang.org/x/sys/windows/memory_windows.go0000644061062106075000000000130213172163421025443 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows const ( MEM_COMMIT = 0x00001000 MEM_RESERVE = 0x00002000 MEM_DECOMMIT = 0x00004000 MEM_RELEASE = 0x00008000 MEM_RESET = 0x00080000 MEM_TOP_DOWN = 0x00100000 MEM_WRITE_WATCH = 0x00200000 MEM_PHYSICAL = 0x00400000 MEM_RESET_UNDO = 0x01000000 MEM_LARGE_PAGES = 0x20000000 PAGE_NOACCESS = 0x01 PAGE_READONLY = 0x02 PAGE_READWRITE = 0x04 PAGE_WRITECOPY = 0x08 PAGE_EXECUTE_READ = 0x20 PAGE_EXECUTE_READWRITE = 0x40 PAGE_EXECUTE_WRITECOPY = 0x80 ) lxd-2.0.11/dist/src/golang.org/x/sys/windows/exec_windows.go0000644061062106075000000000363513172163421025072 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Fork, exec, wait, etc. package windows // EscapeArg rewrites command line argument s as prescribed // in http://msdn.microsoft.com/en-us/library/ms880421. // This function returns "" (2 double quotes) if s is empty. // Alternatively, these transformations are done: // - every back slash (\) is doubled, but only if immediately // followed by double quote ("); // - every double quote (") is escaped by back slash (\); // - finally, s is wrapped with double quotes (arg -> "arg"), // but only if there is space or tab inside s. func EscapeArg(s string) string { if len(s) == 0 { return "\"\"" } n := len(s) hasSpace := false for i := 0; i < len(s); i++ { switch s[i] { case '"', '\\': n++ case ' ', '\t': hasSpace = true } } if hasSpace { n += 2 } if n == len(s) { return s } qs := make([]byte, n) j := 0 if hasSpace { qs[j] = '"' j++ } slashes := 0 for i := 0; i < len(s); i++ { switch s[i] { default: slashes = 0 qs[j] = s[i] case '\\': slashes++ qs[j] = s[i] case '"': for ; slashes > 0; slashes-- { qs[j] = '\\' j++ } qs[j] = '\\' j++ qs[j] = s[i] } j++ } if hasSpace { for ; slashes > 0; slashes-- { qs[j] = '\\' j++ } qs[j] = '"' j++ } return string(qs[:j]) } func CloseOnExec(fd Handle) { SetHandleInformation(Handle(fd), HANDLE_FLAG_INHERIT, 0) } // FullPath retrieves the full path of the specified file. func FullPath(name string) (path string, err error) { p, err := UTF16PtrFromString(name) if err != nil { return "", err } n := uint32(100) for { buf := make([]uint16, n) n, err = GetFullPathName(p, uint32(len(buf)), &buf[0], nil) if err != nil { return "", err } if n <= uint32(len(buf)) { return UTF16ToString(buf[:n]), nil } } } lxd-2.0.11/dist/src/golang.org/x/sys/windows/eventlog.go0000644061062106075000000000147013172163421024212 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package windows const ( EVENTLOG_SUCCESS = 0 EVENTLOG_ERROR_TYPE = 1 EVENTLOG_WARNING_TYPE = 2 EVENTLOG_INFORMATION_TYPE = 4 EVENTLOG_AUDIT_SUCCESS = 8 EVENTLOG_AUDIT_FAILURE = 16 ) //sys RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) [failretval==0] = advapi32.RegisterEventSourceW //sys DeregisterEventSource(handle Handle) (err error) = advapi32.DeregisterEventSource //sys ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) = advapi32.ReportEventW lxd-2.0.11/dist/src/golang.org/x/sys/windows/env_windows.go0000644061062106075000000000074713172163421024737 0ustar stgraberdomain admins// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Windows environment variables. package windows import "syscall" func Getenv(key string) (value string, found bool) { return syscall.Getenv(key) } func Setenv(key, value string) error { return syscall.Setenv(key, value) } func Clearenv() { syscall.Clearenv() } func Environ() []string { return syscall.Environ() } lxd-2.0.11/dist/src/golang.org/x/sys/windows/env_unset.go0000644061062106075000000000050713172163421024375 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // +build go1.4 package windows import "syscall" func Unsetenv(key string) error { // This was added in Go 1.4. return syscall.Unsetenv(key) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/dll_windows.go0000644061062106075000000002557013172163421024723 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package windows import ( "sync" "sync/atomic" "syscall" "unsafe" ) // DLLError describes reasons for DLL load failures. type DLLError struct { Err error ObjName string Msg string } func (e *DLLError) Error() string { return e.Msg } // Implemented in runtime/syscall_windows.goc; we provide jumps to them in our assembly file. func loadlibrary(filename *uint16) (handle uintptr, err syscall.Errno) func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err syscall.Errno) // A DLL implements access to a single DLL. type DLL struct { Name string Handle Handle } // LoadDLL loads DLL file into memory. // // Warning: using LoadDLL without an absolute path name is subject to // DLL preloading attacks. To safely load a system DLL, use LazyDLL // with System set to true, or use LoadLibraryEx directly. func LoadDLL(name string) (dll *DLL, err error) { namep, err := UTF16PtrFromString(name) if err != nil { return nil, err } h, e := loadlibrary(namep) if e != 0 { return nil, &DLLError{ Err: e, ObjName: name, Msg: "Failed to load " + name + ": " + e.Error(), } } d := &DLL{ Name: name, Handle: Handle(h), } return d, nil } // MustLoadDLL is like LoadDLL but panics if load operation failes. func MustLoadDLL(name string) *DLL { d, e := LoadDLL(name) if e != nil { panic(e) } return d } // FindProc searches DLL d for procedure named name and returns *Proc // if found. It returns an error if search fails. func (d *DLL) FindProc(name string) (proc *Proc, err error) { namep, err := BytePtrFromString(name) if err != nil { return nil, err } a, e := getprocaddress(uintptr(d.Handle), namep) if e != 0 { return nil, &DLLError{ Err: e, ObjName: name, Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(), } } p := &Proc{ Dll: d, Name: name, addr: a, } return p, nil } // MustFindProc is like FindProc but panics if search fails. func (d *DLL) MustFindProc(name string) *Proc { p, e := d.FindProc(name) if e != nil { panic(e) } return p } // Release unloads DLL d from memory. func (d *DLL) Release() (err error) { return FreeLibrary(d.Handle) } // A Proc implements access to a procedure inside a DLL. type Proc struct { Dll *DLL Name string addr uintptr } // Addr returns the address of the procedure represented by p. // The return value can be passed to Syscall to run the procedure. func (p *Proc) Addr() uintptr { return p.addr } //go:uintptrescapes // Call executes procedure p with arguments a. It will panic, if more then 15 arguments // are supplied. // // The returned error is always non-nil, constructed from the result of GetLastError. // Callers must inspect the primary return value to decide whether an error occurred // (according to the semantics of the specific function being called) before consulting // the error. The error will be guaranteed to contain windows.Errno. func (p *Proc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) { switch len(a) { case 0: return syscall.Syscall(p.Addr(), uintptr(len(a)), 0, 0, 0) case 1: return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], 0, 0) case 2: return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], 0) case 3: return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], a[2]) case 4: return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], 0, 0) case 5: return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], 0) case 6: return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5]) case 7: return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0) case 8: return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], 0) case 9: return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]) case 10: return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], 0, 0) case 11: return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], 0) case 12: return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]) case 13: return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], 0, 0) case 14: return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], 0) case 15: return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14]) default: panic("Call " + p.Name + " with too many arguments " + itoa(len(a)) + ".") } } // A LazyDLL implements access to a single DLL. // It will delay the load of the DLL until the first // call to its Handle method or to one of its // LazyProc's Addr method. type LazyDLL struct { Name string // System determines whether the DLL must be loaded from the // Windows System directory, bypassing the normal DLL search // path. System bool mu sync.Mutex dll *DLL // non nil once DLL is loaded } // Load loads DLL file d.Name into memory. It returns an error if fails. // Load will not try to load DLL, if it is already loaded into memory. func (d *LazyDLL) Load() error { // Non-racy version of: // if d.dll != nil { if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll))) != nil { return nil } d.mu.Lock() defer d.mu.Unlock() if d.dll != nil { return nil } // kernel32.dll is special, since it's where LoadLibraryEx comes from. // The kernel already special-cases its name, so it's always // loaded from system32. var dll *DLL var err error if d.Name == "kernel32.dll" { dll, err = LoadDLL(d.Name) } else { dll, err = loadLibraryEx(d.Name, d.System) } if err != nil { return err } // Non-racy version of: // d.dll = dll atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll)), unsafe.Pointer(dll)) return nil } // mustLoad is like Load but panics if search fails. func (d *LazyDLL) mustLoad() { e := d.Load() if e != nil { panic(e) } } // Handle returns d's module handle. func (d *LazyDLL) Handle() uintptr { d.mustLoad() return uintptr(d.dll.Handle) } // NewProc returns a LazyProc for accessing the named procedure in the DLL d. func (d *LazyDLL) NewProc(name string) *LazyProc { return &LazyProc{l: d, Name: name} } // NewLazyDLL creates new LazyDLL associated with DLL file. func NewLazyDLL(name string) *LazyDLL { return &LazyDLL{Name: name} } // NewLazySystemDLL is like NewLazyDLL, but will only // search Windows System directory for the DLL if name is // a base name (like "advapi32.dll"). func NewLazySystemDLL(name string) *LazyDLL { return &LazyDLL{Name: name, System: true} } // A LazyProc implements access to a procedure inside a LazyDLL. // It delays the lookup until the Addr method is called. type LazyProc struct { Name string mu sync.Mutex l *LazyDLL proc *Proc } // Find searches DLL for procedure named p.Name. It returns // an error if search fails. Find will not search procedure, // if it is already found and loaded into memory. func (p *LazyProc) Find() error { // Non-racy version of: // if p.proc == nil { if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc))) == nil { p.mu.Lock() defer p.mu.Unlock() if p.proc == nil { e := p.l.Load() if e != nil { return e } proc, e := p.l.dll.FindProc(p.Name) if e != nil { return e } // Non-racy version of: // p.proc = proc atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc)), unsafe.Pointer(proc)) } } return nil } // mustFind is like Find but panics if search fails. func (p *LazyProc) mustFind() { e := p.Find() if e != nil { panic(e) } } // Addr returns the address of the procedure represented by p. // The return value can be passed to Syscall to run the procedure. func (p *LazyProc) Addr() uintptr { p.mustFind() return p.proc.Addr() } //go:uintptrescapes // Call executes procedure p with arguments a. It will panic, if more then 15 arguments // are supplied. // // The returned error is always non-nil, constructed from the result of GetLastError. // Callers must inspect the primary return value to decide whether an error occurred // (according to the semantics of the specific function being called) before consulting // the error. The error will be guaranteed to contain windows.Errno. func (p *LazyProc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) { p.mustFind() return p.proc.Call(a...) } var canDoSearchSystem32Once struct { sync.Once v bool } func initCanDoSearchSystem32() { // https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says: // "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows // Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on // systems that have KB2533623 installed. To determine whether the // flags are available, use GetProcAddress to get the address of the // AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories // function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_* // flags can be used with LoadLibraryEx." canDoSearchSystem32Once.v = (modkernel32.NewProc("AddDllDirectory").Find() == nil) } func canDoSearchSystem32() bool { canDoSearchSystem32Once.Do(initCanDoSearchSystem32) return canDoSearchSystem32Once.v } func isBaseName(name string) bool { for _, c := range name { if c == ':' || c == '/' || c == '\\' { return false } } return true } // loadLibraryEx wraps the Windows LoadLibraryEx function. // // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx // // If name is not an absolute path, LoadLibraryEx searches for the DLL // in a variety of automatic locations unless constrained by flags. // See: https://msdn.microsoft.com/en-us/library/ff919712%28VS.85%29.aspx func loadLibraryEx(name string, system bool) (*DLL, error) { loadDLL := name var flags uintptr if system { if canDoSearchSystem32() { const LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800 flags = LOAD_LIBRARY_SEARCH_SYSTEM32 } else if isBaseName(name) { // WindowsXP or unpatched Windows machine // trying to load "foo.dll" out of the system // folder, but LoadLibraryEx doesn't support // that yet on their system, so emulate it. windir, _ := Getenv("WINDIR") // old var; apparently works on XP if windir == "" { return nil, errString("%WINDIR% not defined") } loadDLL = windir + "\\System32\\" + name } } h, err := LoadLibraryEx(loadDLL, 0, flags) if err != nil { return nil, err } return &DLL{Name: name, Handle: h}, nil } type errString string func (s errString) Error() string { return string(s) } lxd-2.0.11/dist/src/golang.org/x/sys/windows/asm_windows_amd64.s0000644061062106075000000000057513172163421025556 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // System calls for amd64, Windows are implemented in runtime/syscall_windows.goc // TEXT ·getprocaddress(SB), 7, $0-32 JMP syscall·getprocaddress(SB) TEXT ·loadlibrary(SB), 7, $0-8 JMP syscall·loadlibrary(SB) lxd-2.0.11/dist/src/golang.org/x/sys/windows/asm_windows_386.s0000644061062106075000000000057213172163421025160 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // System calls for 386, Windows are implemented in runtime/syscall_windows.goc // TEXT ·getprocaddress(SB), 7, $0-8 JMP syscall·getprocaddress(SB) TEXT ·loadlibrary(SB), 7, $0-4 JMP syscall·loadlibrary(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/0000755061062106075000000000000013172163421021327 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_solaris_amd64.go0000644061062106075000000001510213172163421025742 0ustar stgraberdomain admins// cgo -godefs types_solaris.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,solaris package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x400 MaxHostNameLen = 0x100 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timeval32 struct { Sec int32 Usec int32 } type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Dev uint64 Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint64 Size int64 Atim Timespec Mtim Timespec Ctim Timespec Blksize int32 Pad_cgo_0 [4]byte Blocks int64 Fstype [16]int8 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Sysid int32 Pid int32 Pad [4]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Name [1]int8 Pad_cgo_0 [5]byte } type _Fsblkcnt_t uint64 type Statvfs_t struct { Bsize uint64 Frsize uint64 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Favail uint64 Fsid uint64 Basetype [16]int8 Flag uint64 Namemax uint64 Fstr [32]int8 } type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 X__sin6_src_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrDatalink struct { Family uint16 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [244]int8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [236]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *int8 Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen int32 Pad_cgo_1 [4]byte Accrights *int8 Accrightslen int32 Pad_cgo_2 [4]byte } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { X__icmp6_filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x20 SizeofSockaddrAny = 0xfc SizeofSockaddrUnix = 0x6e SizeofSockaddrDatalink = 0xfc SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x24 SizeofICMPv6Filter = 0x20 ) type FdSet struct { Bits [1024]int64 } type Utsname struct { Sysname [257]int8 Nodename [257]int8 Release [257]int8 Version [257]int8 Machine [257]int8 } type Ustat_t struct { Tfree int64 Tinode uint64 Fname [6]int8 Fpack [6]int8 Pad_cgo_0 [4]byte } const ( AT_FDCWD = 0xffd19553 AT_SYMLINK_NOFOLLOW = 0x1000 AT_SYMLINK_FOLLOW = 0x2000 AT_REMOVEDIR = 0x1 AT_EACCESS = 0x4 ) const ( SizeofIfMsghdr = 0x54 SizeofIfData = 0x44 SizeofIfaMsghdr = 0x14 SizeofRtMsghdr = 0x4c SizeofRtMetrics = 0x28 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Pad_cgo_0 [1]byte Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Lastchange Timeval32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire uint32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x80 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint64 Drop uint64 Capt uint64 Padding [13]uint64 } type BpfProgram struct { Len uint32 Pad_cgo_0 [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfTimeval struct { Sec int32 Usec int32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [19]uint8 Pad_cgo_0 [1]byte } type Termio struct { Iflag uint16 Oflag uint16 Cflag uint16 Lflag uint16 Line int8 Cc [8]uint8 Pad_cgo_0 [1]byte } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_openbsd_arm.go0000644061062106075000000001516213172163421025572 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_openbsd.go // +build arm,openbsd package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int32 } type Timeval struct { Sec int64 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Mode uint32 Dev int32 Ino uint64 Nlink uint32 Uid uint32 Gid uint32 Rdev int32 Atim Timespec Mtim Timespec Ctim Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 X__st_birthtim Timespec } type Statfs_t struct { F_flags uint32 F_bsize uint32 F_iosize uint32 F_blocks uint64 F_bfree uint64 F_bavail int64 F_files uint64 F_ffree uint64 F_favail int64 F_syncwrites uint64 F_syncreads uint64 F_asyncwrites uint64 F_asyncreads uint64 F_fsid Fsid F_namemax uint32 F_owner uint32 F_ctime uint64 F_fstypename [16]uint8 F_mntonname [90]uint8 F_mntfromname [90]uint8 F_mntfromspec [90]uint8 Pad_cgo_0 [2]byte Mount_info [160]byte } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Off int64 Reclen uint16 Type uint8 Namlen uint8 X__d_padding [4]uint8 Name [256]uint8 } type Fsid struct { Val [2]int32 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [24]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x20 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [32]uint32 } const ( SizeofIfMsghdr = 0x98 SizeofIfData = 0x80 SizeofIfaMsghdr = 0x18 SizeofIfAnnounceMsghdr = 0x1a SizeofRtMsghdr = 0x60 SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Pad1 uint8 Pad2 uint8 Addrs int32 Flags int32 Xflags int32 Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Mtu uint32 Metric uint32 Pad uint32 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Capabilities uint32 Lastchange Timeval } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Pad1 uint8 Pad2 uint8 Addrs int32 Flags int32 Metric int32 } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 What uint16 Name [16]uint8 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Priority uint8 Mpls uint8 Addrs int32 Flags int32 Fmask int32 Pid int32 Seq int32 Errno int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Pksent uint64 Expire int64 Locks uint32 Mtu uint32 Refcnt uint32 Hopcount uint32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pad uint32 } type Mclpool struct{} const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type BpfTimeval struct { Sec uint32 Usec uint32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed int32 Ospeed int32 } const ( AT_FDCWD = -0x64 AT_SYMLINK_NOFOLLOW = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_openbsd_amd64.go0000644061062106075000000001555613172163421025735 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_openbsd.go // +build amd64,openbsd package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Mode uint32 Dev int32 Ino uint64 Nlink uint32 Uid uint32 Gid uint32 Rdev int32 Atim Timespec Mtim Timespec Ctim Timespec Size int64 Blocks int64 Blksize uint32 Flags uint32 Gen uint32 Pad_cgo_0 [4]byte X__st_birthtim Timespec } type Statfs_t struct { F_flags uint32 F_bsize uint32 F_iosize uint32 Pad_cgo_0 [4]byte F_blocks uint64 F_bfree uint64 F_bavail int64 F_files uint64 F_ffree uint64 F_favail int64 F_syncwrites uint64 F_syncreads uint64 F_asyncwrites uint64 F_asyncreads uint64 F_fsid Fsid F_namemax uint32 F_owner uint32 F_ctime uint64 F_fstypename [16]int8 F_mntonname [90]int8 F_mntfromname [90]int8 F_mntfromspec [90]int8 Pad_cgo_1 [2]byte Mount_info [160]byte } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Off int64 Reclen uint16 Type uint8 Namlen uint8 X__d_padding [4]uint8 Name [256]int8 } type Fsid struct { Val [2]int32 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [24]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen uint32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x20 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [32]uint32 } const ( SizeofIfMsghdr = 0xf8 SizeofIfData = 0xe0 SizeofIfaMsghdr = 0x18 SizeofIfAnnounceMsghdr = 0x1a SizeofRtMsghdr = 0x60 SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Pad1 uint8 Pad2 uint8 Addrs int32 Flags int32 Xflags int32 Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Mtu uint32 Metric uint32 Pad uint32 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Capabilities uint32 Pad_cgo_0 [4]byte Lastchange Timeval Mclpool [7]Mclpool Pad_cgo_1 [4]byte } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Pad1 uint8 Pad2 uint8 Addrs int32 Flags int32 Metric int32 } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 What uint16 Name [16]int8 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Priority uint8 Mpls uint8 Addrs int32 Flags int32 Fmask int32 Pid int32 Seq int32 Errno int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Pksent uint64 Expire int64 Locks uint32 Mtu uint32 Refcnt uint32 Hopcount uint32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pad uint32 } type Mclpool struct { Grown int32 Alive uint16 Hwm uint16 Cwm uint16 Lwm uint16 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Pad_cgo_0 [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type BpfTimeval struct { Sec uint32 Usec uint32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed int32 Ospeed int32 } const ( AT_FDCWD = -0x64 AT_SYMLINK_NOFOLLOW = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_openbsd_386.go0000644061062106075000000001531513172163421025333 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_openbsd.go // +build 386,openbsd package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int32 } type Timeval struct { Sec int64 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Mode uint32 Dev int32 Ino uint64 Nlink uint32 Uid uint32 Gid uint32 Rdev int32 Atim Timespec Mtim Timespec Ctim Timespec Size int64 Blocks int64 Blksize uint32 Flags uint32 Gen uint32 X__st_birthtim Timespec } type Statfs_t struct { F_flags uint32 F_bsize uint32 F_iosize uint32 F_blocks uint64 F_bfree uint64 F_bavail int64 F_files uint64 F_ffree uint64 F_favail int64 F_syncwrites uint64 F_syncreads uint64 F_asyncwrites uint64 F_asyncreads uint64 F_fsid Fsid F_namemax uint32 F_owner uint32 F_ctime uint64 F_fstypename [16]int8 F_mntonname [90]int8 F_mntfromname [90]int8 F_mntfromspec [90]int8 Pad_cgo_0 [2]byte Mount_info [160]byte } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Off int64 Reclen uint16 Type uint8 Namlen uint8 X__d_padding [4]uint8 Name [256]int8 } type Fsid struct { Val [2]int32 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [24]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x20 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [32]uint32 } const ( SizeofIfMsghdr = 0xec SizeofIfData = 0xd4 SizeofIfaMsghdr = 0x18 SizeofIfAnnounceMsghdr = 0x1a SizeofRtMsghdr = 0x60 SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Pad1 uint8 Pad2 uint8 Addrs int32 Flags int32 Xflags int32 Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Mtu uint32 Metric uint32 Pad uint32 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Capabilities uint32 Lastchange Timeval Mclpool [7]Mclpool } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Pad1 uint8 Pad2 uint8 Addrs int32 Flags int32 Metric int32 } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 What uint16 Name [16]int8 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Hdrlen uint16 Index uint16 Tableid uint16 Priority uint8 Mpls uint8 Addrs int32 Flags int32 Fmask int32 Pid int32 Seq int32 Errno int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Pksent uint64 Expire int64 Locks uint32 Mtu uint32 Refcnt uint32 Hopcount uint32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pad uint32 } type Mclpool struct { Grown int32 Alive uint16 Hwm uint16 Cwm uint16 Lwm uint16 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type BpfTimeval struct { Sec uint32 Usec uint32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed int32 Ospeed int32 } const ( AT_FDCWD = -0x64 AT_SYMLINK_NOFOLLOW = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_netbsd_arm.go0000644061062106075000000001413613172163421025417 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_netbsd.go // +build arm,netbsd package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int32 Pad_cgo_0 [4]byte } type Timeval struct { Sec int64 Usec int32 Pad_cgo_0 [4]byte } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Mode uint32 Pad_cgo_0 [4]byte Ino uint64 Nlink uint32 Uid uint32 Gid uint32 Pad_cgo_1 [4]byte Rdev uint64 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize uint32 Flags uint32 Gen uint32 Spare [2]uint32 Pad_cgo_2 [4]byte } type Statfs_t [0]byte type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Reclen uint16 Namlen uint16 Type uint8 Name [512]int8 Pad_cgo_0 [3]byte } type Fsid struct { X__fsid_val [2]int32 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter uint32 Flags uint32 Fflags uint32 Data int64 Udata int32 Pad_cgo_0 [4]byte } type FdSet struct { Bits [8]uint32 } const ( SizeofIfMsghdr = 0x98 SizeofIfData = 0x88 SizeofIfaMsghdr = 0x18 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x78 SizeofRtMetrics = 0x50 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Pad_cgo_0 [1]byte Link_state int32 Mtu uint64 Metric uint64 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Lastchange Timespec } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Metric int32 Index uint16 Pad_cgo_0 [6]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits int32 Pad_cgo_1 [4]byte Rmx RtMetrics } type RtMetrics struct { Locks uint64 Mtu uint64 Hopcount uint64 Recvpipe uint64 Sendpipe uint64 Ssthresh uint64 Rtt uint64 Rttvar uint64 Expire int64 Pksent int64 } type Mclpool [0]byte const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x80 SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint64 Drop uint64 Capt uint64 Padding [13]uint64 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type BpfTimeval struct { Sec int32 Usec int32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed int32 Ospeed int32 } const ( AT_FDCWD = -0x64 AT_SYMLINK_NOFOLLOW = 0x200 ) type Sysctlnode struct { Flags uint32 Num int32 Name [32]int8 Ver uint32 X__rsvd uint32 Un [16]byte X_sysctl_size [8]byte X_sysctl_func [8]byte X_sysctl_parent [8]byte X_sysctl_desc [8]byte } lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_netbsd_amd64.go0000644061062106075000000001420713172163421025552 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_netbsd.go // +build amd64,netbsd package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int32 Pad_cgo_0 [4]byte } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Mode uint32 Pad_cgo_0 [4]byte Ino uint64 Nlink uint32 Uid uint32 Gid uint32 Pad_cgo_1 [4]byte Rdev uint64 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize uint32 Flags uint32 Gen uint32 Spare [2]uint32 Pad_cgo_2 [4]byte } type Statfs_t [0]byte type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Reclen uint16 Namlen uint16 Type uint8 Name [512]int8 Pad_cgo_0 [3]byte } type Fsid struct { X__fsid_val [2]int32 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter uint32 Flags uint32 Fflags uint32 Pad_cgo_0 [4]byte Data int64 Udata int64 } type FdSet struct { Bits [8]uint32 } const ( SizeofIfMsghdr = 0x98 SizeofIfData = 0x88 SizeofIfaMsghdr = 0x18 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x78 SizeofRtMetrics = 0x50 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Pad_cgo_0 [1]byte Link_state int32 Mtu uint64 Metric uint64 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Lastchange Timespec } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Metric int32 Index uint16 Pad_cgo_0 [6]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits int32 Pad_cgo_1 [4]byte Rmx RtMetrics } type RtMetrics struct { Locks uint64 Mtu uint64 Hopcount uint64 Recvpipe uint64 Sendpipe uint64 Ssthresh uint64 Rtt uint64 Rttvar uint64 Expire int64 Pksent int64 } type Mclpool [0]byte const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x80 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x20 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint64 Drop uint64 Capt uint64 Padding [13]uint64 } type BpfProgram struct { Len uint32 Pad_cgo_0 [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [6]byte } type BpfTimeval struct { Sec int64 Usec int64 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed int32 Ospeed int32 } const ( AT_FDCWD = -0x64 AT_SYMLINK_NOFOLLOW = 0x200 ) type Sysctlnode struct { Flags uint32 Num int32 Name [32]int8 Ver uint32 X__rsvd uint32 Un [16]byte X_sysctl_size [8]byte X_sysctl_func [8]byte X_sysctl_parent [8]byte X_sysctl_desc [8]byte } lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_netbsd_386.go0000644061062106075000000001371513172163421025162 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_netbsd.go // +build 386,netbsd package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int32 } type Timeval struct { Sec int64 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Mode uint32 Ino uint64 Nlink uint32 Uid uint32 Gid uint32 Rdev uint64 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize uint32 Flags uint32 Gen uint32 Spare [2]uint32 } type Statfs_t [0]byte type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Reclen uint16 Namlen uint16 Type uint8 Name [512]int8 Pad_cgo_0 [3]byte } type Fsid struct { X__fsid_val [2]int32 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter uint32 Flags uint32 Fflags uint32 Data int64 Udata int32 } type FdSet struct { Bits [8]uint32 } const ( SizeofIfMsghdr = 0x98 SizeofIfData = 0x84 SizeofIfaMsghdr = 0x18 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x78 SizeofRtMetrics = 0x50 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData Pad_cgo_1 [4]byte } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 Pad_cgo_0 [1]byte Link_state int32 Mtu uint64 Metric uint64 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Lastchange Timespec } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Metric int32 Index uint16 Pad_cgo_0 [6]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits int32 Pad_cgo_1 [4]byte Rmx RtMetrics } type RtMetrics struct { Locks uint64 Mtu uint64 Hopcount uint64 Recvpipe uint64 Sendpipe uint64 Ssthresh uint64 Rtt uint64 Rttvar uint64 Expire int64 Pksent int64 } type Mclpool [0]byte const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x80 SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint64 Drop uint64 Capt uint64 Padding [13]uint64 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp BpfTimeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type BpfTimeval struct { Sec int32 Usec int32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed int32 Ospeed int32 } const ( AT_FDCWD = -0x64 AT_SYMLINK_NOFOLLOW = 0x200 ) type Sysctlnode struct { Flags uint32 Num int32 Name [32]int8 Ver uint32 X__rsvd uint32 Un [16]byte X_sysctl_size [8]byte X_sysctl_func [8]byte X_sysctl_parent [8]byte X_sysctl_desc [8]byte } lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_sparc64.go0000644061062106075000000002626213172163421026005 0ustar stgraberdomain admins// +build sparc64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.go | go run mkpost.go package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int32 Pad_cgo_0 [4]byte } type Timex struct { Modes uint32 Pad_cgo_0 [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 Pad_cgo_1 [4]byte Constant int64 Precision int64 Tolerance int64 Time Timeval Tick int64 Ppsfreq int64 Jitter int64 Shift int32 Pad_cgo_2 [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 Pad_cgo_3 [44]byte } type Time_t int64 type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 X__pad1 uint16 Pad_cgo_0 [6]byte Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint64 X__pad2 uint16 Pad_cgo_1 [6]byte Size int64 Blksize int64 Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec X__glibc_reserved4 uint64 X__glibc_reserved5 uint64 } type Statfs_t struct { Type int64 Bsize int64 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Namelen int64 Frsize int64 Flags int64 Spare [4]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 X__glibc_reserved int16 Pad_cgo_1 [2]byte } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type Cmsghdr struct { Len uint64 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x38 SizeofCmsghdr = 0x10 SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2a RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x10 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [6]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Regs [16]uint64 Tstate uint64 Tpc uint64 Tnpc uint64 Y uint32 Magic uint32 } type ptracePsw struct { } type ptraceFpregs struct { } type ptracePer struct { } type FdSet struct { Bits [16]int64 } type Sysinfo_t struct { Uptime int64 Loads [3]uint64 Totalram uint64 Freeram uint64 Sharedram uint64 Bufferram uint64 Totalswap uint64 Freeswap uint64 Procs uint16 Pad uint16 Pad_cgo_0 [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 X_f [0]int8 Pad_cgo_1 [4]byte } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 Pad_cgo_0 [4]byte Tinode uint64 Fname [6]int8 Fpack [6]int8 Pad_cgo_1 [4]byte } type EpollEvent struct { Events uint32 X_padFd int32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x800 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [16]uint64 } const _SC_PAGESIZE = 0x1e type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_s390x.go0000644061062106075000000003577113172163421025416 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build s390x,linux package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timex struct { Modes uint32 _ [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 _ [4]byte Constant int64 Precision int64 Tolerance int64 Time Timeval Tick int64 Ppsfreq int64 Jitter int64 Shift int32 _ [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 _ [44]byte } type Time_t int64 type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Ino uint64 Nlink uint64 Mode uint32 Uid uint32 Gid uint32 _ int32 Rdev uint64 Size int64 Atim Timespec Mtim Timespec Ctim Timespec Blksize int64 Blocks int64 _ [3]int64 } type Statfs_t struct { Type uint32 Bsize uint32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Namelen uint32 Frsize uint32 Flags uint32 Spare [4]uint32 _ [4]byte } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 _ [5]byte } type Fsid struct { _ [2]int32 } type Flock_t struct { Type int16 Whence int16 _ [4]byte Start int64 Len int64 Pid int32 _ [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x6 FADV_NOREUSE = 0x7 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 _ [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 _ [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 _ [4]byte } type Cmsghdr struct { Len uint64 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x10 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x38 SizeofCmsghdr = 0x10 SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 _ uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x10 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 _ [6]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Psw PtracePsw Gprs [16]uint64 Acrs [16]uint32 Orig_gpr2 uint64 Fp_regs PtraceFpregs Per_info PtracePer Ieee_instruction_pointer uint64 } type PtracePsw struct { Mask uint64 Addr uint64 } type PtraceFpregs struct { Fpc uint32 _ [4]byte Fprs [16]float64 } type PtracePer struct { _ [0]uint64 _ [24]byte _ [8]byte Starting_addr uint64 Ending_addr uint64 Perc_atmid uint16 _ [6]byte Address uint64 Access_id uint8 _ [7]byte } type FdSet struct { Bits [16]int64 } type Sysinfo_t struct { Uptime int64 Loads [3]uint64 Totalram uint64 Freeram uint64 Sharedram uint64 Bufferram uint64 Totalswap uint64 Freeswap uint64 Procs uint16 Pad uint16 _ [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 _ [0]int8 _ [4]byte } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 _ [4]byte Tinode uint64 Fname [6]int8 Fpack [6]int8 _ [4]byte } type EpollEvent struct { Events uint32 _ int32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { _ [16]uint64 } const RNDGETENTCNT = 0x80045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_ppc64le.go0000644061062106075000000003534613172163421026003 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build ppc64le,linux package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timex struct { Modes uint32 Pad_cgo_0 [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 Pad_cgo_1 [4]byte Constant int64 Precision int64 Tolerance int64 Time Timeval Tick int64 Ppsfreq int64 Jitter int64 Shift int32 Pad_cgo_2 [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 Pad_cgo_3 [44]byte } type Time_t int64 type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Ino uint64 Nlink uint64 Mode uint32 Uid uint32 Gid uint32 X__pad2 int32 Rdev uint64 Size int64 Blksize int64 Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec _ uint64 _ uint64 _ uint64 } type Statfs_t struct { Type int64 Bsize int64 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Namelen int64 Frsize int64 Flags int64 Spare [4]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]uint8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]uint8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]uint8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type Cmsghdr struct { Len uint64 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x10 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x38 SizeofCmsghdr = 0x10 SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x10 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [6]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Gpr [32]uint64 Nip uint64 Msr uint64 Orig_gpr3 uint64 Ctr uint64 Link uint64 Xer uint64 Ccr uint64 Softe uint64 Trap uint64 Dar uint64 Dsisr uint64 Result uint64 } type FdSet struct { Bits [16]int64 } type Sysinfo_t struct { Uptime int64 Loads [3]uint64 Totalram uint64 Freeram uint64 Sharedram uint64 Bufferram uint64 Totalswap uint64 Freeswap uint64 Procs uint16 Pad uint16 Pad_cgo_0 [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 X_f [0]uint8 Pad_cgo_1 [4]byte } type Utsname struct { Sysname [65]uint8 Nodename [65]uint8 Release [65]uint8 Version [65]uint8 Machine [65]uint8 Domainname [65]uint8 } type Ustat_t struct { Tfree int32 Pad_cgo_0 [4]byte Tinode uint64 Fname [6]uint8 Fpack [6]uint8 Pad_cgo_1 [4]byte } type EpollEvent struct { Events uint32 X_padFd int32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [16]uint64 } const RNDGETENTCNT = 0x40045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [19]uint8 Line uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]uint8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_ppc64.go0000644061062106075000000003534413172163421025460 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build ppc64,linux package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timex struct { Modes uint32 Pad_cgo_0 [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 Pad_cgo_1 [4]byte Constant int64 Precision int64 Tolerance int64 Time Timeval Tick int64 Ppsfreq int64 Jitter int64 Shift int32 Pad_cgo_2 [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 Pad_cgo_3 [44]byte } type Time_t int64 type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Ino uint64 Nlink uint64 Mode uint32 Uid uint32 Gid uint32 X__pad2 int32 Rdev uint64 Size int64 Blksize int64 Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec _ uint64 _ uint64 _ uint64 } type Statfs_t struct { Type int64 Bsize int64 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Namelen int64 Frsize int64 Flags int64 Spare [4]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]uint8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]uint8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]uint8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type Cmsghdr struct { Len uint64 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x10 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x38 SizeofCmsghdr = 0x10 SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x10 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [6]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Gpr [32]uint64 Nip uint64 Msr uint64 Orig_gpr3 uint64 Ctr uint64 Link uint64 Xer uint64 Ccr uint64 Softe uint64 Trap uint64 Dar uint64 Dsisr uint64 Result uint64 } type FdSet struct { Bits [16]int64 } type Sysinfo_t struct { Uptime int64 Loads [3]uint64 Totalram uint64 Freeram uint64 Sharedram uint64 Bufferram uint64 Totalswap uint64 Freeswap uint64 Procs uint16 Pad uint16 Pad_cgo_0 [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 X_f [0]uint8 Pad_cgo_1 [4]byte } type Utsname struct { Sysname [65]uint8 Nodename [65]uint8 Release [65]uint8 Version [65]uint8 Machine [65]uint8 Domainname [65]uint8 } type Ustat_t struct { Tfree int32 Pad_cgo_0 [4]byte Tinode uint64 Fname [6]uint8 Fpack [6]uint8 Pad_cgo_1 [4]byte } type EpollEvent struct { Events uint32 X_padFd int32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [16]uint64 } const RNDGETENTCNT = 0x40045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [19]uint8 Line uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]uint8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_mipsle.go0000644061062106075000000003475213172163421026017 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build mipsle,linux package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Tai int32 Pad_cgo_0 [44]byte } type Time_t int32 type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 } type Utimbuf struct { Actime int32 Modtime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint32 Pad1 [3]int32 Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint32 Pad2 [3]int32 Size int64 Atim Timespec Mtim Timespec Ctim Timespec Blksize int32 Pad4 int32 Blocks int64 Pad5 [14]int32 } type Statfs_t struct { Type int32 Bsize int32 Frsize int32 Pad_cgo_0 [4]byte Blocks uint64 Bfree uint64 Files uint64 Ffree uint64 Bavail uint64 Fsid Fsid Namelen int32 Flags int32 Spare [5]int32 Pad_cgo_1 [4]byte } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x8 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [2]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Regs [32]uint64 Lo uint64 Hi uint64 Epc uint64 Badvaddr uint64 Status uint64 Cause uint64 } type FdSet struct { Bits [32]int32 } type Sysinfo_t struct { Uptime int32 Loads [3]uint32 Totalram uint32 Freeram uint32 Sharedram uint32 Bufferram uint32 Totalswap uint32 Freeswap uint32 Procs uint16 Pad uint16 Totalhigh uint32 Freehigh uint32 Unit uint32 X_f [8]int8 } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 Tinode uint32 Fname [6]int8 Fpack [6]int8 } type EpollEvent struct { Events uint32 PadFd int32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [32]uint32 } const RNDGETENTCNT = 0x40045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [23]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_mips64le.go0000644061062106075000000003511513172163421026163 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips64le,linux package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timex struct { Modes uint32 Pad_cgo_0 [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 Pad_cgo_1 [4]byte Constant int64 Precision int64 Tolerance int64 Time Timeval Tick int64 Ppsfreq int64 Jitter int64 Shift int32 Pad_cgo_2 [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 Pad_cgo_3 [44]byte } type Time_t int64 type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint32 Pad1 [3]uint32 Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint32 Pad2 [3]uint32 Size int64 Atim Timespec Mtim Timespec Ctim Timespec Blksize uint32 Pad4 uint32 Blocks int64 } type Statfs_t struct { Type int64 Bsize int64 Frsize int64 Blocks uint64 Bfree uint64 Files uint64 Ffree uint64 Bavail uint64 Fsid Fsid Namelen int64 Flags int64 Spare [5]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type Cmsghdr struct { Len uint64 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x10 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x38 SizeofCmsghdr = 0x10 SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x10 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [6]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Regs [32]uint64 Lo uint64 Hi uint64 Epc uint64 Badvaddr uint64 Status uint64 Cause uint64 } type FdSet struct { Bits [16]int64 } type Sysinfo_t struct { Uptime int64 Loads [3]uint64 Totalram uint64 Freeram uint64 Sharedram uint64 Bufferram uint64 Totalswap uint64 Freeswap uint64 Procs uint16 Pad uint16 Pad_cgo_0 [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 X_f [0]int8 Pad_cgo_1 [4]byte } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 Pad_cgo_0 [4]byte Tinode uint64 Fname [6]int8 Fpack [6]int8 Pad_cgo_1 [4]byte } type EpollEvent struct { Events uint32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [16]uint64 } const RNDGETENTCNT = 0x40045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [23]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_mips64.go0000644061062106075000000003511313172163421025640 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips64,linux package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timex struct { Modes uint32 Pad_cgo_0 [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 Pad_cgo_1 [4]byte Constant int64 Precision int64 Tolerance int64 Time Timeval Tick int64 Ppsfreq int64 Jitter int64 Shift int32 Pad_cgo_2 [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 Pad_cgo_3 [44]byte } type Time_t int64 type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint32 Pad1 [3]uint32 Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint32 Pad2 [3]uint32 Size int64 Atim Timespec Mtim Timespec Ctim Timespec Blksize uint32 Pad4 uint32 Blocks int64 } type Statfs_t struct { Type int64 Bsize int64 Frsize int64 Blocks uint64 Bfree uint64 Files uint64 Ffree uint64 Bavail uint64 Fsid Fsid Namelen int64 Flags int64 Spare [5]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type Cmsghdr struct { Len uint64 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x10 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x38 SizeofCmsghdr = 0x10 SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x10 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [6]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Regs [32]uint64 Lo uint64 Hi uint64 Epc uint64 Badvaddr uint64 Status uint64 Cause uint64 } type FdSet struct { Bits [16]int64 } type Sysinfo_t struct { Uptime int64 Loads [3]uint64 Totalram uint64 Freeram uint64 Sharedram uint64 Bufferram uint64 Totalswap uint64 Freeswap uint64 Procs uint16 Pad uint16 Pad_cgo_0 [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 X_f [0]int8 Pad_cgo_1 [4]byte } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 Pad_cgo_0 [4]byte Tinode uint64 Fname [6]int8 Fpack [6]int8 Pad_cgo_1 [4]byte } type EpollEvent struct { Events uint32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [16]uint64 } const RNDGETENTCNT = 0x40045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [23]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_mips.go0000644061062106075000000003475013172163421025474 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips,linux package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Tai int32 Pad_cgo_0 [44]byte } type Time_t int32 type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 } type Utimbuf struct { Actime int32 Modtime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint32 Pad1 [3]int32 Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint32 Pad2 [3]int32 Size int64 Atim Timespec Mtim Timespec Ctim Timespec Blksize int32 Pad4 int32 Blocks int64 Pad5 [14]int32 } type Statfs_t struct { Type int32 Bsize int32 Frsize int32 Pad_cgo_0 [4]byte Blocks uint64 Bfree uint64 Files uint64 Ffree uint64 Bavail uint64 Fsid Fsid Namelen int32 Flags int32 Spare [5]int32 Pad_cgo_1 [4]byte } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x8 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [2]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Regs [32]uint64 Lo uint64 Hi uint64 Epc uint64 Badvaddr uint64 Status uint64 Cause uint64 } type FdSet struct { Bits [32]int32 } type Sysinfo_t struct { Uptime int32 Loads [3]uint32 Totalram uint32 Freeram uint32 Sharedram uint32 Bufferram uint32 Totalswap uint32 Freeswap uint32 Procs uint16 Pad uint16 Totalhigh uint32 Freehigh uint32 Unit uint32 X_f [8]int8 } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 Tinode uint32 Fname [6]int8 Fpack [6]int8 } type EpollEvent struct { Events uint32 PadFd int32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [32]uint32 } const RNDGETENTCNT = 0x40045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [23]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_arm64.go0000644061062106075000000003504513172163421025453 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm64,linux package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timex struct { Modes uint32 Pad_cgo_0 [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 Pad_cgo_1 [4]byte Constant int64 Precision int64 Tolerance int64 Time Timeval Tick int64 Ppsfreq int64 Jitter int64 Shift int32 Pad_cgo_2 [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 Pad_cgo_3 [44]byte } type Time_t int64 type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint64 X__pad1 uint64 Size int64 Blksize int32 X__pad2 int32 Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec _ [2]int32 } type Statfs_t struct { Type int64 Bsize int64 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Namelen int64 Frsize int64 Flags int64 Spare [4]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type Cmsghdr struct { Len uint64 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x10 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x38 SizeofCmsghdr = 0x10 SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x10 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [6]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Regs [31]uint64 Sp uint64 Pc uint64 Pstate uint64 } type FdSet struct { Bits [16]int64 } type Sysinfo_t struct { Uptime int64 Loads [3]uint64 Totalram uint64 Freeram uint64 Sharedram uint64 Bufferram uint64 Totalswap uint64 Freeswap uint64 Procs uint16 Pad uint16 Pad_cgo_0 [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 X_f [0]int8 Pad_cgo_1 [4]byte } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 Pad_cgo_0 [4]byte Tinode uint64 Fname [6]int8 Fpack [6]int8 Pad_cgo_1 [4]byte } type EpollEvent struct { Events uint32 PadFd int32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [16]uint64 } const RNDGETENTCNT = 0x80045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_arm.go0000644061062106075000000003467313172163421025307 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,linux package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Tai int32 Pad_cgo_0 [44]byte } type Time_t int32 type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 } type Utimbuf struct { Actime int32 Modtime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 X__pad1 uint16 Pad_cgo_0 [2]byte X__st_ino uint32 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint64 X__pad2 uint16 Pad_cgo_1 [6]byte Size int64 Blksize int32 Pad_cgo_2 [4]byte Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec Ino uint64 } type Statfs_t struct { Type int32 Bsize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Namelen int32 Frsize int32 Flags int32 Spare [4]int32 Pad_cgo_0 [4]byte } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]uint8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]uint8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]uint8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x8 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [2]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Uregs [18]uint32 } type FdSet struct { Bits [32]int32 } type Sysinfo_t struct { Uptime int32 Loads [3]uint32 Totalram uint32 Freeram uint32 Sharedram uint32 Bufferram uint32 Totalswap uint32 Freeswap uint32 Procs uint16 Pad uint16 Totalhigh uint32 Freehigh uint32 Unit uint32 X_f [8]uint8 } type Utsname struct { Sysname [65]uint8 Nodename [65]uint8 Release [65]uint8 Version [65]uint8 Machine [65]uint8 Domainname [65]uint8 } type Ustat_t struct { Tfree int32 Tinode uint32 Fname [6]uint8 Fpack [6]uint8 } type EpollEvent struct { Events uint32 PadFd int32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [32]uint32 } const RNDGETENTCNT = 0x80045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]uint8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_amd64.go0000644061062106075000000003561113172163421025434 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m64 linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,linux package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Timex struct { Modes uint32 Pad_cgo_0 [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 Pad_cgo_1 [4]byte Constant int64 Precision int64 Tolerance int64 Time Timeval Tick int64 Ppsfreq int64 Jitter int64 Shift int32 Pad_cgo_2 [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 Pad_cgo_3 [44]byte } type Time_t int64 type Tms struct { Utime int64 Stime int64 Cutime int64 Cstime int64 } type Utimbuf struct { Actime int64 Modtime int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 Ino uint64 Nlink uint64 Mode uint32 Uid uint32 Gid uint32 X__pad0 int32 Rdev uint64 Size int64 Blksize int64 Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec _ [3]int64 } type Statfs_t struct { Type int64 Bsize int64 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Namelen int64 Frsize int64 Flags int64 Spare [4]int64 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 Pad_cgo_0 [5]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Pad_cgo_0 [4]byte Start int64 Len int64 Pid int32 Pad_cgo_1 [4]byte } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type Cmsghdr struct { Len uint64 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x10 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x38 SizeofCmsghdr = 0x10 SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x10 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [6]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { R15 uint64 R14 uint64 R13 uint64 R12 uint64 Rbp uint64 Rbx uint64 R11 uint64 R10 uint64 R9 uint64 R8 uint64 Rax uint64 Rcx uint64 Rdx uint64 Rsi uint64 Rdi uint64 Orig_rax uint64 Rip uint64 Cs uint64 Eflags uint64 Rsp uint64 Ss uint64 Fs_base uint64 Gs_base uint64 Ds uint64 Es uint64 Fs uint64 Gs uint64 } type FdSet struct { Bits [16]int64 } type Sysinfo_t struct { Uptime int64 Loads [3]uint64 Totalram uint64 Freeram uint64 Sharedram uint64 Bufferram uint64 Totalswap uint64 Freeswap uint64 Procs uint16 Pad uint16 Pad_cgo_0 [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 X_f [0]int8 Pad_cgo_1 [4]byte } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 Pad_cgo_0 [4]byte Tinode uint64 Fname [6]int8 Fpack [6]int8 Pad_cgo_1 [4]byte } type EpollEvent struct { Events uint32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [16]uint64 } const RNDGETENTCNT = 0x80045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_linux_386.go0000644061062106075000000003506013172163421025037 0ustar stgraberdomain admins// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m32 linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,linux package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Tai int32 Pad_cgo_0 [44]byte } type Time_t int32 type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 } type Utimbuf struct { Actime int32 Modtime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev uint64 X__pad1 uint16 Pad_cgo_0 [2]byte X__st_ino uint32 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint64 X__pad2 uint16 Pad_cgo_1 [2]byte Size int64 Blksize int32 Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec Ino uint64 } type Statfs_t struct { Type int32 Bsize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Namelen int32 Frsize int32 Flags int32 Spare [4]int32 } type Dirent struct { Ino uint64 Off int64 Reclen uint16 Type uint8 Name [256]int8 Pad_cgo_0 [1]byte } type Fsid struct { X__val [2]int32 } type Flock_t struct { Type int16 Whence int16 Start int64 Len int64 Pid int32 } type FscryptPolicy struct { Version uint8 Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 Master_key_descriptor [8]uint8 } type FscryptKey struct { Mode uint32 Raw [64]uint8 Size uint32 } type KeyctlDHParams struct { Private int32 Prime int32 Base int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Family uint16 Path [108]int8 } type RawSockaddrLinklayer struct { Family uint16 Protocol uint16 Ifindex int32 Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]uint8 } type RawSockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 } type RawSockaddrHCI struct { Family uint16 Dev uint16 Channel uint16 } type RawSockaddrCAN struct { Family uint16 Pad_cgo_0 [2]byte Ifindex int32 Addr [8]byte } type RawSockaddrALG struct { Family uint16 Type [14]uint8 Feat uint32 Mask uint32 Name [64]uint8 } type RawSockaddrVM struct { Family uint16 Reserved1 uint16 Port uint32 Cid uint32 Zero [4]uint8 } type RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type PacketMreq struct { Ifindex int32 Type uint16 Alen uint16 Address [8]uint8 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Data [8]uint32 } type Ucred struct { Pid int32 Uid uint32 Gid uint32 } type TCPInfo struct { State uint8 Ca_state uint8 Retransmits uint8 Probes uint8 Backoff uint8 Options uint8 Pad_cgo_0 [2]byte Rto uint32 Ato uint32 Snd_mss uint32 Rcv_mss uint32 Unacked uint32 Sacked uint32 Lost uint32 Retrans uint32 Fackets uint32 Last_data_sent uint32 Last_ack_sent uint32 Last_data_recv uint32 Last_ack_recv uint32 Pmtu uint32 Rcv_ssthresh uint32 Rtt uint32 Rttvar uint32 Snd_ssthresh uint32 Snd_cwnd uint32 Advmss uint32 Reordering uint32 Rcv_rtt uint32 Rcv_space uint32 Total_retrans uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x70 SizeofSockaddrUnix = 0x6e SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 SizeofLinger = 0x8 SizeofIovec = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofPacketMreq = 0x10 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x2c RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x8 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [2]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 } const SizeofInotifyEvent = 0x10 type PtraceRegs struct { Ebx int32 Ecx int32 Edx int32 Esi int32 Edi int32 Ebp int32 Eax int32 Xds int32 Xes int32 Xfs int32 Xgs int32 Orig_eax int32 Eip int32 Xcs int32 Eflags int32 Esp int32 Xss int32 } type FdSet struct { Bits [32]int32 } type Sysinfo_t struct { Uptime int32 Loads [3]uint32 Totalram uint32 Freeram uint32 Sharedram uint32 Bufferram uint32 Totalswap uint32 Freeswap uint32 Procs uint16 Pad uint16 Totalhigh uint32 Freehigh uint32 Unit uint32 X_f [8]int8 } type Utsname struct { Sysname [65]int8 Nodename [65]int8 Release [65]int8 Version [65]int8 Machine [65]int8 Domainname [65]int8 } type Ustat_t struct { Tfree int32 Tinode uint32 Fname [6]int8 Fpack [6]int8 } type EpollEvent struct { Events uint32 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLIN = 0x1 POLLPRI = 0x2 POLLOUT = 0x4 POLLRDHUP = 0x2000 POLLERR = 0x8 POLLHUP = 0x10 POLLNVAL = 0x20 ) type Sigset_t struct { X__val [32]uint32 } const RNDGETENTCNT = 0x80045200 const PERF_IOC_FLAG_GROUP = 0x1 type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type Taskstats struct { Version uint16 Pad_cgo_0 [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 Pad_cgo_1 [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 Blkio_delay_total uint64 Swapin_count uint64 Swapin_delay_total uint64 Cpu_run_real_total uint64 Cpu_run_virtual_total uint64 Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 Pad_cgo_2 [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 Pad_cgo_3 [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 Ac_minflt uint64 Ac_majflt uint64 Coremem uint64 Virtmem uint64 Hiwater_rss uint64 Hiwater_vm uint64 Read_char uint64 Write_char uint64 Read_syscalls uint64 Write_syscalls uint64 Read_bytes uint64 Write_bytes uint64 Cancelled_write_bytes uint64 Nvcsw uint64 Nivcsw uint64 Ac_utimescaled uint64 Ac_stimescaled uint64 Cpu_scaled_run_real_total uint64 Freepages_count uint64 Freepages_delay_total uint64 } const ( TASKSTATS_CMD_UNSPEC = 0x0 TASKSTATS_CMD_GET = 0x1 TASKSTATS_CMD_NEW = 0x2 TASKSTATS_TYPE_UNSPEC = 0x0 TASKSTATS_TYPE_PID = 0x1 TASKSTATS_TYPE_TGID = 0x2 TASKSTATS_TYPE_STATS = 0x3 TASKSTATS_TYPE_AGGR_PID = 0x4 TASKSTATS_TYPE_AGGR_TGID = 0x5 TASKSTATS_TYPE_NULL = 0x6 TASKSTATS_CMD_ATTR_UNSPEC = 0x0 TASKSTATS_CMD_ATTR_PID = 0x1 TASKSTATS_CMD_ATTR_TGID = 0x2 TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) type Genlmsghdr struct { Cmd uint8 Version uint8 Reserved uint16 } const ( CTRL_CMD_UNSPEC = 0x0 CTRL_CMD_NEWFAMILY = 0x1 CTRL_CMD_DELFAMILY = 0x2 CTRL_CMD_GETFAMILY = 0x3 CTRL_CMD_NEWOPS = 0x4 CTRL_CMD_DELOPS = 0x5 CTRL_CMD_GETOPS = 0x6 CTRL_CMD_NEWMCAST_GRP = 0x7 CTRL_CMD_DELMCAST_GRP = 0x8 CTRL_CMD_GETMCAST_GRP = 0x9 CTRL_ATTR_UNSPEC = 0x0 CTRL_ATTR_FAMILY_ID = 0x1 CTRL_ATTR_FAMILY_NAME = 0x2 CTRL_ATTR_VERSION = 0x3 CTRL_ATTR_HDRSIZE = 0x4 CTRL_ATTR_MAXATTR = 0x5 CTRL_ATTR_OPS = 0x6 CTRL_ATTR_MCAST_GROUPS = 0x7 CTRL_ATTR_OP_UNSPEC = 0x0 CTRL_ATTR_OP_ID = 0x1 CTRL_ATTR_OP_FLAGS = 0x2 CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_freebsd_arm.go0000644061062106075000000002045513172163421025553 0ustar stgraberdomain admins// cgo -godefs -- -fsigned-char types_freebsd.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,freebsd package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int32 Pad_cgo_0 [4]byte } type Timeval struct { Sec int64 Usec int32 Pad_cgo_0 [4]byte } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur int64 Max int64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Dev uint32 Ino uint32 Mode uint16 Nlink uint16 Uid uint32 Gid uint32 Rdev uint32 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Birthtimespec Timespec } type Statfs_t struct { Version uint32 Type uint32 Flags uint64 Bsize uint64 Iosize uint64 Blocks uint64 Bfree uint64 Bavail int64 Files uint64 Ffree int64 Syncwrites uint64 Asyncwrites uint64 Syncreads uint64 Asyncreads uint64 Spare [10]uint64 Namemax uint32 Owner uint32 Fsid Fsid Charspare [80]int8 Fstypename [16]int8 Mntfromname [88]int8 Mntonname [88]int8 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 Sysid int32 Pad_cgo_0 [4]byte } type Dirent struct { Fileno uint32 Reclen uint16 Type uint8 Namlen uint8 Name [256]int8 } type Fsid struct { Val [2]int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [46]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x36 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter int16 Flags uint16 Fflags uint32 Data int32 Udata *byte } type FdSet struct { X__fds_bits [32]uint32 } const ( sizeofIfMsghdr = 0xa8 SizeofIfMsghdr = 0x70 sizeofIfData = 0x98 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type ifMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data ifData } type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type ifData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Vhid uint8 Datalen uint16 Mtu uint32 Metric uint32 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Oqdrops uint64 Noproto uint64 Hwassist uint64 X__ifi_epoch [8]byte X__ifi_lastchange [16]byte } type IfData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Spare_char1 uint8 Spare_char2 uint8 Datalen uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Hwassist uint32 Pad_cgo_0 [4]byte Epoch int64 Lastchange Timeval } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Fmask int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire uint32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Weight uint32 Filler [3]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfZbuf = 0xc SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x20 SizeofBpfZbufHeader = 0x20 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfZbuf struct { Bufa *byte Bufb *byte Buflen uint32 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [6]byte } type BpfZbufHeader struct { Kernel_gen uint32 Kernel_len uint32 User_gen uint32 X_bzh_pad [5]uint32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x800 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x200 ) type CapRights struct { Rights [2]uint64 } lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_freebsd_amd64.go0000644061062106075000000002042413172163421025703 0ustar stgraberdomain admins// cgo -godefs types_freebsd.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,freebsd package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur int64 Max int64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Dev uint32 Ino uint32 Mode uint16 Nlink uint16 Uid uint32 Gid uint32 Rdev uint32 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Birthtimespec Timespec } type Statfs_t struct { Version uint32 Type uint32 Flags uint64 Bsize uint64 Iosize uint64 Blocks uint64 Bfree uint64 Bavail int64 Files uint64 Ffree int64 Syncwrites uint64 Asyncwrites uint64 Syncreads uint64 Asyncreads uint64 Spare [10]uint64 Namemax uint32 Owner uint32 Fsid Fsid Charspare [80]int8 Fstypename [16]int8 Mntfromname [88]int8 Mntonname [88]int8 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 Sysid int32 Pad_cgo_0 [4]byte } type Dirent struct { Fileno uint32 Reclen uint16 Type uint8 Namlen uint8 Name [256]int8 } type Fsid struct { Val [2]int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [46]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x36 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { X__fds_bits [16]uint64 } const ( sizeofIfMsghdr = 0xa8 SizeofIfMsghdr = 0xa8 sizeofIfData = 0x98 SizeofIfData = 0x98 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x98 SizeofRtMetrics = 0x70 ) type ifMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data ifData } type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type ifData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Vhid uint8 Datalen uint16 Mtu uint32 Metric uint32 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Oqdrops uint64 Noproto uint64 Hwassist uint64 X__ifi_epoch [8]byte X__ifi_lastchange [16]byte } type IfData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Spare_char1 uint8 Spare_char2 uint8 Datalen uint8 Mtu uint64 Metric uint64 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Hwassist uint64 Epoch int64 Lastchange Timeval } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Fmask int32 Inits uint64 Rmx RtMetrics } type RtMetrics struct { Locks uint64 Mtu uint64 Hopcount uint64 Expire uint64 Recvpipe uint64 Sendpipe uint64 Ssthresh uint64 Rtt uint64 Rttvar uint64 Pksent uint64 Weight uint64 Filler [3]uint64 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfZbuf = 0x18 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x20 SizeofBpfZbufHeader = 0x20 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfZbuf struct { Bufa *byte Bufb *byte Buflen uint64 } type BpfProgram struct { Len uint32 Pad_cgo_0 [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [6]byte } type BpfZbufHeader struct { Kernel_gen uint32 Kernel_len uint32 User_gen uint32 X_bzh_pad [5]uint32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x800 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x200 ) type CapRights struct { Rights [2]uint64 } lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_freebsd_386.go0000644061062106075000000002027713172163421025316 0ustar stgraberdomain admins// cgo -godefs types_freebsd.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,freebsd package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur int64 Max int64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Dev uint32 Ino uint32 Mode uint16 Nlink uint16 Uid uint32 Gid uint32 Rdev uint32 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Birthtimespec Timespec Pad_cgo_0 [8]byte } type Statfs_t struct { Version uint32 Type uint32 Flags uint64 Bsize uint64 Iosize uint64 Blocks uint64 Bfree uint64 Bavail int64 Files uint64 Ffree int64 Syncwrites uint64 Asyncwrites uint64 Syncreads uint64 Asyncreads uint64 Spare [10]uint64 Namemax uint32 Owner uint32 Fsid Fsid Charspare [80]int8 Fstypename [16]int8 Mntfromname [88]int8 Mntonname [88]int8 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 Sysid int32 } type Dirent struct { Fileno uint32 Reclen uint16 Type uint8 Namlen uint8 Name [256]int8 } type Fsid struct { Val [2]int32 } const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [46]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x36 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter int16 Flags uint16 Fflags uint32 Data int32 Udata *byte } type FdSet struct { X__fds_bits [32]uint32 } const ( sizeofIfMsghdr = 0xa8 SizeofIfMsghdr = 0x60 sizeofIfData = 0x98 SizeofIfData = 0x50 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type ifMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data ifData } type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type ifData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Vhid uint8 Datalen uint16 Mtu uint32 Metric uint32 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Oqdrops uint64 Noproto uint64 Hwassist uint64 X__ifi_epoch [8]byte X__ifi_lastchange [16]byte } type IfData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Spare_char1 uint8 Spare_char2 uint8 Datalen uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Hwassist uint32 Epoch int32 Lastchange Timeval } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Fmask int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire uint32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Weight uint32 Filler [3]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfZbuf = 0xc SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 SizeofBpfZbufHeader = 0x20 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfZbuf struct { Bufa *byte Bufb *byte Buflen uint32 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type BpfZbufHeader struct { Kernel_gen uint32 Kernel_len uint32 User_gen uint32 X_bzh_pad [5]uint32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x800 AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x200 ) type CapRights struct { Rights [2]uint64 } lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go0000644061062106075000000001533713172163421026265 0ustar stgraberdomain admins// cgo -godefs types_dragonfly.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,dragonfly package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur int64 Max int64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Ino uint64 Nlink uint32 Dev uint32 Mode uint16 Padding1 uint16 Uid uint32 Gid uint32 Rdev uint32 Atim Timespec Mtim Timespec Ctim Timespec Size int64 Blocks int64 Blksize uint32 Flags uint32 Gen uint32 Lspare int32 Qspare1 int64 Qspare2 int64 } type Statfs_t struct { Spare2 int64 Bsize int64 Iosize int64 Blocks int64 Bfree int64 Bavail int64 Files int64 Ffree int64 Fsid Fsid Owner uint32 Type int32 Flags int32 Pad_cgo_0 [4]byte Syncwrites int64 Asyncwrites int64 Fstypename [16]int8 Mntonname [80]int8 Syncreads int64 Asyncreads int64 Spares1 int16 Mntfromname [80]int8 Spares2 int16 Pad_cgo_1 [4]byte Spare [2]int64 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Namlen uint16 Type uint8 Unused1 uint8 Unused2 uint32 Name [256]int8 } type Fsid struct { Val [2]int32 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 Rcf uint16 Route [16]uint16 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x36 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [16]uint64 } const ( SizeofIfMsghdr = 0xb0 SizeofIfData = 0xa0 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x98 SizeofRtMetrics = 0x70 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Pad_cgo_0 [2]byte Mtu uint64 Metric uint64 Link_state uint64 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Hwassist uint64 Oqdrops uint64 Lastchange Timeval } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint64 Rmx RtMetrics } type RtMetrics struct { Locks uint64 Mtu uint64 Pksent uint64 Expire uint64 Sendpipe uint64 Ssthresh uint64 Rtt uint64 Rttvar uint64 Recvpipe uint64 Hopcount uint64 Mssopt uint16 Pad uint16 Pad_cgo_0 [4]byte Msl uint64 Iwmaxsegs uint64 Iwcapsegs uint64 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x20 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Pad_cgo_0 [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [6]byte } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } const ( AT_FDCWD = 0xfffafdcd AT_SYMLINK_NOFOLLOW = 0x1 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_darwin_arm64.go0000644061062106075000000001612713172163421025600 0ustar stgraberdomain admins// +build arm64,darwin // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_darwin.go package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int32 Pad_cgo_0 [4]byte } type Timeval32 struct { Sec int32 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 Pad_cgo_0 [4]byte Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 } type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 } type Radvisory_t struct { Offset int64 Count int32 Pad_cgo_0 [4]byte } type Fbootstraptransfer_t struct { Offset int64 Length uint64 Buffer *byte } type Log2phys_t struct { Flags uint32 Pad_cgo_0 [8]byte Pad_cgo_1 [8]byte } type Fsid struct { Val [2]int32 } type Dirent struct { Ino uint64 Seekoff uint64 Reclen uint16 Namlen uint16 Type uint8 Name [1024]int8 Pad_cgo_0 [3]byte } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [32]int32 } const ( SizeofIfMsghdr = 0x70 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Typelen uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Unused1 uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Recvtiming uint32 Xmittiming uint32 Lastchange Timeval32 Unused2 uint32 Hwassist uint32 Reserved1 uint32 Reserved2 uint32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte } type IfmaMsghdr2 struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Refcount int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire int32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Filler [4]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Pad_cgo_0 [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval32 Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type Termios struct { Iflag uint64 Oflag uint64 Cflag uint64 Lflag uint64 Cc [20]uint8 Pad_cgo_0 [4]byte Ispeed uint64 Ospeed uint64 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x80 AT_SYMLINK_FOLLOW = 0x40 AT_SYMLINK_NOFOLLOW = 0x20 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_darwin_arm.go0000644061062106075000000001570213172163421025424 0ustar stgraberdomain admins// NOTE: cgo can't generate struct Stat_t and struct Statfs_t yet // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_darwin.go // +build arm,darwin package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timeval32 [0]byte type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 } type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 } type Radvisory_t struct { Offset int64 Count int32 } type Fbootstraptransfer_t struct { Offset int64 Length uint32 Buffer *byte } type Log2phys_t struct { Flags uint32 Contigbytes int64 Devoffset int64 } type Fsid struct { Val [2]int32 } type Dirent struct { Ino uint64 Seekoff uint64 Reclen uint16 Namlen uint16 Type uint8 Name [1024]int8 Pad_cgo_0 [3]byte } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter int16 Flags uint16 Fflags uint32 Data int32 Udata *byte } type FdSet struct { Bits [32]int32 } const ( SizeofIfMsghdr = 0x70 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Typelen uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Unused1 uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Recvtiming uint32 Xmittiming uint32 Lastchange Timeval Unused2 uint32 Hwassist uint32 Reserved1 uint32 Reserved2 uint32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte } type IfmaMsghdr2 struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Refcount int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire int32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Filler [4]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x80 AT_SYMLINK_FOLLOW = 0x40 AT_SYMLINK_NOFOLLOW = 0x20 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_darwin_amd64.go0000644061062106075000000001620713172163421025561 0ustar stgraberdomain admins// cgo -godefs types_darwin.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,darwin package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int32 Pad_cgo_0 [4]byte } type Timeval32 struct { Sec int32 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 Pad_cgo_0 [4]byte Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 } type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 } type Radvisory_t struct { Offset int64 Count int32 Pad_cgo_0 [4]byte } type Fbootstraptransfer_t struct { Offset int64 Length uint64 Buffer *byte } type Log2phys_t struct { Flags uint32 Pad_cgo_0 [8]byte Pad_cgo_1 [8]byte } type Fsid struct { Val [2]int32 } type Dirent struct { Ino uint64 Seekoff uint64 Reclen uint16 Namlen uint16 Type uint8 Name [1024]int8 Pad_cgo_0 [3]byte } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *Iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [32]int32 } const ( SizeofIfMsghdr = 0x70 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Typelen uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Unused1 uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Recvtiming uint32 Xmittiming uint32 Lastchange Timeval32 Unused2 uint32 Hwassist uint32 Reserved1 uint32 Reserved2 uint32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte } type IfmaMsghdr2 struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Refcount int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire int32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Filler [4]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Pad_cgo_0 [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval32 Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type Termios struct { Iflag uint64 Oflag uint64 Cflag uint64 Lflag uint64 Cc [20]uint8 Pad_cgo_0 [4]byte Ispeed uint64 Ospeed uint64 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x80 AT_SYMLINK_FOLLOW = 0x40 AT_SYMLINK_NOFOLLOW = 0x20 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/ztypes_darwin_386.go0000644061062106075000000001566013172163421025170 0ustar stgraberdomain admins// cgo -godefs types_darwin.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,darwin package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timeval32 struct{} type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 } type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 } type Radvisory_t struct { Offset int64 Count int32 } type Fbootstraptransfer_t struct { Offset int64 Length uint32 Buffer *byte } type Log2phys_t struct { Flags uint32 Contigbytes int64 Devoffset int64 } type Fsid struct { Val [2]int32 } type Dirent struct { Ino uint64 Seekoff uint64 Reclen uint16 Namlen uint16 Type uint8 Name [1024]int8 Pad_cgo_0 [3]byte } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter int16 Flags uint16 Fflags uint32 Data int32 Udata *byte } type FdSet struct { Bits [32]int32 } const ( SizeofIfMsghdr = 0x70 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Data IfData } type IfData struct { Type uint8 Typelen uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Unused1 uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Recvtiming uint32 Xmittiming uint32 Lastchange Timeval Unused2 uint32 Hwassist uint32 Reserved1 uint32 Reserved2 uint32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte } type IfmaMsghdr2 struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Pad_cgo_0 [2]byte Refcount int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Pad_cgo_0 [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire int32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Filler [4]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 Pad_cgo_0 [2]byte } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x80 AT_SYMLINK_FOLLOW = 0x40 AT_SYMLINK_NOFOLLOW = 0x20 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_solaris_amd64.go0000644061062106075000000000043613172163421026140 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,solaris package unix // TODO(aram): remove these before Go 1.3. const ( SYS_EXECVE = 59 SYS_FCNTL = 62 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_openbsd_arm.go0000644061062106075000000003472113172163421025766 0ustar stgraberdomain admins// mksysnum_openbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build arm,openbsd package unix const ( SYS_EXIT = 1 // { void sys_exit(int rval); } SYS_FORK = 2 // { int sys_fork(void); } SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \ SYS_OPEN = 5 // { int sys_open(const char *path, \ SYS_CLOSE = 6 // { int sys_close(int fd); } SYS_GETENTROPY = 7 // { int sys_getentropy(void *buf, size_t nbyte); } SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \ SYS_LINK = 9 // { int sys_link(const char *path, const char *link); } SYS_UNLINK = 10 // { int sys_unlink(const char *path); } SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \ SYS_CHDIR = 12 // { int sys_chdir(const char *path); } SYS_FCHDIR = 13 // { int sys_fchdir(int fd); } SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \ SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); } SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \ SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); } SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \ SYS_GETPID = 20 // { pid_t sys_getpid(void); } SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \ SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); } SYS_SETUID = 23 // { int sys_setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t sys_getuid(void); } SYS_GETEUID = 25 // { uid_t sys_geteuid(void); } SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \ SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \ SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \ SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \ SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \ SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \ SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \ SYS_ACCESS = 33 // { int sys_access(const char *path, int amode); } SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); } SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); } SYS_SYNC = 36 // { void sys_sync(void); } SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); } SYS_GETPPID = 39 // { pid_t sys_getppid(void); } SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); } SYS_DUP = 41 // { int sys_dup(int fd); } SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \ SYS_GETEGID = 43 // { gid_t sys_getegid(void); } SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \ SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \ SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \ SYS_GETGID = 47 // { gid_t sys_getgid(void); } SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); } SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); } SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); } SYS_ACCT = 51 // { int sys_acct(const char *path); } SYS_SIGPENDING = 52 // { int sys_sigpending(void); } SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); } SYS_IOCTL = 54 // { int sys_ioctl(int fd, \ SYS_REBOOT = 55 // { int sys_reboot(int opt); } SYS_REVOKE = 56 // { int sys_revoke(const char *path); } SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \ SYS_READLINK = 58 // { ssize_t sys_readlink(const char *path, \ SYS_EXECVE = 59 // { int sys_execve(const char *path, \ SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); } SYS_CHROOT = 61 // { int sys_chroot(const char *path); } SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \ SYS_STATFS = 63 // { int sys_statfs(const char *path, \ SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); } SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \ SYS_VFORK = 66 // { int sys_vfork(void); } SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \ SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \ SYS_SETITIMER = 69 // { int sys_setitimer(int which, \ SYS_GETITIMER = 70 // { int sys_getitimer(int which, \ SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \ SYS_KEVENT = 72 // { int sys_kevent(int fd, \ SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \ SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \ SYS_UTIMES = 76 // { int sys_utimes(const char *path, \ SYS_FUTIMES = 77 // { int sys_futimes(int fd, \ SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, \ SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \ SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \ SYS_GETPGRP = 81 // { int sys_getpgrp(void); } SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, pid_t pgid); } SYS_SENDSYSLOG = 83 // { int sys_sendsyslog(const void *buf, size_t nbyte); } SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \ SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \ SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \ SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \ SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \ SYS_DUP2 = 90 // { int sys_dup2(int from, int to); } SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \ SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); } SYS_ACCEPT4 = 93 // { int sys_accept4(int s, struct sockaddr *name, \ SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \ SYS_FSYNC = 95 // { int sys_fsync(int fd); } SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); } SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); } SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \ SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); } SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); } SYS_PIPE2 = 101 // { int sys_pipe2(int *fdp, int flags); } SYS_DUP3 = 102 // { int sys_dup3(int from, int to, int flags); } SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); } SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \ SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \ SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); } SYS_CHFLAGSAT = 107 // { int sys_chflagsat(int fd, const char *path, \ SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \ SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \ SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); } SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \ SYS_READV = 120 // { ssize_t sys_readv(int fd, \ SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \ SYS_KILL = 122 // { int sys_kill(int pid, int signum); } SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); } SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); } SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); } SYS_FLOCK = 131 // { int sys_flock(int fd, int how); } SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); } SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \ SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \ SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int sys_rmdir(const char *path); } SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \ SYS_SETSID = 147 // { int sys_setsid(void); } SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \ SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); } SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); } SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); } SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \ SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \ SYS_SETGID = 181 // { int sys_setgid(gid_t gid); } SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); } SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); } SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); } SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); } SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); } SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \ SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \ SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \ SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \ SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \ SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); } SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \ SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); } SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); } SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \ SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); } SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \ SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \ SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \ SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); } SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \ SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \ SYS_ISSETUGID = 253 // { int sys_issetugid(void); } SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); } SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); } SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); } SYS_PIPE = 263 // { int sys_pipe(int *fdp); } SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); } SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \ SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \ SYS_KQUEUE = 269 // { int sys_kqueue(void); } SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); } SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); } SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \ SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \ SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \ SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \ SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \ SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); } SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \ SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); } SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \ SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \ SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \ SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \ SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \ SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); } SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); } SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \ SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); } SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \ SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); } SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \ SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); } SYS_GETRTABLE = 311 // { int sys_getrtable(void); } SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \ SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \ SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \ SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \ SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \ SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \ SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \ SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \ SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \ SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \ SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \ SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \ SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); } SYS___GET_TCB = 330 // { void *sys___get_tcb(void); } ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go0000644061062106075000000003401113172163421026112 0ustar stgraberdomain admins// mksysnum_openbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build amd64,openbsd package unix const ( SYS_EXIT = 1 // { void sys_exit(int rval); } SYS_FORK = 2 // { int sys_fork(void); } SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \ SYS_OPEN = 5 // { int sys_open(const char *path, \ SYS_CLOSE = 6 // { int sys_close(int fd); } SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \ SYS_LINK = 9 // { int sys_link(const char *path, const char *link); } SYS_UNLINK = 10 // { int sys_unlink(const char *path); } SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \ SYS_CHDIR = 12 // { int sys_chdir(const char *path); } SYS_FCHDIR = 13 // { int sys_fchdir(int fd); } SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \ SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); } SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \ SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); } SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \ SYS_GETPID = 20 // { pid_t sys_getpid(void); } SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \ SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); } SYS_SETUID = 23 // { int sys_setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t sys_getuid(void); } SYS_GETEUID = 25 // { uid_t sys_geteuid(void); } SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \ SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \ SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \ SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \ SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \ SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \ SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \ SYS_ACCESS = 33 // { int sys_access(const char *path, int flags); } SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); } SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); } SYS_SYNC = 36 // { void sys_sync(void); } SYS_KILL = 37 // { int sys_kill(int pid, int signum); } SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); } SYS_GETPPID = 39 // { pid_t sys_getppid(void); } SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); } SYS_DUP = 41 // { int sys_dup(int fd); } SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \ SYS_GETEGID = 43 // { gid_t sys_getegid(void); } SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \ SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \ SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \ SYS_GETGID = 47 // { gid_t sys_getgid(void); } SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); } SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); } SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); } SYS_ACCT = 51 // { int sys_acct(const char *path); } SYS_SIGPENDING = 52 // { int sys_sigpending(void); } SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); } SYS_IOCTL = 54 // { int sys_ioctl(int fd, \ SYS_REBOOT = 55 // { int sys_reboot(int opt); } SYS_REVOKE = 56 // { int sys_revoke(const char *path); } SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \ SYS_READLINK = 58 // { int sys_readlink(const char *path, char *buf, \ SYS_EXECVE = 59 // { int sys_execve(const char *path, \ SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); } SYS_CHROOT = 61 // { int sys_chroot(const char *path); } SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \ SYS_STATFS = 63 // { int sys_statfs(const char *path, \ SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); } SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \ SYS_VFORK = 66 // { int sys_vfork(void); } SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \ SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \ SYS_SETITIMER = 69 // { int sys_setitimer(int which, \ SYS_GETITIMER = 70 // { int sys_getitimer(int which, \ SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \ SYS_KEVENT = 72 // { int sys_kevent(int fd, \ SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \ SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \ SYS_UTIMES = 76 // { int sys_utimes(const char *path, \ SYS_FUTIMES = 77 // { int sys_futimes(int fd, \ SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, \ SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \ SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \ SYS_GETPGRP = 81 // { int sys_getpgrp(void); } SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, int pgid); } SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \ SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \ SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \ SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \ SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \ SYS_DUP2 = 90 // { int sys_dup2(int from, int to); } SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \ SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); } SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \ SYS_FSYNC = 95 // { int sys_fsync(int fd); } SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); } SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); } SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \ SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); } SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); } SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); } SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \ SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \ SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); } SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \ SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \ SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); } SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \ SYS_READV = 120 // { ssize_t sys_readv(int fd, \ SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \ SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); } SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); } SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); } SYS_FLOCK = 131 // { int sys_flock(int fd, int how); } SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); } SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \ SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \ SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int sys_rmdir(const char *path); } SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \ SYS_SETSID = 147 // { int sys_setsid(void); } SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \ SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); } SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); } SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); } SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \ SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \ SYS_SETGID = 181 // { int sys_setgid(gid_t gid); } SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); } SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); } SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); } SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); } SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); } SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \ SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \ SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \ SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \ SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \ SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); } SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \ SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); } SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); } SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \ SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); } SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \ SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \ SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \ SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); } SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \ SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \ SYS_ISSETUGID = 253 // { int sys_issetugid(void); } SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); } SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); } SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); } SYS_PIPE = 263 // { int sys_pipe(int *fdp); } SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); } SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \ SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \ SYS_KQUEUE = 269 // { int sys_kqueue(void); } SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); } SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); } SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \ SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \ SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \ SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \ SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \ SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); } SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \ SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); } SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \ SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \ SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \ SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \ SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \ SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); } SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); } SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \ SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); } SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \ SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); } SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \ SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); } SYS_GETRTABLE = 311 // { int sys_getrtable(void); } SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \ SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \ SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \ SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \ SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \ SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \ SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \ SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \ SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \ SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \ SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \ SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \ SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); } SYS___GET_TCB = 330 // { void *sys___get_tcb(void); } ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_openbsd_386.go0000644061062106075000000003400713172163421025524 0ustar stgraberdomain admins// mksysnum_openbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build 386,openbsd package unix const ( SYS_EXIT = 1 // { void sys_exit(int rval); } SYS_FORK = 2 // { int sys_fork(void); } SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \ SYS_OPEN = 5 // { int sys_open(const char *path, \ SYS_CLOSE = 6 // { int sys_close(int fd); } SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \ SYS_LINK = 9 // { int sys_link(const char *path, const char *link); } SYS_UNLINK = 10 // { int sys_unlink(const char *path); } SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \ SYS_CHDIR = 12 // { int sys_chdir(const char *path); } SYS_FCHDIR = 13 // { int sys_fchdir(int fd); } SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \ SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); } SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \ SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); } SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \ SYS_GETPID = 20 // { pid_t sys_getpid(void); } SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \ SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); } SYS_SETUID = 23 // { int sys_setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t sys_getuid(void); } SYS_GETEUID = 25 // { uid_t sys_geteuid(void); } SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \ SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \ SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \ SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \ SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \ SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \ SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \ SYS_ACCESS = 33 // { int sys_access(const char *path, int flags); } SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); } SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); } SYS_SYNC = 36 // { void sys_sync(void); } SYS_KILL = 37 // { int sys_kill(int pid, int signum); } SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); } SYS_GETPPID = 39 // { pid_t sys_getppid(void); } SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); } SYS_DUP = 41 // { int sys_dup(int fd); } SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \ SYS_GETEGID = 43 // { gid_t sys_getegid(void); } SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \ SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \ SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \ SYS_GETGID = 47 // { gid_t sys_getgid(void); } SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); } SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); } SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); } SYS_ACCT = 51 // { int sys_acct(const char *path); } SYS_SIGPENDING = 52 // { int sys_sigpending(void); } SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); } SYS_IOCTL = 54 // { int sys_ioctl(int fd, \ SYS_REBOOT = 55 // { int sys_reboot(int opt); } SYS_REVOKE = 56 // { int sys_revoke(const char *path); } SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \ SYS_READLINK = 58 // { int sys_readlink(const char *path, char *buf, \ SYS_EXECVE = 59 // { int sys_execve(const char *path, \ SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); } SYS_CHROOT = 61 // { int sys_chroot(const char *path); } SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \ SYS_STATFS = 63 // { int sys_statfs(const char *path, \ SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); } SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \ SYS_VFORK = 66 // { int sys_vfork(void); } SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \ SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \ SYS_SETITIMER = 69 // { int sys_setitimer(int which, \ SYS_GETITIMER = 70 // { int sys_getitimer(int which, \ SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \ SYS_KEVENT = 72 // { int sys_kevent(int fd, \ SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \ SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \ SYS_UTIMES = 76 // { int sys_utimes(const char *path, \ SYS_FUTIMES = 77 // { int sys_futimes(int fd, \ SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, \ SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \ SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \ SYS_GETPGRP = 81 // { int sys_getpgrp(void); } SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, int pgid); } SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \ SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \ SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \ SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \ SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \ SYS_DUP2 = 90 // { int sys_dup2(int from, int to); } SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \ SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); } SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \ SYS_FSYNC = 95 // { int sys_fsync(int fd); } SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); } SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); } SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \ SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); } SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); } SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); } SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \ SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \ SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); } SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \ SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \ SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); } SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \ SYS_READV = 120 // { ssize_t sys_readv(int fd, \ SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \ SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); } SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); } SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); } SYS_FLOCK = 131 // { int sys_flock(int fd, int how); } SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); } SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \ SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \ SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int sys_rmdir(const char *path); } SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \ SYS_SETSID = 147 // { int sys_setsid(void); } SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \ SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); } SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); } SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); } SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \ SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \ SYS_SETGID = 181 // { int sys_setgid(gid_t gid); } SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); } SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); } SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); } SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); } SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); } SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \ SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \ SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \ SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \ SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \ SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); } SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \ SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); } SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); } SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \ SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); } SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \ SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \ SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \ SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); } SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \ SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \ SYS_ISSETUGID = 253 // { int sys_issetugid(void); } SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); } SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); } SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); } SYS_PIPE = 263 // { int sys_pipe(int *fdp); } SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); } SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \ SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \ SYS_KQUEUE = 269 // { int sys_kqueue(void); } SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); } SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); } SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \ SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \ SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \ SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \ SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \ SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); } SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \ SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); } SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \ SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \ SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \ SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \ SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \ SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); } SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); } SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \ SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); } SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \ SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); } SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \ SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); } SYS_GETRTABLE = 311 // { int sys_getrtable(void); } SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \ SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \ SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \ SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \ SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \ SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \ SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \ SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \ SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \ SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \ SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \ SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \ SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); } SYS___GET_TCB = 330 // { void *sys___get_tcb(void); } ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_netbsd_arm.go0000644061062106075000000006321113172163421025607 0ustar stgraberdomain admins// mksysnum_netbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build arm,netbsd package unix const ( SYS_EXIT = 1 // { void|sys||exit(int rval); } SYS_FORK = 2 // { int|sys||fork(void); } SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); } SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); } SYS_CLOSE = 6 // { int|sys||close(int fd); } SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); } SYS_UNLINK = 10 // { int|sys||unlink(const char *path); } SYS_CHDIR = 12 // { int|sys||chdir(const char *path); } SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); } SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); } SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); } SYS_BREAK = 17 // { int|sys||obreak(char *nsize); } SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); } SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); } SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); } SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); } SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); } SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); } SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); } SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); } SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); } SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); } SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); } SYS_SYNC = 36 // { void|sys||sync(void); } SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); } SYS_GETPPID = 39 // { pid_t|sys||getppid(void); } SYS_DUP = 41 // { int|sys||dup(int fd); } SYS_PIPE = 42 // { int|sys||pipe(void); } SYS_GETEGID = 43 // { gid_t|sys||getegid(void); } SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); } SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); } SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); } SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); } SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); } SYS_ACCT = 51 // { int|sys||acct(const char *path); } SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); } SYS_REVOKE = 56 // { int|sys||revoke(const char *path); } SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); } SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); } SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); } SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); } SYS_CHROOT = 61 // { int|sys||chroot(const char *path); } SYS_VFORK = 66 // { int|sys||vfork(void); } SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); } SYS_SSTK = 70 // { int|sys||sstk(int incr); } SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); } SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); } SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); } SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); } SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); } SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); } SYS_GETPGRP = 81 // { int|sys||getpgrp(void); } SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); } SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); } SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); } SYS_FSYNC = 95 // { int|sys||fsync(int fd); } SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); } SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); } SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); } SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); } SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); } SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); } SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); } SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); } SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); } SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); } SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); } SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); } SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); } SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); } SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); } SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); } SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); } SYS_SETSID = 147 // { int|sys||setsid(void); } SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); } SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); } SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); } SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); } SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); } SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); } SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); } SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); } SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); } SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); } SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); } SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); } SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); } SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); } SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); } SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); } SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); } SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); } SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); } SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); } SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); } SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); } SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); } SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); } SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); } SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); } SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); } SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); } SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); } SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); } SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); } SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); } SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); } SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); } SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); } SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); } SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); } SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); } SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); } SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); } SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); } SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); } SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); } SYS_ISSETUGID = 305 // { int|sys||issetugid(void); } SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); } SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); } SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); } SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); } SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); } SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); } SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); } SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); } SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); } SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); } SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); } SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); } SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); } SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); } SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); } SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); } SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); } SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); } SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); } SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); } SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); } SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); } SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); } SYS_KQUEUE = 344 // { int|sys||kqueue(void); } SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); } SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); } SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); } SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); } SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); } SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); } SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); } SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); } SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); } SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); } SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); } SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); } SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); } SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); } SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); } SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); } SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); } SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); } SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); } SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); } SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); } SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); } SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); } SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); } SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); } SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); } SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); } SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); } SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); } SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); } SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); } SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); } SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); } SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); } SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); } SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); } SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); } SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); } SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); } SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); } SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); } SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); } SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); } SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); } SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); } SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); } SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); } SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); } SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); } SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); } SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); } SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); } SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); } SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); } SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); } SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); } SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); } SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); } SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); } SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); } SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); } SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); } SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); } SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); } SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); } SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); } SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); } SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); } SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); } SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); } SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); } SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); } SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); } SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); } SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); } SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); } SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); } SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); } SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); } SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); } SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); } SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); } SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); } SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); } SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); } SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); } SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); } SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); } SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); } SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); } SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); } ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go0000644061062106075000000006321313172163421025745 0ustar stgraberdomain admins// mksysnum_netbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build amd64,netbsd package unix const ( SYS_EXIT = 1 // { void|sys||exit(int rval); } SYS_FORK = 2 // { int|sys||fork(void); } SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); } SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); } SYS_CLOSE = 6 // { int|sys||close(int fd); } SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); } SYS_UNLINK = 10 // { int|sys||unlink(const char *path); } SYS_CHDIR = 12 // { int|sys||chdir(const char *path); } SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); } SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); } SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); } SYS_BREAK = 17 // { int|sys||obreak(char *nsize); } SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); } SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); } SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); } SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); } SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); } SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); } SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); } SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); } SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); } SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); } SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); } SYS_SYNC = 36 // { void|sys||sync(void); } SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); } SYS_GETPPID = 39 // { pid_t|sys||getppid(void); } SYS_DUP = 41 // { int|sys||dup(int fd); } SYS_PIPE = 42 // { int|sys||pipe(void); } SYS_GETEGID = 43 // { gid_t|sys||getegid(void); } SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); } SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); } SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); } SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); } SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); } SYS_ACCT = 51 // { int|sys||acct(const char *path); } SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); } SYS_REVOKE = 56 // { int|sys||revoke(const char *path); } SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); } SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); } SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); } SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); } SYS_CHROOT = 61 // { int|sys||chroot(const char *path); } SYS_VFORK = 66 // { int|sys||vfork(void); } SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); } SYS_SSTK = 70 // { int|sys||sstk(int incr); } SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); } SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); } SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); } SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); } SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); } SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); } SYS_GETPGRP = 81 // { int|sys||getpgrp(void); } SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); } SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); } SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); } SYS_FSYNC = 95 // { int|sys||fsync(int fd); } SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); } SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); } SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); } SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); } SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); } SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); } SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); } SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); } SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); } SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); } SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); } SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); } SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); } SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); } SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); } SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); } SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); } SYS_SETSID = 147 // { int|sys||setsid(void); } SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); } SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); } SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); } SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); } SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); } SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); } SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); } SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); } SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); } SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); } SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); } SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); } SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); } SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); } SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); } SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); } SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); } SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); } SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); } SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); } SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); } SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); } SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); } SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); } SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); } SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); } SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); } SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); } SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); } SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); } SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); } SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); } SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); } SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); } SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); } SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); } SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); } SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); } SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); } SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); } SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); } SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); } SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); } SYS_ISSETUGID = 305 // { int|sys||issetugid(void); } SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); } SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); } SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); } SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); } SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); } SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); } SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); } SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); } SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); } SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); } SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); } SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); } SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); } SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); } SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); } SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); } SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); } SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); } SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); } SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); } SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); } SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); } SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); } SYS_KQUEUE = 344 // { int|sys||kqueue(void); } SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); } SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); } SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); } SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); } SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); } SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); } SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); } SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); } SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); } SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); } SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); } SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); } SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); } SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); } SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); } SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); } SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); } SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); } SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); } SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); } SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); } SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); } SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); } SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); } SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); } SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); } SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); } SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); } SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); } SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); } SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); } SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); } SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); } SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); } SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); } SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); } SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); } SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); } SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); } SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); } SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); } SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); } SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); } SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); } SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); } SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); } SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); } SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); } SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); } SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); } SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); } SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); } SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); } SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); } SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); } SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); } SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); } SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); } SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); } SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); } SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); } SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); } SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); } SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); } SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); } SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); } SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); } SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); } SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); } SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); } SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); } SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); } SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); } SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); } SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); } SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); } SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); } SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); } SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); } SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); } SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); } SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); } SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); } SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); } SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); } SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); } SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); } SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); } SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); } SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); } SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); } ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_netbsd_386.go0000644061062106075000000006321113172163421025350 0ustar stgraberdomain admins// mksysnum_netbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build 386,netbsd package unix const ( SYS_EXIT = 1 // { void|sys||exit(int rval); } SYS_FORK = 2 // { int|sys||fork(void); } SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); } SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); } SYS_CLOSE = 6 // { int|sys||close(int fd); } SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); } SYS_UNLINK = 10 // { int|sys||unlink(const char *path); } SYS_CHDIR = 12 // { int|sys||chdir(const char *path); } SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); } SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); } SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); } SYS_BREAK = 17 // { int|sys||obreak(char *nsize); } SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); } SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); } SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); } SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); } SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); } SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); } SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); } SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); } SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); } SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); } SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); } SYS_SYNC = 36 // { void|sys||sync(void); } SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); } SYS_GETPPID = 39 // { pid_t|sys||getppid(void); } SYS_DUP = 41 // { int|sys||dup(int fd); } SYS_PIPE = 42 // { int|sys||pipe(void); } SYS_GETEGID = 43 // { gid_t|sys||getegid(void); } SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); } SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); } SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); } SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); } SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); } SYS_ACCT = 51 // { int|sys||acct(const char *path); } SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); } SYS_REVOKE = 56 // { int|sys||revoke(const char *path); } SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); } SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); } SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); } SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); } SYS_CHROOT = 61 // { int|sys||chroot(const char *path); } SYS_VFORK = 66 // { int|sys||vfork(void); } SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); } SYS_SSTK = 70 // { int|sys||sstk(int incr); } SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); } SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); } SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); } SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); } SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); } SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); } SYS_GETPGRP = 81 // { int|sys||getpgrp(void); } SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); } SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); } SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); } SYS_FSYNC = 95 // { int|sys||fsync(int fd); } SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); } SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); } SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); } SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); } SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); } SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); } SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); } SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); } SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); } SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); } SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); } SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); } SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); } SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); } SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); } SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); } SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); } SYS_SETSID = 147 // { int|sys||setsid(void); } SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); } SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); } SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); } SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); } SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); } SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); } SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); } SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); } SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); } SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); } SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); } SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); } SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); } SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); } SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); } SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); } SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); } SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); } SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); } SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); } SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); } SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); } SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); } SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); } SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); } SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); } SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); } SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); } SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); } SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); } SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); } SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); } SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); } SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); } SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); } SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); } SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); } SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); } SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); } SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); } SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); } SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); } SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); } SYS_ISSETUGID = 305 // { int|sys||issetugid(void); } SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); } SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); } SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); } SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); } SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); } SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); } SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); } SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); } SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); } SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); } SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); } SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); } SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); } SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); } SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); } SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); } SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); } SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); } SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); } SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); } SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); } SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); } SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); } SYS_KQUEUE = 344 // { int|sys||kqueue(void); } SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); } SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); } SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); } SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); } SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); } SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); } SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); } SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); } SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); } SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); } SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); } SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); } SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); } SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); } SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); } SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); } SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); } SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); } SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); } SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); } SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); } SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); } SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); } SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); } SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); } SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); } SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); } SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); } SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); } SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); } SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); } SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); } SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); } SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); } SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); } SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); } SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); } SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); } SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); } SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); } SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); } SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); } SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); } SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); } SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); } SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); } SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); } SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); } SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); } SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); } SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); } SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); } SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); } SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); } SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); } SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); } SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); } SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); } SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); } SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); } SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); } SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); } SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); } SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); } SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); } SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); } SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); } SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); } SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); } SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); } SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); } SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); } SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); } SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); } SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); } SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); } SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); } SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); } SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); } SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); } SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); } SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); } SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); } SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); } SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); } SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); } SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); } SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); } SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); } SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); } SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); } ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_sparc64.go0000644061062106075000000002655313172163421026202 0ustar stgraberdomain admins// mksysnum_linux.pl -Ilinux/usr/include -m64 -D__arch64__ linux/usr/include/asm/unistd.h // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build sparc64,linux package unix const ( SYS_RESTART_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAIT4 = 7 SYS_CREAT = 8 SYS_LINK = 9 SYS_UNLINK = 10 SYS_EXECV = 11 SYS_CHDIR = 12 SYS_CHOWN = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 SYS_BRK = 17 SYS_PERFCTR = 18 SYS_LSEEK = 19 SYS_GETPID = 20 SYS_CAPGET = 21 SYS_CAPSET = 22 SYS_SETUID = 23 SYS_GETUID = 24 SYS_VMSPLICE = 25 SYS_PTRACE = 26 SYS_ALARM = 27 SYS_SIGALTSTACK = 28 SYS_PAUSE = 29 SYS_UTIME = 30 SYS_ACCESS = 33 SYS_NICE = 34 SYS_SYNC = 36 SYS_KILL = 37 SYS_STAT = 38 SYS_SENDFILE = 39 SYS_LSTAT = 40 SYS_DUP = 41 SYS_PIPE = 42 SYS_TIMES = 43 SYS_UMOUNT2 = 45 SYS_SETGID = 46 SYS_GETGID = 47 SYS_SIGNAL = 48 SYS_GETEUID = 49 SYS_GETEGID = 50 SYS_ACCT = 51 SYS_MEMORY_ORDERING = 52 SYS_IOCTL = 54 SYS_REBOOT = 55 SYS_SYMLINK = 57 SYS_READLINK = 58 SYS_EXECVE = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_FSTAT = 62 SYS_FSTAT64 = 63 SYS_GETPAGESIZE = 64 SYS_MSYNC = 65 SYS_VFORK = 66 SYS_PREAD64 = 67 SYS_PWRITE64 = 68 SYS_MMAP = 71 SYS_MUNMAP = 73 SYS_MPROTECT = 74 SYS_MADVISE = 75 SYS_VHANGUP = 76 SYS_MINCORE = 78 SYS_GETGROUPS = 79 SYS_SETGROUPS = 80 SYS_GETPGRP = 81 SYS_SETITIMER = 83 SYS_SWAPON = 85 SYS_GETITIMER = 86 SYS_SETHOSTNAME = 88 SYS_DUP2 = 90 SYS_FCNTL = 92 SYS_SELECT = 93 SYS_FSYNC = 95 SYS_SETPRIORITY = 96 SYS_SOCKET = 97 SYS_CONNECT = 98 SYS_ACCEPT = 99 SYS_GETPRIORITY = 100 SYS_RT_SIGRETURN = 101 SYS_RT_SIGACTION = 102 SYS_RT_SIGPROCMASK = 103 SYS_RT_SIGPENDING = 104 SYS_RT_SIGTIMEDWAIT = 105 SYS_RT_SIGQUEUEINFO = 106 SYS_RT_SIGSUSPEND = 107 SYS_SETRESUID = 108 SYS_GETRESUID = 109 SYS_SETRESGID = 110 SYS_GETRESGID = 111 SYS_RECVMSG = 113 SYS_SENDMSG = 114 SYS_GETTIMEOFDAY = 116 SYS_GETRUSAGE = 117 SYS_GETSOCKOPT = 118 SYS_GETCWD = 119 SYS_READV = 120 SYS_WRITEV = 121 SYS_SETTIMEOFDAY = 122 SYS_FCHOWN = 123 SYS_FCHMOD = 124 SYS_RECVFROM = 125 SYS_SETREUID = 126 SYS_SETREGID = 127 SYS_RENAME = 128 SYS_TRUNCATE = 129 SYS_FTRUNCATE = 130 SYS_FLOCK = 131 SYS_LSTAT64 = 132 SYS_SENDTO = 133 SYS_SHUTDOWN = 134 SYS_SOCKETPAIR = 135 SYS_MKDIR = 136 SYS_RMDIR = 137 SYS_UTIMES = 138 SYS_STAT64 = 139 SYS_SENDFILE64 = 140 SYS_GETPEERNAME = 141 SYS_FUTEX = 142 SYS_GETTID = 143 SYS_GETRLIMIT = 144 SYS_SETRLIMIT = 145 SYS_PIVOT_ROOT = 146 SYS_PRCTL = 147 SYS_PCICONFIG_READ = 148 SYS_PCICONFIG_WRITE = 149 SYS_GETSOCKNAME = 150 SYS_INOTIFY_INIT = 151 SYS_INOTIFY_ADD_WATCH = 152 SYS_POLL = 153 SYS_GETDENTS64 = 154 SYS_INOTIFY_RM_WATCH = 156 SYS_STATFS = 157 SYS_FSTATFS = 158 SYS_UMOUNT = 159 SYS_SCHED_SET_AFFINITY = 160 SYS_SCHED_GET_AFFINITY = 161 SYS_GETDOMAINNAME = 162 SYS_SETDOMAINNAME = 163 SYS_UTRAP_INSTALL = 164 SYS_QUOTACTL = 165 SYS_SET_TID_ADDRESS = 166 SYS_MOUNT = 167 SYS_USTAT = 168 SYS_SETXATTR = 169 SYS_LSETXATTR = 170 SYS_FSETXATTR = 171 SYS_GETXATTR = 172 SYS_LGETXATTR = 173 SYS_GETDENTS = 174 SYS_SETSID = 175 SYS_FCHDIR = 176 SYS_FGETXATTR = 177 SYS_LISTXATTR = 178 SYS_LLISTXATTR = 179 SYS_FLISTXATTR = 180 SYS_REMOVEXATTR = 181 SYS_LREMOVEXATTR = 182 SYS_SIGPENDING = 183 SYS_QUERY_MODULE = 184 SYS_SETPGID = 185 SYS_FREMOVEXATTR = 186 SYS_TKILL = 187 SYS_EXIT_GROUP = 188 SYS_UNAME = 189 SYS_INIT_MODULE = 190 SYS_PERSONALITY = 191 SYS_REMAP_FILE_PAGES = 192 SYS_EPOLL_CREATE = 193 SYS_EPOLL_CTL = 194 SYS_EPOLL_WAIT = 195 SYS_IOPRIO_SET = 196 SYS_GETPPID = 197 SYS_SIGACTION = 198 SYS_SGETMASK = 199 SYS_SSETMASK = 200 SYS_SIGSUSPEND = 201 SYS_OLDLSTAT = 202 SYS_USELIB = 203 SYS_READDIR = 204 SYS_READAHEAD = 205 SYS_SOCKETCALL = 206 SYS_SYSLOG = 207 SYS_LOOKUP_DCOOKIE = 208 SYS_FADVISE64 = 209 SYS_FADVISE64_64 = 210 SYS_TGKILL = 211 SYS_WAITPID = 212 SYS_SWAPOFF = 213 SYS_SYSINFO = 214 SYS_IPC = 215 SYS_SIGRETURN = 216 SYS_CLONE = 217 SYS_IOPRIO_GET = 218 SYS_ADJTIMEX = 219 SYS_SIGPROCMASK = 220 SYS_CREATE_MODULE = 221 SYS_DELETE_MODULE = 222 SYS_GET_KERNEL_SYMS = 223 SYS_GETPGID = 224 SYS_BDFLUSH = 225 SYS_SYSFS = 226 SYS_AFS_SYSCALL = 227 SYS_SETFSUID = 228 SYS_SETFSGID = 229 SYS__NEWSELECT = 230 SYS_SPLICE = 232 SYS_STIME = 233 SYS_STATFS64 = 234 SYS_FSTATFS64 = 235 SYS__LLSEEK = 236 SYS_MLOCK = 237 SYS_MUNLOCK = 238 SYS_MLOCKALL = 239 SYS_MUNLOCKALL = 240 SYS_SCHED_SETPARAM = 241 SYS_SCHED_GETPARAM = 242 SYS_SCHED_SETSCHEDULER = 243 SYS_SCHED_GETSCHEDULER = 244 SYS_SCHED_YIELD = 245 SYS_SCHED_GET_PRIORITY_MAX = 246 SYS_SCHED_GET_PRIORITY_MIN = 247 SYS_SCHED_RR_GET_INTERVAL = 248 SYS_NANOSLEEP = 249 SYS_MREMAP = 250 SYS__SYSCTL = 251 SYS_GETSID = 252 SYS_FDATASYNC = 253 SYS_NFSSERVCTL = 254 SYS_SYNC_FILE_RANGE = 255 SYS_CLOCK_SETTIME = 256 SYS_CLOCK_GETTIME = 257 SYS_CLOCK_GETRES = 258 SYS_CLOCK_NANOSLEEP = 259 SYS_SCHED_GETAFFINITY = 260 SYS_SCHED_SETAFFINITY = 261 SYS_TIMER_SETTIME = 262 SYS_TIMER_GETTIME = 263 SYS_TIMER_GETOVERRUN = 264 SYS_TIMER_DELETE = 265 SYS_TIMER_CREATE = 266 SYS_IO_SETUP = 268 SYS_IO_DESTROY = 269 SYS_IO_SUBMIT = 270 SYS_IO_CANCEL = 271 SYS_IO_GETEVENTS = 272 SYS_MQ_OPEN = 273 SYS_MQ_UNLINK = 274 SYS_MQ_TIMEDSEND = 275 SYS_MQ_TIMEDRECEIVE = 276 SYS_MQ_NOTIFY = 277 SYS_MQ_GETSETATTR = 278 SYS_WAITID = 279 SYS_TEE = 280 SYS_ADD_KEY = 281 SYS_REQUEST_KEY = 282 SYS_KEYCTL = 283 SYS_OPENAT = 284 SYS_MKDIRAT = 285 SYS_MKNODAT = 286 SYS_FCHOWNAT = 287 SYS_FUTIMESAT = 288 SYS_FSTATAT64 = 289 SYS_UNLINKAT = 290 SYS_RENAMEAT = 291 SYS_LINKAT = 292 SYS_SYMLINKAT = 293 SYS_READLINKAT = 294 SYS_FCHMODAT = 295 SYS_FACCESSAT = 296 SYS_PSELECT6 = 297 SYS_PPOLL = 298 SYS_UNSHARE = 299 SYS_SET_ROBUST_LIST = 300 SYS_GET_ROBUST_LIST = 301 SYS_MIGRATE_PAGES = 302 SYS_MBIND = 303 SYS_GET_MEMPOLICY = 304 SYS_SET_MEMPOLICY = 305 SYS_KEXEC_LOAD = 306 SYS_MOVE_PAGES = 307 SYS_GETCPU = 308 SYS_EPOLL_PWAIT = 309 SYS_UTIMENSAT = 310 SYS_SIGNALFD = 311 SYS_TIMERFD_CREATE = 312 SYS_EVENTFD = 313 SYS_FALLOCATE = 314 SYS_TIMERFD_SETTIME = 315 SYS_TIMERFD_GETTIME = 316 SYS_SIGNALFD4 = 317 SYS_EVENTFD2 = 318 SYS_EPOLL_CREATE1 = 319 SYS_DUP3 = 320 SYS_PIPE2 = 321 SYS_INOTIFY_INIT1 = 322 SYS_ACCEPT4 = 323 SYS_PREADV = 324 SYS_PWRITEV = 325 SYS_RT_TGSIGQUEUEINFO = 326 SYS_PERF_EVENT_OPEN = 327 SYS_RECVMMSG = 328 SYS_FANOTIFY_INIT = 329 SYS_FANOTIFY_MARK = 330 SYS_PRLIMIT64 = 331 SYS_NAME_TO_HANDLE_AT = 332 SYS_OPEN_BY_HANDLE_AT = 333 SYS_CLOCK_ADJTIME = 334 SYS_SYNCFS = 335 SYS_SENDMMSG = 336 SYS_SETNS = 337 SYS_PROCESS_VM_READV = 338 SYS_PROCESS_VM_WRITEV = 339 SYS_KERN_FEATURES = 340 SYS_KCMP = 341 SYS_FINIT_MODULE = 342 SYS_SCHED_SETATTR = 343 SYS_SCHED_GETATTR = 344 SYS_RENAMEAT2 = 345 SYS_SECCOMP = 346 SYS_GETRANDOM = 347 SYS_MEMFD_CREATE = 348 SYS_BPF = 349 SYS_EXECVEAT = 350 SYS_MEMBARRIER = 351 SYS_USERFAULTFD = 352 SYS_BIND = 353 SYS_LISTEN = 354 SYS_SETSOCKOPT = 355 SYS_MLOCK2 = 356 SYS_COPY_FILE_RANGE = 357 SYS_PREADV2 = 358 SYS_PWRITEV2 = 359 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_s390x.go0000644061062106075000000002562113172163421025601 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -fsigned-char /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build s390x,linux package unix const ( SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_RESTART_SYSCALL = 7 SYS_CREAT = 8 SYS_LINK = 9 SYS_UNLINK = 10 SYS_EXECVE = 11 SYS_CHDIR = 12 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LSEEK = 19 SYS_GETPID = 20 SYS_MOUNT = 21 SYS_UMOUNT = 22 SYS_PTRACE = 26 SYS_ALARM = 27 SYS_PAUSE = 29 SYS_UTIME = 30 SYS_ACCESS = 33 SYS_NICE = 34 SYS_SYNC = 36 SYS_KILL = 37 SYS_RENAME = 38 SYS_MKDIR = 39 SYS_RMDIR = 40 SYS_DUP = 41 SYS_PIPE = 42 SYS_TIMES = 43 SYS_BRK = 45 SYS_SIGNAL = 48 SYS_ACCT = 51 SYS_UMOUNT2 = 52 SYS_IOCTL = 54 SYS_FCNTL = 55 SYS_SETPGID = 57 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_USTAT = 62 SYS_DUP2 = 63 SYS_GETPPID = 64 SYS_GETPGRP = 65 SYS_SETSID = 66 SYS_SIGACTION = 67 SYS_SIGSUSPEND = 72 SYS_SIGPENDING = 73 SYS_SETHOSTNAME = 74 SYS_SETRLIMIT = 75 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_SYMLINK = 83 SYS_READLINK = 85 SYS_USELIB = 86 SYS_SWAPON = 87 SYS_REBOOT = 88 SYS_READDIR = 89 SYS_MMAP = 90 SYS_MUNMAP = 91 SYS_TRUNCATE = 92 SYS_FTRUNCATE = 93 SYS_FCHMOD = 94 SYS_GETPRIORITY = 96 SYS_SETPRIORITY = 97 SYS_STATFS = 99 SYS_FSTATFS = 100 SYS_SOCKETCALL = 102 SYS_SYSLOG = 103 SYS_SETITIMER = 104 SYS_GETITIMER = 105 SYS_STAT = 106 SYS_LSTAT = 107 SYS_FSTAT = 108 SYS_LOOKUP_DCOOKIE = 110 SYS_VHANGUP = 111 SYS_IDLE = 112 SYS_WAIT4 = 114 SYS_SWAPOFF = 115 SYS_SYSINFO = 116 SYS_IPC = 117 SYS_FSYNC = 118 SYS_SIGRETURN = 119 SYS_CLONE = 120 SYS_SETDOMAINNAME = 121 SYS_UNAME = 122 SYS_ADJTIMEX = 124 SYS_MPROTECT = 125 SYS_SIGPROCMASK = 126 SYS_CREATE_MODULE = 127 SYS_INIT_MODULE = 128 SYS_DELETE_MODULE = 129 SYS_GET_KERNEL_SYMS = 130 SYS_QUOTACTL = 131 SYS_GETPGID = 132 SYS_FCHDIR = 133 SYS_BDFLUSH = 134 SYS_SYSFS = 135 SYS_PERSONALITY = 136 SYS_AFS_SYSCALL = 137 SYS_GETDENTS = 141 SYS_FLOCK = 143 SYS_MSYNC = 144 SYS_READV = 145 SYS_WRITEV = 146 SYS_GETSID = 147 SYS_FDATASYNC = 148 SYS__SYSCTL = 149 SYS_MLOCK = 150 SYS_MUNLOCK = 151 SYS_MLOCKALL = 152 SYS_MUNLOCKALL = 153 SYS_SCHED_SETPARAM = 154 SYS_SCHED_GETPARAM = 155 SYS_SCHED_SETSCHEDULER = 156 SYS_SCHED_GETSCHEDULER = 157 SYS_SCHED_YIELD = 158 SYS_SCHED_GET_PRIORITY_MAX = 159 SYS_SCHED_GET_PRIORITY_MIN = 160 SYS_SCHED_RR_GET_INTERVAL = 161 SYS_NANOSLEEP = 162 SYS_MREMAP = 163 SYS_QUERY_MODULE = 167 SYS_POLL = 168 SYS_NFSSERVCTL = 169 SYS_PRCTL = 172 SYS_RT_SIGRETURN = 173 SYS_RT_SIGACTION = 174 SYS_RT_SIGPROCMASK = 175 SYS_RT_SIGPENDING = 176 SYS_RT_SIGTIMEDWAIT = 177 SYS_RT_SIGQUEUEINFO = 178 SYS_RT_SIGSUSPEND = 179 SYS_PREAD64 = 180 SYS_PWRITE64 = 181 SYS_GETCWD = 183 SYS_CAPGET = 184 SYS_CAPSET = 185 SYS_SIGALTSTACK = 186 SYS_SENDFILE = 187 SYS_GETPMSG = 188 SYS_PUTPMSG = 189 SYS_VFORK = 190 SYS_PIVOT_ROOT = 217 SYS_MINCORE = 218 SYS_MADVISE = 219 SYS_GETDENTS64 = 220 SYS_READAHEAD = 222 SYS_SETXATTR = 224 SYS_LSETXATTR = 225 SYS_FSETXATTR = 226 SYS_GETXATTR = 227 SYS_LGETXATTR = 228 SYS_FGETXATTR = 229 SYS_LISTXATTR = 230 SYS_LLISTXATTR = 231 SYS_FLISTXATTR = 232 SYS_REMOVEXATTR = 233 SYS_LREMOVEXATTR = 234 SYS_FREMOVEXATTR = 235 SYS_GETTID = 236 SYS_TKILL = 237 SYS_FUTEX = 238 SYS_SCHED_SETAFFINITY = 239 SYS_SCHED_GETAFFINITY = 240 SYS_TGKILL = 241 SYS_IO_SETUP = 243 SYS_IO_DESTROY = 244 SYS_IO_GETEVENTS = 245 SYS_IO_SUBMIT = 246 SYS_IO_CANCEL = 247 SYS_EXIT_GROUP = 248 SYS_EPOLL_CREATE = 249 SYS_EPOLL_CTL = 250 SYS_EPOLL_WAIT = 251 SYS_SET_TID_ADDRESS = 252 SYS_FADVISE64 = 253 SYS_TIMER_CREATE = 254 SYS_TIMER_SETTIME = 255 SYS_TIMER_GETTIME = 256 SYS_TIMER_GETOVERRUN = 257 SYS_TIMER_DELETE = 258 SYS_CLOCK_SETTIME = 259 SYS_CLOCK_GETTIME = 260 SYS_CLOCK_GETRES = 261 SYS_CLOCK_NANOSLEEP = 262 SYS_STATFS64 = 265 SYS_FSTATFS64 = 266 SYS_REMAP_FILE_PAGES = 267 SYS_MBIND = 268 SYS_GET_MEMPOLICY = 269 SYS_SET_MEMPOLICY = 270 SYS_MQ_OPEN = 271 SYS_MQ_UNLINK = 272 SYS_MQ_TIMEDSEND = 273 SYS_MQ_TIMEDRECEIVE = 274 SYS_MQ_NOTIFY = 275 SYS_MQ_GETSETATTR = 276 SYS_KEXEC_LOAD = 277 SYS_ADD_KEY = 278 SYS_REQUEST_KEY = 279 SYS_KEYCTL = 280 SYS_WAITID = 281 SYS_IOPRIO_SET = 282 SYS_IOPRIO_GET = 283 SYS_INOTIFY_INIT = 284 SYS_INOTIFY_ADD_WATCH = 285 SYS_INOTIFY_RM_WATCH = 286 SYS_MIGRATE_PAGES = 287 SYS_OPENAT = 288 SYS_MKDIRAT = 289 SYS_MKNODAT = 290 SYS_FCHOWNAT = 291 SYS_FUTIMESAT = 292 SYS_UNLINKAT = 294 SYS_RENAMEAT = 295 SYS_LINKAT = 296 SYS_SYMLINKAT = 297 SYS_READLINKAT = 298 SYS_FCHMODAT = 299 SYS_FACCESSAT = 300 SYS_PSELECT6 = 301 SYS_PPOLL = 302 SYS_UNSHARE = 303 SYS_SET_ROBUST_LIST = 304 SYS_GET_ROBUST_LIST = 305 SYS_SPLICE = 306 SYS_SYNC_FILE_RANGE = 307 SYS_TEE = 308 SYS_VMSPLICE = 309 SYS_MOVE_PAGES = 310 SYS_GETCPU = 311 SYS_EPOLL_PWAIT = 312 SYS_UTIMES = 313 SYS_FALLOCATE = 314 SYS_UTIMENSAT = 315 SYS_SIGNALFD = 316 SYS_TIMERFD = 317 SYS_EVENTFD = 318 SYS_TIMERFD_CREATE = 319 SYS_TIMERFD_SETTIME = 320 SYS_TIMERFD_GETTIME = 321 SYS_SIGNALFD4 = 322 SYS_EVENTFD2 = 323 SYS_INOTIFY_INIT1 = 324 SYS_PIPE2 = 325 SYS_DUP3 = 326 SYS_EPOLL_CREATE1 = 327 SYS_PREADV = 328 SYS_PWRITEV = 329 SYS_RT_TGSIGQUEUEINFO = 330 SYS_PERF_EVENT_OPEN = 331 SYS_FANOTIFY_INIT = 332 SYS_FANOTIFY_MARK = 333 SYS_PRLIMIT64 = 334 SYS_NAME_TO_HANDLE_AT = 335 SYS_OPEN_BY_HANDLE_AT = 336 SYS_CLOCK_ADJTIME = 337 SYS_SYNCFS = 338 SYS_SETNS = 339 SYS_PROCESS_VM_READV = 340 SYS_PROCESS_VM_WRITEV = 341 SYS_S390_RUNTIME_INSTR = 342 SYS_KCMP = 343 SYS_FINIT_MODULE = 344 SYS_SCHED_SETATTR = 345 SYS_SCHED_GETATTR = 346 SYS_RENAMEAT2 = 347 SYS_SECCOMP = 348 SYS_GETRANDOM = 349 SYS_MEMFD_CREATE = 350 SYS_BPF = 351 SYS_S390_PCI_MMIO_WRITE = 352 SYS_S390_PCI_MMIO_READ = 353 SYS_EXECVEAT = 354 SYS_USERFAULTFD = 355 SYS_MEMBARRIER = 356 SYS_RECVMMSG = 357 SYS_SENDMMSG = 358 SYS_SOCKET = 359 SYS_SOCKETPAIR = 360 SYS_BIND = 361 SYS_CONNECT = 362 SYS_LISTEN = 363 SYS_ACCEPT4 = 364 SYS_GETSOCKOPT = 365 SYS_SETSOCKOPT = 366 SYS_GETSOCKNAME = 367 SYS_GETPEERNAME = 368 SYS_SENDTO = 369 SYS_SENDMSG = 370 SYS_RECVFROM = 371 SYS_RECVMSG = 372 SYS_SHUTDOWN = 373 SYS_MLOCK2 = 374 SYS_COPY_FILE_RANGE = 375 SYS_PREADV2 = 376 SYS_PWRITEV2 = 377 SYS_S390_GUARDED_STORAGE = 378 SYS_STATX = 379 SYS_SELECT = 142 SYS_GETRLIMIT = 191 SYS_LCHOWN = 198 SYS_GETUID = 199 SYS_GETGID = 200 SYS_GETEUID = 201 SYS_GETEGID = 202 SYS_SETREUID = 203 SYS_SETREGID = 204 SYS_GETGROUPS = 205 SYS_SETGROUPS = 206 SYS_FCHOWN = 207 SYS_SETRESUID = 208 SYS_GETRESUID = 209 SYS_SETRESGID = 210 SYS_GETRESGID = 211 SYS_CHOWN = 212 SYS_SETUID = 213 SYS_SETGID = 214 SYS_SETFSUID = 215 SYS_SETFSGID = 216 SYS_NEWFSTATAT = 293 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go0000644061062106075000000003011613172163421026163 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build ppc64le,linux package unix const ( SYS_RESTART_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAITPID = 7 SYS_CREAT = 8 SYS_LINK = 9 SYS_UNLINK = 10 SYS_EXECVE = 11 SYS_CHDIR = 12 SYS_TIME = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 SYS_BREAK = 17 SYS_OLDSTAT = 18 SYS_LSEEK = 19 SYS_GETPID = 20 SYS_MOUNT = 21 SYS_UMOUNT = 22 SYS_SETUID = 23 SYS_GETUID = 24 SYS_STIME = 25 SYS_PTRACE = 26 SYS_ALARM = 27 SYS_OLDFSTAT = 28 SYS_PAUSE = 29 SYS_UTIME = 30 SYS_STTY = 31 SYS_GTTY = 32 SYS_ACCESS = 33 SYS_NICE = 34 SYS_FTIME = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_RENAME = 38 SYS_MKDIR = 39 SYS_RMDIR = 40 SYS_DUP = 41 SYS_PIPE = 42 SYS_TIMES = 43 SYS_PROF = 44 SYS_BRK = 45 SYS_SETGID = 46 SYS_GETGID = 47 SYS_SIGNAL = 48 SYS_GETEUID = 49 SYS_GETEGID = 50 SYS_ACCT = 51 SYS_UMOUNT2 = 52 SYS_LOCK = 53 SYS_IOCTL = 54 SYS_FCNTL = 55 SYS_MPX = 56 SYS_SETPGID = 57 SYS_ULIMIT = 58 SYS_OLDOLDUNAME = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_USTAT = 62 SYS_DUP2 = 63 SYS_GETPPID = 64 SYS_GETPGRP = 65 SYS_SETSID = 66 SYS_SIGACTION = 67 SYS_SGETMASK = 68 SYS_SSETMASK = 69 SYS_SETREUID = 70 SYS_SETREGID = 71 SYS_SIGSUSPEND = 72 SYS_SIGPENDING = 73 SYS_SETHOSTNAME = 74 SYS_SETRLIMIT = 75 SYS_GETRLIMIT = 76 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_GETGROUPS = 80 SYS_SETGROUPS = 81 SYS_SELECT = 82 SYS_SYMLINK = 83 SYS_OLDLSTAT = 84 SYS_READLINK = 85 SYS_USELIB = 86 SYS_SWAPON = 87 SYS_REBOOT = 88 SYS_READDIR = 89 SYS_MMAP = 90 SYS_MUNMAP = 91 SYS_TRUNCATE = 92 SYS_FTRUNCATE = 93 SYS_FCHMOD = 94 SYS_FCHOWN = 95 SYS_GETPRIORITY = 96 SYS_SETPRIORITY = 97 SYS_PROFIL = 98 SYS_STATFS = 99 SYS_FSTATFS = 100 SYS_IOPERM = 101 SYS_SOCKETCALL = 102 SYS_SYSLOG = 103 SYS_SETITIMER = 104 SYS_GETITIMER = 105 SYS_STAT = 106 SYS_LSTAT = 107 SYS_FSTAT = 108 SYS_OLDUNAME = 109 SYS_IOPL = 110 SYS_VHANGUP = 111 SYS_IDLE = 112 SYS_VM86 = 113 SYS_WAIT4 = 114 SYS_SWAPOFF = 115 SYS_SYSINFO = 116 SYS_IPC = 117 SYS_FSYNC = 118 SYS_SIGRETURN = 119 SYS_CLONE = 120 SYS_SETDOMAINNAME = 121 SYS_UNAME = 122 SYS_MODIFY_LDT = 123 SYS_ADJTIMEX = 124 SYS_MPROTECT = 125 SYS_SIGPROCMASK = 126 SYS_CREATE_MODULE = 127 SYS_INIT_MODULE = 128 SYS_DELETE_MODULE = 129 SYS_GET_KERNEL_SYMS = 130 SYS_QUOTACTL = 131 SYS_GETPGID = 132 SYS_FCHDIR = 133 SYS_BDFLUSH = 134 SYS_SYSFS = 135 SYS_PERSONALITY = 136 SYS_AFS_SYSCALL = 137 SYS_SETFSUID = 138 SYS_SETFSGID = 139 SYS__LLSEEK = 140 SYS_GETDENTS = 141 SYS__NEWSELECT = 142 SYS_FLOCK = 143 SYS_MSYNC = 144 SYS_READV = 145 SYS_WRITEV = 146 SYS_GETSID = 147 SYS_FDATASYNC = 148 SYS__SYSCTL = 149 SYS_MLOCK = 150 SYS_MUNLOCK = 151 SYS_MLOCKALL = 152 SYS_MUNLOCKALL = 153 SYS_SCHED_SETPARAM = 154 SYS_SCHED_GETPARAM = 155 SYS_SCHED_SETSCHEDULER = 156 SYS_SCHED_GETSCHEDULER = 157 SYS_SCHED_YIELD = 158 SYS_SCHED_GET_PRIORITY_MAX = 159 SYS_SCHED_GET_PRIORITY_MIN = 160 SYS_SCHED_RR_GET_INTERVAL = 161 SYS_NANOSLEEP = 162 SYS_MREMAP = 163 SYS_SETRESUID = 164 SYS_GETRESUID = 165 SYS_QUERY_MODULE = 166 SYS_POLL = 167 SYS_NFSSERVCTL = 168 SYS_SETRESGID = 169 SYS_GETRESGID = 170 SYS_PRCTL = 171 SYS_RT_SIGRETURN = 172 SYS_RT_SIGACTION = 173 SYS_RT_SIGPROCMASK = 174 SYS_RT_SIGPENDING = 175 SYS_RT_SIGTIMEDWAIT = 176 SYS_RT_SIGQUEUEINFO = 177 SYS_RT_SIGSUSPEND = 178 SYS_PREAD64 = 179 SYS_PWRITE64 = 180 SYS_CHOWN = 181 SYS_GETCWD = 182 SYS_CAPGET = 183 SYS_CAPSET = 184 SYS_SIGALTSTACK = 185 SYS_SENDFILE = 186 SYS_GETPMSG = 187 SYS_PUTPMSG = 188 SYS_VFORK = 189 SYS_UGETRLIMIT = 190 SYS_READAHEAD = 191 SYS_PCICONFIG_READ = 198 SYS_PCICONFIG_WRITE = 199 SYS_PCICONFIG_IOBASE = 200 SYS_MULTIPLEXER = 201 SYS_GETDENTS64 = 202 SYS_PIVOT_ROOT = 203 SYS_MADVISE = 205 SYS_MINCORE = 206 SYS_GETTID = 207 SYS_TKILL = 208 SYS_SETXATTR = 209 SYS_LSETXATTR = 210 SYS_FSETXATTR = 211 SYS_GETXATTR = 212 SYS_LGETXATTR = 213 SYS_FGETXATTR = 214 SYS_LISTXATTR = 215 SYS_LLISTXATTR = 216 SYS_FLISTXATTR = 217 SYS_REMOVEXATTR = 218 SYS_LREMOVEXATTR = 219 SYS_FREMOVEXATTR = 220 SYS_FUTEX = 221 SYS_SCHED_SETAFFINITY = 222 SYS_SCHED_GETAFFINITY = 223 SYS_TUXCALL = 225 SYS_IO_SETUP = 227 SYS_IO_DESTROY = 228 SYS_IO_GETEVENTS = 229 SYS_IO_SUBMIT = 230 SYS_IO_CANCEL = 231 SYS_SET_TID_ADDRESS = 232 SYS_FADVISE64 = 233 SYS_EXIT_GROUP = 234 SYS_LOOKUP_DCOOKIE = 235 SYS_EPOLL_CREATE = 236 SYS_EPOLL_CTL = 237 SYS_EPOLL_WAIT = 238 SYS_REMAP_FILE_PAGES = 239 SYS_TIMER_CREATE = 240 SYS_TIMER_SETTIME = 241 SYS_TIMER_GETTIME = 242 SYS_TIMER_GETOVERRUN = 243 SYS_TIMER_DELETE = 244 SYS_CLOCK_SETTIME = 245 SYS_CLOCK_GETTIME = 246 SYS_CLOCK_GETRES = 247 SYS_CLOCK_NANOSLEEP = 248 SYS_SWAPCONTEXT = 249 SYS_TGKILL = 250 SYS_UTIMES = 251 SYS_STATFS64 = 252 SYS_FSTATFS64 = 253 SYS_RTAS = 255 SYS_SYS_DEBUG_SETCONTEXT = 256 SYS_MIGRATE_PAGES = 258 SYS_MBIND = 259 SYS_GET_MEMPOLICY = 260 SYS_SET_MEMPOLICY = 261 SYS_MQ_OPEN = 262 SYS_MQ_UNLINK = 263 SYS_MQ_TIMEDSEND = 264 SYS_MQ_TIMEDRECEIVE = 265 SYS_MQ_NOTIFY = 266 SYS_MQ_GETSETATTR = 267 SYS_KEXEC_LOAD = 268 SYS_ADD_KEY = 269 SYS_REQUEST_KEY = 270 SYS_KEYCTL = 271 SYS_WAITID = 272 SYS_IOPRIO_SET = 273 SYS_IOPRIO_GET = 274 SYS_INOTIFY_INIT = 275 SYS_INOTIFY_ADD_WATCH = 276 SYS_INOTIFY_RM_WATCH = 277 SYS_SPU_RUN = 278 SYS_SPU_CREATE = 279 SYS_PSELECT6 = 280 SYS_PPOLL = 281 SYS_UNSHARE = 282 SYS_SPLICE = 283 SYS_TEE = 284 SYS_VMSPLICE = 285 SYS_OPENAT = 286 SYS_MKDIRAT = 287 SYS_MKNODAT = 288 SYS_FCHOWNAT = 289 SYS_FUTIMESAT = 290 SYS_NEWFSTATAT = 291 SYS_UNLINKAT = 292 SYS_RENAMEAT = 293 SYS_LINKAT = 294 SYS_SYMLINKAT = 295 SYS_READLINKAT = 296 SYS_FCHMODAT = 297 SYS_FACCESSAT = 298 SYS_GET_ROBUST_LIST = 299 SYS_SET_ROBUST_LIST = 300 SYS_MOVE_PAGES = 301 SYS_GETCPU = 302 SYS_EPOLL_PWAIT = 303 SYS_UTIMENSAT = 304 SYS_SIGNALFD = 305 SYS_TIMERFD_CREATE = 306 SYS_EVENTFD = 307 SYS_SYNC_FILE_RANGE2 = 308 SYS_FALLOCATE = 309 SYS_SUBPAGE_PROT = 310 SYS_TIMERFD_SETTIME = 311 SYS_TIMERFD_GETTIME = 312 SYS_SIGNALFD4 = 313 SYS_EVENTFD2 = 314 SYS_EPOLL_CREATE1 = 315 SYS_DUP3 = 316 SYS_PIPE2 = 317 SYS_INOTIFY_INIT1 = 318 SYS_PERF_EVENT_OPEN = 319 SYS_PREADV = 320 SYS_PWRITEV = 321 SYS_RT_TGSIGQUEUEINFO = 322 SYS_FANOTIFY_INIT = 323 SYS_FANOTIFY_MARK = 324 SYS_PRLIMIT64 = 325 SYS_SOCKET = 326 SYS_BIND = 327 SYS_CONNECT = 328 SYS_LISTEN = 329 SYS_ACCEPT = 330 SYS_GETSOCKNAME = 331 SYS_GETPEERNAME = 332 SYS_SOCKETPAIR = 333 SYS_SEND = 334 SYS_SENDTO = 335 SYS_RECV = 336 SYS_RECVFROM = 337 SYS_SHUTDOWN = 338 SYS_SETSOCKOPT = 339 SYS_GETSOCKOPT = 340 SYS_SENDMSG = 341 SYS_RECVMSG = 342 SYS_RECVMMSG = 343 SYS_ACCEPT4 = 344 SYS_NAME_TO_HANDLE_AT = 345 SYS_OPEN_BY_HANDLE_AT = 346 SYS_CLOCK_ADJTIME = 347 SYS_SYNCFS = 348 SYS_SENDMMSG = 349 SYS_SETNS = 350 SYS_PROCESS_VM_READV = 351 SYS_PROCESS_VM_WRITEV = 352 SYS_FINIT_MODULE = 353 SYS_KCMP = 354 SYS_SCHED_SETATTR = 355 SYS_SCHED_GETATTR = 356 SYS_RENAMEAT2 = 357 SYS_SECCOMP = 358 SYS_GETRANDOM = 359 SYS_MEMFD_CREATE = 360 SYS_BPF = 361 SYS_EXECVEAT = 362 SYS_SWITCH_ENDIAN = 363 SYS_USERFAULTFD = 364 SYS_MEMBARRIER = 365 SYS_MLOCK2 = 378 SYS_COPY_FILE_RANGE = 379 SYS_PREADV2 = 380 SYS_PWRITEV2 = 381 SYS_KEXEC_FILE_LOAD = 382 SYS_STATX = 383 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_ppc64.go0000644061062106075000000003011413172163421025640 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build ppc64,linux package unix const ( SYS_RESTART_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAITPID = 7 SYS_CREAT = 8 SYS_LINK = 9 SYS_UNLINK = 10 SYS_EXECVE = 11 SYS_CHDIR = 12 SYS_TIME = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 SYS_BREAK = 17 SYS_OLDSTAT = 18 SYS_LSEEK = 19 SYS_GETPID = 20 SYS_MOUNT = 21 SYS_UMOUNT = 22 SYS_SETUID = 23 SYS_GETUID = 24 SYS_STIME = 25 SYS_PTRACE = 26 SYS_ALARM = 27 SYS_OLDFSTAT = 28 SYS_PAUSE = 29 SYS_UTIME = 30 SYS_STTY = 31 SYS_GTTY = 32 SYS_ACCESS = 33 SYS_NICE = 34 SYS_FTIME = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_RENAME = 38 SYS_MKDIR = 39 SYS_RMDIR = 40 SYS_DUP = 41 SYS_PIPE = 42 SYS_TIMES = 43 SYS_PROF = 44 SYS_BRK = 45 SYS_SETGID = 46 SYS_GETGID = 47 SYS_SIGNAL = 48 SYS_GETEUID = 49 SYS_GETEGID = 50 SYS_ACCT = 51 SYS_UMOUNT2 = 52 SYS_LOCK = 53 SYS_IOCTL = 54 SYS_FCNTL = 55 SYS_MPX = 56 SYS_SETPGID = 57 SYS_ULIMIT = 58 SYS_OLDOLDUNAME = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_USTAT = 62 SYS_DUP2 = 63 SYS_GETPPID = 64 SYS_GETPGRP = 65 SYS_SETSID = 66 SYS_SIGACTION = 67 SYS_SGETMASK = 68 SYS_SSETMASK = 69 SYS_SETREUID = 70 SYS_SETREGID = 71 SYS_SIGSUSPEND = 72 SYS_SIGPENDING = 73 SYS_SETHOSTNAME = 74 SYS_SETRLIMIT = 75 SYS_GETRLIMIT = 76 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_GETGROUPS = 80 SYS_SETGROUPS = 81 SYS_SELECT = 82 SYS_SYMLINK = 83 SYS_OLDLSTAT = 84 SYS_READLINK = 85 SYS_USELIB = 86 SYS_SWAPON = 87 SYS_REBOOT = 88 SYS_READDIR = 89 SYS_MMAP = 90 SYS_MUNMAP = 91 SYS_TRUNCATE = 92 SYS_FTRUNCATE = 93 SYS_FCHMOD = 94 SYS_FCHOWN = 95 SYS_GETPRIORITY = 96 SYS_SETPRIORITY = 97 SYS_PROFIL = 98 SYS_STATFS = 99 SYS_FSTATFS = 100 SYS_IOPERM = 101 SYS_SOCKETCALL = 102 SYS_SYSLOG = 103 SYS_SETITIMER = 104 SYS_GETITIMER = 105 SYS_STAT = 106 SYS_LSTAT = 107 SYS_FSTAT = 108 SYS_OLDUNAME = 109 SYS_IOPL = 110 SYS_VHANGUP = 111 SYS_IDLE = 112 SYS_VM86 = 113 SYS_WAIT4 = 114 SYS_SWAPOFF = 115 SYS_SYSINFO = 116 SYS_IPC = 117 SYS_FSYNC = 118 SYS_SIGRETURN = 119 SYS_CLONE = 120 SYS_SETDOMAINNAME = 121 SYS_UNAME = 122 SYS_MODIFY_LDT = 123 SYS_ADJTIMEX = 124 SYS_MPROTECT = 125 SYS_SIGPROCMASK = 126 SYS_CREATE_MODULE = 127 SYS_INIT_MODULE = 128 SYS_DELETE_MODULE = 129 SYS_GET_KERNEL_SYMS = 130 SYS_QUOTACTL = 131 SYS_GETPGID = 132 SYS_FCHDIR = 133 SYS_BDFLUSH = 134 SYS_SYSFS = 135 SYS_PERSONALITY = 136 SYS_AFS_SYSCALL = 137 SYS_SETFSUID = 138 SYS_SETFSGID = 139 SYS__LLSEEK = 140 SYS_GETDENTS = 141 SYS__NEWSELECT = 142 SYS_FLOCK = 143 SYS_MSYNC = 144 SYS_READV = 145 SYS_WRITEV = 146 SYS_GETSID = 147 SYS_FDATASYNC = 148 SYS__SYSCTL = 149 SYS_MLOCK = 150 SYS_MUNLOCK = 151 SYS_MLOCKALL = 152 SYS_MUNLOCKALL = 153 SYS_SCHED_SETPARAM = 154 SYS_SCHED_GETPARAM = 155 SYS_SCHED_SETSCHEDULER = 156 SYS_SCHED_GETSCHEDULER = 157 SYS_SCHED_YIELD = 158 SYS_SCHED_GET_PRIORITY_MAX = 159 SYS_SCHED_GET_PRIORITY_MIN = 160 SYS_SCHED_RR_GET_INTERVAL = 161 SYS_NANOSLEEP = 162 SYS_MREMAP = 163 SYS_SETRESUID = 164 SYS_GETRESUID = 165 SYS_QUERY_MODULE = 166 SYS_POLL = 167 SYS_NFSSERVCTL = 168 SYS_SETRESGID = 169 SYS_GETRESGID = 170 SYS_PRCTL = 171 SYS_RT_SIGRETURN = 172 SYS_RT_SIGACTION = 173 SYS_RT_SIGPROCMASK = 174 SYS_RT_SIGPENDING = 175 SYS_RT_SIGTIMEDWAIT = 176 SYS_RT_SIGQUEUEINFO = 177 SYS_RT_SIGSUSPEND = 178 SYS_PREAD64 = 179 SYS_PWRITE64 = 180 SYS_CHOWN = 181 SYS_GETCWD = 182 SYS_CAPGET = 183 SYS_CAPSET = 184 SYS_SIGALTSTACK = 185 SYS_SENDFILE = 186 SYS_GETPMSG = 187 SYS_PUTPMSG = 188 SYS_VFORK = 189 SYS_UGETRLIMIT = 190 SYS_READAHEAD = 191 SYS_PCICONFIG_READ = 198 SYS_PCICONFIG_WRITE = 199 SYS_PCICONFIG_IOBASE = 200 SYS_MULTIPLEXER = 201 SYS_GETDENTS64 = 202 SYS_PIVOT_ROOT = 203 SYS_MADVISE = 205 SYS_MINCORE = 206 SYS_GETTID = 207 SYS_TKILL = 208 SYS_SETXATTR = 209 SYS_LSETXATTR = 210 SYS_FSETXATTR = 211 SYS_GETXATTR = 212 SYS_LGETXATTR = 213 SYS_FGETXATTR = 214 SYS_LISTXATTR = 215 SYS_LLISTXATTR = 216 SYS_FLISTXATTR = 217 SYS_REMOVEXATTR = 218 SYS_LREMOVEXATTR = 219 SYS_FREMOVEXATTR = 220 SYS_FUTEX = 221 SYS_SCHED_SETAFFINITY = 222 SYS_SCHED_GETAFFINITY = 223 SYS_TUXCALL = 225 SYS_IO_SETUP = 227 SYS_IO_DESTROY = 228 SYS_IO_GETEVENTS = 229 SYS_IO_SUBMIT = 230 SYS_IO_CANCEL = 231 SYS_SET_TID_ADDRESS = 232 SYS_FADVISE64 = 233 SYS_EXIT_GROUP = 234 SYS_LOOKUP_DCOOKIE = 235 SYS_EPOLL_CREATE = 236 SYS_EPOLL_CTL = 237 SYS_EPOLL_WAIT = 238 SYS_REMAP_FILE_PAGES = 239 SYS_TIMER_CREATE = 240 SYS_TIMER_SETTIME = 241 SYS_TIMER_GETTIME = 242 SYS_TIMER_GETOVERRUN = 243 SYS_TIMER_DELETE = 244 SYS_CLOCK_SETTIME = 245 SYS_CLOCK_GETTIME = 246 SYS_CLOCK_GETRES = 247 SYS_CLOCK_NANOSLEEP = 248 SYS_SWAPCONTEXT = 249 SYS_TGKILL = 250 SYS_UTIMES = 251 SYS_STATFS64 = 252 SYS_FSTATFS64 = 253 SYS_RTAS = 255 SYS_SYS_DEBUG_SETCONTEXT = 256 SYS_MIGRATE_PAGES = 258 SYS_MBIND = 259 SYS_GET_MEMPOLICY = 260 SYS_SET_MEMPOLICY = 261 SYS_MQ_OPEN = 262 SYS_MQ_UNLINK = 263 SYS_MQ_TIMEDSEND = 264 SYS_MQ_TIMEDRECEIVE = 265 SYS_MQ_NOTIFY = 266 SYS_MQ_GETSETATTR = 267 SYS_KEXEC_LOAD = 268 SYS_ADD_KEY = 269 SYS_REQUEST_KEY = 270 SYS_KEYCTL = 271 SYS_WAITID = 272 SYS_IOPRIO_SET = 273 SYS_IOPRIO_GET = 274 SYS_INOTIFY_INIT = 275 SYS_INOTIFY_ADD_WATCH = 276 SYS_INOTIFY_RM_WATCH = 277 SYS_SPU_RUN = 278 SYS_SPU_CREATE = 279 SYS_PSELECT6 = 280 SYS_PPOLL = 281 SYS_UNSHARE = 282 SYS_SPLICE = 283 SYS_TEE = 284 SYS_VMSPLICE = 285 SYS_OPENAT = 286 SYS_MKDIRAT = 287 SYS_MKNODAT = 288 SYS_FCHOWNAT = 289 SYS_FUTIMESAT = 290 SYS_NEWFSTATAT = 291 SYS_UNLINKAT = 292 SYS_RENAMEAT = 293 SYS_LINKAT = 294 SYS_SYMLINKAT = 295 SYS_READLINKAT = 296 SYS_FCHMODAT = 297 SYS_FACCESSAT = 298 SYS_GET_ROBUST_LIST = 299 SYS_SET_ROBUST_LIST = 300 SYS_MOVE_PAGES = 301 SYS_GETCPU = 302 SYS_EPOLL_PWAIT = 303 SYS_UTIMENSAT = 304 SYS_SIGNALFD = 305 SYS_TIMERFD_CREATE = 306 SYS_EVENTFD = 307 SYS_SYNC_FILE_RANGE2 = 308 SYS_FALLOCATE = 309 SYS_SUBPAGE_PROT = 310 SYS_TIMERFD_SETTIME = 311 SYS_TIMERFD_GETTIME = 312 SYS_SIGNALFD4 = 313 SYS_EVENTFD2 = 314 SYS_EPOLL_CREATE1 = 315 SYS_DUP3 = 316 SYS_PIPE2 = 317 SYS_INOTIFY_INIT1 = 318 SYS_PERF_EVENT_OPEN = 319 SYS_PREADV = 320 SYS_PWRITEV = 321 SYS_RT_TGSIGQUEUEINFO = 322 SYS_FANOTIFY_INIT = 323 SYS_FANOTIFY_MARK = 324 SYS_PRLIMIT64 = 325 SYS_SOCKET = 326 SYS_BIND = 327 SYS_CONNECT = 328 SYS_LISTEN = 329 SYS_ACCEPT = 330 SYS_GETSOCKNAME = 331 SYS_GETPEERNAME = 332 SYS_SOCKETPAIR = 333 SYS_SEND = 334 SYS_SENDTO = 335 SYS_RECV = 336 SYS_RECVFROM = 337 SYS_SHUTDOWN = 338 SYS_SETSOCKOPT = 339 SYS_GETSOCKOPT = 340 SYS_SENDMSG = 341 SYS_RECVMSG = 342 SYS_RECVMMSG = 343 SYS_ACCEPT4 = 344 SYS_NAME_TO_HANDLE_AT = 345 SYS_OPEN_BY_HANDLE_AT = 346 SYS_CLOCK_ADJTIME = 347 SYS_SYNCFS = 348 SYS_SENDMMSG = 349 SYS_SETNS = 350 SYS_PROCESS_VM_READV = 351 SYS_PROCESS_VM_WRITEV = 352 SYS_FINIT_MODULE = 353 SYS_KCMP = 354 SYS_SCHED_SETATTR = 355 SYS_SCHED_GETATTR = 356 SYS_RENAMEAT2 = 357 SYS_SECCOMP = 358 SYS_GETRANDOM = 359 SYS_MEMFD_CREATE = 360 SYS_BPF = 361 SYS_EXECVEAT = 362 SYS_SWITCH_ENDIAN = 363 SYS_USERFAULTFD = 364 SYS_MEMBARRIER = 365 SYS_MLOCK2 = 378 SYS_COPY_FILE_RANGE = 379 SYS_PREADV2 = 380 SYS_PWRITEV2 = 381 SYS_KEXEC_FILE_LOAD = 382 SYS_STATX = 383 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_mipsle.go0000644061062106075000000003132313172163421026200 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build mipsle,linux package unix const ( SYS_SYSCALL = 4000 SYS_EXIT = 4001 SYS_FORK = 4002 SYS_READ = 4003 SYS_WRITE = 4004 SYS_OPEN = 4005 SYS_CLOSE = 4006 SYS_WAITPID = 4007 SYS_CREAT = 4008 SYS_LINK = 4009 SYS_UNLINK = 4010 SYS_EXECVE = 4011 SYS_CHDIR = 4012 SYS_TIME = 4013 SYS_MKNOD = 4014 SYS_CHMOD = 4015 SYS_LCHOWN = 4016 SYS_BREAK = 4017 SYS_UNUSED18 = 4018 SYS_LSEEK = 4019 SYS_GETPID = 4020 SYS_MOUNT = 4021 SYS_UMOUNT = 4022 SYS_SETUID = 4023 SYS_GETUID = 4024 SYS_STIME = 4025 SYS_PTRACE = 4026 SYS_ALARM = 4027 SYS_UNUSED28 = 4028 SYS_PAUSE = 4029 SYS_UTIME = 4030 SYS_STTY = 4031 SYS_GTTY = 4032 SYS_ACCESS = 4033 SYS_NICE = 4034 SYS_FTIME = 4035 SYS_SYNC = 4036 SYS_KILL = 4037 SYS_RENAME = 4038 SYS_MKDIR = 4039 SYS_RMDIR = 4040 SYS_DUP = 4041 SYS_PIPE = 4042 SYS_TIMES = 4043 SYS_PROF = 4044 SYS_BRK = 4045 SYS_SETGID = 4046 SYS_GETGID = 4047 SYS_SIGNAL = 4048 SYS_GETEUID = 4049 SYS_GETEGID = 4050 SYS_ACCT = 4051 SYS_UMOUNT2 = 4052 SYS_LOCK = 4053 SYS_IOCTL = 4054 SYS_FCNTL = 4055 SYS_MPX = 4056 SYS_SETPGID = 4057 SYS_ULIMIT = 4058 SYS_UNUSED59 = 4059 SYS_UMASK = 4060 SYS_CHROOT = 4061 SYS_USTAT = 4062 SYS_DUP2 = 4063 SYS_GETPPID = 4064 SYS_GETPGRP = 4065 SYS_SETSID = 4066 SYS_SIGACTION = 4067 SYS_SGETMASK = 4068 SYS_SSETMASK = 4069 SYS_SETREUID = 4070 SYS_SETREGID = 4071 SYS_SIGSUSPEND = 4072 SYS_SIGPENDING = 4073 SYS_SETHOSTNAME = 4074 SYS_SETRLIMIT = 4075 SYS_GETRLIMIT = 4076 SYS_GETRUSAGE = 4077 SYS_GETTIMEOFDAY = 4078 SYS_SETTIMEOFDAY = 4079 SYS_GETGROUPS = 4080 SYS_SETGROUPS = 4081 SYS_RESERVED82 = 4082 SYS_SYMLINK = 4083 SYS_UNUSED84 = 4084 SYS_READLINK = 4085 SYS_USELIB = 4086 SYS_SWAPON = 4087 SYS_REBOOT = 4088 SYS_READDIR = 4089 SYS_MMAP = 4090 SYS_MUNMAP = 4091 SYS_TRUNCATE = 4092 SYS_FTRUNCATE = 4093 SYS_FCHMOD = 4094 SYS_FCHOWN = 4095 SYS_GETPRIORITY = 4096 SYS_SETPRIORITY = 4097 SYS_PROFIL = 4098 SYS_STATFS = 4099 SYS_FSTATFS = 4100 SYS_IOPERM = 4101 SYS_SOCKETCALL = 4102 SYS_SYSLOG = 4103 SYS_SETITIMER = 4104 SYS_GETITIMER = 4105 SYS_STAT = 4106 SYS_LSTAT = 4107 SYS_FSTAT = 4108 SYS_UNUSED109 = 4109 SYS_IOPL = 4110 SYS_VHANGUP = 4111 SYS_IDLE = 4112 SYS_VM86 = 4113 SYS_WAIT4 = 4114 SYS_SWAPOFF = 4115 SYS_SYSINFO = 4116 SYS_IPC = 4117 SYS_FSYNC = 4118 SYS_SIGRETURN = 4119 SYS_CLONE = 4120 SYS_SETDOMAINNAME = 4121 SYS_UNAME = 4122 SYS_MODIFY_LDT = 4123 SYS_ADJTIMEX = 4124 SYS_MPROTECT = 4125 SYS_SIGPROCMASK = 4126 SYS_CREATE_MODULE = 4127 SYS_INIT_MODULE = 4128 SYS_DELETE_MODULE = 4129 SYS_GET_KERNEL_SYMS = 4130 SYS_QUOTACTL = 4131 SYS_GETPGID = 4132 SYS_FCHDIR = 4133 SYS_BDFLUSH = 4134 SYS_SYSFS = 4135 SYS_PERSONALITY = 4136 SYS_AFS_SYSCALL = 4137 SYS_SETFSUID = 4138 SYS_SETFSGID = 4139 SYS__LLSEEK = 4140 SYS_GETDENTS = 4141 SYS__NEWSELECT = 4142 SYS_FLOCK = 4143 SYS_MSYNC = 4144 SYS_READV = 4145 SYS_WRITEV = 4146 SYS_CACHEFLUSH = 4147 SYS_CACHECTL = 4148 SYS_SYSMIPS = 4149 SYS_UNUSED150 = 4150 SYS_GETSID = 4151 SYS_FDATASYNC = 4152 SYS__SYSCTL = 4153 SYS_MLOCK = 4154 SYS_MUNLOCK = 4155 SYS_MLOCKALL = 4156 SYS_MUNLOCKALL = 4157 SYS_SCHED_SETPARAM = 4158 SYS_SCHED_GETPARAM = 4159 SYS_SCHED_SETSCHEDULER = 4160 SYS_SCHED_GETSCHEDULER = 4161 SYS_SCHED_YIELD = 4162 SYS_SCHED_GET_PRIORITY_MAX = 4163 SYS_SCHED_GET_PRIORITY_MIN = 4164 SYS_SCHED_RR_GET_INTERVAL = 4165 SYS_NANOSLEEP = 4166 SYS_MREMAP = 4167 SYS_ACCEPT = 4168 SYS_BIND = 4169 SYS_CONNECT = 4170 SYS_GETPEERNAME = 4171 SYS_GETSOCKNAME = 4172 SYS_GETSOCKOPT = 4173 SYS_LISTEN = 4174 SYS_RECV = 4175 SYS_RECVFROM = 4176 SYS_RECVMSG = 4177 SYS_SEND = 4178 SYS_SENDMSG = 4179 SYS_SENDTO = 4180 SYS_SETSOCKOPT = 4181 SYS_SHUTDOWN = 4182 SYS_SOCKET = 4183 SYS_SOCKETPAIR = 4184 SYS_SETRESUID = 4185 SYS_GETRESUID = 4186 SYS_QUERY_MODULE = 4187 SYS_POLL = 4188 SYS_NFSSERVCTL = 4189 SYS_SETRESGID = 4190 SYS_GETRESGID = 4191 SYS_PRCTL = 4192 SYS_RT_SIGRETURN = 4193 SYS_RT_SIGACTION = 4194 SYS_RT_SIGPROCMASK = 4195 SYS_RT_SIGPENDING = 4196 SYS_RT_SIGTIMEDWAIT = 4197 SYS_RT_SIGQUEUEINFO = 4198 SYS_RT_SIGSUSPEND = 4199 SYS_PREAD64 = 4200 SYS_PWRITE64 = 4201 SYS_CHOWN = 4202 SYS_GETCWD = 4203 SYS_CAPGET = 4204 SYS_CAPSET = 4205 SYS_SIGALTSTACK = 4206 SYS_SENDFILE = 4207 SYS_GETPMSG = 4208 SYS_PUTPMSG = 4209 SYS_MMAP2 = 4210 SYS_TRUNCATE64 = 4211 SYS_FTRUNCATE64 = 4212 SYS_STAT64 = 4213 SYS_LSTAT64 = 4214 SYS_FSTAT64 = 4215 SYS_PIVOT_ROOT = 4216 SYS_MINCORE = 4217 SYS_MADVISE = 4218 SYS_GETDENTS64 = 4219 SYS_FCNTL64 = 4220 SYS_RESERVED221 = 4221 SYS_GETTID = 4222 SYS_READAHEAD = 4223 SYS_SETXATTR = 4224 SYS_LSETXATTR = 4225 SYS_FSETXATTR = 4226 SYS_GETXATTR = 4227 SYS_LGETXATTR = 4228 SYS_FGETXATTR = 4229 SYS_LISTXATTR = 4230 SYS_LLISTXATTR = 4231 SYS_FLISTXATTR = 4232 SYS_REMOVEXATTR = 4233 SYS_LREMOVEXATTR = 4234 SYS_FREMOVEXATTR = 4235 SYS_TKILL = 4236 SYS_SENDFILE64 = 4237 SYS_FUTEX = 4238 SYS_SCHED_SETAFFINITY = 4239 SYS_SCHED_GETAFFINITY = 4240 SYS_IO_SETUP = 4241 SYS_IO_DESTROY = 4242 SYS_IO_GETEVENTS = 4243 SYS_IO_SUBMIT = 4244 SYS_IO_CANCEL = 4245 SYS_EXIT_GROUP = 4246 SYS_LOOKUP_DCOOKIE = 4247 SYS_EPOLL_CREATE = 4248 SYS_EPOLL_CTL = 4249 SYS_EPOLL_WAIT = 4250 SYS_REMAP_FILE_PAGES = 4251 SYS_SET_TID_ADDRESS = 4252 SYS_RESTART_SYSCALL = 4253 SYS_FADVISE64 = 4254 SYS_STATFS64 = 4255 SYS_FSTATFS64 = 4256 SYS_TIMER_CREATE = 4257 SYS_TIMER_SETTIME = 4258 SYS_TIMER_GETTIME = 4259 SYS_TIMER_GETOVERRUN = 4260 SYS_TIMER_DELETE = 4261 SYS_CLOCK_SETTIME = 4262 SYS_CLOCK_GETTIME = 4263 SYS_CLOCK_GETRES = 4264 SYS_CLOCK_NANOSLEEP = 4265 SYS_TGKILL = 4266 SYS_UTIMES = 4267 SYS_MBIND = 4268 SYS_GET_MEMPOLICY = 4269 SYS_SET_MEMPOLICY = 4270 SYS_MQ_OPEN = 4271 SYS_MQ_UNLINK = 4272 SYS_MQ_TIMEDSEND = 4273 SYS_MQ_TIMEDRECEIVE = 4274 SYS_MQ_NOTIFY = 4275 SYS_MQ_GETSETATTR = 4276 SYS_VSERVER = 4277 SYS_WAITID = 4278 SYS_ADD_KEY = 4280 SYS_REQUEST_KEY = 4281 SYS_KEYCTL = 4282 SYS_SET_THREAD_AREA = 4283 SYS_INOTIFY_INIT = 4284 SYS_INOTIFY_ADD_WATCH = 4285 SYS_INOTIFY_RM_WATCH = 4286 SYS_MIGRATE_PAGES = 4287 SYS_OPENAT = 4288 SYS_MKDIRAT = 4289 SYS_MKNODAT = 4290 SYS_FCHOWNAT = 4291 SYS_FUTIMESAT = 4292 SYS_FSTATAT64 = 4293 SYS_UNLINKAT = 4294 SYS_RENAMEAT = 4295 SYS_LINKAT = 4296 SYS_SYMLINKAT = 4297 SYS_READLINKAT = 4298 SYS_FCHMODAT = 4299 SYS_FACCESSAT = 4300 SYS_PSELECT6 = 4301 SYS_PPOLL = 4302 SYS_UNSHARE = 4303 SYS_SPLICE = 4304 SYS_SYNC_FILE_RANGE = 4305 SYS_TEE = 4306 SYS_VMSPLICE = 4307 SYS_MOVE_PAGES = 4308 SYS_SET_ROBUST_LIST = 4309 SYS_GET_ROBUST_LIST = 4310 SYS_KEXEC_LOAD = 4311 SYS_GETCPU = 4312 SYS_EPOLL_PWAIT = 4313 SYS_IOPRIO_SET = 4314 SYS_IOPRIO_GET = 4315 SYS_UTIMENSAT = 4316 SYS_SIGNALFD = 4317 SYS_TIMERFD = 4318 SYS_EVENTFD = 4319 SYS_FALLOCATE = 4320 SYS_TIMERFD_CREATE = 4321 SYS_TIMERFD_GETTIME = 4322 SYS_TIMERFD_SETTIME = 4323 SYS_SIGNALFD4 = 4324 SYS_EVENTFD2 = 4325 SYS_EPOLL_CREATE1 = 4326 SYS_DUP3 = 4327 SYS_PIPE2 = 4328 SYS_INOTIFY_INIT1 = 4329 SYS_PREADV = 4330 SYS_PWRITEV = 4331 SYS_RT_TGSIGQUEUEINFO = 4332 SYS_PERF_EVENT_OPEN = 4333 SYS_ACCEPT4 = 4334 SYS_RECVMMSG = 4335 SYS_FANOTIFY_INIT = 4336 SYS_FANOTIFY_MARK = 4337 SYS_PRLIMIT64 = 4338 SYS_NAME_TO_HANDLE_AT = 4339 SYS_OPEN_BY_HANDLE_AT = 4340 SYS_CLOCK_ADJTIME = 4341 SYS_SYNCFS = 4342 SYS_SENDMMSG = 4343 SYS_SETNS = 4344 SYS_PROCESS_VM_READV = 4345 SYS_PROCESS_VM_WRITEV = 4346 SYS_KCMP = 4347 SYS_FINIT_MODULE = 4348 SYS_SCHED_SETATTR = 4349 SYS_SCHED_GETATTR = 4350 SYS_RENAMEAT2 = 4351 SYS_SECCOMP = 4352 SYS_GETRANDOM = 4353 SYS_MEMFD_CREATE = 4354 SYS_BPF = 4355 SYS_EXECVEAT = 4356 SYS_USERFAULTFD = 4357 SYS_MEMBARRIER = 4358 SYS_MLOCK2 = 4359 SYS_COPY_FILE_RANGE = 4360 SYS_PREADV2 = 4361 SYS_PWRITEV2 = 4362 SYS_PKEY_MPROTECT = 4363 SYS_PKEY_ALLOC = 4364 SYS_PKEY_FREE = 4365 SYS_STATX = 4366 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_mips64le.go0000644061062106075000000002653513172163421026363 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips64le,linux package unix const ( SYS_READ = 5000 SYS_WRITE = 5001 SYS_OPEN = 5002 SYS_CLOSE = 5003 SYS_STAT = 5004 SYS_FSTAT = 5005 SYS_LSTAT = 5006 SYS_POLL = 5007 SYS_LSEEK = 5008 SYS_MMAP = 5009 SYS_MPROTECT = 5010 SYS_MUNMAP = 5011 SYS_BRK = 5012 SYS_RT_SIGACTION = 5013 SYS_RT_SIGPROCMASK = 5014 SYS_IOCTL = 5015 SYS_PREAD64 = 5016 SYS_PWRITE64 = 5017 SYS_READV = 5018 SYS_WRITEV = 5019 SYS_ACCESS = 5020 SYS_PIPE = 5021 SYS__NEWSELECT = 5022 SYS_SCHED_YIELD = 5023 SYS_MREMAP = 5024 SYS_MSYNC = 5025 SYS_MINCORE = 5026 SYS_MADVISE = 5027 SYS_SHMGET = 5028 SYS_SHMAT = 5029 SYS_SHMCTL = 5030 SYS_DUP = 5031 SYS_DUP2 = 5032 SYS_PAUSE = 5033 SYS_NANOSLEEP = 5034 SYS_GETITIMER = 5035 SYS_SETITIMER = 5036 SYS_ALARM = 5037 SYS_GETPID = 5038 SYS_SENDFILE = 5039 SYS_SOCKET = 5040 SYS_CONNECT = 5041 SYS_ACCEPT = 5042 SYS_SENDTO = 5043 SYS_RECVFROM = 5044 SYS_SENDMSG = 5045 SYS_RECVMSG = 5046 SYS_SHUTDOWN = 5047 SYS_BIND = 5048 SYS_LISTEN = 5049 SYS_GETSOCKNAME = 5050 SYS_GETPEERNAME = 5051 SYS_SOCKETPAIR = 5052 SYS_SETSOCKOPT = 5053 SYS_GETSOCKOPT = 5054 SYS_CLONE = 5055 SYS_FORK = 5056 SYS_EXECVE = 5057 SYS_EXIT = 5058 SYS_WAIT4 = 5059 SYS_KILL = 5060 SYS_UNAME = 5061 SYS_SEMGET = 5062 SYS_SEMOP = 5063 SYS_SEMCTL = 5064 SYS_SHMDT = 5065 SYS_MSGGET = 5066 SYS_MSGSND = 5067 SYS_MSGRCV = 5068 SYS_MSGCTL = 5069 SYS_FCNTL = 5070 SYS_FLOCK = 5071 SYS_FSYNC = 5072 SYS_FDATASYNC = 5073 SYS_TRUNCATE = 5074 SYS_FTRUNCATE = 5075 SYS_GETDENTS = 5076 SYS_GETCWD = 5077 SYS_CHDIR = 5078 SYS_FCHDIR = 5079 SYS_RENAME = 5080 SYS_MKDIR = 5081 SYS_RMDIR = 5082 SYS_CREAT = 5083 SYS_LINK = 5084 SYS_UNLINK = 5085 SYS_SYMLINK = 5086 SYS_READLINK = 5087 SYS_CHMOD = 5088 SYS_FCHMOD = 5089 SYS_CHOWN = 5090 SYS_FCHOWN = 5091 SYS_LCHOWN = 5092 SYS_UMASK = 5093 SYS_GETTIMEOFDAY = 5094 SYS_GETRLIMIT = 5095 SYS_GETRUSAGE = 5096 SYS_SYSINFO = 5097 SYS_TIMES = 5098 SYS_PTRACE = 5099 SYS_GETUID = 5100 SYS_SYSLOG = 5101 SYS_GETGID = 5102 SYS_SETUID = 5103 SYS_SETGID = 5104 SYS_GETEUID = 5105 SYS_GETEGID = 5106 SYS_SETPGID = 5107 SYS_GETPPID = 5108 SYS_GETPGRP = 5109 SYS_SETSID = 5110 SYS_SETREUID = 5111 SYS_SETREGID = 5112 SYS_GETGROUPS = 5113 SYS_SETGROUPS = 5114 SYS_SETRESUID = 5115 SYS_GETRESUID = 5116 SYS_SETRESGID = 5117 SYS_GETRESGID = 5118 SYS_GETPGID = 5119 SYS_SETFSUID = 5120 SYS_SETFSGID = 5121 SYS_GETSID = 5122 SYS_CAPGET = 5123 SYS_CAPSET = 5124 SYS_RT_SIGPENDING = 5125 SYS_RT_SIGTIMEDWAIT = 5126 SYS_RT_SIGQUEUEINFO = 5127 SYS_RT_SIGSUSPEND = 5128 SYS_SIGALTSTACK = 5129 SYS_UTIME = 5130 SYS_MKNOD = 5131 SYS_PERSONALITY = 5132 SYS_USTAT = 5133 SYS_STATFS = 5134 SYS_FSTATFS = 5135 SYS_SYSFS = 5136 SYS_GETPRIORITY = 5137 SYS_SETPRIORITY = 5138 SYS_SCHED_SETPARAM = 5139 SYS_SCHED_GETPARAM = 5140 SYS_SCHED_SETSCHEDULER = 5141 SYS_SCHED_GETSCHEDULER = 5142 SYS_SCHED_GET_PRIORITY_MAX = 5143 SYS_SCHED_GET_PRIORITY_MIN = 5144 SYS_SCHED_RR_GET_INTERVAL = 5145 SYS_MLOCK = 5146 SYS_MUNLOCK = 5147 SYS_MLOCKALL = 5148 SYS_MUNLOCKALL = 5149 SYS_VHANGUP = 5150 SYS_PIVOT_ROOT = 5151 SYS__SYSCTL = 5152 SYS_PRCTL = 5153 SYS_ADJTIMEX = 5154 SYS_SETRLIMIT = 5155 SYS_CHROOT = 5156 SYS_SYNC = 5157 SYS_ACCT = 5158 SYS_SETTIMEOFDAY = 5159 SYS_MOUNT = 5160 SYS_UMOUNT2 = 5161 SYS_SWAPON = 5162 SYS_SWAPOFF = 5163 SYS_REBOOT = 5164 SYS_SETHOSTNAME = 5165 SYS_SETDOMAINNAME = 5166 SYS_CREATE_MODULE = 5167 SYS_INIT_MODULE = 5168 SYS_DELETE_MODULE = 5169 SYS_GET_KERNEL_SYMS = 5170 SYS_QUERY_MODULE = 5171 SYS_QUOTACTL = 5172 SYS_NFSSERVCTL = 5173 SYS_GETPMSG = 5174 SYS_PUTPMSG = 5175 SYS_AFS_SYSCALL = 5176 SYS_RESERVED177 = 5177 SYS_GETTID = 5178 SYS_READAHEAD = 5179 SYS_SETXATTR = 5180 SYS_LSETXATTR = 5181 SYS_FSETXATTR = 5182 SYS_GETXATTR = 5183 SYS_LGETXATTR = 5184 SYS_FGETXATTR = 5185 SYS_LISTXATTR = 5186 SYS_LLISTXATTR = 5187 SYS_FLISTXATTR = 5188 SYS_REMOVEXATTR = 5189 SYS_LREMOVEXATTR = 5190 SYS_FREMOVEXATTR = 5191 SYS_TKILL = 5192 SYS_RESERVED193 = 5193 SYS_FUTEX = 5194 SYS_SCHED_SETAFFINITY = 5195 SYS_SCHED_GETAFFINITY = 5196 SYS_CACHEFLUSH = 5197 SYS_CACHECTL = 5198 SYS_SYSMIPS = 5199 SYS_IO_SETUP = 5200 SYS_IO_DESTROY = 5201 SYS_IO_GETEVENTS = 5202 SYS_IO_SUBMIT = 5203 SYS_IO_CANCEL = 5204 SYS_EXIT_GROUP = 5205 SYS_LOOKUP_DCOOKIE = 5206 SYS_EPOLL_CREATE = 5207 SYS_EPOLL_CTL = 5208 SYS_EPOLL_WAIT = 5209 SYS_REMAP_FILE_PAGES = 5210 SYS_RT_SIGRETURN = 5211 SYS_SET_TID_ADDRESS = 5212 SYS_RESTART_SYSCALL = 5213 SYS_SEMTIMEDOP = 5214 SYS_FADVISE64 = 5215 SYS_TIMER_CREATE = 5216 SYS_TIMER_SETTIME = 5217 SYS_TIMER_GETTIME = 5218 SYS_TIMER_GETOVERRUN = 5219 SYS_TIMER_DELETE = 5220 SYS_CLOCK_SETTIME = 5221 SYS_CLOCK_GETTIME = 5222 SYS_CLOCK_GETRES = 5223 SYS_CLOCK_NANOSLEEP = 5224 SYS_TGKILL = 5225 SYS_UTIMES = 5226 SYS_MBIND = 5227 SYS_GET_MEMPOLICY = 5228 SYS_SET_MEMPOLICY = 5229 SYS_MQ_OPEN = 5230 SYS_MQ_UNLINK = 5231 SYS_MQ_TIMEDSEND = 5232 SYS_MQ_TIMEDRECEIVE = 5233 SYS_MQ_NOTIFY = 5234 SYS_MQ_GETSETATTR = 5235 SYS_VSERVER = 5236 SYS_WAITID = 5237 SYS_ADD_KEY = 5239 SYS_REQUEST_KEY = 5240 SYS_KEYCTL = 5241 SYS_SET_THREAD_AREA = 5242 SYS_INOTIFY_INIT = 5243 SYS_INOTIFY_ADD_WATCH = 5244 SYS_INOTIFY_RM_WATCH = 5245 SYS_MIGRATE_PAGES = 5246 SYS_OPENAT = 5247 SYS_MKDIRAT = 5248 SYS_MKNODAT = 5249 SYS_FCHOWNAT = 5250 SYS_FUTIMESAT = 5251 SYS_NEWFSTATAT = 5252 SYS_UNLINKAT = 5253 SYS_RENAMEAT = 5254 SYS_LINKAT = 5255 SYS_SYMLINKAT = 5256 SYS_READLINKAT = 5257 SYS_FCHMODAT = 5258 SYS_FACCESSAT = 5259 SYS_PSELECT6 = 5260 SYS_PPOLL = 5261 SYS_UNSHARE = 5262 SYS_SPLICE = 5263 SYS_SYNC_FILE_RANGE = 5264 SYS_TEE = 5265 SYS_VMSPLICE = 5266 SYS_MOVE_PAGES = 5267 SYS_SET_ROBUST_LIST = 5268 SYS_GET_ROBUST_LIST = 5269 SYS_KEXEC_LOAD = 5270 SYS_GETCPU = 5271 SYS_EPOLL_PWAIT = 5272 SYS_IOPRIO_SET = 5273 SYS_IOPRIO_GET = 5274 SYS_UTIMENSAT = 5275 SYS_SIGNALFD = 5276 SYS_TIMERFD = 5277 SYS_EVENTFD = 5278 SYS_FALLOCATE = 5279 SYS_TIMERFD_CREATE = 5280 SYS_TIMERFD_GETTIME = 5281 SYS_TIMERFD_SETTIME = 5282 SYS_SIGNALFD4 = 5283 SYS_EVENTFD2 = 5284 SYS_EPOLL_CREATE1 = 5285 SYS_DUP3 = 5286 SYS_PIPE2 = 5287 SYS_INOTIFY_INIT1 = 5288 SYS_PREADV = 5289 SYS_PWRITEV = 5290 SYS_RT_TGSIGQUEUEINFO = 5291 SYS_PERF_EVENT_OPEN = 5292 SYS_ACCEPT4 = 5293 SYS_RECVMMSG = 5294 SYS_FANOTIFY_INIT = 5295 SYS_FANOTIFY_MARK = 5296 SYS_PRLIMIT64 = 5297 SYS_NAME_TO_HANDLE_AT = 5298 SYS_OPEN_BY_HANDLE_AT = 5299 SYS_CLOCK_ADJTIME = 5300 SYS_SYNCFS = 5301 SYS_SENDMMSG = 5302 SYS_SETNS = 5303 SYS_PROCESS_VM_READV = 5304 SYS_PROCESS_VM_WRITEV = 5305 SYS_KCMP = 5306 SYS_FINIT_MODULE = 5307 SYS_GETDENTS64 = 5308 SYS_SCHED_SETATTR = 5309 SYS_SCHED_GETATTR = 5310 SYS_RENAMEAT2 = 5311 SYS_SECCOMP = 5312 SYS_GETRANDOM = 5313 SYS_MEMFD_CREATE = 5314 SYS_BPF = 5315 SYS_EXECVEAT = 5316 SYS_USERFAULTFD = 5317 SYS_MEMBARRIER = 5318 SYS_MLOCK2 = 5319 SYS_COPY_FILE_RANGE = 5320 SYS_PREADV2 = 5321 SYS_PWRITEV2 = 5322 SYS_PKEY_MPROTECT = 5323 SYS_PKEY_ALLOC = 5324 SYS_PKEY_FREE = 5325 SYS_STATX = 5326 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_mips64.go0000644061062106075000000002653313172163421026040 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips64,linux package unix const ( SYS_READ = 5000 SYS_WRITE = 5001 SYS_OPEN = 5002 SYS_CLOSE = 5003 SYS_STAT = 5004 SYS_FSTAT = 5005 SYS_LSTAT = 5006 SYS_POLL = 5007 SYS_LSEEK = 5008 SYS_MMAP = 5009 SYS_MPROTECT = 5010 SYS_MUNMAP = 5011 SYS_BRK = 5012 SYS_RT_SIGACTION = 5013 SYS_RT_SIGPROCMASK = 5014 SYS_IOCTL = 5015 SYS_PREAD64 = 5016 SYS_PWRITE64 = 5017 SYS_READV = 5018 SYS_WRITEV = 5019 SYS_ACCESS = 5020 SYS_PIPE = 5021 SYS__NEWSELECT = 5022 SYS_SCHED_YIELD = 5023 SYS_MREMAP = 5024 SYS_MSYNC = 5025 SYS_MINCORE = 5026 SYS_MADVISE = 5027 SYS_SHMGET = 5028 SYS_SHMAT = 5029 SYS_SHMCTL = 5030 SYS_DUP = 5031 SYS_DUP2 = 5032 SYS_PAUSE = 5033 SYS_NANOSLEEP = 5034 SYS_GETITIMER = 5035 SYS_SETITIMER = 5036 SYS_ALARM = 5037 SYS_GETPID = 5038 SYS_SENDFILE = 5039 SYS_SOCKET = 5040 SYS_CONNECT = 5041 SYS_ACCEPT = 5042 SYS_SENDTO = 5043 SYS_RECVFROM = 5044 SYS_SENDMSG = 5045 SYS_RECVMSG = 5046 SYS_SHUTDOWN = 5047 SYS_BIND = 5048 SYS_LISTEN = 5049 SYS_GETSOCKNAME = 5050 SYS_GETPEERNAME = 5051 SYS_SOCKETPAIR = 5052 SYS_SETSOCKOPT = 5053 SYS_GETSOCKOPT = 5054 SYS_CLONE = 5055 SYS_FORK = 5056 SYS_EXECVE = 5057 SYS_EXIT = 5058 SYS_WAIT4 = 5059 SYS_KILL = 5060 SYS_UNAME = 5061 SYS_SEMGET = 5062 SYS_SEMOP = 5063 SYS_SEMCTL = 5064 SYS_SHMDT = 5065 SYS_MSGGET = 5066 SYS_MSGSND = 5067 SYS_MSGRCV = 5068 SYS_MSGCTL = 5069 SYS_FCNTL = 5070 SYS_FLOCK = 5071 SYS_FSYNC = 5072 SYS_FDATASYNC = 5073 SYS_TRUNCATE = 5074 SYS_FTRUNCATE = 5075 SYS_GETDENTS = 5076 SYS_GETCWD = 5077 SYS_CHDIR = 5078 SYS_FCHDIR = 5079 SYS_RENAME = 5080 SYS_MKDIR = 5081 SYS_RMDIR = 5082 SYS_CREAT = 5083 SYS_LINK = 5084 SYS_UNLINK = 5085 SYS_SYMLINK = 5086 SYS_READLINK = 5087 SYS_CHMOD = 5088 SYS_FCHMOD = 5089 SYS_CHOWN = 5090 SYS_FCHOWN = 5091 SYS_LCHOWN = 5092 SYS_UMASK = 5093 SYS_GETTIMEOFDAY = 5094 SYS_GETRLIMIT = 5095 SYS_GETRUSAGE = 5096 SYS_SYSINFO = 5097 SYS_TIMES = 5098 SYS_PTRACE = 5099 SYS_GETUID = 5100 SYS_SYSLOG = 5101 SYS_GETGID = 5102 SYS_SETUID = 5103 SYS_SETGID = 5104 SYS_GETEUID = 5105 SYS_GETEGID = 5106 SYS_SETPGID = 5107 SYS_GETPPID = 5108 SYS_GETPGRP = 5109 SYS_SETSID = 5110 SYS_SETREUID = 5111 SYS_SETREGID = 5112 SYS_GETGROUPS = 5113 SYS_SETGROUPS = 5114 SYS_SETRESUID = 5115 SYS_GETRESUID = 5116 SYS_SETRESGID = 5117 SYS_GETRESGID = 5118 SYS_GETPGID = 5119 SYS_SETFSUID = 5120 SYS_SETFSGID = 5121 SYS_GETSID = 5122 SYS_CAPGET = 5123 SYS_CAPSET = 5124 SYS_RT_SIGPENDING = 5125 SYS_RT_SIGTIMEDWAIT = 5126 SYS_RT_SIGQUEUEINFO = 5127 SYS_RT_SIGSUSPEND = 5128 SYS_SIGALTSTACK = 5129 SYS_UTIME = 5130 SYS_MKNOD = 5131 SYS_PERSONALITY = 5132 SYS_USTAT = 5133 SYS_STATFS = 5134 SYS_FSTATFS = 5135 SYS_SYSFS = 5136 SYS_GETPRIORITY = 5137 SYS_SETPRIORITY = 5138 SYS_SCHED_SETPARAM = 5139 SYS_SCHED_GETPARAM = 5140 SYS_SCHED_SETSCHEDULER = 5141 SYS_SCHED_GETSCHEDULER = 5142 SYS_SCHED_GET_PRIORITY_MAX = 5143 SYS_SCHED_GET_PRIORITY_MIN = 5144 SYS_SCHED_RR_GET_INTERVAL = 5145 SYS_MLOCK = 5146 SYS_MUNLOCK = 5147 SYS_MLOCKALL = 5148 SYS_MUNLOCKALL = 5149 SYS_VHANGUP = 5150 SYS_PIVOT_ROOT = 5151 SYS__SYSCTL = 5152 SYS_PRCTL = 5153 SYS_ADJTIMEX = 5154 SYS_SETRLIMIT = 5155 SYS_CHROOT = 5156 SYS_SYNC = 5157 SYS_ACCT = 5158 SYS_SETTIMEOFDAY = 5159 SYS_MOUNT = 5160 SYS_UMOUNT2 = 5161 SYS_SWAPON = 5162 SYS_SWAPOFF = 5163 SYS_REBOOT = 5164 SYS_SETHOSTNAME = 5165 SYS_SETDOMAINNAME = 5166 SYS_CREATE_MODULE = 5167 SYS_INIT_MODULE = 5168 SYS_DELETE_MODULE = 5169 SYS_GET_KERNEL_SYMS = 5170 SYS_QUERY_MODULE = 5171 SYS_QUOTACTL = 5172 SYS_NFSSERVCTL = 5173 SYS_GETPMSG = 5174 SYS_PUTPMSG = 5175 SYS_AFS_SYSCALL = 5176 SYS_RESERVED177 = 5177 SYS_GETTID = 5178 SYS_READAHEAD = 5179 SYS_SETXATTR = 5180 SYS_LSETXATTR = 5181 SYS_FSETXATTR = 5182 SYS_GETXATTR = 5183 SYS_LGETXATTR = 5184 SYS_FGETXATTR = 5185 SYS_LISTXATTR = 5186 SYS_LLISTXATTR = 5187 SYS_FLISTXATTR = 5188 SYS_REMOVEXATTR = 5189 SYS_LREMOVEXATTR = 5190 SYS_FREMOVEXATTR = 5191 SYS_TKILL = 5192 SYS_RESERVED193 = 5193 SYS_FUTEX = 5194 SYS_SCHED_SETAFFINITY = 5195 SYS_SCHED_GETAFFINITY = 5196 SYS_CACHEFLUSH = 5197 SYS_CACHECTL = 5198 SYS_SYSMIPS = 5199 SYS_IO_SETUP = 5200 SYS_IO_DESTROY = 5201 SYS_IO_GETEVENTS = 5202 SYS_IO_SUBMIT = 5203 SYS_IO_CANCEL = 5204 SYS_EXIT_GROUP = 5205 SYS_LOOKUP_DCOOKIE = 5206 SYS_EPOLL_CREATE = 5207 SYS_EPOLL_CTL = 5208 SYS_EPOLL_WAIT = 5209 SYS_REMAP_FILE_PAGES = 5210 SYS_RT_SIGRETURN = 5211 SYS_SET_TID_ADDRESS = 5212 SYS_RESTART_SYSCALL = 5213 SYS_SEMTIMEDOP = 5214 SYS_FADVISE64 = 5215 SYS_TIMER_CREATE = 5216 SYS_TIMER_SETTIME = 5217 SYS_TIMER_GETTIME = 5218 SYS_TIMER_GETOVERRUN = 5219 SYS_TIMER_DELETE = 5220 SYS_CLOCK_SETTIME = 5221 SYS_CLOCK_GETTIME = 5222 SYS_CLOCK_GETRES = 5223 SYS_CLOCK_NANOSLEEP = 5224 SYS_TGKILL = 5225 SYS_UTIMES = 5226 SYS_MBIND = 5227 SYS_GET_MEMPOLICY = 5228 SYS_SET_MEMPOLICY = 5229 SYS_MQ_OPEN = 5230 SYS_MQ_UNLINK = 5231 SYS_MQ_TIMEDSEND = 5232 SYS_MQ_TIMEDRECEIVE = 5233 SYS_MQ_NOTIFY = 5234 SYS_MQ_GETSETATTR = 5235 SYS_VSERVER = 5236 SYS_WAITID = 5237 SYS_ADD_KEY = 5239 SYS_REQUEST_KEY = 5240 SYS_KEYCTL = 5241 SYS_SET_THREAD_AREA = 5242 SYS_INOTIFY_INIT = 5243 SYS_INOTIFY_ADD_WATCH = 5244 SYS_INOTIFY_RM_WATCH = 5245 SYS_MIGRATE_PAGES = 5246 SYS_OPENAT = 5247 SYS_MKDIRAT = 5248 SYS_MKNODAT = 5249 SYS_FCHOWNAT = 5250 SYS_FUTIMESAT = 5251 SYS_NEWFSTATAT = 5252 SYS_UNLINKAT = 5253 SYS_RENAMEAT = 5254 SYS_LINKAT = 5255 SYS_SYMLINKAT = 5256 SYS_READLINKAT = 5257 SYS_FCHMODAT = 5258 SYS_FACCESSAT = 5259 SYS_PSELECT6 = 5260 SYS_PPOLL = 5261 SYS_UNSHARE = 5262 SYS_SPLICE = 5263 SYS_SYNC_FILE_RANGE = 5264 SYS_TEE = 5265 SYS_VMSPLICE = 5266 SYS_MOVE_PAGES = 5267 SYS_SET_ROBUST_LIST = 5268 SYS_GET_ROBUST_LIST = 5269 SYS_KEXEC_LOAD = 5270 SYS_GETCPU = 5271 SYS_EPOLL_PWAIT = 5272 SYS_IOPRIO_SET = 5273 SYS_IOPRIO_GET = 5274 SYS_UTIMENSAT = 5275 SYS_SIGNALFD = 5276 SYS_TIMERFD = 5277 SYS_EVENTFD = 5278 SYS_FALLOCATE = 5279 SYS_TIMERFD_CREATE = 5280 SYS_TIMERFD_GETTIME = 5281 SYS_TIMERFD_SETTIME = 5282 SYS_SIGNALFD4 = 5283 SYS_EVENTFD2 = 5284 SYS_EPOLL_CREATE1 = 5285 SYS_DUP3 = 5286 SYS_PIPE2 = 5287 SYS_INOTIFY_INIT1 = 5288 SYS_PREADV = 5289 SYS_PWRITEV = 5290 SYS_RT_TGSIGQUEUEINFO = 5291 SYS_PERF_EVENT_OPEN = 5292 SYS_ACCEPT4 = 5293 SYS_RECVMMSG = 5294 SYS_FANOTIFY_INIT = 5295 SYS_FANOTIFY_MARK = 5296 SYS_PRLIMIT64 = 5297 SYS_NAME_TO_HANDLE_AT = 5298 SYS_OPEN_BY_HANDLE_AT = 5299 SYS_CLOCK_ADJTIME = 5300 SYS_SYNCFS = 5301 SYS_SENDMMSG = 5302 SYS_SETNS = 5303 SYS_PROCESS_VM_READV = 5304 SYS_PROCESS_VM_WRITEV = 5305 SYS_KCMP = 5306 SYS_FINIT_MODULE = 5307 SYS_GETDENTS64 = 5308 SYS_SCHED_SETATTR = 5309 SYS_SCHED_GETATTR = 5310 SYS_RENAMEAT2 = 5311 SYS_SECCOMP = 5312 SYS_GETRANDOM = 5313 SYS_MEMFD_CREATE = 5314 SYS_BPF = 5315 SYS_EXECVEAT = 5316 SYS_USERFAULTFD = 5317 SYS_MEMBARRIER = 5318 SYS_MLOCK2 = 5319 SYS_COPY_FILE_RANGE = 5320 SYS_PREADV2 = 5321 SYS_PWRITEV2 = 5322 SYS_PKEY_MPROTECT = 5323 SYS_PKEY_ALLOC = 5324 SYS_PKEY_FREE = 5325 SYS_STATX = 5326 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_mips.go0000644061062106075000000003132113172163421025655 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips,linux package unix const ( SYS_SYSCALL = 4000 SYS_EXIT = 4001 SYS_FORK = 4002 SYS_READ = 4003 SYS_WRITE = 4004 SYS_OPEN = 4005 SYS_CLOSE = 4006 SYS_WAITPID = 4007 SYS_CREAT = 4008 SYS_LINK = 4009 SYS_UNLINK = 4010 SYS_EXECVE = 4011 SYS_CHDIR = 4012 SYS_TIME = 4013 SYS_MKNOD = 4014 SYS_CHMOD = 4015 SYS_LCHOWN = 4016 SYS_BREAK = 4017 SYS_UNUSED18 = 4018 SYS_LSEEK = 4019 SYS_GETPID = 4020 SYS_MOUNT = 4021 SYS_UMOUNT = 4022 SYS_SETUID = 4023 SYS_GETUID = 4024 SYS_STIME = 4025 SYS_PTRACE = 4026 SYS_ALARM = 4027 SYS_UNUSED28 = 4028 SYS_PAUSE = 4029 SYS_UTIME = 4030 SYS_STTY = 4031 SYS_GTTY = 4032 SYS_ACCESS = 4033 SYS_NICE = 4034 SYS_FTIME = 4035 SYS_SYNC = 4036 SYS_KILL = 4037 SYS_RENAME = 4038 SYS_MKDIR = 4039 SYS_RMDIR = 4040 SYS_DUP = 4041 SYS_PIPE = 4042 SYS_TIMES = 4043 SYS_PROF = 4044 SYS_BRK = 4045 SYS_SETGID = 4046 SYS_GETGID = 4047 SYS_SIGNAL = 4048 SYS_GETEUID = 4049 SYS_GETEGID = 4050 SYS_ACCT = 4051 SYS_UMOUNT2 = 4052 SYS_LOCK = 4053 SYS_IOCTL = 4054 SYS_FCNTL = 4055 SYS_MPX = 4056 SYS_SETPGID = 4057 SYS_ULIMIT = 4058 SYS_UNUSED59 = 4059 SYS_UMASK = 4060 SYS_CHROOT = 4061 SYS_USTAT = 4062 SYS_DUP2 = 4063 SYS_GETPPID = 4064 SYS_GETPGRP = 4065 SYS_SETSID = 4066 SYS_SIGACTION = 4067 SYS_SGETMASK = 4068 SYS_SSETMASK = 4069 SYS_SETREUID = 4070 SYS_SETREGID = 4071 SYS_SIGSUSPEND = 4072 SYS_SIGPENDING = 4073 SYS_SETHOSTNAME = 4074 SYS_SETRLIMIT = 4075 SYS_GETRLIMIT = 4076 SYS_GETRUSAGE = 4077 SYS_GETTIMEOFDAY = 4078 SYS_SETTIMEOFDAY = 4079 SYS_GETGROUPS = 4080 SYS_SETGROUPS = 4081 SYS_RESERVED82 = 4082 SYS_SYMLINK = 4083 SYS_UNUSED84 = 4084 SYS_READLINK = 4085 SYS_USELIB = 4086 SYS_SWAPON = 4087 SYS_REBOOT = 4088 SYS_READDIR = 4089 SYS_MMAP = 4090 SYS_MUNMAP = 4091 SYS_TRUNCATE = 4092 SYS_FTRUNCATE = 4093 SYS_FCHMOD = 4094 SYS_FCHOWN = 4095 SYS_GETPRIORITY = 4096 SYS_SETPRIORITY = 4097 SYS_PROFIL = 4098 SYS_STATFS = 4099 SYS_FSTATFS = 4100 SYS_IOPERM = 4101 SYS_SOCKETCALL = 4102 SYS_SYSLOG = 4103 SYS_SETITIMER = 4104 SYS_GETITIMER = 4105 SYS_STAT = 4106 SYS_LSTAT = 4107 SYS_FSTAT = 4108 SYS_UNUSED109 = 4109 SYS_IOPL = 4110 SYS_VHANGUP = 4111 SYS_IDLE = 4112 SYS_VM86 = 4113 SYS_WAIT4 = 4114 SYS_SWAPOFF = 4115 SYS_SYSINFO = 4116 SYS_IPC = 4117 SYS_FSYNC = 4118 SYS_SIGRETURN = 4119 SYS_CLONE = 4120 SYS_SETDOMAINNAME = 4121 SYS_UNAME = 4122 SYS_MODIFY_LDT = 4123 SYS_ADJTIMEX = 4124 SYS_MPROTECT = 4125 SYS_SIGPROCMASK = 4126 SYS_CREATE_MODULE = 4127 SYS_INIT_MODULE = 4128 SYS_DELETE_MODULE = 4129 SYS_GET_KERNEL_SYMS = 4130 SYS_QUOTACTL = 4131 SYS_GETPGID = 4132 SYS_FCHDIR = 4133 SYS_BDFLUSH = 4134 SYS_SYSFS = 4135 SYS_PERSONALITY = 4136 SYS_AFS_SYSCALL = 4137 SYS_SETFSUID = 4138 SYS_SETFSGID = 4139 SYS__LLSEEK = 4140 SYS_GETDENTS = 4141 SYS__NEWSELECT = 4142 SYS_FLOCK = 4143 SYS_MSYNC = 4144 SYS_READV = 4145 SYS_WRITEV = 4146 SYS_CACHEFLUSH = 4147 SYS_CACHECTL = 4148 SYS_SYSMIPS = 4149 SYS_UNUSED150 = 4150 SYS_GETSID = 4151 SYS_FDATASYNC = 4152 SYS__SYSCTL = 4153 SYS_MLOCK = 4154 SYS_MUNLOCK = 4155 SYS_MLOCKALL = 4156 SYS_MUNLOCKALL = 4157 SYS_SCHED_SETPARAM = 4158 SYS_SCHED_GETPARAM = 4159 SYS_SCHED_SETSCHEDULER = 4160 SYS_SCHED_GETSCHEDULER = 4161 SYS_SCHED_YIELD = 4162 SYS_SCHED_GET_PRIORITY_MAX = 4163 SYS_SCHED_GET_PRIORITY_MIN = 4164 SYS_SCHED_RR_GET_INTERVAL = 4165 SYS_NANOSLEEP = 4166 SYS_MREMAP = 4167 SYS_ACCEPT = 4168 SYS_BIND = 4169 SYS_CONNECT = 4170 SYS_GETPEERNAME = 4171 SYS_GETSOCKNAME = 4172 SYS_GETSOCKOPT = 4173 SYS_LISTEN = 4174 SYS_RECV = 4175 SYS_RECVFROM = 4176 SYS_RECVMSG = 4177 SYS_SEND = 4178 SYS_SENDMSG = 4179 SYS_SENDTO = 4180 SYS_SETSOCKOPT = 4181 SYS_SHUTDOWN = 4182 SYS_SOCKET = 4183 SYS_SOCKETPAIR = 4184 SYS_SETRESUID = 4185 SYS_GETRESUID = 4186 SYS_QUERY_MODULE = 4187 SYS_POLL = 4188 SYS_NFSSERVCTL = 4189 SYS_SETRESGID = 4190 SYS_GETRESGID = 4191 SYS_PRCTL = 4192 SYS_RT_SIGRETURN = 4193 SYS_RT_SIGACTION = 4194 SYS_RT_SIGPROCMASK = 4195 SYS_RT_SIGPENDING = 4196 SYS_RT_SIGTIMEDWAIT = 4197 SYS_RT_SIGQUEUEINFO = 4198 SYS_RT_SIGSUSPEND = 4199 SYS_PREAD64 = 4200 SYS_PWRITE64 = 4201 SYS_CHOWN = 4202 SYS_GETCWD = 4203 SYS_CAPGET = 4204 SYS_CAPSET = 4205 SYS_SIGALTSTACK = 4206 SYS_SENDFILE = 4207 SYS_GETPMSG = 4208 SYS_PUTPMSG = 4209 SYS_MMAP2 = 4210 SYS_TRUNCATE64 = 4211 SYS_FTRUNCATE64 = 4212 SYS_STAT64 = 4213 SYS_LSTAT64 = 4214 SYS_FSTAT64 = 4215 SYS_PIVOT_ROOT = 4216 SYS_MINCORE = 4217 SYS_MADVISE = 4218 SYS_GETDENTS64 = 4219 SYS_FCNTL64 = 4220 SYS_RESERVED221 = 4221 SYS_GETTID = 4222 SYS_READAHEAD = 4223 SYS_SETXATTR = 4224 SYS_LSETXATTR = 4225 SYS_FSETXATTR = 4226 SYS_GETXATTR = 4227 SYS_LGETXATTR = 4228 SYS_FGETXATTR = 4229 SYS_LISTXATTR = 4230 SYS_LLISTXATTR = 4231 SYS_FLISTXATTR = 4232 SYS_REMOVEXATTR = 4233 SYS_LREMOVEXATTR = 4234 SYS_FREMOVEXATTR = 4235 SYS_TKILL = 4236 SYS_SENDFILE64 = 4237 SYS_FUTEX = 4238 SYS_SCHED_SETAFFINITY = 4239 SYS_SCHED_GETAFFINITY = 4240 SYS_IO_SETUP = 4241 SYS_IO_DESTROY = 4242 SYS_IO_GETEVENTS = 4243 SYS_IO_SUBMIT = 4244 SYS_IO_CANCEL = 4245 SYS_EXIT_GROUP = 4246 SYS_LOOKUP_DCOOKIE = 4247 SYS_EPOLL_CREATE = 4248 SYS_EPOLL_CTL = 4249 SYS_EPOLL_WAIT = 4250 SYS_REMAP_FILE_PAGES = 4251 SYS_SET_TID_ADDRESS = 4252 SYS_RESTART_SYSCALL = 4253 SYS_FADVISE64 = 4254 SYS_STATFS64 = 4255 SYS_FSTATFS64 = 4256 SYS_TIMER_CREATE = 4257 SYS_TIMER_SETTIME = 4258 SYS_TIMER_GETTIME = 4259 SYS_TIMER_GETOVERRUN = 4260 SYS_TIMER_DELETE = 4261 SYS_CLOCK_SETTIME = 4262 SYS_CLOCK_GETTIME = 4263 SYS_CLOCK_GETRES = 4264 SYS_CLOCK_NANOSLEEP = 4265 SYS_TGKILL = 4266 SYS_UTIMES = 4267 SYS_MBIND = 4268 SYS_GET_MEMPOLICY = 4269 SYS_SET_MEMPOLICY = 4270 SYS_MQ_OPEN = 4271 SYS_MQ_UNLINK = 4272 SYS_MQ_TIMEDSEND = 4273 SYS_MQ_TIMEDRECEIVE = 4274 SYS_MQ_NOTIFY = 4275 SYS_MQ_GETSETATTR = 4276 SYS_VSERVER = 4277 SYS_WAITID = 4278 SYS_ADD_KEY = 4280 SYS_REQUEST_KEY = 4281 SYS_KEYCTL = 4282 SYS_SET_THREAD_AREA = 4283 SYS_INOTIFY_INIT = 4284 SYS_INOTIFY_ADD_WATCH = 4285 SYS_INOTIFY_RM_WATCH = 4286 SYS_MIGRATE_PAGES = 4287 SYS_OPENAT = 4288 SYS_MKDIRAT = 4289 SYS_MKNODAT = 4290 SYS_FCHOWNAT = 4291 SYS_FUTIMESAT = 4292 SYS_FSTATAT64 = 4293 SYS_UNLINKAT = 4294 SYS_RENAMEAT = 4295 SYS_LINKAT = 4296 SYS_SYMLINKAT = 4297 SYS_READLINKAT = 4298 SYS_FCHMODAT = 4299 SYS_FACCESSAT = 4300 SYS_PSELECT6 = 4301 SYS_PPOLL = 4302 SYS_UNSHARE = 4303 SYS_SPLICE = 4304 SYS_SYNC_FILE_RANGE = 4305 SYS_TEE = 4306 SYS_VMSPLICE = 4307 SYS_MOVE_PAGES = 4308 SYS_SET_ROBUST_LIST = 4309 SYS_GET_ROBUST_LIST = 4310 SYS_KEXEC_LOAD = 4311 SYS_GETCPU = 4312 SYS_EPOLL_PWAIT = 4313 SYS_IOPRIO_SET = 4314 SYS_IOPRIO_GET = 4315 SYS_UTIMENSAT = 4316 SYS_SIGNALFD = 4317 SYS_TIMERFD = 4318 SYS_EVENTFD = 4319 SYS_FALLOCATE = 4320 SYS_TIMERFD_CREATE = 4321 SYS_TIMERFD_GETTIME = 4322 SYS_TIMERFD_SETTIME = 4323 SYS_SIGNALFD4 = 4324 SYS_EVENTFD2 = 4325 SYS_EPOLL_CREATE1 = 4326 SYS_DUP3 = 4327 SYS_PIPE2 = 4328 SYS_INOTIFY_INIT1 = 4329 SYS_PREADV = 4330 SYS_PWRITEV = 4331 SYS_RT_TGSIGQUEUEINFO = 4332 SYS_PERF_EVENT_OPEN = 4333 SYS_ACCEPT4 = 4334 SYS_RECVMMSG = 4335 SYS_FANOTIFY_INIT = 4336 SYS_FANOTIFY_MARK = 4337 SYS_PRLIMIT64 = 4338 SYS_NAME_TO_HANDLE_AT = 4339 SYS_OPEN_BY_HANDLE_AT = 4340 SYS_CLOCK_ADJTIME = 4341 SYS_SYNCFS = 4342 SYS_SENDMMSG = 4343 SYS_SETNS = 4344 SYS_PROCESS_VM_READV = 4345 SYS_PROCESS_VM_WRITEV = 4346 SYS_KCMP = 4347 SYS_FINIT_MODULE = 4348 SYS_SCHED_SETATTR = 4349 SYS_SCHED_GETATTR = 4350 SYS_RENAMEAT2 = 4351 SYS_SECCOMP = 4352 SYS_GETRANDOM = 4353 SYS_MEMFD_CREATE = 4354 SYS_BPF = 4355 SYS_EXECVEAT = 4356 SYS_USERFAULTFD = 4357 SYS_MEMBARRIER = 4358 SYS_MLOCK2 = 4359 SYS_COPY_FILE_RANGE = 4360 SYS_PREADV2 = 4361 SYS_PWRITEV2 = 4362 SYS_PKEY_MPROTECT = 4363 SYS_PKEY_ALLOC = 4364 SYS_PKEY_FREE = 4365 SYS_STATX = 4366 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_arm64.go0000644061062106075000000002246213172163421025644 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -fsigned-char /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm64,linux package unix const ( SYS_IO_SETUP = 0 SYS_IO_DESTROY = 1 SYS_IO_SUBMIT = 2 SYS_IO_CANCEL = 3 SYS_IO_GETEVENTS = 4 SYS_SETXATTR = 5 SYS_LSETXATTR = 6 SYS_FSETXATTR = 7 SYS_GETXATTR = 8 SYS_LGETXATTR = 9 SYS_FGETXATTR = 10 SYS_LISTXATTR = 11 SYS_LLISTXATTR = 12 SYS_FLISTXATTR = 13 SYS_REMOVEXATTR = 14 SYS_LREMOVEXATTR = 15 SYS_FREMOVEXATTR = 16 SYS_GETCWD = 17 SYS_LOOKUP_DCOOKIE = 18 SYS_EVENTFD2 = 19 SYS_EPOLL_CREATE1 = 20 SYS_EPOLL_CTL = 21 SYS_EPOLL_PWAIT = 22 SYS_DUP = 23 SYS_DUP3 = 24 SYS_FCNTL = 25 SYS_INOTIFY_INIT1 = 26 SYS_INOTIFY_ADD_WATCH = 27 SYS_INOTIFY_RM_WATCH = 28 SYS_IOCTL = 29 SYS_IOPRIO_SET = 30 SYS_IOPRIO_GET = 31 SYS_FLOCK = 32 SYS_MKNODAT = 33 SYS_MKDIRAT = 34 SYS_UNLINKAT = 35 SYS_SYMLINKAT = 36 SYS_LINKAT = 37 SYS_RENAMEAT = 38 SYS_UMOUNT2 = 39 SYS_MOUNT = 40 SYS_PIVOT_ROOT = 41 SYS_NFSSERVCTL = 42 SYS_STATFS = 43 SYS_FSTATFS = 44 SYS_TRUNCATE = 45 SYS_FTRUNCATE = 46 SYS_FALLOCATE = 47 SYS_FACCESSAT = 48 SYS_CHDIR = 49 SYS_FCHDIR = 50 SYS_CHROOT = 51 SYS_FCHMOD = 52 SYS_FCHMODAT = 53 SYS_FCHOWNAT = 54 SYS_FCHOWN = 55 SYS_OPENAT = 56 SYS_CLOSE = 57 SYS_VHANGUP = 58 SYS_PIPE2 = 59 SYS_QUOTACTL = 60 SYS_GETDENTS64 = 61 SYS_LSEEK = 62 SYS_READ = 63 SYS_WRITE = 64 SYS_READV = 65 SYS_WRITEV = 66 SYS_PREAD64 = 67 SYS_PWRITE64 = 68 SYS_PREADV = 69 SYS_PWRITEV = 70 SYS_SENDFILE = 71 SYS_PSELECT6 = 72 SYS_PPOLL = 73 SYS_SIGNALFD4 = 74 SYS_VMSPLICE = 75 SYS_SPLICE = 76 SYS_TEE = 77 SYS_READLINKAT = 78 SYS_FSTATAT = 79 SYS_FSTAT = 80 SYS_SYNC = 81 SYS_FSYNC = 82 SYS_FDATASYNC = 83 SYS_SYNC_FILE_RANGE = 84 SYS_TIMERFD_CREATE = 85 SYS_TIMERFD_SETTIME = 86 SYS_TIMERFD_GETTIME = 87 SYS_UTIMENSAT = 88 SYS_ACCT = 89 SYS_CAPGET = 90 SYS_CAPSET = 91 SYS_PERSONALITY = 92 SYS_EXIT = 93 SYS_EXIT_GROUP = 94 SYS_WAITID = 95 SYS_SET_TID_ADDRESS = 96 SYS_UNSHARE = 97 SYS_FUTEX = 98 SYS_SET_ROBUST_LIST = 99 SYS_GET_ROBUST_LIST = 100 SYS_NANOSLEEP = 101 SYS_GETITIMER = 102 SYS_SETITIMER = 103 SYS_KEXEC_LOAD = 104 SYS_INIT_MODULE = 105 SYS_DELETE_MODULE = 106 SYS_TIMER_CREATE = 107 SYS_TIMER_GETTIME = 108 SYS_TIMER_GETOVERRUN = 109 SYS_TIMER_SETTIME = 110 SYS_TIMER_DELETE = 111 SYS_CLOCK_SETTIME = 112 SYS_CLOCK_GETTIME = 113 SYS_CLOCK_GETRES = 114 SYS_CLOCK_NANOSLEEP = 115 SYS_SYSLOG = 116 SYS_PTRACE = 117 SYS_SCHED_SETPARAM = 118 SYS_SCHED_SETSCHEDULER = 119 SYS_SCHED_GETSCHEDULER = 120 SYS_SCHED_GETPARAM = 121 SYS_SCHED_SETAFFINITY = 122 SYS_SCHED_GETAFFINITY = 123 SYS_SCHED_YIELD = 124 SYS_SCHED_GET_PRIORITY_MAX = 125 SYS_SCHED_GET_PRIORITY_MIN = 126 SYS_SCHED_RR_GET_INTERVAL = 127 SYS_RESTART_SYSCALL = 128 SYS_KILL = 129 SYS_TKILL = 130 SYS_TGKILL = 131 SYS_SIGALTSTACK = 132 SYS_RT_SIGSUSPEND = 133 SYS_RT_SIGACTION = 134 SYS_RT_SIGPROCMASK = 135 SYS_RT_SIGPENDING = 136 SYS_RT_SIGTIMEDWAIT = 137 SYS_RT_SIGQUEUEINFO = 138 SYS_RT_SIGRETURN = 139 SYS_SETPRIORITY = 140 SYS_GETPRIORITY = 141 SYS_REBOOT = 142 SYS_SETREGID = 143 SYS_SETGID = 144 SYS_SETREUID = 145 SYS_SETUID = 146 SYS_SETRESUID = 147 SYS_GETRESUID = 148 SYS_SETRESGID = 149 SYS_GETRESGID = 150 SYS_SETFSUID = 151 SYS_SETFSGID = 152 SYS_TIMES = 153 SYS_SETPGID = 154 SYS_GETPGID = 155 SYS_GETSID = 156 SYS_SETSID = 157 SYS_GETGROUPS = 158 SYS_SETGROUPS = 159 SYS_UNAME = 160 SYS_SETHOSTNAME = 161 SYS_SETDOMAINNAME = 162 SYS_GETRLIMIT = 163 SYS_SETRLIMIT = 164 SYS_GETRUSAGE = 165 SYS_UMASK = 166 SYS_PRCTL = 167 SYS_GETCPU = 168 SYS_GETTIMEOFDAY = 169 SYS_SETTIMEOFDAY = 170 SYS_ADJTIMEX = 171 SYS_GETPID = 172 SYS_GETPPID = 173 SYS_GETUID = 174 SYS_GETEUID = 175 SYS_GETGID = 176 SYS_GETEGID = 177 SYS_GETTID = 178 SYS_SYSINFO = 179 SYS_MQ_OPEN = 180 SYS_MQ_UNLINK = 181 SYS_MQ_TIMEDSEND = 182 SYS_MQ_TIMEDRECEIVE = 183 SYS_MQ_NOTIFY = 184 SYS_MQ_GETSETATTR = 185 SYS_MSGGET = 186 SYS_MSGCTL = 187 SYS_MSGRCV = 188 SYS_MSGSND = 189 SYS_SEMGET = 190 SYS_SEMCTL = 191 SYS_SEMTIMEDOP = 192 SYS_SEMOP = 193 SYS_SHMGET = 194 SYS_SHMCTL = 195 SYS_SHMAT = 196 SYS_SHMDT = 197 SYS_SOCKET = 198 SYS_SOCKETPAIR = 199 SYS_BIND = 200 SYS_LISTEN = 201 SYS_ACCEPT = 202 SYS_CONNECT = 203 SYS_GETSOCKNAME = 204 SYS_GETPEERNAME = 205 SYS_SENDTO = 206 SYS_RECVFROM = 207 SYS_SETSOCKOPT = 208 SYS_GETSOCKOPT = 209 SYS_SHUTDOWN = 210 SYS_SENDMSG = 211 SYS_RECVMSG = 212 SYS_READAHEAD = 213 SYS_BRK = 214 SYS_MUNMAP = 215 SYS_MREMAP = 216 SYS_ADD_KEY = 217 SYS_REQUEST_KEY = 218 SYS_KEYCTL = 219 SYS_CLONE = 220 SYS_EXECVE = 221 SYS_MMAP = 222 SYS_FADVISE64 = 223 SYS_SWAPON = 224 SYS_SWAPOFF = 225 SYS_MPROTECT = 226 SYS_MSYNC = 227 SYS_MLOCK = 228 SYS_MUNLOCK = 229 SYS_MLOCKALL = 230 SYS_MUNLOCKALL = 231 SYS_MINCORE = 232 SYS_MADVISE = 233 SYS_REMAP_FILE_PAGES = 234 SYS_MBIND = 235 SYS_GET_MEMPOLICY = 236 SYS_SET_MEMPOLICY = 237 SYS_MIGRATE_PAGES = 238 SYS_MOVE_PAGES = 239 SYS_RT_TGSIGQUEUEINFO = 240 SYS_PERF_EVENT_OPEN = 241 SYS_ACCEPT4 = 242 SYS_RECVMMSG = 243 SYS_ARCH_SPECIFIC_SYSCALL = 244 SYS_WAIT4 = 260 SYS_PRLIMIT64 = 261 SYS_FANOTIFY_INIT = 262 SYS_FANOTIFY_MARK = 263 SYS_NAME_TO_HANDLE_AT = 264 SYS_OPEN_BY_HANDLE_AT = 265 SYS_CLOCK_ADJTIME = 266 SYS_SYNCFS = 267 SYS_SETNS = 268 SYS_SENDMMSG = 269 SYS_PROCESS_VM_READV = 270 SYS_PROCESS_VM_WRITEV = 271 SYS_KCMP = 272 SYS_FINIT_MODULE = 273 SYS_SCHED_SETATTR = 274 SYS_SCHED_GETATTR = 275 SYS_RENAMEAT2 = 276 SYS_SECCOMP = 277 SYS_GETRANDOM = 278 SYS_MEMFD_CREATE = 279 SYS_BPF = 280 SYS_EXECVEAT = 281 SYS_USERFAULTFD = 282 SYS_MEMBARRIER = 283 SYS_MLOCK2 = 284 SYS_COPY_FILE_RANGE = 285 SYS_PREADV2 = 286 SYS_PWRITEV2 = 287 SYS_PKEY_MPROTECT = 288 SYS_PKEY_ALLOC = 289 SYS_PKEY_FREE = 290 SYS_STATX = 291 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_arm.go0000644061062106075000000002752513172163421025477 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,linux package unix const ( SYS_RESTART_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_CREAT = 8 SYS_LINK = 9 SYS_UNLINK = 10 SYS_EXECVE = 11 SYS_CHDIR = 12 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 SYS_LSEEK = 19 SYS_GETPID = 20 SYS_MOUNT = 21 SYS_SETUID = 23 SYS_GETUID = 24 SYS_PTRACE = 26 SYS_PAUSE = 29 SYS_ACCESS = 33 SYS_NICE = 34 SYS_SYNC = 36 SYS_KILL = 37 SYS_RENAME = 38 SYS_MKDIR = 39 SYS_RMDIR = 40 SYS_DUP = 41 SYS_PIPE = 42 SYS_TIMES = 43 SYS_BRK = 45 SYS_SETGID = 46 SYS_GETGID = 47 SYS_GETEUID = 49 SYS_GETEGID = 50 SYS_ACCT = 51 SYS_UMOUNT2 = 52 SYS_IOCTL = 54 SYS_FCNTL = 55 SYS_SETPGID = 57 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_USTAT = 62 SYS_DUP2 = 63 SYS_GETPPID = 64 SYS_GETPGRP = 65 SYS_SETSID = 66 SYS_SIGACTION = 67 SYS_SETREUID = 70 SYS_SETREGID = 71 SYS_SIGSUSPEND = 72 SYS_SIGPENDING = 73 SYS_SETHOSTNAME = 74 SYS_SETRLIMIT = 75 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_GETGROUPS = 80 SYS_SETGROUPS = 81 SYS_SYMLINK = 83 SYS_READLINK = 85 SYS_USELIB = 86 SYS_SWAPON = 87 SYS_REBOOT = 88 SYS_MUNMAP = 91 SYS_TRUNCATE = 92 SYS_FTRUNCATE = 93 SYS_FCHMOD = 94 SYS_FCHOWN = 95 SYS_GETPRIORITY = 96 SYS_SETPRIORITY = 97 SYS_STATFS = 99 SYS_FSTATFS = 100 SYS_SYSLOG = 103 SYS_SETITIMER = 104 SYS_GETITIMER = 105 SYS_STAT = 106 SYS_LSTAT = 107 SYS_FSTAT = 108 SYS_VHANGUP = 111 SYS_WAIT4 = 114 SYS_SWAPOFF = 115 SYS_SYSINFO = 116 SYS_FSYNC = 118 SYS_SIGRETURN = 119 SYS_CLONE = 120 SYS_SETDOMAINNAME = 121 SYS_UNAME = 122 SYS_ADJTIMEX = 124 SYS_MPROTECT = 125 SYS_SIGPROCMASK = 126 SYS_INIT_MODULE = 128 SYS_DELETE_MODULE = 129 SYS_QUOTACTL = 131 SYS_GETPGID = 132 SYS_FCHDIR = 133 SYS_BDFLUSH = 134 SYS_SYSFS = 135 SYS_PERSONALITY = 136 SYS_SETFSUID = 138 SYS_SETFSGID = 139 SYS__LLSEEK = 140 SYS_GETDENTS = 141 SYS__NEWSELECT = 142 SYS_FLOCK = 143 SYS_MSYNC = 144 SYS_READV = 145 SYS_WRITEV = 146 SYS_GETSID = 147 SYS_FDATASYNC = 148 SYS__SYSCTL = 149 SYS_MLOCK = 150 SYS_MUNLOCK = 151 SYS_MLOCKALL = 152 SYS_MUNLOCKALL = 153 SYS_SCHED_SETPARAM = 154 SYS_SCHED_GETPARAM = 155 SYS_SCHED_SETSCHEDULER = 156 SYS_SCHED_GETSCHEDULER = 157 SYS_SCHED_YIELD = 158 SYS_SCHED_GET_PRIORITY_MAX = 159 SYS_SCHED_GET_PRIORITY_MIN = 160 SYS_SCHED_RR_GET_INTERVAL = 161 SYS_NANOSLEEP = 162 SYS_MREMAP = 163 SYS_SETRESUID = 164 SYS_GETRESUID = 165 SYS_POLL = 168 SYS_NFSSERVCTL = 169 SYS_SETRESGID = 170 SYS_GETRESGID = 171 SYS_PRCTL = 172 SYS_RT_SIGRETURN = 173 SYS_RT_SIGACTION = 174 SYS_RT_SIGPROCMASK = 175 SYS_RT_SIGPENDING = 176 SYS_RT_SIGTIMEDWAIT = 177 SYS_RT_SIGQUEUEINFO = 178 SYS_RT_SIGSUSPEND = 179 SYS_PREAD64 = 180 SYS_PWRITE64 = 181 SYS_CHOWN = 182 SYS_GETCWD = 183 SYS_CAPGET = 184 SYS_CAPSET = 185 SYS_SIGALTSTACK = 186 SYS_SENDFILE = 187 SYS_VFORK = 190 SYS_UGETRLIMIT = 191 SYS_MMAP2 = 192 SYS_TRUNCATE64 = 193 SYS_FTRUNCATE64 = 194 SYS_STAT64 = 195 SYS_LSTAT64 = 196 SYS_FSTAT64 = 197 SYS_LCHOWN32 = 198 SYS_GETUID32 = 199 SYS_GETGID32 = 200 SYS_GETEUID32 = 201 SYS_GETEGID32 = 202 SYS_SETREUID32 = 203 SYS_SETREGID32 = 204 SYS_GETGROUPS32 = 205 SYS_SETGROUPS32 = 206 SYS_FCHOWN32 = 207 SYS_SETRESUID32 = 208 SYS_GETRESUID32 = 209 SYS_SETRESGID32 = 210 SYS_GETRESGID32 = 211 SYS_CHOWN32 = 212 SYS_SETUID32 = 213 SYS_SETGID32 = 214 SYS_SETFSUID32 = 215 SYS_SETFSGID32 = 216 SYS_GETDENTS64 = 217 SYS_PIVOT_ROOT = 218 SYS_MINCORE = 219 SYS_MADVISE = 220 SYS_FCNTL64 = 221 SYS_GETTID = 224 SYS_READAHEAD = 225 SYS_SETXATTR = 226 SYS_LSETXATTR = 227 SYS_FSETXATTR = 228 SYS_GETXATTR = 229 SYS_LGETXATTR = 230 SYS_FGETXATTR = 231 SYS_LISTXATTR = 232 SYS_LLISTXATTR = 233 SYS_FLISTXATTR = 234 SYS_REMOVEXATTR = 235 SYS_LREMOVEXATTR = 236 SYS_FREMOVEXATTR = 237 SYS_TKILL = 238 SYS_SENDFILE64 = 239 SYS_FUTEX = 240 SYS_SCHED_SETAFFINITY = 241 SYS_SCHED_GETAFFINITY = 242 SYS_IO_SETUP = 243 SYS_IO_DESTROY = 244 SYS_IO_GETEVENTS = 245 SYS_IO_SUBMIT = 246 SYS_IO_CANCEL = 247 SYS_EXIT_GROUP = 248 SYS_LOOKUP_DCOOKIE = 249 SYS_EPOLL_CREATE = 250 SYS_EPOLL_CTL = 251 SYS_EPOLL_WAIT = 252 SYS_REMAP_FILE_PAGES = 253 SYS_SET_TID_ADDRESS = 256 SYS_TIMER_CREATE = 257 SYS_TIMER_SETTIME = 258 SYS_TIMER_GETTIME = 259 SYS_TIMER_GETOVERRUN = 260 SYS_TIMER_DELETE = 261 SYS_CLOCK_SETTIME = 262 SYS_CLOCK_GETTIME = 263 SYS_CLOCK_GETRES = 264 SYS_CLOCK_NANOSLEEP = 265 SYS_STATFS64 = 266 SYS_FSTATFS64 = 267 SYS_TGKILL = 268 SYS_UTIMES = 269 SYS_ARM_FADVISE64_64 = 270 SYS_PCICONFIG_IOBASE = 271 SYS_PCICONFIG_READ = 272 SYS_PCICONFIG_WRITE = 273 SYS_MQ_OPEN = 274 SYS_MQ_UNLINK = 275 SYS_MQ_TIMEDSEND = 276 SYS_MQ_TIMEDRECEIVE = 277 SYS_MQ_NOTIFY = 278 SYS_MQ_GETSETATTR = 279 SYS_WAITID = 280 SYS_SOCKET = 281 SYS_BIND = 282 SYS_CONNECT = 283 SYS_LISTEN = 284 SYS_ACCEPT = 285 SYS_GETSOCKNAME = 286 SYS_GETPEERNAME = 287 SYS_SOCKETPAIR = 288 SYS_SEND = 289 SYS_SENDTO = 290 SYS_RECV = 291 SYS_RECVFROM = 292 SYS_SHUTDOWN = 293 SYS_SETSOCKOPT = 294 SYS_GETSOCKOPT = 295 SYS_SENDMSG = 296 SYS_RECVMSG = 297 SYS_SEMOP = 298 SYS_SEMGET = 299 SYS_SEMCTL = 300 SYS_MSGSND = 301 SYS_MSGRCV = 302 SYS_MSGGET = 303 SYS_MSGCTL = 304 SYS_SHMAT = 305 SYS_SHMDT = 306 SYS_SHMGET = 307 SYS_SHMCTL = 308 SYS_ADD_KEY = 309 SYS_REQUEST_KEY = 310 SYS_KEYCTL = 311 SYS_SEMTIMEDOP = 312 SYS_VSERVER = 313 SYS_IOPRIO_SET = 314 SYS_IOPRIO_GET = 315 SYS_INOTIFY_INIT = 316 SYS_INOTIFY_ADD_WATCH = 317 SYS_INOTIFY_RM_WATCH = 318 SYS_MBIND = 319 SYS_GET_MEMPOLICY = 320 SYS_SET_MEMPOLICY = 321 SYS_OPENAT = 322 SYS_MKDIRAT = 323 SYS_MKNODAT = 324 SYS_FCHOWNAT = 325 SYS_FUTIMESAT = 326 SYS_FSTATAT64 = 327 SYS_UNLINKAT = 328 SYS_RENAMEAT = 329 SYS_LINKAT = 330 SYS_SYMLINKAT = 331 SYS_READLINKAT = 332 SYS_FCHMODAT = 333 SYS_FACCESSAT = 334 SYS_PSELECT6 = 335 SYS_PPOLL = 336 SYS_UNSHARE = 337 SYS_SET_ROBUST_LIST = 338 SYS_GET_ROBUST_LIST = 339 SYS_SPLICE = 340 SYS_ARM_SYNC_FILE_RANGE = 341 SYS_TEE = 342 SYS_VMSPLICE = 343 SYS_MOVE_PAGES = 344 SYS_GETCPU = 345 SYS_EPOLL_PWAIT = 346 SYS_KEXEC_LOAD = 347 SYS_UTIMENSAT = 348 SYS_SIGNALFD = 349 SYS_TIMERFD_CREATE = 350 SYS_EVENTFD = 351 SYS_FALLOCATE = 352 SYS_TIMERFD_SETTIME = 353 SYS_TIMERFD_GETTIME = 354 SYS_SIGNALFD4 = 355 SYS_EVENTFD2 = 356 SYS_EPOLL_CREATE1 = 357 SYS_DUP3 = 358 SYS_PIPE2 = 359 SYS_INOTIFY_INIT1 = 360 SYS_PREADV = 361 SYS_PWRITEV = 362 SYS_RT_TGSIGQUEUEINFO = 363 SYS_PERF_EVENT_OPEN = 364 SYS_RECVMMSG = 365 SYS_ACCEPT4 = 366 SYS_FANOTIFY_INIT = 367 SYS_FANOTIFY_MARK = 368 SYS_PRLIMIT64 = 369 SYS_NAME_TO_HANDLE_AT = 370 SYS_OPEN_BY_HANDLE_AT = 371 SYS_CLOCK_ADJTIME = 372 SYS_SYNCFS = 373 SYS_SENDMMSG = 374 SYS_SETNS = 375 SYS_PROCESS_VM_READV = 376 SYS_PROCESS_VM_WRITEV = 377 SYS_KCMP = 378 SYS_FINIT_MODULE = 379 SYS_SCHED_SETATTR = 380 SYS_SCHED_GETATTR = 381 SYS_RENAMEAT2 = 382 SYS_SECCOMP = 383 SYS_GETRANDOM = 384 SYS_MEMFD_CREATE = 385 SYS_BPF = 386 SYS_EXECVEAT = 387 SYS_USERFAULTFD = 388 SYS_MEMBARRIER = 389 SYS_MLOCK2 = 390 SYS_COPY_FILE_RANGE = 391 SYS_PREADV2 = 392 SYS_PWRITEV2 = 393 SYS_PKEY_MPROTECT = 394 SYS_PKEY_ALLOC = 395 SYS_PKEY_FREE = 396 SYS_STATX = 397 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_amd64.go0000644061062106075000000002623113172163421025624 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -m64 /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,linux package unix const ( SYS_READ = 0 SYS_WRITE = 1 SYS_OPEN = 2 SYS_CLOSE = 3 SYS_STAT = 4 SYS_FSTAT = 5 SYS_LSTAT = 6 SYS_POLL = 7 SYS_LSEEK = 8 SYS_MMAP = 9 SYS_MPROTECT = 10 SYS_MUNMAP = 11 SYS_BRK = 12 SYS_RT_SIGACTION = 13 SYS_RT_SIGPROCMASK = 14 SYS_RT_SIGRETURN = 15 SYS_IOCTL = 16 SYS_PREAD64 = 17 SYS_PWRITE64 = 18 SYS_READV = 19 SYS_WRITEV = 20 SYS_ACCESS = 21 SYS_PIPE = 22 SYS_SELECT = 23 SYS_SCHED_YIELD = 24 SYS_MREMAP = 25 SYS_MSYNC = 26 SYS_MINCORE = 27 SYS_MADVISE = 28 SYS_SHMGET = 29 SYS_SHMAT = 30 SYS_SHMCTL = 31 SYS_DUP = 32 SYS_DUP2 = 33 SYS_PAUSE = 34 SYS_NANOSLEEP = 35 SYS_GETITIMER = 36 SYS_ALARM = 37 SYS_SETITIMER = 38 SYS_GETPID = 39 SYS_SENDFILE = 40 SYS_SOCKET = 41 SYS_CONNECT = 42 SYS_ACCEPT = 43 SYS_SENDTO = 44 SYS_RECVFROM = 45 SYS_SENDMSG = 46 SYS_RECVMSG = 47 SYS_SHUTDOWN = 48 SYS_BIND = 49 SYS_LISTEN = 50 SYS_GETSOCKNAME = 51 SYS_GETPEERNAME = 52 SYS_SOCKETPAIR = 53 SYS_SETSOCKOPT = 54 SYS_GETSOCKOPT = 55 SYS_CLONE = 56 SYS_FORK = 57 SYS_VFORK = 58 SYS_EXECVE = 59 SYS_EXIT = 60 SYS_WAIT4 = 61 SYS_KILL = 62 SYS_UNAME = 63 SYS_SEMGET = 64 SYS_SEMOP = 65 SYS_SEMCTL = 66 SYS_SHMDT = 67 SYS_MSGGET = 68 SYS_MSGSND = 69 SYS_MSGRCV = 70 SYS_MSGCTL = 71 SYS_FCNTL = 72 SYS_FLOCK = 73 SYS_FSYNC = 74 SYS_FDATASYNC = 75 SYS_TRUNCATE = 76 SYS_FTRUNCATE = 77 SYS_GETDENTS = 78 SYS_GETCWD = 79 SYS_CHDIR = 80 SYS_FCHDIR = 81 SYS_RENAME = 82 SYS_MKDIR = 83 SYS_RMDIR = 84 SYS_CREAT = 85 SYS_LINK = 86 SYS_UNLINK = 87 SYS_SYMLINK = 88 SYS_READLINK = 89 SYS_CHMOD = 90 SYS_FCHMOD = 91 SYS_CHOWN = 92 SYS_FCHOWN = 93 SYS_LCHOWN = 94 SYS_UMASK = 95 SYS_GETTIMEOFDAY = 96 SYS_GETRLIMIT = 97 SYS_GETRUSAGE = 98 SYS_SYSINFO = 99 SYS_TIMES = 100 SYS_PTRACE = 101 SYS_GETUID = 102 SYS_SYSLOG = 103 SYS_GETGID = 104 SYS_SETUID = 105 SYS_SETGID = 106 SYS_GETEUID = 107 SYS_GETEGID = 108 SYS_SETPGID = 109 SYS_GETPPID = 110 SYS_GETPGRP = 111 SYS_SETSID = 112 SYS_SETREUID = 113 SYS_SETREGID = 114 SYS_GETGROUPS = 115 SYS_SETGROUPS = 116 SYS_SETRESUID = 117 SYS_GETRESUID = 118 SYS_SETRESGID = 119 SYS_GETRESGID = 120 SYS_GETPGID = 121 SYS_SETFSUID = 122 SYS_SETFSGID = 123 SYS_GETSID = 124 SYS_CAPGET = 125 SYS_CAPSET = 126 SYS_RT_SIGPENDING = 127 SYS_RT_SIGTIMEDWAIT = 128 SYS_RT_SIGQUEUEINFO = 129 SYS_RT_SIGSUSPEND = 130 SYS_SIGALTSTACK = 131 SYS_UTIME = 132 SYS_MKNOD = 133 SYS_USELIB = 134 SYS_PERSONALITY = 135 SYS_USTAT = 136 SYS_STATFS = 137 SYS_FSTATFS = 138 SYS_SYSFS = 139 SYS_GETPRIORITY = 140 SYS_SETPRIORITY = 141 SYS_SCHED_SETPARAM = 142 SYS_SCHED_GETPARAM = 143 SYS_SCHED_SETSCHEDULER = 144 SYS_SCHED_GETSCHEDULER = 145 SYS_SCHED_GET_PRIORITY_MAX = 146 SYS_SCHED_GET_PRIORITY_MIN = 147 SYS_SCHED_RR_GET_INTERVAL = 148 SYS_MLOCK = 149 SYS_MUNLOCK = 150 SYS_MLOCKALL = 151 SYS_MUNLOCKALL = 152 SYS_VHANGUP = 153 SYS_MODIFY_LDT = 154 SYS_PIVOT_ROOT = 155 SYS__SYSCTL = 156 SYS_PRCTL = 157 SYS_ARCH_PRCTL = 158 SYS_ADJTIMEX = 159 SYS_SETRLIMIT = 160 SYS_CHROOT = 161 SYS_SYNC = 162 SYS_ACCT = 163 SYS_SETTIMEOFDAY = 164 SYS_MOUNT = 165 SYS_UMOUNT2 = 166 SYS_SWAPON = 167 SYS_SWAPOFF = 168 SYS_REBOOT = 169 SYS_SETHOSTNAME = 170 SYS_SETDOMAINNAME = 171 SYS_IOPL = 172 SYS_IOPERM = 173 SYS_CREATE_MODULE = 174 SYS_INIT_MODULE = 175 SYS_DELETE_MODULE = 176 SYS_GET_KERNEL_SYMS = 177 SYS_QUERY_MODULE = 178 SYS_QUOTACTL = 179 SYS_NFSSERVCTL = 180 SYS_GETPMSG = 181 SYS_PUTPMSG = 182 SYS_AFS_SYSCALL = 183 SYS_TUXCALL = 184 SYS_SECURITY = 185 SYS_GETTID = 186 SYS_READAHEAD = 187 SYS_SETXATTR = 188 SYS_LSETXATTR = 189 SYS_FSETXATTR = 190 SYS_GETXATTR = 191 SYS_LGETXATTR = 192 SYS_FGETXATTR = 193 SYS_LISTXATTR = 194 SYS_LLISTXATTR = 195 SYS_FLISTXATTR = 196 SYS_REMOVEXATTR = 197 SYS_LREMOVEXATTR = 198 SYS_FREMOVEXATTR = 199 SYS_TKILL = 200 SYS_TIME = 201 SYS_FUTEX = 202 SYS_SCHED_SETAFFINITY = 203 SYS_SCHED_GETAFFINITY = 204 SYS_SET_THREAD_AREA = 205 SYS_IO_SETUP = 206 SYS_IO_DESTROY = 207 SYS_IO_GETEVENTS = 208 SYS_IO_SUBMIT = 209 SYS_IO_CANCEL = 210 SYS_GET_THREAD_AREA = 211 SYS_LOOKUP_DCOOKIE = 212 SYS_EPOLL_CREATE = 213 SYS_EPOLL_CTL_OLD = 214 SYS_EPOLL_WAIT_OLD = 215 SYS_REMAP_FILE_PAGES = 216 SYS_GETDENTS64 = 217 SYS_SET_TID_ADDRESS = 218 SYS_RESTART_SYSCALL = 219 SYS_SEMTIMEDOP = 220 SYS_FADVISE64 = 221 SYS_TIMER_CREATE = 222 SYS_TIMER_SETTIME = 223 SYS_TIMER_GETTIME = 224 SYS_TIMER_GETOVERRUN = 225 SYS_TIMER_DELETE = 226 SYS_CLOCK_SETTIME = 227 SYS_CLOCK_GETTIME = 228 SYS_CLOCK_GETRES = 229 SYS_CLOCK_NANOSLEEP = 230 SYS_EXIT_GROUP = 231 SYS_EPOLL_WAIT = 232 SYS_EPOLL_CTL = 233 SYS_TGKILL = 234 SYS_UTIMES = 235 SYS_VSERVER = 236 SYS_MBIND = 237 SYS_SET_MEMPOLICY = 238 SYS_GET_MEMPOLICY = 239 SYS_MQ_OPEN = 240 SYS_MQ_UNLINK = 241 SYS_MQ_TIMEDSEND = 242 SYS_MQ_TIMEDRECEIVE = 243 SYS_MQ_NOTIFY = 244 SYS_MQ_GETSETATTR = 245 SYS_KEXEC_LOAD = 246 SYS_WAITID = 247 SYS_ADD_KEY = 248 SYS_REQUEST_KEY = 249 SYS_KEYCTL = 250 SYS_IOPRIO_SET = 251 SYS_IOPRIO_GET = 252 SYS_INOTIFY_INIT = 253 SYS_INOTIFY_ADD_WATCH = 254 SYS_INOTIFY_RM_WATCH = 255 SYS_MIGRATE_PAGES = 256 SYS_OPENAT = 257 SYS_MKDIRAT = 258 SYS_MKNODAT = 259 SYS_FCHOWNAT = 260 SYS_FUTIMESAT = 261 SYS_NEWFSTATAT = 262 SYS_UNLINKAT = 263 SYS_RENAMEAT = 264 SYS_LINKAT = 265 SYS_SYMLINKAT = 266 SYS_READLINKAT = 267 SYS_FCHMODAT = 268 SYS_FACCESSAT = 269 SYS_PSELECT6 = 270 SYS_PPOLL = 271 SYS_UNSHARE = 272 SYS_SET_ROBUST_LIST = 273 SYS_GET_ROBUST_LIST = 274 SYS_SPLICE = 275 SYS_TEE = 276 SYS_SYNC_FILE_RANGE = 277 SYS_VMSPLICE = 278 SYS_MOVE_PAGES = 279 SYS_UTIMENSAT = 280 SYS_EPOLL_PWAIT = 281 SYS_SIGNALFD = 282 SYS_TIMERFD_CREATE = 283 SYS_EVENTFD = 284 SYS_FALLOCATE = 285 SYS_TIMERFD_SETTIME = 286 SYS_TIMERFD_GETTIME = 287 SYS_ACCEPT4 = 288 SYS_SIGNALFD4 = 289 SYS_EVENTFD2 = 290 SYS_EPOLL_CREATE1 = 291 SYS_DUP3 = 292 SYS_PIPE2 = 293 SYS_INOTIFY_INIT1 = 294 SYS_PREADV = 295 SYS_PWRITEV = 296 SYS_RT_TGSIGQUEUEINFO = 297 SYS_PERF_EVENT_OPEN = 298 SYS_RECVMMSG = 299 SYS_FANOTIFY_INIT = 300 SYS_FANOTIFY_MARK = 301 SYS_PRLIMIT64 = 302 SYS_NAME_TO_HANDLE_AT = 303 SYS_OPEN_BY_HANDLE_AT = 304 SYS_CLOCK_ADJTIME = 305 SYS_SYNCFS = 306 SYS_SENDMMSG = 307 SYS_SETNS = 308 SYS_GETCPU = 309 SYS_PROCESS_VM_READV = 310 SYS_PROCESS_VM_WRITEV = 311 SYS_KCMP = 312 SYS_FINIT_MODULE = 313 SYS_SCHED_SETATTR = 314 SYS_SCHED_GETATTR = 315 SYS_RENAMEAT2 = 316 SYS_SECCOMP = 317 SYS_GETRANDOM = 318 SYS_MEMFD_CREATE = 319 SYS_KEXEC_FILE_LOAD = 320 SYS_BPF = 321 SYS_EXECVEAT = 322 SYS_USERFAULTFD = 323 SYS_MEMBARRIER = 324 SYS_MLOCK2 = 325 SYS_COPY_FILE_RANGE = 326 SYS_PREADV2 = 327 SYS_PWRITEV2 = 328 SYS_PKEY_MPROTECT = 329 SYS_PKEY_ALLOC = 330 SYS_PKEY_FREE = 331 SYS_STATX = 332 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_linux_386.go0000644061062106075000000003136713172163421025237 0ustar stgraberdomain admins// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -m32 /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,linux package unix const ( SYS_RESTART_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAITPID = 7 SYS_CREAT = 8 SYS_LINK = 9 SYS_UNLINK = 10 SYS_EXECVE = 11 SYS_CHDIR = 12 SYS_TIME = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 SYS_BREAK = 17 SYS_OLDSTAT = 18 SYS_LSEEK = 19 SYS_GETPID = 20 SYS_MOUNT = 21 SYS_UMOUNT = 22 SYS_SETUID = 23 SYS_GETUID = 24 SYS_STIME = 25 SYS_PTRACE = 26 SYS_ALARM = 27 SYS_OLDFSTAT = 28 SYS_PAUSE = 29 SYS_UTIME = 30 SYS_STTY = 31 SYS_GTTY = 32 SYS_ACCESS = 33 SYS_NICE = 34 SYS_FTIME = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_RENAME = 38 SYS_MKDIR = 39 SYS_RMDIR = 40 SYS_DUP = 41 SYS_PIPE = 42 SYS_TIMES = 43 SYS_PROF = 44 SYS_BRK = 45 SYS_SETGID = 46 SYS_GETGID = 47 SYS_SIGNAL = 48 SYS_GETEUID = 49 SYS_GETEGID = 50 SYS_ACCT = 51 SYS_UMOUNT2 = 52 SYS_LOCK = 53 SYS_IOCTL = 54 SYS_FCNTL = 55 SYS_MPX = 56 SYS_SETPGID = 57 SYS_ULIMIT = 58 SYS_OLDOLDUNAME = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_USTAT = 62 SYS_DUP2 = 63 SYS_GETPPID = 64 SYS_GETPGRP = 65 SYS_SETSID = 66 SYS_SIGACTION = 67 SYS_SGETMASK = 68 SYS_SSETMASK = 69 SYS_SETREUID = 70 SYS_SETREGID = 71 SYS_SIGSUSPEND = 72 SYS_SIGPENDING = 73 SYS_SETHOSTNAME = 74 SYS_SETRLIMIT = 75 SYS_GETRLIMIT = 76 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_GETGROUPS = 80 SYS_SETGROUPS = 81 SYS_SELECT = 82 SYS_SYMLINK = 83 SYS_OLDLSTAT = 84 SYS_READLINK = 85 SYS_USELIB = 86 SYS_SWAPON = 87 SYS_REBOOT = 88 SYS_READDIR = 89 SYS_MMAP = 90 SYS_MUNMAP = 91 SYS_TRUNCATE = 92 SYS_FTRUNCATE = 93 SYS_FCHMOD = 94 SYS_FCHOWN = 95 SYS_GETPRIORITY = 96 SYS_SETPRIORITY = 97 SYS_PROFIL = 98 SYS_STATFS = 99 SYS_FSTATFS = 100 SYS_IOPERM = 101 SYS_SOCKETCALL = 102 SYS_SYSLOG = 103 SYS_SETITIMER = 104 SYS_GETITIMER = 105 SYS_STAT = 106 SYS_LSTAT = 107 SYS_FSTAT = 108 SYS_OLDUNAME = 109 SYS_IOPL = 110 SYS_VHANGUP = 111 SYS_IDLE = 112 SYS_VM86OLD = 113 SYS_WAIT4 = 114 SYS_SWAPOFF = 115 SYS_SYSINFO = 116 SYS_IPC = 117 SYS_FSYNC = 118 SYS_SIGRETURN = 119 SYS_CLONE = 120 SYS_SETDOMAINNAME = 121 SYS_UNAME = 122 SYS_MODIFY_LDT = 123 SYS_ADJTIMEX = 124 SYS_MPROTECT = 125 SYS_SIGPROCMASK = 126 SYS_CREATE_MODULE = 127 SYS_INIT_MODULE = 128 SYS_DELETE_MODULE = 129 SYS_GET_KERNEL_SYMS = 130 SYS_QUOTACTL = 131 SYS_GETPGID = 132 SYS_FCHDIR = 133 SYS_BDFLUSH = 134 SYS_SYSFS = 135 SYS_PERSONALITY = 136 SYS_AFS_SYSCALL = 137 SYS_SETFSUID = 138 SYS_SETFSGID = 139 SYS__LLSEEK = 140 SYS_GETDENTS = 141 SYS__NEWSELECT = 142 SYS_FLOCK = 143 SYS_MSYNC = 144 SYS_READV = 145 SYS_WRITEV = 146 SYS_GETSID = 147 SYS_FDATASYNC = 148 SYS__SYSCTL = 149 SYS_MLOCK = 150 SYS_MUNLOCK = 151 SYS_MLOCKALL = 152 SYS_MUNLOCKALL = 153 SYS_SCHED_SETPARAM = 154 SYS_SCHED_GETPARAM = 155 SYS_SCHED_SETSCHEDULER = 156 SYS_SCHED_GETSCHEDULER = 157 SYS_SCHED_YIELD = 158 SYS_SCHED_GET_PRIORITY_MAX = 159 SYS_SCHED_GET_PRIORITY_MIN = 160 SYS_SCHED_RR_GET_INTERVAL = 161 SYS_NANOSLEEP = 162 SYS_MREMAP = 163 SYS_SETRESUID = 164 SYS_GETRESUID = 165 SYS_VM86 = 166 SYS_QUERY_MODULE = 167 SYS_POLL = 168 SYS_NFSSERVCTL = 169 SYS_SETRESGID = 170 SYS_GETRESGID = 171 SYS_PRCTL = 172 SYS_RT_SIGRETURN = 173 SYS_RT_SIGACTION = 174 SYS_RT_SIGPROCMASK = 175 SYS_RT_SIGPENDING = 176 SYS_RT_SIGTIMEDWAIT = 177 SYS_RT_SIGQUEUEINFO = 178 SYS_RT_SIGSUSPEND = 179 SYS_PREAD64 = 180 SYS_PWRITE64 = 181 SYS_CHOWN = 182 SYS_GETCWD = 183 SYS_CAPGET = 184 SYS_CAPSET = 185 SYS_SIGALTSTACK = 186 SYS_SENDFILE = 187 SYS_GETPMSG = 188 SYS_PUTPMSG = 189 SYS_VFORK = 190 SYS_UGETRLIMIT = 191 SYS_MMAP2 = 192 SYS_TRUNCATE64 = 193 SYS_FTRUNCATE64 = 194 SYS_STAT64 = 195 SYS_LSTAT64 = 196 SYS_FSTAT64 = 197 SYS_LCHOWN32 = 198 SYS_GETUID32 = 199 SYS_GETGID32 = 200 SYS_GETEUID32 = 201 SYS_GETEGID32 = 202 SYS_SETREUID32 = 203 SYS_SETREGID32 = 204 SYS_GETGROUPS32 = 205 SYS_SETGROUPS32 = 206 SYS_FCHOWN32 = 207 SYS_SETRESUID32 = 208 SYS_GETRESUID32 = 209 SYS_SETRESGID32 = 210 SYS_GETRESGID32 = 211 SYS_CHOWN32 = 212 SYS_SETUID32 = 213 SYS_SETGID32 = 214 SYS_SETFSUID32 = 215 SYS_SETFSGID32 = 216 SYS_PIVOT_ROOT = 217 SYS_MINCORE = 218 SYS_MADVISE = 219 SYS_GETDENTS64 = 220 SYS_FCNTL64 = 221 SYS_GETTID = 224 SYS_READAHEAD = 225 SYS_SETXATTR = 226 SYS_LSETXATTR = 227 SYS_FSETXATTR = 228 SYS_GETXATTR = 229 SYS_LGETXATTR = 230 SYS_FGETXATTR = 231 SYS_LISTXATTR = 232 SYS_LLISTXATTR = 233 SYS_FLISTXATTR = 234 SYS_REMOVEXATTR = 235 SYS_LREMOVEXATTR = 236 SYS_FREMOVEXATTR = 237 SYS_TKILL = 238 SYS_SENDFILE64 = 239 SYS_FUTEX = 240 SYS_SCHED_SETAFFINITY = 241 SYS_SCHED_GETAFFINITY = 242 SYS_SET_THREAD_AREA = 243 SYS_GET_THREAD_AREA = 244 SYS_IO_SETUP = 245 SYS_IO_DESTROY = 246 SYS_IO_GETEVENTS = 247 SYS_IO_SUBMIT = 248 SYS_IO_CANCEL = 249 SYS_FADVISE64 = 250 SYS_EXIT_GROUP = 252 SYS_LOOKUP_DCOOKIE = 253 SYS_EPOLL_CREATE = 254 SYS_EPOLL_CTL = 255 SYS_EPOLL_WAIT = 256 SYS_REMAP_FILE_PAGES = 257 SYS_SET_TID_ADDRESS = 258 SYS_TIMER_CREATE = 259 SYS_TIMER_SETTIME = 260 SYS_TIMER_GETTIME = 261 SYS_TIMER_GETOVERRUN = 262 SYS_TIMER_DELETE = 263 SYS_CLOCK_SETTIME = 264 SYS_CLOCK_GETTIME = 265 SYS_CLOCK_GETRES = 266 SYS_CLOCK_NANOSLEEP = 267 SYS_STATFS64 = 268 SYS_FSTATFS64 = 269 SYS_TGKILL = 270 SYS_UTIMES = 271 SYS_FADVISE64_64 = 272 SYS_VSERVER = 273 SYS_MBIND = 274 SYS_GET_MEMPOLICY = 275 SYS_SET_MEMPOLICY = 276 SYS_MQ_OPEN = 277 SYS_MQ_UNLINK = 278 SYS_MQ_TIMEDSEND = 279 SYS_MQ_TIMEDRECEIVE = 280 SYS_MQ_NOTIFY = 281 SYS_MQ_GETSETATTR = 282 SYS_KEXEC_LOAD = 283 SYS_WAITID = 284 SYS_ADD_KEY = 286 SYS_REQUEST_KEY = 287 SYS_KEYCTL = 288 SYS_IOPRIO_SET = 289 SYS_IOPRIO_GET = 290 SYS_INOTIFY_INIT = 291 SYS_INOTIFY_ADD_WATCH = 292 SYS_INOTIFY_RM_WATCH = 293 SYS_MIGRATE_PAGES = 294 SYS_OPENAT = 295 SYS_MKDIRAT = 296 SYS_MKNODAT = 297 SYS_FCHOWNAT = 298 SYS_FUTIMESAT = 299 SYS_FSTATAT64 = 300 SYS_UNLINKAT = 301 SYS_RENAMEAT = 302 SYS_LINKAT = 303 SYS_SYMLINKAT = 304 SYS_READLINKAT = 305 SYS_FCHMODAT = 306 SYS_FACCESSAT = 307 SYS_PSELECT6 = 308 SYS_PPOLL = 309 SYS_UNSHARE = 310 SYS_SET_ROBUST_LIST = 311 SYS_GET_ROBUST_LIST = 312 SYS_SPLICE = 313 SYS_SYNC_FILE_RANGE = 314 SYS_TEE = 315 SYS_VMSPLICE = 316 SYS_MOVE_PAGES = 317 SYS_GETCPU = 318 SYS_EPOLL_PWAIT = 319 SYS_UTIMENSAT = 320 SYS_SIGNALFD = 321 SYS_TIMERFD_CREATE = 322 SYS_EVENTFD = 323 SYS_FALLOCATE = 324 SYS_TIMERFD_SETTIME = 325 SYS_TIMERFD_GETTIME = 326 SYS_SIGNALFD4 = 327 SYS_EVENTFD2 = 328 SYS_EPOLL_CREATE1 = 329 SYS_DUP3 = 330 SYS_PIPE2 = 331 SYS_INOTIFY_INIT1 = 332 SYS_PREADV = 333 SYS_PWRITEV = 334 SYS_RT_TGSIGQUEUEINFO = 335 SYS_PERF_EVENT_OPEN = 336 SYS_RECVMMSG = 337 SYS_FANOTIFY_INIT = 338 SYS_FANOTIFY_MARK = 339 SYS_PRLIMIT64 = 340 SYS_NAME_TO_HANDLE_AT = 341 SYS_OPEN_BY_HANDLE_AT = 342 SYS_CLOCK_ADJTIME = 343 SYS_SYNCFS = 344 SYS_SENDMMSG = 345 SYS_SETNS = 346 SYS_PROCESS_VM_READV = 347 SYS_PROCESS_VM_WRITEV = 348 SYS_KCMP = 349 SYS_FINIT_MODULE = 350 SYS_SCHED_SETATTR = 351 SYS_SCHED_GETATTR = 352 SYS_RENAMEAT2 = 353 SYS_SECCOMP = 354 SYS_GETRANDOM = 355 SYS_MEMFD_CREATE = 356 SYS_BPF = 357 SYS_EXECVEAT = 358 SYS_SOCKET = 359 SYS_SOCKETPAIR = 360 SYS_BIND = 361 SYS_CONNECT = 362 SYS_LISTEN = 363 SYS_ACCEPT4 = 364 SYS_GETSOCKOPT = 365 SYS_SETSOCKOPT = 366 SYS_GETSOCKNAME = 367 SYS_GETPEERNAME = 368 SYS_SENDTO = 369 SYS_SENDMSG = 370 SYS_RECVFROM = 371 SYS_RECVMSG = 372 SYS_SHUTDOWN = 373 SYS_USERFAULTFD = 374 SYS_MEMBARRIER = 375 SYS_MLOCK2 = 376 SYS_COPY_FILE_RANGE = 377 SYS_PREADV2 = 378 SYS_PWRITEV2 = 379 SYS_PKEY_MPROTECT = 380 SYS_PKEY_ALLOC = 381 SYS_PKEY_FREE = 382 SYS_STATX = 383 SYS_ARCH_PRCTL = 384 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_freebsd_arm.go0000644061062106075000000006202713172163421025746 0ustar stgraberdomain admins// mksysnum_freebsd.pl // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,freebsd package unix const ( // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int SYS_EXIT = 1 // { void sys_exit(int rval); } exit \ SYS_FORK = 2 // { int fork(void); } SYS_READ = 3 // { ssize_t read(int fd, void *buf, \ SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, \ SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } SYS_CLOSE = 6 // { int close(int fd); } SYS_WAIT4 = 7 // { int wait4(int pid, int *status, \ SYS_LINK = 9 // { int link(char *path, char *link); } SYS_UNLINK = 10 // { int unlink(char *path); } SYS_CHDIR = 12 // { int chdir(char *path); } SYS_FCHDIR = 13 // { int fchdir(int fd); } SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } SYS_CHMOD = 15 // { int chmod(char *path, int mode); } SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } SYS_OBREAK = 17 // { int obreak(char *nsize); } break \ SYS_GETPID = 20 // { pid_t getpid(void); } SYS_MOUNT = 21 // { int mount(char *type, char *path, \ SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } SYS_SETUID = 23 // { int setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t getuid(void); } SYS_GETEUID = 25 // { uid_t geteuid(void); } SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, \ SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, \ SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, \ SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, \ SYS_ACCEPT = 30 // { int accept(int s, \ SYS_GETPEERNAME = 31 // { int getpeername(int fdes, \ SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, \ SYS_ACCESS = 33 // { int access(char *path, int amode); } SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); } SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); } SYS_SYNC = 36 // { int sync(void); } SYS_KILL = 37 // { int kill(int pid, int signum); } SYS_GETPPID = 39 // { pid_t getppid(void); } SYS_DUP = 41 // { int dup(u_int fd); } SYS_PIPE = 42 // { int pipe(void); } SYS_GETEGID = 43 // { gid_t getegid(void); } SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \ SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, \ SYS_GETGID = 47 // { gid_t getgid(void); } SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int \ SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } SYS_ACCT = 51 // { int acct(char *path); } SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, \ SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, \ SYS_REBOOT = 55 // { int reboot(int opt); } SYS_REVOKE = 56 // { int revoke(char *path); } SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, \ SYS_EXECVE = 59 // { int execve(char *fname, char **argv, \ SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args \ SYS_CHROOT = 61 // { int chroot(char *path); } SYS_MSYNC = 65 // { int msync(void *addr, size_t len, \ SYS_VFORK = 66 // { int vfork(void); } SYS_SBRK = 69 // { int sbrk(int incr); } SYS_SSTK = 70 // { int sstk(int incr); } SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise \ SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, \ SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, \ SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \ SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, \ SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, \ SYS_GETPGRP = 81 // { int getpgrp(void); } SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } SYS_SETITIMER = 83 // { int setitimer(u_int which, struct \ SYS_SWAPON = 85 // { int swapon(char *name); } SYS_GETITIMER = 86 // { int getitimer(u_int which, \ SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); } SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \ SYS_FSYNC = 95 // { int fsync(int fd); } SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, \ SYS_SOCKET = 97 // { int socket(int domain, int type, \ SYS_CONNECT = 98 // { int connect(int s, caddr_t name, \ SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } SYS_BIND = 104 // { int bind(int s, caddr_t name, \ SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \ SYS_LISTEN = 106 // { int listen(int s, int backlog); } SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \ SYS_GETRUSAGE = 117 // { int getrusage(int who, \ SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \ SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, \ SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \ SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \ SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } SYS_RENAME = 128 // { int rename(char *from, char *to); } SYS_FLOCK = 131 // { int flock(int fd, int how); } SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \ SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, \ SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } SYS_RMDIR = 137 // { int rmdir(char *path); } SYS_UTIMES = 138 // { int utimes(char *path, \ SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \ SYS_SETSID = 147 // { int setsid(void); } SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \ SYS_LGETFH = 160 // { int lgetfh(char *fname, \ SYS_GETFH = 161 // { int getfh(char *fname, \ SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \ SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, \ SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, \ SYS_SETFIB = 175 // { int setfib(int fibnum); } SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int setgid(gid_t gid); } SYS_SETEGID = 182 // { int setegid(gid_t egid); } SYS_SETEUID = 183 // { int seteuid(uid_t euid); } SYS_STAT = 188 // { int stat(char *path, struct stat *ub); } SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); } SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); } SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \ SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \ SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, \ SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, \ SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, \ SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, \ SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, \ SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, \ SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int undelete(char *path); } SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } SYS_GETPGID = 207 // { int getpgid(pid_t pid); } SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \ SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \ SYS_CLOCK_SETTIME = 233 // { int clock_settime( \ SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \ SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, \ SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); } SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, \ SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct \ SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); } SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \ SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); } SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( \ SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( \ SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,\ SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); } SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, \ SYS_RFORK = 251 // { int rfork(int flags); } SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, \ SYS_ISSETUGID = 253 // { int issetugid(void); } SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, \ SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } SYS_LUTIMES = 276 // { int lutimes(char *path, \ SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); } SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); } SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); } SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, \ SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, \ SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, \ SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, \ SYS_MODNEXT = 300 // { int modnext(int modid); } SYS_MODSTAT = 301 // { int modstat(int modid, \ SYS_MODFNEXT = 302 // { int modfnext(int modid); } SYS_MODFIND = 303 // { int modfind(const char *name); } SYS_KLDLOAD = 304 // { int kldload(const char *file); } SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } SYS_KLDFIND = 306 // { int kldfind(const char *file); } SYS_KLDNEXT = 307 // { int kldnext(int fileid); } SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct \ SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } SYS_GETSID = 310 // { int getsid(pid_t pid); } SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, \ SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, \ SYS_YIELD = 321 // { int yield(void); } SYS_MLOCKALL = 324 // { int mlockall(int how); } SYS_MUNLOCKALL = 325 // { int munlockall(void); } SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); } SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, \ SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct \ SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int \ SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } SYS_SCHED_YIELD = 331 // { int sched_yield (void); } SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, \ SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, \ SYS_JAIL = 338 // { int jail(struct jail *jail); } SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, \ SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, \ SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, \ SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \ SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \ SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, \ SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, \ SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \ SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, \ SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \ SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, \ SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \ SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( \ SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( \ SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \ SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, \ SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, \ SYS_KQUEUE = 362 // { int kqueue(void); } SYS_KEVENT = 363 // { int kevent(int fd, \ SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, \ SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, \ SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, \ SYS___SETUGID = 374 // { int __setugid(int flag); } SYS_EACCESS = 376 // { int eaccess(char *path, int amode); } SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, \ SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); } SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); } SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, \ SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, \ SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, \ SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, \ SYS_KENV = 390 // { int kenv(int what, const char *name, \ SYS_LCHFLAGS = 391 // { int lchflags(const char *path, \ SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, \ SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, \ SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, \ SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, \ SYS_STATFS = 396 // { int statfs(char *path, \ SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); } SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, \ SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, \ SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, \ SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, \ SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( \ SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( \ SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( \ SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, \ SYS_SIGACTION = 416 // { int sigaction(int sig, \ SYS_SIGRETURN = 417 // { int sigreturn( \ SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); } SYS_SETCONTEXT = 422 // { int setcontext( \ SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, \ SYS_SWAPOFF = 424 // { int swapoff(const char *name); } SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, \ SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, \ SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, \ SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, \ SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, \ SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, \ SYS_THR_EXIT = 431 // { void thr_exit(long *state); } SYS_THR_SELF = 432 // { int thr_self(long *id); } SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); } SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); } SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); } SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); } SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, \ SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( \ SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( \ SYS_THR_SUSPEND = 442 // { int thr_suspend( \ SYS_THR_WAKE = 443 // { int thr_wake(long id); } SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); } SYS_AUDIT = 445 // { int audit(const void *record, \ SYS_AUDITON = 446 // { int auditon(int cmd, void *data, \ SYS_GETAUID = 447 // { int getauid(uid_t *auid); } SYS_SETAUID = 448 // { int setauid(uid_t *auid); } SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); } SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); } SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( \ SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( \ SYS_AUDITCTL = 453 // { int auditctl(char *path); } SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, \ SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, \ SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); } SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); } SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); } SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, \ SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, \ SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, \ SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, \ SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, \ SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); } SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); } SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); } SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, \ SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); } SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); } SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, \ SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, \ SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, \ SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, \ SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, \ SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, \ SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, \ SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, \ SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, \ SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, \ SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, \ SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); } SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); } SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, \ SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, \ SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, \ SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, \ SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, \ SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); } SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); } SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, \ SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, \ SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); } SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); } SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); } SYS___CAP_RIGHTS_GET = 515 // { int __cap_rights_get(int version, \ SYS_CAP_ENTER = 516 // { int cap_enter(void); } SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); } SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); } SYS_PDKILL = 519 // { int pdkill(int fd, int signum); } SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); } SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, \ SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, \ SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); } SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, \ SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, \ SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, \ SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, \ SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, \ SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, \ SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, \ SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, \ SYS_CAP_RIGHTS_LIMIT = 533 // { int cap_rights_limit(int fd, \ SYS_CAP_IOCTLS_LIMIT = 534 // { int cap_ioctls_limit(int fd, \ SYS_CAP_IOCTLS_GET = 535 // { ssize_t cap_ioctls_get(int fd, \ SYS_CAP_FCNTLS_LIMIT = 536 // { int cap_fcntls_limit(int fd, \ SYS_CAP_FCNTLS_GET = 537 // { int cap_fcntls_get(int fd, \ SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, \ SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, \ SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, \ SYS_ACCEPT4 = 541 // { int accept4(int s, \ SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); } SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, \ SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, \ SYS_FUTIMENS = 546 // { int futimens(int fd, \ SYS_UTIMENSAT = 547 // { int utimensat(int fd, \ ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go0000644061062106075000000006203113172163421026075 0ustar stgraberdomain admins// mksysnum_freebsd.pl // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,freebsd package unix const ( // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int SYS_EXIT = 1 // { void sys_exit(int rval); } exit \ SYS_FORK = 2 // { int fork(void); } SYS_READ = 3 // { ssize_t read(int fd, void *buf, \ SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, \ SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } SYS_CLOSE = 6 // { int close(int fd); } SYS_WAIT4 = 7 // { int wait4(int pid, int *status, \ SYS_LINK = 9 // { int link(char *path, char *link); } SYS_UNLINK = 10 // { int unlink(char *path); } SYS_CHDIR = 12 // { int chdir(char *path); } SYS_FCHDIR = 13 // { int fchdir(int fd); } SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } SYS_CHMOD = 15 // { int chmod(char *path, int mode); } SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } SYS_OBREAK = 17 // { int obreak(char *nsize); } break \ SYS_GETPID = 20 // { pid_t getpid(void); } SYS_MOUNT = 21 // { int mount(char *type, char *path, \ SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } SYS_SETUID = 23 // { int setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t getuid(void); } SYS_GETEUID = 25 // { uid_t geteuid(void); } SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, \ SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, \ SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, \ SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, \ SYS_ACCEPT = 30 // { int accept(int s, \ SYS_GETPEERNAME = 31 // { int getpeername(int fdes, \ SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, \ SYS_ACCESS = 33 // { int access(char *path, int amode); } SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); } SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); } SYS_SYNC = 36 // { int sync(void); } SYS_KILL = 37 // { int kill(int pid, int signum); } SYS_GETPPID = 39 // { pid_t getppid(void); } SYS_DUP = 41 // { int dup(u_int fd); } SYS_PIPE = 42 // { int pipe(void); } SYS_GETEGID = 43 // { gid_t getegid(void); } SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \ SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, \ SYS_GETGID = 47 // { gid_t getgid(void); } SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int \ SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } SYS_ACCT = 51 // { int acct(char *path); } SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, \ SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, \ SYS_REBOOT = 55 // { int reboot(int opt); } SYS_REVOKE = 56 // { int revoke(char *path); } SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, \ SYS_EXECVE = 59 // { int execve(char *fname, char **argv, \ SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args \ SYS_CHROOT = 61 // { int chroot(char *path); } SYS_MSYNC = 65 // { int msync(void *addr, size_t len, \ SYS_VFORK = 66 // { int vfork(void); } SYS_SBRK = 69 // { int sbrk(int incr); } SYS_SSTK = 70 // { int sstk(int incr); } SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise \ SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, \ SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, \ SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \ SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, \ SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, \ SYS_GETPGRP = 81 // { int getpgrp(void); } SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } SYS_SETITIMER = 83 // { int setitimer(u_int which, struct \ SYS_SWAPON = 85 // { int swapon(char *name); } SYS_GETITIMER = 86 // { int getitimer(u_int which, \ SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); } SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \ SYS_FSYNC = 95 // { int fsync(int fd); } SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, \ SYS_SOCKET = 97 // { int socket(int domain, int type, \ SYS_CONNECT = 98 // { int connect(int s, caddr_t name, \ SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } SYS_BIND = 104 // { int bind(int s, caddr_t name, \ SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \ SYS_LISTEN = 106 // { int listen(int s, int backlog); } SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \ SYS_GETRUSAGE = 117 // { int getrusage(int who, \ SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \ SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, \ SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \ SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \ SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } SYS_RENAME = 128 // { int rename(char *from, char *to); } SYS_FLOCK = 131 // { int flock(int fd, int how); } SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \ SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, \ SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } SYS_RMDIR = 137 // { int rmdir(char *path); } SYS_UTIMES = 138 // { int utimes(char *path, \ SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \ SYS_SETSID = 147 // { int setsid(void); } SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \ SYS_LGETFH = 160 // { int lgetfh(char *fname, \ SYS_GETFH = 161 // { int getfh(char *fname, \ SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \ SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, \ SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, \ SYS_SETFIB = 175 // { int setfib(int fibnum); } SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int setgid(gid_t gid); } SYS_SETEGID = 182 // { int setegid(gid_t egid); } SYS_SETEUID = 183 // { int seteuid(uid_t euid); } SYS_STAT = 188 // { int stat(char *path, struct stat *ub); } SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); } SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); } SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \ SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \ SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, \ SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, \ SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, \ SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, \ SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, \ SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, \ SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int undelete(char *path); } SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } SYS_GETPGID = 207 // { int getpgid(pid_t pid); } SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \ SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \ SYS_CLOCK_SETTIME = 233 // { int clock_settime( \ SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \ SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, \ SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); } SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, \ SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct \ SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); } SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \ SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); } SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( \ SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( \ SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,\ SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); } SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, \ SYS_RFORK = 251 // { int rfork(int flags); } SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, \ SYS_ISSETUGID = 253 // { int issetugid(void); } SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, \ SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } SYS_LUTIMES = 276 // { int lutimes(char *path, \ SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); } SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); } SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); } SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, \ SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, \ SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, \ SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, \ SYS_MODNEXT = 300 // { int modnext(int modid); } SYS_MODSTAT = 301 // { int modstat(int modid, \ SYS_MODFNEXT = 302 // { int modfnext(int modid); } SYS_MODFIND = 303 // { int modfind(const char *name); } SYS_KLDLOAD = 304 // { int kldload(const char *file); } SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } SYS_KLDFIND = 306 // { int kldfind(const char *file); } SYS_KLDNEXT = 307 // { int kldnext(int fileid); } SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct \ SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } SYS_GETSID = 310 // { int getsid(pid_t pid); } SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, \ SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, \ SYS_YIELD = 321 // { int yield(void); } SYS_MLOCKALL = 324 // { int mlockall(int how); } SYS_MUNLOCKALL = 325 // { int munlockall(void); } SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); } SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, \ SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct \ SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int \ SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } SYS_SCHED_YIELD = 331 // { int sched_yield (void); } SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, \ SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, \ SYS_JAIL = 338 // { int jail(struct jail *jail); } SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, \ SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, \ SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, \ SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \ SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \ SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, \ SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, \ SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \ SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, \ SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \ SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, \ SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \ SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( \ SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( \ SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \ SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, \ SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, \ SYS_KQUEUE = 362 // { int kqueue(void); } SYS_KEVENT = 363 // { int kevent(int fd, \ SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, \ SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, \ SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, \ SYS___SETUGID = 374 // { int __setugid(int flag); } SYS_EACCESS = 376 // { int eaccess(char *path, int amode); } SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, \ SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); } SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); } SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, \ SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, \ SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, \ SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, \ SYS_KENV = 390 // { int kenv(int what, const char *name, \ SYS_LCHFLAGS = 391 // { int lchflags(const char *path, \ SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, \ SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, \ SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, \ SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, \ SYS_STATFS = 396 // { int statfs(char *path, \ SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); } SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, \ SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, \ SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, \ SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, \ SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( \ SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( \ SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( \ SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, \ SYS_SIGACTION = 416 // { int sigaction(int sig, \ SYS_SIGRETURN = 417 // { int sigreturn( \ SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); } SYS_SETCONTEXT = 422 // { int setcontext( \ SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, \ SYS_SWAPOFF = 424 // { int swapoff(const char *name); } SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, \ SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, \ SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, \ SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, \ SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, \ SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, \ SYS_THR_EXIT = 431 // { void thr_exit(long *state); } SYS_THR_SELF = 432 // { int thr_self(long *id); } SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); } SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); } SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); } SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); } SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, \ SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( \ SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( \ SYS_THR_SUSPEND = 442 // { int thr_suspend( \ SYS_THR_WAKE = 443 // { int thr_wake(long id); } SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); } SYS_AUDIT = 445 // { int audit(const void *record, \ SYS_AUDITON = 446 // { int auditon(int cmd, void *data, \ SYS_GETAUID = 447 // { int getauid(uid_t *auid); } SYS_SETAUID = 448 // { int setauid(uid_t *auid); } SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); } SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); } SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( \ SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( \ SYS_AUDITCTL = 453 // { int auditctl(char *path); } SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, \ SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, \ SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); } SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); } SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); } SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, \ SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, \ SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, \ SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, \ SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, \ SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); } SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); } SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); } SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, \ SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); } SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); } SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, \ SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, \ SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, \ SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, \ SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, \ SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, \ SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, \ SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, \ SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, \ SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, \ SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, \ SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); } SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); } SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, \ SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, \ SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, \ SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, \ SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, \ SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); } SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); } SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, \ SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, \ SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); } SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); } SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); } SYS___CAP_RIGHTS_GET = 515 // { int __cap_rights_get(int version, \ SYS_CAP_ENTER = 516 // { int cap_enter(void); } SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); } SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); } SYS_PDKILL = 519 // { int pdkill(int fd, int signum); } SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); } SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, \ SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, \ SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); } SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, \ SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, \ SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, \ SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, \ SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, \ SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, \ SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, \ SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, \ SYS_CAP_RIGHTS_LIMIT = 533 // { int cap_rights_limit(int fd, \ SYS_CAP_IOCTLS_LIMIT = 534 // { int cap_ioctls_limit(int fd, \ SYS_CAP_IOCTLS_GET = 535 // { ssize_t cap_ioctls_get(int fd, \ SYS_CAP_FCNTLS_LIMIT = 536 // { int cap_fcntls_limit(int fd, \ SYS_CAP_FCNTLS_GET = 537 // { int cap_fcntls_get(int fd, \ SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, \ SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, \ SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, \ SYS_ACCEPT4 = 541 // { int accept4(int s, \ SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); } SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, \ SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, \ SYS_FUTIMENS = 546 // { int futimens(int fd, \ SYS_UTIMENSAT = 547 // { int utimensat(int fd, \ ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_freebsd_386.go0000644061062106075000000006202713172163421025507 0ustar stgraberdomain admins// mksysnum_freebsd.pl // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,freebsd package unix const ( // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int SYS_EXIT = 1 // { void sys_exit(int rval); } exit \ SYS_FORK = 2 // { int fork(void); } SYS_READ = 3 // { ssize_t read(int fd, void *buf, \ SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, \ SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } SYS_CLOSE = 6 // { int close(int fd); } SYS_WAIT4 = 7 // { int wait4(int pid, int *status, \ SYS_LINK = 9 // { int link(char *path, char *link); } SYS_UNLINK = 10 // { int unlink(char *path); } SYS_CHDIR = 12 // { int chdir(char *path); } SYS_FCHDIR = 13 // { int fchdir(int fd); } SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } SYS_CHMOD = 15 // { int chmod(char *path, int mode); } SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } SYS_OBREAK = 17 // { int obreak(char *nsize); } break \ SYS_GETPID = 20 // { pid_t getpid(void); } SYS_MOUNT = 21 // { int mount(char *type, char *path, \ SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } SYS_SETUID = 23 // { int setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t getuid(void); } SYS_GETEUID = 25 // { uid_t geteuid(void); } SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, \ SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, \ SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, \ SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, \ SYS_ACCEPT = 30 // { int accept(int s, \ SYS_GETPEERNAME = 31 // { int getpeername(int fdes, \ SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, \ SYS_ACCESS = 33 // { int access(char *path, int amode); } SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); } SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); } SYS_SYNC = 36 // { int sync(void); } SYS_KILL = 37 // { int kill(int pid, int signum); } SYS_GETPPID = 39 // { pid_t getppid(void); } SYS_DUP = 41 // { int dup(u_int fd); } SYS_PIPE = 42 // { int pipe(void); } SYS_GETEGID = 43 // { gid_t getegid(void); } SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \ SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, \ SYS_GETGID = 47 // { gid_t getgid(void); } SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int \ SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } SYS_ACCT = 51 // { int acct(char *path); } SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, \ SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, \ SYS_REBOOT = 55 // { int reboot(int opt); } SYS_REVOKE = 56 // { int revoke(char *path); } SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, \ SYS_EXECVE = 59 // { int execve(char *fname, char **argv, \ SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args \ SYS_CHROOT = 61 // { int chroot(char *path); } SYS_MSYNC = 65 // { int msync(void *addr, size_t len, \ SYS_VFORK = 66 // { int vfork(void); } SYS_SBRK = 69 // { int sbrk(int incr); } SYS_SSTK = 70 // { int sstk(int incr); } SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise \ SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, \ SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, \ SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \ SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, \ SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, \ SYS_GETPGRP = 81 // { int getpgrp(void); } SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } SYS_SETITIMER = 83 // { int setitimer(u_int which, struct \ SYS_SWAPON = 85 // { int swapon(char *name); } SYS_GETITIMER = 86 // { int getitimer(u_int which, \ SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); } SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \ SYS_FSYNC = 95 // { int fsync(int fd); } SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, \ SYS_SOCKET = 97 // { int socket(int domain, int type, \ SYS_CONNECT = 98 // { int connect(int s, caddr_t name, \ SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } SYS_BIND = 104 // { int bind(int s, caddr_t name, \ SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \ SYS_LISTEN = 106 // { int listen(int s, int backlog); } SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \ SYS_GETRUSAGE = 117 // { int getrusage(int who, \ SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \ SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, \ SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \ SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \ SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } SYS_RENAME = 128 // { int rename(char *from, char *to); } SYS_FLOCK = 131 // { int flock(int fd, int how); } SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \ SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, \ SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } SYS_RMDIR = 137 // { int rmdir(char *path); } SYS_UTIMES = 138 // { int utimes(char *path, \ SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \ SYS_SETSID = 147 // { int setsid(void); } SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \ SYS_LGETFH = 160 // { int lgetfh(char *fname, \ SYS_GETFH = 161 // { int getfh(char *fname, \ SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \ SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, \ SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, \ SYS_SETFIB = 175 // { int setfib(int fibnum); } SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int setgid(gid_t gid); } SYS_SETEGID = 182 // { int setegid(gid_t egid); } SYS_SETEUID = 183 // { int seteuid(uid_t euid); } SYS_STAT = 188 // { int stat(char *path, struct stat *ub); } SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); } SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); } SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \ SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \ SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, \ SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, \ SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, \ SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, \ SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, \ SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, \ SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int undelete(char *path); } SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } SYS_GETPGID = 207 // { int getpgid(pid_t pid); } SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \ SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \ SYS_CLOCK_SETTIME = 233 // { int clock_settime( \ SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \ SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, \ SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); } SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, \ SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct \ SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); } SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \ SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); } SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( \ SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( \ SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,\ SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); } SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, \ SYS_RFORK = 251 // { int rfork(int flags); } SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, \ SYS_ISSETUGID = 253 // { int issetugid(void); } SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, \ SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } SYS_LUTIMES = 276 // { int lutimes(char *path, \ SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); } SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); } SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); } SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, \ SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, \ SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, \ SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, \ SYS_MODNEXT = 300 // { int modnext(int modid); } SYS_MODSTAT = 301 // { int modstat(int modid, \ SYS_MODFNEXT = 302 // { int modfnext(int modid); } SYS_MODFIND = 303 // { int modfind(const char *name); } SYS_KLDLOAD = 304 // { int kldload(const char *file); } SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } SYS_KLDFIND = 306 // { int kldfind(const char *file); } SYS_KLDNEXT = 307 // { int kldnext(int fileid); } SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct \ SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } SYS_GETSID = 310 // { int getsid(pid_t pid); } SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, \ SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, \ SYS_YIELD = 321 // { int yield(void); } SYS_MLOCKALL = 324 // { int mlockall(int how); } SYS_MUNLOCKALL = 325 // { int munlockall(void); } SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); } SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, \ SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct \ SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int \ SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } SYS_SCHED_YIELD = 331 // { int sched_yield (void); } SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, \ SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, \ SYS_JAIL = 338 // { int jail(struct jail *jail); } SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, \ SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, \ SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, \ SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \ SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \ SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, \ SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, \ SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \ SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, \ SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \ SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, \ SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \ SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( \ SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( \ SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \ SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, \ SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, \ SYS_KQUEUE = 362 // { int kqueue(void); } SYS_KEVENT = 363 // { int kevent(int fd, \ SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, \ SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, \ SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, \ SYS___SETUGID = 374 // { int __setugid(int flag); } SYS_EACCESS = 376 // { int eaccess(char *path, int amode); } SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, \ SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); } SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); } SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, \ SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, \ SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, \ SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, \ SYS_KENV = 390 // { int kenv(int what, const char *name, \ SYS_LCHFLAGS = 391 // { int lchflags(const char *path, \ SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, \ SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, \ SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, \ SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, \ SYS_STATFS = 396 // { int statfs(char *path, \ SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); } SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, \ SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, \ SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, \ SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, \ SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( \ SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( \ SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( \ SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, \ SYS_SIGACTION = 416 // { int sigaction(int sig, \ SYS_SIGRETURN = 417 // { int sigreturn( \ SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); } SYS_SETCONTEXT = 422 // { int setcontext( \ SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, \ SYS_SWAPOFF = 424 // { int swapoff(const char *name); } SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, \ SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, \ SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, \ SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, \ SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, \ SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, \ SYS_THR_EXIT = 431 // { void thr_exit(long *state); } SYS_THR_SELF = 432 // { int thr_self(long *id); } SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); } SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); } SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); } SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); } SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, \ SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( \ SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( \ SYS_THR_SUSPEND = 442 // { int thr_suspend( \ SYS_THR_WAKE = 443 // { int thr_wake(long id); } SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); } SYS_AUDIT = 445 // { int audit(const void *record, \ SYS_AUDITON = 446 // { int auditon(int cmd, void *data, \ SYS_GETAUID = 447 // { int getauid(uid_t *auid); } SYS_SETAUID = 448 // { int setauid(uid_t *auid); } SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); } SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); } SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( \ SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( \ SYS_AUDITCTL = 453 // { int auditctl(char *path); } SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, \ SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, \ SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); } SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); } SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); } SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, \ SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, \ SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, \ SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, \ SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, \ SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); } SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); } SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); } SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, \ SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); } SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); } SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, \ SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, \ SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, \ SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, \ SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, \ SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, \ SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, \ SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, \ SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, \ SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, \ SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, \ SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); } SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); } SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, \ SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, \ SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, \ SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, \ SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, \ SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); } SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); } SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, \ SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, \ SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); } SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); } SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); } SYS___CAP_RIGHTS_GET = 515 // { int __cap_rights_get(int version, \ SYS_CAP_ENTER = 516 // { int cap_enter(void); } SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); } SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); } SYS_PDKILL = 519 // { int pdkill(int fd, int signum); } SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); } SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, \ SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, \ SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); } SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, \ SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, \ SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, \ SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, \ SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, \ SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, \ SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, \ SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, \ SYS_CAP_RIGHTS_LIMIT = 533 // { int cap_rights_limit(int fd, \ SYS_CAP_IOCTLS_LIMIT = 534 // { int cap_ioctls_limit(int fd, \ SYS_CAP_IOCTLS_GET = 535 // { ssize_t cap_ioctls_get(int fd, \ SYS_CAP_FCNTLS_LIMIT = 536 // { int cap_fcntls_limit(int fd, \ SYS_CAP_FCNTLS_GET = 537 // { int cap_fcntls_get(int fd, \ SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, \ SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, \ SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, \ SYS_ACCEPT4 = 541 // { int accept4(int s, \ SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); } SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, \ SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, \ SYS_FUTIMENS = 546 // { int futimens(int fd, \ SYS_UTIMENSAT = 547 // { int utimensat(int fd, \ ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go0000644061062106075000000005714113172163421026456 0ustar stgraberdomain admins// mksysnum_dragonfly.pl // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,dragonfly package unix const ( // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int SYS_EXIT = 1 // { void exit(int rval); } SYS_FORK = 2 // { int fork(void); } SYS_READ = 3 // { ssize_t read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, size_t nbyte); } SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } SYS_CLOSE = 6 // { int close(int fd); } SYS_WAIT4 = 7 // { int wait4(int pid, int *status, int options, \ SYS_LINK = 9 // { int link(char *path, char *link); } SYS_UNLINK = 10 // { int unlink(char *path); } SYS_CHDIR = 12 // { int chdir(char *path); } SYS_FCHDIR = 13 // { int fchdir(int fd); } SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } SYS_CHMOD = 15 // { int chmod(char *path, int mode); } SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } SYS_OBREAK = 17 // { int obreak(char *nsize); } break obreak_args int SYS_GETFSSTAT = 18 // { int getfsstat(struct statfs *buf, long bufsize, \ SYS_GETPID = 20 // { pid_t getpid(void); } SYS_MOUNT = 21 // { int mount(char *type, char *path, int flags, \ SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } SYS_SETUID = 23 // { int setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t getuid(void); } SYS_GETEUID = 25 // { uid_t geteuid(void); } SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, caddr_t addr, \ SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { int sendmsg(int s, caddr_t msg, int flags); } SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, size_t len, \ SYS_ACCEPT = 30 // { int accept(int s, caddr_t name, int *anamelen); } SYS_GETPEERNAME = 31 // { int getpeername(int fdes, caddr_t asa, int *alen); } SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, caddr_t asa, int *alen); } SYS_ACCESS = 33 // { int access(char *path, int flags); } SYS_CHFLAGS = 34 // { int chflags(char *path, int flags); } SYS_FCHFLAGS = 35 // { int fchflags(int fd, int flags); } SYS_SYNC = 36 // { int sync(void); } SYS_KILL = 37 // { int kill(int pid, int signum); } SYS_GETPPID = 39 // { pid_t getppid(void); } SYS_DUP = 41 // { int dup(int fd); } SYS_PIPE = 42 // { int pipe(void); } SYS_GETEGID = 43 // { gid_t getegid(void); } SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \ SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, int facs, \ SYS_GETGID = 47 // { gid_t getgid(void); } SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int namelen); } SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } SYS_ACCT = 51 // { int acct(char *path); } SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, stack_t *oss); } SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, caddr_t data); } SYS_REBOOT = 55 // { int reboot(int opt); } SYS_REVOKE = 56 // { int revoke(char *path); } SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } SYS_READLINK = 58 // { int readlink(char *path, char *buf, int count); } SYS_EXECVE = 59 // { int execve(char *fname, char **argv, char **envv); } SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args int SYS_CHROOT = 61 // { int chroot(char *path); } SYS_MSYNC = 65 // { int msync(void *addr, size_t len, int flags); } SYS_VFORK = 66 // { pid_t vfork(void); } SYS_SBRK = 69 // { int sbrk(int incr); } SYS_SSTK = 70 // { int sstk(int incr); } SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int mprotect(void *addr, size_t len, int prot); } SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, int behav); } SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \ SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, gid_t *gidset); } SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, gid_t *gidset); } SYS_GETPGRP = 81 // { int getpgrp(void); } SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } SYS_SETITIMER = 83 // { int setitimer(u_int which, struct itimerval *itv, \ SYS_SWAPON = 85 // { int swapon(char *name); } SYS_GETITIMER = 86 // { int getitimer(u_int which, struct itimerval *itv); } SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } SYS_DUP2 = 90 // { int dup2(int from, int to); } SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \ SYS_FSYNC = 95 // { int fsync(int fd); } SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, int prio); } SYS_SOCKET = 97 // { int socket(int domain, int type, int protocol); } SYS_CONNECT = 98 // { int connect(int s, caddr_t name, int namelen); } SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } SYS_BIND = 104 // { int bind(int s, caddr_t name, int namelen); } SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \ SYS_LISTEN = 106 // { int listen(int s, int backlog); } SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \ SYS_GETRUSAGE = 117 // { int getrusage(int who, struct rusage *rusage); } SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \ SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, u_int iovcnt); } SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \ SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \ SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } SYS_RENAME = 128 // { int rename(char *from, char *to); } SYS_FLOCK = 131 // { int flock(int fd, int how); } SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \ SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, int protocol, \ SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } SYS_RMDIR = 137 // { int rmdir(char *path); } SYS_UTIMES = 138 // { int utimes(char *path, struct timeval *tptr); } SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \ SYS_SETSID = 147 // { int setsid(void); } SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \ SYS_STATFS = 157 // { int statfs(char *path, struct statfs *buf); } SYS_FSTATFS = 158 // { int fstatfs(int fd, struct statfs *buf); } SYS_GETFH = 161 // { int getfh(char *fname, struct fhandle *fhp); } SYS_GETDOMAINNAME = 162 // { int getdomainname(char *domainname, int len); } SYS_SETDOMAINNAME = 163 // { int setdomainname(char *domainname, int len); } SYS_UNAME = 164 // { int uname(struct utsname *name); } SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \ SYS_EXTPREAD = 173 // { ssize_t extpread(int fd, void *buf, \ SYS_EXTPWRITE = 174 // { ssize_t extpwrite(int fd, const void *buf, \ SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int setgid(gid_t gid); } SYS_SETEGID = 182 // { int setegid(gid_t egid); } SYS_SETEUID = 183 // { int seteuid(uid_t euid); } SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \ SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \ SYS_MMAP = 197 // { caddr_t mmap(caddr_t addr, size_t len, int prot, \ // SYS_NOSYS = 198; // { int nosys(void); } __syscall __syscall_args int SYS_LSEEK = 199 // { off_t lseek(int fd, int pad, off_t offset, \ SYS_TRUNCATE = 200 // { int truncate(char *path, int pad, off_t length); } SYS_FTRUNCATE = 201 // { int ftruncate(int fd, int pad, off_t length); } SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, void *old, \ SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int undelete(char *path); } SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } SYS_GETPGID = 207 // { int getpgid(pid_t pid); } SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \ SYS___SEMCTL = 220 // { int __semctl(int semid, int semnum, int cmd, \ SYS_SEMGET = 221 // { int semget(key_t key, int nsems, int semflg); } SYS_SEMOP = 222 // { int semop(int semid, struct sembuf *sops, \ SYS_MSGCTL = 224 // { int msgctl(int msqid, int cmd, \ SYS_MSGGET = 225 // { int msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int msgsnd(int msqid, const void *msgp, size_t msgsz, \ SYS_MSGRCV = 227 // { int msgrcv(int msqid, void *msgp, size_t msgsz, \ SYS_SHMAT = 228 // { caddr_t shmat(int shmid, const void *shmaddr, \ SYS_SHMCTL = 229 // { int shmctl(int shmid, int cmd, \ SYS_SHMDT = 230 // { int shmdt(const void *shmaddr); } SYS_SHMGET = 231 // { int shmget(key_t key, size_t size, int shmflg); } SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \ SYS_CLOCK_SETTIME = 233 // { int clock_settime(clockid_t clock_id, \ SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \ SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \ SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, int inherit); } SYS_RFORK = 251 // { int rfork(int flags); } SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, u_int nfds, \ SYS_ISSETUGID = 253 // { int issetugid(void); } SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } SYS_LUTIMES = 276 // { int lutimes(char *path, struct timeval *tptr); } SYS_EXTPREADV = 289 // { ssize_t extpreadv(int fd, struct iovec *iovp, \ SYS_EXTPWRITEV = 290 // { ssize_t extpwritev(int fd, struct iovec *iovp,\ SYS_FHSTATFS = 297 // { int fhstatfs(const struct fhandle *u_fhp, struct statfs *buf); } SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, int flags); } SYS_MODNEXT = 300 // { int modnext(int modid); } SYS_MODSTAT = 301 // { int modstat(int modid, struct module_stat* stat); } SYS_MODFNEXT = 302 // { int modfnext(int modid); } SYS_MODFIND = 303 // { int modfind(const char *name); } SYS_KLDLOAD = 304 // { int kldload(const char *file); } SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } SYS_KLDFIND = 306 // { int kldfind(const char *file); } SYS_KLDNEXT = 307 // { int kldnext(int fileid); } SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct kld_file_stat* stat); } SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } SYS_GETSID = 310 // { int getsid(pid_t pid); } SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, uid_t suid); } SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, gid_t sgid); } SYS_AIO_RETURN = 314 // { int aio_return(struct aiocb *aiocbp); } SYS_AIO_SUSPEND = 315 // { int aio_suspend(struct aiocb * const * aiocbp, int nent, const struct timespec *timeout); } SYS_AIO_CANCEL = 316 // { int aio_cancel(int fd, struct aiocb *aiocbp); } SYS_AIO_ERROR = 317 // { int aio_error(struct aiocb *aiocbp); } SYS_AIO_READ = 318 // { int aio_read(struct aiocb *aiocbp); } SYS_AIO_WRITE = 319 // { int aio_write(struct aiocb *aiocbp); } SYS_LIO_LISTIO = 320 // { int lio_listio(int mode, struct aiocb * const *acb_list, int nent, struct sigevent *sig); } SYS_YIELD = 321 // { int yield(void); } SYS_MLOCKALL = 324 // { int mlockall(int how); } SYS_MUNLOCKALL = 325 // { int munlockall(void); } SYS___GETCWD = 326 // { int __getcwd(u_char *buf, u_int buflen); } SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, const struct sched_param *param); } SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct sched_param *param); } SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int policy, const struct sched_param *param); } SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } SYS_SCHED_YIELD = 331 // { int sched_yield (void); } SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, struct timespec *interval); } SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, void *data); } SYS_JAIL = 338 // { int jail(struct jail *jail); } SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, const sigset_t *set, \ SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } SYS_SIGACTION = 342 // { int sigaction(int sig, const struct sigaction *act, \ SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } SYS_SIGRETURN = 344 // { int sigreturn(ucontext_t *sigcntxp); } SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set,\ SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set,\ SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \ SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \ SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, acl_type_t type, \ SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, acl_type_t type, \ SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \ SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, acl_type_t type); } SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \ SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, acl_type_t type, \ SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \ SYS_EXTATTR_SET_FILE = 356 // { int extattr_set_file(const char *path, \ SYS_EXTATTR_GET_FILE = 357 // { int extattr_get_file(const char *path, \ SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \ SYS_AIO_WAITCOMPLETE = 359 // { int aio_waitcomplete(struct aiocb **aiocbp, struct timespec *timeout); } SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); } SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); } SYS_KQUEUE = 362 // { int kqueue(void); } SYS_KEVENT = 363 // { int kevent(int fd, \ SYS_KENV = 390 // { int kenv(int what, const char *name, char *value, int len); } SYS_LCHFLAGS = 391 // { int lchflags(char *path, int flags); } SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, int count); } SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, size_t nbytes, \ SYS_VARSYM_SET = 450 // { int varsym_set(int level, const char *name, const char *data); } SYS_VARSYM_GET = 451 // { int varsym_get(int mask, const char *wild, char *buf, int bufsize); } SYS_VARSYM_LIST = 452 // { int varsym_list(int level, char *buf, int maxsize, int *marker); } SYS_EXEC_SYS_REGISTER = 465 // { int exec_sys_register(void *entry); } SYS_EXEC_SYS_UNREGISTER = 466 // { int exec_sys_unregister(int id); } SYS_SYS_CHECKPOINT = 467 // { int sys_checkpoint(int type, int fd, pid_t pid, int retval); } SYS_MOUNTCTL = 468 // { int mountctl(const char *path, int op, int fd, const void *ctl, int ctllen, void *buf, int buflen); } SYS_UMTX_SLEEP = 469 // { int umtx_sleep(volatile const int *ptr, int value, int timeout); } SYS_UMTX_WAKEUP = 470 // { int umtx_wakeup(volatile const int *ptr, int count); } SYS_JAIL_ATTACH = 471 // { int jail_attach(int jid); } SYS_SET_TLS_AREA = 472 // { int set_tls_area(int which, struct tls_info *info, size_t infosize); } SYS_GET_TLS_AREA = 473 // { int get_tls_area(int which, struct tls_info *info, size_t infosize); } SYS_CLOSEFROM = 474 // { int closefrom(int fd); } SYS_STAT = 475 // { int stat(const char *path, struct stat *ub); } SYS_FSTAT = 476 // { int fstat(int fd, struct stat *sb); } SYS_LSTAT = 477 // { int lstat(const char *path, struct stat *ub); } SYS_FHSTAT = 478 // { int fhstat(const struct fhandle *u_fhp, struct stat *sb); } SYS_GETDIRENTRIES = 479 // { int getdirentries(int fd, char *buf, u_int count, \ SYS_GETDENTS = 480 // { int getdents(int fd, char *buf, size_t count); } SYS_USCHED_SET = 481 // { int usched_set(pid_t pid, int cmd, void *data, \ SYS_EXTACCEPT = 482 // { int extaccept(int s, int flags, caddr_t name, int *anamelen); } SYS_EXTCONNECT = 483 // { int extconnect(int s, int flags, caddr_t name, int namelen); } SYS_MCONTROL = 485 // { int mcontrol(void *addr, size_t len, int behav, off_t value); } SYS_VMSPACE_CREATE = 486 // { int vmspace_create(void *id, int type, void *data); } SYS_VMSPACE_DESTROY = 487 // { int vmspace_destroy(void *id); } SYS_VMSPACE_CTL = 488 // { int vmspace_ctl(void *id, int cmd, \ SYS_VMSPACE_MMAP = 489 // { int vmspace_mmap(void *id, void *addr, size_t len, \ SYS_VMSPACE_MUNMAP = 490 // { int vmspace_munmap(void *id, void *addr, \ SYS_VMSPACE_MCONTROL = 491 // { int vmspace_mcontrol(void *id, void *addr, \ SYS_VMSPACE_PREAD = 492 // { ssize_t vmspace_pread(void *id, void *buf, \ SYS_VMSPACE_PWRITE = 493 // { ssize_t vmspace_pwrite(void *id, const void *buf, \ SYS_EXTEXIT = 494 // { void extexit(int how, int status, void *addr); } SYS_LWP_CREATE = 495 // { int lwp_create(struct lwp_params *params); } SYS_LWP_GETTID = 496 // { lwpid_t lwp_gettid(void); } SYS_LWP_KILL = 497 // { int lwp_kill(pid_t pid, lwpid_t tid, int signum); } SYS_LWP_RTPRIO = 498 // { int lwp_rtprio(int function, pid_t pid, lwpid_t tid, struct rtprio *rtp); } SYS_PSELECT = 499 // { int pselect(int nd, fd_set *in, fd_set *ou, \ SYS_STATVFS = 500 // { int statvfs(const char *path, struct statvfs *buf); } SYS_FSTATVFS = 501 // { int fstatvfs(int fd, struct statvfs *buf); } SYS_FHSTATVFS = 502 // { int fhstatvfs(const struct fhandle *u_fhp, struct statvfs *buf); } SYS_GETVFSSTAT = 503 // { int getvfsstat(struct statfs *buf, \ SYS_OPENAT = 504 // { int openat(int fd, char *path, int flags, int mode); } SYS_FSTATAT = 505 // { int fstatat(int fd, char *path, \ SYS_FCHMODAT = 506 // { int fchmodat(int fd, char *path, int mode, \ SYS_FCHOWNAT = 507 // { int fchownat(int fd, char *path, int uid, int gid, \ SYS_UNLINKAT = 508 // { int unlinkat(int fd, char *path, int flags); } SYS_FACCESSAT = 509 // { int faccessat(int fd, char *path, int amode, \ SYS_MQ_OPEN = 510 // { mqd_t mq_open(const char * name, int oflag, \ SYS_MQ_CLOSE = 511 // { int mq_close(mqd_t mqdes); } SYS_MQ_UNLINK = 512 // { int mq_unlink(const char *name); } SYS_MQ_GETATTR = 513 // { int mq_getattr(mqd_t mqdes, \ SYS_MQ_SETATTR = 514 // { int mq_setattr(mqd_t mqdes, \ SYS_MQ_NOTIFY = 515 // { int mq_notify(mqd_t mqdes, \ SYS_MQ_SEND = 516 // { int mq_send(mqd_t mqdes, const char *msg_ptr, \ SYS_MQ_RECEIVE = 517 // { ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, \ SYS_MQ_TIMEDSEND = 518 // { int mq_timedsend(mqd_t mqdes, \ SYS_MQ_TIMEDRECEIVE = 519 // { ssize_t mq_timedreceive(mqd_t mqdes, \ SYS_IOPRIO_SET = 520 // { int ioprio_set(int which, int who, int prio); } SYS_IOPRIO_GET = 521 // { int ioprio_get(int which, int who); } SYS_CHROOT_KERNEL = 522 // { int chroot_kernel(char *path); } SYS_RENAMEAT = 523 // { int renameat(int oldfd, char *old, int newfd, \ SYS_MKDIRAT = 524 // { int mkdirat(int fd, char *path, mode_t mode); } SYS_MKFIFOAT = 525 // { int mkfifoat(int fd, char *path, mode_t mode); } SYS_MKNODAT = 526 // { int mknodat(int fd, char *path, mode_t mode, \ SYS_READLINKAT = 527 // { int readlinkat(int fd, char *path, char *buf, \ SYS_SYMLINKAT = 528 // { int symlinkat(char *path1, int fd, char *path2); } SYS_SWAPOFF = 529 // { int swapoff(char *name); } SYS_VQUOTACTL = 530 // { int vquotactl(const char *path, \ SYS_LINKAT = 531 // { int linkat(int fd1, char *path1, int fd2, \ SYS_EACCESS = 532 // { int eaccess(char *path, int flags); } SYS_LPATHCONF = 533 // { int lpathconf(char *path, int name); } SYS_VMM_GUEST_CTL = 534 // { int vmm_guest_ctl(int op, struct vmm_guest_options *options); } SYS_VMM_GUEST_SYNC_ADDR = 535 // { int vmm_guest_sync_addr(long *dstaddr, long *srcaddr); } SYS_PROCCTL = 536 // { int procctl(idtype_t idtype, id_t id, int cmd, void *data); } SYS_CHFLAGSAT = 537 // { int chflagsat(int fd, const char *path, int flags, int atflags);} SYS_PIPE2 = 538 // { int pipe2(int *fildes, int flags); } SYS_UTIMENSAT = 539 // { int utimensat(int fd, const char *path, const struct timespec *ts, int flags); } SYS_FUTIMENS = 540 // { int futimens(int fd, const struct timespec *ts); } SYS_ACCEPT4 = 541 // { int accept4(int s, caddr_t name, int *anamelen, int flags); } SYS_LWP_SETNAME = 542 // { int lwp_setname(lwpid_t tid, const char *name); } SYS_PPOLL = 543 // { int ppoll(struct pollfd *fds, u_int nfds, \ SYS_LWP_SETAFFINITY = 544 // { int lwp_setaffinity(pid_t pid, lwpid_t tid, const cpumask_t *mask); } SYS_LWP_GETAFFINITY = 545 // { int lwp_getaffinity(pid_t pid, lwpid_t tid, cpumask_t *mask); } SYS_LWP_CREATE2 = 546 // { int lwp_create2(struct lwp_params *params, const cpumask_t *mask); } ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_darwin_arm64.go0000644061062106075000000004244313172163421025772 0ustar stgraberdomain admins// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk/usr/include/sys/syscall.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm64,darwin package unix const ( SYS_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAIT4 = 7 SYS_LINK = 9 SYS_UNLINK = 10 SYS_CHDIR = 12 SYS_FCHDIR = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_CHOWN = 16 SYS_GETFSSTAT = 18 SYS_GETPID = 20 SYS_SETUID = 23 SYS_GETUID = 24 SYS_GETEUID = 25 SYS_PTRACE = 26 SYS_RECVMSG = 27 SYS_SENDMSG = 28 SYS_RECVFROM = 29 SYS_ACCEPT = 30 SYS_GETPEERNAME = 31 SYS_GETSOCKNAME = 32 SYS_ACCESS = 33 SYS_CHFLAGS = 34 SYS_FCHFLAGS = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_GETPPID = 39 SYS_DUP = 41 SYS_PIPE = 42 SYS_GETEGID = 43 SYS_SIGACTION = 46 SYS_GETGID = 47 SYS_SIGPROCMASK = 48 SYS_GETLOGIN = 49 SYS_SETLOGIN = 50 SYS_ACCT = 51 SYS_SIGPENDING = 52 SYS_SIGALTSTACK = 53 SYS_IOCTL = 54 SYS_REBOOT = 55 SYS_REVOKE = 56 SYS_SYMLINK = 57 SYS_READLINK = 58 SYS_EXECVE = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_MSYNC = 65 SYS_VFORK = 66 SYS_MUNMAP = 73 SYS_MPROTECT = 74 SYS_MADVISE = 75 SYS_MINCORE = 78 SYS_GETGROUPS = 79 SYS_SETGROUPS = 80 SYS_GETPGRP = 81 SYS_SETPGID = 82 SYS_SETITIMER = 83 SYS_SWAPON = 85 SYS_GETITIMER = 86 SYS_GETDTABLESIZE = 89 SYS_DUP2 = 90 SYS_FCNTL = 92 SYS_SELECT = 93 SYS_FSYNC = 95 SYS_SETPRIORITY = 96 SYS_SOCKET = 97 SYS_CONNECT = 98 SYS_GETPRIORITY = 100 SYS_BIND = 104 SYS_SETSOCKOPT = 105 SYS_LISTEN = 106 SYS_SIGSUSPEND = 111 SYS_GETTIMEOFDAY = 116 SYS_GETRUSAGE = 117 SYS_GETSOCKOPT = 118 SYS_READV = 120 SYS_WRITEV = 121 SYS_SETTIMEOFDAY = 122 SYS_FCHOWN = 123 SYS_FCHMOD = 124 SYS_SETREUID = 126 SYS_SETREGID = 127 SYS_RENAME = 128 SYS_FLOCK = 131 SYS_MKFIFO = 132 SYS_SENDTO = 133 SYS_SHUTDOWN = 134 SYS_SOCKETPAIR = 135 SYS_MKDIR = 136 SYS_RMDIR = 137 SYS_UTIMES = 138 SYS_FUTIMES = 139 SYS_ADJTIME = 140 SYS_GETHOSTUUID = 142 SYS_SETSID = 147 SYS_GETPGID = 151 SYS_SETPRIVEXEC = 152 SYS_PREAD = 153 SYS_PWRITE = 154 SYS_NFSSVC = 155 SYS_STATFS = 157 SYS_FSTATFS = 158 SYS_UNMOUNT = 159 SYS_GETFH = 161 SYS_QUOTACTL = 165 SYS_MOUNT = 167 SYS_CSOPS = 169 SYS_CSOPS_AUDITTOKEN = 170 SYS_WAITID = 173 SYS_KDEBUG_TYPEFILTER = 177 SYS_KDEBUG_TRACE_STRING = 178 SYS_KDEBUG_TRACE64 = 179 SYS_KDEBUG_TRACE = 180 SYS_SETGID = 181 SYS_SETEGID = 182 SYS_SETEUID = 183 SYS_SIGRETURN = 184 SYS_FDATASYNC = 187 SYS_STAT = 188 SYS_FSTAT = 189 SYS_LSTAT = 190 SYS_PATHCONF = 191 SYS_FPATHCONF = 192 SYS_GETRLIMIT = 194 SYS_SETRLIMIT = 195 SYS_GETDIRENTRIES = 196 SYS_MMAP = 197 SYS_LSEEK = 199 SYS_TRUNCATE = 200 SYS_FTRUNCATE = 201 SYS_SYSCTL = 202 SYS_MLOCK = 203 SYS_MUNLOCK = 204 SYS_UNDELETE = 205 SYS_OPEN_DPROTECTED_NP = 216 SYS_GETATTRLIST = 220 SYS_SETATTRLIST = 221 SYS_GETDIRENTRIESATTR = 222 SYS_EXCHANGEDATA = 223 SYS_SEARCHFS = 225 SYS_DELETE = 226 SYS_COPYFILE = 227 SYS_FGETATTRLIST = 228 SYS_FSETATTRLIST = 229 SYS_POLL = 230 SYS_WATCHEVENT = 231 SYS_WAITEVENT = 232 SYS_MODWATCH = 233 SYS_GETXATTR = 234 SYS_FGETXATTR = 235 SYS_SETXATTR = 236 SYS_FSETXATTR = 237 SYS_REMOVEXATTR = 238 SYS_FREMOVEXATTR = 239 SYS_LISTXATTR = 240 SYS_FLISTXATTR = 241 SYS_FSCTL = 242 SYS_INITGROUPS = 243 SYS_POSIX_SPAWN = 244 SYS_FFSCTL = 245 SYS_NFSCLNT = 247 SYS_FHOPEN = 248 SYS_MINHERIT = 250 SYS_SEMSYS = 251 SYS_MSGSYS = 252 SYS_SHMSYS = 253 SYS_SEMCTL = 254 SYS_SEMGET = 255 SYS_SEMOP = 256 SYS_MSGCTL = 258 SYS_MSGGET = 259 SYS_MSGSND = 260 SYS_MSGRCV = 261 SYS_SHMAT = 262 SYS_SHMCTL = 263 SYS_SHMDT = 264 SYS_SHMGET = 265 SYS_SHM_OPEN = 266 SYS_SHM_UNLINK = 267 SYS_SEM_OPEN = 268 SYS_SEM_CLOSE = 269 SYS_SEM_UNLINK = 270 SYS_SEM_WAIT = 271 SYS_SEM_TRYWAIT = 272 SYS_SEM_POST = 273 SYS_SYSCTLBYNAME = 274 SYS_OPEN_EXTENDED = 277 SYS_UMASK_EXTENDED = 278 SYS_STAT_EXTENDED = 279 SYS_LSTAT_EXTENDED = 280 SYS_FSTAT_EXTENDED = 281 SYS_CHMOD_EXTENDED = 282 SYS_FCHMOD_EXTENDED = 283 SYS_ACCESS_EXTENDED = 284 SYS_SETTID = 285 SYS_GETTID = 286 SYS_SETSGROUPS = 287 SYS_GETSGROUPS = 288 SYS_SETWGROUPS = 289 SYS_GETWGROUPS = 290 SYS_MKFIFO_EXTENDED = 291 SYS_MKDIR_EXTENDED = 292 SYS_IDENTITYSVC = 293 SYS_SHARED_REGION_CHECK_NP = 294 SYS_VM_PRESSURE_MONITOR = 296 SYS_PSYNCH_RW_LONGRDLOCK = 297 SYS_PSYNCH_RW_YIELDWRLOCK = 298 SYS_PSYNCH_RW_DOWNGRADE = 299 SYS_PSYNCH_RW_UPGRADE = 300 SYS_PSYNCH_MUTEXWAIT = 301 SYS_PSYNCH_MUTEXDROP = 302 SYS_PSYNCH_CVBROAD = 303 SYS_PSYNCH_CVSIGNAL = 304 SYS_PSYNCH_CVWAIT = 305 SYS_PSYNCH_RW_RDLOCK = 306 SYS_PSYNCH_RW_WRLOCK = 307 SYS_PSYNCH_RW_UNLOCK = 308 SYS_PSYNCH_RW_UNLOCK2 = 309 SYS_GETSID = 310 SYS_SETTID_WITH_PID = 311 SYS_PSYNCH_CVCLRPREPOST = 312 SYS_AIO_FSYNC = 313 SYS_AIO_RETURN = 314 SYS_AIO_SUSPEND = 315 SYS_AIO_CANCEL = 316 SYS_AIO_ERROR = 317 SYS_AIO_READ = 318 SYS_AIO_WRITE = 319 SYS_LIO_LISTIO = 320 SYS_IOPOLICYSYS = 322 SYS_PROCESS_POLICY = 323 SYS_MLOCKALL = 324 SYS_MUNLOCKALL = 325 SYS_ISSETUGID = 327 SYS___PTHREAD_KILL = 328 SYS___PTHREAD_SIGMASK = 329 SYS___SIGWAIT = 330 SYS___DISABLE_THREADSIGNAL = 331 SYS___PTHREAD_MARKCANCEL = 332 SYS___PTHREAD_CANCELED = 333 SYS___SEMWAIT_SIGNAL = 334 SYS_PROC_INFO = 336 SYS_SENDFILE = 337 SYS_STAT64 = 338 SYS_FSTAT64 = 339 SYS_LSTAT64 = 340 SYS_STAT64_EXTENDED = 341 SYS_LSTAT64_EXTENDED = 342 SYS_FSTAT64_EXTENDED = 343 SYS_GETDIRENTRIES64 = 344 SYS_STATFS64 = 345 SYS_FSTATFS64 = 346 SYS_GETFSSTAT64 = 347 SYS___PTHREAD_CHDIR = 348 SYS___PTHREAD_FCHDIR = 349 SYS_AUDIT = 350 SYS_AUDITON = 351 SYS_GETAUID = 353 SYS_SETAUID = 354 SYS_GETAUDIT_ADDR = 357 SYS_SETAUDIT_ADDR = 358 SYS_AUDITCTL = 359 SYS_BSDTHREAD_CREATE = 360 SYS_BSDTHREAD_TERMINATE = 361 SYS_KQUEUE = 362 SYS_KEVENT = 363 SYS_LCHOWN = 364 SYS_BSDTHREAD_REGISTER = 366 SYS_WORKQ_OPEN = 367 SYS_WORKQ_KERNRETURN = 368 SYS_KEVENT64 = 369 SYS___OLD_SEMWAIT_SIGNAL = 370 SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371 SYS_THREAD_SELFID = 372 SYS_LEDGER = 373 SYS_KEVENT_QOS = 374 SYS___MAC_EXECVE = 380 SYS___MAC_SYSCALL = 381 SYS___MAC_GET_FILE = 382 SYS___MAC_SET_FILE = 383 SYS___MAC_GET_LINK = 384 SYS___MAC_SET_LINK = 385 SYS___MAC_GET_PROC = 386 SYS___MAC_SET_PROC = 387 SYS___MAC_GET_FD = 388 SYS___MAC_SET_FD = 389 SYS___MAC_GET_PID = 390 SYS_PSELECT = 394 SYS_PSELECT_NOCANCEL = 395 SYS_READ_NOCANCEL = 396 SYS_WRITE_NOCANCEL = 397 SYS_OPEN_NOCANCEL = 398 SYS_CLOSE_NOCANCEL = 399 SYS_WAIT4_NOCANCEL = 400 SYS_RECVMSG_NOCANCEL = 401 SYS_SENDMSG_NOCANCEL = 402 SYS_RECVFROM_NOCANCEL = 403 SYS_ACCEPT_NOCANCEL = 404 SYS_MSYNC_NOCANCEL = 405 SYS_FCNTL_NOCANCEL = 406 SYS_SELECT_NOCANCEL = 407 SYS_FSYNC_NOCANCEL = 408 SYS_CONNECT_NOCANCEL = 409 SYS_SIGSUSPEND_NOCANCEL = 410 SYS_READV_NOCANCEL = 411 SYS_WRITEV_NOCANCEL = 412 SYS_SENDTO_NOCANCEL = 413 SYS_PREAD_NOCANCEL = 414 SYS_PWRITE_NOCANCEL = 415 SYS_WAITID_NOCANCEL = 416 SYS_POLL_NOCANCEL = 417 SYS_MSGSND_NOCANCEL = 418 SYS_MSGRCV_NOCANCEL = 419 SYS_SEM_WAIT_NOCANCEL = 420 SYS_AIO_SUSPEND_NOCANCEL = 421 SYS___SIGWAIT_NOCANCEL = 422 SYS___SEMWAIT_SIGNAL_NOCANCEL = 423 SYS___MAC_MOUNT = 424 SYS___MAC_GET_MOUNT = 425 SYS___MAC_GETFSSTAT = 426 SYS_FSGETPATH = 427 SYS_AUDIT_SESSION_SELF = 428 SYS_AUDIT_SESSION_JOIN = 429 SYS_FILEPORT_MAKEPORT = 430 SYS_FILEPORT_MAKEFD = 431 SYS_AUDIT_SESSION_PORT = 432 SYS_PID_SUSPEND = 433 SYS_PID_RESUME = 434 SYS_PID_HIBERNATE = 435 SYS_PID_SHUTDOWN_SOCKETS = 436 SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438 SYS_KAS_INFO = 439 SYS_MEMORYSTATUS_CONTROL = 440 SYS_GUARDED_OPEN_NP = 441 SYS_GUARDED_CLOSE_NP = 442 SYS_GUARDED_KQUEUE_NP = 443 SYS_CHANGE_FDGUARD_NP = 444 SYS_USRCTL = 445 SYS_PROC_RLIMIT_CONTROL = 446 SYS_CONNECTX = 447 SYS_DISCONNECTX = 448 SYS_PEELOFF = 449 SYS_SOCKET_DELEGATE = 450 SYS_TELEMETRY = 451 SYS_PROC_UUID_POLICY = 452 SYS_MEMORYSTATUS_GET_LEVEL = 453 SYS_SYSTEM_OVERRIDE = 454 SYS_VFS_PURGE = 455 SYS_SFI_CTL = 456 SYS_SFI_PIDCTL = 457 SYS_COALITION = 458 SYS_COALITION_INFO = 459 SYS_NECP_MATCH_POLICY = 460 SYS_GETATTRLISTBULK = 461 SYS_CLONEFILEAT = 462 SYS_OPENAT = 463 SYS_OPENAT_NOCANCEL = 464 SYS_RENAMEAT = 465 SYS_FACCESSAT = 466 SYS_FCHMODAT = 467 SYS_FCHOWNAT = 468 SYS_FSTATAT = 469 SYS_FSTATAT64 = 470 SYS_LINKAT = 471 SYS_UNLINKAT = 472 SYS_READLINKAT = 473 SYS_SYMLINKAT = 474 SYS_MKDIRAT = 475 SYS_GETATTRLISTAT = 476 SYS_PROC_TRACE_LOG = 477 SYS_BSDTHREAD_CTL = 478 SYS_OPENBYID_NP = 479 SYS_RECVMSG_X = 480 SYS_SENDMSG_X = 481 SYS_THREAD_SELFUSAGE = 482 SYS_CSRCTL = 483 SYS_GUARDED_OPEN_DPROTECTED_NP = 484 SYS_GUARDED_WRITE_NP = 485 SYS_GUARDED_PWRITE_NP = 486 SYS_GUARDED_WRITEV_NP = 487 SYS_RENAMEATX_NP = 488 SYS_MREMAP_ENCRYPTED = 489 SYS_NETAGENT_TRIGGER = 490 SYS_STACK_SNAPSHOT_WITH_CONFIG = 491 SYS_MICROSTACKSHOT = 492 SYS_GRAB_PGO_DATA = 493 SYS_PERSONA = 494 SYS_WORK_INTERVAL_CTL = 499 SYS_GETENTROPY = 500 SYS_NECP_OPEN = 501 SYS_NECP_CLIENT_ACTION = 502 SYS___NEXUS_OPEN = 503 SYS___NEXUS_REGISTER = 504 SYS___NEXUS_DEREGISTER = 505 SYS___NEXUS_CREATE = 506 SYS___NEXUS_DESTROY = 507 SYS___NEXUS_GET_OPT = 508 SYS___NEXUS_SET_OPT = 509 SYS___CHANNEL_OPEN = 510 SYS___CHANNEL_GET_INFO = 511 SYS___CHANNEL_SYNC = 512 SYS___CHANNEL_GET_OPT = 513 SYS___CHANNEL_SET_OPT = 514 SYS_ULOCK_WAIT = 515 SYS_ULOCK_WAKE = 516 SYS_FCLONEFILEAT = 517 SYS_FS_SNAPSHOT = 518 SYS_TERMINATE_WITH_PAYLOAD = 520 SYS_ABORT_WITH_PAYLOAD = 521 SYS_MAXSYSCALL = 522 SYS_INVALID = 63 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_darwin_arm.go0000644061062106075000000004244113172163421025616 0ustar stgraberdomain admins// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk/usr/include/sys/syscall.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,darwin package unix const ( SYS_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAIT4 = 7 SYS_LINK = 9 SYS_UNLINK = 10 SYS_CHDIR = 12 SYS_FCHDIR = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_CHOWN = 16 SYS_GETFSSTAT = 18 SYS_GETPID = 20 SYS_SETUID = 23 SYS_GETUID = 24 SYS_GETEUID = 25 SYS_PTRACE = 26 SYS_RECVMSG = 27 SYS_SENDMSG = 28 SYS_RECVFROM = 29 SYS_ACCEPT = 30 SYS_GETPEERNAME = 31 SYS_GETSOCKNAME = 32 SYS_ACCESS = 33 SYS_CHFLAGS = 34 SYS_FCHFLAGS = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_GETPPID = 39 SYS_DUP = 41 SYS_PIPE = 42 SYS_GETEGID = 43 SYS_SIGACTION = 46 SYS_GETGID = 47 SYS_SIGPROCMASK = 48 SYS_GETLOGIN = 49 SYS_SETLOGIN = 50 SYS_ACCT = 51 SYS_SIGPENDING = 52 SYS_SIGALTSTACK = 53 SYS_IOCTL = 54 SYS_REBOOT = 55 SYS_REVOKE = 56 SYS_SYMLINK = 57 SYS_READLINK = 58 SYS_EXECVE = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_MSYNC = 65 SYS_VFORK = 66 SYS_MUNMAP = 73 SYS_MPROTECT = 74 SYS_MADVISE = 75 SYS_MINCORE = 78 SYS_GETGROUPS = 79 SYS_SETGROUPS = 80 SYS_GETPGRP = 81 SYS_SETPGID = 82 SYS_SETITIMER = 83 SYS_SWAPON = 85 SYS_GETITIMER = 86 SYS_GETDTABLESIZE = 89 SYS_DUP2 = 90 SYS_FCNTL = 92 SYS_SELECT = 93 SYS_FSYNC = 95 SYS_SETPRIORITY = 96 SYS_SOCKET = 97 SYS_CONNECT = 98 SYS_GETPRIORITY = 100 SYS_BIND = 104 SYS_SETSOCKOPT = 105 SYS_LISTEN = 106 SYS_SIGSUSPEND = 111 SYS_GETTIMEOFDAY = 116 SYS_GETRUSAGE = 117 SYS_GETSOCKOPT = 118 SYS_READV = 120 SYS_WRITEV = 121 SYS_SETTIMEOFDAY = 122 SYS_FCHOWN = 123 SYS_FCHMOD = 124 SYS_SETREUID = 126 SYS_SETREGID = 127 SYS_RENAME = 128 SYS_FLOCK = 131 SYS_MKFIFO = 132 SYS_SENDTO = 133 SYS_SHUTDOWN = 134 SYS_SOCKETPAIR = 135 SYS_MKDIR = 136 SYS_RMDIR = 137 SYS_UTIMES = 138 SYS_FUTIMES = 139 SYS_ADJTIME = 140 SYS_GETHOSTUUID = 142 SYS_SETSID = 147 SYS_GETPGID = 151 SYS_SETPRIVEXEC = 152 SYS_PREAD = 153 SYS_PWRITE = 154 SYS_NFSSVC = 155 SYS_STATFS = 157 SYS_FSTATFS = 158 SYS_UNMOUNT = 159 SYS_GETFH = 161 SYS_QUOTACTL = 165 SYS_MOUNT = 167 SYS_CSOPS = 169 SYS_CSOPS_AUDITTOKEN = 170 SYS_WAITID = 173 SYS_KDEBUG_TYPEFILTER = 177 SYS_KDEBUG_TRACE_STRING = 178 SYS_KDEBUG_TRACE64 = 179 SYS_KDEBUG_TRACE = 180 SYS_SETGID = 181 SYS_SETEGID = 182 SYS_SETEUID = 183 SYS_SIGRETURN = 184 SYS_FDATASYNC = 187 SYS_STAT = 188 SYS_FSTAT = 189 SYS_LSTAT = 190 SYS_PATHCONF = 191 SYS_FPATHCONF = 192 SYS_GETRLIMIT = 194 SYS_SETRLIMIT = 195 SYS_GETDIRENTRIES = 196 SYS_MMAP = 197 SYS_LSEEK = 199 SYS_TRUNCATE = 200 SYS_FTRUNCATE = 201 SYS_SYSCTL = 202 SYS_MLOCK = 203 SYS_MUNLOCK = 204 SYS_UNDELETE = 205 SYS_OPEN_DPROTECTED_NP = 216 SYS_GETATTRLIST = 220 SYS_SETATTRLIST = 221 SYS_GETDIRENTRIESATTR = 222 SYS_EXCHANGEDATA = 223 SYS_SEARCHFS = 225 SYS_DELETE = 226 SYS_COPYFILE = 227 SYS_FGETATTRLIST = 228 SYS_FSETATTRLIST = 229 SYS_POLL = 230 SYS_WATCHEVENT = 231 SYS_WAITEVENT = 232 SYS_MODWATCH = 233 SYS_GETXATTR = 234 SYS_FGETXATTR = 235 SYS_SETXATTR = 236 SYS_FSETXATTR = 237 SYS_REMOVEXATTR = 238 SYS_FREMOVEXATTR = 239 SYS_LISTXATTR = 240 SYS_FLISTXATTR = 241 SYS_FSCTL = 242 SYS_INITGROUPS = 243 SYS_POSIX_SPAWN = 244 SYS_FFSCTL = 245 SYS_NFSCLNT = 247 SYS_FHOPEN = 248 SYS_MINHERIT = 250 SYS_SEMSYS = 251 SYS_MSGSYS = 252 SYS_SHMSYS = 253 SYS_SEMCTL = 254 SYS_SEMGET = 255 SYS_SEMOP = 256 SYS_MSGCTL = 258 SYS_MSGGET = 259 SYS_MSGSND = 260 SYS_MSGRCV = 261 SYS_SHMAT = 262 SYS_SHMCTL = 263 SYS_SHMDT = 264 SYS_SHMGET = 265 SYS_SHM_OPEN = 266 SYS_SHM_UNLINK = 267 SYS_SEM_OPEN = 268 SYS_SEM_CLOSE = 269 SYS_SEM_UNLINK = 270 SYS_SEM_WAIT = 271 SYS_SEM_TRYWAIT = 272 SYS_SEM_POST = 273 SYS_SYSCTLBYNAME = 274 SYS_OPEN_EXTENDED = 277 SYS_UMASK_EXTENDED = 278 SYS_STAT_EXTENDED = 279 SYS_LSTAT_EXTENDED = 280 SYS_FSTAT_EXTENDED = 281 SYS_CHMOD_EXTENDED = 282 SYS_FCHMOD_EXTENDED = 283 SYS_ACCESS_EXTENDED = 284 SYS_SETTID = 285 SYS_GETTID = 286 SYS_SETSGROUPS = 287 SYS_GETSGROUPS = 288 SYS_SETWGROUPS = 289 SYS_GETWGROUPS = 290 SYS_MKFIFO_EXTENDED = 291 SYS_MKDIR_EXTENDED = 292 SYS_IDENTITYSVC = 293 SYS_SHARED_REGION_CHECK_NP = 294 SYS_VM_PRESSURE_MONITOR = 296 SYS_PSYNCH_RW_LONGRDLOCK = 297 SYS_PSYNCH_RW_YIELDWRLOCK = 298 SYS_PSYNCH_RW_DOWNGRADE = 299 SYS_PSYNCH_RW_UPGRADE = 300 SYS_PSYNCH_MUTEXWAIT = 301 SYS_PSYNCH_MUTEXDROP = 302 SYS_PSYNCH_CVBROAD = 303 SYS_PSYNCH_CVSIGNAL = 304 SYS_PSYNCH_CVWAIT = 305 SYS_PSYNCH_RW_RDLOCK = 306 SYS_PSYNCH_RW_WRLOCK = 307 SYS_PSYNCH_RW_UNLOCK = 308 SYS_PSYNCH_RW_UNLOCK2 = 309 SYS_GETSID = 310 SYS_SETTID_WITH_PID = 311 SYS_PSYNCH_CVCLRPREPOST = 312 SYS_AIO_FSYNC = 313 SYS_AIO_RETURN = 314 SYS_AIO_SUSPEND = 315 SYS_AIO_CANCEL = 316 SYS_AIO_ERROR = 317 SYS_AIO_READ = 318 SYS_AIO_WRITE = 319 SYS_LIO_LISTIO = 320 SYS_IOPOLICYSYS = 322 SYS_PROCESS_POLICY = 323 SYS_MLOCKALL = 324 SYS_MUNLOCKALL = 325 SYS_ISSETUGID = 327 SYS___PTHREAD_KILL = 328 SYS___PTHREAD_SIGMASK = 329 SYS___SIGWAIT = 330 SYS___DISABLE_THREADSIGNAL = 331 SYS___PTHREAD_MARKCANCEL = 332 SYS___PTHREAD_CANCELED = 333 SYS___SEMWAIT_SIGNAL = 334 SYS_PROC_INFO = 336 SYS_SENDFILE = 337 SYS_STAT64 = 338 SYS_FSTAT64 = 339 SYS_LSTAT64 = 340 SYS_STAT64_EXTENDED = 341 SYS_LSTAT64_EXTENDED = 342 SYS_FSTAT64_EXTENDED = 343 SYS_GETDIRENTRIES64 = 344 SYS_STATFS64 = 345 SYS_FSTATFS64 = 346 SYS_GETFSSTAT64 = 347 SYS___PTHREAD_CHDIR = 348 SYS___PTHREAD_FCHDIR = 349 SYS_AUDIT = 350 SYS_AUDITON = 351 SYS_GETAUID = 353 SYS_SETAUID = 354 SYS_GETAUDIT_ADDR = 357 SYS_SETAUDIT_ADDR = 358 SYS_AUDITCTL = 359 SYS_BSDTHREAD_CREATE = 360 SYS_BSDTHREAD_TERMINATE = 361 SYS_KQUEUE = 362 SYS_KEVENT = 363 SYS_LCHOWN = 364 SYS_BSDTHREAD_REGISTER = 366 SYS_WORKQ_OPEN = 367 SYS_WORKQ_KERNRETURN = 368 SYS_KEVENT64 = 369 SYS___OLD_SEMWAIT_SIGNAL = 370 SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371 SYS_THREAD_SELFID = 372 SYS_LEDGER = 373 SYS_KEVENT_QOS = 374 SYS___MAC_EXECVE = 380 SYS___MAC_SYSCALL = 381 SYS___MAC_GET_FILE = 382 SYS___MAC_SET_FILE = 383 SYS___MAC_GET_LINK = 384 SYS___MAC_SET_LINK = 385 SYS___MAC_GET_PROC = 386 SYS___MAC_SET_PROC = 387 SYS___MAC_GET_FD = 388 SYS___MAC_SET_FD = 389 SYS___MAC_GET_PID = 390 SYS_PSELECT = 394 SYS_PSELECT_NOCANCEL = 395 SYS_READ_NOCANCEL = 396 SYS_WRITE_NOCANCEL = 397 SYS_OPEN_NOCANCEL = 398 SYS_CLOSE_NOCANCEL = 399 SYS_WAIT4_NOCANCEL = 400 SYS_RECVMSG_NOCANCEL = 401 SYS_SENDMSG_NOCANCEL = 402 SYS_RECVFROM_NOCANCEL = 403 SYS_ACCEPT_NOCANCEL = 404 SYS_MSYNC_NOCANCEL = 405 SYS_FCNTL_NOCANCEL = 406 SYS_SELECT_NOCANCEL = 407 SYS_FSYNC_NOCANCEL = 408 SYS_CONNECT_NOCANCEL = 409 SYS_SIGSUSPEND_NOCANCEL = 410 SYS_READV_NOCANCEL = 411 SYS_WRITEV_NOCANCEL = 412 SYS_SENDTO_NOCANCEL = 413 SYS_PREAD_NOCANCEL = 414 SYS_PWRITE_NOCANCEL = 415 SYS_WAITID_NOCANCEL = 416 SYS_POLL_NOCANCEL = 417 SYS_MSGSND_NOCANCEL = 418 SYS_MSGRCV_NOCANCEL = 419 SYS_SEM_WAIT_NOCANCEL = 420 SYS_AIO_SUSPEND_NOCANCEL = 421 SYS___SIGWAIT_NOCANCEL = 422 SYS___SEMWAIT_SIGNAL_NOCANCEL = 423 SYS___MAC_MOUNT = 424 SYS___MAC_GET_MOUNT = 425 SYS___MAC_GETFSSTAT = 426 SYS_FSGETPATH = 427 SYS_AUDIT_SESSION_SELF = 428 SYS_AUDIT_SESSION_JOIN = 429 SYS_FILEPORT_MAKEPORT = 430 SYS_FILEPORT_MAKEFD = 431 SYS_AUDIT_SESSION_PORT = 432 SYS_PID_SUSPEND = 433 SYS_PID_RESUME = 434 SYS_PID_HIBERNATE = 435 SYS_PID_SHUTDOWN_SOCKETS = 436 SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438 SYS_KAS_INFO = 439 SYS_MEMORYSTATUS_CONTROL = 440 SYS_GUARDED_OPEN_NP = 441 SYS_GUARDED_CLOSE_NP = 442 SYS_GUARDED_KQUEUE_NP = 443 SYS_CHANGE_FDGUARD_NP = 444 SYS_USRCTL = 445 SYS_PROC_RLIMIT_CONTROL = 446 SYS_CONNECTX = 447 SYS_DISCONNECTX = 448 SYS_PEELOFF = 449 SYS_SOCKET_DELEGATE = 450 SYS_TELEMETRY = 451 SYS_PROC_UUID_POLICY = 452 SYS_MEMORYSTATUS_GET_LEVEL = 453 SYS_SYSTEM_OVERRIDE = 454 SYS_VFS_PURGE = 455 SYS_SFI_CTL = 456 SYS_SFI_PIDCTL = 457 SYS_COALITION = 458 SYS_COALITION_INFO = 459 SYS_NECP_MATCH_POLICY = 460 SYS_GETATTRLISTBULK = 461 SYS_CLONEFILEAT = 462 SYS_OPENAT = 463 SYS_OPENAT_NOCANCEL = 464 SYS_RENAMEAT = 465 SYS_FACCESSAT = 466 SYS_FCHMODAT = 467 SYS_FCHOWNAT = 468 SYS_FSTATAT = 469 SYS_FSTATAT64 = 470 SYS_LINKAT = 471 SYS_UNLINKAT = 472 SYS_READLINKAT = 473 SYS_SYMLINKAT = 474 SYS_MKDIRAT = 475 SYS_GETATTRLISTAT = 476 SYS_PROC_TRACE_LOG = 477 SYS_BSDTHREAD_CTL = 478 SYS_OPENBYID_NP = 479 SYS_RECVMSG_X = 480 SYS_SENDMSG_X = 481 SYS_THREAD_SELFUSAGE = 482 SYS_CSRCTL = 483 SYS_GUARDED_OPEN_DPROTECTED_NP = 484 SYS_GUARDED_WRITE_NP = 485 SYS_GUARDED_PWRITE_NP = 486 SYS_GUARDED_WRITEV_NP = 487 SYS_RENAMEATX_NP = 488 SYS_MREMAP_ENCRYPTED = 489 SYS_NETAGENT_TRIGGER = 490 SYS_STACK_SNAPSHOT_WITH_CONFIG = 491 SYS_MICROSTACKSHOT = 492 SYS_GRAB_PGO_DATA = 493 SYS_PERSONA = 494 SYS_WORK_INTERVAL_CTL = 499 SYS_GETENTROPY = 500 SYS_NECP_OPEN = 501 SYS_NECP_CLIENT_ACTION = 502 SYS___NEXUS_OPEN = 503 SYS___NEXUS_REGISTER = 504 SYS___NEXUS_DEREGISTER = 505 SYS___NEXUS_CREATE = 506 SYS___NEXUS_DESTROY = 507 SYS___NEXUS_GET_OPT = 508 SYS___NEXUS_SET_OPT = 509 SYS___CHANNEL_OPEN = 510 SYS___CHANNEL_GET_INFO = 511 SYS___CHANNEL_SYNC = 512 SYS___CHANNEL_GET_OPT = 513 SYS___CHANNEL_SET_OPT = 514 SYS_ULOCK_WAIT = 515 SYS_ULOCK_WAKE = 516 SYS_FCLONEFILEAT = 517 SYS_FS_SNAPSHOT = 518 SYS_TERMINATE_WITH_PAYLOAD = 520 SYS_ABORT_WITH_PAYLOAD = 521 SYS_MAXSYSCALL = 522 SYS_INVALID = 63 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_darwin_amd64.go0000644061062106075000000004017413172163421025753 0ustar stgraberdomain admins// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/sys/syscall.h // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build amd64,darwin package unix const ( SYS_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAIT4 = 7 SYS_LINK = 9 SYS_UNLINK = 10 SYS_CHDIR = 12 SYS_FCHDIR = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_CHOWN = 16 SYS_GETFSSTAT = 18 SYS_GETPID = 20 SYS_SETUID = 23 SYS_GETUID = 24 SYS_GETEUID = 25 SYS_PTRACE = 26 SYS_RECVMSG = 27 SYS_SENDMSG = 28 SYS_RECVFROM = 29 SYS_ACCEPT = 30 SYS_GETPEERNAME = 31 SYS_GETSOCKNAME = 32 SYS_ACCESS = 33 SYS_CHFLAGS = 34 SYS_FCHFLAGS = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_GETPPID = 39 SYS_DUP = 41 SYS_PIPE = 42 SYS_GETEGID = 43 SYS_SIGACTION = 46 SYS_GETGID = 47 SYS_SIGPROCMASK = 48 SYS_GETLOGIN = 49 SYS_SETLOGIN = 50 SYS_ACCT = 51 SYS_SIGPENDING = 52 SYS_SIGALTSTACK = 53 SYS_IOCTL = 54 SYS_REBOOT = 55 SYS_REVOKE = 56 SYS_SYMLINK = 57 SYS_READLINK = 58 SYS_EXECVE = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_MSYNC = 65 SYS_VFORK = 66 SYS_MUNMAP = 73 SYS_MPROTECT = 74 SYS_MADVISE = 75 SYS_MINCORE = 78 SYS_GETGROUPS = 79 SYS_SETGROUPS = 80 SYS_GETPGRP = 81 SYS_SETPGID = 82 SYS_SETITIMER = 83 SYS_SWAPON = 85 SYS_GETITIMER = 86 SYS_GETDTABLESIZE = 89 SYS_DUP2 = 90 SYS_FCNTL = 92 SYS_SELECT = 93 SYS_FSYNC = 95 SYS_SETPRIORITY = 96 SYS_SOCKET = 97 SYS_CONNECT = 98 SYS_GETPRIORITY = 100 SYS_BIND = 104 SYS_SETSOCKOPT = 105 SYS_LISTEN = 106 SYS_SIGSUSPEND = 111 SYS_GETTIMEOFDAY = 116 SYS_GETRUSAGE = 117 SYS_GETSOCKOPT = 118 SYS_READV = 120 SYS_WRITEV = 121 SYS_SETTIMEOFDAY = 122 SYS_FCHOWN = 123 SYS_FCHMOD = 124 SYS_SETREUID = 126 SYS_SETREGID = 127 SYS_RENAME = 128 SYS_FLOCK = 131 SYS_MKFIFO = 132 SYS_SENDTO = 133 SYS_SHUTDOWN = 134 SYS_SOCKETPAIR = 135 SYS_MKDIR = 136 SYS_RMDIR = 137 SYS_UTIMES = 138 SYS_FUTIMES = 139 SYS_ADJTIME = 140 SYS_GETHOSTUUID = 142 SYS_SETSID = 147 SYS_GETPGID = 151 SYS_SETPRIVEXEC = 152 SYS_PREAD = 153 SYS_PWRITE = 154 SYS_NFSSVC = 155 SYS_STATFS = 157 SYS_FSTATFS = 158 SYS_UNMOUNT = 159 SYS_GETFH = 161 SYS_QUOTACTL = 165 SYS_MOUNT = 167 SYS_CSOPS = 169 SYS_CSOPS_AUDITTOKEN = 170 SYS_WAITID = 173 SYS_KDEBUG_TRACE64 = 179 SYS_KDEBUG_TRACE = 180 SYS_SETGID = 181 SYS_SETEGID = 182 SYS_SETEUID = 183 SYS_SIGRETURN = 184 SYS_CHUD = 185 SYS_FDATASYNC = 187 SYS_STAT = 188 SYS_FSTAT = 189 SYS_LSTAT = 190 SYS_PATHCONF = 191 SYS_FPATHCONF = 192 SYS_GETRLIMIT = 194 SYS_SETRLIMIT = 195 SYS_GETDIRENTRIES = 196 SYS_MMAP = 197 SYS_LSEEK = 199 SYS_TRUNCATE = 200 SYS_FTRUNCATE = 201 SYS_SYSCTL = 202 SYS_MLOCK = 203 SYS_MUNLOCK = 204 SYS_UNDELETE = 205 SYS_OPEN_DPROTECTED_NP = 216 SYS_GETATTRLIST = 220 SYS_SETATTRLIST = 221 SYS_GETDIRENTRIESATTR = 222 SYS_EXCHANGEDATA = 223 SYS_SEARCHFS = 225 SYS_DELETE = 226 SYS_COPYFILE = 227 SYS_FGETATTRLIST = 228 SYS_FSETATTRLIST = 229 SYS_POLL = 230 SYS_WATCHEVENT = 231 SYS_WAITEVENT = 232 SYS_MODWATCH = 233 SYS_GETXATTR = 234 SYS_FGETXATTR = 235 SYS_SETXATTR = 236 SYS_FSETXATTR = 237 SYS_REMOVEXATTR = 238 SYS_FREMOVEXATTR = 239 SYS_LISTXATTR = 240 SYS_FLISTXATTR = 241 SYS_FSCTL = 242 SYS_INITGROUPS = 243 SYS_POSIX_SPAWN = 244 SYS_FFSCTL = 245 SYS_NFSCLNT = 247 SYS_FHOPEN = 248 SYS_MINHERIT = 250 SYS_SEMSYS = 251 SYS_MSGSYS = 252 SYS_SHMSYS = 253 SYS_SEMCTL = 254 SYS_SEMGET = 255 SYS_SEMOP = 256 SYS_MSGCTL = 258 SYS_MSGGET = 259 SYS_MSGSND = 260 SYS_MSGRCV = 261 SYS_SHMAT = 262 SYS_SHMCTL = 263 SYS_SHMDT = 264 SYS_SHMGET = 265 SYS_SHM_OPEN = 266 SYS_SHM_UNLINK = 267 SYS_SEM_OPEN = 268 SYS_SEM_CLOSE = 269 SYS_SEM_UNLINK = 270 SYS_SEM_WAIT = 271 SYS_SEM_TRYWAIT = 272 SYS_SEM_POST = 273 SYS_SYSCTLBYNAME = 274 SYS_OPEN_EXTENDED = 277 SYS_UMASK_EXTENDED = 278 SYS_STAT_EXTENDED = 279 SYS_LSTAT_EXTENDED = 280 SYS_FSTAT_EXTENDED = 281 SYS_CHMOD_EXTENDED = 282 SYS_FCHMOD_EXTENDED = 283 SYS_ACCESS_EXTENDED = 284 SYS_SETTID = 285 SYS_GETTID = 286 SYS_SETSGROUPS = 287 SYS_GETSGROUPS = 288 SYS_SETWGROUPS = 289 SYS_GETWGROUPS = 290 SYS_MKFIFO_EXTENDED = 291 SYS_MKDIR_EXTENDED = 292 SYS_IDENTITYSVC = 293 SYS_SHARED_REGION_CHECK_NP = 294 SYS_VM_PRESSURE_MONITOR = 296 SYS_PSYNCH_RW_LONGRDLOCK = 297 SYS_PSYNCH_RW_YIELDWRLOCK = 298 SYS_PSYNCH_RW_DOWNGRADE = 299 SYS_PSYNCH_RW_UPGRADE = 300 SYS_PSYNCH_MUTEXWAIT = 301 SYS_PSYNCH_MUTEXDROP = 302 SYS_PSYNCH_CVBROAD = 303 SYS_PSYNCH_CVSIGNAL = 304 SYS_PSYNCH_CVWAIT = 305 SYS_PSYNCH_RW_RDLOCK = 306 SYS_PSYNCH_RW_WRLOCK = 307 SYS_PSYNCH_RW_UNLOCK = 308 SYS_PSYNCH_RW_UNLOCK2 = 309 SYS_GETSID = 310 SYS_SETTID_WITH_PID = 311 SYS_PSYNCH_CVCLRPREPOST = 312 SYS_AIO_FSYNC = 313 SYS_AIO_RETURN = 314 SYS_AIO_SUSPEND = 315 SYS_AIO_CANCEL = 316 SYS_AIO_ERROR = 317 SYS_AIO_READ = 318 SYS_AIO_WRITE = 319 SYS_LIO_LISTIO = 320 SYS_IOPOLICYSYS = 322 SYS_PROCESS_POLICY = 323 SYS_MLOCKALL = 324 SYS_MUNLOCKALL = 325 SYS_ISSETUGID = 327 SYS___PTHREAD_KILL = 328 SYS___PTHREAD_SIGMASK = 329 SYS___SIGWAIT = 330 SYS___DISABLE_THREADSIGNAL = 331 SYS___PTHREAD_MARKCANCEL = 332 SYS___PTHREAD_CANCELED = 333 SYS___SEMWAIT_SIGNAL = 334 SYS_PROC_INFO = 336 SYS_SENDFILE = 337 SYS_STAT64 = 338 SYS_FSTAT64 = 339 SYS_LSTAT64 = 340 SYS_STAT64_EXTENDED = 341 SYS_LSTAT64_EXTENDED = 342 SYS_FSTAT64_EXTENDED = 343 SYS_GETDIRENTRIES64 = 344 SYS_STATFS64 = 345 SYS_FSTATFS64 = 346 SYS_GETFSSTAT64 = 347 SYS___PTHREAD_CHDIR = 348 SYS___PTHREAD_FCHDIR = 349 SYS_AUDIT = 350 SYS_AUDITON = 351 SYS_GETAUID = 353 SYS_SETAUID = 354 SYS_GETAUDIT_ADDR = 357 SYS_SETAUDIT_ADDR = 358 SYS_AUDITCTL = 359 SYS_BSDTHREAD_CREATE = 360 SYS_BSDTHREAD_TERMINATE = 361 SYS_KQUEUE = 362 SYS_KEVENT = 363 SYS_LCHOWN = 364 SYS_STACK_SNAPSHOT = 365 SYS_BSDTHREAD_REGISTER = 366 SYS_WORKQ_OPEN = 367 SYS_WORKQ_KERNRETURN = 368 SYS_KEVENT64 = 369 SYS___OLD_SEMWAIT_SIGNAL = 370 SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371 SYS_THREAD_SELFID = 372 SYS_LEDGER = 373 SYS___MAC_EXECVE = 380 SYS___MAC_SYSCALL = 381 SYS___MAC_GET_FILE = 382 SYS___MAC_SET_FILE = 383 SYS___MAC_GET_LINK = 384 SYS___MAC_SET_LINK = 385 SYS___MAC_GET_PROC = 386 SYS___MAC_SET_PROC = 387 SYS___MAC_GET_FD = 388 SYS___MAC_SET_FD = 389 SYS___MAC_GET_PID = 390 SYS___MAC_GET_LCID = 391 SYS___MAC_GET_LCTX = 392 SYS___MAC_SET_LCTX = 393 SYS_SETLCID = 394 SYS_GETLCID = 395 SYS_READ_NOCANCEL = 396 SYS_WRITE_NOCANCEL = 397 SYS_OPEN_NOCANCEL = 398 SYS_CLOSE_NOCANCEL = 399 SYS_WAIT4_NOCANCEL = 400 SYS_RECVMSG_NOCANCEL = 401 SYS_SENDMSG_NOCANCEL = 402 SYS_RECVFROM_NOCANCEL = 403 SYS_ACCEPT_NOCANCEL = 404 SYS_MSYNC_NOCANCEL = 405 SYS_FCNTL_NOCANCEL = 406 SYS_SELECT_NOCANCEL = 407 SYS_FSYNC_NOCANCEL = 408 SYS_CONNECT_NOCANCEL = 409 SYS_SIGSUSPEND_NOCANCEL = 410 SYS_READV_NOCANCEL = 411 SYS_WRITEV_NOCANCEL = 412 SYS_SENDTO_NOCANCEL = 413 SYS_PREAD_NOCANCEL = 414 SYS_PWRITE_NOCANCEL = 415 SYS_WAITID_NOCANCEL = 416 SYS_POLL_NOCANCEL = 417 SYS_MSGSND_NOCANCEL = 418 SYS_MSGRCV_NOCANCEL = 419 SYS_SEM_WAIT_NOCANCEL = 420 SYS_AIO_SUSPEND_NOCANCEL = 421 SYS___SIGWAIT_NOCANCEL = 422 SYS___SEMWAIT_SIGNAL_NOCANCEL = 423 SYS___MAC_MOUNT = 424 SYS___MAC_GET_MOUNT = 425 SYS___MAC_GETFSSTAT = 426 SYS_FSGETPATH = 427 SYS_AUDIT_SESSION_SELF = 428 SYS_AUDIT_SESSION_JOIN = 429 SYS_FILEPORT_MAKEPORT = 430 SYS_FILEPORT_MAKEFD = 431 SYS_AUDIT_SESSION_PORT = 432 SYS_PID_SUSPEND = 433 SYS_PID_RESUME = 434 SYS_PID_HIBERNATE = 435 SYS_PID_SHUTDOWN_SOCKETS = 436 SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438 SYS_KAS_INFO = 439 SYS_MEMORYSTATUS_CONTROL = 440 SYS_GUARDED_OPEN_NP = 441 SYS_GUARDED_CLOSE_NP = 442 SYS_GUARDED_KQUEUE_NP = 443 SYS_CHANGE_FDGUARD_NP = 444 SYS_PROC_RLIMIT_CONTROL = 446 SYS_CONNECTX = 447 SYS_DISCONNECTX = 448 SYS_PEELOFF = 449 SYS_SOCKET_DELEGATE = 450 SYS_TELEMETRY = 451 SYS_PROC_UUID_POLICY = 452 SYS_MEMORYSTATUS_GET_LEVEL = 453 SYS_SYSTEM_OVERRIDE = 454 SYS_VFS_PURGE = 455 SYS_SFI_CTL = 456 SYS_SFI_PIDCTL = 457 SYS_COALITION = 458 SYS_COALITION_INFO = 459 SYS_NECP_MATCH_POLICY = 460 SYS_GETATTRLISTBULK = 461 SYS_OPENAT = 463 SYS_OPENAT_NOCANCEL = 464 SYS_RENAMEAT = 465 SYS_FACCESSAT = 466 SYS_FCHMODAT = 467 SYS_FCHOWNAT = 468 SYS_FSTATAT = 469 SYS_FSTATAT64 = 470 SYS_LINKAT = 471 SYS_UNLINKAT = 472 SYS_READLINKAT = 473 SYS_SYMLINKAT = 474 SYS_MKDIRAT = 475 SYS_GETATTRLISTAT = 476 SYS_PROC_TRACE_LOG = 477 SYS_BSDTHREAD_CTL = 478 SYS_OPENBYID_NP = 479 SYS_RECVMSG_X = 480 SYS_SENDMSG_X = 481 SYS_THREAD_SELFUSAGE = 482 SYS_CSRCTL = 483 SYS_GUARDED_OPEN_DPROTECTED_NP = 484 SYS_GUARDED_WRITE_NP = 485 SYS_GUARDED_PWRITE_NP = 486 SYS_GUARDED_WRITEV_NP = 487 SYS_RENAME_EXT = 488 SYS_MREMAP_ENCRYPTED = 489 SYS_MAXSYSCALL = 490 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysnum_darwin_386.go0000644061062106075000000004017213172163421025356 0ustar stgraberdomain admins// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/sys/syscall.h // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build 386,darwin package unix const ( SYS_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAIT4 = 7 SYS_LINK = 9 SYS_UNLINK = 10 SYS_CHDIR = 12 SYS_FCHDIR = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_CHOWN = 16 SYS_GETFSSTAT = 18 SYS_GETPID = 20 SYS_SETUID = 23 SYS_GETUID = 24 SYS_GETEUID = 25 SYS_PTRACE = 26 SYS_RECVMSG = 27 SYS_SENDMSG = 28 SYS_RECVFROM = 29 SYS_ACCEPT = 30 SYS_GETPEERNAME = 31 SYS_GETSOCKNAME = 32 SYS_ACCESS = 33 SYS_CHFLAGS = 34 SYS_FCHFLAGS = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_GETPPID = 39 SYS_DUP = 41 SYS_PIPE = 42 SYS_GETEGID = 43 SYS_SIGACTION = 46 SYS_GETGID = 47 SYS_SIGPROCMASK = 48 SYS_GETLOGIN = 49 SYS_SETLOGIN = 50 SYS_ACCT = 51 SYS_SIGPENDING = 52 SYS_SIGALTSTACK = 53 SYS_IOCTL = 54 SYS_REBOOT = 55 SYS_REVOKE = 56 SYS_SYMLINK = 57 SYS_READLINK = 58 SYS_EXECVE = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_MSYNC = 65 SYS_VFORK = 66 SYS_MUNMAP = 73 SYS_MPROTECT = 74 SYS_MADVISE = 75 SYS_MINCORE = 78 SYS_GETGROUPS = 79 SYS_SETGROUPS = 80 SYS_GETPGRP = 81 SYS_SETPGID = 82 SYS_SETITIMER = 83 SYS_SWAPON = 85 SYS_GETITIMER = 86 SYS_GETDTABLESIZE = 89 SYS_DUP2 = 90 SYS_FCNTL = 92 SYS_SELECT = 93 SYS_FSYNC = 95 SYS_SETPRIORITY = 96 SYS_SOCKET = 97 SYS_CONNECT = 98 SYS_GETPRIORITY = 100 SYS_BIND = 104 SYS_SETSOCKOPT = 105 SYS_LISTEN = 106 SYS_SIGSUSPEND = 111 SYS_GETTIMEOFDAY = 116 SYS_GETRUSAGE = 117 SYS_GETSOCKOPT = 118 SYS_READV = 120 SYS_WRITEV = 121 SYS_SETTIMEOFDAY = 122 SYS_FCHOWN = 123 SYS_FCHMOD = 124 SYS_SETREUID = 126 SYS_SETREGID = 127 SYS_RENAME = 128 SYS_FLOCK = 131 SYS_MKFIFO = 132 SYS_SENDTO = 133 SYS_SHUTDOWN = 134 SYS_SOCKETPAIR = 135 SYS_MKDIR = 136 SYS_RMDIR = 137 SYS_UTIMES = 138 SYS_FUTIMES = 139 SYS_ADJTIME = 140 SYS_GETHOSTUUID = 142 SYS_SETSID = 147 SYS_GETPGID = 151 SYS_SETPRIVEXEC = 152 SYS_PREAD = 153 SYS_PWRITE = 154 SYS_NFSSVC = 155 SYS_STATFS = 157 SYS_FSTATFS = 158 SYS_UNMOUNT = 159 SYS_GETFH = 161 SYS_QUOTACTL = 165 SYS_MOUNT = 167 SYS_CSOPS = 169 SYS_CSOPS_AUDITTOKEN = 170 SYS_WAITID = 173 SYS_KDEBUG_TRACE64 = 179 SYS_KDEBUG_TRACE = 180 SYS_SETGID = 181 SYS_SETEGID = 182 SYS_SETEUID = 183 SYS_SIGRETURN = 184 SYS_CHUD = 185 SYS_FDATASYNC = 187 SYS_STAT = 188 SYS_FSTAT = 189 SYS_LSTAT = 190 SYS_PATHCONF = 191 SYS_FPATHCONF = 192 SYS_GETRLIMIT = 194 SYS_SETRLIMIT = 195 SYS_GETDIRENTRIES = 196 SYS_MMAP = 197 SYS_LSEEK = 199 SYS_TRUNCATE = 200 SYS_FTRUNCATE = 201 SYS_SYSCTL = 202 SYS_MLOCK = 203 SYS_MUNLOCK = 204 SYS_UNDELETE = 205 SYS_OPEN_DPROTECTED_NP = 216 SYS_GETATTRLIST = 220 SYS_SETATTRLIST = 221 SYS_GETDIRENTRIESATTR = 222 SYS_EXCHANGEDATA = 223 SYS_SEARCHFS = 225 SYS_DELETE = 226 SYS_COPYFILE = 227 SYS_FGETATTRLIST = 228 SYS_FSETATTRLIST = 229 SYS_POLL = 230 SYS_WATCHEVENT = 231 SYS_WAITEVENT = 232 SYS_MODWATCH = 233 SYS_GETXATTR = 234 SYS_FGETXATTR = 235 SYS_SETXATTR = 236 SYS_FSETXATTR = 237 SYS_REMOVEXATTR = 238 SYS_FREMOVEXATTR = 239 SYS_LISTXATTR = 240 SYS_FLISTXATTR = 241 SYS_FSCTL = 242 SYS_INITGROUPS = 243 SYS_POSIX_SPAWN = 244 SYS_FFSCTL = 245 SYS_NFSCLNT = 247 SYS_FHOPEN = 248 SYS_MINHERIT = 250 SYS_SEMSYS = 251 SYS_MSGSYS = 252 SYS_SHMSYS = 253 SYS_SEMCTL = 254 SYS_SEMGET = 255 SYS_SEMOP = 256 SYS_MSGCTL = 258 SYS_MSGGET = 259 SYS_MSGSND = 260 SYS_MSGRCV = 261 SYS_SHMAT = 262 SYS_SHMCTL = 263 SYS_SHMDT = 264 SYS_SHMGET = 265 SYS_SHM_OPEN = 266 SYS_SHM_UNLINK = 267 SYS_SEM_OPEN = 268 SYS_SEM_CLOSE = 269 SYS_SEM_UNLINK = 270 SYS_SEM_WAIT = 271 SYS_SEM_TRYWAIT = 272 SYS_SEM_POST = 273 SYS_SYSCTLBYNAME = 274 SYS_OPEN_EXTENDED = 277 SYS_UMASK_EXTENDED = 278 SYS_STAT_EXTENDED = 279 SYS_LSTAT_EXTENDED = 280 SYS_FSTAT_EXTENDED = 281 SYS_CHMOD_EXTENDED = 282 SYS_FCHMOD_EXTENDED = 283 SYS_ACCESS_EXTENDED = 284 SYS_SETTID = 285 SYS_GETTID = 286 SYS_SETSGROUPS = 287 SYS_GETSGROUPS = 288 SYS_SETWGROUPS = 289 SYS_GETWGROUPS = 290 SYS_MKFIFO_EXTENDED = 291 SYS_MKDIR_EXTENDED = 292 SYS_IDENTITYSVC = 293 SYS_SHARED_REGION_CHECK_NP = 294 SYS_VM_PRESSURE_MONITOR = 296 SYS_PSYNCH_RW_LONGRDLOCK = 297 SYS_PSYNCH_RW_YIELDWRLOCK = 298 SYS_PSYNCH_RW_DOWNGRADE = 299 SYS_PSYNCH_RW_UPGRADE = 300 SYS_PSYNCH_MUTEXWAIT = 301 SYS_PSYNCH_MUTEXDROP = 302 SYS_PSYNCH_CVBROAD = 303 SYS_PSYNCH_CVSIGNAL = 304 SYS_PSYNCH_CVWAIT = 305 SYS_PSYNCH_RW_RDLOCK = 306 SYS_PSYNCH_RW_WRLOCK = 307 SYS_PSYNCH_RW_UNLOCK = 308 SYS_PSYNCH_RW_UNLOCK2 = 309 SYS_GETSID = 310 SYS_SETTID_WITH_PID = 311 SYS_PSYNCH_CVCLRPREPOST = 312 SYS_AIO_FSYNC = 313 SYS_AIO_RETURN = 314 SYS_AIO_SUSPEND = 315 SYS_AIO_CANCEL = 316 SYS_AIO_ERROR = 317 SYS_AIO_READ = 318 SYS_AIO_WRITE = 319 SYS_LIO_LISTIO = 320 SYS_IOPOLICYSYS = 322 SYS_PROCESS_POLICY = 323 SYS_MLOCKALL = 324 SYS_MUNLOCKALL = 325 SYS_ISSETUGID = 327 SYS___PTHREAD_KILL = 328 SYS___PTHREAD_SIGMASK = 329 SYS___SIGWAIT = 330 SYS___DISABLE_THREADSIGNAL = 331 SYS___PTHREAD_MARKCANCEL = 332 SYS___PTHREAD_CANCELED = 333 SYS___SEMWAIT_SIGNAL = 334 SYS_PROC_INFO = 336 SYS_SENDFILE = 337 SYS_STAT64 = 338 SYS_FSTAT64 = 339 SYS_LSTAT64 = 340 SYS_STAT64_EXTENDED = 341 SYS_LSTAT64_EXTENDED = 342 SYS_FSTAT64_EXTENDED = 343 SYS_GETDIRENTRIES64 = 344 SYS_STATFS64 = 345 SYS_FSTATFS64 = 346 SYS_GETFSSTAT64 = 347 SYS___PTHREAD_CHDIR = 348 SYS___PTHREAD_FCHDIR = 349 SYS_AUDIT = 350 SYS_AUDITON = 351 SYS_GETAUID = 353 SYS_SETAUID = 354 SYS_GETAUDIT_ADDR = 357 SYS_SETAUDIT_ADDR = 358 SYS_AUDITCTL = 359 SYS_BSDTHREAD_CREATE = 360 SYS_BSDTHREAD_TERMINATE = 361 SYS_KQUEUE = 362 SYS_KEVENT = 363 SYS_LCHOWN = 364 SYS_STACK_SNAPSHOT = 365 SYS_BSDTHREAD_REGISTER = 366 SYS_WORKQ_OPEN = 367 SYS_WORKQ_KERNRETURN = 368 SYS_KEVENT64 = 369 SYS___OLD_SEMWAIT_SIGNAL = 370 SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371 SYS_THREAD_SELFID = 372 SYS_LEDGER = 373 SYS___MAC_EXECVE = 380 SYS___MAC_SYSCALL = 381 SYS___MAC_GET_FILE = 382 SYS___MAC_SET_FILE = 383 SYS___MAC_GET_LINK = 384 SYS___MAC_SET_LINK = 385 SYS___MAC_GET_PROC = 386 SYS___MAC_SET_PROC = 387 SYS___MAC_GET_FD = 388 SYS___MAC_SET_FD = 389 SYS___MAC_GET_PID = 390 SYS___MAC_GET_LCID = 391 SYS___MAC_GET_LCTX = 392 SYS___MAC_SET_LCTX = 393 SYS_SETLCID = 394 SYS_GETLCID = 395 SYS_READ_NOCANCEL = 396 SYS_WRITE_NOCANCEL = 397 SYS_OPEN_NOCANCEL = 398 SYS_CLOSE_NOCANCEL = 399 SYS_WAIT4_NOCANCEL = 400 SYS_RECVMSG_NOCANCEL = 401 SYS_SENDMSG_NOCANCEL = 402 SYS_RECVFROM_NOCANCEL = 403 SYS_ACCEPT_NOCANCEL = 404 SYS_MSYNC_NOCANCEL = 405 SYS_FCNTL_NOCANCEL = 406 SYS_SELECT_NOCANCEL = 407 SYS_FSYNC_NOCANCEL = 408 SYS_CONNECT_NOCANCEL = 409 SYS_SIGSUSPEND_NOCANCEL = 410 SYS_READV_NOCANCEL = 411 SYS_WRITEV_NOCANCEL = 412 SYS_SENDTO_NOCANCEL = 413 SYS_PREAD_NOCANCEL = 414 SYS_PWRITE_NOCANCEL = 415 SYS_WAITID_NOCANCEL = 416 SYS_POLL_NOCANCEL = 417 SYS_MSGSND_NOCANCEL = 418 SYS_MSGRCV_NOCANCEL = 419 SYS_SEM_WAIT_NOCANCEL = 420 SYS_AIO_SUSPEND_NOCANCEL = 421 SYS___SIGWAIT_NOCANCEL = 422 SYS___SEMWAIT_SIGNAL_NOCANCEL = 423 SYS___MAC_MOUNT = 424 SYS___MAC_GET_MOUNT = 425 SYS___MAC_GETFSSTAT = 426 SYS_FSGETPATH = 427 SYS_AUDIT_SESSION_SELF = 428 SYS_AUDIT_SESSION_JOIN = 429 SYS_FILEPORT_MAKEPORT = 430 SYS_FILEPORT_MAKEFD = 431 SYS_AUDIT_SESSION_PORT = 432 SYS_PID_SUSPEND = 433 SYS_PID_RESUME = 434 SYS_PID_HIBERNATE = 435 SYS_PID_SHUTDOWN_SOCKETS = 436 SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438 SYS_KAS_INFO = 439 SYS_MEMORYSTATUS_CONTROL = 440 SYS_GUARDED_OPEN_NP = 441 SYS_GUARDED_CLOSE_NP = 442 SYS_GUARDED_KQUEUE_NP = 443 SYS_CHANGE_FDGUARD_NP = 444 SYS_PROC_RLIMIT_CONTROL = 446 SYS_CONNECTX = 447 SYS_DISCONNECTX = 448 SYS_PEELOFF = 449 SYS_SOCKET_DELEGATE = 450 SYS_TELEMETRY = 451 SYS_PROC_UUID_POLICY = 452 SYS_MEMORYSTATUS_GET_LEVEL = 453 SYS_SYSTEM_OVERRIDE = 454 SYS_VFS_PURGE = 455 SYS_SFI_CTL = 456 SYS_SFI_PIDCTL = 457 SYS_COALITION = 458 SYS_COALITION_INFO = 459 SYS_NECP_MATCH_POLICY = 460 SYS_GETATTRLISTBULK = 461 SYS_OPENAT = 463 SYS_OPENAT_NOCANCEL = 464 SYS_RENAMEAT = 465 SYS_FACCESSAT = 466 SYS_FCHMODAT = 467 SYS_FCHOWNAT = 468 SYS_FSTATAT = 469 SYS_FSTATAT64 = 470 SYS_LINKAT = 471 SYS_UNLINKAT = 472 SYS_READLINKAT = 473 SYS_SYMLINKAT = 474 SYS_MKDIRAT = 475 SYS_GETATTRLISTAT = 476 SYS_PROC_TRACE_LOG = 477 SYS_BSDTHREAD_CTL = 478 SYS_OPENBYID_NP = 479 SYS_RECVMSG_X = 480 SYS_SENDMSG_X = 481 SYS_THREAD_SELFUSAGE = 482 SYS_CSRCTL = 483 SYS_GUARDED_OPEN_DPROTECTED_NP = 484 SYS_GUARDED_WRITE_NP = 485 SYS_GUARDED_PWRITE_NP = 486 SYS_GUARDED_WRITEV_NP = 487 SYS_RENAME_EXT = 488 SYS_MREMAP_ENCRYPTED = 489 SYS_MAXSYSCALL = 490 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysctl_openbsd_arm.go0000644061062106075000000002732213172163421025750 0ustar stgraberdomain admins// mksysctl_openbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT package unix type mibentry struct { ctlname string ctloid []_C_int } var sysctlMib = []mibentry{ {"ddb.console", []_C_int{9, 6}}, {"ddb.log", []_C_int{9, 7}}, {"ddb.max_line", []_C_int{9, 3}}, {"ddb.max_width", []_C_int{9, 2}}, {"ddb.panic", []_C_int{9, 5}}, {"ddb.radix", []_C_int{9, 1}}, {"ddb.tab_stop_width", []_C_int{9, 4}}, {"ddb.trigger", []_C_int{9, 8}}, {"fs.posix.setuid", []_C_int{3, 1, 1}}, {"hw.allowpowerdown", []_C_int{6, 22}}, {"hw.byteorder", []_C_int{6, 4}}, {"hw.cpuspeed", []_C_int{6, 12}}, {"hw.diskcount", []_C_int{6, 10}}, {"hw.disknames", []_C_int{6, 8}}, {"hw.diskstats", []_C_int{6, 9}}, {"hw.machine", []_C_int{6, 1}}, {"hw.model", []_C_int{6, 2}}, {"hw.ncpu", []_C_int{6, 3}}, {"hw.ncpufound", []_C_int{6, 21}}, {"hw.pagesize", []_C_int{6, 7}}, {"hw.physmem", []_C_int{6, 19}}, {"hw.product", []_C_int{6, 15}}, {"hw.serialno", []_C_int{6, 17}}, {"hw.setperf", []_C_int{6, 13}}, {"hw.usermem", []_C_int{6, 20}}, {"hw.uuid", []_C_int{6, 18}}, {"hw.vendor", []_C_int{6, 14}}, {"hw.version", []_C_int{6, 16}}, {"kern.arandom", []_C_int{1, 37}}, {"kern.argmax", []_C_int{1, 8}}, {"kern.boottime", []_C_int{1, 21}}, {"kern.bufcachepercent", []_C_int{1, 72}}, {"kern.ccpu", []_C_int{1, 45}}, {"kern.clockrate", []_C_int{1, 12}}, {"kern.consdev", []_C_int{1, 75}}, {"kern.cp_time", []_C_int{1, 40}}, {"kern.cp_time2", []_C_int{1, 71}}, {"kern.cryptodevallowsoft", []_C_int{1, 53}}, {"kern.domainname", []_C_int{1, 22}}, {"kern.file", []_C_int{1, 73}}, {"kern.forkstat", []_C_int{1, 42}}, {"kern.fscale", []_C_int{1, 46}}, {"kern.fsync", []_C_int{1, 33}}, {"kern.hostid", []_C_int{1, 11}}, {"kern.hostname", []_C_int{1, 10}}, {"kern.intrcnt.nintrcnt", []_C_int{1, 63, 1}}, {"kern.job_control", []_C_int{1, 19}}, {"kern.malloc.buckets", []_C_int{1, 39, 1}}, {"kern.malloc.kmemnames", []_C_int{1, 39, 3}}, {"kern.maxclusters", []_C_int{1, 67}}, {"kern.maxfiles", []_C_int{1, 7}}, {"kern.maxlocksperuid", []_C_int{1, 70}}, {"kern.maxpartitions", []_C_int{1, 23}}, {"kern.maxproc", []_C_int{1, 6}}, {"kern.maxthread", []_C_int{1, 25}}, {"kern.maxvnodes", []_C_int{1, 5}}, {"kern.mbstat", []_C_int{1, 59}}, {"kern.msgbuf", []_C_int{1, 48}}, {"kern.msgbufsize", []_C_int{1, 38}}, {"kern.nchstats", []_C_int{1, 41}}, {"kern.netlivelocks", []_C_int{1, 76}}, {"kern.nfiles", []_C_int{1, 56}}, {"kern.ngroups", []_C_int{1, 18}}, {"kern.nosuidcoredump", []_C_int{1, 32}}, {"kern.nprocs", []_C_int{1, 47}}, {"kern.nselcoll", []_C_int{1, 43}}, {"kern.nthreads", []_C_int{1, 26}}, {"kern.numvnodes", []_C_int{1, 58}}, {"kern.osrelease", []_C_int{1, 2}}, {"kern.osrevision", []_C_int{1, 3}}, {"kern.ostype", []_C_int{1, 1}}, {"kern.osversion", []_C_int{1, 27}}, {"kern.pool_debug", []_C_int{1, 77}}, {"kern.posix1version", []_C_int{1, 17}}, {"kern.proc", []_C_int{1, 66}}, {"kern.random", []_C_int{1, 31}}, {"kern.rawpartition", []_C_int{1, 24}}, {"kern.saved_ids", []_C_int{1, 20}}, {"kern.securelevel", []_C_int{1, 9}}, {"kern.seminfo", []_C_int{1, 61}}, {"kern.shminfo", []_C_int{1, 62}}, {"kern.somaxconn", []_C_int{1, 28}}, {"kern.sominconn", []_C_int{1, 29}}, {"kern.splassert", []_C_int{1, 54}}, {"kern.stackgap_random", []_C_int{1, 50}}, {"kern.sysvipc_info", []_C_int{1, 51}}, {"kern.sysvmsg", []_C_int{1, 34}}, {"kern.sysvsem", []_C_int{1, 35}}, {"kern.sysvshm", []_C_int{1, 36}}, {"kern.timecounter.choice", []_C_int{1, 69, 4}}, {"kern.timecounter.hardware", []_C_int{1, 69, 3}}, {"kern.timecounter.tick", []_C_int{1, 69, 1}}, {"kern.timecounter.timestepwarnings", []_C_int{1, 69, 2}}, {"kern.tty.maxptys", []_C_int{1, 44, 6}}, {"kern.tty.nptys", []_C_int{1, 44, 7}}, {"kern.tty.tk_cancc", []_C_int{1, 44, 4}}, {"kern.tty.tk_nin", []_C_int{1, 44, 1}}, {"kern.tty.tk_nout", []_C_int{1, 44, 2}}, {"kern.tty.tk_rawcc", []_C_int{1, 44, 3}}, {"kern.tty.ttyinfo", []_C_int{1, 44, 5}}, {"kern.ttycount", []_C_int{1, 57}}, {"kern.userasymcrypto", []_C_int{1, 60}}, {"kern.usercrypto", []_C_int{1, 52}}, {"kern.usermount", []_C_int{1, 30}}, {"kern.version", []_C_int{1, 4}}, {"kern.vnode", []_C_int{1, 13}}, {"kern.watchdog.auto", []_C_int{1, 64, 2}}, {"kern.watchdog.period", []_C_int{1, 64, 1}}, {"net.bpf.bufsize", []_C_int{4, 31, 1}}, {"net.bpf.maxbufsize", []_C_int{4, 31, 2}}, {"net.inet.ah.enable", []_C_int{4, 2, 51, 1}}, {"net.inet.ah.stats", []_C_int{4, 2, 51, 2}}, {"net.inet.carp.allow", []_C_int{4, 2, 112, 1}}, {"net.inet.carp.log", []_C_int{4, 2, 112, 3}}, {"net.inet.carp.preempt", []_C_int{4, 2, 112, 2}}, {"net.inet.carp.stats", []_C_int{4, 2, 112, 4}}, {"net.inet.divert.recvspace", []_C_int{4, 2, 258, 1}}, {"net.inet.divert.sendspace", []_C_int{4, 2, 258, 2}}, {"net.inet.divert.stats", []_C_int{4, 2, 258, 3}}, {"net.inet.esp.enable", []_C_int{4, 2, 50, 1}}, {"net.inet.esp.stats", []_C_int{4, 2, 50, 4}}, {"net.inet.esp.udpencap", []_C_int{4, 2, 50, 2}}, {"net.inet.esp.udpencap_port", []_C_int{4, 2, 50, 3}}, {"net.inet.etherip.allow", []_C_int{4, 2, 97, 1}}, {"net.inet.etherip.stats", []_C_int{4, 2, 97, 2}}, {"net.inet.gre.allow", []_C_int{4, 2, 47, 1}}, {"net.inet.gre.wccp", []_C_int{4, 2, 47, 2}}, {"net.inet.icmp.bmcastecho", []_C_int{4, 2, 1, 2}}, {"net.inet.icmp.errppslimit", []_C_int{4, 2, 1, 3}}, {"net.inet.icmp.maskrepl", []_C_int{4, 2, 1, 1}}, {"net.inet.icmp.rediraccept", []_C_int{4, 2, 1, 4}}, {"net.inet.icmp.redirtimeout", []_C_int{4, 2, 1, 5}}, {"net.inet.icmp.stats", []_C_int{4, 2, 1, 7}}, {"net.inet.icmp.tstamprepl", []_C_int{4, 2, 1, 6}}, {"net.inet.igmp.stats", []_C_int{4, 2, 2, 1}}, {"net.inet.ip.arpqueued", []_C_int{4, 2, 0, 36}}, {"net.inet.ip.encdebug", []_C_int{4, 2, 0, 12}}, {"net.inet.ip.forwarding", []_C_int{4, 2, 0, 1}}, {"net.inet.ip.ifq.congestion", []_C_int{4, 2, 0, 30, 4}}, {"net.inet.ip.ifq.drops", []_C_int{4, 2, 0, 30, 3}}, {"net.inet.ip.ifq.len", []_C_int{4, 2, 0, 30, 1}}, {"net.inet.ip.ifq.maxlen", []_C_int{4, 2, 0, 30, 2}}, {"net.inet.ip.maxqueue", []_C_int{4, 2, 0, 11}}, {"net.inet.ip.mforwarding", []_C_int{4, 2, 0, 31}}, {"net.inet.ip.mrtproto", []_C_int{4, 2, 0, 34}}, {"net.inet.ip.mrtstats", []_C_int{4, 2, 0, 35}}, {"net.inet.ip.mtu", []_C_int{4, 2, 0, 4}}, {"net.inet.ip.mtudisc", []_C_int{4, 2, 0, 27}}, {"net.inet.ip.mtudisctimeout", []_C_int{4, 2, 0, 28}}, {"net.inet.ip.multipath", []_C_int{4, 2, 0, 32}}, {"net.inet.ip.portfirst", []_C_int{4, 2, 0, 7}}, {"net.inet.ip.porthifirst", []_C_int{4, 2, 0, 9}}, {"net.inet.ip.porthilast", []_C_int{4, 2, 0, 10}}, {"net.inet.ip.portlast", []_C_int{4, 2, 0, 8}}, {"net.inet.ip.redirect", []_C_int{4, 2, 0, 2}}, {"net.inet.ip.sourceroute", []_C_int{4, 2, 0, 5}}, {"net.inet.ip.stats", []_C_int{4, 2, 0, 33}}, {"net.inet.ip.ttl", []_C_int{4, 2, 0, 3}}, {"net.inet.ipcomp.enable", []_C_int{4, 2, 108, 1}}, {"net.inet.ipcomp.stats", []_C_int{4, 2, 108, 2}}, {"net.inet.ipip.allow", []_C_int{4, 2, 4, 1}}, {"net.inet.ipip.stats", []_C_int{4, 2, 4, 2}}, {"net.inet.mobileip.allow", []_C_int{4, 2, 55, 1}}, {"net.inet.pfsync.stats", []_C_int{4, 2, 240, 1}}, {"net.inet.pim.stats", []_C_int{4, 2, 103, 1}}, {"net.inet.tcp.ackonpush", []_C_int{4, 2, 6, 13}}, {"net.inet.tcp.always_keepalive", []_C_int{4, 2, 6, 22}}, {"net.inet.tcp.baddynamic", []_C_int{4, 2, 6, 6}}, {"net.inet.tcp.drop", []_C_int{4, 2, 6, 19}}, {"net.inet.tcp.ecn", []_C_int{4, 2, 6, 14}}, {"net.inet.tcp.ident", []_C_int{4, 2, 6, 9}}, {"net.inet.tcp.keepidle", []_C_int{4, 2, 6, 3}}, {"net.inet.tcp.keepinittime", []_C_int{4, 2, 6, 2}}, {"net.inet.tcp.keepintvl", []_C_int{4, 2, 6, 4}}, {"net.inet.tcp.mssdflt", []_C_int{4, 2, 6, 11}}, {"net.inet.tcp.reasslimit", []_C_int{4, 2, 6, 18}}, {"net.inet.tcp.rfc1323", []_C_int{4, 2, 6, 1}}, {"net.inet.tcp.rfc3390", []_C_int{4, 2, 6, 17}}, {"net.inet.tcp.rstppslimit", []_C_int{4, 2, 6, 12}}, {"net.inet.tcp.sack", []_C_int{4, 2, 6, 10}}, {"net.inet.tcp.sackholelimit", []_C_int{4, 2, 6, 20}}, {"net.inet.tcp.slowhz", []_C_int{4, 2, 6, 5}}, {"net.inet.tcp.stats", []_C_int{4, 2, 6, 21}}, {"net.inet.tcp.synbucketlimit", []_C_int{4, 2, 6, 16}}, {"net.inet.tcp.syncachelimit", []_C_int{4, 2, 6, 15}}, {"net.inet.udp.baddynamic", []_C_int{4, 2, 17, 2}}, {"net.inet.udp.checksum", []_C_int{4, 2, 17, 1}}, {"net.inet.udp.recvspace", []_C_int{4, 2, 17, 3}}, {"net.inet.udp.sendspace", []_C_int{4, 2, 17, 4}}, {"net.inet.udp.stats", []_C_int{4, 2, 17, 5}}, {"net.inet6.divert.recvspace", []_C_int{4, 24, 86, 1}}, {"net.inet6.divert.sendspace", []_C_int{4, 24, 86, 2}}, {"net.inet6.divert.stats", []_C_int{4, 24, 86, 3}}, {"net.inet6.icmp6.errppslimit", []_C_int{4, 24, 30, 14}}, {"net.inet6.icmp6.mtudisc_hiwat", []_C_int{4, 24, 30, 16}}, {"net.inet6.icmp6.mtudisc_lowat", []_C_int{4, 24, 30, 17}}, {"net.inet6.icmp6.nd6_debug", []_C_int{4, 24, 30, 18}}, {"net.inet6.icmp6.nd6_delay", []_C_int{4, 24, 30, 8}}, {"net.inet6.icmp6.nd6_maxnudhint", []_C_int{4, 24, 30, 15}}, {"net.inet6.icmp6.nd6_mmaxtries", []_C_int{4, 24, 30, 10}}, {"net.inet6.icmp6.nd6_prune", []_C_int{4, 24, 30, 6}}, {"net.inet6.icmp6.nd6_umaxtries", []_C_int{4, 24, 30, 9}}, {"net.inet6.icmp6.nd6_useloopback", []_C_int{4, 24, 30, 11}}, {"net.inet6.icmp6.nodeinfo", []_C_int{4, 24, 30, 13}}, {"net.inet6.icmp6.rediraccept", []_C_int{4, 24, 30, 2}}, {"net.inet6.icmp6.redirtimeout", []_C_int{4, 24, 30, 3}}, {"net.inet6.ip6.accept_rtadv", []_C_int{4, 24, 17, 12}}, {"net.inet6.ip6.auto_flowlabel", []_C_int{4, 24, 17, 17}}, {"net.inet6.ip6.dad_count", []_C_int{4, 24, 17, 16}}, {"net.inet6.ip6.dad_pending", []_C_int{4, 24, 17, 49}}, {"net.inet6.ip6.defmcasthlim", []_C_int{4, 24, 17, 18}}, {"net.inet6.ip6.forwarding", []_C_int{4, 24, 17, 1}}, {"net.inet6.ip6.forwsrcrt", []_C_int{4, 24, 17, 5}}, {"net.inet6.ip6.hdrnestlimit", []_C_int{4, 24, 17, 15}}, {"net.inet6.ip6.hlim", []_C_int{4, 24, 17, 3}}, {"net.inet6.ip6.log_interval", []_C_int{4, 24, 17, 14}}, {"net.inet6.ip6.maxdynroutes", []_C_int{4, 24, 17, 48}}, {"net.inet6.ip6.maxfragpackets", []_C_int{4, 24, 17, 9}}, {"net.inet6.ip6.maxfrags", []_C_int{4, 24, 17, 41}}, {"net.inet6.ip6.maxifdefrouters", []_C_int{4, 24, 17, 47}}, {"net.inet6.ip6.maxifprefixes", []_C_int{4, 24, 17, 46}}, {"net.inet6.ip6.mforwarding", []_C_int{4, 24, 17, 42}}, {"net.inet6.ip6.mrtproto", []_C_int{4, 24, 17, 8}}, {"net.inet6.ip6.mtudisctimeout", []_C_int{4, 24, 17, 50}}, {"net.inet6.ip6.multicast_mtudisc", []_C_int{4, 24, 17, 44}}, {"net.inet6.ip6.multipath", []_C_int{4, 24, 17, 43}}, {"net.inet6.ip6.neighborgcthresh", []_C_int{4, 24, 17, 45}}, {"net.inet6.ip6.redirect", []_C_int{4, 24, 17, 2}}, {"net.inet6.ip6.rr_prune", []_C_int{4, 24, 17, 22}}, {"net.inet6.ip6.sourcecheck", []_C_int{4, 24, 17, 10}}, {"net.inet6.ip6.sourcecheck_logint", []_C_int{4, 24, 17, 11}}, {"net.inet6.ip6.use_deprecated", []_C_int{4, 24, 17, 21}}, {"net.inet6.ip6.v6only", []_C_int{4, 24, 17, 24}}, {"net.key.sadb_dump", []_C_int{4, 30, 1}}, {"net.key.spd_dump", []_C_int{4, 30, 2}}, {"net.mpls.ifq.congestion", []_C_int{4, 33, 3, 4}}, {"net.mpls.ifq.drops", []_C_int{4, 33, 3, 3}}, {"net.mpls.ifq.len", []_C_int{4, 33, 3, 1}}, {"net.mpls.ifq.maxlen", []_C_int{4, 33, 3, 2}}, {"net.mpls.mapttl_ip", []_C_int{4, 33, 5}}, {"net.mpls.mapttl_ip6", []_C_int{4, 33, 6}}, {"net.mpls.maxloop_inkernel", []_C_int{4, 33, 4}}, {"net.mpls.ttl", []_C_int{4, 33, 2}}, {"net.pflow.stats", []_C_int{4, 34, 1}}, {"net.pipex.enable", []_C_int{4, 35, 1}}, {"vm.anonmin", []_C_int{2, 7}}, {"vm.loadavg", []_C_int{2, 2}}, {"vm.maxslp", []_C_int{2, 10}}, {"vm.nkmempages", []_C_int{2, 6}}, {"vm.psstrings", []_C_int{2, 3}}, {"vm.swapencrypt.enable", []_C_int{2, 5, 0}}, {"vm.swapencrypt.keyscreated", []_C_int{2, 5, 1}}, {"vm.swapencrypt.keysdeleted", []_C_int{2, 5, 2}}, {"vm.uspace", []_C_int{2, 11}}, {"vm.uvmexp", []_C_int{2, 4}}, {"vm.vmmeter", []_C_int{2, 1}}, {"vm.vnodemin", []_C_int{2, 9}}, {"vm.vtextmin", []_C_int{2, 8}}, } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go0000644061062106075000000002732213172163421026104 0ustar stgraberdomain admins// mksysctl_openbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT package unix type mibentry struct { ctlname string ctloid []_C_int } var sysctlMib = []mibentry{ {"ddb.console", []_C_int{9, 6}}, {"ddb.log", []_C_int{9, 7}}, {"ddb.max_line", []_C_int{9, 3}}, {"ddb.max_width", []_C_int{9, 2}}, {"ddb.panic", []_C_int{9, 5}}, {"ddb.radix", []_C_int{9, 1}}, {"ddb.tab_stop_width", []_C_int{9, 4}}, {"ddb.trigger", []_C_int{9, 8}}, {"fs.posix.setuid", []_C_int{3, 1, 1}}, {"hw.allowpowerdown", []_C_int{6, 22}}, {"hw.byteorder", []_C_int{6, 4}}, {"hw.cpuspeed", []_C_int{6, 12}}, {"hw.diskcount", []_C_int{6, 10}}, {"hw.disknames", []_C_int{6, 8}}, {"hw.diskstats", []_C_int{6, 9}}, {"hw.machine", []_C_int{6, 1}}, {"hw.model", []_C_int{6, 2}}, {"hw.ncpu", []_C_int{6, 3}}, {"hw.ncpufound", []_C_int{6, 21}}, {"hw.pagesize", []_C_int{6, 7}}, {"hw.physmem", []_C_int{6, 19}}, {"hw.product", []_C_int{6, 15}}, {"hw.serialno", []_C_int{6, 17}}, {"hw.setperf", []_C_int{6, 13}}, {"hw.usermem", []_C_int{6, 20}}, {"hw.uuid", []_C_int{6, 18}}, {"hw.vendor", []_C_int{6, 14}}, {"hw.version", []_C_int{6, 16}}, {"kern.arandom", []_C_int{1, 37}}, {"kern.argmax", []_C_int{1, 8}}, {"kern.boottime", []_C_int{1, 21}}, {"kern.bufcachepercent", []_C_int{1, 72}}, {"kern.ccpu", []_C_int{1, 45}}, {"kern.clockrate", []_C_int{1, 12}}, {"kern.consdev", []_C_int{1, 75}}, {"kern.cp_time", []_C_int{1, 40}}, {"kern.cp_time2", []_C_int{1, 71}}, {"kern.cryptodevallowsoft", []_C_int{1, 53}}, {"kern.domainname", []_C_int{1, 22}}, {"kern.file", []_C_int{1, 73}}, {"kern.forkstat", []_C_int{1, 42}}, {"kern.fscale", []_C_int{1, 46}}, {"kern.fsync", []_C_int{1, 33}}, {"kern.hostid", []_C_int{1, 11}}, {"kern.hostname", []_C_int{1, 10}}, {"kern.intrcnt.nintrcnt", []_C_int{1, 63, 1}}, {"kern.job_control", []_C_int{1, 19}}, {"kern.malloc.buckets", []_C_int{1, 39, 1}}, {"kern.malloc.kmemnames", []_C_int{1, 39, 3}}, {"kern.maxclusters", []_C_int{1, 67}}, {"kern.maxfiles", []_C_int{1, 7}}, {"kern.maxlocksperuid", []_C_int{1, 70}}, {"kern.maxpartitions", []_C_int{1, 23}}, {"kern.maxproc", []_C_int{1, 6}}, {"kern.maxthread", []_C_int{1, 25}}, {"kern.maxvnodes", []_C_int{1, 5}}, {"kern.mbstat", []_C_int{1, 59}}, {"kern.msgbuf", []_C_int{1, 48}}, {"kern.msgbufsize", []_C_int{1, 38}}, {"kern.nchstats", []_C_int{1, 41}}, {"kern.netlivelocks", []_C_int{1, 76}}, {"kern.nfiles", []_C_int{1, 56}}, {"kern.ngroups", []_C_int{1, 18}}, {"kern.nosuidcoredump", []_C_int{1, 32}}, {"kern.nprocs", []_C_int{1, 47}}, {"kern.nselcoll", []_C_int{1, 43}}, {"kern.nthreads", []_C_int{1, 26}}, {"kern.numvnodes", []_C_int{1, 58}}, {"kern.osrelease", []_C_int{1, 2}}, {"kern.osrevision", []_C_int{1, 3}}, {"kern.ostype", []_C_int{1, 1}}, {"kern.osversion", []_C_int{1, 27}}, {"kern.pool_debug", []_C_int{1, 77}}, {"kern.posix1version", []_C_int{1, 17}}, {"kern.proc", []_C_int{1, 66}}, {"kern.random", []_C_int{1, 31}}, {"kern.rawpartition", []_C_int{1, 24}}, {"kern.saved_ids", []_C_int{1, 20}}, {"kern.securelevel", []_C_int{1, 9}}, {"kern.seminfo", []_C_int{1, 61}}, {"kern.shminfo", []_C_int{1, 62}}, {"kern.somaxconn", []_C_int{1, 28}}, {"kern.sominconn", []_C_int{1, 29}}, {"kern.splassert", []_C_int{1, 54}}, {"kern.stackgap_random", []_C_int{1, 50}}, {"kern.sysvipc_info", []_C_int{1, 51}}, {"kern.sysvmsg", []_C_int{1, 34}}, {"kern.sysvsem", []_C_int{1, 35}}, {"kern.sysvshm", []_C_int{1, 36}}, {"kern.timecounter.choice", []_C_int{1, 69, 4}}, {"kern.timecounter.hardware", []_C_int{1, 69, 3}}, {"kern.timecounter.tick", []_C_int{1, 69, 1}}, {"kern.timecounter.timestepwarnings", []_C_int{1, 69, 2}}, {"kern.tty.maxptys", []_C_int{1, 44, 6}}, {"kern.tty.nptys", []_C_int{1, 44, 7}}, {"kern.tty.tk_cancc", []_C_int{1, 44, 4}}, {"kern.tty.tk_nin", []_C_int{1, 44, 1}}, {"kern.tty.tk_nout", []_C_int{1, 44, 2}}, {"kern.tty.tk_rawcc", []_C_int{1, 44, 3}}, {"kern.tty.ttyinfo", []_C_int{1, 44, 5}}, {"kern.ttycount", []_C_int{1, 57}}, {"kern.userasymcrypto", []_C_int{1, 60}}, {"kern.usercrypto", []_C_int{1, 52}}, {"kern.usermount", []_C_int{1, 30}}, {"kern.version", []_C_int{1, 4}}, {"kern.vnode", []_C_int{1, 13}}, {"kern.watchdog.auto", []_C_int{1, 64, 2}}, {"kern.watchdog.period", []_C_int{1, 64, 1}}, {"net.bpf.bufsize", []_C_int{4, 31, 1}}, {"net.bpf.maxbufsize", []_C_int{4, 31, 2}}, {"net.inet.ah.enable", []_C_int{4, 2, 51, 1}}, {"net.inet.ah.stats", []_C_int{4, 2, 51, 2}}, {"net.inet.carp.allow", []_C_int{4, 2, 112, 1}}, {"net.inet.carp.log", []_C_int{4, 2, 112, 3}}, {"net.inet.carp.preempt", []_C_int{4, 2, 112, 2}}, {"net.inet.carp.stats", []_C_int{4, 2, 112, 4}}, {"net.inet.divert.recvspace", []_C_int{4, 2, 258, 1}}, {"net.inet.divert.sendspace", []_C_int{4, 2, 258, 2}}, {"net.inet.divert.stats", []_C_int{4, 2, 258, 3}}, {"net.inet.esp.enable", []_C_int{4, 2, 50, 1}}, {"net.inet.esp.stats", []_C_int{4, 2, 50, 4}}, {"net.inet.esp.udpencap", []_C_int{4, 2, 50, 2}}, {"net.inet.esp.udpencap_port", []_C_int{4, 2, 50, 3}}, {"net.inet.etherip.allow", []_C_int{4, 2, 97, 1}}, {"net.inet.etherip.stats", []_C_int{4, 2, 97, 2}}, {"net.inet.gre.allow", []_C_int{4, 2, 47, 1}}, {"net.inet.gre.wccp", []_C_int{4, 2, 47, 2}}, {"net.inet.icmp.bmcastecho", []_C_int{4, 2, 1, 2}}, {"net.inet.icmp.errppslimit", []_C_int{4, 2, 1, 3}}, {"net.inet.icmp.maskrepl", []_C_int{4, 2, 1, 1}}, {"net.inet.icmp.rediraccept", []_C_int{4, 2, 1, 4}}, {"net.inet.icmp.redirtimeout", []_C_int{4, 2, 1, 5}}, {"net.inet.icmp.stats", []_C_int{4, 2, 1, 7}}, {"net.inet.icmp.tstamprepl", []_C_int{4, 2, 1, 6}}, {"net.inet.igmp.stats", []_C_int{4, 2, 2, 1}}, {"net.inet.ip.arpqueued", []_C_int{4, 2, 0, 36}}, {"net.inet.ip.encdebug", []_C_int{4, 2, 0, 12}}, {"net.inet.ip.forwarding", []_C_int{4, 2, 0, 1}}, {"net.inet.ip.ifq.congestion", []_C_int{4, 2, 0, 30, 4}}, {"net.inet.ip.ifq.drops", []_C_int{4, 2, 0, 30, 3}}, {"net.inet.ip.ifq.len", []_C_int{4, 2, 0, 30, 1}}, {"net.inet.ip.ifq.maxlen", []_C_int{4, 2, 0, 30, 2}}, {"net.inet.ip.maxqueue", []_C_int{4, 2, 0, 11}}, {"net.inet.ip.mforwarding", []_C_int{4, 2, 0, 31}}, {"net.inet.ip.mrtproto", []_C_int{4, 2, 0, 34}}, {"net.inet.ip.mrtstats", []_C_int{4, 2, 0, 35}}, {"net.inet.ip.mtu", []_C_int{4, 2, 0, 4}}, {"net.inet.ip.mtudisc", []_C_int{4, 2, 0, 27}}, {"net.inet.ip.mtudisctimeout", []_C_int{4, 2, 0, 28}}, {"net.inet.ip.multipath", []_C_int{4, 2, 0, 32}}, {"net.inet.ip.portfirst", []_C_int{4, 2, 0, 7}}, {"net.inet.ip.porthifirst", []_C_int{4, 2, 0, 9}}, {"net.inet.ip.porthilast", []_C_int{4, 2, 0, 10}}, {"net.inet.ip.portlast", []_C_int{4, 2, 0, 8}}, {"net.inet.ip.redirect", []_C_int{4, 2, 0, 2}}, {"net.inet.ip.sourceroute", []_C_int{4, 2, 0, 5}}, {"net.inet.ip.stats", []_C_int{4, 2, 0, 33}}, {"net.inet.ip.ttl", []_C_int{4, 2, 0, 3}}, {"net.inet.ipcomp.enable", []_C_int{4, 2, 108, 1}}, {"net.inet.ipcomp.stats", []_C_int{4, 2, 108, 2}}, {"net.inet.ipip.allow", []_C_int{4, 2, 4, 1}}, {"net.inet.ipip.stats", []_C_int{4, 2, 4, 2}}, {"net.inet.mobileip.allow", []_C_int{4, 2, 55, 1}}, {"net.inet.pfsync.stats", []_C_int{4, 2, 240, 1}}, {"net.inet.pim.stats", []_C_int{4, 2, 103, 1}}, {"net.inet.tcp.ackonpush", []_C_int{4, 2, 6, 13}}, {"net.inet.tcp.always_keepalive", []_C_int{4, 2, 6, 22}}, {"net.inet.tcp.baddynamic", []_C_int{4, 2, 6, 6}}, {"net.inet.tcp.drop", []_C_int{4, 2, 6, 19}}, {"net.inet.tcp.ecn", []_C_int{4, 2, 6, 14}}, {"net.inet.tcp.ident", []_C_int{4, 2, 6, 9}}, {"net.inet.tcp.keepidle", []_C_int{4, 2, 6, 3}}, {"net.inet.tcp.keepinittime", []_C_int{4, 2, 6, 2}}, {"net.inet.tcp.keepintvl", []_C_int{4, 2, 6, 4}}, {"net.inet.tcp.mssdflt", []_C_int{4, 2, 6, 11}}, {"net.inet.tcp.reasslimit", []_C_int{4, 2, 6, 18}}, {"net.inet.tcp.rfc1323", []_C_int{4, 2, 6, 1}}, {"net.inet.tcp.rfc3390", []_C_int{4, 2, 6, 17}}, {"net.inet.tcp.rstppslimit", []_C_int{4, 2, 6, 12}}, {"net.inet.tcp.sack", []_C_int{4, 2, 6, 10}}, {"net.inet.tcp.sackholelimit", []_C_int{4, 2, 6, 20}}, {"net.inet.tcp.slowhz", []_C_int{4, 2, 6, 5}}, {"net.inet.tcp.stats", []_C_int{4, 2, 6, 21}}, {"net.inet.tcp.synbucketlimit", []_C_int{4, 2, 6, 16}}, {"net.inet.tcp.syncachelimit", []_C_int{4, 2, 6, 15}}, {"net.inet.udp.baddynamic", []_C_int{4, 2, 17, 2}}, {"net.inet.udp.checksum", []_C_int{4, 2, 17, 1}}, {"net.inet.udp.recvspace", []_C_int{4, 2, 17, 3}}, {"net.inet.udp.sendspace", []_C_int{4, 2, 17, 4}}, {"net.inet.udp.stats", []_C_int{4, 2, 17, 5}}, {"net.inet6.divert.recvspace", []_C_int{4, 24, 86, 1}}, {"net.inet6.divert.sendspace", []_C_int{4, 24, 86, 2}}, {"net.inet6.divert.stats", []_C_int{4, 24, 86, 3}}, {"net.inet6.icmp6.errppslimit", []_C_int{4, 24, 30, 14}}, {"net.inet6.icmp6.mtudisc_hiwat", []_C_int{4, 24, 30, 16}}, {"net.inet6.icmp6.mtudisc_lowat", []_C_int{4, 24, 30, 17}}, {"net.inet6.icmp6.nd6_debug", []_C_int{4, 24, 30, 18}}, {"net.inet6.icmp6.nd6_delay", []_C_int{4, 24, 30, 8}}, {"net.inet6.icmp6.nd6_maxnudhint", []_C_int{4, 24, 30, 15}}, {"net.inet6.icmp6.nd6_mmaxtries", []_C_int{4, 24, 30, 10}}, {"net.inet6.icmp6.nd6_prune", []_C_int{4, 24, 30, 6}}, {"net.inet6.icmp6.nd6_umaxtries", []_C_int{4, 24, 30, 9}}, {"net.inet6.icmp6.nd6_useloopback", []_C_int{4, 24, 30, 11}}, {"net.inet6.icmp6.nodeinfo", []_C_int{4, 24, 30, 13}}, {"net.inet6.icmp6.rediraccept", []_C_int{4, 24, 30, 2}}, {"net.inet6.icmp6.redirtimeout", []_C_int{4, 24, 30, 3}}, {"net.inet6.ip6.accept_rtadv", []_C_int{4, 24, 17, 12}}, {"net.inet6.ip6.auto_flowlabel", []_C_int{4, 24, 17, 17}}, {"net.inet6.ip6.dad_count", []_C_int{4, 24, 17, 16}}, {"net.inet6.ip6.dad_pending", []_C_int{4, 24, 17, 49}}, {"net.inet6.ip6.defmcasthlim", []_C_int{4, 24, 17, 18}}, {"net.inet6.ip6.forwarding", []_C_int{4, 24, 17, 1}}, {"net.inet6.ip6.forwsrcrt", []_C_int{4, 24, 17, 5}}, {"net.inet6.ip6.hdrnestlimit", []_C_int{4, 24, 17, 15}}, {"net.inet6.ip6.hlim", []_C_int{4, 24, 17, 3}}, {"net.inet6.ip6.log_interval", []_C_int{4, 24, 17, 14}}, {"net.inet6.ip6.maxdynroutes", []_C_int{4, 24, 17, 48}}, {"net.inet6.ip6.maxfragpackets", []_C_int{4, 24, 17, 9}}, {"net.inet6.ip6.maxfrags", []_C_int{4, 24, 17, 41}}, {"net.inet6.ip6.maxifdefrouters", []_C_int{4, 24, 17, 47}}, {"net.inet6.ip6.maxifprefixes", []_C_int{4, 24, 17, 46}}, {"net.inet6.ip6.mforwarding", []_C_int{4, 24, 17, 42}}, {"net.inet6.ip6.mrtproto", []_C_int{4, 24, 17, 8}}, {"net.inet6.ip6.mtudisctimeout", []_C_int{4, 24, 17, 50}}, {"net.inet6.ip6.multicast_mtudisc", []_C_int{4, 24, 17, 44}}, {"net.inet6.ip6.multipath", []_C_int{4, 24, 17, 43}}, {"net.inet6.ip6.neighborgcthresh", []_C_int{4, 24, 17, 45}}, {"net.inet6.ip6.redirect", []_C_int{4, 24, 17, 2}}, {"net.inet6.ip6.rr_prune", []_C_int{4, 24, 17, 22}}, {"net.inet6.ip6.sourcecheck", []_C_int{4, 24, 17, 10}}, {"net.inet6.ip6.sourcecheck_logint", []_C_int{4, 24, 17, 11}}, {"net.inet6.ip6.use_deprecated", []_C_int{4, 24, 17, 21}}, {"net.inet6.ip6.v6only", []_C_int{4, 24, 17, 24}}, {"net.key.sadb_dump", []_C_int{4, 30, 1}}, {"net.key.spd_dump", []_C_int{4, 30, 2}}, {"net.mpls.ifq.congestion", []_C_int{4, 33, 3, 4}}, {"net.mpls.ifq.drops", []_C_int{4, 33, 3, 3}}, {"net.mpls.ifq.len", []_C_int{4, 33, 3, 1}}, {"net.mpls.ifq.maxlen", []_C_int{4, 33, 3, 2}}, {"net.mpls.mapttl_ip", []_C_int{4, 33, 5}}, {"net.mpls.mapttl_ip6", []_C_int{4, 33, 6}}, {"net.mpls.maxloop_inkernel", []_C_int{4, 33, 4}}, {"net.mpls.ttl", []_C_int{4, 33, 2}}, {"net.pflow.stats", []_C_int{4, 34, 1}}, {"net.pipex.enable", []_C_int{4, 35, 1}}, {"vm.anonmin", []_C_int{2, 7}}, {"vm.loadavg", []_C_int{2, 2}}, {"vm.maxslp", []_C_int{2, 10}}, {"vm.nkmempages", []_C_int{2, 6}}, {"vm.psstrings", []_C_int{2, 3}}, {"vm.swapencrypt.enable", []_C_int{2, 5, 0}}, {"vm.swapencrypt.keyscreated", []_C_int{2, 5, 1}}, {"vm.swapencrypt.keysdeleted", []_C_int{2, 5, 2}}, {"vm.uspace", []_C_int{2, 11}}, {"vm.uvmexp", []_C_int{2, 4}}, {"vm.vmmeter", []_C_int{2, 1}}, {"vm.vnodemin", []_C_int{2, 9}}, {"vm.vtextmin", []_C_int{2, 8}}, } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsysctl_openbsd_386.go0000644061062106075000000002732213172163421025511 0ustar stgraberdomain admins// mksysctl_openbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT package unix type mibentry struct { ctlname string ctloid []_C_int } var sysctlMib = []mibentry{ {"ddb.console", []_C_int{9, 6}}, {"ddb.log", []_C_int{9, 7}}, {"ddb.max_line", []_C_int{9, 3}}, {"ddb.max_width", []_C_int{9, 2}}, {"ddb.panic", []_C_int{9, 5}}, {"ddb.radix", []_C_int{9, 1}}, {"ddb.tab_stop_width", []_C_int{9, 4}}, {"ddb.trigger", []_C_int{9, 8}}, {"fs.posix.setuid", []_C_int{3, 1, 1}}, {"hw.allowpowerdown", []_C_int{6, 22}}, {"hw.byteorder", []_C_int{6, 4}}, {"hw.cpuspeed", []_C_int{6, 12}}, {"hw.diskcount", []_C_int{6, 10}}, {"hw.disknames", []_C_int{6, 8}}, {"hw.diskstats", []_C_int{6, 9}}, {"hw.machine", []_C_int{6, 1}}, {"hw.model", []_C_int{6, 2}}, {"hw.ncpu", []_C_int{6, 3}}, {"hw.ncpufound", []_C_int{6, 21}}, {"hw.pagesize", []_C_int{6, 7}}, {"hw.physmem", []_C_int{6, 19}}, {"hw.product", []_C_int{6, 15}}, {"hw.serialno", []_C_int{6, 17}}, {"hw.setperf", []_C_int{6, 13}}, {"hw.usermem", []_C_int{6, 20}}, {"hw.uuid", []_C_int{6, 18}}, {"hw.vendor", []_C_int{6, 14}}, {"hw.version", []_C_int{6, 16}}, {"kern.arandom", []_C_int{1, 37}}, {"kern.argmax", []_C_int{1, 8}}, {"kern.boottime", []_C_int{1, 21}}, {"kern.bufcachepercent", []_C_int{1, 72}}, {"kern.ccpu", []_C_int{1, 45}}, {"kern.clockrate", []_C_int{1, 12}}, {"kern.consdev", []_C_int{1, 75}}, {"kern.cp_time", []_C_int{1, 40}}, {"kern.cp_time2", []_C_int{1, 71}}, {"kern.cryptodevallowsoft", []_C_int{1, 53}}, {"kern.domainname", []_C_int{1, 22}}, {"kern.file", []_C_int{1, 73}}, {"kern.forkstat", []_C_int{1, 42}}, {"kern.fscale", []_C_int{1, 46}}, {"kern.fsync", []_C_int{1, 33}}, {"kern.hostid", []_C_int{1, 11}}, {"kern.hostname", []_C_int{1, 10}}, {"kern.intrcnt.nintrcnt", []_C_int{1, 63, 1}}, {"kern.job_control", []_C_int{1, 19}}, {"kern.malloc.buckets", []_C_int{1, 39, 1}}, {"kern.malloc.kmemnames", []_C_int{1, 39, 3}}, {"kern.maxclusters", []_C_int{1, 67}}, {"kern.maxfiles", []_C_int{1, 7}}, {"kern.maxlocksperuid", []_C_int{1, 70}}, {"kern.maxpartitions", []_C_int{1, 23}}, {"kern.maxproc", []_C_int{1, 6}}, {"kern.maxthread", []_C_int{1, 25}}, {"kern.maxvnodes", []_C_int{1, 5}}, {"kern.mbstat", []_C_int{1, 59}}, {"kern.msgbuf", []_C_int{1, 48}}, {"kern.msgbufsize", []_C_int{1, 38}}, {"kern.nchstats", []_C_int{1, 41}}, {"kern.netlivelocks", []_C_int{1, 76}}, {"kern.nfiles", []_C_int{1, 56}}, {"kern.ngroups", []_C_int{1, 18}}, {"kern.nosuidcoredump", []_C_int{1, 32}}, {"kern.nprocs", []_C_int{1, 47}}, {"kern.nselcoll", []_C_int{1, 43}}, {"kern.nthreads", []_C_int{1, 26}}, {"kern.numvnodes", []_C_int{1, 58}}, {"kern.osrelease", []_C_int{1, 2}}, {"kern.osrevision", []_C_int{1, 3}}, {"kern.ostype", []_C_int{1, 1}}, {"kern.osversion", []_C_int{1, 27}}, {"kern.pool_debug", []_C_int{1, 77}}, {"kern.posix1version", []_C_int{1, 17}}, {"kern.proc", []_C_int{1, 66}}, {"kern.random", []_C_int{1, 31}}, {"kern.rawpartition", []_C_int{1, 24}}, {"kern.saved_ids", []_C_int{1, 20}}, {"kern.securelevel", []_C_int{1, 9}}, {"kern.seminfo", []_C_int{1, 61}}, {"kern.shminfo", []_C_int{1, 62}}, {"kern.somaxconn", []_C_int{1, 28}}, {"kern.sominconn", []_C_int{1, 29}}, {"kern.splassert", []_C_int{1, 54}}, {"kern.stackgap_random", []_C_int{1, 50}}, {"kern.sysvipc_info", []_C_int{1, 51}}, {"kern.sysvmsg", []_C_int{1, 34}}, {"kern.sysvsem", []_C_int{1, 35}}, {"kern.sysvshm", []_C_int{1, 36}}, {"kern.timecounter.choice", []_C_int{1, 69, 4}}, {"kern.timecounter.hardware", []_C_int{1, 69, 3}}, {"kern.timecounter.tick", []_C_int{1, 69, 1}}, {"kern.timecounter.timestepwarnings", []_C_int{1, 69, 2}}, {"kern.tty.maxptys", []_C_int{1, 44, 6}}, {"kern.tty.nptys", []_C_int{1, 44, 7}}, {"kern.tty.tk_cancc", []_C_int{1, 44, 4}}, {"kern.tty.tk_nin", []_C_int{1, 44, 1}}, {"kern.tty.tk_nout", []_C_int{1, 44, 2}}, {"kern.tty.tk_rawcc", []_C_int{1, 44, 3}}, {"kern.tty.ttyinfo", []_C_int{1, 44, 5}}, {"kern.ttycount", []_C_int{1, 57}}, {"kern.userasymcrypto", []_C_int{1, 60}}, {"kern.usercrypto", []_C_int{1, 52}}, {"kern.usermount", []_C_int{1, 30}}, {"kern.version", []_C_int{1, 4}}, {"kern.vnode", []_C_int{1, 13}}, {"kern.watchdog.auto", []_C_int{1, 64, 2}}, {"kern.watchdog.period", []_C_int{1, 64, 1}}, {"net.bpf.bufsize", []_C_int{4, 31, 1}}, {"net.bpf.maxbufsize", []_C_int{4, 31, 2}}, {"net.inet.ah.enable", []_C_int{4, 2, 51, 1}}, {"net.inet.ah.stats", []_C_int{4, 2, 51, 2}}, {"net.inet.carp.allow", []_C_int{4, 2, 112, 1}}, {"net.inet.carp.log", []_C_int{4, 2, 112, 3}}, {"net.inet.carp.preempt", []_C_int{4, 2, 112, 2}}, {"net.inet.carp.stats", []_C_int{4, 2, 112, 4}}, {"net.inet.divert.recvspace", []_C_int{4, 2, 258, 1}}, {"net.inet.divert.sendspace", []_C_int{4, 2, 258, 2}}, {"net.inet.divert.stats", []_C_int{4, 2, 258, 3}}, {"net.inet.esp.enable", []_C_int{4, 2, 50, 1}}, {"net.inet.esp.stats", []_C_int{4, 2, 50, 4}}, {"net.inet.esp.udpencap", []_C_int{4, 2, 50, 2}}, {"net.inet.esp.udpencap_port", []_C_int{4, 2, 50, 3}}, {"net.inet.etherip.allow", []_C_int{4, 2, 97, 1}}, {"net.inet.etherip.stats", []_C_int{4, 2, 97, 2}}, {"net.inet.gre.allow", []_C_int{4, 2, 47, 1}}, {"net.inet.gre.wccp", []_C_int{4, 2, 47, 2}}, {"net.inet.icmp.bmcastecho", []_C_int{4, 2, 1, 2}}, {"net.inet.icmp.errppslimit", []_C_int{4, 2, 1, 3}}, {"net.inet.icmp.maskrepl", []_C_int{4, 2, 1, 1}}, {"net.inet.icmp.rediraccept", []_C_int{4, 2, 1, 4}}, {"net.inet.icmp.redirtimeout", []_C_int{4, 2, 1, 5}}, {"net.inet.icmp.stats", []_C_int{4, 2, 1, 7}}, {"net.inet.icmp.tstamprepl", []_C_int{4, 2, 1, 6}}, {"net.inet.igmp.stats", []_C_int{4, 2, 2, 1}}, {"net.inet.ip.arpqueued", []_C_int{4, 2, 0, 36}}, {"net.inet.ip.encdebug", []_C_int{4, 2, 0, 12}}, {"net.inet.ip.forwarding", []_C_int{4, 2, 0, 1}}, {"net.inet.ip.ifq.congestion", []_C_int{4, 2, 0, 30, 4}}, {"net.inet.ip.ifq.drops", []_C_int{4, 2, 0, 30, 3}}, {"net.inet.ip.ifq.len", []_C_int{4, 2, 0, 30, 1}}, {"net.inet.ip.ifq.maxlen", []_C_int{4, 2, 0, 30, 2}}, {"net.inet.ip.maxqueue", []_C_int{4, 2, 0, 11}}, {"net.inet.ip.mforwarding", []_C_int{4, 2, 0, 31}}, {"net.inet.ip.mrtproto", []_C_int{4, 2, 0, 34}}, {"net.inet.ip.mrtstats", []_C_int{4, 2, 0, 35}}, {"net.inet.ip.mtu", []_C_int{4, 2, 0, 4}}, {"net.inet.ip.mtudisc", []_C_int{4, 2, 0, 27}}, {"net.inet.ip.mtudisctimeout", []_C_int{4, 2, 0, 28}}, {"net.inet.ip.multipath", []_C_int{4, 2, 0, 32}}, {"net.inet.ip.portfirst", []_C_int{4, 2, 0, 7}}, {"net.inet.ip.porthifirst", []_C_int{4, 2, 0, 9}}, {"net.inet.ip.porthilast", []_C_int{4, 2, 0, 10}}, {"net.inet.ip.portlast", []_C_int{4, 2, 0, 8}}, {"net.inet.ip.redirect", []_C_int{4, 2, 0, 2}}, {"net.inet.ip.sourceroute", []_C_int{4, 2, 0, 5}}, {"net.inet.ip.stats", []_C_int{4, 2, 0, 33}}, {"net.inet.ip.ttl", []_C_int{4, 2, 0, 3}}, {"net.inet.ipcomp.enable", []_C_int{4, 2, 108, 1}}, {"net.inet.ipcomp.stats", []_C_int{4, 2, 108, 2}}, {"net.inet.ipip.allow", []_C_int{4, 2, 4, 1}}, {"net.inet.ipip.stats", []_C_int{4, 2, 4, 2}}, {"net.inet.mobileip.allow", []_C_int{4, 2, 55, 1}}, {"net.inet.pfsync.stats", []_C_int{4, 2, 240, 1}}, {"net.inet.pim.stats", []_C_int{4, 2, 103, 1}}, {"net.inet.tcp.ackonpush", []_C_int{4, 2, 6, 13}}, {"net.inet.tcp.always_keepalive", []_C_int{4, 2, 6, 22}}, {"net.inet.tcp.baddynamic", []_C_int{4, 2, 6, 6}}, {"net.inet.tcp.drop", []_C_int{4, 2, 6, 19}}, {"net.inet.tcp.ecn", []_C_int{4, 2, 6, 14}}, {"net.inet.tcp.ident", []_C_int{4, 2, 6, 9}}, {"net.inet.tcp.keepidle", []_C_int{4, 2, 6, 3}}, {"net.inet.tcp.keepinittime", []_C_int{4, 2, 6, 2}}, {"net.inet.tcp.keepintvl", []_C_int{4, 2, 6, 4}}, {"net.inet.tcp.mssdflt", []_C_int{4, 2, 6, 11}}, {"net.inet.tcp.reasslimit", []_C_int{4, 2, 6, 18}}, {"net.inet.tcp.rfc1323", []_C_int{4, 2, 6, 1}}, {"net.inet.tcp.rfc3390", []_C_int{4, 2, 6, 17}}, {"net.inet.tcp.rstppslimit", []_C_int{4, 2, 6, 12}}, {"net.inet.tcp.sack", []_C_int{4, 2, 6, 10}}, {"net.inet.tcp.sackholelimit", []_C_int{4, 2, 6, 20}}, {"net.inet.tcp.slowhz", []_C_int{4, 2, 6, 5}}, {"net.inet.tcp.stats", []_C_int{4, 2, 6, 21}}, {"net.inet.tcp.synbucketlimit", []_C_int{4, 2, 6, 16}}, {"net.inet.tcp.syncachelimit", []_C_int{4, 2, 6, 15}}, {"net.inet.udp.baddynamic", []_C_int{4, 2, 17, 2}}, {"net.inet.udp.checksum", []_C_int{4, 2, 17, 1}}, {"net.inet.udp.recvspace", []_C_int{4, 2, 17, 3}}, {"net.inet.udp.sendspace", []_C_int{4, 2, 17, 4}}, {"net.inet.udp.stats", []_C_int{4, 2, 17, 5}}, {"net.inet6.divert.recvspace", []_C_int{4, 24, 86, 1}}, {"net.inet6.divert.sendspace", []_C_int{4, 24, 86, 2}}, {"net.inet6.divert.stats", []_C_int{4, 24, 86, 3}}, {"net.inet6.icmp6.errppslimit", []_C_int{4, 24, 30, 14}}, {"net.inet6.icmp6.mtudisc_hiwat", []_C_int{4, 24, 30, 16}}, {"net.inet6.icmp6.mtudisc_lowat", []_C_int{4, 24, 30, 17}}, {"net.inet6.icmp6.nd6_debug", []_C_int{4, 24, 30, 18}}, {"net.inet6.icmp6.nd6_delay", []_C_int{4, 24, 30, 8}}, {"net.inet6.icmp6.nd6_maxnudhint", []_C_int{4, 24, 30, 15}}, {"net.inet6.icmp6.nd6_mmaxtries", []_C_int{4, 24, 30, 10}}, {"net.inet6.icmp6.nd6_prune", []_C_int{4, 24, 30, 6}}, {"net.inet6.icmp6.nd6_umaxtries", []_C_int{4, 24, 30, 9}}, {"net.inet6.icmp6.nd6_useloopback", []_C_int{4, 24, 30, 11}}, {"net.inet6.icmp6.nodeinfo", []_C_int{4, 24, 30, 13}}, {"net.inet6.icmp6.rediraccept", []_C_int{4, 24, 30, 2}}, {"net.inet6.icmp6.redirtimeout", []_C_int{4, 24, 30, 3}}, {"net.inet6.ip6.accept_rtadv", []_C_int{4, 24, 17, 12}}, {"net.inet6.ip6.auto_flowlabel", []_C_int{4, 24, 17, 17}}, {"net.inet6.ip6.dad_count", []_C_int{4, 24, 17, 16}}, {"net.inet6.ip6.dad_pending", []_C_int{4, 24, 17, 49}}, {"net.inet6.ip6.defmcasthlim", []_C_int{4, 24, 17, 18}}, {"net.inet6.ip6.forwarding", []_C_int{4, 24, 17, 1}}, {"net.inet6.ip6.forwsrcrt", []_C_int{4, 24, 17, 5}}, {"net.inet6.ip6.hdrnestlimit", []_C_int{4, 24, 17, 15}}, {"net.inet6.ip6.hlim", []_C_int{4, 24, 17, 3}}, {"net.inet6.ip6.log_interval", []_C_int{4, 24, 17, 14}}, {"net.inet6.ip6.maxdynroutes", []_C_int{4, 24, 17, 48}}, {"net.inet6.ip6.maxfragpackets", []_C_int{4, 24, 17, 9}}, {"net.inet6.ip6.maxfrags", []_C_int{4, 24, 17, 41}}, {"net.inet6.ip6.maxifdefrouters", []_C_int{4, 24, 17, 47}}, {"net.inet6.ip6.maxifprefixes", []_C_int{4, 24, 17, 46}}, {"net.inet6.ip6.mforwarding", []_C_int{4, 24, 17, 42}}, {"net.inet6.ip6.mrtproto", []_C_int{4, 24, 17, 8}}, {"net.inet6.ip6.mtudisctimeout", []_C_int{4, 24, 17, 50}}, {"net.inet6.ip6.multicast_mtudisc", []_C_int{4, 24, 17, 44}}, {"net.inet6.ip6.multipath", []_C_int{4, 24, 17, 43}}, {"net.inet6.ip6.neighborgcthresh", []_C_int{4, 24, 17, 45}}, {"net.inet6.ip6.redirect", []_C_int{4, 24, 17, 2}}, {"net.inet6.ip6.rr_prune", []_C_int{4, 24, 17, 22}}, {"net.inet6.ip6.sourcecheck", []_C_int{4, 24, 17, 10}}, {"net.inet6.ip6.sourcecheck_logint", []_C_int{4, 24, 17, 11}}, {"net.inet6.ip6.use_deprecated", []_C_int{4, 24, 17, 21}}, {"net.inet6.ip6.v6only", []_C_int{4, 24, 17, 24}}, {"net.key.sadb_dump", []_C_int{4, 30, 1}}, {"net.key.spd_dump", []_C_int{4, 30, 2}}, {"net.mpls.ifq.congestion", []_C_int{4, 33, 3, 4}}, {"net.mpls.ifq.drops", []_C_int{4, 33, 3, 3}}, {"net.mpls.ifq.len", []_C_int{4, 33, 3, 1}}, {"net.mpls.ifq.maxlen", []_C_int{4, 33, 3, 2}}, {"net.mpls.mapttl_ip", []_C_int{4, 33, 5}}, {"net.mpls.mapttl_ip6", []_C_int{4, 33, 6}}, {"net.mpls.maxloop_inkernel", []_C_int{4, 33, 4}}, {"net.mpls.ttl", []_C_int{4, 33, 2}}, {"net.pflow.stats", []_C_int{4, 34, 1}}, {"net.pipex.enable", []_C_int{4, 35, 1}}, {"vm.anonmin", []_C_int{2, 7}}, {"vm.loadavg", []_C_int{2, 2}}, {"vm.maxslp", []_C_int{2, 10}}, {"vm.nkmempages", []_C_int{2, 6}}, {"vm.psstrings", []_C_int{2, 3}}, {"vm.swapencrypt.enable", []_C_int{2, 5, 0}}, {"vm.swapencrypt.keyscreated", []_C_int{2, 5, 1}}, {"vm.swapencrypt.keysdeleted", []_C_int{2, 5, 2}}, {"vm.uspace", []_C_int{2, 11}}, {"vm.uvmexp", []_C_int{2, 4}}, {"vm.vmmeter", []_C_int{2, 1}}, {"vm.vnodemin", []_C_int{2, 9}}, {"vm.vtextmin", []_C_int{2, 8}}, } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_solaris_amd64.go0000644061062106075000000012672413172163421026265 0ustar stgraberdomain admins// mksyscall_solaris.pl -tags solaris,amd64 syscall_solaris.go syscall_solaris_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build solaris,amd64 package unix import ( "syscall" "unsafe" ) //go:cgo_import_dynamic libc_pipe pipe "libc.so" //go:cgo_import_dynamic libc_getsockname getsockname "libsocket.so" //go:cgo_import_dynamic libc_getcwd getcwd "libc.so" //go:cgo_import_dynamic libc_getgroups getgroups "libc.so" //go:cgo_import_dynamic libc_setgroups setgroups "libc.so" //go:cgo_import_dynamic libc_wait4 wait4 "libc.so" //go:cgo_import_dynamic libc_gethostname gethostname "libc.so" //go:cgo_import_dynamic libc_utimes utimes "libc.so" //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" //go:cgo_import_dynamic libc_fcntl fcntl "libc.so" //go:cgo_import_dynamic libc_futimesat futimesat "libc.so" //go:cgo_import_dynamic libc_accept accept "libsocket.so" //go:cgo_import_dynamic libc___xnet_recvmsg __xnet_recvmsg "libsocket.so" //go:cgo_import_dynamic libc___xnet_sendmsg __xnet_sendmsg "libsocket.so" //go:cgo_import_dynamic libc_acct acct "libc.so" //go:cgo_import_dynamic libc___makedev __makedev "libc.so" //go:cgo_import_dynamic libc___major __major "libc.so" //go:cgo_import_dynamic libc___minor __minor "libc.so" //go:cgo_import_dynamic libc_ioctl ioctl "libc.so" //go:cgo_import_dynamic libc_access access "libc.so" //go:cgo_import_dynamic libc_adjtime adjtime "libc.so" //go:cgo_import_dynamic libc_chdir chdir "libc.so" //go:cgo_import_dynamic libc_chmod chmod "libc.so" //go:cgo_import_dynamic libc_chown chown "libc.so" //go:cgo_import_dynamic libc_chroot chroot "libc.so" //go:cgo_import_dynamic libc_close close "libc.so" //go:cgo_import_dynamic libc_creat creat "libc.so" //go:cgo_import_dynamic libc_dup dup "libc.so" //go:cgo_import_dynamic libc_dup2 dup2 "libc.so" //go:cgo_import_dynamic libc_exit exit "libc.so" //go:cgo_import_dynamic libc_fchdir fchdir "libc.so" //go:cgo_import_dynamic libc_fchmod fchmod "libc.so" //go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so" //go:cgo_import_dynamic libc_fchown fchown "libc.so" //go:cgo_import_dynamic libc_fchownat fchownat "libc.so" //go:cgo_import_dynamic libc_fdatasync fdatasync "libc.so" //go:cgo_import_dynamic libc_flock flock "libc.so" //go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so" //go:cgo_import_dynamic libc_fstat fstat "libc.so" //go:cgo_import_dynamic libc_fstatvfs fstatvfs "libc.so" //go:cgo_import_dynamic libc_getdents getdents "libc.so" //go:cgo_import_dynamic libc_getgid getgid "libc.so" //go:cgo_import_dynamic libc_getpid getpid "libc.so" //go:cgo_import_dynamic libc_getpgid getpgid "libc.so" //go:cgo_import_dynamic libc_getpgrp getpgrp "libc.so" //go:cgo_import_dynamic libc_geteuid geteuid "libc.so" //go:cgo_import_dynamic libc_getegid getegid "libc.so" //go:cgo_import_dynamic libc_getppid getppid "libc.so" //go:cgo_import_dynamic libc_getpriority getpriority "libc.so" //go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so" //go:cgo_import_dynamic libc_getrusage getrusage "libc.so" //go:cgo_import_dynamic libc_gettimeofday gettimeofday "libc.so" //go:cgo_import_dynamic libc_getuid getuid "libc.so" //go:cgo_import_dynamic libc_kill kill "libc.so" //go:cgo_import_dynamic libc_lchown lchown "libc.so" //go:cgo_import_dynamic libc_link link "libc.so" //go:cgo_import_dynamic libc___xnet_llisten __xnet_llisten "libsocket.so" //go:cgo_import_dynamic libc_lstat lstat "libc.so" //go:cgo_import_dynamic libc_madvise madvise "libc.so" //go:cgo_import_dynamic libc_mkdir mkdir "libc.so" //go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so" //go:cgo_import_dynamic libc_mkfifo mkfifo "libc.so" //go:cgo_import_dynamic libc_mkfifoat mkfifoat "libc.so" //go:cgo_import_dynamic libc_mknod mknod "libc.so" //go:cgo_import_dynamic libc_mknodat mknodat "libc.so" //go:cgo_import_dynamic libc_mlock mlock "libc.so" //go:cgo_import_dynamic libc_mlockall mlockall "libc.so" //go:cgo_import_dynamic libc_mprotect mprotect "libc.so" //go:cgo_import_dynamic libc_msync msync "libc.so" //go:cgo_import_dynamic libc_munlock munlock "libc.so" //go:cgo_import_dynamic libc_munlockall munlockall "libc.so" //go:cgo_import_dynamic libc_nanosleep nanosleep "libc.so" //go:cgo_import_dynamic libc_open open "libc.so" //go:cgo_import_dynamic libc_openat openat "libc.so" //go:cgo_import_dynamic libc_pathconf pathconf "libc.so" //go:cgo_import_dynamic libc_pause pause "libc.so" //go:cgo_import_dynamic libc_pread pread "libc.so" //go:cgo_import_dynamic libc_pwrite pwrite "libc.so" //go:cgo_import_dynamic libc_read read "libc.so" //go:cgo_import_dynamic libc_readlink readlink "libc.so" //go:cgo_import_dynamic libc_rename rename "libc.so" //go:cgo_import_dynamic libc_renameat renameat "libc.so" //go:cgo_import_dynamic libc_rmdir rmdir "libc.so" //go:cgo_import_dynamic libc_lseek lseek "libc.so" //go:cgo_import_dynamic libc_setegid setegid "libc.so" //go:cgo_import_dynamic libc_seteuid seteuid "libc.so" //go:cgo_import_dynamic libc_setgid setgid "libc.so" //go:cgo_import_dynamic libc_sethostname sethostname "libc.so" //go:cgo_import_dynamic libc_setpgid setpgid "libc.so" //go:cgo_import_dynamic libc_setpriority setpriority "libc.so" //go:cgo_import_dynamic libc_setregid setregid "libc.so" //go:cgo_import_dynamic libc_setreuid setreuid "libc.so" //go:cgo_import_dynamic libc_setrlimit setrlimit "libc.so" //go:cgo_import_dynamic libc_setsid setsid "libc.so" //go:cgo_import_dynamic libc_setuid setuid "libc.so" //go:cgo_import_dynamic libc_shutdown shutdown "libsocket.so" //go:cgo_import_dynamic libc_stat stat "libc.so" //go:cgo_import_dynamic libc_statvfs statvfs "libc.so" //go:cgo_import_dynamic libc_symlink symlink "libc.so" //go:cgo_import_dynamic libc_sync sync "libc.so" //go:cgo_import_dynamic libc_times times "libc.so" //go:cgo_import_dynamic libc_truncate truncate "libc.so" //go:cgo_import_dynamic libc_fsync fsync "libc.so" //go:cgo_import_dynamic libc_ftruncate ftruncate "libc.so" //go:cgo_import_dynamic libc_umask umask "libc.so" //go:cgo_import_dynamic libc_uname uname "libc.so" //go:cgo_import_dynamic libc_umount umount "libc.so" //go:cgo_import_dynamic libc_unlink unlink "libc.so" //go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so" //go:cgo_import_dynamic libc_ustat ustat "libc.so" //go:cgo_import_dynamic libc_utime utime "libc.so" //go:cgo_import_dynamic libc___xnet_bind __xnet_bind "libsocket.so" //go:cgo_import_dynamic libc___xnet_connect __xnet_connect "libsocket.so" //go:cgo_import_dynamic libc_mmap mmap "libc.so" //go:cgo_import_dynamic libc_munmap munmap "libc.so" //go:cgo_import_dynamic libc___xnet_sendto __xnet_sendto "libsocket.so" //go:cgo_import_dynamic libc___xnet_socket __xnet_socket "libsocket.so" //go:cgo_import_dynamic libc___xnet_socketpair __xnet_socketpair "libsocket.so" //go:cgo_import_dynamic libc_write write "libc.so" //go:cgo_import_dynamic libc___xnet_getsockopt __xnet_getsockopt "libsocket.so" //go:cgo_import_dynamic libc_getpeername getpeername "libsocket.so" //go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so" //go:cgo_import_dynamic libc_recvfrom recvfrom "libsocket.so" //go:linkname procpipe libc_pipe //go:linkname procgetsockname libc_getsockname //go:linkname procGetcwd libc_getcwd //go:linkname procgetgroups libc_getgroups //go:linkname procsetgroups libc_setgroups //go:linkname procwait4 libc_wait4 //go:linkname procgethostname libc_gethostname //go:linkname procutimes libc_utimes //go:linkname procutimensat libc_utimensat //go:linkname procfcntl libc_fcntl //go:linkname procfutimesat libc_futimesat //go:linkname procaccept libc_accept //go:linkname proc__xnet_recvmsg libc___xnet_recvmsg //go:linkname proc__xnet_sendmsg libc___xnet_sendmsg //go:linkname procacct libc_acct //go:linkname proc__makedev libc___makedev //go:linkname proc__major libc___major //go:linkname proc__minor libc___minor //go:linkname procioctl libc_ioctl //go:linkname procAccess libc_access //go:linkname procAdjtime libc_adjtime //go:linkname procChdir libc_chdir //go:linkname procChmod libc_chmod //go:linkname procChown libc_chown //go:linkname procChroot libc_chroot //go:linkname procClose libc_close //go:linkname procCreat libc_creat //go:linkname procDup libc_dup //go:linkname procDup2 libc_dup2 //go:linkname procExit libc_exit //go:linkname procFchdir libc_fchdir //go:linkname procFchmod libc_fchmod //go:linkname procFchmodat libc_fchmodat //go:linkname procFchown libc_fchown //go:linkname procFchownat libc_fchownat //go:linkname procFdatasync libc_fdatasync //go:linkname procFlock libc_flock //go:linkname procFpathconf libc_fpathconf //go:linkname procFstat libc_fstat //go:linkname procFstatvfs libc_fstatvfs //go:linkname procGetdents libc_getdents //go:linkname procGetgid libc_getgid //go:linkname procGetpid libc_getpid //go:linkname procGetpgid libc_getpgid //go:linkname procGetpgrp libc_getpgrp //go:linkname procGeteuid libc_geteuid //go:linkname procGetegid libc_getegid //go:linkname procGetppid libc_getppid //go:linkname procGetpriority libc_getpriority //go:linkname procGetrlimit libc_getrlimit //go:linkname procGetrusage libc_getrusage //go:linkname procGettimeofday libc_gettimeofday //go:linkname procGetuid libc_getuid //go:linkname procKill libc_kill //go:linkname procLchown libc_lchown //go:linkname procLink libc_link //go:linkname proc__xnet_llisten libc___xnet_llisten //go:linkname procLstat libc_lstat //go:linkname procMadvise libc_madvise //go:linkname procMkdir libc_mkdir //go:linkname procMkdirat libc_mkdirat //go:linkname procMkfifo libc_mkfifo //go:linkname procMkfifoat libc_mkfifoat //go:linkname procMknod libc_mknod //go:linkname procMknodat libc_mknodat //go:linkname procMlock libc_mlock //go:linkname procMlockall libc_mlockall //go:linkname procMprotect libc_mprotect //go:linkname procMsync libc_msync //go:linkname procMunlock libc_munlock //go:linkname procMunlockall libc_munlockall //go:linkname procNanosleep libc_nanosleep //go:linkname procOpen libc_open //go:linkname procOpenat libc_openat //go:linkname procPathconf libc_pathconf //go:linkname procPause libc_pause //go:linkname procPread libc_pread //go:linkname procPwrite libc_pwrite //go:linkname procread libc_read //go:linkname procReadlink libc_readlink //go:linkname procRename libc_rename //go:linkname procRenameat libc_renameat //go:linkname procRmdir libc_rmdir //go:linkname proclseek libc_lseek //go:linkname procSetegid libc_setegid //go:linkname procSeteuid libc_seteuid //go:linkname procSetgid libc_setgid //go:linkname procSethostname libc_sethostname //go:linkname procSetpgid libc_setpgid //go:linkname procSetpriority libc_setpriority //go:linkname procSetregid libc_setregid //go:linkname procSetreuid libc_setreuid //go:linkname procSetrlimit libc_setrlimit //go:linkname procSetsid libc_setsid //go:linkname procSetuid libc_setuid //go:linkname procshutdown libc_shutdown //go:linkname procStat libc_stat //go:linkname procStatvfs libc_statvfs //go:linkname procSymlink libc_symlink //go:linkname procSync libc_sync //go:linkname procTimes libc_times //go:linkname procTruncate libc_truncate //go:linkname procFsync libc_fsync //go:linkname procFtruncate libc_ftruncate //go:linkname procUmask libc_umask //go:linkname procUname libc_uname //go:linkname procumount libc_umount //go:linkname procUnlink libc_unlink //go:linkname procUnlinkat libc_unlinkat //go:linkname procUstat libc_ustat //go:linkname procUtime libc_utime //go:linkname proc__xnet_bind libc___xnet_bind //go:linkname proc__xnet_connect libc___xnet_connect //go:linkname procmmap libc_mmap //go:linkname procmunmap libc_munmap //go:linkname proc__xnet_sendto libc___xnet_sendto //go:linkname proc__xnet_socket libc___xnet_socket //go:linkname proc__xnet_socketpair libc___xnet_socketpair //go:linkname procwrite libc_write //go:linkname proc__xnet_getsockopt libc___xnet_getsockopt //go:linkname procgetpeername libc_getpeername //go:linkname procsetsockopt libc_setsockopt //go:linkname procrecvfrom libc_recvfrom var ( procpipe, procgetsockname, procGetcwd, procgetgroups, procsetgroups, procwait4, procgethostname, procutimes, procutimensat, procfcntl, procfutimesat, procaccept, proc__xnet_recvmsg, proc__xnet_sendmsg, procacct, proc__makedev, proc__major, proc__minor, procioctl, procAccess, procAdjtime, procChdir, procChmod, procChown, procChroot, procClose, procCreat, procDup, procDup2, procExit, procFchdir, procFchmod, procFchmodat, procFchown, procFchownat, procFdatasync, procFlock, procFpathconf, procFstat, procFstatvfs, procGetdents, procGetgid, procGetpid, procGetpgid, procGetpgrp, procGeteuid, procGetegid, procGetppid, procGetpriority, procGetrlimit, procGetrusage, procGettimeofday, procGetuid, procKill, procLchown, procLink, proc__xnet_llisten, procLstat, procMadvise, procMkdir, procMkdirat, procMkfifo, procMkfifoat, procMknod, procMknodat, procMlock, procMlockall, procMprotect, procMsync, procMunlock, procMunlockall, procNanosleep, procOpen, procOpenat, procPathconf, procPause, procPread, procPwrite, procread, procReadlink, procRename, procRenameat, procRmdir, proclseek, procSetegid, procSeteuid, procSetgid, procSethostname, procSetpgid, procSetpriority, procSetregid, procSetreuid, procSetrlimit, procSetsid, procSetuid, procshutdown, procStat, procStatvfs, procSymlink, procSync, procTimes, procTruncate, procFsync, procFtruncate, procUmask, procUname, procumount, procUnlink, procUnlinkat, procUstat, procUtime, proc__xnet_bind, proc__xnet_connect, procmmap, procmunmap, proc__xnet_sendto, proc__xnet_socket, proc__xnet_socketpair, procwrite, proc__xnet_getsockopt, procgetpeername, procsetsockopt, procrecvfrom syscallFunc ) func pipe(p *[2]_C_int) (n int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procpipe)), 1, uintptr(unsafe.Pointer(p)), 0, 0, 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetsockname)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) if e1 != 0 { err = e1 } return } func Getcwd(buf []byte) (n int, err error) { var _p0 *byte if len(buf) > 0 { _p0 = &buf[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetcwd)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procsetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwait4)), 4, uintptr(pid), uintptr(unsafe.Pointer(statusp)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int32(r0) if e1 != 0 { err = e1 } return } func gethostname(buf []byte) (n int, err error) { var _p0 *byte if len(buf) > 0 { _p0 = &buf[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimes)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimensat)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flag), 0, 0) if e1 != 0 { err = e1 } return } func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0) val = int(r0) if e1 != 0 { err = e1 } return } func futimesat(fildes int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfutimesat)), 3, uintptr(fildes), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times)), 0, 0, 0) if e1 != 0 { err = e1 } return } func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procaccept)), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) fd = int(r0) if e1 != 0 { err = e1 } return } func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_recvmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_sendmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func acct(path *byte) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procacct)), 1, uintptr(unsafe.Pointer(path)), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func __makedev(version int, major uint, minor uint) (val uint64) { r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&proc__makedev)), 3, uintptr(version), uintptr(major), uintptr(minor), 0, 0, 0) val = uint64(r0) return } func __major(version int, dev uint64) (val uint) { r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&proc__major)), 2, uintptr(version), uintptr(dev), 0, 0, 0, 0) val = uint(r0) return } func __minor(version int, dev uint64) (val uint) { r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&proc__minor)), 2, uintptr(version), uintptr(dev), 0, 0, 0, 0) val = uint(r0) return } func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procioctl)), 3, uintptr(fd), uintptr(req), uintptr(arg), 0, 0, 0) if e1 != 0 { err = e1 } return } func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAccess)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAdjtime)), 2, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChmod)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0) if e1 != 0 { err = e1 } return } func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChroot)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Close(fd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procClose)), 1, uintptr(fd), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Creat(path string, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procCreat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) fd = int(r0) if e1 != 0 { err = e1 } return } func Dup(fd int) (nfd int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup)), 1, uintptr(fd), 0, 0, 0, 0, 0) nfd = int(r0) if e1 != 0 { err = e1 } return } func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup2)), 2, uintptr(oldfd), uintptr(newfd), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Exit(code int) { sysvicall6(uintptr(unsafe.Pointer(&procExit)), 1, uintptr(code), 0, 0, 0, 0, 0) return } func Fchdir(fd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchdir)), 1, uintptr(fd), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmod)), 2, uintptr(fd), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = e1 } return } func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchown)), 3, uintptr(fd), uintptr(uid), uintptr(gid), 0, 0, 0) if e1 != 0 { err = e1 } return } func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchownat)), 5, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = e1 } return } func Fdatasync(fd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFdatasync)), 1, uintptr(fd), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Flock(fd int, how int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFlock)), 2, uintptr(fd), uintptr(how), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFpathconf)), 2, uintptr(fd), uintptr(name), 0, 0, 0, 0) val = int(r0) if e1 != 0 { err = e1 } return } func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstat)), 2, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Fstatvfs(fd int, vfsstat *Statvfs_t) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstatvfs)), 2, uintptr(fd), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 *byte if len(buf) > 0 { _p0 = &buf[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetdents)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func Getgid() (gid int) { r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetgid)), 0, 0, 0, 0, 0, 0, 0) gid = int(r0) return } func Getpid() (pid int) { r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpid)), 0, 0, 0, 0, 0, 0, 0) pid = int(r0) return } func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgid)), 1, uintptr(pid), 0, 0, 0, 0, 0) pgid = int(r0) if e1 != 0 { err = e1 } return } func Getpgrp() (pgid int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgrp)), 0, 0, 0, 0, 0, 0, 0) pgid = int(r0) if e1 != 0 { err = e1 } return } func Geteuid() (euid int) { r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGeteuid)), 0, 0, 0, 0, 0, 0, 0) euid = int(r0) return } func Getegid() (egid int) { r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGetegid)), 0, 0, 0, 0, 0, 0, 0) egid = int(r0) return } func Getppid() (ppid int) { r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGetppid)), 0, 0, 0, 0, 0, 0, 0) ppid = int(r0) return } func Getpriority(which int, who int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetpriority)), 2, uintptr(which), uintptr(who), 0, 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrlimit)), 2, uintptr(which), uintptr(unsafe.Pointer(lim)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrusage)), 2, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGettimeofday)), 1, uintptr(unsafe.Pointer(tv)), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Getuid() (uid int) { r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetuid)), 0, 0, 0, 0, 0, 0, 0) uid = int(r0) return } func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procKill)), 2, uintptr(pid), uintptr(signum), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLchown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0) if e1 != 0 { err = e1 } return } func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Listen(s int, backlog int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_llisten)), 2, uintptr(s), uintptr(backlog), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLstat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Madvise(b []byte, advice int) (err error) { var _p0 *byte if len(b) > 0 { _p0 = &b[0] } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMadvise)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(advice), 0, 0, 0) if e1 != 0 { err = e1 } return } func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdir)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdirat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0) if e1 != 0 { err = e1 } return } func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifo)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Mkfifoat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifoat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0) if e1 != 0 { err = e1 } return } func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknod)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0, 0) if e1 != 0 { err = e1 } return } func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = e1 } return } func Mlock(b []byte) (err error) { var _p0 *byte if len(b) > 0 { _p0 = &b[0] } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Mlockall(flags int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlockall)), 1, uintptr(flags), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Mprotect(b []byte, prot int) (err error) { var _p0 *byte if len(b) > 0 { _p0 = &b[0] } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMprotect)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(prot), 0, 0, 0) if e1 != 0 { err = e1 } return } func Msync(b []byte, flags int) (err error) { var _p0 *byte if len(b) > 0 { _p0 = &b[0] } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMsync)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(flags), 0, 0, 0) if e1 != 0 { err = e1 } return } func Munlock(b []byte) (err error) { var _p0 *byte if len(b) > 0 { _p0 = &b[0] } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Munlockall() (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlockall)), 0, 0, 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procNanosleep)), 2, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpen)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0, 0) fd = int(r0) if e1 != 0 { err = e1 } return } func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpenat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = e1 } return } func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPathconf)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0, 0, 0, 0) val = int(r0) if e1 != 0 { err = e1 } return } func Pause() (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPause)), 0, 0, 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 *byte if len(p) > 0 { _p0 = &p[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPread)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 *byte if len(p) > 0 { _p0 = &p[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPwrite)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func read(fd int, p []byte) (n int, err error) { var _p0 *byte if len(p) > 0 { _p0 = &p[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte if len(buf) > 0 { _p1 = &buf[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procReadlink)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(len(buf)), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRename)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRenameat)), 4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = e1 } return } func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRmdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proclseek)), 3, uintptr(fd), uintptr(offset), uintptr(whence), 0, 0, 0) newoffset = int64(r0) if e1 != 0 { err = e1 } return } func Setegid(egid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetegid)), 1, uintptr(egid), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Seteuid(euid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSeteuid)), 1, uintptr(euid), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Setgid(gid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetgid)), 1, uintptr(gid), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Sethostname(p []byte) (err error) { var _p0 *byte if len(p) > 0 { _p0 = &p[0] } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Setpgid(pid int, pgid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetpgid)), 2, uintptr(pid), uintptr(pgid), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSetpriority)), 3, uintptr(which), uintptr(who), uintptr(prio), 0, 0, 0) if e1 != 0 { err = e1 } return } func Setregid(rgid int, egid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetregid)), 2, uintptr(rgid), uintptr(egid), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Setreuid(ruid int, euid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetreuid)), 2, uintptr(ruid), uintptr(euid), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetrlimit)), 2, uintptr(which), uintptr(unsafe.Pointer(lim)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Setsid() (pid int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetsid)), 0, 0, 0, 0, 0, 0, 0) pid = int(r0) if e1 != 0 { err = e1 } return } func Setuid(uid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetuid)), 1, uintptr(uid), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Shutdown(s int, how int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procshutdown)), 2, uintptr(s), uintptr(how), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Statvfs(path string, vfsstat *Statvfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStatvfs)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSymlink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Sync() (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSync)), 0, 0, 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procTimes)), 1, uintptr(unsafe.Pointer(tms)), 0, 0, 0, 0, 0) ticks = uintptr(r0) if e1 != 0 { err = e1 } return } func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procTruncate)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Fsync(fd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFsync)), 1, uintptr(fd), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Ftruncate(fd int, length int64) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFtruncate)), 2, uintptr(fd), uintptr(length), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Umask(mask int) (oldmask int) { r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procUmask)), 1, uintptr(mask), 0, 0, 0, 0, 0) oldmask = int(r0) return } func Uname(buf *Utsname) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procUname)), 1, uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procumount)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlink)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlinkat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0) if e1 != 0 { err = e1 } return } func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUstat)), 2, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUtime)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_bind)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) if e1 != 0 { err = e1 } return } func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_connect)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) if e1 != 0 { err = e1 } return } func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmmap)), 6, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { err = e1 } return } func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmunmap)), 2, uintptr(addr), uintptr(length), 0, 0, 0, 0) if e1 != 0 { err = e1 } return } func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 *byte if len(buf) > 0 { _p0 = &buf[0] } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_sendto)), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = e1 } return } func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_socket)), 3, uintptr(domain), uintptr(typ), uintptr(proto), 0, 0, 0) fd = int(r0) if e1 != 0 { err = e1 } return } func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&proc__xnet_socketpair)), 4, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = e1 } return } func write(fd int, p []byte) (n int, err error) { var _p0 *byte if len(p) > 0 { _p0 = &p[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_getsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = e1 } return } func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetpeername)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) if e1 != 0 { err = e1 } return } func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsetsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = e1 } return } func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 *byte if len(p) > 0 { _p0 = &p[0] } r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procrecvfrom)), 6, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = e1 } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_openbsd_arm.go0000644061062106075000000010103113172163421026067 0ustar stgraberdomain admins// mksyscall.pl -l32 -openbsd -arm -tags openbsd,arm syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build openbsd,arm package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go0000644061062106075000000010060013172163421026224 0ustar stgraberdomain admins// mksyscall.pl -openbsd -tags openbsd,amd64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build openbsd,amd64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_openbsd_386.go0000644061062106075000000010102413172163421025632 0ustar stgraberdomain admins// mksyscall.pl -l32 -openbsd -tags openbsd,386 syscall_bsd.go syscall_openbsd.go syscall_openbsd_386.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build openbsd,386 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_netbsd_arm.go0000644061062106075000000007623013172163421025730 0ustar stgraberdomain admins// mksyscall.pl -l32 -netbsd -arm -tags netbsd,arm syscall_bsd.go syscall_netbsd.go syscall_netbsd_arm.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build netbsd,arm package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (fd1 int, fd2 int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) fd1 = int(r0) fd2 = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go0000644061062106075000000007577713172163421026103 0ustar stgraberdomain admins// mksyscall.pl -netbsd -tags netbsd,amd64 syscall_bsd.go syscall_netbsd.go syscall_netbsd_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build netbsd,amd64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (fd1 int, fd2 int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) fd1 = int(r0) fd2 = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_netbsd_386.go0000644061062106075000000007622313172163421025473 0ustar stgraberdomain admins// mksyscall.pl -l32 -netbsd -tags netbsd,386 syscall_bsd.go syscall_netbsd.go syscall_netbsd_386.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build netbsd,386 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (fd1 int, fd2 int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) fd1 = int(r0) fd2 = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_sparc64.go0000644061062106075000000012727013172163421026314 0ustar stgraberdomain admins// mksyscall.pl -tags linux,sparc64 syscall_linux.go syscall_linux_sparc64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,sparc64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_s390x.go0000644061062106075000000013343213172163421025715 0ustar stgraberdomain admins// mksyscall.pl -tags linux,s390x syscall_linux.go syscall_linux_s390x.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,s390x package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go0000644061062106075000000014731213172163421026306 0ustar stgraberdomain admins// mksyscall.pl -tags linux,ppc64le syscall_linux.go syscall_linux_ppc64x.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,ppc64le package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) tt = Time_t(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_ppc64.go0000644061062106075000000014730613172163421025770 0ustar stgraberdomain admins// mksyscall.pl -tags linux,ppc64 syscall_linux.go syscall_linux_ppc64x.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,ppc64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) tt = Time_t(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_mipsle.go0000644061062106075000000014556613172163421026333 0ustar stgraberdomain admins// mksyscall.pl -l32 -arm -tags linux,mipsle syscall_linux.go syscall_linux_mipsx.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,mipsle package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall9(SYS_SYNC_FILE_RANGE, uintptr(fd), 0, uintptr(off), uintptr(off>>32), uintptr(n), uintptr(n>>32), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) tt = Time_t(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setrlimit(resource int, rlim *rlimit32) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_mips64le.go0000644061062106075000000014430713172163421026475 0ustar stgraberdomain admins// mksyscall.pl -tags linux,mips64le syscall_linux.go syscall_linux_mips64x.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,mips64le package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fstat(fd int, st *stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(st)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func lstat(path string, st *stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, st *stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_mips64.go0000644061062106075000000014430313172163421026150 0ustar stgraberdomain admins// mksyscall.pl -tags linux,mips64 syscall_linux.go syscall_linux_mips64x.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,mips64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fstat(fd int, st *stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(st)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func lstat(path string, st *stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, st *stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_mips.go0000644061062106075000000014556213172163421026006 0ustar stgraberdomain admins// mksyscall.pl -b32 -arm -tags linux,mips syscall_linux.go syscall_linux_mipsx.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,mips package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off>>32), uintptr(off), uintptr(len>>32), uintptr(len)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(int64(r0)<<32 | int64(r1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length>>32), uintptr(length), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset>>32), uintptr(offset)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset>>32), uintptr(offset)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(int64(r0)<<32 | int64(r1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall9(SYS_SYNC_FILE_RANGE, uintptr(fd), 0, uintptr(off>>32), uintptr(off), uintptr(n>>32), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length>>32), uintptr(length), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) tt = Time_t(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setrlimit(resource int, rlim *rlimit32) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_arm64.go0000644061062106075000000014110613172163421025755 0ustar stgraberdomain admins// mksyscall.pl -tags linux,arm64 syscall_linux.go syscall_linux_arm64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,arm64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_arm.go0000644061062106075000000014303413172163421025605 0ustar stgraberdomain admins// mksyscall.pl -l32 -arm -tags linux,arm syscall_linux.go syscall_linux_arm.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,arm package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN32, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID32, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID32, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID32, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID32, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN32, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID32, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID32, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID32, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID32, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID32, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID32, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setrlimit(resource int, rlim *rlimit32) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_amd64.go0000644061062106075000000014700413172163421025742 0ustar stgraberdomain admins// mksyscall.pl -tags linux,amd64 syscall_linux.go syscall_linux_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,amd64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_linux_386.go0000644061062106075000000013466313172163421025356 0ustar stgraberdomain admins// mksyscall.pl -l32 -tags linux,386 syscall_linux.go syscall_linux_386.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,386 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fchmodat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Syncfs(fd int) (err error) { _, _, e1 := Syscall(SYS_SYNCFS, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64_64, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN32, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE64, uintptr(fd), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID32, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID32, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID32, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID32, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN32, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsgid(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID32, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID32, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID32, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID32, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID32, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID32, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(off>>32), uintptr(n), uintptr(n>>32), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getrlimit(resource int, rlim *rlimit32) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setrlimit(resource int, rlim *rlimit32) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Time(t *Time_t) (tt Time_t, err error) { r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) tt = Time_t(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_freebsd_arm.go0000644061062106075000000013121413172163421026055 0ustar stgraberdomain admins// mksyscall.pl -l32 -arm -tags freebsd,arm syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build freebsd,arm package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CapEnter() (err error) { _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsGet(version int, fd int, rightsp *CapRights) (err error) { _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsLimit(fd int, rightsp *CapRights) (err error) { _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go0000644061062106075000000013066313172163421026220 0ustar stgraberdomain admins// mksyscall.pl -tags freebsd,amd64 syscall_bsd.go syscall_freebsd.go syscall_freebsd_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build freebsd,amd64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CapEnter() (err error) { _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsGet(version int, fd int, rightsp *CapRights) (err error) { _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsLimit(fd int, rightsp *CapRights) (err error) { _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_freebsd_386.go0000644061062106075000000013115213172163421025617 0ustar stgraberdomain admins// mksyscall.pl -l32 -tags freebsd,386 syscall_bsd.go syscall_freebsd.go syscall_freebsd_386.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build freebsd,386 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CapEnter() (err error) { _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsGet(version int, fd int, rightsp *CapRights) (err error) { _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func capRightsLimit(fd int, rightsp *CapRights) (err error) { _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(file) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attrname) if err != nil { return } _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(link) if err != nil { return } r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go0000644061062106075000000010252713172163421026571 0ustar stgraberdomain admins// mksyscall.pl -dragonfly -tags dragonfly,amd64 syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build dragonfly,amd64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func extpread(fd int, p []byte, flags int, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EXTPREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EXTPWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_darwin_arm64.go0000644061062106075000000011224013172163421026077 0ustar stgraberdomain admins// mksyscall.pl -tags darwin,arm64 syscall_bsd.go syscall_darwin.go syscall_darwin_arm64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build darwin,arm64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exchangedata(path1 string, path2 string, options int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path1) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(path2) if err != nil { return } _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setprivexec(flag int) (err error) { _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) { r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) sec = int64(r0) usec = int32(r1) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_darwin_arm.go0000644061062106075000000011245413172163421025734 0ustar stgraberdomain admins// mksyscall.pl -tags darwin,arm syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build darwin,arm package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exchangedata(path1 string, path2 string, options int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path1) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(path2) if err != nil { return } _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setprivexec(flag int) (err error) { _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) { r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) sec = int32(r0) usec = int32(r1) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_darwin_amd64.go0000644061062106075000000011224013172163421026061 0ustar stgraberdomain admins// mksyscall.pl -tags darwin,amd64 syscall_bsd.go syscall_darwin.go syscall_darwin_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build darwin,amd64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exchangedata(path1 string, path2 string, options int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path1) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(path2) if err != nil { return } _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setprivexec(flag int) (err error) { _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) { r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) sec = int64(r0) usec = int32(r1) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zsyscall_darwin_386.go0000644061062106075000000011246313172163421025475 0ustar stgraberdomain admins// mksyscall.pl -l32 -tags darwin,386 syscall_bsd.go syscall_darwin.go syscall_darwin_386.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build darwin,386 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) w = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exchangedata(path1 string, path2 string, options int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path1) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(path2) if err != nil { return } _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdtablesize() (size int) { r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) size = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setprivexec(flag int) (err error) { _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Undelete(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) { r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) sec = int32(r0) usec = int32(r1) if e1 != 0 { err = errnoErr(e1) } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_solaris_amd64.go0000644061062106075000000015523213172163421026123 0ustar stgraberdomain admins// mkerrors.sh -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,solaris // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_802 = 0x12 AF_APPLETALK = 0x10 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_ECMA = 0x8 AF_FILE = 0x1 AF_GOSIP = 0x16 AF_HYLINK = 0xf AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1a AF_INET_OFFLOAD = 0x1e AF_IPX = 0x17 AF_KEY = 0x1b AF_LAT = 0xe AF_LINK = 0x19 AF_LOCAL = 0x1 AF_MAX = 0x20 AF_NBS = 0x7 AF_NCA = 0x1c AF_NIT = 0x11 AF_NS = 0x6 AF_OSI = 0x13 AF_OSINET = 0x15 AF_PACKET = 0x20 AF_POLICY = 0x1d AF_PUP = 0x4 AF_ROUTE = 0x18 AF_SNA = 0xb AF_TRILL = 0x1f AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_X25 = 0x14 ARPHRD_ARCNET = 0x7 ARPHRD_ATM = 0x10 ARPHRD_AX25 = 0x3 ARPHRD_CHAOS = 0x5 ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_FC = 0x12 ARPHRD_FRAME = 0xf ARPHRD_HDLC = 0x11 ARPHRD_IB = 0x20 ARPHRD_IEEE802 = 0x6 ARPHRD_IPATM = 0x13 ARPHRD_METRICOM = 0x17 ARPHRD_TUNNEL = 0x1f B0 = 0x0 B110 = 0x3 B115200 = 0x12 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B153600 = 0x13 B1800 = 0xa B19200 = 0xe B200 = 0x6 B230400 = 0x14 B2400 = 0xb B300 = 0x7 B307200 = 0x15 B38400 = 0xf B460800 = 0x16 B4800 = 0xc B50 = 0x1 B57600 = 0x10 B600 = 0x8 B75 = 0x2 B76800 = 0x11 B921600 = 0x17 B9600 = 0xd BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = -0x3fefbd89 BIOCGDLTLIST32 = -0x3ff7bd89 BIOCGETIF = 0x4020426b BIOCGETLIF = 0x4078426b BIOCGHDRCMPLT = 0x40044274 BIOCGRTIMEOUT = 0x4010427b BIOCGRTIMEOUT32 = 0x4008427b BIOCGSEESENT = 0x40044278 BIOCGSTATS = 0x4080426f BIOCGSTATSOLD = 0x4008426f BIOCIMMEDIATE = -0x7ffbbd90 BIOCPROMISC = 0x20004269 BIOCSBLEN = -0x3ffbbd9a BIOCSDLT = -0x7ffbbd8a BIOCSETF = -0x7fefbd99 BIOCSETF32 = -0x7ff7bd99 BIOCSETIF = -0x7fdfbd94 BIOCSETLIF = -0x7f87bd94 BIOCSHDRCMPLT = -0x7ffbbd8b BIOCSRTIMEOUT = -0x7fefbd86 BIOCSRTIMEOUT32 = -0x7ff7bd86 BIOCSSEESENT = -0x7ffbbd87 BIOCSTCPF = -0x7fefbd8e BIOCSUDPF = -0x7fefbd8d BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DFLTBUFSIZE = 0x100000 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x1000000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CBAUD = 0xf CFLUSH = 0xf CIBAUD = 0xf0000 CLOCAL = 0x800 CLOCK_HIGHRES = 0x4 CLOCK_LEVEL = 0xa CLOCK_MONOTONIC = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x5 CLOCK_PROF = 0x2 CLOCK_REALTIME = 0x3 CLOCK_THREAD_CPUTIME_ID = 0x2 CLOCK_VIRTUAL = 0x1 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a CSWTCH = 0x1a DLT_AIRONET_HEADER = 0x78 DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_BACNET_MS_TP = 0xa5 DLT_CHAOS = 0x5 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_DOCSIS = 0x8f DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FDDI = 0xa DLT_FRELAY = 0x6b DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_HDLC = 0x10 DLT_HHDLC = 0x79 DLT_HIPPI = 0xf DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IPNET = 0xe2 DLT_IPOIB = 0xa2 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0xe DLT_PPP_PPPD = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAW = 0xc DLT_RAWAF_MASK = 0x2240000 DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xd DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EMPTY_SET = 0x0 EMT_CPCOVF = 0x1 EQUALITY_CHECK = 0x0 EXTA = 0xe EXTB = 0xf FD_CLOEXEC = 0x1 FD_NFDBITS = 0x40 FD_SETSIZE = 0x10000 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHALL = 0x1 FLUSHDATA = 0x0 FLUSHO = 0x2000 F_ALLOCSP = 0xa F_ALLOCSP64 = 0xa F_BADFD = 0x2e F_BLKSIZE = 0x13 F_BLOCKS = 0x12 F_CHKFL = 0x8 F_COMPAT = 0x8 F_DUP2FD = 0x9 F_DUP2FD_CLOEXEC = 0x24 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x25 F_FLOCK = 0x35 F_FLOCK64 = 0x35 F_FLOCKW = 0x36 F_FLOCKW64 = 0x36 F_FREESP = 0xb F_FREESP64 = 0xb F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0xe F_GETLK64 = 0xe F_GETOWN = 0x17 F_GETXFL = 0x2d F_HASREMOTELOCKS = 0x1a F_ISSTREAM = 0xd F_MANDDNY = 0x10 F_MDACC = 0x20 F_NODNY = 0x0 F_NPRIV = 0x10 F_OFD_GETLK = 0x2f F_OFD_GETLK64 = 0x2f F_OFD_SETLK = 0x30 F_OFD_SETLK64 = 0x30 F_OFD_SETLKW = 0x31 F_OFD_SETLKW64 = 0x31 F_PRIV = 0xf F_QUOTACTL = 0x11 F_RDACC = 0x1 F_RDDNY = 0x1 F_RDLCK = 0x1 F_REVOKE = 0x19 F_RMACC = 0x4 F_RMDNY = 0x4 F_RWACC = 0x3 F_RWDNY = 0x3 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x6 F_SETLK64 = 0x6 F_SETLK64_NBMAND = 0x2a F_SETLKW = 0x7 F_SETLKW64 = 0x7 F_SETLK_NBMAND = 0x2a F_SETOWN = 0x18 F_SHARE = 0x28 F_SHARE_NBMAND = 0x2b F_UNLCK = 0x3 F_UNLKSYS = 0x4 F_UNSHARE = 0x29 F_WRACC = 0x2 F_WRDNY = 0x2 F_WRLCK = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICRNL = 0x100 IEXTEN = 0x8000 IFF_ADDRCONF = 0x80000 IFF_ALLMULTI = 0x200 IFF_ANYCAST = 0x400000 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x7f203003b5a IFF_COS_ENABLED = 0x200000000 IFF_DEBUG = 0x4 IFF_DEPRECATED = 0x40000 IFF_DHCPRUNNING = 0x4000 IFF_DUPLICATE = 0x4000000000 IFF_FAILED = 0x10000000 IFF_FIXEDMTU = 0x1000000000 IFF_INACTIVE = 0x40000000 IFF_INTELLIGENT = 0x400 IFF_IPMP = 0x8000000000 IFF_IPMP_CANTCHANGE = 0x10000000 IFF_IPMP_INVALID = 0x1ec200080 IFF_IPV4 = 0x1000000 IFF_IPV6 = 0x2000000 IFF_L3PROTECT = 0x40000000000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x800 IFF_MULTI_BCAST = 0x1000 IFF_NOACCEPT = 0x4000000 IFF_NOARP = 0x80 IFF_NOFAILOVER = 0x8000000 IFF_NOLINKLOCAL = 0x20000000000 IFF_NOLOCAL = 0x20000 IFF_NONUD = 0x200000 IFF_NORTEXCH = 0x800000 IFF_NOTRAILERS = 0x20 IFF_NOXMIT = 0x10000 IFF_OFFLINE = 0x80000000 IFF_POINTOPOINT = 0x10 IFF_PREFERRED = 0x400000000 IFF_PRIVATE = 0x8000 IFF_PROMISC = 0x100 IFF_ROUTER = 0x100000 IFF_RUNNING = 0x40 IFF_STANDBY = 0x20000000 IFF_TEMPORARY = 0x800000000 IFF_UNNUMBERED = 0x2000 IFF_UP = 0x1 IFF_VIRTUAL = 0x2000000000 IFF_VRRP = 0x10000000000 IFF_XRESOLV = 0x100000000 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_6TO4 = 0xca IFT_AAL5 = 0x31 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ATM = 0x25 IFT_CEPT = 0x13 IFT_DS3 = 0x1e IFT_EON = 0x19 IFT_ETHER = 0x6 IFT_FDDI = 0xf IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_HDH1822 = 0x3 IFT_HIPPI = 0x2f IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IB = 0xc7 IFT_IPV4 = 0xc8 IFT_IPV6 = 0xc9 IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88026 = 0xa IFT_LAPB = 0x10 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_NSIP = 0x1b IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PPP = 0x17 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PTPSERIAL = 0x16 IFT_RS232 = 0x21 IFT_SDLC = 0x11 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_STARLAN = 0xb IFT_T1 = 0x12 IFT_ULTRA = 0x1d IFT_V35 = 0x2d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_AUTOCONF_MASK = 0xffff0000 IN_AUTOCONF_NET = 0xa9fe0000 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_CLASSE_NET = 0xffffffff IN_LOOPBACKNET = 0x7f IN_PRIVATE12_MASK = 0xfff00000 IN_PRIVATE12_NET = 0xac100000 IN_PRIVATE16_MASK = 0xffff0000 IN_PRIVATE16_NET = 0xc0a80000 IN_PRIVATE8_MASK = 0xff000000 IN_PRIVATE8_NET = 0xa000000 IPPROTO_AH = 0x33 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x4 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_HELLO = 0x3f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPV6 = 0x29 IPPROTO_MAX = 0x100 IPPROTO_ND = 0x4d IPPROTO_NONE = 0x3b IPPROTO_OSPF = 0x59 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_UDP = 0x11 IPV6_ADD_MEMBERSHIP = 0x9 IPV6_BOUND_IF = 0x41 IPV6_CHECKSUM = 0x18 IPV6_DONTFRAG = 0x21 IPV6_DROP_MEMBERSHIP = 0xa IPV6_DSTOPTS = 0xf IPV6_FLOWINFO_FLOWLABEL = 0xffff0f00 IPV6_FLOWINFO_TCLASS = 0xf00f IPV6_HOPLIMIT = 0xc IPV6_HOPOPTS = 0xe IPV6_JOIN_GROUP = 0x9 IPV6_LEAVE_GROUP = 0xa IPV6_MULTICAST_HOPS = 0x7 IPV6_MULTICAST_IF = 0x6 IPV6_MULTICAST_LOOP = 0x8 IPV6_NEXTHOP = 0xd IPV6_PAD1_OPT = 0x0 IPV6_PATHMTU = 0x25 IPV6_PKTINFO = 0xb IPV6_PREFER_SRC_CGA = 0x20 IPV6_PREFER_SRC_CGADEFAULT = 0x10 IPV6_PREFER_SRC_CGAMASK = 0x30 IPV6_PREFER_SRC_COA = 0x2 IPV6_PREFER_SRC_DEFAULT = 0x15 IPV6_PREFER_SRC_HOME = 0x1 IPV6_PREFER_SRC_MASK = 0x3f IPV6_PREFER_SRC_MIPDEFAULT = 0x1 IPV6_PREFER_SRC_MIPMASK = 0x3 IPV6_PREFER_SRC_NONCGA = 0x10 IPV6_PREFER_SRC_PUBLIC = 0x4 IPV6_PREFER_SRC_TMP = 0x8 IPV6_PREFER_SRC_TMPDEFAULT = 0x4 IPV6_PREFER_SRC_TMPMASK = 0xc IPV6_RECVDSTOPTS = 0x28 IPV6_RECVHOPLIMIT = 0x13 IPV6_RECVHOPOPTS = 0x14 IPV6_RECVPATHMTU = 0x24 IPV6_RECVPKTINFO = 0x12 IPV6_RECVRTHDR = 0x16 IPV6_RECVRTHDRDSTOPTS = 0x17 IPV6_RECVTCLASS = 0x19 IPV6_RTHDR = 0x10 IPV6_RTHDRDSTOPTS = 0x11 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SEC_OPT = 0x22 IPV6_SRC_PREFERENCES = 0x23 IPV6_TCLASS = 0x26 IPV6_UNICAST_HOPS = 0x5 IPV6_UNSPEC_SRC = 0x42 IPV6_USE_MIN_MTU = 0x20 IPV6_V6ONLY = 0x27 IP_ADD_MEMBERSHIP = 0x13 IP_ADD_SOURCE_MEMBERSHIP = 0x17 IP_BLOCK_SOURCE = 0x15 IP_BOUND_IF = 0x41 IP_BROADCAST = 0x106 IP_BROADCAST_TTL = 0x43 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DHCPINIT_IF = 0x45 IP_DONTFRAG = 0x1b IP_DONTROUTE = 0x105 IP_DROP_MEMBERSHIP = 0x14 IP_DROP_SOURCE_MEMBERSHIP = 0x18 IP_HDRINCL = 0x2 IP_MAXPACKET = 0xffff IP_MF = 0x2000 IP_MSS = 0x240 IP_MULTICAST_IF = 0x10 IP_MULTICAST_LOOP = 0x12 IP_MULTICAST_TTL = 0x11 IP_NEXTHOP = 0x19 IP_OPTIONS = 0x1 IP_PKTINFO = 0x1a IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x9 IP_RECVOPTS = 0x5 IP_RECVPKTINFO = 0x1a IP_RECVRETOPTS = 0x6 IP_RECVSLLA = 0xa IP_RECVTTL = 0xb IP_RETOPTS = 0x8 IP_REUSEADDR = 0x104 IP_SEC_OPT = 0x22 IP_TOS = 0x3 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x16 IP_UNSPEC_SRC = 0x42 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_ACCESS_DEFAULT = 0x6 MADV_ACCESS_LWP = 0x7 MADV_ACCESS_MANY = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_NORMAL = 0x0 MADV_PURGE = 0x9 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MAP_32BIT = 0x80 MAP_ALIGN = 0x200 MAP_ANON = 0x100 MAP_ANONYMOUS = 0x100 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_INITDATA = 0x800 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_TEXT = 0x400 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_CTRUNC = 0x10 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_DUPCTRL = 0x800 MSG_EOR = 0x8 MSG_MAXIOVLEN = 0x10 MSG_NOTIFICATION = 0x100 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x20 MSG_WAITALL = 0x40 MSG_XPG4_2 = 0x8000 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_OLDSYNC = 0x0 MS_SYNC = 0x4 M_FLUSH = 0x86 NAME_MAX = 0xff NEWDEV = 0x1 NL0 = 0x0 NL1 = 0x100 NLDLY = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 OLDDEV = 0x0 ONBITSMAJOR = 0x7 ONBITSMINOR = 0x8 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPENFAIL = -0x1 OPOST = 0x1 O_ACCMODE = 0x600003 O_APPEND = 0x8 O_CLOEXEC = 0x800000 O_CREAT = 0x100 O_DSYNC = 0x40 O_EXCL = 0x400 O_EXEC = 0x400000 O_LARGEFILE = 0x2000 O_NDELAY = 0x4 O_NOCTTY = 0x800 O_NOFOLLOW = 0x20000 O_NOLINKS = 0x40000 O_NONBLOCK = 0x80 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x8000 O_SEARCH = 0x200000 O_SIOCGIFCONF = -0x3ff796ec O_SIOCGLIFCONF = -0x3fef9688 O_SYNC = 0x10 O_TRUNC = 0x200 O_WRONLY = 0x1 O_XATTR = 0x4000 PARENB = 0x100 PAREXT = 0x100000 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x3 RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x9 RTAX_NETMASK = 0x2 RTAX_SRC = 0x8 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTA_NUMBITS = 0x9 RTA_SRC = 0x100 RTF_BLACKHOLE = 0x1000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INDIRECT = 0x40000 RTF_KERNEL = 0x80000 RTF_LLINFO = 0x400 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_MULTIRT = 0x10000 RTF_PRIVATE = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_REJECT = 0x8 RTF_SETSRC = 0x20000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_XRESOLVE = 0x200 RTF_ZONE = 0x100000 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_CHGADDR = 0xf RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_FREEADDR = 0x10 RTM_GET = 0x4 RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_VERSION = 0x3 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RT_AWARE = 0x1 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_RIGHTS = 0x1010 SCM_TIMESTAMP = 0x1013 SCM_UCRED = 0x1012 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIG2STR_MAX = 0x20 SIOCADDMULTI = -0x7fdf96cf SIOCADDRT = -0x7fcf8df6 SIOCATMARK = 0x40047307 SIOCDARP = -0x7fdb96e0 SIOCDELMULTI = -0x7fdf96ce SIOCDELRT = -0x7fcf8df5 SIOCDXARP = -0x7fff9658 SIOCGARP = -0x3fdb96e1 SIOCGDSTINFO = -0x3fff965c SIOCGENADDR = -0x3fdf96ab SIOCGENPSTATS = -0x3fdf96c7 SIOCGETLSGCNT = -0x3fef8deb SIOCGETNAME = 0x40107334 SIOCGETPEER = 0x40107335 SIOCGETPROP = -0x3fff8f44 SIOCGETSGCNT = -0x3feb8deb SIOCGETSYNC = -0x3fdf96d3 SIOCGETVIFCNT = -0x3feb8dec SIOCGHIWAT = 0x40047301 SIOCGIFADDR = -0x3fdf96f3 SIOCGIFBRDADDR = -0x3fdf96e9 SIOCGIFCONF = -0x3ff796a4 SIOCGIFDSTADDR = -0x3fdf96f1 SIOCGIFFLAGS = -0x3fdf96ef SIOCGIFHWADDR = -0x3fdf9647 SIOCGIFINDEX = -0x3fdf96a6 SIOCGIFMEM = -0x3fdf96ed SIOCGIFMETRIC = -0x3fdf96e5 SIOCGIFMTU = -0x3fdf96ea SIOCGIFMUXID = -0x3fdf96a8 SIOCGIFNETMASK = -0x3fdf96e7 SIOCGIFNUM = 0x40046957 SIOCGIP6ADDRPOLICY = -0x3fff965e SIOCGIPMSFILTER = -0x3ffb964c SIOCGLIFADDR = -0x3f87968f SIOCGLIFBINDING = -0x3f879666 SIOCGLIFBRDADDR = -0x3f879685 SIOCGLIFCONF = -0x3fef965b SIOCGLIFDADSTATE = -0x3f879642 SIOCGLIFDSTADDR = -0x3f87968d SIOCGLIFFLAGS = -0x3f87968b SIOCGLIFGROUPINFO = -0x3f4b9663 SIOCGLIFGROUPNAME = -0x3f879664 SIOCGLIFHWADDR = -0x3f879640 SIOCGLIFINDEX = -0x3f87967b SIOCGLIFLNKINFO = -0x3f879674 SIOCGLIFMETRIC = -0x3f879681 SIOCGLIFMTU = -0x3f879686 SIOCGLIFMUXID = -0x3f87967d SIOCGLIFNETMASK = -0x3f879683 SIOCGLIFNUM = -0x3ff3967e SIOCGLIFSRCOF = -0x3fef964f SIOCGLIFSUBNET = -0x3f879676 SIOCGLIFTOKEN = -0x3f879678 SIOCGLIFUSESRC = -0x3f879651 SIOCGLIFZONE = -0x3f879656 SIOCGLOWAT = 0x40047303 SIOCGMSFILTER = -0x3ffb964e SIOCGPGRP = 0x40047309 SIOCGSTAMP = -0x3fef9646 SIOCGXARP = -0x3fff9659 SIOCIFDETACH = -0x7fdf96c8 SIOCILB = -0x3ffb9645 SIOCLIFADDIF = -0x3f879691 SIOCLIFDELND = -0x7f879673 SIOCLIFGETND = -0x3f879672 SIOCLIFREMOVEIF = -0x7f879692 SIOCLIFSETND = -0x7f879671 SIOCLOWER = -0x7fdf96d7 SIOCSARP = -0x7fdb96e2 SIOCSCTPGOPT = -0x3fef9653 SIOCSCTPPEELOFF = -0x3ffb9652 SIOCSCTPSOPT = -0x7fef9654 SIOCSENABLESDP = -0x3ffb9649 SIOCSETPROP = -0x7ffb8f43 SIOCSETSYNC = -0x7fdf96d4 SIOCSHIWAT = -0x7ffb8d00 SIOCSIFADDR = -0x7fdf96f4 SIOCSIFBRDADDR = -0x7fdf96e8 SIOCSIFDSTADDR = -0x7fdf96f2 SIOCSIFFLAGS = -0x7fdf96f0 SIOCSIFINDEX = -0x7fdf96a5 SIOCSIFMEM = -0x7fdf96ee SIOCSIFMETRIC = -0x7fdf96e4 SIOCSIFMTU = -0x7fdf96eb SIOCSIFMUXID = -0x7fdf96a7 SIOCSIFNAME = -0x7fdf96b7 SIOCSIFNETMASK = -0x7fdf96e6 SIOCSIP6ADDRPOLICY = -0x7fff965d SIOCSIPMSFILTER = -0x7ffb964b SIOCSLGETREQ = -0x3fdf96b9 SIOCSLIFADDR = -0x7f879690 SIOCSLIFBRDADDR = -0x7f879684 SIOCSLIFDSTADDR = -0x7f87968e SIOCSLIFFLAGS = -0x7f87968c SIOCSLIFGROUPNAME = -0x7f879665 SIOCSLIFINDEX = -0x7f87967a SIOCSLIFLNKINFO = -0x7f879675 SIOCSLIFMETRIC = -0x7f879680 SIOCSLIFMTU = -0x7f879687 SIOCSLIFMUXID = -0x7f87967c SIOCSLIFNAME = -0x3f87967f SIOCSLIFNETMASK = -0x7f879682 SIOCSLIFPREFIX = -0x3f879641 SIOCSLIFSUBNET = -0x7f879677 SIOCSLIFTOKEN = -0x7f879679 SIOCSLIFUSESRC = -0x7f879650 SIOCSLIFZONE = -0x7f879655 SIOCSLOWAT = -0x7ffb8cfe SIOCSLSTAT = -0x7fdf96b8 SIOCSMSFILTER = -0x7ffb964d SIOCSPGRP = -0x7ffb8cf8 SIOCSPROMISC = -0x7ffb96d0 SIOCSQPTR = -0x3ffb9648 SIOCSSDSTATS = -0x3fdf96d2 SIOCSSESTATS = -0x3fdf96d1 SIOCSXARP = -0x7fff965a SIOCTMYADDR = -0x3ff79670 SIOCTMYSITE = -0x3ff7966e SIOCTONLINK = -0x3ff7966f SIOCUPPER = -0x7fdf96d8 SIOCX25RCV = -0x3fdf96c4 SIOCX25TBL = -0x3fdf96c3 SIOCX25XMT = -0x3fdf96c5 SIOCXPROTO = 0x20007337 SOCK_CLOEXEC = 0x80000 SOCK_DGRAM = 0x1 SOCK_NDELAY = 0x200000 SOCK_NONBLOCK = 0x100000 SOCK_RAW = 0x4 SOCK_RDM = 0x5 SOCK_SEQPACKET = 0x6 SOCK_STREAM = 0x2 SOCK_TYPE_MASK = 0xffff SOL_FILTER = 0xfffc SOL_PACKET = 0xfffd SOL_ROUTE = 0xfffe SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ALL = 0x3f SO_ALLZONES = 0x1014 SO_ANON_MLP = 0x100a SO_ATTACH_FILTER = 0x40000001 SO_BAND = 0x4000 SO_BROADCAST = 0x20 SO_COPYOPT = 0x80000 SO_DEBUG = 0x1 SO_DELIM = 0x8000 SO_DETACH_FILTER = 0x40000002 SO_DGRAM_ERRIND = 0x200 SO_DOMAIN = 0x100c SO_DONTLINGER = -0x81 SO_DONTROUTE = 0x10 SO_ERROPT = 0x40000 SO_ERROR = 0x1007 SO_EXCLBIND = 0x1015 SO_HIWAT = 0x10 SO_ISNTTY = 0x800 SO_ISTTY = 0x400 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_LOWAT = 0x20 SO_MAC_EXEMPT = 0x100b SO_MAC_IMPLICIT = 0x1016 SO_MAXBLK = 0x100000 SO_MAXPSZ = 0x8 SO_MINPSZ = 0x4 SO_MREADOFF = 0x80 SO_MREADON = 0x40 SO_NDELOFF = 0x200 SO_NDELON = 0x100 SO_NODELIM = 0x10000 SO_OOBINLINE = 0x100 SO_PROTOTYPE = 0x1009 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVPSH = 0x100d SO_RCVTIMEO = 0x1006 SO_READOPT = 0x1 SO_RECVUCRED = 0x400 SO_REUSEADDR = 0x4 SO_SECATTR = 0x1011 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_STRHOLD = 0x20000 SO_TAIL = 0x200000 SO_TIMESTAMP = 0x1013 SO_TONSTOP = 0x2000 SO_TOSTOP = 0x1000 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_VRRP = 0x1017 SO_WROFF = 0x2 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_ABORT_THRESHOLD = 0x11 TCP_ANONPRIVBIND = 0x20 TCP_CONN_ABORT_THRESHOLD = 0x13 TCP_CONN_NOTIFY_THRESHOLD = 0x12 TCP_CORK = 0x18 TCP_EXCLBIND = 0x21 TCP_INIT_CWND = 0x15 TCP_KEEPALIVE = 0x8 TCP_KEEPALIVE_ABORT_THRESHOLD = 0x17 TCP_KEEPALIVE_THRESHOLD = 0x16 TCP_KEEPCNT = 0x23 TCP_KEEPIDLE = 0x22 TCP_KEEPINTVL = 0x24 TCP_LINGER2 = 0x1c TCP_MAXSEG = 0x2 TCP_MSS = 0x218 TCP_NODELAY = 0x1 TCP_NOTIFY_THRESHOLD = 0x10 TCP_RECVDSTADDR = 0x14 TCP_RTO_INITIAL = 0x19 TCP_RTO_MAX = 0x1b TCP_RTO_MIN = 0x1a TCSAFLUSH = 0x5410 TCSBRK = 0x5405 TCSETA = 0x5402 TCSETAF = 0x5404 TCSETAW = 0x5403 TCSETS = 0x540e TCSETSF = 0x5410 TCSETSW = 0x540f TCXONC = 0x5406 TIOC = 0x5400 TIOCCBRK = 0x747a TIOCCDTR = 0x7478 TIOCCILOOP = 0x746c TIOCEXCL = 0x740d TIOCFLUSH = 0x7410 TIOCGETC = 0x7412 TIOCGETD = 0x7400 TIOCGETP = 0x7408 TIOCGLTC = 0x7474 TIOCGPGRP = 0x7414 TIOCGPPS = 0x547d TIOCGPPSEV = 0x547f TIOCGSID = 0x7416 TIOCGSOFTCAR = 0x5469 TIOCGWINSZ = 0x5468 TIOCHPCL = 0x7402 TIOCKBOF = 0x5409 TIOCKBON = 0x5408 TIOCLBIC = 0x747e TIOCLBIS = 0x747f TIOCLGET = 0x747c TIOCLSET = 0x747d TIOCMBIC = 0x741c TIOCMBIS = 0x741b TIOCMGET = 0x741d TIOCMSET = 0x741a TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x7471 TIOCNXCL = 0x740e TIOCOUTQ = 0x7473 TIOCREMOTE = 0x741e TIOCSBRK = 0x747b TIOCSCTTY = 0x7484 TIOCSDTR = 0x7479 TIOCSETC = 0x7411 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 TIOCSIGNAL = 0x741f TIOCSILOOP = 0x746d TIOCSLTC = 0x7475 TIOCSPGRP = 0x7415 TIOCSPPS = 0x547e TIOCSSOFTCAR = 0x546a TIOCSTART = 0x746e TIOCSTI = 0x7417 TIOCSTOP = 0x746f TIOCSWINSZ = 0x5467 TOSTOP = 0x100 VCEOF = 0x8 VCEOL = 0x9 VDISCARD = 0xd VDSUSP = 0xb VEOF = 0x4 VEOL = 0x5 VEOL2 = 0x6 VERASE = 0x2 VERASE2 = 0x11 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x4 VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTATUS = 0x10 VSTOP = 0x9 VSUSP = 0xa VSWTCH = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WCONTFLG = 0xffff WCONTINUED = 0x8 WCOREFLG = 0x80 WEXITED = 0x1 WNOHANG = 0x40 WNOWAIT = 0x80 WOPTMASK = 0xcf WRAP = 0x20000 WSIGMASK = 0x7f WSTOPFLG = 0x7f WSTOPPED = 0x4 WTRAPPED = 0x2 WUNTRACED = 0x4 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x7d) EADDRNOTAVAIL = syscall.Errno(0x7e) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x7c) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x95) EBADE = syscall.Errno(0x32) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x51) EBADMSG = syscall.Errno(0x4d) EBADR = syscall.Errno(0x33) EBADRQC = syscall.Errno(0x36) EBADSLT = syscall.Errno(0x37) EBFONT = syscall.Errno(0x39) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x2f) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x25) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x82) ECONNREFUSED = syscall.Errno(0x92) ECONNRESET = syscall.Errno(0x83) EDEADLK = syscall.Errno(0x2d) EDEADLOCK = syscall.Errno(0x38) EDESTADDRREQ = syscall.Errno(0x60) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x31) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EIDRM = syscall.Errno(0x24) EILSEQ = syscall.Errno(0x58) EINPROGRESS = syscall.Errno(0x96) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x85) EISDIR = syscall.Errno(0x15) EL2HLT = syscall.Errno(0x2c) EL2NSYNC = syscall.Errno(0x26) EL3HLT = syscall.Errno(0x27) EL3RST = syscall.Errno(0x28) ELIBACC = syscall.Errno(0x53) ELIBBAD = syscall.Errno(0x54) ELIBEXEC = syscall.Errno(0x57) ELIBMAX = syscall.Errno(0x56) ELIBSCN = syscall.Errno(0x55) ELNRNG = syscall.Errno(0x29) ELOCKUNMAPPED = syscall.Errno(0x48) ELOOP = syscall.Errno(0x5a) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x61) EMULTIHOP = syscall.Errno(0x4a) ENAMETOOLONG = syscall.Errno(0x4e) ENETDOWN = syscall.Errno(0x7f) ENETRESET = syscall.Errno(0x81) ENETUNREACH = syscall.Errno(0x80) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x35) ENOBUFS = syscall.Errno(0x84) ENOCSI = syscall.Errno(0x2b) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x2e) ENOLINK = syscall.Errno(0x43) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x23) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x63) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x59) ENOTACTIVE = syscall.Errno(0x49) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x86) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x5d) ENOTRECOVERABLE = syscall.Errno(0x3b) ENOTSOCK = syscall.Errno(0x5f) ENOTSUP = syscall.Errno(0x30) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x50) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x7a) EOVERFLOW = syscall.Errno(0x4f) EOWNERDEAD = syscall.Errno(0x3a) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x7b) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x78) EPROTOTYPE = syscall.Errno(0x62) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x52) EREMOTE = syscall.Errno(0x42) ERESTART = syscall.Errno(0x5b) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x8f) ESOCKTNOSUPPORT = syscall.Errno(0x79) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x97) ESTRPIPE = syscall.Errno(0x5c) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x91) ETOOMANYREFS = syscall.Errno(0x90) ETXTBSY = syscall.Errno(0x1a) EUNATCH = syscall.Errno(0x2a) EUSERS = syscall.Errno(0x5e) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x34) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCANCEL = syscall.Signal(0x24) SIGCHLD = syscall.Signal(0x12) SIGCLD = syscall.Signal(0x12) SIGCONT = syscall.Signal(0x19) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGFREEZE = syscall.Signal(0x22) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x29) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x16) SIGIOT = syscall.Signal(0x6) SIGJVM1 = syscall.Signal(0x27) SIGJVM2 = syscall.Signal(0x28) SIGKILL = syscall.Signal(0x9) SIGLOST = syscall.Signal(0x25) SIGLWP = syscall.Signal(0x21) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x16) SIGPROF = syscall.Signal(0x1d) SIGPWR = syscall.Signal(0x13) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x17) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHAW = syscall.Signal(0x23) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x18) SIGTTIN = syscall.Signal(0x1a) SIGTTOU = syscall.Signal(0x1b) SIGURG = syscall.Signal(0x15) SIGUSR1 = syscall.Signal(0x10) SIGUSR2 = syscall.Signal(0x11) SIGVTALRM = syscall.Signal(0x1c) SIGWAITING = syscall.Signal(0x20) SIGWINCH = syscall.Signal(0x14) SIGXCPU = syscall.Signal(0x1e) SIGXFSZ = syscall.Signal(0x1f) SIGXRES = syscall.Signal(0x26) ) // Error table var errors = [...]string{ 1: "not owner", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "I/O error", 6: "no such device or address", 7: "arg list too long", 8: "exec format error", 9: "bad file number", 10: "no child processes", 11: "resource temporarily unavailable", 12: "not enough space", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "file table overflow", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "argument out of domain", 34: "result too large", 35: "no message of desired type", 36: "identifier removed", 37: "channel number out of range", 38: "level 2 not synchronized", 39: "level 3 halted", 40: "level 3 reset", 41: "link number out of range", 42: "protocol driver not attached", 43: "no CSI structure available", 44: "level 2 halted", 45: "deadlock situation detected/avoided", 46: "no record locks available", 47: "operation canceled", 48: "operation not supported", 49: "disc quota exceeded", 50: "bad exchange descriptor", 51: "bad request descriptor", 52: "message tables full", 53: "anode table overflow", 54: "bad request code", 55: "invalid slot", 56: "file locking deadlock", 57: "bad font file format", 58: "owner of the lock died", 59: "lock is not recoverable", 60: "not a stream device", 61: "no data available", 62: "timer expired", 63: "out of stream resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "locked lock was unmapped ", 73: "facility is not active", 74: "multihop attempted", 77: "not a data message", 78: "file name too long", 79: "value too large for defined data type", 80: "name not unique on network", 81: "file descriptor in bad state", 82: "remote address changed", 83: "can not access a needed shared library", 84: "accessing a corrupted shared library", 85: ".lib section in a.out corrupted", 86: "attempting to link in more shared libraries than system limit", 87: "can not exec a shared library directly", 88: "illegal byte sequence", 89: "operation not applicable", 90: "number of symbolic links encountered during path name traversal exceeds MAXSYMLINKS", 91: "error 91", 92: "error 92", 93: "directory not empty", 94: "too many users", 95: "socket operation on non-socket", 96: "destination address required", 97: "message too long", 98: "protocol wrong type for socket", 99: "option not supported by protocol", 120: "protocol not supported", 121: "socket type not supported", 122: "operation not supported on transport endpoint", 123: "protocol family not supported", 124: "address family not supported by protocol family", 125: "address already in use", 126: "cannot assign requested address", 127: "network is down", 128: "network is unreachable", 129: "network dropped connection because of reset", 130: "software caused connection abort", 131: "connection reset by peer", 132: "no buffer space available", 133: "transport endpoint is already connected", 134: "transport endpoint is not connected", 143: "cannot send after socket shutdown", 144: "too many references: cannot splice", 145: "connection timed out", 146: "connection refused", 147: "host is down", 148: "no route to host", 149: "operation already in progress", 150: "operation now in progress", 151: "stale NFS file handle", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal Instruction", 5: "trace/Breakpoint Trap", 6: "abort", 7: "emulation Trap", 8: "arithmetic Exception", 9: "killed", 10: "bus Error", 11: "segmentation Fault", 12: "bad System Call", 13: "broken Pipe", 14: "alarm Clock", 15: "terminated", 16: "user Signal 1", 17: "user Signal 2", 18: "child Status Changed", 19: "power-Fail/Restart", 20: "window Size Change", 21: "urgent Socket Condition", 22: "pollable Event", 23: "stopped (signal)", 24: "stopped (user)", 25: "continued", 26: "stopped (tty input)", 27: "stopped (tty output)", 28: "virtual Timer Expired", 29: "profiling Timer Expired", 30: "cpu Limit Exceeded", 31: "file Size Limit Exceeded", 32: "no runnable lwp", 33: "inter-lwp signal", 34: "checkpoint Freeze", 35: "checkpoint Thaw", 36: "thread Cancellation", 37: "resource Lost", 38: "resource Control Exceeded", 39: "reserved for JVM 1", 40: "reserved for JVM 2", 41: "information Request", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_openbsd_arm.go0000644061062106075000000017673213172163421025755 0ustar stgraberdomain admins// mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go // +build arm,openbsd package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_BLUETOOTH = 0x20 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_ENCAP = 0x1c AF_HYLINK = 0xf AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_KEY = 0x1e AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x24 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x1d AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRFILT = 0x4004427c BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc008427b BIOCGETIF = 0x4020426b BIOCGFILDROP = 0x40044278 BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044273 BIOCGRTIMEOUT = 0x400c426e BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x20004276 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDIRFILT = 0x8004427d BIOCSDLT = 0x8004427a BIOCSETF = 0x80084267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x80084277 BIOCSFILDROP = 0x80044279 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044272 BIOCSRTIMEOUT = 0x800c426d BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIRECTION_IN = 0x1 BPF_DIRECTION_OUT = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x200000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CREAD = 0x800 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0xff CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e DLT_ARCNET = 0x7 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0xd DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_LOOP = 0xc DLT_MPLS = 0xdb DLT_NULL = 0x0 DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xe DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMT_TAGOVF = 0x1 EMUL_ENABLED = 0x1 EMUL_NATIVE = 0x2 ENDRUNDISC = 0x9 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_AOE = 0x88a2 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LLDP = 0x88cc ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_QINQ = 0x88a8 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOW = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_ALIGN = 0x2 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_DIX_LEN = 0x600 ETHER_MAX_LEN = 0x5ee ETHER_MIN_LEN = 0x40 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = -0x3 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x7 EVFILT_TIMER = -0x7 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xa F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFA_ROUTE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8e52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BLUETOOTH = 0xf8 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf7 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DUMMY = 0xf1 IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf3 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFLOW = 0xf9 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf2 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_HOST = 0x1 IN_RFC3021_NET = 0xfffffffe IN_RFC3021_NSHIFT = 0x1f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DIVERT = 0x102 IPPROTO_DIVERT_INIT = 0x2 IPPROTO_DIVERT_RESP = 0x1 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x103 IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPV6_AUTH_LEVEL = 0x35 IPV6_AUTOFLOWLABEL = 0x3b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_ESP_NETWORK_LEVEL = 0x37 IPV6_ESP_TRANS_LEVEL = 0x36 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPCOMP_LEVEL = 0x3c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_OPTIONS = 0x1 IPV6_PATHMTU = 0x2c IPV6_PIPEX = 0x3f IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVDSTPORT = 0x40 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTABLE = 0x1021 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_AUTH_LEVEL = 0x14 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DIVERTFL = 0x1022 IP_DROP_MEMBERSHIP = 0xd IP_ESP_NETWORK_LEVEL = 0x16 IP_ESP_TRANS_LEVEL = 0x15 IP_HDRINCL = 0x2 IP_IPCOMP_LEVEL = 0x1d IP_IPSECFLOWINFO = 0x24 IP_IPSEC_LOCAL_AUTH = 0x1b IP_IPSEC_LOCAL_CRED = 0x19 IP_IPSEC_LOCAL_ID = 0x17 IP_IPSEC_REMOTE_AUTH = 0x1c IP_IPSEC_REMOTE_CRED = 0x1a IP_IPSEC_REMOTE_ID = 0x18 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0xfff IP_MF = 0x2000 IP_MINTTL = 0x20 IP_MIN_MEMBERSHIPS = 0xf IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PIPEX = 0x22 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVDSTPORT = 0x21 IP_RECVIF = 0x1e IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRTABLE = 0x23 IP_RECVTTL = 0x1f IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RTABLE = 0x1021 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_FLAGMASK = 0x3ff7 MAP_HASSEMAPHORE = 0x0 MAP_INHERIT = 0x0 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_INHERIT_ZERO = 0x3 MAP_NOEXTEND = 0x0 MAP_NORESERVE = 0x0 MAP_PRIVATE = 0x2 MAP_RENAME = 0x0 MAP_SHARED = 0x1 MAP_TRYFIXED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_BCAST = 0x100 MSG_CMSG_CLOEXEC = 0x800 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_MCAST = 0x200 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x4 MS_SYNC = 0x2 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_MAXID = 0x6 NET_RT_STATS = 0x4 NET_RT_TABLE = 0x5 NOFLSH = 0x80000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EOF = 0x2 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRUNCATE = 0x80 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x80 ONOCR = 0x40 ONOEOT = 0x8 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x10000 O_CREAT = 0x200 O_DIRECTORY = 0x20000 O_DSYNC = 0x80 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x80 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PF_FLUSH = 0x1 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_LABEL = 0xa RTAX_MAX = 0xb RTAX_NETMASK = 0x2 RTAX_SRC = 0x8 RTAX_SRCMASK = 0x9 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_LABEL = 0x400 RTA_NETMASK = 0x4 RTA_SRC = 0x100 RTA_SRCMASK = 0x200 RTF_ANNOUNCE = 0x4000 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CLONED = 0x10000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FMASK = 0x70f808 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_MPATH = 0x40000 RTF_MPLS = 0x100000 RTF_PERMANENT_ARP = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x2000 RTF_REJECT = 0x8 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_USETRAILERS = 0x8000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DESYNC = 0x10 RTM_GET = 0x4 RTM_IFANNOUNCE = 0xf RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MAXSIZE = 0x800 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RT_TABLEID_MAX = 0xff RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCALIFADDR = 0x8218691c SIOCATMARK = 0x40047307 SIOCBRDGADD = 0x8054693c SIOCBRDGADDS = 0x80546941 SIOCBRDGARL = 0x806e694d SIOCBRDGDADDR = 0x81286947 SIOCBRDGDEL = 0x8054693d SIOCBRDGDELS = 0x80546942 SIOCBRDGFLUSH = 0x80546948 SIOCBRDGFRL = 0x806e694e SIOCBRDGGCACHE = 0xc0146941 SIOCBRDGGFD = 0xc0146952 SIOCBRDGGHT = 0xc0146951 SIOCBRDGGIFFLGS = 0xc054693e SIOCBRDGGMA = 0xc0146953 SIOCBRDGGPARAM = 0xc03c6958 SIOCBRDGGPRI = 0xc0146950 SIOCBRDGGRL = 0xc028694f SIOCBRDGGSIFS = 0xc054693c SIOCBRDGGTO = 0xc0146946 SIOCBRDGIFS = 0xc0546942 SIOCBRDGRTS = 0xc0186943 SIOCBRDGSADDR = 0xc1286944 SIOCBRDGSCACHE = 0x80146940 SIOCBRDGSFD = 0x80146952 SIOCBRDGSHT = 0x80146951 SIOCBRDGSIFCOST = 0x80546955 SIOCBRDGSIFFLGS = 0x8054693f SIOCBRDGSIFPRIO = 0x80546954 SIOCBRDGSMA = 0x80146953 SIOCBRDGSPRI = 0x80146950 SIOCBRDGSPROTO = 0x8014695a SIOCBRDGSTO = 0x80146945 SIOCBRDGSTXHC = 0x80146959 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8218691e SIOCGETKALIVE = 0xc01869a4 SIOCGETLABEL = 0x8020699a SIOCGETPFLOW = 0xc02069fe SIOCGETPFSYNC = 0xc02069f8 SIOCGETSGCNT = 0xc0147534 SIOCGETVIFCNT = 0xc0147533 SIOCGETVLAN = 0xc0206990 SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCONF = 0xc0086924 SIOCGIFDATA = 0xc020691b SIOCGIFDESCR = 0xc0206981 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGATTR = 0xc024698b SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc024698a SIOCGIFGROUP = 0xc0246988 SIOCGIFHARDMTU = 0xc02069a5 SIOCGIFMEDIA = 0xc0286936 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc020697e SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPRIORITY = 0xc020699c SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFRDOMAIN = 0xc02069a0 SIOCGIFRTLABEL = 0xc0206983 SIOCGIFRXR = 0x802069aa SIOCGIFTIMESLOT = 0xc0206986 SIOCGIFXFLAGS = 0xc020699e SIOCGLIFADDR = 0xc218691d SIOCGLIFPHYADDR = 0xc218694b SIOCGLIFPHYRTABLE = 0xc02069a2 SIOCGLIFPHYTTL = 0xc02069a9 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGSPPPPARAMS = 0xc0206994 SIOCGVH = 0xc02069f6 SIOCGVNETID = 0xc02069a7 SIOCIFCREATE = 0x8020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc00c6978 SIOCSETKALIVE = 0x801869a3 SIOCSETLABEL = 0x80206999 SIOCSETPFLOW = 0x802069fd SIOCSETPFSYNC = 0x802069f7 SIOCSETVLAN = 0x8020698f SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBRDADDR = 0x80206913 SIOCSIFDESCR = 0x80206980 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGATTR = 0x8024698c SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020691f SIOCSIFMEDIA = 0xc0206935 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x8020697f SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPRIORITY = 0x8020699b SIOCSIFRDOMAIN = 0x8020699f SIOCSIFRTLABEL = 0x80206982 SIOCSIFTIMESLOT = 0x80206985 SIOCSIFXFLAGS = 0x8020699d SIOCSLIFPHYADDR = 0x8218694a SIOCSLIFPHYRTABLE = 0x802069a1 SIOCSLIFPHYTTL = 0x802069a8 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSSPPPPARAMS = 0x80206993 SIOCSVH = 0xc02069f5 SIOCSVNETID = 0x802069a6 SOCK_CLOEXEC = 0x8000 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x4000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BINDANY = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NETPROC = 0x1020 SO_OOBINLINE = 0x100 SO_PEERCRED = 0x1022 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RTABLE = 0x1021 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_SPLICE = 0x1023 SO_TIMESTAMP = 0x800 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x3 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x4 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOPUSH = 0x10 TCP_NSTATES = 0xb TCP_SACK_ENABLE = 0x8 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_PPS = 0x10 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGPGRP = 0x40047477 TIOCGSID = 0x40047463 TIOCGTSTAMP = 0x400c745b TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMODG = 0x4004746a TIOCMODS = 0x8004746d TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSFLAGS = 0x8004745c TIOCSIG = 0x8004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x80047465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSTSTAMP = 0x8008745a TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALTSIG = 0x4 WCONTINUED = 0x8 WCOREFLAG = 0x80 WNOHANG = 0x1 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x58) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x59) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EIPSEC = syscall.Errno(0x52) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x5b) ELOOP = syscall.Errno(0x3e) EMEDIUMTYPE = syscall.Errno(0x56) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x53) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOMEDIUM = syscall.Errno(0x55) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5a) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x5b) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x57) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "connection timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "IPsec processing failure", 83: "attribute not found", 84: "illegal byte sequence", 85: "no medium found", 86: "wrong medium type", 87: "value too large to be stored in data type", 88: "operation canceled", 89: "identifier removed", 90: "no message of desired type", 91: "not supported", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "stopped (signal)", 18: "stopped", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "thread AST", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_openbsd_amd64.go0000644061062106075000000017654213172163421026110 0ustar stgraberdomain admins// mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,openbsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_BLUETOOTH = 0x20 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_ENCAP = 0x1c AF_HYLINK = 0xf AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_KEY = 0x1e AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x24 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x1d AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRFILT = 0x4004427c BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc010427b BIOCGETIF = 0x4020426b BIOCGFILDROP = 0x40044278 BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044273 BIOCGRTIMEOUT = 0x4010426e BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x20004276 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDIRFILT = 0x8004427d BIOCSDLT = 0x8004427a BIOCSETF = 0x80104267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x80104277 BIOCSFILDROP = 0x80044279 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044272 BIOCSRTIMEOUT = 0x8010426d BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIRECTION_IN = 0x1 BPF_DIRECTION_OUT = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x200000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CREAD = 0x800 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0xff CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e DLT_ARCNET = 0x7 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0xd DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_LOOP = 0xc DLT_MPLS = 0xdb DLT_NULL = 0x0 DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xe DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMT_TAGOVF = 0x1 EMUL_ENABLED = 0x1 EMUL_NATIVE = 0x2 ENDRUNDISC = 0x9 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_AOE = 0x88a2 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LLDP = 0x88cc ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_QINQ = 0x88a8 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOW = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_ALIGN = 0x2 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_DIX_LEN = 0x600 ETHER_MAX_LEN = 0x5ee ETHER_MIN_LEN = 0x40 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = -0x3 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x7 EVFILT_TIMER = -0x7 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xa F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 F_OK = 0x0 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFA_ROUTE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8e52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BLUETOOTH = 0xf8 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf7 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DUMMY = 0xf1 IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf3 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFLOW = 0xf9 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf2 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_HOST = 0x1 IN_RFC3021_NET = 0xfffffffe IN_RFC3021_NSHIFT = 0x1f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DIVERT = 0x102 IPPROTO_DIVERT_INIT = 0x2 IPPROTO_DIVERT_RESP = 0x1 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x103 IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPV6_AUTH_LEVEL = 0x35 IPV6_AUTOFLOWLABEL = 0x3b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_ESP_NETWORK_LEVEL = 0x37 IPV6_ESP_TRANS_LEVEL = 0x36 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPCOMP_LEVEL = 0x3c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_OPTIONS = 0x1 IPV6_PATHMTU = 0x2c IPV6_PIPEX = 0x3f IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVDSTPORT = 0x40 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTABLE = 0x1021 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_AUTH_LEVEL = 0x14 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DIVERTFL = 0x1022 IP_DROP_MEMBERSHIP = 0xd IP_ESP_NETWORK_LEVEL = 0x16 IP_ESP_TRANS_LEVEL = 0x15 IP_HDRINCL = 0x2 IP_IPCOMP_LEVEL = 0x1d IP_IPSECFLOWINFO = 0x24 IP_IPSEC_LOCAL_AUTH = 0x1b IP_IPSEC_LOCAL_CRED = 0x19 IP_IPSEC_LOCAL_ID = 0x17 IP_IPSEC_REMOTE_AUTH = 0x1c IP_IPSEC_REMOTE_CRED = 0x1a IP_IPSEC_REMOTE_ID = 0x18 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0xfff IP_MF = 0x2000 IP_MINTTL = 0x20 IP_MIN_MEMBERSHIPS = 0xf IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PIPEX = 0x22 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVDSTPORT = 0x21 IP_RECVIF = 0x1e IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRTABLE = 0x23 IP_RECVTTL = 0x1f IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RTABLE = 0x1021 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 MAP_COPY = 0x4 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_FLAGMASK = 0x1ff7 MAP_HASSEMAPHORE = 0x200 MAP_INHERIT = 0x80 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_DONATE_COPY = 0x3 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_TRYFIXED = 0x400 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_BCAST = 0x100 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_MCAST = 0x200 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x4 MS_SYNC = 0x2 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_MAXID = 0x6 NET_RT_STATS = 0x4 NET_RT_TABLE = 0x5 NOFLSH = 0x80000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EOF = 0x2 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRUNCATE = 0x80 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x80 ONOCR = 0x40 ONOEOT = 0x8 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x10000 O_CREAT = 0x200 O_DIRECTORY = 0x20000 O_DSYNC = 0x80 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x80 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PF_FLUSH = 0x1 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_LABEL = 0xa RTAX_MAX = 0xb RTAX_NETMASK = 0x2 RTAX_SRC = 0x8 RTAX_SRCMASK = 0x9 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_LABEL = 0x400 RTA_NETMASK = 0x4 RTA_SRC = 0x100 RTA_SRCMASK = 0x200 RTF_ANNOUNCE = 0x4000 RTF_BLACKHOLE = 0x1000 RTF_CLONED = 0x10000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FMASK = 0x10f808 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_MPATH = 0x40000 RTF_MPLS = 0x100000 RTF_PERMANENT_ARP = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x2000 RTF_REJECT = 0x8 RTF_SOURCE = 0x20000 RTF_STATIC = 0x800 RTF_TUNNEL = 0x100000 RTF_UP = 0x1 RTF_USETRAILERS = 0x8000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DESYNC = 0x10 RTM_GET = 0x4 RTM_IFANNOUNCE = 0xf RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MAXSIZE = 0x800 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RT_TABLEID_MAX = 0xff RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80286987 SIOCALIFADDR = 0x8218691c SIOCATMARK = 0x40047307 SIOCBRDGADD = 0x8058693c SIOCBRDGADDS = 0x80586941 SIOCBRDGARL = 0x806e694d SIOCBRDGDADDR = 0x81286947 SIOCBRDGDEL = 0x8058693d SIOCBRDGDELS = 0x80586942 SIOCBRDGFLUSH = 0x80586948 SIOCBRDGFRL = 0x806e694e SIOCBRDGGCACHE = 0xc0146941 SIOCBRDGGFD = 0xc0146952 SIOCBRDGGHT = 0xc0146951 SIOCBRDGGIFFLGS = 0xc058693e SIOCBRDGGMA = 0xc0146953 SIOCBRDGGPARAM = 0xc0406958 SIOCBRDGGPRI = 0xc0146950 SIOCBRDGGRL = 0xc030694f SIOCBRDGGSIFS = 0xc058693c SIOCBRDGGTO = 0xc0146946 SIOCBRDGIFS = 0xc0586942 SIOCBRDGRTS = 0xc0206943 SIOCBRDGSADDR = 0xc1286944 SIOCBRDGSCACHE = 0x80146940 SIOCBRDGSFD = 0x80146952 SIOCBRDGSHT = 0x80146951 SIOCBRDGSIFCOST = 0x80586955 SIOCBRDGSIFFLGS = 0x8058693f SIOCBRDGSIFPRIO = 0x80586954 SIOCBRDGSMA = 0x80146953 SIOCBRDGSPRI = 0x80146950 SIOCBRDGSPROTO = 0x8014695a SIOCBRDGSTO = 0x80146945 SIOCBRDGSTXHC = 0x80146959 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80286989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8218691e SIOCGETKALIVE = 0xc01869a4 SIOCGETLABEL = 0x8020699a SIOCGETPFLOW = 0xc02069fe SIOCGETPFSYNC = 0xc02069f8 SIOCGETSGCNT = 0xc0207534 SIOCGETVIFCNT = 0xc0287533 SIOCGETVLAN = 0xc0206990 SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCONF = 0xc0106924 SIOCGIFDATA = 0xc020691b SIOCGIFDESCR = 0xc0206981 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGATTR = 0xc028698b SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc028698a SIOCGIFGROUP = 0xc0286988 SIOCGIFHARDMTU = 0xc02069a5 SIOCGIFMEDIA = 0xc0306936 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc020697e SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPRIORITY = 0xc020699c SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFRDOMAIN = 0xc02069a0 SIOCGIFRTLABEL = 0xc0206983 SIOCGIFTIMESLOT = 0xc0206986 SIOCGIFXFLAGS = 0xc020699e SIOCGLIFADDR = 0xc218691d SIOCGLIFPHYADDR = 0xc218694b SIOCGLIFPHYRTABLE = 0xc02069a2 SIOCGLIFPHYTTL = 0xc02069a9 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGSPPPPARAMS = 0xc0206994 SIOCGVH = 0xc02069f6 SIOCGVNETID = 0xc02069a7 SIOCIFCREATE = 0x8020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106978 SIOCSETKALIVE = 0x801869a3 SIOCSETLABEL = 0x80206999 SIOCSETPFLOW = 0x802069fd SIOCSETPFSYNC = 0x802069f7 SIOCSETVLAN = 0x8020698f SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBRDADDR = 0x80206913 SIOCSIFDESCR = 0x80206980 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGATTR = 0x8028698c SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020691f SIOCSIFMEDIA = 0xc0206935 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x8020697f SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPRIORITY = 0x8020699b SIOCSIFRDOMAIN = 0x8020699f SIOCSIFRTLABEL = 0x80206982 SIOCSIFTIMESLOT = 0x80206985 SIOCSIFXFLAGS = 0x8020699d SIOCSLIFPHYADDR = 0x8218694a SIOCSLIFPHYRTABLE = 0x802069a1 SIOCSLIFPHYTTL = 0x802069a8 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSSPPPPARAMS = 0x80206993 SIOCSVH = 0xc02069f5 SIOCSVNETID = 0x802069a6 SOCK_DGRAM = 0x2 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BINDANY = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NETPROC = 0x1020 SO_OOBINLINE = 0x100 SO_PEERCRED = 0x1022 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RTABLE = 0x1021 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_SPLICE = 0x1023 SO_TIMESTAMP = 0x800 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x3 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x4 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOPUSH = 0x10 TCP_NSTATES = 0xb TCP_SACK_ENABLE = 0x8 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_PPS = 0x10 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGPGRP = 0x40047477 TIOCGSID = 0x40047463 TIOCGTSTAMP = 0x4010745b TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMODG = 0x4004746a TIOCMODS = 0x8004746d TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSFLAGS = 0x8004745c TIOCSIG = 0x8004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x80047465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSTSTAMP = 0x8008745a TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALTSIG = 0x4 WCONTINUED = 0x8 WCOREFLAG = 0x80 WNOHANG = 0x1 WSTOPPED = 0x7f WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x58) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x59) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EIPSEC = syscall.Errno(0x52) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x5b) ELOOP = syscall.Errno(0x3e) EMEDIUMTYPE = syscall.Errno(0x56) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x53) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOMEDIUM = syscall.Errno(0x55) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5a) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x5b) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x57) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "connection timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "IPsec processing failure", 83: "attribute not found", 84: "illegal byte sequence", 85: "no medium found", 86: "wrong medium type", 87: "value too large to be stored in data type", 88: "operation canceled", 89: "identifier removed", 90: "no message of desired type", 91: "not supported", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "stopped (signal)", 18: "stopped", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "thread AST", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_openbsd_386.go0000644061062106075000000017661613172163421025517 0ustar stgraberdomain admins// mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,openbsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m32 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_BLUETOOTH = 0x20 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_ENCAP = 0x1c AF_HYLINK = 0xf AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_KEY = 0x1e AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x24 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x1d AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRFILT = 0x4004427c BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc008427b BIOCGETIF = 0x4020426b BIOCGFILDROP = 0x40044278 BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044273 BIOCGRTIMEOUT = 0x400c426e BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x20004276 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDIRFILT = 0x8004427d BIOCSDLT = 0x8004427a BIOCSETF = 0x80084267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x80084277 BIOCSFILDROP = 0x80044279 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044272 BIOCSRTIMEOUT = 0x800c426d BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIRECTION_IN = 0x1 BPF_DIRECTION_OUT = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x200000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CREAD = 0x800 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0xff CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e DLT_ARCNET = 0x7 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0xd DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_LOOP = 0xc DLT_MPLS = 0xdb DLT_NULL = 0x0 DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xe DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMT_TAGOVF = 0x1 EMUL_ENABLED = 0x1 EMUL_NATIVE = 0x2 ENDRUNDISC = 0x9 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_AOE = 0x88a2 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LLDP = 0x88cc ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_QINQ = 0x88a8 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOW = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_ALIGN = 0x2 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_DIX_LEN = 0x600 ETHER_MAX_LEN = 0x5ee ETHER_MIN_LEN = 0x40 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = -0x3 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x7 EVFILT_TIMER = -0x7 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xa F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 F_OK = 0x0 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFA_ROUTE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8e52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BLUETOOTH = 0xf8 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf7 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DUMMY = 0xf1 IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf3 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFLOW = 0xf9 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf2 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_HOST = 0x1 IN_RFC3021_NET = 0xfffffffe IN_RFC3021_NSHIFT = 0x1f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DIVERT = 0x102 IPPROTO_DIVERT_INIT = 0x2 IPPROTO_DIVERT_RESP = 0x1 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x103 IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPV6_AUTH_LEVEL = 0x35 IPV6_AUTOFLOWLABEL = 0x3b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_ESP_NETWORK_LEVEL = 0x37 IPV6_ESP_TRANS_LEVEL = 0x36 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPCOMP_LEVEL = 0x3c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_OPTIONS = 0x1 IPV6_PATHMTU = 0x2c IPV6_PIPEX = 0x3f IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVDSTPORT = 0x40 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTABLE = 0x1021 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_AUTH_LEVEL = 0x14 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DIVERTFL = 0x1022 IP_DROP_MEMBERSHIP = 0xd IP_ESP_NETWORK_LEVEL = 0x16 IP_ESP_TRANS_LEVEL = 0x15 IP_HDRINCL = 0x2 IP_IPCOMP_LEVEL = 0x1d IP_IPSECFLOWINFO = 0x24 IP_IPSEC_LOCAL_AUTH = 0x1b IP_IPSEC_LOCAL_CRED = 0x19 IP_IPSEC_LOCAL_ID = 0x17 IP_IPSEC_REMOTE_AUTH = 0x1c IP_IPSEC_REMOTE_CRED = 0x1a IP_IPSEC_REMOTE_ID = 0x18 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0xfff IP_MF = 0x2000 IP_MINTTL = 0x20 IP_MIN_MEMBERSHIPS = 0xf IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PIPEX = 0x22 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVDSTPORT = 0x21 IP_RECVIF = 0x1e IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRTABLE = 0x23 IP_RECVTTL = 0x1f IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RTABLE = 0x1021 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 MAP_COPY = 0x4 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_FLAGMASK = 0x1ff7 MAP_HASSEMAPHORE = 0x200 MAP_INHERIT = 0x80 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_DONATE_COPY = 0x3 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_TRYFIXED = 0x400 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_BCAST = 0x100 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_MCAST = 0x200 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x4 MS_SYNC = 0x2 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_MAXID = 0x6 NET_RT_STATS = 0x4 NET_RT_TABLE = 0x5 NOFLSH = 0x80000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EOF = 0x2 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRUNCATE = 0x80 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x80 ONOCR = 0x40 ONOEOT = 0x8 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x10000 O_CREAT = 0x200 O_DIRECTORY = 0x20000 O_DSYNC = 0x80 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x80 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PF_FLUSH = 0x1 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PT_MASK = 0x3ff000 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_LABEL = 0xa RTAX_MAX = 0xb RTAX_NETMASK = 0x2 RTAX_SRC = 0x8 RTAX_SRCMASK = 0x9 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_LABEL = 0x400 RTA_NETMASK = 0x4 RTA_SRC = 0x100 RTA_SRCMASK = 0x200 RTF_ANNOUNCE = 0x4000 RTF_BLACKHOLE = 0x1000 RTF_CLONED = 0x10000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FMASK = 0x10f808 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_MPATH = 0x40000 RTF_MPLS = 0x100000 RTF_PERMANENT_ARP = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x2000 RTF_REJECT = 0x8 RTF_SOURCE = 0x20000 RTF_STATIC = 0x800 RTF_TUNNEL = 0x100000 RTF_UP = 0x1 RTF_USETRAILERS = 0x8000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DESYNC = 0x10 RTM_GET = 0x4 RTM_IFANNOUNCE = 0xf RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MAXSIZE = 0x800 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RT_TABLEID_MAX = 0xff RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCALIFADDR = 0x8218691c SIOCATMARK = 0x40047307 SIOCBRDGADD = 0x8054693c SIOCBRDGADDS = 0x80546941 SIOCBRDGARL = 0x806e694d SIOCBRDGDADDR = 0x81286947 SIOCBRDGDEL = 0x8054693d SIOCBRDGDELS = 0x80546942 SIOCBRDGFLUSH = 0x80546948 SIOCBRDGFRL = 0x806e694e SIOCBRDGGCACHE = 0xc0146941 SIOCBRDGGFD = 0xc0146952 SIOCBRDGGHT = 0xc0146951 SIOCBRDGGIFFLGS = 0xc054693e SIOCBRDGGMA = 0xc0146953 SIOCBRDGGPARAM = 0xc03c6958 SIOCBRDGGPRI = 0xc0146950 SIOCBRDGGRL = 0xc028694f SIOCBRDGGSIFS = 0xc054693c SIOCBRDGGTO = 0xc0146946 SIOCBRDGIFS = 0xc0546942 SIOCBRDGRTS = 0xc0186943 SIOCBRDGSADDR = 0xc1286944 SIOCBRDGSCACHE = 0x80146940 SIOCBRDGSFD = 0x80146952 SIOCBRDGSHT = 0x80146951 SIOCBRDGSIFCOST = 0x80546955 SIOCBRDGSIFFLGS = 0x8054693f SIOCBRDGSIFPRIO = 0x80546954 SIOCBRDGSMA = 0x80146953 SIOCBRDGSPRI = 0x80146950 SIOCBRDGSPROTO = 0x8014695a SIOCBRDGSTO = 0x80146945 SIOCBRDGSTXHC = 0x80146959 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8218691e SIOCGETKALIVE = 0xc01869a4 SIOCGETLABEL = 0x8020699a SIOCGETPFLOW = 0xc02069fe SIOCGETPFSYNC = 0xc02069f8 SIOCGETSGCNT = 0xc0147534 SIOCGETVIFCNT = 0xc0147533 SIOCGETVLAN = 0xc0206990 SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCONF = 0xc0086924 SIOCGIFDATA = 0xc020691b SIOCGIFDESCR = 0xc0206981 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGATTR = 0xc024698b SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc024698a SIOCGIFGROUP = 0xc0246988 SIOCGIFHARDMTU = 0xc02069a5 SIOCGIFMEDIA = 0xc0286936 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc020697e SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPRIORITY = 0xc020699c SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFRDOMAIN = 0xc02069a0 SIOCGIFRTLABEL = 0xc0206983 SIOCGIFTIMESLOT = 0xc0206986 SIOCGIFXFLAGS = 0xc020699e SIOCGLIFADDR = 0xc218691d SIOCGLIFPHYADDR = 0xc218694b SIOCGLIFPHYRTABLE = 0xc02069a2 SIOCGLIFPHYTTL = 0xc02069a9 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGSPPPPARAMS = 0xc0206994 SIOCGVH = 0xc02069f6 SIOCGVNETID = 0xc02069a7 SIOCIFCREATE = 0x8020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc00c6978 SIOCSETKALIVE = 0x801869a3 SIOCSETLABEL = 0x80206999 SIOCSETPFLOW = 0x802069fd SIOCSETPFSYNC = 0x802069f7 SIOCSETVLAN = 0x8020698f SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBRDADDR = 0x80206913 SIOCSIFDESCR = 0x80206980 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGATTR = 0x8024698c SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020691f SIOCSIFMEDIA = 0xc0206935 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x8020697f SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPRIORITY = 0x8020699b SIOCSIFRDOMAIN = 0x8020699f SIOCSIFRTLABEL = 0x80206982 SIOCSIFTIMESLOT = 0x80206985 SIOCSIFXFLAGS = 0x8020699d SIOCSLIFPHYADDR = 0x8218694a SIOCSLIFPHYRTABLE = 0x802069a1 SIOCSLIFPHYTTL = 0x802069a8 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSSPPPPARAMS = 0x80206993 SIOCSVH = 0xc02069f5 SIOCSVNETID = 0x802069a6 SOCK_DGRAM = 0x2 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BINDANY = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NETPROC = 0x1020 SO_OOBINLINE = 0x100 SO_PEERCRED = 0x1022 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RTABLE = 0x1021 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_SPLICE = 0x1023 SO_TIMESTAMP = 0x800 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x3 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x4 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOPUSH = 0x10 TCP_NSTATES = 0xb TCP_SACK_ENABLE = 0x8 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_PPS = 0x10 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGPGRP = 0x40047477 TIOCGSID = 0x40047463 TIOCGTSTAMP = 0x400c745b TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMODG = 0x4004746a TIOCMODS = 0x8004746d TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSFLAGS = 0x8004745c TIOCSIG = 0x8004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x80047465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSTSTAMP = 0x8008745a TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALTSIG = 0x4 WCONTINUED = 0x8 WCOREFLAG = 0x80 WNOHANG = 0x1 WSTOPPED = 0x7f WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x58) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x59) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EIPSEC = syscall.Errno(0x52) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x5b) ELOOP = syscall.Errno(0x3e) EMEDIUMTYPE = syscall.Errno(0x56) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x53) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOMEDIUM = syscall.Errno(0x55) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5a) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x5b) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x57) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "connection timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "IPsec processing failure", 83: "attribute not found", 84: "illegal byte sequence", 85: "no medium found", 86: "wrong medium type", 87: "value too large to be stored in data type", 88: "operation canceled", 89: "identifier removed", 90: "no message of desired type", 91: "not supported", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "stopped (signal)", 18: "stopped", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "thread AST", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_netbsd_arm.go0000644061062106075000000020715513172163421025574 0ustar stgraberdomain admins// mkerrors.sh -marm // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,netbsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -marm _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_ARP = 0x1c AF_BLUETOOTH = 0x1f AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x20 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x23 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OROUTE = 0x11 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x22 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ARPHRD_ARCNET = 0x7 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_STRIP = 0x17 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B460800 = 0x70800 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B921600 = 0xe1000 B9600 = 0x2580 BIOCFEEDBACK = 0x8004427d BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc0084277 BIOCGETIF = 0x4090426b BIOCGFEEDBACK = 0x4004427c BIOCGHDRCMPLT = 0x40044274 BIOCGRTIMEOUT = 0x400c427b BIOCGSEESENT = 0x40044278 BIOCGSTATS = 0x4080426f BIOCGSTATSOLD = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044276 BIOCSETF = 0x80084267 BIOCSETIF = 0x8090426c BIOCSFEEDBACK = 0x8004427d BIOCSHDRCMPLT = 0x80044275 BIOCSRTIMEOUT = 0x800c427a BIOCSSEESENT = 0x80044279 BIOCSTCPF = 0x80084272 BIOCSUDPF = 0x80084273 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALIGNMENT32 = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DFLTBUFSIZE = 0x100000 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x1000000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CREAD = 0x800 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 CTL_QUERY = -0x2 DIOCBSFLUSH = 0x20006478 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HDLC = 0x10 DLT_HHDLC = 0x79 DLT_HIPPI = 0xf DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPNET = 0xe2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RAWAF_MASK = 0x2240000 DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xd DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_WIHART = 0xdf DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMUL_LINUX = 0x1 EMUL_LINUX32 = 0x5 EMUL_MAXID = 0x6 ETHERCAP_JUMBO_MTU = 0x4 ETHERCAP_VLAN_HWTAGGING = 0x2 ETHERCAP_VLAN_MTU = 0x1 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERMTU_JUMBO = 0x2328 ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOWPROTOCOLS = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_LEN = 0x5ee ETHER_MAX_LEN_JUMBO = 0x233a ETHER_MIN_LEN = 0x40 ETHER_PPPOE_ENCAP_LEN = 0x8 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = 0x2 EVFILT_PROC = 0x4 EVFILT_READ = 0x0 EVFILT_SIGNAL = 0x5 EVFILT_SYSCOUNT = 0x7 EVFILT_TIMER = 0x6 EVFILT_VNODE = 0x3 EVFILT_WRITE = 0x1 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x100 FLUSHO = 0x800000 F_CLOSEM = 0xa F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xc F_FSCTL = -0x80000000 F_FSDIRMASK = 0x70000000 F_FSIN = 0x10000000 F_FSINOUT = 0x30000000 F_FSOUT = 0x20000000 F_FSPRIV = 0x8000 F_FSVOID = 0x40000000 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETNOSIGPIPE = 0xd F_GETOWN = 0x5 F_MAXFD = 0xb F_OK = 0x0 F_PARAM_MASK = 0xfff F_PARAM_MAX = 0xfff F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETNOSIGPIPE = 0xe F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFA_ROUTE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8f52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf8 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf2 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xd7 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IPV6_ICMP = 0x3a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MOBILE = 0x37 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_VRRP = 0x70 IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_EF = 0x8000 IP_ERRORMTU = 0x15 IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x16 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINFRAGSIZE = 0x45 IP_MINTTL = 0x18 IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x17 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ALIGNMENT_16MB = 0x18000000 MAP_ALIGNMENT_1TB = 0x28000000 MAP_ALIGNMENT_256TB = 0x30000000 MAP_ALIGNMENT_4GB = 0x20000000 MAP_ALIGNMENT_64KB = 0x10000000 MAP_ALIGNMENT_64PB = 0x38000000 MAP_ALIGNMENT_MASK = -0x1000000 MAP_ALIGNMENT_SHIFT = 0x18 MAP_ANON = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_INHERIT = 0x80 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_DEFAULT = 0x1 MAP_INHERIT_DONATE_COPY = 0x3 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_STACK = 0x2000 MAP_TRYFIXED = 0x400 MAP_WIRED = 0x800 MSG_BCAST = 0x100 MSG_CMSG_CLOEXEC = 0x800 MSG_CONTROLMBUF = 0x2000000 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_IOVUSRSPACE = 0x4000000 MSG_LENUSRSPACE = 0x8000000 MSG_MCAST = 0x200 MSG_NAMEMBUF = 0x1000000 MSG_NBIO = 0x1000 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_USERFLAGS = 0xffffff MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_SYNC = 0x4 NAME_MAX = 0x1ff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x5 NET_RT_MAXID = 0x6 NET_RT_OIFLIST = 0x4 NET_RT_OOIFLIST = 0x3 NOFLSH = 0x80000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_WRITE = 0x2 OCRNL = 0x10 OFIOGETBMAP = 0xc004667a ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 O_ACCMODE = 0x3 O_ALT_IO = 0x40000 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x400000 O_CREAT = 0x200 O_DIRECT = 0x80000 O_DIRECTORY = 0x200000 O_DSYNC = 0x10000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_NOSIGPIPE = 0x1000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x20000 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PRI_IOFLUSH = 0x7c PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 RLIMIT_AS = 0xa RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x9 RTAX_NETMASK = 0x2 RTAX_TAG = 0x8 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTA_TAG = 0x100 RTF_ANNOUNCE = 0x20000 RTF_BLACKHOLE = 0x1000 RTF_CLONED = 0x2000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_REJECT = 0x8 RTF_SRC = 0x10000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_CHGADDR = 0x15 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_GET = 0x4 RTM_IEEE80211 = 0x11 RTM_IFANNOUNCE = 0x10 RTM_IFINFO = 0x14 RTM_LLINFO_UPD = 0x13 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_OIFINFO = 0xf RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_OOIFINFO = 0xe RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_SETGATE = 0x12 RTM_VERSION = 0x4 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x4 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x8 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80906931 SIOCADDRT = 0x8030720a SIOCAIFADDR = 0x8040691a SIOCALIFADDR = 0x8118691c SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80906932 SIOCDELRT = 0x8030720b SIOCDIFADDR = 0x80906919 SIOCDIFPHYADDR = 0x80906949 SIOCDLIFADDR = 0x8118691e SIOCGDRVSPEC = 0xc01c697b SIOCGETPFSYNC = 0xc09069f8 SIOCGETSGCNT = 0xc0147534 SIOCGETVIFCNT = 0xc0147533 SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0906921 SIOCGIFADDRPREF = 0xc0946920 SIOCGIFALIAS = 0xc040691b SIOCGIFBRDADDR = 0xc0906923 SIOCGIFCAP = 0xc0206976 SIOCGIFCONF = 0xc0086926 SIOCGIFDATA = 0xc0946985 SIOCGIFDLT = 0xc0906977 SIOCGIFDSTADDR = 0xc0906922 SIOCGIFFLAGS = 0xc0906911 SIOCGIFGENERIC = 0xc090693a SIOCGIFMEDIA = 0xc0286936 SIOCGIFMETRIC = 0xc0906917 SIOCGIFMTU = 0xc090697e SIOCGIFNETMASK = 0xc0906925 SIOCGIFPDSTADDR = 0xc0906948 SIOCGIFPSRCADDR = 0xc0906947 SIOCGLIFADDR = 0xc118691d SIOCGLIFPHYADDR = 0xc118694b SIOCGLINKSTR = 0xc01c6987 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGVH = 0xc0906983 SIOCIFCREATE = 0x8090697a SIOCIFDESTROY = 0x80906979 SIOCIFGCLONERS = 0xc00c6978 SIOCINITIFADDR = 0xc0446984 SIOCSDRVSPEC = 0x801c697b SIOCSETPFSYNC = 0x809069f7 SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8090690c SIOCSIFADDRPREF = 0x8094691f SIOCSIFBRDADDR = 0x80906913 SIOCSIFCAP = 0x80206975 SIOCSIFDSTADDR = 0x8090690e SIOCSIFFLAGS = 0x80906910 SIOCSIFGENERIC = 0x80906939 SIOCSIFMEDIA = 0xc0906935 SIOCSIFMETRIC = 0x80906918 SIOCSIFMTU = 0x8090697f SIOCSIFNETMASK = 0x80906916 SIOCSIFPHYADDR = 0x80406946 SIOCSLIFPHYADDR = 0x8118694a SIOCSLINKSTR = 0x801c6988 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSVH = 0xc0906982 SIOCZIFDATA = 0xc0946986 SOCK_CLOEXEC = 0x10000000 SOCK_DGRAM = 0x2 SOCK_FLAGS_MASK = 0xf0000000 SOCK_NONBLOCK = 0x20000000 SOCK_NOSIGPIPE = 0x40000000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NOHEADER = 0x100a SO_NOSIGPIPE = 0x800 SO_OOBINLINE = 0x100 SO_OVERFLOWED = 0x1009 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x100c SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x100b SO_TIMESTAMP = 0x2000 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SYSCTL_VERSION = 0x1000000 SYSCTL_VERS_0 = 0x0 SYSCTL_VERS_1 = 0x1000000 SYSCTL_VERS_MASK = 0xff000000 S_ARCH1 = 0x10000 S_ARCH2 = 0x20000 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IFWHT = 0xe000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONGCTL = 0x20 TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x3 TCP_KEEPINIT = 0x7 TCP_KEEPINTVL = 0x5 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x10 TCP_MINMSS = 0xd8 TCP_MSS = 0x218 TCP_NODELAY = 0x1 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x400c7458 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CDTRCTS = 0x10 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGLINED = 0x40207442 TIOCGPGRP = 0x40047477 TIOCGQSIZE = 0x40047481 TIOCGRANTPT = 0x20007447 TIOCGSID = 0x40047463 TIOCGSIZE = 0x40087468 TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTMGET = 0x48087446 TIOCPTSNAME = 0x48087448 TIOCRCVFRAME = 0x80047445 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSFLAGS = 0x8004745c TIOCSIG = 0x2000745f TIOCSLINED = 0x80207443 TIOCSPGRP = 0x80047476 TIOCSQSIZE = 0x80047480 TIOCSSIZE = 0x80087467 TIOCSTART = 0x2000746e TIOCSTAT = 0x80047465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TIOCXMTFRAME = 0x80047444 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALL = 0x8 WALLSIG = 0x8 WALTSIG = 0x4 WCLONE = 0x4 WCOREFLAG = 0x80 WNOHANG = 0x1 WNOWAIT = 0x10000 WNOZOMBIE = 0x20000 WOPTSCHECKED = 0x40000 WSTOPPED = 0x7f WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x58) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x57) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x52) EILSEQ = syscall.Errno(0x55) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x60) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5e) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x5d) ENOBUFS = syscall.Errno(0x37) ENODATA = syscall.Errno(0x59) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x5f) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x53) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x5a) ENOSTR = syscall.Errno(0x5b) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x56) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x54) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x60) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIME = syscall.Errno(0x5c) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x20) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large or too small", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol option not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "connection timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "identifier removed", 83: "no message of desired type", 84: "value too large to be stored in data type", 85: "illegal byte sequence", 86: "not supported", 87: "operation Canceled", 88: "bad or Corrupt message", 89: "no message available", 90: "no STREAM resources", 91: "not a STREAM", 92: "STREAM ioctl timeout", 93: "attribute not found", 94: "multihop attempted", 95: "link has been severed", 96: "protocol error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "stopped (signal)", 18: "stopped", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "power fail/restart", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_netbsd_amd64.go0000644061062106075000000021010213172163421025712 0ustar stgraberdomain admins// mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,netbsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_ARP = 0x1c AF_BLUETOOTH = 0x1f AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x20 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x23 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OROUTE = 0x11 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x22 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ARPHRD_ARCNET = 0x7 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_STRIP = 0x17 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B460800 = 0x70800 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B921600 = 0xe1000 B9600 = 0x2580 BIOCFEEDBACK = 0x8004427d BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc0104277 BIOCGETIF = 0x4090426b BIOCGFEEDBACK = 0x4004427c BIOCGHDRCMPLT = 0x40044274 BIOCGRTIMEOUT = 0x4010427b BIOCGSEESENT = 0x40044278 BIOCGSTATS = 0x4080426f BIOCGSTATSOLD = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044276 BIOCSETF = 0x80104267 BIOCSETIF = 0x8090426c BIOCSFEEDBACK = 0x8004427d BIOCSHDRCMPLT = 0x80044275 BIOCSRTIMEOUT = 0x8010427a BIOCSSEESENT = 0x80044279 BIOCSTCPF = 0x80104272 BIOCSUDPF = 0x80104273 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x8 BPF_ALIGNMENT32 = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DFLTBUFSIZE = 0x100000 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x1000000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CLONE_CSIGNAL = 0xff CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_PID = 0x1000 CLONE_PTRACE = 0x2000 CLONE_SIGHAND = 0x800 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CREAD = 0x800 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 CTL_QUERY = -0x2 DIOCBSFLUSH = 0x20006478 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HDLC = 0x10 DLT_HHDLC = 0x79 DLT_HIPPI = 0xf DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPNET = 0xe2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RAWAF_MASK = 0x2240000 DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xd DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_WIHART = 0xdf DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMUL_LINUX = 0x1 EMUL_LINUX32 = 0x5 EMUL_MAXID = 0x6 ETHERCAP_JUMBO_MTU = 0x4 ETHERCAP_VLAN_HWTAGGING = 0x2 ETHERCAP_VLAN_MTU = 0x1 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERMTU_JUMBO = 0x2328 ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOWPROTOCOLS = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_LEN = 0x5ee ETHER_MAX_LEN_JUMBO = 0x233a ETHER_MIN_LEN = 0x40 ETHER_PPPOE_ENCAP_LEN = 0x8 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = 0x2 EVFILT_PROC = 0x4 EVFILT_READ = 0x0 EVFILT_SIGNAL = 0x5 EVFILT_SYSCOUNT = 0x7 EVFILT_TIMER = 0x6 EVFILT_VNODE = 0x3 EVFILT_WRITE = 0x1 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x100 FLUSHO = 0x800000 F_CLOSEM = 0xa F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xc F_FSCTL = -0x80000000 F_FSDIRMASK = 0x70000000 F_FSIN = 0x10000000 F_FSINOUT = 0x30000000 F_FSOUT = 0x20000000 F_FSPRIV = 0x8000 F_FSVOID = 0x40000000 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETNOSIGPIPE = 0xd F_GETOWN = 0x5 F_MAXFD = 0xb F_OK = 0x0 F_PARAM_MASK = 0xfff F_PARAM_MAX = 0xfff F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETNOSIGPIPE = 0xe F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFA_ROUTE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8f52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf8 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf2 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xd7 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IPV6_ICMP = 0x3a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MOBILE = 0x37 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_VRRP = 0x70 IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_EF = 0x8000 IP_ERRORMTU = 0x15 IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x16 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINFRAGSIZE = 0x45 IP_MINTTL = 0x18 IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x17 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ALIGNMENT_16MB = 0x18000000 MAP_ALIGNMENT_1TB = 0x28000000 MAP_ALIGNMENT_256TB = 0x30000000 MAP_ALIGNMENT_4GB = 0x20000000 MAP_ALIGNMENT_64KB = 0x10000000 MAP_ALIGNMENT_64PB = 0x38000000 MAP_ALIGNMENT_MASK = -0x1000000 MAP_ALIGNMENT_SHIFT = 0x18 MAP_ANON = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_INHERIT = 0x80 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_DEFAULT = 0x1 MAP_INHERIT_DONATE_COPY = 0x3 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_STACK = 0x2000 MAP_TRYFIXED = 0x400 MAP_WIRED = 0x800 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_BCAST = 0x100 MSG_CMSG_CLOEXEC = 0x800 MSG_CONTROLMBUF = 0x2000000 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_IOVUSRSPACE = 0x4000000 MSG_LENUSRSPACE = 0x8000000 MSG_MCAST = 0x200 MSG_NAMEMBUF = 0x1000000 MSG_NBIO = 0x1000 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_USERFLAGS = 0xffffff MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_SYNC = 0x4 NAME_MAX = 0x1ff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x5 NET_RT_MAXID = 0x6 NET_RT_OIFLIST = 0x4 NET_RT_OOIFLIST = 0x3 NOFLSH = 0x80000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_WRITE = 0x2 OCRNL = 0x10 OFIOGETBMAP = 0xc004667a ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 O_ACCMODE = 0x3 O_ALT_IO = 0x40000 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x400000 O_CREAT = 0x200 O_DIRECT = 0x80000 O_DIRECTORY = 0x200000 O_DSYNC = 0x10000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_NOSIGPIPE = 0x1000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x20000 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PRI_IOFLUSH = 0x7c PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0xa RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x9 RTAX_NETMASK = 0x2 RTAX_TAG = 0x8 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTA_TAG = 0x100 RTF_ANNOUNCE = 0x20000 RTF_BLACKHOLE = 0x1000 RTF_CLONED = 0x2000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_REJECT = 0x8 RTF_SRC = 0x10000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_CHGADDR = 0x15 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_GET = 0x4 RTM_IEEE80211 = 0x11 RTM_IFANNOUNCE = 0x10 RTM_IFINFO = 0x14 RTM_LLINFO_UPD = 0x13 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_OIFINFO = 0xf RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_OOIFINFO = 0xe RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_SETGATE = 0x12 RTM_VERSION = 0x4 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x4 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x8 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80906931 SIOCADDRT = 0x8038720a SIOCAIFADDR = 0x8040691a SIOCALIFADDR = 0x8118691c SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80906932 SIOCDELRT = 0x8038720b SIOCDIFADDR = 0x80906919 SIOCDIFPHYADDR = 0x80906949 SIOCDLIFADDR = 0x8118691e SIOCGDRVSPEC = 0xc028697b SIOCGETPFSYNC = 0xc09069f8 SIOCGETSGCNT = 0xc0207534 SIOCGETVIFCNT = 0xc0287533 SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0906921 SIOCGIFADDRPREF = 0xc0986920 SIOCGIFALIAS = 0xc040691b SIOCGIFBRDADDR = 0xc0906923 SIOCGIFCAP = 0xc0206976 SIOCGIFCONF = 0xc0106926 SIOCGIFDATA = 0xc0986985 SIOCGIFDLT = 0xc0906977 SIOCGIFDSTADDR = 0xc0906922 SIOCGIFFLAGS = 0xc0906911 SIOCGIFGENERIC = 0xc090693a SIOCGIFMEDIA = 0xc0306936 SIOCGIFMETRIC = 0xc0906917 SIOCGIFMTU = 0xc090697e SIOCGIFNETMASK = 0xc0906925 SIOCGIFPDSTADDR = 0xc0906948 SIOCGIFPSRCADDR = 0xc0906947 SIOCGLIFADDR = 0xc118691d SIOCGLIFPHYADDR = 0xc118694b SIOCGLINKSTR = 0xc0286987 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGVH = 0xc0906983 SIOCIFCREATE = 0x8090697a SIOCIFDESTROY = 0x80906979 SIOCIFGCLONERS = 0xc0106978 SIOCINITIFADDR = 0xc0706984 SIOCSDRVSPEC = 0x8028697b SIOCSETPFSYNC = 0x809069f7 SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8090690c SIOCSIFADDRPREF = 0x8098691f SIOCSIFBRDADDR = 0x80906913 SIOCSIFCAP = 0x80206975 SIOCSIFDSTADDR = 0x8090690e SIOCSIFFLAGS = 0x80906910 SIOCSIFGENERIC = 0x80906939 SIOCSIFMEDIA = 0xc0906935 SIOCSIFMETRIC = 0x80906918 SIOCSIFMTU = 0x8090697f SIOCSIFNETMASK = 0x80906916 SIOCSIFPHYADDR = 0x80406946 SIOCSLIFPHYADDR = 0x8118694a SIOCSLINKSTR = 0x80286988 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSVH = 0xc0906982 SIOCZIFDATA = 0xc0986986 SOCK_CLOEXEC = 0x10000000 SOCK_DGRAM = 0x2 SOCK_FLAGS_MASK = 0xf0000000 SOCK_NONBLOCK = 0x20000000 SOCK_NOSIGPIPE = 0x40000000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NOHEADER = 0x100a SO_NOSIGPIPE = 0x800 SO_OOBINLINE = 0x100 SO_OVERFLOWED = 0x1009 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x100c SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x100b SO_TIMESTAMP = 0x2000 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SYSCTL_VERSION = 0x1000000 SYSCTL_VERS_0 = 0x0 SYSCTL_VERS_1 = 0x1000000 SYSCTL_VERS_MASK = 0xff000000 S_ARCH1 = 0x10000 S_ARCH2 = 0x20000 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IFWHT = 0xe000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 S_LOGIN_SET = 0x1 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONGCTL = 0x20 TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x3 TCP_KEEPINIT = 0x7 TCP_KEEPINTVL = 0x5 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x10 TCP_MINMSS = 0xd8 TCP_MSS = 0x218 TCP_NODELAY = 0x1 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x40107458 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CDTRCTS = 0x10 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGLINED = 0x40207442 TIOCGPGRP = 0x40047477 TIOCGQSIZE = 0x40047481 TIOCGRANTPT = 0x20007447 TIOCGSID = 0x40047463 TIOCGSIZE = 0x40087468 TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTMGET = 0x40287446 TIOCPTSNAME = 0x40287448 TIOCRCVFRAME = 0x80087445 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSFLAGS = 0x8004745c TIOCSIG = 0x2000745f TIOCSLINED = 0x80207443 TIOCSPGRP = 0x80047476 TIOCSQSIZE = 0x80047480 TIOCSSIZE = 0x80087467 TIOCSTART = 0x2000746e TIOCSTAT = 0x80047465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TIOCXMTFRAME = 0x80087444 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALL = 0x8 WALLSIG = 0x8 WALTSIG = 0x4 WCLONE = 0x4 WCOREFLAG = 0x80 WNOHANG = 0x1 WNOWAIT = 0x10000 WNOZOMBIE = 0x20000 WOPTSCHECKED = 0x40000 WSTOPPED = 0x7f WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x58) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x57) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x52) EILSEQ = syscall.Errno(0x55) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x60) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5e) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x5d) ENOBUFS = syscall.Errno(0x37) ENODATA = syscall.Errno(0x59) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x5f) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x53) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x5a) ENOSTR = syscall.Errno(0x5b) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x56) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x54) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x60) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIME = syscall.Errno(0x5c) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x20) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large or too small", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol option not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "connection timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "identifier removed", 83: "no message of desired type", 84: "value too large to be stored in data type", 85: "illegal byte sequence", 86: "not supported", 87: "operation Canceled", 88: "bad or Corrupt message", 89: "no message available", 90: "no STREAM resources", 91: "not a STREAM", 92: "STREAM ioctl timeout", 93: "attribute not found", 94: "multihop attempted", 95: "link has been severed", 96: "protocol error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "stopped (signal)", 18: "stopped", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "power fail/restart", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_netbsd_386.go0000644061062106075000000021074413172163421025333 0ustar stgraberdomain admins// mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,netbsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m32 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_ARP = 0x1c AF_BLUETOOTH = 0x1f AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x20 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x23 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OROUTE = 0x11 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x22 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ARPHRD_ARCNET = 0x7 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_STRIP = 0x17 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B460800 = 0x70800 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B921600 = 0xe1000 B9600 = 0x2580 BIOCFEEDBACK = 0x8004427d BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc0084277 BIOCGETIF = 0x4090426b BIOCGFEEDBACK = 0x4004427c BIOCGHDRCMPLT = 0x40044274 BIOCGRTIMEOUT = 0x400c427b BIOCGSEESENT = 0x40044278 BIOCGSTATS = 0x4080426f BIOCGSTATSOLD = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044276 BIOCSETF = 0x80084267 BIOCSETIF = 0x8090426c BIOCSFEEDBACK = 0x8004427d BIOCSHDRCMPLT = 0x80044275 BIOCSRTIMEOUT = 0x800c427a BIOCSSEESENT = 0x80044279 BIOCSTCPF = 0x80084272 BIOCSUDPF = 0x80084273 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALIGNMENT32 = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DFLTBUFSIZE = 0x100000 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x1000000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CLONE_CSIGNAL = 0xff CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_PID = 0x1000 CLONE_PTRACE = 0x2000 CLONE_SIGHAND = 0x800 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CREAD = 0x800 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 CTL_QUERY = -0x2 DIOCBSFLUSH = 0x20006478 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HDLC = 0x10 DLT_HHDLC = 0x79 DLT_HIPPI = 0xf DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPNET = 0xe2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RAWAF_MASK = 0x2240000 DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xd DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_WIHART = 0xdf DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMUL_LINUX = 0x1 EMUL_LINUX32 = 0x5 EMUL_MAXID = 0x6 EN_SW_CTL_INF = 0x1000 EN_SW_CTL_PREC = 0x300 EN_SW_CTL_ROUND = 0xc00 EN_SW_DATACHAIN = 0x80 EN_SW_DENORM = 0x2 EN_SW_INVOP = 0x1 EN_SW_OVERFLOW = 0x8 EN_SW_PRECLOSS = 0x20 EN_SW_UNDERFLOW = 0x10 EN_SW_ZERODIV = 0x4 ETHERCAP_JUMBO_MTU = 0x4 ETHERCAP_VLAN_HWTAGGING = 0x2 ETHERCAP_VLAN_MTU = 0x1 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERMTU_JUMBO = 0x2328 ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOWPROTOCOLS = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_LEN = 0x5ee ETHER_MAX_LEN_JUMBO = 0x233a ETHER_MIN_LEN = 0x40 ETHER_PPPOE_ENCAP_LEN = 0x8 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = 0x2 EVFILT_PROC = 0x4 EVFILT_READ = 0x0 EVFILT_SIGNAL = 0x5 EVFILT_SYSCOUNT = 0x7 EVFILT_TIMER = 0x6 EVFILT_VNODE = 0x3 EVFILT_WRITE = 0x1 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x100 FLUSHO = 0x800000 F_CLOSEM = 0xa F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xc F_FSCTL = -0x80000000 F_FSDIRMASK = 0x70000000 F_FSIN = 0x10000000 F_FSINOUT = 0x30000000 F_FSOUT = 0x20000000 F_FSPRIV = 0x8000 F_FSVOID = 0x40000000 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETNOSIGPIPE = 0xd F_GETOWN = 0x5 F_MAXFD = 0xb F_OK = 0x0 F_PARAM_MASK = 0xfff F_PARAM_MAX = 0xfff F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETNOSIGPIPE = 0xe F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFA_ROUTE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8f52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf8 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf2 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xd7 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IPV6_ICMP = 0x3a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MOBILE = 0x37 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_VRRP = 0x70 IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_EF = 0x8000 IP_ERRORMTU = 0x15 IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x16 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINFRAGSIZE = 0x45 IP_MINTTL = 0x18 IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x17 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ALIGNMENT_16MB = 0x18000000 MAP_ALIGNMENT_1TB = 0x28000000 MAP_ALIGNMENT_256TB = 0x30000000 MAP_ALIGNMENT_4GB = 0x20000000 MAP_ALIGNMENT_64KB = 0x10000000 MAP_ALIGNMENT_64PB = 0x38000000 MAP_ALIGNMENT_MASK = -0x1000000 MAP_ALIGNMENT_SHIFT = 0x18 MAP_ANON = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_INHERIT = 0x80 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_DEFAULT = 0x1 MAP_INHERIT_DONATE_COPY = 0x3 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_STACK = 0x2000 MAP_TRYFIXED = 0x400 MAP_WIRED = 0x800 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_BCAST = 0x100 MSG_CMSG_CLOEXEC = 0x800 MSG_CONTROLMBUF = 0x2000000 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_IOVUSRSPACE = 0x4000000 MSG_LENUSRSPACE = 0x8000000 MSG_MCAST = 0x200 MSG_NAMEMBUF = 0x1000000 MSG_NBIO = 0x1000 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_USERFLAGS = 0xffffff MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_SYNC = 0x4 NAME_MAX = 0x1ff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x5 NET_RT_MAXID = 0x6 NET_RT_OIFLIST = 0x4 NET_RT_OOIFLIST = 0x3 NOFLSH = 0x80000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_WRITE = 0x2 OCRNL = 0x10 OFIOGETBMAP = 0xc004667a ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 O_ACCMODE = 0x3 O_ALT_IO = 0x40000 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x400000 O_CREAT = 0x200 O_DIRECT = 0x80000 O_DIRECTORY = 0x200000 O_DSYNC = 0x10000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_NOSIGPIPE = 0x1000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x20000 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PRI_IOFLUSH = 0x7c PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0xa RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x9 RTAX_NETMASK = 0x2 RTAX_TAG = 0x8 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTA_TAG = 0x100 RTF_ANNOUNCE = 0x20000 RTF_BLACKHOLE = 0x1000 RTF_CLONED = 0x2000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_REJECT = 0x8 RTF_SRC = 0x10000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_CHGADDR = 0x15 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_GET = 0x4 RTM_IEEE80211 = 0x11 RTM_IFANNOUNCE = 0x10 RTM_IFINFO = 0x14 RTM_LLINFO_UPD = 0x13 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_OIFINFO = 0xf RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_OOIFINFO = 0xe RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_SETGATE = 0x12 RTM_VERSION = 0x4 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x4 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x8 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80906931 SIOCADDRT = 0x8030720a SIOCAIFADDR = 0x8040691a SIOCALIFADDR = 0x8118691c SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80906932 SIOCDELRT = 0x8030720b SIOCDIFADDR = 0x80906919 SIOCDIFPHYADDR = 0x80906949 SIOCDLIFADDR = 0x8118691e SIOCGDRVSPEC = 0xc01c697b SIOCGETPFSYNC = 0xc09069f8 SIOCGETSGCNT = 0xc0147534 SIOCGETVIFCNT = 0xc0147533 SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0906921 SIOCGIFADDRPREF = 0xc0946920 SIOCGIFALIAS = 0xc040691b SIOCGIFBRDADDR = 0xc0906923 SIOCGIFCAP = 0xc0206976 SIOCGIFCONF = 0xc0086926 SIOCGIFDATA = 0xc0946985 SIOCGIFDLT = 0xc0906977 SIOCGIFDSTADDR = 0xc0906922 SIOCGIFFLAGS = 0xc0906911 SIOCGIFGENERIC = 0xc090693a SIOCGIFMEDIA = 0xc0286936 SIOCGIFMETRIC = 0xc0906917 SIOCGIFMTU = 0xc090697e SIOCGIFNETMASK = 0xc0906925 SIOCGIFPDSTADDR = 0xc0906948 SIOCGIFPSRCADDR = 0xc0906947 SIOCGLIFADDR = 0xc118691d SIOCGLIFPHYADDR = 0xc118694b SIOCGLINKSTR = 0xc01c6987 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGVH = 0xc0906983 SIOCIFCREATE = 0x8090697a SIOCIFDESTROY = 0x80906979 SIOCIFGCLONERS = 0xc00c6978 SIOCINITIFADDR = 0xc0446984 SIOCSDRVSPEC = 0x801c697b SIOCSETPFSYNC = 0x809069f7 SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8090690c SIOCSIFADDRPREF = 0x8094691f SIOCSIFBRDADDR = 0x80906913 SIOCSIFCAP = 0x80206975 SIOCSIFDSTADDR = 0x8090690e SIOCSIFFLAGS = 0x80906910 SIOCSIFGENERIC = 0x80906939 SIOCSIFMEDIA = 0xc0906935 SIOCSIFMETRIC = 0x80906918 SIOCSIFMTU = 0x8090697f SIOCSIFNETMASK = 0x80906916 SIOCSIFPHYADDR = 0x80406946 SIOCSLIFPHYADDR = 0x8118694a SIOCSLINKSTR = 0x801c6988 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSVH = 0xc0906982 SIOCZIFDATA = 0xc0946986 SOCK_CLOEXEC = 0x10000000 SOCK_DGRAM = 0x2 SOCK_FLAGS_MASK = 0xf0000000 SOCK_NONBLOCK = 0x20000000 SOCK_NOSIGPIPE = 0x40000000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NOHEADER = 0x100a SO_NOSIGPIPE = 0x800 SO_OOBINLINE = 0x100 SO_OVERFLOWED = 0x1009 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x100c SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x100b SO_TIMESTAMP = 0x2000 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SYSCTL_VERSION = 0x1000000 SYSCTL_VERS_0 = 0x0 SYSCTL_VERS_1 = 0x1000000 SYSCTL_VERS_MASK = 0xff000000 S_ARCH1 = 0x10000 S_ARCH2 = 0x20000 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IFWHT = 0xe000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 S_LOGIN_SET = 0x1 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONGCTL = 0x20 TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x3 TCP_KEEPINIT = 0x7 TCP_KEEPINTVL = 0x5 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x10 TCP_MINMSS = 0xd8 TCP_MSS = 0x218 TCP_NODELAY = 0x1 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x400c7458 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CDTRCTS = 0x10 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGLINED = 0x40207442 TIOCGPGRP = 0x40047477 TIOCGQSIZE = 0x40047481 TIOCGRANTPT = 0x20007447 TIOCGSID = 0x40047463 TIOCGSIZE = 0x40087468 TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTMGET = 0x40287446 TIOCPTSNAME = 0x40287448 TIOCRCVFRAME = 0x80047445 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSFLAGS = 0x8004745c TIOCSIG = 0x2000745f TIOCSLINED = 0x80207443 TIOCSPGRP = 0x80047476 TIOCSQSIZE = 0x80047480 TIOCSSIZE = 0x80087467 TIOCSTART = 0x2000746e TIOCSTAT = 0x80047465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TIOCXMTFRAME = 0x80047444 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALL = 0x8 WALLSIG = 0x8 WALTSIG = 0x4 WCLONE = 0x4 WCOREFLAG = 0x80 WNOHANG = 0x1 WNOWAIT = 0x10000 WNOZOMBIE = 0x20000 WOPTSCHECKED = 0x40000 WSTOPPED = 0x7f WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x58) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x57) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x52) EILSEQ = syscall.Errno(0x55) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x60) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5e) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x5d) ENOBUFS = syscall.Errno(0x37) ENODATA = syscall.Errno(0x59) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x5f) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x53) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x5a) ENOSTR = syscall.Errno(0x5b) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x56) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x54) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x60) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIME = syscall.Errno(0x5c) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x20) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large or too small", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol option not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "connection timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "identifier removed", 83: "no message of desired type", 84: "value too large to be stored in data type", 85: "illegal byte sequence", 86: "not supported", 87: "operation Canceled", 88: "bad or Corrupt message", 89: "no message available", 90: "no STREAM resources", 91: "not a STREAM", 92: "STREAM ioctl timeout", 93: "attribute not found", 94: "multihop attempted", 95: "link has been severed", 96: "protocol error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "stopped (signal)", 18: "stopped", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "power fail/restart", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_sparc64.go0000644061062106075000000024766013172163421026164 0ustar stgraberdomain admins// mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build sparc64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2a AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f ASI_LEON_DFLUSH = 0x11 ASI_LEON_IFLUSH = 0x10 ASI_LEON_MMUFLUSH = 0x18 B0 = 0x0 B1000000 = 0x100c B110 = 0x3 B115200 = 0x1002 B1152000 = 0x100d B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100e B153600 = 0x1006 B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100f B230400 = 0x1003 B2400 = 0xb B300 = 0x7 B307200 = 0x1007 B38400 = 0xf B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x100a B57600 = 0x1001 B576000 = 0x100b B600 = 0x8 B614400 = 0x1008 B75 = 0x2 B76800 = 0x1005 B921600 = 0x1009 B9600 = 0xd BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d BLKRRPART = 0x125f BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EMT_TAGOVF = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x400000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0x7 F_GETLK64 = 0x7 F_GETOWN = 0x5 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x8 F_SETLK64 = 0x8 F_SETLKW = 0x9 F_SETLKW64 = 0x9 F_SETOWN = 0x6 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x3 F_WRLCK = 0x2 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x8000 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x400000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x4000 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x200 MAP_HUGETLB = 0x40000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x100 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x40 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_STACK = 0x20000 MAP_TYPE = 0xf MCL_CURRENT = 0x2000 MCL_FUTURE = 0x4000 MCL_ONFAULT = 0x8000 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x400000 O_CREAT = 0x200 O_DIRECT = 0x100000 O_DIRECTORY = 0x10000 O_DSYNC = 0x2000 O_EXCL = 0x800 O_FSYNC = 0x802000 O_LARGEFILE = 0x0 O_NDELAY = 0x4004 O_NOATIME = 0x200000 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x20000 O_NONBLOCK = 0x4000 O_PATH = 0x1000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x802000 O_SYNC = 0x802000 O_TMPFILE = 0x2010000 O_TRUNC = 0x400 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = -0x1 PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETFPAREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS64 = 0x19 PTRACE_GETREGS = 0xc PTRACE_GETREGS64 = 0x16 PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_READDATA = 0x10 PTRACE_READTEXT = 0x12 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETFPAREGS = 0x15 PTRACE_SETFPREGS = 0xf PTRACE_SETFPREGS64 = 0x1a PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGS64 = 0x17 PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SINGLESTEP = 0x9 PTRACE_SPARC_DETACH = 0xb PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 PTRACE_WRITEDATA = 0x11 PTRACE_WRITETEXT = 0x13 PT_FP = 0x48 PT_G0 = 0x10 PT_G1 = 0x14 PT_G2 = 0x18 PT_G3 = 0x1c PT_G4 = 0x20 PT_G5 = 0x24 PT_G6 = 0x28 PT_G7 = 0x2c PT_I0 = 0x30 PT_I1 = 0x34 PT_I2 = 0x38 PT_I3 = 0x3c PT_I4 = 0x40 PT_I5 = 0x44 PT_I6 = 0x48 PT_I7 = 0x4c PT_NPC = 0x8 PT_PC = 0x4 PT_PSR = 0x0 PT_REGS_MAGIC = 0x57ac6c00 PT_TNPC = 0x90 PT_TPC = 0x88 PT_TSTATE = 0x80 PT_V9_FP = 0x70 PT_V9_G0 = 0x0 PT_V9_G1 = 0x8 PT_V9_G2 = 0x10 PT_V9_G3 = 0x18 PT_V9_G4 = 0x20 PT_V9_G5 = 0x28 PT_V9_G6 = 0x30 PT_V9_G7 = 0x38 PT_V9_I0 = 0x40 PT_V9_I1 = 0x48 PT_V9_I2 = 0x50 PT_V9_I3 = 0x58 PT_V9_I4 = 0x60 PT_V9_I5 = 0x68 PT_V9_I6 = 0x70 PT_V9_I7 = 0x78 PT_V9_MAGIC = 0x9c PT_V9_TNPC = 0x90 PT_V9_TPC = 0x88 PT_V9_TSTATE = 0x80 PT_V9_Y = 0x98 PT_WIM = 0x10 PT_Y = 0xc RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x6 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x18 RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x5f RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x14 RTM_NR_MSGTYPES = 0x50 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x11 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x23 SCM_TIMESTAMPNS = 0x21 SCM_WIFI_STATUS = 0x25 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x4004667f SIOCOUTQ = 0x40047473 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x400000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x4000 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x8000 SO_ATTACH_BPF = 0x34 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x35 SO_ATTACH_REUSEPORT_EBPF = 0x36 SO_BINDTODEVICE = 0xd SO_BPF_EXTENSIONS = 0x32 SO_BROADCAST = 0x20 SO_BSDCOMPAT = 0x400 SO_BUSY_POLL = 0x30 SO_CNX_ADVICE = 0x37 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x33 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_LOCK_FILTER = 0x28 SO_MARK = 0x22 SO_MAX_PACING_RATE = 0x31 SO_NOFCS = 0x27 SO_NO_CHECK = 0xb SO_OOBINLINE = 0x100 SO_PASSCRED = 0x2 SO_PASSSEC = 0x1f SO_PEEK_OFF = 0x26 SO_PEERCRED = 0x40 SO_PEERNAME = 0x1c SO_PEERSEC = 0x1e SO_PRIORITY = 0xc SO_PROTOCOL = 0x1028 SO_RCVBUF = 0x1002 SO_RCVBUFFORCE = 0x100b SO_RCVLOWAT = 0x800 SO_RCVTIMEO = 0x2000 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RXQ_OVFL = 0x24 SO_SECURITY_AUTHENTICATION = 0x5001 SO_SECURITY_ENCRYPTION_NETWORK = 0x5004 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x5002 SO_SELECT_ERR_QUEUE = 0x29 SO_SNDBUF = 0x1001 SO_SNDBUFFORCE = 0x100a SO_SNDLOWAT = 0x1000 SO_SNDTIMEO = 0x4000 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x23 SO_TIMESTAMPNS = 0x21 SO_TYPE = 0x1008 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x25 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TCFLSH = 0x20005407 TCGETA = 0x40125401 TCGETS = 0x40245408 TCGETS2 = 0x402c540c TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 TCSBRK = 0x20005405 TCSBRKP = 0x5425 TCSETA = 0x80125402 TCSETAF = 0x80125404 TCSETAW = 0x80125403 TCSETS = 0x80245409 TCSETS2 = 0x802c540d TCSETSF = 0x8024540b TCSETSF2 = 0x802c540f TCSETSW = 0x8024540a TCSETSW2 = 0x802c540e TCXONC = 0x20005406 TIOCCBRK = 0x2000747a TIOCCONS = 0x20007424 TIOCEXCL = 0x2000740d TIOCGDEV = 0x40045432 TIOCGETD = 0x40047400 TIOCGEXCL = 0x40045440 TIOCGICOUNT = 0x545d TIOCGLCKTRMIOS = 0x5456 TIOCGPGRP = 0x40047483 TIOCGPKT = 0x40045438 TIOCGPTLCK = 0x40045439 TIOCGPTN = 0x40047486 TIOCGRS485 = 0x40205441 TIOCGSERIAL = 0x541e TIOCGSID = 0x40047485 TIOCGSOFTCAR = 0x40047464 TIOCGWINSZ = 0x40087468 TIOCINQ = 0x4004667f TIOCLINUX = 0x541c TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMIWAIT = 0x545c TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_LOOP = 0x8000 TIOCM_OUT1 = 0x2000 TIOCM_OUT2 = 0x4000 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007484 TIOCSERCONFIG = 0x5453 TIOCSERGETLSR = 0x5459 TIOCSERGETMULTI = 0x545a TIOCSERGSTRUCT = 0x5458 TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 TIOCSER_TEMT = 0x1 TIOCSETD = 0x80047401 TIOCSIG = 0x80047488 TIOCSLCKTRMIOS = 0x5457 TIOCSPGRP = 0x80047482 TIOCSPTLCK = 0x80047487 TIOCSRS485 = 0xc0205442 TIOCSSERIAL = 0x541f TIOCSSOFTCAR = 0x80047465 TIOCSTART = 0x2000746e TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x20005437 TOSTOP = 0x100 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETBE = 0x400454df TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc VDISCARD = 0xd VDSUSP = 0xb VEOF = 0x4 VEOL = 0x5 VEOL2 = 0x6 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x4 VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x40 WRAP = 0x20000 WSTOPPED = 0x2 WUNTRACED = 0x2 XCASE = 0x4 XTABS = 0x1800 __TIOCFLUSH = 0x80047410 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EADV = syscall.Errno(0x53) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x25) EBADE = syscall.Errno(0x66) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x5d) EBADMSG = syscall.Errno(0x4c) EBADR = syscall.Errno(0x67) EBADRQC = syscall.Errno(0x6a) EBADSLT = syscall.Errno(0x6b) EBFONT = syscall.Errno(0x6d) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x7f) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x5e) ECOMM = syscall.Errno(0x55) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0x4e) EDEADLOCK = syscall.Errno(0x6c) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x58) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EHWPOISON = syscall.Errno(0x87) EIDRM = syscall.Errno(0x4d) EILSEQ = syscall.Errno(0x7a) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x78) EKEYEXPIRED = syscall.Errno(0x81) EKEYREJECTED = syscall.Errno(0x83) EKEYREVOKED = syscall.Errno(0x82) EL2HLT = syscall.Errno(0x65) EL2NSYNC = syscall.Errno(0x5f) EL3HLT = syscall.Errno(0x60) EL3RST = syscall.Errno(0x61) ELIBACC = syscall.Errno(0x72) ELIBBAD = syscall.Errno(0x70) ELIBEXEC = syscall.Errno(0x6e) ELIBMAX = syscall.Errno(0x7b) ELIBSCN = syscall.Errno(0x7c) ELNRNG = syscall.Errno(0x62) ELOOP = syscall.Errno(0x3e) EMEDIUMTYPE = syscall.Errno(0x7e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x57) ENAMETOOLONG = syscall.Errno(0x3f) ENAVAIL = syscall.Errno(0x77) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x69) ENOBUFS = syscall.Errno(0x37) ENOCSI = syscall.Errno(0x64) ENODATA = syscall.Errno(0x6f) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0x80) ENOLCK = syscall.Errno(0x4f) ENOLINK = syscall.Errno(0x52) ENOMEDIUM = syscall.Errno(0x7d) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x4b) ENONET = syscall.Errno(0x50) ENOPKG = syscall.Errno(0x71) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x4a) ENOSTR = syscall.Errno(0x48) ENOSYS = syscall.Errno(0x5a) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTNAM = syscall.Errno(0x76) ENOTRECOVERABLE = syscall.Errno(0x85) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x73) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x5c) EOWNERDEAD = syscall.Errno(0x84) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROTO = syscall.Errno(0x56) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x59) EREMOTE = syscall.Errno(0x47) EREMOTEIO = syscall.Errno(0x79) ERESTART = syscall.Errno(0x74) ERFKILL = syscall.Errno(0x86) EROFS = syscall.Errno(0x1e) ERREMOTE = syscall.Errno(0x51) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x54) ESTALE = syscall.Errno(0x46) ESTRPIPE = syscall.Errno(0x5b) ETIME = syscall.Errno(0x49) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x75) EUNATCH = syscall.Errno(0x63) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x68) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGLOST = syscall.Signal(0x1d) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x17) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x1d) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol", 48: "address already in use", 49: "cannot assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "transport endpoint is already connected", 57: "transport endpoint is not connected", 58: "cannot send after transport endpoint shutdown", 59: "too many references: cannot splice", 60: "connection timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disk quota exceeded", 70: "stale file handle", 71: "object is remote", 72: "device not a stream", 73: "timer expired", 74: "out of streams resources", 75: "no message of desired type", 76: "bad message", 77: "identifier removed", 78: "resource deadlock avoided", 79: "no locks available", 80: "machine is not on the network", 81: "unknown error 81", 82: "link has been severed", 83: "advertise error", 84: "srmount error", 85: "communication error on send", 86: "protocol error", 87: "multihop attempted", 88: "RFS specific error", 89: "remote address changed", 90: "function not implemented", 91: "streams pipe error", 92: "value too large for defined data type", 93: "file descriptor in bad state", 94: "channel number out of range", 95: "level 2 not synchronized", 96: "level 3 halted", 97: "level 3 reset", 98: "link number out of range", 99: "protocol driver not attached", 100: "no CSI structure available", 101: "level 2 halted", 102: "invalid exchange", 103: "invalid request descriptor", 104: "exchange full", 105: "no anode", 106: "invalid request code", 107: "invalid slot", 108: "file locking deadlock error", 109: "bad font file format", 110: "cannot exec a shared library directly", 111: "no data available", 112: "accessing a corrupted shared library", 113: "package not installed", 114: "can not access a needed shared library", 115: "name not unique on network", 116: "interrupted system call should be restarted", 117: "structure needs cleaning", 118: "not a XENIX named type file", 119: "no XENIX semaphores available", 120: "is a named type file", 121: "remote I/O error", 122: "invalid or incomplete multibyte or wide character", 123: "attempting to link in too many shared libraries", 124: ".lib section in a.out corrupted", 125: "no medium found", 126: "wrong medium type", 127: "operation canceled", 128: "required key not available", 129: "key has expired", 130: "key has been revoked", 131: "key was rejected by service", 132: "owner died", 133: "state not recoverable", 134: "operation not possible due to RF-kill", 135: "memory page has hardware error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "stopped (signal)", 18: "stopped", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "CPU time limit exceeded", 25: "file size limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window changed", 29: "resource lost", 30: "user defined signal 1", 31: "user defined signal 2", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_s390x.go0000644061062106075000000030303513172163421025555 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include -fsigned-char // Code generated by the command above; see README.md. DO NOT EDIT. // +build s390x,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d BLKRRPART = 0x125f BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0x5 F_GETLK64 = 0x5 F_GETOWN = 0x9 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x6 F_SETLK64 = 0x6 F_SETLKW = 0x7 F_SETLKW64 = 0x7 F_SETOWN = 0x8 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x8000 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_HUGETLB = 0x40000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x2000 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x4000 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_STACK = 0x20000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 O_CLOEXEC = 0x80000 O_CREAT = 0x40 O_DIRECT = 0x4000 O_DIRECTORY = 0x10000 O_DSYNC = 0x1000 O_EXCL = 0x80 O_FSYNC = 0x101000 O_LARGEFILE = 0x0 O_NDELAY = 0x800 O_NOATIME = 0x40000 O_NOCTTY = 0x100 O_NOFOLLOW = 0x20000 O_NONBLOCK = 0x800 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x101000 O_SYNC = 0x101000 O_TMPFILE = 0x410000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x2401 PERF_EVENT_IOC_ENABLE = 0x2400 PERF_EVENT_IOC_ID = 0x80082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = -0x1 PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_DISABLE_TE = 0x5010 PTRACE_ENABLE_TE = 0x5009 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GET_LAST_BREAK = 0x5006 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKDATA_AREA = 0x5003 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKTEXT_AREA = 0x5002 PTRACE_PEEKUSR = 0x3 PTRACE_PEEKUSR_AREA = 0x5000 PTRACE_PEEK_SYSTEM_CALL = 0x5007 PTRACE_POKEDATA = 0x5 PTRACE_POKEDATA_AREA = 0x5005 PTRACE_POKETEXT = 0x4 PTRACE_POKETEXT_AREA = 0x5004 PTRACE_POKEUSR = 0x6 PTRACE_POKEUSR_AREA = 0x5001 PTRACE_POKE_SYSTEM_CALL = 0x5008 PTRACE_PROT = 0x15 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SINGLEBLOCK = 0xc PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TE_ABORT_RAND = 0x5011 PTRACE_TRACEME = 0x0 PT_ACR0 = 0x90 PT_ACR1 = 0x94 PT_ACR10 = 0xb8 PT_ACR11 = 0xbc PT_ACR12 = 0xc0 PT_ACR13 = 0xc4 PT_ACR14 = 0xc8 PT_ACR15 = 0xcc PT_ACR2 = 0x98 PT_ACR3 = 0x9c PT_ACR4 = 0xa0 PT_ACR5 = 0xa4 PT_ACR6 = 0xa8 PT_ACR7 = 0xac PT_ACR8 = 0xb0 PT_ACR9 = 0xb4 PT_CR_10 = 0x168 PT_CR_11 = 0x170 PT_CR_9 = 0x160 PT_ENDREGS = 0x1af PT_FPC = 0xd8 PT_FPR0 = 0xe0 PT_FPR1 = 0xe8 PT_FPR10 = 0x130 PT_FPR11 = 0x138 PT_FPR12 = 0x140 PT_FPR13 = 0x148 PT_FPR14 = 0x150 PT_FPR15 = 0x158 PT_FPR2 = 0xf0 PT_FPR3 = 0xf8 PT_FPR4 = 0x100 PT_FPR5 = 0x108 PT_FPR6 = 0x110 PT_FPR7 = 0x118 PT_FPR8 = 0x120 PT_FPR9 = 0x128 PT_GPR0 = 0x10 PT_GPR1 = 0x18 PT_GPR10 = 0x60 PT_GPR11 = 0x68 PT_GPR12 = 0x70 PT_GPR13 = 0x78 PT_GPR14 = 0x80 PT_GPR15 = 0x88 PT_GPR2 = 0x20 PT_GPR3 = 0x28 PT_GPR4 = 0x30 PT_GPR5 = 0x38 PT_GPR6 = 0x40 PT_GPR7 = 0x48 PT_GPR8 = 0x50 PT_GPR9 = 0x58 PT_IEEE_IP = 0x1a8 PT_LASTOFF = 0x1a8 PT_ORIGGPR2 = 0xd0 PT_PSWADDR = 0x8 PT_PSWMASK = 0x0 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x8 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x7 RLIMIT_NPROC = 0x6 RLIMIT_RSS = 0x5 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x541b SIOCOUTQ = 0x5411 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1f SO_PRIORITY = 0xc SO_PROTOCOL = 0x26 SO_RCVBUF = 0x8 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x12 SO_RCVTIMEO = 0x14 SO_REUSEADDR = 0x2 SO_REUSEPORT = 0xf SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 TCSBRK = 0x5409 TCSBRKP = 0x5425 TCSETA = 0x5406 TCSETAF = 0x5408 TCSETAW = 0x5407 TCSETS = 0x5402 TCSETS2 = 0x402c542b TCSETSF = 0x5404 TCSETSF2 = 0x402c542d TCSETSW = 0x5403 TCSETSW2 = 0x402c542c TCSETX = 0x5433 TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c TIOCGDEV = 0x80045432 TIOCGETD = 0x5424 TIOCGEXCL = 0x80045440 TIOCGICOUNT = 0x545d TIOCGLCKTRMIOS = 0x5456 TIOCGPGRP = 0x540f TIOCGPKT = 0x80045438 TIOCGPTLCK = 0x80045439 TIOCGPTN = 0x80045430 TIOCGPTPEER = 0x5441 TIOCGRS485 = 0x542e TIOCGSERIAL = 0x541e TIOCGSID = 0x5429 TIOCGSOFTCAR = 0x5419 TIOCGWINSZ = 0x5413 TIOCINQ = 0x541b TIOCLINUX = 0x541c TIOCMBIC = 0x5417 TIOCMBIS = 0x5416 TIOCMGET = 0x5415 TIOCMIWAIT = 0x545c TIOCMSET = 0x5418 TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x5422 TIOCNXCL = 0x540d TIOCOUTQ = 0x5411 TIOCPKT = 0x5420 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x540e TIOCSERCONFIG = 0x5453 TIOCSERGETLSR = 0x5459 TIOCSERGETMULTI = 0x545a TIOCSERGSTRUCT = 0x5458 TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSLCKTRMIOS = 0x5457 TIOCSPGRP = 0x5410 TIOCSPTLCK = 0x40045431 TIOCSRS485 = 0x542f TIOCSSERIAL = 0x541f TIOCSSOFTCAR = 0x541a TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf TUNGETFILTER = 0x801054db TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETBE = 0x800454df TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x6 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x40 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x62) EADDRNOTAVAIL = syscall.Errno(0x63) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x61) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x72) EBADE = syscall.Errno(0x34) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x4d) EBADMSG = syscall.Errno(0x4a) EBADR = syscall.Errno(0x35) EBADRQC = syscall.Errno(0x38) EBADSLT = syscall.Errno(0x39) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x7d) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x2c) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x67) ECONNREFUSED = syscall.Errno(0x6f) ECONNRESET = syscall.Errno(0x68) EDEADLK = syscall.Errno(0x23) EDEADLOCK = syscall.Errno(0x23) EDESTADDRREQ = syscall.Errno(0x59) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x7a) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) EIDRM = syscall.Errno(0x2b) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x73) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x6a) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x78) EKEYEXPIRED = syscall.Errno(0x7f) EKEYREJECTED = syscall.Errno(0x81) EKEYREVOKED = syscall.Errno(0x80) EL2HLT = syscall.Errno(0x33) EL2NSYNC = syscall.Errno(0x2d) EL3HLT = syscall.Errno(0x2e) EL3RST = syscall.Errno(0x2f) ELIBACC = syscall.Errno(0x4f) ELIBBAD = syscall.Errno(0x50) ELIBEXEC = syscall.Errno(0x53) ELIBMAX = syscall.Errno(0x52) ELIBSCN = syscall.Errno(0x51) ELNRNG = syscall.Errno(0x30) ELOOP = syscall.Errno(0x28) EMEDIUMTYPE = syscall.Errno(0x7c) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x5a) EMULTIHOP = syscall.Errno(0x48) ENAMETOOLONG = syscall.Errno(0x24) ENAVAIL = syscall.Errno(0x77) ENETDOWN = syscall.Errno(0x64) ENETRESET = syscall.Errno(0x66) ENETUNREACH = syscall.Errno(0x65) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x37) ENOBUFS = syscall.Errno(0x69) ENOCSI = syscall.Errno(0x32) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0x7e) ENOLCK = syscall.Errno(0x25) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x7b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x2a) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x5c) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x26) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x6b) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x27) ENOTNAM = syscall.Errno(0x76) ENOTRECOVERABLE = syscall.Errno(0x83) ENOTSOCK = syscall.Errno(0x58) ENOTSUP = syscall.Errno(0x5f) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x4c) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x5f) EOVERFLOW = syscall.Errno(0x4b) EOWNERDEAD = syscall.Errno(0x82) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x60) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x5d) EPROTOTYPE = syscall.Errno(0x5b) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x4e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x79) ERESTART = syscall.Errno(0x55) ERFKILL = syscall.Errno(0x84) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x6c) ESOCKTNOSUPPORT = syscall.Errno(0x5e) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x74) ESTRPIPE = syscall.Errno(0x56) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x6e) ETOOMANYREFS = syscall.Errno(0x6d) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x75) EUNATCH = syscall.Errno(0x31) EUSERS = syscall.Errno(0x57) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x36) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0x7) SIGCHLD = syscall.Signal(0x11) SIGCLD = syscall.Signal(0x11) SIGCONT = syscall.Signal(0x12) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x1d) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x1d) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x1e) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTKFLT = syscall.Signal(0x10) SIGSTOP = syscall.Signal(0x13) SIGSYS = syscall.Signal(0x1f) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x14) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x17) SIGUSR1 = syscall.Signal(0xa) SIGUSR2 = syscall.Signal(0xc) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "resource deadlock avoided", 36: "file name too long", 37: "no locks available", 38: "function not implemented", 39: "directory not empty", 40: "too many levels of symbolic links", 42: "no message of desired type", 43: "identifier removed", 44: "channel number out of range", 45: "level 2 not synchronized", 46: "level 3 halted", 47: "level 3 reset", 48: "link number out of range", 49: "protocol driver not attached", 50: "no CSI structure available", 51: "level 2 halted", 52: "invalid exchange", 53: "invalid request descriptor", 54: "exchange full", 55: "no anode", 56: "invalid request code", 57: "invalid slot", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "multihop attempted", 73: "RFS specific error", 74: "bad message", 75: "value too large for defined data type", 76: "name not unique on network", 77: "file descriptor in bad state", 78: "remote address changed", 79: "can not access a needed shared library", 80: "accessing a corrupted shared library", 81: ".lib section in a.out corrupted", 82: "attempting to link in too many shared libraries", 83: "cannot exec a shared library directly", 84: "invalid or incomplete multibyte or wide character", 85: "interrupted system call should be restarted", 86: "streams pipe error", 87: "too many users", 88: "socket operation on non-socket", 89: "destination address required", 90: "message too long", 91: "protocol wrong type for socket", 92: "protocol not available", 93: "protocol not supported", 94: "socket type not supported", 95: "operation not supported", 96: "protocol family not supported", 97: "address family not supported by protocol", 98: "address already in use", 99: "cannot assign requested address", 100: "network is down", 101: "network is unreachable", 102: "network dropped connection on reset", 103: "software caused connection abort", 104: "connection reset by peer", 105: "no buffer space available", 106: "transport endpoint is already connected", 107: "transport endpoint is not connected", 108: "cannot send after transport endpoint shutdown", 109: "too many references: cannot splice", 110: "connection timed out", 111: "connection refused", 112: "host is down", 113: "no route to host", 114: "operation already in progress", 115: "operation now in progress", 116: "stale file handle", 117: "structure needs cleaning", 118: "not a XENIX named type file", 119: "no XENIX semaphores available", 120: "is a named type file", 121: "remote I/O error", 122: "disk quota exceeded", 123: "no medium found", 124: "wrong medium type", 125: "operation canceled", 126: "required key not available", 127: "key has expired", 128: "key has been revoked", 129: "key was rejected by service", 130: "owner died", 131: "state not recoverable", 132: "operation not possible due to RF-kill", 133: "memory page has hardware error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "bus error", 8: "floating point exception", 9: "killed", 10: "user defined signal 1", 11: "segmentation fault", 12: "user defined signal 2", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "stack fault", 17: "child exited", 18: "continued", 19: "stopped (signal)", 20: "stopped", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "urgent I/O condition", 24: "CPU time limit exceeded", 25: "file size limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window changed", 29: "I/O possible", 30: "power failure", 31: "bad system call", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_ppc64le.go0000644061062106075000000030324013172163421026142 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include // Code generated by the command above; see README.md. DO NOT EDIT. // +build ppc64le,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x17 B110 = 0x3 B115200 = 0x11 B1152000 = 0x18 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x19 B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x1a B230400 = 0x12 B2400 = 0xb B2500000 = 0x1b B300 = 0x7 B3000000 = 0x1c B3500000 = 0x1d B38400 = 0xf B4000000 = 0x1e B460800 = 0x13 B4800 = 0xc B50 = 0x1 B500000 = 0x14 B57600 = 0x10 B576000 = 0x15 B600 = 0x8 B75 = 0x2 B921600 = 0x16 B9600 = 0xd BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d BLKRRPART = 0x2000125f BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 BOTHER = 0x1f BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0xff CBAUDEX = 0x0 CFLUSH = 0xf CIBAUD = 0xff0000 CLOCAL = 0x8000 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 CR3 = 0x3000 CRDLY = 0x3000 CREAD = 0x800 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIGNAL = 0xff CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0x5 F_GETLK64 = 0xc F_GETOWN = 0x9 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x6 F_SETLK64 = 0xd F_SETLKW = 0x7 F_SETLKW64 = 0xe F_SETOWN = 0x8 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x4000 IBSHIFT = 0x10 ICANON = 0x100 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x400 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x80 ISTRIP = 0x20 IUCLC = 0x1000 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_HUGETLB = 0x40000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x80 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x40 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_STACK = 0x20000 MAP_TYPE = 0xf MCL_CURRENT = 0x2000 MCL_FUTURE = 0x4000 MCL_ONFAULT = 0x8000 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NL2 = 0x200 NL3 = 0x300 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x300 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80000000 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x4 ONLCR = 0x2 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 O_CLOEXEC = 0x80000 O_CREAT = 0x40 O_DIRECT = 0x20000 O_DIRECTORY = 0x4000 O_DSYNC = 0x1000 O_EXCL = 0x80 O_FSYNC = 0x101000 O_LARGEFILE = 0x0 O_NDELAY = 0x800 O_NOATIME = 0x40000 O_NOCTTY = 0x100 O_NOFOLLOW = 0x8000 O_NONBLOCK = 0x800 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x101000 O_SYNC = 0x101000 O_TMPFILE = 0x404000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x1000 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PERF_EVENT_IOC_DISABLE = 0x20002401 PERF_EVENT_IOC_ENABLE = 0x20002400 PERF_EVENT_IOC_ID = 0x40082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80082406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_SAO = 0x10 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = -0x1 PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETEVRREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS = 0xc PTRACE_GETREGS64 = 0x16 PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GETVRREGS = 0x12 PTRACE_GETVSRREGS = 0x1b PTRACE_GET_DEBUGREG = 0x19 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETEVRREGS = 0x15 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGS64 = 0x17 PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SETVRREGS = 0x13 PTRACE_SETVSRREGS = 0x1c PTRACE_SET_DEBUGREG = 0x1a PTRACE_SINGLEBLOCK = 0x100 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 PT_CCR = 0x26 PT_CTR = 0x23 PT_DAR = 0x29 PT_DSCR = 0x2c PT_DSISR = 0x2a PT_FPR0 = 0x30 PT_FPSCR = 0x50 PT_LNK = 0x24 PT_MSR = 0x21 PT_NIP = 0x20 PT_ORIG_R3 = 0x22 PT_R0 = 0x0 PT_R1 = 0x1 PT_R10 = 0xa PT_R11 = 0xb PT_R12 = 0xc PT_R13 = 0xd PT_R14 = 0xe PT_R15 = 0xf PT_R16 = 0x10 PT_R17 = 0x11 PT_R18 = 0x12 PT_R19 = 0x13 PT_R2 = 0x2 PT_R20 = 0x14 PT_R21 = 0x15 PT_R22 = 0x16 PT_R23 = 0x17 PT_R24 = 0x18 PT_R25 = 0x19 PT_R26 = 0x1a PT_R27 = 0x1b PT_R28 = 0x1c PT_R29 = 0x1d PT_R3 = 0x3 PT_R30 = 0x1e PT_R31 = 0x1f PT_R4 = 0x4 PT_R5 = 0x5 PT_R6 = 0x6 PT_R7 = 0x7 PT_R8 = 0x8 PT_R9 = 0x9 PT_REGS_COUNT = 0x2c PT_RESULT = 0x2b PT_SOFTE = 0x27 PT_TRAP = 0x28 PT_VR0 = 0x52 PT_VRSAVE = 0x94 PT_VSCR = 0x93 PT_VSR0 = 0x96 PT_VSR31 = 0xd4 PT_XER = 0x25 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x8 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x7 RLIMIT_NPROC = 0x6 RLIMIT_RSS = 0x5 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x4004667f SIOCOUTQ = 0x40047473 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x14 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x15 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1f SO_PRIORITY = 0xc SO_PROTOCOL = 0x26 SO_RCVBUF = 0x8 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x10 SO_RCVTIMEO = 0x12 SO_REUSEADDR = 0x2 SO_REUSEPORT = 0xf SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x11 SO_SNDTIMEO = 0x13 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0xc00 TABDLY = 0xc00 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x2000741f TCGETA = 0x40147417 TCGETS = 0x402c7413 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 TCSBRK = 0x2000741d TCSBRKP = 0x5425 TCSETA = 0x80147418 TCSETAF = 0x8014741c TCSETAW = 0x80147419 TCSETS = 0x802c7414 TCSETSF = 0x802c7416 TCSETSW = 0x802c7415 TCXONC = 0x2000741e TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c TIOCGDEV = 0x40045432 TIOCGETC = 0x40067412 TIOCGETD = 0x5424 TIOCGETP = 0x40067408 TIOCGEXCL = 0x40045440 TIOCGICOUNT = 0x545d TIOCGLCKTRMIOS = 0x5456 TIOCGLTC = 0x40067474 TIOCGPGRP = 0x40047477 TIOCGPKT = 0x40045438 TIOCGPTLCK = 0x40045439 TIOCGPTN = 0x40045430 TIOCGPTPEER = 0x20005441 TIOCGRS485 = 0x542e TIOCGSERIAL = 0x541e TIOCGSID = 0x5429 TIOCGSOFTCAR = 0x5419 TIOCGWINSZ = 0x40087468 TIOCINQ = 0x4004667f TIOCLINUX = 0x541c TIOCMBIC = 0x5417 TIOCMBIS = 0x5416 TIOCMGET = 0x5415 TIOCMIWAIT = 0x545c TIOCMSET = 0x5418 TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_LOOP = 0x8000 TIOCM_OUT1 = 0x2000 TIOCM_OUT2 = 0x4000 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x5422 TIOCNXCL = 0x540d TIOCOUTQ = 0x40047473 TIOCPKT = 0x5420 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x540e TIOCSERCONFIG = 0x5453 TIOCSERGETLSR = 0x5459 TIOCSERGETMULTI = 0x545a TIOCSERGSTRUCT = 0x5458 TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 TIOCSER_TEMT = 0x1 TIOCSETC = 0x80067411 TIOCSETD = 0x5423 TIOCSETN = 0x8006740a TIOCSETP = 0x80067409 TIOCSIG = 0x80045436 TIOCSLCKTRMIOS = 0x5457 TIOCSLTC = 0x80067475 TIOCSPGRP = 0x80047476 TIOCSPTLCK = 0x80045431 TIOCSRS485 = 0x542f TIOCSSERIAL = 0x541f TIOCSSOFTCAR = 0x541a TIOCSTART = 0x2000746e TIOCSTI = 0x5412 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x400000 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETBE = 0x400454df TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0x10 VEOF = 0x4 VEOL = 0x6 VEOL2 = 0x8 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x5 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xb VSTART = 0xd VSTOP = 0xe VSUSP = 0xc VSWTC = 0x9 VT0 = 0x0 VT1 = 0x10000 VTDLY = 0x10000 VTIME = 0x7 VWERASE = 0xa WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x40 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4000 XTABS = 0xc00 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x62) EADDRNOTAVAIL = syscall.Errno(0x63) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x61) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x72) EBADE = syscall.Errno(0x34) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x4d) EBADMSG = syscall.Errno(0x4a) EBADR = syscall.Errno(0x35) EBADRQC = syscall.Errno(0x38) EBADSLT = syscall.Errno(0x39) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x7d) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x2c) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x67) ECONNREFUSED = syscall.Errno(0x6f) ECONNRESET = syscall.Errno(0x68) EDEADLK = syscall.Errno(0x23) EDEADLOCK = syscall.Errno(0x3a) EDESTADDRREQ = syscall.Errno(0x59) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x7a) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) EIDRM = syscall.Errno(0x2b) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x73) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x6a) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x78) EKEYEXPIRED = syscall.Errno(0x7f) EKEYREJECTED = syscall.Errno(0x81) EKEYREVOKED = syscall.Errno(0x80) EL2HLT = syscall.Errno(0x33) EL2NSYNC = syscall.Errno(0x2d) EL3HLT = syscall.Errno(0x2e) EL3RST = syscall.Errno(0x2f) ELIBACC = syscall.Errno(0x4f) ELIBBAD = syscall.Errno(0x50) ELIBEXEC = syscall.Errno(0x53) ELIBMAX = syscall.Errno(0x52) ELIBSCN = syscall.Errno(0x51) ELNRNG = syscall.Errno(0x30) ELOOP = syscall.Errno(0x28) EMEDIUMTYPE = syscall.Errno(0x7c) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x5a) EMULTIHOP = syscall.Errno(0x48) ENAMETOOLONG = syscall.Errno(0x24) ENAVAIL = syscall.Errno(0x77) ENETDOWN = syscall.Errno(0x64) ENETRESET = syscall.Errno(0x66) ENETUNREACH = syscall.Errno(0x65) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x37) ENOBUFS = syscall.Errno(0x69) ENOCSI = syscall.Errno(0x32) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0x7e) ENOLCK = syscall.Errno(0x25) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x7b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x2a) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x5c) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x26) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x6b) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x27) ENOTNAM = syscall.Errno(0x76) ENOTRECOVERABLE = syscall.Errno(0x83) ENOTSOCK = syscall.Errno(0x58) ENOTSUP = syscall.Errno(0x5f) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x4c) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x5f) EOVERFLOW = syscall.Errno(0x4b) EOWNERDEAD = syscall.Errno(0x82) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x60) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x5d) EPROTOTYPE = syscall.Errno(0x5b) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x4e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x79) ERESTART = syscall.Errno(0x55) ERFKILL = syscall.Errno(0x84) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x6c) ESOCKTNOSUPPORT = syscall.Errno(0x5e) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x74) ESTRPIPE = syscall.Errno(0x56) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x6e) ETOOMANYREFS = syscall.Errno(0x6d) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x75) EUNATCH = syscall.Errno(0x31) EUSERS = syscall.Errno(0x57) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x36) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0x7) SIGCHLD = syscall.Signal(0x11) SIGCLD = syscall.Signal(0x11) SIGCONT = syscall.Signal(0x12) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x1d) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x1d) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x1e) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTKFLT = syscall.Signal(0x10) SIGSTOP = syscall.Signal(0x13) SIGSYS = syscall.Signal(0x1f) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x14) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x17) SIGUSR1 = syscall.Signal(0xa) SIGUSR2 = syscall.Signal(0xc) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "resource deadlock avoided", 36: "file name too long", 37: "no locks available", 38: "function not implemented", 39: "directory not empty", 40: "too many levels of symbolic links", 42: "no message of desired type", 43: "identifier removed", 44: "channel number out of range", 45: "level 2 not synchronized", 46: "level 3 halted", 47: "level 3 reset", 48: "link number out of range", 49: "protocol driver not attached", 50: "no CSI structure available", 51: "level 2 halted", 52: "invalid exchange", 53: "invalid request descriptor", 54: "exchange full", 55: "no anode", 56: "invalid request code", 57: "invalid slot", 58: "file locking deadlock error", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "multihop attempted", 73: "RFS specific error", 74: "bad message", 75: "value too large for defined data type", 76: "name not unique on network", 77: "file descriptor in bad state", 78: "remote address changed", 79: "can not access a needed shared library", 80: "accessing a corrupted shared library", 81: ".lib section in a.out corrupted", 82: "attempting to link in too many shared libraries", 83: "cannot exec a shared library directly", 84: "invalid or incomplete multibyte or wide character", 85: "interrupted system call should be restarted", 86: "streams pipe error", 87: "too many users", 88: "socket operation on non-socket", 89: "destination address required", 90: "message too long", 91: "protocol wrong type for socket", 92: "protocol not available", 93: "protocol not supported", 94: "socket type not supported", 95: "operation not supported", 96: "protocol family not supported", 97: "address family not supported by protocol", 98: "address already in use", 99: "cannot assign requested address", 100: "network is down", 101: "network is unreachable", 102: "network dropped connection on reset", 103: "software caused connection abort", 104: "connection reset by peer", 105: "no buffer space available", 106: "transport endpoint is already connected", 107: "transport endpoint is not connected", 108: "cannot send after transport endpoint shutdown", 109: "too many references: cannot splice", 110: "connection timed out", 111: "connection refused", 112: "host is down", 113: "no route to host", 114: "operation already in progress", 115: "operation now in progress", 116: "stale file handle", 117: "structure needs cleaning", 118: "not a XENIX named type file", 119: "no XENIX semaphores available", 120: "is a named type file", 121: "remote I/O error", 122: "disk quota exceeded", 123: "no medium found", 124: "wrong medium type", 125: "operation canceled", 126: "required key not available", 127: "key has expired", 128: "key has been revoked", 129: "key was rejected by service", 130: "owner died", 131: "state not recoverable", 132: "operation not possible due to RF-kill", 133: "memory page has hardware error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "bus error", 8: "floating point exception", 9: "killed", 10: "user defined signal 1", 11: "segmentation fault", 12: "user defined signal 2", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "stack fault", 17: "child exited", 18: "continued", 19: "stopped (signal)", 20: "stopped", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "urgent I/O condition", 24: "CPU time limit exceeded", 25: "file size limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window changed", 29: "I/O possible", 30: "power failure", 31: "bad system call", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_ppc64.go0000644061062106075000000030323613172163421025626 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include // Code generated by the command above; see README.md. DO NOT EDIT. // +build ppc64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x17 B110 = 0x3 B115200 = 0x11 B1152000 = 0x18 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x19 B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x1a B230400 = 0x12 B2400 = 0xb B2500000 = 0x1b B300 = 0x7 B3000000 = 0x1c B3500000 = 0x1d B38400 = 0xf B4000000 = 0x1e B460800 = 0x13 B4800 = 0xc B50 = 0x1 B500000 = 0x14 B57600 = 0x10 B576000 = 0x15 B600 = 0x8 B75 = 0x2 B921600 = 0x16 B9600 = 0xd BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d BLKRRPART = 0x2000125f BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 BOTHER = 0x1f BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0xff CBAUDEX = 0x0 CFLUSH = 0xf CIBAUD = 0xff0000 CLOCAL = 0x8000 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 CR3 = 0x3000 CRDLY = 0x3000 CREAD = 0x800 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIGNAL = 0xff CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0x5 F_GETLK64 = 0xc F_GETOWN = 0x9 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x6 F_SETLK64 = 0xd F_SETLKW = 0x7 F_SETLKW64 = 0xe F_SETOWN = 0x8 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x4000 IBSHIFT = 0x10 ICANON = 0x100 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x400 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x80 ISTRIP = 0x20 IUCLC = 0x1000 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_HUGETLB = 0x40000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x80 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x40 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_STACK = 0x20000 MAP_TYPE = 0xf MCL_CURRENT = 0x2000 MCL_FUTURE = 0x4000 MCL_ONFAULT = 0x8000 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NL2 = 0x200 NL3 = 0x300 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x300 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80000000 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x4 ONLCR = 0x2 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 O_CLOEXEC = 0x80000 O_CREAT = 0x40 O_DIRECT = 0x20000 O_DIRECTORY = 0x4000 O_DSYNC = 0x1000 O_EXCL = 0x80 O_FSYNC = 0x101000 O_LARGEFILE = 0x0 O_NDELAY = 0x800 O_NOATIME = 0x40000 O_NOCTTY = 0x100 O_NOFOLLOW = 0x8000 O_NONBLOCK = 0x800 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x101000 O_SYNC = 0x101000 O_TMPFILE = 0x404000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x1000 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PERF_EVENT_IOC_DISABLE = 0x20002401 PERF_EVENT_IOC_ENABLE = 0x20002400 PERF_EVENT_IOC_ID = 0x40082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80082406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_SAO = 0x10 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = -0x1 PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETEVRREGS = 0x14 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS = 0xc PTRACE_GETREGS64 = 0x16 PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GETVRREGS = 0x12 PTRACE_GETVSRREGS = 0x1b PTRACE_GET_DEBUGREG = 0x19 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETEVRREGS = 0x15 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGS64 = 0x17 PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SETVRREGS = 0x13 PTRACE_SETVSRREGS = 0x1c PTRACE_SET_DEBUGREG = 0x1a PTRACE_SINGLEBLOCK = 0x100 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 PT_CCR = 0x26 PT_CTR = 0x23 PT_DAR = 0x29 PT_DSCR = 0x2c PT_DSISR = 0x2a PT_FPR0 = 0x30 PT_FPSCR = 0x50 PT_LNK = 0x24 PT_MSR = 0x21 PT_NIP = 0x20 PT_ORIG_R3 = 0x22 PT_R0 = 0x0 PT_R1 = 0x1 PT_R10 = 0xa PT_R11 = 0xb PT_R12 = 0xc PT_R13 = 0xd PT_R14 = 0xe PT_R15 = 0xf PT_R16 = 0x10 PT_R17 = 0x11 PT_R18 = 0x12 PT_R19 = 0x13 PT_R2 = 0x2 PT_R20 = 0x14 PT_R21 = 0x15 PT_R22 = 0x16 PT_R23 = 0x17 PT_R24 = 0x18 PT_R25 = 0x19 PT_R26 = 0x1a PT_R27 = 0x1b PT_R28 = 0x1c PT_R29 = 0x1d PT_R3 = 0x3 PT_R30 = 0x1e PT_R31 = 0x1f PT_R4 = 0x4 PT_R5 = 0x5 PT_R6 = 0x6 PT_R7 = 0x7 PT_R8 = 0x8 PT_R9 = 0x9 PT_REGS_COUNT = 0x2c PT_RESULT = 0x2b PT_SOFTE = 0x27 PT_TRAP = 0x28 PT_VR0 = 0x52 PT_VRSAVE = 0x94 PT_VSCR = 0x93 PT_VSR0 = 0x96 PT_VSR31 = 0xd4 PT_XER = 0x25 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x8 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x7 RLIMIT_NPROC = 0x6 RLIMIT_RSS = 0x5 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x4004667f SIOCOUTQ = 0x40047473 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x14 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x15 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1f SO_PRIORITY = 0xc SO_PROTOCOL = 0x26 SO_RCVBUF = 0x8 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x10 SO_RCVTIMEO = 0x12 SO_REUSEADDR = 0x2 SO_REUSEPORT = 0xf SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x11 SO_SNDTIMEO = 0x13 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0xc00 TABDLY = 0xc00 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x2000741f TCGETA = 0x40147417 TCGETS = 0x402c7413 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 TCSBRK = 0x2000741d TCSBRKP = 0x5425 TCSETA = 0x80147418 TCSETAF = 0x8014741c TCSETAW = 0x80147419 TCSETS = 0x802c7414 TCSETSF = 0x802c7416 TCSETSW = 0x802c7415 TCXONC = 0x2000741e TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c TIOCGDEV = 0x40045432 TIOCGETC = 0x40067412 TIOCGETD = 0x5424 TIOCGETP = 0x40067408 TIOCGEXCL = 0x40045440 TIOCGICOUNT = 0x545d TIOCGLCKTRMIOS = 0x5456 TIOCGLTC = 0x40067474 TIOCGPGRP = 0x40047477 TIOCGPKT = 0x40045438 TIOCGPTLCK = 0x40045439 TIOCGPTN = 0x40045430 TIOCGPTPEER = 0x20005441 TIOCGRS485 = 0x542e TIOCGSERIAL = 0x541e TIOCGSID = 0x5429 TIOCGSOFTCAR = 0x5419 TIOCGWINSZ = 0x40087468 TIOCINQ = 0x4004667f TIOCLINUX = 0x541c TIOCMBIC = 0x5417 TIOCMBIS = 0x5416 TIOCMGET = 0x5415 TIOCMIWAIT = 0x545c TIOCMSET = 0x5418 TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_LOOP = 0x8000 TIOCM_OUT1 = 0x2000 TIOCM_OUT2 = 0x4000 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x5422 TIOCNXCL = 0x540d TIOCOUTQ = 0x40047473 TIOCPKT = 0x5420 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x540e TIOCSERCONFIG = 0x5453 TIOCSERGETLSR = 0x5459 TIOCSERGETMULTI = 0x545a TIOCSERGSTRUCT = 0x5458 TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 TIOCSER_TEMT = 0x1 TIOCSETC = 0x80067411 TIOCSETD = 0x5423 TIOCSETN = 0x8006740a TIOCSETP = 0x80067409 TIOCSIG = 0x80045436 TIOCSLCKTRMIOS = 0x5457 TIOCSLTC = 0x80067475 TIOCSPGRP = 0x80047476 TIOCSPTLCK = 0x80045431 TIOCSRS485 = 0x542f TIOCSSERIAL = 0x541f TIOCSSOFTCAR = 0x541a TIOCSTART = 0x2000746e TIOCSTI = 0x5412 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x400000 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETBE = 0x400454df TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0x10 VEOF = 0x4 VEOL = 0x6 VEOL2 = 0x8 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x5 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xb VSTART = 0xd VSTOP = 0xe VSUSP = 0xc VSWTC = 0x9 VT0 = 0x0 VT1 = 0x10000 VTDLY = 0x10000 VTIME = 0x7 VWERASE = 0xa WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x40 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4000 XTABS = 0xc00 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x62) EADDRNOTAVAIL = syscall.Errno(0x63) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x61) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x72) EBADE = syscall.Errno(0x34) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x4d) EBADMSG = syscall.Errno(0x4a) EBADR = syscall.Errno(0x35) EBADRQC = syscall.Errno(0x38) EBADSLT = syscall.Errno(0x39) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x7d) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x2c) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x67) ECONNREFUSED = syscall.Errno(0x6f) ECONNRESET = syscall.Errno(0x68) EDEADLK = syscall.Errno(0x23) EDEADLOCK = syscall.Errno(0x3a) EDESTADDRREQ = syscall.Errno(0x59) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x7a) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) EIDRM = syscall.Errno(0x2b) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x73) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x6a) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x78) EKEYEXPIRED = syscall.Errno(0x7f) EKEYREJECTED = syscall.Errno(0x81) EKEYREVOKED = syscall.Errno(0x80) EL2HLT = syscall.Errno(0x33) EL2NSYNC = syscall.Errno(0x2d) EL3HLT = syscall.Errno(0x2e) EL3RST = syscall.Errno(0x2f) ELIBACC = syscall.Errno(0x4f) ELIBBAD = syscall.Errno(0x50) ELIBEXEC = syscall.Errno(0x53) ELIBMAX = syscall.Errno(0x52) ELIBSCN = syscall.Errno(0x51) ELNRNG = syscall.Errno(0x30) ELOOP = syscall.Errno(0x28) EMEDIUMTYPE = syscall.Errno(0x7c) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x5a) EMULTIHOP = syscall.Errno(0x48) ENAMETOOLONG = syscall.Errno(0x24) ENAVAIL = syscall.Errno(0x77) ENETDOWN = syscall.Errno(0x64) ENETRESET = syscall.Errno(0x66) ENETUNREACH = syscall.Errno(0x65) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x37) ENOBUFS = syscall.Errno(0x69) ENOCSI = syscall.Errno(0x32) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0x7e) ENOLCK = syscall.Errno(0x25) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x7b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x2a) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x5c) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x26) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x6b) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x27) ENOTNAM = syscall.Errno(0x76) ENOTRECOVERABLE = syscall.Errno(0x83) ENOTSOCK = syscall.Errno(0x58) ENOTSUP = syscall.Errno(0x5f) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x4c) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x5f) EOVERFLOW = syscall.Errno(0x4b) EOWNERDEAD = syscall.Errno(0x82) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x60) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x5d) EPROTOTYPE = syscall.Errno(0x5b) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x4e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x79) ERESTART = syscall.Errno(0x55) ERFKILL = syscall.Errno(0x84) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x6c) ESOCKTNOSUPPORT = syscall.Errno(0x5e) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x74) ESTRPIPE = syscall.Errno(0x56) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x6e) ETOOMANYREFS = syscall.Errno(0x6d) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x75) EUNATCH = syscall.Errno(0x31) EUSERS = syscall.Errno(0x57) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x36) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0x7) SIGCHLD = syscall.Signal(0x11) SIGCLD = syscall.Signal(0x11) SIGCONT = syscall.Signal(0x12) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x1d) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x1d) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x1e) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTKFLT = syscall.Signal(0x10) SIGSTOP = syscall.Signal(0x13) SIGSYS = syscall.Signal(0x1f) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x14) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x17) SIGUSR1 = syscall.Signal(0xa) SIGUSR2 = syscall.Signal(0xc) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "resource deadlock avoided", 36: "file name too long", 37: "no locks available", 38: "function not implemented", 39: "directory not empty", 40: "too many levels of symbolic links", 42: "no message of desired type", 43: "identifier removed", 44: "channel number out of range", 45: "level 2 not synchronized", 46: "level 3 halted", 47: "level 3 reset", 48: "link number out of range", 49: "protocol driver not attached", 50: "no CSI structure available", 51: "level 2 halted", 52: "invalid exchange", 53: "invalid request descriptor", 54: "exchange full", 55: "no anode", 56: "invalid request code", 57: "invalid slot", 58: "file locking deadlock error", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "multihop attempted", 73: "RFS specific error", 74: "bad message", 75: "value too large for defined data type", 76: "name not unique on network", 77: "file descriptor in bad state", 78: "remote address changed", 79: "can not access a needed shared library", 80: "accessing a corrupted shared library", 81: ".lib section in a.out corrupted", 82: "attempting to link in too many shared libraries", 83: "cannot exec a shared library directly", 84: "invalid or incomplete multibyte or wide character", 85: "interrupted system call should be restarted", 86: "streams pipe error", 87: "too many users", 88: "socket operation on non-socket", 89: "destination address required", 90: "message too long", 91: "protocol wrong type for socket", 92: "protocol not available", 93: "protocol not supported", 94: "socket type not supported", 95: "operation not supported", 96: "protocol family not supported", 97: "address family not supported by protocol", 98: "address already in use", 99: "cannot assign requested address", 100: "network is down", 101: "network is unreachable", 102: "network dropped connection on reset", 103: "software caused connection abort", 104: "connection reset by peer", 105: "no buffer space available", 106: "transport endpoint is already connected", 107: "transport endpoint is not connected", 108: "cannot send after transport endpoint shutdown", 109: "too many references: cannot splice", 110: "connection timed out", 111: "connection refused", 112: "host is down", 113: "no route to host", 114: "operation already in progress", 115: "operation now in progress", 116: "stale file handle", 117: "structure needs cleaning", 118: "not a XENIX named type file", 119: "no XENIX semaphores available", 120: "is a named type file", 121: "remote I/O error", 122: "disk quota exceeded", 123: "no medium found", 124: "wrong medium type", 125: "operation canceled", 126: "required key not available", 127: "key has expired", 128: "key has been revoked", 129: "key was rejected by service", 130: "owner died", 131: "state not recoverable", 132: "operation not possible due to RF-kill", 133: "memory page has hardware error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "bus error", 8: "floating point exception", 9: "killed", 10: "user defined signal 1", 11: "segmentation fault", 12: "user defined signal 2", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "stack fault", 17: "child exited", 18: "continued", 19: "stopped (signal)", 20: "stopped", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "urgent I/O condition", 24: "CPU time limit exceeded", 25: "file size limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window changed", 29: "I/O possible", 30: "power failure", 31: "bad system call", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_mipsle.go0000644061062106075000000027665613172163421026202 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include // Code generated by the command above; see README.md. DO NOT EDIT. // +build mipsle,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x40041270 BLKBSZSET = 0x80041271 BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40041272 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d BLKRRPART = 0x2000125f BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0x21 F_GETLK64 = 0x21 F_GETOWN = 0x17 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x22 F_SETLK64 = 0x22 F_SETLKW = 0x23 F_SETLKW64 = 0x23 F_SETOWN = 0x18 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x100 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x80 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x800 MAP_ANONYMOUS = 0x800 MAP_DENYWRITE = 0x2000 MAP_EXECUTABLE = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x1000 MAP_HUGETLB = 0x80000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x8000 MAP_NONBLOCK = 0x20000 MAP_NORESERVE = 0x400 MAP_POPULATE = 0x10000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x800 MAP_SHARED = 0x1 MAP_STACK = 0x40000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x1000 O_CLOEXEC = 0x80000 O_CREAT = 0x100 O_DIRECT = 0x8000 O_DIRECTORY = 0x10000 O_DSYNC = 0x10 O_EXCL = 0x400 O_FSYNC = 0x4010 O_LARGEFILE = 0x2000 O_NDELAY = 0x80 O_NOATIME = 0x40000 O_NOCTTY = 0x800 O_NOFOLLOW = 0x20000 O_NONBLOCK = 0x80 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x4010 O_SYNC = 0x4010 O_TMPFILE = 0x410000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x20002401 PERF_EVENT_IOC_ENABLE = 0x20002400 PERF_EVENT_IOC_ID = 0x40042407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80042406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = 0xffffffff PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 PTRACE_GET_WATCH_REGS = 0xd0 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKDATA_3264 = 0xc1 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKTEXT_3264 = 0xc0 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKEDATA_3264 = 0xc3 PTRACE_POKETEXT = 0x4 PTRACE_POKETEXT_3264 = 0xc2 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SET_THREAD_AREA = 0x1a PTRACE_SET_WATCH_REGS = 0xd1 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x9 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x5 RLIMIT_NPROC = 0x8 RLIMIT_RSS = 0x7 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x40047307 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x40047309 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x467f SIOCOUTQ = 0x7472 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x80047308 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x1 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x80 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x2 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1009 SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x20 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1e SO_PRIORITY = 0xc SO_PROTOCOL = 0x1028 SO_RCVBUF = 0x1002 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x1001 SO_SNDBUFFORCE = 0x1f SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_STYLE = 0x1008 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x1008 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d TCGETS2 = 0x4030542a TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x5410 TCSBRK = 0x5405 TCSBRKP = 0x5486 TCSETA = 0x5402 TCSETAF = 0x5404 TCSETAW = 0x5403 TCSETS = 0x540e TCSETS2 = 0x8030542b TCSETSF = 0x5410 TCSETSF2 = 0x8030542d TCSETSW = 0x540f TCSETSW2 = 0x8030542c TCXONC = 0x5406 TIOCCBRK = 0x5428 TIOCCONS = 0x80047478 TIOCEXCL = 0x740d TIOCGDEV = 0x40045432 TIOCGETD = 0x7400 TIOCGETP = 0x7408 TIOCGEXCL = 0x40045440 TIOCGICOUNT = 0x5492 TIOCGLCKTRMIOS = 0x548b TIOCGLTC = 0x7474 TIOCGPGRP = 0x40047477 TIOCGPKT = 0x40045438 TIOCGPTLCK = 0x40045439 TIOCGPTN = 0x40045430 TIOCGPTPEER = 0x20005441 TIOCGRS485 = 0x4020542e TIOCGSERIAL = 0x5484 TIOCGSID = 0x7416 TIOCGSOFTCAR = 0x5481 TIOCGWINSZ = 0x40087468 TIOCINQ = 0x467f TIOCLINUX = 0x5483 TIOCMBIC = 0x741c TIOCMBIS = 0x741b TIOCMGET = 0x741d TIOCMIWAIT = 0x5491 TIOCMSET = 0x741a TIOCM_CAR = 0x100 TIOCM_CD = 0x100 TIOCM_CTS = 0x40 TIOCM_DSR = 0x400 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x200 TIOCM_RNG = 0x200 TIOCM_RTS = 0x4 TIOCM_SR = 0x20 TIOCM_ST = 0x10 TIOCNOTTY = 0x5471 TIOCNXCL = 0x740e TIOCOUTQ = 0x7472 TIOCPKT = 0x5470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x5480 TIOCSERCONFIG = 0x5488 TIOCSERGETLSR = 0x548e TIOCSERGETMULTI = 0x548f TIOCSERGSTRUCT = 0x548d TIOCSERGWILD = 0x5489 TIOCSERSETMULTI = 0x5490 TIOCSERSWILD = 0x548a TIOCSER_TEMT = 0x1 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 TIOCSIG = 0x80045436 TIOCSLCKTRMIOS = 0x548c TIOCSLTC = 0x7475 TIOCSPGRP = 0x80047476 TIOCSPTLCK = 0x80045431 TIOCSRS485 = 0xc020542f TIOCSSERIAL = 0x5485 TIOCSSOFTCAR = 0x5482 TIOCSTI = 0x5472 TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x8000 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x800854d5 TUNDETACHFILTER = 0x800854d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x400854db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETBE = 0x400454df TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x10 VEOL = 0x11 VEOL2 = 0x6 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x4 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VSWTCH = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x20 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x7d) EADDRNOTAVAIL = syscall.Errno(0x7e) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x7c) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x95) EBADE = syscall.Errno(0x32) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x51) EBADMSG = syscall.Errno(0x4d) EBADR = syscall.Errno(0x33) EBADRQC = syscall.Errno(0x36) EBADSLT = syscall.Errno(0x37) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x9e) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x25) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x82) ECONNREFUSED = syscall.Errno(0x92) ECONNRESET = syscall.Errno(0x83) EDEADLK = syscall.Errno(0x2d) EDEADLOCK = syscall.Errno(0x38) EDESTADDRREQ = syscall.Errno(0x60) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x46d) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) EIDRM = syscall.Errno(0x24) EILSEQ = syscall.Errno(0x58) EINIT = syscall.Errno(0x8d) EINPROGRESS = syscall.Errno(0x96) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x85) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x8b) EKEYEXPIRED = syscall.Errno(0xa2) EKEYREJECTED = syscall.Errno(0xa4) EKEYREVOKED = syscall.Errno(0xa3) EL2HLT = syscall.Errno(0x2c) EL2NSYNC = syscall.Errno(0x26) EL3HLT = syscall.Errno(0x27) EL3RST = syscall.Errno(0x28) ELIBACC = syscall.Errno(0x53) ELIBBAD = syscall.Errno(0x54) ELIBEXEC = syscall.Errno(0x57) ELIBMAX = syscall.Errno(0x56) ELIBSCN = syscall.Errno(0x55) ELNRNG = syscall.Errno(0x29) ELOOP = syscall.Errno(0x5a) EMEDIUMTYPE = syscall.Errno(0xa0) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x61) EMULTIHOP = syscall.Errno(0x4a) ENAMETOOLONG = syscall.Errno(0x4e) ENAVAIL = syscall.Errno(0x8a) ENETDOWN = syscall.Errno(0x7f) ENETRESET = syscall.Errno(0x81) ENETUNREACH = syscall.Errno(0x80) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x35) ENOBUFS = syscall.Errno(0x84) ENOCSI = syscall.Errno(0x2b) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0xa1) ENOLCK = syscall.Errno(0x2e) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x9f) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x23) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x63) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x59) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x86) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x5d) ENOTNAM = syscall.Errno(0x89) ENOTRECOVERABLE = syscall.Errno(0xa6) ENOTSOCK = syscall.Errno(0x5f) ENOTSUP = syscall.Errno(0x7a) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x50) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x7a) EOVERFLOW = syscall.Errno(0x4f) EOWNERDEAD = syscall.Errno(0xa5) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x7b) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x78) EPROTOTYPE = syscall.Errno(0x62) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x52) EREMDEV = syscall.Errno(0x8e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x8c) ERESTART = syscall.Errno(0x5b) ERFKILL = syscall.Errno(0xa7) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x8f) ESOCKTNOSUPPORT = syscall.Errno(0x79) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x97) ESTRPIPE = syscall.Errno(0x5c) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x91) ETOOMANYREFS = syscall.Errno(0x90) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x87) EUNATCH = syscall.Errno(0x2a) EUSERS = syscall.Errno(0x5e) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x34) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x12) SIGCLD = syscall.Signal(0x12) SIGCONT = syscall.Signal(0x19) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x16) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x16) SIGPROF = syscall.Signal(0x1d) SIGPWR = syscall.Signal(0x13) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x17) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x18) SIGTTIN = syscall.Signal(0x1a) SIGTTOU = syscall.Signal(0x1b) SIGURG = syscall.Signal(0x15) SIGUSR1 = syscall.Signal(0x10) SIGUSR2 = syscall.Signal(0x11) SIGVTALRM = syscall.Signal(0x1c) SIGWINCH = syscall.Signal(0x14) SIGXCPU = syscall.Signal(0x1e) SIGXFSZ = syscall.Signal(0x1f) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "no message of desired type", 36: "identifier removed", 37: "channel number out of range", 38: "level 2 not synchronized", 39: "level 3 halted", 40: "level 3 reset", 41: "link number out of range", 42: "protocol driver not attached", 43: "no CSI structure available", 44: "level 2 halted", 45: "resource deadlock avoided", 46: "no locks available", 50: "invalid exchange", 51: "invalid request descriptor", 52: "exchange full", 53: "no anode", 54: "invalid request code", 55: "invalid slot", 56: "file locking deadlock error", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 73: "RFS specific error", 74: "multihop attempted", 77: "bad message", 78: "file name too long", 79: "value too large for defined data type", 80: "name not unique on network", 81: "file descriptor in bad state", 82: "remote address changed", 83: "can not access a needed shared library", 84: "accessing a corrupted shared library", 85: ".lib section in a.out corrupted", 86: "attempting to link in too many shared libraries", 87: "cannot exec a shared library directly", 88: "invalid or incomplete multibyte or wide character", 89: "function not implemented", 90: "too many levels of symbolic links", 91: "interrupted system call should be restarted", 92: "streams pipe error", 93: "directory not empty", 94: "too many users", 95: "socket operation on non-socket", 96: "destination address required", 97: "message too long", 98: "protocol wrong type for socket", 99: "protocol not available", 120: "protocol not supported", 121: "socket type not supported", 122: "operation not supported", 123: "protocol family not supported", 124: "address family not supported by protocol", 125: "address already in use", 126: "cannot assign requested address", 127: "network is down", 128: "network is unreachable", 129: "network dropped connection on reset", 130: "software caused connection abort", 131: "connection reset by peer", 132: "no buffer space available", 133: "transport endpoint is already connected", 134: "transport endpoint is not connected", 135: "structure needs cleaning", 137: "not a XENIX named type file", 138: "no XENIX semaphores available", 139: "is a named type file", 140: "remote I/O error", 141: "unknown error 141", 142: "unknown error 142", 143: "cannot send after transport endpoint shutdown", 144: "too many references: cannot splice", 145: "connection timed out", 146: "connection refused", 147: "host is down", 148: "no route to host", 149: "operation already in progress", 150: "operation now in progress", 151: "stale file handle", 158: "operation canceled", 159: "no medium found", 160: "wrong medium type", 161: "required key not available", 162: "key has expired", 163: "key has been revoked", 164: "key was rejected by service", 165: "owner died", 166: "state not recoverable", 167: "operation not possible due to RF-kill", 168: "memory page has hardware error", 1133: "disk quota exceeded", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "user defined signal 1", 17: "user defined signal 2", 18: "child exited", 19: "power failure", 20: "window changed", 21: "urgent I/O condition", 22: "I/O possible", 23: "stopped (signal)", 24: "stopped", 25: "continued", 26: "stopped (tty input)", 27: "stopped (tty output)", 28: "virtual timer expired", 29: "profiling timer expired", 30: "CPU time limit exceeded", 31: "file size limit exceeded", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_mips64le.go0000644061062106075000000027664113172163421026346 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips64le,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d BLKRRPART = 0x2000125f BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0xe F_GETLK64 = 0xe F_GETOWN = 0x17 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x6 F_SETLK64 = 0x6 F_SETLKW = 0x7 F_SETLKW64 = 0x7 F_SETOWN = 0x18 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x100 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x80 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x800 MAP_ANONYMOUS = 0x800 MAP_DENYWRITE = 0x2000 MAP_EXECUTABLE = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x1000 MAP_HUGETLB = 0x80000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x8000 MAP_NONBLOCK = 0x20000 MAP_NORESERVE = 0x400 MAP_POPULATE = 0x10000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x800 MAP_SHARED = 0x1 MAP_STACK = 0x40000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x1000 O_CLOEXEC = 0x80000 O_CREAT = 0x100 O_DIRECT = 0x8000 O_DIRECTORY = 0x10000 O_DSYNC = 0x10 O_EXCL = 0x400 O_FSYNC = 0x4010 O_LARGEFILE = 0x0 O_NDELAY = 0x80 O_NOATIME = 0x40000 O_NOCTTY = 0x800 O_NOFOLLOW = 0x20000 O_NONBLOCK = 0x80 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x4010 O_SYNC = 0x4010 O_TMPFILE = 0x410000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x20002401 PERF_EVENT_IOC_ENABLE = 0x20002400 PERF_EVENT_IOC_ID = 0x40082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80082406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = -0x1 PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 PTRACE_GET_WATCH_REGS = 0xd0 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKDATA_3264 = 0xc1 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKTEXT_3264 = 0xc0 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKEDATA_3264 = 0xc3 PTRACE_POKETEXT = 0x4 PTRACE_POKETEXT_3264 = 0xc2 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SET_THREAD_AREA = 0x1a PTRACE_SET_WATCH_REGS = 0xd1 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x9 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x5 RLIMIT_NPROC = 0x8 RLIMIT_RSS = 0x7 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x40047307 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x40047309 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x467f SIOCOUTQ = 0x7472 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x80047308 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x1 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x80 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x2 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1009 SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x20 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1e SO_PRIORITY = 0xc SO_PROTOCOL = 0x1028 SO_RCVBUF = 0x1002 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x1001 SO_SNDBUFFORCE = 0x1f SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_STYLE = 0x1008 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x1008 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d TCGETS2 = 0x4030542a TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x5410 TCSBRK = 0x5405 TCSBRKP = 0x5486 TCSETA = 0x5402 TCSETAF = 0x5404 TCSETAW = 0x5403 TCSETS = 0x540e TCSETS2 = 0x8030542b TCSETSF = 0x5410 TCSETSF2 = 0x8030542d TCSETSW = 0x540f TCSETSW2 = 0x8030542c TCXONC = 0x5406 TIOCCBRK = 0x5428 TIOCCONS = 0x80047478 TIOCEXCL = 0x740d TIOCGDEV = 0x40045432 TIOCGETD = 0x7400 TIOCGETP = 0x7408 TIOCGEXCL = 0x40045440 TIOCGICOUNT = 0x5492 TIOCGLCKTRMIOS = 0x548b TIOCGLTC = 0x7474 TIOCGPGRP = 0x40047477 TIOCGPKT = 0x40045438 TIOCGPTLCK = 0x40045439 TIOCGPTN = 0x40045430 TIOCGPTPEER = 0x20005441 TIOCGRS485 = 0x4020542e TIOCGSERIAL = 0x5484 TIOCGSID = 0x7416 TIOCGSOFTCAR = 0x5481 TIOCGWINSZ = 0x40087468 TIOCINQ = 0x467f TIOCLINUX = 0x5483 TIOCMBIC = 0x741c TIOCMBIS = 0x741b TIOCMGET = 0x741d TIOCMIWAIT = 0x5491 TIOCMSET = 0x741a TIOCM_CAR = 0x100 TIOCM_CD = 0x100 TIOCM_CTS = 0x40 TIOCM_DSR = 0x400 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x200 TIOCM_RNG = 0x200 TIOCM_RTS = 0x4 TIOCM_SR = 0x20 TIOCM_ST = 0x10 TIOCNOTTY = 0x5471 TIOCNXCL = 0x740e TIOCOUTQ = 0x7472 TIOCPKT = 0x5470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x5480 TIOCSERCONFIG = 0x5488 TIOCSERGETLSR = 0x548e TIOCSERGETMULTI = 0x548f TIOCSERGSTRUCT = 0x548d TIOCSERGWILD = 0x5489 TIOCSERSETMULTI = 0x5490 TIOCSERSWILD = 0x548a TIOCSER_TEMT = 0x1 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 TIOCSIG = 0x80045436 TIOCSLCKTRMIOS = 0x548c TIOCSLTC = 0x7475 TIOCSPGRP = 0x80047476 TIOCSPTLCK = 0x80045431 TIOCSRS485 = 0xc020542f TIOCSSERIAL = 0x5485 TIOCSSOFTCAR = 0x5482 TIOCSTI = 0x5472 TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x8000 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETBE = 0x400454df TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x10 VEOL = 0x11 VEOL2 = 0x6 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x4 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VSWTCH = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x40 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x7d) EADDRNOTAVAIL = syscall.Errno(0x7e) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x7c) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x95) EBADE = syscall.Errno(0x32) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x51) EBADMSG = syscall.Errno(0x4d) EBADR = syscall.Errno(0x33) EBADRQC = syscall.Errno(0x36) EBADSLT = syscall.Errno(0x37) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x9e) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x25) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x82) ECONNREFUSED = syscall.Errno(0x92) ECONNRESET = syscall.Errno(0x83) EDEADLK = syscall.Errno(0x2d) EDEADLOCK = syscall.Errno(0x38) EDESTADDRREQ = syscall.Errno(0x60) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x46d) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) EIDRM = syscall.Errno(0x24) EILSEQ = syscall.Errno(0x58) EINIT = syscall.Errno(0x8d) EINPROGRESS = syscall.Errno(0x96) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x85) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x8b) EKEYEXPIRED = syscall.Errno(0xa2) EKEYREJECTED = syscall.Errno(0xa4) EKEYREVOKED = syscall.Errno(0xa3) EL2HLT = syscall.Errno(0x2c) EL2NSYNC = syscall.Errno(0x26) EL3HLT = syscall.Errno(0x27) EL3RST = syscall.Errno(0x28) ELIBACC = syscall.Errno(0x53) ELIBBAD = syscall.Errno(0x54) ELIBEXEC = syscall.Errno(0x57) ELIBMAX = syscall.Errno(0x56) ELIBSCN = syscall.Errno(0x55) ELNRNG = syscall.Errno(0x29) ELOOP = syscall.Errno(0x5a) EMEDIUMTYPE = syscall.Errno(0xa0) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x61) EMULTIHOP = syscall.Errno(0x4a) ENAMETOOLONG = syscall.Errno(0x4e) ENAVAIL = syscall.Errno(0x8a) ENETDOWN = syscall.Errno(0x7f) ENETRESET = syscall.Errno(0x81) ENETUNREACH = syscall.Errno(0x80) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x35) ENOBUFS = syscall.Errno(0x84) ENOCSI = syscall.Errno(0x2b) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0xa1) ENOLCK = syscall.Errno(0x2e) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x9f) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x23) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x63) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x59) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x86) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x5d) ENOTNAM = syscall.Errno(0x89) ENOTRECOVERABLE = syscall.Errno(0xa6) ENOTSOCK = syscall.Errno(0x5f) ENOTSUP = syscall.Errno(0x7a) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x50) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x7a) EOVERFLOW = syscall.Errno(0x4f) EOWNERDEAD = syscall.Errno(0xa5) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x7b) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x78) EPROTOTYPE = syscall.Errno(0x62) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x52) EREMDEV = syscall.Errno(0x8e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x8c) ERESTART = syscall.Errno(0x5b) ERFKILL = syscall.Errno(0xa7) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x8f) ESOCKTNOSUPPORT = syscall.Errno(0x79) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x97) ESTRPIPE = syscall.Errno(0x5c) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x91) ETOOMANYREFS = syscall.Errno(0x90) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x87) EUNATCH = syscall.Errno(0x2a) EUSERS = syscall.Errno(0x5e) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x34) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x12) SIGCLD = syscall.Signal(0x12) SIGCONT = syscall.Signal(0x19) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x16) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x16) SIGPROF = syscall.Signal(0x1d) SIGPWR = syscall.Signal(0x13) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x17) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x18) SIGTTIN = syscall.Signal(0x1a) SIGTTOU = syscall.Signal(0x1b) SIGURG = syscall.Signal(0x15) SIGUSR1 = syscall.Signal(0x10) SIGUSR2 = syscall.Signal(0x11) SIGVTALRM = syscall.Signal(0x1c) SIGWINCH = syscall.Signal(0x14) SIGXCPU = syscall.Signal(0x1e) SIGXFSZ = syscall.Signal(0x1f) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "no message of desired type", 36: "identifier removed", 37: "channel number out of range", 38: "level 2 not synchronized", 39: "level 3 halted", 40: "level 3 reset", 41: "link number out of range", 42: "protocol driver not attached", 43: "no CSI structure available", 44: "level 2 halted", 45: "resource deadlock avoided", 46: "no locks available", 50: "invalid exchange", 51: "invalid request descriptor", 52: "exchange full", 53: "no anode", 54: "invalid request code", 55: "invalid slot", 56: "file locking deadlock error", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 73: "RFS specific error", 74: "multihop attempted", 77: "bad message", 78: "file name too long", 79: "value too large for defined data type", 80: "name not unique on network", 81: "file descriptor in bad state", 82: "remote address changed", 83: "can not access a needed shared library", 84: "accessing a corrupted shared library", 85: ".lib section in a.out corrupted", 86: "attempting to link in too many shared libraries", 87: "cannot exec a shared library directly", 88: "invalid or incomplete multibyte or wide character", 89: "function not implemented", 90: "too many levels of symbolic links", 91: "interrupted system call should be restarted", 92: "streams pipe error", 93: "directory not empty", 94: "too many users", 95: "socket operation on non-socket", 96: "destination address required", 97: "message too long", 98: "protocol wrong type for socket", 99: "protocol not available", 120: "protocol not supported", 121: "socket type not supported", 122: "operation not supported", 123: "protocol family not supported", 124: "address family not supported by protocol", 125: "address already in use", 126: "cannot assign requested address", 127: "network is down", 128: "network is unreachable", 129: "network dropped connection on reset", 130: "software caused connection abort", 131: "connection reset by peer", 132: "no buffer space available", 133: "transport endpoint is already connected", 134: "transport endpoint is not connected", 135: "structure needs cleaning", 137: "not a XENIX named type file", 138: "no XENIX semaphores available", 139: "is a named type file", 140: "remote I/O error", 141: "unknown error 141", 142: "unknown error 142", 143: "cannot send after transport endpoint shutdown", 144: "too many references: cannot splice", 145: "connection timed out", 146: "connection refused", 147: "host is down", 148: "no route to host", 149: "operation already in progress", 150: "operation now in progress", 151: "stale file handle", 158: "operation canceled", 159: "no medium found", 160: "wrong medium type", 161: "required key not available", 162: "key has expired", 163: "key has been revoked", 164: "key was rejected by service", 165: "owner died", 166: "state not recoverable", 167: "operation not possible due to RF-kill", 168: "memory page has hardware error", 1133: "disk quota exceeded", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "user defined signal 1", 17: "user defined signal 2", 18: "child exited", 19: "power failure", 20: "window changed", 21: "urgent I/O condition", 22: "I/O possible", 23: "stopped (signal)", 24: "stopped", 25: "continued", 26: "stopped (tty input)", 27: "stopped (tty output)", 28: "virtual timer expired", 29: "profiling timer expired", 30: "CPU time limit exceeded", 31: "file size limit exceeded", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_mips64.go0000644061062106075000000027663713172163421026032 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d BLKRRPART = 0x2000125f BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0xe F_GETLK64 = 0xe F_GETOWN = 0x17 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x6 F_SETLK64 = 0x6 F_SETLKW = 0x7 F_SETLKW64 = 0x7 F_SETOWN = 0x18 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x100 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x80 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x800 MAP_ANONYMOUS = 0x800 MAP_DENYWRITE = 0x2000 MAP_EXECUTABLE = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x1000 MAP_HUGETLB = 0x80000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x8000 MAP_NONBLOCK = 0x20000 MAP_NORESERVE = 0x400 MAP_POPULATE = 0x10000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x800 MAP_SHARED = 0x1 MAP_STACK = 0x40000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x1000 O_CLOEXEC = 0x80000 O_CREAT = 0x100 O_DIRECT = 0x8000 O_DIRECTORY = 0x10000 O_DSYNC = 0x10 O_EXCL = 0x400 O_FSYNC = 0x4010 O_LARGEFILE = 0x0 O_NDELAY = 0x80 O_NOATIME = 0x40000 O_NOCTTY = 0x800 O_NOFOLLOW = 0x20000 O_NONBLOCK = 0x80 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x4010 O_SYNC = 0x4010 O_TMPFILE = 0x410000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x20002401 PERF_EVENT_IOC_ENABLE = 0x20002400 PERF_EVENT_IOC_ID = 0x40082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80082406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = -0x1 PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 PTRACE_GET_WATCH_REGS = 0xd0 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKDATA_3264 = 0xc1 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKTEXT_3264 = 0xc0 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKEDATA_3264 = 0xc3 PTRACE_POKETEXT = 0x4 PTRACE_POKETEXT_3264 = 0xc2 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SET_THREAD_AREA = 0x1a PTRACE_SET_WATCH_REGS = 0xd1 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x9 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x5 RLIMIT_NPROC = 0x8 RLIMIT_RSS = 0x7 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x40047307 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x40047309 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x467f SIOCOUTQ = 0x7472 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x80047308 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x1 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x80 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x2 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1009 SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x20 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1e SO_PRIORITY = 0xc SO_PROTOCOL = 0x1028 SO_RCVBUF = 0x1002 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x1001 SO_SNDBUFFORCE = 0x1f SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_STYLE = 0x1008 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x1008 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d TCGETS2 = 0x4030542a TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x5410 TCSBRK = 0x5405 TCSBRKP = 0x5486 TCSETA = 0x5402 TCSETAF = 0x5404 TCSETAW = 0x5403 TCSETS = 0x540e TCSETS2 = 0x8030542b TCSETSF = 0x5410 TCSETSF2 = 0x8030542d TCSETSW = 0x540f TCSETSW2 = 0x8030542c TCXONC = 0x5406 TIOCCBRK = 0x5428 TIOCCONS = 0x80047478 TIOCEXCL = 0x740d TIOCGDEV = 0x40045432 TIOCGETD = 0x7400 TIOCGETP = 0x7408 TIOCGEXCL = 0x40045440 TIOCGICOUNT = 0x5492 TIOCGLCKTRMIOS = 0x548b TIOCGLTC = 0x7474 TIOCGPGRP = 0x40047477 TIOCGPKT = 0x40045438 TIOCGPTLCK = 0x40045439 TIOCGPTN = 0x40045430 TIOCGPTPEER = 0x20005441 TIOCGRS485 = 0x4020542e TIOCGSERIAL = 0x5484 TIOCGSID = 0x7416 TIOCGSOFTCAR = 0x5481 TIOCGWINSZ = 0x40087468 TIOCINQ = 0x467f TIOCLINUX = 0x5483 TIOCMBIC = 0x741c TIOCMBIS = 0x741b TIOCMGET = 0x741d TIOCMIWAIT = 0x5491 TIOCMSET = 0x741a TIOCM_CAR = 0x100 TIOCM_CD = 0x100 TIOCM_CTS = 0x40 TIOCM_DSR = 0x400 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x200 TIOCM_RNG = 0x200 TIOCM_RTS = 0x4 TIOCM_SR = 0x20 TIOCM_ST = 0x10 TIOCNOTTY = 0x5471 TIOCNXCL = 0x740e TIOCOUTQ = 0x7472 TIOCPKT = 0x5470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x5480 TIOCSERCONFIG = 0x5488 TIOCSERGETLSR = 0x548e TIOCSERGETMULTI = 0x548f TIOCSERGSTRUCT = 0x548d TIOCSERGWILD = 0x5489 TIOCSERSETMULTI = 0x5490 TIOCSERSWILD = 0x548a TIOCSER_TEMT = 0x1 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 TIOCSIG = 0x80045436 TIOCSLCKTRMIOS = 0x548c TIOCSLTC = 0x7475 TIOCSPGRP = 0x80047476 TIOCSPTLCK = 0x80045431 TIOCSRS485 = 0xc020542f TIOCSSERIAL = 0x5485 TIOCSSOFTCAR = 0x5482 TIOCSTI = 0x5472 TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x8000 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETBE = 0x400454df TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x10 VEOL = 0x11 VEOL2 = 0x6 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x4 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VSWTCH = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x40 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x7d) EADDRNOTAVAIL = syscall.Errno(0x7e) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x7c) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x95) EBADE = syscall.Errno(0x32) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x51) EBADMSG = syscall.Errno(0x4d) EBADR = syscall.Errno(0x33) EBADRQC = syscall.Errno(0x36) EBADSLT = syscall.Errno(0x37) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x9e) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x25) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x82) ECONNREFUSED = syscall.Errno(0x92) ECONNRESET = syscall.Errno(0x83) EDEADLK = syscall.Errno(0x2d) EDEADLOCK = syscall.Errno(0x38) EDESTADDRREQ = syscall.Errno(0x60) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x46d) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) EIDRM = syscall.Errno(0x24) EILSEQ = syscall.Errno(0x58) EINIT = syscall.Errno(0x8d) EINPROGRESS = syscall.Errno(0x96) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x85) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x8b) EKEYEXPIRED = syscall.Errno(0xa2) EKEYREJECTED = syscall.Errno(0xa4) EKEYREVOKED = syscall.Errno(0xa3) EL2HLT = syscall.Errno(0x2c) EL2NSYNC = syscall.Errno(0x26) EL3HLT = syscall.Errno(0x27) EL3RST = syscall.Errno(0x28) ELIBACC = syscall.Errno(0x53) ELIBBAD = syscall.Errno(0x54) ELIBEXEC = syscall.Errno(0x57) ELIBMAX = syscall.Errno(0x56) ELIBSCN = syscall.Errno(0x55) ELNRNG = syscall.Errno(0x29) ELOOP = syscall.Errno(0x5a) EMEDIUMTYPE = syscall.Errno(0xa0) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x61) EMULTIHOP = syscall.Errno(0x4a) ENAMETOOLONG = syscall.Errno(0x4e) ENAVAIL = syscall.Errno(0x8a) ENETDOWN = syscall.Errno(0x7f) ENETRESET = syscall.Errno(0x81) ENETUNREACH = syscall.Errno(0x80) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x35) ENOBUFS = syscall.Errno(0x84) ENOCSI = syscall.Errno(0x2b) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0xa1) ENOLCK = syscall.Errno(0x2e) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x9f) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x23) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x63) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x59) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x86) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x5d) ENOTNAM = syscall.Errno(0x89) ENOTRECOVERABLE = syscall.Errno(0xa6) ENOTSOCK = syscall.Errno(0x5f) ENOTSUP = syscall.Errno(0x7a) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x50) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x7a) EOVERFLOW = syscall.Errno(0x4f) EOWNERDEAD = syscall.Errno(0xa5) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x7b) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x78) EPROTOTYPE = syscall.Errno(0x62) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x52) EREMDEV = syscall.Errno(0x8e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x8c) ERESTART = syscall.Errno(0x5b) ERFKILL = syscall.Errno(0xa7) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x8f) ESOCKTNOSUPPORT = syscall.Errno(0x79) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x97) ESTRPIPE = syscall.Errno(0x5c) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x91) ETOOMANYREFS = syscall.Errno(0x90) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x87) EUNATCH = syscall.Errno(0x2a) EUSERS = syscall.Errno(0x5e) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x34) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x12) SIGCLD = syscall.Signal(0x12) SIGCONT = syscall.Signal(0x19) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x16) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x16) SIGPROF = syscall.Signal(0x1d) SIGPWR = syscall.Signal(0x13) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x17) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x18) SIGTTIN = syscall.Signal(0x1a) SIGTTOU = syscall.Signal(0x1b) SIGURG = syscall.Signal(0x15) SIGUSR1 = syscall.Signal(0x10) SIGUSR2 = syscall.Signal(0x11) SIGVTALRM = syscall.Signal(0x1c) SIGWINCH = syscall.Signal(0x14) SIGXCPU = syscall.Signal(0x1e) SIGXFSZ = syscall.Signal(0x1f) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "no message of desired type", 36: "identifier removed", 37: "channel number out of range", 38: "level 2 not synchronized", 39: "level 3 halted", 40: "level 3 reset", 41: "link number out of range", 42: "protocol driver not attached", 43: "no CSI structure available", 44: "level 2 halted", 45: "resource deadlock avoided", 46: "no locks available", 50: "invalid exchange", 51: "invalid request descriptor", 52: "exchange full", 53: "no anode", 54: "invalid request code", 55: "invalid slot", 56: "file locking deadlock error", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 73: "RFS specific error", 74: "multihop attempted", 77: "bad message", 78: "file name too long", 79: "value too large for defined data type", 80: "name not unique on network", 81: "file descriptor in bad state", 82: "remote address changed", 83: "can not access a needed shared library", 84: "accessing a corrupted shared library", 85: ".lib section in a.out corrupted", 86: "attempting to link in too many shared libraries", 87: "cannot exec a shared library directly", 88: "invalid or incomplete multibyte or wide character", 89: "function not implemented", 90: "too many levels of symbolic links", 91: "interrupted system call should be restarted", 92: "streams pipe error", 93: "directory not empty", 94: "too many users", 95: "socket operation on non-socket", 96: "destination address required", 97: "message too long", 98: "protocol wrong type for socket", 99: "protocol not available", 120: "protocol not supported", 121: "socket type not supported", 122: "operation not supported", 123: "protocol family not supported", 124: "address family not supported by protocol", 125: "address already in use", 126: "cannot assign requested address", 127: "network is down", 128: "network is unreachable", 129: "network dropped connection on reset", 130: "software caused connection abort", 131: "connection reset by peer", 132: "no buffer space available", 133: "transport endpoint is already connected", 134: "transport endpoint is not connected", 135: "structure needs cleaning", 137: "not a XENIX named type file", 138: "no XENIX semaphores available", 139: "is a named type file", 140: "remote I/O error", 141: "unknown error 141", 142: "unknown error 142", 143: "cannot send after transport endpoint shutdown", 144: "too many references: cannot splice", 145: "connection timed out", 146: "connection refused", 147: "host is down", 148: "no route to host", 149: "operation already in progress", 150: "operation now in progress", 151: "stale file handle", 158: "operation canceled", 159: "no medium found", 160: "wrong medium type", 161: "required key not available", 162: "key has expired", 163: "key has been revoked", 164: "key was rejected by service", 165: "owner died", 166: "state not recoverable", 167: "operation not possible due to RF-kill", 168: "memory page has hardware error", 1133: "disk quota exceeded", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "user defined signal 1", 17: "user defined signal 2", 18: "child exited", 19: "power failure", 20: "window changed", 21: "urgent I/O condition", 22: "I/O possible", 23: "stopped (signal)", 24: "stopped", 25: "continued", 26: "stopped (tty input)", 27: "stopped (tty output)", 28: "virtual timer expired", 29: "profiling timer expired", 30: "CPU time limit exceeded", 31: "file size limit exceeded", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_mips.go0000644061062106075000000027665413172163421025657 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x40041270 BLKBSZSET = 0x80041271 BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40041272 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d BLKRRPART = 0x2000125f BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0x21 F_GETLK64 = 0x21 F_GETOWN = 0x17 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x22 F_SETLK64 = 0x22 F_SETLKW = 0x23 F_SETLKW64 = 0x23 F_SETOWN = 0x18 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x100 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x80 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x800 MAP_ANONYMOUS = 0x800 MAP_DENYWRITE = 0x2000 MAP_EXECUTABLE = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x1000 MAP_HUGETLB = 0x80000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x8000 MAP_NONBLOCK = 0x20000 MAP_NORESERVE = 0x400 MAP_POPULATE = 0x10000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x800 MAP_SHARED = 0x1 MAP_STACK = 0x40000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x1000 O_CLOEXEC = 0x80000 O_CREAT = 0x100 O_DIRECT = 0x8000 O_DIRECTORY = 0x10000 O_DSYNC = 0x10 O_EXCL = 0x400 O_FSYNC = 0x4010 O_LARGEFILE = 0x2000 O_NDELAY = 0x80 O_NOATIME = 0x40000 O_NOCTTY = 0x800 O_NOFOLLOW = 0x20000 O_NONBLOCK = 0x80 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x4010 O_SYNC = 0x4010 O_TMPFILE = 0x410000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x20002401 PERF_EVENT_IOC_ENABLE = 0x20002400 PERF_EVENT_IOC_ID = 0x40042407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80042406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = 0xffffffff PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETFPREGS = 0xe PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA_3264 = 0xc4 PTRACE_GET_WATCH_REGS = 0xd0 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKDATA_3264 = 0xc1 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKTEXT_3264 = 0xc0 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKEDATA_3264 = 0xc3 PTRACE_POKETEXT = 0x4 PTRACE_POKETEXT_3264 = 0xc2 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SET_THREAD_AREA = 0x1a PTRACE_SET_WATCH_REGS = 0xd1 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x9 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x5 RLIMIT_NPROC = 0x8 RLIMIT_RSS = 0x7 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x40047307 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x40047309 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x467f SIOCOUTQ = 0x7472 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x80047308 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x1 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x80 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x2 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1009 SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x20 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x1029 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1e SO_PRIORITY = 0xc SO_PROTOCOL = 0x1028 SO_RCVBUF = 0x1002 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x1001 SO_SNDBUFFORCE = 0x1f SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_STYLE = 0x1008 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x1008 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d TCGETS2 = 0x4030542a TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x5410 TCSBRK = 0x5405 TCSBRKP = 0x5486 TCSETA = 0x5402 TCSETAF = 0x5404 TCSETAW = 0x5403 TCSETS = 0x540e TCSETS2 = 0x8030542b TCSETSF = 0x5410 TCSETSF2 = 0x8030542d TCSETSW = 0x540f TCSETSW2 = 0x8030542c TCXONC = 0x5406 TIOCCBRK = 0x5428 TIOCCONS = 0x80047478 TIOCEXCL = 0x740d TIOCGDEV = 0x40045432 TIOCGETD = 0x7400 TIOCGETP = 0x7408 TIOCGEXCL = 0x40045440 TIOCGICOUNT = 0x5492 TIOCGLCKTRMIOS = 0x548b TIOCGLTC = 0x7474 TIOCGPGRP = 0x40047477 TIOCGPKT = 0x40045438 TIOCGPTLCK = 0x40045439 TIOCGPTN = 0x40045430 TIOCGPTPEER = 0x20005441 TIOCGRS485 = 0x4020542e TIOCGSERIAL = 0x5484 TIOCGSID = 0x7416 TIOCGSOFTCAR = 0x5481 TIOCGWINSZ = 0x40087468 TIOCINQ = 0x467f TIOCLINUX = 0x5483 TIOCMBIC = 0x741c TIOCMBIS = 0x741b TIOCMGET = 0x741d TIOCMIWAIT = 0x5491 TIOCMSET = 0x741a TIOCM_CAR = 0x100 TIOCM_CD = 0x100 TIOCM_CTS = 0x40 TIOCM_DSR = 0x400 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x200 TIOCM_RNG = 0x200 TIOCM_RTS = 0x4 TIOCM_SR = 0x20 TIOCM_ST = 0x10 TIOCNOTTY = 0x5471 TIOCNXCL = 0x740e TIOCOUTQ = 0x7472 TIOCPKT = 0x5470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x5480 TIOCSERCONFIG = 0x5488 TIOCSERGETLSR = 0x548e TIOCSERGETMULTI = 0x548f TIOCSERGSTRUCT = 0x548d TIOCSERGWILD = 0x5489 TIOCSERSETMULTI = 0x5490 TIOCSERSWILD = 0x548a TIOCSER_TEMT = 0x1 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 TIOCSIG = 0x80045436 TIOCSLCKTRMIOS = 0x548c TIOCSLTC = 0x7475 TIOCSPGRP = 0x80047476 TIOCSPTLCK = 0x80045431 TIOCSRS485 = 0xc020542f TIOCSSERIAL = 0x5485 TIOCSSOFTCAR = 0x5482 TIOCSTI = 0x5472 TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x8000 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x800854d5 TUNDETACHFILTER = 0x800854d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x400854db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETBE = 0x400454df TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x10 VEOL = 0x11 VEOL2 = 0x6 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x4 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VSWTCH = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x20 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x7d) EADDRNOTAVAIL = syscall.Errno(0x7e) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x7c) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x95) EBADE = syscall.Errno(0x32) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x51) EBADMSG = syscall.Errno(0x4d) EBADR = syscall.Errno(0x33) EBADRQC = syscall.Errno(0x36) EBADSLT = syscall.Errno(0x37) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x9e) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x25) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x82) ECONNREFUSED = syscall.Errno(0x92) ECONNRESET = syscall.Errno(0x83) EDEADLK = syscall.Errno(0x2d) EDEADLOCK = syscall.Errno(0x38) EDESTADDRREQ = syscall.Errno(0x60) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x46d) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) EIDRM = syscall.Errno(0x24) EILSEQ = syscall.Errno(0x58) EINIT = syscall.Errno(0x8d) EINPROGRESS = syscall.Errno(0x96) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x85) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x8b) EKEYEXPIRED = syscall.Errno(0xa2) EKEYREJECTED = syscall.Errno(0xa4) EKEYREVOKED = syscall.Errno(0xa3) EL2HLT = syscall.Errno(0x2c) EL2NSYNC = syscall.Errno(0x26) EL3HLT = syscall.Errno(0x27) EL3RST = syscall.Errno(0x28) ELIBACC = syscall.Errno(0x53) ELIBBAD = syscall.Errno(0x54) ELIBEXEC = syscall.Errno(0x57) ELIBMAX = syscall.Errno(0x56) ELIBSCN = syscall.Errno(0x55) ELNRNG = syscall.Errno(0x29) ELOOP = syscall.Errno(0x5a) EMEDIUMTYPE = syscall.Errno(0xa0) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x61) EMULTIHOP = syscall.Errno(0x4a) ENAMETOOLONG = syscall.Errno(0x4e) ENAVAIL = syscall.Errno(0x8a) ENETDOWN = syscall.Errno(0x7f) ENETRESET = syscall.Errno(0x81) ENETUNREACH = syscall.Errno(0x80) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x35) ENOBUFS = syscall.Errno(0x84) ENOCSI = syscall.Errno(0x2b) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0xa1) ENOLCK = syscall.Errno(0x2e) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x9f) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x23) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x63) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x59) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x86) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x5d) ENOTNAM = syscall.Errno(0x89) ENOTRECOVERABLE = syscall.Errno(0xa6) ENOTSOCK = syscall.Errno(0x5f) ENOTSUP = syscall.Errno(0x7a) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x50) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x7a) EOVERFLOW = syscall.Errno(0x4f) EOWNERDEAD = syscall.Errno(0xa5) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x7b) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x78) EPROTOTYPE = syscall.Errno(0x62) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x52) EREMDEV = syscall.Errno(0x8e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x8c) ERESTART = syscall.Errno(0x5b) ERFKILL = syscall.Errno(0xa7) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x8f) ESOCKTNOSUPPORT = syscall.Errno(0x79) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x97) ESTRPIPE = syscall.Errno(0x5c) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x91) ETOOMANYREFS = syscall.Errno(0x90) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x87) EUNATCH = syscall.Errno(0x2a) EUSERS = syscall.Errno(0x5e) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x34) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x12) SIGCLD = syscall.Signal(0x12) SIGCONT = syscall.Signal(0x19) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x16) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x16) SIGPROF = syscall.Signal(0x1d) SIGPWR = syscall.Signal(0x13) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x17) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x18) SIGTTIN = syscall.Signal(0x1a) SIGTTOU = syscall.Signal(0x1b) SIGURG = syscall.Signal(0x15) SIGUSR1 = syscall.Signal(0x10) SIGUSR2 = syscall.Signal(0x11) SIGVTALRM = syscall.Signal(0x1c) SIGWINCH = syscall.Signal(0x14) SIGXCPU = syscall.Signal(0x1e) SIGXFSZ = syscall.Signal(0x1f) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "no message of desired type", 36: "identifier removed", 37: "channel number out of range", 38: "level 2 not synchronized", 39: "level 3 halted", 40: "level 3 reset", 41: "link number out of range", 42: "protocol driver not attached", 43: "no CSI structure available", 44: "level 2 halted", 45: "resource deadlock avoided", 46: "no locks available", 50: "invalid exchange", 51: "invalid request descriptor", 52: "exchange full", 53: "no anode", 54: "invalid request code", 55: "invalid slot", 56: "file locking deadlock error", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 73: "RFS specific error", 74: "multihop attempted", 77: "bad message", 78: "file name too long", 79: "value too large for defined data type", 80: "name not unique on network", 81: "file descriptor in bad state", 82: "remote address changed", 83: "can not access a needed shared library", 84: "accessing a corrupted shared library", 85: ".lib section in a.out corrupted", 86: "attempting to link in too many shared libraries", 87: "cannot exec a shared library directly", 88: "invalid or incomplete multibyte or wide character", 89: "function not implemented", 90: "too many levels of symbolic links", 91: "interrupted system call should be restarted", 92: "streams pipe error", 93: "directory not empty", 94: "too many users", 95: "socket operation on non-socket", 96: "destination address required", 97: "message too long", 98: "protocol wrong type for socket", 99: "protocol not available", 120: "protocol not supported", 121: "socket type not supported", 122: "operation not supported", 123: "protocol family not supported", 124: "address family not supported by protocol", 125: "address already in use", 126: "cannot assign requested address", 127: "network is down", 128: "network is unreachable", 129: "network dropped connection on reset", 130: "software caused connection abort", 131: "connection reset by peer", 132: "no buffer space available", 133: "transport endpoint is already connected", 134: "transport endpoint is not connected", 135: "structure needs cleaning", 137: "not a XENIX named type file", 138: "no XENIX semaphores available", 139: "is a named type file", 140: "remote I/O error", 141: "unknown error 141", 142: "unknown error 142", 143: "cannot send after transport endpoint shutdown", 144: "too many references: cannot splice", 145: "connection timed out", 146: "connection refused", 147: "host is down", 148: "no route to host", 149: "operation already in progress", 150: "operation now in progress", 151: "stale file handle", 158: "operation canceled", 159: "no medium found", 160: "wrong medium type", 161: "required key not available", 162: "key has expired", 163: "key has been revoked", 164: "key was rejected by service", 165: "owner died", 166: "state not recoverable", 167: "operation not possible due to RF-kill", 168: "memory page has hardware error", 1133: "disk quota exceeded", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "user defined signal 1", 17: "user defined signal 2", 18: "child exited", 19: "power failure", 20: "window changed", 21: "urgent I/O condition", 22: "I/O possible", 23: "stopped (signal)", 24: "stopped", 25: "continued", 26: "stopped (tty input)", 27: "stopped (tty output)", 28: "virtual timer expired", 29: "profiling timer expired", 30: "CPU time limit exceeded", 31: "file size limit exceeded", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_arm64.go0000644061062106075000000027460613172163421025633 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include -fsigned-char // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d BLKRRPART = 0x125f BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ESR_MAGIC = 0x45535201 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 EXTRA_MAGIC = 0x45585401 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0x5 F_GETLK64 = 0x5 F_GETOWN = 0x9 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x6 F_SETLK64 = 0x6 F_SETLKW = 0x7 F_SETLKW64 = 0x7 F_SETOWN = 0x8 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x8000 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_HUGETLB = 0x40000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x2000 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x4000 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_STACK = 0x20000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 O_CLOEXEC = 0x80000 O_CREAT = 0x40 O_DIRECT = 0x10000 O_DIRECTORY = 0x4000 O_DSYNC = 0x1000 O_EXCL = 0x80 O_FSYNC = 0x101000 O_LARGEFILE = 0x0 O_NDELAY = 0x800 O_NOATIME = 0x40000 O_NOCTTY = 0x100 O_NOFOLLOW = 0x8000 O_NONBLOCK = 0x800 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x101000 O_SYNC = 0x101000 O_TMPFILE = 0x404000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x2401 PERF_EVENT_IOC_ENABLE = 0x2400 PERF_EVENT_IOC_ID = 0x80082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = -0x1 PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x8 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x7 RLIMIT_NPROC = 0x6 RLIMIT_RSS = 0x5 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x541b SIOCOUTQ = 0x5411 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1f SO_PRIORITY = 0xc SO_PROTOCOL = 0x26 SO_RCVBUF = 0x8 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x12 SO_RCVTIMEO = 0x14 SO_REUSEADDR = 0x2 SO_REUSEPORT = 0xf SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 TCSBRK = 0x5409 TCSBRKP = 0x5425 TCSETA = 0x5406 TCSETAF = 0x5408 TCSETAW = 0x5407 TCSETS = 0x5402 TCSETS2 = 0x402c542b TCSETSF = 0x5404 TCSETSF2 = 0x402c542d TCSETSW = 0x5403 TCSETSW2 = 0x402c542c TCSETX = 0x5433 TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c TIOCGDEV = 0x80045432 TIOCGETD = 0x5424 TIOCGEXCL = 0x80045440 TIOCGICOUNT = 0x545d TIOCGLCKTRMIOS = 0x5456 TIOCGPGRP = 0x540f TIOCGPKT = 0x80045438 TIOCGPTLCK = 0x80045439 TIOCGPTN = 0x80045430 TIOCGPTPEER = 0x5441 TIOCGRS485 = 0x542e TIOCGSERIAL = 0x541e TIOCGSID = 0x5429 TIOCGSOFTCAR = 0x5419 TIOCGWINSZ = 0x5413 TIOCINQ = 0x541b TIOCLINUX = 0x541c TIOCMBIC = 0x5417 TIOCMBIS = 0x5416 TIOCMGET = 0x5415 TIOCMIWAIT = 0x545c TIOCMSET = 0x5418 TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x5422 TIOCNXCL = 0x540d TIOCOUTQ = 0x5411 TIOCPKT = 0x5420 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x540e TIOCSERCONFIG = 0x5453 TIOCSERGETLSR = 0x5459 TIOCSERGETMULTI = 0x545a TIOCSERGSTRUCT = 0x5458 TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSLCKTRMIOS = 0x5457 TIOCSPGRP = 0x5410 TIOCSPTLCK = 0x40045431 TIOCSRS485 = 0x542f TIOCSSERIAL = 0x541f TIOCSSOFTCAR = 0x541a TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf TUNGETFILTER = 0x801054db TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETBE = 0x800454df TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x6 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x40 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x62) EADDRNOTAVAIL = syscall.Errno(0x63) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x61) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x72) EBADE = syscall.Errno(0x34) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x4d) EBADMSG = syscall.Errno(0x4a) EBADR = syscall.Errno(0x35) EBADRQC = syscall.Errno(0x38) EBADSLT = syscall.Errno(0x39) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x7d) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x2c) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x67) ECONNREFUSED = syscall.Errno(0x6f) ECONNRESET = syscall.Errno(0x68) EDEADLK = syscall.Errno(0x23) EDEADLOCK = syscall.Errno(0x23) EDESTADDRREQ = syscall.Errno(0x59) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x7a) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) EIDRM = syscall.Errno(0x2b) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x73) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x6a) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x78) EKEYEXPIRED = syscall.Errno(0x7f) EKEYREJECTED = syscall.Errno(0x81) EKEYREVOKED = syscall.Errno(0x80) EL2HLT = syscall.Errno(0x33) EL2NSYNC = syscall.Errno(0x2d) EL3HLT = syscall.Errno(0x2e) EL3RST = syscall.Errno(0x2f) ELIBACC = syscall.Errno(0x4f) ELIBBAD = syscall.Errno(0x50) ELIBEXEC = syscall.Errno(0x53) ELIBMAX = syscall.Errno(0x52) ELIBSCN = syscall.Errno(0x51) ELNRNG = syscall.Errno(0x30) ELOOP = syscall.Errno(0x28) EMEDIUMTYPE = syscall.Errno(0x7c) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x5a) EMULTIHOP = syscall.Errno(0x48) ENAMETOOLONG = syscall.Errno(0x24) ENAVAIL = syscall.Errno(0x77) ENETDOWN = syscall.Errno(0x64) ENETRESET = syscall.Errno(0x66) ENETUNREACH = syscall.Errno(0x65) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x37) ENOBUFS = syscall.Errno(0x69) ENOCSI = syscall.Errno(0x32) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0x7e) ENOLCK = syscall.Errno(0x25) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x7b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x2a) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x5c) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x26) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x6b) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x27) ENOTNAM = syscall.Errno(0x76) ENOTRECOVERABLE = syscall.Errno(0x83) ENOTSOCK = syscall.Errno(0x58) ENOTSUP = syscall.Errno(0x5f) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x4c) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x5f) EOVERFLOW = syscall.Errno(0x4b) EOWNERDEAD = syscall.Errno(0x82) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x60) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x5d) EPROTOTYPE = syscall.Errno(0x5b) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x4e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x79) ERESTART = syscall.Errno(0x55) ERFKILL = syscall.Errno(0x84) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x6c) ESOCKTNOSUPPORT = syscall.Errno(0x5e) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x74) ESTRPIPE = syscall.Errno(0x56) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x6e) ETOOMANYREFS = syscall.Errno(0x6d) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x75) EUNATCH = syscall.Errno(0x31) EUSERS = syscall.Errno(0x57) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x36) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0x7) SIGCHLD = syscall.Signal(0x11) SIGCLD = syscall.Signal(0x11) SIGCONT = syscall.Signal(0x12) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x1d) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x1d) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x1e) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTKFLT = syscall.Signal(0x10) SIGSTOP = syscall.Signal(0x13) SIGSYS = syscall.Signal(0x1f) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x14) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x17) SIGUSR1 = syscall.Signal(0xa) SIGUSR2 = syscall.Signal(0xc) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "resource deadlock avoided", 36: "file name too long", 37: "no locks available", 38: "function not implemented", 39: "directory not empty", 40: "too many levels of symbolic links", 42: "no message of desired type", 43: "identifier removed", 44: "channel number out of range", 45: "level 2 not synchronized", 46: "level 3 halted", 47: "level 3 reset", 48: "link number out of range", 49: "protocol driver not attached", 50: "no CSI structure available", 51: "level 2 halted", 52: "invalid exchange", 53: "invalid request descriptor", 54: "exchange full", 55: "no anode", 56: "invalid request code", 57: "invalid slot", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "multihop attempted", 73: "RFS specific error", 74: "bad message", 75: "value too large for defined data type", 76: "name not unique on network", 77: "file descriptor in bad state", 78: "remote address changed", 79: "can not access a needed shared library", 80: "accessing a corrupted shared library", 81: ".lib section in a.out corrupted", 82: "attempting to link in too many shared libraries", 83: "cannot exec a shared library directly", 84: "invalid or incomplete multibyte or wide character", 85: "interrupted system call should be restarted", 86: "streams pipe error", 87: "too many users", 88: "socket operation on non-socket", 89: "destination address required", 90: "message too long", 91: "protocol wrong type for socket", 92: "protocol not available", 93: "protocol not supported", 94: "socket type not supported", 95: "operation not supported", 96: "protocol family not supported", 97: "address family not supported by protocol", 98: "address already in use", 99: "cannot assign requested address", 100: "network is down", 101: "network is unreachable", 102: "network dropped connection on reset", 103: "software caused connection abort", 104: "connection reset by peer", 105: "no buffer space available", 106: "transport endpoint is already connected", 107: "transport endpoint is not connected", 108: "cannot send after transport endpoint shutdown", 109: "too many references: cannot splice", 110: "connection timed out", 111: "connection refused", 112: "host is down", 113: "no route to host", 114: "operation already in progress", 115: "operation now in progress", 116: "stale file handle", 117: "structure needs cleaning", 118: "not a XENIX named type file", 119: "no XENIX semaphores available", 120: "is a named type file", 121: "remote I/O error", 122: "disk quota exceeded", 123: "no medium found", 124: "wrong medium type", 125: "operation canceled", 126: "required key not available", 127: "key has expired", 128: "key has been revoked", 129: "key was rejected by service", 130: "owner died", 131: "state not recoverable", 132: "operation not possible due to RF-kill", 133: "memory page has hardware error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "bus error", 8: "floating point exception", 9: "killed", 10: "user defined signal 1", 11: "segmentation fault", 12: "user defined signal 2", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "stack fault", 17: "child exited", 18: "continued", 19: "stopped (signal)", 20: "stopped", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "urgent I/O condition", 24: "CPU time limit exceeded", 25: "file size limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window changed", 29: "I/O possible", 30: "power failure", 31: "bad system call", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_arm.go0000644061062106075000000027574313172163421025464 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x80041270 BLKBSZSET = 0x40041271 BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80041272 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d BLKRRPART = 0x125f BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0xc F_GETLK64 = 0xc F_GETOWN = 0x9 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0xd F_SETLK64 = 0xd F_SETLKW = 0xe F_SETLKW64 = 0xe F_SETOWN = 0x8 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x8000 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_HUGETLB = 0x40000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x2000 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x4000 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_STACK = 0x20000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 O_CLOEXEC = 0x80000 O_CREAT = 0x40 O_DIRECT = 0x10000 O_DIRECTORY = 0x4000 O_DSYNC = 0x1000 O_EXCL = 0x80 O_FSYNC = 0x101000 O_LARGEFILE = 0x20000 O_NDELAY = 0x800 O_NOATIME = 0x40000 O_NOCTTY = 0x100 O_NOFOLLOW = 0x8000 O_NONBLOCK = 0x800 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x101000 O_SYNC = 0x101000 O_TMPFILE = 0x404000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x2401 PERF_EVENT_IOC_ENABLE = 0x2400 PERF_EVENT_IOC_ID = 0x80042407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40042406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = 0xffffffff PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETCRUNCHREGS = 0x19 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETFPREGS = 0xe PTRACE_GETHBPREGS = 0x1d PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GETVFPREGS = 0x1b PTRACE_GETWMMXREGS = 0x12 PTRACE_GET_THREAD_AREA = 0x16 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETCRUNCHREGS = 0x1a PTRACE_SETFPREGS = 0xf PTRACE_SETHBPREGS = 0x1e PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SETVFPREGS = 0x1c PTRACE_SETWMMXREGS = 0x13 PTRACE_SET_SYSCALL = 0x17 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 PT_DATA_ADDR = 0x10004 PT_TEXT_ADDR = 0x10000 PT_TEXT_END_ADDR = 0x10008 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x8 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x7 RLIMIT_NPROC = 0x6 RLIMIT_RSS = 0x5 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x541b SIOCOUTQ = 0x5411 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1f SO_PRIORITY = 0xc SO_PROTOCOL = 0x26 SO_RCVBUF = 0x8 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x12 SO_RCVTIMEO = 0x14 SO_REUSEADDR = 0x2 SO_REUSEPORT = 0xf SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 TCSBRK = 0x5409 TCSBRKP = 0x5425 TCSETA = 0x5406 TCSETAF = 0x5408 TCSETAW = 0x5407 TCSETS = 0x5402 TCSETS2 = 0x402c542b TCSETSF = 0x5404 TCSETSF2 = 0x402c542d TCSETSW = 0x5403 TCSETSW2 = 0x402c542c TCSETX = 0x5433 TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c TIOCGDEV = 0x80045432 TIOCGETD = 0x5424 TIOCGEXCL = 0x80045440 TIOCGICOUNT = 0x545d TIOCGLCKTRMIOS = 0x5456 TIOCGPGRP = 0x540f TIOCGPKT = 0x80045438 TIOCGPTLCK = 0x80045439 TIOCGPTN = 0x80045430 TIOCGPTPEER = 0x5441 TIOCGRS485 = 0x542e TIOCGSERIAL = 0x541e TIOCGSID = 0x5429 TIOCGSOFTCAR = 0x5419 TIOCGWINSZ = 0x5413 TIOCINQ = 0x541b TIOCLINUX = 0x541c TIOCMBIC = 0x5417 TIOCMBIS = 0x5416 TIOCMGET = 0x5415 TIOCMIWAIT = 0x545c TIOCMSET = 0x5418 TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x5422 TIOCNXCL = 0x540d TIOCOUTQ = 0x5411 TIOCPKT = 0x5420 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x540e TIOCSERCONFIG = 0x5453 TIOCSERGETLSR = 0x5459 TIOCSERGETMULTI = 0x545a TIOCSERGSTRUCT = 0x5458 TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSLCKTRMIOS = 0x5457 TIOCSPGRP = 0x5410 TIOCSPTLCK = 0x40045431 TIOCSRS485 = 0x542f TIOCSSERIAL = 0x541f TIOCSSOFTCAR = 0x541a TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 TUNGETFEATURES = 0x800454cf TUNGETFILTER = 0x800854db TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETBE = 0x800454df TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x6 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x20 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x62) EADDRNOTAVAIL = syscall.Errno(0x63) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x61) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x72) EBADE = syscall.Errno(0x34) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x4d) EBADMSG = syscall.Errno(0x4a) EBADR = syscall.Errno(0x35) EBADRQC = syscall.Errno(0x38) EBADSLT = syscall.Errno(0x39) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x7d) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x2c) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x67) ECONNREFUSED = syscall.Errno(0x6f) ECONNRESET = syscall.Errno(0x68) EDEADLK = syscall.Errno(0x23) EDEADLOCK = syscall.Errno(0x23) EDESTADDRREQ = syscall.Errno(0x59) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x7a) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) EIDRM = syscall.Errno(0x2b) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x73) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x6a) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x78) EKEYEXPIRED = syscall.Errno(0x7f) EKEYREJECTED = syscall.Errno(0x81) EKEYREVOKED = syscall.Errno(0x80) EL2HLT = syscall.Errno(0x33) EL2NSYNC = syscall.Errno(0x2d) EL3HLT = syscall.Errno(0x2e) EL3RST = syscall.Errno(0x2f) ELIBACC = syscall.Errno(0x4f) ELIBBAD = syscall.Errno(0x50) ELIBEXEC = syscall.Errno(0x53) ELIBMAX = syscall.Errno(0x52) ELIBSCN = syscall.Errno(0x51) ELNRNG = syscall.Errno(0x30) ELOOP = syscall.Errno(0x28) EMEDIUMTYPE = syscall.Errno(0x7c) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x5a) EMULTIHOP = syscall.Errno(0x48) ENAMETOOLONG = syscall.Errno(0x24) ENAVAIL = syscall.Errno(0x77) ENETDOWN = syscall.Errno(0x64) ENETRESET = syscall.Errno(0x66) ENETUNREACH = syscall.Errno(0x65) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x37) ENOBUFS = syscall.Errno(0x69) ENOCSI = syscall.Errno(0x32) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0x7e) ENOLCK = syscall.Errno(0x25) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x7b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x2a) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x5c) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x26) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x6b) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x27) ENOTNAM = syscall.Errno(0x76) ENOTRECOVERABLE = syscall.Errno(0x83) ENOTSOCK = syscall.Errno(0x58) ENOTSUP = syscall.Errno(0x5f) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x4c) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x5f) EOVERFLOW = syscall.Errno(0x4b) EOWNERDEAD = syscall.Errno(0x82) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x60) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x5d) EPROTOTYPE = syscall.Errno(0x5b) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x4e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x79) ERESTART = syscall.Errno(0x55) ERFKILL = syscall.Errno(0x84) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x6c) ESOCKTNOSUPPORT = syscall.Errno(0x5e) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x74) ESTRPIPE = syscall.Errno(0x56) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x6e) ETOOMANYREFS = syscall.Errno(0x6d) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x75) EUNATCH = syscall.Errno(0x31) EUSERS = syscall.Errno(0x57) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x36) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0x7) SIGCHLD = syscall.Signal(0x11) SIGCLD = syscall.Signal(0x11) SIGCONT = syscall.Signal(0x12) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x1d) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x1d) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x1e) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTKFLT = syscall.Signal(0x10) SIGSTOP = syscall.Signal(0x13) SIGSYS = syscall.Signal(0x1f) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x14) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x17) SIGUSR1 = syscall.Signal(0xa) SIGUSR2 = syscall.Signal(0xc) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "resource deadlock avoided", 36: "file name too long", 37: "no locks available", 38: "function not implemented", 39: "directory not empty", 40: "too many levels of symbolic links", 42: "no message of desired type", 43: "identifier removed", 44: "channel number out of range", 45: "level 2 not synchronized", 46: "level 3 halted", 47: "level 3 reset", 48: "link number out of range", 49: "protocol driver not attached", 50: "no CSI structure available", 51: "level 2 halted", 52: "invalid exchange", 53: "invalid request descriptor", 54: "exchange full", 55: "no anode", 56: "invalid request code", 57: "invalid slot", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "multihop attempted", 73: "RFS specific error", 74: "bad message", 75: "value too large for defined data type", 76: "name not unique on network", 77: "file descriptor in bad state", 78: "remote address changed", 79: "can not access a needed shared library", 80: "accessing a corrupted shared library", 81: ".lib section in a.out corrupted", 82: "attempting to link in too many shared libraries", 83: "cannot exec a shared library directly", 84: "invalid or incomplete multibyte or wide character", 85: "interrupted system call should be restarted", 86: "streams pipe error", 87: "too many users", 88: "socket operation on non-socket", 89: "destination address required", 90: "message too long", 91: "protocol wrong type for socket", 92: "protocol not available", 93: "protocol not supported", 94: "socket type not supported", 95: "operation not supported", 96: "protocol family not supported", 97: "address family not supported by protocol", 98: "address already in use", 99: "cannot assign requested address", 100: "network is down", 101: "network is unreachable", 102: "network dropped connection on reset", 103: "software caused connection abort", 104: "connection reset by peer", 105: "no buffer space available", 106: "transport endpoint is already connected", 107: "transport endpoint is not connected", 108: "cannot send after transport endpoint shutdown", 109: "too many references: cannot splice", 110: "connection timed out", 111: "connection refused", 112: "host is down", 113: "no route to host", 114: "operation already in progress", 115: "operation now in progress", 116: "stale file handle", 117: "structure needs cleaning", 118: "not a XENIX named type file", 119: "no XENIX semaphores available", 120: "is a named type file", 121: "remote I/O error", 122: "disk quota exceeded", 123: "no medium found", 124: "wrong medium type", 125: "operation canceled", 126: "required key not available", 127: "key has expired", 128: "key has been revoked", 129: "key was rejected by service", 130: "owner died", 131: "state not recoverable", 132: "operation not possible due to RF-kill", 133: "memory page has hardware error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "bus error", 8: "floating point exception", 9: "killed", 10: "user defined signal 1", 11: "segmentation fault", 12: "user defined signal 2", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "stack fault", 17: "child exited", 18: "continued", 19: "stopped (signal)", 20: "stopped", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "urgent I/O condition", 24: "CPU time limit exceeded", 25: "file size limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window changed", 29: "I/O possible", 30: "power failure", 31: "bad system call", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_amd64.go0000644061062106075000000027545113172163421025614 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include -m64 _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d BLKRRPART = 0x125f BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0x5 F_GETLK64 = 0x5 F_GETOWN = 0x9 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0x6 F_SETLK64 = 0x6 F_SETLKW = 0x7 F_SETLKW64 = 0x7 F_SETOWN = 0x8 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x8000 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_32BIT = 0x40 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_HUGETLB = 0x40000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x2000 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x4000 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_STACK = 0x20000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 O_CLOEXEC = 0x80000 O_CREAT = 0x40 O_DIRECT = 0x4000 O_DIRECTORY = 0x10000 O_DSYNC = 0x1000 O_EXCL = 0x80 O_FSYNC = 0x101000 O_LARGEFILE = 0x0 O_NDELAY = 0x800 O_NOATIME = 0x40000 O_NOCTTY = 0x100 O_NOFOLLOW = 0x20000 O_NONBLOCK = 0x800 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x101000 O_SYNC = 0x101000 O_TMPFILE = 0x410000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x2401 PERF_EVENT_IOC_ENABLE = 0x2400 PERF_EVENT_IOC_ID = 0x80082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = -0x1 PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ARCH_PRCTL = 0x1e PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETFPREGS = 0xe PTRACE_GETFPXREGS = 0x12 PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GET_THREAD_AREA = 0x19 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETFPXREGS = 0x13 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SET_THREAD_AREA = 0x1a PTRACE_SINGLEBLOCK = 0x21 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_SYSEMU = 0x1f PTRACE_SYSEMU_SINGLESTEP = 0x20 PTRACE_TRACEME = 0x0 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x8 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x7 RLIMIT_NPROC = 0x6 RLIMIT_RSS = 0x5 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x541b SIOCOUTQ = 0x5411 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1f SO_PRIORITY = 0xc SO_PROTOCOL = 0x26 SO_RCVBUF = 0x8 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x12 SO_RCVTIMEO = 0x14 SO_REUSEADDR = 0x2 SO_REUSEPORT = 0xf SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 TCSBRK = 0x5409 TCSBRKP = 0x5425 TCSETA = 0x5406 TCSETAF = 0x5408 TCSETAW = 0x5407 TCSETS = 0x5402 TCSETS2 = 0x402c542b TCSETSF = 0x5404 TCSETSF2 = 0x402c542d TCSETSW = 0x5403 TCSETSW2 = 0x402c542c TCSETX = 0x5433 TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c TIOCGDEV = 0x80045432 TIOCGETD = 0x5424 TIOCGEXCL = 0x80045440 TIOCGICOUNT = 0x545d TIOCGLCKTRMIOS = 0x5456 TIOCGPGRP = 0x540f TIOCGPKT = 0x80045438 TIOCGPTLCK = 0x80045439 TIOCGPTN = 0x80045430 TIOCGPTPEER = 0x5441 TIOCGRS485 = 0x542e TIOCGSERIAL = 0x541e TIOCGSID = 0x5429 TIOCGSOFTCAR = 0x5419 TIOCGWINSZ = 0x5413 TIOCINQ = 0x541b TIOCLINUX = 0x541c TIOCMBIC = 0x5417 TIOCMBIS = 0x5416 TIOCMGET = 0x5415 TIOCMIWAIT = 0x545c TIOCMSET = 0x5418 TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x5422 TIOCNXCL = 0x540d TIOCOUTQ = 0x5411 TIOCPKT = 0x5420 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x540e TIOCSERCONFIG = 0x5453 TIOCSERGETLSR = 0x5459 TIOCSERGETMULTI = 0x545a TIOCSERGSTRUCT = 0x5458 TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSLCKTRMIOS = 0x5457 TIOCSPGRP = 0x5410 TIOCSPTLCK = 0x40045431 TIOCSRS485 = 0x542f TIOCSSERIAL = 0x541f TIOCSSOFTCAR = 0x541a TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf TUNGETFILTER = 0x801054db TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETBE = 0x800454df TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x6 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x40 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x62) EADDRNOTAVAIL = syscall.Errno(0x63) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x61) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x72) EBADE = syscall.Errno(0x34) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x4d) EBADMSG = syscall.Errno(0x4a) EBADR = syscall.Errno(0x35) EBADRQC = syscall.Errno(0x38) EBADSLT = syscall.Errno(0x39) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x7d) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x2c) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x67) ECONNREFUSED = syscall.Errno(0x6f) ECONNRESET = syscall.Errno(0x68) EDEADLK = syscall.Errno(0x23) EDEADLOCK = syscall.Errno(0x23) EDESTADDRREQ = syscall.Errno(0x59) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x7a) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) EIDRM = syscall.Errno(0x2b) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x73) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x6a) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x78) EKEYEXPIRED = syscall.Errno(0x7f) EKEYREJECTED = syscall.Errno(0x81) EKEYREVOKED = syscall.Errno(0x80) EL2HLT = syscall.Errno(0x33) EL2NSYNC = syscall.Errno(0x2d) EL3HLT = syscall.Errno(0x2e) EL3RST = syscall.Errno(0x2f) ELIBACC = syscall.Errno(0x4f) ELIBBAD = syscall.Errno(0x50) ELIBEXEC = syscall.Errno(0x53) ELIBMAX = syscall.Errno(0x52) ELIBSCN = syscall.Errno(0x51) ELNRNG = syscall.Errno(0x30) ELOOP = syscall.Errno(0x28) EMEDIUMTYPE = syscall.Errno(0x7c) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x5a) EMULTIHOP = syscall.Errno(0x48) ENAMETOOLONG = syscall.Errno(0x24) ENAVAIL = syscall.Errno(0x77) ENETDOWN = syscall.Errno(0x64) ENETRESET = syscall.Errno(0x66) ENETUNREACH = syscall.Errno(0x65) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x37) ENOBUFS = syscall.Errno(0x69) ENOCSI = syscall.Errno(0x32) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0x7e) ENOLCK = syscall.Errno(0x25) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x7b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x2a) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x5c) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x26) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x6b) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x27) ENOTNAM = syscall.Errno(0x76) ENOTRECOVERABLE = syscall.Errno(0x83) ENOTSOCK = syscall.Errno(0x58) ENOTSUP = syscall.Errno(0x5f) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x4c) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x5f) EOVERFLOW = syscall.Errno(0x4b) EOWNERDEAD = syscall.Errno(0x82) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x60) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x5d) EPROTOTYPE = syscall.Errno(0x5b) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x4e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x79) ERESTART = syscall.Errno(0x55) ERFKILL = syscall.Errno(0x84) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x6c) ESOCKTNOSUPPORT = syscall.Errno(0x5e) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x74) ESTRPIPE = syscall.Errno(0x56) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x6e) ETOOMANYREFS = syscall.Errno(0x6d) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x75) EUNATCH = syscall.Errno(0x31) EUSERS = syscall.Errno(0x57) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x36) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0x7) SIGCHLD = syscall.Signal(0x11) SIGCLD = syscall.Signal(0x11) SIGCONT = syscall.Signal(0x12) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x1d) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x1d) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x1e) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTKFLT = syscall.Signal(0x10) SIGSTOP = syscall.Signal(0x13) SIGSYS = syscall.Signal(0x1f) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x14) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x17) SIGUSR1 = syscall.Signal(0xa) SIGUSR2 = syscall.Signal(0xc) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "resource deadlock avoided", 36: "file name too long", 37: "no locks available", 38: "function not implemented", 39: "directory not empty", 40: "too many levels of symbolic links", 42: "no message of desired type", 43: "identifier removed", 44: "channel number out of range", 45: "level 2 not synchronized", 46: "level 3 halted", 47: "level 3 reset", 48: "link number out of range", 49: "protocol driver not attached", 50: "no CSI structure available", 51: "level 2 halted", 52: "invalid exchange", 53: "invalid request descriptor", 54: "exchange full", 55: "no anode", 56: "invalid request code", 57: "invalid slot", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "multihop attempted", 73: "RFS specific error", 74: "bad message", 75: "value too large for defined data type", 76: "name not unique on network", 77: "file descriptor in bad state", 78: "remote address changed", 79: "can not access a needed shared library", 80: "accessing a corrupted shared library", 81: ".lib section in a.out corrupted", 82: "attempting to link in too many shared libraries", 83: "cannot exec a shared library directly", 84: "invalid or incomplete multibyte or wide character", 85: "interrupted system call should be restarted", 86: "streams pipe error", 87: "too many users", 88: "socket operation on non-socket", 89: "destination address required", 90: "message too long", 91: "protocol wrong type for socket", 92: "protocol not available", 93: "protocol not supported", 94: "socket type not supported", 95: "operation not supported", 96: "protocol family not supported", 97: "address family not supported by protocol", 98: "address already in use", 99: "cannot assign requested address", 100: "network is down", 101: "network is unreachable", 102: "network dropped connection on reset", 103: "software caused connection abort", 104: "connection reset by peer", 105: "no buffer space available", 106: "transport endpoint is already connected", 107: "transport endpoint is not connected", 108: "cannot send after transport endpoint shutdown", 109: "too many references: cannot splice", 110: "connection timed out", 111: "connection refused", 112: "host is down", 113: "no route to host", 114: "operation already in progress", 115: "operation now in progress", 116: "stale file handle", 117: "structure needs cleaning", 118: "not a XENIX named type file", 119: "no XENIX semaphores available", 120: "is a named type file", 121: "remote I/O error", 122: "disk quota exceeded", 123: "no medium found", 124: "wrong medium type", 125: "operation canceled", 126: "required key not available", 127: "key has expired", 128: "key has been revoked", 129: "key was rejected by service", 130: "owner died", 131: "state not recoverable", 132: "operation not possible due to RF-kill", 133: "memory page has hardware error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "bus error", 8: "floating point exception", 9: "killed", 10: "user defined signal 1", 11: "segmentation fault", 12: "user defined signal 2", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "stack fault", 17: "child exited", 18: "continued", 19: "stopped (signal)", 20: "stopped", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "urgent I/O condition", 24: "CPU time limit exceeded", 25: "file size limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window changed", 29: "I/O possible", 30: "power failure", 31: "bad system call", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_linux_386.go0000644061062106075000000027540313172163421025216 0ustar stgraberdomain admins// mkerrors.sh -Wall -Werror -static -I/tmp/include -m32 // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -Wall -Werror -static -I/tmp/include -m32 _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IB = 0x1b AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KCM = 0x29 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x2c AF_MPLS = 0x1c AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_QIPCRTR = 0x2a AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SMC = 0x2b AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ALG_OP_DECRYPT = 0x0 ALG_OP_ENCRYPT = 0x1 ALG_SET_AEAD_ASSOCLEN = 0x4 ALG_SET_AEAD_AUTHSIZE = 0x5 ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BLKBSZGET = 0x80041270 BLKBSZSET = 0x40041271 BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80041272 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d BLKRRPART = 0x125f BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LL_OFF = -0x200000 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_NET_OFF = -0x100000 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d CAN_EFF_MASK = 0x1fffffff CAN_ERR_FLAG = 0x20000000 CAN_ERR_MASK = 0x1fffffff CAN_INV_FILTER = 0x20000000 CAN_ISOTP = 0x6 CAN_MAX_DLC = 0x8 CAN_MAX_DLEN = 0x8 CAN_MCNET = 0x5 CAN_MTU = 0x10 CAN_NPROTO = 0x7 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff CAN_TP16 = 0x3 CAN_TP20 = 0x4 CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 CLOCK_BOOTTIME_ALARM = 0x9 CLOCK_DEFAULT = 0x0 CLOCK_EXT = 0x1 CLOCK_INT = 0x2 CLOCK_MONOTONIC = 0x1 CLOCK_MONOTONIC_COARSE = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_PROCESS_CPUTIME_ID = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_ALARM = 0x8 CLOCK_REALTIME_COARSE = 0x5 CLOCK_TAI = 0xb CLOCK_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWCGROUP = 0x2000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLEXCLUSIVE = 0x10000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWAKEUP = 0x20000000 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_80221 = 0x8917 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_802_3_MIN = 0x600 ETH_P_802_EX1 = 0x88b5 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BATMAN = 0x4305 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CANFD = 0xd ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PRP = 0x88fb ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_TSN = 0x22f0 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_NO_HIDE_STALE = 0x4 FALLOC_FL_PUNCH_HOLE = 0x2 FALLOC_FL_UNSHARE_RANGE = 0x40 FALLOC_FL_ZERO_RANGE = 0x10 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 FS_ENCRYPTION_MODE_AES_256_CTS = 0x4 FS_ENCRYPTION_MODE_AES_256_GCM = 0x2 FS_ENCRYPTION_MODE_AES_256_XTS = 0x1 FS_ENCRYPTION_MODE_INVALID = 0x0 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 FS_KEY_DESCRIPTOR_SIZE = 0x8 FS_KEY_DESC_PREFIX = "fscrypt:" FS_KEY_DESC_PREFIX_SIZE = 0x8 FS_MAX_KEY_SIZE = 0x40 FS_POLICY_FLAGS_PAD_16 = 0x2 FS_POLICY_FLAGS_PAD_32 = 0x3 FS_POLICY_FLAGS_PAD_4 = 0x0 FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 F_GETLK = 0xc F_GETLK64 = 0xc F_GETOWN = 0x9 F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 F_SETLK = 0xd F_SETLK64 = 0xd F_SETLKW = 0xe F_SETLKW64 = 0xe F_SETOWN = 0x8 F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 GENL_ADMIN_PERM = 0x1 GENL_CMD_CAP_DO = 0x2 GENL_CMD_CAP_DUMP = 0x4 GENL_CMD_CAP_HASPOL = 0x8 GENL_HDRLEN = 0x4 GENL_ID_CTRL = 0x10 GENL_ID_PMCRAID = 0x12 GENL_ID_VFS_DQUOT = 0x11 GENL_MAX_ID = 0x3ff GENL_MIN_ID = 0x10 GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 ICMPV6_FILTER = 0x1 ICRNL = 0x100 IEXTEN = 0x8000 IFA_F_DADFAILED = 0x8 IFA_F_DEPRECATED = 0x20 IFA_F_HOMEADDRESS = 0x10 IFA_F_MANAGETEMPADDR = 0x100 IFA_F_MCAUTOJOIN = 0x400 IFA_F_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_STABLE_PRIVACY = 0x800 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x8 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_ECHO = 0x40000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADDR_PREFERENCES = 0x48 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_AUTOFLOWLABEL = 0x46 IPV6_CHECKSUM = 0x7 IPV6_DONTFRAG = 0x3e IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HDRINCL = 0x24 IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MINHOPCOUNT = 0x49 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_ORIGDSTADDR = 0x4a IPV6_PATHMTU = 0x3d IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_INTERFACE = 0x4 IPV6_PMTUDISC_OMIT = 0x5 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVFRAGSIZE = 0x4d IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVORIGDSTADDR = 0x4a IPV6_RECVPATHMTU = 0x3c IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_TRANSPARENT = 0x4b IPV6_UNICAST_HOPS = 0x10 IPV6_UNICAST_IF = 0x4c IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BIND_ADDRESS_NO_PORT = 0x18 IP_BLOCK_SOURCE = 0x26 IP_CHECKSUM = 0x17 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_NODEFRAG = 0x16 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_INTERFACE = 0x4 IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVFRAGSIZE = 0x19 IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 KEYCTL_DESCRIBE = 0x6 KEYCTL_DH_COMPUTE = 0x17 KEYCTL_GET_KEYRING_ID = 0x0 KEYCTL_GET_PERSISTENT = 0x16 KEYCTL_GET_SECURITY = 0x11 KEYCTL_INSTANTIATE = 0xc KEYCTL_INSTANTIATE_IOV = 0x14 KEYCTL_INVALIDATE = 0x15 KEYCTL_JOIN_SESSION_KEYRING = 0x1 KEYCTL_LINK = 0x8 KEYCTL_NEGATE = 0xd KEYCTL_READ = 0xb KEYCTL_REJECT = 0x13 KEYCTL_RESTRICT_KEYRING = 0x1d KEYCTL_REVOKE = 0x3 KEYCTL_SEARCH = 0xa KEYCTL_SESSION_TO_PARENT = 0x12 KEYCTL_SETPERM = 0x5 KEYCTL_SET_REQKEY_KEYRING = 0xe KEYCTL_SET_TIMEOUT = 0xf KEYCTL_UNLINK = 0x9 KEYCTL_UPDATE = 0x2 KEY_REQKEY_DEFL_DEFAULT = 0x0 KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6 KEY_REQKEY_DEFL_NO_CHANGE = -0x1 KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2 KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7 KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3 KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1 KEY_REQKEY_DEFL_USER_KEYRING = 0x4 KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5 KEY_SPEC_GROUP_KEYRING = -0x6 KEY_SPEC_PROCESS_KEYRING = -0x2 KEY_SPEC_REQKEY_AUTH_KEY = -0x7 KEY_SPEC_REQUESTOR_KEYRING = -0x8 KEY_SPEC_SESSION_KEYRING = -0x3 KEY_SPEC_THREAD_KEYRING = -0x1 KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DODUMP = 0x11 MADV_DOFORK = 0xb MADV_DONTDUMP = 0x10 MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_32BIT = 0x40 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_HUGETLB = 0x40000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_LOCKED = 0x2000 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x4000 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_STACK = 0x20000 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_BORN = 0x20000000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_LAZYTIME = 0x2000000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOREMOTELOCK = 0x8000000 MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x2800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SUBMOUNT = 0x4000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CAP_ACK = 0xa NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_EXT_ACK = 0xb NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_LISTEN_ALL_NSID = 0x8 NETLINK_LIST_MEMBERSHIPS = 0x9 NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_RX_RING = 0x6 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_SMC = 0x16 NETLINK_SOCK_DIAG = 0x4 NETLINK_TX_RING = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_ACK_TLVS = 0x200 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CAPPED = 0x100 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_FILTERED = 0x20 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 O_CLOEXEC = 0x80000 O_CREAT = 0x40 O_DIRECT = 0x4000 O_DIRECTORY = 0x10000 O_DSYNC = 0x1000 O_EXCL = 0x80 O_FSYNC = 0x101000 O_LARGEFILE = 0x8000 O_NDELAY = 0x800 O_NOATIME = 0x40000 O_NOCTTY = 0x100 O_NOFOLLOW = 0x20000 O_NONBLOCK = 0x800 O_PATH = 0x200000 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x101000 O_SYNC = 0x101000 O_TMPFILE = 0x410000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CBPF = 0x6 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_DATA = 0x16 PACKET_FANOUT_EBPF = 0x7 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_FLAG_UNIQUEID = 0x2000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_QM = 0x5 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_KERNEL = 0x7 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_QDISC_BYPASS = 0x14 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_ROLLOVER_STATS = 0x15 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_USER = 0x6 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PERF_EVENT_IOC_DISABLE = 0x2401 PERF_EVENT_IOC_ENABLE = 0x2400 PERF_EVENT_IOC_ID = 0x80042407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40042406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_CAP_AMBIENT = 0x2f PR_CAP_AMBIENT_CLEAR_ALL = 0x4 PR_CAP_AMBIENT_IS_SET = 0x1 PR_CAP_AMBIENT_LOWER = 0x3 PR_CAP_AMBIENT_RAISE = 0x2 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_FP_MODE_FR = 0x1 PR_FP_MODE_FRE = 0x2 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_THP_DISABLE = 0x2a PR_GET_TID_ADDRESS = 0x28 PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b PR_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 PR_SET_MM_ARG_START = 0x8 PR_SET_MM_AUXV = 0xc PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 PR_SET_MM_ENV_END = 0xb PR_SET_MM_ENV_START = 0xa PR_SET_MM_EXE_FILE = 0xd PR_SET_MM_MAP = 0xe PR_SET_MM_MAP_SIZE = 0xf PR_SET_MM_START_BRK = 0x6 PR_SET_MM_START_CODE = 0x1 PR_SET_MM_START_DATA = 0x3 PR_SET_MM_START_STACK = 0x5 PR_SET_NAME = 0xf PR_SET_NO_NEW_PRIVS = 0x26 PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER_ANY = 0xffffffff PR_SET_SECCOMP = 0x16 PR_SET_SECUREBITS = 0x1c PR_SET_THP_DISABLE = 0x29 PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_SECCOMP = 0x7 PTRACE_EVENT_STOP = 0x80 PTRACE_EVENT_VFORK = 0x2 PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETEVENTMSG = 0x4201 PTRACE_GETFPREGS = 0xe PTRACE_GETFPXREGS = 0x12 PTRACE_GETREGS = 0xc PTRACE_GETREGSET = 0x4204 PTRACE_GETSIGINFO = 0x4202 PTRACE_GETSIGMASK = 0x420a PTRACE_GET_THREAD_AREA = 0x19 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_EXITKILL = 0x100000 PTRACE_O_MASK = 0x3000ff PTRACE_O_SUSPEND_SECCOMP = 0x200000 PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESECCOMP = 0x80 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKSIGINFO = 0x4209 PTRACE_PEEKSIGINFO_SHARED = 0x1 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETFPXREGS = 0x13 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 PTRACE_SETSIGMASK = 0x420b PTRACE_SET_THREAD_AREA = 0x1a PTRACE_SINGLEBLOCK = 0x21 PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_SYSEMU = 0x1f PTRACE_SYSEMU_SINGLESTEP = 0x20 PTRACE_TRACEME = 0x0 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_LOCKS = 0xa RLIMIT_MEMLOCK = 0x8 RLIMIT_MSGQUEUE = 0xc RLIMIT_NICE = 0xd RLIMIT_NOFILE = 0x7 RLIMIT_NPROC = 0x6 RLIMIT_RSS = 0x5 RLIMIT_RTPRIO = 0xe RLIMIT_RTTIME = 0xf RLIMIT_SIGPENDING = 0xb RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_MASK = 0xf RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0x10 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x1a RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELMDB = 0x55 RTM_DELNEIGH = 0x1d RTM_DELNETCONF = 0x51 RTM_DELNSID = 0x59 RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETNSID = 0x5a RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x63 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWCACHEREPORT = 0x60 RTM_NEWLINK = 0x10 RTM_NEWMDB = 0x54 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWNETCONF = 0x50 RTM_NEWNSID = 0x58 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x15 RTM_NR_MSGTYPES = 0x54 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_COMPARE_MASK = 0x19 RTNH_F_DEAD = 0x1 RTNH_F_LINKDOWN = 0x10 RTNH_F_OFFLOAD = 0x8 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTNH_F_UNRESOLVED = 0x20 RTN_MAX = 0xb RTPROT_BABEL = 0x2a RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCBONDCHANGEACTIVE = 0x8995 SIOCBONDENSLAVE = 0x8990 SIOCBONDINFOQUERY = 0x8994 SIOCBONDRELEASE = 0x8991 SIOCBONDSETHWADDR = 0x8992 SIOCBONDSLAVEINFOQUERY = 0x8993 SIOCBRADDBR = 0x89a0 SIOCBRADDIF = 0x89a2 SIOCBRDELBR = 0x89a1 SIOCBRDELIF = 0x89a3 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCETHTOOL = 0x8946 SIOCGARP = 0x8954 SIOCGHWTSTAMP = 0x89b1 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGIFVLAN = 0x8982 SIOCGMIIPHY = 0x8947 SIOCGMIIREG = 0x8948 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSKNS = 0x894c SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCINQ = 0x541b SIOCOUTQ = 0x5411 SIOCOUTQNSD = 0x894b SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSHWTSTAMP = 0x89b0 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSIFVLAN = 0x8983 SIOCSMIIREG = 0x8949 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_IOC_TYPE = 0x89 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ALG = 0x117 SOL_ATM = 0x108 SOL_CAIF = 0x116 SOL_CAN_BASE = 0x64 SOL_DCCP = 0x10d SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_IUCV = 0x115 SOL_KCM = 0x119 SOL_LLC = 0x10c SOL_NETBEUI = 0x10b SOL_NETLINK = 0x10e SOL_NFC = 0x118 SOL_PACKET = 0x107 SOL_PNPIPE = 0x113 SOL_PPPOL2TP = 0x111 SOL_RAW = 0xff SOL_RDS = 0x114 SOL_RXRPC = 0x110 SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_BPF = 0x32 SO_ATTACH_FILTER = 0x1a SO_ATTACH_REUSEPORT_CBPF = 0x33 SO_ATTACH_REUSEPORT_EBPF = 0x34 SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_CNX_ADVICE = 0x35 SO_COOKIE = 0x39 SO_DEBUG = 0x1 SO_DETACH_BPF = 0x1b SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a SO_INCOMING_CPU = 0x31 SO_INCOMING_NAPI_ID = 0x38 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_LOCK_FILTER = 0x2c SO_MARK = 0x24 SO_MAX_PACING_RATE = 0x2f SO_MEMINFO = 0x37 SO_NOFCS = 0x2b SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b SO_PEERNAME = 0x1c SO_PEERSEC = 0x1f SO_PRIORITY = 0xc SO_PROTOCOL = 0x26 SO_RCVBUF = 0x8 SO_RCVBUFFORCE = 0x21 SO_RCVLOWAT = 0x12 SO_RCVTIMEO = 0x14 SO_REUSEADDR = 0x2 SO_REUSEPORT = 0xf SO_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SELECT_ERR_QUEUE = 0x2d SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2 SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1 SO_VM_SOCKETS_BUFFER_SIZE = 0x0 SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6 SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7 SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TASKSTATS_CMD_ATTR_MAX = 0x4 TASKSTATS_CMD_MAX = 0x2 TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CC_INFO = 0x1a TCP_CONGESTION = 0xd TCP_COOKIE_IN_ALWAYS = 0x1 TCP_COOKIE_MAX = 0x10 TCP_COOKIE_MIN = 0x8 TCP_COOKIE_OUT_NEVER = 0x2 TCP_COOKIE_PAIR_SIZE = 0x20 TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 TCP_MSS_DESIRED = 0x4c4 TCP_NODELAY = 0x1 TCP_NOTSENT_LOWAT = 0x19 TCP_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 TCP_S_DATA_IN = 0x4 TCP_S_DATA_OUT = 0x8 TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 TCSBRK = 0x5409 TCSBRKP = 0x5425 TCSETA = 0x5406 TCSETAF = 0x5408 TCSETAW = 0x5407 TCSETS = 0x5402 TCSETS2 = 0x402c542b TCSETSF = 0x5404 TCSETSF2 = 0x402c542d TCSETSW = 0x5403 TCSETSW2 = 0x402c542c TCSETX = 0x5433 TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c TIOCGDEV = 0x80045432 TIOCGETD = 0x5424 TIOCGEXCL = 0x80045440 TIOCGICOUNT = 0x545d TIOCGLCKTRMIOS = 0x5456 TIOCGPGRP = 0x540f TIOCGPKT = 0x80045438 TIOCGPTLCK = 0x80045439 TIOCGPTN = 0x80045430 TIOCGPTPEER = 0x5441 TIOCGRS485 = 0x542e TIOCGSERIAL = 0x541e TIOCGSID = 0x5429 TIOCGSOFTCAR = 0x5419 TIOCGWINSZ = 0x5413 TIOCINQ = 0x541b TIOCLINUX = 0x541c TIOCMBIC = 0x5417 TIOCMBIS = 0x5416 TIOCMGET = 0x5415 TIOCMIWAIT = 0x545c TIOCMSET = 0x5418 TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x5422 TIOCNXCL = 0x540d TIOCOUTQ = 0x5411 TIOCPKT = 0x5420 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCSBRK = 0x5427 TIOCSCTTY = 0x540e TIOCSERCONFIG = 0x5453 TIOCSERGETLSR = 0x5459 TIOCSERGETMULTI = 0x545a TIOCSERGSTRUCT = 0x5458 TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSLCKTRMIOS = 0x5457 TIOCSPGRP = 0x5410 TIOCSPTLCK = 0x40045431 TIOCSRS485 = 0x542f TIOCSSERIAL = 0x541f TIOCSSOFTCAR = 0x541a TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 TUNGETFEATURES = 0x800454cf TUNGETFILTER = 0x800854db TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETBE = 0x800454df TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc UMOUNT_NOFOLLOW = 0x8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 VMADDR_CID_RESERVED = 0x1 VMADDR_PORT_ANY = 0xffffffff VMIN = 0x6 VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 VSUSP = 0xa VSWTC = 0x7 VT0 = 0x0 VT1 = 0x4000 VTDLY = 0x4000 VTIME = 0x5 VWERASE = 0xe WALL = 0x40000000 WCLONE = 0x80000000 WCONTINUED = 0x8 WEXITED = 0x4 WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x20 WSTOPPED = 0x2 WUNTRACED = 0x2 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 XTABS = 0x1800 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x62) EADDRNOTAVAIL = syscall.Errno(0x63) EADV = syscall.Errno(0x44) EAFNOSUPPORT = syscall.Errno(0x61) EAGAIN = syscall.Errno(0xb) EALREADY = syscall.Errno(0x72) EBADE = syscall.Errno(0x34) EBADF = syscall.Errno(0x9) EBADFD = syscall.Errno(0x4d) EBADMSG = syscall.Errno(0x4a) EBADR = syscall.Errno(0x35) EBADRQC = syscall.Errno(0x38) EBADSLT = syscall.Errno(0x39) EBFONT = syscall.Errno(0x3b) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x7d) ECHILD = syscall.Errno(0xa) ECHRNG = syscall.Errno(0x2c) ECOMM = syscall.Errno(0x46) ECONNABORTED = syscall.Errno(0x67) ECONNREFUSED = syscall.Errno(0x6f) ECONNRESET = syscall.Errno(0x68) EDEADLK = syscall.Errno(0x23) EDEADLOCK = syscall.Errno(0x23) EDESTADDRREQ = syscall.Errno(0x59) EDOM = syscall.Errno(0x21) EDOTDOT = syscall.Errno(0x49) EDQUOT = syscall.Errno(0x7a) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) EIDRM = syscall.Errno(0x2b) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x73) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x6a) EISDIR = syscall.Errno(0x15) EISNAM = syscall.Errno(0x78) EKEYEXPIRED = syscall.Errno(0x7f) EKEYREJECTED = syscall.Errno(0x81) EKEYREVOKED = syscall.Errno(0x80) EL2HLT = syscall.Errno(0x33) EL2NSYNC = syscall.Errno(0x2d) EL3HLT = syscall.Errno(0x2e) EL3RST = syscall.Errno(0x2f) ELIBACC = syscall.Errno(0x4f) ELIBBAD = syscall.Errno(0x50) ELIBEXEC = syscall.Errno(0x53) ELIBMAX = syscall.Errno(0x52) ELIBSCN = syscall.Errno(0x51) ELNRNG = syscall.Errno(0x30) ELOOP = syscall.Errno(0x28) EMEDIUMTYPE = syscall.Errno(0x7c) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x5a) EMULTIHOP = syscall.Errno(0x48) ENAMETOOLONG = syscall.Errno(0x24) ENAVAIL = syscall.Errno(0x77) ENETDOWN = syscall.Errno(0x64) ENETRESET = syscall.Errno(0x66) ENETUNREACH = syscall.Errno(0x65) ENFILE = syscall.Errno(0x17) ENOANO = syscall.Errno(0x37) ENOBUFS = syscall.Errno(0x69) ENOCSI = syscall.Errno(0x32) ENODATA = syscall.Errno(0x3d) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOKEY = syscall.Errno(0x7e) ENOLCK = syscall.Errno(0x25) ENOLINK = syscall.Errno(0x43) ENOMEDIUM = syscall.Errno(0x7b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x2a) ENONET = syscall.Errno(0x40) ENOPKG = syscall.Errno(0x41) ENOPROTOOPT = syscall.Errno(0x5c) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x3f) ENOSTR = syscall.Errno(0x3c) ENOSYS = syscall.Errno(0x26) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x6b) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x27) ENOTNAM = syscall.Errno(0x76) ENOTRECOVERABLE = syscall.Errno(0x83) ENOTSOCK = syscall.Errno(0x58) ENOTSUP = syscall.Errno(0x5f) ENOTTY = syscall.Errno(0x19) ENOTUNIQ = syscall.Errno(0x4c) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x5f) EOVERFLOW = syscall.Errno(0x4b) EOWNERDEAD = syscall.Errno(0x82) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x60) EPIPE = syscall.Errno(0x20) EPROTO = syscall.Errno(0x47) EPROTONOSUPPORT = syscall.Errno(0x5d) EPROTOTYPE = syscall.Errno(0x5b) ERANGE = syscall.Errno(0x22) EREMCHG = syscall.Errno(0x4e) EREMOTE = syscall.Errno(0x42) EREMOTEIO = syscall.Errno(0x79) ERESTART = syscall.Errno(0x55) ERFKILL = syscall.Errno(0x84) EROFS = syscall.Errno(0x1e) ESHUTDOWN = syscall.Errno(0x6c) ESOCKTNOSUPPORT = syscall.Errno(0x5e) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESRMNT = syscall.Errno(0x45) ESTALE = syscall.Errno(0x74) ESTRPIPE = syscall.Errno(0x56) ETIME = syscall.Errno(0x3e) ETIMEDOUT = syscall.Errno(0x6e) ETOOMANYREFS = syscall.Errno(0x6d) ETXTBSY = syscall.Errno(0x1a) EUCLEAN = syscall.Errno(0x75) EUNATCH = syscall.Errno(0x31) EUSERS = syscall.Errno(0x57) EWOULDBLOCK = syscall.Errno(0xb) EXDEV = syscall.Errno(0x12) EXFULL = syscall.Errno(0x36) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0x7) SIGCHLD = syscall.Signal(0x11) SIGCLD = syscall.Signal(0x11) SIGCONT = syscall.Signal(0x12) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x1d) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPOLL = syscall.Signal(0x1d) SIGPROF = syscall.Signal(0x1b) SIGPWR = syscall.Signal(0x1e) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTKFLT = syscall.Signal(0x10) SIGSTOP = syscall.Signal(0x13) SIGSYS = syscall.Signal(0x1f) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x14) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x17) SIGUSR1 = syscall.Signal(0xa) SIGUSR2 = syscall.Signal(0xc) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "no such device or address", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource temporarily unavailable", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device or resource busy", 17: "file exists", 18: "invalid cross-device link", 19: "no such device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "numerical result out of range", 35: "resource deadlock avoided", 36: "file name too long", 37: "no locks available", 38: "function not implemented", 39: "directory not empty", 40: "too many levels of symbolic links", 42: "no message of desired type", 43: "identifier removed", 44: "channel number out of range", 45: "level 2 not synchronized", 46: "level 3 halted", 47: "level 3 reset", 48: "link number out of range", 49: "protocol driver not attached", 50: "no CSI structure available", 51: "level 2 halted", 52: "invalid exchange", 53: "invalid request descriptor", 54: "exchange full", 55: "no anode", 56: "invalid request code", 57: "invalid slot", 59: "bad font file format", 60: "device not a stream", 61: "no data available", 62: "timer expired", 63: "out of streams resources", 64: "machine is not on the network", 65: "package not installed", 66: "object is remote", 67: "link has been severed", 68: "advertise error", 69: "srmount error", 70: "communication error on send", 71: "protocol error", 72: "multihop attempted", 73: "RFS specific error", 74: "bad message", 75: "value too large for defined data type", 76: "name not unique on network", 77: "file descriptor in bad state", 78: "remote address changed", 79: "can not access a needed shared library", 80: "accessing a corrupted shared library", 81: ".lib section in a.out corrupted", 82: "attempting to link in too many shared libraries", 83: "cannot exec a shared library directly", 84: "invalid or incomplete multibyte or wide character", 85: "interrupted system call should be restarted", 86: "streams pipe error", 87: "too many users", 88: "socket operation on non-socket", 89: "destination address required", 90: "message too long", 91: "protocol wrong type for socket", 92: "protocol not available", 93: "protocol not supported", 94: "socket type not supported", 95: "operation not supported", 96: "protocol family not supported", 97: "address family not supported by protocol", 98: "address already in use", 99: "cannot assign requested address", 100: "network is down", 101: "network is unreachable", 102: "network dropped connection on reset", 103: "software caused connection abort", 104: "connection reset by peer", 105: "no buffer space available", 106: "transport endpoint is already connected", 107: "transport endpoint is not connected", 108: "cannot send after transport endpoint shutdown", 109: "too many references: cannot splice", 110: "connection timed out", 111: "connection refused", 112: "host is down", 113: "no route to host", 114: "operation already in progress", 115: "operation now in progress", 116: "stale file handle", 117: "structure needs cleaning", 118: "not a XENIX named type file", 119: "no XENIX semaphores available", 120: "is a named type file", 121: "remote I/O error", 122: "disk quota exceeded", 123: "no medium found", 124: "wrong medium type", 125: "operation canceled", 126: "required key not available", 127: "key has expired", 128: "key has been revoked", 129: "key was rejected by service", 130: "owner died", 131: "state not recoverable", 132: "operation not possible due to RF-kill", 133: "memory page has hardware error", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/breakpoint trap", 6: "aborted", 7: "bus error", 8: "floating point exception", 9: "killed", 10: "user defined signal 1", 11: "segmentation fault", 12: "user defined signal 2", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "stack fault", 17: "child exited", 18: "continued", 19: "stopped (signal)", 20: "stopped", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "urgent I/O condition", 24: "CPU time limit exceeded", 25: "file size limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window changed", 29: "I/O possible", 30: "power failure", 31: "bad system call", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_freebsd_arm.go0000644061062106075000000020576513172163421025734 0ustar stgraberdomain admins// mkerrors.sh // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_ARP = 0x23 AF_ATM = 0x1e AF_BLUETOOTH = 0x24 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x25 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1c AF_INET6_SDP = 0x2a AF_INET_SDP = 0x28 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x2a AF_NATM = 0x1d AF_NETBIOS = 0x6 AF_NETGRAPH = 0x20 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SCLUSTER = 0x22 AF_SIP = 0x18 AF_SLOW = 0x21 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VENDOR00 = 0x27 AF_VENDOR01 = 0x29 AF_VENDOR02 = 0x2b AF_VENDOR03 = 0x2d AF_VENDOR04 = 0x2f AF_VENDOR05 = 0x31 AF_VENDOR06 = 0x33 AF_VENDOR07 = 0x35 AF_VENDOR08 = 0x37 AF_VENDOR09 = 0x39 AF_VENDOR10 = 0x3b AF_VENDOR11 = 0x3d AF_VENDOR12 = 0x3f AF_VENDOR13 = 0x41 AF_VENDOR14 = 0x43 AF_VENDOR15 = 0x45 AF_VENDOR16 = 0x47 AF_VENDOR17 = 0x49 AF_VENDOR18 = 0x4b AF_VENDOR19 = 0x4d AF_VENDOR20 = 0x4f AF_VENDOR21 = 0x51 AF_VENDOR22 = 0x53 AF_VENDOR23 = 0x55 AF_VENDOR24 = 0x57 AF_VENDOR25 = 0x59 AF_VENDOR26 = 0x5b AF_VENDOR27 = 0x5d AF_VENDOR28 = 0x5f AF_VENDOR29 = 0x61 AF_VENDOR30 = 0x63 AF_VENDOR31 = 0x65 AF_VENDOR32 = 0x67 AF_VENDOR33 = 0x69 AF_VENDOR34 = 0x6b AF_VENDOR35 = 0x6d AF_VENDOR36 = 0x6f AF_VENDOR37 = 0x71 AF_VENDOR38 = 0x73 AF_VENDOR39 = 0x75 AF_VENDOR40 = 0x77 AF_VENDOR41 = 0x79 AF_VENDOR42 = 0x7b AF_VENDOR43 = 0x7d AF_VENDOR44 = 0x7f AF_VENDOR45 = 0x81 AF_VENDOR46 = 0x83 AF_VENDOR47 = 0x85 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B460800 = 0x70800 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B921600 = 0xe1000 B9600 = 0x2580 BIOCFEEDBACK = 0x8004427c BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRECTION = 0x40044276 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc0084279 BIOCGETBUFMODE = 0x4004427d BIOCGETIF = 0x4020426b BIOCGETZMAX = 0x4004427f BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4010426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCGTSTAMP = 0x40044283 BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x2000427a BIOCPROMISC = 0x20004269 BIOCROTZBUF = 0x400c4280 BIOCSBLEN = 0xc0044266 BIOCSDIRECTION = 0x80044277 BIOCSDLT = 0x80044278 BIOCSETBUFMODE = 0x8004427e BIOCSETF = 0x80084267 BIOCSETFNR = 0x80084282 BIOCSETIF = 0x8020426c BIOCSETWF = 0x8008427b BIOCSETZBUF = 0x800c4281 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8010426d BIOCSSEESENT = 0x80044277 BIOCSTSTAMP = 0x80044284 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_BUFMODE_BUFFER = 0x1 BPF_BUFMODE_ZBUF = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_T_BINTIME = 0x2 BPF_T_BINTIME_FAST = 0x102 BPF_T_BINTIME_MONOTONIC = 0x202 BPF_T_BINTIME_MONOTONIC_FAST = 0x302 BPF_T_FAST = 0x100 BPF_T_FLAG_MASK = 0x300 BPF_T_FORMAT_MASK = 0x3 BPF_T_MICROTIME = 0x0 BPF_T_MICROTIME_FAST = 0x100 BPF_T_MICROTIME_MONOTONIC = 0x200 BPF_T_MICROTIME_MONOTONIC_FAST = 0x300 BPF_T_MONOTONIC = 0x200 BPF_T_MONOTONIC_FAST = 0x300 BPF_T_NANOTIME = 0x1 BPF_T_NANOTIME_FAST = 0x101 BPF_T_NANOTIME_MONOTONIC = 0x201 BPF_T_NANOTIME_MONOTONIC_FAST = 0x301 BPF_T_NONE = 0x3 BPF_T_NORMAL = 0x0 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 CAP_ACCEPT = 0x200000020000000 CAP_ACL_CHECK = 0x400000000010000 CAP_ACL_DELETE = 0x400000000020000 CAP_ACL_GET = 0x400000000040000 CAP_ACL_SET = 0x400000000080000 CAP_ALL0 = 0x20007ffffffffff CAP_ALL1 = 0x4000000001fffff CAP_BIND = 0x200000040000000 CAP_BINDAT = 0x200008000000400 CAP_CHFLAGSAT = 0x200000000001400 CAP_CONNECT = 0x200000080000000 CAP_CONNECTAT = 0x200010000000400 CAP_CREATE = 0x200000000000040 CAP_EVENT = 0x400000000000020 CAP_EXTATTR_DELETE = 0x400000000001000 CAP_EXTATTR_GET = 0x400000000002000 CAP_EXTATTR_LIST = 0x400000000004000 CAP_EXTATTR_SET = 0x400000000008000 CAP_FCHDIR = 0x200000000000800 CAP_FCHFLAGS = 0x200000000001000 CAP_FCHMOD = 0x200000000002000 CAP_FCHMODAT = 0x200000000002400 CAP_FCHOWN = 0x200000000004000 CAP_FCHOWNAT = 0x200000000004400 CAP_FCNTL = 0x200000000008000 CAP_FCNTL_ALL = 0x78 CAP_FCNTL_GETFL = 0x8 CAP_FCNTL_GETOWN = 0x20 CAP_FCNTL_SETFL = 0x10 CAP_FCNTL_SETOWN = 0x40 CAP_FEXECVE = 0x200000000000080 CAP_FLOCK = 0x200000000010000 CAP_FPATHCONF = 0x200000000020000 CAP_FSCK = 0x200000000040000 CAP_FSTAT = 0x200000000080000 CAP_FSTATAT = 0x200000000080400 CAP_FSTATFS = 0x200000000100000 CAP_FSYNC = 0x200000000000100 CAP_FTRUNCATE = 0x200000000000200 CAP_FUTIMES = 0x200000000200000 CAP_FUTIMESAT = 0x200000000200400 CAP_GETPEERNAME = 0x200000100000000 CAP_GETSOCKNAME = 0x200000200000000 CAP_GETSOCKOPT = 0x200000400000000 CAP_IOCTL = 0x400000000000080 CAP_IOCTLS_ALL = 0x7fffffff CAP_KQUEUE = 0x400000000100040 CAP_KQUEUE_CHANGE = 0x400000000100000 CAP_KQUEUE_EVENT = 0x400000000000040 CAP_LINKAT_SOURCE = 0x200020000000400 CAP_LINKAT_TARGET = 0x200000000400400 CAP_LISTEN = 0x200000800000000 CAP_LOOKUP = 0x200000000000400 CAP_MAC_GET = 0x400000000000001 CAP_MAC_SET = 0x400000000000002 CAP_MKDIRAT = 0x200000000800400 CAP_MKFIFOAT = 0x200000001000400 CAP_MKNODAT = 0x200000002000400 CAP_MMAP = 0x200000000000010 CAP_MMAP_R = 0x20000000000001d CAP_MMAP_RW = 0x20000000000001f CAP_MMAP_RWX = 0x20000000000003f CAP_MMAP_RX = 0x20000000000003d CAP_MMAP_W = 0x20000000000001e CAP_MMAP_WX = 0x20000000000003e CAP_MMAP_X = 0x20000000000003c CAP_PDGETPID = 0x400000000000200 CAP_PDKILL = 0x400000000000800 CAP_PDWAIT = 0x400000000000400 CAP_PEELOFF = 0x200001000000000 CAP_POLL_EVENT = 0x400000000000020 CAP_PREAD = 0x20000000000000d CAP_PWRITE = 0x20000000000000e CAP_READ = 0x200000000000001 CAP_RECV = 0x200000000000001 CAP_RENAMEAT_SOURCE = 0x200000004000400 CAP_RENAMEAT_TARGET = 0x200040000000400 CAP_RIGHTS_VERSION = 0x0 CAP_RIGHTS_VERSION_00 = 0x0 CAP_SEEK = 0x20000000000000c CAP_SEEK_TELL = 0x200000000000004 CAP_SEM_GETVALUE = 0x400000000000004 CAP_SEM_POST = 0x400000000000008 CAP_SEM_WAIT = 0x400000000000010 CAP_SEND = 0x200000000000002 CAP_SETSOCKOPT = 0x200002000000000 CAP_SHUTDOWN = 0x200004000000000 CAP_SOCK_CLIENT = 0x200007780000003 CAP_SOCK_SERVER = 0x200007f60000003 CAP_SYMLINKAT = 0x200000008000400 CAP_TTYHOOK = 0x400000000000100 CAP_UNLINKAT = 0x200000010000400 CAP_UNUSED0_44 = 0x200080000000000 CAP_UNUSED0_57 = 0x300000000000000 CAP_UNUSED1_22 = 0x400000000200000 CAP_UNUSED1_57 = 0x500000000000000 CAP_WRITE = 0x200000000000002 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x4 CLOCK_MONOTONIC_FAST = 0xc CLOCK_MONOTONIC_PRECISE = 0xb CLOCK_PROCESS_CPUTIME_ID = 0xf CLOCK_PROF = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_FAST = 0xa CLOCK_REALTIME_PRECISE = 0x9 CLOCK_SECOND = 0xd CLOCK_THREAD_CPUTIME_ID = 0xe CLOCK_UPTIME = 0x5 CLOCK_UPTIME_FAST = 0x8 CLOCK_UPTIME_PRECISE = 0x7 CLOCK_VIRTUAL = 0x1 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0x18 CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_BREDR_BB = 0xff DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_BLUETOOTH_LE_LL = 0xfb DLT_BLUETOOTH_LE_LL_WITH_PHDR = 0x100 DLT_BLUETOOTH_LINUX_MONITOR = 0xfe DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_CLASS_NETBSD_RAWAF = 0x2240000 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_EPON = 0x103 DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NOFCS = 0xe6 DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_INFINIBAND = 0xf7 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPMI_HPM_2 = 0x104 DLT_IPNET = 0xe2 DLT_IPOIB = 0xf2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_ISO_14443 = 0x108 DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FIBRECHANNEL = 0xea DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_SRX_E2E = 0xe9 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_JUNIPER_VS = 0xe8 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MATCHING_MAX = 0x109 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPEG_2_TS = 0xf3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_MUX27010 = 0xec DLT_NETANALYZER = 0xf0 DLT_NETANALYZER_TRANSPARENT = 0xf1 DLT_NETLINK = 0xfd DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PPP_WITH_DIRECTION = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PROFIBUS_DL = 0x101 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RDS = 0x109 DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xd DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 DLT_USB_FREEBSD = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DLT_WATTSTOPPER_DLM = 0x107 DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DLT_ZWAVE_R1_R2 = 0x105 DLT_ZWAVE_R3 = 0x106 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_PROCDESC = -0x8 EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xc EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_DROP = 0x1000 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_FLAG2 = 0x4000 EV_FORCEONESHOT = 0x100 EV_ONESHOT = 0x10 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_CANCEL = 0x5 F_DUP2FD = 0xa F_DUP2FD_CLOEXEC = 0x12 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x11 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0xb F_GETOWN = 0x5 F_OGETLK = 0x7 F_OK = 0x0 F_OSETLK = 0x8 F_OSETLKW = 0x9 F_RDAHEAD = 0x10 F_RDLCK = 0x1 F_READAHEAD = 0xf F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0xc F_SETLKW = 0xd F_SETLK_REMOTE = 0xe F_SETOWN = 0x6 F_UNLCK = 0x2 F_UNLCKSYS = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x218f52 IFF_CANTCONFIG = 0x10000 IFF_DEBUG = 0x4 IFF_DRV_OACTIVE = 0x400 IFF_DRV_RUNNING = 0x40 IFF_DYING = 0x200000 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 IFF_PROMISC = 0x100 IFF_RENAMING = 0x400000 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_STATICARP = 0x80000 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_BRIDGE = 0xd1 IFT_CARP = 0xf8 IFT_IEEE1394 = 0x90 IFT_INFINIBAND = 0xc7 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_PPP = 0x17 IFT_PROPVIRTUAL = 0x35 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_MASK = 0xfffffffe IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CARP = 0x70 IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0x102 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HIP = 0x8b IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MEAS = 0x13 IPPROTO_MH = 0x87 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OLD_DIVERT = 0xfe IPPROTO_OSPFIGP = 0x59 IPPROTO_PFSYNC = 0xf0 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_RESERVED_253 = 0xfd IPPROTO_RESERVED_254 = 0xfe IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SCTP = 0x84 IPPROTO_SDRP = 0x2a IPPROTO_SEND = 0x103 IPPROTO_SEP = 0x21 IPPROTO_SHIM6 = 0x8c IPPROTO_SKIP = 0x39 IPPROTO_SPACER = 0x7fff IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TLSP = 0x38 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_AUTOFLOWLABEL = 0x3b IPV6_BINDANY = 0x40 IPV6_BINDMULTI = 0x41 IPV6_BINDV6ONLY = 0x1b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXOPTHDR = 0x800 IPV6_MAXPACKET = 0xffff IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_PREFER_TEMPADDR = 0x3f IPV6_RECVDSTOPTS = 0x28 IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RSSBUCKETID = 0x45 IPV6_RSS_LISTEN_BUCKET = 0x42 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 IP_BINDMULTI = 0x19 IP_BLOCK_SOURCE = 0x48 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DONTFRAG = 0x43 IP_DROP_MEMBERSHIP = 0xd IP_DROP_SOURCE_MEMBERSHIP = 0x47 IP_DUMMYNET3 = 0x31 IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FLOWID = 0x5a IP_FLOWTYPE = 0x5b IP_FW3 = 0x30 IP_FW_ADD = 0x32 IP_FW_DEL = 0x33 IP_FW_FLUSH = 0x34 IP_FW_GET = 0x36 IP_FW_NAT_CFG = 0x38 IP_FW_NAT_DEL = 0x39 IP_FW_NAT_GET_CONFIG = 0x3a IP_FW_NAT_GET_LOG = 0x3b IP_FW_RESETLOG = 0x37 IP_FW_TABLE_ADD = 0x28 IP_FW_TABLE_DEL = 0x29 IP_FW_TABLE_FLUSH = 0x2a IP_FW_TABLE_GETSIZE = 0x2b IP_FW_TABLE_LIST = 0x2c IP_FW_ZERO = 0x35 IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_GROUP_SRC_FILTER = 0x200 IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 IP_RECVTTL = 0x41 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSSBUCKETID = 0x5c IP_RSS_LISTEN_BUCKET = 0x1a IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_SENDSRCADDR = 0x7 IP_TOS = 0x3 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x49 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_AUTOSYNC = 0x7 MADV_CORE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_NOCORE = 0x8 MADV_NORMAL = 0x0 MADV_NOSYNC = 0x6 MADV_PROTECT = 0xa MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MAP_ALIGNED_SUPER = 0x1000000 MAP_ALIGNMENT_MASK = -0x1000000 MAP_ALIGNMENT_SHIFT = 0x18 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GUARD = 0x2000 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RESERVED0020 = 0x20 MAP_RESERVED0040 = 0x40 MAP_RESERVED0080 = 0x80 MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 MNT_ASYNC = 0x40 MNT_AUTOMOUNTED = 0x200000000 MNT_BYFSID = 0x8000000 MNT_CMDFLAGS = 0xd0f0000 MNT_DEFEXPORTED = 0x200 MNT_DELEXPORT = 0x20000 MNT_EXKERB = 0x800 MNT_EXPORTANON = 0x400 MNT_EXPORTED = 0x100 MNT_EXPUBLIC = 0x20000000 MNT_EXRDONLY = 0x80 MNT_FORCE = 0x80000 MNT_GJOURNAL = 0x2000000 MNT_IGNORE = 0x800000 MNT_LAZY = 0x3 MNT_LOCAL = 0x1000 MNT_MULTILABEL = 0x4000000 MNT_NFS4ACLS = 0x10 MNT_NOATIME = 0x10000000 MNT_NOCLUSTERR = 0x40000000 MNT_NOCLUSTERW = 0x80000000 MNT_NOEXEC = 0x4 MNT_NONBUSY = 0x4000000 MNT_NOSUID = 0x8 MNT_NOSYMFOLLOW = 0x400000 MNT_NOWAIT = 0x2 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SNAPSHOT = 0x1000000 MNT_SOFTDEP = 0x200000 MNT_SUIDDIR = 0x100000 MNT_SUJ = 0x100000000 MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 MNT_UPDATE = 0x10000 MNT_UPDATEMASK = 0x2d8d0807e MNT_USER = 0x8000 MNT_VISFLAGMASK = 0x3fef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_NBIO = 0x4000 MSG_NOSIGNAL = 0x20000 MSG_NOTIFICATION = 0x2000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MSG_WAITFORONE = 0x80000 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_SYNC = 0x0 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFLISTL = 0x5 NET_RT_IFMALIST = 0x4 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 NOTE_CLOSE_WRITE = 0x200 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FILE_POLL = 0x2 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_MSECONDS = 0x2 NOTE_NSECONDS = 0x8 NOTE_OPEN = 0x80 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_READ = 0x400 NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_SECONDS = 0x1 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_USECONDS = 0x4 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x100000 O_CREAT = 0x200 O_DIRECT = 0x10000 O_DIRECTORY = 0x20000 O_EXCL = 0x800 O_EXEC = 0x40000 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_TTY_INIT = 0x80000 O_VERIFY = 0x200000 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0xa RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x8 RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FIXEDMTU = 0x80000 RTF_FMASK = 0x1004d808 RTF_GATEWAY = 0x2 RTF_GWFLAG_COMPAT = 0x80000000 RTF_HOST = 0x4 RTF_LLDATA = 0x400 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MULTICAST = 0x800000 RTF_PINNED = 0x100000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_REJECT = 0x8 RTF_RNH_LOCKED = 0x40000000 RTF_STATIC = 0x800 RTF_STICKY = 0x10000000 RTF_UP = 0x1 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_IEEE80211 = 0x12 RTM_IFANNOUNCE = 0x11 RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 RT_HAS_HEADER_BIT = 0x4 RT_L2_ME = 0x4 RT_L2_ME_BIT = 0x2 RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCGDRVSPEC = 0xc01c697b SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 SIOCGHWADDR = 0xc020693e SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020691f SIOCGIFCONF = 0xc0086924 SIOCGIFDESCR = 0xc020692a SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFIB = 0xc020695c SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc024698a SIOCGIFGROUP = 0xc0246988 SIOCGIFINDEX = 0xc0206920 SIOCGIFMAC = 0xc0206926 SIOCGIFMEDIA = 0xc0286938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc028698b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 SIOCGTUNFIB = 0xc020695e SIOCIFCREATE = 0xc020697a SIOCIFCREATE2 = 0xc020697c SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc00c6978 SIOCSDRVSPEC = 0x801c697b SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020691e SIOCSIFDESCR = 0x80206929 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFIB = 0x8020695d SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020693c SIOCSIFMAC = 0x80206927 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNAME = 0x80206928 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f SOCK_CLOEXEC = 0x10000000 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_NONBLOCK = 0x20000000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ACCEPTFILTER = 0x1000 SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LABEL = 0x1009 SO_LINGER = 0x80 SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 SO_OOBINLINE = 0x100 SO_PEERLABEL = 0x1010 SO_PROTOCOL = 0x1016 SO_PROTOTYPE = 0x1016 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 SO_VENDOR = 0x80000000 TAB0 = 0x0 TAB3 = 0x4 TABDLY = 0x4 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 TCP_FASTOPEN = 0x401 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 TCP_KEEPCNT = 0x400 TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x4 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x10 TCP_MINMSS = 0xd8 TCP_MSS = 0x218 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGPTN = 0x4004740f TIOCGSID = 0x40047463 TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DCD = 0x40 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTMASTER = 0x2000741c TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSIG = 0x2004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VERASE2 = 0x7 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x4 WCOREFLAG = 0x80 WEXITED = 0x10 WLINUXCLONE = 0x80000000 WNOHANG = 0x1 WNOWAIT = 0x8 WSTOPPED = 0x2 WTRAPPED = 0x20 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x59) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x55) ECAPMODE = syscall.Errno(0x5e) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDOOFUS = syscall.Errno(0x58) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x52) EILSEQ = syscall.Errno(0x56) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x60) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5a) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x57) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x5b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x53) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCAPABLE = syscall.Errno(0x5d) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x5f) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x54) EOWNERDEAD = syscall.Errno(0x60) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x5c) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGLIBRT = syscall.Signal(0x21) SIGLWP = syscall.Signal(0x20) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "identifier removed", 83: "no message of desired type", 84: "value too large to be stored in data type", 85: "operation canceled", 86: "illegal byte sequence", 87: "attribute not found", 88: "programming error", 89: "bad message", 90: "multihop attempted", 91: "link has been severed", 92: "protocol error", 93: "capabilities insufficient", 94: "not permitted in capability mode", 95: "state not recoverable", 96: "previous owner died", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "unknown signal", 33: "unknown signal", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_freebsd_amd64.go0000644061062106075000000020530313172163421026054 0ustar stgraberdomain admins// mkerrors.sh -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_ARP = 0x23 AF_ATM = 0x1e AF_BLUETOOTH = 0x24 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x25 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1c AF_INET6_SDP = 0x2a AF_INET_SDP = 0x28 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x2a AF_NATM = 0x1d AF_NETBIOS = 0x6 AF_NETGRAPH = 0x20 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SCLUSTER = 0x22 AF_SIP = 0x18 AF_SLOW = 0x21 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VENDOR00 = 0x27 AF_VENDOR01 = 0x29 AF_VENDOR02 = 0x2b AF_VENDOR03 = 0x2d AF_VENDOR04 = 0x2f AF_VENDOR05 = 0x31 AF_VENDOR06 = 0x33 AF_VENDOR07 = 0x35 AF_VENDOR08 = 0x37 AF_VENDOR09 = 0x39 AF_VENDOR10 = 0x3b AF_VENDOR11 = 0x3d AF_VENDOR12 = 0x3f AF_VENDOR13 = 0x41 AF_VENDOR14 = 0x43 AF_VENDOR15 = 0x45 AF_VENDOR16 = 0x47 AF_VENDOR17 = 0x49 AF_VENDOR18 = 0x4b AF_VENDOR19 = 0x4d AF_VENDOR20 = 0x4f AF_VENDOR21 = 0x51 AF_VENDOR22 = 0x53 AF_VENDOR23 = 0x55 AF_VENDOR24 = 0x57 AF_VENDOR25 = 0x59 AF_VENDOR26 = 0x5b AF_VENDOR27 = 0x5d AF_VENDOR28 = 0x5f AF_VENDOR29 = 0x61 AF_VENDOR30 = 0x63 AF_VENDOR31 = 0x65 AF_VENDOR32 = 0x67 AF_VENDOR33 = 0x69 AF_VENDOR34 = 0x6b AF_VENDOR35 = 0x6d AF_VENDOR36 = 0x6f AF_VENDOR37 = 0x71 AF_VENDOR38 = 0x73 AF_VENDOR39 = 0x75 AF_VENDOR40 = 0x77 AF_VENDOR41 = 0x79 AF_VENDOR42 = 0x7b AF_VENDOR43 = 0x7d AF_VENDOR44 = 0x7f AF_VENDOR45 = 0x81 AF_VENDOR46 = 0x83 AF_VENDOR47 = 0x85 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B460800 = 0x70800 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B921600 = 0xe1000 B9600 = 0x2580 BIOCFEEDBACK = 0x8004427c BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRECTION = 0x40044276 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc0104279 BIOCGETBUFMODE = 0x4004427d BIOCGETIF = 0x4020426b BIOCGETZMAX = 0x4008427f BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4010426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCGTSTAMP = 0x40044283 BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x2000427a BIOCPROMISC = 0x20004269 BIOCROTZBUF = 0x40184280 BIOCSBLEN = 0xc0044266 BIOCSDIRECTION = 0x80044277 BIOCSDLT = 0x80044278 BIOCSETBUFMODE = 0x8004427e BIOCSETF = 0x80104267 BIOCSETFNR = 0x80104282 BIOCSETIF = 0x8020426c BIOCSETWF = 0x8010427b BIOCSETZBUF = 0x80184281 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8010426d BIOCSSEESENT = 0x80044277 BIOCSTSTAMP = 0x80044284 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x8 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_BUFMODE_BUFFER = 0x1 BPF_BUFMODE_ZBUF = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_T_BINTIME = 0x2 BPF_T_BINTIME_FAST = 0x102 BPF_T_BINTIME_MONOTONIC = 0x202 BPF_T_BINTIME_MONOTONIC_FAST = 0x302 BPF_T_FAST = 0x100 BPF_T_FLAG_MASK = 0x300 BPF_T_FORMAT_MASK = 0x3 BPF_T_MICROTIME = 0x0 BPF_T_MICROTIME_FAST = 0x100 BPF_T_MICROTIME_MONOTONIC = 0x200 BPF_T_MICROTIME_MONOTONIC_FAST = 0x300 BPF_T_MONOTONIC = 0x200 BPF_T_MONOTONIC_FAST = 0x300 BPF_T_NANOTIME = 0x1 BPF_T_NANOTIME_FAST = 0x101 BPF_T_NANOTIME_MONOTONIC = 0x201 BPF_T_NANOTIME_MONOTONIC_FAST = 0x301 BPF_T_NONE = 0x3 BPF_T_NORMAL = 0x0 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 CAP_ACCEPT = 0x200000020000000 CAP_ACL_CHECK = 0x400000000010000 CAP_ACL_DELETE = 0x400000000020000 CAP_ACL_GET = 0x400000000040000 CAP_ACL_SET = 0x400000000080000 CAP_ALL0 = 0x20007ffffffffff CAP_ALL1 = 0x4000000001fffff CAP_BIND = 0x200000040000000 CAP_BINDAT = 0x200008000000400 CAP_CHFLAGSAT = 0x200000000001400 CAP_CONNECT = 0x200000080000000 CAP_CONNECTAT = 0x200010000000400 CAP_CREATE = 0x200000000000040 CAP_EVENT = 0x400000000000020 CAP_EXTATTR_DELETE = 0x400000000001000 CAP_EXTATTR_GET = 0x400000000002000 CAP_EXTATTR_LIST = 0x400000000004000 CAP_EXTATTR_SET = 0x400000000008000 CAP_FCHDIR = 0x200000000000800 CAP_FCHFLAGS = 0x200000000001000 CAP_FCHMOD = 0x200000000002000 CAP_FCHMODAT = 0x200000000002400 CAP_FCHOWN = 0x200000000004000 CAP_FCHOWNAT = 0x200000000004400 CAP_FCNTL = 0x200000000008000 CAP_FCNTL_ALL = 0x78 CAP_FCNTL_GETFL = 0x8 CAP_FCNTL_GETOWN = 0x20 CAP_FCNTL_SETFL = 0x10 CAP_FCNTL_SETOWN = 0x40 CAP_FEXECVE = 0x200000000000080 CAP_FLOCK = 0x200000000010000 CAP_FPATHCONF = 0x200000000020000 CAP_FSCK = 0x200000000040000 CAP_FSTAT = 0x200000000080000 CAP_FSTATAT = 0x200000000080400 CAP_FSTATFS = 0x200000000100000 CAP_FSYNC = 0x200000000000100 CAP_FTRUNCATE = 0x200000000000200 CAP_FUTIMES = 0x200000000200000 CAP_FUTIMESAT = 0x200000000200400 CAP_GETPEERNAME = 0x200000100000000 CAP_GETSOCKNAME = 0x200000200000000 CAP_GETSOCKOPT = 0x200000400000000 CAP_IOCTL = 0x400000000000080 CAP_IOCTLS_ALL = 0x7fffffffffffffff CAP_KQUEUE = 0x400000000100040 CAP_KQUEUE_CHANGE = 0x400000000100000 CAP_KQUEUE_EVENT = 0x400000000000040 CAP_LINKAT_SOURCE = 0x200020000000400 CAP_LINKAT_TARGET = 0x200000000400400 CAP_LISTEN = 0x200000800000000 CAP_LOOKUP = 0x200000000000400 CAP_MAC_GET = 0x400000000000001 CAP_MAC_SET = 0x400000000000002 CAP_MKDIRAT = 0x200000000800400 CAP_MKFIFOAT = 0x200000001000400 CAP_MKNODAT = 0x200000002000400 CAP_MMAP = 0x200000000000010 CAP_MMAP_R = 0x20000000000001d CAP_MMAP_RW = 0x20000000000001f CAP_MMAP_RWX = 0x20000000000003f CAP_MMAP_RX = 0x20000000000003d CAP_MMAP_W = 0x20000000000001e CAP_MMAP_WX = 0x20000000000003e CAP_MMAP_X = 0x20000000000003c CAP_PDGETPID = 0x400000000000200 CAP_PDKILL = 0x400000000000800 CAP_PDWAIT = 0x400000000000400 CAP_PEELOFF = 0x200001000000000 CAP_POLL_EVENT = 0x400000000000020 CAP_PREAD = 0x20000000000000d CAP_PWRITE = 0x20000000000000e CAP_READ = 0x200000000000001 CAP_RECV = 0x200000000000001 CAP_RENAMEAT_SOURCE = 0x200000004000400 CAP_RENAMEAT_TARGET = 0x200040000000400 CAP_RIGHTS_VERSION = 0x0 CAP_RIGHTS_VERSION_00 = 0x0 CAP_SEEK = 0x20000000000000c CAP_SEEK_TELL = 0x200000000000004 CAP_SEM_GETVALUE = 0x400000000000004 CAP_SEM_POST = 0x400000000000008 CAP_SEM_WAIT = 0x400000000000010 CAP_SEND = 0x200000000000002 CAP_SETSOCKOPT = 0x200002000000000 CAP_SHUTDOWN = 0x200004000000000 CAP_SOCK_CLIENT = 0x200007780000003 CAP_SOCK_SERVER = 0x200007f60000003 CAP_SYMLINKAT = 0x200000008000400 CAP_TTYHOOK = 0x400000000000100 CAP_UNLINKAT = 0x200000010000400 CAP_UNUSED0_44 = 0x200080000000000 CAP_UNUSED0_57 = 0x300000000000000 CAP_UNUSED1_22 = 0x400000000200000 CAP_UNUSED1_57 = 0x500000000000000 CAP_WRITE = 0x200000000000002 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x4 CLOCK_MONOTONIC_FAST = 0xc CLOCK_MONOTONIC_PRECISE = 0xb CLOCK_PROCESS_CPUTIME_ID = 0xf CLOCK_PROF = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_FAST = 0xa CLOCK_REALTIME_PRECISE = 0x9 CLOCK_SECOND = 0xd CLOCK_THREAD_CPUTIME_ID = 0xe CLOCK_UPTIME = 0x5 CLOCK_UPTIME_FAST = 0x8 CLOCK_UPTIME_PRECISE = 0x7 CLOCK_VIRTUAL = 0x1 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0x18 CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_BREDR_BB = 0xff DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_BLUETOOTH_LE_LL = 0xfb DLT_BLUETOOTH_LE_LL_WITH_PHDR = 0x100 DLT_BLUETOOTH_LINUX_MONITOR = 0xfe DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_EPON = 0x103 DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NOFCS = 0xe6 DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_INFINIBAND = 0xf7 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPMI_HPM_2 = 0x104 DLT_IPNET = 0xe2 DLT_IPOIB = 0xf2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FIBRECHANNEL = 0xea DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_SRX_E2E = 0xe9 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_JUNIPER_VS = 0xe8 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MATCHING_MAX = 0x104 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPEG_2_TS = 0xf3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_MUX27010 = 0xec DLT_NETANALYZER = 0xf0 DLT_NETANALYZER_TRANSPARENT = 0xf1 DLT_NETLINK = 0xfd DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PPP_WITH_DIRECTION = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PROFIBUS_DL = 0x101 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_PROCDESC = -0x8 EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xc EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_DROP = 0x1000 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_FLAG2 = 0x4000 EV_FORCEONESHOT = 0x100 EV_ONESHOT = 0x10 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_CANCEL = 0x5 F_DUP2FD = 0xa F_DUP2FD_CLOEXEC = 0x12 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x11 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0xb F_GETOWN = 0x5 F_OGETLK = 0x7 F_OK = 0x0 F_OSETLK = 0x8 F_OSETLKW = 0x9 F_RDAHEAD = 0x10 F_RDLCK = 0x1 F_READAHEAD = 0xf F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0xc F_SETLKW = 0xd F_SETLK_REMOTE = 0xe F_SETOWN = 0x6 F_UNLCK = 0x2 F_UNLCKSYS = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x218f52 IFF_CANTCONFIG = 0x10000 IFF_DEBUG = 0x4 IFF_DRV_OACTIVE = 0x400 IFF_DRV_RUNNING = 0x40 IFF_DYING = 0x200000 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 IFF_PROMISC = 0x100 IFF_RENAMING = 0x400000 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_STATICARP = 0x80000 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_BRIDGE = 0xd1 IFT_CARP = 0xf8 IFT_IEEE1394 = 0x90 IFT_INFINIBAND = 0xc7 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_PPP = 0x17 IFT_PROPVIRTUAL = 0x35 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_MASK = 0xfffffffe IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CARP = 0x70 IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0x102 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HIP = 0x8b IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MEAS = 0x13 IPPROTO_MH = 0x87 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OLD_DIVERT = 0xfe IPPROTO_OSPFIGP = 0x59 IPPROTO_PFSYNC = 0xf0 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_RESERVED_253 = 0xfd IPPROTO_RESERVED_254 = 0xfe IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SCTP = 0x84 IPPROTO_SDRP = 0x2a IPPROTO_SEND = 0x103 IPPROTO_SEP = 0x21 IPPROTO_SHIM6 = 0x8c IPPROTO_SKIP = 0x39 IPPROTO_SPACER = 0x7fff IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TLSP = 0x38 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_AUTOFLOWLABEL = 0x3b IPV6_BINDANY = 0x40 IPV6_BINDMULTI = 0x41 IPV6_BINDV6ONLY = 0x1b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXOPTHDR = 0x800 IPV6_MAXPACKET = 0xffff IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_PREFER_TEMPADDR = 0x3f IPV6_RECVDSTOPTS = 0x28 IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RSSBUCKETID = 0x45 IPV6_RSS_LISTEN_BUCKET = 0x42 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 IP_BINDMULTI = 0x19 IP_BLOCK_SOURCE = 0x48 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DONTFRAG = 0x43 IP_DROP_MEMBERSHIP = 0xd IP_DROP_SOURCE_MEMBERSHIP = 0x47 IP_DUMMYNET3 = 0x31 IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FLOWID = 0x5a IP_FLOWTYPE = 0x5b IP_FW3 = 0x30 IP_FW_ADD = 0x32 IP_FW_DEL = 0x33 IP_FW_FLUSH = 0x34 IP_FW_GET = 0x36 IP_FW_NAT_CFG = 0x38 IP_FW_NAT_DEL = 0x39 IP_FW_NAT_GET_CONFIG = 0x3a IP_FW_NAT_GET_LOG = 0x3b IP_FW_RESETLOG = 0x37 IP_FW_TABLE_ADD = 0x28 IP_FW_TABLE_DEL = 0x29 IP_FW_TABLE_FLUSH = 0x2a IP_FW_TABLE_GETSIZE = 0x2b IP_FW_TABLE_LIST = 0x2c IP_FW_ZERO = 0x35 IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_GROUP_SRC_FILTER = 0x200 IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 IP_RECVTTL = 0x41 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSSBUCKETID = 0x5c IP_RSS_LISTEN_BUCKET = 0x1a IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_SENDSRCADDR = 0x7 IP_TOS = 0x3 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x49 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_AUTOSYNC = 0x7 MADV_CORE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_NOCORE = 0x8 MADV_NORMAL = 0x0 MADV_NOSYNC = 0x6 MADV_PROTECT = 0xa MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MAP_32BIT = 0x80000 MAP_ALIGNED_SUPER = 0x1000000 MAP_ALIGNMENT_MASK = -0x1000000 MAP_ALIGNMENT_SHIFT = 0x18 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RESERVED0020 = 0x20 MAP_RESERVED0040 = 0x40 MAP_RESERVED0080 = 0x80 MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 MNT_ASYNC = 0x40 MNT_AUTOMOUNTED = 0x200000000 MNT_BYFSID = 0x8000000 MNT_CMDFLAGS = 0xd0f0000 MNT_DEFEXPORTED = 0x200 MNT_DELEXPORT = 0x20000 MNT_EXKERB = 0x800 MNT_EXPORTANON = 0x400 MNT_EXPORTED = 0x100 MNT_EXPUBLIC = 0x20000000 MNT_EXRDONLY = 0x80 MNT_FORCE = 0x80000 MNT_GJOURNAL = 0x2000000 MNT_IGNORE = 0x800000 MNT_LAZY = 0x3 MNT_LOCAL = 0x1000 MNT_MULTILABEL = 0x4000000 MNT_NFS4ACLS = 0x10 MNT_NOATIME = 0x10000000 MNT_NOCLUSTERR = 0x40000000 MNT_NOCLUSTERW = 0x80000000 MNT_NOEXEC = 0x4 MNT_NONBUSY = 0x4000000 MNT_NOSUID = 0x8 MNT_NOSYMFOLLOW = 0x400000 MNT_NOWAIT = 0x2 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SNAPSHOT = 0x1000000 MNT_SOFTDEP = 0x200000 MNT_SUIDDIR = 0x100000 MNT_SUJ = 0x100000000 MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 MNT_UPDATE = 0x10000 MNT_UPDATEMASK = 0x2d8d0807e MNT_USER = 0x8000 MNT_VISFLAGMASK = 0x3fef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_NBIO = 0x4000 MSG_NOSIGNAL = 0x20000 MSG_NOTIFICATION = 0x2000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MSG_WAITFORONE = 0x80000 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_SYNC = 0x0 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFLISTL = 0x5 NET_RT_IFMALIST = 0x4 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 NOTE_CLOSE_WRITE = 0x200 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FILE_POLL = 0x2 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_MSECONDS = 0x2 NOTE_NSECONDS = 0x8 NOTE_OPEN = 0x80 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_READ = 0x400 NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_SECONDS = 0x1 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_USECONDS = 0x4 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x100000 O_CREAT = 0x200 O_DIRECT = 0x10000 O_DIRECTORY = 0x20000 O_EXCL = 0x800 O_EXEC = 0x40000 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_TTY_INIT = 0x80000 O_VERIFY = 0x200000 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0xa RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x8 RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FIXEDMTU = 0x80000 RTF_FMASK = 0x1004d808 RTF_GATEWAY = 0x2 RTF_GWFLAG_COMPAT = 0x80000000 RTF_HOST = 0x4 RTF_LLDATA = 0x400 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MULTICAST = 0x800000 RTF_PINNED = 0x100000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_REJECT = 0x8 RTF_RNH_LOCKED = 0x40000000 RTF_STATIC = 0x800 RTF_STICKY = 0x10000000 RTF_UP = 0x1 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_IEEE80211 = 0x12 RTM_IFANNOUNCE = 0x11 RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 RT_HAS_HEADER_BIT = 0x4 RT_L2_ME = 0x4 RT_L2_ME_BIT = 0x2 RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80286987 SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80286989 SIOCDIFPHYADDR = 0x80206949 SIOCGDRVSPEC = 0xc028697b SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020691f SIOCGIFCONF = 0xc0106924 SIOCGIFDESCR = 0xc020692a SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFIB = 0xc020695c SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc028698a SIOCGIFGROUP = 0xc0286988 SIOCGIFINDEX = 0xc0206920 SIOCGIFMAC = 0xc0206926 SIOCGIFMEDIA = 0xc0306938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc030698b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 SIOCGTUNFIB = 0xc020695e SIOCIFCREATE = 0xc020697a SIOCIFCREATE2 = 0xc020697c SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106978 SIOCSDRVSPEC = 0x8028697b SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020691e SIOCSIFDESCR = 0x80206929 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFIB = 0x8020695d SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020693c SIOCSIFMAC = 0x80206927 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNAME = 0x80206928 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f SOCK_CLOEXEC = 0x10000000 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_NONBLOCK = 0x20000000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ACCEPTFILTER = 0x1000 SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LABEL = 0x1009 SO_LINGER = 0x80 SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 SO_OOBINLINE = 0x100 SO_PEERLABEL = 0x1010 SO_PROTOCOL = 0x1016 SO_PROTOTYPE = 0x1016 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 SO_VENDOR = 0x80000000 TAB0 = 0x0 TAB3 = 0x4 TABDLY = 0x4 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 TCP_FASTOPEN = 0x401 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 TCP_KEEPCNT = 0x400 TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x4 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x10 TCP_MINMSS = 0xd8 TCP_MSS = 0x218 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGPTN = 0x4004740f TIOCGSID = 0x40047463 TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DCD = 0x40 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTMASTER = 0x2000741c TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSIG = 0x2004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VERASE2 = 0x7 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x4 WCOREFLAG = 0x80 WEXITED = 0x10 WLINUXCLONE = 0x80000000 WNOHANG = 0x1 WNOWAIT = 0x8 WSTOPPED = 0x2 WTRAPPED = 0x20 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x59) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x55) ECAPMODE = syscall.Errno(0x5e) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDOOFUS = syscall.Errno(0x58) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x52) EILSEQ = syscall.Errno(0x56) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x60) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5a) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x57) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x5b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x53) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCAPABLE = syscall.Errno(0x5d) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x5f) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x54) EOWNERDEAD = syscall.Errno(0x60) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x5c) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGLIBRT = syscall.Signal(0x21) SIGLWP = syscall.Signal(0x20) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "identifier removed", 83: "no message of desired type", 84: "value too large to be stored in data type", 85: "operation canceled", 86: "illegal byte sequence", 87: "attribute not found", 88: "programming error", 89: "bad message", 90: "multihop attempted", 91: "link has been severed", 92: "protocol error", 93: "capabilities insufficient", 94: "not permitted in capability mode", 95: "state not recoverable", 96: "previous owner died", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "unknown signal", 33: "unknown signal", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_freebsd_386.go0000644061062106075000000020521713172163421025465 0ustar stgraberdomain admins// mkerrors.sh -m32 // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m32 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_ARP = 0x23 AF_ATM = 0x1e AF_BLUETOOTH = 0x24 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x25 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1c AF_INET6_SDP = 0x2a AF_INET_SDP = 0x28 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x2a AF_NATM = 0x1d AF_NETBIOS = 0x6 AF_NETGRAPH = 0x20 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SCLUSTER = 0x22 AF_SIP = 0x18 AF_SLOW = 0x21 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VENDOR00 = 0x27 AF_VENDOR01 = 0x29 AF_VENDOR02 = 0x2b AF_VENDOR03 = 0x2d AF_VENDOR04 = 0x2f AF_VENDOR05 = 0x31 AF_VENDOR06 = 0x33 AF_VENDOR07 = 0x35 AF_VENDOR08 = 0x37 AF_VENDOR09 = 0x39 AF_VENDOR10 = 0x3b AF_VENDOR11 = 0x3d AF_VENDOR12 = 0x3f AF_VENDOR13 = 0x41 AF_VENDOR14 = 0x43 AF_VENDOR15 = 0x45 AF_VENDOR16 = 0x47 AF_VENDOR17 = 0x49 AF_VENDOR18 = 0x4b AF_VENDOR19 = 0x4d AF_VENDOR20 = 0x4f AF_VENDOR21 = 0x51 AF_VENDOR22 = 0x53 AF_VENDOR23 = 0x55 AF_VENDOR24 = 0x57 AF_VENDOR25 = 0x59 AF_VENDOR26 = 0x5b AF_VENDOR27 = 0x5d AF_VENDOR28 = 0x5f AF_VENDOR29 = 0x61 AF_VENDOR30 = 0x63 AF_VENDOR31 = 0x65 AF_VENDOR32 = 0x67 AF_VENDOR33 = 0x69 AF_VENDOR34 = 0x6b AF_VENDOR35 = 0x6d AF_VENDOR36 = 0x6f AF_VENDOR37 = 0x71 AF_VENDOR38 = 0x73 AF_VENDOR39 = 0x75 AF_VENDOR40 = 0x77 AF_VENDOR41 = 0x79 AF_VENDOR42 = 0x7b AF_VENDOR43 = 0x7d AF_VENDOR44 = 0x7f AF_VENDOR45 = 0x81 AF_VENDOR46 = 0x83 AF_VENDOR47 = 0x85 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B460800 = 0x70800 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B921600 = 0xe1000 B9600 = 0x2580 BIOCFEEDBACK = 0x8004427c BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRECTION = 0x40044276 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc0084279 BIOCGETBUFMODE = 0x4004427d BIOCGETIF = 0x4020426b BIOCGETZMAX = 0x4004427f BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4008426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCGTSTAMP = 0x40044283 BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x2000427a BIOCPROMISC = 0x20004269 BIOCROTZBUF = 0x400c4280 BIOCSBLEN = 0xc0044266 BIOCSDIRECTION = 0x80044277 BIOCSDLT = 0x80044278 BIOCSETBUFMODE = 0x8004427e BIOCSETF = 0x80084267 BIOCSETFNR = 0x80084282 BIOCSETIF = 0x8020426c BIOCSETWF = 0x8008427b BIOCSETZBUF = 0x800c4281 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8008426d BIOCSSEESENT = 0x80044277 BIOCSTSTAMP = 0x80044284 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_BUFMODE_BUFFER = 0x1 BPF_BUFMODE_ZBUF = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MOD = 0x90 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_T_BINTIME = 0x2 BPF_T_BINTIME_FAST = 0x102 BPF_T_BINTIME_MONOTONIC = 0x202 BPF_T_BINTIME_MONOTONIC_FAST = 0x302 BPF_T_FAST = 0x100 BPF_T_FLAG_MASK = 0x300 BPF_T_FORMAT_MASK = 0x3 BPF_T_MICROTIME = 0x0 BPF_T_MICROTIME_FAST = 0x100 BPF_T_MICROTIME_MONOTONIC = 0x200 BPF_T_MICROTIME_MONOTONIC_FAST = 0x300 BPF_T_MONOTONIC = 0x200 BPF_T_MONOTONIC_FAST = 0x300 BPF_T_NANOTIME = 0x1 BPF_T_NANOTIME_FAST = 0x101 BPF_T_NANOTIME_MONOTONIC = 0x201 BPF_T_NANOTIME_MONOTONIC_FAST = 0x301 BPF_T_NONE = 0x3 BPF_T_NORMAL = 0x0 BPF_W = 0x0 BPF_X = 0x8 BPF_XOR = 0xa0 BRKINT = 0x2 CAP_ACCEPT = 0x200000020000000 CAP_ACL_CHECK = 0x400000000010000 CAP_ACL_DELETE = 0x400000000020000 CAP_ACL_GET = 0x400000000040000 CAP_ACL_SET = 0x400000000080000 CAP_ALL0 = 0x20007ffffffffff CAP_ALL1 = 0x4000000001fffff CAP_BIND = 0x200000040000000 CAP_BINDAT = 0x200008000000400 CAP_CHFLAGSAT = 0x200000000001400 CAP_CONNECT = 0x200000080000000 CAP_CONNECTAT = 0x200010000000400 CAP_CREATE = 0x200000000000040 CAP_EVENT = 0x400000000000020 CAP_EXTATTR_DELETE = 0x400000000001000 CAP_EXTATTR_GET = 0x400000000002000 CAP_EXTATTR_LIST = 0x400000000004000 CAP_EXTATTR_SET = 0x400000000008000 CAP_FCHDIR = 0x200000000000800 CAP_FCHFLAGS = 0x200000000001000 CAP_FCHMOD = 0x200000000002000 CAP_FCHMODAT = 0x200000000002400 CAP_FCHOWN = 0x200000000004000 CAP_FCHOWNAT = 0x200000000004400 CAP_FCNTL = 0x200000000008000 CAP_FCNTL_ALL = 0x78 CAP_FCNTL_GETFL = 0x8 CAP_FCNTL_GETOWN = 0x20 CAP_FCNTL_SETFL = 0x10 CAP_FCNTL_SETOWN = 0x40 CAP_FEXECVE = 0x200000000000080 CAP_FLOCK = 0x200000000010000 CAP_FPATHCONF = 0x200000000020000 CAP_FSCK = 0x200000000040000 CAP_FSTAT = 0x200000000080000 CAP_FSTATAT = 0x200000000080400 CAP_FSTATFS = 0x200000000100000 CAP_FSYNC = 0x200000000000100 CAP_FTRUNCATE = 0x200000000000200 CAP_FUTIMES = 0x200000000200000 CAP_FUTIMESAT = 0x200000000200400 CAP_GETPEERNAME = 0x200000100000000 CAP_GETSOCKNAME = 0x200000200000000 CAP_GETSOCKOPT = 0x200000400000000 CAP_IOCTL = 0x400000000000080 CAP_IOCTLS_ALL = 0x7fffffff CAP_KQUEUE = 0x400000000100040 CAP_KQUEUE_CHANGE = 0x400000000100000 CAP_KQUEUE_EVENT = 0x400000000000040 CAP_LINKAT_SOURCE = 0x200020000000400 CAP_LINKAT_TARGET = 0x200000000400400 CAP_LISTEN = 0x200000800000000 CAP_LOOKUP = 0x200000000000400 CAP_MAC_GET = 0x400000000000001 CAP_MAC_SET = 0x400000000000002 CAP_MKDIRAT = 0x200000000800400 CAP_MKFIFOAT = 0x200000001000400 CAP_MKNODAT = 0x200000002000400 CAP_MMAP = 0x200000000000010 CAP_MMAP_R = 0x20000000000001d CAP_MMAP_RW = 0x20000000000001f CAP_MMAP_RWX = 0x20000000000003f CAP_MMAP_RX = 0x20000000000003d CAP_MMAP_W = 0x20000000000001e CAP_MMAP_WX = 0x20000000000003e CAP_MMAP_X = 0x20000000000003c CAP_PDGETPID = 0x400000000000200 CAP_PDKILL = 0x400000000000800 CAP_PDWAIT = 0x400000000000400 CAP_PEELOFF = 0x200001000000000 CAP_POLL_EVENT = 0x400000000000020 CAP_PREAD = 0x20000000000000d CAP_PWRITE = 0x20000000000000e CAP_READ = 0x200000000000001 CAP_RECV = 0x200000000000001 CAP_RENAMEAT_SOURCE = 0x200000004000400 CAP_RENAMEAT_TARGET = 0x200040000000400 CAP_RIGHTS_VERSION = 0x0 CAP_RIGHTS_VERSION_00 = 0x0 CAP_SEEK = 0x20000000000000c CAP_SEEK_TELL = 0x200000000000004 CAP_SEM_GETVALUE = 0x400000000000004 CAP_SEM_POST = 0x400000000000008 CAP_SEM_WAIT = 0x400000000000010 CAP_SEND = 0x200000000000002 CAP_SETSOCKOPT = 0x200002000000000 CAP_SHUTDOWN = 0x200004000000000 CAP_SOCK_CLIENT = 0x200007780000003 CAP_SOCK_SERVER = 0x200007f60000003 CAP_SYMLINKAT = 0x200000008000400 CAP_TTYHOOK = 0x400000000000100 CAP_UNLINKAT = 0x200000010000400 CAP_UNUSED0_44 = 0x200080000000000 CAP_UNUSED0_57 = 0x300000000000000 CAP_UNUSED1_22 = 0x400000000200000 CAP_UNUSED1_57 = 0x500000000000000 CAP_WRITE = 0x200000000000002 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x4 CLOCK_MONOTONIC_FAST = 0xc CLOCK_MONOTONIC_PRECISE = 0xb CLOCK_PROCESS_CPUTIME_ID = 0xf CLOCK_PROF = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_FAST = 0xa CLOCK_REALTIME_PRECISE = 0x9 CLOCK_SECOND = 0xd CLOCK_THREAD_CPUTIME_ID = 0xe CLOCK_UPTIME = 0x5 CLOCK_UPTIME_FAST = 0x8 CLOCK_UPTIME_PRECISE = 0x7 CLOCK_VIRTUAL = 0x1 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0x18 CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_BREDR_BB = 0xff DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_BLUETOOTH_LE_LL = 0xfb DLT_BLUETOOTH_LE_LL_WITH_PHDR = 0x100 DLT_BLUETOOTH_LINUX_MONITOR = 0xfe DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_EPON = 0x103 DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NOFCS = 0xe6 DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_INFINIBAND = 0xf7 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPMI_HPM_2 = 0x104 DLT_IPNET = 0xe2 DLT_IPOIB = 0xf2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FIBRECHANNEL = 0xea DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_SRX_E2E = 0xe9 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_JUNIPER_VS = 0xe8 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MATCHING_MAX = 0x104 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPEG_2_TS = 0xf3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_MUX27010 = 0xec DLT_NETANALYZER = 0xf0 DLT_NETANALYZER_TRANSPARENT = 0xf1 DLT_NETLINK = 0xfd DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PPP_WITH_DIRECTION = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PROFIBUS_DL = 0x101 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_PROCDESC = -0x8 EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xc EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_DROP = 0x1000 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_FLAG2 = 0x4000 EV_FORCEONESHOT = 0x100 EV_ONESHOT = 0x10 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_CANCEL = 0x5 F_DUP2FD = 0xa F_DUP2FD_CLOEXEC = 0x12 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x11 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0xb F_GETOWN = 0x5 F_OGETLK = 0x7 F_OK = 0x0 F_OSETLK = 0x8 F_OSETLKW = 0x9 F_RDAHEAD = 0x10 F_RDLCK = 0x1 F_READAHEAD = 0xf F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0xc F_SETLKW = 0xd F_SETLK_REMOTE = 0xe F_SETOWN = 0x6 F_UNLCK = 0x2 F_UNLCKSYS = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x218f52 IFF_CANTCONFIG = 0x10000 IFF_DEBUG = 0x4 IFF_DRV_OACTIVE = 0x400 IFF_DRV_RUNNING = 0x40 IFF_DYING = 0x200000 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 IFF_PROMISC = 0x100 IFF_RENAMING = 0x400000 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_STATICARP = 0x80000 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_BRIDGE = 0xd1 IFT_CARP = 0xf8 IFT_IEEE1394 = 0x90 IFT_INFINIBAND = 0xc7 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_PPP = 0x17 IFT_PROPVIRTUAL = 0x35 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_MASK = 0xfffffffe IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CARP = 0x70 IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0x102 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HIP = 0x8b IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MEAS = 0x13 IPPROTO_MH = 0x87 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OLD_DIVERT = 0xfe IPPROTO_OSPFIGP = 0x59 IPPROTO_PFSYNC = 0xf0 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_RESERVED_253 = 0xfd IPPROTO_RESERVED_254 = 0xfe IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SCTP = 0x84 IPPROTO_SDRP = 0x2a IPPROTO_SEND = 0x103 IPPROTO_SEP = 0x21 IPPROTO_SHIM6 = 0x8c IPPROTO_SKIP = 0x39 IPPROTO_SPACER = 0x7fff IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TLSP = 0x38 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_AUTOFLOWLABEL = 0x3b IPV6_BINDANY = 0x40 IPV6_BINDMULTI = 0x41 IPV6_BINDV6ONLY = 0x1b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXOPTHDR = 0x800 IPV6_MAXPACKET = 0xffff IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_PREFER_TEMPADDR = 0x3f IPV6_RECVDSTOPTS = 0x28 IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RSSBUCKETID = 0x45 IPV6_RSS_LISTEN_BUCKET = 0x42 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 IP_BINDMULTI = 0x19 IP_BLOCK_SOURCE = 0x48 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DONTFRAG = 0x43 IP_DROP_MEMBERSHIP = 0xd IP_DROP_SOURCE_MEMBERSHIP = 0x47 IP_DUMMYNET3 = 0x31 IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FLOWID = 0x5a IP_FLOWTYPE = 0x5b IP_FW3 = 0x30 IP_FW_ADD = 0x32 IP_FW_DEL = 0x33 IP_FW_FLUSH = 0x34 IP_FW_GET = 0x36 IP_FW_NAT_CFG = 0x38 IP_FW_NAT_DEL = 0x39 IP_FW_NAT_GET_CONFIG = 0x3a IP_FW_NAT_GET_LOG = 0x3b IP_FW_RESETLOG = 0x37 IP_FW_TABLE_ADD = 0x28 IP_FW_TABLE_DEL = 0x29 IP_FW_TABLE_FLUSH = 0x2a IP_FW_TABLE_GETSIZE = 0x2b IP_FW_TABLE_LIST = 0x2c IP_FW_ZERO = 0x35 IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_GROUP_SRC_FILTER = 0x200 IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 IP_RECVTTL = 0x41 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSSBUCKETID = 0x5c IP_RSS_LISTEN_BUCKET = 0x1a IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_SENDSRCADDR = 0x7 IP_TOS = 0x3 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x49 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_AUTOSYNC = 0x7 MADV_CORE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_NOCORE = 0x8 MADV_NORMAL = 0x0 MADV_NOSYNC = 0x6 MADV_PROTECT = 0xa MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MAP_ALIGNED_SUPER = 0x1000000 MAP_ALIGNMENT_MASK = -0x1000000 MAP_ALIGNMENT_SHIFT = 0x18 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RESERVED0020 = 0x20 MAP_RESERVED0040 = 0x40 MAP_RESERVED0080 = 0x80 MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 MNT_ASYNC = 0x40 MNT_AUTOMOUNTED = 0x200000000 MNT_BYFSID = 0x8000000 MNT_CMDFLAGS = 0xd0f0000 MNT_DEFEXPORTED = 0x200 MNT_DELEXPORT = 0x20000 MNT_EXKERB = 0x800 MNT_EXPORTANON = 0x400 MNT_EXPORTED = 0x100 MNT_EXPUBLIC = 0x20000000 MNT_EXRDONLY = 0x80 MNT_FORCE = 0x80000 MNT_GJOURNAL = 0x2000000 MNT_IGNORE = 0x800000 MNT_LAZY = 0x3 MNT_LOCAL = 0x1000 MNT_MULTILABEL = 0x4000000 MNT_NFS4ACLS = 0x10 MNT_NOATIME = 0x10000000 MNT_NOCLUSTERR = 0x40000000 MNT_NOCLUSTERW = 0x80000000 MNT_NOEXEC = 0x4 MNT_NONBUSY = 0x4000000 MNT_NOSUID = 0x8 MNT_NOSYMFOLLOW = 0x400000 MNT_NOWAIT = 0x2 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SNAPSHOT = 0x1000000 MNT_SOFTDEP = 0x200000 MNT_SUIDDIR = 0x100000 MNT_SUJ = 0x100000000 MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 MNT_UPDATE = 0x10000 MNT_UPDATEMASK = 0x2d8d0807e MNT_USER = 0x8000 MNT_VISFLAGMASK = 0x3fef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_NBIO = 0x4000 MSG_NOSIGNAL = 0x20000 MSG_NOTIFICATION = 0x2000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MSG_WAITFORONE = 0x80000 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_SYNC = 0x0 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFLISTL = 0x5 NET_RT_IFMALIST = 0x4 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 NOTE_CLOSE_WRITE = 0x200 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FILE_POLL = 0x2 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_MSECONDS = 0x2 NOTE_NSECONDS = 0x8 NOTE_OPEN = 0x80 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_READ = 0x400 NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_SECONDS = 0x1 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_USECONDS = 0x4 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x100000 O_CREAT = 0x200 O_DIRECT = 0x10000 O_DIRECTORY = 0x20000 O_EXCL = 0x800 O_EXEC = 0x40000 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_TTY_INIT = 0x80000 O_VERIFY = 0x200000 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0xa RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x8 RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FIXEDMTU = 0x80000 RTF_FMASK = 0x1004d808 RTF_GATEWAY = 0x2 RTF_GWFLAG_COMPAT = 0x80000000 RTF_HOST = 0x4 RTF_LLDATA = 0x400 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MULTICAST = 0x800000 RTF_PINNED = 0x100000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_REJECT = 0x8 RTF_RNH_LOCKED = 0x40000000 RTF_STATIC = 0x800 RTF_STICKY = 0x10000000 RTF_UP = 0x1 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_IEEE80211 = 0x12 RTM_IFANNOUNCE = 0x11 RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 RT_HAS_HEADER_BIT = 0x4 RT_L2_ME = 0x4 RT_L2_ME_BIT = 0x2 RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCGDRVSPEC = 0xc01c697b SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020691f SIOCGIFCONF = 0xc0086924 SIOCGIFDESCR = 0xc020692a SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFIB = 0xc020695c SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc024698a SIOCGIFGROUP = 0xc0246988 SIOCGIFINDEX = 0xc0206920 SIOCGIFMAC = 0xc0206926 SIOCGIFMEDIA = 0xc0286938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc028698b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 SIOCGTUNFIB = 0xc020695e SIOCIFCREATE = 0xc020697a SIOCIFCREATE2 = 0xc020697c SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc00c6978 SIOCSDRVSPEC = 0x801c697b SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020691e SIOCSIFDESCR = 0x80206929 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFIB = 0x8020695d SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020693c SIOCSIFMAC = 0x80206927 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNAME = 0x80206928 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f SOCK_CLOEXEC = 0x10000000 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_NONBLOCK = 0x20000000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ACCEPTFILTER = 0x1000 SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LABEL = 0x1009 SO_LINGER = 0x80 SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 SO_OOBINLINE = 0x100 SO_PEERLABEL = 0x1010 SO_PROTOCOL = 0x1016 SO_PROTOTYPE = 0x1016 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 SO_VENDOR = 0x80000000 TAB0 = 0x0 TAB3 = 0x4 TABDLY = 0x4 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 TCP_FASTOPEN = 0x401 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 TCP_KEEPCNT = 0x400 TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x4 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x10 TCP_MINMSS = 0xd8 TCP_MSS = 0x218 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGPTN = 0x4004740f TIOCGSID = 0x40047463 TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DCD = 0x40 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTMASTER = 0x2000741c TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSIG = 0x2004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40087459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VERASE2 = 0x7 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x4 WCOREFLAG = 0x80 WEXITED = 0x10 WLINUXCLONE = 0x80000000 WNOHANG = 0x1 WNOWAIT = 0x8 WSTOPPED = 0x2 WTRAPPED = 0x20 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x59) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x55) ECAPMODE = syscall.Errno(0x5e) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDOOFUS = syscall.Errno(0x58) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x52) EILSEQ = syscall.Errno(0x56) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x60) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5a) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x57) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x5b) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x53) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCAPABLE = syscall.Errno(0x5d) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x5f) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x54) EOWNERDEAD = syscall.Errno(0x60) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x5c) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGLIBRT = syscall.Signal(0x21) SIGLWP = syscall.Signal(0x20) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "identifier removed", 83: "no message of desired type", 84: "value too large to be stored in data type", 85: "operation canceled", 86: "illegal byte sequence", 87: "attribute not found", 88: "programming error", 89: "bad message", 90: "multihop attempted", 91: "link has been severed", 92: "protocol error", 93: "capabilities insufficient", 94: "not permitted in capability mode", 95: "state not recoverable", 96: "previous owner died", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "unknown signal", 33: "unknown signal", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go0000644061062106075000000017413113172163421026433 0ustar stgraberdomain admins// mkerrors.sh -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,dragonfly // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_ATM = 0x1e AF_BLUETOOTH = 0x21 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x23 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1c AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x24 AF_MPLS = 0x22 AF_NATM = 0x1d AF_NETBIOS = 0x6 AF_NETGRAPH = 0x20 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc0104279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4010426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x2000427a BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80104267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x8010427b BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8010426d BIOCSSEESENT = 0x80044277 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x8 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DEFAULTBUFSIZE = 0x1000 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MAX_CLONES = 0x80 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x4 CLOCK_MONOTONIC_FAST = 0xc CLOCK_MONOTONIC_PRECISE = 0xb CLOCK_PROCESS_CPUTIME_ID = 0xf CLOCK_PROF = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_FAST = 0xa CLOCK_REALTIME_PRECISE = 0x9 CLOCK_SECOND = 0xd CLOCK_THREAD_CPUTIME_ID = 0xe CLOCK_UPTIME = 0x5 CLOCK_UPTIME_FAST = 0x8 CLOCK_UPTIME_PRECISE = 0x7 CLOCK_VIRTUAL = 0x1 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DOCSIS = 0x8f DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DBF = 0xf DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_EXCEPT = -0x8 EVFILT_FS = -0xa EVFILT_MARKER = 0xf EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xa EVFILT_TIMER = -0x7 EVFILT_USER = -0x9 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_NODATA = 0x1000 EV_ONESHOT = 0x10 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTEXIT_LWP = 0x10000 EXTEXIT_PROC = 0x0 EXTEXIT_SETINT = 0x1 EXTEXIT_SIMPLE = 0x0 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_DUP2FD = 0xa F_DUP2FD_CLOEXEC = 0x12 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x11 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 F_OK = 0x0 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x118e72 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NPOLLING = 0x100000 IFF_OACTIVE = 0x400 IFF_OACTIVE_COMPAT = 0x400 IFF_POINTOPOINT = 0x10 IFF_POLLING = 0x10000 IFF_POLLING_COMPAT = 0x10000 IFF_PPROMISC = 0x20000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_SMART = 0x20 IFF_STATICARP = 0x80000 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf8 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf2 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xf3 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VOICEEM = 0x64 IFT_VOICEENCAP = 0x67 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CARP = 0x70 IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0xfe IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MEAS = 0x13 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MOBILE = 0x37 IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OSPFIGP = 0x59 IPPROTO_PFSYNC = 0xf0 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SDRP = 0x2a IPPROTO_SEP = 0x21 IPPROTO_SKIP = 0x39 IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TLSP = 0x38 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_UNKNOWN = 0x102 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_AUTOFLOWLABEL = 0x3b IPV6_BINDV6ONLY = 0x1b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MINHLIM = 0x28 IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PKTOPTIONS = 0x34 IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_PREFER_TEMPADDR = 0x3f IPV6_RECVDSTOPTS = 0x28 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FAITH = 0x16 IP_FW_ADD = 0x32 IP_FW_DEL = 0x33 IP_FW_FLUSH = 0x34 IP_FW_GET = 0x36 IP_FW_RESETLOG = 0x37 IP_FW_X = 0x31 IP_FW_ZERO = 0x35 IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x42 IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x41 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_AUTOSYNC = 0x7 MADV_CONTROL_END = 0xb MADV_CONTROL_START = 0xa MADV_CORE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_INVAL = 0xa MADV_NOCORE = 0x8 MADV_NORMAL = 0x0 MADV_NOSYNC = 0x6 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SETMAP = 0xb MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_INHERIT = 0x80 MAP_NOCORE = 0x20000 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_NOSYNC = 0x800 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_SIZEALIGN = 0x40000 MAP_STACK = 0x400 MAP_TRYFIXED = 0x10000 MAP_VPAGETABLE = 0x2000 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_CMSG_CLOEXEC = 0x1000 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_FBLOCKING = 0x10000 MSG_FMASK = 0xffff0000 MSG_FNONBLOCKING = 0x20000 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_SYNC = 0x800 MSG_TRUNC = 0x10 MSG_UNUSED09 = 0x200 MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_SYNC = 0x0 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_MAXID = 0x4 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_OOB = 0x2 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x20000 O_CREAT = 0x200 O_DIRECT = 0x10000 O_DIRECTORY = 0x8000000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FAPPEND = 0x100000 O_FASYNCWRITE = 0x800000 O_FBLOCKING = 0x40000 O_FMASK = 0xfc0000 O_FNONBLOCKING = 0x80000 O_FOFFSET = 0x200000 O_FSYNC = 0x80 O_FSYNCWRITE = 0x400000 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0xa RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0xb RTAX_MPLS1 = 0x8 RTAX_MPLS2 = 0x9 RTAX_MPLS3 = 0xa RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_MPLS1 = 0x100 RTA_MPLS2 = 0x200 RTA_MPLS3 = 0x400 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MPLSOPS = 0x1000000 RTF_MULTICAST = 0x800000 RTF_PINNED = 0x100000 RTF_PRCLONING = 0x10000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_REJECT = 0x8 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_WASCLONED = 0x20000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_IEEE80211 = 0x12 RTM_IFANNOUNCE = 0x11 RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x6 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_IWCAPSEGS = 0x400 RTV_IWMAXSEGS = 0x200 RTV_MSL = 0x100 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCADDRT = 0x8040720a SIOCAIFADDR = 0x8040691a SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8040720b SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc028697b SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020691f SIOCGIFCONF = 0xc0106924 SIOCGIFDATA = 0xc0206926 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc028698a SIOCGIFINDEX = 0xc0206920 SIOCGIFMEDIA = 0xc0306938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPOLLCPU = 0xc020697e SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFSTATUS = 0xc331693b SIOCGIFTSOLEN = 0xc0206980 SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 SIOCIFCREATE = 0xc020697a SIOCIFCREATE2 = 0xc020697c SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106978 SIOCSDRVSPEC = 0x8028697b SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020691e SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020693c SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNAME = 0x80206928 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPHYS = 0x80206936 SIOCSIFPOLLCPU = 0x8020697d SIOCSIFTSOLEN = 0x8020697f SIOCSLIFPHYADDR = 0x8118694a SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SOCK_CLOEXEC = 0x10000000 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_NONBLOCK = 0x20000000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 SO_CPUHINT = 0x1030 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NOSIGPIPE = 0x800 SO_OOBINLINE = 0x100 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDSPACE = 0x100a SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_FASTKEEP = 0x80 TCP_KEEPCNT = 0x400 TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x20 TCP_KEEPINTVL = 0x200 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MINMSS = 0x100 TCP_MIN_WINSHIFT = 0x5 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_SIGNATURE_ENABLE = 0x10 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x40107458 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGSID = 0x40047463 TIOCGSIZE = 0x40087468 TIOCGWINSZ = 0x40087468 TIOCISPTMASTER = 0x20007455 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMODG = 0x40047403 TIOCMODS = 0x80047404 TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSIG = 0x2000745f TIOCSPGRP = 0x80047476 TIOCSSIZE = 0x80087467 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VCHECKPT = 0x13 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VERASE2 = 0x7 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VM_BCACHE_SIZE_MAX = 0x0 VM_SWZONE_SIZE_MAX = 0x4000000000 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x4 WCOREFLAG = 0x80 WLINUXCLONE = 0x80000000 WNOHANG = 0x1 WSTOPPED = 0x7f WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EASYNC = syscall.Errno(0x63) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x59) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x55) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDOOFUS = syscall.Errno(0x58) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x52) EILSEQ = syscall.Errno(0x56) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x63) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5a) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x57) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x5b) ENOMEDIUM = syscall.Errno(0x5d) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x53) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x54) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x5c) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUNUSED94 = syscall.Errno(0x5e) EUNUSED95 = syscall.Errno(0x5f) EUNUSED96 = syscall.Errno(0x60) EUNUSED97 = syscall.Errno(0x61) EUNUSED98 = syscall.Errno(0x62) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCKPT = syscall.Signal(0x21) SIGCKPTEXIT = syscall.Signal(0x22) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "identifier removed", 83: "no message of desired type", 84: "value too large to be stored in data type", 85: "operation canceled", 86: "illegal byte sequence", 87: "attribute not found", 88: "programming error", 89: "bad message", 90: "multihop attempted", 91: "link has been severed", 92: "protocol error", 93: "no medium found", 94: "unknown error: 94", 95: "unknown error: 95", 96: "unknown error: 96", 97: "unknown error: 97", 98: "unknown error: 98", 99: "unknown error: 99", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "thread Scheduler", 33: "checkPoint", 34: "checkPointExit", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_darwin_arm64.go0000644061062106075000000020521113172163421025742 0ustar stgraberdomain admins// mkerrors.sh -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm64,darwin // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1c AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x25 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1e AF_IPX = 0x17 AF_ISDN = 0x1c AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x28 AF_NATM = 0x1f AF_NDRV = 0x1b AF_NETBIOS = 0x21 AF_NS = 0x6 AF_OSI = 0x7 AF_PPP = 0x22 AF_PUP = 0x4 AF_RESERVED_36 = 0x24 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_SYSTEM = 0x20 AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_UTUN = 0x26 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc00c4279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4010426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80104267 BIOCSETFNR = 0x8010427e BIOCSETIF = 0x8020426c BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8010426d BIOCSSEESENT = 0x80044277 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_MONOTONIC_RAW_APPROX = 0x5 CLOCK_PROCESS_CPUTIME_ID = 0xc CLOCK_REALTIME = 0x0 CLOCK_THREAD_CPUTIME_ID = 0x10 CLOCK_UPTIME_RAW = 0x8 CLOCK_UPTIME_RAW_APPROX = 0x9 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 CR3 = 0x3000 CRDLY = 0x3000 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NOFCS = 0xe6 DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPNET = 0xe2 DLT_IPOIB = 0xf2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FIBRECHANNEL = 0xea DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_SRX_E2E = 0xe9 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_JUNIPER_VS = 0xe8 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MATCHING_MAX = 0xf5 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPEG_2_TS = 0xf3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_MUX27010 = 0xec DLT_NETANALYZER = 0xf0 DLT_NETANALYZER_TRANSPARENT = 0xf1 DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PPP_WITH_DIRECTION = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DLT_WIHART = 0xdf DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_EXCEPT = -0xf EVFILT_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xf EVFILT_THREADMARKER = 0xf EVFILT_TIMER = -0x7 EVFILT_USER = -0xa EVFILT_VM = -0xc EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_DISPATCH2 = 0x180 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG0 = 0x1000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_OOBAND = 0x2000 EV_POLL = 0x1000 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EV_UDATA_SPECIFIC = 0x100 EV_VANISHED = 0x200 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDFILESIGS_FOR_DYLD_SIM = 0x53 F_ADDFILESIGS_RETURN = 0x61 F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 F_BARRIERFSYNC = 0x55 F_CHECK_LV = 0x62 F_CHKCLEAN = 0x29 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x43 F_FINDSIGS = 0x4e F_FLUSH_DATA = 0x28 F_FREEZE_FS = 0x35 F_FULLFSYNC = 0x33 F_GETCODEDIR = 0x48 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETLKPID = 0x42 F_GETNOSIGPIPE = 0x4a F_GETOWN = 0x5 F_GETPATH = 0x32 F_GETPATH_MTMINFO = 0x47 F_GETPROTECTIONCLASS = 0x3f F_GETPROTECTIONLEVEL = 0x4d F_GLOBAL_NOCACHE = 0x37 F_LOG2PHYS = 0x31 F_LOG2PHYS_EXT = 0x41 F_NOCACHE = 0x30 F_NODIRECT = 0x3e F_OK = 0x0 F_PATHPKG_CHECK = 0x34 F_PEOFPOSMODE = 0x3 F_PREALLOCATE = 0x2a F_RDADVISE = 0x2c F_RDAHEAD = 0x2d F_RDLCK = 0x1 F_SETBACKINGSTORE = 0x46 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETLKWTIMEOUT = 0xa F_SETNOSIGPIPE = 0x49 F_SETOWN = 0x6 F_SETPROTECTIONCLASS = 0x40 F_SETSIZE = 0x2b F_SINGLE_WRITER = 0x4c F_THAW_FS = 0x36 F_TRANSCODEKEY = 0x4b F_UNLCK = 0x2 F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_AAL5 = 0x31 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ATM = 0x25 IFT_BRIDGE = 0xd1 IFT_CARP = 0xf8 IFT_CELLULAR = 0xff IFT_CEPT = 0x13 IFT_DS3 = 0x1e IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_ETHER = 0x6 IFT_FAITH = 0x38 IFT_FDDI = 0xf IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_GIF = 0x37 IFT_HDH1822 = 0x3 IFT_HIPPI = 0x2f IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IEEE1394 = 0x90 IFT_IEEE8023ADLAG = 0x88 IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88026 = 0xa IFT_L2VLAN = 0x87 IFT_LAPB = 0x10 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_NSIP = 0x1b IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PDP = 0xff IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PKTAP = 0xfe IFT_PPP = 0x17 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PTPSERIAL = 0x16 IFT_RS232 = 0x21 IFT_SDLC = 0x11 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_STARLAN = 0xb IFT_STF = 0x39 IFT_T1 = 0x12 IFT_ULTRA = 0x1d IFT_V35 = 0x2d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LINKLOCALNETNUM = 0xa9fe0000 IN_LOOPBACKNET = 0x7f IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0xfe IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MEAS = 0x13 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OSPFIGP = 0x59 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SCTP = 0x84 IPPROTO_SDRP = 0x2a IPPROTO_SEP = 0x21 IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_2292DSTOPTS = 0x17 IPV6_2292HOPLIMIT = 0x14 IPV6_2292HOPOPTS = 0x16 IPV6_2292NEXTHOP = 0x15 IPV6_2292PKTINFO = 0x13 IPV6_2292PKTOPTIONS = 0x19 IPV6_2292RTHDR = 0x18 IPV6_BINDV6ONLY = 0x1b IPV6_BOUND_IF = 0x7d IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x3c IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXOPTHDR = 0x800 IPV6_MAXPACKET = 0xffff IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVTCLASS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x24 IPV6_UNICAST_HOPS = 0x4 IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BLOCK_SOURCE = 0x48 IP_BOUND_IF = 0x19 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_DROP_SOURCE_MEMBERSHIP = 0x47 IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FAITH = 0x16 IP_FW_ADD = 0x28 IP_FW_DEL = 0x29 IP_FW_FLUSH = 0x2a IP_FW_GET = 0x2c IP_FW_RESETLOG = 0x2d IP_FW_ZERO = 0x2b IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_GROUP_SRC_FILTER = 0x200 IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 IP_MF = 0x2000 IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_IFINDEX = 0x42 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_NAT__XXX = 0x37 IP_OFFMASK = 0x1fff IP_OLD_FW_ADD = 0x32 IP_OLD_FW_DEL = 0x33 IP_OLD_FW_FLUSH = 0x34 IP_OLD_FW_GET = 0x36 IP_OLD_FW_RESETLOG = 0x38 IP_OLD_FW_ZERO = 0x35 IP_OPTIONS = 0x1 IP_PKTINFO = 0x1a IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVPKTINFO = 0x1a IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x18 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_STRIPHDR = 0x17 IP_TOS = 0x3 IP_TRAFFIC_MGT_BACKGROUND = 0x41 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x49 ISIG = 0x80 ISTRIP = 0x20 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_CAN_REUSE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_FREE_REUSABLE = 0x7 MADV_FREE_REUSE = 0x8 MADV_NORMAL = 0x0 MADV_PAGEOUT = 0xa MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_JIT = 0x800 MAP_NOCACHE = 0x400 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_RESERVED0080 = 0x80 MAP_RESILIENT_CODESIGN = 0x2000 MAP_RESILIENT_MEDIA = 0x4000 MAP_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ASYNC = 0x40 MNT_AUTOMOUNTED = 0x400000 MNT_CMDFLAGS = 0xf0000 MNT_CPROTECT = 0x80 MNT_DEFWRITE = 0x2000000 MNT_DONTBROWSE = 0x100000 MNT_DOVOLFS = 0x8000 MNT_DWAIT = 0x4 MNT_EXPORTED = 0x100 MNT_FORCE = 0x80000 MNT_IGNORE_OWNERSHIP = 0x200000 MNT_JOURNALED = 0x800000 MNT_LOCAL = 0x1000 MNT_MULTILABEL = 0x4000000 MNT_NOATIME = 0x10000000 MNT_NOBLOCK = 0x20000 MNT_NODEV = 0x10 MNT_NOEXEC = 0x4 MNT_NOSUID = 0x8 MNT_NOUSERXATTR = 0x1000000 MNT_NOWAIT = 0x2 MNT_QUARANTINE = 0x400 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 MNT_UNKNOWNPERMISSIONS = 0x200000 MNT_UPDATE = 0x10000 MNT_VISFLAGMASK = 0x17f0f5ff MNT_WAIT = 0x1 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_FLUSH = 0x400 MSG_HAVEMORE = 0x2000 MSG_HOLD = 0x800 MSG_NEEDSA = 0x10000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_RCVMORE = 0x4000 MSG_SEND = 0x1000 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MSG_WAITSTREAM = 0x200 MS_ASYNC = 0x1 MS_DEACTIVATE = 0x8 MS_INVALIDATE = 0x2 MS_KILLPAGES = 0x4 MS_SYNC = 0x10 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_DUMP2 = 0x7 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFLIST2 = 0x6 NET_RT_MAXID = 0xa NET_RT_STAT = 0x4 NET_RT_TRASH = 0x5 NL0 = 0x0 NL1 = 0x100 NL2 = 0x200 NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ABSOLUTE = 0x8 NOTE_ATTRIB = 0x8 NOTE_BACKGROUND = 0x40 NOTE_CHILD = 0x4 NOTE_CRITICAL = 0x20 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXITSTATUS = 0x4000000 NOTE_EXIT_CSERROR = 0x40000 NOTE_EXIT_DECRYPTFAIL = 0x10000 NOTE_EXIT_DETAIL = 0x2000000 NOTE_EXIT_DETAIL_MASK = 0x70000 NOTE_EXIT_MEMORY = 0x20000 NOTE_EXIT_REPARENTED = 0x80000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FORK = 0x40000000 NOTE_FUNLOCK = 0x100 NOTE_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_MACH_CONTINUOUS_TIME = 0x80 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 NOTE_OOB = 0x2 NOTE_PCTRLMASK = -0x100000 NOTE_PDATAMASK = 0xfffff NOTE_REAP = 0x10000000 NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_SECONDS = 0x1 NOTE_SIGNAL = 0x8000000 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_USECONDS = 0x2 NOTE_VM_ERROR = 0x10000000 NOTE_VM_PRESSURE = 0x80000000 NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 NOTE_VM_PRESSURE_TERMINATE = 0x40000000 NOTE_WRITE = 0x2 OCRNL = 0x10 OFDEL = 0x20000 OFILL = 0x80 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_ALERT = 0x20000000 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x1000000 O_CREAT = 0x200 O_DIRECTORY = 0x100000 O_DP_GETRAWENCRYPTED = 0x1 O_DP_GETRAWUNENCRYPTED = 0x2 O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x20000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PT_ATTACH = 0xa PT_ATTACHEXC = 0xe PT_CONTINUE = 0x7 PT_DENY_ATTACH = 0x1f PT_DETACH = 0xb PT_FIRSTMACH = 0x20 PT_FORCEQUOTA = 0x1e PT_KILL = 0x8 PT_READ_D = 0x2 PT_READ_I = 0x1 PT_READ_U = 0x3 PT_SIGEXC = 0xc PT_STEP = 0x9 PT_THUPDATE = 0xd PT_TRACE_ME = 0x0 PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_CPU_USAGE_MONITOR = 0x2 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x8 RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CLONING = 0x100 RTF_CONDEMNED = 0x2000000 RTF_DELCLONE = 0x80 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_IFREF = 0x4000000 RTF_IFSCOPE = 0x1000000 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MULTICAST = 0x800000 RTF_NOIFREF = 0x2000 RTF_PINNED = 0x100000 RTF_PRCLONING = 0x10000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_PROXY = 0x8000000 RTF_REJECT = 0x8 RTF_ROUTER = 0x10000000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_WASCLONED = 0x20000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_GET2 = 0x14 RTM_IFINFO = 0xe RTM_IFINFO2 = 0x12 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_NEWMADDR2 = 0x13 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SCM_TIMESTAMP_MONOTONIC = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCARPIPLL = 0xc0206928 SIOCATMARK = 0x40047307 SIOCAUTOADDR = 0xc0206926 SIOCAUTONETMASK = 0x80206927 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206941 SIOCGDRVSPEC = 0xc028697b SIOCGETVLAN = 0xc020697f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFALTMTU = 0xc0206948 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBOND = 0xc0206947 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020695b SIOCGIFCONF = 0xc00c6924 SIOCGIFDEVMTU = 0xc0206944 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFKPI = 0xc0206987 SIOCGIFMAC = 0xc0206982 SIOCGIFMEDIA = 0xc02c6938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206940 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc020693f SIOCGIFSTATUS = 0xc331693d SIOCGIFVLAN = 0xc020697f SIOCGIFWAKEFLAGS = 0xc0206988 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCIFCREATE = 0xc0206978 SIOCIFCREATE2 = 0xc020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106981 SIOCRSLVMULTI = 0xc010693b SIOCSDRVSPEC = 0x8028697b SIOCSETVLAN = 0x8020697e SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFALTMTU = 0x80206945 SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBOND = 0x80206946 SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020695a SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFKPI = 0x80206986 SIOCSIFLLADDR = 0x8020693c SIOCSIFMAC = 0x80206983 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x8040693e SIOCSIFPHYS = 0x80206936 SIOCSIFVLAN = 0x8020697e SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_DONTTRUNC = 0x2000 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LABEL = 0x1010 SO_LINGER = 0x80 SO_LINGER_SEC = 0x1080 SO_NETSVC_MARKING_LEVEL = 0x1119 SO_NET_SERVICE_TYPE = 0x1116 SO_NKE = 0x1021 SO_NOADDRERR = 0x1023 SO_NOSIGPIPE = 0x1022 SO_NOTIFYCONFLICT = 0x1026 SO_NP_EXTENSIONS = 0x1083 SO_NREAD = 0x1020 SO_NUMRCVPKT = 0x1112 SO_NWRITE = 0x1024 SO_OOBINLINE = 0x100 SO_PEERLABEL = 0x1011 SO_RANDOMPORT = 0x1082 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_REUSESHAREUID = 0x1025 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TIMESTAMP_MONOTONIC = 0x800 SO_TYPE = 0x1008 SO_UPCALLCLOSEWAIT = 0x1027 SO_USELOOPBACK = 0x40 SO_WANTMORE = 0x4000 SO_WANTOOBFLAG = 0x8000 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IFWHT = 0xe000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0x4 TABDLY = 0xc04 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_CONNECTION_INFO = 0x106 TCP_ENABLE_ECN = 0x104 TCP_FASTOPEN = 0x105 TCP_KEEPALIVE = 0x10 TCP_KEEPCNT = 0x102 TCP_KEEPINTVL = 0x101 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x4 TCP_MAX_WINSHIFT = 0xe TCP_MINMSS = 0xd8 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_NOTSENT_LOWAT = 0x201 TCP_RXT_CONNDROPTIME = 0x80 TCP_RXT_FINDROP = 0x100 TCP_SENDMOREACKS = 0x103 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x40107458 TIOCDRAIN = 0x2000745e TIOCDSIMICROCODE = 0x20007455 TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x40487413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGWINSZ = 0x40087468 TIOCIXOFF = 0x20007480 TIOCIXON = 0x20007481 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMODG = 0x40047403 TIOCMODS = 0x80047404 TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTYGNAME = 0x40807453 TIOCPTYGRANT = 0x20007454 TIOCPTYUNLK = 0x20007452 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCONS = 0x20007463 TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x80487414 TIOCSETAF = 0x80487416 TIOCSETAW = 0x80487415 TIOCSETD = 0x8004741b TIOCSIG = 0x2000745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VM_LOADAVG = 0x2 VM_MACHFACTOR = 0x4 VM_MAXID = 0x6 VM_METER = 0x1 VM_SWAPUSAGE = 0x5 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VT0 = 0x0 VT1 = 0x10000 VTDLY = 0x10000 VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x10 WCOREFLAG = 0x80 WEXITED = 0x4 WNOHANG = 0x1 WNOWAIT = 0x20 WORDSIZE = 0x40 WSTOPPED = 0x8 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADARCH = syscall.Errno(0x56) EBADEXEC = syscall.Errno(0x55) EBADF = syscall.Errno(0x9) EBADMACHO = syscall.Errno(0x58) EBADMSG = syscall.Errno(0x5e) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x59) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDEVERR = syscall.Errno(0x53) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x5a) EILSEQ = syscall.Errno(0x5c) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x6a) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5f) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x5d) ENOBUFS = syscall.Errno(0x37) ENODATA = syscall.Errno(0x60) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x61) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5b) ENOPOLICY = syscall.Errno(0x67) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x62) ENOSTR = syscall.Errno(0x63) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x68) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x66) EOVERFLOW = syscall.Errno(0x54) EOWNERDEAD = syscall.Errno(0x69) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x64) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) EPWROFF = syscall.Errno(0x52) EQFULL = syscall.Errno(0x6a) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHLIBVERS = syscall.Errno(0x57) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIME = syscall.Errno(0x65) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "resource busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "device power is off", 83: "device error", 84: "value too large to be stored in data type", 85: "bad executable (or shared library)", 86: "bad CPU type in executable", 87: "shared library version mismatch", 88: "malformed Mach-o file", 89: "operation canceled", 90: "identifier removed", 91: "no message of desired type", 92: "illegal byte sequence", 93: "attribute not found", 94: "bad message", 95: "EMULTIHOP (Reserved)", 96: "no message available on STREAM", 97: "ENOLINK (Reserved)", 98: "no STREAM resources", 99: "not a STREAM", 100: "protocol error", 101: "STREAM ioctl timeout", 102: "operation not supported on socket", 103: "policy not found", 104: "state not recoverable", 105: "previous owner died", 106: "interface output queue is full", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_darwin_arm.go0000644061062106075000000020517513172163421025601 0ustar stgraberdomain admins// mkerrors.sh // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,darwin // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1c AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x25 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1e AF_IPX = 0x17 AF_ISDN = 0x1c AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x28 AF_NATM = 0x1f AF_NDRV = 0x1b AF_NETBIOS = 0x21 AF_NS = 0x6 AF_OSI = 0x7 AF_PPP = 0x22 AF_PUP = 0x4 AF_RESERVED_36 = 0x24 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_SYSTEM = 0x20 AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_UTUN = 0x26 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc00c4279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4010426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80104267 BIOCSETFNR = 0x8010427e BIOCSETIF = 0x8020426c BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8010426d BIOCSSEESENT = 0x80044277 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_MONOTONIC_RAW_APPROX = 0x5 CLOCK_PROCESS_CPUTIME_ID = 0xc CLOCK_REALTIME = 0x0 CLOCK_THREAD_CPUTIME_ID = 0x10 CLOCK_UPTIME_RAW = 0x8 CLOCK_UPTIME_RAW_APPROX = 0x9 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 CR3 = 0x3000 CRDLY = 0x3000 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NOFCS = 0xe6 DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPNET = 0xe2 DLT_IPOIB = 0xf2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FIBRECHANNEL = 0xea DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_SRX_E2E = 0xe9 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_JUNIPER_VS = 0xe8 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MATCHING_MAX = 0xf5 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPEG_2_TS = 0xf3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_MUX27010 = 0xec DLT_NETANALYZER = 0xf0 DLT_NETANALYZER_TRANSPARENT = 0xf1 DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PPP_WITH_DIRECTION = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DLT_WIHART = 0xdf DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_EXCEPT = -0xf EVFILT_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xf EVFILT_THREADMARKER = 0xf EVFILT_TIMER = -0x7 EVFILT_USER = -0xa EVFILT_VM = -0xc EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_DISPATCH2 = 0x180 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG0 = 0x1000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_OOBAND = 0x2000 EV_POLL = 0x1000 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EV_UDATA_SPECIFIC = 0x100 EV_VANISHED = 0x200 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDFILESIGS_FOR_DYLD_SIM = 0x53 F_ADDFILESIGS_RETURN = 0x61 F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 F_BARRIERFSYNC = 0x55 F_CHECK_LV = 0x62 F_CHKCLEAN = 0x29 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x43 F_FINDSIGS = 0x4e F_FLUSH_DATA = 0x28 F_FREEZE_FS = 0x35 F_FULLFSYNC = 0x33 F_GETCODEDIR = 0x48 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETLKPID = 0x42 F_GETNOSIGPIPE = 0x4a F_GETOWN = 0x5 F_GETPATH = 0x32 F_GETPATH_MTMINFO = 0x47 F_GETPROTECTIONCLASS = 0x3f F_GETPROTECTIONLEVEL = 0x4d F_GLOBAL_NOCACHE = 0x37 F_LOG2PHYS = 0x31 F_LOG2PHYS_EXT = 0x41 F_NOCACHE = 0x30 F_NODIRECT = 0x3e F_OK = 0x0 F_PATHPKG_CHECK = 0x34 F_PEOFPOSMODE = 0x3 F_PREALLOCATE = 0x2a F_RDADVISE = 0x2c F_RDAHEAD = 0x2d F_RDLCK = 0x1 F_SETBACKINGSTORE = 0x46 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETLKWTIMEOUT = 0xa F_SETNOSIGPIPE = 0x49 F_SETOWN = 0x6 F_SETPROTECTIONCLASS = 0x40 F_SETSIZE = 0x2b F_SINGLE_WRITER = 0x4c F_THAW_FS = 0x36 F_TRANSCODEKEY = 0x4b F_UNLCK = 0x2 F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_AAL5 = 0x31 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ATM = 0x25 IFT_BRIDGE = 0xd1 IFT_CARP = 0xf8 IFT_CELLULAR = 0xff IFT_CEPT = 0x13 IFT_DS3 = 0x1e IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_ETHER = 0x6 IFT_FAITH = 0x38 IFT_FDDI = 0xf IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_GIF = 0x37 IFT_HDH1822 = 0x3 IFT_HIPPI = 0x2f IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IEEE1394 = 0x90 IFT_IEEE8023ADLAG = 0x88 IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88026 = 0xa IFT_L2VLAN = 0x87 IFT_LAPB = 0x10 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_NSIP = 0x1b IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PDP = 0xff IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PKTAP = 0xfe IFT_PPP = 0x17 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PTPSERIAL = 0x16 IFT_RS232 = 0x21 IFT_SDLC = 0x11 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_STARLAN = 0xb IFT_STF = 0x39 IFT_T1 = 0x12 IFT_ULTRA = 0x1d IFT_V35 = 0x2d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LINKLOCALNETNUM = 0xa9fe0000 IN_LOOPBACKNET = 0x7f IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0xfe IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MEAS = 0x13 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OSPFIGP = 0x59 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SCTP = 0x84 IPPROTO_SDRP = 0x2a IPPROTO_SEP = 0x21 IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_2292DSTOPTS = 0x17 IPV6_2292HOPLIMIT = 0x14 IPV6_2292HOPOPTS = 0x16 IPV6_2292NEXTHOP = 0x15 IPV6_2292PKTINFO = 0x13 IPV6_2292PKTOPTIONS = 0x19 IPV6_2292RTHDR = 0x18 IPV6_BINDV6ONLY = 0x1b IPV6_BOUND_IF = 0x7d IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x3c IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXOPTHDR = 0x800 IPV6_MAXPACKET = 0xffff IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVTCLASS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x24 IPV6_UNICAST_HOPS = 0x4 IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BLOCK_SOURCE = 0x48 IP_BOUND_IF = 0x19 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_DROP_SOURCE_MEMBERSHIP = 0x47 IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FAITH = 0x16 IP_FW_ADD = 0x28 IP_FW_DEL = 0x29 IP_FW_FLUSH = 0x2a IP_FW_GET = 0x2c IP_FW_RESETLOG = 0x2d IP_FW_ZERO = 0x2b IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_GROUP_SRC_FILTER = 0x200 IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 IP_MF = 0x2000 IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_IFINDEX = 0x42 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_NAT__XXX = 0x37 IP_OFFMASK = 0x1fff IP_OLD_FW_ADD = 0x32 IP_OLD_FW_DEL = 0x33 IP_OLD_FW_FLUSH = 0x34 IP_OLD_FW_GET = 0x36 IP_OLD_FW_RESETLOG = 0x38 IP_OLD_FW_ZERO = 0x35 IP_OPTIONS = 0x1 IP_PKTINFO = 0x1a IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVPKTINFO = 0x1a IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x18 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_STRIPHDR = 0x17 IP_TOS = 0x3 IP_TRAFFIC_MGT_BACKGROUND = 0x41 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x49 ISIG = 0x80 ISTRIP = 0x20 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_CAN_REUSE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_FREE_REUSABLE = 0x7 MADV_FREE_REUSE = 0x8 MADV_NORMAL = 0x0 MADV_PAGEOUT = 0xa MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_JIT = 0x800 MAP_NOCACHE = 0x400 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_RESERVED0080 = 0x80 MAP_RESILIENT_CODESIGN = 0x2000 MAP_RESILIENT_MEDIA = 0x4000 MAP_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ASYNC = 0x40 MNT_AUTOMOUNTED = 0x400000 MNT_CMDFLAGS = 0xf0000 MNT_CPROTECT = 0x80 MNT_DEFWRITE = 0x2000000 MNT_DONTBROWSE = 0x100000 MNT_DOVOLFS = 0x8000 MNT_DWAIT = 0x4 MNT_EXPORTED = 0x100 MNT_FORCE = 0x80000 MNT_IGNORE_OWNERSHIP = 0x200000 MNT_JOURNALED = 0x800000 MNT_LOCAL = 0x1000 MNT_MULTILABEL = 0x4000000 MNT_NOATIME = 0x10000000 MNT_NOBLOCK = 0x20000 MNT_NODEV = 0x10 MNT_NOEXEC = 0x4 MNT_NOSUID = 0x8 MNT_NOUSERXATTR = 0x1000000 MNT_NOWAIT = 0x2 MNT_QUARANTINE = 0x400 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 MNT_UNKNOWNPERMISSIONS = 0x200000 MNT_UPDATE = 0x10000 MNT_VISFLAGMASK = 0x17f0f5ff MNT_WAIT = 0x1 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_FLUSH = 0x400 MSG_HAVEMORE = 0x2000 MSG_HOLD = 0x800 MSG_NEEDSA = 0x10000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_RCVMORE = 0x4000 MSG_SEND = 0x1000 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MSG_WAITSTREAM = 0x200 MS_ASYNC = 0x1 MS_DEACTIVATE = 0x8 MS_INVALIDATE = 0x2 MS_KILLPAGES = 0x4 MS_SYNC = 0x10 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_DUMP2 = 0x7 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFLIST2 = 0x6 NET_RT_MAXID = 0xa NET_RT_STAT = 0x4 NET_RT_TRASH = 0x5 NL0 = 0x0 NL1 = 0x100 NL2 = 0x200 NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ABSOLUTE = 0x8 NOTE_ATTRIB = 0x8 NOTE_BACKGROUND = 0x40 NOTE_CHILD = 0x4 NOTE_CRITICAL = 0x20 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXITSTATUS = 0x4000000 NOTE_EXIT_CSERROR = 0x40000 NOTE_EXIT_DECRYPTFAIL = 0x10000 NOTE_EXIT_DETAIL = 0x2000000 NOTE_EXIT_DETAIL_MASK = 0x70000 NOTE_EXIT_MEMORY = 0x20000 NOTE_EXIT_REPARENTED = 0x80000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FORK = 0x40000000 NOTE_FUNLOCK = 0x100 NOTE_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_MACH_CONTINUOUS_TIME = 0x80 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 NOTE_OOB = 0x2 NOTE_PCTRLMASK = -0x100000 NOTE_PDATAMASK = 0xfffff NOTE_REAP = 0x10000000 NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_SECONDS = 0x1 NOTE_SIGNAL = 0x8000000 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_USECONDS = 0x2 NOTE_VM_ERROR = 0x10000000 NOTE_VM_PRESSURE = 0x80000000 NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 NOTE_VM_PRESSURE_TERMINATE = 0x40000000 NOTE_WRITE = 0x2 OCRNL = 0x10 OFDEL = 0x20000 OFILL = 0x80 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_ALERT = 0x20000000 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x1000000 O_CREAT = 0x200 O_DIRECTORY = 0x100000 O_DP_GETRAWENCRYPTED = 0x1 O_DP_GETRAWUNENCRYPTED = 0x2 O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x20000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PT_ATTACH = 0xa PT_ATTACHEXC = 0xe PT_CONTINUE = 0x7 PT_DENY_ATTACH = 0x1f PT_DETACH = 0xb PT_FIRSTMACH = 0x20 PT_FORCEQUOTA = 0x1e PT_KILL = 0x8 PT_READ_D = 0x2 PT_READ_I = 0x1 PT_READ_U = 0x3 PT_SIGEXC = 0xc PT_STEP = 0x9 PT_THUPDATE = 0xd PT_TRACE_ME = 0x0 PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_CPU_USAGE_MONITOR = 0x2 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x8 RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CLONING = 0x100 RTF_CONDEMNED = 0x2000000 RTF_DELCLONE = 0x80 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_IFREF = 0x4000000 RTF_IFSCOPE = 0x1000000 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MULTICAST = 0x800000 RTF_NOIFREF = 0x2000 RTF_PINNED = 0x100000 RTF_PRCLONING = 0x10000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_PROXY = 0x8000000 RTF_REJECT = 0x8 RTF_ROUTER = 0x10000000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_WASCLONED = 0x20000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_GET2 = 0x14 RTM_IFINFO = 0xe RTM_IFINFO2 = 0x12 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_NEWMADDR2 = 0x13 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SCM_TIMESTAMP_MONOTONIC = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCARPIPLL = 0xc0206928 SIOCATMARK = 0x40047307 SIOCAUTOADDR = 0xc0206926 SIOCAUTONETMASK = 0x80206927 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206941 SIOCGDRVSPEC = 0xc028697b SIOCGETVLAN = 0xc020697f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFALTMTU = 0xc0206948 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBOND = 0xc0206947 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020695b SIOCGIFCONF = 0xc00c6924 SIOCGIFDEVMTU = 0xc0206944 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFKPI = 0xc0206987 SIOCGIFMAC = 0xc0206982 SIOCGIFMEDIA = 0xc02c6938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206940 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc020693f SIOCGIFSTATUS = 0xc331693d SIOCGIFVLAN = 0xc020697f SIOCGIFWAKEFLAGS = 0xc0206988 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCIFCREATE = 0xc0206978 SIOCIFCREATE2 = 0xc020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106981 SIOCRSLVMULTI = 0xc010693b SIOCSDRVSPEC = 0x8028697b SIOCSETVLAN = 0x8020697e SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFALTMTU = 0x80206945 SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBOND = 0x80206946 SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020695a SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFKPI = 0x80206986 SIOCSIFLLADDR = 0x8020693c SIOCSIFMAC = 0x80206983 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x8040693e SIOCSIFPHYS = 0x80206936 SIOCSIFVLAN = 0x8020697e SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_DONTTRUNC = 0x2000 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LABEL = 0x1010 SO_LINGER = 0x80 SO_LINGER_SEC = 0x1080 SO_NETSVC_MARKING_LEVEL = 0x1119 SO_NET_SERVICE_TYPE = 0x1116 SO_NKE = 0x1021 SO_NOADDRERR = 0x1023 SO_NOSIGPIPE = 0x1022 SO_NOTIFYCONFLICT = 0x1026 SO_NP_EXTENSIONS = 0x1083 SO_NREAD = 0x1020 SO_NUMRCVPKT = 0x1112 SO_NWRITE = 0x1024 SO_OOBINLINE = 0x100 SO_PEERLABEL = 0x1011 SO_RANDOMPORT = 0x1082 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_REUSESHAREUID = 0x1025 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TIMESTAMP_MONOTONIC = 0x800 SO_TYPE = 0x1008 SO_UPCALLCLOSEWAIT = 0x1027 SO_USELOOPBACK = 0x40 SO_WANTMORE = 0x4000 SO_WANTOOBFLAG = 0x8000 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IFWHT = 0xe000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0x4 TABDLY = 0xc04 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_CONNECTION_INFO = 0x106 TCP_ENABLE_ECN = 0x104 TCP_FASTOPEN = 0x105 TCP_KEEPALIVE = 0x10 TCP_KEEPCNT = 0x102 TCP_KEEPINTVL = 0x101 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x4 TCP_MAX_WINSHIFT = 0xe TCP_MINMSS = 0xd8 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_NOTSENT_LOWAT = 0x201 TCP_RXT_CONNDROPTIME = 0x80 TCP_RXT_FINDROP = 0x100 TCP_SENDMOREACKS = 0x103 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x40107458 TIOCDRAIN = 0x2000745e TIOCDSIMICROCODE = 0x20007455 TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x40487413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGWINSZ = 0x40087468 TIOCIXOFF = 0x20007480 TIOCIXON = 0x20007481 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMODG = 0x40047403 TIOCMODS = 0x80047404 TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTYGNAME = 0x40807453 TIOCPTYGRANT = 0x20007454 TIOCPTYUNLK = 0x20007452 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCONS = 0x20007463 TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x80487414 TIOCSETAF = 0x80487416 TIOCSETAW = 0x80487415 TIOCSETD = 0x8004741b TIOCSIG = 0x2000745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VM_LOADAVG = 0x2 VM_MACHFACTOR = 0x4 VM_MAXID = 0x6 VM_METER = 0x1 VM_SWAPUSAGE = 0x5 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VT0 = 0x0 VT1 = 0x10000 VTDLY = 0x10000 VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x10 WCOREFLAG = 0x80 WEXITED = 0x4 WNOHANG = 0x1 WNOWAIT = 0x20 WORDSIZE = 0x40 WSTOPPED = 0x8 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADARCH = syscall.Errno(0x56) EBADEXEC = syscall.Errno(0x55) EBADF = syscall.Errno(0x9) EBADMACHO = syscall.Errno(0x58) EBADMSG = syscall.Errno(0x5e) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x59) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDEVERR = syscall.Errno(0x53) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x5a) EILSEQ = syscall.Errno(0x5c) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x6a) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5f) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x5d) ENOBUFS = syscall.Errno(0x37) ENODATA = syscall.Errno(0x60) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x61) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5b) ENOPOLICY = syscall.Errno(0x67) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x62) ENOSTR = syscall.Errno(0x63) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x68) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x66) EOVERFLOW = syscall.Errno(0x54) EOWNERDEAD = syscall.Errno(0x69) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x64) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) EPWROFF = syscall.Errno(0x52) EQFULL = syscall.Errno(0x6a) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHLIBVERS = syscall.Errno(0x57) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIME = syscall.Errno(0x65) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "resource busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "device power is off", 83: "device error", 84: "value too large to be stored in data type", 85: "bad executable (or shared library)", 86: "bad CPU type in executable", 87: "shared library version mismatch", 88: "malformed Mach-o file", 89: "operation canceled", 90: "identifier removed", 91: "no message of desired type", 92: "illegal byte sequence", 93: "attribute not found", 94: "bad message", 95: "EMULTIHOP (Reserved)", 96: "no message available on STREAM", 97: "ENOLINK (Reserved)", 98: "no STREAM resources", 99: "not a STREAM", 100: "protocol error", 101: "STREAM ioctl timeout", 102: "operation not supported on socket", 103: "policy not found", 104: "state not recoverable", 105: "previous owner died", 106: "interface output queue is full", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_darwin_amd64.go0000644061062106075000000020521113172163421025724 0ustar stgraberdomain admins// mkerrors.sh -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,darwin // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1c AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x25 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1e AF_IPX = 0x17 AF_ISDN = 0x1c AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x28 AF_NATM = 0x1f AF_NDRV = 0x1b AF_NETBIOS = 0x21 AF_NS = 0x6 AF_OSI = 0x7 AF_PPP = 0x22 AF_PUP = 0x4 AF_RESERVED_36 = 0x24 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_SYSTEM = 0x20 AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_UTUN = 0x26 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc00c4279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4010426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80104267 BIOCSETFNR = 0x8010427e BIOCSETIF = 0x8020426c BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8010426d BIOCSSEESENT = 0x80044277 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_MONOTONIC_RAW_APPROX = 0x5 CLOCK_PROCESS_CPUTIME_ID = 0xc CLOCK_REALTIME = 0x0 CLOCK_THREAD_CPUTIME_ID = 0x10 CLOCK_UPTIME_RAW = 0x8 CLOCK_UPTIME_RAW_APPROX = 0x9 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 CR3 = 0x3000 CRDLY = 0x3000 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NOFCS = 0xe6 DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPNET = 0xe2 DLT_IPOIB = 0xf2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FIBRECHANNEL = 0xea DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_SRX_E2E = 0xe9 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_JUNIPER_VS = 0xe8 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MATCHING_MAX = 0xf5 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPEG_2_TS = 0xf3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_MUX27010 = 0xec DLT_NETANALYZER = 0xf0 DLT_NETANALYZER_TRANSPARENT = 0xf1 DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PPP_WITH_DIRECTION = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DLT_WIHART = 0xdf DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_EXCEPT = -0xf EVFILT_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xf EVFILT_THREADMARKER = 0xf EVFILT_TIMER = -0x7 EVFILT_USER = -0xa EVFILT_VM = -0xc EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_DISPATCH2 = 0x180 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG0 = 0x1000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_OOBAND = 0x2000 EV_POLL = 0x1000 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EV_UDATA_SPECIFIC = 0x100 EV_VANISHED = 0x200 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDFILESIGS_FOR_DYLD_SIM = 0x53 F_ADDFILESIGS_RETURN = 0x61 F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 F_BARRIERFSYNC = 0x55 F_CHECK_LV = 0x62 F_CHKCLEAN = 0x29 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x43 F_FINDSIGS = 0x4e F_FLUSH_DATA = 0x28 F_FREEZE_FS = 0x35 F_FULLFSYNC = 0x33 F_GETCODEDIR = 0x48 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETLKPID = 0x42 F_GETNOSIGPIPE = 0x4a F_GETOWN = 0x5 F_GETPATH = 0x32 F_GETPATH_MTMINFO = 0x47 F_GETPROTECTIONCLASS = 0x3f F_GETPROTECTIONLEVEL = 0x4d F_GLOBAL_NOCACHE = 0x37 F_LOG2PHYS = 0x31 F_LOG2PHYS_EXT = 0x41 F_NOCACHE = 0x30 F_NODIRECT = 0x3e F_OK = 0x0 F_PATHPKG_CHECK = 0x34 F_PEOFPOSMODE = 0x3 F_PREALLOCATE = 0x2a F_RDADVISE = 0x2c F_RDAHEAD = 0x2d F_RDLCK = 0x1 F_SETBACKINGSTORE = 0x46 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETLKWTIMEOUT = 0xa F_SETNOSIGPIPE = 0x49 F_SETOWN = 0x6 F_SETPROTECTIONCLASS = 0x40 F_SETSIZE = 0x2b F_SINGLE_WRITER = 0x4c F_THAW_FS = 0x36 F_TRANSCODEKEY = 0x4b F_UNLCK = 0x2 F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_AAL5 = 0x31 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ATM = 0x25 IFT_BRIDGE = 0xd1 IFT_CARP = 0xf8 IFT_CELLULAR = 0xff IFT_CEPT = 0x13 IFT_DS3 = 0x1e IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_ETHER = 0x6 IFT_FAITH = 0x38 IFT_FDDI = 0xf IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_GIF = 0x37 IFT_HDH1822 = 0x3 IFT_HIPPI = 0x2f IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IEEE1394 = 0x90 IFT_IEEE8023ADLAG = 0x88 IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88026 = 0xa IFT_L2VLAN = 0x87 IFT_LAPB = 0x10 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_NSIP = 0x1b IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PDP = 0xff IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PKTAP = 0xfe IFT_PPP = 0x17 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PTPSERIAL = 0x16 IFT_RS232 = 0x21 IFT_SDLC = 0x11 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_STARLAN = 0xb IFT_STF = 0x39 IFT_T1 = 0x12 IFT_ULTRA = 0x1d IFT_V35 = 0x2d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LINKLOCALNETNUM = 0xa9fe0000 IN_LOOPBACKNET = 0x7f IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0xfe IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MEAS = 0x13 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OSPFIGP = 0x59 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SCTP = 0x84 IPPROTO_SDRP = 0x2a IPPROTO_SEP = 0x21 IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_2292DSTOPTS = 0x17 IPV6_2292HOPLIMIT = 0x14 IPV6_2292HOPOPTS = 0x16 IPV6_2292NEXTHOP = 0x15 IPV6_2292PKTINFO = 0x13 IPV6_2292PKTOPTIONS = 0x19 IPV6_2292RTHDR = 0x18 IPV6_BINDV6ONLY = 0x1b IPV6_BOUND_IF = 0x7d IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x3c IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXOPTHDR = 0x800 IPV6_MAXPACKET = 0xffff IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVTCLASS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x24 IPV6_UNICAST_HOPS = 0x4 IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BLOCK_SOURCE = 0x48 IP_BOUND_IF = 0x19 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_DROP_SOURCE_MEMBERSHIP = 0x47 IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FAITH = 0x16 IP_FW_ADD = 0x28 IP_FW_DEL = 0x29 IP_FW_FLUSH = 0x2a IP_FW_GET = 0x2c IP_FW_RESETLOG = 0x2d IP_FW_ZERO = 0x2b IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_GROUP_SRC_FILTER = 0x200 IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 IP_MF = 0x2000 IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_IFINDEX = 0x42 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_NAT__XXX = 0x37 IP_OFFMASK = 0x1fff IP_OLD_FW_ADD = 0x32 IP_OLD_FW_DEL = 0x33 IP_OLD_FW_FLUSH = 0x34 IP_OLD_FW_GET = 0x36 IP_OLD_FW_RESETLOG = 0x38 IP_OLD_FW_ZERO = 0x35 IP_OPTIONS = 0x1 IP_PKTINFO = 0x1a IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVPKTINFO = 0x1a IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x18 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_STRIPHDR = 0x17 IP_TOS = 0x3 IP_TRAFFIC_MGT_BACKGROUND = 0x41 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x49 ISIG = 0x80 ISTRIP = 0x20 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_CAN_REUSE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_FREE_REUSABLE = 0x7 MADV_FREE_REUSE = 0x8 MADV_NORMAL = 0x0 MADV_PAGEOUT = 0xa MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_JIT = 0x800 MAP_NOCACHE = 0x400 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_RESERVED0080 = 0x80 MAP_RESILIENT_CODESIGN = 0x2000 MAP_RESILIENT_MEDIA = 0x4000 MAP_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ASYNC = 0x40 MNT_AUTOMOUNTED = 0x400000 MNT_CMDFLAGS = 0xf0000 MNT_CPROTECT = 0x80 MNT_DEFWRITE = 0x2000000 MNT_DONTBROWSE = 0x100000 MNT_DOVOLFS = 0x8000 MNT_DWAIT = 0x4 MNT_EXPORTED = 0x100 MNT_FORCE = 0x80000 MNT_IGNORE_OWNERSHIP = 0x200000 MNT_JOURNALED = 0x800000 MNT_LOCAL = 0x1000 MNT_MULTILABEL = 0x4000000 MNT_NOATIME = 0x10000000 MNT_NOBLOCK = 0x20000 MNT_NODEV = 0x10 MNT_NOEXEC = 0x4 MNT_NOSUID = 0x8 MNT_NOUSERXATTR = 0x1000000 MNT_NOWAIT = 0x2 MNT_QUARANTINE = 0x400 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 MNT_UNKNOWNPERMISSIONS = 0x200000 MNT_UPDATE = 0x10000 MNT_VISFLAGMASK = 0x17f0f5ff MNT_WAIT = 0x1 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_FLUSH = 0x400 MSG_HAVEMORE = 0x2000 MSG_HOLD = 0x800 MSG_NEEDSA = 0x10000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_RCVMORE = 0x4000 MSG_SEND = 0x1000 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MSG_WAITSTREAM = 0x200 MS_ASYNC = 0x1 MS_DEACTIVATE = 0x8 MS_INVALIDATE = 0x2 MS_KILLPAGES = 0x4 MS_SYNC = 0x10 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_DUMP2 = 0x7 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFLIST2 = 0x6 NET_RT_MAXID = 0xa NET_RT_STAT = 0x4 NET_RT_TRASH = 0x5 NL0 = 0x0 NL1 = 0x100 NL2 = 0x200 NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ABSOLUTE = 0x8 NOTE_ATTRIB = 0x8 NOTE_BACKGROUND = 0x40 NOTE_CHILD = 0x4 NOTE_CRITICAL = 0x20 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXITSTATUS = 0x4000000 NOTE_EXIT_CSERROR = 0x40000 NOTE_EXIT_DECRYPTFAIL = 0x10000 NOTE_EXIT_DETAIL = 0x2000000 NOTE_EXIT_DETAIL_MASK = 0x70000 NOTE_EXIT_MEMORY = 0x20000 NOTE_EXIT_REPARENTED = 0x80000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FORK = 0x40000000 NOTE_FUNLOCK = 0x100 NOTE_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_MACH_CONTINUOUS_TIME = 0x80 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 NOTE_OOB = 0x2 NOTE_PCTRLMASK = -0x100000 NOTE_PDATAMASK = 0xfffff NOTE_REAP = 0x10000000 NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_SECONDS = 0x1 NOTE_SIGNAL = 0x8000000 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_USECONDS = 0x2 NOTE_VM_ERROR = 0x10000000 NOTE_VM_PRESSURE = 0x80000000 NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 NOTE_VM_PRESSURE_TERMINATE = 0x40000000 NOTE_WRITE = 0x2 OCRNL = 0x10 OFDEL = 0x20000 OFILL = 0x80 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_ALERT = 0x20000000 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x1000000 O_CREAT = 0x200 O_DIRECTORY = 0x100000 O_DP_GETRAWENCRYPTED = 0x1 O_DP_GETRAWUNENCRYPTED = 0x2 O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x20000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PT_ATTACH = 0xa PT_ATTACHEXC = 0xe PT_CONTINUE = 0x7 PT_DENY_ATTACH = 0x1f PT_DETACH = 0xb PT_FIRSTMACH = 0x20 PT_FORCEQUOTA = 0x1e PT_KILL = 0x8 PT_READ_D = 0x2 PT_READ_I = 0x1 PT_READ_U = 0x3 PT_SIGEXC = 0xc PT_STEP = 0x9 PT_THUPDATE = 0xd PT_TRACE_ME = 0x0 PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_CPU_USAGE_MONITOR = 0x2 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x8 RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CLONING = 0x100 RTF_CONDEMNED = 0x2000000 RTF_DELCLONE = 0x80 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_IFREF = 0x4000000 RTF_IFSCOPE = 0x1000000 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MULTICAST = 0x800000 RTF_NOIFREF = 0x2000 RTF_PINNED = 0x100000 RTF_PRCLONING = 0x10000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_PROXY = 0x8000000 RTF_REJECT = 0x8 RTF_ROUTER = 0x10000000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_WASCLONED = 0x20000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_GET2 = 0x14 RTM_IFINFO = 0xe RTM_IFINFO2 = 0x12 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_NEWMADDR2 = 0x13 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SCM_TIMESTAMP_MONOTONIC = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCARPIPLL = 0xc0206928 SIOCATMARK = 0x40047307 SIOCAUTOADDR = 0xc0206926 SIOCAUTONETMASK = 0x80206927 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206941 SIOCGDRVSPEC = 0xc028697b SIOCGETVLAN = 0xc020697f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFALTMTU = 0xc0206948 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBOND = 0xc0206947 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020695b SIOCGIFCONF = 0xc00c6924 SIOCGIFDEVMTU = 0xc0206944 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFKPI = 0xc0206987 SIOCGIFMAC = 0xc0206982 SIOCGIFMEDIA = 0xc02c6938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206940 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc020693f SIOCGIFSTATUS = 0xc331693d SIOCGIFVLAN = 0xc020697f SIOCGIFWAKEFLAGS = 0xc0206988 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCIFCREATE = 0xc0206978 SIOCIFCREATE2 = 0xc020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106981 SIOCRSLVMULTI = 0xc010693b SIOCSDRVSPEC = 0x8028697b SIOCSETVLAN = 0x8020697e SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFALTMTU = 0x80206945 SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBOND = 0x80206946 SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020695a SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFKPI = 0x80206986 SIOCSIFLLADDR = 0x8020693c SIOCSIFMAC = 0x80206983 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x8040693e SIOCSIFPHYS = 0x80206936 SIOCSIFVLAN = 0x8020697e SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_DONTTRUNC = 0x2000 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LABEL = 0x1010 SO_LINGER = 0x80 SO_LINGER_SEC = 0x1080 SO_NETSVC_MARKING_LEVEL = 0x1119 SO_NET_SERVICE_TYPE = 0x1116 SO_NKE = 0x1021 SO_NOADDRERR = 0x1023 SO_NOSIGPIPE = 0x1022 SO_NOTIFYCONFLICT = 0x1026 SO_NP_EXTENSIONS = 0x1083 SO_NREAD = 0x1020 SO_NUMRCVPKT = 0x1112 SO_NWRITE = 0x1024 SO_OOBINLINE = 0x100 SO_PEERLABEL = 0x1011 SO_RANDOMPORT = 0x1082 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_REUSESHAREUID = 0x1025 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TIMESTAMP_MONOTONIC = 0x800 SO_TYPE = 0x1008 SO_UPCALLCLOSEWAIT = 0x1027 SO_USELOOPBACK = 0x40 SO_WANTMORE = 0x4000 SO_WANTOOBFLAG = 0x8000 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IFWHT = 0xe000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0x4 TABDLY = 0xc04 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_CONNECTION_INFO = 0x106 TCP_ENABLE_ECN = 0x104 TCP_FASTOPEN = 0x105 TCP_KEEPALIVE = 0x10 TCP_KEEPCNT = 0x102 TCP_KEEPINTVL = 0x101 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x4 TCP_MAX_WINSHIFT = 0xe TCP_MINMSS = 0xd8 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_NOTSENT_LOWAT = 0x201 TCP_RXT_CONNDROPTIME = 0x80 TCP_RXT_FINDROP = 0x100 TCP_SENDMOREACKS = 0x103 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x40107458 TIOCDRAIN = 0x2000745e TIOCDSIMICROCODE = 0x20007455 TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x40487413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGWINSZ = 0x40087468 TIOCIXOFF = 0x20007480 TIOCIXON = 0x20007481 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMODG = 0x40047403 TIOCMODS = 0x80047404 TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTYGNAME = 0x40807453 TIOCPTYGRANT = 0x20007454 TIOCPTYUNLK = 0x20007452 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCONS = 0x20007463 TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x80487414 TIOCSETAF = 0x80487416 TIOCSETAW = 0x80487415 TIOCSETD = 0x8004741b TIOCSIG = 0x2000745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VM_LOADAVG = 0x2 VM_MACHFACTOR = 0x4 VM_MAXID = 0x6 VM_METER = 0x1 VM_SWAPUSAGE = 0x5 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VT0 = 0x0 VT1 = 0x10000 VTDLY = 0x10000 VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x10 WCOREFLAG = 0x80 WEXITED = 0x4 WNOHANG = 0x1 WNOWAIT = 0x20 WORDSIZE = 0x40 WSTOPPED = 0x8 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADARCH = syscall.Errno(0x56) EBADEXEC = syscall.Errno(0x55) EBADF = syscall.Errno(0x9) EBADMACHO = syscall.Errno(0x58) EBADMSG = syscall.Errno(0x5e) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x59) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDEVERR = syscall.Errno(0x53) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x5a) EILSEQ = syscall.Errno(0x5c) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x6a) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5f) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x5d) ENOBUFS = syscall.Errno(0x37) ENODATA = syscall.Errno(0x60) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x61) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5b) ENOPOLICY = syscall.Errno(0x67) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x62) ENOSTR = syscall.Errno(0x63) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x68) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x66) EOVERFLOW = syscall.Errno(0x54) EOWNERDEAD = syscall.Errno(0x69) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x64) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) EPWROFF = syscall.Errno(0x52) EQFULL = syscall.Errno(0x6a) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHLIBVERS = syscall.Errno(0x57) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIME = syscall.Errno(0x65) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "resource busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "device power is off", 83: "device error", 84: "value too large to be stored in data type", 85: "bad executable (or shared library)", 86: "bad CPU type in executable", 87: "shared library version mismatch", 88: "malformed Mach-o file", 89: "operation canceled", 90: "identifier removed", 91: "no message of desired type", 92: "illegal byte sequence", 93: "attribute not found", 94: "bad message", 95: "EMULTIHOP (Reserved)", 96: "no message available on STREAM", 97: "ENOLINK (Reserved)", 98: "no STREAM resources", 99: "not a STREAM", 100: "protocol error", 101: "STREAM ioctl timeout", 102: "operation not supported on socket", 103: "policy not found", 104: "state not recoverable", 105: "previous owner died", 106: "interface output queue is full", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/zerrors_darwin_386.go0000644061062106075000000020520713172163421025336 0ustar stgraberdomain admins// mkerrors.sh -m32 // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,darwin // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m32 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1c AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x25 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1e AF_IPX = 0x17 AF_ISDN = 0x1c AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x28 AF_NATM = 0x1f AF_NDRV = 0x1b AF_NETBIOS = 0x21 AF_NS = 0x6 AF_OSI = 0x7 AF_PPP = 0x22 AF_PUP = 0x4 AF_RESERVED_36 = 0x24 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_SYSTEM = 0x20 AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_UTUN = 0x26 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc00c4279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4008426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80084267 BIOCSETFNR = 0x8008427e BIOCSETIF = 0x8020426c BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8008426d BIOCSSEESENT = 0x80044277 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x6 CLOCK_MONOTONIC_RAW = 0x4 CLOCK_MONOTONIC_RAW_APPROX = 0x5 CLOCK_PROCESS_CPUTIME_ID = 0xc CLOCK_REALTIME = 0x0 CLOCK_THREAD_CPUTIME_ID = 0x10 CLOCK_UPTIME_RAW = 0x8 CLOCK_UPTIME_RAW_APPROX = 0x9 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 CR3 = 0x3000 CRDLY = 0x3000 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_AOS = 0xde DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CAN_SOCKETCAN = 0xe3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd DLT_DOCSIS = 0x8f DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NOFCS = 0xe6 DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IPNET = 0xe2 DLT_IPOIB = 0xf2 DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FIBRECHANNEL = 0xea DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_SRX_E2E = 0xe9 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_JUNIPER_VS = 0xe8 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_EVDEV = 0xd8 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MATCHING_MAX = 0xf5 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MPEG_2_TS = 0xf3 DLT_MPLS = 0xdb DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_MUX27010 = 0xec DLT_NETANALYZER = 0xf0 DLT_NETANALYZER_TRANSPARENT = 0xf1 DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PPP_WITH_DIRECTION = 0xa6 DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 DLT_USER1 = 0x94 DLT_USER10 = 0x9d DLT_USER11 = 0x9e DLT_USER12 = 0x9f DLT_USER13 = 0xa0 DLT_USER14 = 0xa1 DLT_USER15 = 0xa2 DLT_USER2 = 0x95 DLT_USER3 = 0x96 DLT_USER4 = 0x97 DLT_USER5 = 0x98 DLT_USER6 = 0x99 DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c DLT_WIHART = 0xdf DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_EXCEPT = -0xf EVFILT_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xf EVFILT_THREADMARKER = 0xf EVFILT_TIMER = -0x7 EVFILT_USER = -0xa EVFILT_VM = -0xc EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_DISPATCH2 = 0x180 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG0 = 0x1000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_OOBAND = 0x2000 EV_POLL = 0x1000 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EV_UDATA_SPECIFIC = 0x100 EV_VANISHED = 0x200 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDFILESIGS_FOR_DYLD_SIM = 0x53 F_ADDFILESIGS_RETURN = 0x61 F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 F_BARRIERFSYNC = 0x55 F_CHECK_LV = 0x62 F_CHKCLEAN = 0x29 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x43 F_FINDSIGS = 0x4e F_FLUSH_DATA = 0x28 F_FREEZE_FS = 0x35 F_FULLFSYNC = 0x33 F_GETCODEDIR = 0x48 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETLKPID = 0x42 F_GETNOSIGPIPE = 0x4a F_GETOWN = 0x5 F_GETPATH = 0x32 F_GETPATH_MTMINFO = 0x47 F_GETPROTECTIONCLASS = 0x3f F_GETPROTECTIONLEVEL = 0x4d F_GLOBAL_NOCACHE = 0x37 F_LOG2PHYS = 0x31 F_LOG2PHYS_EXT = 0x41 F_NOCACHE = 0x30 F_NODIRECT = 0x3e F_OK = 0x0 F_PATHPKG_CHECK = 0x34 F_PEOFPOSMODE = 0x3 F_PREALLOCATE = 0x2a F_RDADVISE = 0x2c F_RDAHEAD = 0x2d F_RDLCK = 0x1 F_SETBACKINGSTORE = 0x46 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETLKWTIMEOUT = 0xa F_SETNOSIGPIPE = 0x49 F_SETOWN = 0x6 F_SETPROTECTIONCLASS = 0x40 F_SETSIZE = 0x2b F_SINGLE_WRITER = 0x4c F_THAW_FS = 0x36 F_TRANSCODEKEY = 0x4b F_UNLCK = 0x2 F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_AAL5 = 0x31 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ATM = 0x25 IFT_BRIDGE = 0xd1 IFT_CARP = 0xf8 IFT_CELLULAR = 0xff IFT_CEPT = 0x13 IFT_DS3 = 0x1e IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_ETHER = 0x6 IFT_FAITH = 0x38 IFT_FDDI = 0xf IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_GIF = 0x37 IFT_HDH1822 = 0x3 IFT_HIPPI = 0x2f IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IEEE1394 = 0x90 IFT_IEEE8023ADLAG = 0x88 IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88026 = 0xa IFT_L2VLAN = 0x87 IFT_LAPB = 0x10 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_NSIP = 0x1b IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PDP = 0xff IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PKTAP = 0xfe IFT_PPP = 0x17 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PTPSERIAL = 0x16 IFT_RS232 = 0x21 IFT_SDLC = 0x11 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_STARLAN = 0xb IFT_STF = 0x39 IFT_T1 = 0x12 IFT_ULTRA = 0x1d IFT_V35 = 0x2d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LINKLOCALNETNUM = 0xa9fe0000 IN_LOOPBACKNET = 0x7f IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0xfe IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MEAS = 0x13 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OSPFIGP = 0x59 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SCTP = 0x84 IPPROTO_SDRP = 0x2a IPPROTO_SEP = 0x21 IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_2292DSTOPTS = 0x17 IPV6_2292HOPLIMIT = 0x14 IPV6_2292HOPOPTS = 0x16 IPV6_2292NEXTHOP = 0x15 IPV6_2292PKTINFO = 0x13 IPV6_2292PKTOPTIONS = 0x19 IPV6_2292RTHDR = 0x18 IPV6_BINDV6ONLY = 0x1b IPV6_BOUND_IF = 0x7d IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x3c IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXOPTHDR = 0x800 IPV6_MAXPACKET = 0xffff IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVTCLASS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x24 IPV6_UNICAST_HOPS = 0x4 IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BLOCK_SOURCE = 0x48 IP_BOUND_IF = 0x19 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_DROP_SOURCE_MEMBERSHIP = 0x47 IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FAITH = 0x16 IP_FW_ADD = 0x28 IP_FW_DEL = 0x29 IP_FW_FLUSH = 0x2a IP_FW_GET = 0x2c IP_FW_RESETLOG = 0x2d IP_FW_ZERO = 0x2b IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_GROUP_SRC_FILTER = 0x200 IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 IP_MF = 0x2000 IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_IFINDEX = 0x42 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_NAT__XXX = 0x37 IP_OFFMASK = 0x1fff IP_OLD_FW_ADD = 0x32 IP_OLD_FW_DEL = 0x33 IP_OLD_FW_FLUSH = 0x34 IP_OLD_FW_GET = 0x36 IP_OLD_FW_RESETLOG = 0x38 IP_OLD_FW_ZERO = 0x35 IP_OPTIONS = 0x1 IP_PKTINFO = 0x1a IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVPKTINFO = 0x1a IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x18 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_STRIPHDR = 0x17 IP_TOS = 0x3 IP_TRAFFIC_MGT_BACKGROUND = 0x41 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x49 ISIG = 0x80 ISTRIP = 0x20 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_CAN_REUSE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_FREE_REUSABLE = 0x7 MADV_FREE_REUSE = 0x8 MADV_NORMAL = 0x0 MADV_PAGEOUT = 0xa MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_JIT = 0x800 MAP_NOCACHE = 0x400 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_RESERVED0080 = 0x80 MAP_RESILIENT_CODESIGN = 0x2000 MAP_RESILIENT_MEDIA = 0x4000 MAP_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ASYNC = 0x40 MNT_AUTOMOUNTED = 0x400000 MNT_CMDFLAGS = 0xf0000 MNT_CPROTECT = 0x80 MNT_DEFWRITE = 0x2000000 MNT_DONTBROWSE = 0x100000 MNT_DOVOLFS = 0x8000 MNT_DWAIT = 0x4 MNT_EXPORTED = 0x100 MNT_FORCE = 0x80000 MNT_IGNORE_OWNERSHIP = 0x200000 MNT_JOURNALED = 0x800000 MNT_LOCAL = 0x1000 MNT_MULTILABEL = 0x4000000 MNT_NOATIME = 0x10000000 MNT_NOBLOCK = 0x20000 MNT_NODEV = 0x10 MNT_NOEXEC = 0x4 MNT_NOSUID = 0x8 MNT_NOUSERXATTR = 0x1000000 MNT_NOWAIT = 0x2 MNT_QUARANTINE = 0x400 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 MNT_UNKNOWNPERMISSIONS = 0x200000 MNT_UPDATE = 0x10000 MNT_VISFLAGMASK = 0x17f0f5ff MNT_WAIT = 0x1 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_FLUSH = 0x400 MSG_HAVEMORE = 0x2000 MSG_HOLD = 0x800 MSG_NEEDSA = 0x10000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_RCVMORE = 0x4000 MSG_SEND = 0x1000 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MSG_WAITSTREAM = 0x200 MS_ASYNC = 0x1 MS_DEACTIVATE = 0x8 MS_INVALIDATE = 0x2 MS_KILLPAGES = 0x4 MS_SYNC = 0x10 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_DUMP2 = 0x7 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFLIST2 = 0x6 NET_RT_MAXID = 0xa NET_RT_STAT = 0x4 NET_RT_TRASH = 0x5 NL0 = 0x0 NL1 = 0x100 NL2 = 0x200 NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ABSOLUTE = 0x8 NOTE_ATTRIB = 0x8 NOTE_BACKGROUND = 0x40 NOTE_CHILD = 0x4 NOTE_CRITICAL = 0x20 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXITSTATUS = 0x4000000 NOTE_EXIT_CSERROR = 0x40000 NOTE_EXIT_DECRYPTFAIL = 0x10000 NOTE_EXIT_DETAIL = 0x2000000 NOTE_EXIT_DETAIL_MASK = 0x70000 NOTE_EXIT_MEMORY = 0x20000 NOTE_EXIT_REPARENTED = 0x80000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FORK = 0x40000000 NOTE_FUNLOCK = 0x100 NOTE_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_MACH_CONTINUOUS_TIME = 0x80 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 NOTE_OOB = 0x2 NOTE_PCTRLMASK = -0x100000 NOTE_PDATAMASK = 0xfffff NOTE_REAP = 0x10000000 NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_SECONDS = 0x1 NOTE_SIGNAL = 0x8000000 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_USECONDS = 0x2 NOTE_VM_ERROR = 0x10000000 NOTE_VM_PRESSURE = 0x80000000 NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 NOTE_VM_PRESSURE_TERMINATE = 0x40000000 NOTE_WRITE = 0x2 OCRNL = 0x10 OFDEL = 0x20000 OFILL = 0x80 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_ALERT = 0x20000000 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x1000000 O_CREAT = 0x200 O_DIRECTORY = 0x100000 O_DP_GETRAWENCRYPTED = 0x1 O_DP_GETRAWUNENCRYPTED = 0x2 O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x20000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PT_ATTACH = 0xa PT_ATTACHEXC = 0xe PT_CONTINUE = 0x7 PT_DENY_ATTACH = 0x1f PT_DETACH = 0xb PT_FIRSTMACH = 0x20 PT_FORCEQUOTA = 0x1e PT_KILL = 0x8 PT_READ_D = 0x2 PT_READ_I = 0x1 PT_READ_U = 0x3 PT_SIGEXC = 0xc PT_STEP = 0x9 PT_THUPDATE = 0xd PT_TRACE_ME = 0x0 PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_CPU_USAGE_MONITOR = 0x2 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 RLIMIT_NPROC = 0x7 RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x8 RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CLONING = 0x100 RTF_CONDEMNED = 0x2000000 RTF_DELCLONE = 0x80 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_IFREF = 0x4000000 RTF_IFSCOPE = 0x1000000 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MULTICAST = 0x800000 RTF_NOIFREF = 0x2000 RTF_PINNED = 0x100000 RTF_PRCLONING = 0x10000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_PROXY = 0x8000000 RTF_REJECT = 0x8 RTF_ROUTER = 0x10000000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_WASCLONED = 0x20000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_GET2 = 0x14 RTM_IFINFO = 0xe RTM_IFINFO2 = 0x12 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_NEWMADDR2 = 0x13 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SCM_TIMESTAMP_MONOTONIC = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCARPIPLL = 0xc0206928 SIOCATMARK = 0x40047307 SIOCAUTOADDR = 0xc0206926 SIOCAUTONETMASK = 0x80206927 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206941 SIOCGDRVSPEC = 0xc01c697b SIOCGETVLAN = 0xc020697f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFALTMTU = 0xc0206948 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBOND = 0xc0206947 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020695b SIOCGIFCONF = 0xc0086924 SIOCGIFDEVMTU = 0xc0206944 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFKPI = 0xc0206987 SIOCGIFMAC = 0xc0206982 SIOCGIFMEDIA = 0xc0286938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206940 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc020693f SIOCGIFSTATUS = 0xc331693d SIOCGIFVLAN = 0xc020697f SIOCGIFWAKEFLAGS = 0xc0206988 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCIFCREATE = 0xc0206978 SIOCIFCREATE2 = 0xc020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc00c6981 SIOCRSLVMULTI = 0xc008693b SIOCSDRVSPEC = 0x801c697b SIOCSETVLAN = 0x8020697e SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFALTMTU = 0x80206945 SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBOND = 0x80206946 SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020695a SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFKPI = 0x80206986 SIOCSIFLLADDR = 0x8020693c SIOCSIFMAC = 0x80206983 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x8040693e SIOCSIFPHYS = 0x80206936 SIOCSIFVLAN = 0x8020697e SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_DONTTRUNC = 0x2000 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LABEL = 0x1010 SO_LINGER = 0x80 SO_LINGER_SEC = 0x1080 SO_NETSVC_MARKING_LEVEL = 0x1119 SO_NET_SERVICE_TYPE = 0x1116 SO_NKE = 0x1021 SO_NOADDRERR = 0x1023 SO_NOSIGPIPE = 0x1022 SO_NOTIFYCONFLICT = 0x1026 SO_NP_EXTENSIONS = 0x1083 SO_NREAD = 0x1020 SO_NUMRCVPKT = 0x1112 SO_NWRITE = 0x1024 SO_OOBINLINE = 0x100 SO_PEERLABEL = 0x1011 SO_RANDOMPORT = 0x1082 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_REUSESHAREUID = 0x1025 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TIMESTAMP_MONOTONIC = 0x800 SO_TYPE = 0x1008 SO_UPCALLCLOSEWAIT = 0x1027 SO_USELOOPBACK = 0x40 SO_WANTMORE = 0x4000 SO_WANTOOBFLAG = 0x8000 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IFWHT = 0xe000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0x4 TABDLY = 0xc04 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_CONNECTION_INFO = 0x106 TCP_ENABLE_ECN = 0x104 TCP_FASTOPEN = 0x105 TCP_KEEPALIVE = 0x10 TCP_KEEPCNT = 0x102 TCP_KEEPINTVL = 0x101 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x4 TCP_MAX_WINSHIFT = 0xe TCP_MINMSS = 0xd8 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_NOTSENT_LOWAT = 0x201 TCP_RXT_CONNDROPTIME = 0x80 TCP_RXT_FINDROP = 0x100 TCP_SENDMOREACKS = 0x103 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x40087458 TIOCDRAIN = 0x2000745e TIOCDSIMICROCODE = 0x20007455 TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGWINSZ = 0x40087468 TIOCIXOFF = 0x20007480 TIOCIXON = 0x20007481 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMODG = 0x40047403 TIOCMODS = 0x80047404 TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTYGNAME = 0x40807453 TIOCPTYGRANT = 0x20007454 TIOCPTYUNLK = 0x20007452 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCONS = 0x20007463 TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSIG = 0x2000745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40087459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VM_LOADAVG = 0x2 VM_MACHFACTOR = 0x4 VM_MAXID = 0x6 VM_METER = 0x1 VM_SWAPUSAGE = 0x5 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VT0 = 0x0 VT1 = 0x10000 VTDLY = 0x10000 VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x10 WCOREFLAG = 0x80 WEXITED = 0x4 WNOHANG = 0x1 WNOWAIT = 0x20 WORDSIZE = 0x20 WSTOPPED = 0x8 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADARCH = syscall.Errno(0x56) EBADEXEC = syscall.Errno(0x55) EBADF = syscall.Errno(0x9) EBADMACHO = syscall.Errno(0x58) EBADMSG = syscall.Errno(0x5e) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x59) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDEVERR = syscall.Errno(0x53) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x5a) EILSEQ = syscall.Errno(0x5c) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x6a) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5f) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x5d) ENOBUFS = syscall.Errno(0x37) ENODATA = syscall.Errno(0x60) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x61) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5b) ENOPOLICY = syscall.Errno(0x67) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x62) ENOSTR = syscall.Errno(0x63) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x68) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x66) EOVERFLOW = syscall.Errno(0x54) EOWNERDEAD = syscall.Errno(0x69) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x64) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) EPWROFF = syscall.Errno(0x52) EQFULL = syscall.Errno(0x6a) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHLIBVERS = syscall.Errno(0x57) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIME = syscall.Errno(0x65) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "resource busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "device power is off", 83: "device error", 84: "value too large to be stored in data type", 85: "bad executable (or shared library)", 86: "bad CPU type in executable", 87: "shared library version mismatch", 88: "malformed Mach-o file", 89: "operation canceled", 90: "identifier removed", 91: "no message of desired type", 92: "illegal byte sequence", 93: "attribute not found", 94: "bad message", 95: "EMULTIHOP (Reserved)", 96: "no message available on STREAM", 97: "ENOLINK (Reserved)", 98: "no STREAM resources", 99: "not a STREAM", 100: "protocol error", 101: "STREAM ioctl timeout", 102: "operation not supported on socket", 103: "policy not found", 104: "state not recoverable", 105: "previous owner died", 106: "interface output queue is full", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", } lxd-2.0.11/dist/src/golang.org/x/sys/unix/types_solaris.go0000644061062106075000000001261613172163421024564 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See README.md */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL // These defines ensure that builds done on newer versions of Solaris are // backwards-compatible with older versions of Solaris and // OpenSolaris-based derivatives. #define __USE_SUNOS_SOCKETS__ // msghdr #define __USE_LEGACY_PROTOTYPES__ // iovec #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong PathMax = C.PATH_MAX MaxHostNameLen = C.MAXHOSTNAMELEN ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timeval32 C.struct_timeval32 type Tms C.struct_tms type Utimbuf C.struct_utimbuf // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Flock_t C.struct_flock type Dirent C.struct_dirent // Filesystems type _Fsblkcnt_t C.fsblkcnt_t type Statvfs_t C.struct_statvfs // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Select type FdSet C.fd_set // Misc type Utsname C.struct_utsname type Ustat_t C.struct_ustat const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW AT_REMOVEDIR = C.AT_REMOVEDIR AT_EACCESS = C.AT_EACCESS ) // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfTimeval C.struct_bpf_timeval type BpfHdr C.struct_bpf_hdr // Terminal handling type Termios C.struct_termios type Termio C.struct_termio type Winsize C.struct_winsize lxd-2.0.11/dist/src/golang.org/x/sys/unix/types_openbsd.go0000644061062106075000000001176613172163421024547 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See README.md */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.fsid_t // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics type Mclpool C.struct_mclpool // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfTimeval C.struct_bpf_timeval // Terminal handling type Termios C.struct_termios // fchmodat-like syscalls. const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/types_netbsd.go0000644061062106075000000001135013172163421024361 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See README.md */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.fsid_t // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics type Mclpool C.struct_mclpool // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfTimeval C.struct_bpf_timeval // Terminal handling type Termios C.struct_termios // fchmodat-like syscalls. const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) // Sysctl type Sysctlnode C.struct_sysctlnode lxd-2.0.11/dist/src/golang.org/x/sys/unix/types_freebsd.go0000644061062106075000000002005513172163421024516 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See README.md */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; // This structure is a duplicate of stat on FreeBSD 8-STABLE. // See /usr/include/sys/stat.h. struct stat8 { #undef st_atimespec st_atim #undef st_mtimespec st_mtim #undef st_ctimespec st_ctim #undef st_birthtimespec st_birthtim __dev_t st_dev; ino_t st_ino; mode_t st_mode; nlink_t st_nlink; uid_t st_uid; gid_t st_gid; __dev_t st_rdev; #if __BSD_VISIBLE struct timespec st_atimespec; struct timespec st_mtimespec; struct timespec st_ctimespec; #else time_t st_atime; long __st_atimensec; time_t st_mtime; long __st_mtimensec; time_t st_ctime; long __st_ctimensec; #endif off_t st_size; blkcnt_t st_blocks; blksize_t st_blksize; fflags_t st_flags; __uint32_t st_gen; __int32_t st_lspare; #if __BSD_VISIBLE struct timespec st_birthtimespec; unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); #else time_t st_birthtime; long st_birthtimensec; unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); #endif }; // This structure is a duplicate of if_data on FreeBSD 8-STABLE. // See /usr/include/net/if.h. struct if_data8 { u_char ifi_type; u_char ifi_physical; u_char ifi_addrlen; u_char ifi_hdrlen; u_char ifi_link_state; u_char ifi_spare_char1; u_char ifi_spare_char2; u_char ifi_datalen; u_long ifi_mtu; u_long ifi_metric; u_long ifi_baudrate; u_long ifi_ipackets; u_long ifi_ierrors; u_long ifi_opackets; u_long ifi_oerrors; u_long ifi_collisions; u_long ifi_ibytes; u_long ifi_obytes; u_long ifi_imcasts; u_long ifi_omcasts; u_long ifi_iqdrops; u_long ifi_noproto; u_long ifi_hwassist; // FIXME: these are now unions, so maybe need to change definitions? #undef ifi_epoch time_t ifi_epoch; #undef ifi_lastchange struct timeval ifi_lastchange; }; // This structure is a duplicate of if_msghdr on FreeBSD 8-STABLE. // See /usr/include/net/if.h. struct if_msghdr8 { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; int ifm_addrs; int ifm_flags; u_short ifm_index; struct if_data8 ifm_data; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat8 type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.struct_fsid // Advice to Fadvise const ( FADV_NORMAL = C.POSIX_FADV_NORMAL FADV_RANDOM = C.POSIX_FADV_RANDOM FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL FADV_WILLNEED = C.POSIX_FADV_WILLNEED FADV_DONTNEED = C.POSIX_FADV_DONTNEED FADV_NOREUSE = C.POSIX_FADV_NOREUSE ) // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPMreqn C.struct_ip_mreqn type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPMreqn = C.sizeof_struct_ip_mreqn SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( sizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfMsghdr = C.sizeof_struct_if_msghdr8 sizeofIfData = C.sizeof_struct_if_data SizeofIfData = C.sizeof_struct_if_data8 SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type ifMsghdr C.struct_if_msghdr type IfMsghdr C.struct_if_msghdr8 type ifData C.struct_if_data type IfData C.struct_if_data8 type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfZbuf = C.sizeof_struct_bpf_zbuf SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr SizeofBpfZbufHeader = C.sizeof_struct_bpf_zbuf_header ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfZbuf C.struct_bpf_zbuf type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfZbufHeader C.struct_bpf_zbuf_header // Terminal handling type Termios C.struct_termios type Winsize C.struct_winsize // fchmodat-like syscalls. const ( AT_FDCWD = C.AT_FDCWD AT_REMOVEDIR = C.AT_REMOVEDIR AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) // Capabilities type CapRights C.struct_cap_rights lxd-2.0.11/dist/src/golang.org/x/sys/unix/types_dragonfly.go0000644061062106075000000001177513172163421025102 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See README.md */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.struct_fsid // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr // Terminal handling type Termios C.struct_termios // fchmodat-like syscalls. const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/types_darwin.go0000644061062106075000000001221413172163421024366 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See README.md */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define __DARWIN_UNIX03 0 #define KERNEL #define _DARWIN_USE_64_BIT_INODE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timeval32 C.struct_timeval32 // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat64 type Statfs_t C.struct_statfs64 type Flock_t C.struct_flock type Fstore_t C.struct_fstore type Radvisory_t C.struct_radvisory type Fbootstraptransfer_t C.struct_fbootstraptransfer type Log2phys_t C.struct_log2phys type Fsid C.struct_fsid type Dirent C.struct_dirent // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet4Pktinfo C.struct_in_pktinfo type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2 SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfmaMsghdr2 C.struct_ifma_msghdr2 type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr // Terminal handling type Termios C.struct_termios type Winsize C.struct_winsize // fchmodat-like syscalls. const ( AT_FDCWD = C.AT_FDCWD AT_REMOVEDIR = C.AT_REMOVEDIR AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_unix_test.go0000644061062106075000000002061213172163421025433 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix_test import ( "flag" "fmt" "io/ioutil" "net" "os" "os/exec" "path/filepath" "runtime" "testing" "time" "golang.org/x/sys/unix" ) // Tests that below functions, structures and constants are consistent // on all Unix-like systems. func _() { // program scheduling priority functions and constants var ( _ func(int, int, int) error = unix.Setpriority _ func(int, int) (int, error) = unix.Getpriority ) const ( _ int = unix.PRIO_USER _ int = unix.PRIO_PROCESS _ int = unix.PRIO_PGRP ) // termios constants const ( _ int = unix.TCIFLUSH _ int = unix.TCIOFLUSH _ int = unix.TCOFLUSH ) // fcntl file locking structure and constants var ( _ = unix.Flock_t{ Type: int16(0), Whence: int16(0), Start: int64(0), Len: int64(0), Pid: int32(0), } ) const ( _ = unix.F_GETLK _ = unix.F_SETLK _ = unix.F_SETLKW ) } // TestFcntlFlock tests whether the file locking structure matches // the calling convention of each kernel. func TestFcntlFlock(t *testing.T) { name := filepath.Join(os.TempDir(), "TestFcntlFlock") fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) if err != nil { t.Fatalf("Open failed: %v", err) } defer unix.Unlink(name) defer unix.Close(fd) flock := unix.Flock_t{ Type: unix.F_RDLCK, Start: 0, Len: 0, Whence: 1, } if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil { t.Fatalf("FcntlFlock failed: %v", err) } } // TestPassFD tests passing a file descriptor over a Unix socket. // // This test involved both a parent and child process. The parent // process is invoked as a normal test, with "go test", which then // runs the child process by running the current test binary with args // "-test.run=^TestPassFD$" and an environment variable used to signal // that the test should become the child process instead. func TestPassFD(t *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { passFDChild() return } tempDir, err := ioutil.TempDir("", "TestPassFD") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) if err != nil { t.Fatalf("Socketpair: %v", err) } defer unix.Close(fds[0]) defer unix.Close(fds[1]) writeFile := os.NewFile(uintptr(fds[0]), "child-writes") readFile := os.NewFile(uintptr(fds[1]), "parent-reads") defer writeFile.Close() defer readFile.Close() cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) } cmd.ExtraFiles = []*os.File{writeFile} out, err := cmd.CombinedOutput() if len(out) > 0 || err != nil { t.Fatalf("child process: %q, %v", out, err) } c, err := net.FileConn(readFile) if err != nil { t.Fatalf("FileConn: %v", err) } defer c.Close() uc, ok := c.(*net.UnixConn) if !ok { t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c) } buf := make([]byte, 32) // expect 1 byte oob := make([]byte, 32) // expect 24 bytes closeUnix := time.AfterFunc(5*time.Second, func() { t.Logf("timeout reading from unix socket") uc.Close() }) _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob) closeUnix.Stop() scms, err := unix.ParseSocketControlMessage(oob[:oobn]) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != 1 { t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms) } scm := scms[0] gotFds, err := unix.ParseUnixRights(&scm) if err != nil { t.Fatalf("unix.ParseUnixRights: %v", err) } if len(gotFds) != 1 { t.Fatalf("wanted 1 fd; got %#v", gotFds) } f := os.NewFile(uintptr(gotFds[0]), "fd-from-child") defer f.Close() got, err := ioutil.ReadAll(f) want := "Hello from child process!\n" if string(got) != want { t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want) } } // passFDChild is the child process used by TestPassFD. func passFDChild() { defer os.Exit(0) // Look for our fd. It should be fd 3, but we work around an fd leak // bug here (http://golang.org/issue/2603) to let it be elsewhere. var uc *net.UnixConn for fd := uintptr(3); fd <= 10; fd++ { f := os.NewFile(fd, "unix-conn") var ok bool netc, _ := net.FileConn(f) uc, ok = netc.(*net.UnixConn) if ok { break } } if uc == nil { fmt.Println("failed to find unix fd") return } // Make a file f to send to our parent process on uc. // We make it in tempDir, which our parent will clean up. flag.Parse() tempDir := flag.Arg(0) f, err := ioutil.TempFile(tempDir, "") if err != nil { fmt.Printf("TempFile: %v", err) return } f.Write([]byte("Hello from child process!\n")) f.Seek(0, 0) rights := unix.UnixRights(int(f.Fd())) dummyByte := []byte("x") n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil) if err != nil { fmt.Printf("WriteMsgUnix: %v", err) return } if n != 1 || oobn != len(rights) { fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights)) return } } // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage, // and ParseUnixRights are able to successfully round-trip lists of file descriptors. func TestUnixRightsRoundtrip(t *testing.T) { testCases := [...][][]int{ {{42}}, {{1, 2}}, {{3, 4, 5}}, {{}}, {{1, 2}, {3, 4, 5}, {}, {7}}, } for _, testCase := range testCases { b := []byte{} var n int for _, fds := range testCase { // Last assignment to n wins n = len(b) + unix.CmsgLen(4*len(fds)) b = append(b, unix.UnixRights(fds...)...) } // Truncate b b = b[:n] scms, err := unix.ParseSocketControlMessage(b) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != len(testCase) { t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms) } for i, scm := range scms { gotFds, err := unix.ParseUnixRights(&scm) if err != nil { t.Fatalf("ParseUnixRights: %v", err) } wantFds := testCase[i] if len(gotFds) != len(wantFds) { t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds) } for j, fd := range gotFds { if fd != wantFds[j] { t.Fatalf("expected fd %v, got %v", wantFds[j], fd) } } } } } func TestRlimit(t *testing.T) { var rlimit, zero unix.Rlimit err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit) if err != nil { t.Fatalf("Getrlimit: save failed: %v", err) } if zero == rlimit { t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit) } set := rlimit set.Cur = set.Max - 1 err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set) if err != nil { t.Fatalf("Setrlimit: set failed: %#v %v", set, err) } var get unix.Rlimit err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get) if err != nil { t.Fatalf("Getrlimit: get failed: %v", err) } set = rlimit set.Cur = set.Max - 1 if set != get { // Seems like Darwin requires some privilege to // increase the soft limit of rlimit sandbox, though // Setrlimit never reports an error. switch runtime.GOOS { case "darwin": default: t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get) } } err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit) if err != nil { t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err) } } func TestSeekFailure(t *testing.T) { _, err := unix.Seek(-1, 0, 0) if err == nil { t.Fatalf("Seek(-1, 0, 0) did not fail") } str := err.Error() // used to crash on Linux t.Logf("Seek: %v", str) if str == "" { t.Fatalf("Seek(-1, 0, 0) return error with empty message") } } func TestDup(t *testing.T) { file, err := ioutil.TempFile("", "TestDup") if err != nil { t.Fatalf("Tempfile failed: %v", err) } defer os.Remove(file.Name()) defer file.Close() f := int(file.Fd()) newFd, err := unix.Dup(f) if err != nil { t.Fatalf("Dup: %v", err) } err = unix.Dup2(newFd, newFd+1) if err != nil { t.Fatalf("Dup2: %v", err) } b1 := []byte("Test123") b2 := make([]byte, 7) _, err = unix.Write(newFd+1, b1) if err != nil { t.Fatalf("Write to dup2 fd failed: %v", err) } _, err = unix.Seek(f, 0, 0) _, err = unix.Read(f, b2) if err != nil { t.Fatalf("Read back failed: %v", err) } if string(b1) != string(b2) { t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2)) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_unix_gc.go0000644061062106075000000000113613172163421025045 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris // +build !gccgo package unix import "syscall" func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_unix.go0000644061062106075000000001512313172163421024375 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix import ( "runtime" "sync" "syscall" "unsafe" ) var ( Stdin = 0 Stdout = 1 Stderr = 2 ) const ( darwin64Bit = runtime.GOOS == "darwin" && sizeofPtr == 8 dragonfly64Bit = runtime.GOOS == "dragonfly" && sizeofPtr == 8 netbsd32Bit = runtime.GOOS == "netbsd" && sizeofPtr == 4 solaris64Bit = runtime.GOOS == "solaris" && sizeofPtr == 8 ) // Do the interface allocations only once for common // Errno values. var ( errEAGAIN error = syscall.EAGAIN errEINVAL error = syscall.EINVAL errENOENT error = syscall.ENOENT ) // errnoErr returns common boxed Errno values, to prevent // allocations at runtime. func errnoErr(e syscall.Errno) error { switch e { case 0: return nil case EAGAIN: return errEAGAIN case EINVAL: return errEINVAL case ENOENT: return errENOENT } return e } // Mmap manager, for use by operating system-specific implementations. type mmapper struct { sync.Mutex active map[*byte][]byte // active mappings; key is last byte in mapping mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error) munmap func(addr uintptr, length uintptr) error } func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { if length <= 0 { return nil, EINVAL } // Map the requested memory. addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset) if errno != nil { return nil, errno } // Slice memory layout var sl = struct { addr uintptr len int cap int }{addr, length, length} // Use unsafe to turn sl into a []byte. b := *(*[]byte)(unsafe.Pointer(&sl)) // Register mapping in m and return it. p := &b[cap(b)-1] m.Lock() defer m.Unlock() m.active[p] = b return b, nil } func (m *mmapper) Munmap(data []byte) (err error) { if len(data) == 0 || len(data) != cap(data) { return EINVAL } // Find the base of the mapping. p := &data[cap(data)-1] m.Lock() defer m.Unlock() b := m.active[p] if b == nil || &b[0] != &data[0] { return EINVAL } // Unmap the memory and update m. if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil { return errno } delete(m.active, p) return nil } func Read(fd int, p []byte) (n int, err error) { n, err = read(fd, p) if raceenabled { if n > 0 { raceWriteRange(unsafe.Pointer(&p[0]), n) } if err == nil { raceAcquire(unsafe.Pointer(&ioSync)) } } return } func Write(fd int, p []byte) (n int, err error) { if raceenabled { raceReleaseMerge(unsafe.Pointer(&ioSync)) } n, err = write(fd, p) if raceenabled && n > 0 { raceReadRange(unsafe.Pointer(&p[0]), n) } return } // For testing: clients can set this flag to force // creation of IPv6 sockets to return EAFNOSUPPORT. var SocketDisableIPv6 bool type Sockaddr interface { sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs } type SockaddrInet4 struct { Port int Addr [4]byte raw RawSockaddrInet4 } type SockaddrInet6 struct { Port int ZoneId uint32 Addr [16]byte raw RawSockaddrInet6 } type SockaddrUnix struct { Name string raw RawSockaddrUnix } func Bind(fd int, sa Sockaddr) (err error) { ptr, n, err := sa.sockaddr() if err != nil { return err } return bind(fd, ptr, n) } func Connect(fd int, sa Sockaddr) (err error) { ptr, n, err := sa.sockaddr() if err != nil { return err } return connect(fd, ptr, n) } func Getpeername(fd int) (sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny if err = getpeername(fd, &rsa, &len); err != nil { return } return anyToSockaddr(&rsa) } func GetsockoptInt(fd, level, opt int) (value int, err error) { var n int32 vallen := _Socklen(4) err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) return int(n), err } func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny if n, err = recvfrom(fd, p, flags, &rsa, &len); err != nil { return } if rsa.Addr.Family != AF_UNSPEC { from, err = anyToSockaddr(&rsa) } return } func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) { ptr, n, err := to.sockaddr() if err != nil { return err } return sendto(fd, p, flags, ptr, n) } func SetsockoptByte(fd, level, opt int, value byte) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(&value), 1) } func SetsockoptInt(fd, level, opt int, value int) (err error) { var n = int32(value) return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4) } func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(&value[0]), 4) } func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPMreq) } func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPv6Mreq) } func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error { return setsockopt(fd, level, opt, unsafe.Pointer(filter), SizeofICMPv6Filter) } func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(l), SizeofLinger) } func SetsockoptString(fd, level, opt int, s string) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(&[]byte(s)[0]), uintptr(len(s))) } func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(tv), unsafe.Sizeof(*tv)) } func Socket(domain, typ, proto int) (fd int, err error) { if domain == AF_INET6 && SocketDisableIPv6 { return -1, EAFNOSUPPORT } fd, err = socket(domain, typ, proto) return } func Socketpair(domain, typ, proto int) (fd [2]int, err error) { var fdx [2]int32 err = socketpair(domain, typ, proto, &fdx) if err == nil { fd[0] = int(fdx[0]) fd[1] = int(fdx[1]) } return } func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { if raceenabled { raceReleaseMerge(unsafe.Pointer(&ioSync)) } return sendfile(outfd, infd, offset, count) } var ioSync int64 func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) } func SetNonblock(fd int, nonblocking bool) (err error) { flag, err := fcntl(fd, F_GETFL, 0) if err != nil { return err } if nonblocking { flag |= O_NONBLOCK } else { flag &= ^O_NONBLOCK } _, err = fcntl(fd, F_SETFL, flag) return err } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_test.go0000644061062106075000000000207513172163421024373 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix_test import ( "fmt" "testing" "golang.org/x/sys/unix" ) func testSetGetenv(t *testing.T, key, value string) { err := unix.Setenv(key, value) if err != nil { t.Fatalf("Setenv failed to set %q: %v", value, err) } newvalue, found := unix.Getenv(key) if !found { t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) } if newvalue != value { t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) } } func TestEnv(t *testing.T) { testSetGetenv(t, "TESTENV", "AVALUE") // make sure TESTENV gets set to "", not deleted testSetGetenv(t, "TESTENV", "") } func TestItoa(t *testing.T) { // Make most negative integer: 0x8000... i := 1 for i<<1 != 0 { i <<= 1 } if i >= 0 { t.Fatal("bad math") } s := unix.Itoa(i) f := fmt.Sprint(i) if s != f { t.Fatalf("itoa(%d) = %s, want %s", i, s, f) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_solaris_test.go0000644061062106075000000000126413172163421026126 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package unix_test import ( "os/exec" "testing" "golang.org/x/sys/unix" ) func TestStatvfs(t *testing.T) { if err := unix.Statvfs("", nil); err == nil { t.Fatal(`Statvfs("") expected failure`) } statvfs := unix.Statvfs_t{} if err := unix.Statvfs("/", &statvfs); err != nil { t.Errorf(`Statvfs("/") failed: %v`, err) } if t.Failed() { mount, err := exec.Command("mount").CombinedOutput() if err != nil { t.Logf("mount: %v\n%s", err, mount) } else { t.Logf("mount: %s", mount) } } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_solaris_amd64.go0000644061062106075000000000151213172163421026056 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,solaris package unix func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = nsec % 1e9 / 1e3 tv.Sec = int64(nsec / 1e9) return } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { // TODO(aram): implement this, see issue 5847. panic("unimplemented") } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_solaris.go0000644061062106075000000004762113172163421025076 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Solaris system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and wrap // it in our own nicer implementation, either here or in // syscall_solaris.go or syscall_unix.go. package unix import ( "syscall" "unsafe" ) // Implemented in runtime/syscall_solaris.go. type syscallFunc uintptr func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) type SockaddrDatalink struct { Family uint16 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [244]int8 raw RawSockaddrDatalink } func clen(n []byte) int { for i := 0; i < len(n); i++ { if n[i] == 0 { return i } } return len(n) } func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) } func direntReclen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) } func direntNamlen(buf []byte) (uint64, bool) { reclen, ok := direntReclen(buf) if !ok { return 0, false } return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true } //sysnb pipe(p *[2]_C_int) (n int, err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int n, err := pipe(&pp) if n != 0 { return err } p[0] = int(pp[0]) p[1] = int(pp[1]) return nil } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL } sa.raw.Family = AF_INET p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL } sa.raw.Family = AF_INET6 p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) sa.raw.Scope_id = sa.ZoneId for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { name := sa.Name n := len(name) if n >= len(sa.raw.Path) { return nil, 0, EINVAL } sa.raw.Family = AF_UNIX for i := 0; i < n; i++ { sa.raw.Path[i] = int8(name[i]) } // length is family (uint16), name, NUL. sl := _Socklen(2) if n > 0 { sl += _Socklen(n) + 1 } if sa.raw.Path[0] == '@' { sa.raw.Path[0] = 0 // Don't count trailing NUL for abstract address. sl-- } return unsafe.Pointer(&sa.raw), sl, nil } //sys getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getsockname func Getsockname(fd int) (sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny if err = getsockname(fd, &rsa, &len); err != nil { return } return anyToSockaddr(&rsa) } const ImplementsGetwd = true //sys Getcwd(buf []byte) (n int, err error) func Getwd() (wd string, err error) { var buf [PathMax]byte // Getcwd will return an error if it failed for any reason. _, err = Getcwd(buf[0:]) if err != nil { return "", err } n := clen(buf[:]) if n < 1 { return "", EINVAL } return string(buf[:n]), nil } /* * Wrapped */ //sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error) //sysnb setgroups(ngid int, gid *_Gid_t) (err error) func Getgroups() (gids []int, err error) { n, err := getgroups(0, nil) // Check for error and sanity check group count. Newer versions of // Solaris allow up to 1024 (NGROUPS_MAX). if n < 0 || n > 1024 { if err != nil { return nil, err } return nil, EINVAL } else if n == 0 { return nil, nil } a := make([]_Gid_t, n) n, err = getgroups(n, &a[0]) if n == -1 { return nil, err } gids = make([]int, n) for i, v := range a[0:n] { gids[i] = int(v) } return } func Setgroups(gids []int) (err error) { if len(gids) == 0 { return setgroups(0, nil) } a := make([]_Gid_t, len(gids)) for i, v := range gids { a[i] = _Gid_t(v) } return setgroups(len(a), &a[0]) } func ReadDirent(fd int, buf []byte) (n int, err error) { // Final argument is (basep *uintptr) and the syscall doesn't take nil. // TODO(rsc): Can we use a single global basep for all calls? return Getdents(fd, buf, new(uintptr)) } // Wait status is 7 bits at bottom, either 0 (exited), // 0x7F (stopped), or a signal number that caused an exit. // The 0x80 bit is whether there was a core dump. // An extra number (exit code, signal causing a stop) // is in the high bits. type WaitStatus uint32 const ( mask = 0x7F core = 0x80 shift = 8 exited = 0 stopped = 0x7F ) func (w WaitStatus) Exited() bool { return w&mask == exited } func (w WaitStatus) ExitStatus() int { if w&mask != exited { return -1 } return int(w >> shift) } func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 } func (w WaitStatus) Signal() syscall.Signal { sig := syscall.Signal(w & mask) if sig == stopped || sig == 0 { return -1 } return sig } func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP } func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP } func (w WaitStatus) StopSignal() syscall.Signal { if !w.Stopped() { return -1 } return syscall.Signal(w>>shift) & 0xFF } func (w WaitStatus) TrapCause() int { return -1 } //sys wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (int, error) { var status _C_int rpid, err := wait4(int32(pid), &status, options, rusage) wpid := int(rpid) if wpid == -1 { return wpid, err } if wstatus != nil { *wstatus = WaitStatus(status) } return wpid, nil } //sys gethostname(buf []byte) (n int, err error) func Gethostname() (name string, err error) { var buf [MaxHostNameLen]byte n, err := gethostname(buf[:]) if n != 0 { return "", err } n = clen(buf[:]) if n < 1 { return "", EFAULT } return string(buf[:n]), nil } //sys utimes(path string, times *[2]Timeval) (err error) func Utimes(path string, tv []Timeval) (err error) { if tv == nil { return utimes(path, nil) } if len(tv) != 2 { return EINVAL } return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } //sys utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) func UtimesNano(path string, ts []Timespec) error { if ts == nil { return utimensat(AT_FDCWD, path, nil, 0) } if len(ts) != 2 { return EINVAL } return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) } func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { if ts == nil { return utimensat(dirfd, path, nil, flags) } if len(ts) != 2 { return EINVAL } return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) } //sys fcntl(fd int, cmd int, arg int) (val int, err error) // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(lk)), 0, 0, 0) if e1 != 0 { return e1 } return nil } //sys futimesat(fildes int, path *byte, times *[2]Timeval) (err error) func Futimesat(dirfd int, path string, tv []Timeval) error { pathp, err := BytePtrFromString(path) if err != nil { return err } if tv == nil { return futimesat(dirfd, pathp, nil) } if len(tv) != 2 { return EINVAL } return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } // Solaris doesn't have an futimes function because it allows NULL to be // specified as the path for futimesat. However, Go doesn't like // NULL-style string interfaces, so this simple wrapper is provided. func Futimes(fd int, tv []Timeval) error { if tv == nil { return futimesat(fd, nil, nil) } if len(tv) != 2 { return EINVAL } return futimesat(fd, nil, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_UNIX: pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) sa := new(SockaddrUnix) // Assume path ends at NUL. // This is not technically the Solaris semantics for // abstract Unix domain sockets -- they are supposed // to be uninterpreted fixed-size binary blobs -- but // everyone uses this convention. n := 0 for n < len(pp.Path) && pp.Path[n] != 0 { n++ } bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n] sa.Name = string(bytes) return sa, nil case AF_INET: pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) sa := new(SockaddrInet4) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil case AF_INET6: pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) sa := new(SockaddrInet6) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) sa.ZoneId = pp.Scope_id for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil } return nil, EAFNOSUPPORT } //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = libsocket.accept func Accept(fd int) (nfd int, sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny nfd, err = accept(fd, &rsa, &len) if nfd == -1 { return } sa, err = anyToSockaddr(&rsa) if err != nil { Close(nfd) nfd = 0 } return } //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.__xnet_recvmsg func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { var msg Msghdr var rsa RawSockaddrAny msg.Name = (*byte)(unsafe.Pointer(&rsa)) msg.Namelen = uint32(SizeofSockaddrAny) var iov Iovec if len(p) > 0 { iov.Base = (*int8)(unsafe.Pointer(&p[0])) iov.SetLen(len(p)) } var dummy int8 if len(oob) > 0 { // receive at least one normal byte if len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } msg.Accrightslen = int32(len(oob)) } msg.Iov = &iov msg.Iovlen = 1 if n, err = recvmsg(fd, &msg, flags); n == -1 { return } oobn = int(msg.Accrightslen) // source address is only specified if the socket is unconnected if rsa.Addr.Family != AF_UNSPEC { from, err = anyToSockaddr(&rsa) } return } func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { _, err = SendmsgN(fd, p, oob, to, flags) return } //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.__xnet_sendmsg func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { var ptr unsafe.Pointer var salen _Socklen if to != nil { ptr, salen, err = to.sockaddr() if err != nil { return 0, err } } var msg Msghdr msg.Name = (*byte)(unsafe.Pointer(ptr)) msg.Namelen = uint32(salen) var iov Iovec if len(p) > 0 { iov.Base = (*int8)(unsafe.Pointer(&p[0])) iov.SetLen(len(p)) } var dummy int8 if len(oob) > 0 { // send at least one normal byte if len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } msg.Accrightslen = int32(len(oob)) } msg.Iov = &iov msg.Iovlen = 1 if n, err = sendmsg(fd, &msg, flags); err != nil { return 0, err } if len(oob) > 0 && len(p) == 0 { n = 0 } return n, nil } //sys acct(path *byte) (err error) func Acct(path string) (err error) { if len(path) == 0 { // Assume caller wants to disable accounting. return acct(nil) } pathp, err := BytePtrFromString(path) if err != nil { return err } return acct(pathp) } //sys __makedev(version int, major uint, minor uint) (val uint64) func Mkdev(major, minor uint32) uint64 { return __makedev(NEWDEV, uint(major), uint(minor)) } //sys __major(version int, dev uint64) (val uint) func Major(dev uint64) uint32 { return uint32(__major(NEWDEV, dev)) } //sys __minor(version int, dev uint64) (val uint) func Minor(dev uint64) uint32 { return uint32(__minor(NEWDEV, dev)) } /* * Expose the ioctl function */ //sys ioctl(fd int, req uint, arg uintptr) (err error) func IoctlSetInt(fd int, req uint, value int) (err error) { return ioctl(fd, req, uintptr(value)) } func IoctlSetWinsize(fd int, req uint, value *Winsize) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermios(fd int, req uint, value *Termios) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermio(fd int, req uint, value *Termio) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlGetInt(fd int, req uint) (int, error) { var value int err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return value, err } func IoctlGetWinsize(fd int, req uint) (*Winsize, error) { var value Winsize err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermios(fd int, req uint) (*Termios, error) { var value Termios err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermio(fd int, req uint) (*Termio, error) { var value Termio err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } /* * Exposed directly */ //sys Access(path string, mode uint32) (err error) //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) //sys Chdir(path string) (err error) //sys Chmod(path string, mode uint32) (err error) //sys Chown(path string, uid int, gid int) (err error) //sys Chroot(path string) (err error) //sys Close(fd int) (err error) //sys Creat(path string, mode uint32) (fd int, err error) //sys Dup(fd int) (nfd int, err error) //sys Dup2(oldfd int, newfd int) (err error) //sys Exit(code int) //sys Fchdir(fd int) (err error) //sys Fchmod(fd int, mode uint32) (err error) //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) //sys Fdatasync(fd int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatvfs(fd int, vfsstat *Statvfs_t) (err error) //sys Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) //sysnb Getgid() (gid int) //sysnb Getpid() (pid int) //sysnb Getpgid(pid int) (pgid int, err error) //sysnb Getpgrp() (pgid int, err error) //sys Geteuid() (euid int) //sys Getegid() (egid int) //sys Getppid() (ppid int) //sys Getpriority(which int, who int) (n int, err error) //sysnb Getrlimit(which int, lim *Rlimit) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Getuid() (uid int) //sys Kill(pid int, signum syscall.Signal) (err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Link(path string, link string) (err error) //sys Listen(s int, backlog int) (err error) = libsocket.__xnet_llisten //sys Lstat(path string, stat *Stat_t) (err error) //sys Madvise(b []byte, advice int) (err error) //sys Mkdir(path string, mode uint32) (err error) //sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mkfifoat(dirfd int, path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) //sys Mlock(b []byte) (err error) //sys Mlockall(flags int) (err error) //sys Mprotect(b []byte, prot int) (err error) //sys Msync(b []byte, flags int) (err error) //sys Munlock(b []byte) (err error) //sys Munlockall() (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) //sys Pause() (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Readlink(path string, buf []byte) (n int, err error) //sys Rename(from string, to string) (err error) //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) //sys Rmdir(path string) (err error) //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = lseek //sysnb Setegid(egid int) (err error) //sysnb Seteuid(euid int) (err error) //sysnb Setgid(gid int) (err error) //sys Sethostname(p []byte) (err error) //sysnb Setpgid(pid int, pgid int) (err error) //sys Setpriority(which int, who int, prio int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sysnb Setrlimit(which int, lim *Rlimit) (err error) //sysnb Setsid() (pid int, err error) //sysnb Setuid(uid int) (err error) //sys Shutdown(s int, how int) (err error) = libsocket.shutdown //sys Stat(path string, stat *Stat_t) (err error) //sys Statvfs(path string, vfsstat *Statvfs_t) (err error) //sys Symlink(path string, link string) (err error) //sys Sync() (err error) //sysnb Times(tms *Tms) (ticks uintptr, err error) //sys Truncate(path string, length int64) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) //sys Umask(mask int) (oldmask int) //sysnb Uname(buf *Utsname) (err error) //sys Unmount(target string, flags int) (err error) = libc.umount //sys Unlink(path string) (err error) //sys Unlinkat(dirfd int, path string, flags int) (err error) //sys Ustat(dev int, ubuf *Ustat_t) (err error) //sys Utime(path string, buf *Utimbuf) (err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_bind //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_connect //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_sendto //sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.__xnet_socket //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.__xnet_socketpair //sys write(fd int, p []byte) (n int, err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) = libsocket.__xnet_getsockopt //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getpeername //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) = libsocket.setsockopt //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = libsocket.recvfrom func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0) n = int(r0) if e1 != 0 { err = e1 } return } var mapper = &mmapper{ active: make(map[*byte][]byte), mmap: mmap, munmap: munmap, } func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { return mapper.Mmap(fd, offset, length, prot, flags) } func Munmap(b []byte) (err error) { return mapper.Munmap(b) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_openbsd_arm.go0000644061062106075000000000162013172163421025700 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm,openbsd package unix func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int64(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int64(nsec / 1e9) return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_openbsd_amd64.go0000644061062106075000000000156613172163421026045 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,openbsd package unix func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = nsec % 1e9 / 1e3 tv.Sec = nsec / 1e9 return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_openbsd_386.go0000644061062106075000000000162013172163421025441 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build 386,openbsd package unix func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int64(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int64(nsec / 1e9) return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_openbsd.go0000644061062106075000000001666513172163421025060 0ustar stgraberdomain admins// Copyright 2009,2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // OpenBSD system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and wrap // it in our own nicer implementation, either here or in // syscall_bsd.go or syscall_unix.go. package unix import ( "syscall" "unsafe" ) type SockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [24]int8 raw RawSockaddrDatalink } func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func nametomib(name string) (mib []_C_int, err error) { // Perform lookup via a binary search left := 0 right := len(sysctlMib) - 1 for { idx := left + (right-left)/2 switch { case name == sysctlMib[idx].ctlname: return sysctlMib[idx].ctloid, nil case name > sysctlMib[idx].ctlname: left = idx + 1 default: right = idx - 1 } if left > right { break } } return nil, EINVAL } func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) } func direntReclen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) } func direntNamlen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) } //sysnb pipe(p *[2]_C_int) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe(&pp) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sys getdents(fd int, buf []byte) (n int, err error) func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { return getdents(fd, buf) } // TODO func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { return -1, ENOSYS } func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { var _p0 unsafe.Pointer var bufsize uintptr if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) } r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) n = int(r0) if e1 != 0 { err = e1 } return } /* * Exposed directly */ //sys Access(path string, mode uint32) (err error) //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) //sys Chdir(path string) (err error) //sys Chflags(path string, flags int) (err error) //sys Chmod(path string, mode uint32) (err error) //sys Chown(path string, uid int, gid int) (err error) //sys Chroot(path string) (err error) //sys Close(fd int) (err error) //sys Dup(fd int) (nfd int, err error) //sys Dup2(from int, to int) (err error) //sys Exit(code int) //sys Fchdir(fd int) (err error) //sys Fchflags(fd int, flags int) (err error) //sys Fchmod(fd int, mode uint32) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatfs(fd int, stat *Statfs_t) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (uid int) //sysnb Getgid() (gid int) //sysnb Getpgid(pid int) (pgid int, err error) //sysnb Getpgrp() (pgrp int) //sysnb Getpid() (pid int) //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) //sysnb Getrlimit(which int, lim *Rlimit) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Getuid() (uid int) //sys Issetugid() (tainted bool) //sys Kill(pid int, signum syscall.Signal) (err error) //sys Kqueue() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Link(path string, link string) (err error) //sys Listen(s int, backlog int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Mkdir(path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Readlink(path string, buf []byte) (n int, err error) //sys Rename(from string, to string) (err error) //sys Revoke(path string) (err error) //sys Rmdir(path string) (err error) //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK //sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) //sysnb Setegid(egid int) (err error) //sysnb Seteuid(euid int) (err error) //sysnb Setgid(gid int) (err error) //sys Setlogin(name string) (err error) //sysnb Setpgid(pid int, pgid int) (err error) //sys Setpriority(which int, who int, prio int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(which int, lim *Rlimit) (err error) //sysnb Setsid() (pid int, err error) //sysnb Settimeofday(tp *Timeval) (err error) //sysnb Setuid(uid int) (err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Statfs(path string, stat *Statfs_t) (err error) //sys Symlink(path string, link string) (err error) //sys Sync() (err error) //sys Truncate(path string, length int64) (err error) //sys Umask(newmask int) (oldmask int) //sys Unlink(path string) (err error) //sys Unmount(path string, flags int) (err error) //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) //sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ //sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) /* * Unimplemented */ // __getcwd // __semctl // __syscall // __sysctl // adjfreq // break // clock_getres // clock_gettime // clock_settime // closefrom // execve // faccessat // fchmodat // fchownat // fcntl // fhopen // fhstat // fhstatfs // fork // fstatat // futimens // getfh // getgid // getitimer // getlogin // getresgid // getresuid // getrtable // getthrid // ioctl // ktrace // lfs_bmapv // lfs_markv // lfs_segclean // lfs_segwait // linkat // mincore // minherit // mkdirat // mkfifoat // mknodat // mount // mquery // msgctl // msgget // msgrcv // msgsnd // nfssvc // nnpfspioctl // openat // poll // preadv // profil // pwritev // quotactl // readlinkat // readv // reboot // renameat // rfork // sched_yield // semget // semop // setgroups // setitimer // setrtable // setsockopt // shmat // shmctl // shmdt // shmget // sigaction // sigaltstack // sigpending // sigprocmask // sigreturn // sigsuspend // symlinkat // sysarch // syscall // threxit // thrsigdivert // thrsleep // thrwakeup // unlinkat // vfork // writev lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_no_getwd.go0000644061062106075000000000045513172163421025222 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build dragonfly freebsd netbsd openbsd package unix const ImplementsGetwd = false func Getwd() (string, error) { return "", ENOTSUP } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_netbsd_arm.go0000644061062106075000000000162013172163421025525 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm,netbsd package unix func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int64(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int64(nsec / 1e9) return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = uint32(mode) k.Flags = uint32(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_netbsd_amd64.go0000644061062106075000000000162213172163421025663 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,netbsd package unix func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int64(nsec / 1e9) ts.Nsec = int64(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int64(nsec / 1e9) return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = uint32(mode) k.Flags = uint32(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_netbsd_386.go0000644061062106075000000000162013172163421025266 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build 386,netbsd package unix func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int64(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int64(nsec / 1e9) return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = uint32(mode) k.Flags = uint32(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_netbsd.go0000644061062106075000000002575113172163421024701 0ustar stgraberdomain admins// Copyright 2009,2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // NetBSD system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and wrap // it in our own nicer implementation, either here or in // syscall_bsd.go or syscall_unix.go. package unix import ( "syscall" "unsafe" ) type SockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 raw RawSockaddrDatalink } func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func sysctlNodes(mib []_C_int) (nodes []Sysctlnode, err error) { var olen uintptr // Get a list of all sysctl nodes below the given MIB by performing // a sysctl for the given MIB with CTL_QUERY appended. mib = append(mib, CTL_QUERY) qnode := Sysctlnode{Flags: SYSCTL_VERS_1} qp := (*byte)(unsafe.Pointer(&qnode)) sz := unsafe.Sizeof(qnode) if err = sysctl(mib, nil, &olen, qp, sz); err != nil { return nil, err } // Now that we know the size, get the actual nodes. nodes = make([]Sysctlnode, olen/sz) np := (*byte)(unsafe.Pointer(&nodes[0])) if err = sysctl(mib, np, &olen, qp, sz); err != nil { return nil, err } return nodes, nil } func nametomib(name string) (mib []_C_int, err error) { // Split name into components. var parts []string last := 0 for i := 0; i < len(name); i++ { if name[i] == '.' { parts = append(parts, name[last:i]) last = i + 1 } } parts = append(parts, name[last:]) // Discover the nodes and construct the MIB OID. for partno, part := range parts { nodes, err := sysctlNodes(mib) if err != nil { return nil, err } for _, node := range nodes { n := make([]byte, 0) for i := range node.Name { if node.Name[i] != 0 { n = append(n, byte(node.Name[i])) } } if string(n) == part { mib = append(mib, _C_int(node.Num)) break } } if len(mib) != partno+1 { return nil, EINVAL } } return mib, nil } func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) } func direntReclen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) } func direntNamlen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) } //sysnb pipe() (fd1 int, fd2 int, err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } p[0], p[1], err = pipe() return } //sys getdents(fd int, buf []byte) (n int, err error) func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { return getdents(fd, buf) } // TODO func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { return -1, ENOSYS } /* * Exposed directly */ //sys Access(path string, mode uint32) (err error) //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) //sys Chdir(path string) (err error) //sys Chflags(path string, flags int) (err error) //sys Chmod(path string, mode uint32) (err error) //sys Chown(path string, uid int, gid int) (err error) //sys Chroot(path string) (err error) //sys Close(fd int) (err error) //sys Dup(fd int) (nfd int, err error) //sys Dup2(from int, to int) (err error) //sys Exit(code int) //sys Fchdir(fd int) (err error) //sys Fchflags(fd int, flags int) (err error) //sys Fchmod(fd int, mode uint32) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (uid int) //sysnb Getgid() (gid int) //sysnb Getpgid(pid int) (pgid int, err error) //sysnb Getpgrp() (pgrp int) //sysnb Getpid() (pid int) //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) //sysnb Getrlimit(which int, lim *Rlimit) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Getuid() (uid int) //sys Issetugid() (tainted bool) //sys Kill(pid int, signum syscall.Signal) (err error) //sys Kqueue() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Link(path string, link string) (err error) //sys Listen(s int, backlog int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Mkdir(path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Readlink(path string, buf []byte) (n int, err error) //sys Rename(from string, to string) (err error) //sys Revoke(path string) (err error) //sys Rmdir(path string) (err error) //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK //sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) //sysnb Setegid(egid int) (err error) //sysnb Seteuid(euid int) (err error) //sysnb Setgid(gid int) (err error) //sysnb Setpgid(pid int, pgid int) (err error) //sys Setpriority(which int, who int, prio int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sysnb Setrlimit(which int, lim *Rlimit) (err error) //sysnb Setsid() (pid int, err error) //sysnb Settimeofday(tp *Timeval) (err error) //sysnb Setuid(uid int) (err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Symlink(path string, link string) (err error) //sys Sync() (err error) //sys Truncate(path string, length int64) (err error) //sys Umask(newmask int) (oldmask int) //sys Unlink(path string) (err error) //sys Unmount(path string, flags int) (err error) //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) //sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ //sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) /* * Unimplemented */ // ____semctl13 // __clone // __fhopen40 // __fhstat40 // __fhstatvfs140 // __fstat30 // __getcwd // __getfh30 // __getlogin // __lstat30 // __mount50 // __msgctl13 // __msync13 // __ntp_gettime30 // __posix_chown // __posix_fadvise50 // __posix_fchown // __posix_lchown // __posix_rename // __setlogin // __shmctl13 // __sigaction_sigtramp // __sigaltstack14 // __sigpending14 // __sigprocmask14 // __sigsuspend14 // __sigtimedwait // __stat30 // __syscall // __vfork14 // _ksem_close // _ksem_destroy // _ksem_getvalue // _ksem_init // _ksem_open // _ksem_post // _ksem_trywait // _ksem_unlink // _ksem_wait // _lwp_continue // _lwp_create // _lwp_ctl // _lwp_detach // _lwp_exit // _lwp_getname // _lwp_getprivate // _lwp_kill // _lwp_park // _lwp_self // _lwp_setname // _lwp_setprivate // _lwp_suspend // _lwp_unpark // _lwp_unpark_all // _lwp_wait // _lwp_wakeup // _pset_bind // _sched_getaffinity // _sched_getparam // _sched_setaffinity // _sched_setparam // acct // aio_cancel // aio_error // aio_fsync // aio_read // aio_return // aio_suspend // aio_write // break // clock_getres // clock_gettime // clock_settime // compat_09_ogetdomainname // compat_09_osetdomainname // compat_09_ouname // compat_10_omsgsys // compat_10_osemsys // compat_10_oshmsys // compat_12_fstat12 // compat_12_getdirentries // compat_12_lstat12 // compat_12_msync // compat_12_oreboot // compat_12_oswapon // compat_12_stat12 // compat_13_sigaction13 // compat_13_sigaltstack13 // compat_13_sigpending13 // compat_13_sigprocmask13 // compat_13_sigreturn13 // compat_13_sigsuspend13 // compat_14___semctl // compat_14_msgctl // compat_14_shmctl // compat_16___sigaction14 // compat_16___sigreturn14 // compat_20_fhstatfs // compat_20_fstatfs // compat_20_getfsstat // compat_20_statfs // compat_30___fhstat30 // compat_30___fstat13 // compat_30___lstat13 // compat_30___stat13 // compat_30_fhopen // compat_30_fhstat // compat_30_fhstatvfs1 // compat_30_getdents // compat_30_getfh // compat_30_ntp_gettime // compat_30_socket // compat_40_mount // compat_43_fstat43 // compat_43_lstat43 // compat_43_oaccept // compat_43_ocreat // compat_43_oftruncate // compat_43_ogetdirentries // compat_43_ogetdtablesize // compat_43_ogethostid // compat_43_ogethostname // compat_43_ogetkerninfo // compat_43_ogetpagesize // compat_43_ogetpeername // compat_43_ogetrlimit // compat_43_ogetsockname // compat_43_okillpg // compat_43_olseek // compat_43_ommap // compat_43_oquota // compat_43_orecv // compat_43_orecvfrom // compat_43_orecvmsg // compat_43_osend // compat_43_osendmsg // compat_43_osethostid // compat_43_osethostname // compat_43_osetrlimit // compat_43_osigblock // compat_43_osigsetmask // compat_43_osigstack // compat_43_osigvec // compat_43_otruncate // compat_43_owait // compat_43_stat43 // execve // extattr_delete_fd // extattr_delete_file // extattr_delete_link // extattr_get_fd // extattr_get_file // extattr_get_link // extattr_list_fd // extattr_list_file // extattr_list_link // extattr_set_fd // extattr_set_file // extattr_set_link // extattrctl // fchroot // fdatasync // fgetxattr // fktrace // flistxattr // fork // fremovexattr // fsetxattr // fstatvfs1 // fsync_range // getcontext // getitimer // getvfsstat // getxattr // ioctl // ktrace // lchflags // lchmod // lfs_bmapv // lfs_markv // lfs_segclean // lfs_segwait // lgetxattr // lio_listio // listxattr // llistxattr // lremovexattr // lseek // lsetxattr // lutimes // madvise // mincore // minherit // modctl // mq_close // mq_getattr // mq_notify // mq_open // mq_receive // mq_send // mq_setattr // mq_timedreceive // mq_timedsend // mq_unlink // mremap // msgget // msgrcv // msgsnd // nfssvc // ntp_adjtime // pmc_control // pmc_get_info // poll // pollts // preadv // profil // pselect // pset_assign // pset_create // pset_destroy // ptrace // pwritev // quotactl // rasctl // readv // reboot // removexattr // sa_enable // sa_preempt // sa_register // sa_setconcurrency // sa_stacks // sa_yield // sbrk // sched_yield // semconfig // semget // semop // setcontext // setitimer // setxattr // shmat // shmdt // shmget // sstk // statvfs1 // swapctl // sysarch // syscall // timer_create // timer_delete // timer_getoverrun // timer_gettime // timer_settime // undelete // utrace // uuidgen // vadvise // vfork // writev lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_test.go0000644061062106075000000001130213172163421025603 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux package unix_test import ( "io/ioutil" "os" "testing" "time" "golang.org/x/sys/unix" ) func TestFchmodat(t *testing.T) { defer chtmpdir(t)() touch(t, "file1") os.Symlink("file1", "symlink1") err := unix.Fchmodat(unix.AT_FDCWD, "symlink1", 0444, 0) if err != nil { t.Fatalf("Fchmodat: unexpected error: %v", err) } fi, err := os.Stat("file1") if err != nil { t.Fatal(err) } if fi.Mode() != 0444 { t.Errorf("Fchmodat: failed to change mode: expected %v, got %v", 0444, fi.Mode()) } err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", 0444, unix.AT_SYMLINK_NOFOLLOW) if err != unix.EOPNOTSUPP { t.Fatalf("Fchmodat: unexpected error: %v, expected EOPNOTSUPP", err) } } func TestIoctlGetInt(t *testing.T) { f, err := os.Open("/dev/random") if err != nil { t.Fatalf("failed to open device: %v", err) } defer f.Close() v, err := unix.IoctlGetInt(int(f.Fd()), unix.RNDGETENTCNT) if err != nil { t.Fatalf("failed to perform ioctl: %v", err) } t.Logf("%d bits of entropy available", v) } func TestPoll(t *testing.T) { f, cleanup := mktmpfifo(t) defer cleanup() const timeout = 100 ok := make(chan bool, 1) go func() { select { case <-time.After(10 * timeout * time.Millisecond): t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout) case <-ok: } }() fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}} n, err := unix.Poll(fds, timeout) ok <- true if err != nil { t.Errorf("Poll: unexpected error: %v", err) return } if n != 0 { t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0) return } } func TestPpoll(t *testing.T) { f, cleanup := mktmpfifo(t) defer cleanup() const timeout = 100 * time.Millisecond ok := make(chan bool, 1) go func() { select { case <-time.After(10 * timeout): t.Errorf("Ppoll: failed to timeout after %d", 10*timeout) case <-ok: } }() fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}} timeoutTs := unix.NsecToTimespec(int64(timeout)) n, err := unix.Ppoll(fds, &timeoutTs, nil) ok <- true if err != nil { t.Errorf("Ppoll: unexpected error: %v", err) return } if n != 0 { t.Errorf("Ppoll: wrong number of events: got %v, expected %v", n, 0) return } } // mktmpfifo creates a temporary FIFO and provides a cleanup function. func mktmpfifo(t *testing.T) (*os.File, func()) { err := unix.Mkfifo("fifo", 0666) if err != nil { t.Fatalf("mktmpfifo: failed to create FIFO: %v", err) } f, err := os.OpenFile("fifo", os.O_RDWR, 0666) if err != nil { os.Remove("fifo") t.Fatalf("mktmpfifo: failed to open FIFO: %v", err) } return f, func() { f.Close() os.Remove("fifo") } } func TestTime(t *testing.T) { var ut unix.Time_t ut2, err := unix.Time(&ut) if err != nil { t.Fatalf("Time: %v", err) } if ut != ut2 { t.Errorf("Time: return value %v should be equal to argument %v", ut2, ut) } var now time.Time for i := 0; i < 10; i++ { ut, err = unix.Time(nil) if err != nil { t.Fatalf("Time: %v", err) } now = time.Now() if int64(ut) == now.Unix() { return } } t.Errorf("Time: return value %v should be nearly equal to time.Now().Unix() %v", ut, now.Unix()) } func TestUtime(t *testing.T) { defer chtmpdir(t)() touch(t, "file1") buf := &unix.Utimbuf{ Modtime: 12345, } err := unix.Utime("file1", buf) if err != nil { t.Fatalf("Utime: %v", err) } fi, err := os.Stat("file1") if err != nil { t.Fatal(err) } if fi.ModTime().Unix() != 12345 { t.Errorf("Utime: failed to change modtime: expected %v, got %v", 12345, fi.ModTime().Unix()) } } func TestGetrlimit(t *testing.T) { var rlim unix.Rlimit err := unix.Getrlimit(unix.RLIMIT_AS, &rlim) if err != nil { t.Fatalf("Getrlimit: %v", err) } } func TestSelect(t *testing.T) { _, err := unix.Select(0, nil, nil, nil, &unix.Timeval{0, 0}) if err != nil { t.Fatalf("Select: %v", err) } } // utilities taken from os/os_test.go func touch(t *testing.T, name string) { f, err := os.Create(name) if err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } } // chtmpdir changes the working directory to a new temporary directory and // provides a cleanup function. Used when PWD is read-only. func chtmpdir(t *testing.T) func() { oldwd, err := os.Getwd() if err != nil { t.Fatalf("chtmpdir: %v", err) } d, err := ioutil.TempDir("", "test") if err != nil { t.Fatalf("chtmpdir: %v", err) } if err := os.Chdir(d); err != nil { t.Fatalf("chtmpdir: %v", err) } return func() { if err := os.Chdir(oldwd); err != nil { t.Fatalf("chtmpdir: %v", err) } os.RemoveAll(d) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_sparc64.go0000644061062106075000000001177313172163421026122 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build sparc64,linux package unix //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Dup2(oldfd int, newfd int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) //sysnb Getuid() (uid int) //sysnb InotifyInit() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Pause() (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) func Ioperm(from int, num int, on int) (err error) { return ENOSYS } func Iopl(level int) (err error) { return ENOSYS } //sysnb Gettimeofday(tv *Timeval) (err error) func Time(t *Time_t) (tt Time_t, err error) { var tv Timeval err = Gettimeofday(&tv) if err != nil { return 0, err } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } //sys Utime(path string, buf *Utimbuf) (err error) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = nsec / 1e9 tv.Usec = int32(nsec % 1e9 / 1e3) return } func (r *PtraceRegs) PC() uint64 { return r.Tpc } func (r *PtraceRegs) SetPC(pc uint64) { r.Tpc = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint64(length) } //sysnb pipe(p *[2]_C_int) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe(&pp) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_s390x.go0000644061062106075000000002333713172163421025525 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build s390x,linux package unix import ( "unsafe" ) //sys Dup2(oldfd int, newfd int) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) //sysnb Getuid() (uid int) //sysnb InotifyInit() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Pause() (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sysnb Gettimeofday(tv *Timeval) (err error) func Time(t *Time_t) (tt Time_t, err error) { var tv Timeval err = Gettimeofday(&tv) if err != nil { return 0, err } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } //sys Utime(path string, buf *Utimbuf) (err error) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = nsec / 1e9 tv.Usec = nsec % 1e9 / 1e3 return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, 0) // pipe2 is the same as pipe when flags are set to 0. p[0] = int(pp[0]) p[1] = int(pp[1]) return } func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } func Ioperm(from int, num int, on int) (err error) { return ENOSYS } func Iopl(level int) (err error) { return ENOSYS } func (r *PtraceRegs) PC() uint64 { return r.Psw.Addr } func (r *PtraceRegs) SetPC(pc uint64) { r.Psw.Addr = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint64(length) } // Linux on s390x uses the old mmap interface, which requires arguments to be passed in a struct. // mmap2 also requires arguments to be passed in a struct; it is currently not exposed in . func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { mmap_args := [6]uintptr{addr, length, uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)} r0, _, e1 := Syscall(SYS_MMAP, uintptr(unsafe.Pointer(&mmap_args[0])), 0, 0) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // On s390x Linux, all the socket calls go through an extra indirection. // The arguments to the underlying system call (SYS_SOCKETCALL) are the // number below and a pointer to an array of uintptr. const ( // see linux/net.h netSocket = 1 netBind = 2 netConnect = 3 netListen = 4 netAccept = 5 netGetSockName = 6 netGetPeerName = 7 netSocketPair = 8 netSend = 9 netRecv = 10 netSendTo = 11 netRecvFrom = 12 netShutdown = 13 netSetSockOpt = 14 netGetSockOpt = 15 netSendMsg = 16 netRecvMsg = 17 netAccept4 = 18 netRecvMMsg = 19 netSendMMsg = 20 ) func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (int, error) { args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))} fd, _, err := Syscall(SYS_SOCKETCALL, netAccept, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return 0, err } return int(fd), nil } func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (int, error) { args := [4]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags)} fd, _, err := Syscall(SYS_SOCKETCALL, netAccept4, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return 0, err } return int(fd), nil } func getsockname(s int, rsa *RawSockaddrAny, addrlen *_Socklen) error { args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))} _, _, err := RawSyscall(SYS_SOCKETCALL, netGetSockName, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func getpeername(s int, rsa *RawSockaddrAny, addrlen *_Socklen) error { args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))} _, _, err := RawSyscall(SYS_SOCKETCALL, netGetPeerName, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func socketpair(domain int, typ int, flags int, fd *[2]int32) error { args := [4]uintptr{uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd))} _, _, err := RawSyscall(SYS_SOCKETCALL, netSocketPair, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func bind(s int, addr unsafe.Pointer, addrlen _Socklen) error { args := [3]uintptr{uintptr(s), uintptr(addr), uintptr(addrlen)} _, _, err := Syscall(SYS_SOCKETCALL, netBind, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func connect(s int, addr unsafe.Pointer, addrlen _Socklen) error { args := [3]uintptr{uintptr(s), uintptr(addr), uintptr(addrlen)} _, _, err := Syscall(SYS_SOCKETCALL, netConnect, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func socket(domain int, typ int, proto int) (int, error) { args := [3]uintptr{uintptr(domain), uintptr(typ), uintptr(proto)} fd, _, err := RawSyscall(SYS_SOCKETCALL, netSocket, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return 0, err } return int(fd), nil } func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) error { args := [5]uintptr{uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen))} _, _, err := Syscall(SYS_SOCKETCALL, netGetSockOpt, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) error { args := [4]uintptr{uintptr(s), uintptr(level), uintptr(name), uintptr(val)} _, _, err := Syscall(SYS_SOCKETCALL, netSetSockOpt, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func recvfrom(s int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (int, error) { var base uintptr if len(p) > 0 { base = uintptr(unsafe.Pointer(&p[0])) } args := [6]uintptr{uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))} n, _, err := Syscall(SYS_SOCKETCALL, netRecvFrom, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return 0, err } return int(n), nil } func sendto(s int, p []byte, flags int, to unsafe.Pointer, addrlen _Socklen) error { var base uintptr if len(p) > 0 { base = uintptr(unsafe.Pointer(&p[0])) } args := [6]uintptr{uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(to), uintptr(addrlen)} _, _, err := Syscall(SYS_SOCKETCALL, netSendTo, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func recvmsg(s int, msg *Msghdr, flags int) (int, error) { args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)} n, _, err := Syscall(SYS_SOCKETCALL, netRecvMsg, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return 0, err } return int(n), nil } func sendmsg(s int, msg *Msghdr, flags int) (int, error) { args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)} n, _, err := Syscall(SYS_SOCKETCALL, netSendMsg, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return 0, err } return int(n), nil } func Listen(s int, n int) error { args := [2]uintptr{uintptr(s), uintptr(n)} _, _, err := Syscall(SYS_SOCKETCALL, netListen, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } func Shutdown(s, how int) error { args := [2]uintptr{uintptr(s), uintptr(how)} _, _, err := Syscall(SYS_SOCKETCALL, netShutdown, uintptr(unsafe.Pointer(&args)), 0) if err != 0 { return err } return nil } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_ppc64x.go0000644061062106075000000001160413172163421025755 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build ppc64 ppc64le package unix //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Dup2(oldfd int, newfd int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) = SYS_UGETRLIMIT //sysnb Getuid() (uid int) //sysnb InotifyInit() (fd int, err error) //sys Ioperm(from int, num int, on int) (err error) //sys Iopl(level int) (err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Pause() (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) = SYS_SYNC_FILE_RANGE2 //sys Truncate(path string, length int64) (err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Time(t *Time_t) (tt Time_t, err error) //sys Utime(path string, buf *Utimbuf) (err error) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = nsec / 1e9 tv.Usec = nsec % 1e9 / 1e3 return } func (r *PtraceRegs) PC() uint64 { return r.Nip } func (r *PtraceRegs) SetPC(pc uint64) { r.Nip = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint64(length) } //sysnb pipe(p *[2]_C_int) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe(&pp) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_mipsx.go0000644061062106075000000001555613172163421026003 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build mips mipsle package unix import ( "syscall" "unsafe" ) func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) //sys Dup2(oldfd int, newfd int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getuid() (uid int) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sysnb InotifyInit() (fd int, err error) //sys Ioperm(from int, num int, on int) (err error) //sys Iopl(level int) (err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Time(t *Time_t) (tt Time_t, err error) //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Utime(path string, buf *Utimbuf) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Pause() (err error) func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = errnoErr(e) } return } func Statfs(path string, buf *Statfs_t) (err error) { p, err := BytePtrFromString(path) if err != nil { return err } _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(p)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = errnoErr(e) } return } func Seek(fd int, offset int64, whence int) (off int64, err error) { _, _, e := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offset>>32), uintptr(offset), uintptr(unsafe.Pointer(&off)), uintptr(whence), 0) if e != 0 { err = errnoErr(e) } return } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = int32(nsec / 1e9) tv.Usec = int32(nsec % 1e9 / 1e3) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, 0) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { page := uintptr(offset / 4096) if offset != int64(page)*4096 { return 0, EINVAL } return mmap2(addr, length, prot, flags, fd, page) } const rlimInf32 = ^uint32(0) const rlimInf64 = ^uint64(0) type rlimit32 struct { Cur uint32 Max uint32 } //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT func Getrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, nil, rlim) if err != ENOSYS { return err } rl := rlimit32{} err = getrlimit(resource, &rl) if err != nil { return } if rl.Cur == rlimInf32 { rlim.Cur = rlimInf64 } else { rlim.Cur = uint64(rl.Cur) } if rl.Max == rlimInf32 { rlim.Max = rlimInf64 } else { rlim.Max = uint64(rl.Max) } return } //sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT func Setrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, rlim, nil) if err != ENOSYS { return err } rl := rlimit32{} if rlim.Cur == rlimInf64 { rl.Cur = rlimInf32 } else if rlim.Cur < uint64(rlimInf32) { rl.Cur = uint32(rlim.Cur) } else { return EINVAL } if rlim.Max == rlimInf64 { rl.Max = rlimInf32 } else if rlim.Max < uint64(rlimInf32) { rl.Max = uint32(rlim.Max) } else { return EINVAL } return setrlimit(resource, &rl) } func (r *PtraceRegs) PC() uint64 { return r.Epc } func (r *PtraceRegs) SetPC(pc uint64) { r.Epc = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_mips64x.go0000644061062106075000000001421713172163421026146 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build mips64 mips64le package unix //sys Dup2(oldfd int, newfd int) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) //sysnb Getuid() (uid int) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) //sys Pause() (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { ts := Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} return Pselect(nfd, r, w, e, &ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) //sysnb Gettimeofday(tv *Timeval) (err error) func Time(t *Time_t) (tt Time_t, err error) { var tv Timeval err = Gettimeofday(&tv) if err != nil { return 0, err } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } //sys Utime(path string, buf *Utimbuf) (err error) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = nsec / 1e9 tv.Usec = nsec % 1e9 / 1e3 return } func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, 0) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } func Ioperm(from int, num int, on int) (err error) { return ENOSYS } func Iopl(level int) (err error) { return ENOSYS } type stat_t struct { Dev uint32 Pad0 [3]int32 Ino uint64 Mode uint32 Nlink uint32 Uid uint32 Gid uint32 Rdev uint32 Pad1 [3]uint32 Size int64 Atime uint32 Atime_nsec uint32 Mtime uint32 Mtime_nsec uint32 Ctime uint32 Ctime_nsec uint32 Blksize uint32 Pad2 uint32 Blocks int64 } //sys fstat(fd int, st *stat_t) (err error) //sys lstat(path string, st *stat_t) (err error) //sys stat(path string, st *stat_t) (err error) func Fstat(fd int, s *Stat_t) (err error) { st := &stat_t{} err = fstat(fd, st) fillStat_t(s, st) return } func Lstat(path string, s *Stat_t) (err error) { st := &stat_t{} err = lstat(path, st) fillStat_t(s, st) return } func Stat(path string, s *Stat_t) (err error) { st := &stat_t{} err = stat(path, st) fillStat_t(s, st) return } func fillStat_t(s *Stat_t, st *stat_t) { s.Dev = st.Dev s.Ino = st.Ino s.Mode = st.Mode s.Nlink = st.Nlink s.Uid = st.Uid s.Gid = st.Gid s.Rdev = st.Rdev s.Size = st.Size s.Atim = Timespec{int64(st.Atime), int64(st.Atime_nsec)} s.Mtim = Timespec{int64(st.Mtime), int64(st.Mtime_nsec)} s.Ctim = Timespec{int64(st.Ctime), int64(st.Ctime_nsec)} s.Blksize = st.Blksize s.Blocks = st.Blocks } func (r *PtraceRegs) PC() uint64 { return r.Epc } func (r *PtraceRegs) SetPC(pc uint64) { r.Epc = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint64(length) } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_arm64.go0000644061062106075000000001360613172163421025566 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm64,linux package unix //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) //sysnb Getuid() (uid int) //sys Listen(s int, n int) (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { ts := Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} return Pselect(nfd, r, w, e, &ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) func Stat(path string, stat *Stat_t) (err error) { return Fstatat(AT_FDCWD, path, stat, 0) } func Lchown(path string, uid int, gid int) (err error) { return Fchownat(AT_FDCWD, path, uid, gid, AT_SYMLINK_NOFOLLOW) } func Lstat(path string, stat *Stat_t) (err error) { return Fstatat(AT_FDCWD, path, stat, AT_SYMLINK_NOFOLLOW) } //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) //sysnb Gettimeofday(tv *Timeval) (err error) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = nsec / 1e9 tv.Usec = nsec % 1e9 / 1e3 return } func Time(t *Time_t) (Time_t, error) { var tv Timeval err := Gettimeofday(&tv) if err != nil { return 0, err } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } func Utime(path string, buf *Utimbuf) error { tv := []Timeval{ {Sec: buf.Actime}, {Sec: buf.Modtime}, } return Utimes(path, tv) } func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, 0) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } func (r *PtraceRegs) PC() uint64 { return r.Pc } func (r *PtraceRegs) SetPC(pc uint64) { r.Pc = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint64(length) } func InotifyInit() (fd int, err error) { return InotifyInit1(0) } func Dup2(oldfd int, newfd int) (err error) { return Dup3(oldfd, newfd, 0) } func Pause() (err error) { _, _, e1 := Syscall6(SYS_PPOLL, 0, 0, 0, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // TODO(dfc): constants that should be in zsysnum_linux_arm64.go, remove // these when the deprecated syscalls that the syscall package relies on // are removed. const ( SYS_GETPGRP = 1060 SYS_UTIMES = 1037 SYS_FUTIMESAT = 1066 SYS_PAUSE = 1061 SYS_USTAT = 1070 SYS_UTIME = 1063 SYS_LCHOWN = 1032 SYS_TIME = 1062 SYS_EPOLL_CREATE = 1042 SYS_EPOLL_WAIT = 1069 ) func Poll(fds []PollFd, timeout int) (n int, err error) { var ts *Timespec if timeout >= 0 { ts = new(Timespec) *ts = NsecToTimespec(int64(timeout) * 1e6) } if len(fds) == 0 { return ppoll(nil, 0, ts, nil) } return ppoll(&fds[0], len(fds), ts, nil) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_arm.go0000644061062106075000000001710413172163421025411 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm,linux package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = int32(nsec / 1e9) tv.Usec = int32(nsec % 1e9 / 1e3) return } func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, 0) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } // Underlying system call writes to newoffset via pointer. // Implemented in assembly to avoid allocation. func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno) func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { newoffset, errno := seek(fd, offset, whence) if errno != 0 { return 0, errno } return newoffset, nil } //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32 //sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32 //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sysnb socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) // 64-bit file system and 32-bit uid calls // (16-bit uid calls are not always supported in newer kernels) //sys Dup2(oldfd int, newfd int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sysnb Getegid() (egid int) = SYS_GETEGID32 //sysnb Geteuid() (euid int) = SYS_GETEUID32 //sysnb Getgid() (gid int) = SYS_GETGID32 //sysnb Getuid() (uid int) = SYS_GETUID32 //sysnb InotifyInit() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32 //sys Listen(s int, n int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT //sys Setfsgid(gid int) (err error) = SYS_SETFSGID32 //sys Setfsuid(uid int) (err error) = SYS_SETFSUID32 //sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32 //sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32 //sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32 //sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32 //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 // Vsyscalls on amd64. //sysnb Gettimeofday(tv *Timeval) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Pause() (err error) func Time(t *Time_t) (Time_t, error) { var tv Timeval err := Gettimeofday(&tv) if err != nil { return 0, err } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } func Utime(path string, buf *Utimbuf) error { tv := []Timeval{ {Sec: buf.Actime}, {Sec: buf.Modtime}, } return Utimes(path, tv) } //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_ARM_FADVISE64_64, uintptr(fd), uintptr(advice), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } //sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = e } return } func Statfs(path string, buf *Statfs_t) (err error) { pathp, err := BytePtrFromString(path) if err != nil { return err } _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = e } return } func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { page := uintptr(offset / 4096) if offset != int64(page)*4096 { return 0, EINVAL } return mmap2(addr, length, prot, flags, fd, page) } type rlimit32 struct { Cur uint32 Max uint32 } //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT const rlimInf32 = ^uint32(0) const rlimInf64 = ^uint64(0) func Getrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, nil, rlim) if err != ENOSYS { return err } rl := rlimit32{} err = getrlimit(resource, &rl) if err != nil { return } if rl.Cur == rlimInf32 { rlim.Cur = rlimInf64 } else { rlim.Cur = uint64(rl.Cur) } if rl.Max == rlimInf32 { rlim.Max = rlimInf64 } else { rlim.Max = uint64(rl.Max) } return } //sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT func Setrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, rlim, nil) if err != ENOSYS { return err } rl := rlimit32{} if rlim.Cur == rlimInf64 { rl.Cur = rlimInf32 } else if rlim.Cur < uint64(rlimInf32) { rl.Cur = uint32(rlim.Cur) } else { return EINVAL } if rlim.Max == rlimInf64 { rl.Max = rlimInf32 } else if rlim.Max < uint64(rlimInf32) { rl.Max = uint32(rlim.Max) } else { return EINVAL } return setrlimit(resource, &rl) } func (r *PtraceRegs) PC() uint64 { return uint64(r.Uregs[15]) } func (r *PtraceRegs) SetPC(pc uint64) { r.Uregs[15] = uint32(pc) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_amd64_gc.go0000644061062106075000000000045113172163421026213 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,linux // +build !gccgo package unix import "syscall" //go:noescape func gettimeofday(tv *Timeval) (err syscall.Errno) lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_amd64.go0000644061062106075000000001216613172163421025550 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,linux package unix //sys Dup2(oldfd int, newfd int) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) //sysnb Getuid() (uid int) //sysnb InotifyInit() (fd int, err error) //sys Ioperm(from int, num int, on int) (err error) //sys Iopl(level int) (err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Pause() (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) func Gettimeofday(tv *Timeval) (err error) { errno := gettimeofday(tv) if errno != 0 { return errno } return nil } func Time(t *Time_t) (tt Time_t, err error) { var tv Timeval errno := gettimeofday(&tv) if errno != 0 { return 0, errno } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } //sys Utime(path string, buf *Utimbuf) (err error) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = nsec / 1e9 tv.Usec = nsec % 1e9 / 1e3 return } //sysnb pipe(p *[2]_C_int) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe(&pp) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } func (r *PtraceRegs) PC() uint64 { return r.Rip } func (r *PtraceRegs) SetPC(pc uint64) { r.Rip = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint64(length) } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux_386.go0000644061062106075000000002542213172163421025154 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // TODO(rsc): Rewrite all nn(SP) references into name+(nn-8)(FP) // so that go vet can check that they are correct. // +build 386,linux package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = int32(nsec / 1e9) tv.Usec = int32(nsec % 1e9 / 1e3) return } //sysnb pipe(p *[2]_C_int) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe(&pp) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } // 64-bit file system and 32-bit uid calls // (386 default is 32-bit file system and 16-bit uid). //sys Dup2(oldfd int, newfd int) (err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64_64 //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 //sysnb Getegid() (egid int) = SYS_GETEGID32 //sysnb Geteuid() (euid int) = SYS_GETEUID32 //sysnb Getgid() (gid int) = SYS_GETGID32 //sysnb Getuid() (uid int) = SYS_GETUID32 //sysnb InotifyInit() (fd int, err error) //sys Ioperm(from int, num int, on int) (err error) //sys Iopl(level int) (err error) //sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32 //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 //sys Setfsgid(gid int) (err error) = SYS_SETFSGID32 //sys Setfsuid(uid int) (err error) = SYS_SETFSUID32 //sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32 //sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32 //sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32 //sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32 //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32 //sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32 //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT //sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Pause() (err error) func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { page := uintptr(offset / 4096) if offset != int64(page)*4096 { return 0, EINVAL } return mmap2(addr, length, prot, flags, fd, page) } type rlimit32 struct { Cur uint32 Max uint32 } //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT const rlimInf32 = ^uint32(0) const rlimInf64 = ^uint64(0) func Getrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, nil, rlim) if err != ENOSYS { return err } rl := rlimit32{} err = getrlimit(resource, &rl) if err != nil { return } if rl.Cur == rlimInf32 { rlim.Cur = rlimInf64 } else { rlim.Cur = uint64(rl.Cur) } if rl.Max == rlimInf32 { rlim.Max = rlimInf64 } else { rlim.Max = uint64(rl.Max) } return } //sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT func Setrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, rlim, nil) if err != ENOSYS { return err } rl := rlimit32{} if rlim.Cur == rlimInf64 { rl.Cur = rlimInf32 } else if rlim.Cur < uint64(rlimInf32) { rl.Cur = uint32(rlim.Cur) } else { return EINVAL } if rlim.Max == rlimInf64 { rl.Max = rlimInf32 } else if rlim.Max < uint64(rlimInf32) { rl.Max = uint32(rlim.Max) } else { return EINVAL } return setrlimit(resource, &rl) } // Underlying system call writes to newoffset via pointer. // Implemented in assembly to avoid allocation. func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno) func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { newoffset, errno := seek(fd, offset, whence) if errno != 0 { return 0, errno } return newoffset, nil } // Vsyscalls on amd64. //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Time(t *Time_t) (tt Time_t, err error) //sys Utime(path string, buf *Utimbuf) (err error) // On x86 Linux, all the socket calls go through an extra indirection, // I think because the 5-register system call interface can't handle // the 6-argument calls like sendto and recvfrom. Instead the // arguments to the underlying system call are the number below // and a pointer to an array of uintptr. We hide the pointer in the // socketcall assembly to avoid allocation on every system call. const ( // see linux/net.h _SOCKET = 1 _BIND = 2 _CONNECT = 3 _LISTEN = 4 _ACCEPT = 5 _GETSOCKNAME = 6 _GETPEERNAME = 7 _SOCKETPAIR = 8 _SEND = 9 _RECV = 10 _SENDTO = 11 _RECVFROM = 12 _SHUTDOWN = 13 _SETSOCKOPT = 14 _GETSOCKOPT = 15 _SENDMSG = 16 _RECVMSG = 17 _ACCEPT4 = 18 _RECVMMSG = 19 _SENDMMSG = 20 ) func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno) func rawsocketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno) func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { fd, e := socketcall(_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) if e != 0 { err = e } return } func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { fd, e := socketcall(_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) if e != 0 { err = e } return } func getsockname(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, e := rawsocketcall(_GETSOCKNAME, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) if e != 0 { err = e } return } func getpeername(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, e := rawsocketcall(_GETPEERNAME, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) if e != 0 { err = e } return } func socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) { _, e := rawsocketcall(_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd)), 0, 0) if e != 0 { err = e } return } func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, e := socketcall(_BIND, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) if e != 0 { err = e } return } func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, e := socketcall(_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) if e != 0 { err = e } return } func socket(domain int, typ int, proto int) (fd int, err error) { fd, e := rawsocketcall(_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto), 0, 0, 0) if e != 0 { err = e } return } func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, e := socketcall(_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e != 0 { err = e } return } func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, e := socketcall(_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), vallen, 0) if e != 0 { err = e } return } func recvfrom(s int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var base uintptr if len(p) > 0 { base = uintptr(unsafe.Pointer(&p[0])) } n, e := socketcall(_RECVFROM, uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) if e != 0 { err = e } return } func sendto(s int, p []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var base uintptr if len(p) > 0 { base = uintptr(unsafe.Pointer(&p[0])) } _, e := socketcall(_SENDTO, uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e != 0 { err = e } return } func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { n, e := socketcall(_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) if e != 0 { err = e } return } func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { n, e := socketcall(_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) if e != 0 { err = e } return } func Listen(s int, n int) (err error) { _, e := socketcall(_LISTEN, uintptr(s), uintptr(n), 0, 0, 0, 0) if e != 0 { err = e } return } func Shutdown(s, how int) (err error) { _, e := socketcall(_SHUTDOWN, uintptr(s), uintptr(how), 0, 0, 0, 0) if e != 0 { err = e } return } func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = e } return } func Statfs(path string, buf *Statfs_t) (err error) { pathp, err := BytePtrFromString(path) if err != nil { return err } _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = e } return } func (r *PtraceRegs) PC() uint64 { return uint64(uint32(r.Eip)) } func (r *PtraceRegs) SetPC(pc uint64) { r.Eip = int32(pc) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_linux.go0000644061062106075000000012254113172163421024554 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Linux system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and // wrap it in our own nicer implementation. package unix import ( "syscall" "unsafe" ) /* * Wrapped */ func Access(path string, mode uint32) (err error) { return Faccessat(AT_FDCWD, path, mode, 0) } func Chmod(path string, mode uint32) (err error) { return Fchmodat(AT_FDCWD, path, mode, 0) } func Chown(path string, uid int, gid int) (err error) { return Fchownat(AT_FDCWD, path, uid, gid, 0) } func Creat(path string, mode uint32) (fd int, err error) { return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode) } //sys fchmodat(dirfd int, path string, mode uint32) (err error) func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { // Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior // and check the flags. Otherwise the mode would be applied to the symlink // destination which is not what the user expects. if flags&^AT_SYMLINK_NOFOLLOW != 0 { return EINVAL } else if flags&AT_SYMLINK_NOFOLLOW != 0 { return EOPNOTSUPP } return fchmodat(dirfd, path, mode) } //sys ioctl(fd int, req uint, arg uintptr) (err error) // ioctl itself should not be exposed directly, but additional get/set // functions for specific types are permissible. // IoctlSetInt performs an ioctl operation which sets an integer value // on fd, using the specified request number. func IoctlSetInt(fd int, req uint, value int) error { return ioctl(fd, req, uintptr(value)) } func IoctlSetWinsize(fd int, req uint, value *Winsize) error { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermios(fd int, req uint, value *Termios) error { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } // IoctlGetInt performs an ioctl operation which gets an integer value // from fd, using the specified request number. func IoctlGetInt(fd int, req uint) (int, error) { var value int err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return value, err } func IoctlGetWinsize(fd int, req uint) (*Winsize, error) { var value Winsize err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermios(fd int, req uint) (*Termios, error) { var value Termios err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } //sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) func Link(oldpath string, newpath string) (err error) { return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0) } func Mkdir(path string, mode uint32) (err error) { return Mkdirat(AT_FDCWD, path, mode) } func Mknod(path string, mode uint32, dev int) (err error) { return Mknodat(AT_FDCWD, path, mode, dev) } func Open(path string, mode int, perm uint32) (fd int, err error) { return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm) } //sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { return openat(dirfd, path, flags|O_LARGEFILE, mode) } //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { if len(fds) == 0 { return ppoll(nil, 0, timeout, sigmask) } return ppoll(&fds[0], len(fds), timeout, sigmask) } //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error) func Readlink(path string, buf []byte) (n int, err error) { return Readlinkat(AT_FDCWD, path, buf) } func Rename(oldpath string, newpath string) (err error) { return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath) } func Rmdir(path string) error { return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR) } //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) func Symlink(oldpath string, newpath string) (err error) { return Symlinkat(oldpath, AT_FDCWD, newpath) } func Unlink(path string) error { return Unlinkat(AT_FDCWD, path, 0) } //sys Unlinkat(dirfd int, path string, flags int) (err error) //sys utimes(path string, times *[2]Timeval) (err error) func Utimes(path string, tv []Timeval) error { if tv == nil { err := utimensat(AT_FDCWD, path, nil, 0) if err != ENOSYS { return err } return utimes(path, nil) } if len(tv) != 2 { return EINVAL } var ts [2]Timespec ts[0] = NsecToTimespec(TimevalToNsec(tv[0])) ts[1] = NsecToTimespec(TimevalToNsec(tv[1])) err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) if err != ENOSYS { return err } return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) func UtimesNano(path string, ts []Timespec) error { if ts == nil { err := utimensat(AT_FDCWD, path, nil, 0) if err != ENOSYS { return err } return utimes(path, nil) } if len(ts) != 2 { return EINVAL } err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) if err != ENOSYS { return err } // If the utimensat syscall isn't available (utimensat was added to Linux // in 2.6.22, Released, 8 July 2007) then fall back to utimes var tv [2]Timeval for i := 0; i < 2; i++ { tv[i] = NsecToTimeval(TimespecToNsec(ts[i])) } return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { if ts == nil { return utimensat(dirfd, path, nil, flags) } if len(ts) != 2 { return EINVAL } return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) } //sys futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) func Futimesat(dirfd int, path string, tv []Timeval) error { pathp, err := BytePtrFromString(path) if err != nil { return err } if tv == nil { return futimesat(dirfd, pathp, nil) } if len(tv) != 2 { return EINVAL } return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } func Futimes(fd int, tv []Timeval) (err error) { // Believe it or not, this is the best we can do on Linux // (and is what glibc does). return Utimes("/proc/self/fd/"+itoa(fd), tv) } const ImplementsGetwd = true //sys Getcwd(buf []byte) (n int, err error) func Getwd() (wd string, err error) { var buf [PathMax]byte n, err := Getcwd(buf[0:]) if err != nil { return "", err } // Getcwd returns the number of bytes written to buf, including the NUL. if n < 1 || n > len(buf) || buf[n-1] != 0 { return "", EINVAL } return string(buf[0 : n-1]), nil } func Getgroups() (gids []int, err error) { n, err := getgroups(0, nil) if err != nil { return nil, err } if n == 0 { return nil, nil } // Sanity check group count. Max is 1<<16 on Linux. if n < 0 || n > 1<<20 { return nil, EINVAL } a := make([]_Gid_t, n) n, err = getgroups(n, &a[0]) if err != nil { return nil, err } gids = make([]int, n) for i, v := range a[0:n] { gids[i] = int(v) } return } func Setgroups(gids []int) (err error) { if len(gids) == 0 { return setgroups(0, nil) } a := make([]_Gid_t, len(gids)) for i, v := range gids { a[i] = _Gid_t(v) } return setgroups(len(a), &a[0]) } type WaitStatus uint32 // Wait status is 7 bits at bottom, either 0 (exited), // 0x7F (stopped), or a signal number that caused an exit. // The 0x80 bit is whether there was a core dump. // An extra number (exit code, signal causing a stop) // is in the high bits. At least that's the idea. // There are various irregularities. For example, the // "continued" status is 0xFFFF, distinguishing itself // from stopped via the core dump bit. const ( mask = 0x7F core = 0x80 exited = 0x00 stopped = 0x7F shift = 8 ) func (w WaitStatus) Exited() bool { return w&mask == exited } func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited } func (w WaitStatus) Stopped() bool { return w&0xFF == stopped } func (w WaitStatus) Continued() bool { return w == 0xFFFF } func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } func (w WaitStatus) ExitStatus() int { if !w.Exited() { return -1 } return int(w>>shift) & 0xFF } func (w WaitStatus) Signal() syscall.Signal { if !w.Signaled() { return -1 } return syscall.Signal(w & mask) } func (w WaitStatus) StopSignal() syscall.Signal { if !w.Stopped() { return -1 } return syscall.Signal(w>>shift) & 0xFF } func (w WaitStatus) TrapCause() int { if w.StopSignal() != SIGTRAP { return -1 } return int(w>>shift) >> 8 } //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { var status _C_int wpid, err = wait4(pid, &status, options, rusage) if wstatus != nil { *wstatus = WaitStatus(status) } return } func Mkfifo(path string, mode uint32) error { return Mknod(path, mode|S_IFIFO, 0) } func Mkfifoat(dirfd int, path string, mode uint32) error { return Mknodat(dirfd, path, mode|S_IFIFO, 0) } func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL } sa.raw.Family = AF_INET p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL } sa.raw.Family = AF_INET6 p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) sa.raw.Scope_id = sa.ZoneId for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { name := sa.Name n := len(name) if n >= len(sa.raw.Path) { return nil, 0, EINVAL } sa.raw.Family = AF_UNIX for i := 0; i < n; i++ { sa.raw.Path[i] = int8(name[i]) } // length is family (uint16), name, NUL. sl := _Socklen(2) if n > 0 { sl += _Socklen(n) + 1 } if sa.raw.Path[0] == '@' { sa.raw.Path[0] = 0 // Don't count trailing NUL for abstract address. sl-- } return unsafe.Pointer(&sa.raw), sl, nil } type SockaddrLinklayer struct { Protocol uint16 Ifindex int Hatype uint16 Pkttype uint8 Halen uint8 Addr [8]byte raw RawSockaddrLinklayer } func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff { return nil, 0, EINVAL } sa.raw.Family = AF_PACKET sa.raw.Protocol = sa.Protocol sa.raw.Ifindex = int32(sa.Ifindex) sa.raw.Hatype = sa.Hatype sa.raw.Pkttype = sa.Pkttype sa.raw.Halen = sa.Halen for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil } type SockaddrNetlink struct { Family uint16 Pad uint16 Pid uint32 Groups uint32 raw RawSockaddrNetlink } func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) { sa.raw.Family = AF_NETLINK sa.raw.Pad = sa.Pad sa.raw.Pid = sa.Pid sa.raw.Groups = sa.Groups return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil } type SockaddrHCI struct { Dev uint16 Channel uint16 raw RawSockaddrHCI } func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) { sa.raw.Family = AF_BLUETOOTH sa.raw.Dev = sa.Dev sa.raw.Channel = sa.Channel return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil } // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets. // The RxID and TxID fields are used for transport protocol addressing in // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with // zero values for CAN_RAW and CAN_BCM sockets as they have no meaning. // // The SockaddrCAN struct must be bound to the socket file descriptor // using Bind before the CAN socket can be used. // // // Read one raw CAN frame // fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW) // addr := &SockaddrCAN{Ifindex: index} // Bind(fd, addr) // frame := make([]byte, 16) // Read(fd, frame) // // The full SocketCAN documentation can be found in the linux kernel // archives at: https://www.kernel.org/doc/Documentation/networking/can.txt type SockaddrCAN struct { Ifindex int RxID uint32 TxID uint32 raw RawSockaddrCAN } func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff { return nil, 0, EINVAL } sa.raw.Family = AF_CAN sa.raw.Ifindex = int32(sa.Ifindex) rx := (*[4]byte)(unsafe.Pointer(&sa.RxID)) for i := 0; i < 4; i++ { sa.raw.Addr[i] = rx[i] } tx := (*[4]byte)(unsafe.Pointer(&sa.TxID)) for i := 0; i < 4; i++ { sa.raw.Addr[i+4] = tx[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil } // SockaddrALG implements the Sockaddr interface for AF_ALG type sockets. // SockaddrALG enables userspace access to the Linux kernel's cryptography // subsystem. The Type and Name fields specify which type of hash or cipher // should be used with a given socket. // // To create a file descriptor that provides access to a hash or cipher, both // Bind and Accept must be used. Once the setup process is complete, input // data can be written to the socket, processed by the kernel, and then read // back as hash output or ciphertext. // // Here is an example of using an AF_ALG socket with SHA1 hashing. // The initial socket setup process is as follows: // // // Open a socket to perform SHA1 hashing. // fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0) // addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"} // unix.Bind(fd, addr) // // Note: unix.Accept does not work at this time; must invoke accept() // // manually using unix.Syscall. // hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0) // // Once a file descriptor has been returned from Accept, it may be used to // perform SHA1 hashing. The descriptor is not safe for concurrent use, but // may be re-used repeatedly with subsequent Write and Read operations. // // When hashing a small byte slice or string, a single Write and Read may // be used: // // // Assume hashfd is already configured using the setup process. // hash := os.NewFile(hashfd, "sha1") // // Hash an input string and read the results. Each Write discards // // previous hash state. Read always reads the current state. // b := make([]byte, 20) // for i := 0; i < 2; i++ { // io.WriteString(hash, "Hello, world.") // hash.Read(b) // fmt.Println(hex.EncodeToString(b)) // } // // Output: // // 2ae01472317d1935a84797ec1983ae243fc6aa28 // // 2ae01472317d1935a84797ec1983ae243fc6aa28 // // For hashing larger byte slices, or byte streams such as those read from // a file or socket, use Sendto with MSG_MORE to instruct the kernel to update // the hash digest instead of creating a new one for a given chunk and finalizing it. // // // Assume hashfd and addr are already configured using the setup process. // hash := os.NewFile(hashfd, "sha1") // // Hash the contents of a file. // f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz") // b := make([]byte, 4096) // for { // n, err := f.Read(b) // if err == io.EOF { // break // } // unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr) // } // hash.Read(b) // fmt.Println(hex.EncodeToString(b)) // // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5 // // For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html. type SockaddrALG struct { Type string Name string Feature uint32 Mask uint32 raw RawSockaddrALG } func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) { // Leave room for NUL byte terminator. if len(sa.Type) > 13 { return nil, 0, EINVAL } if len(sa.Name) > 63 { return nil, 0, EINVAL } sa.raw.Family = AF_ALG sa.raw.Feat = sa.Feature sa.raw.Mask = sa.Mask typ, err := ByteSliceFromString(sa.Type) if err != nil { return nil, 0, err } name, err := ByteSliceFromString(sa.Name) if err != nil { return nil, 0, err } copy(sa.raw.Type[:], typ) copy(sa.raw.Name[:], name) return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil } // SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets. // SockaddrVM provides access to Linux VM sockets: a mechanism that enables // bidirectional communication between a hypervisor and its guest virtual // machines. type SockaddrVM struct { // CID and Port specify a context ID and port address for a VM socket. // Guests have a unique CID, and hosts may have a well-known CID of: // - VMADDR_CID_HYPERVISOR: refers to the hypervisor process. // - VMADDR_CID_HOST: refers to other processes on the host. CID uint32 Port uint32 raw RawSockaddrVM } func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) { sa.raw.Family = AF_VSOCK sa.raw.Port = sa.Port sa.raw.Cid = sa.CID return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil } func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_NETLINK: pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa)) sa := new(SockaddrNetlink) sa.Family = pp.Family sa.Pad = pp.Pad sa.Pid = pp.Pid sa.Groups = pp.Groups return sa, nil case AF_PACKET: pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa)) sa := new(SockaddrLinklayer) sa.Protocol = pp.Protocol sa.Ifindex = int(pp.Ifindex) sa.Hatype = pp.Hatype sa.Pkttype = pp.Pkttype sa.Halen = pp.Halen for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil case AF_UNIX: pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) sa := new(SockaddrUnix) if pp.Path[0] == 0 { // "Abstract" Unix domain socket. // Rewrite leading NUL as @ for textual display. // (This is the standard convention.) // Not friendly to overwrite in place, // but the callers below don't care. pp.Path[0] = '@' } // Assume path ends at NUL. // This is not technically the Linux semantics for // abstract Unix domain sockets--they are supposed // to be uninterpreted fixed-size binary blobs--but // everyone uses this convention. n := 0 for n < len(pp.Path) && pp.Path[n] != 0 { n++ } bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n] sa.Name = string(bytes) return sa, nil case AF_INET: pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) sa := new(SockaddrInet4) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil case AF_INET6: pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) sa := new(SockaddrInet6) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) sa.ZoneId = pp.Scope_id for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil case AF_VSOCK: pp := (*RawSockaddrVM)(unsafe.Pointer(rsa)) sa := &SockaddrVM{ CID: pp.Cid, Port: pp.Port, } return sa, nil } return nil, EAFNOSUPPORT } func Accept(fd int) (nfd int, sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny nfd, err = accept(fd, &rsa, &len) if err != nil { return } sa, err = anyToSockaddr(&rsa) if err != nil { Close(nfd) nfd = 0 } return } func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny nfd, err = accept4(fd, &rsa, &len, flags) if err != nil { return } if len > SizeofSockaddrAny { panic("RawSockaddrAny too small") } sa, err = anyToSockaddr(&rsa) if err != nil { Close(nfd) nfd = 0 } return } func Getsockname(fd int) (sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny if err = getsockname(fd, &rsa, &len); err != nil { return } return anyToSockaddr(&rsa) } func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { vallen := _Socklen(4) err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) return value, err } func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { var value IPMreq vallen := _Socklen(SizeofIPMreq) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { var value IPMreqn vallen := _Socklen(SizeofIPMreqn) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { var value IPv6Mreq vallen := _Socklen(SizeofIPv6Mreq) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { var value IPv6MTUInfo vallen := _Socklen(SizeofIPv6MTUInfo) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { var value ICMPv6Filter vallen := _Socklen(SizeofICMPv6Filter) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptUcred(fd, level, opt int) (*Ucred, error) { var value Ucred vallen := _Socklen(SizeofUcred) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) { var value TCPInfo vallen := _Socklen(SizeofTCPInfo) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) } // Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html) // KeyctlInt calls keyctl commands in which each argument is an int. // These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK, // KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT, // KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT, // KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT. //sys KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL // KeyctlBuffer calls keyctl commands in which the third and fourth // arguments are a buffer and its length, respectively. // These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE. //sys KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL // KeyctlString calls keyctl commands which return a string. // These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY. func KeyctlString(cmd int, id int) (string, error) { // We must loop as the string data may change in between the syscalls. // We could allocate a large buffer here to reduce the chance that the // syscall needs to be called twice; however, this is unnecessary as // the performance loss is negligible. var buffer []byte for { // Try to fill the buffer with data length, err := KeyctlBuffer(cmd, id, buffer, 0) if err != nil { return "", err } // Check if the data was written if length <= len(buffer) { // Exclude the null terminator return string(buffer[:length-1]), nil } // Make a bigger buffer if needed buffer = make([]byte, length) } } // Keyctl commands with special signatures. // KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command. // See the full documentation at: // http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) { createInt := 0 if create { createInt = 1 } return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0) } // KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the // key handle permission mask as described in the "keyctl setperm" section of // http://man7.org/linux/man-pages/man1/keyctl.1.html. // See the full documentation at: // http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html func KeyctlSetperm(id int, perm uint32) error { _, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0) return err } //sys keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL // KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command. // See the full documentation at: // http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html func KeyctlJoinSessionKeyring(name string) (ringid int, err error) { return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name) } //sys keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL // KeyctlSearch implements the KEYCTL_SEARCH command. // See the full documentation at: // http://man7.org/linux/man-pages/man3/keyctl_search.3.html func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) { return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid) } //sys keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL // KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This // command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice // of Iovec (each of which represents a buffer) instead of a single buffer. // See the full documentation at: // http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error { return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid) } //sys keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL // KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command // computes a Diffie-Hellman shared secret based on the provide params. The // secret is written to the provided buffer and the returned size is the number // of bytes written (returning an error if there is insufficient space in the // buffer). If a nil buffer is passed in, this function returns the minimum // buffer length needed to store the appropriate data. Note that this differs // from KEYCTL_READ's behavior which always returns the requested payload size. // See the full documentation at: // http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) { return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer) } func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { var msg Msghdr var rsa RawSockaddrAny msg.Name = (*byte)(unsafe.Pointer(&rsa)) msg.Namelen = uint32(SizeofSockaddrAny) var iov Iovec if len(p) > 0 { iov.Base = (*byte)(unsafe.Pointer(&p[0])) iov.SetLen(len(p)) } var dummy byte if len(oob) > 0 { var sockType int sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) if err != nil { return } // receive at least one normal byte if sockType != SOCK_DGRAM && len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } msg.Control = (*byte)(unsafe.Pointer(&oob[0])) msg.SetControllen(len(oob)) } msg.Iov = &iov msg.Iovlen = 1 if n, err = recvmsg(fd, &msg, flags); err != nil { return } oobn = int(msg.Controllen) recvflags = int(msg.Flags) // source address is only specified if the socket is unconnected if rsa.Addr.Family != AF_UNSPEC { from, err = anyToSockaddr(&rsa) } return } func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { _, err = SendmsgN(fd, p, oob, to, flags) return } func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { var ptr unsafe.Pointer var salen _Socklen if to != nil { var err error ptr, salen, err = to.sockaddr() if err != nil { return 0, err } } var msg Msghdr msg.Name = (*byte)(unsafe.Pointer(ptr)) msg.Namelen = uint32(salen) var iov Iovec if len(p) > 0 { iov.Base = (*byte)(unsafe.Pointer(&p[0])) iov.SetLen(len(p)) } var dummy byte if len(oob) > 0 { var sockType int sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) if err != nil { return 0, err } // send at least one normal byte if sockType != SOCK_DGRAM && len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } msg.Control = (*byte)(unsafe.Pointer(&oob[0])) msg.SetControllen(len(oob)) } msg.Iov = &iov msg.Iovlen = 1 if n, err = sendmsg(fd, &msg, flags); err != nil { return 0, err } if len(oob) > 0 && len(p) == 0 { n = 0 } return n, nil } // BindToDevice binds the socket associated with fd to device. func BindToDevice(fd int, device string) (err error) { return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device) } //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error) func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) { // The peek requests are machine-size oriented, so we wrap it // to retrieve arbitrary-length data. // The ptrace syscall differs from glibc's ptrace. // Peeks returns the word in *data, not as the return value. var buf [sizeofPtr]byte // Leading edge. PEEKTEXT/PEEKDATA don't require aligned // access (PEEKUSER warns that it might), but if we don't // align our reads, we might straddle an unmapped page // boundary and not get the bytes leading up to the page // boundary. n := 0 if addr%sizeofPtr != 0 { err = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0]))) if err != nil { return 0, err } n += copy(out, buf[addr%sizeofPtr:]) out = out[n:] } // Remainder. for len(out) > 0 { // We use an internal buffer to guarantee alignment. // It's not documented if this is necessary, but we're paranoid. err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0]))) if err != nil { return n, err } copied := copy(out, buf[0:]) n += copied out = out[copied:] } return n, nil } func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) { return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out) } func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) { return ptracePeek(PTRACE_PEEKDATA, pid, addr, out) } func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) { return ptracePeek(PTRACE_PEEKUSR, pid, addr, out) } func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) { // As for ptracePeek, we need to align our accesses to deal // with the possibility of straddling an invalid page. // Leading edge. n := 0 if addr%sizeofPtr != 0 { var buf [sizeofPtr]byte err = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0]))) if err != nil { return 0, err } n += copy(buf[addr%sizeofPtr:], data) word := *((*uintptr)(unsafe.Pointer(&buf[0]))) err = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word) if err != nil { return 0, err } data = data[n:] } // Interior. for len(data) > sizeofPtr { word := *((*uintptr)(unsafe.Pointer(&data[0]))) err = ptrace(pokeReq, pid, addr+uintptr(n), word) if err != nil { return n, err } n += sizeofPtr data = data[sizeofPtr:] } // Trailing edge. if len(data) > 0 { var buf [sizeofPtr]byte err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0]))) if err != nil { return n, err } copy(buf[0:], data) word := *((*uintptr)(unsafe.Pointer(&buf[0]))) err = ptrace(pokeReq, pid, addr+uintptr(n), word) if err != nil { return n, err } n += len(data) } return n, nil } func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) { return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data) } func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) { return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data) } func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) { return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout))) } func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) { return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs))) } func PtraceSetOptions(pid int, options int) (err error) { return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options)) } func PtraceGetEventMsg(pid int) (msg uint, err error) { var data _C_long err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data))) msg = uint(data) return } func PtraceCont(pid int, signal int) (err error) { return ptrace(PTRACE_CONT, pid, 0, uintptr(signal)) } func PtraceSyscall(pid int, signal int) (err error) { return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal)) } func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) } func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) } func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) } //sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) func Reboot(cmd int) (err error) { return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "") } func ReadDirent(fd int, buf []byte) (n int, err error) { return Getdents(fd, buf) } func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) } func direntReclen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) } func direntNamlen(buf []byte) (uint64, bool) { reclen, ok := direntReclen(buf) if !ok { return 0, false } return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true } //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { // Certain file systems get rather angry and EINVAL if you give // them an empty string of data, rather than NULL. if data == "" { return mount(source, target, fstype, flags, nil) } datap, err := BytePtrFromString(data) if err != nil { return err } return mount(source, target, fstype, flags, datap) } // Sendto // Recvfrom // Socketpair /* * Direct access */ //sys Acct(path string) (err error) //sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) //sys Adjtimex(buf *Timex) (state int, err error) //sys Chdir(path string) (err error) //sys Chroot(path string) (err error) //sys ClockGettime(clockid int32, time *Timespec) (err error) //sys Close(fd int) (err error) //sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys Dup(oldfd int) (fd int, err error) //sys Dup3(oldfd int, newfd int, flags int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sysnb EpollCreate1(flag int) (fd int, err error) //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2 //sys Exit(code int) = SYS_EXIT_GROUP //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error) //sys Fchdir(fd int) (err error) //sys Fchmod(fd int, mode uint32) (err error) //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) //sys fcntl(fd int, cmd int, arg int) (val int, err error) //sys Fdatasync(fd int) (err error) //sys Flock(fd int, how int) (err error) //sys Fsync(fd int) (err error) //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 //sysnb Getpgid(pid int) (pgid int, err error) func Getpgrp() (pid int) { pid, _ = Getpgid(0) return } //sysnb Getpid() (pid int) //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) //sys Getrandom(buf []byte, flags int) (n int, err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Gettid() (tid int) //sys Getxattr(path string, attr string, dest []byte) (sz int, err error) //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) //sysnb InotifyInit1(flags int) (fd int, err error) //sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) //sysnb Kill(pid int, sig syscall.Signal) (err error) //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error) //sys Listxattr(path string, dest []byte) (sz int, err error) //sys Llistxattr(path string, dest []byte) (sz int, err error) //sys Lremovexattr(path string, attr string) (err error) //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error) //sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT //sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64 //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) //sys Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) = SYS_PSELECT6 //sys read(fd int, p []byte) (n int, err error) //sys Removexattr(path string, attr string) (err error) //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) //sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) //sys Setdomainname(p []byte) (err error) //sys Sethostname(p []byte) (err error) //sysnb Setpgid(pid int, pgid int) (err error) //sysnb Setsid() (pid int, err error) //sysnb Settimeofday(tv *Timeval) (err error) //sys Setns(fd int, nstype int) (err error) // issue 1435. // On linux Setuid and Setgid only affects the current thread, not the process. // This does not match what most callers expect so we must return an error // here rather than letting the caller think that the call succeeded. func Setuid(uid int) (err error) { return EOPNOTSUPP } func Setgid(uid int) (err error) { return EOPNOTSUPP } //sys Setpriority(which int, who int, prio int) (err error) //sys Setxattr(path string, attr string, data []byte, flags int) (err error) //sys Sync() //sys Syncfs(fd int) (err error) //sysnb Sysinfo(info *Sysinfo_t) (err error) //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error) //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error) //sysnb Times(tms *Tms) (ticks uintptr, err error) //sysnb Umask(mask int) (oldmask int) //sysnb Uname(buf *Utsname) (err error) //sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2 //sys Unshare(flags int) (err error) //sys Ustat(dev int, ubuf *Ustat_t) (err error) //sys write(fd int, p []byte) (n int, err error) //sys exitThread(code int) (err error) = SYS_EXIT //sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ //sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE // mmap varies by architecture; see syscall_linux_*.go. //sys munmap(addr uintptr, length uintptr) (err error) var mapper = &mmapper{ active: make(map[*byte][]byte), mmap: mmap, munmap: munmap, } func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { return mapper.Mmap(fd, offset, length, prot, flags) } func Munmap(b []byte) (err error) { return mapper.Munmap(b) } //sys Madvise(b []byte, advice int) (err error) //sys Mprotect(b []byte, prot int) (err error) //sys Mlock(b []byte) (err error) //sys Mlockall(flags int) (err error) //sys Msync(b []byte, flags int) (err error) //sys Munlock(b []byte) (err error) //sys Munlockall() (err error) // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd, // using the specified flags. func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) { n, _, errno := Syscall6( SYS_VMSPLICE, uintptr(fd), uintptr(unsafe.Pointer(&iovs[0])), uintptr(len(iovs)), uintptr(flags), 0, 0, ) if errno != 0 { return 0, syscall.Errno(errno) } return int(n), nil } /* * Unimplemented */ // AfsSyscall // Alarm // ArchPrctl // Brk // Capget // Capset // ClockGetres // ClockNanosleep // ClockSettime // Clone // CreateModule // DeleteModule // EpollCtlOld // EpollPwait // EpollWaitOld // Execve // Fgetxattr // Flistxattr // Fork // Fremovexattr // Fsetxattr // Futex // GetKernelSyms // GetMempolicy // GetRobustList // GetThreadArea // Getitimer // Getpmsg // IoCancel // IoDestroy // IoGetevents // IoSetup // IoSubmit // IoprioGet // IoprioSet // KexecLoad // LookupDcookie // Mbind // MigratePages // Mincore // ModifyLdt // Mount // MovePages // MqGetsetattr // MqNotify // MqOpen // MqTimedreceive // MqTimedsend // MqUnlink // Mremap // Msgctl // Msgget // Msgrcv // Msgsnd // Newfstatat // Nfsservctl // Personality // Pselect6 // Ptrace // Putpmsg // QueryModule // Quotactl // Readahead // Readv // RemapFilePages // RestartSyscall // RtSigaction // RtSigpending // RtSigprocmask // RtSigqueueinfo // RtSigreturn // RtSigsuspend // RtSigtimedwait // SchedGetPriorityMax // SchedGetPriorityMin // SchedGetaffinity // SchedGetparam // SchedGetscheduler // SchedRrGetInterval // SchedSetaffinity // SchedSetparam // SchedYield // Security // Semctl // Semget // Semop // Semtimedop // SetMempolicy // SetRobustList // SetThreadArea // SetTidAddress // Shmat // Shmctl // Shmdt // Shmget // Sigaltstack // Signalfd // Swapoff // Swapon // Sysfs // TimerCreate // TimerDelete // TimerGetoverrun // TimerGettime // TimerSettime // Timerfd // Tkill (obsolete) // Tuxcall // Umount2 // Uselib // Utimensat // Vfork // Vhangup // Vserver // Waitid // _Sysctl lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_freebsd_test.go0000644061062106075000000001563713172163421026075 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build freebsd package unix_test import ( "flag" "fmt" "io/ioutil" "os" "os/exec" "path" "path/filepath" "runtime" "testing" "golang.org/x/sys/unix" ) func TestSysctlUint64(t *testing.T) { _, err := unix.SysctlUint64("vm.swap_total") if err != nil { t.Fatal(err) } } // FIXME: Infrastructure for launching tests in subprocesses stolen from openbsd_test.go - refactor? // testCmd generates a proper command that, when executed, runs the test // corresponding to the given key. type testProc struct { fn func() // should always exit instead of returning arg func(t *testing.T) string // generate argument for test cleanup func(arg string) error // for instance, delete coredumps from testing pledge success bool // whether zero-exit means success or failure } var ( testProcs = map[string]testProc{} procName = "" procArg = "" ) const ( optName = "sys-unix-internal-procname" optArg = "sys-unix-internal-arg" ) func init() { flag.StringVar(&procName, optName, "", "internal use only") flag.StringVar(&procArg, optArg, "", "internal use only") } func testCmd(procName string, procArg string) (*exec.Cmd, error) { exe, err := filepath.Abs(os.Args[0]) if err != nil { return nil, err } cmd := exec.Command(exe, "-"+optName+"="+procName, "-"+optArg+"="+procArg) cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr return cmd, nil } // ExitsCorrectly is a comprehensive, one-line-of-use wrapper for testing // a testProc with a key. func ExitsCorrectly(t *testing.T, procName string) { s := testProcs[procName] arg := "-" if s.arg != nil { arg = s.arg(t) } c, err := testCmd(procName, arg) defer func(arg string) { if err := s.cleanup(arg); err != nil { t.Fatalf("Failed to run cleanup for %s %s %#v", procName, err, err) } }(arg) if err != nil { t.Fatalf("Failed to construct command for %s", procName) } if (c.Run() == nil) != s.success { result := "succeed" if !s.success { result = "fail" } t.Fatalf("Process did not %s when it was supposed to", result) } } func TestMain(m *testing.M) { flag.Parse() if procName != "" { t := testProcs[procName] t.fn() os.Stderr.WriteString("test function did not exit\n") if t.success { os.Exit(1) } else { os.Exit(0) } } os.Exit(m.Run()) } // end of infrastructure const testfile = "gocapmodetest" const testfile2 = testfile + "2" func CapEnterTest() { _, err := os.OpenFile(path.Join(procArg, testfile), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(fmt.Sprintf("OpenFile: %s", err)) } err = unix.CapEnter() if err != nil { panic(fmt.Sprintf("CapEnter: %s", err)) } _, err = os.OpenFile(path.Join(procArg, testfile2), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err == nil { panic("OpenFile works!") } if err.(*os.PathError).Err != unix.ECAPMODE { panic(fmt.Sprintf("OpenFile failed wrong: %s %#v", err, err)) } os.Exit(0) } func makeTempDir(t *testing.T) string { d, err := ioutil.TempDir("", "go_openat_test") if err != nil { t.Fatalf("TempDir failed: %s", err) } return d } func removeTempDir(arg string) error { err := os.RemoveAll(arg) if err != nil && err.(*os.PathError).Err == unix.ENOENT { return nil } return err } func init() { testProcs["cap_enter"] = testProc{ CapEnterTest, makeTempDir, removeTempDir, true, } } func TestCapEnter(t *testing.T) { if runtime.GOARCH != "amd64" { t.Skipf("skipping test on %s", runtime.GOARCH) } ExitsCorrectly(t, "cap_enter") } func OpenatTest() { f, err := os.Open(procArg) if err != nil { panic(err) } err = unix.CapEnter() if err != nil { panic(fmt.Sprintf("CapEnter: %s", err)) } fxx, err := unix.Openat(int(f.Fd()), "xx", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(err) } unix.Close(fxx) // The right to open BASE/xx is not ambient _, err = os.OpenFile(procArg+"/xx", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err == nil { panic("OpenFile succeeded") } if err.(*os.PathError).Err != unix.ECAPMODE { panic(fmt.Sprintf("OpenFile failed wrong: %s %#v", err, err)) } // Can't make a new directory either err = os.Mkdir(procArg+"2", 0777) if err == nil { panic("MKdir succeeded") } if err.(*os.PathError).Err != unix.ECAPMODE { panic(fmt.Sprintf("Mkdir failed wrong: %s %#v", err, err)) } // Remove all caps except read and lookup. r, err := unix.CapRightsInit([]uint64{unix.CAP_READ, unix.CAP_LOOKUP}) if err != nil { panic(fmt.Sprintf("CapRightsInit failed: %s %#v", err, err)) } err = unix.CapRightsLimit(f.Fd(), r) if err != nil { panic(fmt.Sprintf("CapRightsLimit failed: %s %#v", err, err)) } // Check we can get the rights back again r, err = unix.CapRightsGet(f.Fd()) if err != nil { panic(fmt.Sprintf("CapRightsGet failed: %s %#v", err, err)) } b, err := unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_LOOKUP}) if err != nil { panic(fmt.Sprintf("CapRightsIsSet failed: %s %#v", err, err)) } if !b { panic(fmt.Sprintf("Unexpected rights")) } b, err = unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_LOOKUP, unix.CAP_WRITE}) if err != nil { panic(fmt.Sprintf("CapRightsIsSet failed: %s %#v", err, err)) } if b { panic(fmt.Sprintf("Unexpected rights (2)")) } // Can no longer create a file _, err = unix.Openat(int(f.Fd()), "xx2", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err == nil { panic("Openat succeeded") } if err != unix.ENOTCAPABLE { panic(fmt.Sprintf("OpenFileAt failed wrong: %s %#v", err, err)) } // But can read an existing one _, err = unix.Openat(int(f.Fd()), "xx", os.O_RDONLY, 0666) if err != nil { panic(fmt.Sprintf("Openat failed: %s %#v", err, err)) } os.Exit(0) } func init() { testProcs["openat"] = testProc{ OpenatTest, makeTempDir, removeTempDir, true, } } func TestOpenat(t *testing.T) { if runtime.GOARCH != "amd64" { t.Skipf("skipping test on %s", runtime.GOARCH) } ExitsCorrectly(t, "openat") } func TestCapRightsSetAndClear(t *testing.T) { r, err := unix.CapRightsInit([]uint64{unix.CAP_READ, unix.CAP_WRITE, unix.CAP_PDWAIT}) if err != nil { t.Fatalf("CapRightsInit failed: %s", err) } err = unix.CapRightsSet(r, []uint64{unix.CAP_EVENT, unix.CAP_LISTEN}) if err != nil { t.Fatalf("CapRightsSet failed: %s", err) } b, err := unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_WRITE, unix.CAP_PDWAIT, unix.CAP_EVENT, unix.CAP_LISTEN}) if err != nil { t.Fatalf("CapRightsIsSet failed: %s", err) } if !b { t.Fatalf("Wrong rights set") } err = unix.CapRightsClear(r, []uint64{unix.CAP_READ, unix.CAP_PDWAIT}) if err != nil { t.Fatalf("CapRightsClear failed: %s", err) } b, err = unix.CapRightsIsSet(r, []uint64{unix.CAP_WRITE, unix.CAP_EVENT, unix.CAP_LISTEN}) if err != nil { t.Fatalf("CapRightsIsSet failed: %s", err) } if !b { t.Fatalf("Wrong rights set") } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_freebsd_arm.go0000644061062106075000000000254313172163421025665 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm,freebsd package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return ts.Sec*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = nsec / 1e9 return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var writtenOut uint64 = 0 _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0) written = int(writtenOut) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_freebsd_amd64.go0000644061062106075000000000252013172163421026014 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,freebsd package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = nsec % 1e9 / 1e3 tv.Sec = int64(nsec / 1e9) return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var writtenOut uint64 = 0 _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0) written = int(writtenOut) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_freebsd_386.go0000644061062106075000000000257013172163421025426 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build 386,freebsd package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int32(nsec / 1e9) return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var writtenOut uint64 = 0 _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0) written = int(writtenOut) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_freebsd.go0000644061062106075000000004505013172163421025026 0ustar stgraberdomain admins// Copyright 2009,2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // FreeBSD system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and wrap // it in our own nicer implementation, either here or in // syscall_bsd.go or syscall_unix.go. package unix import "unsafe" type SockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [46]int8 raw RawSockaddrDatalink } // Translate "kern.hostname" to []_C_int{0,1,2,3}. func nametomib(name string) (mib []_C_int, err error) { const siz = unsafe.Sizeof(mib[0]) // NOTE(rsc): It seems strange to set the buffer to have // size CTL_MAXNAME+2 but use only CTL_MAXNAME // as the size. I don't know why the +2 is here, but the // kernel uses +2 for its own implementation of this function. // I am scared that if we don't include the +2 here, the kernel // will silently write 2 words farther than we specify // and we'll get memory corruption. var buf [CTL_MAXNAME + 2]_C_int n := uintptr(CTL_MAXNAME) * siz p := (*byte)(unsafe.Pointer(&buf[0])) bytes, err := ByteSliceFromString(name) if err != nil { return nil, err } // Magic sysctl: "setting" 0.3 to a string name // lets you read back the array of integers form. if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { return nil, err } return buf[0 : n/siz], nil } func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) } func direntReclen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) } func direntNamlen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) } //sysnb pipe() (r int, w int, err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } p[0], p[1], err = pipe() return } func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { var value IPMreqn vallen := _Socklen(SizeofIPMreqn) errno := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, errno } func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) } func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny nfd, err = accept4(fd, &rsa, &len, flags) if err != nil { return } if len > SizeofSockaddrAny { panic("RawSockaddrAny too small") } sa, err = anyToSockaddr(&rsa) if err != nil { Close(nfd) nfd = 0 } return } func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { var _p0 unsafe.Pointer var bufsize uintptr if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) } r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) n = int(r0) if e1 != 0 { err = e1 } return } // Derive extattr namespace and attribute name func xattrnamespace(fullattr string) (ns int, attr string, err error) { s := -1 for idx, val := range fullattr { if val == '.' { s = idx break } } if s == -1 { return -1, "", ENOATTR } namespace := fullattr[0:s] attr = fullattr[s+1:] switch namespace { case "user": return EXTATTR_NAMESPACE_USER, attr, nil case "system": return EXTATTR_NAMESPACE_SYSTEM, attr, nil default: return -1, "", ENOATTR } } func initxattrdest(dest []byte, idx int) (d unsafe.Pointer) { if len(dest) > idx { return unsafe.Pointer(&dest[idx]) } else { return unsafe.Pointer(_zero) } } // FreeBSD implements its own syscalls to handle extended attributes func Getxattr(file string, attr string, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsize := len(dest) nsid, a, err := xattrnamespace(attr) if err != nil { return -1, err } return ExtattrGetFile(file, nsid, a, uintptr(d), destsize) } func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsize := len(dest) nsid, a, err := xattrnamespace(attr) if err != nil { return -1, err } return ExtattrGetFd(fd, nsid, a, uintptr(d), destsize) } func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsize := len(dest) nsid, a, err := xattrnamespace(attr) if err != nil { return -1, err } return ExtattrGetLink(link, nsid, a, uintptr(d), destsize) } // flags are unused on FreeBSD func Fsetxattr(fd int, attr string, data []byte, flags int) (err error) { d := unsafe.Pointer(&data[0]) datasiz := len(data) nsid, a, err := xattrnamespace(attr) if err != nil { return } _, err = ExtattrSetFd(fd, nsid, a, uintptr(d), datasiz) return } func Setxattr(file string, attr string, data []byte, flags int) (err error) { d := unsafe.Pointer(&data[0]) datasiz := len(data) nsid, a, err := xattrnamespace(attr) if err != nil { return } _, err = ExtattrSetFile(file, nsid, a, uintptr(d), datasiz) return } func Lsetxattr(link string, attr string, data []byte, flags int) (err error) { d := unsafe.Pointer(&data[0]) datasiz := len(data) nsid, a, err := xattrnamespace(attr) if err != nil { return } _, err = ExtattrSetLink(link, nsid, a, uintptr(d), datasiz) return } func Removexattr(file string, attr string) (err error) { nsid, a, err := xattrnamespace(attr) if err != nil { return } err = ExtattrDeleteFile(file, nsid, a) return } func Fremovexattr(fd int, attr string) (err error) { nsid, a, err := xattrnamespace(attr) if err != nil { return } err = ExtattrDeleteFd(fd, nsid, a) return } func Lremovexattr(link string, attr string) (err error) { nsid, a, err := xattrnamespace(attr) if err != nil { return } err = ExtattrDeleteLink(link, nsid, a) return } func Listxattr(file string, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsiz := len(dest) // FreeBSD won't allow you to list xattrs from multiple namespaces s := 0 var e error for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { stmp, e := ExtattrListFile(file, nsid, uintptr(d), destsiz) /* Errors accessing system attrs are ignored so that * we can implement the Linux-like behavior of omitting errors that * we don't have read permissions on * * Linux will still error if we ask for user attributes on a file that * we don't have read permissions on, so don't ignore those errors */ if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { e = nil continue } else if e != nil { return s, e } s += stmp destsiz -= s if destsiz < 0 { destsiz = 0 } d = initxattrdest(dest, s) } return s, e } func Flistxattr(fd int, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsiz := len(dest) s := 0 var e error for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { stmp, e := ExtattrListFd(fd, nsid, uintptr(d), destsiz) if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { e = nil continue } else if e != nil { return s, e } s += stmp destsiz -= s if destsiz < 0 { destsiz = 0 } d = initxattrdest(dest, s) } return s, e } func Llistxattr(link string, dest []byte) (sz int, err error) { d := initxattrdest(dest, 0) destsiz := len(dest) s := 0 var e error for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { stmp, e := ExtattrListLink(link, nsid, uintptr(d), destsiz) if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { e = nil continue } else if e != nil { return s, e } s += stmp destsiz -= s if destsiz < 0 { destsiz = 0 } d = initxattrdest(dest, s) } return s, e } //sys ioctl(fd int, req uint, arg uintptr) (err error) // ioctl itself should not be exposed directly, but additional get/set // functions for specific types are permissible. // IoctlSetInt performs an ioctl operation which sets an integer value // on fd, using the specified request number. func IoctlSetInt(fd int, req uint, value int) error { return ioctl(fd, req, uintptr(value)) } func IoctlSetWinsize(fd int, req uint, value *Winsize) error { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermios(fd int, req uint, value *Termios) error { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } // IoctlGetInt performs an ioctl operation which gets an integer value // from fd, using the specified request number. func IoctlGetInt(fd int, req uint) (int, error) { var value int err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return value, err } func IoctlGetWinsize(fd int, req uint) (*Winsize, error) { var value Winsize err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermios(fd int, req uint) (*Termios, error) { var value Termios err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } /* * Exposed directly */ //sys Access(path string, mode uint32) (err error) //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) //sys CapEnter() (err error) //sys capRightsGet(version int, fd int, rightsp *CapRights) (err error) = SYS___CAP_RIGHTS_GET //sys capRightsLimit(fd int, rightsp *CapRights) (err error) //sys Chdir(path string) (err error) //sys Chflags(path string, flags int) (err error) //sys Chmod(path string, mode uint32) (err error) //sys Chown(path string, uid int, gid int) (err error) //sys Chroot(path string) (err error) //sys Close(fd int) (err error) //sys Dup(fd int) (nfd int, err error) //sys Dup2(from int, to int) (err error) //sys Exit(code int) //sys ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) //sys ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) //sys ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) //sys ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) //sys ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) //sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchdir(fd int) (err error) //sys Fchflags(fd int, flags int) (err error) //sys Fchmod(fd int, mode uint32) (err error) //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatfs(fd int, stat *Statfs_t) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) //sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) //sys Getdtablesize() (size int) //sysnb Getegid() (egid int) //sysnb Geteuid() (uid int) //sysnb Getgid() (gid int) //sysnb Getpgid(pid int) (pgid int, err error) //sysnb Getpgrp() (pgrp int) //sysnb Getpid() (pid int) //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) //sysnb Getrlimit(which int, lim *Rlimit) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Getuid() (uid int) //sys Issetugid() (tainted bool) //sys Kill(pid int, signum syscall.Signal) (err error) //sys Kqueue() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Link(path string, link string) (err error) //sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) //sys Listen(s int, backlog int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Mkdir(path string, mode uint32) (err error) //sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Readlink(path string, buf []byte) (n int, err error) //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error) //sys Rename(from string, to string) (err error) //sys Renameat(fromfd int, from string, tofd int, to string) (err error) //sys Revoke(path string) (err error) //sys Rmdir(path string) (err error) //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK //sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) //sysnb Setegid(egid int) (err error) //sysnb Seteuid(euid int) (err error) //sysnb Setgid(gid int) (err error) //sys Setlogin(name string) (err error) //sysnb Setpgid(pid int, pgid int) (err error) //sys Setpriority(which int, who int, prio int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(which int, lim *Rlimit) (err error) //sysnb Setsid() (pid int, err error) //sysnb Settimeofday(tp *Timeval) (err error) //sysnb Setuid(uid int) (err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Statfs(path string, stat *Statfs_t) (err error) //sys Symlink(path string, link string) (err error) //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) //sys Sync() (err error) //sys Truncate(path string, length int64) (err error) //sys Umask(newmask int) (oldmask int) //sys Undelete(path string) (err error) //sys Unlink(path string) (err error) //sys Unlinkat(dirfd int, path string, flags int) (err error) //sys Unmount(path string, flags int) (err error) //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) //sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ //sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE //sys accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) /* * Unimplemented */ // Profil // Sigaction // Sigprocmask // Getlogin // Sigpending // Sigaltstack // Ioctl // Reboot // Execve // Vfork // Sbrk // Sstk // Ovadvise // Mincore // Setitimer // Swapon // Select // Sigsuspend // Readv // Writev // Nfssvc // Getfh // Quotactl // Mount // Csops // Waitid // Add_profil // Kdebug_trace // Sigreturn // Atsocket // Kqueue_from_portset_np // Kqueue_portset // Getattrlist // Setattrlist // Getdirentriesattr // Searchfs // Delete // Copyfile // Poll // Watchevent // Waitevent // Modwatch // Getxattr // Fgetxattr // Setxattr // Fsetxattr // Removexattr // Fremovexattr // Listxattr // Flistxattr // Fsctl // Initgroups // Posix_spawn // Nfsclnt // Fhopen // Minherit // Semsys // Msgsys // Shmsys // Semctl // Semget // Semop // Msgctl // Msgget // Msgsnd // Msgrcv // Shmat // Shmctl // Shmdt // Shmget // Shm_open // Shm_unlink // Sem_open // Sem_close // Sem_unlink // Sem_wait // Sem_trywait // Sem_post // Sem_getvalue // Sem_init // Sem_destroy // Open_extended // Umask_extended // Stat_extended // Lstat_extended // Fstat_extended // Chmod_extended // Fchmod_extended // Access_extended // Settid // Gettid // Setsgroups // Getsgroups // Setwgroups // Getwgroups // Mkfifo_extended // Mkdir_extended // Identitysvc // Shared_region_check_np // Shared_region_map_np // __pthread_mutex_destroy // __pthread_mutex_init // __pthread_mutex_lock // __pthread_mutex_trylock // __pthread_mutex_unlock // __pthread_cond_init // __pthread_cond_destroy // __pthread_cond_broadcast // __pthread_cond_signal // Setsid_with_pid // __pthread_cond_timedwait // Aio_fsync // Aio_return // Aio_suspend // Aio_cancel // Aio_error // Aio_read // Aio_write // Lio_listio // __pthread_cond_wait // Iopolicysys // __pthread_kill // __pthread_sigmask // __sigwait // __disable_threadsignal // __pthread_markcancel // __pthread_canceled // __semwait_signal // Proc_info // Stat64_extended // Lstat64_extended // Fstat64_extended // __pthread_chdir // __pthread_fchdir // Audit // Auditon // Getauid // Setauid // Getaudit // Setaudit // Getaudit_addr // Setaudit_addr // Auditctl // Bsdthread_create // Bsdthread_terminate // Stack_snapshot // Bsdthread_register // Workq_open // Workq_ops // __mac_execve // __mac_syscall // __mac_get_file // __mac_set_file // __mac_get_link // __mac_set_link // __mac_get_proc // __mac_set_proc // __mac_get_fd // __mac_set_fd // __mac_get_pid // __mac_get_lcid // __mac_get_lctx // __mac_set_lctx // Setlcid // Read_nocancel // Write_nocancel // Open_nocancel // Close_nocancel // Wait4_nocancel // Recvmsg_nocancel // Sendmsg_nocancel // Recvfrom_nocancel // Accept_nocancel // Fcntl_nocancel // Select_nocancel // Fsync_nocancel // Connect_nocancel // Sigsuspend_nocancel // Readv_nocancel // Writev_nocancel // Sendto_nocancel // Pread_nocancel // Pwrite_nocancel // Waitid_nocancel // Poll_nocancel // Msgsnd_nocancel // Msgrcv_nocancel // Sem_wait_nocancel // Aio_suspend_nocancel // __sigwait_nocancel // __semwait_signal_nocancel // __mac_mount // __mac_get_mount // __mac_getfsstat lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_dragonfly_amd64.go0000644061062106075000000000252213172163421026371 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,dragonfly package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = nsec % 1e9 / 1e3 tv.Sec = int64(nsec / 1e9) return } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var writtenOut uint64 = 0 _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0) written = int(writtenOut) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_dragonfly.go0000644061062106075000000002464513172163421025410 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // DragonFly BSD system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and wrap // it in our own nicer implementation, either here or in // syscall_bsd.go or syscall_unix.go. package unix import "unsafe" type SockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 Rcf uint16 Route [16]uint16 raw RawSockaddrDatalink } // Translate "kern.hostname" to []_C_int{0,1,2,3}. func nametomib(name string) (mib []_C_int, err error) { const siz = unsafe.Sizeof(mib[0]) // NOTE(rsc): It seems strange to set the buffer to have // size CTL_MAXNAME+2 but use only CTL_MAXNAME // as the size. I don't know why the +2 is here, but the // kernel uses +2 for its own implementation of this function. // I am scared that if we don't include the +2 here, the kernel // will silently write 2 words farther than we specify // and we'll get memory corruption. var buf [CTL_MAXNAME + 2]_C_int n := uintptr(CTL_MAXNAME) * siz p := (*byte)(unsafe.Pointer(&buf[0])) bytes, err := ByteSliceFromString(name) if err != nil { return nil, err } // Magic sysctl: "setting" 0.3 to a string name // lets you read back the array of integers form. if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { return nil, err } return buf[0 : n/siz], nil } func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) } func direntReclen(buf []byte) (uint64, bool) { namlen, ok := direntNamlen(buf) if !ok { return 0, false } return (16 + namlen + 1 + 7) &^ 7, true } func direntNamlen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) } //sysnb pipe() (r int, w int, err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } p[0], p[1], err = pipe() return } //sys extpread(fd int, p []byte, flags int, offset int64) (n int, err error) func Pread(fd int, p []byte, offset int64) (n int, err error) { return extpread(fd, p, 0, offset) } //sys extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error) func Pwrite(fd int, p []byte, offset int64) (n int, err error) { return extpwrite(fd, p, 0, offset) } func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny nfd, err = accept4(fd, &rsa, &len, flags) if err != nil { return } if len > SizeofSockaddrAny { panic("RawSockaddrAny too small") } sa, err = anyToSockaddr(&rsa) if err != nil { Close(nfd) nfd = 0 } return } func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { var _p0 unsafe.Pointer var bufsize uintptr if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) } r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) n = int(r0) if e1 != 0 { err = e1 } return } /* * Exposed directly */ //sys Access(path string, mode uint32) (err error) //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) //sys Chdir(path string) (err error) //sys Chflags(path string, flags int) (err error) //sys Chmod(path string, mode uint32) (err error) //sys Chown(path string, uid int, gid int) (err error) //sys Chroot(path string) (err error) //sys Close(fd int) (err error) //sys Dup(fd int) (nfd int, err error) //sys Dup2(from int, to int) (err error) //sys Exit(code int) //sys Fchdir(fd int) (err error) //sys Fchflags(fd int, flags int) (err error) //sys Fchmod(fd int, mode uint32) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatfs(fd int, stat *Statfs_t) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) //sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) //sys Getdtablesize() (size int) //sysnb Getegid() (egid int) //sysnb Geteuid() (uid int) //sysnb Getgid() (gid int) //sysnb Getpgid(pid int) (pgid int, err error) //sysnb Getpgrp() (pgrp int) //sysnb Getpid() (pid int) //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) //sysnb Getrlimit(which int, lim *Rlimit) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Getuid() (uid int) //sys Issetugid() (tainted bool) //sys Kill(pid int, signum syscall.Signal) (err error) //sys Kqueue() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Link(path string, link string) (err error) //sys Listen(s int, backlog int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Mkdir(path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Readlink(path string, buf []byte) (n int, err error) //sys Rename(from string, to string) (err error) //sys Revoke(path string) (err error) //sys Rmdir(path string) (err error) //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK //sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) //sysnb Setegid(egid int) (err error) //sysnb Seteuid(euid int) (err error) //sysnb Setgid(gid int) (err error) //sys Setlogin(name string) (err error) //sysnb Setpgid(pid int, pgid int) (err error) //sys Setpriority(which int, who int, prio int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(which int, lim *Rlimit) (err error) //sysnb Setsid() (pid int, err error) //sysnb Settimeofday(tp *Timeval) (err error) //sysnb Setuid(uid int) (err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Statfs(path string, stat *Statfs_t) (err error) //sys Symlink(path string, link string) (err error) //sys Sync() (err error) //sys Truncate(path string, length int64) (err error) //sys Umask(newmask int) (oldmask int) //sys Undelete(path string) (err error) //sys Unlink(path string) (err error) //sys Unmount(path string, flags int) (err error) //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) //sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ //sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE //sys accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) /* * Unimplemented * TODO(jsing): Update this list for DragonFly. */ // Profil // Sigaction // Sigprocmask // Getlogin // Sigpending // Sigaltstack // Ioctl // Reboot // Execve // Vfork // Sbrk // Sstk // Ovadvise // Mincore // Setitimer // Swapon // Select // Sigsuspend // Readv // Writev // Nfssvc // Getfh // Quotactl // Mount // Csops // Waitid // Add_profil // Kdebug_trace // Sigreturn // Atsocket // Kqueue_from_portset_np // Kqueue_portset // Getattrlist // Setattrlist // Getdirentriesattr // Searchfs // Delete // Copyfile // Poll // Watchevent // Waitevent // Modwatch // Getxattr // Fgetxattr // Setxattr // Fsetxattr // Removexattr // Fremovexattr // Listxattr // Flistxattr // Fsctl // Initgroups // Posix_spawn // Nfsclnt // Fhopen // Minherit // Semsys // Msgsys // Shmsys // Semctl // Semget // Semop // Msgctl // Msgget // Msgsnd // Msgrcv // Shmat // Shmctl // Shmdt // Shmget // Shm_open // Shm_unlink // Sem_open // Sem_close // Sem_unlink // Sem_wait // Sem_trywait // Sem_post // Sem_getvalue // Sem_init // Sem_destroy // Open_extended // Umask_extended // Stat_extended // Lstat_extended // Fstat_extended // Chmod_extended // Fchmod_extended // Access_extended // Settid // Gettid // Setsgroups // Getsgroups // Setwgroups // Getwgroups // Mkfifo_extended // Mkdir_extended // Identitysvc // Shared_region_check_np // Shared_region_map_np // __pthread_mutex_destroy // __pthread_mutex_init // __pthread_mutex_lock // __pthread_mutex_trylock // __pthread_mutex_unlock // __pthread_cond_init // __pthread_cond_destroy // __pthread_cond_broadcast // __pthread_cond_signal // Setsid_with_pid // __pthread_cond_timedwait // Aio_fsync // Aio_return // Aio_suspend // Aio_cancel // Aio_error // Aio_read // Aio_write // Lio_listio // __pthread_cond_wait // Iopolicysys // __pthread_kill // __pthread_sigmask // __sigwait // __disable_threadsignal // __pthread_markcancel // __pthread_canceled // __semwait_signal // Proc_info // Stat64_extended // Lstat64_extended // Fstat64_extended // __pthread_chdir // __pthread_fchdir // Audit // Auditon // Getauid // Setauid // Getaudit // Setaudit // Getaudit_addr // Setaudit_addr // Auditctl // Bsdthread_create // Bsdthread_terminate // Stack_snapshot // Bsdthread_register // Workq_open // Workq_ops // __mac_execve // __mac_syscall // __mac_get_file // __mac_set_file // __mac_get_link // __mac_set_link // __mac_get_proc // __mac_set_proc // __mac_get_fd // __mac_set_fd // __mac_get_pid // __mac_get_lcid // __mac_get_lctx // __mac_set_lctx // Setlcid // Read_nocancel // Write_nocancel // Open_nocancel // Close_nocancel // Wait4_nocancel // Recvmsg_nocancel // Sendmsg_nocancel // Recvfrom_nocancel // Accept_nocancel // Fcntl_nocancel // Select_nocancel // Fsync_nocancel // Connect_nocancel // Sigsuspend_nocancel // Readv_nocancel // Writev_nocancel // Sendto_nocancel // Pread_nocancel // Pwrite_nocancel // Waitid_nocancel // Poll_nocancel // Msgsnd_nocancel // Msgrcv_nocancel // Sem_wait_nocancel // Aio_suspend_nocancel // __sigwait_nocancel // __semwait_signal_nocancel // __mac_mount // __mac_get_mount // __mac_getfsstat lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_darwin_arm64.go0000644061062106075000000000347113172163421025712 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm64,darwin package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int64(nsec / 1e9) return } //sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) func Gettimeofday(tv *Timeval) (err error) { // The tv passed to gettimeofday must be non-nil // but is otherwise unused. The answers come back // in the two registers. sec, usec, err := gettimeofday(tv) tv.Sec = sec tv.Usec = usec return err } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var length = uint64(count) _, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0) written = int(length) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // sic // SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions // of darwin/arm64 the syscall is called sysctl instead of __sysctl. const SYS___SYSCTL = SYS_SYSCTL lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_darwin_arm.go0000644061062106075000000000324413172163421025536 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int32(nsec / 1e9) return } //sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error) func Gettimeofday(tv *Timeval) (err error) { // The tv passed to gettimeofday must be non-nil // but is otherwise unused. The answers come back // in the two registers. sec, usec, err := gettimeofday(tv) tv.Sec = int32(sec) tv.Usec = int32(usec) return err } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var length = uint64(count) _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(*offset>>32), uintptr(unsafe.Pointer(&length)), 0, 0, 0, 0) written = int(length) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // sic lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_darwin_amd64.go0000644061062106075000000000346213172163421025674 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,darwin package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int64(nsec / 1e9) return } //sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) func Gettimeofday(tv *Timeval) (err error) { // The tv passed to gettimeofday must be non-nil // but is otherwise unused. The answers come back // in the two registers. sec, usec, err := gettimeofday(tv) tv.Sec = sec tv.Usec = usec return err } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var length = uint64(count) _, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0) written = int(length) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions // of darwin/amd64 the syscall is called sysctl instead of __sysctl. const SYS___SYSCTL = SYS_SYSCTL lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_darwin_386.go0000644061062106075000000000354613172163421025304 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build 386,darwin package unix import ( "syscall" "unsafe" ) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int32(nsec / 1e9) return } //sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error) func Gettimeofday(tv *Timeval) (err error) { // The tv passed to gettimeofday must be non-nil // but is otherwise unused. The answers come back // in the two registers. sec, usec, err := gettimeofday(tv) tv.Sec = int32(sec) tv.Usec = int32(usec) return err } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { var length = uint64(count) _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(*offset>>32), uintptr(unsafe.Pointer(&length)), 0, 0, 0, 0) written = int(length) if e1 != 0 { err = e1 } return } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions // of darwin/386 the syscall is called sysctl instead of __sysctl. const SYS___SYSCTL = SYS_SYSCTL lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_darwin.go0000644061062106075000000003410213172163421024674 0ustar stgraberdomain admins// Copyright 2009,2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Darwin system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and wrap // it in our own nicer implementation, either here or in // syscall_bsd.go or syscall_unix.go. package unix import ( errorspkg "errors" "syscall" "unsafe" ) const ImplementsGetwd = true func Getwd() (string, error) { buf := make([]byte, 2048) attrs, err := getAttrList(".", attrList{CommonAttr: attrCmnFullpath}, buf, 0) if err == nil && len(attrs) == 1 && len(attrs[0]) >= 2 { wd := string(attrs[0]) // Sanity check that it's an absolute path and ends // in a null byte, which we then strip. if wd[0] == '/' && wd[len(wd)-1] == 0 { return wd[:len(wd)-1], nil } } // If pkg/os/getwd.go gets ENOTSUP, it will fall back to the // slow algorithm. return "", ENOTSUP } type SockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 raw RawSockaddrDatalink } // Translate "kern.hostname" to []_C_int{0,1,2,3}. func nametomib(name string) (mib []_C_int, err error) { const siz = unsafe.Sizeof(mib[0]) // NOTE(rsc): It seems strange to set the buffer to have // size CTL_MAXNAME+2 but use only CTL_MAXNAME // as the size. I don't know why the +2 is here, but the // kernel uses +2 for its own implementation of this function. // I am scared that if we don't include the +2 here, the kernel // will silently write 2 words farther than we specify // and we'll get memory corruption. var buf [CTL_MAXNAME + 2]_C_int n := uintptr(CTL_MAXNAME) * siz p := (*byte)(unsafe.Pointer(&buf[0])) bytes, err := ByteSliceFromString(name) if err != nil { return nil, err } // Magic sysctl: "setting" 0.3 to a string name // lets you read back the array of integers form. if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { return nil, err } return buf[0 : n/siz], nil } func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) } func direntReclen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) } func direntNamlen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) } //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error) func PtraceAttach(pid int) (err error) { return ptrace(PT_ATTACH, pid, 0, 0) } func PtraceDetach(pid int) (err error) { return ptrace(PT_DETACH, pid, 0, 0) } const ( attrBitMapCount = 5 attrCmnFullpath = 0x08000000 ) type attrList struct { bitmapCount uint16 _ uint16 CommonAttr uint32 VolAttr uint32 DirAttr uint32 FileAttr uint32 Forkattr uint32 } func getAttrList(path string, attrList attrList, attrBuf []byte, options uint) (attrs [][]byte, err error) { if len(attrBuf) < 4 { return nil, errorspkg.New("attrBuf too small") } attrList.bitmapCount = attrBitMapCount var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return nil, err } _, _, e1 := Syscall6( SYS_GETATTRLIST, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(&attrList)), uintptr(unsafe.Pointer(&attrBuf[0])), uintptr(len(attrBuf)), uintptr(options), 0, ) if e1 != 0 { return nil, e1 } size := *(*uint32)(unsafe.Pointer(&attrBuf[0])) // dat is the section of attrBuf that contains valid data, // without the 4 byte length header. All attribute offsets // are relative to dat. dat := attrBuf if int(size) < len(attrBuf) { dat = dat[:size] } dat = dat[4:] // remove length prefix for i := uint32(0); int(i) < len(dat); { header := dat[i:] if len(header) < 8 { return attrs, errorspkg.New("truncated attribute header") } datOff := *(*int32)(unsafe.Pointer(&header[0])) attrLen := *(*uint32)(unsafe.Pointer(&header[4])) if datOff < 0 || uint32(datOff)+attrLen > uint32(len(dat)) { return attrs, errorspkg.New("truncated results; attrBuf too small") } end := uint32(datOff) + attrLen attrs = append(attrs, dat[datOff:end]) i = end if r := i % 4; r != 0 { i += (4 - r) } } return } //sysnb pipe() (r int, w int, err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } p[0], p[1], err = pipe() return } func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { var _p0 unsafe.Pointer var bufsize uintptr if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) } r0, _, e1 := Syscall(SYS_GETFSSTAT64, uintptr(_p0), bufsize, uintptr(flags)) n = int(r0) if e1 != 0 { err = e1 } return } func utimensat(dirfd int, path string, times *[2]Timespec, flags int) error { // Darwin doesn't support SYS_UTIMENSAT return ENOSYS } /* * Wrapped */ //sys kill(pid int, signum int, posix int) (err error) func Kill(pid int, signum syscall.Signal) (err error) { return kill(pid, int(signum), 1) } //sys ioctl(fd int, req uint, arg uintptr) (err error) // ioctl itself should not be exposed directly, but additional get/set // functions for specific types are permissible. // IoctlSetInt performs an ioctl operation which sets an integer value // on fd, using the specified request number. func IoctlSetInt(fd int, req uint, value int) error { return ioctl(fd, req, uintptr(value)) } func IoctlSetWinsize(fd int, req uint, value *Winsize) error { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermios(fd int, req uint, value *Termios) error { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } // IoctlGetInt performs an ioctl operation which gets an integer value // from fd, using the specified request number. func IoctlGetInt(fd int, req uint) (int, error) { var value int err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return value, err } func IoctlGetWinsize(fd int, req uint) (*Winsize, error) { var value Winsize err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermios(fd int, req uint) (*Termios, error) { var value Termios err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } /* * Exposed directly */ //sys Access(path string, mode uint32) (err error) //sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) //sys Chdir(path string) (err error) //sys Chflags(path string, flags int) (err error) //sys Chmod(path string, mode uint32) (err error) //sys Chown(path string, uid int, gid int) (err error) //sys Chroot(path string) (err error) //sys Close(fd int) (err error) //sys Dup(fd int) (nfd int, err error) //sys Dup2(from int, to int) (err error) //sys Exchangedata(path1 string, path2 string, options int) (err error) //sys Exit(code int) //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchdir(fd int) (err error) //sys Fchflags(fd int, flags int) (err error) //sys Fchmod(fd int, mode uint32) (err error) //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64 //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) //sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64 //sys Getdtablesize() (size int) //sysnb Getegid() (egid int) //sysnb Geteuid() (uid int) //sysnb Getgid() (gid int) //sysnb Getpgid(pid int) (pgid int, err error) //sysnb Getpgrp() (pgrp int) //sysnb Getpid() (pid int) //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) //sysnb Getrlimit(which int, lim *Rlimit) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Getuid() (uid int) //sysnb Issetugid() (tainted bool) //sys Kqueue() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Link(path string, link string) (err error) //sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) //sys Listen(s int, backlog int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys Mkdir(path string, mode uint32) (err error) //sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Readlink(path string, buf []byte) (n int, err error) //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error) //sys Rename(from string, to string) (err error) //sys Renameat(fromfd int, from string, tofd int, to string) (err error) //sys Revoke(path string) (err error) //sys Rmdir(path string) (err error) //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK //sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) //sys Setegid(egid int) (err error) //sysnb Seteuid(euid int) (err error) //sysnb Setgid(gid int) (err error) //sys Setlogin(name string) (err error) //sysnb Setpgid(pid int, pgid int) (err error) //sys Setpriority(which int, who int, prio int) (err error) //sys Setprivexec(flag int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sysnb Setrlimit(which int, lim *Rlimit) (err error) //sysnb Setsid() (pid int, err error) //sysnb Settimeofday(tp *Timeval) (err error) //sysnb Setuid(uid int) (err error) //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Statfs(path string, stat *Statfs_t) (err error) = SYS_STATFS64 //sys Symlink(path string, link string) (err error) //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error) //sys Sync() (err error) //sys Truncate(path string, length int64) (err error) //sys Umask(newmask int) (oldmask int) //sys Undelete(path string) (err error) //sys Unlink(path string) (err error) //sys Unlinkat(dirfd int, path string, flags int) (err error) //sys Unmount(path string, flags int) (err error) //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) //sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ //sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE /* * Unimplemented */ // Profil // Sigaction // Sigprocmask // Getlogin // Sigpending // Sigaltstack // Ioctl // Reboot // Execve // Vfork // Sbrk // Sstk // Ovadvise // Mincore // Setitimer // Swapon // Select // Sigsuspend // Readv // Writev // Nfssvc // Getfh // Quotactl // Mount // Csops // Waitid // Add_profil // Kdebug_trace // Sigreturn // Atsocket // Kqueue_from_portset_np // Kqueue_portset // Getattrlist // Setattrlist // Getdirentriesattr // Searchfs // Delete // Copyfile // Poll // Watchevent // Waitevent // Modwatch // Getxattr // Fgetxattr // Setxattr // Fsetxattr // Removexattr // Fremovexattr // Listxattr // Flistxattr // Fsctl // Initgroups // Posix_spawn // Nfsclnt // Fhopen // Minherit // Semsys // Msgsys // Shmsys // Semctl // Semget // Semop // Msgctl // Msgget // Msgsnd // Msgrcv // Shmat // Shmctl // Shmdt // Shmget // Shm_open // Shm_unlink // Sem_open // Sem_close // Sem_unlink // Sem_wait // Sem_trywait // Sem_post // Sem_getvalue // Sem_init // Sem_destroy // Open_extended // Umask_extended // Stat_extended // Lstat_extended // Fstat_extended // Chmod_extended // Fchmod_extended // Access_extended // Settid // Gettid // Setsgroups // Getsgroups // Setwgroups // Getwgroups // Mkfifo_extended // Mkdir_extended // Identitysvc // Shared_region_check_np // Shared_region_map_np // __pthread_mutex_destroy // __pthread_mutex_init // __pthread_mutex_lock // __pthread_mutex_trylock // __pthread_mutex_unlock // __pthread_cond_init // __pthread_cond_destroy // __pthread_cond_broadcast // __pthread_cond_signal // Setsid_with_pid // __pthread_cond_timedwait // Aio_fsync // Aio_return // Aio_suspend // Aio_cancel // Aio_error // Aio_read // Aio_write // Lio_listio // __pthread_cond_wait // Iopolicysys // __pthread_kill // __pthread_sigmask // __sigwait // __disable_threadsignal // __pthread_markcancel // __pthread_canceled // __semwait_signal // Proc_info // sendfile // Stat64_extended // Lstat64_extended // Fstat64_extended // __pthread_chdir // __pthread_fchdir // Audit // Auditon // Getauid // Setauid // Getaudit // Setaudit // Getaudit_addr // Setaudit_addr // Auditctl // Bsdthread_create // Bsdthread_terminate // Stack_snapshot // Bsdthread_register // Workq_open // Workq_ops // __mac_execve // __mac_syscall // __mac_get_file // __mac_set_file // __mac_get_link // __mac_set_link // __mac_get_proc // __mac_set_proc // __mac_get_fd // __mac_set_fd // __mac_get_pid // __mac_get_lcid // __mac_get_lctx // __mac_set_lctx // Setlcid // Read_nocancel // Write_nocancel // Open_nocancel // Close_nocancel // Wait4_nocancel // Recvmsg_nocancel // Sendmsg_nocancel // Recvfrom_nocancel // Accept_nocancel // Fcntl_nocancel // Select_nocancel // Fsync_nocancel // Connect_nocancel // Sigsuspend_nocancel // Readv_nocancel // Writev_nocancel // Sendto_nocancel // Pread_nocancel // Pwrite_nocancel // Waitid_nocancel // Poll_nocancel // Msgsnd_nocancel // Msgrcv_nocancel // Sem_wait_nocancel // Aio_suspend_nocancel // __sigwait_nocancel // __semwait_signal_nocancel // __mac_mount // __mac_get_mount // __mac_getfsstat lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_bsd_test.go0000644061062106075000000000242713172163421025224 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd openbsd package unix_test import ( "os/exec" "runtime" "testing" "golang.org/x/sys/unix" ) const MNT_WAIT = 1 const MNT_NOWAIT = 2 func TestGetfsstat(t *testing.T) { const flags = MNT_NOWAIT // see golang.org/issue/16937 n, err := unix.Getfsstat(nil, flags) if err != nil { t.Fatal(err) } data := make([]unix.Statfs_t, n) n2, err := unix.Getfsstat(data, flags) if err != nil { t.Fatal(err) } if n != n2 { t.Errorf("Getfsstat(nil) = %d, but subsequent Getfsstat(slice) = %d", n, n2) } for i, stat := range data { if stat == (unix.Statfs_t{}) { t.Errorf("index %v is an empty Statfs_t struct", i) } } if t.Failed() { for i, stat := range data[:n2] { t.Logf("data[%v] = %+v", i, stat) } mount, err := exec.Command("mount").CombinedOutput() if err != nil { t.Logf("mount: %v\n%s", err, mount) } else { t.Logf("mount: %s", mount) } } } func TestSysctlRaw(t *testing.T) { if runtime.GOOS == "openbsd" { t.Skip("kern.proc.pid does not exist on OpenBSD") } _, err := unix.SysctlRaw("kern.proc.pid", unix.Getpid()) if err != nil { t.Fatal(err) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall_bsd.go0000644061062106075000000004003413172163421024161 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd // BSD system call wrappers shared by *BSD based systems // including OS X (Darwin) and FreeBSD. Like the other // syscall_*.go files it is compiled as Go code but also // used as input to mksyscall which parses the //sys // lines and generates system call stubs. package unix import ( "runtime" "syscall" "unsafe" ) /* * Wrapped */ //sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error) //sysnb setgroups(ngid int, gid *_Gid_t) (err error) func Getgroups() (gids []int, err error) { n, err := getgroups(0, nil) if err != nil { return nil, err } if n == 0 { return nil, nil } // Sanity check group count. Max is 16 on BSD. if n < 0 || n > 1000 { return nil, EINVAL } a := make([]_Gid_t, n) n, err = getgroups(n, &a[0]) if err != nil { return nil, err } gids = make([]int, n) for i, v := range a[0:n] { gids[i] = int(v) } return } func Setgroups(gids []int) (err error) { if len(gids) == 0 { return setgroups(0, nil) } a := make([]_Gid_t, len(gids)) for i, v := range gids { a[i] = _Gid_t(v) } return setgroups(len(a), &a[0]) } func ReadDirent(fd int, buf []byte) (n int, err error) { // Final argument is (basep *uintptr) and the syscall doesn't take nil. // 64 bits should be enough. (32 bits isn't even on 386). Since the // actual system call is getdirentries64, 64 is a good guess. // TODO(rsc): Can we use a single global basep for all calls? var base = (*uintptr)(unsafe.Pointer(new(uint64))) return Getdirentries(fd, buf, base) } // Wait status is 7 bits at bottom, either 0 (exited), // 0x7F (stopped), or a signal number that caused an exit. // The 0x80 bit is whether there was a core dump. // An extra number (exit code, signal causing a stop) // is in the high bits. type WaitStatus uint32 const ( mask = 0x7F core = 0x80 shift = 8 exited = 0 stopped = 0x7F ) func (w WaitStatus) Exited() bool { return w&mask == exited } func (w WaitStatus) ExitStatus() int { if w&mask != exited { return -1 } return int(w >> shift) } func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 } func (w WaitStatus) Signal() syscall.Signal { sig := syscall.Signal(w & mask) if sig == stopped || sig == 0 { return -1 } return sig } func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP } func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP } func (w WaitStatus) StopSignal() syscall.Signal { if !w.Stopped() { return -1 } return syscall.Signal(w>>shift) & 0xFF } func (w WaitStatus) TrapCause() int { return -1 } //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { var status _C_int wpid, err = wait4(pid, &status, options, rusage) if wstatus != nil { *wstatus = WaitStatus(status) } return } //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys Shutdown(s int, how int) (err error) func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL } sa.raw.Len = SizeofSockaddrInet4 sa.raw.Family = AF_INET p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil } func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL } sa.raw.Len = SizeofSockaddrInet6 sa.raw.Family = AF_INET6 p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) sa.raw.Scope_id = sa.ZoneId for i := 0; i < len(sa.Addr); i++ { sa.raw.Addr[i] = sa.Addr[i] } return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil } func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { name := sa.Name n := len(name) if n >= len(sa.raw.Path) || n == 0 { return nil, 0, EINVAL } sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL sa.raw.Family = AF_UNIX for i := 0; i < n; i++ { sa.raw.Path[i] = int8(name[i]) } return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil } func (sa *SockaddrDatalink) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Index == 0 { return nil, 0, EINVAL } sa.raw.Len = sa.Len sa.raw.Family = AF_LINK sa.raw.Index = sa.Index sa.raw.Type = sa.Type sa.raw.Nlen = sa.Nlen sa.raw.Alen = sa.Alen sa.raw.Slen = sa.Slen for i := 0; i < len(sa.raw.Data); i++ { sa.raw.Data[i] = sa.Data[i] } return unsafe.Pointer(&sa.raw), SizeofSockaddrDatalink, nil } func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_LINK: pp := (*RawSockaddrDatalink)(unsafe.Pointer(rsa)) sa := new(SockaddrDatalink) sa.Len = pp.Len sa.Family = pp.Family sa.Index = pp.Index sa.Type = pp.Type sa.Nlen = pp.Nlen sa.Alen = pp.Alen sa.Slen = pp.Slen for i := 0; i < len(sa.Data); i++ { sa.Data[i] = pp.Data[i] } return sa, nil case AF_UNIX: pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) if pp.Len < 2 || pp.Len > SizeofSockaddrUnix { return nil, EINVAL } sa := new(SockaddrUnix) // Some BSDs include the trailing NUL in the length, whereas // others do not. Work around this by subtracting the leading // family and len. The path is then scanned to see if a NUL // terminator still exists within the length. n := int(pp.Len) - 2 // subtract leading Family, Len for i := 0; i < n; i++ { if pp.Path[i] == 0 { // found early NUL; assume Len included the NUL // or was overestimating. n = i break } } bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n] sa.Name = string(bytes) return sa, nil case AF_INET: pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) sa := new(SockaddrInet4) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil case AF_INET6: pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) sa := new(SockaddrInet6) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) sa.ZoneId = pp.Scope_id for i := 0; i < len(sa.Addr); i++ { sa.Addr[i] = pp.Addr[i] } return sa, nil } return nil, EAFNOSUPPORT } func Accept(fd int) (nfd int, sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny nfd, err = accept(fd, &rsa, &len) if err != nil { return } if runtime.GOOS == "darwin" && len == 0 { // Accepted socket has no address. // This is likely due to a bug in xnu kernels, // where instead of ECONNABORTED error socket // is accepted, but has no address. Close(nfd) return 0, nil, ECONNABORTED } sa, err = anyToSockaddr(&rsa) if err != nil { Close(nfd) nfd = 0 } return } func Getsockname(fd int) (sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny if err = getsockname(fd, &rsa, &len); err != nil { return } // TODO(jsing): DragonFly has a "bug" (see issue 3349), which should be // reported upstream. if runtime.GOOS == "dragonfly" && rsa.Addr.Family == AF_UNSPEC && rsa.Addr.Len == 0 { rsa.Addr.Family = AF_UNIX rsa.Addr.Len = SizeofSockaddrUnix } return anyToSockaddr(&rsa) } //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) func GetsockoptByte(fd, level, opt int) (value byte, err error) { var n byte vallen := _Socklen(1) err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) return n, err } func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { vallen := _Socklen(4) err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) return value, err } func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { var value IPMreq vallen := _Socklen(SizeofIPMreq) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { var value IPv6Mreq vallen := _Socklen(SizeofIPv6Mreq) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { var value IPv6MTUInfo vallen := _Socklen(SizeofIPv6MTUInfo) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { var value ICMPv6Filter vallen := _Socklen(SizeofICMPv6Filter) err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) return &value, err } //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { var msg Msghdr var rsa RawSockaddrAny msg.Name = (*byte)(unsafe.Pointer(&rsa)) msg.Namelen = uint32(SizeofSockaddrAny) var iov Iovec if len(p) > 0 { iov.Base = (*byte)(unsafe.Pointer(&p[0])) iov.SetLen(len(p)) } var dummy byte if len(oob) > 0 { // receive at least one normal byte if len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } msg.Control = (*byte)(unsafe.Pointer(&oob[0])) msg.SetControllen(len(oob)) } msg.Iov = &iov msg.Iovlen = 1 if n, err = recvmsg(fd, &msg, flags); err != nil { return } oobn = int(msg.Controllen) recvflags = int(msg.Flags) // source address is only specified if the socket is unconnected if rsa.Addr.Family != AF_UNSPEC { from, err = anyToSockaddr(&rsa) } return } //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { _, err = SendmsgN(fd, p, oob, to, flags) return } func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { var ptr unsafe.Pointer var salen _Socklen if to != nil { ptr, salen, err = to.sockaddr() if err != nil { return 0, err } } var msg Msghdr msg.Name = (*byte)(unsafe.Pointer(ptr)) msg.Namelen = uint32(salen) var iov Iovec if len(p) > 0 { iov.Base = (*byte)(unsafe.Pointer(&p[0])) iov.SetLen(len(p)) } var dummy byte if len(oob) > 0 { // send at least one normal byte if len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } msg.Control = (*byte)(unsafe.Pointer(&oob[0])) msg.SetControllen(len(oob)) } msg.Iov = &iov msg.Iovlen = 1 if n, err = sendmsg(fd, &msg, flags); err != nil { return 0, err } if len(oob) > 0 && len(p) == 0 { n = 0 } return n, nil } //sys kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) func Kevent(kq int, changes, events []Kevent_t, timeout *Timespec) (n int, err error) { var change, event unsafe.Pointer if len(changes) > 0 { change = unsafe.Pointer(&changes[0]) } if len(events) > 0 { event = unsafe.Pointer(&events[0]) } return kevent(kq, change, len(changes), event, len(events), timeout) } //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL // sysctlmib translates name to mib number and appends any additional args. func sysctlmib(name string, args ...int) ([]_C_int, error) { // Translate name to mib number. mib, err := nametomib(name) if err != nil { return nil, err } for _, a := range args { mib = append(mib, _C_int(a)) } return mib, nil } func Sysctl(name string) (string, error) { return SysctlArgs(name) } func SysctlArgs(name string, args ...int) (string, error) { buf, err := SysctlRaw(name, args...) if err != nil { return "", err } n := len(buf) // Throw away terminating NUL. if n > 0 && buf[n-1] == '\x00' { n-- } return string(buf[0:n]), nil } func SysctlUint32(name string) (uint32, error) { return SysctlUint32Args(name) } func SysctlUint32Args(name string, args ...int) (uint32, error) { mib, err := sysctlmib(name, args...) if err != nil { return 0, err } n := uintptr(4) buf := make([]byte, 4) if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { return 0, err } if n != 4 { return 0, EIO } return *(*uint32)(unsafe.Pointer(&buf[0])), nil } func SysctlUint64(name string, args ...int) (uint64, error) { mib, err := sysctlmib(name, args...) if err != nil { return 0, err } n := uintptr(8) buf := make([]byte, 8) if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { return 0, err } if n != 8 { return 0, EIO } return *(*uint64)(unsafe.Pointer(&buf[0])), nil } func SysctlRaw(name string, args ...int) ([]byte, error) { mib, err := sysctlmib(name, args...) if err != nil { return nil, err } // Find size. n := uintptr(0) if err := sysctl(mib, nil, &n, nil, 0); err != nil { return nil, err } if n == 0 { return nil, nil } // Read into buffer of that size. buf := make([]byte, n) if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { return nil, err } // The actual call may return less than the original reported required // size so ensure we deal with that. return buf[:n], nil } //sys utimes(path string, timeval *[2]Timeval) (err error) func Utimes(path string, tv []Timeval) error { if tv == nil { return utimes(path, nil) } if len(tv) != 2 { return EINVAL } return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } func UtimesNano(path string, ts []Timespec) error { if ts == nil { err := utimensat(AT_FDCWD, path, nil, 0) if err != ENOSYS { return err } return utimes(path, nil) } if len(ts) != 2 { return EINVAL } err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) if err != ENOSYS { return err } // Not as efficient as it could be because Timespec and // Timeval have different types in the different OSes tv := [2]Timeval{ NsecToTimeval(TimespecToNsec(ts[0])), NsecToTimeval(TimespecToNsec(ts[1])), } return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { if ts == nil { return utimensat(dirfd, path, nil, flags) } if len(ts) != 2 { return EINVAL } return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) } //sys futimes(fd int, timeval *[2]Timeval) (err error) func Futimes(fd int, tv []Timeval) error { if tv == nil { return futimes(fd, nil) } if len(tv) != 2 { return EINVAL } return futimes(fd, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } //sys fcntl(fd int, cmd int, arg int) (val int, err error) // TODO: wrap // Acct(name nil-string) (err error) // Gethostuuid(uuid *byte, timeout *Timespec) (err error) // Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error) var mapper = &mmapper{ active: make(map[*byte][]byte), mmap: mmap, munmap: munmap, } func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { return mapper.Mmap(fd, offset, length, prot, flags) } func Munmap(b []byte) (err error) { return mapper.Munmap(b) } //sys Madvise(b []byte, behav int) (err error) //sys Mlock(b []byte) (err error) //sys Mlockall(flags int) (err error) //sys Mprotect(b []byte, prot int) (err error) //sys Msync(b []byte, flags int) (err error) //sys Munlock(b []byte) (err error) //sys Munlockall() (err error) lxd-2.0.11/dist/src/golang.org/x/sys/unix/syscall.go0000644061062106075000000000465113172163421023336 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris // Package unix contains an interface to the low-level operating system // primitives. OS details vary depending on the underlying system, and // by default, godoc will display OS-specific documentation for the current // system. If you want godoc to display OS documentation for another // system, set $GOOS and $GOARCH to the desired system. For example, if // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS // to freebsd and $GOARCH to arm. // The primary use of this package is inside other packages that provide a more // portable interface to the system, such as "os", "time" and "net". Use // those packages rather than this one if you can. // For details of the functions and data types in this package consult // the manuals for the appropriate operating system. // These calls return err == nil to indicate success; otherwise // err represents an operating system error describing the failure and // holds a value of type syscall.Errno. package unix // import "golang.org/x/sys/unix" // ByteSliceFromString returns a NUL-terminated slice of bytes // containing the text of s. If s contains a NUL byte at any // location, it returns (nil, EINVAL). func ByteSliceFromString(s string) ([]byte, error) { for i := 0; i < len(s); i++ { if s[i] == 0 { return nil, EINVAL } } a := make([]byte, len(s)+1) copy(a, s) return a, nil } // BytePtrFromString returns a pointer to a NUL-terminated array of // bytes containing the text of s. If s contains a NUL byte at any // location, it returns (nil, EINVAL). func BytePtrFromString(s string) (*byte, error) { a, err := ByteSliceFromString(s) if err != nil { return nil, err } return &a[0], nil } // Single-word zero for use when we need a valid pointer to 0 bytes. // See mkunix.pl. var _zero uintptr func (ts *Timespec) Unix() (sec int64, nsec int64) { return int64(ts.Sec), int64(ts.Nsec) } func (tv *Timeval) Unix() (sec int64, nsec int64) { return int64(tv.Sec), int64(tv.Usec) * 1000 } func (ts *Timespec) Nano() int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func (tv *Timeval) Nano() int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 } func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } lxd-2.0.11/dist/src/golang.org/x/sys/unix/str.go0000644061062106075000000000114313172163421022465 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix func itoa(val int) string { // do it here rather than with fmt to avoid dependency if val < 0 { return "-" + uitoa(uint(-val)) } return uitoa(uint(val)) } func uitoa(val uint) string { var buf [32]byte // big enough for int64 i := len(buf) - 1 for val >= 10 { buf[i] = byte(val%10 + '0') i-- val /= 10 } buf[i] = byte(val + '0') return string(buf[i:]) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/sockcmsg_unix.go0000644061062106075000000000567413172163421024546 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris // Socket control messages package unix import "unsafe" // Round the length of a raw sockaddr up to align it properly. func cmsgAlignOf(salen int) int { salign := sizeofPtr // NOTE: It seems like 64-bit Darwin, DragonFly BSD and // Solaris kernels still require 32-bit aligned access to // network subsystem. if darwin64Bit || dragonfly64Bit || solaris64Bit { salign = 4 } return (salen + salign - 1) & ^(salign - 1) } // CmsgLen returns the value to store in the Len field of the Cmsghdr // structure, taking into account any necessary alignment. func CmsgLen(datalen int) int { return cmsgAlignOf(SizeofCmsghdr) + datalen } // CmsgSpace returns the number of bytes an ancillary element with // payload of the passed data length occupies. func CmsgSpace(datalen int) int { return cmsgAlignOf(SizeofCmsghdr) + cmsgAlignOf(datalen) } func cmsgData(h *Cmsghdr) unsafe.Pointer { return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(SizeofCmsghdr))) } // SocketControlMessage represents a socket control message. type SocketControlMessage struct { Header Cmsghdr Data []byte } // ParseSocketControlMessage parses b as an array of socket control // messages. func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error) { var msgs []SocketControlMessage i := 0 for i+CmsgLen(0) <= len(b) { h, dbuf, err := socketControlMessageHeaderAndData(b[i:]) if err != nil { return nil, err } m := SocketControlMessage{Header: *h, Data: dbuf} msgs = append(msgs, m) i += cmsgAlignOf(int(h.Len)) } return msgs, nil } func socketControlMessageHeaderAndData(b []byte) (*Cmsghdr, []byte, error) { h := (*Cmsghdr)(unsafe.Pointer(&b[0])) if h.Len < SizeofCmsghdr || uint64(h.Len) > uint64(len(b)) { return nil, nil, EINVAL } return h, b[cmsgAlignOf(SizeofCmsghdr):h.Len], nil } // UnixRights encodes a set of open file descriptors into a socket // control message for sending to another process. func UnixRights(fds ...int) []byte { datalen := len(fds) * 4 b := make([]byte, CmsgSpace(datalen)) h := (*Cmsghdr)(unsafe.Pointer(&b[0])) h.Level = SOL_SOCKET h.Type = SCM_RIGHTS h.SetLen(CmsgLen(datalen)) data := cmsgData(h) for _, fd := range fds { *(*int32)(data) = int32(fd) data = unsafe.Pointer(uintptr(data) + 4) } return b } // ParseUnixRights decodes a socket control message that contains an // integer array of open file descriptors from another process. func ParseUnixRights(m *SocketControlMessage) ([]int, error) { if m.Header.Level != SOL_SOCKET { return nil, EINVAL } if m.Header.Type != SCM_RIGHTS { return nil, EINVAL } fds := make([]int, len(m.Data)>>2) for i, j := 0, 0; i < len(m.Data); i += 4 { fds[j] = int(*(*int32)(unsafe.Pointer(&m.Data[i]))) j++ } return fds, nil } lxd-2.0.11/dist/src/golang.org/x/sys/unix/sockcmsg_linux.go0000644061062106075000000000206013172163421024704 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Socket control messages package unix import "unsafe" // UnixCredentials encodes credentials into a socket control message // for sending to another process. This can be used for // authentication. func UnixCredentials(ucred *Ucred) []byte { b := make([]byte, CmsgSpace(SizeofUcred)) h := (*Cmsghdr)(unsafe.Pointer(&b[0])) h.Level = SOL_SOCKET h.Type = SCM_CREDENTIALS h.SetLen(CmsgLen(SizeofUcred)) *((*Ucred)(cmsgData(h))) = *ucred return b } // ParseUnixCredentials decodes a socket control message that contains // credentials in a Ucred structure. To receive such a message, the // SO_PASSCRED option must be enabled on the socket. func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error) { if m.Header.Level != SOL_SOCKET { return nil, EINVAL } if m.Header.Type != SCM_CREDENTIALS { return nil, EINVAL } ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0])) return &ucred, nil } lxd-2.0.11/dist/src/golang.org/x/sys/unix/race0.go0000644061062106075000000000077213172163421022656 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin,!race linux,!race freebsd,!race netbsd openbsd solaris dragonfly package unix import ( "unsafe" ) const raceenabled = false func raceAcquire(addr unsafe.Pointer) { } func raceReleaseMerge(addr unsafe.Pointer) { } func raceReadRange(addr unsafe.Pointer, len int) { } func raceWriteRange(addr unsafe.Pointer, len int) { } lxd-2.0.11/dist/src/golang.org/x/sys/unix/race.go0000644061062106075000000000114013172163421022564 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin,race linux,race freebsd,race package unix import ( "runtime" "unsafe" ) const raceenabled = true func raceAcquire(addr unsafe.Pointer) { runtime.RaceAcquire(addr) } func raceReleaseMerge(addr unsafe.Pointer) { runtime.RaceReleaseMerge(addr) } func raceReadRange(addr unsafe.Pointer, len int) { runtime.RaceReadRange(addr, len) } func raceWriteRange(addr unsafe.Pointer, len int) { runtime.RaceWriteRange(addr, len) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/pagesize_unix.go0000644061062106075000000000055413172163421024534 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris // For Unix, get the pagesize from the runtime. package unix import "syscall" func Getpagesize() int { return syscall.Getpagesize() } lxd-2.0.11/dist/src/golang.org/x/sys/unix/openbsd_test.go0000644061062106075000000000471013172163421024351 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build openbsd // This, on the face of it, bizarre testing mechanism is necessary because // the only reliable way to gauge whether or not a pledge(2) call has succeeded // is that the program has been killed as a result of breaking its pledge. package unix_test import ( "flag" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "testing" "golang.org/x/sys/unix" ) type testProc struct { fn func() // should always exit instead of returning cleanup func() error // for instance, delete coredumps from testing pledge success bool // whether zero-exit means success or failure } var ( testProcs = map[string]testProc{} procName = "" ) const ( optName = "sys-unix-internal-procname" ) func init() { flag.StringVar(&procName, optName, "", "internal use only") } // testCmd generates a proper command that, when executed, runs the test // corresponding to the given key. func testCmd(procName string) (*exec.Cmd, error) { exe, err := filepath.Abs(os.Args[0]) if err != nil { return nil, err } cmd := exec.Command(exe, "-"+optName+"="+procName) cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr return cmd, nil } // ExitsCorrectly is a comprehensive, one-line-of-use wrapper for testing // a testProc with a key. func ExitsCorrectly(procName string, t *testing.T) { s := testProcs[procName] c, err := testCmd(procName) defer func() { if s.cleanup() != nil { t.Fatalf("Failed to run cleanup for %s", procName) } }() if err != nil { t.Fatalf("Failed to construct command for %s", procName) } if (c.Run() == nil) != s.success { result := "succeed" if !s.success { result = "fail" } t.Fatalf("Process did not %s when it was supposed to", result) } } func TestMain(m *testing.M) { flag.Parse() if procName != "" { testProcs[procName].fn() } os.Exit(m.Run()) } // For example, add a test for pledge. func init() { testProcs["pledge"] = testProc{ func() { fmt.Println(unix.Pledge("", nil)) os.Exit(0) }, func() error { files, err := ioutil.ReadDir(".") if err != nil { return err } for _, file := range files { if filepath.Ext(file.Name()) == ".core" { if err := os.Remove(file.Name()); err != nil { return err } } } return nil }, false, } } func TestPledge(t *testing.T) { ExitsCorrectly("pledge", t) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/openbsd_pledge.go0000644061062106075000000000157113172163421024634 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build openbsd // +build 386 amd64 arm package unix import ( "syscall" "unsafe" ) const ( SYS_PLEDGE = 108 ) // Pledge implements the pledge syscall. For more information see pledge(2). func Pledge(promises string, paths []string) error { promisesPtr, err := syscall.BytePtrFromString(promises) if err != nil { return err } promisesUnsafe, pathsUnsafe := unsafe.Pointer(promisesPtr), unsafe.Pointer(nil) if paths != nil { var pathsPtr []*byte if pathsPtr, err = syscall.SlicePtrFromStrings(paths); err != nil { return err } pathsUnsafe = unsafe.Pointer(&pathsPtr[0]) } _, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(promisesUnsafe), uintptr(pathsUnsafe), 0) if e != 0 { return e } return nil } lxd-2.0.11/dist/src/golang.org/x/sys/unix/mmap_unix_test.go0000644061062106075000000000151413172163421024713 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix_test import ( "testing" "golang.org/x/sys/unix" ) func TestMmap(t *testing.T) { b, err := unix.Mmap(-1, 0, unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE) if err != nil { t.Fatalf("Mmap: %v", err) } if err := unix.Mprotect(b, unix.PROT_READ|unix.PROT_WRITE); err != nil { t.Fatalf("Mprotect: %v", err) } b[0] = 42 if err := unix.Msync(b, unix.MS_SYNC); err != nil { t.Fatalf("Msync: %v", err) } if err := unix.Madvise(b, unix.MADV_DONTNEED); err != nil { t.Fatalf("Madvise: %v", err) } if err := unix.Munmap(b); err != nil { t.Fatalf("Munmap: %v", err) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/mksysnum_openbsd.pl0000755061062106075000000000202413172163421025265 0ustar stgraberdomain admins#!/usr/bin/env perl # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # # Generate system call table for OpenBSD from master list # (for example, /usr/src/sys/kern/syscalls.master). use strict; if($ENV{'GOARCH'} eq "" || $ENV{'GOOS'} eq "") { print STDERR "GOARCH or GOOS not defined in environment\n"; exit 1; } my $command = "mksysnum_openbsd.pl " . join(' ', @ARGV); print <){ if(/^([0-9]+)\s+STD\s+(NOLOCK\s+)?({ \S+\s+\*?(\w+).*)$/){ my $num = $1; my $proto = $3; my $name = $4; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } print " $name = $num; // $proto\n"; } } print <){ if($line =~ /^(.*)\\$/) { # Handle continuation $line = $1; $_ =~ s/^\s+//; $line .= $_; } else { # New line $line = $_; } next if $line =~ /\\$/; if($line =~ /^([0-9]+)\s+((STD)|(NOERR))\s+(RUMP\s+)?({\s+\S+\s*\*?\s*\|(\S+)\|(\S*)\|(\w+).*\s+})(\s+(\S+))?$/) { my $num = $1; my $proto = $6; my $compat = $8; my $name = "$7_$9"; $name = "$7_$11" if $11 ne ''; $name =~ y/a-z/A-Z/; if($compat eq '' || $compat eq '13' || $compat eq '30' || $compat eq '50') { print " $name = $num; // $proto\n"; } } } print <){ if(/^([0-9]+)\s+\S+\s+STD\s+({ \S+\s+(\w+).*)$/){ my $num = $1; my $proto = $2; my $name = "SYS_$3"; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } print " $name = $num; // $proto\n"; } } print <){ if(/^([0-9]+)\s+STD\s+({ \S+\s+(\w+).*)$/){ my $num = $1; my $proto = $2; my $name = "SYS_$3"; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } print " $name = $num; // $proto\n"; } } print <){ if(/^#define\s+SYS_(\w+)\s+([0-9]+)/){ my $name = $1; my $num = $2; $name =~ y/a-z/A-Z/; print " SYS_$name = $num;" } } print < "net.inet", "net.inet.ipproto" => "net.inet", "net.inet6.ipv6proto" => "net.inet6", "net.inet6.ipv6" => "net.inet6.ip6", "net.inet.icmpv6" => "net.inet6.icmp6", "net.inet6.divert6" => "net.inet6.divert", "net.inet6.tcp6" => "net.inet.tcp", "net.inet6.udp6" => "net.inet.udp", "mpls" => "net.mpls", "swpenc" => "vm.swapencrypt" ); # Node mappings my %node_map = ( "net.inet.ip.ifq" => "net.ifq", "net.inet.pfsync" => "net.pfsync", "net.mpls.ifq" => "net.ifq" ); my $ctlname; my %mib = (); my %sysctl = (); my $node; sub debug() { print STDERR "$_[0]\n" if $debug; } # Walk the MIB and build a sysctl name to OID mapping. sub build_sysctl() { my ($node, $name, $oid) = @_; my %node = %{$node}; my @oid = @{$oid}; foreach my $key (sort keys %node) { my @node = @{$node{$key}}; my $nodename = $name.($name ne '' ? '.' : '').$key; my @nodeoid = (@oid, $node[0]); if ($node[1] eq 'CTLTYPE_NODE') { if (exists $node_map{$nodename}) { $node = \%mib; $ctlname = $node_map{$nodename}; foreach my $part (split /\./, $ctlname) { $node = \%{@{$$node{$part}}[2]}; } } else { $node = $node[2]; } &build_sysctl($node, $nodename, \@nodeoid); } elsif ($node[1] ne '') { $sysctl{$nodename} = \@nodeoid; } } } foreach my $ctl (@ctls) { $ctls{$ctl} = $ctl; } # Build MIB foreach my $header (@headers) { &debug("Processing $header..."); open HEADER, "/usr/include/$header" || print STDERR "Failed to open $header\n"; while (
) { if ($_ =~ /^#define\s+(CTL_NAMES)\s+{/ || $_ =~ /^#define\s+(CTL_(.*)_NAMES)\s+{/ || $_ =~ /^#define\s+((.*)CTL_NAMES)\s+{/) { if ($1 eq 'CTL_NAMES') { # Top level. $node = \%mib; } else { # Node. my $nodename = lc($2); if ($header =~ /^netinet\//) { $ctlname = "net.inet.$nodename"; } elsif ($header =~ /^netinet6\//) { $ctlname = "net.inet6.$nodename"; } elsif ($header =~ /^net\//) { $ctlname = "net.$nodename"; } else { $ctlname = "$nodename"; $ctlname =~ s/^(fs|net|kern)_/$1\./; } if (exists $ctl_map{$ctlname}) { $ctlname = $ctl_map{$ctlname}; } if (not exists $ctls{$ctlname}) { &debug("Ignoring $ctlname..."); next; } # Walk down from the top of the MIB. $node = \%mib; foreach my $part (split /\./, $ctlname) { if (not exists $$node{$part}) { &debug("Missing node $part"); $$node{$part} = [ 0, '', {} ]; } $node = \%{@{$$node{$part}}[2]}; } } # Populate current node with entries. my $i = -1; while (defined($_) && $_ !~ /^}/) { $_ =
; $i++ if $_ =~ /{.*}/; next if $_ !~ /{\s+"(\w+)",\s+(CTLTYPE_[A-Z]+)\s+}/; $$node{$1} = [ $i, $2, {} ]; } } } close HEADER; } &build_sysctl(\%mib, "", []); print <) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; $package = $1 if !$package && /^package (\S+)$/; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, err error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($nb, $func, $in, $out, $modname, $sysname) = ($1, $2, $3, $4, $5, $6); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # So file name. if($modname eq "") { $modname = "libc"; } # System call name. if($sysname eq "") { $sysname = "$func"; } # System call pointer variable name. my $sysvarname = "proc$sysname"; my $strconvfunc = "BytePtrFromString"; my $strconvtype = "*byte"; $sysname =~ y/A-Z/a-z/; # All libc functions are lowercase. # Runtime import of function to allow cross-platform builds. $dynimports .= "//go:cgo_import_dynamic libc_${sysname} ${sysname} \"$modname.so\"\n"; # Link symbol to proc address variable. $linknames .= "//go:linkname ${sysvarname} libc_${sysname}\n"; # Library proc address variable. push @vars, $sysvarname; # Go function header. $out = join(', ', @out); if($out ne "") { $out = " ($out)"; } if($text ne "") { $text .= "\n" } $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n $strconvtype\n"; $text .= "\t_p$n, $errvar = $strconvfunc($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n $strconvtype\n"; $text .= "\t_p$n, _ = $strconvfunc($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass nil in that case. $text .= "\tvar _p$n *$1\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = \&$name\[0]\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && $_32bit ne "") { if($_32bit eq "big-endian") { push @args, "uintptr($name >> 32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name >> 32)"; } } elsif($type eq "bool") { $text .= "\tvar _p$n uint32\n"; $text .= "\tif $name {\n\t\t_p$n = 1\n\t} else {\n\t\t_p$n = 0\n\t}\n"; push @args, "uintptr(_p$n)"; $n++; } else { push @args, "uintptr($name)"; } } my $nargs = @args; # Determine which form to use; pad args with zeros. my $asm = "sysvicall6"; if ($nonblock) { $asm = "rawSysvicall6"; } if(@args <= 6) { while(@args < 6) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # Actual call. my $args = join(', ', @args); my $call = "$asm(uintptr(unsafe.Pointer(&$sysvarname)), $nargs, $args)"; # Assign return values. my $body = ""; my $failexpr = ""; my @ret = ("_", "_", "_"); my @pout= (); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err") { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1") { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } $text .= $body; if ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n"; } if($errors) { exit 1; } print <) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, errno error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($func, $in, $out, $sysname) = ($2, $3, $4, $5); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # Try in vain to keep people from editing this file. # The theory is that they jump into the middle of the file # without reading the header. $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; # Go function header. my $out_decl = @out ? sprintf(" (%s)", join(', ', @out)) : ""; $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out_decl; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, $errvar = BytePtrFromString($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, _ = BytePtrFromString($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass dummy pointer in that case. # Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). $text .= "\tvar _p$n unsafe.Pointer\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = unsafe.Pointer(\&${name}[0])\n\t}"; $text .= " else {\n\t\t_p$n = unsafe.Pointer(&_zero)\n\t}"; $text .= "\n"; push @args, "uintptr(_p$n)", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && ($openbsd || $netbsd)) { push @args, "0"; if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $dragonfly) { if ($func !~ /^extp(read|write)/i) { push @args, "0"; } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $_32bit ne "") { if(@args % 2 && $arm) { # arm abi specifies 64-bit argument uses # (even, odd) pair push @args, "0" } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name>>32)"; } } else { push @args, "uintptr($name)"; } } # Determine which form to use; pad args with zeros. my $asm = "Syscall"; if ($nonblock) { $asm = "RawSyscall"; } if(@args <= 3) { while(@args < 3) { push @args, "0"; } } elsif(@args <= 6) { $asm .= "6"; while(@args < 6) { push @args, "0"; } } elsif(@args <= 9) { $asm .= "9"; while(@args < 9) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # System call number. if($sysname eq "") { $sysname = "SYS_$func"; $sysname =~ s/([a-z])([A-Z])/${1}_$2/g; # turn FooBar into Foo_Bar $sysname =~ y/a-z/A-Z/; } # Actual call. my $args = join(', ', @args); my $call = "$asm($sysname, $args)"; # Assign return values. my $body = ""; my @ret = ("_", "_", "_"); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err" && !$plan9) { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } elsif($name eq "err" && $plan9) { $ret[0] = "r0"; $ret[2] = "e1"; next; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1" || $plan9) { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } $text .= $body; if ($plan9 && $ret[2] eq "e1") { $text .= "\tif int32(r0) == -1 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } elsif ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = errnoErr(e1)\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n\n"; } chomp $text; chomp $text; if($errors) { exit 1; } print <&2 "GOARCH or GOOS not defined in environment" exit 1 fi # Check that we are using the new build system if we should if [[ "$GOOS" = "linux" ]] && [[ "$GOARCH" != "sparc64" ]]; then if [[ "$GOLANG_SYS_BUILD" != "docker" ]]; then echo 1>&2 "In the new build system, mkerrors should not be called directly." echo 1>&2 "See README.md" exit 1 fi fi CC=${CC:-cc} if [[ "$GOOS" = "solaris" ]]; then # Assumes GNU versions of utilities in PATH. export PATH=/usr/gnu/bin:$PATH fi uname=$(uname) includes_Darwin=' #define _DARWIN_C_SOURCE #define KERNEL #define _DARWIN_USE_64_BIT_INODE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes_DragonFly=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes_FreeBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __FreeBSD__ >= 10 #define IFT_CARP 0xf8 // IFT_CARP is deprecated in FreeBSD 10 #undef SIOCAIFADDR #define SIOCAIFADDR _IOW(105, 26, struct oifaliasreq) // ifaliasreq contains if_data #undef SIOCSIFPHYADDR #define SIOCSIFPHYADDR _IOW(105, 70, struct oifaliasreq) // ifaliasreq contains if_data #endif ' includes_Linux=' #define _LARGEFILE_SOURCE #define _LARGEFILE64_SOURCE #ifndef __LP64__ #define _FILE_OFFSET_BITS 64 #endif #define _GNU_SOURCE // is broken on powerpc64, as it fails to include definitions of // these structures. We just include them copied from . #if defined(__powerpc__) struct sgttyb { char sg_ispeed; char sg_ospeed; char sg_erase; char sg_kill; short sg_flags; }; struct tchars { char t_intrc; char t_quitc; char t_startc; char t_stopc; char t_eofc; char t_brkc; }; struct ltchars { char t_suspc; char t_dsuspc; char t_rprntc; char t_flushc; char t_werasc; char t_lnextc; }; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef MSG_FASTOPEN #define MSG_FASTOPEN 0x20000000 #endif #ifndef PTRACE_GETREGS #define PTRACE_GETREGS 0xc #endif #ifndef PTRACE_SETREGS #define PTRACE_SETREGS 0xd #endif #ifndef SOL_NETLINK #define SOL_NETLINK 270 #endif #ifdef SOL_BLUETOOTH // SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h // but it is already in bluetooth_linux.go #undef SOL_BLUETOOTH #endif // Certain constants are missing from the fs/crypto UAPI #define FS_KEY_DESC_PREFIX "fscrypt:" #define FS_KEY_DESC_PREFIX_SIZE 8 #define FS_MAX_KEY_SIZE 64 ' includes_NetBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Needed since refers to it... #define schedppq 1 ' includes_OpenBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // We keep some constants not supported in OpenBSD 5.5 and beyond for // the promise of compatibility. #define EMUL_ENABLED 0x1 #define EMUL_NATIVE 0x2 #define IPV6_FAITH 0x1d #define IPV6_OPTIONS 0x1 #define IPV6_RTHDR_STRICT 0x1 #define IPV6_SOCKOPT_RESERVED1 0x3 #define SIOCGIFGENERIC 0xc020693a #define SIOCSIFGENERIC 0x80206939 #define WALTSIG 0x4 ' includes_SunOS=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' ccflags="$@" # Write go tool cgo -godefs input. ( echo package unix echo echo '/*' indirect="includes_$(uname)" echo "${!indirect} $includes" echo '*/' echo 'import "C"' echo 'import "syscall"' echo echo 'const (' # The gcc command line prints all the #defines # it encounters while processing the input echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | awk ' $1 != "#define" || $2 ~ /\(/ || $3 == "" {next} $2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers $2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next} $2 ~ /^(SCM_SRCRT)$/ {next} $2 ~ /^(MAP_FAILED)$/ {next} $2 ~ /^ELF_.*$/ {next}# contains ELF_ARCH, etc. $2 ~ /^EXTATTR_NAMESPACE_NAMES/ || $2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next} $2 !~ /^ETH_/ && $2 !~ /^EPROC_/ && $2 !~ /^EQUIV_/ && $2 !~ /^EXPR_/ && $2 ~ /^E[A-Z0-9_]+$/ || $2 ~ /^B[0-9_]+$/ || $2 ~ /^(OLD|NEW)DEV$/ || $2 == "BOTHER" || $2 ~ /^CI?BAUD(EX)?$/ || $2 == "IBSHIFT" || $2 ~ /^V[A-Z0-9]+$/ || $2 ~ /^CS[A-Z0-9]/ || $2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ || $2 ~ /^IGN/ || $2 ~ /^IX(ON|ANY|OFF)$/ || $2 ~ /^IN(LCR|PCK)$/ || $2 ~ /(^FLU?SH)|(FLU?SH$)/ || $2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ || $2 == "BRKINT" || $2 == "HUPCL" || $2 == "PENDIN" || $2 == "TOSTOP" || $2 == "XCASE" || $2 == "ALTWERASE" || $2 == "NOKERNINFO" || $2 ~ /^PAR/ || $2 ~ /^SIG[^_]/ || $2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ || $2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ || $2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ || $2 ~ /^O?XTABS$/ || $2 ~ /^TC[IO](ON|OFF)$/ || $2 ~ /^IN_/ || $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || $2 ~ /^FALLOC_/ || $2 == "ICMPV6_FILTER" || $2 == "SOMAXCONN" || $2 == "NAME_MAX" || $2 == "IFNAMSIZ" || $2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ || $2 ~ /^SYSCTL_VERS/ || $2 ~ /^(MS|MNT|UMOUNT)_/ || $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || $2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ || $2 ~ /^LINUX_REBOOT_CMD_/ || $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || $2 !~ "NLA_TYPE_MASK" && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || $2 ~ /^TCGET/ || $2 ~ /^TCSET/ || $2 ~ /^TC(FLSH|SBRKP?|XONC)$/ || $2 !~ "RTF_BITS" && $2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ || $2 ~ /^BIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || $2 ~ /^CLONE_[A-Z_]+/ || $2 !~ /^(BPF_TIMEVAL)$/ && $2 ~ /^(BPF|DLT)_/ || $2 ~ /^CLOCK_/ || $2 ~ /^CAN_/ || $2 ~ /^CAP_/ || $2 ~ /^ALG_/ || $2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ || $2 ~ /^GRND_/ || $2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ || $2 ~ /^KEYCTL_/ || $2 ~ /^PERF_EVENT_IOC_/ || $2 ~ /^SECCOMP_MODE_/ || $2 ~ /^SPLICE_/ || $2 ~ /^(VM|VMADDR)_/ || $2 ~ /^(TASKSTATS|TS)_/ || $2 ~ /^GENL_/ || $2 ~ /^XATTR_(CREATE|REPLACE)/ || $2 !~ "WMESGLEN" && $2 ~ /^W[A-Z0-9]+$/ || $2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)} $2 ~ /^__WCOREFLAG$/ {next} $2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)} {next} ' | sort echo ')' ) >_const.go # Pull out the error names for later. errors=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | sort ) # Pull out the signal names for later. signals=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort ) # Again, writing regexps to a file. echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | sort >_error.grep echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort >_signal.grep echo '// mkerrors.sh' "$@" echo '// Code generated by the command above; see README.md. DO NOT EDIT.' echo echo "// +build ${GOARCH},${GOOS}" echo go tool cgo -godefs -- "$@" _const.go >_error.out cat _error.out | grep -vf _error.grep | grep -vf _signal.grep echo echo '// Errors' echo 'const (' cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/' echo ')' echo echo '// Signals' echo 'const (' cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/' echo ')' # Run C program to print error and syscall strings. ( echo -E " #include #include #include #include #include #include #define nelem(x) (sizeof(x)/sizeof((x)[0])) enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below int errors[] = { " for i in $errors do echo -E ' '$i, done echo -E " }; int signals[] = { " for i in $signals do echo -E ' '$i, done # Use -E because on some systems bash builtin interprets \n itself. echo -E ' }; static int intcmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } int main(void) { int i, e; char buf[1024], *p; printf("\n\n// Error table\n"); printf("var errors = [...]string {\n"); qsort(errors, nelem(errors), sizeof errors[0], intcmp); for(i=0; i 0 && errors[i-1] == e) continue; strcpy(buf, strerror(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); printf("\n\n// Signal table\n"); printf("var signals = [...]string {\n"); qsort(signals, nelem(signals), sizeof signals[0], intcmp); for(i=0; i 0 && signals[i-1] == e) continue; strcpy(buf, strsignal(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; // cut trailing : number. p = strrchr(buf, ":"[0]); if(p) *p = '\0'; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); return 0; } ' ) >_errors.c $CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out lxd-2.0.11/dist/src/golang.org/x/sys/unix/mkall.sh0000755061062106075000000001451213172163421022771 0ustar stgraberdomain admins#!/usr/bin/env bash # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # This script runs or (given -n) prints suggested commands to generate files for # the Architecture/OS specified by the GOARCH and GOOS environment variables. # See README.md for more information about how the build system works. GOOSARCH="${GOOS}_${GOARCH}" # defaults mksyscall="./mksyscall.pl" mkerrors="./mkerrors.sh" zerrors="zerrors_$GOOSARCH.go" mksysctl="" zsysctl="zsysctl_$GOOSARCH.go" mksysnum= mktypes= run="sh" cmd="" case "$1" in -syscalls) for i in zsyscall*go do # Run the command line that appears in the first line # of the generated file to regenerate it. sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i rm _$i done exit 0 ;; -n) run="cat" cmd="echo" shift esac case "$#" in 0) ;; *) echo 'usage: mkall.sh [-n]' 1>&2 exit 2 esac if [[ "$GOOS" = "linux" ]] && [[ "$GOARCH" != "sparc64" ]]; then # Use then new build system # Files generated through docker (use $cmd so you can Ctl-C the build or run) $cmd docker build --tag generate:$GOOS $GOOS $cmd docker run --interactive --tty --volume $(dirname "$(readlink -f "$0")"):/build generate:$GOOS exit fi GOOSARCH_in=syscall_$GOOSARCH.go case "$GOOSARCH" in _* | *_ | _) echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 exit 1 ;; darwin_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_amd64) mkerrors="$mkerrors -m64" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_arm) mkerrors="$mkerrors" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_arm64) mkerrors="$mkerrors -m64" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; dragonfly_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -dragonfly" mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; dragonfly_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -dragonfly" mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_amd64) mkerrors="$mkerrors -m64" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_arm) mkerrors="$mkerrors" mksyscall="./mksyscall.pl -l32 -arm" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" # Let the type of C char be signed for making the bare syscall # API consistent across platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; linux_sparc64) GOOSARCH_in=syscall_linux_sparc64.go unistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h mkerrors="$mkerrors -m64" mksysnum="./mksysnum_linux.pl $unistd_h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -netbsd" mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -netbsd" mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_arm) mkerrors="$mkerrors" mksyscall="./mksyscall.pl -l32 -netbsd -arm" mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" # Let the type of C char be signed for making the bare syscall # API consistent across platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; openbsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -openbsd" mksysctl="./mksysctl_openbsd.pl" mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -openbsd" mksysctl="./mksysctl_openbsd.pl" mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_arm) mkerrors="$mkerrors" mksyscall="./mksyscall.pl -l32 -openbsd -arm" mksysctl="./mksysctl_openbsd.pl" mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" # Let the type of C char be signed for making the bare syscall # API consistent across platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; solaris_amd64) mksyscall="./mksyscall_solaris.pl" mkerrors="$mkerrors -m64" mksysnum= mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 ;; esac ( if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi case "$GOOS" in *) syscall_goos="syscall_$GOOS.go" case "$GOOS" in darwin | dragonfly | freebsd | netbsd | openbsd) syscall_goos="syscall_bsd.go $syscall_goos" ;; esac if [ -n "$mksyscall" ]; then echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi ;; esac if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi ) | $run lxd-2.0.11/dist/src/golang.org/x/sys/unix/linux/0000755061062106075000000000000013172163421022466 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/unix/linux/types.go0000644061062106075000000003716113172163421024171 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See README.md */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define _LARGEFILE_SOURCE #define _LARGEFILE64_SOURCE #define _FILE_OFFSET_BITS 64 #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // On mips64, the glibc stat and kernel stat do not agree #if (defined(__mips__) && _MIPS_SIM == _MIPS_SIM_ABI64) // Use the stat defined by the kernel with a few modifications. These are: // * The time fields (like st_atime and st_atimensec) use the timespec // struct (like st_atim) for consitancy with the glibc fields. // * The padding fields get different names to not break compatibility. // * st_blocks is signed, again for compatibility. struct stat { unsigned int st_dev; unsigned int st_pad1[3]; // Reserved for st_dev expansion unsigned long st_ino; mode_t st_mode; __u32 st_nlink; uid_t st_uid; gid_t st_gid; unsigned int st_rdev; unsigned int st_pad2[3]; // Reserved for st_rdev expansion off_t st_size; // These are declared as speperate fields in the kernel. Here we use // the timespec struct for consistancy with the other stat structs. struct timespec st_atim; struct timespec st_mtim; struct timespec st_ctim; unsigned int st_blksize; unsigned int st_pad4; long st_blocks; }; // These are needed because we do not include fcntl.h or sys/types.h #include #include #else // Use the stat defined by glibc #include #include #endif #ifdef TCSETS2 // On systems that have "struct termios2" use this as type Termios. typedef struct termios2 termios_t; #else typedef struct termios termios_t; #endif enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_ll s5; struct sockaddr_nl s6; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; // copied from /usr/include/bluetooth/hci.h struct sockaddr_hci { sa_family_t hci_family; unsigned short hci_dev; unsigned short hci_channel; };; // copied from /usr/include/linux/un.h struct my_sockaddr_un { sa_family_t sun_family; #if defined(__ARM_EABI__) || defined(__powerpc64__) // on ARM char is by default unsigned signed char sun_path[108]; #else char sun_path[108]; #endif }; #ifdef __ARM_EABI__ typedef struct user_regs PtraceRegs; #elif defined(__aarch64__) typedef struct user_pt_regs PtraceRegs; #elif defined(__mips__) || defined(__powerpc64__) typedef struct pt_regs PtraceRegs; #elif defined(__s390x__) typedef struct _user_regs_struct PtraceRegs; #elif defined(__sparc__) #include typedef struct pt_regs PtraceRegs; #else typedef struct user_regs_struct PtraceRegs; #endif #if defined(__s390x__) typedef struct _user_psw_struct ptracePsw; typedef struct _user_fpregs_struct ptraceFpregs; typedef struct _user_per_struct ptracePer; #else typedef struct {} ptracePsw; typedef struct {} ptraceFpregs; typedef struct {} ptracePer; #endif // The real epoll_event is a union, and godefs doesn't handle it well. struct my_epoll_event { uint32_t events; #if defined(__ARM_EABI__) || defined(__aarch64__) || (defined(__mips__) && _MIPS_SIM == _ABIO32) // padding is not specified in linux/eventpoll.h but added to conform to the // alignment requirements of EABI int32_t padFd; #elif defined(__powerpc64__) || defined(__s390x__) || defined(__sparc__) int32_t _padFd; #endif int32_t fd; int32_t pad; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong PathMax = C.PATH_MAX ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timex C.struct_timex type Time_t C.time_t type Tms C.struct_tms type Utimbuf C.struct_utimbuf // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Dirent C.struct_dirent type Fsid C.fsid_t type Flock_t C.struct_flock // Filesystem Encryption type FscryptPolicy C.struct_fscrypt_policy type FscryptKey C.struct_fscrypt_key // Structure for Keyctl type KeyctlDHParams C.struct_keyctl_dh_params // Advice to Fadvise const ( FADV_NORMAL = C.POSIX_FADV_NORMAL FADV_RANDOM = C.POSIX_FADV_RANDOM FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL FADV_WILLNEED = C.POSIX_FADV_WILLNEED FADV_DONTNEED = C.POSIX_FADV_DONTNEED FADV_NOREUSE = C.POSIX_FADV_NOREUSE ) // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_my_sockaddr_un type RawSockaddrLinklayer C.struct_sockaddr_ll type RawSockaddrNetlink C.struct_sockaddr_nl type RawSockaddrHCI C.struct_sockaddr_hci type RawSockaddrCAN C.struct_sockaddr_can type RawSockaddrALG C.struct_sockaddr_alg type RawSockaddrVM C.struct_sockaddr_vm type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPMreqn C.struct_ip_mreqn type IPv6Mreq C.struct_ipv6_mreq type PacketMreq C.struct_packet_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet4Pktinfo C.struct_in_pktinfo type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter type Ucred C.struct_ucred type TCPInfo C.struct_tcp_info const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrLinklayer = C.sizeof_struct_sockaddr_ll SizeofSockaddrNetlink = C.sizeof_struct_sockaddr_nl SizeofSockaddrHCI = C.sizeof_struct_sockaddr_hci SizeofSockaddrCAN = C.sizeof_struct_sockaddr_can SizeofSockaddrALG = C.sizeof_struct_sockaddr_alg SizeofSockaddrVM = C.sizeof_struct_sockaddr_vm SizeofLinger = C.sizeof_struct_linger SizeofIovec = C.sizeof_struct_iovec SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPMreqn = C.sizeof_struct_ip_mreqn SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofPacketMreq = C.sizeof_struct_packet_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter SizeofUcred = C.sizeof_struct_ucred SizeofTCPInfo = C.sizeof_struct_tcp_info ) // Netlink routing and interface messages const ( IFA_UNSPEC = C.IFA_UNSPEC IFA_ADDRESS = C.IFA_ADDRESS IFA_LOCAL = C.IFA_LOCAL IFA_LABEL = C.IFA_LABEL IFA_BROADCAST = C.IFA_BROADCAST IFA_ANYCAST = C.IFA_ANYCAST IFA_CACHEINFO = C.IFA_CACHEINFO IFA_MULTICAST = C.IFA_MULTICAST IFLA_UNSPEC = C.IFLA_UNSPEC IFLA_ADDRESS = C.IFLA_ADDRESS IFLA_BROADCAST = C.IFLA_BROADCAST IFLA_IFNAME = C.IFLA_IFNAME IFLA_MTU = C.IFLA_MTU IFLA_LINK = C.IFLA_LINK IFLA_QDISC = C.IFLA_QDISC IFLA_STATS = C.IFLA_STATS IFLA_COST = C.IFLA_COST IFLA_PRIORITY = C.IFLA_PRIORITY IFLA_MASTER = C.IFLA_MASTER IFLA_WIRELESS = C.IFLA_WIRELESS IFLA_PROTINFO = C.IFLA_PROTINFO IFLA_TXQLEN = C.IFLA_TXQLEN IFLA_MAP = C.IFLA_MAP IFLA_WEIGHT = C.IFLA_WEIGHT IFLA_OPERSTATE = C.IFLA_OPERSTATE IFLA_LINKMODE = C.IFLA_LINKMODE IFLA_LINKINFO = C.IFLA_LINKINFO IFLA_NET_NS_PID = C.IFLA_NET_NS_PID IFLA_IFALIAS = C.IFLA_IFALIAS IFLA_MAX = C.IFLA_MAX RT_SCOPE_UNIVERSE = C.RT_SCOPE_UNIVERSE RT_SCOPE_SITE = C.RT_SCOPE_SITE RT_SCOPE_LINK = C.RT_SCOPE_LINK RT_SCOPE_HOST = C.RT_SCOPE_HOST RT_SCOPE_NOWHERE = C.RT_SCOPE_NOWHERE RT_TABLE_UNSPEC = C.RT_TABLE_UNSPEC RT_TABLE_COMPAT = C.RT_TABLE_COMPAT RT_TABLE_DEFAULT = C.RT_TABLE_DEFAULT RT_TABLE_MAIN = C.RT_TABLE_MAIN RT_TABLE_LOCAL = C.RT_TABLE_LOCAL RT_TABLE_MAX = C.RT_TABLE_MAX RTA_UNSPEC = C.RTA_UNSPEC RTA_DST = C.RTA_DST RTA_SRC = C.RTA_SRC RTA_IIF = C.RTA_IIF RTA_OIF = C.RTA_OIF RTA_GATEWAY = C.RTA_GATEWAY RTA_PRIORITY = C.RTA_PRIORITY RTA_PREFSRC = C.RTA_PREFSRC RTA_METRICS = C.RTA_METRICS RTA_MULTIPATH = C.RTA_MULTIPATH RTA_FLOW = C.RTA_FLOW RTA_CACHEINFO = C.RTA_CACHEINFO RTA_TABLE = C.RTA_TABLE RTN_UNSPEC = C.RTN_UNSPEC RTN_UNICAST = C.RTN_UNICAST RTN_LOCAL = C.RTN_LOCAL RTN_BROADCAST = C.RTN_BROADCAST RTN_ANYCAST = C.RTN_ANYCAST RTN_MULTICAST = C.RTN_MULTICAST RTN_BLACKHOLE = C.RTN_BLACKHOLE RTN_UNREACHABLE = C.RTN_UNREACHABLE RTN_PROHIBIT = C.RTN_PROHIBIT RTN_THROW = C.RTN_THROW RTN_NAT = C.RTN_NAT RTN_XRESOLVE = C.RTN_XRESOLVE RTNLGRP_NONE = C.RTNLGRP_NONE RTNLGRP_LINK = C.RTNLGRP_LINK RTNLGRP_NOTIFY = C.RTNLGRP_NOTIFY RTNLGRP_NEIGH = C.RTNLGRP_NEIGH RTNLGRP_TC = C.RTNLGRP_TC RTNLGRP_IPV4_IFADDR = C.RTNLGRP_IPV4_IFADDR RTNLGRP_IPV4_MROUTE = C.RTNLGRP_IPV4_MROUTE RTNLGRP_IPV4_ROUTE = C.RTNLGRP_IPV4_ROUTE RTNLGRP_IPV4_RULE = C.RTNLGRP_IPV4_RULE RTNLGRP_IPV6_IFADDR = C.RTNLGRP_IPV6_IFADDR RTNLGRP_IPV6_MROUTE = C.RTNLGRP_IPV6_MROUTE RTNLGRP_IPV6_ROUTE = C.RTNLGRP_IPV6_ROUTE RTNLGRP_IPV6_IFINFO = C.RTNLGRP_IPV6_IFINFO RTNLGRP_IPV6_PREFIX = C.RTNLGRP_IPV6_PREFIX RTNLGRP_IPV6_RULE = C.RTNLGRP_IPV6_RULE RTNLGRP_ND_USEROPT = C.RTNLGRP_ND_USEROPT SizeofNlMsghdr = C.sizeof_struct_nlmsghdr SizeofNlMsgerr = C.sizeof_struct_nlmsgerr SizeofRtGenmsg = C.sizeof_struct_rtgenmsg SizeofNlAttr = C.sizeof_struct_nlattr SizeofRtAttr = C.sizeof_struct_rtattr SizeofIfInfomsg = C.sizeof_struct_ifinfomsg SizeofIfAddrmsg = C.sizeof_struct_ifaddrmsg SizeofRtMsg = C.sizeof_struct_rtmsg SizeofRtNexthop = C.sizeof_struct_rtnexthop ) type NlMsghdr C.struct_nlmsghdr type NlMsgerr C.struct_nlmsgerr type RtGenmsg C.struct_rtgenmsg type NlAttr C.struct_nlattr type RtAttr C.struct_rtattr type IfInfomsg C.struct_ifinfomsg type IfAddrmsg C.struct_ifaddrmsg type RtMsg C.struct_rtmsg type RtNexthop C.struct_rtnexthop // Linux socket filter const ( SizeofSockFilter = C.sizeof_struct_sock_filter SizeofSockFprog = C.sizeof_struct_sock_fprog ) type SockFilter C.struct_sock_filter type SockFprog C.struct_sock_fprog // Inotify type InotifyEvent C.struct_inotify_event const SizeofInotifyEvent = C.sizeof_struct_inotify_event // Ptrace // Register structures type PtraceRegs C.PtraceRegs // Structures contained in PtraceRegs on s390x (exported by mkpost.go) type PtracePsw C.ptracePsw type PtraceFpregs C.ptraceFpregs type PtracePer C.ptracePer // Misc type FdSet C.fd_set type Sysinfo_t C.struct_sysinfo type Utsname C.struct_utsname type Ustat_t C.struct_ustat type EpollEvent C.struct_my_epoll_event const ( AT_FDCWD = C.AT_FDCWD AT_REMOVEDIR = C.AT_REMOVEDIR AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) type PollFd C.struct_pollfd const ( POLLIN = C.POLLIN POLLPRI = C.POLLPRI POLLOUT = C.POLLOUT POLLRDHUP = C.POLLRDHUP POLLERR = C.POLLERR POLLHUP = C.POLLHUP POLLNVAL = C.POLLNVAL ) type Sigset_t C.sigset_t const RNDGETENTCNT = C.RNDGETENTCNT const PERF_IOC_FLAG_GROUP = C.PERF_IOC_FLAG_GROUP // Terminal handling type Termios C.termios_t type Winsize C.struct_winsize // Taskstats type Taskstats C.struct_taskstats const ( TASKSTATS_CMD_UNSPEC = C.TASKSTATS_CMD_UNSPEC TASKSTATS_CMD_GET = C.TASKSTATS_CMD_GET TASKSTATS_CMD_NEW = C.TASKSTATS_CMD_NEW TASKSTATS_TYPE_UNSPEC = C.TASKSTATS_TYPE_UNSPEC TASKSTATS_TYPE_PID = C.TASKSTATS_TYPE_PID TASKSTATS_TYPE_TGID = C.TASKSTATS_TYPE_TGID TASKSTATS_TYPE_STATS = C.TASKSTATS_TYPE_STATS TASKSTATS_TYPE_AGGR_PID = C.TASKSTATS_TYPE_AGGR_PID TASKSTATS_TYPE_AGGR_TGID = C.TASKSTATS_TYPE_AGGR_TGID TASKSTATS_TYPE_NULL = C.TASKSTATS_TYPE_NULL TASKSTATS_CMD_ATTR_UNSPEC = C.TASKSTATS_CMD_ATTR_UNSPEC TASKSTATS_CMD_ATTR_PID = C.TASKSTATS_CMD_ATTR_PID TASKSTATS_CMD_ATTR_TGID = C.TASKSTATS_CMD_ATTR_TGID TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = C.TASKSTATS_CMD_ATTR_REGISTER_CPUMASK TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = C.TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK ) // Generic netlink type Genlmsghdr C.struct_genlmsghdr const ( CTRL_CMD_UNSPEC = C.CTRL_CMD_UNSPEC CTRL_CMD_NEWFAMILY = C.CTRL_CMD_NEWFAMILY CTRL_CMD_DELFAMILY = C.CTRL_CMD_DELFAMILY CTRL_CMD_GETFAMILY = C.CTRL_CMD_GETFAMILY CTRL_CMD_NEWOPS = C.CTRL_CMD_NEWOPS CTRL_CMD_DELOPS = C.CTRL_CMD_DELOPS CTRL_CMD_GETOPS = C.CTRL_CMD_GETOPS CTRL_CMD_NEWMCAST_GRP = C.CTRL_CMD_NEWMCAST_GRP CTRL_CMD_DELMCAST_GRP = C.CTRL_CMD_DELMCAST_GRP CTRL_CMD_GETMCAST_GRP = C.CTRL_CMD_GETMCAST_GRP CTRL_ATTR_UNSPEC = C.CTRL_ATTR_UNSPEC CTRL_ATTR_FAMILY_ID = C.CTRL_ATTR_FAMILY_ID CTRL_ATTR_FAMILY_NAME = C.CTRL_ATTR_FAMILY_NAME CTRL_ATTR_VERSION = C.CTRL_ATTR_VERSION CTRL_ATTR_HDRSIZE = C.CTRL_ATTR_HDRSIZE CTRL_ATTR_MAXATTR = C.CTRL_ATTR_MAXATTR CTRL_ATTR_OPS = C.CTRL_ATTR_OPS CTRL_ATTR_MCAST_GROUPS = C.CTRL_ATTR_MCAST_GROUPS CTRL_ATTR_OP_UNSPEC = C.CTRL_ATTR_OP_UNSPEC CTRL_ATTR_OP_ID = C.CTRL_ATTR_OP_ID CTRL_ATTR_OP_FLAGS = C.CTRL_ATTR_OP_FLAGS CTRL_ATTR_MCAST_GRP_UNSPEC = C.CTRL_ATTR_MCAST_GRP_UNSPEC CTRL_ATTR_MCAST_GRP_NAME = C.CTRL_ATTR_MCAST_GRP_NAME CTRL_ATTR_MCAST_GRP_ID = C.CTRL_ATTR_MCAST_GRP_ID ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/linux/mksysnum.pl0000755061062106075000000000370413172163421024720 0ustar stgraberdomain admins#!/usr/bin/env perl # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. use strict; if($ENV{'GOARCH'} eq "" || $ENV{'GOOS'} eq "") { print STDERR "GOARCH or GOOS not defined in environment\n"; exit 1; } # Check that we are using the new build system if we should if($ENV{'GOLANG_SYS_BUILD'} ne "docker") { print STDERR "In the new build system, mksysnum should not be called directly.\n"; print STDERR "See README.md\n"; exit 1; } my $command = "$0 ". join(' ', @ARGV); print < 999){ # ignore deprecated syscalls that are no longer implemented # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/uapi/asm-generic/unistd.h?id=refs/heads/master#n716 return; } $name =~ y/a-z/A-Z/; $num = $num + $offset; print " SYS_$name = $num;\n"; } my $prev; open(CC, "$ENV{'CC'} -E -dD @ARGV |") || die "can't run $ENV{'CC'}"; while(){ if(/^#define __NR_Linux\s+([0-9]+)/){ # mips/mips64: extract offset $offset = $1; } elsif(/^#define __NR(\w*)_SYSCALL_BASE\s+([0-9]+)/){ # arm: extract offset $offset = $1; } elsif(/^#define __NR_syscalls\s+/) { # ignore redefinitions of __NR_syscalls } elsif(/^#define __NR_(\w*)Linux_syscalls\s+/) { # mips/mips64: ignore definitions about the number of syscalls } elsif(/^#define __NR_(\w+)\s+([0-9]+)/){ $prev = $2; fmt($1, $2); } elsif(/^#define __NR3264_(\w+)\s+([0-9]+)/){ $prev = $2; fmt($1, $2); } elsif(/^#define __NR_(\w+)\s+\(\w+\+\s*([0-9]+)\)/){ fmt($1, $prev+$2) } elsif(/^#define __NR_(\w+)\s+\(__NR_Linux \+ ([0-9]+)/){ fmt($1, $2); } elsif(/^#define __NR_(\w+)\s+\(__NR_SYSCALL_BASE \+ ([0-9]+)/){ fmt($1, $2); } } print < // +build ignore package main import ( "fmt" "os" "os/exec" "path/filepath" "runtime" "strings" ) // These will be paths to the appropriate source directories. var LinuxDir string var GlibcDir string const TempDir = "/tmp" const IncludeDir = TempDir + "/include" // To hold our C headers const BuildDir = TempDir + "/build" // To hold intermediate build files const GOOS = "linux" // Only for Linux targets const BuildArch = "amd64" // Must be built on this architecture const MinKernel = "2.6.23" // https://golang.org/doc/install#requirements type target struct { GoArch string // Architecture name according to Go LinuxArch string // Architecture name according to the Linux Kernel GNUArch string // Architecture name according to GNU tools (https://wiki.debian.org/Multiarch/Tuples) BigEndian bool // Default Little Endian SignedChar bool // Is -fsigned-char needed (default no) Bits int } // List of the 11 Linux targets supported by the go compiler. sparc64 is not // currently supported, though a port is in progress. var targets = []target{ { GoArch: "386", LinuxArch: "x86", GNUArch: "i686-linux-gnu", // Note "i686" not "i386" Bits: 32, }, { GoArch: "amd64", LinuxArch: "x86", GNUArch: "x86_64-linux-gnu", Bits: 64, }, { GoArch: "arm64", LinuxArch: "arm64", GNUArch: "aarch64-linux-gnu", SignedChar: true, Bits: 64, }, { GoArch: "arm", LinuxArch: "arm", GNUArch: "arm-linux-gnueabi", Bits: 32, }, { GoArch: "mips", LinuxArch: "mips", GNUArch: "mips-linux-gnu", BigEndian: true, Bits: 32, }, { GoArch: "mipsle", LinuxArch: "mips", GNUArch: "mipsel-linux-gnu", Bits: 32, }, { GoArch: "mips64", LinuxArch: "mips", GNUArch: "mips64-linux-gnuabi64", BigEndian: true, Bits: 64, }, { GoArch: "mips64le", LinuxArch: "mips", GNUArch: "mips64el-linux-gnuabi64", Bits: 64, }, { GoArch: "ppc64", LinuxArch: "powerpc", GNUArch: "powerpc64-linux-gnu", BigEndian: true, Bits: 64, }, { GoArch: "ppc64le", LinuxArch: "powerpc", GNUArch: "powerpc64le-linux-gnu", Bits: 64, }, { GoArch: "s390x", LinuxArch: "s390", GNUArch: "s390x-linux-gnu", BigEndian: true, SignedChar: true, Bits: 64, }, // { // GoArch: "sparc64", // LinuxArch: "sparc", // GNUArch: "sparc64-linux-gnu", // BigEndian: true, // Bits: 64, // }, } func main() { if runtime.GOOS != GOOS || runtime.GOARCH != BuildArch { fmt.Printf("Build system has GOOS_GOARCH = %s_%s, need %s_%s\n", runtime.GOOS, runtime.GOARCH, GOOS, BuildArch) return } // Check that we are using the new build system if we should if os.Getenv("GOLANG_SYS_BUILD") != "docker" { fmt.Println("In the new build system, mkall.go should not be called directly.") fmt.Println("See README.md") return } // Parse the command line options if len(os.Args) != 3 { fmt.Println("USAGE: go run linux/mkall.go ") return } LinuxDir = os.Args[1] GlibcDir = os.Args[2] for _, t := range targets { fmt.Printf("----- GENERATING: %s -----\n", t.GoArch) if err := t.generateFiles(); err != nil { fmt.Printf("%v\n***** FAILURE: %s *****\n\n", err, t.GoArch) } else { fmt.Printf("----- SUCCESS: %s -----\n\n", t.GoArch) } } } // Makes an exec.Cmd with Stderr attached to os.Stderr func makeCommand(name string, args ...string) *exec.Cmd { cmd := exec.Command(name, args...) cmd.Stderr = os.Stderr return cmd } // Runs the command, pipes output to a formatter, pipes that to an output file. func (t *target) commandFormatOutput(formatter string, outputFile string, name string, args ...string) (err error) { mainCmd := makeCommand(name, args...) fmtCmd := makeCommand(formatter) if formatter == "mkpost" { fmtCmd = makeCommand("go", "run", "mkpost.go") // Set GOARCH_TARGET so mkpost knows what GOARCH is.. fmtCmd.Env = append(os.Environ(), "GOARCH_TARGET="+t.GoArch) // Set GOARCH to host arch for mkpost, so it can run natively. for i, s := range fmtCmd.Env { if strings.HasPrefix(s, "GOARCH=") { fmtCmd.Env[i] = "GOARCH=" + BuildArch } } } // mainCmd | fmtCmd > outputFile if fmtCmd.Stdin, err = mainCmd.StdoutPipe(); err != nil { return } if fmtCmd.Stdout, err = os.Create(outputFile); err != nil { return } // Make sure the formatter eventually closes if err = fmtCmd.Start(); err != nil { return } defer func() { fmtErr := fmtCmd.Wait() if err == nil { err = fmtErr } }() return mainCmd.Run() } // Generates all the files for a Linux target func (t *target) generateFiles() error { // Setup environment variables os.Setenv("GOOS", GOOS) os.Setenv("GOARCH", t.GoArch) // Get appropriate compiler and emulator (unless on x86) if t.LinuxArch != "x86" { // Check/Setup cross compiler compiler := t.GNUArch + "-gcc" if _, err := exec.LookPath(compiler); err != nil { return err } os.Setenv("CC", compiler) // Check/Setup emulator (usually first component of GNUArch) qemuArchName := t.GNUArch[:strings.Index(t.GNUArch, "-")] if t.LinuxArch == "powerpc" { qemuArchName = t.GoArch } os.Setenv("GORUN", "qemu-"+qemuArchName) } else { os.Setenv("CC", "gcc") } // Make the include directory and fill it with headers if err := os.MkdirAll(IncludeDir, os.ModePerm); err != nil { return err } defer os.RemoveAll(IncludeDir) if err := t.makeHeaders(); err != nil { return fmt.Errorf("could not make header files: %v", err) } fmt.Println("header files generated") // Make each of the four files if err := t.makeZSysnumFile(); err != nil { return fmt.Errorf("could not make zsysnum file: %v", err) } fmt.Println("zsysnum file generated") if err := t.makeZSyscallFile(); err != nil { return fmt.Errorf("could not make zsyscall file: %v", err) } fmt.Println("zsyscall file generated") if err := t.makeZTypesFile(); err != nil { return fmt.Errorf("could not make ztypes file: %v", err) } fmt.Println("ztypes file generated") if err := t.makeZErrorsFile(); err != nil { return fmt.Errorf("could not make zerrors file: %v", err) } fmt.Println("zerrors file generated") return nil } // Create the Linux and glibc headers in the include directory. func (t *target) makeHeaders() error { // Make the Linux headers we need for this architecture linuxMake := makeCommand("make", "headers_install", "ARCH="+t.LinuxArch, "INSTALL_HDR_PATH="+TempDir) linuxMake.Dir = LinuxDir if err := linuxMake.Run(); err != nil { return err } // A Temporary build directory for glibc if err := os.MkdirAll(BuildDir, os.ModePerm); err != nil { return err } defer os.RemoveAll(BuildDir) // Make the glibc headers we need for this architecture confScript := filepath.Join(GlibcDir, "configure") glibcConf := makeCommand(confScript, "--prefix="+TempDir, "--host="+t.GNUArch, "--enable-kernel="+MinKernel) glibcConf.Dir = BuildDir if err := glibcConf.Run(); err != nil { return err } glibcMake := makeCommand("make", "install-headers") glibcMake.Dir = BuildDir if err := glibcMake.Run(); err != nil { return err } // We only need an empty stubs file stubsFile := filepath.Join(IncludeDir, "gnu/stubs.h") if file, err := os.Create(stubsFile); err != nil { return err } else { file.Close() } return nil } // makes the zsysnum_linux_$GOARCH.go file func (t *target) makeZSysnumFile() error { zsysnumFile := fmt.Sprintf("zsysnum_linux_%s.go", t.GoArch) unistdFile := filepath.Join(IncludeDir, "asm/unistd.h") args := append(t.cFlags(), unistdFile) return t.commandFormatOutput("gofmt", zsysnumFile, "linux/mksysnum.pl", args...) } // makes the zsyscall_linux_$GOARCH.go file func (t *target) makeZSyscallFile() error { zsyscallFile := fmt.Sprintf("zsyscall_linux_%s.go", t.GoArch) // Find the correct architecture syscall file (might end with x.go) archSyscallFile := fmt.Sprintf("syscall_linux_%s.go", t.GoArch) if _, err := os.Stat(archSyscallFile); os.IsNotExist(err) { shortArch := strings.TrimSuffix(t.GoArch, "le") archSyscallFile = fmt.Sprintf("syscall_linux_%sx.go", shortArch) } args := append(t.mksyscallFlags(), "-tags", "linux,"+t.GoArch, "syscall_linux.go", archSyscallFile) return t.commandFormatOutput("gofmt", zsyscallFile, "./mksyscall.pl", args...) } // makes the zerrors_linux_$GOARCH.go file func (t *target) makeZErrorsFile() error { zerrorsFile := fmt.Sprintf("zerrors_linux_%s.go", t.GoArch) return t.commandFormatOutput("gofmt", zerrorsFile, "./mkerrors.sh", t.cFlags()...) } // makes the ztypes_linux_$GOARCH.go file func (t *target) makeZTypesFile() error { ztypesFile := fmt.Sprintf("ztypes_linux_%s.go", t.GoArch) args := []string{"tool", "cgo", "-godefs", "--"} args = append(args, t.cFlags()...) args = append(args, "linux/types.go") return t.commandFormatOutput("mkpost", ztypesFile, "go", args...) } // Flags that should be given to gcc and cgo for this target func (t *target) cFlags() []string { // Compile statically to avoid cross-architecture dynamic linking. flags := []string{"-Wall", "-Werror", "-static", "-I" + IncludeDir} // Architecture-specific flags if t.SignedChar { flags = append(flags, "-fsigned-char") } if t.LinuxArch == "x86" { flags = append(flags, fmt.Sprintf("-m%d", t.Bits)) } return flags } // Flags that should be given to mksyscall for this target func (t *target) mksyscallFlags() (flags []string) { if t.Bits == 32 { if t.BigEndian { flags = append(flags, "-b32") } else { flags = append(flags, "-l32") } } // This flag menas a 64-bit value should use (even, odd)-pair. if t.GoArch == "arm" || (t.LinuxArch == "mips" && t.Bits == 32) { flags = append(flags, "-arm") } return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/linux/Dockerfile0000644061062106075000000000405013172163421024457 0ustar stgraberdomain adminsFROM ubuntu:16.04 # Use the most recent ubuntu sources RUN echo 'deb http://en.archive.ubuntu.com/ubuntu/ artful main universe' >> /etc/apt/sources.list # Dependencies to get the git sources and go binaries RUN apt-get update && apt-get install -y \ curl \ git \ && rm -rf /var/lib/apt/lists/* # Get the git sources. If not cached, this takes O(5 minutes). WORKDIR /git RUN git config --global advice.detachedHead false # Linux Kernel: Released 03 Sep 2017 RUN git clone --branch v4.13 --depth 1 https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux # GNU C library: Released 02 Aug 2017 (we should try to get a secure way to clone this) RUN git clone --branch glibc-2.26 --depth 1 git://sourceware.org/git/glibc.git # Get Go 1.8 (https://github.com/docker-library/golang/blob/master/1.8/Dockerfile) ENV GOLANG_VERSION 1.8 ENV GOLANG_DOWNLOAD_URL https://golang.org/dl/go$GOLANG_VERSION.linux-amd64.tar.gz ENV GOLANG_DOWNLOAD_SHA256 53ab94104ee3923e228a2cb2116e5e462ad3ebaeea06ff04463479d7f12d27ca RUN curl -fsSL "$GOLANG_DOWNLOAD_URL" -o golang.tar.gz \ && echo "$GOLANG_DOWNLOAD_SHA256 golang.tar.gz" | sha256sum -c - \ && tar -C /usr/local -xzf golang.tar.gz \ && rm golang.tar.gz ENV PATH /usr/local/go/bin:$PATH # Linux and Glibc build dependencies RUN apt-get update && apt-get install -y \ gawk make python \ gcc gcc-multilib \ gettext texinfo \ && rm -rf /var/lib/apt/lists/* # Emulator and cross compilers RUN apt-get update && apt-get install -y \ qemu \ gcc-aarch64-linux-gnu gcc-arm-linux-gnueabi \ gcc-mips-linux-gnu gcc-mips64-linux-gnuabi64 \ gcc-mips64el-linux-gnuabi64 gcc-mipsel-linux-gnu \ gcc-powerpc64-linux-gnu gcc-powerpc64le-linux-gnu \ gcc-s390x-linux-gnu gcc-sparc64-linux-gnu \ && rm -rf /var/lib/apt/lists/* # Let the scripts know they are in the docker environment ENV GOLANG_SYS_BUILD docker WORKDIR /build ENTRYPOINT ["go", "run", "linux/mkall.go", "/git/linux", "/git/glibc"] lxd-2.0.11/dist/src/golang.org/x/sys/unix/gccgo_linux_amd64.go0000644061062106075000000000065613172163421025161 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build gccgo,linux,amd64 package unix import "syscall" //extern gettimeofday func realGettimeofday(*Timeval, *byte) int32 func gettimeofday(tv *Timeval) (err syscall.Errno) { r := realGettimeofday(tv, nil) if r < 0 { return syscall.GetErrno() } return 0 } lxd-2.0.11/dist/src/golang.org/x/sys/unix/gccgo_c.c0000644061062106075000000000176613172163421023071 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build gccgo #include #include #include #define _STRINGIFY2_(x) #x #define _STRINGIFY_(x) _STRINGIFY2_(x) #define GOSYM_PREFIX _STRINGIFY_(__USER_LABEL_PREFIX__) // Call syscall from C code because the gccgo support for calling from // Go to C does not support varargs functions. struct ret { uintptr_t r; uintptr_t err; }; struct ret gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9) { struct ret r; errno = 0; r.r = syscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9); r.err = errno; return r; } // Define the use function in C so that it is not inlined. extern void use(void *) __asm__ (GOSYM_PREFIX GOPKGPATH ".use") __attribute__((noinline)); void use(void *p __attribute__ ((unused))) { } lxd-2.0.11/dist/src/golang.org/x/sys/unix/gccgo.go0000644061062106075000000000300513172163421022736 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build gccgo package unix import "syscall" // We can't use the gc-syntax .s files for gccgo. On the plus side // much of the functionality can be written directly in Go. //extern gccgoRealSyscall func realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r, errno uintptr) func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { syscall.Entersyscall() r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) syscall.Exitsyscall() return r, 0, syscall.Errno(errno) } func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { syscall.Entersyscall() r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0) syscall.Exitsyscall() return r, 0, syscall.Errno(errno) } func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) { syscall.Entersyscall() r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9) syscall.Exitsyscall() return r, 0, syscall.Errno(errno) } func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) return r, 0, syscall.Errno(errno) } func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0) return r, 0, syscall.Errno(errno) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/flock_linux_32bit.go0000644061062106075000000000060413172163421025176 0ustar stgraberdomain admins// +build linux,386 linux,arm linux,mips linux,mipsle // Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix func init() { // On 32-bit Linux systems, the fcntl syscall that matches Go's // Flock_t type is SYS_FCNTL64, not SYS_FCNTL. fcntl64Syscall = SYS_FCNTL64 } lxd-2.0.11/dist/src/golang.org/x/sys/unix/flock.go0000644061062106075000000000126713172163421022762 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd package unix import "unsafe" // fcntl64Syscall is usually SYS_FCNTL, but is overridden on 32-bit Linux // systems by flock_linux_32bit.go to be SYS_FCNTL64. var fcntl64Syscall uintptr = SYS_FCNTL // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { _, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk))) if errno == 0 { return nil } return errno } lxd-2.0.11/dist/src/golang.org/x/sys/unix/file_unix.go0000644061062106075000000000114613172163421023642 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix import ( "os" "syscall" ) // FIXME: unexported function from os // syscallMode returns the syscall-specific mode bits from Go's portable mode bits. func syscallMode(i os.FileMode) (o uint32) { o |= uint32(i.Perm()) if i&os.ModeSetuid != 0 { o |= syscall.S_ISUID } if i&os.ModeSetgid != 0 { o |= syscall.S_ISGID } if i&os.ModeSticky != 0 { o |= syscall.S_ISVTX } // No mapping for Go's ModeTemporary (plan9 only). return } lxd-2.0.11/dist/src/golang.org/x/sys/unix/export_test.go0000644061062106075000000000040013172163421024230 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix var Itoa = itoa lxd-2.0.11/dist/src/golang.org/x/sys/unix/errors_freebsd_arm.go0000644061062106075000000002151513172163421025527 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix const ( IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BSC = 0x53 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf6 IFT_PFSYNC = 0xf7 IFT_PLC = 0xae IFT_POS = 0xab IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xd7 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VOICEEM = 0x64 IFT_VOICEENCAP = 0x67 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a // missing constants on FreeBSD-11.1-RELEASE, copied from old values in ztypes_freebsd_arm.go IFF_SMART = 0x20 IFT_FAITH = 0xf2 IFT_IPXIP = 0xf9 IPPROTO_MAXID = 0x34 IPV6_FAITH = 0x1d IP_FAITH = 0x16 MAP_NORESERVE = 0x40 MAP_RENAME = 0x20 NET_RT_MAXID = 0x6 RTF_PRCLONING = 0x10000 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa SIOCADDRT = 0x8030720a SIOCALIFADDR = 0x8118691b SIOCDELRT = 0x8030720b SIOCDLIFADDR = 0x8118691d SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCSLIFPHYADDR = 0x8118694a ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/errors_freebsd_amd64.go0000644061062106075000000002227713172163421025671 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Constants that were deprecated or moved to enums in the FreeBSD headers. Keep // them here for backwards compatibility. package unix const ( IFF_SMART = 0x20 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BSC = 0x53 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf2 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_IPXIP = 0xf9 IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf6 IFT_PFSYNC = 0xf7 IFT_PLC = 0xae IFT_POS = 0xab IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xd7 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VOICEEM = 0x64 IFT_VOICEENCAP = 0x67 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IPPROTO_MAXID = 0x34 IPV6_FAITH = 0x1d IP_FAITH = 0x16 MAP_NORESERVE = 0x40 MAP_RENAME = 0x20 NET_RT_MAXID = 0x6 RTF_PRCLONING = 0x10000 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa SIOCADDRT = 0x8040720a SIOCALIFADDR = 0x8118691b SIOCDELRT = 0x8040720b SIOCDLIFADDR = 0x8118691d SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCSLIFPHYADDR = 0x8118694a ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/errors_freebsd_386.go0000644061062106075000000002227713172163421025276 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Constants that were deprecated or moved to enums in the FreeBSD headers. Keep // them here for backwards compatibility. package unix const ( IFF_SMART = 0x20 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BSC = 0x53 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf2 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_IPXIP = 0xf9 IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf6 IFT_PFSYNC = 0xf7 IFT_PLC = 0xae IFT_POS = 0xab IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xd7 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VOICEEM = 0x64 IFT_VOICEENCAP = 0x67 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IPPROTO_MAXID = 0x34 IPV6_FAITH = 0x1d IP_FAITH = 0x16 MAP_NORESERVE = 0x40 MAP_RENAME = 0x20 NET_RT_MAXID = 0x6 RTF_PRCLONING = 0x10000 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa SIOCADDRT = 0x8030720a SIOCALIFADDR = 0x8118691b SIOCDELRT = 0x8030720b SIOCDLIFADDR = 0x8118691d SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCSLIFPHYADDR = 0x8118694a ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/env_unset.go0000644061062106075000000000046213172163421023666 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.4 package unix import "syscall" func Unsetenv(key string) error { // This was added in Go 1.4. return syscall.Unsetenv(key) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/env_unix.go0000644061062106075000000000104213172163421023506 0ustar stgraberdomain admins// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris // Unix environment variables. package unix import "syscall" func Getenv(key string) (value string, found bool) { return syscall.Getenv(key) } func Setenv(key, value string) error { return syscall.Setenv(key, value) } func Clearenv() { syscall.Clearenv() } func Environ() []string { return syscall.Environ() } lxd-2.0.11/dist/src/golang.org/x/sys/unix/endian_little.go0000644061062106075000000000041213172163421024466 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // +build 386 amd64 amd64p32 arm arm64 ppc64le mipsle mips64le package unix const isBigEndian = false lxd-2.0.11/dist/src/golang.org/x/sys/unix/endian_big.go0000644061062106075000000000035413172163421023737 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // +build ppc64 s390x mips mips64 package unix const isBigEndian = true lxd-2.0.11/dist/src/golang.org/x/sys/unix/dirent.go0000644061062106075000000000576113172163421023154 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris package unix import "unsafe" // readInt returns the size-bytes unsigned integer in native byte order at offset off. func readInt(b []byte, off, size uintptr) (u uint64, ok bool) { if len(b) < int(off+size) { return 0, false } if isBigEndian { return readIntBE(b[off:], size), true } return readIntLE(b[off:], size), true } func readIntBE(b []byte, size uintptr) uint64 { switch size { case 1: return uint64(b[0]) case 2: _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[1]) | uint64(b[0])<<8 case 4: _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[3]) | uint64(b[2])<<8 | uint64(b[1])<<16 | uint64(b[0])<<24 case 8: _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 default: panic("syscall: readInt with unsupported size") } } func readIntLE(b []byte, size uintptr) uint64 { switch size { case 1: return uint64(b[0]) case 2: _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[0]) | uint64(b[1])<<8 case 4: _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 case 8: _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 default: panic("syscall: readInt with unsupported size") } } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number of // bytes consumed from buf, the number of entries added // to names, and the new names slice. func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { origlen := len(buf) count = 0 for max != 0 && len(buf) > 0 { reclen, ok := direntReclen(buf) if !ok || reclen > uint64(len(buf)) { return origlen, count, names } rec := buf[:reclen] buf = buf[reclen:] ino, ok := direntIno(rec) if !ok { break } if ino == 0 { // File absent in directory. continue } const namoff = uint64(unsafe.Offsetof(Dirent{}.Name)) namlen, ok := direntNamlen(rec) if !ok || namoff+namlen > uint64(len(rec)) { break } name := rec[namoff : namoff+namlen] for i, c := range name { if c == 0 { name = name[:i] break } } // Check for useless names before allocating a string. if string(name) == "." || string(name) == ".." { continue } max-- count++ names = append(names, string(name)) } return origlen - len(buf), count, names } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_solaris_test.go0000644061062106075000000000241313172163421025227 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix_test import ( "fmt" "testing" "golang.org/x/sys/unix" ) func TestDevices(t *testing.T) { testCases := []struct { path string major uint32 minor uint32 }{ // Well-known major/minor numbers on OpenSolaris according to // /etc/name_to_major {"/dev/zero", 134, 12}, {"/dev/null", 134, 2}, {"/dev/ptyp0", 172, 0}, {"/dev/ttyp0", 175, 0}, {"/dev/ttyp1", 175, 1}, } for _, tc := range testCases { t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { var stat unix.Stat_t err := unix.Stat(tc.path, &stat) if err != nil { t.Errorf("failed to stat device: %v", err) return } dev := uint64(stat.Rdev) if unix.Major(dev) != tc.major { t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) } if unix.Minor(dev) != tc.minor { t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) } if unix.Mkdev(tc.major, tc.minor) != dev { t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) } }) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_openbsd_test.go0000644061062106075000000000251613172163421025211 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix_test import ( "fmt" "testing" "golang.org/x/sys/unix" ) func TestDevices(t *testing.T) { testCases := []struct { path string major uint32 minor uint32 }{ // well known major/minor numbers according to /dev/MAKEDEV on // OpenBSD 6.0 {"/dev/null", 2, 2}, {"/dev/zero", 2, 12}, {"/dev/ttyp0", 5, 0}, {"/dev/ttyp1", 5, 1}, {"/dev/random", 45, 0}, {"/dev/srandom", 45, 1}, {"/dev/urandom", 45, 2}, {"/dev/arandom", 45, 3}, } for _, tc := range testCases { t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { var stat unix.Stat_t err := unix.Stat(tc.path, &stat) if err != nil { t.Errorf("failed to stat device: %v", err) return } dev := uint64(stat.Rdev) if unix.Major(dev) != tc.major { t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) } if unix.Minor(dev) != tc.minor { t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) } if unix.Mkdev(tc.major, tc.minor) != dev { t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) } }) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_openbsd.go0000644061062106075000000000162613172163421024153 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Functions to access/create device major and minor numbers matching the // encoding used in OpenBSD's sys/types.h header. package unix // Major returns the major component of an OpenBSD device number. func Major(dev uint64) uint32 { return uint32((dev & 0x0000ff00) >> 8) } // Minor returns the minor component of an OpenBSD device number. func Minor(dev uint64) uint32 { minor := uint32((dev & 0x000000ff) >> 0) minor |= uint32((dev & 0xffff0000) >> 8) return minor } // Mkdev returns an OpenBSD device number generated from the given major and minor // components. func Mkdev(major, minor uint32) uint64 { dev := (uint64(major) << 8) & 0x0000ff00 dev |= (uint64(minor) << 8) & 0xffff0000 dev |= (uint64(minor) << 0) & 0x000000ff return dev } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_netbsd_test.go0000644061062106075000000000242713172163421025037 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix_test import ( "fmt" "testing" "golang.org/x/sys/unix" ) func TestDevices(t *testing.T) { testCases := []struct { path string major uint32 minor uint32 }{ // well known major/minor numbers according to /dev/MAKEDEV on // NetBSD 7.0 {"/dev/null", 2, 2}, {"/dev/zero", 2, 12}, {"/dev/ttyp0", 5, 0}, {"/dev/ttyp1", 5, 1}, {"/dev/random", 46, 0}, {"/dev/urandom", 46, 1}, } for _, tc := range testCases { t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { var stat unix.Stat_t err := unix.Stat(tc.path, &stat) if err != nil { t.Errorf("failed to stat device: %v", err) return } dev := uint64(stat.Rdev) if unix.Major(dev) != tc.major { t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) } if unix.Minor(dev) != tc.minor { t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) } if unix.Mkdev(tc.major, tc.minor) != dev { t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) } }) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_netbsd.go0000644061062106075000000000162113172163421023773 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Functions to access/create device major and minor numbers matching the // encoding used in NetBSD's sys/types.h header. package unix // Major returns the major component of a NetBSD device number. func Major(dev uint64) uint32 { return uint32((dev & 0x000fff00) >> 8) } // Minor returns the minor component of a NetBSD device number. func Minor(dev uint64) uint32 { minor := uint32((dev & 0x000000ff) >> 0) minor |= uint32((dev & 0xfff00000) >> 12) return minor } // Mkdev returns a NetBSD device number generated from the given major and minor // components. func Mkdev(major, minor uint32) uint64 { dev := (uint64(major) << 8) & 0x000fff00 dev |= (uint64(minor) << 12) & 0xfff00000 dev |= (uint64(minor) << 0) & 0x000000ff return dev } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_linux_test.go0000644061062106075000000000254513172163421024720 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix_test import ( "fmt" "testing" "golang.org/x/sys/unix" ) func TestDevices(t *testing.T) { testCases := []struct { path string major uint32 minor uint32 }{ // well known major/minor numbers according to // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/admin-guide/devices.txt {"/dev/null", 1, 3}, {"/dev/zero", 1, 5}, {"/dev/random", 1, 8}, {"/dev/full", 1, 7}, {"/dev/urandom", 1, 9}, {"/dev/tty", 5, 0}, } for _, tc := range testCases { t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { var stat unix.Stat_t err := unix.Stat(tc.path, &stat) if err != nil { t.Errorf("failed to stat device: %v", err) return } dev := uint64(stat.Rdev) if unix.Major(dev) != tc.major { t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) } if unix.Minor(dev) != tc.minor { t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) } if unix.Mkdev(tc.major, tc.minor) != dev { t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) } }) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_linux.go0000644061062106075000000000305313172163421023654 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Functions to access/create device major and minor numbers matching the // encoding used by the Linux kernel and glibc. // // The information below is extracted and adapted from bits/sysmacros.h in the // glibc sources: // // dev_t in glibc is 64-bit, with 32-bit major and minor numbers. glibc's // default encoding is MMMM Mmmm mmmM MMmm, where M is a hex digit of the major // number and m is a hex digit of the minor number. This is backward compatible // with legacy systems where dev_t is 16 bits wide, encoded as MMmm. It is also // backward compatible with the Linux kernel, which for some architectures uses // 32-bit dev_t, encoded as mmmM MMmm. package unix // Major returns the major component of a Linux device number. func Major(dev uint64) uint32 { major := uint32((dev & 0x00000000000fff00) >> 8) major |= uint32((dev & 0xfffff00000000000) >> 32) return major } // Minor returns the minor component of a Linux device number. func Minor(dev uint64) uint32 { minor := uint32((dev & 0x00000000000000ff) >> 0) minor |= uint32((dev & 0x00000ffffff00000) >> 12) return minor } // Mkdev returns a Linux device number generated from the given major and minor // components. func Mkdev(major, minor uint32) uint64 { dev := (uint64(major) & 0x00000fff) << 8 dev |= (uint64(major) & 0xfffff000) << 32 dev |= (uint64(minor) & 0x000000ff) << 0 dev |= (uint64(minor) & 0xffffff00) << 12 return dev } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_freebsd.go0000644061062106075000000000176513172163421024137 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Functions to access/create device major and minor numbers matching the // encoding used in FreeBSD's sys/types.h header. // // The information below is extracted and adapted from sys/types.h: // // Minor gives a cookie instead of an index since in order to avoid changing the // meanings of bits 0-15 or wasting time and space shifting bits 16-31 for // devices that don't use them. package unix // Major returns the major component of a FreeBSD device number. func Major(dev uint64) uint32 { return uint32((dev >> 8) & 0xff) } // Minor returns the minor component of a FreeBSD device number. func Minor(dev uint64) uint32 { return uint32(dev & 0xffff00ff) } // Mkdev returns a FreeBSD device number generated from the given major and // minor components. func Mkdev(major, minor uint32) uint64 { return (uint64(major) << 8) | uint64(minor) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_dragonfly_test.go0000644061062106075000000000242613172163421025544 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix_test import ( "fmt" "testing" "golang.org/x/sys/unix" ) func TestDevices(t *testing.T) { testCases := []struct { path string major uint32 minor uint32 }{ // Minor is a cookie instead of an index on DragonFlyBSD {"/dev/null", 10, 0x00000002}, {"/dev/random", 10, 0x00000003}, {"/dev/urandom", 10, 0x00000004}, {"/dev/zero", 10, 0x0000000c}, {"/dev/bpf", 15, 0xffff00ff}, } for _, tc := range testCases { t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { var stat unix.Stat_t err := unix.Stat(tc.path, &stat) if err != nil { t.Errorf("failed to stat device: %v", err) return } dev := uint64(stat.Rdev) if unix.Major(dev) != tc.major { t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) } if unix.Minor(dev) != tc.minor { t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) } if unix.Mkdev(tc.major, tc.minor) != dev { t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) } }) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_dragonfly.go0000644061062106075000000000200613172163421024477 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Functions to access/create device major and minor numbers matching the // encoding used in Dragonfly's sys/types.h header. // // The information below is extracted and adapted from sys/types.h: // // Minor gives a cookie instead of an index since in order to avoid changing the // meanings of bits 0-15 or wasting time and space shifting bits 16-31 for // devices that don't use them. package unix // Major returns the major component of a DragonFlyBSD device number. func Major(dev uint64) uint32 { return uint32((dev >> 8) & 0xff) } // Minor returns the minor component of a DragonFlyBSD device number. func Minor(dev uint64) uint32 { return uint32(dev & 0xffff00ff) } // Mkdev returns a DragonFlyBSD device number generated from the given major and // minor components. func Mkdev(major, minor uint32) uint64 { return (uint64(major) << 8) | uint64(minor) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_darwin_test.go0000644061062106075000000000244213172163421025041 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix_test import ( "fmt" "testing" "golang.org/x/sys/unix" ) func TestDevices(t *testing.T) { testCases := []struct { path string major uint32 minor uint32 }{ // Most of the device major/minor numbers on Darwin are // dynamically generated by devfs. These are some well-known // static numbers. {"/dev/ttyp0", 4, 0}, {"/dev/ttys0", 4, 48}, {"/dev/ptyp0", 5, 0}, {"/dev/ptyr0", 5, 32}, } for _, tc := range testCases { t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { var stat unix.Stat_t err := unix.Stat(tc.path, &stat) if err != nil { t.Errorf("failed to stat device: %v", err) return } dev := uint64(stat.Rdev) if unix.Major(dev) != tc.major { t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) } if unix.Minor(dev) != tc.minor { t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) } if unix.Mkdev(tc.major, tc.minor) != dev { t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) } }) } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/dev_darwin.go0000644061062106075000000000135313172163421024002 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Functions to access/create device major and minor numbers matching the // encoding used in Darwin's sys/types.h header. package unix // Major returns the major component of a Darwin device number. func Major(dev uint64) uint32 { return uint32((dev >> 24) & 0xff) } // Minor returns the minor component of a Darwin device number. func Minor(dev uint64) uint32 { return uint32(dev & 0xffffff) } // Mkdev returns a Darwin device number generated from the given major and minor // components. func Mkdev(major, minor uint32) uint64 { return (uint64(major) << 24) | uint64(minor) } lxd-2.0.11/dist/src/golang.org/x/sys/unix/creds_test.go0000644061062106075000000000637113172163421024024 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux package unix_test import ( "bytes" "net" "os" "syscall" "testing" "golang.org/x/sys/unix" ) // TestSCMCredentials tests the sending and receiving of credentials // (PID, UID, GID) in an ancillary message between two UNIX // sockets. The SO_PASSCRED socket option is enabled on the sending // socket for this to work. func TestSCMCredentials(t *testing.T) { socketTypeTests := []struct { socketType int dataLen int }{ { unix.SOCK_STREAM, 1, }, { unix.SOCK_DGRAM, 0, }, } for _, tt := range socketTypeTests { fds, err := unix.Socketpair(unix.AF_LOCAL, tt.socketType, 0) if err != nil { t.Fatalf("Socketpair: %v", err) } defer unix.Close(fds[0]) defer unix.Close(fds[1]) err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1) if err != nil { t.Fatalf("SetsockoptInt: %v", err) } srvFile := os.NewFile(uintptr(fds[0]), "server") defer srvFile.Close() srv, err := net.FileConn(srvFile) if err != nil { t.Errorf("FileConn: %v", err) return } defer srv.Close() cliFile := os.NewFile(uintptr(fds[1]), "client") defer cliFile.Close() cli, err := net.FileConn(cliFile) if err != nil { t.Errorf("FileConn: %v", err) return } defer cli.Close() var ucred unix.Ucred if os.Getuid() != 0 { ucred.Pid = int32(os.Getpid()) ucred.Uid = 0 ucred.Gid = 0 oob := unix.UnixCredentials(&ucred) _, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) if op, ok := err.(*net.OpError); ok { err = op.Err } if sys, ok := err.(*os.SyscallError); ok { err = sys.Err } if err != syscall.EPERM { t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err) } } ucred.Pid = int32(os.Getpid()) ucred.Uid = uint32(os.Getuid()) ucred.Gid = uint32(os.Getgid()) oob := unix.UnixCredentials(&ucred) // On SOCK_STREAM, this is internally going to send a dummy byte n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) if err != nil { t.Fatalf("WriteMsgUnix: %v", err) } if n != 0 { t.Fatalf("WriteMsgUnix n = %d, want 0", n) } if oobn != len(oob) { t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob)) } oob2 := make([]byte, 10*len(oob)) n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2) if err != nil { t.Fatalf("ReadMsgUnix: %v", err) } if flags != 0 { t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags) } if n != tt.dataLen { t.Fatalf("ReadMsgUnix n = %d, want %d", n, tt.dataLen) } if oobn2 != oobn { // without SO_PASSCRED set on the socket, ReadMsgUnix will // return zero oob bytes t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn) } oob2 = oob2[:oobn2] if !bytes.Equal(oob, oob2) { t.Fatal("ReadMsgUnix oob bytes don't match") } scm, err := unix.ParseSocketControlMessage(oob2) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } newUcred, err := unix.ParseUnixCredentials(&scm[0]) if err != nil { t.Fatalf("ParseUnixCredentials: %v", err) } if *newUcred != ucred { t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred) } } } lxd-2.0.11/dist/src/golang.org/x/sys/unix/constants.go0000644061062106075000000000043513172163421023674 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix const ( R_OK = 0x4 W_OK = 0x2 X_OK = 0x1 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/cap_freebsd.go0000644061062106075000000001207613172163421024121 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build freebsd package unix import ( errorspkg "errors" "fmt" ) // Go implementation of C mostly found in /usr/src/sys/kern/subr_capability.c const ( // This is the version of CapRights this package understands. See C implementation for parallels. capRightsGoVersion = CAP_RIGHTS_VERSION_00 capArSizeMin = CAP_RIGHTS_VERSION_00 + 2 capArSizeMax = capRightsGoVersion + 2 ) var ( bit2idx = []int{ -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, } ) func capidxbit(right uint64) int { return int((right >> 57) & 0x1f) } func rightToIndex(right uint64) (int, error) { idx := capidxbit(right) if idx < 0 || idx >= len(bit2idx) { return -2, fmt.Errorf("index for right 0x%x out of range", right) } return bit2idx[idx], nil } func caprver(right uint64) int { return int(right >> 62) } func capver(rights *CapRights) int { return caprver(rights.Rights[0]) } func caparsize(rights *CapRights) int { return capver(rights) + 2 } // CapRightsSet sets the permissions in setrights in rights. func CapRightsSet(rights *CapRights, setrights []uint64) error { // This is essentially a copy of cap_rights_vset() if capver(rights) != CAP_RIGHTS_VERSION_00 { return fmt.Errorf("bad rights version %d", capver(rights)) } n := caparsize(rights) if n < capArSizeMin || n > capArSizeMax { return errorspkg.New("bad rights size") } for _, right := range setrights { if caprver(right) != CAP_RIGHTS_VERSION_00 { return errorspkg.New("bad right version") } i, err := rightToIndex(right) if err != nil { return err } if i >= n { return errorspkg.New("index overflow") } if capidxbit(rights.Rights[i]) != capidxbit(right) { return errorspkg.New("index mismatch") } rights.Rights[i] |= right if capidxbit(rights.Rights[i]) != capidxbit(right) { return errorspkg.New("index mismatch (after assign)") } } return nil } // CapRightsClear clears the permissions in clearrights from rights. func CapRightsClear(rights *CapRights, clearrights []uint64) error { // This is essentially a copy of cap_rights_vclear() if capver(rights) != CAP_RIGHTS_VERSION_00 { return fmt.Errorf("bad rights version %d", capver(rights)) } n := caparsize(rights) if n < capArSizeMin || n > capArSizeMax { return errorspkg.New("bad rights size") } for _, right := range clearrights { if caprver(right) != CAP_RIGHTS_VERSION_00 { return errorspkg.New("bad right version") } i, err := rightToIndex(right) if err != nil { return err } if i >= n { return errorspkg.New("index overflow") } if capidxbit(rights.Rights[i]) != capidxbit(right) { return errorspkg.New("index mismatch") } rights.Rights[i] &= ^(right & 0x01FFFFFFFFFFFFFF) if capidxbit(rights.Rights[i]) != capidxbit(right) { return errorspkg.New("index mismatch (after assign)") } } return nil } // CapRightsIsSet checks whether all the permissions in setrights are present in rights. func CapRightsIsSet(rights *CapRights, setrights []uint64) (bool, error) { // This is essentially a copy of cap_rights_is_vset() if capver(rights) != CAP_RIGHTS_VERSION_00 { return false, fmt.Errorf("bad rights version %d", capver(rights)) } n := caparsize(rights) if n < capArSizeMin || n > capArSizeMax { return false, errorspkg.New("bad rights size") } for _, right := range setrights { if caprver(right) != CAP_RIGHTS_VERSION_00 { return false, errorspkg.New("bad right version") } i, err := rightToIndex(right) if err != nil { return false, err } if i >= n { return false, errorspkg.New("index overflow") } if capidxbit(rights.Rights[i]) != capidxbit(right) { return false, errorspkg.New("index mismatch") } if (rights.Rights[i] & right) != right { return false, nil } } return true, nil } func capright(idx uint64, bit uint64) uint64 { return ((1 << (57 + idx)) | bit) } // CapRightsInit returns a pointer to an initialised CapRights structure filled with rights. // See man cap_rights_init(3) and rights(4). func CapRightsInit(rights []uint64) (*CapRights, error) { var r CapRights r.Rights[0] = (capRightsGoVersion << 62) | capright(0, 0) r.Rights[1] = capright(1, 0) err := CapRightsSet(&r, rights) if err != nil { return nil, err } return &r, nil } // CapRightsLimit reduces the operations permitted on fd to at most those contained in rights. // The capability rights on fd can never be increased by CapRightsLimit. // See man cap_rights_limit(2) and rights(4). func CapRightsLimit(fd uintptr, rights *CapRights) error { return capRightsLimit(int(fd), rights) } // CapRightsGet returns a CapRights structure containing the operations permitted on fd. // See man cap_rights_get(3) and rights(4). func CapRightsGet(fd uintptr) (*CapRights, error) { r, err := CapRightsInit(nil) if err != nil { return nil, err } err = capRightsGet(capRightsGoVersion, int(fd), r) if err != nil { return nil, err } return r, nil } lxd-2.0.11/dist/src/golang.org/x/sys/unix/bluetooth_linux.go0000644061062106075000000000121713172163421025103 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Bluetooth sockets and messages package unix // Bluetooth Protocols const ( BTPROTO_L2CAP = 0 BTPROTO_HCI = 1 BTPROTO_SCO = 2 BTPROTO_RFCOMM = 3 BTPROTO_BNEP = 4 BTPROTO_CMTP = 5 BTPROTO_HIDP = 6 BTPROTO_AVDTP = 7 ) const ( HCI_CHANNEL_RAW = 0 HCI_CHANNEL_USER = 1 HCI_CHANNEL_MONITOR = 2 HCI_CHANNEL_CONTROL = 3 ) // Socketoption Level const ( SOL_BLUETOOTH = 0x112 SOL_HCI = 0x0 SOL_L2CAP = 0x6 SOL_RFCOMM = 0x12 SOL_SCO = 0x11 ) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_solaris_amd64.s0000644061062106075000000000065213172163421025025 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System calls for amd64, Solaris are implemented in runtime/syscall_solaris.go // TEXT ·sysvicall6(SB),NOSPLIT,$0-88 JMP syscall·sysvicall6(SB) TEXT ·rawSysvicall6(SB),NOSPLIT,$0-88 JMP syscall·rawSysvicall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_openbsd_arm.s0000644061062106075000000000123213172163421024642 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for ARM, OpenBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 B syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 B syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 B syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_openbsd_amd64.s0000644061062106075000000000124713172163421025004 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for AMD64, OpenBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-104 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_openbsd_386.s0000644061062106075000000000124413172163421024406 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for 386, OpenBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_netbsd_arm.s0000644061062106075000000000123113172163421024466 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for ARM, NetBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 B syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 B syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 B syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_netbsd_amd64.s0000644061062106075000000000124613172163421024630 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for AMD64, NetBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-104 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_netbsd_386.s0000644061062106075000000000124313172163421024232 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for 386, NetBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_linux_s390x.s0000644061062106075000000000117313172163421024462 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build s390x // +build linux // +build !gccgo #include "textflag.h" // // System calls for s390x, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 BR syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 BR syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 BR syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 BR syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_linux_ppc64x.s0000644061062106075000000000120313172163421024712 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build ppc64 ppc64le // +build !gccgo #include "textflag.h" // // System calls for ppc64, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 BR syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 BR syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 BR syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 BR syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_linux_mipsx.s0000644061062106075000000000130213172163421024726 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build mips mipsle // +build !gccgo #include "textflag.h" // // System calls for mips, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_linux_mips64x.s0000644061062106075000000000121213172163421025100 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build mips64 mips64le // +build !gccgo #include "textflag.h" // // System calls for mips64, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_linux_arm64.s0000644061062106075000000000111713172163421024523 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build arm64 // +build !gccgo #include "textflag.h" // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 B syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 B syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_linux_arm.s0000644061062106075000000000121113172163421024344 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System calls for arm, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 B syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 B syscall·RawSyscall6(SB) TEXT ·seek(SB),NOSPLIT,$0-32 B syscall·seek(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_linux_amd64.s0000644061062106075000000000124513172163421024507 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System calls for AMD64, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) TEXT ·gettimeofday(SB),NOSPLIT,$0-16 JMP syscall·gettimeofday(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_linux_386.s0000644061062106075000000000143513172163421024115 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System calls for 386, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) TEXT ·socketcall(SB),NOSPLIT,$0-36 JMP syscall·socketcall(SB) TEXT ·rawsocketcall(SB),NOSPLIT,$0-36 JMP syscall·rawsocketcall(SB) TEXT ·seek(SB),NOSPLIT,$0-28 JMP syscall·seek(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_freebsd_arm.s0000644061062106075000000000123213172163421024622 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for ARM, FreeBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 B syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 B syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 B syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_freebsd_amd64.s0000644061062106075000000000124713172163421024764 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for AMD64, FreeBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-104 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_freebsd_386.s0000644061062106075000000000124413172163421024366 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for 386, FreeBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_dragonfly_amd64.s0000644061062106075000000000125113172163421025332 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for AMD64, DragonFly // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-64 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-88 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-112 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-64 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-88 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_darwin_arm64.s0000644061062106075000000000126313172163421024652 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo // +build arm64,darwin #include "textflag.h" // // System call support for AMD64, Darwin // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 B syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-104 B syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 B syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_darwin_arm.s0000644061062106075000000000125613172163421024502 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo // +build arm,darwin #include "textflag.h" // // System call support for ARM, Darwin // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 B syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 B syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 B syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_darwin_amd64.s0000644061062106075000000000124613172163421024635 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for AMD64, Darwin // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-104 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/asm_darwin_386.s0000644061062106075000000000124313172163421024237 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for 386, Darwin // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-52 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) lxd-2.0.11/dist/src/golang.org/x/sys/unix/README.md0000644061062106075000000002011713172163421022607 0ustar stgraberdomain admins# Building `sys/unix` The sys/unix package provides access to the raw system call interface of the underlying operating system. See: https://godoc.org/golang.org/x/sys/unix Porting Go to a new architecture/OS combination or adding syscalls, types, or constants to an existing architecture/OS pair requires some manual effort; however, there are tools that automate much of the process. ## Build Systems There are currently two ways we generate the necessary files. We are currently migrating the build system to use containers so the builds are reproducible. This is being done on an OS-by-OS basis. Please update this documentation as components of the build system change. ### Old Build System (currently for `GOOS != "Linux" || GOARCH == "sparc64"`) The old build system generates the Go files based on the C header files present on your system. This means that files for a given GOOS/GOARCH pair must be generated on a system with that OS and architecture. This also means that the generated code can differ from system to system, based on differences in the header files. To avoid this, if you are using the old build system, only generate the Go files on an installation with unmodified header files. It is also important to keep track of which version of the OS the files were generated from (ex. Darwin 14 vs Darwin 15). This makes it easier to track the progress of changes and have each OS upgrade correspond to a single change. To build the files for your current OS and architecture, make sure GOOS and GOARCH are set correctly and run `mkall.sh`. This will generate the files for your specific system. Running `mkall.sh -n` shows the commands that will be run. Requirements: bash, perl, go ### New Build System (currently for `GOOS == "Linux" && GOARCH != "sparc64"`) The new build system uses a Docker container to generate the go files directly from source checkouts of the kernel and various system libraries. This means that on any platform that supports Docker, all the files using the new build system can be generated at once, and generated files will not change based on what the person running the scripts has installed on their computer. The OS specific files for the new build system are located in the `${GOOS}` directory, and the build is coordinated by the `${GOOS}/mkall.go` program. When the kernel or system library updates, modify the Dockerfile at `${GOOS}/Dockerfile` to checkout the new release of the source. To build all the files under the new build system, you must be on an amd64/Linux system and have your GOOS and GOARCH set accordingly. Running `mkall.sh` will then generate all of the files for all of the GOOS/GOARCH pairs in the new build system. Running `mkall.sh -n` shows the commands that will be run. Requirements: bash, perl, go, docker ## Component files This section describes the various files used in the code generation process. It also contains instructions on how to modify these files to add a new architecture/OS or to add additional syscalls, types, or constants. Note that if you are using the new build system, the scripts cannot be called normally. They must be called from within the docker container. ### asm files The hand-written assembly file at `asm_${GOOS}_${GOARCH}.s` implements system call dispatch. There are three entry points: ``` func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` The first and second are the standard ones; they differ only in how many arguments can be passed to the kernel. The third is for low-level use by the ForkExec wrapper. Unlike the first two, it does not call into the scheduler to let it know that a system call is running. When porting Go to an new architecture/OS, this file must be implemented for each GOOS/GOARCH pair. ### mksysnum Mksysnum is a script located at `${GOOS}/mksysnum.pl` (or `mksysnum_${GOOS}.pl` for the old system). This script takes in a list of header files containing the syscall number declarations and parses them to produce the corresponding list of Go numeric constants. See `zsysnum_${GOOS}_${GOARCH}.go` for the generated constants. Adding new syscall numbers is mostly done by running the build on a sufficiently new installation of the target OS (or updating the source checkouts for the new build system). However, depending on the OS, you make need to update the parsing in mksysnum. ### mksyscall.pl The `syscall.go`, `syscall_${GOOS}.go`, `syscall_${GOOS}_${GOARCH}.go` are hand-written Go files which implement system calls (for unix, the specific OS, or the specific OS/Architecture pair respectively) that need special handling and list `//sys` comments giving prototypes for ones that can be generated. The mksyscall.pl script takes the `//sys` and `//sysnb` comments and converts them into syscalls. This requires the name of the prototype in the comment to match a syscall number in the `zsysnum_${GOOS}_${GOARCH}.go` file. The function prototype can be exported (capitalized) or not. Adding a new syscall often just requires adding a new `//sys` function prototype with the desired arguments and a capitalized name so it is exported. However, if you want the interface to the syscall to be different, often one will make an unexported `//sys` prototype, an then write a custom wrapper in `syscall_${GOOS}.go`. ### types files For each OS, there is a hand-written Go file at `${GOOS}/types.go` (or `types_${GOOS}.go` on the old system). This file includes standard C headers and creates Go type aliases to the corresponding C types. The file is then fed through godef to get the Go compatible definitions. Finally, the generated code is fed though mkpost.go to format the code correctly and remove any hidden or private identifiers. This cleaned-up code is written to `ztypes_${GOOS}_${GOARCH}.go`. The hardest part about preparing this file is figuring out which headers to include and which symbols need to be `#define`d to get the actual data structures that pass through to the kernel system calls. Some C libraries preset alternate versions for binary compatibility and translate them on the way in and out of system calls, but there is almost always a `#define` that can get the real ones. See `types_darwin.go` and `linux/types.go` for examples. To add a new type, add in the necessary include statement at the top of the file (if it is not already there) and add in a type alias line. Note that if your type is significantly different on different architectures, you may need some `#if/#elif` macros in your include statements. ### mkerrors.sh This script is used to generate the system's various constants. This doesn't just include the error numbers and error strings, but also the signal numbers an a wide variety of miscellaneous constants. The constants come from the list of include files in the `includes_${uname}` variable. A regex then picks out the desired `#define` statements, and generates the corresponding Go constants. The error numbers and strings are generated from `#include `, and the signal numbers and strings are generated from `#include `. All of these constants are written to `zerrors_${GOOS}_${GOARCH}.go` via a C program, `_errors.c`, which prints out all the constants. To add a constant, add the header that includes it to the appropriate variable. Then, edit the regex (if necessary) to match the desired constant. Avoid making the regex too broad to avoid matching unintended constants. ## Generated files ### `zerror_${GOOS}_${GOARCH}.go` A file containing all of the system's generated error numbers, error strings, signal numbers, and constants. Generated by `mkerrors.sh` (see above). ### `zsyscall_${GOOS}_${GOARCH}.go` A file containing all the generated syscalls for a specific GOOS and GOARCH. Generated by `mksyscall.pl` (see above). ### `zsysnum_${GOOS}_${GOARCH}.go` A list of numeric constants for all the syscall number of the specific GOOS and GOARCH. Generated by mksysnum (see above). ### `ztypes_${GOOS}_${GOARCH}.go` A file containing Go types for passing into (or returning from) syscalls. Generated by godefs and the types file (see above). lxd-2.0.11/dist/src/golang.org/x/sys/plan9/0000755061062106075000000000000013172163421021367 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/sys/plan9/zsysnum_plan9.go0000644061062106075000000000204113172163421024546 0ustar stgraberdomain admins// mksysnum_plan9.sh /opt/plan9/sys/src/libc/9syscall/sys.h // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT package plan9 const ( SYS_SYSR1 = 0 SYS_BIND = 2 SYS_CHDIR = 3 SYS_CLOSE = 4 SYS_DUP = 5 SYS_ALARM = 6 SYS_EXEC = 7 SYS_EXITS = 8 SYS_FAUTH = 10 SYS_SEGBRK = 12 SYS_OPEN = 14 SYS_OSEEK = 16 SYS_SLEEP = 17 SYS_RFORK = 19 SYS_PIPE = 21 SYS_CREATE = 22 SYS_FD2PATH = 23 SYS_BRK_ = 24 SYS_REMOVE = 25 SYS_NOTIFY = 28 SYS_NOTED = 29 SYS_SEGATTACH = 30 SYS_SEGDETACH = 31 SYS_SEGFREE = 32 SYS_SEGFLUSH = 33 SYS_RENDEZVOUS = 34 SYS_UNMOUNT = 35 SYS_SEMACQUIRE = 37 SYS_SEMRELEASE = 38 SYS_SEEK = 39 SYS_FVERSION = 40 SYS_ERRSTR = 41 SYS_STAT = 42 SYS_FSTAT = 43 SYS_WSTAT = 44 SYS_FWSTAT = 45 SYS_MOUNT = 46 SYS_AWAIT = 47 SYS_PREAD = 50 SYS_PWRITE = 51 SYS_TSEMACQUIRE = 52 SYS_NSEC = 53 ) lxd-2.0.11/dist/src/golang.org/x/sys/plan9/zsyscall_plan9_amd64.go0000644061062106075000000001461313172163421025665 0ustar stgraberdomain admins// mksyscall.pl -l32 -plan9 syscall_plan9.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package plan9 import "unsafe" // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fd2path(fd int, buf []byte) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FD2PATH, uintptr(fd), uintptr(_p0), uintptr(len(buf))) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]int32) (err error) { r0, _, e1 := Syscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func await(s []byte) (n int, err error) { var _p0 unsafe.Pointer if len(s) > 0 { _p0 = unsafe.Pointer(&s[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_AWAIT, uintptr(_p0), uintptr(len(s)), 0) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func open(path string, mode int) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func create(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) use(unsafe.Pointer(_p0)) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func remove(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_REMOVE, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, edir []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(edir) > 0 { _p1 = unsafe.Pointer(&edir[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir))) use(unsafe.Pointer(_p0)) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(name string, old string, flag int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(old) if err != nil { return } r0, _, e1 := Syscall(SYS_BIND, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag)) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(fd int, afd int, old string, flag int, aname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(old) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(aname) if err != nil { return } r0, _, e1 := Syscall6(SYS_MOUNT, uintptr(fd), uintptr(afd), uintptr(unsafe.Pointer(_p0)), uintptr(flag), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wstat(path string, edir []byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(edir) > 0 { _p1 = unsafe.Pointer(&edir[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir))) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int, newfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), uintptr(newfd), 0) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { r0, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, edir []byte) (n int, err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fwstat(fd int, edir []byte) (err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FWSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) if int32(r0) == -1 { err = e1 } return } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/zsyscall_plan9_386.go0000644061062106075000000001461313172163421025272 0ustar stgraberdomain admins// mksyscall.pl -l32 -plan9 syscall_plan9.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package plan9 import "unsafe" // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fd2path(fd int, buf []byte) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FD2PATH, uintptr(fd), uintptr(_p0), uintptr(len(buf))) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]int32) (err error) { r0, _, e1 := Syscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func await(s []byte) (n int, err error) { var _p0 unsafe.Pointer if len(s) > 0 { _p0 = unsafe.Pointer(&s[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_AWAIT, uintptr(_p0), uintptr(len(s)), 0) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func open(path string, mode int) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func create(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) use(unsafe.Pointer(_p0)) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func remove(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_REMOVE, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, edir []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(edir) > 0 { _p1 = unsafe.Pointer(&edir[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir))) use(unsafe.Pointer(_p0)) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(name string, old string, flag int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(old) if err != nil { return } r0, _, e1 := Syscall(SYS_BIND, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag)) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(fd int, afd int, old string, flag int, aname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(old) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(aname) if err != nil { return } r0, _, e1 := Syscall6(SYS_MOUNT, uintptr(fd), uintptr(afd), uintptr(unsafe.Pointer(_p0)), uintptr(flag), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wstat(path string, edir []byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(edir) > 0 { _p1 = unsafe.Pointer(&edir[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir))) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int, newfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), uintptr(newfd), 0) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { r0, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, edir []byte) (n int, err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fwstat(fd int, edir []byte) (err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FWSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) if int32(r0) == -1 { err = e1 } return } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/syscall_test.go0000644061062106075000000000141613172163421024431 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build plan9 package plan9_test import ( "testing" "golang.org/x/sys/plan9" ) func testSetGetenv(t *testing.T, key, value string) { err := plan9.Setenv(key, value) if err != nil { t.Fatalf("Setenv failed to set %q: %v", value, err) } newvalue, found := plan9.Getenv(key) if !found { t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) } if newvalue != value { t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) } } func TestEnv(t *testing.T) { testSetGetenv(t, "TESTENV", "AVALUE") // make sure TESTENV gets set to "", not deleted testSetGetenv(t, "TESTENV", "") } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/syscall_plan9.go0000644061062106075000000001601613172163421024477 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Plan 9 system calls. // This file is compiled as ordinary Go code, // but it is also input to mksyscall, // which parses the //sys lines and generates system call stubs. // Note that sometimes we use a lowercase //sys name and // wrap it in our own nicer implementation. package plan9 import ( "syscall" "unsafe" ) // A Note is a string describing a process note. // It implements the os.Signal interface. type Note string func (n Note) Signal() {} func (n Note) String() string { return string(n) } var ( Stdin = 0 Stdout = 1 Stderr = 2 ) // For testing: clients can set this flag to force // creation of IPv6 sockets to return EAFNOSUPPORT. var SocketDisableIPv6 bool func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.ErrorString) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.ErrorString) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) func atoi(b []byte) (n uint) { n = 0 for i := 0; i < len(b); i++ { n = n*10 + uint(b[i]-'0') } return } func cstring(s []byte) string { for i := range s { if s[i] == 0 { return string(s[0:i]) } } return string(s) } func errstr() string { var buf [ERRMAX]byte RawSyscall(SYS_ERRSTR, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), 0) buf[len(buf)-1] = 0 return cstring(buf[:]) } // Implemented in assembly to import from runtime. func exit(code int) func Exit(code int) { exit(code) } func readnum(path string) (uint, error) { var b [12]byte fd, e := Open(path, O_RDONLY) if e != nil { return 0, e } defer Close(fd) n, e := Pread(fd, b[:], 0) if e != nil { return 0, e } m := 0 for ; m < n && b[m] == ' '; m++ { } return atoi(b[m : n-1]), nil } func Getpid() (pid int) { n, _ := readnum("#c/pid") return int(n) } func Getppid() (ppid int) { n, _ := readnum("#c/ppid") return int(n) } func Read(fd int, p []byte) (n int, err error) { return Pread(fd, p, -1) } func Write(fd int, p []byte) (n int, err error) { return Pwrite(fd, p, -1) } var ioSync int64 //sys fd2path(fd int, buf []byte) (err error) func Fd2path(fd int) (path string, err error) { var buf [512]byte e := fd2path(fd, buf[:]) if e != nil { return "", e } return cstring(buf[:]), nil } //sys pipe(p *[2]int32) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return syscall.ErrorString("bad arg in system call") } var pp [2]int32 err = pipe(&pp) p[0] = int(pp[0]) p[1] = int(pp[1]) return } // Underlying system call writes to newoffset via pointer. // Implemented in assembly to avoid allocation. func seek(placeholder uintptr, fd int, offset int64, whence int) (newoffset int64, err string) func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { newoffset, e := seek(0, fd, offset, whence) if newoffset == -1 { err = syscall.ErrorString(e) } return } func Mkdir(path string, mode uint32) (err error) { fd, err := Create(path, O_RDONLY, DMDIR|mode) if fd != -1 { Close(fd) } return } type Waitmsg struct { Pid int Time [3]uint32 Msg string } func (w Waitmsg) Exited() bool { return true } func (w Waitmsg) Signaled() bool { return false } func (w Waitmsg) ExitStatus() int { if len(w.Msg) == 0 { // a normal exit returns no message return 0 } return 1 } //sys await(s []byte) (n int, err error) func Await(w *Waitmsg) (err error) { var buf [512]byte var f [5][]byte n, err := await(buf[:]) if err != nil || w == nil { return } nf := 0 p := 0 for i := 0; i < n && nf < len(f)-1; i++ { if buf[i] == ' ' { f[nf] = buf[p:i] p = i + 1 nf++ } } f[nf] = buf[p:] nf++ if nf != len(f) { return syscall.ErrorString("invalid wait message") } w.Pid = int(atoi(f[0])) w.Time[0] = uint32(atoi(f[1])) w.Time[1] = uint32(atoi(f[2])) w.Time[2] = uint32(atoi(f[3])) w.Msg = cstring(f[4]) if w.Msg == "''" { // await() returns '' for no error w.Msg = "" } return } func Unmount(name, old string) (err error) { fixwd() oldp, err := BytePtrFromString(old) if err != nil { return err } oldptr := uintptr(unsafe.Pointer(oldp)) var r0 uintptr var e syscall.ErrorString // bind(2) man page: If name is zero, everything bound or mounted upon old is unbound or unmounted. if name == "" { r0, _, e = Syscall(SYS_UNMOUNT, _zero, oldptr, 0) } else { namep, err := BytePtrFromString(name) if err != nil { return err } r0, _, e = Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(namep)), oldptr, 0) } if int32(r0) == -1 { err = e } return } func Fchdir(fd int) (err error) { path, err := Fd2path(fd) if err != nil { return } return Chdir(path) } type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Usec = int32(nsec % 1e9 / 1e3) tv.Sec = int32(nsec / 1e9) return } func nsec() int64 { var scratch int64 r0, _, _ := Syscall(SYS_NSEC, uintptr(unsafe.Pointer(&scratch)), 0, 0) // TODO(aram): remove hack after I fix _nsec in the pc64 kernel. if r0 == 0 { return scratch } return int64(r0) } func Gettimeofday(tv *Timeval) error { nsec := nsec() *tv = NsecToTimeval(nsec) return nil } func Getpagesize() int { return 0x1000 } func Getegid() (egid int) { return -1 } func Geteuid() (euid int) { return -1 } func Getgid() (gid int) { return -1 } func Getuid() (uid int) { return -1 } func Getgroups() (gids []int, err error) { return make([]int, 0), nil } //sys open(path string, mode int) (fd int, err error) func Open(path string, mode int) (fd int, err error) { fixwd() return open(path, mode) } //sys create(path string, mode int, perm uint32) (fd int, err error) func Create(path string, mode int, perm uint32) (fd int, err error) { fixwd() return create(path, mode, perm) } //sys remove(path string) (err error) func Remove(path string) error { fixwd() return remove(path) } //sys stat(path string, edir []byte) (n int, err error) func Stat(path string, edir []byte) (n int, err error) { fixwd() return stat(path, edir) } //sys bind(name string, old string, flag int) (err error) func Bind(name string, old string, flag int) (err error) { fixwd() return bind(name, old, flag) } //sys mount(fd int, afd int, old string, flag int, aname string) (err error) func Mount(fd int, afd int, old string, flag int, aname string) (err error) { fixwd() return mount(fd, afd, old, flag, aname) } //sys wstat(path string, edir []byte) (err error) func Wstat(path string, edir []byte) (err error) { fixwd() return wstat(path, edir) } //sys chdir(path string) (err error) //sys Dup(oldfd int, newfd int) (fd int, err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) //sys Close(fd int) (err error) //sys Fstat(fd int, edir []byte) (n int, err error) //sys Fwstat(fd int, edir []byte) (err error) lxd-2.0.11/dist/src/golang.org/x/sys/plan9/syscall.go0000644061062106075000000000474413172163421023401 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build plan9 // Package plan9 contains an interface to the low-level operating system // primitives. OS details vary depending on the underlying system, and // by default, godoc will display the OS-specific documentation for the current // system. If you want godoc to display documentation for another // system, set $GOOS and $GOARCH to the desired system. For example, if // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS // to freebsd and $GOARCH to arm. // The primary use of this package is inside other packages that provide a more // portable interface to the system, such as "os", "time" and "net". Use // those packages rather than this one if you can. // For details of the functions and data types in this package consult // the manuals for the appropriate operating system. // These calls return err == nil to indicate success; otherwise // err represents an operating system error describing the failure and // holds a value of type syscall.ErrorString. package plan9 // import "golang.org/x/sys/plan9" import "unsafe" // ByteSliceFromString returns a NUL-terminated slice of bytes // containing the text of s. If s contains a NUL byte at any // location, it returns (nil, EINVAL). func ByteSliceFromString(s string) ([]byte, error) { for i := 0; i < len(s); i++ { if s[i] == 0 { return nil, EINVAL } } a := make([]byte, len(s)+1) copy(a, s) return a, nil } // BytePtrFromString returns a pointer to a NUL-terminated array of // bytes containing the text of s. If s contains a NUL byte at any // location, it returns (nil, EINVAL). func BytePtrFromString(s string) (*byte, error) { a, err := ByteSliceFromString(s) if err != nil { return nil, err } return &a[0], nil } // Single-word zero for use when we need a valid pointer to 0 bytes. // See mksyscall.pl. var _zero uintptr func (ts *Timespec) Unix() (sec int64, nsec int64) { return int64(ts.Sec), int64(ts.Nsec) } func (tv *Timeval) Unix() (sec int64, nsec int64) { return int64(tv.Sec), int64(tv.Usec) * 1000 } func (ts *Timespec) Nano() int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func (tv *Timeval) Nano() int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 } // use is a no-op, but the compiler cannot see that it is. // Calling use(p) ensures that p is kept live until that point. //go:noescape func use(p unsafe.Pointer) lxd-2.0.11/dist/src/golang.org/x/sys/plan9/str.go0000644061062106075000000000076313172163421022534 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build plan9 package plan9 func itoa(val int) string { // do it here rather than with fmt to avoid dependency if val < 0 { return "-" + itoa(-val) } var buf [32]byte // big enough for int64 i := len(buf) - 1 for val >= 10 { buf[i] = byte(val%10 + '0') i-- val /= 10 } buf[i] = byte(val + '0') return string(buf[i:]) } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/race0.go0000644061062106075000000000067713172163421022722 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build plan9,!race package plan9 import ( "unsafe" ) const raceenabled = false func raceAcquire(addr unsafe.Pointer) { } func raceReleaseMerge(addr unsafe.Pointer) { } func raceReadRange(addr unsafe.Pointer, len int) { } func raceWriteRange(addr unsafe.Pointer, len int) { } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/race.go0000644061062106075000000000111013172163421022621 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build plan9,race package plan9 import ( "runtime" "unsafe" ) const raceenabled = true func raceAcquire(addr unsafe.Pointer) { runtime.RaceAcquire(addr) } func raceReleaseMerge(addr unsafe.Pointer) { runtime.RaceReleaseMerge(addr) } func raceReadRange(addr unsafe.Pointer, len int) { runtime.RaceReadRange(addr, len) } func raceWriteRange(addr unsafe.Pointer, len int) { runtime.RaceWriteRange(addr, len) } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/pwd_plan9.go0000644061062106075000000000063413172163421023616 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.5 package plan9 func fixwd() { } func Getwd() (wd string, err error) { fd, err := open(".", O_RDONLY) if err != nil { return "", err } defer Close(fd) return Fd2path(fd) } func Chdir(path string) error { return chdir(path) } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/pwd_go15_plan9.go0000644061062106075000000000056413172163421024453 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.5 package plan9 import "syscall" func fixwd() { syscall.Fixwd() } func Getwd() (wd string, err error) { return syscall.Getwd() } func Chdir(path string) error { return syscall.Chdir(path) } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/mksysnum_plan9.sh0000755061062106075000000000071313172163421024720 0ustar stgraberdomain admins#!/bin/sh # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. COMMAND="mksysnum_plan9.sh $@" cat <) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, errno error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($func, $in, $out, $sysname) = ($2, $3, $4, $5); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # Try in vain to keep people from editing this file. # The theory is that they jump into the middle of the file # without reading the header. $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; # Go function header. my $out_decl = @out ? sprintf(" (%s)", join(', ', @out)) : ""; $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out_decl; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my @uses = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, $errvar = BytePtrFromString($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, _ = BytePtrFromString($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass dummy pointer in that case. # Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). $text .= "\tvar _p$n unsafe.Pointer\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = unsafe.Pointer(\&${name}[0])\n\t}"; $text .= " else {\n\t\t_p$n = unsafe.Pointer(&_zero)\n\t}"; $text .= "\n"; push @args, "uintptr(_p$n)", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && ($openbsd || $netbsd)) { push @args, "0"; if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $dragonfly) { if ($func !~ /^extp(read|write)/i) { push @args, "0"; } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $_32bit ne "") { if(@args % 2 && $arm) { # arm abi specifies 64-bit argument uses # (even, odd) pair push @args, "0" } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name>>32)"; } } else { push @args, "uintptr($name)"; } } # Determine which form to use; pad args with zeros. my $asm = "Syscall"; if ($nonblock) { $asm = "RawSyscall"; } if(@args <= 3) { while(@args < 3) { push @args, "0"; } } elsif(@args <= 6) { $asm .= "6"; while(@args < 6) { push @args, "0"; } } elsif(@args <= 9) { $asm .= "9"; while(@args < 9) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # System call number. if($sysname eq "") { $sysname = "SYS_$func"; $sysname =~ s/([a-z])([A-Z])/${1}_$2/g; # turn FooBar into Foo_Bar $sysname =~ y/a-z/A-Z/; if($nacl) { $sysname =~ y/A-Z/a-z/; } } # Actual call. my $args = join(', ', @args); my $call = "$asm($sysname, $args)"; # Assign return values. my $body = ""; my @ret = ("_", "_", "_"); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err" && !$plan9) { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } elsif($name eq "err" && $plan9) { $ret[0] = "r0"; $ret[2] = "e1"; next; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1" || $plan9) { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } foreach my $use (@uses) { $text .= "\t$use\n"; } $text .= $body; if ($plan9 && $ret[2] eq "e1") { $text .= "\tif int32(r0) == -1 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } elsif ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n\n"; } chomp $text; chomp $text; if($errors) { exit 1; } print <_const.go # Pull out the error names for later. errors=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | sort ) # Pull out the signal names for later. signals=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort ) # Again, writing regexps to a file. echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | sort >_error.grep echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort >_signal.grep echo '// mkerrors.sh' "$@" echo '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT' echo go tool cgo -godefs -- "$@" _const.go >_error.out cat _error.out | grep -vf _error.grep | grep -vf _signal.grep echo echo '// Errors' echo 'const (' cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= Errno(\1)/' echo ')' echo echo '// Signals' echo 'const (' cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= Signal(\1)/' echo ')' # Run C program to print error and syscall strings. ( echo -E " #include #include #include #include #include #include #define nelem(x) (sizeof(x)/sizeof((x)[0])) enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below int errors[] = { " for i in $errors do echo -E ' '$i, done echo -E " }; int signals[] = { " for i in $signals do echo -E ' '$i, done # Use -E because on some systems bash builtin interprets \n itself. echo -E ' }; static int intcmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } int main(void) { int i, j, e; char buf[1024], *p; printf("\n\n// Error table\n"); printf("var errors = [...]string {\n"); qsort(errors, nelem(errors), sizeof errors[0], intcmp); for(i=0; i 0 && errors[i-1] == e) continue; strcpy(buf, strerror(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); printf("\n\n// Signal table\n"); printf("var signals = [...]string {\n"); qsort(signals, nelem(signals), sizeof signals[0], intcmp); for(i=0; i 0 && signals[i-1] == e) continue; strcpy(buf, strsignal(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; // cut trailing : number. p = strrchr(buf, ":"[0]); if(p) *p = '\0'; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); return 0; } ' ) >_errors.c $CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out lxd-2.0.11/dist/src/golang.org/x/sys/plan9/mkall.sh0000755061062106075000000001011013172163421023017 0ustar stgraberdomain admins#!/usr/bin/env bash # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # The plan9 package provides access to the raw system call # interface of the underlying operating system. Porting Go to # a new architecture/operating system combination requires # some manual effort, though there are tools that automate # much of the process. The auto-generated files have names # beginning with z. # # This script runs or (given -n) prints suggested commands to generate z files # for the current system. Running those commands is not automatic. # This script is documentation more than anything else. # # * asm_${GOOS}_${GOARCH}.s # # This hand-written assembly file implements system call dispatch. # There are three entry points: # # func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr); # func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr); # func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr); # # The first and second are the standard ones; they differ only in # how many arguments can be passed to the kernel. # The third is for low-level use by the ForkExec wrapper; # unlike the first two, it does not call into the scheduler to # let it know that a system call is running. # # * syscall_${GOOS}.go # # This hand-written Go file implements system calls that need # special handling and lists "//sys" comments giving prototypes # for ones that can be auto-generated. Mksyscall reads those # comments to generate the stubs. # # * syscall_${GOOS}_${GOARCH}.go # # Same as syscall_${GOOS}.go except that it contains code specific # to ${GOOS} on one particular architecture. # # * types_${GOOS}.c # # This hand-written C file includes standard C headers and then # creates typedef or enum names beginning with a dollar sign # (use of $ in variable names is a gcc extension). The hardest # part about preparing this file is figuring out which headers to # include and which symbols need to be #defined to get the # actual data structures that pass through to the kernel system calls. # Some C libraries present alternate versions for binary compatibility # and translate them on the way in and out of system calls, but # there is almost always a #define that can get the real ones. # See types_darwin.c and types_linux.c for examples. # # * zerror_${GOOS}_${GOARCH}.go # # This machine-generated file defines the system's error numbers, # error strings, and signal numbers. The generator is "mkerrors.sh". # Usually no arguments are needed, but mkerrors.sh will pass its # arguments on to godefs. # # * zsyscall_${GOOS}_${GOARCH}.go # # Generated by mksyscall.pl; see syscall_${GOOS}.go above. # # * zsysnum_${GOOS}_${GOARCH}.go # # Generated by mksysnum_${GOOS}. # # * ztypes_${GOOS}_${GOARCH}.go # # Generated by godefs; see types_${GOOS}.c above. GOOSARCH="${GOOS}_${GOARCH}" # defaults mksyscall="./mksyscall.pl" mkerrors="./mkerrors.sh" zerrors="zerrors_$GOOSARCH.go" mksysctl="" zsysctl="zsysctl_$GOOSARCH.go" mksysnum= mktypes= run="sh" case "$1" in -syscalls) for i in zsyscall*go do sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i rm _$i done exit 0 ;; -n) run="cat" shift esac case "$#" in 0) ;; *) echo 'usage: mkall.sh [-n]' 1>&2 exit 2 esac case "$GOOSARCH" in _* | *_ | _) echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 exit 1 ;; plan9_386) mkerrors= mksyscall="./mksyscall.pl -l32 -plan9" mksysnum="./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h" mktypes="XXX" ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 ;; esac ( if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi case "$GOOS" in plan9) syscall_goos="syscall_$GOOS.go" if [ -n "$mksyscall" ]; then echo "$mksyscall $syscall_goos syscall_$GOOSARCH.go |gofmt >zsyscall_$GOOSARCH.go"; fi ;; esac if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go"; fi ) | $run lxd-2.0.11/dist/src/golang.org/x/sys/plan9/errors_plan9.go0000644061062106075000000000303613172163421024337 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package plan9 import "syscall" // Constants const ( // Invented values to support what package os expects. O_CREAT = 0x02000 O_APPEND = 0x00400 O_NOCTTY = 0x00000 O_NONBLOCK = 0x00000 O_SYNC = 0x00000 O_ASYNC = 0x00000 S_IFMT = 0x1f000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 ) // Errors var ( EINVAL = syscall.NewError("bad arg in system call") ENOTDIR = syscall.NewError("not a directory") EISDIR = syscall.NewError("file is a directory") ENOENT = syscall.NewError("file does not exist") EEXIST = syscall.NewError("file already exists") EMFILE = syscall.NewError("no free file descriptors") EIO = syscall.NewError("i/o error") ENAMETOOLONG = syscall.NewError("file name too long") EINTR = syscall.NewError("interrupted") EPERM = syscall.NewError("permission denied") EBUSY = syscall.NewError("no free devices") ETIMEDOUT = syscall.NewError("connection timed out") EPLAN9 = syscall.NewError("not supported by plan 9") // The following errors do not correspond to any // Plan 9 system messages. Invented to support // what package os and others expect. EACCES = syscall.NewError("access permission denied") EAFNOSUPPORT = syscall.NewError("address family not supported by protocol") ) lxd-2.0.11/dist/src/golang.org/x/sys/plan9/env_unset.go0000644061062106075000000000046313172163421023727 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.4 package plan9 import "syscall" func Unsetenv(key string) error { // This was added in Go 1.4. return syscall.Unsetenv(key) } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/env_plan9.go0000644061062106075000000000075113172163421023614 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Plan 9 environment variables. package plan9 import ( "syscall" ) func Getenv(key string) (value string, found bool) { return syscall.Getenv(key) } func Setenv(key, value string) error { return syscall.Setenv(key, value) } func Clearenv() { syscall.Clearenv() } func Environ() []string { return syscall.Environ() } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/dir_plan9.go0000644061062106075000000001314613172163421023604 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Plan 9 directory marshalling. See intro(5). package plan9 import "errors" var ( ErrShortStat = errors.New("stat buffer too short") ErrBadStat = errors.New("malformed stat buffer") ErrBadName = errors.New("bad character in file name") ) // A Qid represents a 9P server's unique identification for a file. type Qid struct { Path uint64 // the file server's unique identification for the file Vers uint32 // version number for given Path Type uint8 // the type of the file (plan9.QTDIR for example) } // A Dir contains the metadata for a file. type Dir struct { // system-modified data Type uint16 // server type Dev uint32 // server subtype // file data Qid Qid // unique id from server Mode uint32 // permissions Atime uint32 // last read time Mtime uint32 // last write time Length int64 // file length Name string // last element of path Uid string // owner name Gid string // group name Muid string // last modifier name } var nullDir = Dir{ Type: ^uint16(0), Dev: ^uint32(0), Qid: Qid{ Path: ^uint64(0), Vers: ^uint32(0), Type: ^uint8(0), }, Mode: ^uint32(0), Atime: ^uint32(0), Mtime: ^uint32(0), Length: ^int64(0), } // Null assigns special "don't touch" values to members of d to // avoid modifying them during plan9.Wstat. func (d *Dir) Null() { *d = nullDir } // Marshal encodes a 9P stat message corresponding to d into b // // If there isn't enough space in b for a stat message, ErrShortStat is returned. func (d *Dir) Marshal(b []byte) (n int, err error) { n = STATFIXLEN + len(d.Name) + len(d.Uid) + len(d.Gid) + len(d.Muid) if n > len(b) { return n, ErrShortStat } for _, c := range d.Name { if c == '/' { return n, ErrBadName } } b = pbit16(b, uint16(n)-2) b = pbit16(b, d.Type) b = pbit32(b, d.Dev) b = pbit8(b, d.Qid.Type) b = pbit32(b, d.Qid.Vers) b = pbit64(b, d.Qid.Path) b = pbit32(b, d.Mode) b = pbit32(b, d.Atime) b = pbit32(b, d.Mtime) b = pbit64(b, uint64(d.Length)) b = pstring(b, d.Name) b = pstring(b, d.Uid) b = pstring(b, d.Gid) b = pstring(b, d.Muid) return n, nil } // UnmarshalDir decodes a single 9P stat message from b and returns the resulting Dir. // // If b is too small to hold a valid stat message, ErrShortStat is returned. // // If the stat message itself is invalid, ErrBadStat is returned. func UnmarshalDir(b []byte) (*Dir, error) { if len(b) < STATFIXLEN { return nil, ErrShortStat } size, buf := gbit16(b) if len(b) != int(size)+2 { return nil, ErrBadStat } b = buf var d Dir d.Type, b = gbit16(b) d.Dev, b = gbit32(b) d.Qid.Type, b = gbit8(b) d.Qid.Vers, b = gbit32(b) d.Qid.Path, b = gbit64(b) d.Mode, b = gbit32(b) d.Atime, b = gbit32(b) d.Mtime, b = gbit32(b) n, b := gbit64(b) d.Length = int64(n) var ok bool if d.Name, b, ok = gstring(b); !ok { return nil, ErrBadStat } if d.Uid, b, ok = gstring(b); !ok { return nil, ErrBadStat } if d.Gid, b, ok = gstring(b); !ok { return nil, ErrBadStat } if d.Muid, b, ok = gstring(b); !ok { return nil, ErrBadStat } return &d, nil } // pbit8 copies the 8-bit number v to b and returns the remaining slice of b. func pbit8(b []byte, v uint8) []byte { b[0] = byte(v) return b[1:] } // pbit16 copies the 16-bit number v to b in little-endian order and returns the remaining slice of b. func pbit16(b []byte, v uint16) []byte { b[0] = byte(v) b[1] = byte(v >> 8) return b[2:] } // pbit32 copies the 32-bit number v to b in little-endian order and returns the remaining slice of b. func pbit32(b []byte, v uint32) []byte { b[0] = byte(v) b[1] = byte(v >> 8) b[2] = byte(v >> 16) b[3] = byte(v >> 24) return b[4:] } // pbit64 copies the 64-bit number v to b in little-endian order and returns the remaining slice of b. func pbit64(b []byte, v uint64) []byte { b[0] = byte(v) b[1] = byte(v >> 8) b[2] = byte(v >> 16) b[3] = byte(v >> 24) b[4] = byte(v >> 32) b[5] = byte(v >> 40) b[6] = byte(v >> 48) b[7] = byte(v >> 56) return b[8:] } // pstring copies the string s to b, prepending it with a 16-bit length in little-endian order, and // returning the remaining slice of b.. func pstring(b []byte, s string) []byte { b = pbit16(b, uint16(len(s))) n := copy(b, s) return b[n:] } // gbit8 reads an 8-bit number from b and returns it with the remaining slice of b. func gbit8(b []byte) (uint8, []byte) { return uint8(b[0]), b[1:] } // gbit16 reads a 16-bit number in little-endian order from b and returns it with the remaining slice of b. func gbit16(b []byte) (uint16, []byte) { return uint16(b[0]) | uint16(b[1])<<8, b[2:] } // gbit32 reads a 32-bit number in little-endian order from b and returns it with the remaining slice of b. func gbit32(b []byte) (uint32, []byte) { return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24, b[4:] } // gbit64 reads a 64-bit number in little-endian order from b and returns it with the remaining slice of b. func gbit64(b []byte) (uint64, []byte) { lo := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 hi := uint32(b[4]) | uint32(b[5])<<8 | uint32(b[6])<<16 | uint32(b[7])<<24 return uint64(lo) | uint64(hi)<<32, b[8:] } // gstring reads a string from b, prefixed with a 16-bit length in little-endian order. // It returns the string with the remaining slice of b and a boolean. If the length is // greater than the number of bytes in b, the boolean will be false. func gstring(b []byte) (string, []byte, bool) { n, b := gbit16(b) if int(n) > len(b) { return "", b, false } return string(b[:n]), b[n:], true } lxd-2.0.11/dist/src/golang.org/x/sys/plan9/const_plan9.go0000644061062106075000000000175413172163421024156 0ustar stgraberdomain adminspackage plan9 // Plan 9 Constants // Open modes const ( O_RDONLY = 0 O_WRONLY = 1 O_RDWR = 2 O_TRUNC = 16 O_CLOEXEC = 32 O_EXCL = 0x1000 ) // Rfork flags const ( RFNAMEG = 1 << 0 RFENVG = 1 << 1 RFFDG = 1 << 2 RFNOTEG = 1 << 3 RFPROC = 1 << 4 RFMEM = 1 << 5 RFNOWAIT = 1 << 6 RFCNAMEG = 1 << 10 RFCENVG = 1 << 11 RFCFDG = 1 << 12 RFREND = 1 << 13 RFNOMNT = 1 << 14 ) // Qid.Type bits const ( QTDIR = 0x80 QTAPPEND = 0x40 QTEXCL = 0x20 QTMOUNT = 0x10 QTAUTH = 0x08 QTTMP = 0x04 QTFILE = 0x00 ) // Dir.Mode bits const ( DMDIR = 0x80000000 DMAPPEND = 0x40000000 DMEXCL = 0x20000000 DMMOUNT = 0x10000000 DMAUTH = 0x08000000 DMTMP = 0x04000000 DMREAD = 0x4 DMWRITE = 0x2 DMEXEC = 0x1 ) const ( STATMAX = 65535 ERRMAX = 128 STATFIXLEN = 49 ) // Mount and bind flags const ( MREPL = 0x0000 MBEFORE = 0x0001 MAFTER = 0x0002 MORDER = 0x0003 MCREATE = 0x0004 MCACHE = 0x0010 MMASK = 0x0017 ) lxd-2.0.11/dist/src/golang.org/x/sys/plan9/asm_plan9_amd64.s0000644061062106075000000000130013172163421024423 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "textflag.h" // // System call support for amd64, Plan 9 // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-64 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-88 JMP syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) TEXT ·seek(SB),NOSPLIT,$0-56 JMP syscall·seek(SB) TEXT ·exit(SB),NOSPLIT,$8-8 JMP syscall·exit(SB) lxd-2.0.11/dist/src/golang.org/x/sys/plan9/asm_plan9_386.s0000644061062106075000000000127613172163421024044 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "textflag.h" // // System call support for 386, Plan 9 // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-32 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-44 JMP syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) TEXT ·seek(SB),NOSPLIT,$0-36 JMP syscall·seek(SB) TEXT ·exit(SB),NOSPLIT,$4-4 JMP syscall·exit(SB) lxd-2.0.11/dist/src/golang.org/x/sys/plan9/asm.s0000644061062106075000000000032713172163421022335 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "textflag.h" TEXT ·use(SB),NOSPLIT,$0 RET lxd-2.0.11/dist/src/golang.org/x/sys/codereview.cfg0000644061062106075000000000002513172163421023156 0ustar stgraberdomain adminsissuerepo: golang/go lxd-2.0.11/dist/src/golang.org/x/sys/README.md0000644061062106075000000000116413172163421021625 0ustar stgraberdomain admins# sys This repository holds supplemental Go packages for low-level interactions with the operating system. ## Download/Install The easiest way to install is to run `go get -u golang.org/x/sys`. You can also manually git clone the repository to `$GOPATH/src/golang.org/x/sys`. ## Report Issues / Send Patches This repository uses Gerrit for code changes. To learn how to submit changes to this repository, see https://golang.org/doc/contribute.html. The main issue tracker for the sys repository is located at https://github.com/golang/go/issues. Prefix your issue with "x/sys:" in the subject line, so it is easy to find. lxd-2.0.11/dist/src/golang.org/x/sys/PATENTS0000644061062106075000000000242713172163421021412 0ustar stgraberdomain adminsAdditional IP Rights Grant (Patents) "This implementation" means the copyrightable works distributed by Google as part of the Go project. Google hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer and otherwise run, modify and propagate the contents of this implementation of Go, where such license applies only to those patent claims, both currently owned or controlled by Google and acquired in the future, licensable by Google that are necessarily infringed by this implementation of Go. This grant does not include claims that would be infringed only as a consequence of further modification of this implementation. If you or your agent or exclusive licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that this implementation of Go or any code incorporated within this implementation of Go constitutes direct or contributory patent infringement, or inducement of patent infringement, then any patent rights granted to you under this License for this implementation of Go shall terminate as of the date such litigation is filed. lxd-2.0.11/dist/src/golang.org/x/sys/LICENSE0000644061062106075000000000270713172163421021357 0ustar stgraberdomain adminsCopyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. lxd-2.0.11/dist/src/golang.org/x/sys/CONTRIBUTORS0000644061062106075000000000025213172163421022223 0ustar stgraberdomain admins# This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at http://tip.golang.org/CONTRIBUTORS. lxd-2.0.11/dist/src/golang.org/x/sys/CONTRIBUTING.md0000644061062106075000000000200713172163421022574 0ustar stgraberdomain admins# Contributing to Go Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! ## Filing issues When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: 1. What version of Go are you using (`go version`)? 2. What operating system and processor architecture are you using? 3. What did you do? 4. What did you expect to see? 5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. ## Contributing code Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. **We do not accept GitHub pull requests** (we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file. lxd-2.0.11/dist/src/golang.org/x/sys/AUTHORS0000644061062106075000000000025513172163421021416 0ustar stgraberdomain admins# This source code refers to The Go Authors for copyright purposes. # The master list of authors is in the main Go distribution, # visible at http://tip.golang.org/AUTHORS. lxd-2.0.11/dist/src/golang.org/x/net/0000755061062106075000000000000013172163402020313 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/xsrftoken/0000755061062106075000000000000013172163402022336 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/xsrftoken/xsrf_test.go0000644061062106075000000000515513172163402024714 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xsrftoken import ( "encoding/base64" "testing" "time" ) const ( key = "quay" userID = "12345678" actionID = "POST /form" ) var ( now = time.Now() oneMinuteFromNow = now.Add(1 * time.Minute) ) func TestValidToken(t *testing.T) { tok := generateTokenAtTime(key, userID, actionID, now) if !validTokenAtTime(tok, key, userID, actionID, oneMinuteFromNow) { t.Error("One second later: Expected token to be valid") } if !validTokenAtTime(tok, key, userID, actionID, now.Add(Timeout-1*time.Nanosecond)) { t.Error("Just before timeout: Expected token to be valid") } if !validTokenAtTime(tok, key, userID, actionID, now.Add(-1*time.Minute+1*time.Millisecond)) { t.Error("One minute in the past: Expected token to be valid") } } // TestSeparatorReplacement tests that separators are being correctly substituted func TestSeparatorReplacement(t *testing.T) { tok := generateTokenAtTime("foo:bar", "baz", "wah", now) tok2 := generateTokenAtTime("foo", "bar:baz", "wah", now) if tok == tok2 { t.Errorf("Expected generated tokens to be different") } } func TestInvalidToken(t *testing.T) { invalidTokenTests := []struct { name, key, userID, actionID string t time.Time }{ {"Bad key", "foobar", userID, actionID, oneMinuteFromNow}, {"Bad userID", key, "foobar", actionID, oneMinuteFromNow}, {"Bad actionID", key, userID, "foobar", oneMinuteFromNow}, {"Expired", key, userID, actionID, now.Add(Timeout + 1*time.Millisecond)}, {"More than 1 minute from the future", key, userID, actionID, now.Add(-1*time.Nanosecond - 1*time.Minute)}, } tok := generateTokenAtTime(key, userID, actionID, now) for _, itt := range invalidTokenTests { if validTokenAtTime(tok, itt.key, itt.userID, itt.actionID, itt.t) { t.Errorf("%v: Expected token to be invalid", itt.name) } } } // TestValidateBadData primarily tests that no unexpected panics are triggered // during parsing func TestValidateBadData(t *testing.T) { badDataTests := []struct { name, tok string }{ {"Invalid Base64", "ASDab24(@)$*=="}, {"No delimiter", base64.URLEncoding.EncodeToString([]byte("foobar12345678"))}, {"Invalid time", base64.URLEncoding.EncodeToString([]byte("foobar:foobar"))}, {"Wrong length", "1234" + generateTokenAtTime(key, userID, actionID, now)}, } for _, bdt := range badDataTests { if validTokenAtTime(bdt.tok, key, userID, actionID, oneMinuteFromNow) { t.Errorf("%v: Expected token to be invalid", bdt.name) } } } lxd-2.0.11/dist/src/golang.org/x/net/xsrftoken/xsrf.go0000644061062106075000000000602513172163402023652 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package xsrftoken provides methods for generating and validating secure XSRF tokens. package xsrftoken // import "golang.org/x/net/xsrftoken" import ( "crypto/hmac" "crypto/sha1" "crypto/subtle" "encoding/base64" "fmt" "strconv" "strings" "time" ) // Timeout is the duration for which XSRF tokens are valid. // It is exported so clients may set cookie timeouts that match generated tokens. const Timeout = 24 * time.Hour // clean sanitizes a string for inclusion in a token by replacing all ":"s. func clean(s string) string { return strings.Replace(s, ":", "_", -1) } // Generate returns a URL-safe secure XSRF token that expires in 24 hours. // // key is a secret key for your application; it must be non-empty. // userID is an optional unique identifier for the user. // actionID is an optional action the user is taking (e.g. POSTing to a particular path). func Generate(key, userID, actionID string) string { return generateTokenAtTime(key, userID, actionID, time.Now()) } // generateTokenAtTime is like Generate, but returns a token that expires 24 hours from now. func generateTokenAtTime(key, userID, actionID string, now time.Time) string { if len(key) == 0 { panic("zero length xsrf secret key") } // Round time up and convert to milliseconds. milliTime := (now.UnixNano() + 1e6 - 1) / 1e6 h := hmac.New(sha1.New, []byte(key)) fmt.Fprintf(h, "%s:%s:%d", clean(userID), clean(actionID), milliTime) // Get the padded base64 string then removing the padding. tok := string(h.Sum(nil)) tok = base64.URLEncoding.EncodeToString([]byte(tok)) tok = strings.TrimRight(tok, "=") return fmt.Sprintf("%s:%d", tok, milliTime) } // Valid reports whether a token is a valid, unexpired token returned by Generate. func Valid(token, key, userID, actionID string) bool { return validTokenAtTime(token, key, userID, actionID, time.Now()) } // validTokenAtTime reports whether a token is valid at the given time. func validTokenAtTime(token, key, userID, actionID string, now time.Time) bool { if len(key) == 0 { panic("zero length xsrf secret key") } // Extract the issue time of the token. sep := strings.LastIndex(token, ":") if sep < 0 { return false } millis, err := strconv.ParseInt(token[sep+1:], 10, 64) if err != nil { return false } issueTime := time.Unix(0, millis*1e6) // Check that the token is not expired. if now.Sub(issueTime) >= Timeout { return false } // Check that the token is not from the future. // Allow 1 minute grace period in case the token is being verified on a // machine whose clock is behind the machine that issued the token. if issueTime.After(now.Add(1 * time.Minute)) { return false } expected := generateTokenAtTime(key, userID, actionID, issueTime) // Check that the token matches the expected value. // Use constant time comparison to avoid timing attacks. return subtle.ConstantTimeCompare([]byte(token), []byte(expected)) == 1 } lxd-2.0.11/dist/src/golang.org/x/net/websocket/0000755061062106075000000000000013172163402022301 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/websocket/websocket_test.go0000644061062106075000000003461513172163402025666 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "crypto/rand" "fmt" "io" "log" "net" "net/http" "net/http/httptest" "net/url" "reflect" "runtime" "strings" "sync" "testing" "time" ) var serverAddr string var once sync.Once func echoServer(ws *Conn) { defer ws.Close() io.Copy(ws, ws) } type Count struct { S string N int } func countServer(ws *Conn) { defer ws.Close() for { var count Count err := JSON.Receive(ws, &count) if err != nil { return } count.N++ count.S = strings.Repeat(count.S, count.N) err = JSON.Send(ws, count) if err != nil { return } } } type testCtrlAndDataHandler struct { hybiFrameHandler } func (h *testCtrlAndDataHandler) WritePing(b []byte) (int, error) { h.hybiFrameHandler.conn.wio.Lock() defer h.hybiFrameHandler.conn.wio.Unlock() w, err := h.hybiFrameHandler.conn.frameWriterFactory.NewFrameWriter(PingFrame) if err != nil { return 0, err } n, err := w.Write(b) w.Close() return n, err } func ctrlAndDataServer(ws *Conn) { defer ws.Close() h := &testCtrlAndDataHandler{hybiFrameHandler: hybiFrameHandler{conn: ws}} ws.frameHandler = h go func() { for i := 0; ; i++ { var b []byte if i%2 != 0 { // with or without payload b = []byte(fmt.Sprintf("#%d-CONTROL-FRAME-FROM-SERVER", i)) } if _, err := h.WritePing(b); err != nil { break } if _, err := h.WritePong(b); err != nil { // unsolicited pong break } time.Sleep(10 * time.Millisecond) } }() b := make([]byte, 128) for { n, err := ws.Read(b) if err != nil { break } if _, err := ws.Write(b[:n]); err != nil { break } } } func subProtocolHandshake(config *Config, req *http.Request) error { for _, proto := range config.Protocol { if proto == "chat" { config.Protocol = []string{proto} return nil } } return ErrBadWebSocketProtocol } func subProtoServer(ws *Conn) { for _, proto := range ws.Config().Protocol { io.WriteString(ws, proto) } } func startServer() { http.Handle("/echo", Handler(echoServer)) http.Handle("/count", Handler(countServer)) http.Handle("/ctrldata", Handler(ctrlAndDataServer)) subproto := Server{ Handshake: subProtocolHandshake, Handler: Handler(subProtoServer), } http.Handle("/subproto", subproto) server := httptest.NewServer(nil) serverAddr = server.Listener.Addr().String() log.Print("Test WebSocket server listening on ", serverAddr) } func newConfig(t *testing.T, path string) *Config { config, _ := NewConfig(fmt.Sprintf("ws://%s%s", serverAddr, path), "http://localhost") return config } func TestEcho(t *testing.T) { once.Do(startServer) // websocket.Dial() client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } conn, err := NewClient(newConfig(t, "/echo"), client) if err != nil { t.Errorf("WebSocket handshake error: %v", err) return } msg := []byte("hello, world\n") if _, err := conn.Write(msg); err != nil { t.Errorf("Write: %v", err) } var actual_msg = make([]byte, 512) n, err := conn.Read(actual_msg) if err != nil { t.Errorf("Read: %v", err) } actual_msg = actual_msg[0:n] if !bytes.Equal(msg, actual_msg) { t.Errorf("Echo: expected %q got %q", msg, actual_msg) } conn.Close() } func TestAddr(t *testing.T) { once.Do(startServer) // websocket.Dial() client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } conn, err := NewClient(newConfig(t, "/echo"), client) if err != nil { t.Errorf("WebSocket handshake error: %v", err) return } ra := conn.RemoteAddr().String() if !strings.HasPrefix(ra, "ws://") || !strings.HasSuffix(ra, "/echo") { t.Errorf("Bad remote addr: %v", ra) } la := conn.LocalAddr().String() if !strings.HasPrefix(la, "http://") { t.Errorf("Bad local addr: %v", la) } conn.Close() } func TestCount(t *testing.T) { once.Do(startServer) // websocket.Dial() client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } conn, err := NewClient(newConfig(t, "/count"), client) if err != nil { t.Errorf("WebSocket handshake error: %v", err) return } var count Count count.S = "hello" if err := JSON.Send(conn, count); err != nil { t.Errorf("Write: %v", err) } if err := JSON.Receive(conn, &count); err != nil { t.Errorf("Read: %v", err) } if count.N != 1 { t.Errorf("count: expected %d got %d", 1, count.N) } if count.S != "hello" { t.Errorf("count: expected %q got %q", "hello", count.S) } if err := JSON.Send(conn, count); err != nil { t.Errorf("Write: %v", err) } if err := JSON.Receive(conn, &count); err != nil { t.Errorf("Read: %v", err) } if count.N != 2 { t.Errorf("count: expected %d got %d", 2, count.N) } if count.S != "hellohello" { t.Errorf("count: expected %q got %q", "hellohello", count.S) } conn.Close() } func TestWithQuery(t *testing.T) { once.Do(startServer) client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } config := newConfig(t, "/echo") config.Location, err = url.ParseRequestURI(fmt.Sprintf("ws://%s/echo?q=v", serverAddr)) if err != nil { t.Fatal("location url", err) } ws, err := NewClient(config, client) if err != nil { t.Errorf("WebSocket handshake: %v", err) return } ws.Close() } func testWithProtocol(t *testing.T, subproto []string) (string, error) { once.Do(startServer) client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } config := newConfig(t, "/subproto") config.Protocol = subproto ws, err := NewClient(config, client) if err != nil { return "", err } msg := make([]byte, 16) n, err := ws.Read(msg) if err != nil { return "", err } ws.Close() return string(msg[:n]), nil } func TestWithProtocol(t *testing.T) { proto, err := testWithProtocol(t, []string{"chat"}) if err != nil { t.Errorf("SubProto: unexpected error: %v", err) } if proto != "chat" { t.Errorf("SubProto: expected %q, got %q", "chat", proto) } } func TestWithTwoProtocol(t *testing.T) { proto, err := testWithProtocol(t, []string{"test", "chat"}) if err != nil { t.Errorf("SubProto: unexpected error: %v", err) } if proto != "chat" { t.Errorf("SubProto: expected %q, got %q", "chat", proto) } } func TestWithBadProtocol(t *testing.T) { _, err := testWithProtocol(t, []string{"test"}) if err != ErrBadStatus { t.Errorf("SubProto: expected %v, got %v", ErrBadStatus, err) } } func TestHTTP(t *testing.T) { once.Do(startServer) // If the client did not send a handshake that matches the protocol // specification, the server MUST return an HTTP response with an // appropriate error code (such as 400 Bad Request) resp, err := http.Get(fmt.Sprintf("http://%s/echo", serverAddr)) if err != nil { t.Errorf("Get: error %#v", err) return } if resp == nil { t.Error("Get: resp is null") return } if resp.StatusCode != http.StatusBadRequest { t.Errorf("Get: expected %q got %q", http.StatusBadRequest, resp.StatusCode) } } func TestTrailingSpaces(t *testing.T) { // http://code.google.com/p/go/issues/detail?id=955 // The last runs of this create keys with trailing spaces that should not be // generated by the client. once.Do(startServer) config := newConfig(t, "/echo") for i := 0; i < 30; i++ { // body ws, err := DialConfig(config) if err != nil { t.Errorf("Dial #%d failed: %v", i, err) break } ws.Close() } } func TestDialConfigBadVersion(t *testing.T) { once.Do(startServer) config := newConfig(t, "/echo") config.Version = 1234 _, err := DialConfig(config) if dialerr, ok := err.(*DialError); ok { if dialerr.Err != ErrBadProtocolVersion { t.Errorf("dial expected err %q but got %q", ErrBadProtocolVersion, dialerr.Err) } } } func TestDialConfigWithDialer(t *testing.T) { once.Do(startServer) config := newConfig(t, "/echo") config.Dialer = &net.Dialer{ Deadline: time.Now().Add(-time.Minute), } _, err := DialConfig(config) dialerr, ok := err.(*DialError) if !ok { t.Fatalf("DialError expected, got %#v", err) } neterr, ok := dialerr.Err.(*net.OpError) if !ok { t.Fatalf("net.OpError error expected, got %#v", dialerr.Err) } if !neterr.Timeout() { t.Fatalf("expected timeout error, got %#v", neterr) } } func TestSmallBuffer(t *testing.T) { // http://code.google.com/p/go/issues/detail?id=1145 // Read should be able to handle reading a fragment of a frame. once.Do(startServer) // websocket.Dial() client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } conn, err := NewClient(newConfig(t, "/echo"), client) if err != nil { t.Errorf("WebSocket handshake error: %v", err) return } msg := []byte("hello, world\n") if _, err := conn.Write(msg); err != nil { t.Errorf("Write: %v", err) } var small_msg = make([]byte, 8) n, err := conn.Read(small_msg) if err != nil { t.Errorf("Read: %v", err) } if !bytes.Equal(msg[:len(small_msg)], small_msg) { t.Errorf("Echo: expected %q got %q", msg[:len(small_msg)], small_msg) } var second_msg = make([]byte, len(msg)) n, err = conn.Read(second_msg) if err != nil { t.Errorf("Read: %v", err) } second_msg = second_msg[0:n] if !bytes.Equal(msg[len(small_msg):], second_msg) { t.Errorf("Echo: expected %q got %q", msg[len(small_msg):], second_msg) } conn.Close() } var parseAuthorityTests = []struct { in *url.URL out string }{ { &url.URL{ Scheme: "ws", Host: "www.google.com", }, "www.google.com:80", }, { &url.URL{ Scheme: "wss", Host: "www.google.com", }, "www.google.com:443", }, { &url.URL{ Scheme: "ws", Host: "www.google.com:80", }, "www.google.com:80", }, { &url.URL{ Scheme: "wss", Host: "www.google.com:443", }, "www.google.com:443", }, // some invalid ones for parseAuthority. parseAuthority doesn't // concern itself with the scheme unless it actually knows about it { &url.URL{ Scheme: "http", Host: "www.google.com", }, "www.google.com", }, { &url.URL{ Scheme: "http", Host: "www.google.com:80", }, "www.google.com:80", }, { &url.URL{ Scheme: "asdf", Host: "127.0.0.1", }, "127.0.0.1", }, { &url.URL{ Scheme: "asdf", Host: "www.google.com", }, "www.google.com", }, } func TestParseAuthority(t *testing.T) { for _, tt := range parseAuthorityTests { out := parseAuthority(tt.in) if out != tt.out { t.Errorf("got %v; want %v", out, tt.out) } } } type closerConn struct { net.Conn closed int // count of the number of times Close was called } func (c *closerConn) Close() error { c.closed++ return c.Conn.Close() } func TestClose(t *testing.T) { if runtime.GOOS == "plan9" { t.Skip("see golang.org/issue/11454") } once.Do(startServer) conn, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } cc := closerConn{Conn: conn} client, err := NewClient(newConfig(t, "/echo"), &cc) if err != nil { t.Fatalf("WebSocket handshake: %v", err) } // set the deadline to ten minutes ago, which will have expired by the time // client.Close sends the close status frame. conn.SetDeadline(time.Now().Add(-10 * time.Minute)) if err := client.Close(); err == nil { t.Errorf("ws.Close(): expected error, got %v", err) } if cc.closed < 1 { t.Fatalf("ws.Close(): expected underlying ws.rwc.Close to be called > 0 times, got: %v", cc.closed) } } var originTests = []struct { req *http.Request origin *url.URL }{ { req: &http.Request{ Header: http.Header{ "Origin": []string{"http://www.example.com"}, }, }, origin: &url.URL{ Scheme: "http", Host: "www.example.com", }, }, { req: &http.Request{}, }, } func TestOrigin(t *testing.T) { conf := newConfig(t, "/echo") conf.Version = ProtocolVersionHybi13 for i, tt := range originTests { origin, err := Origin(conf, tt.req) if err != nil { t.Error(err) continue } if !reflect.DeepEqual(origin, tt.origin) { t.Errorf("#%d: got origin %v; want %v", i, origin, tt.origin) continue } } } func TestCtrlAndData(t *testing.T) { once.Do(startServer) c, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal(err) } ws, err := NewClient(newConfig(t, "/ctrldata"), c) if err != nil { t.Fatal(err) } defer ws.Close() h := &testCtrlAndDataHandler{hybiFrameHandler: hybiFrameHandler{conn: ws}} ws.frameHandler = h b := make([]byte, 128) for i := 0; i < 2; i++ { data := []byte(fmt.Sprintf("#%d-DATA-FRAME-FROM-CLIENT", i)) if _, err := ws.Write(data); err != nil { t.Fatalf("#%d: %v", i, err) } var ctrl []byte if i%2 != 0 { // with or without payload ctrl = []byte(fmt.Sprintf("#%d-CONTROL-FRAME-FROM-CLIENT", i)) } if _, err := h.WritePing(ctrl); err != nil { t.Fatalf("#%d: %v", i, err) } n, err := ws.Read(b) if err != nil { t.Fatalf("#%d: %v", i, err) } if !bytes.Equal(b[:n], data) { t.Fatalf("#%d: got %v; want %v", i, b[:n], data) } } } func TestCodec_ReceiveLimited(t *testing.T) { const limit = 2048 var payloads [][]byte for _, size := range []int{ 1024, 2048, 4096, // receive of this message would be interrupted due to limit 2048, // this one is to make sure next receive recovers discarding leftovers } { b := make([]byte, size) rand.Read(b) payloads = append(payloads, b) } handlerDone := make(chan struct{}) limitedHandler := func(ws *Conn) { defer close(handlerDone) ws.MaxPayloadBytes = limit defer ws.Close() for i, p := range payloads { t.Logf("payload #%d (size %d, exceeds limit: %v)", i, len(p), len(p) > limit) var recv []byte err := Message.Receive(ws, &recv) switch err { case nil: case ErrFrameTooLarge: if len(p) <= limit { t.Fatalf("unexpected frame size limit: expected %d bytes of payload having limit at %d", len(p), limit) } continue default: t.Fatalf("unexpected error: %v (want either nil or ErrFrameTooLarge)", err) } if len(recv) > limit { t.Fatalf("received %d bytes of payload having limit at %d", len(recv), limit) } if !bytes.Equal(p, recv) { t.Fatalf("received payload differs:\ngot:\t%v\nwant:\t%v", recv, p) } } } server := httptest.NewServer(Handler(limitedHandler)) defer server.CloseClientConnections() defer server.Close() addr := server.Listener.Addr().String() ws, err := Dial("ws://"+addr+"/", "", "http://localhost/") if err != nil { t.Fatal(err) } defer ws.Close() for i, p := range payloads { if err := Message.Send(ws, p); err != nil { t.Fatalf("payload #%d (size %d): %v", i, len(p), err) } } <-handlerDone } lxd-2.0.11/dist/src/golang.org/x/net/websocket/websocket.go0000644061062106075000000002756113172163402024631 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package websocket implements a client and server for the WebSocket protocol // as specified in RFC 6455. // // This package currently lacks some features found in an alternative // and more actively maintained WebSocket package: // // https://godoc.org/github.com/gorilla/websocket // package websocket // import "golang.org/x/net/websocket" import ( "bufio" "crypto/tls" "encoding/json" "errors" "io" "io/ioutil" "net" "net/http" "net/url" "sync" "time" ) const ( ProtocolVersionHybi13 = 13 ProtocolVersionHybi = ProtocolVersionHybi13 SupportedProtocolVersion = "13" ContinuationFrame = 0 TextFrame = 1 BinaryFrame = 2 CloseFrame = 8 PingFrame = 9 PongFrame = 10 UnknownFrame = 255 DefaultMaxPayloadBytes = 32 << 20 // 32MB ) // ProtocolError represents WebSocket protocol errors. type ProtocolError struct { ErrorString string } func (err *ProtocolError) Error() string { return err.ErrorString } var ( ErrBadProtocolVersion = &ProtocolError{"bad protocol version"} ErrBadScheme = &ProtocolError{"bad scheme"} ErrBadStatus = &ProtocolError{"bad status"} ErrBadUpgrade = &ProtocolError{"missing or bad upgrade"} ErrBadWebSocketOrigin = &ProtocolError{"missing or bad WebSocket-Origin"} ErrBadWebSocketLocation = &ProtocolError{"missing or bad WebSocket-Location"} ErrBadWebSocketProtocol = &ProtocolError{"missing or bad WebSocket-Protocol"} ErrBadWebSocketVersion = &ProtocolError{"missing or bad WebSocket Version"} ErrChallengeResponse = &ProtocolError{"mismatch challenge/response"} ErrBadFrame = &ProtocolError{"bad frame"} ErrBadFrameBoundary = &ProtocolError{"not on frame boundary"} ErrNotWebSocket = &ProtocolError{"not websocket protocol"} ErrBadRequestMethod = &ProtocolError{"bad method"} ErrNotSupported = &ProtocolError{"not supported"} ) // ErrFrameTooLarge is returned by Codec's Receive method if payload size // exceeds limit set by Conn.MaxPayloadBytes var ErrFrameTooLarge = errors.New("websocket: frame payload size exceeds limit") // Addr is an implementation of net.Addr for WebSocket. type Addr struct { *url.URL } // Network returns the network type for a WebSocket, "websocket". func (addr *Addr) Network() string { return "websocket" } // Config is a WebSocket configuration type Config struct { // A WebSocket server address. Location *url.URL // A Websocket client origin. Origin *url.URL // WebSocket subprotocols. Protocol []string // WebSocket protocol version. Version int // TLS config for secure WebSocket (wss). TlsConfig *tls.Config // Additional header fields to be sent in WebSocket opening handshake. Header http.Header // Dialer used when opening websocket connections. Dialer *net.Dialer handshakeData map[string]string } // serverHandshaker is an interface to handle WebSocket server side handshake. type serverHandshaker interface { // ReadHandshake reads handshake request message from client. // Returns http response code and error if any. ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) // AcceptHandshake accepts the client handshake request and sends // handshake response back to client. AcceptHandshake(buf *bufio.Writer) (err error) // NewServerConn creates a new WebSocket connection. NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn) } // frameReader is an interface to read a WebSocket frame. type frameReader interface { // Reader is to read payload of the frame. io.Reader // PayloadType returns payload type. PayloadType() byte // HeaderReader returns a reader to read header of the frame. HeaderReader() io.Reader // TrailerReader returns a reader to read trailer of the frame. // If it returns nil, there is no trailer in the frame. TrailerReader() io.Reader // Len returns total length of the frame, including header and trailer. Len() int } // frameReaderFactory is an interface to creates new frame reader. type frameReaderFactory interface { NewFrameReader() (r frameReader, err error) } // frameWriter is an interface to write a WebSocket frame. type frameWriter interface { // Writer is to write payload of the frame. io.WriteCloser } // frameWriterFactory is an interface to create new frame writer. type frameWriterFactory interface { NewFrameWriter(payloadType byte) (w frameWriter, err error) } type frameHandler interface { HandleFrame(frame frameReader) (r frameReader, err error) WriteClose(status int) (err error) } // Conn represents a WebSocket connection. // // Multiple goroutines may invoke methods on a Conn simultaneously. type Conn struct { config *Config request *http.Request buf *bufio.ReadWriter rwc io.ReadWriteCloser rio sync.Mutex frameReaderFactory frameReader wio sync.Mutex frameWriterFactory frameHandler PayloadType byte defaultCloseStatus int // MaxPayloadBytes limits the size of frame payload received over Conn // by Codec's Receive method. If zero, DefaultMaxPayloadBytes is used. MaxPayloadBytes int } // Read implements the io.Reader interface: // it reads data of a frame from the WebSocket connection. // if msg is not large enough for the frame data, it fills the msg and next Read // will read the rest of the frame data. // it reads Text frame or Binary frame. func (ws *Conn) Read(msg []byte) (n int, err error) { ws.rio.Lock() defer ws.rio.Unlock() again: if ws.frameReader == nil { frame, err := ws.frameReaderFactory.NewFrameReader() if err != nil { return 0, err } ws.frameReader, err = ws.frameHandler.HandleFrame(frame) if err != nil { return 0, err } if ws.frameReader == nil { goto again } } n, err = ws.frameReader.Read(msg) if err == io.EOF { if trailer := ws.frameReader.TrailerReader(); trailer != nil { io.Copy(ioutil.Discard, trailer) } ws.frameReader = nil goto again } return n, err } // Write implements the io.Writer interface: // it writes data as a frame to the WebSocket connection. func (ws *Conn) Write(msg []byte) (n int, err error) { ws.wio.Lock() defer ws.wio.Unlock() w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType) if err != nil { return 0, err } n, err = w.Write(msg) w.Close() return n, err } // Close implements the io.Closer interface. func (ws *Conn) Close() error { err := ws.frameHandler.WriteClose(ws.defaultCloseStatus) err1 := ws.rwc.Close() if err != nil { return err } return err1 } func (ws *Conn) IsClientConn() bool { return ws.request == nil } func (ws *Conn) IsServerConn() bool { return ws.request != nil } // LocalAddr returns the WebSocket Origin for the connection for client, or // the WebSocket location for server. func (ws *Conn) LocalAddr() net.Addr { if ws.IsClientConn() { return &Addr{ws.config.Origin} } return &Addr{ws.config.Location} } // RemoteAddr returns the WebSocket location for the connection for client, or // the Websocket Origin for server. func (ws *Conn) RemoteAddr() net.Addr { if ws.IsClientConn() { return &Addr{ws.config.Location} } return &Addr{ws.config.Origin} } var errSetDeadline = errors.New("websocket: cannot set deadline: not using a net.Conn") // SetDeadline sets the connection's network read & write deadlines. func (ws *Conn) SetDeadline(t time.Time) error { if conn, ok := ws.rwc.(net.Conn); ok { return conn.SetDeadline(t) } return errSetDeadline } // SetReadDeadline sets the connection's network read deadline. func (ws *Conn) SetReadDeadline(t time.Time) error { if conn, ok := ws.rwc.(net.Conn); ok { return conn.SetReadDeadline(t) } return errSetDeadline } // SetWriteDeadline sets the connection's network write deadline. func (ws *Conn) SetWriteDeadline(t time.Time) error { if conn, ok := ws.rwc.(net.Conn); ok { return conn.SetWriteDeadline(t) } return errSetDeadline } // Config returns the WebSocket config. func (ws *Conn) Config() *Config { return ws.config } // Request returns the http request upgraded to the WebSocket. // It is nil for client side. func (ws *Conn) Request() *http.Request { return ws.request } // Codec represents a symmetric pair of functions that implement a codec. type Codec struct { Marshal func(v interface{}) (data []byte, payloadType byte, err error) Unmarshal func(data []byte, payloadType byte, v interface{}) (err error) } // Send sends v marshaled by cd.Marshal as single frame to ws. func (cd Codec) Send(ws *Conn, v interface{}) (err error) { data, payloadType, err := cd.Marshal(v) if err != nil { return err } ws.wio.Lock() defer ws.wio.Unlock() w, err := ws.frameWriterFactory.NewFrameWriter(payloadType) if err != nil { return err } _, err = w.Write(data) w.Close() return err } // Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores // in v. The whole frame payload is read to an in-memory buffer; max size of // payload is defined by ws.MaxPayloadBytes. If frame payload size exceeds // limit, ErrFrameTooLarge is returned; in this case frame is not read off wire // completely. The next call to Receive would read and discard leftover data of // previous oversized frame before processing next frame. func (cd Codec) Receive(ws *Conn, v interface{}) (err error) { ws.rio.Lock() defer ws.rio.Unlock() if ws.frameReader != nil { _, err = io.Copy(ioutil.Discard, ws.frameReader) if err != nil { return err } ws.frameReader = nil } again: frame, err := ws.frameReaderFactory.NewFrameReader() if err != nil { return err } frame, err = ws.frameHandler.HandleFrame(frame) if err != nil { return err } if frame == nil { goto again } maxPayloadBytes := ws.MaxPayloadBytes if maxPayloadBytes == 0 { maxPayloadBytes = DefaultMaxPayloadBytes } if hf, ok := frame.(*hybiFrameReader); ok && hf.header.Length > int64(maxPayloadBytes) { // payload size exceeds limit, no need to call Unmarshal // // set frameReader to current oversized frame so that // the next call to this function can drain leftover // data before processing the next frame ws.frameReader = frame return ErrFrameTooLarge } payloadType := frame.PayloadType() data, err := ioutil.ReadAll(frame) if err != nil { return err } return cd.Unmarshal(data, payloadType, v) } func marshal(v interface{}) (msg []byte, payloadType byte, err error) { switch data := v.(type) { case string: return []byte(data), TextFrame, nil case []byte: return data, BinaryFrame, nil } return nil, UnknownFrame, ErrNotSupported } func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) { switch data := v.(type) { case *string: *data = string(msg) return nil case *[]byte: *data = msg return nil } return ErrNotSupported } /* Message is a codec to send/receive text/binary data in a frame on WebSocket connection. To send/receive text frame, use string type. To send/receive binary frame, use []byte type. Trivial usage: import "websocket" // receive text frame var message string websocket.Message.Receive(ws, &message) // send text frame message = "hello" websocket.Message.Send(ws, message) // receive binary frame var data []byte websocket.Message.Receive(ws, &data) // send binary frame data = []byte{0, 1, 2} websocket.Message.Send(ws, data) */ var Message = Codec{marshal, unmarshal} func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) { msg, err = json.Marshal(v) return msg, TextFrame, err } func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) { return json.Unmarshal(msg, v) } /* JSON is a codec to send/receive JSON data in a frame from a WebSocket connection. Trivial usage: import "websocket" type T struct { Msg string Count int } // receive JSON type T var data T websocket.JSON.Receive(ws, &data) // send JSON type T websocket.JSON.Send(ws, data) */ var JSON = Codec{jsonMarshal, jsonUnmarshal} lxd-2.0.11/dist/src/golang.org/x/net/websocket/server.go0000644061062106075000000000660213172163402024142 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "fmt" "io" "net/http" ) func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) { var hs serverHandshaker = &hybiServerHandshaker{Config: config} code, err := hs.ReadHandshake(buf.Reader, req) if err == ErrBadWebSocketVersion { fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion) buf.WriteString("\r\n") buf.WriteString(err.Error()) buf.Flush() return } if err != nil { fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) buf.WriteString("\r\n") buf.WriteString(err.Error()) buf.Flush() return } if handshake != nil { err = handshake(config, req) if err != nil { code = http.StatusForbidden fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) buf.WriteString("\r\n") buf.Flush() return } } err = hs.AcceptHandshake(buf.Writer) if err != nil { code = http.StatusBadRequest fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) buf.WriteString("\r\n") buf.Flush() return } conn = hs.NewServerConn(buf, rwc, req) return } // Server represents a server of a WebSocket. type Server struct { // Config is a WebSocket configuration for new WebSocket connection. Config // Handshake is an optional function in WebSocket handshake. // For example, you can check, or don't check Origin header. // Another example, you can select config.Protocol. Handshake func(*Config, *http.Request) error // Handler handles a WebSocket connection. Handler } // ServeHTTP implements the http.Handler interface for a WebSocket func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { s.serveWebSocket(w, req) } func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) { rwc, buf, err := w.(http.Hijacker).Hijack() if err != nil { panic("Hijack failed: " + err.Error()) } // The server should abort the WebSocket connection if it finds // the client did not send a handshake that matches with protocol // specification. defer rwc.Close() conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake) if err != nil { return } if conn == nil { panic("unexpected nil conn") } s.Handler(conn) } // Handler is a simple interface to a WebSocket browser client. // It checks if Origin header is valid URL by default. // You might want to verify websocket.Conn.Config().Origin in the func. // If you use Server instead of Handler, you could call websocket.Origin and // check the origin in your Handshake func. So, if you want to accept // non-browser clients, which do not send an Origin header, set a // Server.Handshake that does not check the origin. type Handler func(*Conn) func checkOrigin(config *Config, req *http.Request) (err error) { config.Origin, err = Origin(config, req) if err == nil && config.Origin == nil { return fmt.Errorf("null origin") } return err } // ServeHTTP implements the http.Handler interface for a WebSocket func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { s := Server{Handler: h, Handshake: checkOrigin} s.serveWebSocket(w, req) } lxd-2.0.11/dist/src/golang.org/x/net/websocket/hybi_test.go0000644061062106075000000004430413172163402024627 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "bytes" "fmt" "io" "net/http" "net/url" "strings" "testing" ) // Test the getNonceAccept function with values in // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 func TestSecWebSocketAccept(t *testing.T) { nonce := []byte("dGhlIHNhbXBsZSBub25jZQ==") expected := []byte("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") accept, err := getNonceAccept(nonce) if err != nil { t.Errorf("getNonceAccept: returned error %v", err) return } if !bytes.Equal(expected, accept) { t.Errorf("getNonceAccept: expected %q got %q", expected, accept) } } func TestHybiClientHandshake(t *testing.T) { type test struct { url, host string } tests := []test{ {"ws://server.example.com/chat", "server.example.com"}, {"ws://127.0.0.1/chat", "127.0.0.1"}, } if _, err := url.ParseRequestURI("http://[fe80::1%25lo0]"); err == nil { tests = append(tests, test{"ws://[fe80::1%25lo0]/chat", "[fe80::1]"}) } for _, tt := range tests { var b bytes.Buffer bw := bufio.NewWriter(&b) br := bufio.NewReader(strings.NewReader(`HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat `)) var err error var config Config config.Location, err = url.ParseRequestURI(tt.url) if err != nil { t.Fatal("location url", err) } config.Origin, err = url.ParseRequestURI("http://example.com") if err != nil { t.Fatal("origin url", err) } config.Protocol = append(config.Protocol, "chat") config.Protocol = append(config.Protocol, "superchat") config.Version = ProtocolVersionHybi13 config.handshakeData = map[string]string{ "key": "dGhlIHNhbXBsZSBub25jZQ==", } if err := hybiClientHandshake(&config, br, bw); err != nil { t.Fatal("handshake", err) } req, err := http.ReadRequest(bufio.NewReader(&b)) if err != nil { t.Fatal("read request", err) } if req.Method != "GET" { t.Errorf("request method expected GET, but got %s", req.Method) } if req.URL.Path != "/chat" { t.Errorf("request path expected /chat, but got %s", req.URL.Path) } if req.Proto != "HTTP/1.1" { t.Errorf("request proto expected HTTP/1.1, but got %s", req.Proto) } if req.Host != tt.host { t.Errorf("request host expected %s, but got %s", tt.host, req.Host) } var expectedHeader = map[string]string{ "Connection": "Upgrade", "Upgrade": "websocket", "Sec-Websocket-Key": config.handshakeData["key"], "Origin": config.Origin.String(), "Sec-Websocket-Protocol": "chat, superchat", "Sec-Websocket-Version": fmt.Sprintf("%d", ProtocolVersionHybi13), } for k, v := range expectedHeader { if req.Header.Get(k) != v { t.Errorf("%s expected %s, but got %v", k, v, req.Header.Get(k)) } } } } func TestHybiClientHandshakeWithHeader(t *testing.T) { b := bytes.NewBuffer([]byte{}) bw := bufio.NewWriter(b) br := bufio.NewReader(strings.NewReader(`HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat `)) var err error config := new(Config) config.Location, err = url.ParseRequestURI("ws://server.example.com/chat") if err != nil { t.Fatal("location url", err) } config.Origin, err = url.ParseRequestURI("http://example.com") if err != nil { t.Fatal("origin url", err) } config.Protocol = append(config.Protocol, "chat") config.Protocol = append(config.Protocol, "superchat") config.Version = ProtocolVersionHybi13 config.Header = http.Header(make(map[string][]string)) config.Header.Add("User-Agent", "test") config.handshakeData = map[string]string{ "key": "dGhlIHNhbXBsZSBub25jZQ==", } err = hybiClientHandshake(config, br, bw) if err != nil { t.Errorf("handshake failed: %v", err) } req, err := http.ReadRequest(bufio.NewReader(b)) if err != nil { t.Fatalf("read request: %v", err) } if req.Method != "GET" { t.Errorf("request method expected GET, but got %q", req.Method) } if req.URL.Path != "/chat" { t.Errorf("request path expected /chat, but got %q", req.URL.Path) } if req.Proto != "HTTP/1.1" { t.Errorf("request proto expected HTTP/1.1, but got %q", req.Proto) } if req.Host != "server.example.com" { t.Errorf("request Host expected server.example.com, but got %v", req.Host) } var expectedHeader = map[string]string{ "Connection": "Upgrade", "Upgrade": "websocket", "Sec-Websocket-Key": config.handshakeData["key"], "Origin": config.Origin.String(), "Sec-Websocket-Protocol": "chat, superchat", "Sec-Websocket-Version": fmt.Sprintf("%d", ProtocolVersionHybi13), "User-Agent": "test", } for k, v := range expectedHeader { if req.Header.Get(k) != v { t.Errorf(fmt.Sprintf("%s expected %q but got %q", k, v, req.Header.Get(k))) } } } func TestHybiServerHandshake(t *testing.T) { config := new(Config) handshaker := &hybiServerHandshaker{Config: config} br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 `)) req, err := http.ReadRequest(br) if err != nil { t.Fatal("request", err) } code, err := handshaker.ReadHandshake(br, req) if err != nil { t.Errorf("handshake failed: %v", err) } if code != http.StatusSwitchingProtocols { t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) } expectedProtocols := []string{"chat", "superchat"} if fmt.Sprintf("%v", config.Protocol) != fmt.Sprintf("%v", expectedProtocols) { t.Errorf("protocol expected %q but got %q", expectedProtocols, config.Protocol) } b := bytes.NewBuffer([]byte{}) bw := bufio.NewWriter(b) config.Protocol = config.Protocol[:1] err = handshaker.AcceptHandshake(bw) if err != nil { t.Errorf("handshake response failed: %v", err) } expectedResponse := strings.Join([]string{ "HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", "Sec-WebSocket-Protocol: chat", "", ""}, "\r\n") if b.String() != expectedResponse { t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) } } func TestHybiServerHandshakeNoSubProtocol(t *testing.T) { config := new(Config) handshaker := &hybiServerHandshaker{Config: config} br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Version: 13 `)) req, err := http.ReadRequest(br) if err != nil { t.Fatal("request", err) } code, err := handshaker.ReadHandshake(br, req) if err != nil { t.Errorf("handshake failed: %v", err) } if code != http.StatusSwitchingProtocols { t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) } if len(config.Protocol) != 0 { t.Errorf("len(config.Protocol) expected 0, but got %q", len(config.Protocol)) } b := bytes.NewBuffer([]byte{}) bw := bufio.NewWriter(b) err = handshaker.AcceptHandshake(bw) if err != nil { t.Errorf("handshake response failed: %v", err) } expectedResponse := strings.Join([]string{ "HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", "", ""}, "\r\n") if b.String() != expectedResponse { t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) } } func TestHybiServerHandshakeHybiBadVersion(t *testing.T) { config := new(Config) handshaker := &hybiServerHandshaker{Config: config} br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 9 `)) req, err := http.ReadRequest(br) if err != nil { t.Fatal("request", err) } code, err := handshaker.ReadHandshake(br, req) if err != ErrBadWebSocketVersion { t.Errorf("handshake expected err %q but got %q", ErrBadWebSocketVersion, err) } if code != http.StatusBadRequest { t.Errorf("status expected %q but got %q", http.StatusBadRequest, code) } } func testHybiFrame(t *testing.T, testHeader, testPayload, testMaskedPayload []byte, frameHeader *hybiFrameHeader) { b := bytes.NewBuffer([]byte{}) frameWriterFactory := &hybiFrameWriterFactory{bufio.NewWriter(b), false} w, _ := frameWriterFactory.NewFrameWriter(TextFrame) w.(*hybiFrameWriter).header = frameHeader _, err := w.Write(testPayload) w.Close() if err != nil { t.Errorf("Write error %q", err) } var expectedFrame []byte expectedFrame = append(expectedFrame, testHeader...) expectedFrame = append(expectedFrame, testMaskedPayload...) if !bytes.Equal(expectedFrame, b.Bytes()) { t.Errorf("frame expected %q got %q", expectedFrame, b.Bytes()) } frameReaderFactory := &hybiFrameReaderFactory{bufio.NewReader(b)} r, err := frameReaderFactory.NewFrameReader() if err != nil { t.Errorf("Read error %q", err) } if header := r.HeaderReader(); header == nil { t.Errorf("no header") } else { actualHeader := make([]byte, r.Len()) n, err := header.Read(actualHeader) if err != nil { t.Errorf("Read header error %q", err) } else { if n < len(testHeader) { t.Errorf("header too short %q got %q", testHeader, actualHeader[:n]) } if !bytes.Equal(testHeader, actualHeader[:n]) { t.Errorf("header expected %q got %q", testHeader, actualHeader[:n]) } } } if trailer := r.TrailerReader(); trailer != nil { t.Errorf("unexpected trailer %q", trailer) } frame := r.(*hybiFrameReader) if frameHeader.Fin != frame.header.Fin || frameHeader.OpCode != frame.header.OpCode || len(testPayload) != int(frame.header.Length) { t.Errorf("mismatch %v (%d) vs %v", frameHeader, len(testPayload), frame) } payload := make([]byte, len(testPayload)) _, err = r.Read(payload) if err != nil && err != io.EOF { t.Errorf("read %v", err) } if !bytes.Equal(testPayload, payload) { t.Errorf("payload %q vs %q", testPayload, payload) } } func TestHybiShortTextFrame(t *testing.T) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame} payload := []byte("hello") testHybiFrame(t, []byte{0x81, 0x05}, payload, payload, frameHeader) payload = make([]byte, 125) testHybiFrame(t, []byte{0x81, 125}, payload, payload, frameHeader) } func TestHybiShortMaskedTextFrame(t *testing.T) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame, MaskingKey: []byte{0xcc, 0x55, 0x80, 0x20}} payload := []byte("hello") maskedPayload := []byte{0xa4, 0x30, 0xec, 0x4c, 0xa3} header := []byte{0x81, 0x85} header = append(header, frameHeader.MaskingKey...) testHybiFrame(t, header, payload, maskedPayload, frameHeader) } func TestHybiShortBinaryFrame(t *testing.T) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: BinaryFrame} payload := []byte("hello") testHybiFrame(t, []byte{0x82, 0x05}, payload, payload, frameHeader) payload = make([]byte, 125) testHybiFrame(t, []byte{0x82, 125}, payload, payload, frameHeader) } func TestHybiControlFrame(t *testing.T) { payload := []byte("hello") frameHeader := &hybiFrameHeader{Fin: true, OpCode: PingFrame} testHybiFrame(t, []byte{0x89, 0x05}, payload, payload, frameHeader) frameHeader = &hybiFrameHeader{Fin: true, OpCode: PingFrame} testHybiFrame(t, []byte{0x89, 0x00}, nil, nil, frameHeader) frameHeader = &hybiFrameHeader{Fin: true, OpCode: PongFrame} testHybiFrame(t, []byte{0x8A, 0x05}, payload, payload, frameHeader) frameHeader = &hybiFrameHeader{Fin: true, OpCode: PongFrame} testHybiFrame(t, []byte{0x8A, 0x00}, nil, nil, frameHeader) frameHeader = &hybiFrameHeader{Fin: true, OpCode: CloseFrame} payload = []byte{0x03, 0xe8} // 1000 testHybiFrame(t, []byte{0x88, 0x02}, payload, payload, frameHeader) } func TestHybiLongFrame(t *testing.T) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame} payload := make([]byte, 126) testHybiFrame(t, []byte{0x81, 126, 0x00, 126}, payload, payload, frameHeader) payload = make([]byte, 65535) testHybiFrame(t, []byte{0x81, 126, 0xff, 0xff}, payload, payload, frameHeader) payload = make([]byte, 65536) testHybiFrame(t, []byte{0x81, 127, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00}, payload, payload, frameHeader) } func TestHybiClientRead(t *testing.T) { wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o', 0x89, 0x05, 'h', 'e', 'l', 'l', 'o', // ping 0x81, 0x05, 'w', 'o', 'r', 'l', 'd'} br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) msg := make([]byte, 512) n, err := conn.Read(msg) if err != nil { t.Errorf("read 1st frame, error %q", err) } if n != 5 { t.Errorf("read 1st frame, expect 5, got %d", n) } if !bytes.Equal(wireData[2:7], msg[:n]) { t.Errorf("read 1st frame %v, got %v", wireData[2:7], msg[:n]) } n, err = conn.Read(msg) if err != nil { t.Errorf("read 2nd frame, error %q", err) } if n != 5 { t.Errorf("read 2nd frame, expect 5, got %d", n) } if !bytes.Equal(wireData[16:21], msg[:n]) { t.Errorf("read 2nd frame %v, got %v", wireData[16:21], msg[:n]) } n, err = conn.Read(msg) if err == nil { t.Errorf("read not EOF") } if n != 0 { t.Errorf("expect read 0, got %d", n) } } func TestHybiShortRead(t *testing.T) { wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o', 0x89, 0x05, 'h', 'e', 'l', 'l', 'o', // ping 0x81, 0x05, 'w', 'o', 'r', 'l', 'd'} br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) step := 0 pos := 0 expectedPos := []int{2, 5, 16, 19} expectedLen := []int{3, 2, 3, 2} for { msg := make([]byte, 3) n, err := conn.Read(msg) if step >= len(expectedPos) { if err == nil { t.Errorf("read not EOF") } if n != 0 { t.Errorf("expect read 0, got %d", n) } return } pos = expectedPos[step] endPos := pos + expectedLen[step] if err != nil { t.Errorf("read from %d, got error %q", pos, err) return } if n != endPos-pos { t.Errorf("read from %d, expect %d, got %d", pos, endPos-pos, n) } if !bytes.Equal(wireData[pos:endPos], msg[:n]) { t.Errorf("read from %d, frame %v, got %v", pos, wireData[pos:endPos], msg[:n]) } step++ } } func TestHybiServerRead(t *testing.T) { wireData := []byte{0x81, 0x85, 0xcc, 0x55, 0x80, 0x20, 0xa4, 0x30, 0xec, 0x4c, 0xa3, // hello 0x89, 0x85, 0xcc, 0x55, 0x80, 0x20, 0xa4, 0x30, 0xec, 0x4c, 0xa3, // ping: hello 0x81, 0x85, 0xed, 0x83, 0xb4, 0x24, 0x9a, 0xec, 0xc6, 0x48, 0x89, // world } br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, new(http.Request)) expected := [][]byte{[]byte("hello"), []byte("world")} msg := make([]byte, 512) n, err := conn.Read(msg) if err != nil { t.Errorf("read 1st frame, error %q", err) } if n != 5 { t.Errorf("read 1st frame, expect 5, got %d", n) } if !bytes.Equal(expected[0], msg[:n]) { t.Errorf("read 1st frame %q, got %q", expected[0], msg[:n]) } n, err = conn.Read(msg) if err != nil { t.Errorf("read 2nd frame, error %q", err) } if n != 5 { t.Errorf("read 2nd frame, expect 5, got %d", n) } if !bytes.Equal(expected[1], msg[:n]) { t.Errorf("read 2nd frame %q, got %q", expected[1], msg[:n]) } n, err = conn.Read(msg) if err == nil { t.Errorf("read not EOF") } if n != 0 { t.Errorf("expect read 0, got %d", n) } } func TestHybiServerReadWithoutMasking(t *testing.T) { wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o'} br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, new(http.Request)) // server MUST close the connection upon receiving a non-masked frame. msg := make([]byte, 512) _, err := conn.Read(msg) if err != io.EOF { t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err) } } func TestHybiClientReadWithMasking(t *testing.T) { wireData := []byte{0x81, 0x85, 0xcc, 0x55, 0x80, 0x20, 0xa4, 0x30, 0xec, 0x4c, 0xa3, // hello } br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) // client MUST close the connection upon receiving a masked frame. msg := make([]byte, 512) _, err := conn.Read(msg) if err != io.EOF { t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err) } } // Test the hybiServerHandshaker supports firefox implementation and // checks Connection request header include (but it's not necessary // equal to) "upgrade" func TestHybiServerFirefoxHandshake(t *testing.T) { config := new(Config) handshaker := &hybiServerHandshaker{Config: config} br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: keep-alive, upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 `)) req, err := http.ReadRequest(br) if err != nil { t.Fatal("request", err) } code, err := handshaker.ReadHandshake(br, req) if err != nil { t.Errorf("handshake failed: %v", err) } if code != http.StatusSwitchingProtocols { t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) } b := bytes.NewBuffer([]byte{}) bw := bufio.NewWriter(b) config.Protocol = []string{"chat"} err = handshaker.AcceptHandshake(bw) if err != nil { t.Errorf("handshake response failed: %v", err) } expectedResponse := strings.Join([]string{ "HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", "Sec-WebSocket-Protocol: chat", "", ""}, "\r\n") if b.String() != expectedResponse { t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) } } lxd-2.0.11/dist/src/golang.org/x/net/websocket/hybi.go0000644061062106075000000003714013172163402023570 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket // This file implements a protocol of hybi draft. // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 import ( "bufio" "bytes" "crypto/rand" "crypto/sha1" "encoding/base64" "encoding/binary" "fmt" "io" "io/ioutil" "net/http" "net/url" "strings" ) const ( websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" closeStatusNormal = 1000 closeStatusGoingAway = 1001 closeStatusProtocolError = 1002 closeStatusUnsupportedData = 1003 closeStatusFrameTooLarge = 1004 closeStatusNoStatusRcvd = 1005 closeStatusAbnormalClosure = 1006 closeStatusBadMessageData = 1007 closeStatusPolicyViolation = 1008 closeStatusTooBigData = 1009 closeStatusExtensionMismatch = 1010 maxControlFramePayloadLength = 125 ) var ( ErrBadMaskingKey = &ProtocolError{"bad masking key"} ErrBadPongMessage = &ProtocolError{"bad pong message"} ErrBadClosingStatus = &ProtocolError{"bad closing status"} ErrUnsupportedExtensions = &ProtocolError{"unsupported extensions"} ErrNotImplemented = &ProtocolError{"not implemented"} handshakeHeader = map[string]bool{ "Host": true, "Upgrade": true, "Connection": true, "Sec-Websocket-Key": true, "Sec-Websocket-Origin": true, "Sec-Websocket-Version": true, "Sec-Websocket-Protocol": true, "Sec-Websocket-Accept": true, } ) // A hybiFrameHeader is a frame header as defined in hybi draft. type hybiFrameHeader struct { Fin bool Rsv [3]bool OpCode byte Length int64 MaskingKey []byte data *bytes.Buffer } // A hybiFrameReader is a reader for hybi frame. type hybiFrameReader struct { reader io.Reader header hybiFrameHeader pos int64 length int } func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) { n, err = frame.reader.Read(msg) if frame.header.MaskingKey != nil { for i := 0; i < n; i++ { msg[i] = msg[i] ^ frame.header.MaskingKey[frame.pos%4] frame.pos++ } } return n, err } func (frame *hybiFrameReader) PayloadType() byte { return frame.header.OpCode } func (frame *hybiFrameReader) HeaderReader() io.Reader { if frame.header.data == nil { return nil } if frame.header.data.Len() == 0 { return nil } return frame.header.data } func (frame *hybiFrameReader) TrailerReader() io.Reader { return nil } func (frame *hybiFrameReader) Len() (n int) { return frame.length } // A hybiFrameReaderFactory creates new frame reader based on its frame type. type hybiFrameReaderFactory struct { *bufio.Reader } // NewFrameReader reads a frame header from the connection, and creates new reader for the frame. // See Section 5.2 Base Framing protocol for detail. // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5.2 func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err error) { hybiFrame := new(hybiFrameReader) frame = hybiFrame var header []byte var b byte // First byte. FIN/RSV1/RSV2/RSV3/OpCode(4bits) b, err = buf.ReadByte() if err != nil { return } header = append(header, b) hybiFrame.header.Fin = ((header[0] >> 7) & 1) != 0 for i := 0; i < 3; i++ { j := uint(6 - i) hybiFrame.header.Rsv[i] = ((header[0] >> j) & 1) != 0 } hybiFrame.header.OpCode = header[0] & 0x0f // Second byte. Mask/Payload len(7bits) b, err = buf.ReadByte() if err != nil { return } header = append(header, b) mask := (b & 0x80) != 0 b &= 0x7f lengthFields := 0 switch { case b <= 125: // Payload length 7bits. hybiFrame.header.Length = int64(b) case b == 126: // Payload length 7+16bits lengthFields = 2 case b == 127: // Payload length 7+64bits lengthFields = 8 } for i := 0; i < lengthFields; i++ { b, err = buf.ReadByte() if err != nil { return } if lengthFields == 8 && i == 0 { // MSB must be zero when 7+64 bits b &= 0x7f } header = append(header, b) hybiFrame.header.Length = hybiFrame.header.Length*256 + int64(b) } if mask { // Masking key. 4 bytes. for i := 0; i < 4; i++ { b, err = buf.ReadByte() if err != nil { return } header = append(header, b) hybiFrame.header.MaskingKey = append(hybiFrame.header.MaskingKey, b) } } hybiFrame.reader = io.LimitReader(buf.Reader, hybiFrame.header.Length) hybiFrame.header.data = bytes.NewBuffer(header) hybiFrame.length = len(header) + int(hybiFrame.header.Length) return } // A HybiFrameWriter is a writer for hybi frame. type hybiFrameWriter struct { writer *bufio.Writer header *hybiFrameHeader } func (frame *hybiFrameWriter) Write(msg []byte) (n int, err error) { var header []byte var b byte if frame.header.Fin { b |= 0x80 } for i := 0; i < 3; i++ { if frame.header.Rsv[i] { j := uint(6 - i) b |= 1 << j } } b |= frame.header.OpCode header = append(header, b) if frame.header.MaskingKey != nil { b = 0x80 } else { b = 0 } lengthFields := 0 length := len(msg) switch { case length <= 125: b |= byte(length) case length < 65536: b |= 126 lengthFields = 2 default: b |= 127 lengthFields = 8 } header = append(header, b) for i := 0; i < lengthFields; i++ { j := uint((lengthFields - i - 1) * 8) b = byte((length >> j) & 0xff) header = append(header, b) } if frame.header.MaskingKey != nil { if len(frame.header.MaskingKey) != 4 { return 0, ErrBadMaskingKey } header = append(header, frame.header.MaskingKey...) frame.writer.Write(header) data := make([]byte, length) for i := range data { data[i] = msg[i] ^ frame.header.MaskingKey[i%4] } frame.writer.Write(data) err = frame.writer.Flush() return length, err } frame.writer.Write(header) frame.writer.Write(msg) err = frame.writer.Flush() return length, err } func (frame *hybiFrameWriter) Close() error { return nil } type hybiFrameWriterFactory struct { *bufio.Writer needMaskingKey bool } func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: payloadType} if buf.needMaskingKey { frameHeader.MaskingKey, err = generateMaskingKey() if err != nil { return nil, err } } return &hybiFrameWriter{writer: buf.Writer, header: frameHeader}, nil } type hybiFrameHandler struct { conn *Conn payloadType byte } func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (frameReader, error) { if handler.conn.IsServerConn() { // The client MUST mask all frames sent to the server. if frame.(*hybiFrameReader).header.MaskingKey == nil { handler.WriteClose(closeStatusProtocolError) return nil, io.EOF } } else { // The server MUST NOT mask all frames. if frame.(*hybiFrameReader).header.MaskingKey != nil { handler.WriteClose(closeStatusProtocolError) return nil, io.EOF } } if header := frame.HeaderReader(); header != nil { io.Copy(ioutil.Discard, header) } switch frame.PayloadType() { case ContinuationFrame: frame.(*hybiFrameReader).header.OpCode = handler.payloadType case TextFrame, BinaryFrame: handler.payloadType = frame.PayloadType() case CloseFrame: return nil, io.EOF case PingFrame, PongFrame: b := make([]byte, maxControlFramePayloadLength) n, err := io.ReadFull(frame, b) if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { return nil, err } io.Copy(ioutil.Discard, frame) if frame.PayloadType() == PingFrame { if _, err := handler.WritePong(b[:n]); err != nil { return nil, err } } return nil, nil } return frame, nil } func (handler *hybiFrameHandler) WriteClose(status int) (err error) { handler.conn.wio.Lock() defer handler.conn.wio.Unlock() w, err := handler.conn.frameWriterFactory.NewFrameWriter(CloseFrame) if err != nil { return err } msg := make([]byte, 2) binary.BigEndian.PutUint16(msg, uint16(status)) _, err = w.Write(msg) w.Close() return err } func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err error) { handler.conn.wio.Lock() defer handler.conn.wio.Unlock() w, err := handler.conn.frameWriterFactory.NewFrameWriter(PongFrame) if err != nil { return 0, err } n, err = w.Write(msg) w.Close() return n, err } // newHybiConn creates a new WebSocket connection speaking hybi draft protocol. func newHybiConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { if buf == nil { br := bufio.NewReader(rwc) bw := bufio.NewWriter(rwc) buf = bufio.NewReadWriter(br, bw) } ws := &Conn{config: config, request: request, buf: buf, rwc: rwc, frameReaderFactory: hybiFrameReaderFactory{buf.Reader}, frameWriterFactory: hybiFrameWriterFactory{ buf.Writer, request == nil}, PayloadType: TextFrame, defaultCloseStatus: closeStatusNormal} ws.frameHandler = &hybiFrameHandler{conn: ws} return ws } // generateMaskingKey generates a masking key for a frame. func generateMaskingKey() (maskingKey []byte, err error) { maskingKey = make([]byte, 4) if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil { return } return } // generateNonce generates a nonce consisting of a randomly selected 16-byte // value that has been base64-encoded. func generateNonce() (nonce []byte) { key := make([]byte, 16) if _, err := io.ReadFull(rand.Reader, key); err != nil { panic(err) } nonce = make([]byte, 24) base64.StdEncoding.Encode(nonce, key) return } // removeZone removes IPv6 zone identifer from host. // E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080" func removeZone(host string) string { if !strings.HasPrefix(host, "[") { return host } i := strings.LastIndex(host, "]") if i < 0 { return host } j := strings.LastIndex(host[:i], "%") if j < 0 { return host } return host[:j] + host[i:] } // getNonceAccept computes the base64-encoded SHA-1 of the concatenation of // the nonce ("Sec-WebSocket-Key" value) with the websocket GUID string. func getNonceAccept(nonce []byte) (expected []byte, err error) { h := sha1.New() if _, err = h.Write(nonce); err != nil { return } if _, err = h.Write([]byte(websocketGUID)); err != nil { return } expected = make([]byte, 28) base64.StdEncoding.Encode(expected, h.Sum(nil)) return } // Client handshake described in draft-ietf-hybi-thewebsocket-protocol-17 func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) { bw.WriteString("GET " + config.Location.RequestURI() + " HTTP/1.1\r\n") // According to RFC 6874, an HTTP client, proxy, or other // intermediary must remove any IPv6 zone identifier attached // to an outgoing URI. bw.WriteString("Host: " + removeZone(config.Location.Host) + "\r\n") bw.WriteString("Upgrade: websocket\r\n") bw.WriteString("Connection: Upgrade\r\n") nonce := generateNonce() if config.handshakeData != nil { nonce = []byte(config.handshakeData["key"]) } bw.WriteString("Sec-WebSocket-Key: " + string(nonce) + "\r\n") bw.WriteString("Origin: " + strings.ToLower(config.Origin.String()) + "\r\n") if config.Version != ProtocolVersionHybi13 { return ErrBadProtocolVersion } bw.WriteString("Sec-WebSocket-Version: " + fmt.Sprintf("%d", config.Version) + "\r\n") if len(config.Protocol) > 0 { bw.WriteString("Sec-WebSocket-Protocol: " + strings.Join(config.Protocol, ", ") + "\r\n") } // TODO(ukai): send Sec-WebSocket-Extensions. err = config.Header.WriteSubset(bw, handshakeHeader) if err != nil { return err } bw.WriteString("\r\n") if err = bw.Flush(); err != nil { return err } resp, err := http.ReadResponse(br, &http.Request{Method: "GET"}) if err != nil { return err } if resp.StatusCode != 101 { return ErrBadStatus } if strings.ToLower(resp.Header.Get("Upgrade")) != "websocket" || strings.ToLower(resp.Header.Get("Connection")) != "upgrade" { return ErrBadUpgrade } expectedAccept, err := getNonceAccept(nonce) if err != nil { return err } if resp.Header.Get("Sec-WebSocket-Accept") != string(expectedAccept) { return ErrChallengeResponse } if resp.Header.Get("Sec-WebSocket-Extensions") != "" { return ErrUnsupportedExtensions } offeredProtocol := resp.Header.Get("Sec-WebSocket-Protocol") if offeredProtocol != "" { protocolMatched := false for i := 0; i < len(config.Protocol); i++ { if config.Protocol[i] == offeredProtocol { protocolMatched = true break } } if !protocolMatched { return ErrBadWebSocketProtocol } config.Protocol = []string{offeredProtocol} } return nil } // newHybiClientConn creates a client WebSocket connection after handshake. func newHybiClientConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser) *Conn { return newHybiConn(config, buf, rwc, nil) } // A HybiServerHandshaker performs a server handshake using hybi draft protocol. type hybiServerHandshaker struct { *Config accept []byte } func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) { c.Version = ProtocolVersionHybi13 if req.Method != "GET" { return http.StatusMethodNotAllowed, ErrBadRequestMethod } // HTTP version can be safely ignored. if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" || !strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") { return http.StatusBadRequest, ErrNotWebSocket } key := req.Header.Get("Sec-Websocket-Key") if key == "" { return http.StatusBadRequest, ErrChallengeResponse } version := req.Header.Get("Sec-Websocket-Version") switch version { case "13": c.Version = ProtocolVersionHybi13 default: return http.StatusBadRequest, ErrBadWebSocketVersion } var scheme string if req.TLS != nil { scheme = "wss" } else { scheme = "ws" } c.Location, err = url.ParseRequestURI(scheme + "://" + req.Host + req.URL.RequestURI()) if err != nil { return http.StatusBadRequest, err } protocol := strings.TrimSpace(req.Header.Get("Sec-Websocket-Protocol")) if protocol != "" { protocols := strings.Split(protocol, ",") for i := 0; i < len(protocols); i++ { c.Protocol = append(c.Protocol, strings.TrimSpace(protocols[i])) } } c.accept, err = getNonceAccept([]byte(key)) if err != nil { return http.StatusInternalServerError, err } return http.StatusSwitchingProtocols, nil } // Origin parses the Origin header in req. // If the Origin header is not set, it returns nil and nil. func Origin(config *Config, req *http.Request) (*url.URL, error) { var origin string switch config.Version { case ProtocolVersionHybi13: origin = req.Header.Get("Origin") } if origin == "" { return nil, nil } return url.ParseRequestURI(origin) } func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) { if len(c.Protocol) > 0 { if len(c.Protocol) != 1 { // You need choose a Protocol in Handshake func in Server. return ErrBadWebSocketProtocol } } buf.WriteString("HTTP/1.1 101 Switching Protocols\r\n") buf.WriteString("Upgrade: websocket\r\n") buf.WriteString("Connection: Upgrade\r\n") buf.WriteString("Sec-WebSocket-Accept: " + string(c.accept) + "\r\n") if len(c.Protocol) > 0 { buf.WriteString("Sec-WebSocket-Protocol: " + c.Protocol[0] + "\r\n") } // TODO(ukai): send Sec-WebSocket-Extensions. if c.Header != nil { err := c.Header.WriteSubset(buf, handshakeHeader) if err != nil { return err } } buf.WriteString("\r\n") return buf.Flush() } func (c *hybiServerHandshaker) NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { return newHybiServerConn(c.Config, buf, rwc, request) } // newHybiServerConn returns a new WebSocket connection speaking hybi draft protocol. func newHybiServerConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { return newHybiConn(config, buf, rwc, request) } lxd-2.0.11/dist/src/golang.org/x/net/websocket/examplehandler_test.go0000644061062106075000000000110713172163402026657 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket_test import ( "io" "net/http" "golang.org/x/net/websocket" ) // Echo the data received on the WebSocket. func EchoServer(ws *websocket.Conn) { io.Copy(ws, ws) } // This example demonstrates a trivial echo server. func ExampleHandler() { http.Handle("/echo", websocket.Handler(EchoServer)) err := http.ListenAndServe(":12345", nil) if err != nil { panic("ListenAndServe: " + err.Error()) } } lxd-2.0.11/dist/src/golang.org/x/net/websocket/exampledial_test.go0000644061062106075000000000125113172163402026153 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket_test import ( "fmt" "log" "golang.org/x/net/websocket" ) // This example demonstrates a trivial client. func ExampleDial() { origin := "http://localhost/" url := "ws://localhost:12345/ws" ws, err := websocket.Dial(url, "", origin) if err != nil { log.Fatal(err) } if _, err := ws.Write([]byte("hello, world!\n")); err != nil { log.Fatal(err) } var msg = make([]byte, 512) var n int if n, err = ws.Read(msg); err != nil { log.Fatal(err) } fmt.Printf("Received: %s.\n", msg[:n]) } lxd-2.0.11/dist/src/golang.org/x/net/websocket/dial_test.go0000644061062106075000000000225313172163402024602 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "crypto/tls" "fmt" "log" "net" "net/http/httptest" "testing" "time" ) // This test depend on Go 1.3+ because in earlier versions the Dialer won't be // used in TLS connections and a timeout won't be triggered. func TestDialConfigTLSWithDialer(t *testing.T) { tlsServer := httptest.NewTLSServer(nil) tlsServerAddr := tlsServer.Listener.Addr().String() log.Print("Test TLS WebSocket server listening on ", tlsServerAddr) defer tlsServer.Close() config, _ := NewConfig(fmt.Sprintf("wss://%s/echo", tlsServerAddr), "http://localhost") config.Dialer = &net.Dialer{ Deadline: time.Now().Add(-time.Minute), } config.TlsConfig = &tls.Config{ InsecureSkipVerify: true, } _, err := DialConfig(config) dialerr, ok := err.(*DialError) if !ok { t.Fatalf("DialError expected, got %#v", err) } neterr, ok := dialerr.Err.(*net.OpError) if !ok { t.Fatalf("net.OpError error expected, got %#v", dialerr.Err) } if !neterr.Timeout() { t.Fatalf("expected timeout error, got %#v", neterr) } } lxd-2.0.11/dist/src/golang.org/x/net/websocket/dial.go0000644061062106075000000000106613172163402023544 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "crypto/tls" "net" ) func dialWithDialer(dialer *net.Dialer, config *Config) (conn net.Conn, err error) { switch config.Location.Scheme { case "ws": conn, err = dialer.Dial("tcp", parseAuthority(config.Location)) case "wss": conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig) default: err = ErrBadScheme } return } lxd-2.0.11/dist/src/golang.org/x/net/websocket/client.go0000644061062106075000000000467313172163402024120 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "io" "net" "net/http" "net/url" ) // DialError is an error that occurs while dialling a websocket server. type DialError struct { *Config Err error } func (e *DialError) Error() string { return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error() } // NewConfig creates a new WebSocket config for client connection. func NewConfig(server, origin string) (config *Config, err error) { config = new(Config) config.Version = ProtocolVersionHybi13 config.Location, err = url.ParseRequestURI(server) if err != nil { return } config.Origin, err = url.ParseRequestURI(origin) if err != nil { return } config.Header = http.Header(make(map[string][]string)) return } // NewClient creates a new WebSocket client connection over rwc. func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) { br := bufio.NewReader(rwc) bw := bufio.NewWriter(rwc) err = hybiClientHandshake(config, br, bw) if err != nil { return } buf := bufio.NewReadWriter(br, bw) ws = newHybiClientConn(config, buf, rwc) return } // Dial opens a new client connection to a WebSocket. func Dial(url_, protocol, origin string) (ws *Conn, err error) { config, err := NewConfig(url_, origin) if err != nil { return nil, err } if protocol != "" { config.Protocol = []string{protocol} } return DialConfig(config) } var portMap = map[string]string{ "ws": "80", "wss": "443", } func parseAuthority(location *url.URL) string { if _, ok := portMap[location.Scheme]; ok { if _, _, err := net.SplitHostPort(location.Host); err != nil { return net.JoinHostPort(location.Host, portMap[location.Scheme]) } } return location.Host } // DialConfig opens a new client connection to a WebSocket with a config. func DialConfig(config *Config) (ws *Conn, err error) { var client net.Conn if config.Location == nil { return nil, &DialError{config, ErrBadWebSocketLocation} } if config.Origin == nil { return nil, &DialError{config, ErrBadWebSocketOrigin} } dialer := config.Dialer if dialer == nil { dialer = &net.Dialer{} } client, err = dialWithDialer(dialer, config) if err != nil { goto Error } ws, err = NewClient(config, client) if err != nil { client.Close() goto Error } return Error: return nil, &DialError{config, err} } lxd-2.0.11/dist/src/golang.org/x/net/webdav/0000755061062106075000000000000013172163402021563 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/webdav/xml_test.go0000644061062106075000000006166313172163402023765 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "bytes" "encoding/xml" "fmt" "io" "net/http" "net/http/httptest" "reflect" "sort" "strings" "testing" ixml "golang.org/x/net/webdav/internal/xml" ) func TestReadLockInfo(t *testing.T) { // The "section x.y.z" test cases come from section x.y.z of the spec at // http://www.webdav.org/specs/rfc4918.html testCases := []struct { desc string input string wantLI lockInfo wantStatus int }{{ "bad: junk", "xxx", lockInfo{}, http.StatusBadRequest, }, { "bad: invalid owner XML", "" + "\n" + " \n" + " \n" + " \n" + " no end tag \n" + " \n" + "", lockInfo{}, http.StatusBadRequest, }, { "bad: invalid UTF-8", "" + "\n" + " \n" + " \n" + " \n" + " \xff \n" + " \n" + "", lockInfo{}, http.StatusBadRequest, }, { "bad: unfinished XML #1", "" + "\n" + " \n" + " \n", lockInfo{}, http.StatusBadRequest, }, { "bad: unfinished XML #2", "" + "\n" + " \n" + " \n" + " \n", lockInfo{}, http.StatusBadRequest, }, { "good: empty", "", lockInfo{}, 0, }, { "good: plain-text owner", "" + "\n" + " \n" + " \n" + " gopher\n" + "", lockInfo{ XMLName: ixml.Name{Space: "DAV:", Local: "lockinfo"}, Exclusive: new(struct{}), Write: new(struct{}), Owner: owner{ InnerXML: "gopher", }, }, 0, }, { "section 9.10.7", "" + "\n" + " \n" + " \n" + " \n" + " http://example.org/~ejw/contact.html\n" + " \n" + "", lockInfo{ XMLName: ixml.Name{Space: "DAV:", Local: "lockinfo"}, Exclusive: new(struct{}), Write: new(struct{}), Owner: owner{ InnerXML: "\n http://example.org/~ejw/contact.html\n ", }, }, 0, }} for _, tc := range testCases { li, status, err := readLockInfo(strings.NewReader(tc.input)) if tc.wantStatus != 0 { if err == nil { t.Errorf("%s: got nil error, want non-nil", tc.desc) continue } } else if err != nil { t.Errorf("%s: %v", tc.desc, err) continue } if !reflect.DeepEqual(li, tc.wantLI) || status != tc.wantStatus { t.Errorf("%s:\ngot lockInfo=%v, status=%v\nwant lockInfo=%v, status=%v", tc.desc, li, status, tc.wantLI, tc.wantStatus) continue } } } func TestReadPropfind(t *testing.T) { testCases := []struct { desc string input string wantPF propfind wantStatus int }{{ desc: "propfind: propname", input: "" + "\n" + " \n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Propname: new(struct{}), }, }, { desc: "propfind: empty body means allprop", input: "", wantPF: propfind{ Allprop: new(struct{}), }, }, { desc: "propfind: allprop", input: "" + "\n" + " \n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Allprop: new(struct{}), }, }, { desc: "propfind: allprop followed by include", input: "" + "\n" + " \n" + " \n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Allprop: new(struct{}), Include: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: include followed by allprop", input: "" + "\n" + " \n" + " \n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Allprop: new(struct{}), Include: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: propfind", input: "" + "\n" + " \n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: prop with ignored comments", input: "" + "\n" + " \n" + " \n" + " \n" + " \n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: propfind with ignored whitespace", input: "" + "\n" + " \n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: propfind with ignored mixed-content", input: "" + "\n" + " foobar\n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: propname with ignored element (section A.4)", input: "" + "\n" + " \n" + " *boss*\n" + "", wantPF: propfind{ XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, Propname: new(struct{}), }, }, { desc: "propfind: bad: junk", input: "xxx", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: propname and allprop (section A.3)", input: "" + "\n" + " " + " " + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: propname and prop", input: "" + "\n" + " \n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: allprop and prop", input: "" + "\n" + " \n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: empty propfind with ignored element (section A.4)", input: "" + "\n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: empty prop", input: "" + "\n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: prop with just chardata", input: "" + "\n" + " foo\n" + "", wantStatus: http.StatusBadRequest, }, { desc: "bad: interrupted prop", input: "" + "\n" + " \n", wantStatus: http.StatusBadRequest, }, { desc: "bad: malformed end element prop", input: "" + "\n" + " \n", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: property with chardata value", input: "" + "\n" + " bar\n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: property with whitespace value", input: "" + "\n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: include without allprop", input: "" + "\n" + " \n" + "", wantStatus: http.StatusBadRequest, }} for _, tc := range testCases { pf, status, err := readPropfind(strings.NewReader(tc.input)) if tc.wantStatus != 0 { if err == nil { t.Errorf("%s: got nil error, want non-nil", tc.desc) continue } } else if err != nil { t.Errorf("%s: %v", tc.desc, err) continue } if !reflect.DeepEqual(pf, tc.wantPF) || status != tc.wantStatus { t.Errorf("%s:\ngot propfind=%v, status=%v\nwant propfind=%v, status=%v", tc.desc, pf, status, tc.wantPF, tc.wantStatus) continue } } } func TestMultistatusWriter(t *testing.T) { ///The "section x.y.z" test cases come from section x.y.z of the spec at // http://www.webdav.org/specs/rfc4918.html testCases := []struct { desc string responses []response respdesc string writeHeader bool wantXML string wantCode int wantErr error }{{ desc: "section 9.2.2 (failed dependency)", responses: []response{{ Href: []string{"http://example.com/foo"}, Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{ Space: "http://ns.example.com/", Local: "Authors", }, }}, Status: "HTTP/1.1 424 Failed Dependency", }, { Prop: []Property{{ XMLName: xml.Name{ Space: "http://ns.example.com/", Local: "Copyright-Owner", }, }}, Status: "HTTP/1.1 409 Conflict", }}, ResponseDescription: "Copyright Owner cannot be deleted or altered.", }}, wantXML: `` + `` + `` + ` ` + ` http://example.com/foo` + ` ` + ` ` + ` ` + ` ` + ` HTTP/1.1 424 Failed Dependency` + ` ` + ` ` + ` ` + ` ` + ` ` + ` HTTP/1.1 409 Conflict` + ` ` + ` Copyright Owner cannot be deleted or altered.` + `` + ``, wantCode: StatusMulti, }, { desc: "section 9.6.2 (lock-token-submitted)", responses: []response{{ Href: []string{"http://example.com/foo"}, Status: "HTTP/1.1 423 Locked", Error: &xmlError{ InnerXML: []byte(``), }, }}, wantXML: `` + `` + `` + ` ` + ` http://example.com/foo` + ` HTTP/1.1 423 Locked` + ` ` + ` ` + ``, wantCode: StatusMulti, }, { desc: "section 9.1.3", responses: []response{{ Href: []string{"http://example.com/foo"}, Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "bigbox"}, InnerXML: []byte(`` + `` + `Box type A` + ``), }, { XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "author"}, InnerXML: []byte(`` + `` + `J.J. Johnson` + ``), }}, Status: "HTTP/1.1 200 OK", }, { Prop: []Property{{ XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "DingALing"}, }, { XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "Random"}, }}, Status: "HTTP/1.1 403 Forbidden", ResponseDescription: "The user does not have access to the DingALing property.", }}, }}, respdesc: "There has been an access violation error.", wantXML: `` + `` + `` + ` ` + ` http://example.com/foo` + ` ` + ` ` + ` Box type A` + ` J.J. Johnson` + ` ` + ` HTTP/1.1 200 OK` + ` ` + ` ` + ` ` + ` ` + ` ` + ` ` + ` HTTP/1.1 403 Forbidden` + ` The user does not have access to the DingALing property.` + ` ` + ` ` + ` There has been an access violation error.` + ``, wantCode: StatusMulti, }, { desc: "no response written", // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "no response written (with description)", respdesc: "too bad", // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "empty multistatus with header", writeHeader: true, wantXML: ``, wantCode: StatusMulti, }, { desc: "bad: no href", responses: []response{{ Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{ Space: "http://example.com/", Local: "foo", }, }}, Status: "HTTP/1.1 200 OK", }}, }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "bad: multiple hrefs and no status", responses: []response{{ Href: []string{"http://example.com/foo", "http://example.com/bar"}, }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "bad: one href and no propstat", responses: []response{{ Href: []string{"http://example.com/foo"}, }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "bad: status with one href and propstat", responses: []response{{ Href: []string{"http://example.com/foo"}, Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{ Space: "http://example.com/", Local: "foo", }, }}, Status: "HTTP/1.1 200 OK", }}, Status: "HTTP/1.1 200 OK", }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "bad: multiple hrefs and propstat", responses: []response{{ Href: []string{ "http://example.com/foo", "http://example.com/bar", }, Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{ Space: "http://example.com/", Local: "foo", }, }}, Status: "HTTP/1.1 200 OK", }}, }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }} n := xmlNormalizer{omitWhitespace: true} loop: for _, tc := range testCases { rec := httptest.NewRecorder() w := multistatusWriter{w: rec, responseDescription: tc.respdesc} if tc.writeHeader { if err := w.writeHeader(); err != nil { t.Errorf("%s: got writeHeader error %v, want nil", tc.desc, err) continue } } for _, r := range tc.responses { if err := w.write(&r); err != nil { if err != tc.wantErr { t.Errorf("%s: got write error %v, want %v", tc.desc, err, tc.wantErr) } continue loop } } if err := w.close(); err != tc.wantErr { t.Errorf("%s: got close error %v, want %v", tc.desc, err, tc.wantErr) continue } if rec.Code != tc.wantCode { t.Errorf("%s: got HTTP status code %d, want %d\n", tc.desc, rec.Code, tc.wantCode) continue } gotXML := rec.Body.String() eq, err := n.equalXML(strings.NewReader(gotXML), strings.NewReader(tc.wantXML)) if err != nil { t.Errorf("%s: equalXML: %v", tc.desc, err) continue } if !eq { t.Errorf("%s: XML body\ngot %s\nwant %s", tc.desc, gotXML, tc.wantXML) } } } func TestReadProppatch(t *testing.T) { ppStr := func(pps []Proppatch) string { var outer []string for _, pp := range pps { var inner []string for _, p := range pp.Props { inner = append(inner, fmt.Sprintf("{XMLName: %q, Lang: %q, InnerXML: %q}", p.XMLName, p.Lang, p.InnerXML)) } outer = append(outer, fmt.Sprintf("{Remove: %t, Props: [%s]}", pp.Remove, strings.Join(inner, ", "))) } return "[" + strings.Join(outer, ", ") + "]" } testCases := []struct { desc string input string wantPP []Proppatch wantStatus int }{{ desc: "proppatch: section 9.2 (with simple property value)", input: `` + `` + `` + ` ` + ` somevalue` + ` ` + ` ` + ` ` + ` ` + ``, wantPP: []Proppatch{{ Props: []Property{{ xml.Name{Space: "http://ns.example.com/z/", Local: "Authors"}, "", []byte(`somevalue`), }}, }, { Remove: true, Props: []Property{{ xml.Name{Space: "http://ns.example.com/z/", Local: "Copyright-Owner"}, "", nil, }}, }}, }, { desc: "proppatch: lang attribute on prop", input: `` + `` + `` + ` ` + ` ` + ` ` + ` ` + ` ` + ``, wantPP: []Proppatch{{ Props: []Property{{ xml.Name{Space: "http://example.com/ns", Local: "foo"}, "en", nil, }}, }}, }, { desc: "bad: remove with value", input: `` + `` + `` + ` ` + ` ` + ` ` + ` Jim Whitehead` + ` ` + ` ` + ` ` + ``, wantStatus: http.StatusBadRequest, }, { desc: "bad: empty propertyupdate", input: `` + `` + ``, wantStatus: http.StatusBadRequest, }, { desc: "bad: empty prop", input: `` + `` + `` + ` ` + ` ` + ` ` + ``, wantStatus: http.StatusBadRequest, }} for _, tc := range testCases { pp, status, err := readProppatch(strings.NewReader(tc.input)) if tc.wantStatus != 0 { if err == nil { t.Errorf("%s: got nil error, want non-nil", tc.desc) continue } } else if err != nil { t.Errorf("%s: %v", tc.desc, err) continue } if status != tc.wantStatus { t.Errorf("%s: got status %d, want %d", tc.desc, status, tc.wantStatus) continue } if !reflect.DeepEqual(pp, tc.wantPP) || status != tc.wantStatus { t.Errorf("%s: proppatch\ngot %v\nwant %v", tc.desc, ppStr(pp), ppStr(tc.wantPP)) } } } func TestUnmarshalXMLValue(t *testing.T) { testCases := []struct { desc string input string wantVal string }{{ desc: "simple char data", input: "foo", wantVal: "foo", }, { desc: "empty element", input: "", wantVal: "", }, { desc: "preserve namespace", input: ``, wantVal: ``, }, { desc: "preserve root element namespace", input: ``, wantVal: ``, }, { desc: "preserve whitespace", input: " \t ", wantVal: " \t ", }, { desc: "preserve mixed content", input: ` a `, wantVal: ` a `, }, { desc: "section 9.2", input: `` + `` + ` Jim Whitehead` + ` Roy Fielding` + ``, wantVal: `` + ` Jim Whitehead` + ` Roy Fielding`, }, { desc: "section 4.3.1 (mixed content)", input: `` + `` + ` Jane Doe` + ` ` + ` mailto:jane.doe@example.com` + ` http://www.example.com` + ` ` + ` Jane has been working way too long on the` + ` long-awaited revision of ]]>.` + ` ` + ``, wantVal: `` + ` Jane Doe` + ` ` + ` mailto:jane.doe@example.com` + ` http://www.example.com` + ` ` + ` Jane has been working way too long on the` + ` long-awaited revision of <RFC2518>.` + ` `, }} var n xmlNormalizer for _, tc := range testCases { d := ixml.NewDecoder(strings.NewReader(tc.input)) var v xmlValue if err := d.Decode(&v); err != nil { t.Errorf("%s: got error %v, want nil", tc.desc, err) continue } eq, err := n.equalXML(bytes.NewReader(v), strings.NewReader(tc.wantVal)) if err != nil { t.Errorf("%s: equalXML: %v", tc.desc, err) continue } if !eq { t.Errorf("%s:\ngot %s\nwant %s", tc.desc, string(v), tc.wantVal) } } } // xmlNormalizer normalizes XML. type xmlNormalizer struct { // omitWhitespace instructs to ignore whitespace between element tags. omitWhitespace bool // omitComments instructs to ignore XML comments. omitComments bool } // normalize writes the normalized XML content of r to w. It applies the // following rules // // * Rename namespace prefixes according to an internal heuristic. // * Remove unnecessary namespace declarations. // * Sort attributes in XML start elements in lexical order of their // fully qualified name. // * Remove XML directives and processing instructions. // * Remove CDATA between XML tags that only contains whitespace, if // instructed to do so. // * Remove comments, if instructed to do so. // func (n *xmlNormalizer) normalize(w io.Writer, r io.Reader) error { d := ixml.NewDecoder(r) e := ixml.NewEncoder(w) for { t, err := d.Token() if err != nil { if t == nil && err == io.EOF { break } return err } switch val := t.(type) { case ixml.Directive, ixml.ProcInst: continue case ixml.Comment: if n.omitComments { continue } case ixml.CharData: if n.omitWhitespace && len(bytes.TrimSpace(val)) == 0 { continue } case ixml.StartElement: start, _ := ixml.CopyToken(val).(ixml.StartElement) attr := start.Attr[:0] for _, a := range start.Attr { if a.Name.Space == "xmlns" || a.Name.Local == "xmlns" { continue } attr = append(attr, a) } sort.Sort(byName(attr)) start.Attr = attr t = start } err = e.EncodeToken(t) if err != nil { return err } } return e.Flush() } // equalXML tests for equality of the normalized XML contents of a and b. func (n *xmlNormalizer) equalXML(a, b io.Reader) (bool, error) { var buf bytes.Buffer if err := n.normalize(&buf, a); err != nil { return false, err } normA := buf.String() buf.Reset() if err := n.normalize(&buf, b); err != nil { return false, err } normB := buf.String() return normA == normB, nil } type byName []ixml.Attr func (a byName) Len() int { return len(a) } func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byName) Less(i, j int) bool { if a[i].Name.Space != a[j].Name.Space { return a[i].Name.Space < a[j].Name.Space } return a[i].Name.Local < a[j].Name.Local } lxd-2.0.11/dist/src/golang.org/x/net/webdav/xml.go0000644061062106075000000003751613172163402022726 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav // The XML encoding is covered by Section 14. // http://www.webdav.org/specs/rfc4918.html#xml.element.definitions import ( "bytes" "encoding/xml" "fmt" "io" "net/http" "time" // As of https://go-review.googlesource.com/#/c/12772/ which was submitted // in July 2015, this package uses an internal fork of the standard // library's encoding/xml package, due to changes in the way namespaces // were encoded. Such changes were introduced in the Go 1.5 cycle, but were // rolled back in response to https://github.com/golang/go/issues/11841 // // However, this package's exported API, specifically the Property and // DeadPropsHolder types, need to refer to the standard library's version // of the xml.Name type, as code that imports this package cannot refer to // the internal version. // // This file therefore imports both the internal and external versions, as // ixml and xml, and converts between them. // // In the long term, this package should use the standard library's version // only, and the internal fork deleted, once // https://github.com/golang/go/issues/13400 is resolved. ixml "golang.org/x/net/webdav/internal/xml" ) // http://www.webdav.org/specs/rfc4918.html#ELEMENT_lockinfo type lockInfo struct { XMLName ixml.Name `xml:"lockinfo"` Exclusive *struct{} `xml:"lockscope>exclusive"` Shared *struct{} `xml:"lockscope>shared"` Write *struct{} `xml:"locktype>write"` Owner owner `xml:"owner"` } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_owner type owner struct { InnerXML string `xml:",innerxml"` } func readLockInfo(r io.Reader) (li lockInfo, status int, err error) { c := &countingReader{r: r} if err = ixml.NewDecoder(c).Decode(&li); err != nil { if err == io.EOF { if c.n == 0 { // An empty body means to refresh the lock. // http://www.webdav.org/specs/rfc4918.html#refreshing-locks return lockInfo{}, 0, nil } err = errInvalidLockInfo } return lockInfo{}, http.StatusBadRequest, err } // We only support exclusive (non-shared) write locks. In practice, these are // the only types of locks that seem to matter. if li.Exclusive == nil || li.Shared != nil || li.Write == nil { return lockInfo{}, http.StatusNotImplemented, errUnsupportedLockInfo } return li, 0, nil } type countingReader struct { n int r io.Reader } func (c *countingReader) Read(p []byte) (int, error) { n, err := c.r.Read(p) c.n += n return n, err } func writeLockInfo(w io.Writer, token string, ld LockDetails) (int, error) { depth := "infinity" if ld.ZeroDepth { depth = "0" } timeout := ld.Duration / time.Second return fmt.Fprintf(w, "\n"+ "\n"+ " \n"+ " \n"+ " %s\n"+ " %s\n"+ " Second-%d\n"+ " %s\n"+ " %s\n"+ "", depth, ld.OwnerXML, timeout, escape(token), escape(ld.Root), ) } func escape(s string) string { for i := 0; i < len(s); i++ { switch s[i] { case '"', '&', '\'', '<', '>': b := bytes.NewBuffer(nil) ixml.EscapeText(b, []byte(s)) return b.String() } } return s } // Next returns the next token, if any, in the XML stream of d. // RFC 4918 requires to ignore comments, processing instructions // and directives. // http://www.webdav.org/specs/rfc4918.html#property_values // http://www.webdav.org/specs/rfc4918.html#xml-extensibility func next(d *ixml.Decoder) (ixml.Token, error) { for { t, err := d.Token() if err != nil { return t, err } switch t.(type) { case ixml.Comment, ixml.Directive, ixml.ProcInst: continue default: return t, nil } } } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_prop (for propfind) type propfindProps []xml.Name // UnmarshalXML appends the property names enclosed within start to pn. // // It returns an error if start does not contain any properties or if // properties contain values. Character data between properties is ignored. func (pn *propfindProps) UnmarshalXML(d *ixml.Decoder, start ixml.StartElement) error { for { t, err := next(d) if err != nil { return err } switch t.(type) { case ixml.EndElement: if len(*pn) == 0 { return fmt.Errorf("%s must not be empty", start.Name.Local) } return nil case ixml.StartElement: name := t.(ixml.StartElement).Name t, err = next(d) if err != nil { return err } if _, ok := t.(ixml.EndElement); !ok { return fmt.Errorf("unexpected token %T", t) } *pn = append(*pn, xml.Name(name)) } } } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propfind type propfind struct { XMLName ixml.Name `xml:"DAV: propfind"` Allprop *struct{} `xml:"DAV: allprop"` Propname *struct{} `xml:"DAV: propname"` Prop propfindProps `xml:"DAV: prop"` Include propfindProps `xml:"DAV: include"` } func readPropfind(r io.Reader) (pf propfind, status int, err error) { c := countingReader{r: r} if err = ixml.NewDecoder(&c).Decode(&pf); err != nil { if err == io.EOF { if c.n == 0 { // An empty body means to propfind allprop. // http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND return propfind{Allprop: new(struct{})}, 0, nil } err = errInvalidPropfind } return propfind{}, http.StatusBadRequest, err } if pf.Allprop == nil && pf.Include != nil { return propfind{}, http.StatusBadRequest, errInvalidPropfind } if pf.Allprop != nil && (pf.Prop != nil || pf.Propname != nil) { return propfind{}, http.StatusBadRequest, errInvalidPropfind } if pf.Prop != nil && pf.Propname != nil { return propfind{}, http.StatusBadRequest, errInvalidPropfind } if pf.Propname == nil && pf.Allprop == nil && pf.Prop == nil { return propfind{}, http.StatusBadRequest, errInvalidPropfind } return pf, 0, nil } // Property represents a single DAV resource property as defined in RFC 4918. // See http://www.webdav.org/specs/rfc4918.html#data.model.for.resource.properties type Property struct { // XMLName is the fully qualified name that identifies this property. XMLName xml.Name // Lang is an optional xml:lang attribute. Lang string `xml:"xml:lang,attr,omitempty"` // InnerXML contains the XML representation of the property value. // See http://www.webdav.org/specs/rfc4918.html#property_values // // Property values of complex type or mixed-content must have fully // expanded XML namespaces or be self-contained with according // XML namespace declarations. They must not rely on any XML // namespace declarations within the scope of the XML document, // even including the DAV: namespace. InnerXML []byte `xml:",innerxml"` } // ixmlProperty is the same as the Property type except it holds an ixml.Name // instead of an xml.Name. type ixmlProperty struct { XMLName ixml.Name Lang string `xml:"xml:lang,attr,omitempty"` InnerXML []byte `xml:",innerxml"` } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_error // See multistatusWriter for the "D:" namespace prefix. type xmlError struct { XMLName ixml.Name `xml:"D:error"` InnerXML []byte `xml:",innerxml"` } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat // See multistatusWriter for the "D:" namespace prefix. type propstat struct { Prop []Property `xml:"D:prop>_ignored_"` Status string `xml:"D:status"` Error *xmlError `xml:"D:error"` ResponseDescription string `xml:"D:responsedescription,omitempty"` } // ixmlPropstat is the same as the propstat type except it holds an ixml.Name // instead of an xml.Name. type ixmlPropstat struct { Prop []ixmlProperty `xml:"D:prop>_ignored_"` Status string `xml:"D:status"` Error *xmlError `xml:"D:error"` ResponseDescription string `xml:"D:responsedescription,omitempty"` } // MarshalXML prepends the "D:" namespace prefix on properties in the DAV: namespace // before encoding. See multistatusWriter. func (ps propstat) MarshalXML(e *ixml.Encoder, start ixml.StartElement) error { // Convert from a propstat to an ixmlPropstat. ixmlPs := ixmlPropstat{ Prop: make([]ixmlProperty, len(ps.Prop)), Status: ps.Status, Error: ps.Error, ResponseDescription: ps.ResponseDescription, } for k, prop := range ps.Prop { ixmlPs.Prop[k] = ixmlProperty{ XMLName: ixml.Name(prop.XMLName), Lang: prop.Lang, InnerXML: prop.InnerXML, } } for k, prop := range ixmlPs.Prop { if prop.XMLName.Space == "DAV:" { prop.XMLName = ixml.Name{Space: "", Local: "D:" + prop.XMLName.Local} ixmlPs.Prop[k] = prop } } // Distinct type to avoid infinite recursion of MarshalXML. type newpropstat ixmlPropstat return e.EncodeElement(newpropstat(ixmlPs), start) } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_response // See multistatusWriter for the "D:" namespace prefix. type response struct { XMLName ixml.Name `xml:"D:response"` Href []string `xml:"D:href"` Propstat []propstat `xml:"D:propstat"` Status string `xml:"D:status,omitempty"` Error *xmlError `xml:"D:error"` ResponseDescription string `xml:"D:responsedescription,omitempty"` } // MultistatusWriter marshals one or more Responses into a XML // multistatus response. // See http://www.webdav.org/specs/rfc4918.html#ELEMENT_multistatus // TODO(rsto, mpl): As a workaround, the "D:" namespace prefix, defined as // "DAV:" on this element, is prepended on the nested response, as well as on all // its nested elements. All property names in the DAV: namespace are prefixed as // well. This is because some versions of Mini-Redirector (on windows 7) ignore // elements with a default namespace (no prefixed namespace). A less intrusive fix // should be possible after golang.org/cl/11074. See https://golang.org/issue/11177 type multistatusWriter struct { // ResponseDescription contains the optional responsedescription // of the multistatus XML element. Only the latest content before // close will be emitted. Empty response descriptions are not // written. responseDescription string w http.ResponseWriter enc *ixml.Encoder } // Write validates and emits a DAV response as part of a multistatus response // element. // // It sets the HTTP status code of its underlying http.ResponseWriter to 207 // (Multi-Status) and populates the Content-Type header. If r is the // first, valid response to be written, Write prepends the XML representation // of r with a multistatus tag. Callers must call close after the last response // has been written. func (w *multistatusWriter) write(r *response) error { switch len(r.Href) { case 0: return errInvalidResponse case 1: if len(r.Propstat) > 0 != (r.Status == "") { return errInvalidResponse } default: if len(r.Propstat) > 0 || r.Status == "" { return errInvalidResponse } } err := w.writeHeader() if err != nil { return err } return w.enc.Encode(r) } // writeHeader writes a XML multistatus start element on w's underlying // http.ResponseWriter and returns the result of the write operation. // After the first write attempt, writeHeader becomes a no-op. func (w *multistatusWriter) writeHeader() error { if w.enc != nil { return nil } w.w.Header().Add("Content-Type", "text/xml; charset=utf-8") w.w.WriteHeader(StatusMulti) _, err := fmt.Fprintf(w.w, ``) if err != nil { return err } w.enc = ixml.NewEncoder(w.w) return w.enc.EncodeToken(ixml.StartElement{ Name: ixml.Name{ Space: "DAV:", Local: "multistatus", }, Attr: []ixml.Attr{{ Name: ixml.Name{Space: "xmlns", Local: "D"}, Value: "DAV:", }}, }) } // Close completes the marshalling of the multistatus response. It returns // an error if the multistatus response could not be completed. If both the // return value and field enc of w are nil, then no multistatus response has // been written. func (w *multistatusWriter) close() error { if w.enc == nil { return nil } var end []ixml.Token if w.responseDescription != "" { name := ixml.Name{Space: "DAV:", Local: "responsedescription"} end = append(end, ixml.StartElement{Name: name}, ixml.CharData(w.responseDescription), ixml.EndElement{Name: name}, ) } end = append(end, ixml.EndElement{ Name: ixml.Name{Space: "DAV:", Local: "multistatus"}, }) for _, t := range end { err := w.enc.EncodeToken(t) if err != nil { return err } } return w.enc.Flush() } var xmlLangName = ixml.Name{Space: "http://www.w3.org/XML/1998/namespace", Local: "lang"} func xmlLang(s ixml.StartElement, d string) string { for _, attr := range s.Attr { if attr.Name == xmlLangName { return attr.Value } } return d } type xmlValue []byte func (v *xmlValue) UnmarshalXML(d *ixml.Decoder, start ixml.StartElement) error { // The XML value of a property can be arbitrary, mixed-content XML. // To make sure that the unmarshalled value contains all required // namespaces, we encode all the property value XML tokens into a // buffer. This forces the encoder to redeclare any used namespaces. var b bytes.Buffer e := ixml.NewEncoder(&b) for { t, err := next(d) if err != nil { return err } if e, ok := t.(ixml.EndElement); ok && e.Name == start.Name { break } if err = e.EncodeToken(t); err != nil { return err } } err := e.Flush() if err != nil { return err } *v = b.Bytes() return nil } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_prop (for proppatch) type proppatchProps []Property // UnmarshalXML appends the property names and values enclosed within start // to ps. // // An xml:lang attribute that is defined either on the DAV:prop or property // name XML element is propagated to the property's Lang field. // // UnmarshalXML returns an error if start does not contain any properties or if // property values contain syntactically incorrect XML. func (ps *proppatchProps) UnmarshalXML(d *ixml.Decoder, start ixml.StartElement) error { lang := xmlLang(start, "") for { t, err := next(d) if err != nil { return err } switch elem := t.(type) { case ixml.EndElement: if len(*ps) == 0 { return fmt.Errorf("%s must not be empty", start.Name.Local) } return nil case ixml.StartElement: p := Property{ XMLName: xml.Name(t.(ixml.StartElement).Name), Lang: xmlLang(t.(ixml.StartElement), lang), } err = d.DecodeElement(((*xmlValue)(&p.InnerXML)), &elem) if err != nil { return err } *ps = append(*ps, p) } } } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_set // http://www.webdav.org/specs/rfc4918.html#ELEMENT_remove type setRemove struct { XMLName ixml.Name Lang string `xml:"xml:lang,attr,omitempty"` Prop proppatchProps `xml:"DAV: prop"` } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propertyupdate type propertyupdate struct { XMLName ixml.Name `xml:"DAV: propertyupdate"` Lang string `xml:"xml:lang,attr,omitempty"` SetRemove []setRemove `xml:",any"` } func readProppatch(r io.Reader) (patches []Proppatch, status int, err error) { var pu propertyupdate if err = ixml.NewDecoder(r).Decode(&pu); err != nil { return nil, http.StatusBadRequest, err } for _, op := range pu.SetRemove { remove := false switch op.XMLName { case ixml.Name{Space: "DAV:", Local: "set"}: // No-op. case ixml.Name{Space: "DAV:", Local: "remove"}: for _, p := range op.Prop { if len(p.InnerXML) > 0 { return nil, http.StatusBadRequest, errInvalidProppatch } } remove = true default: return nil, http.StatusBadRequest, errInvalidProppatch } patches = append(patches, Proppatch{Remove: remove, Props: op.Prop}) } return patches, 0, nil } lxd-2.0.11/dist/src/golang.org/x/net/webdav/webdav_test.go0000644061062106075000000002225713172163402024431 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "errors" "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "net/url" "os" "reflect" "regexp" "sort" "strings" "testing" "golang.org/x/net/context" ) // TODO: add tests to check XML responses with the expected prefix path func TestPrefix(t *testing.T) { const dst, blah = "Destination", "blah blah blah" // createLockBody comes from the example in Section 9.10.7. const createLockBody = ` http://example.org/~ejw/contact.html ` do := func(method, urlStr string, body string, wantStatusCode int, headers ...string) (http.Header, error) { var bodyReader io.Reader if body != "" { bodyReader = strings.NewReader(body) } req, err := http.NewRequest(method, urlStr, bodyReader) if err != nil { return nil, err } for len(headers) >= 2 { req.Header.Add(headers[0], headers[1]) headers = headers[2:] } res, err := http.DefaultTransport.RoundTrip(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != wantStatusCode { return nil, fmt.Errorf("got status code %d, want %d", res.StatusCode, wantStatusCode) } return res.Header, nil } prefixes := []string{ "/", "/a/", "/a/b/", "/a/b/c/", } ctx := context.Background() for _, prefix := range prefixes { fs := NewMemFS() h := &Handler{ FileSystem: fs, LockSystem: NewMemLS(), } mux := http.NewServeMux() if prefix != "/" { h.Prefix = prefix } mux.Handle(prefix, h) srv := httptest.NewServer(mux) defer srv.Close() // The script is: // MKCOL /a // MKCOL /a/b // PUT /a/b/c // COPY /a/b/c /a/b/d // MKCOL /a/b/e // MOVE /a/b/d /a/b/e/f // LOCK /a/b/e/g // PUT /a/b/e/g // which should yield the (possibly stripped) filenames /a/b/c, // /a/b/e/f and /a/b/e/g, plus their parent directories. wantA := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusMovedPermanently, "/a/b/": http.StatusNotFound, "/a/b/c/": http.StatusNotFound, }[prefix] if _, err := do("MKCOL", srv.URL+"/a", "", wantA); err != nil { t.Errorf("prefix=%-9q MKCOL /a: %v", prefix, err) continue } wantB := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusMovedPermanently, "/a/b/c/": http.StatusNotFound, }[prefix] if _, err := do("MKCOL", srv.URL+"/a/b", "", wantB); err != nil { t.Errorf("prefix=%-9q MKCOL /a/b: %v", prefix, err) continue } wantC := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusMovedPermanently, }[prefix] if _, err := do("PUT", srv.URL+"/a/b/c", blah, wantC); err != nil { t.Errorf("prefix=%-9q PUT /a/b/c: %v", prefix, err) continue } wantD := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusMovedPermanently, }[prefix] if _, err := do("COPY", srv.URL+"/a/b/c", "", wantD, dst, srv.URL+"/a/b/d"); err != nil { t.Errorf("prefix=%-9q COPY /a/b/c /a/b/d: %v", prefix, err) continue } wantE := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusNotFound, }[prefix] if _, err := do("MKCOL", srv.URL+"/a/b/e", "", wantE); err != nil { t.Errorf("prefix=%-9q MKCOL /a/b/e: %v", prefix, err) continue } wantF := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusNotFound, }[prefix] if _, err := do("MOVE", srv.URL+"/a/b/d", "", wantF, dst, srv.URL+"/a/b/e/f"); err != nil { t.Errorf("prefix=%-9q MOVE /a/b/d /a/b/e/f: %v", prefix, err) continue } var lockToken string wantG := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusNotFound, }[prefix] if h, err := do("LOCK", srv.URL+"/a/b/e/g", createLockBody, wantG); err != nil { t.Errorf("prefix=%-9q LOCK /a/b/e/g: %v", prefix, err) continue } else { lockToken = h.Get("Lock-Token") } ifHeader := fmt.Sprintf("<%s/a/b/e/g> (%s)", srv.URL, lockToken) wantH := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusNotFound, }[prefix] if _, err := do("PUT", srv.URL+"/a/b/e/g", blah, wantH, "If", ifHeader); err != nil { t.Errorf("prefix=%-9q PUT /a/b/e/g: %v", prefix, err) continue } got, err := find(ctx, nil, fs, "/") if err != nil { t.Errorf("prefix=%-9q find: %v", prefix, err) continue } sort.Strings(got) want := map[string][]string{ "/": {"/", "/a", "/a/b", "/a/b/c", "/a/b/e", "/a/b/e/f", "/a/b/e/g"}, "/a/": {"/", "/b", "/b/c", "/b/e", "/b/e/f", "/b/e/g"}, "/a/b/": {"/", "/c", "/e", "/e/f", "/e/g"}, "/a/b/c/": {"/"}, }[prefix] if !reflect.DeepEqual(got, want) { t.Errorf("prefix=%-9q find:\ngot %v\nwant %v", prefix, got, want) continue } } } func TestEscapeXML(t *testing.T) { // These test cases aren't exhaustive, and there is more than one way to // escape e.g. a quot (as """ or """) or an apos. We presume that // the encoding/xml package tests xml.EscapeText more thoroughly. This test // here is just a sanity check for this package's escapeXML function, and // its attempt to provide a fast path (and avoid a bytes.Buffer allocation) // when escaping filenames is obviously a no-op. testCases := map[string]string{ "": "", " ": " ", "&": "&", "*": "*", "+": "+", ",": ",", "-": "-", ".": ".", "/": "/", "0": "0", "9": "9", ":": ":", "<": "<", ">": ">", "A": "A", "_": "_", "a": "a", "~": "~", "\u0201": "\u0201", "&": "&amp;", "foo&baz": "foo&<b/ar>baz", } for in, want := range testCases { if got := escapeXML(in); got != want { t.Errorf("in=%q: got %q, want %q", in, got, want) } } } func TestFilenameEscape(t *testing.T) { hrefRe := regexp.MustCompile(`([^<]*)`) displayNameRe := regexp.MustCompile(`([^<]*)`) do := func(method, urlStr string) (string, string, error) { req, err := http.NewRequest(method, urlStr, nil) if err != nil { return "", "", err } res, err := http.DefaultClient.Do(req) if err != nil { return "", "", err } defer res.Body.Close() b, err := ioutil.ReadAll(res.Body) if err != nil { return "", "", err } hrefMatch := hrefRe.FindStringSubmatch(string(b)) if len(hrefMatch) != 2 { return "", "", errors.New("D:href not found") } displayNameMatch := displayNameRe.FindStringSubmatch(string(b)) if len(displayNameMatch) != 2 { return "", "", errors.New("D:displayname not found") } return hrefMatch[1], displayNameMatch[1], nil } testCases := []struct { name, wantHref, wantDisplayName string }{{ name: `/foo%bar`, wantHref: `/foo%25bar`, wantDisplayName: `foo%bar`, }, { name: `/ã“ã‚“ã«ã¡ã‚世界`, wantHref: `/%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%82%8F%E4%B8%96%E7%95%8C`, wantDisplayName: `ã“ã‚“ã«ã¡ã‚世界`, }, { name: `/Program Files/`, wantHref: `/Program%20Files`, wantDisplayName: `Program Files`, }, { name: `/go+lang`, wantHref: `/go+lang`, wantDisplayName: `go+lang`, }, { name: `/go&lang`, wantHref: `/go&lang`, wantDisplayName: `go&lang`, }, { name: `/go 0 { return http.StatusUnsupportedMediaType, nil } if err := h.FileSystem.Mkdir(ctx, reqPath, 0777); err != nil { if os.IsNotExist(err) { return http.StatusConflict, err } return http.StatusMethodNotAllowed, err } return http.StatusCreated, nil } func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) (status int, err error) { hdr := r.Header.Get("Destination") if hdr == "" { return http.StatusBadRequest, errInvalidDestination } u, err := url.Parse(hdr) if err != nil { return http.StatusBadRequest, errInvalidDestination } if u.Host != r.Host { return http.StatusBadGateway, errInvalidDestination } src, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } dst, status, err := h.stripPrefix(u.Path) if err != nil { return status, err } if dst == "" { return http.StatusBadGateway, errInvalidDestination } if dst == src { return http.StatusForbidden, errDestinationEqualsSource } ctx := getContext(r) if r.Method == "COPY" { // Section 7.5.1 says that a COPY only needs to lock the destination, // not both destination and source. Strictly speaking, this is racy, // even though a COPY doesn't modify the source, if a concurrent // operation modifies the source. However, the litmus test explicitly // checks that COPYing a locked-by-another source is OK. release, status, err := h.confirmLocks(r, "", dst) if err != nil { return status, err } defer release() // Section 9.8.3 says that "The COPY method on a collection without a Depth // header must act as if a Depth header with value "infinity" was included". depth := infiniteDepth if hdr := r.Header.Get("Depth"); hdr != "" { depth = parseDepth(hdr) if depth != 0 && depth != infiniteDepth { // Section 9.8.3 says that "A client may submit a Depth header on a // COPY on a collection with a value of "0" or "infinity"." return http.StatusBadRequest, errInvalidDepth } } return copyFiles(ctx, h.FileSystem, src, dst, r.Header.Get("Overwrite") != "F", depth, 0) } release, status, err := h.confirmLocks(r, src, dst) if err != nil { return status, err } defer release() // Section 9.9.2 says that "The MOVE method on a collection must act as if // a "Depth: infinity" header was used on it. A client must not submit a // Depth header on a MOVE on a collection with any value but "infinity"." if hdr := r.Header.Get("Depth"); hdr != "" { if parseDepth(hdr) != infiniteDepth { return http.StatusBadRequest, errInvalidDepth } } return moveFiles(ctx, h.FileSystem, src, dst, r.Header.Get("Overwrite") == "T") } func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus int, retErr error) { duration, err := parseTimeout(r.Header.Get("Timeout")) if err != nil { return http.StatusBadRequest, err } li, status, err := readLockInfo(r.Body) if err != nil { return status, err } ctx := getContext(r) token, ld, now, created := "", LockDetails{}, time.Now(), false if li == (lockInfo{}) { // An empty lockInfo means to refresh the lock. ih, ok := parseIfHeader(r.Header.Get("If")) if !ok { return http.StatusBadRequest, errInvalidIfHeader } if len(ih.lists) == 1 && len(ih.lists[0].conditions) == 1 { token = ih.lists[0].conditions[0].Token } if token == "" { return http.StatusBadRequest, errInvalidLockToken } ld, err = h.LockSystem.Refresh(now, token, duration) if err != nil { if err == ErrNoSuchLock { return http.StatusPreconditionFailed, err } return http.StatusInternalServerError, err } } else { // Section 9.10.3 says that "If no Depth header is submitted on a LOCK request, // then the request MUST act as if a "Depth:infinity" had been submitted." depth := infiniteDepth if hdr := r.Header.Get("Depth"); hdr != "" { depth = parseDepth(hdr) if depth != 0 && depth != infiniteDepth { // Section 9.10.3 says that "Values other than 0 or infinity must not be // used with the Depth header on a LOCK method". return http.StatusBadRequest, errInvalidDepth } } reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } ld = LockDetails{ Root: reqPath, Duration: duration, OwnerXML: li.Owner.InnerXML, ZeroDepth: depth == 0, } token, err = h.LockSystem.Create(now, ld) if err != nil { if err == ErrLocked { return StatusLocked, err } return http.StatusInternalServerError, err } defer func() { if retErr != nil { h.LockSystem.Unlock(now, token) } }() // Create the resource if it didn't previously exist. if _, err := h.FileSystem.Stat(ctx, reqPath); err != nil { f, err := h.FileSystem.OpenFile(ctx, reqPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { // TODO: detect missing intermediate dirs and return http.StatusConflict? return http.StatusInternalServerError, err } f.Close() created = true } // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the // Lock-Token value is a Coded-URL. We add angle brackets. w.Header().Set("Lock-Token", "<"+token+">") } w.Header().Set("Content-Type", "application/xml; charset=utf-8") if created { // This is "w.WriteHeader(http.StatusCreated)" and not "return // http.StatusCreated, nil" because we write our own (XML) response to w // and Handler.ServeHTTP would otherwise write "Created". w.WriteHeader(http.StatusCreated) } writeLockInfo(w, token, ld) return 0, nil } func (h *Handler) handleUnlock(w http.ResponseWriter, r *http.Request) (status int, err error) { // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the // Lock-Token value is a Coded-URL. We strip its angle brackets. t := r.Header.Get("Lock-Token") if len(t) < 2 || t[0] != '<' || t[len(t)-1] != '>' { return http.StatusBadRequest, errInvalidLockToken } t = t[1 : len(t)-1] switch err = h.LockSystem.Unlock(time.Now(), t); err { case nil: return http.StatusNoContent, err case ErrForbidden: return http.StatusForbidden, err case ErrLocked: return StatusLocked, err case ErrNoSuchLock: return http.StatusConflict, err default: return http.StatusInternalServerError, err } } func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } ctx := getContext(r) fi, err := h.FileSystem.Stat(ctx, reqPath) if err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusMethodNotAllowed, err } depth := infiniteDepth if hdr := r.Header.Get("Depth"); hdr != "" { depth = parseDepth(hdr) if depth == invalidDepth { return http.StatusBadRequest, errInvalidDepth } } pf, status, err := readPropfind(r.Body) if err != nil { return status, err } mw := multistatusWriter{w: w} walkFn := func(reqPath string, info os.FileInfo, err error) error { if err != nil { return err } var pstats []Propstat if pf.Propname != nil { pnames, err := propnames(ctx, h.FileSystem, h.LockSystem, reqPath) if err != nil { return err } pstat := Propstat{Status: http.StatusOK} for _, xmlname := range pnames { pstat.Props = append(pstat.Props, Property{XMLName: xmlname}) } pstats = append(pstats, pstat) } else if pf.Allprop != nil { pstats, err = allprop(ctx, h.FileSystem, h.LockSystem, reqPath, pf.Prop) } else { pstats, err = props(ctx, h.FileSystem, h.LockSystem, reqPath, pf.Prop) } if err != nil { return err } return mw.write(makePropstatResponse(path.Join(h.Prefix, reqPath), pstats)) } walkErr := walkFS(ctx, h.FileSystem, depth, reqPath, fi, walkFn) closeErr := mw.close() if walkErr != nil { return http.StatusInternalServerError, walkErr } if closeErr != nil { return http.StatusInternalServerError, closeErr } return 0, nil } func (h *Handler) handleProppatch(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } release, status, err := h.confirmLocks(r, reqPath, "") if err != nil { return status, err } defer release() ctx := getContext(r) if _, err := h.FileSystem.Stat(ctx, reqPath); err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusMethodNotAllowed, err } patches, status, err := readProppatch(r.Body) if err != nil { return status, err } pstats, err := patch(ctx, h.FileSystem, h.LockSystem, reqPath, patches) if err != nil { return http.StatusInternalServerError, err } mw := multistatusWriter{w: w} writeErr := mw.write(makePropstatResponse(r.URL.Path, pstats)) closeErr := mw.close() if writeErr != nil { return http.StatusInternalServerError, writeErr } if closeErr != nil { return http.StatusInternalServerError, closeErr } return 0, nil } func makePropstatResponse(href string, pstats []Propstat) *response { resp := response{ Href: []string{(&url.URL{Path: href}).EscapedPath()}, Propstat: make([]propstat, 0, len(pstats)), } for _, p := range pstats { var xmlErr *xmlError if p.XMLError != "" { xmlErr = &xmlError{InnerXML: []byte(p.XMLError)} } resp.Propstat = append(resp.Propstat, propstat{ Status: fmt.Sprintf("HTTP/1.1 %d %s", p.Status, StatusText(p.Status)), Prop: p.Props, ResponseDescription: p.ResponseDescription, Error: xmlErr, }) } return &resp } const ( infiniteDepth = -1 invalidDepth = -2 ) // parseDepth maps the strings "0", "1" and "infinity" to 0, 1 and // infiniteDepth. Parsing any other string returns invalidDepth. // // Different WebDAV methods have further constraints on valid depths: // - PROPFIND has no further restrictions, as per section 9.1. // - COPY accepts only "0" or "infinity", as per section 9.8.3. // - MOVE accepts only "infinity", as per section 9.9.2. // - LOCK accepts only "0" or "infinity", as per section 9.10.3. // These constraints are enforced by the handleXxx methods. func parseDepth(s string) int { switch s { case "0": return 0 case "1": return 1 case "infinity": return infiniteDepth } return invalidDepth } // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11 const ( StatusMulti = 207 StatusUnprocessableEntity = 422 StatusLocked = 423 StatusFailedDependency = 424 StatusInsufficientStorage = 507 ) func StatusText(code int) string { switch code { case StatusMulti: return "Multi-Status" case StatusUnprocessableEntity: return "Unprocessable Entity" case StatusLocked: return "Locked" case StatusFailedDependency: return "Failed Dependency" case StatusInsufficientStorage: return "Insufficient Storage" } return http.StatusText(code) } var ( errDestinationEqualsSource = errors.New("webdav: destination equals source") errDirectoryNotEmpty = errors.New("webdav: directory not empty") errInvalidDepth = errors.New("webdav: invalid depth") errInvalidDestination = errors.New("webdav: invalid destination") errInvalidIfHeader = errors.New("webdav: invalid If header") errInvalidLockInfo = errors.New("webdav: invalid lock info") errInvalidLockToken = errors.New("webdav: invalid lock token") errInvalidPropfind = errors.New("webdav: invalid propfind") errInvalidProppatch = errors.New("webdav: invalid proppatch") errInvalidResponse = errors.New("webdav: invalid response") errInvalidTimeout = errors.New("webdav: invalid timeout") errNoFileSystem = errors.New("webdav: no file system") errNoLockSystem = errors.New("webdav: no lock system") errNotADirectory = errors.New("webdav: not a directory") errPrefixMismatch = errors.New("webdav: prefix mismatch") errRecursionTooDeep = errors.New("webdav: recursion too deep") errUnsupportedLockInfo = errors.New("webdav: unsupported lock info") errUnsupportedMethod = errors.New("webdav: unsupported method") ) lxd-2.0.11/dist/src/golang.org/x/net/webdav/prop_test.go0000644061062106075000000004076713172163402024147 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "encoding/xml" "fmt" "net/http" "os" "reflect" "sort" "testing" "golang.org/x/net/context" ) func TestMemPS(t *testing.T) { ctx := context.Background() // calcProps calculates the getlastmodified and getetag DAV: property // values in pstats for resource name in file-system fs. calcProps := func(name string, fs FileSystem, ls LockSystem, pstats []Propstat) error { fi, err := fs.Stat(ctx, name) if err != nil { return err } for _, pst := range pstats { for i, p := range pst.Props { switch p.XMLName { case xml.Name{Space: "DAV:", Local: "getlastmodified"}: p.InnerXML = []byte(fi.ModTime().Format(http.TimeFormat)) pst.Props[i] = p case xml.Name{Space: "DAV:", Local: "getetag"}: if fi.IsDir() { continue } etag, err := findETag(ctx, fs, ls, name, fi) if err != nil { return err } p.InnerXML = []byte(etag) pst.Props[i] = p } } } return nil } const ( lockEntry = `` + `` + `` + `` + `` statForbiddenError = `` ) type propOp struct { op string name string pnames []xml.Name patches []Proppatch wantPnames []xml.Name wantPropstats []Propstat } testCases := []struct { desc string noDeadProps bool buildfs []string propOp []propOp }{{ desc: "propname", buildfs: []string{"mkdir /dir", "touch /file"}, propOp: []propOp{{ op: "propname", name: "/dir", wantPnames: []xml.Name{ {Space: "DAV:", Local: "resourcetype"}, {Space: "DAV:", Local: "displayname"}, {Space: "DAV:", Local: "supportedlock"}, {Space: "DAV:", Local: "getlastmodified"}, }, }, { op: "propname", name: "/file", wantPnames: []xml.Name{ {Space: "DAV:", Local: "resourcetype"}, {Space: "DAV:", Local: "displayname"}, {Space: "DAV:", Local: "getcontentlength"}, {Space: "DAV:", Local: "getlastmodified"}, {Space: "DAV:", Local: "getcontenttype"}, {Space: "DAV:", Local: "getetag"}, {Space: "DAV:", Local: "supportedlock"}, }, }}, }, { desc: "allprop dir and file", buildfs: []string{"mkdir /dir", "write /file foobarbaz"}, propOp: []propOp{{ op: "allprop", name: "/dir", wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(``), }, { XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, InnerXML: []byte("dir"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, InnerXML: []byte(lockEntry), }}, }}, }, { op: "allprop", name: "/file", wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(""), }, { XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, InnerXML: []byte("file"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontentlength"}, InnerXML: []byte("9"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontenttype"}, InnerXML: []byte("text/plain; charset=utf-8"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, InnerXML: []byte(lockEntry), }}, }}, }, { op: "allprop", name: "/file", pnames: []xml.Name{ {"DAV:", "resourcetype"}, {"foo", "bar"}, }, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(""), }, { XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, InnerXML: []byte("file"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontentlength"}, InnerXML: []byte("9"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontenttype"}, InnerXML: []byte("text/plain; charset=utf-8"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, InnerXML: []byte(lockEntry), }}}, { Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}}, }, }}, }, { desc: "propfind DAV:resourcetype", buildfs: []string{"mkdir /dir", "touch /file"}, propOp: []propOp{{ op: "propfind", name: "/dir", pnames: []xml.Name{{"DAV:", "resourcetype"}}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(``), }}, }}, }, { op: "propfind", name: "/file", pnames: []xml.Name{{"DAV:", "resourcetype"}}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(""), }}, }}, }}, }, { desc: "propfind unsupported DAV properties", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "propfind", name: "/dir", pnames: []xml.Name{{"DAV:", "getcontentlanguage"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getcontentlanguage"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{{"DAV:", "creationdate"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "creationdate"}, }}, }}, }}, }, { desc: "propfind getetag for files but not for directories", buildfs: []string{"mkdir /dir", "touch /file"}, propOp: []propOp{{ op: "propfind", name: "/dir", pnames: []xml.Name{{"DAV:", "getetag"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, }}, }}, }, { op: "propfind", name: "/file", pnames: []xml.Name{{"DAV:", "getetag"}}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, InnerXML: nil, // Calculated during test. }}, }}, }}, }, { desc: "proppatch property on no-dead-properties file system", buildfs: []string{"mkdir /dir"}, noDeadProps: true, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, wantPropstats: []Propstat{{ Status: http.StatusForbidden, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, }}, }}, wantPropstats: []Propstat{{ Status: http.StatusForbidden, XMLError: statForbiddenError, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, }}, }}, }}, }, { desc: "proppatch dead property", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{{Space: "foo", Local: "bar"}}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }}, }}, }}, }, { desc: "proppatch dead property with failed dependency", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }}, }, { Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, InnerXML: []byte("xxx"), }}, }}, wantPropstats: []Propstat{{ Status: http.StatusForbidden, XMLError: statForbiddenError, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, }}, }, { Status: StatusFailedDependency, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{{Space: "foo", Local: "bar"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }}, }, { desc: "proppatch remove dead property", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }, { XMLName: xml.Name{Space: "spam", Local: "ham"}, InnerXML: []byte("eggs"), }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }, { XMLName: xml.Name{Space: "spam", Local: "ham"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{ {Space: "foo", Local: "bar"}, {Space: "spam", Local: "ham"}, }, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }, { XMLName: xml.Name{Space: "spam", Local: "ham"}, InnerXML: []byte("eggs"), }}, }}, }, { op: "proppatch", name: "/dir", patches: []Proppatch{{ Remove: true, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{ {Space: "foo", Local: "bar"}, {Space: "spam", Local: "ham"}, }, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }, { Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "spam", Local: "ham"}, InnerXML: []byte("eggs"), }}, }}, }}, }, { desc: "propname with dead property", buildfs: []string{"touch /file"}, propOp: []propOp{{ op: "proppatch", name: "/file", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "propname", name: "/file", wantPnames: []xml.Name{ {Space: "DAV:", Local: "resourcetype"}, {Space: "DAV:", Local: "displayname"}, {Space: "DAV:", Local: "getcontentlength"}, {Space: "DAV:", Local: "getlastmodified"}, {Space: "DAV:", Local: "getcontenttype"}, {Space: "DAV:", Local: "getetag"}, {Space: "DAV:", Local: "supportedlock"}, {Space: "foo", Local: "bar"}, }, }}, }, { desc: "proppatch remove unknown dead property", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Remove: true, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }}, }, { desc: "bad: propfind unknown property", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "propfind", name: "/dir", pnames: []xml.Name{{"foo:", "bar"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "foo:", Local: "bar"}, }}, }}, }}, }} for _, tc := range testCases { fs, err := buildTestFS(tc.buildfs) if err != nil { t.Fatalf("%s: cannot create test filesystem: %v", tc.desc, err) } if tc.noDeadProps { fs = noDeadPropsFS{fs} } ls := NewMemLS() for _, op := range tc.propOp { desc := fmt.Sprintf("%s: %s %s", tc.desc, op.op, op.name) if err = calcProps(op.name, fs, ls, op.wantPropstats); err != nil { t.Fatalf("%s: calcProps: %v", desc, err) } // Call property system. var propstats []Propstat switch op.op { case "propname": pnames, err := propnames(ctx, fs, ls, op.name) if err != nil { t.Errorf("%s: got error %v, want nil", desc, err) continue } sort.Sort(byXMLName(pnames)) sort.Sort(byXMLName(op.wantPnames)) if !reflect.DeepEqual(pnames, op.wantPnames) { t.Errorf("%s: pnames\ngot %q\nwant %q", desc, pnames, op.wantPnames) } continue case "allprop": propstats, err = allprop(ctx, fs, ls, op.name, op.pnames) case "propfind": propstats, err = props(ctx, fs, ls, op.name, op.pnames) case "proppatch": propstats, err = patch(ctx, fs, ls, op.name, op.patches) default: t.Fatalf("%s: %s not implemented", desc, op.op) } if err != nil { t.Errorf("%s: got error %v, want nil", desc, err) continue } // Compare return values from allprop, propfind or proppatch. for _, pst := range propstats { sort.Sort(byPropname(pst.Props)) } for _, pst := range op.wantPropstats { sort.Sort(byPropname(pst.Props)) } sort.Sort(byStatus(propstats)) sort.Sort(byStatus(op.wantPropstats)) if !reflect.DeepEqual(propstats, op.wantPropstats) { t.Errorf("%s: propstat\ngot %q\nwant %q", desc, propstats, op.wantPropstats) } } } } func cmpXMLName(a, b xml.Name) bool { if a.Space != b.Space { return a.Space < b.Space } return a.Local < b.Local } type byXMLName []xml.Name func (b byXMLName) Len() int { return len(b) } func (b byXMLName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byXMLName) Less(i, j int) bool { return cmpXMLName(b[i], b[j]) } type byPropname []Property func (b byPropname) Len() int { return len(b) } func (b byPropname) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byPropname) Less(i, j int) bool { return cmpXMLName(b[i].XMLName, b[j].XMLName) } type byStatus []Propstat func (b byStatus) Len() int { return len(b) } func (b byStatus) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byStatus) Less(i, j int) bool { return b[i].Status < b[j].Status } type noDeadPropsFS struct { FileSystem } func (fs noDeadPropsFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) { f, err := fs.FileSystem.OpenFile(ctx, name, flag, perm) if err != nil { return nil, err } return noDeadPropsFile{f}, nil } // noDeadPropsFile wraps a File but strips any optional DeadPropsHolder methods // provided by the underlying File implementation. type noDeadPropsFile struct { f File } func (f noDeadPropsFile) Close() error { return f.f.Close() } func (f noDeadPropsFile) Read(p []byte) (int, error) { return f.f.Read(p) } func (f noDeadPropsFile) Readdir(count int) ([]os.FileInfo, error) { return f.f.Readdir(count) } func (f noDeadPropsFile) Seek(off int64, whence int) (int64, error) { return f.f.Seek(off, whence) } func (f noDeadPropsFile) Stat() (os.FileInfo, error) { return f.f.Stat() } func (f noDeadPropsFile) Write(p []byte) (int, error) { return f.f.Write(p) } lxd-2.0.11/dist/src/golang.org/x/net/webdav/prop.go0000644061062106075000000003172713172163402023104 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "bytes" "encoding/xml" "fmt" "io" "mime" "net/http" "os" "path/filepath" "strconv" "golang.org/x/net/context" ) // Proppatch describes a property update instruction as defined in RFC 4918. // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH type Proppatch struct { // Remove specifies whether this patch removes properties. If it does not // remove them, it sets them. Remove bool // Props contains the properties to be set or removed. Props []Property } // Propstat describes a XML propstat element as defined in RFC 4918. // See http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat type Propstat struct { // Props contains the properties for which Status applies. Props []Property // Status defines the HTTP status code of the properties in Prop. // Allowed values include, but are not limited to the WebDAV status // code extensions for HTTP/1.1. // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11 Status int // XMLError contains the XML representation of the optional error element. // XML content within this field must not rely on any predefined // namespace declarations or prefixes. If empty, the XML error element // is omitted. XMLError string // ResponseDescription contains the contents of the optional // responsedescription field. If empty, the XML element is omitted. ResponseDescription string } // makePropstats returns a slice containing those of x and y whose Props slice // is non-empty. If both are empty, it returns a slice containing an otherwise // zero Propstat whose HTTP status code is 200 OK. func makePropstats(x, y Propstat) []Propstat { pstats := make([]Propstat, 0, 2) if len(x.Props) != 0 { pstats = append(pstats, x) } if len(y.Props) != 0 { pstats = append(pstats, y) } if len(pstats) == 0 { pstats = append(pstats, Propstat{ Status: http.StatusOK, }) } return pstats } // DeadPropsHolder holds the dead properties of a resource. // // Dead properties are those properties that are explicitly defined. In // comparison, live properties, such as DAV:getcontentlength, are implicitly // defined by the underlying resource, and cannot be explicitly overridden or // removed. See the Terminology section of // http://www.webdav.org/specs/rfc4918.html#rfc.section.3 // // There is a whitelist of the names of live properties. This package handles // all live properties, and will only pass non-whitelisted names to the Patch // method of DeadPropsHolder implementations. type DeadPropsHolder interface { // DeadProps returns a copy of the dead properties held. DeadProps() (map[xml.Name]Property, error) // Patch patches the dead properties held. // // Patching is atomic; either all or no patches succeed. It returns (nil, // non-nil) if an internal server error occurred, otherwise the Propstats // collectively contain one Property for each proposed patch Property. If // all patches succeed, Patch returns a slice of length one and a Propstat // element with a 200 OK HTTP status code. If none succeed, for reasons // other than an internal server error, no Propstat has status 200 OK. // // For more details on when various HTTP status codes apply, see // http://www.webdav.org/specs/rfc4918.html#PROPPATCH-status Patch([]Proppatch) ([]Propstat, error) } // liveProps contains all supported, protected DAV: properties. var liveProps = map[xml.Name]struct { // findFn implements the propfind function of this property. If nil, // it indicates a hidden property. findFn func(context.Context, FileSystem, LockSystem, string, os.FileInfo) (string, error) // dir is true if the property applies to directories. dir bool }{ {Space: "DAV:", Local: "resourcetype"}: { findFn: findResourceType, dir: true, }, {Space: "DAV:", Local: "displayname"}: { findFn: findDisplayName, dir: true, }, {Space: "DAV:", Local: "getcontentlength"}: { findFn: findContentLength, dir: false, }, {Space: "DAV:", Local: "getlastmodified"}: { findFn: findLastModified, // http://webdav.org/specs/rfc4918.html#PROPERTY_getlastmodified // suggests that getlastmodified should only apply to GETable // resources, and this package does not support GET on directories. // // Nonetheless, some WebDAV clients expect child directories to be // sortable by getlastmodified date, so this value is true, not false. // See golang.org/issue/15334. dir: true, }, {Space: "DAV:", Local: "creationdate"}: { findFn: nil, dir: false, }, {Space: "DAV:", Local: "getcontentlanguage"}: { findFn: nil, dir: false, }, {Space: "DAV:", Local: "getcontenttype"}: { findFn: findContentType, dir: false, }, {Space: "DAV:", Local: "getetag"}: { findFn: findETag, // findETag implements ETag as the concatenated hex values of a file's // modification time and size. This is not a reliable synchronization // mechanism for directories, so we do not advertise getetag for DAV // collections. dir: false, }, // TODO: The lockdiscovery property requires LockSystem to list the // active locks on a resource. {Space: "DAV:", Local: "lockdiscovery"}: {}, {Space: "DAV:", Local: "supportedlock"}: { findFn: findSupportedLock, dir: true, }, } // TODO(nigeltao) merge props and allprop? // Props returns the status of the properties named pnames for resource name. // // Each Propstat has a unique status and each property name will only be part // of one Propstat element. func props(ctx context.Context, fs FileSystem, ls LockSystem, name string, pnames []xml.Name) ([]Propstat, error) { f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0) if err != nil { return nil, err } defer f.Close() fi, err := f.Stat() if err != nil { return nil, err } isDir := fi.IsDir() var deadProps map[xml.Name]Property if dph, ok := f.(DeadPropsHolder); ok { deadProps, err = dph.DeadProps() if err != nil { return nil, err } } pstatOK := Propstat{Status: http.StatusOK} pstatNotFound := Propstat{Status: http.StatusNotFound} for _, pn := range pnames { // If this file has dead properties, check if they contain pn. if dp, ok := deadProps[pn]; ok { pstatOK.Props = append(pstatOK.Props, dp) continue } // Otherwise, it must either be a live property or we don't know it. if prop := liveProps[pn]; prop.findFn != nil && (prop.dir || !isDir) { innerXML, err := prop.findFn(ctx, fs, ls, name, fi) if err != nil { return nil, err } pstatOK.Props = append(pstatOK.Props, Property{ XMLName: pn, InnerXML: []byte(innerXML), }) } else { pstatNotFound.Props = append(pstatNotFound.Props, Property{ XMLName: pn, }) } } return makePropstats(pstatOK, pstatNotFound), nil } // Propnames returns the property names defined for resource name. func propnames(ctx context.Context, fs FileSystem, ls LockSystem, name string) ([]xml.Name, error) { f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0) if err != nil { return nil, err } defer f.Close() fi, err := f.Stat() if err != nil { return nil, err } isDir := fi.IsDir() var deadProps map[xml.Name]Property if dph, ok := f.(DeadPropsHolder); ok { deadProps, err = dph.DeadProps() if err != nil { return nil, err } } pnames := make([]xml.Name, 0, len(liveProps)+len(deadProps)) for pn, prop := range liveProps { if prop.findFn != nil && (prop.dir || !isDir) { pnames = append(pnames, pn) } } for pn := range deadProps { pnames = append(pnames, pn) } return pnames, nil } // Allprop returns the properties defined for resource name and the properties // named in include. // // Note that RFC 4918 defines 'allprop' to return the DAV: properties defined // within the RFC plus dead properties. Other live properties should only be // returned if they are named in 'include'. // // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND func allprop(ctx context.Context, fs FileSystem, ls LockSystem, name string, include []xml.Name) ([]Propstat, error) { pnames, err := propnames(ctx, fs, ls, name) if err != nil { return nil, err } // Add names from include if they are not already covered in pnames. nameset := make(map[xml.Name]bool) for _, pn := range pnames { nameset[pn] = true } for _, pn := range include { if !nameset[pn] { pnames = append(pnames, pn) } } return props(ctx, fs, ls, name, pnames) } // Patch patches the properties of resource name. The return values are // constrained in the same manner as DeadPropsHolder.Patch. func patch(ctx context.Context, fs FileSystem, ls LockSystem, name string, patches []Proppatch) ([]Propstat, error) { conflict := false loop: for _, patch := range patches { for _, p := range patch.Props { if _, ok := liveProps[p.XMLName]; ok { conflict = true break loop } } } if conflict { pstatForbidden := Propstat{ Status: http.StatusForbidden, XMLError: ``, } pstatFailedDep := Propstat{ Status: StatusFailedDependency, } for _, patch := range patches { for _, p := range patch.Props { if _, ok := liveProps[p.XMLName]; ok { pstatForbidden.Props = append(pstatForbidden.Props, Property{XMLName: p.XMLName}) } else { pstatFailedDep.Props = append(pstatFailedDep.Props, Property{XMLName: p.XMLName}) } } } return makePropstats(pstatForbidden, pstatFailedDep), nil } f, err := fs.OpenFile(ctx, name, os.O_RDWR, 0) if err != nil { return nil, err } defer f.Close() if dph, ok := f.(DeadPropsHolder); ok { ret, err := dph.Patch(patches) if err != nil { return nil, err } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat says that // "The contents of the prop XML element must only list the names of // properties to which the result in the status element applies." for _, pstat := range ret { for i, p := range pstat.Props { pstat.Props[i] = Property{XMLName: p.XMLName} } } return ret, nil } // The file doesn't implement the optional DeadPropsHolder interface, so // all patches are forbidden. pstat := Propstat{Status: http.StatusForbidden} for _, patch := range patches { for _, p := range patch.Props { pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName}) } } return []Propstat{pstat}, nil } func escapeXML(s string) string { for i := 0; i < len(s); i++ { // As an optimization, if s contains only ASCII letters, digits or a // few special characters, the escaped value is s itself and we don't // need to allocate a buffer and convert between string and []byte. switch c := s[i]; { case c == ' ' || c == '_' || ('+' <= c && c <= '9') || // Digits as well as + , - . and / ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'): continue } // Otherwise, go through the full escaping process. var buf bytes.Buffer xml.EscapeText(&buf, []byte(s)) return buf.String() } return s } func findResourceType(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { if fi.IsDir() { return ``, nil } return "", nil } func findDisplayName(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { if slashClean(name) == "/" { // Hide the real name of a possibly prefixed root directory. return "", nil } return escapeXML(fi.Name()), nil } func findContentLength(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { return strconv.FormatInt(fi.Size(), 10), nil } func findLastModified(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { return fi.ModTime().Format(http.TimeFormat), nil } func findContentType(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0) if err != nil { return "", err } defer f.Close() // This implementation is based on serveContent's code in the standard net/http package. ctype := mime.TypeByExtension(filepath.Ext(name)) if ctype != "" { return ctype, nil } // Read a chunk to decide between utf-8 text and binary. var buf [512]byte n, err := io.ReadFull(f, buf[:]) if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { return "", err } ctype = http.DetectContentType(buf[:n]) // Rewind file. _, err = f.Seek(0, os.SEEK_SET) return ctype, err } func findETag(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { // The Apache http 2.4 web server by default concatenates the // modification time and size of a file. We replicate the heuristic // with nanosecond granularity. return fmt.Sprintf(`"%x%x"`, fi.ModTime().UnixNano(), fi.Size()), nil } func findSupportedLock(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { return `` + `` + `` + `` + ``, nil } lxd-2.0.11/dist/src/golang.org/x/net/webdav/lock_test.go0000644061062106075000000004327513172163402024114 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "fmt" "math/rand" "path" "reflect" "sort" "strconv" "strings" "testing" "time" ) func TestWalkToRoot(t *testing.T) { testCases := []struct { name string want []string }{{ "/a/b/c/d", []string{ "/a/b/c/d", "/a/b/c", "/a/b", "/a", "/", }, }, { "/a", []string{ "/a", "/", }, }, { "/", []string{ "/", }, }} for _, tc := range testCases { var got []string if !walkToRoot(tc.name, func(name0 string, first bool) bool { if first != (len(got) == 0) { t.Errorf("name=%q: first=%t but len(got)==%d", tc.name, first, len(got)) return false } got = append(got, name0) return true }) { continue } if !reflect.DeepEqual(got, tc.want) { t.Errorf("name=%q:\ngot %q\nwant %q", tc.name, got, tc.want) } } } var lockTestDurations = []time.Duration{ infiniteTimeout, // infiniteTimeout means to never expire. 0, // A zero duration means to expire immediately. 100 * time.Hour, // A very large duration will not expire in these tests. } // lockTestNames are the names of a set of mutually compatible locks. For each // name fragment: // - _ means no explicit lock. // - i means an infinite-depth lock, // - z means a zero-depth lock, var lockTestNames = []string{ "/_/_/_/_/z", "/_/_/i", "/_/z", "/_/z/i", "/_/z/z", "/_/z/_/i", "/_/z/_/z", "/i", "/z", "/z/_/i", "/z/_/z", } func lockTestZeroDepth(name string) bool { switch name[len(name)-1] { case 'i': return false case 'z': return true } panic(fmt.Sprintf("lock name %q did not end with 'i' or 'z'", name)) } func TestMemLSCanCreate(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) for _, name := range lockTestNames { _, err := m.Create(now, LockDetails{ Root: name, Duration: infiniteTimeout, ZeroDepth: lockTestZeroDepth(name), }) if err != nil { t.Fatalf("creating lock for %q: %v", name, err) } } wantCanCreate := func(name string, zeroDepth bool) bool { for _, n := range lockTestNames { switch { case n == name: // An existing lock has the same name as the proposed lock. return false case strings.HasPrefix(n, name): // An existing lock would be a child of the proposed lock, // which conflicts if the proposed lock has infinite depth. if !zeroDepth { return false } case strings.HasPrefix(name, n): // An existing lock would be an ancestor of the proposed lock, // which conflicts if the ancestor has infinite depth. if n[len(n)-1] == 'i' { return false } } } return true } var check func(int, string) check = func(recursion int, name string) { for _, zeroDepth := range []bool{false, true} { got := m.canCreate(name, zeroDepth) want := wantCanCreate(name, zeroDepth) if got != want { t.Errorf("canCreate name=%q zeroDepth=%t: got %t, want %t", name, zeroDepth, got, want) } } if recursion == 6 { return } if name != "/" { name += "/" } for _, c := range "_iz" { check(recursion+1, name+string(c)) } } check(0, "/") } func TestMemLSLookup(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) badToken := m.nextToken() t.Logf("badToken=%q", badToken) for _, name := range lockTestNames { token, err := m.Create(now, LockDetails{ Root: name, Duration: infiniteTimeout, ZeroDepth: lockTestZeroDepth(name), }) if err != nil { t.Fatalf("creating lock for %q: %v", name, err) } t.Logf("%-15q -> node=%p token=%q", name, m.byName[name], token) } baseNames := append([]string{"/a", "/b/c"}, lockTestNames...) for _, baseName := range baseNames { for _, suffix := range []string{"", "/0", "/1/2/3"} { name := baseName + suffix goodToken := "" base := m.byName[baseName] if base != nil && (suffix == "" || !lockTestZeroDepth(baseName)) { goodToken = base.token } for _, token := range []string{badToken, goodToken} { if token == "" { continue } got := m.lookup(name, Condition{Token: token}) want := base if token == badToken { want = nil } if got != want { t.Errorf("name=%-20qtoken=%q (bad=%t): got %p, want %p", name, token, token == badToken, got, want) } } } } } func TestMemLSConfirm(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) alice, err := m.Create(now, LockDetails{ Root: "/alice", Duration: infiniteTimeout, ZeroDepth: false, }) tweedle, err := m.Create(now, LockDetails{ Root: "/tweedle", Duration: infiniteTimeout, ZeroDepth: false, }) if err != nil { t.Fatalf("Create: %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Create: inconsistent state: %v", err) } // Test a mismatch between name and condition. _, err = m.Confirm(now, "/tweedle/dee", "", Condition{Token: alice}) if err != ErrConfirmationFailed { t.Fatalf("Confirm (mismatch): got %v, want ErrConfirmationFailed", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (mismatch): inconsistent state: %v", err) } // Test two names (that fall under the same lock) in the one Confirm call. release, err := m.Confirm(now, "/tweedle/dee", "/tweedle/dum", Condition{Token: tweedle}) if err != nil { t.Fatalf("Confirm (twins): %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (twins): inconsistent state: %v", err) } release() if err := m.consistent(); err != nil { t.Fatalf("release (twins): inconsistent state: %v", err) } // Test the same two names in overlapping Confirm / release calls. releaseDee, err := m.Confirm(now, "/tweedle/dee", "", Condition{Token: tweedle}) if err != nil { t.Fatalf("Confirm (sequence #0): %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (sequence #0): inconsistent state: %v", err) } _, err = m.Confirm(now, "/tweedle/dum", "", Condition{Token: tweedle}) if err != ErrConfirmationFailed { t.Fatalf("Confirm (sequence #1): got %v, want ErrConfirmationFailed", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (sequence #1): inconsistent state: %v", err) } releaseDee() if err := m.consistent(); err != nil { t.Fatalf("release (sequence #2): inconsistent state: %v", err) } releaseDum, err := m.Confirm(now, "/tweedle/dum", "", Condition{Token: tweedle}) if err != nil { t.Fatalf("Confirm (sequence #3): %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (sequence #3): inconsistent state: %v", err) } // Test that you can't unlock a held lock. err = m.Unlock(now, tweedle) if err != ErrLocked { t.Fatalf("Unlock (sequence #4): got %v, want ErrLocked", err) } releaseDum() if err := m.consistent(); err != nil { t.Fatalf("release (sequence #5): inconsistent state: %v", err) } err = m.Unlock(now, tweedle) if err != nil { t.Fatalf("Unlock (sequence #6): %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Unlock (sequence #6): inconsistent state: %v", err) } } func TestMemLSNonCanonicalRoot(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) token, err := m.Create(now, LockDetails{ Root: "/foo/./bar//", Duration: 1 * time.Second, }) if err != nil { t.Fatalf("Create: %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Create: inconsistent state: %v", err) } if err := m.Unlock(now, token); err != nil { t.Fatalf("Unlock: %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Unlock: inconsistent state: %v", err) } } func TestMemLSExpiry(t *testing.T) { m := NewMemLS().(*memLS) testCases := []string{ "setNow 0", "create /a.5", "want /a.5", "create /c.6", "want /a.5 /c.6", "create /a/b.7", "want /a.5 /a/b.7 /c.6", "setNow 4", "want /a.5 /a/b.7 /c.6", "setNow 5", "want /a/b.7 /c.6", "setNow 6", "want /a/b.7", "setNow 7", "want ", "setNow 8", "want ", "create /a.12", "create /b.13", "create /c.15", "create /a/d.16", "want /a.12 /a/d.16 /b.13 /c.15", "refresh /a.14", "want /a.14 /a/d.16 /b.13 /c.15", "setNow 12", "want /a.14 /a/d.16 /b.13 /c.15", "setNow 13", "want /a.14 /a/d.16 /c.15", "setNow 14", "want /a/d.16 /c.15", "refresh /a/d.20", "refresh /c.20", "want /a/d.20 /c.20", "setNow 20", "want ", } tokens := map[string]string{} zTime := time.Unix(0, 0) now := zTime for i, tc := range testCases { j := strings.IndexByte(tc, ' ') if j < 0 { t.Fatalf("test case #%d %q: invalid command", i, tc) } op, arg := tc[:j], tc[j+1:] switch op { default: t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) case "create", "refresh": parts := strings.Split(arg, ".") if len(parts) != 2 { t.Fatalf("test case #%d %q: invalid create", i, tc) } root := parts[0] d, err := strconv.Atoi(parts[1]) if err != nil { t.Fatalf("test case #%d %q: invalid duration", i, tc) } dur := time.Unix(0, 0).Add(time.Duration(d) * time.Second).Sub(now) switch op { case "create": token, err := m.Create(now, LockDetails{ Root: root, Duration: dur, ZeroDepth: true, }) if err != nil { t.Fatalf("test case #%d %q: Create: %v", i, tc, err) } tokens[root] = token case "refresh": token := tokens[root] if token == "" { t.Fatalf("test case #%d %q: no token for %q", i, tc, root) } got, err := m.Refresh(now, token, dur) if err != nil { t.Fatalf("test case #%d %q: Refresh: %v", i, tc, err) } want := LockDetails{ Root: root, Duration: dur, ZeroDepth: true, } if got != want { t.Fatalf("test case #%d %q:\ngot %v\nwant %v", i, tc, got, want) } } case "setNow": d, err := strconv.Atoi(arg) if err != nil { t.Fatalf("test case #%d %q: invalid duration", i, tc) } now = time.Unix(0, 0).Add(time.Duration(d) * time.Second) case "want": m.mu.Lock() m.collectExpiredNodes(now) got := make([]string, 0, len(m.byToken)) for _, n := range m.byToken { got = append(got, fmt.Sprintf("%s.%d", n.details.Root, n.expiry.Sub(zTime)/time.Second)) } m.mu.Unlock() sort.Strings(got) want := []string{} if arg != "" { want = strings.Split(arg, " ") } if !reflect.DeepEqual(got, want) { t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, want) } } if err := m.consistent(); err != nil { t.Fatalf("test case #%d %q: inconsistent state: %v", i, tc, err) } } } func TestMemLS(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) rng := rand.New(rand.NewSource(0)) tokens := map[string]string{} nConfirm, nCreate, nRefresh, nUnlock := 0, 0, 0, 0 const N = 2000 for i := 0; i < N; i++ { name := lockTestNames[rng.Intn(len(lockTestNames))] duration := lockTestDurations[rng.Intn(len(lockTestDurations))] confirmed, unlocked := false, false // If the name was already locked, we randomly confirm/release, refresh // or unlock it. Otherwise, we create a lock. token := tokens[name] if token != "" { switch rng.Intn(3) { case 0: confirmed = true nConfirm++ release, err := m.Confirm(now, name, "", Condition{Token: token}) if err != nil { t.Fatalf("iteration #%d: Confirm %q: %v", i, name, err) } if err := m.consistent(); err != nil { t.Fatalf("iteration #%d: inconsistent state: %v", i, err) } release() case 1: nRefresh++ if _, err := m.Refresh(now, token, duration); err != nil { t.Fatalf("iteration #%d: Refresh %q: %v", i, name, err) } case 2: unlocked = true nUnlock++ if err := m.Unlock(now, token); err != nil { t.Fatalf("iteration #%d: Unlock %q: %v", i, name, err) } } } else { nCreate++ var err error token, err = m.Create(now, LockDetails{ Root: name, Duration: duration, ZeroDepth: lockTestZeroDepth(name), }) if err != nil { t.Fatalf("iteration #%d: Create %q: %v", i, name, err) } } if !confirmed { if duration == 0 || unlocked { // A zero-duration lock should expire immediately and is // effectively equivalent to being unlocked. tokens[name] = "" } else { tokens[name] = token } } if err := m.consistent(); err != nil { t.Fatalf("iteration #%d: inconsistent state: %v", i, err) } } if nConfirm < N/10 { t.Fatalf("too few Confirm calls: got %d, want >= %d", nConfirm, N/10) } if nCreate < N/10 { t.Fatalf("too few Create calls: got %d, want >= %d", nCreate, N/10) } if nRefresh < N/10 { t.Fatalf("too few Refresh calls: got %d, want >= %d", nRefresh, N/10) } if nUnlock < N/10 { t.Fatalf("too few Unlock calls: got %d, want >= %d", nUnlock, N/10) } } func (m *memLS) consistent() error { m.mu.Lock() defer m.mu.Unlock() // If m.byName is non-empty, then it must contain an entry for the root "/", // and its refCount should equal the number of locked nodes. if len(m.byName) > 0 { n := m.byName["/"] if n == nil { return fmt.Errorf(`non-empty m.byName does not contain the root "/"`) } if n.refCount != len(m.byToken) { return fmt.Errorf("root node refCount=%d, differs from len(m.byToken)=%d", n.refCount, len(m.byToken)) } } for name, n := range m.byName { // The map keys should be consistent with the node's copy of the key. if n.details.Root != name { return fmt.Errorf("node name %q != byName map key %q", n.details.Root, name) } // A name must be clean, and start with a "/". if len(name) == 0 || name[0] != '/' { return fmt.Errorf(`node name %q does not start with "/"`, name) } if name != path.Clean(name) { return fmt.Errorf(`node name %q is not clean`, name) } // A node's refCount should be positive. if n.refCount <= 0 { return fmt.Errorf("non-positive refCount for node at name %q", name) } // A node's refCount should be the number of self-or-descendents that // are locked (i.e. have a non-empty token). var list []string for name0, n0 := range m.byName { // All of lockTestNames' name fragments are one byte long: '_', 'i' or 'z', // so strings.HasPrefix is equivalent to self-or-descendent name match. // We don't have to worry about "/foo/bar" being a false positive match // for "/foo/b". if strings.HasPrefix(name0, name) && n0.token != "" { list = append(list, name0) } } if n.refCount != len(list) { sort.Strings(list) return fmt.Errorf("node at name %q has refCount %d but locked self-or-descendents are %q (len=%d)", name, n.refCount, list, len(list)) } // A node n is in m.byToken if it has a non-empty token. if n.token != "" { if _, ok := m.byToken[n.token]; !ok { return fmt.Errorf("node at name %q has token %q but not in m.byToken", name, n.token) } } // A node n is in m.byExpiry if it has a non-negative byExpiryIndex. if n.byExpiryIndex >= 0 { if n.byExpiryIndex >= len(m.byExpiry) { return fmt.Errorf("node at name %q has byExpiryIndex %d but m.byExpiry has length %d", name, n.byExpiryIndex, len(m.byExpiry)) } if n != m.byExpiry[n.byExpiryIndex] { return fmt.Errorf("node at name %q has byExpiryIndex %d but that indexes a different node", name, n.byExpiryIndex) } } } for token, n := range m.byToken { // The map keys should be consistent with the node's copy of the key. if n.token != token { return fmt.Errorf("node token %q != byToken map key %q", n.token, token) } // Every node in m.byToken is in m.byName. if _, ok := m.byName[n.details.Root]; !ok { return fmt.Errorf("node at name %q in m.byToken but not in m.byName", n.details.Root) } } for i, n := range m.byExpiry { // The slice indices should be consistent with the node's copy of the index. if n.byExpiryIndex != i { return fmt.Errorf("node byExpiryIndex %d != byExpiry slice index %d", n.byExpiryIndex, i) } // Every node in m.byExpiry is in m.byName. if _, ok := m.byName[n.details.Root]; !ok { return fmt.Errorf("node at name %q in m.byExpiry but not in m.byName", n.details.Root) } // No node in m.byExpiry should be held. if n.held { return fmt.Errorf("node at name %q in m.byExpiry is held", n.details.Root) } } return nil } func TestParseTimeout(t *testing.T) { testCases := []struct { s string want time.Duration wantErr error }{{ "", infiniteTimeout, nil, }, { "Infinite", infiniteTimeout, nil, }, { "Infinitesimal", 0, errInvalidTimeout, }, { "infinite", 0, errInvalidTimeout, }, { "Second-0", 0 * time.Second, nil, }, { "Second-123", 123 * time.Second, nil, }, { " Second-456 ", 456 * time.Second, nil, }, { "Second-4100000000", 4100000000 * time.Second, nil, }, { "junk", 0, errInvalidTimeout, }, { "Second-", 0, errInvalidTimeout, }, { "Second--1", 0, errInvalidTimeout, }, { "Second--123", 0, errInvalidTimeout, }, { "Second-+123", 0, errInvalidTimeout, }, { "Second-0x123", 0, errInvalidTimeout, }, { "second-123", 0, errInvalidTimeout, }, { "Second-4294967295", 4294967295 * time.Second, nil, }, { // Section 10.7 says that "The timeout value for TimeType "Second" // must not be greater than 2^32-1." "Second-4294967296", 0, errInvalidTimeout, }, { // This test case comes from section 9.10.9 of the spec. It says, // // "In this request, the client has specified that it desires an // infinite-length lock, if available, otherwise a timeout of 4.1 // billion seconds, if available." // // The Go WebDAV package always supports infinite length locks, // and ignores the fallback after the comma. "Infinite, Second-4100000000", infiniteTimeout, nil, }} for _, tc := range testCases { got, gotErr := parseTimeout(tc.s) if got != tc.want || gotErr != tc.wantErr { t.Errorf("parsing %q:\ngot %v, %v\nwant %v, %v", tc.s, got, gotErr, tc.want, tc.wantErr) } } } lxd-2.0.11/dist/src/golang.org/x/net/webdav/lock.go0000644061062106075000000002752513172163402023055 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "container/heap" "errors" "strconv" "strings" "sync" "time" ) var ( // ErrConfirmationFailed is returned by a LockSystem's Confirm method. ErrConfirmationFailed = errors.New("webdav: confirmation failed") // ErrForbidden is returned by a LockSystem's Unlock method. ErrForbidden = errors.New("webdav: forbidden") // ErrLocked is returned by a LockSystem's Create, Refresh and Unlock methods. ErrLocked = errors.New("webdav: locked") // ErrNoSuchLock is returned by a LockSystem's Refresh and Unlock methods. ErrNoSuchLock = errors.New("webdav: no such lock") ) // Condition can match a WebDAV resource, based on a token or ETag. // Exactly one of Token and ETag should be non-empty. type Condition struct { Not bool Token string ETag string } // LockSystem manages access to a collection of named resources. The elements // in a lock name are separated by slash ('/', U+002F) characters, regardless // of host operating system convention. type LockSystem interface { // Confirm confirms that the caller can claim all of the locks specified by // the given conditions, and that holding the union of all of those locks // gives exclusive access to all of the named resources. Up to two resources // can be named. Empty names are ignored. // // Exactly one of release and err will be non-nil. If release is non-nil, // all of the requested locks are held until release is called. Calling // release does not unlock the lock, in the WebDAV UNLOCK sense, but once // Confirm has confirmed that a lock claim is valid, that lock cannot be // Confirmed again until it has been released. // // If Confirm returns ErrConfirmationFailed then the Handler will continue // to try any other set of locks presented (a WebDAV HTTP request can // present more than one set of locks). If it returns any other non-nil // error, the Handler will write a "500 Internal Server Error" HTTP status. Confirm(now time.Time, name0, name1 string, conditions ...Condition) (release func(), err error) // Create creates a lock with the given depth, duration, owner and root // (name). The depth will either be negative (meaning infinite) or zero. // // If Create returns ErrLocked then the Handler will write a "423 Locked" // HTTP status. If it returns any other non-nil error, the Handler will // write a "500 Internal Server Error" HTTP status. // // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.10.6 for // when to use each error. // // The token returned identifies the created lock. It should be an absolute // URI as defined by RFC 3986, Section 4.3. In particular, it should not // contain whitespace. Create(now time.Time, details LockDetails) (token string, err error) // Refresh refreshes the lock with the given token. // // If Refresh returns ErrLocked then the Handler will write a "423 Locked" // HTTP Status. If Refresh returns ErrNoSuchLock then the Handler will write // a "412 Precondition Failed" HTTP Status. If it returns any other non-nil // error, the Handler will write a "500 Internal Server Error" HTTP status. // // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.10.6 for // when to use each error. Refresh(now time.Time, token string, duration time.Duration) (LockDetails, error) // Unlock unlocks the lock with the given token. // // If Unlock returns ErrForbidden then the Handler will write a "403 // Forbidden" HTTP Status. If Unlock returns ErrLocked then the Handler // will write a "423 Locked" HTTP status. If Unlock returns ErrNoSuchLock // then the Handler will write a "409 Conflict" HTTP Status. If it returns // any other non-nil error, the Handler will write a "500 Internal Server // Error" HTTP status. // // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.11.1 for // when to use each error. Unlock(now time.Time, token string) error } // LockDetails are a lock's metadata. type LockDetails struct { // Root is the root resource name being locked. For a zero-depth lock, the // root is the only resource being locked. Root string // Duration is the lock timeout. A negative duration means infinite. Duration time.Duration // OwnerXML is the verbatim XML given in a LOCK HTTP request. // // TODO: does the "verbatim" nature play well with XML namespaces? // Does the OwnerXML field need to have more structure? See // https://codereview.appspot.com/175140043/#msg2 OwnerXML string // ZeroDepth is whether the lock has zero depth. If it does not have zero // depth, it has infinite depth. ZeroDepth bool } // NewMemLS returns a new in-memory LockSystem. func NewMemLS() LockSystem { return &memLS{ byName: make(map[string]*memLSNode), byToken: make(map[string]*memLSNode), gen: uint64(time.Now().Unix()), } } type memLS struct { mu sync.Mutex byName map[string]*memLSNode byToken map[string]*memLSNode gen uint64 // byExpiry only contains those nodes whose LockDetails have a finite // Duration and are yet to expire. byExpiry byExpiry } func (m *memLS) nextToken() string { m.gen++ return strconv.FormatUint(m.gen, 10) } func (m *memLS) collectExpiredNodes(now time.Time) { for len(m.byExpiry) > 0 { if now.Before(m.byExpiry[0].expiry) { break } m.remove(m.byExpiry[0]) } } func (m *memLS) Confirm(now time.Time, name0, name1 string, conditions ...Condition) (func(), error) { m.mu.Lock() defer m.mu.Unlock() m.collectExpiredNodes(now) var n0, n1 *memLSNode if name0 != "" { if n0 = m.lookup(slashClean(name0), conditions...); n0 == nil { return nil, ErrConfirmationFailed } } if name1 != "" { if n1 = m.lookup(slashClean(name1), conditions...); n1 == nil { return nil, ErrConfirmationFailed } } // Don't hold the same node twice. if n1 == n0 { n1 = nil } if n0 != nil { m.hold(n0) } if n1 != nil { m.hold(n1) } return func() { m.mu.Lock() defer m.mu.Unlock() if n1 != nil { m.unhold(n1) } if n0 != nil { m.unhold(n0) } }, nil } // lookup returns the node n that locks the named resource, provided that n // matches at least one of the given conditions and that lock isn't held by // another party. Otherwise, it returns nil. // // n may be a parent of the named resource, if n is an infinite depth lock. func (m *memLS) lookup(name string, conditions ...Condition) (n *memLSNode) { // TODO: support Condition.Not and Condition.ETag. for _, c := range conditions { n = m.byToken[c.Token] if n == nil || n.held { continue } if name == n.details.Root { return n } if n.details.ZeroDepth { continue } if n.details.Root == "/" || strings.HasPrefix(name, n.details.Root+"/") { return n } } return nil } func (m *memLS) hold(n *memLSNode) { if n.held { panic("webdav: memLS inconsistent held state") } n.held = true if n.details.Duration >= 0 && n.byExpiryIndex >= 0 { heap.Remove(&m.byExpiry, n.byExpiryIndex) } } func (m *memLS) unhold(n *memLSNode) { if !n.held { panic("webdav: memLS inconsistent held state") } n.held = false if n.details.Duration >= 0 { heap.Push(&m.byExpiry, n) } } func (m *memLS) Create(now time.Time, details LockDetails) (string, error) { m.mu.Lock() defer m.mu.Unlock() m.collectExpiredNodes(now) details.Root = slashClean(details.Root) if !m.canCreate(details.Root, details.ZeroDepth) { return "", ErrLocked } n := m.create(details.Root) n.token = m.nextToken() m.byToken[n.token] = n n.details = details if n.details.Duration >= 0 { n.expiry = now.Add(n.details.Duration) heap.Push(&m.byExpiry, n) } return n.token, nil } func (m *memLS) Refresh(now time.Time, token string, duration time.Duration) (LockDetails, error) { m.mu.Lock() defer m.mu.Unlock() m.collectExpiredNodes(now) n := m.byToken[token] if n == nil { return LockDetails{}, ErrNoSuchLock } if n.held { return LockDetails{}, ErrLocked } if n.byExpiryIndex >= 0 { heap.Remove(&m.byExpiry, n.byExpiryIndex) } n.details.Duration = duration if n.details.Duration >= 0 { n.expiry = now.Add(n.details.Duration) heap.Push(&m.byExpiry, n) } return n.details, nil } func (m *memLS) Unlock(now time.Time, token string) error { m.mu.Lock() defer m.mu.Unlock() m.collectExpiredNodes(now) n := m.byToken[token] if n == nil { return ErrNoSuchLock } if n.held { return ErrLocked } m.remove(n) return nil } func (m *memLS) canCreate(name string, zeroDepth bool) bool { return walkToRoot(name, func(name0 string, first bool) bool { n := m.byName[name0] if n == nil { return true } if first { if n.token != "" { // The target node is already locked. return false } if !zeroDepth { // The requested lock depth is infinite, and the fact that n exists // (n != nil) means that a descendent of the target node is locked. return false } } else if n.token != "" && !n.details.ZeroDepth { // An ancestor of the target node is locked with infinite depth. return false } return true }) } func (m *memLS) create(name string) (ret *memLSNode) { walkToRoot(name, func(name0 string, first bool) bool { n := m.byName[name0] if n == nil { n = &memLSNode{ details: LockDetails{ Root: name0, }, byExpiryIndex: -1, } m.byName[name0] = n } n.refCount++ if first { ret = n } return true }) return ret } func (m *memLS) remove(n *memLSNode) { delete(m.byToken, n.token) n.token = "" walkToRoot(n.details.Root, func(name0 string, first bool) bool { x := m.byName[name0] x.refCount-- if x.refCount == 0 { delete(m.byName, name0) } return true }) if n.byExpiryIndex >= 0 { heap.Remove(&m.byExpiry, n.byExpiryIndex) } } func walkToRoot(name string, f func(name0 string, first bool) bool) bool { for first := true; ; first = false { if !f(name, first) { return false } if name == "/" { break } name = name[:strings.LastIndex(name, "/")] if name == "" { name = "/" } } return true } type memLSNode struct { // details are the lock metadata. Even if this node's name is not explicitly locked, // details.Root will still equal the node's name. details LockDetails // token is the unique identifier for this node's lock. An empty token means that // this node is not explicitly locked. token string // refCount is the number of self-or-descendent nodes that are explicitly locked. refCount int // expiry is when this node's lock expires. expiry time.Time // byExpiryIndex is the index of this node in memLS.byExpiry. It is -1 // if this node does not expire, or has expired. byExpiryIndex int // held is whether this node's lock is actively held by a Confirm call. held bool } type byExpiry []*memLSNode func (b *byExpiry) Len() int { return len(*b) } func (b *byExpiry) Less(i, j int) bool { return (*b)[i].expiry.Before((*b)[j].expiry) } func (b *byExpiry) Swap(i, j int) { (*b)[i], (*b)[j] = (*b)[j], (*b)[i] (*b)[i].byExpiryIndex = i (*b)[j].byExpiryIndex = j } func (b *byExpiry) Push(x interface{}) { n := x.(*memLSNode) n.byExpiryIndex = len(*b) *b = append(*b, n) } func (b *byExpiry) Pop() interface{} { i := len(*b) - 1 n := (*b)[i] (*b)[i] = nil n.byExpiryIndex = -1 *b = (*b)[:i] return n } const infiniteTimeout = -1 // parseTimeout parses the Timeout HTTP header, as per section 10.7. If s is // empty, an infiniteTimeout is returned. func parseTimeout(s string) (time.Duration, error) { if s == "" { return infiniteTimeout, nil } if i := strings.IndexByte(s, ','); i >= 0 { s = s[:i] } s = strings.TrimSpace(s) if s == "Infinite" { return infiniteTimeout, nil } const pre = "Second-" if !strings.HasPrefix(s, pre) { return 0, errInvalidTimeout } s = s[len(pre):] if s == "" || s[0] < '0' || '9' < s[0] { return 0, errInvalidTimeout } n, err := strconv.ParseInt(s, 10, 64) if err != nil || 1<<32-1 < n { return 0, errInvalidTimeout } return time.Duration(n) * time.Second, nil } lxd-2.0.11/dist/src/golang.org/x/net/webdav/litmus_test_server.go0000644061062106075000000000534513172163402026063 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* This program is a server for the WebDAV 'litmus' compliance test at http://www.webdav.org/neon/litmus/ To run the test: go run litmus_test_server.go and separately, from the downloaded litmus-xxx directory: make URL=http://localhost:9999/ check */ package main import ( "flag" "fmt" "log" "net/http" "net/url" "golang.org/x/net/webdav" ) var port = flag.Int("port", 9999, "server port") func main() { flag.Parse() log.SetFlags(0) h := &webdav.Handler{ FileSystem: webdav.NewMemFS(), LockSystem: webdav.NewMemLS(), Logger: func(r *http.Request, err error) { litmus := r.Header.Get("X-Litmus") if len(litmus) > 19 { litmus = litmus[:16] + "..." } switch r.Method { case "COPY", "MOVE": dst := "" if u, err := url.Parse(r.Header.Get("Destination")); err == nil { dst = u.Path } o := r.Header.Get("Overwrite") log.Printf("%-20s%-10s%-30s%-30so=%-2s%v", litmus, r.Method, r.URL.Path, dst, o, err) default: log.Printf("%-20s%-10s%-30s%v", litmus, r.Method, r.URL.Path, err) } }, } // The next line would normally be: // http.Handle("/", h) // but we wrap that HTTP handler h to cater for a special case. // // The propfind_invalid2 litmus test case expects an empty namespace prefix // declaration to be an error. The FAQ in the webdav litmus test says: // // "What does the "propfind_invalid2" test check for?... // // If a request was sent with an XML body which included an empty namespace // prefix declaration (xmlns:ns1=""), then the server must reject that with // a "400 Bad Request" response, as it is invalid according to the XML // Namespace specification." // // On the other hand, the Go standard library's encoding/xml package // accepts an empty xmlns namespace, as per the discussion at // https://github.com/golang/go/issues/8068 // // Empty namespaces seem disallowed in the second (2006) edition of the XML // standard, but allowed in a later edition. The grammar differs between // http://www.w3.org/TR/2006/REC-xml-names-20060816/#ns-decl and // http://www.w3.org/TR/REC-xml-names/#dt-prefix // // Thus, we assume that the propfind_invalid2 test is obsolete, and // hard-code the 400 Bad Request response that the test expects. http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-Litmus") == "props: 3 (propfind_invalid2)" { http.Error(w, "400 Bad Request", http.StatusBadRequest) return } h.ServeHTTP(w, r) })) addr := fmt.Sprintf(":%d", *port) log.Printf("Serving %v", addr) log.Fatal(http.ListenAndServe(addr, nil)) } lxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/0000755061062106075000000000000013172163402023377 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/0000755061062106075000000000000013172163402024177 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/xml_test.go0000644061062106075000000004654013172163402026376 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xml import ( "bytes" "fmt" "io" "reflect" "strings" "testing" "unicode/utf8" ) const testInput = ` World <>'" 白鵬ç¿” &何; &is-it; ` var testEntity = map[string]string{"何": "What", "is-it": "is it?"} var rawTokens = []Token{ CharData("\n"), ProcInst{"xml", []byte(`version="1.0" encoding="UTF-8"`)}, CharData("\n"), Directive(`DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"`), CharData("\n"), StartElement{Name{"", "body"}, []Attr{{Name{"xmlns", "foo"}, "ns1"}, {Name{"", "xmlns"}, "ns2"}, {Name{"xmlns", "tag"}, "ns3"}}}, CharData("\n "), StartElement{Name{"", "hello"}, []Attr{{Name{"", "lang"}, "en"}}}, CharData("World <>'\" 白鵬翔"), EndElement{Name{"", "hello"}}, CharData("\n "), StartElement{Name{"", "query"}, []Attr{}}, CharData("What is it?"), EndElement{Name{"", "query"}}, CharData("\n "), StartElement{Name{"", "goodbye"}, []Attr{}}, EndElement{Name{"", "goodbye"}}, CharData("\n "), StartElement{Name{"", "outer"}, []Attr{{Name{"foo", "attr"}, "value"}, {Name{"xmlns", "tag"}, "ns4"}}}, CharData("\n "), StartElement{Name{"", "inner"}, []Attr{}}, EndElement{Name{"", "inner"}}, CharData("\n "), EndElement{Name{"", "outer"}}, CharData("\n "), StartElement{Name{"tag", "name"}, []Attr{}}, CharData("\n "), CharData("Some text here."), CharData("\n "), EndElement{Name{"tag", "name"}}, CharData("\n"), EndElement{Name{"", "body"}}, Comment(" missing final newline "), } var cookedTokens = []Token{ CharData("\n"), ProcInst{"xml", []byte(`version="1.0" encoding="UTF-8"`)}, CharData("\n"), Directive(`DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"`), CharData("\n"), StartElement{Name{"ns2", "body"}, []Attr{{Name{"xmlns", "foo"}, "ns1"}, {Name{"", "xmlns"}, "ns2"}, {Name{"xmlns", "tag"}, "ns3"}}}, CharData("\n "), StartElement{Name{"ns2", "hello"}, []Attr{{Name{"", "lang"}, "en"}}}, CharData("World <>'\" 白鵬翔"), EndElement{Name{"ns2", "hello"}}, CharData("\n "), StartElement{Name{"ns2", "query"}, []Attr{}}, CharData("What is it?"), EndElement{Name{"ns2", "query"}}, CharData("\n "), StartElement{Name{"ns2", "goodbye"}, []Attr{}}, EndElement{Name{"ns2", "goodbye"}}, CharData("\n "), StartElement{Name{"ns2", "outer"}, []Attr{{Name{"ns1", "attr"}, "value"}, {Name{"xmlns", "tag"}, "ns4"}}}, CharData("\n "), StartElement{Name{"ns2", "inner"}, []Attr{}}, EndElement{Name{"ns2", "inner"}}, CharData("\n "), EndElement{Name{"ns2", "outer"}}, CharData("\n "), StartElement{Name{"ns3", "name"}, []Attr{}}, CharData("\n "), CharData("Some text here."), CharData("\n "), EndElement{Name{"ns3", "name"}}, CharData("\n"), EndElement{Name{"ns2", "body"}}, Comment(" missing final newline "), } const testInputAltEncoding = ` VALUE` var rawTokensAltEncoding = []Token{ CharData("\n"), ProcInst{"xml", []byte(`version="1.0" encoding="x-testing-uppercase"`)}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("value"), EndElement{Name{"", "tag"}}, } var xmlInput = []string{ // unexpected EOF cases "<", "", "", "", // "", // let the Token() caller handle "", "", "", "", " c;", "", "", "", // "", // let the Token() caller handle "", "", "cdata]]>", } func TestRawToken(t *testing.T) { d := NewDecoder(strings.NewReader(testInput)) d.Entity = testEntity testRawToken(t, d, testInput, rawTokens) } const nonStrictInput = ` non&entity &unknown;entity { &#zzz; &ãªã¾ãˆ3; <-gt; &; &0a; ` var nonStringEntity = map[string]string{"": "oops!", "0a": "oops!"} var nonStrictTokens = []Token{ CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("non&entity"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&unknown;entity"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("{"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&#zzz;"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&ãªã¾ãˆ3;"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("<-gt;"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&;"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&0a;"), EndElement{Name{"", "tag"}}, CharData("\n"), } func TestNonStrictRawToken(t *testing.T) { d := NewDecoder(strings.NewReader(nonStrictInput)) d.Strict = false testRawToken(t, d, nonStrictInput, nonStrictTokens) } type downCaser struct { t *testing.T r io.ByteReader } func (d *downCaser) ReadByte() (c byte, err error) { c, err = d.r.ReadByte() if c >= 'A' && c <= 'Z' { c += 'a' - 'A' } return } func (d *downCaser) Read(p []byte) (int, error) { d.t.Fatalf("unexpected Read call on downCaser reader") panic("unreachable") } func TestRawTokenAltEncoding(t *testing.T) { d := NewDecoder(strings.NewReader(testInputAltEncoding)) d.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { if charset != "x-testing-uppercase" { t.Fatalf("unexpected charset %q", charset) } return &downCaser{t, input.(io.ByteReader)}, nil } testRawToken(t, d, testInputAltEncoding, rawTokensAltEncoding) } func TestRawTokenAltEncodingNoConverter(t *testing.T) { d := NewDecoder(strings.NewReader(testInputAltEncoding)) token, err := d.RawToken() if token == nil { t.Fatalf("expected a token on first RawToken call") } if err != nil { t.Fatal(err) } token, err = d.RawToken() if token != nil { t.Errorf("expected a nil token; got %#v", token) } if err == nil { t.Fatalf("expected an error on second RawToken call") } const encoding = "x-testing-uppercase" if !strings.Contains(err.Error(), encoding) { t.Errorf("expected error to contain %q; got error: %v", encoding, err) } } func testRawToken(t *testing.T, d *Decoder, raw string, rawTokens []Token) { lastEnd := int64(0) for i, want := range rawTokens { start := d.InputOffset() have, err := d.RawToken() end := d.InputOffset() if err != nil { t.Fatalf("token %d: unexpected error: %s", i, err) } if !reflect.DeepEqual(have, want) { var shave, swant string if _, ok := have.(CharData); ok { shave = fmt.Sprintf("CharData(%q)", have) } else { shave = fmt.Sprintf("%#v", have) } if _, ok := want.(CharData); ok { swant = fmt.Sprintf("CharData(%q)", want) } else { swant = fmt.Sprintf("%#v", want) } t.Errorf("token %d = %s, want %s", i, shave, swant) } // Check that InputOffset returned actual token. switch { case start < lastEnd: t.Errorf("token %d: position [%d,%d) for %T is before previous token", i, start, end, have) case start >= end: // Special case: EndElement can be synthesized. if start == end && end == lastEnd { break } t.Errorf("token %d: position [%d,%d) for %T is empty", i, start, end, have) case end > int64(len(raw)): t.Errorf("token %d: position [%d,%d) for %T extends beyond input", i, start, end, have) default: text := raw[start:end] if strings.ContainsAny(text, "<>") && (!strings.HasPrefix(text, "<") || !strings.HasSuffix(text, ">")) { t.Errorf("token %d: misaligned raw token %#q for %T", i, text, have) } } lastEnd = end } } // Ensure that directives (specifically !DOCTYPE) include the complete // text of any nested directives, noting that < and > do not change // nesting depth if they are in single or double quotes. var nestedDirectivesInput = ` ]> ">]> ]> '>]> ]> '>]> ]> ` var nestedDirectivesTokens = []Token{ CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE [">]`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE ['>]`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE ['>]`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), } func TestNestedDirectives(t *testing.T) { d := NewDecoder(strings.NewReader(nestedDirectivesInput)) for i, want := range nestedDirectivesTokens { have, err := d.Token() if err != nil { t.Fatalf("token %d: unexpected error: %s", i, err) } if !reflect.DeepEqual(have, want) { t.Errorf("token %d = %#v want %#v", i, have, want) } } } func TestToken(t *testing.T) { d := NewDecoder(strings.NewReader(testInput)) d.Entity = testEntity for i, want := range cookedTokens { have, err := d.Token() if err != nil { t.Fatalf("token %d: unexpected error: %s", i, err) } if !reflect.DeepEqual(have, want) { t.Errorf("token %d = %#v want %#v", i, have, want) } } } func TestSyntax(t *testing.T) { for i := range xmlInput { d := NewDecoder(strings.NewReader(xmlInput[i])) var err error for _, err = d.Token(); err == nil; _, err = d.Token() { } if _, ok := err.(*SyntaxError); !ok { t.Fatalf(`xmlInput "%s": expected SyntaxError not received`, xmlInput[i]) } } } type allScalars struct { True1 bool True2 bool False1 bool False2 bool Int int Int8 int8 Int16 int16 Int32 int32 Int64 int64 Uint int Uint8 uint8 Uint16 uint16 Uint32 uint32 Uint64 uint64 Uintptr uintptr Float32 float32 Float64 float64 String string PtrString *string } var all = allScalars{ True1: true, True2: true, False1: false, False2: false, Int: 1, Int8: -2, Int16: 3, Int32: -4, Int64: 5, Uint: 6, Uint8: 7, Uint16: 8, Uint32: 9, Uint64: 10, Uintptr: 11, Float32: 13.0, Float64: 14.0, String: "15", PtrString: &sixteen, } var sixteen = "16" const testScalarsInput = ` true 1 false 0 1 -2 3 -4 5 6 7 8 9 10 11 12.0 13.0 14.0 15 16 ` func TestAllScalars(t *testing.T) { var a allScalars err := Unmarshal([]byte(testScalarsInput), &a) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(a, all) { t.Errorf("have %+v want %+v", a, all) } } type item struct { Field_a string } func TestIssue569(t *testing.T) { data := `abcd` var i item err := Unmarshal([]byte(data), &i) if err != nil || i.Field_a != "abcd" { t.Fatal("Expecting abcd") } } func TestUnquotedAttrs(t *testing.T) { data := "" d := NewDecoder(strings.NewReader(data)) d.Strict = false token, err := d.Token() if _, ok := err.(*SyntaxError); ok { t.Errorf("Unexpected error: %v", err) } if token.(StartElement).Name.Local != "tag" { t.Errorf("Unexpected tag name: %v", token.(StartElement).Name.Local) } attr := token.(StartElement).Attr[0] if attr.Value != "azAZ09:-_" { t.Errorf("Unexpected attribute value: %v", attr.Value) } if attr.Name.Local != "attr" { t.Errorf("Unexpected attribute name: %v", attr.Name.Local) } } func TestValuelessAttrs(t *testing.T) { tests := [][3]string{ {"

", "p", "nowrap"}, {"

", "p", "nowrap"}, {"", "input", "checked"}, {"", "input", "checked"}, } for _, test := range tests { d := NewDecoder(strings.NewReader(test[0])) d.Strict = false token, err := d.Token() if _, ok := err.(*SyntaxError); ok { t.Errorf("Unexpected error: %v", err) } if token.(StartElement).Name.Local != test[1] { t.Errorf("Unexpected tag name: %v", token.(StartElement).Name.Local) } attr := token.(StartElement).Attr[0] if attr.Value != test[2] { t.Errorf("Unexpected attribute value: %v", attr.Value) } if attr.Name.Local != test[2] { t.Errorf("Unexpected attribute name: %v", attr.Name.Local) } } } func TestCopyTokenCharData(t *testing.T) { data := []byte("same data") var tok1 Token = CharData(data) tok2 := CopyToken(tok1) if !reflect.DeepEqual(tok1, tok2) { t.Error("CopyToken(CharData) != CharData") } data[1] = 'o' if reflect.DeepEqual(tok1, tok2) { t.Error("CopyToken(CharData) uses same buffer.") } } func TestCopyTokenStartElement(t *testing.T) { elt := StartElement{Name{"", "hello"}, []Attr{{Name{"", "lang"}, "en"}}} var tok1 Token = elt tok2 := CopyToken(tok1) if tok1.(StartElement).Attr[0].Value != "en" { t.Error("CopyToken overwrote Attr[0]") } if !reflect.DeepEqual(tok1, tok2) { t.Error("CopyToken(StartElement) != StartElement") } tok1.(StartElement).Attr[0] = Attr{Name{"", "lang"}, "de"} if reflect.DeepEqual(tok1, tok2) { t.Error("CopyToken(CharData) uses same buffer.") } } func TestSyntaxErrorLineNum(t *testing.T) { testInput := "

Foo

\n\n

Bar\n" d := NewDecoder(strings.NewReader(testInput)) var err error for _, err = d.Token(); err == nil; _, err = d.Token() { } synerr, ok := err.(*SyntaxError) if !ok { t.Error("Expected SyntaxError.") } if synerr.Line != 3 { t.Error("SyntaxError didn't have correct line number.") } } func TestTrailingRawToken(t *testing.T) { input := ` ` d := NewDecoder(strings.NewReader(input)) var err error for _, err = d.RawToken(); err == nil; _, err = d.RawToken() { } if err != io.EOF { t.Fatalf("d.RawToken() = _, %v, want _, io.EOF", err) } } func TestTrailingToken(t *testing.T) { input := ` ` d := NewDecoder(strings.NewReader(input)) var err error for _, err = d.Token(); err == nil; _, err = d.Token() { } if err != io.EOF { t.Fatalf("d.Token() = _, %v, want _, io.EOF", err) } } func TestEntityInsideCDATA(t *testing.T) { input := `` d := NewDecoder(strings.NewReader(input)) var err error for _, err = d.Token(); err == nil; _, err = d.Token() { } if err != io.EOF { t.Fatalf("d.Token() = _, %v, want _, io.EOF", err) } } var characterTests = []struct { in string err string }{ {"\x12", "illegal character code U+0012"}, {"\x0b", "illegal character code U+000B"}, {"\xef\xbf\xbe", "illegal character code U+FFFE"}, {"\r\n\x07", "illegal character code U+0007"}, {"what's up", "expected attribute name in element"}, {"&abc\x01;", "invalid character entity &abc (no semicolon)"}, {"&\x01;", "invalid character entity & (no semicolon)"}, {"&\xef\xbf\xbe;", "invalid character entity &\uFFFE;"}, {"&hello;", "invalid character entity &hello;"}, } func TestDisallowedCharacters(t *testing.T) { for i, tt := range characterTests { d := NewDecoder(strings.NewReader(tt.in)) var err error for err == nil { _, err = d.Token() } synerr, ok := err.(*SyntaxError) if !ok { t.Fatalf("input %d d.Token() = _, %v, want _, *SyntaxError", i, err) } if synerr.Msg != tt.err { t.Fatalf("input %d synerr.Msg wrong: want %q, got %q", i, tt.err, synerr.Msg) } } } type procInstEncodingTest struct { expect, got string } var procInstTests = []struct { input string expect [2]string }{ {`version="1.0" encoding="utf-8"`, [2]string{"1.0", "utf-8"}}, {`version="1.0" encoding='utf-8'`, [2]string{"1.0", "utf-8"}}, {`version="1.0" encoding='utf-8' `, [2]string{"1.0", "utf-8"}}, {`version="1.0" encoding=utf-8`, [2]string{"1.0", ""}}, {`encoding="FOO" `, [2]string{"", "FOO"}}, } func TestProcInstEncoding(t *testing.T) { for _, test := range procInstTests { if got := procInst("version", test.input); got != test.expect[0] { t.Errorf("procInst(version, %q) = %q; want %q", test.input, got, test.expect[0]) } if got := procInst("encoding", test.input); got != test.expect[1] { t.Errorf("procInst(encoding, %q) = %q; want %q", test.input, got, test.expect[1]) } } } // Ensure that directives with comments include the complete // text of any nested directives. var directivesWithCommentsInput = ` ]> ]> --> --> []> ` var directivesWithCommentsTokens = []Token{ CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), } func TestDirectivesWithComments(t *testing.T) { d := NewDecoder(strings.NewReader(directivesWithCommentsInput)) for i, want := range directivesWithCommentsTokens { have, err := d.Token() if err != nil { t.Fatalf("token %d: unexpected error: %s", i, err) } if !reflect.DeepEqual(have, want) { t.Errorf("token %d = %#v want %#v", i, have, want) } } } // Writer whose Write method always returns an error. type errWriter struct{} func (errWriter) Write(p []byte) (n int, err error) { return 0, fmt.Errorf("unwritable") } func TestEscapeTextIOErrors(t *testing.T) { expectErr := "unwritable" err := EscapeText(errWriter{}, []byte{'A'}) if err == nil || err.Error() != expectErr { t.Errorf("have %v, want %v", err, expectErr) } } func TestEscapeTextInvalidChar(t *testing.T) { input := []byte("A \x00 terminated string.") expected := "A \uFFFD terminated string." buff := new(bytes.Buffer) if err := EscapeText(buff, input); err != nil { t.Fatalf("have %v, want nil", err) } text := buff.String() if text != expected { t.Errorf("have %v, want %v", text, expected) } } func TestIssue5880(t *testing.T) { type T []byte data, err := Marshal(T{192, 168, 0, 1}) if err != nil { t.Errorf("Marshal error: %v", err) } if !utf8.Valid(data) { t.Errorf("Marshal generated invalid UTF-8: %x", data) } } lxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/xml.go0000644061062106075000000013172213172163402025334 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package xml implements a simple XML 1.0 parser that // understands XML name spaces. package xml // References: // Annotated XML spec: http://www.xml.com/axml/testaxml.htm // XML name spaces: http://www.w3.org/TR/REC-xml-names/ // TODO(rsc): // Test error handling. import ( "bufio" "bytes" "errors" "fmt" "io" "strconv" "strings" "unicode" "unicode/utf8" ) // A SyntaxError represents a syntax error in the XML input stream. type SyntaxError struct { Msg string Line int } func (e *SyntaxError) Error() string { return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg } // A Name represents an XML name (Local) annotated with a name space // identifier (Space). In tokens returned by Decoder.Token, the Space // identifier is given as a canonical URL, not the short prefix used in // the document being parsed. // // As a special case, XML namespace declarations will use the literal // string "xmlns" for the Space field instead of the fully resolved URL. // See Encoder.EncodeToken for more information on namespace encoding // behaviour. type Name struct { Space, Local string } // isNamespace reports whether the name is a namespace-defining name. func (name Name) isNamespace() bool { return name.Local == "xmlns" || name.Space == "xmlns" } // An Attr represents an attribute in an XML element (Name=Value). type Attr struct { Name Name Value string } // A Token is an interface holding one of the token types: // StartElement, EndElement, CharData, Comment, ProcInst, or Directive. type Token interface{} // A StartElement represents an XML start element. type StartElement struct { Name Name Attr []Attr } func (e StartElement) Copy() StartElement { attrs := make([]Attr, len(e.Attr)) copy(attrs, e.Attr) e.Attr = attrs return e } // End returns the corresponding XML end element. func (e StartElement) End() EndElement { return EndElement{e.Name} } // setDefaultNamespace sets the namespace of the element // as the default for all elements contained within it. func (e *StartElement) setDefaultNamespace() { if e.Name.Space == "" { // If there's no namespace on the element, don't // set the default. Strictly speaking this might be wrong, as // we can't tell if the element had no namespace set // or was just using the default namespace. return } // Don't add a default name space if there's already one set. for _, attr := range e.Attr { if attr.Name.Space == "" && attr.Name.Local == "xmlns" { return } } e.Attr = append(e.Attr, Attr{ Name: Name{ Local: "xmlns", }, Value: e.Name.Space, }) } // An EndElement represents an XML end element. type EndElement struct { Name Name } // A CharData represents XML character data (raw text), // in which XML escape sequences have been replaced by // the characters they represent. type CharData []byte func makeCopy(b []byte) []byte { b1 := make([]byte, len(b)) copy(b1, b) return b1 } func (c CharData) Copy() CharData { return CharData(makeCopy(c)) } // A Comment represents an XML comment of the form . // The bytes do not include the comment markers. type Comment []byte func (c Comment) Copy() Comment { return Comment(makeCopy(c)) } // A ProcInst represents an XML processing instruction of the form type ProcInst struct { Target string Inst []byte } func (p ProcInst) Copy() ProcInst { p.Inst = makeCopy(p.Inst) return p } // A Directive represents an XML directive of the form . // The bytes do not include the markers. type Directive []byte func (d Directive) Copy() Directive { return Directive(makeCopy(d)) } // CopyToken returns a copy of a Token. func CopyToken(t Token) Token { switch v := t.(type) { case CharData: return v.Copy() case Comment: return v.Copy() case Directive: return v.Copy() case ProcInst: return v.Copy() case StartElement: return v.Copy() } return t } // A Decoder represents an XML parser reading a particular input stream. // The parser assumes that its input is encoded in UTF-8. type Decoder struct { // Strict defaults to true, enforcing the requirements // of the XML specification. // If set to false, the parser allows input containing common // mistakes: // * If an element is missing an end tag, the parser invents // end tags as necessary to keep the return values from Token // properly balanced. // * In attribute values and character data, unknown or malformed // character entities (sequences beginning with &) are left alone. // // Setting: // // d.Strict = false; // d.AutoClose = HTMLAutoClose; // d.Entity = HTMLEntity // // creates a parser that can handle typical HTML. // // Strict mode does not enforce the requirements of the XML name spaces TR. // In particular it does not reject name space tags using undefined prefixes. // Such tags are recorded with the unknown prefix as the name space URL. Strict bool // When Strict == false, AutoClose indicates a set of elements to // consider closed immediately after they are opened, regardless // of whether an end element is present. AutoClose []string // Entity can be used to map non-standard entity names to string replacements. // The parser behaves as if these standard mappings are present in the map, // regardless of the actual map content: // // "lt": "<", // "gt": ">", // "amp": "&", // "apos": "'", // "quot": `"`, Entity map[string]string // CharsetReader, if non-nil, defines a function to generate // charset-conversion readers, converting from the provided // non-UTF-8 charset into UTF-8. If CharsetReader is nil or // returns an error, parsing stops with an error. One of the // the CharsetReader's result values must be non-nil. CharsetReader func(charset string, input io.Reader) (io.Reader, error) // DefaultSpace sets the default name space used for unadorned tags, // as if the entire XML stream were wrapped in an element containing // the attribute xmlns="DefaultSpace". DefaultSpace string r io.ByteReader buf bytes.Buffer saved *bytes.Buffer stk *stack free *stack needClose bool toClose Name nextToken Token nextByte int ns map[string]string err error line int offset int64 unmarshalDepth int } // NewDecoder creates a new XML parser reading from r. // If r does not implement io.ByteReader, NewDecoder will // do its own buffering. func NewDecoder(r io.Reader) *Decoder { d := &Decoder{ ns: make(map[string]string), nextByte: -1, line: 1, Strict: true, } d.switchToReader(r) return d } // Token returns the next XML token in the input stream. // At the end of the input stream, Token returns nil, io.EOF. // // Slices of bytes in the returned token data refer to the // parser's internal buffer and remain valid only until the next // call to Token. To acquire a copy of the bytes, call CopyToken // or the token's Copy method. // // Token expands self-closing elements such as
// into separate start and end elements returned by successive calls. // // Token guarantees that the StartElement and EndElement // tokens it returns are properly nested and matched: // if Token encounters an unexpected end element, // it will return an error. // // Token implements XML name spaces as described by // http://www.w3.org/TR/REC-xml-names/. Each of the // Name structures contained in the Token has the Space // set to the URL identifying its name space when known. // If Token encounters an unrecognized name space prefix, // it uses the prefix as the Space rather than report an error. func (d *Decoder) Token() (t Token, err error) { if d.stk != nil && d.stk.kind == stkEOF { err = io.EOF return } if d.nextToken != nil { t = d.nextToken d.nextToken = nil } else if t, err = d.rawToken(); err != nil { return } if !d.Strict { if t1, ok := d.autoClose(t); ok { d.nextToken = t t = t1 } } switch t1 := t.(type) { case StartElement: // In XML name spaces, the translations listed in the // attributes apply to the element name and // to the other attribute names, so process // the translations first. for _, a := range t1.Attr { if a.Name.Space == "xmlns" { v, ok := d.ns[a.Name.Local] d.pushNs(a.Name.Local, v, ok) d.ns[a.Name.Local] = a.Value } if a.Name.Space == "" && a.Name.Local == "xmlns" { // Default space for untagged names v, ok := d.ns[""] d.pushNs("", v, ok) d.ns[""] = a.Value } } d.translate(&t1.Name, true) for i := range t1.Attr { d.translate(&t1.Attr[i].Name, false) } d.pushElement(t1.Name) t = t1 case EndElement: d.translate(&t1.Name, true) if !d.popElement(&t1) { return nil, d.err } t = t1 } return } const xmlURL = "http://www.w3.org/XML/1998/namespace" // Apply name space translation to name n. // The default name space (for Space=="") // applies only to element names, not to attribute names. func (d *Decoder) translate(n *Name, isElementName bool) { switch { case n.Space == "xmlns": return case n.Space == "" && !isElementName: return case n.Space == "xml": n.Space = xmlURL case n.Space == "" && n.Local == "xmlns": return } if v, ok := d.ns[n.Space]; ok { n.Space = v } else if n.Space == "" { n.Space = d.DefaultSpace } } func (d *Decoder) switchToReader(r io.Reader) { // Get efficient byte at a time reader. // Assume that if reader has its own // ReadByte, it's efficient enough. // Otherwise, use bufio. if rb, ok := r.(io.ByteReader); ok { d.r = rb } else { d.r = bufio.NewReader(r) } } // Parsing state - stack holds old name space translations // and the current set of open elements. The translations to pop when // ending a given tag are *below* it on the stack, which is // more work but forced on us by XML. type stack struct { next *stack kind int name Name ok bool } const ( stkStart = iota stkNs stkEOF ) func (d *Decoder) push(kind int) *stack { s := d.free if s != nil { d.free = s.next } else { s = new(stack) } s.next = d.stk s.kind = kind d.stk = s return s } func (d *Decoder) pop() *stack { s := d.stk if s != nil { d.stk = s.next s.next = d.free d.free = s } return s } // Record that after the current element is finished // (that element is already pushed on the stack) // Token should return EOF until popEOF is called. func (d *Decoder) pushEOF() { // Walk down stack to find Start. // It might not be the top, because there might be stkNs // entries above it. start := d.stk for start.kind != stkStart { start = start.next } // The stkNs entries below a start are associated with that // element too; skip over them. for start.next != nil && start.next.kind == stkNs { start = start.next } s := d.free if s != nil { d.free = s.next } else { s = new(stack) } s.kind = stkEOF s.next = start.next start.next = s } // Undo a pushEOF. // The element must have been finished, so the EOF should be at the top of the stack. func (d *Decoder) popEOF() bool { if d.stk == nil || d.stk.kind != stkEOF { return false } d.pop() return true } // Record that we are starting an element with the given name. func (d *Decoder) pushElement(name Name) { s := d.push(stkStart) s.name = name } // Record that we are changing the value of ns[local]. // The old value is url, ok. func (d *Decoder) pushNs(local string, url string, ok bool) { s := d.push(stkNs) s.name.Local = local s.name.Space = url s.ok = ok } // Creates a SyntaxError with the current line number. func (d *Decoder) syntaxError(msg string) error { return &SyntaxError{Msg: msg, Line: d.line} } // Record that we are ending an element with the given name. // The name must match the record at the top of the stack, // which must be a pushElement record. // After popping the element, apply any undo records from // the stack to restore the name translations that existed // before we saw this element. func (d *Decoder) popElement(t *EndElement) bool { s := d.pop() name := t.Name switch { case s == nil || s.kind != stkStart: d.err = d.syntaxError("unexpected end element ") return false case s.name.Local != name.Local: if !d.Strict { d.needClose = true d.toClose = t.Name t.Name = s.name return true } d.err = d.syntaxError("element <" + s.name.Local + "> closed by ") return false case s.name.Space != name.Space: d.err = d.syntaxError("element <" + s.name.Local + "> in space " + s.name.Space + "closed by in space " + name.Space) return false } // Pop stack until a Start or EOF is on the top, undoing the // translations that were associated with the element we just closed. for d.stk != nil && d.stk.kind != stkStart && d.stk.kind != stkEOF { s := d.pop() if s.ok { d.ns[s.name.Local] = s.name.Space } else { delete(d.ns, s.name.Local) } } return true } // If the top element on the stack is autoclosing and // t is not the end tag, invent the end tag. func (d *Decoder) autoClose(t Token) (Token, bool) { if d.stk == nil || d.stk.kind != stkStart { return nil, false } name := strings.ToLower(d.stk.name.Local) for _, s := range d.AutoClose { if strings.ToLower(s) == name { // This one should be auto closed if t doesn't close it. et, ok := t.(EndElement) if !ok || et.Name.Local != name { return EndElement{d.stk.name}, true } break } } return nil, false } var errRawToken = errors.New("xml: cannot use RawToken from UnmarshalXML method") // RawToken is like Token but does not verify that // start and end elements match and does not translate // name space prefixes to their corresponding URLs. func (d *Decoder) RawToken() (Token, error) { if d.unmarshalDepth > 0 { return nil, errRawToken } return d.rawToken() } func (d *Decoder) rawToken() (Token, error) { if d.err != nil { return nil, d.err } if d.needClose { // The last element we read was self-closing and // we returned just the StartElement half. // Return the EndElement half now. d.needClose = false return EndElement{d.toClose}, nil } b, ok := d.getc() if !ok { return nil, d.err } if b != '<' { // Text section. d.ungetc(b) data := d.text(-1, false) if data == nil { return nil, d.err } return CharData(data), nil } if b, ok = d.mustgetc(); !ok { return nil, d.err } switch b { case '/': // ' { d.err = d.syntaxError("invalid characters between ") return nil, d.err } return EndElement{name}, nil case '?': // ' { break } b0 = b } data := d.buf.Bytes() data = data[0 : len(data)-2] // chop ?> if target == "xml" { content := string(data) ver := procInst("version", content) if ver != "" && ver != "1.0" { d.err = fmt.Errorf("xml: unsupported version %q; only version 1.0 is supported", ver) return nil, d.err } enc := procInst("encoding", content) if enc != "" && enc != "utf-8" && enc != "UTF-8" { if d.CharsetReader == nil { d.err = fmt.Errorf("xml: encoding %q declared but Decoder.CharsetReader is nil", enc) return nil, d.err } newr, err := d.CharsetReader(enc, d.r.(io.Reader)) if err != nil { d.err = fmt.Errorf("xml: opening charset %q: %v", enc, err) return nil, d.err } if newr == nil { panic("CharsetReader returned a nil Reader for charset " + enc) } d.switchToReader(newr) } } return ProcInst{target, data}, nil case '!': // ' { break } b0, b1 = b1, b } data := d.buf.Bytes() data = data[0 : len(data)-3] // chop --> return Comment(data), nil case '[': // . data := d.text(-1, true) if data == nil { return nil, d.err } return CharData(data), nil } // Probably a directive: , , etc. // We don't care, but accumulate for caller. Quoted angle // brackets do not count for nesting. d.buf.Reset() d.buf.WriteByte(b) inquote := uint8(0) depth := 0 for { if b, ok = d.mustgetc(); !ok { return nil, d.err } if inquote == 0 && b == '>' && depth == 0 { break } HandleB: d.buf.WriteByte(b) switch { case b == inquote: inquote = 0 case inquote != 0: // in quotes, no special action case b == '\'' || b == '"': inquote = b case b == '>' && inquote == 0: depth-- case b == '<' && inquote == 0: // Look for world howdy world ` var m MyStruct if err := Unmarshal([]byte(xml), &m); err != nil { t.Fatal(err) } if m.Data == nil || m.Attr == nil || m.Data.body != "hello world" || m.Attr.attr != "attr1" || m.Data2.body != "howdy world" || m.Attr2.attr != "attr2" { t.Errorf("m=%#+v\n", m) } } type Pea struct { Cotelydon string } type Pod struct { Pea interface{} `xml:"Pea"` } // https://golang.org/issue/6836 func TestUnmarshalIntoInterface(t *testing.T) { pod := new(Pod) pod.Pea = new(Pea) xml := `Green stuff` err := Unmarshal([]byte(xml), pod) if err != nil { t.Fatalf("failed to unmarshal %q: %v", xml, err) } pea, ok := pod.Pea.(*Pea) if !ok { t.Fatalf("unmarshalled into wrong type: have %T want *Pea", pod.Pea) } have, want := pea.Cotelydon, "Green stuff" if have != want { t.Errorf("failed to unmarshal into interface, have %q want %q", have, want) } } lxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/read.go0000644061062106075000000004746013172163402025454 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xml import ( "bytes" "encoding" "errors" "fmt" "reflect" "strconv" "strings" ) // BUG(rsc): Mapping between XML elements and data structures is inherently flawed: // an XML element is an order-dependent collection of anonymous // values, while a data structure is an order-independent collection // of named values. // See package json for a textual representation more suitable // to data structures. // Unmarshal parses the XML-encoded data and stores the result in // the value pointed to by v, which must be an arbitrary struct, // slice, or string. Well-formed data that does not fit into v is // discarded. // // Because Unmarshal uses the reflect package, it can only assign // to exported (upper case) fields. Unmarshal uses a case-sensitive // comparison to match XML element names to tag values and struct // field names. // // Unmarshal maps an XML element to a struct using the following rules. // In the rules, the tag of a field refers to the value associated with the // key 'xml' in the struct field's tag (see the example above). // // * If the struct has a field of type []byte or string with tag // ",innerxml", Unmarshal accumulates the raw XML nested inside the // element in that field. The rest of the rules still apply. // // * If the struct has a field named XMLName of type xml.Name, // Unmarshal records the element name in that field. // // * If the XMLName field has an associated tag of the form // "name" or "namespace-URL name", the XML element must have // the given name (and, optionally, name space) or else Unmarshal // returns an error. // // * If the XML element has an attribute whose name matches a // struct field name with an associated tag containing ",attr" or // the explicit name in a struct field tag of the form "name,attr", // Unmarshal records the attribute value in that field. // // * If the XML element contains character data, that data is // accumulated in the first struct field that has tag ",chardata". // The struct field may have type []byte or string. // If there is no such field, the character data is discarded. // // * If the XML element contains comments, they are accumulated in // the first struct field that has tag ",comment". The struct // field may have type []byte or string. If there is no such // field, the comments are discarded. // // * If the XML element contains a sub-element whose name matches // the prefix of a tag formatted as "a" or "a>b>c", unmarshal // will descend into the XML structure looking for elements with the // given names, and will map the innermost elements to that struct // field. A tag starting with ">" is equivalent to one starting // with the field name followed by ">". // // * If the XML element contains a sub-element whose name matches // a struct field's XMLName tag and the struct field has no // explicit name tag as per the previous rule, unmarshal maps // the sub-element to that struct field. // // * If the XML element contains a sub-element whose name matches a // field without any mode flags (",attr", ",chardata", etc), Unmarshal // maps the sub-element to that struct field. // // * If the XML element contains a sub-element that hasn't matched any // of the above rules and the struct has a field with tag ",any", // unmarshal maps the sub-element to that struct field. // // * An anonymous struct field is handled as if the fields of its // value were part of the outer struct. // // * A struct field with tag "-" is never unmarshalled into. // // Unmarshal maps an XML element to a string or []byte by saving the // concatenation of that element's character data in the string or // []byte. The saved []byte is never nil. // // Unmarshal maps an attribute value to a string or []byte by saving // the value in the string or slice. // // Unmarshal maps an XML element to a slice by extending the length of // the slice and mapping the element to the newly created value. // // Unmarshal maps an XML element or attribute value to a bool by // setting it to the boolean value represented by the string. // // Unmarshal maps an XML element or attribute value to an integer or // floating-point field by setting the field to the result of // interpreting the string value in decimal. There is no check for // overflow. // // Unmarshal maps an XML element to an xml.Name by recording the // element name. // // Unmarshal maps an XML element to a pointer by setting the pointer // to a freshly allocated value and then mapping the element to that value. // func Unmarshal(data []byte, v interface{}) error { return NewDecoder(bytes.NewReader(data)).Decode(v) } // Decode works like xml.Unmarshal, except it reads the decoder // stream to find the start element. func (d *Decoder) Decode(v interface{}) error { return d.DecodeElement(v, nil) } // DecodeElement works like xml.Unmarshal except that it takes // a pointer to the start XML element to decode into v. // It is useful when a client reads some raw XML tokens itself // but also wants to defer to Unmarshal for some elements. func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error { val := reflect.ValueOf(v) if val.Kind() != reflect.Ptr { return errors.New("non-pointer passed to Unmarshal") } return d.unmarshal(val.Elem(), start) } // An UnmarshalError represents an error in the unmarshalling process. type UnmarshalError string func (e UnmarshalError) Error() string { return string(e) } // Unmarshaler is the interface implemented by objects that can unmarshal // an XML element description of themselves. // // UnmarshalXML decodes a single XML element // beginning with the given start element. // If it returns an error, the outer call to Unmarshal stops and // returns that error. // UnmarshalXML must consume exactly one XML element. // One common implementation strategy is to unmarshal into // a separate value with a layout matching the expected XML // using d.DecodeElement, and then to copy the data from // that value into the receiver. // Another common strategy is to use d.Token to process the // XML object one token at a time. // UnmarshalXML may not use d.RawToken. type Unmarshaler interface { UnmarshalXML(d *Decoder, start StartElement) error } // UnmarshalerAttr is the interface implemented by objects that can unmarshal // an XML attribute description of themselves. // // UnmarshalXMLAttr decodes a single XML attribute. // If it returns an error, the outer call to Unmarshal stops and // returns that error. // UnmarshalXMLAttr is used only for struct fields with the // "attr" option in the field tag. type UnmarshalerAttr interface { UnmarshalXMLAttr(attr Attr) error } // receiverType returns the receiver type to use in an expression like "%s.MethodName". func receiverType(val interface{}) string { t := reflect.TypeOf(val) if t.Name() != "" { return t.String() } return "(" + t.String() + ")" } // unmarshalInterface unmarshals a single XML element into val. // start is the opening tag of the element. func (p *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error { // Record that decoder must stop at end tag corresponding to start. p.pushEOF() p.unmarshalDepth++ err := val.UnmarshalXML(p, *start) p.unmarshalDepth-- if err != nil { p.popEOF() return err } if !p.popEOF() { return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local) } return nil } // unmarshalTextInterface unmarshals a single XML element into val. // The chardata contained in the element (but not its children) // is passed to the text unmarshaler. func (p *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler, start *StartElement) error { var buf []byte depth := 1 for depth > 0 { t, err := p.Token() if err != nil { return err } switch t := t.(type) { case CharData: if depth == 1 { buf = append(buf, t...) } case StartElement: depth++ case EndElement: depth-- } } return val.UnmarshalText(buf) } // unmarshalAttr unmarshals a single XML attribute into val. func (p *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error { if val.Kind() == reflect.Ptr { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } val = val.Elem() } if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) { // This is an unmarshaler with a non-pointer receiver, // so it's likely to be incorrect, but we do what we're told. return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) { return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr) } } // Not an UnmarshalerAttr; try encoding.TextUnmarshaler. if val.CanInterface() && val.Type().Implements(textUnmarshalerType) { // This is an unmarshaler with a non-pointer receiver, // so it's likely to be incorrect, but we do what we're told. return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value)) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value)) } } copyValue(val, []byte(attr.Value)) return nil } var ( unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem() textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() ) // Unmarshal a single XML element into val. func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error { // Find start element if we need it. if start == nil { for { tok, err := p.Token() if err != nil { return err } if t, ok := tok.(StartElement); ok { start = &t break } } } // Load value from interface, but only if the result will be // usefully addressable. if val.Kind() == reflect.Interface && !val.IsNil() { e := val.Elem() if e.Kind() == reflect.Ptr && !e.IsNil() { val = e } } if val.Kind() == reflect.Ptr { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } val = val.Elem() } if val.CanInterface() && val.Type().Implements(unmarshalerType) { // This is an unmarshaler with a non-pointer receiver, // so it's likely to be incorrect, but we do what we're told. return p.unmarshalInterface(val.Interface().(Unmarshaler), start) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(unmarshalerType) { return p.unmarshalInterface(pv.Interface().(Unmarshaler), start) } } if val.CanInterface() && val.Type().Implements(textUnmarshalerType) { return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler), start) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler), start) } } var ( data []byte saveData reflect.Value comment []byte saveComment reflect.Value saveXML reflect.Value saveXMLIndex int saveXMLData []byte saveAny reflect.Value sv reflect.Value tinfo *typeInfo err error ) switch v := val; v.Kind() { default: return errors.New("unknown type " + v.Type().String()) case reflect.Interface: // TODO: For now, simply ignore the field. In the near // future we may choose to unmarshal the start // element on it, if not nil. return p.Skip() case reflect.Slice: typ := v.Type() if typ.Elem().Kind() == reflect.Uint8 { // []byte saveData = v break } // Slice of element values. // Grow slice. n := v.Len() if n >= v.Cap() { ncap := 2 * n if ncap < 4 { ncap = 4 } new := reflect.MakeSlice(typ, n, ncap) reflect.Copy(new, v) v.Set(new) } v.SetLen(n + 1) // Recur to read element into slice. if err := p.unmarshal(v.Index(n), start); err != nil { v.SetLen(n) return err } return nil case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.String: saveData = v case reflect.Struct: typ := v.Type() if typ == nameType { v.Set(reflect.ValueOf(start.Name)) break } sv = v tinfo, err = getTypeInfo(typ) if err != nil { return err } // Validate and assign element name. if tinfo.xmlname != nil { finfo := tinfo.xmlname if finfo.name != "" && finfo.name != start.Name.Local { return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">") } if finfo.xmlns != "" && finfo.xmlns != start.Name.Space { e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have " if start.Name.Space == "" { e += "no name space" } else { e += start.Name.Space } return UnmarshalError(e) } fv := finfo.value(sv) if _, ok := fv.Interface().(Name); ok { fv.Set(reflect.ValueOf(start.Name)) } } // Assign attributes. // Also, determine whether we need to save character data or comments. for i := range tinfo.fields { finfo := &tinfo.fields[i] switch finfo.flags & fMode { case fAttr: strv := finfo.value(sv) // Look for attribute. for _, a := range start.Attr { if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) { if err := p.unmarshalAttr(strv, a); err != nil { return err } break } } case fCharData: if !saveData.IsValid() { saveData = finfo.value(sv) } case fComment: if !saveComment.IsValid() { saveComment = finfo.value(sv) } case fAny, fAny | fElement: if !saveAny.IsValid() { saveAny = finfo.value(sv) } case fInnerXml: if !saveXML.IsValid() { saveXML = finfo.value(sv) if p.saved == nil { saveXMLIndex = 0 p.saved = new(bytes.Buffer) } else { saveXMLIndex = p.savedOffset() } } } } } // Find end element. // Process sub-elements along the way. Loop: for { var savedOffset int if saveXML.IsValid() { savedOffset = p.savedOffset() } tok, err := p.Token() if err != nil { return err } switch t := tok.(type) { case StartElement: consumed := false if sv.IsValid() { consumed, err = p.unmarshalPath(tinfo, sv, nil, &t) if err != nil { return err } if !consumed && saveAny.IsValid() { consumed = true if err := p.unmarshal(saveAny, &t); err != nil { return err } } } if !consumed { if err := p.Skip(); err != nil { return err } } case EndElement: if saveXML.IsValid() { saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset] if saveXMLIndex == 0 { p.saved = nil } } break Loop case CharData: if saveData.IsValid() { data = append(data, t...) } case Comment: if saveComment.IsValid() { comment = append(comment, t...) } } } if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) { if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { return err } saveData = reflect.Value{} } if saveData.IsValid() && saveData.CanAddr() { pv := saveData.Addr() if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { return err } saveData = reflect.Value{} } } if err := copyValue(saveData, data); err != nil { return err } switch t := saveComment; t.Kind() { case reflect.String: t.SetString(string(comment)) case reflect.Slice: t.Set(reflect.ValueOf(comment)) } switch t := saveXML; t.Kind() { case reflect.String: t.SetString(string(saveXMLData)) case reflect.Slice: t.Set(reflect.ValueOf(saveXMLData)) } return nil } func copyValue(dst reflect.Value, src []byte) (err error) { dst0 := dst if dst.Kind() == reflect.Ptr { if dst.IsNil() { dst.Set(reflect.New(dst.Type().Elem())) } dst = dst.Elem() } // Save accumulated data. switch dst.Kind() { case reflect.Invalid: // Probably a comment. default: return errors.New("cannot unmarshal into " + dst0.Type().String()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits()) if err != nil { return err } dst.SetInt(itmp) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: utmp, err := strconv.ParseUint(string(src), 10, dst.Type().Bits()) if err != nil { return err } dst.SetUint(utmp) case reflect.Float32, reflect.Float64: ftmp, err := strconv.ParseFloat(string(src), dst.Type().Bits()) if err != nil { return err } dst.SetFloat(ftmp) case reflect.Bool: value, err := strconv.ParseBool(strings.TrimSpace(string(src))) if err != nil { return err } dst.SetBool(value) case reflect.String: dst.SetString(string(src)) case reflect.Slice: if len(src) == 0 { // non-nil to flag presence src = []byte{} } dst.SetBytes(src) } return nil } // unmarshalPath walks down an XML structure looking for wanted // paths, and calls unmarshal on them. // The consumed result tells whether XML elements have been consumed // from the Decoder until start's matching end element, or if it's // still untouched because start is uninteresting for sv's fields. func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) { recurse := false Loop: for i := range tinfo.fields { finfo := &tinfo.fields[i] if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space { continue } for j := range parents { if parents[j] != finfo.parents[j] { continue Loop } } if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local { // It's a perfect match, unmarshal the field. return true, p.unmarshal(finfo.value(sv), start) } if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local { // It's a prefix for the field. Break and recurse // since it's not ok for one field path to be itself // the prefix for another field path. recurse = true // We can reuse the same slice as long as we // don't try to append to it. parents = finfo.parents[:len(parents)+1] break } } if !recurse { // We have no business with this element. return false, nil } // The element is not a perfect match for any field, but one // or more fields have the path to this element as a parent // prefix. Recurse and attempt to match these. for { var tok Token tok, err = p.Token() if err != nil { return true, err } switch t := tok.(type) { case StartElement: consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t) if err != nil { return true, err } if !consumed2 { if err := p.Skip(); err != nil { return true, err } } case EndElement: return true, nil } } } // Skip reads tokens until it has consumed the end element // matching the most recent start element already consumed. // It recurs if it encounters a start element, so it can be used to // skip nested structures. // It returns nil if it finds an end element matching the start // element; otherwise it returns an error describing the problem. func (d *Decoder) Skip() error { for { tok, err := d.Token() if err != nil { return err } switch tok.(type) { case StartElement: if err := d.Skip(); err != nil { return err } case EndElement: return nil } } } lxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/marshal_test.go0000644061062106075000000013743313172163402027227 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xml import ( "bytes" "errors" "fmt" "io" "reflect" "strconv" "strings" "sync" "testing" "time" ) type DriveType int const ( HyperDrive DriveType = iota ImprobabilityDrive ) type Passenger struct { Name []string `xml:"name"` Weight float32 `xml:"weight"` } type Ship struct { XMLName struct{} `xml:"spaceship"` Name string `xml:"name,attr"` Pilot string `xml:"pilot,attr"` Drive DriveType `xml:"drive"` Age uint `xml:"age"` Passenger []*Passenger `xml:"passenger"` secret string } type NamedType string type Port struct { XMLName struct{} `xml:"port"` Type string `xml:"type,attr,omitempty"` Comment string `xml:",comment"` Number string `xml:",chardata"` } type Domain struct { XMLName struct{} `xml:"domain"` Country string `xml:",attr,omitempty"` Name []byte `xml:",chardata"` Comment []byte `xml:",comment"` } type Book struct { XMLName struct{} `xml:"book"` Title string `xml:",chardata"` } type Event struct { XMLName struct{} `xml:"event"` Year int `xml:",chardata"` } type Movie struct { XMLName struct{} `xml:"movie"` Length uint `xml:",chardata"` } type Pi struct { XMLName struct{} `xml:"pi"` Approximation float32 `xml:",chardata"` } type Universe struct { XMLName struct{} `xml:"universe"` Visible float64 `xml:",chardata"` } type Particle struct { XMLName struct{} `xml:"particle"` HasMass bool `xml:",chardata"` } type Departure struct { XMLName struct{} `xml:"departure"` When time.Time `xml:",chardata"` } type SecretAgent struct { XMLName struct{} `xml:"agent"` Handle string `xml:"handle,attr"` Identity string Obfuscate string `xml:",innerxml"` } type NestedItems struct { XMLName struct{} `xml:"result"` Items []string `xml:">item"` Item1 []string `xml:"Items>item1"` } type NestedOrder struct { XMLName struct{} `xml:"result"` Field1 string `xml:"parent>c"` Field2 string `xml:"parent>b"` Field3 string `xml:"parent>a"` } type MixedNested struct { XMLName struct{} `xml:"result"` A string `xml:"parent1>a"` B string `xml:"b"` C string `xml:"parent1>parent2>c"` D string `xml:"parent1>d"` } type NilTest struct { A interface{} `xml:"parent1>parent2>a"` B interface{} `xml:"parent1>b"` C interface{} `xml:"parent1>parent2>c"` } type Service struct { XMLName struct{} `xml:"service"` Domain *Domain `xml:"host>domain"` Port *Port `xml:"host>port"` Extra1 interface{} Extra2 interface{} `xml:"host>extra2"` } var nilStruct *Ship type EmbedA struct { EmbedC EmbedB EmbedB FieldA string } type EmbedB struct { FieldB string *EmbedC } type EmbedC struct { FieldA1 string `xml:"FieldA>A1"` FieldA2 string `xml:"FieldA>A2"` FieldB string FieldC string } type NameCasing struct { XMLName struct{} `xml:"casing"` Xy string XY string XyA string `xml:"Xy,attr"` XYA string `xml:"XY,attr"` } type NamePrecedence struct { XMLName Name `xml:"Parent"` FromTag XMLNameWithoutTag `xml:"InTag"` FromNameVal XMLNameWithoutTag FromNameTag XMLNameWithTag InFieldName string } type XMLNameWithTag struct { XMLName Name `xml:"InXMLNameTag"` Value string `xml:",chardata"` } type XMLNameWithNSTag struct { XMLName Name `xml:"ns InXMLNameWithNSTag"` Value string `xml:",chardata"` } type XMLNameWithoutTag struct { XMLName Name Value string `xml:",chardata"` } type NameInField struct { Foo Name `xml:"ns foo"` } type AttrTest struct { Int int `xml:",attr"` Named int `xml:"int,attr"` Float float64 `xml:",attr"` Uint8 uint8 `xml:",attr"` Bool bool `xml:",attr"` Str string `xml:",attr"` Bytes []byte `xml:",attr"` } type OmitAttrTest struct { Int int `xml:",attr,omitempty"` Named int `xml:"int,attr,omitempty"` Float float64 `xml:",attr,omitempty"` Uint8 uint8 `xml:",attr,omitempty"` Bool bool `xml:",attr,omitempty"` Str string `xml:",attr,omitempty"` Bytes []byte `xml:",attr,omitempty"` } type OmitFieldTest struct { Int int `xml:",omitempty"` Named int `xml:"int,omitempty"` Float float64 `xml:",omitempty"` Uint8 uint8 `xml:",omitempty"` Bool bool `xml:",omitempty"` Str string `xml:",omitempty"` Bytes []byte `xml:",omitempty"` Ptr *PresenceTest `xml:",omitempty"` } type AnyTest struct { XMLName struct{} `xml:"a"` Nested string `xml:"nested>value"` AnyField AnyHolder `xml:",any"` } type AnyOmitTest struct { XMLName struct{} `xml:"a"` Nested string `xml:"nested>value"` AnyField *AnyHolder `xml:",any,omitempty"` } type AnySliceTest struct { XMLName struct{} `xml:"a"` Nested string `xml:"nested>value"` AnyField []AnyHolder `xml:",any"` } type AnyHolder struct { XMLName Name XML string `xml:",innerxml"` } type RecurseA struct { A string B *RecurseB } type RecurseB struct { A *RecurseA B string } type PresenceTest struct { Exists *struct{} } type IgnoreTest struct { PublicSecret string `xml:"-"` } type MyBytes []byte type Data struct { Bytes []byte Attr []byte `xml:",attr"` Custom MyBytes } type Plain struct { V interface{} } type MyInt int type EmbedInt struct { MyInt } type Strings struct { X []string `xml:"A>B,omitempty"` } type PointerFieldsTest struct { XMLName Name `xml:"dummy"` Name *string `xml:"name,attr"` Age *uint `xml:"age,attr"` Empty *string `xml:"empty,attr"` Contents *string `xml:",chardata"` } type ChardataEmptyTest struct { XMLName Name `xml:"test"` Contents *string `xml:",chardata"` } type MyMarshalerTest struct { } var _ Marshaler = (*MyMarshalerTest)(nil) func (m *MyMarshalerTest) MarshalXML(e *Encoder, start StartElement) error { e.EncodeToken(start) e.EncodeToken(CharData([]byte("hello world"))) e.EncodeToken(EndElement{start.Name}) return nil } type MyMarshalerAttrTest struct{} var _ MarshalerAttr = (*MyMarshalerAttrTest)(nil) func (m *MyMarshalerAttrTest) MarshalXMLAttr(name Name) (Attr, error) { return Attr{name, "hello world"}, nil } type MyMarshalerValueAttrTest struct{} var _ MarshalerAttr = MyMarshalerValueAttrTest{} func (m MyMarshalerValueAttrTest) MarshalXMLAttr(name Name) (Attr, error) { return Attr{name, "hello world"}, nil } type MarshalerStruct struct { Foo MyMarshalerAttrTest `xml:",attr"` } type MarshalerValueStruct struct { Foo MyMarshalerValueAttrTest `xml:",attr"` } type InnerStruct struct { XMLName Name `xml:"testns outer"` } type OuterStruct struct { InnerStruct IntAttr int `xml:"int,attr"` } type OuterNamedStruct struct { InnerStruct XMLName Name `xml:"outerns test"` IntAttr int `xml:"int,attr"` } type OuterNamedOrderedStruct struct { XMLName Name `xml:"outerns test"` InnerStruct IntAttr int `xml:"int,attr"` } type OuterOuterStruct struct { OuterStruct } type NestedAndChardata struct { AB []string `xml:"A>B"` Chardata string `xml:",chardata"` } type NestedAndComment struct { AB []string `xml:"A>B"` Comment string `xml:",comment"` } type XMLNSFieldStruct struct { Ns string `xml:"xmlns,attr"` Body string } type NamedXMLNSFieldStruct struct { XMLName struct{} `xml:"testns test"` Ns string `xml:"xmlns,attr"` Body string } type XMLNSFieldStructWithOmitEmpty struct { Ns string `xml:"xmlns,attr,omitempty"` Body string } type NamedXMLNSFieldStructWithEmptyNamespace struct { XMLName struct{} `xml:"test"` Ns string `xml:"xmlns,attr"` Body string } type RecursiveXMLNSFieldStruct struct { Ns string `xml:"xmlns,attr"` Body *RecursiveXMLNSFieldStruct `xml:",omitempty"` Text string `xml:",omitempty"` } func ifaceptr(x interface{}) interface{} { return &x } var ( nameAttr = "Sarah" ageAttr = uint(12) contentsAttr = "lorem ipsum" ) // Unless explicitly stated as such (or *Plain), all of the // tests below are two-way tests. When introducing new tests, // please try to make them two-way as well to ensure that // marshalling and unmarshalling are as symmetrical as feasible. var marshalTests = []struct { Value interface{} ExpectXML string MarshalOnly bool UnmarshalOnly bool }{ // Test nil marshals to nothing {Value: nil, ExpectXML: ``, MarshalOnly: true}, {Value: nilStruct, ExpectXML: ``, MarshalOnly: true}, // Test value types {Value: &Plain{true}, ExpectXML: `true`}, {Value: &Plain{false}, ExpectXML: `false`}, {Value: &Plain{int(42)}, ExpectXML: `42`}, {Value: &Plain{int8(42)}, ExpectXML: `42`}, {Value: &Plain{int16(42)}, ExpectXML: `42`}, {Value: &Plain{int32(42)}, ExpectXML: `42`}, {Value: &Plain{uint(42)}, ExpectXML: `42`}, {Value: &Plain{uint8(42)}, ExpectXML: `42`}, {Value: &Plain{uint16(42)}, ExpectXML: `42`}, {Value: &Plain{uint32(42)}, ExpectXML: `42`}, {Value: &Plain{float32(1.25)}, ExpectXML: `1.25`}, {Value: &Plain{float64(1.25)}, ExpectXML: `1.25`}, {Value: &Plain{uintptr(0xFFDD)}, ExpectXML: `65501`}, {Value: &Plain{"gopher"}, ExpectXML: `gopher`}, {Value: &Plain{[]byte("gopher")}, ExpectXML: `gopher`}, {Value: &Plain{""}, ExpectXML: `</>`}, {Value: &Plain{[]byte("")}, ExpectXML: `</>`}, {Value: &Plain{[3]byte{'<', '/', '>'}}, ExpectXML: `</>`}, {Value: &Plain{NamedType("potato")}, ExpectXML: `potato`}, {Value: &Plain{[]int{1, 2, 3}}, ExpectXML: `123`}, {Value: &Plain{[3]int{1, 2, 3}}, ExpectXML: `123`}, {Value: ifaceptr(true), MarshalOnly: true, ExpectXML: `true`}, // Test time. { Value: &Plain{time.Unix(1e9, 123456789).UTC()}, ExpectXML: `2001-09-09T01:46:40.123456789Z`, }, // A pointer to struct{} may be used to test for an element's presence. { Value: &PresenceTest{new(struct{})}, ExpectXML: ``, }, { Value: &PresenceTest{}, ExpectXML: ``, }, // A pointer to struct{} may be used to test for an element's presence. { Value: &PresenceTest{new(struct{})}, ExpectXML: ``, }, { Value: &PresenceTest{}, ExpectXML: ``, }, // A []byte field is only nil if the element was not found. { Value: &Data{}, ExpectXML: ``, UnmarshalOnly: true, }, { Value: &Data{Bytes: []byte{}, Custom: MyBytes{}, Attr: []byte{}}, ExpectXML: ``, UnmarshalOnly: true, }, // Check that []byte works, including named []byte types. { Value: &Data{Bytes: []byte("ab"), Custom: MyBytes("cd"), Attr: []byte{'v'}}, ExpectXML: `abcd`, }, // Test innerxml { Value: &SecretAgent{ Handle: "007", Identity: "James Bond", Obfuscate: "", }, ExpectXML: `James Bond`, MarshalOnly: true, }, { Value: &SecretAgent{ Handle: "007", Identity: "James Bond", Obfuscate: "James Bond", }, ExpectXML: `James Bond`, UnmarshalOnly: true, }, // Test structs {Value: &Port{Type: "ssl", Number: "443"}, ExpectXML: `443`}, {Value: &Port{Number: "443"}, ExpectXML: `443`}, {Value: &Port{Type: ""}, ExpectXML: ``}, {Value: &Port{Number: "443", Comment: "https"}, ExpectXML: `443`}, {Value: &Port{Number: "443", Comment: "add space-"}, ExpectXML: `443`, MarshalOnly: true}, {Value: &Domain{Name: []byte("google.com&friends")}, ExpectXML: `google.com&friends`}, {Value: &Domain{Name: []byte("google.com"), Comment: []byte(" &friends ")}, ExpectXML: `google.com`}, {Value: &Book{Title: "Pride & Prejudice"}, ExpectXML: `Pride & Prejudice`}, {Value: &Event{Year: -3114}, ExpectXML: `-3114`}, {Value: &Movie{Length: 13440}, ExpectXML: `13440`}, {Value: &Pi{Approximation: 3.14159265}, ExpectXML: `3.1415927`}, {Value: &Universe{Visible: 9.3e13}, ExpectXML: `9.3e+13`}, {Value: &Particle{HasMass: true}, ExpectXML: `true`}, {Value: &Departure{When: ParseTime("2013-01-09T00:15:00-09:00")}, ExpectXML: `2013-01-09T00:15:00-09:00`}, {Value: atomValue, ExpectXML: atomXml}, { Value: &Ship{ Name: "Heart of Gold", Pilot: "Computer", Age: 1, Drive: ImprobabilityDrive, Passenger: []*Passenger{ { Name: []string{"Zaphod", "Beeblebrox"}, Weight: 7.25, }, { Name: []string{"Trisha", "McMillen"}, Weight: 5.5, }, { Name: []string{"Ford", "Prefect"}, Weight: 7, }, { Name: []string{"Arthur", "Dent"}, Weight: 6.75, }, }, }, ExpectXML: `` + `` + strconv.Itoa(int(ImprobabilityDrive)) + `` + `1` + `` + `Zaphod` + `Beeblebrox` + `7.25` + `` + `` + `Trisha` + `McMillen` + `5.5` + `` + `` + `Ford` + `Prefect` + `7` + `` + `` + `Arthur` + `Dent` + `6.75` + `` + ``, }, // Test a>b { Value: &NestedItems{Items: nil, Item1: nil}, ExpectXML: `` + `` + `` + ``, }, { Value: &NestedItems{Items: []string{}, Item1: []string{}}, ExpectXML: `` + `` + `` + ``, MarshalOnly: true, }, { Value: &NestedItems{Items: nil, Item1: []string{"A"}}, ExpectXML: `` + `` + `A` + `` + ``, }, { Value: &NestedItems{Items: []string{"A", "B"}, Item1: nil}, ExpectXML: `` + `` + `A` + `B` + `` + ``, }, { Value: &NestedItems{Items: []string{"A", "B"}, Item1: []string{"C"}}, ExpectXML: `` + `` + `A` + `B` + `C` + `` + ``, }, { Value: &NestedOrder{Field1: "C", Field2: "B", Field3: "A"}, ExpectXML: `` + `` + `C` + `B` + `A` + `` + ``, }, { Value: &NilTest{A: "A", B: nil, C: "C"}, ExpectXML: `` + `` + `A` + `C` + `` + ``, MarshalOnly: true, // Uses interface{} }, { Value: &MixedNested{A: "A", B: "B", C: "C", D: "D"}, ExpectXML: `` + `A` + `B` + `` + `C` + `D` + `` + ``, }, { Value: &Service{Port: &Port{Number: "80"}}, ExpectXML: `80`, }, { Value: &Service{}, ExpectXML: ``, }, { Value: &Service{Port: &Port{Number: "80"}, Extra1: "A", Extra2: "B"}, ExpectXML: `` + `80` + `A` + `B` + ``, MarshalOnly: true, }, { Value: &Service{Port: &Port{Number: "80"}, Extra2: "example"}, ExpectXML: `` + `80` + `example` + ``, MarshalOnly: true, }, { Value: &struct { XMLName struct{} `xml:"space top"` A string `xml:"x>a"` B string `xml:"x>b"` C string `xml:"space x>c"` C1 string `xml:"space1 x>c"` D1 string `xml:"space1 x>d"` E1 string `xml:"x>e"` }{ A: "a", B: "b", C: "c", C1: "c1", D1: "d1", E1: "e1", }, ExpectXML: `` + `abc` + `` + `c1` + `d1` + `` + `` + `e1` + `` + ``, }, { Value: &struct { XMLName Name A string `xml:"x>a"` B string `xml:"x>b"` C string `xml:"space x>c"` C1 string `xml:"space1 x>c"` D1 string `xml:"space1 x>d"` }{ XMLName: Name{ Space: "space0", Local: "top", }, A: "a", B: "b", C: "c", C1: "c1", D1: "d1", }, ExpectXML: `` + `ab` + `c` + `` + `c1` + `d1` + `` + ``, }, { Value: &struct { XMLName struct{} `xml:"top"` B string `xml:"space x>b"` B1 string `xml:"space1 x>b"` }{ B: "b", B1: "b1", }, ExpectXML: `` + `b` + `b1` + ``, }, // Test struct embedding { Value: &EmbedA{ EmbedC: EmbedC{ FieldA1: "", // Shadowed by A.A FieldA2: "", // Shadowed by A.A FieldB: "A.C.B", FieldC: "A.C.C", }, EmbedB: EmbedB{ FieldB: "A.B.B", EmbedC: &EmbedC{ FieldA1: "A.B.C.A1", FieldA2: "A.B.C.A2", FieldB: "", // Shadowed by A.B.B FieldC: "A.B.C.C", }, }, FieldA: "A.A", }, ExpectXML: `` + `A.C.B` + `A.C.C` + `` + `A.B.B` + `` + `A.B.C.A1` + `A.B.C.A2` + `` + `A.B.C.C` + `` + `A.A` + ``, }, // Test that name casing matters { Value: &NameCasing{Xy: "mixed", XY: "upper", XyA: "mixedA", XYA: "upperA"}, ExpectXML: `mixedupper`, }, // Test the order in which the XML element name is chosen { Value: &NamePrecedence{ FromTag: XMLNameWithoutTag{Value: "A"}, FromNameVal: XMLNameWithoutTag{XMLName: Name{Local: "InXMLName"}, Value: "B"}, FromNameTag: XMLNameWithTag{Value: "C"}, InFieldName: "D", }, ExpectXML: `` + `A` + `B` + `C` + `D` + ``, MarshalOnly: true, }, { Value: &NamePrecedence{ XMLName: Name{Local: "Parent"}, FromTag: XMLNameWithoutTag{XMLName: Name{Local: "InTag"}, Value: "A"}, FromNameVal: XMLNameWithoutTag{XMLName: Name{Local: "FromNameVal"}, Value: "B"}, FromNameTag: XMLNameWithTag{XMLName: Name{Local: "InXMLNameTag"}, Value: "C"}, InFieldName: "D", }, ExpectXML: `` + `A` + `B` + `C` + `D` + ``, UnmarshalOnly: true, }, // xml.Name works in a plain field as well. { Value: &NameInField{Name{Space: "ns", Local: "foo"}}, ExpectXML: ``, }, { Value: &NameInField{Name{Space: "ns", Local: "foo"}}, ExpectXML: ``, UnmarshalOnly: true, }, // Marshaling zero xml.Name uses the tag or field name. { Value: &NameInField{}, ExpectXML: ``, MarshalOnly: true, }, // Test attributes { Value: &AttrTest{ Int: 8, Named: 9, Float: 23.5, Uint8: 255, Bool: true, Str: "str", Bytes: []byte("byt"), }, ExpectXML: ``, }, { Value: &AttrTest{Bytes: []byte{}}, ExpectXML: ``, }, { Value: &OmitAttrTest{ Int: 8, Named: 9, Float: 23.5, Uint8: 255, Bool: true, Str: "str", Bytes: []byte("byt"), }, ExpectXML: ``, }, { Value: &OmitAttrTest{}, ExpectXML: ``, }, // pointer fields { Value: &PointerFieldsTest{Name: &nameAttr, Age: &ageAttr, Contents: &contentsAttr}, ExpectXML: `lorem ipsum`, MarshalOnly: true, }, // empty chardata pointer field { Value: &ChardataEmptyTest{}, ExpectXML: ``, MarshalOnly: true, }, // omitempty on fields { Value: &OmitFieldTest{ Int: 8, Named: 9, Float: 23.5, Uint8: 255, Bool: true, Str: "str", Bytes: []byte("byt"), Ptr: &PresenceTest{}, }, ExpectXML: `` + `8` + `9` + `23.5` + `255` + `true` + `str` + `byt` + `` + ``, }, { Value: &OmitFieldTest{}, ExpectXML: ``, }, // Test ",any" { ExpectXML: `knownunknown`, Value: &AnyTest{ Nested: "known", AnyField: AnyHolder{ XMLName: Name{Local: "other"}, XML: "unknown", }, }, }, { Value: &AnyTest{Nested: "known", AnyField: AnyHolder{ XML: "", XMLName: Name{Local: "AnyField"}, }, }, ExpectXML: `known`, }, { ExpectXML: `b`, Value: &AnyOmitTest{ Nested: "b", }, }, { ExpectXML: `bei`, Value: &AnySliceTest{ Nested: "b", AnyField: []AnyHolder{ { XMLName: Name{Local: "c"}, XML: "e", }, { XMLName: Name{Space: "f", Local: "g"}, XML: "i", }, }, }, }, { ExpectXML: `b`, Value: &AnySliceTest{ Nested: "b", }, }, // Test recursive types. { Value: &RecurseA{ A: "a1", B: &RecurseB{ A: &RecurseA{"a2", nil}, B: "b1", }, }, ExpectXML: `a1a2b1`, }, // Test ignoring fields via "-" tag { ExpectXML: ``, Value: &IgnoreTest{}, }, { ExpectXML: ``, Value: &IgnoreTest{PublicSecret: "can't tell"}, MarshalOnly: true, }, { ExpectXML: `ignore me`, Value: &IgnoreTest{}, UnmarshalOnly: true, }, // Test escaping. { ExpectXML: `dquote: "; squote: '; ampersand: &; less: <; greater: >;`, Value: &AnyTest{ Nested: `dquote: "; squote: '; ampersand: &; less: <; greater: >;`, AnyField: AnyHolder{XMLName: Name{Local: "empty"}}, }, }, { ExpectXML: `newline: ; cr: ; tab: ;`, Value: &AnyTest{ Nested: "newline: \n; cr: \r; tab: \t;", AnyField: AnyHolder{XMLName: Name{Local: "AnyField"}}, }, }, { ExpectXML: "1\r2\r\n3\n\r4\n5", Value: &AnyTest{ Nested: "1\n2\n3\n\n4\n5", }, UnmarshalOnly: true, }, { ExpectXML: `42`, Value: &EmbedInt{ MyInt: 42, }, }, // Test omitempty with parent chain; see golang.org/issue/4168. { ExpectXML: ``, Value: &Strings{}, }, // Custom marshalers. { ExpectXML: `hello world`, Value: &MyMarshalerTest{}, }, { ExpectXML: ``, Value: &MarshalerStruct{}, }, { ExpectXML: ``, Value: &MarshalerValueStruct{}, }, { ExpectXML: ``, Value: &OuterStruct{IntAttr: 10}, }, { ExpectXML: ``, Value: &OuterNamedStruct{XMLName: Name{Space: "outerns", Local: "test"}, IntAttr: 10}, }, { ExpectXML: ``, Value: &OuterNamedOrderedStruct{XMLName: Name{Space: "outerns", Local: "test"}, IntAttr: 10}, }, { ExpectXML: ``, Value: &OuterOuterStruct{OuterStruct{IntAttr: 10}}, }, { ExpectXML: `test`, Value: &NestedAndChardata{AB: make([]string, 2), Chardata: "test"}, }, { ExpectXML: ``, Value: &NestedAndComment{AB: make([]string, 2), Comment: "test"}, }, { ExpectXML: `hello world`, Value: &XMLNSFieldStruct{Ns: "http://example.com/ns", Body: "hello world"}, }, { ExpectXML: `hello world`, Value: &NamedXMLNSFieldStruct{Ns: "http://example.com/ns", Body: "hello world"}, }, { ExpectXML: `hello world`, Value: &NamedXMLNSFieldStruct{Ns: "", Body: "hello world"}, }, { ExpectXML: `hello world`, Value: &XMLNSFieldStructWithOmitEmpty{Body: "hello world"}, }, { // The xmlns attribute must be ignored because the // element is in the empty namespace, so it's not possible // to set the default namespace to something non-empty. ExpectXML: `hello world`, Value: &NamedXMLNSFieldStructWithEmptyNamespace{Ns: "foo", Body: "hello world"}, MarshalOnly: true, }, { ExpectXML: `hello world`, Value: &RecursiveXMLNSFieldStruct{ Ns: "foo", Body: &RecursiveXMLNSFieldStruct{ Text: "hello world", }, }, }, } func TestMarshal(t *testing.T) { for idx, test := range marshalTests { if test.UnmarshalOnly { continue } data, err := Marshal(test.Value) if err != nil { t.Errorf("#%d: marshal(%#v): %s", idx, test.Value, err) continue } if got, want := string(data), test.ExpectXML; got != want { if strings.Contains(want, "\n") { t.Errorf("#%d: marshal(%#v):\nHAVE:\n%s\nWANT:\n%s", idx, test.Value, got, want) } else { t.Errorf("#%d: marshal(%#v):\nhave %#q\nwant %#q", idx, test.Value, got, want) } } } } type AttrParent struct { X string `xml:"X>Y,attr"` } type BadAttr struct { Name []string `xml:"name,attr"` } var marshalErrorTests = []struct { Value interface{} Err string Kind reflect.Kind }{ { Value: make(chan bool), Err: "xml: unsupported type: chan bool", Kind: reflect.Chan, }, { Value: map[string]string{ "question": "What do you get when you multiply six by nine?", "answer": "42", }, Err: "xml: unsupported type: map[string]string", Kind: reflect.Map, }, { Value: map[*Ship]bool{nil: false}, Err: "xml: unsupported type: map[*xml.Ship]bool", Kind: reflect.Map, }, { Value: &Domain{Comment: []byte("f--bar")}, Err: `xml: comments must not contain "--"`, }, // Reject parent chain with attr, never worked; see golang.org/issue/5033. { Value: &AttrParent{}, Err: `xml: X>Y chain not valid with attr flag`, }, { Value: BadAttr{[]string{"X", "Y"}}, Err: `xml: unsupported type: []string`, }, } var marshalIndentTests = []struct { Value interface{} Prefix string Indent string ExpectXML string }{ { Value: &SecretAgent{ Handle: "007", Identity: "James Bond", Obfuscate: "", }, Prefix: "", Indent: "\t", ExpectXML: fmt.Sprintf("\n\tJames Bond\n"), }, } func TestMarshalErrors(t *testing.T) { for idx, test := range marshalErrorTests { data, err := Marshal(test.Value) if err == nil { t.Errorf("#%d: marshal(%#v) = [success] %q, want error %v", idx, test.Value, data, test.Err) continue } if err.Error() != test.Err { t.Errorf("#%d: marshal(%#v) = [error] %v, want %v", idx, test.Value, err, test.Err) } if test.Kind != reflect.Invalid { if kind := err.(*UnsupportedTypeError).Type.Kind(); kind != test.Kind { t.Errorf("#%d: marshal(%#v) = [error kind] %s, want %s", idx, test.Value, kind, test.Kind) } } } } // Do invertibility testing on the various structures that we test func TestUnmarshal(t *testing.T) { for i, test := range marshalTests { if test.MarshalOnly { continue } if _, ok := test.Value.(*Plain); ok { continue } vt := reflect.TypeOf(test.Value) dest := reflect.New(vt.Elem()).Interface() err := Unmarshal([]byte(test.ExpectXML), dest) switch fix := dest.(type) { case *Feed: fix.Author.InnerXML = "" for i := range fix.Entry { fix.Entry[i].Author.InnerXML = "" } } if err != nil { t.Errorf("#%d: unexpected error: %#v", i, err) } else if got, want := dest, test.Value; !reflect.DeepEqual(got, want) { t.Errorf("#%d: unmarshal(%q):\nhave %#v\nwant %#v", i, test.ExpectXML, got, want) } } } func TestMarshalIndent(t *testing.T) { for i, test := range marshalIndentTests { data, err := MarshalIndent(test.Value, test.Prefix, test.Indent) if err != nil { t.Errorf("#%d: Error: %s", i, err) continue } if got, want := string(data), test.ExpectXML; got != want { t.Errorf("#%d: MarshalIndent:\nGot:%s\nWant:\n%s", i, got, want) } } } type limitedBytesWriter struct { w io.Writer remain int // until writes fail } func (lw *limitedBytesWriter) Write(p []byte) (n int, err error) { if lw.remain <= 0 { println("error") return 0, errors.New("write limit hit") } if len(p) > lw.remain { p = p[:lw.remain] n, _ = lw.w.Write(p) lw.remain = 0 return n, errors.New("write limit hit") } n, err = lw.w.Write(p) lw.remain -= n return n, err } func TestMarshalWriteErrors(t *testing.T) { var buf bytes.Buffer const writeCap = 1024 w := &limitedBytesWriter{&buf, writeCap} enc := NewEncoder(w) var err error var i int const n = 4000 for i = 1; i <= n; i++ { err = enc.Encode(&Passenger{ Name: []string{"Alice", "Bob"}, Weight: 5, }) if err != nil { break } } if err == nil { t.Error("expected an error") } if i == n { t.Errorf("expected to fail before the end") } if buf.Len() != writeCap { t.Errorf("buf.Len() = %d; want %d", buf.Len(), writeCap) } } func TestMarshalWriteIOErrors(t *testing.T) { enc := NewEncoder(errWriter{}) expectErr := "unwritable" err := enc.Encode(&Passenger{}) if err == nil || err.Error() != expectErr { t.Errorf("EscapeTest = [error] %v, want %v", err, expectErr) } } func TestMarshalFlush(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) if err := enc.EncodeToken(CharData("hello world")); err != nil { t.Fatalf("enc.EncodeToken: %v", err) } if buf.Len() > 0 { t.Fatalf("enc.EncodeToken caused actual write: %q", buf.Bytes()) } if err := enc.Flush(); err != nil { t.Fatalf("enc.Flush: %v", err) } if buf.String() != "hello world" { t.Fatalf("after enc.Flush, buf.String() = %q, want %q", buf.String(), "hello world") } } var encodeElementTests = []struct { desc string value interface{} start StartElement expectXML string }{{ desc: "simple string", value: "hello", start: StartElement{ Name: Name{Local: "a"}, }, expectXML: `hello`, }, { desc: "string with added attributes", value: "hello", start: StartElement{ Name: Name{Local: "a"}, Attr: []Attr{{ Name: Name{Local: "x"}, Value: "y", }, { Name: Name{Local: "foo"}, Value: "bar", }}, }, expectXML: `hello`, }, { desc: "start element with default name space", value: struct { Foo XMLNameWithNSTag }{ Foo: XMLNameWithNSTag{ Value: "hello", }, }, start: StartElement{ Name: Name{Space: "ns", Local: "a"}, Attr: []Attr{{ Name: Name{Local: "xmlns"}, // "ns" is the name space defined in XMLNameWithNSTag Value: "ns", }}, }, expectXML: `hello`, }, { desc: "start element in name space with different default name space", value: struct { Foo XMLNameWithNSTag }{ Foo: XMLNameWithNSTag{ Value: "hello", }, }, start: StartElement{ Name: Name{Space: "ns2", Local: "a"}, Attr: []Attr{{ Name: Name{Local: "xmlns"}, // "ns" is the name space defined in XMLNameWithNSTag Value: "ns", }}, }, expectXML: `hello`, }, { desc: "XMLMarshaler with start element with default name space", value: &MyMarshalerTest{}, start: StartElement{ Name: Name{Space: "ns2", Local: "a"}, Attr: []Attr{{ Name: Name{Local: "xmlns"}, // "ns" is the name space defined in XMLNameWithNSTag Value: "ns", }}, }, expectXML: `hello world`, }} func TestEncodeElement(t *testing.T) { for idx, test := range encodeElementTests { var buf bytes.Buffer enc := NewEncoder(&buf) err := enc.EncodeElement(test.value, test.start) if err != nil { t.Fatalf("enc.EncodeElement: %v", err) } err = enc.Flush() if err != nil { t.Fatalf("enc.Flush: %v", err) } if got, want := buf.String(), test.expectXML; got != want { t.Errorf("#%d(%s): EncodeElement(%#v, %#v):\nhave %#q\nwant %#q", idx, test.desc, test.value, test.start, got, want) } } } func BenchmarkMarshal(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { Marshal(atomValue) } } func BenchmarkUnmarshal(b *testing.B) { b.ReportAllocs() xml := []byte(atomXml) for i := 0; i < b.N; i++ { Unmarshal(xml, &Feed{}) } } // golang.org/issue/6556 func TestStructPointerMarshal(t *testing.T) { type A struct { XMLName string `xml:"a"` B []interface{} } type C struct { XMLName Name Value string `xml:"value"` } a := new(A) a.B = append(a.B, &C{ XMLName: Name{Local: "c"}, Value: "x", }) b, err := Marshal(a) if err != nil { t.Fatal(err) } if x := string(b); x != "x" { t.Fatal(x) } var v A err = Unmarshal(b, &v) if err != nil { t.Fatal(err) } } var encodeTokenTests = []struct { desc string toks []Token want string err string }{{ desc: "start element with name space", toks: []Token{ StartElement{Name{"space", "local"}, nil}, }, want: ``, }, { desc: "start element with no name", toks: []Token{ StartElement{Name{"space", ""}, nil}, }, err: "xml: start tag with no name", }, { desc: "end element with no name", toks: []Token{ EndElement{Name{"space", ""}}, }, err: "xml: end tag with no name", }, { desc: "char data", toks: []Token{ CharData("foo"), }, want: `foo`, }, { desc: "char data with escaped chars", toks: []Token{ CharData(" \t\n"), }, want: " \n", }, { desc: "comment", toks: []Token{ Comment("foo"), }, want: ``, }, { desc: "comment with invalid content", toks: []Token{ Comment("foo-->"), }, err: "xml: EncodeToken of Comment containing --> marker", }, { desc: "proc instruction", toks: []Token{ ProcInst{"Target", []byte("Instruction")}, }, want: ``, }, { desc: "proc instruction with empty target", toks: []Token{ ProcInst{"", []byte("Instruction")}, }, err: "xml: EncodeToken of ProcInst with invalid Target", }, { desc: "proc instruction with bad content", toks: []Token{ ProcInst{"", []byte("Instruction?>")}, }, err: "xml: EncodeToken of ProcInst with invalid Target", }, { desc: "directive", toks: []Token{ Directive("foo"), }, want: ``, }, { desc: "more complex directive", toks: []Token{ Directive("DOCTYPE doc [ '> ]"), }, want: `'> ]>`, }, { desc: "directive instruction with bad name", toks: []Token{ Directive("foo>"), }, err: "xml: EncodeToken of Directive containing wrong < or > markers", }, { desc: "end tag without start tag", toks: []Token{ EndElement{Name{"foo", "bar"}}, }, err: "xml: end tag without start tag", }, { desc: "mismatching end tag local name", toks: []Token{ StartElement{Name{"", "foo"}, nil}, EndElement{Name{"", "bar"}}, }, err: "xml: end tag does not match start tag ", want: ``, }, { desc: "mismatching end tag namespace", toks: []Token{ StartElement{Name{"space", "foo"}, nil}, EndElement{Name{"another", "foo"}}, }, err: "xml: end tag in namespace another does not match start tag in namespace space", want: ``, }, { desc: "start element with explicit namespace", toks: []Token{ StartElement{Name{"space", "local"}, []Attr{ {Name{"xmlns", "x"}, "space"}, {Name{"space", "foo"}, "value"}, }}, }, want: ``, }, { desc: "start element with explicit namespace and colliding prefix", toks: []Token{ StartElement{Name{"space", "local"}, []Attr{ {Name{"xmlns", "x"}, "space"}, {Name{"space", "foo"}, "value"}, {Name{"x", "bar"}, "other"}, }}, }, want: ``, }, { desc: "start element using previously defined namespace", toks: []Token{ StartElement{Name{"", "local"}, []Attr{ {Name{"xmlns", "x"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"space", "x"}, "y"}, }}, }, want: ``, }, { desc: "nested name space with same prefix", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "x"}, "space1"}, }}, StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "x"}, "space2"}, }}, StartElement{Name{"", "foo"}, []Attr{ {Name{"space1", "a"}, "space1 value"}, {Name{"space2", "b"}, "space2 value"}, }}, EndElement{Name{"", "foo"}}, EndElement{Name{"", "foo"}}, StartElement{Name{"", "foo"}, []Attr{ {Name{"space1", "a"}, "space1 value"}, {Name{"space2", "b"}, "space2 value"}, }}, }, want: ``, }, { desc: "start element defining several prefixes for the same name space", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"xmlns", "a"}, "space"}, {Name{"xmlns", "b"}, "space"}, {Name{"space", "x"}, "value"}, }}, }, want: ``, }, { desc: "nested element redefines name space", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "x"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"xmlns", "y"}, "space"}, {Name{"space", "a"}, "value"}, }}, }, want: ``, }, { desc: "nested element creates alias for default name space", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"xmlns", "y"}, "space"}, {Name{"space", "a"}, "value"}, }}, }, want: ``, }, { desc: "nested element defines default name space with existing prefix", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "x"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, {Name{"space", "a"}, "value"}, }}, }, want: ``, }, { desc: "nested element uses empty attribute name space when default ns defined", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "attr"}, "value"}, }}, }, want: ``, }, { desc: "redefine xmlns", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"foo", "xmlns"}, "space"}, }}, }, err: `xml: cannot redefine xmlns attribute prefix`, }, { desc: "xmlns with explicit name space #1", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"xml", "xmlns"}, "space"}, }}, }, want: ``, }, { desc: "xmlns with explicit name space #2", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{xmlURL, "xmlns"}, "space"}, }}, }, want: ``, }, { desc: "empty name space declaration is ignored", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "foo"}, ""}, }}, }, want: ``, }, { desc: "attribute with no name is ignored", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"", ""}, "value"}, }}, }, want: ``, }, { desc: "namespace URL with non-valid name", toks: []Token{ StartElement{Name{"/34", "foo"}, []Attr{ {Name{"/34", "x"}, "value"}, }}, }, want: `<_:foo xmlns:_="/34" _:x="value">`, }, { desc: "nested element resets default namespace to empty", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"", "foo"}, []Attr{ {Name{"", "xmlns"}, ""}, {Name{"", "x"}, "value"}, {Name{"space", "x"}, "value"}, }}, }, want: ``, }, { desc: "nested element requires empty default name space", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"", "foo"}, nil}, }, want: ``, }, { desc: "attribute uses name space from xmlns", toks: []Token{ StartElement{Name{"some/space", "foo"}, []Attr{ {Name{"", "attr"}, "value"}, {Name{"some/space", "other"}, "other value"}, }}, }, want: ``, }, { desc: "default name space should not be used by attributes", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, {Name{"xmlns", "bar"}, "space"}, {Name{"space", "baz"}, "foo"}, }}, StartElement{Name{"space", "baz"}, nil}, EndElement{Name{"space", "baz"}}, EndElement{Name{"space", "foo"}}, }, want: ``, }, { desc: "default name space not used by attributes, not explicitly defined", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, {Name{"space", "baz"}, "foo"}, }}, StartElement{Name{"space", "baz"}, nil}, EndElement{Name{"space", "baz"}}, EndElement{Name{"space", "foo"}}, }, want: ``, }, { desc: "impossible xmlns declaration", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"space", "bar"}, []Attr{ {Name{"space", "attr"}, "value"}, }}, }, want: ``, }} func TestEncodeToken(t *testing.T) { loop: for i, tt := range encodeTokenTests { var buf bytes.Buffer enc := NewEncoder(&buf) var err error for j, tok := range tt.toks { err = enc.EncodeToken(tok) if err != nil && j < len(tt.toks)-1 { t.Errorf("#%d %s token #%d: %v", i, tt.desc, j, err) continue loop } } errorf := func(f string, a ...interface{}) { t.Errorf("#%d %s token #%d:%s", i, tt.desc, len(tt.toks)-1, fmt.Sprintf(f, a...)) } switch { case tt.err != "" && err == nil: errorf(" expected error; got none") continue case tt.err == "" && err != nil: errorf(" got error: %v", err) continue case tt.err != "" && err != nil && tt.err != err.Error(): errorf(" error mismatch; got %v, want %v", err, tt.err) continue } if err := enc.Flush(); err != nil { errorf(" %v", err) continue } if got := buf.String(); got != tt.want { errorf("\ngot %v\nwant %v", got, tt.want) continue } } } func TestProcInstEncodeToken(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) if err := enc.EncodeToken(ProcInst{"xml", []byte("Instruction")}); err != nil { t.Fatalf("enc.EncodeToken: expected to be able to encode xml target ProcInst as first token, %s", err) } if err := enc.EncodeToken(ProcInst{"Target", []byte("Instruction")}); err != nil { t.Fatalf("enc.EncodeToken: expected to be able to add non-xml target ProcInst") } if err := enc.EncodeToken(ProcInst{"xml", []byte("Instruction")}); err == nil { t.Fatalf("enc.EncodeToken: expected to not be allowed to encode xml target ProcInst when not first token") } } func TestDecodeEncode(t *testing.T) { var in, out bytes.Buffer in.WriteString(` `) dec := NewDecoder(&in) enc := NewEncoder(&out) for tok, err := dec.Token(); err == nil; tok, err = dec.Token() { err = enc.EncodeToken(tok) if err != nil { t.Fatalf("enc.EncodeToken: Unable to encode token (%#v), %v", tok, err) } } } // Issue 9796. Used to fail with GORACE="halt_on_error=1" -race. func TestRace9796(t *testing.T) { type A struct{} type B struct { C []A `xml:"X>Y"` } var wg sync.WaitGroup for i := 0; i < 2; i++ { wg.Add(1) go func() { Marshal(B{[]A{{}}}) wg.Done() }() } wg.Wait() } func TestIsValidDirective(t *testing.T) { testOK := []string{ "<>", "< < > >", "' '>' >", " ]>", " '<' ' doc ANY> ]>", ">>> a < comment --> [ ] >", } testKO := []string{ "<", ">", "", "< > > < < >", " -->", "", "'", "", } for _, s := range testOK { if !isValidDirective(Directive(s)) { t.Errorf("Directive %q is expected to be valid", s) } } for _, s := range testKO { if isValidDirective(Directive(s)) { t.Errorf("Directive %q is expected to be invalid", s) } } } // Issue 11719. EncodeToken used to silently eat tokens with an invalid type. func TestSimpleUseOfEncodeToken(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) if err := enc.EncodeToken(&StartElement{Name: Name{"", "object1"}}); err == nil { t.Errorf("enc.EncodeToken: pointer type should be rejected") } if err := enc.EncodeToken(&EndElement{Name: Name{"", "object1"}}); err == nil { t.Errorf("enc.EncodeToken: pointer type should be rejected") } if err := enc.EncodeToken(StartElement{Name: Name{"", "object2"}}); err != nil { t.Errorf("enc.EncodeToken: StartElement %s", err) } if err := enc.EncodeToken(EndElement{Name: Name{"", "object2"}}); err != nil { t.Errorf("enc.EncodeToken: EndElement %s", err) } if err := enc.EncodeToken(Universe{}); err == nil { t.Errorf("enc.EncodeToken: invalid type not caught") } if err := enc.Flush(); err != nil { t.Errorf("enc.Flush: %s", err) } if buf.Len() == 0 { t.Errorf("enc.EncodeToken: empty buffer") } want := "" if buf.String() != want { t.Errorf("enc.EncodeToken: expected %q; got %q", want, buf.String()) } } lxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/marshal.go0000644061062106075000000010605613172163402026165 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xml import ( "bufio" "bytes" "encoding" "fmt" "io" "reflect" "strconv" "strings" ) const ( // A generic XML header suitable for use with the output of Marshal. // This is not automatically added to any output of this package, // it is provided as a convenience. Header = `` + "\n" ) // Marshal returns the XML encoding of v. // // Marshal handles an array or slice by marshalling each of the elements. // Marshal handles a pointer by marshalling the value it points at or, if the // pointer is nil, by writing nothing. Marshal handles an interface value by // marshalling the value it contains or, if the interface value is nil, by // writing nothing. Marshal handles all other data by writing one or more XML // elements containing the data. // // The name for the XML elements is taken from, in order of preference: // - the tag on the XMLName field, if the data is a struct // - the value of the XMLName field of type xml.Name // - the tag of the struct field used to obtain the data // - the name of the struct field used to obtain the data // - the name of the marshalled type // // The XML element for a struct contains marshalled elements for each of the // exported fields of the struct, with these exceptions: // - the XMLName field, described above, is omitted. // - a field with tag "-" is omitted. // - a field with tag "name,attr" becomes an attribute with // the given name in the XML element. // - a field with tag ",attr" becomes an attribute with the // field name in the XML element. // - a field with tag ",chardata" is written as character data, // not as an XML element. // - a field with tag ",innerxml" is written verbatim, not subject // to the usual marshalling procedure. // - a field with tag ",comment" is written as an XML comment, not // subject to the usual marshalling procedure. It must not contain // the "--" string within it. // - a field with a tag including the "omitempty" option is omitted // if the field value is empty. The empty values are false, 0, any // nil pointer or interface value, and any array, slice, map, or // string of length zero. // - an anonymous struct field is handled as if the fields of its // value were part of the outer struct. // // If a field uses a tag "a>b>c", then the element c will be nested inside // parent elements a and b. Fields that appear next to each other that name // the same parent will be enclosed in one XML element. // // See MarshalIndent for an example. // // Marshal will return an error if asked to marshal a channel, function, or map. func Marshal(v interface{}) ([]byte, error) { var b bytes.Buffer if err := NewEncoder(&b).Encode(v); err != nil { return nil, err } return b.Bytes(), nil } // Marshaler is the interface implemented by objects that can marshal // themselves into valid XML elements. // // MarshalXML encodes the receiver as zero or more XML elements. // By convention, arrays or slices are typically encoded as a sequence // of elements, one per entry. // Using start as the element tag is not required, but doing so // will enable Unmarshal to match the XML elements to the correct // struct field. // One common implementation strategy is to construct a separate // value with a layout corresponding to the desired XML and then // to encode it using e.EncodeElement. // Another common strategy is to use repeated calls to e.EncodeToken // to generate the XML output one token at a time. // The sequence of encoded tokens must make up zero or more valid // XML elements. type Marshaler interface { MarshalXML(e *Encoder, start StartElement) error } // MarshalerAttr is the interface implemented by objects that can marshal // themselves into valid XML attributes. // // MarshalXMLAttr returns an XML attribute with the encoded value of the receiver. // Using name as the attribute name is not required, but doing so // will enable Unmarshal to match the attribute to the correct // struct field. // If MarshalXMLAttr returns the zero attribute Attr{}, no attribute // will be generated in the output. // MarshalXMLAttr is used only for struct fields with the // "attr" option in the field tag. type MarshalerAttr interface { MarshalXMLAttr(name Name) (Attr, error) } // MarshalIndent works like Marshal, but each XML element begins on a new // indented line that starts with prefix and is followed by one or more // copies of indent according to the nesting depth. func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { var b bytes.Buffer enc := NewEncoder(&b) enc.Indent(prefix, indent) if err := enc.Encode(v); err != nil { return nil, err } return b.Bytes(), nil } // An Encoder writes XML data to an output stream. type Encoder struct { p printer } // NewEncoder returns a new encoder that writes to w. func NewEncoder(w io.Writer) *Encoder { e := &Encoder{printer{Writer: bufio.NewWriter(w)}} e.p.encoder = e return e } // Indent sets the encoder to generate XML in which each element // begins on a new indented line that starts with prefix and is followed by // one or more copies of indent according to the nesting depth. func (enc *Encoder) Indent(prefix, indent string) { enc.p.prefix = prefix enc.p.indent = indent } // Encode writes the XML encoding of v to the stream. // // See the documentation for Marshal for details about the conversion // of Go values to XML. // // Encode calls Flush before returning. func (enc *Encoder) Encode(v interface{}) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil) if err != nil { return err } return enc.p.Flush() } // EncodeElement writes the XML encoding of v to the stream, // using start as the outermost tag in the encoding. // // See the documentation for Marshal for details about the conversion // of Go values to XML. // // EncodeElement calls Flush before returning. func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start) if err != nil { return err } return enc.p.Flush() } var ( begComment = []byte("") endProcInst = []byte("?>") endDirective = []byte(">") ) // EncodeToken writes the given XML token to the stream. // It returns an error if StartElement and EndElement tokens are not // properly matched. // // EncodeToken does not call Flush, because usually it is part of a // larger operation such as Encode or EncodeElement (or a custom // Marshaler's MarshalXML invoked during those), and those will call // Flush when finished. Callers that create an Encoder and then invoke // EncodeToken directly, without using Encode or EncodeElement, need to // call Flush when finished to ensure that the XML is written to the // underlying writer. // // EncodeToken allows writing a ProcInst with Target set to "xml" only // as the first token in the stream. // // When encoding a StartElement holding an XML namespace prefix // declaration for a prefix that is not already declared, contained // elements (including the StartElement itself) will use the declared // prefix when encoding names with matching namespace URIs. func (enc *Encoder) EncodeToken(t Token) error { p := &enc.p switch t := t.(type) { case StartElement: if err := p.writeStart(&t); err != nil { return err } case EndElement: if err := p.writeEnd(t.Name); err != nil { return err } case CharData: escapeText(p, t, false) case Comment: if bytes.Contains(t, endComment) { return fmt.Errorf("xml: EncodeToken of Comment containing --> marker") } p.WriteString("") return p.cachedWriteError() case ProcInst: // First token to be encoded which is also a ProcInst with target of xml // is the xml declaration. The only ProcInst where target of xml is allowed. if t.Target == "xml" && p.Buffered() != 0 { return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded") } if !isNameString(t.Target) { return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target") } if bytes.Contains(t.Inst, endProcInst) { return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker") } p.WriteString(" 0 { p.WriteByte(' ') p.Write(t.Inst) } p.WriteString("?>") case Directive: if !isValidDirective(t) { return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers") } p.WriteString("") default: return fmt.Errorf("xml: EncodeToken of invalid token type") } return p.cachedWriteError() } // isValidDirective reports whether dir is a valid directive text, // meaning angle brackets are matched, ignoring comments and strings. func isValidDirective(dir Directive) bool { var ( depth int inquote uint8 incomment bool ) for i, c := range dir { switch { case incomment: if c == '>' { if n := 1 + i - len(endComment); n >= 0 && bytes.Equal(dir[n:i+1], endComment) { incomment = false } } // Just ignore anything in comment case inquote != 0: if c == inquote { inquote = 0 } // Just ignore anything within quotes case c == '\'' || c == '"': inquote = c case c == '<': if i+len(begComment) < len(dir) && bytes.Equal(dir[i:i+len(begComment)], begComment) { incomment = true } else { depth++ } case c == '>': if depth == 0 { return false } depth-- } } return depth == 0 && inquote == 0 && !incomment } // Flush flushes any buffered XML to the underlying writer. // See the EncodeToken documentation for details about when it is necessary. func (enc *Encoder) Flush() error { return enc.p.Flush() } type printer struct { *bufio.Writer encoder *Encoder seq int indent string prefix string depth int indentedIn bool putNewline bool defaultNS string attrNS map[string]string // map prefix -> name space attrPrefix map[string]string // map name space -> prefix prefixes []printerPrefix tags []Name } // printerPrefix holds a namespace undo record. // When an element is popped, the prefix record // is set back to the recorded URL. The empty // prefix records the URL for the default name space. // // The start of an element is recorded with an element // that has mark=true. type printerPrefix struct { prefix string url string mark bool } func (p *printer) prefixForNS(url string, isAttr bool) string { // The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml" // and must be referred to that way. // (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns", // but users should not be trying to use that one directly - that's our job.) if url == xmlURL { return "xml" } if !isAttr && url == p.defaultNS { // We can use the default name space. return "" } return p.attrPrefix[url] } // defineNS pushes any namespace definition found in the given attribute. // If ignoreNonEmptyDefault is true, an xmlns="nonempty" // attribute will be ignored. func (p *printer) defineNS(attr Attr, ignoreNonEmptyDefault bool) error { var prefix string if attr.Name.Local == "xmlns" { if attr.Name.Space != "" && attr.Name.Space != "xml" && attr.Name.Space != xmlURL { return fmt.Errorf("xml: cannot redefine xmlns attribute prefix") } } else if attr.Name.Space == "xmlns" && attr.Name.Local != "" { prefix = attr.Name.Local if attr.Value == "" { // Technically, an empty XML namespace is allowed for an attribute. // From http://www.w3.org/TR/xml-names11/#scoping-defaulting: // // The attribute value in a namespace declaration for a prefix may be // empty. This has the effect, within the scope of the declaration, of removing // any association of the prefix with a namespace name. // // However our namespace prefixes here are used only as hints. There's // no need to respect the removal of a namespace prefix, so we ignore it. return nil } } else { // Ignore: it's not a namespace definition return nil } if prefix == "" { if attr.Value == p.defaultNS { // No need for redefinition. return nil } if attr.Value != "" && ignoreNonEmptyDefault { // We have an xmlns="..." value but // it can't define a name space in this context, // probably because the element has an empty // name space. In this case, we just ignore // the name space declaration. return nil } } else if _, ok := p.attrPrefix[attr.Value]; ok { // There's already a prefix for the given name space, // so use that. This prevents us from // having two prefixes for the same name space // so attrNS and attrPrefix can remain bijective. return nil } p.pushPrefix(prefix, attr.Value) return nil } // createNSPrefix creates a name space prefix attribute // to use for the given name space, defining a new prefix // if necessary. // If isAttr is true, the prefix is to be created for an attribute // prefix, which means that the default name space cannot // be used. func (p *printer) createNSPrefix(url string, isAttr bool) { if _, ok := p.attrPrefix[url]; ok { // We already have a prefix for the given URL. return } switch { case !isAttr && url == p.defaultNS: // We can use the default name space. return case url == "": // The only way we can encode names in the empty // name space is by using the default name space, // so we must use that. if p.defaultNS != "" { // The default namespace is non-empty, so we // need to set it to empty. p.pushPrefix("", "") } return case url == xmlURL: return } // TODO If the URL is an existing prefix, we could // use it as is. That would enable the // marshaling of elements that had been unmarshaled // and with a name space prefix that was not found. // although technically it would be incorrect. // Pick a name. We try to use the final element of the path // but fall back to _. prefix := strings.TrimRight(url, "/") if i := strings.LastIndex(prefix, "/"); i >= 0 { prefix = prefix[i+1:] } if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") { prefix = "_" } if strings.HasPrefix(prefix, "xml") { // xmlanything is reserved. prefix = "_" + prefix } if p.attrNS[prefix] != "" { // Name is taken. Find a better one. for p.seq++; ; p.seq++ { if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" { prefix = id break } } } p.pushPrefix(prefix, url) } // writeNamespaces writes xmlns attributes for all the // namespace prefixes that have been defined in // the current element. func (p *printer) writeNamespaces() { for i := len(p.prefixes) - 1; i >= 0; i-- { prefix := p.prefixes[i] if prefix.mark { return } p.WriteString(" ") if prefix.prefix == "" { // Default name space. p.WriteString(`xmlns="`) } else { p.WriteString("xmlns:") p.WriteString(prefix.prefix) p.WriteString(`="`) } EscapeText(p, []byte(p.nsForPrefix(prefix.prefix))) p.WriteString(`"`) } } // pushPrefix pushes a new prefix on the prefix stack // without checking to see if it is already defined. func (p *printer) pushPrefix(prefix, url string) { p.prefixes = append(p.prefixes, printerPrefix{ prefix: prefix, url: p.nsForPrefix(prefix), }) p.setAttrPrefix(prefix, url) } // nsForPrefix returns the name space for the given // prefix. Note that this is not valid for the // empty attribute prefix, which always has an empty // name space. func (p *printer) nsForPrefix(prefix string) string { if prefix == "" { return p.defaultNS } return p.attrNS[prefix] } // markPrefix marks the start of an element on the prefix // stack. func (p *printer) markPrefix() { p.prefixes = append(p.prefixes, printerPrefix{ mark: true, }) } // popPrefix pops all defined prefixes for the current // element. func (p *printer) popPrefix() { for len(p.prefixes) > 0 { prefix := p.prefixes[len(p.prefixes)-1] p.prefixes = p.prefixes[:len(p.prefixes)-1] if prefix.mark { break } p.setAttrPrefix(prefix.prefix, prefix.url) } } // setAttrPrefix sets an attribute name space prefix. // If url is empty, the attribute is removed. // If prefix is empty, the default name space is set. func (p *printer) setAttrPrefix(prefix, url string) { if prefix == "" { p.defaultNS = url return } if url == "" { delete(p.attrPrefix, p.attrNS[prefix]) delete(p.attrNS, prefix) return } if p.attrPrefix == nil { // Need to define a new name space. p.attrPrefix = make(map[string]string) p.attrNS = make(map[string]string) } // Remove any old prefix value. This is OK because we maintain a // strict one-to-one mapping between prefix and URL (see // defineNS) delete(p.attrPrefix, p.attrNS[prefix]) p.attrPrefix[url] = prefix p.attrNS[prefix] = url } var ( marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() marshalerAttrType = reflect.TypeOf((*MarshalerAttr)(nil)).Elem() textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() ) // marshalValue writes one or more XML elements representing val. // If val was obtained from a struct field, finfo must have its details. func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error { if startTemplate != nil && startTemplate.Name.Local == "" { return fmt.Errorf("xml: EncodeElement of StartElement with missing name") } if !val.IsValid() { return nil } if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) { return nil } // Drill into interfaces and pointers. // This can turn into an infinite loop given a cyclic chain, // but it matches the Go 1 behavior. for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { if val.IsNil() { return nil } val = val.Elem() } kind := val.Kind() typ := val.Type() // Check for marshaler. if val.CanInterface() && typ.Implements(marshalerType) { return p.marshalInterface(val.Interface().(Marshaler), p.defaultStart(typ, finfo, startTemplate)) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(marshalerType) { return p.marshalInterface(pv.Interface().(Marshaler), p.defaultStart(pv.Type(), finfo, startTemplate)) } } // Check for text marshaler. if val.CanInterface() && typ.Implements(textMarshalerType) { return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), p.defaultStart(typ, finfo, startTemplate)) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), p.defaultStart(pv.Type(), finfo, startTemplate)) } } // Slices and arrays iterate over the elements. They do not have an enclosing tag. if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 { for i, n := 0, val.Len(); i < n; i++ { if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil { return err } } return nil } tinfo, err := getTypeInfo(typ) if err != nil { return err } // Create start element. // Precedence for the XML element name is: // 0. startTemplate // 1. XMLName field in underlying struct; // 2. field name/tag in the struct field; and // 3. type name var start StartElement // explicitNS records whether the element's name space has been // explicitly set (for example an XMLName field). explicitNS := false if startTemplate != nil { start.Name = startTemplate.Name explicitNS = true start.Attr = append(start.Attr, startTemplate.Attr...) } else if tinfo.xmlname != nil { xmlname := tinfo.xmlname if xmlname.name != "" { start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name } else if v, ok := xmlname.value(val).Interface().(Name); ok && v.Local != "" { start.Name = v } explicitNS = true } if start.Name.Local == "" && finfo != nil { start.Name.Local = finfo.name if finfo.xmlns != "" { start.Name.Space = finfo.xmlns explicitNS = true } } if start.Name.Local == "" { name := typ.Name() if name == "" { return &UnsupportedTypeError{typ} } start.Name.Local = name } // defaultNS records the default name space as set by a xmlns="..." // attribute. We don't set p.defaultNS because we want to let // the attribute writing code (in p.defineNS) be solely responsible // for maintaining that. defaultNS := p.defaultNS // Attributes for i := range tinfo.fields { finfo := &tinfo.fields[i] if finfo.flags&fAttr == 0 { continue } attr, err := p.fieldAttr(finfo, val) if err != nil { return err } if attr.Name.Local == "" { continue } start.Attr = append(start.Attr, attr) if attr.Name.Space == "" && attr.Name.Local == "xmlns" { defaultNS = attr.Value } } if !explicitNS { // Historic behavior: elements use the default name space // they are contained in by default. start.Name.Space = defaultNS } // Historic behaviour: an element that's in a namespace sets // the default namespace for all elements contained within it. start.setDefaultNamespace() if err := p.writeStart(&start); err != nil { return err } if val.Kind() == reflect.Struct { err = p.marshalStruct(tinfo, val) } else { s, b, err1 := p.marshalSimple(typ, val) if err1 != nil { err = err1 } else if b != nil { EscapeText(p, b) } else { p.EscapeString(s) } } if err != nil { return err } if err := p.writeEnd(start.Name); err != nil { return err } return p.cachedWriteError() } // fieldAttr returns the attribute of the given field. // If the returned attribute has an empty Name.Local, // it should not be used. // The given value holds the value containing the field. func (p *printer) fieldAttr(finfo *fieldInfo, val reflect.Value) (Attr, error) { fv := finfo.value(val) name := Name{Space: finfo.xmlns, Local: finfo.name} if finfo.flags&fOmitEmpty != 0 && isEmptyValue(fv) { return Attr{}, nil } if fv.Kind() == reflect.Interface && fv.IsNil() { return Attr{}, nil } if fv.CanInterface() && fv.Type().Implements(marshalerAttrType) { attr, err := fv.Interface().(MarshalerAttr).MarshalXMLAttr(name) return attr, err } if fv.CanAddr() { pv := fv.Addr() if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) { attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name) return attr, err } } if fv.CanInterface() && fv.Type().Implements(textMarshalerType) { text, err := fv.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return Attr{}, err } return Attr{name, string(text)}, nil } if fv.CanAddr() { pv := fv.Addr() if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { text, err := pv.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return Attr{}, err } return Attr{name, string(text)}, nil } } // Dereference or skip nil pointer, interface values. switch fv.Kind() { case reflect.Ptr, reflect.Interface: if fv.IsNil() { return Attr{}, nil } fv = fv.Elem() } s, b, err := p.marshalSimple(fv.Type(), fv) if err != nil { return Attr{}, err } if b != nil { s = string(b) } return Attr{name, s}, nil } // defaultStart returns the default start element to use, // given the reflect type, field info, and start template. func (p *printer) defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement { var start StartElement // Precedence for the XML element name is as above, // except that we do not look inside structs for the first field. if startTemplate != nil { start.Name = startTemplate.Name start.Attr = append(start.Attr, startTemplate.Attr...) } else if finfo != nil && finfo.name != "" { start.Name.Local = finfo.name start.Name.Space = finfo.xmlns } else if typ.Name() != "" { start.Name.Local = typ.Name() } else { // Must be a pointer to a named type, // since it has the Marshaler methods. start.Name.Local = typ.Elem().Name() } // Historic behaviour: elements use the name space of // the element they are contained in by default. if start.Name.Space == "" { start.Name.Space = p.defaultNS } start.setDefaultNamespace() return start } // marshalInterface marshals a Marshaler interface value. func (p *printer) marshalInterface(val Marshaler, start StartElement) error { // Push a marker onto the tag stack so that MarshalXML // cannot close the XML tags that it did not open. p.tags = append(p.tags, Name{}) n := len(p.tags) err := val.MarshalXML(p.encoder, start) if err != nil { return err } // Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark. if len(p.tags) > n { return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local) } p.tags = p.tags[:n-1] return nil } // marshalTextInterface marshals a TextMarshaler interface value. func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error { if err := p.writeStart(&start); err != nil { return err } text, err := val.MarshalText() if err != nil { return err } EscapeText(p, text) return p.writeEnd(start.Name) } // writeStart writes the given start element. func (p *printer) writeStart(start *StartElement) error { if start.Name.Local == "" { return fmt.Errorf("xml: start tag with no name") } p.tags = append(p.tags, start.Name) p.markPrefix() // Define any name spaces explicitly declared in the attributes. // We do this as a separate pass so that explicitly declared prefixes // will take precedence over implicitly declared prefixes // regardless of the order of the attributes. ignoreNonEmptyDefault := start.Name.Space == "" for _, attr := range start.Attr { if err := p.defineNS(attr, ignoreNonEmptyDefault); err != nil { return err } } // Define any new name spaces implied by the attributes. for _, attr := range start.Attr { name := attr.Name // From http://www.w3.org/TR/xml-names11/#defaulting // "Default namespace declarations do not apply directly // to attribute names; the interpretation of unprefixed // attributes is determined by the element on which they // appear." // This means we don't need to create a new namespace // when an attribute name space is empty. if name.Space != "" && !name.isNamespace() { p.createNSPrefix(name.Space, true) } } p.createNSPrefix(start.Name.Space, false) p.writeIndent(1) p.WriteByte('<') p.writeName(start.Name, false) p.writeNamespaces() for _, attr := range start.Attr { name := attr.Name if name.Local == "" || name.isNamespace() { // Namespaces have already been written by writeNamespaces above. continue } p.WriteByte(' ') p.writeName(name, true) p.WriteString(`="`) p.EscapeString(attr.Value) p.WriteByte('"') } p.WriteByte('>') return nil } // writeName writes the given name. It assumes // that p.createNSPrefix(name) has already been called. func (p *printer) writeName(name Name, isAttr bool) { if prefix := p.prefixForNS(name.Space, isAttr); prefix != "" { p.WriteString(prefix) p.WriteByte(':') } p.WriteString(name.Local) } func (p *printer) writeEnd(name Name) error { if name.Local == "" { return fmt.Errorf("xml: end tag with no name") } if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" { return fmt.Errorf("xml: end tag without start tag", name.Local) } if top := p.tags[len(p.tags)-1]; top != name { if top.Local != name.Local { return fmt.Errorf("xml: end tag does not match start tag <%s>", name.Local, top.Local) } return fmt.Errorf("xml: end tag in namespace %s does not match start tag <%s> in namespace %s", name.Local, name.Space, top.Local, top.Space) } p.tags = p.tags[:len(p.tags)-1] p.writeIndent(-1) p.WriteByte('<') p.WriteByte('/') p.writeName(name, false) p.WriteByte('>') p.popPrefix() return nil } func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) { switch val.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return strconv.FormatInt(val.Int(), 10), nil, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return strconv.FormatUint(val.Uint(), 10), nil, nil case reflect.Float32, reflect.Float64: return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil case reflect.String: return val.String(), nil, nil case reflect.Bool: return strconv.FormatBool(val.Bool()), nil, nil case reflect.Array: if typ.Elem().Kind() != reflect.Uint8 { break } // [...]byte var bytes []byte if val.CanAddr() { bytes = val.Slice(0, val.Len()).Bytes() } else { bytes = make([]byte, val.Len()) reflect.Copy(reflect.ValueOf(bytes), val) } return "", bytes, nil case reflect.Slice: if typ.Elem().Kind() != reflect.Uint8 { break } // []byte return "", val.Bytes(), nil } return "", nil, &UnsupportedTypeError{typ} } var ddBytes = []byte("--") func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error { s := parentStack{p: p} for i := range tinfo.fields { finfo := &tinfo.fields[i] if finfo.flags&fAttr != 0 { continue } vf := finfo.value(val) // Dereference or skip nil pointer, interface values. switch vf.Kind() { case reflect.Ptr, reflect.Interface: if !vf.IsNil() { vf = vf.Elem() } } switch finfo.flags & fMode { case fCharData: if err := s.setParents(&noField, reflect.Value{}); err != nil { return err } if vf.CanInterface() && vf.Type().Implements(textMarshalerType) { data, err := vf.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return err } Escape(p, data) continue } if vf.CanAddr() { pv := vf.Addr() if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { data, err := pv.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return err } Escape(p, data) continue } } var scratch [64]byte switch vf.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: Escape(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: Escape(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)) case reflect.Float32, reflect.Float64: Escape(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())) case reflect.Bool: Escape(p, strconv.AppendBool(scratch[:0], vf.Bool())) case reflect.String: if err := EscapeText(p, []byte(vf.String())); err != nil { return err } case reflect.Slice: if elem, ok := vf.Interface().([]byte); ok { if err := EscapeText(p, elem); err != nil { return err } } } continue case fComment: if err := s.setParents(&noField, reflect.Value{}); err != nil { return err } k := vf.Kind() if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) { return fmt.Errorf("xml: bad type for comment field of %s", val.Type()) } if vf.Len() == 0 { continue } p.writeIndent(0) p.WriteString("" is invalid grammar. Make it "- -->" p.WriteByte(' ') } p.WriteString("-->") continue case fInnerXml: iface := vf.Interface() switch raw := iface.(type) { case []byte: p.Write(raw) continue case string: p.WriteString(raw) continue } case fElement, fElement | fAny: if err := s.setParents(finfo, vf); err != nil { return err } } if err := p.marshalValue(vf, finfo, nil); err != nil { return err } } if err := s.setParents(&noField, reflect.Value{}); err != nil { return err } return p.cachedWriteError() } var noField fieldInfo // return the bufio Writer's cached write error func (p *printer) cachedWriteError() error { _, err := p.Write(nil) return err } func (p *printer) writeIndent(depthDelta int) { if len(p.prefix) == 0 && len(p.indent) == 0 { return } if depthDelta < 0 { p.depth-- if p.indentedIn { p.indentedIn = false return } p.indentedIn = false } if p.putNewline { p.WriteByte('\n') } else { p.putNewline = true } if len(p.prefix) > 0 { p.WriteString(p.prefix) } if len(p.indent) > 0 { for i := 0; i < p.depth; i++ { p.WriteString(p.indent) } } if depthDelta > 0 { p.depth++ p.indentedIn = true } } type parentStack struct { p *printer xmlns string parents []string } // setParents sets the stack of current parents to those found in finfo. // It only writes the start elements if vf holds a non-nil value. // If finfo is &noField, it pops all elements. func (s *parentStack) setParents(finfo *fieldInfo, vf reflect.Value) error { xmlns := s.p.defaultNS if finfo.xmlns != "" { xmlns = finfo.xmlns } commonParents := 0 if xmlns == s.xmlns { for ; commonParents < len(finfo.parents) && commonParents < len(s.parents); commonParents++ { if finfo.parents[commonParents] != s.parents[commonParents] { break } } } // Pop off any parents that aren't in common with the previous field. for i := len(s.parents) - 1; i >= commonParents; i-- { if err := s.p.writeEnd(Name{ Space: s.xmlns, Local: s.parents[i], }); err != nil { return err } } s.parents = finfo.parents s.xmlns = xmlns if commonParents >= len(s.parents) { // No new elements to push. return nil } if (vf.Kind() == reflect.Ptr || vf.Kind() == reflect.Interface) && vf.IsNil() { // The element is nil, so no need for the start elements. s.parents = s.parents[:commonParents] return nil } // Push any new parents required. for _, name := range s.parents[commonParents:] { start := &StartElement{ Name: Name{ Space: s.xmlns, Local: name, }, } // Set the default name space for parent elements // to match what we do with other elements. if s.xmlns != s.p.defaultNS { start.setDefaultNamespace() } if err := s.p.writeStart(start); err != nil { return err } } return nil } // A MarshalXMLError is returned when Marshal encounters a type // that cannot be converted into XML. type UnsupportedTypeError struct { Type reflect.Type } func (e *UnsupportedTypeError) Error() string { return "xml: unsupported type: " + e.Type.String() } func isEmptyValue(v reflect.Value) bool { switch v.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: return v.Len() == 0 case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Ptr: return v.IsNil() } return false } lxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/example_test.go0000644061062106075000000000733613172163402027231 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xml_test import ( "encoding/xml" "fmt" "os" ) func ExampleMarshalIndent() { type Address struct { City, State string } type Person struct { XMLName xml.Name `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Comment string `xml:",comment"` } v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42} v.Comment = " Need more details. " v.Address = Address{"Hanga Roa", "Easter Island"} output, err := xml.MarshalIndent(v, " ", " ") if err != nil { fmt.Printf("error: %v\n", err) } os.Stdout.Write(output) // Output: // // // John // Doe // // 42 // false // Hanga Roa // Easter Island // // } func ExampleEncoder() { type Address struct { City, State string } type Person struct { XMLName xml.Name `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Comment string `xml:",comment"` } v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42} v.Comment = " Need more details. " v.Address = Address{"Hanga Roa", "Easter Island"} enc := xml.NewEncoder(os.Stdout) enc.Indent(" ", " ") if err := enc.Encode(v); err != nil { fmt.Printf("error: %v\n", err) } // Output: // // // John // Doe // // 42 // false // Hanga Roa // Easter Island // // } // This example demonstrates unmarshaling an XML excerpt into a value with // some preset fields. Note that the Phone field isn't modified and that // the XML element is ignored. Also, the Groups field is assigned // considering the element path provided in its tag. func ExampleUnmarshal() { type Email struct { Where string `xml:"where,attr"` Addr string } type Address struct { City, State string } type Result struct { XMLName xml.Name `xml:"Person"` Name string `xml:"FullName"` Phone string Email []Email Groups []string `xml:"Group>Value"` Address } v := Result{Name: "none", Phone: "none"} data := ` Grace R. Emlin Example Inc. gre@example.com gre@work.com Friends Squash Hanga Roa Easter Island ` err := xml.Unmarshal([]byte(data), &v) if err != nil { fmt.Printf("error: %v", err) return } fmt.Printf("XMLName: %#v\n", v.XMLName) fmt.Printf("Name: %q\n", v.Name) fmt.Printf("Phone: %q\n", v.Phone) fmt.Printf("Email: %v\n", v.Email) fmt.Printf("Groups: %v\n", v.Groups) fmt.Printf("Address: %v\n", v.Address) // Output: // XMLName: xml.Name{Space:"", Local:"Person"} // Name: "Grace R. Emlin" // Phone: "none" // Email: [{home gre@example.com} {work gre@work.com}] // Groups: [Friends Squash] // Address: {Hanga Roa Easter Island} } lxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/atom_test.go0000644061062106075000000000312613172163402026527 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xml import "time" var atomValue = &Feed{ XMLName: Name{"http://www.w3.org/2005/Atom", "feed"}, Title: "Example Feed", Link: []Link{{Href: "http://example.org/"}}, Updated: ParseTime("2003-12-13T18:30:02Z"), Author: Person{Name: "John Doe"}, Id: "urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", Entry: []Entry{ { Title: "Atom-Powered Robots Run Amok", Link: []Link{{Href: "http://example.org/2003/12/13/atom03"}}, Id: "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", Updated: ParseTime("2003-12-13T18:30:02Z"), Summary: NewText("Some text."), }, }, } var atomXml = `` + `` + `Example Feed` + `urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6` + `` + `John Doe` + `` + `Atom-Powered Robots Run Amok` + `urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a` + `` + `2003-12-13T18:30:02Z` + `` + `

Some text.` + `` + `` func ParseTime(str string) time.Time { t, err := time.Parse(time.RFC3339, str) if err != nil { panic(err) } return t } func NewText(text string) Text { return Text{ Body: text, } } lxd-2.0.11/dist/src/golang.org/x/net/webdav/internal/xml/README0000644061062106075000000000067113172163402025063 0ustar stgraberdomain adminsThis is a fork of the encoding/xml package at ca1d6c4, the last commit before https://go.googlesource.com/go/+/c0d6d33 "encoding/xml: restore Go 1.4 name space behavior" made late in the lead-up to the Go 1.5 release. The list of encoding/xml changes is at https://go.googlesource.com/go/+log/master/src/encoding/xml This fork is temporary, and I (nigeltao) expect to revert it after Go 1.6 is released. See http://golang.org/issue/11841 lxd-2.0.11/dist/src/golang.org/x/net/webdav/if_test.go0000644061062106075000000001515213172163402023553 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "reflect" "strings" "testing" ) func TestParseIfHeader(t *testing.T) { // The "section x.y.z" test cases come from section x.y.z of the spec at // http://www.webdav.org/specs/rfc4918.html testCases := []struct { desc string input string want ifHeader }{{ "bad: empty", ``, ifHeader{}, }, { "bad: no parens", `foobar`, ifHeader{}, }, { "bad: empty list #1", `()`, ifHeader{}, }, { "bad: empty list #2", `(a) (b c) () (d)`, ifHeader{}, }, { "bad: no list after resource #1", ``, ifHeader{}, }, { "bad: no list after resource #2", ` (a)`, ifHeader{}, }, { "bad: no list after resource #3", ` (a) (b) `, ifHeader{}, }, { "bad: no-tag-list followed by tagged-list", `(a) (b) (c)`, ifHeader{}, }, { "bad: unfinished list", `(a`, ifHeader{}, }, { "bad: unfinished ETag", `([b`, ifHeader{}, }, { "bad: unfinished Notted list", `(Not a`, ifHeader{}, }, { "bad: double Not", `(Not Not a)`, ifHeader{}, }, { "good: one list with a Token", `(a)`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `a`, }}, }}, }, }, { "good: one list with an ETag", `([a])`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ ETag: `a`, }}, }}, }, }, { "good: one list with three Nots", `(Not a Not b Not [d])`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Not: true, Token: `a`, }, { Not: true, Token: `b`, }, { Not: true, ETag: `d`, }}, }}, }, }, { "good: two lists", `(a) (b)`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `a`, }}, }, { conditions: []Condition{{ Token: `b`, }}, }}, }, }, { "good: two Notted lists", `(Not a) (Not b)`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Not: true, Token: `a`, }}, }, { conditions: []Condition{{ Not: true, Token: `b`, }}, }}, }, }, { "section 7.5.1", ` ()`, ifHeader{ lists: []ifList{{ resourceTag: `http://www.example.com/users/f/fielding/index.html`, conditions: []Condition{{ Token: `urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6`, }}, }}, }, }, { "section 7.5.2 #1", `()`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, }}, }}, }, }, { "section 7.5.2 #2", ` ()`, ifHeader{ lists: []ifList{{ resourceTag: `http://example.com/locked/`, conditions: []Condition{{ Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, }}, }}, }, }, { "section 7.5.2 #3", ` ()`, ifHeader{ lists: []ifList{{ resourceTag: `http://example.com/locked/member`, conditions: []Condition{{ Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, }}, }}, }, }, { "section 9.9.6", `() ()`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:fe184f2e-6eec-41d0-c765-01adc56e6bb4`, }}, }, { conditions: []Condition{{ Token: `urn:uuid:e454f3f3-acdc-452a-56c7-00a5c91e4b77`, }}, }}, }, }, { "section 9.10.8", `()`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4`, }}, }}, }, }, { "section 10.4.6", `( ["I am an ETag"]) (["I am another ETag"])`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }, { ETag: `"I am an ETag"`, }}, }, { conditions: []Condition{{ ETag: `"I am another ETag"`, }}, }}, }, }, { "section 10.4.7", `(Not )`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Not: true, Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }, { Token: `urn:uuid:58f202ac-22cf-11d1-b12d-002035b29092`, }}, }}, }, }, { "section 10.4.8", `() (Not )`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }}, }, { conditions: []Condition{{ Not: true, Token: `DAV:no-lock`, }}, }}, }, }, { "section 10.4.9", ` ( [W/"A weak ETag"]) (["strong ETag"])`, ifHeader{ lists: []ifList{{ resourceTag: `/resource1`, conditions: []Condition{{ Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }, { ETag: `W/"A weak ETag"`, }}, }, { resourceTag: `/resource1`, conditions: []Condition{{ ETag: `"strong ETag"`, }}, }}, }, }, { "section 10.4.10", ` ()`, ifHeader{ lists: []ifList{{ resourceTag: `http://www.example.com/specs/`, conditions: []Condition{{ Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }}, }}, }, }, { "section 10.4.11 #1", ` (["4217"])`, ifHeader{ lists: []ifList{{ resourceTag: `/specs/rfc2518.doc`, conditions: []Condition{{ ETag: `"4217"`, }}, }}, }, }, { "section 10.4.11 #2", ` (Not ["4217"])`, ifHeader{ lists: []ifList{{ resourceTag: `/specs/rfc2518.doc`, conditions: []Condition{{ Not: true, ETag: `"4217"`, }}, }}, }, }} for _, tc := range testCases { got, ok := parseIfHeader(strings.Replace(tc.input, "\n", "", -1)) if gotEmpty := reflect.DeepEqual(got, ifHeader{}); gotEmpty == ok { t.Errorf("%s: should be different: empty header == %t, ok == %t", tc.desc, gotEmpty, ok) continue } if !reflect.DeepEqual(got, tc.want) { t.Errorf("%s:\ngot %v\nwant %v", tc.desc, got, tc.want) continue } } } lxd-2.0.11/dist/src/golang.org/x/net/webdav/if.go0000644061062106075000000000757113172163402022522 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav // The If header is covered by Section 10.4. // http://www.webdav.org/specs/rfc4918.html#HEADER_If import ( "strings" ) // ifHeader is a disjunction (OR) of ifLists. type ifHeader struct { lists []ifList } // ifList is a conjunction (AND) of Conditions, and an optional resource tag. type ifList struct { resourceTag string conditions []Condition } // parseIfHeader parses the "If: foo bar" HTTP header. The httpHeader string // should omit the "If:" prefix and have any "\r\n"s collapsed to a " ", as is // returned by req.Header.Get("If") for a http.Request req. func parseIfHeader(httpHeader string) (h ifHeader, ok bool) { s := strings.TrimSpace(httpHeader) switch tokenType, _, _ := lex(s); tokenType { case '(': return parseNoTagLists(s) case angleTokenType: return parseTaggedLists(s) default: return ifHeader{}, false } } func parseNoTagLists(s string) (h ifHeader, ok bool) { for { l, remaining, ok := parseList(s) if !ok { return ifHeader{}, false } h.lists = append(h.lists, l) if remaining == "" { return h, true } s = remaining } } func parseTaggedLists(s string) (h ifHeader, ok bool) { resourceTag, n := "", 0 for first := true; ; first = false { tokenType, tokenStr, remaining := lex(s) switch tokenType { case angleTokenType: if !first && n == 0 { return ifHeader{}, false } resourceTag, n = tokenStr, 0 s = remaining case '(': n++ l, remaining, ok := parseList(s) if !ok { return ifHeader{}, false } l.resourceTag = resourceTag h.lists = append(h.lists, l) if remaining == "" { return h, true } s = remaining default: return ifHeader{}, false } } } func parseList(s string) (l ifList, remaining string, ok bool) { tokenType, _, s := lex(s) if tokenType != '(' { return ifList{}, "", false } for { tokenType, _, remaining = lex(s) if tokenType == ')' { if len(l.conditions) == 0 { return ifList{}, "", false } return l, remaining, true } c, remaining, ok := parseCondition(s) if !ok { return ifList{}, "", false } l.conditions = append(l.conditions, c) s = remaining } } func parseCondition(s string) (c Condition, remaining string, ok bool) { tokenType, tokenStr, s := lex(s) if tokenType == notTokenType { c.Not = true tokenType, tokenStr, s = lex(s) } switch tokenType { case strTokenType, angleTokenType: c.Token = tokenStr case squareTokenType: c.ETag = tokenStr default: return Condition{}, "", false } return c, s, true } // Single-rune tokens like '(' or ')' have a token type equal to their rune. // All other tokens have a negative token type. const ( errTokenType = rune(-1) eofTokenType = rune(-2) strTokenType = rune(-3) notTokenType = rune(-4) angleTokenType = rune(-5) squareTokenType = rune(-6) ) func lex(s string) (tokenType rune, tokenStr string, remaining string) { // The net/textproto Reader that parses the HTTP header will collapse // Linear White Space that spans multiple "\r\n" lines to a single " ", // so we don't need to look for '\r' or '\n'. for len(s) > 0 && (s[0] == '\t' || s[0] == ' ') { s = s[1:] } if len(s) == 0 { return eofTokenType, "", "" } i := 0 loop: for ; i < len(s); i++ { switch s[i] { case '\t', ' ', '(', ')', '<', '>', '[', ']': break loop } } if i != 0 { tokenStr, remaining = s[:i], s[i:] if tokenStr == "Not" { return notTokenType, "", remaining } return strTokenType, tokenStr, remaining } j := 0 switch s[0] { case '<': j, tokenType = strings.IndexByte(s, '>'), angleTokenType case '[': j, tokenType = strings.IndexByte(s, ']'), squareTokenType default: return rune(s[0]), "", s[1:] } if j < 0 { return errTokenType, "", "" } return tokenType, s[1:j], s[j+1:] } lxd-2.0.11/dist/src/golang.org/x/net/webdav/file_test.go0000644061062106075000000006654513172163402024110 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "encoding/xml" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "reflect" "runtime" "sort" "strconv" "strings" "testing" "golang.org/x/net/context" ) func TestSlashClean(t *testing.T) { testCases := []string{ "", ".", "/", "/./", "//", "//.", "//a", "/a", "/a/b/c", "/a//b/./../c/d/", "a", "a/b/c", } for _, tc := range testCases { got := slashClean(tc) want := path.Clean("/" + tc) if got != want { t.Errorf("tc=%q: got %q, want %q", tc, got, want) } } } func TestDirResolve(t *testing.T) { testCases := []struct { dir, name, want string }{ {"/", "", "/"}, {"/", "/", "/"}, {"/", ".", "/"}, {"/", "./a", "/a"}, {"/", "..", "/"}, {"/", "..", "/"}, {"/", "../", "/"}, {"/", "../.", "/"}, {"/", "../a", "/a"}, {"/", "../..", "/"}, {"/", "../bar/a", "/bar/a"}, {"/", "../baz/a", "/baz/a"}, {"/", "...", "/..."}, {"/", ".../a", "/.../a"}, {"/", ".../..", "/"}, {"/", "a", "/a"}, {"/", "a/./b", "/a/b"}, {"/", "a/../../b", "/b"}, {"/", "a/../b", "/b"}, {"/", "a/b", "/a/b"}, {"/", "a/b/c/../../d", "/a/d"}, {"/", "a/b/c/../../../d", "/d"}, {"/", "a/b/c/../../../../d", "/d"}, {"/", "a/b/c/d", "/a/b/c/d"}, {"/foo/bar", "", "/foo/bar"}, {"/foo/bar", "/", "/foo/bar"}, {"/foo/bar", ".", "/foo/bar"}, {"/foo/bar", "./a", "/foo/bar/a"}, {"/foo/bar", "..", "/foo/bar"}, {"/foo/bar", "../", "/foo/bar"}, {"/foo/bar", "../.", "/foo/bar"}, {"/foo/bar", "../a", "/foo/bar/a"}, {"/foo/bar", "../..", "/foo/bar"}, {"/foo/bar", "../bar/a", "/foo/bar/bar/a"}, {"/foo/bar", "../baz/a", "/foo/bar/baz/a"}, {"/foo/bar", "...", "/foo/bar/..."}, {"/foo/bar", ".../a", "/foo/bar/.../a"}, {"/foo/bar", ".../..", "/foo/bar"}, {"/foo/bar", "a", "/foo/bar/a"}, {"/foo/bar", "a/./b", "/foo/bar/a/b"}, {"/foo/bar", "a/../../b", "/foo/bar/b"}, {"/foo/bar", "a/../b", "/foo/bar/b"}, {"/foo/bar", "a/b", "/foo/bar/a/b"}, {"/foo/bar", "a/b/c/../../d", "/foo/bar/a/d"}, {"/foo/bar", "a/b/c/../../../d", "/foo/bar/d"}, {"/foo/bar", "a/b/c/../../../../d", "/foo/bar/d"}, {"/foo/bar", "a/b/c/d", "/foo/bar/a/b/c/d"}, {"/foo/bar/", "", "/foo/bar"}, {"/foo/bar/", "/", "/foo/bar"}, {"/foo/bar/", ".", "/foo/bar"}, {"/foo/bar/", "./a", "/foo/bar/a"}, {"/foo/bar/", "..", "/foo/bar"}, {"/foo//bar///", "", "/foo/bar"}, {"/foo//bar///", "/", "/foo/bar"}, {"/foo//bar///", ".", "/foo/bar"}, {"/foo//bar///", "./a", "/foo/bar/a"}, {"/foo//bar///", "..", "/foo/bar"}, {"/x/y/z", "ab/c\x00d/ef", ""}, {".", "", "."}, {".", "/", "."}, {".", ".", "."}, {".", "./a", "a"}, {".", "..", "."}, {".", "..", "."}, {".", "../", "."}, {".", "../.", "."}, {".", "../a", "a"}, {".", "../..", "."}, {".", "../bar/a", "bar/a"}, {".", "../baz/a", "baz/a"}, {".", "...", "..."}, {".", ".../a", ".../a"}, {".", ".../..", "."}, {".", "a", "a"}, {".", "a/./b", "a/b"}, {".", "a/../../b", "b"}, {".", "a/../b", "b"}, {".", "a/b", "a/b"}, {".", "a/b/c/../../d", "a/d"}, {".", "a/b/c/../../../d", "d"}, {".", "a/b/c/../../../../d", "d"}, {".", "a/b/c/d", "a/b/c/d"}, {"", "", "."}, {"", "/", "."}, {"", ".", "."}, {"", "./a", "a"}, {"", "..", "."}, } for _, tc := range testCases { d := Dir(filepath.FromSlash(tc.dir)) if got := filepath.ToSlash(d.resolve(tc.name)); got != tc.want { t.Errorf("dir=%q, name=%q: got %q, want %q", tc.dir, tc.name, got, tc.want) } } } func TestWalk(t *testing.T) { type walkStep struct { name, frag string final bool } testCases := []struct { dir string want []walkStep }{ {"", []walkStep{ {"", "", true}, }}, {"/", []walkStep{ {"", "", true}, }}, {"/a", []walkStep{ {"", "a", true}, }}, {"/a/", []walkStep{ {"", "a", true}, }}, {"/a/b", []walkStep{ {"", "a", false}, {"a", "b", true}, }}, {"/a/b/", []walkStep{ {"", "a", false}, {"a", "b", true}, }}, {"/a/b/c", []walkStep{ {"", "a", false}, {"a", "b", false}, {"b", "c", true}, }}, // The following test case is the one mentioned explicitly // in the method description. {"/foo/bar/x", []walkStep{ {"", "foo", false}, {"foo", "bar", false}, {"bar", "x", true}, }}, } ctx := context.Background() for _, tc := range testCases { fs := NewMemFS().(*memFS) parts := strings.Split(tc.dir, "/") for p := 2; p < len(parts); p++ { d := strings.Join(parts[:p], "/") if err := fs.Mkdir(ctx, d, 0666); err != nil { t.Errorf("tc.dir=%q: mkdir: %q: %v", tc.dir, d, err) } } i, prevFrag := 0, "" err := fs.walk("test", tc.dir, func(dir *memFSNode, frag string, final bool) error { got := walkStep{ name: prevFrag, frag: frag, final: final, } want := tc.want[i] if got != want { return fmt.Errorf("got %+v, want %+v", got, want) } i, prevFrag = i+1, frag return nil }) if err != nil { t.Errorf("tc.dir=%q: %v", tc.dir, err) } } } // find appends to ss the names of the named file and its children. It is // analogous to the Unix find command. // // The returned strings are not guaranteed to be in any particular order. func find(ctx context.Context, ss []string, fs FileSystem, name string) ([]string, error) { stat, err := fs.Stat(ctx, name) if err != nil { return nil, err } ss = append(ss, name) if stat.IsDir() { f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0) if err != nil { return nil, err } defer f.Close() children, err := f.Readdir(-1) if err != nil { return nil, err } for _, c := range children { ss, err = find(ctx, ss, fs, path.Join(name, c.Name())) if err != nil { return nil, err } } } return ss, nil } func testFS(t *testing.T, fs FileSystem) { errStr := func(err error) string { switch { case os.IsExist(err): return "errExist" case os.IsNotExist(err): return "errNotExist" case err != nil: return "err" } return "ok" } // The non-"find" non-"stat" test cases should change the file system state. The // indentation of the "find"s and "stat"s helps distinguish such test cases. testCases := []string{ " stat / want dir", " stat /a want errNotExist", " stat /d want errNotExist", " stat /d/e want errNotExist", "create /a A want ok", " stat /a want 1", "create /d/e EEE want errNotExist", "mk-dir /a want errExist", "mk-dir /d/m want errNotExist", "mk-dir /d want ok", " stat /d want dir", "create /d/e EEE want ok", " stat /d/e want 3", " find / /a /d /d/e", "create /d/f FFFF want ok", "create /d/g GGGGGGG want ok", "mk-dir /d/m want ok", "mk-dir /d/m want errExist", "create /d/m/p PPPPP want ok", " stat /d/e want 3", " stat /d/f want 4", " stat /d/g want 7", " stat /d/h want errNotExist", " stat /d/m want dir", " stat /d/m/p want 5", " find / /a /d /d/e /d/f /d/g /d/m /d/m/p", "rm-all /d want ok", " stat /a want 1", " stat /d want errNotExist", " stat /d/e want errNotExist", " stat /d/f want errNotExist", " stat /d/g want errNotExist", " stat /d/m want errNotExist", " stat /d/m/p want errNotExist", " find / /a", "mk-dir /d/m want errNotExist", "mk-dir /d want ok", "create /d/f FFFF want ok", "rm-all /d/f want ok", "mk-dir /d/m want ok", "rm-all /z want ok", "rm-all / want err", "create /b BB want ok", " stat / want dir", " stat /a want 1", " stat /b want 2", " stat /c want errNotExist", " stat /d want dir", " stat /d/m want dir", " find / /a /b /d /d/m", "move__ o=F /b /c want ok", " stat /b want errNotExist", " stat /c want 2", " stat /d/m want dir", " stat /d/n want errNotExist", " find / /a /c /d /d/m", "move__ o=F /d/m /d/n want ok", "create /d/n/q QQQQ want ok", " stat /d/m want errNotExist", " stat /d/n want dir", " stat /d/n/q want 4", "move__ o=F /d /d/n/z want err", "move__ o=T /c /d/n/q want ok", " stat /c want errNotExist", " stat /d/n/q want 2", " find / /a /d /d/n /d/n/q", "create /d/n/r RRRRR want ok", "mk-dir /u want ok", "mk-dir /u/v want ok", "move__ o=F /d/n /u want errExist", "create /t TTTTTT want ok", "move__ o=F /d/n /t want errExist", "rm-all /t want ok", "move__ o=F /d/n /t want ok", " stat /d want dir", " stat /d/n want errNotExist", " stat /d/n/r want errNotExist", " stat /t want dir", " stat /t/q want 2", " stat /t/r want 5", " find / /a /d /t /t/q /t/r /u /u/v", "move__ o=F /t / want errExist", "move__ o=T /t /u/v want ok", " stat /u/v/r want 5", "move__ o=F / /z want err", " find / /a /d /u /u/v /u/v/q /u/v/r", " stat /a want 1", " stat /b want errNotExist", " stat /c want errNotExist", " stat /u/v/r want 5", "copy__ o=F d=0 /a /b want ok", "copy__ o=T d=0 /a /c want ok", " stat /a want 1", " stat /b want 1", " stat /c want 1", " stat /u/v/r want 5", "copy__ o=F d=0 /u/v/r /b want errExist", " stat /b want 1", "copy__ o=T d=0 /u/v/r /b want ok", " stat /a want 1", " stat /b want 5", " stat /u/v/r want 5", "rm-all /a want ok", "rm-all /b want ok", "mk-dir /u/v/w want ok", "create /u/v/w/s SSSSSSSS want ok", " stat /d want dir", " stat /d/x want errNotExist", " stat /d/y want errNotExist", " stat /u/v/r want 5", " stat /u/v/w/s want 8", " find / /c /d /u /u/v /u/v/q /u/v/r /u/v/w /u/v/w/s", "copy__ o=T d=0 /u/v /d/x want ok", "copy__ o=T d=∞ /u/v /d/y want ok", "rm-all /u want ok", " stat /d/x want dir", " stat /d/x/q want errNotExist", " stat /d/x/r want errNotExist", " stat /d/x/w want errNotExist", " stat /d/x/w/s want errNotExist", " stat /d/y want dir", " stat /d/y/q want 2", " stat /d/y/r want 5", " stat /d/y/w want dir", " stat /d/y/w/s want 8", " stat /u want errNotExist", " find / /c /d /d/x /d/y /d/y/q /d/y/r /d/y/w /d/y/w/s", "copy__ o=F d=∞ /d/y /d/x want errExist", } ctx := context.Background() for i, tc := range testCases { tc = strings.TrimSpace(tc) j := strings.IndexByte(tc, ' ') if j < 0 { t.Fatalf("test case #%d %q: invalid command", i, tc) } op, arg := tc[:j], tc[j+1:] switch op { default: t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) case "create": parts := strings.Split(arg, " ") if len(parts) != 4 || parts[2] != "want" { t.Fatalf("test case #%d %q: invalid write", i, tc) } f, opErr := fs.OpenFile(ctx, parts[0], os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if got := errStr(opErr); got != parts[3] { t.Fatalf("test case #%d %q: OpenFile: got %q (%v), want %q", i, tc, got, opErr, parts[3]) } if f != nil { if _, err := f.Write([]byte(parts[1])); err != nil { t.Fatalf("test case #%d %q: Write: %v", i, tc, err) } if err := f.Close(); err != nil { t.Fatalf("test case #%d %q: Close: %v", i, tc, err) } } case "find": got, err := find(ctx, nil, fs, "/") if err != nil { t.Fatalf("test case #%d %q: find: %v", i, tc, err) } sort.Strings(got) want := strings.Split(arg, " ") if !reflect.DeepEqual(got, want) { t.Fatalf("test case #%d %q:\ngot %s\nwant %s", i, tc, got, want) } case "copy__", "mk-dir", "move__", "rm-all", "stat": nParts := 3 switch op { case "copy__": nParts = 6 case "move__": nParts = 5 } parts := strings.Split(arg, " ") if len(parts) != nParts { t.Fatalf("test case #%d %q: invalid %s", i, tc, op) } got, opErr := "", error(nil) switch op { case "copy__": depth := 0 if parts[1] == "d=∞" { depth = infiniteDepth } _, opErr = copyFiles(ctx, fs, parts[2], parts[3], parts[0] == "o=T", depth, 0) case "mk-dir": opErr = fs.Mkdir(ctx, parts[0], 0777) case "move__": _, opErr = moveFiles(ctx, fs, parts[1], parts[2], parts[0] == "o=T") case "rm-all": opErr = fs.RemoveAll(ctx, parts[0]) case "stat": var stat os.FileInfo fileName := parts[0] if stat, opErr = fs.Stat(ctx, fileName); opErr == nil { if stat.IsDir() { got = "dir" } else { got = strconv.Itoa(int(stat.Size())) } if fileName == "/" { // For a Dir FileSystem, the virtual file system root maps to a // real file system name like "/tmp/webdav-test012345", which does // not end with "/". We skip such cases. } else if statName := stat.Name(); path.Base(fileName) != statName { t.Fatalf("test case #%d %q: file name %q inconsistent with stat name %q", i, tc, fileName, statName) } } } if got == "" { got = errStr(opErr) } if parts[len(parts)-2] != "want" { t.Fatalf("test case #%d %q: invalid %s", i, tc, op) } if want := parts[len(parts)-1]; got != want { t.Fatalf("test case #%d %q: got %q (%v), want %q", i, tc, got, opErr, want) } } } } func TestDir(t *testing.T) { switch runtime.GOOS { case "nacl": t.Skip("see golang.org/issue/12004") case "plan9": t.Skip("see golang.org/issue/11453") } td, err := ioutil.TempDir("", "webdav-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(td) testFS(t, Dir(td)) } func TestMemFS(t *testing.T) { testFS(t, NewMemFS()) } func TestMemFSRoot(t *testing.T) { ctx := context.Background() fs := NewMemFS() for i := 0; i < 5; i++ { stat, err := fs.Stat(ctx, "/") if err != nil { t.Fatalf("i=%d: Stat: %v", i, err) } if !stat.IsDir() { t.Fatalf("i=%d: Stat.IsDir is false, want true", i) } f, err := fs.OpenFile(ctx, "/", os.O_RDONLY, 0) if err != nil { t.Fatalf("i=%d: OpenFile: %v", i, err) } defer f.Close() children, err := f.Readdir(-1) if err != nil { t.Fatalf("i=%d: Readdir: %v", i, err) } if len(children) != i { t.Fatalf("i=%d: got %d children, want %d", i, len(children), i) } if _, err := f.Write(make([]byte, 1)); err == nil { t.Fatalf("i=%d: Write: got nil error, want non-nil", i) } if err := fs.Mkdir(ctx, fmt.Sprintf("/dir%d", i), 0777); err != nil { t.Fatalf("i=%d: Mkdir: %v", i, err) } } } func TestMemFileReaddir(t *testing.T) { ctx := context.Background() fs := NewMemFS() if err := fs.Mkdir(ctx, "/foo", 0777); err != nil { t.Fatalf("Mkdir: %v", err) } readdir := func(count int) ([]os.FileInfo, error) { f, err := fs.OpenFile(ctx, "/foo", os.O_RDONLY, 0) if err != nil { t.Fatalf("OpenFile: %v", err) } defer f.Close() return f.Readdir(count) } if got, err := readdir(-1); len(got) != 0 || err != nil { t.Fatalf("readdir(-1): got %d fileInfos with err=%v, want 0, ", len(got), err) } if got, err := readdir(+1); len(got) != 0 || err != io.EOF { t.Fatalf("readdir(+1): got %d fileInfos with err=%v, want 0, EOF", len(got), err) } } func TestMemFile(t *testing.T) { testCases := []string{ "wantData ", "wantSize 0", "write abc", "wantData abc", "write de", "wantData abcde", "wantSize 5", "write 5*x", "write 4*y+2*z", "write 3*st", "wantData abcdexxxxxyyyyzzststst", "wantSize 22", "seek set 4 want 4", "write EFG", "wantData abcdEFGxxxyyyyzzststst", "wantSize 22", "seek set 2 want 2", "read cdEF", "read Gx", "seek cur 0 want 8", "seek cur 2 want 10", "seek cur -1 want 9", "write J", "wantData abcdEFGxxJyyyyzzststst", "wantSize 22", "seek cur -4 want 6", "write ghijk", "wantData abcdEFghijkyyyzzststst", "wantSize 22", "read yyyz", "seek cur 0 want 15", "write ", "seek cur 0 want 15", "read ", "seek cur 0 want 15", "seek end -3 want 19", "write ZZ", "wantData abcdEFghijkyyyzzstsZZt", "wantSize 22", "write 4*A", "wantData abcdEFghijkyyyzzstsZZAAAA", "wantSize 25", "seek end 0 want 25", "seek end -5 want 20", "read Z+4*A", "write 5*B", "wantData abcdEFghijkyyyzzstsZZAAAABBBBB", "wantSize 30", "seek end 10 want 40", "write C", "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........C", "wantSize 41", "write D", "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........CD", "wantSize 42", "seek set 43 want 43", "write E", "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........CD.E", "wantSize 44", "seek set 0 want 0", "write 5*123456789_", "wantData 123456789_123456789_123456789_123456789_123456789_", "wantSize 50", "seek cur 0 want 50", "seek cur -99 want err", } ctx := context.Background() const filename = "/foo" fs := NewMemFS() f, err := fs.OpenFile(ctx, filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { t.Fatalf("OpenFile: %v", err) } defer f.Close() for i, tc := range testCases { j := strings.IndexByte(tc, ' ') if j < 0 { t.Fatalf("test case #%d %q: invalid command", i, tc) } op, arg := tc[:j], tc[j+1:] // Expand an arg like "3*a+2*b" to "aaabb". parts := strings.Split(arg, "+") for j, part := range parts { if k := strings.IndexByte(part, '*'); k >= 0 { repeatCount, repeatStr := part[:k], part[k+1:] n, err := strconv.Atoi(repeatCount) if err != nil { t.Fatalf("test case #%d %q: invalid repeat count %q", i, tc, repeatCount) } parts[j] = strings.Repeat(repeatStr, n) } } arg = strings.Join(parts, "") switch op { default: t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) case "read": buf := make([]byte, len(arg)) if _, err := io.ReadFull(f, buf); err != nil { t.Fatalf("test case #%d %q: ReadFull: %v", i, tc, err) } if got := string(buf); got != arg { t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, arg) } case "seek": parts := strings.Split(arg, " ") if len(parts) != 4 { t.Fatalf("test case #%d %q: invalid seek", i, tc) } whence := 0 switch parts[0] { default: t.Fatalf("test case #%d %q: invalid seek whence", i, tc) case "set": whence = os.SEEK_SET case "cur": whence = os.SEEK_CUR case "end": whence = os.SEEK_END } offset, err := strconv.Atoi(parts[1]) if err != nil { t.Fatalf("test case #%d %q: invalid offset %q", i, tc, parts[1]) } if parts[2] != "want" { t.Fatalf("test case #%d %q: invalid seek", i, tc) } if parts[3] == "err" { _, err := f.Seek(int64(offset), whence) if err == nil { t.Fatalf("test case #%d %q: Seek returned nil error, want non-nil", i, tc) } } else { got, err := f.Seek(int64(offset), whence) if err != nil { t.Fatalf("test case #%d %q: Seek: %v", i, tc, err) } want, err := strconv.Atoi(parts[3]) if err != nil { t.Fatalf("test case #%d %q: invalid want %q", i, tc, parts[3]) } if got != int64(want) { t.Fatalf("test case #%d %q: got %d, want %d", i, tc, got, want) } } case "write": n, err := f.Write([]byte(arg)) if err != nil { t.Fatalf("test case #%d %q: write: %v", i, tc, err) } if n != len(arg) { t.Fatalf("test case #%d %q: write returned %d bytes, want %d", i, tc, n, len(arg)) } case "wantData": g, err := fs.OpenFile(ctx, filename, os.O_RDONLY, 0666) if err != nil { t.Fatalf("test case #%d %q: OpenFile: %v", i, tc, err) } gotBytes, err := ioutil.ReadAll(g) if err != nil { t.Fatalf("test case #%d %q: ReadAll: %v", i, tc, err) } for i, c := range gotBytes { if c == '\x00' { gotBytes[i] = '.' } } got := string(gotBytes) if got != arg { t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, arg) } if err := g.Close(); err != nil { t.Fatalf("test case #%d %q: Close: %v", i, tc, err) } case "wantSize": n, err := strconv.Atoi(arg) if err != nil { t.Fatalf("test case #%d %q: invalid size %q", i, tc, arg) } fi, err := fs.Stat(ctx, filename) if err != nil { t.Fatalf("test case #%d %q: Stat: %v", i, tc, err) } if got, want := fi.Size(), int64(n); got != want { t.Fatalf("test case #%d %q: got %d, want %d", i, tc, got, want) } } } } // TestMemFileWriteAllocs tests that writing N consecutive 1KiB chunks to a // memFile doesn't allocate a new buffer for each of those N times. Otherwise, // calling io.Copy(aMemFile, src) is likely to have quadratic complexity. func TestMemFileWriteAllocs(t *testing.T) { if runtime.Compiler == "gccgo" { t.Skip("gccgo allocates here") } ctx := context.Background() fs := NewMemFS() f, err := fs.OpenFile(ctx, "/xxx", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { t.Fatalf("OpenFile: %v", err) } defer f.Close() xxx := make([]byte, 1024) for i := range xxx { xxx[i] = 'x' } a := testing.AllocsPerRun(100, func() { f.Write(xxx) }) // AllocsPerRun returns an integral value, so we compare the rounded-down // number to zero. if a > 0 { t.Fatalf("%v allocs per run, want 0", a) } } func BenchmarkMemFileWrite(b *testing.B) { ctx := context.Background() fs := NewMemFS() xxx := make([]byte, 1024) for i := range xxx { xxx[i] = 'x' } b.ResetTimer() for i := 0; i < b.N; i++ { f, err := fs.OpenFile(ctx, "/xxx", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { b.Fatalf("OpenFile: %v", err) } for j := 0; j < 100; j++ { f.Write(xxx) } if err := f.Close(); err != nil { b.Fatalf("Close: %v", err) } if err := fs.RemoveAll(ctx, "/xxx"); err != nil { b.Fatalf("RemoveAll: %v", err) } } } func TestCopyMoveProps(t *testing.T) { ctx := context.Background() fs := NewMemFS() create := func(name string) error { f, err := fs.OpenFile(ctx, name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return err } _, wErr := f.Write([]byte("contents")) cErr := f.Close() if wErr != nil { return wErr } return cErr } patch := func(name string, patches ...Proppatch) error { f, err := fs.OpenFile(ctx, name, os.O_RDWR, 0666) if err != nil { return err } _, pErr := f.(DeadPropsHolder).Patch(patches) cErr := f.Close() if pErr != nil { return pErr } return cErr } props := func(name string) (map[xml.Name]Property, error) { f, err := fs.OpenFile(ctx, name, os.O_RDWR, 0666) if err != nil { return nil, err } m, pErr := f.(DeadPropsHolder).DeadProps() cErr := f.Close() if pErr != nil { return nil, pErr } if cErr != nil { return nil, cErr } return m, nil } p0 := Property{ XMLName: xml.Name{Space: "x:", Local: "boat"}, InnerXML: []byte("pea-green"), } p1 := Property{ XMLName: xml.Name{Space: "x:", Local: "ring"}, InnerXML: []byte("1 shilling"), } p2 := Property{ XMLName: xml.Name{Space: "x:", Local: "spoon"}, InnerXML: []byte("runcible"), } p3 := Property{ XMLName: xml.Name{Space: "x:", Local: "moon"}, InnerXML: []byte("light"), } if err := create("/src"); err != nil { t.Fatalf("create /src: %v", err) } if err := patch("/src", Proppatch{Props: []Property{p0, p1}}); err != nil { t.Fatalf("patch /src +p0 +p1: %v", err) } if _, err := copyFiles(ctx, fs, "/src", "/tmp", true, infiniteDepth, 0); err != nil { t.Fatalf("copyFiles /src /tmp: %v", err) } if _, err := moveFiles(ctx, fs, "/tmp", "/dst", true); err != nil { t.Fatalf("moveFiles /tmp /dst: %v", err) } if err := patch("/src", Proppatch{Props: []Property{p0}, Remove: true}); err != nil { t.Fatalf("patch /src -p0: %v", err) } if err := patch("/src", Proppatch{Props: []Property{p2}}); err != nil { t.Fatalf("patch /src +p2: %v", err) } if err := patch("/dst", Proppatch{Props: []Property{p1}, Remove: true}); err != nil { t.Fatalf("patch /dst -p1: %v", err) } if err := patch("/dst", Proppatch{Props: []Property{p3}}); err != nil { t.Fatalf("patch /dst +p3: %v", err) } gotSrc, err := props("/src") if err != nil { t.Fatalf("props /src: %v", err) } wantSrc := map[xml.Name]Property{ p1.XMLName: p1, p2.XMLName: p2, } if !reflect.DeepEqual(gotSrc, wantSrc) { t.Fatalf("props /src:\ngot %v\nwant %v", gotSrc, wantSrc) } gotDst, err := props("/dst") if err != nil { t.Fatalf("props /dst: %v", err) } wantDst := map[xml.Name]Property{ p0.XMLName: p0, p3.XMLName: p3, } if !reflect.DeepEqual(gotDst, wantDst) { t.Fatalf("props /dst:\ngot %v\nwant %v", gotDst, wantDst) } } func TestWalkFS(t *testing.T) { testCases := []struct { desc string buildfs []string startAt string depth int walkFn filepath.WalkFunc want []string }{{ "just root", []string{}, "/", infiniteDepth, nil, []string{ "/", }, }, { "infinite walk from root", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/d", "mkdir /e", "touch /f", }, "/", infiniteDepth, nil, []string{ "/", "/a", "/a/b", "/a/b/c", "/a/d", "/e", "/f", }, }, { "infinite walk from subdir", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/d", "mkdir /e", "touch /f", }, "/a", infiniteDepth, nil, []string{ "/a", "/a/b", "/a/b/c", "/a/d", }, }, { "depth 1 walk from root", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/d", "mkdir /e", "touch /f", }, "/", 1, nil, []string{ "/", "/a", "/e", "/f", }, }, { "depth 1 walk from subdir", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/b/g", "mkdir /a/b/g/h", "touch /a/b/g/i", "touch /a/b/g/h/j", }, "/a/b", 1, nil, []string{ "/a/b", "/a/b/c", "/a/b/g", }, }, { "depth 0 walk from subdir", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/b/g", "mkdir /a/b/g/h", "touch /a/b/g/i", "touch /a/b/g/h/j", }, "/a/b", 0, nil, []string{ "/a/b", }, }, { "infinite walk from file", []string{ "mkdir /a", "touch /a/b", "touch /a/c", }, "/a/b", 0, nil, []string{ "/a/b", }, }, { "infinite walk with skipped subdir", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/b/g", "mkdir /a/b/g/h", "touch /a/b/g/i", "touch /a/b/g/h/j", "touch /a/b/z", }, "/", infiniteDepth, func(path string, info os.FileInfo, err error) error { if path == "/a/b/g" { return filepath.SkipDir } return nil }, []string{ "/", "/a", "/a/b", "/a/b/c", "/a/b/z", }, }} ctx := context.Background() for _, tc := range testCases { fs, err := buildTestFS(tc.buildfs) if err != nil { t.Fatalf("%s: cannot create test filesystem: %v", tc.desc, err) } var got []string traceFn := func(path string, info os.FileInfo, err error) error { if tc.walkFn != nil { err = tc.walkFn(path, info, err) if err != nil { return err } } got = append(got, path) return nil } fi, err := fs.Stat(ctx, tc.startAt) if err != nil { t.Fatalf("%s: cannot stat: %v", tc.desc, err) } err = walkFS(ctx, fs, tc.depth, tc.startAt, fi, traceFn) if err != nil { t.Errorf("%s:\ngot error %v, want nil", tc.desc, err) continue } sort.Strings(got) sort.Strings(tc.want) if !reflect.DeepEqual(got, tc.want) { t.Errorf("%s:\ngot %q\nwant %q", tc.desc, got, tc.want) continue } } } func buildTestFS(buildfs []string) (FileSystem, error) { // TODO: Could this be merged with the build logic in TestFS? ctx := context.Background() fs := NewMemFS() for _, b := range buildfs { op := strings.Split(b, " ") switch op[0] { case "mkdir": err := fs.Mkdir(ctx, op[1], os.ModeDir|0777) if err != nil { return nil, err } case "touch": f, err := fs.OpenFile(ctx, op[1], os.O_RDWR|os.O_CREATE, 0666) if err != nil { return nil, err } f.Close() case "write": f, err := fs.OpenFile(ctx, op[1], os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return nil, err } _, err = f.Write([]byte(op[2])) f.Close() if err != nil { return nil, err } default: return nil, fmt.Errorf("unknown file operation %q", op[0]) } } return fs, nil } lxd-2.0.11/dist/src/golang.org/x/net/webdav/file_go1.7.go0000644061062106075000000000045513172163402023750 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package webdav import ( "context" "net/http" ) func getContext(r *http.Request) context.Context { return r.Context() } lxd-2.0.11/dist/src/golang.org/x/net/webdav/file_go1.6.go0000644061062106075000000000051113172163402023740 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package webdav import ( "net/http" "golang.org/x/net/context" ) func getContext(r *http.Request) context.Context { return context.Background() } lxd-2.0.11/dist/src/golang.org/x/net/webdav/file.go0000644061062106075000000004736113172163402023044 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webdav import ( "encoding/xml" "io" "net/http" "os" "path" "path/filepath" "strings" "sync" "time" "golang.org/x/net/context" ) // slashClean is equivalent to but slightly more efficient than // path.Clean("/" + name). func slashClean(name string) string { if name == "" || name[0] != '/' { name = "/" + name } return path.Clean(name) } // A FileSystem implements access to a collection of named files. The elements // in a file path are separated by slash ('/', U+002F) characters, regardless // of host operating system convention. // // Each method has the same semantics as the os package's function of the same // name. // // Note that the os.Rename documentation says that "OS-specific restrictions // might apply". In particular, whether or not renaming a file or directory // overwriting another existing file or directory is an error is OS-dependent. type FileSystem interface { Mkdir(ctx context.Context, name string, perm os.FileMode) error OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) RemoveAll(ctx context.Context, name string) error Rename(ctx context.Context, oldName, newName string) error Stat(ctx context.Context, name string) (os.FileInfo, error) } // A File is returned by a FileSystem's OpenFile method and can be served by a // Handler. // // A File may optionally implement the DeadPropsHolder interface, if it can // load and save dead properties. type File interface { http.File io.Writer } // A Dir implements FileSystem using the native file system restricted to a // specific directory tree. // // While the FileSystem.OpenFile method takes '/'-separated paths, a Dir's // string value is a filename on the native file system, not a URL, so it is // separated by filepath.Separator, which isn't necessarily '/'. // // An empty Dir is treated as ".". type Dir string func (d Dir) resolve(name string) string { // This implementation is based on Dir.Open's code in the standard net/http package. if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 || strings.Contains(name, "\x00") { return "" } dir := string(d) if dir == "" { dir = "." } return filepath.Join(dir, filepath.FromSlash(slashClean(name))) } func (d Dir) Mkdir(ctx context.Context, name string, perm os.FileMode) error { if name = d.resolve(name); name == "" { return os.ErrNotExist } return os.Mkdir(name, perm) } func (d Dir) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) { if name = d.resolve(name); name == "" { return nil, os.ErrNotExist } f, err := os.OpenFile(name, flag, perm) if err != nil { return nil, err } return f, nil } func (d Dir) RemoveAll(ctx context.Context, name string) error { if name = d.resolve(name); name == "" { return os.ErrNotExist } if name == filepath.Clean(string(d)) { // Prohibit removing the virtual root directory. return os.ErrInvalid } return os.RemoveAll(name) } func (d Dir) Rename(ctx context.Context, oldName, newName string) error { if oldName = d.resolve(oldName); oldName == "" { return os.ErrNotExist } if newName = d.resolve(newName); newName == "" { return os.ErrNotExist } if root := filepath.Clean(string(d)); root == oldName || root == newName { // Prohibit renaming from or to the virtual root directory. return os.ErrInvalid } return os.Rename(oldName, newName) } func (d Dir) Stat(ctx context.Context, name string) (os.FileInfo, error) { if name = d.resolve(name); name == "" { return nil, os.ErrNotExist } return os.Stat(name) } // NewMemFS returns a new in-memory FileSystem implementation. func NewMemFS() FileSystem { return &memFS{ root: memFSNode{ children: make(map[string]*memFSNode), mode: 0660 | os.ModeDir, modTime: time.Now(), }, } } // A memFS implements FileSystem, storing all metadata and actual file data // in-memory. No limits on filesystem size are used, so it is not recommended // this be used where the clients are untrusted. // // Concurrent access is permitted. The tree structure is protected by a mutex, // and each node's contents and metadata are protected by a per-node mutex. // // TODO: Enforce file permissions. type memFS struct { mu sync.Mutex root memFSNode } // TODO: clean up and rationalize the walk/find code. // walk walks the directory tree for the fullname, calling f at each step. If f // returns an error, the walk will be aborted and return that same error. // // dir is the directory at that step, frag is the name fragment, and final is // whether it is the final step. For example, walking "/foo/bar/x" will result // in 3 calls to f: // - "/", "foo", false // - "/foo/", "bar", false // - "/foo/bar/", "x", true // The frag argument will be empty only if dir is the root node and the walk // ends at that root node. func (fs *memFS) walk(op, fullname string, f func(dir *memFSNode, frag string, final bool) error) error { original := fullname fullname = slashClean(fullname) // Strip any leading "/"s to make fullname a relative path, as the walk // starts at fs.root. if fullname[0] == '/' { fullname = fullname[1:] } dir := &fs.root for { frag, remaining := fullname, "" i := strings.IndexRune(fullname, '/') final := i < 0 if !final { frag, remaining = fullname[:i], fullname[i+1:] } if frag == "" && dir != &fs.root { panic("webdav: empty path fragment for a clean path") } if err := f(dir, frag, final); err != nil { return &os.PathError{ Op: op, Path: original, Err: err, } } if final { break } child := dir.children[frag] if child == nil { return &os.PathError{ Op: op, Path: original, Err: os.ErrNotExist, } } if !child.mode.IsDir() { return &os.PathError{ Op: op, Path: original, Err: os.ErrInvalid, } } dir, fullname = child, remaining } return nil } // find returns the parent of the named node and the relative name fragment // from the parent to the child. For example, if finding "/foo/bar/baz" then // parent will be the node for "/foo/bar" and frag will be "baz". // // If the fullname names the root node, then parent, frag and err will be zero. // // find returns an error if the parent does not already exist or the parent // isn't a directory, but it will not return an error per se if the child does // not already exist. The error returned is either nil or an *os.PathError // whose Op is op. func (fs *memFS) find(op, fullname string) (parent *memFSNode, frag string, err error) { err = fs.walk(op, fullname, func(parent0 *memFSNode, frag0 string, final bool) error { if !final { return nil } if frag0 != "" { parent, frag = parent0, frag0 } return nil }) return parent, frag, err } func (fs *memFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error { fs.mu.Lock() defer fs.mu.Unlock() dir, frag, err := fs.find("mkdir", name) if err != nil { return err } if dir == nil { // We can't create the root. return os.ErrInvalid } if _, ok := dir.children[frag]; ok { return os.ErrExist } dir.children[frag] = &memFSNode{ children: make(map[string]*memFSNode), mode: perm.Perm() | os.ModeDir, modTime: time.Now(), } return nil } func (fs *memFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) { fs.mu.Lock() defer fs.mu.Unlock() dir, frag, err := fs.find("open", name) if err != nil { return nil, err } var n *memFSNode if dir == nil { // We're opening the root. if flag&(os.O_WRONLY|os.O_RDWR) != 0 { return nil, os.ErrPermission } n, frag = &fs.root, "/" } else { n = dir.children[frag] if flag&(os.O_SYNC|os.O_APPEND) != 0 { // memFile doesn't support these flags yet. return nil, os.ErrInvalid } if flag&os.O_CREATE != 0 { if flag&os.O_EXCL != 0 && n != nil { return nil, os.ErrExist } if n == nil { n = &memFSNode{ mode: perm.Perm(), } dir.children[frag] = n } } if n == nil { return nil, os.ErrNotExist } if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 { n.mu.Lock() n.data = nil n.mu.Unlock() } } children := make([]os.FileInfo, 0, len(n.children)) for cName, c := range n.children { children = append(children, c.stat(cName)) } return &memFile{ n: n, nameSnapshot: frag, childrenSnapshot: children, }, nil } func (fs *memFS) RemoveAll(ctx context.Context, name string) error { fs.mu.Lock() defer fs.mu.Unlock() dir, frag, err := fs.find("remove", name) if err != nil { return err } if dir == nil { // We can't remove the root. return os.ErrInvalid } delete(dir.children, frag) return nil } func (fs *memFS) Rename(ctx context.Context, oldName, newName string) error { fs.mu.Lock() defer fs.mu.Unlock() oldName = slashClean(oldName) newName = slashClean(newName) if oldName == newName { return nil } if strings.HasPrefix(newName, oldName+"/") { // We can't rename oldName to be a sub-directory of itself. return os.ErrInvalid } oDir, oFrag, err := fs.find("rename", oldName) if err != nil { return err } if oDir == nil { // We can't rename from the root. return os.ErrInvalid } nDir, nFrag, err := fs.find("rename", newName) if err != nil { return err } if nDir == nil { // We can't rename to the root. return os.ErrInvalid } oNode, ok := oDir.children[oFrag] if !ok { return os.ErrNotExist } if oNode.children != nil { if nNode, ok := nDir.children[nFrag]; ok { if nNode.children == nil { return errNotADirectory } if len(nNode.children) != 0 { return errDirectoryNotEmpty } } } delete(oDir.children, oFrag) nDir.children[nFrag] = oNode return nil } func (fs *memFS) Stat(ctx context.Context, name string) (os.FileInfo, error) { fs.mu.Lock() defer fs.mu.Unlock() dir, frag, err := fs.find("stat", name) if err != nil { return nil, err } if dir == nil { // We're stat'ting the root. return fs.root.stat("/"), nil } if n, ok := dir.children[frag]; ok { return n.stat(path.Base(name)), nil } return nil, os.ErrNotExist } // A memFSNode represents a single entry in the in-memory filesystem and also // implements os.FileInfo. type memFSNode struct { // children is protected by memFS.mu. children map[string]*memFSNode mu sync.Mutex data []byte mode os.FileMode modTime time.Time deadProps map[xml.Name]Property } func (n *memFSNode) stat(name string) *memFileInfo { n.mu.Lock() defer n.mu.Unlock() return &memFileInfo{ name: name, size: int64(len(n.data)), mode: n.mode, modTime: n.modTime, } } func (n *memFSNode) DeadProps() (map[xml.Name]Property, error) { n.mu.Lock() defer n.mu.Unlock() if len(n.deadProps) == 0 { return nil, nil } ret := make(map[xml.Name]Property, len(n.deadProps)) for k, v := range n.deadProps { ret[k] = v } return ret, nil } func (n *memFSNode) Patch(patches []Proppatch) ([]Propstat, error) { n.mu.Lock() defer n.mu.Unlock() pstat := Propstat{Status: http.StatusOK} for _, patch := range patches { for _, p := range patch.Props { pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName}) if patch.Remove { delete(n.deadProps, p.XMLName) continue } if n.deadProps == nil { n.deadProps = map[xml.Name]Property{} } n.deadProps[p.XMLName] = p } } return []Propstat{pstat}, nil } type memFileInfo struct { name string size int64 mode os.FileMode modTime time.Time } func (f *memFileInfo) Name() string { return f.name } func (f *memFileInfo) Size() int64 { return f.size } func (f *memFileInfo) Mode() os.FileMode { return f.mode } func (f *memFileInfo) ModTime() time.Time { return f.modTime } func (f *memFileInfo) IsDir() bool { return f.mode.IsDir() } func (f *memFileInfo) Sys() interface{} { return nil } // A memFile is a File implementation for a memFSNode. It is a per-file (not // per-node) read/write position, and a snapshot of the memFS' tree structure // (a node's name and children) for that node. type memFile struct { n *memFSNode nameSnapshot string childrenSnapshot []os.FileInfo // pos is protected by n.mu. pos int } // A *memFile implements the optional DeadPropsHolder interface. var _ DeadPropsHolder = (*memFile)(nil) func (f *memFile) DeadProps() (map[xml.Name]Property, error) { return f.n.DeadProps() } func (f *memFile) Patch(patches []Proppatch) ([]Propstat, error) { return f.n.Patch(patches) } func (f *memFile) Close() error { return nil } func (f *memFile) Read(p []byte) (int, error) { f.n.mu.Lock() defer f.n.mu.Unlock() if f.n.mode.IsDir() { return 0, os.ErrInvalid } if f.pos >= len(f.n.data) { return 0, io.EOF } n := copy(p, f.n.data[f.pos:]) f.pos += n return n, nil } func (f *memFile) Readdir(count int) ([]os.FileInfo, error) { f.n.mu.Lock() defer f.n.mu.Unlock() if !f.n.mode.IsDir() { return nil, os.ErrInvalid } old := f.pos if old >= len(f.childrenSnapshot) { // The os.File Readdir docs say that at the end of a directory, // the error is io.EOF if count > 0 and nil if count <= 0. if count > 0 { return nil, io.EOF } return nil, nil } if count > 0 { f.pos += count if f.pos > len(f.childrenSnapshot) { f.pos = len(f.childrenSnapshot) } } else { f.pos = len(f.childrenSnapshot) old = 0 } return f.childrenSnapshot[old:f.pos], nil } func (f *memFile) Seek(offset int64, whence int) (int64, error) { f.n.mu.Lock() defer f.n.mu.Unlock() npos := f.pos // TODO: How to handle offsets greater than the size of system int? switch whence { case os.SEEK_SET: npos = int(offset) case os.SEEK_CUR: npos += int(offset) case os.SEEK_END: npos = len(f.n.data) + int(offset) default: npos = -1 } if npos < 0 { return 0, os.ErrInvalid } f.pos = npos return int64(f.pos), nil } func (f *memFile) Stat() (os.FileInfo, error) { return f.n.stat(f.nameSnapshot), nil } func (f *memFile) Write(p []byte) (int, error) { lenp := len(p) f.n.mu.Lock() defer f.n.mu.Unlock() if f.n.mode.IsDir() { return 0, os.ErrInvalid } if f.pos < len(f.n.data) { n := copy(f.n.data[f.pos:], p) f.pos += n p = p[n:] } else if f.pos > len(f.n.data) { // Write permits the creation of holes, if we've seek'ed past the // existing end of file. if f.pos <= cap(f.n.data) { oldLen := len(f.n.data) f.n.data = f.n.data[:f.pos] hole := f.n.data[oldLen:] for i := range hole { hole[i] = 0 } } else { d := make([]byte, f.pos, f.pos+len(p)) copy(d, f.n.data) f.n.data = d } } if len(p) > 0 { // We should only get here if f.pos == len(f.n.data). f.n.data = append(f.n.data, p...) f.pos = len(f.n.data) } f.n.modTime = time.Now() return lenp, nil } // moveFiles moves files and/or directories from src to dst. // // See section 9.9.4 for when various HTTP status codes apply. func moveFiles(ctx context.Context, fs FileSystem, src, dst string, overwrite bool) (status int, err error) { created := false if _, err := fs.Stat(ctx, dst); err != nil { if !os.IsNotExist(err) { return http.StatusForbidden, err } created = true } else if overwrite { // Section 9.9.3 says that "If a resource exists at the destination // and the Overwrite header is "T", then prior to performing the move, // the server must perform a DELETE with "Depth: infinity" on the // destination resource. if err := fs.RemoveAll(ctx, dst); err != nil { return http.StatusForbidden, err } } else { return http.StatusPreconditionFailed, os.ErrExist } if err := fs.Rename(ctx, src, dst); err != nil { return http.StatusForbidden, err } if created { return http.StatusCreated, nil } return http.StatusNoContent, nil } func copyProps(dst, src File) error { d, ok := dst.(DeadPropsHolder) if !ok { return nil } s, ok := src.(DeadPropsHolder) if !ok { return nil } m, err := s.DeadProps() if err != nil { return err } props := make([]Property, 0, len(m)) for _, prop := range m { props = append(props, prop) } _, err = d.Patch([]Proppatch{{Props: props}}) return err } // copyFiles copies files and/or directories from src to dst. // // See section 9.8.5 for when various HTTP status codes apply. func copyFiles(ctx context.Context, fs FileSystem, src, dst string, overwrite bool, depth int, recursion int) (status int, err error) { if recursion == 1000 { return http.StatusInternalServerError, errRecursionTooDeep } recursion++ // TODO: section 9.8.3 says that "Note that an infinite-depth COPY of /A/ // into /A/B/ could lead to infinite recursion if not handled correctly." srcFile, err := fs.OpenFile(ctx, src, os.O_RDONLY, 0) if err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusInternalServerError, err } defer srcFile.Close() srcStat, err := srcFile.Stat() if err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusInternalServerError, err } srcPerm := srcStat.Mode() & os.ModePerm created := false if _, err := fs.Stat(ctx, dst); err != nil { if os.IsNotExist(err) { created = true } else { return http.StatusForbidden, err } } else { if !overwrite { return http.StatusPreconditionFailed, os.ErrExist } if err := fs.RemoveAll(ctx, dst); err != nil && !os.IsNotExist(err) { return http.StatusForbidden, err } } if srcStat.IsDir() { if err := fs.Mkdir(ctx, dst, srcPerm); err != nil { return http.StatusForbidden, err } if depth == infiniteDepth { children, err := srcFile.Readdir(-1) if err != nil { return http.StatusForbidden, err } for _, c := range children { name := c.Name() s := path.Join(src, name) d := path.Join(dst, name) cStatus, cErr := copyFiles(ctx, fs, s, d, overwrite, depth, recursion) if cErr != nil { // TODO: MultiStatus. return cStatus, cErr } } } } else { dstFile, err := fs.OpenFile(ctx, dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, srcPerm) if err != nil { if os.IsNotExist(err) { return http.StatusConflict, err } return http.StatusForbidden, err } _, copyErr := io.Copy(dstFile, srcFile) propsErr := copyProps(dstFile, srcFile) closeErr := dstFile.Close() if copyErr != nil { return http.StatusInternalServerError, copyErr } if propsErr != nil { return http.StatusInternalServerError, propsErr } if closeErr != nil { return http.StatusInternalServerError, closeErr } } if created { return http.StatusCreated, nil } return http.StatusNoContent, nil } // walkFS traverses filesystem fs starting at name up to depth levels. // // Allowed values for depth are 0, 1 or infiniteDepth. For each visited node, // walkFS calls walkFn. If a visited file system node is a directory and // walkFn returns filepath.SkipDir, walkFS will skip traversal of this node. func walkFS(ctx context.Context, fs FileSystem, depth int, name string, info os.FileInfo, walkFn filepath.WalkFunc) error { // This implementation is based on Walk's code in the standard path/filepath package. err := walkFn(name, info, nil) if err != nil { if info.IsDir() && err == filepath.SkipDir { return nil } return err } if !info.IsDir() || depth == 0 { return nil } if depth == 1 { depth = 0 } // Read directory names. f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0) if err != nil { return walkFn(name, info, err) } fileInfos, err := f.Readdir(0) f.Close() if err != nil { return walkFn(name, info, err) } for _, fileInfo := range fileInfos { filename := path.Join(name, fileInfo.Name()) fileInfo, err := fs.Stat(ctx, filename) if err != nil { if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir { return err } } else { err = walkFS(ctx, fs, depth, filename, fileInfo, walkFn) if err != nil { if !fileInfo.IsDir() || err != filepath.SkipDir { return err } } } } return nil } lxd-2.0.11/dist/src/golang.org/x/net/trace/0000755061062106075000000000000013172163402021411 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/trace/trace_test.go0000644061062106075000000000762213172163402024104 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package trace import ( "net/http" "reflect" "testing" ) type s struct{} func (s) String() string { return "lazy string" } // TestReset checks whether all the fields are zeroed after reset. func TestReset(t *testing.T) { tr := New("foo", "bar") tr.LazyLog(s{}, false) tr.LazyPrintf("%d", 1) tr.SetRecycler(func(_ interface{}) {}) tr.SetTraceInfo(3, 4) tr.SetMaxEvents(100) tr.SetError() tr.Finish() tr.(*trace).reset() if !reflect.DeepEqual(tr, new(trace)) { t.Errorf("reset didn't clear all fields: %+v", tr) } } // TestResetLog checks whether all the fields are zeroed after reset. func TestResetLog(t *testing.T) { el := NewEventLog("foo", "bar") el.Printf("message") el.Errorf("error") el.Finish() el.(*eventLog).reset() if !reflect.DeepEqual(el, new(eventLog)) { t.Errorf("reset didn't clear all fields: %+v", el) } } func TestAuthRequest(t *testing.T) { testCases := []struct { host string want bool }{ {host: "192.168.23.1", want: false}, {host: "192.168.23.1:8080", want: false}, {host: "malformed remote addr", want: false}, {host: "localhost", want: true}, {host: "localhost:8080", want: true}, {host: "127.0.0.1", want: true}, {host: "127.0.0.1:8080", want: true}, {host: "::1", want: true}, {host: "[::1]:8080", want: true}, } for _, tt := range testCases { req := &http.Request{RemoteAddr: tt.host} any, sensitive := AuthRequest(req) if any != tt.want || sensitive != tt.want { t.Errorf("AuthRequest(%q) = %t, %t; want %t, %t", tt.host, any, sensitive, tt.want, tt.want) } } } // TestParseTemplate checks that all templates used by this package are valid // as they are parsed on first usage func TestParseTemplate(t *testing.T) { if tmpl := distTmpl(); tmpl == nil { t.Error("invalid template returned from distTmpl()") } if tmpl := pageTmpl(); tmpl == nil { t.Error("invalid template returned from pageTmpl()") } if tmpl := eventsTmpl(); tmpl == nil { t.Error("invalid template returned from eventsTmpl()") } } func benchmarkTrace(b *testing.B, maxEvents, numEvents int) { numSpans := (b.N + numEvents + 1) / numEvents for i := 0; i < numSpans; i++ { tr := New("test", "test") tr.SetMaxEvents(maxEvents) for j := 0; j < numEvents; j++ { tr.LazyPrintf("%d", j) } tr.Finish() } } func BenchmarkTrace_Default_2(b *testing.B) { benchmarkTrace(b, 0, 2) } func BenchmarkTrace_Default_10(b *testing.B) { benchmarkTrace(b, 0, 10) } func BenchmarkTrace_Default_100(b *testing.B) { benchmarkTrace(b, 0, 100) } func BenchmarkTrace_Default_1000(b *testing.B) { benchmarkTrace(b, 0, 1000) } func BenchmarkTrace_Default_10000(b *testing.B) { benchmarkTrace(b, 0, 10000) } func BenchmarkTrace_10_2(b *testing.B) { benchmarkTrace(b, 10, 2) } func BenchmarkTrace_10_10(b *testing.B) { benchmarkTrace(b, 10, 10) } func BenchmarkTrace_10_100(b *testing.B) { benchmarkTrace(b, 10, 100) } func BenchmarkTrace_10_1000(b *testing.B) { benchmarkTrace(b, 10, 1000) } func BenchmarkTrace_10_10000(b *testing.B) { benchmarkTrace(b, 10, 10000) } func BenchmarkTrace_100_2(b *testing.B) { benchmarkTrace(b, 100, 2) } func BenchmarkTrace_100_10(b *testing.B) { benchmarkTrace(b, 100, 10) } func BenchmarkTrace_100_100(b *testing.B) { benchmarkTrace(b, 100, 100) } func BenchmarkTrace_100_1000(b *testing.B) { benchmarkTrace(b, 100, 1000) } func BenchmarkTrace_100_10000(b *testing.B) { benchmarkTrace(b, 100, 10000) } func BenchmarkTrace_1000_2(b *testing.B) { benchmarkTrace(b, 1000, 2) } func BenchmarkTrace_1000_10(b *testing.B) { benchmarkTrace(b, 1000, 10) } func BenchmarkTrace_1000_100(b *testing.B) { benchmarkTrace(b, 1000, 100) } func BenchmarkTrace_1000_1000(b *testing.B) { benchmarkTrace(b, 1000, 1000) } func BenchmarkTrace_1000_10000(b *testing.B) { benchmarkTrace(b, 1000, 10000) } lxd-2.0.11/dist/src/golang.org/x/net/trace/trace_go17.go0000644061062106075000000000111013172163402023664 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package trace import "context" // NewContext returns a copy of the parent context // and associates it with a Trace. func NewContext(ctx context.Context, tr Trace) context.Context { return context.WithValue(ctx, contextKey, tr) } // FromContext returns the Trace bound to the context, if any. func FromContext(ctx context.Context) (tr Trace, ok bool) { tr, ok = ctx.Value(contextKey).(Trace) return } lxd-2.0.11/dist/src/golang.org/x/net/trace/trace_go16.go0000644061062106075000000000113213172163402023667 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package trace import "golang.org/x/net/context" // NewContext returns a copy of the parent context // and associates it with a Trace. func NewContext(ctx context.Context, tr Trace) context.Context { return context.WithValue(ctx, contextKey, tr) } // FromContext returns the Trace bound to the context, if any. func FromContext(ctx context.Context) (tr Trace, ok bool) { tr, ok = ctx.Value(contextKey).(Trace) return } lxd-2.0.11/dist/src/golang.org/x/net/trace/trace.go0000644061062106075000000006557413172163402023057 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package trace implements tracing of requests and long-lived objects. It exports HTTP interfaces on /debug/requests and /debug/events. A trace.Trace provides tracing for short-lived objects, usually requests. A request handler might be implemented like this: func fooHandler(w http.ResponseWriter, req *http.Request) { tr := trace.New("mypkg.Foo", req.URL.Path) defer tr.Finish() ... tr.LazyPrintf("some event %q happened", str) ... if err := somethingImportant(); err != nil { tr.LazyPrintf("somethingImportant failed: %v", err) tr.SetError() } } The /debug/requests HTTP endpoint organizes the traces by family, errors, and duration. It also provides histogram of request duration for each family. A trace.EventLog provides tracing for long-lived objects, such as RPC connections. // A Fetcher fetches URL paths for a single domain. type Fetcher struct { domain string events trace.EventLog } func NewFetcher(domain string) *Fetcher { return &Fetcher{ domain, trace.NewEventLog("mypkg.Fetcher", domain), } } func (f *Fetcher) Fetch(path string) (string, error) { resp, err := http.Get("http://" + f.domain + "/" + path) if err != nil { f.events.Errorf("Get(%q) = %v", path, err) return "", err } f.events.Printf("Get(%q) = %s", path, resp.Status) ... } func (f *Fetcher) Close() error { f.events.Finish() return nil } The /debug/events HTTP endpoint organizes the event logs by family and by time since the last error. The expanded view displays recent log entries and the log's call stack. */ package trace // import "golang.org/x/net/trace" import ( "bytes" "fmt" "html/template" "io" "log" "net" "net/http" "runtime" "sort" "strconv" "sync" "sync/atomic" "time" "golang.org/x/net/internal/timeseries" ) // DebugUseAfterFinish controls whether to debug uses of Trace values after finishing. // FOR DEBUGGING ONLY. This will slow down the program. var DebugUseAfterFinish = false // AuthRequest determines whether a specific request is permitted to load the // /debug/requests or /debug/events pages. // // It returns two bools; the first indicates whether the page may be viewed at all, // and the second indicates whether sensitive events will be shown. // // AuthRequest may be replaced by a program to customize its authorization requirements. // // The default AuthRequest function returns (true, true) if and only if the request // comes from localhost/127.0.0.1/[::1]. var AuthRequest = func(req *http.Request) (any, sensitive bool) { // RemoteAddr is commonly in the form "IP" or "IP:port". // If it is in the form "IP:port", split off the port. host, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { host = req.RemoteAddr } switch host { case "localhost", "127.0.0.1", "::1": return true, true default: return false, false } } func init() { // TODO(jbd): Serve Traces from /debug/traces in the future? // There is no requirement for a request to be present to have traces. http.HandleFunc("/debug/requests", Traces) http.HandleFunc("/debug/events", Events) } // Traces responds with traces from the program. // The package initialization registers it in http.DefaultServeMux // at /debug/requests. // // It performs authorization by running AuthRequest. func Traces(w http.ResponseWriter, req *http.Request) { any, sensitive := AuthRequest(req) if !any { http.Error(w, "not allowed", http.StatusUnauthorized) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") Render(w, req, sensitive) } // Events responds with a page of events collected by EventLogs. // The package initialization registers it in http.DefaultServeMux // at /debug/events. // // It performs authorization by running AuthRequest. func Events(w http.ResponseWriter, req *http.Request) { any, sensitive := AuthRequest(req) if !any { http.Error(w, "not allowed", http.StatusUnauthorized) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") RenderEvents(w, req, sensitive) } // Render renders the HTML page typically served at /debug/requests. // It does not do any auth checking. The request may be nil. // // Most users will use the Traces handler. func Render(w io.Writer, req *http.Request, sensitive bool) { data := &struct { Families []string ActiveTraceCount map[string]int CompletedTraces map[string]*family // Set when a bucket has been selected. Traces traceList Family string Bucket int Expanded bool Traced bool Active bool ShowSensitive bool // whether to show sensitive events Histogram template.HTML HistogramWindow string // e.g. "last minute", "last hour", "all time" // If non-zero, the set of traces is a partial set, // and this is the total number. Total int }{ CompletedTraces: completedTraces, } data.ShowSensitive = sensitive if req != nil { // Allow show_sensitive=0 to force hiding of sensitive data for testing. // This only goes one way; you can't use show_sensitive=1 to see things. if req.FormValue("show_sensitive") == "0" { data.ShowSensitive = false } if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil { data.Expanded = exp } if exp, err := strconv.ParseBool(req.FormValue("rtraced")); err == nil { data.Traced = exp } } completedMu.RLock() data.Families = make([]string, 0, len(completedTraces)) for fam := range completedTraces { data.Families = append(data.Families, fam) } completedMu.RUnlock() sort.Strings(data.Families) // We are careful here to minimize the time spent locking activeMu, // since that lock is required every time an RPC starts and finishes. data.ActiveTraceCount = make(map[string]int, len(data.Families)) activeMu.RLock() for fam, s := range activeTraces { data.ActiveTraceCount[fam] = s.Len() } activeMu.RUnlock() var ok bool data.Family, data.Bucket, ok = parseArgs(req) switch { case !ok: // No-op case data.Bucket == -1: data.Active = true n := data.ActiveTraceCount[data.Family] data.Traces = getActiveTraces(data.Family) if len(data.Traces) < n { data.Total = n } case data.Bucket < bucketsPerFamily: if b := lookupBucket(data.Family, data.Bucket); b != nil { data.Traces = b.Copy(data.Traced) } default: if f := getFamily(data.Family, false); f != nil { var obs timeseries.Observable f.LatencyMu.RLock() switch o := data.Bucket - bucketsPerFamily; o { case 0: obs = f.Latency.Minute() data.HistogramWindow = "last minute" case 1: obs = f.Latency.Hour() data.HistogramWindow = "last hour" case 2: obs = f.Latency.Total() data.HistogramWindow = "all time" } f.LatencyMu.RUnlock() if obs != nil { data.Histogram = obs.(*histogram).html() } } } if data.Traces != nil { defer data.Traces.Free() sort.Sort(data.Traces) } completedMu.RLock() defer completedMu.RUnlock() if err := pageTmpl().ExecuteTemplate(w, "Page", data); err != nil { log.Printf("net/trace: Failed executing template: %v", err) } } func parseArgs(req *http.Request) (fam string, b int, ok bool) { if req == nil { return "", 0, false } fam, bStr := req.FormValue("fam"), req.FormValue("b") if fam == "" || bStr == "" { return "", 0, false } b, err := strconv.Atoi(bStr) if err != nil || b < -1 { return "", 0, false } return fam, b, true } func lookupBucket(fam string, b int) *traceBucket { f := getFamily(fam, false) if f == nil || b < 0 || b >= len(f.Buckets) { return nil } return f.Buckets[b] } type contextKeyT string var contextKey = contextKeyT("golang.org/x/net/trace.Trace") // Trace represents an active request. type Trace interface { // LazyLog adds x to the event log. It will be evaluated each time the // /debug/requests page is rendered. Any memory referenced by x will be // pinned until the trace is finished and later discarded. LazyLog(x fmt.Stringer, sensitive bool) // LazyPrintf evaluates its arguments with fmt.Sprintf each time the // /debug/requests page is rendered. Any memory referenced by a will be // pinned until the trace is finished and later discarded. LazyPrintf(format string, a ...interface{}) // SetError declares that this trace resulted in an error. SetError() // SetRecycler sets a recycler for the trace. // f will be called for each event passed to LazyLog at a time when // it is no longer required, whether while the trace is still active // and the event is discarded, or when a completed trace is discarded. SetRecycler(f func(interface{})) // SetTraceInfo sets the trace info for the trace. // This is currently unused. SetTraceInfo(traceID, spanID uint64) // SetMaxEvents sets the maximum number of events that will be stored // in the trace. This has no effect if any events have already been // added to the trace. SetMaxEvents(m int) // Finish declares that this trace is complete. // The trace should not be used after calling this method. Finish() } type lazySprintf struct { format string a []interface{} } func (l *lazySprintf) String() string { return fmt.Sprintf(l.format, l.a...) } // New returns a new Trace with the specified family and title. func New(family, title string) Trace { tr := newTrace() tr.ref() tr.Family, tr.Title = family, title tr.Start = time.Now() tr.maxEvents = maxEventsPerTrace tr.events = tr.eventsBuf[:0] activeMu.RLock() s := activeTraces[tr.Family] activeMu.RUnlock() if s == nil { activeMu.Lock() s = activeTraces[tr.Family] // check again if s == nil { s = new(traceSet) activeTraces[tr.Family] = s } activeMu.Unlock() } s.Add(tr) // Trigger allocation of the completed trace structure for this family. // This will cause the family to be present in the request page during // the first trace of this family. We don't care about the return value, // nor is there any need for this to run inline, so we execute it in its // own goroutine, but only if the family isn't allocated yet. completedMu.RLock() if _, ok := completedTraces[tr.Family]; !ok { go allocFamily(tr.Family) } completedMu.RUnlock() return tr } func (tr *trace) Finish() { tr.Elapsed = time.Now().Sub(tr.Start) if DebugUseAfterFinish { buf := make([]byte, 4<<10) // 4 KB should be enough n := runtime.Stack(buf, false) tr.finishStack = buf[:n] } activeMu.RLock() m := activeTraces[tr.Family] activeMu.RUnlock() m.Remove(tr) f := getFamily(tr.Family, true) for _, b := range f.Buckets { if b.Cond.match(tr) { b.Add(tr) } } // Add a sample of elapsed time as microseconds to the family's timeseries h := new(histogram) h.addMeasurement(tr.Elapsed.Nanoseconds() / 1e3) f.LatencyMu.Lock() f.Latency.Add(h) f.LatencyMu.Unlock() tr.unref() // matches ref in New } const ( bucketsPerFamily = 9 tracesPerBucket = 10 maxActiveTraces = 20 // Maximum number of active traces to show. maxEventsPerTrace = 10 numHistogramBuckets = 38 ) var ( // The active traces. activeMu sync.RWMutex activeTraces = make(map[string]*traceSet) // family -> traces // Families of completed traces. completedMu sync.RWMutex completedTraces = make(map[string]*family) // family -> traces ) type traceSet struct { mu sync.RWMutex m map[*trace]bool // We could avoid the entire map scan in FirstN by having a slice of all the traces // ordered by start time, and an index into that from the trace struct, with a periodic // repack of the slice after enough traces finish; we could also use a skip list or similar. // However, that would shift some of the expense from /debug/requests time to RPC time, // which is probably the wrong trade-off. } func (ts *traceSet) Len() int { ts.mu.RLock() defer ts.mu.RUnlock() return len(ts.m) } func (ts *traceSet) Add(tr *trace) { ts.mu.Lock() if ts.m == nil { ts.m = make(map[*trace]bool) } ts.m[tr] = true ts.mu.Unlock() } func (ts *traceSet) Remove(tr *trace) { ts.mu.Lock() delete(ts.m, tr) ts.mu.Unlock() } // FirstN returns the first n traces ordered by time. func (ts *traceSet) FirstN(n int) traceList { ts.mu.RLock() defer ts.mu.RUnlock() if n > len(ts.m) { n = len(ts.m) } trl := make(traceList, 0, n) // Fast path for when no selectivity is needed. if n == len(ts.m) { for tr := range ts.m { tr.ref() trl = append(trl, tr) } sort.Sort(trl) return trl } // Pick the oldest n traces. // This is inefficient. See the comment in the traceSet struct. for tr := range ts.m { // Put the first n traces into trl in the order they occur. // When we have n, sort trl, and thereafter maintain its order. if len(trl) < n { tr.ref() trl = append(trl, tr) if len(trl) == n { // This is guaranteed to happen exactly once during this loop. sort.Sort(trl) } continue } if tr.Start.After(trl[n-1].Start) { continue } // Find where to insert this one. tr.ref() i := sort.Search(n, func(i int) bool { return trl[i].Start.After(tr.Start) }) trl[n-1].unref() copy(trl[i+1:], trl[i:]) trl[i] = tr } return trl } func getActiveTraces(fam string) traceList { activeMu.RLock() s := activeTraces[fam] activeMu.RUnlock() if s == nil { return nil } return s.FirstN(maxActiveTraces) } func getFamily(fam string, allocNew bool) *family { completedMu.RLock() f := completedTraces[fam] completedMu.RUnlock() if f == nil && allocNew { f = allocFamily(fam) } return f } func allocFamily(fam string) *family { completedMu.Lock() defer completedMu.Unlock() f := completedTraces[fam] if f == nil { f = newFamily() completedTraces[fam] = f } return f } // family represents a set of trace buckets and associated latency information. type family struct { // traces may occur in multiple buckets. Buckets [bucketsPerFamily]*traceBucket // latency time series LatencyMu sync.RWMutex Latency *timeseries.MinuteHourSeries } func newFamily() *family { return &family{ Buckets: [bucketsPerFamily]*traceBucket{ {Cond: minCond(0)}, {Cond: minCond(50 * time.Millisecond)}, {Cond: minCond(100 * time.Millisecond)}, {Cond: minCond(200 * time.Millisecond)}, {Cond: minCond(500 * time.Millisecond)}, {Cond: minCond(1 * time.Second)}, {Cond: minCond(10 * time.Second)}, {Cond: minCond(100 * time.Second)}, {Cond: errorCond{}}, }, Latency: timeseries.NewMinuteHourSeries(func() timeseries.Observable { return new(histogram) }), } } // traceBucket represents a size-capped bucket of historic traces, // along with a condition for a trace to belong to the bucket. type traceBucket struct { Cond cond // Ring buffer implementation of a fixed-size FIFO queue. mu sync.RWMutex buf [tracesPerBucket]*trace start int // < tracesPerBucket length int // <= tracesPerBucket } func (b *traceBucket) Add(tr *trace) { b.mu.Lock() defer b.mu.Unlock() i := b.start + b.length if i >= tracesPerBucket { i -= tracesPerBucket } if b.length == tracesPerBucket { // "Remove" an element from the bucket. b.buf[i].unref() b.start++ if b.start == tracesPerBucket { b.start = 0 } } b.buf[i] = tr if b.length < tracesPerBucket { b.length++ } tr.ref() } // Copy returns a copy of the traces in the bucket. // If tracedOnly is true, only the traces with trace information will be returned. // The logs will be ref'd before returning; the caller should call // the Free method when it is done with them. // TODO(dsymonds): keep track of traced requests in separate buckets. func (b *traceBucket) Copy(tracedOnly bool) traceList { b.mu.RLock() defer b.mu.RUnlock() trl := make(traceList, 0, b.length) for i, x := 0, b.start; i < b.length; i++ { tr := b.buf[x] if !tracedOnly || tr.spanID != 0 { tr.ref() trl = append(trl, tr) } x++ if x == b.length { x = 0 } } return trl } func (b *traceBucket) Empty() bool { b.mu.RLock() defer b.mu.RUnlock() return b.length == 0 } // cond represents a condition on a trace. type cond interface { match(t *trace) bool String() string } type minCond time.Duration func (m minCond) match(t *trace) bool { return t.Elapsed >= time.Duration(m) } func (m minCond) String() string { return fmt.Sprintf("≥%gs", time.Duration(m).Seconds()) } type errorCond struct{} func (e errorCond) match(t *trace) bool { return t.IsError } func (e errorCond) String() string { return "errors" } type traceList []*trace // Free calls unref on each element of the list. func (trl traceList) Free() { for _, t := range trl { t.unref() } } // traceList may be sorted in reverse chronological order. func (trl traceList) Len() int { return len(trl) } func (trl traceList) Less(i, j int) bool { return trl[i].Start.After(trl[j].Start) } func (trl traceList) Swap(i, j int) { trl[i], trl[j] = trl[j], trl[i] } // An event is a timestamped log entry in a trace. type event struct { When time.Time Elapsed time.Duration // since previous event in trace NewDay bool // whether this event is on a different day to the previous event Recyclable bool // whether this event was passed via LazyLog Sensitive bool // whether this event contains sensitive information What interface{} // string or fmt.Stringer } // WhenString returns a string representation of the elapsed time of the event. // It will include the date if midnight was crossed. func (e event) WhenString() string { if e.NewDay { return e.When.Format("2006/01/02 15:04:05.000000") } return e.When.Format("15:04:05.000000") } // discarded represents a number of discarded events. // It is stored as *discarded to make it easier to update in-place. type discarded int func (d *discarded) String() string { return fmt.Sprintf("(%d events discarded)", int(*d)) } // trace represents an active or complete request, // either sent or received by this program. type trace struct { // Family is the top-level grouping of traces to which this belongs. Family string // Title is the title of this trace. Title string // Timing information. Start time.Time Elapsed time.Duration // zero while active // Trace information if non-zero. traceID uint64 spanID uint64 // Whether this trace resulted in an error. IsError bool // Append-only sequence of events (modulo discards). mu sync.RWMutex events []event maxEvents int refs int32 // how many buckets this is in recycler func(interface{}) disc discarded // scratch space to avoid allocation finishStack []byte // where finish was called, if DebugUseAfterFinish is set eventsBuf [4]event // preallocated buffer in case we only log a few events } func (tr *trace) reset() { // Clear all but the mutex. Mutexes may not be copied, even when unlocked. tr.Family = "" tr.Title = "" tr.Start = time.Time{} tr.Elapsed = 0 tr.traceID = 0 tr.spanID = 0 tr.IsError = false tr.maxEvents = 0 tr.events = nil tr.refs = 0 tr.recycler = nil tr.disc = 0 tr.finishStack = nil for i := range tr.eventsBuf { tr.eventsBuf[i] = event{} } } // delta returns the elapsed time since the last event or the trace start, // and whether it spans midnight. // L >= tr.mu func (tr *trace) delta(t time.Time) (time.Duration, bool) { if len(tr.events) == 0 { return t.Sub(tr.Start), false } prev := tr.events[len(tr.events)-1].When return t.Sub(prev), prev.Day() != t.Day() } func (tr *trace) addEvent(x interface{}, recyclable, sensitive bool) { if DebugUseAfterFinish && tr.finishStack != nil { buf := make([]byte, 4<<10) // 4 KB should be enough n := runtime.Stack(buf, false) log.Printf("net/trace: trace used after finish:\nFinished at:\n%s\nUsed at:\n%s", tr.finishStack, buf[:n]) } /* NOTE TO DEBUGGERS If you are here because your program panicked in this code, it is almost definitely the fault of code using this package, and very unlikely to be the fault of this code. The most likely scenario is that some code elsewhere is using a trace.Trace after its Finish method is called. You can temporarily set the DebugUseAfterFinish var to help discover where that is; do not leave that var set, since it makes this package much less efficient. */ e := event{When: time.Now(), What: x, Recyclable: recyclable, Sensitive: sensitive} tr.mu.Lock() e.Elapsed, e.NewDay = tr.delta(e.When) if len(tr.events) < tr.maxEvents { tr.events = append(tr.events, e) } else { // Discard the middle events. di := int((tr.maxEvents - 1) / 2) if d, ok := tr.events[di].What.(*discarded); ok { (*d)++ } else { // disc starts at two to count for the event it is replacing, // plus the next one that we are about to drop. tr.disc = 2 if tr.recycler != nil && tr.events[di].Recyclable { go tr.recycler(tr.events[di].What) } tr.events[di].What = &tr.disc } // The timestamp of the discarded meta-event should be // the time of the last event it is representing. tr.events[di].When = tr.events[di+1].When if tr.recycler != nil && tr.events[di+1].Recyclable { go tr.recycler(tr.events[di+1].What) } copy(tr.events[di+1:], tr.events[di+2:]) tr.events[tr.maxEvents-1] = e } tr.mu.Unlock() } func (tr *trace) LazyLog(x fmt.Stringer, sensitive bool) { tr.addEvent(x, true, sensitive) } func (tr *trace) LazyPrintf(format string, a ...interface{}) { tr.addEvent(&lazySprintf{format, a}, false, false) } func (tr *trace) SetError() { tr.IsError = true } func (tr *trace) SetRecycler(f func(interface{})) { tr.recycler = f } func (tr *trace) SetTraceInfo(traceID, spanID uint64) { tr.traceID, tr.spanID = traceID, spanID } func (tr *trace) SetMaxEvents(m int) { // Always keep at least three events: first, discarded count, last. if len(tr.events) == 0 && m > 3 { tr.maxEvents = m } } func (tr *trace) ref() { atomic.AddInt32(&tr.refs, 1) } func (tr *trace) unref() { if atomic.AddInt32(&tr.refs, -1) == 0 { if tr.recycler != nil { // freeTrace clears tr, so we hold tr.recycler and tr.events here. go func(f func(interface{}), es []event) { for _, e := range es { if e.Recyclable { f(e.What) } } }(tr.recycler, tr.events) } freeTrace(tr) } } func (tr *trace) When() string { return tr.Start.Format("2006/01/02 15:04:05.000000") } func (tr *trace) ElapsedTime() string { t := tr.Elapsed if t == 0 { // Active trace. t = time.Since(tr.Start) } return fmt.Sprintf("%.6f", t.Seconds()) } func (tr *trace) Events() []event { tr.mu.RLock() defer tr.mu.RUnlock() return tr.events } var traceFreeList = make(chan *trace, 1000) // TODO(dsymonds): Use sync.Pool? // newTrace returns a trace ready to use. func newTrace() *trace { select { case tr := <-traceFreeList: return tr default: return new(trace) } } // freeTrace adds tr to traceFreeList if there's room. // This is non-blocking. func freeTrace(tr *trace) { if DebugUseAfterFinish { return // never reuse } tr.reset() select { case traceFreeList <- tr: default: } } func elapsed(d time.Duration) string { b := []byte(fmt.Sprintf("%.6f", d.Seconds())) // For subsecond durations, blank all zeros before decimal point, // and all zeros between the decimal point and the first non-zero digit. if d < time.Second { dot := bytes.IndexByte(b, '.') for i := 0; i < dot; i++ { b[i] = ' ' } for i := dot + 1; i < len(b); i++ { if b[i] == '0' { b[i] = ' ' } else { break } } } return string(b) } var pageTmplCache *template.Template var pageTmplOnce sync.Once func pageTmpl() *template.Template { pageTmplOnce.Do(func() { pageTmplCache = template.Must(template.New("Page").Funcs(template.FuncMap{ "elapsed": elapsed, "add": func(a, b int) int { return a + b }, }).Parse(pageHTML)) }) return pageTmplCache } const pageHTML = ` {{template "Prolog" .}} {{template "StatusTable" .}} {{template "Epilog" .}} {{define "Prolog"}} /debug/requests

/debug/requests

{{end}} {{/* end of Prolog */}} {{define "StatusTable"}} {{range $fam := .Families}} {{$n := index $.ActiveTraceCount $fam}} {{$f := index $.CompletedTraces $fam}} {{range $i, $b := $f.Buckets}} {{$empty := $b.Empty}} {{end}} {{$nb := len $f.Buckets}} {{end}}
{{$fam}} {{if $n}}{{end}} [{{$n}} active] {{if $n}}{{end}} {{if not $empty}}{{end}} [{{.Cond}}] {{if not $empty}}{{end}} [minute] [hour] [total]
{{end}} {{/* end of StatusTable */}} {{define "Epilog"}} {{if $.Traces}}

Family: {{$.Family}}

{{if or $.Expanded $.Traced}} [Normal/Summary] {{else}} [Normal/Summary] {{end}} {{if or (not $.Expanded) $.Traced}} [Normal/Expanded] {{else}} [Normal/Expanded] {{end}} {{if not $.Active}} {{if or $.Expanded (not $.Traced)}} [Traced/Summary] {{else}} [Traced/Summary] {{end}} {{if or (not $.Expanded) (not $.Traced)}} [Traced/Expanded] {{else}} [Traced/Expanded] {{end}} {{end}} {{if $.Total}}

Showing {{len $.Traces}} of {{$.Total}} traces.

{{end}} {{range $tr := $.Traces}} {{/* TODO: include traceID/spanID */}} {{if $.Expanded}} {{range $tr.Events}} {{end}} {{end}} {{end}}
{{if $.Active}}Active{{else}}Completed{{end}} Requests
WhenElapsed (s)
{{$tr.When}} {{$tr.ElapsedTime}} {{$tr.Title}}
{{.WhenString}} {{elapsed .Elapsed}} {{if or $.ShowSensitive (not .Sensitive)}}... {{.What}}{{else}}[redacted]{{end}}
{{end}} {{/* if $.Traces */}} {{if $.Histogram}}

Latency (µs) of {{$.Family}} over {{$.HistogramWindow}}

{{$.Histogram}} {{end}} {{/* if $.Histogram */}} {{end}} {{/* end of Epilog */}} ` lxd-2.0.11/dist/src/golang.org/x/net/trace/histogram_test.go0000644061062106075000000001655713172163402025012 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package trace import ( "math" "testing" ) type sumTest struct { value int64 sum int64 sumOfSquares float64 total int64 } var sumTests = []sumTest{ {100, 100, 10000, 1}, {50, 150, 12500, 2}, {50, 200, 15000, 3}, {50, 250, 17500, 4}, } type bucketingTest struct { in int64 log int bucket int } var bucketingTests = []bucketingTest{ {0, 0, 0}, {1, 1, 0}, {2, 2, 1}, {3, 2, 1}, {4, 3, 2}, {1000, 10, 9}, {1023, 10, 9}, {1024, 11, 10}, {1000000, 20, 19}, } type multiplyTest struct { in int64 ratio float64 expectedSum int64 expectedTotal int64 expectedSumOfSquares float64 } var multiplyTests = []multiplyTest{ {15, 2.5, 37, 2, 562.5}, {128, 4.6, 758, 13, 77953.9}, } type percentileTest struct { fraction float64 expected int64 } var percentileTests = []percentileTest{ {0.25, 48}, {0.5, 96}, {0.6, 109}, {0.75, 128}, {0.90, 205}, {0.95, 230}, {0.99, 256}, } func TestSum(t *testing.T) { var h histogram for _, test := range sumTests { h.addMeasurement(test.value) sum := h.sum if sum != test.sum { t.Errorf("h.Sum = %v WANT: %v", sum, test.sum) } sumOfSquares := h.sumOfSquares if sumOfSquares != test.sumOfSquares { t.Errorf("h.SumOfSquares = %v WANT: %v", sumOfSquares, test.sumOfSquares) } total := h.total() if total != test.total { t.Errorf("h.Total = %v WANT: %v", total, test.total) } } } func TestMultiply(t *testing.T) { var h histogram for i, test := range multiplyTests { h.addMeasurement(test.in) h.Multiply(test.ratio) if h.sum != test.expectedSum { t.Errorf("#%v: h.sum = %v WANT: %v", i, h.sum, test.expectedSum) } if h.total() != test.expectedTotal { t.Errorf("#%v: h.total = %v WANT: %v", i, h.total(), test.expectedTotal) } if h.sumOfSquares != test.expectedSumOfSquares { t.Errorf("#%v: h.SumOfSquares = %v WANT: %v", i, test.expectedSumOfSquares, h.sumOfSquares) } } } func TestBucketingFunctions(t *testing.T) { for _, test := range bucketingTests { log := log2(test.in) if log != test.log { t.Errorf("log2 = %v WANT: %v", log, test.log) } bucket := getBucket(test.in) if bucket != test.bucket { t.Errorf("getBucket = %v WANT: %v", bucket, test.bucket) } } } func TestAverage(t *testing.T) { a := new(histogram) average := a.average() if average != 0 { t.Errorf("Average of empty histogram was %v WANT: 0", average) } a.addMeasurement(1) a.addMeasurement(1) a.addMeasurement(3) const expected = float64(5) / float64(3) average = a.average() if !isApproximate(average, expected) { t.Errorf("Average = %g WANT: %v", average, expected) } } func TestStandardDeviation(t *testing.T) { a := new(histogram) add(a, 10, 1<<4) add(a, 10, 1<<5) add(a, 10, 1<<6) stdDev := a.standardDeviation() const expected = 19.95 if !isApproximate(stdDev, expected) { t.Errorf("StandardDeviation = %v WANT: %v", stdDev, expected) } // No values a = new(histogram) stdDev = a.standardDeviation() if !isApproximate(stdDev, 0) { t.Errorf("StandardDeviation = %v WANT: 0", stdDev) } add(a, 1, 1<<4) if !isApproximate(stdDev, 0) { t.Errorf("StandardDeviation = %v WANT: 0", stdDev) } add(a, 10, 1<<4) if !isApproximate(stdDev, 0) { t.Errorf("StandardDeviation = %v WANT: 0", stdDev) } } func TestPercentileBoundary(t *testing.T) { a := new(histogram) add(a, 5, 1<<4) add(a, 10, 1<<6) add(a, 5, 1<<7) for _, test := range percentileTests { percentile := a.percentileBoundary(test.fraction) if percentile != test.expected { t.Errorf("h.PercentileBoundary (fraction=%v) = %v WANT: %v", test.fraction, percentile, test.expected) } } } func TestCopyFrom(t *testing.T) { a := histogram{5, 25, []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}, 4, -1} b := histogram{6, 36, []int64{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39}, 5, -1} a.CopyFrom(&b) if a.String() != b.String() { t.Errorf("a.String = %s WANT: %s", a.String(), b.String()) } } func TestClear(t *testing.T) { a := histogram{5, 25, []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}, 4, -1} a.Clear() expected := "0, 0.000000, 0, 0, []" if a.String() != expected { t.Errorf("a.String = %s WANT %s", a.String(), expected) } } func TestNew(t *testing.T) { a := histogram{5, 25, []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}, 4, -1} b := a.New() expected := "0, 0.000000, 0, 0, []" if b.(*histogram).String() != expected { t.Errorf("b.(*histogram).String = %s WANT: %s", b.(*histogram).String(), expected) } } func TestAdd(t *testing.T) { // The tests here depend on the associativity of addMeasurement and Add. // Add empty observation a := histogram{5, 25, []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}, 4, -1} b := a.New() expected := a.String() a.Add(b) if a.String() != expected { t.Errorf("a.String = %s WANT: %s", a.String(), expected) } // Add same bucketed value, no new buckets c := new(histogram) d := new(histogram) e := new(histogram) c.addMeasurement(12) d.addMeasurement(11) e.addMeasurement(12) e.addMeasurement(11) c.Add(d) if c.String() != e.String() { t.Errorf("c.String = %s WANT: %s", c.String(), e.String()) } // Add bucketed values f := new(histogram) g := new(histogram) h := new(histogram) f.addMeasurement(4) f.addMeasurement(12) f.addMeasurement(100) g.addMeasurement(18) g.addMeasurement(36) g.addMeasurement(255) h.addMeasurement(4) h.addMeasurement(12) h.addMeasurement(100) h.addMeasurement(18) h.addMeasurement(36) h.addMeasurement(255) f.Add(g) if f.String() != h.String() { t.Errorf("f.String = %q WANT: %q", f.String(), h.String()) } // add buckets to no buckets i := new(histogram) j := new(histogram) k := new(histogram) j.addMeasurement(18) j.addMeasurement(36) j.addMeasurement(255) k.addMeasurement(18) k.addMeasurement(36) k.addMeasurement(255) i.Add(j) if i.String() != k.String() { t.Errorf("i.String = %q WANT: %q", i.String(), k.String()) } // add buckets to single value (no overlap) l := new(histogram) m := new(histogram) n := new(histogram) l.addMeasurement(0) m.addMeasurement(18) m.addMeasurement(36) m.addMeasurement(255) n.addMeasurement(0) n.addMeasurement(18) n.addMeasurement(36) n.addMeasurement(255) l.Add(m) if l.String() != n.String() { t.Errorf("l.String = %q WANT: %q", l.String(), n.String()) } // mixed order o := new(histogram) p := new(histogram) o.addMeasurement(0) o.addMeasurement(2) o.addMeasurement(0) p.addMeasurement(0) p.addMeasurement(0) p.addMeasurement(2) if o.String() != p.String() { t.Errorf("o.String = %q WANT: %q", o.String(), p.String()) } } func add(h *histogram, times int, val int64) { for i := 0; i < times; i++ { h.addMeasurement(val) } } func isApproximate(x, y float64) bool { return math.Abs(x-y) < 1e-2 } lxd-2.0.11/dist/src/golang.org/x/net/trace/histogram.go0000644061062106075000000002232113172163402023735 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package trace // This file implements histogramming for RPC statistics collection. import ( "bytes" "fmt" "html/template" "log" "math" "sync" "golang.org/x/net/internal/timeseries" ) const ( bucketCount = 38 ) // histogram keeps counts of values in buckets that are spaced // out in powers of 2: 0-1, 2-3, 4-7... // histogram implements timeseries.Observable type histogram struct { sum int64 // running total of measurements sumOfSquares float64 // square of running total buckets []int64 // bucketed values for histogram value int // holds a single value as an optimization valueCount int64 // number of values recorded for single value } // AddMeasurement records a value measurement observation to the histogram. func (h *histogram) addMeasurement(value int64) { // TODO: assert invariant h.sum += value h.sumOfSquares += float64(value) * float64(value) bucketIndex := getBucket(value) if h.valueCount == 0 || (h.valueCount > 0 && h.value == bucketIndex) { h.value = bucketIndex h.valueCount++ } else { h.allocateBuckets() h.buckets[bucketIndex]++ } } func (h *histogram) allocateBuckets() { if h.buckets == nil { h.buckets = make([]int64, bucketCount) h.buckets[h.value] = h.valueCount h.value = 0 h.valueCount = -1 } } func log2(i int64) int { n := 0 for ; i >= 0x100; i >>= 8 { n += 8 } for ; i > 0; i >>= 1 { n += 1 } return n } func getBucket(i int64) (index int) { index = log2(i) - 1 if index < 0 { index = 0 } if index >= bucketCount { index = bucketCount - 1 } return } // Total returns the number of recorded observations. func (h *histogram) total() (total int64) { if h.valueCount >= 0 { total = h.valueCount } for _, val := range h.buckets { total += int64(val) } return } // Average returns the average value of recorded observations. func (h *histogram) average() float64 { t := h.total() if t == 0 { return 0 } return float64(h.sum) / float64(t) } // Variance returns the variance of recorded observations. func (h *histogram) variance() float64 { t := float64(h.total()) if t == 0 { return 0 } s := float64(h.sum) / t return h.sumOfSquares/t - s*s } // StandardDeviation returns the standard deviation of recorded observations. func (h *histogram) standardDeviation() float64 { return math.Sqrt(h.variance()) } // PercentileBoundary estimates the value that the given fraction of recorded // observations are less than. func (h *histogram) percentileBoundary(percentile float64) int64 { total := h.total() // Corner cases (make sure result is strictly less than Total()) if total == 0 { return 0 } else if total == 1 { return int64(h.average()) } percentOfTotal := round(float64(total) * percentile) var runningTotal int64 for i := range h.buckets { value := h.buckets[i] runningTotal += value if runningTotal == percentOfTotal { // We hit an exact bucket boundary. If the next bucket has data, it is a // good estimate of the value. If the bucket is empty, we interpolate the // midpoint between the next bucket's boundary and the next non-zero // bucket. If the remaining buckets are all empty, then we use the // boundary for the next bucket as the estimate. j := uint8(i + 1) min := bucketBoundary(j) if runningTotal < total { for h.buckets[j] == 0 { j++ } } max := bucketBoundary(j) return min + round(float64(max-min)/2) } else if runningTotal > percentOfTotal { // The value is in this bucket. Interpolate the value. delta := runningTotal - percentOfTotal percentBucket := float64(value-delta) / float64(value) bucketMin := bucketBoundary(uint8(i)) nextBucketMin := bucketBoundary(uint8(i + 1)) bucketSize := nextBucketMin - bucketMin return bucketMin + round(percentBucket*float64(bucketSize)) } } return bucketBoundary(bucketCount - 1) } // Median returns the estimated median of the observed values. func (h *histogram) median() int64 { return h.percentileBoundary(0.5) } // Add adds other to h. func (h *histogram) Add(other timeseries.Observable) { o := other.(*histogram) if o.valueCount == 0 { // Other histogram is empty } else if h.valueCount >= 0 && o.valueCount > 0 && h.value == o.value { // Both have a single bucketed value, aggregate them h.valueCount += o.valueCount } else { // Two different values necessitate buckets in this histogram h.allocateBuckets() if o.valueCount >= 0 { h.buckets[o.value] += o.valueCount } else { for i := range h.buckets { h.buckets[i] += o.buckets[i] } } } h.sumOfSquares += o.sumOfSquares h.sum += o.sum } // Clear resets the histogram to an empty state, removing all observed values. func (h *histogram) Clear() { h.buckets = nil h.value = 0 h.valueCount = 0 h.sum = 0 h.sumOfSquares = 0 } // CopyFrom copies from other, which must be a *histogram, into h. func (h *histogram) CopyFrom(other timeseries.Observable) { o := other.(*histogram) if o.valueCount == -1 { h.allocateBuckets() copy(h.buckets, o.buckets) } h.sum = o.sum h.sumOfSquares = o.sumOfSquares h.value = o.value h.valueCount = o.valueCount } // Multiply scales the histogram by the specified ratio. func (h *histogram) Multiply(ratio float64) { if h.valueCount == -1 { for i := range h.buckets { h.buckets[i] = int64(float64(h.buckets[i]) * ratio) } } else { h.valueCount = int64(float64(h.valueCount) * ratio) } h.sum = int64(float64(h.sum) * ratio) h.sumOfSquares = h.sumOfSquares * ratio } // New creates a new histogram. func (h *histogram) New() timeseries.Observable { r := new(histogram) r.Clear() return r } func (h *histogram) String() string { return fmt.Sprintf("%d, %f, %d, %d, %v", h.sum, h.sumOfSquares, h.value, h.valueCount, h.buckets) } // round returns the closest int64 to the argument func round(in float64) int64 { return int64(math.Floor(in + 0.5)) } // bucketBoundary returns the first value in the bucket. func bucketBoundary(bucket uint8) int64 { if bucket == 0 { return 0 } return 1 << bucket } // bucketData holds data about a specific bucket for use in distTmpl. type bucketData struct { Lower, Upper int64 N int64 Pct, CumulativePct float64 GraphWidth int } // data holds data about a Distribution for use in distTmpl. type data struct { Buckets []*bucketData Count, Median int64 Mean, StandardDeviation float64 } // maxHTMLBarWidth is the maximum width of the HTML bar for visualizing buckets. const maxHTMLBarWidth = 350.0 // newData returns data representing h for use in distTmpl. func (h *histogram) newData() *data { // Force the allocation of buckets to simplify the rendering implementation h.allocateBuckets() // We scale the bars on the right so that the largest bar is // maxHTMLBarWidth pixels in width. maxBucket := int64(0) for _, n := range h.buckets { if n > maxBucket { maxBucket = n } } total := h.total() barsizeMult := maxHTMLBarWidth / float64(maxBucket) var pctMult float64 if total == 0 { pctMult = 1.0 } else { pctMult = 100.0 / float64(total) } buckets := make([]*bucketData, len(h.buckets)) runningTotal := int64(0) for i, n := range h.buckets { if n == 0 { continue } runningTotal += n var upperBound int64 if i < bucketCount-1 { upperBound = bucketBoundary(uint8(i + 1)) } else { upperBound = math.MaxInt64 } buckets[i] = &bucketData{ Lower: bucketBoundary(uint8(i)), Upper: upperBound, N: n, Pct: float64(n) * pctMult, CumulativePct: float64(runningTotal) * pctMult, GraphWidth: int(float64(n) * barsizeMult), } } return &data{ Buckets: buckets, Count: total, Median: h.median(), Mean: h.average(), StandardDeviation: h.standardDeviation(), } } func (h *histogram) html() template.HTML { buf := new(bytes.Buffer) if err := distTmpl().Execute(buf, h.newData()); err != nil { buf.Reset() log.Printf("net/trace: couldn't execute template: %v", err) } return template.HTML(buf.String()) } var distTmplCache *template.Template var distTmplOnce sync.Once func distTmpl() *template.Template { distTmplOnce.Do(func() { // Input: data distTmplCache = template.Must(template.New("distTmpl").Parse(`
Count: {{.Count}} Mean: {{printf "%.0f" .Mean}} StdDev: {{printf "%.0f" .StandardDeviation}} Median: {{.Median}}

{{range $b := .Buckets}} {{if $b}} {{end}} {{end}}
[ {{.Lower}}, {{.Upper}}) {{.N}} {{printf "%#.3f" .Pct}}% {{printf "%#.3f" .CumulativePct}}%
`)) }) return distTmplCache } lxd-2.0.11/dist/src/golang.org/x/net/trace/events.go0000644061062106075000000003040513172163402023246 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package trace import ( "bytes" "fmt" "html/template" "io" "log" "net/http" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "text/tabwriter" "time" ) const maxEventsPerLog = 100 type bucket struct { MaxErrAge time.Duration String string } var buckets = []bucket{ {0, "total"}, {10 * time.Second, "errs<10s"}, {1 * time.Minute, "errs<1m"}, {10 * time.Minute, "errs<10m"}, {1 * time.Hour, "errs<1h"}, {10 * time.Hour, "errs<10h"}, {24000 * time.Hour, "errors"}, } // RenderEvents renders the HTML page typically served at /debug/events. // It does not do any auth checking. The request may be nil. // // Most users will use the Events handler. func RenderEvents(w http.ResponseWriter, req *http.Request, sensitive bool) { now := time.Now() data := &struct { Families []string // family names Buckets []bucket Counts [][]int // eventLog count per family/bucket // Set when a bucket has been selected. Family string Bucket int EventLogs eventLogs Expanded bool }{ Buckets: buckets, } data.Families = make([]string, 0, len(families)) famMu.RLock() for name := range families { data.Families = append(data.Families, name) } famMu.RUnlock() sort.Strings(data.Families) // Count the number of eventLogs in each family for each error age. data.Counts = make([][]int, len(data.Families)) for i, name := range data.Families { // TODO(sameer): move this loop under the family lock. f := getEventFamily(name) data.Counts[i] = make([]int, len(data.Buckets)) for j, b := range data.Buckets { data.Counts[i][j] = f.Count(now, b.MaxErrAge) } } if req != nil { var ok bool data.Family, data.Bucket, ok = parseEventsArgs(req) if !ok { // No-op } else { data.EventLogs = getEventFamily(data.Family).Copy(now, buckets[data.Bucket].MaxErrAge) } if data.EventLogs != nil { defer data.EventLogs.Free() sort.Sort(data.EventLogs) } if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil { data.Expanded = exp } } famMu.RLock() defer famMu.RUnlock() if err := eventsTmpl().Execute(w, data); err != nil { log.Printf("net/trace: Failed executing template: %v", err) } } func parseEventsArgs(req *http.Request) (fam string, b int, ok bool) { fam, bStr := req.FormValue("fam"), req.FormValue("b") if fam == "" || bStr == "" { return "", 0, false } b, err := strconv.Atoi(bStr) if err != nil || b < 0 || b >= len(buckets) { return "", 0, false } return fam, b, true } // An EventLog provides a log of events associated with a specific object. type EventLog interface { // Printf formats its arguments with fmt.Sprintf and adds the // result to the event log. Printf(format string, a ...interface{}) // Errorf is like Printf, but it marks this event as an error. Errorf(format string, a ...interface{}) // Finish declares that this event log is complete. // The event log should not be used after calling this method. Finish() } // NewEventLog returns a new EventLog with the specified family name // and title. func NewEventLog(family, title string) EventLog { el := newEventLog() el.ref() el.Family, el.Title = family, title el.Start = time.Now() el.events = make([]logEntry, 0, maxEventsPerLog) el.stack = make([]uintptr, 32) n := runtime.Callers(2, el.stack) el.stack = el.stack[:n] getEventFamily(family).add(el) return el } func (el *eventLog) Finish() { getEventFamily(el.Family).remove(el) el.unref() // matches ref in New } var ( famMu sync.RWMutex families = make(map[string]*eventFamily) // family name => family ) func getEventFamily(fam string) *eventFamily { famMu.Lock() defer famMu.Unlock() f := families[fam] if f == nil { f = &eventFamily{} families[fam] = f } return f } type eventFamily struct { mu sync.RWMutex eventLogs eventLogs } func (f *eventFamily) add(el *eventLog) { f.mu.Lock() f.eventLogs = append(f.eventLogs, el) f.mu.Unlock() } func (f *eventFamily) remove(el *eventLog) { f.mu.Lock() defer f.mu.Unlock() for i, el0 := range f.eventLogs { if el == el0 { copy(f.eventLogs[i:], f.eventLogs[i+1:]) f.eventLogs = f.eventLogs[:len(f.eventLogs)-1] return } } } func (f *eventFamily) Count(now time.Time, maxErrAge time.Duration) (n int) { f.mu.RLock() defer f.mu.RUnlock() for _, el := range f.eventLogs { if el.hasRecentError(now, maxErrAge) { n++ } } return } func (f *eventFamily) Copy(now time.Time, maxErrAge time.Duration) (els eventLogs) { f.mu.RLock() defer f.mu.RUnlock() els = make(eventLogs, 0, len(f.eventLogs)) for _, el := range f.eventLogs { if el.hasRecentError(now, maxErrAge) { el.ref() els = append(els, el) } } return } type eventLogs []*eventLog // Free calls unref on each element of the list. func (els eventLogs) Free() { for _, el := range els { el.unref() } } // eventLogs may be sorted in reverse chronological order. func (els eventLogs) Len() int { return len(els) } func (els eventLogs) Less(i, j int) bool { return els[i].Start.After(els[j].Start) } func (els eventLogs) Swap(i, j int) { els[i], els[j] = els[j], els[i] } // A logEntry is a timestamped log entry in an event log. type logEntry struct { When time.Time Elapsed time.Duration // since previous event in log NewDay bool // whether this event is on a different day to the previous event What string IsErr bool } // WhenString returns a string representation of the elapsed time of the event. // It will include the date if midnight was crossed. func (e logEntry) WhenString() string { if e.NewDay { return e.When.Format("2006/01/02 15:04:05.000000") } return e.When.Format("15:04:05.000000") } // An eventLog represents an active event log. type eventLog struct { // Family is the top-level grouping of event logs to which this belongs. Family string // Title is the title of this event log. Title string // Timing information. Start time.Time // Call stack where this event log was created. stack []uintptr // Append-only sequence of events. // // TODO(sameer): change this to a ring buffer to avoid the array copy // when we hit maxEventsPerLog. mu sync.RWMutex events []logEntry LastErrorTime time.Time discarded int refs int32 // how many buckets this is in } func (el *eventLog) reset() { // Clear all but the mutex. Mutexes may not be copied, even when unlocked. el.Family = "" el.Title = "" el.Start = time.Time{} el.stack = nil el.events = nil el.LastErrorTime = time.Time{} el.discarded = 0 el.refs = 0 } func (el *eventLog) hasRecentError(now time.Time, maxErrAge time.Duration) bool { if maxErrAge == 0 { return true } el.mu.RLock() defer el.mu.RUnlock() return now.Sub(el.LastErrorTime) < maxErrAge } // delta returns the elapsed time since the last event or the log start, // and whether it spans midnight. // L >= el.mu func (el *eventLog) delta(t time.Time) (time.Duration, bool) { if len(el.events) == 0 { return t.Sub(el.Start), false } prev := el.events[len(el.events)-1].When return t.Sub(prev), prev.Day() != t.Day() } func (el *eventLog) Printf(format string, a ...interface{}) { el.printf(false, format, a...) } func (el *eventLog) Errorf(format string, a ...interface{}) { el.printf(true, format, a...) } func (el *eventLog) printf(isErr bool, format string, a ...interface{}) { e := logEntry{When: time.Now(), IsErr: isErr, What: fmt.Sprintf(format, a...)} el.mu.Lock() e.Elapsed, e.NewDay = el.delta(e.When) if len(el.events) < maxEventsPerLog { el.events = append(el.events, e) } else { // Discard the oldest event. if el.discarded == 0 { // el.discarded starts at two to count for the event it // is replacing, plus the next one that we are about to // drop. el.discarded = 2 } else { el.discarded++ } // TODO(sameer): if this causes allocations on a critical path, // change eventLog.What to be a fmt.Stringer, as in trace.go. el.events[0].What = fmt.Sprintf("(%d events discarded)", el.discarded) // The timestamp of the discarded meta-event should be // the time of the last event it is representing. el.events[0].When = el.events[1].When copy(el.events[1:], el.events[2:]) el.events[maxEventsPerLog-1] = e } if e.IsErr { el.LastErrorTime = e.When } el.mu.Unlock() } func (el *eventLog) ref() { atomic.AddInt32(&el.refs, 1) } func (el *eventLog) unref() { if atomic.AddInt32(&el.refs, -1) == 0 { freeEventLog(el) } } func (el *eventLog) When() string { return el.Start.Format("2006/01/02 15:04:05.000000") } func (el *eventLog) ElapsedTime() string { elapsed := time.Since(el.Start) return fmt.Sprintf("%.6f", elapsed.Seconds()) } func (el *eventLog) Stack() string { buf := new(bytes.Buffer) tw := tabwriter.NewWriter(buf, 1, 8, 1, '\t', 0) printStackRecord(tw, el.stack) tw.Flush() return buf.String() } // printStackRecord prints the function + source line information // for a single stack trace. // Adapted from runtime/pprof/pprof.go. func printStackRecord(w io.Writer, stk []uintptr) { for _, pc := range stk { f := runtime.FuncForPC(pc) if f == nil { continue } file, line := f.FileLine(pc) name := f.Name() // Hide runtime.goexit and any runtime functions at the beginning. if strings.HasPrefix(name, "runtime.") { continue } fmt.Fprintf(w, "# %s\t%s:%d\n", name, file, line) } } func (el *eventLog) Events() []logEntry { el.mu.RLock() defer el.mu.RUnlock() return el.events } // freeEventLogs is a freelist of *eventLog var freeEventLogs = make(chan *eventLog, 1000) // newEventLog returns a event log ready to use. func newEventLog() *eventLog { select { case el := <-freeEventLogs: return el default: return new(eventLog) } } // freeEventLog adds el to freeEventLogs if there's room. // This is non-blocking. func freeEventLog(el *eventLog) { el.reset() select { case freeEventLogs <- el: default: } } var eventsTmplCache *template.Template var eventsTmplOnce sync.Once func eventsTmpl() *template.Template { eventsTmplOnce.Do(func() { eventsTmplCache = template.Must(template.New("events").Funcs(template.FuncMap{ "elapsed": elapsed, "trimSpace": strings.TrimSpace, }).Parse(eventsHTML)) }) return eventsTmplCache } const eventsHTML = ` events

/debug/events

{{range $i, $fam := .Families}} {{range $j, $bucket := $.Buckets}} {{$n := index $.Counts $i $j}} {{end}} {{end}}
{{$fam}} {{if $n}}{{end}} [{{$n}} {{$bucket.String}}] {{if $n}}{{end}}
{{if $.EventLogs}}

Family: {{$.Family}}

{{if $.Expanded}}{{end}} [Summary]{{if $.Expanded}}{{end}} {{if not $.Expanded}}{{end}} [Expanded]{{if not $.Expanded}}{{end}} {{range $el := $.EventLogs}} {{if $.Expanded}} {{range $el.Events}} {{end}} {{end}} {{end}}
WhenElapsed
{{$el.When}} {{$el.ElapsedTime}} {{$el.Title}}
{{$el.Stack|trimSpace}}
{{.WhenString}} {{elapsed .Elapsed}} .{{if .IsErr}}E{{else}}.{{end}}. {{.What}}
{{end}} ` lxd-2.0.11/dist/src/golang.org/x/net/route/0000755061062106075000000000000013172163402021451 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/route/zsys_openbsd.go0000644061062106075000000000367613172163402024536 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package route const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_ROUTE = 0x11 sysAF_LINK = 0x12 sysAF_INET6 = 0x18 sysSOCK_RAW = 0x3 sysNET_RT_DUMP = 0x1 sysNET_RT_FLAGS = 0x2 sysNET_RT_IFLIST = 0x3 sysNET_RT_STATS = 0x4 sysNET_RT_TABLE = 0x5 sysNET_RT_IFNAMES = 0x6 sysNET_RT_MAXID = 0x7 ) const ( sysCTL_MAXNAME = 0xc sysCTL_UNSPEC = 0x0 sysCTL_KERN = 0x1 sysCTL_VM = 0x2 sysCTL_FS = 0x3 sysCTL_NET = 0x4 sysCTL_DEBUG = 0x5 sysCTL_HW = 0x6 sysCTL_MACHDEP = 0x7 sysCTL_DDB = 0x9 sysCTL_VFS = 0xa sysCTL_MAXID = 0xb ) const ( sysRTM_VERSION = 0x5 sysRTM_ADD = 0x1 sysRTM_DELETE = 0x2 sysRTM_CHANGE = 0x3 sysRTM_GET = 0x4 sysRTM_LOSING = 0x5 sysRTM_REDIRECT = 0x6 sysRTM_MISS = 0x7 sysRTM_LOCK = 0x8 sysRTM_RESOLVE = 0xb sysRTM_NEWADDR = 0xc sysRTM_DELADDR = 0xd sysRTM_IFINFO = 0xe sysRTM_IFANNOUNCE = 0xf sysRTM_DESYNC = 0x10 sysRTM_INVALIDATE = 0x11 sysRTM_BFD = 0x12 sysRTM_PROPOSAL = 0x13 sysRTA_DST = 0x1 sysRTA_GATEWAY = 0x2 sysRTA_NETMASK = 0x4 sysRTA_GENMASK = 0x8 sysRTA_IFP = 0x10 sysRTA_IFA = 0x20 sysRTA_AUTHOR = 0x40 sysRTA_BRD = 0x80 sysRTA_SRC = 0x100 sysRTA_SRCMASK = 0x200 sysRTA_LABEL = 0x400 sysRTA_BFD = 0x800 sysRTA_DNS = 0x1000 sysRTA_STATIC = 0x2000 sysRTA_SEARCH = 0x4000 sysRTAX_DST = 0x0 sysRTAX_GATEWAY = 0x1 sysRTAX_NETMASK = 0x2 sysRTAX_GENMASK = 0x3 sysRTAX_IFP = 0x4 sysRTAX_IFA = 0x5 sysRTAX_AUTHOR = 0x6 sysRTAX_BRD = 0x7 sysRTAX_SRC = 0x8 sysRTAX_SRCMASK = 0x9 sysRTAX_LABEL = 0xa sysRTAX_BFD = 0xb sysRTAX_DNS = 0xc sysRTAX_STATIC = 0xd sysRTAX_SEARCH = 0xe sysRTAX_MAX = 0xf ) const ( sizeofRtMsghdr = 0x60 sizeofSockaddrStorage = 0x100 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/route/zsys_netbsd.go0000644061062106075000000000360513172163402024353 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_netbsd.go package route const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_ROUTE = 0x22 sysAF_LINK = 0x12 sysAF_INET6 = 0x18 sysSOCK_RAW = 0x3 sysNET_RT_DUMP = 0x1 sysNET_RT_FLAGS = 0x2 sysNET_RT_IFLIST = 0x5 sysNET_RT_MAXID = 0x6 ) const ( sysCTL_MAXNAME = 0xc sysCTL_UNSPEC = 0x0 sysCTL_KERN = 0x1 sysCTL_VM = 0x2 sysCTL_VFS = 0x3 sysCTL_NET = 0x4 sysCTL_DEBUG = 0x5 sysCTL_HW = 0x6 sysCTL_MACHDEP = 0x7 sysCTL_USER = 0x8 sysCTL_DDB = 0x9 sysCTL_PROC = 0xa sysCTL_VENDOR = 0xb sysCTL_EMUL = 0xc sysCTL_SECURITY = 0xd sysCTL_MAXID = 0xe ) const ( sysRTM_VERSION = 0x4 sysRTM_ADD = 0x1 sysRTM_DELETE = 0x2 sysRTM_CHANGE = 0x3 sysRTM_GET = 0x4 sysRTM_LOSING = 0x5 sysRTM_REDIRECT = 0x6 sysRTM_MISS = 0x7 sysRTM_LOCK = 0x8 sysRTM_OLDADD = 0x9 sysRTM_OLDDEL = 0xa sysRTM_RESOLVE = 0xb sysRTM_NEWADDR = 0xc sysRTM_DELADDR = 0xd sysRTM_IFANNOUNCE = 0x10 sysRTM_IEEE80211 = 0x11 sysRTM_SETGATE = 0x12 sysRTM_LLINFO_UPD = 0x13 sysRTM_IFINFO = 0x14 sysRTM_CHGADDR = 0x15 sysRTA_DST = 0x1 sysRTA_GATEWAY = 0x2 sysRTA_NETMASK = 0x4 sysRTA_GENMASK = 0x8 sysRTA_IFP = 0x10 sysRTA_IFA = 0x20 sysRTA_AUTHOR = 0x40 sysRTA_BRD = 0x80 sysRTA_TAG = 0x100 sysRTAX_DST = 0x0 sysRTAX_GATEWAY = 0x1 sysRTAX_NETMASK = 0x2 sysRTAX_GENMASK = 0x3 sysRTAX_IFP = 0x4 sysRTAX_IFA = 0x5 sysRTAX_AUTHOR = 0x6 sysRTAX_BRD = 0x7 sysRTAX_TAG = 0x8 sysRTAX_MAX = 0x9 ) const ( sizeofIfMsghdrNetBSD7 = 0x98 sizeofIfaMsghdrNetBSD7 = 0x18 sizeofIfAnnouncemsghdrNetBSD7 = 0x18 sizeofRtMsghdrNetBSD7 = 0x78 sizeofRtMetricsNetBSD7 = 0x50 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/route/zsys_freebsd_arm.go0000644061062106075000000000530213172163402025341 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package route const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_ROUTE = 0x11 sysAF_LINK = 0x12 sysAF_INET6 = 0x1c sysSOCK_RAW = 0x3 sysNET_RT_DUMP = 0x1 sysNET_RT_FLAGS = 0x2 sysNET_RT_IFLIST = 0x3 sysNET_RT_IFMALIST = 0x4 sysNET_RT_IFLISTL = 0x5 ) const ( sysCTL_MAXNAME = 0x18 sysCTL_UNSPEC = 0x0 sysCTL_KERN = 0x1 sysCTL_VM = 0x2 sysCTL_VFS = 0x3 sysCTL_NET = 0x4 sysCTL_DEBUG = 0x5 sysCTL_HW = 0x6 sysCTL_MACHDEP = 0x7 sysCTL_USER = 0x8 sysCTL_P1003_1B = 0x9 ) const ( sysRTM_VERSION = 0x5 sysRTM_ADD = 0x1 sysRTM_DELETE = 0x2 sysRTM_CHANGE = 0x3 sysRTM_GET = 0x4 sysRTM_LOSING = 0x5 sysRTM_REDIRECT = 0x6 sysRTM_MISS = 0x7 sysRTM_LOCK = 0x8 sysRTM_RESOLVE = 0xb sysRTM_NEWADDR = 0xc sysRTM_DELADDR = 0xd sysRTM_IFINFO = 0xe sysRTM_NEWMADDR = 0xf sysRTM_DELMADDR = 0x10 sysRTM_IFANNOUNCE = 0x11 sysRTM_IEEE80211 = 0x12 sysRTA_DST = 0x1 sysRTA_GATEWAY = 0x2 sysRTA_NETMASK = 0x4 sysRTA_GENMASK = 0x8 sysRTA_IFP = 0x10 sysRTA_IFA = 0x20 sysRTA_AUTHOR = 0x40 sysRTA_BRD = 0x80 sysRTAX_DST = 0x0 sysRTAX_GATEWAY = 0x1 sysRTAX_NETMASK = 0x2 sysRTAX_GENMASK = 0x3 sysRTAX_IFP = 0x4 sysRTAX_IFA = 0x5 sysRTAX_AUTHOR = 0x6 sysRTAX_BRD = 0x7 sysRTAX_MAX = 0x8 ) const ( sizeofIfMsghdrlFreeBSD10 = 0x68 sizeofIfaMsghdrFreeBSD10 = 0x14 sizeofIfaMsghdrlFreeBSD10 = 0x6c sizeofIfmaMsghdrFreeBSD10 = 0x10 sizeofIfAnnouncemsghdrFreeBSD10 = 0x18 sizeofRtMsghdrFreeBSD10 = 0x5c sizeofRtMetricsFreeBSD10 = 0x38 sizeofIfMsghdrFreeBSD7 = 0x70 sizeofIfMsghdrFreeBSD8 = 0x70 sizeofIfMsghdrFreeBSD9 = 0x70 sizeofIfMsghdrFreeBSD10 = 0x70 sizeofIfMsghdrFreeBSD11 = 0xa8 sizeofIfDataFreeBSD7 = 0x60 sizeofIfDataFreeBSD8 = 0x60 sizeofIfDataFreeBSD9 = 0x60 sizeofIfDataFreeBSD10 = 0x60 sizeofIfDataFreeBSD11 = 0x98 sizeofIfMsghdrlFreeBSD10Emu = 0x68 sizeofIfaMsghdrFreeBSD10Emu = 0x14 sizeofIfaMsghdrlFreeBSD10Emu = 0x6c sizeofIfmaMsghdrFreeBSD10Emu = 0x10 sizeofIfAnnouncemsghdrFreeBSD10Emu = 0x18 sizeofRtMsghdrFreeBSD10Emu = 0x5c sizeofRtMetricsFreeBSD10Emu = 0x38 sizeofIfMsghdrFreeBSD7Emu = 0x70 sizeofIfMsghdrFreeBSD8Emu = 0x70 sizeofIfMsghdrFreeBSD9Emu = 0x70 sizeofIfMsghdrFreeBSD10Emu = 0x70 sizeofIfMsghdrFreeBSD11Emu = 0xa8 sizeofIfDataFreeBSD7Emu = 0x60 sizeofIfDataFreeBSD8Emu = 0x60 sizeofIfDataFreeBSD9Emu = 0x60 sizeofIfDataFreeBSD10Emu = 0x60 sizeofIfDataFreeBSD11Emu = 0x98 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/route/zsys_freebsd_amd64.go0000644061062106075000000000530213172163402025475 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package route const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_ROUTE = 0x11 sysAF_LINK = 0x12 sysAF_INET6 = 0x1c sysSOCK_RAW = 0x3 sysNET_RT_DUMP = 0x1 sysNET_RT_FLAGS = 0x2 sysNET_RT_IFLIST = 0x3 sysNET_RT_IFMALIST = 0x4 sysNET_RT_IFLISTL = 0x5 ) const ( sysCTL_MAXNAME = 0x18 sysCTL_UNSPEC = 0x0 sysCTL_KERN = 0x1 sysCTL_VM = 0x2 sysCTL_VFS = 0x3 sysCTL_NET = 0x4 sysCTL_DEBUG = 0x5 sysCTL_HW = 0x6 sysCTL_MACHDEP = 0x7 sysCTL_USER = 0x8 sysCTL_P1003_1B = 0x9 ) const ( sysRTM_VERSION = 0x5 sysRTM_ADD = 0x1 sysRTM_DELETE = 0x2 sysRTM_CHANGE = 0x3 sysRTM_GET = 0x4 sysRTM_LOSING = 0x5 sysRTM_REDIRECT = 0x6 sysRTM_MISS = 0x7 sysRTM_LOCK = 0x8 sysRTM_RESOLVE = 0xb sysRTM_NEWADDR = 0xc sysRTM_DELADDR = 0xd sysRTM_IFINFO = 0xe sysRTM_NEWMADDR = 0xf sysRTM_DELMADDR = 0x10 sysRTM_IFANNOUNCE = 0x11 sysRTM_IEEE80211 = 0x12 sysRTA_DST = 0x1 sysRTA_GATEWAY = 0x2 sysRTA_NETMASK = 0x4 sysRTA_GENMASK = 0x8 sysRTA_IFP = 0x10 sysRTA_IFA = 0x20 sysRTA_AUTHOR = 0x40 sysRTA_BRD = 0x80 sysRTAX_DST = 0x0 sysRTAX_GATEWAY = 0x1 sysRTAX_NETMASK = 0x2 sysRTAX_GENMASK = 0x3 sysRTAX_IFP = 0x4 sysRTAX_IFA = 0x5 sysRTAX_AUTHOR = 0x6 sysRTAX_BRD = 0x7 sysRTAX_MAX = 0x8 ) const ( sizeofIfMsghdrlFreeBSD10 = 0xb0 sizeofIfaMsghdrFreeBSD10 = 0x14 sizeofIfaMsghdrlFreeBSD10 = 0xb0 sizeofIfmaMsghdrFreeBSD10 = 0x10 sizeofIfAnnouncemsghdrFreeBSD10 = 0x18 sizeofRtMsghdrFreeBSD10 = 0x98 sizeofRtMetricsFreeBSD10 = 0x70 sizeofIfMsghdrFreeBSD7 = 0xa8 sizeofIfMsghdrFreeBSD8 = 0xa8 sizeofIfMsghdrFreeBSD9 = 0xa8 sizeofIfMsghdrFreeBSD10 = 0xa8 sizeofIfMsghdrFreeBSD11 = 0xa8 sizeofIfDataFreeBSD7 = 0x98 sizeofIfDataFreeBSD8 = 0x98 sizeofIfDataFreeBSD9 = 0x98 sizeofIfDataFreeBSD10 = 0x98 sizeofIfDataFreeBSD11 = 0x98 sizeofIfMsghdrlFreeBSD10Emu = 0xb0 sizeofIfaMsghdrFreeBSD10Emu = 0x14 sizeofIfaMsghdrlFreeBSD10Emu = 0xb0 sizeofIfmaMsghdrFreeBSD10Emu = 0x10 sizeofIfAnnouncemsghdrFreeBSD10Emu = 0x18 sizeofRtMsghdrFreeBSD10Emu = 0x98 sizeofRtMetricsFreeBSD10Emu = 0x70 sizeofIfMsghdrFreeBSD7Emu = 0xa8 sizeofIfMsghdrFreeBSD8Emu = 0xa8 sizeofIfMsghdrFreeBSD9Emu = 0xa8 sizeofIfMsghdrFreeBSD10Emu = 0xa8 sizeofIfMsghdrFreeBSD11Emu = 0xa8 sizeofIfDataFreeBSD7Emu = 0x98 sizeofIfDataFreeBSD8Emu = 0x98 sizeofIfDataFreeBSD9Emu = 0x98 sizeofIfDataFreeBSD10Emu = 0x98 sizeofIfDataFreeBSD11Emu = 0x98 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/route/zsys_freebsd_386.go0000644061062106075000000000545113172163402025107 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package route const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_ROUTE = 0x11 sysAF_LINK = 0x12 sysAF_INET6 = 0x1c sysSOCK_RAW = 0x3 sysNET_RT_DUMP = 0x1 sysNET_RT_FLAGS = 0x2 sysNET_RT_IFLIST = 0x3 sysNET_RT_IFMALIST = 0x4 sysNET_RT_IFLISTL = 0x5 ) const ( sysCTL_MAXNAME = 0x18 sysCTL_UNSPEC = 0x0 sysCTL_KERN = 0x1 sysCTL_VM = 0x2 sysCTL_VFS = 0x3 sysCTL_NET = 0x4 sysCTL_DEBUG = 0x5 sysCTL_HW = 0x6 sysCTL_MACHDEP = 0x7 sysCTL_USER = 0x8 sysCTL_P1003_1B = 0x9 ) const ( sysRTM_VERSION = 0x5 sysRTM_ADD = 0x1 sysRTM_DELETE = 0x2 sysRTM_CHANGE = 0x3 sysRTM_GET = 0x4 sysRTM_LOSING = 0x5 sysRTM_REDIRECT = 0x6 sysRTM_MISS = 0x7 sysRTM_LOCK = 0x8 sysRTM_RESOLVE = 0xb sysRTM_NEWADDR = 0xc sysRTM_DELADDR = 0xd sysRTM_IFINFO = 0xe sysRTM_NEWMADDR = 0xf sysRTM_DELMADDR = 0x10 sysRTM_IFANNOUNCE = 0x11 sysRTM_IEEE80211 = 0x12 sysRTA_DST = 0x1 sysRTA_GATEWAY = 0x2 sysRTA_NETMASK = 0x4 sysRTA_GENMASK = 0x8 sysRTA_IFP = 0x10 sysRTA_IFA = 0x20 sysRTA_AUTHOR = 0x40 sysRTA_BRD = 0x80 sysRTAX_DST = 0x0 sysRTAX_GATEWAY = 0x1 sysRTAX_NETMASK = 0x2 sysRTAX_GENMASK = 0x3 sysRTAX_IFP = 0x4 sysRTAX_IFA = 0x5 sysRTAX_AUTHOR = 0x6 sysRTAX_BRD = 0x7 sysRTAX_MAX = 0x8 ) const ( sizeofIfMsghdrlFreeBSD10 = 0x68 sizeofIfaMsghdrFreeBSD10 = 0x14 sizeofIfaMsghdrlFreeBSD10 = 0x6c sizeofIfmaMsghdrFreeBSD10 = 0x10 sizeofIfAnnouncemsghdrFreeBSD10 = 0x18 sizeofRtMsghdrFreeBSD10 = 0x5c sizeofRtMetricsFreeBSD10 = 0x38 sizeofIfMsghdrFreeBSD7 = 0x60 sizeofIfMsghdrFreeBSD8 = 0x60 sizeofIfMsghdrFreeBSD9 = 0x60 sizeofIfMsghdrFreeBSD10 = 0x64 sizeofIfMsghdrFreeBSD11 = 0xa8 sizeofIfDataFreeBSD7 = 0x50 sizeofIfDataFreeBSD8 = 0x50 sizeofIfDataFreeBSD9 = 0x50 sizeofIfDataFreeBSD10 = 0x54 sizeofIfDataFreeBSD11 = 0x98 // MODIFIED BY HAND FOR 386 EMULATION ON AMD64 // 386 EMULATION USES THE UNDERLYING RAW DATA LAYOUT sizeofIfMsghdrlFreeBSD10Emu = 0xb0 sizeofIfaMsghdrFreeBSD10Emu = 0x14 sizeofIfaMsghdrlFreeBSD10Emu = 0xb0 sizeofIfmaMsghdrFreeBSD10Emu = 0x10 sizeofIfAnnouncemsghdrFreeBSD10Emu = 0x18 sizeofRtMsghdrFreeBSD10Emu = 0x98 sizeofRtMetricsFreeBSD10Emu = 0x70 sizeofIfMsghdrFreeBSD7Emu = 0xa8 sizeofIfMsghdrFreeBSD8Emu = 0xa8 sizeofIfMsghdrFreeBSD9Emu = 0xa8 sizeofIfMsghdrFreeBSD10Emu = 0xa8 sizeofIfMsghdrFreeBSD11Emu = 0xa8 sizeofIfDataFreeBSD7Emu = 0x98 sizeofIfDataFreeBSD8Emu = 0x98 sizeofIfDataFreeBSD9Emu = 0x98 sizeofIfDataFreeBSD10Emu = 0x98 sizeofIfDataFreeBSD11Emu = 0x98 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/route/zsys_dragonfly.go0000644061062106075000000000371713172163402025065 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_dragonfly.go package route const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_ROUTE = 0x11 sysAF_LINK = 0x12 sysAF_INET6 = 0x1c sysSOCK_RAW = 0x3 sysNET_RT_DUMP = 0x1 sysNET_RT_FLAGS = 0x2 sysNET_RT_IFLIST = 0x3 sysNET_RT_MAXID = 0x4 ) const ( sysCTL_MAXNAME = 0xc sysCTL_UNSPEC = 0x0 sysCTL_KERN = 0x1 sysCTL_VM = 0x2 sysCTL_VFS = 0x3 sysCTL_NET = 0x4 sysCTL_DEBUG = 0x5 sysCTL_HW = 0x6 sysCTL_MACHDEP = 0x7 sysCTL_USER = 0x8 sysCTL_P1003_1B = 0x9 sysCTL_LWKT = 0xa sysCTL_MAXID = 0xb ) const ( sysRTM_VERSION = 0x6 sysRTM_ADD = 0x1 sysRTM_DELETE = 0x2 sysRTM_CHANGE = 0x3 sysRTM_GET = 0x4 sysRTM_LOSING = 0x5 sysRTM_REDIRECT = 0x6 sysRTM_MISS = 0x7 sysRTM_LOCK = 0x8 sysRTM_OLDADD = 0x9 sysRTM_OLDDEL = 0xa sysRTM_RESOLVE = 0xb sysRTM_NEWADDR = 0xc sysRTM_DELADDR = 0xd sysRTM_IFINFO = 0xe sysRTM_NEWMADDR = 0xf sysRTM_DELMADDR = 0x10 sysRTM_IFANNOUNCE = 0x11 sysRTM_IEEE80211 = 0x12 sysRTA_DST = 0x1 sysRTA_GATEWAY = 0x2 sysRTA_NETMASK = 0x4 sysRTA_GENMASK = 0x8 sysRTA_IFP = 0x10 sysRTA_IFA = 0x20 sysRTA_AUTHOR = 0x40 sysRTA_BRD = 0x80 sysRTA_MPLS1 = 0x100 sysRTA_MPLS2 = 0x200 sysRTA_MPLS3 = 0x400 sysRTAX_DST = 0x0 sysRTAX_GATEWAY = 0x1 sysRTAX_NETMASK = 0x2 sysRTAX_GENMASK = 0x3 sysRTAX_IFP = 0x4 sysRTAX_IFA = 0x5 sysRTAX_AUTHOR = 0x6 sysRTAX_BRD = 0x7 sysRTAX_MPLS1 = 0x8 sysRTAX_MPLS2 = 0x9 sysRTAX_MPLS3 = 0xa sysRTAX_MAX = 0xb ) const ( sizeofIfMsghdrDragonFlyBSD4 = 0xb0 sizeofIfaMsghdrDragonFlyBSD4 = 0x14 sizeofIfmaMsghdrDragonFlyBSD4 = 0x10 sizeofIfAnnouncemsghdrDragonFlyBSD4 = 0x18 sizeofRtMsghdrDragonFlyBSD4 = 0x98 sizeofRtMetricsDragonFlyBSD4 = 0x70 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/route/zsys_darwin.go0000644061062106075000000000371213172163402024357 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_darwin.go package route const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_ROUTE = 0x11 sysAF_LINK = 0x12 sysAF_INET6 = 0x1e sysSOCK_RAW = 0x3 sysNET_RT_DUMP = 0x1 sysNET_RT_FLAGS = 0x2 sysNET_RT_IFLIST = 0x3 sysNET_RT_STAT = 0x4 sysNET_RT_TRASH = 0x5 sysNET_RT_IFLIST2 = 0x6 sysNET_RT_DUMP2 = 0x7 sysNET_RT_MAXID = 0xa ) const ( sysCTL_MAXNAME = 0xc sysCTL_UNSPEC = 0x0 sysCTL_KERN = 0x1 sysCTL_VM = 0x2 sysCTL_VFS = 0x3 sysCTL_NET = 0x4 sysCTL_DEBUG = 0x5 sysCTL_HW = 0x6 sysCTL_MACHDEP = 0x7 sysCTL_USER = 0x8 sysCTL_MAXID = 0x9 ) const ( sysRTM_VERSION = 0x5 sysRTM_ADD = 0x1 sysRTM_DELETE = 0x2 sysRTM_CHANGE = 0x3 sysRTM_GET = 0x4 sysRTM_LOSING = 0x5 sysRTM_REDIRECT = 0x6 sysRTM_MISS = 0x7 sysRTM_LOCK = 0x8 sysRTM_OLDADD = 0x9 sysRTM_OLDDEL = 0xa sysRTM_RESOLVE = 0xb sysRTM_NEWADDR = 0xc sysRTM_DELADDR = 0xd sysRTM_IFINFO = 0xe sysRTM_NEWMADDR = 0xf sysRTM_DELMADDR = 0x10 sysRTM_IFINFO2 = 0x12 sysRTM_NEWMADDR2 = 0x13 sysRTM_GET2 = 0x14 sysRTA_DST = 0x1 sysRTA_GATEWAY = 0x2 sysRTA_NETMASK = 0x4 sysRTA_GENMASK = 0x8 sysRTA_IFP = 0x10 sysRTA_IFA = 0x20 sysRTA_AUTHOR = 0x40 sysRTA_BRD = 0x80 sysRTAX_DST = 0x0 sysRTAX_GATEWAY = 0x1 sysRTAX_NETMASK = 0x2 sysRTAX_GENMASK = 0x3 sysRTAX_IFP = 0x4 sysRTAX_IFA = 0x5 sysRTAX_AUTHOR = 0x6 sysRTAX_BRD = 0x7 sysRTAX_MAX = 0x8 ) const ( sizeofIfMsghdrDarwin15 = 0x70 sizeofIfaMsghdrDarwin15 = 0x14 sizeofIfmaMsghdrDarwin15 = 0x10 sizeofIfMsghdr2Darwin15 = 0xa0 sizeofIfmaMsghdr2Darwin15 = 0x14 sizeofIfDataDarwin15 = 0x60 sizeofIfData64Darwin15 = 0x80 sizeofRtMsghdrDarwin15 = 0x5c sizeofRtMsghdr2Darwin15 = 0x5c sizeofRtMetricsDarwin15 = 0x38 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/route/syscall.go0000644061062106075000000000133113172163402023450 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route import ( "syscall" "unsafe" ) var zero uintptr func sysctl(mib []int32, old *byte, oldlen *uintptr, new *byte, newlen uintptr) error { var p unsafe.Pointer if len(mib) > 0 { p = unsafe.Pointer(&mib[0]) } else { p = unsafe.Pointer(&zero) } _, _, errno := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(p), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if errno != 0 { return error(errno) } return nil } lxd-2.0.11/dist/src/golang.org/x/net/route/sys_openbsd.go0000644061062106075000000000407013172163402024331 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route import "unsafe" func (typ RIBType) parseable() bool { switch typ { case sysNET_RT_STATS, sysNET_RT_TABLE: return false default: return true } } // RouteMetrics represents route metrics. type RouteMetrics struct { PathMTU int // path maximum transmission unit } // SysType implements the SysType method of Sys interface. func (rmx *RouteMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *RouteMessage) Sys() []Sys { return []Sys{ &RouteMetrics{ PathMTU: int(nativeEndian.Uint32(m.raw[60:64])), }, } } // InterfaceMetrics represents interface metrics. type InterfaceMetrics struct { Type int // interface type MTU int // maximum transmission unit } // SysType implements the SysType method of Sys interface. func (imx *InterfaceMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *InterfaceMessage) Sys() []Sys { return []Sys{ &InterfaceMetrics{ Type: int(m.raw[24]), MTU: int(nativeEndian.Uint32(m.raw[28:32])), }, } } func probeRoutingStack() (int, map[int]*wireFormat) { var p uintptr rtm := &wireFormat{extOff: -1, bodyOff: -1} rtm.parse = rtm.parseRouteMessage ifm := &wireFormat{extOff: -1, bodyOff: -1} ifm.parse = ifm.parseInterfaceMessage ifam := &wireFormat{extOff: -1, bodyOff: -1} ifam.parse = ifam.parseInterfaceAddrMessage ifanm := &wireFormat{extOff: -1, bodyOff: -1} ifanm.parse = ifanm.parseInterfaceAnnounceMessage return int(unsafe.Sizeof(p)), map[int]*wireFormat{ sysRTM_ADD: rtm, sysRTM_DELETE: rtm, sysRTM_CHANGE: rtm, sysRTM_GET: rtm, sysRTM_LOSING: rtm, sysRTM_REDIRECT: rtm, sysRTM_MISS: rtm, sysRTM_LOCK: rtm, sysRTM_RESOLVE: rtm, sysRTM_NEWADDR: ifam, sysRTM_DELADDR: ifam, sysRTM_IFINFO: ifm, sysRTM_IFANNOUNCE: ifanm, sysRTM_DESYNC: rtm, } } lxd-2.0.11/dist/src/golang.org/x/net/route/sys_netbsd.go0000644061062106075000000000422613172163402024161 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route func (typ RIBType) parseable() bool { return true } // RouteMetrics represents route metrics. type RouteMetrics struct { PathMTU int // path maximum transmission unit } // SysType implements the SysType method of Sys interface. func (rmx *RouteMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *RouteMessage) Sys() []Sys { return []Sys{ &RouteMetrics{ PathMTU: int(nativeEndian.Uint64(m.raw[m.extOff+8 : m.extOff+16])), }, } } // RouteMetrics represents route metrics. type InterfaceMetrics struct { Type int // interface type MTU int // maximum transmission unit } // SysType implements the SysType method of Sys interface. func (imx *InterfaceMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *InterfaceMessage) Sys() []Sys { return []Sys{ &InterfaceMetrics{ Type: int(m.raw[m.extOff]), MTU: int(nativeEndian.Uint32(m.raw[m.extOff+8 : m.extOff+12])), }, } } func probeRoutingStack() (int, map[int]*wireFormat) { rtm := &wireFormat{extOff: 40, bodyOff: sizeofRtMsghdrNetBSD7} rtm.parse = rtm.parseRouteMessage ifm := &wireFormat{extOff: 16, bodyOff: sizeofIfMsghdrNetBSD7} ifm.parse = ifm.parseInterfaceMessage ifam := &wireFormat{extOff: sizeofIfaMsghdrNetBSD7, bodyOff: sizeofIfaMsghdrNetBSD7} ifam.parse = ifam.parseInterfaceAddrMessage ifanm := &wireFormat{extOff: sizeofIfAnnouncemsghdrNetBSD7, bodyOff: sizeofIfAnnouncemsghdrNetBSD7} ifanm.parse = ifanm.parseInterfaceAnnounceMessage // NetBSD 6 and above kernels require 64-bit aligned access to // routing facilities. return 8, map[int]*wireFormat{ sysRTM_ADD: rtm, sysRTM_DELETE: rtm, sysRTM_CHANGE: rtm, sysRTM_GET: rtm, sysRTM_LOSING: rtm, sysRTM_REDIRECT: rtm, sysRTM_MISS: rtm, sysRTM_LOCK: rtm, sysRTM_RESOLVE: rtm, sysRTM_NEWADDR: ifam, sysRTM_DELADDR: ifam, sysRTM_IFANNOUNCE: ifanm, sysRTM_IFINFO: ifm, } } lxd-2.0.11/dist/src/golang.org/x/net/route/sys_freebsd.go0000644061062106075000000001121113172163402024304 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route import ( "syscall" "unsafe" ) func (typ RIBType) parseable() bool { return true } // RouteMetrics represents route metrics. type RouteMetrics struct { PathMTU int // path maximum transmission unit } // SysType implements the SysType method of Sys interface. func (rmx *RouteMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *RouteMessage) Sys() []Sys { if kernelAlign == 8 { return []Sys{ &RouteMetrics{ PathMTU: int(nativeEndian.Uint64(m.raw[m.extOff+8 : m.extOff+16])), }, } } return []Sys{ &RouteMetrics{ PathMTU: int(nativeEndian.Uint32(m.raw[m.extOff+4 : m.extOff+8])), }, } } // InterfaceMetrics represents interface metrics. type InterfaceMetrics struct { Type int // interface type MTU int // maximum transmission unit } // SysType implements the SysType method of Sys interface. func (imx *InterfaceMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *InterfaceMessage) Sys() []Sys { return []Sys{ &InterfaceMetrics{ Type: int(m.raw[m.extOff]), MTU: int(nativeEndian.Uint32(m.raw[m.extOff+8 : m.extOff+12])), }, } } func probeRoutingStack() (int, map[int]*wireFormat) { var p uintptr wordSize := int(unsafe.Sizeof(p)) align := int(unsafe.Sizeof(p)) // In the case of kern.supported_archs="amd64 i386", we need // to know the underlying kernel's architecture because the // alignment for routing facilities are set at the build time // of the kernel. conf, _ := syscall.Sysctl("kern.conftxt") for i, j := 0, 0; j < len(conf); j++ { if conf[j] != '\n' { continue } s := conf[i:j] i = j + 1 if len(s) > len("machine") && s[:len("machine")] == "machine" { s = s[len("machine"):] for k := 0; k < len(s); k++ { if s[k] == ' ' || s[k] == '\t' { s = s[1:] } break } if s == "amd64" { align = 8 } break } } var rtm, ifm, ifam, ifmam, ifanm *wireFormat if align != wordSize { // 386 emulation on amd64 rtm = &wireFormat{extOff: sizeofRtMsghdrFreeBSD10Emu - sizeofRtMetricsFreeBSD10Emu, bodyOff: sizeofRtMsghdrFreeBSD10Emu} ifm = &wireFormat{extOff: 16} ifam = &wireFormat{extOff: sizeofIfaMsghdrFreeBSD10Emu, bodyOff: sizeofIfaMsghdrFreeBSD10Emu} ifmam = &wireFormat{extOff: sizeofIfmaMsghdrFreeBSD10Emu, bodyOff: sizeofIfmaMsghdrFreeBSD10Emu} ifanm = &wireFormat{extOff: sizeofIfAnnouncemsghdrFreeBSD10Emu, bodyOff: sizeofIfAnnouncemsghdrFreeBSD10Emu} } else { rtm = &wireFormat{extOff: sizeofRtMsghdrFreeBSD10 - sizeofRtMetricsFreeBSD10, bodyOff: sizeofRtMsghdrFreeBSD10} ifm = &wireFormat{extOff: 16} ifam = &wireFormat{extOff: sizeofIfaMsghdrFreeBSD10, bodyOff: sizeofIfaMsghdrFreeBSD10} ifmam = &wireFormat{extOff: sizeofIfmaMsghdrFreeBSD10, bodyOff: sizeofIfmaMsghdrFreeBSD10} ifanm = &wireFormat{extOff: sizeofIfAnnouncemsghdrFreeBSD10, bodyOff: sizeofIfAnnouncemsghdrFreeBSD10} } rel, _ := syscall.SysctlUint32("kern.osreldate") switch { case rel < 800000: if align != wordSize { // 386 emulation on amd64 ifm.bodyOff = sizeofIfMsghdrFreeBSD7Emu } else { ifm.bodyOff = sizeofIfMsghdrFreeBSD7 } case 800000 <= rel && rel < 900000: if align != wordSize { // 386 emulation on amd64 ifm.bodyOff = sizeofIfMsghdrFreeBSD8Emu } else { ifm.bodyOff = sizeofIfMsghdrFreeBSD8 } case 900000 <= rel && rel < 1000000: if align != wordSize { // 386 emulation on amd64 ifm.bodyOff = sizeofIfMsghdrFreeBSD9Emu } else { ifm.bodyOff = sizeofIfMsghdrFreeBSD9 } case 1000000 <= rel && rel < 1100000: if align != wordSize { // 386 emulation on amd64 ifm.bodyOff = sizeofIfMsghdrFreeBSD10Emu } else { ifm.bodyOff = sizeofIfMsghdrFreeBSD10 } default: if align != wordSize { // 386 emulation on amd64 ifm.bodyOff = sizeofIfMsghdrFreeBSD11Emu } else { ifm.bodyOff = sizeofIfMsghdrFreeBSD11 } } rtm.parse = rtm.parseRouteMessage ifm.parse = ifm.parseInterfaceMessage ifam.parse = ifam.parseInterfaceAddrMessage ifmam.parse = ifmam.parseInterfaceMulticastAddrMessage ifanm.parse = ifanm.parseInterfaceAnnounceMessage return align, map[int]*wireFormat{ sysRTM_ADD: rtm, sysRTM_DELETE: rtm, sysRTM_CHANGE: rtm, sysRTM_GET: rtm, sysRTM_LOSING: rtm, sysRTM_REDIRECT: rtm, sysRTM_MISS: rtm, sysRTM_LOCK: rtm, sysRTM_RESOLVE: rtm, sysRTM_NEWADDR: ifam, sysRTM_DELADDR: ifam, sysRTM_IFINFO: ifm, sysRTM_NEWMADDR: ifmam, sysRTM_DELMADDR: ifmam, sysRTM_IFANNOUNCE: ifanm, } } lxd-2.0.11/dist/src/golang.org/x/net/route/sys_dragonfly.go0000644061062106075000000000456313172163402024673 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route import "unsafe" func (typ RIBType) parseable() bool { return true } // RouteMetrics represents route metrics. type RouteMetrics struct { PathMTU int // path maximum transmission unit } // SysType implements the SysType method of Sys interface. func (rmx *RouteMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *RouteMessage) Sys() []Sys { return []Sys{ &RouteMetrics{ PathMTU: int(nativeEndian.Uint64(m.raw[m.extOff+8 : m.extOff+16])), }, } } // InterfaceMetrics represents interface metrics. type InterfaceMetrics struct { Type int // interface type MTU int // maximum transmission unit } // SysType implements the SysType method of Sys interface. func (imx *InterfaceMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *InterfaceMessage) Sys() []Sys { return []Sys{ &InterfaceMetrics{ Type: int(m.raw[m.extOff]), MTU: int(nativeEndian.Uint32(m.raw[m.extOff+8 : m.extOff+12])), }, } } func probeRoutingStack() (int, map[int]*wireFormat) { var p uintptr rtm := &wireFormat{extOff: 40, bodyOff: sizeofRtMsghdrDragonFlyBSD4} rtm.parse = rtm.parseRouteMessage ifm := &wireFormat{extOff: 16, bodyOff: sizeofIfMsghdrDragonFlyBSD4} ifm.parse = ifm.parseInterfaceMessage ifam := &wireFormat{extOff: sizeofIfaMsghdrDragonFlyBSD4, bodyOff: sizeofIfaMsghdrDragonFlyBSD4} ifam.parse = ifam.parseInterfaceAddrMessage ifmam := &wireFormat{extOff: sizeofIfmaMsghdrDragonFlyBSD4, bodyOff: sizeofIfmaMsghdrDragonFlyBSD4} ifmam.parse = ifmam.parseInterfaceMulticastAddrMessage ifanm := &wireFormat{extOff: sizeofIfAnnouncemsghdrDragonFlyBSD4, bodyOff: sizeofIfAnnouncemsghdrDragonFlyBSD4} ifanm.parse = ifanm.parseInterfaceAnnounceMessage return int(unsafe.Sizeof(p)), map[int]*wireFormat{ sysRTM_ADD: rtm, sysRTM_DELETE: rtm, sysRTM_CHANGE: rtm, sysRTM_GET: rtm, sysRTM_LOSING: rtm, sysRTM_REDIRECT: rtm, sysRTM_MISS: rtm, sysRTM_LOCK: rtm, sysRTM_RESOLVE: rtm, sysRTM_NEWADDR: ifam, sysRTM_DELADDR: ifam, sysRTM_IFINFO: ifm, sysRTM_NEWMADDR: ifmam, sysRTM_DELMADDR: ifmam, sysRTM_IFANNOUNCE: ifanm, } } lxd-2.0.11/dist/src/golang.org/x/net/route/sys_darwin.go0000644061062106075000000000525113172163402024165 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route func (typ RIBType) parseable() bool { switch typ { case sysNET_RT_STAT, sysNET_RT_TRASH: return false default: return true } } // RouteMetrics represents route metrics. type RouteMetrics struct { PathMTU int // path maximum transmission unit } // SysType implements the SysType method of Sys interface. func (rmx *RouteMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *RouteMessage) Sys() []Sys { return []Sys{ &RouteMetrics{ PathMTU: int(nativeEndian.Uint32(m.raw[m.extOff+4 : m.extOff+8])), }, } } // InterfaceMetrics represents interface metrics. type InterfaceMetrics struct { Type int // interface type MTU int // maximum transmission unit } // SysType implements the SysType method of Sys interface. func (imx *InterfaceMetrics) SysType() SysType { return SysMetrics } // Sys implements the Sys method of Message interface. func (m *InterfaceMessage) Sys() []Sys { return []Sys{ &InterfaceMetrics{ Type: int(m.raw[m.extOff]), MTU: int(nativeEndian.Uint32(m.raw[m.extOff+8 : m.extOff+12])), }, } } func probeRoutingStack() (int, map[int]*wireFormat) { rtm := &wireFormat{extOff: 36, bodyOff: sizeofRtMsghdrDarwin15} rtm.parse = rtm.parseRouteMessage rtm2 := &wireFormat{extOff: 36, bodyOff: sizeofRtMsghdr2Darwin15} rtm2.parse = rtm2.parseRouteMessage ifm := &wireFormat{extOff: 16, bodyOff: sizeofIfMsghdrDarwin15} ifm.parse = ifm.parseInterfaceMessage ifm2 := &wireFormat{extOff: 32, bodyOff: sizeofIfMsghdr2Darwin15} ifm2.parse = ifm2.parseInterfaceMessage ifam := &wireFormat{extOff: sizeofIfaMsghdrDarwin15, bodyOff: sizeofIfaMsghdrDarwin15} ifam.parse = ifam.parseInterfaceAddrMessage ifmam := &wireFormat{extOff: sizeofIfmaMsghdrDarwin15, bodyOff: sizeofIfmaMsghdrDarwin15} ifmam.parse = ifmam.parseInterfaceMulticastAddrMessage ifmam2 := &wireFormat{extOff: sizeofIfmaMsghdr2Darwin15, bodyOff: sizeofIfmaMsghdr2Darwin15} ifmam2.parse = ifmam2.parseInterfaceMulticastAddrMessage // Darwin kernels require 32-bit aligned access to routing facilities. return 4, map[int]*wireFormat{ sysRTM_ADD: rtm, sysRTM_DELETE: rtm, sysRTM_CHANGE: rtm, sysRTM_GET: rtm, sysRTM_LOSING: rtm, sysRTM_REDIRECT: rtm, sysRTM_MISS: rtm, sysRTM_LOCK: rtm, sysRTM_RESOLVE: rtm, sysRTM_NEWADDR: ifam, sysRTM_DELADDR: ifam, sysRTM_IFINFO: ifm, sysRTM_NEWMADDR: ifmam, sysRTM_DELMADDR: ifmam, sysRTM_IFINFO2: ifm2, sysRTM_NEWMADDR2: ifmam2, sysRTM_GET2: rtm2, } } lxd-2.0.11/dist/src/golang.org/x/net/route/sys.go0000644061062106075000000000145413172163402022622 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route import "unsafe" var ( nativeEndian binaryByteOrder kernelAlign int wireFormats map[int]*wireFormat ) func init() { i := uint32(1) b := (*[4]byte)(unsafe.Pointer(&i)) if b[0] == 1 { nativeEndian = littleEndian } else { nativeEndian = bigEndian } kernelAlign, wireFormats = probeRoutingStack() } func roundup(l int) int { if l == 0 { return kernelAlign } return (l + kernelAlign - 1) & ^(kernelAlign - 1) } type wireFormat struct { extOff int // offset of header extension bodyOff int // offset of message body parse func(RIBType, []byte) (Message, error) } lxd-2.0.11/dist/src/golang.org/x/net/route/route_test.go0000644061062106075000000002105213172163402024175 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route import ( "fmt" "os/exec" "runtime" "time" ) func (m *RouteMessage) String() string { return fmt.Sprintf("%s", addrAttrs(nativeEndian.Uint32(m.raw[12:16]))) } func (m *InterfaceMessage) String() string { var attrs addrAttrs if runtime.GOOS == "openbsd" { attrs = addrAttrs(nativeEndian.Uint32(m.raw[12:16])) } else { attrs = addrAttrs(nativeEndian.Uint32(m.raw[4:8])) } return fmt.Sprintf("%s", attrs) } func (m *InterfaceAddrMessage) String() string { var attrs addrAttrs if runtime.GOOS == "openbsd" { attrs = addrAttrs(nativeEndian.Uint32(m.raw[12:16])) } else { attrs = addrAttrs(nativeEndian.Uint32(m.raw[4:8])) } return fmt.Sprintf("%s", attrs) } func (m *InterfaceMulticastAddrMessage) String() string { return fmt.Sprintf("%s", addrAttrs(nativeEndian.Uint32(m.raw[4:8]))) } func (m *InterfaceAnnounceMessage) String() string { what := "" switch m.What { case 0: what = "arrival" case 1: what = "departure" } return fmt.Sprintf("(%d %s %s)", m.Index, m.Name, what) } func (m *InterfaceMetrics) String() string { return fmt.Sprintf("(type=%d mtu=%d)", m.Type, m.MTU) } func (m *RouteMetrics) String() string { return fmt.Sprintf("(pmtu=%d)", m.PathMTU) } type addrAttrs uint var addrAttrNames = [...]string{ "dst", "gateway", "netmask", "genmask", "ifp", "ifa", "author", "brd", "df:mpls1-n:tag-o:src", // mpls1 for dragonfly, tag for netbsd, src for openbsd "df:mpls2-o:srcmask", // mpls2 for dragonfly, srcmask for openbsd "df:mpls3-o:label", // mpls3 for dragonfly, label for openbsd "o:bfd", // bfd for openbsd "o:dns", // dns for openbsd "o:static", // static for openbsd "o:search", // search for openbsd } func (attrs addrAttrs) String() string { var s string for i, name := range addrAttrNames { if attrs&(1<" } return s } type msgs []Message func (ms msgs) validate() ([]string, error) { var ss []string for _, m := range ms { switch m := m.(type) { case *RouteMessage: if err := addrs(m.Addrs).match(addrAttrs(nativeEndian.Uint32(m.raw[12:16]))); err != nil { return nil, err } sys := m.Sys() if sys == nil { return nil, fmt.Errorf("no sys for %s", m.String()) } ss = append(ss, m.String()+" "+syss(sys).String()+" "+addrs(m.Addrs).String()) case *InterfaceMessage: var attrs addrAttrs if runtime.GOOS == "openbsd" { attrs = addrAttrs(nativeEndian.Uint32(m.raw[12:16])) } else { attrs = addrAttrs(nativeEndian.Uint32(m.raw[4:8])) } if err := addrs(m.Addrs).match(attrs); err != nil { return nil, err } sys := m.Sys() if sys == nil { return nil, fmt.Errorf("no sys for %s", m.String()) } ss = append(ss, m.String()+" "+syss(sys).String()+" "+addrs(m.Addrs).String()) case *InterfaceAddrMessage: var attrs addrAttrs if runtime.GOOS == "openbsd" { attrs = addrAttrs(nativeEndian.Uint32(m.raw[12:16])) } else { attrs = addrAttrs(nativeEndian.Uint32(m.raw[4:8])) } if err := addrs(m.Addrs).match(attrs); err != nil { return nil, err } ss = append(ss, m.String()+" "+addrs(m.Addrs).String()) case *InterfaceMulticastAddrMessage: if err := addrs(m.Addrs).match(addrAttrs(nativeEndian.Uint32(m.raw[4:8]))); err != nil { return nil, err } ss = append(ss, m.String()+" "+addrs(m.Addrs).String()) case *InterfaceAnnounceMessage: ss = append(ss, m.String()) default: ss = append(ss, fmt.Sprintf("%+v", m)) } } return ss, nil } type syss []Sys func (sys syss) String() string { var s string for _, sy := range sys { switch sy := sy.(type) { case *InterfaceMetrics: if len(s) > 0 { s += " " } s += sy.String() case *RouteMetrics: if len(s) > 0 { s += " " } s += sy.String() } } return s } type addrFamily int func (af addrFamily) String() string { switch af { case sysAF_UNSPEC: return "unspec" case sysAF_LINK: return "link" case sysAF_INET: return "inet4" case sysAF_INET6: return "inet6" default: return fmt.Sprintf("%d", af) } } const hexDigit = "0123456789abcdef" type llAddr []byte func (a llAddr) String() string { if len(a) == 0 { return "" } buf := make([]byte, 0, len(a)*3-1) for i, b := range a { if i > 0 { buf = append(buf, ':') } buf = append(buf, hexDigit[b>>4]) buf = append(buf, hexDigit[b&0xF]) } return string(buf) } type ipAddr []byte func (a ipAddr) String() string { if len(a) == 0 { return "" } if len(a) == 4 { return fmt.Sprintf("%d.%d.%d.%d", a[0], a[1], a[2], a[3]) } if len(a) == 16 { return fmt.Sprintf("%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]) } s := make([]byte, len(a)*2) for i, tn := range a { s[i*2], s[i*2+1] = hexDigit[tn>>4], hexDigit[tn&0xf] } return string(s) } func (a *LinkAddr) String() string { name := a.Name if name == "" { name = "" } lla := llAddr(a.Addr).String() if lla == "" { lla = "" } return fmt.Sprintf("(%v %d %s %s)", addrFamily(a.Family()), a.Index, name, lla) } func (a *Inet4Addr) String() string { return fmt.Sprintf("(%v %v)", addrFamily(a.Family()), ipAddr(a.IP[:])) } func (a *Inet6Addr) String() string { return fmt.Sprintf("(%v %v %d)", addrFamily(a.Family()), ipAddr(a.IP[:]), a.ZoneID) } func (a *DefaultAddr) String() string { return fmt.Sprintf("(%v %s)", addrFamily(a.Family()), ipAddr(a.Raw[2:]).String()) } type addrs []Addr func (as addrs) String() string { var s string for _, a := range as { if a == nil { continue } if len(s) > 0 { s += " " } switch a := a.(type) { case *LinkAddr: s += a.String() case *Inet4Addr: s += a.String() case *Inet6Addr: s += a.String() case *DefaultAddr: s += a.String() } } if s == "" { return "" } return s } func (as addrs) match(attrs addrAttrs) error { var ts addrAttrs af := sysAF_UNSPEC for i := range as { if as[i] != nil { ts |= 1 << uint(i) } switch as[i].(type) { case *Inet4Addr: if af == sysAF_UNSPEC { af = sysAF_INET } if af != sysAF_INET { return fmt.Errorf("got %v; want %v", addrs(as), addrFamily(af)) } case *Inet6Addr: if af == sysAF_UNSPEC { af = sysAF_INET6 } if af != sysAF_INET6 { return fmt.Errorf("got %v; want %v", addrs(as), addrFamily(af)) } } } if ts != attrs && ts > attrs { return fmt.Errorf("%v not included in %v", ts, attrs) } return nil } func fetchAndParseRIB(af int, typ RIBType) ([]Message, error) { var err error var b []byte for i := 0; i < 3; i++ { if b, err = FetchRIB(af, typ, 0); err != nil { time.Sleep(10 * time.Millisecond) continue } break } if err != nil { return nil, fmt.Errorf("%v %d %v", addrFamily(af), typ, err) } ms, err := ParseRIB(typ, b) if err != nil { return nil, fmt.Errorf("%v %d %v", addrFamily(af), typ, err) } return ms, nil } // propVirtual is a proprietary virtual network interface. type propVirtual struct { name string addr, mask string setupCmds []*exec.Cmd teardownCmds []*exec.Cmd } func (pv *propVirtual) setup() error { for _, cmd := range pv.setupCmds { if err := cmd.Run(); err != nil { pv.teardown() return err } } return nil } func (pv *propVirtual) teardown() error { for _, cmd := range pv.teardownCmds { if err := cmd.Run(); err != nil { return err } } return nil } func (pv *propVirtual) configure(suffix int) error { if runtime.GOOS == "openbsd" { pv.name = fmt.Sprintf("vether%d", suffix) } else { pv.name = fmt.Sprintf("vlan%d", suffix) } xname, err := exec.LookPath("ifconfig") if err != nil { return err } pv.setupCmds = append(pv.setupCmds, &exec.Cmd{ Path: xname, Args: []string{"ifconfig", pv.name, "create"}, }) if runtime.GOOS == "netbsd" { // NetBSD requires an underlying dot1Q-capable network // interface. pv.setupCmds = append(pv.setupCmds, &exec.Cmd{ Path: xname, Args: []string{"ifconfig", pv.name, "vlan", fmt.Sprintf("%d", suffix&0xfff), "vlanif", "wm0"}, }) } pv.setupCmds = append(pv.setupCmds, &exec.Cmd{ Path: xname, Args: []string{"ifconfig", pv.name, "inet", pv.addr, "netmask", pv.mask}, }) pv.teardownCmds = append(pv.teardownCmds, &exec.Cmd{ Path: xname, Args: []string{"ifconfig", pv.name, "destroy"}, }) return nil } lxd-2.0.11/dist/src/golang.org/x/net/route/route_openbsd.go0000644061062106075000000000331513172163402024652 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route import "syscall" func (m *RouteMessage) marshal() ([]byte, error) { l := sizeofRtMsghdr + addrsSpace(m.Addrs) b := make([]byte, l) nativeEndian.PutUint16(b[:2], uint16(l)) if m.Version == 0 { b[2] = sysRTM_VERSION } else { b[2] = byte(m.Version) } b[3] = byte(m.Type) nativeEndian.PutUint16(b[4:6], uint16(sizeofRtMsghdr)) nativeEndian.PutUint32(b[16:20], uint32(m.Flags)) nativeEndian.PutUint16(b[6:8], uint16(m.Index)) nativeEndian.PutUint32(b[24:28], uint32(m.ID)) nativeEndian.PutUint32(b[28:32], uint32(m.Seq)) attrs, err := marshalAddrs(b[sizeofRtMsghdr:], m.Addrs) if err != nil { return nil, err } if attrs > 0 { nativeEndian.PutUint32(b[12:16], uint32(attrs)) } return b, nil } func (*wireFormat) parseRouteMessage(_ RIBType, b []byte) (Message, error) { if len(b) < sizeofRtMsghdr { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } m := &RouteMessage{ Version: int(b[2]), Type: int(b[3]), Flags: int(nativeEndian.Uint32(b[16:20])), Index: int(nativeEndian.Uint16(b[6:8])), ID: uintptr(nativeEndian.Uint32(b[24:28])), Seq: int(nativeEndian.Uint32(b[28:32])), raw: b[:l], } ll := int(nativeEndian.Uint16(b[4:6])) if len(b) < ll { return nil, errInvalidMessage } errno := syscall.Errno(nativeEndian.Uint32(b[32:36])) if errno != 0 { m.Err = errno } as, err := parseAddrs(uint(nativeEndian.Uint32(b[12:16])), parseKernelInetAddr, b[ll:]) if err != nil { return nil, err } m.Addrs = as return m, nil } lxd-2.0.11/dist/src/golang.org/x/net/route/route_classic.go0000644061062106075000000000330613172163402024641 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd package route import "syscall" func (m *RouteMessage) marshal() ([]byte, error) { w, ok := wireFormats[m.Type] if !ok { return nil, errUnsupportedMessage } l := w.bodyOff + addrsSpace(m.Addrs) b := make([]byte, l) nativeEndian.PutUint16(b[:2], uint16(l)) if m.Version == 0 { b[2] = sysRTM_VERSION } else { b[2] = byte(m.Version) } b[3] = byte(m.Type) nativeEndian.PutUint32(b[8:12], uint32(m.Flags)) nativeEndian.PutUint16(b[4:6], uint16(m.Index)) nativeEndian.PutUint32(b[16:20], uint32(m.ID)) nativeEndian.PutUint32(b[20:24], uint32(m.Seq)) attrs, err := marshalAddrs(b[w.bodyOff:], m.Addrs) if err != nil { return nil, err } if attrs > 0 { nativeEndian.PutUint32(b[12:16], uint32(attrs)) } return b, nil } func (w *wireFormat) parseRouteMessage(typ RIBType, b []byte) (Message, error) { if len(b) < w.bodyOff { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } m := &RouteMessage{ Version: int(b[2]), Type: int(b[3]), Flags: int(nativeEndian.Uint32(b[8:12])), Index: int(nativeEndian.Uint16(b[4:6])), ID: uintptr(nativeEndian.Uint32(b[16:20])), Seq: int(nativeEndian.Uint32(b[20:24])), extOff: w.extOff, raw: b[:l], } errno := syscall.Errno(nativeEndian.Uint32(b[28:32])) if errno != 0 { m.Err = errno } var err error m.Addrs, err = parseAddrs(uint(nativeEndian.Uint32(b[12:16])), parseKernelInetAddr, b[w.bodyOff:]) if err != nil { return nil, err } return m, nil } lxd-2.0.11/dist/src/golang.org/x/net/route/route.go0000644061062106075000000000767613172163402023156 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd // Package route provides basic functions for the manipulation of // packet routing facilities on BSD variants. // // The package supports any version of Darwin, any version of // DragonFly BSD, FreeBSD 7 through 11, NetBSD 6 and above, and // OpenBSD 5.6 and above. package route import ( "errors" "os" "syscall" ) var ( errUnsupportedMessage = errors.New("unsupported message") errMessageMismatch = errors.New("message mismatch") errMessageTooShort = errors.New("message too short") errInvalidMessage = errors.New("invalid message") errInvalidAddr = errors.New("invalid address") errShortBuffer = errors.New("short buffer") ) // A RouteMessage represents a message conveying an address prefix, a // nexthop address and an output interface. // // Unlike other messages, this message can be used to query adjacency // information for the given address prefix, to add a new route, and // to delete or modify the existing route from the routing information // base inside the kernel by writing and reading route messages on a // routing socket. // // For the manipulation of routing information, the route message must // contain appropriate fields that include: // // Version = // Type = // Flags = // Index = // ID = // Seq = // Addrs = // // The Type field specifies a type of manipulation, the Flags field // specifies a class of target information and the Addrs field // specifies target information like the following: // // route.RouteMessage{ // Version: RTM_VERSION, // Type: RTM_GET, // Flags: RTF_UP | RTF_HOST, // ID: uintptr(os.Getpid()), // Seq: 1, // Addrs: []route.Addrs{ // RTAX_DST: &route.Inet4Addr{ ... }, // RTAX_IFP: &route.LinkAddr{ ... }, // RTAX_BRD: &route.Inet4Addr{ ... }, // }, // } // // The values for the above fields depend on the implementation of // each operating system. // // The Err field on a response message contains an error value on the // requested operation. If non-nil, the requested operation is failed. type RouteMessage struct { Version int // message version Type int // message type Flags int // route flags Index int // interface index when atatched ID uintptr // sender's identifier; usually process ID Seq int // sequence number Err error // error on requested operation Addrs []Addr // addresses extOff int // offset of header extension raw []byte // raw message } // Marshal returns the binary encoding of m. func (m *RouteMessage) Marshal() ([]byte, error) { return m.marshal() } // A RIBType reprensents a type of routing information base. type RIBType int const ( RIBTypeRoute RIBType = syscall.NET_RT_DUMP RIBTypeInterface RIBType = syscall.NET_RT_IFLIST ) // FetchRIB fetches a routing information base from the operating // system. // // The provided af must be an address family. // // The provided arg must be a RIBType-specific argument. // When RIBType is related to routes, arg might be a set of route // flags. When RIBType is related to network interfaces, arg might be // an interface index or a set of interface flags. In most cases, zero // means a wildcard. func FetchRIB(af int, typ RIBType, arg int) ([]byte, error) { mib := [6]int32{sysCTL_NET, sysAF_ROUTE, 0, int32(af), int32(typ), int32(arg)} n := uintptr(0) if err := sysctl(mib[:], nil, &n, nil, 0); err != nil { return nil, os.NewSyscallError("sysctl", err) } if n == 0 { return nil, nil } b := make([]byte, n) if err := sysctl(mib[:], &b[0], &n, nil, 0); err != nil { return nil, os.NewSyscallError("sysctl", err) } return b[:n], nil } lxd-2.0.11/dist/src/golang.org/x/net/route/message_test.go0000644061062106075000000001210313172163402024460 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route import ( "os" "syscall" "testing" "time" ) func TestFetchAndParseRIB(t *testing.T) { for _, typ := range []RIBType{sysNET_RT_DUMP, sysNET_RT_IFLIST} { var lastErr error var ms []Message for _, af := range []int{sysAF_UNSPEC, sysAF_INET, sysAF_INET6} { rs, err := fetchAndParseRIB(af, typ) if err != nil { lastErr = err continue } ms = append(ms, rs...) } if len(ms) == 0 && lastErr != nil { t.Error(typ, lastErr) continue } ss, err := msgs(ms).validate() if err != nil { t.Error(typ, err) continue } for _, s := range ss { t.Log(typ, s) } } } var ( rtmonSock int rtmonErr error ) func init() { // We need to keep rtmonSock alive to avoid treading on // recycled socket descriptors. rtmonSock, rtmonErr = syscall.Socket(sysAF_ROUTE, sysSOCK_RAW, sysAF_UNSPEC) } // TestMonitorAndParseRIB leaks a worker goroutine and a socket // descriptor but that's intentional. func TestMonitorAndParseRIB(t *testing.T) { if testing.Short() || os.Getuid() != 0 { t.Skip("must be root") } if rtmonErr != nil { t.Fatal(rtmonErr) } // We suppose that using an IPv4 link-local address and the // dot1Q ID for Token Ring and FDDI doesn't harm anyone. pv := &propVirtual{addr: "169.254.0.1", mask: "255.255.255.0"} if err := pv.configure(1002); err != nil { t.Skip(err) } if err := pv.setup(); err != nil { t.Skip(err) } pv.teardown() go func() { b := make([]byte, os.Getpagesize()) for { // There's no easy way to unblock this read // call because the routing message exchange // over routing socket is a connectionless // message-oriented protocol, no control plane // for signaling connectivity, and we cannot // use the net package of standard library due // to the lack of support for routing socket // and circular dependency. n, err := syscall.Read(rtmonSock, b) if err != nil { return } ms, err := ParseRIB(0, b[:n]) if err != nil { t.Error(err) return } ss, err := msgs(ms).validate() if err != nil { t.Error(err) return } for _, s := range ss { t.Log(s) } } }() for _, vid := range []int{1002, 1003, 1004, 1005} { pv := &propVirtual{addr: "169.254.0.1", mask: "255.255.255.0"} if err := pv.configure(vid); err != nil { t.Fatal(err) } if err := pv.setup(); err != nil { t.Fatal(err) } time.Sleep(200 * time.Millisecond) if err := pv.teardown(); err != nil { t.Fatal(err) } time.Sleep(200 * time.Millisecond) } } func TestParseRIBWithFuzz(t *testing.T) { for _, fuzz := range []string{ "0\x00\x05\x050000000000000000" + "00000000000000000000" + "00000000000000000000" + "00000000000000000000" + "0000000000000\x02000000" + "00000000", "\x02\x00\x05\f0000000000000000" + "0\x0200000000000000", "\x02\x00\x05\x100000000000000\x1200" + "0\x00\xff\x00", "\x02\x00\x05\f0000000000000000" + "0\x12000\x00\x02\x0000", "\x00\x00\x00\x01\x00", "00000", } { for typ := RIBType(0); typ < 256; typ++ { ParseRIB(typ, []byte(fuzz)) } } } func TestRouteMessage(t *testing.T) { s, err := syscall.Socket(sysAF_ROUTE, sysSOCK_RAW, sysAF_UNSPEC) if err != nil { t.Fatal(err) } defer syscall.Close(s) var ms []RouteMessage for _, af := range []int{sysAF_INET, sysAF_INET6} { if _, err := fetchAndParseRIB(af, sysNET_RT_DUMP); err != nil { t.Log(err) continue } switch af { case sysAF_INET: ms = append(ms, []RouteMessage{ { Type: sysRTM_GET, Addrs: []Addr{ &Inet4Addr{IP: [4]byte{127, 0, 0, 1}}, nil, nil, nil, &LinkAddr{}, &Inet4Addr{}, nil, &Inet4Addr{}, }, }, { Type: sysRTM_GET, Addrs: []Addr{ &Inet4Addr{IP: [4]byte{127, 0, 0, 1}}, }, }, }...) case sysAF_INET6: ms = append(ms, []RouteMessage{ { Type: sysRTM_GET, Addrs: []Addr{ &Inet6Addr{IP: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}, nil, nil, nil, &LinkAddr{}, &Inet6Addr{}, nil, &Inet6Addr{}, }, }, { Type: sysRTM_GET, Addrs: []Addr{ &Inet6Addr{IP: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}, }, }, }...) } } for i, m := range ms { m.ID = uintptr(os.Getpid()) m.Seq = i + 1 wb, err := m.Marshal() if err != nil { t.Fatalf("%v: %v", m, err) } if _, err := syscall.Write(s, wb); err != nil { t.Fatalf("%v: %v", m, err) } rb := make([]byte, os.Getpagesize()) n, err := syscall.Read(s, rb) if err != nil { t.Fatalf("%v: %v", m, err) } rms, err := ParseRIB(0, rb[:n]) if err != nil { t.Fatalf("%v: %v", m, err) } for _, rm := range rms { err := rm.(*RouteMessage).Err if err != nil { t.Errorf("%v: %v", m, err) } } ss, err := msgs(rms).validate() if err != nil { t.Fatalf("%v: %v", m, err) } for _, s := range ss { t.Log(s) } } } lxd-2.0.11/dist/src/golang.org/x/net/route/message_freebsd_test.go0000644061062106075000000000403013172163402026152 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route import ( "testing" "unsafe" ) func TestFetchAndParseRIBOnFreeBSD(t *testing.T) { for _, typ := range []RIBType{sysNET_RT_IFMALIST} { var lastErr error var ms []Message for _, af := range []int{sysAF_UNSPEC, sysAF_INET, sysAF_INET6} { rs, err := fetchAndParseRIB(af, typ) if err != nil { lastErr = err continue } ms = append(ms, rs...) } if len(ms) == 0 && lastErr != nil { t.Error(typ, lastErr) continue } ss, err := msgs(ms).validate() if err != nil { t.Error(typ, err) continue } for _, s := range ss { t.Log(s) } } } func TestFetchAndParseRIBOnFreeBSD10AndAbove(t *testing.T) { if _, err := FetchRIB(sysAF_UNSPEC, sysNET_RT_IFLISTL, 0); err != nil { t.Skip("NET_RT_IFLISTL not supported") } var p uintptr if kernelAlign != int(unsafe.Sizeof(p)) { t.Skip("NET_RT_IFLIST vs. NET_RT_IFLISTL doesn't work for 386 emulation on amd64") } var tests = [2]struct { typ RIBType b []byte msgs []Message ss []string }{ {typ: sysNET_RT_IFLIST}, {typ: sysNET_RT_IFLISTL}, } for i := range tests { var lastErr error for _, af := range []int{sysAF_UNSPEC, sysAF_INET, sysAF_INET6} { rs, err := fetchAndParseRIB(af, tests[i].typ) if err != nil { lastErr = err continue } tests[i].msgs = append(tests[i].msgs, rs...) } if len(tests[i].msgs) == 0 && lastErr != nil { t.Error(tests[i].typ, lastErr) continue } tests[i].ss, lastErr = msgs(tests[i].msgs).validate() if lastErr != nil { t.Error(tests[i].typ, lastErr) continue } for _, s := range tests[i].ss { t.Log(s) } } for i := len(tests) - 1; i > 0; i-- { if len(tests[i].ss) != len(tests[i-1].ss) { t.Errorf("got %v; want %v", tests[i].ss, tests[i-1].ss) continue } for j, s1 := range tests[i].ss { s0 := tests[i-1].ss[j] if s1 != s0 { t.Errorf("got %s; want %s", s1, s0) } } } } lxd-2.0.11/dist/src/golang.org/x/net/route/message_darwin_test.go0000644061062106075000000000140613172163402026030 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route import "testing" func TestFetchAndParseRIBOnDarwin(t *testing.T) { for _, typ := range []RIBType{sysNET_RT_FLAGS, sysNET_RT_DUMP2, sysNET_RT_IFLIST2} { var lastErr error var ms []Message for _, af := range []int{sysAF_UNSPEC, sysAF_INET, sysAF_INET6} { rs, err := fetchAndParseRIB(af, typ) if err != nil { lastErr = err continue } ms = append(ms, rs...) } if len(ms) == 0 && lastErr != nil { t.Error(typ, lastErr) continue } ss, err := msgs(ms).validate() if err != nil { t.Error(typ, err) continue } for _, s := range ss { t.Log(s) } } } lxd-2.0.11/dist/src/golang.org/x/net/route/message.go0000644061062106075000000000302513172163402023424 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route // A Message represents a routing message. type Message interface { // Sys returns operating system-specific information. Sys() []Sys } // A Sys reprensents operating system-specific information. type Sys interface { // SysType returns a type of operating system-specific // information. SysType() SysType } // A SysType represents a type of operating system-specific // information. type SysType int const ( SysMetrics SysType = iota SysStats ) // ParseRIB parses b as a routing information base and returns a list // of routing messages. func ParseRIB(typ RIBType, b []byte) ([]Message, error) { if !typ.parseable() { return nil, errUnsupportedMessage } var msgs []Message nmsgs, nskips := 0, 0 for len(b) > 4 { nmsgs++ l := int(nativeEndian.Uint16(b[:2])) if l == 0 { return nil, errInvalidMessage } if len(b) < l { return nil, errMessageTooShort } if b[2] != sysRTM_VERSION { b = b[l:] continue } if w, ok := wireFormats[int(b[3])]; !ok { nskips++ } else { m, err := w.parse(typ, b) if err != nil { return nil, err } if m == nil { nskips++ } else { msgs = append(msgs, m) } } b = b[l:] } // We failed to parse any of the messages - version mismatch? if nmsgs != len(msgs)+nskips { return nil, errMessageMismatch } return msgs, nil } lxd-2.0.11/dist/src/golang.org/x/net/route/interface_openbsd.go0000644061062106075000000000421013172163402025447 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route func (*wireFormat) parseInterfaceMessage(_ RIBType, b []byte) (Message, error) { if len(b) < 32 { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } attrs := uint(nativeEndian.Uint32(b[12:16])) if attrs&sysRTA_IFP == 0 { return nil, nil } m := &InterfaceMessage{ Version: int(b[2]), Type: int(b[3]), Flags: int(nativeEndian.Uint32(b[16:20])), Index: int(nativeEndian.Uint16(b[6:8])), Addrs: make([]Addr, sysRTAX_MAX), raw: b[:l], } ll := int(nativeEndian.Uint16(b[4:6])) if len(b) < ll { return nil, errInvalidMessage } a, err := parseLinkAddr(b[ll:]) if err != nil { return nil, err } m.Addrs[sysRTAX_IFP] = a m.Name = a.(*LinkAddr).Name return m, nil } func (*wireFormat) parseInterfaceAddrMessage(_ RIBType, b []byte) (Message, error) { if len(b) < 24 { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } bodyOff := int(nativeEndian.Uint16(b[4:6])) if len(b) < bodyOff { return nil, errInvalidMessage } m := &InterfaceAddrMessage{ Version: int(b[2]), Type: int(b[3]), Flags: int(nativeEndian.Uint32(b[12:16])), Index: int(nativeEndian.Uint16(b[6:8])), raw: b[:l], } var err error m.Addrs, err = parseAddrs(uint(nativeEndian.Uint32(b[12:16])), parseKernelInetAddr, b[bodyOff:]) if err != nil { return nil, err } return m, nil } func (*wireFormat) parseInterfaceAnnounceMessage(_ RIBType, b []byte) (Message, error) { if len(b) < 26 { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } m := &InterfaceAnnounceMessage{ Version: int(b[2]), Type: int(b[3]), Index: int(nativeEndian.Uint16(b[6:8])), What: int(nativeEndian.Uint16(b[8:10])), raw: b[:l], } for i := 0; i < 16; i++ { if b[10+i] != 0 { continue } m.Name = string(b[10 : 10+i]) break } return m, nil } lxd-2.0.11/dist/src/golang.org/x/net/route/interface_multicast.go0000644061062106075000000000146613172163402026034 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd package route func (w *wireFormat) parseInterfaceMulticastAddrMessage(_ RIBType, b []byte) (Message, error) { if len(b) < w.bodyOff { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } m := &InterfaceMulticastAddrMessage{ Version: int(b[2]), Type: int(b[3]), Flags: int(nativeEndian.Uint32(b[8:12])), Index: int(nativeEndian.Uint16(b[12:14])), raw: b[:l], } var err error m.Addrs, err = parseAddrs(uint(nativeEndian.Uint32(b[4:8])), parseKernelInetAddr, b[w.bodyOff:]) if err != nil { return nil, err } return m, nil } lxd-2.0.11/dist/src/golang.org/x/net/route/interface_freebsd.go0000644061062106075000000000363313172163402025437 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route func (w *wireFormat) parseInterfaceMessage(typ RIBType, b []byte) (Message, error) { var extOff, bodyOff int if typ == sysNET_RT_IFLISTL { if len(b) < 20 { return nil, errMessageTooShort } extOff = int(nativeEndian.Uint16(b[18:20])) bodyOff = int(nativeEndian.Uint16(b[16:18])) } else { extOff = w.extOff bodyOff = w.bodyOff } if len(b) < extOff || len(b) < bodyOff { return nil, errInvalidMessage } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } attrs := uint(nativeEndian.Uint32(b[4:8])) if attrs&sysRTA_IFP == 0 { return nil, nil } m := &InterfaceMessage{ Version: int(b[2]), Type: int(b[3]), Flags: int(nativeEndian.Uint32(b[8:12])), Index: int(nativeEndian.Uint16(b[12:14])), Addrs: make([]Addr, sysRTAX_MAX), extOff: extOff, raw: b[:l], } a, err := parseLinkAddr(b[bodyOff:]) if err != nil { return nil, err } m.Addrs[sysRTAX_IFP] = a m.Name = a.(*LinkAddr).Name return m, nil } func (w *wireFormat) parseInterfaceAddrMessage(typ RIBType, b []byte) (Message, error) { var bodyOff int if typ == sysNET_RT_IFLISTL { if len(b) < 24 { return nil, errMessageTooShort } bodyOff = int(nativeEndian.Uint16(b[16:18])) } else { bodyOff = w.bodyOff } if len(b) < bodyOff { return nil, errInvalidMessage } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } m := &InterfaceAddrMessage{ Version: int(b[2]), Type: int(b[3]), Flags: int(nativeEndian.Uint32(b[8:12])), Index: int(nativeEndian.Uint16(b[12:14])), raw: b[:l], } var err error m.Addrs, err = parseAddrs(uint(nativeEndian.Uint32(b[4:8])), parseKernelInetAddr, b[bodyOff:]) if err != nil { return nil, err } return m, nil } lxd-2.0.11/dist/src/golang.org/x/net/route/interface_classic.go0000644061062106075000000000314013172163402025437 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly netbsd package route import "runtime" func (w *wireFormat) parseInterfaceMessage(_ RIBType, b []byte) (Message, error) { if len(b) < w.bodyOff { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } attrs := uint(nativeEndian.Uint32(b[4:8])) if attrs&sysRTA_IFP == 0 { return nil, nil } m := &InterfaceMessage{ Version: int(b[2]), Type: int(b[3]), Addrs: make([]Addr, sysRTAX_MAX), Flags: int(nativeEndian.Uint32(b[8:12])), Index: int(nativeEndian.Uint16(b[12:14])), extOff: w.extOff, raw: b[:l], } a, err := parseLinkAddr(b[w.bodyOff:]) if err != nil { return nil, err } m.Addrs[sysRTAX_IFP] = a m.Name = a.(*LinkAddr).Name return m, nil } func (w *wireFormat) parseInterfaceAddrMessage(_ RIBType, b []byte) (Message, error) { if len(b) < w.bodyOff { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } m := &InterfaceAddrMessage{ Version: int(b[2]), Type: int(b[3]), Flags: int(nativeEndian.Uint32(b[8:12])), raw: b[:l], } if runtime.GOOS == "netbsd" { m.Index = int(nativeEndian.Uint16(b[16:18])) } else { m.Index = int(nativeEndian.Uint16(b[12:14])) } var err error m.Addrs, err = parseAddrs(uint(nativeEndian.Uint32(b[4:8])), parseKernelInetAddr, b[w.bodyOff:]) if err != nil { return nil, err } return m, nil } lxd-2.0.11/dist/src/golang.org/x/net/route/interface_announce.go0000644061062106075000000000137313172163402025632 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build dragonfly freebsd netbsd package route func (w *wireFormat) parseInterfaceAnnounceMessage(_ RIBType, b []byte) (Message, error) { if len(b) < w.bodyOff { return nil, errMessageTooShort } l := int(nativeEndian.Uint16(b[:2])) if len(b) < l { return nil, errInvalidMessage } m := &InterfaceAnnounceMessage{ Version: int(b[2]), Type: int(b[3]), Index: int(nativeEndian.Uint16(b[4:6])), What: int(nativeEndian.Uint16(b[22:24])), raw: b[:l], } for i := 0; i < 16; i++ { if b[6+i] != 0 { continue } m.Name = string(b[6 : 6+i]) break } return m, nil } lxd-2.0.11/dist/src/golang.org/x/net/route/interface.go0000644061062106075000000000356513172163402023751 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route // An InterfaceMessage represents an interface message. type InterfaceMessage struct { Version int // message version Type int // message type Flags int // interface flags Index int // interface index Name string // interface name Addrs []Addr // addresses extOff int // offset of header extension raw []byte // raw message } // An InterfaceAddrMessage represents an interface address message. type InterfaceAddrMessage struct { Version int // message version Type int // message type Flags int // interface flags Index int // interface index Addrs []Addr // addresses raw []byte // raw message } // Sys implements the Sys method of Message interface. func (m *InterfaceAddrMessage) Sys() []Sys { return nil } // An InterfaceMulticastAddrMessage represents an interface multicast // address message. type InterfaceMulticastAddrMessage struct { Version int // message version Type int // messsage type Flags int // interface flags Index int // interface index Addrs []Addr // addresses raw []byte // raw message } // Sys implements the Sys method of Message interface. func (m *InterfaceMulticastAddrMessage) Sys() []Sys { return nil } // An InterfaceAnnounceMessage represents an interface announcement // message. type InterfaceAnnounceMessage struct { Version int // message version Type int // message type Index int // interface index Name string // interface name What int // what type of announcement raw []byte // raw message } // Sys implements the Sys method of Message interface. func (m *InterfaceAnnounceMessage) Sys() []Sys { return nil } lxd-2.0.11/dist/src/golang.org/x/net/route/defs_openbsd.go0000644061062106075000000000557313172163402024445 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package route /* #include #include #include #include #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_ROUTE = C.AF_ROUTE sysAF_LINK = C.AF_LINK sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW sysNET_RT_DUMP = C.NET_RT_DUMP sysNET_RT_FLAGS = C.NET_RT_FLAGS sysNET_RT_IFLIST = C.NET_RT_IFLIST sysNET_RT_STATS = C.NET_RT_STATS sysNET_RT_TABLE = C.NET_RT_TABLE sysNET_RT_IFNAMES = C.NET_RT_IFNAMES sysNET_RT_MAXID = C.NET_RT_MAXID ) const ( sysCTL_MAXNAME = C.CTL_MAXNAME sysCTL_UNSPEC = C.CTL_UNSPEC sysCTL_KERN = C.CTL_KERN sysCTL_VM = C.CTL_VM sysCTL_FS = C.CTL_FS sysCTL_NET = C.CTL_NET sysCTL_DEBUG = C.CTL_DEBUG sysCTL_HW = C.CTL_HW sysCTL_MACHDEP = C.CTL_MACHDEP sysCTL_DDB = C.CTL_DDB sysCTL_VFS = C.CTL_VFS sysCTL_MAXID = C.CTL_MAXID ) const ( sysRTM_VERSION = C.RTM_VERSION sysRTM_ADD = C.RTM_ADD sysRTM_DELETE = C.RTM_DELETE sysRTM_CHANGE = C.RTM_CHANGE sysRTM_GET = C.RTM_GET sysRTM_LOSING = C.RTM_LOSING sysRTM_REDIRECT = C.RTM_REDIRECT sysRTM_MISS = C.RTM_MISS sysRTM_LOCK = C.RTM_LOCK sysRTM_RESOLVE = C.RTM_RESOLVE sysRTM_NEWADDR = C.RTM_NEWADDR sysRTM_DELADDR = C.RTM_DELADDR sysRTM_IFINFO = C.RTM_IFINFO sysRTM_IFANNOUNCE = C.RTM_IFANNOUNCE sysRTM_DESYNC = C.RTM_DESYNC sysRTM_INVALIDATE = C.RTM_INVALIDATE sysRTM_BFD = C.RTM_BFD sysRTM_PROPOSAL = C.RTM_PROPOSAL sysRTA_DST = C.RTA_DST sysRTA_GATEWAY = C.RTA_GATEWAY sysRTA_NETMASK = C.RTA_NETMASK sysRTA_GENMASK = C.RTA_GENMASK sysRTA_IFP = C.RTA_IFP sysRTA_IFA = C.RTA_IFA sysRTA_AUTHOR = C.RTA_AUTHOR sysRTA_BRD = C.RTA_BRD sysRTA_SRC = C.RTA_SRC sysRTA_SRCMASK = C.RTA_SRCMASK sysRTA_LABEL = C.RTA_LABEL sysRTA_BFD = C.RTA_BFD sysRTA_DNS = C.RTA_DNS sysRTA_STATIC = C.RTA_STATIC sysRTA_SEARCH = C.RTA_SEARCH sysRTAX_DST = C.RTAX_DST sysRTAX_GATEWAY = C.RTAX_GATEWAY sysRTAX_NETMASK = C.RTAX_NETMASK sysRTAX_GENMASK = C.RTAX_GENMASK sysRTAX_IFP = C.RTAX_IFP sysRTAX_IFA = C.RTAX_IFA sysRTAX_AUTHOR = C.RTAX_AUTHOR sysRTAX_BRD = C.RTAX_BRD sysRTAX_SRC = C.RTAX_SRC sysRTAX_SRCMASK = C.RTAX_SRCMASK sysRTAX_LABEL = C.RTAX_LABEL sysRTAX_BFD = C.RTAX_BFD sysRTAX_DNS = C.RTAX_DNS sysRTAX_STATIC = C.RTAX_STATIC sysRTAX_SEARCH = C.RTAX_SEARCH sysRTAX_MAX = C.RTAX_MAX ) const ( sizeofRtMsghdr = C.sizeof_struct_rt_msghdr sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/route/defs_netbsd.go0000644061062106075000000000554213172163402024266 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package route /* #include #include #include #include #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_ROUTE = C.AF_ROUTE sysAF_LINK = C.AF_LINK sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW sysNET_RT_DUMP = C.NET_RT_DUMP sysNET_RT_FLAGS = C.NET_RT_FLAGS sysNET_RT_IFLIST = C.NET_RT_IFLIST sysNET_RT_MAXID = C.NET_RT_MAXID ) const ( sysCTL_MAXNAME = C.CTL_MAXNAME sysCTL_UNSPEC = C.CTL_UNSPEC sysCTL_KERN = C.CTL_KERN sysCTL_VM = C.CTL_VM sysCTL_VFS = C.CTL_VFS sysCTL_NET = C.CTL_NET sysCTL_DEBUG = C.CTL_DEBUG sysCTL_HW = C.CTL_HW sysCTL_MACHDEP = C.CTL_MACHDEP sysCTL_USER = C.CTL_USER sysCTL_DDB = C.CTL_DDB sysCTL_PROC = C.CTL_PROC sysCTL_VENDOR = C.CTL_VENDOR sysCTL_EMUL = C.CTL_EMUL sysCTL_SECURITY = C.CTL_SECURITY sysCTL_MAXID = C.CTL_MAXID ) const ( sysRTM_VERSION = C.RTM_VERSION sysRTM_ADD = C.RTM_ADD sysRTM_DELETE = C.RTM_DELETE sysRTM_CHANGE = C.RTM_CHANGE sysRTM_GET = C.RTM_GET sysRTM_LOSING = C.RTM_LOSING sysRTM_REDIRECT = C.RTM_REDIRECT sysRTM_MISS = C.RTM_MISS sysRTM_LOCK = C.RTM_LOCK sysRTM_OLDADD = C.RTM_OLDADD sysRTM_OLDDEL = C.RTM_OLDDEL sysRTM_RESOLVE = C.RTM_RESOLVE sysRTM_NEWADDR = C.RTM_NEWADDR sysRTM_DELADDR = C.RTM_DELADDR sysRTM_IFANNOUNCE = C.RTM_IFANNOUNCE sysRTM_IEEE80211 = C.RTM_IEEE80211 sysRTM_SETGATE = C.RTM_SETGATE sysRTM_LLINFO_UPD = C.RTM_LLINFO_UPD sysRTM_IFINFO = C.RTM_IFINFO sysRTM_CHGADDR = C.RTM_CHGADDR sysRTA_DST = C.RTA_DST sysRTA_GATEWAY = C.RTA_GATEWAY sysRTA_NETMASK = C.RTA_NETMASK sysRTA_GENMASK = C.RTA_GENMASK sysRTA_IFP = C.RTA_IFP sysRTA_IFA = C.RTA_IFA sysRTA_AUTHOR = C.RTA_AUTHOR sysRTA_BRD = C.RTA_BRD sysRTA_TAG = C.RTA_TAG sysRTAX_DST = C.RTAX_DST sysRTAX_GATEWAY = C.RTAX_GATEWAY sysRTAX_NETMASK = C.RTAX_NETMASK sysRTAX_GENMASK = C.RTAX_GENMASK sysRTAX_IFP = C.RTAX_IFP sysRTAX_IFA = C.RTAX_IFA sysRTAX_AUTHOR = C.RTAX_AUTHOR sysRTAX_BRD = C.RTAX_BRD sysRTAX_TAG = C.RTAX_TAG sysRTAX_MAX = C.RTAX_MAX ) const ( sizeofIfMsghdrNetBSD7 = C.sizeof_struct_if_msghdr sizeofIfaMsghdrNetBSD7 = C.sizeof_struct_ifa_msghdr sizeofIfAnnouncemsghdrNetBSD7 = C.sizeof_struct_if_announcemsghdr sizeofRtMsghdrNetBSD7 = C.sizeof_struct_rt_msghdr sizeofRtMetricsNetBSD7 = C.sizeof_struct_rt_metrics sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/route/defs_freebsd.go0000644061062106075000000002030313172163402024411 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package route /* #include #include #include #include #include #include struct if_data_freebsd7 { u_char ifi_type; u_char ifi_physical; u_char ifi_addrlen; u_char ifi_hdrlen; u_char ifi_link_state; u_char ifi_spare_char1; u_char ifi_spare_char2; u_char ifi_datalen; u_long ifi_mtu; u_long ifi_metric; u_long ifi_baudrate; u_long ifi_ipackets; u_long ifi_ierrors; u_long ifi_opackets; u_long ifi_oerrors; u_long ifi_collisions; u_long ifi_ibytes; u_long ifi_obytes; u_long ifi_imcasts; u_long ifi_omcasts; u_long ifi_iqdrops; u_long ifi_noproto; u_long ifi_hwassist; time_t __ifi_epoch; struct timeval __ifi_lastchange; }; struct if_data_freebsd8 { u_char ifi_type; u_char ifi_physical; u_char ifi_addrlen; u_char ifi_hdrlen; u_char ifi_link_state; u_char ifi_spare_char1; u_char ifi_spare_char2; u_char ifi_datalen; u_long ifi_mtu; u_long ifi_metric; u_long ifi_baudrate; u_long ifi_ipackets; u_long ifi_ierrors; u_long ifi_opackets; u_long ifi_oerrors; u_long ifi_collisions; u_long ifi_ibytes; u_long ifi_obytes; u_long ifi_imcasts; u_long ifi_omcasts; u_long ifi_iqdrops; u_long ifi_noproto; u_long ifi_hwassist; time_t __ifi_epoch; struct timeval __ifi_lastchange; }; struct if_data_freebsd9 { u_char ifi_type; u_char ifi_physical; u_char ifi_addrlen; u_char ifi_hdrlen; u_char ifi_link_state; u_char ifi_spare_char1; u_char ifi_spare_char2; u_char ifi_datalen; u_long ifi_mtu; u_long ifi_metric; u_long ifi_baudrate; u_long ifi_ipackets; u_long ifi_ierrors; u_long ifi_opackets; u_long ifi_oerrors; u_long ifi_collisions; u_long ifi_ibytes; u_long ifi_obytes; u_long ifi_imcasts; u_long ifi_omcasts; u_long ifi_iqdrops; u_long ifi_noproto; u_long ifi_hwassist; time_t __ifi_epoch; struct timeval __ifi_lastchange; }; struct if_data_freebsd10 { u_char ifi_type; u_char ifi_physical; u_char ifi_addrlen; u_char ifi_hdrlen; u_char ifi_link_state; u_char ifi_vhid; u_char ifi_baudrate_pf; u_char ifi_datalen; u_long ifi_mtu; u_long ifi_metric; u_long ifi_baudrate; u_long ifi_ipackets; u_long ifi_ierrors; u_long ifi_opackets; u_long ifi_oerrors; u_long ifi_collisions; u_long ifi_ibytes; u_long ifi_obytes; u_long ifi_imcasts; u_long ifi_omcasts; u_long ifi_iqdrops; u_long ifi_noproto; uint64_t ifi_hwassist; time_t __ifi_epoch; struct timeval __ifi_lastchange; }; struct if_data_freebsd11 { uint8_t ifi_type; uint8_t ifi_physical; uint8_t ifi_addrlen; uint8_t ifi_hdrlen; uint8_t ifi_link_state; uint8_t ifi_vhid; uint16_t ifi_datalen; uint32_t ifi_mtu; uint32_t ifi_metric; uint64_t ifi_baudrate; uint64_t ifi_ipackets; uint64_t ifi_ierrors; uint64_t ifi_opackets; uint64_t ifi_oerrors; uint64_t ifi_collisions; uint64_t ifi_ibytes; uint64_t ifi_obytes; uint64_t ifi_imcasts; uint64_t ifi_omcasts; uint64_t ifi_iqdrops; uint64_t ifi_oqdrops; uint64_t ifi_noproto; uint64_t ifi_hwassist; union { time_t tt; uint64_t ph; } __ifi_epoch; union { struct timeval tv; struct { uint64_t ph1; uint64_t ph2; } ph; } __ifi_lastchange; }; struct if_msghdr_freebsd7 { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; int ifm_addrs; int ifm_flags; u_short ifm_index; struct if_data_freebsd7 ifm_data; }; struct if_msghdr_freebsd8 { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; int ifm_addrs; int ifm_flags; u_short ifm_index; struct if_data_freebsd8 ifm_data; }; struct if_msghdr_freebsd9 { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; int ifm_addrs; int ifm_flags; u_short ifm_index; struct if_data_freebsd9 ifm_data; }; struct if_msghdr_freebsd10 { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; int ifm_addrs; int ifm_flags; u_short ifm_index; struct if_data_freebsd10 ifm_data; }; struct if_msghdr_freebsd11 { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; int ifm_addrs; int ifm_flags; u_short ifm_index; struct if_data_freebsd11 ifm_data; }; */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_ROUTE = C.AF_ROUTE sysAF_LINK = C.AF_LINK sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW sysNET_RT_DUMP = C.NET_RT_DUMP sysNET_RT_FLAGS = C.NET_RT_FLAGS sysNET_RT_IFLIST = C.NET_RT_IFLIST sysNET_RT_IFMALIST = C.NET_RT_IFMALIST sysNET_RT_IFLISTL = C.NET_RT_IFLISTL ) const ( sysCTL_MAXNAME = C.CTL_MAXNAME sysCTL_UNSPEC = C.CTL_UNSPEC sysCTL_KERN = C.CTL_KERN sysCTL_VM = C.CTL_VM sysCTL_VFS = C.CTL_VFS sysCTL_NET = C.CTL_NET sysCTL_DEBUG = C.CTL_DEBUG sysCTL_HW = C.CTL_HW sysCTL_MACHDEP = C.CTL_MACHDEP sysCTL_USER = C.CTL_USER sysCTL_P1003_1B = C.CTL_P1003_1B ) const ( sysRTM_VERSION = C.RTM_VERSION sysRTM_ADD = C.RTM_ADD sysRTM_DELETE = C.RTM_DELETE sysRTM_CHANGE = C.RTM_CHANGE sysRTM_GET = C.RTM_GET sysRTM_LOSING = C.RTM_LOSING sysRTM_REDIRECT = C.RTM_REDIRECT sysRTM_MISS = C.RTM_MISS sysRTM_LOCK = C.RTM_LOCK sysRTM_RESOLVE = C.RTM_RESOLVE sysRTM_NEWADDR = C.RTM_NEWADDR sysRTM_DELADDR = C.RTM_DELADDR sysRTM_IFINFO = C.RTM_IFINFO sysRTM_NEWMADDR = C.RTM_NEWMADDR sysRTM_DELMADDR = C.RTM_DELMADDR sysRTM_IFANNOUNCE = C.RTM_IFANNOUNCE sysRTM_IEEE80211 = C.RTM_IEEE80211 sysRTA_DST = C.RTA_DST sysRTA_GATEWAY = C.RTA_GATEWAY sysRTA_NETMASK = C.RTA_NETMASK sysRTA_GENMASK = C.RTA_GENMASK sysRTA_IFP = C.RTA_IFP sysRTA_IFA = C.RTA_IFA sysRTA_AUTHOR = C.RTA_AUTHOR sysRTA_BRD = C.RTA_BRD sysRTAX_DST = C.RTAX_DST sysRTAX_GATEWAY = C.RTAX_GATEWAY sysRTAX_NETMASK = C.RTAX_NETMASK sysRTAX_GENMASK = C.RTAX_GENMASK sysRTAX_IFP = C.RTAX_IFP sysRTAX_IFA = C.RTAX_IFA sysRTAX_AUTHOR = C.RTAX_AUTHOR sysRTAX_BRD = C.RTAX_BRD sysRTAX_MAX = C.RTAX_MAX ) const ( sizeofIfMsghdrlFreeBSD10 = C.sizeof_struct_if_msghdrl sizeofIfaMsghdrFreeBSD10 = C.sizeof_struct_ifa_msghdr sizeofIfaMsghdrlFreeBSD10 = C.sizeof_struct_ifa_msghdrl sizeofIfmaMsghdrFreeBSD10 = C.sizeof_struct_ifma_msghdr sizeofIfAnnouncemsghdrFreeBSD10 = C.sizeof_struct_if_announcemsghdr sizeofRtMsghdrFreeBSD10 = C.sizeof_struct_rt_msghdr sizeofRtMetricsFreeBSD10 = C.sizeof_struct_rt_metrics sizeofIfMsghdrFreeBSD7 = C.sizeof_struct_if_msghdr_freebsd7 sizeofIfMsghdrFreeBSD8 = C.sizeof_struct_if_msghdr_freebsd8 sizeofIfMsghdrFreeBSD9 = C.sizeof_struct_if_msghdr_freebsd9 sizeofIfMsghdrFreeBSD10 = C.sizeof_struct_if_msghdr_freebsd10 sizeofIfMsghdrFreeBSD11 = C.sizeof_struct_if_msghdr_freebsd11 sizeofIfDataFreeBSD7 = C.sizeof_struct_if_data_freebsd7 sizeofIfDataFreeBSD8 = C.sizeof_struct_if_data_freebsd8 sizeofIfDataFreeBSD9 = C.sizeof_struct_if_data_freebsd9 sizeofIfDataFreeBSD10 = C.sizeof_struct_if_data_freebsd10 sizeofIfDataFreeBSD11 = C.sizeof_struct_if_data_freebsd11 sizeofIfMsghdrlFreeBSD10Emu = C.sizeof_struct_if_msghdrl sizeofIfaMsghdrFreeBSD10Emu = C.sizeof_struct_ifa_msghdr sizeofIfaMsghdrlFreeBSD10Emu = C.sizeof_struct_ifa_msghdrl sizeofIfmaMsghdrFreeBSD10Emu = C.sizeof_struct_ifma_msghdr sizeofIfAnnouncemsghdrFreeBSD10Emu = C.sizeof_struct_if_announcemsghdr sizeofRtMsghdrFreeBSD10Emu = C.sizeof_struct_rt_msghdr sizeofRtMetricsFreeBSD10Emu = C.sizeof_struct_rt_metrics sizeofIfMsghdrFreeBSD7Emu = C.sizeof_struct_if_msghdr_freebsd7 sizeofIfMsghdrFreeBSD8Emu = C.sizeof_struct_if_msghdr_freebsd8 sizeofIfMsghdrFreeBSD9Emu = C.sizeof_struct_if_msghdr_freebsd9 sizeofIfMsghdrFreeBSD10Emu = C.sizeof_struct_if_msghdr_freebsd10 sizeofIfMsghdrFreeBSD11Emu = C.sizeof_struct_if_msghdr_freebsd11 sizeofIfDataFreeBSD7Emu = C.sizeof_struct_if_data_freebsd7 sizeofIfDataFreeBSD8Emu = C.sizeof_struct_if_data_freebsd8 sizeofIfDataFreeBSD9Emu = C.sizeof_struct_if_data_freebsd9 sizeofIfDataFreeBSD10Emu = C.sizeof_struct_if_data_freebsd10 sizeofIfDataFreeBSD11Emu = C.sizeof_struct_if_data_freebsd11 sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/route/defs_dragonfly.go0000644061062106075000000000570413172163402024774 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package route /* #include #include #include #include #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_ROUTE = C.AF_ROUTE sysAF_LINK = C.AF_LINK sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW sysNET_RT_DUMP = C.NET_RT_DUMP sysNET_RT_FLAGS = C.NET_RT_FLAGS sysNET_RT_IFLIST = C.NET_RT_IFLIST sysNET_RT_MAXID = C.NET_RT_MAXID ) const ( sysCTL_MAXNAME = C.CTL_MAXNAME sysCTL_UNSPEC = C.CTL_UNSPEC sysCTL_KERN = C.CTL_KERN sysCTL_VM = C.CTL_VM sysCTL_VFS = C.CTL_VFS sysCTL_NET = C.CTL_NET sysCTL_DEBUG = C.CTL_DEBUG sysCTL_HW = C.CTL_HW sysCTL_MACHDEP = C.CTL_MACHDEP sysCTL_USER = C.CTL_USER sysCTL_P1003_1B = C.CTL_P1003_1B sysCTL_LWKT = C.CTL_LWKT sysCTL_MAXID = C.CTL_MAXID ) const ( sysRTM_VERSION = C.RTM_VERSION sysRTM_ADD = C.RTM_ADD sysRTM_DELETE = C.RTM_DELETE sysRTM_CHANGE = C.RTM_CHANGE sysRTM_GET = C.RTM_GET sysRTM_LOSING = C.RTM_LOSING sysRTM_REDIRECT = C.RTM_REDIRECT sysRTM_MISS = C.RTM_MISS sysRTM_LOCK = C.RTM_LOCK sysRTM_OLDADD = C.RTM_OLDADD sysRTM_OLDDEL = C.RTM_OLDDEL sysRTM_RESOLVE = C.RTM_RESOLVE sysRTM_NEWADDR = C.RTM_NEWADDR sysRTM_DELADDR = C.RTM_DELADDR sysRTM_IFINFO = C.RTM_IFINFO sysRTM_NEWMADDR = C.RTM_NEWMADDR sysRTM_DELMADDR = C.RTM_DELMADDR sysRTM_IFANNOUNCE = C.RTM_IFANNOUNCE sysRTM_IEEE80211 = C.RTM_IEEE80211 sysRTA_DST = C.RTA_DST sysRTA_GATEWAY = C.RTA_GATEWAY sysRTA_NETMASK = C.RTA_NETMASK sysRTA_GENMASK = C.RTA_GENMASK sysRTA_IFP = C.RTA_IFP sysRTA_IFA = C.RTA_IFA sysRTA_AUTHOR = C.RTA_AUTHOR sysRTA_BRD = C.RTA_BRD sysRTA_MPLS1 = C.RTA_MPLS1 sysRTA_MPLS2 = C.RTA_MPLS2 sysRTA_MPLS3 = C.RTA_MPLS3 sysRTAX_DST = C.RTAX_DST sysRTAX_GATEWAY = C.RTAX_GATEWAY sysRTAX_NETMASK = C.RTAX_NETMASK sysRTAX_GENMASK = C.RTAX_GENMASK sysRTAX_IFP = C.RTAX_IFP sysRTAX_IFA = C.RTAX_IFA sysRTAX_AUTHOR = C.RTAX_AUTHOR sysRTAX_BRD = C.RTAX_BRD sysRTAX_MPLS1 = C.RTAX_MPLS1 sysRTAX_MPLS2 = C.RTAX_MPLS2 sysRTAX_MPLS3 = C.RTAX_MPLS3 sysRTAX_MAX = C.RTAX_MAX ) const ( sizeofIfMsghdrDragonFlyBSD4 = C.sizeof_struct_if_msghdr sizeofIfaMsghdrDragonFlyBSD4 = C.sizeof_struct_ifa_msghdr sizeofIfmaMsghdrDragonFlyBSD4 = C.sizeof_struct_ifma_msghdr sizeofIfAnnouncemsghdrDragonFlyBSD4 = C.sizeof_struct_if_announcemsghdr sizeofRtMsghdrDragonFlyBSD4 = C.sizeof_struct_rt_msghdr sizeofRtMetricsDragonFlyBSD4 = C.sizeof_struct_rt_metrics sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/route/defs_darwin.go0000644061062106075000000000600213172163402024263 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package route /* #include #include #include #include #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_ROUTE = C.AF_ROUTE sysAF_LINK = C.AF_LINK sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW sysNET_RT_DUMP = C.NET_RT_DUMP sysNET_RT_FLAGS = C.NET_RT_FLAGS sysNET_RT_IFLIST = C.NET_RT_IFLIST sysNET_RT_STAT = C.NET_RT_STAT sysNET_RT_TRASH = C.NET_RT_TRASH sysNET_RT_IFLIST2 = C.NET_RT_IFLIST2 sysNET_RT_DUMP2 = C.NET_RT_DUMP2 sysNET_RT_MAXID = C.NET_RT_MAXID ) const ( sysCTL_MAXNAME = C.CTL_MAXNAME sysCTL_UNSPEC = C.CTL_UNSPEC sysCTL_KERN = C.CTL_KERN sysCTL_VM = C.CTL_VM sysCTL_VFS = C.CTL_VFS sysCTL_NET = C.CTL_NET sysCTL_DEBUG = C.CTL_DEBUG sysCTL_HW = C.CTL_HW sysCTL_MACHDEP = C.CTL_MACHDEP sysCTL_USER = C.CTL_USER sysCTL_MAXID = C.CTL_MAXID ) const ( sysRTM_VERSION = C.RTM_VERSION sysRTM_ADD = C.RTM_ADD sysRTM_DELETE = C.RTM_DELETE sysRTM_CHANGE = C.RTM_CHANGE sysRTM_GET = C.RTM_GET sysRTM_LOSING = C.RTM_LOSING sysRTM_REDIRECT = C.RTM_REDIRECT sysRTM_MISS = C.RTM_MISS sysRTM_LOCK = C.RTM_LOCK sysRTM_OLDADD = C.RTM_OLDADD sysRTM_OLDDEL = C.RTM_OLDDEL sysRTM_RESOLVE = C.RTM_RESOLVE sysRTM_NEWADDR = C.RTM_NEWADDR sysRTM_DELADDR = C.RTM_DELADDR sysRTM_IFINFO = C.RTM_IFINFO sysRTM_NEWMADDR = C.RTM_NEWMADDR sysRTM_DELMADDR = C.RTM_DELMADDR sysRTM_IFINFO2 = C.RTM_IFINFO2 sysRTM_NEWMADDR2 = C.RTM_NEWMADDR2 sysRTM_GET2 = C.RTM_GET2 sysRTA_DST = C.RTA_DST sysRTA_GATEWAY = C.RTA_GATEWAY sysRTA_NETMASK = C.RTA_NETMASK sysRTA_GENMASK = C.RTA_GENMASK sysRTA_IFP = C.RTA_IFP sysRTA_IFA = C.RTA_IFA sysRTA_AUTHOR = C.RTA_AUTHOR sysRTA_BRD = C.RTA_BRD sysRTAX_DST = C.RTAX_DST sysRTAX_GATEWAY = C.RTAX_GATEWAY sysRTAX_NETMASK = C.RTAX_NETMASK sysRTAX_GENMASK = C.RTAX_GENMASK sysRTAX_IFP = C.RTAX_IFP sysRTAX_IFA = C.RTAX_IFA sysRTAX_AUTHOR = C.RTAX_AUTHOR sysRTAX_BRD = C.RTAX_BRD sysRTAX_MAX = C.RTAX_MAX ) const ( sizeofIfMsghdrDarwin15 = C.sizeof_struct_if_msghdr sizeofIfaMsghdrDarwin15 = C.sizeof_struct_ifa_msghdr sizeofIfmaMsghdrDarwin15 = C.sizeof_struct_ifma_msghdr sizeofIfMsghdr2Darwin15 = C.sizeof_struct_if_msghdr2 sizeofIfmaMsghdr2Darwin15 = C.sizeof_struct_ifma_msghdr2 sizeofIfDataDarwin15 = C.sizeof_struct_if_data sizeofIfData64Darwin15 = C.sizeof_struct_if_data64 sizeofRtMsghdrDarwin15 = C.sizeof_struct_rt_msghdr sizeofRtMsghdr2Darwin15 = C.sizeof_struct_rt_msghdr2 sizeofRtMetricsDarwin15 = C.sizeof_struct_rt_metrics sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/route/binary.go0000644061062106075000000000534113172163402023267 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route // This file contains duplicates of encoding/binary package. // // This package is supposed to be used by the net package of standard // library. Therefore the package set used in the package must be the // same as net package. var ( littleEndian binaryLittleEndian bigEndian binaryBigEndian ) type binaryByteOrder interface { Uint16([]byte) uint16 Uint32([]byte) uint32 PutUint16([]byte, uint16) PutUint32([]byte, uint32) Uint64([]byte) uint64 } type binaryLittleEndian struct{} func (binaryLittleEndian) Uint16(b []byte) uint16 { _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 return uint16(b[0]) | uint16(b[1])<<8 } func (binaryLittleEndian) PutUint16(b []byte, v uint16) { _ = b[1] // early bounds check to guarantee safety of writes below b[0] = byte(v) b[1] = byte(v >> 8) } func (binaryLittleEndian) Uint32(b []byte) uint32 { _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 } func (binaryLittleEndian) PutUint32(b []byte, v uint32) { _ = b[3] // early bounds check to guarantee safety of writes below b[0] = byte(v) b[1] = byte(v >> 8) b[2] = byte(v >> 16) b[3] = byte(v >> 24) } func (binaryLittleEndian) Uint64(b []byte) uint64 { _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 } type binaryBigEndian struct{} func (binaryBigEndian) Uint16(b []byte) uint16 { _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 return uint16(b[1]) | uint16(b[0])<<8 } func (binaryBigEndian) PutUint16(b []byte, v uint16) { _ = b[1] // early bounds check to guarantee safety of writes below b[0] = byte(v >> 8) b[1] = byte(v) } func (binaryBigEndian) Uint32(b []byte) uint32 { _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 } func (binaryBigEndian) PutUint32(b []byte, v uint32) { _ = b[3] // early bounds check to guarantee safety of writes below b[0] = byte(v >> 24) b[1] = byte(v >> 16) b[2] = byte(v >> 8) b[3] = byte(v) } func (binaryBigEndian) Uint64(b []byte) uint64 { _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 } lxd-2.0.11/dist/src/golang.org/x/net/route/address_test.go0000644061062106075000000000506013172163402024465 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route import ( "reflect" "testing" ) type parseAddrsTest struct { attrs uint fn func(int, []byte) (int, Addr, error) b []byte as []Addr } var parseAddrsLittleEndianTests = []parseAddrsTest{ { sysRTA_DST | sysRTA_GATEWAY | sysRTA_NETMASK | sysRTA_BRD, parseKernelInetAddr, []byte{ 0x38, 0x12, 0x0, 0x0, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x38, 0x12, 0x2, 0x0, 0x6, 0x3, 0x6, 0x0, 0x65, 0x6d, 0x31, 0x0, 0xc, 0x29, 0x66, 0x2c, 0xdc, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, 0x2, 0x0, 0x0, 0xac, 0x10, 0xdc, 0xb4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, 0x2, 0x0, 0x0, 0xac, 0x10, 0xdc, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, }, []Addr{ &LinkAddr{Index: 0}, &LinkAddr{Index: 2, Name: "em1", Addr: []byte{0x00, 0x0c, 0x29, 0x66, 0x2c, 0xdc}}, &Inet4Addr{IP: [4]byte{172, 16, 220, 180}}, nil, nil, nil, nil, &Inet4Addr{IP: [4]byte{172, 16, 220, 255}}, }, }, { sysRTA_NETMASK | sysRTA_IFP | sysRTA_IFA, parseKernelInetAddr, []byte{ 0x7, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0x0, 0x18, 0x12, 0xa, 0x0, 0x87, 0x8, 0x0, 0x0, 0x76, 0x6c, 0x61, 0x6e, 0x35, 0x36, 0x38, 0x32, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, 0x2, 0x0, 0x0, 0xa9, 0xfe, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, }, []Addr{ nil, nil, &Inet4Addr{IP: [4]byte{255, 255, 255, 0}}, nil, &LinkAddr{Index: 10, Name: "vlan5682"}, &Inet4Addr{IP: [4]byte{169, 254, 0, 1}}, nil, nil, }, }, } func TestParseAddrs(t *testing.T) { tests := parseAddrsLittleEndianTests if nativeEndian != littleEndian { t.Skip("no test for non-little endian machine yet") } for i, tt := range tests { as, err := parseAddrs(tt.attrs, tt.fn, tt.b) if err != nil { t.Error(i, err) continue } as = as[:8] // the list varies between operating systems if !reflect.DeepEqual(as, tt.as) { t.Errorf("#%d: got %+v; want %+v", i, as, tt.as) continue } } } lxd-2.0.11/dist/src/golang.org/x/net/route/address_darwin_test.go0000644061062106075000000000247113172163402026034 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package route import ( "reflect" "testing" ) type parseAddrsOnDarwinTest struct { attrs uint fn func(int, []byte) (int, Addr, error) b []byte as []Addr } var parseAddrsOnDarwinLittleEndianTests = []parseAddrsOnDarwinTest{ { sysRTA_DST | sysRTA_GATEWAY | sysRTA_NETMASK, parseKernelInetAddr, []byte{ 0x10, 0x2, 0x0, 0x0, 0xc0, 0xa8, 0x56, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x12, 0x4, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }, []Addr{ &Inet4Addr{IP: [4]byte{192, 168, 86, 0}}, &LinkAddr{Index: 4}, &Inet4Addr{IP: [4]byte{255, 255, 255, 255}}, nil, nil, nil, nil, nil, }, }, } func TestParseAddrsOnDarwin(t *testing.T) { tests := parseAddrsOnDarwinLittleEndianTests if nativeEndian != littleEndian { t.Skip("no test for non-little endian machine yet") } for i, tt := range tests { as, err := parseAddrs(tt.attrs, tt.fn, tt.b) if err != nil { t.Error(i, err) continue } if !reflect.DeepEqual(as, tt.as) { t.Errorf("#%d: got %+v; want %+v", i, as, tt.as) continue } } } lxd-2.0.11/dist/src/golang.org/x/net/route/address.go0000644061062106075000000002305113172163402023426 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package route import "runtime" // An Addr represents an address associated with packet routing. type Addr interface { // Family returns an address family. Family() int } // A LinkAddr represents a link-layer address. type LinkAddr struct { Index int // interface index when attached Name string // interface name when attached Addr []byte // link-layer address when attached } // Family implements the Family method of Addr interface. func (a *LinkAddr) Family() int { return sysAF_LINK } func (a *LinkAddr) lenAndSpace() (int, int) { l := 8 + len(a.Name) + len(a.Addr) return l, roundup(l) } func (a *LinkAddr) marshal(b []byte) (int, error) { l, ll := a.lenAndSpace() if len(b) < ll { return 0, errShortBuffer } nlen, alen := len(a.Name), len(a.Addr) if nlen > 255 || alen > 255 { return 0, errInvalidAddr } b[0] = byte(l) b[1] = sysAF_LINK if a.Index > 0 { nativeEndian.PutUint16(b[2:4], uint16(a.Index)) } data := b[8:] if nlen > 0 { b[5] = byte(nlen) copy(data[:nlen], a.Addr) data = data[nlen:] } if alen > 0 { b[6] = byte(alen) copy(data[:alen], a.Name) data = data[alen:] } return ll, nil } func parseLinkAddr(b []byte) (Addr, error) { if len(b) < 8 { return nil, errInvalidAddr } _, a, err := parseKernelLinkAddr(sysAF_LINK, b[4:]) if err != nil { return nil, err } a.(*LinkAddr).Index = int(nativeEndian.Uint16(b[2:4])) return a, nil } // parseKernelLinkAddr parses b as a link-layer address in // conventional BSD kernel form. func parseKernelLinkAddr(_ int, b []byte) (int, Addr, error) { // The encoding looks like the following: // +----------------------------+ // | Type (1 octet) | // +----------------------------+ // | Name length (1 octet) | // +----------------------------+ // | Address length (1 octet) | // +----------------------------+ // | Selector length (1 octet) | // +----------------------------+ // | Data (variable) | // +----------------------------+ // // On some platforms, all-bit-one of length field means "don't // care". nlen, alen, slen := int(b[1]), int(b[2]), int(b[3]) if nlen == 0xff { nlen = 0 } if alen == 0xff { alen = 0 } if slen == 0xff { slen = 0 } l := 4 + nlen + alen + slen if len(b) < l { return 0, nil, errInvalidAddr } data := b[4:] var name string var addr []byte if nlen > 0 { name = string(data[:nlen]) data = data[nlen:] } if alen > 0 { addr = data[:alen] data = data[alen:] } return l, &LinkAddr{Name: name, Addr: addr}, nil } // An Inet4Addr represents an internet address for IPv4. type Inet4Addr struct { IP [4]byte // IP address } // Family implements the Family method of Addr interface. func (a *Inet4Addr) Family() int { return sysAF_INET } func (a *Inet4Addr) lenAndSpace() (int, int) { return sizeofSockaddrInet, roundup(sizeofSockaddrInet) } func (a *Inet4Addr) marshal(b []byte) (int, error) { l, ll := a.lenAndSpace() if len(b) < ll { return 0, errShortBuffer } b[0] = byte(l) b[1] = sysAF_INET copy(b[4:8], a.IP[:]) return ll, nil } // An Inet6Addr represents an internet address for IPv6. type Inet6Addr struct { IP [16]byte // IP address ZoneID int // zone identifier } // Family implements the Family method of Addr interface. func (a *Inet6Addr) Family() int { return sysAF_INET6 } func (a *Inet6Addr) lenAndSpace() (int, int) { return sizeofSockaddrInet6, roundup(sizeofSockaddrInet6) } func (a *Inet6Addr) marshal(b []byte) (int, error) { l, ll := a.lenAndSpace() if len(b) < ll { return 0, errShortBuffer } b[0] = byte(l) b[1] = sysAF_INET6 copy(b[8:24], a.IP[:]) if a.ZoneID > 0 { nativeEndian.PutUint32(b[24:28], uint32(a.ZoneID)) } return ll, nil } // parseInetAddr parses b as an internet address for IPv4 or IPv6. func parseInetAddr(af int, b []byte) (Addr, error) { switch af { case sysAF_INET: if len(b) < sizeofSockaddrInet { return nil, errInvalidAddr } a := &Inet4Addr{} copy(a.IP[:], b[4:8]) return a, nil case sysAF_INET6: if len(b) < sizeofSockaddrInet6 { return nil, errInvalidAddr } a := &Inet6Addr{ZoneID: int(nativeEndian.Uint32(b[24:28]))} copy(a.IP[:], b[8:24]) if a.IP[0] == 0xfe && a.IP[1]&0xc0 == 0x80 || a.IP[0] == 0xff && (a.IP[1]&0x0f == 0x01 || a.IP[1]&0x0f == 0x02) { // KAME based IPv6 protocol stack usually // embeds the interface index in the // interface-local or link-local address as // the kernel-internal form. id := int(bigEndian.Uint16(a.IP[2:4])) if id != 0 { a.ZoneID = id a.IP[2], a.IP[3] = 0, 0 } } return a, nil default: return nil, errInvalidAddr } } // parseKernelInetAddr parses b as an internet address in conventional // BSD kernel form. func parseKernelInetAddr(af int, b []byte) (int, Addr, error) { // The encoding looks similar to the NLRI encoding. // +----------------------------+ // | Length (1 octet) | // +----------------------------+ // | Address prefix (variable) | // +----------------------------+ // // The differences between the kernel form and the NLRI // encoding are: // // - The length field of the kernel form indicates the prefix // length in bytes, not in bits // // - In the kernel form, zero value of the length field // doesn't mean 0.0.0.0/0 or ::/0 // // - The kernel form appends leading bytes to the prefix field // to make the tuple to be conformed with // the routing message boundary l := int(b[0]) if runtime.GOOS == "darwin" { // On Darwn, an address in the kernel form is also // used as a message filler. if l == 0 || len(b) > roundup(l) { l = roundup(l) } } else { l = roundup(l) } if len(b) < l { return 0, nil, errInvalidAddr } // Don't reorder case expressions. // The case expressions for IPv6 must come first. const ( off4 = 4 // offset of in_addr off6 = 8 // offset of in6_addr ) switch { case b[0] == sizeofSockaddrInet6: a := &Inet6Addr{} copy(a.IP[:], b[off6:off6+16]) return int(b[0]), a, nil case af == sysAF_INET6: a := &Inet6Addr{} if l-1 < off6 { copy(a.IP[:], b[1:l]) } else { copy(a.IP[:], b[l-off6:l]) } return int(b[0]), a, nil case b[0] == sizeofSockaddrInet: a := &Inet4Addr{} copy(a.IP[:], b[off4:off4+4]) return int(b[0]), a, nil default: // an old fashion, AF_UNSPEC or unknown means AF_INET a := &Inet4Addr{} if l-1 < off4 { copy(a.IP[:], b[1:l]) } else { copy(a.IP[:], b[l-off4:l]) } return int(b[0]), a, nil } } // A DefaultAddr represents an address of various operating // system-specific features. type DefaultAddr struct { af int Raw []byte // raw format of address } // Family implements the Family method of Addr interface. func (a *DefaultAddr) Family() int { return a.af } func (a *DefaultAddr) lenAndSpace() (int, int) { l := len(a.Raw) return l, roundup(l) } func (a *DefaultAddr) marshal(b []byte) (int, error) { l, ll := a.lenAndSpace() if len(b) < ll { return 0, errShortBuffer } if l > 255 { return 0, errInvalidAddr } b[1] = byte(l) copy(b[:l], a.Raw) return ll, nil } func parseDefaultAddr(b []byte) (Addr, error) { if len(b) < 2 || len(b) < int(b[0]) { return nil, errInvalidAddr } a := &DefaultAddr{af: int(b[1]), Raw: b[:b[0]]} return a, nil } func addrsSpace(as []Addr) int { var l int for _, a := range as { switch a := a.(type) { case *LinkAddr: _, ll := a.lenAndSpace() l += ll case *Inet4Addr: _, ll := a.lenAndSpace() l += ll case *Inet6Addr: _, ll := a.lenAndSpace() l += ll case *DefaultAddr: _, ll := a.lenAndSpace() l += ll } } return l } // marshalAddrs marshals as and returns a bitmap indicating which // address is stored in b. func marshalAddrs(b []byte, as []Addr) (uint, error) { var attrs uint for i, a := range as { switch a := a.(type) { case *LinkAddr: l, err := a.marshal(b) if err != nil { return 0, err } b = b[l:] attrs |= 1 << uint(i) case *Inet4Addr: l, err := a.marshal(b) if err != nil { return 0, err } b = b[l:] attrs |= 1 << uint(i) case *Inet6Addr: l, err := a.marshal(b) if err != nil { return 0, err } b = b[l:] attrs |= 1 << uint(i) case *DefaultAddr: l, err := a.marshal(b) if err != nil { return 0, err } b = b[l:] attrs |= 1 << uint(i) } } return attrs, nil } func parseAddrs(attrs uint, fn func(int, []byte) (int, Addr, error), b []byte) ([]Addr, error) { var as [sysRTAX_MAX]Addr af := int(sysAF_UNSPEC) for i := uint(0); i < sysRTAX_MAX && len(b) >= roundup(0); i++ { if attrs&(1< len(b[j]) } // eTLDPlusOneTestCases come from // https://github.com/publicsuffix/list/blob/master/tests/test_psl.txt var eTLDPlusOneTestCases = []struct { domain, want string }{ // Empty input. {"", ""}, // Unlisted TLD. {"example", ""}, {"example.example", "example.example"}, {"b.example.example", "example.example"}, {"a.b.example.example", "example.example"}, // TLD with only 1 rule. {"biz", ""}, {"domain.biz", "domain.biz"}, {"b.domain.biz", "domain.biz"}, {"a.b.domain.biz", "domain.biz"}, // TLD with some 2-level rules. {"com", ""}, {"example.com", "example.com"}, {"b.example.com", "example.com"}, {"a.b.example.com", "example.com"}, {"uk.com", ""}, {"example.uk.com", "example.uk.com"}, {"b.example.uk.com", "example.uk.com"}, {"a.b.example.uk.com", "example.uk.com"}, {"test.ac", "test.ac"}, // TLD with only 1 (wildcard) rule. {"mm", ""}, {"c.mm", ""}, {"b.c.mm", "b.c.mm"}, {"a.b.c.mm", "b.c.mm"}, // More complex TLD. {"jp", ""}, {"test.jp", "test.jp"}, {"www.test.jp", "test.jp"}, {"ac.jp", ""}, {"test.ac.jp", "test.ac.jp"}, {"www.test.ac.jp", "test.ac.jp"}, {"kyoto.jp", ""}, {"test.kyoto.jp", "test.kyoto.jp"}, {"ide.kyoto.jp", ""}, {"b.ide.kyoto.jp", "b.ide.kyoto.jp"}, {"a.b.ide.kyoto.jp", "b.ide.kyoto.jp"}, {"c.kobe.jp", ""}, {"b.c.kobe.jp", "b.c.kobe.jp"}, {"a.b.c.kobe.jp", "b.c.kobe.jp"}, {"city.kobe.jp", "city.kobe.jp"}, {"www.city.kobe.jp", "city.kobe.jp"}, // TLD with a wildcard rule and exceptions. {"ck", ""}, {"test.ck", ""}, {"b.test.ck", "b.test.ck"}, {"a.b.test.ck", "b.test.ck"}, {"www.ck", "www.ck"}, {"www.www.ck", "www.ck"}, // US K12. {"us", ""}, {"test.us", "test.us"}, {"www.test.us", "test.us"}, {"ak.us", ""}, {"test.ak.us", "test.ak.us"}, {"www.test.ak.us", "test.ak.us"}, {"k12.ak.us", ""}, {"test.k12.ak.us", "test.k12.ak.us"}, {"www.test.k12.ak.us", "test.k12.ak.us"}, // Punycoded IDN labels {"xn--85x722f.com.cn", "xn--85x722f.com.cn"}, {"xn--85x722f.xn--55qx5d.cn", "xn--85x722f.xn--55qx5d.cn"}, {"www.xn--85x722f.xn--55qx5d.cn", "xn--85x722f.xn--55qx5d.cn"}, {"shishi.xn--55qx5d.cn", "shishi.xn--55qx5d.cn"}, {"xn--55qx5d.cn", ""}, {"xn--85x722f.xn--fiqs8s", "xn--85x722f.xn--fiqs8s"}, {"www.xn--85x722f.xn--fiqs8s", "xn--85x722f.xn--fiqs8s"}, {"shishi.xn--fiqs8s", "shishi.xn--fiqs8s"}, {"xn--fiqs8s", ""}, } func TestEffectiveTLDPlusOne(t *testing.T) { for _, tc := range eTLDPlusOneTestCases { got, _ := EffectiveTLDPlusOne(tc.domain) if got != tc.want { t.Errorf("%q: got %q, want %q", tc.domain, got, tc.want) } } } lxd-2.0.11/dist/src/golang.org/x/net/publicsuffix/list.go0000644061062106075000000000747213172163402024332 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:generate go run gen.go // Package publicsuffix provides a public suffix list based on data from // http://publicsuffix.org/. A public suffix is one under which Internet users // can directly register names. package publicsuffix // import "golang.org/x/net/publicsuffix" // TODO: specify case sensitivity and leading/trailing dot behavior for // func PublicSuffix and func EffectiveTLDPlusOne. import ( "fmt" "net/http/cookiejar" "strings" ) // List implements the cookiejar.PublicSuffixList interface by calling the // PublicSuffix function. var List cookiejar.PublicSuffixList = list{} type list struct{} func (list) PublicSuffix(domain string) string { ps, _ := PublicSuffix(domain) return ps } func (list) String() string { return version } // PublicSuffix returns the public suffix of the domain using a copy of the // publicsuffix.org database compiled into the library. // // icann is whether the public suffix is managed by the Internet Corporation // for Assigned Names and Numbers. If not, the public suffix is privately // managed. For example, foo.org and foo.co.uk are ICANN domains, // foo.dyndns.org and foo.blogspot.co.uk are private domains. // // Use cases for distinguishing ICANN domains like foo.com from private // domains like foo.appspot.com can be found at // https://wiki.mozilla.org/Public_Suffix_List/Use_Cases func PublicSuffix(domain string) (publicSuffix string, icann bool) { lo, hi := uint32(0), uint32(numTLD) s, suffix, wildcard := domain, len(domain), false loop: for { dot := strings.LastIndex(s, ".") if wildcard { suffix = 1 + dot } if lo == hi { break } f := find(s[1+dot:], lo, hi) if f == notFound { break } u := nodes[f] >> (nodesBitsTextOffset + nodesBitsTextLength) icann = u&(1<>= nodesBitsICANN u = children[u&(1<>= childrenBitsLo hi = u & (1<>= childrenBitsHi switch u & (1<>= childrenBitsNodeType wildcard = u&(1<>= nodesBitsTextLength offset := x & (1< 32 { return fmt.Errorf("not enough bits to encode the nodes table") } if childrenBitsLo+childrenBitsHi+childrenBitsNodeType+childrenBitsWildcard > 32 { return fmt.Errorf("not enough bits to encode the children table") } if *version == "" { if *url != defaultURL { return fmt.Errorf("-version was not specified, and the -url is not the default one") } sha, date, err := gitCommit() if err != nil { return err } *version = fmt.Sprintf("publicsuffix.org's public_suffix_list.dat, git revision %s (%s)", sha, date) } var r io.Reader = os.Stdin if *url != "" { res, err := http.Get(*url) if err != nil { return err } if res.StatusCode != http.StatusOK { return fmt.Errorf("bad GET status for %s: %d", *url, res.Status) } r = res.Body defer res.Body.Close() } var root node icann := false br := bufio.NewReader(r) for { s, err := br.ReadString('\n') if err != nil { if err == io.EOF { break } return err } s = strings.TrimSpace(s) if strings.Contains(s, "BEGIN ICANN DOMAINS") { icann = true continue } if strings.Contains(s, "END ICANN DOMAINS") { icann = false continue } if s == "" || strings.HasPrefix(s, "//") { continue } s, err = idna.ToASCII(s) if err != nil { return err } if !validSuffixRE.MatchString(s) { return fmt.Errorf("bad publicsuffix.org list data: %q", s) } if *subset { switch { case s == "ac.jp" || strings.HasSuffix(s, ".ac.jp"): case s == "ak.us" || strings.HasSuffix(s, ".ak.us"): case s == "ao" || strings.HasSuffix(s, ".ao"): case s == "ar" || strings.HasSuffix(s, ".ar"): case s == "arpa" || strings.HasSuffix(s, ".arpa"): case s == "cy" || strings.HasSuffix(s, ".cy"): case s == "dyndns.org" || strings.HasSuffix(s, ".dyndns.org"): case s == "jp": case s == "kobe.jp" || strings.HasSuffix(s, ".kobe.jp"): case s == "kyoto.jp" || strings.HasSuffix(s, ".kyoto.jp"): case s == "om" || strings.HasSuffix(s, ".om"): case s == "uk" || strings.HasSuffix(s, ".uk"): case s == "uk.com" || strings.HasSuffix(s, ".uk.com"): case s == "tw" || strings.HasSuffix(s, ".tw"): case s == "zw" || strings.HasSuffix(s, ".zw"): case s == "xn--p1ai" || strings.HasSuffix(s, ".xn--p1ai"): // xn--p1ai is Russian-Cyrillic "рф". default: continue } } rules = append(rules, s) nt, wildcard := nodeTypeNormal, false switch { case strings.HasPrefix(s, "*."): s, nt = s[2:], nodeTypeParentOnly wildcard = true case strings.HasPrefix(s, "!"): s, nt = s[1:], nodeTypeException } labels := strings.Split(s, ".") for n, i := &root, len(labels)-1; i >= 0; i-- { label := labels[i] n = n.child(label) if i == 0 { if nt != nodeTypeParentOnly && n.nodeType == nodeTypeParentOnly { n.nodeType = nt } n.icann = n.icann && icann n.wildcard = n.wildcard || wildcard } labelsMap[label] = true } } labelsList = make([]string, 0, len(labelsMap)) for label := range labelsMap { labelsList = append(labelsList, label) } sort.Strings(labelsList) if err := generate(printReal, &root, "table.go"); err != nil { return err } if err := generate(printTest, &root, "table_test.go"); err != nil { return err } return nil } func generate(p func(io.Writer, *node) error, root *node, filename string) error { buf := new(bytes.Buffer) if err := p(buf, root); err != nil { return err } b, err := format.Source(buf.Bytes()) if err != nil { return err } return ioutil.WriteFile(filename, b, 0644) } func gitCommit() (sha, date string, retErr error) { res, err := http.Get(gitCommitURL) if err != nil { return "", "", err } if res.StatusCode != http.StatusOK { return "", "", fmt.Errorf("bad GET status for %s: %d", gitCommitURL, res.Status) } defer res.Body.Close() b, err := ioutil.ReadAll(res.Body) if err != nil { return "", "", err } if m := shaRE.FindSubmatch(b); m != nil { sha = string(m[1]) } if m := dateRE.FindSubmatch(b); m != nil { date = string(m[1]) } if sha == "" || date == "" { retErr = fmt.Errorf("could not find commit SHA and date in %s", gitCommitURL) } return sha, date, retErr } func printTest(w io.Writer, n *node) error { fmt.Fprintf(w, "// generated by go run gen.go; DO NOT EDIT\n\n") fmt.Fprintf(w, "package publicsuffix\n\nvar rules = [...]string{\n") for _, rule := range rules { fmt.Fprintf(w, "%q,\n", rule) } fmt.Fprintf(w, "}\n\nvar nodeLabels = [...]string{\n") if err := n.walk(w, printNodeLabel); err != nil { return err } fmt.Fprintf(w, "}\n") return nil } func printReal(w io.Writer, n *node) error { const header = `// generated by go run gen.go; DO NOT EDIT package publicsuffix const version = %q const ( nodesBitsChildren = %d nodesBitsICANN = %d nodesBitsTextOffset = %d nodesBitsTextLength = %d childrenBitsWildcard = %d childrenBitsNodeType = %d childrenBitsHi = %d childrenBitsLo = %d ) const ( nodeTypeNormal = %d nodeTypeException = %d nodeTypeParentOnly = %d ) // numTLD is the number of top level domains. const numTLD = %d ` fmt.Fprintf(w, header, *version, nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength, childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo, nodeTypeNormal, nodeTypeException, nodeTypeParentOnly, len(n.children)) text := combineText(labelsList) if text == "" { return fmt.Errorf("internal error: makeText returned no text") } for _, label := range labelsList { offset, length := strings.Index(text, label), len(label) if offset < 0 { return fmt.Errorf("internal error: could not find %q in text %q", label, text) } maxTextOffset, maxTextLength = max(maxTextOffset, offset), max(maxTextLength, length) if offset >= 1<= 1< 64 { n, plus = 64, " +" } fmt.Fprintf(w, "%q%s\n", text[:n], plus) text = text[n:] } if err := n.walk(w, assignIndexes); err != nil { return err } fmt.Fprintf(w, ` // nodes is the list of nodes. Each node is represented as a uint32, which // encodes the node's children, wildcard bit and node type (as an index into // the children array), ICANN bit and text. // // If the table was generated with the -comments flag, there is a //-comment // after each node's data. In it is the nodes-array indexes of the children, // formatted as (n0x1234-n0x1256), with * denoting the wildcard bit. The // nodeType is printed as + for normal, ! for exception, and o for parent-only // nodes that have children but don't match a domain label in their own right. // An I denotes an ICANN domain. // // The layout within the uint32, from MSB to LSB, is: // [%2d bits] unused // [%2d bits] children index // [%2d bits] ICANN bit // [%2d bits] text index // [%2d bits] text length var nodes = [...]uint32{ `, 32-nodesBitsChildren-nodesBitsICANN-nodesBitsTextOffset-nodesBitsTextLength, nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength) if err := n.walk(w, printNode); err != nil { return err } fmt.Fprintf(w, `} // children is the list of nodes' children, the parent's wildcard bit and the // parent's node type. If a node has no children then their children index // will be in the range [0, 6), depending on the wildcard bit and node type. // // The layout within the uint32, from MSB to LSB, is: // [%2d bits] unused // [%2d bits] wildcard bit // [%2d bits] node type // [%2d bits] high nodes index (exclusive) of children // [%2d bits] low nodes index (inclusive) of children var children=[...]uint32{ `, 32-childrenBitsWildcard-childrenBitsNodeType-childrenBitsHi-childrenBitsLo, childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo) for i, c := range childrenEncoding { s := "---------------" lo := c & (1<> childrenBitsLo) & (1<>(childrenBitsLo+childrenBitsHi)) & (1<>(childrenBitsLo+childrenBitsHi+childrenBitsNodeType) != 0 if *comments { fmt.Fprintf(w, "0x%08x, // c0x%04x (%s)%s %s\n", c, i, s, wildcardStr(wildcard), nodeTypeStr(nodeType)) } else { fmt.Fprintf(w, "0x%x,\n", c) } } fmt.Fprintf(w, "}\n\n") fmt.Fprintf(w, "// max children %d (capacity %d)\n", maxChildren, 1<= 1<= 1<= 1< 0 && ss[0] == "" { ss = ss[1:] } return ss } // crush combines a list of strings, taking advantage of overlaps. It returns a // single string that contains each input string as a substring. func crush(ss []string) string { maxLabelLen := 0 for _, s := range ss { if maxLabelLen < len(s) { maxLabelLen = len(s) } } for prefixLen := maxLabelLen; prefixLen > 0; prefixLen-- { prefixes := makePrefixMap(ss, prefixLen) for i, s := range ss { if len(s) <= prefixLen { continue } mergeLabel(ss, i, prefixLen, prefixes) } } return strings.Join(ss, "") } // mergeLabel merges the label at ss[i] with the first available matching label // in prefixMap, where the last "prefixLen" characters in ss[i] match the first // "prefixLen" characters in the matching label. // It will merge ss[i] repeatedly until no more matches are available. // All matching labels merged into ss[i] are replaced by "". func mergeLabel(ss []string, i, prefixLen int, prefixes prefixMap) { s := ss[i] suffix := s[len(s)-prefixLen:] for _, j := range prefixes[suffix] { // Empty strings mean "already used." Also avoid merging with self. if ss[j] == "" || i == j { continue } if *v { fmt.Fprintf(os.Stderr, "%d-length overlap at (%4d,%4d): %q and %q share %q\n", prefixLen, i, j, ss[i], ss[j], suffix) } ss[i] += ss[j][prefixLen:] ss[j] = "" // ss[i] has a new suffix, so merge again if possible. // Note: we only have to merge again at the same prefix length. Shorter // prefix lengths will be handled in the next iteration of crush's for loop. // Can there be matches for longer prefix lengths, introduced by the merge? // I believe that any such matches would by necessity have been eliminated // during substring removal or merged at a higher prefix length. For // instance, in crush("abc", "cde", "bcdef"), combining "abc" and "cde" // would yield "abcde", which could be merged with "bcdef." However, in // practice "cde" would already have been elimintated by removeSubstrings. mergeLabel(ss, i, prefixLen, prefixes) return } } // prefixMap maps from a prefix to a list of strings containing that prefix. The // list of strings is represented as indexes into a slice of strings stored // elsewhere. type prefixMap map[string][]int // makePrefixMap constructs a prefixMap from a slice of strings. func makePrefixMap(ss []string, prefixLen int) prefixMap { prefixes := make(prefixMap) for i, s := range ss { // We use < rather than <= because if a label matches on a prefix equal to // its full length, that's actually a substring match handled by // removeSubstrings. if prefixLen < len(s) { prefix := s[:prefixLen] prefixes[prefix] = append(prefixes[prefix], i) } } return prefixes } lxd-2.0.11/dist/src/golang.org/x/net/proxy/0000755061062106075000000000000013172163402021474 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/proxy/socks5.go0000644061062106075000000001334413172163402023237 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package proxy import ( "errors" "io" "net" "strconv" ) // SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address // with an optional username and password. See RFC 1928 and RFC 1929. func SOCKS5(network, addr string, auth *Auth, forward Dialer) (Dialer, error) { s := &socks5{ network: network, addr: addr, forward: forward, } if auth != nil { s.user = auth.User s.password = auth.Password } return s, nil } type socks5 struct { user, password string network, addr string forward Dialer } const socks5Version = 5 const ( socks5AuthNone = 0 socks5AuthPassword = 2 ) const socks5Connect = 1 const ( socks5IP4 = 1 socks5Domain = 3 socks5IP6 = 4 ) var socks5Errors = []string{ "", "general failure", "connection forbidden", "network unreachable", "host unreachable", "connection refused", "TTL expired", "command not supported", "address type not supported", } // Dial connects to the address addr on the given network via the SOCKS5 proxy. func (s *socks5) Dial(network, addr string) (net.Conn, error) { switch network { case "tcp", "tcp6", "tcp4": default: return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) } conn, err := s.forward.Dial(s.network, s.addr) if err != nil { return nil, err } if err := s.connect(conn, addr); err != nil { conn.Close() return nil, err } return conn, nil } // connect takes an existing connection to a socks5 proxy server, // and commands the server to extend that connection to target, // which must be a canonical address with a host and port. func (s *socks5) connect(conn net.Conn, target string) error { host, portStr, err := net.SplitHostPort(target) if err != nil { return err } port, err := strconv.Atoi(portStr) if err != nil { return errors.New("proxy: failed to parse port number: " + portStr) } if port < 1 || port > 0xffff { return errors.New("proxy: port number out of range: " + portStr) } // the size here is just an estimate buf := make([]byte, 0, 6+len(host)) buf = append(buf, socks5Version) if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { buf = append(buf, 2 /* num auth methods */, socks5AuthNone, socks5AuthPassword) } else { buf = append(buf, 1 /* num auth methods */, socks5AuthNone) } if _, err := conn.Write(buf); err != nil { return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if _, err := io.ReadFull(conn, buf[:2]); err != nil { return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if buf[0] != 5 { return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) } if buf[1] == 0xff { return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") } // See RFC 1929 if buf[1] == socks5AuthPassword { buf = buf[:0] buf = append(buf, 1 /* password protocol version */) buf = append(buf, uint8(len(s.user))) buf = append(buf, s.user...) buf = append(buf, uint8(len(s.password))) buf = append(buf, s.password...) if _, err := conn.Write(buf); err != nil { return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if _, err := io.ReadFull(conn, buf[:2]); err != nil { return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if buf[1] != 0 { return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") } } buf = buf[:0] buf = append(buf, socks5Version, socks5Connect, 0 /* reserved */) if ip := net.ParseIP(host); ip != nil { if ip4 := ip.To4(); ip4 != nil { buf = append(buf, socks5IP4) ip = ip4 } else { buf = append(buf, socks5IP6) } buf = append(buf, ip...) } else { if len(host) > 255 { return errors.New("proxy: destination host name too long: " + host) } buf = append(buf, socks5Domain) buf = append(buf, byte(len(host))) buf = append(buf, host...) } buf = append(buf, byte(port>>8), byte(port)) if _, err := conn.Write(buf); err != nil { return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if _, err := io.ReadFull(conn, buf[:4]); err != nil { return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } failure := "unknown error" if int(buf[1]) < len(socks5Errors) { failure = socks5Errors[buf[1]] } if len(failure) > 0 { return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) } bytesToDiscard := 0 switch buf[3] { case socks5IP4: bytesToDiscard = net.IPv4len case socks5IP6: bytesToDiscard = net.IPv6len case socks5Domain: _, err := io.ReadFull(conn, buf[:1]) if err != nil { return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } bytesToDiscard = int(buf[0]) default: return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) } if cap(buf) < bytesToDiscard { buf = make([]byte, bytesToDiscard) } else { buf = buf[:bytesToDiscard] } if _, err := io.ReadFull(conn, buf); err != nil { return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } // Also need to discard the port number if _, err := io.ReadFull(conn, buf[:2]); err != nil { return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } return nil } lxd-2.0.11/dist/src/golang.org/x/net/proxy/proxy_test.go0000644061062106075000000001203113172163402024240 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package proxy import ( "bytes" "fmt" "io" "net" "net/url" "os" "strconv" "strings" "sync" "testing" ) type proxyFromEnvTest struct { allProxyEnv string noProxyEnv string wantTypeOf Dialer } func (t proxyFromEnvTest) String() string { var buf bytes.Buffer space := func() { if buf.Len() > 0 { buf.WriteByte(' ') } } if t.allProxyEnv != "" { fmt.Fprintf(&buf, "all_proxy=%q", t.allProxyEnv) } if t.noProxyEnv != "" { space() fmt.Fprintf(&buf, "no_proxy=%q", t.noProxyEnv) } return strings.TrimSpace(buf.String()) } func TestFromEnvironment(t *testing.T) { ResetProxyEnv() type dummyDialer struct { direct } RegisterDialerType("irc", func(_ *url.URL, _ Dialer) (Dialer, error) { return dummyDialer{}, nil }) proxyFromEnvTests := []proxyFromEnvTest{ {allProxyEnv: "127.0.0.1:8080", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}}, {allProxyEnv: "ftp://example.com:8000", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}}, {allProxyEnv: "socks5://example.com:8080", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: &PerHost{}}, {allProxyEnv: "irc://example.com:8000", wantTypeOf: dummyDialer{}}, {noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}}, {wantTypeOf: direct{}}, } for _, tt := range proxyFromEnvTests { os.Setenv("ALL_PROXY", tt.allProxyEnv) os.Setenv("NO_PROXY", tt.noProxyEnv) ResetCachedEnvironment() d := FromEnvironment() if got, want := fmt.Sprintf("%T", d), fmt.Sprintf("%T", tt.wantTypeOf); got != want { t.Errorf("%v: got type = %T, want %T", tt, d, tt.wantTypeOf) } } } func TestFromURL(t *testing.T) { endSystem, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("net.Listen failed: %v", err) } defer endSystem.Close() gateway, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("net.Listen failed: %v", err) } defer gateway.Close() var wg sync.WaitGroup wg.Add(1) go socks5Gateway(t, gateway, endSystem, socks5Domain, &wg) url, err := url.Parse("socks5://user:password@" + gateway.Addr().String()) if err != nil { t.Fatalf("url.Parse failed: %v", err) } proxy, err := FromURL(url, Direct) if err != nil { t.Fatalf("FromURL failed: %v", err) } _, port, err := net.SplitHostPort(endSystem.Addr().String()) if err != nil { t.Fatalf("net.SplitHostPort failed: %v", err) } if c, err := proxy.Dial("tcp", "localhost:"+port); err != nil { t.Fatalf("FromURL.Dial failed: %v", err) } else { c.Close() } wg.Wait() } func TestSOCKS5(t *testing.T) { endSystem, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("net.Listen failed: %v", err) } defer endSystem.Close() gateway, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("net.Listen failed: %v", err) } defer gateway.Close() var wg sync.WaitGroup wg.Add(1) go socks5Gateway(t, gateway, endSystem, socks5IP4, &wg) proxy, err := SOCKS5("tcp", gateway.Addr().String(), nil, Direct) if err != nil { t.Fatalf("SOCKS5 failed: %v", err) } if c, err := proxy.Dial("tcp", endSystem.Addr().String()); err != nil { t.Fatalf("SOCKS5.Dial failed: %v", err) } else { c.Close() } wg.Wait() } func socks5Gateway(t *testing.T, gateway, endSystem net.Listener, typ byte, wg *sync.WaitGroup) { defer wg.Done() c, err := gateway.Accept() if err != nil { t.Errorf("net.Listener.Accept failed: %v", err) return } defer c.Close() b := make([]byte, 32) var n int if typ == socks5Domain { n = 4 } else { n = 3 } if _, err := io.ReadFull(c, b[:n]); err != nil { t.Errorf("io.ReadFull failed: %v", err) return } if _, err := c.Write([]byte{socks5Version, socks5AuthNone}); err != nil { t.Errorf("net.Conn.Write failed: %v", err) return } if typ == socks5Domain { n = 16 } else { n = 10 } if _, err := io.ReadFull(c, b[:n]); err != nil { t.Errorf("io.ReadFull failed: %v", err) return } if b[0] != socks5Version || b[1] != socks5Connect || b[2] != 0x00 || b[3] != typ { t.Errorf("got an unexpected packet: %#02x %#02x %#02x %#02x", b[0], b[1], b[2], b[3]) return } if typ == socks5Domain { copy(b[:5], []byte{socks5Version, 0x00, 0x00, socks5Domain, 9}) b = append(b, []byte("localhost")...) } else { copy(b[:4], []byte{socks5Version, 0x00, 0x00, socks5IP4}) } host, port, err := net.SplitHostPort(endSystem.Addr().String()) if err != nil { t.Errorf("net.SplitHostPort failed: %v", err) return } b = append(b, []byte(net.ParseIP(host).To4())...) p, err := strconv.Atoi(port) if err != nil { t.Errorf("strconv.Atoi failed: %v", err) return } b = append(b, []byte{byte(p >> 8), byte(p)}...) if _, err := c.Write(b); err != nil { t.Errorf("net.Conn.Write failed: %v", err) return } } func ResetProxyEnv() { for _, env := range []*envOnce{allProxyEnv, noProxyEnv} { for _, v := range env.names { os.Setenv(v, "") } } ResetCachedEnvironment() } func ResetCachedEnvironment() { allProxyEnv.reset() noProxyEnv.reset() } lxd-2.0.11/dist/src/golang.org/x/net/proxy/proxy.go0000644061062106075000000000607413172163402023213 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package proxy provides support for a variety of protocols to proxy network // data. package proxy // import "golang.org/x/net/proxy" import ( "errors" "net" "net/url" "os" "sync" ) // A Dialer is a means to establish a connection. type Dialer interface { // Dial connects to the given address via the proxy. Dial(network, addr string) (c net.Conn, err error) } // Auth contains authentication parameters that specific Dialers may require. type Auth struct { User, Password string } // FromEnvironment returns the dialer specified by the proxy related variables in // the environment. func FromEnvironment() Dialer { allProxy := allProxyEnv.Get() if len(allProxy) == 0 { return Direct } proxyURL, err := url.Parse(allProxy) if err != nil { return Direct } proxy, err := FromURL(proxyURL, Direct) if err != nil { return Direct } noProxy := noProxyEnv.Get() if len(noProxy) == 0 { return proxy } perHost := NewPerHost(proxy, Direct) perHost.AddFromString(noProxy) return perHost } // proxySchemes is a map from URL schemes to a function that creates a Dialer // from a URL with such a scheme. var proxySchemes map[string]func(*url.URL, Dialer) (Dialer, error) // RegisterDialerType takes a URL scheme and a function to generate Dialers from // a URL with that scheme and a forwarding Dialer. Registered schemes are used // by FromURL. func RegisterDialerType(scheme string, f func(*url.URL, Dialer) (Dialer, error)) { if proxySchemes == nil { proxySchemes = make(map[string]func(*url.URL, Dialer) (Dialer, error)) } proxySchemes[scheme] = f } // FromURL returns a Dialer given a URL specification and an underlying // Dialer for it to make network requests. func FromURL(u *url.URL, forward Dialer) (Dialer, error) { var auth *Auth if u.User != nil { auth = new(Auth) auth.User = u.User.Username() if p, ok := u.User.Password(); ok { auth.Password = p } } switch u.Scheme { case "socks5": return SOCKS5("tcp", u.Host, auth, forward) } // If the scheme doesn't match any of the built-in schemes, see if it // was registered by another package. if proxySchemes != nil { if f, ok := proxySchemes[u.Scheme]; ok { return f(u, forward) } } return nil, errors.New("proxy: unknown scheme: " + u.Scheme) } var ( allProxyEnv = &envOnce{ names: []string{"ALL_PROXY", "all_proxy"}, } noProxyEnv = &envOnce{ names: []string{"NO_PROXY", "no_proxy"}, } ) // envOnce looks up an environment variable (optionally by multiple // names) once. It mitigates expensive lookups on some platforms // (e.g. Windows). // (Borrowed from net/http/transport.go) type envOnce struct { names []string once sync.Once val string } func (e *envOnce) Get() string { e.once.Do(e.init) return e.val } func (e *envOnce) init() { for _, n := range e.names { e.val = os.Getenv(n) if e.val != "" { return } } } // reset is used by tests func (e *envOnce) reset() { e.once = sync.Once{} e.val = "" } lxd-2.0.11/dist/src/golang.org/x/net/proxy/per_host_test.go0000644061062106075000000000241513172163402024707 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package proxy import ( "errors" "net" "reflect" "testing" ) type recordingProxy struct { addrs []string } func (r *recordingProxy) Dial(network, addr string) (net.Conn, error) { r.addrs = append(r.addrs, addr) return nil, errors.New("recordingProxy") } func TestPerHost(t *testing.T) { var def, bypass recordingProxy perHost := NewPerHost(&def, &bypass) perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16") expectedDef := []string{ "example.com:123", "1.2.3.4:123", "[1001::]:123", } expectedBypass := []string{ "localhost:123", "zone:123", "foo.zone:123", "127.0.0.1:123", "10.1.2.3:123", "[1000::]:123", } for _, addr := range expectedDef { perHost.Dial("tcp", addr) } for _, addr := range expectedBypass { perHost.Dial("tcp", addr) } if !reflect.DeepEqual(expectedDef, def.addrs) { t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef) } if !reflect.DeepEqual(expectedBypass, bypass.addrs) { t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass) } } lxd-2.0.11/dist/src/golang.org/x/net/proxy/per_host.go0000644061062106075000000000720013172163402023645 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package proxy import ( "net" "strings" ) // A PerHost directs connections to a default Dialer unless the host name // requested matches one of a number of exceptions. type PerHost struct { def, bypass Dialer bypassNetworks []*net.IPNet bypassIPs []net.IP bypassZones []string bypassHosts []string } // NewPerHost returns a PerHost Dialer that directs connections to either // defaultDialer or bypass, depending on whether the connection matches one of // the configured rules. func NewPerHost(defaultDialer, bypass Dialer) *PerHost { return &PerHost{ def: defaultDialer, bypass: bypass, } } // Dial connects to the address addr on the given network through either // defaultDialer or bypass. func (p *PerHost) Dial(network, addr string) (c net.Conn, err error) { host, _, err := net.SplitHostPort(addr) if err != nil { return nil, err } return p.dialerForRequest(host).Dial(network, addr) } func (p *PerHost) dialerForRequest(host string) Dialer { if ip := net.ParseIP(host); ip != nil { for _, net := range p.bypassNetworks { if net.Contains(ip) { return p.bypass } } for _, bypassIP := range p.bypassIPs { if bypassIP.Equal(ip) { return p.bypass } } return p.def } for _, zone := range p.bypassZones { if strings.HasSuffix(host, zone) { return p.bypass } if host == zone[1:] { // For a zone ".example.com", we match "example.com" // too. return p.bypass } } for _, bypassHost := range p.bypassHosts { if bypassHost == host { return p.bypass } } return p.def } // AddFromString parses a string that contains comma-separated values // specifying hosts that should use the bypass proxy. Each value is either an // IP address, a CIDR range, a zone (*.example.com) or a host name // (localhost). A best effort is made to parse the string and errors are // ignored. func (p *PerHost) AddFromString(s string) { hosts := strings.Split(s, ",") for _, host := range hosts { host = strings.TrimSpace(host) if len(host) == 0 { continue } if strings.Contains(host, "/") { // We assume that it's a CIDR address like 127.0.0.0/8 if _, net, err := net.ParseCIDR(host); err == nil { p.AddNetwork(net) } continue } if ip := net.ParseIP(host); ip != nil { p.AddIP(ip) continue } if strings.HasPrefix(host, "*.") { p.AddZone(host[1:]) continue } p.AddHost(host) } } // AddIP specifies an IP address that will use the bypass proxy. Note that // this will only take effect if a literal IP address is dialed. A connection // to a named host will never match an IP. func (p *PerHost) AddIP(ip net.IP) { p.bypassIPs = append(p.bypassIPs, ip) } // AddNetwork specifies an IP range that will use the bypass proxy. Note that // this will only take effect if a literal IP address is dialed. A connection // to a named host will never match. func (p *PerHost) AddNetwork(net *net.IPNet) { p.bypassNetworks = append(p.bypassNetworks, net) } // AddZone specifies a DNS suffix that will use the bypass proxy. A zone of // "example.com" matches "example.com" and all of its subdomains. func (p *PerHost) AddZone(zone string) { if strings.HasSuffix(zone, ".") { zone = zone[:len(zone)-1] } if !strings.HasPrefix(zone, ".") { zone = "." + zone } p.bypassZones = append(p.bypassZones, zone) } // AddHost specifies a host name that will use the bypass proxy. func (p *PerHost) AddHost(host string) { if strings.HasSuffix(host, ".") { host = host[:len(host)-1] } p.bypassHosts = append(p.bypassHosts, host) } lxd-2.0.11/dist/src/golang.org/x/net/proxy/direct.go0000644061062106075000000000063013172163402023274 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package proxy import ( "net" ) type direct struct{} // Direct is a direct proxy: one that makes network connections directly. var Direct = direct{} func (direct) Dial(network, addr string) (net.Conn, error) { return net.Dial(network, addr) } lxd-2.0.11/dist/src/golang.org/x/net/netutil/0000755061062106075000000000000013172163402021777 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/netutil/listen_test.go0000644061062106075000000000413513172163402024666 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package netutil import ( "errors" "fmt" "io" "io/ioutil" "net" "net/http" "sync" "sync/atomic" "testing" "time" "golang.org/x/net/internal/nettest" ) func TestLimitListener(t *testing.T) { const max = 5 attempts := (nettest.MaxOpenFiles() - max) / 2 if attempts > 256 { // maximum length of accept queue is 128 by default attempts = 256 } l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer l.Close() l = LimitListener(l, max) var open int32 go http.Serve(l, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if n := atomic.AddInt32(&open, 1); n > max { t.Errorf("%d open connections, want <= %d", n, max) } defer atomic.AddInt32(&open, -1) time.Sleep(10 * time.Millisecond) fmt.Fprint(w, "some body") })) var wg sync.WaitGroup var failed int32 for i := 0; i < attempts; i++ { wg.Add(1) go func() { defer wg.Done() c := http.Client{Timeout: 3 * time.Second} r, err := c.Get("http://" + l.Addr().String()) if err != nil { t.Log(err) atomic.AddInt32(&failed, 1) return } defer r.Body.Close() io.Copy(ioutil.Discard, r.Body) }() } wg.Wait() // We expect some Gets to fail as the kernel's accept queue is filled, // but most should succeed. if int(failed) >= attempts/2 { t.Errorf("%d requests failed within %d attempts", failed, attempts) } } type errorListener struct { net.Listener } func (errorListener) Accept() (net.Conn, error) { return nil, errFake } var errFake = errors.New("fake error from errorListener") // This used to hang. func TestLimitListenerError(t *testing.T) { donec := make(chan bool, 1) go func() { const n = 2 ll := LimitListener(errorListener{}, n) for i := 0; i < n+1; i++ { _, err := ll.Accept() if err != errFake { t.Fatalf("Accept error = %v; want errFake", err) } } donec <- true }() select { case <-donec: case <-time.After(5 * time.Second): t.Fatal("timeout. deadlock?") } } lxd-2.0.11/dist/src/golang.org/x/net/netutil/listen.go0000644061062106075000000000220713172163402023625 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package netutil provides network utility functions, complementing the more // common ones in the net package. package netutil // import "golang.org/x/net/netutil" import ( "net" "sync" ) // LimitListener returns a Listener that accepts at most n simultaneous // connections from the provided Listener. func LimitListener(l net.Listener, n int) net.Listener { return &limitListener{l, make(chan struct{}, n)} } type limitListener struct { net.Listener sem chan struct{} } func (l *limitListener) acquire() { l.sem <- struct{}{} } func (l *limitListener) release() { <-l.sem } func (l *limitListener) Accept() (net.Conn, error) { l.acquire() c, err := l.Listener.Accept() if err != nil { l.release() return nil, err } return &limitListenerConn{Conn: c, release: l.release}, nil } type limitListenerConn struct { net.Conn releaseOnce sync.Once release func() } func (l *limitListenerConn) Close() error { err := l.Conn.Close() l.releaseOnce.Do(l.release) return err } lxd-2.0.11/dist/src/golang.org/x/net/nettest/0000755061062106075000000000000013172163402022001 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/nettest/conntest_test.go0000644061062106075000000000271713172163402025233 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.8 package nettest import ( "net" "os" "runtime" "testing" "golang.org/x/net/internal/nettest" ) func TestTestConn(t *testing.T) { tests := []struct{ name, network string }{ {"TCP", "tcp"}, {"UnixPipe", "unix"}, {"UnixPacketPipe", "unixpacket"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if !nettest.TestableNetwork(tt.network) { t.Skipf("not supported on %s", runtime.GOOS) } mp := func() (c1, c2 net.Conn, stop func(), err error) { ln, err := nettest.NewLocalListener(tt.network) if err != nil { return nil, nil, nil, err } // Start a connection between two endpoints. var err1, err2 error done := make(chan bool) go func() { c2, err2 = ln.Accept() close(done) }() c1, err1 = net.Dial(ln.Addr().Network(), ln.Addr().String()) <-done stop = func() { if err1 == nil { c1.Close() } if err2 == nil { c2.Close() } ln.Close() switch tt.network { case "unix", "unixpacket": os.Remove(ln.Addr().String()) } } switch { case err1 != nil: stop() return nil, nil, nil, err1 case err2 != nil: stop() return nil, nil, nil, err2 default: return c1, c2, stop, nil } } TestConn(t, mp) }) } } lxd-2.0.11/dist/src/golang.org/x/net/nettest/conntest_go17.go0000644061062106075000000000235513172163402025027 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package nettest import "testing" func testConn(t *testing.T, mp MakePipe) { // Use subtests on Go 1.7 and above since it is better organized. t.Run("BasicIO", func(t *testing.T) { timeoutWrapper(t, mp, testBasicIO) }) t.Run("PingPong", func(t *testing.T) { timeoutWrapper(t, mp, testPingPong) }) t.Run("RacyRead", func(t *testing.T) { timeoutWrapper(t, mp, testRacyRead) }) t.Run("RacyWrite", func(t *testing.T) { timeoutWrapper(t, mp, testRacyWrite) }) t.Run("ReadTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testReadTimeout) }) t.Run("WriteTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testWriteTimeout) }) t.Run("PastTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testPastTimeout) }) t.Run("PresentTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testPresentTimeout) }) t.Run("FutureTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testFutureTimeout) }) t.Run("CloseTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testCloseTimeout) }) t.Run("ConcurrentMethods", func(t *testing.T) { timeoutWrapper(t, mp, testConcurrentMethods) }) } lxd-2.0.11/dist/src/golang.org/x/net/nettest/conntest_go16.go0000644061062106075000000000135113172163402025021 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package nettest import "testing" func testConn(t *testing.T, mp MakePipe) { // Avoid using subtests on Go 1.6 and below. timeoutWrapper(t, mp, testBasicIO) timeoutWrapper(t, mp, testPingPong) timeoutWrapper(t, mp, testRacyRead) timeoutWrapper(t, mp, testRacyWrite) timeoutWrapper(t, mp, testReadTimeout) timeoutWrapper(t, mp, testWriteTimeout) timeoutWrapper(t, mp, testPastTimeout) timeoutWrapper(t, mp, testPresentTimeout) timeoutWrapper(t, mp, testFutureTimeout) timeoutWrapper(t, mp, testCloseTimeout) timeoutWrapper(t, mp, testConcurrentMethods) } lxd-2.0.11/dist/src/golang.org/x/net/nettest/conntest.go0000644061062106075000000002627113172163402024175 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package nettest provides utilities for network testing. package nettest import ( "bytes" "encoding/binary" "io" "io/ioutil" "math/rand" "net" "runtime" "sync" "testing" "time" ) var ( aLongTimeAgo = time.Unix(233431200, 0) neverTimeout = time.Time{} ) // MakePipe creates a connection between two endpoints and returns the pair // as c1 and c2, such that anything written to c1 is read by c2 and vice-versa. // The stop function closes all resources, including c1, c2, and the underlying // net.Listener (if there is one), and should not be nil. type MakePipe func() (c1, c2 net.Conn, stop func(), err error) // TestConn tests that a net.Conn implementation properly satisfies the interface. // The tests should not produce any false positives, but may experience // false negatives. Thus, some issues may only be detected when the test is // run multiple times. For maximal effectiveness, run the tests under the // race detector. func TestConn(t *testing.T, mp MakePipe) { testConn(t, mp) } type connTester func(t *testing.T, c1, c2 net.Conn) func timeoutWrapper(t *testing.T, mp MakePipe, f connTester) { c1, c2, stop, err := mp() if err != nil { t.Fatalf("unable to make pipe: %v", err) } var once sync.Once defer once.Do(func() { stop() }) timer := time.AfterFunc(time.Minute, func() { once.Do(func() { t.Error("test timed out; terminating pipe") stop() }) }) defer timer.Stop() f(t, c1, c2) } // testBasicIO tests that the data sent on c1 is properly received on c2. func testBasicIO(t *testing.T, c1, c2 net.Conn) { want := make([]byte, 1<<20) rand.New(rand.NewSource(0)).Read(want) dataCh := make(chan []byte) go func() { rd := bytes.NewReader(want) if err := chunkedCopy(c1, rd); err != nil { t.Errorf("unexpected c1.Write error: %v", err) } if err := c1.Close(); err != nil { t.Errorf("unexpected c1.Close error: %v", err) } }() go func() { wr := new(bytes.Buffer) if err := chunkedCopy(wr, c2); err != nil { t.Errorf("unexpected c2.Read error: %v", err) } if err := c2.Close(); err != nil { t.Errorf("unexpected c2.Close error: %v", err) } dataCh <- wr.Bytes() }() if got := <-dataCh; !bytes.Equal(got, want) { t.Errorf("transmitted data differs") } } // testPingPong tests that the two endpoints can synchronously send data to // each other in a typical request-response pattern. func testPingPong(t *testing.T, c1, c2 net.Conn) { var wg sync.WaitGroup defer wg.Wait() pingPonger := func(c net.Conn) { defer wg.Done() buf := make([]byte, 8) var prev uint64 for { if _, err := io.ReadFull(c, buf); err != nil { if err == io.EOF { break } t.Errorf("unexpected Read error: %v", err) } v := binary.LittleEndian.Uint64(buf) binary.LittleEndian.PutUint64(buf, v+1) if prev != 0 && prev+2 != v { t.Errorf("mismatching value: got %d, want %d", v, prev+2) } prev = v if v == 1000 { break } if _, err := c.Write(buf); err != nil { t.Errorf("unexpected Write error: %v", err) break } } if err := c.Close(); err != nil { t.Errorf("unexpected Close error: %v", err) } } wg.Add(2) go pingPonger(c1) go pingPonger(c2) // Start off the chain reaction. if _, err := c1.Write(make([]byte, 8)); err != nil { t.Errorf("unexpected c1.Write error: %v", err) } } // testRacyRead tests that it is safe to mutate the input Read buffer // immediately after cancelation has occurred. func testRacyRead(t *testing.T, c1, c2 net.Conn) { go chunkedCopy(c2, rand.New(rand.NewSource(0))) var wg sync.WaitGroup defer wg.Wait() c1.SetReadDeadline(time.Now().Add(time.Millisecond)) for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() b1 := make([]byte, 1024) b2 := make([]byte, 1024) for j := 0; j < 100; j++ { _, err := c1.Read(b1) copy(b1, b2) // Mutate b1 to trigger potential race if err != nil { checkForTimeoutError(t, err) c1.SetReadDeadline(time.Now().Add(time.Millisecond)) } } }() } } // testRacyWrite tests that it is safe to mutate the input Write buffer // immediately after cancelation has occurred. func testRacyWrite(t *testing.T, c1, c2 net.Conn) { go chunkedCopy(ioutil.Discard, c2) var wg sync.WaitGroup defer wg.Wait() c1.SetWriteDeadline(time.Now().Add(time.Millisecond)) for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() b1 := make([]byte, 1024) b2 := make([]byte, 1024) for j := 0; j < 100; j++ { _, err := c1.Write(b1) copy(b1, b2) // Mutate b1 to trigger potential race if err != nil { checkForTimeoutError(t, err) c1.SetWriteDeadline(time.Now().Add(time.Millisecond)) } } }() } } // testReadTimeout tests that Read timeouts do not affect Write. func testReadTimeout(t *testing.T, c1, c2 net.Conn) { go chunkedCopy(ioutil.Discard, c2) c1.SetReadDeadline(aLongTimeAgo) _, err := c1.Read(make([]byte, 1024)) checkForTimeoutError(t, err) if _, err := c1.Write(make([]byte, 1024)); err != nil { t.Errorf("unexpected Write error: %v", err) } } // testWriteTimeout tests that Write timeouts do not affect Read. func testWriteTimeout(t *testing.T, c1, c2 net.Conn) { go chunkedCopy(c2, rand.New(rand.NewSource(0))) c1.SetWriteDeadline(aLongTimeAgo) _, err := c1.Write(make([]byte, 1024)) checkForTimeoutError(t, err) if _, err := c1.Read(make([]byte, 1024)); err != nil { t.Errorf("unexpected Read error: %v", err) } } // testPastTimeout tests that a deadline set in the past immediately times out // Read and Write requests. func testPastTimeout(t *testing.T, c1, c2 net.Conn) { go chunkedCopy(c2, c2) testRoundtrip(t, c1) c1.SetDeadline(aLongTimeAgo) n, err := c1.Write(make([]byte, 1024)) if n != 0 { t.Errorf("unexpected Write count: got %d, want 0", n) } checkForTimeoutError(t, err) n, err = c1.Read(make([]byte, 1024)) if n != 0 { t.Errorf("unexpected Read count: got %d, want 0", n) } checkForTimeoutError(t, err) testRoundtrip(t, c1) } // testPresentTimeout tests that a deadline set while there are pending // Read and Write operations immediately times out those operations. func testPresentTimeout(t *testing.T, c1, c2 net.Conn) { var wg sync.WaitGroup defer wg.Wait() wg.Add(3) deadlineSet := make(chan bool, 1) go func() { defer wg.Done() time.Sleep(100 * time.Millisecond) deadlineSet <- true c1.SetReadDeadline(aLongTimeAgo) c1.SetWriteDeadline(aLongTimeAgo) }() go func() { defer wg.Done() n, err := c1.Read(make([]byte, 1024)) if n != 0 { t.Errorf("unexpected Read count: got %d, want 0", n) } checkForTimeoutError(t, err) if len(deadlineSet) == 0 { t.Error("Read timed out before deadline is set") } }() go func() { defer wg.Done() var err error for err == nil { _, err = c1.Write(make([]byte, 1024)) } checkForTimeoutError(t, err) if len(deadlineSet) == 0 { t.Error("Write timed out before deadline is set") } }() } // testFutureTimeout tests that a future deadline will eventually time out // Read and Write operations. func testFutureTimeout(t *testing.T, c1, c2 net.Conn) { var wg sync.WaitGroup wg.Add(2) c1.SetDeadline(time.Now().Add(100 * time.Millisecond)) go func() { defer wg.Done() _, err := c1.Read(make([]byte, 1024)) checkForTimeoutError(t, err) }() go func() { defer wg.Done() var err error for err == nil { _, err = c1.Write(make([]byte, 1024)) } checkForTimeoutError(t, err) }() wg.Wait() go chunkedCopy(c2, c2) resyncConn(t, c1) testRoundtrip(t, c1) } // testCloseTimeout tests that calling Close immediately times out pending // Read and Write operations. func testCloseTimeout(t *testing.T, c1, c2 net.Conn) { go chunkedCopy(c2, c2) var wg sync.WaitGroup defer wg.Wait() wg.Add(3) // Test for cancelation upon connection closure. c1.SetDeadline(neverTimeout) go func() { defer wg.Done() time.Sleep(100 * time.Millisecond) c1.Close() }() go func() { defer wg.Done() var err error buf := make([]byte, 1024) for err == nil { _, err = c1.Read(buf) } }() go func() { defer wg.Done() var err error buf := make([]byte, 1024) for err == nil { _, err = c1.Write(buf) } }() } // testConcurrentMethods tests that the methods of net.Conn can safely // be called concurrently. func testConcurrentMethods(t *testing.T, c1, c2 net.Conn) { if runtime.GOOS == "plan9" { t.Skip("skipping on plan9; see https://golang.org/issue/20489") } go chunkedCopy(c2, c2) // The results of the calls may be nonsensical, but this should // not trigger a race detector warning. var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(7) go func() { defer wg.Done() c1.Read(make([]byte, 1024)) }() go func() { defer wg.Done() c1.Write(make([]byte, 1024)) }() go func() { defer wg.Done() c1.SetDeadline(time.Now().Add(10 * time.Millisecond)) }() go func() { defer wg.Done() c1.SetReadDeadline(aLongTimeAgo) }() go func() { defer wg.Done() c1.SetWriteDeadline(aLongTimeAgo) }() go func() { defer wg.Done() c1.LocalAddr() }() go func() { defer wg.Done() c1.RemoteAddr() }() } wg.Wait() // At worst, the deadline is set 10ms into the future resyncConn(t, c1) testRoundtrip(t, c1) } // checkForTimeoutError checks that the error satisfies the Error interface // and that Timeout returns true. func checkForTimeoutError(t *testing.T, err error) { if nerr, ok := err.(net.Error); ok { if !nerr.Timeout() { t.Errorf("err.Timeout() = false, want true") } } else { t.Errorf("got %T, want net.Error", err) } } // testRoundtrip writes something into c and reads it back. // It assumes that everything written into c is echoed back to itself. func testRoundtrip(t *testing.T, c net.Conn) { if err := c.SetDeadline(neverTimeout); err != nil { t.Errorf("roundtrip SetDeadline error: %v", err) } const s = "Hello, world!" buf := []byte(s) if _, err := c.Write(buf); err != nil { t.Errorf("roundtrip Write error: %v", err) } if _, err := io.ReadFull(c, buf); err != nil { t.Errorf("roundtrip Read error: %v", err) } if string(buf) != s { t.Errorf("roundtrip data mismatch: got %q, want %q", buf, s) } } // resyncConn resynchronizes the connection into a sane state. // It assumes that everything written into c is echoed back to itself. // It assumes that 0xff is not currently on the wire or in the read buffer. func resyncConn(t *testing.T, c net.Conn) { c.SetDeadline(neverTimeout) errCh := make(chan error) go func() { _, err := c.Write([]byte{0xff}) errCh <- err }() buf := make([]byte, 1024) for { n, err := c.Read(buf) if n > 0 && bytes.IndexByte(buf[:n], 0xff) == n-1 { break } if err != nil { t.Errorf("unexpected Read error: %v", err) break } } if err := <-errCh; err != nil { t.Errorf("unexpected Write error: %v", err) } } // chunkedCopy copies from r to w in fixed-width chunks to avoid // causing a Write that exceeds the maximum packet size for packet-based // connections like "unixpacket". // We assume that the maximum packet size is at least 1024. func chunkedCopy(w io.Writer, r io.Reader) error { b := make([]byte, 1024) _, err := io.CopyBuffer(struct{ io.Writer }{w}, struct{ io.Reader }{r}, b) return err } lxd-2.0.11/dist/src/golang.org/x/net/lif/0000755061062106075000000000000013172163402021065 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/lif/zsys_solaris_amd64.go0000644061062106075000000000365613172163402025165 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_solaris.go package lif const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1a sysSOCK_DGRAM = 0x1 ) type sockaddrStorage struct { Family uint16 X_ss_pad1 [6]int8 X_ss_align float64 X_ss_pad2 [240]int8 } const ( sysLIFC_NOXMIT = 0x1 sysLIFC_EXTERNAL_SOURCE = 0x2 sysLIFC_TEMPORARY = 0x4 sysLIFC_ALLZONES = 0x8 sysLIFC_UNDER_IPMP = 0x10 sysLIFC_ENABLED = 0x20 sysSIOCGLIFADDR = -0x3f87968f sysSIOCGLIFDSTADDR = -0x3f87968d sysSIOCGLIFFLAGS = -0x3f87968b sysSIOCGLIFMTU = -0x3f879686 sysSIOCGLIFNETMASK = -0x3f879683 sysSIOCGLIFMETRIC = -0x3f879681 sysSIOCGLIFNUM = -0x3ff3967e sysSIOCGLIFINDEX = -0x3f87967b sysSIOCGLIFSUBNET = -0x3f879676 sysSIOCGLIFLNKINFO = -0x3f879674 sysSIOCGLIFCONF = -0x3fef965b sysSIOCGLIFHWADDR = -0x3f879640 ) const ( sysIFF_UP = 0x1 sysIFF_BROADCAST = 0x2 sysIFF_DEBUG = 0x4 sysIFF_LOOPBACK = 0x8 sysIFF_POINTOPOINT = 0x10 sysIFF_NOTRAILERS = 0x20 sysIFF_RUNNING = 0x40 sysIFF_NOARP = 0x80 sysIFF_PROMISC = 0x100 sysIFF_ALLMULTI = 0x200 sysIFF_INTELLIGENT = 0x400 sysIFF_MULTICAST = 0x800 sysIFF_MULTI_BCAST = 0x1000 sysIFF_UNNUMBERED = 0x2000 sysIFF_PRIVATE = 0x8000 ) const ( sizeofLifnum = 0xc sizeofLifreq = 0x178 sizeofLifconf = 0x18 sizeofLifIfinfoReq = 0x10 ) type lifnum struct { Family uint16 Pad_cgo_0 [2]byte Flags int32 Count int32 } type lifreq struct { Name [32]int8 Lifru1 [4]byte Type uint32 Lifru [336]byte } type lifconf struct { Family uint16 Pad_cgo_0 [2]byte Flags int32 Len int32 Pad_cgo_1 [4]byte Lifcu [8]byte } type lifIfinfoReq struct { Maxhops uint8 Pad_cgo_0 [3]byte Reachtime uint32 Reachretrans uint32 Maxmtu uint32 } const ( sysIFT_IPV4 = 0xc8 sysIFT_IPV6 = 0xc9 sysIFT_6TO4 = 0xca ) lxd-2.0.11/dist/src/golang.org/x/net/lif/syscall.go0000644061062106075000000000120113172163402023060 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package lif import ( "syscall" "unsafe" ) //go:cgo_import_dynamic libc_ioctl ioctl "libc.so" //go:linkname procIoctl libc_ioctl var procIoctl uintptr func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (uintptr, uintptr, syscall.Errno) func ioctl(s, ioc uintptr, arg unsafe.Pointer) error { _, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procIoctl)), 3, s, ioc, uintptr(arg), 0, 0, 0) if errno != 0 { return error(errno) } return nil } lxd-2.0.11/dist/src/golang.org/x/net/lif/sys_solaris_amd64.s0000644061062106075000000000037013172163402024616 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "textflag.h" TEXT ·sysvicall6(SB),NOSPLIT,$0-88 JMP syscall·sysvicall6(SB) lxd-2.0.11/dist/src/golang.org/x/net/lif/sys.go0000644061062106075000000000061613172163402022235 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package lif import "unsafe" var nativeEndian binaryByteOrder func init() { i := uint32(1) b := (*[4]byte)(unsafe.Pointer(&i)) if b[0] == 1 { nativeEndian = littleEndian } else { nativeEndian = bigEndian } } lxd-2.0.11/dist/src/golang.org/x/net/lif/link_test.go0000644061062106075000000000255013172163402023412 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package lif import ( "fmt" "testing" ) func (ll *Link) String() string { return fmt.Sprintf("name=%s index=%d type=%d flags=%#x mtu=%d addr=%v", ll.Name, ll.Index, ll.Type, ll.Flags, ll.MTU, llAddr(ll.Addr)) } type linkPack struct { af int lls []Link } func linkPacks() ([]linkPack, error) { var lastErr error var lps []linkPack for _, af := range [...]int{sysAF_UNSPEC, sysAF_INET, sysAF_INET6} { lls, err := Links(af, "") if err != nil { lastErr = err continue } lps = append(lps, linkPack{af: af, lls: lls}) } return lps, lastErr } func TestLinks(t *testing.T) { lps, err := linkPacks() if len(lps) == 0 && err != nil { t.Fatal(err) } for _, lp := range lps { n := 0 for _, sll := range lp.lls { lls, err := Links(lp.af, sll.Name) if err != nil { t.Fatal(lp.af, sll.Name, err) } for _, ll := range lls { if ll.Name != sll.Name || ll.Index != sll.Index { t.Errorf("af=%s got %v; want %v", addrFamily(lp.af), &ll, &sll) continue } t.Logf("af=%s name=%s %v", addrFamily(lp.af), sll.Name, &ll) n++ } } if n != len(lp.lls) { t.Errorf("af=%s got %d; want %d", addrFamily(lp.af), n, len(lp.lls)) continue } } } lxd-2.0.11/dist/src/golang.org/x/net/lif/link.go0000644061062106075000000000722013172163402022352 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package lif import "unsafe" // A Link represents logical data link information. // // It also represents base information for logical network interface. // On Solaris, each logical network interface represents network layer // adjacency information and the interface has a only single network // address or address pair for tunneling. It's usual that multiple // logical network interfaces share the same logical data link. type Link struct { Name string // name, equivalent to IP interface name Index int // index, equivalent to IP interface index Type int // type Flags int // flags MTU int // maximum transmission unit, basically link MTU but may differ between IP address families Addr []byte // address } func (ll *Link) fetch(s uintptr) { var lifr lifreq for i := 0; i < len(ll.Name); i++ { lifr.Name[i] = int8(ll.Name[i]) } ioc := int64(sysSIOCGLIFINDEX) if err := ioctl(s, uintptr(ioc), unsafe.Pointer(&lifr)); err == nil { ll.Index = int(nativeEndian.Uint32(lifr.Lifru[:4])) } ioc = int64(sysSIOCGLIFFLAGS) if err := ioctl(s, uintptr(ioc), unsafe.Pointer(&lifr)); err == nil { ll.Flags = int(nativeEndian.Uint64(lifr.Lifru[:8])) } ioc = int64(sysSIOCGLIFMTU) if err := ioctl(s, uintptr(ioc), unsafe.Pointer(&lifr)); err == nil { ll.MTU = int(nativeEndian.Uint32(lifr.Lifru[:4])) } switch ll.Type { case sysIFT_IPV4, sysIFT_IPV6, sysIFT_6TO4: default: ioc = int64(sysSIOCGLIFHWADDR) if err := ioctl(s, uintptr(ioc), unsafe.Pointer(&lifr)); err == nil { ll.Addr, _ = parseLinkAddr(lifr.Lifru[4:]) } } } // Links returns a list of logical data links. // // The provided af must be an address family and name must be a data // link name. The zero value of af or name means a wildcard. func Links(af int, name string) ([]Link, error) { eps, err := newEndpoints(af) if len(eps) == 0 { return nil, err } defer func() { for _, ep := range eps { ep.close() } }() return links(eps, name) } func links(eps []endpoint, name string) ([]Link, error) { var lls []Link lifn := lifnum{Flags: sysLIFC_NOXMIT | sysLIFC_TEMPORARY | sysLIFC_ALLZONES | sysLIFC_UNDER_IPMP} lifc := lifconf{Flags: sysLIFC_NOXMIT | sysLIFC_TEMPORARY | sysLIFC_ALLZONES | sysLIFC_UNDER_IPMP} for _, ep := range eps { lifn.Family = uint16(ep.af) ioc := int64(sysSIOCGLIFNUM) if err := ioctl(ep.s, uintptr(ioc), unsafe.Pointer(&lifn)); err != nil { continue } if lifn.Count == 0 { continue } b := make([]byte, lifn.Count*sizeofLifreq) lifc.Family = uint16(ep.af) lifc.Len = lifn.Count * sizeofLifreq if len(lifc.Lifcu) == 8 { nativeEndian.PutUint64(lifc.Lifcu[:], uint64(uintptr(unsafe.Pointer(&b[0])))) } else { nativeEndian.PutUint32(lifc.Lifcu[:], uint32(uintptr(unsafe.Pointer(&b[0])))) } ioc = int64(sysSIOCGLIFCONF) if err := ioctl(ep.s, uintptr(ioc), unsafe.Pointer(&lifc)); err != nil { continue } nb := make([]byte, 32) // see LIFNAMSIZ in net/if.h for i := 0; i < int(lifn.Count); i++ { lifr := (*lifreq)(unsafe.Pointer(&b[i*sizeofLifreq])) for i := 0; i < 32; i++ { if lifr.Name[i] == 0 { nb = nb[:i] break } nb[i] = byte(lifr.Name[i]) } llname := string(nb) nb = nb[:32] if isDupLink(lls, llname) || name != "" && name != llname { continue } ll := Link{Name: llname, Type: int(lifr.Type)} ll.fetch(ep.s) lls = append(lls, ll) } } return lls, nil } func isDupLink(lls []Link, name string) bool { for _, ll := range lls { if ll.Name == name { return true } } return false } lxd-2.0.11/dist/src/golang.org/x/net/lif/lif.go0000644061062106075000000000163413172163402022172 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris // Package lif provides basic functions for the manipulation of // logical network interfaces and interface addresses on Solaris. // // The package supports Solaris 11 or above. package lif import "syscall" type endpoint struct { af int s uintptr } func (ep *endpoint) close() error { return syscall.Close(int(ep.s)) } func newEndpoints(af int) ([]endpoint, error) { var lastErr error var eps []endpoint afs := []int{sysAF_INET, sysAF_INET6} if af != sysAF_UNSPEC { afs = []int{af} } for _, af := range afs { s, err := syscall.Socket(af, sysSOCK_DGRAM, 0) if err != nil { lastErr = err continue } eps = append(eps, endpoint{af: af, s: uintptr(s)}) } if len(eps) == 0 { return nil, lastErr } return eps, nil } lxd-2.0.11/dist/src/golang.org/x/net/lif/defs_solaris.go0000644061062106075000000000440113172163402024070 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package lif /* #include #include #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_DGRAM = C.SOCK_DGRAM ) type sockaddrStorage C.struct_sockaddr_storage const ( sysLIFC_NOXMIT = C.LIFC_NOXMIT sysLIFC_EXTERNAL_SOURCE = C.LIFC_EXTERNAL_SOURCE sysLIFC_TEMPORARY = C.LIFC_TEMPORARY sysLIFC_ALLZONES = C.LIFC_ALLZONES sysLIFC_UNDER_IPMP = C.LIFC_UNDER_IPMP sysLIFC_ENABLED = C.LIFC_ENABLED sysSIOCGLIFADDR = C.SIOCGLIFADDR sysSIOCGLIFDSTADDR = C.SIOCGLIFDSTADDR sysSIOCGLIFFLAGS = C.SIOCGLIFFLAGS sysSIOCGLIFMTU = C.SIOCGLIFMTU sysSIOCGLIFNETMASK = C.SIOCGLIFNETMASK sysSIOCGLIFMETRIC = C.SIOCGLIFMETRIC sysSIOCGLIFNUM = C.SIOCGLIFNUM sysSIOCGLIFINDEX = C.SIOCGLIFINDEX sysSIOCGLIFSUBNET = C.SIOCGLIFSUBNET sysSIOCGLIFLNKINFO = C.SIOCGLIFLNKINFO sysSIOCGLIFCONF = C.SIOCGLIFCONF sysSIOCGLIFHWADDR = C.SIOCGLIFHWADDR ) const ( sysIFF_UP = C.IFF_UP sysIFF_BROADCAST = C.IFF_BROADCAST sysIFF_DEBUG = C.IFF_DEBUG sysIFF_LOOPBACK = C.IFF_LOOPBACK sysIFF_POINTOPOINT = C.IFF_POINTOPOINT sysIFF_NOTRAILERS = C.IFF_NOTRAILERS sysIFF_RUNNING = C.IFF_RUNNING sysIFF_NOARP = C.IFF_NOARP sysIFF_PROMISC = C.IFF_PROMISC sysIFF_ALLMULTI = C.IFF_ALLMULTI sysIFF_INTELLIGENT = C.IFF_INTELLIGENT sysIFF_MULTICAST = C.IFF_MULTICAST sysIFF_MULTI_BCAST = C.IFF_MULTI_BCAST sysIFF_UNNUMBERED = C.IFF_UNNUMBERED sysIFF_PRIVATE = C.IFF_PRIVATE ) const ( sizeofLifnum = C.sizeof_struct_lifnum sizeofLifreq = C.sizeof_struct_lifreq sizeofLifconf = C.sizeof_struct_lifconf sizeofLifIfinfoReq = C.sizeof_struct_lif_ifinfo_req ) type lifnum C.struct_lifnum type lifreq C.struct_lifreq type lifconf C.struct_lifconf type lifIfinfoReq C.struct_lif_ifinfo_req const ( sysIFT_IPV4 = C.IFT_IPV4 sysIFT_IPV6 = C.IFT_IPV6 sysIFT_6TO4 = C.IFT_6TO4 ) lxd-2.0.11/dist/src/golang.org/x/net/lif/binary.go0000644061062106075000000000645313172163402022710 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package lif // This file contains duplicates of encoding/binary package. // // This package is supposed to be used by the net package of standard // library. Therefore the package set used in the package must be the // same as net package. var ( littleEndian binaryLittleEndian bigEndian binaryBigEndian ) type binaryByteOrder interface { Uint16([]byte) uint16 Uint32([]byte) uint32 Uint64([]byte) uint64 PutUint16([]byte, uint16) PutUint32([]byte, uint32) PutUint64([]byte, uint64) } type binaryLittleEndian struct{} func (binaryLittleEndian) Uint16(b []byte) uint16 { _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 return uint16(b[0]) | uint16(b[1])<<8 } func (binaryLittleEndian) PutUint16(b []byte, v uint16) { _ = b[1] // early bounds check to guarantee safety of writes below b[0] = byte(v) b[1] = byte(v >> 8) } func (binaryLittleEndian) Uint32(b []byte) uint32 { _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 } func (binaryLittleEndian) PutUint32(b []byte, v uint32) { _ = b[3] // early bounds check to guarantee safety of writes below b[0] = byte(v) b[1] = byte(v >> 8) b[2] = byte(v >> 16) b[3] = byte(v >> 24) } func (binaryLittleEndian) Uint64(b []byte) uint64 { _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 } func (binaryLittleEndian) PutUint64(b []byte, v uint64) { _ = b[7] // early bounds check to guarantee safety of writes below b[0] = byte(v) b[1] = byte(v >> 8) b[2] = byte(v >> 16) b[3] = byte(v >> 24) b[4] = byte(v >> 32) b[5] = byte(v >> 40) b[6] = byte(v >> 48) b[7] = byte(v >> 56) } type binaryBigEndian struct{} func (binaryBigEndian) Uint16(b []byte) uint16 { _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 return uint16(b[1]) | uint16(b[0])<<8 } func (binaryBigEndian) PutUint16(b []byte, v uint16) { _ = b[1] // early bounds check to guarantee safety of writes below b[0] = byte(v >> 8) b[1] = byte(v) } func (binaryBigEndian) Uint32(b []byte) uint32 { _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 } func (binaryBigEndian) PutUint32(b []byte, v uint32) { _ = b[3] // early bounds check to guarantee safety of writes below b[0] = byte(v >> 24) b[1] = byte(v >> 16) b[2] = byte(v >> 8) b[3] = byte(v) } func (binaryBigEndian) Uint64(b []byte) uint64 { _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 } func (binaryBigEndian) PutUint64(b []byte, v uint64) { _ = b[7] // early bounds check to guarantee safety of writes below b[0] = byte(v >> 56) b[1] = byte(v >> 48) b[2] = byte(v >> 40) b[3] = byte(v >> 32) b[4] = byte(v >> 24) b[5] = byte(v >> 16) b[6] = byte(v >> 8) b[7] = byte(v) } lxd-2.0.11/dist/src/golang.org/x/net/lif/address_test.go0000644061062106075000000000474413172163402024111 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package lif import ( "fmt" "testing" ) type addrFamily int func (af addrFamily) String() string { switch af { case sysAF_UNSPEC: return "unspec" case sysAF_INET: return "inet4" case sysAF_INET6: return "inet6" default: return fmt.Sprintf("%d", af) } } const hexDigit = "0123456789abcdef" type llAddr []byte func (a llAddr) String() string { if len(a) == 0 { return "" } buf := make([]byte, 0, len(a)*3-1) for i, b := range a { if i > 0 { buf = append(buf, ':') } buf = append(buf, hexDigit[b>>4]) buf = append(buf, hexDigit[b&0xF]) } return string(buf) } type ipAddr []byte func (a ipAddr) String() string { if len(a) == 0 { return "" } if len(a) == 4 { return fmt.Sprintf("%d.%d.%d.%d", a[0], a[1], a[2], a[3]) } if len(a) == 16 { return fmt.Sprintf("%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]) } s := make([]byte, len(a)*2) for i, tn := range a { s[i*2], s[i*2+1] = hexDigit[tn>>4], hexDigit[tn&0xf] } return string(s) } func (a *Inet4Addr) String() string { return fmt.Sprintf("(%s %s %d)", addrFamily(a.Family()), ipAddr(a.IP[:]), a.PrefixLen) } func (a *Inet6Addr) String() string { return fmt.Sprintf("(%s %s %d %d)", addrFamily(a.Family()), ipAddr(a.IP[:]), a.PrefixLen, a.ZoneID) } type addrPack struct { af int as []Addr } func addrPacks() ([]addrPack, error) { var lastErr error var aps []addrPack for _, af := range [...]int{sysAF_UNSPEC, sysAF_INET, sysAF_INET6} { as, err := Addrs(af, "") if err != nil { lastErr = err continue } aps = append(aps, addrPack{af: af, as: as}) } return aps, lastErr } func TestAddrs(t *testing.T) { aps, err := addrPacks() if len(aps) == 0 && err != nil { t.Fatal(err) } lps, err := linkPacks() if len(lps) == 0 && err != nil { t.Fatal(err) } for _, lp := range lps { n := 0 for _, ll := range lp.lls { as, err := Addrs(lp.af, ll.Name) if err != nil { t.Fatal(lp.af, ll.Name, err) } t.Logf("af=%s name=%s %v", addrFamily(lp.af), ll.Name, as) n += len(as) } for _, ap := range aps { if ap.af != lp.af { continue } if n != len(ap.as) { t.Errorf("af=%s got %d; want %d", addrFamily(lp.af), n, len(ap.as)) continue } } } } lxd-2.0.11/dist/src/golang.org/x/net/lif/address.go0000644061062106075000000000471313172163402023046 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package lif import ( "errors" "unsafe" ) // An Addr represents an address associated with packet routing. type Addr interface { // Family returns an address family. Family() int } // An Inet4Addr represents an internet address for IPv4. type Inet4Addr struct { IP [4]byte // IP address PrefixLen int // address prefix length } // Family implements the Family method of Addr interface. func (a *Inet4Addr) Family() int { return sysAF_INET } // An Inet6Addr represents an internet address for IPv6. type Inet6Addr struct { IP [16]byte // IP address PrefixLen int // address prefix length ZoneID int // zone identifier } // Family implements the Family method of Addr interface. func (a *Inet6Addr) Family() int { return sysAF_INET6 } // Addrs returns a list of interface addresses. // // The provided af must be an address family and name must be a data // link name. The zero value of af or name means a wildcard. func Addrs(af int, name string) ([]Addr, error) { eps, err := newEndpoints(af) if len(eps) == 0 { return nil, err } defer func() { for _, ep := range eps { ep.close() } }() lls, err := links(eps, name) if len(lls) == 0 { return nil, err } var as []Addr for _, ll := range lls { var lifr lifreq for i := 0; i < len(ll.Name); i++ { lifr.Name[i] = int8(ll.Name[i]) } for _, ep := range eps { ioc := int64(sysSIOCGLIFADDR) err := ioctl(ep.s, uintptr(ioc), unsafe.Pointer(&lifr)) if err != nil { continue } sa := (*sockaddrStorage)(unsafe.Pointer(&lifr.Lifru[0])) l := int(nativeEndian.Uint32(lifr.Lifru1[:4])) if l == 0 { continue } switch sa.Family { case sysAF_INET: a := &Inet4Addr{PrefixLen: l} copy(a.IP[:], lifr.Lifru[4:8]) as = append(as, a) case sysAF_INET6: a := &Inet6Addr{PrefixLen: l, ZoneID: int(nativeEndian.Uint32(lifr.Lifru[24:28]))} copy(a.IP[:], lifr.Lifru[8:24]) as = append(as, a) } } } return as, nil } func parseLinkAddr(b []byte) ([]byte, error) { nlen, alen, slen := int(b[1]), int(b[2]), int(b[3]) l := 4 + nlen + alen + slen if len(b) < l { return nil, errors.New("invalid address") } b = b[4:] var addr []byte if nlen > 0 { b = b[nlen:] } if alen > 0 { addr = make([]byte, alen) copy(addr, b[:alen]) } return addr, nil } lxd-2.0.11/dist/src/golang.org/x/net/lex/0000755061062106075000000000000013172163402021103 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/lex/httplex/0000755061062106075000000000000013172163402022573 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/lex/httplex/httplex_test.go0000644061062106075000000000444713172163402025662 0ustar stgraberdomain admins// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package httplex import ( "testing" ) func isChar(c rune) bool { return c <= 127 } func isCtl(c rune) bool { return c <= 31 || c == 127 } func isSeparator(c rune) bool { switch c { case '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' ', '\t': return true } return false } func TestIsToken(t *testing.T) { for i := 0; i <= 130; i++ { r := rune(i) expected := isChar(r) && !isCtl(r) && !isSeparator(r) if IsTokenRune(r) != expected { t.Errorf("isToken(0x%x) = %v", r, !expected) } } } func TestHeaderValuesContainsToken(t *testing.T) { tests := []struct { vals []string token string want bool }{ { vals: []string{"foo"}, token: "foo", want: true, }, { vals: []string{"bar", "foo"}, token: "foo", want: true, }, { vals: []string{"foo"}, token: "FOO", want: true, }, { vals: []string{"foo"}, token: "bar", want: false, }, { vals: []string{" foo "}, token: "FOO", want: true, }, { vals: []string{"foo,bar"}, token: "FOO", want: true, }, { vals: []string{"bar,foo,bar"}, token: "FOO", want: true, }, { vals: []string{"bar , foo"}, token: "FOO", want: true, }, { vals: []string{"foo ,bar "}, token: "FOO", want: true, }, { vals: []string{"bar, foo ,bar"}, token: "FOO", want: true, }, { vals: []string{"bar , foo"}, token: "FOO", want: true, }, } for _, tt := range tests { got := HeaderValuesContainsToken(tt.vals, tt.token) if got != tt.want { t.Errorf("headerValuesContainsToken(%q, %q) = %v; want %v", tt.vals, tt.token, got, tt.want) } } } func TestPunycodeHostPort(t *testing.T) { tests := []struct { in, want string }{ {"www.google.com", "www.google.com"}, {"гофер.рф", "xn--c1ae0ajs.xn--p1ai"}, {"bücher.de", "xn--bcher-kva.de"}, {"bücher.de:8080", "xn--bcher-kva.de:8080"}, {"[1::6]:8080", "[1::6]:8080"}, } for _, tt := range tests { got, err := PunycodeHostPort(tt.in) if tt.want != got || err != nil { t.Errorf("PunycodeHostPort(%q) = %q, %v, want %q, nil", tt.in, got, err, tt.want) } } } lxd-2.0.11/dist/src/golang.org/x/net/lex/httplex/httplex.go0000644061062106075000000002211713172163402024615 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package httplex contains rules around lexical matters of various // HTTP-related specifications. // // This package is shared by the standard library (which vendors it) // and x/net/http2. It comes with no API stability promise. package httplex import ( "net" "strings" "unicode/utf8" "golang.org/x/net/idna" ) var isTokenTable = [127]bool{ '!': true, '#': true, '$': true, '%': true, '&': true, '\'': true, '*': true, '+': true, '-': true, '.': true, '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'W': true, 'V': true, 'X': true, 'Y': true, 'Z': true, '^': true, '_': true, '`': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, 'y': true, 'z': true, '|': true, '~': true, } func IsTokenRune(r rune) bool { i := int(r) return i < len(isTokenTable) && isTokenTable[i] } func isNotToken(r rune) bool { return !IsTokenRune(r) } // HeaderValuesContainsToken reports whether any string in values // contains the provided token, ASCII case-insensitively. func HeaderValuesContainsToken(values []string, token string) bool { for _, v := range values { if headerValueContainsToken(v, token) { return true } } return false } // isOWS reports whether b is an optional whitespace byte, as defined // by RFC 7230 section 3.2.3. func isOWS(b byte) bool { return b == ' ' || b == '\t' } // trimOWS returns x with all optional whitespace removes from the // beginning and end. func trimOWS(x string) string { // TODO: consider using strings.Trim(x, " \t") instead, // if and when it's fast enough. See issue 10292. // But this ASCII-only code will probably always beat UTF-8 // aware code. for len(x) > 0 && isOWS(x[0]) { x = x[1:] } for len(x) > 0 && isOWS(x[len(x)-1]) { x = x[:len(x)-1] } return x } // headerValueContainsToken reports whether v (assumed to be a // 0#element, in the ABNF extension described in RFC 7230 section 7) // contains token amongst its comma-separated tokens, ASCII // case-insensitively. func headerValueContainsToken(v string, token string) bool { v = trimOWS(v) if comma := strings.IndexByte(v, ','); comma != -1 { return tokenEqual(trimOWS(v[:comma]), token) || headerValueContainsToken(v[comma+1:], token) } return tokenEqual(v, token) } // lowerASCII returns the ASCII lowercase version of b. func lowerASCII(b byte) byte { if 'A' <= b && b <= 'Z' { return b + ('a' - 'A') } return b } // tokenEqual reports whether t1 and t2 are equal, ASCII case-insensitively. func tokenEqual(t1, t2 string) bool { if len(t1) != len(t2) { return false } for i, b := range t1 { if b >= utf8.RuneSelf { // No UTF-8 or non-ASCII allowed in tokens. return false } if lowerASCII(byte(b)) != lowerASCII(t2[i]) { return false } } return true } // isLWS reports whether b is linear white space, according // to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 // LWS = [CRLF] 1*( SP | HT ) func isLWS(b byte) bool { return b == ' ' || b == '\t' } // isCTL reports whether b is a control byte, according // to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 // CTL = func isCTL(b byte) bool { const del = 0x7f // a CTL return b < ' ' || b == del } // ValidHeaderFieldName reports whether v is a valid HTTP/1.x header name. // HTTP/2 imposes the additional restriction that uppercase ASCII // letters are not allowed. // // RFC 7230 says: // header-field = field-name ":" OWS field-value OWS // field-name = token // token = 1*tchar // tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / // "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA func ValidHeaderFieldName(v string) bool { if len(v) == 0 { return false } for _, r := range v { if !IsTokenRune(r) { return false } } return true } // ValidHostHeader reports whether h is a valid host header. func ValidHostHeader(h string) bool { // The latest spec is actually this: // // http://tools.ietf.org/html/rfc7230#section-5.4 // Host = uri-host [ ":" port ] // // Where uri-host is: // http://tools.ietf.org/html/rfc3986#section-3.2.2 // // But we're going to be much more lenient for now and just // search for any byte that's not a valid byte in any of those // expressions. for i := 0; i < len(h); i++ { if !validHostByte[h[i]] { return false } } return true } // See the validHostHeader comment. var validHostByte = [256]bool{ '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, 'y': true, 'z': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, 'Y': true, 'Z': true, '!': true, // sub-delims '$': true, // sub-delims '%': true, // pct-encoded (and used in IPv6 zones) '&': true, // sub-delims '(': true, // sub-delims ')': true, // sub-delims '*': true, // sub-delims '+': true, // sub-delims ',': true, // sub-delims '-': true, // unreserved '.': true, // unreserved ':': true, // IPv6address + Host expression's optional port ';': true, // sub-delims '=': true, // sub-delims '[': true, '\'': true, // sub-delims ']': true, '_': true, // unreserved '~': true, // unreserved } // ValidHeaderFieldValue reports whether v is a valid "field-value" according to // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 : // // message-header = field-name ":" [ field-value ] // field-value = *( field-content | LWS ) // field-content = // // http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 : // // TEXT = // LWS = [CRLF] 1*( SP | HT ) // CTL = // // RFC 7230 says: // field-value = *( field-content / obs-fold ) // obj-fold = N/A to http2, and deprecated // field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] // field-vchar = VCHAR / obs-text // obs-text = %x80-FF // VCHAR = "any visible [USASCII] character" // // http2 further says: "Similarly, HTTP/2 allows header field values // that are not valid. While most of the values that can be encoded // will not alter header field parsing, carriage return (CR, ASCII // 0xd), line feed (LF, ASCII 0xa), and the zero character (NUL, ASCII // 0x0) might be exploited by an attacker if they are translated // verbatim. Any request or response that contains a character not // permitted in a header field value MUST be treated as malformed // (Section 8.1.2.6). Valid characters are defined by the // field-content ABNF rule in Section 3.2 of [RFC7230]." // // This function does not (yet?) properly handle the rejection of // strings that begin or end with SP or HTAB. func ValidHeaderFieldValue(v string) bool { for i := 0; i < len(v); i++ { b := v[i] if isCTL(b) && !isLWS(b) { return false } } return true } func isASCII(s string) bool { for i := 0; i < len(s); i++ { if s[i] >= utf8.RuneSelf { return false } } return true } // PunycodeHostPort returns the IDNA Punycode version // of the provided "host" or "host:port" string. func PunycodeHostPort(v string) (string, error) { if isASCII(v) { return v, nil } host, port, err := net.SplitHostPort(v) if err != nil { // The input 'v' argument was just a "host" argument, // without a port. This error should not be returned // to the caller. host = v port = "" } host, err = idna.ToASCII(host) if err != nil { // Non-UTF-8? Not representable in Punycode, in any // case. return "", err } if port == "" { return host, nil } return net.JoinHostPort(host, port), nil } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/0000755061062106075000000000000013172163402021177 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_solaris.go0000644061062106075000000000523613172163402024300 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_solaris.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x5 sysIPV6_MULTICAST_IF = 0x6 sysIPV6_MULTICAST_HOPS = 0x7 sysIPV6_MULTICAST_LOOP = 0x8 sysIPV6_JOIN_GROUP = 0x9 sysIPV6_LEAVE_GROUP = 0xa sysIPV6_PKTINFO = 0xb sysIPV6_HOPLIMIT = 0xc sysIPV6_NEXTHOP = 0xd sysIPV6_HOPOPTS = 0xe sysIPV6_DSTOPTS = 0xf sysIPV6_RTHDR = 0x10 sysIPV6_RTHDRDSTOPTS = 0x11 sysIPV6_RECVPKTINFO = 0x12 sysIPV6_RECVHOPLIMIT = 0x13 sysIPV6_RECVHOPOPTS = 0x14 sysIPV6_RECVRTHDR = 0x16 sysIPV6_RECVRTHDRDSTOPTS = 0x17 sysIPV6_CHECKSUM = 0x18 sysIPV6_RECVTCLASS = 0x19 sysIPV6_USE_MIN_MTU = 0x20 sysIPV6_DONTFRAG = 0x21 sysIPV6_SEC_OPT = 0x22 sysIPV6_SRC_PREFERENCES = 0x23 sysIPV6_RECVPATHMTU = 0x24 sysIPV6_PATHMTU = 0x25 sysIPV6_TCLASS = 0x26 sysIPV6_V6ONLY = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysMCAST_JOIN_GROUP = 0x29 sysMCAST_LEAVE_GROUP = 0x2a sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_JOIN_SOURCE_GROUP = 0x2d sysMCAST_LEAVE_SOURCE_GROUP = 0x2e sysIPV6_PREFER_SRC_HOME = 0x1 sysIPV6_PREFER_SRC_COA = 0x2 sysIPV6_PREFER_SRC_PUBLIC = 0x4 sysIPV6_PREFER_SRC_TMP = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x10 sysIPV6_PREFER_SRC_CGA = 0x20 sysIPV6_PREFER_SRC_MIPMASK = 0x3 sysIPV6_PREFER_SRC_MIPDEFAULT = 0x1 sysIPV6_PREFER_SRC_TMPMASK = 0xc sysIPV6_PREFER_SRC_TMPDEFAULT = 0x4 sysIPV6_PREFER_SRC_CGAMASK = 0x30 sysIPV6_PREFER_SRC_CGADEFAULT = 0x10 sysIPV6_PREFER_SRC_MASK = 0x3f sysIPV6_PREFER_SRC_DEFAULT = 0x15 sysIPV6_BOUND_IF = 0x41 sysIPV6_UNSPEC_SRC = 0x42 sysICMP6_FILTER = 0x1 sizeofSockaddrStorage = 0x100 sizeofSockaddrInet6 = 0x20 sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x24 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x104 sizeofGroupSourceReq = 0x204 sizeofICMPv6Filter = 0x20 ) type sockaddrStorage struct { Family uint16 X_ss_pad1 [6]int8 X_ss_align float64 X_ss_pad2 [240]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 X__sin6_src_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [256]byte } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [256]byte Pad_cgo_1 [256]byte } type icmpv6Filter struct { X__icmp6_filt [8]uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_openbsd.go0000644061062106075000000000336613172163402024260 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_AUTH_LEVEL = 0x35 sysIPV6_ESP_TRANS_LEVEL = 0x36 sysIPV6_ESP_NETWORK_LEVEL = 0x37 sysIPSEC6_OUTSA = 0x38 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_IPCOMP_LEVEL = 0x3c sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PIPEX = 0x3f sysIPV6_RTABLE = 0x1021 sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6Mreq = 0x14 sizeofICMPv6Filter = 0x20 ) type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type icmpv6Filter struct { Filt [8]uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_netbsd.go0000644061062106075000000000302713172163402024077 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_netbsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6Mreq = 0x14 sizeofICMPv6Filter = 0x20 ) type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type icmpv6Filter struct { Filt [8]uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_s390x.go0000644061062106075000000000733013172163402024726 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_ppc64le.go0000644061062106075000000000733013172163402025315 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_ppc64.go0000644061062106075000000000733013172163402024774 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_ppc.go0000644061062106075000000000726213172163402024626 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_mipsle.go0000644061062106075000000000726113172163402025334 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_mips64le.go0000644061062106075000000000733013172163402025503 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_mips64.go0000644061062106075000000000733013172163402025162 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_mips.go0000644061062106075000000000726113172163402025013 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_arm64.go0000644061062106075000000000733013172163402024771 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_arm.go0000644061062106075000000000726113172163402024622 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_amd64.go0000644061062106075000000000733013172163402024753 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_linux_386.go0000644061062106075000000000726113172163402024363 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6FlowlabelReq = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPv6Filter = 0x20 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpv6Filter struct { Data [8]uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_freebsd_arm.go0000644061062106075000000000444113172163402025072 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_BINDANY = 0x40 sysIPV6_MSFILTER = 0x4a sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sockaddrStorage Source sockaddrStorage } type icmpv6Filter struct { Filt [8]uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_freebsd_amd64.go0000644061062106075000000000444113172163402025226 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_BINDANY = 0x40 sysIPV6_MSFILTER = 0x4a sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPv6Filter = 0x20 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sockaddrStorage Source sockaddrStorage } type icmpv6Filter struct { Filt [8]uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_freebsd_386.go0000644061062106075000000000437313172163402024637 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_BINDANY = 0x40 sysIPV6_MSFILTER = 0x4a sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPv6Filter = 0x20 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type groupReq struct { Interface uint32 Group sockaddrStorage } type groupSourceReq struct { Interface uint32 Group sockaddrStorage Source sockaddrStorage } type icmpv6Filter struct { Filt [8]uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_dragonfly.go0000644061062106075000000000312613172163402024605 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_dragonfly.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6Mreq = 0x14 sizeofICMPv6Filter = 0x20 ) type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type icmpv6Filter struct { Filt [8]uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/zsys_darwin.go0000644061062106075000000000470013172163402024103 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_darwin.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_2292PKTINFO = 0x13 sysIPV6_2292HOPLIMIT = 0x14 sysIPV6_2292NEXTHOP = 0x15 sysIPV6_2292HOPOPTS = 0x16 sysIPV6_2292DSTOPTS = 0x17 sysIPV6_2292RTHDR = 0x18 sysIPV6_2292PKTOPTIONS = 0x19 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RECVTCLASS = 0x23 sysIPV6_TCLASS = 0x24 sysIPV6_RTHDRDSTOPTS = 0x39 sysIPV6_RECVPKTINFO = 0x3d sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_MSFILTER = 0x4a sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysIPV6_BOUND_IF = 0x7d sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPv6Filter = 0x20 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type icmpv6Filter struct { Filt [8]uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [128]byte } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [128]byte Pad_cgo_1 [128]byte } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/unicastsockopt_test.go0000644061062106075000000000471613172163402025646 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) func TestConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ln, err := net.Listen("tcp6", "[::1]:0") if err != nil { t.Fatal(err) } defer ln.Close() errc := make(chan error, 1) go func() { c, err := ln.Accept() if err != nil { errc <- err return } errc <- c.Close() }() c, err := net.Dial("tcp6", ln.Addr().String()) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv6.NewConn(c)) if err := <-errc; err != nil { t.Errorf("server: %v", err) } } var packetConnUnicastSocketOptionTests = []struct { net, proto, addr string }{ {"udp6", "", "[::1]:0"}, {"ip6", ":ipv6-icmp", "::1"}, } func TestPacketConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnUnicastSocketOptionTests { if tt.net == "ip6" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv6.NewPacketConn(c)) } } type testIPv6UnicastConn interface { TrafficClass() (int, error) SetTrafficClass(int) error HopLimit() (int, error) SetHopLimit(int) error } func testUnicastSocketOptions(t *testing.T, c testIPv6UnicastConn) { tclass := iana.DiffServCS0 | iana.NotECNTransport if err := c.SetTrafficClass(tclass); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels don't support IPV6_TCLASS option t.Logf("not supported on %s", runtime.GOOS) goto next } t.Fatal(err) } if v, err := c.TrafficClass(); err != nil { t.Fatal(err) } else if v != tclass { t.Fatalf("got %v; want %v", v, tclass) } next: hoplim := 255 if err := c.SetHopLimit(hoplim); err != nil { t.Fatal(err) } if v, err := c.HopLimit(); err != nil { t.Fatal(err) } else if v != hoplim { t.Fatalf("got %v; want %v", v, hoplim) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/unicast_test.go0000644061062106075000000001132513172163402024235 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "bytes" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) func TestPacketConnReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } c, err := nettest.NewLocalPacketListener("udp6") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() dst := c.LocalAddr() cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) if ifi != nil { cm.IfIndex = ifi.Index } wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } cm.HopLimit = i + 1 if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, _, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; want %v", rb[:n], wb) } } } func TestPacketConnReadWriteUnicastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip6:ipv6-icmp", "::1") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() dst, err := net.ResolveIPAddr("ip6", "::1") if err != nil { t.Fatal(err) } pshicmp := icmp.IPv6PseudoHeader(c.LocalAddr().(*net.IPAddr).IP, dst.IP) cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) if ifi != nil { cm.IfIndex = ifi.Index } var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } var psh []byte for i, toggle := range []bool{true, false, true} { if toggle { psh = nil if err := p.SetChecksum(true, 2); err != nil { // Solaris never allows to modify // ICMP properties. if runtime.GOOS != "solaris" { t.Fatal(err) } } } else { psh = pshicmp // Some platforms never allow to disable the // kernel checksum processing. p.SetChecksum(false, -1) } wb, err := (&icmp.Message{ Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(psh) if err != nil { t.Fatal(err) } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } cm.HopLimit = i + 1 if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, _, _, err := p.ReadFrom(rb); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels have some limitation on receiving icmp packet through raw socket t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } else { if m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, rb[:n]); err != nil { t.Fatal(err) } else if m.Type != ipv6.ICMPTypeEchoReply || m.Code != 0 { t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv6.ICMPTypeEchoReply, 0) } } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_windows.go0000644061062106075000000000367413172163402024130 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "net" "syscall" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) const ( // See ws2tcpip.h. sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PKTINFO = 0x13 sizeofSockaddrInet6 = 0x1c sizeofIPv6Mreq = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofICMPv6Filter = 0 ) type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type icmpv6Filter struct { // TODO(mikio): implement this } var ( ctlOpts = [ctlMax]ctlOpt{} sockOpts = map[int]*sockOpt{ ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_JOIN_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_LEAVE_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, } ) func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (mreq *ipv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_stub.go0000644061062106075000000000050313172163402023377 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package ipv6 var ( ctlOpts = [ctlMax]ctlOpt{} sockOpts = map[int]*sockOpt{} ) lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_ssmreq_stub.go0000644061062106075000000000077613172163402025005 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!freebsd,!linux,!solaris package ipv6 import ( "net" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setGroupReq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } func (so *sockOpt) setGroupSourceReq(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_ssmreq.go0000644061062106075000000000236113172163402023740 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin freebsd linux solaris package ipv6 import ( "net" "unsafe" "golang.org/x/net/internal/socket" ) var freebsd32o64 bool func (so *sockOpt) setGroupReq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { var gr groupReq if ifi != nil { gr.Interface = uint32(ifi.Index) } gr.setGroup(grp) var b []byte if freebsd32o64 { var d [sizeofGroupReq + 4]byte s := (*[sizeofGroupReq]byte)(unsafe.Pointer(&gr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) b = d[:] } else { b = (*[sizeofGroupReq]byte)(unsafe.Pointer(&gr))[:sizeofGroupReq] } return so.Set(c, b) } func (so *sockOpt) setGroupSourceReq(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { var gsr groupSourceReq if ifi != nil { gsr.Interface = uint32(ifi.Index) } gsr.setSourceGroup(grp, src) var b []byte if freebsd32o64 { var d [sizeofGroupSourceReq + 4]byte s := (*[sizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) b = d[:] } else { b = (*[sizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr))[:sizeofGroupSourceReq] } return so.Set(c, b) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_solaris.go0000644061062106075000000000744613172163402024113 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, ctlNextHop: {sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop}, ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, } sockOpts = map[int]*sockOpt{ ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}}, ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}}, ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}}, ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}}, ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}}, ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}}, ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}}, ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, } ) func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *inet6Pktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (mreq *ipv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gr)) + 4)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 4)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) sa = (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 260)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], src) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_linux.go0000644061062106075000000000740513172163402023571 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, } sockOpts = map[int]*sockOpt{ ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}}, ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}}, ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}}, ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}}, ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}}, ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}}, ssoChecksum: {Option: socket.Option{Level: iana.ProtocolReserved, Name: sysIPV6_CHECKSUM, Len: 4}}, ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMPV6_FILTER, Len: sizeofICMPv6Filter}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoAttachFilter: {Option: socket.Option{Level: sysSOL_SOCKET, Name: sysSO_ATTACH_FILTER, Len: sizeofSockFprog}}, } ) func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *inet6Pktinfo) setIfindex(i int) { pi.Ifindex = int32(i) } func (mreq *ipv6Mreq) setIfindex(i int) { mreq.Ifindex = int32(i) } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet6)(unsafe.Pointer(&gr.Group)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet6)(unsafe.Pointer(&gsr.Group)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) sa = (*sockaddrInet6)(unsafe.Pointer(&gsr.Source)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], src) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_freebsd.go0000644061062106075000000001014013172163402024032 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "net" "runtime" "strings" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, ctlNextHop: {sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop}, ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, } sockOpts = map[int]sockOpt{ ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}}, ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}}, ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}}, ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}}, ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}}, ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}}, ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}}, ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, } ) func init() { if runtime.GOOS == "freebsd" && runtime.GOARCH == "386" { archs, _ := syscall.Sysctl("kern.supported_archs") for _, s := range strings.Fields(archs) { if s == "amd64" { freebsd32o64 = true break } } } } func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *inet6Pktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (mreq *ipv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet6)(unsafe.Pointer(&gr.Group)) sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet6)(unsafe.Pointer(&gsr.Group)) sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) sa = (*sockaddrInet6)(unsafe.Pointer(&gsr.Source)) sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], src) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_darwin.go0000644061062106075000000001250613172163402023714 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "net" "strconv" "strings" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlHopLimit: {sysIPV6_2292HOPLIMIT, 4, marshal2292HopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_2292PKTINFO, sizeofInet6Pktinfo, marshal2292PacketInfo, parsePacketInfo}, } sockOpts = map[int]*sockOpt{ ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_2292HOPLIMIT, Len: 4}}, ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_2292PKTINFO, Len: 4}}, ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}}, ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_JOIN_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_LEAVE_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, } ) func init() { // Seems like kern.osreldate is veiled on latest OS X. We use // kern.osrelease instead. s, err := syscall.Sysctl("kern.osrelease") if err != nil { return } ss := strings.Split(s, ".") if len(ss) == 0 { return } // The IP_PKTINFO and protocol-independent multicast API were // introduced in OS X 10.7 (Darwin 11). But it looks like // those features require OS X 10.8 (Darwin 12) or above. // See http://support.apple.com/kb/HT1633. if mjver, err := strconv.Atoi(ss[0]); err != nil || mjver < 12 { return } ctlOpts[ctlTrafficClass] = ctlOpt{sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass} ctlOpts[ctlHopLimit] = ctlOpt{sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit} ctlOpts[ctlPacketInfo] = ctlOpt{sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo} ctlOpts[ctlNextHop] = ctlOpt{sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop} ctlOpts[ctlPathMTU] = ctlOpt{sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU} sockOpts[ssoTrafficClass] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}} sockOpts[ssoReceiveTrafficClass] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}} sockOpts[ssoReceiveHopLimit] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}} sockOpts[ssoReceivePacketInfo] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}} sockOpts[ssoReceivePathMTU] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}} sockOpts[ssoPathMTU] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}} sockOpts[ssoJoinGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq} sockOpts[ssoLeaveGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq} sockOpts[ssoJoinSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} sockOpts[ssoLeaveSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} sockOpts[ssoBlockSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} sockOpts[ssoUnblockSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} } func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *inet6Pktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (mreq *ipv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gr)) + 4)) sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 4)) sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) sa = (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 132)) sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], src) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_bsd.go0000644061062106075000000000533413172163402023201 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build dragonfly netbsd openbsd package ipv6 import ( "net" "syscall" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, ctlNextHop: {sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop}, ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, } sockOpts = map[int]*sockOpt{ ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}}, ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}}, ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}}, ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}}, ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}}, ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}}, ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}}, ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_JOIN_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_LEAVE_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, } ) func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Len = sizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *inet6Pktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (mreq *ipv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_bpf_stub.go0000644061062106075000000000056413172163402024235 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !linux package ipv6 import ( "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setAttachFilter(c *socket.Conn, f []bpf.RawInstruction) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_bpf.go0000644061062106075000000000104513172163402023173 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux package ipv6 import ( "unsafe" "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setAttachFilter(c *socket.Conn, f []bpf.RawInstruction) error { prog := sockFProg{ Len: uint16(len(f)), Filter: (*sockFilter)(unsafe.Pointer(&f[0])), } b := (*[sizeofSockFprog]byte)(unsafe.Pointer(&prog))[:sizeofSockFprog] return so.Set(c, b) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_asmreq_stub.go0000644061062106075000000000064513172163402024756 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package ipv6 import ( "net" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setIPMreq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sys_asmreq.go0000644061062106075000000000111513172163402023712 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package ipv6 import ( "net" "unsafe" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setIPMreq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { var mreq ipv6Mreq copy(mreq.Multiaddr[:], grp) if ifi != nil { mreq.setIfindex(ifi.Index) } b := (*[sizeofIPv6Mreq]byte)(unsafe.Pointer(&mreq))[:sizeofIPv6Mreq] return so.Set(c, b) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sockopt_test.go0000644061062106075000000000560513172163402024255 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "fmt" "net" "runtime" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var supportsIPv6 bool = nettest.SupportsIPv6() func TestConnInitiatorPathMTU(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ln, err := net.Listen("tcp6", "[::1]:0") if err != nil { t.Fatal(err) } defer ln.Close() done := make(chan bool) go acceptor(t, ln, done) c, err := net.Dial("tcp6", ln.Addr().String()) if err != nil { t.Fatal(err) } defer c.Close() if pmtu, err := ipv6.NewConn(c).PathMTU(); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels don't support IPV6_PATHMTU option t.Logf("not supported on %s", runtime.GOOS) default: t.Fatal(err) } } else { t.Logf("path mtu for %v: %v", c.RemoteAddr(), pmtu) } <-done } func TestConnResponderPathMTU(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ln, err := net.Listen("tcp6", "[::1]:0") if err != nil { t.Fatal(err) } defer ln.Close() done := make(chan bool) go connector(t, "tcp6", ln.Addr().String(), done) c, err := ln.Accept() if err != nil { t.Fatal(err) } defer c.Close() if pmtu, err := ipv6.NewConn(c).PathMTU(); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels don't support IPV6_PATHMTU option t.Logf("not supported on %s", runtime.GOOS) default: t.Fatal(err) } } else { t.Logf("path mtu for %v: %v", c.RemoteAddr(), pmtu) } <-done } func TestPacketConnChecksum(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket(fmt.Sprintf("ip6:%d", iana.ProtocolOSPFIGP), "::") // OSPF for IPv6 if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) offset := 12 // see RFC 5340 for _, toggle := range []bool{false, true} { if err := p.SetChecksum(toggle, offset); err != nil { if toggle { t.Fatalf("ipv6.PacketConn.SetChecksum(%v, %v) failed: %v", toggle, offset, err) } else { // Some platforms never allow to disable the kernel // checksum processing. t.Logf("ipv6.PacketConn.SetChecksum(%v, %v) failed: %v", toggle, offset, err) } } if on, offset, err := p.Checksum(); err != nil { t.Fatal(err) } else { t.Logf("kernel checksum processing enabled=%v, offset=%v", on, offset) } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sockopt_stub.go0000644061062106075000000000226213172163402024247 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package ipv6 import ( "net" "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) getMulticastInterface(c *socket.Conn) (*net.Interface, error) { return nil, errOpNoSupport } func (so *sockOpt) setMulticastInterface(c *socket.Conn, ifi *net.Interface) error { return errOpNoSupport } func (so *sockOpt) getICMPFilter(c *socket.Conn) (*ICMPFilter, error) { return nil, errOpNoSupport } func (so *sockOpt) setICMPFilter(c *socket.Conn, f *ICMPFilter) error { return errOpNoSupport } func (so *sockOpt) getMTUInfo(c *socket.Conn) (*net.Interface, int, error) { return nil, 0, errOpNoSupport } func (so *sockOpt) setGroup(c *socket.Conn, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } func (so *sockOpt) setSourceGroup(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { return errOpNoSupport } func (so *sockOpt) setBPF(c *socket.Conn, f []bpf.RawInstruction) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sockopt_posix.go0000644061062106075000000000407013172163402024433 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package ipv6 import ( "net" "unsafe" "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) getMulticastInterface(c *socket.Conn) (*net.Interface, error) { n, err := so.GetInt(c) if err != nil { return nil, err } return net.InterfaceByIndex(n) } func (so *sockOpt) setMulticastInterface(c *socket.Conn, ifi *net.Interface) error { var n int if ifi != nil { n = ifi.Index } return so.SetInt(c, n) } func (so *sockOpt) getICMPFilter(c *socket.Conn) (*ICMPFilter, error) { b := make([]byte, so.Len) n, err := so.Get(c, b) if err != nil { return nil, err } if n != sizeofICMPv6Filter { return nil, errOpNoSupport } return (*ICMPFilter)(unsafe.Pointer(&b[0])), nil } func (so *sockOpt) setICMPFilter(c *socket.Conn, f *ICMPFilter) error { b := (*[sizeofICMPv6Filter]byte)(unsafe.Pointer(f))[:sizeofICMPv6Filter] return so.Set(c, b) } func (so *sockOpt) getMTUInfo(c *socket.Conn) (*net.Interface, int, error) { b := make([]byte, so.Len) n, err := so.Get(c, b) if err != nil { return nil, 0, err } if n != sizeofIPv6Mtuinfo { return nil, 0, errOpNoSupport } mi := (*ipv6Mtuinfo)(unsafe.Pointer(&b[0])) if mi.Addr.Scope_id == 0 { return nil, int(mi.Mtu), nil } ifi, err := net.InterfaceByIndex(int(mi.Addr.Scope_id)) if err != nil { return nil, 0, err } return ifi, int(mi.Mtu), nil } func (so *sockOpt) setGroup(c *socket.Conn, ifi *net.Interface, grp net.IP) error { switch so.typ { case ssoTypeIPMreq: return so.setIPMreq(c, ifi, grp) case ssoTypeGroupReq: return so.setGroupReq(c, ifi, grp) default: return errOpNoSupport } } func (so *sockOpt) setSourceGroup(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { return so.setGroupSourceReq(c, ifi, grp, src) } func (so *sockOpt) setBPF(c *socket.Conn, f []bpf.RawInstruction) error { return so.setAttachFilter(c, f) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/sockopt.go0000644061062106075000000000350213172163402023210 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import "golang.org/x/net/internal/socket" // Sticky socket options const ( ssoTrafficClass = iota // header field for unicast packet, RFC 3542 ssoHopLimit // header field for unicast packet, RFC 3493 ssoMulticastInterface // outbound interface for multicast packet, RFC 3493 ssoMulticastHopLimit // header field for multicast packet, RFC 3493 ssoMulticastLoopback // loopback for multicast packet, RFC 3493 ssoReceiveTrafficClass // header field on received packet, RFC 3542 ssoReceiveHopLimit // header field on received packet, RFC 2292 or 3542 ssoReceivePacketInfo // incbound or outbound packet path, RFC 2292 or 3542 ssoReceivePathMTU // path mtu, RFC 3542 ssoPathMTU // path mtu, RFC 3542 ssoChecksum // packet checksum, RFC 2292 or 3542 ssoICMPFilter // icmp filter, RFC 2292 or 3542 ssoJoinGroup // any-source multicast, RFC 3493 ssoLeaveGroup // any-source multicast, RFC 3493 ssoJoinSourceGroup // source-specific multicast ssoLeaveSourceGroup // source-specific multicast ssoBlockSourceGroup // any-source or source-specific multicast ssoUnblockSourceGroup // any-source or source-specific multicast ssoAttachFilter // attach BPF for filtering inbound traffic ) // Sticky socket option value types const ( ssoTypeIPMreq = iota + 1 ssoTypeGroupReq ssoTypeGroupSourceReq ) // A sockOpt represents a binding for sticky socket option. type sockOpt struct { socket.Option typ int // hint for option value type; optional } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/readwrite_test.go0000644061062106075000000000654013172163402024560 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "bytes" "net" "runtime" "strings" "sync" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) func BenchmarkReadWriteUnicast(b *testing.B) { c, err := nettest.NewLocalPacketListener("udp6") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() dst := c.LocalAddr() wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) b.Run("NetUDP", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(wb, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(rb); err != nil { b.Fatal(err) } } }) b.Run("IPv6UDP", func(b *testing.B) { p := ipv6.NewPacketConn(c) cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, HopLimit: 1, } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) if ifi != nil { cm.IfIndex = ifi.Index } for i := 0; i < b.N; i++ { if _, err := p.WriteTo(wb, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(rb); err != nil { b.Fatal(err) } } }) } func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } c, err := nettest.NewLocalPacketListener("udp6") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() dst := c.LocalAddr() ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU wb := []byte("HELLO-R-U-THERE") if err := p.SetControlMessage(cf, true); err != nil { // probe before test if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } var wg sync.WaitGroup reader := func() { defer wg.Done() rb := make([]byte, 128) if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Error(err) return } else if !bytes.Equal(rb[:n], wb) { t.Errorf("got %v; want %v", rb[:n], wb) return } else { s := cm.String() if strings.Contains(s, ",") { t.Errorf("should be space-separated values: %s", s) } } } writer := func(toggle bool) { defer wg.Done() cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Error(err) return } else if n != len(wb) { t.Errorf("got %d; want %d", n, len(wb)) return } } const N = 10 wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Add(2 * N) for i := 0; i < 2*N; i++ { go writer(i%2 != 0) } wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Wait() } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/readwrite_go1_9_test.go0000644061062106075000000002146313172163402025557 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package ipv6_test import ( "bytes" "fmt" "net" "runtime" "strings" "sync" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) func BenchmarkPacketConnReadWriteUnicast(b *testing.B) { switch runtime.GOOS { case "nacl", "plan9", "windows": b.Skipf("not supported on %s", runtime.GOOS) } payload := []byte("HELLO-R-U-THERE") iph := []byte{ 0x69, 0x8b, 0xee, 0xf1, 0xca, 0xfe, 0xff, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, } greh := []byte{0x00, 0x00, 0x86, 0xdd, 0x00, 0x00, 0x00, 0x00} datagram := append(greh, append(iph, payload...)...) bb := make([]byte, 128) cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, HopLimit: 1, Src: net.IPv6loopback, } if ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback); ifi != nil { cm.IfIndex = ifi.Index } b.Run("UDP", func(b *testing.B) { c, err := nettest.NewLocalPacketListener("udp6") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv6.NewPacketConn(c) dst := c.LocalAddr() cf := ipv6.FlagHopLimit | ipv6.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } wms := []ipv6.Message{ { Buffers: [][]byte{payload}, Addr: dst, OOB: cm.Marshal(), }, } rms := []ipv6.Message{ { Buffers: [][]byte{bb}, OOB: ipv6.NewControlMessage(cf), }, } b.Run("Net", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(payload, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("ToFrom", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteTo(payload, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("Batch", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteBatch(wms, 0); err != nil { b.Fatal(err) } if _, err := p.ReadBatch(rms, 0); err != nil { b.Fatal(err) } } }) }) b.Run("IP", func(b *testing.B) { switch runtime.GOOS { case "netbsd": b.Skip("need to configure gre on netbsd") case "openbsd": b.Skip("net.inet.gre.allow=0 by default on openbsd") } c, err := net.ListenPacket(fmt.Sprintf("ip6:%d", iana.ProtocolGRE), "::1") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv6.NewPacketConn(c) dst := c.LocalAddr() cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } wms := []ipv6.Message{ { Buffers: [][]byte{datagram}, Addr: dst, OOB: cm.Marshal(), }, } rms := []ipv6.Message{ { Buffers: [][]byte{bb}, OOB: ipv6.NewControlMessage(cf), }, } b.Run("Net", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(datagram, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("ToFrom", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteTo(datagram, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("Batch", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteBatch(wms, 0); err != nil { b.Fatal(err) } if _, err := p.ReadBatch(rms, 0); err != nil { b.Fatal(err) } } }) }) } func TestPacketConnConcurrentReadWriteUnicast(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } payload := []byte("HELLO-R-U-THERE") iph := []byte{ 0x69, 0x8b, 0xee, 0xf1, 0xca, 0xfe, 0xff, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, } greh := []byte{0x00, 0x00, 0x86, 0xdd, 0x00, 0x00, 0x00, 0x00} datagram := append(greh, append(iph, payload...)...) t.Run("UDP", func(t *testing.T) { c, err := nettest.NewLocalPacketListener("udp6") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv6.NewPacketConn(c) t.Run("ToFrom", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, payload, c.LocalAddr(), false) }) t.Run("Batch", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, payload, c.LocalAddr(), true) }) }) t.Run("IP", func(t *testing.T) { switch runtime.GOOS { case "netbsd": t.Skip("need to configure gre on netbsd") case "openbsd": t.Skip("net.inet.gre.allow=0 by default on openbsd") } c, err := net.ListenPacket(fmt.Sprintf("ip6:%d", iana.ProtocolGRE), "::1") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv6.NewPacketConn(c) t.Run("ToFrom", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, datagram, c.LocalAddr(), false) }) t.Run("Batch", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, datagram, c.LocalAddr(), true) }) }) } func testPacketConnConcurrentReadWriteUnicast(t *testing.T, p *ipv6.PacketConn, data []byte, dst net.Addr, batch bool) { ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU if err := p.SetControlMessage(cf, true); err != nil { // probe before test if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } var wg sync.WaitGroup reader := func() { defer wg.Done() b := make([]byte, 128) n, cm, _, err := p.ReadFrom(b) if err != nil { t.Error(err) return } if !bytes.Equal(b[:n], data) { t.Errorf("got %#v; want %#v", b[:n], data) return } s := cm.String() if strings.Contains(s, ",") { t.Errorf("should be space-separated values: %s", s) return } } batchReader := func() { defer wg.Done() ms := []ipv6.Message{ { Buffers: [][]byte{make([]byte, 128)}, OOB: ipv6.NewControlMessage(cf), }, } n, err := p.ReadBatch(ms, 0) if err != nil { t.Error(err) return } if n != len(ms) { t.Errorf("got %d; want %d", n, len(ms)) return } var cm ipv6.ControlMessage if err := cm.Parse(ms[0].OOB[:ms[0].NN]); err != nil { t.Error(err) return } b := ms[0].Buffers[0][:ms[0].N] if !bytes.Equal(b, data) { t.Errorf("got %#v; want %#v", b, data) return } s := cm.String() if strings.Contains(s, ",") { t.Errorf("should be space-separated values: %s", s) return } } writer := func(toggle bool) { defer wg.Done() cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, HopLimit: 1, Src: net.IPv6loopback, } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } n, err := p.WriteTo(data, &cm, dst) if err != nil { t.Error(err) return } if n != len(data) { t.Errorf("got %d; want %d", n, len(data)) return } } batchWriter := func(toggle bool) { defer wg.Done() cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, HopLimit: 1, Src: net.IPv6loopback, } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } ms := []ipv6.Message{ { Buffers: [][]byte{data}, OOB: cm.Marshal(), Addr: dst, }, } n, err := p.WriteBatch(ms, 0) if err != nil { t.Error(err) return } if n != len(ms) { t.Errorf("got %d; want %d", n, len(ms)) return } if ms[0].N != len(data) { t.Errorf("got %d; want %d", ms[0].N, len(data)) return } } const N = 10 wg.Add(N) for i := 0; i < N; i++ { if batch { go batchReader() } else { go reader() } } wg.Add(2 * N) for i := 0; i < 2*N; i++ { if batch { go batchWriter(i%2 != 0) } else { go writer(i%2 != 0) } } wg.Add(N) for i := 0; i < N; i++ { if batch { go batchReader() } else { go reader() } } wg.Wait() } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/readwrite_go1_8_test.go0000644061062106075000000001422013172163402025547 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 package ipv6_test import ( "bytes" "fmt" "net" "runtime" "strings" "sync" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) func BenchmarkPacketConnReadWriteUnicast(b *testing.B) { switch runtime.GOOS { case "nacl", "plan9", "windows": b.Skipf("not supported on %s", runtime.GOOS) } payload := []byte("HELLO-R-U-THERE") iph := []byte{ 0x69, 0x8b, 0xee, 0xf1, 0xca, 0xfe, 0xff, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, } greh := []byte{0x00, 0x00, 0x86, 0xdd, 0x00, 0x00, 0x00, 0x00} datagram := append(greh, append(iph, payload...)...) bb := make([]byte, 128) cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, HopLimit: 1, Src: net.IPv6loopback, } if ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback); ifi != nil { cm.IfIndex = ifi.Index } b.Run("UDP", func(b *testing.B) { c, err := nettest.NewLocalPacketListener("udp6") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv6.NewPacketConn(c) dst := c.LocalAddr() cf := ipv6.FlagHopLimit | ipv6.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } b.Run("Net", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(payload, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("ToFrom", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteTo(payload, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(bb); err != nil { b.Fatal(err) } } }) }) b.Run("IP", func(b *testing.B) { switch runtime.GOOS { case "netbsd": b.Skip("need to configure gre on netbsd") case "openbsd": b.Skip("net.inet.gre.allow=0 by default on openbsd") } c, err := net.ListenPacket(fmt.Sprintf("ip6:%d", iana.ProtocolGRE), "::1") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv6.NewPacketConn(c) dst := c.LocalAddr() cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } b.Run("Net", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(datagram, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("ToFrom", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteTo(datagram, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(bb); err != nil { b.Fatal(err) } } }) }) } func TestPacketConnConcurrentReadWriteUnicast(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } payload := []byte("HELLO-R-U-THERE") iph := []byte{ 0x69, 0x8b, 0xee, 0xf1, 0xca, 0xfe, 0xff, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, } greh := []byte{0x00, 0x00, 0x86, 0xdd, 0x00, 0x00, 0x00, 0x00} datagram := append(greh, append(iph, payload...)...) t.Run("UDP", func(t *testing.T) { c, err := nettest.NewLocalPacketListener("udp6") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv6.NewPacketConn(c) t.Run("ToFrom", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, payload, c.LocalAddr()) }) }) t.Run("IP", func(t *testing.T) { switch runtime.GOOS { case "netbsd": t.Skip("need to configure gre on netbsd") case "openbsd": t.Skip("net.inet.gre.allow=0 by default on openbsd") } c, err := net.ListenPacket(fmt.Sprintf("ip6:%d", iana.ProtocolGRE), "::1") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv6.NewPacketConn(c) t.Run("ToFrom", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, datagram, c.LocalAddr()) }) }) } func testPacketConnConcurrentReadWriteUnicast(t *testing.T, p *ipv6.PacketConn, data []byte, dst net.Addr) { ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU if err := p.SetControlMessage(cf, true); err != nil { // probe before test if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } var wg sync.WaitGroup reader := func() { defer wg.Done() b := make([]byte, 128) n, cm, _, err := p.ReadFrom(b) if err != nil { t.Error(err) return } if !bytes.Equal(b[:n], data) { t.Errorf("got %#v; want %#v", b[:n], data) return } s := cm.String() if strings.Contains(s, ",") { t.Errorf("should be space-separated values: %s", s) return } } writer := func(toggle bool) { defer wg.Done() cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, HopLimit: 1, Src: net.IPv6loopback, } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } n, err := p.WriteTo(data, &cm, dst) if err != nil { t.Error(err) return } if n != len(data) { t.Errorf("got %d; want %d", n, len(data)) return } } const N = 10 wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Add(2 * N) for i := 0; i < 2*N; i++ { go writer(i%2 != 0) } wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Wait() } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/payload_nocmsg.go0000644061062106075000000000242613172163402024531 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build nacl plan9 windows package ipv6 import ( "net" "syscall" ) // ReadFrom reads a payload of the received IPv6 datagram, from the // endpoint c, copying the payload into b. It returns the number of // bytes copied into b, the control message cm and the source address // src of the received datagram. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { if !c.ok() { return 0, nil, nil, syscall.EINVAL } if n, src, err = c.PacketConn.ReadFrom(b); err != nil { return 0, nil, nil, err } return } // WriteTo writes a payload of the IPv6 datagram, to the destination // address dst through the endpoint c, copying the payload from b. It // returns the number of bytes written. The control message cm allows // the IPv6 header fields and the datagram path to be specified. The // cm may be nil if control of the outgoing datagram is not required. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { if !c.ok() { return 0, syscall.EINVAL } if dst == nil { return 0, errMissingAddress } return c.PacketConn.WriteTo(b, dst) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/payload_cmsg_go1_9.go0000644061062106075000000000340013172163402025163 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 // +build !nacl,!plan9,!windows package ipv6 import ( "net" "golang.org/x/net/internal/socket" ) func (c *payloadHandler) readFrom(b []byte) (int, *ControlMessage, net.Addr, error) { c.rawOpt.RLock() m := socket.Message{ Buffers: [][]byte{b}, OOB: NewControlMessage(c.rawOpt.cflags), } c.rawOpt.RUnlock() switch c.PacketConn.(type) { case *net.UDPConn: if err := c.RecvMsg(&m, 0); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } case *net.IPConn: if err := c.RecvMsg(&m, 0); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } default: return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errInvalidConnType} } var cm *ControlMessage if m.NN > 0 { cm = new(ControlMessage) if err := cm.Parse(m.OOB[:m.NN]); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } cm.Src = netAddrToIP16(m.Addr) } return m.N, cm, m.Addr, nil } func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (int, error) { m := socket.Message{ Buffers: [][]byte{b}, OOB: cm.Marshal(), Addr: dst, } err := c.SendMsg(&m, 0) if err != nil { err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Addr: opAddr(dst), Err: err} } return m.N, err } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/payload_cmsg_go1_8.go0000644061062106075000000000327713172163402025176 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 // +build !nacl,!plan9,!windows package ipv6 import "net" func (c *payloadHandler) readFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { c.rawOpt.RLock() oob := NewControlMessage(c.rawOpt.cflags) c.rawOpt.RUnlock() var nn int switch c := c.PacketConn.(type) { case *net.UDPConn: if n, nn, _, src, err = c.ReadMsgUDP(b, oob); err != nil { return 0, nil, nil, err } case *net.IPConn: if n, nn, _, src, err = c.ReadMsgIP(b, oob); err != nil { return 0, nil, nil, err } default: return 0, nil, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Err: errInvalidConnType} } if nn > 0 { cm = new(ControlMessage) if err = cm.Parse(oob[:nn]); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } } if cm != nil { cm.Src = netAddrToIP16(src) } return } func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { oob := cm.Marshal() if dst == nil { return 0, &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errMissingAddress} } switch c := c.PacketConn.(type) { case *net.UDPConn: n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr)) case *net.IPConn: n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr)) default: return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Addr: opAddr(dst), Err: errInvalidConnType} } return } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/payload_cmsg.go0000644061062106075000000000223013172163402024165 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !nacl,!plan9,!windows package ipv6 import ( "net" "syscall" ) // ReadFrom reads a payload of the received IPv6 datagram, from the // endpoint c, copying the payload into b. It returns the number of // bytes copied into b, the control message cm and the source address // src of the received datagram. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { if !c.ok() { return 0, nil, nil, syscall.EINVAL } return c.readFrom(b) } // WriteTo writes a payload of the IPv6 datagram, to the destination // address dst through the endpoint c, copying the payload from b. It // returns the number of bytes written. The control message cm allows // the IPv6 header fields and the datagram path to be specified. The // cm may be nil if control of the outgoing datagram is not required. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { if !c.ok() { return 0, syscall.EINVAL } return c.writeTo(b, cm, dst) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/payload.go0000644061062106075000000000110213172163402023151 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "net" "golang.org/x/net/internal/socket" ) // BUG(mikio): On Windows, the ControlMessage for ReadFrom and WriteTo // methods of PacketConn is not implemented. // A payloadHandler represents the IPv6 datagram payload handler. type payloadHandler struct { net.PacketConn *socket.Conn rawOpt } func (c *payloadHandler) ok() bool { return c != nil && c.PacketConn != nil && c.Conn != nil } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/multicastsockopt_test.go0000644061062106075000000001023313172163402026174 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var packetConnMulticastSocketOptionTests = []struct { net, proto, addr string grp, src net.Addr }{ {"udp6", "", "[ff02::]:0", &net.UDPAddr{IP: net.ParseIP("ff02::114")}, nil}, // see RFC 4727 {"ip6", ":ipv6-icmp", "::", &net.IPAddr{IP: net.ParseIP("ff02::115")}, nil}, // see RFC 4727 {"udp6", "", "[ff30::8000:0]:0", &net.UDPAddr{IP: net.ParseIP("ff30::8000:1")}, &net.UDPAddr{IP: net.IPv6loopback}}, // see RFC 5771 {"ip6", ":ipv6-icmp", "::", &net.IPAddr{IP: net.ParseIP("ff30::8000:2")}, &net.IPAddr{IP: net.IPv6loopback}}, // see RFC 5771 } func TestPacketConnMulticastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnMulticastSocketOptionTests { if tt.net == "ip6" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() if tt.src == nil { testMulticastSocketOptions(t, p, ifi, tt.grp) } else { testSourceSpecificMulticastSocketOptions(t, p, ifi, tt.grp, tt.src) } } } type testIPv6MulticastConn interface { MulticastHopLimit() (int, error) SetMulticastHopLimit(ttl int) error MulticastLoopback() (bool, error) SetMulticastLoopback(bool) error JoinGroup(*net.Interface, net.Addr) error LeaveGroup(*net.Interface, net.Addr) error JoinSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error LeaveSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error ExcludeSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error IncludeSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error } func testMulticastSocketOptions(t *testing.T, c testIPv6MulticastConn, ifi *net.Interface, grp net.Addr) { const hoplim = 255 if err := c.SetMulticastHopLimit(hoplim); err != nil { t.Error(err) return } if v, err := c.MulticastHopLimit(); err != nil { t.Error(err) return } else if v != hoplim { t.Errorf("got %v; want %v", v, hoplim) return } for _, toggle := range []bool{true, false} { if err := c.SetMulticastLoopback(toggle); err != nil { t.Error(err) return } if v, err := c.MulticastLoopback(); err != nil { t.Error(err) return } else if v != toggle { t.Errorf("got %v; want %v", v, toggle) return } } if err := c.JoinGroup(ifi, grp); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } } func testSourceSpecificMulticastSocketOptions(t *testing.T, c testIPv6MulticastConn, ifi *net.Interface, grp, src net.Addr) { // MCAST_JOIN_GROUP -> MCAST_BLOCK_SOURCE -> MCAST_UNBLOCK_SOURCE -> MCAST_LEAVE_GROUP if err := c.JoinGroup(ifi, grp); err != nil { t.Error(err) return } if err := c.ExcludeSourceSpecificGroup(ifi, grp, src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support MLDv2 fail here t.Logf("not supported on %s", runtime.GOOS) return } t.Error(err) return } if err := c.IncludeSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } // MCAST_JOIN_SOURCE_GROUP -> MCAST_LEAVE_SOURCE_GROUP if err := c.JoinSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } // MCAST_JOIN_SOURCE_GROUP -> MCAST_LEAVE_GROUP if err := c.JoinSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/multicastlistener_test.go0000644061062106075000000001377113172163402026351 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var udpMultipleGroupListenerTests = []net.Addr{ &net.UDPAddr{IP: net.ParseIP("ff02::114")}, // see RFC 4727 &net.UDPAddr{IP: net.ParseIP("ff02::1:114")}, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}, } func TestUDPSinglePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } for _, gaddr := range udpMultipleGroupListenerTests { c, err := net.ListenPacket("udp6", "[::]:0") // wildcard address with non-reusable port if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip6", &ifi); !ok { continue } if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } for _, gaddr := range udpMultipleGroupListenerTests { c1, err := net.ListenPacket("udp6", "[ff02::]:0") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c1.Close() _, port, err := net.SplitHostPort(c1.LocalAddr().String()) if err != nil { t.Fatal(err) } c2, err := net.ListenPacket("udp6", net.JoinHostPort("ff02::", port)) // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c2.Close() var ps [2]*ipv6.PacketConn ps[0] = ipv6.NewPacketConn(c1) ps[1] = ipv6.NewPacketConn(c2) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip6", &ifi); !ok { continue } for _, p := range ps { if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } } mift = append(mift, &ift[i]) } for _, ifi := range mift { for _, p := range ps { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } } func TestUDPPerInterfaceSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } gaddr := net.IPAddr{IP: net.ParseIP("ff02::114")} // see RFC 4727 type ml struct { c *ipv6.PacketConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } port := "0" for i, ifi := range ift { ip, ok := nettest.IsMulticastCapable("ip6", &ifi) if !ok { continue } c, err := net.ListenPacket("udp6", net.JoinHostPort(ip.String()+"%"+ifi.Name, port)) // unicast address with non-reusable port if err != nil { // The listen may fail when the serivce is // already in use, but it's fine because the // purpose of this is not to test the // bookkeeping of IP control block inside the // kernel. t.Log(err) continue } defer c.Close() if port == "0" { _, port, err = net.SplitHostPort(c.LocalAddr().String()) if err != nil { t.Fatal(err) } } p := ipv6.NewPacketConn(c) if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{p, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip6:ipv6-icmp", "::") // wildcard address if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) gaddr := net.IPAddr{IP: net.ParseIP("ff02::114")} // see RFC 4727 var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip6", &ifi); !ok { continue } if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := p.LeaveGroup(ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPPerInterfaceSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "darwin", "dragonfly", "openbsd": // platforms that return fe80::1%lo0: bind: can't assign requested address t.Skipf("not supported on %s", runtime.GOOS) case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } gaddr := net.IPAddr{IP: net.ParseIP("ff02::114")} // see RFC 4727 type ml struct { c *ipv6.PacketConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { ip, ok := nettest.IsMulticastCapable("ip6", &ifi) if !ok { continue } c, err := net.ListenPacket("ip6:ipv6-icmp", ip.String()+"%"+ifi.Name) // unicast address if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{p, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/multicast_test.go0000644061062106075000000001620113172163402024572 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "bytes" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var packetConnReadWriteMulticastUDPTests = []struct { addr string grp, src *net.UDPAddr }{ {"[ff02::]:0", &net.UDPAddr{IP: net.ParseIP("ff02::114")}, nil}, // see RFC 4727 {"[ff30::8000:0]:0", &net.UDPAddr{IP: net.ParseIP("ff30::8000:1")}, &net.UDPAddr{IP: net.IPv6loopback}}, // see RFC 5771 } func TestPacketConnReadWriteMulticastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if !nettest.SupportsIPv6MulticastDeliveryOnLoopback() { t.Skipf("multicast delivery doesn't work correctly on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range packetConnReadWriteMulticastUDPTests { c, err := net.ListenPacket("udp6", tt.addr) if err != nil { t.Fatal(err) } defer c.Close() grp := *tt.grp grp.Port = c.LocalAddr().(*net.UDPAddr).Port p := ipv6.NewPacketConn(c) defer p.Close() if tt.src == nil { if err := p.JoinGroup(ifi, &grp); err != nil { t.Fatal(err) } defer p.LeaveGroup(ifi, &grp) } else { if err := p.JoinSourceSpecificGroup(ifi, &grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support MLDv2 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer p.LeaveSourceSpecificGroup(ifi, &grp, tt.src) } if err := p.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := p.MulticastInterface(); err != nil { t.Fatal(err) } if err := p.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := p.MulticastLoopback(); err != nil { t.Fatal(err) } cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, IfIndex: ifi.Index, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := p.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } cm.HopLimit = i + 1 if n, err := p.WriteTo(wb, &cm, &grp); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatal(err) } rb := make([]byte, 128) if n, _, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; want %v", rb[:n], wb) } } } } var packetConnReadWriteMulticastICMPTests = []struct { grp, src *net.IPAddr }{ {&net.IPAddr{IP: net.ParseIP("ff02::114")}, nil}, // see RFC 4727 {&net.IPAddr{IP: net.ParseIP("ff30::8000:1")}, &net.IPAddr{IP: net.IPv6loopback}}, // see RFC 5771 } func TestPacketConnReadWriteMulticastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if !nettest.SupportsIPv6MulticastDeliveryOnLoopback() { t.Skipf("multicast delivery doesn't work correctly on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range packetConnReadWriteMulticastICMPTests { c, err := net.ListenPacket("ip6:ipv6-icmp", "::") if err != nil { t.Fatal(err) } defer c.Close() pshicmp := icmp.IPv6PseudoHeader(c.LocalAddr().(*net.IPAddr).IP, tt.grp.IP) p := ipv6.NewPacketConn(c) defer p.Close() if tt.src == nil { if err := p.JoinGroup(ifi, tt.grp); err != nil { t.Fatal(err) } defer p.LeaveGroup(ifi, tt.grp) } else { if err := p.JoinSourceSpecificGroup(ifi, tt.grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support MLDv2 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer p.LeaveSourceSpecificGroup(ifi, tt.grp, tt.src) } if err := p.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := p.MulticastInterface(); err != nil { t.Fatal(err) } if err := p.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := p.MulticastLoopback(); err != nil { t.Fatal(err) } cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, IfIndex: ifi.Index, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } var psh []byte for i, toggle := range []bool{true, false, true} { if toggle { psh = nil if err := p.SetChecksum(true, 2); err != nil { // Solaris never allows to // modify ICMP properties. if runtime.GOOS != "solaris" { t.Fatal(err) } } } else { psh = pshicmp // Some platforms never allow to // disable the kernel checksum // processing. p.SetChecksum(false, -1) } wb, err := (&icmp.Message{ Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(psh) if err != nil { t.Fatal(err) } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := p.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } cm.HopLimit = i + 1 if n, err := p.WriteTo(wb, &cm, tt.grp); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if n, _, _, err := p.ReadFrom(rb); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels have some limitation on receiving icmp packet through raw socket t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } else { if m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, rb[:n]); err != nil { t.Fatal(err) } else if m.Type != ipv6.ICMPTypeEchoReply || m.Code != 0 { t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv6.ICMPTypeEchoReply, 0) } } } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/mocktransponder_test.go0000644061062106075000000000111213172163402025771 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "net" "testing" ) func connector(t *testing.T, network, addr string, done chan<- bool) { defer func() { done <- true }() c, err := net.Dial(network, addr) if err != nil { t.Error(err) return } c.Close() } func acceptor(t *testing.T, ln net.Listener, done chan<- bool) { defer func() { done <- true }() c, err := ln.Accept() if err != nil { t.Error(err) return } c.Close() } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/icmp_windows.go0000644061062106075000000000100413172163402024223 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 func (f *icmpv6Filter) accept(typ ICMPType) { // TODO(mikio): implement this } func (f *icmpv6Filter) block(typ ICMPType) { // TODO(mikio): implement this } func (f *icmpv6Filter) setAll(block bool) { // TODO(mikio): implement this } func (f *icmpv6Filter) willBlock(typ ICMPType) bool { // TODO(mikio): implement this return false } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/icmp_test.go0000644061062106075000000000367313172163402023526 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "net" "reflect" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var icmpStringTests = []struct { in ipv6.ICMPType out string }{ {ipv6.ICMPTypeDestinationUnreachable, "destination unreachable"}, {256, ""}, } func TestICMPString(t *testing.T) { for _, tt := range icmpStringTests { s := tt.in.String() if s != tt.out { t.Errorf("got %s; want %s", s, tt.out) } } } func TestICMPFilter(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } var f ipv6.ICMPFilter for _, toggle := range []bool{false, true} { f.SetAll(toggle) for _, typ := range []ipv6.ICMPType{ ipv6.ICMPTypeDestinationUnreachable, ipv6.ICMPTypeEchoReply, ipv6.ICMPTypeNeighborSolicitation, ipv6.ICMPTypeDuplicateAddressConfirmation, } { f.Accept(typ) if f.WillBlock(typ) { t.Errorf("ipv6.ICMPFilter.Set(%v, false) failed", typ) } f.Block(typ) if !f.WillBlock(typ) { t.Errorf("ipv6.ICMPFilter.Set(%v, true) failed", typ) } } } } func TestSetICMPFilter(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip6:ipv6-icmp", "::1") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeEchoRequest) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } kf, err := p.ICMPFilter() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(kf, &f) { t.Fatalf("got %#v; want %#v", kf, f) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/icmp_stub.go0000644061062106075000000000076313172163402023521 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package ipv6 type icmpv6Filter struct { } func (f *icmpv6Filter) accept(typ ICMPType) { } func (f *icmpv6Filter) block(typ ICMPType) { } func (f *icmpv6Filter) setAll(block bool) { } func (f *icmpv6Filter) willBlock(typ ICMPType) bool { return false } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/icmp_solaris.go0000644061062106075000000000122713172163402024214 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 func (f *icmpv6Filter) accept(typ ICMPType) { f.X__icmp6_filt[typ>>5] |= 1 << (uint32(typ) & 31) } func (f *icmpv6Filter) block(typ ICMPType) { f.X__icmp6_filt[typ>>5] &^= 1 << (uint32(typ) & 31) } func (f *icmpv6Filter) setAll(block bool) { for i := range f.X__icmp6_filt { if block { f.X__icmp6_filt[i] = 0 } else { f.X__icmp6_filt[i] = 1<<32 - 1 } } } func (f *icmpv6Filter) willBlock(typ ICMPType) bool { return f.X__icmp6_filt[typ>>5]&(1<<(uint32(typ)&31)) == 0 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/icmp_linux.go0000644061062106075000000000114113172163402023672 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 func (f *icmpv6Filter) accept(typ ICMPType) { f.Data[typ>>5] &^= 1 << (uint32(typ) & 31) } func (f *icmpv6Filter) block(typ ICMPType) { f.Data[typ>>5] |= 1 << (uint32(typ) & 31) } func (f *icmpv6Filter) setAll(block bool) { for i := range f.Data { if block { f.Data[i] = 1<<32 - 1 } else { f.Data[i] = 0 } } } func (f *icmpv6Filter) willBlock(typ ICMPType) bool { return f.Data[typ>>5]&(1<<(uint32(typ)&31)) != 0 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/icmp_bsd.go0000644061062106075000000000122413172163402023305 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package ipv6 func (f *icmpv6Filter) accept(typ ICMPType) { f.Filt[typ>>5] |= 1 << (uint32(typ) & 31) } func (f *icmpv6Filter) block(typ ICMPType) { f.Filt[typ>>5] &^= 1 << (uint32(typ) & 31) } func (f *icmpv6Filter) setAll(block bool) { for i := range f.Filt { if block { f.Filt[i] = 0 } else { f.Filt[i] = 1<<32 - 1 } } } func (f *icmpv6Filter) willBlock(typ ICMPType) bool { return f.Filt[typ>>5]&(1<<(uint32(typ)&31)) == 0 } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/icmp.go0000644061062106075000000000307713172163402022465 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import "golang.org/x/net/internal/iana" // BUG(mikio): On Windows, methods related to ICMPFilter are not // implemented. // An ICMPType represents a type of ICMP message. type ICMPType int func (typ ICMPType) String() string { s, ok := icmpTypes[typ] if !ok { return "" } return s } // Protocol returns the ICMPv6 protocol number. func (typ ICMPType) Protocol() int { return iana.ProtocolIPv6ICMP } // An ICMPFilter represents an ICMP message filter for incoming // packets. The filter belongs to a packet delivery path on a host and // it cannot interact with forwarding packets or tunnel-outer packets. // // Note: RFC 8200 defines a reasonable role model. A node means a // device that implements IP. A router means a node that forwards IP // packets not explicitly addressed to itself, and a host means a node // that is not a router. type ICMPFilter struct { icmpv6Filter } // Accept accepts incoming ICMP packets including the type field value // typ. func (f *ICMPFilter) Accept(typ ICMPType) { f.accept(typ) } // Block blocks incoming ICMP packets including the type field value // typ. func (f *ICMPFilter) Block(typ ICMPType) { f.block(typ) } // SetAll sets the filter action to the filter. func (f *ICMPFilter) SetAll(block bool) { f.setAll(block) } // WillBlock reports whether the ICMP type will be blocked. func (f *ICMPFilter) WillBlock(typ ICMPType) bool { return f.willBlock(typ) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/iana.go0000644061062106075000000001125613172163402022443 0ustar stgraberdomain admins// go generate gen.go // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package ipv6 // Internet Control Message Protocol version 6 (ICMPv6) Parameters, Updated: 2015-07-07 const ( ICMPTypeDestinationUnreachable ICMPType = 1 // Destination Unreachable ICMPTypePacketTooBig ICMPType = 2 // Packet Too Big ICMPTypeTimeExceeded ICMPType = 3 // Time Exceeded ICMPTypeParameterProblem ICMPType = 4 // Parameter Problem ICMPTypeEchoRequest ICMPType = 128 // Echo Request ICMPTypeEchoReply ICMPType = 129 // Echo Reply ICMPTypeMulticastListenerQuery ICMPType = 130 // Multicast Listener Query ICMPTypeMulticastListenerReport ICMPType = 131 // Multicast Listener Report ICMPTypeMulticastListenerDone ICMPType = 132 // Multicast Listener Done ICMPTypeRouterSolicitation ICMPType = 133 // Router Solicitation ICMPTypeRouterAdvertisement ICMPType = 134 // Router Advertisement ICMPTypeNeighborSolicitation ICMPType = 135 // Neighbor Solicitation ICMPTypeNeighborAdvertisement ICMPType = 136 // Neighbor Advertisement ICMPTypeRedirect ICMPType = 137 // Redirect Message ICMPTypeRouterRenumbering ICMPType = 138 // Router Renumbering ICMPTypeNodeInformationQuery ICMPType = 139 // ICMP Node Information Query ICMPTypeNodeInformationResponse ICMPType = 140 // ICMP Node Information Response ICMPTypeInverseNeighborDiscoverySolicitation ICMPType = 141 // Inverse Neighbor Discovery Solicitation Message ICMPTypeInverseNeighborDiscoveryAdvertisement ICMPType = 142 // Inverse Neighbor Discovery Advertisement Message ICMPTypeVersion2MulticastListenerReport ICMPType = 143 // Version 2 Multicast Listener Report ICMPTypeHomeAgentAddressDiscoveryRequest ICMPType = 144 // Home Agent Address Discovery Request Message ICMPTypeHomeAgentAddressDiscoveryReply ICMPType = 145 // Home Agent Address Discovery Reply Message ICMPTypeMobilePrefixSolicitation ICMPType = 146 // Mobile Prefix Solicitation ICMPTypeMobilePrefixAdvertisement ICMPType = 147 // Mobile Prefix Advertisement ICMPTypeCertificationPathSolicitation ICMPType = 148 // Certification Path Solicitation Message ICMPTypeCertificationPathAdvertisement ICMPType = 149 // Certification Path Advertisement Message ICMPTypeMulticastRouterAdvertisement ICMPType = 151 // Multicast Router Advertisement ICMPTypeMulticastRouterSolicitation ICMPType = 152 // Multicast Router Solicitation ICMPTypeMulticastRouterTermination ICMPType = 153 // Multicast Router Termination ICMPTypeFMIPv6 ICMPType = 154 // FMIPv6 Messages ICMPTypeRPLControl ICMPType = 155 // RPL Control Message ICMPTypeILNPv6LocatorUpdate ICMPType = 156 // ILNPv6 Locator Update Message ICMPTypeDuplicateAddressRequest ICMPType = 157 // Duplicate Address Request ICMPTypeDuplicateAddressConfirmation ICMPType = 158 // Duplicate Address Confirmation ICMPTypeMPLControl ICMPType = 159 // MPL Control Message ) // Internet Control Message Protocol version 6 (ICMPv6) Parameters, Updated: 2015-07-07 var icmpTypes = map[ICMPType]string{ 1: "destination unreachable", 2: "packet too big", 3: "time exceeded", 4: "parameter problem", 128: "echo request", 129: "echo reply", 130: "multicast listener query", 131: "multicast listener report", 132: "multicast listener done", 133: "router solicitation", 134: "router advertisement", 135: "neighbor solicitation", 136: "neighbor advertisement", 137: "redirect message", 138: "router renumbering", 139: "icmp node information query", 140: "icmp node information response", 141: "inverse neighbor discovery solicitation message", 142: "inverse neighbor discovery advertisement message", 143: "version 2 multicast listener report", 144: "home agent address discovery request message", 145: "home agent address discovery reply message", 146: "mobile prefix solicitation", 147: "mobile prefix advertisement", 148: "certification path solicitation message", 149: "certification path advertisement message", 151: "multicast router advertisement", 152: "multicast router solicitation", 153: "multicast router termination", 154: "fmipv6 messages", 155: "rpl control message", 156: "ilnpv6 locator update message", 157: "duplicate address request", 158: "duplicate address confirmation", 159: "mpl control message", } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/helper.go0000644061062106075000000000202213172163402023001 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "errors" "net" ) var ( errMissingAddress = errors.New("missing address") errHeaderTooShort = errors.New("header too short") errInvalidConnType = errors.New("invalid conn type") errOpNoSupport = errors.New("operation not supported") errNoSuchInterface = errors.New("no such interface") ) func boolint(b bool) int { if b { return 1 } return 0 } func netAddrToIP16(a net.Addr) net.IP { switch v := a.(type) { case *net.UDPAddr: if ip := v.IP.To16(); ip != nil && ip.To4() == nil { return ip } case *net.IPAddr: if ip := v.IP.To16(); ip != nil && ip.To4() == nil { return ip } } return nil } func opAddr(a net.Addr) net.Addr { switch a.(type) { case *net.TCPAddr: if a == nil { return nil } case *net.UDPAddr: if a == nil { return nil } case *net.IPAddr: if a == nil { return nil } } return a } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/header_test.go0000644061062106075000000000231313172163402024014 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "net" "reflect" "strings" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv6" ) var ( wireHeaderFromKernel = [ipv6.HeaderLen]byte{ 0x69, 0x8b, 0xee, 0xf1, 0xca, 0xfe, 0x2c, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, } testHeader = &ipv6.Header{ Version: ipv6.Version, TrafficClass: iana.DiffServAF43, FlowLabel: 0xbeef1, PayloadLen: 0xcafe, NextHeader: iana.ProtocolIPv6Frag, HopLimit: 1, Src: net.ParseIP("2001:db8:1::1"), Dst: net.ParseIP("2001:db8:2::1"), } ) func TestParseHeader(t *testing.T) { h, err := ipv6.ParseHeader(wireHeaderFromKernel[:]) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(h, testHeader) { t.Fatalf("got %#v; want %#v", h, testHeader) } s := h.String() if strings.Contains(s, ",") { t.Fatalf("should be space-separated values: %s", s) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/header.go0000644061062106075000000000273213172163402022762 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "encoding/binary" "fmt" "net" ) const ( Version = 6 // protocol version HeaderLen = 40 // header length ) // A Header represents an IPv6 base header. type Header struct { Version int // protocol version TrafficClass int // traffic class FlowLabel int // flow label PayloadLen int // payload length NextHeader int // next header HopLimit int // hop limit Src net.IP // source address Dst net.IP // destination address } func (h *Header) String() string { if h == nil { return "" } return fmt.Sprintf("ver=%d tclass=%#x flowlbl=%#x payloadlen=%d nxthdr=%d hoplim=%d src=%v dst=%v", h.Version, h.TrafficClass, h.FlowLabel, h.PayloadLen, h.NextHeader, h.HopLimit, h.Src, h.Dst) } // ParseHeader parses b as an IPv6 base header. func ParseHeader(b []byte) (*Header, error) { if len(b) < HeaderLen { return nil, errHeaderTooShort } h := &Header{ Version: int(b[0]) >> 4, TrafficClass: int(b[0]&0x0f)<<4 | int(b[1])>>4, FlowLabel: int(b[1]&0x0f)<<16 | int(b[2])<<8 | int(b[3]), PayloadLen: int(binary.BigEndian.Uint16(b[4:6])), NextHeader: int(b[6]), HopLimit: int(b[7]), } h.Src = make(net.IP, net.IPv6len) copy(h.Src, b[8:24]) h.Dst = make(net.IP, net.IPv6len) copy(h.Dst, b[24:40]) return h, nil } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/genericopt.go0000644061062106075000000000243213172163402023666 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import "syscall" // TrafficClass returns the traffic class field value for outgoing // packets. func (c *genericOpt) TrafficClass() (int, error) { if !c.ok() { return 0, syscall.EINVAL } so, ok := sockOpts[ssoTrafficClass] if !ok { return 0, errOpNoSupport } return so.GetInt(c.Conn) } // SetTrafficClass sets the traffic class field value for future // outgoing packets. func (c *genericOpt) SetTrafficClass(tclass int) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoTrafficClass] if !ok { return errOpNoSupport } return so.SetInt(c.Conn, tclass) } // HopLimit returns the hop limit field value for outgoing packets. func (c *genericOpt) HopLimit() (int, error) { if !c.ok() { return 0, syscall.EINVAL } so, ok := sockOpts[ssoHopLimit] if !ok { return 0, errOpNoSupport } return so.GetInt(c.Conn) } // SetHopLimit sets the hop limit field value for future outgoing // packets. func (c *genericOpt) SetHopLimit(hoplim int) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoHopLimit] if !ok { return errOpNoSupport } return so.SetInt(c.Conn, hoplim) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/gen.go0000644061062106075000000001050113172163402022274 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore //go:generate go run gen.go // This program generates system adaptation constants and types, // internet protocol constants and tables by reading template files // and IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "io/ioutil" "net/http" "os" "os/exec" "runtime" "strconv" "strings" ) func main() { if err := genzsys(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := geniana(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func genzsys() error { defs := "defs_" + runtime.GOOS + ".go" f, err := os.Open(defs) if err != nil { if os.IsNotExist(err) { return nil } return err } f.Close() cmd := exec.Command("go", "tool", "cgo", "-godefs", defs) b, err := cmd.Output() if err != nil { return err } b, err = format.Source(b) if err != nil { return err } zsys := "zsys_" + runtime.GOOS + ".go" switch runtime.GOOS { case "freebsd", "linux": zsys = "zsys_" + runtime.GOOS + "_" + runtime.GOARCH + ".go" } if err := ioutil.WriteFile(zsys, b, 0644); err != nil { return err } return nil } var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "http://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xml", parseICMPv6Parameters, }, } func geniana() error { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n") fmt.Fprintf(&bb, "package ipv6\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("got HTTP status code %v for %v\n", resp.StatusCode, r.url) } if err := r.parse(&bb, resp.Body); err != nil { return err } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { return err } if err := ioutil.WriteFile("iana.go", b, 0644); err != nil { return err } return nil } func parseICMPv6Parameters(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var icp icmpv6Parameters if err := dec.Decode(&icp); err != nil { return err } prs := icp.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "ICMPType%s ICMPType = %d", pr.Name, pr.Value) fmt.Fprintf(w, "// %s\n", pr.OrigName) } fmt.Fprintf(w, ")\n\n") fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "var icmpTypes = map[ICMPType]string{\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "%d: %q,\n", pr.Value, strings.ToLower(pr.OrigName)) } fmt.Fprintf(w, "}\n") return nil } type icmpv6Parameters struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Registries []struct { Title string `xml:"title"` Records []struct { Value string `xml:"value"` Name string `xml:"name"` } `xml:"record"` } `xml:"registry"` } type canonICMPv6ParamRecord struct { OrigName string Name string Value int } func (icp *icmpv6Parameters) escape() []canonICMPv6ParamRecord { id := -1 for i, r := range icp.Registries { if strings.Contains(r.Title, "Type") || strings.Contains(r.Title, "type") { id = i break } } if id < 0 { return nil } prs := make([]canonICMPv6ParamRecord, len(icp.Registries[id].Records)) sr := strings.NewReplacer( "Messages", "", "Message", "", "ICMP", "", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range icp.Registries[id].Records { if strings.Contains(pr.Name, "Reserved") || strings.Contains(pr.Name, "Unassigned") || strings.Contains(pr.Name, "Deprecated") || strings.Contains(pr.Name, "Experiment") || strings.Contains(pr.Name, "experiment") { continue } ss := strings.Split(pr.Name, "\n") if len(ss) > 1 { prs[i].Name = strings.Join(ss, " ") } else { prs[i].Name = ss[0] } s := strings.TrimSpace(prs[i].Name) prs[i].OrigName = s prs[i].Name = sr.Replace(s) prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/example_test.go0000644061062106075000000001231413172163402024221 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "fmt" "log" "net" "os" "time" "golang.org/x/net/icmp" "golang.org/x/net/ipv6" ) func ExampleConn_markingTCP() { ln, err := net.Listen("tcp", "[::]:1024") if err != nil { log.Fatal(err) } defer ln.Close() for { c, err := ln.Accept() if err != nil { log.Fatal(err) } go func(c net.Conn) { defer c.Close() if c.RemoteAddr().(*net.TCPAddr).IP.To16() != nil && c.RemoteAddr().(*net.TCPAddr).IP.To4() == nil { p := ipv6.NewConn(c) if err := p.SetTrafficClass(0x28); err != nil { // DSCP AF11 log.Fatal(err) } if err := p.SetHopLimit(128); err != nil { log.Fatal(err) } } if _, err := c.Write([]byte("HELLO-R-U-THERE-ACK")); err != nil { log.Fatal(err) } }(c) } } func ExamplePacketConn_servingOneShotMulticastDNS() { c, err := net.ListenPacket("udp6", "[::]:5353") // mDNS over UDP if err != nil { log.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) en0, err := net.InterfaceByName("en0") if err != nil { log.Fatal(err) } mDNSLinkLocal := net.UDPAddr{IP: net.ParseIP("ff02::fb")} if err := p.JoinGroup(en0, &mDNSLinkLocal); err != nil { log.Fatal(err) } defer p.LeaveGroup(en0, &mDNSLinkLocal) if err := p.SetControlMessage(ipv6.FlagDst|ipv6.FlagInterface, true); err != nil { log.Fatal(err) } var wcm ipv6.ControlMessage b := make([]byte, 1500) for { _, rcm, peer, err := p.ReadFrom(b) if err != nil { log.Fatal(err) } if !rcm.Dst.IsMulticast() || !rcm.Dst.Equal(mDNSLinkLocal.IP) { continue } wcm.IfIndex = rcm.IfIndex answers := []byte("FAKE-MDNS-ANSWERS") // fake mDNS answers, you need to implement this if _, err := p.WriteTo(answers, &wcm, peer); err != nil { log.Fatal(err) } } } func ExamplePacketConn_tracingIPPacketRoute() { // Tracing an IP packet route to www.google.com. const host = "www.google.com" ips, err := net.LookupIP(host) if err != nil { log.Fatal(err) } var dst net.IPAddr for _, ip := range ips { if ip.To16() != nil && ip.To4() == nil { dst.IP = ip fmt.Printf("using %v for tracing an IP packet route to %s\n", dst.IP, host) break } } if dst.IP == nil { log.Fatal("no AAAA record found") } c, err := net.ListenPacket("ip6:58", "::") // ICMP for IPv6 if err != nil { log.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) if err := p.SetControlMessage(ipv6.FlagHopLimit|ipv6.FlagSrc|ipv6.FlagDst|ipv6.FlagInterface, true); err != nil { log.Fatal(err) } wm := icmp.Message{ Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Data: []byte("HELLO-R-U-THERE"), }, } var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeTimeExceeded) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { log.Fatal(err) } var wcm ipv6.ControlMessage rb := make([]byte, 1500) for i := 1; i <= 64; i++ { // up to 64 hops wm.Body.(*icmp.Echo).Seq = i wb, err := wm.Marshal(nil) if err != nil { log.Fatal(err) } // In the real world usually there are several // multiple traffic-engineered paths for each hop. // You may need to probe a few times to each hop. begin := time.Now() wcm.HopLimit = i if _, err := p.WriteTo(wb, &wcm, &dst); err != nil { log.Fatal(err) } if err := p.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil { log.Fatal(err) } n, rcm, peer, err := p.ReadFrom(rb) if err != nil { if err, ok := err.(net.Error); ok && err.Timeout() { fmt.Printf("%v\t*\n", i) continue } log.Fatal(err) } rm, err := icmp.ParseMessage(58, rb[:n]) if err != nil { log.Fatal(err) } rtt := time.Since(begin) // In the real world you need to determine whether the // received message is yours using ControlMessage.Src, // ControlMesage.Dst, icmp.Echo.ID and icmp.Echo.Seq. switch rm.Type { case ipv6.ICMPTypeTimeExceeded: names, _ := net.LookupAddr(peer.String()) fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm) case ipv6.ICMPTypeEchoReply: names, _ := net.LookupAddr(peer.String()) fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm) return } } } func ExamplePacketConn_advertisingOSPFHello() { c, err := net.ListenPacket("ip6:89", "::") // OSPF for IPv6 if err != nil { log.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) en0, err := net.InterfaceByName("en0") if err != nil { log.Fatal(err) } allSPFRouters := net.IPAddr{IP: net.ParseIP("ff02::5")} if err := p.JoinGroup(en0, &allSPFRouters); err != nil { log.Fatal(err) } defer p.LeaveGroup(en0, &allSPFRouters) hello := make([]byte, 24) // fake hello data, you need to implement this ospf := make([]byte, 16) // fake ospf header, you need to implement this ospf[0] = 3 // version 3 ospf[1] = 1 // hello packet ospf = append(ospf, hello...) if err := p.SetChecksum(true, 12); err != nil { log.Fatal(err) } cm := ipv6.ControlMessage{ TrafficClass: 0xc0, // DSCP CS6 HopLimit: 1, IfIndex: en0.Index, } if _, err := p.WriteTo(ospf, &cm, &allSPFRouters); err != nil { log.Fatal(err) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/endpoint.go0000644061062106075000000000621713172163402023354 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "net" "syscall" "time" "golang.org/x/net/internal/socket" ) // BUG(mikio): On Windows, the JoinSourceSpecificGroup, // LeaveSourceSpecificGroup, ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup methods of PacketConn are not // implemented. // A Conn represents a network endpoint that uses IPv6 transport. // It allows to set basic IP-level socket options such as traffic // class and hop limit. type Conn struct { genericOpt } type genericOpt struct { *socket.Conn } func (c *genericOpt) ok() bool { return c != nil && c.Conn != nil } // PathMTU returns a path MTU value for the destination associated // with the endpoint. func (c *Conn) PathMTU() (int, error) { if !c.ok() { return 0, syscall.EINVAL } so, ok := sockOpts[ssoPathMTU] if !ok { return 0, errOpNoSupport } _, mtu, err := so.getMTUInfo(c.Conn) if err != nil { return 0, err } return mtu, nil } // NewConn returns a new Conn. func NewConn(c net.Conn) *Conn { cc, _ := socket.NewConn(c) return &Conn{ genericOpt: genericOpt{Conn: cc}, } } // A PacketConn represents a packet network endpoint that uses IPv6 // transport. It is used to control several IP-level socket options // including IPv6 header manipulation. It also provides datagram // based network I/O methods specific to the IPv6 and higher layer // protocols such as OSPF, GRE, and UDP. type PacketConn struct { genericOpt dgramOpt payloadHandler } type dgramOpt struct { *socket.Conn } func (c *dgramOpt) ok() bool { return c != nil && c.Conn != nil } // SetControlMessage allows to receive the per packet basis IP-level // socket options. func (c *PacketConn) SetControlMessage(cf ControlFlags, on bool) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return setControlMessage(c.dgramOpt.Conn, &c.payloadHandler.rawOpt, cf, on) } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *PacketConn) SetDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *PacketConn) SetReadDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *PacketConn) SetWriteDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.SetWriteDeadline(t) } // Close closes the endpoint. func (c *PacketConn) Close() error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.Close() } // NewPacketConn returns a new PacketConn using c as its underlying // transport. func NewPacketConn(c net.PacketConn) *PacketConn { cc, _ := socket.NewConn(c.(net.Conn)) return &PacketConn{ genericOpt: genericOpt{Conn: cc}, dgramOpt: dgramOpt{Conn: cc}, payloadHandler: payloadHandler{PacketConn: c, Conn: cc}, } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/doc.go0000644061062106075000000001733313172163402022302 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ipv6 implements IP-level socket options for the Internet // Protocol version 6. // // The package provides IP-level socket options that allow // manipulation of IPv6 facilities. // // The IPv6 protocol is defined in RFC 8200. // Socket interface extensions are defined in RFC 3493, RFC 3542 and // RFC 3678. // MLDv1 and MLDv2 are defined in RFC 2710 and RFC 3810. // Source-specific multicast is defined in RFC 4607. // // On Darwin, this package requires OS X Mavericks version 10.9 or // above, or equivalent. // // // Unicasting // // The options for unicasting are available for net.TCPConn, // net.UDPConn and net.IPConn which are created as network connections // that use the IPv6 transport. When a single TCP connection carrying // a data flow of multiple packets needs to indicate the flow is // important, Conn is used to set the traffic class field on the IPv6 // header for each packet. // // ln, err := net.Listen("tcp6", "[::]:1024") // if err != nil { // // error handling // } // defer ln.Close() // for { // c, err := ln.Accept() // if err != nil { // // error handling // } // go func(c net.Conn) { // defer c.Close() // // The outgoing packets will be labeled DiffServ assured forwarding // class 1 low drop precedence, known as AF11 packets. // // if err := ipv6.NewConn(c).SetTrafficClass(0x28); err != nil { // // error handling // } // if _, err := c.Write(data); err != nil { // // error handling // } // }(c) // } // // // Multicasting // // The options for multicasting are available for net.UDPConn and // net.IPconn which are created as network connections that use the // IPv6 transport. A few network facilities must be prepared before // you begin multicasting, at a minimum joining network interfaces and // multicast groups. // // en0, err := net.InterfaceByName("en0") // if err != nil { // // error handling // } // en1, err := net.InterfaceByIndex(911) // if err != nil { // // error handling // } // group := net.ParseIP("ff02::114") // // First, an application listens to an appropriate address with an // appropriate service port. // // c, err := net.ListenPacket("udp6", "[::]:1024") // if err != nil { // // error handling // } // defer c.Close() // // Second, the application joins multicast groups, starts listening to // the groups on the specified network interfaces. Note that the // service port for transport layer protocol does not matter with this // operation as joining groups affects only network and link layer // protocols, such as IPv6 and Ethernet. // // p := ipv6.NewPacketConn(c) // if err := p.JoinGroup(en0, &net.UDPAddr{IP: group}); err != nil { // // error handling // } // if err := p.JoinGroup(en1, &net.UDPAddr{IP: group}); err != nil { // // error handling // } // // The application might set per packet control message transmissions // between the protocol stack within the kernel. When the application // needs a destination address on an incoming packet, // SetControlMessage of PacketConn is used to enable control message // transmissions. // // if err := p.SetControlMessage(ipv6.FlagDst, true); err != nil { // // error handling // } // // The application could identify whether the received packets are // of interest by using the control message that contains the // destination address of the received packet. // // b := make([]byte, 1500) // for { // n, rcm, src, err := p.ReadFrom(b) // if err != nil { // // error handling // } // if rcm.Dst.IsMulticast() { // if rcm.Dst.Equal(group) { // // joined group, do something // } else { // // unknown group, discard // continue // } // } // // The application can also send both unicast and multicast packets. // // p.SetTrafficClass(0x0) // p.SetHopLimit(16) // if _, err := p.WriteTo(data[:n], nil, src); err != nil { // // error handling // } // dst := &net.UDPAddr{IP: group, Port: 1024} // wcm := ipv6.ControlMessage{TrafficClass: 0xe0, HopLimit: 1} // for _, ifi := range []*net.Interface{en0, en1} { // wcm.IfIndex = ifi.Index // if _, err := p.WriteTo(data[:n], &wcm, dst); err != nil { // // error handling // } // } // } // // // More multicasting // // An application that uses PacketConn may join multiple multicast // groups. For example, a UDP listener with port 1024 might join two // different groups across over two different network interfaces by // using: // // c, err := net.ListenPacket("udp6", "[::]:1024") // if err != nil { // // error handling // } // defer c.Close() // p := ipv6.NewPacketConn(c) // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::1:114")}); err != nil { // // error handling // } // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}); err != nil { // // error handling // } // if err := p.JoinGroup(en1, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}); err != nil { // // error handling // } // // It is possible for multiple UDP listeners that listen on the same // UDP port to join the same multicast group. The net package will // provide a socket that listens to a wildcard address with reusable // UDP port when an appropriate multicast address prefix is passed to // the net.ListenPacket or net.ListenUDP. // // c1, err := net.ListenPacket("udp6", "[ff02::]:1024") // if err != nil { // // error handling // } // defer c1.Close() // c2, err := net.ListenPacket("udp6", "[ff02::]:1024") // if err != nil { // // error handling // } // defer c2.Close() // p1 := ipv6.NewPacketConn(c1) // if err := p1.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { // // error handling // } // p2 := ipv6.NewPacketConn(c2) // if err := p2.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { // // error handling // } // // Also it is possible for the application to leave or rejoin a // multicast group on the network interface. // // if err := p.LeaveGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { // // error handling // } // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff01::114")}); err != nil { // // error handling // } // // // Source-specific multicasting // // An application that uses PacketConn on MLDv2 supported platform is // able to join source-specific multicast groups. // The application may use JoinSourceSpecificGroup and // LeaveSourceSpecificGroup for the operation known as "include" mode, // // ssmgroup := net.UDPAddr{IP: net.ParseIP("ff32::8000:9")} // ssmsource := net.UDPAddr{IP: net.ParseIP("fe80::cafe")} // if err := p.JoinSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { // // error handling // } // if err := p.LeaveSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { // // error handling // } // // or JoinGroup, ExcludeSourceSpecificGroup, // IncludeSourceSpecificGroup and LeaveGroup for the operation known // as "exclude" mode. // // exclsource := net.UDPAddr{IP: net.ParseIP("fe80::dead")} // if err := p.JoinGroup(en0, &ssmgroup); err != nil { // // error handling // } // if err := p.ExcludeSourceSpecificGroup(en0, &ssmgroup, &exclsource); err != nil { // // error handling // } // if err := p.LeaveGroup(en0, &ssmgroup); err != nil { // // error handling // } // // Note that it depends on each platform implementation what happens // when an application which runs on MLDv2 unsupported platform uses // JoinSourceSpecificGroup and LeaveSourceSpecificGroup. // In general the platform tries to fall back to conversations using // MLDv1 and starts to listen to multicast traffic. // In the fallback case, ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup may return an error. package ipv6 // import "golang.org/x/net/ipv6" // BUG(mikio): This package is not implemented on NaCl and Plan 9. lxd-2.0.11/dist/src/golang.org/x/net/ipv6/dgramopt.go0000644061062106075000000001677613172163402023364 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "net" "syscall" "golang.org/x/net/bpf" ) // MulticastHopLimit returns the hop limit field value for outgoing // multicast packets. func (c *dgramOpt) MulticastHopLimit() (int, error) { if !c.ok() { return 0, syscall.EINVAL } so, ok := sockOpts[ssoMulticastHopLimit] if !ok { return 0, errOpNoSupport } return so.GetInt(c.Conn) } // SetMulticastHopLimit sets the hop limit field value for future // outgoing multicast packets. func (c *dgramOpt) SetMulticastHopLimit(hoplim int) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoMulticastHopLimit] if !ok { return errOpNoSupport } return so.SetInt(c.Conn, hoplim) } // MulticastInterface returns the default interface for multicast // packet transmissions. func (c *dgramOpt) MulticastInterface() (*net.Interface, error) { if !c.ok() { return nil, syscall.EINVAL } so, ok := sockOpts[ssoMulticastInterface] if !ok { return nil, errOpNoSupport } return so.getMulticastInterface(c.Conn) } // SetMulticastInterface sets the default interface for future // multicast packet transmissions. func (c *dgramOpt) SetMulticastInterface(ifi *net.Interface) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoMulticastInterface] if !ok { return errOpNoSupport } return so.setMulticastInterface(c.Conn, ifi) } // MulticastLoopback reports whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) MulticastLoopback() (bool, error) { if !c.ok() { return false, syscall.EINVAL } so, ok := sockOpts[ssoMulticastLoopback] if !ok { return false, errOpNoSupport } on, err := so.GetInt(c.Conn) if err != nil { return false, err } return on == 1, nil } // SetMulticastLoopback sets whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) SetMulticastLoopback(on bool) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoMulticastLoopback] if !ok { return errOpNoSupport } return so.SetInt(c.Conn, boolint(on)) } // JoinGroup joins the group address group on the interface ifi. // By default all sources that can cast data to group are accepted. // It's possible to mute and unmute data transmission from a specific // source by using ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup. // JoinGroup uses the system assigned multicast interface when ifi is // nil, although this is not recommended because the assignment // depends on platforms and sometimes it might require routing // configuration. func (c *dgramOpt) JoinGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoJoinGroup] if !ok { return errOpNoSupport } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } return so.setGroup(c.Conn, ifi, grp) } // LeaveGroup leaves the group address group on the interface ifi // regardless of whether the group is any-source group or // source-specific group. func (c *dgramOpt) LeaveGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoLeaveGroup] if !ok { return errOpNoSupport } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } return so.setGroup(c.Conn, ifi, grp) } // JoinSourceSpecificGroup joins the source-specific group comprising // group and source on the interface ifi. // JoinSourceSpecificGroup uses the system assigned multicast // interface when ifi is nil, although this is not recommended because // the assignment depends on platforms and sometimes it might require // routing configuration. func (c *dgramOpt) JoinSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoJoinSourceGroup] if !ok { return errOpNoSupport } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } src := netAddrToIP16(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // LeaveSourceSpecificGroup leaves the source-specific group on the // interface ifi. func (c *dgramOpt) LeaveSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoLeaveSourceGroup] if !ok { return errOpNoSupport } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } src := netAddrToIP16(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // ExcludeSourceSpecificGroup excludes the source-specific group from // the already joined any-source groups by JoinGroup on the interface // ifi. func (c *dgramOpt) ExcludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoBlockSourceGroup] if !ok { return errOpNoSupport } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } src := netAddrToIP16(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // IncludeSourceSpecificGroup includes the excluded source-specific // group by ExcludeSourceSpecificGroup again on the interface ifi. func (c *dgramOpt) IncludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoUnblockSourceGroup] if !ok { return errOpNoSupport } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } src := netAddrToIP16(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // Checksum reports whether the kernel will compute, store or verify a // checksum for both incoming and outgoing packets. If on is true, it // returns an offset in bytes into the data of where the checksum // field is located. func (c *dgramOpt) Checksum() (on bool, offset int, err error) { if !c.ok() { return false, 0, syscall.EINVAL } so, ok := sockOpts[ssoChecksum] if !ok { return false, 0, errOpNoSupport } offset, err = so.GetInt(c.Conn) if err != nil { return false, 0, err } if offset < 0 { return false, 0, nil } return true, offset, nil } // SetChecksum enables the kernel checksum processing. If on is ture, // the offset should be an offset in bytes into the data of where the // checksum field is located. func (c *dgramOpt) SetChecksum(on bool, offset int) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoChecksum] if !ok { return errOpNoSupport } if !on { offset = -1 } return so.SetInt(c.Conn, offset) } // ICMPFilter returns an ICMP filter. func (c *dgramOpt) ICMPFilter() (*ICMPFilter, error) { if !c.ok() { return nil, syscall.EINVAL } so, ok := sockOpts[ssoICMPFilter] if !ok { return nil, errOpNoSupport } return so.getICMPFilter(c.Conn) } // SetICMPFilter deploys the ICMP filter. func (c *dgramOpt) SetICMPFilter(f *ICMPFilter) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoICMPFilter] if !ok { return errOpNoSupport } return so.setICMPFilter(c.Conn, f) } // SetBPF attaches a BPF program to the connection. // // Only supported on Linux. func (c *dgramOpt) SetBPF(filter []bpf.RawInstruction) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoAttachFilter] if !ok { return errOpNoSupport } return so.setBPF(c.Conn, filter) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/defs_solaris.go0000644061062106075000000000676313172163402024217 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVRTHDRDSTOPTS = C.IPV6_RECVRTHDRDSTOPTS sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_SEC_OPT = C.IPV6_SEC_OPT sysIPV6_SRC_PREFERENCES = C.IPV6_SRC_PREFERENCES sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysIPV6_PREFER_SRC_HOME = C.IPV6_PREFER_SRC_HOME sysIPV6_PREFER_SRC_COA = C.IPV6_PREFER_SRC_COA sysIPV6_PREFER_SRC_PUBLIC = C.IPV6_PREFER_SRC_PUBLIC sysIPV6_PREFER_SRC_TMP = C.IPV6_PREFER_SRC_TMP sysIPV6_PREFER_SRC_NONCGA = C.IPV6_PREFER_SRC_NONCGA sysIPV6_PREFER_SRC_CGA = C.IPV6_PREFER_SRC_CGA sysIPV6_PREFER_SRC_MIPMASK = C.IPV6_PREFER_SRC_MIPMASK sysIPV6_PREFER_SRC_MIPDEFAULT = C.IPV6_PREFER_SRC_MIPDEFAULT sysIPV6_PREFER_SRC_TMPMASK = C.IPV6_PREFER_SRC_TMPMASK sysIPV6_PREFER_SRC_TMPDEFAULT = C.IPV6_PREFER_SRC_TMPDEFAULT sysIPV6_PREFER_SRC_CGAMASK = C.IPV6_PREFER_SRC_CGAMASK sysIPV6_PREFER_SRC_CGADEFAULT = C.IPV6_PREFER_SRC_CGADEFAULT sysIPV6_PREFER_SRC_MASK = C.IPV6_PREFER_SRC_MASK sysIPV6_PREFER_SRC_DEFAULT = C.IPV6_PREFER_SRC_DEFAULT sysIPV6_BOUND_IF = C.IPV6_BOUND_IF sysIPV6_UNSPEC_SRC = C.IPV6_UNSPEC_SRC sysICMP6_FILTER = C.ICMP6_FILTER sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sizeofGroupReq = C.sizeof_struct_group_req sizeofGroupSourceReq = C.sizeof_struct_group_source_req sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sockaddrStorage C.struct_sockaddr_storage type sockaddrInet6 C.struct_sockaddr_in6 type inet6Pktinfo C.struct_in6_pktinfo type ipv6Mtuinfo C.struct_ip6_mtuinfo type ipv6Mreq C.struct_ipv6_mreq type groupReq C.struct_group_req type groupSourceReq C.struct_group_source_req type icmpv6Filter C.struct_icmp6_filter lxd-2.0.11/dist/src/golang.org/x/net/ipv6/defs_openbsd.go0000644061062106075000000000465313172163402024171 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_AUTH_LEVEL = C.IPV6_AUTH_LEVEL sysIPV6_ESP_TRANS_LEVEL = C.IPV6_ESP_TRANS_LEVEL sysIPV6_ESP_NETWORK_LEVEL = C.IPV6_ESP_NETWORK_LEVEL sysIPSEC6_OUTSA = C.IPSEC6_OUTSA sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL sysIPV6_IPCOMP_LEVEL = C.IPV6_IPCOMP_LEVEL sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PIPEX = C.IPV6_PIPEX sysIPV6_RTABLE = C.IPV6_RTABLE sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sockaddrInet6 C.struct_sockaddr_in6 type inet6Pktinfo C.struct_in6_pktinfo type ipv6Mtuinfo C.struct_ip6_mtuinfo type ipv6Mreq C.struct_ipv6_mreq type icmpv6Filter C.struct_icmp6_filter lxd-2.0.11/dist/src/golang.org/x/net/ipv6/defs_netbsd.go0000644061062106075000000000416113172163402024010 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sockaddrInet6 C.struct_sockaddr_in6 type inet6Pktinfo C.struct_in6_pktinfo type ipv6Mtuinfo C.struct_ip6_mtuinfo type ipv6Mreq C.struct_ipv6_mreq type icmpv6Filter C.struct_icmp6_filter lxd-2.0.11/dist/src/golang.org/x/net/ipv6/defs_linux.go0000644061062106075000000001201713172163402023667 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include #include #include */ import "C" const ( sysIPV6_ADDRFORM = C.IPV6_ADDRFORM sysIPV6_2292PKTINFO = C.IPV6_2292PKTINFO sysIPV6_2292HOPOPTS = C.IPV6_2292HOPOPTS sysIPV6_2292DSTOPTS = C.IPV6_2292DSTOPTS sysIPV6_2292RTHDR = C.IPV6_2292RTHDR sysIPV6_2292PKTOPTIONS = C.IPV6_2292PKTOPTIONS sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_2292HOPLIMIT = C.IPV6_2292HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_FLOWINFO = C.IPV6_FLOWINFO sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_ADD_MEMBERSHIP = C.IPV6_ADD_MEMBERSHIP sysIPV6_DROP_MEMBERSHIP = C.IPV6_DROP_MEMBERSHIP sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysMCAST_MSFILTER = C.MCAST_MSFILTER sysIPV6_ROUTER_ALERT = C.IPV6_ROUTER_ALERT sysIPV6_MTU_DISCOVER = C.IPV6_MTU_DISCOVER sysIPV6_MTU = C.IPV6_MTU sysIPV6_RECVERR = C.IPV6_RECVERR sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_JOIN_ANYCAST = C.IPV6_JOIN_ANYCAST sysIPV6_LEAVE_ANYCAST = C.IPV6_LEAVE_ANYCAST //sysIPV6_PMTUDISC_DONT = C.IPV6_PMTUDISC_DONT //sysIPV6_PMTUDISC_WANT = C.IPV6_PMTUDISC_WANT //sysIPV6_PMTUDISC_DO = C.IPV6_PMTUDISC_DO //sysIPV6_PMTUDISC_PROBE = C.IPV6_PMTUDISC_PROBE //sysIPV6_PMTUDISC_INTERFACE = C.IPV6_PMTUDISC_INTERFACE //sysIPV6_PMTUDISC_OMIT = C.IPV6_PMTUDISC_OMIT sysIPV6_FLOWLABEL_MGR = C.IPV6_FLOWLABEL_MGR sysIPV6_FLOWINFO_SEND = C.IPV6_FLOWINFO_SEND sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_XFRM_POLICY = C.IPV6_XFRM_POLICY sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_ADDR_PREFERENCES = C.IPV6_ADDR_PREFERENCES sysIPV6_PREFER_SRC_TMP = C.IPV6_PREFER_SRC_TMP sysIPV6_PREFER_SRC_PUBLIC = C.IPV6_PREFER_SRC_PUBLIC sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = C.IPV6_PREFER_SRC_PUBTMP_DEFAULT sysIPV6_PREFER_SRC_COA = C.IPV6_PREFER_SRC_COA sysIPV6_PREFER_SRC_HOME = C.IPV6_PREFER_SRC_HOME sysIPV6_PREFER_SRC_CGA = C.IPV6_PREFER_SRC_CGA sysIPV6_PREFER_SRC_NONCGA = C.IPV6_PREFER_SRC_NONCGA sysIPV6_MINHOPCOUNT = C.IPV6_MINHOPCOUNT sysIPV6_ORIGDSTADDR = C.IPV6_ORIGDSTADDR sysIPV6_RECVORIGDSTADDR = C.IPV6_RECVORIGDSTADDR sysIPV6_TRANSPARENT = C.IPV6_TRANSPARENT sysIPV6_UNICAST_IF = C.IPV6_UNICAST_IF sysICMPV6_FILTER = C.ICMPV6_FILTER sysICMPV6_FILTER_BLOCK = C.ICMPV6_FILTER_BLOCK sysICMPV6_FILTER_PASS = C.ICMPV6_FILTER_PASS sysICMPV6_FILTER_BLOCKOTHERS = C.ICMPV6_FILTER_BLOCKOTHERS sysICMPV6_FILTER_PASSONLY = C.ICMPV6_FILTER_PASSONLY sysSOL_SOCKET = C.SOL_SOCKET sysSO_ATTACH_FILTER = C.SO_ATTACH_FILTER sizeofKernelSockaddrStorage = C.sizeof_struct___kernel_sockaddr_storage sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sizeofIPv6FlowlabelReq = C.sizeof_struct_in6_flowlabel_req sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sizeofGroupReq = C.sizeof_struct_group_req sizeofGroupSourceReq = C.sizeof_struct_group_source_req sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter sizeofSockFprog = C.sizeof_struct_sock_fprog ) type kernelSockaddrStorage C.struct___kernel_sockaddr_storage type sockaddrInet6 C.struct_sockaddr_in6 type inet6Pktinfo C.struct_in6_pktinfo type ipv6Mtuinfo C.struct_ip6_mtuinfo type ipv6FlowlabelReq C.struct_in6_flowlabel_req type ipv6Mreq C.struct_ipv6_mreq type groupReq C.struct_group_req type groupSourceReq C.struct_group_source_req type icmpv6Filter C.struct_icmp6_filter type sockFProg C.struct_sock_fprog type sockFilter C.struct_sock_filter lxd-2.0.11/dist/src/golang.org/x/net/ipv6/defs_freebsd.go0000644061062106075000000000561513172163402024150 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR sysIPV6_BINDANY = C.IPV6_BINDANY sysIPV6_MSFILTER = C.IPV6_MSFILTER sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sizeofGroupReq = C.sizeof_struct_group_req sizeofGroupSourceReq = C.sizeof_struct_group_source_req sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sockaddrStorage C.struct_sockaddr_storage type sockaddrInet6 C.struct_sockaddr_in6 type inet6Pktinfo C.struct_in6_pktinfo type ipv6Mtuinfo C.struct_ip6_mtuinfo type ipv6Mreq C.struct_ipv6_mreq type groupReq C.struct_group_req type groupSourceReq C.struct_group_source_req type icmpv6Filter C.struct_icmp6_filter lxd-2.0.11/dist/src/golang.org/x/net/ipv6/defs_dragonfly.go0000644061062106075000000000431713172163402024521 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sockaddrInet6 C.struct_sockaddr_in6 type inet6Pktinfo C.struct_in6_pktinfo type ipv6Mtuinfo C.struct_ip6_mtuinfo type ipv6Mreq C.struct_ipv6_mreq type icmpv6Filter C.struct_icmp6_filter lxd-2.0.11/dist/src/golang.org/x/net/ipv6/defs_darwin.go0000644061062106075000000000626713172163402024026 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #define __APPLE_USE_RFC_3542 #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_2292PKTINFO = C.IPV6_2292PKTINFO sysIPV6_2292HOPLIMIT = C.IPV6_2292HOPLIMIT sysIPV6_2292NEXTHOP = C.IPV6_2292NEXTHOP sysIPV6_2292HOPOPTS = C.IPV6_2292HOPOPTS sysIPV6_2292DSTOPTS = C.IPV6_2292DSTOPTS sysIPV6_2292RTHDR = C.IPV6_2292RTHDR sysIPV6_2292PKTOPTIONS = C.IPV6_2292PKTOPTIONS sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR sysIPV6_MSFILTER = C.IPV6_MSFILTER sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysIPV6_BOUND_IF = C.IPV6_BOUND_IF sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sizeofGroupReq = C.sizeof_struct_group_req sizeofGroupSourceReq = C.sizeof_struct_group_source_req sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sockaddrStorage C.struct_sockaddr_storage type sockaddrInet6 C.struct_sockaddr_in6 type inet6Pktinfo C.struct_in6_pktinfo type ipv6Mtuinfo C.struct_ip6_mtuinfo type ipv6Mreq C.struct_ipv6_mreq type icmpv6Filter C.struct_icmp6_filter type groupReq C.struct_group_req type groupSourceReq C.struct_group_source_req lxd-2.0.11/dist/src/golang.org/x/net/ipv6/control_windows.go0000644061062106075000000000057313172163402024765 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "syscall" "golang.org/x/net/internal/socket" ) func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { // TODO(mikio): implement this return syscall.EWINDOWS } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/control_unix.go0000644061062106075000000000247013172163402024254 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package ipv6 import "golang.org/x/net/internal/socket" func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { opt.Lock() defer opt.Unlock() if so, ok := sockOpts[ssoReceiveTrafficClass]; ok && cf&FlagTrafficClass != 0 { if err := so.SetInt(c, boolint(on)); err != nil { return err } if on { opt.set(FlagTrafficClass) } else { opt.clear(FlagTrafficClass) } } if so, ok := sockOpts[ssoReceiveHopLimit]; ok && cf&FlagHopLimit != 0 { if err := so.SetInt(c, boolint(on)); err != nil { return err } if on { opt.set(FlagHopLimit) } else { opt.clear(FlagHopLimit) } } if so, ok := sockOpts[ssoReceivePacketInfo]; ok && cf&flagPacketInfo != 0 { if err := so.SetInt(c, boolint(on)); err != nil { return err } if on { opt.set(cf & flagPacketInfo) } else { opt.clear(cf & flagPacketInfo) } } if so, ok := sockOpts[ssoReceivePathMTU]; ok && cf&FlagPathMTU != 0 { if err := so.SetInt(c, boolint(on)); err != nil { return err } if on { opt.set(FlagPathMTU) } else { opt.clear(FlagPathMTU) } } return nil } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/control_test.go0000644061062106075000000000072413172163402024250 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "testing" "golang.org/x/net/ipv6" ) func TestControlMessageParseWithFuzz(t *testing.T) { var cm ipv6.ControlMessage for _, fuzz := range []string{ "\f\x00\x00\x00)\x00\x00\x00.\x00\x00\x00", "\f\x00\x00\x00)\x00\x00\x00,\x00\x00\x00", } { cm.Parse([]byte(fuzz)) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/control_stub.go0000644061062106075000000000063113172163402024243 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package ipv6 import "golang.org/x/net/internal/socket" func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/control_rfc3542_unix.go0000644061062106075000000000503113172163402025420 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package ipv6 import ( "net" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) func marshalTrafficClass(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_TCLASS, 4) if cm != nil { socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.TrafficClass)) } return m.Next(4) } func parseTrafficClass(cm *ControlMessage, b []byte) { cm.TrafficClass = int(socket.NativeEndian.Uint32(b[:4])) } func marshalHopLimit(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_HOPLIMIT, 4) if cm != nil { socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.HopLimit)) } return m.Next(4) } func parseHopLimit(cm *ControlMessage, b []byte) { cm.HopLimit = int(socket.NativeEndian.Uint32(b[:4])) } func marshalPacketInfo(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_PKTINFO, sizeofInet6Pktinfo) if cm != nil { pi := (*inet6Pktinfo)(unsafe.Pointer(&m.Data(sizeofInet6Pktinfo)[0])) if ip := cm.Src.To16(); ip != nil && ip.To4() == nil { copy(pi.Addr[:], ip) } if cm.IfIndex > 0 { pi.setIfindex(cm.IfIndex) } } return m.Next(sizeofInet6Pktinfo) } func parsePacketInfo(cm *ControlMessage, b []byte) { pi := (*inet6Pktinfo)(unsafe.Pointer(&b[0])) if len(cm.Dst) < net.IPv6len { cm.Dst = make(net.IP, net.IPv6len) } copy(cm.Dst, pi.Addr[:]) cm.IfIndex = int(pi.Ifindex) } func marshalNextHop(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_NEXTHOP, sizeofSockaddrInet6) if cm != nil { sa := (*sockaddrInet6)(unsafe.Pointer(&m.Data(sizeofSockaddrInet6)[0])) sa.setSockaddr(cm.NextHop, cm.IfIndex) } return m.Next(sizeofSockaddrInet6) } func parseNextHop(cm *ControlMessage, b []byte) { } func marshalPathMTU(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_PATHMTU, sizeofIPv6Mtuinfo) return m.Next(sizeofIPv6Mtuinfo) } func parsePathMTU(cm *ControlMessage, b []byte) { mi := (*ipv6Mtuinfo)(unsafe.Pointer(&b[0])) if len(cm.Dst) < net.IPv6len { cm.Dst = make(net.IP, net.IPv6len) } copy(cm.Dst, mi.Addr.Addr[:]) cm.IfIndex = int(mi.Addr.Scope_id) cm.MTU = int(mi.Mtu) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/control_rfc2292_unix.go0000644061062106075000000000246413172163402025430 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin package ipv6 import ( "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) func marshal2292HopLimit(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_2292HOPLIMIT, 4) if cm != nil { socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.HopLimit)) } return m.Next(4) } func marshal2292PacketInfo(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_2292PKTINFO, sizeofInet6Pktinfo) if cm != nil { pi := (*inet6Pktinfo)(unsafe.Pointer(&m.Data(sizeofInet6Pktinfo)[0])) if ip := cm.Src.To16(); ip != nil && ip.To4() == nil { copy(pi.Addr[:], ip) } if cm.IfIndex > 0 { pi.setIfindex(cm.IfIndex) } } return m.Next(sizeofInet6Pktinfo) } func marshal2292NextHop(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_2292NEXTHOP, sizeofSockaddrInet6) if cm != nil { sa := (*sockaddrInet6)(unsafe.Pointer(&m.Data(sizeofSockaddrInet6)[0])) sa.setSockaddr(cm.NextHop, cm.IfIndex) } return m.Next(sizeofSockaddrInet6) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/control.go0000644061062106075000000001361213172163402023211 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6 import ( "fmt" "net" "sync" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) // Note that RFC 3542 obsoletes RFC 2292 but OS X Snow Leopard and the // former still support RFC 2292 only. Please be aware that almost // all protocol implementations prohibit using a combination of RFC // 2292 and RFC 3542 for some practical reasons. type rawOpt struct { sync.RWMutex cflags ControlFlags } func (c *rawOpt) set(f ControlFlags) { c.cflags |= f } func (c *rawOpt) clear(f ControlFlags) { c.cflags &^= f } func (c *rawOpt) isset(f ControlFlags) bool { return c.cflags&f != 0 } // A ControlFlags represents per packet basis IP-level socket option // control flags. type ControlFlags uint const ( FlagTrafficClass ControlFlags = 1 << iota // pass the traffic class on the received packet FlagHopLimit // pass the hop limit on the received packet FlagSrc // pass the source address on the received packet FlagDst // pass the destination address on the received packet FlagInterface // pass the interface index on the received packet FlagPathMTU // pass the path MTU on the received packet path ) const flagPacketInfo = FlagDst | FlagInterface // A ControlMessage represents per packet basis IP-level socket // options. type ControlMessage struct { // Receiving socket options: SetControlMessage allows to // receive the options from the protocol stack using ReadFrom // method of PacketConn. // // Specifying socket options: ControlMessage for WriteTo // method of PacketConn allows to send the options to the // protocol stack. // TrafficClass int // traffic class, must be 1 <= value <= 255 when specifying HopLimit int // hop limit, must be 1 <= value <= 255 when specifying Src net.IP // source address, specifying only Dst net.IP // destination address, receiving only IfIndex int // interface index, must be 1 <= value when specifying NextHop net.IP // next hop address, specifying only MTU int // path MTU, receiving only } func (cm *ControlMessage) String() string { if cm == nil { return "" } return fmt.Sprintf("tclass=%#x hoplim=%d src=%v dst=%v ifindex=%d nexthop=%v mtu=%d", cm.TrafficClass, cm.HopLimit, cm.Src, cm.Dst, cm.IfIndex, cm.NextHop, cm.MTU) } // Marshal returns the binary encoding of cm. func (cm *ControlMessage) Marshal() []byte { if cm == nil { return nil } var l int tclass := false if ctlOpts[ctlTrafficClass].name > 0 && cm.TrafficClass > 0 { tclass = true l += socket.ControlMessageSpace(ctlOpts[ctlTrafficClass].length) } hoplimit := false if ctlOpts[ctlHopLimit].name > 0 && cm.HopLimit > 0 { hoplimit = true l += socket.ControlMessageSpace(ctlOpts[ctlHopLimit].length) } pktinfo := false if ctlOpts[ctlPacketInfo].name > 0 && (cm.Src.To16() != nil && cm.Src.To4() == nil || cm.IfIndex > 0) { pktinfo = true l += socket.ControlMessageSpace(ctlOpts[ctlPacketInfo].length) } nexthop := false if ctlOpts[ctlNextHop].name > 0 && cm.NextHop.To16() != nil && cm.NextHop.To4() == nil { nexthop = true l += socket.ControlMessageSpace(ctlOpts[ctlNextHop].length) } var b []byte if l > 0 { b = make([]byte, l) bb := b if tclass { bb = ctlOpts[ctlTrafficClass].marshal(bb, cm) } if hoplimit { bb = ctlOpts[ctlHopLimit].marshal(bb, cm) } if pktinfo { bb = ctlOpts[ctlPacketInfo].marshal(bb, cm) } if nexthop { bb = ctlOpts[ctlNextHop].marshal(bb, cm) } } return b } // Parse parses b as a control message and stores the result in cm. func (cm *ControlMessage) Parse(b []byte) error { ms, err := socket.ControlMessage(b).Parse() if err != nil { return err } for _, m := range ms { lvl, typ, l, err := m.ParseHeader() if err != nil { return err } if lvl != iana.ProtocolIPv6 { continue } switch { case typ == ctlOpts[ctlTrafficClass].name && l >= ctlOpts[ctlTrafficClass].length: ctlOpts[ctlTrafficClass].parse(cm, m.Data(l)) case typ == ctlOpts[ctlHopLimit].name && l >= ctlOpts[ctlHopLimit].length: ctlOpts[ctlHopLimit].parse(cm, m.Data(l)) case typ == ctlOpts[ctlPacketInfo].name && l >= ctlOpts[ctlPacketInfo].length: ctlOpts[ctlPacketInfo].parse(cm, m.Data(l)) case typ == ctlOpts[ctlPathMTU].name && l >= ctlOpts[ctlPathMTU].length: ctlOpts[ctlPathMTU].parse(cm, m.Data(l)) } } return nil } // NewControlMessage returns a new control message. // // The returned message is large enough for options specified by cf. func NewControlMessage(cf ControlFlags) []byte { opt := rawOpt{cflags: cf} var l int if opt.isset(FlagTrafficClass) && ctlOpts[ctlTrafficClass].name > 0 { l += socket.ControlMessageSpace(ctlOpts[ctlTrafficClass].length) } if opt.isset(FlagHopLimit) && ctlOpts[ctlHopLimit].name > 0 { l += socket.ControlMessageSpace(ctlOpts[ctlHopLimit].length) } if opt.isset(flagPacketInfo) && ctlOpts[ctlPacketInfo].name > 0 { l += socket.ControlMessageSpace(ctlOpts[ctlPacketInfo].length) } if opt.isset(FlagPathMTU) && ctlOpts[ctlPathMTU].name > 0 { l += socket.ControlMessageSpace(ctlOpts[ctlPathMTU].length) } var b []byte if l > 0 { b = make([]byte, l) } return b } // Ancillary data socket options const ( ctlTrafficClass = iota // header field ctlHopLimit // header field ctlPacketInfo // inbound or outbound packet path ctlNextHop // nexthop ctlPathMTU // path mtu ctlMax ) // A ctlOpt represents a binding for ancillary data socket option. type ctlOpt struct { name int // option name, must be equal or greater than 1 length int // option length marshal func([]byte, *ControlMessage) []byte parse func(*ControlMessage, []byte) } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/bpf_test.go0000644061062106075000000000364013172163402023337 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv6_test import ( "net" "runtime" "testing" "time" "golang.org/x/net/bpf" "golang.org/x/net/ipv6" ) func TestBPF(t *testing.T) { if runtime.GOOS != "linux" { t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } l, err := net.ListenPacket("udp6", "[::1]:0") if err != nil { t.Fatal(err) } defer l.Close() p := ipv6.NewPacketConn(l) // This filter accepts UDP packets whose first payload byte is // even. prog, err := bpf.Assemble([]bpf.Instruction{ // Load the first byte of the payload (skipping UDP header). bpf.LoadAbsolute{Off: 8, Size: 1}, // Select LSB of the byte. bpf.ALUOpConstant{Op: bpf.ALUOpAnd, Val: 1}, // Byte is even? bpf.JumpIf{Cond: bpf.JumpEqual, Val: 0, SkipFalse: 1}, // Accept. bpf.RetConstant{Val: 4096}, // Ignore. bpf.RetConstant{Val: 0}, }) if err != nil { t.Fatalf("compiling BPF: %s", err) } if err = p.SetBPF(prog); err != nil { t.Fatalf("attaching filter to Conn: %s", err) } s, err := net.Dial("udp6", l.LocalAddr().String()) if err != nil { t.Fatal(err) } defer s.Close() go func() { for i := byte(0); i < 10; i++ { s.Write([]byte{i}) } }() l.SetDeadline(time.Now().Add(2 * time.Second)) seen := make([]bool, 5) for { var b [512]byte n, _, err := l.ReadFrom(b[:]) if err != nil { t.Fatalf("reading from listener: %s", err) } if n != 1 { t.Fatalf("unexpected packet length, want 1, got %d", n) } if b[0] >= 10 { t.Fatalf("unexpected byte, want 0-9, got %d", b[0]) } if b[0]%2 != 0 { t.Fatalf("got odd byte %d, wanted only even bytes", b[0]) } seen[b[0]/2] = true seenAll := true for _, v := range seen { if !v { seenAll = false break } } if seenAll { break } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv6/batch.go0000644061062106075000000000653113172163402022614 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package ipv6 import ( "net" "runtime" "syscall" "golang.org/x/net/internal/socket" ) // BUG(mikio): On Windows, the ReadBatch and WriteBatch methods of // PacketConn are not implemented. // A Message represents an IO message. // // type Message struct { // Buffers [][]byte // OOB []byte // Addr net.Addr // N int // NN int // Flags int // } // // The Buffers fields represents a list of contiguous buffers, which // can be used for vectored IO, for example, putting a header and a // payload in each slice. // When writing, the Buffers field must contain at least one byte to // write. // When reading, the Buffers field will always contain a byte to read. // // The OOB field contains protocol-specific control or miscellaneous // ancillary data known as out-of-band data. // It can be nil when not required. // // The Addr field specifies a destination address when writing. // It can be nil when the underlying protocol of the endpoint uses // connection-oriented communication. // After a successful read, it may contain the source address on the // received packet. // // The N field indicates the number of bytes read or written from/to // Buffers. // // The NN field indicates the number of bytes read or written from/to // OOB. // // The Flags field contains protocol-specific information on the // received message. type Message = socket.Message // ReadBatch reads a batch of messages. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_PEEK. // // On a successful read it returns the number of messages received, up // to len(ms). // // On Linux, a batch read will be optimized. // On other platforms, this method will read only a single message. func (c *payloadHandler) ReadBatch(ms []Message, flags int) (int, error) { if !c.ok() { return 0, syscall.EINVAL } switch runtime.GOOS { case "linux": n, err := c.RecvMsgs([]socket.Message(ms), flags) if err != nil { err = &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } return n, err default: n := 1 err := c.RecvMsg(&ms[0], flags) if err != nil { n = 0 err = &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } return n, err } } // WriteBatch writes a batch of messages. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_DONTROUTE. // // It returns the number of messages written on a successful write. // // On Linux, a batch write will be optimized. // On other platforms, this method will write only a single message. func (c *payloadHandler) WriteBatch(ms []Message, flags int) (int, error) { if !c.ok() { return 0, syscall.EINVAL } switch runtime.GOOS { case "linux": n, err := c.SendMsgs([]socket.Message(ms), flags) if err != nil { err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } return n, err default: n := 1 err := c.SendMsg(&ms[0], flags) if err != nil { n = 0 err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } return n, err } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/0000755061062106075000000000000013172163402021175 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_solaris.go0000644061062106075000000000414013172163402024267 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_solaris.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x9 sysIP_RECVSLLA = 0xa sysIP_RECVTTL = 0xb sysIP_MULTICAST_IF = 0x10 sysIP_MULTICAST_TTL = 0x11 sysIP_MULTICAST_LOOP = 0x12 sysIP_ADD_MEMBERSHIP = 0x13 sysIP_DROP_MEMBERSHIP = 0x14 sysIP_BLOCK_SOURCE = 0x15 sysIP_UNBLOCK_SOURCE = 0x16 sysIP_ADD_SOURCE_MEMBERSHIP = 0x17 sysIP_DROP_SOURCE_MEMBERSHIP = 0x18 sysIP_NEXTHOP = 0x19 sysIP_PKTINFO = 0x1a sysIP_RECVPKTINFO = 0x1a sysIP_DONTFRAG = 0x1b sysIP_BOUND_IF = 0x41 sysIP_UNSPEC_SRC = 0x42 sysIP_BROADCAST_TTL = 0x43 sysIP_DHCPINIT_IF = 0x45 sysIP_REUSEADDR = 0x104 sysIP_DONTROUTE = 0x105 sysIP_BROADCAST = 0x106 sysMCAST_JOIN_GROUP = 0x29 sysMCAST_LEAVE_GROUP = 0x2a sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_JOIN_SOURCE_GROUP = 0x2d sysMCAST_LEAVE_SOURCE_GROUP = 0x2e sizeofSockaddrStorage = 0x100 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofIPMreq = 0x8 sizeofIPMreqSource = 0xc sizeofGroupReq = 0x104 sizeofGroupSourceReq = 0x204 ) type sockaddrStorage struct { Family uint16 X_ss_pad1 [6]int8 X_ss_align float64 X_ss_pad2 [240]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type inetPktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type groupReq struct { Interface uint32 Pad_cgo_0 [256]byte } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [256]byte Pad_cgo_1 [256]byte } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_openbsd.go0000644061062106075000000000113513172163402024246 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x1e sysIP_RECVTTL = 0x1f sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sizeofIPMreq = 0x8 ) type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_netbsd.go0000644061062106075000000000113413172163402024072 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_netbsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_RECVTTL = 0x17 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sizeofIPMreq = 0x8 ) type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_s390x.go0000644061062106075000000000616113172163402024725 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_ppc64le.go0000644061062106075000000000616113172163402025314 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_ppc64.go0000644061062106075000000000616113172163402024773 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_ppc.go0000644061062106075000000000611313172163402024616 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]uint8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_mipsle.go0000644061062106075000000000611213172163402025324 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_mips64le.go0000644061062106075000000000616113172163402025502 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_mips64.go0000644061062106075000000000616113172163402025161 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_mips.go0000644061062106075000000000611213172163402025003 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_arm64.go0000644061062106075000000000616113172163402024770 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_arm.go0000644061062106075000000000611213172163402024612 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_amd64.go0000644061062106075000000000616113172163402024752 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_linux_386.go0000644061062106075000000000611213172163402024353 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x8 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_freebsd_arm.go0000644061062106075000000000405313172163402025067 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_SENDSRCADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_ONESBCAST = 0x17 sysIP_BINDANY = 0x18 sysIP_RECVTTL = 0x41 sysIP_MINTTL = 0x42 sysIP_DONTFRAG = 0x43 sysIP_RECVTOS = 0x44 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_MULTICAST_VIF = 0xe sysIP_ADD_SOURCE_MEMBERSHIP = 0x46 sysIP_DROP_SOURCE_MEMBERSHIP = 0x47 sysIP_BLOCK_SOURCE = 0x48 sysIP_UNBLOCK_SOURCE = 0x49 sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sockaddrStorage Source sockaddrStorage } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_freebsd_amd64.go0000644061062106075000000000405313172163402025223 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_SENDSRCADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_ONESBCAST = 0x17 sysIP_BINDANY = 0x18 sysIP_RECVTTL = 0x41 sysIP_MINTTL = 0x42 sysIP_DONTFRAG = 0x43 sysIP_RECVTOS = 0x44 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_MULTICAST_VIF = 0xe sysIP_ADD_SOURCE_MEMBERSHIP = 0x46 sysIP_DROP_SOURCE_MEMBERSHIP = 0x47 sysIP_BLOCK_SOURCE = 0x48 sysIP_UNBLOCK_SOURCE = 0x49 sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sockaddrStorage Source sockaddrStorage } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_freebsd_386.go0000644061062106075000000000400513172163402024625 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_SENDSRCADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_ONESBCAST = 0x17 sysIP_BINDANY = 0x18 sysIP_RECVTTL = 0x41 sysIP_MINTTL = 0x42 sysIP_DONTFRAG = 0x43 sysIP_RECVTOS = 0x44 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_MULTICAST_VIF = 0xe sysIP_ADD_SOURCE_MEMBERSHIP = 0x46 sysIP_DROP_SOURCE_MEMBERSHIP = 0x47 sysIP_BLOCK_SOURCE = 0x48 sysIP_UNBLOCK_SOURCE = 0x49 sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type groupReq struct { Interface uint32 Group sockaddrStorage } type groupSourceReq struct { Interface uint32 Group sockaddrStorage Source sockaddrStorage } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_dragonfly.go0000644061062106075000000000117413172163402024604 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_dragonfly.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_RECVTTL = 0x41 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_MULTICAST_VIF = 0xe sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sizeofIPMreq = 0x8 ) type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/zsys_darwin.go0000644061062106075000000000415713172163402024107 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_darwin.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_STRIPHDR = 0x17 sysIP_RECVTTL = 0x18 sysIP_BOUND_IF = 0x19 sysIP_PKTINFO = 0x1a sysIP_RECVPKTINFO = 0x1a sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_MULTICAST_VIF = 0xe sysIP_MULTICAST_IFINDEX = 0x42 sysIP_ADD_SOURCE_MEMBERSHIP = 0x46 sysIP_DROP_SOURCE_MEMBERSHIP = 0x47 sysIP_BLOCK_SOURCE = 0x48 sysIP_UNBLOCK_SOURCE = 0x49 sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sizeofSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type inetPktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type groupReq struct { Interface uint32 Pad_cgo_0 [128]byte } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [128]byte Pad_cgo_1 [128]byte } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/unicastsockopt_test.go0000644061062106075000000000611313172163402025635 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) func TestConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } ln, err := net.Listen("tcp4", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer ln.Close() errc := make(chan error, 1) go func() { c, err := ln.Accept() if err != nil { errc <- err return } errc <- c.Close() }() c, err := net.Dial("tcp4", ln.Addr().String()) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv4.NewConn(c)) if err := <-errc; err != nil { t.Errorf("server: %v", err) } } var packetConnUnicastSocketOptionTests = []struct { net, proto, addr string }{ {"udp4", "", "127.0.0.1:0"}, {"ip4", ":icmp", "127.0.0.1"}, } func TestPacketConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnUnicastSocketOptionTests { if tt.net == "ip4" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv4.NewPacketConn(c)) } } func TestRawConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := net.ListenPacket("ip4:icmp", "127.0.0.1") if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } testUnicastSocketOptions(t, r) } type testIPv4UnicastConn interface { TOS() (int, error) SetTOS(int) error TTL() (int, error) SetTTL(int) error } func testUnicastSocketOptions(t *testing.T, c testIPv4UnicastConn) { tos := iana.DiffServCS0 | iana.NotECNTransport switch runtime.GOOS { case "windows": // IP_TOS option is supported on Windows 8 and beyond. t.Skipf("not supported on %s", runtime.GOOS) } if err := c.SetTOS(tos); err != nil { t.Fatal(err) } if v, err := c.TOS(); err != nil { t.Fatal(err) } else if v != tos { t.Fatalf("got %v; want %v", v, tos) } const ttl = 255 if err := c.SetTTL(ttl); err != nil { t.Fatal(err) } if v, err := c.TTL(); err != nil { t.Fatal(err) } else if v != ttl { t.Fatalf("got %v; want %v", v, ttl) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/unicast_test.go0000644061062106075000000001433613172163402024240 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "bytes" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) func TestPacketConnReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := nettest.NewLocalPacketListener("udp4") if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) defer p.Close() dst := c.LocalAddr() cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } p.SetTTL(i + 1) if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, err := p.WriteTo(wb, nil, dst); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, _, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; want %v", rb[:n], wb) } } } func TestPacketConnReadWriteUnicastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() dst, err := net.ResolveIPAddr("ip4", "127.0.0.1") if err != nil { t.Fatal(err) } p := ipv4.NewPacketConn(c) defer p.Close() cf := ipv4.FlagDst | ipv4.FlagInterface if runtime.GOOS != "solaris" { // Solaris never allows to modify ICMP properties. cf |= ipv4.FlagTTL } for i, toggle := range []bool{true, false, true} { wb, err := (&icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(nil) if err != nil { t.Fatal(err) } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } p.SetTTL(i + 1) if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, err := p.WriteTo(wb, nil, dst); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) loop: if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, _, _, err := p.ReadFrom(rb); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels have some limitation on receiving icmp packet through raw socket t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } else { m, err := icmp.ParseMessage(iana.ProtocolICMP, rb[:n]) if err != nil { t.Fatal(err) } if runtime.GOOS == "linux" && m.Type == ipv4.ICMPTypeEcho { // On Linux we must handle own sent packets. goto loop } if m.Type != ipv4.ICMPTypeEchoReply || m.Code != 0 { t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv4.ICMPTypeEchoReply, 0) } } } } func TestRawConnReadWriteUnicastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() dst, err := net.ResolveIPAddr("ip4", "127.0.0.1") if err != nil { t.Fatal(err) } r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } defer r.Close() cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface for i, toggle := range []bool{true, false, true} { wb, err := (&icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(nil) if err != nil { t.Fatal(err) } wh := &ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TOS: i + 1, TotalLen: ipv4.HeaderLen + len(wb), TTL: i + 1, Protocol: 1, Dst: dst.IP, } if err := r.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := r.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if err := r.WriteTo(wh, wb, nil); err != nil { t.Fatal(err) } rb := make([]byte, ipv4.HeaderLen+128) loop: if err := r.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if _, b, _, err := r.ReadFrom(rb); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels have some limitation on receiving icmp packet through raw socket t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } else { m, err := icmp.ParseMessage(iana.ProtocolICMP, b) if err != nil { t.Fatal(err) } if runtime.GOOS == "linux" && m.Type == ipv4.ICMPTypeEcho { // On Linux we must handle own sent packets. goto loop } if m.Type != ipv4.ICMPTypeEchoReply || m.Code != 0 { t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv4.ICMPTypeEchoReply, 0) } } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_windows.go0000644061062106075000000000421113172163402024112 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) const ( // See ws2tcpip.h. sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_DONTFRAGMENT = 0xe sysIP_ADD_SOURCE_MEMBERSHIP = 0xf sysIP_DROP_SOURCE_MEMBERSHIP = 0x10 sysIP_PKTINFO = 0x13 sizeofInetPktinfo = 0x8 sizeofIPMreq = 0x8 sizeofIPMreqSource = 0xc ) type inetPktinfo struct { Addr [4]byte Ifindex int32 } type ipMreq struct { Multiaddr [4]byte Interface [4]byte } type ipMreqSource struct { Multiaddr [4]byte Sourceaddr [4]byte Interface [4]byte } // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms738586(v=vs.85).aspx var ( ctlOpts = [ctlMax]ctlOpt{} sockOpts = map[int]*sockOpt{ ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, } ) func (pi *inetPktinfo) setIfindex(i int) { pi.Ifindex = int32(i) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_stub.go0000644061062106075000000000050313172163402023375 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package ipv4 var ( ctlOpts = [ctlMax]ctlOpt{} sockOpts = map[int]*sockOpt{} ) lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_ssmreq_stub.go0000644061062106075000000000077613172163402025003 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!freebsd,!linux,!solaris package ipv4 import ( "net" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setGroupReq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } func (so *sockOpt) setGroupSourceReq(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_ssmreq.go0000644061062106075000000000236113172163402023736 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin freebsd linux solaris package ipv4 import ( "net" "unsafe" "golang.org/x/net/internal/socket" ) var freebsd32o64 bool func (so *sockOpt) setGroupReq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { var gr groupReq if ifi != nil { gr.Interface = uint32(ifi.Index) } gr.setGroup(grp) var b []byte if freebsd32o64 { var d [sizeofGroupReq + 4]byte s := (*[sizeofGroupReq]byte)(unsafe.Pointer(&gr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) b = d[:] } else { b = (*[sizeofGroupReq]byte)(unsafe.Pointer(&gr))[:sizeofGroupReq] } return so.Set(c, b) } func (so *sockOpt) setGroupSourceReq(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { var gsr groupSourceReq if ifi != nil { gsr.Interface = uint32(ifi.Index) } gsr.setSourceGroup(grp, src) var b []byte if freebsd32o64 { var d [sizeofGroupSourceReq + 4]byte s := (*[sizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) b = d[:] } else { b = (*[sizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr))[:sizeofGroupSourceReq] } return so.Set(c, b) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_solaris.go0000644061062106075000000000541713172163402024105 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 4, marshalTTL, parseTTL}, ctlPacketInfo: {sysIP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo}, } sockOpts = map[int]sockOpt{ ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 1}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVPKTINFO, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, } ) func (pi *inetPktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(uintptr(unsafe.Pointer(gr)) + 4)) sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 4)) sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) sa = (*sockaddrInet)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 260)) sa.Family = syscall.AF_INET copy(sa.Addr[:], src) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_linux.go0000644061062106075000000000573313172163402023571 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_TTL, 1, marshalTTL, parseTTL}, ctlPacketInfo: {sysIP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo}, } sockOpts = map[int]*sockOpt{ ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_PKTINFO, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolReserved, Name: sysICMP_FILTER, Len: sizeofICMPFilter}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoAttachFilter: {Option: socket.Option{Level: sysSOL_SOCKET, Name: sysSO_ATTACH_FILTER, Len: sizeofSockFprog}}, } ) func (pi *inetPktinfo) setIfindex(i int) { pi.Ifindex = int32(i) } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(&gr.Group)) sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(&gsr.Group)) sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) sa = (*sockaddrInet)(unsafe.Pointer(&gsr.Source)) sa.Family = syscall.AF_INET copy(sa.Addr[:], src) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_freebsd.go0000644061062106075000000000663013172163402024041 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "runtime" "strings" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, } sockOpts = map[int]*sockOpt{ ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, } ) func init() { freebsdVersion, _ = syscall.SysctlUint32("kern.osreldate") if freebsdVersion >= 1000000 { sockOpts[ssoMulticastInterface] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn} } if runtime.GOOS == "freebsd" && runtime.GOARCH == "386" { archs, _ := syscall.Sysctl("kern.supported_archs") for _, s := range strings.Fields(archs) { if s == "amd64" { freebsd32o64 = true break } } } } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(&gr.Group)) sa.Len = sizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(&gsr.Group)) sa.Len = sizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) sa = (*sockaddrInet)(unsafe.Pointer(&gsr.Source)) sa.Len = sizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], src) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_dragonfly.go0000644061062106075000000000340613172163402024412 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "syscall" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, } sockOpts = map[int]*sockOpt{ ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, } ) lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_darwin.go0000644061062106075000000001077213172163402023715 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "strconv" "strings" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, } sockOpts = map[int]*sockOpt{ ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoStripHeader: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_STRIPHDR, Len: 4}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, } ) func init() { // Seems like kern.osreldate is veiled on latest OS X. We use // kern.osrelease instead. s, err := syscall.Sysctl("kern.osrelease") if err != nil { return } ss := strings.Split(s, ".") if len(ss) == 0 { return } // The IP_PKTINFO and protocol-independent multicast API were // introduced in OS X 10.7 (Darwin 11). But it looks like // those features require OS X 10.8 (Darwin 12) or above. // See http://support.apple.com/kb/HT1633. if mjver, err := strconv.Atoi(ss[0]); err != nil || mjver < 12 { return } ctlOpts[ctlPacketInfo].name = sysIP_PKTINFO ctlOpts[ctlPacketInfo].length = sizeofInetPktinfo ctlOpts[ctlPacketInfo].marshal = marshalPacketInfo ctlOpts[ctlPacketInfo].parse = parsePacketInfo sockOpts[ssoPacketInfo] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVPKTINFO, Len: 4}} sockOpts[ssoMulticastInterface] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn} sockOpts[ssoJoinGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq} sockOpts[ssoLeaveGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq} sockOpts[ssoJoinSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} sockOpts[ssoLeaveSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} sockOpts[ssoBlockSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} sockOpts[ssoUnblockSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} } func (pi *inetPktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(uintptr(unsafe.Pointer(gr)) + 4)) sa.Len = sizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 4)) sa.Len = sizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) sa = (*sockaddrInet)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 132)) sa.Len = sizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], src) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_bsd.go0000644061062106075000000000344013172163402023173 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build netbsd openbsd package ipv4 import ( "net" "syscall" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, } sockOpts = map[int]*sockOpt{ ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 1}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, } ) lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_bpf_stub.go0000644061062106075000000000056413172163402024233 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !linux package ipv4 import ( "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setAttachFilter(c *socket.Conn, f []bpf.RawInstruction) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_bpf.go0000644061062106075000000000104513172163402023171 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux package ipv4 import ( "unsafe" "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setAttachFilter(c *socket.Conn, f []bpf.RawInstruction) error { prog := sockFProg{ Len: uint16(len(f)), Filter: (*sockFilter)(unsafe.Pointer(&f[0])), } b := (*[sizeofSockFprog]byte)(unsafe.Pointer(&prog))[:sizeofSockFprog] return so.Set(c, b) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_asmreqn_stub.go0000644061062106075000000000073713172163402025134 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!freebsd,!linux package ipv4 import ( "net" "golang.org/x/net/internal/socket" ) func (so *sockOpt) getIPMreqn(c *socket.Conn) (*net.Interface, error) { return nil, errOpNoSupport } func (so *sockOpt) setIPMreqn(c *socket.Conn, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_asmreqn.go0000644061062106075000000000170713172163402024075 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin freebsd linux package ipv4 import ( "net" "unsafe" "golang.org/x/net/internal/socket" ) func (so *sockOpt) getIPMreqn(c *socket.Conn) (*net.Interface, error) { b := make([]byte, so.Len) if _, err := so.Get(c, b); err != nil { return nil, err } mreqn := (*ipMreqn)(unsafe.Pointer(&b[0])) if mreqn.Ifindex == 0 { return nil, nil } ifi, err := net.InterfaceByIndex(int(mreqn.Ifindex)) if err != nil { return nil, err } return ifi, nil } func (so *sockOpt) setIPMreqn(c *socket.Conn, ifi *net.Interface, grp net.IP) error { var mreqn ipMreqn if ifi != nil { mreqn.Ifindex = int32(ifi.Index) } if grp != nil { mreqn.Multiaddr = [4]byte{grp[0], grp[1], grp[2], grp[3]} } b := (*[sizeofIPMreqn]byte)(unsafe.Pointer(&mreqn))[:sizeofIPMreqn] return so.Set(c, b) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_asmreq_stub.go0000644061062106075000000000116113172163402024746 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!netbsd,!openbsd,!solaris,!windows package ipv4 import ( "net" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setIPMreq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } func (so *sockOpt) getMulticastIf(c *socket.Conn) (*net.Interface, error) { return nil, errOpNoSupport } func (so *sockOpt) setMulticastIf(c *socket.Conn, ifi *net.Interface) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sys_asmreq.go0000644061062106075000000000467513172163402023726 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd solaris windows package ipv4 import ( "net" "unsafe" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setIPMreq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { mreq := ipMreq{Multiaddr: [4]byte{grp[0], grp[1], grp[2], grp[3]}} if err := setIPMreqInterface(&mreq, ifi); err != nil { return err } b := (*[sizeofIPMreq]byte)(unsafe.Pointer(&mreq))[:sizeofIPMreq] return so.Set(c, b) } func (so *sockOpt) getMulticastIf(c *socket.Conn) (*net.Interface, error) { var b [4]byte if _, err := so.Get(c, b[:]); err != nil { return nil, err } ifi, err := netIP4ToInterface(net.IPv4(b[0], b[1], b[2], b[3])) if err != nil { return nil, err } return ifi, nil } func (so *sockOpt) setMulticastIf(c *socket.Conn, ifi *net.Interface) error { ip, err := netInterfaceToIP4(ifi) if err != nil { return err } var b [4]byte copy(b[:], ip) return so.Set(c, b[:]) } func setIPMreqInterface(mreq *ipMreq, ifi *net.Interface) error { if ifi == nil { return nil } ifat, err := ifi.Addrs() if err != nil { return err } for _, ifa := range ifat { switch ifa := ifa.(type) { case *net.IPAddr: if ip := ifa.IP.To4(); ip != nil { copy(mreq.Interface[:], ip) return nil } case *net.IPNet: if ip := ifa.IP.To4(); ip != nil { copy(mreq.Interface[:], ip) return nil } } } return errNoSuchInterface } func netIP4ToInterface(ip net.IP) (*net.Interface, error) { ift, err := net.Interfaces() if err != nil { return nil, err } for _, ifi := range ift { ifat, err := ifi.Addrs() if err != nil { return nil, err } for _, ifa := range ifat { switch ifa := ifa.(type) { case *net.IPAddr: if ip.Equal(ifa.IP) { return &ifi, nil } case *net.IPNet: if ip.Equal(ifa.IP) { return &ifi, nil } } } } return nil, errNoSuchInterface } func netInterfaceToIP4(ifi *net.Interface) (net.IP, error) { if ifi == nil { return net.IPv4zero.To4(), nil } ifat, err := ifi.Addrs() if err != nil { return nil, err } for _, ifa := range ifat { switch ifa := ifa.(type) { case *net.IPAddr: if ip := ifa.IP.To4(); ip != nil { return ip, nil } case *net.IPNet: if ip := ifa.IP.To4(); ip != nil { return ip, nil } } } return nil, errNoSuchInterface } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sockopt_stub.go0000644061062106075000000000210313172163402024237 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package ipv4 import ( "net" "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) getMulticastInterface(c *socket.Conn) (*net.Interface, error) { return nil, errOpNoSupport } func (so *sockOpt) setMulticastInterface(c *socket.Conn, ifi *net.Interface) error { return errOpNoSupport } func (so *sockOpt) getICMPFilter(c *socket.Conn) (*ICMPFilter, error) { return nil, errOpNoSupport } func (so *sockOpt) setICMPFilter(c *socket.Conn, f *ICMPFilter) error { return errOpNoSupport } func (so *sockOpt) setGroup(c *socket.Conn, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } func (so *sockOpt) setSourceGroup(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { return errOpNoSupport } func (so *sockOpt) setBPF(c *socket.Conn, f []bpf.RawInstruction) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sockopt_posix.go0000644061062106075000000000332713172163402024435 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package ipv4 import ( "net" "unsafe" "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) getMulticastInterface(c *socket.Conn) (*net.Interface, error) { switch so.typ { case ssoTypeIPMreqn: return so.getIPMreqn(c) default: return so.getMulticastIf(c) } } func (so *sockOpt) setMulticastInterface(c *socket.Conn, ifi *net.Interface) error { switch so.typ { case ssoTypeIPMreqn: return so.setIPMreqn(c, ifi, nil) default: return so.setMulticastIf(c, ifi) } } func (so *sockOpt) getICMPFilter(c *socket.Conn) (*ICMPFilter, error) { b := make([]byte, so.Len) n, err := so.Get(c, b) if err != nil { return nil, err } if n != sizeofICMPFilter { return nil, errOpNoSupport } return (*ICMPFilter)(unsafe.Pointer(&b[0])), nil } func (so *sockOpt) setICMPFilter(c *socket.Conn, f *ICMPFilter) error { b := (*[sizeofICMPFilter]byte)(unsafe.Pointer(f))[:sizeofICMPFilter] return so.Set(c, b) } func (so *sockOpt) setGroup(c *socket.Conn, ifi *net.Interface, grp net.IP) error { switch so.typ { case ssoTypeIPMreq: return so.setIPMreq(c, ifi, grp) case ssoTypeIPMreqn: return so.setIPMreqn(c, ifi, grp) case ssoTypeGroupReq: return so.setGroupReq(c, ifi, grp) default: return errOpNoSupport } } func (so *sockOpt) setSourceGroup(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { return so.setGroupSourceReq(c, ifi, grp, src) } func (so *sockOpt) setBPF(c *socket.Conn, f []bpf.RawInstruction) error { return so.setAttachFilter(c, f) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/sockopt.go0000644061062106075000000000327413172163402023214 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import "golang.org/x/net/internal/socket" // Sticky socket options const ( ssoTOS = iota // header field for unicast packet ssoTTL // header field for unicast packet ssoMulticastTTL // header field for multicast packet ssoMulticastInterface // outbound interface for multicast packet ssoMulticastLoopback // loopback for multicast packet ssoReceiveTTL // header field on received packet ssoReceiveDst // header field on received packet ssoReceiveInterface // inbound interface on received packet ssoPacketInfo // incbound or outbound packet path ssoHeaderPrepend // ipv4 header prepend ssoStripHeader // strip ipv4 header ssoICMPFilter // icmp filter ssoJoinGroup // any-source multicast ssoLeaveGroup // any-source multicast ssoJoinSourceGroup // source-specific multicast ssoLeaveSourceGroup // source-specific multicast ssoBlockSourceGroup // any-source or source-specific multicast ssoUnblockSourceGroup // any-source or source-specific multicast ssoAttachFilter // attach BPF for filtering inbound traffic ) // Sticky socket option value types const ( ssoTypeIPMreq = iota + 1 ssoTypeIPMreqn ssoTypeGroupReq ssoTypeGroupSourceReq ) // A sockOpt represents a binding for sticky socket option. type sockOpt struct { socket.Option typ int // hint for option value type; optional } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/readwrite_test.go0000644061062106075000000000576113172163402024562 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "bytes" "net" "runtime" "strings" "sync" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) func BenchmarkReadWriteUnicast(b *testing.B) { c, err := nettest.NewLocalPacketListener("udp4") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() dst := c.LocalAddr() wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) b.Run("NetUDP", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(wb, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(rb); err != nil { b.Fatal(err) } } }) b.Run("IPv4UDP", func(b *testing.B) { p := ipv4.NewPacketConn(c) cf := ipv4.FlagTTL | ipv4.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } cm := ipv4.ControlMessage{TTL: 1} ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi != nil { cm.IfIndex = ifi.Index } for i := 0; i < b.N; i++ { if _, err := p.WriteTo(wb, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(rb); err != nil { b.Fatal(err) } } }) } func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } c, err := nettest.NewLocalPacketListener("udp4") if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) defer p.Close() dst := c.LocalAddr() ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) cf := ipv4.FlagTTL | ipv4.FlagSrc | ipv4.FlagDst | ipv4.FlagInterface wb := []byte("HELLO-R-U-THERE") if err := p.SetControlMessage(cf, true); err != nil { // probe before test if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } var wg sync.WaitGroup reader := func() { defer wg.Done() rb := make([]byte, 128) if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Error(err) return } else if !bytes.Equal(rb[:n], wb) { t.Errorf("got %v; want %v", rb[:n], wb) return } else { s := cm.String() if strings.Contains(s, ",") { t.Errorf("should be space-separated values: %s", s) } } } writer := func(toggle bool) { defer wg.Done() cm := ipv4.ControlMessage{ Src: net.IPv4(127, 0, 0, 1), } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Error(err) return } else if n != len(wb) { t.Errorf("got %d; want %d", n, len(wb)) return } } const N = 10 wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Add(2 * N) for i := 0; i < 2*N; i++ { go writer(i%2 != 0) } wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Wait() } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/readwrite_go1_9_test.go0000644061062106075000000002132113172163402025546 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package ipv4_test import ( "bytes" "fmt" "net" "runtime" "strings" "sync" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) func BenchmarkPacketConnReadWriteUnicast(b *testing.B) { switch runtime.GOOS { case "nacl", "plan9", "windows": b.Skipf("not supported on %s", runtime.GOOS) } payload := []byte("HELLO-R-U-THERE") iph, err := (&ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TotalLen: ipv4.HeaderLen + len(payload), TTL: 1, Protocol: iana.ProtocolReserved, Src: net.IPv4(192, 0, 2, 1), Dst: net.IPv4(192, 0, 2, 254), }).Marshal() if err != nil { b.Fatal(err) } greh := []byte{0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00} datagram := append(greh, append(iph, payload...)...) bb := make([]byte, 128) cm := ipv4.ControlMessage{ Src: net.IPv4(127, 0, 0, 1), } if ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback); ifi != nil { cm.IfIndex = ifi.Index } b.Run("UDP", func(b *testing.B) { c, err := nettest.NewLocalPacketListener("udp4") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv4.NewPacketConn(c) dst := c.LocalAddr() cf := ipv4.FlagTTL | ipv4.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } wms := []ipv4.Message{ { Buffers: [][]byte{payload}, Addr: dst, OOB: cm.Marshal(), }, } rms := []ipv4.Message{ { Buffers: [][]byte{bb}, OOB: ipv4.NewControlMessage(cf), }, } b.Run("Net", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(payload, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("ToFrom", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteTo(payload, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("Batch", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteBatch(wms, 0); err != nil { b.Fatal(err) } if _, err := p.ReadBatch(rms, 0); err != nil { b.Fatal(err) } } }) }) b.Run("IP", func(b *testing.B) { switch runtime.GOOS { case "netbsd": b.Skip("need to configure gre on netbsd") case "openbsd": b.Skip("net.inet.gre.allow=0 by default on openbsd") } c, err := net.ListenPacket(fmt.Sprintf("ip4:%d", iana.ProtocolGRE), "127.0.0.1") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv4.NewPacketConn(c) dst := c.LocalAddr() cf := ipv4.FlagTTL | ipv4.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } wms := []ipv4.Message{ { Buffers: [][]byte{datagram}, Addr: dst, OOB: cm.Marshal(), }, } rms := []ipv4.Message{ { Buffers: [][]byte{bb}, OOB: ipv4.NewControlMessage(cf), }, } b.Run("Net", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(datagram, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("ToFrom", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteTo(datagram, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("Batch", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteBatch(wms, 0); err != nil { b.Fatal(err) } if _, err := p.ReadBatch(rms, 0); err != nil { b.Fatal(err) } } }) }) } func TestPacketConnConcurrentReadWriteUnicast(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } payload := []byte("HELLO-R-U-THERE") iph, err := (&ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TotalLen: ipv4.HeaderLen + len(payload), TTL: 1, Protocol: iana.ProtocolReserved, Src: net.IPv4(192, 0, 2, 1), Dst: net.IPv4(192, 0, 2, 254), }).Marshal() if err != nil { t.Fatal(err) } greh := []byte{0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00} datagram := append(greh, append(iph, payload...)...) t.Run("UDP", func(t *testing.T) { c, err := nettest.NewLocalPacketListener("udp4") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv4.NewPacketConn(c) t.Run("ToFrom", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, payload, c.LocalAddr(), false) }) t.Run("Batch", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, payload, c.LocalAddr(), true) }) }) t.Run("IP", func(t *testing.T) { switch runtime.GOOS { case "netbsd": t.Skip("need to configure gre on netbsd") case "openbsd": t.Skip("net.inet.gre.allow=0 by default on openbsd") } c, err := net.ListenPacket(fmt.Sprintf("ip4:%d", iana.ProtocolGRE), "127.0.0.1") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv4.NewPacketConn(c) t.Run("ToFrom", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, datagram, c.LocalAddr(), false) }) t.Run("Batch", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, datagram, c.LocalAddr(), true) }) }) } func testPacketConnConcurrentReadWriteUnicast(t *testing.T, p *ipv4.PacketConn, data []byte, dst net.Addr, batch bool) { ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) cf := ipv4.FlagTTL | ipv4.FlagSrc | ipv4.FlagDst | ipv4.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { // probe before test if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } var wg sync.WaitGroup reader := func() { defer wg.Done() b := make([]byte, 128) n, cm, _, err := p.ReadFrom(b) if err != nil { t.Error(err) return } if !bytes.Equal(b[:n], data) { t.Errorf("got %#v; want %#v", b[:n], data) return } s := cm.String() if strings.Contains(s, ",") { t.Errorf("should be space-separated values: %s", s) return } } batchReader := func() { defer wg.Done() ms := []ipv4.Message{ { Buffers: [][]byte{make([]byte, 128)}, OOB: ipv4.NewControlMessage(cf), }, } n, err := p.ReadBatch(ms, 0) if err != nil { t.Error(err) return } if n != len(ms) { t.Errorf("got %d; want %d", n, len(ms)) return } var cm ipv4.ControlMessage if err := cm.Parse(ms[0].OOB[:ms[0].NN]); err != nil { t.Error(err) return } var b []byte if _, ok := dst.(*net.IPAddr); ok { var h ipv4.Header if err := h.Parse(ms[0].Buffers[0][:ms[0].N]); err != nil { t.Error(err) return } b = ms[0].Buffers[0][h.Len:ms[0].N] } else { b = ms[0].Buffers[0][:ms[0].N] } if !bytes.Equal(b, data) { t.Errorf("got %#v; want %#v", b, data) return } s := cm.String() if strings.Contains(s, ",") { t.Errorf("should be space-separated values: %s", s) return } } writer := func(toggle bool) { defer wg.Done() cm := ipv4.ControlMessage{ Src: net.IPv4(127, 0, 0, 1), } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } n, err := p.WriteTo(data, &cm, dst) if err != nil { t.Error(err) return } if n != len(data) { t.Errorf("got %d; want %d", n, len(data)) return } } batchWriter := func(toggle bool) { defer wg.Done() cm := ipv4.ControlMessage{ Src: net.IPv4(127, 0, 0, 1), } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } ms := []ipv4.Message{ { Buffers: [][]byte{data}, OOB: cm.Marshal(), Addr: dst, }, } n, err := p.WriteBatch(ms, 0) if err != nil { t.Error(err) return } if n != len(ms) { t.Errorf("got %d; want %d", n, len(ms)) return } if ms[0].N != len(data) { t.Errorf("got %d; want %d", ms[0].N, len(data)) return } } const N = 10 wg.Add(N) for i := 0; i < N; i++ { if batch { go batchReader() } else { go reader() } } wg.Add(2 * N) for i := 0; i < 2*N; i++ { if batch { go batchWriter(i%2 != 0) } else { go writer(i%2 != 0) } } wg.Add(N) for i := 0; i < N; i++ { if batch { go batchReader() } else { go reader() } } wg.Wait() } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/readwrite_go1_8_test.go0000644061062106075000000001364513172163402025557 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 package ipv4_test import ( "bytes" "fmt" "net" "runtime" "strings" "sync" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) func BenchmarkPacketConnReadWriteUnicast(b *testing.B) { switch runtime.GOOS { case "nacl", "plan9", "windows": b.Skipf("not supported on %s", runtime.GOOS) } payload := []byte("HELLO-R-U-THERE") iph, err := (&ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TotalLen: ipv4.HeaderLen + len(payload), TTL: 1, Protocol: iana.ProtocolReserved, Src: net.IPv4(192, 0, 2, 1), Dst: net.IPv4(192, 0, 2, 254), }).Marshal() if err != nil { b.Fatal(err) } greh := []byte{0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00} datagram := append(greh, append(iph, payload...)...) bb := make([]byte, 128) cm := ipv4.ControlMessage{ Src: net.IPv4(127, 0, 0, 1), } if ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback); ifi != nil { cm.IfIndex = ifi.Index } b.Run("UDP", func(b *testing.B) { c, err := nettest.NewLocalPacketListener("udp4") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv4.NewPacketConn(c) dst := c.LocalAddr() cf := ipv4.FlagTTL | ipv4.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } b.Run("Net", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(payload, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("ToFrom", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteTo(payload, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(bb); err != nil { b.Fatal(err) } } }) }) b.Run("IP", func(b *testing.B) { switch runtime.GOOS { case "netbsd": b.Skip("need to configure gre on netbsd") case "openbsd": b.Skip("net.inet.gre.allow=0 by default on openbsd") } c, err := net.ListenPacket(fmt.Sprintf("ip4:%d", iana.ProtocolGRE), "127.0.0.1") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv4.NewPacketConn(c) dst := c.LocalAddr() cf := ipv4.FlagTTL | ipv4.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } b.Run("Net", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := c.WriteTo(datagram, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(bb); err != nil { b.Fatal(err) } } }) b.Run("ToFrom", func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := p.WriteTo(datagram, &cm, dst); err != nil { b.Fatal(err) } if _, _, _, err := p.ReadFrom(bb); err != nil { b.Fatal(err) } } }) }) } func TestPacketConnConcurrentReadWriteUnicast(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } payload := []byte("HELLO-R-U-THERE") iph, err := (&ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TotalLen: ipv4.HeaderLen + len(payload), TTL: 1, Protocol: iana.ProtocolReserved, Src: net.IPv4(192, 0, 2, 1), Dst: net.IPv4(192, 0, 2, 254), }).Marshal() if err != nil { t.Fatal(err) } greh := []byte{0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00} datagram := append(greh, append(iph, payload...)...) t.Run("UDP", func(t *testing.T) { c, err := nettest.NewLocalPacketListener("udp4") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv4.NewPacketConn(c) t.Run("ToFrom", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, payload, c.LocalAddr()) }) }) t.Run("IP", func(t *testing.T) { switch runtime.GOOS { case "netbsd": t.Skip("need to configure gre on netbsd") case "openbsd": t.Skip("net.inet.gre.allow=0 by default on openbsd") } c, err := net.ListenPacket(fmt.Sprintf("ip4:%d", iana.ProtocolGRE), "127.0.0.1") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() p := ipv4.NewPacketConn(c) t.Run("ToFrom", func(t *testing.T) { testPacketConnConcurrentReadWriteUnicast(t, p, datagram, c.LocalAddr()) }) }) } func testPacketConnConcurrentReadWriteUnicast(t *testing.T, p *ipv4.PacketConn, data []byte, dst net.Addr) { ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) cf := ipv4.FlagTTL | ipv4.FlagSrc | ipv4.FlagDst | ipv4.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { // probe before test if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } var wg sync.WaitGroup reader := func() { defer wg.Done() b := make([]byte, 128) n, cm, _, err := p.ReadFrom(b) if err != nil { t.Error(err) return } if !bytes.Equal(b[:n], data) { t.Errorf("got %#v; want %#v", b[:n], data) return } s := cm.String() if strings.Contains(s, ",") { t.Errorf("should be space-separated values: %s", s) return } } writer := func(toggle bool) { defer wg.Done() cm := ipv4.ControlMessage{ Src: net.IPv4(127, 0, 0, 1), } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } n, err := p.WriteTo(data, &cm, dst) if err != nil { t.Error(err) return } if n != len(data) { t.Errorf("got %d; want %d", n, len(data)) return } } const N = 10 wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Add(2 * N) for i := 0; i < 2*N; i++ { go writer(i%2 != 0) } wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Wait() } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/payload_nocmsg.go0000644061062106075000000000250713172163402024527 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build nacl plan9 windows package ipv4 import ( "net" "syscall" ) // ReadFrom reads a payload of the received IPv4 datagram, from the // endpoint c, copying the payload into b. It returns the number of // bytes copied into b, the control message cm and the source address // src of the received datagram. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { if !c.ok() { return 0, nil, nil, syscall.EINVAL } if n, src, err = c.PacketConn.ReadFrom(b); err != nil { return 0, nil, nil, err } return } // WriteTo writes a payload of the IPv4 datagram, to the destination // address dst through the endpoint c, copying the payload from b. It // returns the number of bytes written. The control message cm allows // the datagram path and the outgoing interface to be specified. // Currently only Darwin and Linux support this. The cm may be nil if // control of the outgoing datagram is not required. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { if !c.ok() { return 0, syscall.EINVAL } if dst == nil { return 0, errMissingAddress } return c.PacketConn.WriteTo(b, dst) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/payload_cmsg_go1_9.go0000644061062106075000000000370613172163402025172 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 // +build !nacl,!plan9,!windows package ipv4 import ( "net" "golang.org/x/net/internal/socket" ) func (c *payloadHandler) readFrom(b []byte) (int, *ControlMessage, net.Addr, error) { c.rawOpt.RLock() m := socket.Message{ OOB: NewControlMessage(c.rawOpt.cflags), } c.rawOpt.RUnlock() switch c.PacketConn.(type) { case *net.UDPConn: m.Buffers = [][]byte{b} if err := c.RecvMsg(&m, 0); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } case *net.IPConn: h := make([]byte, HeaderLen) m.Buffers = [][]byte{h, b} if err := c.RecvMsg(&m, 0); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } hdrlen := int(h[0]&0x0f) << 2 if hdrlen > len(h) { d := hdrlen - len(h) copy(b, b[d:]) m.N -= d } else { m.N -= hdrlen } default: return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errInvalidConnType} } var cm *ControlMessage if m.NN > 0 { cm = new(ControlMessage) if err := cm.Parse(m.OOB[:m.NN]); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } cm.Src = netAddrToIP4(m.Addr) } return m.N, cm, m.Addr, nil } func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (int, error) { m := socket.Message{ Buffers: [][]byte{b}, OOB: cm.Marshal(), Addr: dst, } err := c.SendMsg(&m, 0) if err != nil { err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Addr: opAddr(dst), Err: err} } return m.N, err } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/payload_cmsg_go1_8.go0000644061062106075000000000345713172163402025174 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 // +build !nacl,!plan9,!windows package ipv4 import "net" func (c *payloadHandler) readFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { c.rawOpt.RLock() oob := NewControlMessage(c.rawOpt.cflags) c.rawOpt.RUnlock() var nn int switch c := c.PacketConn.(type) { case *net.UDPConn: if n, nn, _, src, err = c.ReadMsgUDP(b, oob); err != nil { return 0, nil, nil, err } case *net.IPConn: nb := make([]byte, maxHeaderLen+len(b)) if n, nn, _, src, err = c.ReadMsgIP(nb, oob); err != nil { return 0, nil, nil, err } hdrlen := int(nb[0]&0x0f) << 2 copy(b, nb[hdrlen:]) n -= hdrlen default: return 0, nil, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Err: errInvalidConnType} } if nn > 0 { cm = new(ControlMessage) if err = cm.Parse(oob[:nn]); err != nil { return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } } if cm != nil { cm.Src = netAddrToIP4(src) } return } func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { oob := cm.Marshal() if dst == nil { return 0, &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errMissingAddress} } switch c := c.PacketConn.(type) { case *net.UDPConn: n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr)) case *net.IPConn: n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr)) default: return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Addr: opAddr(dst), Err: errInvalidConnType} } return } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/payload_cmsg.go0000644061062106075000000000231113172163402024163 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !nacl,!plan9,!windows package ipv4 import ( "net" "syscall" ) // ReadFrom reads a payload of the received IPv4 datagram, from the // endpoint c, copying the payload into b. It returns the number of // bytes copied into b, the control message cm and the source address // src of the received datagram. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { if !c.ok() { return 0, nil, nil, syscall.EINVAL } return c.readFrom(b) } // WriteTo writes a payload of the IPv4 datagram, to the destination // address dst through the endpoint c, copying the payload from b. It // returns the number of bytes written. The control message cm allows // the datagram path and the outgoing interface to be specified. // Currently only Darwin and Linux support this. The cm may be nil if // control of the outgoing datagram is not required. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { if !c.ok() { return 0, syscall.EINVAL } return c.writeTo(b, cm, dst) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/payload.go0000644061062106075000000000110213172163402023147 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "golang.org/x/net/internal/socket" ) // BUG(mikio): On Windows, the ControlMessage for ReadFrom and WriteTo // methods of PacketConn is not implemented. // A payloadHandler represents the IPv4 datagram payload handler. type payloadHandler struct { net.PacketConn *socket.Conn rawOpt } func (c *payloadHandler) ok() bool { return c != nil && c.PacketConn != nil && c.Conn != nil } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/packet_go1_9.go0000644061062106075000000000353613172163402024000 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package ipv4 import ( "net" "golang.org/x/net/internal/socket" ) func (c *packetHandler) readFrom(b []byte) (h *Header, p []byte, cm *ControlMessage, err error) { c.rawOpt.RLock() m := socket.Message{ Buffers: [][]byte{b}, OOB: NewControlMessage(c.rawOpt.cflags), } c.rawOpt.RUnlock() if err := c.RecvMsg(&m, 0); err != nil { return nil, nil, nil, &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} } var hs []byte if hs, p, err = slicePacket(b[:m.N]); err != nil { return nil, nil, nil, &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} } if h, err = ParseHeader(hs); err != nil { return nil, nil, nil, &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} } if m.NN > 0 { cm = new(ControlMessage) if err := cm.Parse(m.OOB[:m.NN]); err != nil { return nil, nil, nil, &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} } } if src, ok := m.Addr.(*net.IPAddr); ok && cm != nil { cm.Src = src.IP } return } func (c *packetHandler) writeTo(h *Header, p []byte, cm *ControlMessage) error { m := socket.Message{ OOB: cm.Marshal(), } wh, err := h.Marshal() if err != nil { return err } m.Buffers = [][]byte{wh, p} dst := new(net.IPAddr) if cm != nil { if ip := cm.Dst.To4(); ip != nil { dst.IP = ip } } if dst.IP == nil { dst.IP = h.Dst } m.Addr = dst if err := c.SendMsg(&m, 0); err != nil { return &net.OpError{Op: "write", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Addr: opAddr(dst), Err: err} } return nil } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/packet_go1_8.go0000644061062106075000000000226413172163402023774 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 package ipv4 import "net" func (c *packetHandler) readFrom(b []byte) (h *Header, p []byte, cm *ControlMessage, err error) { c.rawOpt.RLock() oob := NewControlMessage(c.rawOpt.cflags) c.rawOpt.RUnlock() n, nn, _, src, err := c.ReadMsgIP(b, oob) if err != nil { return nil, nil, nil, err } var hs []byte if hs, p, err = slicePacket(b[:n]); err != nil { return nil, nil, nil, err } if h, err = ParseHeader(hs); err != nil { return nil, nil, nil, err } if nn > 0 { cm = new(ControlMessage) if err := cm.Parse(oob[:nn]); err != nil { return nil, nil, nil, err } } if src != nil && cm != nil { cm.Src = src.IP } return } func (c *packetHandler) writeTo(h *Header, p []byte, cm *ControlMessage) error { oob := cm.Marshal() wh, err := h.Marshal() if err != nil { return err } dst := new(net.IPAddr) if cm != nil { if ip := cm.Dst.To4(); ip != nil { dst.IP = ip } } if dst.IP == nil { dst.IP = h.Dst } wh = append(wh, p...) _, _, err = c.WriteMsgIP(wh, oob, dst) return err } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/packet.go0000644061062106075000000000426213172163402022777 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "syscall" "golang.org/x/net/internal/socket" ) // BUG(mikio): On Windows, the ReadFrom and WriteTo methods of RawConn // are not implemented. // A packetHandler represents the IPv4 datagram handler. type packetHandler struct { *net.IPConn *socket.Conn rawOpt } func (c *packetHandler) ok() bool { return c != nil && c.IPConn != nil && c.Conn != nil } // ReadFrom reads an IPv4 datagram from the endpoint c, copying the // datagram into b. It returns the received datagram as the IPv4 // header h, the payload p and the control message cm. func (c *packetHandler) ReadFrom(b []byte) (h *Header, p []byte, cm *ControlMessage, err error) { if !c.ok() { return nil, nil, nil, syscall.EINVAL } return c.readFrom(b) } func slicePacket(b []byte) (h, p []byte, err error) { if len(b) < HeaderLen { return nil, nil, errHeaderTooShort } hdrlen := int(b[0]&0x0f) << 2 return b[:hdrlen], b[hdrlen:], nil } // WriteTo writes an IPv4 datagram through the endpoint c, copying the // datagram from the IPv4 header h and the payload p. The control // message cm allows the datagram path and the outgoing interface to be // specified. Currently only Darwin and Linux support this. The cm // may be nil if control of the outgoing datagram is not required. // // The IPv4 header h must contain appropriate fields that include: // // Version = // Len = // TOS = // TotalLen = // ID = platform sets an appropriate value if ID is zero // FragOff = // TTL = // Protocol = // Checksum = platform sets an appropriate value if Checksum is zero // Src = platform sets an appropriate value if Src is nil // Dst = // Options = optional func (c *packetHandler) WriteTo(h *Header, p []byte, cm *ControlMessage) error { if !c.ok() { return syscall.EINVAL } return c.writeTo(h, p, cm) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/multicastsockopt_test.go0000644061062106075000000001207713172163402026202 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) var packetConnMulticastSocketOptionTests = []struct { net, proto, addr string grp, src net.Addr }{ {"udp4", "", "224.0.0.0:0", &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}, nil}, // see RFC 4727 {"ip4", ":icmp", "0.0.0.0", &net.IPAddr{IP: net.IPv4(224, 0, 0, 250)}, nil}, // see RFC 4727 {"udp4", "", "232.0.0.0:0", &net.UDPAddr{IP: net.IPv4(232, 0, 1, 249)}, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 {"ip4", ":icmp", "0.0.0.0", &net.IPAddr{IP: net.IPv4(232, 0, 1, 250)}, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestPacketConnMulticastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnMulticastSocketOptionTests { if tt.net == "ip4" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) defer p.Close() if tt.src == nil { testMulticastSocketOptions(t, p, ifi, tt.grp) } else { testSourceSpecificMulticastSocketOptions(t, p, ifi, tt.grp, tt.src) } } } var rawConnMulticastSocketOptionTests = []struct { grp, src net.Addr }{ {&net.IPAddr{IP: net.IPv4(224, 0, 0, 250)}, nil}, // see RFC 4727 {&net.IPAddr{IP: net.IPv4(232, 0, 1, 250)}, &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestRawConnMulticastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range rawConnMulticastSocketOptionTests { c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } defer r.Close() if tt.src == nil { testMulticastSocketOptions(t, r, ifi, tt.grp) } else { testSourceSpecificMulticastSocketOptions(t, r, ifi, tt.grp, tt.src) } } } type testIPv4MulticastConn interface { MulticastTTL() (int, error) SetMulticastTTL(ttl int) error MulticastLoopback() (bool, error) SetMulticastLoopback(bool) error JoinGroup(*net.Interface, net.Addr) error LeaveGroup(*net.Interface, net.Addr) error JoinSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error LeaveSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error ExcludeSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error IncludeSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error } func testMulticastSocketOptions(t *testing.T, c testIPv4MulticastConn, ifi *net.Interface, grp net.Addr) { const ttl = 255 if err := c.SetMulticastTTL(ttl); err != nil { t.Error(err) return } if v, err := c.MulticastTTL(); err != nil { t.Error(err) return } else if v != ttl { t.Errorf("got %v; want %v", v, ttl) return } for _, toggle := range []bool{true, false} { if err := c.SetMulticastLoopback(toggle); err != nil { t.Error(err) return } if v, err := c.MulticastLoopback(); err != nil { t.Error(err) return } else if v != toggle { t.Errorf("got %v; want %v", v, toggle) return } } if err := c.JoinGroup(ifi, grp); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } } func testSourceSpecificMulticastSocketOptions(t *testing.T, c testIPv4MulticastConn, ifi *net.Interface, grp, src net.Addr) { // MCAST_JOIN_GROUP -> MCAST_BLOCK_SOURCE -> MCAST_UNBLOCK_SOURCE -> MCAST_LEAVE_GROUP if err := c.JoinGroup(ifi, grp); err != nil { t.Error(err) return } if err := c.ExcludeSourceSpecificGroup(ifi, grp, src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support IGMPv2/3 fail here t.Logf("not supported on %s", runtime.GOOS) return } t.Error(err) return } if err := c.IncludeSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } // MCAST_JOIN_SOURCE_GROUP -> MCAST_LEAVE_SOURCE_GROUP if err := c.JoinSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } // MCAST_JOIN_SOURCE_GROUP -> MCAST_LEAVE_GROUP if err := c.JoinSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/multicastlistener_test.go0000644061062106075000000001363313172163402026344 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) var udpMultipleGroupListenerTests = []net.Addr{ &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}, // see RFC 4727 &net.UDPAddr{IP: net.IPv4(224, 0, 0, 250)}, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 254)}, } func TestUDPSinglePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } for _, gaddr := range udpMultipleGroupListenerTests { c, err := net.ListenPacket("udp4", "0.0.0.0:0") // wildcard address with no reusable port if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip4", &ifi); !ok { continue } if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } for _, gaddr := range udpMultipleGroupListenerTests { c1, err := net.ListenPacket("udp4", "224.0.0.0:0") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c1.Close() _, port, err := net.SplitHostPort(c1.LocalAddr().String()) if err != nil { t.Fatal(err) } c2, err := net.ListenPacket("udp4", net.JoinHostPort("224.0.0.0", port)) // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c2.Close() var ps [2]*ipv4.PacketConn ps[0] = ipv4.NewPacketConn(c1) ps[1] = ipv4.NewPacketConn(c2) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip4", &ifi); !ok { continue } for _, p := range ps { if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } } mift = append(mift, &ift[i]) } for _, ifi := range mift { for _, p := range ps { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } } func TestUDPPerInterfaceSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 type ml struct { c *ipv4.PacketConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } port := "0" for i, ifi := range ift { ip, ok := nettest.IsMulticastCapable("ip4", &ifi) if !ok { continue } c, err := net.ListenPacket("udp4", net.JoinHostPort(ip.String(), port)) // unicast address with non-reusable port if err != nil { // The listen may fail when the serivce is // already in use, but it's fine because the // purpose of this is not to test the // bookkeeping of IP control block inside the // kernel. t.Log(err) continue } defer c.Close() if port == "0" { _, port, err = net.SplitHostPort(c.LocalAddr().String()) if err != nil { t.Fatal(err) } } p := ipv4.NewPacketConn(c) if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{p, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPSingleRawConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") // wildcard address if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip4", &ifi); !ok { continue } if err := r.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := r.LeaveGroup(ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPPerInterfaceSingleRawConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 type ml struct { c *ipv4.RawConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { ip, ok := nettest.IsMulticastCapable("ip4", &ifi) if !ok { continue } c, err := net.ListenPacket("ip4:253", ip.String()) // unicast address if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } if err := r.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{r, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/multicast_test.go0000644061062106075000000002170413172163402024574 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "bytes" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) var packetConnReadWriteMulticastUDPTests = []struct { addr string grp, src *net.UDPAddr }{ {"224.0.0.0:0", &net.UDPAddr{IP: net.IPv4(224, 0, 0, 254)}, nil}, // see RFC 4727 {"232.0.1.0:0", &net.UDPAddr{IP: net.IPv4(232, 0, 1, 254)}, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestPacketConnReadWriteMulticastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range packetConnReadWriteMulticastUDPTests { c, err := net.ListenPacket("udp4", tt.addr) if err != nil { t.Fatal(err) } defer c.Close() grp := *tt.grp grp.Port = c.LocalAddr().(*net.UDPAddr).Port p := ipv4.NewPacketConn(c) defer p.Close() if tt.src == nil { if err := p.JoinGroup(ifi, &grp); err != nil { t.Fatal(err) } defer p.LeaveGroup(ifi, &grp) } else { if err := p.JoinSourceSpecificGroup(ifi, &grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support IGMPv2/3 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer p.LeaveSourceSpecificGroup(ifi, &grp, tt.src) } if err := p.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := p.MulticastInterface(); err != nil { t.Fatal(err) } if err := p.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := p.MulticastLoopback(); err != nil { t.Fatal(err) } cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := p.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } p.SetMulticastTTL(i + 1) if n, err := p.WriteTo(wb, nil, &grp); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if n, _, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; want %v", rb[:n], wb) } } } } var packetConnReadWriteMulticastICMPTests = []struct { grp, src *net.IPAddr }{ {&net.IPAddr{IP: net.IPv4(224, 0, 0, 254)}, nil}, // see RFC 4727 {&net.IPAddr{IP: net.IPv4(232, 0, 1, 254)}, &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestPacketConnReadWriteMulticastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range packetConnReadWriteMulticastICMPTests { c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) defer p.Close() if tt.src == nil { if err := p.JoinGroup(ifi, tt.grp); err != nil { t.Fatal(err) } defer p.LeaveGroup(ifi, tt.grp) } else { if err := p.JoinSourceSpecificGroup(ifi, tt.grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support IGMPv2/3 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer p.LeaveSourceSpecificGroup(ifi, tt.grp, tt.src) } if err := p.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := p.MulticastInterface(); err != nil { t.Fatal(err) } if err := p.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := p.MulticastLoopback(); err != nil { t.Fatal(err) } cf := ipv4.FlagDst | ipv4.FlagInterface if runtime.GOOS != "solaris" { // Solaris never allows to modify ICMP properties. cf |= ipv4.FlagTTL } for i, toggle := range []bool{true, false, true} { wb, err := (&icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(nil) if err != nil { t.Fatal(err) } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := p.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } p.SetMulticastTTL(i + 1) if n, err := p.WriteTo(wb, nil, tt.grp); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if n, _, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else { m, err := icmp.ParseMessage(iana.ProtocolICMP, rb[:n]) if err != nil { t.Fatal(err) } switch { case m.Type == ipv4.ICMPTypeEchoReply && m.Code == 0: // net.inet.icmp.bmcastecho=1 case m.Type == ipv4.ICMPTypeEcho && m.Code == 0: // net.inet.icmp.bmcastecho=0 default: t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv4.ICMPTypeEchoReply, 0) } } } } } var rawConnReadWriteMulticastICMPTests = []struct { grp, src *net.IPAddr }{ {&net.IPAddr{IP: net.IPv4(224, 0, 0, 254)}, nil}, // see RFC 4727 {&net.IPAddr{IP: net.IPv4(232, 0, 1, 254)}, &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestRawConnReadWriteMulticastICMP(t *testing.T) { if testing.Short() { t.Skip("to avoid external network") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range rawConnReadWriteMulticastICMPTests { c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } defer r.Close() if tt.src == nil { if err := r.JoinGroup(ifi, tt.grp); err != nil { t.Fatal(err) } defer r.LeaveGroup(ifi, tt.grp) } else { if err := r.JoinSourceSpecificGroup(ifi, tt.grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support IGMPv2/3 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer r.LeaveSourceSpecificGroup(ifi, tt.grp, tt.src) } if err := r.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := r.MulticastInterface(); err != nil { t.Fatal(err) } if err := r.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := r.MulticastLoopback(); err != nil { t.Fatal(err) } cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface for i, toggle := range []bool{true, false, true} { wb, err := (&icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(nil) if err != nil { t.Fatal(err) } wh := &ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TOS: i + 1, TotalLen: ipv4.HeaderLen + len(wb), Protocol: 1, Dst: tt.grp.IP, } if err := r.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := r.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } r.SetMulticastTTL(i + 1) if err := r.WriteTo(wh, wb, nil); err != nil { t.Fatal(err) } rb := make([]byte, ipv4.HeaderLen+128) if rh, b, _, err := r.ReadFrom(rb); err != nil { t.Fatal(err) } else { m, err := icmp.ParseMessage(iana.ProtocolICMP, b) if err != nil { t.Fatal(err) } switch { case (rh.Dst.IsLoopback() || rh.Dst.IsLinkLocalUnicast() || rh.Dst.IsGlobalUnicast()) && m.Type == ipv4.ICMPTypeEchoReply && m.Code == 0: // net.inet.icmp.bmcastecho=1 case rh.Dst.IsMulticast() && m.Type == ipv4.ICMPTypeEcho && m.Code == 0: // net.inet.icmp.bmcastecho=0 default: t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv4.ICMPTypeEchoReply, 0) } } } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/icmp_test.go0000644061062106075000000000352613172163402023521 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "net" "reflect" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) var icmpStringTests = []struct { in ipv4.ICMPType out string }{ {ipv4.ICMPTypeDestinationUnreachable, "destination unreachable"}, {256, ""}, } func TestICMPString(t *testing.T) { for _, tt := range icmpStringTests { s := tt.in.String() if s != tt.out { t.Errorf("got %s; want %s", s, tt.out) } } } func TestICMPFilter(t *testing.T) { switch runtime.GOOS { case "linux": default: t.Skipf("not supported on %s", runtime.GOOS) } var f ipv4.ICMPFilter for _, toggle := range []bool{false, true} { f.SetAll(toggle) for _, typ := range []ipv4.ICMPType{ ipv4.ICMPTypeDestinationUnreachable, ipv4.ICMPTypeEchoReply, ipv4.ICMPTypeTimeExceeded, ipv4.ICMPTypeParameterProblem, } { f.Accept(typ) if f.WillBlock(typ) { t.Errorf("ipv4.ICMPFilter.Set(%v, false) failed", typ) } f.Block(typ) if !f.WillBlock(typ) { t.Errorf("ipv4.ICMPFilter.Set(%v, true) failed", typ) } } } } func TestSetICMPFilter(t *testing.T) { switch runtime.GOOS { case "linux": default: t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip4:icmp", "127.0.0.1") if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) var f ipv4.ICMPFilter f.SetAll(true) f.Accept(ipv4.ICMPTypeEcho) f.Accept(ipv4.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } kf, err := p.ICMPFilter() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(kf, &f) { t.Fatalf("got %#v; want %#v", kf, f) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/icmp_stub.go0000644061062106075000000000071013172163402023507 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !linux package ipv4 const sizeofICMPFilter = 0x0 type icmpFilter struct { } func (f *icmpFilter) accept(typ ICMPType) { } func (f *icmpFilter) block(typ ICMPType) { } func (f *icmpFilter) setAll(block bool) { } func (f *icmpFilter) willBlock(typ ICMPType) bool { return false } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/icmp_linux.go0000644061062106075000000000103213172163402023667 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 func (f *icmpFilter) accept(typ ICMPType) { f.Data &^= 1 << (uint32(typ) & 31) } func (f *icmpFilter) block(typ ICMPType) { f.Data |= 1 << (uint32(typ) & 31) } func (f *icmpFilter) setAll(block bool) { if block { f.Data = 1<<32 - 1 } else { f.Data = 0 } } func (f *icmpFilter) willBlock(typ ICMPType) bool { return f.Data&(1<<(uint32(typ)&31)) != 0 } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/icmp.go0000644061062106075000000000301713172163402022455 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import "golang.org/x/net/internal/iana" // An ICMPType represents a type of ICMP message. type ICMPType int func (typ ICMPType) String() string { s, ok := icmpTypes[typ] if !ok { return "" } return s } // Protocol returns the ICMPv4 protocol number. func (typ ICMPType) Protocol() int { return iana.ProtocolICMP } // An ICMPFilter represents an ICMP message filter for incoming // packets. The filter belongs to a packet delivery path on a host and // it cannot interact with forwarding packets or tunnel-outer packets. // // Note: RFC 8200 defines a reasonable role model and it works not // only for IPv6 but IPv4. A node means a device that implements IP. // A router means a node that forwards IP packets not explicitly // addressed to itself, and a host means a node that is not a router. type ICMPFilter struct { icmpFilter } // Accept accepts incoming ICMP packets including the type field value // typ. func (f *ICMPFilter) Accept(typ ICMPType) { f.accept(typ) } // Block blocks incoming ICMP packets including the type field value // typ. func (f *ICMPFilter) Block(typ ICMPType) { f.block(typ) } // SetAll sets the filter action to the filter. func (f *ICMPFilter) SetAll(block bool) { f.setAll(block) } // WillBlock reports whether the ICMP type will be blocked. func (f *ICMPFilter) WillBlock(typ ICMPType) bool { return f.willBlock(typ) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/iana.go0000644061062106075000000000231313172163402022433 0ustar stgraberdomain admins// go generate gen.go // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package ipv4 // Internet Control Message Protocol (ICMP) Parameters, Updated: 2013-04-19 const ( ICMPTypeEchoReply ICMPType = 0 // Echo Reply ICMPTypeDestinationUnreachable ICMPType = 3 // Destination Unreachable ICMPTypeRedirect ICMPType = 5 // Redirect ICMPTypeEcho ICMPType = 8 // Echo ICMPTypeRouterAdvertisement ICMPType = 9 // Router Advertisement ICMPTypeRouterSolicitation ICMPType = 10 // Router Solicitation ICMPTypeTimeExceeded ICMPType = 11 // Time Exceeded ICMPTypeParameterProblem ICMPType = 12 // Parameter Problem ICMPTypeTimestamp ICMPType = 13 // Timestamp ICMPTypeTimestampReply ICMPType = 14 // Timestamp Reply ICMPTypePhoturis ICMPType = 40 // Photuris ) // Internet Control Message Protocol (ICMP) Parameters, Updated: 2013-04-19 var icmpTypes = map[ICMPType]string{ 0: "echo reply", 3: "destination unreachable", 5: "redirect", 8: "echo", 9: "router advertisement", 10: "router solicitation", 11: "time exceeded", 12: "parameter problem", 13: "timestamp", 14: "timestamp reply", 40: "photuris", } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/helper.go0000644061062106075000000000250513172163402023005 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "errors" "net" ) var ( errMissingAddress = errors.New("missing address") errMissingHeader = errors.New("missing header") errHeaderTooShort = errors.New("header too short") errBufferTooShort = errors.New("buffer too short") errInvalidConnType = errors.New("invalid conn type") errOpNoSupport = errors.New("operation not supported") errNoSuchInterface = errors.New("no such interface") errNoSuchMulticastInterface = errors.New("no such multicast interface") // See http://www.freebsd.org/doc/en/books/porters-handbook/freebsd-versions.html. freebsdVersion uint32 ) func boolint(b bool) int { if b { return 1 } return 0 } func netAddrToIP4(a net.Addr) net.IP { switch v := a.(type) { case *net.UDPAddr: if ip := v.IP.To4(); ip != nil { return ip } case *net.IPAddr: if ip := v.IP.To4(); ip != nil { return ip } } return nil } func opAddr(a net.Addr) net.Addr { switch a.(type) { case *net.TCPAddr: if a == nil { return nil } case *net.UDPAddr: if a == nil { return nil } case *net.IPAddr: if a == nil { return nil } } return a } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/header_test.go0000644061062106075000000001215613172163402024020 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "bytes" "encoding/binary" "net" "reflect" "runtime" "strings" "testing" "golang.org/x/net/internal/socket" ) type headerTest struct { wireHeaderFromKernel []byte wireHeaderToKernel []byte wireHeaderFromTradBSDKernel []byte wireHeaderToTradBSDKernel []byte wireHeaderFromFreeBSD10Kernel []byte wireHeaderToFreeBSD10Kernel []byte *Header } var headerLittleEndianTests = []headerTest{ // TODO(mikio): Add platform dependent wire header formats when // we support new platforms. { wireHeaderFromKernel: []byte{ 0x45, 0x01, 0xbe, 0xef, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, }, wireHeaderToKernel: []byte{ 0x45, 0x01, 0xbe, 0xef, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, }, wireHeaderFromTradBSDKernel: []byte{ 0x45, 0x01, 0xdb, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, }, wireHeaderToTradBSDKernel: []byte{ 0x45, 0x01, 0xef, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, }, wireHeaderFromFreeBSD10Kernel: []byte{ 0x45, 0x01, 0xef, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, }, wireHeaderToFreeBSD10Kernel: []byte{ 0x45, 0x01, 0xef, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, }, Header: &Header{ Version: Version, Len: HeaderLen, TOS: 1, TotalLen: 0xbeef, ID: 0xcafe, Flags: DontFragment, FragOff: 1500, TTL: 255, Protocol: 1, Checksum: 0xdead, Src: net.IPv4(172, 16, 254, 254), Dst: net.IPv4(192, 168, 0, 1), }, }, // with option headers { wireHeaderFromKernel: []byte{ 0x46, 0x01, 0xbe, 0xf3, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, 0xff, 0xfe, 0xfe, 0xff, }, wireHeaderToKernel: []byte{ 0x46, 0x01, 0xbe, 0xf3, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, 0xff, 0xfe, 0xfe, 0xff, }, wireHeaderFromTradBSDKernel: []byte{ 0x46, 0x01, 0xdb, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, 0xff, 0xfe, 0xfe, 0xff, }, wireHeaderToTradBSDKernel: []byte{ 0x46, 0x01, 0xf3, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, 0xff, 0xfe, 0xfe, 0xff, }, wireHeaderFromFreeBSD10Kernel: []byte{ 0x46, 0x01, 0xf3, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, 0xff, 0xfe, 0xfe, 0xff, }, wireHeaderToFreeBSD10Kernel: []byte{ 0x46, 0x01, 0xf3, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, 0xff, 0xfe, 0xfe, 0xff, }, Header: &Header{ Version: Version, Len: HeaderLen + 4, TOS: 1, TotalLen: 0xbef3, ID: 0xcafe, Flags: DontFragment, FragOff: 1500, TTL: 255, Protocol: 1, Checksum: 0xdead, Src: net.IPv4(172, 16, 254, 254), Dst: net.IPv4(192, 168, 0, 1), Options: []byte{0xff, 0xfe, 0xfe, 0xff}, }, }, } func TestMarshalHeader(t *testing.T) { if socket.NativeEndian != binary.LittleEndian { t.Skip("no test for non-little endian machine yet") } for _, tt := range headerLittleEndianTests { b, err := tt.Header.Marshal() if err != nil { t.Fatal(err) } var wh []byte switch runtime.GOOS { case "darwin", "dragonfly", "netbsd": wh = tt.wireHeaderToTradBSDKernel case "freebsd": switch { case freebsdVersion < 1000000: wh = tt.wireHeaderToTradBSDKernel case 1000000 <= freebsdVersion && freebsdVersion < 1100000: wh = tt.wireHeaderToFreeBSD10Kernel default: wh = tt.wireHeaderToKernel } default: wh = tt.wireHeaderToKernel } if !bytes.Equal(b, wh) { t.Fatalf("got %#v; want %#v", b, wh) } } } func TestParseHeader(t *testing.T) { if socket.NativeEndian != binary.LittleEndian { t.Skip("no test for big endian machine yet") } for _, tt := range headerLittleEndianTests { var wh []byte switch runtime.GOOS { case "darwin", "dragonfly", "netbsd": wh = tt.wireHeaderFromTradBSDKernel case "freebsd": switch { case freebsdVersion < 1000000: wh = tt.wireHeaderFromTradBSDKernel case 1000000 <= freebsdVersion && freebsdVersion < 1100000: wh = tt.wireHeaderFromFreeBSD10Kernel default: wh = tt.wireHeaderFromKernel } default: wh = tt.wireHeaderFromKernel } h, err := ParseHeader(wh) if err != nil { t.Fatal(err) } if err := h.Parse(wh); err != nil { t.Fatal(err) } if !reflect.DeepEqual(h, tt.Header) { t.Fatalf("got %#v; want %#v", h, tt.Header) } s := h.String() if strings.Contains(s, ",") { t.Fatalf("should be space-separated values: %s", s) } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/header.go0000644061062106075000000001112413172163402022753 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "encoding/binary" "fmt" "net" "runtime" "syscall" "golang.org/x/net/internal/socket" ) const ( Version = 4 // protocol version HeaderLen = 20 // header length without extension headers maxHeaderLen = 60 // sensible default, revisit if later RFCs define new usage of version and header length fields ) type HeaderFlags int const ( MoreFragments HeaderFlags = 1 << iota // more fragments flag DontFragment // don't fragment flag ) // A Header represents an IPv4 header. type Header struct { Version int // protocol version Len int // header length TOS int // type-of-service TotalLen int // packet total length ID int // identification Flags HeaderFlags // flags FragOff int // fragment offset TTL int // time-to-live Protocol int // next protocol Checksum int // checksum Src net.IP // source address Dst net.IP // destination address Options []byte // options, extension headers } func (h *Header) String() string { if h == nil { return "" } return fmt.Sprintf("ver=%d hdrlen=%d tos=%#x totallen=%d id=%#x flags=%#x fragoff=%#x ttl=%d proto=%d cksum=%#x src=%v dst=%v", h.Version, h.Len, h.TOS, h.TotalLen, h.ID, h.Flags, h.FragOff, h.TTL, h.Protocol, h.Checksum, h.Src, h.Dst) } // Marshal returns the binary encoding of h. func (h *Header) Marshal() ([]byte, error) { if h == nil { return nil, syscall.EINVAL } if h.Len < HeaderLen { return nil, errHeaderTooShort } hdrlen := HeaderLen + len(h.Options) b := make([]byte, hdrlen) b[0] = byte(Version<<4 | (hdrlen >> 2 & 0x0f)) b[1] = byte(h.TOS) flagsAndFragOff := (h.FragOff & 0x1fff) | int(h.Flags<<13) switch runtime.GOOS { case "darwin", "dragonfly", "netbsd": socket.NativeEndian.PutUint16(b[2:4], uint16(h.TotalLen)) socket.NativeEndian.PutUint16(b[6:8], uint16(flagsAndFragOff)) case "freebsd": if freebsdVersion < 1100000 { socket.NativeEndian.PutUint16(b[2:4], uint16(h.TotalLen)) socket.NativeEndian.PutUint16(b[6:8], uint16(flagsAndFragOff)) } else { binary.BigEndian.PutUint16(b[2:4], uint16(h.TotalLen)) binary.BigEndian.PutUint16(b[6:8], uint16(flagsAndFragOff)) } default: binary.BigEndian.PutUint16(b[2:4], uint16(h.TotalLen)) binary.BigEndian.PutUint16(b[6:8], uint16(flagsAndFragOff)) } binary.BigEndian.PutUint16(b[4:6], uint16(h.ID)) b[8] = byte(h.TTL) b[9] = byte(h.Protocol) binary.BigEndian.PutUint16(b[10:12], uint16(h.Checksum)) if ip := h.Src.To4(); ip != nil { copy(b[12:16], ip[:net.IPv4len]) } if ip := h.Dst.To4(); ip != nil { copy(b[16:20], ip[:net.IPv4len]) } else { return nil, errMissingAddress } if len(h.Options) > 0 { copy(b[HeaderLen:], h.Options) } return b, nil } // Parse parses b as an IPv4 header and sotres the result in h. func (h *Header) Parse(b []byte) error { if h == nil || len(b) < HeaderLen { return errHeaderTooShort } hdrlen := int(b[0]&0x0f) << 2 if hdrlen > len(b) { return errBufferTooShort } h.Version = int(b[0] >> 4) h.Len = hdrlen h.TOS = int(b[1]) h.ID = int(binary.BigEndian.Uint16(b[4:6])) h.TTL = int(b[8]) h.Protocol = int(b[9]) h.Checksum = int(binary.BigEndian.Uint16(b[10:12])) h.Src = net.IPv4(b[12], b[13], b[14], b[15]) h.Dst = net.IPv4(b[16], b[17], b[18], b[19]) switch runtime.GOOS { case "darwin", "dragonfly", "netbsd": h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4])) + hdrlen h.FragOff = int(socket.NativeEndian.Uint16(b[6:8])) case "freebsd": if freebsdVersion < 1100000 { h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4])) if freebsdVersion < 1000000 { h.TotalLen += hdrlen } h.FragOff = int(socket.NativeEndian.Uint16(b[6:8])) } else { h.TotalLen = int(binary.BigEndian.Uint16(b[2:4])) h.FragOff = int(binary.BigEndian.Uint16(b[6:8])) } default: h.TotalLen = int(binary.BigEndian.Uint16(b[2:4])) h.FragOff = int(binary.BigEndian.Uint16(b[6:8])) } h.Flags = HeaderFlags(h.FragOff&0xe000) >> 13 h.FragOff = h.FragOff & 0x1fff optlen := hdrlen - HeaderLen if optlen > 0 && len(b) >= hdrlen { if cap(h.Options) < optlen { h.Options = make([]byte, optlen) } else { h.Options = h.Options[:optlen] } copy(h.Options, b[HeaderLen:hdrlen]) } return nil } // ParseHeader parses b as an IPv4 header. func ParseHeader(b []byte) (*Header, error) { h := new(Header) if err := h.Parse(b); err != nil { return nil, err } return h, nil } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/genericopt.go0000644061062106075000000000230113172163402023657 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import "syscall" // TOS returns the type-of-service field value for outgoing packets. func (c *genericOpt) TOS() (int, error) { if !c.ok() { return 0, syscall.EINVAL } so, ok := sockOpts[ssoTOS] if !ok { return 0, errOpNoSupport } return so.GetInt(c.Conn) } // SetTOS sets the type-of-service field value for future outgoing // packets. func (c *genericOpt) SetTOS(tos int) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoTOS] if !ok { return errOpNoSupport } return so.SetInt(c.Conn, tos) } // TTL returns the time-to-live field value for outgoing packets. func (c *genericOpt) TTL() (int, error) { if !c.ok() { return 0, syscall.EINVAL } so, ok := sockOpts[ssoTTL] if !ok { return 0, errOpNoSupport } return so.GetInt(c.Conn) } // SetTTL sets the time-to-live field value for future outgoing // packets. func (c *genericOpt) SetTTL(ttl int) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoTTL] if !ok { return errOpNoSupport } return so.SetInt(c.Conn, ttl) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/gen.go0000644061062106075000000001052713172163402022302 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore //go:generate go run gen.go // This program generates system adaptation constants and types, // internet protocol constants and tables by reading template files // and IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "io/ioutil" "net/http" "os" "os/exec" "runtime" "strconv" "strings" ) func main() { if err := genzsys(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := geniana(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func genzsys() error { defs := "defs_" + runtime.GOOS + ".go" f, err := os.Open(defs) if err != nil { if os.IsNotExist(err) { return nil } return err } f.Close() cmd := exec.Command("go", "tool", "cgo", "-godefs", defs) b, err := cmd.Output() if err != nil { return err } b, err = format.Source(b) if err != nil { return err } zsys := "zsys_" + runtime.GOOS + ".go" switch runtime.GOOS { case "freebsd", "linux": zsys = "zsys_" + runtime.GOOS + "_" + runtime.GOARCH + ".go" } if err := ioutil.WriteFile(zsys, b, 0644); err != nil { return err } return nil } var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xml", parseICMPv4Parameters, }, } func geniana() error { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n") fmt.Fprintf(&bb, "package ipv4\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("got HTTP status code %v for %v\n", resp.StatusCode, r.url) } if err := r.parse(&bb, resp.Body); err != nil { return err } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { return err } if err := ioutil.WriteFile("iana.go", b, 0644); err != nil { return err } return nil } func parseICMPv4Parameters(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var icp icmpv4Parameters if err := dec.Decode(&icp); err != nil { return err } prs := icp.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Descr == "" { continue } fmt.Fprintf(w, "ICMPType%s ICMPType = %d", pr.Descr, pr.Value) fmt.Fprintf(w, "// %s\n", pr.OrigDescr) } fmt.Fprintf(w, ")\n\n") fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "var icmpTypes = map[ICMPType]string{\n") for _, pr := range prs { if pr.Descr == "" { continue } fmt.Fprintf(w, "%d: %q,\n", pr.Value, strings.ToLower(pr.OrigDescr)) } fmt.Fprintf(w, "}\n") return nil } type icmpv4Parameters struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Registries []struct { Title string `xml:"title"` Records []struct { Value string `xml:"value"` Descr string `xml:"description"` } `xml:"record"` } `xml:"registry"` } type canonICMPv4ParamRecord struct { OrigDescr string Descr string Value int } func (icp *icmpv4Parameters) escape() []canonICMPv4ParamRecord { id := -1 for i, r := range icp.Registries { if strings.Contains(r.Title, "Type") || strings.Contains(r.Title, "type") { id = i break } } if id < 0 { return nil } prs := make([]canonICMPv4ParamRecord, len(icp.Registries[id].Records)) sr := strings.NewReplacer( "Messages", "", "Message", "", "ICMP", "", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range icp.Registries[id].Records { if strings.Contains(pr.Descr, "Reserved") || strings.Contains(pr.Descr, "Unassigned") || strings.Contains(pr.Descr, "Deprecated") || strings.Contains(pr.Descr, "Experiment") || strings.Contains(pr.Descr, "experiment") { continue } ss := strings.Split(pr.Descr, "\n") if len(ss) > 1 { prs[i].Descr = strings.Join(ss, " ") } else { prs[i].Descr = ss[0] } s := strings.TrimSpace(prs[i].Descr) prs[i].OrigDescr = s prs[i].Descr = sr.Replace(s) prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/example_test.go0000644061062106075000000001233113172163402024216 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "fmt" "log" "net" "os" "runtime" "time" "golang.org/x/net/icmp" "golang.org/x/net/ipv4" ) func ExampleConn_markingTCP() { ln, err := net.Listen("tcp", "0.0.0.0:1024") if err != nil { log.Fatal(err) } defer ln.Close() for { c, err := ln.Accept() if err != nil { log.Fatal(err) } go func(c net.Conn) { defer c.Close() if c.RemoteAddr().(*net.TCPAddr).IP.To4() != nil { p := ipv4.NewConn(c) if err := p.SetTOS(0x28); err != nil { // DSCP AF11 log.Fatal(err) } if err := p.SetTTL(128); err != nil { log.Fatal(err) } } if _, err := c.Write([]byte("HELLO-R-U-THERE-ACK")); err != nil { log.Fatal(err) } }(c) } } func ExamplePacketConn_servingOneShotMulticastDNS() { c, err := net.ListenPacket("udp4", "0.0.0.0:5353") // mDNS over UDP if err != nil { log.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) en0, err := net.InterfaceByName("en0") if err != nil { log.Fatal(err) } mDNSLinkLocal := net.UDPAddr{IP: net.IPv4(224, 0, 0, 251)} if err := p.JoinGroup(en0, &mDNSLinkLocal); err != nil { log.Fatal(err) } defer p.LeaveGroup(en0, &mDNSLinkLocal) if err := p.SetControlMessage(ipv4.FlagDst, true); err != nil { log.Fatal(err) } b := make([]byte, 1500) for { _, cm, peer, err := p.ReadFrom(b) if err != nil { log.Fatal(err) } if !cm.Dst.IsMulticast() || !cm.Dst.Equal(mDNSLinkLocal.IP) { continue } answers := []byte("FAKE-MDNS-ANSWERS") // fake mDNS answers, you need to implement this if _, err := p.WriteTo(answers, nil, peer); err != nil { log.Fatal(err) } } } func ExamplePacketConn_tracingIPPacketRoute() { // Tracing an IP packet route to www.google.com. const host = "www.google.com" ips, err := net.LookupIP(host) if err != nil { log.Fatal(err) } var dst net.IPAddr for _, ip := range ips { if ip.To4() != nil { dst.IP = ip fmt.Printf("using %v for tracing an IP packet route to %s\n", dst.IP, host) break } } if dst.IP == nil { log.Fatal("no A record found") } c, err := net.ListenPacket("ip4:1", "0.0.0.0") // ICMP for IPv4 if err != nil { log.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) if err := p.SetControlMessage(ipv4.FlagTTL|ipv4.FlagSrc|ipv4.FlagDst|ipv4.FlagInterface, true); err != nil { log.Fatal(err) } wm := icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Data: []byte("HELLO-R-U-THERE"), }, } rb := make([]byte, 1500) for i := 1; i <= 64; i++ { // up to 64 hops wm.Body.(*icmp.Echo).Seq = i wb, err := wm.Marshal(nil) if err != nil { log.Fatal(err) } if err := p.SetTTL(i); err != nil { log.Fatal(err) } // In the real world usually there are several // multiple traffic-engineered paths for each hop. // You may need to probe a few times to each hop. begin := time.Now() if _, err := p.WriteTo(wb, nil, &dst); err != nil { log.Fatal(err) } if err := p.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil { log.Fatal(err) } n, cm, peer, err := p.ReadFrom(rb) if err != nil { if err, ok := err.(net.Error); ok && err.Timeout() { fmt.Printf("%v\t*\n", i) continue } log.Fatal(err) } rm, err := icmp.ParseMessage(1, rb[:n]) if err != nil { log.Fatal(err) } rtt := time.Since(begin) // In the real world you need to determine whether the // received message is yours using ControlMessage.Src, // ControlMessage.Dst, icmp.Echo.ID and icmp.Echo.Seq. switch rm.Type { case ipv4.ICMPTypeTimeExceeded: names, _ := net.LookupAddr(peer.String()) fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, cm) case ipv4.ICMPTypeEchoReply: names, _ := net.LookupAddr(peer.String()) fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, cm) return default: log.Printf("unknown ICMP message: %+v\n", rm) } } } func ExampleRawConn_advertisingOSPFHello() { c, err := net.ListenPacket("ip4:89", "0.0.0.0") // OSPF for IPv4 if err != nil { log.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { log.Fatal(err) } en0, err := net.InterfaceByName("en0") if err != nil { log.Fatal(err) } allSPFRouters := net.IPAddr{IP: net.IPv4(224, 0, 0, 5)} if err := r.JoinGroup(en0, &allSPFRouters); err != nil { log.Fatal(err) } defer r.LeaveGroup(en0, &allSPFRouters) hello := make([]byte, 24) // fake hello data, you need to implement this ospf := make([]byte, 24) // fake ospf header, you need to implement this ospf[0] = 2 // version 2 ospf[1] = 1 // hello packet ospf = append(ospf, hello...) iph := &ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TOS: 0xc0, // DSCP CS6 TotalLen: ipv4.HeaderLen + len(ospf), TTL: 1, Protocol: 89, Dst: allSPFRouters.IP.To4(), } var cm *ipv4.ControlMessage switch runtime.GOOS { case "darwin", "linux": cm = &ipv4.ControlMessage{IfIndex: en0.Index} default: if err := r.SetMulticastInterface(en0); err != nil { log.Fatal(err) } } if err := r.WriteTo(iph, ospf, cm); err != nil { log.Fatal(err) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/endpoint.go0000644061062106075000000001157713172163402023357 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "syscall" "time" "golang.org/x/net/internal/socket" ) // BUG(mikio): On Windows, the JoinSourceSpecificGroup, // LeaveSourceSpecificGroup, ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup methods of PacketConn and RawConn are // not implemented. // A Conn represents a network endpoint that uses the IPv4 transport. // It is used to control basic IP-level socket options such as TOS and // TTL. type Conn struct { genericOpt } type genericOpt struct { *socket.Conn } func (c *genericOpt) ok() bool { return c != nil && c.Conn != nil } // NewConn returns a new Conn. func NewConn(c net.Conn) *Conn { cc, _ := socket.NewConn(c) return &Conn{ genericOpt: genericOpt{Conn: cc}, } } // A PacketConn represents a packet network endpoint that uses the // IPv4 transport. It is used to control several IP-level socket // options including multicasting. It also provides datagram based // network I/O methods specific to the IPv4 and higher layer protocols // such as UDP. type PacketConn struct { genericOpt dgramOpt payloadHandler } type dgramOpt struct { *socket.Conn } func (c *dgramOpt) ok() bool { return c != nil && c.Conn != nil } // SetControlMessage sets the per packet IP-level socket options. func (c *PacketConn) SetControlMessage(cf ControlFlags, on bool) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return setControlMessage(c.dgramOpt.Conn, &c.payloadHandler.rawOpt, cf, on) } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *PacketConn) SetDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.PacketConn.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *PacketConn) SetReadDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.PacketConn.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *PacketConn) SetWriteDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.PacketConn.SetWriteDeadline(t) } // Close closes the endpoint. func (c *PacketConn) Close() error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.PacketConn.Close() } // NewPacketConn returns a new PacketConn using c as its underlying // transport. func NewPacketConn(c net.PacketConn) *PacketConn { cc, _ := socket.NewConn(c.(net.Conn)) p := &PacketConn{ genericOpt: genericOpt{Conn: cc}, dgramOpt: dgramOpt{Conn: cc}, payloadHandler: payloadHandler{PacketConn: c, Conn: cc}, } return p } // A RawConn represents a packet network endpoint that uses the IPv4 // transport. It is used to control several IP-level socket options // including IPv4 header manipulation. It also provides datagram // based network I/O methods specific to the IPv4 and higher layer // protocols that handle IPv4 datagram directly such as OSPF, GRE. type RawConn struct { genericOpt dgramOpt packetHandler } // SetControlMessage sets the per packet IP-level socket options. func (c *RawConn) SetControlMessage(cf ControlFlags, on bool) error { if !c.packetHandler.ok() { return syscall.EINVAL } return setControlMessage(c.dgramOpt.Conn, &c.packetHandler.rawOpt, cf, on) } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *RawConn) SetDeadline(t time.Time) error { if !c.packetHandler.ok() { return syscall.EINVAL } return c.packetHandler.IPConn.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *RawConn) SetReadDeadline(t time.Time) error { if !c.packetHandler.ok() { return syscall.EINVAL } return c.packetHandler.IPConn.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *RawConn) SetWriteDeadline(t time.Time) error { if !c.packetHandler.ok() { return syscall.EINVAL } return c.packetHandler.IPConn.SetWriteDeadline(t) } // Close closes the endpoint. func (c *RawConn) Close() error { if !c.packetHandler.ok() { return syscall.EINVAL } return c.packetHandler.IPConn.Close() } // NewRawConn returns a new RawConn using c as its underlying // transport. func NewRawConn(c net.PacketConn) (*RawConn, error) { cc, err := socket.NewConn(c.(net.Conn)) if err != nil { return nil, err } r := &RawConn{ genericOpt: genericOpt{Conn: cc}, dgramOpt: dgramOpt{Conn: cc}, packetHandler: packetHandler{IPConn: c.(*net.IPConn), Conn: cc}, } so, ok := sockOpts[ssoHeaderPrepend] if !ok { return nil, errOpNoSupport } if err := so.SetInt(r.dgramOpt.Conn, boolint(true)); err != nil { return nil, err } return r, nil } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/doc.go0000644061062106075000000001743113172163402022277 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ipv4 implements IP-level socket options for the Internet // Protocol version 4. // // The package provides IP-level socket options that allow // manipulation of IPv4 facilities. // // The IPv4 protocol and basic host requirements for IPv4 are defined // in RFC 791 and RFC 1122. // Host extensions for multicasting and socket interface extensions // for multicast source filters are defined in RFC 1112 and RFC 3678. // IGMPv1, IGMPv2 and IGMPv3 are defined in RFC 1112, RFC 2236 and RFC // 3376. // Source-specific multicast is defined in RFC 4607. // // // Unicasting // // The options for unicasting are available for net.TCPConn, // net.UDPConn and net.IPConn which are created as network connections // that use the IPv4 transport. When a single TCP connection carrying // a data flow of multiple packets needs to indicate the flow is // important, Conn is used to set the type-of-service field on the // IPv4 header for each packet. // // ln, err := net.Listen("tcp4", "0.0.0.0:1024") // if err != nil { // // error handling // } // defer ln.Close() // for { // c, err := ln.Accept() // if err != nil { // // error handling // } // go func(c net.Conn) { // defer c.Close() // // The outgoing packets will be labeled DiffServ assured forwarding // class 1 low drop precedence, known as AF11 packets. // // if err := ipv4.NewConn(c).SetTOS(0x28); err != nil { // // error handling // } // if _, err := c.Write(data); err != nil { // // error handling // } // }(c) // } // // // Multicasting // // The options for multicasting are available for net.UDPConn and // net.IPconn which are created as network connections that use the // IPv4 transport. A few network facilities must be prepared before // you begin multicasting, at a minimum joining network interfaces and // multicast groups. // // en0, err := net.InterfaceByName("en0") // if err != nil { // // error handling // } // en1, err := net.InterfaceByIndex(911) // if err != nil { // // error handling // } // group := net.IPv4(224, 0, 0, 250) // // First, an application listens to an appropriate address with an // appropriate service port. // // c, err := net.ListenPacket("udp4", "0.0.0.0:1024") // if err != nil { // // error handling // } // defer c.Close() // // Second, the application joins multicast groups, starts listening to // the groups on the specified network interfaces. Note that the // service port for transport layer protocol does not matter with this // operation as joining groups affects only network and link layer // protocols, such as IPv4 and Ethernet. // // p := ipv4.NewPacketConn(c) // if err := p.JoinGroup(en0, &net.UDPAddr{IP: group}); err != nil { // // error handling // } // if err := p.JoinGroup(en1, &net.UDPAddr{IP: group}); err != nil { // // error handling // } // // The application might set per packet control message transmissions // between the protocol stack within the kernel. When the application // needs a destination address on an incoming packet, // SetControlMessage of PacketConn is used to enable control message // transmissions. // // if err := p.SetControlMessage(ipv4.FlagDst, true); err != nil { // // error handling // } // // The application could identify whether the received packets are // of interest by using the control message that contains the // destination address of the received packet. // // b := make([]byte, 1500) // for { // n, cm, src, err := p.ReadFrom(b) // if err != nil { // // error handling // } // if cm.Dst.IsMulticast() { // if cm.Dst.Equal(group) { // // joined group, do something // } else { // // unknown group, discard // continue // } // } // // The application can also send both unicast and multicast packets. // // p.SetTOS(0x0) // p.SetTTL(16) // if _, err := p.WriteTo(data, nil, src); err != nil { // // error handling // } // dst := &net.UDPAddr{IP: group, Port: 1024} // for _, ifi := range []*net.Interface{en0, en1} { // if err := p.SetMulticastInterface(ifi); err != nil { // // error handling // } // p.SetMulticastTTL(2) // if _, err := p.WriteTo(data, nil, dst); err != nil { // // error handling // } // } // } // // // More multicasting // // An application that uses PacketConn or RawConn may join multiple // multicast groups. For example, a UDP listener with port 1024 might // join two different groups across over two different network // interfaces by using: // // c, err := net.ListenPacket("udp4", "0.0.0.0:1024") // if err != nil { // // error handling // } // defer c.Close() // p := ipv4.NewPacketConn(c) // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil { // // error handling // } // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}); err != nil { // // error handling // } // if err := p.JoinGroup(en1, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}); err != nil { // // error handling // } // // It is possible for multiple UDP listeners that listen on the same // UDP port to join the same multicast group. The net package will // provide a socket that listens to a wildcard address with reusable // UDP port when an appropriate multicast address prefix is passed to // the net.ListenPacket or net.ListenUDP. // // c1, err := net.ListenPacket("udp4", "224.0.0.0:1024") // if err != nil { // // error handling // } // defer c1.Close() // c2, err := net.ListenPacket("udp4", "224.0.0.0:1024") // if err != nil { // // error handling // } // defer c2.Close() // p1 := ipv4.NewPacketConn(c1) // if err := p1.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil { // // error handling // } // p2 := ipv4.NewPacketConn(c2) // if err := p2.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil { // // error handling // } // // Also it is possible for the application to leave or rejoin a // multicast group on the network interface. // // if err := p.LeaveGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil { // // error handling // } // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 250)}); err != nil { // // error handling // } // // // Source-specific multicasting // // An application that uses PacketConn or RawConn on IGMPv3 supported // platform is able to join source-specific multicast groups. // The application may use JoinSourceSpecificGroup and // LeaveSourceSpecificGroup for the operation known as "include" mode, // // ssmgroup := net.UDPAddr{IP: net.IPv4(232, 7, 8, 9)} // ssmsource := net.UDPAddr{IP: net.IPv4(192, 168, 0, 1)}) // if err := p.JoinSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { // // error handling // } // if err := p.LeaveSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { // // error handling // } // // or JoinGroup, ExcludeSourceSpecificGroup, // IncludeSourceSpecificGroup and LeaveGroup for the operation known // as "exclude" mode. // // exclsource := net.UDPAddr{IP: net.IPv4(192, 168, 0, 254)} // if err := p.JoinGroup(en0, &ssmgroup); err != nil { // // error handling // } // if err := p.ExcludeSourceSpecificGroup(en0, &ssmgroup, &exclsource); err != nil { // // error handling // } // if err := p.LeaveGroup(en0, &ssmgroup); err != nil { // // error handling // } // // Note that it depends on each platform implementation what happens // when an application which runs on IGMPv3 unsupported platform uses // JoinSourceSpecificGroup and LeaveSourceSpecificGroup. // In general the platform tries to fall back to conversations using // IGMPv1 or IGMPv2 and starts to listen to multicast traffic. // In the fallback case, ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup may return an error. package ipv4 // import "golang.org/x/net/ipv4" // BUG(mikio): This package is not implemented on NaCl and Plan 9. lxd-2.0.11/dist/src/golang.org/x/net/ipv4/dgramopt.go0000644061062106075000000001512313172163402023343 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "net" "syscall" "golang.org/x/net/bpf" ) // MulticastTTL returns the time-to-live field value for outgoing // multicast packets. func (c *dgramOpt) MulticastTTL() (int, error) { if !c.ok() { return 0, syscall.EINVAL } so, ok := sockOpts[ssoMulticastTTL] if !ok { return 0, errOpNoSupport } return so.GetInt(c.Conn) } // SetMulticastTTL sets the time-to-live field value for future // outgoing multicast packets. func (c *dgramOpt) SetMulticastTTL(ttl int) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoMulticastTTL] if !ok { return errOpNoSupport } return so.SetInt(c.Conn, ttl) } // MulticastInterface returns the default interface for multicast // packet transmissions. func (c *dgramOpt) MulticastInterface() (*net.Interface, error) { if !c.ok() { return nil, syscall.EINVAL } so, ok := sockOpts[ssoMulticastInterface] if !ok { return nil, errOpNoSupport } return so.getMulticastInterface(c.Conn) } // SetMulticastInterface sets the default interface for future // multicast packet transmissions. func (c *dgramOpt) SetMulticastInterface(ifi *net.Interface) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoMulticastInterface] if !ok { return errOpNoSupport } return so.setMulticastInterface(c.Conn, ifi) } // MulticastLoopback reports whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) MulticastLoopback() (bool, error) { if !c.ok() { return false, syscall.EINVAL } so, ok := sockOpts[ssoMulticastLoopback] if !ok { return false, errOpNoSupport } on, err := so.GetInt(c.Conn) if err != nil { return false, err } return on == 1, nil } // SetMulticastLoopback sets whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) SetMulticastLoopback(on bool) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoMulticastLoopback] if !ok { return errOpNoSupport } return so.SetInt(c.Conn, boolint(on)) } // JoinGroup joins the group address group on the interface ifi. // By default all sources that can cast data to group are accepted. // It's possible to mute and unmute data transmission from a specific // source by using ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup. // JoinGroup uses the system assigned multicast interface when ifi is // nil, although this is not recommended because the assignment // depends on platforms and sometimes it might require routing // configuration. func (c *dgramOpt) JoinGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoJoinGroup] if !ok { return errOpNoSupport } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } return so.setGroup(c.Conn, ifi, grp) } // LeaveGroup leaves the group address group on the interface ifi // regardless of whether the group is any-source group or // source-specific group. func (c *dgramOpt) LeaveGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoLeaveGroup] if !ok { return errOpNoSupport } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } return so.setGroup(c.Conn, ifi, grp) } // JoinSourceSpecificGroup joins the source-specific group comprising // group and source on the interface ifi. // JoinSourceSpecificGroup uses the system assigned multicast // interface when ifi is nil, although this is not recommended because // the assignment depends on platforms and sometimes it might require // routing configuration. func (c *dgramOpt) JoinSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoJoinSourceGroup] if !ok { return errOpNoSupport } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // LeaveSourceSpecificGroup leaves the source-specific group on the // interface ifi. func (c *dgramOpt) LeaveSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoLeaveSourceGroup] if !ok { return errOpNoSupport } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // ExcludeSourceSpecificGroup excludes the source-specific group from // the already joined any-source groups by JoinGroup on the interface // ifi. func (c *dgramOpt) ExcludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoBlockSourceGroup] if !ok { return errOpNoSupport } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // IncludeSourceSpecificGroup includes the excluded source-specific // group by ExcludeSourceSpecificGroup again on the interface ifi. func (c *dgramOpt) IncludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoUnblockSourceGroup] if !ok { return errOpNoSupport } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return so.setSourceGroup(c.Conn, ifi, grp, src) } // ICMPFilter returns an ICMP filter. // Currently only Linux supports this. func (c *dgramOpt) ICMPFilter() (*ICMPFilter, error) { if !c.ok() { return nil, syscall.EINVAL } so, ok := sockOpts[ssoICMPFilter] if !ok { return nil, errOpNoSupport } return so.getICMPFilter(c.Conn) } // SetICMPFilter deploys the ICMP filter. // Currently only Linux supports this. func (c *dgramOpt) SetICMPFilter(f *ICMPFilter) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoICMPFilter] if !ok { return errOpNoSupport } return so.setICMPFilter(c.Conn, f) } // SetBPF attaches a BPF program to the connection. // // Only supported on Linux. func (c *dgramOpt) SetBPF(filter []bpf.RawInstruction) error { if !c.ok() { return syscall.EINVAL } so, ok := sockOpts[ssoAttachFilter] if !ok { return errOpNoSupport } return so.setBPF(c.Conn, filter) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/defs_solaris.go0000644061062106075000000000501213172163402024177 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_RECVSLLA = C.IP_RECVSLLA sysIP_RECVTTL = C.IP_RECVTTL sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP sysIP_NEXTHOP = C.IP_NEXTHOP sysIP_PKTINFO = C.IP_PKTINFO sysIP_RECVPKTINFO = C.IP_RECVPKTINFO sysIP_DONTFRAG = C.IP_DONTFRAG sysIP_BOUND_IF = C.IP_BOUND_IF sysIP_UNSPEC_SRC = C.IP_UNSPEC_SRC sysIP_BROADCAST_TTL = C.IP_BROADCAST_TTL sysIP_DHCPINIT_IF = C.IP_DHCPINIT_IF sysIP_REUSEADDR = C.IP_REUSEADDR sysIP_DONTROUTE = C.IP_DONTROUTE sysIP_BROADCAST = C.IP_BROADCAST sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofInetPktinfo = C.sizeof_struct_in_pktinfo sizeofIPMreq = C.sizeof_struct_ip_mreq sizeofIPMreqSource = C.sizeof_struct_ip_mreq_source sizeofGroupReq = C.sizeof_struct_group_req sizeofGroupSourceReq = C.sizeof_struct_group_source_req ) type sockaddrStorage C.struct_sockaddr_storage type sockaddrInet C.struct_sockaddr_in type inetPktinfo C.struct_in_pktinfo type ipMreq C.struct_ip_mreq type ipMreqSource C.struct_ip_mreq_source type groupReq C.struct_group_req type groupSourceReq C.struct_group_source_req lxd-2.0.11/dist/src/golang.org/x/net/ipv4/defs_openbsd.go0000644061062106075000000000164413172163402024164 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_RECVTTL = C.IP_RECVTTL sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sizeofIPMreq = C.sizeof_struct_ip_mreq ) type ipMreq C.struct_ip_mreq lxd-2.0.11/dist/src/golang.org/x/net/ipv4/defs_netbsd.go0000644061062106075000000000164413172163402024011 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_RECVTTL = C.IP_RECVTTL sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sizeofIPMreq = C.sizeof_struct_ip_mreq ) type ipMreq C.struct_ip_mreq lxd-2.0.11/dist/src/golang.org/x/net/ipv4/defs_linux.go0000644061062106075000000000774613172163402023702 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include #include #include #include #include #include */ import "C" const ( sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_HDRINCL = C.IP_HDRINCL sysIP_OPTIONS = C.IP_OPTIONS sysIP_ROUTER_ALERT = C.IP_ROUTER_ALERT sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RETOPTS = C.IP_RETOPTS sysIP_PKTINFO = C.IP_PKTINFO sysIP_PKTOPTIONS = C.IP_PKTOPTIONS sysIP_MTU_DISCOVER = C.IP_MTU_DISCOVER sysIP_RECVERR = C.IP_RECVERR sysIP_RECVTTL = C.IP_RECVTTL sysIP_RECVTOS = C.IP_RECVTOS sysIP_MTU = C.IP_MTU sysIP_FREEBIND = C.IP_FREEBIND sysIP_TRANSPARENT = C.IP_TRANSPARENT sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_ORIGDSTADDR = C.IP_ORIGDSTADDR sysIP_RECVORIGDSTADDR = C.IP_RECVORIGDSTADDR sysIP_MINTTL = C.IP_MINTTL sysIP_NODEFRAG = C.IP_NODEFRAG sysIP_UNICAST_IF = C.IP_UNICAST_IF sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP sysIP_MSFILTER = C.IP_MSFILTER sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysMCAST_MSFILTER = C.MCAST_MSFILTER sysIP_MULTICAST_ALL = C.IP_MULTICAST_ALL //sysIP_PMTUDISC_DONT = C.IP_PMTUDISC_DONT //sysIP_PMTUDISC_WANT = C.IP_PMTUDISC_WANT //sysIP_PMTUDISC_DO = C.IP_PMTUDISC_DO //sysIP_PMTUDISC_PROBE = C.IP_PMTUDISC_PROBE //sysIP_PMTUDISC_INTERFACE = C.IP_PMTUDISC_INTERFACE //sysIP_PMTUDISC_OMIT = C.IP_PMTUDISC_OMIT sysICMP_FILTER = C.ICMP_FILTER sysSO_EE_ORIGIN_NONE = C.SO_EE_ORIGIN_NONE sysSO_EE_ORIGIN_LOCAL = C.SO_EE_ORIGIN_LOCAL sysSO_EE_ORIGIN_ICMP = C.SO_EE_ORIGIN_ICMP sysSO_EE_ORIGIN_ICMP6 = C.SO_EE_ORIGIN_ICMP6 sysSO_EE_ORIGIN_TXSTATUS = C.SO_EE_ORIGIN_TXSTATUS sysSO_EE_ORIGIN_TIMESTAMPING = C.SO_EE_ORIGIN_TIMESTAMPING sysSOL_SOCKET = C.SOL_SOCKET sysSO_ATTACH_FILTER = C.SO_ATTACH_FILTER sizeofKernelSockaddrStorage = C.sizeof_struct___kernel_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofInetPktinfo = C.sizeof_struct_in_pktinfo sizeofSockExtendedErr = C.sizeof_struct_sock_extended_err sizeofIPMreq = C.sizeof_struct_ip_mreq sizeofIPMreqn = C.sizeof_struct_ip_mreqn sizeofIPMreqSource = C.sizeof_struct_ip_mreq_source sizeofGroupReq = C.sizeof_struct_group_req sizeofGroupSourceReq = C.sizeof_struct_group_source_req sizeofICMPFilter = C.sizeof_struct_icmp_filter sizeofSockFprog = C.sizeof_struct_sock_fprog ) type kernelSockaddrStorage C.struct___kernel_sockaddr_storage type sockaddrInet C.struct_sockaddr_in type inetPktinfo C.struct_in_pktinfo type sockExtendedErr C.struct_sock_extended_err type ipMreq C.struct_ip_mreq type ipMreqn C.struct_ip_mreqn type ipMreqSource C.struct_ip_mreq_source type groupReq C.struct_group_req type groupSourceReq C.struct_group_source_req type icmpFilter C.struct_icmp_filter type sockFProg C.struct_sock_fprog type sockFilter C.struct_sock_filter lxd-2.0.11/dist/src/golang.org/x/net/ipv4/defs_freebsd.go0000644061062106075000000000451113172163402024140 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_SENDSRCADDR = C.IP_SENDSRCADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_ONESBCAST = C.IP_ONESBCAST sysIP_BINDANY = C.IP_BINDANY sysIP_RECVTTL = C.IP_RECVTTL sysIP_MINTTL = C.IP_MINTTL sysIP_DONTFRAG = C.IP_DONTFRAG sysIP_RECVTOS = C.IP_RECVTOS sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofIPMreq = C.sizeof_struct_ip_mreq sizeofIPMreqn = C.sizeof_struct_ip_mreqn sizeofIPMreqSource = C.sizeof_struct_ip_mreq_source sizeofGroupReq = C.sizeof_struct_group_req sizeofGroupSourceReq = C.sizeof_struct_group_source_req ) type sockaddrStorage C.struct_sockaddr_storage type sockaddrInet C.struct_sockaddr_in type ipMreq C.struct_ip_mreq type ipMreqn C.struct_ip_mreqn type ipMreqSource C.struct_ip_mreq_source type groupReq C.struct_group_req type groupSourceReq C.struct_group_source_req lxd-2.0.11/dist/src/golang.org/x/net/ipv4/defs_dragonfly.go0000644061062106075000000000172013172163402024512 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_RECVTTL = C.IP_RECVTTL sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sizeofIPMreq = C.sizeof_struct_ip_mreq ) type ipMreq C.struct_ip_mreq lxd-2.0.11/dist/src/golang.org/x/net/ipv4/defs_darwin.go0000644061062106075000000000462613172163402024021 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_STRIPHDR = C.IP_STRIPHDR sysIP_RECVTTL = C.IP_RECVTTL sysIP_BOUND_IF = C.IP_BOUND_IF sysIP_PKTINFO = C.IP_PKTINFO sysIP_RECVPKTINFO = C.IP_RECVPKTINFO sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF sysIP_MULTICAST_IFINDEX = C.IP_MULTICAST_IFINDEX sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofInetPktinfo = C.sizeof_struct_in_pktinfo sizeofIPMreq = C.sizeof_struct_ip_mreq sizeofIPMreqn = C.sizeof_struct_ip_mreqn sizeofIPMreqSource = C.sizeof_struct_ip_mreq_source sizeofGroupReq = C.sizeof_struct_group_req sizeofGroupSourceReq = C.sizeof_struct_group_source_req ) type sockaddrStorage C.struct_sockaddr_storage type sockaddrInet C.struct_sockaddr_in type inetPktinfo C.struct_in_pktinfo type ipMreq C.struct_ip_mreq type ipMreqn C.struct_ip_mreqn type ipMreqSource C.struct_ip_mreq_source type groupReq C.struct_group_req type groupSourceReq C.struct_group_source_req lxd-2.0.11/dist/src/golang.org/x/net/ipv4/control_windows.go0000644061062106075000000000057313172163402024763 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "syscall" "golang.org/x/net/internal/socket" ) func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { // TODO(mikio): implement this return syscall.EWINDOWS } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/control_unix.go0000644061062106075000000000323713172163402024254 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package ipv4 import ( "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { opt.Lock() defer opt.Unlock() if so, ok := sockOpts[ssoReceiveTTL]; ok && cf&FlagTTL != 0 { if err := so.SetInt(c, boolint(on)); err != nil { return err } if on { opt.set(FlagTTL) } else { opt.clear(FlagTTL) } } if so, ok := sockOpts[ssoPacketInfo]; ok { if cf&(FlagSrc|FlagDst|FlagInterface) != 0 { if err := so.SetInt(c, boolint(on)); err != nil { return err } if on { opt.set(cf & (FlagSrc | FlagDst | FlagInterface)) } else { opt.clear(cf & (FlagSrc | FlagDst | FlagInterface)) } } } else { if so, ok := sockOpts[ssoReceiveDst]; ok && cf&FlagDst != 0 { if err := so.SetInt(c, boolint(on)); err != nil { return err } if on { opt.set(FlagDst) } else { opt.clear(FlagDst) } } if so, ok := sockOpts[ssoReceiveInterface]; ok && cf&FlagInterface != 0 { if err := so.SetInt(c, boolint(on)); err != nil { return err } if on { opt.set(FlagInterface) } else { opt.clear(FlagInterface) } } } return nil } func marshalTTL(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIP, sysIP_RECVTTL, 1) return m.Next(1) } func parseTTL(cm *ControlMessage, b []byte) { cm.TTL = int(*(*byte)(unsafe.Pointer(&b[:1][0]))) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/control_test.go0000644061062106075000000000074013172163402024244 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "testing" "golang.org/x/net/ipv4" ) func TestControlMessageParseWithFuzz(t *testing.T) { var cm ipv4.ControlMessage for _, fuzz := range []string{ "\f\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00", "\f\x00\x00\x00\x00\x00\x00\x00\x1a\x00\x00\x00", } { cm.Parse([]byte(fuzz)) } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/control_stub.go0000644061062106075000000000063113172163402024241 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package ipv4 import "golang.org/x/net/internal/socket" func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { return errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/control_pktinfo.go0000644061062106075000000000166113172163402024742 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin linux solaris package ipv4 import ( "net" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) func marshalPacketInfo(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIP, sysIP_PKTINFO, sizeofInetPktinfo) if cm != nil { pi := (*inetPktinfo)(unsafe.Pointer(&m.Data(sizeofInetPktinfo)[0])) if ip := cm.Src.To4(); ip != nil { copy(pi.Spec_dst[:], ip) } if cm.IfIndex > 0 { pi.setIfindex(cm.IfIndex) } } return m.Next(sizeofInetPktinfo) } func parsePacketInfo(cm *ControlMessage, b []byte) { pi := (*inetPktinfo)(unsafe.Pointer(&b[0])) cm.IfIndex = int(pi.Ifindex) if len(cm.Dst) < net.IPv4len { cm.Dst = make(net.IP, net.IPv4len) } copy(cm.Dst, pi.Addr[:]) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/control_bsd.go0000644061062106075000000000201513172163402024032 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package ipv4 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) func marshalDst(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIP, sysIP_RECVDSTADDR, net.IPv4len) return m.Next(net.IPv4len) } func parseDst(cm *ControlMessage, b []byte) { if len(cm.Dst) < net.IPv4len { cm.Dst = make(net.IP, net.IPv4len) } copy(cm.Dst, b[:net.IPv4len]) } func marshalInterface(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIP, sysIP_RECVIF, syscall.SizeofSockaddrDatalink) return m.Next(syscall.SizeofSockaddrDatalink) } func parseInterface(cm *ControlMessage, b []byte) { sadl := (*syscall.SockaddrDatalink)(unsafe.Pointer(&b[0])) cm.IfIndex = int(sadl.Index) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/control.go0000644061062106075000000001033713172163402023210 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4 import ( "fmt" "net" "sync" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) type rawOpt struct { sync.RWMutex cflags ControlFlags } func (c *rawOpt) set(f ControlFlags) { c.cflags |= f } func (c *rawOpt) clear(f ControlFlags) { c.cflags &^= f } func (c *rawOpt) isset(f ControlFlags) bool { return c.cflags&f != 0 } type ControlFlags uint const ( FlagTTL ControlFlags = 1 << iota // pass the TTL on the received packet FlagSrc // pass the source address on the received packet FlagDst // pass the destination address on the received packet FlagInterface // pass the interface index on the received packet ) // A ControlMessage represents per packet basis IP-level socket options. type ControlMessage struct { // Receiving socket options: SetControlMessage allows to // receive the options from the protocol stack using ReadFrom // method of PacketConn or RawConn. // // Specifying socket options: ControlMessage for WriteTo // method of PacketConn or RawConn allows to send the options // to the protocol stack. // TTL int // time-to-live, receiving only Src net.IP // source address, specifying only Dst net.IP // destination address, receiving only IfIndex int // interface index, must be 1 <= value when specifying } func (cm *ControlMessage) String() string { if cm == nil { return "" } return fmt.Sprintf("ttl=%d src=%v dst=%v ifindex=%d", cm.TTL, cm.Src, cm.Dst, cm.IfIndex) } // Marshal returns the binary encoding of cm. func (cm *ControlMessage) Marshal() []byte { if cm == nil { return nil } var m socket.ControlMessage if ctlOpts[ctlPacketInfo].name > 0 && (cm.Src.To4() != nil || cm.IfIndex > 0) { m = socket.NewControlMessage([]int{ctlOpts[ctlPacketInfo].length}) } if len(m) > 0 { ctlOpts[ctlPacketInfo].marshal(m, cm) } return m } // Parse parses b as a control message and stores the result in cm. func (cm *ControlMessage) Parse(b []byte) error { ms, err := socket.ControlMessage(b).Parse() if err != nil { return err } for _, m := range ms { lvl, typ, l, err := m.ParseHeader() if err != nil { return err } if lvl != iana.ProtocolIP { continue } switch { case typ == ctlOpts[ctlTTL].name && l >= ctlOpts[ctlTTL].length: ctlOpts[ctlTTL].parse(cm, m.Data(l)) case typ == ctlOpts[ctlDst].name && l >= ctlOpts[ctlDst].length: ctlOpts[ctlDst].parse(cm, m.Data(l)) case typ == ctlOpts[ctlInterface].name && l >= ctlOpts[ctlInterface].length: ctlOpts[ctlInterface].parse(cm, m.Data(l)) case typ == ctlOpts[ctlPacketInfo].name && l >= ctlOpts[ctlPacketInfo].length: ctlOpts[ctlPacketInfo].parse(cm, m.Data(l)) } } return nil } // NewControlMessage returns a new control message. // // The returned message is large enough for options specified by cf. func NewControlMessage(cf ControlFlags) []byte { opt := rawOpt{cflags: cf} var l int if opt.isset(FlagTTL) && ctlOpts[ctlTTL].name > 0 { l += socket.ControlMessageSpace(ctlOpts[ctlTTL].length) } if ctlOpts[ctlPacketInfo].name > 0 { if opt.isset(FlagSrc | FlagDst | FlagInterface) { l += socket.ControlMessageSpace(ctlOpts[ctlPacketInfo].length) } } else { if opt.isset(FlagDst) && ctlOpts[ctlDst].name > 0 { l += socket.ControlMessageSpace(ctlOpts[ctlDst].length) } if opt.isset(FlagInterface) && ctlOpts[ctlInterface].name > 0 { l += socket.ControlMessageSpace(ctlOpts[ctlInterface].length) } } var b []byte if l > 0 { b = make([]byte, l) } return b } // Ancillary data socket options const ( ctlTTL = iota // header field ctlSrc // header field ctlDst // header field ctlInterface // inbound or outbound interface ctlPacketInfo // inbound or outbound packet path ctlMax ) // A ctlOpt represents a binding for ancillary data socket option. type ctlOpt struct { name int // option name, must be equal or greater than 1 length int // option length marshal func([]byte, *ControlMessage) []byte parse func(*ControlMessage, []byte) } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/bpf_test.go0000644061062106075000000000355313172163402023340 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipv4_test import ( "net" "runtime" "testing" "time" "golang.org/x/net/bpf" "golang.org/x/net/ipv4" ) func TestBPF(t *testing.T) { if runtime.GOOS != "linux" { t.Skipf("not supported on %s", runtime.GOOS) } l, err := net.ListenPacket("udp4", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer l.Close() p := ipv4.NewPacketConn(l) // This filter accepts UDP packets whose first payload byte is // even. prog, err := bpf.Assemble([]bpf.Instruction{ // Load the first byte of the payload (skipping UDP header). bpf.LoadAbsolute{Off: 8, Size: 1}, // Select LSB of the byte. bpf.ALUOpConstant{Op: bpf.ALUOpAnd, Val: 1}, // Byte is even? bpf.JumpIf{Cond: bpf.JumpEqual, Val: 0, SkipFalse: 1}, // Accept. bpf.RetConstant{Val: 4096}, // Ignore. bpf.RetConstant{Val: 0}, }) if err != nil { t.Fatalf("compiling BPF: %s", err) } if err = p.SetBPF(prog); err != nil { t.Fatalf("attaching filter to Conn: %s", err) } s, err := net.Dial("udp4", l.LocalAddr().String()) if err != nil { t.Fatal(err) } defer s.Close() go func() { for i := byte(0); i < 10; i++ { s.Write([]byte{i}) } }() l.SetDeadline(time.Now().Add(2 * time.Second)) seen := make([]bool, 5) for { var b [512]byte n, _, err := l.ReadFrom(b[:]) if err != nil { t.Fatalf("reading from listener: %s", err) } if n != 1 { t.Fatalf("unexpected packet length, want 1, got %d", n) } if b[0] >= 10 { t.Fatalf("unexpected byte, want 0-9, got %d", b[0]) } if b[0]%2 != 0 { t.Fatalf("got odd byte %d, wanted only even bytes", b[0]) } seen[b[0]/2] = true seenAll := true for _, v := range seen { if !v { seenAll = false break } } if seenAll { break } } } lxd-2.0.11/dist/src/golang.org/x/net/ipv4/batch.go0000644061062106075000000001276113172163402022614 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package ipv4 import ( "net" "runtime" "syscall" "golang.org/x/net/internal/socket" ) // BUG(mikio): On Windows, the ReadBatch and WriteBatch methods of // PacketConn are not implemented. // BUG(mikio): On Windows, the ReadBatch and WriteBatch methods of // RawConn are not implemented. // A Message represents an IO message. // // type Message struct { // Buffers [][]byte // OOB []byte // Addr net.Addr // N int // NN int // Flags int // } // // The Buffers fields represents a list of contiguous buffers, which // can be used for vectored IO, for example, putting a header and a // payload in each slice. // When writing, the Buffers field must contain at least one byte to // write. // When reading, the Buffers field will always contain a byte to read. // // The OOB field contains protocol-specific control or miscellaneous // ancillary data known as out-of-band data. // It can be nil when not required. // // The Addr field specifies a destination address when writing. // It can be nil when the underlying protocol of the endpoint uses // connection-oriented communication. // After a successful read, it may contain the source address on the // received packet. // // The N field indicates the number of bytes read or written from/to // Buffers. // // The NN field indicates the number of bytes read or written from/to // OOB. // // The Flags field contains protocol-specific information on the // received message. type Message = socket.Message // ReadBatch reads a batch of messages. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_PEEK. // // On a successful read it returns the number of messages received, up // to len(ms). // // On Linux, a batch read will be optimized. // On other platforms, this method will read only a single message. // // Unlike the ReadFrom method, it doesn't strip the IPv4 header // followed by option headers from the received IPv4 datagram when the // underlying transport is net.IPConn. Each Buffers field of Message // must be large enough to accommodate an IPv4 header and option // headers. func (c *payloadHandler) ReadBatch(ms []Message, flags int) (int, error) { if !c.ok() { return 0, syscall.EINVAL } switch runtime.GOOS { case "linux": n, err := c.RecvMsgs([]socket.Message(ms), flags) if err != nil { err = &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } return n, err default: n := 1 err := c.RecvMsg(&ms[0], flags) if err != nil { n = 0 err = &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } return n, err } } // WriteBatch writes a batch of messages. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_DONTROUTE. // // It returns the number of messages written on a successful write. // // On Linux, a batch write will be optimized. // On other platforms, this method will write only a single message. func (c *payloadHandler) WriteBatch(ms []Message, flags int) (int, error) { if !c.ok() { return 0, syscall.EINVAL } switch runtime.GOOS { case "linux": n, err := c.SendMsgs([]socket.Message(ms), flags) if err != nil { err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } return n, err default: n := 1 err := c.SendMsg(&ms[0], flags) if err != nil { n = 0 err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} } return n, err } } // ReadBatch reads a batch of messages. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_PEEK. // // On a successful read it returns the number of messages received, up // to len(ms). // // On Linux, a batch read will be optimized. // On other platforms, this method will read only a single message. func (c *packetHandler) ReadBatch(ms []Message, flags int) (int, error) { if !c.ok() { return 0, syscall.EINVAL } switch runtime.GOOS { case "linux": n, err := c.RecvMsgs([]socket.Message(ms), flags) if err != nil { err = &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} } return n, err default: n := 1 err := c.RecvMsg(&ms[0], flags) if err != nil { n = 0 err = &net.OpError{Op: "read", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} } return n, err } } // WriteBatch writes a batch of messages. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_DONTROUTE. // // It returns the number of messages written on a successful write. // // On Linux, a batch write will be optimized. // On other platforms, this method will write only a single message. func (c *packetHandler) WriteBatch(ms []Message, flags int) (int, error) { if !c.ok() { return 0, syscall.EINVAL } switch runtime.GOOS { case "linux": n, err := c.SendMsgs([]socket.Message(ms), flags) if err != nil { err = &net.OpError{Op: "write", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} } return n, err default: n := 1 err := c.SendMsg(&ms[0], flags) if err != nil { n = 0 err = &net.OpError{Op: "write", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} } return n, err } } lxd-2.0.11/dist/src/golang.org/x/net/internal/0000755061062106075000000000000013172163402022127 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/internal/timeseries/0000755061062106075000000000000013172163402024300 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/internal/timeseries/timeseries_test.go0000644061062106075000000001071113172163402030037 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package timeseries import ( "math" "testing" "time" ) func isNear(x *Float, y float64, tolerance float64) bool { return math.Abs(x.Value()-y) < tolerance } func isApproximate(x *Float, y float64) bool { return isNear(x, y, 1e-2) } func checkApproximate(t *testing.T, o Observable, y float64) { x := o.(*Float) if !isApproximate(x, y) { t.Errorf("Wanted %g, got %g", y, x.Value()) } } func checkNear(t *testing.T, o Observable, y, tolerance float64) { x := o.(*Float) if !isNear(x, y, tolerance) { t.Errorf("Wanted %g +- %g, got %g", y, tolerance, x.Value()) } } var baseTime = time.Date(2013, 1, 1, 0, 0, 0, 0, time.UTC) func tu(s int64) time.Time { return baseTime.Add(time.Duration(s) * time.Second) } func tu2(s int64, ns int64) time.Time { return baseTime.Add(time.Duration(s)*time.Second + time.Duration(ns)*time.Nanosecond) } func TestBasicTimeSeries(t *testing.T) { ts := NewTimeSeries(NewFloat) fo := new(Float) *fo = Float(10) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) checkApproximate(t, ts.Range(tu(0), tu(1)), 40) checkApproximate(t, ts.Total(), 40) ts.AddWithTime(fo, tu(3)) ts.AddWithTime(fo, tu(3)) ts.AddWithTime(fo, tu(3)) checkApproximate(t, ts.Range(tu(0), tu(2)), 40) checkApproximate(t, ts.Range(tu(2), tu(4)), 30) checkApproximate(t, ts.Total(), 70) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) checkApproximate(t, ts.Range(tu(0), tu(2)), 60) checkApproximate(t, ts.Range(tu(2), tu(4)), 30) checkApproximate(t, ts.Total(), 90) *fo = Float(100) ts.AddWithTime(fo, tu(100)) checkApproximate(t, ts.Range(tu(99), tu(100)), 100) checkApproximate(t, ts.Range(tu(0), tu(4)), 36) checkApproximate(t, ts.Total(), 190) *fo = Float(10) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) checkApproximate(t, ts.Range(tu(0), tu(4)), 44) checkApproximate(t, ts.Range(tu(37), tu2(100, 100e6)), 100) checkApproximate(t, ts.Range(tu(50), tu2(100, 100e6)), 100) checkApproximate(t, ts.Range(tu(99), tu2(100, 100e6)), 100) checkApproximate(t, ts.Total(), 210) for i, l := range ts.ComputeRange(tu(36), tu(100), 64) { if i == 63 { checkApproximate(t, l, 100) } else { checkApproximate(t, l, 0) } } checkApproximate(t, ts.Range(tu(0), tu(100)), 210) checkApproximate(t, ts.Range(tu(10), tu(100)), 100) for i, l := range ts.ComputeRange(tu(0), tu(100), 100) { if i < 10 { checkApproximate(t, l, 11) } else if i >= 90 { checkApproximate(t, l, 10) } else { checkApproximate(t, l, 0) } } } func TestFloat(t *testing.T) { f := Float(1) if g, w := f.String(), "1"; g != w { t.Errorf("Float(1).String = %q; want %q", g, w) } f2 := Float(2) var o Observable = &f2 f.Add(o) if g, w := f.Value(), 3.0; g != w { t.Errorf("Float post-add = %v; want %v", g, w) } f.Multiply(2) if g, w := f.Value(), 6.0; g != w { t.Errorf("Float post-multiply = %v; want %v", g, w) } f.Clear() if g, w := f.Value(), 0.0; g != w { t.Errorf("Float post-clear = %v; want %v", g, w) } f.CopyFrom(&f2) if g, w := f.Value(), 2.0; g != w { t.Errorf("Float post-CopyFrom = %v; want %v", g, w) } } type mockClock struct { time time.Time } func (m *mockClock) Time() time.Time { return m.time } func (m *mockClock) Set(t time.Time) { m.time = t } const buckets = 6 var testResolutions = []time.Duration{ 10 * time.Second, // level holds one minute of observations 100 * time.Second, // level holds ten minutes of observations 10 * time.Minute, // level holds one hour of observations } // TestTimeSeries uses a small number of buckets to force a higher // error rate on approximations from the timeseries. type TestTimeSeries struct { timeSeries } func TestExpectedErrorRate(t *testing.T) { ts := new(TestTimeSeries) fake := new(mockClock) fake.Set(time.Now()) ts.timeSeries.init(testResolutions, NewFloat, buckets, fake) for i := 1; i <= 61*61; i++ { fake.Set(fake.Time().Add(1 * time.Second)) ob := Float(1) ts.AddWithTime(&ob, fake.Time()) // The results should be accurate within one missing bucket (1/6) of the observations recorded. checkNear(t, ts.Latest(0, buckets), min(float64(i), 60), 10) checkNear(t, ts.Latest(1, buckets), min(float64(i), 600), 100) checkNear(t, ts.Latest(2, buckets), min(float64(i), 3600), 600) } } func min(a, b float64) float64 { if a < b { return a } return b } lxd-2.0.11/dist/src/golang.org/x/net/internal/timeseries/timeseries.go0000644061062106075000000003512613172163402027007 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package timeseries implements a time series structure for stats collection. package timeseries // import "golang.org/x/net/internal/timeseries" import ( "fmt" "log" "time" ) const ( timeSeriesNumBuckets = 64 minuteHourSeriesNumBuckets = 60 ) var timeSeriesResolutions = []time.Duration{ 1 * time.Second, 10 * time.Second, 1 * time.Minute, 10 * time.Minute, 1 * time.Hour, 6 * time.Hour, 24 * time.Hour, // 1 day 7 * 24 * time.Hour, // 1 week 4 * 7 * 24 * time.Hour, // 4 weeks 16 * 7 * 24 * time.Hour, // 16 weeks } var minuteHourSeriesResolutions = []time.Duration{ 1 * time.Second, 1 * time.Minute, } // An Observable is a kind of data that can be aggregated in a time series. type Observable interface { Multiply(ratio float64) // Multiplies the data in self by a given ratio Add(other Observable) // Adds the data from a different observation to self Clear() // Clears the observation so it can be reused. CopyFrom(other Observable) // Copies the contents of a given observation to self } // Float attaches the methods of Observable to a float64. type Float float64 // NewFloat returns a Float. func NewFloat() Observable { f := Float(0) return &f } // String returns the float as a string. func (f *Float) String() string { return fmt.Sprintf("%g", f.Value()) } // Value returns the float's value. func (f *Float) Value() float64 { return float64(*f) } func (f *Float) Multiply(ratio float64) { *f *= Float(ratio) } func (f *Float) Add(other Observable) { o := other.(*Float) *f += *o } func (f *Float) Clear() { *f = 0 } func (f *Float) CopyFrom(other Observable) { o := other.(*Float) *f = *o } // A Clock tells the current time. type Clock interface { Time() time.Time } type defaultClock int var defaultClockInstance defaultClock func (defaultClock) Time() time.Time { return time.Now() } // Information kept per level. Each level consists of a circular list of // observations. The start of the level may be derived from end and the // len(buckets) * sizeInMillis. type tsLevel struct { oldest int // index to oldest bucketed Observable newest int // index to newest bucketed Observable end time.Time // end timestamp for this level size time.Duration // duration of the bucketed Observable buckets []Observable // collections of observations provider func() Observable // used for creating new Observable } func (l *tsLevel) Clear() { l.oldest = 0 l.newest = len(l.buckets) - 1 l.end = time.Time{} for i := range l.buckets { if l.buckets[i] != nil { l.buckets[i].Clear() l.buckets[i] = nil } } } func (l *tsLevel) InitLevel(size time.Duration, numBuckets int, f func() Observable) { l.size = size l.provider = f l.buckets = make([]Observable, numBuckets) } // Keeps a sequence of levels. Each level is responsible for storing data at // a given resolution. For example, the first level stores data at a one // minute resolution while the second level stores data at a one hour // resolution. // Each level is represented by a sequence of buckets. Each bucket spans an // interval equal to the resolution of the level. New observations are added // to the last bucket. type timeSeries struct { provider func() Observable // make more Observable numBuckets int // number of buckets in each level levels []*tsLevel // levels of bucketed Observable lastAdd time.Time // time of last Observable tracked total Observable // convenient aggregation of all Observable clock Clock // Clock for getting current time pending Observable // observations not yet bucketed pendingTime time.Time // what time are we keeping in pending dirty bool // if there are pending observations } // init initializes a level according to the supplied criteria. func (ts *timeSeries) init(resolutions []time.Duration, f func() Observable, numBuckets int, clock Clock) { ts.provider = f ts.numBuckets = numBuckets ts.clock = clock ts.levels = make([]*tsLevel, len(resolutions)) for i := range resolutions { if i > 0 && resolutions[i-1] >= resolutions[i] { log.Print("timeseries: resolutions must be monotonically increasing") break } newLevel := new(tsLevel) newLevel.InitLevel(resolutions[i], ts.numBuckets, ts.provider) ts.levels[i] = newLevel } ts.Clear() } // Clear removes all observations from the time series. func (ts *timeSeries) Clear() { ts.lastAdd = time.Time{} ts.total = ts.resetObservation(ts.total) ts.pending = ts.resetObservation(ts.pending) ts.pendingTime = time.Time{} ts.dirty = false for i := range ts.levels { ts.levels[i].Clear() } } // Add records an observation at the current time. func (ts *timeSeries) Add(observation Observable) { ts.AddWithTime(observation, ts.clock.Time()) } // AddWithTime records an observation at the specified time. func (ts *timeSeries) AddWithTime(observation Observable, t time.Time) { smallBucketDuration := ts.levels[0].size if t.After(ts.lastAdd) { ts.lastAdd = t } if t.After(ts.pendingTime) { ts.advance(t) ts.mergePendingUpdates() ts.pendingTime = ts.levels[0].end ts.pending.CopyFrom(observation) ts.dirty = true } else if t.After(ts.pendingTime.Add(-1 * smallBucketDuration)) { // The observation is close enough to go into the pending bucket. // This compensates for clock skewing and small scheduling delays // by letting the update stay in the fast path. ts.pending.Add(observation) ts.dirty = true } else { ts.mergeValue(observation, t) } } // mergeValue inserts the observation at the specified time in the past into all levels. func (ts *timeSeries) mergeValue(observation Observable, t time.Time) { for _, level := range ts.levels { index := (ts.numBuckets - 1) - int(level.end.Sub(t)/level.size) if 0 <= index && index < ts.numBuckets { bucketNumber := (level.oldest + index) % ts.numBuckets if level.buckets[bucketNumber] == nil { level.buckets[bucketNumber] = level.provider() } level.buckets[bucketNumber].Add(observation) } } ts.total.Add(observation) } // mergePendingUpdates applies the pending updates into all levels. func (ts *timeSeries) mergePendingUpdates() { if ts.dirty { ts.mergeValue(ts.pending, ts.pendingTime) ts.pending = ts.resetObservation(ts.pending) ts.dirty = false } } // advance cycles the buckets at each level until the latest bucket in // each level can hold the time specified. func (ts *timeSeries) advance(t time.Time) { if !t.After(ts.levels[0].end) { return } for i := 0; i < len(ts.levels); i++ { level := ts.levels[i] if !level.end.Before(t) { break } // If the time is sufficiently far, just clear the level and advance // directly. if !t.Before(level.end.Add(level.size * time.Duration(ts.numBuckets))) { for _, b := range level.buckets { ts.resetObservation(b) } level.end = time.Unix(0, (t.UnixNano()/level.size.Nanoseconds())*level.size.Nanoseconds()) } for t.After(level.end) { level.end = level.end.Add(level.size) level.newest = level.oldest level.oldest = (level.oldest + 1) % ts.numBuckets ts.resetObservation(level.buckets[level.newest]) } t = level.end } } // Latest returns the sum of the num latest buckets from the level. func (ts *timeSeries) Latest(level, num int) Observable { now := ts.clock.Time() if ts.levels[0].end.Before(now) { ts.advance(now) } ts.mergePendingUpdates() result := ts.provider() l := ts.levels[level] index := l.newest for i := 0; i < num; i++ { if l.buckets[index] != nil { result.Add(l.buckets[index]) } if index == 0 { index = ts.numBuckets } index-- } return result } // LatestBuckets returns a copy of the num latest buckets from level. func (ts *timeSeries) LatestBuckets(level, num int) []Observable { if level < 0 || level > len(ts.levels) { log.Print("timeseries: bad level argument: ", level) return nil } if num < 0 || num >= ts.numBuckets { log.Print("timeseries: bad num argument: ", num) return nil } results := make([]Observable, num) now := ts.clock.Time() if ts.levels[0].end.Before(now) { ts.advance(now) } ts.mergePendingUpdates() l := ts.levels[level] index := l.newest for i := 0; i < num; i++ { result := ts.provider() results[i] = result if l.buckets[index] != nil { result.CopyFrom(l.buckets[index]) } if index == 0 { index = ts.numBuckets } index -= 1 } return results } // ScaleBy updates observations by scaling by factor. func (ts *timeSeries) ScaleBy(factor float64) { for _, l := range ts.levels { for i := 0; i < ts.numBuckets; i++ { l.buckets[i].Multiply(factor) } } ts.total.Multiply(factor) ts.pending.Multiply(factor) } // Range returns the sum of observations added over the specified time range. // If start or finish times don't fall on bucket boundaries of the same // level, then return values are approximate answers. func (ts *timeSeries) Range(start, finish time.Time) Observable { return ts.ComputeRange(start, finish, 1)[0] } // Recent returns the sum of observations from the last delta. func (ts *timeSeries) Recent(delta time.Duration) Observable { now := ts.clock.Time() return ts.Range(now.Add(-delta), now) } // Total returns the total of all observations. func (ts *timeSeries) Total() Observable { ts.mergePendingUpdates() return ts.total } // ComputeRange computes a specified number of values into a slice using // the observations recorded over the specified time period. The return // values are approximate if the start or finish times don't fall on the // bucket boundaries at the same level or if the number of buckets spanning // the range is not an integral multiple of num. func (ts *timeSeries) ComputeRange(start, finish time.Time, num int) []Observable { if start.After(finish) { log.Printf("timeseries: start > finish, %v>%v", start, finish) return nil } if num < 0 { log.Printf("timeseries: num < 0, %v", num) return nil } results := make([]Observable, num) for _, l := range ts.levels { if !start.Before(l.end.Add(-l.size * time.Duration(ts.numBuckets))) { ts.extract(l, start, finish, num, results) return results } } // Failed to find a level that covers the desired range. So just // extract from the last level, even if it doesn't cover the entire // desired range. ts.extract(ts.levels[len(ts.levels)-1], start, finish, num, results) return results } // RecentList returns the specified number of values in slice over the most // recent time period of the specified range. func (ts *timeSeries) RecentList(delta time.Duration, num int) []Observable { if delta < 0 { return nil } now := ts.clock.Time() return ts.ComputeRange(now.Add(-delta), now, num) } // extract returns a slice of specified number of observations from a given // level over a given range. func (ts *timeSeries) extract(l *tsLevel, start, finish time.Time, num int, results []Observable) { ts.mergePendingUpdates() srcInterval := l.size dstInterval := finish.Sub(start) / time.Duration(num) dstStart := start srcStart := l.end.Add(-srcInterval * time.Duration(ts.numBuckets)) srcIndex := 0 // Where should scanning start? if dstStart.After(srcStart) { advance := dstStart.Sub(srcStart) / srcInterval srcIndex += int(advance) srcStart = srcStart.Add(advance * srcInterval) } // The i'th value is computed as show below. // interval = (finish/start)/num // i'th value = sum of observation in range // [ start + i * interval, // start + (i + 1) * interval ) for i := 0; i < num; i++ { results[i] = ts.resetObservation(results[i]) dstEnd := dstStart.Add(dstInterval) for srcIndex < ts.numBuckets && srcStart.Before(dstEnd) { srcEnd := srcStart.Add(srcInterval) if srcEnd.After(ts.lastAdd) { srcEnd = ts.lastAdd } if !srcEnd.Before(dstStart) { srcValue := l.buckets[(srcIndex+l.oldest)%ts.numBuckets] if !srcStart.Before(dstStart) && !srcEnd.After(dstEnd) { // dst completely contains src. if srcValue != nil { results[i].Add(srcValue) } } else { // dst partially overlaps src. overlapStart := maxTime(srcStart, dstStart) overlapEnd := minTime(srcEnd, dstEnd) base := srcEnd.Sub(srcStart) fraction := overlapEnd.Sub(overlapStart).Seconds() / base.Seconds() used := ts.provider() if srcValue != nil { used.CopyFrom(srcValue) } used.Multiply(fraction) results[i].Add(used) } if srcEnd.After(dstEnd) { break } } srcIndex++ srcStart = srcStart.Add(srcInterval) } dstStart = dstStart.Add(dstInterval) } } // resetObservation clears the content so the struct may be reused. func (ts *timeSeries) resetObservation(observation Observable) Observable { if observation == nil { observation = ts.provider() } else { observation.Clear() } return observation } // TimeSeries tracks data at granularities from 1 second to 16 weeks. type TimeSeries struct { timeSeries } // NewTimeSeries creates a new TimeSeries using the function provided for creating new Observable. func NewTimeSeries(f func() Observable) *TimeSeries { return NewTimeSeriesWithClock(f, defaultClockInstance) } // NewTimeSeriesWithClock creates a new TimeSeries using the function provided for creating new Observable and the clock for // assigning timestamps. func NewTimeSeriesWithClock(f func() Observable, clock Clock) *TimeSeries { ts := new(TimeSeries) ts.timeSeries.init(timeSeriesResolutions, f, timeSeriesNumBuckets, clock) return ts } // MinuteHourSeries tracks data at granularities of 1 minute and 1 hour. type MinuteHourSeries struct { timeSeries } // NewMinuteHourSeries creates a new MinuteHourSeries using the function provided for creating new Observable. func NewMinuteHourSeries(f func() Observable) *MinuteHourSeries { return NewMinuteHourSeriesWithClock(f, defaultClockInstance) } // NewMinuteHourSeriesWithClock creates a new MinuteHourSeries using the function provided for creating new Observable and the clock for // assigning timestamps. func NewMinuteHourSeriesWithClock(f func() Observable, clock Clock) *MinuteHourSeries { ts := new(MinuteHourSeries) ts.timeSeries.init(minuteHourSeriesResolutions, f, minuteHourSeriesNumBuckets, clock) return ts } func (ts *MinuteHourSeries) Minute() Observable { return ts.timeSeries.Latest(0, 60) } func (ts *MinuteHourSeries) Hour() Observable { return ts.timeSeries.Latest(1, 60) } func minTime(a, b time.Time) time.Time { if a.Before(b) { return a } return b } func maxTime(a, b time.Time) time.Time { if a.After(b) { return a } return b } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/0000755061062106075000000000000013172163402023417 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_solaris_amd64.go0000644061062106075000000000164113172163402027507 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_solaris.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1a sysSOCK_RAW = 0x4 ) type iovec struct { Base *int8 Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen int32 Pad_cgo_1 [4]byte Accrights *int8 Accrightslen int32 Pad_cgo_2 [4]byte } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 X__sin6_src_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x30 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x20 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_openbsd_arm.go0000644061062106075000000000151513172163402027331 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x18 sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_openbsd_amd64.go0000644061062106075000000000156613172163402027473 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x18 sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen uint32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x30 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_openbsd_386.go0000644061062106075000000000151513172163402027072 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x18 sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_netbsd_arm.go0000644061062106075000000000151313172163402027154 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_netbsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x18 sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_netbsd_amd64.go0000644061062106075000000000173213172163402027313 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_netbsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x18 sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type mmsghdr struct { Hdr msghdr Len uint32 Pad_cgo_0 [4]byte } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x30 sizeofMmsghdr = 0x40 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_netbsd_386.go0000644061062106075000000000162213172163402026716 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_netbsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x18 sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type mmsghdr struct { Hdr msghdr Len uint32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofMmsghdr = 0x20 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_s390x.go0000644061062106075000000000167713172163402027156 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type mmsghdr struct { Hdr msghdr Len uint32 Pad_cgo_0 [4]byte } type cmsghdr struct { Len uint64 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x38 sizeofMmsghdr = 0x40 sizeofCmsghdr = 0x10 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_ppc64le.go0000644061062106075000000000167713172163402027545 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type mmsghdr struct { Hdr msghdr Len uint32 Pad_cgo_0 [4]byte } type cmsghdr struct { Len uint64 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x38 sizeofMmsghdr = 0x40 sizeofCmsghdr = 0x10 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_ppc64.go0000644061062106075000000000167713172163402027224 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type mmsghdr struct { Hdr msghdr Len uint32 Pad_cgo_0 [4]byte } type cmsghdr struct { Len uint64 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x38 sizeofMmsghdr = 0x40 sizeofCmsghdr = 0x10 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_mipsle.go0000644061062106075000000000156613172163402027556 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type mmsghdr struct { Hdr msghdr Len uint32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofMmsghdr = 0x20 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_mips64le.go0000644061062106075000000000167713172163402027733 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type mmsghdr struct { Hdr msghdr Len uint32 Pad_cgo_0 [4]byte } type cmsghdr struct { Len uint64 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x38 sizeofMmsghdr = 0x40 sizeofCmsghdr = 0x10 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_mips64.go0000644061062106075000000000167713172163402027412 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type mmsghdr struct { Hdr msghdr Len uint32 Pad_cgo_0 [4]byte } type cmsghdr struct { Len uint64 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x38 sizeofMmsghdr = 0x40 sizeofCmsghdr = 0x10 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_mips.go0000644061062106075000000000156613172163402027235 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type mmsghdr struct { Hdr msghdr Len uint32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofMmsghdr = 0x20 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_arm64.go0000644061062106075000000000167713172163402027221 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type mmsghdr struct { Hdr msghdr Len uint32 Pad_cgo_0 [4]byte } type cmsghdr struct { Len uint64 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x38 sizeofMmsghdr = 0x40 sizeofCmsghdr = 0x10 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_arm.go0000644061062106075000000000156613172163402027044 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type mmsghdr struct { Hdr msghdr Len uint32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofMmsghdr = 0x20 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_amd64.go0000644061062106075000000000167713172163402027203 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 Pad_cgo_1 [4]byte } type mmsghdr struct { Hdr msghdr Len uint32 Pad_cgo_0 [4]byte } type cmsghdr struct { Len uint64 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x38 sizeofMmsghdr = 0x40 sizeofCmsghdr = 0x10 sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_linux_386.go0000644061062106075000000000156613172163402026605 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type mmsghdr struct { Hdr msghdr Len uint32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofMmsghdr = 0x20 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_freebsd_arm.go0000644061062106075000000000151413172163402027310 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1c sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_freebsd_amd64.go0000644061062106075000000000156513172163402027452 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1c sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x30 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_freebsd_386.go0000644061062106075000000000151413172163402027051 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1c sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_dragonfly_amd64.go0000644061062106075000000000156713172163402030027 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_dragonfly.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1c sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x30 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_darwin_arm.go0000644061062106075000000000151313172163402027161 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_darwin.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1e sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_darwin_amd64.go0000644061062106075000000000156413172163402027323 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_darwin.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1e sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint64 } type msghdr struct { Name *byte Namelen uint32 Pad_cgo_0 [4]byte Iov *iovec Iovlen int32 Pad_cgo_1 [4]byte Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x10 sizeofMsghdr = 0x30 sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/zsys_darwin_386.go0000644061062106075000000000151313172163402026722 0ustar stgraberdomain admins// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_darwin.go package socket const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x1e sysSOCK_RAW = 0x3 ) type iovec struct { Base *byte Len uint32 } type msghdr struct { Name *byte Namelen uint32 Iov *iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type cmsghdr struct { Len uint32 Level int32 Type int32 } type sockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofIovec = 0x8 sizeofMsghdr = 0x1c sizeofCmsghdr = 0xc sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_windows.go0000644061062106075000000000302613172163402026337 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket import ( "errors" "syscall" "unsafe" ) func probeProtocolStack() int { var p uintptr return int(unsafe.Sizeof(p)) } const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0x17 sysSOCK_RAW = 0x3 ) type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type sockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } const ( sizeofSockaddrInet = 0x10 sizeofSockaddrInet6 = 0x1c ) func getsockopt(s uintptr, level, name int, b []byte) (int, error) { l := uint32(len(b)) err := syscall.Getsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(unsafe.Pointer(&b[0])), (*int32)(unsafe.Pointer(&l))) return int(l), err } func setsockopt(s uintptr, level, name int, b []byte) error { return syscall.Setsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(unsafe.Pointer(&b[0])), int32(len(b))) } func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { return 0, errors.New("not implemented") } func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { return 0, errors.New("not implemented") } func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { return 0, errors.New("not implemented") } func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { return 0, errors.New("not implemented") } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_unix.go0000644061062106075000000000223513172163402025631 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux,!s390x,!386 netbsd openbsd package socket import ( "syscall" "unsafe" ) func getsockopt(s uintptr, level, name int, b []byte) (int, error) { l := uint32(len(b)) _, _, errno := syscall.Syscall6(syscall.SYS_GETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0) return int(l), errnoErr(errno) } func setsockopt(s uintptr, level, name int, b []byte) error { _, _, errno := syscall.Syscall6(syscall.SYS_SETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0) return errnoErr(errno) } func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { n, _, errno := syscall.Syscall(syscall.SYS_RECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags)) return int(n), errnoErr(errno) } func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { n, _, errno := syscall.Syscall(syscall.SYS_SENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags)) return int(n), errnoErr(errno) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_stub.go0000644061062106075000000000256113172163402025625 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package socket import ( "errors" "net" "runtime" "unsafe" ) const ( sysAF_UNSPEC = 0x0 sysAF_INET = 0x2 sysAF_INET6 = 0xa sysSOCK_RAW = 0x3 ) func probeProtocolStack() int { switch runtime.GOARCH { case "amd64p32", "mips64p32": return 4 default: var p uintptr return int(unsafe.Sizeof(p)) } } func marshalInetAddr(ip net.IP, port int, zone string) []byte { return nil } func parseInetAddr(b []byte, network string) (net.Addr, error) { return nil, errors.New("not implemented") } func getsockopt(s uintptr, level, name int, b []byte) (int, error) { return 0, errors.New("not implemented") } func setsockopt(s uintptr, level, name int, b []byte) error { return errors.New("not implemented") } func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { return 0, errors.New("not implemented") } func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { return 0, errors.New("not implemented") } func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { return 0, errors.New("not implemented") } func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { return 0, errors.New("not implemented") } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_solaris_amd64.s0000644061062106075000000000050013172163402027143 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "textflag.h" TEXT ·sysvicall6(SB),NOSPLIT,$0-88 JMP syscall·sysvicall6(SB) TEXT ·rawSysvicall6(SB),NOSPLIT,$0-88 JMP syscall·rawSysvicall6(SB) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_solaris.go0000644061062106075000000000447113172163402026326 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket import ( "errors" "runtime" "syscall" "unsafe" ) func probeProtocolStack() int { switch runtime.GOARCH { case "amd64": return 4 default: var p uintptr return int(unsafe.Sizeof(p)) } } //go:cgo_import_dynamic libc___xnet_getsockopt __xnet_getsockopt "libsocket.so" //go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so" //go:cgo_import_dynamic libc___xnet_recvmsg __xnet_recvmsg "libsocket.so" //go:cgo_import_dynamic libc___xnet_sendmsg __xnet_sendmsg "libsocket.so" //go:linkname procGetsockopt libc___xnet_getsockopt //go:linkname procSetsockopt libc_setsockopt //go:linkname procRecvmsg libc___xnet_recvmsg //go:linkname procSendmsg libc___xnet_sendmsg var ( procGetsockopt uintptr procSetsockopt uintptr procRecvmsg uintptr procSendmsg uintptr ) func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (uintptr, uintptr, syscall.Errno) func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (uintptr, uintptr, syscall.Errno) func getsockopt(s uintptr, level, name int, b []byte) (int, error) { l := uint32(len(b)) _, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procGetsockopt)), 5, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0) return int(l), errnoErr(errno) } func setsockopt(s uintptr, level, name int, b []byte) error { _, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procSetsockopt)), 5, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0) return errnoErr(errno) } func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { n, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procRecvmsg)), 3, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) return int(n), errnoErr(errno) } func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { n, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procSendmsg)), 3, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) return int(n), errnoErr(errno) } func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { return 0, errors.New("not implemented") } func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { return 0, errors.New("not implemented") } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_posix.go0000644061062106075000000001013113172163402026002 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package socket import ( "encoding/binary" "errors" "net" "runtime" "strconv" "sync" "time" ) func marshalInetAddr(a net.Addr) []byte { switch a := a.(type) { case *net.TCPAddr: return marshalSockaddr(a.IP, a.Port, a.Zone) case *net.UDPAddr: return marshalSockaddr(a.IP, a.Port, a.Zone) case *net.IPAddr: return marshalSockaddr(a.IP, 0, a.Zone) default: return nil } } func marshalSockaddr(ip net.IP, port int, zone string) []byte { if ip4 := ip.To4(); ip4 != nil { b := make([]byte, sizeofSockaddrInet) switch runtime.GOOS { case "android", "linux", "solaris", "windows": NativeEndian.PutUint16(b[:2], uint16(sysAF_INET)) default: b[0] = sizeofSockaddrInet b[1] = sysAF_INET } binary.BigEndian.PutUint16(b[2:4], uint16(port)) copy(b[4:8], ip4) return b } if ip6 := ip.To16(); ip6 != nil && ip.To4() == nil { b := make([]byte, sizeofSockaddrInet6) switch runtime.GOOS { case "android", "linux", "solaris", "windows": NativeEndian.PutUint16(b[:2], uint16(sysAF_INET6)) default: b[0] = sizeofSockaddrInet6 b[1] = sysAF_INET6 } binary.BigEndian.PutUint16(b[2:4], uint16(port)) copy(b[8:24], ip6) if zone != "" { NativeEndian.PutUint32(b[24:28], uint32(zoneCache.index(zone))) } return b } return nil } func parseInetAddr(b []byte, network string) (net.Addr, error) { if len(b) < 2 { return nil, errors.New("invalid address") } var af int switch runtime.GOOS { case "android", "linux", "solaris", "windows": af = int(NativeEndian.Uint16(b[:2])) default: af = int(b[1]) } var ip net.IP var zone string if af == sysAF_INET { if len(b) < sizeofSockaddrInet { return nil, errors.New("short address") } ip = make(net.IP, net.IPv4len) copy(ip, b[4:8]) } if af == sysAF_INET6 { if len(b) < sizeofSockaddrInet6 { return nil, errors.New("short address") } ip = make(net.IP, net.IPv6len) copy(ip, b[8:24]) if id := int(NativeEndian.Uint32(b[24:28])); id > 0 { zone = zoneCache.name(id) } } switch network { case "tcp", "tcp4", "tcp6": return &net.TCPAddr{IP: ip, Port: int(binary.BigEndian.Uint16(b[2:4])), Zone: zone}, nil case "udp", "udp4", "udp6": return &net.UDPAddr{IP: ip, Port: int(binary.BigEndian.Uint16(b[2:4])), Zone: zone}, nil default: return &net.IPAddr{IP: ip, Zone: zone}, nil } } // An ipv6ZoneCache represents a cache holding partial network // interface information. It is used for reducing the cost of IPv6 // addressing scope zone resolution. // // Multiple names sharing the index are managed by first-come // first-served basis for consistency. type ipv6ZoneCache struct { sync.RWMutex // guard the following lastFetched time.Time // last time routing information was fetched toIndex map[string]int // interface name to its index toName map[int]string // interface index to its name } var zoneCache = ipv6ZoneCache{ toIndex: make(map[string]int), toName: make(map[int]string), } func (zc *ipv6ZoneCache) update(ift []net.Interface) { zc.Lock() defer zc.Unlock() now := time.Now() if zc.lastFetched.After(now.Add(-60 * time.Second)) { return } zc.lastFetched = now if len(ift) == 0 { var err error if ift, err = net.Interfaces(); err != nil { return } } zc.toIndex = make(map[string]int, len(ift)) zc.toName = make(map[int]string, len(ift)) for _, ifi := range ift { zc.toIndex[ifi.Name] = ifi.Index if _, ok := zc.toName[ifi.Index]; !ok { zc.toName[ifi.Index] = ifi.Name } } } func (zc *ipv6ZoneCache) name(zone int) string { zoneCache.update(nil) zoneCache.RLock() defer zoneCache.RUnlock() name, ok := zoneCache.toName[zone] if !ok { name = strconv.Itoa(zone) } return name } func (zc *ipv6ZoneCache) index(zone string) int { zoneCache.update(nil) zoneCache.RLock() defer zoneCache.RUnlock() index, ok := zoneCache.toIndex[zone] if !ok { index, _ = strconv.Atoi(zone) } return index } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_netbsd.go0000644061062106075000000000130113172163402026116 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket import ( "syscall" "unsafe" ) const ( sysRECVMMSG = 0x1db sysSENDMMSG = 0x1dc ) func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { n, _, errno := syscall.Syscall6(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) return int(n), errnoErr(errno) } func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { n, _, errno := syscall.Syscall6(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) return int(n), errnoErr(errno) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_s390x.s0000644061062106075000000000050013172163402026601 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "textflag.h" TEXT ·socketcall(SB),NOSPLIT,$0-72 JMP syscall·socketcall(SB) TEXT ·rawsocketcall(SB),NOSPLIT,$0-72 JMP syscall·rawsocketcall(SB) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_s390x.go0000644061062106075000000000345113172163402026754 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket import ( "syscall" "unsafe" ) func probeProtocolStack() int { return 8 } const ( sysSETSOCKOPT = 0xe sysGETSOCKOPT = 0xf sysSENDMSG = 0x10 sysRECVMSG = 0x11 sysRECVMMSG = 0x13 sysSENDMMSG = 0x14 ) func socketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno) func rawsocketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno) func getsockopt(s uintptr, level, name int, b []byte) (int, error) { l := uint32(len(b)) _, errno := socketcall(sysGETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0) return int(l), errnoErr(errno) } func setsockopt(s uintptr, level, name int, b []byte) error { _, errno := socketcall(sysSETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0) return errnoErr(errno) } func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { n, errno := socketcall(sysRECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) return int(n), errnoErr(errno) } func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { n, errno := socketcall(sysSENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) return int(n), errnoErr(errno) } func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { n, errno := socketcall(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) return int(n), errnoErr(errno) } func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { n, errno := socketcall(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) return int(n), errnoErr(errno) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_ppc64le.go0000644061062106075000000000034413172163402027341 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0x157 sysSENDMMSG = 0x15d ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_ppc64.go0000644061062106075000000000034413172163402027020 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0x157 sysSENDMMSG = 0x15d ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_mipsle.go0000644061062106075000000000034613172163402027357 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0x10ef sysSENDMMSG = 0x10f7 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_mips64le.go0000644061062106075000000000034613172163402027531 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0x14ae sysSENDMMSG = 0x14b6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_mips64.go0000644061062106075000000000034613172163402027210 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0x14ae sysSENDMMSG = 0x14b6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_mips.go0000644061062106075000000000034613172163402027036 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0x10ef sysSENDMMSG = 0x10f7 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_arm64.go0000644061062106075000000000034313172163402027014 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0xf3 sysSENDMMSG = 0x10d ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_arm.go0000644061062106075000000000034413172163402026643 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0x16d sysSENDMMSG = 0x176 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_amd64.go0000644061062106075000000000034413172163402026777 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket const ( sysRECVMMSG = 0x12b sysSENDMMSG = 0x133 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_386.s0000644061062106075000000000050013172163402026233 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "textflag.h" TEXT ·socketcall(SB),NOSPLIT,$0-36 JMP syscall·socketcall(SB) TEXT ·rawsocketcall(SB),NOSPLIT,$0-36 JMP syscall·rawsocketcall(SB) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux_386.go0000644061062106075000000000345113172163402026406 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket import ( "syscall" "unsafe" ) func probeProtocolStack() int { return 4 } const ( sysSETSOCKOPT = 0xe sysGETSOCKOPT = 0xf sysSENDMSG = 0x10 sysRECVMSG = 0x11 sysRECVMMSG = 0x13 sysSENDMMSG = 0x14 ) func socketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno) func rawsocketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno) func getsockopt(s uintptr, level, name int, b []byte) (int, error) { l := uint32(len(b)) _, errno := socketcall(sysGETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0) return int(l), errnoErr(errno) } func setsockopt(s uintptr, level, name int, b []byte) error { _, errno := socketcall(sysSETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0) return errnoErr(errno) } func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { n, errno := socketcall(sysRECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) return int(n), errnoErr(errno) } func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { n, errno := socketcall(sysSENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) return int(n), errnoErr(errno) } func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { n, errno := socketcall(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) return int(n), errnoErr(errno) } func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { n, errno := socketcall(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) return int(n), errnoErr(errno) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_linux.go0000644061062106075000000000137113172163402026005 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux,!s390x,!386 package socket import ( "syscall" "unsafe" ) func probeProtocolStack() int { var p uintptr return int(unsafe.Sizeof(p)) } func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { n, _, errno := syscall.Syscall6(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) return int(n), errnoErr(errno) } func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { n, _, errno := syscall.Syscall6(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) return int(n), errnoErr(errno) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_dragonfly.go0000644061062106075000000000033313172163402026630 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket func probeProtocolStack() int { return 4 } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_darwin.go0000644061062106075000000000033313172163402026127 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket func probeProtocolStack() int { return 4 } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_bsdvar.go0000644061062106075000000000046213172163402026127 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build freebsd netbsd openbsd package socket import "unsafe" func probeProtocolStack() int { var p uintptr return int(unsafe.Sizeof(p)) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys_bsd.go0000644061062106075000000000070613172163402025417 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd openbsd package socket import "errors" func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { return 0, errors.New("not implemented") } func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { return 0, errors.New("not implemented") } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/sys.go0000644061062106075000000000117713172163402024572 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket import ( "encoding/binary" "unsafe" ) var ( // NativeEndian is the machine native endian implementation of // ByteOrder. NativeEndian binary.ByteOrder kernelAlign int ) func init() { i := uint32(1) b := (*[4]byte)(unsafe.Pointer(&i)) if b[0] == 1 { NativeEndian = binary.LittleEndian } else { NativeEndian = binary.BigEndian } kernelAlign = probeProtocolStack() } func roundup(l int) int { return (l + kernelAlign - 1) & ^(kernelAlign - 1) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/socket_test.go0000644061062106075000000000204713172163402026300 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package socket_test import ( "net" "runtime" "syscall" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/internal/socket" ) func TestSocket(t *testing.T) { t.Run("Option", func(t *testing.T) { testSocketOption(t, &socket.Option{Level: syscall.SOL_SOCKET, Name: syscall.SO_RCVBUF, Len: 4}) }) } func testSocketOption(t *testing.T, so *socket.Option) { c, err := nettest.NewLocalPacketListener("udp") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() cc, err := socket.NewConn(c.(net.Conn)) if err != nil { t.Fatal(err) } const N = 2048 if err := so.SetInt(cc, N); err != nil { t.Fatal(err) } n, err := so.GetInt(cc) if err != nil { t.Fatal(err) } if n < N { t.Fatalf("got %d; want greater than or equal to %d", n, N) } } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/socket_go1_9_test.go0000644061062106075000000001407213172163402027277 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 // +build darwin dragonfly freebsd linux netbsd openbsd solaris package socket_test import ( "bytes" "fmt" "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/internal/socket" ) type mockControl struct { Level int Type int Data []byte } func TestControlMessage(t *testing.T) { for _, tt := range []struct { cs []mockControl }{ { []mockControl{ {Level: 1, Type: 1}, }, }, { []mockControl{ {Level: 2, Type: 2, Data: []byte{0xfe}}, }, }, { []mockControl{ {Level: 3, Type: 3, Data: []byte{0xfe, 0xff, 0xff, 0xfe}}, }, }, { []mockControl{ {Level: 4, Type: 4, Data: []byte{0xfe, 0xff, 0xff, 0xfe, 0xfe, 0xff, 0xff, 0xfe}}, }, }, { []mockControl{ {Level: 4, Type: 4, Data: []byte{0xfe, 0xff, 0xff, 0xfe, 0xfe, 0xff, 0xff, 0xfe}}, {Level: 2, Type: 2, Data: []byte{0xfe}}, }, }, } { var w []byte var tailPadLen int mm := socket.NewControlMessage([]int{0}) for i, c := range tt.cs { m := socket.NewControlMessage([]int{len(c.Data)}) l := len(m) - len(mm) if i == len(tt.cs)-1 && l > len(c.Data) { tailPadLen = l - len(c.Data) } w = append(w, m...) } var err error ww := make([]byte, len(w)) copy(ww, w) m := socket.ControlMessage(ww) for _, c := range tt.cs { if err = m.MarshalHeader(c.Level, c.Type, len(c.Data)); err != nil { t.Fatalf("(%v).MarshalHeader() = %v", tt.cs, err) } copy(m.Data(len(c.Data)), c.Data) m = m.Next(len(c.Data)) } m = socket.ControlMessage(w) for _, c := range tt.cs { m, err = m.Marshal(c.Level, c.Type, c.Data) if err != nil { t.Fatalf("(%v).Marshal() = %v", tt.cs, err) } } if !bytes.Equal(ww, w) { t.Fatalf("got %#v; want %#v", ww, w) } ws := [][]byte{w} if tailPadLen > 0 { // Test a message with no tail padding. nopad := w[:len(w)-tailPadLen] ws = append(ws, [][]byte{nopad}...) } for _, w := range ws { ms, err := socket.ControlMessage(w).Parse() if err != nil { t.Fatalf("(%v).Parse() = %v", tt.cs, err) } for i, m := range ms { lvl, typ, dataLen, err := m.ParseHeader() if err != nil { t.Fatalf("(%v).ParseHeader() = %v", tt.cs, err) } if lvl != tt.cs[i].Level || typ != tt.cs[i].Type || dataLen != len(tt.cs[i].Data) { t.Fatalf("%v: got %d, %d, %d; want %d, %d, %d", tt.cs[i], lvl, typ, dataLen, tt.cs[i].Level, tt.cs[i].Type, len(tt.cs[i].Data)) } } } } } func TestUDP(t *testing.T) { c, err := nettest.NewLocalPacketListener("udp") if err != nil { t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() cc, err := socket.NewConn(c.(net.Conn)) if err != nil { t.Fatal(err) } t.Run("Message", func(t *testing.T) { data := []byte("HELLO-R-U-THERE") wm := socket.Message{ Buffers: bytes.SplitAfter(data, []byte("-")), Addr: c.LocalAddr(), } if err := cc.SendMsg(&wm, 0); err != nil { t.Fatal(err) } b := make([]byte, 32) rm := socket.Message{ Buffers: [][]byte{b[:1], b[1:3], b[3:7], b[7:11], b[11:]}, } if err := cc.RecvMsg(&rm, 0); err != nil { t.Fatal(err) } if !bytes.Equal(b[:rm.N], data) { t.Fatalf("got %#v; want %#v", b[:rm.N], data) } }) switch runtime.GOOS { case "android", "linux": t.Run("Messages", func(t *testing.T) { data := []byte("HELLO-R-U-THERE") wmbs := bytes.SplitAfter(data, []byte("-")) wms := []socket.Message{ {Buffers: wmbs[:1], Addr: c.LocalAddr()}, {Buffers: wmbs[1:], Addr: c.LocalAddr()}, } n, err := cc.SendMsgs(wms, 0) if err != nil { t.Fatal(err) } if n != len(wms) { t.Fatalf("got %d; want %d", n, len(wms)) } b := make([]byte, 32) rmbs := [][][]byte{{b[:len(wmbs[0])]}, {b[len(wmbs[0]):]}} rms := []socket.Message{ {Buffers: rmbs[0]}, {Buffers: rmbs[1]}, } n, err = cc.RecvMsgs(rms, 0) if err != nil { t.Fatal(err) } if n != len(rms) { t.Fatalf("got %d; want %d", n, len(rms)) } nn := 0 for i := 0; i < n; i++ { nn += rms[i].N } if !bytes.Equal(b[:nn], data) { t.Fatalf("got %#v; want %#v", b[:nn], data) } }) } // The behavior of transmission for zero byte paylaod depends // on each platform implementation. Some may transmit only // protocol header and options, other may transmit nothing. // We test only that SendMsg and SendMsgs will not crash with // empty buffers. wm := socket.Message{ Buffers: [][]byte{{}}, Addr: c.LocalAddr(), } cc.SendMsg(&wm, 0) wms := []socket.Message{ {Buffers: [][]byte{{}}, Addr: c.LocalAddr()}, } cc.SendMsgs(wms, 0) } func BenchmarkUDP(b *testing.B) { c, err := nettest.NewLocalPacketListener("udp") if err != nil { b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() cc, err := socket.NewConn(c.(net.Conn)) if err != nil { b.Fatal(err) } data := []byte("HELLO-R-U-THERE") wm := socket.Message{ Buffers: [][]byte{data}, Addr: c.LocalAddr(), } rm := socket.Message{ Buffers: [][]byte{make([]byte, 128)}, OOB: make([]byte, 128), } for M := 1; M <= 1<<9; M = M << 1 { b.Run(fmt.Sprintf("Iter-%d", M), func(b *testing.B) { for i := 0; i < b.N; i++ { for j := 0; j < M; j++ { if err := cc.SendMsg(&wm, 0); err != nil { b.Fatal(err) } if err := cc.RecvMsg(&rm, 0); err != nil { b.Fatal(err) } } } }) switch runtime.GOOS { case "android", "linux": wms := make([]socket.Message, M) for i := range wms { wms[i].Buffers = [][]byte{data} wms[i].Addr = c.LocalAddr() } rms := make([]socket.Message, M) for i := range rms { rms[i].Buffers = [][]byte{make([]byte, 128)} rms[i].OOB = make([]byte, 128) } b.Run(fmt.Sprintf("Batch-%d", M), func(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := cc.SendMsgs(wms, 0); err != nil { b.Fatal(err) } if _, err := cc.RecvMsgs(rms, 0); err != nil { b.Fatal(err) } } }) } } } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/socket.go0000644061062106075000000001704413172163402025244 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package socket provides a portable interface for socket system // calls. package socket // import "golang.org/x/net/internal/socket" import ( "errors" "net" "unsafe" ) // An Option represents a sticky socket option. type Option struct { Level int // level Name int // name; must be equal or greater than 1 Len int // length of value in bytes; must be equal or greater than 1 } // Get reads a value for the option from the kernel. // It returns the number of bytes written into b. func (o *Option) Get(c *Conn, b []byte) (int, error) { if o.Name < 1 || o.Len < 1 { return 0, errors.New("invalid option") } if len(b) < o.Len { return 0, errors.New("short buffer") } return o.get(c, b) } // GetInt returns an integer value for the option. // // The Len field of Option must be either 1 or 4. func (o *Option) GetInt(c *Conn) (int, error) { if o.Len != 1 && o.Len != 4 { return 0, errors.New("invalid option") } var b []byte var bb [4]byte if o.Len == 1 { b = bb[:1] } else { b = bb[:4] } n, err := o.get(c, b) if err != nil { return 0, err } if n != o.Len { return 0, errors.New("invalid option length") } if o.Len == 1 { return int(b[0]), nil } return int(NativeEndian.Uint32(b[:4])), nil } // Set writes the option and value to the kernel. func (o *Option) Set(c *Conn, b []byte) error { if o.Name < 1 || o.Len < 1 { return errors.New("invalid option") } if len(b) < o.Len { return errors.New("short buffer") } return o.set(c, b) } // SetInt writes the option and value to the kernel. // // The Len field of Option must be either 1 or 4. func (o *Option) SetInt(c *Conn, v int) error { if o.Len != 1 && o.Len != 4 { return errors.New("invalid option") } var b []byte if o.Len == 1 { b = []byte{byte(v)} } else { var bb [4]byte NativeEndian.PutUint32(bb[:o.Len], uint32(v)) b = bb[:4] } return o.set(c, b) } func controlHeaderLen() int { return roundup(sizeofCmsghdr) } func controlMessageLen(dataLen int) int { return roundup(sizeofCmsghdr) + dataLen } // ControlMessageSpace returns the whole length of control message. func ControlMessageSpace(dataLen int) int { return roundup(sizeofCmsghdr) + roundup(dataLen) } // A ControlMessage represents the head message in a stream of control // messages. // // A control message comprises of a header, data and a few padding // fields to conform to the interface to the kernel. // // See RFC 3542 for further information. type ControlMessage []byte // Data returns the data field of the control message at the head on // w. func (m ControlMessage) Data(dataLen int) []byte { l := controlHeaderLen() if len(m) < l || len(m) < l+dataLen { return nil } return m[l : l+dataLen] } // Next returns the control message at the next on w. // // Next works only for standard control messages. func (m ControlMessage) Next(dataLen int) ControlMessage { l := ControlMessageSpace(dataLen) if len(m) < l { return nil } return m[l:] } // MarshalHeader marshals the header fields of the control message at // the head on w. func (m ControlMessage) MarshalHeader(lvl, typ, dataLen int) error { if len(m) < controlHeaderLen() { return errors.New("short message") } h := (*cmsghdr)(unsafe.Pointer(&m[0])) h.set(controlMessageLen(dataLen), lvl, typ) return nil } // ParseHeader parses and returns the header fields of the control // message at the head on w. func (m ControlMessage) ParseHeader() (lvl, typ, dataLen int, err error) { l := controlHeaderLen() if len(m) < l { return 0, 0, 0, errors.New("short message") } h := (*cmsghdr)(unsafe.Pointer(&m[0])) return h.lvl(), h.typ(), int(uint64(h.len()) - uint64(l)), nil } // Marshal marshals the control message at the head on w, and returns // the next control message. func (m ControlMessage) Marshal(lvl, typ int, data []byte) (ControlMessage, error) { l := len(data) if len(m) < ControlMessageSpace(l) { return nil, errors.New("short message") } h := (*cmsghdr)(unsafe.Pointer(&m[0])) h.set(controlMessageLen(l), lvl, typ) if l > 0 { copy(m.Data(l), data) } return m.Next(l), nil } // Parse parses w as a single or multiple control messages. // // Parse works for both standard and compatible messages. func (m ControlMessage) Parse() ([]ControlMessage, error) { var ms []ControlMessage for len(m) >= controlHeaderLen() { h := (*cmsghdr)(unsafe.Pointer(&m[0])) l := h.len() if l <= 0 { return nil, errors.New("invalid header length") } if uint64(l) < uint64(controlHeaderLen()) { return nil, errors.New("invalid message length") } if uint64(l) > uint64(len(m)) { return nil, errors.New("short buffer") } // On message reception: // // |<- ControlMessageSpace --------------->| // |<- controlMessageLen ---------->| | // |<- controlHeaderLen ->| | | // +---------------+------+---------+------+ // | Header | PadH | Data | PadD | // +---------------+------+---------+------+ // // On compatible message reception: // // | ... |<- controlMessageLen ----------->| // | ... |<- controlHeaderLen ->| | // +-----+---------------+------+----------+ // | ... | Header | PadH | Data | // +-----+---------------+------+----------+ ms = append(ms, ControlMessage(m[:l])) ll := l - controlHeaderLen() if len(m) >= ControlMessageSpace(ll) { m = m[ControlMessageSpace(ll):] } else { m = m[controlMessageLen(ll):] } } return ms, nil } // NewControlMessage returns a new stream of control messages. func NewControlMessage(dataLen []int) ControlMessage { var l int for i := range dataLen { l += ControlMessageSpace(dataLen[i]) } return make([]byte, l) } // A Message represents an IO message. type Message struct { // When writing, the Buffers field must contain at least one // byte to write. // When reading, the Buffers field will always contain a byte // to read. Buffers [][]byte // OOB contains protocol-specific control or miscellaneous // ancillary data known as out-of-band data. OOB []byte // Addr specifies a destination address when writing. // It can be nil when the underlying protocol of the raw // connection uses connection-oriented communication. // After a successful read, it may contain the source address // on the received packet. Addr net.Addr N int // # of bytes read or written from/to Buffers NN int // # of bytes read or written from/to OOB Flags int // protocol-specific information on the received message } // RecvMsg wraps recvmsg system call. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_PEEK. func (c *Conn) RecvMsg(m *Message, flags int) error { return c.recvMsg(m, flags) } // SendMsg wraps sendmsg system call. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_DONTROUTE. func (c *Conn) SendMsg(m *Message, flags int) error { return c.sendMsg(m, flags) } // RecvMsgs wraps recvmmsg system call. // // It returns the number of processed messages. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_PEEK. // // Only Linux supports this. func (c *Conn) RecvMsgs(ms []Message, flags int) (int, error) { return c.recvMsgs(ms, flags) } // SendMsgs wraps sendmmsg system call. // // It returns the number of processed messages. // // The provided flags is a set of platform-dependent flags, such as // syscall.MSG_DONTROUTE. // // Only Linux supports this. func (c *Conn) SendMsgs(ms []Message, flags int) (int, error) { return c.sendMsgs(ms, flags) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/reflect.go0000644061062106075000000000247713172163402025404 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 package socket import ( "errors" "net" "os" "reflect" "runtime" ) // A Conn represents a raw connection. type Conn struct { c net.Conn } // NewConn returns a new raw connection. func NewConn(c net.Conn) (*Conn, error) { return &Conn{c: c}, nil } func (o *Option) get(c *Conn, b []byte) (int, error) { s, err := socketOf(c.c) if err != nil { return 0, err } n, err := getsockopt(s, o.Level, o.Name, b) return n, os.NewSyscallError("getsockopt", err) } func (o *Option) set(c *Conn, b []byte) error { s, err := socketOf(c.c) if err != nil { return err } return os.NewSyscallError("setsockopt", setsockopt(s, o.Level, o.Name, b)) } func socketOf(c net.Conn) (uintptr, error) { switch c.(type) { case *net.TCPConn, *net.UDPConn, *net.IPConn: v := reflect.ValueOf(c) switch e := v.Elem(); e.Kind() { case reflect.Struct: fd := e.FieldByName("conn").FieldByName("fd") switch e := fd.Elem(); e.Kind() { case reflect.Struct: sysfd := e.FieldByName("sysfd") if runtime.GOOS == "windows" { return uintptr(sysfd.Uint()), nil } return uintptr(sysfd.Int()), nil } } } return 0, errors.New("invalid type") } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/rawconn_stub.go0000644061062106075000000000115013172163402026447 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 package socket import "errors" func (c *Conn) recvMsg(m *Message, flags int) error { return errors.New("not implemented") } func (c *Conn) sendMsg(m *Message, flags int) error { return errors.New("not implemented") } func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) { return 0, errors.New("not implemented") } func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) { return 0, errors.New("not implemented") } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/rawconn_nomsg.go0000644061062106075000000000073713172163402026627 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows package socket import "errors" func (c *Conn) recvMsg(m *Message, flags int) error { return errors.New("not implemented") } func (c *Conn) sendMsg(m *Message, flags int) error { return errors.New("not implemented") } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/rawconn_nommsg.go0000644061062106075000000000067213172163402027002 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 // +build !linux package socket import "errors" func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) { return 0, errors.New("not implemented") } func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) { return 0, errors.New("not implemented") } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/rawconn_msg.go0000644061062106075000000000277213172163402026273 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package socket import ( "os" "syscall" ) func (c *Conn) recvMsg(m *Message, flags int) error { var h msghdr vs := make([]iovec, len(m.Buffers)) var sa []byte if c.network != "tcp" { sa = make([]byte, sizeofSockaddrInet6) } h.pack(vs, m.Buffers, m.OOB, sa) var operr error var n int fn := func(s uintptr) bool { n, operr = recvmsg(s, &h, flags) if operr == syscall.EAGAIN { return false } return true } if err := c.c.Read(fn); err != nil { return err } if operr != nil { return os.NewSyscallError("recvmsg", operr) } if c.network != "tcp" { var err error m.Addr, err = parseInetAddr(sa[:], c.network) if err != nil { return err } } m.N = n m.NN = h.controllen() m.Flags = h.flags() return nil } func (c *Conn) sendMsg(m *Message, flags int) error { var h msghdr vs := make([]iovec, len(m.Buffers)) var sa []byte if m.Addr != nil { sa = marshalInetAddr(m.Addr) } h.pack(vs, m.Buffers, m.OOB, sa) var operr error var n int fn := func(s uintptr) bool { n, operr = sendmsg(s, &h, flags) if operr == syscall.EAGAIN { return false } return true } if err := c.c.Write(fn); err != nil { return err } if operr != nil { return os.NewSyscallError("sendmsg", operr) } m.N = n m.NN = len(m.OOB) return nil } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/rawconn_mmsg.go0000644061062106075000000000302513172163402026440 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 // +build linux package socket import ( "net" "os" "syscall" ) func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) { hs := make(mmsghdrs, len(ms)) var parseFn func([]byte, string) (net.Addr, error) if c.network != "tcp" { parseFn = parseInetAddr } if err := hs.pack(ms, parseFn, nil); err != nil { return 0, err } var operr error var n int fn := func(s uintptr) bool { n, operr = recvmmsg(s, hs, flags) if operr == syscall.EAGAIN { return false } return true } if err := c.c.Read(fn); err != nil { return n, err } if operr != nil { return n, os.NewSyscallError("recvmmsg", operr) } if err := hs[:n].unpack(ms[:n], parseFn, c.network); err != nil { return n, err } return n, nil } func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) { hs := make(mmsghdrs, len(ms)) var marshalFn func(net.Addr) []byte if c.network != "tcp" { marshalFn = marshalInetAddr } if err := hs.pack(ms, nil, marshalFn); err != nil { return 0, err } var operr error var n int fn := func(s uintptr) bool { n, operr = sendmmsg(s, hs, flags) if operr == syscall.EAGAIN { return false } return true } if err := c.c.Write(fn); err != nil { return n, err } if operr != nil { return n, os.NewSyscallError("sendmmsg", operr) } if err := hs[:n].unpack(ms[:n], nil, ""); err != nil { return n, err } return n, nil } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/rawconn.go0000644061062106075000000000245613172163402025424 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package socket import ( "errors" "net" "os" "syscall" ) // A Conn represents a raw connection. type Conn struct { network string c syscall.RawConn } // NewConn returns a new raw connection. func NewConn(c net.Conn) (*Conn, error) { var err error var cc Conn switch c := c.(type) { case *net.TCPConn: cc.network = "tcp" cc.c, err = c.SyscallConn() case *net.UDPConn: cc.network = "udp" cc.c, err = c.SyscallConn() case *net.IPConn: cc.network = "ip" cc.c, err = c.SyscallConn() default: return nil, errors.New("unknown connection type") } if err != nil { return nil, err } return &cc, nil } func (o *Option) get(c *Conn, b []byte) (int, error) { var operr error var n int fn := func(s uintptr) { n, operr = getsockopt(s, o.Level, o.Name, b) } if err := c.c.Control(fn); err != nil { return 0, err } return n, os.NewSyscallError("getsockopt", operr) } func (o *Option) set(c *Conn, b []byte) error { var operr error fn := func(s uintptr) { operr = setsockopt(s, o.Level, o.Name, b) } if err := c.c.Control(fn); err != nil { return err } return os.NewSyscallError("setsockopt", operr) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/msghdr_stub.go0000644061062106075000000000112213172163402026263 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris package socket type msghdr struct{} func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) {} func (h *msghdr) name() []byte { return nil } func (h *msghdr) controllen() int { return 0 } func (h *msghdr) flags() int { return 0 } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/msghdr_solaris_64bit.go0000644061062106075000000000136713172163402030005 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64 // +build solaris package socket import "unsafe" func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) { for i := range vs { vs[i].set(bs[i]) } if len(vs) > 0 { h.Iov = &vs[0] h.Iovlen = int32(len(vs)) } if len(oob) > 0 { h.Accrights = (*int8)(unsafe.Pointer(&oob[0])) h.Accrightslen = int32(len(oob)) } if sa != nil { h.Name = (*byte)(unsafe.Pointer(&sa[0])) h.Namelen = uint32(len(sa)) } } func (h *msghdr) controllen() int { return int(h.Accrightslen) } func (h *msghdr) flags() int { return int(NativeEndian.Uint32(h.Pad_cgo_2[:])) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/msghdr_openbsd.go0000644061062106075000000000044513172163402026747 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket func (h *msghdr) setIov(vs []iovec) { l := len(vs) if l == 0 { return } h.Iov = &vs[0] h.Iovlen = uint32(l) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/msghdr_linux_64bit.go0000644061062106075000000000076713172163402027473 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x // +build linux package socket import "unsafe" func (h *msghdr) setIov(vs []iovec) { l := len(vs) if l == 0 { return } h.Iov = &vs[0] h.Iovlen = uint64(l) } func (h *msghdr) setControl(b []byte) { h.Control = (*byte)(unsafe.Pointer(&b[0])) h.Controllen = uint64(len(b)) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/msghdr_linux_32bit.go0000644061062106075000000000073313172163402027457 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm mips mipsle 386 // +build linux package socket import "unsafe" func (h *msghdr) setIov(vs []iovec) { l := len(vs) if l == 0 { return } h.Iov = &vs[0] h.Iovlen = uint32(l) } func (h *msghdr) setControl(b []byte) { h.Control = (*byte)(unsafe.Pointer(&b[0])) h.Controllen = uint32(len(b)) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/msghdr_linux.go0000644061062106075000000000134413172163402026453 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket import "unsafe" func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) { for i := range vs { vs[i].set(bs[i]) } h.setIov(vs) if len(oob) > 0 { h.setControl(oob) } if sa != nil { h.Name = (*byte)(unsafe.Pointer(&sa[0])) h.Namelen = uint32(len(sa)) } } func (h *msghdr) name() []byte { if h.Name != nil && h.Namelen > 0 { return (*[sizeofSockaddrInet6]byte)(unsafe.Pointer(h.Name))[:h.Namelen] } return nil } func (h *msghdr) controllen() int { return int(h.Controllen) } func (h *msghdr) flags() int { return int(h.Flags) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/msghdr_bsdvar.go0000644061062106075000000000051713172163402026576 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd package socket func (h *msghdr) setIov(vs []iovec) { l := len(vs) if l == 0 { return } h.Iov = &vs[0] h.Iovlen = int32(l) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/msghdr_bsd.go0000644061062106075000000000152413172163402026064 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package socket import "unsafe" func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) { for i := range vs { vs[i].set(bs[i]) } h.setIov(vs) if len(oob) > 0 { h.Control = (*byte)(unsafe.Pointer(&oob[0])) h.Controllen = uint32(len(oob)) } if sa != nil { h.Name = (*byte)(unsafe.Pointer(&sa[0])) h.Namelen = uint32(len(sa)) } } func (h *msghdr) name() []byte { if h.Name != nil && h.Namelen > 0 { return (*[sizeofSockaddrInet6]byte)(unsafe.Pointer(h.Name))[:h.Namelen] } return nil } func (h *msghdr) controllen() int { return int(h.Controllen) } func (h *msghdr) flags() int { return int(h.Flags) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/mmsghdr_unix.go0000644061062106075000000000177313172163402026462 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux netbsd package socket import "net" type mmsghdrs []mmsghdr func (hs mmsghdrs) pack(ms []Message, parseFn func([]byte, string) (net.Addr, error), marshalFn func(net.Addr) []byte) error { for i := range hs { vs := make([]iovec, len(ms[i].Buffers)) var sa []byte if parseFn != nil { sa = make([]byte, sizeofSockaddrInet6) } if marshalFn != nil { sa = marshalFn(ms[i].Addr) } hs[i].Hdr.pack(vs, ms[i].Buffers, ms[i].OOB, sa) } return nil } func (hs mmsghdrs) unpack(ms []Message, parseFn func([]byte, string) (net.Addr, error), hint string) error { for i := range hs { ms[i].N = int(hs[i].Len) ms[i].NN = hs[i].Hdr.controllen() ms[i].Flags = hs[i].Hdr.flags() if parseFn != nil { var err error ms[i].Addr, err = parseFn(hs[i].Hdr.name(), hint) if err != nil { return err } } } return nil } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/mmsghdr_stub.go0000644061062106075000000000102113172163402026436 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !linux,!netbsd package socket import "net" type mmsghdr struct{} type mmsghdrs []mmsghdr func (hs mmsghdrs) pack(ms []Message, parseFn func([]byte, string) (net.Addr, error), marshalFn func(net.Addr) []byte) error { return nil } func (hs mmsghdrs) unpack(ms []Message, parseFn func([]byte, string) (net.Addr, error), hint string) error { return nil } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/iovec_stub.go0000644061062106075000000000045613172163402026115 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris package socket type iovec struct{} func (v *iovec) set(b []byte) {} lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/iovec_solaris_64bit.go0000644061062106075000000000055013172163402027617 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64 // +build solaris package socket import "unsafe" func (v *iovec) set(b []byte) { l := len(b) if l == 0 { return } v.Base = (*int8)(unsafe.Pointer(&b[0])) v.Len = uint64(l) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/iovec_64bit.go0000644061062106075000000000067013172163402026066 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x // +build darwin dragonfly freebsd linux netbsd openbsd package socket import "unsafe" func (v *iovec) set(b []byte) { l := len(b) if l == 0 { return } v.Base = (*byte)(unsafe.Pointer(&b[0])) v.Len = uint64(l) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/iovec_32bit.go0000644061062106075000000000063413172163402026061 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm mips mipsle 386 // +build darwin dragonfly freebsd linux netbsd openbsd package socket import "unsafe" func (v *iovec) set(b []byte) { l := len(b) if l == 0 { return } v.Base = (*byte)(unsafe.Pointer(&b[0])) v.Len = uint32(l) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/error_windows.go0000644061062106075000000000111413172163402026646 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package socket import "syscall" var ( errERROR_IO_PENDING error = syscall.ERROR_IO_PENDING errEINVAL error = syscall.EINVAL ) // errnoErr returns common boxed Errno values, to prevent allocations // at runtime. func errnoErr(errno syscall.Errno) error { switch errno { case 0: return nil case syscall.ERROR_IO_PENDING: return errERROR_IO_PENDING case syscall.EINVAL: return errEINVAL } return errno } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/error_unix.go0000644061062106075000000000124613172163402026145 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package socket import "syscall" var ( errEAGAIN error = syscall.EAGAIN errEINVAL error = syscall.EINVAL errENOENT error = syscall.ENOENT ) // errnoErr returns common boxed Errno values, to prevent allocations // at runtime. func errnoErr(errno syscall.Errno) error { switch errno { case 0: return nil case syscall.EAGAIN: return errEAGAIN case syscall.EINVAL: return errEINVAL case syscall.ENOENT: return errENOENT } return errno } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/defs_solaris.go0000644061062106075000000000157313172163402026431 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package socket /* #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW ) type iovec C.struct_iovec type msghdr C.struct_msghdr type cmsghdr C.struct_cmsghdr type sockaddrInet C.struct_sockaddr_in type sockaddrInet6 C.struct_sockaddr_in6 const ( sizeofIovec = C.sizeof_struct_iovec sizeofMsghdr = C.sizeof_struct_msghdr sizeofCmsghdr = C.sizeof_struct_cmsghdr sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/defs_openbsd.go0000644061062106075000000000157313172163402026407 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package socket /* #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW ) type iovec C.struct_iovec type msghdr C.struct_msghdr type cmsghdr C.struct_cmsghdr type sockaddrInet C.struct_sockaddr_in type sockaddrInet6 C.struct_sockaddr_in6 const ( sizeofIovec = C.sizeof_struct_iovec sizeofMsghdr = C.sizeof_struct_msghdr sizeofCmsghdr = C.sizeof_struct_cmsghdr sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/defs_netbsd.go0000644061062106075000000000170313172163402026227 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package socket /* #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW ) type iovec C.struct_iovec type msghdr C.struct_msghdr type mmsghdr C.struct_mmsghdr type cmsghdr C.struct_cmsghdr type sockaddrInet C.struct_sockaddr_in type sockaddrInet6 C.struct_sockaddr_in6 const ( sizeofIovec = C.sizeof_struct_iovec sizeofMsghdr = C.sizeof_struct_msghdr sizeofMmsghdr = C.sizeof_struct_mmsghdr sizeofCmsghdr = C.sizeof_struct_cmsghdr sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/defs_linux.go0000644061062106075000000000175413172163402026115 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package socket /* #include #include #define _GNU_SOURCE #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW ) type iovec C.struct_iovec type msghdr C.struct_msghdr type mmsghdr C.struct_mmsghdr type cmsghdr C.struct_cmsghdr type sockaddrInet C.struct_sockaddr_in type sockaddrInet6 C.struct_sockaddr_in6 const ( sizeofIovec = C.sizeof_struct_iovec sizeofMsghdr = C.sizeof_struct_msghdr sizeofMmsghdr = C.sizeof_struct_mmsghdr sizeofCmsghdr = C.sizeof_struct_cmsghdr sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/defs_freebsd.go0000644061062106075000000000157313172163402026367 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package socket /* #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW ) type iovec C.struct_iovec type msghdr C.struct_msghdr type cmsghdr C.struct_cmsghdr type sockaddrInet C.struct_sockaddr_in type sockaddrInet6 C.struct_sockaddr_in6 const ( sizeofIovec = C.sizeof_struct_iovec sizeofMsghdr = C.sizeof_struct_msghdr sizeofCmsghdr = C.sizeof_struct_cmsghdr sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/defs_dragonfly.go0000644061062106075000000000157313172163402026742 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package socket /* #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW ) type iovec C.struct_iovec type msghdr C.struct_msghdr type cmsghdr C.struct_cmsghdr type sockaddrInet C.struct_sockaddr_in type sockaddrInet6 C.struct_sockaddr_in6 const ( sizeofIovec = C.sizeof_struct_iovec sizeofMsghdr = C.sizeof_struct_msghdr sizeofCmsghdr = C.sizeof_struct_cmsghdr sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/defs_darwin.go0000644061062106075000000000157313172163402026241 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package socket /* #include #include */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW ) type iovec C.struct_iovec type msghdr C.struct_msghdr type cmsghdr C.struct_cmsghdr type sockaddrInet C.struct_sockaddr_in type sockaddrInet6 C.struct_sockaddr_in6 const ( sizeofIovec = C.sizeof_struct_iovec sizeofMsghdr = C.sizeof_struct_msghdr sizeofCmsghdr = C.sizeof_struct_cmsghdr sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 ) lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/cmsghdr_stub.go0000644061062106075000000000071613172163402026436 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris package socket type cmsghdr struct{} const sizeofCmsghdr = 0 func (h *cmsghdr) len() int { return 0 } func (h *cmsghdr) lvl() int { return 0 } func (h *cmsghdr) typ() int { return 0 } func (h *cmsghdr) set(l, lvl, typ int) {} lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/cmsghdr_solaris_64bit.go0000644061062106075000000000047413172163402030146 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64 // +build solaris package socket func (h *cmsghdr) set(l, lvl, typ int) { h.Len = uint32(l) h.Level = int32(lvl) h.Type = int32(typ) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/cmsghdr_linux_64bit.go0000644061062106075000000000054413172163402027627 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x // +build linux package socket func (h *cmsghdr) set(l, lvl, typ int) { h.Len = uint64(l) h.Level = int32(lvl) h.Type = int32(typ) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/cmsghdr_linux_32bit.go0000644061062106075000000000051013172163402027613 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm mips mipsle 386 // +build linux package socket func (h *cmsghdr) set(l, lvl, typ int) { h.Len = uint32(l) h.Level = int32(lvl) h.Type = int32(typ) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/cmsghdr_bsd.go0000644061062106075000000000051413172163402026225 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package socket func (h *cmsghdr) set(l, lvl, typ int) { h.Len = uint32(l) h.Level = int32(lvl) h.Type = int32(typ) } lxd-2.0.11/dist/src/golang.org/x/net/internal/socket/cmsghdr.go0000644061062106075000000000061213172163402025374 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package socket func (h *cmsghdr) len() int { return int(h.Len) } func (h *cmsghdr) lvl() int { return int(h.Level) } func (h *cmsghdr) typ() int { return int(h.Type) } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/0000755061062106075000000000000013172163402023615 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/stack.go0000644061062106075000000000722013172163402025252 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package nettest provides utilities for network testing. package nettest // import "golang.org/x/net/internal/nettest" import ( "fmt" "io/ioutil" "net" "os" "runtime" ) var ( supportsIPv4 bool supportsIPv6 bool ) func init() { if ln, err := net.Listen("tcp4", "127.0.0.1:0"); err == nil { ln.Close() supportsIPv4 = true } if ln, err := net.Listen("tcp6", "[::1]:0"); err == nil { ln.Close() supportsIPv6 = true } } // SupportsIPv4 reports whether the platform supports IPv4 networking // functionality. func SupportsIPv4() bool { return supportsIPv4 } // SupportsIPv6 reports whether the platform supports IPv6 networking // functionality. func SupportsIPv6() bool { return supportsIPv6 } // SupportsRawIPSocket reports whether the platform supports raw IP // sockets. func SupportsRawIPSocket() (string, bool) { return supportsRawIPSocket() } // SupportsIPv6MulticastDeliveryOnLoopback reports whether the // platform supports IPv6 multicast packet delivery on software // loopback interface. func SupportsIPv6MulticastDeliveryOnLoopback() bool { return supportsIPv6MulticastDeliveryOnLoopback() } // ProtocolNotSupported reports whether err is a protocol not // supported error. func ProtocolNotSupported(err error) bool { return protocolNotSupported(err) } // TestableNetwork reports whether network is testable on the current // platform configuration. func TestableNetwork(network string) bool { // This is based on logic from standard library's // net/platform_test.go. switch network { case "unix", "unixgram": switch runtime.GOOS { case "android", "nacl", "plan9", "windows": return false } if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") { return false } case "unixpacket": switch runtime.GOOS { case "android", "darwin", "freebsd", "nacl", "plan9", "windows": return false } } return true } // NewLocalListener returns a listener which listens to a loopback IP // address or local file system path. // Network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket". func NewLocalListener(network string) (net.Listener, error) { switch network { case "tcp": if supportsIPv4 { if ln, err := net.Listen("tcp4", "127.0.0.1:0"); err == nil { return ln, nil } } if supportsIPv6 { return net.Listen("tcp6", "[::1]:0") } case "tcp4": if supportsIPv4 { return net.Listen("tcp4", "127.0.0.1:0") } case "tcp6": if supportsIPv6 { return net.Listen("tcp6", "[::1]:0") } case "unix", "unixpacket": return net.Listen(network, localPath()) } return nil, fmt.Errorf("%s is not supported", network) } // NewLocalPacketListener returns a packet listener which listens to a // loopback IP address or local file system path. // Network must be "udp", "udp4", "udp6" or "unixgram". func NewLocalPacketListener(network string) (net.PacketConn, error) { switch network { case "udp": if supportsIPv4 { if c, err := net.ListenPacket("udp4", "127.0.0.1:0"); err == nil { return c, nil } } if supportsIPv6 { return net.ListenPacket("udp6", "[::1]:0") } case "udp4": if supportsIPv4 { return net.ListenPacket("udp4", "127.0.0.1:0") } case "udp6": if supportsIPv6 { return net.ListenPacket("udp6", "[::1]:0") } case "unixgram": return net.ListenPacket(network, localPath()) } return nil, fmt.Errorf("%s is not supported", network) } func localPath() string { f, err := ioutil.TempFile("", "nettest") if err != nil { panic(err) } path := f.Name() f.Close() os.Remove(path) return path } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/rlimit.go0000644061062106075000000000053213172163402025444 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package nettest const defaultMaxOpenFiles = 256 // MaxOpenFiles returns the maximum number of open files for the // caller's process. func MaxOpenFiles() int { return maxOpenFiles() } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/interface.go0000644061062106075000000000417613172163402026114 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package nettest import "net" // IsMulticastCapable reports whether ifi is an IP multicast-capable // network interface. Network must be "ip", "ip4" or "ip6". func IsMulticastCapable(network string, ifi *net.Interface) (net.IP, bool) { switch network { case "ip", "ip4", "ip6": default: return nil, false } if ifi == nil || ifi.Flags&net.FlagUp == 0 || ifi.Flags&net.FlagMulticast == 0 { return nil, false } return hasRoutableIP(network, ifi) } // RoutedInterface returns a network interface that can route IP // traffic and satisfies flags. It returns nil when an appropriate // network interface is not found. Network must be "ip", "ip4" or // "ip6". func RoutedInterface(network string, flags net.Flags) *net.Interface { switch network { case "ip", "ip4", "ip6": default: return nil } ift, err := net.Interfaces() if err != nil { return nil } for _, ifi := range ift { if ifi.Flags&flags != flags { continue } if _, ok := hasRoutableIP(network, &ifi); !ok { continue } return &ifi } return nil } func hasRoutableIP(network string, ifi *net.Interface) (net.IP, bool) { ifat, err := ifi.Addrs() if err != nil { return nil, false } for _, ifa := range ifat { switch ifa := ifa.(type) { case *net.IPAddr: if ip := routableIP(network, ifa.IP); ip != nil { return ip, true } case *net.IPNet: if ip := routableIP(network, ifa.IP); ip != nil { return ip, true } } } return nil, false } func routableIP(network string, ip net.IP) net.IP { if !ip.IsLoopback() && !ip.IsLinkLocalUnicast() && !ip.IsGlobalUnicast() { return nil } switch network { case "ip4": if ip := ip.To4(); ip != nil { return ip } case "ip6": if ip.IsLoopback() { // addressing scope of the loopback address depends on each implementation return nil } if ip := ip.To16(); ip != nil && ip.To4() == nil { return ip } default: if ip := ip.To4(); ip != nil { return ip } if ip := ip.To16(); ip != nil { return ip } } return nil } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/helper_windows.go0000644061062106075000000000242013172163402027173 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package nettest import ( "fmt" "runtime" "syscall" ) func maxOpenFiles() int { return 4 * defaultMaxOpenFiles /* actually it's 16581375 */ } func supportsRawIPSocket() (string, bool) { // From http://msdn.microsoft.com/en-us/library/windows/desktop/ms740548.aspx: // Note: To use a socket of type SOCK_RAW requires administrative privileges. // Users running Winsock applications that use raw sockets must be a member of // the Administrators group on the local computer, otherwise raw socket calls // will fail with an error code of WSAEACCES. On Windows Vista and later, access // for raw sockets is enforced at socket creation. In earlier versions of Windows, // access for raw sockets is enforced during other socket operations. s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, 0) if err == syscall.WSAEACCES { return fmt.Sprintf("no access to raw socket allowed on %s", runtime.GOOS), false } if err != nil { return err.Error(), false } syscall.Closesocket(s) return "", true } func supportsIPv6MulticastDeliveryOnLoopback() bool { return true } func causesIPv6Crash() bool { return false } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/helper_unix.go0000644061062106075000000000115713172163402026472 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package nettest import ( "fmt" "os" "runtime" "syscall" ) func maxOpenFiles() int { var rlim syscall.Rlimit if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim); err != nil { return defaultMaxOpenFiles } return int(rlim.Cur) } func supportsRawIPSocket() (string, bool) { if os.Getuid() != 0 { return fmt.Sprintf("must be root on %s", runtime.GOOS), false } return "", true } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/helper_stub.go0000644061062106075000000000107713172163402026465 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build nacl plan9 package nettest import ( "fmt" "runtime" ) func maxOpenFiles() int { return defaultMaxOpenFiles } func supportsRawIPSocket() (string, bool) { return fmt.Sprintf("not supported on %s", runtime.GOOS), false } func supportsIPv6MulticastDeliveryOnLoopback() bool { return false } func causesIPv6Crash() bool { return false } func protocolNotSupported(err error) bool { return false } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/helper_posix.go0000644061062106075000000000121413172163402026643 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package nettest import ( "os" "syscall" ) func protocolNotSupported(err error) bool { switch err := err.(type) { case syscall.Errno: switch err { case syscall.EPROTONOSUPPORT, syscall.ENOPROTOOPT: return true } case *os.SyscallError: switch err := err.Err.(type) { case syscall.Errno: switch err { case syscall.EPROTONOSUPPORT, syscall.ENOPROTOOPT: return true } } } return false } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/helper_nobsd.go0000644061062106075000000000047613172163402026617 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux solaris package nettest func supportsIPv6MulticastDeliveryOnLoopback() bool { return true } func causesIPv6Crash() bool { return false } lxd-2.0.11/dist/src/golang.org/x/net/internal/nettest/helper_bsd.go0000644061062106075000000000221013172163402026246 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package nettest import ( "runtime" "strconv" "strings" "syscall" ) var darwinVersion int func init() { if runtime.GOOS == "darwin" { // See http://support.apple.com/kb/HT1633. s, err := syscall.Sysctl("kern.osrelease") if err != nil { return } ss := strings.Split(s, ".") if len(ss) == 0 { return } darwinVersion, _ = strconv.Atoi(ss[0]) } } func supportsIPv6MulticastDeliveryOnLoopback() bool { switch runtime.GOOS { case "freebsd": // See http://www.freebsd.org/cgi/query-pr.cgi?pr=180065. // Even after the fix, it looks like the latest // kernels don't deliver link-local scoped multicast // packets correctly. return false case "darwin": return !causesIPv6Crash() default: return true } } func causesIPv6Crash() bool { // We see some kernel crash when running IPv6 with IP-level // options on Darwin kernel version 12 or below. // See golang.org/issues/17015. return darwinVersion < 13 } lxd-2.0.11/dist/src/golang.org/x/net/internal/iana/0000755061062106075000000000000013172163402023037 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/internal/iana/gen.go0000644061062106075000000001507213172163402024144 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore //go:generate go run gen.go // This program generates internet protocol constants and tables by // reading IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "io/ioutil" "net/http" "os" "strconv" "strings" ) var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "http://www.iana.org/assignments/dscp-registry/dscp-registry.xml", parseDSCPRegistry, }, { "http://www.iana.org/assignments/ipv4-tos-byte/ipv4-tos-byte.xml", parseTOSTCByte, }, { "http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml", parseProtocolNumbers, }, } func main() { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n") fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n") fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"`+"\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url) os.Exit(1) } if err := r.parse(&bb, resp.Body); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := ioutil.WriteFile("const.go", b, 0644); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func parseDSCPRegistry(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var dr dscpRegistry if err := dec.Decode(&dr); err != nil { return err } drs := dr.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated) fmt.Fprintf(w, "const (\n") for _, dr := range drs { fmt.Fprintf(w, "DiffServ%s = %#x", dr.Name, dr.Value) fmt.Fprintf(w, "// %s\n", dr.OrigName) } fmt.Fprintf(w, ")\n") return nil } type dscpRegistry struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Note string `xml:"note"` RegTitle string `xml:"registry>title"` PoolRecords []struct { Name string `xml:"name"` Space string `xml:"space"` } `xml:"registry>record"` Records []struct { Name string `xml:"name"` Space string `xml:"space"` } `xml:"registry>registry>record"` } type canonDSCPRecord struct { OrigName string Name string Value int } func (drr *dscpRegistry) escape() []canonDSCPRecord { drs := make([]canonDSCPRecord, len(drr.Records)) sr := strings.NewReplacer( "+", "", "-", "", "/", "", ".", "", " ", "", ) for i, dr := range drr.Records { s := strings.TrimSpace(dr.Name) drs[i].OrigName = s drs[i].Name = sr.Replace(s) n, err := strconv.ParseUint(dr.Space, 2, 8) if err != nil { continue } drs[i].Value = int(n) << 2 } return drs } func parseTOSTCByte(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var ttb tosTCByte if err := dec.Decode(&ttb); err != nil { return err } trs := ttb.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", ttb.Title, ttb.Updated) fmt.Fprintf(w, "const (\n") for _, tr := range trs { fmt.Fprintf(w, "%s = %#x", tr.Keyword, tr.Value) fmt.Fprintf(w, "// %s\n", tr.OrigKeyword) } fmt.Fprintf(w, ")\n") return nil } type tosTCByte struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Note string `xml:"note"` RegTitle string `xml:"registry>title"` Records []struct { Binary string `xml:"binary"` Keyword string `xml:"keyword"` } `xml:"registry>record"` } type canonTOSTCByteRecord struct { OrigKeyword string Keyword string Value int } func (ttb *tosTCByte) escape() []canonTOSTCByteRecord { trs := make([]canonTOSTCByteRecord, len(ttb.Records)) sr := strings.NewReplacer( "Capable", "", "(", "", ")", "", "+", "", "-", "", "/", "", ".", "", " ", "", ) for i, tr := range ttb.Records { s := strings.TrimSpace(tr.Keyword) trs[i].OrigKeyword = s ss := strings.Split(s, " ") if len(ss) > 1 { trs[i].Keyword = strings.Join(ss[1:], " ") } else { trs[i].Keyword = ss[0] } trs[i].Keyword = sr.Replace(trs[i].Keyword) n, err := strconv.ParseUint(tr.Binary, 2, 8) if err != nil { continue } trs[i].Value = int(n) } return trs } func parseProtocolNumbers(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var pn protocolNumbers if err := dec.Decode(&pn); err != nil { return err } prs := pn.escape() prs = append([]canonProtocolRecord{{ Name: "IP", Descr: "IPv4 encapsulation, pseudo protocol number", Value: 0, }}, prs...) fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value) s := pr.Descr if s == "" { s = pr.OrigName } fmt.Fprintf(w, "// %s\n", s) } fmt.Fprintf(w, ")\n") return nil } type protocolNumbers struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` RegTitle string `xml:"registry>title"` Note string `xml:"registry>note"` Records []struct { Value string `xml:"value"` Name string `xml:"name"` Descr string `xml:"description"` } `xml:"registry>record"` } type canonProtocolRecord struct { OrigName string Name string Descr string Value int } func (pn *protocolNumbers) escape() []canonProtocolRecord { prs := make([]canonProtocolRecord, len(pn.Records)) sr := strings.NewReplacer( "-in-", "in", "-within-", "within", "-over-", "over", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range pn.Records { if strings.Contains(pr.Name, "Deprecated") || strings.Contains(pr.Name, "deprecated") { continue } prs[i].OrigName = pr.Name s := strings.TrimSpace(pr.Name) switch pr.Name { case "ISIS over IPv4": prs[i].Name = "ISIS" case "manet": prs[i].Name = "MANET" default: prs[i].Name = sr.Replace(s) } ss := strings.Split(pr.Descr, "\n") for i := range ss { ss[i] = strings.TrimSpace(ss[i]) } if len(ss) > 1 { prs[i].Descr = strings.Join(ss, " ") } else { prs[i].Descr = ss[0] } prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs } lxd-2.0.11/dist/src/golang.org/x/net/internal/iana/const.go0000644061062106075000000002136313172163402024521 0ustar stgraberdomain admins// go generate gen.go // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA). package iana // import "golang.org/x/net/internal/iana" // Differentiated Services Field Codepoints (DSCP), Updated: 2017-05-12 const ( DiffServCS0 = 0x0 // CS0 DiffServCS1 = 0x20 // CS1 DiffServCS2 = 0x40 // CS2 DiffServCS3 = 0x60 // CS3 DiffServCS4 = 0x80 // CS4 DiffServCS5 = 0xa0 // CS5 DiffServCS6 = 0xc0 // CS6 DiffServCS7 = 0xe0 // CS7 DiffServAF11 = 0x28 // AF11 DiffServAF12 = 0x30 // AF12 DiffServAF13 = 0x38 // AF13 DiffServAF21 = 0x48 // AF21 DiffServAF22 = 0x50 // AF22 DiffServAF23 = 0x58 // AF23 DiffServAF31 = 0x68 // AF31 DiffServAF32 = 0x70 // AF32 DiffServAF33 = 0x78 // AF33 DiffServAF41 = 0x88 // AF41 DiffServAF42 = 0x90 // AF42 DiffServAF43 = 0x98 // AF43 DiffServEF = 0xb8 // EF DiffServVOICEADMIT = 0xb0 // VOICE-ADMIT ) // IPv4 TOS Byte and IPv6 Traffic Class Octet, Updated: 2001-09-06 const ( NotECNTransport = 0x0 // Not-ECT (Not ECN-Capable Transport) ECNTransport1 = 0x1 // ECT(1) (ECN-Capable Transport(1)) ECNTransport0 = 0x2 // ECT(0) (ECN-Capable Transport(0)) CongestionExperienced = 0x3 // CE (Congestion Experienced) ) // Protocol Numbers, Updated: 2016-06-22 const ( ProtocolIP = 0 // IPv4 encapsulation, pseudo protocol number ProtocolHOPOPT = 0 // IPv6 Hop-by-Hop Option ProtocolICMP = 1 // Internet Control Message ProtocolIGMP = 2 // Internet Group Management ProtocolGGP = 3 // Gateway-to-Gateway ProtocolIPv4 = 4 // IPv4 encapsulation ProtocolST = 5 // Stream ProtocolTCP = 6 // Transmission Control ProtocolCBT = 7 // CBT ProtocolEGP = 8 // Exterior Gateway Protocol ProtocolIGP = 9 // any private interior gateway (used by Cisco for their IGRP) ProtocolBBNRCCMON = 10 // BBN RCC Monitoring ProtocolNVPII = 11 // Network Voice Protocol ProtocolPUP = 12 // PUP ProtocolEMCON = 14 // EMCON ProtocolXNET = 15 // Cross Net Debugger ProtocolCHAOS = 16 // Chaos ProtocolUDP = 17 // User Datagram ProtocolMUX = 18 // Multiplexing ProtocolDCNMEAS = 19 // DCN Measurement Subsystems ProtocolHMP = 20 // Host Monitoring ProtocolPRM = 21 // Packet Radio Measurement ProtocolXNSIDP = 22 // XEROX NS IDP ProtocolTRUNK1 = 23 // Trunk-1 ProtocolTRUNK2 = 24 // Trunk-2 ProtocolLEAF1 = 25 // Leaf-1 ProtocolLEAF2 = 26 // Leaf-2 ProtocolRDP = 27 // Reliable Data Protocol ProtocolIRTP = 28 // Internet Reliable Transaction ProtocolISOTP4 = 29 // ISO Transport Protocol Class 4 ProtocolNETBLT = 30 // Bulk Data Transfer Protocol ProtocolMFENSP = 31 // MFE Network Services Protocol ProtocolMERITINP = 32 // MERIT Internodal Protocol ProtocolDCCP = 33 // Datagram Congestion Control Protocol Protocol3PC = 34 // Third Party Connect Protocol ProtocolIDPR = 35 // Inter-Domain Policy Routing Protocol ProtocolXTP = 36 // XTP ProtocolDDP = 37 // Datagram Delivery Protocol ProtocolIDPRCMTP = 38 // IDPR Control Message Transport Proto ProtocolTPPP = 39 // TP++ Transport Protocol ProtocolIL = 40 // IL Transport Protocol ProtocolIPv6 = 41 // IPv6 encapsulation ProtocolSDRP = 42 // Source Demand Routing Protocol ProtocolIPv6Route = 43 // Routing Header for IPv6 ProtocolIPv6Frag = 44 // Fragment Header for IPv6 ProtocolIDRP = 45 // Inter-Domain Routing Protocol ProtocolRSVP = 46 // Reservation Protocol ProtocolGRE = 47 // Generic Routing Encapsulation ProtocolDSR = 48 // Dynamic Source Routing Protocol ProtocolBNA = 49 // BNA ProtocolESP = 50 // Encap Security Payload ProtocolAH = 51 // Authentication Header ProtocolINLSP = 52 // Integrated Net Layer Security TUBA ProtocolNARP = 54 // NBMA Address Resolution Protocol ProtocolMOBILE = 55 // IP Mobility ProtocolTLSP = 56 // Transport Layer Security Protocol using Kryptonet key management ProtocolSKIP = 57 // SKIP ProtocolIPv6ICMP = 58 // ICMP for IPv6 ProtocolIPv6NoNxt = 59 // No Next Header for IPv6 ProtocolIPv6Opts = 60 // Destination Options for IPv6 ProtocolCFTP = 62 // CFTP ProtocolSATEXPAK = 64 // SATNET and Backroom EXPAK ProtocolKRYPTOLAN = 65 // Kryptolan ProtocolRVD = 66 // MIT Remote Virtual Disk Protocol ProtocolIPPC = 67 // Internet Pluribus Packet Core ProtocolSATMON = 69 // SATNET Monitoring ProtocolVISA = 70 // VISA Protocol ProtocolIPCV = 71 // Internet Packet Core Utility ProtocolCPNX = 72 // Computer Protocol Network Executive ProtocolCPHB = 73 // Computer Protocol Heart Beat ProtocolWSN = 74 // Wang Span Network ProtocolPVP = 75 // Packet Video Protocol ProtocolBRSATMON = 76 // Backroom SATNET Monitoring ProtocolSUNND = 77 // SUN ND PROTOCOL-Temporary ProtocolWBMON = 78 // WIDEBAND Monitoring ProtocolWBEXPAK = 79 // WIDEBAND EXPAK ProtocolISOIP = 80 // ISO Internet Protocol ProtocolVMTP = 81 // VMTP ProtocolSECUREVMTP = 82 // SECURE-VMTP ProtocolVINES = 83 // VINES ProtocolTTP = 84 // Transaction Transport Protocol ProtocolIPTM = 84 // Internet Protocol Traffic Manager ProtocolNSFNETIGP = 85 // NSFNET-IGP ProtocolDGP = 86 // Dissimilar Gateway Protocol ProtocolTCF = 87 // TCF ProtocolEIGRP = 88 // EIGRP ProtocolOSPFIGP = 89 // OSPFIGP ProtocolSpriteRPC = 90 // Sprite RPC Protocol ProtocolLARP = 91 // Locus Address Resolution Protocol ProtocolMTP = 92 // Multicast Transport Protocol ProtocolAX25 = 93 // AX.25 Frames ProtocolIPIP = 94 // IP-within-IP Encapsulation Protocol ProtocolSCCSP = 96 // Semaphore Communications Sec. Pro. ProtocolETHERIP = 97 // Ethernet-within-IP Encapsulation ProtocolENCAP = 98 // Encapsulation Header ProtocolGMTP = 100 // GMTP ProtocolIFMP = 101 // Ipsilon Flow Management Protocol ProtocolPNNI = 102 // PNNI over IP ProtocolPIM = 103 // Protocol Independent Multicast ProtocolARIS = 104 // ARIS ProtocolSCPS = 105 // SCPS ProtocolQNX = 106 // QNX ProtocolAN = 107 // Active Networks ProtocolIPComp = 108 // IP Payload Compression Protocol ProtocolSNP = 109 // Sitara Networks Protocol ProtocolCompaqPeer = 110 // Compaq Peer Protocol ProtocolIPXinIP = 111 // IPX in IP ProtocolVRRP = 112 // Virtual Router Redundancy Protocol ProtocolPGM = 113 // PGM Reliable Transport Protocol ProtocolL2TP = 115 // Layer Two Tunneling Protocol ProtocolDDX = 116 // D-II Data Exchange (DDX) ProtocolIATP = 117 // Interactive Agent Transfer Protocol ProtocolSTP = 118 // Schedule Transfer Protocol ProtocolSRP = 119 // SpectraLink Radio Protocol ProtocolUTI = 120 // UTI ProtocolSMP = 121 // Simple Message Protocol ProtocolPTP = 123 // Performance Transparency Protocol ProtocolISIS = 124 // ISIS over IPv4 ProtocolFIRE = 125 // FIRE ProtocolCRTP = 126 // Combat Radio Transport Protocol ProtocolCRUDP = 127 // Combat Radio User Datagram ProtocolSSCOPMCE = 128 // SSCOPMCE ProtocolIPLT = 129 // IPLT ProtocolSPS = 130 // Secure Packet Shield ProtocolPIPE = 131 // Private IP Encapsulation within IP ProtocolSCTP = 132 // Stream Control Transmission Protocol ProtocolFC = 133 // Fibre Channel ProtocolRSVPE2EIGNORE = 134 // RSVP-E2E-IGNORE ProtocolMobilityHeader = 135 // Mobility Header ProtocolUDPLite = 136 // UDPLite ProtocolMPLSinIP = 137 // MPLS-in-IP ProtocolMANET = 138 // MANET Protocols ProtocolHIP = 139 // Host Identity Protocol ProtocolShim6 = 140 // Shim6 Protocol ProtocolWESP = 141 // Wrapped Encapsulating Security Payload ProtocolROHC = 142 // Robust Header Compression ProtocolReserved = 255 // Reserved ) lxd-2.0.11/dist/src/golang.org/x/net/idna/0000755061062106075000000000000013172163402021226 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/idna/trieval.go0000644061062106075000000000567213172163402023235 0ustar stgraberdomain admins// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. package idna // This file contains definitions for interpreting the trie value of the idna // trie generated by "go run gen*.go". It is shared by both the generator // program and the resultant package. Sharing is achieved by the generator // copying gen_trieval.go to trieval.go and changing what's above this comment. // info holds information from the IDNA mapping table for a single rune. It is // the value returned by a trie lookup. In most cases, all information fits in // a 16-bit value. For mappings, this value may contain an index into a slice // with the mapped string. Such mappings can consist of the actual mapped value // or an XOR pattern to be applied to the bytes of the UTF8 encoding of the // input rune. This technique is used by the cases packages and reduces the // table size significantly. // // The per-rune values have the following format: // // if mapped { // if inlinedXOR { // 15..13 inline XOR marker // 12..11 unused // 10..3 inline XOR mask // } else { // 15..3 index into xor or mapping table // } // } else { // 15..13 unused // 12 modifier (including virama) // 11 virama modifier // 10..8 joining type // 7..3 category type // } // 2 use xor pattern // 1..0 mapped category // // See the definitions below for a more detailed description of the various // bits. type info uint16 const ( catSmallMask = 0x3 catBigMask = 0xF8 indexShift = 3 xorBit = 0x4 // interpret the index as an xor pattern inlineXOR = 0xE000 // These bits are set if the XOR pattern is inlined. joinShift = 8 joinMask = 0x07 viramaModifier = 0x0800 modifier = 0x1000 ) // A category corresponds to a category defined in the IDNA mapping table. type category uint16 const ( unknown category = 0 // not defined currently in unicode. mapped category = 1 disallowedSTD3Mapped category = 2 deviation category = 3 ) const ( valid category = 0x08 validNV8 category = 0x18 validXV8 category = 0x28 disallowed category = 0x40 disallowedSTD3Valid category = 0x80 ignored category = 0xC0 ) // join types and additional rune information const ( joiningL = (iota + 1) joiningD joiningT joiningR //the following types are derived during processing joinZWJ joinZWNJ joinVirama numJoinTypes ) func (c info) isMapped() bool { return c&0x3 != 0 } func (c info) category() category { small := c & catSmallMask if small != 0 { return category(small) } return category(c & catBigMask) } func (c info) joinType() info { if c.isMapped() { return 0 } return (c >> joinShift) & joinMask } func (c info) isModifier() bool { return c&(modifier|catSmallMask) == modifier } func (c info) isViramaModifier() bool { return c&(viramaModifier|catSmallMask) == viramaModifier } lxd-2.0.11/dist/src/golang.org/x/net/idna/trie.go0000644061062106075000000000351413172163402022523 0ustar stgraberdomain admins// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. // Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package idna // appendMapping appends the mapping for the respective rune. isMapped must be // true. A mapping is a categorization of a rune as defined in UTS #46. func (c info) appendMapping(b []byte, s string) []byte { index := int(c >> indexShift) if c&xorBit == 0 { s := mappings[index:] return append(b, s[1:s[0]+1]...) } b = append(b, s...) if c&inlineXOR == inlineXOR { // TODO: support and handle two-byte inline masks b[len(b)-1] ^= byte(index) } else { for p := len(b) - int(xorData[index]); p < len(b); p++ { index++ b[p] ^= xorData[index] } } return b } // Sparse block handling code. type valueRange struct { value uint16 // header: value:stride lo, hi byte // header: lo:n } type sparseBlocks struct { values []valueRange offset []uint16 } var idnaSparse = sparseBlocks{ values: idnaSparseValues[:], offset: idnaSparseOffset[:], } // Don't use newIdnaTrie to avoid unconditional linking in of the table. var trie = &idnaTrie{} // lookup determines the type of block n and looks up the value for b. // For n < t.cutoff, the block is a simple lookup table. Otherwise, the block // is a list of ranges with an accompanying value. Given a matching range r, // the value for b is by r.value + (b - r.lo) * stride. func (t *sparseBlocks) lookup(n uint32, b byte) uint16 { offset := t.offset[n] header := t.values[offset] lo := offset + 1 hi := lo + uint16(header.lo) for lo < hi { m := lo + (hi-lo)/2 r := t.values[m] if r.lo <= b && b <= r.hi { return r.value + uint16(b-r.lo)*header.value } if b < r.lo { hi = m } else { lo = m + 1 } } return 0 } lxd-2.0.11/dist/src/golang.org/x/net/idna/tables.go0000644061062106075000000101506113172163402023033 0ustar stgraberdomain admins// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. package idna // UnicodeVersion is the Unicode version from which the tables in this package are derived. const UnicodeVersion = "9.0.0" var mappings string = "" + // Size: 8176 bytes "\x00\x01 \x03 ̈\x01a\x03 Ì„\x012\x013\x03 Ì\x03 ̧\x011\x01o\x051â„4\x051â„2" + "\x053â„4\x03i̇\x03l·\x03ʼn\x01s\x03dž\x03â±¥\x03ⱦ\x01h\x01j\x01r\x01w\x01y" + "\x03 ̆\x03 ̇\x03 ÌŠ\x03 ̨\x03 ̃\x03 Ì‹\x01l\x01x\x04̈Ì\x03 ι\x01;\x05 ̈Ì" + "\x04Õ¥Ö‚\x04اٴ\x04وٴ\x04Û‡Ù´\x04يٴ\x06क़\x06ख़\x06ग़\x06ज़\x06ड़\x06ढ़\x06फ़" + "\x06य़\x06ড়\x06ঢ়\x06য়\x06ਲ਼\x06ਸ਼\x06ਖ਼\x06ਗ਼\x06ਜ਼\x06ਫ਼\x06ଡ଼\x06ଢ଼" + "\x06à¹à¸²\x06à»àº²\x06ຫນ\x06ຫມ\x06གྷ\x06ཌྷ\x06དྷ\x06བྷ\x06ཛྷ\x06ཀྵ\x06ཱི\x06ཱུ" + "\x06ྲྀ\x09ྲཱྀ\x06ླྀ\x09ླཱྀ\x06ཱྀ\x06ྒྷ\x06ྜྷ\x06ྡྷ\x06ྦྷ\x06ྫྷ\x06à¾à¾µ\x02" + "в\x02д\x02о\x02Ñ\x02Ñ‚\x02ÑŠ\x02Ñ£\x02æ\x01b\x01d\x01e\x02Ç\x01g\x01i\x01k" + "\x01m\x01n\x02È£\x01p\x01t\x01u\x02É\x02É‘\x02É™\x02É›\x02Éœ\x02Å‹\x02É”\x02ɯ" + "\x01v\x02β\x02γ\x02δ\x02φ\x02χ\x02Ï\x02н\x02É’\x01c\x02É•\x02ð\x01f\x02ÉŸ" + "\x02É¡\x02É¥\x02ɨ\x02É©\x02ɪ\x02Ê\x02É­\x02ÊŸ\x02ɱ\x02ɰ\x02ɲ\x02ɳ\x02É´\x02ɵ" + "\x02ɸ\x02Ê‚\x02ʃ\x02Æ«\x02ʉ\x02ÊŠ\x02Ê‹\x02ÊŒ\x01z\x02Ê\x02Ê‘\x02Ê’\x02θ\x02ss" + "\x02ά\x02έ\x02ή\x02ί\x02ÏŒ\x02Ï\x02ÏŽ\x05ἀι\x05á¼Î¹\x05ἂι\x05ἃι\x05ἄι\x05ἅι" + "\x05ἆι\x05ἇι\x05ἠι\x05ἡι\x05ἢι\x05ἣι\x05ἤι\x05ἥι\x05ἦι\x05ἧι\x05ὠι\x05ὡι" + "\x05ὢι\x05ὣι\x05ὤι\x05ὥι\x05ὦι\x05ὧι\x05ὰι\x04αι\x04άι\x05ᾶι\x02ι\x05 ̈͂" + "\x05ὴι\x04ηι\x04ήι\x05ῆι\x05 ̓̀\x05 Ì“Ì\x05 ̓͂\x02Î\x05 ̔̀\x05 Ì”Ì\x05 ̔͂" + "\x02ΰ\x05 ̈̀\x01`\x05ὼι\x04ωι\x04ώι\x05ῶι\x06′′\x09′′′\x06‵‵\x09‵‵‵\x02!" + "!\x02??\x02?!\x02!?\x0c′′′′\x010\x014\x015\x016\x017\x018\x019\x01+\x01=" + "\x01(\x01)\x02rs\x02ħ\x02no\x01q\x02sm\x02tm\x02ω\x02Ã¥\x02×\x02ב\x02×’" + "\x02ד\x02Ï€\x051â„7\x051â„9\x061â„10\x051â„3\x052â„3\x051â„5\x052â„5\x053â„5\x054" + "â„5\x051â„6\x055â„6\x051â„8\x053â„8\x055â„8\x057â„8\x041â„\x02ii\x02iv\x02vi" + "\x04viii\x02ix\x02xi\x050â„3\x06∫∫\x09∫∫∫\x06∮∮\x09∮∮∮\x0210\x0211\x0212" + "\x0213\x0214\x0215\x0216\x0217\x0218\x0219\x0220\x04(10)\x04(11)\x04(12)" + "\x04(13)\x04(14)\x04(15)\x04(16)\x04(17)\x04(18)\x04(19)\x04(20)\x0c∫∫∫∫" + "\x02==\x05â«Ì¸\x02É«\x02ɽ\x02È¿\x02É€\x01.\x04 ã‚™\x04 ゚\x06より\x06コト\x05(á„€)\x05" + "(á„‚)\x05(ᄃ)\x05(á„…)\x05(ᄆ)\x05(ᄇ)\x05(ᄉ)\x05(á„‹)\x05(ᄌ)\x05(ᄎ)\x05(á„)\x05(á„" + ")\x05(á„‘)\x05(á„’)\x05(ê°€)\x05(나)\x05(다)\x05(ë¼)\x05(마)\x05(ë°”)\x05(사)\x05(ì•„)" + "\x05(ìž)\x05(ì°¨)\x05(ì¹´)\x05(타)\x05(파)\x05(하)\x05(주)\x08(오전)\x08(오후)\x05(一)" + "\x05(二)\x05(三)\x05(å››)\x05(五)\x05(å…­)\x05(七)\x05(å…«)\x05(ä¹)\x05(å)\x05(月)" + "\x05(ç«)\x05(æ°´)\x05(木)\x05(金)\x05(土)\x05(æ—¥)\x05(æ ª)\x05(有)\x05(社)\x05(å)" + "\x05(特)\x05(財)\x05(ç¥)\x05(労)\x05(代)\x05(呼)\x05(å­¦)\x05(監)\x05(ä¼)\x05(資)" + "\x05(å”)\x05(祭)\x05(休)\x05(自)\x05(至)\x0221\x0222\x0223\x0224\x0225\x0226" + "\x0227\x0228\x0229\x0230\x0231\x0232\x0233\x0234\x0235\x06참고\x06주ì˜\x0236" + "\x0237\x0238\x0239\x0240\x0241\x0242\x0243\x0244\x0245\x0246\x0247\x0248" + "\x0249\x0250\x041月\x042月\x043月\x044月\x045月\x046月\x047月\x048月\x049月\x0510" + "月\x0511月\x0512月\x02hg\x02ev\x0cアパート\x0cアルファ\x0cアンペア\x09アール\x0cイニング\x09" + "インãƒ\x09ウォン\x0fエスクード\x0cエーカー\x09オンス\x09オーム\x09カイリ\x0cカラット\x0cカロリー\x09ガロ" + "ン\x09ガンマ\x06ギガ\x09ギニー\x0cキュリー\x0cギルダー\x06キロ\x0fキログラム\x12キロメートル\x0fキロワッ" + "ト\x09グラム\x0fグラムトン\x0fクルゼイロ\x0cクローãƒ\x09ケース\x09コルナ\x09コーãƒ\x0cサイクル\x0fサンãƒ" + "ーム\x0cシリング\x09センãƒ\x09セント\x09ダース\x06デシ\x06ドル\x06トン\x06ナノ\x09ノット\x09ãƒã‚¤ãƒ„" + "\x0fパーセント\x09パーツ\x0cãƒãƒ¼ãƒ¬ãƒ«\x0fピアストル\x09ピクル\x06ピコ\x06ビル\x0fファラッド\x0cフィート" + "\x0fブッシェル\x09フラン\x0fヘクタール\x06ペソ\x09ペニヒ\x09ヘルツ\x09ペンス\x09ページ\x09ベータ\x0cãƒã‚¤" + "ント\x09ボルト\x06ホン\x09ãƒãƒ³ãƒ‰\x09ホール\x09ホーン\x0cマイクロ\x09マイル\x09マッãƒ\x09マルク\x0fマ" + "ンション\x0cミクロン\x06ミリ\x0fミリãƒãƒ¼ãƒ«\x06メガ\x0cメガトン\x0cメートル\x09ヤード\x09ヤール\x09ユアン" + "\x0cリットル\x06リラ\x09ルピー\x0cルーブル\x06レム\x0fレントゲン\x09ワット\x040点\x041点\x042点" + "\x043点\x044点\x045点\x046点\x047点\x048点\x049点\x0510点\x0511点\x0512点\x0513点" + "\x0514点\x0515点\x0516点\x0517点\x0518点\x0519点\x0520点\x0521点\x0522点\x0523点" + "\x0524点\x02da\x02au\x02ov\x02pc\x02dm\x02iu\x06å¹³æˆ\x06昭和\x06大正\x06明治\x0cæ ª" + "å¼ä¼šç¤¾\x02pa\x02na\x02ma\x02ka\x02kb\x02mb\x02gb\x04kcal\x02pf\x02nf\x02m" + "g\x02kg\x02hz\x02ml\x02dl\x02kl\x02fm\x02nm\x02mm\x02cm\x02km\x02m2\x02m" + "3\x05m∕s\x06m∕s2\x07rad∕s\x08rad∕s2\x02ps\x02ns\x02ms\x02pv\x02nv\x02mv" + "\x02kv\x02pw\x02nw\x02mw\x02kw\x02bq\x02cc\x02cd\x06c∕kg\x02db\x02gy\x02" + "ha\x02hp\x02in\x02kk\x02kt\x02lm\x02ln\x02lx\x02ph\x02pr\x02sr\x02sv\x02" + "wb\x05v∕m\x05a∕m\x041æ—¥\x042æ—¥\x043æ—¥\x044æ—¥\x045æ—¥\x046æ—¥\x047æ—¥\x048æ—¥\x049æ—¥" + "\x0510æ—¥\x0511æ—¥\x0512æ—¥\x0513æ—¥\x0514æ—¥\x0515æ—¥\x0516æ—¥\x0517æ—¥\x0518æ—¥\x0519æ—¥" + "\x0520æ—¥\x0521æ—¥\x0522æ—¥\x0523æ—¥\x0524æ—¥\x0525æ—¥\x0526æ—¥\x0527æ—¥\x0528æ—¥\x0529æ—¥" + "\x0530æ—¥\x0531æ—¥\x02ÑŒ\x02ɦ\x02ɬ\x02Êž\x02ʇ\x02Å“\x04𤋮\x04𢡊\x04𢡄\x04ð£•\x04𥉉" + "\x04ð¥³\x04𧻓\x02ff\x02fi\x02fl\x02st\x04Õ´Õ¶\x04Õ´Õ¥\x04Õ´Õ«\x04Õ¾Õ¶\x04Õ´Õ­\x04×™Ö´" + "\x04ײַ\x02×¢\x02×”\x02×›\x02ל\x02×\x02ר\x02ת\x04ש×\x04שׂ\x06שּ×\x06שּׂ\x04×" + "Ö·\x04×Ö¸\x04×Ö¼\x04בּ\x04×’Ö¼\x04דּ\x04×”Ö¼\x04וּ\x04×–Ö¼\x04טּ\x04×™Ö¼\x04ךּ\x04" + "×›Ö¼\x04לּ\x04מּ\x04× Ö¼\x04סּ\x04×£Ö¼\x04פּ\x04צּ\x04×§Ö¼\x04רּ\x04שּ\x04תּ" + "\x04וֹ\x04בֿ\x04×›Ö¿\x04פֿ\x04×ל\x02Ù±\x02Ù»\x02Ù¾\x02Ú€\x02Ùº\x02Ù¿\x02Ù¹\x02Ú¤" + "\x02Ú¦\x02Ú„\x02Úƒ\x02Ú†\x02Ú‡\x02Ú\x02ÚŒ\x02ÚŽ\x02Úˆ\x02Ú˜\x02Ú‘\x02Ú©\x02Ú¯\x02Ú³" + "\x02Ú±\x02Úº\x02Ú»\x02Û€\x02Û\x02Ú¾\x02Û’\x02Û“\x02Ú­\x02Û‡\x02Û†\x02Ûˆ\x02Û‹\x02Û…" + "\x02Û‰\x02Û\x02Ù‰\x04ئا\x04ئە\x04ئو\x04ئۇ\x04ئۆ\x04ئۈ\x04ئÛ\x04ئى\x02ÛŒ\x04" + "ئج\x04ئح\x04ئم\x04ئي\x04بج\x04بح\x04بخ\x04بم\x04بى\x04بي\x04تج\x04تح" + "\x04تخ\x04تم\x04تى\x04تي\x04ثج\x04ثم\x04ثى\x04ثي\x04جح\x04جم\x04حج\x04حم" + "\x04خج\x04خح\x04خم\x04سج\x04سح\x04سخ\x04سم\x04صح\x04صم\x04ضج\x04ضح\x04ضخ" + "\x04ضم\x04طح\x04طم\x04ظم\x04عج\x04عم\x04غج\x04غم\x04ÙØ¬\x04ÙØ­\x04ÙØ®\x04ÙÙ…" + "\x04ÙÙ‰\x04ÙÙŠ\x04قح\x04قم\x04قى\x04قي\x04كا\x04كج\x04كح\x04كخ\x04كل\x04كم" + "\x04كى\x04كي\x04لج\x04لح\x04لخ\x04لم\x04لى\x04لي\x04مج\x04مح\x04مخ\x04مم" + "\x04مى\x04مي\x04نج\x04نح\x04نخ\x04نم\x04نى\x04ني\x04هج\x04هم\x04هى\x04هي" + "\x04يج\x04يح\x04يخ\x04يم\x04يى\x04يي\x04ذٰ\x04رٰ\x04ىٰ\x05 ٌّ\x05 ÙÙ‘\x05" + " ÙŽÙ‘\x05 ÙÙ‘\x05 ÙÙ‘\x05 ّٰ\x04ئر\x04ئز\x04ئن\x04بر\x04بز\x04بن\x04تر\x04تز" + "\x04تن\x04ثر\x04ثز\x04ثن\x04ما\x04نر\x04نز\x04نن\x04ير\x04يز\x04ين\x04ئخ" + "\x04ئه\x04به\x04ته\x04صخ\x04له\x04نه\x04هٰ\x04يه\x04ثه\x04سه\x04شم\x04شه" + "\x06Ù€ÙŽÙ‘\x06Ù€ÙÙ‘\x06Ù€ÙÙ‘\x04طى\x04طي\x04عى\x04عي\x04غى\x04غي\x04سى\x04سي" + "\x04شى\x04شي\x04حى\x04حي\x04جى\x04جي\x04خى\x04خي\x04صى\x04صي\x04ضى\x04ضي" + "\x04شج\x04شح\x04شخ\x04شر\x04سر\x04صر\x04ضر\x04اً\x06تجم\x06تحج\x06تحم" + "\x06تخم\x06تمج\x06تمح\x06تمخ\x06جمح\x06حمي\x06حمى\x06سحج\x06سجح\x06سجى" + "\x06سمح\x06سمج\x06سمم\x06صحح\x06صمم\x06شحم\x06شجي\x06شمخ\x06شمم\x06ضحى" + "\x06ضخم\x06طمح\x06طمم\x06طمي\x06عجم\x06عمم\x06عمى\x06غمم\x06غمي\x06غمى" + "\x06ÙØ®Ù…\x06قمح\x06قمم\x06لحم\x06لحي\x06لحى\x06لجج\x06لخم\x06لمح\x06محج" + "\x06محم\x06محي\x06مجح\x06مجم\x06مخج\x06مخم\x06مجخ\x06همج\x06همم\x06نحم" + "\x06نحى\x06نجم\x06نجى\x06نمي\x06نمى\x06يمم\x06بخي\x06تجي\x06تجى\x06تخي" + "\x06تخى\x06تمي\x06تمى\x06جمي\x06جحى\x06جمى\x06سخى\x06صحي\x06شحي\x06ضحي" + "\x06لجي\x06لمي\x06يحي\x06يجي\x06يمي\x06ممي\x06قمي\x06نحي\x06عمي\x06كمي" + "\x06نجح\x06مخي\x06لجم\x06كمم\x06جحي\x06حجي\x06مجي\x06Ùمي\x06بحي\x06سخي" + "\x06نجي\x06صلے\x06قلے\x08الله\x08اكبر\x08محمد\x08صلعم\x08رسول\x08عليه" + "\x08وسلم\x06صلى!صلى الله عليه وسلم\x0fجل جلاله\x08ریال\x01,\x01:\x01!" + "\x01?\x01_\x01{\x01}\x01[\x01]\x01#\x01&\x01*\x01-\x01<\x01>\x01\\\x01$" + "\x01%\x01@\x04ـً\x04Ù€ÙŽ\x04Ù€Ù\x04Ù€Ù\x04ـّ\x04ـْ\x02Ø¡\x02Ø¢\x02Ø£\x02ؤ\x02Ø¥" + "\x02ئ\x02ا\x02ب\x02Ø©\x02ت\x02Ø«\x02ج\x02Ø­\x02Ø®\x02د\x02ذ\x02ر\x02ز\x02س" + "\x02Ø´\x02ص\x02ض\x02Ø·\x02ظ\x02ع\x02غ\x02Ù\x02Ù‚\x02Ùƒ\x02Ù„\x02Ù…\x02Ù†\x02Ù‡" + "\x02Ùˆ\x02ÙŠ\x04لآ\x04لأ\x04لإ\x04لا\x01\x22\x01'\x01/\x01^\x01|\x01~\x02¢" + "\x02£\x02¬\x02¦\x02Â¥\x08ð…—ð…¥\x08ð…˜ð…¥\x0cð…˜ð…¥ð…®\x0cð…˜ð…¥ð…¯\x0cð…˜ð…¥ð…°\x0cð…˜ð…¥ð…±\x0cð…˜ð…¥ð…²\x08ð†¹" + "ð…¥\x08ð†ºð…¥\x0cð†¹ð…¥ð…®\x0cð†ºð…¥ð…®\x0cð†¹ð…¥ð…¯\x0cð†ºð…¥ð…¯\x02ı\x02È·\x02α\x02ε\x02ζ\x02η\x02" + "κ\x02λ\x02μ\x02ν\x02ξ\x02ο\x02σ\x02Ï„\x02Ï…\x02ψ\x03∇\x03∂\x02Ï\x02Ù®\x02Ú¡" + "\x02Ù¯\x020,\x021,\x022,\x023,\x024,\x025,\x026,\x027,\x028,\x029,\x03(a)" + "\x03(b)\x03(c)\x03(d)\x03(e)\x03(f)\x03(g)\x03(h)\x03(i)\x03(j)\x03(k)" + "\x03(l)\x03(m)\x03(n)\x03(o)\x03(p)\x03(q)\x03(r)\x03(s)\x03(t)\x03(u)" + "\x03(v)\x03(w)\x03(x)\x03(y)\x03(z)\x07〔s〕\x02wz\x02hv\x02sd\x03ppv\x02w" + "c\x02mc\x02md\x02dj\x06ã»ã‹\x06ココ\x03サ\x03手\x03å­—\x03åŒ\x03デ\x03二\x03多\x03è§£" + "\x03天\x03交\x03映\x03ç„¡\x03æ–™\x03å‰\x03後\x03å†\x03æ–°\x03åˆ\x03終\x03生\x03販\x03声" + "\x03å¹\x03æ¼”\x03投\x03æ•\x03一\x03三\x03éŠ\x03å·¦\x03中\x03å³\x03指\x03èµ°\x03打\x03ç¦" + "\x03空\x03åˆ\x03満\x03有\x03月\x03申\x03割\x03å–¶\x03é…\x09〔本〕\x09〔三〕\x09〔二〕\x09〔安" + "〕\x09〔点〕\x09〔打〕\x09〔盗〕\x09〔å‹ã€•\x09〔敗〕\x03å¾—\x03å¯\x03丽\x03丸\x03ä¹\x03ä½ \x03" + "ä¾®\x03ä¾»\x03倂\x03åº\x03å‚™\x03僧\x03åƒ\x03ã’ž\x03å…\x03å…”\x03å…¤\x03å…·\x03ã’¹\x03å…§\x03" + "冗\x03冤\x03仌\x03冬\x03况\x03凵\x03刃\x03㓟\x03刻\x03剆\x03剷\x03㔕\x03勇\x03勉\x03" + "勤\x03勺\x03包\x03匆\x03北\x03å‰\x03å‘\x03åš\x03å³\x03å½\x03å¿\x03ç°\x03åŠ\x03åŸ\x03" + "å«\x03å±\x03å†\x03å’ž\x03å¸\x03呈\x03周\x03å’¢\x03å“¶\x03å”\x03å•“\x03å•£\x03å–„\x03å–™\x03" + "å–«\x03å–³\x03å—‚\x03圖\x03嘆\x03圗\x03噑\x03å™´\x03切\x03壮\x03城\x03埴\x03å \x03åž‹\x03" + "å ²\x03å ±\x03墬\x03売\x03壷\x03夆\x03夢\x03奢\x03姬\x03娛\x03娧\x03姘\x03婦\x03ã›®\x03" + "嬈\x03嬾\x03寃\x03寘\x03寧\x03寳\x03寿\x03å°†\x03å°¢\x03ãž\x03å± \x03å±®\x03å³€\x03å²\x03" + "嵃\x03åµ®\x03嵫\x03åµ¼\x03å·¡\x03å·¢\x03ã ¯\x03å·½\x03帨\x03帽\x03幩\x03ã¡¢\x03㡼\x03庰\x03" + "庳\x03庶\x03廊\x03廾\x03èˆ\x03å¼¢\x03㣇\x03å½¢\x03彫\x03㣣\x03徚\x03å¿\x03å¿—\x03忹\x03" + "æ‚\x03㤺\x03㤜\x03æ‚”\x03惇\x03æ…ˆ\x03æ…Œ\x03æ…Ž\x03æ…º\x03憎\x03憲\x03憤\x03憯\x03懞\x03" + "懲\x03懶\x03æˆ\x03戛\x03æ‰\x03抱\x03æ‹”\x03æ\x03挽\x03拼\x03æ¨\x03掃\x03æ¤\x03æ¢\x03" + "æ…\x03掩\x03㨮\x03æ‘©\x03摾\x03æ’\x03æ‘·\x03㩬\x03æ•\x03敬\x03æ—£\x03書\x03晉\x03㬙\x03" + "æš‘\x03㬈\x03㫤\x03冒\x03冕\x03最\x03æšœ\x03è‚­\x03ä™\x03朗\x03望\x03朡\x03æž\x03æ“\x03" + "ã­‰\x03柺\x03æž…\x03æ¡’\x03梅\x03梎\x03æ Ÿ\x03椔\x03ã®\x03楂\x03榣\x03槪\x03檨\x03æ«›\x03" + "ã°˜\x03次\x03æ­”\x03㱎\x03æ­²\x03殟\x03殺\x03æ®»\x03汎\x03沿\x03æ³\x03æ±§\x03æ´–\x03æ´¾\x03" + "æµ·\x03æµ\x03浩\x03浸\x03æ¶…\x03æ´´\x03港\x03æ¹®\x03ã´³\x03滋\x03滇\x03æ·¹\x03æ½®\x03濆\x03" + "瀹\x03瀞\x03瀛\x03ã¶–\x03çŠ\x03ç½\x03ç·\x03ç‚­\x03ç……\x03熜\x03爨\x03爵\x03ç‰\x03犀\x03" + "犕\x03çº\x03王\x03㺬\x03玥\x03㺸\x03瑇\x03瑜\x03瑱\x03ç’…\x03瓊\x03ã¼›\x03甤\x03甾\x03" + "ç•°\x03ç˜\x03㿼\x03䀈\x03ç›´\x03眞\x03真\x03çŠ\x03䀹\x03çž‹\x03ä†\x03ä‚–\x03硎\x03碌\x03" + "磌\x03䃣\x03祖\x03ç¦\x03ç§«\x03䄯\x03ç©€\x03穊\x03ç©\x03䈂\x03篆\x03築\x03䈧\x03ç³’\x03" + "䊠\x03糨\x03ç³£\x03ç´€\x03çµ£\x03äŒ\x03ç·‡\x03縂\x03ç¹…\x03䌴\x03ä™\x03罺\x03羕\x03翺\x03" + "者\x03è \x03è°\x03ä•\x03育\x03脃\x03ä‹\x03脾\x03媵\x03舄\x03辞\x03ä‘«\x03芑\x03芋\x03" + "èŠ\x03劳\x03花\x03芳\x03芽\x03苦\x03è‹¥\x03èŒ\x03è£\x03莭\x03茣\x03莽\x03è§\x03è‘—\x03" + "è“\x03èŠ\x03èŒ\x03èœ\x03䔫\x03蓱\x03蓳\x03è”–\x03蕤\x03ä•\x03ä•¡\x03ä•«\x03è™\x03虜\x03" + "è™§\x03虩\x03èš©\x03蚈\x03蜎\x03蛢\x03è¹\x03蜨\x03è«\x03螆\x03蟡\x03è \x03ä—¹\x03è¡ \x03" + "è¡£\x03裗\x03裞\x03䘵\x03裺\x03ã’»\x03äš¾\x03䛇\x03誠\x03è«­\x03變\x03豕\x03貫\x03è³\x03" + "è´›\x03èµ·\x03è·‹\x03è¶¼\x03è·°\x03è»”\x03輸\x03é‚”\x03郱\x03é„‘\x03é„›\x03鈸\x03é‹—\x03鋘\x03" + "鉼\x03é¹\x03é•\x03é–‹\x03䦕\x03é–·\x03䧦\x03雃\x03å¶²\x03霣\x03ä©®\x03ä©¶\x03韠\x03䪲\x03" + "é ‹\x03é ©\x03飢\x03䬳\x03餩\x03馧\x03é§‚\x03é§¾\x03䯎\x03鬒\x03é±€\x03é³½\x03䳎\x03ä³­\x03" + "éµ§\x03䳸\x03麻\x03äµ–\x03黹\x03黾\x03é¼…\x03é¼\x03é¼–\x03é¼»" var xorData string = "" + // Size: 4855 bytes "\x02\x0c\x09\x02\xb0\xec\x02\xad\xd8\x02\xad\xd9\x02\x06\x07\x02\x0f\x12" + "\x02\x0f\x1f\x02\x0f\x1d\x02\x01\x13\x02\x0f\x16\x02\x0f\x0b\x02\x0f3" + "\x02\x0f7\x02\x0f?\x02\x0f/\x02\x0f*\x02\x0c&\x02\x0c*\x02\x0c;\x02\x0c9" + "\x02\x0c%\x02\xab\xed\x02\xab\xe2\x02\xab\xe3\x02\xa9\xe0\x02\xa9\xe1" + "\x02\xa9\xe6\x02\xa3\xcb\x02\xa3\xc8\x02\xa3\xc9\x02\x01#\x02\x01\x08" + "\x02\x0e>\x02\x0e'\x02\x0f\x03\x02\x03\x0d\x02\x03\x09\x02\x03\x17\x02" + "\x03\x0e\x02\x02\x03\x02\x011\x02\x01\x00\x02\x01\x10\x02\x03<\x02\x07" + "\x0d\x02\x02\x0c\x02\x0c0\x02\x01\x03\x02\x01\x01\x02\x01 \x02\x01\x22" + "\x02\x01)\x02\x01\x0a\x02\x01\x0c\x02\x02\x06\x02\x02\x02\x02\x03\x10" + "\x03\x037 \x03\x0b+\x03\x02\x01\x04\x02\x01\x02\x02\x019\x02\x03\x1c\x02" + "\x02$\x03\x80p$\x02\x03:\x02\x03\x0a\x03\xc1r.\x03\xc1r,\x03\xc1r\x02" + "\x02\x02:\x02\x02>\x02\x02,\x02\x02\x10\x02\x02\x00\x03\xc1s<\x03\xc1s*" + "\x03\xc2L$\x03\xc2L;\x02\x09)\x02\x0a\x19\x03\x83\xab\xe3\x03\x83\xab" + "\xf2\x03 4\xe0\x03\x81\xab\xea\x03\x81\xab\xf3\x03 4\xef\x03\x96\xe1\xcd" + "\x03\x84\xe5\xc3\x02\x0d\x11\x03\x8b\xec\xcb\x03\x94\xec\xcf\x03\x9a\xec" + "\xc2\x03\x8b\xec\xdb\x03\x94\xec\xdf\x03\x9a\xec\xd2\x03\x01\x0c!\x03" + "\x01\x0c#\x03Ê \x9d\x03Ê£\x9c\x03Ê¢\x9f\x03Ê¥\x9e\x03ʤ\x91\x03ʧ\x90\x03ʦ\x93" + "\x03Ê©\x92\x03ʨ\x95\x03\xca\xf3\xb5\x03\xca\xf0\xb4\x03\xca\xf1\xb7\x03" + "\xca\xf6\xb6\x03\xca\xf7\x89\x03\xca\xf4\x88\x03\xca\xf5\x8b\x03\xca\xfa" + "\x8a\x03\xca\xfb\x8d\x03\xca\xf8\x8c\x03\xca\xf9\x8f\x03\xca\xfe\x8e\x03" + "\xca\xff\x81\x03\xca\xfc\x80\x03\xca\xfd\x83\x03\xca\xe2\x82\x03\xca\xe3" + "\x85\x03\xca\xe0\x84\x03\xca\xe1\x87\x03\xca\xe6\x86\x03\xca\xe7\x99\x03" + "\xca\xe4\x98\x03\xca\xe5\x9b\x03\xca\xea\x9a\x03\xca\xeb\x9d\x03\xca\xe8" + "\x9c\x03Ø“\x89\x03ß”\x8b\x02\x010\x03\x03\x04\x1e\x03\x04\x15\x12\x03\x0b" + "\x05,\x03\x06\x04\x00\x03\x06\x04)\x03\x06\x044\x03\x06\x04<\x03\x06\x05" + "\x1d\x03\x06\x06\x00\x03\x06\x06\x0a\x03\x06\x06'\x03\x06\x062\x03\x0786" + "\x03\x079/\x03\x079 \x03\x07:\x0e\x03\x07:\x1b\x03\x07:%\x03\x07;/\x03" + "\x07;%\x03\x074\x11\x03\x076\x09\x03\x077*\x03\x070\x01\x03\x070\x0f\x03" + "\x070.\x03\x071\x16\x03\x071\x04\x03\x0710\x03\x072\x18\x03\x072-\x03" + "\x073\x14\x03\x073>\x03\x07'\x09\x03\x07 \x00\x03\x07\x1f\x0b\x03\x07" + "\x18#\x03\x07\x18(\x03\x07\x186\x03\x07\x18\x03\x03\x07\x19\x16\x03\x07" + "\x116\x03\x07\x12'\x03\x07\x13\x10\x03\x07\x0c&\x03\x07\x0c\x08\x03\x07" + "\x0c\x13\x03\x07\x0d\x02\x03\x07\x0d\x1c\x03\x07\x0b5\x03\x07\x0b\x0a" + "\x03\x07\x0b\x01\x03\x07\x0b\x0f\x03\x07\x05\x00\x03\x07\x05\x09\x03\x07" + "\x05\x0b\x03\x07\x07\x01\x03\x07\x07\x08\x03\x07\x00<\x03\x07\x00+\x03" + "\x07\x01)\x03\x07\x01\x1b\x03\x07\x01\x08\x03\x07\x03?\x03\x0445\x03\x04" + "4\x08\x03\x0454\x03\x04)/\x03\x04)5\x03\x04+\x05\x03\x04+\x14\x03\x04+ " + "\x03\x04+<\x03\x04*&\x03\x04*\x22\x03\x04&8\x03\x04!\x01\x03\x04!\x22" + "\x03\x04\x11+\x03\x04\x10.\x03\x04\x104\x03\x04\x13=\x03\x04\x12\x04\x03" + "\x04\x12\x0a\x03\x04\x0d\x1d\x03\x04\x0d\x07\x03\x04\x0d \x03\x05<>\x03" + "\x055<\x03\x055!\x03\x055#\x03\x055&\x03\x054\x1d\x03\x054\x02\x03\x054" + "\x07\x03\x0571\x03\x053\x1a\x03\x053\x16\x03\x05.<\x03\x05.\x07\x03\x05)" + ":\x03\x05)<\x03\x05)\x0c\x03\x05)\x15\x03\x05+-\x03\x05+5\x03\x05$\x1e" + "\x03\x05$\x14\x03\x05'\x04\x03\x05'\x14\x03\x05&\x02\x03\x05\x226\x03" + "\x05\x22\x0c\x03\x05\x22\x1c\x03\x05\x19\x0a\x03\x05\x1b\x09\x03\x05\x1b" + "\x0c\x03\x05\x14\x07\x03\x05\x16?\x03\x05\x16\x0c\x03\x05\x0c\x05\x03" + "\x05\x0e\x0f\x03\x05\x01\x0e\x03\x05\x00(\x03\x05\x030\x03\x05\x03\x06" + "\x03\x0a==\x03\x0a=1\x03\x0a=,\x03\x0a=\x0c\x03\x0a??\x03\x0a<\x08\x03" + "\x0a9!\x03\x0a9)\x03\x0a97\x03\x0a99\x03\x0a6\x0a\x03\x0a6\x1c\x03\x0a6" + "\x17\x03\x0a7'\x03\x0a78\x03\x0a73\x03\x0a'\x01\x03\x0a'&\x03\x0a\x1f" + "\x0e\x03\x0a\x1f\x03\x03\x0a\x1f3\x03\x0a\x1b/\x03\x0a\x18\x19\x03\x0a" + "\x19\x01\x03\x0a\x16\x14\x03\x0a\x0e\x22\x03\x0a\x0f\x10\x03\x0a\x0f\x02" + "\x03\x0a\x0f \x03\x0a\x0c\x04\x03\x0a\x0b>\x03\x0a\x0b+\x03\x0a\x08/\x03" + "\x0a\x046\x03\x0a\x05\x14\x03\x0a\x00\x04\x03\x0a\x00\x10\x03\x0a\x00" + "\x14\x03\x0b<3\x03\x0b;*\x03\x0b9\x22\x03\x0b9)\x03\x0b97\x03\x0b+\x10" + "\x03\x0b((\x03\x0b&5\x03\x0b$\x1c\x03\x0b$\x12\x03\x0b%\x04\x03\x0b#<" + "\x03\x0b#0\x03\x0b#\x0d\x03\x0b#\x19\x03\x0b!:\x03\x0b!\x1f\x03\x0b!\x00" + "\x03\x0b\x1e5\x03\x0b\x1c\x1d\x03\x0b\x1d-\x03\x0b\x1d(\x03\x0b\x18.\x03" + "\x0b\x18 \x03\x0b\x18\x16\x03\x0b\x14\x13\x03\x0b\x15$\x03\x0b\x15\x22" + "\x03\x0b\x12\x1b\x03\x0b\x12\x10\x03\x0b\x132\x03\x0b\x13=\x03\x0b\x12" + "\x18\x03\x0b\x0c&\x03\x0b\x061\x03\x0b\x06:\x03\x0b\x05#\x03\x0b\x05<" + "\x03\x0b\x04\x0b\x03\x0b\x04\x04\x03\x0b\x04\x1b\x03\x0b\x042\x03\x0b" + "\x041\x03\x0b\x03\x03\x03\x0b\x03\x1d\x03\x0b\x03/\x03\x0b\x03+\x03\x0b" + "\x02\x1b\x03\x0b\x02\x00\x03\x0b\x01\x1e\x03\x0b\x01\x08\x03\x0b\x015" + "\x03\x06\x0d9\x03\x06\x0d=\x03\x06\x0d?\x03\x02\x001\x03\x02\x003\x03" + "\x02\x02\x19\x03\x02\x006\x03\x02\x02\x1b\x03\x02\x004\x03\x02\x00<\x03" + "\x02\x02\x0a\x03\x02\x02\x0e\x03\x02\x01\x1a\x03\x02\x01\x07\x03\x02\x01" + "\x05\x03\x02\x01\x0b\x03\x02\x01%\x03\x02\x01\x0c\x03\x02\x01\x04\x03" + "\x02\x01\x1c\x03\x02\x00.\x03\x02\x002\x03\x02\x00>\x03\x02\x00\x12\x03" + "\x02\x00\x16\x03\x02\x011\x03\x02\x013\x03\x02\x02 \x03\x02\x02%\x03\x02" + "\x02$\x03\x02\x028\x03\x02\x02;\x03\x02\x024\x03\x02\x012\x03\x02\x022" + "\x03\x02\x02/\x03\x02\x01,\x03\x02\x01\x13\x03\x02\x01\x16\x03\x02\x01" + "\x11\x03\x02\x01\x1e\x03\x02\x01\x15\x03\x02\x01\x17\x03\x02\x01\x0f\x03" + "\x02\x01\x08\x03\x02\x00?\x03\x02\x03\x07\x03\x02\x03\x0d\x03\x02\x03" + "\x13\x03\x02\x03\x1d\x03\x02\x03\x1f\x03\x02\x00\x03\x03\x02\x00\x0d\x03" + "\x02\x00\x01\x03\x02\x00\x1b\x03\x02\x00\x19\x03\x02\x00\x18\x03\x02\x00" + "\x13\x03\x02\x00/\x03\x07>\x12\x03\x07<\x1f\x03\x07>\x1d\x03\x06\x1d\x0e" + "\x03\x07>\x1c\x03\x07>:\x03\x07>\x13\x03\x04\x12+\x03\x07?\x03\x03\x07>" + "\x02\x03\x06\x224\x03\x06\x1a.\x03\x07<%\x03\x06\x1c\x0b\x03\x0609\x03" + "\x05\x1f\x01\x03\x04'\x08\x03\x93\xfd\xf5\x03\x02\x0d \x03\x02\x0d#\x03" + "\x02\x0d!\x03\x02\x0d&\x03\x02\x0d\x22\x03\x02\x0d/\x03\x02\x0d,\x03\x02" + "\x0d$\x03\x02\x0d'\x03\x02\x0d%\x03\x02\x0d;\x03\x02\x0d=\x03\x02\x0d?" + "\x03\x099.\x03\x08\x0b7\x03\x08\x02\x14\x03\x08\x14\x0d\x03\x08.:\x03" + "\x089'\x03\x0f\x0b\x18\x03\x0f\x1c1\x03\x0f\x17&\x03\x0f9\x1f\x03\x0f0" + "\x0c\x03\x0e\x0a9\x03\x0e\x056\x03\x0e\x1c#\x03\x0f\x13\x0e\x03\x072\x00" + "\x03\x070\x0d\x03\x072\x0b\x03\x06\x11\x18\x03\x070\x10\x03\x06\x0f(\x03" + "\x072\x05\x03\x06\x0f,\x03\x073\x15\x03\x06\x07\x08\x03\x05\x16\x02\x03" + "\x04\x0b \x03\x05:8\x03\x05\x16%\x03\x0a\x0d\x1f\x03\x06\x16\x10\x03\x05" + "\x1d5\x03\x05*;\x03\x05\x16\x1b\x03\x04.-\x03\x06\x1a\x19\x03\x04\x03," + "\x03\x0b87\x03\x04/\x0a\x03\x06\x00,\x03\x04-\x01\x03\x04\x1e-\x03\x06/(" + "\x03\x0a\x0b5\x03\x06\x0e7\x03\x06\x07.\x03\x0597\x03\x0a*%\x03\x0760" + "\x03\x06\x0c;\x03\x05'\x00\x03\x072.\x03\x072\x08\x03\x06=\x01\x03\x06" + "\x05\x1b\x03\x06\x06\x12\x03\x06$=\x03\x06'\x0d\x03\x04\x11\x0f\x03\x076" + ",\x03\x06\x07;\x03\x06.,\x03\x86\xf9\xea\x03\x8f\xff\xeb\x02\x092\x02" + "\x095\x02\x094\x02\x09;\x02\x09>\x02\x098\x02\x09*\x02\x09/\x02\x09,\x02" + "\x09%\x02\x09&\x02\x09#\x02\x09 \x02\x08!\x02\x08%\x02\x08$\x02\x08+\x02" + "\x08.\x02\x08*\x02\x08&\x02\x088\x02\x08>\x02\x084\x02\x086\x02\x080\x02" + "\x08\x10\x02\x08\x17\x02\x08\x12\x02\x08\x1d\x02\x08\x1f\x02\x08\x13\x02" + "\x08\x15\x02\x08\x14\x02\x08\x0c\x03\x8b\xfd\xd0\x03\x81\xec\xc6\x03\x87" + "\xe0\x8a\x03-2\xe3\x03\x80\xef\xe4\x03-2\xea\x03\x88\xe6\xeb\x03\x8e\xe6" + "\xe8\x03\x84\xe6\xe9\x03\x97\xe6\xee\x03-2\xf9\x03-2\xf6\x03\x8e\xe3\xad" + "\x03\x80\xe3\x92\x03\x88\xe3\x90\x03\x8e\xe3\x90\x03\x80\xe3\x97\x03\x88" + "\xe3\x95\x03\x88\xfe\xcb\x03\x8e\xfe\xca\x03\x84\xfe\xcd\x03\x91\xef\xc9" + "\x03-2\xc1\x03-2\xc0\x03-2\xcb\x03\x88@\x09\x03\x8e@\x08\x03\x8f\xe0\xf5" + "\x03\x8e\xe6\xf9\x03\x8e\xe0\xfa\x03\x93\xff\xf4\x03\x84\xee\xd3\x03\x0b" + "(\x04\x023 \x021;\x02\x01*\x03\x0b#\x10\x03\x0b 0\x03\x0b!\x10\x03\x0b!0" + "\x03\x07\x15\x08\x03\x09?5\x03\x07\x1f\x08\x03\x07\x17\x0b\x03\x09\x1f" + "\x15\x03\x0b\x1c7\x03\x0a+#\x03\x06\x1a\x1b\x03\x06\x1a\x14\x03\x0a\x01" + "\x18\x03\x06#\x1b\x03\x0a2\x0c\x03\x0a\x01\x04\x03\x09#;\x03\x08='\x03" + "\x08\x1a\x0a\x03\x07\x03\x0a\x111\x03\x09\x1b\x09\x03\x073.\x03\x07\x01\x00" + "\x03\x09/,\x03\x07#>\x03\x07\x048\x03\x0a\x1f\x22\x03\x098>\x03\x09\x11" + "\x00\x03\x08/\x17\x03\x06'\x22\x03\x0b\x1a+\x03\x0a\x22\x19\x03\x0a/1" + "\x03\x0974\x03\x09\x0f\x22\x03\x08,\x22\x03\x08?\x14\x03\x07$5\x03\x07<3" + "\x03\x07=*\x03\x07\x13\x18\x03\x068\x0a\x03\x06\x09\x16\x03\x06\x13\x00" + "\x03\x08\x067\x03\x08\x01\x03\x03\x08\x12\x1d\x03\x07+7\x03\x06(;\x03" + "\x06\x1c?\x03\x07\x0e\x17\x03\x0a\x06\x1d\x03\x0a\x19\x07\x03\x08\x14$" + "\x03\x07$;\x03\x08,$\x03\x08\x06\x0d\x03\x07\x16\x0a\x03\x06>>\x03\x0a" + "\x06\x12\x03\x0a\x14)\x03\x09\x0d\x1f\x03\x09\x12\x17\x03\x09\x19\x01" + "\x03\x08\x11 \x03\x08\x1d'\x03\x06<\x1a\x03\x0a.\x00\x03\x07'\x18\x03" + "\x0a\x22\x08\x03\x08\x0d\x0a\x03\x08\x13)\x03\x07*)\x03\x06<,\x03\x07" + "\x0b\x1a\x03\x09.\x14\x03\x09\x0d\x1e\x03\x07\x0e#\x03\x0b\x1d'\x03\x0a" + "\x0a8\x03\x09%2\x03\x08+&\x03\x080\x12\x03\x0a)4\x03\x08\x06\x1f\x03\x0b" + "\x1b\x1a\x03\x0a\x1b\x0f\x03\x0b\x1d*\x03\x09\x16$\x03\x090\x11\x03\x08" + "\x11\x08\x03\x0a*(\x03\x0a\x042\x03\x089,\x03\x074'\x03\x07\x0f\x05\x03" + "\x09\x0b\x0a\x03\x07\x1b\x01\x03\x09\x17:\x03\x09.\x0d\x03\x07.\x11\x03" + "\x09+\x15\x03\x080\x13\x03\x0b\x1f\x19\x03\x0a \x11\x03\x0a\x220\x03\x09" + "\x07;\x03\x08\x16\x1c\x03\x07,\x13\x03\x07\x0e/\x03\x06\x221\x03\x0a." + "\x0a\x03\x0a7\x02\x03\x0a\x032\x03\x0a\x1d.\x03\x091\x06\x03\x09\x19:" + "\x03\x08\x02/\x03\x060+\x03\x06\x0f-\x03\x06\x1c\x1f\x03\x06\x1d\x07\x03" + "\x0a,\x11\x03\x09=\x0d\x03\x09\x0b;\x03\x07\x1b/\x03\x0a\x1f:\x03\x09 " + "\x1f\x03\x09.\x10\x03\x094\x0b\x03\x09\x1a1\x03\x08#\x1a\x03\x084\x1d" + "\x03\x08\x01\x1f\x03\x08\x11\x22\x03\x07'8\x03\x07\x1a>\x03\x0757\x03" + "\x06&9\x03\x06+\x11\x03\x0a.\x0b\x03\x0a,>\x03\x0a4#\x03\x08%\x17\x03" + "\x07\x05\x22\x03\x07\x0c\x0b\x03\x0a\x1d+\x03\x0a\x19\x16\x03\x09+\x1f" + "\x03\x09\x08\x0b\x03\x08\x16\x18\x03\x08+\x12\x03\x0b\x1d\x0c\x03\x0a=" + "\x10\x03\x0a\x09\x0d\x03\x0a\x10\x11\x03\x09&0\x03\x08(\x1f\x03\x087\x07" + "\x03\x08\x185\x03\x07'6\x03\x06.\x05\x03\x06=\x04\x03\x06;;\x03\x06\x06," + "\x03\x0b\x18>\x03\x08\x00\x18\x03\x06 \x03\x03\x06<\x00\x03\x09%\x18\x03" + "\x0b\x1c<\x03\x0a%!\x03\x0a\x09\x12\x03\x0a\x16\x02\x03\x090'\x03\x09" + "\x0e=\x03\x08 \x0e\x03\x08>\x03\x03\x074>\x03\x06&?\x03\x06\x19\x09\x03" + "\x06?(\x03\x0a-\x0e\x03\x09:3\x03\x098:\x03\x09\x12\x0b\x03\x09\x1d\x17" + "\x03\x087\x05\x03\x082\x14\x03\x08\x06%\x03\x08\x13\x1f\x03\x06\x06\x0e" + "\x03\x0a\x22<\x03\x09/<\x03\x06>+\x03\x0a'?\x03\x0a\x13\x0c\x03\x09\x10<" + "\x03\x07\x1b=\x03\x0a\x19\x13\x03\x09\x22\x1d\x03\x09\x07\x0d\x03\x08)" + "\x1c\x03\x06=\x1a\x03\x0a/4\x03\x0a7\x11\x03\x0a\x16:\x03\x09?3\x03\x09:" + "/\x03\x09\x05\x0a\x03\x09\x14\x06\x03\x087\x22\x03\x080\x07\x03\x08\x1a" + "\x1f\x03\x07\x04(\x03\x07\x04\x09\x03\x06 %\x03\x06<\x08\x03\x0a+\x14" + "\x03\x09\x1d\x16\x03\x0a70\x03\x08 >\x03\x0857\x03\x070\x0a\x03\x06=\x12" + "\x03\x06\x16%\x03\x06\x1d,\x03\x099#\x03\x09\x10>\x03\x07 \x1e\x03\x08" + "\x0c<\x03\x08\x0b\x18\x03\x08\x15+\x03\x08,:\x03\x08%\x22\x03\x07\x0a$" + "\x03\x0b\x1c=\x03\x07+\x08\x03\x0a/\x05\x03\x0a \x07\x03\x0a\x12'\x03" + "\x09#\x11\x03\x08\x1b\x15\x03\x0a\x06\x01\x03\x09\x1c\x1b\x03\x0922\x03" + "\x07\x14<\x03\x07\x09\x04\x03\x061\x04\x03\x07\x0e\x01\x03\x0a\x13\x18" + "\x03\x0a-\x0c\x03\x0a?\x0d\x03\x0a\x09\x0a\x03\x091&\x03\x0a/\x0b\x03" + "\x08$<\x03\x083\x1d\x03\x08\x0c$\x03\x08\x0d\x07\x03\x08\x0d?\x03\x08" + "\x0e\x14\x03\x065\x0a\x03\x08\x1a#\x03\x08\x16#\x03\x0702\x03\x07\x03" + "\x1a\x03\x06(\x1d\x03\x06+\x1b\x03\x06\x0b\x05\x03\x06\x0b\x17\x03\x06" + "\x0c\x04\x03\x06\x1e\x19\x03\x06+0\x03\x062\x18\x03\x0b\x16\x1e\x03\x0a+" + "\x16\x03\x0a-?\x03\x0a#:\x03\x0a#\x10\x03\x0a%$\x03\x0a>+\x03\x0a01\x03" + "\x0a1\x10\x03\x0a\x099\x03\x0a\x0a\x12\x03\x0a\x19\x1f\x03\x0a\x19\x12" + "\x03\x09*)\x03\x09-\x16\x03\x09.1\x03\x09.2\x03\x09<\x0e\x03\x09> \x03" + "\x093\x12\x03\x09\x0b\x01\x03\x09\x1c2\x03\x09\x11\x1c\x03\x09\x15%\x03" + "\x08,&\x03\x08!\x22\x03\x089(\x03\x08\x0b\x1a\x03\x08\x0d2\x03\x08\x0c" + "\x04\x03\x08\x0c\x06\x03\x08\x0c\x1f\x03\x08\x0c\x0c\x03\x08\x0f\x1f\x03" + "\x08\x0f\x1d\x03\x08\x00\x14\x03\x08\x03\x14\x03\x08\x06\x16\x03\x08\x1e" + "#\x03\x08\x11\x11\x03\x08\x10\x18\x03\x08\x14(\x03\x07)\x1e\x03\x07.1" + "\x03\x07 $\x03\x07 '\x03\x078\x08\x03\x07\x0d0\x03\x07\x0f7\x03\x07\x05#" + "\x03\x07\x05\x1a\x03\x07\x1a7\x03\x07\x1d-\x03\x07\x17\x10\x03\x06)\x1f" + "\x03\x062\x0b\x03\x066\x16\x03\x06\x09\x11\x03\x09(\x1e\x03\x07!5\x03" + "\x0b\x11\x16\x03\x0a/\x04\x03\x0a,\x1a\x03\x0b\x173\x03\x0a,1\x03\x0a/5" + "\x03\x0a\x221\x03\x0a\x22\x0d\x03\x0a?%\x03\x0a<,\x03\x0a?#\x03\x0a>\x19" + "\x03\x0a\x08&\x03\x0a\x0b\x0e\x03\x0a\x0c:\x03\x0a\x0c+\x03\x0a\x03\x22" + "\x03\x0a\x06)\x03\x0a\x11\x10\x03\x0a\x11\x1a\x03\x0a\x17-\x03\x0a\x14(" + "\x03\x09)\x1e\x03\x09/\x09\x03\x09.\x00\x03\x09,\x07\x03\x09/*\x03\x09-9" + "\x03\x09\x228\x03\x09%\x09\x03\x09:\x12\x03\x09;\x1d\x03\x09?\x06\x03" + "\x093%\x03\x096\x05\x03\x096\x08\x03\x097\x02\x03\x09\x07,\x03\x09\x04," + "\x03\x09\x1f\x16\x03\x09\x11\x03\x03\x09\x11\x12\x03\x09\x168\x03\x08*" + "\x05\x03\x08/2\x03\x084:\x03\x08\x22+\x03\x08 0\x03\x08&\x0a\x03\x08;" + "\x10\x03\x08>$\x03\x08>\x18\x03\x0829\x03\x082:\x03\x081,\x03\x081<\x03" + "\x081\x1c\x03\x087#\x03\x087*\x03\x08\x09'\x03\x08\x00\x1d\x03\x08\x05-" + "\x03\x08\x1f4\x03\x08\x1d\x04\x03\x08\x16\x0f\x03\x07*7\x03\x07'!\x03" + "\x07%\x1b\x03\x077\x0c\x03\x07\x0c1\x03\x07\x0c.\x03\x07\x00\x06\x03\x07" + "\x01\x02\x03\x07\x010\x03\x07\x06=\x03\x07\x01\x03\x03\x07\x01\x13\x03" + "\x07\x06\x06\x03\x07\x05\x0a\x03\x07\x1f\x09\x03\x07\x17:\x03\x06*1\x03" + "\x06-\x1d\x03\x06\x223\x03\x062:\x03\x060$\x03\x066\x1e\x03\x064\x12\x03" + "\x0645\x03\x06\x0b\x00\x03\x06\x0b7\x03\x06\x07\x1f\x03\x06\x15\x12\x03" + "\x0c\x05\x0f\x03\x0b+\x0b\x03\x0b+-\x03\x06\x16\x1b\x03\x06\x15\x17\x03" + "\x89\xca\xea\x03\x89\xca\xe8\x03\x0c8\x10\x03\x0c8\x01\x03\x0c8\x0f\x03" + "\x0d8%\x03\x0d8!\x03\x0c8-\x03\x0c8/\x03\x0c8+\x03\x0c87\x03\x0c85\x03" + "\x0c9\x09\x03\x0c9\x0d\x03\x0c9\x0f\x03\x0c9\x0b\x03\xcfu\x0c\x03\xcfu" + "\x0f\x03\xcfu\x0e\x03\xcfu\x09\x03\x0c9\x10\x03\x0d9\x0c\x03\xcf`;\x03" + "\xcf`>\x03\xcf`9\x03\xcf`8\x03\xcf`7\x03\xcf`*\x03\xcf`-\x03\xcf`,\x03" + "\x0d\x1b\x1a\x03\x0d\x1b&\x03\x0c=.\x03\x0c=%\x03\x0c>\x1e\x03\x0c>\x14" + "\x03\x0c?\x06\x03\x0c?\x0b\x03\x0c?\x0c\x03\x0c?\x0d\x03\x0c?\x02\x03" + "\x0c>\x0f\x03\x0c>\x08\x03\x0c>\x09\x03\x0c>,\x03\x0c>\x0c\x03\x0c?\x13" + "\x03\x0c?\x16\x03\x0c?\x15\x03\x0c?\x1c\x03\x0c?\x1f\x03\x0c?\x1d\x03" + "\x0c?\x1a\x03\x0c?\x17\x03\x0c?\x08\x03\x0c?\x09\x03\x0c?\x0e\x03\x0c?" + "\x04\x03\x0c?\x05\x03\x0c" + "\x03\x0c=2\x03\x0c=6\x03\x0c<\x07\x03\x0c<\x05\x03\x0e:!\x03\x0e:#\x03" + "\x0e8\x09\x03\x0e:&\x03\x0e8\x0b\x03\x0e:$\x03\x0e:,\x03\x0e8\x1a\x03" + "\x0e8\x1e\x03\x0e:*\x03\x0e:7\x03\x0e:5\x03\x0e:;\x03\x0e:\x15\x03\x0e:<" + "\x03\x0e:4\x03\x0e:'\x03\x0e:-\x03\x0e:%\x03\x0e:?\x03\x0e:=\x03\x0e:)" + "\x03\x0e:/\x03\xcfs'\x03\x0d=\x0f\x03\x0d+*\x03\x0d99\x03\x0d9;\x03\x0d9" + "?\x03\x0d)\x0d\x03\x0d(%\x02\x01\x18\x02\x01(\x02\x01\x1e\x03\x0f$!\x03" + "\x0f87\x03\x0f4\x0e\x03\x0f5\x1d\x03\x06'\x03\x03\x0f\x08\x18\x03\x0f" + "\x0d\x1b\x03\x0e2=\x03\x0e;\x08\x03\x0e:\x0b\x03\x0e\x06$\x03\x0e\x0d)" + "\x03\x0e\x16\x1f\x03\x0e\x16\x1b\x03\x0d$\x0a\x03\x05,\x1d\x03\x0d. \x03" + "\x0d.#\x03\x0c(/\x03\x09%\x02\x03\x0d90\x03\x0d\x0e4\x03\x0d\x0d\x0f\x03" + "\x0c#\x00\x03\x0c,\x1e\x03\x0c2\x0e\x03\x0c\x01\x17\x03\x0c\x09:\x03\x0e" + "\x173\x03\x0c\x08\x03\x03\x0c\x11\x07\x03\x0c\x10\x18\x03\x0c\x1f\x1c" + "\x03\x0c\x19\x0e\x03\x0c\x1a\x1f\x03\x0f0>\x03\x0b->\x03\x0b<+\x03\x0b8" + "\x13\x03\x0b\x043\x03\x0b\x14\x03\x03\x0b\x16%\x03\x0d\x22&\x03\x0b\x1a" + "\x1a\x03\x0b\x1a\x04\x03\x0a%9\x03\x0a&2\x03\x0a&0\x03\x0a!\x1a\x03\x0a!" + "7\x03\x0a5\x10\x03\x0a=4\x03\x0a?\x0e\x03\x0a>\x10\x03\x0a\x00 \x03\x0a" + "\x0f:\x03\x0a\x0f9\x03\x0a\x0b\x0a\x03\x0a\x17%\x03\x0a\x1b-\x03\x09-" + "\x1a\x03\x09,4\x03\x09.,\x03\x09)\x09\x03\x096!\x03\x091\x1f\x03\x093" + "\x16\x03\x0c+\x1f\x03\x098 \x03\x098=\x03\x0c(\x1a\x03\x0c(\x16\x03\x09" + "\x0a+\x03\x09\x16\x12\x03\x09\x13\x0e\x03\x09\x153\x03\x08)!\x03\x09\x1a" + "\x01\x03\x09\x18\x01\x03\x08%#\x03\x08>\x22\x03\x08\x05%\x03\x08\x02*" + "\x03\x08\x15;\x03\x08\x1b7\x03\x0f\x07\x1d\x03\x0f\x04\x03\x03\x070\x0c" + "\x03\x07;\x0b\x03\x07\x08\x17\x03\x07\x12\x06\x03\x06/-\x03\x0671\x03" + "\x065+\x03\x06>7\x03\x06\x049\x03\x05+\x1e\x03\x05,\x17\x03\x05 \x1d\x03" + "\x05\x22\x05\x03\x050\x1d" // lookup returns the trie value for the first UTF-8 encoding in s and // the width in bytes of this encoding. The size will be 0 if s does not // hold enough bytes to complete the encoding. len(s) must be greater than 0. func (t *idnaTrie) lookup(s []byte) (v uint16, sz int) { c0 := s[0] switch { case c0 < 0x80: // is ASCII return idnaValues[c0], 1 case c0 < 0xC2: return 0, 1 // Illegal UTF-8: not a starter, not ASCII. case c0 < 0xE0: // 2-byte UTF-8 if len(s) < 2 { return 0, 0 } i := idnaIndex[c0] c1 := s[1] if c1 < 0x80 || 0xC0 <= c1 { return 0, 1 // Illegal UTF-8: not a continuation byte. } return t.lookupValue(uint32(i), c1), 2 case c0 < 0xF0: // 3-byte UTF-8 if len(s) < 3 { return 0, 0 } i := idnaIndex[c0] c1 := s[1] if c1 < 0x80 || 0xC0 <= c1 { return 0, 1 // Illegal UTF-8: not a continuation byte. } o := uint32(i)<<6 + uint32(c1) i = idnaIndex[o] c2 := s[2] if c2 < 0x80 || 0xC0 <= c2 { return 0, 2 // Illegal UTF-8: not a continuation byte. } return t.lookupValue(uint32(i), c2), 3 case c0 < 0xF8: // 4-byte UTF-8 if len(s) < 4 { return 0, 0 } i := idnaIndex[c0] c1 := s[1] if c1 < 0x80 || 0xC0 <= c1 { return 0, 1 // Illegal UTF-8: not a continuation byte. } o := uint32(i)<<6 + uint32(c1) i = idnaIndex[o] c2 := s[2] if c2 < 0x80 || 0xC0 <= c2 { return 0, 2 // Illegal UTF-8: not a continuation byte. } o = uint32(i)<<6 + uint32(c2) i = idnaIndex[o] c3 := s[3] if c3 < 0x80 || 0xC0 <= c3 { return 0, 3 // Illegal UTF-8: not a continuation byte. } return t.lookupValue(uint32(i), c3), 4 } // Illegal rune return 0, 1 } // lookupUnsafe returns the trie value for the first UTF-8 encoding in s. // s must start with a full and valid UTF-8 encoded rune. func (t *idnaTrie) lookupUnsafe(s []byte) uint16 { c0 := s[0] if c0 < 0x80 { // is ASCII return idnaValues[c0] } i := idnaIndex[c0] if c0 < 0xE0 { // 2-byte UTF-8 return t.lookupValue(uint32(i), s[1]) } i = idnaIndex[uint32(i)<<6+uint32(s[1])] if c0 < 0xF0 { // 3-byte UTF-8 return t.lookupValue(uint32(i), s[2]) } i = idnaIndex[uint32(i)<<6+uint32(s[2])] if c0 < 0xF8 { // 4-byte UTF-8 return t.lookupValue(uint32(i), s[3]) } return 0 } // lookupString returns the trie value for the first UTF-8 encoding in s and // the width in bytes of this encoding. The size will be 0 if s does not // hold enough bytes to complete the encoding. len(s) must be greater than 0. func (t *idnaTrie) lookupString(s string) (v uint16, sz int) { c0 := s[0] switch { case c0 < 0x80: // is ASCII return idnaValues[c0], 1 case c0 < 0xC2: return 0, 1 // Illegal UTF-8: not a starter, not ASCII. case c0 < 0xE0: // 2-byte UTF-8 if len(s) < 2 { return 0, 0 } i := idnaIndex[c0] c1 := s[1] if c1 < 0x80 || 0xC0 <= c1 { return 0, 1 // Illegal UTF-8: not a continuation byte. } return t.lookupValue(uint32(i), c1), 2 case c0 < 0xF0: // 3-byte UTF-8 if len(s) < 3 { return 0, 0 } i := idnaIndex[c0] c1 := s[1] if c1 < 0x80 || 0xC0 <= c1 { return 0, 1 // Illegal UTF-8: not a continuation byte. } o := uint32(i)<<6 + uint32(c1) i = idnaIndex[o] c2 := s[2] if c2 < 0x80 || 0xC0 <= c2 { return 0, 2 // Illegal UTF-8: not a continuation byte. } return t.lookupValue(uint32(i), c2), 3 case c0 < 0xF8: // 4-byte UTF-8 if len(s) < 4 { return 0, 0 } i := idnaIndex[c0] c1 := s[1] if c1 < 0x80 || 0xC0 <= c1 { return 0, 1 // Illegal UTF-8: not a continuation byte. } o := uint32(i)<<6 + uint32(c1) i = idnaIndex[o] c2 := s[2] if c2 < 0x80 || 0xC0 <= c2 { return 0, 2 // Illegal UTF-8: not a continuation byte. } o = uint32(i)<<6 + uint32(c2) i = idnaIndex[o] c3 := s[3] if c3 < 0x80 || 0xC0 <= c3 { return 0, 3 // Illegal UTF-8: not a continuation byte. } return t.lookupValue(uint32(i), c3), 4 } // Illegal rune return 0, 1 } // lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. // s must start with a full and valid UTF-8 encoded rune. func (t *idnaTrie) lookupStringUnsafe(s string) uint16 { c0 := s[0] if c0 < 0x80 { // is ASCII return idnaValues[c0] } i := idnaIndex[c0] if c0 < 0xE0 { // 2-byte UTF-8 return t.lookupValue(uint32(i), s[1]) } i = idnaIndex[uint32(i)<<6+uint32(s[1])] if c0 < 0xF0 { // 3-byte UTF-8 return t.lookupValue(uint32(i), s[2]) } i = idnaIndex[uint32(i)<<6+uint32(s[2])] if c0 < 0xF8 { // 4-byte UTF-8 return t.lookupValue(uint32(i), s[3]) } return 0 } // idnaTrie. Total size: 28496 bytes (27.83 KiB). Checksum: 43288b883596640e. type idnaTrie struct{} func newIdnaTrie(i int) *idnaTrie { return &idnaTrie{} } // lookupValue determines the type of block n and looks up the value for b. func (t *idnaTrie) lookupValue(n uint32, b byte) uint16 { switch { case n < 123: return uint16(idnaValues[n<<6+uint32(b)]) default: n -= 123 return uint16(idnaSparse.lookup(n, b)) } } // idnaValues: 125 blocks, 8000 entries, 16000 bytes // The third block is the zero block. var idnaValues = [8000]uint16{ // Block 0x0, offset 0x0 0x00: 0x0080, 0x01: 0x0080, 0x02: 0x0080, 0x03: 0x0080, 0x04: 0x0080, 0x05: 0x0080, 0x06: 0x0080, 0x07: 0x0080, 0x08: 0x0080, 0x09: 0x0080, 0x0a: 0x0080, 0x0b: 0x0080, 0x0c: 0x0080, 0x0d: 0x0080, 0x0e: 0x0080, 0x0f: 0x0080, 0x10: 0x0080, 0x11: 0x0080, 0x12: 0x0080, 0x13: 0x0080, 0x14: 0x0080, 0x15: 0x0080, 0x16: 0x0080, 0x17: 0x0080, 0x18: 0x0080, 0x19: 0x0080, 0x1a: 0x0080, 0x1b: 0x0080, 0x1c: 0x0080, 0x1d: 0x0080, 0x1e: 0x0080, 0x1f: 0x0080, 0x20: 0x0080, 0x21: 0x0080, 0x22: 0x0080, 0x23: 0x0080, 0x24: 0x0080, 0x25: 0x0080, 0x26: 0x0080, 0x27: 0x0080, 0x28: 0x0080, 0x29: 0x0080, 0x2a: 0x0080, 0x2b: 0x0080, 0x2c: 0x0080, 0x2d: 0x0008, 0x2e: 0x0008, 0x2f: 0x0080, 0x30: 0x0008, 0x31: 0x0008, 0x32: 0x0008, 0x33: 0x0008, 0x34: 0x0008, 0x35: 0x0008, 0x36: 0x0008, 0x37: 0x0008, 0x38: 0x0008, 0x39: 0x0008, 0x3a: 0x0080, 0x3b: 0x0080, 0x3c: 0x0080, 0x3d: 0x0080, 0x3e: 0x0080, 0x3f: 0x0080, // Block 0x1, offset 0x40 0x40: 0x0080, 0x41: 0xe105, 0x42: 0xe105, 0x43: 0xe105, 0x44: 0xe105, 0x45: 0xe105, 0x46: 0xe105, 0x47: 0xe105, 0x48: 0xe105, 0x49: 0xe105, 0x4a: 0xe105, 0x4b: 0xe105, 0x4c: 0xe105, 0x4d: 0xe105, 0x4e: 0xe105, 0x4f: 0xe105, 0x50: 0xe105, 0x51: 0xe105, 0x52: 0xe105, 0x53: 0xe105, 0x54: 0xe105, 0x55: 0xe105, 0x56: 0xe105, 0x57: 0xe105, 0x58: 0xe105, 0x59: 0xe105, 0x5a: 0xe105, 0x5b: 0x0080, 0x5c: 0x0080, 0x5d: 0x0080, 0x5e: 0x0080, 0x5f: 0x0080, 0x60: 0x0080, 0x61: 0x0008, 0x62: 0x0008, 0x63: 0x0008, 0x64: 0x0008, 0x65: 0x0008, 0x66: 0x0008, 0x67: 0x0008, 0x68: 0x0008, 0x69: 0x0008, 0x6a: 0x0008, 0x6b: 0x0008, 0x6c: 0x0008, 0x6d: 0x0008, 0x6e: 0x0008, 0x6f: 0x0008, 0x70: 0x0008, 0x71: 0x0008, 0x72: 0x0008, 0x73: 0x0008, 0x74: 0x0008, 0x75: 0x0008, 0x76: 0x0008, 0x77: 0x0008, 0x78: 0x0008, 0x79: 0x0008, 0x7a: 0x0008, 0x7b: 0x0080, 0x7c: 0x0080, 0x7d: 0x0080, 0x7e: 0x0080, 0x7f: 0x0080, // Block 0x2, offset 0x80 // Block 0x3, offset 0xc0 0xc0: 0x0040, 0xc1: 0x0040, 0xc2: 0x0040, 0xc3: 0x0040, 0xc4: 0x0040, 0xc5: 0x0040, 0xc6: 0x0040, 0xc7: 0x0040, 0xc8: 0x0040, 0xc9: 0x0040, 0xca: 0x0040, 0xcb: 0x0040, 0xcc: 0x0040, 0xcd: 0x0040, 0xce: 0x0040, 0xcf: 0x0040, 0xd0: 0x0040, 0xd1: 0x0040, 0xd2: 0x0040, 0xd3: 0x0040, 0xd4: 0x0040, 0xd5: 0x0040, 0xd6: 0x0040, 0xd7: 0x0040, 0xd8: 0x0040, 0xd9: 0x0040, 0xda: 0x0040, 0xdb: 0x0040, 0xdc: 0x0040, 0xdd: 0x0040, 0xde: 0x0040, 0xdf: 0x0040, 0xe0: 0x000a, 0xe1: 0x0018, 0xe2: 0x0018, 0xe3: 0x0018, 0xe4: 0x0018, 0xe5: 0x0018, 0xe6: 0x0018, 0xe7: 0x0018, 0xe8: 0x001a, 0xe9: 0x0018, 0xea: 0x0039, 0xeb: 0x0018, 0xec: 0x0018, 0xed: 0x03c0, 0xee: 0x0018, 0xef: 0x004a, 0xf0: 0x0018, 0xf1: 0x0018, 0xf2: 0x0069, 0xf3: 0x0079, 0xf4: 0x008a, 0xf5: 0x0005, 0xf6: 0x0018, 0xf7: 0x0008, 0xf8: 0x00aa, 0xf9: 0x00c9, 0xfa: 0x00d9, 0xfb: 0x0018, 0xfc: 0x00e9, 0xfd: 0x0119, 0xfe: 0x0149, 0xff: 0x0018, // Block 0x4, offset 0x100 0x100: 0xe00d, 0x101: 0x0008, 0x102: 0xe00d, 0x103: 0x0008, 0x104: 0xe00d, 0x105: 0x0008, 0x106: 0xe00d, 0x107: 0x0008, 0x108: 0xe00d, 0x109: 0x0008, 0x10a: 0xe00d, 0x10b: 0x0008, 0x10c: 0xe00d, 0x10d: 0x0008, 0x10e: 0xe00d, 0x10f: 0x0008, 0x110: 0xe00d, 0x111: 0x0008, 0x112: 0xe00d, 0x113: 0x0008, 0x114: 0xe00d, 0x115: 0x0008, 0x116: 0xe00d, 0x117: 0x0008, 0x118: 0xe00d, 0x119: 0x0008, 0x11a: 0xe00d, 0x11b: 0x0008, 0x11c: 0xe00d, 0x11d: 0x0008, 0x11e: 0xe00d, 0x11f: 0x0008, 0x120: 0xe00d, 0x121: 0x0008, 0x122: 0xe00d, 0x123: 0x0008, 0x124: 0xe00d, 0x125: 0x0008, 0x126: 0xe00d, 0x127: 0x0008, 0x128: 0xe00d, 0x129: 0x0008, 0x12a: 0xe00d, 0x12b: 0x0008, 0x12c: 0xe00d, 0x12d: 0x0008, 0x12e: 0xe00d, 0x12f: 0x0008, 0x130: 0x0179, 0x131: 0x0008, 0x132: 0x0035, 0x133: 0x004d, 0x134: 0xe00d, 0x135: 0x0008, 0x136: 0xe00d, 0x137: 0x0008, 0x138: 0x0008, 0x139: 0xe01d, 0x13a: 0x0008, 0x13b: 0xe03d, 0x13c: 0x0008, 0x13d: 0xe01d, 0x13e: 0x0008, 0x13f: 0x0199, // Block 0x5, offset 0x140 0x140: 0x0199, 0x141: 0xe01d, 0x142: 0x0008, 0x143: 0xe03d, 0x144: 0x0008, 0x145: 0xe01d, 0x146: 0x0008, 0x147: 0xe07d, 0x148: 0x0008, 0x149: 0x01b9, 0x14a: 0xe00d, 0x14b: 0x0008, 0x14c: 0xe00d, 0x14d: 0x0008, 0x14e: 0xe00d, 0x14f: 0x0008, 0x150: 0xe00d, 0x151: 0x0008, 0x152: 0xe00d, 0x153: 0x0008, 0x154: 0xe00d, 0x155: 0x0008, 0x156: 0xe00d, 0x157: 0x0008, 0x158: 0xe00d, 0x159: 0x0008, 0x15a: 0xe00d, 0x15b: 0x0008, 0x15c: 0xe00d, 0x15d: 0x0008, 0x15e: 0xe00d, 0x15f: 0x0008, 0x160: 0xe00d, 0x161: 0x0008, 0x162: 0xe00d, 0x163: 0x0008, 0x164: 0xe00d, 0x165: 0x0008, 0x166: 0xe00d, 0x167: 0x0008, 0x168: 0xe00d, 0x169: 0x0008, 0x16a: 0xe00d, 0x16b: 0x0008, 0x16c: 0xe00d, 0x16d: 0x0008, 0x16e: 0xe00d, 0x16f: 0x0008, 0x170: 0xe00d, 0x171: 0x0008, 0x172: 0xe00d, 0x173: 0x0008, 0x174: 0xe00d, 0x175: 0x0008, 0x176: 0xe00d, 0x177: 0x0008, 0x178: 0x0065, 0x179: 0xe01d, 0x17a: 0x0008, 0x17b: 0xe03d, 0x17c: 0x0008, 0x17d: 0xe01d, 0x17e: 0x0008, 0x17f: 0x01d9, // Block 0x6, offset 0x180 0x180: 0x0008, 0x181: 0x007d, 0x182: 0xe00d, 0x183: 0x0008, 0x184: 0xe00d, 0x185: 0x0008, 0x186: 0x007d, 0x187: 0xe07d, 0x188: 0x0008, 0x189: 0x0095, 0x18a: 0x00ad, 0x18b: 0xe03d, 0x18c: 0x0008, 0x18d: 0x0008, 0x18e: 0x00c5, 0x18f: 0x00dd, 0x190: 0x00f5, 0x191: 0xe01d, 0x192: 0x0008, 0x193: 0x010d, 0x194: 0x0125, 0x195: 0x0008, 0x196: 0x013d, 0x197: 0x013d, 0x198: 0xe00d, 0x199: 0x0008, 0x19a: 0x0008, 0x19b: 0x0008, 0x19c: 0x010d, 0x19d: 0x0155, 0x19e: 0x0008, 0x19f: 0x016d, 0x1a0: 0xe00d, 0x1a1: 0x0008, 0x1a2: 0xe00d, 0x1a3: 0x0008, 0x1a4: 0xe00d, 0x1a5: 0x0008, 0x1a6: 0x0185, 0x1a7: 0xe07d, 0x1a8: 0x0008, 0x1a9: 0x019d, 0x1aa: 0x0008, 0x1ab: 0x0008, 0x1ac: 0xe00d, 0x1ad: 0x0008, 0x1ae: 0x0185, 0x1af: 0xe0fd, 0x1b0: 0x0008, 0x1b1: 0x01b5, 0x1b2: 0x01cd, 0x1b3: 0xe03d, 0x1b4: 0x0008, 0x1b5: 0xe01d, 0x1b6: 0x0008, 0x1b7: 0x01e5, 0x1b8: 0xe00d, 0x1b9: 0x0008, 0x1ba: 0x0008, 0x1bb: 0x0008, 0x1bc: 0xe00d, 0x1bd: 0x0008, 0x1be: 0x0008, 0x1bf: 0x0008, // Block 0x7, offset 0x1c0 0x1c0: 0x0008, 0x1c1: 0x0008, 0x1c2: 0x0008, 0x1c3: 0x0008, 0x1c4: 0x01e9, 0x1c5: 0x01e9, 0x1c6: 0x01e9, 0x1c7: 0x01fd, 0x1c8: 0x0215, 0x1c9: 0x022d, 0x1ca: 0x0245, 0x1cb: 0x025d, 0x1cc: 0x0275, 0x1cd: 0xe01d, 0x1ce: 0x0008, 0x1cf: 0xe0fd, 0x1d0: 0x0008, 0x1d1: 0xe01d, 0x1d2: 0x0008, 0x1d3: 0xe03d, 0x1d4: 0x0008, 0x1d5: 0xe01d, 0x1d6: 0x0008, 0x1d7: 0xe07d, 0x1d8: 0x0008, 0x1d9: 0xe01d, 0x1da: 0x0008, 0x1db: 0xe03d, 0x1dc: 0x0008, 0x1dd: 0x0008, 0x1de: 0xe00d, 0x1df: 0x0008, 0x1e0: 0xe00d, 0x1e1: 0x0008, 0x1e2: 0xe00d, 0x1e3: 0x0008, 0x1e4: 0xe00d, 0x1e5: 0x0008, 0x1e6: 0xe00d, 0x1e7: 0x0008, 0x1e8: 0xe00d, 0x1e9: 0x0008, 0x1ea: 0xe00d, 0x1eb: 0x0008, 0x1ec: 0xe00d, 0x1ed: 0x0008, 0x1ee: 0xe00d, 0x1ef: 0x0008, 0x1f0: 0x0008, 0x1f1: 0x028d, 0x1f2: 0x02a5, 0x1f3: 0x02bd, 0x1f4: 0xe00d, 0x1f5: 0x0008, 0x1f6: 0x02d5, 0x1f7: 0x02ed, 0x1f8: 0xe00d, 0x1f9: 0x0008, 0x1fa: 0xe00d, 0x1fb: 0x0008, 0x1fc: 0xe00d, 0x1fd: 0x0008, 0x1fe: 0xe00d, 0x1ff: 0x0008, // Block 0x8, offset 0x200 0x200: 0xe00d, 0x201: 0x0008, 0x202: 0xe00d, 0x203: 0x0008, 0x204: 0xe00d, 0x205: 0x0008, 0x206: 0xe00d, 0x207: 0x0008, 0x208: 0xe00d, 0x209: 0x0008, 0x20a: 0xe00d, 0x20b: 0x0008, 0x20c: 0xe00d, 0x20d: 0x0008, 0x20e: 0xe00d, 0x20f: 0x0008, 0x210: 0xe00d, 0x211: 0x0008, 0x212: 0xe00d, 0x213: 0x0008, 0x214: 0xe00d, 0x215: 0x0008, 0x216: 0xe00d, 0x217: 0x0008, 0x218: 0xe00d, 0x219: 0x0008, 0x21a: 0xe00d, 0x21b: 0x0008, 0x21c: 0xe00d, 0x21d: 0x0008, 0x21e: 0xe00d, 0x21f: 0x0008, 0x220: 0x0305, 0x221: 0x0008, 0x222: 0xe00d, 0x223: 0x0008, 0x224: 0xe00d, 0x225: 0x0008, 0x226: 0xe00d, 0x227: 0x0008, 0x228: 0xe00d, 0x229: 0x0008, 0x22a: 0xe00d, 0x22b: 0x0008, 0x22c: 0xe00d, 0x22d: 0x0008, 0x22e: 0xe00d, 0x22f: 0x0008, 0x230: 0xe00d, 0x231: 0x0008, 0x232: 0xe00d, 0x233: 0x0008, 0x234: 0x0008, 0x235: 0x0008, 0x236: 0x0008, 0x237: 0x0008, 0x238: 0x0008, 0x239: 0x0008, 0x23a: 0x0209, 0x23b: 0xe03d, 0x23c: 0x0008, 0x23d: 0x031d, 0x23e: 0x0229, 0x23f: 0x0008, // Block 0x9, offset 0x240 0x240: 0x0008, 0x241: 0x0008, 0x242: 0x0018, 0x243: 0x0018, 0x244: 0x0018, 0x245: 0x0018, 0x246: 0x0008, 0x247: 0x0008, 0x248: 0x0008, 0x249: 0x0008, 0x24a: 0x0008, 0x24b: 0x0008, 0x24c: 0x0008, 0x24d: 0x0008, 0x24e: 0x0008, 0x24f: 0x0008, 0x250: 0x0008, 0x251: 0x0008, 0x252: 0x0018, 0x253: 0x0018, 0x254: 0x0018, 0x255: 0x0018, 0x256: 0x0018, 0x257: 0x0018, 0x258: 0x029a, 0x259: 0x02ba, 0x25a: 0x02da, 0x25b: 0x02fa, 0x25c: 0x031a, 0x25d: 0x033a, 0x25e: 0x0018, 0x25f: 0x0018, 0x260: 0x03ad, 0x261: 0x0359, 0x262: 0x01d9, 0x263: 0x0369, 0x264: 0x03c5, 0x265: 0x0018, 0x266: 0x0018, 0x267: 0x0018, 0x268: 0x0018, 0x269: 0x0018, 0x26a: 0x0018, 0x26b: 0x0018, 0x26c: 0x0008, 0x26d: 0x0018, 0x26e: 0x0008, 0x26f: 0x0018, 0x270: 0x0018, 0x271: 0x0018, 0x272: 0x0018, 0x273: 0x0018, 0x274: 0x0018, 0x275: 0x0018, 0x276: 0x0018, 0x277: 0x0018, 0x278: 0x0018, 0x279: 0x0018, 0x27a: 0x0018, 0x27b: 0x0018, 0x27c: 0x0018, 0x27d: 0x0018, 0x27e: 0x0018, 0x27f: 0x0018, // Block 0xa, offset 0x280 0x280: 0x03dd, 0x281: 0x03dd, 0x282: 0x1308, 0x283: 0x03f5, 0x284: 0x0379, 0x285: 0x040d, 0x286: 0x1308, 0x287: 0x1308, 0x288: 0x1308, 0x289: 0x1308, 0x28a: 0x1308, 0x28b: 0x1308, 0x28c: 0x1308, 0x28d: 0x1308, 0x28e: 0x1308, 0x28f: 0x13c0, 0x290: 0x1308, 0x291: 0x1308, 0x292: 0x1308, 0x293: 0x1308, 0x294: 0x1308, 0x295: 0x1308, 0x296: 0x1308, 0x297: 0x1308, 0x298: 0x1308, 0x299: 0x1308, 0x29a: 0x1308, 0x29b: 0x1308, 0x29c: 0x1308, 0x29d: 0x1308, 0x29e: 0x1308, 0x29f: 0x1308, 0x2a0: 0x1308, 0x2a1: 0x1308, 0x2a2: 0x1308, 0x2a3: 0x1308, 0x2a4: 0x1308, 0x2a5: 0x1308, 0x2a6: 0x1308, 0x2a7: 0x1308, 0x2a8: 0x1308, 0x2a9: 0x1308, 0x2aa: 0x1308, 0x2ab: 0x1308, 0x2ac: 0x1308, 0x2ad: 0x1308, 0x2ae: 0x1308, 0x2af: 0x1308, 0x2b0: 0xe00d, 0x2b1: 0x0008, 0x2b2: 0xe00d, 0x2b3: 0x0008, 0x2b4: 0x0425, 0x2b5: 0x0008, 0x2b6: 0xe00d, 0x2b7: 0x0008, 0x2b8: 0x0040, 0x2b9: 0x0040, 0x2ba: 0x03a2, 0x2bb: 0x0008, 0x2bc: 0x0008, 0x2bd: 0x0008, 0x2be: 0x03c2, 0x2bf: 0x043d, // Block 0xb, offset 0x2c0 0x2c0: 0x0040, 0x2c1: 0x0040, 0x2c2: 0x0040, 0x2c3: 0x0040, 0x2c4: 0x008a, 0x2c5: 0x03d2, 0x2c6: 0xe155, 0x2c7: 0x0455, 0x2c8: 0xe12d, 0x2c9: 0xe13d, 0x2ca: 0xe12d, 0x2cb: 0x0040, 0x2cc: 0x03dd, 0x2cd: 0x0040, 0x2ce: 0x046d, 0x2cf: 0x0485, 0x2d0: 0x0008, 0x2d1: 0xe105, 0x2d2: 0xe105, 0x2d3: 0xe105, 0x2d4: 0xe105, 0x2d5: 0xe105, 0x2d6: 0xe105, 0x2d7: 0xe105, 0x2d8: 0xe105, 0x2d9: 0xe105, 0x2da: 0xe105, 0x2db: 0xe105, 0x2dc: 0xe105, 0x2dd: 0xe105, 0x2de: 0xe105, 0x2df: 0xe105, 0x2e0: 0x049d, 0x2e1: 0x049d, 0x2e2: 0x0040, 0x2e3: 0x049d, 0x2e4: 0x049d, 0x2e5: 0x049d, 0x2e6: 0x049d, 0x2e7: 0x049d, 0x2e8: 0x049d, 0x2e9: 0x049d, 0x2ea: 0x049d, 0x2eb: 0x049d, 0x2ec: 0x0008, 0x2ed: 0x0008, 0x2ee: 0x0008, 0x2ef: 0x0008, 0x2f0: 0x0008, 0x2f1: 0x0008, 0x2f2: 0x0008, 0x2f3: 0x0008, 0x2f4: 0x0008, 0x2f5: 0x0008, 0x2f6: 0x0008, 0x2f7: 0x0008, 0x2f8: 0x0008, 0x2f9: 0x0008, 0x2fa: 0x0008, 0x2fb: 0x0008, 0x2fc: 0x0008, 0x2fd: 0x0008, 0x2fe: 0x0008, 0x2ff: 0x0008, // Block 0xc, offset 0x300 0x300: 0x0008, 0x301: 0x0008, 0x302: 0xe00f, 0x303: 0x0008, 0x304: 0x0008, 0x305: 0x0008, 0x306: 0x0008, 0x307: 0x0008, 0x308: 0x0008, 0x309: 0x0008, 0x30a: 0x0008, 0x30b: 0x0008, 0x30c: 0x0008, 0x30d: 0x0008, 0x30e: 0x0008, 0x30f: 0xe0c5, 0x310: 0x04b5, 0x311: 0x04cd, 0x312: 0xe0bd, 0x313: 0xe0f5, 0x314: 0xe0fd, 0x315: 0xe09d, 0x316: 0xe0b5, 0x317: 0x0008, 0x318: 0xe00d, 0x319: 0x0008, 0x31a: 0xe00d, 0x31b: 0x0008, 0x31c: 0xe00d, 0x31d: 0x0008, 0x31e: 0xe00d, 0x31f: 0x0008, 0x320: 0xe00d, 0x321: 0x0008, 0x322: 0xe00d, 0x323: 0x0008, 0x324: 0xe00d, 0x325: 0x0008, 0x326: 0xe00d, 0x327: 0x0008, 0x328: 0xe00d, 0x329: 0x0008, 0x32a: 0xe00d, 0x32b: 0x0008, 0x32c: 0xe00d, 0x32d: 0x0008, 0x32e: 0xe00d, 0x32f: 0x0008, 0x330: 0x04e5, 0x331: 0xe185, 0x332: 0xe18d, 0x333: 0x0008, 0x334: 0x04fd, 0x335: 0x03dd, 0x336: 0x0018, 0x337: 0xe07d, 0x338: 0x0008, 0x339: 0xe1d5, 0x33a: 0xe00d, 0x33b: 0x0008, 0x33c: 0x0008, 0x33d: 0x0515, 0x33e: 0x052d, 0x33f: 0x052d, // Block 0xd, offset 0x340 0x340: 0x0008, 0x341: 0x0008, 0x342: 0x0008, 0x343: 0x0008, 0x344: 0x0008, 0x345: 0x0008, 0x346: 0x0008, 0x347: 0x0008, 0x348: 0x0008, 0x349: 0x0008, 0x34a: 0x0008, 0x34b: 0x0008, 0x34c: 0x0008, 0x34d: 0x0008, 0x34e: 0x0008, 0x34f: 0x0008, 0x350: 0x0008, 0x351: 0x0008, 0x352: 0x0008, 0x353: 0x0008, 0x354: 0x0008, 0x355: 0x0008, 0x356: 0x0008, 0x357: 0x0008, 0x358: 0x0008, 0x359: 0x0008, 0x35a: 0x0008, 0x35b: 0x0008, 0x35c: 0x0008, 0x35d: 0x0008, 0x35e: 0x0008, 0x35f: 0x0008, 0x360: 0xe00d, 0x361: 0x0008, 0x362: 0xe00d, 0x363: 0x0008, 0x364: 0xe00d, 0x365: 0x0008, 0x366: 0xe00d, 0x367: 0x0008, 0x368: 0xe00d, 0x369: 0x0008, 0x36a: 0xe00d, 0x36b: 0x0008, 0x36c: 0xe00d, 0x36d: 0x0008, 0x36e: 0xe00d, 0x36f: 0x0008, 0x370: 0xe00d, 0x371: 0x0008, 0x372: 0xe00d, 0x373: 0x0008, 0x374: 0xe00d, 0x375: 0x0008, 0x376: 0xe00d, 0x377: 0x0008, 0x378: 0xe00d, 0x379: 0x0008, 0x37a: 0xe00d, 0x37b: 0x0008, 0x37c: 0xe00d, 0x37d: 0x0008, 0x37e: 0xe00d, 0x37f: 0x0008, // Block 0xe, offset 0x380 0x380: 0xe00d, 0x381: 0x0008, 0x382: 0x0018, 0x383: 0x1308, 0x384: 0x1308, 0x385: 0x1308, 0x386: 0x1308, 0x387: 0x1308, 0x388: 0x1318, 0x389: 0x1318, 0x38a: 0xe00d, 0x38b: 0x0008, 0x38c: 0xe00d, 0x38d: 0x0008, 0x38e: 0xe00d, 0x38f: 0x0008, 0x390: 0xe00d, 0x391: 0x0008, 0x392: 0xe00d, 0x393: 0x0008, 0x394: 0xe00d, 0x395: 0x0008, 0x396: 0xe00d, 0x397: 0x0008, 0x398: 0xe00d, 0x399: 0x0008, 0x39a: 0xe00d, 0x39b: 0x0008, 0x39c: 0xe00d, 0x39d: 0x0008, 0x39e: 0xe00d, 0x39f: 0x0008, 0x3a0: 0xe00d, 0x3a1: 0x0008, 0x3a2: 0xe00d, 0x3a3: 0x0008, 0x3a4: 0xe00d, 0x3a5: 0x0008, 0x3a6: 0xe00d, 0x3a7: 0x0008, 0x3a8: 0xe00d, 0x3a9: 0x0008, 0x3aa: 0xe00d, 0x3ab: 0x0008, 0x3ac: 0xe00d, 0x3ad: 0x0008, 0x3ae: 0xe00d, 0x3af: 0x0008, 0x3b0: 0xe00d, 0x3b1: 0x0008, 0x3b2: 0xe00d, 0x3b3: 0x0008, 0x3b4: 0xe00d, 0x3b5: 0x0008, 0x3b6: 0xe00d, 0x3b7: 0x0008, 0x3b8: 0xe00d, 0x3b9: 0x0008, 0x3ba: 0xe00d, 0x3bb: 0x0008, 0x3bc: 0xe00d, 0x3bd: 0x0008, 0x3be: 0xe00d, 0x3bf: 0x0008, // Block 0xf, offset 0x3c0 0x3c0: 0x0040, 0x3c1: 0xe01d, 0x3c2: 0x0008, 0x3c3: 0xe03d, 0x3c4: 0x0008, 0x3c5: 0xe01d, 0x3c6: 0x0008, 0x3c7: 0xe07d, 0x3c8: 0x0008, 0x3c9: 0xe01d, 0x3ca: 0x0008, 0x3cb: 0xe03d, 0x3cc: 0x0008, 0x3cd: 0xe01d, 0x3ce: 0x0008, 0x3cf: 0x0008, 0x3d0: 0xe00d, 0x3d1: 0x0008, 0x3d2: 0xe00d, 0x3d3: 0x0008, 0x3d4: 0xe00d, 0x3d5: 0x0008, 0x3d6: 0xe00d, 0x3d7: 0x0008, 0x3d8: 0xe00d, 0x3d9: 0x0008, 0x3da: 0xe00d, 0x3db: 0x0008, 0x3dc: 0xe00d, 0x3dd: 0x0008, 0x3de: 0xe00d, 0x3df: 0x0008, 0x3e0: 0xe00d, 0x3e1: 0x0008, 0x3e2: 0xe00d, 0x3e3: 0x0008, 0x3e4: 0xe00d, 0x3e5: 0x0008, 0x3e6: 0xe00d, 0x3e7: 0x0008, 0x3e8: 0xe00d, 0x3e9: 0x0008, 0x3ea: 0xe00d, 0x3eb: 0x0008, 0x3ec: 0xe00d, 0x3ed: 0x0008, 0x3ee: 0xe00d, 0x3ef: 0x0008, 0x3f0: 0xe00d, 0x3f1: 0x0008, 0x3f2: 0xe00d, 0x3f3: 0x0008, 0x3f4: 0xe00d, 0x3f5: 0x0008, 0x3f6: 0xe00d, 0x3f7: 0x0008, 0x3f8: 0xe00d, 0x3f9: 0x0008, 0x3fa: 0xe00d, 0x3fb: 0x0008, 0x3fc: 0xe00d, 0x3fd: 0x0008, 0x3fe: 0xe00d, 0x3ff: 0x0008, // Block 0x10, offset 0x400 0x400: 0xe00d, 0x401: 0x0008, 0x402: 0xe00d, 0x403: 0x0008, 0x404: 0xe00d, 0x405: 0x0008, 0x406: 0xe00d, 0x407: 0x0008, 0x408: 0xe00d, 0x409: 0x0008, 0x40a: 0xe00d, 0x40b: 0x0008, 0x40c: 0xe00d, 0x40d: 0x0008, 0x40e: 0xe00d, 0x40f: 0x0008, 0x410: 0xe00d, 0x411: 0x0008, 0x412: 0xe00d, 0x413: 0x0008, 0x414: 0xe00d, 0x415: 0x0008, 0x416: 0xe00d, 0x417: 0x0008, 0x418: 0xe00d, 0x419: 0x0008, 0x41a: 0xe00d, 0x41b: 0x0008, 0x41c: 0xe00d, 0x41d: 0x0008, 0x41e: 0xe00d, 0x41f: 0x0008, 0x420: 0xe00d, 0x421: 0x0008, 0x422: 0xe00d, 0x423: 0x0008, 0x424: 0xe00d, 0x425: 0x0008, 0x426: 0xe00d, 0x427: 0x0008, 0x428: 0xe00d, 0x429: 0x0008, 0x42a: 0xe00d, 0x42b: 0x0008, 0x42c: 0xe00d, 0x42d: 0x0008, 0x42e: 0xe00d, 0x42f: 0x0008, 0x430: 0x0040, 0x431: 0x03f5, 0x432: 0x03f5, 0x433: 0x03f5, 0x434: 0x03f5, 0x435: 0x03f5, 0x436: 0x03f5, 0x437: 0x03f5, 0x438: 0x03f5, 0x439: 0x03f5, 0x43a: 0x03f5, 0x43b: 0x03f5, 0x43c: 0x03f5, 0x43d: 0x03f5, 0x43e: 0x03f5, 0x43f: 0x03f5, // Block 0x11, offset 0x440 0x440: 0x0040, 0x441: 0x0040, 0x442: 0x0040, 0x443: 0x0040, 0x444: 0x0040, 0x445: 0x0040, 0x446: 0x0018, 0x447: 0x0018, 0x448: 0x0018, 0x449: 0x0018, 0x44a: 0x0018, 0x44b: 0x0018, 0x44c: 0x0018, 0x44d: 0x0018, 0x44e: 0x0018, 0x44f: 0x0018, 0x450: 0x1308, 0x451: 0x1308, 0x452: 0x1308, 0x453: 0x1308, 0x454: 0x1308, 0x455: 0x1308, 0x456: 0x1308, 0x457: 0x1308, 0x458: 0x1308, 0x459: 0x1308, 0x45a: 0x1308, 0x45b: 0x0018, 0x45c: 0x0340, 0x45d: 0x0040, 0x45e: 0x0018, 0x45f: 0x0018, 0x460: 0x0208, 0x461: 0x0008, 0x462: 0x0408, 0x463: 0x0408, 0x464: 0x0408, 0x465: 0x0408, 0x466: 0x0208, 0x467: 0x0408, 0x468: 0x0208, 0x469: 0x0408, 0x46a: 0x0208, 0x46b: 0x0208, 0x46c: 0x0208, 0x46d: 0x0208, 0x46e: 0x0208, 0x46f: 0x0408, 0x470: 0x0408, 0x471: 0x0408, 0x472: 0x0408, 0x473: 0x0208, 0x474: 0x0208, 0x475: 0x0208, 0x476: 0x0208, 0x477: 0x0208, 0x478: 0x0208, 0x479: 0x0208, 0x47a: 0x0208, 0x47b: 0x0208, 0x47c: 0x0208, 0x47d: 0x0208, 0x47e: 0x0208, 0x47f: 0x0208, // Block 0x12, offset 0x480 0x480: 0x0408, 0x481: 0x0208, 0x482: 0x0208, 0x483: 0x0408, 0x484: 0x0408, 0x485: 0x0408, 0x486: 0x0408, 0x487: 0x0408, 0x488: 0x0408, 0x489: 0x0408, 0x48a: 0x0408, 0x48b: 0x0408, 0x48c: 0x0208, 0x48d: 0x0408, 0x48e: 0x0208, 0x48f: 0x0408, 0x490: 0x0208, 0x491: 0x0208, 0x492: 0x0408, 0x493: 0x0408, 0x494: 0x0018, 0x495: 0x0408, 0x496: 0x1308, 0x497: 0x1308, 0x498: 0x1308, 0x499: 0x1308, 0x49a: 0x1308, 0x49b: 0x1308, 0x49c: 0x1308, 0x49d: 0x0040, 0x49e: 0x0018, 0x49f: 0x1308, 0x4a0: 0x1308, 0x4a1: 0x1308, 0x4a2: 0x1308, 0x4a3: 0x1308, 0x4a4: 0x1308, 0x4a5: 0x0008, 0x4a6: 0x0008, 0x4a7: 0x1308, 0x4a8: 0x1308, 0x4a9: 0x0018, 0x4aa: 0x1308, 0x4ab: 0x1308, 0x4ac: 0x1308, 0x4ad: 0x1308, 0x4ae: 0x0408, 0x4af: 0x0408, 0x4b0: 0x0008, 0x4b1: 0x0008, 0x4b2: 0x0008, 0x4b3: 0x0008, 0x4b4: 0x0008, 0x4b5: 0x0008, 0x4b6: 0x0008, 0x4b7: 0x0008, 0x4b8: 0x0008, 0x4b9: 0x0008, 0x4ba: 0x0208, 0x4bb: 0x0208, 0x4bc: 0x0208, 0x4bd: 0x0008, 0x4be: 0x0008, 0x4bf: 0x0208, // Block 0x13, offset 0x4c0 0x4c0: 0x0018, 0x4c1: 0x0018, 0x4c2: 0x0018, 0x4c3: 0x0018, 0x4c4: 0x0018, 0x4c5: 0x0018, 0x4c6: 0x0018, 0x4c7: 0x0018, 0x4c8: 0x0018, 0x4c9: 0x0018, 0x4ca: 0x0018, 0x4cb: 0x0018, 0x4cc: 0x0018, 0x4cd: 0x0018, 0x4ce: 0x0040, 0x4cf: 0x0340, 0x4d0: 0x0408, 0x4d1: 0x1308, 0x4d2: 0x0208, 0x4d3: 0x0208, 0x4d4: 0x0208, 0x4d5: 0x0408, 0x4d6: 0x0408, 0x4d7: 0x0408, 0x4d8: 0x0408, 0x4d9: 0x0408, 0x4da: 0x0208, 0x4db: 0x0208, 0x4dc: 0x0208, 0x4dd: 0x0208, 0x4de: 0x0408, 0x4df: 0x0208, 0x4e0: 0x0208, 0x4e1: 0x0208, 0x4e2: 0x0208, 0x4e3: 0x0208, 0x4e4: 0x0208, 0x4e5: 0x0208, 0x4e6: 0x0208, 0x4e7: 0x0208, 0x4e8: 0x0408, 0x4e9: 0x0208, 0x4ea: 0x0408, 0x4eb: 0x0208, 0x4ec: 0x0408, 0x4ed: 0x0208, 0x4ee: 0x0208, 0x4ef: 0x0408, 0x4f0: 0x1308, 0x4f1: 0x1308, 0x4f2: 0x1308, 0x4f3: 0x1308, 0x4f4: 0x1308, 0x4f5: 0x1308, 0x4f6: 0x1308, 0x4f7: 0x1308, 0x4f8: 0x1308, 0x4f9: 0x1308, 0x4fa: 0x1308, 0x4fb: 0x1308, 0x4fc: 0x1308, 0x4fd: 0x1308, 0x4fe: 0x1308, 0x4ff: 0x1308, // Block 0x14, offset 0x500 0x500: 0x1008, 0x501: 0x1308, 0x502: 0x1308, 0x503: 0x1308, 0x504: 0x1308, 0x505: 0x1308, 0x506: 0x1308, 0x507: 0x1308, 0x508: 0x1308, 0x509: 0x1008, 0x50a: 0x1008, 0x50b: 0x1008, 0x50c: 0x1008, 0x50d: 0x1b08, 0x50e: 0x1008, 0x50f: 0x1008, 0x510: 0x0008, 0x511: 0x1308, 0x512: 0x1308, 0x513: 0x1308, 0x514: 0x1308, 0x515: 0x1308, 0x516: 0x1308, 0x517: 0x1308, 0x518: 0x04c9, 0x519: 0x0501, 0x51a: 0x0539, 0x51b: 0x0571, 0x51c: 0x05a9, 0x51d: 0x05e1, 0x51e: 0x0619, 0x51f: 0x0651, 0x520: 0x0008, 0x521: 0x0008, 0x522: 0x1308, 0x523: 0x1308, 0x524: 0x0018, 0x525: 0x0018, 0x526: 0x0008, 0x527: 0x0008, 0x528: 0x0008, 0x529: 0x0008, 0x52a: 0x0008, 0x52b: 0x0008, 0x52c: 0x0008, 0x52d: 0x0008, 0x52e: 0x0008, 0x52f: 0x0008, 0x530: 0x0018, 0x531: 0x0008, 0x532: 0x0008, 0x533: 0x0008, 0x534: 0x0008, 0x535: 0x0008, 0x536: 0x0008, 0x537: 0x0008, 0x538: 0x0008, 0x539: 0x0008, 0x53a: 0x0008, 0x53b: 0x0008, 0x53c: 0x0008, 0x53d: 0x0008, 0x53e: 0x0008, 0x53f: 0x0008, // Block 0x15, offset 0x540 0x540: 0x0008, 0x541: 0x1308, 0x542: 0x1008, 0x543: 0x1008, 0x544: 0x0040, 0x545: 0x0008, 0x546: 0x0008, 0x547: 0x0008, 0x548: 0x0008, 0x549: 0x0008, 0x54a: 0x0008, 0x54b: 0x0008, 0x54c: 0x0008, 0x54d: 0x0040, 0x54e: 0x0040, 0x54f: 0x0008, 0x550: 0x0008, 0x551: 0x0040, 0x552: 0x0040, 0x553: 0x0008, 0x554: 0x0008, 0x555: 0x0008, 0x556: 0x0008, 0x557: 0x0008, 0x558: 0x0008, 0x559: 0x0008, 0x55a: 0x0008, 0x55b: 0x0008, 0x55c: 0x0008, 0x55d: 0x0008, 0x55e: 0x0008, 0x55f: 0x0008, 0x560: 0x0008, 0x561: 0x0008, 0x562: 0x0008, 0x563: 0x0008, 0x564: 0x0008, 0x565: 0x0008, 0x566: 0x0008, 0x567: 0x0008, 0x568: 0x0008, 0x569: 0x0040, 0x56a: 0x0008, 0x56b: 0x0008, 0x56c: 0x0008, 0x56d: 0x0008, 0x56e: 0x0008, 0x56f: 0x0008, 0x570: 0x0008, 0x571: 0x0040, 0x572: 0x0008, 0x573: 0x0040, 0x574: 0x0040, 0x575: 0x0040, 0x576: 0x0008, 0x577: 0x0008, 0x578: 0x0008, 0x579: 0x0008, 0x57a: 0x0040, 0x57b: 0x0040, 0x57c: 0x1308, 0x57d: 0x0008, 0x57e: 0x1008, 0x57f: 0x1008, // Block 0x16, offset 0x580 0x580: 0x1008, 0x581: 0x1308, 0x582: 0x1308, 0x583: 0x1308, 0x584: 0x1308, 0x585: 0x0040, 0x586: 0x0040, 0x587: 0x1008, 0x588: 0x1008, 0x589: 0x0040, 0x58a: 0x0040, 0x58b: 0x1008, 0x58c: 0x1008, 0x58d: 0x1b08, 0x58e: 0x0008, 0x58f: 0x0040, 0x590: 0x0040, 0x591: 0x0040, 0x592: 0x0040, 0x593: 0x0040, 0x594: 0x0040, 0x595: 0x0040, 0x596: 0x0040, 0x597: 0x1008, 0x598: 0x0040, 0x599: 0x0040, 0x59a: 0x0040, 0x59b: 0x0040, 0x59c: 0x0689, 0x59d: 0x06c1, 0x59e: 0x0040, 0x59f: 0x06f9, 0x5a0: 0x0008, 0x5a1: 0x0008, 0x5a2: 0x1308, 0x5a3: 0x1308, 0x5a4: 0x0040, 0x5a5: 0x0040, 0x5a6: 0x0008, 0x5a7: 0x0008, 0x5a8: 0x0008, 0x5a9: 0x0008, 0x5aa: 0x0008, 0x5ab: 0x0008, 0x5ac: 0x0008, 0x5ad: 0x0008, 0x5ae: 0x0008, 0x5af: 0x0008, 0x5b0: 0x0008, 0x5b1: 0x0008, 0x5b2: 0x0018, 0x5b3: 0x0018, 0x5b4: 0x0018, 0x5b5: 0x0018, 0x5b6: 0x0018, 0x5b7: 0x0018, 0x5b8: 0x0018, 0x5b9: 0x0018, 0x5ba: 0x0018, 0x5bb: 0x0018, 0x5bc: 0x0040, 0x5bd: 0x0040, 0x5be: 0x0040, 0x5bf: 0x0040, // Block 0x17, offset 0x5c0 0x5c0: 0x0040, 0x5c1: 0x1308, 0x5c2: 0x1308, 0x5c3: 0x1008, 0x5c4: 0x0040, 0x5c5: 0x0008, 0x5c6: 0x0008, 0x5c7: 0x0008, 0x5c8: 0x0008, 0x5c9: 0x0008, 0x5ca: 0x0008, 0x5cb: 0x0040, 0x5cc: 0x0040, 0x5cd: 0x0040, 0x5ce: 0x0040, 0x5cf: 0x0008, 0x5d0: 0x0008, 0x5d1: 0x0040, 0x5d2: 0x0040, 0x5d3: 0x0008, 0x5d4: 0x0008, 0x5d5: 0x0008, 0x5d6: 0x0008, 0x5d7: 0x0008, 0x5d8: 0x0008, 0x5d9: 0x0008, 0x5da: 0x0008, 0x5db: 0x0008, 0x5dc: 0x0008, 0x5dd: 0x0008, 0x5de: 0x0008, 0x5df: 0x0008, 0x5e0: 0x0008, 0x5e1: 0x0008, 0x5e2: 0x0008, 0x5e3: 0x0008, 0x5e4: 0x0008, 0x5e5: 0x0008, 0x5e6: 0x0008, 0x5e7: 0x0008, 0x5e8: 0x0008, 0x5e9: 0x0040, 0x5ea: 0x0008, 0x5eb: 0x0008, 0x5ec: 0x0008, 0x5ed: 0x0008, 0x5ee: 0x0008, 0x5ef: 0x0008, 0x5f0: 0x0008, 0x5f1: 0x0040, 0x5f2: 0x0008, 0x5f3: 0x0731, 0x5f4: 0x0040, 0x5f5: 0x0008, 0x5f6: 0x0769, 0x5f7: 0x0040, 0x5f8: 0x0008, 0x5f9: 0x0008, 0x5fa: 0x0040, 0x5fb: 0x0040, 0x5fc: 0x1308, 0x5fd: 0x0040, 0x5fe: 0x1008, 0x5ff: 0x1008, // Block 0x18, offset 0x600 0x600: 0x1008, 0x601: 0x1308, 0x602: 0x1308, 0x603: 0x0040, 0x604: 0x0040, 0x605: 0x0040, 0x606: 0x0040, 0x607: 0x1308, 0x608: 0x1308, 0x609: 0x0040, 0x60a: 0x0040, 0x60b: 0x1308, 0x60c: 0x1308, 0x60d: 0x1b08, 0x60e: 0x0040, 0x60f: 0x0040, 0x610: 0x0040, 0x611: 0x1308, 0x612: 0x0040, 0x613: 0x0040, 0x614: 0x0040, 0x615: 0x0040, 0x616: 0x0040, 0x617: 0x0040, 0x618: 0x0040, 0x619: 0x07a1, 0x61a: 0x07d9, 0x61b: 0x0811, 0x61c: 0x0008, 0x61d: 0x0040, 0x61e: 0x0849, 0x61f: 0x0040, 0x620: 0x0040, 0x621: 0x0040, 0x622: 0x0040, 0x623: 0x0040, 0x624: 0x0040, 0x625: 0x0040, 0x626: 0x0008, 0x627: 0x0008, 0x628: 0x0008, 0x629: 0x0008, 0x62a: 0x0008, 0x62b: 0x0008, 0x62c: 0x0008, 0x62d: 0x0008, 0x62e: 0x0008, 0x62f: 0x0008, 0x630: 0x1308, 0x631: 0x1308, 0x632: 0x0008, 0x633: 0x0008, 0x634: 0x0008, 0x635: 0x1308, 0x636: 0x0040, 0x637: 0x0040, 0x638: 0x0040, 0x639: 0x0040, 0x63a: 0x0040, 0x63b: 0x0040, 0x63c: 0x0040, 0x63d: 0x0040, 0x63e: 0x0040, 0x63f: 0x0040, // Block 0x19, offset 0x640 0x640: 0x0040, 0x641: 0x1308, 0x642: 0x1308, 0x643: 0x1008, 0x644: 0x0040, 0x645: 0x0008, 0x646: 0x0008, 0x647: 0x0008, 0x648: 0x0008, 0x649: 0x0008, 0x64a: 0x0008, 0x64b: 0x0008, 0x64c: 0x0008, 0x64d: 0x0008, 0x64e: 0x0040, 0x64f: 0x0008, 0x650: 0x0008, 0x651: 0x0008, 0x652: 0x0040, 0x653: 0x0008, 0x654: 0x0008, 0x655: 0x0008, 0x656: 0x0008, 0x657: 0x0008, 0x658: 0x0008, 0x659: 0x0008, 0x65a: 0x0008, 0x65b: 0x0008, 0x65c: 0x0008, 0x65d: 0x0008, 0x65e: 0x0008, 0x65f: 0x0008, 0x660: 0x0008, 0x661: 0x0008, 0x662: 0x0008, 0x663: 0x0008, 0x664: 0x0008, 0x665: 0x0008, 0x666: 0x0008, 0x667: 0x0008, 0x668: 0x0008, 0x669: 0x0040, 0x66a: 0x0008, 0x66b: 0x0008, 0x66c: 0x0008, 0x66d: 0x0008, 0x66e: 0x0008, 0x66f: 0x0008, 0x670: 0x0008, 0x671: 0x0040, 0x672: 0x0008, 0x673: 0x0008, 0x674: 0x0040, 0x675: 0x0008, 0x676: 0x0008, 0x677: 0x0008, 0x678: 0x0008, 0x679: 0x0008, 0x67a: 0x0040, 0x67b: 0x0040, 0x67c: 0x1308, 0x67d: 0x0008, 0x67e: 0x1008, 0x67f: 0x1008, // Block 0x1a, offset 0x680 0x680: 0x1008, 0x681: 0x1308, 0x682: 0x1308, 0x683: 0x1308, 0x684: 0x1308, 0x685: 0x1308, 0x686: 0x0040, 0x687: 0x1308, 0x688: 0x1308, 0x689: 0x1008, 0x68a: 0x0040, 0x68b: 0x1008, 0x68c: 0x1008, 0x68d: 0x1b08, 0x68e: 0x0040, 0x68f: 0x0040, 0x690: 0x0008, 0x691: 0x0040, 0x692: 0x0040, 0x693: 0x0040, 0x694: 0x0040, 0x695: 0x0040, 0x696: 0x0040, 0x697: 0x0040, 0x698: 0x0040, 0x699: 0x0040, 0x69a: 0x0040, 0x69b: 0x0040, 0x69c: 0x0040, 0x69d: 0x0040, 0x69e: 0x0040, 0x69f: 0x0040, 0x6a0: 0x0008, 0x6a1: 0x0008, 0x6a2: 0x1308, 0x6a3: 0x1308, 0x6a4: 0x0040, 0x6a5: 0x0040, 0x6a6: 0x0008, 0x6a7: 0x0008, 0x6a8: 0x0008, 0x6a9: 0x0008, 0x6aa: 0x0008, 0x6ab: 0x0008, 0x6ac: 0x0008, 0x6ad: 0x0008, 0x6ae: 0x0008, 0x6af: 0x0008, 0x6b0: 0x0018, 0x6b1: 0x0018, 0x6b2: 0x0040, 0x6b3: 0x0040, 0x6b4: 0x0040, 0x6b5: 0x0040, 0x6b6: 0x0040, 0x6b7: 0x0040, 0x6b8: 0x0040, 0x6b9: 0x0008, 0x6ba: 0x0040, 0x6bb: 0x0040, 0x6bc: 0x0040, 0x6bd: 0x0040, 0x6be: 0x0040, 0x6bf: 0x0040, // Block 0x1b, offset 0x6c0 0x6c0: 0x0040, 0x6c1: 0x1308, 0x6c2: 0x1008, 0x6c3: 0x1008, 0x6c4: 0x0040, 0x6c5: 0x0008, 0x6c6: 0x0008, 0x6c7: 0x0008, 0x6c8: 0x0008, 0x6c9: 0x0008, 0x6ca: 0x0008, 0x6cb: 0x0008, 0x6cc: 0x0008, 0x6cd: 0x0040, 0x6ce: 0x0040, 0x6cf: 0x0008, 0x6d0: 0x0008, 0x6d1: 0x0040, 0x6d2: 0x0040, 0x6d3: 0x0008, 0x6d4: 0x0008, 0x6d5: 0x0008, 0x6d6: 0x0008, 0x6d7: 0x0008, 0x6d8: 0x0008, 0x6d9: 0x0008, 0x6da: 0x0008, 0x6db: 0x0008, 0x6dc: 0x0008, 0x6dd: 0x0008, 0x6de: 0x0008, 0x6df: 0x0008, 0x6e0: 0x0008, 0x6e1: 0x0008, 0x6e2: 0x0008, 0x6e3: 0x0008, 0x6e4: 0x0008, 0x6e5: 0x0008, 0x6e6: 0x0008, 0x6e7: 0x0008, 0x6e8: 0x0008, 0x6e9: 0x0040, 0x6ea: 0x0008, 0x6eb: 0x0008, 0x6ec: 0x0008, 0x6ed: 0x0008, 0x6ee: 0x0008, 0x6ef: 0x0008, 0x6f0: 0x0008, 0x6f1: 0x0040, 0x6f2: 0x0008, 0x6f3: 0x0008, 0x6f4: 0x0040, 0x6f5: 0x0008, 0x6f6: 0x0008, 0x6f7: 0x0008, 0x6f8: 0x0008, 0x6f9: 0x0008, 0x6fa: 0x0040, 0x6fb: 0x0040, 0x6fc: 0x1308, 0x6fd: 0x0008, 0x6fe: 0x1008, 0x6ff: 0x1308, // Block 0x1c, offset 0x700 0x700: 0x1008, 0x701: 0x1308, 0x702: 0x1308, 0x703: 0x1308, 0x704: 0x1308, 0x705: 0x0040, 0x706: 0x0040, 0x707: 0x1008, 0x708: 0x1008, 0x709: 0x0040, 0x70a: 0x0040, 0x70b: 0x1008, 0x70c: 0x1008, 0x70d: 0x1b08, 0x70e: 0x0040, 0x70f: 0x0040, 0x710: 0x0040, 0x711: 0x0040, 0x712: 0x0040, 0x713: 0x0040, 0x714: 0x0040, 0x715: 0x0040, 0x716: 0x1308, 0x717: 0x1008, 0x718: 0x0040, 0x719: 0x0040, 0x71a: 0x0040, 0x71b: 0x0040, 0x71c: 0x0881, 0x71d: 0x08b9, 0x71e: 0x0040, 0x71f: 0x0008, 0x720: 0x0008, 0x721: 0x0008, 0x722: 0x1308, 0x723: 0x1308, 0x724: 0x0040, 0x725: 0x0040, 0x726: 0x0008, 0x727: 0x0008, 0x728: 0x0008, 0x729: 0x0008, 0x72a: 0x0008, 0x72b: 0x0008, 0x72c: 0x0008, 0x72d: 0x0008, 0x72e: 0x0008, 0x72f: 0x0008, 0x730: 0x0018, 0x731: 0x0008, 0x732: 0x0018, 0x733: 0x0018, 0x734: 0x0018, 0x735: 0x0018, 0x736: 0x0018, 0x737: 0x0018, 0x738: 0x0040, 0x739: 0x0040, 0x73a: 0x0040, 0x73b: 0x0040, 0x73c: 0x0040, 0x73d: 0x0040, 0x73e: 0x0040, 0x73f: 0x0040, // Block 0x1d, offset 0x740 0x740: 0x0040, 0x741: 0x0040, 0x742: 0x1308, 0x743: 0x0008, 0x744: 0x0040, 0x745: 0x0008, 0x746: 0x0008, 0x747: 0x0008, 0x748: 0x0008, 0x749: 0x0008, 0x74a: 0x0008, 0x74b: 0x0040, 0x74c: 0x0040, 0x74d: 0x0040, 0x74e: 0x0008, 0x74f: 0x0008, 0x750: 0x0008, 0x751: 0x0040, 0x752: 0x0008, 0x753: 0x0008, 0x754: 0x0008, 0x755: 0x0008, 0x756: 0x0040, 0x757: 0x0040, 0x758: 0x0040, 0x759: 0x0008, 0x75a: 0x0008, 0x75b: 0x0040, 0x75c: 0x0008, 0x75d: 0x0040, 0x75e: 0x0008, 0x75f: 0x0008, 0x760: 0x0040, 0x761: 0x0040, 0x762: 0x0040, 0x763: 0x0008, 0x764: 0x0008, 0x765: 0x0040, 0x766: 0x0040, 0x767: 0x0040, 0x768: 0x0008, 0x769: 0x0008, 0x76a: 0x0008, 0x76b: 0x0040, 0x76c: 0x0040, 0x76d: 0x0040, 0x76e: 0x0008, 0x76f: 0x0008, 0x770: 0x0008, 0x771: 0x0008, 0x772: 0x0008, 0x773: 0x0008, 0x774: 0x0008, 0x775: 0x0008, 0x776: 0x0008, 0x777: 0x0008, 0x778: 0x0008, 0x779: 0x0008, 0x77a: 0x0040, 0x77b: 0x0040, 0x77c: 0x0040, 0x77d: 0x0040, 0x77e: 0x1008, 0x77f: 0x1008, // Block 0x1e, offset 0x780 0x780: 0x1308, 0x781: 0x1008, 0x782: 0x1008, 0x783: 0x1008, 0x784: 0x1008, 0x785: 0x0040, 0x786: 0x1308, 0x787: 0x1308, 0x788: 0x1308, 0x789: 0x0040, 0x78a: 0x1308, 0x78b: 0x1308, 0x78c: 0x1308, 0x78d: 0x1b08, 0x78e: 0x0040, 0x78f: 0x0040, 0x790: 0x0040, 0x791: 0x0040, 0x792: 0x0040, 0x793: 0x0040, 0x794: 0x0040, 0x795: 0x1308, 0x796: 0x1308, 0x797: 0x0040, 0x798: 0x0008, 0x799: 0x0008, 0x79a: 0x0008, 0x79b: 0x0040, 0x79c: 0x0040, 0x79d: 0x0040, 0x79e: 0x0040, 0x79f: 0x0040, 0x7a0: 0x0008, 0x7a1: 0x0008, 0x7a2: 0x1308, 0x7a3: 0x1308, 0x7a4: 0x0040, 0x7a5: 0x0040, 0x7a6: 0x0008, 0x7a7: 0x0008, 0x7a8: 0x0008, 0x7a9: 0x0008, 0x7aa: 0x0008, 0x7ab: 0x0008, 0x7ac: 0x0008, 0x7ad: 0x0008, 0x7ae: 0x0008, 0x7af: 0x0008, 0x7b0: 0x0040, 0x7b1: 0x0040, 0x7b2: 0x0040, 0x7b3: 0x0040, 0x7b4: 0x0040, 0x7b5: 0x0040, 0x7b6: 0x0040, 0x7b7: 0x0040, 0x7b8: 0x0018, 0x7b9: 0x0018, 0x7ba: 0x0018, 0x7bb: 0x0018, 0x7bc: 0x0018, 0x7bd: 0x0018, 0x7be: 0x0018, 0x7bf: 0x0018, // Block 0x1f, offset 0x7c0 0x7c0: 0x0008, 0x7c1: 0x1308, 0x7c2: 0x1008, 0x7c3: 0x1008, 0x7c4: 0x0040, 0x7c5: 0x0008, 0x7c6: 0x0008, 0x7c7: 0x0008, 0x7c8: 0x0008, 0x7c9: 0x0008, 0x7ca: 0x0008, 0x7cb: 0x0008, 0x7cc: 0x0008, 0x7cd: 0x0040, 0x7ce: 0x0008, 0x7cf: 0x0008, 0x7d0: 0x0008, 0x7d1: 0x0040, 0x7d2: 0x0008, 0x7d3: 0x0008, 0x7d4: 0x0008, 0x7d5: 0x0008, 0x7d6: 0x0008, 0x7d7: 0x0008, 0x7d8: 0x0008, 0x7d9: 0x0008, 0x7da: 0x0008, 0x7db: 0x0008, 0x7dc: 0x0008, 0x7dd: 0x0008, 0x7de: 0x0008, 0x7df: 0x0008, 0x7e0: 0x0008, 0x7e1: 0x0008, 0x7e2: 0x0008, 0x7e3: 0x0008, 0x7e4: 0x0008, 0x7e5: 0x0008, 0x7e6: 0x0008, 0x7e7: 0x0008, 0x7e8: 0x0008, 0x7e9: 0x0040, 0x7ea: 0x0008, 0x7eb: 0x0008, 0x7ec: 0x0008, 0x7ed: 0x0008, 0x7ee: 0x0008, 0x7ef: 0x0008, 0x7f0: 0x0008, 0x7f1: 0x0008, 0x7f2: 0x0008, 0x7f3: 0x0008, 0x7f4: 0x0040, 0x7f5: 0x0008, 0x7f6: 0x0008, 0x7f7: 0x0008, 0x7f8: 0x0008, 0x7f9: 0x0008, 0x7fa: 0x0040, 0x7fb: 0x0040, 0x7fc: 0x1308, 0x7fd: 0x0008, 0x7fe: 0x1008, 0x7ff: 0x1308, // Block 0x20, offset 0x800 0x800: 0x1008, 0x801: 0x1008, 0x802: 0x1008, 0x803: 0x1008, 0x804: 0x1008, 0x805: 0x0040, 0x806: 0x1308, 0x807: 0x1008, 0x808: 0x1008, 0x809: 0x0040, 0x80a: 0x1008, 0x80b: 0x1008, 0x80c: 0x1308, 0x80d: 0x1b08, 0x80e: 0x0040, 0x80f: 0x0040, 0x810: 0x0040, 0x811: 0x0040, 0x812: 0x0040, 0x813: 0x0040, 0x814: 0x0040, 0x815: 0x1008, 0x816: 0x1008, 0x817: 0x0040, 0x818: 0x0040, 0x819: 0x0040, 0x81a: 0x0040, 0x81b: 0x0040, 0x81c: 0x0040, 0x81d: 0x0040, 0x81e: 0x0008, 0x81f: 0x0040, 0x820: 0x0008, 0x821: 0x0008, 0x822: 0x1308, 0x823: 0x1308, 0x824: 0x0040, 0x825: 0x0040, 0x826: 0x0008, 0x827: 0x0008, 0x828: 0x0008, 0x829: 0x0008, 0x82a: 0x0008, 0x82b: 0x0008, 0x82c: 0x0008, 0x82d: 0x0008, 0x82e: 0x0008, 0x82f: 0x0008, 0x830: 0x0040, 0x831: 0x0008, 0x832: 0x0008, 0x833: 0x0040, 0x834: 0x0040, 0x835: 0x0040, 0x836: 0x0040, 0x837: 0x0040, 0x838: 0x0040, 0x839: 0x0040, 0x83a: 0x0040, 0x83b: 0x0040, 0x83c: 0x0040, 0x83d: 0x0040, 0x83e: 0x0040, 0x83f: 0x0040, // Block 0x21, offset 0x840 0x840: 0x1008, 0x841: 0x1308, 0x842: 0x1308, 0x843: 0x1308, 0x844: 0x1308, 0x845: 0x0040, 0x846: 0x1008, 0x847: 0x1008, 0x848: 0x1008, 0x849: 0x0040, 0x84a: 0x1008, 0x84b: 0x1008, 0x84c: 0x1008, 0x84d: 0x1b08, 0x84e: 0x0008, 0x84f: 0x0018, 0x850: 0x0040, 0x851: 0x0040, 0x852: 0x0040, 0x853: 0x0040, 0x854: 0x0008, 0x855: 0x0008, 0x856: 0x0008, 0x857: 0x1008, 0x858: 0x0018, 0x859: 0x0018, 0x85a: 0x0018, 0x85b: 0x0018, 0x85c: 0x0018, 0x85d: 0x0018, 0x85e: 0x0018, 0x85f: 0x0008, 0x860: 0x0008, 0x861: 0x0008, 0x862: 0x1308, 0x863: 0x1308, 0x864: 0x0040, 0x865: 0x0040, 0x866: 0x0008, 0x867: 0x0008, 0x868: 0x0008, 0x869: 0x0008, 0x86a: 0x0008, 0x86b: 0x0008, 0x86c: 0x0008, 0x86d: 0x0008, 0x86e: 0x0008, 0x86f: 0x0008, 0x870: 0x0018, 0x871: 0x0018, 0x872: 0x0018, 0x873: 0x0018, 0x874: 0x0018, 0x875: 0x0018, 0x876: 0x0018, 0x877: 0x0018, 0x878: 0x0018, 0x879: 0x0018, 0x87a: 0x0008, 0x87b: 0x0008, 0x87c: 0x0008, 0x87d: 0x0008, 0x87e: 0x0008, 0x87f: 0x0008, // Block 0x22, offset 0x880 0x880: 0x0040, 0x881: 0x0008, 0x882: 0x0008, 0x883: 0x0040, 0x884: 0x0008, 0x885: 0x0040, 0x886: 0x0040, 0x887: 0x0008, 0x888: 0x0008, 0x889: 0x0040, 0x88a: 0x0008, 0x88b: 0x0040, 0x88c: 0x0040, 0x88d: 0x0008, 0x88e: 0x0040, 0x88f: 0x0040, 0x890: 0x0040, 0x891: 0x0040, 0x892: 0x0040, 0x893: 0x0040, 0x894: 0x0008, 0x895: 0x0008, 0x896: 0x0008, 0x897: 0x0008, 0x898: 0x0040, 0x899: 0x0008, 0x89a: 0x0008, 0x89b: 0x0008, 0x89c: 0x0008, 0x89d: 0x0008, 0x89e: 0x0008, 0x89f: 0x0008, 0x8a0: 0x0040, 0x8a1: 0x0008, 0x8a2: 0x0008, 0x8a3: 0x0008, 0x8a4: 0x0040, 0x8a5: 0x0008, 0x8a6: 0x0040, 0x8a7: 0x0008, 0x8a8: 0x0040, 0x8a9: 0x0040, 0x8aa: 0x0008, 0x8ab: 0x0008, 0x8ac: 0x0040, 0x8ad: 0x0008, 0x8ae: 0x0008, 0x8af: 0x0008, 0x8b0: 0x0008, 0x8b1: 0x1308, 0x8b2: 0x0008, 0x8b3: 0x0929, 0x8b4: 0x1308, 0x8b5: 0x1308, 0x8b6: 0x1308, 0x8b7: 0x1308, 0x8b8: 0x1308, 0x8b9: 0x1308, 0x8ba: 0x0040, 0x8bb: 0x1308, 0x8bc: 0x1308, 0x8bd: 0x0008, 0x8be: 0x0040, 0x8bf: 0x0040, // Block 0x23, offset 0x8c0 0x8c0: 0x0008, 0x8c1: 0x0008, 0x8c2: 0x0008, 0x8c3: 0x09d1, 0x8c4: 0x0008, 0x8c5: 0x0008, 0x8c6: 0x0008, 0x8c7: 0x0008, 0x8c8: 0x0040, 0x8c9: 0x0008, 0x8ca: 0x0008, 0x8cb: 0x0008, 0x8cc: 0x0008, 0x8cd: 0x0a09, 0x8ce: 0x0008, 0x8cf: 0x0008, 0x8d0: 0x0008, 0x8d1: 0x0008, 0x8d2: 0x0a41, 0x8d3: 0x0008, 0x8d4: 0x0008, 0x8d5: 0x0008, 0x8d6: 0x0008, 0x8d7: 0x0a79, 0x8d8: 0x0008, 0x8d9: 0x0008, 0x8da: 0x0008, 0x8db: 0x0008, 0x8dc: 0x0ab1, 0x8dd: 0x0008, 0x8de: 0x0008, 0x8df: 0x0008, 0x8e0: 0x0008, 0x8e1: 0x0008, 0x8e2: 0x0008, 0x8e3: 0x0008, 0x8e4: 0x0008, 0x8e5: 0x0008, 0x8e6: 0x0008, 0x8e7: 0x0008, 0x8e8: 0x0008, 0x8e9: 0x0ae9, 0x8ea: 0x0008, 0x8eb: 0x0008, 0x8ec: 0x0008, 0x8ed: 0x0040, 0x8ee: 0x0040, 0x8ef: 0x0040, 0x8f0: 0x0040, 0x8f1: 0x1308, 0x8f2: 0x1308, 0x8f3: 0x0b21, 0x8f4: 0x1308, 0x8f5: 0x0b59, 0x8f6: 0x0b91, 0x8f7: 0x0bc9, 0x8f8: 0x0c19, 0x8f9: 0x0c51, 0x8fa: 0x1308, 0x8fb: 0x1308, 0x8fc: 0x1308, 0x8fd: 0x1308, 0x8fe: 0x1308, 0x8ff: 0x1008, // Block 0x24, offset 0x900 0x900: 0x1308, 0x901: 0x0ca1, 0x902: 0x1308, 0x903: 0x1308, 0x904: 0x1b08, 0x905: 0x0018, 0x906: 0x1308, 0x907: 0x1308, 0x908: 0x0008, 0x909: 0x0008, 0x90a: 0x0008, 0x90b: 0x0008, 0x90c: 0x0008, 0x90d: 0x1308, 0x90e: 0x1308, 0x90f: 0x1308, 0x910: 0x1308, 0x911: 0x1308, 0x912: 0x1308, 0x913: 0x0cd9, 0x914: 0x1308, 0x915: 0x1308, 0x916: 0x1308, 0x917: 0x1308, 0x918: 0x0040, 0x919: 0x1308, 0x91a: 0x1308, 0x91b: 0x1308, 0x91c: 0x1308, 0x91d: 0x0d11, 0x91e: 0x1308, 0x91f: 0x1308, 0x920: 0x1308, 0x921: 0x1308, 0x922: 0x0d49, 0x923: 0x1308, 0x924: 0x1308, 0x925: 0x1308, 0x926: 0x1308, 0x927: 0x0d81, 0x928: 0x1308, 0x929: 0x1308, 0x92a: 0x1308, 0x92b: 0x1308, 0x92c: 0x0db9, 0x92d: 0x1308, 0x92e: 0x1308, 0x92f: 0x1308, 0x930: 0x1308, 0x931: 0x1308, 0x932: 0x1308, 0x933: 0x1308, 0x934: 0x1308, 0x935: 0x1308, 0x936: 0x1308, 0x937: 0x1308, 0x938: 0x1308, 0x939: 0x0df1, 0x93a: 0x1308, 0x93b: 0x1308, 0x93c: 0x1308, 0x93d: 0x0040, 0x93e: 0x0018, 0x93f: 0x0018, // Block 0x25, offset 0x940 0x940: 0x0008, 0x941: 0x0008, 0x942: 0x0008, 0x943: 0x0008, 0x944: 0x0008, 0x945: 0x0008, 0x946: 0x0008, 0x947: 0x0008, 0x948: 0x0008, 0x949: 0x0008, 0x94a: 0x0008, 0x94b: 0x0008, 0x94c: 0x0008, 0x94d: 0x0008, 0x94e: 0x0008, 0x94f: 0x0008, 0x950: 0x0008, 0x951: 0x0008, 0x952: 0x0008, 0x953: 0x0008, 0x954: 0x0008, 0x955: 0x0008, 0x956: 0x0008, 0x957: 0x0008, 0x958: 0x0008, 0x959: 0x0008, 0x95a: 0x0008, 0x95b: 0x0008, 0x95c: 0x0008, 0x95d: 0x0008, 0x95e: 0x0008, 0x95f: 0x0008, 0x960: 0x0008, 0x961: 0x0008, 0x962: 0x0008, 0x963: 0x0008, 0x964: 0x0008, 0x965: 0x0008, 0x966: 0x0008, 0x967: 0x0008, 0x968: 0x0008, 0x969: 0x0008, 0x96a: 0x0008, 0x96b: 0x0008, 0x96c: 0x0039, 0x96d: 0x0ed1, 0x96e: 0x0ee9, 0x96f: 0x0008, 0x970: 0x0ef9, 0x971: 0x0f09, 0x972: 0x0f19, 0x973: 0x0f31, 0x974: 0x0249, 0x975: 0x0f41, 0x976: 0x0259, 0x977: 0x0f51, 0x978: 0x0359, 0x979: 0x0f61, 0x97a: 0x0f71, 0x97b: 0x0008, 0x97c: 0x00d9, 0x97d: 0x0f81, 0x97e: 0x0f99, 0x97f: 0x0269, // Block 0x26, offset 0x980 0x980: 0x0fa9, 0x981: 0x0fb9, 0x982: 0x0279, 0x983: 0x0039, 0x984: 0x0fc9, 0x985: 0x0fe1, 0x986: 0x059d, 0x987: 0x0ee9, 0x988: 0x0ef9, 0x989: 0x0f09, 0x98a: 0x0ff9, 0x98b: 0x1011, 0x98c: 0x1029, 0x98d: 0x0f31, 0x98e: 0x0008, 0x98f: 0x0f51, 0x990: 0x0f61, 0x991: 0x1041, 0x992: 0x00d9, 0x993: 0x1059, 0x994: 0x05b5, 0x995: 0x05b5, 0x996: 0x0f99, 0x997: 0x0fa9, 0x998: 0x0fb9, 0x999: 0x059d, 0x99a: 0x1071, 0x99b: 0x1089, 0x99c: 0x05cd, 0x99d: 0x1099, 0x99e: 0x10b1, 0x99f: 0x10c9, 0x9a0: 0x10e1, 0x9a1: 0x10f9, 0x9a2: 0x0f41, 0x9a3: 0x0269, 0x9a4: 0x0fb9, 0x9a5: 0x1089, 0x9a6: 0x1099, 0x9a7: 0x10b1, 0x9a8: 0x1111, 0x9a9: 0x10e1, 0x9aa: 0x10f9, 0x9ab: 0x0008, 0x9ac: 0x0008, 0x9ad: 0x0008, 0x9ae: 0x0008, 0x9af: 0x0008, 0x9b0: 0x0008, 0x9b1: 0x0008, 0x9b2: 0x0008, 0x9b3: 0x0008, 0x9b4: 0x0008, 0x9b5: 0x0008, 0x9b6: 0x0008, 0x9b7: 0x0008, 0x9b8: 0x1129, 0x9b9: 0x0008, 0x9ba: 0x0008, 0x9bb: 0x0008, 0x9bc: 0x0008, 0x9bd: 0x0008, 0x9be: 0x0008, 0x9bf: 0x0008, // Block 0x27, offset 0x9c0 0x9c0: 0x0008, 0x9c1: 0x0008, 0x9c2: 0x0008, 0x9c3: 0x0008, 0x9c4: 0x0008, 0x9c5: 0x0008, 0x9c6: 0x0008, 0x9c7: 0x0008, 0x9c8: 0x0008, 0x9c9: 0x0008, 0x9ca: 0x0008, 0x9cb: 0x0008, 0x9cc: 0x0008, 0x9cd: 0x0008, 0x9ce: 0x0008, 0x9cf: 0x0008, 0x9d0: 0x0008, 0x9d1: 0x0008, 0x9d2: 0x0008, 0x9d3: 0x0008, 0x9d4: 0x0008, 0x9d5: 0x0008, 0x9d6: 0x0008, 0x9d7: 0x0008, 0x9d8: 0x0008, 0x9d9: 0x0008, 0x9da: 0x0008, 0x9db: 0x1141, 0x9dc: 0x1159, 0x9dd: 0x1169, 0x9de: 0x1181, 0x9df: 0x1029, 0x9e0: 0x1199, 0x9e1: 0x11a9, 0x9e2: 0x11c1, 0x9e3: 0x11d9, 0x9e4: 0x11f1, 0x9e5: 0x1209, 0x9e6: 0x1221, 0x9e7: 0x05e5, 0x9e8: 0x1239, 0x9e9: 0x1251, 0x9ea: 0xe17d, 0x9eb: 0x1269, 0x9ec: 0x1281, 0x9ed: 0x1299, 0x9ee: 0x12b1, 0x9ef: 0x12c9, 0x9f0: 0x12e1, 0x9f1: 0x12f9, 0x9f2: 0x1311, 0x9f3: 0x1329, 0x9f4: 0x1341, 0x9f5: 0x1359, 0x9f6: 0x1371, 0x9f7: 0x1389, 0x9f8: 0x05fd, 0x9f9: 0x13a1, 0x9fa: 0x13b9, 0x9fb: 0x13d1, 0x9fc: 0x13e1, 0x9fd: 0x13f9, 0x9fe: 0x1411, 0x9ff: 0x1429, // Block 0x28, offset 0xa00 0xa00: 0xe00d, 0xa01: 0x0008, 0xa02: 0xe00d, 0xa03: 0x0008, 0xa04: 0xe00d, 0xa05: 0x0008, 0xa06: 0xe00d, 0xa07: 0x0008, 0xa08: 0xe00d, 0xa09: 0x0008, 0xa0a: 0xe00d, 0xa0b: 0x0008, 0xa0c: 0xe00d, 0xa0d: 0x0008, 0xa0e: 0xe00d, 0xa0f: 0x0008, 0xa10: 0xe00d, 0xa11: 0x0008, 0xa12: 0xe00d, 0xa13: 0x0008, 0xa14: 0xe00d, 0xa15: 0x0008, 0xa16: 0xe00d, 0xa17: 0x0008, 0xa18: 0xe00d, 0xa19: 0x0008, 0xa1a: 0xe00d, 0xa1b: 0x0008, 0xa1c: 0xe00d, 0xa1d: 0x0008, 0xa1e: 0xe00d, 0xa1f: 0x0008, 0xa20: 0xe00d, 0xa21: 0x0008, 0xa22: 0xe00d, 0xa23: 0x0008, 0xa24: 0xe00d, 0xa25: 0x0008, 0xa26: 0xe00d, 0xa27: 0x0008, 0xa28: 0xe00d, 0xa29: 0x0008, 0xa2a: 0xe00d, 0xa2b: 0x0008, 0xa2c: 0xe00d, 0xa2d: 0x0008, 0xa2e: 0xe00d, 0xa2f: 0x0008, 0xa30: 0xe00d, 0xa31: 0x0008, 0xa32: 0xe00d, 0xa33: 0x0008, 0xa34: 0xe00d, 0xa35: 0x0008, 0xa36: 0xe00d, 0xa37: 0x0008, 0xa38: 0xe00d, 0xa39: 0x0008, 0xa3a: 0xe00d, 0xa3b: 0x0008, 0xa3c: 0xe00d, 0xa3d: 0x0008, 0xa3e: 0xe00d, 0xa3f: 0x0008, // Block 0x29, offset 0xa40 0xa40: 0xe00d, 0xa41: 0x0008, 0xa42: 0xe00d, 0xa43: 0x0008, 0xa44: 0xe00d, 0xa45: 0x0008, 0xa46: 0xe00d, 0xa47: 0x0008, 0xa48: 0xe00d, 0xa49: 0x0008, 0xa4a: 0xe00d, 0xa4b: 0x0008, 0xa4c: 0xe00d, 0xa4d: 0x0008, 0xa4e: 0xe00d, 0xa4f: 0x0008, 0xa50: 0xe00d, 0xa51: 0x0008, 0xa52: 0xe00d, 0xa53: 0x0008, 0xa54: 0xe00d, 0xa55: 0x0008, 0xa56: 0x0008, 0xa57: 0x0008, 0xa58: 0x0008, 0xa59: 0x0008, 0xa5a: 0x0615, 0xa5b: 0x0635, 0xa5c: 0x0008, 0xa5d: 0x0008, 0xa5e: 0x1441, 0xa5f: 0x0008, 0xa60: 0xe00d, 0xa61: 0x0008, 0xa62: 0xe00d, 0xa63: 0x0008, 0xa64: 0xe00d, 0xa65: 0x0008, 0xa66: 0xe00d, 0xa67: 0x0008, 0xa68: 0xe00d, 0xa69: 0x0008, 0xa6a: 0xe00d, 0xa6b: 0x0008, 0xa6c: 0xe00d, 0xa6d: 0x0008, 0xa6e: 0xe00d, 0xa6f: 0x0008, 0xa70: 0xe00d, 0xa71: 0x0008, 0xa72: 0xe00d, 0xa73: 0x0008, 0xa74: 0xe00d, 0xa75: 0x0008, 0xa76: 0xe00d, 0xa77: 0x0008, 0xa78: 0xe00d, 0xa79: 0x0008, 0xa7a: 0xe00d, 0xa7b: 0x0008, 0xa7c: 0xe00d, 0xa7d: 0x0008, 0xa7e: 0xe00d, 0xa7f: 0x0008, // Block 0x2a, offset 0xa80 0xa80: 0x0008, 0xa81: 0x0008, 0xa82: 0x0008, 0xa83: 0x0008, 0xa84: 0x0008, 0xa85: 0x0008, 0xa86: 0x0040, 0xa87: 0x0040, 0xa88: 0xe045, 0xa89: 0xe045, 0xa8a: 0xe045, 0xa8b: 0xe045, 0xa8c: 0xe045, 0xa8d: 0xe045, 0xa8e: 0x0040, 0xa8f: 0x0040, 0xa90: 0x0008, 0xa91: 0x0008, 0xa92: 0x0008, 0xa93: 0x0008, 0xa94: 0x0008, 0xa95: 0x0008, 0xa96: 0x0008, 0xa97: 0x0008, 0xa98: 0x0040, 0xa99: 0xe045, 0xa9a: 0x0040, 0xa9b: 0xe045, 0xa9c: 0x0040, 0xa9d: 0xe045, 0xa9e: 0x0040, 0xa9f: 0xe045, 0xaa0: 0x0008, 0xaa1: 0x0008, 0xaa2: 0x0008, 0xaa3: 0x0008, 0xaa4: 0x0008, 0xaa5: 0x0008, 0xaa6: 0x0008, 0xaa7: 0x0008, 0xaa8: 0xe045, 0xaa9: 0xe045, 0xaaa: 0xe045, 0xaab: 0xe045, 0xaac: 0xe045, 0xaad: 0xe045, 0xaae: 0xe045, 0xaaf: 0xe045, 0xab0: 0x0008, 0xab1: 0x1459, 0xab2: 0x0008, 0xab3: 0x1471, 0xab4: 0x0008, 0xab5: 0x1489, 0xab6: 0x0008, 0xab7: 0x14a1, 0xab8: 0x0008, 0xab9: 0x14b9, 0xaba: 0x0008, 0xabb: 0x14d1, 0xabc: 0x0008, 0xabd: 0x14e9, 0xabe: 0x0040, 0xabf: 0x0040, // Block 0x2b, offset 0xac0 0xac0: 0x1501, 0xac1: 0x1531, 0xac2: 0x1561, 0xac3: 0x1591, 0xac4: 0x15c1, 0xac5: 0x15f1, 0xac6: 0x1621, 0xac7: 0x1651, 0xac8: 0x1501, 0xac9: 0x1531, 0xaca: 0x1561, 0xacb: 0x1591, 0xacc: 0x15c1, 0xacd: 0x15f1, 0xace: 0x1621, 0xacf: 0x1651, 0xad0: 0x1681, 0xad1: 0x16b1, 0xad2: 0x16e1, 0xad3: 0x1711, 0xad4: 0x1741, 0xad5: 0x1771, 0xad6: 0x17a1, 0xad7: 0x17d1, 0xad8: 0x1681, 0xad9: 0x16b1, 0xada: 0x16e1, 0xadb: 0x1711, 0xadc: 0x1741, 0xadd: 0x1771, 0xade: 0x17a1, 0xadf: 0x17d1, 0xae0: 0x1801, 0xae1: 0x1831, 0xae2: 0x1861, 0xae3: 0x1891, 0xae4: 0x18c1, 0xae5: 0x18f1, 0xae6: 0x1921, 0xae7: 0x1951, 0xae8: 0x1801, 0xae9: 0x1831, 0xaea: 0x1861, 0xaeb: 0x1891, 0xaec: 0x18c1, 0xaed: 0x18f1, 0xaee: 0x1921, 0xaef: 0x1951, 0xaf0: 0x0008, 0xaf1: 0x0008, 0xaf2: 0x1981, 0xaf3: 0x19b1, 0xaf4: 0x19d9, 0xaf5: 0x0040, 0xaf6: 0x0008, 0xaf7: 0x1a01, 0xaf8: 0xe045, 0xaf9: 0xe045, 0xafa: 0x064d, 0xafb: 0x1459, 0xafc: 0x19b1, 0xafd: 0x0666, 0xafe: 0x1a31, 0xaff: 0x0686, // Block 0x2c, offset 0xb00 0xb00: 0x06a6, 0xb01: 0x1a4a, 0xb02: 0x1a79, 0xb03: 0x1aa9, 0xb04: 0x1ad1, 0xb05: 0x0040, 0xb06: 0x0008, 0xb07: 0x1af9, 0xb08: 0x06c5, 0xb09: 0x1471, 0xb0a: 0x06dd, 0xb0b: 0x1489, 0xb0c: 0x1aa9, 0xb0d: 0x1b2a, 0xb0e: 0x1b5a, 0xb0f: 0x1b8a, 0xb10: 0x0008, 0xb11: 0x0008, 0xb12: 0x0008, 0xb13: 0x1bb9, 0xb14: 0x0040, 0xb15: 0x0040, 0xb16: 0x0008, 0xb17: 0x0008, 0xb18: 0xe045, 0xb19: 0xe045, 0xb1a: 0x06f5, 0xb1b: 0x14a1, 0xb1c: 0x0040, 0xb1d: 0x1bd2, 0xb1e: 0x1c02, 0xb1f: 0x1c32, 0xb20: 0x0008, 0xb21: 0x0008, 0xb22: 0x0008, 0xb23: 0x1c61, 0xb24: 0x0008, 0xb25: 0x0008, 0xb26: 0x0008, 0xb27: 0x0008, 0xb28: 0xe045, 0xb29: 0xe045, 0xb2a: 0x070d, 0xb2b: 0x14d1, 0xb2c: 0xe04d, 0xb2d: 0x1c7a, 0xb2e: 0x03d2, 0xb2f: 0x1caa, 0xb30: 0x0040, 0xb31: 0x0040, 0xb32: 0x1cb9, 0xb33: 0x1ce9, 0xb34: 0x1d11, 0xb35: 0x0040, 0xb36: 0x0008, 0xb37: 0x1d39, 0xb38: 0x0725, 0xb39: 0x14b9, 0xb3a: 0x0515, 0xb3b: 0x14e9, 0xb3c: 0x1ce9, 0xb3d: 0x073e, 0xb3e: 0x075e, 0xb3f: 0x0040, // Block 0x2d, offset 0xb40 0xb40: 0x000a, 0xb41: 0x000a, 0xb42: 0x000a, 0xb43: 0x000a, 0xb44: 0x000a, 0xb45: 0x000a, 0xb46: 0x000a, 0xb47: 0x000a, 0xb48: 0x000a, 0xb49: 0x000a, 0xb4a: 0x000a, 0xb4b: 0x03c0, 0xb4c: 0x0003, 0xb4d: 0x0003, 0xb4e: 0x0340, 0xb4f: 0x0340, 0xb50: 0x0018, 0xb51: 0xe00d, 0xb52: 0x0018, 0xb53: 0x0018, 0xb54: 0x0018, 0xb55: 0x0018, 0xb56: 0x0018, 0xb57: 0x077e, 0xb58: 0x0018, 0xb59: 0x0018, 0xb5a: 0x0018, 0xb5b: 0x0018, 0xb5c: 0x0018, 0xb5d: 0x0018, 0xb5e: 0x0018, 0xb5f: 0x0018, 0xb60: 0x0018, 0xb61: 0x0018, 0xb62: 0x0018, 0xb63: 0x0018, 0xb64: 0x0040, 0xb65: 0x0040, 0xb66: 0x0040, 0xb67: 0x0018, 0xb68: 0x0040, 0xb69: 0x0040, 0xb6a: 0x0340, 0xb6b: 0x0340, 0xb6c: 0x0340, 0xb6d: 0x0340, 0xb6e: 0x0340, 0xb6f: 0x000a, 0xb70: 0x0018, 0xb71: 0x0018, 0xb72: 0x0018, 0xb73: 0x1d69, 0xb74: 0x1da1, 0xb75: 0x0018, 0xb76: 0x1df1, 0xb77: 0x1e29, 0xb78: 0x0018, 0xb79: 0x0018, 0xb7a: 0x0018, 0xb7b: 0x0018, 0xb7c: 0x1e7a, 0xb7d: 0x0018, 0xb7e: 0x079e, 0xb7f: 0x0018, // Block 0x2e, offset 0xb80 0xb80: 0x0018, 0xb81: 0x0018, 0xb82: 0x0018, 0xb83: 0x0018, 0xb84: 0x0018, 0xb85: 0x0018, 0xb86: 0x0018, 0xb87: 0x1e92, 0xb88: 0x1eaa, 0xb89: 0x1ec2, 0xb8a: 0x0018, 0xb8b: 0x0018, 0xb8c: 0x0018, 0xb8d: 0x0018, 0xb8e: 0x0018, 0xb8f: 0x0018, 0xb90: 0x0018, 0xb91: 0x0018, 0xb92: 0x0018, 0xb93: 0x0018, 0xb94: 0x0018, 0xb95: 0x0018, 0xb96: 0x0018, 0xb97: 0x1ed9, 0xb98: 0x0018, 0xb99: 0x0018, 0xb9a: 0x0018, 0xb9b: 0x0018, 0xb9c: 0x0018, 0xb9d: 0x0018, 0xb9e: 0x0018, 0xb9f: 0x000a, 0xba0: 0x03c0, 0xba1: 0x0340, 0xba2: 0x0340, 0xba3: 0x0340, 0xba4: 0x03c0, 0xba5: 0x0040, 0xba6: 0x0040, 0xba7: 0x0040, 0xba8: 0x0040, 0xba9: 0x0040, 0xbaa: 0x0340, 0xbab: 0x0340, 0xbac: 0x0340, 0xbad: 0x0340, 0xbae: 0x0340, 0xbaf: 0x0340, 0xbb0: 0x1f41, 0xbb1: 0x0f41, 0xbb2: 0x0040, 0xbb3: 0x0040, 0xbb4: 0x1f51, 0xbb5: 0x1f61, 0xbb6: 0x1f71, 0xbb7: 0x1f81, 0xbb8: 0x1f91, 0xbb9: 0x1fa1, 0xbba: 0x1fb2, 0xbbb: 0x07bd, 0xbbc: 0x1fc2, 0xbbd: 0x1fd2, 0xbbe: 0x1fe2, 0xbbf: 0x0f71, // Block 0x2f, offset 0xbc0 0xbc0: 0x1f41, 0xbc1: 0x00c9, 0xbc2: 0x0069, 0xbc3: 0x0079, 0xbc4: 0x1f51, 0xbc5: 0x1f61, 0xbc6: 0x1f71, 0xbc7: 0x1f81, 0xbc8: 0x1f91, 0xbc9: 0x1fa1, 0xbca: 0x1fb2, 0xbcb: 0x07d5, 0xbcc: 0x1fc2, 0xbcd: 0x1fd2, 0xbce: 0x1fe2, 0xbcf: 0x0040, 0xbd0: 0x0039, 0xbd1: 0x0f09, 0xbd2: 0x00d9, 0xbd3: 0x0369, 0xbd4: 0x0ff9, 0xbd5: 0x0249, 0xbd6: 0x0f51, 0xbd7: 0x0359, 0xbd8: 0x0f61, 0xbd9: 0x0f71, 0xbda: 0x0f99, 0xbdb: 0x01d9, 0xbdc: 0x0fa9, 0xbdd: 0x0040, 0xbde: 0x0040, 0xbdf: 0x0040, 0xbe0: 0x0018, 0xbe1: 0x0018, 0xbe2: 0x0018, 0xbe3: 0x0018, 0xbe4: 0x0018, 0xbe5: 0x0018, 0xbe6: 0x0018, 0xbe7: 0x0018, 0xbe8: 0x1ff1, 0xbe9: 0x0018, 0xbea: 0x0018, 0xbeb: 0x0018, 0xbec: 0x0018, 0xbed: 0x0018, 0xbee: 0x0018, 0xbef: 0x0018, 0xbf0: 0x0018, 0xbf1: 0x0018, 0xbf2: 0x0018, 0xbf3: 0x0018, 0xbf4: 0x0018, 0xbf5: 0x0018, 0xbf6: 0x0018, 0xbf7: 0x0018, 0xbf8: 0x0018, 0xbf9: 0x0018, 0xbfa: 0x0018, 0xbfb: 0x0018, 0xbfc: 0x0018, 0xbfd: 0x0018, 0xbfe: 0x0018, 0xbff: 0x0040, // Block 0x30, offset 0xc00 0xc00: 0x07ee, 0xc01: 0x080e, 0xc02: 0x1159, 0xc03: 0x082d, 0xc04: 0x0018, 0xc05: 0x084e, 0xc06: 0x086e, 0xc07: 0x1011, 0xc08: 0x0018, 0xc09: 0x088d, 0xc0a: 0x0f31, 0xc0b: 0x0249, 0xc0c: 0x0249, 0xc0d: 0x0249, 0xc0e: 0x0249, 0xc0f: 0x2009, 0xc10: 0x0f41, 0xc11: 0x0f41, 0xc12: 0x0359, 0xc13: 0x0359, 0xc14: 0x0018, 0xc15: 0x0f71, 0xc16: 0x2021, 0xc17: 0x0018, 0xc18: 0x0018, 0xc19: 0x0f99, 0xc1a: 0x2039, 0xc1b: 0x0269, 0xc1c: 0x0269, 0xc1d: 0x0269, 0xc1e: 0x0018, 0xc1f: 0x0018, 0xc20: 0x2049, 0xc21: 0x08ad, 0xc22: 0x2061, 0xc23: 0x0018, 0xc24: 0x13d1, 0xc25: 0x0018, 0xc26: 0x2079, 0xc27: 0x0018, 0xc28: 0x13d1, 0xc29: 0x0018, 0xc2a: 0x0f51, 0xc2b: 0x2091, 0xc2c: 0x0ee9, 0xc2d: 0x1159, 0xc2e: 0x0018, 0xc2f: 0x0f09, 0xc30: 0x0f09, 0xc31: 0x1199, 0xc32: 0x0040, 0xc33: 0x0f61, 0xc34: 0x00d9, 0xc35: 0x20a9, 0xc36: 0x20c1, 0xc37: 0x20d9, 0xc38: 0x20f1, 0xc39: 0x0f41, 0xc3a: 0x0018, 0xc3b: 0x08cd, 0xc3c: 0x2109, 0xc3d: 0x10b1, 0xc3e: 0x10b1, 0xc3f: 0x2109, // Block 0x31, offset 0xc40 0xc40: 0x08ed, 0xc41: 0x0018, 0xc42: 0x0018, 0xc43: 0x0018, 0xc44: 0x0018, 0xc45: 0x0ef9, 0xc46: 0x0ef9, 0xc47: 0x0f09, 0xc48: 0x0f41, 0xc49: 0x0259, 0xc4a: 0x0018, 0xc4b: 0x0018, 0xc4c: 0x0018, 0xc4d: 0x0018, 0xc4e: 0x0008, 0xc4f: 0x0018, 0xc50: 0x2121, 0xc51: 0x2151, 0xc52: 0x2181, 0xc53: 0x21b9, 0xc54: 0x21e9, 0xc55: 0x2219, 0xc56: 0x2249, 0xc57: 0x2279, 0xc58: 0x22a9, 0xc59: 0x22d9, 0xc5a: 0x2309, 0xc5b: 0x2339, 0xc5c: 0x2369, 0xc5d: 0x2399, 0xc5e: 0x23c9, 0xc5f: 0x23f9, 0xc60: 0x0f41, 0xc61: 0x2421, 0xc62: 0x0905, 0xc63: 0x2439, 0xc64: 0x1089, 0xc65: 0x2451, 0xc66: 0x0925, 0xc67: 0x2469, 0xc68: 0x2491, 0xc69: 0x0369, 0xc6a: 0x24a9, 0xc6b: 0x0945, 0xc6c: 0x0359, 0xc6d: 0x1159, 0xc6e: 0x0ef9, 0xc6f: 0x0f61, 0xc70: 0x0f41, 0xc71: 0x2421, 0xc72: 0x0965, 0xc73: 0x2439, 0xc74: 0x1089, 0xc75: 0x2451, 0xc76: 0x0985, 0xc77: 0x2469, 0xc78: 0x2491, 0xc79: 0x0369, 0xc7a: 0x24a9, 0xc7b: 0x09a5, 0xc7c: 0x0359, 0xc7d: 0x1159, 0xc7e: 0x0ef9, 0xc7f: 0x0f61, // Block 0x32, offset 0xc80 0xc80: 0x0018, 0xc81: 0x0018, 0xc82: 0x0018, 0xc83: 0x0018, 0xc84: 0x0018, 0xc85: 0x0018, 0xc86: 0x0018, 0xc87: 0x0018, 0xc88: 0x0018, 0xc89: 0x0018, 0xc8a: 0x0018, 0xc8b: 0x0040, 0xc8c: 0x0040, 0xc8d: 0x0040, 0xc8e: 0x0040, 0xc8f: 0x0040, 0xc90: 0x0040, 0xc91: 0x0040, 0xc92: 0x0040, 0xc93: 0x0040, 0xc94: 0x0040, 0xc95: 0x0040, 0xc96: 0x0040, 0xc97: 0x0040, 0xc98: 0x0040, 0xc99: 0x0040, 0xc9a: 0x0040, 0xc9b: 0x0040, 0xc9c: 0x0040, 0xc9d: 0x0040, 0xc9e: 0x0040, 0xc9f: 0x0040, 0xca0: 0x00c9, 0xca1: 0x0069, 0xca2: 0x0079, 0xca3: 0x1f51, 0xca4: 0x1f61, 0xca5: 0x1f71, 0xca6: 0x1f81, 0xca7: 0x1f91, 0xca8: 0x1fa1, 0xca9: 0x2601, 0xcaa: 0x2619, 0xcab: 0x2631, 0xcac: 0x2649, 0xcad: 0x2661, 0xcae: 0x2679, 0xcaf: 0x2691, 0xcb0: 0x26a9, 0xcb1: 0x26c1, 0xcb2: 0x26d9, 0xcb3: 0x26f1, 0xcb4: 0x0a06, 0xcb5: 0x0a26, 0xcb6: 0x0a46, 0xcb7: 0x0a66, 0xcb8: 0x0a86, 0xcb9: 0x0aa6, 0xcba: 0x0ac6, 0xcbb: 0x0ae6, 0xcbc: 0x0b06, 0xcbd: 0x270a, 0xcbe: 0x2732, 0xcbf: 0x275a, // Block 0x33, offset 0xcc0 0xcc0: 0x2782, 0xcc1: 0x27aa, 0xcc2: 0x27d2, 0xcc3: 0x27fa, 0xcc4: 0x2822, 0xcc5: 0x284a, 0xcc6: 0x2872, 0xcc7: 0x289a, 0xcc8: 0x0040, 0xcc9: 0x0040, 0xcca: 0x0040, 0xccb: 0x0040, 0xccc: 0x0040, 0xccd: 0x0040, 0xcce: 0x0040, 0xccf: 0x0040, 0xcd0: 0x0040, 0xcd1: 0x0040, 0xcd2: 0x0040, 0xcd3: 0x0040, 0xcd4: 0x0040, 0xcd5: 0x0040, 0xcd6: 0x0040, 0xcd7: 0x0040, 0xcd8: 0x0040, 0xcd9: 0x0040, 0xcda: 0x0040, 0xcdb: 0x0040, 0xcdc: 0x0b26, 0xcdd: 0x0b46, 0xcde: 0x0b66, 0xcdf: 0x0b86, 0xce0: 0x0ba6, 0xce1: 0x0bc6, 0xce2: 0x0be6, 0xce3: 0x0c06, 0xce4: 0x0c26, 0xce5: 0x0c46, 0xce6: 0x0c66, 0xce7: 0x0c86, 0xce8: 0x0ca6, 0xce9: 0x0cc6, 0xcea: 0x0ce6, 0xceb: 0x0d06, 0xcec: 0x0d26, 0xced: 0x0d46, 0xcee: 0x0d66, 0xcef: 0x0d86, 0xcf0: 0x0da6, 0xcf1: 0x0dc6, 0xcf2: 0x0de6, 0xcf3: 0x0e06, 0xcf4: 0x0e26, 0xcf5: 0x0e46, 0xcf6: 0x0039, 0xcf7: 0x0ee9, 0xcf8: 0x1159, 0xcf9: 0x0ef9, 0xcfa: 0x0f09, 0xcfb: 0x1199, 0xcfc: 0x0f31, 0xcfd: 0x0249, 0xcfe: 0x0f41, 0xcff: 0x0259, // Block 0x34, offset 0xd00 0xd00: 0x0f51, 0xd01: 0x0359, 0xd02: 0x0f61, 0xd03: 0x0f71, 0xd04: 0x00d9, 0xd05: 0x0f99, 0xd06: 0x2039, 0xd07: 0x0269, 0xd08: 0x01d9, 0xd09: 0x0fa9, 0xd0a: 0x0fb9, 0xd0b: 0x1089, 0xd0c: 0x0279, 0xd0d: 0x0369, 0xd0e: 0x0289, 0xd0f: 0x13d1, 0xd10: 0x0039, 0xd11: 0x0ee9, 0xd12: 0x1159, 0xd13: 0x0ef9, 0xd14: 0x0f09, 0xd15: 0x1199, 0xd16: 0x0f31, 0xd17: 0x0249, 0xd18: 0x0f41, 0xd19: 0x0259, 0xd1a: 0x0f51, 0xd1b: 0x0359, 0xd1c: 0x0f61, 0xd1d: 0x0f71, 0xd1e: 0x00d9, 0xd1f: 0x0f99, 0xd20: 0x2039, 0xd21: 0x0269, 0xd22: 0x01d9, 0xd23: 0x0fa9, 0xd24: 0x0fb9, 0xd25: 0x1089, 0xd26: 0x0279, 0xd27: 0x0369, 0xd28: 0x0289, 0xd29: 0x13d1, 0xd2a: 0x1f41, 0xd2b: 0x0018, 0xd2c: 0x0018, 0xd2d: 0x0018, 0xd2e: 0x0018, 0xd2f: 0x0018, 0xd30: 0x0018, 0xd31: 0x0018, 0xd32: 0x0018, 0xd33: 0x0018, 0xd34: 0x0018, 0xd35: 0x0018, 0xd36: 0x0018, 0xd37: 0x0018, 0xd38: 0x0018, 0xd39: 0x0018, 0xd3a: 0x0018, 0xd3b: 0x0018, 0xd3c: 0x0018, 0xd3d: 0x0018, 0xd3e: 0x0018, 0xd3f: 0x0018, // Block 0x35, offset 0xd40 0xd40: 0x0008, 0xd41: 0x0008, 0xd42: 0x0008, 0xd43: 0x0008, 0xd44: 0x0008, 0xd45: 0x0008, 0xd46: 0x0008, 0xd47: 0x0008, 0xd48: 0x0008, 0xd49: 0x0008, 0xd4a: 0x0008, 0xd4b: 0x0008, 0xd4c: 0x0008, 0xd4d: 0x0008, 0xd4e: 0x0008, 0xd4f: 0x0008, 0xd50: 0x0008, 0xd51: 0x0008, 0xd52: 0x0008, 0xd53: 0x0008, 0xd54: 0x0008, 0xd55: 0x0008, 0xd56: 0x0008, 0xd57: 0x0008, 0xd58: 0x0008, 0xd59: 0x0008, 0xd5a: 0x0008, 0xd5b: 0x0008, 0xd5c: 0x0008, 0xd5d: 0x0008, 0xd5e: 0x0008, 0xd5f: 0x0040, 0xd60: 0xe00d, 0xd61: 0x0008, 0xd62: 0x2971, 0xd63: 0x0ebd, 0xd64: 0x2989, 0xd65: 0x0008, 0xd66: 0x0008, 0xd67: 0xe07d, 0xd68: 0x0008, 0xd69: 0xe01d, 0xd6a: 0x0008, 0xd6b: 0xe03d, 0xd6c: 0x0008, 0xd6d: 0x0fe1, 0xd6e: 0x1281, 0xd6f: 0x0fc9, 0xd70: 0x1141, 0xd71: 0x0008, 0xd72: 0xe00d, 0xd73: 0x0008, 0xd74: 0x0008, 0xd75: 0xe01d, 0xd76: 0x0008, 0xd77: 0x0008, 0xd78: 0x0008, 0xd79: 0x0008, 0xd7a: 0x0008, 0xd7b: 0x0008, 0xd7c: 0x0259, 0xd7d: 0x1089, 0xd7e: 0x29a1, 0xd7f: 0x29b9, // Block 0x36, offset 0xd80 0xd80: 0xe00d, 0xd81: 0x0008, 0xd82: 0xe00d, 0xd83: 0x0008, 0xd84: 0xe00d, 0xd85: 0x0008, 0xd86: 0xe00d, 0xd87: 0x0008, 0xd88: 0xe00d, 0xd89: 0x0008, 0xd8a: 0xe00d, 0xd8b: 0x0008, 0xd8c: 0xe00d, 0xd8d: 0x0008, 0xd8e: 0xe00d, 0xd8f: 0x0008, 0xd90: 0xe00d, 0xd91: 0x0008, 0xd92: 0xe00d, 0xd93: 0x0008, 0xd94: 0xe00d, 0xd95: 0x0008, 0xd96: 0xe00d, 0xd97: 0x0008, 0xd98: 0xe00d, 0xd99: 0x0008, 0xd9a: 0xe00d, 0xd9b: 0x0008, 0xd9c: 0xe00d, 0xd9d: 0x0008, 0xd9e: 0xe00d, 0xd9f: 0x0008, 0xda0: 0xe00d, 0xda1: 0x0008, 0xda2: 0xe00d, 0xda3: 0x0008, 0xda4: 0x0008, 0xda5: 0x0018, 0xda6: 0x0018, 0xda7: 0x0018, 0xda8: 0x0018, 0xda9: 0x0018, 0xdaa: 0x0018, 0xdab: 0xe03d, 0xdac: 0x0008, 0xdad: 0xe01d, 0xdae: 0x0008, 0xdaf: 0x1308, 0xdb0: 0x1308, 0xdb1: 0x1308, 0xdb2: 0xe00d, 0xdb3: 0x0008, 0xdb4: 0x0040, 0xdb5: 0x0040, 0xdb6: 0x0040, 0xdb7: 0x0040, 0xdb8: 0x0040, 0xdb9: 0x0018, 0xdba: 0x0018, 0xdbb: 0x0018, 0xdbc: 0x0018, 0xdbd: 0x0018, 0xdbe: 0x0018, 0xdbf: 0x0018, // Block 0x37, offset 0xdc0 0xdc0: 0x26fd, 0xdc1: 0x271d, 0xdc2: 0x273d, 0xdc3: 0x275d, 0xdc4: 0x277d, 0xdc5: 0x279d, 0xdc6: 0x27bd, 0xdc7: 0x27dd, 0xdc8: 0x27fd, 0xdc9: 0x281d, 0xdca: 0x283d, 0xdcb: 0x285d, 0xdcc: 0x287d, 0xdcd: 0x289d, 0xdce: 0x28bd, 0xdcf: 0x28dd, 0xdd0: 0x28fd, 0xdd1: 0x291d, 0xdd2: 0x293d, 0xdd3: 0x295d, 0xdd4: 0x297d, 0xdd5: 0x299d, 0xdd6: 0x0040, 0xdd7: 0x0040, 0xdd8: 0x0040, 0xdd9: 0x0040, 0xdda: 0x0040, 0xddb: 0x0040, 0xddc: 0x0040, 0xddd: 0x0040, 0xdde: 0x0040, 0xddf: 0x0040, 0xde0: 0x0040, 0xde1: 0x0040, 0xde2: 0x0040, 0xde3: 0x0040, 0xde4: 0x0040, 0xde5: 0x0040, 0xde6: 0x0040, 0xde7: 0x0040, 0xde8: 0x0040, 0xde9: 0x0040, 0xdea: 0x0040, 0xdeb: 0x0040, 0xdec: 0x0040, 0xded: 0x0040, 0xdee: 0x0040, 0xdef: 0x0040, 0xdf0: 0x0040, 0xdf1: 0x0040, 0xdf2: 0x0040, 0xdf3: 0x0040, 0xdf4: 0x0040, 0xdf5: 0x0040, 0xdf6: 0x0040, 0xdf7: 0x0040, 0xdf8: 0x0040, 0xdf9: 0x0040, 0xdfa: 0x0040, 0xdfb: 0x0040, 0xdfc: 0x0040, 0xdfd: 0x0040, 0xdfe: 0x0040, 0xdff: 0x0040, // Block 0x38, offset 0xe00 0xe00: 0x000a, 0xe01: 0x0018, 0xe02: 0x29d1, 0xe03: 0x0018, 0xe04: 0x0018, 0xe05: 0x0008, 0xe06: 0x0008, 0xe07: 0x0008, 0xe08: 0x0018, 0xe09: 0x0018, 0xe0a: 0x0018, 0xe0b: 0x0018, 0xe0c: 0x0018, 0xe0d: 0x0018, 0xe0e: 0x0018, 0xe0f: 0x0018, 0xe10: 0x0018, 0xe11: 0x0018, 0xe12: 0x0018, 0xe13: 0x0018, 0xe14: 0x0018, 0xe15: 0x0018, 0xe16: 0x0018, 0xe17: 0x0018, 0xe18: 0x0018, 0xe19: 0x0018, 0xe1a: 0x0018, 0xe1b: 0x0018, 0xe1c: 0x0018, 0xe1d: 0x0018, 0xe1e: 0x0018, 0xe1f: 0x0018, 0xe20: 0x0018, 0xe21: 0x0018, 0xe22: 0x0018, 0xe23: 0x0018, 0xe24: 0x0018, 0xe25: 0x0018, 0xe26: 0x0018, 0xe27: 0x0018, 0xe28: 0x0018, 0xe29: 0x0018, 0xe2a: 0x1308, 0xe2b: 0x1308, 0xe2c: 0x1308, 0xe2d: 0x1308, 0xe2e: 0x1018, 0xe2f: 0x1018, 0xe30: 0x0018, 0xe31: 0x0018, 0xe32: 0x0018, 0xe33: 0x0018, 0xe34: 0x0018, 0xe35: 0x0018, 0xe36: 0xe125, 0xe37: 0x0018, 0xe38: 0x29bd, 0xe39: 0x29dd, 0xe3a: 0x29fd, 0xe3b: 0x0018, 0xe3c: 0x0008, 0xe3d: 0x0018, 0xe3e: 0x0018, 0xe3f: 0x0018, // Block 0x39, offset 0xe40 0xe40: 0x2b3d, 0xe41: 0x2b5d, 0xe42: 0x2b7d, 0xe43: 0x2b9d, 0xe44: 0x2bbd, 0xe45: 0x2bdd, 0xe46: 0x2bdd, 0xe47: 0x2bdd, 0xe48: 0x2bfd, 0xe49: 0x2bfd, 0xe4a: 0x2bfd, 0xe4b: 0x2bfd, 0xe4c: 0x2c1d, 0xe4d: 0x2c1d, 0xe4e: 0x2c1d, 0xe4f: 0x2c3d, 0xe50: 0x2c5d, 0xe51: 0x2c5d, 0xe52: 0x2a7d, 0xe53: 0x2a7d, 0xe54: 0x2c5d, 0xe55: 0x2c5d, 0xe56: 0x2c7d, 0xe57: 0x2c7d, 0xe58: 0x2c5d, 0xe59: 0x2c5d, 0xe5a: 0x2a7d, 0xe5b: 0x2a7d, 0xe5c: 0x2c5d, 0xe5d: 0x2c5d, 0xe5e: 0x2c3d, 0xe5f: 0x2c3d, 0xe60: 0x2c9d, 0xe61: 0x2c9d, 0xe62: 0x2cbd, 0xe63: 0x2cbd, 0xe64: 0x0040, 0xe65: 0x2cdd, 0xe66: 0x2cfd, 0xe67: 0x2d1d, 0xe68: 0x2d1d, 0xe69: 0x2d3d, 0xe6a: 0x2d5d, 0xe6b: 0x2d7d, 0xe6c: 0x2d9d, 0xe6d: 0x2dbd, 0xe6e: 0x2ddd, 0xe6f: 0x2dfd, 0xe70: 0x2e1d, 0xe71: 0x2e3d, 0xe72: 0x2e3d, 0xe73: 0x2e5d, 0xe74: 0x2e7d, 0xe75: 0x2e7d, 0xe76: 0x2e9d, 0xe77: 0x2ebd, 0xe78: 0x2e5d, 0xe79: 0x2edd, 0xe7a: 0x2efd, 0xe7b: 0x2edd, 0xe7c: 0x2e5d, 0xe7d: 0x2f1d, 0xe7e: 0x2f3d, 0xe7f: 0x2f5d, // Block 0x3a, offset 0xe80 0xe80: 0x2f7d, 0xe81: 0x2f9d, 0xe82: 0x2cfd, 0xe83: 0x2cdd, 0xe84: 0x2fbd, 0xe85: 0x2fdd, 0xe86: 0x2ffd, 0xe87: 0x301d, 0xe88: 0x303d, 0xe89: 0x305d, 0xe8a: 0x307d, 0xe8b: 0x309d, 0xe8c: 0x30bd, 0xe8d: 0x30dd, 0xe8e: 0x30fd, 0xe8f: 0x0040, 0xe90: 0x0018, 0xe91: 0x0018, 0xe92: 0x311d, 0xe93: 0x313d, 0xe94: 0x315d, 0xe95: 0x317d, 0xe96: 0x319d, 0xe97: 0x31bd, 0xe98: 0x31dd, 0xe99: 0x31fd, 0xe9a: 0x321d, 0xe9b: 0x323d, 0xe9c: 0x315d, 0xe9d: 0x325d, 0xe9e: 0x327d, 0xe9f: 0x329d, 0xea0: 0x0008, 0xea1: 0x0008, 0xea2: 0x0008, 0xea3: 0x0008, 0xea4: 0x0008, 0xea5: 0x0008, 0xea6: 0x0008, 0xea7: 0x0008, 0xea8: 0x0008, 0xea9: 0x0008, 0xeaa: 0x0008, 0xeab: 0x0008, 0xeac: 0x0008, 0xead: 0x0008, 0xeae: 0x0008, 0xeaf: 0x0008, 0xeb0: 0x0008, 0xeb1: 0x0008, 0xeb2: 0x0008, 0xeb3: 0x0008, 0xeb4: 0x0008, 0xeb5: 0x0008, 0xeb6: 0x0008, 0xeb7: 0x0008, 0xeb8: 0x0008, 0xeb9: 0x0008, 0xeba: 0x0008, 0xebb: 0x0040, 0xebc: 0x0040, 0xebd: 0x0040, 0xebe: 0x0040, 0xebf: 0x0040, // Block 0x3b, offset 0xec0 0xec0: 0x36a2, 0xec1: 0x36d2, 0xec2: 0x3702, 0xec3: 0x3732, 0xec4: 0x32bd, 0xec5: 0x32dd, 0xec6: 0x32fd, 0xec7: 0x331d, 0xec8: 0x0018, 0xec9: 0x0018, 0xeca: 0x0018, 0xecb: 0x0018, 0xecc: 0x0018, 0xecd: 0x0018, 0xece: 0x0018, 0xecf: 0x0018, 0xed0: 0x333d, 0xed1: 0x3761, 0xed2: 0x3779, 0xed3: 0x3791, 0xed4: 0x37a9, 0xed5: 0x37c1, 0xed6: 0x37d9, 0xed7: 0x37f1, 0xed8: 0x3809, 0xed9: 0x3821, 0xeda: 0x3839, 0xedb: 0x3851, 0xedc: 0x3869, 0xedd: 0x3881, 0xede: 0x3899, 0xedf: 0x38b1, 0xee0: 0x335d, 0xee1: 0x337d, 0xee2: 0x339d, 0xee3: 0x33bd, 0xee4: 0x33dd, 0xee5: 0x33dd, 0xee6: 0x33fd, 0xee7: 0x341d, 0xee8: 0x343d, 0xee9: 0x345d, 0xeea: 0x347d, 0xeeb: 0x349d, 0xeec: 0x34bd, 0xeed: 0x34dd, 0xeee: 0x34fd, 0xeef: 0x351d, 0xef0: 0x353d, 0xef1: 0x355d, 0xef2: 0x357d, 0xef3: 0x359d, 0xef4: 0x35bd, 0xef5: 0x35dd, 0xef6: 0x35fd, 0xef7: 0x361d, 0xef8: 0x363d, 0xef9: 0x365d, 0xefa: 0x367d, 0xefb: 0x369d, 0xefc: 0x38c9, 0xefd: 0x3901, 0xefe: 0x36bd, 0xeff: 0x0018, // Block 0x3c, offset 0xf00 0xf00: 0x36dd, 0xf01: 0x36fd, 0xf02: 0x371d, 0xf03: 0x373d, 0xf04: 0x375d, 0xf05: 0x377d, 0xf06: 0x379d, 0xf07: 0x37bd, 0xf08: 0x37dd, 0xf09: 0x37fd, 0xf0a: 0x381d, 0xf0b: 0x383d, 0xf0c: 0x385d, 0xf0d: 0x387d, 0xf0e: 0x389d, 0xf0f: 0x38bd, 0xf10: 0x38dd, 0xf11: 0x38fd, 0xf12: 0x391d, 0xf13: 0x393d, 0xf14: 0x395d, 0xf15: 0x397d, 0xf16: 0x399d, 0xf17: 0x39bd, 0xf18: 0x39dd, 0xf19: 0x39fd, 0xf1a: 0x3a1d, 0xf1b: 0x3a3d, 0xf1c: 0x3a5d, 0xf1d: 0x3a7d, 0xf1e: 0x3a9d, 0xf1f: 0x3abd, 0xf20: 0x3add, 0xf21: 0x3afd, 0xf22: 0x3b1d, 0xf23: 0x3b3d, 0xf24: 0x3b5d, 0xf25: 0x3b7d, 0xf26: 0x127d, 0xf27: 0x3b9d, 0xf28: 0x3bbd, 0xf29: 0x3bdd, 0xf2a: 0x3bfd, 0xf2b: 0x3c1d, 0xf2c: 0x3c3d, 0xf2d: 0x3c5d, 0xf2e: 0x239d, 0xf2f: 0x3c7d, 0xf30: 0x3c9d, 0xf31: 0x3939, 0xf32: 0x3951, 0xf33: 0x3969, 0xf34: 0x3981, 0xf35: 0x3999, 0xf36: 0x39b1, 0xf37: 0x39c9, 0xf38: 0x39e1, 0xf39: 0x39f9, 0xf3a: 0x3a11, 0xf3b: 0x3a29, 0xf3c: 0x3a41, 0xf3d: 0x3a59, 0xf3e: 0x3a71, 0xf3f: 0x3a89, // Block 0x3d, offset 0xf40 0xf40: 0x3aa1, 0xf41: 0x3ac9, 0xf42: 0x3af1, 0xf43: 0x3b19, 0xf44: 0x3b41, 0xf45: 0x3b69, 0xf46: 0x3b91, 0xf47: 0x3bb9, 0xf48: 0x3be1, 0xf49: 0x3c09, 0xf4a: 0x3c39, 0xf4b: 0x3c69, 0xf4c: 0x3c99, 0xf4d: 0x3cbd, 0xf4e: 0x3cb1, 0xf4f: 0x3cdd, 0xf50: 0x3cfd, 0xf51: 0x3d15, 0xf52: 0x3d2d, 0xf53: 0x3d45, 0xf54: 0x3d5d, 0xf55: 0x3d5d, 0xf56: 0x3d45, 0xf57: 0x3d75, 0xf58: 0x07bd, 0xf59: 0x3d8d, 0xf5a: 0x3da5, 0xf5b: 0x3dbd, 0xf5c: 0x3dd5, 0xf5d: 0x3ded, 0xf5e: 0x3e05, 0xf5f: 0x3e1d, 0xf60: 0x3e35, 0xf61: 0x3e4d, 0xf62: 0x3e65, 0xf63: 0x3e7d, 0xf64: 0x3e95, 0xf65: 0x3e95, 0xf66: 0x3ead, 0xf67: 0x3ead, 0xf68: 0x3ec5, 0xf69: 0x3ec5, 0xf6a: 0x3edd, 0xf6b: 0x3ef5, 0xf6c: 0x3f0d, 0xf6d: 0x3f25, 0xf6e: 0x3f3d, 0xf6f: 0x3f3d, 0xf70: 0x3f55, 0xf71: 0x3f55, 0xf72: 0x3f55, 0xf73: 0x3f6d, 0xf74: 0x3f85, 0xf75: 0x3f9d, 0xf76: 0x3fb5, 0xf77: 0x3f9d, 0xf78: 0x3fcd, 0xf79: 0x3fe5, 0xf7a: 0x3f6d, 0xf7b: 0x3ffd, 0xf7c: 0x4015, 0xf7d: 0x4015, 0xf7e: 0x4015, 0xf7f: 0x0040, // Block 0x3e, offset 0xf80 0xf80: 0x3cc9, 0xf81: 0x3d31, 0xf82: 0x3d99, 0xf83: 0x3e01, 0xf84: 0x3e51, 0xf85: 0x3eb9, 0xf86: 0x3f09, 0xf87: 0x3f59, 0xf88: 0x3fd9, 0xf89: 0x4041, 0xf8a: 0x4091, 0xf8b: 0x40e1, 0xf8c: 0x4131, 0xf8d: 0x4199, 0xf8e: 0x4201, 0xf8f: 0x4251, 0xf90: 0x42a1, 0xf91: 0x42d9, 0xf92: 0x4329, 0xf93: 0x4391, 0xf94: 0x43f9, 0xf95: 0x4431, 0xf96: 0x44b1, 0xf97: 0x4549, 0xf98: 0x45c9, 0xf99: 0x4619, 0xf9a: 0x4699, 0xf9b: 0x4719, 0xf9c: 0x4781, 0xf9d: 0x47d1, 0xf9e: 0x4821, 0xf9f: 0x4871, 0xfa0: 0x48d9, 0xfa1: 0x4959, 0xfa2: 0x49c1, 0xfa3: 0x4a11, 0xfa4: 0x4a61, 0xfa5: 0x4ab1, 0xfa6: 0x4ae9, 0xfa7: 0x4b21, 0xfa8: 0x4b59, 0xfa9: 0x4b91, 0xfaa: 0x4be1, 0xfab: 0x4c31, 0xfac: 0x4cb1, 0xfad: 0x4d01, 0xfae: 0x4d69, 0xfaf: 0x4de9, 0xfb0: 0x4e39, 0xfb1: 0x4e71, 0xfb2: 0x4ea9, 0xfb3: 0x4f29, 0xfb4: 0x4f91, 0xfb5: 0x5011, 0xfb6: 0x5061, 0xfb7: 0x50e1, 0xfb8: 0x5119, 0xfb9: 0x5169, 0xfba: 0x51b9, 0xfbb: 0x5209, 0xfbc: 0x5259, 0xfbd: 0x52a9, 0xfbe: 0x5311, 0xfbf: 0x5361, // Block 0x3f, offset 0xfc0 0xfc0: 0x5399, 0xfc1: 0x53e9, 0xfc2: 0x5439, 0xfc3: 0x5489, 0xfc4: 0x54f1, 0xfc5: 0x5541, 0xfc6: 0x5591, 0xfc7: 0x55e1, 0xfc8: 0x5661, 0xfc9: 0x56c9, 0xfca: 0x5701, 0xfcb: 0x5781, 0xfcc: 0x57b9, 0xfcd: 0x5821, 0xfce: 0x5889, 0xfcf: 0x58d9, 0xfd0: 0x5929, 0xfd1: 0x5979, 0xfd2: 0x59e1, 0xfd3: 0x5a19, 0xfd4: 0x5a69, 0xfd5: 0x5ad1, 0xfd6: 0x5b09, 0xfd7: 0x5b89, 0xfd8: 0x5bd9, 0xfd9: 0x5c01, 0xfda: 0x5c29, 0xfdb: 0x5c51, 0xfdc: 0x5c79, 0xfdd: 0x5ca1, 0xfde: 0x5cc9, 0xfdf: 0x5cf1, 0xfe0: 0x5d19, 0xfe1: 0x5d41, 0xfe2: 0x5d69, 0xfe3: 0x5d99, 0xfe4: 0x5dc9, 0xfe5: 0x5df9, 0xfe6: 0x5e29, 0xfe7: 0x5e59, 0xfe8: 0x5e89, 0xfe9: 0x5eb9, 0xfea: 0x5ee9, 0xfeb: 0x5f19, 0xfec: 0x5f49, 0xfed: 0x5f79, 0xfee: 0x5fa9, 0xfef: 0x5fd9, 0xff0: 0x6009, 0xff1: 0x402d, 0xff2: 0x6039, 0xff3: 0x6051, 0xff4: 0x404d, 0xff5: 0x6069, 0xff6: 0x6081, 0xff7: 0x6099, 0xff8: 0x406d, 0xff9: 0x406d, 0xffa: 0x60b1, 0xffb: 0x60c9, 0xffc: 0x6101, 0xffd: 0x6139, 0xffe: 0x6171, 0xfff: 0x61a9, // Block 0x40, offset 0x1000 0x1000: 0x6211, 0x1001: 0x6229, 0x1002: 0x408d, 0x1003: 0x6241, 0x1004: 0x6259, 0x1005: 0x6271, 0x1006: 0x6289, 0x1007: 0x62a1, 0x1008: 0x40ad, 0x1009: 0x62b9, 0x100a: 0x62e1, 0x100b: 0x62f9, 0x100c: 0x40cd, 0x100d: 0x40cd, 0x100e: 0x6311, 0x100f: 0x6329, 0x1010: 0x6341, 0x1011: 0x40ed, 0x1012: 0x410d, 0x1013: 0x412d, 0x1014: 0x414d, 0x1015: 0x416d, 0x1016: 0x6359, 0x1017: 0x6371, 0x1018: 0x6389, 0x1019: 0x63a1, 0x101a: 0x63b9, 0x101b: 0x418d, 0x101c: 0x63d1, 0x101d: 0x63e9, 0x101e: 0x6401, 0x101f: 0x41ad, 0x1020: 0x41cd, 0x1021: 0x6419, 0x1022: 0x41ed, 0x1023: 0x420d, 0x1024: 0x422d, 0x1025: 0x6431, 0x1026: 0x424d, 0x1027: 0x6449, 0x1028: 0x6479, 0x1029: 0x6211, 0x102a: 0x426d, 0x102b: 0x428d, 0x102c: 0x42ad, 0x102d: 0x42cd, 0x102e: 0x64b1, 0x102f: 0x64f1, 0x1030: 0x6539, 0x1031: 0x6551, 0x1032: 0x42ed, 0x1033: 0x6569, 0x1034: 0x6581, 0x1035: 0x6599, 0x1036: 0x430d, 0x1037: 0x65b1, 0x1038: 0x65c9, 0x1039: 0x65b1, 0x103a: 0x65e1, 0x103b: 0x65f9, 0x103c: 0x432d, 0x103d: 0x6611, 0x103e: 0x6629, 0x103f: 0x6611, // Block 0x41, offset 0x1040 0x1040: 0x434d, 0x1041: 0x436d, 0x1042: 0x0040, 0x1043: 0x6641, 0x1044: 0x6659, 0x1045: 0x6671, 0x1046: 0x6689, 0x1047: 0x0040, 0x1048: 0x66c1, 0x1049: 0x66d9, 0x104a: 0x66f1, 0x104b: 0x6709, 0x104c: 0x6721, 0x104d: 0x6739, 0x104e: 0x6401, 0x104f: 0x6751, 0x1050: 0x6769, 0x1051: 0x6781, 0x1052: 0x438d, 0x1053: 0x6799, 0x1054: 0x6289, 0x1055: 0x43ad, 0x1056: 0x43cd, 0x1057: 0x67b1, 0x1058: 0x0040, 0x1059: 0x43ed, 0x105a: 0x67c9, 0x105b: 0x67e1, 0x105c: 0x67f9, 0x105d: 0x6811, 0x105e: 0x6829, 0x105f: 0x6859, 0x1060: 0x6889, 0x1061: 0x68b1, 0x1062: 0x68d9, 0x1063: 0x6901, 0x1064: 0x6929, 0x1065: 0x6951, 0x1066: 0x6979, 0x1067: 0x69a1, 0x1068: 0x69c9, 0x1069: 0x69f1, 0x106a: 0x6a21, 0x106b: 0x6a51, 0x106c: 0x6a81, 0x106d: 0x6ab1, 0x106e: 0x6ae1, 0x106f: 0x6b11, 0x1070: 0x6b41, 0x1071: 0x6b71, 0x1072: 0x6ba1, 0x1073: 0x6bd1, 0x1074: 0x6c01, 0x1075: 0x6c31, 0x1076: 0x6c61, 0x1077: 0x6c91, 0x1078: 0x6cc1, 0x1079: 0x6cf1, 0x107a: 0x6d21, 0x107b: 0x6d51, 0x107c: 0x6d81, 0x107d: 0x6db1, 0x107e: 0x6de1, 0x107f: 0x440d, // Block 0x42, offset 0x1080 0x1080: 0xe00d, 0x1081: 0x0008, 0x1082: 0xe00d, 0x1083: 0x0008, 0x1084: 0xe00d, 0x1085: 0x0008, 0x1086: 0xe00d, 0x1087: 0x0008, 0x1088: 0xe00d, 0x1089: 0x0008, 0x108a: 0xe00d, 0x108b: 0x0008, 0x108c: 0xe00d, 0x108d: 0x0008, 0x108e: 0xe00d, 0x108f: 0x0008, 0x1090: 0xe00d, 0x1091: 0x0008, 0x1092: 0xe00d, 0x1093: 0x0008, 0x1094: 0xe00d, 0x1095: 0x0008, 0x1096: 0xe00d, 0x1097: 0x0008, 0x1098: 0xe00d, 0x1099: 0x0008, 0x109a: 0xe00d, 0x109b: 0x0008, 0x109c: 0xe00d, 0x109d: 0x0008, 0x109e: 0xe00d, 0x109f: 0x0008, 0x10a0: 0xe00d, 0x10a1: 0x0008, 0x10a2: 0xe00d, 0x10a3: 0x0008, 0x10a4: 0xe00d, 0x10a5: 0x0008, 0x10a6: 0xe00d, 0x10a7: 0x0008, 0x10a8: 0xe00d, 0x10a9: 0x0008, 0x10aa: 0xe00d, 0x10ab: 0x0008, 0x10ac: 0xe00d, 0x10ad: 0x0008, 0x10ae: 0x0008, 0x10af: 0x1308, 0x10b0: 0x1318, 0x10b1: 0x1318, 0x10b2: 0x1318, 0x10b3: 0x0018, 0x10b4: 0x1308, 0x10b5: 0x1308, 0x10b6: 0x1308, 0x10b7: 0x1308, 0x10b8: 0x1308, 0x10b9: 0x1308, 0x10ba: 0x1308, 0x10bb: 0x1308, 0x10bc: 0x1308, 0x10bd: 0x1308, 0x10be: 0x0018, 0x10bf: 0x0008, // Block 0x43, offset 0x10c0 0x10c0: 0xe00d, 0x10c1: 0x0008, 0x10c2: 0xe00d, 0x10c3: 0x0008, 0x10c4: 0xe00d, 0x10c5: 0x0008, 0x10c6: 0xe00d, 0x10c7: 0x0008, 0x10c8: 0xe00d, 0x10c9: 0x0008, 0x10ca: 0xe00d, 0x10cb: 0x0008, 0x10cc: 0xe00d, 0x10cd: 0x0008, 0x10ce: 0xe00d, 0x10cf: 0x0008, 0x10d0: 0xe00d, 0x10d1: 0x0008, 0x10d2: 0xe00d, 0x10d3: 0x0008, 0x10d4: 0xe00d, 0x10d5: 0x0008, 0x10d6: 0xe00d, 0x10d7: 0x0008, 0x10d8: 0xe00d, 0x10d9: 0x0008, 0x10da: 0xe00d, 0x10db: 0x0008, 0x10dc: 0x0ea1, 0x10dd: 0x6e11, 0x10de: 0x1308, 0x10df: 0x1308, 0x10e0: 0x0008, 0x10e1: 0x0008, 0x10e2: 0x0008, 0x10e3: 0x0008, 0x10e4: 0x0008, 0x10e5: 0x0008, 0x10e6: 0x0008, 0x10e7: 0x0008, 0x10e8: 0x0008, 0x10e9: 0x0008, 0x10ea: 0x0008, 0x10eb: 0x0008, 0x10ec: 0x0008, 0x10ed: 0x0008, 0x10ee: 0x0008, 0x10ef: 0x0008, 0x10f0: 0x0008, 0x10f1: 0x0008, 0x10f2: 0x0008, 0x10f3: 0x0008, 0x10f4: 0x0008, 0x10f5: 0x0008, 0x10f6: 0x0008, 0x10f7: 0x0008, 0x10f8: 0x0008, 0x10f9: 0x0008, 0x10fa: 0x0008, 0x10fb: 0x0008, 0x10fc: 0x0008, 0x10fd: 0x0008, 0x10fe: 0x0008, 0x10ff: 0x0008, // Block 0x44, offset 0x1100 0x1100: 0x0018, 0x1101: 0x0018, 0x1102: 0x0018, 0x1103: 0x0018, 0x1104: 0x0018, 0x1105: 0x0018, 0x1106: 0x0018, 0x1107: 0x0018, 0x1108: 0x0018, 0x1109: 0x0018, 0x110a: 0x0018, 0x110b: 0x0018, 0x110c: 0x0018, 0x110d: 0x0018, 0x110e: 0x0018, 0x110f: 0x0018, 0x1110: 0x0018, 0x1111: 0x0018, 0x1112: 0x0018, 0x1113: 0x0018, 0x1114: 0x0018, 0x1115: 0x0018, 0x1116: 0x0018, 0x1117: 0x0008, 0x1118: 0x0008, 0x1119: 0x0008, 0x111a: 0x0008, 0x111b: 0x0008, 0x111c: 0x0008, 0x111d: 0x0008, 0x111e: 0x0008, 0x111f: 0x0008, 0x1120: 0x0018, 0x1121: 0x0018, 0x1122: 0xe00d, 0x1123: 0x0008, 0x1124: 0xe00d, 0x1125: 0x0008, 0x1126: 0xe00d, 0x1127: 0x0008, 0x1128: 0xe00d, 0x1129: 0x0008, 0x112a: 0xe00d, 0x112b: 0x0008, 0x112c: 0xe00d, 0x112d: 0x0008, 0x112e: 0xe00d, 0x112f: 0x0008, 0x1130: 0x0008, 0x1131: 0x0008, 0x1132: 0xe00d, 0x1133: 0x0008, 0x1134: 0xe00d, 0x1135: 0x0008, 0x1136: 0xe00d, 0x1137: 0x0008, 0x1138: 0xe00d, 0x1139: 0x0008, 0x113a: 0xe00d, 0x113b: 0x0008, 0x113c: 0xe00d, 0x113d: 0x0008, 0x113e: 0xe00d, 0x113f: 0x0008, // Block 0x45, offset 0x1140 0x1140: 0xe00d, 0x1141: 0x0008, 0x1142: 0xe00d, 0x1143: 0x0008, 0x1144: 0xe00d, 0x1145: 0x0008, 0x1146: 0xe00d, 0x1147: 0x0008, 0x1148: 0xe00d, 0x1149: 0x0008, 0x114a: 0xe00d, 0x114b: 0x0008, 0x114c: 0xe00d, 0x114d: 0x0008, 0x114e: 0xe00d, 0x114f: 0x0008, 0x1150: 0xe00d, 0x1151: 0x0008, 0x1152: 0xe00d, 0x1153: 0x0008, 0x1154: 0xe00d, 0x1155: 0x0008, 0x1156: 0xe00d, 0x1157: 0x0008, 0x1158: 0xe00d, 0x1159: 0x0008, 0x115a: 0xe00d, 0x115b: 0x0008, 0x115c: 0xe00d, 0x115d: 0x0008, 0x115e: 0xe00d, 0x115f: 0x0008, 0x1160: 0xe00d, 0x1161: 0x0008, 0x1162: 0xe00d, 0x1163: 0x0008, 0x1164: 0xe00d, 0x1165: 0x0008, 0x1166: 0xe00d, 0x1167: 0x0008, 0x1168: 0xe00d, 0x1169: 0x0008, 0x116a: 0xe00d, 0x116b: 0x0008, 0x116c: 0xe00d, 0x116d: 0x0008, 0x116e: 0xe00d, 0x116f: 0x0008, 0x1170: 0xe0fd, 0x1171: 0x0008, 0x1172: 0x0008, 0x1173: 0x0008, 0x1174: 0x0008, 0x1175: 0x0008, 0x1176: 0x0008, 0x1177: 0x0008, 0x1178: 0x0008, 0x1179: 0xe01d, 0x117a: 0x0008, 0x117b: 0xe03d, 0x117c: 0x0008, 0x117d: 0x442d, 0x117e: 0xe00d, 0x117f: 0x0008, // Block 0x46, offset 0x1180 0x1180: 0xe00d, 0x1181: 0x0008, 0x1182: 0xe00d, 0x1183: 0x0008, 0x1184: 0xe00d, 0x1185: 0x0008, 0x1186: 0xe00d, 0x1187: 0x0008, 0x1188: 0x0008, 0x1189: 0x0018, 0x118a: 0x0018, 0x118b: 0xe03d, 0x118c: 0x0008, 0x118d: 0x11d9, 0x118e: 0x0008, 0x118f: 0x0008, 0x1190: 0xe00d, 0x1191: 0x0008, 0x1192: 0xe00d, 0x1193: 0x0008, 0x1194: 0x0008, 0x1195: 0x0008, 0x1196: 0xe00d, 0x1197: 0x0008, 0x1198: 0xe00d, 0x1199: 0x0008, 0x119a: 0xe00d, 0x119b: 0x0008, 0x119c: 0xe00d, 0x119d: 0x0008, 0x119e: 0xe00d, 0x119f: 0x0008, 0x11a0: 0xe00d, 0x11a1: 0x0008, 0x11a2: 0xe00d, 0x11a3: 0x0008, 0x11a4: 0xe00d, 0x11a5: 0x0008, 0x11a6: 0xe00d, 0x11a7: 0x0008, 0x11a8: 0xe00d, 0x11a9: 0x0008, 0x11aa: 0x6e29, 0x11ab: 0x1029, 0x11ac: 0x11c1, 0x11ad: 0x6e41, 0x11ae: 0x1221, 0x11af: 0x0040, 0x11b0: 0x6e59, 0x11b1: 0x6e71, 0x11b2: 0x1239, 0x11b3: 0x444d, 0x11b4: 0xe00d, 0x11b5: 0x0008, 0x11b6: 0xe00d, 0x11b7: 0x0008, 0x11b8: 0x0040, 0x11b9: 0x0040, 0x11ba: 0x0040, 0x11bb: 0x0040, 0x11bc: 0x0040, 0x11bd: 0x0040, 0x11be: 0x0040, 0x11bf: 0x0040, // Block 0x47, offset 0x11c0 0x11c0: 0x64d5, 0x11c1: 0x64f5, 0x11c2: 0x6515, 0x11c3: 0x6535, 0x11c4: 0x6555, 0x11c5: 0x6575, 0x11c6: 0x6595, 0x11c7: 0x65b5, 0x11c8: 0x65d5, 0x11c9: 0x65f5, 0x11ca: 0x6615, 0x11cb: 0x6635, 0x11cc: 0x6655, 0x11cd: 0x6675, 0x11ce: 0x0008, 0x11cf: 0x0008, 0x11d0: 0x6695, 0x11d1: 0x0008, 0x11d2: 0x66b5, 0x11d3: 0x0008, 0x11d4: 0x0008, 0x11d5: 0x66d5, 0x11d6: 0x66f5, 0x11d7: 0x6715, 0x11d8: 0x6735, 0x11d9: 0x6755, 0x11da: 0x6775, 0x11db: 0x6795, 0x11dc: 0x67b5, 0x11dd: 0x67d5, 0x11de: 0x67f5, 0x11df: 0x0008, 0x11e0: 0x6815, 0x11e1: 0x0008, 0x11e2: 0x6835, 0x11e3: 0x0008, 0x11e4: 0x0008, 0x11e5: 0x6855, 0x11e6: 0x6875, 0x11e7: 0x0008, 0x11e8: 0x0008, 0x11e9: 0x0008, 0x11ea: 0x6895, 0x11eb: 0x68b5, 0x11ec: 0x68d5, 0x11ed: 0x68f5, 0x11ee: 0x6915, 0x11ef: 0x6935, 0x11f0: 0x6955, 0x11f1: 0x6975, 0x11f2: 0x6995, 0x11f3: 0x69b5, 0x11f4: 0x69d5, 0x11f5: 0x69f5, 0x11f6: 0x6a15, 0x11f7: 0x6a35, 0x11f8: 0x6a55, 0x11f9: 0x6a75, 0x11fa: 0x6a95, 0x11fb: 0x6ab5, 0x11fc: 0x6ad5, 0x11fd: 0x6af5, 0x11fe: 0x6b15, 0x11ff: 0x6b35, // Block 0x48, offset 0x1200 0x1200: 0x7a95, 0x1201: 0x7ab5, 0x1202: 0x7ad5, 0x1203: 0x7af5, 0x1204: 0x7b15, 0x1205: 0x7b35, 0x1206: 0x7b55, 0x1207: 0x7b75, 0x1208: 0x7b95, 0x1209: 0x7bb5, 0x120a: 0x7bd5, 0x120b: 0x7bf5, 0x120c: 0x7c15, 0x120d: 0x7c35, 0x120e: 0x7c55, 0x120f: 0x6ec9, 0x1210: 0x6ef1, 0x1211: 0x6f19, 0x1212: 0x7c75, 0x1213: 0x7c95, 0x1214: 0x7cb5, 0x1215: 0x6f41, 0x1216: 0x6f69, 0x1217: 0x6f91, 0x1218: 0x7cd5, 0x1219: 0x7cf5, 0x121a: 0x0040, 0x121b: 0x0040, 0x121c: 0x0040, 0x121d: 0x0040, 0x121e: 0x0040, 0x121f: 0x0040, 0x1220: 0x0040, 0x1221: 0x0040, 0x1222: 0x0040, 0x1223: 0x0040, 0x1224: 0x0040, 0x1225: 0x0040, 0x1226: 0x0040, 0x1227: 0x0040, 0x1228: 0x0040, 0x1229: 0x0040, 0x122a: 0x0040, 0x122b: 0x0040, 0x122c: 0x0040, 0x122d: 0x0040, 0x122e: 0x0040, 0x122f: 0x0040, 0x1230: 0x0040, 0x1231: 0x0040, 0x1232: 0x0040, 0x1233: 0x0040, 0x1234: 0x0040, 0x1235: 0x0040, 0x1236: 0x0040, 0x1237: 0x0040, 0x1238: 0x0040, 0x1239: 0x0040, 0x123a: 0x0040, 0x123b: 0x0040, 0x123c: 0x0040, 0x123d: 0x0040, 0x123e: 0x0040, 0x123f: 0x0040, // Block 0x49, offset 0x1240 0x1240: 0x6fb9, 0x1241: 0x6fd1, 0x1242: 0x6fe9, 0x1243: 0x7d15, 0x1244: 0x7d35, 0x1245: 0x7001, 0x1246: 0x7001, 0x1247: 0x0040, 0x1248: 0x0040, 0x1249: 0x0040, 0x124a: 0x0040, 0x124b: 0x0040, 0x124c: 0x0040, 0x124d: 0x0040, 0x124e: 0x0040, 0x124f: 0x0040, 0x1250: 0x0040, 0x1251: 0x0040, 0x1252: 0x0040, 0x1253: 0x7019, 0x1254: 0x7041, 0x1255: 0x7069, 0x1256: 0x7091, 0x1257: 0x70b9, 0x1258: 0x0040, 0x1259: 0x0040, 0x125a: 0x0040, 0x125b: 0x0040, 0x125c: 0x0040, 0x125d: 0x70e1, 0x125e: 0x1308, 0x125f: 0x7109, 0x1260: 0x7131, 0x1261: 0x20a9, 0x1262: 0x20f1, 0x1263: 0x7149, 0x1264: 0x7161, 0x1265: 0x7179, 0x1266: 0x7191, 0x1267: 0x71a9, 0x1268: 0x71c1, 0x1269: 0x1fb2, 0x126a: 0x71d9, 0x126b: 0x7201, 0x126c: 0x7229, 0x126d: 0x7261, 0x126e: 0x7299, 0x126f: 0x72c1, 0x1270: 0x72e9, 0x1271: 0x7311, 0x1272: 0x7339, 0x1273: 0x7361, 0x1274: 0x7389, 0x1275: 0x73b1, 0x1276: 0x73d9, 0x1277: 0x0040, 0x1278: 0x7401, 0x1279: 0x7429, 0x127a: 0x7451, 0x127b: 0x7479, 0x127c: 0x74a1, 0x127d: 0x0040, 0x127e: 0x74c9, 0x127f: 0x0040, // Block 0x4a, offset 0x1280 0x1280: 0x74f1, 0x1281: 0x7519, 0x1282: 0x0040, 0x1283: 0x7541, 0x1284: 0x7569, 0x1285: 0x0040, 0x1286: 0x7591, 0x1287: 0x75b9, 0x1288: 0x75e1, 0x1289: 0x7609, 0x128a: 0x7631, 0x128b: 0x7659, 0x128c: 0x7681, 0x128d: 0x76a9, 0x128e: 0x76d1, 0x128f: 0x76f9, 0x1290: 0x7721, 0x1291: 0x7721, 0x1292: 0x7739, 0x1293: 0x7739, 0x1294: 0x7739, 0x1295: 0x7739, 0x1296: 0x7751, 0x1297: 0x7751, 0x1298: 0x7751, 0x1299: 0x7751, 0x129a: 0x7769, 0x129b: 0x7769, 0x129c: 0x7769, 0x129d: 0x7769, 0x129e: 0x7781, 0x129f: 0x7781, 0x12a0: 0x7781, 0x12a1: 0x7781, 0x12a2: 0x7799, 0x12a3: 0x7799, 0x12a4: 0x7799, 0x12a5: 0x7799, 0x12a6: 0x77b1, 0x12a7: 0x77b1, 0x12a8: 0x77b1, 0x12a9: 0x77b1, 0x12aa: 0x77c9, 0x12ab: 0x77c9, 0x12ac: 0x77c9, 0x12ad: 0x77c9, 0x12ae: 0x77e1, 0x12af: 0x77e1, 0x12b0: 0x77e1, 0x12b1: 0x77e1, 0x12b2: 0x77f9, 0x12b3: 0x77f9, 0x12b4: 0x77f9, 0x12b5: 0x77f9, 0x12b6: 0x7811, 0x12b7: 0x7811, 0x12b8: 0x7811, 0x12b9: 0x7811, 0x12ba: 0x7829, 0x12bb: 0x7829, 0x12bc: 0x7829, 0x12bd: 0x7829, 0x12be: 0x7841, 0x12bf: 0x7841, // Block 0x4b, offset 0x12c0 0x12c0: 0x7841, 0x12c1: 0x7841, 0x12c2: 0x7859, 0x12c3: 0x7859, 0x12c4: 0x7871, 0x12c5: 0x7871, 0x12c6: 0x7889, 0x12c7: 0x7889, 0x12c8: 0x78a1, 0x12c9: 0x78a1, 0x12ca: 0x78b9, 0x12cb: 0x78b9, 0x12cc: 0x78d1, 0x12cd: 0x78d1, 0x12ce: 0x78e9, 0x12cf: 0x78e9, 0x12d0: 0x78e9, 0x12d1: 0x78e9, 0x12d2: 0x7901, 0x12d3: 0x7901, 0x12d4: 0x7901, 0x12d5: 0x7901, 0x12d6: 0x7919, 0x12d7: 0x7919, 0x12d8: 0x7919, 0x12d9: 0x7919, 0x12da: 0x7931, 0x12db: 0x7931, 0x12dc: 0x7931, 0x12dd: 0x7931, 0x12de: 0x7949, 0x12df: 0x7949, 0x12e0: 0x7961, 0x12e1: 0x7961, 0x12e2: 0x7961, 0x12e3: 0x7961, 0x12e4: 0x7979, 0x12e5: 0x7979, 0x12e6: 0x7991, 0x12e7: 0x7991, 0x12e8: 0x7991, 0x12e9: 0x7991, 0x12ea: 0x79a9, 0x12eb: 0x79a9, 0x12ec: 0x79a9, 0x12ed: 0x79a9, 0x12ee: 0x79c1, 0x12ef: 0x79c1, 0x12f0: 0x79d9, 0x12f1: 0x79d9, 0x12f2: 0x0018, 0x12f3: 0x0018, 0x12f4: 0x0018, 0x12f5: 0x0018, 0x12f6: 0x0018, 0x12f7: 0x0018, 0x12f8: 0x0018, 0x12f9: 0x0018, 0x12fa: 0x0018, 0x12fb: 0x0018, 0x12fc: 0x0018, 0x12fd: 0x0018, 0x12fe: 0x0018, 0x12ff: 0x0018, // Block 0x4c, offset 0x1300 0x1300: 0x0018, 0x1301: 0x0018, 0x1302: 0x0040, 0x1303: 0x0040, 0x1304: 0x0040, 0x1305: 0x0040, 0x1306: 0x0040, 0x1307: 0x0040, 0x1308: 0x0040, 0x1309: 0x0040, 0x130a: 0x0040, 0x130b: 0x0040, 0x130c: 0x0040, 0x130d: 0x0040, 0x130e: 0x0040, 0x130f: 0x0040, 0x1310: 0x0040, 0x1311: 0x0040, 0x1312: 0x0040, 0x1313: 0x79f1, 0x1314: 0x79f1, 0x1315: 0x79f1, 0x1316: 0x79f1, 0x1317: 0x7a09, 0x1318: 0x7a09, 0x1319: 0x7a21, 0x131a: 0x7a21, 0x131b: 0x7a39, 0x131c: 0x7a39, 0x131d: 0x0479, 0x131e: 0x7a51, 0x131f: 0x7a51, 0x1320: 0x7a69, 0x1321: 0x7a69, 0x1322: 0x7a81, 0x1323: 0x7a81, 0x1324: 0x7a99, 0x1325: 0x7a99, 0x1326: 0x7a99, 0x1327: 0x7a99, 0x1328: 0x7ab1, 0x1329: 0x7ab1, 0x132a: 0x7ac9, 0x132b: 0x7ac9, 0x132c: 0x7af1, 0x132d: 0x7af1, 0x132e: 0x7b19, 0x132f: 0x7b19, 0x1330: 0x7b41, 0x1331: 0x7b41, 0x1332: 0x7b69, 0x1333: 0x7b69, 0x1334: 0x7b91, 0x1335: 0x7b91, 0x1336: 0x7bb9, 0x1337: 0x7bb9, 0x1338: 0x7bb9, 0x1339: 0x7be1, 0x133a: 0x7be1, 0x133b: 0x7be1, 0x133c: 0x7c09, 0x133d: 0x7c09, 0x133e: 0x7c09, 0x133f: 0x7c09, // Block 0x4d, offset 0x1340 0x1340: 0x85f9, 0x1341: 0x8621, 0x1342: 0x8649, 0x1343: 0x8671, 0x1344: 0x8699, 0x1345: 0x86c1, 0x1346: 0x86e9, 0x1347: 0x8711, 0x1348: 0x8739, 0x1349: 0x8761, 0x134a: 0x8789, 0x134b: 0x87b1, 0x134c: 0x87d9, 0x134d: 0x8801, 0x134e: 0x8829, 0x134f: 0x8851, 0x1350: 0x8879, 0x1351: 0x88a1, 0x1352: 0x88c9, 0x1353: 0x88f1, 0x1354: 0x8919, 0x1355: 0x8941, 0x1356: 0x8969, 0x1357: 0x8991, 0x1358: 0x89b9, 0x1359: 0x89e1, 0x135a: 0x8a09, 0x135b: 0x8a31, 0x135c: 0x8a59, 0x135d: 0x8a81, 0x135e: 0x8aaa, 0x135f: 0x8ada, 0x1360: 0x8b0a, 0x1361: 0x8b3a, 0x1362: 0x8b6a, 0x1363: 0x8b9a, 0x1364: 0x8bc9, 0x1365: 0x8bf1, 0x1366: 0x7c71, 0x1367: 0x8c19, 0x1368: 0x7be1, 0x1369: 0x7c99, 0x136a: 0x8c41, 0x136b: 0x8c69, 0x136c: 0x7d39, 0x136d: 0x8c91, 0x136e: 0x7d61, 0x136f: 0x7d89, 0x1370: 0x8cb9, 0x1371: 0x8ce1, 0x1372: 0x7e29, 0x1373: 0x8d09, 0x1374: 0x7e51, 0x1375: 0x7e79, 0x1376: 0x8d31, 0x1377: 0x8d59, 0x1378: 0x7ec9, 0x1379: 0x8d81, 0x137a: 0x7ef1, 0x137b: 0x7f19, 0x137c: 0x83a1, 0x137d: 0x83c9, 0x137e: 0x8441, 0x137f: 0x8469, // Block 0x4e, offset 0x1380 0x1380: 0x8491, 0x1381: 0x8531, 0x1382: 0x8559, 0x1383: 0x8581, 0x1384: 0x85a9, 0x1385: 0x8649, 0x1386: 0x8671, 0x1387: 0x8699, 0x1388: 0x8da9, 0x1389: 0x8739, 0x138a: 0x8dd1, 0x138b: 0x8df9, 0x138c: 0x8829, 0x138d: 0x8e21, 0x138e: 0x8851, 0x138f: 0x8879, 0x1390: 0x8a81, 0x1391: 0x8e49, 0x1392: 0x8e71, 0x1393: 0x89b9, 0x1394: 0x8e99, 0x1395: 0x89e1, 0x1396: 0x8a09, 0x1397: 0x7c21, 0x1398: 0x7c49, 0x1399: 0x8ec1, 0x139a: 0x7c71, 0x139b: 0x8ee9, 0x139c: 0x7cc1, 0x139d: 0x7ce9, 0x139e: 0x7d11, 0x139f: 0x7d39, 0x13a0: 0x8f11, 0x13a1: 0x7db1, 0x13a2: 0x7dd9, 0x13a3: 0x7e01, 0x13a4: 0x7e29, 0x13a5: 0x8f39, 0x13a6: 0x7ec9, 0x13a7: 0x7f41, 0x13a8: 0x7f69, 0x13a9: 0x7f91, 0x13aa: 0x7fb9, 0x13ab: 0x7fe1, 0x13ac: 0x8031, 0x13ad: 0x8059, 0x13ae: 0x8081, 0x13af: 0x80a9, 0x13b0: 0x80d1, 0x13b1: 0x80f9, 0x13b2: 0x8f61, 0x13b3: 0x8121, 0x13b4: 0x8149, 0x13b5: 0x8171, 0x13b6: 0x8199, 0x13b7: 0x81c1, 0x13b8: 0x81e9, 0x13b9: 0x8239, 0x13ba: 0x8261, 0x13bb: 0x8289, 0x13bc: 0x82b1, 0x13bd: 0x82d9, 0x13be: 0x8301, 0x13bf: 0x8329, // Block 0x4f, offset 0x13c0 0x13c0: 0x8351, 0x13c1: 0x8379, 0x13c2: 0x83f1, 0x13c3: 0x8419, 0x13c4: 0x84b9, 0x13c5: 0x84e1, 0x13c6: 0x8509, 0x13c7: 0x8531, 0x13c8: 0x8559, 0x13c9: 0x85d1, 0x13ca: 0x85f9, 0x13cb: 0x8621, 0x13cc: 0x8649, 0x13cd: 0x8f89, 0x13ce: 0x86c1, 0x13cf: 0x86e9, 0x13d0: 0x8711, 0x13d1: 0x8739, 0x13d2: 0x87b1, 0x13d3: 0x87d9, 0x13d4: 0x8801, 0x13d5: 0x8829, 0x13d6: 0x8fb1, 0x13d7: 0x88a1, 0x13d8: 0x88c9, 0x13d9: 0x8fd9, 0x13da: 0x8941, 0x13db: 0x8969, 0x13dc: 0x8991, 0x13dd: 0x89b9, 0x13de: 0x9001, 0x13df: 0x7c71, 0x13e0: 0x8ee9, 0x13e1: 0x7d39, 0x13e2: 0x8f11, 0x13e3: 0x7e29, 0x13e4: 0x8f39, 0x13e5: 0x7ec9, 0x13e6: 0x9029, 0x13e7: 0x80d1, 0x13e8: 0x9051, 0x13e9: 0x9079, 0x13ea: 0x90a1, 0x13eb: 0x8531, 0x13ec: 0x8559, 0x13ed: 0x8649, 0x13ee: 0x8829, 0x13ef: 0x8fb1, 0x13f0: 0x89b9, 0x13f1: 0x9001, 0x13f2: 0x90c9, 0x13f3: 0x9101, 0x13f4: 0x9139, 0x13f5: 0x9171, 0x13f6: 0x9199, 0x13f7: 0x91c1, 0x13f8: 0x91e9, 0x13f9: 0x9211, 0x13fa: 0x9239, 0x13fb: 0x9261, 0x13fc: 0x9289, 0x13fd: 0x92b1, 0x13fe: 0x92d9, 0x13ff: 0x9301, // Block 0x50, offset 0x1400 0x1400: 0x9329, 0x1401: 0x9351, 0x1402: 0x9379, 0x1403: 0x93a1, 0x1404: 0x93c9, 0x1405: 0x93f1, 0x1406: 0x9419, 0x1407: 0x9441, 0x1408: 0x9469, 0x1409: 0x9491, 0x140a: 0x94b9, 0x140b: 0x94e1, 0x140c: 0x9079, 0x140d: 0x9509, 0x140e: 0x9531, 0x140f: 0x9559, 0x1410: 0x9581, 0x1411: 0x9171, 0x1412: 0x9199, 0x1413: 0x91c1, 0x1414: 0x91e9, 0x1415: 0x9211, 0x1416: 0x9239, 0x1417: 0x9261, 0x1418: 0x9289, 0x1419: 0x92b1, 0x141a: 0x92d9, 0x141b: 0x9301, 0x141c: 0x9329, 0x141d: 0x9351, 0x141e: 0x9379, 0x141f: 0x93a1, 0x1420: 0x93c9, 0x1421: 0x93f1, 0x1422: 0x9419, 0x1423: 0x9441, 0x1424: 0x9469, 0x1425: 0x9491, 0x1426: 0x94b9, 0x1427: 0x94e1, 0x1428: 0x9079, 0x1429: 0x9509, 0x142a: 0x9531, 0x142b: 0x9559, 0x142c: 0x9581, 0x142d: 0x9491, 0x142e: 0x94b9, 0x142f: 0x94e1, 0x1430: 0x9079, 0x1431: 0x9051, 0x1432: 0x90a1, 0x1433: 0x8211, 0x1434: 0x8059, 0x1435: 0x8081, 0x1436: 0x80a9, 0x1437: 0x9491, 0x1438: 0x94b9, 0x1439: 0x94e1, 0x143a: 0x8211, 0x143b: 0x8239, 0x143c: 0x95a9, 0x143d: 0x95a9, 0x143e: 0x0018, 0x143f: 0x0018, // Block 0x51, offset 0x1440 0x1440: 0x0040, 0x1441: 0x0040, 0x1442: 0x0040, 0x1443: 0x0040, 0x1444: 0x0040, 0x1445: 0x0040, 0x1446: 0x0040, 0x1447: 0x0040, 0x1448: 0x0040, 0x1449: 0x0040, 0x144a: 0x0040, 0x144b: 0x0040, 0x144c: 0x0040, 0x144d: 0x0040, 0x144e: 0x0040, 0x144f: 0x0040, 0x1450: 0x95d1, 0x1451: 0x9609, 0x1452: 0x9609, 0x1453: 0x9641, 0x1454: 0x9679, 0x1455: 0x96b1, 0x1456: 0x96e9, 0x1457: 0x9721, 0x1458: 0x9759, 0x1459: 0x9759, 0x145a: 0x9791, 0x145b: 0x97c9, 0x145c: 0x9801, 0x145d: 0x9839, 0x145e: 0x9871, 0x145f: 0x98a9, 0x1460: 0x98a9, 0x1461: 0x98e1, 0x1462: 0x9919, 0x1463: 0x9919, 0x1464: 0x9951, 0x1465: 0x9951, 0x1466: 0x9989, 0x1467: 0x99c1, 0x1468: 0x99c1, 0x1469: 0x99f9, 0x146a: 0x9a31, 0x146b: 0x9a31, 0x146c: 0x9a69, 0x146d: 0x9a69, 0x146e: 0x9aa1, 0x146f: 0x9ad9, 0x1470: 0x9ad9, 0x1471: 0x9b11, 0x1472: 0x9b11, 0x1473: 0x9b49, 0x1474: 0x9b81, 0x1475: 0x9bb9, 0x1476: 0x9bf1, 0x1477: 0x9bf1, 0x1478: 0x9c29, 0x1479: 0x9c61, 0x147a: 0x9c99, 0x147b: 0x9cd1, 0x147c: 0x9d09, 0x147d: 0x9d09, 0x147e: 0x9d41, 0x147f: 0x9d79, // Block 0x52, offset 0x1480 0x1480: 0xa949, 0x1481: 0xa981, 0x1482: 0xa9b9, 0x1483: 0xa8a1, 0x1484: 0x9bb9, 0x1485: 0x9989, 0x1486: 0xa9f1, 0x1487: 0xaa29, 0x1488: 0x0040, 0x1489: 0x0040, 0x148a: 0x0040, 0x148b: 0x0040, 0x148c: 0x0040, 0x148d: 0x0040, 0x148e: 0x0040, 0x148f: 0x0040, 0x1490: 0x0040, 0x1491: 0x0040, 0x1492: 0x0040, 0x1493: 0x0040, 0x1494: 0x0040, 0x1495: 0x0040, 0x1496: 0x0040, 0x1497: 0x0040, 0x1498: 0x0040, 0x1499: 0x0040, 0x149a: 0x0040, 0x149b: 0x0040, 0x149c: 0x0040, 0x149d: 0x0040, 0x149e: 0x0040, 0x149f: 0x0040, 0x14a0: 0x0040, 0x14a1: 0x0040, 0x14a2: 0x0040, 0x14a3: 0x0040, 0x14a4: 0x0040, 0x14a5: 0x0040, 0x14a6: 0x0040, 0x14a7: 0x0040, 0x14a8: 0x0040, 0x14a9: 0x0040, 0x14aa: 0x0040, 0x14ab: 0x0040, 0x14ac: 0x0040, 0x14ad: 0x0040, 0x14ae: 0x0040, 0x14af: 0x0040, 0x14b0: 0xaa61, 0x14b1: 0xaa99, 0x14b2: 0xaad1, 0x14b3: 0xab19, 0x14b4: 0xab61, 0x14b5: 0xaba9, 0x14b6: 0xabf1, 0x14b7: 0xac39, 0x14b8: 0xac81, 0x14b9: 0xacc9, 0x14ba: 0xad02, 0x14bb: 0xae12, 0x14bc: 0xae91, 0x14bd: 0x0018, 0x14be: 0x0040, 0x14bf: 0x0040, // Block 0x53, offset 0x14c0 0x14c0: 0x13c0, 0x14c1: 0x13c0, 0x14c2: 0x13c0, 0x14c3: 0x13c0, 0x14c4: 0x13c0, 0x14c5: 0x13c0, 0x14c6: 0x13c0, 0x14c7: 0x13c0, 0x14c8: 0x13c0, 0x14c9: 0x13c0, 0x14ca: 0x13c0, 0x14cb: 0x13c0, 0x14cc: 0x13c0, 0x14cd: 0x13c0, 0x14ce: 0x13c0, 0x14cf: 0x13c0, 0x14d0: 0xaeda, 0x14d1: 0x7d55, 0x14d2: 0x0040, 0x14d3: 0xaeea, 0x14d4: 0x03c2, 0x14d5: 0xaefa, 0x14d6: 0xaf0a, 0x14d7: 0x7d75, 0x14d8: 0x7d95, 0x14d9: 0x0040, 0x14da: 0x0040, 0x14db: 0x0040, 0x14dc: 0x0040, 0x14dd: 0x0040, 0x14de: 0x0040, 0x14df: 0x0040, 0x14e0: 0x1308, 0x14e1: 0x1308, 0x14e2: 0x1308, 0x14e3: 0x1308, 0x14e4: 0x1308, 0x14e5: 0x1308, 0x14e6: 0x1308, 0x14e7: 0x1308, 0x14e8: 0x1308, 0x14e9: 0x1308, 0x14ea: 0x1308, 0x14eb: 0x1308, 0x14ec: 0x1308, 0x14ed: 0x1308, 0x14ee: 0x1308, 0x14ef: 0x1308, 0x14f0: 0x0040, 0x14f1: 0x7db5, 0x14f2: 0x7dd5, 0x14f3: 0xaf1a, 0x14f4: 0xaf1a, 0x14f5: 0x1fd2, 0x14f6: 0x1fe2, 0x14f7: 0xaf2a, 0x14f8: 0xaf3a, 0x14f9: 0x7df5, 0x14fa: 0x7e15, 0x14fb: 0x7e35, 0x14fc: 0x7df5, 0x14fd: 0x7e55, 0x14fe: 0x7e75, 0x14ff: 0x7e55, // Block 0x54, offset 0x1500 0x1500: 0x7e95, 0x1501: 0x7eb5, 0x1502: 0x7ed5, 0x1503: 0x7eb5, 0x1504: 0x7ef5, 0x1505: 0x0018, 0x1506: 0x0018, 0x1507: 0xaf4a, 0x1508: 0xaf5a, 0x1509: 0x7f16, 0x150a: 0x7f36, 0x150b: 0x7f56, 0x150c: 0x7f76, 0x150d: 0xaf1a, 0x150e: 0xaf1a, 0x150f: 0xaf1a, 0x1510: 0xaeda, 0x1511: 0x7f95, 0x1512: 0x0040, 0x1513: 0x0040, 0x1514: 0x03c2, 0x1515: 0xaeea, 0x1516: 0xaf0a, 0x1517: 0xaefa, 0x1518: 0x7fb5, 0x1519: 0x1fd2, 0x151a: 0x1fe2, 0x151b: 0xaf2a, 0x151c: 0xaf3a, 0x151d: 0x7e95, 0x151e: 0x7ef5, 0x151f: 0xaf6a, 0x1520: 0xaf7a, 0x1521: 0xaf8a, 0x1522: 0x1fb2, 0x1523: 0xaf99, 0x1524: 0xafaa, 0x1525: 0xafba, 0x1526: 0x1fc2, 0x1527: 0x0040, 0x1528: 0xafca, 0x1529: 0xafda, 0x152a: 0xafea, 0x152b: 0xaffa, 0x152c: 0x0040, 0x152d: 0x0040, 0x152e: 0x0040, 0x152f: 0x0040, 0x1530: 0x7fd6, 0x1531: 0xb009, 0x1532: 0x7ff6, 0x1533: 0x0008, 0x1534: 0x8016, 0x1535: 0x0040, 0x1536: 0x8036, 0x1537: 0xb031, 0x1538: 0x8056, 0x1539: 0xb059, 0x153a: 0x8076, 0x153b: 0xb081, 0x153c: 0x8096, 0x153d: 0xb0a9, 0x153e: 0x80b6, 0x153f: 0xb0d1, // Block 0x55, offset 0x1540 0x1540: 0xb0f9, 0x1541: 0xb111, 0x1542: 0xb111, 0x1543: 0xb129, 0x1544: 0xb129, 0x1545: 0xb141, 0x1546: 0xb141, 0x1547: 0xb159, 0x1548: 0xb159, 0x1549: 0xb171, 0x154a: 0xb171, 0x154b: 0xb171, 0x154c: 0xb171, 0x154d: 0xb189, 0x154e: 0xb189, 0x154f: 0xb1a1, 0x1550: 0xb1a1, 0x1551: 0xb1a1, 0x1552: 0xb1a1, 0x1553: 0xb1b9, 0x1554: 0xb1b9, 0x1555: 0xb1d1, 0x1556: 0xb1d1, 0x1557: 0xb1d1, 0x1558: 0xb1d1, 0x1559: 0xb1e9, 0x155a: 0xb1e9, 0x155b: 0xb1e9, 0x155c: 0xb1e9, 0x155d: 0xb201, 0x155e: 0xb201, 0x155f: 0xb201, 0x1560: 0xb201, 0x1561: 0xb219, 0x1562: 0xb219, 0x1563: 0xb219, 0x1564: 0xb219, 0x1565: 0xb231, 0x1566: 0xb231, 0x1567: 0xb231, 0x1568: 0xb231, 0x1569: 0xb249, 0x156a: 0xb249, 0x156b: 0xb261, 0x156c: 0xb261, 0x156d: 0xb279, 0x156e: 0xb279, 0x156f: 0xb291, 0x1570: 0xb291, 0x1571: 0xb2a9, 0x1572: 0xb2a9, 0x1573: 0xb2a9, 0x1574: 0xb2a9, 0x1575: 0xb2c1, 0x1576: 0xb2c1, 0x1577: 0xb2c1, 0x1578: 0xb2c1, 0x1579: 0xb2d9, 0x157a: 0xb2d9, 0x157b: 0xb2d9, 0x157c: 0xb2d9, 0x157d: 0xb2f1, 0x157e: 0xb2f1, 0x157f: 0xb2f1, // Block 0x56, offset 0x1580 0x1580: 0xb2f1, 0x1581: 0xb309, 0x1582: 0xb309, 0x1583: 0xb309, 0x1584: 0xb309, 0x1585: 0xb321, 0x1586: 0xb321, 0x1587: 0xb321, 0x1588: 0xb321, 0x1589: 0xb339, 0x158a: 0xb339, 0x158b: 0xb339, 0x158c: 0xb339, 0x158d: 0xb351, 0x158e: 0xb351, 0x158f: 0xb351, 0x1590: 0xb351, 0x1591: 0xb369, 0x1592: 0xb369, 0x1593: 0xb369, 0x1594: 0xb369, 0x1595: 0xb381, 0x1596: 0xb381, 0x1597: 0xb381, 0x1598: 0xb381, 0x1599: 0xb399, 0x159a: 0xb399, 0x159b: 0xb399, 0x159c: 0xb399, 0x159d: 0xb3b1, 0x159e: 0xb3b1, 0x159f: 0xb3b1, 0x15a0: 0xb3b1, 0x15a1: 0xb3c9, 0x15a2: 0xb3c9, 0x15a3: 0xb3c9, 0x15a4: 0xb3c9, 0x15a5: 0xb3e1, 0x15a6: 0xb3e1, 0x15a7: 0xb3e1, 0x15a8: 0xb3e1, 0x15a9: 0xb3f9, 0x15aa: 0xb3f9, 0x15ab: 0xb3f9, 0x15ac: 0xb3f9, 0x15ad: 0xb411, 0x15ae: 0xb411, 0x15af: 0x7ab1, 0x15b0: 0x7ab1, 0x15b1: 0xb429, 0x15b2: 0xb429, 0x15b3: 0xb429, 0x15b4: 0xb429, 0x15b5: 0xb441, 0x15b6: 0xb441, 0x15b7: 0xb469, 0x15b8: 0xb469, 0x15b9: 0xb491, 0x15ba: 0xb491, 0x15bb: 0xb4b9, 0x15bc: 0xb4b9, 0x15bd: 0x0040, 0x15be: 0x0040, 0x15bf: 0x03c0, // Block 0x57, offset 0x15c0 0x15c0: 0x0040, 0x15c1: 0xaefa, 0x15c2: 0xb4e2, 0x15c3: 0xaf6a, 0x15c4: 0xafda, 0x15c5: 0xafea, 0x15c6: 0xaf7a, 0x15c7: 0xb4f2, 0x15c8: 0x1fd2, 0x15c9: 0x1fe2, 0x15ca: 0xaf8a, 0x15cb: 0x1fb2, 0x15cc: 0xaeda, 0x15cd: 0xaf99, 0x15ce: 0x29d1, 0x15cf: 0xb502, 0x15d0: 0x1f41, 0x15d1: 0x00c9, 0x15d2: 0x0069, 0x15d3: 0x0079, 0x15d4: 0x1f51, 0x15d5: 0x1f61, 0x15d6: 0x1f71, 0x15d7: 0x1f81, 0x15d8: 0x1f91, 0x15d9: 0x1fa1, 0x15da: 0xaeea, 0x15db: 0x03c2, 0x15dc: 0xafaa, 0x15dd: 0x1fc2, 0x15de: 0xafba, 0x15df: 0xaf0a, 0x15e0: 0xaffa, 0x15e1: 0x0039, 0x15e2: 0x0ee9, 0x15e3: 0x1159, 0x15e4: 0x0ef9, 0x15e5: 0x0f09, 0x15e6: 0x1199, 0x15e7: 0x0f31, 0x15e8: 0x0249, 0x15e9: 0x0f41, 0x15ea: 0x0259, 0x15eb: 0x0f51, 0x15ec: 0x0359, 0x15ed: 0x0f61, 0x15ee: 0x0f71, 0x15ef: 0x00d9, 0x15f0: 0x0f99, 0x15f1: 0x2039, 0x15f2: 0x0269, 0x15f3: 0x01d9, 0x15f4: 0x0fa9, 0x15f5: 0x0fb9, 0x15f6: 0x1089, 0x15f7: 0x0279, 0x15f8: 0x0369, 0x15f9: 0x0289, 0x15fa: 0x13d1, 0x15fb: 0xaf4a, 0x15fc: 0xafca, 0x15fd: 0xaf5a, 0x15fe: 0xb512, 0x15ff: 0xaf1a, // Block 0x58, offset 0x1600 0x1600: 0x1caa, 0x1601: 0x0039, 0x1602: 0x0ee9, 0x1603: 0x1159, 0x1604: 0x0ef9, 0x1605: 0x0f09, 0x1606: 0x1199, 0x1607: 0x0f31, 0x1608: 0x0249, 0x1609: 0x0f41, 0x160a: 0x0259, 0x160b: 0x0f51, 0x160c: 0x0359, 0x160d: 0x0f61, 0x160e: 0x0f71, 0x160f: 0x00d9, 0x1610: 0x0f99, 0x1611: 0x2039, 0x1612: 0x0269, 0x1613: 0x01d9, 0x1614: 0x0fa9, 0x1615: 0x0fb9, 0x1616: 0x1089, 0x1617: 0x0279, 0x1618: 0x0369, 0x1619: 0x0289, 0x161a: 0x13d1, 0x161b: 0xaf2a, 0x161c: 0xb522, 0x161d: 0xaf3a, 0x161e: 0xb532, 0x161f: 0x80d5, 0x1620: 0x80f5, 0x1621: 0x29d1, 0x1622: 0x8115, 0x1623: 0x8115, 0x1624: 0x8135, 0x1625: 0x8155, 0x1626: 0x8175, 0x1627: 0x8195, 0x1628: 0x81b5, 0x1629: 0x81d5, 0x162a: 0x81f5, 0x162b: 0x8215, 0x162c: 0x8235, 0x162d: 0x8255, 0x162e: 0x8275, 0x162f: 0x8295, 0x1630: 0x82b5, 0x1631: 0x82d5, 0x1632: 0x82f5, 0x1633: 0x8315, 0x1634: 0x8335, 0x1635: 0x8355, 0x1636: 0x8375, 0x1637: 0x8395, 0x1638: 0x83b5, 0x1639: 0x83d5, 0x163a: 0x83f5, 0x163b: 0x8415, 0x163c: 0x81b5, 0x163d: 0x8435, 0x163e: 0x8455, 0x163f: 0x8215, // Block 0x59, offset 0x1640 0x1640: 0x8475, 0x1641: 0x8495, 0x1642: 0x84b5, 0x1643: 0x84d5, 0x1644: 0x84f5, 0x1645: 0x8515, 0x1646: 0x8535, 0x1647: 0x8555, 0x1648: 0x84d5, 0x1649: 0x8575, 0x164a: 0x84d5, 0x164b: 0x8595, 0x164c: 0x8595, 0x164d: 0x85b5, 0x164e: 0x85b5, 0x164f: 0x85d5, 0x1650: 0x8515, 0x1651: 0x85f5, 0x1652: 0x8615, 0x1653: 0x85f5, 0x1654: 0x8635, 0x1655: 0x8615, 0x1656: 0x8655, 0x1657: 0x8655, 0x1658: 0x8675, 0x1659: 0x8675, 0x165a: 0x8695, 0x165b: 0x8695, 0x165c: 0x8615, 0x165d: 0x8115, 0x165e: 0x86b5, 0x165f: 0x86d5, 0x1660: 0x0040, 0x1661: 0x86f5, 0x1662: 0x8715, 0x1663: 0x8735, 0x1664: 0x8755, 0x1665: 0x8735, 0x1666: 0x8775, 0x1667: 0x8795, 0x1668: 0x87b5, 0x1669: 0x87b5, 0x166a: 0x87d5, 0x166b: 0x87d5, 0x166c: 0x87f5, 0x166d: 0x87f5, 0x166e: 0x87d5, 0x166f: 0x87d5, 0x1670: 0x8815, 0x1671: 0x8835, 0x1672: 0x8855, 0x1673: 0x8875, 0x1674: 0x8895, 0x1675: 0x88b5, 0x1676: 0x88b5, 0x1677: 0x88b5, 0x1678: 0x88d5, 0x1679: 0x88d5, 0x167a: 0x88d5, 0x167b: 0x88d5, 0x167c: 0x87b5, 0x167d: 0x87b5, 0x167e: 0x87b5, 0x167f: 0x0040, // Block 0x5a, offset 0x1680 0x1680: 0x0040, 0x1681: 0x0040, 0x1682: 0x8715, 0x1683: 0x86f5, 0x1684: 0x88f5, 0x1685: 0x86f5, 0x1686: 0x8715, 0x1687: 0x86f5, 0x1688: 0x0040, 0x1689: 0x0040, 0x168a: 0x8915, 0x168b: 0x8715, 0x168c: 0x8935, 0x168d: 0x88f5, 0x168e: 0x8935, 0x168f: 0x8715, 0x1690: 0x0040, 0x1691: 0x0040, 0x1692: 0x8955, 0x1693: 0x8975, 0x1694: 0x8875, 0x1695: 0x8935, 0x1696: 0x88f5, 0x1697: 0x8935, 0x1698: 0x0040, 0x1699: 0x0040, 0x169a: 0x8995, 0x169b: 0x89b5, 0x169c: 0x8995, 0x169d: 0x0040, 0x169e: 0x0040, 0x169f: 0x0040, 0x16a0: 0xb541, 0x16a1: 0xb559, 0x16a2: 0xb571, 0x16a3: 0x89d6, 0x16a4: 0xb589, 0x16a5: 0xb5a1, 0x16a6: 0x89f5, 0x16a7: 0x0040, 0x16a8: 0x8a15, 0x16a9: 0x8a35, 0x16aa: 0x8a55, 0x16ab: 0x8a35, 0x16ac: 0x8a75, 0x16ad: 0x8a95, 0x16ae: 0x8ab5, 0x16af: 0x0040, 0x16b0: 0x0040, 0x16b1: 0x0040, 0x16b2: 0x0040, 0x16b3: 0x0040, 0x16b4: 0x0040, 0x16b5: 0x0040, 0x16b6: 0x0040, 0x16b7: 0x0040, 0x16b8: 0x0040, 0x16b9: 0x0340, 0x16ba: 0x0340, 0x16bb: 0x0340, 0x16bc: 0x0040, 0x16bd: 0x0040, 0x16be: 0x0040, 0x16bf: 0x0040, // Block 0x5b, offset 0x16c0 0x16c0: 0x0208, 0x16c1: 0x0208, 0x16c2: 0x0208, 0x16c3: 0x0208, 0x16c4: 0x0208, 0x16c5: 0x0408, 0x16c6: 0x0008, 0x16c7: 0x0408, 0x16c8: 0x0018, 0x16c9: 0x0408, 0x16ca: 0x0408, 0x16cb: 0x0008, 0x16cc: 0x0008, 0x16cd: 0x0108, 0x16ce: 0x0408, 0x16cf: 0x0408, 0x16d0: 0x0408, 0x16d1: 0x0408, 0x16d2: 0x0408, 0x16d3: 0x0208, 0x16d4: 0x0208, 0x16d5: 0x0208, 0x16d6: 0x0208, 0x16d7: 0x0108, 0x16d8: 0x0208, 0x16d9: 0x0208, 0x16da: 0x0208, 0x16db: 0x0208, 0x16dc: 0x0208, 0x16dd: 0x0408, 0x16de: 0x0208, 0x16df: 0x0208, 0x16e0: 0x0208, 0x16e1: 0x0408, 0x16e2: 0x0008, 0x16e3: 0x0008, 0x16e4: 0x0408, 0x16e5: 0x1308, 0x16e6: 0x1308, 0x16e7: 0x0040, 0x16e8: 0x0040, 0x16e9: 0x0040, 0x16ea: 0x0040, 0x16eb: 0x0218, 0x16ec: 0x0218, 0x16ed: 0x0218, 0x16ee: 0x0218, 0x16ef: 0x0418, 0x16f0: 0x0018, 0x16f1: 0x0018, 0x16f2: 0x0018, 0x16f3: 0x0018, 0x16f4: 0x0018, 0x16f5: 0x0018, 0x16f6: 0x0018, 0x16f7: 0x0040, 0x16f8: 0x0040, 0x16f9: 0x0040, 0x16fa: 0x0040, 0x16fb: 0x0040, 0x16fc: 0x0040, 0x16fd: 0x0040, 0x16fe: 0x0040, 0x16ff: 0x0040, // Block 0x5c, offset 0x1700 0x1700: 0x0208, 0x1701: 0x0408, 0x1702: 0x0208, 0x1703: 0x0408, 0x1704: 0x0408, 0x1705: 0x0408, 0x1706: 0x0208, 0x1707: 0x0208, 0x1708: 0x0208, 0x1709: 0x0408, 0x170a: 0x0208, 0x170b: 0x0208, 0x170c: 0x0408, 0x170d: 0x0208, 0x170e: 0x0408, 0x170f: 0x0408, 0x1710: 0x0208, 0x1711: 0x0408, 0x1712: 0x0040, 0x1713: 0x0040, 0x1714: 0x0040, 0x1715: 0x0040, 0x1716: 0x0040, 0x1717: 0x0040, 0x1718: 0x0040, 0x1719: 0x0018, 0x171a: 0x0018, 0x171b: 0x0018, 0x171c: 0x0018, 0x171d: 0x0040, 0x171e: 0x0040, 0x171f: 0x0040, 0x1720: 0x0040, 0x1721: 0x0040, 0x1722: 0x0040, 0x1723: 0x0040, 0x1724: 0x0040, 0x1725: 0x0040, 0x1726: 0x0040, 0x1727: 0x0040, 0x1728: 0x0040, 0x1729: 0x0418, 0x172a: 0x0418, 0x172b: 0x0418, 0x172c: 0x0418, 0x172d: 0x0218, 0x172e: 0x0218, 0x172f: 0x0018, 0x1730: 0x0040, 0x1731: 0x0040, 0x1732: 0x0040, 0x1733: 0x0040, 0x1734: 0x0040, 0x1735: 0x0040, 0x1736: 0x0040, 0x1737: 0x0040, 0x1738: 0x0040, 0x1739: 0x0040, 0x173a: 0x0040, 0x173b: 0x0040, 0x173c: 0x0040, 0x173d: 0x0040, 0x173e: 0x0040, 0x173f: 0x0040, // Block 0x5d, offset 0x1740 0x1740: 0x1308, 0x1741: 0x1308, 0x1742: 0x1008, 0x1743: 0x1008, 0x1744: 0x0040, 0x1745: 0x0008, 0x1746: 0x0008, 0x1747: 0x0008, 0x1748: 0x0008, 0x1749: 0x0008, 0x174a: 0x0008, 0x174b: 0x0008, 0x174c: 0x0008, 0x174d: 0x0040, 0x174e: 0x0040, 0x174f: 0x0008, 0x1750: 0x0008, 0x1751: 0x0040, 0x1752: 0x0040, 0x1753: 0x0008, 0x1754: 0x0008, 0x1755: 0x0008, 0x1756: 0x0008, 0x1757: 0x0008, 0x1758: 0x0008, 0x1759: 0x0008, 0x175a: 0x0008, 0x175b: 0x0008, 0x175c: 0x0008, 0x175d: 0x0008, 0x175e: 0x0008, 0x175f: 0x0008, 0x1760: 0x0008, 0x1761: 0x0008, 0x1762: 0x0008, 0x1763: 0x0008, 0x1764: 0x0008, 0x1765: 0x0008, 0x1766: 0x0008, 0x1767: 0x0008, 0x1768: 0x0008, 0x1769: 0x0040, 0x176a: 0x0008, 0x176b: 0x0008, 0x176c: 0x0008, 0x176d: 0x0008, 0x176e: 0x0008, 0x176f: 0x0008, 0x1770: 0x0008, 0x1771: 0x0040, 0x1772: 0x0008, 0x1773: 0x0008, 0x1774: 0x0040, 0x1775: 0x0008, 0x1776: 0x0008, 0x1777: 0x0008, 0x1778: 0x0008, 0x1779: 0x0008, 0x177a: 0x0040, 0x177b: 0x0040, 0x177c: 0x1308, 0x177d: 0x0008, 0x177e: 0x1008, 0x177f: 0x1008, // Block 0x5e, offset 0x1780 0x1780: 0x1308, 0x1781: 0x1008, 0x1782: 0x1008, 0x1783: 0x1008, 0x1784: 0x1008, 0x1785: 0x0040, 0x1786: 0x0040, 0x1787: 0x1008, 0x1788: 0x1008, 0x1789: 0x0040, 0x178a: 0x0040, 0x178b: 0x1008, 0x178c: 0x1008, 0x178d: 0x1808, 0x178e: 0x0040, 0x178f: 0x0040, 0x1790: 0x0008, 0x1791: 0x0040, 0x1792: 0x0040, 0x1793: 0x0040, 0x1794: 0x0040, 0x1795: 0x0040, 0x1796: 0x0040, 0x1797: 0x1008, 0x1798: 0x0040, 0x1799: 0x0040, 0x179a: 0x0040, 0x179b: 0x0040, 0x179c: 0x0040, 0x179d: 0x0008, 0x179e: 0x0008, 0x179f: 0x0008, 0x17a0: 0x0008, 0x17a1: 0x0008, 0x17a2: 0x1008, 0x17a3: 0x1008, 0x17a4: 0x0040, 0x17a5: 0x0040, 0x17a6: 0x1308, 0x17a7: 0x1308, 0x17a8: 0x1308, 0x17a9: 0x1308, 0x17aa: 0x1308, 0x17ab: 0x1308, 0x17ac: 0x1308, 0x17ad: 0x0040, 0x17ae: 0x0040, 0x17af: 0x0040, 0x17b0: 0x1308, 0x17b1: 0x1308, 0x17b2: 0x1308, 0x17b3: 0x1308, 0x17b4: 0x1308, 0x17b5: 0x0040, 0x17b6: 0x0040, 0x17b7: 0x0040, 0x17b8: 0x0040, 0x17b9: 0x0040, 0x17ba: 0x0040, 0x17bb: 0x0040, 0x17bc: 0x0040, 0x17bd: 0x0040, 0x17be: 0x0040, 0x17bf: 0x0040, // Block 0x5f, offset 0x17c0 0x17c0: 0x0039, 0x17c1: 0x0ee9, 0x17c2: 0x1159, 0x17c3: 0x0ef9, 0x17c4: 0x0f09, 0x17c5: 0x1199, 0x17c6: 0x0f31, 0x17c7: 0x0249, 0x17c8: 0x0f41, 0x17c9: 0x0259, 0x17ca: 0x0f51, 0x17cb: 0x0359, 0x17cc: 0x0f61, 0x17cd: 0x0f71, 0x17ce: 0x00d9, 0x17cf: 0x0f99, 0x17d0: 0x2039, 0x17d1: 0x0269, 0x17d2: 0x01d9, 0x17d3: 0x0fa9, 0x17d4: 0x0fb9, 0x17d5: 0x1089, 0x17d6: 0x0279, 0x17d7: 0x0369, 0x17d8: 0x0289, 0x17d9: 0x13d1, 0x17da: 0x0039, 0x17db: 0x0ee9, 0x17dc: 0x1159, 0x17dd: 0x0ef9, 0x17de: 0x0f09, 0x17df: 0x1199, 0x17e0: 0x0f31, 0x17e1: 0x0249, 0x17e2: 0x0f41, 0x17e3: 0x0259, 0x17e4: 0x0f51, 0x17e5: 0x0359, 0x17e6: 0x0f61, 0x17e7: 0x0f71, 0x17e8: 0x00d9, 0x17e9: 0x0f99, 0x17ea: 0x2039, 0x17eb: 0x0269, 0x17ec: 0x01d9, 0x17ed: 0x0fa9, 0x17ee: 0x0fb9, 0x17ef: 0x1089, 0x17f0: 0x0279, 0x17f1: 0x0369, 0x17f2: 0x0289, 0x17f3: 0x13d1, 0x17f4: 0x0039, 0x17f5: 0x0ee9, 0x17f6: 0x1159, 0x17f7: 0x0ef9, 0x17f8: 0x0f09, 0x17f9: 0x1199, 0x17fa: 0x0f31, 0x17fb: 0x0249, 0x17fc: 0x0f41, 0x17fd: 0x0259, 0x17fe: 0x0f51, 0x17ff: 0x0359, // Block 0x60, offset 0x1800 0x1800: 0x0f61, 0x1801: 0x0f71, 0x1802: 0x00d9, 0x1803: 0x0f99, 0x1804: 0x2039, 0x1805: 0x0269, 0x1806: 0x01d9, 0x1807: 0x0fa9, 0x1808: 0x0fb9, 0x1809: 0x1089, 0x180a: 0x0279, 0x180b: 0x0369, 0x180c: 0x0289, 0x180d: 0x13d1, 0x180e: 0x0039, 0x180f: 0x0ee9, 0x1810: 0x1159, 0x1811: 0x0ef9, 0x1812: 0x0f09, 0x1813: 0x1199, 0x1814: 0x0f31, 0x1815: 0x0040, 0x1816: 0x0f41, 0x1817: 0x0259, 0x1818: 0x0f51, 0x1819: 0x0359, 0x181a: 0x0f61, 0x181b: 0x0f71, 0x181c: 0x00d9, 0x181d: 0x0f99, 0x181e: 0x2039, 0x181f: 0x0269, 0x1820: 0x01d9, 0x1821: 0x0fa9, 0x1822: 0x0fb9, 0x1823: 0x1089, 0x1824: 0x0279, 0x1825: 0x0369, 0x1826: 0x0289, 0x1827: 0x13d1, 0x1828: 0x0039, 0x1829: 0x0ee9, 0x182a: 0x1159, 0x182b: 0x0ef9, 0x182c: 0x0f09, 0x182d: 0x1199, 0x182e: 0x0f31, 0x182f: 0x0249, 0x1830: 0x0f41, 0x1831: 0x0259, 0x1832: 0x0f51, 0x1833: 0x0359, 0x1834: 0x0f61, 0x1835: 0x0f71, 0x1836: 0x00d9, 0x1837: 0x0f99, 0x1838: 0x2039, 0x1839: 0x0269, 0x183a: 0x01d9, 0x183b: 0x0fa9, 0x183c: 0x0fb9, 0x183d: 0x1089, 0x183e: 0x0279, 0x183f: 0x0369, // Block 0x61, offset 0x1840 0x1840: 0x0289, 0x1841: 0x13d1, 0x1842: 0x0039, 0x1843: 0x0ee9, 0x1844: 0x1159, 0x1845: 0x0ef9, 0x1846: 0x0f09, 0x1847: 0x1199, 0x1848: 0x0f31, 0x1849: 0x0249, 0x184a: 0x0f41, 0x184b: 0x0259, 0x184c: 0x0f51, 0x184d: 0x0359, 0x184e: 0x0f61, 0x184f: 0x0f71, 0x1850: 0x00d9, 0x1851: 0x0f99, 0x1852: 0x2039, 0x1853: 0x0269, 0x1854: 0x01d9, 0x1855: 0x0fa9, 0x1856: 0x0fb9, 0x1857: 0x1089, 0x1858: 0x0279, 0x1859: 0x0369, 0x185a: 0x0289, 0x185b: 0x13d1, 0x185c: 0x0039, 0x185d: 0x0040, 0x185e: 0x1159, 0x185f: 0x0ef9, 0x1860: 0x0040, 0x1861: 0x0040, 0x1862: 0x0f31, 0x1863: 0x0040, 0x1864: 0x0040, 0x1865: 0x0259, 0x1866: 0x0f51, 0x1867: 0x0040, 0x1868: 0x0040, 0x1869: 0x0f71, 0x186a: 0x00d9, 0x186b: 0x0f99, 0x186c: 0x2039, 0x186d: 0x0040, 0x186e: 0x01d9, 0x186f: 0x0fa9, 0x1870: 0x0fb9, 0x1871: 0x1089, 0x1872: 0x0279, 0x1873: 0x0369, 0x1874: 0x0289, 0x1875: 0x13d1, 0x1876: 0x0039, 0x1877: 0x0ee9, 0x1878: 0x1159, 0x1879: 0x0ef9, 0x187a: 0x0040, 0x187b: 0x1199, 0x187c: 0x0040, 0x187d: 0x0249, 0x187e: 0x0f41, 0x187f: 0x0259, // Block 0x62, offset 0x1880 0x1880: 0x0f51, 0x1881: 0x0359, 0x1882: 0x0f61, 0x1883: 0x0f71, 0x1884: 0x0040, 0x1885: 0x0f99, 0x1886: 0x2039, 0x1887: 0x0269, 0x1888: 0x01d9, 0x1889: 0x0fa9, 0x188a: 0x0fb9, 0x188b: 0x1089, 0x188c: 0x0279, 0x188d: 0x0369, 0x188e: 0x0289, 0x188f: 0x13d1, 0x1890: 0x0039, 0x1891: 0x0ee9, 0x1892: 0x1159, 0x1893: 0x0ef9, 0x1894: 0x0f09, 0x1895: 0x1199, 0x1896: 0x0f31, 0x1897: 0x0249, 0x1898: 0x0f41, 0x1899: 0x0259, 0x189a: 0x0f51, 0x189b: 0x0359, 0x189c: 0x0f61, 0x189d: 0x0f71, 0x189e: 0x00d9, 0x189f: 0x0f99, 0x18a0: 0x2039, 0x18a1: 0x0269, 0x18a2: 0x01d9, 0x18a3: 0x0fa9, 0x18a4: 0x0fb9, 0x18a5: 0x1089, 0x18a6: 0x0279, 0x18a7: 0x0369, 0x18a8: 0x0289, 0x18a9: 0x13d1, 0x18aa: 0x0039, 0x18ab: 0x0ee9, 0x18ac: 0x1159, 0x18ad: 0x0ef9, 0x18ae: 0x0f09, 0x18af: 0x1199, 0x18b0: 0x0f31, 0x18b1: 0x0249, 0x18b2: 0x0f41, 0x18b3: 0x0259, 0x18b4: 0x0f51, 0x18b5: 0x0359, 0x18b6: 0x0f61, 0x18b7: 0x0f71, 0x18b8: 0x00d9, 0x18b9: 0x0f99, 0x18ba: 0x2039, 0x18bb: 0x0269, 0x18bc: 0x01d9, 0x18bd: 0x0fa9, 0x18be: 0x0fb9, 0x18bf: 0x1089, // Block 0x63, offset 0x18c0 0x18c0: 0x0279, 0x18c1: 0x0369, 0x18c2: 0x0289, 0x18c3: 0x13d1, 0x18c4: 0x0039, 0x18c5: 0x0ee9, 0x18c6: 0x0040, 0x18c7: 0x0ef9, 0x18c8: 0x0f09, 0x18c9: 0x1199, 0x18ca: 0x0f31, 0x18cb: 0x0040, 0x18cc: 0x0040, 0x18cd: 0x0259, 0x18ce: 0x0f51, 0x18cf: 0x0359, 0x18d0: 0x0f61, 0x18d1: 0x0f71, 0x18d2: 0x00d9, 0x18d3: 0x0f99, 0x18d4: 0x2039, 0x18d5: 0x0040, 0x18d6: 0x01d9, 0x18d7: 0x0fa9, 0x18d8: 0x0fb9, 0x18d9: 0x1089, 0x18da: 0x0279, 0x18db: 0x0369, 0x18dc: 0x0289, 0x18dd: 0x0040, 0x18de: 0x0039, 0x18df: 0x0ee9, 0x18e0: 0x1159, 0x18e1: 0x0ef9, 0x18e2: 0x0f09, 0x18e3: 0x1199, 0x18e4: 0x0f31, 0x18e5: 0x0249, 0x18e6: 0x0f41, 0x18e7: 0x0259, 0x18e8: 0x0f51, 0x18e9: 0x0359, 0x18ea: 0x0f61, 0x18eb: 0x0f71, 0x18ec: 0x00d9, 0x18ed: 0x0f99, 0x18ee: 0x2039, 0x18ef: 0x0269, 0x18f0: 0x01d9, 0x18f1: 0x0fa9, 0x18f2: 0x0fb9, 0x18f3: 0x1089, 0x18f4: 0x0279, 0x18f5: 0x0369, 0x18f6: 0x0289, 0x18f7: 0x13d1, 0x18f8: 0x0039, 0x18f9: 0x0ee9, 0x18fa: 0x0040, 0x18fb: 0x0ef9, 0x18fc: 0x0f09, 0x18fd: 0x1199, 0x18fe: 0x0f31, 0x18ff: 0x0040, // Block 0x64, offset 0x1900 0x1900: 0x0f41, 0x1901: 0x0259, 0x1902: 0x0f51, 0x1903: 0x0359, 0x1904: 0x0f61, 0x1905: 0x0040, 0x1906: 0x00d9, 0x1907: 0x0040, 0x1908: 0x0040, 0x1909: 0x0040, 0x190a: 0x01d9, 0x190b: 0x0fa9, 0x190c: 0x0fb9, 0x190d: 0x1089, 0x190e: 0x0279, 0x190f: 0x0369, 0x1910: 0x0289, 0x1911: 0x0040, 0x1912: 0x0039, 0x1913: 0x0ee9, 0x1914: 0x1159, 0x1915: 0x0ef9, 0x1916: 0x0f09, 0x1917: 0x1199, 0x1918: 0x0f31, 0x1919: 0x0249, 0x191a: 0x0f41, 0x191b: 0x0259, 0x191c: 0x0f51, 0x191d: 0x0359, 0x191e: 0x0f61, 0x191f: 0x0f71, 0x1920: 0x00d9, 0x1921: 0x0f99, 0x1922: 0x2039, 0x1923: 0x0269, 0x1924: 0x01d9, 0x1925: 0x0fa9, 0x1926: 0x0fb9, 0x1927: 0x1089, 0x1928: 0x0279, 0x1929: 0x0369, 0x192a: 0x0289, 0x192b: 0x13d1, 0x192c: 0x0039, 0x192d: 0x0ee9, 0x192e: 0x1159, 0x192f: 0x0ef9, 0x1930: 0x0f09, 0x1931: 0x1199, 0x1932: 0x0f31, 0x1933: 0x0249, 0x1934: 0x0f41, 0x1935: 0x0259, 0x1936: 0x0f51, 0x1937: 0x0359, 0x1938: 0x0f61, 0x1939: 0x0f71, 0x193a: 0x00d9, 0x193b: 0x0f99, 0x193c: 0x2039, 0x193d: 0x0269, 0x193e: 0x01d9, 0x193f: 0x0fa9, // Block 0x65, offset 0x1940 0x1940: 0x0fb9, 0x1941: 0x1089, 0x1942: 0x0279, 0x1943: 0x0369, 0x1944: 0x0289, 0x1945: 0x13d1, 0x1946: 0x0039, 0x1947: 0x0ee9, 0x1948: 0x1159, 0x1949: 0x0ef9, 0x194a: 0x0f09, 0x194b: 0x1199, 0x194c: 0x0f31, 0x194d: 0x0249, 0x194e: 0x0f41, 0x194f: 0x0259, 0x1950: 0x0f51, 0x1951: 0x0359, 0x1952: 0x0f61, 0x1953: 0x0f71, 0x1954: 0x00d9, 0x1955: 0x0f99, 0x1956: 0x2039, 0x1957: 0x0269, 0x1958: 0x01d9, 0x1959: 0x0fa9, 0x195a: 0x0fb9, 0x195b: 0x1089, 0x195c: 0x0279, 0x195d: 0x0369, 0x195e: 0x0289, 0x195f: 0x13d1, 0x1960: 0x0039, 0x1961: 0x0ee9, 0x1962: 0x1159, 0x1963: 0x0ef9, 0x1964: 0x0f09, 0x1965: 0x1199, 0x1966: 0x0f31, 0x1967: 0x0249, 0x1968: 0x0f41, 0x1969: 0x0259, 0x196a: 0x0f51, 0x196b: 0x0359, 0x196c: 0x0f61, 0x196d: 0x0f71, 0x196e: 0x00d9, 0x196f: 0x0f99, 0x1970: 0x2039, 0x1971: 0x0269, 0x1972: 0x01d9, 0x1973: 0x0fa9, 0x1974: 0x0fb9, 0x1975: 0x1089, 0x1976: 0x0279, 0x1977: 0x0369, 0x1978: 0x0289, 0x1979: 0x13d1, 0x197a: 0x0039, 0x197b: 0x0ee9, 0x197c: 0x1159, 0x197d: 0x0ef9, 0x197e: 0x0f09, 0x197f: 0x1199, // Block 0x66, offset 0x1980 0x1980: 0x0f31, 0x1981: 0x0249, 0x1982: 0x0f41, 0x1983: 0x0259, 0x1984: 0x0f51, 0x1985: 0x0359, 0x1986: 0x0f61, 0x1987: 0x0f71, 0x1988: 0x00d9, 0x1989: 0x0f99, 0x198a: 0x2039, 0x198b: 0x0269, 0x198c: 0x01d9, 0x198d: 0x0fa9, 0x198e: 0x0fb9, 0x198f: 0x1089, 0x1990: 0x0279, 0x1991: 0x0369, 0x1992: 0x0289, 0x1993: 0x13d1, 0x1994: 0x0039, 0x1995: 0x0ee9, 0x1996: 0x1159, 0x1997: 0x0ef9, 0x1998: 0x0f09, 0x1999: 0x1199, 0x199a: 0x0f31, 0x199b: 0x0249, 0x199c: 0x0f41, 0x199d: 0x0259, 0x199e: 0x0f51, 0x199f: 0x0359, 0x19a0: 0x0f61, 0x19a1: 0x0f71, 0x19a2: 0x00d9, 0x19a3: 0x0f99, 0x19a4: 0x2039, 0x19a5: 0x0269, 0x19a6: 0x01d9, 0x19a7: 0x0fa9, 0x19a8: 0x0fb9, 0x19a9: 0x1089, 0x19aa: 0x0279, 0x19ab: 0x0369, 0x19ac: 0x0289, 0x19ad: 0x13d1, 0x19ae: 0x0039, 0x19af: 0x0ee9, 0x19b0: 0x1159, 0x19b1: 0x0ef9, 0x19b2: 0x0f09, 0x19b3: 0x1199, 0x19b4: 0x0f31, 0x19b5: 0x0249, 0x19b6: 0x0f41, 0x19b7: 0x0259, 0x19b8: 0x0f51, 0x19b9: 0x0359, 0x19ba: 0x0f61, 0x19bb: 0x0f71, 0x19bc: 0x00d9, 0x19bd: 0x0f99, 0x19be: 0x2039, 0x19bf: 0x0269, // Block 0x67, offset 0x19c0 0x19c0: 0x01d9, 0x19c1: 0x0fa9, 0x19c2: 0x0fb9, 0x19c3: 0x1089, 0x19c4: 0x0279, 0x19c5: 0x0369, 0x19c6: 0x0289, 0x19c7: 0x13d1, 0x19c8: 0x0039, 0x19c9: 0x0ee9, 0x19ca: 0x1159, 0x19cb: 0x0ef9, 0x19cc: 0x0f09, 0x19cd: 0x1199, 0x19ce: 0x0f31, 0x19cf: 0x0249, 0x19d0: 0x0f41, 0x19d1: 0x0259, 0x19d2: 0x0f51, 0x19d3: 0x0359, 0x19d4: 0x0f61, 0x19d5: 0x0f71, 0x19d6: 0x00d9, 0x19d7: 0x0f99, 0x19d8: 0x2039, 0x19d9: 0x0269, 0x19da: 0x01d9, 0x19db: 0x0fa9, 0x19dc: 0x0fb9, 0x19dd: 0x1089, 0x19de: 0x0279, 0x19df: 0x0369, 0x19e0: 0x0289, 0x19e1: 0x13d1, 0x19e2: 0x0039, 0x19e3: 0x0ee9, 0x19e4: 0x1159, 0x19e5: 0x0ef9, 0x19e6: 0x0f09, 0x19e7: 0x1199, 0x19e8: 0x0f31, 0x19e9: 0x0249, 0x19ea: 0x0f41, 0x19eb: 0x0259, 0x19ec: 0x0f51, 0x19ed: 0x0359, 0x19ee: 0x0f61, 0x19ef: 0x0f71, 0x19f0: 0x00d9, 0x19f1: 0x0f99, 0x19f2: 0x2039, 0x19f3: 0x0269, 0x19f4: 0x01d9, 0x19f5: 0x0fa9, 0x19f6: 0x0fb9, 0x19f7: 0x1089, 0x19f8: 0x0279, 0x19f9: 0x0369, 0x19fa: 0x0289, 0x19fb: 0x13d1, 0x19fc: 0x0039, 0x19fd: 0x0ee9, 0x19fe: 0x1159, 0x19ff: 0x0ef9, // Block 0x68, offset 0x1a00 0x1a00: 0x0f09, 0x1a01: 0x1199, 0x1a02: 0x0f31, 0x1a03: 0x0249, 0x1a04: 0x0f41, 0x1a05: 0x0259, 0x1a06: 0x0f51, 0x1a07: 0x0359, 0x1a08: 0x0f61, 0x1a09: 0x0f71, 0x1a0a: 0x00d9, 0x1a0b: 0x0f99, 0x1a0c: 0x2039, 0x1a0d: 0x0269, 0x1a0e: 0x01d9, 0x1a0f: 0x0fa9, 0x1a10: 0x0fb9, 0x1a11: 0x1089, 0x1a12: 0x0279, 0x1a13: 0x0369, 0x1a14: 0x0289, 0x1a15: 0x13d1, 0x1a16: 0x0039, 0x1a17: 0x0ee9, 0x1a18: 0x1159, 0x1a19: 0x0ef9, 0x1a1a: 0x0f09, 0x1a1b: 0x1199, 0x1a1c: 0x0f31, 0x1a1d: 0x0249, 0x1a1e: 0x0f41, 0x1a1f: 0x0259, 0x1a20: 0x0f51, 0x1a21: 0x0359, 0x1a22: 0x0f61, 0x1a23: 0x0f71, 0x1a24: 0x00d9, 0x1a25: 0x0f99, 0x1a26: 0x2039, 0x1a27: 0x0269, 0x1a28: 0x01d9, 0x1a29: 0x0fa9, 0x1a2a: 0x0fb9, 0x1a2b: 0x1089, 0x1a2c: 0x0279, 0x1a2d: 0x0369, 0x1a2e: 0x0289, 0x1a2f: 0x13d1, 0x1a30: 0x0039, 0x1a31: 0x0ee9, 0x1a32: 0x1159, 0x1a33: 0x0ef9, 0x1a34: 0x0f09, 0x1a35: 0x1199, 0x1a36: 0x0f31, 0x1a37: 0x0249, 0x1a38: 0x0f41, 0x1a39: 0x0259, 0x1a3a: 0x0f51, 0x1a3b: 0x0359, 0x1a3c: 0x0f61, 0x1a3d: 0x0f71, 0x1a3e: 0x00d9, 0x1a3f: 0x0f99, // Block 0x69, offset 0x1a40 0x1a40: 0x2039, 0x1a41: 0x0269, 0x1a42: 0x01d9, 0x1a43: 0x0fa9, 0x1a44: 0x0fb9, 0x1a45: 0x1089, 0x1a46: 0x0279, 0x1a47: 0x0369, 0x1a48: 0x0289, 0x1a49: 0x13d1, 0x1a4a: 0x0039, 0x1a4b: 0x0ee9, 0x1a4c: 0x1159, 0x1a4d: 0x0ef9, 0x1a4e: 0x0f09, 0x1a4f: 0x1199, 0x1a50: 0x0f31, 0x1a51: 0x0249, 0x1a52: 0x0f41, 0x1a53: 0x0259, 0x1a54: 0x0f51, 0x1a55: 0x0359, 0x1a56: 0x0f61, 0x1a57: 0x0f71, 0x1a58: 0x00d9, 0x1a59: 0x0f99, 0x1a5a: 0x2039, 0x1a5b: 0x0269, 0x1a5c: 0x01d9, 0x1a5d: 0x0fa9, 0x1a5e: 0x0fb9, 0x1a5f: 0x1089, 0x1a60: 0x0279, 0x1a61: 0x0369, 0x1a62: 0x0289, 0x1a63: 0x13d1, 0x1a64: 0xba81, 0x1a65: 0xba99, 0x1a66: 0x0040, 0x1a67: 0x0040, 0x1a68: 0xbab1, 0x1a69: 0x1099, 0x1a6a: 0x10b1, 0x1a6b: 0x10c9, 0x1a6c: 0xbac9, 0x1a6d: 0xbae1, 0x1a6e: 0xbaf9, 0x1a6f: 0x1429, 0x1a70: 0x1a31, 0x1a71: 0xbb11, 0x1a72: 0xbb29, 0x1a73: 0xbb41, 0x1a74: 0xbb59, 0x1a75: 0xbb71, 0x1a76: 0xbb89, 0x1a77: 0x2109, 0x1a78: 0x1111, 0x1a79: 0x1429, 0x1a7a: 0xbba1, 0x1a7b: 0xbbb9, 0x1a7c: 0xbbd1, 0x1a7d: 0x10e1, 0x1a7e: 0x10f9, 0x1a7f: 0xbbe9, // Block 0x6a, offset 0x1a80 0x1a80: 0x2079, 0x1a81: 0xbc01, 0x1a82: 0xbab1, 0x1a83: 0x1099, 0x1a84: 0x10b1, 0x1a85: 0x10c9, 0x1a86: 0xbac9, 0x1a87: 0xbae1, 0x1a88: 0xbaf9, 0x1a89: 0x1429, 0x1a8a: 0x1a31, 0x1a8b: 0xbb11, 0x1a8c: 0xbb29, 0x1a8d: 0xbb41, 0x1a8e: 0xbb59, 0x1a8f: 0xbb71, 0x1a90: 0xbb89, 0x1a91: 0x2109, 0x1a92: 0x1111, 0x1a93: 0xbba1, 0x1a94: 0xbba1, 0x1a95: 0xbbb9, 0x1a96: 0xbbd1, 0x1a97: 0x10e1, 0x1a98: 0x10f9, 0x1a99: 0xbbe9, 0x1a9a: 0x2079, 0x1a9b: 0xbc21, 0x1a9c: 0xbac9, 0x1a9d: 0x1429, 0x1a9e: 0xbb11, 0x1a9f: 0x10e1, 0x1aa0: 0x1111, 0x1aa1: 0x2109, 0x1aa2: 0xbab1, 0x1aa3: 0x1099, 0x1aa4: 0x10b1, 0x1aa5: 0x10c9, 0x1aa6: 0xbac9, 0x1aa7: 0xbae1, 0x1aa8: 0xbaf9, 0x1aa9: 0x1429, 0x1aaa: 0x1a31, 0x1aab: 0xbb11, 0x1aac: 0xbb29, 0x1aad: 0xbb41, 0x1aae: 0xbb59, 0x1aaf: 0xbb71, 0x1ab0: 0xbb89, 0x1ab1: 0x2109, 0x1ab2: 0x1111, 0x1ab3: 0x1429, 0x1ab4: 0xbba1, 0x1ab5: 0xbbb9, 0x1ab6: 0xbbd1, 0x1ab7: 0x10e1, 0x1ab8: 0x10f9, 0x1ab9: 0xbbe9, 0x1aba: 0x2079, 0x1abb: 0xbc01, 0x1abc: 0xbab1, 0x1abd: 0x1099, 0x1abe: 0x10b1, 0x1abf: 0x10c9, // Block 0x6b, offset 0x1ac0 0x1ac0: 0xbac9, 0x1ac1: 0xbae1, 0x1ac2: 0xbaf9, 0x1ac3: 0x1429, 0x1ac4: 0x1a31, 0x1ac5: 0xbb11, 0x1ac6: 0xbb29, 0x1ac7: 0xbb41, 0x1ac8: 0xbb59, 0x1ac9: 0xbb71, 0x1aca: 0xbb89, 0x1acb: 0x2109, 0x1acc: 0x1111, 0x1acd: 0xbba1, 0x1ace: 0xbba1, 0x1acf: 0xbbb9, 0x1ad0: 0xbbd1, 0x1ad1: 0x10e1, 0x1ad2: 0x10f9, 0x1ad3: 0xbbe9, 0x1ad4: 0x2079, 0x1ad5: 0xbc21, 0x1ad6: 0xbac9, 0x1ad7: 0x1429, 0x1ad8: 0xbb11, 0x1ad9: 0x10e1, 0x1ada: 0x1111, 0x1adb: 0x2109, 0x1adc: 0xbab1, 0x1add: 0x1099, 0x1ade: 0x10b1, 0x1adf: 0x10c9, 0x1ae0: 0xbac9, 0x1ae1: 0xbae1, 0x1ae2: 0xbaf9, 0x1ae3: 0x1429, 0x1ae4: 0x1a31, 0x1ae5: 0xbb11, 0x1ae6: 0xbb29, 0x1ae7: 0xbb41, 0x1ae8: 0xbb59, 0x1ae9: 0xbb71, 0x1aea: 0xbb89, 0x1aeb: 0x2109, 0x1aec: 0x1111, 0x1aed: 0x1429, 0x1aee: 0xbba1, 0x1aef: 0xbbb9, 0x1af0: 0xbbd1, 0x1af1: 0x10e1, 0x1af2: 0x10f9, 0x1af3: 0xbbe9, 0x1af4: 0x2079, 0x1af5: 0xbc01, 0x1af6: 0xbab1, 0x1af7: 0x1099, 0x1af8: 0x10b1, 0x1af9: 0x10c9, 0x1afa: 0xbac9, 0x1afb: 0xbae1, 0x1afc: 0xbaf9, 0x1afd: 0x1429, 0x1afe: 0x1a31, 0x1aff: 0xbb11, // Block 0x6c, offset 0x1b00 0x1b00: 0xbb29, 0x1b01: 0xbb41, 0x1b02: 0xbb59, 0x1b03: 0xbb71, 0x1b04: 0xbb89, 0x1b05: 0x2109, 0x1b06: 0x1111, 0x1b07: 0xbba1, 0x1b08: 0xbba1, 0x1b09: 0xbbb9, 0x1b0a: 0xbbd1, 0x1b0b: 0x10e1, 0x1b0c: 0x10f9, 0x1b0d: 0xbbe9, 0x1b0e: 0x2079, 0x1b0f: 0xbc21, 0x1b10: 0xbac9, 0x1b11: 0x1429, 0x1b12: 0xbb11, 0x1b13: 0x10e1, 0x1b14: 0x1111, 0x1b15: 0x2109, 0x1b16: 0xbab1, 0x1b17: 0x1099, 0x1b18: 0x10b1, 0x1b19: 0x10c9, 0x1b1a: 0xbac9, 0x1b1b: 0xbae1, 0x1b1c: 0xbaf9, 0x1b1d: 0x1429, 0x1b1e: 0x1a31, 0x1b1f: 0xbb11, 0x1b20: 0xbb29, 0x1b21: 0xbb41, 0x1b22: 0xbb59, 0x1b23: 0xbb71, 0x1b24: 0xbb89, 0x1b25: 0x2109, 0x1b26: 0x1111, 0x1b27: 0x1429, 0x1b28: 0xbba1, 0x1b29: 0xbbb9, 0x1b2a: 0xbbd1, 0x1b2b: 0x10e1, 0x1b2c: 0x10f9, 0x1b2d: 0xbbe9, 0x1b2e: 0x2079, 0x1b2f: 0xbc01, 0x1b30: 0xbab1, 0x1b31: 0x1099, 0x1b32: 0x10b1, 0x1b33: 0x10c9, 0x1b34: 0xbac9, 0x1b35: 0xbae1, 0x1b36: 0xbaf9, 0x1b37: 0x1429, 0x1b38: 0x1a31, 0x1b39: 0xbb11, 0x1b3a: 0xbb29, 0x1b3b: 0xbb41, 0x1b3c: 0xbb59, 0x1b3d: 0xbb71, 0x1b3e: 0xbb89, 0x1b3f: 0x2109, // Block 0x6d, offset 0x1b40 0x1b40: 0x1111, 0x1b41: 0xbba1, 0x1b42: 0xbba1, 0x1b43: 0xbbb9, 0x1b44: 0xbbd1, 0x1b45: 0x10e1, 0x1b46: 0x10f9, 0x1b47: 0xbbe9, 0x1b48: 0x2079, 0x1b49: 0xbc21, 0x1b4a: 0xbac9, 0x1b4b: 0x1429, 0x1b4c: 0xbb11, 0x1b4d: 0x10e1, 0x1b4e: 0x1111, 0x1b4f: 0x2109, 0x1b50: 0xbab1, 0x1b51: 0x1099, 0x1b52: 0x10b1, 0x1b53: 0x10c9, 0x1b54: 0xbac9, 0x1b55: 0xbae1, 0x1b56: 0xbaf9, 0x1b57: 0x1429, 0x1b58: 0x1a31, 0x1b59: 0xbb11, 0x1b5a: 0xbb29, 0x1b5b: 0xbb41, 0x1b5c: 0xbb59, 0x1b5d: 0xbb71, 0x1b5e: 0xbb89, 0x1b5f: 0x2109, 0x1b60: 0x1111, 0x1b61: 0x1429, 0x1b62: 0xbba1, 0x1b63: 0xbbb9, 0x1b64: 0xbbd1, 0x1b65: 0x10e1, 0x1b66: 0x10f9, 0x1b67: 0xbbe9, 0x1b68: 0x2079, 0x1b69: 0xbc01, 0x1b6a: 0xbab1, 0x1b6b: 0x1099, 0x1b6c: 0x10b1, 0x1b6d: 0x10c9, 0x1b6e: 0xbac9, 0x1b6f: 0xbae1, 0x1b70: 0xbaf9, 0x1b71: 0x1429, 0x1b72: 0x1a31, 0x1b73: 0xbb11, 0x1b74: 0xbb29, 0x1b75: 0xbb41, 0x1b76: 0xbb59, 0x1b77: 0xbb71, 0x1b78: 0xbb89, 0x1b79: 0x2109, 0x1b7a: 0x1111, 0x1b7b: 0xbba1, 0x1b7c: 0xbba1, 0x1b7d: 0xbbb9, 0x1b7e: 0xbbd1, 0x1b7f: 0x10e1, // Block 0x6e, offset 0x1b80 0x1b80: 0x10f9, 0x1b81: 0xbbe9, 0x1b82: 0x2079, 0x1b83: 0xbc21, 0x1b84: 0xbac9, 0x1b85: 0x1429, 0x1b86: 0xbb11, 0x1b87: 0x10e1, 0x1b88: 0x1111, 0x1b89: 0x2109, 0x1b8a: 0xbc41, 0x1b8b: 0xbc41, 0x1b8c: 0x0040, 0x1b8d: 0x0040, 0x1b8e: 0x1f41, 0x1b8f: 0x00c9, 0x1b90: 0x0069, 0x1b91: 0x0079, 0x1b92: 0x1f51, 0x1b93: 0x1f61, 0x1b94: 0x1f71, 0x1b95: 0x1f81, 0x1b96: 0x1f91, 0x1b97: 0x1fa1, 0x1b98: 0x1f41, 0x1b99: 0x00c9, 0x1b9a: 0x0069, 0x1b9b: 0x0079, 0x1b9c: 0x1f51, 0x1b9d: 0x1f61, 0x1b9e: 0x1f71, 0x1b9f: 0x1f81, 0x1ba0: 0x1f91, 0x1ba1: 0x1fa1, 0x1ba2: 0x1f41, 0x1ba3: 0x00c9, 0x1ba4: 0x0069, 0x1ba5: 0x0079, 0x1ba6: 0x1f51, 0x1ba7: 0x1f61, 0x1ba8: 0x1f71, 0x1ba9: 0x1f81, 0x1baa: 0x1f91, 0x1bab: 0x1fa1, 0x1bac: 0x1f41, 0x1bad: 0x00c9, 0x1bae: 0x0069, 0x1baf: 0x0079, 0x1bb0: 0x1f51, 0x1bb1: 0x1f61, 0x1bb2: 0x1f71, 0x1bb3: 0x1f81, 0x1bb4: 0x1f91, 0x1bb5: 0x1fa1, 0x1bb6: 0x1f41, 0x1bb7: 0x00c9, 0x1bb8: 0x0069, 0x1bb9: 0x0079, 0x1bba: 0x1f51, 0x1bbb: 0x1f61, 0x1bbc: 0x1f71, 0x1bbd: 0x1f81, 0x1bbe: 0x1f91, 0x1bbf: 0x1fa1, // Block 0x6f, offset 0x1bc0 0x1bc0: 0xe115, 0x1bc1: 0xe115, 0x1bc2: 0xe135, 0x1bc3: 0xe135, 0x1bc4: 0xe115, 0x1bc5: 0xe115, 0x1bc6: 0xe175, 0x1bc7: 0xe175, 0x1bc8: 0xe115, 0x1bc9: 0xe115, 0x1bca: 0xe135, 0x1bcb: 0xe135, 0x1bcc: 0xe115, 0x1bcd: 0xe115, 0x1bce: 0xe1f5, 0x1bcf: 0xe1f5, 0x1bd0: 0xe115, 0x1bd1: 0xe115, 0x1bd2: 0xe135, 0x1bd3: 0xe135, 0x1bd4: 0xe115, 0x1bd5: 0xe115, 0x1bd6: 0xe175, 0x1bd7: 0xe175, 0x1bd8: 0xe115, 0x1bd9: 0xe115, 0x1bda: 0xe135, 0x1bdb: 0xe135, 0x1bdc: 0xe115, 0x1bdd: 0xe115, 0x1bde: 0x8b05, 0x1bdf: 0x8b05, 0x1be0: 0x04b5, 0x1be1: 0x04b5, 0x1be2: 0x0208, 0x1be3: 0x0208, 0x1be4: 0x0208, 0x1be5: 0x0208, 0x1be6: 0x0208, 0x1be7: 0x0208, 0x1be8: 0x0208, 0x1be9: 0x0208, 0x1bea: 0x0208, 0x1beb: 0x0208, 0x1bec: 0x0208, 0x1bed: 0x0208, 0x1bee: 0x0208, 0x1bef: 0x0208, 0x1bf0: 0x0208, 0x1bf1: 0x0208, 0x1bf2: 0x0208, 0x1bf3: 0x0208, 0x1bf4: 0x0208, 0x1bf5: 0x0208, 0x1bf6: 0x0208, 0x1bf7: 0x0208, 0x1bf8: 0x0208, 0x1bf9: 0x0208, 0x1bfa: 0x0208, 0x1bfb: 0x0208, 0x1bfc: 0x0208, 0x1bfd: 0x0208, 0x1bfe: 0x0208, 0x1bff: 0x0208, // Block 0x70, offset 0x1c00 0x1c00: 0xb189, 0x1c01: 0xb1a1, 0x1c02: 0xb201, 0x1c03: 0xb249, 0x1c04: 0x0040, 0x1c05: 0xb411, 0x1c06: 0xb291, 0x1c07: 0xb219, 0x1c08: 0xb309, 0x1c09: 0xb429, 0x1c0a: 0xb399, 0x1c0b: 0xb3b1, 0x1c0c: 0xb3c9, 0x1c0d: 0xb3e1, 0x1c0e: 0xb2a9, 0x1c0f: 0xb339, 0x1c10: 0xb369, 0x1c11: 0xb2d9, 0x1c12: 0xb381, 0x1c13: 0xb279, 0x1c14: 0xb2c1, 0x1c15: 0xb1d1, 0x1c16: 0xb1e9, 0x1c17: 0xb231, 0x1c18: 0xb261, 0x1c19: 0xb2f1, 0x1c1a: 0xb321, 0x1c1b: 0xb351, 0x1c1c: 0xbc59, 0x1c1d: 0x7949, 0x1c1e: 0xbc71, 0x1c1f: 0xbc89, 0x1c20: 0x0040, 0x1c21: 0xb1a1, 0x1c22: 0xb201, 0x1c23: 0x0040, 0x1c24: 0xb3f9, 0x1c25: 0x0040, 0x1c26: 0x0040, 0x1c27: 0xb219, 0x1c28: 0x0040, 0x1c29: 0xb429, 0x1c2a: 0xb399, 0x1c2b: 0xb3b1, 0x1c2c: 0xb3c9, 0x1c2d: 0xb3e1, 0x1c2e: 0xb2a9, 0x1c2f: 0xb339, 0x1c30: 0xb369, 0x1c31: 0xb2d9, 0x1c32: 0xb381, 0x1c33: 0x0040, 0x1c34: 0xb2c1, 0x1c35: 0xb1d1, 0x1c36: 0xb1e9, 0x1c37: 0xb231, 0x1c38: 0x0040, 0x1c39: 0xb2f1, 0x1c3a: 0x0040, 0x1c3b: 0xb351, 0x1c3c: 0x0040, 0x1c3d: 0x0040, 0x1c3e: 0x0040, 0x1c3f: 0x0040, // Block 0x71, offset 0x1c40 0x1c40: 0x0040, 0x1c41: 0x0040, 0x1c42: 0xb201, 0x1c43: 0x0040, 0x1c44: 0x0040, 0x1c45: 0x0040, 0x1c46: 0x0040, 0x1c47: 0xb219, 0x1c48: 0x0040, 0x1c49: 0xb429, 0x1c4a: 0x0040, 0x1c4b: 0xb3b1, 0x1c4c: 0x0040, 0x1c4d: 0xb3e1, 0x1c4e: 0xb2a9, 0x1c4f: 0xb339, 0x1c50: 0x0040, 0x1c51: 0xb2d9, 0x1c52: 0xb381, 0x1c53: 0x0040, 0x1c54: 0xb2c1, 0x1c55: 0x0040, 0x1c56: 0x0040, 0x1c57: 0xb231, 0x1c58: 0x0040, 0x1c59: 0xb2f1, 0x1c5a: 0x0040, 0x1c5b: 0xb351, 0x1c5c: 0x0040, 0x1c5d: 0x7949, 0x1c5e: 0x0040, 0x1c5f: 0xbc89, 0x1c60: 0x0040, 0x1c61: 0xb1a1, 0x1c62: 0xb201, 0x1c63: 0x0040, 0x1c64: 0xb3f9, 0x1c65: 0x0040, 0x1c66: 0x0040, 0x1c67: 0xb219, 0x1c68: 0xb309, 0x1c69: 0xb429, 0x1c6a: 0xb399, 0x1c6b: 0x0040, 0x1c6c: 0xb3c9, 0x1c6d: 0xb3e1, 0x1c6e: 0xb2a9, 0x1c6f: 0xb339, 0x1c70: 0xb369, 0x1c71: 0xb2d9, 0x1c72: 0xb381, 0x1c73: 0x0040, 0x1c74: 0xb2c1, 0x1c75: 0xb1d1, 0x1c76: 0xb1e9, 0x1c77: 0xb231, 0x1c78: 0x0040, 0x1c79: 0xb2f1, 0x1c7a: 0xb321, 0x1c7b: 0xb351, 0x1c7c: 0xbc59, 0x1c7d: 0x0040, 0x1c7e: 0xbc71, 0x1c7f: 0x0040, // Block 0x72, offset 0x1c80 0x1c80: 0xb189, 0x1c81: 0xb1a1, 0x1c82: 0xb201, 0x1c83: 0xb249, 0x1c84: 0xb3f9, 0x1c85: 0xb411, 0x1c86: 0xb291, 0x1c87: 0xb219, 0x1c88: 0xb309, 0x1c89: 0xb429, 0x1c8a: 0x0040, 0x1c8b: 0xb3b1, 0x1c8c: 0xb3c9, 0x1c8d: 0xb3e1, 0x1c8e: 0xb2a9, 0x1c8f: 0xb339, 0x1c90: 0xb369, 0x1c91: 0xb2d9, 0x1c92: 0xb381, 0x1c93: 0xb279, 0x1c94: 0xb2c1, 0x1c95: 0xb1d1, 0x1c96: 0xb1e9, 0x1c97: 0xb231, 0x1c98: 0xb261, 0x1c99: 0xb2f1, 0x1c9a: 0xb321, 0x1c9b: 0xb351, 0x1c9c: 0x0040, 0x1c9d: 0x0040, 0x1c9e: 0x0040, 0x1c9f: 0x0040, 0x1ca0: 0x0040, 0x1ca1: 0xb1a1, 0x1ca2: 0xb201, 0x1ca3: 0xb249, 0x1ca4: 0x0040, 0x1ca5: 0xb411, 0x1ca6: 0xb291, 0x1ca7: 0xb219, 0x1ca8: 0xb309, 0x1ca9: 0xb429, 0x1caa: 0x0040, 0x1cab: 0xb3b1, 0x1cac: 0xb3c9, 0x1cad: 0xb3e1, 0x1cae: 0xb2a9, 0x1caf: 0xb339, 0x1cb0: 0xb369, 0x1cb1: 0xb2d9, 0x1cb2: 0xb381, 0x1cb3: 0xb279, 0x1cb4: 0xb2c1, 0x1cb5: 0xb1d1, 0x1cb6: 0xb1e9, 0x1cb7: 0xb231, 0x1cb8: 0xb261, 0x1cb9: 0xb2f1, 0x1cba: 0xb321, 0x1cbb: 0xb351, 0x1cbc: 0x0040, 0x1cbd: 0x0040, 0x1cbe: 0x0040, 0x1cbf: 0x0040, // Block 0x73, offset 0x1cc0 0x1cc0: 0x0040, 0x1cc1: 0xbca2, 0x1cc2: 0xbcba, 0x1cc3: 0xbcd2, 0x1cc4: 0xbcea, 0x1cc5: 0xbd02, 0x1cc6: 0xbd1a, 0x1cc7: 0xbd32, 0x1cc8: 0xbd4a, 0x1cc9: 0xbd62, 0x1cca: 0xbd7a, 0x1ccb: 0x0018, 0x1ccc: 0x0018, 0x1ccd: 0x0040, 0x1cce: 0x0040, 0x1ccf: 0x0040, 0x1cd0: 0xbd92, 0x1cd1: 0xbdb2, 0x1cd2: 0xbdd2, 0x1cd3: 0xbdf2, 0x1cd4: 0xbe12, 0x1cd5: 0xbe32, 0x1cd6: 0xbe52, 0x1cd7: 0xbe72, 0x1cd8: 0xbe92, 0x1cd9: 0xbeb2, 0x1cda: 0xbed2, 0x1cdb: 0xbef2, 0x1cdc: 0xbf12, 0x1cdd: 0xbf32, 0x1cde: 0xbf52, 0x1cdf: 0xbf72, 0x1ce0: 0xbf92, 0x1ce1: 0xbfb2, 0x1ce2: 0xbfd2, 0x1ce3: 0xbff2, 0x1ce4: 0xc012, 0x1ce5: 0xc032, 0x1ce6: 0xc052, 0x1ce7: 0xc072, 0x1ce8: 0xc092, 0x1ce9: 0xc0b2, 0x1cea: 0xc0d1, 0x1ceb: 0x1159, 0x1cec: 0x0269, 0x1ced: 0x6671, 0x1cee: 0xc111, 0x1cef: 0x0040, 0x1cf0: 0x0039, 0x1cf1: 0x0ee9, 0x1cf2: 0x1159, 0x1cf3: 0x0ef9, 0x1cf4: 0x0f09, 0x1cf5: 0x1199, 0x1cf6: 0x0f31, 0x1cf7: 0x0249, 0x1cf8: 0x0f41, 0x1cf9: 0x0259, 0x1cfa: 0x0f51, 0x1cfb: 0x0359, 0x1cfc: 0x0f61, 0x1cfd: 0x0f71, 0x1cfe: 0x00d9, 0x1cff: 0x0f99, // Block 0x74, offset 0x1d00 0x1d00: 0x2039, 0x1d01: 0x0269, 0x1d02: 0x01d9, 0x1d03: 0x0fa9, 0x1d04: 0x0fb9, 0x1d05: 0x1089, 0x1d06: 0x0279, 0x1d07: 0x0369, 0x1d08: 0x0289, 0x1d09: 0x13d1, 0x1d0a: 0xc129, 0x1d0b: 0x65b1, 0x1d0c: 0xc141, 0x1d0d: 0x1441, 0x1d0e: 0xc159, 0x1d0f: 0xc179, 0x1d10: 0x0018, 0x1d11: 0x0018, 0x1d12: 0x0018, 0x1d13: 0x0018, 0x1d14: 0x0018, 0x1d15: 0x0018, 0x1d16: 0x0018, 0x1d17: 0x0018, 0x1d18: 0x0018, 0x1d19: 0x0018, 0x1d1a: 0x0018, 0x1d1b: 0x0018, 0x1d1c: 0x0018, 0x1d1d: 0x0018, 0x1d1e: 0x0018, 0x1d1f: 0x0018, 0x1d20: 0x0018, 0x1d21: 0x0018, 0x1d22: 0x0018, 0x1d23: 0x0018, 0x1d24: 0x0018, 0x1d25: 0x0018, 0x1d26: 0x0018, 0x1d27: 0x0018, 0x1d28: 0x0018, 0x1d29: 0x0018, 0x1d2a: 0xc191, 0x1d2b: 0xc1a9, 0x1d2c: 0x0040, 0x1d2d: 0x0040, 0x1d2e: 0x0040, 0x1d2f: 0x0040, 0x1d30: 0x0018, 0x1d31: 0x0018, 0x1d32: 0x0018, 0x1d33: 0x0018, 0x1d34: 0x0018, 0x1d35: 0x0018, 0x1d36: 0x0018, 0x1d37: 0x0018, 0x1d38: 0x0018, 0x1d39: 0x0018, 0x1d3a: 0x0018, 0x1d3b: 0x0018, 0x1d3c: 0x0018, 0x1d3d: 0x0018, 0x1d3e: 0x0018, 0x1d3f: 0x0018, // Block 0x75, offset 0x1d40 0x1d40: 0xc1d9, 0x1d41: 0xc211, 0x1d42: 0xc249, 0x1d43: 0x0040, 0x1d44: 0x0040, 0x1d45: 0x0040, 0x1d46: 0x0040, 0x1d47: 0x0040, 0x1d48: 0x0040, 0x1d49: 0x0040, 0x1d4a: 0x0040, 0x1d4b: 0x0040, 0x1d4c: 0x0040, 0x1d4d: 0x0040, 0x1d4e: 0x0040, 0x1d4f: 0x0040, 0x1d50: 0xc269, 0x1d51: 0xc289, 0x1d52: 0xc2a9, 0x1d53: 0xc2c9, 0x1d54: 0xc2e9, 0x1d55: 0xc309, 0x1d56: 0xc329, 0x1d57: 0xc349, 0x1d58: 0xc369, 0x1d59: 0xc389, 0x1d5a: 0xc3a9, 0x1d5b: 0xc3c9, 0x1d5c: 0xc3e9, 0x1d5d: 0xc409, 0x1d5e: 0xc429, 0x1d5f: 0xc449, 0x1d60: 0xc469, 0x1d61: 0xc489, 0x1d62: 0xc4a9, 0x1d63: 0xc4c9, 0x1d64: 0xc4e9, 0x1d65: 0xc509, 0x1d66: 0xc529, 0x1d67: 0xc549, 0x1d68: 0xc569, 0x1d69: 0xc589, 0x1d6a: 0xc5a9, 0x1d6b: 0xc5c9, 0x1d6c: 0xc5e9, 0x1d6d: 0xc609, 0x1d6e: 0xc629, 0x1d6f: 0xc649, 0x1d70: 0xc669, 0x1d71: 0xc689, 0x1d72: 0xc6a9, 0x1d73: 0xc6c9, 0x1d74: 0xc6e9, 0x1d75: 0xc709, 0x1d76: 0xc729, 0x1d77: 0xc749, 0x1d78: 0xc769, 0x1d79: 0xc789, 0x1d7a: 0xc7a9, 0x1d7b: 0xc7c9, 0x1d7c: 0x0040, 0x1d7d: 0x0040, 0x1d7e: 0x0040, 0x1d7f: 0x0040, // Block 0x76, offset 0x1d80 0x1d80: 0xcaf9, 0x1d81: 0xcb19, 0x1d82: 0xcb39, 0x1d83: 0x8b1d, 0x1d84: 0xcb59, 0x1d85: 0xcb79, 0x1d86: 0xcb99, 0x1d87: 0xcbb9, 0x1d88: 0xcbd9, 0x1d89: 0xcbf9, 0x1d8a: 0xcc19, 0x1d8b: 0xcc39, 0x1d8c: 0xcc59, 0x1d8d: 0x8b3d, 0x1d8e: 0xcc79, 0x1d8f: 0xcc99, 0x1d90: 0xccb9, 0x1d91: 0xccd9, 0x1d92: 0x8b5d, 0x1d93: 0xccf9, 0x1d94: 0xcd19, 0x1d95: 0xc429, 0x1d96: 0x8b7d, 0x1d97: 0xcd39, 0x1d98: 0xcd59, 0x1d99: 0xcd79, 0x1d9a: 0xcd99, 0x1d9b: 0xcdb9, 0x1d9c: 0x8b9d, 0x1d9d: 0xcdd9, 0x1d9e: 0xcdf9, 0x1d9f: 0xce19, 0x1da0: 0xce39, 0x1da1: 0xce59, 0x1da2: 0xc789, 0x1da3: 0xce79, 0x1da4: 0xce99, 0x1da5: 0xceb9, 0x1da6: 0xced9, 0x1da7: 0xcef9, 0x1da8: 0xcf19, 0x1da9: 0xcf39, 0x1daa: 0xcf59, 0x1dab: 0xcf79, 0x1dac: 0xcf99, 0x1dad: 0xcfb9, 0x1dae: 0xcfd9, 0x1daf: 0xcff9, 0x1db0: 0xd019, 0x1db1: 0xd039, 0x1db2: 0xd039, 0x1db3: 0xd039, 0x1db4: 0x8bbd, 0x1db5: 0xd059, 0x1db6: 0xd079, 0x1db7: 0xd099, 0x1db8: 0x8bdd, 0x1db9: 0xd0b9, 0x1dba: 0xd0d9, 0x1dbb: 0xd0f9, 0x1dbc: 0xd119, 0x1dbd: 0xd139, 0x1dbe: 0xd159, 0x1dbf: 0xd179, // Block 0x77, offset 0x1dc0 0x1dc0: 0xd199, 0x1dc1: 0xd1b9, 0x1dc2: 0xd1d9, 0x1dc3: 0xd1f9, 0x1dc4: 0xd219, 0x1dc5: 0xd239, 0x1dc6: 0xd239, 0x1dc7: 0xd259, 0x1dc8: 0xd279, 0x1dc9: 0xd299, 0x1dca: 0xd2b9, 0x1dcb: 0xd2d9, 0x1dcc: 0xd2f9, 0x1dcd: 0xd319, 0x1dce: 0xd339, 0x1dcf: 0xd359, 0x1dd0: 0xd379, 0x1dd1: 0xd399, 0x1dd2: 0xd3b9, 0x1dd3: 0xd3d9, 0x1dd4: 0xd3f9, 0x1dd5: 0xd419, 0x1dd6: 0xd439, 0x1dd7: 0xd459, 0x1dd8: 0xd479, 0x1dd9: 0x8bfd, 0x1dda: 0xd499, 0x1ddb: 0xd4b9, 0x1ddc: 0xd4d9, 0x1ddd: 0xc309, 0x1dde: 0xd4f9, 0x1ddf: 0xd519, 0x1de0: 0x8c1d, 0x1de1: 0x8c3d, 0x1de2: 0xd539, 0x1de3: 0xd559, 0x1de4: 0xd579, 0x1de5: 0xd599, 0x1de6: 0xd5b9, 0x1de7: 0xd5d9, 0x1de8: 0x0040, 0x1de9: 0xd5f9, 0x1dea: 0xd619, 0x1deb: 0xd619, 0x1dec: 0x8c5d, 0x1ded: 0xd639, 0x1dee: 0xd659, 0x1def: 0xd679, 0x1df0: 0xd699, 0x1df1: 0x8c7d, 0x1df2: 0xd6b9, 0x1df3: 0xd6d9, 0x1df4: 0x0040, 0x1df5: 0xd6f9, 0x1df6: 0xd719, 0x1df7: 0xd739, 0x1df8: 0xd759, 0x1df9: 0xd779, 0x1dfa: 0xd799, 0x1dfb: 0x8c9d, 0x1dfc: 0xd7b9, 0x1dfd: 0x8cbd, 0x1dfe: 0xd7d9, 0x1dff: 0xd7f9, // Block 0x78, offset 0x1e00 0x1e00: 0xd819, 0x1e01: 0xd839, 0x1e02: 0xd859, 0x1e03: 0xd879, 0x1e04: 0xd899, 0x1e05: 0xd8b9, 0x1e06: 0xd8d9, 0x1e07: 0xd8f9, 0x1e08: 0xd919, 0x1e09: 0x8cdd, 0x1e0a: 0xd939, 0x1e0b: 0xd959, 0x1e0c: 0xd979, 0x1e0d: 0xd999, 0x1e0e: 0xd9b9, 0x1e0f: 0x8cfd, 0x1e10: 0xd9d9, 0x1e11: 0x8d1d, 0x1e12: 0x8d3d, 0x1e13: 0xd9f9, 0x1e14: 0xda19, 0x1e15: 0xda19, 0x1e16: 0xda39, 0x1e17: 0x8d5d, 0x1e18: 0x8d7d, 0x1e19: 0xda59, 0x1e1a: 0xda79, 0x1e1b: 0xda99, 0x1e1c: 0xdab9, 0x1e1d: 0xdad9, 0x1e1e: 0xdaf9, 0x1e1f: 0xdb19, 0x1e20: 0xdb39, 0x1e21: 0xdb59, 0x1e22: 0xdb79, 0x1e23: 0xdb99, 0x1e24: 0x8d9d, 0x1e25: 0xdbb9, 0x1e26: 0xdbd9, 0x1e27: 0xdbf9, 0x1e28: 0xdc19, 0x1e29: 0xdbf9, 0x1e2a: 0xdc39, 0x1e2b: 0xdc59, 0x1e2c: 0xdc79, 0x1e2d: 0xdc99, 0x1e2e: 0xdcb9, 0x1e2f: 0xdcd9, 0x1e30: 0xdcf9, 0x1e31: 0xdd19, 0x1e32: 0xdd39, 0x1e33: 0xdd59, 0x1e34: 0xdd79, 0x1e35: 0xdd99, 0x1e36: 0xddb9, 0x1e37: 0xddd9, 0x1e38: 0x8dbd, 0x1e39: 0xddf9, 0x1e3a: 0xde19, 0x1e3b: 0xde39, 0x1e3c: 0xde59, 0x1e3d: 0xde79, 0x1e3e: 0x8ddd, 0x1e3f: 0xde99, // Block 0x79, offset 0x1e40 0x1e40: 0xe599, 0x1e41: 0xe5b9, 0x1e42: 0xe5d9, 0x1e43: 0xe5f9, 0x1e44: 0xe619, 0x1e45: 0xe639, 0x1e46: 0x8efd, 0x1e47: 0xe659, 0x1e48: 0xe679, 0x1e49: 0xe699, 0x1e4a: 0xe6b9, 0x1e4b: 0xe6d9, 0x1e4c: 0xe6f9, 0x1e4d: 0x8f1d, 0x1e4e: 0xe719, 0x1e4f: 0xe739, 0x1e50: 0x8f3d, 0x1e51: 0x8f5d, 0x1e52: 0xe759, 0x1e53: 0xe779, 0x1e54: 0xe799, 0x1e55: 0xe7b9, 0x1e56: 0xe7d9, 0x1e57: 0xe7f9, 0x1e58: 0xe819, 0x1e59: 0xe839, 0x1e5a: 0xe859, 0x1e5b: 0x8f7d, 0x1e5c: 0xe879, 0x1e5d: 0x8f9d, 0x1e5e: 0xe899, 0x1e5f: 0x0040, 0x1e60: 0xe8b9, 0x1e61: 0xe8d9, 0x1e62: 0xe8f9, 0x1e63: 0x8fbd, 0x1e64: 0xe919, 0x1e65: 0xe939, 0x1e66: 0x8fdd, 0x1e67: 0x8ffd, 0x1e68: 0xe959, 0x1e69: 0xe979, 0x1e6a: 0xe999, 0x1e6b: 0xe9b9, 0x1e6c: 0xe9d9, 0x1e6d: 0xe9d9, 0x1e6e: 0xe9f9, 0x1e6f: 0xea19, 0x1e70: 0xea39, 0x1e71: 0xea59, 0x1e72: 0xea79, 0x1e73: 0xea99, 0x1e74: 0xeab9, 0x1e75: 0x901d, 0x1e76: 0xead9, 0x1e77: 0x903d, 0x1e78: 0xeaf9, 0x1e79: 0x905d, 0x1e7a: 0xeb19, 0x1e7b: 0x907d, 0x1e7c: 0x909d, 0x1e7d: 0x90bd, 0x1e7e: 0xeb39, 0x1e7f: 0xeb59, // Block 0x7a, offset 0x1e80 0x1e80: 0xeb79, 0x1e81: 0x90dd, 0x1e82: 0x90fd, 0x1e83: 0x911d, 0x1e84: 0x913d, 0x1e85: 0xeb99, 0x1e86: 0xebb9, 0x1e87: 0xebb9, 0x1e88: 0xebd9, 0x1e89: 0xebf9, 0x1e8a: 0xec19, 0x1e8b: 0xec39, 0x1e8c: 0xec59, 0x1e8d: 0x915d, 0x1e8e: 0xec79, 0x1e8f: 0xec99, 0x1e90: 0xecb9, 0x1e91: 0xecd9, 0x1e92: 0x917d, 0x1e93: 0xecf9, 0x1e94: 0x919d, 0x1e95: 0x91bd, 0x1e96: 0xed19, 0x1e97: 0xed39, 0x1e98: 0xed59, 0x1e99: 0xed79, 0x1e9a: 0xed99, 0x1e9b: 0xedb9, 0x1e9c: 0x91dd, 0x1e9d: 0x91fd, 0x1e9e: 0x921d, 0x1e9f: 0x0040, 0x1ea0: 0xedd9, 0x1ea1: 0x923d, 0x1ea2: 0xedf9, 0x1ea3: 0xee19, 0x1ea4: 0xee39, 0x1ea5: 0x925d, 0x1ea6: 0xee59, 0x1ea7: 0xee79, 0x1ea8: 0xee99, 0x1ea9: 0xeeb9, 0x1eaa: 0xeed9, 0x1eab: 0x927d, 0x1eac: 0xeef9, 0x1ead: 0xef19, 0x1eae: 0xef39, 0x1eaf: 0xef59, 0x1eb0: 0xef79, 0x1eb1: 0xef99, 0x1eb2: 0x929d, 0x1eb3: 0x92bd, 0x1eb4: 0xefb9, 0x1eb5: 0x92dd, 0x1eb6: 0xefd9, 0x1eb7: 0x92fd, 0x1eb8: 0xeff9, 0x1eb9: 0xf019, 0x1eba: 0xf039, 0x1ebb: 0x931d, 0x1ebc: 0x933d, 0x1ebd: 0xf059, 0x1ebe: 0x935d, 0x1ebf: 0xf079, // Block 0x7b, offset 0x1ec0 0x1ec0: 0xf6b9, 0x1ec1: 0xf6d9, 0x1ec2: 0xf6f9, 0x1ec3: 0xf719, 0x1ec4: 0xf739, 0x1ec5: 0x951d, 0x1ec6: 0xf759, 0x1ec7: 0xf779, 0x1ec8: 0xf799, 0x1ec9: 0xf7b9, 0x1eca: 0xf7d9, 0x1ecb: 0x953d, 0x1ecc: 0x955d, 0x1ecd: 0xf7f9, 0x1ece: 0xf819, 0x1ecf: 0xf839, 0x1ed0: 0xf859, 0x1ed1: 0xf879, 0x1ed2: 0xf899, 0x1ed3: 0x957d, 0x1ed4: 0xf8b9, 0x1ed5: 0xf8d9, 0x1ed6: 0xf8f9, 0x1ed7: 0xf919, 0x1ed8: 0x959d, 0x1ed9: 0x95bd, 0x1eda: 0xf939, 0x1edb: 0xf959, 0x1edc: 0xf979, 0x1edd: 0x95dd, 0x1ede: 0xf999, 0x1edf: 0xf9b9, 0x1ee0: 0x6815, 0x1ee1: 0x95fd, 0x1ee2: 0xf9d9, 0x1ee3: 0xf9f9, 0x1ee4: 0xfa19, 0x1ee5: 0x961d, 0x1ee6: 0xfa39, 0x1ee7: 0xfa59, 0x1ee8: 0xfa79, 0x1ee9: 0xfa99, 0x1eea: 0xfab9, 0x1eeb: 0xfad9, 0x1eec: 0xfaf9, 0x1eed: 0x963d, 0x1eee: 0xfb19, 0x1eef: 0xfb39, 0x1ef0: 0xfb59, 0x1ef1: 0x965d, 0x1ef2: 0xfb79, 0x1ef3: 0xfb99, 0x1ef4: 0xfbb9, 0x1ef5: 0xfbd9, 0x1ef6: 0x7b35, 0x1ef7: 0x967d, 0x1ef8: 0xfbf9, 0x1ef9: 0xfc19, 0x1efa: 0xfc39, 0x1efb: 0x969d, 0x1efc: 0xfc59, 0x1efd: 0x96bd, 0x1efe: 0xfc79, 0x1eff: 0xfc79, // Block 0x7c, offset 0x1f00 0x1f00: 0xfc99, 0x1f01: 0x96dd, 0x1f02: 0xfcb9, 0x1f03: 0xfcd9, 0x1f04: 0xfcf9, 0x1f05: 0xfd19, 0x1f06: 0xfd39, 0x1f07: 0xfd59, 0x1f08: 0xfd79, 0x1f09: 0x96fd, 0x1f0a: 0xfd99, 0x1f0b: 0xfdb9, 0x1f0c: 0xfdd9, 0x1f0d: 0xfdf9, 0x1f0e: 0xfe19, 0x1f0f: 0xfe39, 0x1f10: 0x971d, 0x1f11: 0xfe59, 0x1f12: 0x973d, 0x1f13: 0x975d, 0x1f14: 0x977d, 0x1f15: 0xfe79, 0x1f16: 0xfe99, 0x1f17: 0xfeb9, 0x1f18: 0xfed9, 0x1f19: 0xfef9, 0x1f1a: 0xff19, 0x1f1b: 0xff39, 0x1f1c: 0xff59, 0x1f1d: 0x979d, 0x1f1e: 0x0040, 0x1f1f: 0x0040, 0x1f20: 0x0040, 0x1f21: 0x0040, 0x1f22: 0x0040, 0x1f23: 0x0040, 0x1f24: 0x0040, 0x1f25: 0x0040, 0x1f26: 0x0040, 0x1f27: 0x0040, 0x1f28: 0x0040, 0x1f29: 0x0040, 0x1f2a: 0x0040, 0x1f2b: 0x0040, 0x1f2c: 0x0040, 0x1f2d: 0x0040, 0x1f2e: 0x0040, 0x1f2f: 0x0040, 0x1f30: 0x0040, 0x1f31: 0x0040, 0x1f32: 0x0040, 0x1f33: 0x0040, 0x1f34: 0x0040, 0x1f35: 0x0040, 0x1f36: 0x0040, 0x1f37: 0x0040, 0x1f38: 0x0040, 0x1f39: 0x0040, 0x1f3a: 0x0040, 0x1f3b: 0x0040, 0x1f3c: 0x0040, 0x1f3d: 0x0040, 0x1f3e: 0x0040, 0x1f3f: 0x0040, } // idnaIndex: 35 blocks, 2240 entries, 4480 bytes // Block 0 is the zero block. var idnaIndex = [2240]uint16{ // Block 0x0, offset 0x0 // Block 0x1, offset 0x40 // Block 0x2, offset 0x80 // Block 0x3, offset 0xc0 0xc2: 0x01, 0xc3: 0x7b, 0xc4: 0x02, 0xc5: 0x03, 0xc6: 0x04, 0xc7: 0x05, 0xc8: 0x06, 0xc9: 0x7c, 0xca: 0x7d, 0xcb: 0x07, 0xcc: 0x7e, 0xcd: 0x08, 0xce: 0x09, 0xcf: 0x0a, 0xd0: 0x7f, 0xd1: 0x0b, 0xd2: 0x0c, 0xd3: 0x0d, 0xd4: 0x0e, 0xd5: 0x80, 0xd6: 0x81, 0xd7: 0x82, 0xd8: 0x0f, 0xd9: 0x83, 0xda: 0x84, 0xdb: 0x10, 0xdc: 0x11, 0xdd: 0x85, 0xde: 0x86, 0xdf: 0x87, 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, 0xe4: 0x06, 0xe5: 0x07, 0xe6: 0x07, 0xe7: 0x07, 0xe8: 0x07, 0xe9: 0x08, 0xea: 0x09, 0xeb: 0x07, 0xec: 0x07, 0xed: 0x0a, 0xee: 0x0b, 0xef: 0x0c, 0xf0: 0x1c, 0xf1: 0x1d, 0xf2: 0x1d, 0xf3: 0x1f, 0xf4: 0x20, // Block 0x4, offset 0x100 0x120: 0x88, 0x121: 0x89, 0x122: 0x8a, 0x123: 0x8b, 0x124: 0x8c, 0x125: 0x12, 0x126: 0x13, 0x127: 0x14, 0x128: 0x15, 0x129: 0x16, 0x12a: 0x17, 0x12b: 0x18, 0x12c: 0x19, 0x12d: 0x1a, 0x12e: 0x1b, 0x12f: 0x8d, 0x130: 0x8e, 0x131: 0x1c, 0x132: 0x1d, 0x133: 0x1e, 0x134: 0x8f, 0x135: 0x1f, 0x136: 0x90, 0x137: 0x91, 0x138: 0x92, 0x139: 0x93, 0x13a: 0x20, 0x13b: 0x94, 0x13c: 0x95, 0x13d: 0x21, 0x13e: 0x22, 0x13f: 0x96, // Block 0x5, offset 0x140 0x140: 0x97, 0x141: 0x98, 0x142: 0x99, 0x143: 0x9a, 0x144: 0x9b, 0x145: 0x9c, 0x146: 0x9b, 0x147: 0x9b, 0x148: 0x9d, 0x149: 0x9e, 0x14a: 0x9f, 0x14b: 0xa0, 0x14c: 0xa1, 0x14d: 0xa2, 0x14e: 0xa3, 0x14f: 0xa4, 0x150: 0xa5, 0x151: 0x9d, 0x152: 0x9d, 0x153: 0x9d, 0x154: 0x9d, 0x155: 0x9d, 0x156: 0x9d, 0x157: 0x9d, 0x158: 0x9d, 0x159: 0xa6, 0x15a: 0xa7, 0x15b: 0xa8, 0x15c: 0xa9, 0x15d: 0xaa, 0x15e: 0xab, 0x15f: 0xac, 0x160: 0xad, 0x161: 0xae, 0x162: 0xaf, 0x163: 0xb0, 0x164: 0xb1, 0x165: 0xb2, 0x166: 0xb3, 0x167: 0xb4, 0x168: 0xb5, 0x169: 0xb6, 0x16a: 0xb7, 0x16b: 0xb8, 0x16c: 0xb9, 0x16d: 0xba, 0x16e: 0xbb, 0x16f: 0xbc, 0x170: 0xbd, 0x171: 0xbe, 0x172: 0xbf, 0x173: 0xc0, 0x174: 0x23, 0x175: 0x24, 0x176: 0x25, 0x177: 0xc1, 0x178: 0x26, 0x179: 0x26, 0x17a: 0x27, 0x17b: 0x26, 0x17c: 0xc2, 0x17d: 0x28, 0x17e: 0x29, 0x17f: 0x2a, // Block 0x6, offset 0x180 0x180: 0x2b, 0x181: 0x2c, 0x182: 0x2d, 0x183: 0xc3, 0x184: 0x2e, 0x185: 0x2f, 0x186: 0xc4, 0x187: 0x9b, 0x188: 0xc5, 0x189: 0xc6, 0x18a: 0x9b, 0x18b: 0x9b, 0x18c: 0xc7, 0x18d: 0x9b, 0x18e: 0x9b, 0x18f: 0xc8, 0x190: 0xc9, 0x191: 0x30, 0x192: 0x31, 0x193: 0x32, 0x194: 0x9b, 0x195: 0x9b, 0x196: 0x9b, 0x197: 0x9b, 0x198: 0x9b, 0x199: 0x9b, 0x19a: 0x9b, 0x19b: 0x9b, 0x19c: 0x9b, 0x19d: 0x9b, 0x19e: 0x9b, 0x19f: 0x9b, 0x1a0: 0x9b, 0x1a1: 0x9b, 0x1a2: 0x9b, 0x1a3: 0x9b, 0x1a4: 0x9b, 0x1a5: 0x9b, 0x1a6: 0x9b, 0x1a7: 0x9b, 0x1a8: 0xca, 0x1a9: 0xcb, 0x1aa: 0x9b, 0x1ab: 0xcc, 0x1ac: 0x9b, 0x1ad: 0xcd, 0x1ae: 0xce, 0x1af: 0xcf, 0x1b0: 0xd0, 0x1b1: 0x33, 0x1b2: 0x26, 0x1b3: 0x34, 0x1b4: 0xd1, 0x1b5: 0xd2, 0x1b6: 0xd3, 0x1b7: 0xd4, 0x1b8: 0xd5, 0x1b9: 0xd6, 0x1ba: 0xd7, 0x1bb: 0xd8, 0x1bc: 0xd9, 0x1bd: 0xda, 0x1be: 0xdb, 0x1bf: 0x35, // Block 0x7, offset 0x1c0 0x1c0: 0x36, 0x1c1: 0xdc, 0x1c2: 0xdd, 0x1c3: 0xde, 0x1c4: 0xdf, 0x1c5: 0x37, 0x1c6: 0x38, 0x1c7: 0xe0, 0x1c8: 0xe1, 0x1c9: 0x39, 0x1ca: 0x3a, 0x1cb: 0x3b, 0x1cc: 0x3c, 0x1cd: 0x3d, 0x1ce: 0x3e, 0x1cf: 0x3f, 0x1d0: 0x9d, 0x1d1: 0x9d, 0x1d2: 0x9d, 0x1d3: 0x9d, 0x1d4: 0x9d, 0x1d5: 0x9d, 0x1d6: 0x9d, 0x1d7: 0x9d, 0x1d8: 0x9d, 0x1d9: 0x9d, 0x1da: 0x9d, 0x1db: 0x9d, 0x1dc: 0x9d, 0x1dd: 0x9d, 0x1de: 0x9d, 0x1df: 0x9d, 0x1e0: 0x9d, 0x1e1: 0x9d, 0x1e2: 0x9d, 0x1e3: 0x9d, 0x1e4: 0x9d, 0x1e5: 0x9d, 0x1e6: 0x9d, 0x1e7: 0x9d, 0x1e8: 0x9d, 0x1e9: 0x9d, 0x1ea: 0x9d, 0x1eb: 0x9d, 0x1ec: 0x9d, 0x1ed: 0x9d, 0x1ee: 0x9d, 0x1ef: 0x9d, 0x1f0: 0x9d, 0x1f1: 0x9d, 0x1f2: 0x9d, 0x1f3: 0x9d, 0x1f4: 0x9d, 0x1f5: 0x9d, 0x1f6: 0x9d, 0x1f7: 0x9d, 0x1f8: 0x9d, 0x1f9: 0x9d, 0x1fa: 0x9d, 0x1fb: 0x9d, 0x1fc: 0x9d, 0x1fd: 0x9d, 0x1fe: 0x9d, 0x1ff: 0x9d, // Block 0x8, offset 0x200 0x200: 0x9d, 0x201: 0x9d, 0x202: 0x9d, 0x203: 0x9d, 0x204: 0x9d, 0x205: 0x9d, 0x206: 0x9d, 0x207: 0x9d, 0x208: 0x9d, 0x209: 0x9d, 0x20a: 0x9d, 0x20b: 0x9d, 0x20c: 0x9d, 0x20d: 0x9d, 0x20e: 0x9d, 0x20f: 0x9d, 0x210: 0x9d, 0x211: 0x9d, 0x212: 0x9d, 0x213: 0x9d, 0x214: 0x9d, 0x215: 0x9d, 0x216: 0x9d, 0x217: 0x9d, 0x218: 0x9d, 0x219: 0x9d, 0x21a: 0x9d, 0x21b: 0x9d, 0x21c: 0x9d, 0x21d: 0x9d, 0x21e: 0x9d, 0x21f: 0x9d, 0x220: 0x9d, 0x221: 0x9d, 0x222: 0x9d, 0x223: 0x9d, 0x224: 0x9d, 0x225: 0x9d, 0x226: 0x9d, 0x227: 0x9d, 0x228: 0x9d, 0x229: 0x9d, 0x22a: 0x9d, 0x22b: 0x9d, 0x22c: 0x9d, 0x22d: 0x9d, 0x22e: 0x9d, 0x22f: 0x9d, 0x230: 0x9d, 0x231: 0x9d, 0x232: 0x9d, 0x233: 0x9d, 0x234: 0x9d, 0x235: 0x9d, 0x236: 0xb0, 0x237: 0x9b, 0x238: 0x9d, 0x239: 0x9d, 0x23a: 0x9d, 0x23b: 0x9d, 0x23c: 0x9d, 0x23d: 0x9d, 0x23e: 0x9d, 0x23f: 0x9d, // Block 0x9, offset 0x240 0x240: 0x9d, 0x241: 0x9d, 0x242: 0x9d, 0x243: 0x9d, 0x244: 0x9d, 0x245: 0x9d, 0x246: 0x9d, 0x247: 0x9d, 0x248: 0x9d, 0x249: 0x9d, 0x24a: 0x9d, 0x24b: 0x9d, 0x24c: 0x9d, 0x24d: 0x9d, 0x24e: 0x9d, 0x24f: 0x9d, 0x250: 0x9d, 0x251: 0x9d, 0x252: 0x9d, 0x253: 0x9d, 0x254: 0x9d, 0x255: 0x9d, 0x256: 0x9d, 0x257: 0x9d, 0x258: 0x9d, 0x259: 0x9d, 0x25a: 0x9d, 0x25b: 0x9d, 0x25c: 0x9d, 0x25d: 0x9d, 0x25e: 0x9d, 0x25f: 0x9d, 0x260: 0x9d, 0x261: 0x9d, 0x262: 0x9d, 0x263: 0x9d, 0x264: 0x9d, 0x265: 0x9d, 0x266: 0x9d, 0x267: 0x9d, 0x268: 0x9d, 0x269: 0x9d, 0x26a: 0x9d, 0x26b: 0x9d, 0x26c: 0x9d, 0x26d: 0x9d, 0x26e: 0x9d, 0x26f: 0x9d, 0x270: 0x9d, 0x271: 0x9d, 0x272: 0x9d, 0x273: 0x9d, 0x274: 0x9d, 0x275: 0x9d, 0x276: 0x9d, 0x277: 0x9d, 0x278: 0x9d, 0x279: 0x9d, 0x27a: 0x9d, 0x27b: 0x9d, 0x27c: 0x9d, 0x27d: 0x9d, 0x27e: 0x9d, 0x27f: 0x9d, // Block 0xa, offset 0x280 0x280: 0x9d, 0x281: 0x9d, 0x282: 0x9d, 0x283: 0x9d, 0x284: 0x9d, 0x285: 0x9d, 0x286: 0x9d, 0x287: 0x9d, 0x288: 0x9d, 0x289: 0x9d, 0x28a: 0x9d, 0x28b: 0x9d, 0x28c: 0x9d, 0x28d: 0x9d, 0x28e: 0x9d, 0x28f: 0x9d, 0x290: 0x9d, 0x291: 0x9d, 0x292: 0x9d, 0x293: 0x9d, 0x294: 0x9d, 0x295: 0x9d, 0x296: 0x9d, 0x297: 0x9d, 0x298: 0x9d, 0x299: 0x9d, 0x29a: 0x9d, 0x29b: 0x9d, 0x29c: 0x9d, 0x29d: 0x9d, 0x29e: 0x9d, 0x29f: 0x9d, 0x2a0: 0x9d, 0x2a1: 0x9d, 0x2a2: 0x9d, 0x2a3: 0x9d, 0x2a4: 0x9d, 0x2a5: 0x9d, 0x2a6: 0x9d, 0x2a7: 0x9d, 0x2a8: 0x9d, 0x2a9: 0x9d, 0x2aa: 0x9d, 0x2ab: 0x9d, 0x2ac: 0x9d, 0x2ad: 0x9d, 0x2ae: 0x9d, 0x2af: 0x9d, 0x2b0: 0x9d, 0x2b1: 0x9d, 0x2b2: 0x9d, 0x2b3: 0x9d, 0x2b4: 0x9d, 0x2b5: 0x9d, 0x2b6: 0x9d, 0x2b7: 0x9d, 0x2b8: 0x9d, 0x2b9: 0x9d, 0x2ba: 0x9d, 0x2bb: 0x9d, 0x2bc: 0x9d, 0x2bd: 0x9d, 0x2be: 0x9d, 0x2bf: 0xe2, // Block 0xb, offset 0x2c0 0x2c0: 0x9d, 0x2c1: 0x9d, 0x2c2: 0x9d, 0x2c3: 0x9d, 0x2c4: 0x9d, 0x2c5: 0x9d, 0x2c6: 0x9d, 0x2c7: 0x9d, 0x2c8: 0x9d, 0x2c9: 0x9d, 0x2ca: 0x9d, 0x2cb: 0x9d, 0x2cc: 0x9d, 0x2cd: 0x9d, 0x2ce: 0x9d, 0x2cf: 0x9d, 0x2d0: 0x9d, 0x2d1: 0x9d, 0x2d2: 0xe3, 0x2d3: 0xe4, 0x2d4: 0x9d, 0x2d5: 0x9d, 0x2d6: 0x9d, 0x2d7: 0x9d, 0x2d8: 0xe5, 0x2d9: 0x40, 0x2da: 0x41, 0x2db: 0xe6, 0x2dc: 0x42, 0x2dd: 0x43, 0x2de: 0x44, 0x2df: 0xe7, 0x2e0: 0xe8, 0x2e1: 0xe9, 0x2e2: 0xea, 0x2e3: 0xeb, 0x2e4: 0xec, 0x2e5: 0xed, 0x2e6: 0xee, 0x2e7: 0xef, 0x2e8: 0xf0, 0x2e9: 0xf1, 0x2ea: 0xf2, 0x2eb: 0xf3, 0x2ec: 0xf4, 0x2ed: 0xf5, 0x2ee: 0xf6, 0x2ef: 0xf7, 0x2f0: 0x9d, 0x2f1: 0x9d, 0x2f2: 0x9d, 0x2f3: 0x9d, 0x2f4: 0x9d, 0x2f5: 0x9d, 0x2f6: 0x9d, 0x2f7: 0x9d, 0x2f8: 0x9d, 0x2f9: 0x9d, 0x2fa: 0x9d, 0x2fb: 0x9d, 0x2fc: 0x9d, 0x2fd: 0x9d, 0x2fe: 0x9d, 0x2ff: 0x9d, // Block 0xc, offset 0x300 0x300: 0x9d, 0x301: 0x9d, 0x302: 0x9d, 0x303: 0x9d, 0x304: 0x9d, 0x305: 0x9d, 0x306: 0x9d, 0x307: 0x9d, 0x308: 0x9d, 0x309: 0x9d, 0x30a: 0x9d, 0x30b: 0x9d, 0x30c: 0x9d, 0x30d: 0x9d, 0x30e: 0x9d, 0x30f: 0x9d, 0x310: 0x9d, 0x311: 0x9d, 0x312: 0x9d, 0x313: 0x9d, 0x314: 0x9d, 0x315: 0x9d, 0x316: 0x9d, 0x317: 0x9d, 0x318: 0x9d, 0x319: 0x9d, 0x31a: 0x9d, 0x31b: 0x9d, 0x31c: 0x9d, 0x31d: 0x9d, 0x31e: 0xf8, 0x31f: 0xf9, // Block 0xd, offset 0x340 0x340: 0xb8, 0x341: 0xb8, 0x342: 0xb8, 0x343: 0xb8, 0x344: 0xb8, 0x345: 0xb8, 0x346: 0xb8, 0x347: 0xb8, 0x348: 0xb8, 0x349: 0xb8, 0x34a: 0xb8, 0x34b: 0xb8, 0x34c: 0xb8, 0x34d: 0xb8, 0x34e: 0xb8, 0x34f: 0xb8, 0x350: 0xb8, 0x351: 0xb8, 0x352: 0xb8, 0x353: 0xb8, 0x354: 0xb8, 0x355: 0xb8, 0x356: 0xb8, 0x357: 0xb8, 0x358: 0xb8, 0x359: 0xb8, 0x35a: 0xb8, 0x35b: 0xb8, 0x35c: 0xb8, 0x35d: 0xb8, 0x35e: 0xb8, 0x35f: 0xb8, 0x360: 0xb8, 0x361: 0xb8, 0x362: 0xb8, 0x363: 0xb8, 0x364: 0xb8, 0x365: 0xb8, 0x366: 0xb8, 0x367: 0xb8, 0x368: 0xb8, 0x369: 0xb8, 0x36a: 0xb8, 0x36b: 0xb8, 0x36c: 0xb8, 0x36d: 0xb8, 0x36e: 0xb8, 0x36f: 0xb8, 0x370: 0xb8, 0x371: 0xb8, 0x372: 0xb8, 0x373: 0xb8, 0x374: 0xb8, 0x375: 0xb8, 0x376: 0xb8, 0x377: 0xb8, 0x378: 0xb8, 0x379: 0xb8, 0x37a: 0xb8, 0x37b: 0xb8, 0x37c: 0xb8, 0x37d: 0xb8, 0x37e: 0xb8, 0x37f: 0xb8, // Block 0xe, offset 0x380 0x380: 0xb8, 0x381: 0xb8, 0x382: 0xb8, 0x383: 0xb8, 0x384: 0xb8, 0x385: 0xb8, 0x386: 0xb8, 0x387: 0xb8, 0x388: 0xb8, 0x389: 0xb8, 0x38a: 0xb8, 0x38b: 0xb8, 0x38c: 0xb8, 0x38d: 0xb8, 0x38e: 0xb8, 0x38f: 0xb8, 0x390: 0xb8, 0x391: 0xb8, 0x392: 0xb8, 0x393: 0xb8, 0x394: 0xb8, 0x395: 0xb8, 0x396: 0xb8, 0x397: 0xb8, 0x398: 0xb8, 0x399: 0xb8, 0x39a: 0xb8, 0x39b: 0xb8, 0x39c: 0xb8, 0x39d: 0xb8, 0x39e: 0xb8, 0x39f: 0xb8, 0x3a0: 0xb8, 0x3a1: 0xb8, 0x3a2: 0xb8, 0x3a3: 0xb8, 0x3a4: 0xfa, 0x3a5: 0xfb, 0x3a6: 0xfc, 0x3a7: 0xfd, 0x3a8: 0x45, 0x3a9: 0xfe, 0x3aa: 0xff, 0x3ab: 0x46, 0x3ac: 0x47, 0x3ad: 0x48, 0x3ae: 0x49, 0x3af: 0x4a, 0x3b0: 0x100, 0x3b1: 0x4b, 0x3b2: 0x4c, 0x3b3: 0x4d, 0x3b4: 0x4e, 0x3b5: 0x4f, 0x3b6: 0x101, 0x3b7: 0x50, 0x3b8: 0x51, 0x3b9: 0x52, 0x3ba: 0x53, 0x3bb: 0x54, 0x3bc: 0x55, 0x3bd: 0x56, 0x3be: 0x57, 0x3bf: 0x58, // Block 0xf, offset 0x3c0 0x3c0: 0x102, 0x3c1: 0x103, 0x3c2: 0x9d, 0x3c3: 0x104, 0x3c4: 0x105, 0x3c5: 0x9b, 0x3c6: 0x106, 0x3c7: 0x107, 0x3c8: 0xb8, 0x3c9: 0xb8, 0x3ca: 0x108, 0x3cb: 0x109, 0x3cc: 0x10a, 0x3cd: 0x10b, 0x3ce: 0x10c, 0x3cf: 0x10d, 0x3d0: 0x10e, 0x3d1: 0x9d, 0x3d2: 0x10f, 0x3d3: 0x110, 0x3d4: 0x111, 0x3d5: 0x112, 0x3d6: 0xb8, 0x3d7: 0xb8, 0x3d8: 0x9d, 0x3d9: 0x9d, 0x3da: 0x9d, 0x3db: 0x9d, 0x3dc: 0x113, 0x3dd: 0x114, 0x3de: 0xb8, 0x3df: 0xb8, 0x3e0: 0x115, 0x3e1: 0x116, 0x3e2: 0x117, 0x3e3: 0x118, 0x3e4: 0x119, 0x3e5: 0xb8, 0x3e6: 0x11a, 0x3e7: 0x11b, 0x3e8: 0x11c, 0x3e9: 0x11d, 0x3ea: 0x11e, 0x3eb: 0x59, 0x3ec: 0x11f, 0x3ed: 0x120, 0x3ee: 0x5a, 0x3ef: 0xb8, 0x3f0: 0x9d, 0x3f1: 0x121, 0x3f2: 0x122, 0x3f3: 0x123, 0x3f4: 0xb8, 0x3f5: 0xb8, 0x3f6: 0xb8, 0x3f7: 0xb8, 0x3f8: 0xb8, 0x3f9: 0x124, 0x3fa: 0xb8, 0x3fb: 0xb8, 0x3fc: 0xb8, 0x3fd: 0xb8, 0x3fe: 0xb8, 0x3ff: 0xb8, // Block 0x10, offset 0x400 0x400: 0x125, 0x401: 0x126, 0x402: 0x127, 0x403: 0x128, 0x404: 0x129, 0x405: 0x12a, 0x406: 0x12b, 0x407: 0x12c, 0x408: 0x12d, 0x409: 0xb8, 0x40a: 0x12e, 0x40b: 0x12f, 0x40c: 0x5b, 0x40d: 0x5c, 0x40e: 0xb8, 0x40f: 0xb8, 0x410: 0x130, 0x411: 0x131, 0x412: 0x132, 0x413: 0x133, 0x414: 0xb8, 0x415: 0xb8, 0x416: 0x134, 0x417: 0x135, 0x418: 0x136, 0x419: 0x137, 0x41a: 0x138, 0x41b: 0x139, 0x41c: 0x13a, 0x41d: 0xb8, 0x41e: 0xb8, 0x41f: 0xb8, 0x420: 0xb8, 0x421: 0xb8, 0x422: 0x13b, 0x423: 0x13c, 0x424: 0xb8, 0x425: 0xb8, 0x426: 0xb8, 0x427: 0xb8, 0x428: 0xb8, 0x429: 0xb8, 0x42a: 0xb8, 0x42b: 0x13d, 0x42c: 0xb8, 0x42d: 0xb8, 0x42e: 0xb8, 0x42f: 0xb8, 0x430: 0x13e, 0x431: 0x13f, 0x432: 0x140, 0x433: 0xb8, 0x434: 0xb8, 0x435: 0xb8, 0x436: 0xb8, 0x437: 0xb8, 0x438: 0xb8, 0x439: 0xb8, 0x43a: 0xb8, 0x43b: 0xb8, 0x43c: 0xb8, 0x43d: 0xb8, 0x43e: 0xb8, 0x43f: 0xb8, // Block 0x11, offset 0x440 0x440: 0x9d, 0x441: 0x9d, 0x442: 0x9d, 0x443: 0x9d, 0x444: 0x9d, 0x445: 0x9d, 0x446: 0x9d, 0x447: 0x9d, 0x448: 0x9d, 0x449: 0x9d, 0x44a: 0x9d, 0x44b: 0x9d, 0x44c: 0x9d, 0x44d: 0x9d, 0x44e: 0x141, 0x44f: 0xb8, 0x450: 0x9b, 0x451: 0x142, 0x452: 0x9d, 0x453: 0x9d, 0x454: 0x9d, 0x455: 0x143, 0x456: 0xb8, 0x457: 0xb8, 0x458: 0xb8, 0x459: 0xb8, 0x45a: 0xb8, 0x45b: 0xb8, 0x45c: 0xb8, 0x45d: 0xb8, 0x45e: 0xb8, 0x45f: 0xb8, 0x460: 0xb8, 0x461: 0xb8, 0x462: 0xb8, 0x463: 0xb8, 0x464: 0xb8, 0x465: 0xb8, 0x466: 0xb8, 0x467: 0xb8, 0x468: 0xb8, 0x469: 0xb8, 0x46a: 0xb8, 0x46b: 0xb8, 0x46c: 0xb8, 0x46d: 0xb8, 0x46e: 0xb8, 0x46f: 0xb8, 0x470: 0xb8, 0x471: 0xb8, 0x472: 0xb8, 0x473: 0xb8, 0x474: 0xb8, 0x475: 0xb8, 0x476: 0xb8, 0x477: 0xb8, 0x478: 0xb8, 0x479: 0xb8, 0x47a: 0xb8, 0x47b: 0xb8, 0x47c: 0xb8, 0x47d: 0xb8, 0x47e: 0xb8, 0x47f: 0xb8, // Block 0x12, offset 0x480 0x480: 0x9d, 0x481: 0x9d, 0x482: 0x9d, 0x483: 0x9d, 0x484: 0x9d, 0x485: 0x9d, 0x486: 0x9d, 0x487: 0x9d, 0x488: 0x9d, 0x489: 0x9d, 0x48a: 0x9d, 0x48b: 0x9d, 0x48c: 0x9d, 0x48d: 0x9d, 0x48e: 0x9d, 0x48f: 0x9d, 0x490: 0x144, 0x491: 0xb8, 0x492: 0xb8, 0x493: 0xb8, 0x494: 0xb8, 0x495: 0xb8, 0x496: 0xb8, 0x497: 0xb8, 0x498: 0xb8, 0x499: 0xb8, 0x49a: 0xb8, 0x49b: 0xb8, 0x49c: 0xb8, 0x49d: 0xb8, 0x49e: 0xb8, 0x49f: 0xb8, 0x4a0: 0xb8, 0x4a1: 0xb8, 0x4a2: 0xb8, 0x4a3: 0xb8, 0x4a4: 0xb8, 0x4a5: 0xb8, 0x4a6: 0xb8, 0x4a7: 0xb8, 0x4a8: 0xb8, 0x4a9: 0xb8, 0x4aa: 0xb8, 0x4ab: 0xb8, 0x4ac: 0xb8, 0x4ad: 0xb8, 0x4ae: 0xb8, 0x4af: 0xb8, 0x4b0: 0xb8, 0x4b1: 0xb8, 0x4b2: 0xb8, 0x4b3: 0xb8, 0x4b4: 0xb8, 0x4b5: 0xb8, 0x4b6: 0xb8, 0x4b7: 0xb8, 0x4b8: 0xb8, 0x4b9: 0xb8, 0x4ba: 0xb8, 0x4bb: 0xb8, 0x4bc: 0xb8, 0x4bd: 0xb8, 0x4be: 0xb8, 0x4bf: 0xb8, // Block 0x13, offset 0x4c0 0x4c0: 0xb8, 0x4c1: 0xb8, 0x4c2: 0xb8, 0x4c3: 0xb8, 0x4c4: 0xb8, 0x4c5: 0xb8, 0x4c6: 0xb8, 0x4c7: 0xb8, 0x4c8: 0xb8, 0x4c9: 0xb8, 0x4ca: 0xb8, 0x4cb: 0xb8, 0x4cc: 0xb8, 0x4cd: 0xb8, 0x4ce: 0xb8, 0x4cf: 0xb8, 0x4d0: 0x9d, 0x4d1: 0x9d, 0x4d2: 0x9d, 0x4d3: 0x9d, 0x4d4: 0x9d, 0x4d5: 0x9d, 0x4d6: 0x9d, 0x4d7: 0x9d, 0x4d8: 0x9d, 0x4d9: 0x145, 0x4da: 0xb8, 0x4db: 0xb8, 0x4dc: 0xb8, 0x4dd: 0xb8, 0x4de: 0xb8, 0x4df: 0xb8, 0x4e0: 0xb8, 0x4e1: 0xb8, 0x4e2: 0xb8, 0x4e3: 0xb8, 0x4e4: 0xb8, 0x4e5: 0xb8, 0x4e6: 0xb8, 0x4e7: 0xb8, 0x4e8: 0xb8, 0x4e9: 0xb8, 0x4ea: 0xb8, 0x4eb: 0xb8, 0x4ec: 0xb8, 0x4ed: 0xb8, 0x4ee: 0xb8, 0x4ef: 0xb8, 0x4f0: 0xb8, 0x4f1: 0xb8, 0x4f2: 0xb8, 0x4f3: 0xb8, 0x4f4: 0xb8, 0x4f5: 0xb8, 0x4f6: 0xb8, 0x4f7: 0xb8, 0x4f8: 0xb8, 0x4f9: 0xb8, 0x4fa: 0xb8, 0x4fb: 0xb8, 0x4fc: 0xb8, 0x4fd: 0xb8, 0x4fe: 0xb8, 0x4ff: 0xb8, // Block 0x14, offset 0x500 0x500: 0xb8, 0x501: 0xb8, 0x502: 0xb8, 0x503: 0xb8, 0x504: 0xb8, 0x505: 0xb8, 0x506: 0xb8, 0x507: 0xb8, 0x508: 0xb8, 0x509: 0xb8, 0x50a: 0xb8, 0x50b: 0xb8, 0x50c: 0xb8, 0x50d: 0xb8, 0x50e: 0xb8, 0x50f: 0xb8, 0x510: 0xb8, 0x511: 0xb8, 0x512: 0xb8, 0x513: 0xb8, 0x514: 0xb8, 0x515: 0xb8, 0x516: 0xb8, 0x517: 0xb8, 0x518: 0xb8, 0x519: 0xb8, 0x51a: 0xb8, 0x51b: 0xb8, 0x51c: 0xb8, 0x51d: 0xb8, 0x51e: 0xb8, 0x51f: 0xb8, 0x520: 0x9d, 0x521: 0x9d, 0x522: 0x9d, 0x523: 0x9d, 0x524: 0x9d, 0x525: 0x9d, 0x526: 0x9d, 0x527: 0x9d, 0x528: 0x13d, 0x529: 0x146, 0x52a: 0xb8, 0x52b: 0x147, 0x52c: 0x148, 0x52d: 0x149, 0x52e: 0x14a, 0x52f: 0xb8, 0x530: 0xb8, 0x531: 0xb8, 0x532: 0xb8, 0x533: 0xb8, 0x534: 0xb8, 0x535: 0xb8, 0x536: 0xb8, 0x537: 0xb8, 0x538: 0xb8, 0x539: 0xb8, 0x53a: 0xb8, 0x53b: 0xb8, 0x53c: 0x9d, 0x53d: 0x14b, 0x53e: 0x14c, 0x53f: 0x14d, // Block 0x15, offset 0x540 0x540: 0x9d, 0x541: 0x9d, 0x542: 0x9d, 0x543: 0x9d, 0x544: 0x9d, 0x545: 0x9d, 0x546: 0x9d, 0x547: 0x9d, 0x548: 0x9d, 0x549: 0x9d, 0x54a: 0x9d, 0x54b: 0x9d, 0x54c: 0x9d, 0x54d: 0x9d, 0x54e: 0x9d, 0x54f: 0x9d, 0x550: 0x9d, 0x551: 0x9d, 0x552: 0x9d, 0x553: 0x9d, 0x554: 0x9d, 0x555: 0x9d, 0x556: 0x9d, 0x557: 0x9d, 0x558: 0x9d, 0x559: 0x9d, 0x55a: 0x9d, 0x55b: 0x9d, 0x55c: 0x9d, 0x55d: 0x9d, 0x55e: 0x9d, 0x55f: 0x14e, 0x560: 0x9d, 0x561: 0x9d, 0x562: 0x9d, 0x563: 0x9d, 0x564: 0x9d, 0x565: 0x9d, 0x566: 0x9d, 0x567: 0x9d, 0x568: 0x9d, 0x569: 0x9d, 0x56a: 0x9d, 0x56b: 0x14f, 0x56c: 0xb8, 0x56d: 0xb8, 0x56e: 0xb8, 0x56f: 0xb8, 0x570: 0xb8, 0x571: 0xb8, 0x572: 0xb8, 0x573: 0xb8, 0x574: 0xb8, 0x575: 0xb8, 0x576: 0xb8, 0x577: 0xb8, 0x578: 0xb8, 0x579: 0xb8, 0x57a: 0xb8, 0x57b: 0xb8, 0x57c: 0xb8, 0x57d: 0xb8, 0x57e: 0xb8, 0x57f: 0xb8, // Block 0x16, offset 0x580 0x580: 0x150, 0x581: 0xb8, 0x582: 0xb8, 0x583: 0xb8, 0x584: 0xb8, 0x585: 0xb8, 0x586: 0xb8, 0x587: 0xb8, 0x588: 0xb8, 0x589: 0xb8, 0x58a: 0xb8, 0x58b: 0xb8, 0x58c: 0xb8, 0x58d: 0xb8, 0x58e: 0xb8, 0x58f: 0xb8, 0x590: 0xb8, 0x591: 0xb8, 0x592: 0xb8, 0x593: 0xb8, 0x594: 0xb8, 0x595: 0xb8, 0x596: 0xb8, 0x597: 0xb8, 0x598: 0xb8, 0x599: 0xb8, 0x59a: 0xb8, 0x59b: 0xb8, 0x59c: 0xb8, 0x59d: 0xb8, 0x59e: 0xb8, 0x59f: 0xb8, 0x5a0: 0xb8, 0x5a1: 0xb8, 0x5a2: 0xb8, 0x5a3: 0xb8, 0x5a4: 0xb8, 0x5a5: 0xb8, 0x5a6: 0xb8, 0x5a7: 0xb8, 0x5a8: 0xb8, 0x5a9: 0xb8, 0x5aa: 0xb8, 0x5ab: 0xb8, 0x5ac: 0xb8, 0x5ad: 0xb8, 0x5ae: 0xb8, 0x5af: 0xb8, 0x5b0: 0x9d, 0x5b1: 0x151, 0x5b2: 0x152, 0x5b3: 0xb8, 0x5b4: 0xb8, 0x5b5: 0xb8, 0x5b6: 0xb8, 0x5b7: 0xb8, 0x5b8: 0xb8, 0x5b9: 0xb8, 0x5ba: 0xb8, 0x5bb: 0xb8, 0x5bc: 0xb8, 0x5bd: 0xb8, 0x5be: 0xb8, 0x5bf: 0xb8, // Block 0x17, offset 0x5c0 0x5c0: 0x9b, 0x5c1: 0x9b, 0x5c2: 0x9b, 0x5c3: 0x153, 0x5c4: 0x154, 0x5c5: 0x155, 0x5c6: 0x156, 0x5c7: 0x157, 0x5c8: 0x9b, 0x5c9: 0x158, 0x5ca: 0xb8, 0x5cb: 0xb8, 0x5cc: 0x9b, 0x5cd: 0x159, 0x5ce: 0xb8, 0x5cf: 0xb8, 0x5d0: 0x5d, 0x5d1: 0x5e, 0x5d2: 0x5f, 0x5d3: 0x60, 0x5d4: 0x61, 0x5d5: 0x62, 0x5d6: 0x63, 0x5d7: 0x64, 0x5d8: 0x65, 0x5d9: 0x66, 0x5da: 0x67, 0x5db: 0x68, 0x5dc: 0x69, 0x5dd: 0x6a, 0x5de: 0x6b, 0x5df: 0x6c, 0x5e0: 0x9b, 0x5e1: 0x9b, 0x5e2: 0x9b, 0x5e3: 0x9b, 0x5e4: 0x9b, 0x5e5: 0x9b, 0x5e6: 0x9b, 0x5e7: 0x9b, 0x5e8: 0x15a, 0x5e9: 0x15b, 0x5ea: 0x15c, 0x5eb: 0xb8, 0x5ec: 0xb8, 0x5ed: 0xb8, 0x5ee: 0xb8, 0x5ef: 0xb8, 0x5f0: 0xb8, 0x5f1: 0xb8, 0x5f2: 0xb8, 0x5f3: 0xb8, 0x5f4: 0xb8, 0x5f5: 0xb8, 0x5f6: 0xb8, 0x5f7: 0xb8, 0x5f8: 0xb8, 0x5f9: 0xb8, 0x5fa: 0xb8, 0x5fb: 0xb8, 0x5fc: 0xb8, 0x5fd: 0xb8, 0x5fe: 0xb8, 0x5ff: 0xb8, // Block 0x18, offset 0x600 0x600: 0x15d, 0x601: 0xb8, 0x602: 0xb8, 0x603: 0xb8, 0x604: 0xb8, 0x605: 0xb8, 0x606: 0xb8, 0x607: 0xb8, 0x608: 0xb8, 0x609: 0xb8, 0x60a: 0xb8, 0x60b: 0xb8, 0x60c: 0xb8, 0x60d: 0xb8, 0x60e: 0xb8, 0x60f: 0xb8, 0x610: 0xb8, 0x611: 0xb8, 0x612: 0xb8, 0x613: 0xb8, 0x614: 0xb8, 0x615: 0xb8, 0x616: 0xb8, 0x617: 0xb8, 0x618: 0xb8, 0x619: 0xb8, 0x61a: 0xb8, 0x61b: 0xb8, 0x61c: 0xb8, 0x61d: 0xb8, 0x61e: 0xb8, 0x61f: 0xb8, 0x620: 0x9d, 0x621: 0x9d, 0x622: 0x9d, 0x623: 0x15e, 0x624: 0x6d, 0x625: 0x15f, 0x626: 0xb8, 0x627: 0xb8, 0x628: 0xb8, 0x629: 0xb8, 0x62a: 0xb8, 0x62b: 0xb8, 0x62c: 0xb8, 0x62d: 0xb8, 0x62e: 0xb8, 0x62f: 0xb8, 0x630: 0xb8, 0x631: 0xb8, 0x632: 0xb8, 0x633: 0xb8, 0x634: 0xb8, 0x635: 0xb8, 0x636: 0xb8, 0x637: 0xb8, 0x638: 0x6e, 0x639: 0x6f, 0x63a: 0x70, 0x63b: 0x160, 0x63c: 0xb8, 0x63d: 0xb8, 0x63e: 0xb8, 0x63f: 0xb8, // Block 0x19, offset 0x640 0x640: 0x161, 0x641: 0x9b, 0x642: 0x162, 0x643: 0x163, 0x644: 0x71, 0x645: 0x72, 0x646: 0x164, 0x647: 0x165, 0x648: 0x73, 0x649: 0x166, 0x64a: 0xb8, 0x64b: 0xb8, 0x64c: 0x9b, 0x64d: 0x9b, 0x64e: 0x9b, 0x64f: 0x9b, 0x650: 0x9b, 0x651: 0x9b, 0x652: 0x9b, 0x653: 0x9b, 0x654: 0x9b, 0x655: 0x9b, 0x656: 0x9b, 0x657: 0x9b, 0x658: 0x9b, 0x659: 0x9b, 0x65a: 0x9b, 0x65b: 0x167, 0x65c: 0x9b, 0x65d: 0x168, 0x65e: 0x9b, 0x65f: 0x169, 0x660: 0x16a, 0x661: 0x16b, 0x662: 0x16c, 0x663: 0xb8, 0x664: 0x16d, 0x665: 0x16e, 0x666: 0x16f, 0x667: 0x170, 0x668: 0xb8, 0x669: 0xb8, 0x66a: 0xb8, 0x66b: 0xb8, 0x66c: 0xb8, 0x66d: 0xb8, 0x66e: 0xb8, 0x66f: 0xb8, 0x670: 0xb8, 0x671: 0xb8, 0x672: 0xb8, 0x673: 0xb8, 0x674: 0xb8, 0x675: 0xb8, 0x676: 0xb8, 0x677: 0xb8, 0x678: 0xb8, 0x679: 0xb8, 0x67a: 0xb8, 0x67b: 0xb8, 0x67c: 0xb8, 0x67d: 0xb8, 0x67e: 0xb8, 0x67f: 0xb8, // Block 0x1a, offset 0x680 0x680: 0x9d, 0x681: 0x9d, 0x682: 0x9d, 0x683: 0x9d, 0x684: 0x9d, 0x685: 0x9d, 0x686: 0x9d, 0x687: 0x9d, 0x688: 0x9d, 0x689: 0x9d, 0x68a: 0x9d, 0x68b: 0x9d, 0x68c: 0x9d, 0x68d: 0x9d, 0x68e: 0x9d, 0x68f: 0x9d, 0x690: 0x9d, 0x691: 0x9d, 0x692: 0x9d, 0x693: 0x9d, 0x694: 0x9d, 0x695: 0x9d, 0x696: 0x9d, 0x697: 0x9d, 0x698: 0x9d, 0x699: 0x9d, 0x69a: 0x9d, 0x69b: 0x171, 0x69c: 0x9d, 0x69d: 0x9d, 0x69e: 0x9d, 0x69f: 0x9d, 0x6a0: 0x9d, 0x6a1: 0x9d, 0x6a2: 0x9d, 0x6a3: 0x9d, 0x6a4: 0x9d, 0x6a5: 0x9d, 0x6a6: 0x9d, 0x6a7: 0x9d, 0x6a8: 0x9d, 0x6a9: 0x9d, 0x6aa: 0x9d, 0x6ab: 0x9d, 0x6ac: 0x9d, 0x6ad: 0x9d, 0x6ae: 0x9d, 0x6af: 0x9d, 0x6b0: 0x9d, 0x6b1: 0x9d, 0x6b2: 0x9d, 0x6b3: 0x9d, 0x6b4: 0x9d, 0x6b5: 0x9d, 0x6b6: 0x9d, 0x6b7: 0x9d, 0x6b8: 0x9d, 0x6b9: 0x9d, 0x6ba: 0x9d, 0x6bb: 0x9d, 0x6bc: 0x9d, 0x6bd: 0x9d, 0x6be: 0x9d, 0x6bf: 0x9d, // Block 0x1b, offset 0x6c0 0x6c0: 0x9d, 0x6c1: 0x9d, 0x6c2: 0x9d, 0x6c3: 0x9d, 0x6c4: 0x9d, 0x6c5: 0x9d, 0x6c6: 0x9d, 0x6c7: 0x9d, 0x6c8: 0x9d, 0x6c9: 0x9d, 0x6ca: 0x9d, 0x6cb: 0x9d, 0x6cc: 0x9d, 0x6cd: 0x9d, 0x6ce: 0x9d, 0x6cf: 0x9d, 0x6d0: 0x9d, 0x6d1: 0x9d, 0x6d2: 0x9d, 0x6d3: 0x9d, 0x6d4: 0x9d, 0x6d5: 0x9d, 0x6d6: 0x9d, 0x6d7: 0x9d, 0x6d8: 0x9d, 0x6d9: 0x9d, 0x6da: 0x9d, 0x6db: 0x9d, 0x6dc: 0x172, 0x6dd: 0x9d, 0x6de: 0x9d, 0x6df: 0x9d, 0x6e0: 0x173, 0x6e1: 0x9d, 0x6e2: 0x9d, 0x6e3: 0x9d, 0x6e4: 0x9d, 0x6e5: 0x9d, 0x6e6: 0x9d, 0x6e7: 0x9d, 0x6e8: 0x9d, 0x6e9: 0x9d, 0x6ea: 0x9d, 0x6eb: 0x9d, 0x6ec: 0x9d, 0x6ed: 0x9d, 0x6ee: 0x9d, 0x6ef: 0x9d, 0x6f0: 0x9d, 0x6f1: 0x9d, 0x6f2: 0x9d, 0x6f3: 0x9d, 0x6f4: 0x9d, 0x6f5: 0x9d, 0x6f6: 0x9d, 0x6f7: 0x9d, 0x6f8: 0x9d, 0x6f9: 0x9d, 0x6fa: 0x9d, 0x6fb: 0x9d, 0x6fc: 0x9d, 0x6fd: 0x9d, 0x6fe: 0x9d, 0x6ff: 0x9d, // Block 0x1c, offset 0x700 0x700: 0x9d, 0x701: 0x9d, 0x702: 0x9d, 0x703: 0x9d, 0x704: 0x9d, 0x705: 0x9d, 0x706: 0x9d, 0x707: 0x9d, 0x708: 0x9d, 0x709: 0x9d, 0x70a: 0x9d, 0x70b: 0x9d, 0x70c: 0x9d, 0x70d: 0x9d, 0x70e: 0x9d, 0x70f: 0x9d, 0x710: 0x9d, 0x711: 0x9d, 0x712: 0x9d, 0x713: 0x9d, 0x714: 0x9d, 0x715: 0x9d, 0x716: 0x9d, 0x717: 0x9d, 0x718: 0x9d, 0x719: 0x9d, 0x71a: 0x9d, 0x71b: 0x9d, 0x71c: 0x9d, 0x71d: 0x9d, 0x71e: 0x9d, 0x71f: 0x9d, 0x720: 0x9d, 0x721: 0x9d, 0x722: 0x9d, 0x723: 0x9d, 0x724: 0x9d, 0x725: 0x9d, 0x726: 0x9d, 0x727: 0x9d, 0x728: 0x9d, 0x729: 0x9d, 0x72a: 0x9d, 0x72b: 0x9d, 0x72c: 0x9d, 0x72d: 0x9d, 0x72e: 0x9d, 0x72f: 0x9d, 0x730: 0x9d, 0x731: 0x9d, 0x732: 0x9d, 0x733: 0x9d, 0x734: 0x9d, 0x735: 0x9d, 0x736: 0x9d, 0x737: 0x9d, 0x738: 0x9d, 0x739: 0x9d, 0x73a: 0x174, 0x73b: 0xb8, 0x73c: 0xb8, 0x73d: 0xb8, 0x73e: 0xb8, 0x73f: 0xb8, // Block 0x1d, offset 0x740 0x740: 0xb8, 0x741: 0xb8, 0x742: 0xb8, 0x743: 0xb8, 0x744: 0xb8, 0x745: 0xb8, 0x746: 0xb8, 0x747: 0xb8, 0x748: 0xb8, 0x749: 0xb8, 0x74a: 0xb8, 0x74b: 0xb8, 0x74c: 0xb8, 0x74d: 0xb8, 0x74e: 0xb8, 0x74f: 0xb8, 0x750: 0xb8, 0x751: 0xb8, 0x752: 0xb8, 0x753: 0xb8, 0x754: 0xb8, 0x755: 0xb8, 0x756: 0xb8, 0x757: 0xb8, 0x758: 0xb8, 0x759: 0xb8, 0x75a: 0xb8, 0x75b: 0xb8, 0x75c: 0xb8, 0x75d: 0xb8, 0x75e: 0xb8, 0x75f: 0xb8, 0x760: 0x74, 0x761: 0x75, 0x762: 0x76, 0x763: 0x175, 0x764: 0x77, 0x765: 0x78, 0x766: 0x176, 0x767: 0x79, 0x768: 0x7a, 0x769: 0xb8, 0x76a: 0xb8, 0x76b: 0xb8, 0x76c: 0xb8, 0x76d: 0xb8, 0x76e: 0xb8, 0x76f: 0xb8, 0x770: 0xb8, 0x771: 0xb8, 0x772: 0xb8, 0x773: 0xb8, 0x774: 0xb8, 0x775: 0xb8, 0x776: 0xb8, 0x777: 0xb8, 0x778: 0xb8, 0x779: 0xb8, 0x77a: 0xb8, 0x77b: 0xb8, 0x77c: 0xb8, 0x77d: 0xb8, 0x77e: 0xb8, 0x77f: 0xb8, // Block 0x1e, offset 0x780 0x790: 0x0d, 0x791: 0x0e, 0x792: 0x0f, 0x793: 0x10, 0x794: 0x11, 0x795: 0x0b, 0x796: 0x12, 0x797: 0x07, 0x798: 0x13, 0x799: 0x0b, 0x79a: 0x0b, 0x79b: 0x14, 0x79c: 0x0b, 0x79d: 0x15, 0x79e: 0x16, 0x79f: 0x17, 0x7a0: 0x07, 0x7a1: 0x07, 0x7a2: 0x07, 0x7a3: 0x07, 0x7a4: 0x07, 0x7a5: 0x07, 0x7a6: 0x07, 0x7a7: 0x07, 0x7a8: 0x07, 0x7a9: 0x07, 0x7aa: 0x18, 0x7ab: 0x19, 0x7ac: 0x1a, 0x7ad: 0x0b, 0x7ae: 0x0b, 0x7af: 0x1b, 0x7b0: 0x0b, 0x7b1: 0x0b, 0x7b2: 0x0b, 0x7b3: 0x0b, 0x7b4: 0x0b, 0x7b5: 0x0b, 0x7b6: 0x0b, 0x7b7: 0x0b, 0x7b8: 0x0b, 0x7b9: 0x0b, 0x7ba: 0x0b, 0x7bb: 0x0b, 0x7bc: 0x0b, 0x7bd: 0x0b, 0x7be: 0x0b, 0x7bf: 0x0b, // Block 0x1f, offset 0x7c0 0x7c0: 0x0b, 0x7c1: 0x0b, 0x7c2: 0x0b, 0x7c3: 0x0b, 0x7c4: 0x0b, 0x7c5: 0x0b, 0x7c6: 0x0b, 0x7c7: 0x0b, 0x7c8: 0x0b, 0x7c9: 0x0b, 0x7ca: 0x0b, 0x7cb: 0x0b, 0x7cc: 0x0b, 0x7cd: 0x0b, 0x7ce: 0x0b, 0x7cf: 0x0b, 0x7d0: 0x0b, 0x7d1: 0x0b, 0x7d2: 0x0b, 0x7d3: 0x0b, 0x7d4: 0x0b, 0x7d5: 0x0b, 0x7d6: 0x0b, 0x7d7: 0x0b, 0x7d8: 0x0b, 0x7d9: 0x0b, 0x7da: 0x0b, 0x7db: 0x0b, 0x7dc: 0x0b, 0x7dd: 0x0b, 0x7de: 0x0b, 0x7df: 0x0b, 0x7e0: 0x0b, 0x7e1: 0x0b, 0x7e2: 0x0b, 0x7e3: 0x0b, 0x7e4: 0x0b, 0x7e5: 0x0b, 0x7e6: 0x0b, 0x7e7: 0x0b, 0x7e8: 0x0b, 0x7e9: 0x0b, 0x7ea: 0x0b, 0x7eb: 0x0b, 0x7ec: 0x0b, 0x7ed: 0x0b, 0x7ee: 0x0b, 0x7ef: 0x0b, 0x7f0: 0x0b, 0x7f1: 0x0b, 0x7f2: 0x0b, 0x7f3: 0x0b, 0x7f4: 0x0b, 0x7f5: 0x0b, 0x7f6: 0x0b, 0x7f7: 0x0b, 0x7f8: 0x0b, 0x7f9: 0x0b, 0x7fa: 0x0b, 0x7fb: 0x0b, 0x7fc: 0x0b, 0x7fd: 0x0b, 0x7fe: 0x0b, 0x7ff: 0x0b, // Block 0x20, offset 0x800 0x800: 0x177, 0x801: 0x178, 0x802: 0xb8, 0x803: 0xb8, 0x804: 0x179, 0x805: 0x179, 0x806: 0x179, 0x807: 0x17a, 0x808: 0xb8, 0x809: 0xb8, 0x80a: 0xb8, 0x80b: 0xb8, 0x80c: 0xb8, 0x80d: 0xb8, 0x80e: 0xb8, 0x80f: 0xb8, 0x810: 0xb8, 0x811: 0xb8, 0x812: 0xb8, 0x813: 0xb8, 0x814: 0xb8, 0x815: 0xb8, 0x816: 0xb8, 0x817: 0xb8, 0x818: 0xb8, 0x819: 0xb8, 0x81a: 0xb8, 0x81b: 0xb8, 0x81c: 0xb8, 0x81d: 0xb8, 0x81e: 0xb8, 0x81f: 0xb8, 0x820: 0xb8, 0x821: 0xb8, 0x822: 0xb8, 0x823: 0xb8, 0x824: 0xb8, 0x825: 0xb8, 0x826: 0xb8, 0x827: 0xb8, 0x828: 0xb8, 0x829: 0xb8, 0x82a: 0xb8, 0x82b: 0xb8, 0x82c: 0xb8, 0x82d: 0xb8, 0x82e: 0xb8, 0x82f: 0xb8, 0x830: 0xb8, 0x831: 0xb8, 0x832: 0xb8, 0x833: 0xb8, 0x834: 0xb8, 0x835: 0xb8, 0x836: 0xb8, 0x837: 0xb8, 0x838: 0xb8, 0x839: 0xb8, 0x83a: 0xb8, 0x83b: 0xb8, 0x83c: 0xb8, 0x83d: 0xb8, 0x83e: 0xb8, 0x83f: 0xb8, // Block 0x21, offset 0x840 0x840: 0x0b, 0x841: 0x0b, 0x842: 0x0b, 0x843: 0x0b, 0x844: 0x0b, 0x845: 0x0b, 0x846: 0x0b, 0x847: 0x0b, 0x848: 0x0b, 0x849: 0x0b, 0x84a: 0x0b, 0x84b: 0x0b, 0x84c: 0x0b, 0x84d: 0x0b, 0x84e: 0x0b, 0x84f: 0x0b, 0x850: 0x0b, 0x851: 0x0b, 0x852: 0x0b, 0x853: 0x0b, 0x854: 0x0b, 0x855: 0x0b, 0x856: 0x0b, 0x857: 0x0b, 0x858: 0x0b, 0x859: 0x0b, 0x85a: 0x0b, 0x85b: 0x0b, 0x85c: 0x0b, 0x85d: 0x0b, 0x85e: 0x0b, 0x85f: 0x0b, 0x860: 0x1e, 0x861: 0x0b, 0x862: 0x0b, 0x863: 0x0b, 0x864: 0x0b, 0x865: 0x0b, 0x866: 0x0b, 0x867: 0x0b, 0x868: 0x0b, 0x869: 0x0b, 0x86a: 0x0b, 0x86b: 0x0b, 0x86c: 0x0b, 0x86d: 0x0b, 0x86e: 0x0b, 0x86f: 0x0b, 0x870: 0x0b, 0x871: 0x0b, 0x872: 0x0b, 0x873: 0x0b, 0x874: 0x0b, 0x875: 0x0b, 0x876: 0x0b, 0x877: 0x0b, 0x878: 0x0b, 0x879: 0x0b, 0x87a: 0x0b, 0x87b: 0x0b, 0x87c: 0x0b, 0x87d: 0x0b, 0x87e: 0x0b, 0x87f: 0x0b, // Block 0x22, offset 0x880 0x880: 0x0b, 0x881: 0x0b, 0x882: 0x0b, 0x883: 0x0b, 0x884: 0x0b, 0x885: 0x0b, 0x886: 0x0b, 0x887: 0x0b, 0x888: 0x0b, 0x889: 0x0b, 0x88a: 0x0b, 0x88b: 0x0b, 0x88c: 0x0b, 0x88d: 0x0b, 0x88e: 0x0b, 0x88f: 0x0b, } // idnaSparseOffset: 256 entries, 512 bytes var idnaSparseOffset = []uint16{0x0, 0x8, 0x19, 0x25, 0x27, 0x2c, 0x34, 0x3f, 0x4b, 0x5c, 0x60, 0x6f, 0x74, 0x7b, 0x87, 0x95, 0xa3, 0xa8, 0xb1, 0xc1, 0xcf, 0xdc, 0xe8, 0xf9, 0x103, 0x10a, 0x117, 0x128, 0x12f, 0x13a, 0x149, 0x157, 0x161, 0x163, 0x167, 0x169, 0x175, 0x180, 0x188, 0x18e, 0x194, 0x199, 0x19e, 0x1a1, 0x1a5, 0x1ab, 0x1b0, 0x1bc, 0x1c6, 0x1cc, 0x1dd, 0x1e7, 0x1ea, 0x1f2, 0x1f5, 0x202, 0x20a, 0x20e, 0x215, 0x21d, 0x22d, 0x239, 0x23b, 0x245, 0x251, 0x25d, 0x269, 0x271, 0x276, 0x280, 0x291, 0x295, 0x2a0, 0x2a4, 0x2ad, 0x2b5, 0x2bb, 0x2c0, 0x2c3, 0x2c6, 0x2ca, 0x2d0, 0x2d4, 0x2d8, 0x2de, 0x2e5, 0x2eb, 0x2f3, 0x2fa, 0x305, 0x30f, 0x313, 0x316, 0x31c, 0x320, 0x322, 0x325, 0x327, 0x32a, 0x334, 0x337, 0x346, 0x34a, 0x34f, 0x352, 0x356, 0x35b, 0x360, 0x366, 0x36c, 0x37b, 0x381, 0x385, 0x394, 0x399, 0x3a1, 0x3ab, 0x3b6, 0x3be, 0x3cf, 0x3d8, 0x3e8, 0x3f5, 0x3ff, 0x404, 0x411, 0x415, 0x41a, 0x41c, 0x420, 0x422, 0x426, 0x42f, 0x435, 0x439, 0x449, 0x453, 0x458, 0x45b, 0x461, 0x468, 0x46d, 0x471, 0x477, 0x47c, 0x485, 0x48a, 0x490, 0x497, 0x49e, 0x4a5, 0x4a9, 0x4ae, 0x4b1, 0x4b6, 0x4c2, 0x4c8, 0x4cd, 0x4d4, 0x4dc, 0x4e1, 0x4e5, 0x4f5, 0x4fc, 0x500, 0x504, 0x50b, 0x50e, 0x511, 0x515, 0x519, 0x51f, 0x528, 0x534, 0x53b, 0x544, 0x54c, 0x553, 0x561, 0x56e, 0x57b, 0x584, 0x588, 0x596, 0x59e, 0x5a9, 0x5b2, 0x5b8, 0x5c0, 0x5c9, 0x5d3, 0x5d6, 0x5e2, 0x5e5, 0x5ea, 0x5ed, 0x5f7, 0x600, 0x60c, 0x60f, 0x614, 0x617, 0x61a, 0x61d, 0x624, 0x62b, 0x62f, 0x63a, 0x63d, 0x643, 0x648, 0x64c, 0x64f, 0x652, 0x655, 0x65a, 0x664, 0x667, 0x66b, 0x67a, 0x686, 0x68a, 0x68f, 0x694, 0x698, 0x69d, 0x6a6, 0x6b1, 0x6b7, 0x6bf, 0x6c3, 0x6c7, 0x6cd, 0x6d3, 0x6d8, 0x6db, 0x6e9, 0x6f0, 0x6f3, 0x6f6, 0x6fa, 0x700, 0x705, 0x70f, 0x714, 0x717, 0x71a, 0x71d, 0x720, 0x724, 0x727, 0x737, 0x748, 0x74d, 0x74f, 0x751} // idnaSparseValues: 1876 entries, 7504 bytes var idnaSparseValues = [1876]valueRange{ // Block 0x0, offset 0x0 {value: 0x0000, lo: 0x07}, {value: 0xe105, lo: 0x80, hi: 0x96}, {value: 0x0018, lo: 0x97, hi: 0x97}, {value: 0xe105, lo: 0x98, hi: 0x9e}, {value: 0x001f, lo: 0x9f, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xb6}, {value: 0x0018, lo: 0xb7, hi: 0xb7}, {value: 0x0008, lo: 0xb8, hi: 0xbf}, // Block 0x1, offset 0x8 {value: 0x0000, lo: 0x10}, {value: 0x0008, lo: 0x80, hi: 0x80}, {value: 0xe01d, lo: 0x81, hi: 0x81}, {value: 0x0008, lo: 0x82, hi: 0x82}, {value: 0x0335, lo: 0x83, hi: 0x83}, {value: 0x034d, lo: 0x84, hi: 0x84}, {value: 0x0365, lo: 0x85, hi: 0x85}, {value: 0xe00d, lo: 0x86, hi: 0x86}, {value: 0x0008, lo: 0x87, hi: 0x87}, {value: 0xe00d, lo: 0x88, hi: 0x88}, {value: 0x0008, lo: 0x89, hi: 0x89}, {value: 0xe00d, lo: 0x8a, hi: 0x8a}, {value: 0x0008, lo: 0x8b, hi: 0x8b}, {value: 0xe00d, lo: 0x8c, hi: 0x8c}, {value: 0x0008, lo: 0x8d, hi: 0x8d}, {value: 0xe00d, lo: 0x8e, hi: 0x8e}, {value: 0x0008, lo: 0x8f, hi: 0xbf}, // Block 0x2, offset 0x19 {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0xaf}, {value: 0x0249, lo: 0xb0, hi: 0xb0}, {value: 0x037d, lo: 0xb1, hi: 0xb1}, {value: 0x0259, lo: 0xb2, hi: 0xb2}, {value: 0x0269, lo: 0xb3, hi: 0xb3}, {value: 0x034d, lo: 0xb4, hi: 0xb4}, {value: 0x0395, lo: 0xb5, hi: 0xb5}, {value: 0xe1bd, lo: 0xb6, hi: 0xb6}, {value: 0x0279, lo: 0xb7, hi: 0xb7}, {value: 0x0289, lo: 0xb8, hi: 0xb8}, {value: 0x0008, lo: 0xb9, hi: 0xbf}, // Block 0x3, offset 0x25 {value: 0x0000, lo: 0x01}, {value: 0x1308, lo: 0x80, hi: 0xbf}, // Block 0x4, offset 0x27 {value: 0x0000, lo: 0x04}, {value: 0x03f5, lo: 0x80, hi: 0x8f}, {value: 0xe105, lo: 0x90, hi: 0x9f}, {value: 0x049d, lo: 0xa0, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x5, offset 0x2c {value: 0x0000, lo: 0x07}, {value: 0xe185, lo: 0x80, hi: 0x8f}, {value: 0x0545, lo: 0x90, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x98}, {value: 0x0008, lo: 0x99, hi: 0x99}, {value: 0x0018, lo: 0x9a, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xa0}, {value: 0x0008, lo: 0xa1, hi: 0xbf}, // Block 0x6, offset 0x34 {value: 0x0000, lo: 0x0a}, {value: 0x0008, lo: 0x80, hi: 0x86}, {value: 0x0401, lo: 0x87, hi: 0x87}, {value: 0x0040, lo: 0x88, hi: 0x88}, {value: 0x0018, lo: 0x89, hi: 0x8a}, {value: 0x0040, lo: 0x8b, hi: 0x8c}, {value: 0x0018, lo: 0x8d, hi: 0x8f}, {value: 0x0040, lo: 0x90, hi: 0x90}, {value: 0x1308, lo: 0x91, hi: 0xbd}, {value: 0x0018, lo: 0xbe, hi: 0xbe}, {value: 0x1308, lo: 0xbf, hi: 0xbf}, // Block 0x7, offset 0x3f {value: 0x0000, lo: 0x0b}, {value: 0x0018, lo: 0x80, hi: 0x80}, {value: 0x1308, lo: 0x81, hi: 0x82}, {value: 0x0018, lo: 0x83, hi: 0x83}, {value: 0x1308, lo: 0x84, hi: 0x85}, {value: 0x0018, lo: 0x86, hi: 0x86}, {value: 0x1308, lo: 0x87, hi: 0x87}, {value: 0x0040, lo: 0x88, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xaa}, {value: 0x0040, lo: 0xab, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xb4}, {value: 0x0040, lo: 0xb5, hi: 0xbf}, // Block 0x8, offset 0x4b {value: 0x0000, lo: 0x10}, {value: 0x0018, lo: 0x80, hi: 0x80}, {value: 0x0208, lo: 0x81, hi: 0x87}, {value: 0x0408, lo: 0x88, hi: 0x88}, {value: 0x0208, lo: 0x89, hi: 0x8a}, {value: 0x1308, lo: 0x8b, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa9}, {value: 0x0018, lo: 0xaa, hi: 0xad}, {value: 0x0208, lo: 0xae, hi: 0xaf}, {value: 0x1308, lo: 0xb0, hi: 0xb0}, {value: 0x0408, lo: 0xb1, hi: 0xb3}, {value: 0x0008, lo: 0xb4, hi: 0xb4}, {value: 0x0429, lo: 0xb5, hi: 0xb5}, {value: 0x0451, lo: 0xb6, hi: 0xb6}, {value: 0x0479, lo: 0xb7, hi: 0xb7}, {value: 0x04a1, lo: 0xb8, hi: 0xb8}, {value: 0x0208, lo: 0xb9, hi: 0xbf}, // Block 0x9, offset 0x5c {value: 0x0000, lo: 0x03}, {value: 0x0208, lo: 0x80, hi: 0x87}, {value: 0x0408, lo: 0x88, hi: 0x99}, {value: 0x0208, lo: 0x9a, hi: 0xbf}, // Block 0xa, offset 0x60 {value: 0x0000, lo: 0x0e}, {value: 0x1308, lo: 0x80, hi: 0x8a}, {value: 0x0040, lo: 0x8b, hi: 0x8c}, {value: 0x0408, lo: 0x8d, hi: 0x8d}, {value: 0x0208, lo: 0x8e, hi: 0x98}, {value: 0x0408, lo: 0x99, hi: 0x9b}, {value: 0x0208, lo: 0x9c, hi: 0xaa}, {value: 0x0408, lo: 0xab, hi: 0xac}, {value: 0x0208, lo: 0xad, hi: 0xb0}, {value: 0x0408, lo: 0xb1, hi: 0xb1}, {value: 0x0208, lo: 0xb2, hi: 0xb2}, {value: 0x0408, lo: 0xb3, hi: 0xb4}, {value: 0x0208, lo: 0xb5, hi: 0xb7}, {value: 0x0408, lo: 0xb8, hi: 0xb9}, {value: 0x0208, lo: 0xba, hi: 0xbf}, // Block 0xb, offset 0x6f {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0xa5}, {value: 0x1308, lo: 0xa6, hi: 0xb0}, {value: 0x0008, lo: 0xb1, hi: 0xb1}, {value: 0x0040, lo: 0xb2, hi: 0xbf}, // Block 0xc, offset 0x74 {value: 0x0000, lo: 0x06}, {value: 0x0008, lo: 0x80, hi: 0x89}, {value: 0x0208, lo: 0x8a, hi: 0xaa}, {value: 0x1308, lo: 0xab, hi: 0xb3}, {value: 0x0008, lo: 0xb4, hi: 0xb5}, {value: 0x0018, lo: 0xb6, hi: 0xba}, {value: 0x0040, lo: 0xbb, hi: 0xbf}, // Block 0xd, offset 0x7b {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0x95}, {value: 0x1308, lo: 0x96, hi: 0x99}, {value: 0x0008, lo: 0x9a, hi: 0x9a}, {value: 0x1308, lo: 0x9b, hi: 0xa3}, {value: 0x0008, lo: 0xa4, hi: 0xa4}, {value: 0x1308, lo: 0xa5, hi: 0xa7}, {value: 0x0008, lo: 0xa8, hi: 0xa8}, {value: 0x1308, lo: 0xa9, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0xe, offset 0x87 {value: 0x0000, lo: 0x0d}, {value: 0x0408, lo: 0x80, hi: 0x80}, {value: 0x0208, lo: 0x81, hi: 0x85}, {value: 0x0408, lo: 0x86, hi: 0x87}, {value: 0x0208, lo: 0x88, hi: 0x88}, {value: 0x0408, lo: 0x89, hi: 0x89}, {value: 0x0208, lo: 0x8a, hi: 0x93}, {value: 0x0408, lo: 0x94, hi: 0x94}, {value: 0x0208, lo: 0x95, hi: 0x95}, {value: 0x0008, lo: 0x96, hi: 0x98}, {value: 0x1308, lo: 0x99, hi: 0x9b}, {value: 0x0040, lo: 0x9c, hi: 0x9d}, {value: 0x0018, lo: 0x9e, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0xbf}, // Block 0xf, offset 0x95 {value: 0x0000, lo: 0x0d}, {value: 0x0040, lo: 0x80, hi: 0x9f}, {value: 0x0208, lo: 0xa0, hi: 0xa9}, {value: 0x0408, lo: 0xaa, hi: 0xac}, {value: 0x0008, lo: 0xad, hi: 0xad}, {value: 0x0408, lo: 0xae, hi: 0xae}, {value: 0x0208, lo: 0xaf, hi: 0xb0}, {value: 0x0408, lo: 0xb1, hi: 0xb2}, {value: 0x0208, lo: 0xb3, hi: 0xb4}, {value: 0x0040, lo: 0xb5, hi: 0xb5}, {value: 0x0208, lo: 0xb6, hi: 0xb8}, {value: 0x0408, lo: 0xb9, hi: 0xb9}, {value: 0x0208, lo: 0xba, hi: 0xbd}, {value: 0x0040, lo: 0xbe, hi: 0xbf}, // Block 0x10, offset 0xa3 {value: 0x0000, lo: 0x04}, {value: 0x0040, lo: 0x80, hi: 0x93}, {value: 0x1308, lo: 0x94, hi: 0xa1}, {value: 0x0040, lo: 0xa2, hi: 0xa2}, {value: 0x1308, lo: 0xa3, hi: 0xbf}, // Block 0x11, offset 0xa8 {value: 0x0000, lo: 0x08}, {value: 0x1308, lo: 0x80, hi: 0x82}, {value: 0x1008, lo: 0x83, hi: 0x83}, {value: 0x0008, lo: 0x84, hi: 0xb9}, {value: 0x1308, lo: 0xba, hi: 0xba}, {value: 0x1008, lo: 0xbb, hi: 0xbb}, {value: 0x1308, lo: 0xbc, hi: 0xbc}, {value: 0x0008, lo: 0xbd, hi: 0xbd}, {value: 0x1008, lo: 0xbe, hi: 0xbf}, // Block 0x12, offset 0xb1 {value: 0x0000, lo: 0x0f}, {value: 0x1308, lo: 0x80, hi: 0x80}, {value: 0x1008, lo: 0x81, hi: 0x82}, {value: 0x0040, lo: 0x83, hi: 0x85}, {value: 0x1008, lo: 0x86, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x89}, {value: 0x1008, lo: 0x8a, hi: 0x8c}, {value: 0x1b08, lo: 0x8d, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x90}, {value: 0x0040, lo: 0x91, hi: 0x96}, {value: 0x1008, lo: 0x97, hi: 0x97}, {value: 0x0040, lo: 0x98, hi: 0xa5}, {value: 0x0008, lo: 0xa6, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xba}, {value: 0x0040, lo: 0xbb, hi: 0xbf}, // Block 0x13, offset 0xc1 {value: 0x0000, lo: 0x0d}, {value: 0x1308, lo: 0x80, hi: 0x80}, {value: 0x1008, lo: 0x81, hi: 0x83}, {value: 0x0040, lo: 0x84, hi: 0x84}, {value: 0x0008, lo: 0x85, hi: 0x8c}, {value: 0x0040, lo: 0x8d, hi: 0x8d}, {value: 0x0008, lo: 0x8e, hi: 0x90}, {value: 0x0040, lo: 0x91, hi: 0x91}, {value: 0x0008, lo: 0x92, hi: 0xa8}, {value: 0x0040, lo: 0xa9, hi: 0xa9}, {value: 0x0008, lo: 0xaa, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbc}, {value: 0x0008, lo: 0xbd, hi: 0xbd}, {value: 0x1308, lo: 0xbe, hi: 0xbf}, // Block 0x14, offset 0xcf {value: 0x0000, lo: 0x0c}, {value: 0x0040, lo: 0x80, hi: 0x80}, {value: 0x1308, lo: 0x81, hi: 0x81}, {value: 0x1008, lo: 0x82, hi: 0x83}, {value: 0x0040, lo: 0x84, hi: 0x84}, {value: 0x0008, lo: 0x85, hi: 0x8c}, {value: 0x0040, lo: 0x8d, hi: 0x8d}, {value: 0x0008, lo: 0x8e, hi: 0x90}, {value: 0x0040, lo: 0x91, hi: 0x91}, {value: 0x0008, lo: 0x92, hi: 0xba}, {value: 0x0040, lo: 0xbb, hi: 0xbc}, {value: 0x0008, lo: 0xbd, hi: 0xbd}, {value: 0x1008, lo: 0xbe, hi: 0xbf}, // Block 0x15, offset 0xdc {value: 0x0000, lo: 0x0b}, {value: 0x0040, lo: 0x80, hi: 0x81}, {value: 0x1008, lo: 0x82, hi: 0x83}, {value: 0x0040, lo: 0x84, hi: 0x84}, {value: 0x0008, lo: 0x85, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x99}, {value: 0x0008, lo: 0x9a, hi: 0xb1}, {value: 0x0040, lo: 0xb2, hi: 0xb2}, {value: 0x0008, lo: 0xb3, hi: 0xbb}, {value: 0x0040, lo: 0xbc, hi: 0xbc}, {value: 0x0008, lo: 0xbd, hi: 0xbd}, {value: 0x0040, lo: 0xbe, hi: 0xbf}, // Block 0x16, offset 0xe8 {value: 0x0000, lo: 0x10}, {value: 0x0008, lo: 0x80, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x89}, {value: 0x1b08, lo: 0x8a, hi: 0x8a}, {value: 0x0040, lo: 0x8b, hi: 0x8e}, {value: 0x1008, lo: 0x8f, hi: 0x91}, {value: 0x1308, lo: 0x92, hi: 0x94}, {value: 0x0040, lo: 0x95, hi: 0x95}, {value: 0x1308, lo: 0x96, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x97}, {value: 0x1008, lo: 0x98, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xa5}, {value: 0x0008, lo: 0xa6, hi: 0xaf}, {value: 0x0040, lo: 0xb0, hi: 0xb1}, {value: 0x1008, lo: 0xb2, hi: 0xb3}, {value: 0x0018, lo: 0xb4, hi: 0xb4}, {value: 0x0040, lo: 0xb5, hi: 0xbf}, // Block 0x17, offset 0xf9 {value: 0x0000, lo: 0x09}, {value: 0x0040, lo: 0x80, hi: 0x80}, {value: 0x0008, lo: 0x81, hi: 0xb0}, {value: 0x1308, lo: 0xb1, hi: 0xb1}, {value: 0x0008, lo: 0xb2, hi: 0xb2}, {value: 0x08f1, lo: 0xb3, hi: 0xb3}, {value: 0x1308, lo: 0xb4, hi: 0xb9}, {value: 0x1b08, lo: 0xba, hi: 0xba}, {value: 0x0040, lo: 0xbb, hi: 0xbe}, {value: 0x0018, lo: 0xbf, hi: 0xbf}, // Block 0x18, offset 0x103 {value: 0x0000, lo: 0x06}, {value: 0x0008, lo: 0x80, hi: 0x86}, {value: 0x1308, lo: 0x87, hi: 0x8e}, {value: 0x0018, lo: 0x8f, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0018, lo: 0x9a, hi: 0x9b}, {value: 0x0040, lo: 0x9c, hi: 0xbf}, // Block 0x19, offset 0x10a {value: 0x0000, lo: 0x0c}, {value: 0x0008, lo: 0x80, hi: 0x84}, {value: 0x0040, lo: 0x85, hi: 0x85}, {value: 0x0008, lo: 0x86, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x87}, {value: 0x1308, lo: 0x88, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9b}, {value: 0x0961, lo: 0x9c, hi: 0x9c}, {value: 0x0999, lo: 0x9d, hi: 0x9d}, {value: 0x0008, lo: 0x9e, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xbf}, // Block 0x1a, offset 0x117 {value: 0x0000, lo: 0x10}, {value: 0x0008, lo: 0x80, hi: 0x80}, {value: 0x0018, lo: 0x81, hi: 0x8a}, {value: 0x0008, lo: 0x8b, hi: 0x8b}, {value: 0xe03d, lo: 0x8c, hi: 0x8c}, {value: 0x0018, lo: 0x8d, hi: 0x97}, {value: 0x1308, lo: 0x98, hi: 0x99}, {value: 0x0018, lo: 0x9a, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa9}, {value: 0x0018, lo: 0xaa, hi: 0xb4}, {value: 0x1308, lo: 0xb5, hi: 0xb5}, {value: 0x0018, lo: 0xb6, hi: 0xb6}, {value: 0x1308, lo: 0xb7, hi: 0xb7}, {value: 0x0018, lo: 0xb8, hi: 0xb8}, {value: 0x1308, lo: 0xb9, hi: 0xb9}, {value: 0x0018, lo: 0xba, hi: 0xbd}, {value: 0x1008, lo: 0xbe, hi: 0xbf}, // Block 0x1b, offset 0x128 {value: 0x0000, lo: 0x06}, {value: 0x0018, lo: 0x80, hi: 0x85}, {value: 0x1308, lo: 0x86, hi: 0x86}, {value: 0x0018, lo: 0x87, hi: 0x8c}, {value: 0x0040, lo: 0x8d, hi: 0x8d}, {value: 0x0018, lo: 0x8e, hi: 0x9a}, {value: 0x0040, lo: 0x9b, hi: 0xbf}, // Block 0x1c, offset 0x12f {value: 0x0000, lo: 0x0a}, {value: 0x0008, lo: 0x80, hi: 0xaa}, {value: 0x1008, lo: 0xab, hi: 0xac}, {value: 0x1308, lo: 0xad, hi: 0xb0}, {value: 0x1008, lo: 0xb1, hi: 0xb1}, {value: 0x1308, lo: 0xb2, hi: 0xb7}, {value: 0x1008, lo: 0xb8, hi: 0xb8}, {value: 0x1b08, lo: 0xb9, hi: 0xba}, {value: 0x1008, lo: 0xbb, hi: 0xbc}, {value: 0x1308, lo: 0xbd, hi: 0xbe}, {value: 0x0008, lo: 0xbf, hi: 0xbf}, // Block 0x1d, offset 0x13a {value: 0x0000, lo: 0x0e}, {value: 0x0008, lo: 0x80, hi: 0x89}, {value: 0x0018, lo: 0x8a, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x95}, {value: 0x1008, lo: 0x96, hi: 0x97}, {value: 0x1308, lo: 0x98, hi: 0x99}, {value: 0x0008, lo: 0x9a, hi: 0x9d}, {value: 0x1308, lo: 0x9e, hi: 0xa0}, {value: 0x0008, lo: 0xa1, hi: 0xa1}, {value: 0x1008, lo: 0xa2, hi: 0xa4}, {value: 0x0008, lo: 0xa5, hi: 0xa6}, {value: 0x1008, lo: 0xa7, hi: 0xad}, {value: 0x0008, lo: 0xae, hi: 0xb0}, {value: 0x1308, lo: 0xb1, hi: 0xb4}, {value: 0x0008, lo: 0xb5, hi: 0xbf}, // Block 0x1e, offset 0x149 {value: 0x0000, lo: 0x0d}, {value: 0x0008, lo: 0x80, hi: 0x81}, {value: 0x1308, lo: 0x82, hi: 0x82}, {value: 0x1008, lo: 0x83, hi: 0x84}, {value: 0x1308, lo: 0x85, hi: 0x86}, {value: 0x1008, lo: 0x87, hi: 0x8c}, {value: 0x1308, lo: 0x8d, hi: 0x8d}, {value: 0x0008, lo: 0x8e, hi: 0x8e}, {value: 0x1008, lo: 0x8f, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x1008, lo: 0x9a, hi: 0x9c}, {value: 0x1308, lo: 0x9d, hi: 0x9d}, {value: 0x0018, lo: 0x9e, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xbf}, // Block 0x1f, offset 0x157 {value: 0x0000, lo: 0x09}, {value: 0x0040, lo: 0x80, hi: 0x86}, {value: 0x055d, lo: 0x87, hi: 0x87}, {value: 0x0040, lo: 0x88, hi: 0x8c}, {value: 0x055d, lo: 0x8d, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xba}, {value: 0x0018, lo: 0xbb, hi: 0xbb}, {value: 0xe105, lo: 0xbc, hi: 0xbc}, {value: 0x0008, lo: 0xbd, hi: 0xbf}, // Block 0x20, offset 0x161 {value: 0x0000, lo: 0x01}, {value: 0x0018, lo: 0x80, hi: 0xbf}, // Block 0x21, offset 0x163 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0xa0}, {value: 0x0018, lo: 0xa1, hi: 0xbf}, // Block 0x22, offset 0x167 {value: 0x0000, lo: 0x01}, {value: 0x0008, lo: 0x80, hi: 0xbf}, // Block 0x23, offset 0x169 {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x89}, {value: 0x0008, lo: 0x8a, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x97}, {value: 0x0008, lo: 0x98, hi: 0x98}, {value: 0x0040, lo: 0x99, hi: 0x99}, {value: 0x0008, lo: 0x9a, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xbf}, // Block 0x24, offset 0x175 {value: 0x0000, lo: 0x0a}, {value: 0x0008, lo: 0x80, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x89}, {value: 0x0008, lo: 0x8a, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xb0}, {value: 0x0040, lo: 0xb1, hi: 0xb1}, {value: 0x0008, lo: 0xb2, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xb7}, {value: 0x0008, lo: 0xb8, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0x25, offset 0x180 {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0x80}, {value: 0x0040, lo: 0x81, hi: 0x81}, {value: 0x0008, lo: 0x82, hi: 0x85}, {value: 0x0040, lo: 0x86, hi: 0x87}, {value: 0x0008, lo: 0x88, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x97}, {value: 0x0008, lo: 0x98, hi: 0xbf}, // Block 0x26, offset 0x188 {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0x90}, {value: 0x0040, lo: 0x91, hi: 0x91}, {value: 0x0008, lo: 0x92, hi: 0x95}, {value: 0x0040, lo: 0x96, hi: 0x97}, {value: 0x0008, lo: 0x98, hi: 0xbf}, // Block 0x27, offset 0x18e {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0x9a}, {value: 0x0040, lo: 0x9b, hi: 0x9c}, {value: 0x1308, lo: 0x9d, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xbc}, {value: 0x0040, lo: 0xbd, hi: 0xbf}, // Block 0x28, offset 0x194 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xbf}, // Block 0x29, offset 0x199 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xb7}, {value: 0xe045, lo: 0xb8, hi: 0xbd}, {value: 0x0040, lo: 0xbe, hi: 0xbf}, // Block 0x2a, offset 0x19e {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0x80}, {value: 0x0008, lo: 0x81, hi: 0xbf}, // Block 0x2b, offset 0x1a1 {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0xac}, {value: 0x0018, lo: 0xad, hi: 0xae}, {value: 0x0008, lo: 0xaf, hi: 0xbf}, // Block 0x2c, offset 0x1a5 {value: 0x0000, lo: 0x05}, {value: 0x0040, lo: 0x80, hi: 0x80}, {value: 0x0008, lo: 0x81, hi: 0x9a}, {value: 0x0018, lo: 0x9b, hi: 0x9c}, {value: 0x0040, lo: 0x9d, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xbf}, // Block 0x2d, offset 0x1ab {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0xaa}, {value: 0x0018, lo: 0xab, hi: 0xb0}, {value: 0x0008, lo: 0xb1, hi: 0xb8}, {value: 0x0040, lo: 0xb9, hi: 0xbf}, // Block 0x2e, offset 0x1b0 {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0x8c}, {value: 0x0040, lo: 0x8d, hi: 0x8d}, {value: 0x0008, lo: 0x8e, hi: 0x91}, {value: 0x1308, lo: 0x92, hi: 0x93}, {value: 0x1b08, lo: 0x94, hi: 0x94}, {value: 0x0040, lo: 0x95, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xb1}, {value: 0x1308, lo: 0xb2, hi: 0xb3}, {value: 0x1b08, lo: 0xb4, hi: 0xb4}, {value: 0x0018, lo: 0xb5, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xbf}, // Block 0x2f, offset 0x1bc {value: 0x0000, lo: 0x09}, {value: 0x0008, lo: 0x80, hi: 0x91}, {value: 0x1308, lo: 0x92, hi: 0x93}, {value: 0x0040, lo: 0x94, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xac}, {value: 0x0040, lo: 0xad, hi: 0xad}, {value: 0x0008, lo: 0xae, hi: 0xb0}, {value: 0x0040, lo: 0xb1, hi: 0xb1}, {value: 0x1308, lo: 0xb2, hi: 0xb3}, {value: 0x0040, lo: 0xb4, hi: 0xbf}, // Block 0x30, offset 0x1c6 {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0xb3}, {value: 0x1340, lo: 0xb4, hi: 0xb5}, {value: 0x1008, lo: 0xb6, hi: 0xb6}, {value: 0x1308, lo: 0xb7, hi: 0xbd}, {value: 0x1008, lo: 0xbe, hi: 0xbf}, // Block 0x31, offset 0x1cc {value: 0x0000, lo: 0x10}, {value: 0x1008, lo: 0x80, hi: 0x85}, {value: 0x1308, lo: 0x86, hi: 0x86}, {value: 0x1008, lo: 0x87, hi: 0x88}, {value: 0x1308, lo: 0x89, hi: 0x91}, {value: 0x1b08, lo: 0x92, hi: 0x92}, {value: 0x1308, lo: 0x93, hi: 0x93}, {value: 0x0018, lo: 0x94, hi: 0x96}, {value: 0x0008, lo: 0x97, hi: 0x97}, {value: 0x0018, lo: 0x98, hi: 0x9b}, {value: 0x0008, lo: 0x9c, hi: 0x9c}, {value: 0x1308, lo: 0x9d, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa9}, {value: 0x0040, lo: 0xaa, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbf}, // Block 0x32, offset 0x1dd {value: 0x0000, lo: 0x09}, {value: 0x0018, lo: 0x80, hi: 0x85}, {value: 0x0040, lo: 0x86, hi: 0x86}, {value: 0x0218, lo: 0x87, hi: 0x87}, {value: 0x0018, lo: 0x88, hi: 0x8a}, {value: 0x13c0, lo: 0x8b, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9f}, {value: 0x0208, lo: 0xa0, hi: 0xbf}, // Block 0x33, offset 0x1e7 {value: 0x0000, lo: 0x02}, {value: 0x0208, lo: 0x80, hi: 0xb7}, {value: 0x0040, lo: 0xb8, hi: 0xbf}, // Block 0x34, offset 0x1ea {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0x84}, {value: 0x1308, lo: 0x85, hi: 0x86}, {value: 0x0208, lo: 0x87, hi: 0xa8}, {value: 0x1308, lo: 0xa9, hi: 0xa9}, {value: 0x0208, lo: 0xaa, hi: 0xaa}, {value: 0x0040, lo: 0xab, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x35, offset 0x1f2 {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xbf}, // Block 0x36, offset 0x1f5 {value: 0x0000, lo: 0x0c}, {value: 0x0008, lo: 0x80, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0x9f}, {value: 0x1308, lo: 0xa0, hi: 0xa2}, {value: 0x1008, lo: 0xa3, hi: 0xa6}, {value: 0x1308, lo: 0xa7, hi: 0xa8}, {value: 0x1008, lo: 0xa9, hi: 0xab}, {value: 0x0040, lo: 0xac, hi: 0xaf}, {value: 0x1008, lo: 0xb0, hi: 0xb1}, {value: 0x1308, lo: 0xb2, hi: 0xb2}, {value: 0x1008, lo: 0xb3, hi: 0xb8}, {value: 0x1308, lo: 0xb9, hi: 0xbb}, {value: 0x0040, lo: 0xbc, hi: 0xbf}, // Block 0x37, offset 0x202 {value: 0x0000, lo: 0x07}, {value: 0x0018, lo: 0x80, hi: 0x80}, {value: 0x0040, lo: 0x81, hi: 0x83}, {value: 0x0018, lo: 0x84, hi: 0x85}, {value: 0x0008, lo: 0x86, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xb4}, {value: 0x0040, lo: 0xb5, hi: 0xbf}, // Block 0x38, offset 0x20a {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0xab}, {value: 0x0040, lo: 0xac, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x39, offset 0x20e {value: 0x0000, lo: 0x06}, {value: 0x0008, lo: 0x80, hi: 0x89}, {value: 0x0040, lo: 0x8a, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0028, lo: 0x9a, hi: 0x9a}, {value: 0x0040, lo: 0x9b, hi: 0x9d}, {value: 0x0018, lo: 0x9e, hi: 0xbf}, // Block 0x3a, offset 0x215 {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0x96}, {value: 0x1308, lo: 0x97, hi: 0x98}, {value: 0x1008, lo: 0x99, hi: 0x9a}, {value: 0x1308, lo: 0x9b, hi: 0x9b}, {value: 0x0040, lo: 0x9c, hi: 0x9d}, {value: 0x0018, lo: 0x9e, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xbf}, // Block 0x3b, offset 0x21d {value: 0x0000, lo: 0x0f}, {value: 0x0008, lo: 0x80, hi: 0x94}, {value: 0x1008, lo: 0x95, hi: 0x95}, {value: 0x1308, lo: 0x96, hi: 0x96}, {value: 0x1008, lo: 0x97, hi: 0x97}, {value: 0x1308, lo: 0x98, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0x9f}, {value: 0x1b08, lo: 0xa0, hi: 0xa0}, {value: 0x1008, lo: 0xa1, hi: 0xa1}, {value: 0x1308, lo: 0xa2, hi: 0xa2}, {value: 0x1008, lo: 0xa3, hi: 0xa4}, {value: 0x1308, lo: 0xa5, hi: 0xac}, {value: 0x1008, lo: 0xad, hi: 0xb2}, {value: 0x1308, lo: 0xb3, hi: 0xbc}, {value: 0x0040, lo: 0xbd, hi: 0xbe}, {value: 0x1308, lo: 0xbf, hi: 0xbf}, // Block 0x3c, offset 0x22d {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0x89}, {value: 0x0040, lo: 0x8a, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xa6}, {value: 0x0008, lo: 0xa7, hi: 0xa7}, {value: 0x0018, lo: 0xa8, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xaf}, {value: 0x1308, lo: 0xb0, hi: 0xbd}, {value: 0x1318, lo: 0xbe, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0x3d, offset 0x239 {value: 0x0000, lo: 0x01}, {value: 0x0040, lo: 0x80, hi: 0xbf}, // Block 0x3e, offset 0x23b {value: 0x0000, lo: 0x09}, {value: 0x1308, lo: 0x80, hi: 0x83}, {value: 0x1008, lo: 0x84, hi: 0x84}, {value: 0x0008, lo: 0x85, hi: 0xb3}, {value: 0x1308, lo: 0xb4, hi: 0xb4}, {value: 0x1008, lo: 0xb5, hi: 0xb5}, {value: 0x1308, lo: 0xb6, hi: 0xba}, {value: 0x1008, lo: 0xbb, hi: 0xbb}, {value: 0x1308, lo: 0xbc, hi: 0xbc}, {value: 0x1008, lo: 0xbd, hi: 0xbf}, // Block 0x3f, offset 0x245 {value: 0x0000, lo: 0x0b}, {value: 0x1008, lo: 0x80, hi: 0x81}, {value: 0x1308, lo: 0x82, hi: 0x82}, {value: 0x1008, lo: 0x83, hi: 0x83}, {value: 0x1808, lo: 0x84, hi: 0x84}, {value: 0x0008, lo: 0x85, hi: 0x8b}, {value: 0x0040, lo: 0x8c, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0018, lo: 0x9a, hi: 0xaa}, {value: 0x1308, lo: 0xab, hi: 0xb3}, {value: 0x0018, lo: 0xb4, hi: 0xbc}, {value: 0x0040, lo: 0xbd, hi: 0xbf}, // Block 0x40, offset 0x251 {value: 0x0000, lo: 0x0b}, {value: 0x1308, lo: 0x80, hi: 0x81}, {value: 0x1008, lo: 0x82, hi: 0x82}, {value: 0x0008, lo: 0x83, hi: 0xa0}, {value: 0x1008, lo: 0xa1, hi: 0xa1}, {value: 0x1308, lo: 0xa2, hi: 0xa5}, {value: 0x1008, lo: 0xa6, hi: 0xa7}, {value: 0x1308, lo: 0xa8, hi: 0xa9}, {value: 0x1808, lo: 0xaa, hi: 0xaa}, {value: 0x1b08, lo: 0xab, hi: 0xab}, {value: 0x1308, lo: 0xac, hi: 0xad}, {value: 0x0008, lo: 0xae, hi: 0xbf}, // Block 0x41, offset 0x25d {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0xa5}, {value: 0x1308, lo: 0xa6, hi: 0xa6}, {value: 0x1008, lo: 0xa7, hi: 0xa7}, {value: 0x1308, lo: 0xa8, hi: 0xa9}, {value: 0x1008, lo: 0xaa, hi: 0xac}, {value: 0x1308, lo: 0xad, hi: 0xad}, {value: 0x1008, lo: 0xae, hi: 0xae}, {value: 0x1308, lo: 0xaf, hi: 0xb1}, {value: 0x1808, lo: 0xb2, hi: 0xb3}, {value: 0x0040, lo: 0xb4, hi: 0xbb}, {value: 0x0018, lo: 0xbc, hi: 0xbf}, // Block 0x42, offset 0x269 {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0xa3}, {value: 0x1008, lo: 0xa4, hi: 0xab}, {value: 0x1308, lo: 0xac, hi: 0xb3}, {value: 0x1008, lo: 0xb4, hi: 0xb5}, {value: 0x1308, lo: 0xb6, hi: 0xb7}, {value: 0x0040, lo: 0xb8, hi: 0xba}, {value: 0x0018, lo: 0xbb, hi: 0xbf}, // Block 0x43, offset 0x271 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0x89}, {value: 0x0040, lo: 0x8a, hi: 0x8c}, {value: 0x0008, lo: 0x8d, hi: 0xbd}, {value: 0x0018, lo: 0xbe, hi: 0xbf}, // Block 0x44, offset 0x276 {value: 0x0000, lo: 0x09}, {value: 0x0e29, lo: 0x80, hi: 0x80}, {value: 0x0e41, lo: 0x81, hi: 0x81}, {value: 0x0e59, lo: 0x82, hi: 0x82}, {value: 0x0e71, lo: 0x83, hi: 0x83}, {value: 0x0e89, lo: 0x84, hi: 0x85}, {value: 0x0ea1, lo: 0x86, hi: 0x86}, {value: 0x0eb9, lo: 0x87, hi: 0x87}, {value: 0x057d, lo: 0x88, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0xbf}, // Block 0x45, offset 0x280 {value: 0x0000, lo: 0x10}, {value: 0x0018, lo: 0x80, hi: 0x87}, {value: 0x0040, lo: 0x88, hi: 0x8f}, {value: 0x1308, lo: 0x90, hi: 0x92}, {value: 0x0018, lo: 0x93, hi: 0x93}, {value: 0x1308, lo: 0x94, hi: 0xa0}, {value: 0x1008, lo: 0xa1, hi: 0xa1}, {value: 0x1308, lo: 0xa2, hi: 0xa8}, {value: 0x0008, lo: 0xa9, hi: 0xac}, {value: 0x1308, lo: 0xad, hi: 0xad}, {value: 0x0008, lo: 0xae, hi: 0xb1}, {value: 0x1008, lo: 0xb2, hi: 0xb3}, {value: 0x1308, lo: 0xb4, hi: 0xb4}, {value: 0x0008, lo: 0xb5, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xb7}, {value: 0x1308, lo: 0xb8, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbf}, // Block 0x46, offset 0x291 {value: 0x0000, lo: 0x03}, {value: 0x1308, lo: 0x80, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xba}, {value: 0x1308, lo: 0xbb, hi: 0xbf}, // Block 0x47, offset 0x295 {value: 0x0000, lo: 0x0a}, {value: 0x0008, lo: 0x80, hi: 0x87}, {value: 0xe045, lo: 0x88, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x95}, {value: 0x0040, lo: 0x96, hi: 0x97}, {value: 0xe045, lo: 0x98, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa7}, {value: 0xe045, lo: 0xa8, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xb7}, {value: 0xe045, lo: 0xb8, hi: 0xbf}, // Block 0x48, offset 0x2a0 {value: 0x0000, lo: 0x03}, {value: 0x0040, lo: 0x80, hi: 0x8f}, {value: 0x1318, lo: 0x90, hi: 0xb0}, {value: 0x0040, lo: 0xb1, hi: 0xbf}, // Block 0x49, offset 0x2a4 {value: 0x0000, lo: 0x08}, {value: 0x0018, lo: 0x80, hi: 0x82}, {value: 0x0040, lo: 0x83, hi: 0x83}, {value: 0x0008, lo: 0x84, hi: 0x84}, {value: 0x0018, lo: 0x85, hi: 0x88}, {value: 0x24c1, lo: 0x89, hi: 0x89}, {value: 0x0018, lo: 0x8a, hi: 0x8b}, {value: 0x0040, lo: 0x8c, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0xbf}, // Block 0x4a, offset 0x2ad {value: 0x0000, lo: 0x07}, {value: 0x0018, lo: 0x80, hi: 0xab}, {value: 0x24f1, lo: 0xac, hi: 0xac}, {value: 0x2529, lo: 0xad, hi: 0xad}, {value: 0x0018, lo: 0xae, hi: 0xae}, {value: 0x2579, lo: 0xaf, hi: 0xaf}, {value: 0x25b1, lo: 0xb0, hi: 0xb0}, {value: 0x0018, lo: 0xb1, hi: 0xbf}, // Block 0x4b, offset 0x2b5 {value: 0x0000, lo: 0x05}, {value: 0x0018, lo: 0x80, hi: 0x9f}, {value: 0x0080, lo: 0xa0, hi: 0xa0}, {value: 0x0018, lo: 0xa1, hi: 0xad}, {value: 0x0080, lo: 0xae, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xbf}, // Block 0x4c, offset 0x2bb {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0xa8}, {value: 0x09c5, lo: 0xa9, hi: 0xa9}, {value: 0x09e5, lo: 0xaa, hi: 0xaa}, {value: 0x0018, lo: 0xab, hi: 0xbf}, // Block 0x4d, offset 0x2c0 {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0x4e, offset 0x2c3 {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0xa6}, {value: 0x0040, lo: 0xa7, hi: 0xbf}, // Block 0x4f, offset 0x2c6 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0x8b}, {value: 0x28c1, lo: 0x8c, hi: 0x8c}, {value: 0x0018, lo: 0x8d, hi: 0xbf}, // Block 0x50, offset 0x2ca {value: 0x0000, lo: 0x05}, {value: 0x0018, lo: 0x80, hi: 0xb3}, {value: 0x0e66, lo: 0xb4, hi: 0xb4}, {value: 0x292a, lo: 0xb5, hi: 0xb5}, {value: 0x0e86, lo: 0xb6, hi: 0xb6}, {value: 0x0018, lo: 0xb7, hi: 0xbf}, // Block 0x51, offset 0x2d0 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0x9b}, {value: 0x2941, lo: 0x9c, hi: 0x9c}, {value: 0x0018, lo: 0x9d, hi: 0xbf}, // Block 0x52, offset 0x2d4 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0xb3}, {value: 0x0040, lo: 0xb4, hi: 0xb5}, {value: 0x0018, lo: 0xb6, hi: 0xbf}, // Block 0x53, offset 0x2d8 {value: 0x0000, lo: 0x05}, {value: 0x0018, lo: 0x80, hi: 0x95}, {value: 0x0040, lo: 0x96, hi: 0x97}, {value: 0x0018, lo: 0x98, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbc}, {value: 0x0018, lo: 0xbd, hi: 0xbf}, // Block 0x54, offset 0x2de {value: 0x0000, lo: 0x06}, {value: 0x0018, lo: 0x80, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x89}, {value: 0x0018, lo: 0x8a, hi: 0x91}, {value: 0x0040, lo: 0x92, hi: 0xab}, {value: 0x0018, lo: 0xac, hi: 0xaf}, {value: 0x0040, lo: 0xb0, hi: 0xbf}, // Block 0x55, offset 0x2e5 {value: 0x0000, lo: 0x05}, {value: 0xe185, lo: 0x80, hi: 0x8f}, {value: 0x03f5, lo: 0x90, hi: 0x9f}, {value: 0x0ea5, lo: 0xa0, hi: 0xae}, {value: 0x0040, lo: 0xaf, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x56, offset 0x2eb {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0xa5}, {value: 0x0040, lo: 0xa6, hi: 0xa6}, {value: 0x0008, lo: 0xa7, hi: 0xa7}, {value: 0x0040, lo: 0xa8, hi: 0xac}, {value: 0x0008, lo: 0xad, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x57, offset 0x2f3 {value: 0x0000, lo: 0x06}, {value: 0x0008, lo: 0x80, hi: 0xa7}, {value: 0x0040, lo: 0xa8, hi: 0xae}, {value: 0xe075, lo: 0xaf, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb0}, {value: 0x0040, lo: 0xb1, hi: 0xbe}, {value: 0x1b08, lo: 0xbf, hi: 0xbf}, // Block 0x58, offset 0x2fa {value: 0x0000, lo: 0x0a}, {value: 0x0008, lo: 0x80, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa6}, {value: 0x0040, lo: 0xa7, hi: 0xa7}, {value: 0x0008, lo: 0xa8, hi: 0xae}, {value: 0x0040, lo: 0xaf, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xb7}, {value: 0x0008, lo: 0xb8, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0x59, offset 0x305 {value: 0x0000, lo: 0x09}, {value: 0x0008, lo: 0x80, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x87}, {value: 0x0008, lo: 0x88, hi: 0x8e}, {value: 0x0040, lo: 0x8f, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x97}, {value: 0x0008, lo: 0x98, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0x9f}, {value: 0x1308, lo: 0xa0, hi: 0xbf}, // Block 0x5a, offset 0x30f {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0xae}, {value: 0x0008, lo: 0xaf, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xbf}, // Block 0x5b, offset 0x313 {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0x84}, {value: 0x0040, lo: 0x85, hi: 0xbf}, // Block 0x5c, offset 0x316 {value: 0x0000, lo: 0x05}, {value: 0x0018, lo: 0x80, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9a}, {value: 0x0018, lo: 0x9b, hi: 0x9e}, {value: 0x0edd, lo: 0x9f, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xbf}, // Block 0x5d, offset 0x31c {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0xb2}, {value: 0x0efd, lo: 0xb3, hi: 0xb3}, {value: 0x0040, lo: 0xb4, hi: 0xbf}, // Block 0x5e, offset 0x320 {value: 0x0020, lo: 0x01}, {value: 0x0f1d, lo: 0x80, hi: 0xbf}, // Block 0x5f, offset 0x322 {value: 0x0020, lo: 0x02}, {value: 0x171d, lo: 0x80, hi: 0x8f}, {value: 0x18fd, lo: 0x90, hi: 0xbf}, // Block 0x60, offset 0x325 {value: 0x0020, lo: 0x01}, {value: 0x1efd, lo: 0x80, hi: 0xbf}, // Block 0x61, offset 0x327 {value: 0x0000, lo: 0x02}, {value: 0x0040, lo: 0x80, hi: 0x80}, {value: 0x0008, lo: 0x81, hi: 0xbf}, // Block 0x62, offset 0x32a {value: 0x0000, lo: 0x09}, {value: 0x0008, lo: 0x80, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x98}, {value: 0x1308, lo: 0x99, hi: 0x9a}, {value: 0x29e2, lo: 0x9b, hi: 0x9b}, {value: 0x2a0a, lo: 0x9c, hi: 0x9c}, {value: 0x0008, lo: 0x9d, hi: 0x9e}, {value: 0x2a31, lo: 0x9f, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xa0}, {value: 0x0008, lo: 0xa1, hi: 0xbf}, // Block 0x63, offset 0x334 {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xbe}, {value: 0x2a69, lo: 0xbf, hi: 0xbf}, // Block 0x64, offset 0x337 {value: 0x0000, lo: 0x0e}, {value: 0x0040, lo: 0x80, hi: 0x84}, {value: 0x0008, lo: 0x85, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xb0}, {value: 0x2a1d, lo: 0xb1, hi: 0xb1}, {value: 0x2a3d, lo: 0xb2, hi: 0xb2}, {value: 0x2a5d, lo: 0xb3, hi: 0xb3}, {value: 0x2a7d, lo: 0xb4, hi: 0xb4}, {value: 0x2a5d, lo: 0xb5, hi: 0xb5}, {value: 0x2a9d, lo: 0xb6, hi: 0xb6}, {value: 0x2abd, lo: 0xb7, hi: 0xb7}, {value: 0x2add, lo: 0xb8, hi: 0xb9}, {value: 0x2afd, lo: 0xba, hi: 0xbb}, {value: 0x2b1d, lo: 0xbc, hi: 0xbd}, {value: 0x2afd, lo: 0xbe, hi: 0xbf}, // Block 0x65, offset 0x346 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0xa3}, {value: 0x0040, lo: 0xa4, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x66, offset 0x34a {value: 0x0030, lo: 0x04}, {value: 0x2aa2, lo: 0x80, hi: 0x9d}, {value: 0x305a, lo: 0x9e, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0x9f}, {value: 0x30a2, lo: 0xa0, hi: 0xbf}, // Block 0x67, offset 0x34f {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x95}, {value: 0x0040, lo: 0x96, hi: 0xbf}, // Block 0x68, offset 0x352 {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0x8c}, {value: 0x0040, lo: 0x8d, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0xbf}, // Block 0x69, offset 0x356 {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xbd}, {value: 0x0018, lo: 0xbe, hi: 0xbf}, // Block 0x6a, offset 0x35b {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0x8c}, {value: 0x0018, lo: 0x8d, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xab}, {value: 0x0040, lo: 0xac, hi: 0xbf}, // Block 0x6b, offset 0x360 {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0xa5}, {value: 0x0018, lo: 0xa6, hi: 0xaf}, {value: 0x1308, lo: 0xb0, hi: 0xb1}, {value: 0x0018, lo: 0xb2, hi: 0xb7}, {value: 0x0040, lo: 0xb8, hi: 0xbf}, // Block 0x6c, offset 0x366 {value: 0x0000, lo: 0x05}, {value: 0x0040, lo: 0x80, hi: 0xb6}, {value: 0x0008, lo: 0xb7, hi: 0xb7}, {value: 0x2009, lo: 0xb8, hi: 0xb8}, {value: 0x6e89, lo: 0xb9, hi: 0xb9}, {value: 0x0008, lo: 0xba, hi: 0xbf}, // Block 0x6d, offset 0x36c {value: 0x0000, lo: 0x0e}, {value: 0x0008, lo: 0x80, hi: 0x81}, {value: 0x1308, lo: 0x82, hi: 0x82}, {value: 0x0008, lo: 0x83, hi: 0x85}, {value: 0x1b08, lo: 0x86, hi: 0x86}, {value: 0x0008, lo: 0x87, hi: 0x8a}, {value: 0x1308, lo: 0x8b, hi: 0x8b}, {value: 0x0008, lo: 0x8c, hi: 0xa2}, {value: 0x1008, lo: 0xa3, hi: 0xa4}, {value: 0x1308, lo: 0xa5, hi: 0xa6}, {value: 0x1008, lo: 0xa7, hi: 0xa7}, {value: 0x0018, lo: 0xa8, hi: 0xab}, {value: 0x0040, lo: 0xac, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbf}, // Block 0x6e, offset 0x37b {value: 0x0000, lo: 0x05}, {value: 0x0208, lo: 0x80, hi: 0xb1}, {value: 0x0108, lo: 0xb2, hi: 0xb2}, {value: 0x0008, lo: 0xb3, hi: 0xb3}, {value: 0x0018, lo: 0xb4, hi: 0xb7}, {value: 0x0040, lo: 0xb8, hi: 0xbf}, // Block 0x6f, offset 0x381 {value: 0x0000, lo: 0x03}, {value: 0x1008, lo: 0x80, hi: 0x81}, {value: 0x0008, lo: 0x82, hi: 0xb3}, {value: 0x1008, lo: 0xb4, hi: 0xbf}, // Block 0x70, offset 0x385 {value: 0x0000, lo: 0x0e}, {value: 0x1008, lo: 0x80, hi: 0x83}, {value: 0x1b08, lo: 0x84, hi: 0x84}, {value: 0x1308, lo: 0x85, hi: 0x85}, {value: 0x0040, lo: 0x86, hi: 0x8d}, {value: 0x0018, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9f}, {value: 0x1308, lo: 0xa0, hi: 0xb1}, {value: 0x0008, lo: 0xb2, hi: 0xb7}, {value: 0x0018, lo: 0xb8, hi: 0xba}, {value: 0x0008, lo: 0xbb, hi: 0xbb}, {value: 0x0018, lo: 0xbc, hi: 0xbc}, {value: 0x0008, lo: 0xbd, hi: 0xbd}, {value: 0x0040, lo: 0xbe, hi: 0xbf}, // Block 0x71, offset 0x394 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0xa5}, {value: 0x1308, lo: 0xa6, hi: 0xad}, {value: 0x0018, lo: 0xae, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x72, offset 0x399 {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0x86}, {value: 0x1308, lo: 0x87, hi: 0x91}, {value: 0x1008, lo: 0x92, hi: 0x92}, {value: 0x1808, lo: 0x93, hi: 0x93}, {value: 0x0040, lo: 0x94, hi: 0x9e}, {value: 0x0018, lo: 0x9f, hi: 0xbc}, {value: 0x0040, lo: 0xbd, hi: 0xbf}, // Block 0x73, offset 0x3a1 {value: 0x0000, lo: 0x09}, {value: 0x1308, lo: 0x80, hi: 0x82}, {value: 0x1008, lo: 0x83, hi: 0x83}, {value: 0x0008, lo: 0x84, hi: 0xb2}, {value: 0x1308, lo: 0xb3, hi: 0xb3}, {value: 0x1008, lo: 0xb4, hi: 0xb5}, {value: 0x1308, lo: 0xb6, hi: 0xb9}, {value: 0x1008, lo: 0xba, hi: 0xbb}, {value: 0x1308, lo: 0xbc, hi: 0xbc}, {value: 0x1008, lo: 0xbd, hi: 0xbf}, // Block 0x74, offset 0x3ab {value: 0x0000, lo: 0x0a}, {value: 0x1808, lo: 0x80, hi: 0x80}, {value: 0x0018, lo: 0x81, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8e}, {value: 0x0008, lo: 0x8f, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9d}, {value: 0x0018, lo: 0x9e, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa4}, {value: 0x1308, lo: 0xa5, hi: 0xa5}, {value: 0x0008, lo: 0xa6, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0x75, offset 0x3b6 {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0xa8}, {value: 0x1308, lo: 0xa9, hi: 0xae}, {value: 0x1008, lo: 0xaf, hi: 0xb0}, {value: 0x1308, lo: 0xb1, hi: 0xb2}, {value: 0x1008, lo: 0xb3, hi: 0xb4}, {value: 0x1308, lo: 0xb5, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xbf}, // Block 0x76, offset 0x3be {value: 0x0000, lo: 0x10}, {value: 0x0008, lo: 0x80, hi: 0x82}, {value: 0x1308, lo: 0x83, hi: 0x83}, {value: 0x0008, lo: 0x84, hi: 0x8b}, {value: 0x1308, lo: 0x8c, hi: 0x8c}, {value: 0x1008, lo: 0x8d, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9b}, {value: 0x0018, lo: 0x9c, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xb6}, {value: 0x0018, lo: 0xb7, hi: 0xb9}, {value: 0x0008, lo: 0xba, hi: 0xba}, {value: 0x1008, lo: 0xbb, hi: 0xbb}, {value: 0x1308, lo: 0xbc, hi: 0xbc}, {value: 0x1008, lo: 0xbd, hi: 0xbd}, {value: 0x0008, lo: 0xbe, hi: 0xbf}, // Block 0x77, offset 0x3cf {value: 0x0000, lo: 0x08}, {value: 0x0008, lo: 0x80, hi: 0xaf}, {value: 0x1308, lo: 0xb0, hi: 0xb0}, {value: 0x0008, lo: 0xb1, hi: 0xb1}, {value: 0x1308, lo: 0xb2, hi: 0xb4}, {value: 0x0008, lo: 0xb5, hi: 0xb6}, {value: 0x1308, lo: 0xb7, hi: 0xb8}, {value: 0x0008, lo: 0xb9, hi: 0xbd}, {value: 0x1308, lo: 0xbe, hi: 0xbf}, // Block 0x78, offset 0x3d8 {value: 0x0000, lo: 0x0f}, {value: 0x0008, lo: 0x80, hi: 0x80}, {value: 0x1308, lo: 0x81, hi: 0x81}, {value: 0x0008, lo: 0x82, hi: 0x82}, {value: 0x0040, lo: 0x83, hi: 0x9a}, {value: 0x0008, lo: 0x9b, hi: 0x9d}, {value: 0x0018, lo: 0x9e, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xaa}, {value: 0x1008, lo: 0xab, hi: 0xab}, {value: 0x1308, lo: 0xac, hi: 0xad}, {value: 0x1008, lo: 0xae, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb1}, {value: 0x0008, lo: 0xb2, hi: 0xb4}, {value: 0x1008, lo: 0xb5, hi: 0xb5}, {value: 0x1b08, lo: 0xb6, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xbf}, // Block 0x79, offset 0x3e8 {value: 0x0000, lo: 0x0c}, {value: 0x0040, lo: 0x80, hi: 0x80}, {value: 0x0008, lo: 0x81, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x88}, {value: 0x0008, lo: 0x89, hi: 0x8e}, {value: 0x0040, lo: 0x8f, hi: 0x90}, {value: 0x0008, lo: 0x91, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa6}, {value: 0x0040, lo: 0xa7, hi: 0xa7}, {value: 0x0008, lo: 0xa8, hi: 0xae}, {value: 0x0040, lo: 0xaf, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x7a, offset 0x3f5 {value: 0x0000, lo: 0x09}, {value: 0x0008, lo: 0x80, hi: 0x9a}, {value: 0x0018, lo: 0x9b, hi: 0x9b}, {value: 0x4465, lo: 0x9c, hi: 0x9c}, {value: 0x447d, lo: 0x9d, hi: 0x9d}, {value: 0x2971, lo: 0x9e, hi: 0x9e}, {value: 0xe06d, lo: 0x9f, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa5}, {value: 0x0040, lo: 0xa6, hi: 0xaf}, {value: 0x4495, lo: 0xb0, hi: 0xbf}, // Block 0x7b, offset 0x3ff {value: 0x0000, lo: 0x04}, {value: 0x44b5, lo: 0x80, hi: 0x8f}, {value: 0x44d5, lo: 0x90, hi: 0x9f}, {value: 0x44f5, lo: 0xa0, hi: 0xaf}, {value: 0x44d5, lo: 0xb0, hi: 0xbf}, // Block 0x7c, offset 0x404 {value: 0x0000, lo: 0x0c}, {value: 0x0008, lo: 0x80, hi: 0xa2}, {value: 0x1008, lo: 0xa3, hi: 0xa4}, {value: 0x1308, lo: 0xa5, hi: 0xa5}, {value: 0x1008, lo: 0xa6, hi: 0xa7}, {value: 0x1308, lo: 0xa8, hi: 0xa8}, {value: 0x1008, lo: 0xa9, hi: 0xaa}, {value: 0x0018, lo: 0xab, hi: 0xab}, {value: 0x1008, lo: 0xac, hi: 0xac}, {value: 0x1b08, lo: 0xad, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbf}, // Block 0x7d, offset 0x411 {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0xa3}, {value: 0x0040, lo: 0xa4, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xbf}, // Block 0x7e, offset 0x415 {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x8a}, {value: 0x0018, lo: 0x8b, hi: 0xbb}, {value: 0x0040, lo: 0xbc, hi: 0xbf}, // Block 0x7f, offset 0x41a {value: 0x0020, lo: 0x01}, {value: 0x4515, lo: 0x80, hi: 0xbf}, // Block 0x80, offset 0x41c {value: 0x0020, lo: 0x03}, {value: 0x4d15, lo: 0x80, hi: 0x94}, {value: 0x4ad5, lo: 0x95, hi: 0x95}, {value: 0x4fb5, lo: 0x96, hi: 0xbf}, // Block 0x81, offset 0x420 {value: 0x0020, lo: 0x01}, {value: 0x54f5, lo: 0x80, hi: 0xbf}, // Block 0x82, offset 0x422 {value: 0x0020, lo: 0x03}, {value: 0x5cf5, lo: 0x80, hi: 0x84}, {value: 0x5655, lo: 0x85, hi: 0x85}, {value: 0x5d95, lo: 0x86, hi: 0xbf}, // Block 0x83, offset 0x426 {value: 0x0020, lo: 0x08}, {value: 0x6b55, lo: 0x80, hi: 0x8f}, {value: 0x6d15, lo: 0x90, hi: 0x90}, {value: 0x6d55, lo: 0x91, hi: 0xab}, {value: 0x6ea1, lo: 0xac, hi: 0xac}, {value: 0x70b5, lo: 0xad, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xae}, {value: 0x0040, lo: 0xaf, hi: 0xaf}, {value: 0x70d5, lo: 0xb0, hi: 0xbf}, // Block 0x84, offset 0x42f {value: 0x0020, lo: 0x05}, {value: 0x72d5, lo: 0x80, hi: 0xad}, {value: 0x6535, lo: 0xae, hi: 0xae}, {value: 0x7895, lo: 0xaf, hi: 0xb5}, {value: 0x6f55, lo: 0xb6, hi: 0xb6}, {value: 0x7975, lo: 0xb7, hi: 0xbf}, // Block 0x85, offset 0x435 {value: 0x0028, lo: 0x03}, {value: 0x7c21, lo: 0x80, hi: 0x82}, {value: 0x7be1, lo: 0x83, hi: 0x83}, {value: 0x7c99, lo: 0x84, hi: 0xbf}, // Block 0x86, offset 0x439 {value: 0x0038, lo: 0x0f}, {value: 0x9db1, lo: 0x80, hi: 0x83}, {value: 0x9e59, lo: 0x84, hi: 0x85}, {value: 0x9e91, lo: 0x86, hi: 0x87}, {value: 0x9ec9, lo: 0x88, hi: 0x8f}, {value: 0x0040, lo: 0x90, hi: 0x90}, {value: 0x0040, lo: 0x91, hi: 0x91}, {value: 0xa089, lo: 0x92, hi: 0x97}, {value: 0xa1a1, lo: 0x98, hi: 0x9c}, {value: 0xa281, lo: 0x9d, hi: 0xb3}, {value: 0x9d41, lo: 0xb4, hi: 0xb4}, {value: 0x9db1, lo: 0xb5, hi: 0xb5}, {value: 0xa789, lo: 0xb6, hi: 0xbb}, {value: 0xa869, lo: 0xbc, hi: 0xbc}, {value: 0xa7f9, lo: 0xbd, hi: 0xbd}, {value: 0xa8d9, lo: 0xbe, hi: 0xbf}, // Block 0x87, offset 0x449 {value: 0x0000, lo: 0x09}, {value: 0x0008, lo: 0x80, hi: 0x8b}, {value: 0x0040, lo: 0x8c, hi: 0x8c}, {value: 0x0008, lo: 0x8d, hi: 0xa6}, {value: 0x0040, lo: 0xa7, hi: 0xa7}, {value: 0x0008, lo: 0xa8, hi: 0xba}, {value: 0x0040, lo: 0xbb, hi: 0xbb}, {value: 0x0008, lo: 0xbc, hi: 0xbd}, {value: 0x0040, lo: 0xbe, hi: 0xbe}, {value: 0x0008, lo: 0xbf, hi: 0xbf}, // Block 0x88, offset 0x453 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0xbf}, // Block 0x89, offset 0x458 {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xba}, {value: 0x0040, lo: 0xbb, hi: 0xbf}, // Block 0x8a, offset 0x45b {value: 0x0000, lo: 0x05}, {value: 0x0018, lo: 0x80, hi: 0x82}, {value: 0x0040, lo: 0x83, hi: 0x86}, {value: 0x0018, lo: 0x87, hi: 0xb3}, {value: 0x0040, lo: 0xb4, hi: 0xb6}, {value: 0x0018, lo: 0xb7, hi: 0xbf}, // Block 0x8b, offset 0x461 {value: 0x0000, lo: 0x06}, {value: 0x0018, lo: 0x80, hi: 0x8e}, {value: 0x0040, lo: 0x8f, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0x9b}, {value: 0x0040, lo: 0x9c, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xa0}, {value: 0x0040, lo: 0xa1, hi: 0xbf}, // Block 0x8c, offset 0x468 {value: 0x0000, lo: 0x04}, {value: 0x0040, lo: 0x80, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0xbc}, {value: 0x1308, lo: 0xbd, hi: 0xbd}, {value: 0x0040, lo: 0xbe, hi: 0xbf}, // Block 0x8d, offset 0x46d {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0x9c}, {value: 0x0040, lo: 0x9d, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xbf}, // Block 0x8e, offset 0x471 {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0x90}, {value: 0x0040, lo: 0x91, hi: 0x9f}, {value: 0x1308, lo: 0xa0, hi: 0xa0}, {value: 0x0018, lo: 0xa1, hi: 0xbb}, {value: 0x0040, lo: 0xbc, hi: 0xbf}, // Block 0x8f, offset 0x477 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xa3}, {value: 0x0040, lo: 0xa4, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x90, offset 0x47c {value: 0x0000, lo: 0x08}, {value: 0x0008, lo: 0x80, hi: 0x80}, {value: 0x0018, lo: 0x81, hi: 0x81}, {value: 0x0008, lo: 0x82, hi: 0x89}, {value: 0x0018, lo: 0x8a, hi: 0x8a}, {value: 0x0040, lo: 0x8b, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xb5}, {value: 0x1308, lo: 0xb6, hi: 0xba}, {value: 0x0040, lo: 0xbb, hi: 0xbf}, // Block 0x91, offset 0x485 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0x9e}, {value: 0x0018, lo: 0x9f, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xbf}, // Block 0x92, offset 0x48a {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0x83}, {value: 0x0040, lo: 0x84, hi: 0x87}, {value: 0x0008, lo: 0x88, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0x95}, {value: 0x0040, lo: 0x96, hi: 0xbf}, // Block 0x93, offset 0x490 {value: 0x0000, lo: 0x06}, {value: 0xe145, lo: 0x80, hi: 0x87}, {value: 0xe1c5, lo: 0x88, hi: 0x8f}, {value: 0xe145, lo: 0x90, hi: 0x97}, {value: 0x8ad5, lo: 0x98, hi: 0x9f}, {value: 0x8aed, lo: 0xa0, hi: 0xa7}, {value: 0x0008, lo: 0xa8, hi: 0xbf}, // Block 0x94, offset 0x497 {value: 0x0000, lo: 0x06}, {value: 0x0008, lo: 0x80, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa9}, {value: 0x0040, lo: 0xaa, hi: 0xaf}, {value: 0x8aed, lo: 0xb0, hi: 0xb7}, {value: 0x8ad5, lo: 0xb8, hi: 0xbf}, // Block 0x95, offset 0x49e {value: 0x0000, lo: 0x06}, {value: 0xe145, lo: 0x80, hi: 0x87}, {value: 0xe1c5, lo: 0x88, hi: 0x8f}, {value: 0xe145, lo: 0x90, hi: 0x93}, {value: 0x0040, lo: 0x94, hi: 0x97}, {value: 0x0008, lo: 0x98, hi: 0xbb}, {value: 0x0040, lo: 0xbc, hi: 0xbf}, // Block 0x96, offset 0x4a5 {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0xa7}, {value: 0x0040, lo: 0xa8, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0x97, offset 0x4a9 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0xa3}, {value: 0x0040, lo: 0xa4, hi: 0xae}, {value: 0x0018, lo: 0xaf, hi: 0xaf}, {value: 0x0040, lo: 0xb0, hi: 0xbf}, // Block 0x98, offset 0x4ae {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xbf}, // Block 0x99, offset 0x4b1 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0x95}, {value: 0x0040, lo: 0x96, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa7}, {value: 0x0040, lo: 0xa8, hi: 0xbf}, // Block 0x9a, offset 0x4b6 {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0x85}, {value: 0x0040, lo: 0x86, hi: 0x87}, {value: 0x0008, lo: 0x88, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x89}, {value: 0x0008, lo: 0x8a, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xb6}, {value: 0x0008, lo: 0xb7, hi: 0xb8}, {value: 0x0040, lo: 0xb9, hi: 0xbb}, {value: 0x0008, lo: 0xbc, hi: 0xbc}, {value: 0x0040, lo: 0xbd, hi: 0xbe}, {value: 0x0008, lo: 0xbf, hi: 0xbf}, // Block 0x9b, offset 0x4c2 {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0x95}, {value: 0x0040, lo: 0x96, hi: 0x96}, {value: 0x0018, lo: 0x97, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xb6}, {value: 0x0018, lo: 0xb7, hi: 0xbf}, // Block 0x9c, offset 0x4c8 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0xa6}, {value: 0x0018, lo: 0xa7, hi: 0xaf}, {value: 0x0040, lo: 0xb0, hi: 0xbf}, // Block 0x9d, offset 0x4cd {value: 0x0000, lo: 0x06}, {value: 0x0040, lo: 0x80, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xb2}, {value: 0x0040, lo: 0xb3, hi: 0xb3}, {value: 0x0008, lo: 0xb4, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xba}, {value: 0x0018, lo: 0xbb, hi: 0xbf}, // Block 0x9e, offset 0x4d4 {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0x95}, {value: 0x0018, lo: 0x96, hi: 0x9b}, {value: 0x0040, lo: 0x9c, hi: 0x9e}, {value: 0x0018, lo: 0x9f, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbe}, {value: 0x0018, lo: 0xbf, hi: 0xbf}, // Block 0x9f, offset 0x4dc {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0xb7}, {value: 0x0040, lo: 0xb8, hi: 0xbb}, {value: 0x0018, lo: 0xbc, hi: 0xbd}, {value: 0x0008, lo: 0xbe, hi: 0xbf}, // Block 0xa0, offset 0x4e1 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0x8f}, {value: 0x0040, lo: 0x90, hi: 0x91}, {value: 0x0018, lo: 0x92, hi: 0xbf}, // Block 0xa1, offset 0x4e5 {value: 0x0000, lo: 0x0f}, {value: 0x0008, lo: 0x80, hi: 0x80}, {value: 0x1308, lo: 0x81, hi: 0x83}, {value: 0x0040, lo: 0x84, hi: 0x84}, {value: 0x1308, lo: 0x85, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x8b}, {value: 0x1308, lo: 0x8c, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x93}, {value: 0x0040, lo: 0x94, hi: 0x94}, {value: 0x0008, lo: 0x95, hi: 0x97}, {value: 0x0040, lo: 0x98, hi: 0x98}, {value: 0x0008, lo: 0x99, hi: 0xb3}, {value: 0x0040, lo: 0xb4, hi: 0xb7}, {value: 0x1308, lo: 0xb8, hi: 0xba}, {value: 0x0040, lo: 0xbb, hi: 0xbe}, {value: 0x1b08, lo: 0xbf, hi: 0xbf}, // Block 0xa2, offset 0x4f5 {value: 0x0000, lo: 0x06}, {value: 0x0018, lo: 0x80, hi: 0x87}, {value: 0x0040, lo: 0x88, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0x98}, {value: 0x0040, lo: 0x99, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xbc}, {value: 0x0018, lo: 0xbd, hi: 0xbf}, // Block 0xa3, offset 0x4fc {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0x9c}, {value: 0x0018, lo: 0x9d, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xbf}, // Block 0xa4, offset 0x500 {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xb8}, {value: 0x0018, lo: 0xb9, hi: 0xbf}, // Block 0xa5, offset 0x504 {value: 0x0000, lo: 0x06}, {value: 0x0008, lo: 0x80, hi: 0x95}, {value: 0x0040, lo: 0x96, hi: 0x97}, {value: 0x0018, lo: 0x98, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xb2}, {value: 0x0040, lo: 0xb3, hi: 0xb7}, {value: 0x0018, lo: 0xb8, hi: 0xbf}, // Block 0xa6, offset 0x50b {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0xbf}, // Block 0xa7, offset 0x50e {value: 0x0000, lo: 0x02}, {value: 0x03dd, lo: 0x80, hi: 0xb2}, {value: 0x0040, lo: 0xb3, hi: 0xbf}, // Block 0xa8, offset 0x511 {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0xb2}, {value: 0x0040, lo: 0xb3, hi: 0xb9}, {value: 0x0018, lo: 0xba, hi: 0xbf}, // Block 0xa9, offset 0x515 {value: 0x0000, lo: 0x03}, {value: 0x0040, lo: 0x80, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0xaa, offset 0x519 {value: 0x0000, lo: 0x05}, {value: 0x1008, lo: 0x80, hi: 0x80}, {value: 0x1308, lo: 0x81, hi: 0x81}, {value: 0x1008, lo: 0x82, hi: 0x82}, {value: 0x0008, lo: 0x83, hi: 0xb7}, {value: 0x1308, lo: 0xb8, hi: 0xbf}, // Block 0xab, offset 0x51f {value: 0x0000, lo: 0x08}, {value: 0x1308, lo: 0x80, hi: 0x85}, {value: 0x1b08, lo: 0x86, hi: 0x86}, {value: 0x0018, lo: 0x87, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x91}, {value: 0x0018, lo: 0x92, hi: 0xa5}, {value: 0x0008, lo: 0xa6, hi: 0xaf}, {value: 0x0040, lo: 0xb0, hi: 0xbe}, {value: 0x1b08, lo: 0xbf, hi: 0xbf}, // Block 0xac, offset 0x528 {value: 0x0000, lo: 0x0b}, {value: 0x1308, lo: 0x80, hi: 0x81}, {value: 0x1008, lo: 0x82, hi: 0x82}, {value: 0x0008, lo: 0x83, hi: 0xaf}, {value: 0x1008, lo: 0xb0, hi: 0xb2}, {value: 0x1308, lo: 0xb3, hi: 0xb6}, {value: 0x1008, lo: 0xb7, hi: 0xb8}, {value: 0x1b08, lo: 0xb9, hi: 0xb9}, {value: 0x1308, lo: 0xba, hi: 0xba}, {value: 0x0018, lo: 0xbb, hi: 0xbc}, {value: 0x0340, lo: 0xbd, hi: 0xbd}, {value: 0x0018, lo: 0xbe, hi: 0xbf}, // Block 0xad, offset 0x534 {value: 0x0000, lo: 0x06}, {value: 0x0018, lo: 0x80, hi: 0x81}, {value: 0x0040, lo: 0x82, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xa8}, {value: 0x0040, lo: 0xa9, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbf}, // Block 0xae, offset 0x53b {value: 0x0000, lo: 0x08}, {value: 0x1308, lo: 0x80, hi: 0x82}, {value: 0x0008, lo: 0x83, hi: 0xa6}, {value: 0x1308, lo: 0xa7, hi: 0xab}, {value: 0x1008, lo: 0xac, hi: 0xac}, {value: 0x1308, lo: 0xad, hi: 0xb2}, {value: 0x1b08, lo: 0xb3, hi: 0xb4}, {value: 0x0040, lo: 0xb5, hi: 0xb5}, {value: 0x0008, lo: 0xb6, hi: 0xbf}, // Block 0xaf, offset 0x544 {value: 0x0000, lo: 0x07}, {value: 0x0018, lo: 0x80, hi: 0x83}, {value: 0x0040, lo: 0x84, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xb2}, {value: 0x1308, lo: 0xb3, hi: 0xb3}, {value: 0x0018, lo: 0xb4, hi: 0xb5}, {value: 0x0008, lo: 0xb6, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xbf}, // Block 0xb0, offset 0x54c {value: 0x0000, lo: 0x06}, {value: 0x1308, lo: 0x80, hi: 0x81}, {value: 0x1008, lo: 0x82, hi: 0x82}, {value: 0x0008, lo: 0x83, hi: 0xb2}, {value: 0x1008, lo: 0xb3, hi: 0xb5}, {value: 0x1308, lo: 0xb6, hi: 0xbe}, {value: 0x1008, lo: 0xbf, hi: 0xbf}, // Block 0xb1, offset 0x553 {value: 0x0000, lo: 0x0d}, {value: 0x1808, lo: 0x80, hi: 0x80}, {value: 0x0008, lo: 0x81, hi: 0x84}, {value: 0x0018, lo: 0x85, hi: 0x89}, {value: 0x1308, lo: 0x8a, hi: 0x8c}, {value: 0x0018, lo: 0x8d, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x9a}, {value: 0x0018, lo: 0x9b, hi: 0x9b}, {value: 0x0008, lo: 0x9c, hi: 0x9c}, {value: 0x0018, lo: 0x9d, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xa0}, {value: 0x0018, lo: 0xa1, hi: 0xb4}, {value: 0x0040, lo: 0xb5, hi: 0xbf}, // Block 0xb2, offset 0x561 {value: 0x0000, lo: 0x0c}, {value: 0x0008, lo: 0x80, hi: 0x91}, {value: 0x0040, lo: 0x92, hi: 0x92}, {value: 0x0008, lo: 0x93, hi: 0xab}, {value: 0x1008, lo: 0xac, hi: 0xae}, {value: 0x1308, lo: 0xaf, hi: 0xb1}, {value: 0x1008, lo: 0xb2, hi: 0xb3}, {value: 0x1308, lo: 0xb4, hi: 0xb4}, {value: 0x1808, lo: 0xb5, hi: 0xb5}, {value: 0x1308, lo: 0xb6, hi: 0xb7}, {value: 0x0018, lo: 0xb8, hi: 0xbd}, {value: 0x1308, lo: 0xbe, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0xb3, offset 0x56e {value: 0x0000, lo: 0x0c}, {value: 0x0008, lo: 0x80, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x87}, {value: 0x0008, lo: 0x88, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x89}, {value: 0x0008, lo: 0x8a, hi: 0x8d}, {value: 0x0040, lo: 0x8e, hi: 0x8e}, {value: 0x0008, lo: 0x8f, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0x9e}, {value: 0x0008, lo: 0x9f, hi: 0xa8}, {value: 0x0018, lo: 0xa9, hi: 0xa9}, {value: 0x0040, lo: 0xaa, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbf}, // Block 0xb4, offset 0x57b {value: 0x0000, lo: 0x08}, {value: 0x0008, lo: 0x80, hi: 0x9e}, {value: 0x1308, lo: 0x9f, hi: 0x9f}, {value: 0x1008, lo: 0xa0, hi: 0xa2}, {value: 0x1308, lo: 0xa3, hi: 0xa9}, {value: 0x1b08, lo: 0xaa, hi: 0xaa}, {value: 0x0040, lo: 0xab, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xb9}, {value: 0x0040, lo: 0xba, hi: 0xbf}, // Block 0xb5, offset 0x584 {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0xb4}, {value: 0x1008, lo: 0xb5, hi: 0xb7}, {value: 0x1308, lo: 0xb8, hi: 0xbf}, // Block 0xb6, offset 0x588 {value: 0x0000, lo: 0x0d}, {value: 0x1008, lo: 0x80, hi: 0x81}, {value: 0x1b08, lo: 0x82, hi: 0x82}, {value: 0x1308, lo: 0x83, hi: 0x84}, {value: 0x1008, lo: 0x85, hi: 0x85}, {value: 0x1308, lo: 0x86, hi: 0x86}, {value: 0x0008, lo: 0x87, hi: 0x8a}, {value: 0x0018, lo: 0x8b, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9a}, {value: 0x0018, lo: 0x9b, hi: 0x9b}, {value: 0x0040, lo: 0x9c, hi: 0x9c}, {value: 0x0018, lo: 0x9d, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0xbf}, // Block 0xb7, offset 0x596 {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0xaf}, {value: 0x1008, lo: 0xb0, hi: 0xb2}, {value: 0x1308, lo: 0xb3, hi: 0xb8}, {value: 0x1008, lo: 0xb9, hi: 0xb9}, {value: 0x1308, lo: 0xba, hi: 0xba}, {value: 0x1008, lo: 0xbb, hi: 0xbe}, {value: 0x1308, lo: 0xbf, hi: 0xbf}, // Block 0xb8, offset 0x59e {value: 0x0000, lo: 0x0a}, {value: 0x1308, lo: 0x80, hi: 0x80}, {value: 0x1008, lo: 0x81, hi: 0x81}, {value: 0x1b08, lo: 0x82, hi: 0x82}, {value: 0x1308, lo: 0x83, hi: 0x83}, {value: 0x0008, lo: 0x84, hi: 0x85}, {value: 0x0018, lo: 0x86, hi: 0x86}, {value: 0x0008, lo: 0x87, hi: 0x87}, {value: 0x0040, lo: 0x88, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0xbf}, // Block 0xb9, offset 0x5a9 {value: 0x0000, lo: 0x08}, {value: 0x0008, lo: 0x80, hi: 0xae}, {value: 0x1008, lo: 0xaf, hi: 0xb1}, {value: 0x1308, lo: 0xb2, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xb7}, {value: 0x1008, lo: 0xb8, hi: 0xbb}, {value: 0x1308, lo: 0xbc, hi: 0xbd}, {value: 0x1008, lo: 0xbe, hi: 0xbe}, {value: 0x1b08, lo: 0xbf, hi: 0xbf}, // Block 0xba, offset 0x5b2 {value: 0x0000, lo: 0x05}, {value: 0x1308, lo: 0x80, hi: 0x80}, {value: 0x0018, lo: 0x81, hi: 0x97}, {value: 0x0008, lo: 0x98, hi: 0x9b}, {value: 0x1308, lo: 0x9c, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0xbf}, // Block 0xbb, offset 0x5b8 {value: 0x0000, lo: 0x07}, {value: 0x0008, lo: 0x80, hi: 0xaf}, {value: 0x1008, lo: 0xb0, hi: 0xb2}, {value: 0x1308, lo: 0xb3, hi: 0xba}, {value: 0x1008, lo: 0xbb, hi: 0xbc}, {value: 0x1308, lo: 0xbd, hi: 0xbd}, {value: 0x1008, lo: 0xbe, hi: 0xbe}, {value: 0x1b08, lo: 0xbf, hi: 0xbf}, // Block 0xbc, offset 0x5c0 {value: 0x0000, lo: 0x08}, {value: 0x1308, lo: 0x80, hi: 0x80}, {value: 0x0018, lo: 0x81, hi: 0x83}, {value: 0x0008, lo: 0x84, hi: 0x84}, {value: 0x0040, lo: 0x85, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xac}, {value: 0x0040, lo: 0xad, hi: 0xbf}, // Block 0xbd, offset 0x5c9 {value: 0x0000, lo: 0x09}, {value: 0x0008, lo: 0x80, hi: 0xaa}, {value: 0x1308, lo: 0xab, hi: 0xab}, {value: 0x1008, lo: 0xac, hi: 0xac}, {value: 0x1308, lo: 0xad, hi: 0xad}, {value: 0x1008, lo: 0xae, hi: 0xaf}, {value: 0x1308, lo: 0xb0, hi: 0xb5}, {value: 0x1808, lo: 0xb6, hi: 0xb6}, {value: 0x1308, lo: 0xb7, hi: 0xb7}, {value: 0x0040, lo: 0xb8, hi: 0xbf}, // Block 0xbe, offset 0x5d3 {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x89}, {value: 0x0040, lo: 0x8a, hi: 0xbf}, // Block 0xbf, offset 0x5d6 {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9c}, {value: 0x1308, lo: 0x9d, hi: 0x9f}, {value: 0x1008, lo: 0xa0, hi: 0xa1}, {value: 0x1308, lo: 0xa2, hi: 0xa5}, {value: 0x1008, lo: 0xa6, hi: 0xa6}, {value: 0x1308, lo: 0xa7, hi: 0xaa}, {value: 0x1b08, lo: 0xab, hi: 0xab}, {value: 0x0040, lo: 0xac, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xb9}, {value: 0x0018, lo: 0xba, hi: 0xbf}, // Block 0xc0, offset 0x5e2 {value: 0x0000, lo: 0x02}, {value: 0x0040, lo: 0x80, hi: 0x9f}, {value: 0x049d, lo: 0xa0, hi: 0xbf}, // Block 0xc1, offset 0x5e5 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0xa9}, {value: 0x0018, lo: 0xaa, hi: 0xb2}, {value: 0x0040, lo: 0xb3, hi: 0xbe}, {value: 0x0008, lo: 0xbf, hi: 0xbf}, // Block 0xc2, offset 0x5ea {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xb8}, {value: 0x0040, lo: 0xb9, hi: 0xbf}, // Block 0xc3, offset 0x5ed {value: 0x0000, lo: 0x09}, {value: 0x0008, lo: 0x80, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x89}, {value: 0x0008, lo: 0x8a, hi: 0xae}, {value: 0x1008, lo: 0xaf, hi: 0xaf}, {value: 0x1308, lo: 0xb0, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xb7}, {value: 0x1308, lo: 0xb8, hi: 0xbd}, {value: 0x1008, lo: 0xbe, hi: 0xbe}, {value: 0x1b08, lo: 0xbf, hi: 0xbf}, // Block 0xc4, offset 0x5f7 {value: 0x0000, lo: 0x08}, {value: 0x0008, lo: 0x80, hi: 0x80}, {value: 0x0018, lo: 0x81, hi: 0x85}, {value: 0x0040, lo: 0x86, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0018, lo: 0x9a, hi: 0xac}, {value: 0x0040, lo: 0xad, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb1}, {value: 0x0008, lo: 0xb2, hi: 0xbf}, // Block 0xc5, offset 0x600 {value: 0x0000, lo: 0x0b}, {value: 0x0008, lo: 0x80, hi: 0x8f}, {value: 0x0040, lo: 0x90, hi: 0x91}, {value: 0x1308, lo: 0x92, hi: 0xa7}, {value: 0x0040, lo: 0xa8, hi: 0xa8}, {value: 0x1008, lo: 0xa9, hi: 0xa9}, {value: 0x1308, lo: 0xaa, hi: 0xb0}, {value: 0x1008, lo: 0xb1, hi: 0xb1}, {value: 0x1308, lo: 0xb2, hi: 0xb3}, {value: 0x1008, lo: 0xb4, hi: 0xb4}, {value: 0x1308, lo: 0xb5, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xbf}, // Block 0xc6, offset 0x60c {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0xbf}, // Block 0xc7, offset 0x60f {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0xae}, {value: 0x0040, lo: 0xaf, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb4}, {value: 0x0040, lo: 0xb5, hi: 0xbf}, // Block 0xc8, offset 0x614 {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x83}, {value: 0x0040, lo: 0x84, hi: 0xbf}, // Block 0xc9, offset 0x617 {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xae}, {value: 0x0040, lo: 0xaf, hi: 0xbf}, // Block 0xca, offset 0x61a {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0xbf}, // Block 0xcb, offset 0x61d {value: 0x0000, lo: 0x06}, {value: 0x0008, lo: 0x80, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa9}, {value: 0x0040, lo: 0xaa, hi: 0xad}, {value: 0x0018, lo: 0xae, hi: 0xaf}, {value: 0x0040, lo: 0xb0, hi: 0xbf}, // Block 0xcc, offset 0x624 {value: 0x0000, lo: 0x06}, {value: 0x0040, lo: 0x80, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xaf}, {value: 0x1308, lo: 0xb0, hi: 0xb4}, {value: 0x0018, lo: 0xb5, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xbf}, // Block 0xcd, offset 0x62b {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0xaf}, {value: 0x1308, lo: 0xb0, hi: 0xb6}, {value: 0x0018, lo: 0xb7, hi: 0xbf}, // Block 0xce, offset 0x62f {value: 0x0000, lo: 0x0a}, {value: 0x0008, lo: 0x80, hi: 0x83}, {value: 0x0018, lo: 0x84, hi: 0x85}, {value: 0x0040, lo: 0x86, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9a}, {value: 0x0018, lo: 0x9b, hi: 0xa1}, {value: 0x0040, lo: 0xa2, hi: 0xa2}, {value: 0x0008, lo: 0xa3, hi: 0xb7}, {value: 0x0040, lo: 0xb8, hi: 0xbc}, {value: 0x0008, lo: 0xbd, hi: 0xbf}, // Block 0xcf, offset 0x63a {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x8f}, {value: 0x0040, lo: 0x90, hi: 0xbf}, // Block 0xd0, offset 0x63d {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0x84}, {value: 0x0040, lo: 0x85, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x90}, {value: 0x1008, lo: 0x91, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0xd1, offset 0x643 {value: 0x0000, lo: 0x04}, {value: 0x0040, lo: 0x80, hi: 0x8e}, {value: 0x1308, lo: 0x8f, hi: 0x92}, {value: 0x0008, lo: 0x93, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xbf}, // Block 0xd2, offset 0x648 {value: 0x0000, lo: 0x03}, {value: 0x0040, lo: 0x80, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xa0}, {value: 0x0040, lo: 0xa1, hi: 0xbf}, // Block 0xd3, offset 0x64c {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xac}, {value: 0x0040, lo: 0xad, hi: 0xbf}, // Block 0xd4, offset 0x64f {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xb2}, {value: 0x0040, lo: 0xb3, hi: 0xbf}, // Block 0xd5, offset 0x652 {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x81}, {value: 0x0040, lo: 0x82, hi: 0xbf}, // Block 0xd6, offset 0x655 {value: 0x0000, lo: 0x04}, {value: 0x0008, lo: 0x80, hi: 0xaa}, {value: 0x0040, lo: 0xab, hi: 0xaf}, {value: 0x0008, lo: 0xb0, hi: 0xbc}, {value: 0x0040, lo: 0xbd, hi: 0xbf}, // Block 0xd7, offset 0x65a {value: 0x0000, lo: 0x09}, {value: 0x0008, lo: 0x80, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9b}, {value: 0x0018, lo: 0x9c, hi: 0x9c}, {value: 0x1308, lo: 0x9d, hi: 0x9e}, {value: 0x0018, lo: 0x9f, hi: 0x9f}, {value: 0x03c0, lo: 0xa0, hi: 0xa3}, {value: 0x0040, lo: 0xa4, hi: 0xbf}, // Block 0xd8, offset 0x664 {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xbf}, // Block 0xd9, offset 0x667 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0xa6}, {value: 0x0040, lo: 0xa7, hi: 0xa8}, {value: 0x0018, lo: 0xa9, hi: 0xbf}, // Block 0xda, offset 0x66b {value: 0x0000, lo: 0x0e}, {value: 0x0018, lo: 0x80, hi: 0x9d}, {value: 0xb5b9, lo: 0x9e, hi: 0x9e}, {value: 0xb601, lo: 0x9f, hi: 0x9f}, {value: 0xb649, lo: 0xa0, hi: 0xa0}, {value: 0xb6b1, lo: 0xa1, hi: 0xa1}, {value: 0xb719, lo: 0xa2, hi: 0xa2}, {value: 0xb781, lo: 0xa3, hi: 0xa3}, {value: 0xb7e9, lo: 0xa4, hi: 0xa4}, {value: 0x1018, lo: 0xa5, hi: 0xa6}, {value: 0x1318, lo: 0xa7, hi: 0xa9}, {value: 0x0018, lo: 0xaa, hi: 0xac}, {value: 0x1018, lo: 0xad, hi: 0xb2}, {value: 0x0340, lo: 0xb3, hi: 0xba}, {value: 0x1318, lo: 0xbb, hi: 0xbf}, // Block 0xdb, offset 0x67a {value: 0x0000, lo: 0x0b}, {value: 0x1318, lo: 0x80, hi: 0x82}, {value: 0x0018, lo: 0x83, hi: 0x84}, {value: 0x1318, lo: 0x85, hi: 0x8b}, {value: 0x0018, lo: 0x8c, hi: 0xa9}, {value: 0x1318, lo: 0xaa, hi: 0xad}, {value: 0x0018, lo: 0xae, hi: 0xba}, {value: 0xb851, lo: 0xbb, hi: 0xbb}, {value: 0xb899, lo: 0xbc, hi: 0xbc}, {value: 0xb8e1, lo: 0xbd, hi: 0xbd}, {value: 0xb949, lo: 0xbe, hi: 0xbe}, {value: 0xb9b1, lo: 0xbf, hi: 0xbf}, // Block 0xdc, offset 0x686 {value: 0x0000, lo: 0x03}, {value: 0xba19, lo: 0x80, hi: 0x80}, {value: 0x0018, lo: 0x81, hi: 0xa8}, {value: 0x0040, lo: 0xa9, hi: 0xbf}, // Block 0xdd, offset 0x68a {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0x81}, {value: 0x1318, lo: 0x82, hi: 0x84}, {value: 0x0018, lo: 0x85, hi: 0x85}, {value: 0x0040, lo: 0x86, hi: 0xbf}, // Block 0xde, offset 0x68f {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xb1}, {value: 0x0040, lo: 0xb2, hi: 0xbf}, // Block 0xdf, offset 0x694 {value: 0x0000, lo: 0x03}, {value: 0x1308, lo: 0x80, hi: 0xb6}, {value: 0x0018, lo: 0xb7, hi: 0xba}, {value: 0x1308, lo: 0xbb, hi: 0xbf}, // Block 0xe0, offset 0x698 {value: 0x0000, lo: 0x04}, {value: 0x1308, lo: 0x80, hi: 0xac}, {value: 0x0018, lo: 0xad, hi: 0xb4}, {value: 0x1308, lo: 0xb5, hi: 0xb5}, {value: 0x0018, lo: 0xb6, hi: 0xbf}, // Block 0xe1, offset 0x69d {value: 0x0000, lo: 0x08}, {value: 0x0018, lo: 0x80, hi: 0x83}, {value: 0x1308, lo: 0x84, hi: 0x84}, {value: 0x0018, lo: 0x85, hi: 0x8b}, {value: 0x0040, lo: 0x8c, hi: 0x9a}, {value: 0x1308, lo: 0x9b, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xa0}, {value: 0x1308, lo: 0xa1, hi: 0xaf}, {value: 0x0040, lo: 0xb0, hi: 0xbf}, // Block 0xe2, offset 0x6a6 {value: 0x0000, lo: 0x0a}, {value: 0x1308, lo: 0x80, hi: 0x86}, {value: 0x0040, lo: 0x87, hi: 0x87}, {value: 0x1308, lo: 0x88, hi: 0x98}, {value: 0x0040, lo: 0x99, hi: 0x9a}, {value: 0x1308, lo: 0x9b, hi: 0xa1}, {value: 0x0040, lo: 0xa2, hi: 0xa2}, {value: 0x1308, lo: 0xa3, hi: 0xa4}, {value: 0x0040, lo: 0xa5, hi: 0xa5}, {value: 0x1308, lo: 0xa6, hi: 0xaa}, {value: 0x0040, lo: 0xab, hi: 0xbf}, // Block 0xe3, offset 0x6b1 {value: 0x0000, lo: 0x05}, {value: 0x0008, lo: 0x80, hi: 0x84}, {value: 0x0040, lo: 0x85, hi: 0x86}, {value: 0x0018, lo: 0x87, hi: 0x8f}, {value: 0x1308, lo: 0x90, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0xbf}, // Block 0xe4, offset 0x6b7 {value: 0x0000, lo: 0x07}, {value: 0x0208, lo: 0x80, hi: 0x83}, {value: 0x1308, lo: 0x84, hi: 0x8a}, {value: 0x0040, lo: 0x8b, hi: 0x8f}, {value: 0x0008, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9d}, {value: 0x0018, lo: 0x9e, hi: 0x9f}, {value: 0x0040, lo: 0xa0, hi: 0xbf}, // Block 0xe5, offset 0x6bf {value: 0x0000, lo: 0x03}, {value: 0x0040, lo: 0x80, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb1}, {value: 0x0040, lo: 0xb2, hi: 0xbf}, // Block 0xe6, offset 0x6c3 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0xab}, {value: 0x0040, lo: 0xac, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xbf}, // Block 0xe7, offset 0x6c7 {value: 0x0000, lo: 0x05}, {value: 0x0018, lo: 0x80, hi: 0x93}, {value: 0x0040, lo: 0x94, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xae}, {value: 0x0040, lo: 0xaf, hi: 0xb0}, {value: 0x0018, lo: 0xb1, hi: 0xbf}, // Block 0xe8, offset 0x6cd {value: 0x0000, lo: 0x05}, {value: 0x0040, lo: 0x80, hi: 0x80}, {value: 0x0018, lo: 0x81, hi: 0x8f}, {value: 0x0040, lo: 0x90, hi: 0x90}, {value: 0x0018, lo: 0x91, hi: 0xb5}, {value: 0x0040, lo: 0xb6, hi: 0xbf}, // Block 0xe9, offset 0x6d3 {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0x8f}, {value: 0xc1c1, lo: 0x90, hi: 0x90}, {value: 0x0018, lo: 0x91, hi: 0xac}, {value: 0x0040, lo: 0xad, hi: 0xbf}, // Block 0xea, offset 0x6d8 {value: 0x0000, lo: 0x02}, {value: 0x0040, lo: 0x80, hi: 0xa5}, {value: 0x0018, lo: 0xa6, hi: 0xbf}, // Block 0xeb, offset 0x6db {value: 0x0000, lo: 0x0d}, {value: 0xc7e9, lo: 0x80, hi: 0x80}, {value: 0xc839, lo: 0x81, hi: 0x81}, {value: 0xc889, lo: 0x82, hi: 0x82}, {value: 0xc8d9, lo: 0x83, hi: 0x83}, {value: 0xc929, lo: 0x84, hi: 0x84}, {value: 0xc979, lo: 0x85, hi: 0x85}, {value: 0xc9c9, lo: 0x86, hi: 0x86}, {value: 0xca19, lo: 0x87, hi: 0x87}, {value: 0xca69, lo: 0x88, hi: 0x88}, {value: 0x0040, lo: 0x89, hi: 0x8f}, {value: 0xcab9, lo: 0x90, hi: 0x90}, {value: 0xcad9, lo: 0x91, hi: 0x91}, {value: 0x0040, lo: 0x92, hi: 0xbf}, // Block 0xec, offset 0x6e9 {value: 0x0000, lo: 0x06}, {value: 0x0018, lo: 0x80, hi: 0x92}, {value: 0x0040, lo: 0x93, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xac}, {value: 0x0040, lo: 0xad, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb6}, {value: 0x0040, lo: 0xb7, hi: 0xbf}, // Block 0xed, offset 0x6f0 {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0xb3}, {value: 0x0040, lo: 0xb4, hi: 0xbf}, // Block 0xee, offset 0x6f3 {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0x94}, {value: 0x0040, lo: 0x95, hi: 0xbf}, // Block 0xef, offset 0x6f6 {value: 0x0000, lo: 0x03}, {value: 0x0018, lo: 0x80, hi: 0x8b}, {value: 0x0040, lo: 0x8c, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0xbf}, // Block 0xf0, offset 0x6fa {value: 0x0000, lo: 0x05}, {value: 0x0018, lo: 0x80, hi: 0x87}, {value: 0x0040, lo: 0x88, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0x99}, {value: 0x0040, lo: 0x9a, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xbf}, // Block 0xf1, offset 0x700 {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0x87}, {value: 0x0040, lo: 0x88, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0xad}, {value: 0x0040, lo: 0xae, hi: 0xbf}, // Block 0xf2, offset 0x705 {value: 0x0000, lo: 0x09}, {value: 0x0040, lo: 0x80, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0x9f}, {value: 0x0018, lo: 0xa0, hi: 0xa7}, {value: 0x0040, lo: 0xa8, hi: 0xaf}, {value: 0x0018, lo: 0xb0, hi: 0xb0}, {value: 0x0040, lo: 0xb1, hi: 0xb2}, {value: 0x0018, lo: 0xb3, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0xf3, offset 0x70f {value: 0x0000, lo: 0x04}, {value: 0x0018, lo: 0x80, hi: 0x8b}, {value: 0x0040, lo: 0x8c, hi: 0x8f}, {value: 0x0018, lo: 0x90, hi: 0x9e}, {value: 0x0040, lo: 0x9f, hi: 0xbf}, // Block 0xf4, offset 0x714 {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0x91}, {value: 0x0040, lo: 0x92, hi: 0xbf}, // Block 0xf5, offset 0x717 {value: 0x0000, lo: 0x02}, {value: 0x0018, lo: 0x80, hi: 0x80}, {value: 0x0040, lo: 0x81, hi: 0xbf}, // Block 0xf6, offset 0x71a {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0x96}, {value: 0x0040, lo: 0x97, hi: 0xbf}, // Block 0xf7, offset 0x71d {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xb4}, {value: 0x0040, lo: 0xb5, hi: 0xbf}, // Block 0xf8, offset 0x720 {value: 0x0000, lo: 0x03}, {value: 0x0008, lo: 0x80, hi: 0x9d}, {value: 0x0040, lo: 0x9e, hi: 0x9f}, {value: 0x0008, lo: 0xa0, hi: 0xbf}, // Block 0xf9, offset 0x724 {value: 0x0000, lo: 0x02}, {value: 0x0008, lo: 0x80, hi: 0xa1}, {value: 0x0040, lo: 0xa2, hi: 0xbf}, // Block 0xfa, offset 0x727 {value: 0x0020, lo: 0x0f}, {value: 0xdeb9, lo: 0x80, hi: 0x89}, {value: 0x8dfd, lo: 0x8a, hi: 0x8a}, {value: 0xdff9, lo: 0x8b, hi: 0x9c}, {value: 0x8e1d, lo: 0x9d, hi: 0x9d}, {value: 0xe239, lo: 0x9e, hi: 0xa2}, {value: 0x8e3d, lo: 0xa3, hi: 0xa3}, {value: 0xe2d9, lo: 0xa4, hi: 0xab}, {value: 0x7ed5, lo: 0xac, hi: 0xac}, {value: 0xe3d9, lo: 0xad, hi: 0xaf}, {value: 0x8e5d, lo: 0xb0, hi: 0xb0}, {value: 0xe439, lo: 0xb1, hi: 0xb6}, {value: 0x8e7d, lo: 0xb7, hi: 0xb9}, {value: 0xe4f9, lo: 0xba, hi: 0xba}, {value: 0x8edd, lo: 0xbb, hi: 0xbb}, {value: 0xe519, lo: 0xbc, hi: 0xbf}, // Block 0xfb, offset 0x737 {value: 0x0020, lo: 0x10}, {value: 0x937d, lo: 0x80, hi: 0x80}, {value: 0xf099, lo: 0x81, hi: 0x86}, {value: 0x939d, lo: 0x87, hi: 0x8a}, {value: 0xd9f9, lo: 0x8b, hi: 0x8b}, {value: 0xf159, lo: 0x8c, hi: 0x96}, {value: 0x941d, lo: 0x97, hi: 0x97}, {value: 0xf2b9, lo: 0x98, hi: 0xa3}, {value: 0x943d, lo: 0xa4, hi: 0xa6}, {value: 0xf439, lo: 0xa7, hi: 0xaa}, {value: 0x949d, lo: 0xab, hi: 0xab}, {value: 0xf4b9, lo: 0xac, hi: 0xac}, {value: 0x94bd, lo: 0xad, hi: 0xad}, {value: 0xf4d9, lo: 0xae, hi: 0xaf}, {value: 0x94dd, lo: 0xb0, hi: 0xb1}, {value: 0xf519, lo: 0xb2, hi: 0xbe}, {value: 0x0040, lo: 0xbf, hi: 0xbf}, // Block 0xfc, offset 0x748 {value: 0x0000, lo: 0x04}, {value: 0x0040, lo: 0x80, hi: 0x80}, {value: 0x0340, lo: 0x81, hi: 0x81}, {value: 0x0040, lo: 0x82, hi: 0x9f}, {value: 0x0340, lo: 0xa0, hi: 0xbf}, // Block 0xfd, offset 0x74d {value: 0x0000, lo: 0x01}, {value: 0x0340, lo: 0x80, hi: 0xbf}, // Block 0xfe, offset 0x74f {value: 0x0000, lo: 0x01}, {value: 0x13c0, lo: 0x80, hi: 0xbf}, // Block 0xff, offset 0x751 {value: 0x0000, lo: 0x02}, {value: 0x13c0, lo: 0x80, hi: 0xaf}, {value: 0x0040, lo: 0xb0, hi: 0xbf}, } // Total table size 41559 bytes (40KiB); checksum: F4A1FA4E lxd-2.0.11/dist/src/golang.org/x/net/idna/punycode_test.go0000644061062106075000000001343313172163402024446 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package idna import ( "strings" "testing" ) var punycodeTestCases = [...]struct { s, encoded string }{ {"", ""}, {"-", "--"}, {"-a", "-a-"}, {"-a-", "-a--"}, {"a", "a-"}, {"a-", "a--"}, {"a-b", "a-b-"}, {"books", "books-"}, {"bücher", "bcher-kva"}, {"Hello世界", "Hello-ck1hg65u"}, {"ü", "tda"}, {"üý", "tdac"}, // The test cases below come from RFC 3492 section 7.1 with Errata 3026. { // (A) Arabic (Egyptian). "\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" + "\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", "egbpdaj6bu4bxfgehfvwxn", }, { // (B) Chinese (simplified). "\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", "ihqwcrb4cv8a8dqg056pqjye", }, { // (C) Chinese (traditional). "\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587", "ihqwctvzc91f659drss3x8bo0yb", }, { // (D) Czech. "\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074" + "\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D" + "\u0065\u0073\u006B\u0079", "Proprostnemluvesky-uyb24dma41a", }, { // (E) Hebrew. "\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8" + "\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2" + "\u05D1\u05E8\u05D9\u05EA", "4dbcagdahymbxekheh6e0a7fei0b", }, { // (F) Hindi (Devanagari). "\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D" + "\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939" + "\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947" + "\u0939\u0948\u0902", "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd", }, { // (G) Japanese (kanji and hiragana). "\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092" + "\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B", "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa", }, { // (H) Korean (Hangul syllables). "\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774" + "\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74" + "\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C", "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j" + "psd879ccm6fea98c", }, { // (I) Russian (Cyrillic). "\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E" + "\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440" + "\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A" + "\u0438", "b1abfaaepdrnnbgefbadotcwatmq2g4l", }, { // (J) Spanish. "\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070" + "\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070" + "\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061" + "\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070" + "\u0061\u00F1\u006F\u006C", "PorqunopuedensimplementehablarenEspaol-fmd56a", }, { // (K) Vietnamese. "\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B" + "\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068" + "\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067" + "\u0056\u0069\u1EC7\u0074", "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g", }, { // (L) 3B. "\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F", "3B-ww4c5e180e575a65lsy2b", }, { // (M) -with-SUPER-MONKEYS. "\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074" + "\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D" + "\u004F\u004E\u004B\u0045\u0059\u0053", "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n", }, { // (N) Hello-Another-Way-. "\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F" + "\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D" + "\u305D\u308C\u305E\u308C\u306E\u5834\u6240", "Hello-Another-Way--fc4qua05auwb3674vfr0b", }, { // (O) 2. "\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032", "2-u9tlzr9756bt3uc0v", }, { // (P) MajiKoi5 "\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" + "\u308B\u0035\u79D2\u524D", "MajiKoi5-783gue6qz075azm5e", }, { // (Q) de "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", "de-jg4avhby1noc0d", }, { // (R) "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", "d9juau41awczczp", }, { // (S) -> $1.00 <- "\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020" + "\u003C\u002D", "-> $1.00 <--", }, } func TestPunycode(t *testing.T) { for _, tc := range punycodeTestCases { if got, err := decode(tc.encoded); err != nil { t.Errorf("decode(%q): %v", tc.encoded, err) } else if got != tc.s { t.Errorf("decode(%q): got %q, want %q", tc.encoded, got, tc.s) } if got, err := encode("", tc.s); err != nil { t.Errorf(`encode("", %q): %v`, tc.s, err) } else if got != tc.encoded { t.Errorf(`encode("", %q): got %q, want %q`, tc.s, got, tc.encoded) } } } var punycodeErrorTestCases = [...]string{ "decode -", // A sole '-' is invalid. "decode foo\x00bar", // '\x00' is not in [0-9A-Za-z]. "decode foo#bar", // '#' is not in [0-9A-Za-z]. "decode foo\u00A3bar", // '\u00A3' is not in [0-9A-Za-z]. "decode 9", // "9a" decodes to codepoint \u00A3; "9" is truncated. "decode 99999a", // "99999a" decodes to codepoint \U0048A3C1, which is > \U0010FFFF. "decode 9999999999a", // "9999999999a" overflows the int32 calculation. "encode " + strings.Repeat("x", 65536) + "\uff00", // int32 overflow. } func TestPunycodeErrors(t *testing.T) { for _, tc := range punycodeErrorTestCases { var err error switch { case strings.HasPrefix(tc, "decode "): _, err = decode(tc[7:]) case strings.HasPrefix(tc, "encode "): _, err = encode("", tc[7:]) } if err == nil { if len(tc) > 256 { tc = tc[:100] + "..." + tc[len(tc)-100:] } t.Errorf("no error for %s", tc) } } } lxd-2.0.11/dist/src/golang.org/x/net/idna/punycode.go0000644061062106075000000001041713172163402023406 0ustar stgraberdomain admins// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. // Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package idna // This file implements the Punycode algorithm from RFC 3492. import ( "math" "strings" "unicode/utf8" ) // These parameter values are specified in section 5. // // All computation is done with int32s, so that overflow behavior is identical // regardless of whether int is 32-bit or 64-bit. const ( base int32 = 36 damp int32 = 700 initialBias int32 = 72 initialN int32 = 128 skew int32 = 38 tmax int32 = 26 tmin int32 = 1 ) func punyError(s string) error { return &labelError{s, "A3"} } // decode decodes a string as specified in section 6.2. func decode(encoded string) (string, error) { if encoded == "" { return "", nil } pos := 1 + strings.LastIndex(encoded, "-") if pos == 1 { return "", punyError(encoded) } if pos == len(encoded) { return encoded[:len(encoded)-1], nil } output := make([]rune, 0, len(encoded)) if pos != 0 { for _, r := range encoded[:pos-1] { output = append(output, r) } } i, n, bias := int32(0), initialN, initialBias for pos < len(encoded) { oldI, w := i, int32(1) for k := base; ; k += base { if pos == len(encoded) { return "", punyError(encoded) } digit, ok := decodeDigit(encoded[pos]) if !ok { return "", punyError(encoded) } pos++ i += digit * w if i < 0 { return "", punyError(encoded) } t := k - bias if t < tmin { t = tmin } else if t > tmax { t = tmax } if digit < t { break } w *= base - t if w >= math.MaxInt32/base { return "", punyError(encoded) } } x := int32(len(output) + 1) bias = adapt(i-oldI, x, oldI == 0) n += i / x i %= x if n > utf8.MaxRune || len(output) >= 1024 { return "", punyError(encoded) } output = append(output, 0) copy(output[i+1:], output[i:]) output[i] = n i++ } return string(output), nil } // encode encodes a string as specified in section 6.3 and prepends prefix to // the result. // // The "while h < length(input)" line in the specification becomes "for // remaining != 0" in the Go code, because len(s) in Go is in bytes, not runes. func encode(prefix, s string) (string, error) { output := make([]byte, len(prefix), len(prefix)+1+2*len(s)) copy(output, prefix) delta, n, bias := int32(0), initialN, initialBias b, remaining := int32(0), int32(0) for _, r := range s { if r < 0x80 { b++ output = append(output, byte(r)) } else { remaining++ } } h := b if b > 0 { output = append(output, '-') } for remaining != 0 { m := int32(0x7fffffff) for _, r := range s { if m > r && r >= n { m = r } } delta += (m - n) * (h + 1) if delta < 0 { return "", punyError(s) } n = m for _, r := range s { if r < n { delta++ if delta < 0 { return "", punyError(s) } continue } if r > n { continue } q := delta for k := base; ; k += base { t := k - bias if t < tmin { t = tmin } else if t > tmax { t = tmax } if q < t { break } output = append(output, encodeDigit(t+(q-t)%(base-t))) q = (q - t) / (base - t) } output = append(output, encodeDigit(q)) bias = adapt(delta, h+1, h == b) delta = 0 h++ remaining-- } delta++ n++ } return string(output), nil } func decodeDigit(x byte) (digit int32, ok bool) { switch { case '0' <= x && x <= '9': return int32(x - ('0' - 26)), true case 'A' <= x && x <= 'Z': return int32(x - 'A'), true case 'a' <= x && x <= 'z': return int32(x - 'a'), true } return 0, false } func encodeDigit(digit int32) byte { switch { case 0 <= digit && digit < 26: return byte(digit + 'a') case 26 <= digit && digit < 36: return byte(digit + ('0' - 26)) } panic("idna: internal error in punycode encoding") } // adapt is the bias adaptation function specified in section 6.1. func adapt(delta, numPoints int32, firstTime bool) int32 { if firstTime { delta /= damp } else { delta /= 2 } delta += delta / numPoints k := int32(0) for delta > ((base-tmin)*tmax)/2 { delta /= base - tmin k += base } return k + (base-tmin+1)*delta/(delta+skew) } lxd-2.0.11/dist/src/golang.org/x/net/idna/idna_test.go0000644061062106075000000000524013172163402023530 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package idna import ( "testing" ) var idnaTestCases = [...]struct { ascii, unicode string }{ // Labels. {"books", "books"}, {"xn--bcher-kva", "bücher"}, // Domains. {"foo--xn--bar.org", "foo--xn--bar.org"}, {"golang.org", "golang.org"}, {"example.xn--p1ai", "example.рф"}, {"xn--czrw28b.tw", "商業.tw"}, {"www.xn--mller-kva.de", "www.müller.de"}, } func TestIDNA(t *testing.T) { for _, tc := range idnaTestCases { if a, err := ToASCII(tc.unicode); err != nil { t.Errorf("ToASCII(%q): %v", tc.unicode, err) } else if a != tc.ascii { t.Errorf("ToASCII(%q): got %q, want %q", tc.unicode, a, tc.ascii) } if u, err := ToUnicode(tc.ascii); err != nil { t.Errorf("ToUnicode(%q): %v", tc.ascii, err) } else if u != tc.unicode { t.Errorf("ToUnicode(%q): got %q, want %q", tc.ascii, u, tc.unicode) } } } func TestIDNASeparators(t *testing.T) { type subCase struct { unicode string wantASCII string wantErr bool } testCases := []struct { name string profile *Profile subCases []subCase }{ { name: "Punycode", profile: Punycode, subCases: []subCase{ {"example\u3002jp", "xn--examplejp-ck3h", false}, {"æ±äº¬\uFF0Ejp", "xn--jp-l92cn98g071o", false}, {"大阪\uFF61jp", "xn--jp-ku9cz72u463f", false}, }, }, { name: "Lookup", profile: Lookup, subCases: []subCase{ {"example\u3002jp", "example.jp", false}, {"æ±äº¬\uFF0Ejp", "xn--1lqs71d.jp", false}, {"大阪\uFF61jp", "xn--pssu33l.jp", false}, }, }, { name: "Display", profile: Display, subCases: []subCase{ {"example\u3002jp", "example.jp", false}, {"æ±äº¬\uFF0Ejp", "xn--1lqs71d.jp", false}, {"大阪\uFF61jp", "xn--pssu33l.jp", false}, }, }, { name: "Registration", profile: Registration, subCases: []subCase{ {"example\u3002jp", "", true}, {"æ±äº¬\uFF0Ejp", "", true}, {"大阪\uFF61jp", "", true}, }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { for _, c := range tc.subCases { gotA, err := tc.profile.ToASCII(c.unicode) if c.wantErr { if err == nil { t.Errorf("ToASCII(%q): got no error, but an error expected", c.unicode) } } else { if err != nil { t.Errorf("ToASCII(%q): got err=%v, but no error expected", c.unicode, err) } else if gotA != c.wantASCII { t.Errorf("ToASCII(%q): got %q, want %q", c.unicode, gotA, c.wantASCII) } } } }) } } // TODO(nigeltao): test errors, once we've specified when ToASCII and ToUnicode // return errors. lxd-2.0.11/dist/src/golang.org/x/net/idna/idna.go0000644061062106075000000004412613172163402022477 0ustar stgraberdomain admins// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. // Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package idna implements IDNA2008 using the compatibility processing // defined by UTS (Unicode Technical Standard) #46, which defines a standard to // deal with the transition from IDNA2003. // // IDNA2008 (Internationalized Domain Names for Applications), is defined in RFC // 5890, RFC 5891, RFC 5892, RFC 5893 and RFC 5894. // UTS #46 is defined in http://www.unicode.org/reports/tr46. // See http://unicode.org/cldr/utility/idna.jsp for a visualization of the // differences between these two standards. package idna // import "golang.org/x/net/idna" import ( "fmt" "strings" "unicode/utf8" "golang.org/x/text/secure/bidirule" "golang.org/x/text/unicode/norm" ) // NOTE: Unlike common practice in Go APIs, the functions will return a // sanitized domain name in case of errors. Browsers sometimes use a partially // evaluated string as lookup. // TODO: the current error handling is, in my opinion, the least opinionated. // Other strategies are also viable, though: // Option 1) Return an empty string in case of error, but allow the user to // specify explicitly which errors to ignore. // Option 2) Return the partially evaluated string if it is itself a valid // string, otherwise return the empty string in case of error. // Option 3) Option 1 and 2. // Option 4) Always return an empty string for now and implement Option 1 as // needed, and document that the return string may not be empty in case of // error in the future. // I think Option 1 is best, but it is quite opinionated. // ToASCII is a wrapper for Punycode.ToASCII. func ToASCII(s string) (string, error) { return Punycode.process(s, true) } // ToUnicode is a wrapper for Punycode.ToUnicode. func ToUnicode(s string) (string, error) { return Punycode.process(s, false) } // An Option configures a Profile at creation time. type Option func(*options) // Transitional sets a Profile to use the Transitional mapping as defined in UTS // #46. This will cause, for example, "ß" to be mapped to "ss". Using the // transitional mapping provides a compromise between IDNA2003 and IDNA2008 // compatibility. It is used by most browsers when resolving domain names. This // option is only meaningful if combined with MapForLookup. func Transitional(transitional bool) Option { return func(o *options) { o.transitional = true } } // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts // are longer than allowed by the RFC. func VerifyDNSLength(verify bool) Option { return func(o *options) { o.verifyDNSLength = verify } } // RemoveLeadingDots removes leading label separators. Leading runes that map to // dots, such as U+3002, are removed as well. // // This is the behavior suggested by the UTS #46 and is adopted by some // browsers. func RemoveLeadingDots(remove bool) Option { return func(o *options) { o.removeLeadingDots = remove } } // ValidateLabels sets whether to check the mandatory label validation criteria // as defined in Section 5.4 of RFC 5891. This includes testing for correct use // of hyphens ('-'), normalization, validity of runes, and the context rules. func ValidateLabels(enable bool) Option { return func(o *options) { // Don't override existing mappings, but set one that at least checks // normalization if it is not set. if o.mapping == nil && enable { o.mapping = normalize } o.trie = trie o.validateLabels = enable o.fromPuny = validateFromPunycode } } // StrictDomainName limits the set of permissable ASCII characters to those // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the // hyphen). This is set by default for MapForLookup and ValidateForRegistration. // // This option is useful, for instance, for browsers that allow characters // outside this range, for example a '_' (U+005F LOW LINE). See // http://www.rfc-editor.org/std/std3.txt for more details This option // corresponds to the UseSTD3ASCIIRules option in UTS #46. func StrictDomainName(use bool) Option { return func(o *options) { o.trie = trie o.useSTD3Rules = use o.fromPuny = validateFromPunycode } } // NOTE: the following options pull in tables. The tables should not be linked // in as long as the options are not used. // BidiRule enables the Bidi rule as defined in RFC 5893. Any application // that relies on proper validation of labels should include this rule. func BidiRule() Option { return func(o *options) { o.bidirule = bidirule.ValidString } } // ValidateForRegistration sets validation options to verify that a given IDN is // properly formatted for registration as defined by Section 4 of RFC 5891. func ValidateForRegistration() Option { return func(o *options) { o.mapping = validateRegistration StrictDomainName(true)(o) ValidateLabels(true)(o) VerifyDNSLength(true)(o) BidiRule()(o) } } // MapForLookup sets validation and mapping options such that a given IDN is // transformed for domain name lookup according to the requirements set out in // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894, // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option // to add this check. // // The mappings include normalization and mapping case, width and other // compatibility mappings. func MapForLookup() Option { return func(o *options) { o.mapping = validateAndMap StrictDomainName(true)(o) ValidateLabels(true)(o) RemoveLeadingDots(true)(o) } } type options struct { transitional bool useSTD3Rules bool validateLabels bool verifyDNSLength bool removeLeadingDots bool trie *idnaTrie // fromPuny calls validation rules when converting A-labels to U-labels. fromPuny func(p *Profile, s string) error // mapping implements a validation and mapping step as defined in RFC 5895 // or UTS 46, tailored to, for example, domain registration or lookup. mapping func(p *Profile, s string) (string, error) // bidirule, if specified, checks whether s conforms to the Bidi Rule // defined in RFC 5893. bidirule func(s string) bool } // A Profile defines the configuration of an IDNA mapper. type Profile struct { options } func apply(o *options, opts []Option) { for _, f := range opts { f(o) } } // New creates a new Profile. // // With no options, the returned Profile is the most permissive and equals the // Punycode Profile. Options can be passed to further restrict the Profile. The // MapForLookup and ValidateForRegistration options set a collection of options, // for lookup and registration purposes respectively, which can be tailored by // adding more fine-grained options, where later options override earlier // options. func New(o ...Option) *Profile { p := &Profile{} apply(&p.options, o) return p } // ToASCII converts a domain or domain label to its ASCII form. For example, // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and // ToASCII("golang") is "golang". If an error is encountered it will return // an error and a (partially) processed result. func (p *Profile) ToASCII(s string) (string, error) { return p.process(s, true) } // ToUnicode converts a domain or domain label to its Unicode form. For example, // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and // ToUnicode("golang") is "golang". If an error is encountered it will return // an error and a (partially) processed result. func (p *Profile) ToUnicode(s string) (string, error) { pp := *p pp.transitional = false return pp.process(s, false) } // String reports a string with a description of the profile for debugging // purposes. The string format may change with different versions. func (p *Profile) String() string { s := "" if p.transitional { s = "Transitional" } else { s = "NonTransitional" } if p.useSTD3Rules { s += ":UseSTD3Rules" } if p.validateLabels { s += ":ValidateLabels" } if p.verifyDNSLength { s += ":VerifyDNSLength" } return s } var ( // Punycode is a Profile that does raw punycode processing with a minimum // of validation. Punycode *Profile = punycode // Lookup is the recommended profile for looking up domain names, according // to Section 5 of RFC 5891. The exact configuration of this profile may // change over time. Lookup *Profile = lookup // Display is the recommended profile for displaying domain names. // The configuration of this profile may change over time. Display *Profile = display // Registration is the recommended profile for checking whether a given // IDN is valid for registration, according to Section 4 of RFC 5891. Registration *Profile = registration punycode = &Profile{} lookup = &Profile{options{ transitional: true, useSTD3Rules: true, validateLabels: true, removeLeadingDots: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateAndMap, bidirule: bidirule.ValidString, }} display = &Profile{options{ useSTD3Rules: true, validateLabels: true, removeLeadingDots: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateAndMap, bidirule: bidirule.ValidString, }} registration = &Profile{options{ useSTD3Rules: true, validateLabels: true, verifyDNSLength: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateRegistration, bidirule: bidirule.ValidString, }} // TODO: profiles // Register: recommended for approving domain names: don't do any mappings // but rather reject on invalid input. Bundle or block deviation characters. ) type labelError struct{ label, code_ string } func (e labelError) code() string { return e.code_ } func (e labelError) Error() string { return fmt.Sprintf("idna: invalid label %q", e.label) } type runeError rune func (e runeError) code() string { return "P1" } func (e runeError) Error() string { return fmt.Sprintf("idna: disallowed rune %U", e) } // process implements the algorithm described in section 4 of UTS #46, // see http://www.unicode.org/reports/tr46. func (p *Profile) process(s string, toASCII bool) (string, error) { var err error if p.mapping != nil { s, err = p.mapping(p, s) } // Remove leading empty labels. if p.removeLeadingDots { for ; len(s) > 0 && s[0] == '.'; s = s[1:] { } } // It seems like we should only create this error on ToASCII, but the // UTS 46 conformance tests suggests we should always check this. if err == nil && p.verifyDNSLength && s == "" { err = &labelError{s, "A4"} } labels := labelIter{orig: s} for ; !labels.done(); labels.next() { label := labels.label() if label == "" { // Empty labels are not okay. The label iterator skips the last // label if it is empty. if err == nil && p.verifyDNSLength { err = &labelError{s, "A4"} } continue } if strings.HasPrefix(label, acePrefix) { u, err2 := decode(label[len(acePrefix):]) if err2 != nil { if err == nil { err = err2 } // Spec says keep the old label. continue } labels.set(u) if err == nil && p.validateLabels { err = p.fromPuny(p, u) } if err == nil { // This should be called on NonTransitional, according to the // spec, but that currently does not have any effect. Use the // original profile to preserve options. err = p.validateLabel(u) } } else if err == nil { err = p.validateLabel(label) } } if toASCII { for labels.reset(); !labels.done(); labels.next() { label := labels.label() if !ascii(label) { a, err2 := encode(acePrefix, label) if err == nil { err = err2 } label = a labels.set(a) } n := len(label) if p.verifyDNSLength && err == nil && (n == 0 || n > 63) { err = &labelError{label, "A4"} } } } s = labels.result() if toASCII && p.verifyDNSLength && err == nil { // Compute the length of the domain name minus the root label and its dot. n := len(s) if n > 0 && s[n-1] == '.' { n-- } if len(s) < 1 || n > 253 { err = &labelError{s, "A4"} } } return s, err } func normalize(p *Profile, s string) (string, error) { return norm.NFC.String(s), nil } func validateRegistration(p *Profile, s string) (string, error) { if !norm.NFC.IsNormalString(s) { return s, &labelError{s, "V1"} } for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) // Copy bytes not copied so far. switch p.simplify(info(v).category()) { // TODO: handle the NV8 defined in the Unicode idna data set to allow // for strict conformance to IDNA2008. case valid, deviation: case disallowed, mapped, unknown, ignored: r, _ := utf8.DecodeRuneInString(s[i:]) return s, runeError(r) } i += sz } return s, nil } func validateAndMap(p *Profile, s string) (string, error) { var ( err error b []byte k int ) for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) start := i i += sz // Copy bytes not copied so far. switch p.simplify(info(v).category()) { case valid: continue case disallowed: if err == nil { r, _ := utf8.DecodeRuneInString(s[start:]) err = runeError(r) } continue case mapped, deviation: b = append(b, s[k:start]...) b = info(v).appendMapping(b, s[start:i]) case ignored: b = append(b, s[k:start]...) // drop the rune case unknown: b = append(b, s[k:start]...) b = append(b, "\ufffd"...) } k = i } if k == 0 { // No changes so far. s = norm.NFC.String(s) } else { b = append(b, s[k:]...) if norm.NFC.QuickSpan(b) != len(b) { b = norm.NFC.Bytes(b) } // TODO: the punycode converters require strings as input. s = string(b) } return s, err } // A labelIter allows iterating over domain name labels. type labelIter struct { orig string slice []string curStart int curEnd int i int } func (l *labelIter) reset() { l.curStart = 0 l.curEnd = 0 l.i = 0 } func (l *labelIter) done() bool { return l.curStart >= len(l.orig) } func (l *labelIter) result() string { if l.slice != nil { return strings.Join(l.slice, ".") } return l.orig } func (l *labelIter) label() string { if l.slice != nil { return l.slice[l.i] } p := strings.IndexByte(l.orig[l.curStart:], '.') l.curEnd = l.curStart + p if p == -1 { l.curEnd = len(l.orig) } return l.orig[l.curStart:l.curEnd] } // next sets the value to the next label. It skips the last label if it is empty. func (l *labelIter) next() { l.i++ if l.slice != nil { if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" { l.curStart = len(l.orig) } } else { l.curStart = l.curEnd + 1 if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' { l.curStart = len(l.orig) } } } func (l *labelIter) set(s string) { if l.slice == nil { l.slice = strings.Split(l.orig, ".") } l.slice[l.i] = s } // acePrefix is the ASCII Compatible Encoding prefix. const acePrefix = "xn--" func (p *Profile) simplify(cat category) category { switch cat { case disallowedSTD3Mapped: if p.useSTD3Rules { cat = disallowed } else { cat = mapped } case disallowedSTD3Valid: if p.useSTD3Rules { cat = disallowed } else { cat = valid } case deviation: if !p.transitional { cat = valid } case validNV8, validXV8: // TODO: handle V2008 cat = valid } return cat } func validateFromPunycode(p *Profile, s string) error { if !norm.NFC.IsNormalString(s) { return &labelError{s, "V1"} } for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) if c := p.simplify(info(v).category()); c != valid && c != deviation { return &labelError{s, "V6"} } i += sz } return nil } const ( zwnj = "\u200c" zwj = "\u200d" ) type joinState int8 const ( stateStart joinState = iota stateVirama stateBefore stateBeforeVirama stateAfter stateFAIL ) var joinStates = [][numJoinTypes]joinState{ stateStart: { joiningL: stateBefore, joiningD: stateBefore, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateVirama, }, stateVirama: { joiningL: stateBefore, joiningD: stateBefore, }, stateBefore: { joiningL: stateBefore, joiningD: stateBefore, joiningT: stateBefore, joinZWNJ: stateAfter, joinZWJ: stateFAIL, joinVirama: stateBeforeVirama, }, stateBeforeVirama: { joiningL: stateBefore, joiningD: stateBefore, joiningT: stateBefore, }, stateAfter: { joiningL: stateFAIL, joiningD: stateBefore, joiningT: stateAfter, joiningR: stateStart, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateAfter, // no-op as we can't accept joiners here }, stateFAIL: { 0: stateFAIL, joiningL: stateFAIL, joiningD: stateFAIL, joiningT: stateFAIL, joiningR: stateFAIL, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateFAIL, }, } // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are // already implicitly satisfied by the overall implementation. func (p *Profile) validateLabel(s string) error { if s == "" { if p.verifyDNSLength { return &labelError{s, "A4"} } return nil } if p.bidirule != nil && !p.bidirule(s) { return &labelError{s, "B"} } if !p.validateLabels { return nil } trie := p.trie // p.validateLabels is only set if trie is set. if len(s) > 4 && s[2] == '-' && s[3] == '-' { return &labelError{s, "V2"} } if s[0] == '-' || s[len(s)-1] == '-' { return &labelError{s, "V3"} } // TODO: merge the use of this in the trie. v, sz := trie.lookupString(s) x := info(v) if x.isModifier() { return &labelError{s, "V5"} } // Quickly return in the absence of zero-width (non) joiners. if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 { return nil } st := stateStart for i := 0; ; { jt := x.joinType() if s[i:i+sz] == zwj { jt = joinZWJ } else if s[i:i+sz] == zwnj { jt = joinZWNJ } st = joinStates[st][jt] if x.isViramaModifier() { st = joinStates[st][joinVirama] } if i += sz; i == len(s) { break } v, sz = trie.lookupString(s[i:]) x = info(v) } if st == stateFAIL || st == stateAfter { return &labelError{s, "C"} } return nil } func ascii(s string) bool { for i := 0; i < len(s); i++ { if s[i] >= utf8.RuneSelf { return false } } return true } lxd-2.0.11/dist/src/golang.org/x/net/idna/example_test.go0000644061062106075000000000375513172163402024261 0ustar stgraberdomain admins// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. // Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package idna_test import ( "fmt" "golang.org/x/net/idna" ) func ExampleProfile() { // Raw Punycode has no restrictions and does no mappings. fmt.Println(idna.ToASCII("")) fmt.Println(idna.ToASCII("*.faß.com")) fmt.Println(idna.Punycode.ToASCII("*.faß.com")) // Rewrite IDN for lookup. This (currently) uses transitional mappings to // find a balance between IDNA2003 and IDNA2008 compatibility. fmt.Println(idna.Lookup.ToASCII("")) fmt.Println(idna.Lookup.ToASCII("www.faß.com")) // Convert an IDN to ASCII for registration purposes. This changes the // encoding, but reports an error if the input was illformed. fmt.Println(idna.Registration.ToASCII("")) fmt.Println(idna.Registration.ToASCII("www.faß.com")) // Output: // // *.xn--fa-hia.com // *.xn--fa-hia.com // // www.fass.com // idna: invalid label "" // www.xn--fa-hia.com } func ExampleNew() { var p *idna.Profile // Raw Punycode has no restrictions and does no mappings. p = idna.New() fmt.Println(p.ToASCII("*.faß.com")) // Do mappings. Note that star is not allowed in a DNS lookup. p = idna.New( idna.MapForLookup(), idna.Transitional(true)) // Map ß -> ss fmt.Println(p.ToASCII("*.faß.com")) // Lookup for registration. Also does not allow '*'. p = idna.New(idna.ValidateForRegistration()) fmt.Println(p.ToUnicode("*.faß.com")) // Set up a profile maps for lookup, but allows wild cards. p = idna.New( idna.MapForLookup(), idna.Transitional(true), // Map ß -> ss idna.StrictDomainName(false)) // Set more permissive ASCII rules. fmt.Println(p.ToASCII("*.faß.com")) // Output: // *.xn--fa-hia.com // *.fass.com idna: disallowed rune U+002A // *.faß.com idna: disallowed rune U+002A // *.fass.com } lxd-2.0.11/dist/src/golang.org/x/net/icmp/0000755061062106075000000000000013172163402021243 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/icmp/timeexceeded.go0000644061062106075000000000215113172163402024216 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp // A TimeExceeded represents an ICMP time exceeded message body. type TimeExceeded struct { Data []byte // data, known as original datagram field Extensions []Extension // extensions } // Len implements the Len method of MessageBody interface. func (p *TimeExceeded) Len(proto int) int { if p == nil { return 0 } l, _ := multipartMessageBodyDataLen(proto, p.Data, p.Extensions) return 4 + l } // Marshal implements the Marshal method of MessageBody interface. func (p *TimeExceeded) Marshal(proto int) ([]byte, error) { return marshalMultipartMessageBody(proto, p.Data, p.Extensions) } // parseTimeExceeded parses b as an ICMP time exceeded message body. func parseTimeExceeded(proto int, b []byte) (MessageBody, error) { if len(b) < 4 { return nil, errMessageTooShort } p := &TimeExceeded{} var err error p.Data, p.Extensions, err = parseMultipartMessageBody(proto, b) if err != nil { return nil, err } return p, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/sys_freebsd.go0000644061062106075000000000041413172163402024101 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import "syscall" func init() { freebsdVersion, _ = syscall.SysctlUint32("kern.osreldate") } lxd-2.0.11/dist/src/golang.org/x/net/icmp/ping_test.go0000644061062106075000000001036213172163402023570 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp_test import ( "errors" "fmt" "net" "os" "runtime" "sync" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) func googleAddr(c *icmp.PacketConn, protocol int) (net.Addr, error) { const host = "www.google.com" ips, err := net.LookupIP(host) if err != nil { return nil, err } netaddr := func(ip net.IP) (net.Addr, error) { switch c.LocalAddr().(type) { case *net.UDPAddr: return &net.UDPAddr{IP: ip}, nil case *net.IPAddr: return &net.IPAddr{IP: ip}, nil default: return nil, errors.New("neither UDPAddr nor IPAddr") } } for _, ip := range ips { switch protocol { case iana.ProtocolICMP: if ip.To4() != nil { return netaddr(ip) } case iana.ProtocolIPv6ICMP: if ip.To16() != nil && ip.To4() == nil { return netaddr(ip) } } } return nil, errors.New("no A or AAAA record") } type pingTest struct { network, address string protocol int mtype icmp.Type } var nonPrivilegedPingTests = []pingTest{ {"udp4", "0.0.0.0", iana.ProtocolICMP, ipv4.ICMPTypeEcho}, {"udp6", "::", iana.ProtocolIPv6ICMP, ipv6.ICMPTypeEchoRequest}, } func TestNonPrivilegedPing(t *testing.T) { if testing.Short() { t.Skip("avoid external network") } switch runtime.GOOS { case "darwin": case "linux": t.Log("you may need to adjust the net.ipv4.ping_group_range kernel state") default: t.Skipf("not supported on %s", runtime.GOOS) } for i, tt := range nonPrivilegedPingTests { if err := doPing(tt, i); err != nil { t.Error(err) } } } var privilegedPingTests = []pingTest{ {"ip4:icmp", "0.0.0.0", iana.ProtocolICMP, ipv4.ICMPTypeEcho}, {"ip6:ipv6-icmp", "::", iana.ProtocolIPv6ICMP, ipv6.ICMPTypeEchoRequest}, } func TestPrivilegedPing(t *testing.T) { if testing.Short() { t.Skip("avoid external network") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } for i, tt := range privilegedPingTests { if err := doPing(tt, i); err != nil { t.Error(err) } } } func doPing(tt pingTest, seq int) error { c, err := icmp.ListenPacket(tt.network, tt.address) if err != nil { return err } defer c.Close() dst, err := googleAddr(c, tt.protocol) if err != nil { return err } if tt.network != "udp6" && tt.protocol == iana.ProtocolIPv6ICMP { var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeDestinationUnreachable) f.Accept(ipv6.ICMPTypePacketTooBig) f.Accept(ipv6.ICMPTypeTimeExceeded) f.Accept(ipv6.ICMPTypeParameterProblem) f.Accept(ipv6.ICMPTypeEchoReply) if err := c.IPv6PacketConn().SetICMPFilter(&f); err != nil { return err } } wm := icmp.Message{ Type: tt.mtype, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: 1 << uint(seq), Data: []byte("HELLO-R-U-THERE"), }, } wb, err := wm.Marshal(nil) if err != nil { return err } if n, err := c.WriteTo(wb, dst); err != nil { return err } else if n != len(wb) { return fmt.Errorf("got %v; want %v", n, len(wb)) } rb := make([]byte, 1500) if err := c.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil { return err } n, peer, err := c.ReadFrom(rb) if err != nil { return err } rm, err := icmp.ParseMessage(tt.protocol, rb[:n]) if err != nil { return err } switch rm.Type { case ipv4.ICMPTypeEchoReply, ipv6.ICMPTypeEchoReply: return nil default: return fmt.Errorf("got %+v from %v; want echo reply", rm, peer) } } func TestConcurrentNonPrivilegedListenPacket(t *testing.T) { if testing.Short() { t.Skip("avoid external network") } switch runtime.GOOS { case "darwin": case "linux": t.Log("you may need to adjust the net.ipv4.ping_group_range kernel state") default: t.Skipf("not supported on %s", runtime.GOOS) } network, address := "udp4", "127.0.0.1" if !nettest.SupportsIPv4() { network, address = "udp6", "::1" } const N = 1000 var wg sync.WaitGroup wg.Add(N) for i := 0; i < N; i++ { go func() { defer wg.Done() c, err := icmp.ListenPacket(network, address) if err != nil { t.Error(err) return } c.Close() }() } wg.Wait() } lxd-2.0.11/dist/src/golang.org/x/net/icmp/paramprob.go0000644061062106075000000000324413172163402023560 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "encoding/binary" "golang.org/x/net/internal/iana" ) // A ParamProb represents an ICMP parameter problem message body. type ParamProb struct { Pointer uintptr // offset within the data where the error was detected Data []byte // data, known as original datagram field Extensions []Extension // extensions } // Len implements the Len method of MessageBody interface. func (p *ParamProb) Len(proto int) int { if p == nil { return 0 } l, _ := multipartMessageBodyDataLen(proto, p.Data, p.Extensions) return 4 + l } // Marshal implements the Marshal method of MessageBody interface. func (p *ParamProb) Marshal(proto int) ([]byte, error) { if proto == iana.ProtocolIPv6ICMP { b := make([]byte, p.Len(proto)) binary.BigEndian.PutUint32(b[:4], uint32(p.Pointer)) copy(b[4:], p.Data) return b, nil } b, err := marshalMultipartMessageBody(proto, p.Data, p.Extensions) if err != nil { return nil, err } b[0] = byte(p.Pointer) return b, nil } // parseParamProb parses b as an ICMP parameter problem message body. func parseParamProb(proto int, b []byte) (MessageBody, error) { if len(b) < 4 { return nil, errMessageTooShort } p := &ParamProb{} if proto == iana.ProtocolIPv6ICMP { p.Pointer = uintptr(binary.BigEndian.Uint32(b[:4])) p.Data = make([]byte, len(b)-4) copy(p.Data, b[4:]) return p, nil } p.Pointer = uintptr(b[0]) var err error p.Data, p.Extensions, err = parseMultipartMessageBody(proto, b) if err != nil { return nil, err } return p, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/packettoobig.go0000644061062106075000000000224513172163402024250 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import "encoding/binary" // A PacketTooBig represents an ICMP packet too big message body. type PacketTooBig struct { MTU int // maximum transmission unit of the nexthop link Data []byte // data, known as original datagram field } // Len implements the Len method of MessageBody interface. func (p *PacketTooBig) Len(proto int) int { if p == nil { return 0 } return 4 + len(p.Data) } // Marshal implements the Marshal method of MessageBody interface. func (p *PacketTooBig) Marshal(proto int) ([]byte, error) { b := make([]byte, 4+len(p.Data)) binary.BigEndian.PutUint32(b[:4], uint32(p.MTU)) copy(b[4:], p.Data) return b, nil } // parsePacketTooBig parses b as an ICMP packet too big message body. func parsePacketTooBig(proto int, b []byte) (MessageBody, error) { bodyLen := len(b) if bodyLen < 4 { return nil, errMessageTooShort } p := &PacketTooBig{MTU: int(binary.BigEndian.Uint32(b[:4]))} if bodyLen > 4 { p.Data = make([]byte, bodyLen-4) copy(p.Data, b[4:]) } return p, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/multipart_test.go0000644061062106075000000002423713172163402024662 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp_test import ( "fmt" "net" "reflect" "testing" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) var marshalAndParseMultipartMessageForIPv4Tests = []icmp.Message{ { Type: ipv4.ICMPTypeDestinationUnreachable, Code: 15, Body: &icmp.DstUnreach{ Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.IPv4(192, 168, 0, 1).To4(), }, }, }, }, }, { Type: ipv4.ICMPTypeTimeExceeded, Code: 1, Body: &icmp.TimeExceeded{ Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.IPv4(192, 168, 0, 1).To4(), }, }, &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, }, }, }, { Type: ipv4.ICMPTypeParameterProblem, Code: 2, Body: &icmp.ParamProb{ Pointer: 8, Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.IPv4(192, 168, 0, 1).To4(), }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x2f, Interface: &net.Interface{ Index: 16, Name: "en102", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.IPv4(192, 168, 0, 2).To4(), }, }, }, }, }, } func TestMarshalAndParseMultipartMessageForIPv4(t *testing.T) { for i, tt := range marshalAndParseMultipartMessageForIPv4Tests { b, err := tt.Marshal(nil) if err != nil { t.Fatal(err) } if b[5] != 32 { t.Errorf("#%v: got %v; want 32", i, b[5]) } m, err := icmp.ParseMessage(iana.ProtocolICMP, b) if err != nil { t.Fatal(err) } if m.Type != tt.Type || m.Code != tt.Code { t.Errorf("#%v: got %v; want %v", i, m, &tt) } switch m.Type { case ipv4.ICMPTypeDestinationUnreachable: got, want := m.Body.(*icmp.DstUnreach), tt.Body.(*icmp.DstUnreach) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } case ipv4.ICMPTypeTimeExceeded: got, want := m.Body.(*icmp.TimeExceeded), tt.Body.(*icmp.TimeExceeded) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } case ipv4.ICMPTypeParameterProblem: got, want := m.Body.(*icmp.ParamProb), tt.Body.(*icmp.ParamProb) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } } } } var marshalAndParseMultipartMessageForIPv6Tests = []icmp.Message{ { Type: ipv6.ICMPTypeDestinationUnreachable, Code: 6, Body: &icmp.DstUnreach{ Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en101", }, }, }, }, }, { Type: ipv6.ICMPTypeTimeExceeded, Code: 1, Body: &icmp.TimeExceeded{ Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en101", }, }, &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x2f, Interface: &net.Interface{ Index: 16, Name: "en102", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en102", }, }, }, }, }, } func TestMarshalAndParseMultipartMessageForIPv6(t *testing.T) { pshicmp := icmp.IPv6PseudoHeader(net.ParseIP("fe80::1"), net.ParseIP("ff02::1")) for i, tt := range marshalAndParseMultipartMessageForIPv6Tests { for _, psh := range [][]byte{pshicmp, nil} { b, err := tt.Marshal(psh) if err != nil { t.Fatal(err) } if b[4] != 16 { t.Errorf("#%v: got %v; want 16", i, b[4]) } m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, b) if err != nil { t.Fatal(err) } if m.Type != tt.Type || m.Code != tt.Code { t.Errorf("#%v: got %v; want %v", i, m, &tt) } switch m.Type { case ipv6.ICMPTypeDestinationUnreachable: got, want := m.Body.(*icmp.DstUnreach), tt.Body.(*icmp.DstUnreach) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } case ipv6.ICMPTypeTimeExceeded: got, want := m.Body.(*icmp.TimeExceeded), tt.Body.(*icmp.TimeExceeded) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } } } } } func dumpExtensions(i int, gotExts, wantExts []icmp.Extension) string { var s string for j, got := range gotExts { switch got := got.(type) { case *icmp.MPLSLabelStack: want := wantExts[j].(*icmp.MPLSLabelStack) if !reflect.DeepEqual(got, want) { s += fmt.Sprintf("#%v/%v: got %#v; want %#v\n", i, j, got, want) } case *icmp.InterfaceInfo: want := wantExts[j].(*icmp.InterfaceInfo) if !reflect.DeepEqual(got, want) { s += fmt.Sprintf("#%v/%v: got %#v, %#v, %#v; want %#v, %#v, %#v\n", i, j, got, got.Interface, got.Addr, want, want.Interface, want.Addr) } } } return s[:len(s)-1] } var multipartMessageBodyLenTests = []struct { proto int in icmp.MessageBody out int }{ { iana.ProtocolICMP, &icmp.DstUnreach{ Data: make([]byte, ipv4.HeaderLen), }, 4 + ipv4.HeaderLen, // unused and original datagram }, { iana.ProtocolICMP, &icmp.TimeExceeded{ Data: make([]byte, ipv4.HeaderLen), }, 4 + ipv4.HeaderLen, // unused and original datagram }, { iana.ProtocolICMP, &icmp.ParamProb{ Data: make([]byte, ipv4.HeaderLen), }, 4 + ipv4.HeaderLen, // [pointer, unused] and original datagram }, { iana.ProtocolICMP, &icmp.ParamProb{ Data: make([]byte, ipv4.HeaderLen), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{}, }, }, 4 + 4 + 4 + 0 + 128, // [pointer, length, unused], extension header, object header, object payload, original datagram }, { iana.ProtocolICMP, &icmp.ParamProb{ Data: make([]byte, 128), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{}, }, }, 4 + 4 + 4 + 0 + 128, // [pointer, length, unused], extension header, object header, object payload and original datagram }, { iana.ProtocolICMP, &icmp.ParamProb{ Data: make([]byte, 129), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{}, }, }, 4 + 4 + 4 + 0 + 132, // [pointer, length, unused], extension header, object header, object payload and original datagram }, { iana.ProtocolIPv6ICMP, &icmp.DstUnreach{ Data: make([]byte, ipv6.HeaderLen), }, 4 + ipv6.HeaderLen, // unused and original datagram }, { iana.ProtocolIPv6ICMP, &icmp.PacketTooBig{ Data: make([]byte, ipv6.HeaderLen), }, 4 + ipv6.HeaderLen, // mtu and original datagram }, { iana.ProtocolIPv6ICMP, &icmp.TimeExceeded{ Data: make([]byte, ipv6.HeaderLen), }, 4 + ipv6.HeaderLen, // unused and original datagram }, { iana.ProtocolIPv6ICMP, &icmp.ParamProb{ Data: make([]byte, ipv6.HeaderLen), }, 4 + ipv6.HeaderLen, // pointer and original datagram }, { iana.ProtocolIPv6ICMP, &icmp.DstUnreach{ Data: make([]byte, 127), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{}, }, }, 4 + 4 + 4 + 0 + 128, // [length, unused], extension header, object header, object payload and original datagram }, { iana.ProtocolIPv6ICMP, &icmp.DstUnreach{ Data: make([]byte, 128), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{}, }, }, 4 + 4 + 4 + 0 + 128, // [length, unused], extension header, object header, object payload and original datagram }, { iana.ProtocolIPv6ICMP, &icmp.DstUnreach{ Data: make([]byte, 129), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{}, }, }, 4 + 4 + 4 + 0 + 136, // [length, unused], extension header, object header, object payload and original datagram }, } func TestMultipartMessageBodyLen(t *testing.T) { for i, tt := range multipartMessageBodyLenTests { if out := tt.in.Len(tt.proto); out != tt.out { t.Errorf("#%d: got %d; want %d", i, out, tt.out) } } } lxd-2.0.11/dist/src/golang.org/x/net/icmp/multipart.go0000644061062106075000000000577213172163402023626 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import "golang.org/x/net/internal/iana" // multipartMessageBodyDataLen takes b as an original datagram and // exts as extensions, and returns a required length for message body // and a required length for a padded original datagram in wire // format. func multipartMessageBodyDataLen(proto int, b []byte, exts []Extension) (bodyLen, dataLen int) { for _, ext := range exts { bodyLen += ext.Len(proto) } if bodyLen > 0 { dataLen = multipartMessageOrigDatagramLen(proto, b) bodyLen += 4 // length of extension header } else { dataLen = len(b) } bodyLen += dataLen return bodyLen, dataLen } // multipartMessageOrigDatagramLen takes b as an original datagram, // and returns a required length for a padded orignal datagram in wire // format. func multipartMessageOrigDatagramLen(proto int, b []byte) int { roundup := func(b []byte, align int) int { // According to RFC 4884, the padded original datagram // field must contain at least 128 octets. if len(b) < 128 { return 128 } r := len(b) return (r + align - 1) & ^(align - 1) } switch proto { case iana.ProtocolICMP: return roundup(b, 4) case iana.ProtocolIPv6ICMP: return roundup(b, 8) default: return len(b) } } // marshalMultipartMessageBody takes data as an original datagram and // exts as extesnsions, and returns a binary encoding of message body. // It can be used for non-multipart message bodies when exts is nil. func marshalMultipartMessageBody(proto int, data []byte, exts []Extension) ([]byte, error) { bodyLen, dataLen := multipartMessageBodyDataLen(proto, data, exts) b := make([]byte, 4+bodyLen) copy(b[4:], data) off := dataLen + 4 if len(exts) > 0 { b[dataLen+4] = byte(extensionVersion << 4) off += 4 // length of object header for _, ext := range exts { switch ext := ext.(type) { case *MPLSLabelStack: if err := ext.marshal(proto, b[off:]); err != nil { return nil, err } off += ext.Len(proto) case *InterfaceInfo: attrs, l := ext.attrsAndLen(proto) if err := ext.marshal(proto, b[off:], attrs, l); err != nil { return nil, err } off += ext.Len(proto) } } s := checksum(b[dataLen+4:]) b[dataLen+4+2] ^= byte(s) b[dataLen+4+3] ^= byte(s >> 8) switch proto { case iana.ProtocolICMP: b[1] = byte(dataLen / 4) case iana.ProtocolIPv6ICMP: b[0] = byte(dataLen / 8) } } return b, nil } // parseMultipartMessageBody parses b as either a non-multipart // message body or a multipart message body. func parseMultipartMessageBody(proto int, b []byte) ([]byte, []Extension, error) { var l int switch proto { case iana.ProtocolICMP: l = 4 * int(b[1]) case iana.ProtocolIPv6ICMP: l = 8 * int(b[0]) } if len(b) == 4 { return nil, nil, nil } exts, l, err := parseExtensions(b[4:], l) if err != nil { l = len(b) - 4 } data := make([]byte, l) copy(data, b[4:]) return data, exts, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/mpls.go0000644061062106075000000000360213172163402022546 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import "encoding/binary" // A MPLSLabel represents a MPLS label stack entry. type MPLSLabel struct { Label int // label value TC int // traffic class; formerly experimental use S bool // bottom of stack TTL int // time to live } const ( classMPLSLabelStack = 1 typeIncomingMPLSLabelStack = 1 ) // A MPLSLabelStack represents a MPLS label stack. type MPLSLabelStack struct { Class int // extension object class number Type int // extension object sub-type Labels []MPLSLabel } // Len implements the Len method of Extension interface. func (ls *MPLSLabelStack) Len(proto int) int { return 4 + (4 * len(ls.Labels)) } // Marshal implements the Marshal method of Extension interface. func (ls *MPLSLabelStack) Marshal(proto int) ([]byte, error) { b := make([]byte, ls.Len(proto)) if err := ls.marshal(proto, b); err != nil { return nil, err } return b, nil } func (ls *MPLSLabelStack) marshal(proto int, b []byte) error { l := ls.Len(proto) binary.BigEndian.PutUint16(b[:2], uint16(l)) b[2], b[3] = classMPLSLabelStack, typeIncomingMPLSLabelStack off := 4 for _, ll := range ls.Labels { b[off], b[off+1], b[off+2] = byte(ll.Label>>12), byte(ll.Label>>4&0xff), byte(ll.Label<<4&0xf0) b[off+2] |= byte(ll.TC << 1 & 0x0e) if ll.S { b[off+2] |= 0x1 } b[off+3] = byte(ll.TTL) off += 4 } return nil } func parseMPLSLabelStack(b []byte) (Extension, error) { ls := &MPLSLabelStack{ Class: int(b[2]), Type: int(b[3]), } for b = b[4:]; len(b) >= 4; b = b[4:] { ll := MPLSLabel{ Label: int(b[0])<<12 | int(b[1])<<4 | int(b[2])>>4, TC: int(b[2]&0x0e) >> 1, TTL: int(b[3]), } if b[2]&0x1 != 0 { ll.S = true } ls.Labels = append(ls.Labels, ll) } return ls, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/messagebody.go0000644061062106075000000000226713172163402024103 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp // A MessageBody represents an ICMP message body. type MessageBody interface { // Len returns the length of ICMP message body. // Proto must be either the ICMPv4 or ICMPv6 protocol number. Len(proto int) int // Marshal returns the binary encoding of ICMP message body. // Proto must be either the ICMPv4 or ICMPv6 protocol number. Marshal(proto int) ([]byte, error) } // A DefaultMessageBody represents the default message body. type DefaultMessageBody struct { Data []byte // data } // Len implements the Len method of MessageBody interface. func (p *DefaultMessageBody) Len(proto int) int { if p == nil { return 0 } return len(p.Data) } // Marshal implements the Marshal method of MessageBody interface. func (p *DefaultMessageBody) Marshal(proto int) ([]byte, error) { return p.Data, nil } // parseDefaultMessageBody parses b as an ICMP message body. func parseDefaultMessageBody(proto int, b []byte) (MessageBody, error) { p := &DefaultMessageBody{Data: make([]byte, len(b))} copy(p.Data, b) return p, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/message_test.go0000644061062106075000000000570413172163402024263 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp_test import ( "net" "reflect" "testing" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) var marshalAndParseMessageForIPv4Tests = []icmp.Message{ { Type: ipv4.ICMPTypeDestinationUnreachable, Code: 15, Body: &icmp.DstUnreach{ Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv4.ICMPTypeTimeExceeded, Code: 1, Body: &icmp.TimeExceeded{ Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv4.ICMPTypeParameterProblem, Code: 2, Body: &icmp.ParamProb{ Pointer: 8, Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: 1, Seq: 2, Data: []byte("HELLO-R-U-THERE"), }, }, { Type: ipv4.ICMPTypePhoturis, Body: &icmp.DefaultMessageBody{ Data: []byte{0x80, 0x40, 0x20, 0x10}, }, }, } func TestMarshalAndParseMessageForIPv4(t *testing.T) { for i, tt := range marshalAndParseMessageForIPv4Tests { b, err := tt.Marshal(nil) if err != nil { t.Fatal(err) } m, err := icmp.ParseMessage(iana.ProtocolICMP, b) if err != nil { t.Fatal(err) } if m.Type != tt.Type || m.Code != tt.Code { t.Errorf("#%v: got %v; want %v", i, m, &tt) } if !reflect.DeepEqual(m.Body, tt.Body) { t.Errorf("#%v: got %v; want %v", i, m.Body, tt.Body) } } } var marshalAndParseMessageForIPv6Tests = []icmp.Message{ { Type: ipv6.ICMPTypeDestinationUnreachable, Code: 6, Body: &icmp.DstUnreach{ Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv6.ICMPTypePacketTooBig, Code: 0, Body: &icmp.PacketTooBig{ MTU: 1<<16 - 1, Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv6.ICMPTypeTimeExceeded, Code: 1, Body: &icmp.TimeExceeded{ Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv6.ICMPTypeParameterProblem, Code: 2, Body: &icmp.ParamProb{ Pointer: 8, Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: 1, Seq: 2, Data: []byte("HELLO-R-U-THERE"), }, }, { Type: ipv6.ICMPTypeDuplicateAddressConfirmation, Body: &icmp.DefaultMessageBody{ Data: []byte{0x80, 0x40, 0x20, 0x10}, }, }, } func TestMarshalAndParseMessageForIPv6(t *testing.T) { pshicmp := icmp.IPv6PseudoHeader(net.ParseIP("fe80::1"), net.ParseIP("ff02::1")) for i, tt := range marshalAndParseMessageForIPv6Tests { for _, psh := range [][]byte{pshicmp, nil} { b, err := tt.Marshal(psh) if err != nil { t.Fatal(err) } m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, b) if err != nil { t.Fatal(err) } if m.Type != tt.Type || m.Code != tt.Code { t.Errorf("#%v: got %v; want %v", i, m, &tt) } if !reflect.DeepEqual(m.Body, tt.Body) { t.Errorf("#%v: got %v; want %v", i, m.Body, tt.Body) } } } } lxd-2.0.11/dist/src/golang.org/x/net/icmp/message.go0000644061062106075000000001052013172163402023214 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package icmp provides basic functions for the manipulation of // messages used in the Internet Control Message Protocols, // ICMPv4 and ICMPv6. // // ICMPv4 and ICMPv6 are defined in RFC 792 and RFC 4443. // Multi-part message support for ICMP is defined in RFC 4884. // ICMP extensions for MPLS are defined in RFC 4950. // ICMP extensions for interface and next-hop identification are // defined in RFC 5837. package icmp // import "golang.org/x/net/icmp" import ( "encoding/binary" "errors" "net" "syscall" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) // BUG(mikio): This package is not implemented on NaCl and Plan 9. var ( errMessageTooShort = errors.New("message too short") errHeaderTooShort = errors.New("header too short") errBufferTooShort = errors.New("buffer too short") errOpNoSupport = errors.New("operation not supported") errNoExtension = errors.New("no extension") errInvalidExtension = errors.New("invalid extension") ) func checksum(b []byte) uint16 { csumcv := len(b) - 1 // checksum coverage s := uint32(0) for i := 0; i < csumcv; i += 2 { s += uint32(b[i+1])<<8 | uint32(b[i]) } if csumcv&1 == 0 { s += uint32(b[csumcv]) } s = s>>16 + s&0xffff s = s + s>>16 return ^uint16(s) } // A Type represents an ICMP message type. type Type interface { Protocol() int } // A Message represents an ICMP message. type Message struct { Type Type // type, either ipv4.ICMPType or ipv6.ICMPType Code int // code Checksum int // checksum Body MessageBody // body } // Marshal returns the binary encoding of the ICMP message m. // // For an ICMPv4 message, the returned message always contains the // calculated checksum field. // // For an ICMPv6 message, the returned message contains the calculated // checksum field when psh is not nil, otherwise the kernel will // compute the checksum field during the message transmission. // When psh is not nil, it must be the pseudo header for IPv6. func (m *Message) Marshal(psh []byte) ([]byte, error) { var mtype int switch typ := m.Type.(type) { case ipv4.ICMPType: mtype = int(typ) case ipv6.ICMPType: mtype = int(typ) default: return nil, syscall.EINVAL } b := []byte{byte(mtype), byte(m.Code), 0, 0} if m.Type.Protocol() == iana.ProtocolIPv6ICMP && psh != nil { b = append(psh, b...) } if m.Body != nil && m.Body.Len(m.Type.Protocol()) != 0 { mb, err := m.Body.Marshal(m.Type.Protocol()) if err != nil { return nil, err } b = append(b, mb...) } if m.Type.Protocol() == iana.ProtocolIPv6ICMP { if psh == nil { // cannot calculate checksum here return b, nil } off, l := 2*net.IPv6len, len(b)-len(psh) binary.BigEndian.PutUint32(b[off:off+4], uint32(l)) } s := checksum(b) // Place checksum back in header; using ^= avoids the // assumption the checksum bytes are zero. b[len(psh)+2] ^= byte(s) b[len(psh)+3] ^= byte(s >> 8) return b[len(psh):], nil } var parseFns = map[Type]func(int, []byte) (MessageBody, error){ ipv4.ICMPTypeDestinationUnreachable: parseDstUnreach, ipv4.ICMPTypeTimeExceeded: parseTimeExceeded, ipv4.ICMPTypeParameterProblem: parseParamProb, ipv4.ICMPTypeEcho: parseEcho, ipv4.ICMPTypeEchoReply: parseEcho, ipv6.ICMPTypeDestinationUnreachable: parseDstUnreach, ipv6.ICMPTypePacketTooBig: parsePacketTooBig, ipv6.ICMPTypeTimeExceeded: parseTimeExceeded, ipv6.ICMPTypeParameterProblem: parseParamProb, ipv6.ICMPTypeEchoRequest: parseEcho, ipv6.ICMPTypeEchoReply: parseEcho, } // ParseMessage parses b as an ICMP message. // Proto must be either the ICMPv4 or ICMPv6 protocol number. func ParseMessage(proto int, b []byte) (*Message, error) { if len(b) < 4 { return nil, errMessageTooShort } var err error m := &Message{Code: int(b[1]), Checksum: int(binary.BigEndian.Uint16(b[2:4]))} switch proto { case iana.ProtocolICMP: m.Type = ipv4.ICMPType(b[0]) case iana.ProtocolIPv6ICMP: m.Type = ipv6.ICMPType(b[0]) default: return nil, syscall.EINVAL } if fn, ok := parseFns[m.Type]; !ok { m.Body, err = parseDefaultMessageBody(proto, b[4:]) } else { m.Body, err = fn(proto, b[4:]) } if err != nil { return nil, err } return m, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/listen_stub.go0000644061062106075000000000214113172163402024123 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build nacl plan9 package icmp // ListenPacket listens for incoming ICMP packets addressed to // address. See net.Dial for the syntax of address. // // For non-privileged datagram-oriented ICMP endpoints, network must // be "udp4" or "udp6". The endpoint allows to read, write a few // limited ICMP messages such as echo request and echo reply. // Currently only Darwin and Linux support this. // // Examples: // ListenPacket("udp4", "192.168.0.1") // ListenPacket("udp4", "0.0.0.0") // ListenPacket("udp6", "fe80::1%en0") // ListenPacket("udp6", "::") // // For privileged raw ICMP endpoints, network must be "ip4" or "ip6" // followed by a colon and an ICMP protocol number or name. // // Examples: // ListenPacket("ip4:icmp", "192.168.0.1") // ListenPacket("ip4:1", "0.0.0.0") // ListenPacket("ip6:ipv6-icmp", "fe80::1%en0") // ListenPacket("ip6:58", "::") func ListenPacket(network, address string) (*PacketConn, error) { return nil, errOpNoSupport } lxd-2.0.11/dist/src/golang.org/x/net/icmp/listen_posix.go0000644061062106075000000000535713172163402024324 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package icmp import ( "net" "os" "runtime" "syscall" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) const sysIP_STRIPHDR = 0x17 // for now only darwin supports this option // ListenPacket listens for incoming ICMP packets addressed to // address. See net.Dial for the syntax of address. // // For non-privileged datagram-oriented ICMP endpoints, network must // be "udp4" or "udp6". The endpoint allows to read, write a few // limited ICMP messages such as echo request and echo reply. // Currently only Darwin and Linux support this. // // Examples: // ListenPacket("udp4", "192.168.0.1") // ListenPacket("udp4", "0.0.0.0") // ListenPacket("udp6", "fe80::1%en0") // ListenPacket("udp6", "::") // // For privileged raw ICMP endpoints, network must be "ip4" or "ip6" // followed by a colon and an ICMP protocol number or name. // // Examples: // ListenPacket("ip4:icmp", "192.168.0.1") // ListenPacket("ip4:1", "0.0.0.0") // ListenPacket("ip6:ipv6-icmp", "fe80::1%en0") // ListenPacket("ip6:58", "::") func ListenPacket(network, address string) (*PacketConn, error) { var family, proto int switch network { case "udp4": family, proto = syscall.AF_INET, iana.ProtocolICMP case "udp6": family, proto = syscall.AF_INET6, iana.ProtocolIPv6ICMP default: i := last(network, ':') switch network[:i] { case "ip4": proto = iana.ProtocolICMP case "ip6": proto = iana.ProtocolIPv6ICMP } } var cerr error var c net.PacketConn switch family { case syscall.AF_INET, syscall.AF_INET6: s, err := syscall.Socket(family, syscall.SOCK_DGRAM, proto) if err != nil { return nil, os.NewSyscallError("socket", err) } if runtime.GOOS == "darwin" && family == syscall.AF_INET { if err := syscall.SetsockoptInt(s, iana.ProtocolIP, sysIP_STRIPHDR, 1); err != nil { syscall.Close(s) return nil, os.NewSyscallError("setsockopt", err) } } sa, err := sockaddr(family, address) if err != nil { syscall.Close(s) return nil, err } if err := syscall.Bind(s, sa); err != nil { syscall.Close(s) return nil, os.NewSyscallError("bind", err) } f := os.NewFile(uintptr(s), "datagram-oriented icmp") c, cerr = net.FilePacketConn(f) f.Close() default: c, cerr = net.ListenPacket(network, address) } if cerr != nil { return nil, cerr } switch proto { case iana.ProtocolICMP: return &PacketConn{c: c, p4: ipv4.NewPacketConn(c)}, nil case iana.ProtocolIPv6ICMP: return &PacketConn{c: c, p6: ipv6.NewPacketConn(c)}, nil default: return &PacketConn{c: c}, nil } } lxd-2.0.11/dist/src/golang.org/x/net/icmp/ipv6.go0000644061062106075000000000105113172163402022453 0ustar stgraberdomain admins// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "net" "golang.org/x/net/internal/iana" ) const ipv6PseudoHeaderLen = 2*net.IPv6len + 8 // IPv6PseudoHeader returns an IPv6 pseudo header for checksum // calculation. func IPv6PseudoHeader(src, dst net.IP) []byte { b := make([]byte, ipv6PseudoHeaderLen) copy(b, src.To16()) copy(b[net.IPv6len:], dst.To16()) b[len(b)-1] = byte(iana.ProtocolIPv6ICMP) return b } lxd-2.0.11/dist/src/golang.org/x/net/icmp/ipv4_test.go0000644061062106075000000000356213172163402023521 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "encoding/binary" "net" "reflect" "runtime" "testing" "golang.org/x/net/internal/socket" "golang.org/x/net/ipv4" ) type ipv4HeaderTest struct { wireHeaderFromKernel [ipv4.HeaderLen]byte wireHeaderFromTradBSDKernel [ipv4.HeaderLen]byte Header *ipv4.Header } var ipv4HeaderLittleEndianTest = ipv4HeaderTest{ // TODO(mikio): Add platform dependent wire header formats when // we support new platforms. wireHeaderFromKernel: [ipv4.HeaderLen]byte{ 0x45, 0x01, 0xbe, 0xef, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, }, wireHeaderFromTradBSDKernel: [ipv4.HeaderLen]byte{ 0x45, 0x01, 0xef, 0xbe, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, }, Header: &ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TOS: 1, TotalLen: 0xbeef, ID: 0xcafe, Flags: ipv4.DontFragment, FragOff: 1500, TTL: 255, Protocol: 1, Checksum: 0xdead, Src: net.IPv4(172, 16, 254, 254), Dst: net.IPv4(192, 168, 0, 1), }, } func TestParseIPv4Header(t *testing.T) { tt := &ipv4HeaderLittleEndianTest if socket.NativeEndian != binary.LittleEndian { t.Skip("no test for non-little endian machine yet") } var wh []byte switch runtime.GOOS { case "darwin": wh = tt.wireHeaderFromTradBSDKernel[:] case "freebsd": if freebsdVersion >= 1000000 { wh = tt.wireHeaderFromKernel[:] } else { wh = tt.wireHeaderFromTradBSDKernel[:] } default: wh = tt.wireHeaderFromKernel[:] } h, err := ParseIPv4Header(wh) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(h, tt.Header) { t.Fatalf("got %#v; want %#v", h, tt.Header) } } lxd-2.0.11/dist/src/golang.org/x/net/icmp/ipv4.go0000644061062106075000000000327613172163402022464 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "encoding/binary" "net" "runtime" "golang.org/x/net/internal/socket" "golang.org/x/net/ipv4" ) // freebsdVersion is set in sys_freebsd.go. // See http://www.freebsd.org/doc/en/books/porters-handbook/freebsd-versions.html. var freebsdVersion uint32 // ParseIPv4Header parses b as an IPv4 header of ICMP error message // invoking packet, which is contained in ICMP error message. func ParseIPv4Header(b []byte) (*ipv4.Header, error) { if len(b) < ipv4.HeaderLen { return nil, errHeaderTooShort } hdrlen := int(b[0]&0x0f) << 2 if hdrlen > len(b) { return nil, errBufferTooShort } h := &ipv4.Header{ Version: int(b[0] >> 4), Len: hdrlen, TOS: int(b[1]), ID: int(binary.BigEndian.Uint16(b[4:6])), FragOff: int(binary.BigEndian.Uint16(b[6:8])), TTL: int(b[8]), Protocol: int(b[9]), Checksum: int(binary.BigEndian.Uint16(b[10:12])), Src: net.IPv4(b[12], b[13], b[14], b[15]), Dst: net.IPv4(b[16], b[17], b[18], b[19]), } switch runtime.GOOS { case "darwin": h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4])) case "freebsd": if freebsdVersion >= 1000000 { h.TotalLen = int(binary.BigEndian.Uint16(b[2:4])) } else { h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4])) } default: h.TotalLen = int(binary.BigEndian.Uint16(b[2:4])) } h.Flags = ipv4.HeaderFlags(h.FragOff&0xe000) >> 13 h.FragOff = h.FragOff & 0x1fff if hdrlen-ipv4.HeaderLen > 0 { h.Options = make([]byte, hdrlen-ipv4.HeaderLen) copy(h.Options, b[ipv4.HeaderLen:]) } return h, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/interface.go0000644061062106075000000001272213172163402023536 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "encoding/binary" "net" "strings" "golang.org/x/net/internal/iana" ) const ( classInterfaceInfo = 2 afiIPv4 = 1 afiIPv6 = 2 ) const ( attrMTU = 1 << iota attrName attrIPAddr attrIfIndex ) // An InterfaceInfo represents interface and next-hop identification. type InterfaceInfo struct { Class int // extension object class number Type int // extension object sub-type Interface *net.Interface Addr *net.IPAddr } func (ifi *InterfaceInfo) nameLen() int { if len(ifi.Interface.Name) > 63 { return 64 } l := 1 + len(ifi.Interface.Name) return (l + 3) &^ 3 } func (ifi *InterfaceInfo) attrsAndLen(proto int) (attrs, l int) { l = 4 if ifi.Interface != nil && ifi.Interface.Index > 0 { attrs |= attrIfIndex l += 4 if len(ifi.Interface.Name) > 0 { attrs |= attrName l += ifi.nameLen() } if ifi.Interface.MTU > 0 { attrs |= attrMTU l += 4 } } if ifi.Addr != nil { switch proto { case iana.ProtocolICMP: if ifi.Addr.IP.To4() != nil { attrs |= attrIPAddr l += 4 + net.IPv4len } case iana.ProtocolIPv6ICMP: if ifi.Addr.IP.To16() != nil && ifi.Addr.IP.To4() == nil { attrs |= attrIPAddr l += 4 + net.IPv6len } } } return } // Len implements the Len method of Extension interface. func (ifi *InterfaceInfo) Len(proto int) int { _, l := ifi.attrsAndLen(proto) return l } // Marshal implements the Marshal method of Extension interface. func (ifi *InterfaceInfo) Marshal(proto int) ([]byte, error) { attrs, l := ifi.attrsAndLen(proto) b := make([]byte, l) if err := ifi.marshal(proto, b, attrs, l); err != nil { return nil, err } return b, nil } func (ifi *InterfaceInfo) marshal(proto int, b []byte, attrs, l int) error { binary.BigEndian.PutUint16(b[:2], uint16(l)) b[2], b[3] = classInterfaceInfo, byte(ifi.Type) for b = b[4:]; len(b) > 0 && attrs != 0; { switch { case attrs&attrIfIndex != 0: b = ifi.marshalIfIndex(proto, b) attrs &^= attrIfIndex case attrs&attrIPAddr != 0: b = ifi.marshalIPAddr(proto, b) attrs &^= attrIPAddr case attrs&attrName != 0: b = ifi.marshalName(proto, b) attrs &^= attrName case attrs&attrMTU != 0: b = ifi.marshalMTU(proto, b) attrs &^= attrMTU } } return nil } func (ifi *InterfaceInfo) marshalIfIndex(proto int, b []byte) []byte { binary.BigEndian.PutUint32(b[:4], uint32(ifi.Interface.Index)) return b[4:] } func (ifi *InterfaceInfo) parseIfIndex(b []byte) ([]byte, error) { if len(b) < 4 { return nil, errMessageTooShort } ifi.Interface.Index = int(binary.BigEndian.Uint32(b[:4])) return b[4:], nil } func (ifi *InterfaceInfo) marshalIPAddr(proto int, b []byte) []byte { switch proto { case iana.ProtocolICMP: binary.BigEndian.PutUint16(b[:2], uint16(afiIPv4)) copy(b[4:4+net.IPv4len], ifi.Addr.IP.To4()) b = b[4+net.IPv4len:] case iana.ProtocolIPv6ICMP: binary.BigEndian.PutUint16(b[:2], uint16(afiIPv6)) copy(b[4:4+net.IPv6len], ifi.Addr.IP.To16()) b = b[4+net.IPv6len:] } return b } func (ifi *InterfaceInfo) parseIPAddr(b []byte) ([]byte, error) { if len(b) < 4 { return nil, errMessageTooShort } afi := int(binary.BigEndian.Uint16(b[:2])) b = b[4:] switch afi { case afiIPv4: if len(b) < net.IPv4len { return nil, errMessageTooShort } ifi.Addr.IP = make(net.IP, net.IPv4len) copy(ifi.Addr.IP, b[:net.IPv4len]) b = b[net.IPv4len:] case afiIPv6: if len(b) < net.IPv6len { return nil, errMessageTooShort } ifi.Addr.IP = make(net.IP, net.IPv6len) copy(ifi.Addr.IP, b[:net.IPv6len]) b = b[net.IPv6len:] } return b, nil } func (ifi *InterfaceInfo) marshalName(proto int, b []byte) []byte { l := byte(ifi.nameLen()) b[0] = l copy(b[1:], []byte(ifi.Interface.Name)) return b[l:] } func (ifi *InterfaceInfo) parseName(b []byte) ([]byte, error) { if 4 > len(b) || len(b) < int(b[0]) { return nil, errMessageTooShort } l := int(b[0]) if l%4 != 0 || 4 > l || l > 64 { return nil, errInvalidExtension } var name [63]byte copy(name[:], b[1:l]) ifi.Interface.Name = strings.Trim(string(name[:]), "\000") return b[l:], nil } func (ifi *InterfaceInfo) marshalMTU(proto int, b []byte) []byte { binary.BigEndian.PutUint32(b[:4], uint32(ifi.Interface.MTU)) return b[4:] } func (ifi *InterfaceInfo) parseMTU(b []byte) ([]byte, error) { if len(b) < 4 { return nil, errMessageTooShort } ifi.Interface.MTU = int(binary.BigEndian.Uint32(b[:4])) return b[4:], nil } func parseInterfaceInfo(b []byte) (Extension, error) { ifi := &InterfaceInfo{ Class: int(b[2]), Type: int(b[3]), } if ifi.Type&(attrIfIndex|attrName|attrMTU) != 0 { ifi.Interface = &net.Interface{} } if ifi.Type&attrIPAddr != 0 { ifi.Addr = &net.IPAddr{} } attrs := ifi.Type & (attrIfIndex | attrIPAddr | attrName | attrMTU) for b = b[4:]; len(b) > 0 && attrs != 0; { var err error switch { case attrs&attrIfIndex != 0: b, err = ifi.parseIfIndex(b) attrs &^= attrIfIndex case attrs&attrIPAddr != 0: b, err = ifi.parseIPAddr(b) attrs &^= attrIPAddr case attrs&attrName != 0: b, err = ifi.parseName(b) attrs &^= attrName case attrs&attrMTU != 0: b, err = ifi.parseMTU(b) attrs &^= attrMTU } if err != nil { return nil, err } } if ifi.Interface != nil && ifi.Interface.Name != "" && ifi.Addr != nil && ifi.Addr.IP.To16() != nil && ifi.Addr.IP.To4() == nil { ifi.Addr.Zone = ifi.Interface.Name } return ifi, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/helper_posix.go0000644061062106075000000000306613172163402024300 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris windows package icmp import ( "net" "strconv" "syscall" ) func sockaddr(family int, address string) (syscall.Sockaddr, error) { switch family { case syscall.AF_INET: a, err := net.ResolveIPAddr("ip4", address) if err != nil { return nil, err } if len(a.IP) == 0 { a.IP = net.IPv4zero } if a.IP = a.IP.To4(); a.IP == nil { return nil, net.InvalidAddrError("non-ipv4 address") } sa := &syscall.SockaddrInet4{} copy(sa.Addr[:], a.IP) return sa, nil case syscall.AF_INET6: a, err := net.ResolveIPAddr("ip6", address) if err != nil { return nil, err } if len(a.IP) == 0 { a.IP = net.IPv6unspecified } if a.IP.Equal(net.IPv4zero) { a.IP = net.IPv6unspecified } if a.IP = a.IP.To16(); a.IP == nil || a.IP.To4() != nil { return nil, net.InvalidAddrError("non-ipv6 address") } sa := &syscall.SockaddrInet6{ZoneId: zoneToUint32(a.Zone)} copy(sa.Addr[:], a.IP) return sa, nil default: return nil, net.InvalidAddrError("unexpected family") } } func zoneToUint32(zone string) uint32 { if zone == "" { return 0 } if ifi, err := net.InterfaceByName(zone); err == nil { return uint32(ifi.Index) } n, err := strconv.Atoi(zone) if err != nil { return 0 } return uint32(n) } func last(s string, b byte) int { i := len(s) for i--; i >= 0; i-- { if s[i] == b { break } } return i } lxd-2.0.11/dist/src/golang.org/x/net/icmp/extension_test.go0000644061062106075000000001342013172163402024645 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "net" "reflect" "testing" "golang.org/x/net/internal/iana" ) var marshalAndParseExtensionTests = []struct { proto int hdr []byte obj []byte exts []Extension }{ // MPLS label stack with no label { proto: iana.ProtocolICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x04, 0x01, 0x01, }, exts: []Extension{ &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, }, }, }, // MPLS label stack with a single label { proto: iana.ProtocolIPv6ICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x08, 0x01, 0x01, 0x03, 0xe8, 0xe9, 0xff, }, exts: []Extension{ &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, Labels: []MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, }, }, // MPLS label stack with multiple labels { proto: iana.ProtocolICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x0c, 0x01, 0x01, 0x03, 0xe8, 0xde, 0xfe, 0x03, 0xe8, 0xe1, 0xff, }, exts: []Extension{ &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, Labels: []MPLSLabel{ { Label: 16013, TC: 0x7, S: false, TTL: 254, }, { Label: 16014, TC: 0, S: true, TTL: 255, }, }, }, }, }, // Interface information with no attribute { proto: iana.ProtocolICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x04, 0x02, 0x00, }, exts: []Extension{ &InterfaceInfo{ Class: classInterfaceInfo, }, }, }, // Interface information with ifIndex and name { proto: iana.ProtocolICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x10, 0x02, 0x0a, 0x00, 0x00, 0x00, 0x10, 0x08, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, }, exts: []Extension{ &InterfaceInfo{ Class: classInterfaceInfo, Type: 0x0a, Interface: &net.Interface{ Index: 16, Name: "en101", }, }, }, }, // Interface information with ifIndex, IPAddr, name and MTU { proto: iana.ProtocolIPv6ICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x28, 0x02, 0x0f, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x02, 0x00, 0x00, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, }, exts: []Extension{ &InterfaceInfo{ Class: classInterfaceInfo, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en101", }, }, }, }, } func TestMarshalAndParseExtension(t *testing.T) { for i, tt := range marshalAndParseExtensionTests { for j, ext := range tt.exts { var err error var b []byte switch ext := ext.(type) { case *MPLSLabelStack: b, err = ext.Marshal(tt.proto) if err != nil { t.Errorf("#%v/%v: %v", i, j, err) continue } case *InterfaceInfo: b, err = ext.Marshal(tt.proto) if err != nil { t.Errorf("#%v/%v: %v", i, j, err) continue } } if !reflect.DeepEqual(b, tt.obj) { t.Errorf("#%v/%v: got %#v; want %#v", i, j, b, tt.obj) continue } } for j, wire := range []struct { data []byte // original datagram inlattr int // length of padded original datagram, a hint outlattr int // length of padded original datagram, a want err error }{ {nil, 0, -1, errNoExtension}, {make([]byte, 127), 128, -1, errNoExtension}, {make([]byte, 128), 127, -1, errNoExtension}, {make([]byte, 128), 128, -1, errNoExtension}, {make([]byte, 128), 129, -1, errNoExtension}, {append(make([]byte, 128), append(tt.hdr, tt.obj...)...), 127, 128, nil}, {append(make([]byte, 128), append(tt.hdr, tt.obj...)...), 128, 128, nil}, {append(make([]byte, 128), append(tt.hdr, tt.obj...)...), 129, 128, nil}, {append(make([]byte, 512), append(tt.hdr, tt.obj...)...), 511, -1, errNoExtension}, {append(make([]byte, 512), append(tt.hdr, tt.obj...)...), 512, 512, nil}, {append(make([]byte, 512), append(tt.hdr, tt.obj...)...), 513, -1, errNoExtension}, } { exts, l, err := parseExtensions(wire.data, wire.inlattr) if err != wire.err { t.Errorf("#%v/%v: got %v; want %v", i, j, err, wire.err) continue } if wire.err != nil { continue } if l != wire.outlattr { t.Errorf("#%v/%v: got %v; want %v", i, j, l, wire.outlattr) } if !reflect.DeepEqual(exts, tt.exts) { for j, ext := range exts { switch ext := ext.(type) { case *MPLSLabelStack: want := tt.exts[j].(*MPLSLabelStack) t.Errorf("#%v/%v: got %#v; want %#v", i, j, ext, want) case *InterfaceInfo: want := tt.exts[j].(*InterfaceInfo) t.Errorf("#%v/%v: got %#v; want %#v", i, j, ext, want) } } continue } } } } var parseInterfaceNameTests = []struct { b []byte error }{ {[]byte{0, 'e', 'n', '0'}, errInvalidExtension}, {[]byte{4, 'e', 'n', '0'}, nil}, {[]byte{7, 'e', 'n', '0', 0xff, 0xff, 0xff, 0xff}, errInvalidExtension}, {[]byte{8, 'e', 'n', '0', 0xff, 0xff, 0xff}, errMessageTooShort}, } func TestParseInterfaceName(t *testing.T) { ifi := InterfaceInfo{Interface: &net.Interface{}} for i, tt := range parseInterfaceNameTests { if _, err := ifi.parseName(tt.b); err != tt.error { t.Errorf("#%d: got %v; want %v", i, err, tt.error) } } } lxd-2.0.11/dist/src/golang.org/x/net/icmp/extension.go0000644061062106075000000000442713172163402023615 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import "encoding/binary" // An Extension represents an ICMP extension. type Extension interface { // Len returns the length of ICMP extension. // Proto must be either the ICMPv4 or ICMPv6 protocol number. Len(proto int) int // Marshal returns the binary encoding of ICMP extension. // Proto must be either the ICMPv4 or ICMPv6 protocol number. Marshal(proto int) ([]byte, error) } const extensionVersion = 2 func validExtensionHeader(b []byte) bool { v := int(b[0]&0xf0) >> 4 s := binary.BigEndian.Uint16(b[2:4]) if s != 0 { s = checksum(b) } if v != extensionVersion || s != 0 { return false } return true } // parseExtensions parses b as a list of ICMP extensions. // The length attribute l must be the length attribute field in // received icmp messages. // // It will return a list of ICMP extensions and an adjusted length // attribute that represents the length of the padded original // datagram field. Otherwise, it returns an error. func parseExtensions(b []byte, l int) ([]Extension, int, error) { // Still a lot of non-RFC 4884 compliant implementations are // out there. Set the length attribute l to 128 when it looks // inappropriate for backwards compatibility. // // A minimal extension at least requires 8 octets; 4 octets // for an extension header, and 4 octets for a single object // header. // // See RFC 4884 for further information. if 128 > l || l+8 > len(b) { l = 128 } if l+8 > len(b) { return nil, -1, errNoExtension } if !validExtensionHeader(b[l:]) { if l == 128 { return nil, -1, errNoExtension } l = 128 if !validExtensionHeader(b[l:]) { return nil, -1, errNoExtension } } var exts []Extension for b = b[l+4:]; len(b) >= 4; { ol := int(binary.BigEndian.Uint16(b[:2])) if 4 > ol || ol > len(b) { break } switch b[2] { case classMPLSLabelStack: ext, err := parseMPLSLabelStack(b[:ol]) if err != nil { return nil, -1, err } exts = append(exts, ext) case classInterfaceInfo: ext, err := parseInterfaceInfo(b[:ol]) if err != nil { return nil, -1, err } exts = append(exts, ext) } b = b[ol:] } return exts, l, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/example_test.go0000644061062106075000000000243413172163402024267 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp_test import ( "log" "net" "os" "runtime" "golang.org/x/net/icmp" "golang.org/x/net/ipv6" ) func ExamplePacketConn_nonPrivilegedPing() { switch runtime.GOOS { case "darwin": case "linux": log.Println("you may need to adjust the net.ipv4.ping_group_range kernel state") default: log.Println("not supported on", runtime.GOOS) return } c, err := icmp.ListenPacket("udp6", "fe80::1%en0") if err != nil { log.Fatal(err) } defer c.Close() wm := icmp.Message{ Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: 1, Data: []byte("HELLO-R-U-THERE"), }, } wb, err := wm.Marshal(nil) if err != nil { log.Fatal(err) } if _, err := c.WriteTo(wb, &net.UDPAddr{IP: net.ParseIP("ff02::1"), Zone: "en0"}); err != nil { log.Fatal(err) } rb := make([]byte, 1500) n, peer, err := c.ReadFrom(rb) if err != nil { log.Fatal(err) } rm, err := icmp.ParseMessage(58, rb[:n]) if err != nil { log.Fatal(err) } switch rm.Type { case ipv6.ICMPTypeEchoReply: log.Printf("got reflection from %v", peer) default: log.Printf("got %+v; want echo reply", rm) } } lxd-2.0.11/dist/src/golang.org/x/net/icmp/endpoint.go0000644061062106075000000000517113172163402023416 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "net" "runtime" "syscall" "time" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) var _ net.PacketConn = &PacketConn{} // A PacketConn represents a packet network endpoint that uses either // ICMPv4 or ICMPv6. type PacketConn struct { c net.PacketConn p4 *ipv4.PacketConn p6 *ipv6.PacketConn } func (c *PacketConn) ok() bool { return c != nil && c.c != nil } // IPv4PacketConn returns the ipv4.PacketConn of c. // It returns nil when c is not created as the endpoint for ICMPv4. func (c *PacketConn) IPv4PacketConn() *ipv4.PacketConn { if !c.ok() { return nil } return c.p4 } // IPv6PacketConn returns the ipv6.PacketConn of c. // It returns nil when c is not created as the endpoint for ICMPv6. func (c *PacketConn) IPv6PacketConn() *ipv6.PacketConn { if !c.ok() { return nil } return c.p6 } // ReadFrom reads an ICMP message from the connection. func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) { if !c.ok() { return 0, nil, syscall.EINVAL } // Please be informed that ipv4.NewPacketConn enables // IP_STRIPHDR option by default on Darwin. // See golang.org/issue/9395 for further information. if runtime.GOOS == "darwin" && c.p4 != nil { n, _, peer, err := c.p4.ReadFrom(b) return n, peer, err } return c.c.ReadFrom(b) } // WriteTo writes the ICMP message b to dst. // Dst must be net.UDPAddr when c is a non-privileged // datagram-oriented ICMP endpoint. Otherwise it must be net.IPAddr. func (c *PacketConn) WriteTo(b []byte, dst net.Addr) (int, error) { if !c.ok() { return 0, syscall.EINVAL } return c.c.WriteTo(b, dst) } // Close closes the endpoint. func (c *PacketConn) Close() error { if !c.ok() { return syscall.EINVAL } return c.c.Close() } // LocalAddr returns the local network address. func (c *PacketConn) LocalAddr() net.Addr { if !c.ok() { return nil } return c.c.LocalAddr() } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *PacketConn) SetDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *PacketConn) SetReadDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *PacketConn) SetWriteDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetWriteDeadline(t) } lxd-2.0.11/dist/src/golang.org/x/net/icmp/echo.go0000644061062106075000000000226313172163402022513 0ustar stgraberdomain admins// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import "encoding/binary" // An Echo represents an ICMP echo request or reply message body. type Echo struct { ID int // identifier Seq int // sequence number Data []byte // data } // Len implements the Len method of MessageBody interface. func (p *Echo) Len(proto int) int { if p == nil { return 0 } return 4 + len(p.Data) } // Marshal implements the Marshal method of MessageBody interface. func (p *Echo) Marshal(proto int) ([]byte, error) { b := make([]byte, 4+len(p.Data)) binary.BigEndian.PutUint16(b[:2], uint16(p.ID)) binary.BigEndian.PutUint16(b[2:4], uint16(p.Seq)) copy(b[4:], p.Data) return b, nil } // parseEcho parses b as an ICMP echo request or reply message body. func parseEcho(proto int, b []byte) (MessageBody, error) { bodyLen := len(b) if bodyLen < 4 { return nil, errMessageTooShort } p := &Echo{ID: int(binary.BigEndian.Uint16(b[:2])), Seq: int(binary.BigEndian.Uint16(b[2:4]))} if bodyLen > 4 { p.Data = make([]byte, bodyLen-4) copy(p.Data, b[4:]) } return p, nil } lxd-2.0.11/dist/src/golang.org/x/net/icmp/dstunreach.go0000644061062106075000000000216513172163402023736 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp // A DstUnreach represents an ICMP destination unreachable message // body. type DstUnreach struct { Data []byte // data, known as original datagram field Extensions []Extension // extensions } // Len implements the Len method of MessageBody interface. func (p *DstUnreach) Len(proto int) int { if p == nil { return 0 } l, _ := multipartMessageBodyDataLen(proto, p.Data, p.Extensions) return 4 + l } // Marshal implements the Marshal method of MessageBody interface. func (p *DstUnreach) Marshal(proto int) ([]byte, error) { return marshalMultipartMessageBody(proto, p.Data, p.Extensions) } // parseDstUnreach parses b as an ICMP destination unreachable message // body. func parseDstUnreach(proto int, b []byte) (MessageBody, error) { if len(b) < 4 { return nil, errMessageTooShort } p := &DstUnreach{} var err error p.Data, p.Extensions, err = parseMultipartMessageBody(proto, b) if err != nil { return nil, err } return p, nil } lxd-2.0.11/dist/src/golang.org/x/net/http2/0000755061062106075000000000000013172163402021354 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/http2/z_spec_test.go0000644061062106075000000001642313172163402024233 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bytes" "encoding/xml" "flag" "fmt" "io" "os" "reflect" "regexp" "sort" "strconv" "strings" "sync" "testing" ) var coverSpec = flag.Bool("coverspec", false, "Run spec coverage tests") // The global map of sentence coverage for the http2 spec. var defaultSpecCoverage specCoverage var loadSpecOnce sync.Once func loadSpec() { if f, err := os.Open("testdata/draft-ietf-httpbis-http2.xml"); err != nil { panic(err) } else { defaultSpecCoverage = readSpecCov(f) f.Close() } } // covers marks all sentences for section sec in defaultSpecCoverage. Sentences not // "covered" will be included in report outputted by TestSpecCoverage. func covers(sec, sentences string) { loadSpecOnce.Do(loadSpec) defaultSpecCoverage.cover(sec, sentences) } type specPart struct { section string sentence string } func (ss specPart) Less(oo specPart) bool { atoi := func(s string) int { n, err := strconv.Atoi(s) if err != nil { panic(err) } return n } a := strings.Split(ss.section, ".") b := strings.Split(oo.section, ".") for len(a) > 0 { if len(b) == 0 { return false } x, y := atoi(a[0]), atoi(b[0]) if x == y { a, b = a[1:], b[1:] continue } return x < y } if len(b) > 0 { return true } return false } type bySpecSection []specPart func (a bySpecSection) Len() int { return len(a) } func (a bySpecSection) Less(i, j int) bool { return a[i].Less(a[j]) } func (a bySpecSection) Swap(i, j int) { a[i], a[j] = a[j], a[i] } type specCoverage struct { coverage map[specPart]bool d *xml.Decoder } func joinSection(sec []int) string { s := fmt.Sprintf("%d", sec[0]) for _, n := range sec[1:] { s = fmt.Sprintf("%s.%d", s, n) } return s } func (sc specCoverage) readSection(sec []int) { var ( buf = new(bytes.Buffer) sub = 0 ) for { tk, err := sc.d.Token() if err != nil { if err == io.EOF { return } panic(err) } switch v := tk.(type) { case xml.StartElement: if skipElement(v) { if err := sc.d.Skip(); err != nil { panic(err) } if v.Name.Local == "section" { sub++ } break } switch v.Name.Local { case "section": sub++ sc.readSection(append(sec, sub)) case "xref": buf.Write(sc.readXRef(v)) } case xml.CharData: if len(sec) == 0 { break } buf.Write(v) case xml.EndElement: if v.Name.Local == "section" { sc.addSentences(joinSection(sec), buf.String()) return } } } } func (sc specCoverage) readXRef(se xml.StartElement) []byte { var b []byte for { tk, err := sc.d.Token() if err != nil { panic(err) } switch v := tk.(type) { case xml.CharData: if b != nil { panic("unexpected CharData") } b = []byte(string(v)) case xml.EndElement: if v.Name.Local != "xref" { panic("expected ") } if b != nil { return b } sig := attrSig(se) switch sig { case "target": return []byte(fmt.Sprintf("[%s]", attrValue(se, "target"))) case "fmt-of,rel,target", "fmt-,,rel,target": return []byte(fmt.Sprintf("[%s, %s]", attrValue(se, "target"), attrValue(se, "rel"))) case "fmt-of,sec,target", "fmt-,,sec,target": return []byte(fmt.Sprintf("[section %s of %s]", attrValue(se, "sec"), attrValue(se, "target"))) case "fmt-of,rel,sec,target": return []byte(fmt.Sprintf("[section %s of %s, %s]", attrValue(se, "sec"), attrValue(se, "target"), attrValue(se, "rel"))) default: panic(fmt.Sprintf("unknown attribute signature %q in %#v", sig, fmt.Sprintf("%#v", se))) } default: panic(fmt.Sprintf("unexpected tag %q", v)) } } } var skipAnchor = map[string]bool{ "intro": true, "Overview": true, } var skipTitle = map[string]bool{ "Acknowledgements": true, "Change Log": true, "Document Organization": true, "Conventions and Terminology": true, } func skipElement(s xml.StartElement) bool { switch s.Name.Local { case "artwork": return true case "section": for _, attr := range s.Attr { switch attr.Name.Local { case "anchor": if skipAnchor[attr.Value] || strings.HasPrefix(attr.Value, "changes.since.") { return true } case "title": if skipTitle[attr.Value] { return true } } } } return false } func readSpecCov(r io.Reader) specCoverage { sc := specCoverage{ coverage: map[specPart]bool{}, d: xml.NewDecoder(r)} sc.readSection(nil) return sc } func (sc specCoverage) addSentences(sec string, sentence string) { for _, s := range parseSentences(sentence) { sc.coverage[specPart{sec, s}] = false } } func (sc specCoverage) cover(sec string, sentence string) { for _, s := range parseSentences(sentence) { p := specPart{sec, s} if _, ok := sc.coverage[p]; !ok { panic(fmt.Sprintf("Not found in spec: %q, %q", sec, s)) } sc.coverage[specPart{sec, s}] = true } } var whitespaceRx = regexp.MustCompile(`\s+`) func parseSentences(sens string) []string { sens = strings.TrimSpace(sens) if sens == "" { return nil } ss := strings.Split(whitespaceRx.ReplaceAllString(sens, " "), ". ") for i, s := range ss { s = strings.TrimSpace(s) if !strings.HasSuffix(s, ".") { s += "." } ss[i] = s } return ss } func TestSpecParseSentences(t *testing.T) { tests := []struct { ss string want []string }{ {"Sentence 1. Sentence 2.", []string{ "Sentence 1.", "Sentence 2.", }}, {"Sentence 1. \nSentence 2.\tSentence 3.", []string{ "Sentence 1.", "Sentence 2.", "Sentence 3.", }}, } for i, tt := range tests { got := parseSentences(tt.ss) if !reflect.DeepEqual(got, tt.want) { t.Errorf("%d: got = %q, want %q", i, got, tt.want) } } } func TestSpecCoverage(t *testing.T) { if !*coverSpec { t.Skip() } loadSpecOnce.Do(loadSpec) var ( list []specPart cv = defaultSpecCoverage.coverage total = len(cv) complete = 0 ) for sp, touched := range defaultSpecCoverage.coverage { if touched { complete++ } else { list = append(list, sp) } } sort.Stable(bySpecSection(list)) if testing.Short() && len(list) > 5 { list = list[:5] } for _, p := range list { t.Errorf("\tSECTION %s: %s", p.section, p.sentence) } t.Logf("%d/%d (%d%%) sentences covered", complete, total, (complete/total)*100) } func attrSig(se xml.StartElement) string { var names []string for _, attr := range se.Attr { if attr.Name.Local == "fmt" { names = append(names, "fmt-"+attr.Value) } else { names = append(names, attr.Name.Local) } } sort.Strings(names) return strings.Join(names, ",") } func attrValue(se xml.StartElement, attr string) string { for _, a := range se.Attr { if a.Name.Local == attr { return a.Value } } panic("unknown attribute " + attr) } func TestSpecPartLess(t *testing.T) { tests := []struct { sec1, sec2 string want bool }{ {"6.2.1", "6.2", false}, {"6.2", "6.2.1", true}, {"6.10", "6.10.1", true}, {"6.10", "6.1.1", false}, // 10, not 1 {"6.1", "6.1", false}, // equal, so not less } for _, tt := range tests { got := (specPart{tt.sec1, "foo"}).Less(specPart{tt.sec2, "foo"}) if got != tt.want { t.Errorf("Less(%q, %q) = %v; want %v", tt.sec1, tt.sec2, got, tt.want) } } } lxd-2.0.11/dist/src/golang.org/x/net/http2/writesched_test.go0000644061062106075000000000654613172163402025116 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "fmt" "math" "reflect" "testing" ) func makeWriteNonStreamRequest() FrameWriteRequest { return FrameWriteRequest{writeSettingsAck{}, nil, nil} } func makeWriteHeadersRequest(streamID uint32) FrameWriteRequest { st := &stream{id: streamID} return FrameWriteRequest{&writeResHeaders{streamID: streamID, httpResCode: 200}, st, nil} } func checkConsume(wr FrameWriteRequest, nbytes int32, want []FrameWriteRequest) error { consumed, rest, n := wr.Consume(nbytes) var wantConsumed, wantRest FrameWriteRequest switch len(want) { case 0: case 1: wantConsumed = want[0] case 2: wantConsumed = want[0] wantRest = want[1] } if !reflect.DeepEqual(consumed, wantConsumed) || !reflect.DeepEqual(rest, wantRest) || n != len(want) { return fmt.Errorf("got %v, %v, %v\nwant %v, %v, %v", consumed, rest, n, wantConsumed, wantRest, len(want)) } return nil } func TestFrameWriteRequestNonData(t *testing.T) { wr := makeWriteNonStreamRequest() if got, want := wr.DataSize(), 0; got != want { t.Errorf("DataSize: got %v, want %v", got, want) } // Non-DATA frames are always consumed whole. if err := checkConsume(wr, 0, []FrameWriteRequest{wr}); err != nil { t.Errorf("Consume:\n%v", err) } } func TestFrameWriteRequestData(t *testing.T) { st := &stream{ id: 1, sc: &serverConn{maxFrameSize: 16}, } const size = 32 wr := FrameWriteRequest{&writeData{st.id, make([]byte, size), true}, st, make(chan error)} if got, want := wr.DataSize(), size; got != want { t.Errorf("DataSize: got %v, want %v", got, want) } // No flow-control bytes available: cannot consume anything. if err := checkConsume(wr, math.MaxInt32, []FrameWriteRequest{}); err != nil { t.Errorf("Consume(limited by flow control):\n%v", err) } // Add enough flow-control bytes to consume the entire frame, // but we're now restricted by st.sc.maxFrameSize. st.flow.add(size) want := []FrameWriteRequest{ { write: &writeData{st.id, make([]byte, st.sc.maxFrameSize), false}, stream: st, done: nil, }, { write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize), true}, stream: st, done: wr.done, }, } if err := checkConsume(wr, math.MaxInt32, want); err != nil { t.Errorf("Consume(limited by maxFrameSize):\n%v", err) } rest := want[1] // Consume 8 bytes from the remaining frame. want = []FrameWriteRequest{ { write: &writeData{st.id, make([]byte, 8), false}, stream: st, done: nil, }, { write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize-8), true}, stream: st, done: wr.done, }, } if err := checkConsume(rest, 8, want); err != nil { t.Errorf("Consume(8):\n%v", err) } rest = want[1] // Consume all remaining bytes. want = []FrameWriteRequest{ { write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize-8), true}, stream: st, done: wr.done, }, } if err := checkConsume(rest, math.MaxInt32, want); err != nil { t.Errorf("Consume(remainder):\n%v", err) } } func TestFrameWriteRequest_StreamID(t *testing.T) { const streamID = 123 wr := FrameWriteRequest{write: streamError(streamID, ErrCodeNo)} if got := wr.StreamID(); got != streamID { t.Errorf("FrameWriteRequest(StreamError) = %v; want %v", got, streamID) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/writesched_random_test.go0000644061062106075000000000221113172163402026437 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import "testing" func TestRandomScheduler(t *testing.T) { ws := NewRandomWriteScheduler() ws.Push(makeWriteHeadersRequest(3)) ws.Push(makeWriteHeadersRequest(4)) ws.Push(makeWriteHeadersRequest(1)) ws.Push(makeWriteHeadersRequest(2)) ws.Push(makeWriteNonStreamRequest()) ws.Push(makeWriteNonStreamRequest()) // Pop all frames. Should get the non-stream requests first, // followed by the stream requests in any order. var order []FrameWriteRequest for { wr, ok := ws.Pop() if !ok { break } order = append(order, wr) } t.Logf("got frames: %v", order) if len(order) != 6 { t.Fatalf("got %d frames, expected 6", len(order)) } if order[0].StreamID() != 0 || order[1].StreamID() != 0 { t.Fatal("expected non-stream frames first", order[0], order[1]) } got := make(map[uint32]bool) for _, wr := range order[2:] { got[wr.StreamID()] = true } for id := uint32(1); id <= 4; id++ { if !got[id] { t.Errorf("frame not found for stream %d", id) } } } lxd-2.0.11/dist/src/golang.org/x/net/http2/writesched_random.go0000644061062106075000000000361513172163402025411 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import "math" // NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2 // priorities. Control frames like SETTINGS and PING are written before DATA // frames, but if no control frames are queued and multiple streams have queued // HEADERS or DATA frames, Pop selects a ready stream arbitrarily. func NewRandomWriteScheduler() WriteScheduler { return &randomWriteScheduler{sq: make(map[uint32]*writeQueue)} } type randomWriteScheduler struct { // zero are frames not associated with a specific stream. zero writeQueue // sq contains the stream-specific queues, keyed by stream ID. // When a stream is idle or closed, it's deleted from the map. sq map[uint32]*writeQueue // pool of empty queues for reuse. queuePool writeQueuePool } func (ws *randomWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { // no-op: idle streams are not tracked } func (ws *randomWriteScheduler) CloseStream(streamID uint32) { q, ok := ws.sq[streamID] if !ok { return } delete(ws.sq, streamID) ws.queuePool.put(q) } func (ws *randomWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { // no-op: priorities are ignored } func (ws *randomWriteScheduler) Push(wr FrameWriteRequest) { id := wr.StreamID() if id == 0 { ws.zero.push(wr) return } q, ok := ws.sq[id] if !ok { q = ws.queuePool.get() ws.sq[id] = q } q.push(wr) } func (ws *randomWriteScheduler) Pop() (FrameWriteRequest, bool) { // Control frames first. if !ws.zero.empty() { return ws.zero.shift(), true } // Iterate over all non-idle streams until finding one that can be consumed. for _, q := range ws.sq { if wr, ok := q.consume(math.MaxInt32); ok { return wr, true } } return FrameWriteRequest{}, false } lxd-2.0.11/dist/src/golang.org/x/net/http2/writesched_priority_test.go0000644061062106075000000004212513172163402027050 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bytes" "fmt" "sort" "testing" ) func defaultPriorityWriteScheduler() *priorityWriteScheduler { return NewPriorityWriteScheduler(nil).(*priorityWriteScheduler) } func checkPriorityWellFormed(ws *priorityWriteScheduler) error { for id, n := range ws.nodes { if id != n.id { return fmt.Errorf("bad ws.nodes: ws.nodes[%d] = %d", id, n.id) } if n.parent == nil { if n.next != nil || n.prev != nil { return fmt.Errorf("bad node %d: nil parent but prev/next not nil", id) } continue } found := false for k := n.parent.kids; k != nil; k = k.next { if k.id == id { found = true break } } if !found { return fmt.Errorf("bad node %d: not found in parent %d kids list", id, n.parent.id) } } return nil } func fmtTree(ws *priorityWriteScheduler, fmtNode func(*priorityNode) string) string { var ids []int for _, n := range ws.nodes { ids = append(ids, int(n.id)) } sort.Ints(ids) var buf bytes.Buffer for _, id := range ids { if buf.Len() != 0 { buf.WriteString(" ") } if id == 0 { buf.WriteString(fmtNode(&ws.root)) } else { buf.WriteString(fmtNode(ws.nodes[uint32(id)])) } } return buf.String() } func fmtNodeParentSkipRoot(n *priorityNode) string { switch { case n.id == 0: return "" case n.parent == nil: return fmt.Sprintf("%d{parent:nil}", n.id) default: return fmt.Sprintf("%d{parent:%d}", n.id, n.parent.id) } } func fmtNodeWeightParentSkipRoot(n *priorityNode) string { switch { case n.id == 0: return "" case n.parent == nil: return fmt.Sprintf("%d{weight:%d,parent:nil}", n.id, n.weight) default: return fmt.Sprintf("%d{weight:%d,parent:%d}", n.id, n.weight, n.parent.id) } } func TestPriorityTwoStreams(t *testing.T) { ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{}) want := "1{weight:15,parent:0} 2{weight:15,parent:0}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After open\ngot %q\nwant %q", got, want) } // Move 1's parent to 2. ws.AdjustStream(1, PriorityParam{ StreamDep: 2, Weight: 32, Exclusive: false, }) want = "1{weight:32,parent:2} 2{weight:15,parent:0}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After adjust\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPriorityAdjustExclusiveZero(t *testing.T) { // 1, 2, and 3 are all children of the 0 stream. // Exclusive reprioritization to any of the streams should bring // the rest of the streams under the reprioritized stream. ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{}) ws.OpenStream(3, OpenStreamOptions{}) want := "1{weight:15,parent:0} 2{weight:15,parent:0} 3{weight:15,parent:0}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After open\ngot %q\nwant %q", got, want) } ws.AdjustStream(2, PriorityParam{ StreamDep: 0, Weight: 20, Exclusive: true, }) want = "1{weight:15,parent:2} 2{weight:20,parent:0} 3{weight:15,parent:2}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After adjust\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPriorityAdjustOwnParent(t *testing.T) { // Assigning a node as its own parent should have no effect. ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{}) ws.AdjustStream(2, PriorityParam{ StreamDep: 2, Weight: 20, Exclusive: true, }) want := "1{weight:15,parent:0} 2{weight:15,parent:0}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After adjust\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPriorityClosedStreams(t *testing.T) { ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{MaxClosedNodesInTree: 2}).(*priorityWriteScheduler) ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) // Close the first three streams. We lose 1, but keep 2 and 3. ws.CloseStream(1) ws.CloseStream(2) ws.CloseStream(3) want := "2{weight:15,parent:0} 3{weight:15,parent:2} 4{weight:15,parent:3}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After close\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } // Adding a stream as an exclusive child of 1 gives it default // priorities, since 1 is gone. ws.OpenStream(5, OpenStreamOptions{}) ws.AdjustStream(5, PriorityParam{StreamDep: 1, Weight: 15, Exclusive: true}) // Adding a stream as an exclusive child of 2 should work, since 2 is not gone. ws.OpenStream(6, OpenStreamOptions{}) ws.AdjustStream(6, PriorityParam{StreamDep: 2, Weight: 15, Exclusive: true}) want = "2{weight:15,parent:0} 3{weight:15,parent:6} 4{weight:15,parent:3} 5{weight:15,parent:0} 6{weight:15,parent:2}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After add streams\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPriorityClosedStreamsDisabled(t *testing.T) { ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{}).(*priorityWriteScheduler) ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) // Close the first two streams. We keep only 3. ws.CloseStream(1) ws.CloseStream(2) want := "3{weight:15,parent:0}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After close\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPriorityIdleStreams(t *testing.T) { ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{MaxIdleNodesInTree: 2}).(*priorityWriteScheduler) ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 15}) // idle ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 15}) // idle ws.AdjustStream(3, PriorityParam{StreamDep: 2, Weight: 20}) // idle ws.OpenStream(4, OpenStreamOptions{}) ws.OpenStream(5, OpenStreamOptions{}) ws.OpenStream(6, OpenStreamOptions{}) ws.AdjustStream(4, PriorityParam{StreamDep: 1, Weight: 15}) ws.AdjustStream(5, PriorityParam{StreamDep: 2, Weight: 15}) ws.AdjustStream(6, PriorityParam{StreamDep: 3, Weight: 15}) want := "2{weight:15,parent:0} 3{weight:20,parent:2} 4{weight:15,parent:0} 5{weight:15,parent:2} 6{weight:15,parent:3}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After open\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPriorityIdleStreamsDisabled(t *testing.T) { ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{}).(*priorityWriteScheduler) ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 15}) // idle ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 15}) // idle ws.AdjustStream(3, PriorityParam{StreamDep: 2, Weight: 20}) // idle ws.OpenStream(4, OpenStreamOptions{}) want := "4{weight:15,parent:0}" if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { t.Errorf("After open\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPrioritySection531NonExclusive(t *testing.T) { // Example from RFC 7540 Section 5.3.1. // A,B,C,D = 1,2,3,4 ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) ws.OpenStream(4, OpenStreamOptions{}) ws.AdjustStream(4, PriorityParam{ StreamDep: 1, Weight: 15, Exclusive: false, }) want := "1{parent:0} 2{parent:1} 3{parent:1} 4{parent:1}" if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { t.Errorf("After adjust\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPrioritySection531Exclusive(t *testing.T) { // Example from RFC 7540 Section 5.3.1. // A,B,C,D = 1,2,3,4 ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) ws.OpenStream(4, OpenStreamOptions{}) ws.AdjustStream(4, PriorityParam{ StreamDep: 1, Weight: 15, Exclusive: true, }) want := "1{parent:0} 2{parent:4} 3{parent:4} 4{parent:1}" if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { t.Errorf("After adjust\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func makeSection533Tree() *priorityWriteScheduler { // Initial tree from RFC 7540 Section 5.3.3. // A,B,C,D,E,F = 1,2,3,4,5,6 ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) return ws } func TestPrioritySection533NonExclusive(t *testing.T) { // Example from RFC 7540 Section 5.3.3. // A,B,C,D,E,F = 1,2,3,4,5,6 ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) ws.AdjustStream(1, PriorityParam{ StreamDep: 4, Weight: 15, Exclusive: false, }) want := "1{parent:4} 2{parent:1} 3{parent:1} 4{parent:0} 5{parent:3} 6{parent:4}" if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { t.Errorf("After adjust\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func TestPrioritySection533Exclusive(t *testing.T) { // Example from RFC 7540 Section 5.3.3. // A,B,C,D,E,F = 1,2,3,4,5,6 ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) ws.AdjustStream(1, PriorityParam{ StreamDep: 4, Weight: 15, Exclusive: true, }) want := "1{parent:4} 2{parent:1} 3{parent:1} 4{parent:0} 5{parent:3} 6{parent:1}" if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { t.Errorf("After adjust\ngot %q\nwant %q", got, want) } if err := checkPriorityWellFormed(ws); err != nil { t.Error(err) } } func checkPopAll(ws WriteScheduler, order []uint32) error { for k, id := range order { wr, ok := ws.Pop() if !ok { return fmt.Errorf("Pop[%d]: got ok=false, want %d (order=%v)", k, id, order) } if got := wr.StreamID(); got != id { return fmt.Errorf("Pop[%d]: got %v, want %d (order=%v)", k, got, id, order) } } wr, ok := ws.Pop() if ok { return fmt.Errorf("Pop[%d]: got %v, want ok=false (order=%v)", len(order), wr.StreamID(), order) } return nil } func TestPriorityPopFrom533Tree(t *testing.T) { ws := makeSection533Tree() ws.Push(makeWriteHeadersRequest(3 /*C*/)) ws.Push(makeWriteNonStreamRequest()) ws.Push(makeWriteHeadersRequest(5 /*E*/)) ws.Push(makeWriteHeadersRequest(1 /*A*/)) t.Log("tree:", fmtTree(ws, fmtNodeParentSkipRoot)) if err := checkPopAll(ws, []uint32{0 /*NonStream*/, 1, 3, 5}); err != nil { t.Error(err) } } func TestPriorityPopFromLinearTree(t *testing.T) { ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) ws.Push(makeWriteHeadersRequest(3)) ws.Push(makeWriteHeadersRequest(4)) ws.Push(makeWriteHeadersRequest(1)) ws.Push(makeWriteHeadersRequest(2)) ws.Push(makeWriteNonStreamRequest()) ws.Push(makeWriteNonStreamRequest()) t.Log("tree:", fmtTree(ws, fmtNodeParentSkipRoot)) if err := checkPopAll(ws, []uint32{0, 0 /*NonStreams*/, 1, 2, 3, 4}); err != nil { t.Error(err) } } func TestPriorityFlowControl(t *testing.T) { ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ThrottleOutOfOrderWrites: false}) ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) sc := &serverConn{maxFrameSize: 16} st1 := &stream{id: 1, sc: sc} st2 := &stream{id: 2, sc: sc} ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 16), false}, st1, nil}) ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 16), false}, st2, nil}) ws.AdjustStream(2, PriorityParam{StreamDep: 1}) // No flow-control bytes available. if wr, ok := ws.Pop(); ok { t.Fatalf("Pop(limited by flow control)=%v,true, want false", wr) } // Add enough flow-control bytes to write st2 in two Pop calls. // Should write data from st2 even though it's lower priority than st1. for i := 1; i <= 2; i++ { st2.flow.add(8) wr, ok := ws.Pop() if !ok { t.Fatalf("Pop(%d)=false, want true", i) } if got, want := wr.DataSize(), 8; got != want { t.Fatalf("Pop(%d)=%d bytes, want %d bytes", i, got, want) } } } func TestPriorityThrottleOutOfOrderWrites(t *testing.T) { ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ThrottleOutOfOrderWrites: true}) ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) sc := &serverConn{maxFrameSize: 4096} st1 := &stream{id: 1, sc: sc} st2 := &stream{id: 2, sc: sc} st1.flow.add(4096) st2.flow.add(4096) ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 4096), false}, st2, nil}) ws.AdjustStream(2, PriorityParam{StreamDep: 1}) // We have enough flow-control bytes to write st2 in a single Pop call. // However, due to out-of-order write throttling, the first call should // only write 1KB. wr, ok := ws.Pop() if !ok { t.Fatalf("Pop(st2.first)=false, want true") } if got, want := wr.StreamID(), uint32(2); got != want { t.Fatalf("Pop(st2.first)=stream %d, want stream %d", got, want) } if got, want := wr.DataSize(), 1024; got != want { t.Fatalf("Pop(st2.first)=%d bytes, want %d bytes", got, want) } // Now add data on st1. This should take precedence. ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 4096), false}, st1, nil}) wr, ok = ws.Pop() if !ok { t.Fatalf("Pop(st1)=false, want true") } if got, want := wr.StreamID(), uint32(1); got != want { t.Fatalf("Pop(st1)=stream %d, want stream %d", got, want) } if got, want := wr.DataSize(), 4096; got != want { t.Fatalf("Pop(st1)=%d bytes, want %d bytes", got, want) } // Should go back to writing 1KB from st2. wr, ok = ws.Pop() if !ok { t.Fatalf("Pop(st2.last)=false, want true") } if got, want := wr.StreamID(), uint32(2); got != want { t.Fatalf("Pop(st2.last)=stream %d, want stream %d", got, want) } if got, want := wr.DataSize(), 1024; got != want { t.Fatalf("Pop(st2.last)=%d bytes, want %d bytes", got, want) } } func TestPriorityWeights(t *testing.T) { ws := defaultPriorityWriteScheduler() ws.OpenStream(1, OpenStreamOptions{}) ws.OpenStream(2, OpenStreamOptions{}) sc := &serverConn{maxFrameSize: 8} st1 := &stream{id: 1, sc: sc} st2 := &stream{id: 2, sc: sc} st1.flow.add(40) st2.flow.add(40) ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 40), false}, st1, nil}) ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 40), false}, st2, nil}) ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 34}) ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 9}) // st1 gets 3.5x the bandwidth of st2 (3.5 = (34+1)/(9+1)). // The maximum frame size is 8 bytes. The write sequence should be: // st1, total bytes so far is (st1=8, st=0) // st2, total bytes so far is (st1=8, st=8) // st1, total bytes so far is (st1=16, st=8) // st1, total bytes so far is (st1=24, st=8) // 3x bandwidth // st1, total bytes so far is (st1=32, st=8) // 4x bandwidth // st2, total bytes so far is (st1=32, st=16) // 2x bandwidth // st1, total bytes so far is (st1=40, st=16) // st2, total bytes so far is (st1=40, st=24) // st2, total bytes so far is (st1=40, st=32) // st2, total bytes so far is (st1=40, st=40) if err := checkPopAll(ws, []uint32{1, 2, 1, 1, 1, 2, 1, 2, 2, 2}); err != nil { t.Error(err) } } func TestPriorityRstStreamOnNonOpenStreams(t *testing.T) { ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ MaxClosedNodesInTree: 0, MaxIdleNodesInTree: 0, }) ws.OpenStream(1, OpenStreamOptions{}) ws.CloseStream(1) ws.Push(FrameWriteRequest{write: streamError(1, ErrCodeProtocol)}) ws.Push(FrameWriteRequest{write: streamError(2, ErrCodeProtocol)}) if err := checkPopAll(ws, []uint32{1, 2}); err != nil { t.Error(err) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/writesched_priority.go0000644061062106075000000003272613172163402026017 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "fmt" "math" "sort" ) // RFC 7540, Section 5.3.5: the default weight is 16. const priorityDefaultWeight = 15 // 16 = 15 + 1 // PriorityWriteSchedulerConfig configures a priorityWriteScheduler. type PriorityWriteSchedulerConfig struct { // MaxClosedNodesInTree controls the maximum number of closed streams to // retain in the priority tree. Setting this to zero saves a small amount // of memory at the cost of performance. // // See RFC 7540, Section 5.3.4: // "It is possible for a stream to become closed while prioritization // information ... is in transit. ... This potentially creates suboptimal // prioritization, since the stream could be given a priority that is // different from what is intended. To avoid these problems, an endpoint // SHOULD retain stream prioritization state for a period after streams // become closed. The longer state is retained, the lower the chance that // streams are assigned incorrect or default priority values." MaxClosedNodesInTree int // MaxIdleNodesInTree controls the maximum number of idle streams to // retain in the priority tree. Setting this to zero saves a small amount // of memory at the cost of performance. // // See RFC 7540, Section 5.3.4: // Similarly, streams that are in the "idle" state can be assigned // priority or become a parent of other streams. This allows for the // creation of a grouping node in the dependency tree, which enables // more flexible expressions of priority. Idle streams begin with a // default priority (Section 5.3.5). MaxIdleNodesInTree int // ThrottleOutOfOrderWrites enables write throttling to help ensure that // data is delivered in priority order. This works around a race where // stream B depends on stream A and both streams are about to call Write // to queue DATA frames. If B wins the race, a naive scheduler would eagerly // write as much data from B as possible, but this is suboptimal because A // is a higher-priority stream. With throttling enabled, we write a small // amount of data from B to minimize the amount of bandwidth that B can // steal from A. ThrottleOutOfOrderWrites bool } // NewPriorityWriteScheduler constructs a WriteScheduler that schedules // frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3. // If cfg is nil, default options are used. func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler { if cfg == nil { // For justification of these defaults, see: // https://docs.google.com/document/d/1oLhNg1skaWD4_DtaoCxdSRN5erEXrH-KnLrMwEpOtFY cfg = &PriorityWriteSchedulerConfig{ MaxClosedNodesInTree: 10, MaxIdleNodesInTree: 10, ThrottleOutOfOrderWrites: false, } } ws := &priorityWriteScheduler{ nodes: make(map[uint32]*priorityNode), maxClosedNodesInTree: cfg.MaxClosedNodesInTree, maxIdleNodesInTree: cfg.MaxIdleNodesInTree, enableWriteThrottle: cfg.ThrottleOutOfOrderWrites, } ws.nodes[0] = &ws.root if cfg.ThrottleOutOfOrderWrites { ws.writeThrottleLimit = 1024 } else { ws.writeThrottleLimit = math.MaxInt32 } return ws } type priorityNodeState int const ( priorityNodeOpen priorityNodeState = iota priorityNodeClosed priorityNodeIdle ) // priorityNode is a node in an HTTP/2 priority tree. // Each node is associated with a single stream ID. // See RFC 7540, Section 5.3. type priorityNode struct { q writeQueue // queue of pending frames to write id uint32 // id of the stream, or 0 for the root of the tree weight uint8 // the actual weight is weight+1, so the value is in [1,256] state priorityNodeState // open | closed | idle bytes int64 // number of bytes written by this node, or 0 if closed subtreeBytes int64 // sum(node.bytes) of all nodes in this subtree // These links form the priority tree. parent *priorityNode kids *priorityNode // start of the kids list prev, next *priorityNode // doubly-linked list of siblings } func (n *priorityNode) setParent(parent *priorityNode) { if n == parent { panic("setParent to self") } if n.parent == parent { return } // Unlink from current parent. if parent := n.parent; parent != nil { if n.prev == nil { parent.kids = n.next } else { n.prev.next = n.next } if n.next != nil { n.next.prev = n.prev } } // Link to new parent. // If parent=nil, remove n from the tree. // Always insert at the head of parent.kids (this is assumed by walkReadyInOrder). n.parent = parent if parent == nil { n.next = nil n.prev = nil } else { n.next = parent.kids n.prev = nil if n.next != nil { n.next.prev = n } parent.kids = n } } func (n *priorityNode) addBytes(b int64) { n.bytes += b for ; n != nil; n = n.parent { n.subtreeBytes += b } } // walkReadyInOrder iterates over the tree in priority order, calling f for each node // with a non-empty write queue. When f returns true, this funcion returns true and the // walk halts. tmp is used as scratch space for sorting. // // f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true // if any ancestor p of n is still open (ignoring the root node). func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f func(*priorityNode, bool) bool) bool { if !n.q.empty() && f(n, openParent) { return true } if n.kids == nil { return false } // Don't consider the root "open" when updating openParent since // we can't send data frames on the root stream (only control frames). if n.id != 0 { openParent = openParent || (n.state == priorityNodeOpen) } // Common case: only one kid or all kids have the same weight. // Some clients don't use weights; other clients (like web browsers) // use mostly-linear priority trees. w := n.kids.weight needSort := false for k := n.kids.next; k != nil; k = k.next { if k.weight != w { needSort = true break } } if !needSort { for k := n.kids; k != nil; k = k.next { if k.walkReadyInOrder(openParent, tmp, f) { return true } } return false } // Uncommon case: sort the child nodes. We remove the kids from the parent, // then re-insert after sorting so we can reuse tmp for future sort calls. *tmp = (*tmp)[:0] for n.kids != nil { *tmp = append(*tmp, n.kids) n.kids.setParent(nil) } sort.Sort(sortPriorityNodeSiblings(*tmp)) for i := len(*tmp) - 1; i >= 0; i-- { (*tmp)[i].setParent(n) // setParent inserts at the head of n.kids } for k := n.kids; k != nil; k = k.next { if k.walkReadyInOrder(openParent, tmp, f) { return true } } return false } type sortPriorityNodeSiblings []*priorityNode func (z sortPriorityNodeSiblings) Len() int { return len(z) } func (z sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] } func (z sortPriorityNodeSiblings) Less(i, k int) bool { // Prefer the subtree that has sent fewer bytes relative to its weight. // See sections 5.3.2 and 5.3.4. wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes) wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes) if bi == 0 && bk == 0 { return wi >= wk } if bk == 0 { return false } return bi/bk <= wi/wk } type priorityWriteScheduler struct { // root is the root of the priority tree, where root.id = 0. // The root queues control frames that are not associated with any stream. root priorityNode // nodes maps stream ids to priority tree nodes. nodes map[uint32]*priorityNode // maxID is the maximum stream id in nodes. maxID uint32 // lists of nodes that have been closed or are idle, but are kept in // the tree for improved prioritization. When the lengths exceed either // maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded. closedNodes, idleNodes []*priorityNode // From the config. maxClosedNodesInTree int maxIdleNodesInTree int writeThrottleLimit int32 enableWriteThrottle bool // tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations. tmp []*priorityNode // pool of empty queues for reuse. queuePool writeQueuePool } func (ws *priorityWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { // The stream may be currently idle but cannot be opened or closed. if curr := ws.nodes[streamID]; curr != nil { if curr.state != priorityNodeIdle { panic(fmt.Sprintf("stream %d already opened", streamID)) } curr.state = priorityNodeOpen return } // RFC 7540, Section 5.3.5: // "All streams are initially assigned a non-exclusive dependency on stream 0x0. // Pushed streams initially depend on their associated stream. In both cases, // streams are assigned a default weight of 16." parent := ws.nodes[options.PusherID] if parent == nil { parent = &ws.root } n := &priorityNode{ q: *ws.queuePool.get(), id: streamID, weight: priorityDefaultWeight, state: priorityNodeOpen, } n.setParent(parent) ws.nodes[streamID] = n if streamID > ws.maxID { ws.maxID = streamID } } func (ws *priorityWriteScheduler) CloseStream(streamID uint32) { if streamID == 0 { panic("violation of WriteScheduler interface: cannot close stream 0") } if ws.nodes[streamID] == nil { panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID)) } if ws.nodes[streamID].state != priorityNodeOpen { panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID)) } n := ws.nodes[streamID] n.state = priorityNodeClosed n.addBytes(-n.bytes) q := n.q ws.queuePool.put(&q) n.q.s = nil if ws.maxClosedNodesInTree > 0 { ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n) } else { ws.removeNode(n) } } func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { if streamID == 0 { panic("adjustPriority on root") } // If streamID does not exist, there are two cases: // - A closed stream that has been removed (this will have ID <= maxID) // - An idle stream that is being used for "grouping" (this will have ID > maxID) n := ws.nodes[streamID] if n == nil { if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 { return } ws.maxID = streamID n = &priorityNode{ q: *ws.queuePool.get(), id: streamID, weight: priorityDefaultWeight, state: priorityNodeIdle, } n.setParent(&ws.root) ws.nodes[streamID] = n ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n) } // Section 5.3.1: A dependency on a stream that is not currently in the tree // results in that stream being given a default priority (Section 5.3.5). parent := ws.nodes[priority.StreamDep] if parent == nil { n.setParent(&ws.root) n.weight = priorityDefaultWeight return } // Ignore if the client tries to make a node its own parent. if n == parent { return } // Section 5.3.3: // "If a stream is made dependent on one of its own dependencies, the // formerly dependent stream is first moved to be dependent on the // reprioritized stream's previous parent. The moved dependency retains // its weight." // // That is: if parent depends on n, move parent to depend on n.parent. for x := parent.parent; x != nil; x = x.parent { if x == n { parent.setParent(n.parent) break } } // Section 5.3.3: The exclusive flag causes the stream to become the sole // dependency of its parent stream, causing other dependencies to become // dependent on the exclusive stream. if priority.Exclusive { k := parent.kids for k != nil { next := k.next if k != n { k.setParent(n) } k = next } } n.setParent(parent) n.weight = priority.Weight } func (ws *priorityWriteScheduler) Push(wr FrameWriteRequest) { var n *priorityNode if id := wr.StreamID(); id == 0 { n = &ws.root } else { n = ws.nodes[id] if n == nil { // id is an idle or closed stream. wr should not be a HEADERS or // DATA frame. However, wr can be a RST_STREAM. In this case, we // push wr onto the root, rather than creating a new priorityNode, // since RST_STREAM is tiny and the stream's priority is unknown // anyway. See issue #17919. if wr.DataSize() > 0 { panic("add DATA on non-open stream") } n = &ws.root } } n.q.push(wr) } func (ws *priorityWriteScheduler) Pop() (wr FrameWriteRequest, ok bool) { ws.root.walkReadyInOrder(false, &ws.tmp, func(n *priorityNode, openParent bool) bool { limit := int32(math.MaxInt32) if openParent { limit = ws.writeThrottleLimit } wr, ok = n.q.consume(limit) if !ok { return false } n.addBytes(int64(wr.DataSize())) // If B depends on A and B continuously has data available but A // does not, gradually increase the throttling limit to allow B to // steal more and more bandwidth from A. if openParent { ws.writeThrottleLimit += 1024 if ws.writeThrottleLimit < 0 { ws.writeThrottleLimit = math.MaxInt32 } } else if ws.enableWriteThrottle { ws.writeThrottleLimit = 1024 } return true }) return wr, ok } func (ws *priorityWriteScheduler) addClosedOrIdleNode(list *[]*priorityNode, maxSize int, n *priorityNode) { if maxSize == 0 { return } if len(*list) == maxSize { // Remove the oldest node, then shift left. ws.removeNode((*list)[0]) x := (*list)[1:] copy(*list, x) *list = (*list)[:len(x)] } *list = append(*list, n) } func (ws *priorityWriteScheduler) removeNode(n *priorityNode) { for k := n.kids; k != nil; k = k.next { k.setParent(n.parent) } n.setParent(nil) delete(ws.nodes, n.id) } lxd-2.0.11/dist/src/golang.org/x/net/http2/writesched.go0000644061062106075000000001637413172163402024057 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import "fmt" // WriteScheduler is the interface implemented by HTTP/2 write schedulers. // Methods are never called concurrently. type WriteScheduler interface { // OpenStream opens a new stream in the write scheduler. // It is illegal to call this with streamID=0 or with a streamID that is // already open -- the call may panic. OpenStream(streamID uint32, options OpenStreamOptions) // CloseStream closes a stream in the write scheduler. Any frames queued on // this stream should be discarded. It is illegal to call this on a stream // that is not open -- the call may panic. CloseStream(streamID uint32) // AdjustStream adjusts the priority of the given stream. This may be called // on a stream that has not yet been opened or has been closed. Note that // RFC 7540 allows PRIORITY frames to be sent on streams in any state. See: // https://tools.ietf.org/html/rfc7540#section-5.1 AdjustStream(streamID uint32, priority PriorityParam) // Push queues a frame in the scheduler. In most cases, this will not be // called with wr.StreamID()!=0 unless that stream is currently open. The one // exception is RST_STREAM frames, which may be sent on idle or closed streams. Push(wr FrameWriteRequest) // Pop dequeues the next frame to write. Returns false if no frames can // be written. Frames with a given wr.StreamID() are Pop'd in the same // order they are Push'd. Pop() (wr FrameWriteRequest, ok bool) } // OpenStreamOptions specifies extra options for WriteScheduler.OpenStream. type OpenStreamOptions struct { // PusherID is zero if the stream was initiated by the client. Otherwise, // PusherID names the stream that pushed the newly opened stream. PusherID uint32 } // FrameWriteRequest is a request to write a frame. type FrameWriteRequest struct { // write is the interface value that does the writing, once the // WriteScheduler has selected this frame to write. The write // functions are all defined in write.go. write writeFramer // stream is the stream on which this frame will be written. // nil for non-stream frames like PING and SETTINGS. stream *stream // done, if non-nil, must be a buffered channel with space for // 1 message and is sent the return value from write (or an // earlier error) when the frame has been written. done chan error } // StreamID returns the id of the stream this frame will be written to. // 0 is used for non-stream frames such as PING and SETTINGS. func (wr FrameWriteRequest) StreamID() uint32 { if wr.stream == nil { if se, ok := wr.write.(StreamError); ok { // (*serverConn).resetStream doesn't set // stream because it doesn't necessarily have // one. So special case this type of write // message. return se.StreamID } return 0 } return wr.stream.id } // DataSize returns the number of flow control bytes that must be consumed // to write this entire frame. This is 0 for non-DATA frames. func (wr FrameWriteRequest) DataSize() int { if wd, ok := wr.write.(*writeData); ok { return len(wd.p) } return 0 } // Consume consumes min(n, available) bytes from this frame, where available // is the number of flow control bytes available on the stream. Consume returns // 0, 1, or 2 frames, where the integer return value gives the number of frames // returned. // // If flow control prevents consuming any bytes, this returns (_, _, 0). If // the entire frame was consumed, this returns (wr, _, 1). Otherwise, this // returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and // 'rest' contains the remaining bytes. The consumed bytes are deducted from the // underlying stream's flow control budget. func (wr FrameWriteRequest) Consume(n int32) (FrameWriteRequest, FrameWriteRequest, int) { var empty FrameWriteRequest // Non-DATA frames are always consumed whole. wd, ok := wr.write.(*writeData) if !ok || len(wd.p) == 0 { return wr, empty, 1 } // Might need to split after applying limits. allowed := wr.stream.flow.available() if n < allowed { allowed = n } if wr.stream.sc.maxFrameSize < allowed { allowed = wr.stream.sc.maxFrameSize } if allowed <= 0 { return empty, empty, 0 } if len(wd.p) > int(allowed) { wr.stream.flow.take(allowed) consumed := FrameWriteRequest{ stream: wr.stream, write: &writeData{ streamID: wd.streamID, p: wd.p[:allowed], // Even if the original had endStream set, there // are bytes remaining because len(wd.p) > allowed, // so we know endStream is false. endStream: false, }, // Our caller is blocking on the final DATA frame, not // this intermediate frame, so no need to wait. done: nil, } rest := FrameWriteRequest{ stream: wr.stream, write: &writeData{ streamID: wd.streamID, p: wd.p[allowed:], endStream: wd.endStream, }, done: wr.done, } return consumed, rest, 2 } // The frame is consumed whole. // NB: This cast cannot overflow because allowed is <= math.MaxInt32. wr.stream.flow.take(int32(len(wd.p))) return wr, empty, 1 } // String is for debugging only. func (wr FrameWriteRequest) String() string { var des string if s, ok := wr.write.(fmt.Stringer); ok { des = s.String() } else { des = fmt.Sprintf("%T", wr.write) } return fmt.Sprintf("[FrameWriteRequest stream=%d, ch=%v, writer=%v]", wr.StreamID(), wr.done != nil, des) } // replyToWriter sends err to wr.done and panics if the send must block // This does nothing if wr.done is nil. func (wr *FrameWriteRequest) replyToWriter(err error) { if wr.done == nil { return } select { case wr.done <- err: default: panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write)) } wr.write = nil // prevent use (assume it's tainted after wr.done send) } // writeQueue is used by implementations of WriteScheduler. type writeQueue struct { s []FrameWriteRequest } func (q *writeQueue) empty() bool { return len(q.s) == 0 } func (q *writeQueue) push(wr FrameWriteRequest) { q.s = append(q.s, wr) } func (q *writeQueue) shift() FrameWriteRequest { if len(q.s) == 0 { panic("invalid use of queue") } wr := q.s[0] // TODO: less copy-happy queue. copy(q.s, q.s[1:]) q.s[len(q.s)-1] = FrameWriteRequest{} q.s = q.s[:len(q.s)-1] return wr } // consume consumes up to n bytes from q.s[0]. If the frame is // entirely consumed, it is removed from the queue. If the frame // is partially consumed, the frame is kept with the consumed // bytes removed. Returns true iff any bytes were consumed. func (q *writeQueue) consume(n int32) (FrameWriteRequest, bool) { if len(q.s) == 0 { return FrameWriteRequest{}, false } consumed, rest, numresult := q.s[0].Consume(n) switch numresult { case 0: return FrameWriteRequest{}, false case 1: q.shift() case 2: q.s[0] = rest } return consumed, true } type writeQueuePool []*writeQueue // put inserts an unused writeQueue into the pool. func (p *writeQueuePool) put(q *writeQueue) { for i := range q.s { q.s[i] = FrameWriteRequest{} } q.s = q.s[:0] *p = append(*p, q) } // get returns an empty writeQueue. func (p *writeQueuePool) get() *writeQueue { ln := len(*p) if ln == 0 { return new(writeQueue) } x := ln - 1 q := (*p)[x] (*p)[x] = nil *p = (*p)[:x] return q } lxd-2.0.11/dist/src/golang.org/x/net/http2/write.go0000644061062106075000000002512113172163402023036 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bytes" "fmt" "log" "net/http" "net/url" "time" "golang.org/x/net/http2/hpack" "golang.org/x/net/lex/httplex" ) // writeFramer is implemented by any type that is used to write frames. type writeFramer interface { writeFrame(writeContext) error // staysWithinBuffer reports whether this writer promises that // it will only write less than or equal to size bytes, and it // won't Flush the write context. staysWithinBuffer(size int) bool } // writeContext is the interface needed by the various frame writer // types below. All the writeFrame methods below are scheduled via the // frame writing scheduler (see writeScheduler in writesched.go). // // This interface is implemented by *serverConn. // // TODO: decide whether to a) use this in the client code (which didn't // end up using this yet, because it has a simpler design, not // currently implementing priorities), or b) delete this and // make the server code a bit more concrete. type writeContext interface { Framer() *Framer Flush() error CloseConn() error // HeaderEncoder returns an HPACK encoder that writes to the // returned buffer. HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) } // writeEndsStream reports whether w writes a frame that will transition // the stream to a half-closed local state. This returns false for RST_STREAM, // which closes the entire stream (not just the local half). func writeEndsStream(w writeFramer) bool { switch v := w.(type) { case *writeData: return v.endStream case *writeResHeaders: return v.endStream case nil: // This can only happen if the caller reuses w after it's // been intentionally nil'ed out to prevent use. Keep this // here to catch future refactoring breaking it. panic("writeEndsStream called on nil writeFramer") } return false } type flushFrameWriter struct{} func (flushFrameWriter) writeFrame(ctx writeContext) error { return ctx.Flush() } func (flushFrameWriter) staysWithinBuffer(max int) bool { return false } type writeSettings []Setting func (s writeSettings) staysWithinBuffer(max int) bool { const settingSize = 6 // uint16 + uint32 return frameHeaderLen+settingSize*len(s) <= max } func (s writeSettings) writeFrame(ctx writeContext) error { return ctx.Framer().WriteSettings([]Setting(s)...) } type writeGoAway struct { maxStreamID uint32 code ErrCode } func (p *writeGoAway) writeFrame(ctx writeContext) error { err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil) if p.code != 0 { ctx.Flush() // ignore error: we're hanging up on them anyway time.Sleep(50 * time.Millisecond) ctx.CloseConn() } return err } func (*writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes type writeData struct { streamID uint32 p []byte endStream bool } func (w *writeData) String() string { return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream) } func (w *writeData) writeFrame(ctx writeContext) error { return ctx.Framer().WriteData(w.streamID, w.endStream, w.p) } func (w *writeData) staysWithinBuffer(max int) bool { return frameHeaderLen+len(w.p) <= max } // handlerPanicRST is the message sent from handler goroutines when // the handler panics. type handlerPanicRST struct { StreamID uint32 } func (hp handlerPanicRST) writeFrame(ctx writeContext) error { return ctx.Framer().WriteRSTStream(hp.StreamID, ErrCodeInternal) } func (hp handlerPanicRST) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } func (se StreamError) writeFrame(ctx writeContext) error { return ctx.Framer().WriteRSTStream(se.StreamID, se.Code) } func (se StreamError) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } type writePingAck struct{ pf *PingFrame } func (w writePingAck) writeFrame(ctx writeContext) error { return ctx.Framer().WritePing(true, w.pf.Data) } func (w writePingAck) staysWithinBuffer(max int) bool { return frameHeaderLen+len(w.pf.Data) <= max } type writeSettingsAck struct{} func (writeSettingsAck) writeFrame(ctx writeContext) error { return ctx.Framer().WriteSettingsAck() } func (writeSettingsAck) staysWithinBuffer(max int) bool { return frameHeaderLen <= max } // splitHeaderBlock splits headerBlock into fragments so that each fragment fits // in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true // for the first/last fragment, respectively. func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error { // For now we're lazy and just pick the minimum MAX_FRAME_SIZE // that all peers must support (16KB). Later we could care // more and send larger frames if the peer advertised it, but // there's little point. Most headers are small anyway (so we // generally won't have CONTINUATION frames), and extra frames // only waste 9 bytes anyway. const maxFrameSize = 16384 first := true for len(headerBlock) > 0 { frag := headerBlock if len(frag) > maxFrameSize { frag = frag[:maxFrameSize] } headerBlock = headerBlock[len(frag):] if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil { return err } first = false } return nil } // writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames // for HTTP response headers or trailers from a server handler. type writeResHeaders struct { streamID uint32 httpResCode int // 0 means no ":status" line h http.Header // may be nil trailers []string // if non-nil, which keys of h to write. nil means all. endStream bool date string contentType string contentLength string } func encKV(enc *hpack.Encoder, k, v string) { if VerboseLogs { log.Printf("http2: server encoding header %q = %q", k, v) } enc.WriteField(hpack.HeaderField{Name: k, Value: v}) } func (w *writeResHeaders) staysWithinBuffer(max int) bool { // TODO: this is a common one. It'd be nice to return true // here and get into the fast path if we could be clever and // calculate the size fast enough, or at least a conservative // uppper bound that usually fires. (Maybe if w.h and // w.trailers are nil, so we don't need to enumerate it.) // Otherwise I'm afraid that just calculating the length to // answer this question would be slower than the ~2µs benefit. return false } func (w *writeResHeaders) writeFrame(ctx writeContext) error { enc, buf := ctx.HeaderEncoder() buf.Reset() if w.httpResCode != 0 { encKV(enc, ":status", httpCodeString(w.httpResCode)) } encodeHeaders(enc, w.h, w.trailers) if w.contentType != "" { encKV(enc, "content-type", w.contentType) } if w.contentLength != "" { encKV(enc, "content-length", w.contentLength) } if w.date != "" { encKV(enc, "date", w.date) } headerBlock := buf.Bytes() if len(headerBlock) == 0 && w.trailers == nil { panic("unexpected empty hpack") } return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock) } func (w *writeResHeaders) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error { if firstFrag { return ctx.Framer().WriteHeaders(HeadersFrameParam{ StreamID: w.streamID, BlockFragment: frag, EndStream: w.endStream, EndHeaders: lastFrag, }) } else { return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag) } } // writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames. type writePushPromise struct { streamID uint32 // pusher stream method string // for :method url *url.URL // for :scheme, :authority, :path h http.Header // Creates an ID for a pushed stream. This runs on serveG just before // the frame is written. The returned ID is copied to promisedID. allocatePromisedID func() (uint32, error) promisedID uint32 } func (w *writePushPromise) staysWithinBuffer(max int) bool { // TODO: see writeResHeaders.staysWithinBuffer return false } func (w *writePushPromise) writeFrame(ctx writeContext) error { enc, buf := ctx.HeaderEncoder() buf.Reset() encKV(enc, ":method", w.method) encKV(enc, ":scheme", w.url.Scheme) encKV(enc, ":authority", w.url.Host) encKV(enc, ":path", w.url.RequestURI()) encodeHeaders(enc, w.h, nil) headerBlock := buf.Bytes() if len(headerBlock) == 0 { panic("unexpected empty hpack") } return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock) } func (w *writePushPromise) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error { if firstFrag { return ctx.Framer().WritePushPromise(PushPromiseParam{ StreamID: w.streamID, PromiseID: w.promisedID, BlockFragment: frag, EndHeaders: lastFrag, }) } else { return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag) } } type write100ContinueHeadersFrame struct { streamID uint32 } func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error { enc, buf := ctx.HeaderEncoder() buf.Reset() encKV(enc, ":status", "100") return ctx.Framer().WriteHeaders(HeadersFrameParam{ StreamID: w.streamID, BlockFragment: buf.Bytes(), EndStream: false, EndHeaders: true, }) } func (w write100ContinueHeadersFrame) staysWithinBuffer(max int) bool { // Sloppy but conservative: return 9+2*(len(":status")+len("100")) <= max } type writeWindowUpdate struct { streamID uint32 // or 0 for conn-level n uint32 } func (wu writeWindowUpdate) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } func (wu writeWindowUpdate) writeFrame(ctx writeContext) error { return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n) } // encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k]) // is encoded only only if k is in keys. func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) { if keys == nil { sorter := sorterPool.Get().(*sorter) // Using defer here, since the returned keys from the // sorter.Keys method is only valid until the sorter // is returned: defer sorterPool.Put(sorter) keys = sorter.Keys(h) } for _, k := range keys { vv := h[k] k = lowerHeader(k) if !validWireHeaderFieldName(k) { // Skip it as backup paranoia. Per // golang.org/issue/14048, these should // already be rejected at a higher level. continue } isTE := k == "transfer-encoding" for _, v := range vv { if !httplex.ValidHeaderFieldValue(v) { // TODO: return an error? golang.org/issue/14048 // For now just omit it. continue } // TODO: more of "8.1.2.2 Connection-Specific Header Fields" if isTE && v != "trailers" { continue } encKV(enc, k, v) } } } lxd-2.0.11/dist/src/golang.org/x/net/http2/transport_test.go0000644061062106075000000027674013172163402025016 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bufio" "bytes" "crypto/tls" "errors" "flag" "fmt" "io" "io/ioutil" "math/rand" "net" "net/http" "net/http/httptest" "net/url" "os" "reflect" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "testing" "time" "golang.org/x/net/http2/hpack" ) var ( extNet = flag.Bool("extnet", false, "do external network tests") transportHost = flag.String("transporthost", "http2.golang.org", "hostname to use for TestTransport") insecure = flag.Bool("insecure", false, "insecure TLS dials") // TODO: dead code. remove? ) var tlsConfigInsecure = &tls.Config{InsecureSkipVerify: true} type testContext struct{} func (testContext) Done() <-chan struct{} { return make(chan struct{}) } func (testContext) Err() error { panic("should not be called") } func (testContext) Deadline() (deadline time.Time, ok bool) { return time.Time{}, false } func (testContext) Value(key interface{}) interface{} { return nil } func TestTransportExternal(t *testing.T) { if !*extNet { t.Skip("skipping external network test") } req, _ := http.NewRequest("GET", "https://"+*transportHost+"/", nil) rt := &Transport{TLSClientConfig: tlsConfigInsecure} res, err := rt.RoundTrip(req) if err != nil { t.Fatalf("%v", err) } res.Write(os.Stdout) } type fakeTLSConn struct { net.Conn } func (c *fakeTLSConn) ConnectionState() tls.ConnectionState { return tls.ConnectionState{ Version: tls.VersionTLS12, CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, } } func startH2cServer(t *testing.T) net.Listener { h2Server := &Server{} l := newLocalListener(t) go func() { conn, err := l.Accept() if err != nil { t.Error(err) return } h2Server.ServeConn(&fakeTLSConn{conn}, &ServeConnOpts{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %v, http: %v", r.URL.Path, r.TLS == nil) })}) }() return l } func TestTransportH2c(t *testing.T) { l := startH2cServer(t) defer l.Close() req, err := http.NewRequest("GET", "http://"+l.Addr().String()+"/foobar", nil) if err != nil { t.Fatal(err) } tr := &Transport{ AllowHTTP: true, DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { return net.Dial(network, addr) }, } res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } if res.ProtoMajor != 2 { t.Fatal("proto not h2c") } body, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } if got, want := string(body), "Hello, /foobar, http: true"; got != want { t.Fatalf("response got %v, want %v", got, want) } } func TestTransport(t *testing.T) { const body = "sup" st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, body) }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Fatal(err) } res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } defer res.Body.Close() t.Logf("Got res: %+v", res) if g, w := res.StatusCode, 200; g != w { t.Errorf("StatusCode = %v; want %v", g, w) } if g, w := res.Status, "200 OK"; g != w { t.Errorf("Status = %q; want %q", g, w) } wantHeader := http.Header{ "Content-Length": []string{"3"}, "Content-Type": []string{"text/plain; charset=utf-8"}, "Date": []string{"XXX"}, // see cleanDate } cleanDate(res) if !reflect.DeepEqual(res.Header, wantHeader) { t.Errorf("res Header = %v; want %v", res.Header, wantHeader) } if res.Request != req { t.Errorf("Response.Request = %p; want %p", res.Request, req) } if res.TLS == nil { t.Error("Response.TLS = nil; want non-nil") } slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Errorf("Body read: %v", err) } else if string(slurp) != body { t.Errorf("Body = %q; want %q", slurp, body) } } func onSameConn(t *testing.T, modReq func(*http.Request)) bool { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, r.RemoteAddr) }, optOnlyServer, func(c net.Conn, st http.ConnState) { t.Logf("conn %v is now state %v", c.RemoteAddr(), st) }) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() get := func() string { req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Fatal(err) } modReq(req) res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } defer res.Body.Close() slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatalf("Body read: %v", err) } addr := strings.TrimSpace(string(slurp)) if addr == "" { t.Fatalf("didn't get an addr in response") } return addr } first := get() second := get() return first == second } func TestTransportReusesConns(t *testing.T) { if !onSameConn(t, func(*http.Request) {}) { t.Errorf("first and second responses were on different connections") } } func TestTransportReusesConn_RequestClose(t *testing.T) { if onSameConn(t, func(r *http.Request) { r.Close = true }) { t.Errorf("first and second responses were not on different connections") } } func TestTransportReusesConn_ConnClose(t *testing.T) { if onSameConn(t, func(r *http.Request) { r.Header.Set("Connection", "close") }) { t.Errorf("first and second responses were not on different connections") } } // Tests that the Transport only keeps one pending dial open per destination address. // https://golang.org/issue/13397 func TestTransportGroupsPendingDials(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, r.RemoteAddr) }, optOnlyServer) defer st.Close() tr := &Transport{ TLSClientConfig: tlsConfigInsecure, } defer tr.CloseIdleConnections() var ( mu sync.Mutex dials = map[string]int{} ) var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Error(err) return } res, err := tr.RoundTrip(req) if err != nil { t.Error(err) return } defer res.Body.Close() slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Errorf("Body read: %v", err) } addr := strings.TrimSpace(string(slurp)) if addr == "" { t.Errorf("didn't get an addr in response") } mu.Lock() dials[addr]++ mu.Unlock() }() } wg.Wait() if len(dials) != 1 { t.Errorf("saw %d dials; want 1: %v", len(dials), dials) } tr.CloseIdleConnections() if err := retry(50, 10*time.Millisecond, func() error { cp, ok := tr.connPool().(*clientConnPool) if !ok { return fmt.Errorf("Conn pool is %T; want *clientConnPool", tr.connPool()) } cp.mu.Lock() defer cp.mu.Unlock() if len(cp.dialing) != 0 { return fmt.Errorf("dialing map = %v; want empty", cp.dialing) } if len(cp.conns) != 0 { return fmt.Errorf("conns = %v; want empty", cp.conns) } if len(cp.keys) != 0 { return fmt.Errorf("keys = %v; want empty", cp.keys) } return nil }); err != nil { t.Errorf("State of pool after CloseIdleConnections: %v", err) } } func retry(tries int, delay time.Duration, fn func() error) error { var err error for i := 0; i < tries; i++ { err = fn() if err == nil { return nil } time.Sleep(delay) } return err } func TestTransportAbortClosesPipes(t *testing.T) { shutdown := make(chan struct{}) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.(http.Flusher).Flush() <-shutdown }, optOnlyServer, ) defer st.Close() defer close(shutdown) // we must shutdown before st.Close() to avoid hanging done := make(chan struct{}) requestMade := make(chan struct{}) go func() { defer close(done) tr := &Transport{TLSClientConfig: tlsConfigInsecure} req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Fatal(err) } res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } defer res.Body.Close() close(requestMade) _, err = ioutil.ReadAll(res.Body) if err == nil { t.Error("expected error from res.Body.Read") } }() <-requestMade // Now force the serve loop to end, via closing the connection. st.closeConn() // deadlock? that's a bug. select { case <-done: case <-time.After(3 * time.Second): t.Fatal("timeout") } } // TODO: merge this with TestTransportBody to make TestTransportRequest? This // could be a table-driven test with extra goodies. func TestTransportPath(t *testing.T) { gotc := make(chan *url.URL, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { gotc <- r.URL }, optOnlyServer, ) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() const ( path = "/testpath" query = "q=1" ) surl := st.ts.URL + path + "?" + query req, err := http.NewRequest("POST", surl, nil) if err != nil { t.Fatal(err) } c := &http.Client{Transport: tr} res, err := c.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() got := <-gotc if got.Path != path { t.Errorf("Read Path = %q; want %q", got.Path, path) } if got.RawQuery != query { t.Errorf("Read RawQuery = %q; want %q", got.RawQuery, query) } } func randString(n int) string { rnd := rand.New(rand.NewSource(int64(n))) b := make([]byte, n) for i := range b { b[i] = byte(rnd.Intn(256)) } return string(b) } type panicReader struct{} func (panicReader) Read([]byte) (int, error) { panic("unexpected Read") } func (panicReader) Close() error { panic("unexpected Close") } func TestActualContentLength(t *testing.T) { tests := []struct { req *http.Request want int64 }{ // Verify we don't read from Body: 0: { req: &http.Request{Body: panicReader{}}, want: -1, }, // nil Body means 0, regardless of ContentLength: 1: { req: &http.Request{Body: nil, ContentLength: 5}, want: 0, }, // ContentLength is used if set. 2: { req: &http.Request{Body: panicReader{}, ContentLength: 5}, want: 5, }, // http.NoBody means 0, not -1. 3: { req: &http.Request{Body: go18httpNoBody()}, want: 0, }, } for i, tt := range tests { got := actualContentLength(tt.req) if got != tt.want { t.Errorf("test[%d]: got %d; want %d", i, got, tt.want) } } } func TestTransportBody(t *testing.T) { bodyTests := []struct { body string noContentLen bool }{ {body: "some message"}, {body: "some message", noContentLen: true}, {body: strings.Repeat("a", 1<<20), noContentLen: true}, {body: strings.Repeat("a", 1<<20)}, {body: randString(16<<10 - 1)}, {body: randString(16 << 10)}, {body: randString(16<<10 + 1)}, {body: randString(512<<10 - 1)}, {body: randString(512 << 10)}, {body: randString(512<<10 + 1)}, {body: randString(1<<20 - 1)}, {body: randString(1 << 20)}, {body: randString(1<<20 + 2)}, } type reqInfo struct { req *http.Request slurp []byte err error } gotc := make(chan reqInfo, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { slurp, err := ioutil.ReadAll(r.Body) if err != nil { gotc <- reqInfo{err: err} } else { gotc <- reqInfo{req: r, slurp: slurp} } }, optOnlyServer, ) defer st.Close() for i, tt := range bodyTests { tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() var body io.Reader = strings.NewReader(tt.body) if tt.noContentLen { body = struct{ io.Reader }{body} // just a Reader, hiding concrete type and other methods } req, err := http.NewRequest("POST", st.ts.URL, body) if err != nil { t.Fatalf("#%d: %v", i, err) } c := &http.Client{Transport: tr} res, err := c.Do(req) if err != nil { t.Fatalf("#%d: %v", i, err) } defer res.Body.Close() ri := <-gotc if ri.err != nil { t.Errorf("#%d: read error: %v", i, ri.err) continue } if got := string(ri.slurp); got != tt.body { t.Errorf("#%d: Read body mismatch.\n got: %q (len %d)\nwant: %q (len %d)", i, shortString(got), len(got), shortString(tt.body), len(tt.body)) } wantLen := int64(len(tt.body)) if tt.noContentLen && tt.body != "" { wantLen = -1 } if ri.req.ContentLength != wantLen { t.Errorf("#%d. handler got ContentLength = %v; want %v", i, ri.req.ContentLength, wantLen) } } } func shortString(v string) string { const maxLen = 100 if len(v) <= maxLen { return v } return fmt.Sprintf("%v[...%d bytes omitted...]%v", v[:maxLen/2], len(v)-maxLen, v[len(v)-maxLen/2:]) } func TestTransportDialTLS(t *testing.T) { var mu sync.Mutex // guards following var gotReq, didDial bool ts := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { mu.Lock() gotReq = true mu.Unlock() }, optOnlyServer, ) defer ts.Close() tr := &Transport{ DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) { mu.Lock() didDial = true mu.Unlock() cfg.InsecureSkipVerify = true c, err := tls.Dial(netw, addr, cfg) if err != nil { return nil, err } return c, c.Handshake() }, } defer tr.CloseIdleConnections() client := &http.Client{Transport: tr} res, err := client.Get(ts.ts.URL) if err != nil { t.Fatal(err) } res.Body.Close() mu.Lock() if !gotReq { t.Error("didn't get request") } if !didDial { t.Error("didn't use dial hook") } } func TestConfigureTransport(t *testing.T) { t1 := &http.Transport{} err := ConfigureTransport(t1) if err == errTransportVersion { t.Skip(err) } if err != nil { t.Fatal(err) } if got := fmt.Sprintf("%#v", t1); !strings.Contains(got, `"h2"`) { // Laziness, to avoid buildtags. t.Errorf("stringification of HTTP/1 transport didn't contain \"h2\": %v", got) } wantNextProtos := []string{"h2", "http/1.1"} if t1.TLSClientConfig == nil { t.Errorf("nil t1.TLSClientConfig") } else if !reflect.DeepEqual(t1.TLSClientConfig.NextProtos, wantNextProtos) { t.Errorf("TLSClientConfig.NextProtos = %q; want %q", t1.TLSClientConfig.NextProtos, wantNextProtos) } if err := ConfigureTransport(t1); err == nil { t.Error("unexpected success on second call to ConfigureTransport") } // And does it work? st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, r.Proto) }, optOnlyServer) defer st.Close() t1.TLSClientConfig.InsecureSkipVerify = true c := &http.Client{Transport: t1} res, err := c.Get(st.ts.URL) if err != nil { t.Fatal(err) } slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } if got, want := string(slurp), "HTTP/2.0"; got != want { t.Errorf("body = %q; want %q", got, want) } } type capitalizeReader struct { r io.Reader } func (cr capitalizeReader) Read(p []byte) (n int, err error) { n, err = cr.r.Read(p) for i, b := range p[:n] { if b >= 'a' && b <= 'z' { p[i] = b - ('a' - 'A') } } return } type flushWriter struct { w io.Writer } func (fw flushWriter) Write(p []byte) (n int, err error) { n, err = fw.w.Write(p) if f, ok := fw.w.(http.Flusher); ok { f.Flush() } return } type clientTester struct { t *testing.T tr *Transport sc, cc net.Conn // server and client conn fr *Framer // server's framer client func() error server func() error } func newClientTester(t *testing.T) *clientTester { var dialOnce struct { sync.Mutex dialed bool } ct := &clientTester{ t: t, } ct.tr = &Transport{ TLSClientConfig: tlsConfigInsecure, DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { dialOnce.Lock() defer dialOnce.Unlock() if dialOnce.dialed { return nil, errors.New("only one dial allowed in test mode") } dialOnce.dialed = true return ct.cc, nil }, } ln := newLocalListener(t) cc, err := net.Dial("tcp", ln.Addr().String()) if err != nil { t.Fatal(err) } sc, err := ln.Accept() if err != nil { t.Fatal(err) } ln.Close() ct.cc = cc ct.sc = sc ct.fr = NewFramer(sc, sc) return ct } func newLocalListener(t *testing.T) net.Listener { ln, err := net.Listen("tcp4", "127.0.0.1:0") if err == nil { return ln } ln, err = net.Listen("tcp6", "[::1]:0") if err != nil { t.Fatal(err) } return ln } func (ct *clientTester) greet(settings ...Setting) { buf := make([]byte, len(ClientPreface)) _, err := io.ReadFull(ct.sc, buf) if err != nil { ct.t.Fatalf("reading client preface: %v", err) } f, err := ct.fr.ReadFrame() if err != nil { ct.t.Fatalf("Reading client settings frame: %v", err) } if sf, ok := f.(*SettingsFrame); !ok { ct.t.Fatalf("Wanted client settings frame; got %v", f) _ = sf // stash it away? } if err := ct.fr.WriteSettings(settings...); err != nil { ct.t.Fatal(err) } if err := ct.fr.WriteSettingsAck(); err != nil { ct.t.Fatal(err) } } func (ct *clientTester) readNonSettingsFrame() (Frame, error) { for { f, err := ct.fr.ReadFrame() if err != nil { return nil, err } if _, ok := f.(*SettingsFrame); ok { continue } return f, nil } } func (ct *clientTester) cleanup() { ct.tr.CloseIdleConnections() } func (ct *clientTester) run() { errc := make(chan error, 2) ct.start("client", errc, ct.client) ct.start("server", errc, ct.server) defer ct.cleanup() for i := 0; i < 2; i++ { if err := <-errc; err != nil { ct.t.Error(err) return } } } func (ct *clientTester) start(which string, errc chan<- error, fn func() error) { go func() { finished := false var err error defer func() { if !finished { err = fmt.Errorf("%s goroutine didn't finish.", which) } else if err != nil { err = fmt.Errorf("%s: %v", which, err) } errc <- err }() err = fn() finished = true }() } func (ct *clientTester) readFrame() (Frame, error) { return readFrameTimeout(ct.fr, 2*time.Second) } func (ct *clientTester) firstHeaders() (*HeadersFrame, error) { for { f, err := ct.readFrame() if err != nil { return nil, fmt.Errorf("ReadFrame while waiting for Headers: %v", err) } switch f.(type) { case *WindowUpdateFrame, *SettingsFrame: continue } hf, ok := f.(*HeadersFrame) if !ok { return nil, fmt.Errorf("Got %T; want HeadersFrame", f) } return hf, nil } } type countingReader struct { n *int64 } func (r countingReader) Read(p []byte) (n int, err error) { for i := range p { p[i] = byte(i) } atomic.AddInt64(r.n, int64(len(p))) return len(p), err } func TestTransportReqBodyAfterResponse_200(t *testing.T) { testTransportReqBodyAfterResponse(t, 200) } func TestTransportReqBodyAfterResponse_403(t *testing.T) { testTransportReqBodyAfterResponse(t, 403) } func testTransportReqBodyAfterResponse(t *testing.T, status int) { const bodySize = 10 << 20 clientDone := make(chan struct{}) ct := newClientTester(t) ct.client = func() error { defer ct.cc.(*net.TCPConn).CloseWrite() defer close(clientDone) var n int64 // atomic req, err := http.NewRequest("PUT", "https://dummy.tld/", io.LimitReader(countingReader{&n}, bodySize)) if err != nil { return err } res, err := ct.tr.RoundTrip(req) if err != nil { return fmt.Errorf("RoundTrip: %v", err) } defer res.Body.Close() if res.StatusCode != status { return fmt.Errorf("status code = %v; want %v", res.StatusCode, status) } slurp, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("Slurp: %v", err) } if len(slurp) > 0 { return fmt.Errorf("unexpected body: %q", slurp) } if status == 200 { if got := atomic.LoadInt64(&n); got != bodySize { return fmt.Errorf("For 200 response, Transport wrote %d bytes; want %d", got, bodySize) } } else { if got := atomic.LoadInt64(&n); got == 0 || got >= bodySize { return fmt.Errorf("For %d response, Transport wrote %d bytes; want (0,%d) exclusive", status, got, bodySize) } } return nil } ct.server = func() error { ct.greet() var buf bytes.Buffer enc := hpack.NewEncoder(&buf) var dataRecv int64 var closed bool for { f, err := ct.fr.ReadFrame() if err != nil { select { case <-clientDone: // If the client's done, it // will have reported any // errors on its side. return nil default: return err } } //println(fmt.Sprintf("server got frame: %v", f)) switch f := f.(type) { case *WindowUpdateFrame, *SettingsFrame: case *HeadersFrame: if !f.HeadersEnded() { return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) } if f.StreamEnded() { return fmt.Errorf("headers contains END_STREAM unexpectedly: %v", f) } case *DataFrame: dataLen := len(f.Data()) if dataLen > 0 { if dataRecv == 0 { enc.WriteField(hpack.HeaderField{Name: ":status", Value: strconv.Itoa(status)}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.StreamID, EndHeaders: true, EndStream: false, BlockFragment: buf.Bytes(), }) } if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil { return err } if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil { return err } } dataRecv += int64(dataLen) if !closed && ((status != 200 && dataRecv > 0) || (status == 200 && dataRecv == bodySize)) { closed = true if err := ct.fr.WriteData(f.StreamID, true, nil); err != nil { return err } } default: return fmt.Errorf("Unexpected client frame %v", f) } } } ct.run() } // See golang.org/issue/13444 func TestTransportFullDuplex(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) // redundant but for clarity w.(http.Flusher).Flush() io.Copy(flushWriter{w}, capitalizeReader{r.Body}) fmt.Fprintf(w, "bye.\n") }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() c := &http.Client{Transport: tr} pr, pw := io.Pipe() req, err := http.NewRequest("PUT", st.ts.URL, ioutil.NopCloser(pr)) if err != nil { t.Fatal(err) } req.ContentLength = -1 res, err := c.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() if res.StatusCode != 200 { t.Fatalf("StatusCode = %v; want %v", res.StatusCode, 200) } bs := bufio.NewScanner(res.Body) want := func(v string) { if !bs.Scan() { t.Fatalf("wanted to read %q but Scan() = false, err = %v", v, bs.Err()) } } write := func(v string) { _, err := io.WriteString(pw, v) if err != nil { t.Fatalf("pipe write: %v", err) } } write("foo\n") want("FOO") write("bar\n") want("BAR") pw.Close() want("bye.") if err := bs.Err(); err != nil { t.Fatal(err) } } func TestTransportConnectRequest(t *testing.T) { gotc := make(chan *http.Request, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { gotc <- r }, optOnlyServer) defer st.Close() u, err := url.Parse(st.ts.URL) if err != nil { t.Fatal(err) } tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() c := &http.Client{Transport: tr} tests := []struct { req *http.Request want string }{ { req: &http.Request{ Method: "CONNECT", Header: http.Header{}, URL: u, }, want: u.Host, }, { req: &http.Request{ Method: "CONNECT", Header: http.Header{}, URL: u, Host: "example.com:123", }, want: "example.com:123", }, } for i, tt := range tests { res, err := c.Do(tt.req) if err != nil { t.Errorf("%d. RoundTrip = %v", i, err) continue } res.Body.Close() req := <-gotc if req.Method != "CONNECT" { t.Errorf("method = %q; want CONNECT", req.Method) } if req.Host != tt.want { t.Errorf("Host = %q; want %q", req.Host, tt.want) } if req.URL.Host != tt.want { t.Errorf("URL.Host = %q; want %q", req.URL.Host, tt.want) } } } type headerType int const ( noHeader headerType = iota // omitted oneHeader splitHeader // broken into continuation on purpose ) const ( f0 = noHeader f1 = oneHeader f2 = splitHeader d0 = false d1 = true ) // Test all 36 combinations of response frame orders: // (3 ways of 100-continue) * (2 ways of headers) * (2 ways of data) * (3 ways of trailers):func TestTransportResponsePattern_00f0(t *testing.T) { testTransportResponsePattern(h0, h1, false, h0) } // Generated by http://play.golang.org/p/SScqYKJYXd func TestTransportResPattern_c0h1d0t0(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f0) } func TestTransportResPattern_c0h1d0t1(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f1) } func TestTransportResPattern_c0h1d0t2(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f2) } func TestTransportResPattern_c0h1d1t0(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f0) } func TestTransportResPattern_c0h1d1t1(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f1) } func TestTransportResPattern_c0h1d1t2(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f2) } func TestTransportResPattern_c0h2d0t0(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f0) } func TestTransportResPattern_c0h2d0t1(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f1) } func TestTransportResPattern_c0h2d0t2(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f2) } func TestTransportResPattern_c0h2d1t0(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f0) } func TestTransportResPattern_c0h2d1t1(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f1) } func TestTransportResPattern_c0h2d1t2(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f2) } func TestTransportResPattern_c1h1d0t0(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f0) } func TestTransportResPattern_c1h1d0t1(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f1) } func TestTransportResPattern_c1h1d0t2(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f2) } func TestTransportResPattern_c1h1d1t0(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f0) } func TestTransportResPattern_c1h1d1t1(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f1) } func TestTransportResPattern_c1h1d1t2(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f2) } func TestTransportResPattern_c1h2d0t0(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f0) } func TestTransportResPattern_c1h2d0t1(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f1) } func TestTransportResPattern_c1h2d0t2(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f2) } func TestTransportResPattern_c1h2d1t0(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f0) } func TestTransportResPattern_c1h2d1t1(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f1) } func TestTransportResPattern_c1h2d1t2(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f2) } func TestTransportResPattern_c2h1d0t0(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f0) } func TestTransportResPattern_c2h1d0t1(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f1) } func TestTransportResPattern_c2h1d0t2(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f2) } func TestTransportResPattern_c2h1d1t0(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f0) } func TestTransportResPattern_c2h1d1t1(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f1) } func TestTransportResPattern_c2h1d1t2(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f2) } func TestTransportResPattern_c2h2d0t0(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f0) } func TestTransportResPattern_c2h2d0t1(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f1) } func TestTransportResPattern_c2h2d0t2(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f2) } func TestTransportResPattern_c2h2d1t0(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f0) } func TestTransportResPattern_c2h2d1t1(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f1) } func TestTransportResPattern_c2h2d1t2(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f2) } func testTransportResPattern(t *testing.T, expect100Continue, resHeader headerType, withData bool, trailers headerType) { const reqBody = "some request body" const resBody = "some response body" if resHeader == noHeader { // TODO: test 100-continue followed by immediate // server stream reset, without headers in the middle? panic("invalid combination") } ct := newClientTester(t) ct.client = func() error { req, _ := http.NewRequest("POST", "https://dummy.tld/", strings.NewReader(reqBody)) if expect100Continue != noHeader { req.Header.Set("Expect", "100-continue") } res, err := ct.tr.RoundTrip(req) if err != nil { return fmt.Errorf("RoundTrip: %v", err) } defer res.Body.Close() if res.StatusCode != 200 { return fmt.Errorf("status code = %v; want 200", res.StatusCode) } slurp, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("Slurp: %v", err) } wantBody := resBody if !withData { wantBody = "" } if string(slurp) != wantBody { return fmt.Errorf("body = %q; want %q", slurp, wantBody) } if trailers == noHeader { if len(res.Trailer) > 0 { t.Errorf("Trailer = %v; want none", res.Trailer) } } else { want := http.Header{"Some-Trailer": {"some-value"}} if !reflect.DeepEqual(res.Trailer, want) { t.Errorf("Trailer = %v; want %v", res.Trailer, want) } } return nil } ct.server = func() error { ct.greet() var buf bytes.Buffer enc := hpack.NewEncoder(&buf) for { f, err := ct.fr.ReadFrame() if err != nil { return err } endStream := false send := func(mode headerType) { hbf := buf.Bytes() switch mode { case oneHeader: ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.Header().StreamID, EndHeaders: true, EndStream: endStream, BlockFragment: hbf, }) case splitHeader: if len(hbf) < 2 { panic("too small") } ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.Header().StreamID, EndHeaders: false, EndStream: endStream, BlockFragment: hbf[:1], }) ct.fr.WriteContinuation(f.Header().StreamID, true, hbf[1:]) default: panic("bogus mode") } } switch f := f.(type) { case *WindowUpdateFrame, *SettingsFrame: case *DataFrame: if !f.StreamEnded() { // No need to send flow control tokens. The test request body is tiny. continue } // Response headers (1+ frames; 1 or 2 in this test, but never 0) { buf.Reset() enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) enc.WriteField(hpack.HeaderField{Name: "x-foo", Value: "blah"}) enc.WriteField(hpack.HeaderField{Name: "x-bar", Value: "more"}) if trailers != noHeader { enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "some-trailer"}) } endStream = withData == false && trailers == noHeader send(resHeader) } if withData { endStream = trailers == noHeader ct.fr.WriteData(f.StreamID, endStream, []byte(resBody)) } if trailers != noHeader { endStream = true buf.Reset() enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "some-value"}) send(trailers) } if endStream { return nil } case *HeadersFrame: if expect100Continue != noHeader { buf.Reset() enc.WriteField(hpack.HeaderField{Name: ":status", Value: "100"}) send(expect100Continue) } } } } ct.run() } func TestTransportReceiveUndeclaredTrailer(t *testing.T) { ct := newClientTester(t) ct.client = func() error { req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) res, err := ct.tr.RoundTrip(req) if err != nil { return fmt.Errorf("RoundTrip: %v", err) } defer res.Body.Close() if res.StatusCode != 200 { return fmt.Errorf("status code = %v; want 200", res.StatusCode) } slurp, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("res.Body ReadAll error = %q, %v; want %v", slurp, err, nil) } if len(slurp) > 0 { return fmt.Errorf("body = %q; want nothing", slurp) } if _, ok := res.Trailer["Some-Trailer"]; !ok { return fmt.Errorf("expected Some-Trailer") } return nil } ct.server = func() error { ct.greet() var n int var hf *HeadersFrame for hf == nil && n < 10 { f, err := ct.fr.ReadFrame() if err != nil { return err } hf, _ = f.(*HeadersFrame) n++ } var buf bytes.Buffer enc := hpack.NewEncoder(&buf) // send headers without Trailer header enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: hf.StreamID, EndHeaders: true, EndStream: false, BlockFragment: buf.Bytes(), }) // send trailers buf.Reset() enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "I'm an undeclared Trailer!"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: hf.StreamID, EndHeaders: true, EndStream: true, BlockFragment: buf.Bytes(), }) return nil } ct.run() } func TestTransportInvalidTrailer_Pseudo1(t *testing.T) { testTransportInvalidTrailer_Pseudo(t, oneHeader) } func TestTransportInvalidTrailer_Pseudo2(t *testing.T) { testTransportInvalidTrailer_Pseudo(t, splitHeader) } func testTransportInvalidTrailer_Pseudo(t *testing.T, trailers headerType) { testInvalidTrailer(t, trailers, pseudoHeaderError(":colon"), func(enc *hpack.Encoder) { enc.WriteField(hpack.HeaderField{Name: ":colon", Value: "foo"}) enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) }) } func TestTransportInvalidTrailer_Capital1(t *testing.T) { testTransportInvalidTrailer_Capital(t, oneHeader) } func TestTransportInvalidTrailer_Capital2(t *testing.T) { testTransportInvalidTrailer_Capital(t, splitHeader) } func testTransportInvalidTrailer_Capital(t *testing.T, trailers headerType) { testInvalidTrailer(t, trailers, headerFieldNameError("Capital"), func(enc *hpack.Encoder) { enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) enc.WriteField(hpack.HeaderField{Name: "Capital", Value: "bad"}) }) } func TestTransportInvalidTrailer_EmptyFieldName(t *testing.T) { testInvalidTrailer(t, oneHeader, headerFieldNameError(""), func(enc *hpack.Encoder) { enc.WriteField(hpack.HeaderField{Name: "", Value: "bad"}) }) } func TestTransportInvalidTrailer_BinaryFieldValue(t *testing.T) { testInvalidTrailer(t, oneHeader, headerFieldValueError("has\nnewline"), func(enc *hpack.Encoder) { enc.WriteField(hpack.HeaderField{Name: "x", Value: "has\nnewline"}) }) } func testInvalidTrailer(t *testing.T, trailers headerType, wantErr error, writeTrailer func(*hpack.Encoder)) { ct := newClientTester(t) ct.client = func() error { req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) res, err := ct.tr.RoundTrip(req) if err != nil { return fmt.Errorf("RoundTrip: %v", err) } defer res.Body.Close() if res.StatusCode != 200 { return fmt.Errorf("status code = %v; want 200", res.StatusCode) } slurp, err := ioutil.ReadAll(res.Body) se, ok := err.(StreamError) if !ok || se.Cause != wantErr { return fmt.Errorf("res.Body ReadAll error = %q, %#v; want StreamError with cause %T, %#v", slurp, err, wantErr, wantErr) } if len(slurp) > 0 { return fmt.Errorf("body = %q; want nothing", slurp) } return nil } ct.server = func() error { ct.greet() var buf bytes.Buffer enc := hpack.NewEncoder(&buf) for { f, err := ct.fr.ReadFrame() if err != nil { return err } switch f := f.(type) { case *HeadersFrame: var endStream bool send := func(mode headerType) { hbf := buf.Bytes() switch mode { case oneHeader: ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.StreamID, EndHeaders: true, EndStream: endStream, BlockFragment: hbf, }) case splitHeader: if len(hbf) < 2 { panic("too small") } ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.StreamID, EndHeaders: false, EndStream: endStream, BlockFragment: hbf[:1], }) ct.fr.WriteContinuation(f.StreamID, true, hbf[1:]) default: panic("bogus mode") } } // Response headers (1+ frames; 1 or 2 in this test, but never 0) { buf.Reset() enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "declared"}) endStream = false send(oneHeader) } // Trailers: { endStream = true buf.Reset() writeTrailer(enc) send(trailers) } return nil } } } ct.run() } // headerListSize returns the HTTP2 header list size of h. // http://httpwg.org/specs/rfc7540.html#SETTINGS_MAX_HEADER_LIST_SIZE // http://httpwg.org/specs/rfc7540.html#MaxHeaderBlock func headerListSize(h http.Header) (size uint32) { for k, vv := range h { for _, v := range vv { hf := hpack.HeaderField{Name: k, Value: v} size += hf.Size() } } return size } // padHeaders adds data to an http.Header until headerListSize(h) == // limit. Due to the way header list sizes are calculated, padHeaders // cannot add fewer than len("Pad-Headers") + 32 bytes to h, and will // call t.Fatal if asked to do so. PadHeaders first reserves enough // space for an empty "Pad-Headers" key, then adds as many copies of // filler as possible. Any remaining bytes necessary to push the // header list size up to limit are added to h["Pad-Headers"]. func padHeaders(t *testing.T, h http.Header, limit uint64, filler string) { if limit > 0xffffffff { t.Fatalf("padHeaders: refusing to pad to more than 2^32-1 bytes. limit = %v", limit) } hf := hpack.HeaderField{Name: "Pad-Headers", Value: ""} minPadding := uint64(hf.Size()) size := uint64(headerListSize(h)) minlimit := size + minPadding if limit < minlimit { t.Fatalf("padHeaders: limit %v < %v", limit, minlimit) } // Use a fixed-width format for name so that fieldSize // remains constant. nameFmt := "Pad-Headers-%06d" hf = hpack.HeaderField{Name: fmt.Sprintf(nameFmt, 1), Value: filler} fieldSize := uint64(hf.Size()) // Add as many complete filler values as possible, leaving // room for at least one empty "Pad-Headers" key. limit = limit - minPadding for i := 0; size+fieldSize < limit; i++ { name := fmt.Sprintf(nameFmt, i) h.Add(name, filler) size += fieldSize } // Add enough bytes to reach limit. remain := limit - size lastValue := strings.Repeat("*", int(remain)) h.Add("Pad-Headers", lastValue) } func TestPadHeaders(t *testing.T) { check := func(h http.Header, limit uint32, fillerLen int) { if h == nil { h = make(http.Header) } filler := strings.Repeat("f", fillerLen) padHeaders(t, h, uint64(limit), filler) gotSize := headerListSize(h) if gotSize != limit { t.Errorf("Got size = %v; want %v", gotSize, limit) } } // Try all possible combinations for small fillerLen and limit. hf := hpack.HeaderField{Name: "Pad-Headers", Value: ""} minLimit := hf.Size() for limit := minLimit; limit <= 128; limit++ { for fillerLen := 0; uint32(fillerLen) <= limit; fillerLen++ { check(nil, limit, fillerLen) } } // Try a few tests with larger limits, plus cumulative // tests. Since these tests are cumulative, tests[i+1].limit // must be >= tests[i].limit + minLimit. See the comment on // padHeaders for more info on why the limit arg has this // restriction. tests := []struct { fillerLen int limit uint32 }{ { fillerLen: 64, limit: 1024, }, { fillerLen: 1024, limit: 1286, }, { fillerLen: 256, limit: 2048, }, { fillerLen: 1024, limit: 10 * 1024, }, { fillerLen: 1023, limit: 11 * 1024, }, } h := make(http.Header) for _, tc := range tests { check(nil, tc.limit, tc.fillerLen) check(h, tc.limit, tc.fillerLen) } } func TestTransportChecksRequestHeaderListSize(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { // Consume body & force client to send // trailers before writing response. // ioutil.ReadAll returns non-nil err for // requests that attempt to send greater than // maxHeaderListSize bytes of trailers, since // those requests generate a stream reset. ioutil.ReadAll(r.Body) r.Body.Close() }, func(ts *httptest.Server) { ts.Config.MaxHeaderBytes = 16 << 10 }, optOnlyServer, optQuiet, ) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() checkRoundTrip := func(req *http.Request, wantErr error, desc string) { res, err := tr.RoundTrip(req) if err != wantErr { if res != nil { res.Body.Close() } t.Errorf("%v: RoundTrip err = %v; want %v", desc, err, wantErr) return } if err == nil { if res == nil { t.Errorf("%v: response nil; want non-nil.", desc) return } defer res.Body.Close() if res.StatusCode != http.StatusOK { t.Errorf("%v: response status = %v; want %v", desc, res.StatusCode, http.StatusOK) } return } if res != nil { t.Errorf("%v: RoundTrip err = %v but response non-nil", desc, err) } } headerListSizeForRequest := func(req *http.Request) (size uint64) { contentLen := actualContentLength(req) trailers, err := commaSeparatedTrailers(req) if err != nil { t.Fatalf("headerListSizeForRequest: %v", err) } cc := &ClientConn{peerMaxHeaderListSize: 0xffffffffffffffff} cc.henc = hpack.NewEncoder(&cc.hbuf) cc.mu.Lock() hdrs, err := cc.encodeHeaders(req, true, trailers, contentLen) cc.mu.Unlock() if err != nil { t.Fatalf("headerListSizeForRequest: %v", err) } hpackDec := hpack.NewDecoder(initialHeaderTableSize, func(hf hpack.HeaderField) { size += uint64(hf.Size()) }) if len(hdrs) > 0 { if _, err := hpackDec.Write(hdrs); err != nil { t.Fatalf("headerListSizeForRequest: %v", err) } } return size } // Create a new Request for each test, rather than reusing the // same Request, to avoid a race when modifying req.Headers. // See https://github.com/golang/go/issues/21316 newRequest := func() *http.Request { // Body must be non-nil to enable writing trailers. body := strings.NewReader("hello") req, err := http.NewRequest("POST", st.ts.URL, body) if err != nil { t.Fatalf("newRequest: NewRequest: %v", err) } return req } // Make an arbitrary request to ensure we get the server's // settings frame and initialize peerMaxHeaderListSize. req := newRequest() checkRoundTrip(req, nil, "Initial request") // Get the ClientConn associated with the request and validate // peerMaxHeaderListSize. addr := authorityAddr(req.URL.Scheme, req.URL.Host) cc, err := tr.connPool().GetClientConn(req, addr) if err != nil { t.Fatalf("GetClientConn: %v", err) } cc.mu.Lock() peerSize := cc.peerMaxHeaderListSize cc.mu.Unlock() st.scMu.Lock() wantSize := uint64(st.sc.maxHeaderListSize()) st.scMu.Unlock() if peerSize != wantSize { t.Errorf("peerMaxHeaderListSize = %v; want %v", peerSize, wantSize) } // Sanity check peerSize. (*serverConn) maxHeaderListSize adds // 320 bytes of padding. wantHeaderBytes := uint64(st.ts.Config.MaxHeaderBytes) + 320 if peerSize != wantHeaderBytes { t.Errorf("peerMaxHeaderListSize = %v; want %v.", peerSize, wantHeaderBytes) } // Pad headers & trailers, but stay under peerSize. req = newRequest() req.Header = make(http.Header) req.Trailer = make(http.Header) filler := strings.Repeat("*", 1024) padHeaders(t, req.Trailer, peerSize, filler) // cc.encodeHeaders adds some default headers to the request, // so we need to leave room for those. defaultBytes := headerListSizeForRequest(req) padHeaders(t, req.Header, peerSize-defaultBytes, filler) checkRoundTrip(req, nil, "Headers & Trailers under limit") // Add enough header bytes to push us over peerSize. req = newRequest() req.Header = make(http.Header) padHeaders(t, req.Header, peerSize, filler) checkRoundTrip(req, errRequestHeaderListSize, "Headers over limit") // Push trailers over the limit. req = newRequest() req.Trailer = make(http.Header) padHeaders(t, req.Trailer, peerSize+1, filler) checkRoundTrip(req, errRequestHeaderListSize, "Trailers over limit") // Send headers with a single large value. req = newRequest() filler = strings.Repeat("*", int(peerSize)) req.Header = make(http.Header) req.Header.Set("Big", filler) checkRoundTrip(req, errRequestHeaderListSize, "Single large header") // Send trailers with a single large value. req = newRequest() req.Trailer = make(http.Header) req.Trailer.Set("Big", filler) checkRoundTrip(req, errRequestHeaderListSize, "Single large trailer") } func TestTransportChecksResponseHeaderListSize(t *testing.T) { ct := newClientTester(t) ct.client = func() error { req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) res, err := ct.tr.RoundTrip(req) if err != errResponseHeaderListSize { if res != nil { res.Body.Close() } size := int64(0) for k, vv := range res.Header { for _, v := range vv { size += int64(len(k)) + int64(len(v)) + 32 } } return fmt.Errorf("RoundTrip Error = %v (and %d bytes of response headers); want errResponseHeaderListSize", err, size) } return nil } ct.server = func() error { ct.greet() var buf bytes.Buffer enc := hpack.NewEncoder(&buf) for { f, err := ct.fr.ReadFrame() if err != nil { return err } switch f := f.(type) { case *HeadersFrame: enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) large := strings.Repeat("a", 1<<10) for i := 0; i < 5042; i++ { enc.WriteField(hpack.HeaderField{Name: large, Value: large}) } if size, want := buf.Len(), 6329; size != want { // Note: this number might change if // our hpack implementation // changes. That's fine. This is // just a sanity check that our // response can fit in a single // header block fragment frame. return fmt.Errorf("encoding over 10MB of duplicate keypairs took %d bytes; expected %d", size, want) } ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.StreamID, EndHeaders: true, EndStream: true, BlockFragment: buf.Bytes(), }) return nil } } } ct.run() } // Test that the the Transport returns a typed error from Response.Body.Read calls // when the server sends an error. (here we use a panic, since that should generate // a stream error, but others like cancel should be similar) func TestTransportBodyReadErrorType(t *testing.T) { doPanic := make(chan bool, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.(http.Flusher).Flush() // force headers out <-doPanic panic("boom") }, optOnlyServer, optQuiet, ) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() c := &http.Client{Transport: tr} res, err := c.Get(st.ts.URL) if err != nil { t.Fatal(err) } defer res.Body.Close() doPanic <- true buf := make([]byte, 100) n, err := res.Body.Read(buf) want := StreamError{StreamID: 0x1, Code: 0x2} if !reflect.DeepEqual(want, err) { t.Errorf("Read = %v, %#v; want error %#v", n, err, want) } } // golang.org/issue/13924 // This used to fail after many iterations, especially with -race: // go test -v -run=TestTransportDoubleCloseOnWriteError -count=500 -race func TestTransportDoubleCloseOnWriteError(t *testing.T) { var ( mu sync.Mutex conn net.Conn // to close if set ) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { mu.Lock() defer mu.Unlock() if conn != nil { conn.Close() } }, optOnlyServer, ) defer st.Close() tr := &Transport{ TLSClientConfig: tlsConfigInsecure, DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { tc, err := tls.Dial(network, addr, cfg) if err != nil { return nil, err } mu.Lock() defer mu.Unlock() conn = tc return tc, nil }, } defer tr.CloseIdleConnections() c := &http.Client{Transport: tr} c.Get(st.ts.URL) } // Test that the http1 Transport.DisableKeepAlives option is respected // and connections are closed as soon as idle. // See golang.org/issue/14008 func TestTransportDisableKeepAlives(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hi") }, optOnlyServer, ) defer st.Close() connClosed := make(chan struct{}) // closed on tls.Conn.Close tr := &Transport{ t1: &http.Transport{ DisableKeepAlives: true, }, TLSClientConfig: tlsConfigInsecure, DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { tc, err := tls.Dial(network, addr, cfg) if err != nil { return nil, err } return ¬eCloseConn{Conn: tc, closefn: func() { close(connClosed) }}, nil }, } c := &http.Client{Transport: tr} res, err := c.Get(st.ts.URL) if err != nil { t.Fatal(err) } if _, err := ioutil.ReadAll(res.Body); err != nil { t.Fatal(err) } defer res.Body.Close() select { case <-connClosed: case <-time.After(1 * time.Second): t.Errorf("timeout") } } // Test concurrent requests with Transport.DisableKeepAlives. We can share connections, // but when things are totally idle, it still needs to close. func TestTransportDisableKeepAlives_Concurrency(t *testing.T) { const D = 25 * time.Millisecond st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { time.Sleep(D) io.WriteString(w, "hi") }, optOnlyServer, ) defer st.Close() var dials int32 var conns sync.WaitGroup tr := &Transport{ t1: &http.Transport{ DisableKeepAlives: true, }, TLSClientConfig: tlsConfigInsecure, DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { tc, err := tls.Dial(network, addr, cfg) if err != nil { return nil, err } atomic.AddInt32(&dials, 1) conns.Add(1) return ¬eCloseConn{Conn: tc, closefn: func() { conns.Done() }}, nil }, } c := &http.Client{Transport: tr} var reqs sync.WaitGroup const N = 20 for i := 0; i < N; i++ { reqs.Add(1) if i == N-1 { // For the final request, try to make all the // others close. This isn't verified in the // count, other than the Log statement, since // it's so timing dependent. This test is // really to make sure we don't interrupt a // valid request. time.Sleep(D * 2) } go func() { defer reqs.Done() res, err := c.Get(st.ts.URL) if err != nil { t.Error(err) return } if _, err := ioutil.ReadAll(res.Body); err != nil { t.Error(err) return } res.Body.Close() }() } reqs.Wait() conns.Wait() t.Logf("did %d dials, %d requests", atomic.LoadInt32(&dials), N) } type noteCloseConn struct { net.Conn onceClose sync.Once closefn func() } func (c *noteCloseConn) Close() error { c.onceClose.Do(c.closefn) return c.Conn.Close() } func isTimeout(err error) bool { switch err := err.(type) { case nil: return false case *url.Error: return isTimeout(err.Err) case net.Error: return err.Timeout() } return false } // Test that the http1 Transport.ResponseHeaderTimeout option and cancel is sent. func TestTransportResponseHeaderTimeout_NoBody(t *testing.T) { testTransportResponseHeaderTimeout(t, false) } func TestTransportResponseHeaderTimeout_Body(t *testing.T) { testTransportResponseHeaderTimeout(t, true) } func testTransportResponseHeaderTimeout(t *testing.T, body bool) { ct := newClientTester(t) ct.tr.t1 = &http.Transport{ ResponseHeaderTimeout: 5 * time.Millisecond, } ct.client = func() error { c := &http.Client{Transport: ct.tr} var err error var n int64 const bodySize = 4 << 20 if body { _, err = c.Post("https://dummy.tld/", "text/foo", io.LimitReader(countingReader{&n}, bodySize)) } else { _, err = c.Get("https://dummy.tld/") } if !isTimeout(err) { t.Errorf("client expected timeout error; got %#v", err) } if body && n != bodySize { t.Errorf("only read %d bytes of body; want %d", n, bodySize) } return nil } ct.server = func() error { ct.greet() for { f, err := ct.fr.ReadFrame() if err != nil { t.Logf("ReadFrame: %v", err) return nil } switch f := f.(type) { case *DataFrame: dataLen := len(f.Data()) if dataLen > 0 { if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil { return err } if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil { return err } } case *RSTStreamFrame: if f.StreamID == 1 && f.ErrCode == ErrCodeCancel { return nil } } } } ct.run() } func TestTransportDisableCompression(t *testing.T) { const body = "sup" st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { want := http.Header{ "User-Agent": []string{"Go-http-client/2.0"}, } if !reflect.DeepEqual(r.Header, want) { t.Errorf("request headers = %v; want %v", r.Header, want) } }, optOnlyServer) defer st.Close() tr := &Transport{ TLSClientConfig: tlsConfigInsecure, t1: &http.Transport{ DisableCompression: true, }, } defer tr.CloseIdleConnections() req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Fatal(err) } res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } defer res.Body.Close() } // RFC 7540 section 8.1.2.2 func TestTransportRejectsConnHeaders(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { var got []string for k := range r.Header { got = append(got, k) } sort.Strings(got) w.Header().Set("Got-Header", strings.Join(got, ",")) }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() tests := []struct { key string value []string want string }{ { key: "Upgrade", value: []string{"anything"}, want: "ERROR: http2: invalid Upgrade request header: [\"anything\"]", }, { key: "Connection", value: []string{"foo"}, want: "ERROR: http2: invalid Connection request header: [\"foo\"]", }, { key: "Connection", value: []string{"close"}, want: "Accept-Encoding,User-Agent", }, { key: "Connection", value: []string{"close", "something-else"}, want: "ERROR: http2: invalid Connection request header: [\"close\" \"something-else\"]", }, { key: "Connection", value: []string{"keep-alive"}, want: "Accept-Encoding,User-Agent", }, { key: "Proxy-Connection", // just deleted and ignored value: []string{"keep-alive"}, want: "Accept-Encoding,User-Agent", }, { key: "Transfer-Encoding", value: []string{""}, want: "Accept-Encoding,User-Agent", }, { key: "Transfer-Encoding", value: []string{"foo"}, want: "ERROR: http2: invalid Transfer-Encoding request header: [\"foo\"]", }, { key: "Transfer-Encoding", value: []string{"chunked"}, want: "Accept-Encoding,User-Agent", }, { key: "Transfer-Encoding", value: []string{"chunked", "other"}, want: "ERROR: http2: invalid Transfer-Encoding request header: [\"chunked\" \"other\"]", }, { key: "Content-Length", value: []string{"123"}, want: "Accept-Encoding,User-Agent", }, { key: "Keep-Alive", value: []string{"doop"}, want: "Accept-Encoding,User-Agent", }, } for _, tt := range tests { req, _ := http.NewRequest("GET", st.ts.URL, nil) req.Header[tt.key] = tt.value res, err := tr.RoundTrip(req) var got string if err != nil { got = fmt.Sprintf("ERROR: %v", err) } else { got = res.Header.Get("Got-Header") res.Body.Close() } if got != tt.want { t.Errorf("For key %q, value %q, got = %q; want %q", tt.key, tt.value, got, tt.want) } } } // golang.org/issue/14048 func TestTransportFailsOnInvalidHeaders(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { var got []string for k := range r.Header { got = append(got, k) } sort.Strings(got) w.Header().Set("Got-Header", strings.Join(got, ",")) }, optOnlyServer) defer st.Close() tests := [...]struct { h http.Header wantErr string }{ 0: { h: http.Header{"with space": {"foo"}}, wantErr: `invalid HTTP header name "with space"`, }, 1: { h: http.Header{"name": {"БрÑд"}}, wantErr: "", // okay }, 2: { h: http.Header{"имÑ": {"Brad"}}, wantErr: `invalid HTTP header name "имÑ"`, }, 3: { h: http.Header{"foo": {"foo\x01bar"}}, wantErr: `invalid HTTP header value "foo\x01bar" for header "foo"`, }, } tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() for i, tt := range tests { req, _ := http.NewRequest("GET", st.ts.URL, nil) req.Header = tt.h res, err := tr.RoundTrip(req) var bad bool if tt.wantErr == "" { if err != nil { bad = true t.Errorf("case %d: error = %v; want no error", i, err) } } else { if !strings.Contains(fmt.Sprint(err), tt.wantErr) { bad = true t.Errorf("case %d: error = %v; want error %q", i, err, tt.wantErr) } } if err == nil { if bad { t.Logf("case %d: server got headers %q", i, res.Header.Get("Got-Header")) } res.Body.Close() } } } // Tests that gzipReader doesn't crash on a second Read call following // the first Read call's gzip.NewReader returning an error. func TestGzipReader_DoubleReadCrash(t *testing.T) { gz := &gzipReader{ body: ioutil.NopCloser(strings.NewReader("0123456789")), } var buf [1]byte n, err1 := gz.Read(buf[:]) if n != 0 || !strings.Contains(fmt.Sprint(err1), "invalid header") { t.Fatalf("Read = %v, %v; want 0, invalid header", n, err1) } n, err2 := gz.Read(buf[:]) if n != 0 || err2 != err1 { t.Fatalf("second Read = %v, %v; want 0, %v", n, err2, err1) } } func TestTransportNewTLSConfig(t *testing.T) { tests := [...]struct { conf *tls.Config host string want *tls.Config }{ // Normal case. 0: { conf: nil, host: "foo.com", want: &tls.Config{ ServerName: "foo.com", NextProtos: []string{NextProtoTLS}, }, }, // User-provided name (bar.com) takes precedence: 1: { conf: &tls.Config{ ServerName: "bar.com", }, host: "foo.com", want: &tls.Config{ ServerName: "bar.com", NextProtos: []string{NextProtoTLS}, }, }, // NextProto is prepended: 2: { conf: &tls.Config{ NextProtos: []string{"foo", "bar"}, }, host: "example.com", want: &tls.Config{ ServerName: "example.com", NextProtos: []string{NextProtoTLS, "foo", "bar"}, }, }, // NextProto is not duplicated: 3: { conf: &tls.Config{ NextProtos: []string{"foo", "bar", NextProtoTLS}, }, host: "example.com", want: &tls.Config{ ServerName: "example.com", NextProtos: []string{"foo", "bar", NextProtoTLS}, }, }, } for i, tt := range tests { // Ignore the session ticket keys part, which ends up populating // unexported fields in the Config: if tt.conf != nil { tt.conf.SessionTicketsDisabled = true } tr := &Transport{TLSClientConfig: tt.conf} got := tr.newTLSConfig(tt.host) got.SessionTicketsDisabled = false if !reflect.DeepEqual(got, tt.want) { t.Errorf("%d. got %#v; want %#v", i, got, tt.want) } } } // The Google GFE responds to HEAD requests with a HEADERS frame // without END_STREAM, followed by a 0-length DATA frame with // END_STREAM. Make sure we don't get confused by that. (We did.) func TestTransportReadHeadResponse(t *testing.T) { ct := newClientTester(t) clientDone := make(chan struct{}) ct.client = func() error { defer close(clientDone) req, _ := http.NewRequest("HEAD", "https://dummy.tld/", nil) res, err := ct.tr.RoundTrip(req) if err != nil { return err } if res.ContentLength != 123 { return fmt.Errorf("Content-Length = %d; want 123", res.ContentLength) } slurp, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("ReadAll: %v", err) } if len(slurp) > 0 { return fmt.Errorf("Unexpected non-empty ReadAll body: %q", slurp) } return nil } ct.server = func() error { ct.greet() for { f, err := ct.fr.ReadFrame() if err != nil { t.Logf("ReadFrame: %v", err) return nil } hf, ok := f.(*HeadersFrame) if !ok { continue } var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: hf.StreamID, EndHeaders: true, EndStream: false, // as the GFE does BlockFragment: buf.Bytes(), }) ct.fr.WriteData(hf.StreamID, true, nil) <-clientDone return nil } } ct.run() } type neverEnding byte func (b neverEnding) Read(p []byte) (int, error) { for i := range p { p[i] = byte(b) } return len(p), nil } // golang.org/issue/15425: test that a handler closing the request // body doesn't terminate the stream to the peer. (It just stops // readability from the handler's side, and eventually the client // runs out of flow control tokens) func TestTransportHandlerBodyClose(t *testing.T) { const bodySize = 10 << 20 st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { r.Body.Close() io.Copy(w, io.LimitReader(neverEnding('A'), bodySize)) }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() g0 := runtime.NumGoroutine() const numReq = 10 for i := 0; i < numReq; i++ { req, err := http.NewRequest("POST", st.ts.URL, struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)}) if err != nil { t.Fatal(err) } res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } n, err := io.Copy(ioutil.Discard, res.Body) res.Body.Close() if n != bodySize || err != nil { t.Fatalf("req#%d: Copy = %d, %v; want %d, nil", i, n, err, bodySize) } } tr.CloseIdleConnections() gd := runtime.NumGoroutine() - g0 if gd > numReq/2 { t.Errorf("appeared to leak goroutines") } } // https://golang.org/issue/15930 func TestTransportFlowControl(t *testing.T) { const bufLen = 64 << 10 var total int64 = 100 << 20 // 100MB if testing.Short() { total = 10 << 20 } var wrote int64 // updated atomically st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { b := make([]byte, bufLen) for wrote < total { n, err := w.Write(b) atomic.AddInt64(&wrote, int64(n)) if err != nil { t.Errorf("ResponseWriter.Write error: %v", err) break } w.(http.Flusher).Flush() } }, optOnlyServer) tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Fatal("NewRequest error:", err) } resp, err := tr.RoundTrip(req) if err != nil { t.Fatal("RoundTrip error:", err) } defer resp.Body.Close() var read int64 b := make([]byte, bufLen) for { n, err := resp.Body.Read(b) if err == io.EOF { break } if err != nil { t.Fatal("Read error:", err) } read += int64(n) const max = transportDefaultStreamFlow if w := atomic.LoadInt64(&wrote); -max > read-w || read-w > max { t.Fatalf("Too much data inflight: server wrote %v bytes but client only received %v", w, read) } // Let the server get ahead of the client. time.Sleep(1 * time.Millisecond) } } // golang.org/issue/14627 -- if the server sends a GOAWAY frame, make // the Transport remember it and return it back to users (via // RoundTrip or request body reads) if needed (e.g. if the server // proceeds to close the TCP connection before the client gets its // response) func TestTransportUsesGoAwayDebugError_RoundTrip(t *testing.T) { testTransportUsesGoAwayDebugError(t, false) } func TestTransportUsesGoAwayDebugError_Body(t *testing.T) { testTransportUsesGoAwayDebugError(t, true) } func testTransportUsesGoAwayDebugError(t *testing.T, failMidBody bool) { ct := newClientTester(t) clientDone := make(chan struct{}) const goAwayErrCode = ErrCodeHTTP11Required // arbitrary const goAwayDebugData = "some debug data" ct.client = func() error { defer close(clientDone) req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) res, err := ct.tr.RoundTrip(req) if failMidBody { if err != nil { return fmt.Errorf("unexpected client RoundTrip error: %v", err) } _, err = io.Copy(ioutil.Discard, res.Body) res.Body.Close() } want := GoAwayError{ LastStreamID: 5, ErrCode: goAwayErrCode, DebugData: goAwayDebugData, } if !reflect.DeepEqual(err, want) { t.Errorf("RoundTrip error = %T: %#v, want %T (%#v)", err, err, want, want) } return nil } ct.server = func() error { ct.greet() for { f, err := ct.fr.ReadFrame() if err != nil { t.Logf("ReadFrame: %v", err) return nil } hf, ok := f.(*HeadersFrame) if !ok { continue } if failMidBody { var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: hf.StreamID, EndHeaders: true, EndStream: false, BlockFragment: buf.Bytes(), }) } // Write two GOAWAY frames, to test that the Transport takes // the interesting parts of both. ct.fr.WriteGoAway(5, ErrCodeNo, []byte(goAwayDebugData)) ct.fr.WriteGoAway(5, goAwayErrCode, nil) ct.sc.(*net.TCPConn).CloseWrite() <-clientDone return nil } } ct.run() } func testTransportReturnsUnusedFlowControl(t *testing.T, oneDataFrame bool) { ct := newClientTester(t) clientClosed := make(chan struct{}) serverWroteFirstByte := make(chan struct{}) ct.client = func() error { req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) res, err := ct.tr.RoundTrip(req) if err != nil { return err } <-serverWroteFirstByte if n, err := res.Body.Read(make([]byte, 1)); err != nil || n != 1 { return fmt.Errorf("body read = %v, %v; want 1, nil", n, err) } res.Body.Close() // leaving 4999 bytes unread close(clientClosed) return nil } ct.server = func() error { ct.greet() var hf *HeadersFrame for { f, err := ct.fr.ReadFrame() if err != nil { return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) } switch f.(type) { case *WindowUpdateFrame, *SettingsFrame: continue } var ok bool hf, ok = f.(*HeadersFrame) if !ok { return fmt.Errorf("Got %T; want HeadersFrame", f) } break } var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: hf.StreamID, EndHeaders: true, EndStream: false, BlockFragment: buf.Bytes(), }) // Two cases: // - Send one DATA frame with 5000 bytes. // - Send two DATA frames with 1 and 4999 bytes each. // // In both cases, the client should consume one byte of data, // refund that byte, then refund the following 4999 bytes. // // In the second case, the server waits for the client connection to // close before seconding the second DATA frame. This tests the case // where the client receives a DATA frame after it has reset the stream. if oneDataFrame { ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 5000)) close(serverWroteFirstByte) <-clientClosed } else { ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 1)) close(serverWroteFirstByte) <-clientClosed ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 4999)) } waitingFor := "RSTStreamFrame" for { f, err := ct.fr.ReadFrame() if err != nil { return fmt.Errorf("ReadFrame while waiting for %s: %v", waitingFor, err) } if _, ok := f.(*SettingsFrame); ok { continue } switch waitingFor { case "RSTStreamFrame": if rf, ok := f.(*RSTStreamFrame); !ok || rf.ErrCode != ErrCodeCancel { return fmt.Errorf("Expected a RSTStreamFrame with code cancel; got %v", summarizeFrame(f)) } waitingFor = "WindowUpdateFrame" case "WindowUpdateFrame": if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != 4999 { return fmt.Errorf("Expected WindowUpdateFrame for 4999 bytes; got %v", summarizeFrame(f)) } return nil } } } ct.run() } // See golang.org/issue/16481 func TestTransportReturnsUnusedFlowControlSingleWrite(t *testing.T) { testTransportReturnsUnusedFlowControl(t, true) } // See golang.org/issue/20469 func TestTransportReturnsUnusedFlowControlMultipleWrites(t *testing.T) { testTransportReturnsUnusedFlowControl(t, false) } // Issue 16612: adjust flow control on open streams when transport // receives SETTINGS with INITIAL_WINDOW_SIZE from server. func TestTransportAdjustsFlowControl(t *testing.T) { ct := newClientTester(t) clientDone := make(chan struct{}) const bodySize = 1 << 20 ct.client = func() error { defer ct.cc.(*net.TCPConn).CloseWrite() defer close(clientDone) req, _ := http.NewRequest("POST", "https://dummy.tld/", struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)}) res, err := ct.tr.RoundTrip(req) if err != nil { return err } res.Body.Close() return nil } ct.server = func() error { _, err := io.ReadFull(ct.sc, make([]byte, len(ClientPreface))) if err != nil { return fmt.Errorf("reading client preface: %v", err) } var gotBytes int64 var sentSettings bool for { f, err := ct.fr.ReadFrame() if err != nil { select { case <-clientDone: return nil default: return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) } } switch f := f.(type) { case *DataFrame: gotBytes += int64(len(f.Data())) // After we've got half the client's // initial flow control window's worth // of request body data, give it just // enough flow control to finish. if gotBytes >= initialWindowSize/2 && !sentSettings { sentSettings = true ct.fr.WriteSettings(Setting{ID: SettingInitialWindowSize, Val: bodySize}) ct.fr.WriteWindowUpdate(0, bodySize) ct.fr.WriteSettingsAck() } if f.StreamEnded() { var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.StreamID, EndHeaders: true, EndStream: true, BlockFragment: buf.Bytes(), }) } } } } ct.run() } // See golang.org/issue/16556 func TestTransportReturnsDataPaddingFlowControl(t *testing.T) { ct := newClientTester(t) unblockClient := make(chan bool, 1) ct.client = func() error { req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) res, err := ct.tr.RoundTrip(req) if err != nil { return err } defer res.Body.Close() <-unblockClient return nil } ct.server = func() error { ct.greet() var hf *HeadersFrame for { f, err := ct.fr.ReadFrame() if err != nil { return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) } switch f.(type) { case *WindowUpdateFrame, *SettingsFrame: continue } var ok bool hf, ok = f.(*HeadersFrame) if !ok { return fmt.Errorf("Got %T; want HeadersFrame", f) } break } var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: hf.StreamID, EndHeaders: true, EndStream: false, BlockFragment: buf.Bytes(), }) pad := make([]byte, 5) ct.fr.WriteDataPadded(hf.StreamID, false, make([]byte, 5000), pad) // without ending stream f, err := ct.readNonSettingsFrame() if err != nil { return fmt.Errorf("ReadFrame while waiting for first WindowUpdateFrame: %v", err) } wantBack := uint32(len(pad)) + 1 // one byte for the length of the padding if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID != 0 { return fmt.Errorf("Expected conn WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f)) } f, err = ct.readNonSettingsFrame() if err != nil { return fmt.Errorf("ReadFrame while waiting for second WindowUpdateFrame: %v", err) } if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID == 0 { return fmt.Errorf("Expected stream WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f)) } unblockClient <- true return nil } ct.run() } // golang.org/issue/16572 -- RoundTrip shouldn't hang when it gets a // StreamError as a result of the response HEADERS func TestTransportReturnsErrorOnBadResponseHeaders(t *testing.T) { ct := newClientTester(t) ct.client = func() error { req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) res, err := ct.tr.RoundTrip(req) if err == nil { res.Body.Close() return errors.New("unexpected successful GET") } want := StreamError{1, ErrCodeProtocol, headerFieldNameError(" content-type")} if !reflect.DeepEqual(want, err) { t.Errorf("RoundTrip error = %#v; want %#v", err, want) } return nil } ct.server = func() error { ct.greet() hf, err := ct.firstHeaders() if err != nil { return err } var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) enc.WriteField(hpack.HeaderField{Name: " content-type", Value: "bogus"}) // bogus spaces ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: hf.StreamID, EndHeaders: true, EndStream: false, BlockFragment: buf.Bytes(), }) for { fr, err := ct.readFrame() if err != nil { return fmt.Errorf("error waiting for RST_STREAM from client: %v", err) } if _, ok := fr.(*SettingsFrame); ok { continue } if rst, ok := fr.(*RSTStreamFrame); !ok || rst.StreamID != 1 || rst.ErrCode != ErrCodeProtocol { t.Errorf("Frame = %v; want RST_STREAM for stream 1 with ErrCodeProtocol", summarizeFrame(fr)) } break } return nil } ct.run() } // byteAndEOFReader returns is in an io.Reader which reads one byte // (the underlying byte) and io.EOF at once in its Read call. type byteAndEOFReader byte func (b byteAndEOFReader) Read(p []byte) (n int, err error) { if len(p) == 0 { panic("unexpected useless call") } p[0] = byte(b) return 1, io.EOF } // Issue 16788: the Transport had a regression where it started // sending a spurious DATA frame with a duplicate END_STREAM bit after // the request body writer goroutine had already read an EOF from the // Request.Body and included the END_STREAM on a data-carrying DATA // frame. // // Notably, to trigger this, the requests need to use a Request.Body // which returns (non-0, io.EOF) and also needs to set the ContentLength // explicitly. func TestTransportBodyDoubleEndStream(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { // Nothing. }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() for i := 0; i < 2; i++ { req, _ := http.NewRequest("POST", st.ts.URL, byteAndEOFReader('a')) req.ContentLength = 1 res, err := tr.RoundTrip(req) if err != nil { t.Fatalf("failure on req %d: %v", i+1, err) } defer res.Body.Close() } } // golang.org/issue/16847, golang.org/issue/19103 func TestTransportRequestPathPseudo(t *testing.T) { type result struct { path string err string } tests := []struct { req *http.Request want result }{ 0: { req: &http.Request{ Method: "GET", URL: &url.URL{ Host: "foo.com", Path: "/foo", }, }, want: result{path: "/foo"}, }, // In Go 1.7, we accepted paths of "//foo". // In Go 1.8, we rejected it (issue 16847). // In Go 1.9, we accepted it again (issue 19103). 1: { req: &http.Request{ Method: "GET", URL: &url.URL{ Host: "foo.com", Path: "//foo", }, }, want: result{path: "//foo"}, }, // Opaque with //$Matching_Hostname/path 2: { req: &http.Request{ Method: "GET", URL: &url.URL{ Scheme: "https", Opaque: "//foo.com/path", Host: "foo.com", Path: "/ignored", }, }, want: result{path: "/path"}, }, // Opaque with some other Request.Host instead: 3: { req: &http.Request{ Method: "GET", Host: "bar.com", URL: &url.URL{ Scheme: "https", Opaque: "//bar.com/path", Host: "foo.com", Path: "/ignored", }, }, want: result{path: "/path"}, }, // Opaque without the leading "//": 4: { req: &http.Request{ Method: "GET", URL: &url.URL{ Opaque: "/path", Host: "foo.com", Path: "/ignored", }, }, want: result{path: "/path"}, }, // Opaque we can't handle: 5: { req: &http.Request{ Method: "GET", URL: &url.URL{ Scheme: "https", Opaque: "//unknown_host/path", Host: "foo.com", Path: "/ignored", }, }, want: result{err: `invalid request :path "https://unknown_host/path" from URL.Opaque = "//unknown_host/path"`}, }, // A CONNECT request: 6: { req: &http.Request{ Method: "CONNECT", URL: &url.URL{ Host: "foo.com", }, }, want: result{}, }, } for i, tt := range tests { cc := &ClientConn{peerMaxHeaderListSize: 0xffffffffffffffff} cc.henc = hpack.NewEncoder(&cc.hbuf) cc.mu.Lock() hdrs, err := cc.encodeHeaders(tt.req, false, "", -1) cc.mu.Unlock() var got result hpackDec := hpack.NewDecoder(initialHeaderTableSize, func(f hpack.HeaderField) { if f.Name == ":path" { got.path = f.Value } }) if err != nil { got.err = err.Error() } else if len(hdrs) > 0 { if _, err := hpackDec.Write(hdrs); err != nil { t.Errorf("%d. bogus hpack: %v", i, err) continue } } if got != tt.want { t.Errorf("%d. got %+v; want %+v", i, got, tt.want) } } } // golang.org/issue/17071 -- don't sniff the first byte of the request body // before we've determined that the ClientConn is usable. func TestRoundTripDoesntConsumeRequestBodyEarly(t *testing.T) { const body = "foo" req, _ := http.NewRequest("POST", "http://foo.com/", ioutil.NopCloser(strings.NewReader(body))) cc := &ClientConn{ closed: true, } _, err := cc.RoundTrip(req) if err != errClientConnUnusable { t.Fatalf("RoundTrip = %v; want errClientConnUnusable", err) } slurp, err := ioutil.ReadAll(req.Body) if err != nil { t.Errorf("ReadAll = %v", err) } if string(slurp) != body { t.Errorf("Body = %q; want %q", slurp, body) } } func TestClientConnPing(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() cc, err := tr.dialClientConn(st.ts.Listener.Addr().String(), false) if err != nil { t.Fatal(err) } if err = cc.Ping(testContext{}); err != nil { t.Fatal(err) } } // Issue 16974: if the server sent a DATA frame after the user // canceled the Transport's Request, the Transport previously wrote to a // closed pipe, got an error, and ended up closing the whole TCP // connection. func TestTransportCancelDataResponseRace(t *testing.T) { cancel := make(chan struct{}) clientGotError := make(chan bool, 1) const msg = "Hello." st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { if strings.Contains(r.URL.Path, "/hello") { time.Sleep(50 * time.Millisecond) io.WriteString(w, msg) return } for i := 0; i < 50; i++ { io.WriteString(w, "Some data.") w.(http.Flusher).Flush() if i == 2 { close(cancel) <-clientGotError } time.Sleep(10 * time.Millisecond) } }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() c := &http.Client{Transport: tr} req, _ := http.NewRequest("GET", st.ts.URL, nil) req.Cancel = cancel res, err := c.Do(req) if err != nil { t.Fatal(err) } if _, err = io.Copy(ioutil.Discard, res.Body); err == nil { t.Fatal("unexpected success") } clientGotError <- true res, err = c.Get(st.ts.URL + "/hello") if err != nil { t.Fatal(err) } slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } if string(slurp) != msg { t.Errorf("Got = %q; want %q", slurp, msg) } } func TestTransportRetryAfterGOAWAY(t *testing.T) { var dialer struct { sync.Mutex count int } ct1 := make(chan *clientTester) ct2 := make(chan *clientTester) ln := newLocalListener(t) defer ln.Close() tr := &Transport{ TLSClientConfig: tlsConfigInsecure, } tr.DialTLS = func(network, addr string, cfg *tls.Config) (net.Conn, error) { dialer.Lock() defer dialer.Unlock() dialer.count++ if dialer.count == 3 { return nil, errors.New("unexpected number of dials") } cc, err := net.Dial("tcp", ln.Addr().String()) if err != nil { return nil, fmt.Errorf("dial error: %v", err) } sc, err := ln.Accept() if err != nil { return nil, fmt.Errorf("accept error: %v", err) } ct := &clientTester{ t: t, tr: tr, cc: cc, sc: sc, fr: NewFramer(sc, sc), } switch dialer.count { case 1: ct1 <- ct case 2: ct2 <- ct } return cc, nil } errs := make(chan error, 3) done := make(chan struct{}) defer close(done) // Client. go func() { req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) res, err := tr.RoundTrip(req) if res != nil { res.Body.Close() if got := res.Header.Get("Foo"); got != "bar" { err = fmt.Errorf("foo header = %q; want bar", got) } } if err != nil { err = fmt.Errorf("RoundTrip: %v", err) } errs <- err }() connToClose := make(chan io.Closer, 2) // Server for the first request. go func() { var ct *clientTester select { case ct = <-ct1: case <-done: return } connToClose <- ct.cc ct.greet() hf, err := ct.firstHeaders() if err != nil { errs <- fmt.Errorf("server1 failed reading HEADERS: %v", err) return } t.Logf("server1 got %v", hf) if err := ct.fr.WriteGoAway(0 /*max id*/, ErrCodeNo, nil); err != nil { errs <- fmt.Errorf("server1 failed writing GOAWAY: %v", err) return } errs <- nil }() // Server for the second request. go func() { var ct *clientTester select { case ct = <-ct2: case <-done: return } connToClose <- ct.cc ct.greet() hf, err := ct.firstHeaders() if err != nil { errs <- fmt.Errorf("server2 failed reading HEADERS: %v", err) return } t.Logf("server2 got %v", hf) var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) err = ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: hf.StreamID, EndHeaders: true, EndStream: false, BlockFragment: buf.Bytes(), }) if err != nil { errs <- fmt.Errorf("server2 failed writing response HEADERS: %v", err) } else { errs <- nil } }() for k := 0; k < 3; k++ { select { case err := <-errs: if err != nil { t.Error(err) } case <-time.After(1 * time.Second): t.Errorf("timed out") } } for { select { case c := <-connToClose: c.Close() default: return } } } func TestTransportRetryAfterRefusedStream(t *testing.T) { clientDone := make(chan struct{}) ct := newClientTester(t) ct.client = func() error { defer ct.cc.(*net.TCPConn).CloseWrite() defer close(clientDone) req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) resp, err := ct.tr.RoundTrip(req) if err != nil { return fmt.Errorf("RoundTrip: %v", err) } resp.Body.Close() if resp.StatusCode != 204 { return fmt.Errorf("Status = %v; want 204", resp.StatusCode) } return nil } ct.server = func() error { ct.greet() var buf bytes.Buffer enc := hpack.NewEncoder(&buf) nreq := 0 for { f, err := ct.fr.ReadFrame() if err != nil { select { case <-clientDone: // If the client's done, it // will have reported any // errors on its side. return nil default: return err } } switch f := f.(type) { case *WindowUpdateFrame, *SettingsFrame: case *HeadersFrame: if !f.HeadersEnded() { return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) } nreq++ if nreq == 1 { ct.fr.WriteRSTStream(f.StreamID, ErrCodeRefusedStream) } else { enc.WriteField(hpack.HeaderField{Name: ":status", Value: "204"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.StreamID, EndHeaders: true, EndStream: true, BlockFragment: buf.Bytes(), }) } default: return fmt.Errorf("Unexpected client frame %v", f) } } } ct.run() } func TestTransportRetryHasLimit(t *testing.T) { // Skip in short mode because the total expected delay is 1s+2s+4s+8s+16s=29s. if testing.Short() { t.Skip("skipping long test in short mode") } clientDone := make(chan struct{}) ct := newClientTester(t) ct.client = func() error { defer ct.cc.(*net.TCPConn).CloseWrite() defer close(clientDone) req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) resp, err := ct.tr.RoundTrip(req) if err == nil { return fmt.Errorf("RoundTrip expected error, got response: %+v", resp) } t.Logf("expected error, got: %v", err) return nil } ct.server = func() error { ct.greet() for { f, err := ct.fr.ReadFrame() if err != nil { select { case <-clientDone: // If the client's done, it // will have reported any // errors on its side. return nil default: return err } } switch f := f.(type) { case *WindowUpdateFrame, *SettingsFrame: case *HeadersFrame: if !f.HeadersEnded() { return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) } ct.fr.WriteRSTStream(f.StreamID, ErrCodeRefusedStream) default: return fmt.Errorf("Unexpected client frame %v", f) } } } ct.run() } func TestTransportResponseDataBeforeHeaders(t *testing.T) { ct := newClientTester(t) ct.client = func() error { defer ct.cc.(*net.TCPConn).CloseWrite() req := httptest.NewRequest("GET", "https://dummy.tld/", nil) // First request is normal to ensure the check is per stream and not per connection. _, err := ct.tr.RoundTrip(req) if err != nil { return fmt.Errorf("RoundTrip expected no error, got: %v", err) } // Second request returns a DATA frame with no HEADERS. resp, err := ct.tr.RoundTrip(req) if err == nil { return fmt.Errorf("RoundTrip expected error, got response: %+v", resp) } if err, ok := err.(StreamError); !ok || err.Code != ErrCodeProtocol { return fmt.Errorf("expected stream PROTOCOL_ERROR, got: %v", err) } return nil } ct.server = func() error { ct.greet() for { f, err := ct.fr.ReadFrame() if err == io.EOF { return nil } else if err != nil { return err } switch f := f.(type) { case *WindowUpdateFrame, *SettingsFrame: case *HeadersFrame: switch f.StreamID { case 1: // Send a valid response to first request. var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: f.StreamID, EndHeaders: true, EndStream: true, BlockFragment: buf.Bytes(), }) case 3: ct.fr.WriteData(f.StreamID, true, []byte("payload")) } default: return fmt.Errorf("Unexpected client frame %v", f) } } } ct.run() } func TestTransportRequestsStallAtServerLimit(t *testing.T) { const maxConcurrent = 2 greet := make(chan struct{}) // server sends initial SETTINGS frame gotRequest := make(chan struct{}) // server received a request clientDone := make(chan struct{}) // Collect errors from goroutines. var wg sync.WaitGroup errs := make(chan error, 100) defer func() { wg.Wait() close(errs) for err := range errs { t.Error(err) } }() // We will send maxConcurrent+2 requests. This checker goroutine waits for the // following stages: // 1. The first maxConcurrent requests are received by the server. // 2. The client will cancel the next request // 3. The server is unblocked so it can service the first maxConcurrent requests // 4. The client will send the final request wg.Add(1) unblockClient := make(chan struct{}) clientRequestCancelled := make(chan struct{}) unblockServer := make(chan struct{}) go func() { defer wg.Done() // Stage 1. for k := 0; k < maxConcurrent; k++ { <-gotRequest } // Stage 2. close(unblockClient) <-clientRequestCancelled // Stage 3: give some time for the final RoundTrip call to be scheduled and // verify that the final request is not sent. time.Sleep(50 * time.Millisecond) select { case <-gotRequest: errs <- errors.New("last request did not stall") close(unblockServer) return default: } close(unblockServer) // Stage 4. <-gotRequest }() ct := newClientTester(t) ct.client = func() error { var wg sync.WaitGroup defer func() { wg.Wait() close(clientDone) ct.cc.(*net.TCPConn).CloseWrite() }() for k := 0; k < maxConcurrent+2; k++ { wg.Add(1) go func(k int) { defer wg.Done() // Don't send the second request until after receiving SETTINGS from the server // to avoid a race where we use the default SettingMaxConcurrentStreams, which // is much larger than maxConcurrent. We have to send the first request before // waiting because the first request triggers the dial and greet. if k > 0 { <-greet } // Block until maxConcurrent requests are sent before sending any more. if k >= maxConcurrent { <-unblockClient } req, _ := http.NewRequest("GET", fmt.Sprintf("https://dummy.tld/%d", k), nil) if k == maxConcurrent { // This request will be canceled. cancel := make(chan struct{}) req.Cancel = cancel close(cancel) _, err := ct.tr.RoundTrip(req) close(clientRequestCancelled) if err == nil { errs <- fmt.Errorf("RoundTrip(%d) should have failed due to cancel", k) return } } else { resp, err := ct.tr.RoundTrip(req) if err != nil { errs <- fmt.Errorf("RoundTrip(%d): %v", k, err) return } ioutil.ReadAll(resp.Body) resp.Body.Close() if resp.StatusCode != 204 { errs <- fmt.Errorf("Status = %v; want 204", resp.StatusCode) return } } }(k) } return nil } ct.server = func() error { var wg sync.WaitGroup defer wg.Wait() ct.greet(Setting{SettingMaxConcurrentStreams, maxConcurrent}) // Server write loop. var buf bytes.Buffer enc := hpack.NewEncoder(&buf) writeResp := make(chan uint32, maxConcurrent+1) wg.Add(1) go func() { defer wg.Done() <-unblockServer for id := range writeResp { buf.Reset() enc.WriteField(hpack.HeaderField{Name: ":status", Value: "204"}) ct.fr.WriteHeaders(HeadersFrameParam{ StreamID: id, EndHeaders: true, EndStream: true, BlockFragment: buf.Bytes(), }) } }() // Server read loop. var nreq int for { f, err := ct.fr.ReadFrame() if err != nil { select { case <-clientDone: // If the client's done, it will have reported any errors on its side. return nil default: return err } } switch f := f.(type) { case *WindowUpdateFrame: case *SettingsFrame: // Wait for the client SETTINGS ack until ending the greet. close(greet) case *HeadersFrame: if !f.HeadersEnded() { return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) } gotRequest <- struct{}{} nreq++ writeResp <- f.StreamID if nreq == maxConcurrent+1 { close(writeResp) } default: return fmt.Errorf("Unexpected client frame %v", f) } } } ct.run() } func TestAuthorityAddr(t *testing.T) { tests := []struct { scheme, authority string want string }{ {"http", "foo.com", "foo.com:80"}, {"https", "foo.com", "foo.com:443"}, {"https", "foo.com:1234", "foo.com:1234"}, {"https", "1.2.3.4:1234", "1.2.3.4:1234"}, {"https", "1.2.3.4", "1.2.3.4:443"}, {"https", "[::1]:1234", "[::1]:1234"}, {"https", "[::1]", "[::1]:443"}, } for _, tt := range tests { got := authorityAddr(tt.scheme, tt.authority) if got != tt.want { t.Errorf("authorityAddr(%q, %q) = %q; want %q", tt.scheme, tt.authority, got, tt.want) } } } // Issue 20448: stop allocating for DATA frames' payload after // Response.Body.Close is called. func TestTransportAllocationsAfterResponseBodyClose(t *testing.T) { megabyteZero := make([]byte, 1<<20) writeErr := make(chan error, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.(http.Flusher).Flush() var sum int64 for i := 0; i < 100; i++ { n, err := w.Write(megabyteZero) sum += int64(n) if err != nil { writeErr <- err return } } t.Logf("wrote all %d bytes", sum) writeErr <- nil }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() c := &http.Client{Transport: tr} res, err := c.Get(st.ts.URL) if err != nil { t.Fatal(err) } var buf [1]byte if _, err := res.Body.Read(buf[:]); err != nil { t.Error(err) } if err := res.Body.Close(); err != nil { t.Error(err) } trb, ok := res.Body.(transportResponseBody) if !ok { t.Fatalf("res.Body = %T; want transportResponseBody", res.Body) } if trb.cs.bufPipe.b != nil { t.Errorf("response body pipe is still open") } gotErr := <-writeErr if gotErr == nil { t.Errorf("Handler unexpectedly managed to write its entire response without getting an error") } else if gotErr != errStreamClosed { t.Errorf("Handler Write err = %v; want errStreamClosed", gotErr) } } // Issue 18891: make sure Request.Body == NoBody means no DATA frame // is ever sent, even if empty. func TestTransportNoBodyMeansNoDATA(t *testing.T) { ct := newClientTester(t) unblockClient := make(chan bool) ct.client = func() error { req, _ := http.NewRequest("GET", "https://dummy.tld/", go18httpNoBody()) ct.tr.RoundTrip(req) <-unblockClient return nil } ct.server = func() error { defer close(unblockClient) defer ct.cc.(*net.TCPConn).Close() ct.greet() for { f, err := ct.fr.ReadFrame() if err != nil { return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) } switch f := f.(type) { default: return fmt.Errorf("Got %T; want HeadersFrame", f) case *WindowUpdateFrame, *SettingsFrame: continue case *HeadersFrame: if !f.StreamEnded() { return fmt.Errorf("got headers frame without END_STREAM") } return nil } } } ct.run() } func benchSimpleRoundTrip(b *testing.B, nHeaders int) { defer disableGoroutineTracking()() b.ReportAllocs() st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { }, optOnlyServer, optQuiet, ) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { b.Fatal(err) } for i := 0; i < nHeaders; i++ { name := fmt.Sprint("A-", i) req.Header.Set(name, "*") } b.ResetTimer() for i := 0; i < b.N; i++ { res, err := tr.RoundTrip(req) if err != nil { if res != nil { res.Body.Close() } b.Fatalf("RoundTrip err = %v; want nil", err) } res.Body.Close() if res.StatusCode != http.StatusOK { b.Fatalf("Response code = %v; want %v", res.StatusCode, http.StatusOK) } } } type infiniteReader struct{} func (r infiniteReader) Read(b []byte) (int, error) { return len(b), nil } // Issue 20521: it is not an error to receive a response and end stream // from the server without the body being consumed. func TestTransportResponseAndResetWithoutConsumingBodyRace(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() // The request body needs to be big enough to trigger flow control. req, _ := http.NewRequest("PUT", st.ts.URL, infiniteReader{}) res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } if res.StatusCode != http.StatusOK { t.Fatalf("Response code = %v; want %v", res.StatusCode, http.StatusOK) } } func BenchmarkClientRequestHeaders(b *testing.B) { b.Run(" 0 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 0) }) b.Run(" 10 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 10) }) b.Run(" 100 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 100) }) b.Run("1000 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 1000) }) } lxd-2.0.11/dist/src/golang.org/x/net/http2/transport.go0000644061062106075000000017544013172163402023752 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Transport code. package http2 import ( "bufio" "bytes" "compress/gzip" "crypto/rand" "crypto/tls" "errors" "fmt" "io" "io/ioutil" "log" "math" mathrand "math/rand" "net" "net/http" "sort" "strconv" "strings" "sync" "time" "golang.org/x/net/http2/hpack" "golang.org/x/net/idna" "golang.org/x/net/lex/httplex" ) const ( // transportDefaultConnFlow is how many connection-level flow control // tokens we give the server at start-up, past the default 64k. transportDefaultConnFlow = 1 << 30 // transportDefaultStreamFlow is how many stream-level flow // control tokens we announce to the peer, and how many bytes // we buffer per stream. transportDefaultStreamFlow = 4 << 20 // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send // a stream-level WINDOW_UPDATE for at a time. transportDefaultStreamMinRefresh = 4 << 10 defaultUserAgent = "Go-http-client/2.0" ) // Transport is an HTTP/2 Transport. // // A Transport internally caches connections to servers. It is safe // for concurrent use by multiple goroutines. type Transport struct { // DialTLS specifies an optional dial function for creating // TLS connections for requests. // // If DialTLS is nil, tls.Dial is used. // // If the returned net.Conn has a ConnectionState method like tls.Conn, // it will be used to set http.Response.TLS. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. TLSClientConfig *tls.Config // ConnPool optionally specifies an alternate connection pool to use. // If nil, the default is used. ConnPool ClientConnPool // DisableCompression, if true, prevents the Transport from // requesting compression with an "Accept-Encoding: gzip" // request header when the Request contains no existing // Accept-Encoding value. If the Transport requests gzip on // its own and gets a gzipped response, it's transparently // decoded in the Response.Body. However, if the user // explicitly requested gzip it is not automatically // uncompressed. DisableCompression bool // AllowHTTP, if true, permits HTTP/2 requests using the insecure, // plain-text "http" scheme. Note that this does not enable h2c support. AllowHTTP bool // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to // send in the initial settings frame. It is how many bytes // of response headers are allowed. Unlike the http2 spec, zero here // means to use a default limit (currently 10MB). If you actually // want to advertise an ulimited value to the peer, Transport // interprets the highest possible value here (0xffffffff or 1<<32-1) // to mean no limit. MaxHeaderListSize uint32 // t1, if non-nil, is the standard library Transport using // this transport. Its settings are used (but not its // RoundTrip method, etc). t1 *http.Transport connPoolOnce sync.Once connPoolOrDef ClientConnPool // non-nil version of ConnPool } func (t *Transport) maxHeaderListSize() uint32 { if t.MaxHeaderListSize == 0 { return 10 << 20 } if t.MaxHeaderListSize == 0xffffffff { return 0 } return t.MaxHeaderListSize } func (t *Transport) disableCompression() bool { return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression) } var errTransportVersion = errors.New("http2: ConfigureTransport is only supported starting at Go 1.6") // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2. // It requires Go 1.6 or later and returns an error if the net/http package is too old // or if t1 has already been HTTP/2-enabled. func ConfigureTransport(t1 *http.Transport) error { _, err := configureTransport(t1) // in configure_transport.go (go1.6) or not_go16.go return err } func (t *Transport) connPool() ClientConnPool { t.connPoolOnce.Do(t.initConnPool) return t.connPoolOrDef } func (t *Transport) initConnPool() { if t.ConnPool != nil { t.connPoolOrDef = t.ConnPool } else { t.connPoolOrDef = &clientConnPool{t: t} } } // ClientConn is the state of a single HTTP/2 client connection to an // HTTP/2 server. type ClientConn struct { t *Transport tconn net.Conn // usually *tls.Conn, except specialized impls tlsState *tls.ConnectionState // nil only for specialized impls singleUse bool // whether being used for a single http.Request // readLoop goroutine fields: readerDone chan struct{} // closed on error readerErr error // set before readerDone is closed idleTimeout time.Duration // or 0 for never idleTimer *time.Timer mu sync.Mutex // guards following cond *sync.Cond // hold mu; broadcast on flow/closed changes flow flow // our conn-level flow control quota (cs.flow is per stream) inflow flow // peer's conn-level flow control closed bool wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received goAwayDebug string // goAway frame's debug data, retained as a string streams map[uint32]*clientStream // client-initiated nextStreamID uint32 pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams pings map[[8]byte]chan struct{} // in flight ping data to notification channel bw *bufio.Writer br *bufio.Reader fr *Framer lastActive time.Time // Settings from peer: (also guarded by mu) maxFrameSize uint32 maxConcurrentStreams uint32 peerMaxHeaderListSize uint64 initialWindowSize uint32 hbuf bytes.Buffer // HPACK encoder writes into this henc *hpack.Encoder freeBuf [][]byte wmu sync.Mutex // held while writing; acquire AFTER mu if holding both werr error // first write error that has occurred } // clientStream is the state for a single HTTP/2 stream. One of these // is created for each Transport.RoundTrip call. type clientStream struct { cc *ClientConn req *http.Request trace *clientTrace // or nil ID uint32 resc chan resAndError bufPipe pipe // buffered pipe with the flow-controlled response payload startedWrite bool // started request body write; guarded by cc.mu requestedGzip bool on100 func() // optional code to run if get a 100 continue response flow flow // guarded by cc.mu inflow flow // guarded by cc.mu bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read readErr error // sticky read error; owned by transportResponseBody.Read stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu didReset bool // whether we sent a RST_STREAM to the server; guarded by cc.mu peerReset chan struct{} // closed on peer reset resetErr error // populated before peerReset is closed done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu // owned by clientConnReadLoop: firstByte bool // got the first response byte pastHeaders bool // got first MetaHeadersFrame (actual headers) pastTrailers bool // got optional second MetaHeadersFrame (trailers) trailer http.Header // accumulated trailers resTrailer *http.Header // client's Response.Trailer } // awaitRequestCancel waits for the user to cancel a request or for the done // channel to be signaled. A non-nil error is returned only if the request was // canceled. func awaitRequestCancel(req *http.Request, done <-chan struct{}) error { ctx := reqContext(req) if req.Cancel == nil && ctx.Done() == nil { return nil } select { case <-req.Cancel: return errRequestCanceled case <-ctx.Done(): return ctx.Err() case <-done: return nil } } // awaitRequestCancel waits for the user to cancel a request, its context to // expire, or for the request to be done (any way it might be removed from the // cc.streams map: peer reset, successful completion, TCP connection breakage, // etc). If the request is canceled, then cs will be canceled and closed. func (cs *clientStream) awaitRequestCancel(req *http.Request) { if err := awaitRequestCancel(req, cs.done); err != nil { cs.cancelStream() cs.bufPipe.CloseWithError(err) } } func (cs *clientStream) cancelStream() { cc := cs.cc cc.mu.Lock() didReset := cs.didReset cs.didReset = true cc.mu.Unlock() if !didReset { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) cc.forgetStreamID(cs.ID) } } // checkResetOrDone reports any error sent in a RST_STREAM frame by the // server, or errStreamClosed if the stream is complete. func (cs *clientStream) checkResetOrDone() error { select { case <-cs.peerReset: return cs.resetErr case <-cs.done: return errStreamClosed default: return nil } } func (cs *clientStream) abortRequestBodyWrite(err error) { if err == nil { panic("nil error") } cc := cs.cc cc.mu.Lock() cs.stopReqBody = err cc.cond.Broadcast() cc.mu.Unlock() } type stickyErrWriter struct { w io.Writer err *error } func (sew stickyErrWriter) Write(p []byte) (n int, err error) { if *sew.err != nil { return 0, *sew.err } n, err = sew.w.Write(p) *sew.err = err return } var ErrNoCachedConn = errors.New("http2: no cached connection was available") // RoundTripOpt are options for the Transport.RoundTripOpt method. type RoundTripOpt struct { // OnlyCachedConn controls whether RoundTripOpt may // create a new TCP connection. If set true and // no cached connection is available, RoundTripOpt // will return ErrNoCachedConn. OnlyCachedConn bool } func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { return t.RoundTripOpt(req, RoundTripOpt{}) } // authorityAddr returns a given authority (a host/IP, or host:port / ip:port) // and returns a host:port. The port 443 is added if needed. func authorityAddr(scheme string, authority string) (addr string) { host, port, err := net.SplitHostPort(authority) if err != nil { // authority didn't have a port port = "443" if scheme == "http" { port = "80" } host = authority } if a, err := idna.ToASCII(host); err == nil { host = a } // IPv6 address literal, without a port: if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { return host + ":" + port } return net.JoinHostPort(host, port) } // RoundTripOpt is like RoundTrip, but takes options. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) { return nil, errors.New("http2: unsupported scheme") } addr := authorityAddr(req.URL.Scheme, req.URL.Host) for retry := 0; ; retry++ { cc, err := t.connPool().GetClientConn(req, addr) if err != nil { t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err) return nil, err } traceGotConn(req, cc) res, err := cc.RoundTrip(req) if err != nil && retry <= 6 { afterBodyWrite := false if e, ok := err.(afterReqBodyWriteError); ok { err = e afterBodyWrite = true } if req, err = shouldRetryRequest(req, err, afterBodyWrite); err == nil { // After the first retry, do exponential backoff with 10% jitter. if retry == 0 { continue } backoff := float64(uint(1) << (uint(retry) - 1)) backoff += backoff * (0.1 * mathrand.Float64()) select { case <-time.After(time.Second * time.Duration(backoff)): continue case <-reqContext(req).Done(): return nil, reqContext(req).Err() } } } if err != nil { t.vlogf("RoundTrip failure: %v", err) return nil, err } return res, nil } } // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle. // It does not interrupt any connections currently in use. func (t *Transport) CloseIdleConnections() { if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok { cp.closeIdleConnections() } } var ( errClientConnClosed = errors.New("http2: client conn is closed") errClientConnUnusable = errors.New("http2: client conn not usable") errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY") ) // afterReqBodyWriteError is a wrapper around errors returned by ClientConn.RoundTrip. // It is used to signal that err happened after part of Request.Body was sent to the server. type afterReqBodyWriteError struct { err error } func (e afterReqBodyWriteError) Error() string { return e.err.Error() + "; some request body already written" } // shouldRetryRequest is called by RoundTrip when a request fails to get // response headers. It is always called with a non-nil error. // It returns either a request to retry (either the same request, or a // modified clone), or an error if the request can't be replayed. func shouldRetryRequest(req *http.Request, err error, afterBodyWrite bool) (*http.Request, error) { if !canRetryError(err) { return nil, err } if !afterBodyWrite { return req, nil } // If the Body is nil (or http.NoBody), it's safe to reuse // this request and its Body. if req.Body == nil || reqBodyIsNoBody(req.Body) { return req, nil } // Otherwise we depend on the Request having its GetBody // func defined. getBody := reqGetBody(req) // Go 1.8: getBody = req.GetBody if getBody == nil { return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err) } body, err := getBody() if err != nil { return nil, err } newReq := *req newReq.Body = body return &newReq, nil } func canRetryError(err error) bool { if err == errClientConnUnusable || err == errClientConnGotGoAway { return true } if se, ok := err.(StreamError); ok { return se.Code == ErrCodeRefusedStream } return false } func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) { host, _, err := net.SplitHostPort(addr) if err != nil { return nil, err } tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host)) if err != nil { return nil, err } return t.newClientConn(tconn, singleUse) } func (t *Transport) newTLSConfig(host string) *tls.Config { cfg := new(tls.Config) if t.TLSClientConfig != nil { *cfg = *cloneTLSConfig(t.TLSClientConfig) } if !strSliceContains(cfg.NextProtos, NextProtoTLS) { cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...) } if cfg.ServerName == "" { cfg.ServerName = host } return cfg } func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) { if t.DialTLS != nil { return t.DialTLS } return t.dialTLSDefault } func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) { cn, err := tls.Dial(network, addr, cfg) if err != nil { return nil, err } if err := cn.Handshake(); err != nil { return nil, err } if !cfg.InsecureSkipVerify { if err := cn.VerifyHostname(cfg.ServerName); err != nil { return nil, err } } state := cn.ConnectionState() if p := state.NegotiatedProtocol; p != NextProtoTLS { return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS) } if !state.NegotiatedProtocolIsMutual { return nil, errors.New("http2: could not negotiate protocol mutually") } return cn, nil } // disableKeepAlives reports whether connections should be closed as // soon as possible after handling the first request. func (t *Transport) disableKeepAlives() bool { return t.t1 != nil && t.t1.DisableKeepAlives } func (t *Transport) expectContinueTimeout() time.Duration { if t.t1 == nil { return 0 } return transportExpectContinueTimeout(t.t1) } func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { return t.newClientConn(c, false) } func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) { cc := &ClientConn{ t: t, tconn: c, readerDone: make(chan struct{}), nextStreamID: 1, maxFrameSize: 16 << 10, // spec default initialWindowSize: 65535, // spec default maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough. peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead. streams: make(map[uint32]*clientStream), singleUse: singleUse, wantSettingsAck: true, pings: make(map[[8]byte]chan struct{}), } if d := t.idleConnTimeout(); d != 0 { cc.idleTimeout = d cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout) } if VerboseLogs { t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr()) } cc.cond = sync.NewCond(&cc.mu) cc.flow.add(int32(initialWindowSize)) // TODO: adjust this writer size to account for frame size + // MTU + crypto/tls record padding. cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr}) cc.br = bufio.NewReader(c) cc.fr = NewFramer(cc.bw, cc.br) cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) cc.fr.MaxHeaderListSize = t.maxHeaderListSize() // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on // henc in response to SETTINGS frames? cc.henc = hpack.NewEncoder(&cc.hbuf) if cs, ok := c.(connectionStater); ok { state := cs.ConnectionState() cc.tlsState = &state } initialSettings := []Setting{ {ID: SettingEnablePush, Val: 0}, {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow}, } if max := t.maxHeaderListSize(); max != 0 { initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max}) } cc.bw.Write(clientPreface) cc.fr.WriteSettings(initialSettings...) cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow) cc.inflow.add(transportDefaultConnFlow + initialWindowSize) cc.bw.Flush() if cc.werr != nil { return nil, cc.werr } go cc.readLoop() return cc, nil } func (cc *ClientConn) setGoAway(f *GoAwayFrame) { cc.mu.Lock() defer cc.mu.Unlock() old := cc.goAway cc.goAway = f // Merge the previous and current GoAway error frames. if cc.goAwayDebug == "" { cc.goAwayDebug = string(f.DebugData()) } if old != nil && old.ErrCode != ErrCodeNo { cc.goAway.ErrCode = old.ErrCode } last := f.LastStreamID for streamID, cs := range cc.streams { if streamID > last { select { case cs.resc <- resAndError{err: errClientConnGotGoAway}: default: } } } } // CanTakeNewRequest reports whether the connection can take a new request, // meaning it has not been closed or received or sent a GOAWAY. func (cc *ClientConn) CanTakeNewRequest() bool { cc.mu.Lock() defer cc.mu.Unlock() return cc.canTakeNewRequestLocked() } func (cc *ClientConn) canTakeNewRequestLocked() bool { if cc.singleUse && cc.nextStreamID > 1 { return false } return cc.goAway == nil && !cc.closed && int64(cc.nextStreamID)+int64(cc.pendingRequests) < math.MaxInt32 } // onIdleTimeout is called from a time.AfterFunc goroutine. It will // only be called when we're idle, but because we're coming from a new // goroutine, there could be a new request coming in at the same time, // so this simply calls the synchronized closeIfIdle to shut down this // connection. The timer could just call closeIfIdle, but this is more // clear. func (cc *ClientConn) onIdleTimeout() { cc.closeIfIdle() } func (cc *ClientConn) closeIfIdle() { cc.mu.Lock() if len(cc.streams) > 0 { cc.mu.Unlock() return } cc.closed = true nextID := cc.nextStreamID // TODO: do clients send GOAWAY too? maybe? Just Close: cc.mu.Unlock() if VerboseLogs { cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2) } cc.tconn.Close() } const maxAllocFrameSize = 512 << 10 // frameBuffer returns a scratch buffer suitable for writing DATA frames. // They're capped at the min of the peer's max frame size or 512KB // (kinda arbitrarily), but definitely capped so we don't allocate 4GB // bufers. func (cc *ClientConn) frameScratchBuffer() []byte { cc.mu.Lock() size := cc.maxFrameSize if size > maxAllocFrameSize { size = maxAllocFrameSize } for i, buf := range cc.freeBuf { if len(buf) >= int(size) { cc.freeBuf[i] = nil cc.mu.Unlock() return buf[:size] } } cc.mu.Unlock() return make([]byte, size) } func (cc *ClientConn) putFrameScratchBuffer(buf []byte) { cc.mu.Lock() defer cc.mu.Unlock() const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate. if len(cc.freeBuf) < maxBufs { cc.freeBuf = append(cc.freeBuf, buf) return } for i, old := range cc.freeBuf { if old == nil { cc.freeBuf[i] = buf return } } // forget about it. } // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests. var errRequestCanceled = errors.New("net/http: request canceled") func commaSeparatedTrailers(req *http.Request) (string, error) { keys := make([]string, 0, len(req.Trailer)) for k := range req.Trailer { k = http.CanonicalHeaderKey(k) switch k { case "Transfer-Encoding", "Trailer", "Content-Length": return "", &badStringError{"invalid Trailer key", k} } keys = append(keys, k) } if len(keys) > 0 { sort.Strings(keys) return strings.Join(keys, ","), nil } return "", nil } func (cc *ClientConn) responseHeaderTimeout() time.Duration { if cc.t.t1 != nil { return cc.t.t1.ResponseHeaderTimeout } // No way to do this (yet?) with just an http2.Transport. Probably // no need. Request.Cancel this is the new way. We only need to support // this for compatibility with the old http.Transport fields when // we're doing transparent http2. return 0 } // checkConnHeaders checks whether req has any invalid connection-level headers. // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields. // Certain headers are special-cased as okay but not transmitted later. func checkConnHeaders(req *http.Request) error { if v := req.Header.Get("Upgrade"); v != "" { return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"]) } if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") { return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv) } if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "close" && vv[0] != "keep-alive") { return fmt.Errorf("http2: invalid Connection request header: %q", vv) } return nil } // actualContentLength returns a sanitized version of // req.ContentLength, where 0 actually means zero (not unknown) and -1 // means unknown. func actualContentLength(req *http.Request) int64 { if req.Body == nil || reqBodyIsNoBody(req.Body) { return 0 } if req.ContentLength != 0 { return req.ContentLength } return -1 } func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { if err := checkConnHeaders(req); err != nil { return nil, err } if cc.idleTimer != nil { cc.idleTimer.Stop() } trailers, err := commaSeparatedTrailers(req) if err != nil { return nil, err } hasTrailers := trailers != "" cc.mu.Lock() if err := cc.awaitOpenSlotForRequest(req); err != nil { cc.mu.Unlock() return nil, err } body := req.Body contentLen := actualContentLength(req) hasBody := contentLen != 0 // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere? var requestedGzip bool if !cc.t.disableCompression() && req.Header.Get("Accept-Encoding") == "" && req.Header.Get("Range") == "" && req.Method != "HEAD" { // Request gzip only, not deflate. Deflate is ambiguous and // not as universally supported anyway. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 // // Note that we don't request this for HEAD requests, // due to a bug in nginx: // http://trac.nginx.org/nginx/ticket/358 // https://golang.org/issue/5522 // // We don't request gzip if the request is for a range, since // auto-decoding a portion of a gzipped document will just fail // anyway. See https://golang.org/issue/8923 requestedGzip = true } // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is // sent by writeRequestBody below, along with any Trailers, // again in form HEADERS{1}, CONTINUATION{0,}) hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen) if err != nil { cc.mu.Unlock() return nil, err } cs := cc.newStream() cs.req = req cs.trace = requestTrace(req) cs.requestedGzip = requestedGzip bodyWriter := cc.t.getBodyWriterState(cs, body) cs.on100 = bodyWriter.on100 cc.wmu.Lock() endStream := !hasBody && !hasTrailers werr := cc.writeHeaders(cs.ID, endStream, hdrs) cc.wmu.Unlock() traceWroteHeaders(cs.trace) cc.mu.Unlock() if werr != nil { if hasBody { req.Body.Close() // per RoundTripper contract bodyWriter.cancel() } cc.forgetStreamID(cs.ID) // Don't bother sending a RST_STREAM (our write already failed; // no need to keep writing) traceWroteRequest(cs.trace, werr) return nil, werr } var respHeaderTimer <-chan time.Time if hasBody { bodyWriter.scheduleBodyWrite() } else { traceWroteRequest(cs.trace, nil) if d := cc.responseHeaderTimeout(); d != 0 { timer := time.NewTimer(d) defer timer.Stop() respHeaderTimer = timer.C } } readLoopResCh := cs.resc bodyWritten := false ctx := reqContext(req) handleReadLoopResponse := func(re resAndError) (*http.Response, error) { res := re.res if re.err != nil || res.StatusCode > 299 { // On error or status code 3xx, 4xx, 5xx, etc abort any // ongoing write, assuming that the server doesn't care // about our request body. If the server replied with 1xx or // 2xx, however, then assume the server DOES potentially // want our body (e.g. full-duplex streaming: // golang.org/issue/13444). If it turns out the server // doesn't, they'll RST_STREAM us soon enough. This is a // heuristic to avoid adding knobs to Transport. Hopefully // we can keep it. bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWrite) } if re.err != nil { cc.mu.Lock() afterBodyWrite := cs.startedWrite cc.mu.Unlock() cc.forgetStreamID(cs.ID) if afterBodyWrite { return nil, afterReqBodyWriteError{re.err} } return nil, re.err } res.Request = req res.TLS = cc.tlsState return res, nil } for { select { case re := <-readLoopResCh: return handleReadLoopResponse(re) case <-respHeaderTimer: if !hasBody || bodyWritten { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } else { bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) } cc.forgetStreamID(cs.ID) return nil, errTimeout case <-ctx.Done(): if !hasBody || bodyWritten { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } else { bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) } cc.forgetStreamID(cs.ID) return nil, ctx.Err() case <-req.Cancel: if !hasBody || bodyWritten { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } else { bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) } cc.forgetStreamID(cs.ID) return nil, errRequestCanceled case <-cs.peerReset: // processResetStream already removed the // stream from the streams map; no need for // forgetStreamID. return nil, cs.resetErr case err := <-bodyWriter.resc: // Prefer the read loop's response, if available. Issue 16102. select { case re := <-readLoopResCh: return handleReadLoopResponse(re) default: } if err != nil { return nil, err } bodyWritten = true if d := cc.responseHeaderTimeout(); d != 0 { timer := time.NewTimer(d) defer timer.Stop() respHeaderTimer = timer.C } } } } // awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams. // Must hold cc.mu. func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error { var waitingForConn chan struct{} var waitingForConnErr error // guarded by cc.mu for { cc.lastActive = time.Now() if cc.closed || !cc.canTakeNewRequestLocked() { return errClientConnUnusable } if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) { if waitingForConn != nil { close(waitingForConn) } return nil } // Unfortunately, we cannot wait on a condition variable and channel at // the same time, so instead, we spin up a goroutine to check if the // request is canceled while we wait for a slot to open in the connection. if waitingForConn == nil { waitingForConn = make(chan struct{}) go func() { if err := awaitRequestCancel(req, waitingForConn); err != nil { cc.mu.Lock() waitingForConnErr = err cc.cond.Broadcast() cc.mu.Unlock() } }() } cc.pendingRequests++ cc.cond.Wait() cc.pendingRequests-- if waitingForConnErr != nil { return waitingForConnErr } } } // requires cc.wmu be held func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, hdrs []byte) error { first := true // first frame written (HEADERS is first, then CONTINUATION) frameSize := int(cc.maxFrameSize) for len(hdrs) > 0 && cc.werr == nil { chunk := hdrs if len(chunk) > frameSize { chunk = chunk[:frameSize] } hdrs = hdrs[len(chunk):] endHeaders := len(hdrs) == 0 if first { cc.fr.WriteHeaders(HeadersFrameParam{ StreamID: streamID, BlockFragment: chunk, EndStream: endStream, EndHeaders: endHeaders, }) first = false } else { cc.fr.WriteContinuation(streamID, endHeaders, chunk) } } // TODO(bradfitz): this Flush could potentially block (as // could the WriteHeaders call(s) above), which means they // wouldn't respond to Request.Cancel being readable. That's // rare, but this should probably be in a goroutine. cc.bw.Flush() return cc.werr } // internal error values; they don't escape to callers var ( // abort request body write; don't send cancel errStopReqBodyWrite = errors.New("http2: aborting request body write") // abort request body write, but send stream reset of cancel. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request") ) func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) { cc := cs.cc sentEnd := false // whether we sent the final DATA frame w/ END_STREAM buf := cc.frameScratchBuffer() defer cc.putFrameScratchBuffer(buf) defer func() { traceWroteRequest(cs.trace, err) // TODO: write h12Compare test showing whether // Request.Body is closed by the Transport, // and in multiple cases: server replies <=299 and >299 // while still writing request body cerr := bodyCloser.Close() if err == nil { err = cerr } }() req := cs.req hasTrailers := req.Trailer != nil var sawEOF bool for !sawEOF { n, err := body.Read(buf) if err == io.EOF { sawEOF = true err = nil } else if err != nil { return err } remain := buf[:n] for len(remain) > 0 && err == nil { var allowed int32 allowed, err = cs.awaitFlowControl(len(remain)) switch { case err == errStopReqBodyWrite: return err case err == errStopReqBodyWriteAndCancel: cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) return err case err != nil: return err } cc.wmu.Lock() data := remain[:allowed] remain = remain[allowed:] sentEnd = sawEOF && len(remain) == 0 && !hasTrailers err = cc.fr.WriteData(cs.ID, sentEnd, data) if err == nil { // TODO(bradfitz): this flush is for latency, not bandwidth. // Most requests won't need this. Make this opt-in or // opt-out? Use some heuristic on the body type? Nagel-like // timers? Based on 'n'? Only last chunk of this for loop, // unless flow control tokens are low? For now, always. // If we change this, see comment below. err = cc.bw.Flush() } cc.wmu.Unlock() } if err != nil { return err } } if sentEnd { // Already sent END_STREAM (which implies we have no // trailers) and flushed, because currently all // WriteData frames above get a flush. So we're done. return nil } var trls []byte if hasTrailers { cc.mu.Lock() trls, err = cc.encodeTrailers(req) cc.mu.Unlock() if err != nil { cc.writeStreamReset(cs.ID, ErrCodeInternal, err) cc.forgetStreamID(cs.ID) return err } } cc.wmu.Lock() defer cc.wmu.Unlock() // Two ways to send END_STREAM: either with trailers, or // with an empty DATA frame. if len(trls) > 0 { err = cc.writeHeaders(cs.ID, true, trls) } else { err = cc.fr.WriteData(cs.ID, true, nil) } if ferr := cc.bw.Flush(); ferr != nil && err == nil { err = ferr } return err } // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow // control tokens from the server. // It returns either the non-zero number of tokens taken or an error // if the stream is dead. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) { cc := cs.cc cc.mu.Lock() defer cc.mu.Unlock() for { if cc.closed { return 0, errClientConnClosed } if cs.stopReqBody != nil { return 0, cs.stopReqBody } if err := cs.checkResetOrDone(); err != nil { return 0, err } if a := cs.flow.available(); a > 0 { take := a if int(take) > maxBytes { take = int32(maxBytes) // can't truncate int; take is int32 } if take > int32(cc.maxFrameSize) { take = int32(cc.maxFrameSize) } cs.flow.take(take) return take, nil } cc.cond.Wait() } } type badStringError struct { what string str string } func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) } // requires cc.mu be held. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) { cc.hbuf.Reset() host := req.Host if host == "" { host = req.URL.Host } host, err := httplex.PunycodeHostPort(host) if err != nil { return nil, err } var path string if req.Method != "CONNECT" { path = req.URL.RequestURI() if !validPseudoPath(path) { orig := path path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host) if !validPseudoPath(path) { if req.URL.Opaque != "" { return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque) } else { return nil, fmt.Errorf("invalid request :path %q", orig) } } } } // Check for any invalid headers and return an error before we // potentially pollute our hpack state. (We want to be able to // continue to reuse the hpack encoder for future requests) for k, vv := range req.Header { if !httplex.ValidHeaderFieldName(k) { return nil, fmt.Errorf("invalid HTTP header name %q", k) } for _, v := range vv { if !httplex.ValidHeaderFieldValue(v) { return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k) } } } enumerateHeaders := func(f func(name, value string)) { // 8.1.2.3 Request Pseudo-Header Fields // The :path pseudo-header field includes the path and query parts of the // target URI (the path-absolute production and optionally a '?' character // followed by the query production (see Sections 3.3 and 3.4 of // [RFC3986]). f(":authority", host) f(":method", req.Method) if req.Method != "CONNECT" { f(":path", path) f(":scheme", req.URL.Scheme) } if trailers != "" { f("trailer", trailers) } var didUA bool for k, vv := range req.Header { if strings.EqualFold(k, "host") || strings.EqualFold(k, "content-length") { // Host is :authority, already sent. // Content-Length is automatic, set below. continue } else if strings.EqualFold(k, "connection") || strings.EqualFold(k, "proxy-connection") || strings.EqualFold(k, "transfer-encoding") || strings.EqualFold(k, "upgrade") || strings.EqualFold(k, "keep-alive") { // Per 8.1.2.2 Connection-Specific Header // Fields, don't send connection-specific // fields. We have already checked if any // are error-worthy so just ignore the rest. continue } else if strings.EqualFold(k, "user-agent") { // Match Go's http1 behavior: at most one // User-Agent. If set to nil or empty string, // then omit it. Otherwise if not mentioned, // include the default (below). didUA = true if len(vv) < 1 { continue } vv = vv[:1] if vv[0] == "" { continue } } for _, v := range vv { f(k, v) } } if shouldSendReqContentLength(req.Method, contentLength) { f("content-length", strconv.FormatInt(contentLength, 10)) } if addGzipHeader { f("accept-encoding", "gzip") } if !didUA { f("user-agent", defaultUserAgent) } } // Do a first pass over the headers counting bytes to ensure // we don't exceed cc.peerMaxHeaderListSize. This is done as a // separate pass before encoding the headers to prevent // modifying the hpack state. hlSize := uint64(0) enumerateHeaders(func(name, value string) { hf := hpack.HeaderField{Name: name, Value: value} hlSize += uint64(hf.Size()) }) if hlSize > cc.peerMaxHeaderListSize { return nil, errRequestHeaderListSize } // Header list size is ok. Write the headers. enumerateHeaders(func(name, value string) { cc.writeHeader(strings.ToLower(name), value) }) return cc.hbuf.Bytes(), nil } // shouldSendReqContentLength reports whether the http2.Transport should send // a "content-length" request header. This logic is basically a copy of the net/http // transferWriter.shouldSendContentLength. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown). // -1 means unknown. func shouldSendReqContentLength(method string, contentLength int64) bool { if contentLength > 0 { return true } if contentLength < 0 { return false } // For zero bodies, whether we send a content-length depends on the method. // It also kinda doesn't matter for http2 either way, with END_STREAM. switch method { case "POST", "PUT", "PATCH": return true default: return false } } // requires cc.mu be held. func (cc *ClientConn) encodeTrailers(req *http.Request) ([]byte, error) { cc.hbuf.Reset() hlSize := uint64(0) for k, vv := range req.Trailer { for _, v := range vv { hf := hpack.HeaderField{Name: k, Value: v} hlSize += uint64(hf.Size()) } } if hlSize > cc.peerMaxHeaderListSize { return nil, errRequestHeaderListSize } for k, vv := range req.Trailer { // Transfer-Encoding, etc.. have already been filtered at the // start of RoundTrip lowKey := strings.ToLower(k) for _, v := range vv { cc.writeHeader(lowKey, v) } } return cc.hbuf.Bytes(), nil } func (cc *ClientConn) writeHeader(name, value string) { if VerboseLogs { log.Printf("http2: Transport encoding header %q = %q", name, value) } cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value}) } type resAndError struct { res *http.Response err error } // requires cc.mu be held. func (cc *ClientConn) newStream() *clientStream { cs := &clientStream{ cc: cc, ID: cc.nextStreamID, resc: make(chan resAndError, 1), peerReset: make(chan struct{}), done: make(chan struct{}), } cs.flow.add(int32(cc.initialWindowSize)) cs.flow.setConnFlow(&cc.flow) cs.inflow.add(transportDefaultStreamFlow) cs.inflow.setConnFlow(&cc.inflow) cc.nextStreamID += 2 cc.streams[cs.ID] = cs return cs } func (cc *ClientConn) forgetStreamID(id uint32) { cc.streamByID(id, true) } func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream { cc.mu.Lock() defer cc.mu.Unlock() cs := cc.streams[id] if andRemove && cs != nil && !cc.closed { cc.lastActive = time.Now() delete(cc.streams, id) if len(cc.streams) == 0 && cc.idleTimer != nil { cc.idleTimer.Reset(cc.idleTimeout) } close(cs.done) // Wake up checkResetOrDone via clientStream.awaitFlowControl and // wake up RoundTrip if there is a pending request. cc.cond.Broadcast() } return cs } // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop. type clientConnReadLoop struct { cc *ClientConn activeRes map[uint32]*clientStream // keyed by streamID closeWhenIdle bool } // readLoop runs in its own goroutine and reads and dispatches frames. func (cc *ClientConn) readLoop() { rl := &clientConnReadLoop{ cc: cc, activeRes: make(map[uint32]*clientStream), } defer rl.cleanup() cc.readerErr = rl.run() if ce, ok := cc.readerErr.(ConnectionError); ok { cc.wmu.Lock() cc.fr.WriteGoAway(0, ErrCode(ce), nil) cc.wmu.Unlock() } } // GoAwayError is returned by the Transport when the server closes the // TCP connection after sending a GOAWAY frame. type GoAwayError struct { LastStreamID uint32 ErrCode ErrCode DebugData string } func (e GoAwayError) Error() string { return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q", e.LastStreamID, e.ErrCode, e.DebugData) } func isEOFOrNetReadError(err error) bool { if err == io.EOF { return true } ne, ok := err.(*net.OpError) return ok && ne.Op == "read" } func (rl *clientConnReadLoop) cleanup() { cc := rl.cc defer cc.tconn.Close() defer cc.t.connPool().MarkDead(cc) defer close(cc.readerDone) if cc.idleTimer != nil { cc.idleTimer.Stop() } // Close any response bodies if the server closes prematurely. // TODO: also do this if we've written the headers but not // gotten a response yet. err := cc.readerErr cc.mu.Lock() if cc.goAway != nil && isEOFOrNetReadError(err) { err = GoAwayError{ LastStreamID: cc.goAway.LastStreamID, ErrCode: cc.goAway.ErrCode, DebugData: cc.goAwayDebug, } } else if err == io.EOF { err = io.ErrUnexpectedEOF } for _, cs := range rl.activeRes { cs.bufPipe.CloseWithError(err) } for _, cs := range cc.streams { select { case cs.resc <- resAndError{err: err}: default: } close(cs.done) } cc.closed = true cc.cond.Broadcast() cc.mu.Unlock() } func (rl *clientConnReadLoop) run() error { cc := rl.cc rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse gotReply := false // ever saw a HEADERS reply gotSettings := false for { f, err := cc.fr.ReadFrame() if err != nil { cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err) } if se, ok := err.(StreamError); ok { if cs := cc.streamByID(se.StreamID, false); cs != nil { cs.cc.writeStreamReset(cs.ID, se.Code, err) cs.cc.forgetStreamID(cs.ID) if se.Cause == nil { se.Cause = cc.fr.errDetail } rl.endStreamError(cs, se) } continue } else if err != nil { return err } if VerboseLogs { cc.vlogf("http2: Transport received %s", summarizeFrame(f)) } if !gotSettings { if _, ok := f.(*SettingsFrame); !ok { cc.logf("protocol error: received %T before a SETTINGS frame", f) return ConnectionError(ErrCodeProtocol) } gotSettings = true } maybeIdle := false // whether frame might transition us to idle switch f := f.(type) { case *MetaHeadersFrame: err = rl.processHeaders(f) maybeIdle = true gotReply = true case *DataFrame: err = rl.processData(f) maybeIdle = true case *GoAwayFrame: err = rl.processGoAway(f) maybeIdle = true case *RSTStreamFrame: err = rl.processResetStream(f) maybeIdle = true case *SettingsFrame: err = rl.processSettings(f) case *PushPromiseFrame: err = rl.processPushPromise(f) case *WindowUpdateFrame: err = rl.processWindowUpdate(f) case *PingFrame: err = rl.processPing(f) default: cc.logf("Transport: unhandled response frame type %T", f) } if err != nil { if VerboseLogs { cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err) } return err } if rl.closeWhenIdle && gotReply && maybeIdle && len(rl.activeRes) == 0 { cc.closeIfIdle() } } } func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { cc := rl.cc if f.StreamEnded() { // Issue 20521: If the stream has ended, streamByID() causes // clientStream.done to be closed, which causes the request's bodyWriter // to be closed with an errStreamClosed, which may be received by // clientConn.RoundTrip before the result of processing these headers. // Deferring stream closure allows the header processing to occur first. // clientConn.RoundTrip may still receive the bodyWriter error first, but // the fix for issue 16102 prioritises any response. defer cc.streamByID(f.StreamID, true) } cs := cc.streamByID(f.StreamID, false) if cs == nil { // We'd get here if we canceled a request while the // server had its response still in flight. So if this // was just something we canceled, ignore it. return nil } if !cs.firstByte { if cs.trace != nil { // TODO(bradfitz): move first response byte earlier, // when we first read the 9 byte header, not waiting // until all the HEADERS+CONTINUATION frames have been // merged. This works for now. traceFirstResponseByte(cs.trace) } cs.firstByte = true } if !cs.pastHeaders { cs.pastHeaders = true } else { return rl.processTrailers(cs, f) } res, err := rl.handleResponse(cs, f) if err != nil { if _, ok := err.(ConnectionError); ok { return err } // Any other error type is a stream error. cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err) cs.resc <- resAndError{err: err} return nil // return nil from process* funcs to keep conn alive } if res == nil { // (nil, nil) special case. See handleResponse docs. return nil } if res.Body != noBody { rl.activeRes[cs.ID] = cs } cs.resTrailer = &res.Trailer cs.resc <- resAndError{res: res} return nil } // may return error types nil, or ConnectionError. Any other error value // is a StreamError of type ErrCodeProtocol. The returned error in that case // is the detail. // // As a special case, handleResponse may return (nil, nil) to skip the // frame (currently only used for 100 expect continue). This special // case is going away after Issue 13851 is fixed. func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) { if f.Truncated { return nil, errResponseHeaderListSize } status := f.PseudoValue("status") if status == "" { return nil, errors.New("missing status pseudo header") } statusCode, err := strconv.Atoi(status) if err != nil { return nil, errors.New("malformed non-numeric status pseudo header") } if statusCode == 100 { traceGot100Continue(cs.trace) if cs.on100 != nil { cs.on100() // forces any write delay timer to fire } cs.pastHeaders = false // do it all again return nil, nil } header := make(http.Header) res := &http.Response{ Proto: "HTTP/2.0", ProtoMajor: 2, Header: header, StatusCode: statusCode, Status: status + " " + http.StatusText(statusCode), } for _, hf := range f.RegularFields() { key := http.CanonicalHeaderKey(hf.Name) if key == "Trailer" { t := res.Trailer if t == nil { t = make(http.Header) res.Trailer = t } foreachHeaderElement(hf.Value, func(v string) { t[http.CanonicalHeaderKey(v)] = nil }) } else { header[key] = append(header[key], hf.Value) } } streamEnded := f.StreamEnded() isHead := cs.req.Method == "HEAD" if !streamEnded || isHead { res.ContentLength = -1 if clens := res.Header["Content-Length"]; len(clens) == 1 { if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil { res.ContentLength = clen64 } else { // TODO: care? unlike http/1, it won't mess up our framing, so it's // more safe smuggling-wise to ignore. } } else if len(clens) > 1 { // TODO: care? unlike http/1, it won't mess up our framing, so it's // more safe smuggling-wise to ignore. } } if streamEnded || isHead { res.Body = noBody return res, nil } cs.bufPipe = pipe{b: &dataBuffer{expected: res.ContentLength}} cs.bytesRemain = res.ContentLength res.Body = transportResponseBody{cs} go cs.awaitRequestCancel(cs.req) if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" { res.Header.Del("Content-Encoding") res.Header.Del("Content-Length") res.ContentLength = -1 res.Body = &gzipReader{body: res.Body} setResponseUncompressed(res) } return res, nil } func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error { if cs.pastTrailers { // Too many HEADERS frames for this stream. return ConnectionError(ErrCodeProtocol) } cs.pastTrailers = true if !f.StreamEnded() { // We expect that any headers for trailers also // has END_STREAM. return ConnectionError(ErrCodeProtocol) } if len(f.PseudoFields()) > 0 { // No pseudo header fields are defined for trailers. // TODO: ConnectionError might be overly harsh? Check. return ConnectionError(ErrCodeProtocol) } trailer := make(http.Header) for _, hf := range f.RegularFields() { key := http.CanonicalHeaderKey(hf.Name) trailer[key] = append(trailer[key], hf.Value) } cs.trailer = trailer rl.endStream(cs) return nil } // transportResponseBody is the concrete type of Transport.RoundTrip's // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body. // On Close it sends RST_STREAM if EOF wasn't already seen. type transportResponseBody struct { cs *clientStream } func (b transportResponseBody) Read(p []byte) (n int, err error) { cs := b.cs cc := cs.cc if cs.readErr != nil { return 0, cs.readErr } n, err = b.cs.bufPipe.Read(p) if cs.bytesRemain != -1 { if int64(n) > cs.bytesRemain { n = int(cs.bytesRemain) if err == nil { err = errors.New("net/http: server replied with more than declared Content-Length; truncated") cc.writeStreamReset(cs.ID, ErrCodeProtocol, err) } cs.readErr = err return int(cs.bytesRemain), err } cs.bytesRemain -= int64(n) if err == io.EOF && cs.bytesRemain > 0 { err = io.ErrUnexpectedEOF cs.readErr = err return n, err } } if n == 0 { // No flow control tokens to send back. return } cc.mu.Lock() defer cc.mu.Unlock() var connAdd, streamAdd int32 // Check the conn-level first, before the stream-level. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 { connAdd = transportDefaultConnFlow - v cc.inflow.add(connAdd) } if err == nil { // No need to refresh if the stream is over or failed. // Consider any buffered body data (read from the conn but not // consumed by the client) when computing flow control for this // stream. v := int(cs.inflow.available()) + cs.bufPipe.Len() if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh { streamAdd = int32(transportDefaultStreamFlow - v) cs.inflow.add(streamAdd) } } if connAdd != 0 || streamAdd != 0 { cc.wmu.Lock() defer cc.wmu.Unlock() if connAdd != 0 { cc.fr.WriteWindowUpdate(0, mustUint31(connAdd)) } if streamAdd != 0 { cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd)) } cc.bw.Flush() } return } var errClosedResponseBody = errors.New("http2: response body closed") func (b transportResponseBody) Close() error { cs := b.cs cc := cs.cc serverSentStreamEnd := cs.bufPipe.Err() == io.EOF unread := cs.bufPipe.Len() if unread > 0 || !serverSentStreamEnd { cc.mu.Lock() cc.wmu.Lock() if !serverSentStreamEnd { cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel) cs.didReset = true } // Return connection-level flow control. if unread > 0 { cc.inflow.add(int32(unread)) cc.fr.WriteWindowUpdate(0, uint32(unread)) } cc.bw.Flush() cc.wmu.Unlock() cc.mu.Unlock() } cs.bufPipe.BreakWithError(errClosedResponseBody) cc.forgetStreamID(cs.ID) return nil } func (rl *clientConnReadLoop) processData(f *DataFrame) error { cc := rl.cc cs := cc.streamByID(f.StreamID, f.StreamEnded()) data := f.Data() if cs == nil { cc.mu.Lock() neverSent := cc.nextStreamID cc.mu.Unlock() if f.StreamID >= neverSent { // We never asked for this. cc.logf("http2: Transport received unsolicited DATA frame; closing connection") return ConnectionError(ErrCodeProtocol) } // We probably did ask for this, but canceled. Just ignore it. // TODO: be stricter here? only silently ignore things which // we canceled, but not things which were closed normally // by the peer? Tough without accumulating too much state. // But at least return their flow control: if f.Length > 0 { cc.mu.Lock() cc.inflow.add(int32(f.Length)) cc.mu.Unlock() cc.wmu.Lock() cc.fr.WriteWindowUpdate(0, uint32(f.Length)) cc.bw.Flush() cc.wmu.Unlock() } return nil } if !cs.firstByte { cc.logf("protocol error: received DATA before a HEADERS frame") rl.endStreamError(cs, StreamError{ StreamID: f.StreamID, Code: ErrCodeProtocol, }) return nil } if f.Length > 0 { // Check connection-level flow control. cc.mu.Lock() if cs.inflow.available() >= int32(f.Length) { cs.inflow.take(int32(f.Length)) } else { cc.mu.Unlock() return ConnectionError(ErrCodeFlowControl) } // Return any padded flow control now, since we won't // refund it later on body reads. var refund int if pad := int(f.Length) - len(data); pad > 0 { refund += pad } // Return len(data) now if the stream is already closed, // since data will never be read. didReset := cs.didReset if didReset { refund += len(data) } if refund > 0 { cc.inflow.add(int32(refund)) cc.wmu.Lock() cc.fr.WriteWindowUpdate(0, uint32(refund)) if !didReset { cs.inflow.add(int32(refund)) cc.fr.WriteWindowUpdate(cs.ID, uint32(refund)) } cc.bw.Flush() cc.wmu.Unlock() } cc.mu.Unlock() if len(data) > 0 && !didReset { if _, err := cs.bufPipe.Write(data); err != nil { rl.endStreamError(cs, err) return err } } } if f.StreamEnded() { rl.endStream(cs) } return nil } var errInvalidTrailers = errors.New("http2: invalid trailers") func (rl *clientConnReadLoop) endStream(cs *clientStream) { // TODO: check that any declared content-length matches, like // server.go's (*stream).endStream method. rl.endStreamError(cs, nil) } func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) { var code func() if err == nil { err = io.EOF code = cs.copyTrailers } cs.bufPipe.closeWithErrorAndCode(err, code) delete(rl.activeRes, cs.ID) if isConnectionCloseRequest(cs.req) { rl.closeWhenIdle = true } select { case cs.resc <- resAndError{err: err}: default: } } func (cs *clientStream) copyTrailers() { for k, vv := range cs.trailer { t := cs.resTrailer if *t == nil { *t = make(http.Header) } (*t)[k] = vv } } func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error { cc := rl.cc cc.t.connPool().MarkDead(cc) if f.ErrCode != 0 { // TODO: deal with GOAWAY more. particularly the error code cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode) } cc.setGoAway(f) return nil } func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error { cc := rl.cc cc.mu.Lock() defer cc.mu.Unlock() if f.IsAck() { if cc.wantSettingsAck { cc.wantSettingsAck = false return nil } return ConnectionError(ErrCodeProtocol) } err := f.ForeachSetting(func(s Setting) error { switch s.ID { case SettingMaxFrameSize: cc.maxFrameSize = s.Val case SettingMaxConcurrentStreams: cc.maxConcurrentStreams = s.Val case SettingMaxHeaderListSize: cc.peerMaxHeaderListSize = uint64(s.Val) case SettingInitialWindowSize: // Values above the maximum flow-control // window size of 2^31-1 MUST be treated as a // connection error (Section 5.4.1) of type // FLOW_CONTROL_ERROR. if s.Val > math.MaxInt32 { return ConnectionError(ErrCodeFlowControl) } // Adjust flow control of currently-open // frames by the difference of the old initial // window size and this one. delta := int32(s.Val) - int32(cc.initialWindowSize) for _, cs := range cc.streams { cs.flow.add(delta) } cc.cond.Broadcast() cc.initialWindowSize = s.Val default: // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably. cc.vlogf("Unhandled Setting: %v", s) } return nil }) if err != nil { return err } cc.wmu.Lock() defer cc.wmu.Unlock() cc.fr.WriteSettingsAck() cc.bw.Flush() return cc.werr } func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error { cc := rl.cc cs := cc.streamByID(f.StreamID, false) if f.StreamID != 0 && cs == nil { return nil } cc.mu.Lock() defer cc.mu.Unlock() fl := &cc.flow if cs != nil { fl = &cs.flow } if !fl.add(int32(f.Increment)) { return ConnectionError(ErrCodeFlowControl) } cc.cond.Broadcast() return nil } func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error { cs := rl.cc.streamByID(f.StreamID, true) if cs == nil { // TODO: return error if server tries to RST_STEAM an idle stream return nil } select { case <-cs.peerReset: // Already reset. // This is the only goroutine // which closes this, so there // isn't a race. default: err := streamError(cs.ID, f.ErrCode) cs.resetErr = err close(cs.peerReset) cs.bufPipe.CloseWithError(err) cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl } delete(rl.activeRes, cs.ID) return nil } // Ping sends a PING frame to the server and waits for the ack. // Public implementation is in go17.go and not_go17.go func (cc *ClientConn) ping(ctx contextContext) error { c := make(chan struct{}) // Generate a random payload var p [8]byte for { if _, err := rand.Read(p[:]); err != nil { return err } cc.mu.Lock() // check for dup before insert if _, found := cc.pings[p]; !found { cc.pings[p] = c cc.mu.Unlock() break } cc.mu.Unlock() } cc.wmu.Lock() if err := cc.fr.WritePing(false, p); err != nil { cc.wmu.Unlock() return err } if err := cc.bw.Flush(); err != nil { cc.wmu.Unlock() return err } cc.wmu.Unlock() select { case <-c: return nil case <-ctx.Done(): return ctx.Err() case <-cc.readerDone: // connection closed return cc.readerErr } } func (rl *clientConnReadLoop) processPing(f *PingFrame) error { if f.IsAck() { cc := rl.cc cc.mu.Lock() defer cc.mu.Unlock() // If ack, notify listener if any if c, ok := cc.pings[f.Data]; ok { close(c) delete(cc.pings, f.Data) } return nil } cc := rl.cc cc.wmu.Lock() defer cc.wmu.Unlock() if err := cc.fr.WritePing(true, f.Data); err != nil { return err } return cc.bw.Flush() } func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error { // We told the peer we don't want them. // Spec says: // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH // setting of the peer endpoint is set to 0. An endpoint that // has set this setting and has received acknowledgement MUST // treat the receipt of a PUSH_PROMISE frame as a connection // error (Section 5.4.1) of type PROTOCOL_ERROR." return ConnectionError(ErrCodeProtocol) } func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) { // TODO: map err to more interesting error codes, once the // HTTP community comes up with some. But currently for // RST_STREAM there's no equivalent to GOAWAY frame's debug // data, and the error codes are all pretty vague ("cancel"). cc.wmu.Lock() cc.fr.WriteRSTStream(streamID, code) cc.bw.Flush() cc.wmu.Unlock() } var ( errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit") errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit") errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers") ) func (cc *ClientConn) logf(format string, args ...interface{}) { cc.t.logf(format, args...) } func (cc *ClientConn) vlogf(format string, args ...interface{}) { cc.t.vlogf(format, args...) } func (t *Transport) vlogf(format string, args ...interface{}) { if VerboseLogs { t.logf(format, args...) } } func (t *Transport) logf(format string, args ...interface{}) { log.Printf(format, args...) } var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil)) func strSliceContains(ss []string, s string) bool { for _, v := range ss { if v == s { return true } } return false } type erringRoundTripper struct{ err error } func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err } // gzipReader wraps a response body so it can lazily // call gzip.NewReader on the first call to Read type gzipReader struct { body io.ReadCloser // underlying Response.Body zr *gzip.Reader // lazily-initialized gzip reader zerr error // sticky error } func (gz *gzipReader) Read(p []byte) (n int, err error) { if gz.zerr != nil { return 0, gz.zerr } if gz.zr == nil { gz.zr, err = gzip.NewReader(gz.body) if err != nil { gz.zerr = err return 0, err } } return gz.zr.Read(p) } func (gz *gzipReader) Close() error { return gz.body.Close() } type errorReader struct{ err error } func (r errorReader) Read(p []byte) (int, error) { return 0, r.err } // bodyWriterState encapsulates various state around the Transport's writing // of the request body, particularly regarding doing delayed writes of the body // when the request contains "Expect: 100-continue". type bodyWriterState struct { cs *clientStream timer *time.Timer // if non-nil, we're doing a delayed write fnonce *sync.Once // to call fn with fn func() // the code to run in the goroutine, writing the body resc chan error // result of fn's execution delay time.Duration // how long we should delay a delayed write for } func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) { s.cs = cs if body == nil { return } resc := make(chan error, 1) s.resc = resc s.fn = func() { cs.cc.mu.Lock() cs.startedWrite = true cs.cc.mu.Unlock() resc <- cs.writeRequestBody(body, cs.req.Body) } s.delay = t.expectContinueTimeout() if s.delay == 0 || !httplex.HeaderValuesContainsToken( cs.req.Header["Expect"], "100-continue") { return } s.fnonce = new(sync.Once) // Arm the timer with a very large duration, which we'll // intentionally lower later. It has to be large now because // we need a handle to it before writing the headers, but the // s.delay value is defined to not start until after the // request headers were written. const hugeDuration = 365 * 24 * time.Hour s.timer = time.AfterFunc(hugeDuration, func() { s.fnonce.Do(s.fn) }) return } func (s bodyWriterState) cancel() { if s.timer != nil { s.timer.Stop() } } func (s bodyWriterState) on100() { if s.timer == nil { // If we didn't do a delayed write, ignore the server's // bogus 100 continue response. return } s.timer.Stop() go func() { s.fnonce.Do(s.fn) }() } // scheduleBodyWrite starts writing the body, either immediately (in // the common case) or after the delay timeout. It should not be // called until after the headers have been written. func (s bodyWriterState) scheduleBodyWrite() { if s.timer == nil { // We're not doing a delayed write (see // getBodyWriterState), so just start the writing // goroutine immediately. go s.fn() return } traceWait100Continue(s.cs.trace) if s.timer.Stop() { s.timer.Reset(s.delay) } } // isConnectionCloseRequest reports whether req should use its own // connection for a single request and then close the connection. func isConnectionCloseRequest(req *http.Request) bool { return req.Close || httplex.HeaderValuesContainsToken(req.Header["Connection"], "close") } lxd-2.0.11/dist/src/golang.org/x/net/http2/testdata/0000755061062106075000000000000013172163402023165 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/http2/testdata/draft-ietf-httpbis-http2.xml0000644061062106075000000076726513172163402030475 0ustar stgraberdomain admins Hypertext Transfer Protocol version 2 Twist
mbelshe@chromium.org
Google, Inc
fenix@google.com
Mozilla
331 E Evelyn Street Mountain View CA 94041 US martin.thomson@gmail.com
Applications HTTPbis HTTP SPDY Web This specification describes an optimized expression of the semantics of the Hypertext Transfer Protocol (HTTP). HTTP/2 enables a more efficient use of network resources and a reduced perception of latency by introducing header field compression and allowing multiple concurrent messages on the same connection. It also introduces unsolicited push of representations from servers to clients. This specification is an alternative to, but does not obsolete, the HTTP/1.1 message syntax. HTTP's existing semantics remain unchanged. Discussion of this draft takes place on the HTTPBIS working group mailing list (ietf-http-wg@w3.org), which is archived at . Working Group information can be found at ; that specific to HTTP/2 are at . The changes in this draft are summarized in .
The Hypertext Transfer Protocol (HTTP) is a wildly successful protocol. However, the HTTP/1.1 message format () has several characteristics that have a negative overall effect on application performance today. In particular, HTTP/1.0 allowed only one request to be outstanding at a time on a given TCP connection. HTTP/1.1 added request pipelining, but this only partially addressed request concurrency and still suffers from head-of-line blocking. Therefore, HTTP/1.1 clients that need to make many requests typically use multiple connections to a server in order to achieve concurrency and thereby reduce latency. Furthermore, HTTP header fields are often repetitive and verbose, causing unnecessary network traffic, as well as causing the initial TCP congestion window to quickly fill. This can result in excessive latency when multiple requests are made on a new TCP connection. HTTP/2 addresses these issues by defining an optimized mapping of HTTP's semantics to an underlying connection. Specifically, it allows interleaving of request and response messages on the same connection and uses an efficient coding for HTTP header fields. It also allows prioritization of requests, letting more important requests complete more quickly, further improving performance. The resulting protocol is more friendly to the network, because fewer TCP connections can be used in comparison to HTTP/1.x. This means less competition with other flows, and longer-lived connections, which in turn leads to better utilization of available network capacity. Finally, HTTP/2 also enables more efficient processing of messages through use of binary message framing.
HTTP/2 provides an optimized transport for HTTP semantics. HTTP/2 supports all of the core features of HTTP/1.1, but aims to be more efficient in several ways. The basic protocol unit in HTTP/2 is a frame. Each frame type serves a different purpose. For example, HEADERS and DATA frames form the basis of HTTP requests and responses; other frame types like SETTINGS, WINDOW_UPDATE, and PUSH_PROMISE are used in support of other HTTP/2 features. Multiplexing of requests is achieved by having each HTTP request-response exchange associated with its own stream. Streams are largely independent of each other, so a blocked or stalled request or response does not prevent progress on other streams. Flow control and prioritization ensure that it is possible to efficiently use multiplexed streams. Flow control helps to ensure that only data that can be used by a receiver is transmitted. Prioritization ensures that limited resources can be directed to the most important streams first. HTTP/2 adds a new interaction mode, whereby a server can push responses to a client. Server push allows a server to speculatively send a client data that the server anticipates the client will need, trading off some network usage against a potential latency gain. The server does this by synthesizing a request, which it sends as a PUSH_PROMISE frame. The server is then able to send a response to the synthetic request on a separate stream. Frames that contain HTTP header fields are compressed. HTTP requests can be highly redundant, so compression can reduce the size of requests and responses significantly.
The HTTP/2 specification is split into four parts: Starting HTTP/2 covers how an HTTP/2 connection is initiated. The framing and streams layers describe the way HTTP/2 frames are structured and formed into multiplexed streams. Frame and error definitions include details of the frame and error types used in HTTP/2. HTTP mappings and additional requirements describe how HTTP semantics are expressed using frames and streams. While some of the frame and stream layer concepts are isolated from HTTP, this specification does not define a completely generic framing layer. The framing and streams layers are tailored to the needs of the HTTP protocol and server push.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. All numeric values are in network byte order. Values are unsigned unless otherwise indicated. Literal values are provided in decimal or hexadecimal as appropriate. Hexadecimal literals are prefixed with 0x to distinguish them from decimal literals. The following terms are used: The endpoint initiating the HTTP/2 connection. A transport-layer connection between two endpoints. An error that affects the entire HTTP/2 connection. Either the client or server of the connection. The smallest unit of communication within an HTTP/2 connection, consisting of a header and a variable-length sequence of octets structured according to the frame type. An endpoint. When discussing a particular endpoint, "peer" refers to the endpoint that is remote to the primary subject of discussion. An endpoint that is receiving frames. An endpoint that is transmitting frames. The endpoint which did not initiate the HTTP/2 connection. A bi-directional flow of frames across a virtual channel within the HTTP/2 connection. An error on the individual HTTP/2 stream. Finally, the terms "gateway", "intermediary", "proxy", and "tunnel" are defined in .
An HTTP/2 connection is an application layer protocol running on top of a TCP connection (). The client is the TCP connection initiator. HTTP/2 uses the same "http" and "https" URI schemes used by HTTP/1.1. HTTP/2 shares the same default port numbers: 80 for "http" URIs and 443 for "https" URIs. As a result, implementations processing requests for target resource URIs like http://example.org/foo or https://example.com/bar are required to first discover whether the upstream server (the immediate peer to which the client wishes to establish a connection) supports HTTP/2. The means by which support for HTTP/2 is determined is different for "http" and "https" URIs. Discovery for "http" URIs is described in . Discovery for "https" URIs is described in .
The protocol defined in this document has two identifiers. The string "h2" identifies the protocol where HTTP/2 uses TLS. This identifier is used in the TLS application layer protocol negotiation extension (ALPN) field and any place that HTTP/2 over TLS is identified. The "h2" string is serialized into an ALPN protocol identifier as the two octet sequence: 0x68, 0x32. The string "h2c" identifies the protocol where HTTP/2 is run over cleartext TCP. This identifier is used in the HTTP/1.1 Upgrade header field and any place that HTTP/2 over TCP is identified. Negotiating "h2" or "h2c" implies the use of the transport, security, framing and message semantics described in this document. RFC Editor's Note: please remove the remainder of this section prior to the publication of a final version of this document. Only implementations of the final, published RFC can identify themselves as "h2" or "h2c". Until such an RFC exists, implementations MUST NOT identify themselves using these strings. Examples and text throughout the rest of this document use "h2" as a matter of editorial convenience only. Implementations of draft versions MUST NOT identify using this string. Implementations of draft versions of the protocol MUST add the string "-" and the corresponding draft number to the identifier. For example, draft-ietf-httpbis-http2-11 over TLS is identified using the string "h2-11". Non-compatible experiments that are based on these draft versions MUST append the string "-" and an experiment name to the identifier. For example, an experimental implementation of packet mood-based encoding based on draft-ietf-httpbis-http2-09 might identify itself as "h2-09-emo". Note that any label MUST conform to the "token" syntax defined in . Experimenters are encouraged to coordinate their experiments on the ietf-http-wg@w3.org mailing list.
A client that makes a request for an "http" URI without prior knowledge about support for HTTP/2 uses the HTTP Upgrade mechanism (). The client makes an HTTP/1.1 request that includes an Upgrade header field identifying HTTP/2 with the "h2c" token. The HTTP/1.1 request MUST include exactly one HTTP2-Settings header field.
For example: ]]>
Requests that contain an entity body MUST be sent in their entirety before the client can send HTTP/2 frames. This means that a large request entity can block the use of the connection until it is completely sent. If concurrency of an initial request with subsequent requests is important, an OPTIONS request can be used to perform the upgrade to HTTP/2, at the cost of an additional round-trip. A server that does not support HTTP/2 can respond to the request as though the Upgrade header field were absent:
HTTP/1.1 200 OK Content-Length: 243 Content-Type: text/html ...
A server MUST ignore a "h2" token in an Upgrade header field. Presence of a token with "h2" implies HTTP/2 over TLS, which is instead negotiated as described in . A server that supports HTTP/2 can accept the upgrade with a 101 (Switching Protocols) response. After the empty line that terminates the 101 response, the server can begin sending HTTP/2 frames. These frames MUST include a response to the request that initiated the Upgrade.
For example: HTTP/1.1 101 Switching Protocols Connection: Upgrade Upgrade: h2c [ HTTP/2 connection ...
The first HTTP/2 frame sent by the server is a SETTINGS frame () as the server connection preface (). Upon receiving the 101 response, the client sends a connection preface, which includes a SETTINGS frame. The HTTP/1.1 request that is sent prior to upgrade is assigned stream identifier 1 and is assigned default priority values. Stream 1 is implicitly half closed from the client toward the server, since the request is completed as an HTTP/1.1 request. After commencing the HTTP/2 connection, stream 1 is used for the response.
A request that upgrades from HTTP/1.1 to HTTP/2 MUST include exactly one HTTP2-Settings header field. The HTTP2-Settings header field is a connection-specific header field that includes parameters that govern the HTTP/2 connection, provided in anticipation of the server accepting the request to upgrade.
A server MUST NOT upgrade the connection to HTTP/2 if this header field is not present, or if more than one is present. A server MUST NOT send this header field. The content of the HTTP2-Settings header field is the payload of a SETTINGS frame (), encoded as a base64url string (that is, the URL- and filename-safe Base64 encoding described in , with any trailing '=' characters omitted). The ABNF production for token68 is defined in . Since the upgrade is only intended to apply to the immediate connection, a client sending HTTP2-Settings MUST also send HTTP2-Settings as a connection option in the Connection header field to prevent it from being forwarded downstream. A server decodes and interprets these values as it would any other SETTINGS frame. Acknowledgement of the SETTINGS parameters is not necessary, since a 101 response serves as implicit acknowledgment. Providing these values in the Upgrade request gives a client an opportunity to provide parameters prior to receiving any frames from the server.
A client that makes a request to an "https" URI uses TLS with the application layer protocol negotiation extension. HTTP/2 over TLS uses the "h2" application token. The "h2c" token MUST NOT be sent by a client or selected by a server. Once TLS negotiation is complete, both the client and the server send a connection preface.
A client can learn that a particular server supports HTTP/2 by other means. For example, describes a mechanism for advertising this capability. A client MAY immediately send HTTP/2 frames to a server that is known to support HTTP/2, after the connection preface; a server can identify such a connection by the presence of the connection preface. This only affects the establishment of HTTP/2 connections over cleartext TCP; implementations that support HTTP/2 over TLS MUST use protocol negotiation in TLS. Without additional information, prior support for HTTP/2 is not a strong signal that a given server will support HTTP/2 for future connections. For example, it is possible for server configurations to change, for configurations to differ between instances in clustered servers, or for network conditions to change.
Upon establishment of a TCP connection and determination that HTTP/2 will be used by both peers, each endpoint MUST send a connection preface as a final confirmation and to establish the initial SETTINGS parameters for the HTTP/2 connection. The client and server each send a different connection preface. The client connection preface starts with a sequence of 24 octets, which in hex notation are:
(the string PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n). This sequence is followed by a SETTINGS frame (). The SETTINGS frame MAY be empty. The client sends the client connection preface immediately upon receipt of a 101 Switching Protocols response (indicating a successful upgrade), or as the first application data octets of a TLS connection. If starting an HTTP/2 connection with prior knowledge of server support for the protocol, the client connection preface is sent upon connection establishment. The client connection preface is selected so that a large proportion of HTTP/1.1 or HTTP/1.0 servers and intermediaries do not attempt to process further frames. Note that this does not address the concerns raised in . The server connection preface consists of a potentially empty SETTINGS frame () that MUST be the first frame the server sends in the HTTP/2 connection. The SETTINGS frames received from a peer as part of the connection preface MUST be acknowledged (see ) after sending the connection preface. To avoid unnecessary latency, clients are permitted to send additional frames to the server immediately after sending the client connection preface, without waiting to receive the server connection preface. It is important to note, however, that the server connection preface SETTINGS frame might include parameters that necessarily alter how a client is expected to communicate with the server. Upon receiving the SETTINGS frame, the client is expected to honor any parameters established. In some configurations, it is possible for the server to transmit SETTINGS before the client sends additional frames, providing an opportunity to avoid this issue. Clients and servers MUST treat an invalid connection preface as a connection error of type PROTOCOL_ERROR. A GOAWAY frame () MAY be omitted in this case, since an invalid preface indicates that the peer is not using HTTP/2.
Once the HTTP/2 connection is established, endpoints can begin exchanging frames.
All frames begin with a fixed 9-octet header followed by a variable-length payload.
The fields of the frame header are defined as: The length of the frame payload expressed as an unsigned 24-bit integer. Values greater than 214 (16,384) MUST NOT be sent unless the receiver has set a larger value for SETTINGS_MAX_FRAME_SIZE. The 9 octets of the frame header are not included in this value. The 8-bit type of the frame. The frame type determines the format and semantics of the frame. Implementations MUST ignore and discard any frame that has a type that is unknown. An 8-bit field reserved for frame-type specific boolean flags. Flags are assigned semantics specific to the indicated frame type. Flags that have no defined semantics for a particular frame type MUST be ignored, and MUST be left unset (0) when sending. A reserved 1-bit field. The semantics of this bit are undefined and the bit MUST remain unset (0) when sending and MUST be ignored when receiving. A 31-bit stream identifier (see ). The value 0 is reserved for frames that are associated with the connection as a whole as opposed to an individual stream. The structure and content of the frame payload is dependent entirely on the frame type.
The size of a frame payload is limited by the maximum size that a receiver advertises in the SETTINGS_MAX_FRAME_SIZE setting. This setting can have any value between 214 (16,384) and 224-1 (16,777,215) octets, inclusive. All implementations MUST be capable of receiving and minimally processing frames up to 214 octets in length, plus the 9 octet frame header. The size of the frame header is not included when describing frame sizes. Certain frame types, such as PING, impose additional limits on the amount of payload data allowed. If a frame size exceeds any defined limit, or is too small to contain mandatory frame data, the endpoint MUST send a FRAME_SIZE_ERROR error. A frame size error in a frame that could alter the state of the entire connection MUST be treated as a connection error; this includes any frame carrying a header block (that is, HEADERS, PUSH_PROMISE, and CONTINUATION), SETTINGS, and any WINDOW_UPDATE frame with a stream identifier of 0. Endpoints are not obligated to use all available space in a frame. Responsiveness can be improved by using frames that are smaller than the permitted maximum size. Sending large frames can result in delays in sending time-sensitive frames (such RST_STREAM, WINDOW_UPDATE, or PRIORITY) which if blocked by the transmission of a large frame, could affect performance.
Just as in HTTP/1, a header field in HTTP/2 is a name with one or more associated values. They are used within HTTP request and response messages as well as server push operations (see ). Header lists are collections of zero or more header fields. When transmitted over a connection, a header list is serialized into a header block using HTTP Header Compression. The serialized header block is then divided into one or more octet sequences, called header block fragments, and transmitted within the payload of HEADERS, PUSH_PROMISE or CONTINUATION frames. The Cookie header field is treated specially by the HTTP mapping (see ). A receiving endpoint reassembles the header block by concatenating its fragments, then decompresses the block to reconstruct the header list. A complete header block consists of either: a single HEADERS or PUSH_PROMISE frame, with the END_HEADERS flag set, or a HEADERS or PUSH_PROMISE frame with the END_HEADERS flag cleared and one or more CONTINUATION frames, where the last CONTINUATION frame has the END_HEADERS flag set. Header compression is stateful. One compression context and one decompression context is used for the entire connection. Each header block is processed as a discrete unit. Header blocks MUST be transmitted as a contiguous sequence of frames, with no interleaved frames of any other type or from any other stream. The last frame in a sequence of HEADERS or CONTINUATION frames MUST have the END_HEADERS flag set. The last frame in a sequence of PUSH_PROMISE or CONTINUATION frames MUST have the END_HEADERS flag set. This allows a header block to be logically equivalent to a single frame. Header block fragments can only be sent as the payload of HEADERS, PUSH_PROMISE or CONTINUATION frames, because these frames carry data that can modify the compression context maintained by a receiver. An endpoint receiving HEADERS, PUSH_PROMISE or CONTINUATION frames MUST reassemble header blocks and perform decompression even if the frames are to be discarded. A receiver MUST terminate the connection with a connection error of type COMPRESSION_ERROR if it does not decompress a header block.
A "stream" is an independent, bi-directional sequence of frames exchanged between the client and server within an HTTP/2 connection. Streams have several important characteristics: A single HTTP/2 connection can contain multiple concurrently open streams, with either endpoint interleaving frames from multiple streams. Streams can be established and used unilaterally or shared by either the client or server. Streams can be closed by either endpoint. The order in which frames are sent on a stream is significant. Recipients process frames in the order they are received. In particular, the order of HEADERS, and DATA frames is semantically significant. Streams are identified by an integer. Stream identifiers are assigned to streams by the endpoint initiating the stream.
The lifecycle of a stream is shown in .
| |<-----------' | | R | closed | R | `-------------------->| |<--------------------' +--------+ H: HEADERS frame (with implied CONTINUATIONs) PP: PUSH_PROMISE frame (with implied CONTINUATIONs) ES: END_STREAM flag R: RST_STREAM frame ]]>
Note that this diagram shows stream state transitions and the frames and flags that affect those transitions only. In this regard, CONTINUATION frames do not result in state transitions; they are effectively part of the HEADERS or PUSH_PROMISE that they follow. For this purpose, the END_STREAM flag is processed as a separate event to the frame that bears it; a HEADERS frame with the END_STREAM flag set can cause two state transitions. Both endpoints have a subjective view of the state of a stream that could be different when frames are in transit. Endpoints do not coordinate the creation of streams; they are created unilaterally by either endpoint. The negative consequences of a mismatch in states are limited to the "closed" state after sending RST_STREAM, where frames might be received for some time after closing. Streams have the following states: All streams start in the "idle" state. In this state, no frames have been exchanged. The following transitions are valid from this state: Sending or receiving a HEADERS frame causes the stream to become "open". The stream identifier is selected as described in . The same HEADERS frame can also cause a stream to immediately become "half closed". Sending a PUSH_PROMISE frame marks the associated stream for later use. The stream state for the reserved stream transitions to "reserved (local)". Receiving a PUSH_PROMISE frame marks the associated stream as reserved by the remote peer. The state of the stream becomes "reserved (remote)". Receiving any frames other than HEADERS or PUSH_PROMISE on a stream in this state MUST be treated as a connection error of type PROTOCOL_ERROR. A stream in the "reserved (local)" state is one that has been promised by sending a PUSH_PROMISE frame. A PUSH_PROMISE frame reserves an idle stream by associating the stream with an open stream that was initiated by the remote peer (see ). In this state, only the following transitions are possible: The endpoint can send a HEADERS frame. This causes the stream to open in a "half closed (remote)" state. Either endpoint can send a RST_STREAM frame to cause the stream to become "closed". This releases the stream reservation. An endpoint MUST NOT send any type of frame other than HEADERS or RST_STREAM in this state. A PRIORITY frame MAY be received in this state. Receiving any type of frame other than RST_STREAM or PRIORITY on a stream in this state MUST be treated as a connection error of type PROTOCOL_ERROR. A stream in the "reserved (remote)" state has been reserved by a remote peer. In this state, only the following transitions are possible: Receiving a HEADERS frame causes the stream to transition to "half closed (local)". Either endpoint can send a RST_STREAM frame to cause the stream to become "closed". This releases the stream reservation. An endpoint MAY send a PRIORITY frame in this state to reprioritize the reserved stream. An endpoint MUST NOT send any type of frame other than RST_STREAM, WINDOW_UPDATE, or PRIORITY in this state. Receiving any type of frame other than HEADERS or RST_STREAM on a stream in this state MUST be treated as a connection error of type PROTOCOL_ERROR. A stream in the "open" state may be used by both peers to send frames of any type. In this state, sending peers observe advertised stream level flow control limits. From this state either endpoint can send a frame with an END_STREAM flag set, which causes the stream to transition into one of the "half closed" states: an endpoint sending an END_STREAM flag causes the stream state to become "half closed (local)"; an endpoint receiving an END_STREAM flag causes the stream state to become "half closed (remote)". Either endpoint can send a RST_STREAM frame from this state, causing it to transition immediately to "closed". A stream that is in the "half closed (local)" state cannot be used for sending frames. Only WINDOW_UPDATE, PRIORITY and RST_STREAM frames can be sent in this state. A stream transitions from this state to "closed" when a frame that contains an END_STREAM flag is received, or when either peer sends a RST_STREAM frame. A receiver can ignore WINDOW_UPDATE frames in this state, which might arrive for a short period after a frame bearing the END_STREAM flag is sent. PRIORITY frames received in this state are used to reprioritize streams that depend on the current stream. A stream that is "half closed (remote)" is no longer being used by the peer to send frames. In this state, an endpoint is no longer obligated to maintain a receiver flow control window if it performs flow control. If an endpoint receives additional frames for a stream that is in this state, other than WINDOW_UPDATE, PRIORITY or RST_STREAM, it MUST respond with a stream error of type STREAM_CLOSED. A stream that is "half closed (remote)" can be used by the endpoint to send frames of any type. In this state, the endpoint continues to observe advertised stream level flow control limits. A stream can transition from this state to "closed" by sending a frame that contains an END_STREAM flag, or when either peer sends a RST_STREAM frame. The "closed" state is the terminal state. An endpoint MUST NOT send frames other than PRIORITY on a closed stream. An endpoint that receives any frame other than PRIORITY after receiving a RST_STREAM MUST treat that as a stream error of type STREAM_CLOSED. Similarly, an endpoint that receives any frames after receiving a frame with the END_STREAM flag set MUST treat that as a connection error of type STREAM_CLOSED, unless the frame is permitted as described below. WINDOW_UPDATE or RST_STREAM frames can be received in this state for a short period after a DATA or HEADERS frame containing an END_STREAM flag is sent. Until the remote peer receives and processes RST_STREAM or the frame bearing the END_STREAM flag, it might send frames of these types. Endpoints MUST ignore WINDOW_UPDATE or RST_STREAM frames received in this state, though endpoints MAY choose to treat frames that arrive a significant time after sending END_STREAM as a connection error of type PROTOCOL_ERROR. PRIORITY frames can be sent on closed streams to prioritize streams that are dependent on the closed stream. Endpoints SHOULD process PRIORITY frame, though they can be ignored if the stream has been removed from the dependency tree (see ). If this state is reached as a result of sending a RST_STREAM frame, the peer that receives the RST_STREAM might have already sent - or enqueued for sending - frames on the stream that cannot be withdrawn. An endpoint MUST ignore frames that it receives on closed streams after it has sent a RST_STREAM frame. An endpoint MAY choose to limit the period over which it ignores frames and treat frames that arrive after this time as being in error. Flow controlled frames (i.e., DATA) received after sending RST_STREAM are counted toward the connection flow control window. Even though these frames might be ignored, because they are sent before the sender receives the RST_STREAM, the sender will consider the frames to count against the flow control window. An endpoint might receive a PUSH_PROMISE frame after it sends RST_STREAM. PUSH_PROMISE causes a stream to become "reserved" even if the associated stream has been reset. Therefore, a RST_STREAM is needed to close an unwanted promised stream. In the absence of more specific guidance elsewhere in this document, implementations SHOULD treat the receipt of a frame that is not expressly permitted in the description of a state as a connection error of type PROTOCOL_ERROR. Frame of unknown types are ignored. An example of the state transitions for an HTTP request/response exchange can be found in . An example of the state transitions for server push can be found in and .
Streams are identified with an unsigned 31-bit integer. Streams initiated by a client MUST use odd-numbered stream identifiers; those initiated by the server MUST use even-numbered stream identifiers. A stream identifier of zero (0x0) is used for connection control messages; the stream identifier zero cannot be used to establish a new stream. HTTP/1.1 requests that are upgraded to HTTP/2 (see ) are responded to with a stream identifier of one (0x1). After the upgrade completes, stream 0x1 is "half closed (local)" to the client. Therefore, stream 0x1 cannot be selected as a new stream identifier by a client that upgrades from HTTP/1.1. The identifier of a newly established stream MUST be numerically greater than all streams that the initiating endpoint has opened or reserved. This governs streams that are opened using a HEADERS frame and streams that are reserved using PUSH_PROMISE. An endpoint that receives an unexpected stream identifier MUST respond with a connection error of type PROTOCOL_ERROR. The first use of a new stream identifier implicitly closes all streams in the "idle" state that might have been initiated by that peer with a lower-valued stream identifier. For example, if a client sends a HEADERS frame on stream 7 without ever sending a frame on stream 5, then stream 5 transitions to the "closed" state when the first frame for stream 7 is sent or received. Stream identifiers cannot be reused. Long-lived connections can result in an endpoint exhausting the available range of stream identifiers. A client that is unable to establish a new stream identifier can establish a new connection for new streams. A server that is unable to establish a new stream identifier can send a GOAWAY frame so that the client is forced to open a new connection for new streams.
A peer can limit the number of concurrently active streams using the SETTINGS_MAX_CONCURRENT_STREAMS parameter (see ) within a SETTINGS frame. The maximum concurrent streams setting is specific to each endpoint and applies only to the peer that receives the setting. That is, clients specify the maximum number of concurrent streams the server can initiate, and servers specify the maximum number of concurrent streams the client can initiate. Streams that are in the "open" state, or either of the "half closed" states count toward the maximum number of streams that an endpoint is permitted to open. Streams in any of these three states count toward the limit advertised in the SETTINGS_MAX_CONCURRENT_STREAMS setting. Streams in either of the "reserved" states do not count toward the stream limit. Endpoints MUST NOT exceed the limit set by their peer. An endpoint that receives a HEADERS frame that causes their advertised concurrent stream limit to be exceeded MUST treat this as a stream error. An endpoint that wishes to reduce the value of SETTINGS_MAX_CONCURRENT_STREAMS to a value that is below the current number of open streams can either close streams that exceed the new value or allow streams to complete.
Using streams for multiplexing introduces contention over use of the TCP connection, resulting in blocked streams. A flow control scheme ensures that streams on the same connection do not destructively interfere with each other. Flow control is used for both individual streams and for the connection as a whole. HTTP/2 provides for flow control through use of the WINDOW_UPDATE frame.
HTTP/2 stream flow control aims to allow a variety of flow control algorithms to be used without requiring protocol changes. Flow control in HTTP/2 has the following characteristics: Flow control is specific to a connection; i.e., it is "hop-by-hop", not "end-to-end". Flow control is based on window update frames. Receivers advertise how many octets they are prepared to receive on a stream and for the entire connection. This is a credit-based scheme. Flow control is directional with overall control provided by the receiver. A receiver MAY choose to set any window size that it desires for each stream and for the entire connection. A sender MUST respect flow control limits imposed by a receiver. Clients, servers and intermediaries all independently advertise their flow control window as a receiver and abide by the flow control limits set by their peer when sending. The initial value for the flow control window is 65,535 octets for both new streams and the overall connection. The frame type determines whether flow control applies to a frame. Of the frames specified in this document, only DATA frames are subject to flow control; all other frame types do not consume space in the advertised flow control window. This ensures that important control frames are not blocked by flow control. Flow control cannot be disabled. HTTP/2 defines only the format and semantics of the WINDOW_UPDATE frame (). This document does not stipulate how a receiver decides when to send this frame or the value that it sends, nor does it specify how a sender chooses to send packets. Implementations are able to select any algorithm that suits their needs. Implementations are also responsible for managing how requests and responses are sent based on priority; choosing how to avoid head of line blocking for requests; and managing the creation of new streams. Algorithm choices for these could interact with any flow control algorithm.
Flow control is defined to protect endpoints that are operating under resource constraints. For example, a proxy needs to share memory between many connections, and also might have a slow upstream connection and a fast downstream one. Flow control addresses cases where the receiver is unable process data on one stream, yet wants to continue to process other streams in the same connection. Deployments that do not require this capability can advertise a flow control window of the maximum size, incrementing the available space when new data is received. This effectively disables flow control for that receiver. Conversely, a sender is always subject to the flow control window advertised by the receiver. Deployments with constrained resources (for example, memory) can employ flow control to limit the amount of memory a peer can consume. Note, however, that this can lead to suboptimal use of available network resources if flow control is enabled without knowledge of the bandwidth-delay product (see ). Even with full awareness of the current bandwidth-delay product, implementation of flow control can be difficult. When using flow control, the receiver MUST read from the TCP receive buffer in a timely fashion. Failure to do so could lead to a deadlock when critical frames, such as WINDOW_UPDATE, are not read and acted upon.
A client can assign a priority for a new stream by including prioritization information in the HEADERS frame that opens the stream. For an existing stream, the PRIORITY frame can be used to change the priority. The purpose of prioritization is to allow an endpoint to express how it would prefer its peer allocate resources when managing concurrent streams. Most importantly, priority can be used to select streams for transmitting frames when there is limited capacity for sending. Streams can be prioritized by marking them as dependent on the completion of other streams (). Each dependency is assigned a relative weight, a number that is used to determine the relative proportion of available resources that are assigned to streams dependent on the same stream. Explicitly setting the priority for a stream is input to a prioritization process. It does not guarantee any particular processing or transmission order for the stream relative to any other stream. An endpoint cannot force a peer to process concurrent streams in a particular order using priority. Expressing priority is therefore only ever a suggestion. Providing prioritization information is optional, so default values are used if no explicit indicator is provided ().
Each stream can be given an explicit dependency on another stream. Including a dependency expresses a preference to allocate resources to the identified stream rather than to the dependent stream. A stream that is not dependent on any other stream is given a stream dependency of 0x0. In other words, the non-existent stream 0 forms the root of the tree. A stream that depends on another stream is a dependent stream. The stream upon which a stream is dependent is a parent stream. A dependency on a stream that is not currently in the tree - such as a stream in the "idle" state - results in that stream being given a default priority. When assigning a dependency on another stream, the stream is added as a new dependency of the parent stream. Dependent streams that share the same parent are not ordered with respect to each other. For example, if streams B and C are dependent on stream A, and if stream D is created with a dependency on stream A, this results in a dependency order of A followed by B, C, and D in any order.
/|\ B C B D C ]]>
An exclusive flag allows for the insertion of a new level of dependencies. The exclusive flag causes the stream to become the sole dependency of its parent stream, causing other dependencies to become dependent on the exclusive stream. In the previous example, if stream D is created with an exclusive dependency on stream A, this results in D becoming the dependency parent of B and C.
D B C / \ B C ]]>
Inside the dependency tree, a dependent stream SHOULD only be allocated resources if all of the streams that it depends on (the chain of parent streams up to 0x0) are either closed, or it is not possible to make progress on them. A stream cannot depend on itself. An endpoint MUST treat this as a stream error of type PROTOCOL_ERROR.
All dependent streams are allocated an integer weight between 1 and 256 (inclusive). Streams with the same parent SHOULD be allocated resources proportionally based on their weight. Thus, if stream B depends on stream A with weight 4, and C depends on stream A with weight 12, and if no progress can be made on A, stream B ideally receives one third of the resources allocated to stream C.
Stream priorities are changed using the PRIORITY frame. Setting a dependency causes a stream to become dependent on the identified parent stream. Dependent streams move with their parent stream if the parent is reprioritized. Setting a dependency with the exclusive flag for a reprioritized stream moves all the dependencies of the new parent stream to become dependent on the reprioritized stream. If a stream is made dependent on one of its own dependencies, the formerly dependent stream is first moved to be dependent on the reprioritized stream's previous parent. The moved dependency retains its weight.
For example, consider an original dependency tree where B and C depend on A, D and E depend on C, and F depends on D. If A is made dependent on D, then D takes the place of A. All other dependency relationships stay the same, except for F, which becomes dependent on A if the reprioritization is exclusive. F B C ==> F A OR A / \ | / \ /|\ D E E B C B C F | | | F E E (intermediate) (non-exclusive) (exclusive) ]]>
When a stream is removed from the dependency tree, its dependencies can be moved to become dependent on the parent of the closed stream. The weights of new dependencies are recalculated by distributing the weight of the dependency of the closed stream proportionally based on the weights of its dependencies. Streams that are removed from the dependency tree cause some prioritization information to be lost. Resources are shared between streams with the same parent stream, which means that if a stream in that set closes or becomes blocked, any spare capacity allocated to a stream is distributed to the immediate neighbors of the stream. However, if the common dependency is removed from the tree, those streams share resources with streams at the next highest level. For example, assume streams A and B share a parent, and streams C and D both depend on stream A. Prior to the removal of stream A, if streams A and D are unable to proceed, then stream C receives all the resources dedicated to stream A. If stream A is removed from the tree, the weight of stream A is divided between streams C and D. If stream D is still unable to proceed, this results in stream C receiving a reduced proportion of resources. For equal starting weights, C receives one third, rather than one half, of available resources. It is possible for a stream to become closed while prioritization information that creates a dependency on that stream is in transit. If a stream identified in a dependency has no associated priority information, then the dependent stream is instead assigned a default priority. This potentially creates suboptimal prioritization, since the stream could be given a priority that is different to what is intended. To avoid these problems, an endpoint SHOULD retain stream prioritization state for a period after streams become closed. The longer state is retained, the lower the chance that streams are assigned incorrect or default priority values. This could create a large state burden for an endpoint, so this state MAY be limited. An endpoint MAY apply a fixed upper limit on the number of closed streams for which prioritization state is tracked to limit state exposure. The amount of additional state an endpoint maintains could be dependent on load; under high load, prioritization state can be discarded to limit resource commitments. In extreme cases, an endpoint could even discard prioritization state for active or reserved streams. If a fixed limit is applied, endpoints SHOULD maintain state for at least as many streams as allowed by their setting for SETTINGS_MAX_CONCURRENT_STREAMS. An endpoint receiving a PRIORITY frame that changes the priority of a closed stream SHOULD alter the dependencies of the streams that depend on it, if it has retained enough state to do so.
Providing priority information is optional. Streams are assigned a non-exclusive dependency on stream 0x0 by default. Pushed streams initially depend on their associated stream. In both cases, streams are assigned a default weight of 16.
HTTP/2 framing permits two classes of error: An error condition that renders the entire connection unusable is a connection error. An error in an individual stream is a stream error. A list of error codes is included in .
A connection error is any error which prevents further processing of the framing layer, or which corrupts any connection state. An endpoint that encounters a connection error SHOULD first send a GOAWAY frame () with the stream identifier of the last stream that it successfully received from its peer. The GOAWAY frame includes an error code that indicates why the connection is terminating. After sending the GOAWAY frame, the endpoint MUST close the TCP connection. It is possible that the GOAWAY will not be reliably received by the receiving endpoint (see ). In the event of a connection error, GOAWAY only provides a best effort attempt to communicate with the peer about why the connection is being terminated. An endpoint can end a connection at any time. In particular, an endpoint MAY choose to treat a stream error as a connection error. Endpoints SHOULD send a GOAWAY frame when ending a connection, providing that circumstances permit it.
A stream error is an error related to a specific stream that does not affect processing of other streams. An endpoint that detects a stream error sends a RST_STREAM frame () that contains the stream identifier of the stream where the error occurred. The RST_STREAM frame includes an error code that indicates the type of error. A RST_STREAM is the last frame that an endpoint can send on a stream. The peer that sends the RST_STREAM frame MUST be prepared to receive any frames that were sent or enqueued for sending by the remote peer. These frames can be ignored, except where they modify connection state (such as the state maintained for header compression, or flow control). Normally, an endpoint SHOULD NOT send more than one RST_STREAM frame for any stream. However, an endpoint MAY send additional RST_STREAM frames if it receives frames on a closed stream after more than a round-trip time. This behavior is permitted to deal with misbehaving implementations. An endpoint MUST NOT send a RST_STREAM in response to an RST_STREAM frame, to avoid looping.
If the TCP connection is closed or reset while streams remain in open or half closed states, then the endpoint MUST assume that those streams were abnormally interrupted and could be incomplete.
HTTP/2 permits extension of the protocol. Protocol extensions can be used to provide additional services or alter any aspect of the protocol, within the limitations described in this section. Extensions are effective only within the scope of a single HTTP/2 connection. Extensions are permitted to use new frame types, new settings, or new error codes. Registries are established for managing these extension points: frame types, settings and error codes. Implementations MUST ignore unknown or unsupported values in all extensible protocol elements. Implementations MUST discard frames that have unknown or unsupported types. This means that any of these extension points can be safely used by extensions without prior arrangement or negotiation. However, extension frames that appear in the middle of a header block are not permitted; these MUST be treated as a connection error of type PROTOCOL_ERROR. However, extensions that could change the semantics of existing protocol components MUST be negotiated before being used. For example, an extension that changes the layout of the HEADERS frame cannot be used until the peer has given a positive signal that this is acceptable. In this case, it could also be necessary to coordinate when the revised layout comes into effect. Note that treating any frame other than DATA frames as flow controlled is such a change in semantics, and can only be done through negotiation. This document doesn't mandate a specific method for negotiating the use of an extension, but notes that a setting could be used for that purpose. If both peers set a value that indicates willingness to use the extension, then the extension can be used. If a setting is used for extension negotiation, the initial value MUST be defined so that the extension is initially disabled.
This specification defines a number of frame types, each identified by a unique 8-bit type code. Each frame type serves a distinct purpose either in the establishment and management of the connection as a whole, or of individual streams. The transmission of specific frame types can alter the state of a connection. If endpoints fail to maintain a synchronized view of the connection state, successful communication within the connection will no longer be possible. Therefore, it is important that endpoints have a shared comprehension of how the state is affected by the use any given frame.
DATA frames (type=0x0) convey arbitrary, variable-length sequences of octets associated with a stream. One or more DATA frames are used, for instance, to carry HTTP request or response payloads. DATA frames MAY also contain arbitrary padding. Padding can be added to DATA frames to obscure the size of messages.
The DATA frame contains the following fields: An 8-bit field containing the length of the frame padding in units of octets. This field is optional and is only present if the PADDED flag is set. Application data. The amount of data is the remainder of the frame payload after subtracting the length of the other fields that are present. Padding octets that contain no application semantic value. Padding octets MUST be set to zero when sending and ignored when receiving. The DATA frame defines the following flags: Bit 1 being set indicates that this frame is the last that the endpoint will send for the identified stream. Setting this flag causes the stream to enter one of the "half closed" states or the "closed" state. Bit 4 being set indicates that the Pad Length field and any padding that it describes is present. DATA frames MUST be associated with a stream. If a DATA frame is received whose stream identifier field is 0x0, the recipient MUST respond with a connection error of type PROTOCOL_ERROR. DATA frames are subject to flow control and can only be sent when a stream is in the "open" or "half closed (remote)" states. The entire DATA frame payload is included in flow control, including Pad Length and Padding fields if present. If a DATA frame is received whose stream is not in "open" or "half closed (local)" state, the recipient MUST respond with a stream error of type STREAM_CLOSED. The total number of padding octets is determined by the value of the Pad Length field. If the length of the padding is greater than the length of the frame payload, the recipient MUST treat this as a connection error of type PROTOCOL_ERROR. A frame can be increased in size by one octet by including a Pad Length field with a value of zero. Padding is a security feature; see .
The HEADERS frame (type=0x1) is used to open a stream, and additionally carries a header block fragment. HEADERS frames can be sent on a stream in the "open" or "half closed (remote)" states.
The HEADERS frame payload has the following fields: An 8-bit field containing the length of the frame padding in units of octets. This field is only present if the PADDED flag is set. A single bit flag indicates that the stream dependency is exclusive, see . This field is only present if the PRIORITY flag is set. A 31-bit stream identifier for the stream that this stream depends on, see . This field is only present if the PRIORITY flag is set. An 8-bit weight for the stream, see . Add one to the value to obtain a weight between 1 and 256. This field is only present if the PRIORITY flag is set. A header block fragment. Padding octets that contain no application semantic value. Padding octets MUST be set to zero when sending and ignored when receiving. The HEADERS frame defines the following flags: Bit 1 being set indicates that the header block is the last that the endpoint will send for the identified stream. Setting this flag causes the stream to enter one of "half closed" states. A HEADERS frame carries the END_STREAM flag that signals the end of a stream. However, a HEADERS frame with the END_STREAM flag set can be followed by CONTINUATION frames on the same stream. Logically, the CONTINUATION frames are part of the HEADERS frame. Bit 3 being set indicates that this frame contains an entire header block and is not followed by any CONTINUATION frames. A HEADERS frame without the END_HEADERS flag set MUST be followed by a CONTINUATION frame for the same stream. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error of type PROTOCOL_ERROR. Bit 4 being set indicates that the Pad Length field and any padding that it describes is present. Bit 6 being set indicates that the Exclusive Flag (E), Stream Dependency, and Weight fields are present; see . The payload of a HEADERS frame contains a header block fragment. A header block that does not fit within a HEADERS frame is continued in a CONTINUATION frame. HEADERS frames MUST be associated with a stream. If a HEADERS frame is received whose stream identifier field is 0x0, the recipient MUST respond with a connection error of type PROTOCOL_ERROR. The HEADERS frame changes the connection state as described in . The HEADERS frame includes optional padding. Padding fields and flags are identical to those defined for DATA frames. Prioritization information in a HEADERS frame is logically equivalent to a separate PRIORITY frame, but inclusion in HEADERS avoids the potential for churn in stream prioritization when new streams are created. Priorization fields in HEADERS frames subsequent to the first on a stream reprioritize the stream.
The PRIORITY frame (type=0x2) specifies the sender-advised priority of a stream. It can be sent at any time for an existing stream, including closed streams. This enables reprioritization of existing streams.
The payload of a PRIORITY frame contains the following fields: A single bit flag indicates that the stream dependency is exclusive, see . A 31-bit stream identifier for the stream that this stream depends on, see . An 8-bit weight for the identified stream dependency, see . Add one to the value to obtain a weight between 1 and 256. The PRIORITY frame does not define any flags. The PRIORITY frame is associated with an existing stream. If a PRIORITY frame is received with a stream identifier of 0x0, the recipient MUST respond with a connection error of type PROTOCOL_ERROR. The PRIORITY frame can be sent on a stream in any of the "reserved (remote)", "open", "half closed (local)", "half closed (remote)", or "closed" states, though it cannot be sent between consecutive frames that comprise a single header block. Note that this frame could arrive after processing or frame sending has completed, which would cause it to have no effect on the current stream. For a stream that is in the "half closed (remote)" or "closed" - state, this frame can only affect processing of the current stream and not frame transmission. The PRIORITY frame is the only frame that can be sent for a stream in the "closed" state. This allows for the reprioritization of a group of dependent streams by altering the priority of a parent stream, which might be closed. However, a PRIORITY frame sent on a closed stream risks being ignored due to the peer having discarded priority state information for that stream.
The RST_STREAM frame (type=0x3) allows for abnormal termination of a stream. When sent by the initiator of a stream, it indicates that they wish to cancel the stream or that an error condition has occurred. When sent by the receiver of a stream, it indicates that either the receiver is rejecting the stream, requesting that the stream be cancelled, or that an error condition has occurred.
The RST_STREAM frame contains a single unsigned, 32-bit integer identifying the error code. The error code indicates why the stream is being terminated. The RST_STREAM frame does not define any flags. The RST_STREAM frame fully terminates the referenced stream and causes it to enter the closed state. After receiving a RST_STREAM on a stream, the receiver MUST NOT send additional frames for that stream, with the exception of PRIORITY. However, after sending the RST_STREAM, the sending endpoint MUST be prepared to receive and process additional frames sent on the stream that might have been sent by the peer prior to the arrival of the RST_STREAM. RST_STREAM frames MUST be associated with a stream. If a RST_STREAM frame is received with a stream identifier of 0x0, the recipient MUST treat this as a connection error of type PROTOCOL_ERROR. RST_STREAM frames MUST NOT be sent for a stream in the "idle" state. If a RST_STREAM frame identifying an idle stream is received, the recipient MUST treat this as a connection error of type PROTOCOL_ERROR.
The SETTINGS frame (type=0x4) conveys configuration parameters that affect how endpoints communicate, such as preferences and constraints on peer behavior. The SETTINGS frame is also used to acknowledge the receipt of those parameters. Individually, a SETTINGS parameter can also be referred to as a "setting". SETTINGS parameters are not negotiated; they describe characteristics of the sending peer, which are used by the receiving peer. Different values for the same parameter can be advertised by each peer. For example, a client might set a high initial flow control window, whereas a server might set a lower value to conserve resources. A SETTINGS frame MUST be sent by both endpoints at the start of a connection, and MAY be sent at any other time by either endpoint over the lifetime of the connection. Implementations MUST support all of the parameters defined by this specification. Each parameter in a SETTINGS frame replaces any existing value for that parameter. Parameters are processed in the order in which they appear, and a receiver of a SETTINGS frame does not need to maintain any state other than the current value of its parameters. Therefore, the value of a SETTINGS parameter is the last value that is seen by a receiver. SETTINGS parameters are acknowledged by the receiving peer. To enable this, the SETTINGS frame defines the following flag: Bit 1 being set indicates that this frame acknowledges receipt and application of the peer's SETTINGS frame. When this bit is set, the payload of the SETTINGS frame MUST be empty. Receipt of a SETTINGS frame with the ACK flag set and a length field value other than 0 MUST be treated as a connection error of type FRAME_SIZE_ERROR. For more info, see Settings Synchronization. SETTINGS frames always apply to a connection, never a single stream. The stream identifier for a SETTINGS frame MUST be zero (0x0). If an endpoint receives a SETTINGS frame whose stream identifier field is anything other than 0x0, the endpoint MUST respond with a connection error of type PROTOCOL_ERROR. The SETTINGS frame affects connection state. A badly formed or incomplete SETTINGS frame MUST be treated as a connection error of type PROTOCOL_ERROR.
The payload of a SETTINGS frame consists of zero or more parameters, each consisting of an unsigned 16-bit setting identifier and an unsigned 32-bit value.
The following parameters are defined: Allows the sender to inform the remote endpoint of the maximum size of the header compression table used to decode header blocks, in octets. The encoder can select any size equal to or less than this value by using signaling specific to the header compression format inside a header block. The initial value is 4,096 octets. This setting can be use to disable server push. An endpoint MUST NOT send a PUSH_PROMISE frame if it receives this parameter set to a value of 0. An endpoint that has both set this parameter to 0 and had it acknowledged MUST treat the receipt of a PUSH_PROMISE frame as a connection error of type PROTOCOL_ERROR. The initial value is 1, which indicates that server push is permitted. Any value other than 0 or 1 MUST be treated as a connection error of type PROTOCOL_ERROR. Indicates the maximum number of concurrent streams that the sender will allow. This limit is directional: it applies to the number of streams that the sender permits the receiver to create. Initially there is no limit to this value. It is recommended that this value be no smaller than 100, so as to not unnecessarily limit parallelism. A value of 0 for SETTINGS_MAX_CONCURRENT_STREAMS SHOULD NOT be treated as special by endpoints. A zero value does prevent the creation of new streams, however this can also happen for any limit that is exhausted with active streams. Servers SHOULD only set a zero value for short durations; if a server does not wish to accept requests, closing the connection could be preferable. Indicates the sender's initial window size (in octets) for stream level flow control. The initial value is 216-1 (65,535) octets. This setting affects the window size of all streams, including existing streams, see . Values above the maximum flow control window size of 231-1 MUST be treated as a connection error of type FLOW_CONTROL_ERROR. Indicates the size of the largest frame payload that the sender is willing to receive, in octets. The initial value is 214 (16,384) octets. The value advertised by an endpoint MUST be between this initial value and the maximum allowed frame size (224-1 or 16,777,215 octets), inclusive. Values outside this range MUST be treated as a connection error of type PROTOCOL_ERROR. This advisory setting informs a peer of the maximum size of header list that the sender is prepared to accept, in octets. The value is based on the uncompressed size of header fields, including the length of the name and value in octets plus an overhead of 32 octets for each header field. For any given request, a lower limit than what is advertised MAY be enforced. The initial value of this setting is unlimited. An endpoint that receives a SETTINGS frame with any unknown or unsupported identifier MUST ignore that setting.
Most values in SETTINGS benefit from or require an understanding of when the peer has received and applied the changed parameter values. In order to provide such synchronization timepoints, the recipient of a SETTINGS frame in which the ACK flag is not set MUST apply the updated parameters as soon as possible upon receipt. The values in the SETTINGS frame MUST be processed in the order they appear, with no other frame processing between values. Unsupported parameters MUST be ignored. Once all values have been processed, the recipient MUST immediately emit a SETTINGS frame with the ACK flag set. Upon receiving a SETTINGS frame with the ACK flag set, the sender of the altered parameters can rely on the setting having been applied. If the sender of a SETTINGS frame does not receive an acknowledgement within a reasonable amount of time, it MAY issue a connection error of type SETTINGS_TIMEOUT.
The PUSH_PROMISE frame (type=0x5) is used to notify the peer endpoint in advance of streams the sender intends to initiate. The PUSH_PROMISE frame includes the unsigned 31-bit identifier of the stream the endpoint plans to create along with a set of headers that provide additional context for the stream. contains a thorough description of the use of PUSH_PROMISE frames.
The PUSH_PROMISE frame payload has the following fields: An 8-bit field containing the length of the frame padding in units of octets. This field is only present if the PADDED flag is set. A single reserved bit. An unsigned 31-bit integer that identifies the stream that is reserved by the PUSH_PROMISE. The promised stream identifier MUST be a valid choice for the next stream sent by the sender (see new stream identifier). A header block fragment containing request header fields. Padding octets. The PUSH_PROMISE frame defines the following flags: Bit 3 being set indicates that this frame contains an entire header block and is not followed by any CONTINUATION frames. A PUSH_PROMISE frame without the END_HEADERS flag set MUST be followed by a CONTINUATION frame for the same stream. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error of type PROTOCOL_ERROR. Bit 4 being set indicates that the Pad Length field and any padding that it describes is present. PUSH_PROMISE frames MUST be associated with an existing, peer-initiated stream. The stream identifier of a PUSH_PROMISE frame indicates the stream it is associated with. If the stream identifier field specifies the value 0x0, a recipient MUST respond with a connection error of type PROTOCOL_ERROR. Promised streams are not required to be used in the order they are promised. The PUSH_PROMISE only reserves stream identifiers for later use. PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH setting of the peer endpoint is set to 0. An endpoint that has set this setting and has received acknowledgement MUST treat the receipt of a PUSH_PROMISE frame as a connection error of type PROTOCOL_ERROR. Recipients of PUSH_PROMISE frames can choose to reject promised streams by returning a RST_STREAM referencing the promised stream identifier back to the sender of the PUSH_PROMISE. A PUSH_PROMISE frame modifies the connection state in two ways. The inclusion of a header block potentially modifies the state maintained for header compression. PUSH_PROMISE also reserves a stream for later use, causing the promised stream to enter the "reserved" state. A sender MUST NOT send a PUSH_PROMISE on a stream unless that stream is either "open" or "half closed (remote)"; the sender MUST ensure that the promised stream is a valid choice for a new stream identifier (that is, the promised stream MUST be in the "idle" state). Since PUSH_PROMISE reserves a stream, ignoring a PUSH_PROMISE frame causes the stream state to become indeterminate. A receiver MUST treat the receipt of a PUSH_PROMISE on a stream that is neither "open" nor "half closed (local)" as a connection error of type PROTOCOL_ERROR. However, an endpoint that has sent RST_STREAM on the associated stream MUST handle PUSH_PROMISE frames that might have been created before the RST_STREAM frame is received and processed. A receiver MUST treat the receipt of a PUSH_PROMISE that promises an illegal stream identifier (that is, an identifier for a stream that is not currently in the "idle" state) as a connection error of type PROTOCOL_ERROR. The PUSH_PROMISE frame includes optional padding. Padding fields and flags are identical to those defined for DATA frames.
The PING frame (type=0x6) is a mechanism for measuring a minimal round trip time from the sender, as well as determining whether an idle connection is still functional. PING frames can be sent from any endpoint.
In addition to the frame header, PING frames MUST contain 8 octets of data in the payload. A sender can include any value it chooses and use those bytes in any fashion. Receivers of a PING frame that does not include an ACK flag MUST send a PING frame with the ACK flag set in response, with an identical payload. PING responses SHOULD be given higher priority than any other frame. The PING frame defines the following flags: Bit 1 being set indicates that this PING frame is a PING response. An endpoint MUST set this flag in PING responses. An endpoint MUST NOT respond to PING frames containing this flag. PING frames are not associated with any individual stream. If a PING frame is received with a stream identifier field value other than 0x0, the recipient MUST respond with a connection error of type PROTOCOL_ERROR. Receipt of a PING frame with a length field value other than 8 MUST be treated as a connection error of type FRAME_SIZE_ERROR.
The GOAWAY frame (type=0x7) informs the remote peer to stop creating streams on this connection. GOAWAY can be sent by either the client or the server. Once sent, the sender will ignore frames sent on any new streams with identifiers higher than the included last stream identifier. Receivers of a GOAWAY frame MUST NOT open additional streams on the connection, although a new connection can be established for new streams. The purpose of this frame is to allow an endpoint to gracefully stop accepting new streams, while still finishing processing of previously established streams. This enables administrative actions, like server maintainance. There is an inherent race condition between an endpoint starting new streams and the remote sending a GOAWAY frame. To deal with this case, the GOAWAY contains the stream identifier of the last peer-initiated stream which was or might be processed on the sending endpoint in this connection. For instance, if the server sends a GOAWAY frame, the identified stream is the highest numbered stream initiated by the client. If the receiver of the GOAWAY has sent data on streams with a higher stream identifier than what is indicated in the GOAWAY frame, those streams are not or will not be processed. The receiver of the GOAWAY frame can treat the streams as though they had never been created at all, thereby allowing those streams to be retried later on a new connection. Endpoints SHOULD always send a GOAWAY frame before closing a connection so that the remote can know whether a stream has been partially processed or not. For example, if an HTTP client sends a POST at the same time that a server closes a connection, the client cannot know if the server started to process that POST request if the server does not send a GOAWAY frame to indicate what streams it might have acted on. An endpoint might choose to close a connection without sending GOAWAY for misbehaving peers.
The GOAWAY frame does not define any flags. The GOAWAY frame applies to the connection, not a specific stream. An endpoint MUST treat a GOAWAY frame with a stream identifier other than 0x0 as a connection error of type PROTOCOL_ERROR. The last stream identifier in the GOAWAY frame contains the highest numbered stream identifier for which the sender of the GOAWAY frame might have taken some action on, or might yet take action on. All streams up to and including the identified stream might have been processed in some way. The last stream identifier can be set to 0 if no streams were processed. In this context, "processed" means that some data from the stream was passed to some higher layer of software that might have taken some action as a result. If a connection terminates without a GOAWAY frame, the last stream identifier is effectively the highest possible stream identifier. On streams with lower or equal numbered identifiers that were not closed completely prior to the connection being closed, re-attempting requests, transactions, or any protocol activity is not possible, with the exception of idempotent actions like HTTP GET, PUT, or DELETE. Any protocol activity that uses higher numbered streams can be safely retried using a new connection. Activity on streams numbered lower or equal to the last stream identifier might still complete successfully. The sender of a GOAWAY frame might gracefully shut down a connection by sending a GOAWAY frame, maintaining the connection in an open state until all in-progress streams complete. An endpoint MAY send multiple GOAWAY frames if circumstances change. For instance, an endpoint that sends GOAWAY with NO_ERROR during graceful shutdown could subsequently encounter an condition that requires immediate termination of the connection. The last stream identifier from the last GOAWAY frame received indicates which streams could have been acted upon. Endpoints MUST NOT increase the value they send in the last stream identifier, since the peers might already have retried unprocessed requests on another connection. A client that is unable to retry requests loses all requests that are in flight when the server closes the connection. This is especially true for intermediaries that might not be serving clients using HTTP/2. A server that is attempting to gracefully shut down a connection SHOULD send an initial GOAWAY frame with the last stream identifier set to 231-1 and a NO_ERROR code. This signals to the client that a shutdown is imminent and that no further requests can be initiated. After waiting at least one round trip time, the server can send another GOAWAY frame with an updated last stream identifier. This ensures that a connection can be cleanly shut down without losing requests. After sending a GOAWAY frame, the sender can discard frames for streams with identifiers higher than the identified last stream. However, any frames that alter connection state cannot be completely ignored. For instance, HEADERS, PUSH_PROMISE and CONTINUATION frames MUST be minimally processed to ensure the state maintained for header compression is consistent (see ); similarly DATA frames MUST be counted toward the connection flow control window. Failure to process these frames can cause flow control or header compression state to become unsynchronized. The GOAWAY frame also contains a 32-bit error code that contains the reason for closing the connection. Endpoints MAY append opaque data to the payload of any GOAWAY frame. Additional debug data is intended for diagnostic purposes only and carries no semantic value. Debug information could contain security- or privacy-sensitive data. Logged or otherwise persistently stored debug data MUST have adequate safeguards to prevent unauthorized access.
The WINDOW_UPDATE frame (type=0x8) is used to implement flow control; see for an overview. Flow control operates at two levels: on each individual stream and on the entire connection. Both types of flow control are hop-by-hop; that is, only between the two endpoints. Intermediaries do not forward WINDOW_UPDATE frames between dependent connections. However, throttling of data transfer by any receiver can indirectly cause the propagation of flow control information toward the original sender. Flow control only applies to frames that are identified as being subject to flow control. Of the frame types defined in this document, this includes only DATA frames. Frames that are exempt from flow control MUST be accepted and processed, unless the receiver is unable to assign resources to handling the frame. A receiver MAY respond with a stream error or connection error of type FLOW_CONTROL_ERROR if it is unable to accept a frame.
The payload of a WINDOW_UPDATE frame is one reserved bit, plus an unsigned 31-bit integer indicating the number of octets that the sender can transmit in addition to the existing flow control window. The legal range for the increment to the flow control window is 1 to 231-1 (0x7fffffff) octets. The WINDOW_UPDATE frame does not define any flags. The WINDOW_UPDATE frame can be specific to a stream or to the entire connection. In the former case, the frame's stream identifier indicates the affected stream; in the latter, the value "0" indicates that the entire connection is the subject of the frame. A receiver MUST treat the receipt of a WINDOW_UPDATE frame with an flow control window increment of 0 as a stream error of type PROTOCOL_ERROR; errors on the connection flow control window MUST be treated as a connection error. WINDOW_UPDATE can be sent by a peer that has sent a frame bearing the END_STREAM flag. This means that a receiver could receive a WINDOW_UPDATE frame on a "half closed (remote)" or "closed" stream. A receiver MUST NOT treat this as an error, see . A receiver that receives a flow controlled frame MUST always account for its contribution against the connection flow control window, unless the receiver treats this as a connection error. This is necessary even if the frame is in error. Since the sender counts the frame toward the flow control window, if the receiver does not, the flow control window at sender and receiver can become different.
Flow control in HTTP/2 is implemented using a window kept by each sender on every stream. The flow control window is a simple integer value that indicates how many octets of data the sender is permitted to transmit; as such, its size is a measure of the buffering capacity of the receiver. Two flow control windows are applicable: the stream flow control window and the connection flow control window. The sender MUST NOT send a flow controlled frame with a length that exceeds the space available in either of the flow control windows advertised by the receiver. Frames with zero length with the END_STREAM flag set (that is, an empty DATA frame) MAY be sent if there is no available space in either flow control window. For flow control calculations, the 9 octet frame header is not counted. After sending a flow controlled frame, the sender reduces the space available in both windows by the length of the transmitted frame. The receiver of a frame sends a WINDOW_UPDATE frame as it consumes data and frees up space in flow control windows. Separate WINDOW_UPDATE frames are sent for the stream and connection level flow control windows. A sender that receives a WINDOW_UPDATE frame updates the corresponding window by the amount specified in the frame. A sender MUST NOT allow a flow control window to exceed 231-1 octets. If a sender receives a WINDOW_UPDATE that causes a flow control window to exceed this maximum it MUST terminate either the stream or the connection, as appropriate. For streams, the sender sends a RST_STREAM with the error code of FLOW_CONTROL_ERROR code; for the connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code. Flow controlled frames from the sender and WINDOW_UPDATE frames from the receiver are completely asynchronous with respect to each other. This property allows a receiver to aggressively update the window size kept by the sender to prevent streams from stalling.
When an HTTP/2 connection is first established, new streams are created with an initial flow control window size of 65,535 octets. The connection flow control window is 65,535 octets. Both endpoints can adjust the initial window size for new streams by including a value for SETTINGS_INITIAL_WINDOW_SIZE in the SETTINGS frame that forms part of the connection preface. The connection flow control window can only be changed using WINDOW_UPDATE frames. Prior to receiving a SETTINGS frame that sets a value for SETTINGS_INITIAL_WINDOW_SIZE, an endpoint can only use the default initial window size when sending flow controlled frames. Similarly, the connection flow control window is set to the default initial window size until a WINDOW_UPDATE frame is received. A SETTINGS frame can alter the initial flow control window size for all current streams. When the value of SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST adjust the size of all stream flow control windows that it maintains by the difference between the new value and the old value. A change to SETTINGS_INITIAL_WINDOW_SIZE can cause the available space in a flow control window to become negative. A sender MUST track the negative flow control window, and MUST NOT send new flow controlled frames until it receives WINDOW_UPDATE frames that cause the flow control window to become positive. For example, if the client sends 60KB immediately on connection establishment, and the server sets the initial window size to be 16KB, the client will recalculate the available flow control window to be -44KB on receipt of the SETTINGS frame. The client retains a negative flow control window until WINDOW_UPDATE frames restore the window to being positive, after which the client can resume sending. A SETTINGS frame cannot alter the connection flow control window. An endpoint MUST treat a change to SETTINGS_INITIAL_WINDOW_SIZE that causes any flow control window to exceed the maximum size as a connection error of type FLOW_CONTROL_ERROR.
A receiver that wishes to use a smaller flow control window than the current size can send a new SETTINGS frame. However, the receiver MUST be prepared to receive data that exceeds this window size, since the sender might send data that exceeds the lower limit prior to processing the SETTINGS frame. After sending a SETTINGS frame that reduces the initial flow control window size, a receiver has two options for handling streams that exceed flow control limits: The receiver can immediately send RST_STREAM with FLOW_CONTROL_ERROR error code for the affected streams. The receiver can accept the streams and tolerate the resulting head of line blocking, sending WINDOW_UPDATE frames as it consumes data.
The CONTINUATION frame (type=0x9) is used to continue a sequence of header block fragments. Any number of CONTINUATION frames can be sent on an existing stream, as long as the preceding frame is on the same stream and is a HEADERS, PUSH_PROMISE or CONTINUATION frame without the END_HEADERS flag set.
The CONTINUATION frame payload contains a header block fragment. The CONTINUATION frame defines the following flag: Bit 3 being set indicates that this frame ends a header block. If the END_HEADERS bit is not set, this frame MUST be followed by another CONTINUATION frame. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error of type PROTOCOL_ERROR. The CONTINUATION frame changes the connection state as defined in . CONTINUATION frames MUST be associated with a stream. If a CONTINUATION frame is received whose stream identifier field is 0x0, the recipient MUST respond with a connection error of type PROTOCOL_ERROR. A CONTINUATION frame MUST be preceded by a HEADERS, PUSH_PROMISE or CONTINUATION frame without the END_HEADERS flag set. A recipient that observes violation of this rule MUST respond with a connection error of type PROTOCOL_ERROR.
Error codes are 32-bit fields that are used in RST_STREAM and GOAWAY frames to convey the reasons for the stream or connection error. Error codes share a common code space. Some error codes apply only to either streams or the entire connection and have no defined semantics in the other context. The following error codes are defined: The associated condition is not as a result of an error. For example, a GOAWAY might include this code to indicate graceful shutdown of a connection. The endpoint detected an unspecific protocol error. This error is for use when a more specific error code is not available. The endpoint encountered an unexpected internal error. The endpoint detected that its peer violated the flow control protocol. The endpoint sent a SETTINGS frame, but did not receive a response in a timely manner. See Settings Synchronization. The endpoint received a frame after a stream was half closed. The endpoint received a frame with an invalid size. The endpoint refuses the stream prior to performing any application processing, see for details. Used by the endpoint to indicate that the stream is no longer needed. The endpoint is unable to maintain the header compression context for the connection. The connection established in response to a CONNECT request was reset or abnormally closed. The endpoint detected that its peer is exhibiting a behavior that might be generating excessive load. The underlying transport has properties that do not meet minimum security requirements (see ). Unknown or unsupported error codes MUST NOT trigger any special behavior. These MAY be treated by an implementation as being equivalent to INTERNAL_ERROR.
HTTP/2 is intended to be as compatible as possible with current uses of HTTP. This means that, from the application perspective, the features of the protocol are largely unchanged. To achieve this, all request and response semantics are preserved, although the syntax of conveying those semantics has changed. Thus, the specification and requirements of HTTP/1.1 Semantics and Content , Conditional Requests , Range Requests , Caching and Authentication are applicable to HTTP/2. Selected portions of HTTP/1.1 Message Syntax and Routing , such as the HTTP and HTTPS URI schemes, are also applicable in HTTP/2, but the expression of those semantics for this protocol are defined in the sections below.
A client sends an HTTP request on a new stream, using a previously unused stream identifier. A server sends an HTTP response on the same stream as the request. An HTTP message (request or response) consists of: for a response only, zero or more HEADERS frames (each followed by zero or more CONTINUATION frames) containing the message headers of informational (1xx) HTTP responses (see and ), and one HEADERS frame (followed by zero or more CONTINUATION frames) containing the message headers (see ), and zero or more DATA frames containing the message payload (see ), and optionally, one HEADERS frame, followed by zero or more CONTINUATION frames containing the trailer-part, if present (see ). The last frame in the sequence bears an END_STREAM flag, noting that a HEADERS frame bearing the END_STREAM flag can be followed by CONTINUATION frames that carry any remaining portions of the header block. Other frames (from any stream) MUST NOT occur between either HEADERS frame and any CONTINUATION frames that might follow. Trailing header fields are carried in a header block that also terminates the stream. That is, a sequence starting with a HEADERS frame, followed by zero or more CONTINUATION frames, where the HEADERS frame bears an END_STREAM flag. Header blocks after the first that do not terminate the stream are not part of an HTTP request or response. A HEADERS frame (and associated CONTINUATION frames) can only appear at the start or end of a stream. An endpoint that receives a HEADERS frame without the END_STREAM flag set after receiving a final (non-informational) status code MUST treat the corresponding request or response as malformed. An HTTP request/response exchange fully consumes a single stream. A request starts with the HEADERS frame that puts the stream into an "open" state. The request ends with a frame bearing END_STREAM, which causes the stream to become "half closed (local)" for the client and "half closed (remote)" for the server. A response starts with a HEADERS frame and ends with a frame bearing END_STREAM, which places the stream in the "closed" state.
HTTP/2 removes support for the 101 (Switching Protocols) informational status code (). The semantics of 101 (Switching Protocols) aren't applicable to a multiplexed protocol. Alternative protocols are able to use the same mechanisms that HTTP/2 uses to negotiate their use (see ).
HTTP header fields carry information as a series of key-value pairs. For a listing of registered HTTP headers, see the Message Header Field Registry maintained at .
While HTTP/1.x used the message start-line (see ) to convey the target URI and method of the request, and the status code for the response, HTTP/2 uses special pseudo-header fields beginning with ':' character (ASCII 0x3a) for this purpose. Pseudo-header fields are not HTTP header fields. Endpoints MUST NOT generate pseudo-header fields other than those defined in this document. Pseudo-header fields are only valid in the context in which they are defined. Pseudo-header fields defined for requests MUST NOT appear in responses; pseudo-header fields defined for responses MUST NOT appear in requests. Pseudo-header fields MUST NOT appear in trailers. Endpoints MUST treat a request or response that contains undefined or invalid pseudo-header fields as malformed. Just as in HTTP/1.x, header field names are strings of ASCII characters that are compared in a case-insensitive fashion. However, header field names MUST be converted to lowercase prior to their encoding in HTTP/2. A request or response containing uppercase header field names MUST be treated as malformed. All pseudo-header fields MUST appear in the header block before regular header fields. Any request or response that contains a pseudo-header field that appears in a header block after a regular header field MUST be treated as malformed.
HTTP/2 does not use the Connection header field to indicate connection-specific header fields; in this protocol, connection-specific metadata is conveyed by other means. An endpoint MUST NOT generate a HTTP/2 message containing connection-specific header fields; any message containing connection-specific header fields MUST be treated as malformed. This means that an intermediary transforming an HTTP/1.x message to HTTP/2 will need to remove any header fields nominated by the Connection header field, along with the Connection header field itself. Such intermediaries SHOULD also remove other connection-specific header fields, such as Keep-Alive, Proxy-Connection, Transfer-Encoding and Upgrade, even if they are not nominated by Connection. One exception to this is the TE header field, which MAY be present in an HTTP/2 request, but when it is MUST NOT contain any value other than "trailers". HTTP/2 purposefully does not support upgrade to another protocol. The handshake methods described in are believed sufficient to negotiate the use of alternative protocols.
The following pseudo-header fields are defined for HTTP/2 requests: The :method pseudo-header field includes the HTTP method (). The :scheme pseudo-header field includes the scheme portion of the target URI (). :scheme is not restricted to http and https schemed URIs. A proxy or gateway can translate requests for non-HTTP schemes, enabling the use of HTTP to interact with non-HTTP services. The :authority pseudo-header field includes the authority portion of the target URI (). The authority MUST NOT include the deprecated userinfo subcomponent for http or https schemed URIs. To ensure that the HTTP/1.1 request line can be reproduced accurately, this pseudo-header field MUST be omitted when translating from an HTTP/1.1 request that has a request target in origin or asterisk form (see ). Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. An intermediary that converts an HTTP/2 request to HTTP/1.1 MUST create a Host header field if one is not present in a request by copying the value of the :authority pseudo-header field. The :path pseudo-header field includes the path and query parts of the target URI (the path-absolute production from and optionally a '?' character followed by the query production, see and ). A request in asterisk form includes the value '*' for the :path pseudo-header field. This pseudo-header field MUST NOT be empty for http or https URIs; http or https URIs that do not contain a path component MUST include a value of '/'. The exception to this rule is an OPTIONS request for an http or https URI that does not include a path component; these MUST include a :path pseudo-header field with a value of '*' (see ). All HTTP/2 requests MUST include exactly one valid value for the :method, :scheme, and :path pseudo-header fields, unless it is a CONNECT request. An HTTP request that omits mandatory pseudo-header fields is malformed. HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
For HTTP/2 responses, a single :status pseudo-header field is defined that carries the HTTP status code field (see ). This pseudo-header field MUST be included in all responses, otherwise the response is malformed. HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.
The Cookie header field can carry a significant amount of redundant data. The Cookie header field uses a semi-colon (";") to delimit cookie-pairs (or "crumbs"). This header field doesn't follow the list construction rules in HTTP (see ), which prevents cookie-pairs from being separated into different name-value pairs. This can significantly reduce compression efficiency as individual cookie-pairs are updated. To allow for better compression efficiency, the Cookie header field MAY be split into separate header fields, each with one or more cookie-pairs. If there are multiple Cookie header fields after decompression, these MUST be concatenated into a single octet string using the two octet delimiter of 0x3B, 0x20 (the ASCII string "; ") before being passed into a non-HTTP/2 context, such as an HTTP/1.1 connection, or a generic HTTP server application.
Therefore, the following two lists of Cookie header fields are semantically equivalent.
A malformed request or response is one that is an otherwise valid sequence of HTTP/2 frames, but is otherwise invalid due to the presence of extraneous frames, prohibited header fields, the absence of mandatory header fields, or the inclusion of uppercase header field names. A request or response that includes an entity body can include a content-length header field. A request or response is also malformed if the value of a content-length header field does not equal the sum of the DATA frame payload lengths that form the body. A response that is defined to have no payload, as described in , can have a non-zero content-length header field, even though no content is included in DATA frames. Intermediaries that process HTTP requests or responses (i.e., any intermediary not acting as a tunnel) MUST NOT forward a malformed request or response. Malformed requests or responses that are detected MUST be treated as a stream error of type PROTOCOL_ERROR. For malformed requests, a server MAY send an HTTP response prior to closing or resetting the stream. Clients MUST NOT accept a malformed response. Note that these requirements are intended to protect against several types of common attacks against HTTP; they are deliberately strict, because being permissive can expose implementations to these vulnerabilities.
This section shows HTTP/1.1 requests and responses, with illustrations of equivalent HTTP/2 requests and responses. An HTTP GET request includes request header fields and no body and is therefore transmitted as a single HEADERS frame, followed by zero or more CONTINUATION frames containing the serialized block of request header fields. The HEADERS frame in the following has both the END_HEADERS and END_STREAM flags set; no CONTINUATION frames are sent:
+ END_STREAM Accept: image/jpeg + END_HEADERS :method = GET :scheme = https :path = /resource host = example.org accept = image/jpeg ]]>
Similarly, a response that includes only response header fields is transmitted as a HEADERS frame (again, followed by zero or more CONTINUATION frames) containing the serialized block of response header fields.
+ END_STREAM Expires: Thu, 23 Jan ... + END_HEADERS :status = 304 etag = "xyzzy" expires = Thu, 23 Jan ... ]]>
An HTTP POST request that includes request header fields and payload data is transmitted as one HEADERS frame, followed by zero or more CONTINUATION frames containing the request header fields, followed by one or more DATA frames, with the last CONTINUATION (or HEADERS) frame having the END_HEADERS flag set and the final DATA frame having the END_STREAM flag set:
- END_STREAM Content-Type: image/jpeg - END_HEADERS Content-Length: 123 :method = POST :path = /resource {binary data} :scheme = https CONTINUATION + END_HEADERS content-type = image/jpeg host = example.org content-length = 123 DATA + END_STREAM {binary data} ]]> Note that data contributing to any given header field could be spread between header block fragments. The allocation of header fields to frames in this example is illustrative only.
A response that includes header fields and payload data is transmitted as a HEADERS frame, followed by zero or more CONTINUATION frames, followed by one or more DATA frames, with the last DATA frame in the sequence having the END_STREAM flag set:
- END_STREAM Content-Length: 123 + END_HEADERS :status = 200 {binary data} content-type = image/jpeg content-length = 123 DATA + END_STREAM {binary data} ]]>
Trailing header fields are sent as a header block after both the request or response header block and all the DATA frames have been sent. The HEADERS frame starting the trailers header block has the END_STREAM flag set.
- END_STREAM Transfer-Encoding: chunked + END_HEADERS Trailer: Foo :status = 200 content-length = 123 123 content-type = image/jpeg {binary data} trailer = Foo 0 Foo: bar DATA - END_STREAM {binary data} HEADERS + END_STREAM + END_HEADERS foo = bar ]]>
An informational response using a 1xx status code other than 101 is transmitted as a HEADERS frame, followed by zero or more CONTINUATION frames: - END_STREAM + END_HEADERS :status = 103 extension-field = bar ]]>
In HTTP/1.1, an HTTP client is unable to retry a non-idempotent request when an error occurs, because there is no means to determine the nature of the error. It is possible that some server processing occurred prior to the error, which could result in undesirable effects if the request were reattempted. HTTP/2 provides two mechanisms for providing a guarantee to a client that a request has not been processed: The GOAWAY frame indicates the highest stream number that might have been processed. Requests on streams with higher numbers are therefore guaranteed to be safe to retry. The REFUSED_STREAM error code can be included in a RST_STREAM frame to indicate that the stream is being closed prior to any processing having occurred. Any request that was sent on the reset stream can be safely retried. Requests that have not been processed have not failed; clients MAY automatically retry them, even those with non-idempotent methods. A server MUST NOT indicate that a stream has not been processed unless it can guarantee that fact. If frames that are on a stream are passed to the application layer for any stream, then REFUSED_STREAM MUST NOT be used for that stream, and a GOAWAY frame MUST include a stream identifier that is greater than or equal to the given stream identifier. In addition to these mechanisms, the PING frame provides a way for a client to easily test a connection. Connections that remain idle can become broken as some middleboxes (for instance, network address translators, or load balancers) silently discard connection bindings. The PING frame allows a client to safely test whether a connection is still active without sending a request.
HTTP/2 allows a server to pre-emptively send (or "push") responses (along with corresponding "promised" requests) to a client in association with a previous client-initiated request. This can be useful when the server knows the client will need to have those responses available in order to fully process the response to the original request. Pushing additional message exchanges in this fashion is optional, and is negotiated between individual endpoints. The SETTINGS_ENABLE_PUSH setting can be set to 0 to indicate that server push is disabled. Promised requests MUST be cacheable (see ), MUST be safe (see ) and MUST NOT include a request body. Clients that receive a promised request that is not cacheable, unsafe or that includes a request body MUST reset the stream with a stream error of type PROTOCOL_ERROR. Pushed responses that are cacheable (see ) can be stored by the client, if it implements a HTTP cache. Pushed responses are considered successfully validated on the origin server (e.g., if the "no-cache" cache response directive is present) while the stream identified by the promised stream ID is still open. Pushed responses that are not cacheable MUST NOT be stored by any HTTP cache. They MAY be made available to the application separately. An intermediary can receive pushes from the server and choose not to forward them on to the client. In other words, how to make use of the pushed information is up to that intermediary. Equally, the intermediary might choose to make additional pushes to the client, without any action taken by the server. A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE frame as a connection error of type PROTOCOL_ERROR. Clients MUST reject any attempt to change the SETTINGS_ENABLE_PUSH setting to a value other than 0 by treating the message as a connection error of type PROTOCOL_ERROR.
Server push is semantically equivalent to a server responding to a request; however, in this case that request is also sent by the server, as a PUSH_PROMISE frame. The PUSH_PROMISE frame includes a header block that contains a complete set of request header fields that the server attributes to the request. It is not possible to push a response to a request that includes a request body. Pushed responses are always associated with an explicit request from the client. The PUSH_PROMISE frames sent by the server are sent on that explicit request's stream. The PUSH_PROMISE frame also includes a promised stream identifier, chosen from the stream identifiers available to the server (see ). The header fields in PUSH_PROMISE and any subsequent CONTINUATION frames MUST be a valid and complete set of request header fields. The server MUST include a method in the :method header field that is safe and cacheable. If a client receives a PUSH_PROMISE that does not include a complete and valid set of header fields, or the :method header field identifies a method that is not safe, it MUST respond with a stream error of type PROTOCOL_ERROR. The server SHOULD send PUSH_PROMISE () frames prior to sending any frames that reference the promised responses. This avoids a race where clients issue requests prior to receiving any PUSH_PROMISE frames. For example, if the server receives a request for a document containing embedded links to multiple image files, and the server chooses to push those additional images to the client, sending push promises before the DATA frames that contain the image links ensures that the client is able to see the promises before discovering embedded links. Similarly, if the server pushes responses referenced by the header block (for instance, in Link header fields), sending the push promises before sending the header block ensures that clients do not request them. PUSH_PROMISE frames MUST NOT be sent by the client. PUSH_PROMISE frames can be sent by the server in response to any client-initiated stream, but the stream MUST be in either the "open" or "half closed (remote)" state with respect to the server. PUSH_PROMISE frames are interspersed with the frames that comprise a response, though they cannot be interspersed with HEADERS and CONTINUATION frames that comprise a single header block. Sending a PUSH_PROMISE frame creates a new stream and puts the stream into the “reserved (local)†state for the server and the “reserved (remote)†state for the client.
After sending the PUSH_PROMISE frame, the server can begin delivering the pushed response as a response on a server-initiated stream that uses the promised stream identifier. The server uses this stream to transmit an HTTP response, using the same sequence of frames as defined in . This stream becomes "half closed" to the client after the initial HEADERS frame is sent. Once a client receives a PUSH_PROMISE frame and chooses to accept the pushed response, the client SHOULD NOT issue any requests for the promised response until after the promised stream has closed. If the client determines, for any reason, that it does not wish to receive the pushed response from the server, or if the server takes too long to begin sending the promised response, the client can send an RST_STREAM frame, using either the CANCEL or REFUSED_STREAM codes, and referencing the pushed stream's identifier. A client can use the SETTINGS_MAX_CONCURRENT_STREAMS setting to limit the number of responses that can be concurrently pushed by a server. Advertising a SETTINGS_MAX_CONCURRENT_STREAMS value of zero disables server push by preventing the server from creating the necessary streams. This does not prohibit a server from sending PUSH_PROMISE frames; clients need to reset any promised streams that are not wanted. Clients receiving a pushed response MUST validate that either the server is authoritative (see ), or the proxy that provided the pushed response is configured for the corresponding request. For example, a server that offers a certificate for only the example.com DNS-ID or Common Name is not permitted to push a response for https://www.example.org/doc. The response for a PUSH_PROMISE stream begins with a HEADERS frame, which immediately puts the stream into the “half closed (remote)†state for the server and “half closed (local)†state for the client, and ends with a frame bearing END_STREAM, which places the stream in the "closed" state. The client never sends a frame with the END_STREAM flag for a server push.
In HTTP/1.x, the pseudo-method CONNECT () is used to convert an HTTP connection into a tunnel to a remote host. CONNECT is primarily used with HTTP proxies to establish a TLS session with an origin server for the purposes of interacting with https resources. In HTTP/2, the CONNECT method is used to establish a tunnel over a single HTTP/2 stream to a remote host, for similar purposes. The HTTP header field mapping works as defined in Request Header Fields, with a few differences. Specifically: The :method header field is set to CONNECT. The :scheme and :path header fields MUST be omitted. The :authority header field contains the host and port to connect to (equivalent to the authority-form of the request-target of CONNECT requests, see ). A proxy that supports CONNECT establishes a TCP connection to the server identified in the :authority header field. Once this connection is successfully established, the proxy sends a HEADERS frame containing a 2xx series status code to the client, as defined in . After the initial HEADERS frame sent by each peer, all subsequent DATA frames correspond to data sent on the TCP connection. The payload of any DATA frames sent by the client is transmitted by the proxy to the TCP server; data received from the TCP server is assembled into DATA frames by the proxy. Frame types other than DATA or stream management frames (RST_STREAM, WINDOW_UPDATE, and PRIORITY) MUST NOT be sent on a connected stream, and MUST be treated as a stream error if received. The TCP connection can be closed by either peer. The END_STREAM flag on a DATA frame is treated as being equivalent to the TCP FIN bit. A client is expected to send a DATA frame with the END_STREAM flag set after receiving a frame bearing the END_STREAM flag. A proxy that receives a DATA frame with the END_STREAM flag set sends the attached data with the FIN bit set on the last TCP segment. A proxy that receives a TCP segment with the FIN bit set sends a DATA frame with the END_STREAM flag set. Note that the final TCP segment or DATA frame could be empty. A TCP connection error is signaled with RST_STREAM. A proxy treats any error in the TCP connection, which includes receiving a TCP segment with the RST bit set, as a stream error of type CONNECT_ERROR. Correspondingly, a proxy MUST send a TCP segment with the RST bit set if it detects an error with the stream or the HTTP/2 connection.
This section outlines attributes of the HTTP protocol that improve interoperability, reduce exposure to known security vulnerabilities, or reduce the potential for implementation variation.
HTTP/2 connections are persistent. For best performance, it is expected clients will not close connections until it is determined that no further communication with a server is necessary (for example, when a user navigates away from a particular web page), or until the server closes the connection. Clients SHOULD NOT open more than one HTTP/2 connection to a given host and port pair, where host is derived from a URI, a selected alternative service, or a configured proxy. A client can create additional connections as replacements, either to replace connections that are near to exhausting the available stream identifier space, to refresh the keying material for a TLS connection, or to replace connections that have encountered errors. A client MAY open multiple connections to the same IP address and TCP port using different Server Name Indication values or to provide different TLS client certificates, but SHOULD avoid creating multiple connections with the same configuration. Servers are encouraged to maintain open connections for as long as possible, but are permitted to terminate idle connections if necessary. When either endpoint chooses to close the transport-layer TCP connection, the terminating endpoint SHOULD first send a GOAWAY () frame so that both endpoints can reliably determine whether previously sent frames have been processed and gracefully complete or terminate any necessary remaining tasks.
Connections that are made to an origin servers, either directly or through a tunnel created using the CONNECT method MAY be reused for requests with multiple different URI authority components. A connection can be reused as long as the origin server is authoritative. For http resources, this depends on the host having resolved to the same IP address. For https resources, connection reuse additionally depends on having a certificate that is valid for the host in the URI. An origin server might offer a certificate with multiple subjectAltName attributes, or names with wildcards, one of which is valid for the authority in the URI. For example, a certificate with a subjectAltName of *.example.com might permit the use of the same connection for requests to URIs starting with https://a.example.com/ and https://b.example.com/. In some deployments, reusing a connection for multiple origins can result in requests being directed to the wrong origin server. For example, TLS termination might be performed by a middlebox that uses the TLS Server Name Indication (SNI) extension to select an origin server. This means that it is possible for clients to send confidential information to servers that might not be the intended target for the request, even though the server is otherwise authoritative. A server that does not wish clients to reuse connections can indicate that it is not authoritative for a request by sending a 421 (Misdirected Request) status code in response to the request (see ). A client that is configured to use a proxy over HTTP/2 directs requests to that proxy through a single connection. That is, all requests sent via a proxy reuse the connection to the proxy.
The 421 (Misdirected Request) status code indicates that the request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI. Clients receiving a 421 (Misdirected Request) response from a server MAY retry the request - whether the request method is idempotent or not - over a different connection. This is possible if a connection is reused () or if an alternative service is selected (). This status code MUST NOT be generated by proxies. A 421 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see ).
Implementations of HTTP/2 MUST support TLS 1.2 for HTTP/2 over TLS. The general TLS usage guidance in SHOULD be followed, with some additional restrictions that are specific to HTTP/2. An implementation of HTTP/2 over TLS MUST use TLS 1.2 or higher with the restrictions on feature set and cipher suite described in this section. Due to implementation limitations, it might not be possible to fail TLS negotiation. An endpoint MUST immediately terminate an HTTP/2 connection that does not meet these minimum requirements with a connection error of type INADEQUATE_SECURITY.
The TLS implementation MUST support the Server Name Indication (SNI) extension to TLS. HTTP/2 clients MUST indicate the target domain name when negotiating TLS. The TLS implementation MUST disable compression. TLS compression can lead to the exposure of information that would not otherwise be revealed . Generic compression is unnecessary since HTTP/2 provides compression features that are more aware of context and therefore likely to be more appropriate for use for performance, security or other reasons. The TLS implementation MUST disable renegotiation. An endpoint MUST treat a TLS renegotiation as a connection error of type PROTOCOL_ERROR. Note that disabling renegotiation can result in long-lived connections becoming unusable due to limits on the number of messages the underlying cipher suite can encipher. A client MAY use renegotiation to provide confidentiality protection for client credentials offered in the handshake, but any renegotiation MUST occur prior to sending the connection preface. A server SHOULD request a client certificate if it sees a renegotiation request immediately after establishing a connection. This effectively prevents the use of renegotiation in response to a request for a specific protected resource. A future specification might provide a way to support this use case.
The set of TLS cipher suites that are permitted in HTTP/2 is restricted. HTTP/2 MUST only be used with cipher suites that have ephemeral key exchange, such as the ephemeral Diffie-Hellman (DHE) or the elliptic curve variant (ECDHE). Ephemeral key exchange MUST have a minimum size of 2048 bits for DHE or security level of 128 bits for ECDHE. Clients MUST accept DHE sizes of up to 4096 bits. HTTP MUST NOT be used with cipher suites that use stream or block ciphers. Authenticated Encryption with Additional Data (AEAD) modes, such as the Galois Counter Model (GCM) mode for AES are acceptable. The effect of these restrictions is that TLS 1.2 implementations could have non-intersecting sets of available cipher suites, since these prevent the use of the cipher suite that TLS 1.2 makes mandatory. To avoid this problem, implementations of HTTP/2 that use TLS 1.2 MUST support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 with P256 . Clients MAY advertise support of cipher suites that are prohibited by the above restrictions in order to allow for connection to servers that do not support HTTP/2. This enables a fallback to protocols without these constraints without the additional latency imposed by using a separate connection for fallback.
HTTP/2 relies on the HTTP/1.1 definition of authority for determining whether a server is authoritative in providing a given response, see . This relies on local name resolution for the "http" URI scheme, and the authenticated server identity for the "https" scheme (see ).
In a cross-protocol attack, an attacker causes a client to initiate a transaction in one protocol toward a server that understands a different protocol. An attacker might be able to cause the transaction to appear as valid transaction in the second protocol. In combination with the capabilities of the web context, this can be used to interact with poorly protected servers in private networks. Completing a TLS handshake with an ALPN identifier for HTTP/2 can be considered sufficient protection against cross protocol attacks. ALPN provides a positive indication that a server is willing to proceed with HTTP/2, which prevents attacks on other TLS-based protocols. The encryption in TLS makes it difficult for attackers to control the data which could be used in a cross-protocol attack on a cleartext protocol. The cleartext version of HTTP/2 has minimal protection against cross-protocol attacks. The connection preface contains a string that is designed to confuse HTTP/1.1 servers, but no special protection is offered for other protocols. A server that is willing to ignore parts of an HTTP/1.1 request containing an Upgrade header field in addition to the client connection preface could be exposed to a cross-protocol attack.
HTTP/2 header field names and values are encoded as sequences of octets with a length prefix. This enables HTTP/2 to carry any string of octets as the name or value of a header field. An intermediary that translates HTTP/2 requests or responses into HTTP/1.1 directly could permit the creation of corrupted HTTP/1.1 messages. An attacker might exploit this behavior to cause the intermediary to create HTTP/1.1 messages with illegal header fields, extra header fields, or even new messages that are entirely falsified. Header field names or values that contain characters not permitted by HTTP/1.1, including carriage return (ASCII 0xd) or line feed (ASCII 0xa) MUST NOT be translated verbatim by an intermediary, as stipulated in . Translation from HTTP/1.x to HTTP/2 does not produce the same opportunity to an attacker. Intermediaries that perform translation to HTTP/2 MUST remove any instances of the obs-fold production from header field values.
Pushed responses do not have an explicit request from the client; the request is provided by the server in the PUSH_PROMISE frame. Caching responses that are pushed is possible based on the guidance provided by the origin server in the Cache-Control header field. However, this can cause issues if a single server hosts more than one tenant. For example, a server might offer multiple users each a small portion of its URI space. Where multiple tenants share space on the same server, that server MUST ensure that tenants are not able to push representations of resources that they do not have authority over. Failure to enforce this would allow a tenant to provide a representation that would be served out of cache, overriding the actual representation that the authoritative tenant provides. Pushed responses for which an origin server is not authoritative (see ) are never cached or used.
An HTTP/2 connection can demand a greater commitment of resources to operate than a HTTP/1.1 connection. The use of header compression and flow control depend on a commitment of resources for storing a greater amount of state. Settings for these features ensure that memory commitments for these features are strictly bounded. The number of PUSH_PROMISE frames is not constrained in the same fashion. A client that accepts server push SHOULD limit the number of streams it allows to be in the "reserved (remote)" state. Excessive number of server push streams can be treated as a stream error of type ENHANCE_YOUR_CALM. Processing capacity cannot be guarded as effectively as state capacity. The SETTINGS frame can be abused to cause a peer to expend additional processing time. This might be done by pointlessly changing SETTINGS parameters, setting multiple undefined parameters, or changing the same setting multiple times in the same frame. WINDOW_UPDATE or PRIORITY frames can be abused to cause an unnecessary waste of resources. Large numbers of small or empty frames can be abused to cause a peer to expend time processing frame headers. Note however that some uses are entirely legitimate, such as the sending of an empty DATA frame to end a stream. Header compression also offers some opportunities to waste processing resources; see for more details on potential abuses. Limits in SETTINGS parameters cannot be reduced instantaneously, which leaves an endpoint exposed to behavior from a peer that could exceed the new limits. In particular, immediately after establishing a connection, limits set by a server are not known to clients and could be exceeded without being an obvious protocol violation. All these features - i.e., SETTINGS changes, small frames, header compression - have legitimate uses. These features become a burden only when they are used unnecessarily or to excess. An endpoint that doesn't monitor this behavior exposes itself to a risk of denial of service attack. Implementations SHOULD track the use of these features and set limits on their use. An endpoint MAY treat activity that is suspicious as a connection error of type ENHANCE_YOUR_CALM.
A large header block can cause an implementation to commit a large amount of state. Header fields that are critical for routing can appear toward the end of a header block, which prevents streaming of header fields to their ultimate destination. For this an other reasons, such as ensuring cache correctness, means that an endpoint might need to buffer the entire header block. Since there is no hard limit to the size of a header block, some endpoints could be forced commit a large amount of available memory for header fields. An endpoint can use the SETTINGS_MAX_HEADER_LIST_SIZE to advise peers of limits that might apply on the size of header blocks. This setting is only advisory, so endpoints MAY choose to send header blocks that exceed this limit and risk having the request or response being treated as malformed. This setting specific to a connection, so any request or response could encounter a hop with a lower, unknown limit. An intermediary can attempt to avoid this problem by passing on values presented by different peers, but they are not obligated to do so. A server that receives a larger header block than it is willing to handle can send an HTTP 431 (Request Header Fields Too Large) status code . A client can discard responses that it cannot process. The header block MUST be processed to ensure a consistent connection state, unless the connection is closed.
HTTP/2 enables greater use of compression for both header fields () and entity bodies. Compression can allow an attacker to recover secret data when it is compressed in the same context as data under attacker control. There are demonstrable attacks on compression that exploit the characteristics of the web (e.g., ). The attacker induces multiple requests containing varying plaintext, observing the length of the resulting ciphertext in each, which reveals a shorter length when a guess about the secret is correct. Implementations communicating on a secure channel MUST NOT compress content that includes both confidential and attacker-controlled data unless separate compression dictionaries are used for each source of data. Compression MUST NOT be used if the source of data cannot be reliably determined. Generic stream compression, such as that provided by TLS MUST NOT be used with HTTP/2 (). Further considerations regarding the compression of header fields are described in .
Padding within HTTP/2 is not intended as a replacement for general purpose padding, such as might be provided by TLS. Redundant padding could even be counterproductive. Correct application can depend on having specific knowledge of the data that is being padded. To mitigate attacks that rely on compression, disabling or limiting compression might be preferable to padding as a countermeasure. Padding can be used to obscure the exact size of frame content, and is provided to mitigate specific attacks within HTTP. For example, attacks where compressed content includes both attacker-controlled plaintext and secret data (see for example, ). Use of padding can result in less protection than might seem immediately obvious. At best, padding only makes it more difficult for an attacker to infer length information by increasing the number of frames an attacker has to observe. Incorrectly implemented padding schemes can be easily defeated. In particular, randomized padding with a predictable distribution provides very little protection; similarly, padding payloads to a fixed size exposes information as payload sizes cross the fixed size boundary, which could be possible if an attacker can control plaintext. Intermediaries SHOULD retain padding for DATA frames, but MAY drop padding for HEADERS and PUSH_PROMISE frames. A valid reason for an intermediary to change the amount of padding of frames is to improve the protections that padding provides.
Several characteristics of HTTP/2 provide an observer an opportunity to correlate actions of a single client or server over time. This includes the value of settings, the manner in which flow control windows are managed, the way priorities are allocated to streams, timing of reactions to stimulus, and handling of any optional features. As far as this creates observable differences in behavior, they could be used as a basis for fingerprinting a specific client, as defined in .
A string for identifying HTTP/2 is entered into the "Application Layer Protocol Negotiation (ALPN) Protocol IDs" registry established in . This document establishes a registry for frame types, settings, and error codes. These new registries are entered into a new "Hypertext Transfer Protocol (HTTP) 2 Parameters" section. This document registers the HTTP2-Settings header field for use in HTTP; and the 421 (Misdirected Request) status code. This document registers the PRI method for use in HTTP, to avoid collisions with the connection preface.
This document creates two registrations for the identification of HTTP/2 in the "Application Layer Protocol Negotiation (ALPN) Protocol IDs" registry established in . The "h2" string identifies HTTP/2 when used over TLS: HTTP/2 over TLS 0x68 0x32 ("h2") This document The "h2c" string identifies HTTP/2 when used over cleartext TCP: HTTP/2 over TCP 0x68 0x32 0x63 ("h2c") This document
This document establishes a registry for HTTP/2 frame type codes. The "HTTP/2 Frame Type" registry manages an 8-bit space. The "HTTP/2 Frame Type" registry operates under either of the "IETF Review" or "IESG Approval" policies for values between 0x00 and 0xef, with values between 0xf0 and 0xff being reserved for experimental use. New entries in this registry require the following information: A name or label for the frame type. The 8-bit code assigned to the frame type. A reference to a specification that includes a description of the frame layout, it's semantics and flags that the frame type uses, including any parts of the frame that are conditionally present based on the value of flags. The entries in the following table are registered by this document. Frame Type Code Section DATA0x0 HEADERS0x1 PRIORITY0x2 RST_STREAM0x3 SETTINGS0x4 PUSH_PROMISE0x5 PING0x6 GOAWAY0x7 WINDOW_UPDATE0x8 CONTINUATION0x9
This document establishes a registry for HTTP/2 settings. The "HTTP/2 Settings" registry manages a 16-bit space. The "HTTP/2 Settings" registry operates under the "Expert Review" policy for values in the range from 0x0000 to 0xefff, with values between and 0xf000 and 0xffff being reserved for experimental use. New registrations are advised to provide the following information: A symbolic name for the setting. Specifying a setting name is optional. The 16-bit code assigned to the setting. An initial value for the setting. An optional reference to a specification that describes the use of the setting. An initial set of setting registrations can be found in . Name Code Initial Value Specification HEADER_TABLE_SIZE 0x14096 ENABLE_PUSH 0x21 MAX_CONCURRENT_STREAMS 0x3(infinite) INITIAL_WINDOW_SIZE 0x465535 MAX_FRAME_SIZE 0x516384 MAX_HEADER_LIST_SIZE 0x6(infinite)
This document establishes a registry for HTTP/2 error codes. The "HTTP/2 Error Code" registry manages a 32-bit space. The "HTTP/2 Error Code" registry operates under the "Expert Review" policy. Registrations for error codes are required to include a description of the error code. An expert reviewer is advised to examine new registrations for possible duplication with existing error codes. Use of existing registrations is to be encouraged, but not mandated. New registrations are advised to provide the following information: A name for the error code. Specifying an error code name is optional. The 32-bit error code value. A brief description of the error code semantics, longer if no detailed specification is provided. An optional reference for a specification that defines the error code. The entries in the following table are registered by this document. Name Code Description Specification NO_ERROR0x0 Graceful shutdown PROTOCOL_ERROR0x1 Protocol error detected INTERNAL_ERROR0x2 Implementation fault FLOW_CONTROL_ERROR0x3 Flow control limits exceeded SETTINGS_TIMEOUT0x4 Settings not acknowledged STREAM_CLOSED0x5 Frame received for closed stream FRAME_SIZE_ERROR0x6 Frame size incorrect REFUSED_STREAM0x7 Stream not processed CANCEL0x8 Stream cancelled COMPRESSION_ERROR0x9 Compression state not updated CONNECT_ERROR0xa TCP connection error for CONNECT method ENHANCE_YOUR_CALM0xb Processing capacity exceeded INADEQUATE_SECURITY0xc Negotiated TLS parameters not acceptable
This section registers the HTTP2-Settings header field in the Permanent Message Header Field Registry. HTTP2-Settings http standard IETF of this document This header field is only used by an HTTP/2 client for Upgrade-based negotiation.
This section registers the PRI method in the HTTP Method Registry (). PRI No No of this document This method is never used by an actual client. This method will appear to be used when an HTTP/1.1 server or intermediary attempts to parse an HTTP/2 connection preface.
This document registers the 421 (Misdirected Request) HTTP Status code in the Hypertext Transfer Protocol (HTTP) Status Code Registry (). 421 Misdirected Request of this document
This document includes substantial input from the following individuals: Adam Langley, Wan-Teh Chang, Jim Morrison, Mark Nottingham, Alyssa Wilk, Costin Manolache, William Chan, Vitaliy Lvin, Joe Chan, Adam Barth, Ryan Hamilton, Gavin Peters, Kent Alstad, Kevin Lindsay, Paul Amer, Fan Yang, Jonathan Leighton (SPDY contributors). Gabriel Montenegro and Willy Tarreau (Upgrade mechanism). William Chan, Salvatore Loreto, Osama Mazahir, Gabriel Montenegro, Jitu Padhye, Roberto Peon, Rob Trace (Flow control). Mike Bishop (Extensibility). Mark Nottingham, Julian Reschke, James Snell, Jeff Pinner, Mike Bishop, Herve Ruellan (Substantial editorial contributions). Kari Hurtta, Tatsuhiro Tsujikawa, Greg Wilkins, Poul-Henning Kamp. Alexey Melnikov was an editor of this document during 2013. A substantial proportion of Martin's contribution was supported by Microsoft during his employment there.
HPACK - Header Compression for HTTP/2 Transmission Control Protocol University of Southern California (USC)/Information Sciences Institute Key words for use in RFCs to Indicate Requirement Levels Harvard University
sob@harvard.edu
HTTP Over TLS Uniform Resource Identifier (URI): Generic Syntax The Base16, Base32, and Base64 Data Encodings Guidelines for Writing an IANA Considerations Section in RFCs Augmented BNF for Syntax Specifications: ABNF The Transport Layer Security (TLS) Protocol Version 1.2 Transport Layer Security (TLS) Extensions: Extension Definitions Transport Layer Security (TLS) Application-Layer Protocol Negotiation Extension TLS Elliptic Curve Cipher Suites with SHA-256/384 and AES Galois Counter Mode (GCM) Digital Signature Standard (DSS) NIST Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing Adobe Systems Incorporated
fielding@gbiv.com
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content Adobe Systems Incorporated
fielding@gbiv.com
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests Adobe Systems Incorporated
fielding@gbiv.com
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Range Requests Adobe Systems Incorporated
fielding@gbiv.com
World Wide Web Consortium
ylafon@w3.org
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Caching Adobe Systems Incorporated
fielding@gbiv.com
Akamai
mnot@mnot.net
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Authentication Adobe Systems Incorporated
fielding@gbiv.com
greenbytes GmbH
julian.reschke@greenbytes.de
HTTP State Management Mechanism
TCP Extensions for High Performance Transport Layer Security Protocol Compression Methods Additional HTTP Status Codes Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS) AES Galois Counter Mode (GCM) Cipher Suites for TLS HTML5 Latest version available at . Talking to Yourself for Fun and Profit BREACH: Reviving the CRIME Attack Registration Procedures for Message Header Fields Nine by Nine
GK-IETF@ninebynine.org
BEA Systems
mnot@pobox.com
HP Labs
JeffMogul@acm.org
Recommendations for Secure Use of TLS and DTLS HTTP Alternative Services Akamai Mozilla greenbytes
This section is to be removed by RFC Editor before publication.
Renamed Not Authoritative status code to Misdirected Request.
Pseudo-header fields are now required to appear strictly before regular ones. Restored 1xx series status codes, except 101. Changed frame length field 24-bits. Expanded frame header to 9 octets. Added a setting to limit the damage. Added a setting to advise peers of header set size limits. Removed segments. Made non-semantic-bearing HEADERS frames illegal in the HTTP mapping.
Restored extensibility options. Restricting TLS cipher suites to AEAD only. Removing Content-Encoding requirements. Permitting the use of PRIORITY after stream close. Removed ALTSVC frame. Removed BLOCKED frame. Reducing the maximum padding size to 256 octets; removing padding from CONTINUATION frames. Removed per-frame GZIP compression.
Added BLOCKED frame (at risk). Simplified priority scheme. Added DATA per-frame GZIP compression.
Changed "connection header" to "connection preface" to avoid confusion. Added dependency-based stream prioritization. Added "h2c" identifier to distinguish between cleartext and secured HTTP/2. Adding missing padding to PUSH_PROMISE. Integrate ALTSVC frame and supporting text. Dropping requirement on "deflate" Content-Encoding. Improving security considerations around use of compression.
Adding padding for data frames. Renumbering frame types, error codes, and settings. Adding INADEQUATE_SECURITY error code. Updating TLS usage requirements to 1.2; forbidding TLS compression. Removing extensibility for frames and settings. Changing setting identifier size. Removing the ability to disable flow control. Changing the protocol identification token to "h2". Changing the use of :authority to make it optional and to allow userinfo in non-HTTP cases. Allowing split on 0x0 for Cookie. Reserved PRI method in HTTP/1.1 to avoid possible future collisions.
Added cookie crumbling for more efficient header compression. Added header field ordering with the value-concatenation mechanism.
Marked draft for implementation.
Adding definition for CONNECT method. Constraining the use of push to safe, cacheable methods with no request body. Changing from :host to :authority to remove any potential confusion. Adding setting for header compression table size. Adding settings acknowledgement. Removing unnecessary and potentially problematic flags from CONTINUATION. Added denial of service considerations.
Marking the draft ready for implementation. Renumbering END_PUSH_PROMISE flag. Editorial clarifications and changes.
Added CONTINUATION frame for HEADERS and PUSH_PROMISE. PUSH_PROMISE is no longer implicitly prohibited if SETTINGS_MAX_CONCURRENT_STREAMS is zero. Push expanded to allow all safe methods without a request body. Clarified the use of HTTP header fields in requests and responses. Prohibited HTTP/1.1 hop-by-hop header fields. Requiring that intermediaries not forward requests with missing or illegal routing :-headers. Clarified requirements around handling different frames after stream close, stream reset and GOAWAY. Added more specific prohibitions for sending of different frame types in various stream states. Making the last received setting value the effective value. Clarified requirements on TLS version, extension and ciphers.
Committed major restructuring atrocities. Added reference to first header compression draft. Added more formal description of frame lifecycle. Moved END_STREAM (renamed from FINAL) back to HEADERS/DATA. Removed HEADERS+PRIORITY, added optional priority to HEADERS frame. Added PRIORITY frame.
Added continuations to frames carrying header blocks. Replaced use of "session" with "connection" to avoid confusion with other HTTP stateful concepts, like cookies. Removed "message". Switched to TLS ALPN from NPN. Editorial changes.
Added IANA considerations section for frame types, error codes and settings. Removed data frame compression. Added PUSH_PROMISE. Added globally applicable flags to framing. Removed zlib-based header compression mechanism. Updated references. Clarified stream identifier reuse. Removed CREDENTIALS frame and associated mechanisms. Added advice against naive implementation of flow control. Added session header section. Restructured frame header. Removed distinction between data and control frames. Altered flow control properties to include session-level limits. Added note on cacheability of pushed resources and multiple tenant servers. Changed protocol label form based on discussions.
Changed title throughout. Removed section on Incompatibilities with SPDY draft#2. Changed INTERNAL_ERROR on GOAWAY to have a value of 2 . Replaced abstract and introduction. Added section on starting HTTP/2.0, including upgrade mechanism. Removed unused references. Added flow control principles based on .
Adopted as base for draft-ietf-httpbis-http2. Updated authors/editors list. Added status note.
lxd-2.0.11/dist/src/golang.org/x/net/http2/server_test.go0000644061062106075000000031404213172163402024254 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bytes" "crypto/tls" "errors" "flag" "fmt" "io" "io/ioutil" "log" "net" "net/http" "net/http/httptest" "os" "os/exec" "reflect" "runtime" "strconv" "strings" "sync" "sync/atomic" "testing" "time" "golang.org/x/net/http2/hpack" ) var stderrVerbose = flag.Bool("stderr_verbose", false, "Mirror verbosity to stderr, unbuffered") func stderrv() io.Writer { if *stderrVerbose { return os.Stderr } return ioutil.Discard } type serverTester struct { cc net.Conn // client conn t testing.TB ts *httptest.Server fr *Framer serverLogBuf bytes.Buffer // logger for httptest.Server logFilter []string // substrings to filter out scMu sync.Mutex // guards sc sc *serverConn hpackDec *hpack.Decoder decodedHeaders [][2]string // If http2debug!=2, then we capture Frame debug logs that will be written // to t.Log after a test fails. The read and write logs use separate locks // and buffers so we don't accidentally introduce synchronization between // the read and write goroutines, which may hide data races. frameReadLogMu sync.Mutex frameReadLogBuf bytes.Buffer frameWriteLogMu sync.Mutex frameWriteLogBuf bytes.Buffer // writing headers: headerBuf bytes.Buffer hpackEnc *hpack.Encoder } func init() { testHookOnPanicMu = new(sync.Mutex) } func resetHooks() { testHookOnPanicMu.Lock() testHookOnPanic = nil testHookOnPanicMu.Unlock() } type serverTesterOpt string var optOnlyServer = serverTesterOpt("only_server") var optQuiet = serverTesterOpt("quiet_logging") var optFramerReuseFrames = serverTesterOpt("frame_reuse_frames") func newServerTester(t testing.TB, handler http.HandlerFunc, opts ...interface{}) *serverTester { resetHooks() ts := httptest.NewUnstartedServer(handler) tlsConfig := &tls.Config{ InsecureSkipVerify: true, NextProtos: []string{NextProtoTLS}, } var onlyServer, quiet, framerReuseFrames bool h2server := new(Server) for _, opt := range opts { switch v := opt.(type) { case func(*tls.Config): v(tlsConfig) case func(*httptest.Server): v(ts) case func(*Server): v(h2server) case serverTesterOpt: switch v { case optOnlyServer: onlyServer = true case optQuiet: quiet = true case optFramerReuseFrames: framerReuseFrames = true } case func(net.Conn, http.ConnState): ts.Config.ConnState = v default: t.Fatalf("unknown newServerTester option type %T", v) } } ConfigureServer(ts.Config, h2server) st := &serverTester{ t: t, ts: ts, } st.hpackEnc = hpack.NewEncoder(&st.headerBuf) st.hpackDec = hpack.NewDecoder(initialHeaderTableSize, st.onHeaderField) ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config if quiet { ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0) } else { ts.Config.ErrorLog = log.New(io.MultiWriter(stderrv(), twriter{t: t, st: st}, &st.serverLogBuf), "", log.LstdFlags) } ts.StartTLS() if VerboseLogs { t.Logf("Running test server at: %s", ts.URL) } testHookGetServerConn = func(v *serverConn) { st.scMu.Lock() defer st.scMu.Unlock() st.sc = v } log.SetOutput(io.MultiWriter(stderrv(), twriter{t: t, st: st})) if !onlyServer { cc, err := tls.Dial("tcp", ts.Listener.Addr().String(), tlsConfig) if err != nil { t.Fatal(err) } st.cc = cc st.fr = NewFramer(cc, cc) if framerReuseFrames { st.fr.SetReuseFrames() } if !logFrameReads && !logFrameWrites { st.fr.debugReadLoggerf = func(m string, v ...interface{}) { m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n" st.frameReadLogMu.Lock() fmt.Fprintf(&st.frameReadLogBuf, m, v...) st.frameReadLogMu.Unlock() } st.fr.debugWriteLoggerf = func(m string, v ...interface{}) { m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n" st.frameWriteLogMu.Lock() fmt.Fprintf(&st.frameWriteLogBuf, m, v...) st.frameWriteLogMu.Unlock() } st.fr.logReads = true st.fr.logWrites = true } } return st } func (st *serverTester) closeConn() { st.scMu.Lock() defer st.scMu.Unlock() st.sc.conn.Close() } func (st *serverTester) addLogFilter(phrase string) { st.logFilter = append(st.logFilter, phrase) } func (st *serverTester) stream(id uint32) *stream { ch := make(chan *stream, 1) st.sc.serveMsgCh <- func(int) { ch <- st.sc.streams[id] } return <-ch } func (st *serverTester) streamState(id uint32) streamState { ch := make(chan streamState, 1) st.sc.serveMsgCh <- func(int) { state, _ := st.sc.state(id) ch <- state } return <-ch } // loopNum reports how many times this conn's select loop has gone around. func (st *serverTester) loopNum() int { lastc := make(chan int, 1) st.sc.serveMsgCh <- func(loopNum int) { lastc <- loopNum } return <-lastc } // awaitIdle heuristically awaits for the server conn's select loop to be idle. // The heuristic is that the server connection's serve loop must schedule // 50 times in a row without any channel sends or receives occurring. func (st *serverTester) awaitIdle() { remain := 50 last := st.loopNum() for remain > 0 { n := st.loopNum() if n == last+1 { remain-- } else { remain = 50 } last = n } } func (st *serverTester) Close() { if st.t.Failed() { st.frameReadLogMu.Lock() if st.frameReadLogBuf.Len() > 0 { st.t.Logf("Framer read log:\n%s", st.frameReadLogBuf.String()) } st.frameReadLogMu.Unlock() st.frameWriteLogMu.Lock() if st.frameWriteLogBuf.Len() > 0 { st.t.Logf("Framer write log:\n%s", st.frameWriteLogBuf.String()) } st.frameWriteLogMu.Unlock() // If we failed already (and are likely in a Fatal, // unwindowing), force close the connection, so the // httptest.Server doesn't wait forever for the conn // to close. if st.cc != nil { st.cc.Close() } } st.ts.Close() if st.cc != nil { st.cc.Close() } log.SetOutput(os.Stderr) } // greet initiates the client's HTTP/2 connection into a state where // frames may be sent. func (st *serverTester) greet() { st.greetAndCheckSettings(func(Setting) error { return nil }) } func (st *serverTester) greetAndCheckSettings(checkSetting func(s Setting) error) { st.writePreface() st.writeInitialSettings() st.wantSettings().ForeachSetting(checkSetting) st.writeSettingsAck() // The initial WINDOW_UPDATE and SETTINGS ACK can come in any order. var gotSettingsAck bool var gotWindowUpdate bool for i := 0; i < 2; i++ { f, err := st.readFrame() if err != nil { st.t.Fatal(err) } switch f := f.(type) { case *SettingsFrame: if !f.Header().Flags.Has(FlagSettingsAck) { st.t.Fatal("Settings Frame didn't have ACK set") } gotSettingsAck = true case *WindowUpdateFrame: if f.FrameHeader.StreamID != 0 { st.t.Fatalf("WindowUpdate StreamID = %d; want 0", f.FrameHeader.StreamID) } incr := uint32((&Server{}).initialConnRecvWindowSize() - initialWindowSize) if f.Increment != incr { st.t.Fatalf("WindowUpdate increment = %d; want %d", f.Increment, incr) } gotWindowUpdate = true default: st.t.Fatalf("Wanting a settings ACK or window update, received a %T", f) } } if !gotSettingsAck { st.t.Fatalf("Didn't get a settings ACK") } if !gotWindowUpdate { st.t.Fatalf("Didn't get a window update") } } func (st *serverTester) writePreface() { n, err := st.cc.Write(clientPreface) if err != nil { st.t.Fatalf("Error writing client preface: %v", err) } if n != len(clientPreface) { st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(clientPreface)) } } func (st *serverTester) writeInitialSettings() { if err := st.fr.WriteSettings(); err != nil { st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err) } } func (st *serverTester) writeSettingsAck() { if err := st.fr.WriteSettingsAck(); err != nil { st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err) } } func (st *serverTester) writeHeaders(p HeadersFrameParam) { if err := st.fr.WriteHeaders(p); err != nil { st.t.Fatalf("Error writing HEADERS: %v", err) } } func (st *serverTester) writePriority(id uint32, p PriorityParam) { if err := st.fr.WritePriority(id, p); err != nil { st.t.Fatalf("Error writing PRIORITY: %v", err) } } func (st *serverTester) encodeHeaderField(k, v string) { err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v}) if err != nil { st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) } } // encodeHeaderRaw is the magic-free version of encodeHeader. // It takes 0 or more (k, v) pairs and encodes them. func (st *serverTester) encodeHeaderRaw(headers ...string) []byte { if len(headers)%2 == 1 { panic("odd number of kv args") } st.headerBuf.Reset() for len(headers) > 0 { k, v := headers[0], headers[1] st.encodeHeaderField(k, v) headers = headers[2:] } return st.headerBuf.Bytes() } // encodeHeader encodes headers and returns their HPACK bytes. headers // must contain an even number of key/value pairs. There may be // multiple pairs for keys (e.g. "cookie"). The :method, :path, and // :scheme headers default to GET, / and https. The :authority header // defaults to st.ts.Listener.Addr(). func (st *serverTester) encodeHeader(headers ...string) []byte { if len(headers)%2 == 1 { panic("odd number of kv args") } st.headerBuf.Reset() defaultAuthority := st.ts.Listener.Addr().String() if len(headers) == 0 { // Fast path, mostly for benchmarks, so test code doesn't pollute // profiles when we're looking to improve server allocations. st.encodeHeaderField(":method", "GET") st.encodeHeaderField(":scheme", "https") st.encodeHeaderField(":authority", defaultAuthority) st.encodeHeaderField(":path", "/") return st.headerBuf.Bytes() } if len(headers) == 2 && headers[0] == ":method" { // Another fast path for benchmarks. st.encodeHeaderField(":method", headers[1]) st.encodeHeaderField(":scheme", "https") st.encodeHeaderField(":authority", defaultAuthority) st.encodeHeaderField(":path", "/") return st.headerBuf.Bytes() } pseudoCount := map[string]int{} keys := []string{":method", ":scheme", ":authority", ":path"} vals := map[string][]string{ ":method": {"GET"}, ":scheme": {"https"}, ":authority": {defaultAuthority}, ":path": {"/"}, } for len(headers) > 0 { k, v := headers[0], headers[1] headers = headers[2:] if _, ok := vals[k]; !ok { keys = append(keys, k) } if strings.HasPrefix(k, ":") { pseudoCount[k]++ if pseudoCount[k] == 1 { vals[k] = []string{v} } else { // Allows testing of invalid headers w/ dup pseudo fields. vals[k] = append(vals[k], v) } } else { vals[k] = append(vals[k], v) } } for _, k := range keys { for _, v := range vals[k] { st.encodeHeaderField(k, v) } } return st.headerBuf.Bytes() } // bodylessReq1 writes a HEADERS frames with StreamID 1 and EndStream and EndHeaders set. func (st *serverTester) bodylessReq1(headers ...string) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(headers...), EndStream: true, EndHeaders: true, }) } func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) { if err := st.fr.WriteData(streamID, endStream, data); err != nil { st.t.Fatalf("Error writing DATA: %v", err) } } func (st *serverTester) writeDataPadded(streamID uint32, endStream bool, data, pad []byte) { if err := st.fr.WriteDataPadded(streamID, endStream, data, pad); err != nil { st.t.Fatalf("Error writing DATA: %v", err) } } func readFrameTimeout(fr *Framer, wait time.Duration) (Frame, error) { ch := make(chan interface{}, 1) go func() { fr, err := fr.ReadFrame() if err != nil { ch <- err } else { ch <- fr } }() t := time.NewTimer(wait) select { case v := <-ch: t.Stop() if fr, ok := v.(Frame); ok { return fr, nil } return nil, v.(error) case <-t.C: return nil, errors.New("timeout waiting for frame") } } func (st *serverTester) readFrame() (Frame, error) { return readFrameTimeout(st.fr, 2*time.Second) } func (st *serverTester) wantHeaders() *HeadersFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a HEADERS frame: %v", err) } hf, ok := f.(*HeadersFrame) if !ok { st.t.Fatalf("got a %T; want *HeadersFrame", f) } return hf } func (st *serverTester) wantContinuation() *ContinuationFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a CONTINUATION frame: %v", err) } cf, ok := f.(*ContinuationFrame) if !ok { st.t.Fatalf("got a %T; want *ContinuationFrame", f) } return cf } func (st *serverTester) wantData() *DataFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a DATA frame: %v", err) } df, ok := f.(*DataFrame) if !ok { st.t.Fatalf("got a %T; want *DataFrame", f) } return df } func (st *serverTester) wantSettings() *SettingsFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err) } sf, ok := f.(*SettingsFrame) if !ok { st.t.Fatalf("got a %T; want *SettingsFrame", f) } return sf } func (st *serverTester) wantPing() *PingFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a PING frame: %v", err) } pf, ok := f.(*PingFrame) if !ok { st.t.Fatalf("got a %T; want *PingFrame", f) } return pf } func (st *serverTester) wantGoAway() *GoAwayFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a GOAWAY frame: %v", err) } gf, ok := f.(*GoAwayFrame) if !ok { st.t.Fatalf("got a %T; want *GoAwayFrame", f) } return gf } func (st *serverTester) wantRSTStream(streamID uint32, errCode ErrCode) { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting an RSTStream frame: %v", err) } rs, ok := f.(*RSTStreamFrame) if !ok { st.t.Fatalf("got a %T; want *RSTStreamFrame", f) } if rs.FrameHeader.StreamID != streamID { st.t.Fatalf("RSTStream StreamID = %d; want %d", rs.FrameHeader.StreamID, streamID) } if rs.ErrCode != errCode { st.t.Fatalf("RSTStream ErrCode = %d (%s); want %d (%s)", rs.ErrCode, rs.ErrCode, errCode, errCode) } } func (st *serverTester) wantWindowUpdate(streamID, incr uint32) { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a WINDOW_UPDATE frame: %v", err) } wu, ok := f.(*WindowUpdateFrame) if !ok { st.t.Fatalf("got a %T; want *WindowUpdateFrame", f) } if wu.FrameHeader.StreamID != streamID { st.t.Fatalf("WindowUpdate StreamID = %d; want %d", wu.FrameHeader.StreamID, streamID) } if wu.Increment != incr { st.t.Fatalf("WindowUpdate increment = %d; want %d", wu.Increment, incr) } } func (st *serverTester) wantSettingsAck() { f, err := st.readFrame() if err != nil { st.t.Fatal(err) } sf, ok := f.(*SettingsFrame) if !ok { st.t.Fatalf("Wanting a settings ACK, received a %T", f) } if !sf.Header().Flags.Has(FlagSettingsAck) { st.t.Fatal("Settings Frame didn't have ACK set") } } func (st *serverTester) wantPushPromise() *PushPromiseFrame { f, err := st.readFrame() if err != nil { st.t.Fatal(err) } ppf, ok := f.(*PushPromiseFrame) if !ok { st.t.Fatalf("Wanted PushPromise, received %T", ppf) } return ppf } func TestServer(t *testing.T) { gotReq := make(chan bool, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Foo", "Bar") gotReq <- true }) defer st.Close() covers("3.5", ` The server connection preface consists of a potentially empty SETTINGS frame ([SETTINGS]) that MUST be the first frame the server sends in the HTTP/2 connection. `) st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(), EndStream: true, // no DATA frames EndHeaders: true, }) select { case <-gotReq: case <-time.After(2 * time.Second): t.Error("timeout waiting for request") } } func TestServer_Request_Get(t *testing.T) { testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader("foo-bar", "some-value"), EndStream: true, // no DATA frames EndHeaders: true, }) }, func(r *http.Request) { if r.Method != "GET" { t.Errorf("Method = %q; want GET", r.Method) } if r.URL.Path != "/" { t.Errorf("URL.Path = %q; want /", r.URL.Path) } if r.ContentLength != 0 { t.Errorf("ContentLength = %v; want 0", r.ContentLength) } if r.Close { t.Error("Close = true; want false") } if !strings.Contains(r.RemoteAddr, ":") { t.Errorf("RemoteAddr = %q; want something with a colon", r.RemoteAddr) } if r.Proto != "HTTP/2.0" || r.ProtoMajor != 2 || r.ProtoMinor != 0 { t.Errorf("Proto = %q Major=%v,Minor=%v; want HTTP/2.0", r.Proto, r.ProtoMajor, r.ProtoMinor) } wantHeader := http.Header{ "Foo-Bar": []string{"some-value"}, } if !reflect.DeepEqual(r.Header, wantHeader) { t.Errorf("Header = %#v; want %#v", r.Header, wantHeader) } if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 { t.Errorf("Read = %d, %v; want 0, EOF", n, err) } }) } func TestServer_Request_Get_PathSlashes(t *testing.T) { testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":path", "/%2f/"), EndStream: true, // no DATA frames EndHeaders: true, }) }, func(r *http.Request) { if r.RequestURI != "/%2f/" { t.Errorf("RequestURI = %q; want /%%2f/", r.RequestURI) } if r.URL.Path != "///" { t.Errorf("URL.Path = %q; want ///", r.URL.Path) } }) } // TODO: add a test with EndStream=true on the HEADERS but setting a // Content-Length anyway. Should we just omit it and force it to // zero? func TestServer_Request_Post_NoContentLength_EndStream(t *testing.T) { testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: true, EndHeaders: true, }) }, func(r *http.Request) { if r.Method != "POST" { t.Errorf("Method = %q; want POST", r.Method) } if r.ContentLength != 0 { t.Errorf("ContentLength = %v; want 0", r.ContentLength) } if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 { t.Errorf("Read = %d, %v; want 0, EOF", n, err) } }) } func TestServer_Request_Post_Body_ImmediateEOF(t *testing.T) { testBodyContents(t, -1, "", func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, nil) // just kidding. empty body. }) } func TestServer_Request_Post_Body_OneData(t *testing.T) { const content = "Some content" testBodyContents(t, -1, content, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, []byte(content)) }) } func TestServer_Request_Post_Body_TwoData(t *testing.T) { const content = "Some content" testBodyContents(t, -1, content, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, false, []byte(content[:5])) st.writeData(1, true, []byte(content[5:])) }) } func TestServer_Request_Post_Body_ContentLength_Correct(t *testing.T) { const content = "Some content" testBodyContents(t, int64(len(content)), content, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader( ":method", "POST", "content-length", strconv.Itoa(len(content)), ), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, []byte(content)) }) } func TestServer_Request_Post_Body_ContentLength_TooLarge(t *testing.T) { testBodyContentsFail(t, 3, "request declared a Content-Length of 3 but only wrote 2 bytes", func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader( ":method", "POST", "content-length", "3", ), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, []byte("12")) }) } func TestServer_Request_Post_Body_ContentLength_TooSmall(t *testing.T) { testBodyContentsFail(t, 4, "sender tried to send more than declared Content-Length of 4 bytes", func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader( ":method", "POST", "content-length", "4", ), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, []byte("12345")) }) } func testBodyContents(t *testing.T, wantContentLength int64, wantBody string, write func(st *serverTester)) { testServerRequest(t, write, func(r *http.Request) { if r.Method != "POST" { t.Errorf("Method = %q; want POST", r.Method) } if r.ContentLength != wantContentLength { t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength) } all, err := ioutil.ReadAll(r.Body) if err != nil { t.Fatal(err) } if string(all) != wantBody { t.Errorf("Read = %q; want %q", all, wantBody) } if err := r.Body.Close(); err != nil { t.Fatalf("Close: %v", err) } }) } func testBodyContentsFail(t *testing.T, wantContentLength int64, wantReadError string, write func(st *serverTester)) { testServerRequest(t, write, func(r *http.Request) { if r.Method != "POST" { t.Errorf("Method = %q; want POST", r.Method) } if r.ContentLength != wantContentLength { t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength) } all, err := ioutil.ReadAll(r.Body) if err == nil { t.Fatalf("expected an error (%q) reading from the body. Successfully read %q instead.", wantReadError, all) } if !strings.Contains(err.Error(), wantReadError) { t.Fatalf("Body.Read = %v; want substring %q", err, wantReadError) } if err := r.Body.Close(); err != nil { t.Fatalf("Close: %v", err) } }) } // Using a Host header, instead of :authority func TestServer_Request_Get_Host(t *testing.T) { const host = "example.com" testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":authority", "", "host", host), EndStream: true, EndHeaders: true, }) }, func(r *http.Request) { if r.Host != host { t.Errorf("Host = %q; want %q", r.Host, host) } }) } // Using an :authority pseudo-header, instead of Host func TestServer_Request_Get_Authority(t *testing.T) { const host = "example.com" testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":authority", host), EndStream: true, EndHeaders: true, }) }, func(r *http.Request) { if r.Host != host { t.Errorf("Host = %q; want %q", r.Host, host) } }) } func TestServer_Request_WithContinuation(t *testing.T) { wantHeader := http.Header{ "Foo-One": []string{"value-one"}, "Foo-Two": []string{"value-two"}, "Foo-Three": []string{"value-three"}, } testServerRequest(t, func(st *serverTester) { fullHeaders := st.encodeHeader( "foo-one", "value-one", "foo-two", "value-two", "foo-three", "value-three", ) remain := fullHeaders chunks := 0 for len(remain) > 0 { const maxChunkSize = 5 chunk := remain if len(chunk) > maxChunkSize { chunk = chunk[:maxChunkSize] } remain = remain[len(chunk):] if chunks == 0 { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: chunk, EndStream: true, // no DATA frames EndHeaders: false, // we'll have continuation frames }) } else { err := st.fr.WriteContinuation(1, len(remain) == 0, chunk) if err != nil { t.Fatal(err) } } chunks++ } if chunks < 2 { t.Fatal("too few chunks") } }, func(r *http.Request) { if !reflect.DeepEqual(r.Header, wantHeader) { t.Errorf("Header = %#v; want %#v", r.Header, wantHeader) } }) } // Concatenated cookie headers. ("8.1.2.5 Compressing the Cookie Header Field") func TestServer_Request_CookieConcat(t *testing.T) { const host = "example.com" testServerRequest(t, func(st *serverTester) { st.bodylessReq1( ":authority", host, "cookie", "a=b", "cookie", "c=d", "cookie", "e=f", ) }, func(r *http.Request) { const want = "a=b; c=d; e=f" if got := r.Header.Get("Cookie"); got != want { t.Errorf("Cookie = %q; want %q", got, want) } }) } func TestServer_Request_Reject_CapitalHeader(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("UPPER", "v") }) } func TestServer_Request_Reject_HeaderFieldNameColon(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has:colon", "v") }) } func TestServer_Request_Reject_HeaderFieldNameNULL(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has\x00null", "v") }) } func TestServer_Request_Reject_HeaderFieldNameEmpty(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("", "v") }) } func TestServer_Request_Reject_HeaderFieldValueNewline(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\nnewline") }) } func TestServer_Request_Reject_HeaderFieldValueCR(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\rcarriage") }) } func TestServer_Request_Reject_HeaderFieldValueDEL(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\x7fdel") }) } func TestServer_Request_Reject_Pseudo_Missing_method(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":method", "") }) } func TestServer_Request_Reject_Pseudo_ExactlyOne(t *testing.T) { // 8.1.2.3 Request Pseudo-Header Fields // "All HTTP/2 requests MUST include exactly one valid value" ... testRejectRequest(t, func(st *serverTester) { st.addLogFilter("duplicate pseudo-header") st.bodylessReq1(":method", "GET", ":method", "POST") }) } func TestServer_Request_Reject_Pseudo_AfterRegular(t *testing.T) { // 8.1.2.3 Request Pseudo-Header Fields // "All pseudo-header fields MUST appear in the header block // before regular header fields. Any request or response that // contains a pseudo-header field that appears in a header // block after a regular header field MUST be treated as // malformed (Section 8.1.2.6)." testRejectRequest(t, func(st *serverTester) { st.addLogFilter("pseudo-header after regular header") var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":method", Value: "GET"}) enc.WriteField(hpack.HeaderField{Name: "regular", Value: "foobar"}) enc.WriteField(hpack.HeaderField{Name: ":path", Value: "/"}) enc.WriteField(hpack.HeaderField{Name: ":scheme", Value: "https"}) st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: buf.Bytes(), EndStream: true, EndHeaders: true, }) }) } func TestServer_Request_Reject_Pseudo_Missing_path(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":path", "") }) } func TestServer_Request_Reject_Pseudo_Missing_scheme(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "") }) } func TestServer_Request_Reject_Pseudo_scheme_invalid(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "bogus") }) } func TestServer_Request_Reject_Pseudo_Unknown(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.addLogFilter(`invalid pseudo-header ":unknown_thing"`) st.bodylessReq1(":unknown_thing", "") }) } func testRejectRequest(t *testing.T, send func(*serverTester)) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { t.Error("server request made it to handler; should've been rejected") }) defer st.Close() st.greet() send(st) st.wantRSTStream(1, ErrCodeProtocol) } func testRejectRequestWithProtocolError(t *testing.T, send func(*serverTester)) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { t.Error("server request made it to handler; should've been rejected") }, optQuiet) defer st.Close() st.greet() send(st) gf := st.wantGoAway() if gf.ErrCode != ErrCodeProtocol { t.Errorf("err code = %v; want %v", gf.ErrCode, ErrCodeProtocol) } } // Section 5.1, on idle connections: "Receiving any frame other than // HEADERS or PRIORITY on a stream in this state MUST be treated as a // connection error (Section 5.4.1) of type PROTOCOL_ERROR." func TestRejectFrameOnIdle_WindowUpdate(t *testing.T) { testRejectRequestWithProtocolError(t, func(st *serverTester) { st.fr.WriteWindowUpdate(123, 456) }) } func TestRejectFrameOnIdle_Data(t *testing.T) { testRejectRequestWithProtocolError(t, func(st *serverTester) { st.fr.WriteData(123, true, nil) }) } func TestRejectFrameOnIdle_RSTStream(t *testing.T) { testRejectRequestWithProtocolError(t, func(st *serverTester) { st.fr.WriteRSTStream(123, ErrCodeCancel) }) } func TestServer_Request_Connect(t *testing.T) { testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeaderRaw( ":method", "CONNECT", ":authority", "example.com:123", ), EndStream: true, EndHeaders: true, }) }, func(r *http.Request) { if g, w := r.Method, "CONNECT"; g != w { t.Errorf("Method = %q; want %q", g, w) } if g, w := r.RequestURI, "example.com:123"; g != w { t.Errorf("RequestURI = %q; want %q", g, w) } if g, w := r.URL.Host, "example.com:123"; g != w { t.Errorf("URL.Host = %q; want %q", g, w) } }) } func TestServer_Request_Connect_InvalidPath(t *testing.T) { testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeaderRaw( ":method", "CONNECT", ":authority", "example.com:123", ":path", "/bogus", ), EndStream: true, EndHeaders: true, }) }) } func TestServer_Request_Connect_InvalidScheme(t *testing.T) { testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeaderRaw( ":method", "CONNECT", ":authority", "example.com:123", ":scheme", "https", ), EndStream: true, EndHeaders: true, }) }) } func TestServer_Ping(t *testing.T) { st := newServerTester(t, nil) defer st.Close() st.greet() // Server should ignore this one, since it has ACK set. ackPingData := [8]byte{1, 2, 4, 8, 16, 32, 64, 128} if err := st.fr.WritePing(true, ackPingData); err != nil { t.Fatal(err) } // But the server should reply to this one, since ACK is false. pingData := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} if err := st.fr.WritePing(false, pingData); err != nil { t.Fatal(err) } pf := st.wantPing() if !pf.Flags.Has(FlagPingAck) { t.Error("response ping doesn't have ACK set") } if pf.Data != pingData { t.Errorf("response ping has data %q; want %q", pf.Data, pingData) } } func TestServer_RejectsLargeFrames(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("see golang.org/issue/13434") } st := newServerTester(t, nil) defer st.Close() st.greet() // Write too large of a frame (too large by one byte) // We ignore the return value because it's expected that the server // will only read the first 9 bytes (the headre) and then disconnect. st.fr.WriteRawFrame(0xff, 0, 0, make([]byte, defaultMaxReadFrameSize+1)) gf := st.wantGoAway() if gf.ErrCode != ErrCodeFrameSize { t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFrameSize) } if st.serverLogBuf.Len() != 0 { // Previously we spun here for a bit until the GOAWAY disconnect // timer fired, logging while we fired. t.Errorf("unexpected server output: %.500s\n", st.serverLogBuf.Bytes()) } } func TestServer_Handler_Sends_WindowUpdate(t *testing.T) { puppet := newHandlerPuppet() st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { puppet.act(w, r) }) defer st.Close() defer puppet.done() st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // data coming EndHeaders: true, }) st.writeData(1, false, []byte("abcdef")) puppet.do(readBodyHandler(t, "abc")) st.wantWindowUpdate(0, 3) st.wantWindowUpdate(1, 3) puppet.do(readBodyHandler(t, "def")) st.wantWindowUpdate(0, 3) st.wantWindowUpdate(1, 3) st.writeData(1, true, []byte("ghijkl")) // END_STREAM here puppet.do(readBodyHandler(t, "ghi")) puppet.do(readBodyHandler(t, "jkl")) st.wantWindowUpdate(0, 3) st.wantWindowUpdate(0, 3) // no more stream-level, since END_STREAM } // the version of the TestServer_Handler_Sends_WindowUpdate with padding. // See golang.org/issue/16556 func TestServer_Handler_Sends_WindowUpdate_Padding(t *testing.T) { puppet := newHandlerPuppet() st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { puppet.act(w, r) }) defer st.Close() defer puppet.done() st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, EndHeaders: true, }) st.writeDataPadded(1, false, []byte("abcdef"), []byte{0, 0, 0, 0}) // Expect to immediately get our 5 bytes of padding back for // both the connection and stream (4 bytes of padding + 1 byte of length) st.wantWindowUpdate(0, 5) st.wantWindowUpdate(1, 5) puppet.do(readBodyHandler(t, "abc")) st.wantWindowUpdate(0, 3) st.wantWindowUpdate(1, 3) puppet.do(readBodyHandler(t, "def")) st.wantWindowUpdate(0, 3) st.wantWindowUpdate(1, 3) } func TestServer_Send_GoAway_After_Bogus_WindowUpdate(t *testing.T) { st := newServerTester(t, nil) defer st.Close() st.greet() if err := st.fr.WriteWindowUpdate(0, 1<<31-1); err != nil { t.Fatal(err) } gf := st.wantGoAway() if gf.ErrCode != ErrCodeFlowControl { t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFlowControl) } if gf.LastStreamID != 0 { t.Errorf("GOAWAY last stream ID = %v; want %v", gf.LastStreamID, 0) } } func TestServer_Send_RstStream_After_Bogus_WindowUpdate(t *testing.T) { inHandler := make(chan bool) blockHandler := make(chan bool) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { inHandler <- true <-blockHandler }) defer st.Close() defer close(blockHandler) st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // keep it open EndHeaders: true, }) <-inHandler // Send a bogus window update: if err := st.fr.WriteWindowUpdate(1, 1<<31-1); err != nil { t.Fatal(err) } st.wantRSTStream(1, ErrCodeFlowControl) } // testServerPostUnblock sends a hanging POST with unsent data to handler, // then runs fn once in the handler, and verifies that the error returned from // handler is acceptable. It fails if takes over 5 seconds for handler to exit. func testServerPostUnblock(t *testing.T, handler func(http.ResponseWriter, *http.Request) error, fn func(*serverTester), checkErr func(error), otherHeaders ...string) { inHandler := make(chan bool) errc := make(chan error, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { inHandler <- true errc <- handler(w, r) }) defer st.Close() st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(append([]string{":method", "POST"}, otherHeaders...)...), EndStream: false, // keep it open EndHeaders: true, }) <-inHandler fn(st) select { case err := <-errc: if checkErr != nil { checkErr(err) } case <-time.After(5 * time.Second): t.Fatal("timeout waiting for Handler to return") } } func TestServer_RSTStream_Unblocks_Read(t *testing.T) { testServerPostUnblock(t, func(w http.ResponseWriter, r *http.Request) (err error) { _, err = r.Body.Read(make([]byte, 1)) return }, func(st *serverTester) { if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { t.Fatal(err) } }, func(err error) { want := StreamError{StreamID: 0x1, Code: 0x8} if !reflect.DeepEqual(err, want) { t.Errorf("Read error = %v; want %v", err, want) } }, ) } func TestServer_RSTStream_Unblocks_Header_Write(t *testing.T) { // Run this test a bunch, because it doesn't always // deadlock. But with a bunch, it did. n := 50 if testing.Short() { n = 5 } for i := 0; i < n; i++ { testServer_RSTStream_Unblocks_Header_Write(t) } } func testServer_RSTStream_Unblocks_Header_Write(t *testing.T) { inHandler := make(chan bool, 1) unblockHandler := make(chan bool, 1) headerWritten := make(chan bool, 1) wroteRST := make(chan bool, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { inHandler <- true <-wroteRST w.Header().Set("foo", "bar") w.WriteHeader(200) w.(http.Flusher).Flush() headerWritten <- true <-unblockHandler }) defer st.Close() st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // keep it open EndHeaders: true, }) <-inHandler if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { t.Fatal(err) } wroteRST <- true st.awaitIdle() select { case <-headerWritten: case <-time.After(2 * time.Second): t.Error("timeout waiting for header write") } unblockHandler <- true } func TestServer_DeadConn_Unblocks_Read(t *testing.T) { testServerPostUnblock(t, func(w http.ResponseWriter, r *http.Request) (err error) { _, err = r.Body.Read(make([]byte, 1)) return }, func(st *serverTester) { st.cc.Close() }, func(err error) { if err == nil { t.Error("unexpected nil error from Request.Body.Read") } }, ) } var blockUntilClosed = func(w http.ResponseWriter, r *http.Request) error { <-w.(http.CloseNotifier).CloseNotify() return nil } func TestServer_CloseNotify_After_RSTStream(t *testing.T) { testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { t.Fatal(err) } }, nil) } func TestServer_CloseNotify_After_ConnClose(t *testing.T) { testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { st.cc.Close() }, nil) } // that CloseNotify unblocks after a stream error due to the client's // problem that's unrelated to them explicitly canceling it (which is // TestServer_CloseNotify_After_RSTStream above) func TestServer_CloseNotify_After_StreamError(t *testing.T) { testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { // data longer than declared Content-Length => stream error st.writeData(1, true, []byte("1234")) }, nil, "content-length", "3") } func TestServer_StateTransitions(t *testing.T) { var st *serverTester inHandler := make(chan bool) writeData := make(chan bool) leaveHandler := make(chan bool) st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) { inHandler <- true if st.stream(1) == nil { t.Errorf("nil stream 1 in handler") } if got, want := st.streamState(1), stateOpen; got != want { t.Errorf("in handler, state is %v; want %v", got, want) } writeData <- true if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF { t.Errorf("body read = %d, %v; want 0, EOF", n, err) } if got, want := st.streamState(1), stateHalfClosedRemote; got != want { t.Errorf("in handler, state is %v; want %v", got, want) } <-leaveHandler }) st.greet() if st.stream(1) != nil { t.Fatal("stream 1 should be empty") } if got := st.streamState(1); got != stateIdle { t.Fatalf("stream 1 should be idle; got %v", got) } st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // keep it open EndHeaders: true, }) <-inHandler <-writeData st.writeData(1, true, nil) leaveHandler <- true hf := st.wantHeaders() if !hf.StreamEnded() { t.Fatal("expected END_STREAM flag") } if got, want := st.streamState(1), stateClosed; got != want { t.Errorf("at end, state is %v; want %v", got, want) } if st.stream(1) != nil { t.Fatal("at end, stream 1 should be gone") } } // test HEADERS w/o EndHeaders + another HEADERS (should get rejected) func TestServer_Rejects_HeadersNoEnd_Then_Headers(t *testing.T) { testServerRejectsConn(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: false, }) st.writeHeaders(HeadersFrameParam{ // Not a continuation. StreamID: 3, // different stream. BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) }) } // test HEADERS w/o EndHeaders + PING (should get rejected) func TestServer_Rejects_HeadersNoEnd_Then_Ping(t *testing.T) { testServerRejectsConn(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: false, }) if err := st.fr.WritePing(false, [8]byte{}); err != nil { t.Fatal(err) } }) } // test HEADERS w/ EndHeaders + a continuation HEADERS (should get rejected) func TestServer_Rejects_HeadersEnd_Then_Continuation(t *testing.T) { testServerRejectsConn(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) st.wantHeaders() if err := st.fr.WriteContinuation(1, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil { t.Fatal(err) } }) } // test HEADERS w/o EndHeaders + a continuation HEADERS on wrong stream ID func TestServer_Rejects_HeadersNoEnd_Then_ContinuationWrongStream(t *testing.T) { testServerRejectsConn(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: false, }) if err := st.fr.WriteContinuation(3, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil { t.Fatal(err) } }) } // No HEADERS on stream 0. func TestServer_Rejects_Headers0(t *testing.T) { testServerRejectsConn(t, func(st *serverTester) { st.fr.AllowIllegalWrites = true st.writeHeaders(HeadersFrameParam{ StreamID: 0, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) }) } // No CONTINUATION on stream 0. func TestServer_Rejects_Continuation0(t *testing.T) { testServerRejectsConn(t, func(st *serverTester) { st.fr.AllowIllegalWrites = true if err := st.fr.WriteContinuation(0, true, st.encodeHeader()); err != nil { t.Fatal(err) } }) } // No PRIORITY on stream 0. func TestServer_Rejects_Priority0(t *testing.T) { testServerRejectsConn(t, func(st *serverTester) { st.fr.AllowIllegalWrites = true st.writePriority(0, PriorityParam{StreamDep: 1}) }) } // No HEADERS frame with a self-dependence. func TestServer_Rejects_HeadersSelfDependence(t *testing.T) { testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { st.fr.AllowIllegalWrites = true st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, Priority: PriorityParam{StreamDep: 1}, }) }) } // No PRIORTY frame with a self-dependence. func TestServer_Rejects_PrioritySelfDependence(t *testing.T) { testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { st.fr.AllowIllegalWrites = true st.writePriority(1, PriorityParam{StreamDep: 1}) }) } func TestServer_Rejects_PushPromise(t *testing.T) { testServerRejectsConn(t, func(st *serverTester) { pp := PushPromiseParam{ StreamID: 1, PromiseID: 3, } if err := st.fr.WritePushPromise(pp); err != nil { t.Fatal(err) } }) } // testServerRejectsConn tests that the server hangs up with a GOAWAY // frame and a server close after the client does something // deserving a CONNECTION_ERROR. func testServerRejectsConn(t *testing.T, writeReq func(*serverTester)) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) st.addLogFilter("connection error: PROTOCOL_ERROR") defer st.Close() st.greet() writeReq(st) st.wantGoAway() errc := make(chan error, 1) go func() { fr, err := st.fr.ReadFrame() if err == nil { err = fmt.Errorf("got frame of type %T", fr) } errc <- err }() select { case err := <-errc: if err != io.EOF { t.Errorf("ReadFrame = %v; want io.EOF", err) } case <-time.After(2 * time.Second): t.Error("timeout waiting for disconnect") } } // testServerRejectsStream tests that the server sends a RST_STREAM with the provided // error code after a client sends a bogus request. func testServerRejectsStream(t *testing.T, code ErrCode, writeReq func(*serverTester)) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) defer st.Close() st.greet() writeReq(st) st.wantRSTStream(1, code) } // testServerRequest sets up an idle HTTP/2 connection and lets you // write a single request with writeReq, and then verify that the // *http.Request is built correctly in checkReq. func testServerRequest(t *testing.T, writeReq func(*serverTester), checkReq func(*http.Request)) { gotReq := make(chan bool, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { if r.Body == nil { t.Fatal("nil Body") } checkReq(r) gotReq <- true }) defer st.Close() st.greet() writeReq(st) select { case <-gotReq: case <-time.After(2 * time.Second): t.Error("timeout waiting for request") } } func getSlash(st *serverTester) { st.bodylessReq1() } func TestServer_Response_NoData(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { // Nothing. return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if !hf.StreamEnded() { t.Fatal("want END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } }) } func TestServer_Response_NoData_Header_FooBar(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("Foo-Bar", "some-value") return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if !hf.StreamEnded() { t.Fatal("want END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"foo-bar", "some-value"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", "0"}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } }) } func TestServer_Response_Data_Sniff_DoesntOverride(t *testing.T) { const msg = "this is HTML." testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("Content-Type", "foo/bar") io.WriteString(w, msg) return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("don't want END_STREAM, expecting data") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "foo/bar"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } df := st.wantData() if !df.StreamEnded() { t.Error("expected DATA to have END_STREAM flag") } if got := string(df.Data()); got != msg { t.Errorf("got DATA %q; want %q", got, msg) } }) } func TestServer_Response_TransferEncoding_chunked(t *testing.T) { const msg = "hi" testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("Transfer-Encoding", "chunked") // should be stripped io.WriteString(w, msg) return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } }) } // Header accessed only after the initial write. func TestServer_Response_Data_IgnoreHeaderAfterWrite_After(t *testing.T) { const msg = "this is HTML." testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { io.WriteString(w, msg) w.Header().Set("foo", "should be ignored") return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/html; charset=utf-8"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } }) } // Header accessed before the initial write and later mutated. func TestServer_Response_Data_IgnoreHeaderAfterWrite_Overwrite(t *testing.T) { const msg = "this is HTML." testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("foo", "proper value") io.WriteString(w, msg) w.Header().Set("foo", "should be ignored") return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"foo", "proper value"}, {"content-type", "text/html; charset=utf-8"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } }) } func TestServer_Response_Data_SniffLenType(t *testing.T) { const msg = "this is HTML." testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { io.WriteString(w, msg) return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("don't want END_STREAM, expecting data") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/html; charset=utf-8"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } df := st.wantData() if !df.StreamEnded() { t.Error("expected DATA to have END_STREAM flag") } if got := string(df.Data()); got != msg { t.Errorf("got DATA %q; want %q", got, msg) } }) } func TestServer_Response_Header_Flush_MidWrite(t *testing.T) { const msg = "this is HTML" const msg2 = ", and this is the next chunk" testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { io.WriteString(w, msg) w.(http.Flusher).Flush() io.WriteString(w, msg2) return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/html; charset=utf-8"}, // sniffed // and no content-length } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } { df := st.wantData() if df.StreamEnded() { t.Error("unexpected END_STREAM flag") } if got := string(df.Data()); got != msg { t.Errorf("got DATA %q; want %q", got, msg) } } { df := st.wantData() if !df.StreamEnded() { t.Error("wanted END_STREAM flag on last data chunk") } if got := string(df.Data()); got != msg2 { t.Errorf("got DATA %q; want %q", got, msg2) } } }) } func TestServer_Response_LargeWrite(t *testing.T) { const size = 1 << 20 const maxFrameSize = 16 << 10 testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { n, err := w.Write(bytes.Repeat([]byte("a"), size)) if err != nil { return fmt.Errorf("Write error: %v", err) } if n != size { return fmt.Errorf("wrong size %d from Write", n) } return nil }, func(st *serverTester) { if err := st.fr.WriteSettings( Setting{SettingInitialWindowSize, 0}, Setting{SettingMaxFrameSize, maxFrameSize}, ); err != nil { t.Fatal(err) } st.wantSettingsAck() getSlash(st) // make the single request // Give the handler quota to write: if err := st.fr.WriteWindowUpdate(1, size); err != nil { t.Fatal(err) } // Give the handler quota to write to connection-level // window as well if err := st.fr.WriteWindowUpdate(0, size); err != nil { t.Fatal(err) } hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/plain; charset=utf-8"}, // sniffed // and no content-length } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } var bytes, frames int for { df := st.wantData() bytes += len(df.Data()) frames++ for _, b := range df.Data() { if b != 'a' { t.Fatal("non-'a' byte seen in DATA") } } if df.StreamEnded() { break } } if bytes != size { t.Errorf("Got %d bytes; want %d", bytes, size) } if want := int(size / maxFrameSize); frames < want || frames > want*2 { t.Errorf("Got %d frames; want %d", frames, size) } }) } // Test that the handler can't write more than the client allows func TestServer_Response_LargeWrite_FlowControlled(t *testing.T) { // Make these reads. Before each read, the client adds exactly enough // flow-control to satisfy the read. Numbers chosen arbitrarily. reads := []int{123, 1, 13, 127} size := 0 for _, n := range reads { size += n } testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.(http.Flusher).Flush() n, err := w.Write(bytes.Repeat([]byte("a"), size)) if err != nil { return fmt.Errorf("Write error: %v", err) } if n != size { return fmt.Errorf("wrong size %d from Write", n) } return nil }, func(st *serverTester) { // Set the window size to something explicit for this test. // It's also how much initial data we expect. if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, uint32(reads[0])}); err != nil { t.Fatal(err) } st.wantSettingsAck() getSlash(st) // make the single request hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } df := st.wantData() if got := len(df.Data()); got != reads[0] { t.Fatalf("Initial window size = %d but got DATA with %d bytes", reads[0], got) } for _, quota := range reads[1:] { if err := st.fr.WriteWindowUpdate(1, uint32(quota)); err != nil { t.Fatal(err) } df := st.wantData() if int(quota) != len(df.Data()) { t.Fatalf("read %d bytes after giving %d quota", len(df.Data()), quota) } } }) } // Test that the handler blocked in a Write is unblocked if the server sends a RST_STREAM. func TestServer_Response_RST_Unblocks_LargeWrite(t *testing.T) { const size = 1 << 20 const maxFrameSize = 16 << 10 testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.(http.Flusher).Flush() errc := make(chan error, 1) go func() { _, err := w.Write(bytes.Repeat([]byte("a"), size)) errc <- err }() select { case err := <-errc: if err == nil { return errors.New("unexpected nil error from Write in handler") } return nil case <-time.After(2 * time.Second): return errors.New("timeout waiting for Write in handler") } }, func(st *serverTester) { if err := st.fr.WriteSettings( Setting{SettingInitialWindowSize, 0}, Setting{SettingMaxFrameSize, maxFrameSize}, ); err != nil { t.Fatal(err) } st.wantSettingsAck() getSlash(st) // make the single request hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { t.Fatal(err) } }) } func TestServer_Response_Empty_Data_Not_FlowControlled(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.(http.Flusher).Flush() // Nothing; send empty DATA return nil }, func(st *serverTester) { // Handler gets no data quota: if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, 0}); err != nil { t.Fatal(err) } st.wantSettingsAck() getSlash(st) // make the single request hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } df := st.wantData() if got := len(df.Data()); got != 0 { t.Fatalf("unexpected %d DATA bytes; want 0", got) } if !df.StreamEnded() { t.Fatal("DATA didn't have END_STREAM") } }) } func TestServer_Response_Automatic100Continue(t *testing.T) { const msg = "foo" const reply = "bar" testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { if v := r.Header.Get("Expect"); v != "" { t.Errorf("Expect header = %q; want empty", v) } buf := make([]byte, len(msg)) // This read should trigger the 100-continue being sent. if n, err := io.ReadFull(r.Body, buf); err != nil || n != len(msg) || string(buf) != msg { return fmt.Errorf("ReadFull = %q, %v; want %q, nil", buf[:n], err, msg) } _, err := io.WriteString(w, reply) return err }, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST", "expect", "100-continue"), EndStream: false, EndHeaders: true, }) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "100"}, } if !reflect.DeepEqual(goth, wanth) { t.Fatalf("Got headers %v; want %v", goth, wanth) } // Okay, they sent status 100, so we can send our // gigantic and/or sensitive "foo" payload now. st.writeData(1, true, []byte(msg)) st.wantWindowUpdate(0, uint32(len(msg))) hf = st.wantHeaders() if hf.StreamEnded() { t.Fatal("expected data to follow") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth = st.decodeHeader(hf.HeaderBlockFragment()) wanth = [][2]string{ {":status", "200"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", strconv.Itoa(len(reply))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } df := st.wantData() if string(df.Data()) != reply { t.Errorf("Client read %q; want %q", df.Data(), reply) } if !df.StreamEnded() { t.Errorf("expect data stream end") } }) } func TestServer_HandlerWriteErrorOnDisconnect(t *testing.T) { errc := make(chan error, 1) testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { p := []byte("some data.\n") for { _, err := w.Write(p) if err != nil { errc <- err return nil } } }, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: false, EndHeaders: true, }) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } // Close the connection and wait for the handler to (hopefully) notice. st.cc.Close() select { case <-errc: case <-time.After(5 * time.Second): t.Error("timeout") } }) } func TestServer_Rejects_Too_Many_Streams(t *testing.T) { const testPath = "/some/path" inHandler := make(chan uint32) leaveHandler := make(chan bool) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { id := w.(*responseWriter).rws.stream.id inHandler <- id if id == 1+(defaultMaxStreams+1)*2 && r.URL.Path != testPath { t.Errorf("decoded final path as %q; want %q", r.URL.Path, testPath) } <-leaveHandler }) defer st.Close() st.greet() nextStreamID := uint32(1) streamID := func() uint32 { defer func() { nextStreamID += 2 }() return nextStreamID } sendReq := func(id uint32, headers ...string) { st.writeHeaders(HeadersFrameParam{ StreamID: id, BlockFragment: st.encodeHeader(headers...), EndStream: true, EndHeaders: true, }) } for i := 0; i < defaultMaxStreams; i++ { sendReq(streamID()) <-inHandler } defer func() { for i := 0; i < defaultMaxStreams; i++ { leaveHandler <- true } }() // And this one should cross the limit: // (It's also sent as a CONTINUATION, to verify we still track the decoder context, // even if we're rejecting it) rejectID := streamID() headerBlock := st.encodeHeader(":path", testPath) frag1, frag2 := headerBlock[:3], headerBlock[3:] st.writeHeaders(HeadersFrameParam{ StreamID: rejectID, BlockFragment: frag1, EndStream: true, EndHeaders: false, // CONTINUATION coming }) if err := st.fr.WriteContinuation(rejectID, true, frag2); err != nil { t.Fatal(err) } st.wantRSTStream(rejectID, ErrCodeProtocol) // But let a handler finish: leaveHandler <- true st.wantHeaders() // And now another stream should be able to start: goodID := streamID() sendReq(goodID, ":path", testPath) select { case got := <-inHandler: if got != goodID { t.Errorf("Got stream %d; want %d", got, goodID) } case <-time.After(3 * time.Second): t.Error("timeout waiting for handler") } } // So many response headers that the server needs to use CONTINUATION frames: func TestServer_Response_ManyHeaders_With_Continuation(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { h := w.Header() for i := 0; i < 5000; i++ { h.Set(fmt.Sprintf("x-header-%d", i), fmt.Sprintf("x-value-%d", i)) } return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.HeadersEnded() { t.Fatal("got unwanted END_HEADERS flag") } n := 0 for { n++ cf := st.wantContinuation() if cf.HeadersEnded() { break } } if n < 5 { t.Errorf("Only got %d CONTINUATION frames; expected 5+ (currently 6)", n) } }) } // This previously crashed (reported by Mathieu Lonjaret as observed // while using Camlistore) because we got a DATA frame from the client // after the handler exited and our logic at the time was wrong, // keeping a stream in the map in stateClosed, which tickled an // invariant check later when we tried to remove that stream (via // defer sc.closeAllStreamsOnConnClose) when the serverConn serve loop // ended. func TestServer_NoCrash_HandlerClose_Then_ClientClose(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { // nothing return nil }, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: false, // DATA is coming EndHeaders: true, }) hf := st.wantHeaders() if !hf.HeadersEnded() || !hf.StreamEnded() { t.Fatalf("want END_HEADERS+END_STREAM, got %v", hf) } // Sent when the a Handler closes while a client has // indicated it's still sending DATA: st.wantRSTStream(1, ErrCodeNo) // Now the handler has ended, so it's ended its // stream, but the client hasn't closed its side // (stateClosedLocal). So send more data and verify // it doesn't crash with an internal invariant panic, like // it did before. st.writeData(1, true, []byte("foo")) // Get our flow control bytes back, since the handler didn't get them. st.wantWindowUpdate(0, uint32(len("foo"))) // Sent after a peer sends data anyway (admittedly the // previous RST_STREAM might've still been in-flight), // but they'll get the more friendly 'cancel' code // first. st.wantRSTStream(1, ErrCodeStreamClosed) // Set up a bunch of machinery to record the panic we saw // previously. var ( panMu sync.Mutex panicVal interface{} ) testHookOnPanicMu.Lock() testHookOnPanic = func(sc *serverConn, pv interface{}) bool { panMu.Lock() panicVal = pv panMu.Unlock() return true } testHookOnPanicMu.Unlock() // Now force the serve loop to end, via closing the connection. st.cc.Close() select { case <-st.sc.doneServing: // Loop has exited. panMu.Lock() got := panicVal panMu.Unlock() if got != nil { t.Errorf("Got panic: %v", got) } case <-time.After(5 * time.Second): t.Error("timeout") } }) } func TestServer_Rejects_TLS10(t *testing.T) { testRejectTLS(t, tls.VersionTLS10) } func TestServer_Rejects_TLS11(t *testing.T) { testRejectTLS(t, tls.VersionTLS11) } func testRejectTLS(t *testing.T, max uint16) { st := newServerTester(t, nil, func(c *tls.Config) { c.MaxVersion = max }) defer st.Close() gf := st.wantGoAway() if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want { t.Errorf("Got error code %v; want %v", got, want) } } func TestServer_Rejects_TLSBadCipher(t *testing.T) { st := newServerTester(t, nil, func(c *tls.Config) { // Only list bad ones: c.CipherSuites = []uint16{ tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_RSA_WITH_AES_128_CBC_SHA256, } }) defer st.Close() gf := st.wantGoAway() if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want { t.Errorf("Got error code %v; want %v", got, want) } } func TestServer_Advertises_Common_Cipher(t *testing.T) { const requiredSuite = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 st := newServerTester(t, nil, func(c *tls.Config) { // Have the client only support the one required by the spec. c.CipherSuites = []uint16{requiredSuite} }, func(ts *httptest.Server) { var srv *http.Server = ts.Config // Have the server configured with no specific cipher suites. // This tests that Go's defaults include the required one. srv.TLSConfig = nil }) defer st.Close() st.greet() } func (st *serverTester) onHeaderField(f hpack.HeaderField) { if f.Name == "date" { return } st.decodedHeaders = append(st.decodedHeaders, [2]string{f.Name, f.Value}) } func (st *serverTester) decodeHeader(headerBlock []byte) (pairs [][2]string) { st.decodedHeaders = nil if _, err := st.hpackDec.Write(headerBlock); err != nil { st.t.Fatalf("hpack decoding error: %v", err) } if err := st.hpackDec.Close(); err != nil { st.t.Fatalf("hpack decoding error: %v", err) } return st.decodedHeaders } // testServerResponse sets up an idle HTTP/2 connection. The client function should // write a single request that must be handled by the handler. This waits up to 5s // for client to return, then up to an additional 2s for the handler to return. func testServerResponse(t testing.TB, handler func(http.ResponseWriter, *http.Request) error, client func(*serverTester), ) { errc := make(chan error, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { if r.Body == nil { t.Fatal("nil Body") } errc <- handler(w, r) }) defer st.Close() donec := make(chan bool) go func() { defer close(donec) st.greet() client(st) }() select { case <-donec: case <-time.After(5 * time.Second): t.Fatal("timeout in client") } select { case err := <-errc: if err != nil { t.Fatalf("Error in handler: %v", err) } case <-time.After(2 * time.Second): t.Fatal("timeout in handler") } } // readBodyHandler returns an http Handler func that reads len(want) // bytes from r.Body and fails t if the contents read were not // the value of want. func readBodyHandler(t *testing.T, want string) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { buf := make([]byte, len(want)) _, err := io.ReadFull(r.Body, buf) if err != nil { t.Error(err) return } if string(buf) != want { t.Errorf("read %q; want %q", buf, want) } } } // TestServerWithCurl currently fails, hence the LenientCipherSuites test. See: // https://github.com/tatsuhiro-t/nghttp2/issues/140 & // http://sourceforge.net/p/curl/bugs/1472/ func TestServerWithCurl(t *testing.T) { testServerWithCurl(t, false) } func TestServerWithCurl_LenientCipherSuites(t *testing.T) { testServerWithCurl(t, true) } func testServerWithCurl(t *testing.T, permitProhibitedCipherSuites bool) { if runtime.GOOS != "linux" { t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway") } if testing.Short() { t.Skip("skipping curl test in short mode") } requireCurl(t) var gotConn int32 testHookOnConn = func() { atomic.StoreInt32(&gotConn, 1) } const msg = "Hello from curl!\n" ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Foo", "Bar") w.Header().Set("Client-Proto", r.Proto) io.WriteString(w, msg) })) ConfigureServer(ts.Config, &Server{ PermitProhibitedCipherSuites: permitProhibitedCipherSuites, }) ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config ts.StartTLS() defer ts.Close() t.Logf("Running test server for curl to hit at: %s", ts.URL) container := curl(t, "--silent", "--http2", "--insecure", "-v", ts.URL) defer kill(container) resc := make(chan interface{}, 1) go func() { res, err := dockerLogs(container) if err != nil { resc <- err } else { resc <- res } }() select { case res := <-resc: if err, ok := res.(error); ok { t.Fatal(err) } body := string(res.([]byte)) // Search for both "key: value" and "key:value", since curl changed their format // Our Dockerfile contains the latest version (no space), but just in case people // didn't rebuild, check both. if !strings.Contains(body, "foo: Bar") && !strings.Contains(body, "foo:Bar") { t.Errorf("didn't see foo: Bar header") t.Logf("Got: %s", body) } if !strings.Contains(body, "client-proto: HTTP/2") && !strings.Contains(body, "client-proto:HTTP/2") { t.Errorf("didn't see client-proto: HTTP/2 header") t.Logf("Got: %s", res) } if !strings.Contains(string(res.([]byte)), msg) { t.Errorf("didn't see %q content", msg) t.Logf("Got: %s", res) } case <-time.After(3 * time.Second): t.Errorf("timeout waiting for curl") } if atomic.LoadInt32(&gotConn) == 0 { t.Error("never saw an http2 connection") } } var doh2load = flag.Bool("h2load", false, "Run h2load test") func TestServerWithH2Load(t *testing.T) { if !*doh2load { t.Skip("Skipping without --h2load flag.") } if runtime.GOOS != "linux" { t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway") } requireH2load(t) msg := strings.Repeat("Hello, h2load!\n", 5000) ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, msg) w.(http.Flusher).Flush() io.WriteString(w, msg) })) ts.StartTLS() defer ts.Close() cmd := exec.Command("docker", "run", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl", "-n100000", "-c100", "-m100", ts.URL) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { t.Fatal(err) } } // Issue 12843 func TestServerDoS_MaxHeaderListSize(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) defer st.Close() // shake hands frameSize := defaultMaxReadFrameSize var advHeaderListSize *uint32 st.greetAndCheckSettings(func(s Setting) error { switch s.ID { case SettingMaxFrameSize: if s.Val < minMaxFrameSize { frameSize = minMaxFrameSize } else if s.Val > maxFrameSize { frameSize = maxFrameSize } else { frameSize = int(s.Val) } case SettingMaxHeaderListSize: advHeaderListSize = &s.Val } return nil }) if advHeaderListSize == nil { t.Errorf("server didn't advertise a max header list size") } else if *advHeaderListSize == 0 { t.Errorf("server advertised a max header list size of 0") } st.encodeHeaderField(":method", "GET") st.encodeHeaderField(":path", "/") st.encodeHeaderField(":scheme", "https") cookie := strings.Repeat("*", 4058) st.encodeHeaderField("cookie", cookie) st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.headerBuf.Bytes(), EndStream: true, EndHeaders: false, }) // Capture the short encoding of a duplicate ~4K cookie, now // that we've already sent it once. st.headerBuf.Reset() st.encodeHeaderField("cookie", cookie) // Now send 1MB of it. const size = 1 << 20 b := bytes.Repeat(st.headerBuf.Bytes(), size/st.headerBuf.Len()) for len(b) > 0 { chunk := b if len(chunk) > frameSize { chunk = chunk[:frameSize] } b = b[len(chunk):] st.fr.WriteContinuation(1, len(b) == 0, chunk) } h := st.wantHeaders() if !h.HeadersEnded() { t.Fatalf("Got HEADERS without END_HEADERS set: %v", h) } headers := st.decodeHeader(h.HeaderBlockFragment()) want := [][2]string{ {":status", "431"}, {"content-type", "text/html; charset=utf-8"}, {"content-length", "63"}, } if !reflect.DeepEqual(headers, want) { t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) } } func TestCompressionErrorOnWrite(t *testing.T) { const maxStrLen = 8 << 10 var serverConfig *http.Server st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { // No response body. }, func(ts *httptest.Server) { serverConfig = ts.Config serverConfig.MaxHeaderBytes = maxStrLen }) st.addLogFilter("connection error: COMPRESSION_ERROR") defer st.Close() st.greet() maxAllowed := st.sc.framer.maxHeaderStringLen() // Crank this up, now that we have a conn connected with the // hpack.Decoder's max string length set has been initialized // from the earlier low ~8K value. We want this higher so don't // hit the max header list size. We only want to test hitting // the max string size. serverConfig.MaxHeaderBytes = 1 << 20 // First a request with a header that's exactly the max allowed size // for the hpack compression. It's still too long for the header list // size, so we'll get the 431 error, but that keeps the compression // context still valid. hbf := st.encodeHeader("foo", strings.Repeat("a", maxAllowed)) st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: hbf, EndStream: true, EndHeaders: true, }) h := st.wantHeaders() if !h.HeadersEnded() { t.Fatalf("Got HEADERS without END_HEADERS set: %v", h) } headers := st.decodeHeader(h.HeaderBlockFragment()) want := [][2]string{ {":status", "431"}, {"content-type", "text/html; charset=utf-8"}, {"content-length", "63"}, } if !reflect.DeepEqual(headers, want) { t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) } df := st.wantData() if !strings.Contains(string(df.Data()), "HTTP Error 431") { t.Errorf("Unexpected data body: %q", df.Data()) } if !df.StreamEnded() { t.Fatalf("expect data stream end") } // And now send one that's just one byte too big. hbf = st.encodeHeader("bar", strings.Repeat("b", maxAllowed+1)) st.writeHeaders(HeadersFrameParam{ StreamID: 3, BlockFragment: hbf, EndStream: true, EndHeaders: true, }) ga := st.wantGoAway() if ga.ErrCode != ErrCodeCompression { t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode) } } func TestCompressionErrorOnClose(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { // No response body. }) st.addLogFilter("connection error: COMPRESSION_ERROR") defer st.Close() st.greet() hbf := st.encodeHeader("foo", "bar") hbf = hbf[:len(hbf)-1] // truncate one byte from the end, so hpack.Decoder.Close fails. st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: hbf, EndStream: true, EndHeaders: true, }) ga := st.wantGoAway() if ga.ErrCode != ErrCodeCompression { t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode) } } // test that a server handler can read trailers from a client func TestServerReadsTrailers(t *testing.T) { const testBody = "some test body" writeReq := func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader("trailer", "Foo, Bar", "trailer", "Baz"), EndStream: false, EndHeaders: true, }) st.writeData(1, false, []byte(testBody)) st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeaderRaw( "foo", "foov", "bar", "barv", "baz", "bazv", "surprise", "wasn't declared; shouldn't show up", ), EndStream: true, EndHeaders: true, }) } checkReq := func(r *http.Request) { wantTrailer := http.Header{ "Foo": nil, "Bar": nil, "Baz": nil, } if !reflect.DeepEqual(r.Trailer, wantTrailer) { t.Errorf("initial Trailer = %v; want %v", r.Trailer, wantTrailer) } slurp, err := ioutil.ReadAll(r.Body) if string(slurp) != testBody { t.Errorf("read body %q; want %q", slurp, testBody) } if err != nil { t.Fatalf("Body slurp: %v", err) } wantTrailerAfter := http.Header{ "Foo": {"foov"}, "Bar": {"barv"}, "Baz": {"bazv"}, } if !reflect.DeepEqual(r.Trailer, wantTrailerAfter) { t.Errorf("final Trailer = %v; want %v", r.Trailer, wantTrailerAfter) } } testServerRequest(t, writeReq, checkReq) } // test that a server handler can send trailers func TestServerWritesTrailers_WithFlush(t *testing.T) { testServerWritesTrailers(t, true) } func TestServerWritesTrailers_WithoutFlush(t *testing.T) { testServerWritesTrailers(t, false) } func testServerWritesTrailers(t *testing.T, withFlush bool) { // See https://httpwg.github.io/specs/rfc7540.html#rfc.section.8.1.3 testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B") w.Header().Add("Trailer", "Server-Trailer-C") w.Header().Add("Trailer", "Transfer-Encoding, Content-Length, Trailer") // filtered // Regular headers: w.Header().Set("Foo", "Bar") w.Header().Set("Content-Length", "5") // len("Hello") io.WriteString(w, "Hello") if withFlush { w.(http.Flusher).Flush() } w.Header().Set("Server-Trailer-A", "valuea") w.Header().Set("Server-Trailer-C", "valuec") // skipping B // After a flush, random keys like Server-Surprise shouldn't show up: w.Header().Set("Server-Surpise", "surprise! this isn't predeclared!") // But we do permit promoting keys to trailers after a // flush if they start with the magic // otherwise-invalid "Trailer:" prefix: w.Header().Set("Trailer:Post-Header-Trailer", "hi1") w.Header().Set("Trailer:post-header-trailer2", "hi2") w.Header().Set("Trailer:Range", "invalid") w.Header().Set("Trailer:Foo\x01Bogus", "invalid") w.Header().Set("Transfer-Encoding", "should not be included; Forbidden by RFC 2616 14.40") w.Header().Set("Content-Length", "should not be included; Forbidden by RFC 2616 14.40") w.Header().Set("Trailer", "should not be included; Forbidden by RFC 2616 14.40") return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("response HEADERS had END_STREAM") } if !hf.HeadersEnded() { t.Fatal("response HEADERS didn't have END_HEADERS") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"foo", "Bar"}, {"trailer", "Server-Trailer-A, Server-Trailer-B"}, {"trailer", "Server-Trailer-C"}, {"trailer", "Transfer-Encoding, Content-Length, Trailer"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", "5"}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) } df := st.wantData() if string(df.Data()) != "Hello" { t.Fatalf("Client read %q; want Hello", df.Data()) } if df.StreamEnded() { t.Fatalf("data frame had STREAM_ENDED") } tf := st.wantHeaders() // for the trailers if !tf.StreamEnded() { t.Fatalf("trailers HEADERS lacked END_STREAM") } if !tf.HeadersEnded() { t.Fatalf("trailers HEADERS lacked END_HEADERS") } wanth = [][2]string{ {"post-header-trailer", "hi1"}, {"post-header-trailer2", "hi2"}, {"server-trailer-a", "valuea"}, {"server-trailer-c", "valuec"}, } goth = st.decodeHeader(tf.HeaderBlockFragment()) if !reflect.DeepEqual(goth, wanth) { t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) } }) } // validate transmitted header field names & values // golang.org/issue/14048 func TestServerDoesntWriteInvalidHeaders(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Add("OK1", "x") w.Header().Add("Bad:Colon", "x") // colon (non-token byte) in key w.Header().Add("Bad1\x00", "x") // null in key w.Header().Add("Bad2", "x\x00y") // null in value return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if !hf.StreamEnded() { t.Error("response HEADERS lacked END_STREAM") } if !hf.HeadersEnded() { t.Fatal("response HEADERS didn't have END_HEADERS") } goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"ok1", "x"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", "0"}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) } }) } func BenchmarkServerGets(b *testing.B) { defer disableGoroutineTracking()() b.ReportAllocs() const msg = "Hello, world" st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, msg) }) defer st.Close() st.greet() // Give the server quota to reply. (plus it has the the 64KB) if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { b.Fatal(err) } for i := 0; i < b.N; i++ { id := 1 + uint32(i)*2 st.writeHeaders(HeadersFrameParam{ StreamID: id, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) st.wantHeaders() df := st.wantData() if !df.StreamEnded() { b.Fatalf("DATA didn't have END_STREAM; got %v", df) } } } func BenchmarkServerPosts(b *testing.B) { defer disableGoroutineTracking()() b.ReportAllocs() const msg = "Hello, world" st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { // Consume the (empty) body from th peer before replying, otherwise // the server will sometimes (depending on scheduling) send the peer a // a RST_STREAM with the CANCEL error code. if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil { b.Errorf("Copy error; got %v, %v; want 0, nil", n, err) } io.WriteString(w, msg) }) defer st.Close() st.greet() // Give the server quota to reply. (plus it has the the 64KB) if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { b.Fatal(err) } for i := 0; i < b.N; i++ { id := 1 + uint32(i)*2 st.writeHeaders(HeadersFrameParam{ StreamID: id, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, EndHeaders: true, }) st.writeData(id, true, nil) st.wantHeaders() df := st.wantData() if !df.StreamEnded() { b.Fatalf("DATA didn't have END_STREAM; got %v", df) } } } // Send a stream of messages from server to client in separate data frames. // Brings up performance issues seen in long streams. // Created to show problem in go issue #18502 func BenchmarkServerToClientStreamDefaultOptions(b *testing.B) { benchmarkServerToClientStream(b) } // Justification for Change-Id: Iad93420ef6c3918f54249d867098f1dadfa324d8 // Expect to see memory/alloc reduction by opting in to Frame reuse with the Framer. func BenchmarkServerToClientStreamReuseFrames(b *testing.B) { benchmarkServerToClientStream(b, optFramerReuseFrames) } func benchmarkServerToClientStream(b *testing.B, newServerOpts ...interface{}) { defer disableGoroutineTracking()() b.ReportAllocs() const msgLen = 1 // default window size const windowSize = 1<<16 - 1 // next message to send from the server and for the client to expect nextMsg := func(i int) []byte { msg := make([]byte, msgLen) msg[0] = byte(i) if len(msg) != msgLen { panic("invalid test setup msg length") } return msg } st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { // Consume the (empty) body from th peer before replying, otherwise // the server will sometimes (depending on scheduling) send the peer a // a RST_STREAM with the CANCEL error code. if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil { b.Errorf("Copy error; got %v, %v; want 0, nil", n, err) } for i := 0; i < b.N; i += 1 { w.Write(nextMsg(i)) w.(http.Flusher).Flush() } }, newServerOpts...) defer st.Close() st.greet() const id = uint32(1) st.writeHeaders(HeadersFrameParam{ StreamID: id, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, EndHeaders: true, }) st.writeData(id, true, nil) st.wantHeaders() var pendingWindowUpdate = uint32(0) for i := 0; i < b.N; i += 1 { expected := nextMsg(i) df := st.wantData() if bytes.Compare(expected, df.data) != 0 { b.Fatalf("Bad message received; want %v; got %v", expected, df.data) } // try to send infrequent but large window updates so they don't overwhelm the test pendingWindowUpdate += uint32(len(df.data)) if pendingWindowUpdate >= windowSize/2 { if err := st.fr.WriteWindowUpdate(0, pendingWindowUpdate); err != nil { b.Fatal(err) } if err := st.fr.WriteWindowUpdate(id, pendingWindowUpdate); err != nil { b.Fatal(err) } pendingWindowUpdate = 0 } } df := st.wantData() if !df.StreamEnded() { b.Fatalf("DATA didn't have END_STREAM; got %v", df) } } // go-fuzz bug, originally reported at https://github.com/bradfitz/http2/issues/53 // Verify we don't hang. func TestIssue53(t *testing.T) { const data = "PRI * HTTP/2.0\r\n\r\nSM" + "\r\n\r\n\x00\x00\x00\x01\ainfinfin\ad" s := &http.Server{ ErrorLog: log.New(io.MultiWriter(stderrv(), twriter{t: t}), "", log.LstdFlags), Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("hello")) }), } s2 := &Server{ MaxReadFrameSize: 1 << 16, PermitProhibitedCipherSuites: true, } c := &issue53Conn{[]byte(data), false, false} s2.ServeConn(c, &ServeConnOpts{BaseConfig: s}) if !c.closed { t.Fatal("connection is not closed") } } type issue53Conn struct { data []byte closed bool written bool } func (c *issue53Conn) Read(b []byte) (n int, err error) { if len(c.data) == 0 { return 0, io.EOF } n = copy(b, c.data) c.data = c.data[n:] return } func (c *issue53Conn) Write(b []byte) (n int, err error) { c.written = true return len(b), nil } func (c *issue53Conn) Close() error { c.closed = true return nil } func (c *issue53Conn) LocalAddr() net.Addr { return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706} } func (c *issue53Conn) RemoteAddr() net.Addr { return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706} } func (c *issue53Conn) SetDeadline(t time.Time) error { return nil } func (c *issue53Conn) SetReadDeadline(t time.Time) error { return nil } func (c *issue53Conn) SetWriteDeadline(t time.Time) error { return nil } // golang.org/issue/12895 func TestConfigureServer(t *testing.T) { tests := []struct { name string tlsConfig *tls.Config wantErr string }{ { name: "empty server", }, { name: "just the required cipher suite", tlsConfig: &tls.Config{ CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, }, }, { name: "missing required cipher suite", tlsConfig: &tls.Config{ CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384}, }, wantErr: "is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", }, { name: "required after bad", tlsConfig: &tls.Config{ CipherSuites: []uint16{tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, }, wantErr: "contains an HTTP/2-approved cipher suite (0xc02f), but it comes after", }, { name: "bad after required", tlsConfig: &tls.Config{ CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_RC4_128_SHA}, }, }, } for _, tt := range tests { srv := &http.Server{TLSConfig: tt.tlsConfig} err := ConfigureServer(srv, nil) if (err != nil) != (tt.wantErr != "") { if tt.wantErr != "" { t.Errorf("%s: success, but want error", tt.name) } else { t.Errorf("%s: unexpected error: %v", tt.name, err) } } if err != nil && tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr) { t.Errorf("%s: err = %v; want substring %q", tt.name, err, tt.wantErr) } if err == nil && !srv.TLSConfig.PreferServerCipherSuites { t.Errorf("%s: PreferServerCipherSuite is false; want true", tt.name) } } } func TestServerRejectHeadWithBody(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { // No response body. }) defer st.Close() st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "HEAD"), EndStream: false, // what we're testing, a bogus HEAD request with body EndHeaders: true, }) st.wantRSTStream(1, ErrCodeProtocol) } func TestServerNoAutoContentLengthOnHead(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { // No response body. (or smaller than one frame) }) defer st.Close() st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "HEAD"), EndStream: true, EndHeaders: true, }) h := st.wantHeaders() headers := st.decodeHeader(h.HeaderBlockFragment()) want := [][2]string{ {":status", "200"}, {"content-type", "text/plain; charset=utf-8"}, } if !reflect.DeepEqual(headers, want) { t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) } } // golang.org/issue/13495 func TestServerNoDuplicateContentType(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.Header()["Content-Type"] = []string{""} fmt.Fprintf(w, "hi") }) defer st.Close() st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) h := st.wantHeaders() headers := st.decodeHeader(h.HeaderBlockFragment()) want := [][2]string{ {":status", "200"}, {"content-type", ""}, {"content-length", "41"}, } if !reflect.DeepEqual(headers, want) { t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) } } func disableGoroutineTracking() (restore func()) { old := DebugGoroutines DebugGoroutines = false return func() { DebugGoroutines = old } } func BenchmarkServer_GetRequest(b *testing.B) { defer disableGoroutineTracking()() b.ReportAllocs() const msg = "Hello, world." st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { n, err := io.Copy(ioutil.Discard, r.Body) if err != nil || n > 0 { b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err) } io.WriteString(w, msg) }) defer st.Close() st.greet() // Give the server quota to reply. (plus it has the the 64KB) if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { b.Fatal(err) } hbf := st.encodeHeader(":method", "GET") for i := 0; i < b.N; i++ { streamID := uint32(1 + 2*i) st.writeHeaders(HeadersFrameParam{ StreamID: streamID, BlockFragment: hbf, EndStream: true, EndHeaders: true, }) st.wantHeaders() st.wantData() } } func BenchmarkServer_PostRequest(b *testing.B) { defer disableGoroutineTracking()() b.ReportAllocs() const msg = "Hello, world." st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { n, err := io.Copy(ioutil.Discard, r.Body) if err != nil || n > 0 { b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err) } io.WriteString(w, msg) }) defer st.Close() st.greet() // Give the server quota to reply. (plus it has the the 64KB) if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { b.Fatal(err) } hbf := st.encodeHeader(":method", "POST") for i := 0; i < b.N; i++ { streamID := uint32(1 + 2*i) st.writeHeaders(HeadersFrameParam{ StreamID: streamID, BlockFragment: hbf, EndStream: false, EndHeaders: true, }) st.writeData(streamID, true, nil) st.wantHeaders() st.wantData() } } type connStateConn struct { net.Conn cs tls.ConnectionState } func (c connStateConn) ConnectionState() tls.ConnectionState { return c.cs } // golang.org/issue/12737 -- handle any net.Conn, not just // *tls.Conn. func TestServerHandleCustomConn(t *testing.T) { var s Server c1, c2 := net.Pipe() clientDone := make(chan struct{}) handlerDone := make(chan struct{}) var req *http.Request go func() { defer close(clientDone) defer c2.Close() fr := NewFramer(c2, c2) io.WriteString(c2, ClientPreface) fr.WriteSettings() fr.WriteSettingsAck() f, err := fr.ReadFrame() if err != nil { t.Error(err) return } if sf, ok := f.(*SettingsFrame); !ok || sf.IsAck() { t.Errorf("Got %v; want non-ACK SettingsFrame", summarizeFrame(f)) return } f, err = fr.ReadFrame() if err != nil { t.Error(err) return } if sf, ok := f.(*SettingsFrame); !ok || !sf.IsAck() { t.Errorf("Got %v; want ACK SettingsFrame", summarizeFrame(f)) return } var henc hpackEncoder fr.WriteHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: henc.encodeHeaderRaw(t, ":method", "GET", ":path", "/", ":scheme", "https", ":authority", "foo.com"), EndStream: true, EndHeaders: true, }) go io.Copy(ioutil.Discard, c2) <-handlerDone }() const testString = "my custom ConnectionState" fakeConnState := tls.ConnectionState{ ServerName: testString, Version: tls.VersionTLS12, CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, } go s.ServeConn(connStateConn{c1, fakeConnState}, &ServeConnOpts{ BaseConfig: &http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer close(handlerDone) req = r }), }}) select { case <-clientDone: case <-time.After(5 * time.Second): t.Fatal("timeout waiting for handler") } if req.TLS == nil { t.Fatalf("Request.TLS is nil. Got: %#v", req) } if req.TLS.ServerName != testString { t.Fatalf("Request.TLS = %+v; want ServerName of %q", req.TLS, testString) } } // golang.org/issue/14214 func TestServer_Rejects_ConnHeaders(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { t.Error("should not get to Handler") }) defer st.Close() st.greet() st.bodylessReq1("connection", "foo") hf := st.wantHeaders() goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "400"}, {"content-type", "text/plain; charset=utf-8"}, {"x-content-type-options", "nosniff"}, {"content-length", "51"}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } } type hpackEncoder struct { enc *hpack.Encoder buf bytes.Buffer } func (he *hpackEncoder) encodeHeaderRaw(t *testing.T, headers ...string) []byte { if len(headers)%2 == 1 { panic("odd number of kv args") } he.buf.Reset() if he.enc == nil { he.enc = hpack.NewEncoder(&he.buf) } for len(headers) > 0 { k, v := headers[0], headers[1] err := he.enc.WriteField(hpack.HeaderField{Name: k, Value: v}) if err != nil { t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) } headers = headers[2:] } return he.buf.Bytes() } func TestCheckValidHTTP2Request(t *testing.T) { tests := []struct { h http.Header want error }{ { h: http.Header{"Te": {"trailers"}}, want: nil, }, { h: http.Header{"Te": {"trailers", "bogus"}}, want: errors.New(`request header "TE" may only be "trailers" in HTTP/2`), }, { h: http.Header{"Foo": {""}}, want: nil, }, { h: http.Header{"Connection": {""}}, want: errors.New(`request header "Connection" is not valid in HTTP/2`), }, { h: http.Header{"Proxy-Connection": {""}}, want: errors.New(`request header "Proxy-Connection" is not valid in HTTP/2`), }, { h: http.Header{"Keep-Alive": {""}}, want: errors.New(`request header "Keep-Alive" is not valid in HTTP/2`), }, { h: http.Header{"Upgrade": {""}}, want: errors.New(`request header "Upgrade" is not valid in HTTP/2`), }, } for i, tt := range tests { got := checkValidHTTP2RequestHeaders(tt.h) if !reflect.DeepEqual(got, tt.want) { t.Errorf("%d. checkValidHTTP2Request = %v; want %v", i, got, tt.want) } } } // golang.org/issue/14030 func TestExpect100ContinueAfterHandlerWrites(t *testing.T) { const msg = "Hello" const msg2 = "World" doRead := make(chan bool, 1) defer close(doRead) // fallback cleanup st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, msg) w.(http.Flusher).Flush() // Do a read, which might force a 100-continue status to be sent. <-doRead r.Body.Read(make([]byte, 10)) io.WriteString(w, msg2) }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() req, _ := http.NewRequest("POST", st.ts.URL, io.LimitReader(neverEnding('A'), 2<<20)) req.Header.Set("Expect", "100-continue") res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } defer res.Body.Close() buf := make([]byte, len(msg)) if _, err := io.ReadFull(res.Body, buf); err != nil { t.Fatal(err) } if string(buf) != msg { t.Fatalf("msg = %q; want %q", buf, msg) } doRead <- true if _, err := io.ReadFull(res.Body, buf); err != nil { t.Fatal(err) } if string(buf) != msg2 { t.Fatalf("second msg = %q; want %q", buf, msg2) } } type funcReader func([]byte) (n int, err error) func (f funcReader) Read(p []byte) (n int, err error) { return f(p) } // golang.org/issue/16481 -- return flow control when streams close with unread data. // (The Server version of the bug. See also TestUnreadFlowControlReturned_Transport) func TestUnreadFlowControlReturned_Server(t *testing.T) { unblock := make(chan bool, 1) defer close(unblock) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { // Don't read the 16KB request body. Wait until the client's // done sending it and then return. This should cause the Server // to then return those 16KB of flow control to the client. <-unblock }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() // This previously hung on the 4th iteration. for i := 0; i < 6; i++ { body := io.MultiReader( io.LimitReader(neverEnding('A'), 16<<10), funcReader(func([]byte) (n int, err error) { unblock <- true return 0, io.EOF }), ) req, _ := http.NewRequest("POST", st.ts.URL, body) res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } res.Body.Close() } } func TestServerIdleTimeout(t *testing.T) { if testing.Short() { t.Skip("skipping in short mode") } st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { }, func(h2s *Server) { h2s.IdleTimeout = 500 * time.Millisecond }) defer st.Close() st.greet() ga := st.wantGoAway() if ga.ErrCode != ErrCodeNo { t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) } } func TestServerIdleTimeout_AfterRequest(t *testing.T) { if testing.Short() { t.Skip("skipping in short mode") } const timeout = 250 * time.Millisecond st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { time.Sleep(timeout * 2) }, func(h2s *Server) { h2s.IdleTimeout = timeout }) defer st.Close() st.greet() // Send a request which takes twice the timeout. Verifies the // idle timeout doesn't fire while we're in a request: st.bodylessReq1() st.wantHeaders() // But the idle timeout should be rearmed after the request // is done: ga := st.wantGoAway() if ga.ErrCode != ErrCodeNo { t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) } } // grpc-go closes the Request.Body currently with a Read. // Verify that it doesn't race. // See https://github.com/grpc/grpc-go/pull/938 func TestRequestBodyReadCloseRace(t *testing.T) { for i := 0; i < 100; i++ { body := &requestBody{ pipe: &pipe{ b: new(bytes.Buffer), }, } body.pipe.CloseWithError(io.EOF) done := make(chan bool, 1) buf := make([]byte, 10) go func() { time.Sleep(1 * time.Millisecond) body.Close() done <- true }() body.Read(buf) <-done } } func TestIssue20704Race(t *testing.T) { if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" { t.Skip("skipping in short mode") } const ( itemSize = 1 << 10 itemCount = 100 ) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { for i := 0; i < itemCount; i++ { _, err := w.Write(make([]byte, itemSize)) if err != nil { return } } }, optOnlyServer) defer st.Close() tr := &Transport{TLSClientConfig: tlsConfigInsecure} defer tr.CloseIdleConnections() cl := &http.Client{Transport: tr} for i := 0; i < 1000; i++ { resp, err := cl.Get(st.ts.URL) if err != nil { t.Fatal(err) } // Force a RST stream to the server by closing without // reading the body: resp.Body.Close() } } lxd-2.0.11/dist/src/golang.org/x/net/http2/server_push_test.go0000644061062106075000000003444113172163402025315 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.8 package http2 import ( "errors" "fmt" "io" "io/ioutil" "net/http" "reflect" "strconv" "sync" "testing" "time" ) func TestServer_Push_Success(t *testing.T) { const ( mainBody = "index page" pushedBody = "pushed page" userAgent = "testagent" cookie = "testcookie" ) var stURL string checkPromisedReq := func(r *http.Request, wantMethod string, wantH http.Header) error { if got, want := r.Method, wantMethod; got != want { return fmt.Errorf("promised Req.Method=%q, want %q", got, want) } if got, want := r.Header, wantH; !reflect.DeepEqual(got, want) { return fmt.Errorf("promised Req.Header=%q, want %q", got, want) } if got, want := "https://"+r.Host, stURL; got != want { return fmt.Errorf("promised Req.Host=%q, want %q", got, want) } if r.Body == nil { return fmt.Errorf("nil Body") } if buf, err := ioutil.ReadAll(r.Body); err != nil || len(buf) != 0 { return fmt.Errorf("ReadAll(Body)=%q,%v, want '',nil", buf, err) } return nil } errc := make(chan error, 3) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { switch r.URL.RequestURI() { case "/": // Push "/pushed?get" as a GET request, using an absolute URL. opt := &http.PushOptions{ Header: http.Header{ "User-Agent": {userAgent}, }, } if err := w.(http.Pusher).Push(stURL+"/pushed?get", opt); err != nil { errc <- fmt.Errorf("error pushing /pushed?get: %v", err) return } // Push "/pushed?head" as a HEAD request, using a path. opt = &http.PushOptions{ Method: "HEAD", Header: http.Header{ "User-Agent": {userAgent}, "Cookie": {cookie}, }, } if err := w.(http.Pusher).Push("/pushed?head", opt); err != nil { errc <- fmt.Errorf("error pushing /pushed?head: %v", err) return } w.Header().Set("Content-Type", "text/html") w.Header().Set("Content-Length", strconv.Itoa(len(mainBody))) w.WriteHeader(200) io.WriteString(w, mainBody) errc <- nil case "/pushed?get": wantH := http.Header{} wantH.Set("User-Agent", userAgent) if err := checkPromisedReq(r, "GET", wantH); err != nil { errc <- fmt.Errorf("/pushed?get: %v", err) return } w.Header().Set("Content-Type", "text/html") w.Header().Set("Content-Length", strconv.Itoa(len(pushedBody))) w.WriteHeader(200) io.WriteString(w, pushedBody) errc <- nil case "/pushed?head": wantH := http.Header{} wantH.Set("User-Agent", userAgent) wantH.Set("Cookie", cookie) if err := checkPromisedReq(r, "HEAD", wantH); err != nil { errc <- fmt.Errorf("/pushed?head: %v", err) return } w.WriteHeader(204) errc <- nil default: errc <- fmt.Errorf("unknown RequestURL %q", r.URL.RequestURI()) } }) stURL = st.ts.URL // Send one request, which should push two responses. st.greet() getSlash(st) for k := 0; k < 3; k++ { select { case <-time.After(2 * time.Second): t.Errorf("timeout waiting for handler %d to finish", k) case err := <-errc: if err != nil { t.Fatal(err) } } } checkPushPromise := func(f Frame, promiseID uint32, wantH [][2]string) error { pp, ok := f.(*PushPromiseFrame) if !ok { return fmt.Errorf("got a %T; want *PushPromiseFrame", f) } if !pp.HeadersEnded() { return fmt.Errorf("want END_HEADERS flag in PushPromiseFrame") } if got, want := pp.PromiseID, promiseID; got != want { return fmt.Errorf("got PromiseID %v; want %v", got, want) } gotH := st.decodeHeader(pp.HeaderBlockFragment()) if !reflect.DeepEqual(gotH, wantH) { return fmt.Errorf("got promised headers %v; want %v", gotH, wantH) } return nil } checkHeaders := func(f Frame, wantH [][2]string) error { hf, ok := f.(*HeadersFrame) if !ok { return fmt.Errorf("got a %T; want *HeadersFrame", f) } gotH := st.decodeHeader(hf.HeaderBlockFragment()) if !reflect.DeepEqual(gotH, wantH) { return fmt.Errorf("got response headers %v; want %v", gotH, wantH) } return nil } checkData := func(f Frame, wantData string) error { df, ok := f.(*DataFrame) if !ok { return fmt.Errorf("got a %T; want *DataFrame", f) } if gotData := string(df.Data()); gotData != wantData { return fmt.Errorf("got response data %q; want %q", gotData, wantData) } return nil } // Stream 1 has 2 PUSH_PROMISE + HEADERS + DATA // Stream 2 has HEADERS + DATA // Stream 4 has HEADERS expected := map[uint32][]func(Frame) error{ 1: { func(f Frame) error { return checkPushPromise(f, 2, [][2]string{ {":method", "GET"}, {":scheme", "https"}, {":authority", st.ts.Listener.Addr().String()}, {":path", "/pushed?get"}, {"user-agent", userAgent}, }) }, func(f Frame) error { return checkPushPromise(f, 4, [][2]string{ {":method", "HEAD"}, {":scheme", "https"}, {":authority", st.ts.Listener.Addr().String()}, {":path", "/pushed?head"}, {"cookie", cookie}, {"user-agent", userAgent}, }) }, func(f Frame) error { return checkHeaders(f, [][2]string{ {":status", "200"}, {"content-type", "text/html"}, {"content-length", strconv.Itoa(len(mainBody))}, }) }, func(f Frame) error { return checkData(f, mainBody) }, }, 2: { func(f Frame) error { return checkHeaders(f, [][2]string{ {":status", "200"}, {"content-type", "text/html"}, {"content-length", strconv.Itoa(len(pushedBody))}, }) }, func(f Frame) error { return checkData(f, pushedBody) }, }, 4: { func(f Frame) error { return checkHeaders(f, [][2]string{ {":status", "204"}, }) }, }, } consumed := map[uint32]int{} for k := 0; len(expected) > 0; k++ { f, err := st.readFrame() if err != nil { for id, left := range expected { t.Errorf("stream %d: missing %d frames", id, len(left)) } t.Fatalf("readFrame %d: %v", k, err) } id := f.Header().StreamID label := fmt.Sprintf("stream %d, frame %d", id, consumed[id]) if len(expected[id]) == 0 { t.Fatalf("%s: unexpected frame %#+v", label, f) } check := expected[id][0] expected[id] = expected[id][1:] if len(expected[id]) == 0 { delete(expected, id) } if err := check(f); err != nil { t.Fatalf("%s: %v", label, err) } consumed[id]++ } } func TestServer_Push_SuccessNoRace(t *testing.T) { // Regression test for issue #18326. Ensure the request handler can mutate // pushed request headers without racing with the PUSH_PROMISE write. errc := make(chan error, 2) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { switch r.URL.RequestURI() { case "/": opt := &http.PushOptions{ Header: http.Header{"User-Agent": {"testagent"}}, } if err := w.(http.Pusher).Push("/pushed", opt); err != nil { errc <- fmt.Errorf("error pushing: %v", err) return } w.WriteHeader(200) errc <- nil case "/pushed": // Update request header, ensure there is no race. r.Header.Set("User-Agent", "newagent") r.Header.Set("Cookie", "cookie") w.WriteHeader(200) errc <- nil default: errc <- fmt.Errorf("unknown RequestURL %q", r.URL.RequestURI()) } }) // Send one request, which should push one response. st.greet() getSlash(st) for k := 0; k < 2; k++ { select { case <-time.After(2 * time.Second): t.Errorf("timeout waiting for handler %d to finish", k) case err := <-errc: if err != nil { t.Fatal(err) } } } } func TestServer_Push_RejectRecursivePush(t *testing.T) { // Expect two requests, but might get three if there's a bug and the second push succeeds. errc := make(chan error, 3) handler := func(w http.ResponseWriter, r *http.Request) error { baseURL := "https://" + r.Host switch r.URL.Path { case "/": if err := w.(http.Pusher).Push(baseURL+"/push1", nil); err != nil { return fmt.Errorf("first Push()=%v, want nil", err) } return nil case "/push1": if got, want := w.(http.Pusher).Push(baseURL+"/push2", nil), ErrRecursivePush; got != want { return fmt.Errorf("Push()=%v, want %v", got, want) } return nil default: return fmt.Errorf("unexpected path: %q", r.URL.Path) } } st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { errc <- handler(w, r) }) defer st.Close() st.greet() getSlash(st) if err := <-errc; err != nil { t.Errorf("First request failed: %v", err) } if err := <-errc; err != nil { t.Errorf("Second request failed: %v", err) } } func testServer_Push_RejectSingleRequest(t *testing.T, doPush func(http.Pusher, *http.Request) error, settings ...Setting) { // Expect one request, but might get two if there's a bug and the push succeeds. errc := make(chan error, 2) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { errc <- doPush(w.(http.Pusher), r) }) defer st.Close() st.greet() if err := st.fr.WriteSettings(settings...); err != nil { st.t.Fatalf("WriteSettings: %v", err) } st.wantSettingsAck() getSlash(st) if err := <-errc; err != nil { t.Error(err) } // Should not get a PUSH_PROMISE frame. hf := st.wantHeaders() if !hf.StreamEnded() { t.Error("stream should end after headers") } } func TestServer_Push_RejectIfDisabled(t *testing.T) { testServer_Push_RejectSingleRequest(t, func(p http.Pusher, r *http.Request) error { if got, want := p.Push("https://"+r.Host+"/pushed", nil), http.ErrNotSupported; got != want { return fmt.Errorf("Push()=%v, want %v", got, want) } return nil }, Setting{SettingEnablePush, 0}) } func TestServer_Push_RejectWhenNoConcurrentStreams(t *testing.T) { testServer_Push_RejectSingleRequest(t, func(p http.Pusher, r *http.Request) error { if got, want := p.Push("https://"+r.Host+"/pushed", nil), ErrPushLimitReached; got != want { return fmt.Errorf("Push()=%v, want %v", got, want) } return nil }, Setting{SettingMaxConcurrentStreams, 0}) } func TestServer_Push_RejectWrongScheme(t *testing.T) { testServer_Push_RejectSingleRequest(t, func(p http.Pusher, r *http.Request) error { if err := p.Push("http://"+r.Host+"/pushed", nil); err == nil { return errors.New("Push() should have failed (push target URL is http)") } return nil }) } func TestServer_Push_RejectMissingHost(t *testing.T) { testServer_Push_RejectSingleRequest(t, func(p http.Pusher, r *http.Request) error { if err := p.Push("https:pushed", nil); err == nil { return errors.New("Push() should have failed (push target URL missing host)") } return nil }) } func TestServer_Push_RejectRelativePath(t *testing.T) { testServer_Push_RejectSingleRequest(t, func(p http.Pusher, r *http.Request) error { if err := p.Push("../test", nil); err == nil { return errors.New("Push() should have failed (push target is a relative path)") } return nil }) } func TestServer_Push_RejectForbiddenMethod(t *testing.T) { testServer_Push_RejectSingleRequest(t, func(p http.Pusher, r *http.Request) error { if err := p.Push("https://"+r.Host+"/pushed", &http.PushOptions{Method: "POST"}); err == nil { return errors.New("Push() should have failed (cannot promise a POST)") } return nil }) } func TestServer_Push_RejectForbiddenHeader(t *testing.T) { testServer_Push_RejectSingleRequest(t, func(p http.Pusher, r *http.Request) error { header := http.Header{ "Content-Length": {"10"}, "Content-Encoding": {"gzip"}, "Trailer": {"Foo"}, "Te": {"trailers"}, "Host": {"test.com"}, ":authority": {"test.com"}, } if err := p.Push("https://"+r.Host+"/pushed", &http.PushOptions{Header: header}); err == nil { return errors.New("Push() should have failed (forbidden headers)") } return nil }) } func TestServer_Push_StateTransitions(t *testing.T) { const body = "foo" gotPromise := make(chan bool) finishedPush := make(chan bool) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { switch r.URL.RequestURI() { case "/": if err := w.(http.Pusher).Push("/pushed", nil); err != nil { t.Errorf("Push error: %v", err) } // Don't finish this request until the push finishes so we don't // nondeterministically interleave output frames with the push. <-finishedPush case "/pushed": <-gotPromise } w.Header().Set("Content-Type", "text/html") w.Header().Set("Content-Length", strconv.Itoa(len(body))) w.WriteHeader(200) io.WriteString(w, body) }) defer st.Close() st.greet() if st.stream(2) != nil { t.Fatal("stream 2 should be empty") } if got, want := st.streamState(2), stateIdle; got != want { t.Fatalf("streamState(2)=%v, want %v", got, want) } getSlash(st) // After the PUSH_PROMISE is sent, the stream should be stateHalfClosedRemote. st.wantPushPromise() if got, want := st.streamState(2), stateHalfClosedRemote; got != want { t.Fatalf("streamState(2)=%v, want %v", got, want) } // We stall the HTTP handler for "/pushed" until the above check. If we don't // stall the handler, then the handler might write HEADERS and DATA and finish // the stream before we check st.streamState(2) -- should that happen, we'll // see stateClosed and fail the above check. close(gotPromise) st.wantHeaders() if df := st.wantData(); !df.StreamEnded() { t.Fatal("expected END_STREAM flag on DATA") } if got, want := st.streamState(2), stateClosed; got != want { t.Fatalf("streamState(2)=%v, want %v", got, want) } close(finishedPush) } func TestServer_Push_RejectAfterGoAway(t *testing.T) { var readyOnce sync.Once ready := make(chan struct{}) errc := make(chan error, 2) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { select { case <-ready: case <-time.After(5 * time.Second): errc <- fmt.Errorf("timeout waiting for GOAWAY to be processed") } if got, want := w.(http.Pusher).Push("https://"+r.Host+"/pushed", nil), http.ErrNotSupported; got != want { errc <- fmt.Errorf("Push()=%v, want %v", got, want) } errc <- nil }) defer st.Close() st.greet() getSlash(st) // Send GOAWAY and wait for it to be processed. st.fr.WriteGoAway(1, ErrCodeNo, nil) go func() { for { select { case <-ready: return default: } st.sc.serveMsgCh <- func(loopNum int) { if !st.sc.pushEnabled { readyOnce.Do(func() { close(ready) }) } } } }() if err := <-errc; err != nil { t.Error(err) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/server.go0000644061062106075000000025425713172163402023230 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // TODO: turn off the serve goroutine when idle, so // an idle conn only has the readFrames goroutine active. (which could // also be optimized probably to pin less memory in crypto/tls). This // would involve tracking when the serve goroutine is active (atomic // int32 read/CAS probably?) and starting it up when frames arrive, // and shutting it down when all handlers exit. the occasional PING // packets could use time.AfterFunc to call sc.wakeStartServeLoop() // (which is a no-op if already running) and then queue the PING write // as normal. The serve loop would then exit in most cases (if no // Handlers running) and not be woken up again until the PING packet // returns. // TODO (maybe): add a mechanism for Handlers to going into // half-closed-local mode (rw.(io.Closer) test?) but not exit their // handler, and continue to be able to read from the // Request.Body. This would be a somewhat semantic change from HTTP/1 // (or at least what we expose in net/http), so I'd probably want to // add it there too. For now, this package says that returning from // the Handler ServeHTTP function means you're both done reading and // done writing, without a way to stop just one or the other. package http2 import ( "bufio" "bytes" "crypto/tls" "errors" "fmt" "io" "log" "math" "net" "net/http" "net/textproto" "net/url" "os" "reflect" "runtime" "strconv" "strings" "sync" "time" "golang.org/x/net/http2/hpack" ) const ( prefaceTimeout = 10 * time.Second firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway handlerChunkWriteSize = 4 << 10 defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to? ) var ( errClientDisconnected = errors.New("client disconnected") errClosedBody = errors.New("body closed by handler") errHandlerComplete = errors.New("http2: request body closed due to handler exiting") errStreamClosed = errors.New("http2: stream closed") ) var responseWriterStatePool = sync.Pool{ New: func() interface{} { rws := &responseWriterState{} rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize) return rws }, } // Test hooks. var ( testHookOnConn func() testHookGetServerConn func(*serverConn) testHookOnPanicMu *sync.Mutex // nil except in tests testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool) ) // Server is an HTTP/2 server. type Server struct { // MaxHandlers limits the number of http.Handler ServeHTTP goroutines // which may run at a time over all connections. // Negative or zero no limit. // TODO: implement MaxHandlers int // MaxConcurrentStreams optionally specifies the number of // concurrent streams that each client may have open at a // time. This is unrelated to the number of http.Handler goroutines // which may be active globally, which is MaxHandlers. // If zero, MaxConcurrentStreams defaults to at least 100, per // the HTTP/2 spec's recommendations. MaxConcurrentStreams uint32 // MaxReadFrameSize optionally specifies the largest frame // this server is willing to read. A valid value is between // 16k and 16M, inclusive. If zero or otherwise invalid, a // default value is used. MaxReadFrameSize uint32 // PermitProhibitedCipherSuites, if true, permits the use of // cipher suites prohibited by the HTTP/2 spec. PermitProhibitedCipherSuites bool // IdleTimeout specifies how long until idle clients should be // closed with a GOAWAY frame. PING frames are not considered // activity for the purposes of IdleTimeout. IdleTimeout time.Duration // MaxUploadBufferPerConnection is the size of the initial flow // control window for each connections. The HTTP/2 spec does not // allow this to be smaller than 65535 or larger than 2^32-1. // If the value is outside this range, a default value will be // used instead. MaxUploadBufferPerConnection int32 // MaxUploadBufferPerStream is the size of the initial flow control // window for each stream. The HTTP/2 spec does not allow this to // be larger than 2^32-1. If the value is zero or larger than the // maximum, a default value will be used instead. MaxUploadBufferPerStream int32 // NewWriteScheduler constructs a write scheduler for a connection. // If nil, a default scheduler is chosen. NewWriteScheduler func() WriteScheduler // Internal state. This is a pointer (rather than embedded directly) // so that we don't embed a Mutex in this struct, which will make the // struct non-copyable, which might break some callers. state *serverInternalState } func (s *Server) initialConnRecvWindowSize() int32 { if s.MaxUploadBufferPerConnection > initialWindowSize { return s.MaxUploadBufferPerConnection } return 1 << 20 } func (s *Server) initialStreamRecvWindowSize() int32 { if s.MaxUploadBufferPerStream > 0 { return s.MaxUploadBufferPerStream } return 1 << 20 } func (s *Server) maxReadFrameSize() uint32 { if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize { return v } return defaultMaxReadFrameSize } func (s *Server) maxConcurrentStreams() uint32 { if v := s.MaxConcurrentStreams; v > 0 { return v } return defaultMaxStreams } type serverInternalState struct { mu sync.Mutex activeConns map[*serverConn]struct{} } func (s *serverInternalState) registerConn(sc *serverConn) { if s == nil { return // if the Server was used without calling ConfigureServer } s.mu.Lock() s.activeConns[sc] = struct{}{} s.mu.Unlock() } func (s *serverInternalState) unregisterConn(sc *serverConn) { if s == nil { return // if the Server was used without calling ConfigureServer } s.mu.Lock() delete(s.activeConns, sc) s.mu.Unlock() } func (s *serverInternalState) startGracefulShutdown() { if s == nil { return // if the Server was used without calling ConfigureServer } s.mu.Lock() for sc := range s.activeConns { sc.startGracefulShutdown() } s.mu.Unlock() } // ConfigureServer adds HTTP/2 support to a net/http Server. // // The configuration conf may be nil. // // ConfigureServer must be called before s begins serving. func ConfigureServer(s *http.Server, conf *Server) error { if s == nil { panic("nil *http.Server") } if conf == nil { conf = new(Server) } conf.state = &serverInternalState{activeConns: make(map[*serverConn]struct{})} if err := configureServer18(s, conf); err != nil { return err } if err := configureServer19(s, conf); err != nil { return err } if s.TLSConfig == nil { s.TLSConfig = new(tls.Config) } else if s.TLSConfig.CipherSuites != nil { // If they already provided a CipherSuite list, return // an error if it has a bad order or is missing // ECDHE_RSA_WITH_AES_128_GCM_SHA256. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 haveRequired := false sawBad := false for i, cs := range s.TLSConfig.CipherSuites { if cs == requiredCipher { haveRequired = true } if isBadCipher(cs) { sawBad = true } else if sawBad { return fmt.Errorf("http2: TLSConfig.CipherSuites index %d contains an HTTP/2-approved cipher suite (%#04x), but it comes after unapproved cipher suites. With this configuration, clients that don't support previous, approved cipher suites may be given an unapproved one and reject the connection.", i, cs) } } if !haveRequired { return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256") } } // Note: not setting MinVersion to tls.VersionTLS12, // as we don't want to interfere with HTTP/1.1 traffic // on the user's server. We enforce TLS 1.2 later once // we accept a connection. Ideally this should be done // during next-proto selection, but using TLS <1.2 with // HTTP/2 is still the client's bug. s.TLSConfig.PreferServerCipherSuites = true haveNPN := false for _, p := range s.TLSConfig.NextProtos { if p == NextProtoTLS { haveNPN = true break } } if !haveNPN { s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS) } if s.TLSNextProto == nil { s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} } protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) { if testHookOnConn != nil { testHookOnConn() } conf.ServeConn(c, &ServeConnOpts{ Handler: h, BaseConfig: hs, }) } s.TLSNextProto[NextProtoTLS] = protoHandler return nil } // ServeConnOpts are options for the Server.ServeConn method. type ServeConnOpts struct { // BaseConfig optionally sets the base configuration // for values. If nil, defaults are used. BaseConfig *http.Server // Handler specifies which handler to use for processing // requests. If nil, BaseConfig.Handler is used. If BaseConfig // or BaseConfig.Handler is nil, http.DefaultServeMux is used. Handler http.Handler } func (o *ServeConnOpts) baseConfig() *http.Server { if o != nil && o.BaseConfig != nil { return o.BaseConfig } return new(http.Server) } func (o *ServeConnOpts) handler() http.Handler { if o != nil { if o.Handler != nil { return o.Handler } if o.BaseConfig != nil && o.BaseConfig.Handler != nil { return o.BaseConfig.Handler } } return http.DefaultServeMux } // ServeConn serves HTTP/2 requests on the provided connection and // blocks until the connection is no longer readable. // // ServeConn starts speaking HTTP/2 assuming that c has not had any // reads or writes. It writes its initial settings frame and expects // to be able to read the preface and settings frame from the // client. If c has a ConnectionState method like a *tls.Conn, the // ConnectionState is used to verify the TLS ciphersuite and to set // the Request.TLS field in Handlers. // // ServeConn does not support h2c by itself. Any h2c support must be // implemented in terms of providing a suitably-behaving net.Conn. // // The opts parameter is optional. If nil, default values are used. func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { baseCtx, cancel := serverConnBaseContext(c, opts) defer cancel() sc := &serverConn{ srv: s, hs: opts.baseConfig(), conn: c, baseCtx: baseCtx, remoteAddrStr: c.RemoteAddr().String(), bw: newBufferedWriter(c), handler: opts.handler(), streams: make(map[uint32]*stream), readFrameCh: make(chan readFrameResult), wantWriteFrameCh: make(chan FrameWriteRequest, 8), serveMsgCh: make(chan interface{}, 8), wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way doneServing: make(chan struct{}), clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value" advMaxStreams: s.maxConcurrentStreams(), initialStreamSendWindowSize: initialWindowSize, maxFrameSize: initialMaxFrameSize, headerTableSize: initialHeaderTableSize, serveG: newGoroutineLock(), pushEnabled: true, } s.state.registerConn(sc) defer s.state.unregisterConn(sc) // The net/http package sets the write deadline from the // http.Server.WriteTimeout during the TLS handshake, but then // passes the connection off to us with the deadline already set. // Write deadlines are set per stream in serverConn.newStream. // Disarm the net.Conn write deadline here. if sc.hs.WriteTimeout != 0 { sc.conn.SetWriteDeadline(time.Time{}) } if s.NewWriteScheduler != nil { sc.writeSched = s.NewWriteScheduler() } else { sc.writeSched = NewRandomWriteScheduler() } // These start at the RFC-specified defaults. If there is a higher // configured value for inflow, that will be updated when we send a // WINDOW_UPDATE shortly after sending SETTINGS. sc.flow.add(initialWindowSize) sc.inflow.add(initialWindowSize) sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf) fr := NewFramer(sc.bw, c) fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) fr.MaxHeaderListSize = sc.maxHeaderListSize() fr.SetMaxReadFrameSize(s.maxReadFrameSize()) sc.framer = fr if tc, ok := c.(connectionStater); ok { sc.tlsState = new(tls.ConnectionState) *sc.tlsState = tc.ConnectionState() // 9.2 Use of TLS Features // An implementation of HTTP/2 over TLS MUST use TLS // 1.2 or higher with the restrictions on feature set // and cipher suite described in this section. Due to // implementation limitations, it might not be // possible to fail TLS negotiation. An endpoint MUST // immediately terminate an HTTP/2 connection that // does not meet the TLS requirements described in // this section with a connection error (Section // 5.4.1) of type INADEQUATE_SECURITY. if sc.tlsState.Version < tls.VersionTLS12 { sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low") return } if sc.tlsState.ServerName == "" { // Client must use SNI, but we don't enforce that anymore, // since it was causing problems when connecting to bare IP // addresses during development. // // TODO: optionally enforce? Or enforce at the time we receive // a new request, and verify the the ServerName matches the :authority? // But that precludes proxy situations, perhaps. // // So for now, do nothing here again. } if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) { // "Endpoints MAY choose to generate a connection error // (Section 5.4.1) of type INADEQUATE_SECURITY if one of // the prohibited cipher suites are negotiated." // // We choose that. In my opinion, the spec is weak // here. It also says both parties must support at least // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no // excuses here. If we really must, we could allow an // "AllowInsecureWeakCiphers" option on the server later. // Let's see how it plays out first. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite)) return } } if hook := testHookGetServerConn; hook != nil { hook(sc) } sc.serve() } func (sc *serverConn) rejectConn(err ErrCode, debug string) { sc.vlogf("http2: server rejecting conn: %v, %s", err, debug) // ignoring errors. hanging up anyway. sc.framer.WriteGoAway(0, err, []byte(debug)) sc.bw.Flush() sc.conn.Close() } type serverConn struct { // Immutable: srv *Server hs *http.Server conn net.Conn bw *bufferedWriter // writing to conn handler http.Handler baseCtx contextContext framer *Framer doneServing chan struct{} // closed when serverConn.serve ends readFrameCh chan readFrameResult // written by serverConn.readFrames wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes bodyReadCh chan bodyReadMsg // from handlers -> serve serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop flow flow // conn-wide (not stream-specific) outbound flow control inflow flow // conn-wide inbound flow control tlsState *tls.ConnectionState // shared by all handlers, like net/http remoteAddrStr string writeSched WriteScheduler // Everything following is owned by the serve loop; use serveG.check(): serveG goroutineLock // used to verify funcs are on serve() pushEnabled bool sawFirstSettings bool // got the initial SETTINGS frame after the preface needToSendSettingsAck bool unackedSettings int // how many SETTINGS have we sent without ACKs? clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit) advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client curClientStreams uint32 // number of open streams initiated by the client curPushedStreams uint32 // number of open streams initiated by server push maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes streams map[uint32]*stream initialStreamSendWindowSize int32 maxFrameSize int32 headerTableSize uint32 peerMaxHeaderListSize uint32 // zero means unknown (default) canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case writingFrame bool // started writing a frame (on serve goroutine or separate) writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh needsFrameFlush bool // last frame write wasn't a flush inGoAway bool // we've started to or sent GOAWAY inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop needToSendGoAway bool // we need to schedule a GOAWAY frame write goAwayCode ErrCode shutdownTimer *time.Timer // nil until used idleTimer *time.Timer // nil if unused // Owned by the writeFrameAsync goroutine: headerWriteBuf bytes.Buffer hpackEncoder *hpack.Encoder // Used by startGracefulShutdown. shutdownOnce sync.Once } func (sc *serverConn) maxHeaderListSize() uint32 { n := sc.hs.MaxHeaderBytes if n <= 0 { n = http.DefaultMaxHeaderBytes } // http2's count is in a slightly different unit and includes 32 bytes per pair. // So, take the net/http.Server value and pad it up a bit, assuming 10 headers. const perFieldOverhead = 32 // per http2 spec const typicalHeaders = 10 // conservative return uint32(n + typicalHeaders*perFieldOverhead) } func (sc *serverConn) curOpenStreams() uint32 { sc.serveG.check() return sc.curClientStreams + sc.curPushedStreams } // stream represents a stream. This is the minimal metadata needed by // the serve goroutine. Most of the actual stream state is owned by // the http.Handler's goroutine in the responseWriter. Because the // responseWriter's responseWriterState is recycled at the end of a // handler, this struct intentionally has no pointer to the // *responseWriter{,State} itself, as the Handler ending nils out the // responseWriter's state field. type stream struct { // immutable: sc *serverConn id uint32 body *pipe // non-nil if expecting DATA frames cw closeWaiter // closed wait stream transitions to closed state ctx contextContext cancelCtx func() // owned by serverConn's serve loop: bodyBytes int64 // body bytes seen so far declBodyBytes int64 // or -1 if undeclared flow flow // limits writing from Handler to client inflow flow // what the client is allowed to POST/etc to us parent *stream // or nil numTrailerValues int64 weight uint8 state streamState resetQueued bool // RST_STREAM queued for write; set by sc.resetStream gotTrailerHeader bool // HEADER frame for trailers was seen wroteHeaders bool // whether we wrote headers (not status 100) writeDeadline *time.Timer // nil if unused trailer http.Header // accumulated trailers reqTrailer http.Header // handler's Request.Trailer } func (sc *serverConn) Framer() *Framer { return sc.framer } func (sc *serverConn) CloseConn() error { return sc.conn.Close() } func (sc *serverConn) Flush() error { return sc.bw.Flush() } func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) { return sc.hpackEncoder, &sc.headerWriteBuf } func (sc *serverConn) state(streamID uint32) (streamState, *stream) { sc.serveG.check() // http://tools.ietf.org/html/rfc7540#section-5.1 if st, ok := sc.streams[streamID]; ok { return st.state, st } // "The first use of a new stream identifier implicitly closes all // streams in the "idle" state that might have been initiated by // that peer with a lower-valued stream identifier. For example, if // a client sends a HEADERS frame on stream 7 without ever sending a // frame on stream 5, then stream 5 transitions to the "closed" // state when the first frame for stream 7 is sent or received." if streamID%2 == 1 { if streamID <= sc.maxClientStreamID { return stateClosed, nil } } else { if streamID <= sc.maxPushPromiseID { return stateClosed, nil } } return stateIdle, nil } // setConnState calls the net/http ConnState hook for this connection, if configured. // Note that the net/http package does StateNew and StateClosed for us. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections. func (sc *serverConn) setConnState(state http.ConnState) { if sc.hs.ConnState != nil { sc.hs.ConnState(sc.conn, state) } } func (sc *serverConn) vlogf(format string, args ...interface{}) { if VerboseLogs { sc.logf(format, args...) } } func (sc *serverConn) logf(format string, args ...interface{}) { if lg := sc.hs.ErrorLog; lg != nil { lg.Printf(format, args...) } else { log.Printf(format, args...) } } // errno returns v's underlying uintptr, else 0. // // TODO: remove this helper function once http2 can use build // tags. See comment in isClosedConnError. func errno(v error) uintptr { if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr { return uintptr(rv.Uint()) } return 0 } // isClosedConnError reports whether err is an error from use of a closed // network connection. func isClosedConnError(err error) bool { if err == nil { return false } // TODO: remove this string search and be more like the Windows // case below. That might involve modifying the standard library // to return better error types. str := err.Error() if strings.Contains(str, "use of closed network connection") { return true } // TODO(bradfitz): x/tools/cmd/bundle doesn't really support // build tags, so I can't make an http2_windows.go file with // Windows-specific stuff. Fix that and move this, once we // have a way to bundle this into std's net/http somehow. if runtime.GOOS == "windows" { if oe, ok := err.(*net.OpError); ok && oe.Op == "read" { if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" { const WSAECONNABORTED = 10053 const WSAECONNRESET = 10054 if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED { return true } } } } return false } func (sc *serverConn) condlogf(err error, format string, args ...interface{}) { if err == nil { return } if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) { // Boring, expected errors. sc.vlogf(format, args...) } else { sc.logf(format, args...) } } func (sc *serverConn) canonicalHeader(v string) string { sc.serveG.check() cv, ok := commonCanonHeader[v] if ok { return cv } cv, ok = sc.canonHeader[v] if ok { return cv } if sc.canonHeader == nil { sc.canonHeader = make(map[string]string) } cv = http.CanonicalHeaderKey(v) sc.canonHeader[v] = cv return cv } type readFrameResult struct { f Frame // valid until readMore is called err error // readMore should be called once the consumer no longer needs or // retains f. After readMore, f is invalid and more frames can be // read. readMore func() } // readFrames is the loop that reads incoming frames. // It takes care to only read one frame at a time, blocking until the // consumer is done with the frame. // It's run on its own goroutine. func (sc *serverConn) readFrames() { gate := make(gate) gateDone := gate.Done for { f, err := sc.framer.ReadFrame() select { case sc.readFrameCh <- readFrameResult{f, err, gateDone}: case <-sc.doneServing: return } select { case <-gate: case <-sc.doneServing: return } if terminalReadFrameError(err) { return } } } // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine. type frameWriteResult struct { wr FrameWriteRequest // what was written (or attempted) err error // result of the writeFrame call } // writeFrameAsync runs in its own goroutine and writes a single frame // and then reports when it's done. // At most one goroutine can be running writeFrameAsync at a time per // serverConn. func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest) { err := wr.write.writeFrame(sc) sc.wroteFrameCh <- frameWriteResult{wr, err} } func (sc *serverConn) closeAllStreamsOnConnClose() { sc.serveG.check() for _, st := range sc.streams { sc.closeStream(st, errClientDisconnected) } } func (sc *serverConn) stopShutdownTimer() { sc.serveG.check() if t := sc.shutdownTimer; t != nil { t.Stop() } } func (sc *serverConn) notePanic() { // Note: this is for serverConn.serve panicking, not http.Handler code. if testHookOnPanicMu != nil { testHookOnPanicMu.Lock() defer testHookOnPanicMu.Unlock() } if testHookOnPanic != nil { if e := recover(); e != nil { if testHookOnPanic(sc, e) { panic(e) } } } } func (sc *serverConn) serve() { sc.serveG.check() defer sc.notePanic() defer sc.conn.Close() defer sc.closeAllStreamsOnConnClose() defer sc.stopShutdownTimer() defer close(sc.doneServing) // unblocks handlers trying to send if VerboseLogs { sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs) } sc.writeFrame(FrameWriteRequest{ write: writeSettings{ {SettingMaxFrameSize, sc.srv.maxReadFrameSize()}, {SettingMaxConcurrentStreams, sc.advMaxStreams}, {SettingMaxHeaderListSize, sc.maxHeaderListSize()}, {SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())}, }, }) sc.unackedSettings++ // Each connection starts with intialWindowSize inflow tokens. // If a higher value is configured, we add more tokens. if diff := sc.srv.initialConnRecvWindowSize() - initialWindowSize; diff > 0 { sc.sendWindowUpdate(nil, int(diff)) } if err := sc.readPreface(); err != nil { sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err) return } // Now that we've got the preface, get us out of the // "StateNew" state. We can't go directly to idle, though. // Active means we read some data and anticipate a request. We'll // do another Active when we get a HEADERS frame. sc.setConnState(http.StateActive) sc.setConnState(http.StateIdle) if sc.srv.IdleTimeout != 0 { sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer) defer sc.idleTimer.Stop() } go sc.readFrames() // closed by defer sc.conn.Close above settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer) defer settingsTimer.Stop() loopNum := 0 for { loopNum++ select { case wr := <-sc.wantWriteFrameCh: if se, ok := wr.write.(StreamError); ok { sc.resetStream(se) break } sc.writeFrame(wr) case res := <-sc.wroteFrameCh: sc.wroteFrame(res) case res := <-sc.readFrameCh: if !sc.processFrameFromReader(res) { return } res.readMore() if settingsTimer != nil { settingsTimer.Stop() settingsTimer = nil } case m := <-sc.bodyReadCh: sc.noteBodyRead(m.st, m.n) case msg := <-sc.serveMsgCh: switch v := msg.(type) { case func(int): v(loopNum) // for testing case *serverMessage: switch v { case settingsTimerMsg: sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr()) return case idleTimerMsg: sc.vlogf("connection is idle") sc.goAway(ErrCodeNo) case shutdownTimerMsg: sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr()) return case gracefulShutdownMsg: sc.startGracefulShutdownInternal() default: panic("unknown timer") } case *startPushRequest: sc.startPush(v) default: panic(fmt.Sprintf("unexpected type %T", v)) } } if sc.inGoAway && sc.curOpenStreams() == 0 && !sc.needToSendGoAway && !sc.writingFrame { return } } } func (sc *serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{}) { select { case <-sc.doneServing: case <-sharedCh: close(privateCh) } } type serverMessage int // Message values sent to serveMsgCh. var ( settingsTimerMsg = new(serverMessage) idleTimerMsg = new(serverMessage) shutdownTimerMsg = new(serverMessage) gracefulShutdownMsg = new(serverMessage) ) func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) } func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) } func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) } func (sc *serverConn) sendServeMsg(msg interface{}) { sc.serveG.checkNotOn() // NOT select { case sc.serveMsgCh <- msg: case <-sc.doneServing: } } // readPreface reads the ClientPreface greeting from the peer // or returns an error on timeout or an invalid greeting. func (sc *serverConn) readPreface() error { errc := make(chan error, 1) go func() { // Read the client preface buf := make([]byte, len(ClientPreface)) if _, err := io.ReadFull(sc.conn, buf); err != nil { errc <- err } else if !bytes.Equal(buf, clientPreface) { errc <- fmt.Errorf("bogus greeting %q", buf) } else { errc <- nil } }() timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server? defer timer.Stop() select { case <-timer.C: return errors.New("timeout waiting for client preface") case err := <-errc: if err == nil { if VerboseLogs { sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr()) } } return err } } var errChanPool = sync.Pool{ New: func() interface{} { return make(chan error, 1) }, } var writeDataPool = sync.Pool{ New: func() interface{} { return new(writeData) }, } // writeDataFromHandler writes DATA response frames from a handler on // the given stream. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error { ch := errChanPool.Get().(chan error) writeArg := writeDataPool.Get().(*writeData) *writeArg = writeData{stream.id, data, endStream} err := sc.writeFrameFromHandler(FrameWriteRequest{ write: writeArg, stream: stream, done: ch, }) if err != nil { return err } var frameWriteDone bool // the frame write is done (successfully or not) select { case err = <-ch: frameWriteDone = true case <-sc.doneServing: return errClientDisconnected case <-stream.cw: // If both ch and stream.cw were ready (as might // happen on the final Write after an http.Handler // ends), prefer the write result. Otherwise this // might just be us successfully closing the stream. // The writeFrameAsync and serve goroutines guarantee // that the ch send will happen before the stream.cw // close. select { case err = <-ch: frameWriteDone = true default: return errStreamClosed } } errChanPool.Put(ch) if frameWriteDone { writeDataPool.Put(writeArg) } return err } // writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts // if the connection has gone away. // // This must not be run from the serve goroutine itself, else it might // deadlock writing to sc.wantWriteFrameCh (which is only mildly // buffered and is read by serve itself). If you're on the serve // goroutine, call writeFrame instead. func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error { sc.serveG.checkNotOn() // NOT select { case sc.wantWriteFrameCh <- wr: return nil case <-sc.doneServing: // Serve loop is gone. // Client has closed their connection to the server. return errClientDisconnected } } // writeFrame schedules a frame to write and sends it if there's nothing // already being written. // // There is no pushback here (the serve goroutine never blocks). It's // the http.Handlers that block, waiting for their previous frames to // make it onto the wire // // If you're not on the serve goroutine, use writeFrameFromHandler instead. func (sc *serverConn) writeFrame(wr FrameWriteRequest) { sc.serveG.check() // If true, wr will not be written and wr.done will not be signaled. var ignoreWrite bool // We are not allowed to write frames on closed streams. RFC 7540 Section // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on // a closed stream." Our server never sends PRIORITY, so that exception // does not apply. // // The serverConn might close an open stream while the stream's handler // is still running. For example, the server might close a stream when it // receives bad data from the client. If this happens, the handler might // attempt to write a frame after the stream has been closed (since the // handler hasn't yet been notified of the close). In this case, we simply // ignore the frame. The handler will notice that the stream is closed when // it waits for the frame to be written. // // As an exception to this rule, we allow sending RST_STREAM after close. // This allows us to immediately reject new streams without tracking any // state for those streams (except for the queued RST_STREAM frame). This // may result in duplicate RST_STREAMs in some cases, but the client should // ignore those. if wr.StreamID() != 0 { _, isReset := wr.write.(StreamError) if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset { ignoreWrite = true } } // Don't send a 100-continue response if we've already sent headers. // See golang.org/issue/14030. switch wr.write.(type) { case *writeResHeaders: wr.stream.wroteHeaders = true case write100ContinueHeadersFrame: if wr.stream.wroteHeaders { // We do not need to notify wr.done because this frame is // never written with wr.done != nil. if wr.done != nil { panic("wr.done != nil for write100ContinueHeadersFrame") } ignoreWrite = true } } if !ignoreWrite { sc.writeSched.Push(wr) } sc.scheduleFrameWrite() } // startFrameWrite starts a goroutine to write wr (in a separate // goroutine since that might block on the network), and updates the // serve goroutine's state about the world, updated from info in wr. func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) { sc.serveG.check() if sc.writingFrame { panic("internal error: can only be writing one frame at a time") } st := wr.stream if st != nil { switch st.state { case stateHalfClosedLocal: switch wr.write.(type) { case StreamError, handlerPanicRST, writeWindowUpdate: // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE // in this state. (We never send PRIORITY from the server, so that is not checked.) default: panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr)) } case stateClosed: panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr)) } } if wpp, ok := wr.write.(*writePushPromise); ok { var err error wpp.promisedID, err = wpp.allocatePromisedID() if err != nil { sc.writingFrameAsync = false wr.replyToWriter(err) return } } sc.writingFrame = true sc.needsFrameFlush = true if wr.write.staysWithinBuffer(sc.bw.Available()) { sc.writingFrameAsync = false err := wr.write.writeFrame(sc) sc.wroteFrame(frameWriteResult{wr, err}) } else { sc.writingFrameAsync = true go sc.writeFrameAsync(wr) } } // errHandlerPanicked is the error given to any callers blocked in a read from // Request.Body when the main goroutine panics. Since most handlers read in the // the main ServeHTTP goroutine, this will show up rarely. var errHandlerPanicked = errors.New("http2: handler panicked") // wroteFrame is called on the serve goroutine with the result of // whatever happened on writeFrameAsync. func (sc *serverConn) wroteFrame(res frameWriteResult) { sc.serveG.check() if !sc.writingFrame { panic("internal error: expected to be already writing a frame") } sc.writingFrame = false sc.writingFrameAsync = false wr := res.wr if writeEndsStream(wr.write) { st := wr.stream if st == nil { panic("internal error: expecting non-nil stream") } switch st.state { case stateOpen: // Here we would go to stateHalfClosedLocal in // theory, but since our handler is done and // the net/http package provides no mechanism // for closing a ResponseWriter while still // reading data (see possible TODO at top of // this file), we go into closed state here // anyway, after telling the peer we're // hanging up on them. We'll transition to // stateClosed after the RST_STREAM frame is // written. st.state = stateHalfClosedLocal // Section 8.1: a server MAY request that the client abort // transmission of a request without error by sending a // RST_STREAM with an error code of NO_ERROR after sending // a complete response. sc.resetStream(streamError(st.id, ErrCodeNo)) case stateHalfClosedRemote: sc.closeStream(st, errHandlerComplete) } } else { switch v := wr.write.(type) { case StreamError: // st may be unknown if the RST_STREAM was generated to reject bad input. if st, ok := sc.streams[v.StreamID]; ok { sc.closeStream(st, v) } case handlerPanicRST: sc.closeStream(wr.stream, errHandlerPanicked) } } // Reply (if requested) to unblock the ServeHTTP goroutine. wr.replyToWriter(res.err) sc.scheduleFrameWrite() } // scheduleFrameWrite tickles the frame writing scheduler. // // If a frame is already being written, nothing happens. This will be called again // when the frame is done being written. // // If a frame isn't being written we need to send one, the best frame // to send is selected, preferring first things that aren't // stream-specific (e.g. ACKing settings), and then finding the // highest priority stream. // // If a frame isn't being written and there's nothing else to send, we // flush the write buffer. func (sc *serverConn) scheduleFrameWrite() { sc.serveG.check() if sc.writingFrame || sc.inFrameScheduleLoop { return } sc.inFrameScheduleLoop = true for !sc.writingFrameAsync { if sc.needToSendGoAway { sc.needToSendGoAway = false sc.startFrameWrite(FrameWriteRequest{ write: &writeGoAway{ maxStreamID: sc.maxClientStreamID, code: sc.goAwayCode, }, }) continue } if sc.needToSendSettingsAck { sc.needToSendSettingsAck = false sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}}) continue } if !sc.inGoAway || sc.goAwayCode == ErrCodeNo { if wr, ok := sc.writeSched.Pop(); ok { sc.startFrameWrite(wr) continue } } if sc.needsFrameFlush { sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}}) sc.needsFrameFlush = false // after startFrameWrite, since it sets this true continue } break } sc.inFrameScheduleLoop = false } // startGracefulShutdown gracefully shuts down a connection. This // sends GOAWAY with ErrCodeNo to tell the client we're gracefully // shutting down. The connection isn't closed until all current // streams are done. // // startGracefulShutdown returns immediately; it does not wait until // the connection has shut down. func (sc *serverConn) startGracefulShutdown() { sc.serveG.checkNotOn() // NOT sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) }) } func (sc *serverConn) startGracefulShutdownInternal() { sc.goAwayIn(ErrCodeNo, 0) } func (sc *serverConn) goAway(code ErrCode) { sc.serveG.check() var forceCloseIn time.Duration if code != ErrCodeNo { forceCloseIn = 250 * time.Millisecond } else { // TODO: configurable forceCloseIn = 1 * time.Second } sc.goAwayIn(code, forceCloseIn) } func (sc *serverConn) goAwayIn(code ErrCode, forceCloseIn time.Duration) { sc.serveG.check() if sc.inGoAway { return } if forceCloseIn != 0 { sc.shutDownIn(forceCloseIn) } sc.inGoAway = true sc.needToSendGoAway = true sc.goAwayCode = code sc.scheduleFrameWrite() } func (sc *serverConn) shutDownIn(d time.Duration) { sc.serveG.check() sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer) } func (sc *serverConn) resetStream(se StreamError) { sc.serveG.check() sc.writeFrame(FrameWriteRequest{write: se}) if st, ok := sc.streams[se.StreamID]; ok { st.resetQueued = true } } // processFrameFromReader processes the serve loop's read from readFrameCh from the // frame-reading goroutine. // processFrameFromReader returns whether the connection should be kept open. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool { sc.serveG.check() err := res.err if err != nil { if err == ErrFrameTooLarge { sc.goAway(ErrCodeFrameSize) return true // goAway will close the loop } clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) if clientGone { // TODO: could we also get into this state if // the peer does a half close // (e.g. CloseWrite) because they're done // sending frames but they're still wanting // our open replies? Investigate. // TODO: add CloseWrite to crypto/tls.Conn first // so we have a way to test this? I suppose // just for testing we could have a non-TLS mode. return false } } else { f := res.f if VerboseLogs { sc.vlogf("http2: server read frame %v", summarizeFrame(f)) } err = sc.processFrame(f) if err == nil { return true } } switch ev := err.(type) { case StreamError: sc.resetStream(ev) return true case goAwayFlowError: sc.goAway(ErrCodeFlowControl) return true case ConnectionError: sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev) sc.goAway(ErrCode(ev)) return true // goAway will handle shutdown default: if res.err != nil { sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err) } else { sc.logf("http2: server closing client connection: %v", err) } return false } } func (sc *serverConn) processFrame(f Frame) error { sc.serveG.check() // First frame received must be SETTINGS. if !sc.sawFirstSettings { if _, ok := f.(*SettingsFrame); !ok { return ConnectionError(ErrCodeProtocol) } sc.sawFirstSettings = true } switch f := f.(type) { case *SettingsFrame: return sc.processSettings(f) case *MetaHeadersFrame: return sc.processHeaders(f) case *WindowUpdateFrame: return sc.processWindowUpdate(f) case *PingFrame: return sc.processPing(f) case *DataFrame: return sc.processData(f) case *RSTStreamFrame: return sc.processResetStream(f) case *PriorityFrame: return sc.processPriority(f) case *GoAwayFrame: return sc.processGoAway(f) case *PushPromiseFrame: // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR. return ConnectionError(ErrCodeProtocol) default: sc.vlogf("http2: server ignoring frame: %v", f.Header()) return nil } } func (sc *serverConn) processPing(f *PingFrame) error { sc.serveG.check() if f.IsAck() { // 6.7 PING: " An endpoint MUST NOT respond to PING frames // containing this flag." return nil } if f.StreamID != 0 { // "PING frames are not associated with any individual // stream. If a PING frame is received with a stream // identifier field value other than 0x0, the recipient MUST // respond with a connection error (Section 5.4.1) of type // PROTOCOL_ERROR." return ConnectionError(ErrCodeProtocol) } if sc.inGoAway && sc.goAwayCode != ErrCodeNo { return nil } sc.writeFrame(FrameWriteRequest{write: writePingAck{f}}) return nil } func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error { sc.serveG.check() switch { case f.StreamID != 0: // stream-level flow control state, st := sc.state(f.StreamID) if state == stateIdle { // Section 5.1: "Receiving any frame other than HEADERS // or PRIORITY on a stream in this state MUST be // treated as a connection error (Section 5.4.1) of // type PROTOCOL_ERROR." return ConnectionError(ErrCodeProtocol) } if st == nil { // "WINDOW_UPDATE can be sent by a peer that has sent a // frame bearing the END_STREAM flag. This means that a // receiver could receive a WINDOW_UPDATE frame on a "half // closed (remote)" or "closed" stream. A receiver MUST // NOT treat this as an error, see Section 5.1." return nil } if !st.flow.add(int32(f.Increment)) { return streamError(f.StreamID, ErrCodeFlowControl) } default: // connection-level flow control if !sc.flow.add(int32(f.Increment)) { return goAwayFlowError{} } } sc.scheduleFrameWrite() return nil } func (sc *serverConn) processResetStream(f *RSTStreamFrame) error { sc.serveG.check() state, st := sc.state(f.StreamID) if state == stateIdle { // 6.4 "RST_STREAM frames MUST NOT be sent for a // stream in the "idle" state. If a RST_STREAM frame // identifying an idle stream is received, the // recipient MUST treat this as a connection error // (Section 5.4.1) of type PROTOCOL_ERROR. return ConnectionError(ErrCodeProtocol) } if st != nil { st.cancelCtx() sc.closeStream(st, streamError(f.StreamID, f.ErrCode)) } return nil } func (sc *serverConn) closeStream(st *stream, err error) { sc.serveG.check() if st.state == stateIdle || st.state == stateClosed { panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state)) } st.state = stateClosed if st.writeDeadline != nil { st.writeDeadline.Stop() } if st.isPushed() { sc.curPushedStreams-- } else { sc.curClientStreams-- } delete(sc.streams, st.id) if len(sc.streams) == 0 { sc.setConnState(http.StateIdle) if sc.srv.IdleTimeout != 0 { sc.idleTimer.Reset(sc.srv.IdleTimeout) } if h1ServerKeepAlivesDisabled(sc.hs) { sc.startGracefulShutdownInternal() } } if p := st.body; p != nil { // Return any buffered unread bytes worth of conn-level flow control. // See golang.org/issue/16481 sc.sendWindowUpdate(nil, p.Len()) p.CloseWithError(err) } st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc sc.writeSched.CloseStream(st.id) } func (sc *serverConn) processSettings(f *SettingsFrame) error { sc.serveG.check() if f.IsAck() { sc.unackedSettings-- if sc.unackedSettings < 0 { // Why is the peer ACKing settings we never sent? // The spec doesn't mention this case, but // hang up on them anyway. return ConnectionError(ErrCodeProtocol) } return nil } if err := f.ForeachSetting(sc.processSetting); err != nil { return err } sc.needToSendSettingsAck = true sc.scheduleFrameWrite() return nil } func (sc *serverConn) processSetting(s Setting) error { sc.serveG.check() if err := s.Valid(); err != nil { return err } if VerboseLogs { sc.vlogf("http2: server processing setting %v", s) } switch s.ID { case SettingHeaderTableSize: sc.headerTableSize = s.Val sc.hpackEncoder.SetMaxDynamicTableSize(s.Val) case SettingEnablePush: sc.pushEnabled = s.Val != 0 case SettingMaxConcurrentStreams: sc.clientMaxStreams = s.Val case SettingInitialWindowSize: return sc.processSettingInitialWindowSize(s.Val) case SettingMaxFrameSize: sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31 case SettingMaxHeaderListSize: sc.peerMaxHeaderListSize = s.Val default: // Unknown setting: "An endpoint that receives a SETTINGS // frame with any unknown or unsupported identifier MUST // ignore that setting." if VerboseLogs { sc.vlogf("http2: server ignoring unknown setting %v", s) } } return nil } func (sc *serverConn) processSettingInitialWindowSize(val uint32) error { sc.serveG.check() // Note: val already validated to be within range by // processSetting's Valid call. // "A SETTINGS frame can alter the initial flow control window // size for all current streams. When the value of // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST // adjust the size of all stream flow control windows that it // maintains by the difference between the new value and the // old value." old := sc.initialStreamSendWindowSize sc.initialStreamSendWindowSize = int32(val) growth := int32(val) - old // may be negative for _, st := range sc.streams { if !st.flow.add(growth) { // 6.9.2 Initial Flow Control Window Size // "An endpoint MUST treat a change to // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow // control window to exceed the maximum size as a // connection error (Section 5.4.1) of type // FLOW_CONTROL_ERROR." return ConnectionError(ErrCodeFlowControl) } } return nil } func (sc *serverConn) processData(f *DataFrame) error { sc.serveG.check() if sc.inGoAway && sc.goAwayCode != ErrCodeNo { return nil } data := f.Data() // "If a DATA frame is received whose stream is not in "open" // or "half closed (local)" state, the recipient MUST respond // with a stream error (Section 5.4.2) of type STREAM_CLOSED." id := f.Header().StreamID state, st := sc.state(id) if id == 0 || state == stateIdle { // Section 5.1: "Receiving any frame other than HEADERS // or PRIORITY on a stream in this state MUST be // treated as a connection error (Section 5.4.1) of // type PROTOCOL_ERROR." return ConnectionError(ErrCodeProtocol) } if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued { // This includes sending a RST_STREAM if the stream is // in stateHalfClosedLocal (which currently means that // the http.Handler returned, so it's done reading & // done writing). Try to stop the client from sending // more DATA. // But still enforce their connection-level flow control, // and return any flow control bytes since we're not going // to consume them. if sc.inflow.available() < int32(f.Length) { return streamError(id, ErrCodeFlowControl) } // Deduct the flow control from inflow, since we're // going to immediately add it back in // sendWindowUpdate, which also schedules sending the // frames. sc.inflow.take(int32(f.Length)) sc.sendWindowUpdate(nil, int(f.Length)) // conn-level if st != nil && st.resetQueued { // Already have a stream error in flight. Don't send another. return nil } return streamError(id, ErrCodeStreamClosed) } if st.body == nil { panic("internal error: should have a body in this state") } // Sender sending more than they'd declared? if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes { st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes)) return streamError(id, ErrCodeStreamClosed) } if f.Length > 0 { // Check whether the client has flow control quota. if st.inflow.available() < int32(f.Length) { return streamError(id, ErrCodeFlowControl) } st.inflow.take(int32(f.Length)) if len(data) > 0 { wrote, err := st.body.Write(data) if err != nil { return streamError(id, ErrCodeStreamClosed) } if wrote != len(data) { panic("internal error: bad Writer") } st.bodyBytes += int64(len(data)) } // Return any padded flow control now, since we won't // refund it later on body reads. if pad := int32(f.Length) - int32(len(data)); pad > 0 { sc.sendWindowUpdate32(nil, pad) sc.sendWindowUpdate32(st, pad) } } if f.StreamEnded() { st.endStream() } return nil } func (sc *serverConn) processGoAway(f *GoAwayFrame) error { sc.serveG.check() if f.ErrCode != ErrCodeNo { sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f) } else { sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f) } sc.startGracefulShutdownInternal() // http://tools.ietf.org/html/rfc7540#section-6.8 // We should not create any new streams, which means we should disable push. sc.pushEnabled = false return nil } // isPushed reports whether the stream is server-initiated. func (st *stream) isPushed() bool { return st.id%2 == 0 } // endStream closes a Request.Body's pipe. It is called when a DATA // frame says a request body is over (or after trailers). func (st *stream) endStream() { sc := st.sc sc.serveG.check() if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes { st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes", st.declBodyBytes, st.bodyBytes)) } else { st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest) st.body.CloseWithError(io.EOF) } st.state = stateHalfClosedRemote } // copyTrailersToHandlerRequest is run in the Handler's goroutine in // its Request.Body.Read just before it gets io.EOF. func (st *stream) copyTrailersToHandlerRequest() { for k, vv := range st.trailer { if _, ok := st.reqTrailer[k]; ok { // Only copy it over it was pre-declared. st.reqTrailer[k] = vv } } } // onWriteTimeout is run on its own goroutine (from time.AfterFunc) // when the stream's WriteTimeout has fired. func (st *stream) onWriteTimeout() { st.sc.writeFrameFromHandler(FrameWriteRequest{write: streamError(st.id, ErrCodeInternal)}) } func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error { sc.serveG.check() id := f.StreamID if sc.inGoAway { // Ignore. return nil } // http://tools.ietf.org/html/rfc7540#section-5.1.1 // Streams initiated by a client MUST use odd-numbered stream // identifiers. [...] An endpoint that receives an unexpected // stream identifier MUST respond with a connection error // (Section 5.4.1) of type PROTOCOL_ERROR. if id%2 != 1 { return ConnectionError(ErrCodeProtocol) } // A HEADERS frame can be used to create a new stream or // send a trailer for an open one. If we already have a stream // open, let it process its own HEADERS frame (trailers at this // point, if it's valid). if st := sc.streams[f.StreamID]; st != nil { if st.resetQueued { // We're sending RST_STREAM to close the stream, so don't bother // processing this frame. return nil } return st.processTrailerHeaders(f) } // [...] The identifier of a newly established stream MUST be // numerically greater than all streams that the initiating // endpoint has opened or reserved. [...] An endpoint that // receives an unexpected stream identifier MUST respond with // a connection error (Section 5.4.1) of type PROTOCOL_ERROR. if id <= sc.maxClientStreamID { return ConnectionError(ErrCodeProtocol) } sc.maxClientStreamID = id if sc.idleTimer != nil { sc.idleTimer.Stop() } // http://tools.ietf.org/html/rfc7540#section-5.1.2 // [...] Endpoints MUST NOT exceed the limit set by their peer. An // endpoint that receives a HEADERS frame that causes their // advertised concurrent stream limit to be exceeded MUST treat // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR // or REFUSED_STREAM. if sc.curClientStreams+1 > sc.advMaxStreams { if sc.unackedSettings == 0 { // They should know better. return streamError(id, ErrCodeProtocol) } // Assume it's a network race, where they just haven't // received our last SETTINGS update. But actually // this can't happen yet, because we don't yet provide // a way for users to adjust server parameters at // runtime. return streamError(id, ErrCodeRefusedStream) } initialState := stateOpen if f.StreamEnded() { initialState = stateHalfClosedRemote } st := sc.newStream(id, 0, initialState) if f.HasPriority() { if err := checkPriority(f.StreamID, f.Priority); err != nil { return err } sc.writeSched.AdjustStream(st.id, f.Priority) } rw, req, err := sc.newWriterAndRequest(st, f) if err != nil { return err } st.reqTrailer = req.Trailer if st.reqTrailer != nil { st.trailer = make(http.Header) } st.body = req.Body.(*requestBody).pipe // may be nil st.declBodyBytes = req.ContentLength handler := sc.handler.ServeHTTP if f.Truncated { // Their header list was too long. Send a 431 error. handler = handleHeaderListTooLong } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil { handler = new400Handler(err) } // The net/http package sets the read deadline from the // http.Server.ReadTimeout during the TLS handshake, but then // passes the connection off to us with the deadline already // set. Disarm it here after the request headers are read, // similar to how the http1 server works. Here it's // technically more like the http1 Server's ReadHeaderTimeout // (in Go 1.8), though. That's a more sane option anyway. if sc.hs.ReadTimeout != 0 { sc.conn.SetReadDeadline(time.Time{}) } go sc.runHandler(rw, req, handler) return nil } func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error { sc := st.sc sc.serveG.check() if st.gotTrailerHeader { return ConnectionError(ErrCodeProtocol) } st.gotTrailerHeader = true if !f.StreamEnded() { return streamError(st.id, ErrCodeProtocol) } if len(f.PseudoFields()) > 0 { return streamError(st.id, ErrCodeProtocol) } if st.trailer != nil { for _, hf := range f.RegularFields() { key := sc.canonicalHeader(hf.Name) if !ValidTrailerHeader(key) { // TODO: send more details to the peer somehow. But http2 has // no way to send debug data at a stream level. Discuss with // HTTP folk. return streamError(st.id, ErrCodeProtocol) } st.trailer[key] = append(st.trailer[key], hf.Value) } } st.endStream() return nil } func checkPriority(streamID uint32, p PriorityParam) error { if streamID == p.StreamDep { // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR." // Section 5.3.3 says that a stream can depend on one of its dependencies, // so it's only self-dependencies that are forbidden. return streamError(streamID, ErrCodeProtocol) } return nil } func (sc *serverConn) processPriority(f *PriorityFrame) error { if sc.inGoAway { return nil } if err := checkPriority(f.StreamID, f.PriorityParam); err != nil { return err } sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam) return nil } func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream { sc.serveG.check() if id == 0 { panic("internal error: cannot create stream with id 0") } ctx, cancelCtx := contextWithCancel(sc.baseCtx) st := &stream{ sc: sc, id: id, state: state, ctx: ctx, cancelCtx: cancelCtx, } st.cw.Init() st.flow.conn = &sc.flow // link to conn-level counter st.flow.add(sc.initialStreamSendWindowSize) st.inflow.conn = &sc.inflow // link to conn-level counter st.inflow.add(sc.srv.initialStreamRecvWindowSize()) if sc.hs.WriteTimeout != 0 { st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout) } sc.streams[id] = st sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID}) if st.isPushed() { sc.curPushedStreams++ } else { sc.curClientStreams++ } if sc.curOpenStreams() == 1 { sc.setConnState(http.StateActive) } return st } func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) { sc.serveG.check() rp := requestParam{ method: f.PseudoValue("method"), scheme: f.PseudoValue("scheme"), authority: f.PseudoValue("authority"), path: f.PseudoValue("path"), } isConnect := rp.method == "CONNECT" if isConnect { if rp.path != "" || rp.scheme != "" || rp.authority == "" { return nil, nil, streamError(f.StreamID, ErrCodeProtocol) } } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") { // See 8.1.2.6 Malformed Requests and Responses: // // Malformed requests or responses that are detected // MUST be treated as a stream error (Section 5.4.2) // of type PROTOCOL_ERROR." // // 8.1.2.3 Request Pseudo-Header Fields // "All HTTP/2 requests MUST include exactly one valid // value for the :method, :scheme, and :path // pseudo-header fields" return nil, nil, streamError(f.StreamID, ErrCodeProtocol) } bodyOpen := !f.StreamEnded() if rp.method == "HEAD" && bodyOpen { // HEAD requests can't have bodies return nil, nil, streamError(f.StreamID, ErrCodeProtocol) } rp.header = make(http.Header) for _, hf := range f.RegularFields() { rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value) } if rp.authority == "" { rp.authority = rp.header.Get("Host") } rw, req, err := sc.newWriterAndRequestNoBody(st, rp) if err != nil { return nil, nil, err } if bodyOpen { if vv, ok := rp.header["Content-Length"]; ok { req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64) } else { req.ContentLength = -1 } req.Body.(*requestBody).pipe = &pipe{ b: &dataBuffer{expected: req.ContentLength}, } } return rw, req, nil } type requestParam struct { method string scheme, authority, path string header http.Header } func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) { sc.serveG.check() var tlsState *tls.ConnectionState // nil if not scheme https if rp.scheme == "https" { tlsState = sc.tlsState } needsContinue := rp.header.Get("Expect") == "100-continue" if needsContinue { rp.header.Del("Expect") } // Merge Cookie headers into one "; "-delimited value. if cookies := rp.header["Cookie"]; len(cookies) > 1 { rp.header.Set("Cookie", strings.Join(cookies, "; ")) } // Setup Trailers var trailer http.Header for _, v := range rp.header["Trailer"] { for _, key := range strings.Split(v, ",") { key = http.CanonicalHeaderKey(strings.TrimSpace(key)) switch key { case "Transfer-Encoding", "Trailer", "Content-Length": // Bogus. (copy of http1 rules) // Ignore. default: if trailer == nil { trailer = make(http.Header) } trailer[key] = nil } } } delete(rp.header, "Trailer") var url_ *url.URL var requestURI string if rp.method == "CONNECT" { url_ = &url.URL{Host: rp.authority} requestURI = rp.authority // mimic HTTP/1 server behavior } else { var err error url_, err = url.ParseRequestURI(rp.path) if err != nil { return nil, nil, streamError(st.id, ErrCodeProtocol) } requestURI = rp.path } body := &requestBody{ conn: sc, stream: st, needsContinue: needsContinue, } req := &http.Request{ Method: rp.method, URL: url_, RemoteAddr: sc.remoteAddrStr, Header: rp.header, RequestURI: requestURI, Proto: "HTTP/2.0", ProtoMajor: 2, ProtoMinor: 0, TLS: tlsState, Host: rp.authority, Body: body, Trailer: trailer, } req = requestWithContext(req, st.ctx) rws := responseWriterStatePool.Get().(*responseWriterState) bwSave := rws.bw *rws = responseWriterState{} // zero all the fields rws.conn = sc rws.bw = bwSave rws.bw.Reset(chunkWriter{rws}) rws.stream = st rws.req = req rws.body = body rw := &responseWriter{rws: rws} return rw, req, nil } // Run on its own goroutine. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) { didPanic := true defer func() { rw.rws.stream.cancelCtx() if didPanic { e := recover() sc.writeFrameFromHandler(FrameWriteRequest{ write: handlerPanicRST{rw.rws.stream.id}, stream: rw.rws.stream, }) // Same as net/http: if shouldLogPanic(e) { const size = 64 << 10 buf := make([]byte, size) buf = buf[:runtime.Stack(buf, false)] sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf) } return } rw.handlerDone() }() handler(rw, req) didPanic = false } func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) { // 10.5.1 Limits on Header Block Size: // .. "A server that receives a larger header block than it is // willing to handle can send an HTTP 431 (Request Header Fields Too // Large) status code" const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+ w.WriteHeader(statusRequestHeaderFieldsTooLarge) io.WriteString(w, "

HTTP Error 431

Request Header Field(s) Too Large

") } // called from handler goroutines. // h may be nil. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error { sc.serveG.checkNotOn() // NOT on var errc chan error if headerData.h != nil { // If there's a header map (which we don't own), so we have to block on // waiting for this frame to be written, so an http.Flush mid-handler // writes out the correct value of keys, before a handler later potentially // mutates it. errc = errChanPool.Get().(chan error) } if err := sc.writeFrameFromHandler(FrameWriteRequest{ write: headerData, stream: st, done: errc, }); err != nil { return err } if errc != nil { select { case err := <-errc: errChanPool.Put(errc) return err case <-sc.doneServing: return errClientDisconnected case <-st.cw: return errStreamClosed } } return nil } // called from handler goroutines. func (sc *serverConn) write100ContinueHeaders(st *stream) { sc.writeFrameFromHandler(FrameWriteRequest{ write: write100ContinueHeadersFrame{st.id}, stream: st, }) } // A bodyReadMsg tells the server loop that the http.Handler read n // bytes of the DATA from the client on the given stream. type bodyReadMsg struct { st *stream n int } // called from handler goroutines. // Notes that the handler for the given stream ID read n bytes of its body // and schedules flow control tokens to be sent. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) { sc.serveG.checkNotOn() // NOT on if n > 0 { select { case sc.bodyReadCh <- bodyReadMsg{st, n}: case <-sc.doneServing: } } } func (sc *serverConn) noteBodyRead(st *stream, n int) { sc.serveG.check() sc.sendWindowUpdate(nil, n) // conn-level if st.state != stateHalfClosedRemote && st.state != stateClosed { // Don't send this WINDOW_UPDATE if the stream is closed // remotely. sc.sendWindowUpdate(st, n) } } // st may be nil for conn-level func (sc *serverConn) sendWindowUpdate(st *stream, n int) { sc.serveG.check() // "The legal range for the increment to the flow control // window is 1 to 2^31-1 (2,147,483,647) octets." // A Go Read call on 64-bit machines could in theory read // a larger Read than this. Very unlikely, but we handle it here // rather than elsewhere for now. const maxUint31 = 1<<31 - 1 for n >= maxUint31 { sc.sendWindowUpdate32(st, maxUint31) n -= maxUint31 } sc.sendWindowUpdate32(st, int32(n)) } // st may be nil for conn-level func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) { sc.serveG.check() if n == 0 { return } if n < 0 { panic("negative update") } var streamID uint32 if st != nil { streamID = st.id } sc.writeFrame(FrameWriteRequest{ write: writeWindowUpdate{streamID: streamID, n: uint32(n)}, stream: st, }) var ok bool if st == nil { ok = sc.inflow.add(n) } else { ok = st.inflow.add(n) } if !ok { panic("internal error; sent too many window updates without decrements?") } } // requestBody is the Handler's Request.Body type. // Read and Close may be called concurrently. type requestBody struct { stream *stream conn *serverConn closed bool // for use by Close only sawEOF bool // for use by Read only pipe *pipe // non-nil if we have a HTTP entity message body needsContinue bool // need to send a 100-continue } func (b *requestBody) Close() error { if b.pipe != nil && !b.closed { b.pipe.BreakWithError(errClosedBody) } b.closed = true return nil } func (b *requestBody) Read(p []byte) (n int, err error) { if b.needsContinue { b.needsContinue = false b.conn.write100ContinueHeaders(b.stream) } if b.pipe == nil || b.sawEOF { return 0, io.EOF } n, err = b.pipe.Read(p) if err == io.EOF { b.sawEOF = true } if b.conn == nil && inTests { return } b.conn.noteBodyReadFromHandler(b.stream, n, err) return } // responseWriter is the http.ResponseWriter implementation. It's // intentionally small (1 pointer wide) to minimize garbage. The // responseWriterState pointer inside is zeroed at the end of a // request (in handlerDone) and calls on the responseWriter thereafter // simply crash (caller's mistake), but the much larger responseWriterState // and buffers are reused between multiple requests. type responseWriter struct { rws *responseWriterState } // Optional http.ResponseWriter interfaces implemented. var ( _ http.CloseNotifier = (*responseWriter)(nil) _ http.Flusher = (*responseWriter)(nil) _ stringWriter = (*responseWriter)(nil) ) type responseWriterState struct { // immutable within a request: stream *stream req *http.Request body *requestBody // to close at end of request, if DATA frames didn't conn *serverConn // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState} // mutated by http.Handler goroutine: handlerHeader http.Header // nil until called snapHeader http.Header // snapshot of handlerHeader at WriteHeader time trailers []string // set in writeChunk status int // status code passed to WriteHeader wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet. sentHeader bool // have we sent the header frame? handlerDone bool // handler has finished dirty bool // a Write failed; don't reuse this responseWriterState sentContentLen int64 // non-zero if handler set a Content-Length header wroteBytes int64 closeNotifierMu sync.Mutex // guards closeNotifierCh closeNotifierCh chan bool // nil until first used } type chunkWriter struct{ rws *responseWriterState } func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) } func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 } // declareTrailer is called for each Trailer header when the // response header is written. It notes that a header will need to be // written in the trailers at the end of the response. func (rws *responseWriterState) declareTrailer(k string) { k = http.CanonicalHeaderKey(k) if !ValidTrailerHeader(k) { // Forbidden by RFC 2616 14.40. rws.conn.logf("ignoring invalid trailer %q", k) return } if !strSliceContains(rws.trailers, k) { rws.trailers = append(rws.trailers, k) } } // writeChunk writes chunks from the bufio.Writer. But because // bufio.Writer may bypass its chunking, sometimes p may be // arbitrarily large. // // writeChunk is also responsible (on the first chunk) for sending the // HEADER response. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) { if !rws.wroteHeader { rws.writeHeader(200) } isHeadResp := rws.req.Method == "HEAD" if !rws.sentHeader { rws.sentHeader = true var ctype, clen string if clen = rws.snapHeader.Get("Content-Length"); clen != "" { rws.snapHeader.Del("Content-Length") clen64, err := strconv.ParseInt(clen, 10, 64) if err == nil && clen64 >= 0 { rws.sentContentLen = clen64 } else { clen = "" } } if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) { clen = strconv.Itoa(len(p)) } _, hasContentType := rws.snapHeader["Content-Type"] if !hasContentType && bodyAllowedForStatus(rws.status) { ctype = http.DetectContentType(p) } var date string if _, ok := rws.snapHeader["Date"]; !ok { // TODO(bradfitz): be faster here, like net/http? measure. date = time.Now().UTC().Format(http.TimeFormat) } for _, v := range rws.snapHeader["Trailer"] { foreachHeaderElement(v, rws.declareTrailer) } endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{ streamID: rws.stream.id, httpResCode: rws.status, h: rws.snapHeader, endStream: endStream, contentType: ctype, contentLength: clen, date: date, }) if err != nil { rws.dirty = true return 0, err } if endStream { return 0, nil } } if isHeadResp { return len(p), nil } if len(p) == 0 && !rws.handlerDone { return 0, nil } if rws.handlerDone { rws.promoteUndeclaredTrailers() } endStream := rws.handlerDone && !rws.hasTrailers() if len(p) > 0 || endStream { // only send a 0 byte DATA frame if we're ending the stream. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil { rws.dirty = true return 0, err } } if rws.handlerDone && rws.hasTrailers() { err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{ streamID: rws.stream.id, h: rws.handlerHeader, trailers: rws.trailers, endStream: true, }) if err != nil { rws.dirty = true } return len(p), err } return len(p), nil } // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys // that, if present, signals that the map entry is actually for // the response trailers, and not the response headers. The prefix // is stripped after the ServeHTTP call finishes and the values are // sent in the trailers. // // This mechanism is intended only for trailers that are not known // prior to the headers being written. If the set of trailers is fixed // or known before the header is written, the normal Go trailers mechanism // is preferred: // https://golang.org/pkg/net/http/#ResponseWriter // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers const TrailerPrefix = "Trailer:" // promoteUndeclaredTrailers permits http.Handlers to set trailers // after the header has already been flushed. Because the Go // ResponseWriter interface has no way to set Trailers (only the // Header), and because we didn't want to expand the ResponseWriter // interface, and because nobody used trailers, and because RFC 2616 // says you SHOULD (but not must) predeclare any trailers in the // header, the official ResponseWriter rules said trailers in Go must // be predeclared, and then we reuse the same ResponseWriter.Header() // map to mean both Headers and Trailers. When it's time to write the // Trailers, we pick out the fields of Headers that were declared as // trailers. That worked for a while, until we found the first major // user of Trailers in the wild: gRPC (using them only over http2), // and gRPC libraries permit setting trailers mid-stream without // predeclarnig them. So: change of plans. We still permit the old // way, but we also permit this hack: if a Header() key begins with // "Trailer:", the suffix of that key is a Trailer. Because ':' is an // invalid token byte anyway, there is no ambiguity. (And it's already // filtered out) It's mildly hacky, but not terrible. // // This method runs after the Handler is done and promotes any Header // fields to be trailers. func (rws *responseWriterState) promoteUndeclaredTrailers() { for k, vv := range rws.handlerHeader { if !strings.HasPrefix(k, TrailerPrefix) { continue } trailerKey := strings.TrimPrefix(k, TrailerPrefix) rws.declareTrailer(trailerKey) rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv } if len(rws.trailers) > 1 { sorter := sorterPool.Get().(*sorter) sorter.SortStrings(rws.trailers) sorterPool.Put(sorter) } } func (w *responseWriter) Flush() { rws := w.rws if rws == nil { panic("Header called after Handler finished") } if rws.bw.Buffered() > 0 { if err := rws.bw.Flush(); err != nil { // Ignore the error. The frame writer already knows. return } } else { // The bufio.Writer won't call chunkWriter.Write // (writeChunk with zero bytes, so we have to do it // ourselves to force the HTTP response header and/or // final DATA frame (with END_STREAM) to be sent. rws.writeChunk(nil) } } func (w *responseWriter) CloseNotify() <-chan bool { rws := w.rws if rws == nil { panic("CloseNotify called after Handler finished") } rws.closeNotifierMu.Lock() ch := rws.closeNotifierCh if ch == nil { ch = make(chan bool, 1) rws.closeNotifierCh = ch cw := rws.stream.cw go func() { cw.Wait() // wait for close ch <- true }() } rws.closeNotifierMu.Unlock() return ch } func (w *responseWriter) Header() http.Header { rws := w.rws if rws == nil { panic("Header called after Handler finished") } if rws.handlerHeader == nil { rws.handlerHeader = make(http.Header) } return rws.handlerHeader } func (w *responseWriter) WriteHeader(code int) { rws := w.rws if rws == nil { panic("WriteHeader called after Handler finished") } rws.writeHeader(code) } func (rws *responseWriterState) writeHeader(code int) { if !rws.wroteHeader { rws.wroteHeader = true rws.status = code if len(rws.handlerHeader) > 0 { rws.snapHeader = cloneHeader(rws.handlerHeader) } } } func cloneHeader(h http.Header) http.Header { h2 := make(http.Header, len(h)) for k, vv := range h { vv2 := make([]string, len(vv)) copy(vv2, vv) h2[k] = vv2 } return h2 } // The Life Of A Write is like this: // // * Handler calls w.Write or w.WriteString -> // * -> rws.bw (*bufio.Writer) -> // * (Handler might call Flush) // * -> chunkWriter{rws} // * -> responseWriterState.writeChunk(p []byte) // * -> responseWriterState.writeChunk (most of the magic; see comment there) func (w *responseWriter) Write(p []byte) (n int, err error) { return w.write(len(p), p, "") } func (w *responseWriter) WriteString(s string) (n int, err error) { return w.write(len(s), nil, s) } // either dataB or dataS is non-zero. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) { rws := w.rws if rws == nil { panic("Write called after Handler finished") } if !rws.wroteHeader { w.WriteHeader(200) } if !bodyAllowedForStatus(rws.status) { return 0, http.ErrBodyNotAllowed } rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen { // TODO: send a RST_STREAM return 0, errors.New("http2: handler wrote more than declared Content-Length") } if dataB != nil { return rws.bw.Write(dataB) } else { return rws.bw.WriteString(dataS) } } func (w *responseWriter) handlerDone() { rws := w.rws dirty := rws.dirty rws.handlerDone = true w.Flush() w.rws = nil if !dirty { // Only recycle the pool if all prior Write calls to // the serverConn goroutine completed successfully. If // they returned earlier due to resets from the peer // there might still be write goroutines outstanding // from the serverConn referencing the rws memory. See // issue 20704. responseWriterStatePool.Put(rws) } } // Push errors. var ( ErrRecursivePush = errors.New("http2: recursive push not allowed") ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS") ) // pushOptions is the internal version of http.PushOptions, which we // cannot include here because it's only defined in Go 1.8 and later. type pushOptions struct { Method string Header http.Header } func (w *responseWriter) push(target string, opts pushOptions) error { st := w.rws.stream sc := st.sc sc.serveG.checkNotOn() // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream." // http://tools.ietf.org/html/rfc7540#section-6.6 if st.isPushed() { return ErrRecursivePush } // Default options. if opts.Method == "" { opts.Method = "GET" } if opts.Header == nil { opts.Header = http.Header{} } wantScheme := "http" if w.rws.req.TLS != nil { wantScheme = "https" } // Validate the request. u, err := url.Parse(target) if err != nil { return err } if u.Scheme == "" { if !strings.HasPrefix(target, "/") { return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target) } u.Scheme = wantScheme u.Host = w.rws.req.Host } else { if u.Scheme != wantScheme { return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme) } if u.Host == "" { return errors.New("URL must have a host") } } for k := range opts.Header { if strings.HasPrefix(k, ":") { return fmt.Errorf("promised request headers cannot include pseudo header %q", k) } // These headers are meaningful only if the request has a body, // but PUSH_PROMISE requests cannot have a body. // http://tools.ietf.org/html/rfc7540#section-8.2 // Also disallow Host, since the promised URL must be absolute. switch strings.ToLower(k) { case "content-length", "content-encoding", "trailer", "te", "expect", "host": return fmt.Errorf("promised request headers cannot include %q", k) } } if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil { return err } // The RFC effectively limits promised requests to GET and HEAD: // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]" // http://tools.ietf.org/html/rfc7540#section-8.2 if opts.Method != "GET" && opts.Method != "HEAD" { return fmt.Errorf("method %q must be GET or HEAD", opts.Method) } msg := &startPushRequest{ parent: st, method: opts.Method, url: u, header: cloneHeader(opts.Header), done: errChanPool.Get().(chan error), } select { case <-sc.doneServing: return errClientDisconnected case <-st.cw: return errStreamClosed case sc.serveMsgCh <- msg: } select { case <-sc.doneServing: return errClientDisconnected case <-st.cw: return errStreamClosed case err := <-msg.done: errChanPool.Put(msg.done) return err } } type startPushRequest struct { parent *stream method string url *url.URL header http.Header done chan error } func (sc *serverConn) startPush(msg *startPushRequest) { sc.serveG.check() // http://tools.ietf.org/html/rfc7540#section-6.6. // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that // is in either the "open" or "half-closed (remote)" state. if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote { // responseWriter.Push checks that the stream is peer-initiaed. msg.done <- errStreamClosed return } // http://tools.ietf.org/html/rfc7540#section-6.6. if !sc.pushEnabled { msg.done <- http.ErrNotSupported return } // PUSH_PROMISE frames must be sent in increasing order by stream ID, so // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE // is written. Once the ID is allocated, we start the request handler. allocatePromisedID := func() (uint32, error) { sc.serveG.check() // Check this again, just in case. Technically, we might have received // an updated SETTINGS by the time we got around to writing this frame. if !sc.pushEnabled { return 0, http.ErrNotSupported } // http://tools.ietf.org/html/rfc7540#section-6.5.2. if sc.curPushedStreams+1 > sc.clientMaxStreams { return 0, ErrPushLimitReached } // http://tools.ietf.org/html/rfc7540#section-5.1.1. // Streams initiated by the server MUST use even-numbered identifiers. // A server that is unable to establish a new stream identifier can send a GOAWAY // frame so that the client is forced to open a new connection for new streams. if sc.maxPushPromiseID+2 >= 1<<31 { sc.startGracefulShutdownInternal() return 0, ErrPushLimitReached } sc.maxPushPromiseID += 2 promisedID := sc.maxPushPromiseID // http://tools.ietf.org/html/rfc7540#section-8.2. // Strictly speaking, the new stream should start in "reserved (local)", then // transition to "half closed (remote)" after sending the initial HEADERS, but // we start in "half closed (remote)" for simplicity. // See further comments at the definition of stateHalfClosedRemote. promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote) rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{ method: msg.method, scheme: msg.url.Scheme, authority: msg.url.Host, path: msg.url.RequestURI(), header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE }) if err != nil { // Should not happen, since we've already validated msg.url. panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err)) } go sc.runHandler(rw, req, sc.handler.ServeHTTP) return promisedID, nil } sc.writeFrame(FrameWriteRequest{ write: &writePushPromise{ streamID: msg.parent.id, method: msg.method, url: msg.url, h: msg.header, allocatePromisedID: allocatePromisedID, }, stream: msg.parent, done: msg.done, }) } // foreachHeaderElement splits v according to the "#rule" construction // in RFC 2616 section 2.1 and calls fn for each non-empty element. func foreachHeaderElement(v string, fn func(string)) { v = textproto.TrimString(v) if v == "" { return } if !strings.Contains(v, ",") { fn(v) return } for _, f := range strings.Split(v, ",") { if f = textproto.TrimString(f); f != "" { fn(f) } } } // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2 var connHeaders = []string{ "Connection", "Keep-Alive", "Proxy-Connection", "Transfer-Encoding", "Upgrade", } // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request, // per RFC 7540 Section 8.1.2.2. // The returned error is reported to users. func checkValidHTTP2RequestHeaders(h http.Header) error { for _, k := range connHeaders { if _, ok := h[k]; ok { return fmt.Errorf("request header %q is not valid in HTTP/2", k) } } te := h["Te"] if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) { return errors.New(`request header "TE" may only be "trailers" in HTTP/2`) } return nil } func new400Handler(err error) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusBadRequest) } } // ValidTrailerHeader reports whether name is a valid header field name to appear // in trailers. // See: http://tools.ietf.org/html/rfc7230#section-4.1.2 func ValidTrailerHeader(name string) bool { name = http.CanonicalHeaderKey(name) if strings.HasPrefix(name, "If-") || badTrailer[name] { return false } return true } var badTrailer = map[string]bool{ "Authorization": true, "Cache-Control": true, "Connection": true, "Content-Encoding": true, "Content-Length": true, "Content-Range": true, "Content-Type": true, "Expect": true, "Host": true, "Keep-Alive": true, "Max-Forwards": true, "Pragma": true, "Proxy-Authenticate": true, "Proxy-Authorization": true, "Proxy-Connection": true, "Range": true, "Realm": true, "Te": true, "Trailer": true, "Transfer-Encoding": true, "Www-Authenticate": true, } // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives // disabled. See comments on h1ServerShutdownChan above for why // the code is written this way. func h1ServerKeepAlivesDisabled(hs *http.Server) bool { var x interface{} = hs type I interface { doKeepAlives() bool } if hs, ok := x.(I); ok { return !hs.doKeepAlives() } return false } lxd-2.0.11/dist/src/golang.org/x/net/http2/pipe_test.go0000644061062106075000000000533213172163402023702 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bytes" "errors" "io" "io/ioutil" "testing" ) func TestPipeClose(t *testing.T) { var p pipe p.b = new(bytes.Buffer) a := errors.New("a") b := errors.New("b") p.CloseWithError(a) p.CloseWithError(b) _, err := p.Read(make([]byte, 1)) if err != a { t.Errorf("err = %v want %v", err, a) } } func TestPipeDoneChan(t *testing.T) { var p pipe done := p.Done() select { case <-done: t.Fatal("done too soon") default: } p.CloseWithError(io.EOF) select { case <-done: default: t.Fatal("should be done") } } func TestPipeDoneChan_ErrFirst(t *testing.T) { var p pipe p.CloseWithError(io.EOF) done := p.Done() select { case <-done: default: t.Fatal("should be done") } } func TestPipeDoneChan_Break(t *testing.T) { var p pipe done := p.Done() select { case <-done: t.Fatal("done too soon") default: } p.BreakWithError(io.EOF) select { case <-done: default: t.Fatal("should be done") } } func TestPipeDoneChan_Break_ErrFirst(t *testing.T) { var p pipe p.BreakWithError(io.EOF) done := p.Done() select { case <-done: default: t.Fatal("should be done") } } func TestPipeCloseWithError(t *testing.T) { p := &pipe{b: new(bytes.Buffer)} const body = "foo" io.WriteString(p, body) a := errors.New("test error") p.CloseWithError(a) all, err := ioutil.ReadAll(p) if string(all) != body { t.Errorf("read bytes = %q; want %q", all, body) } if err != a { t.Logf("read error = %v, %v", err, a) } // Read and Write should fail. if n, err := p.Write([]byte("abc")); err != errClosedPipeWrite || n != 0 { t.Errorf("Write(abc) after close\ngot %v, %v\nwant 0, %v", n, err, errClosedPipeWrite) } if n, err := p.Read(make([]byte, 1)); err == nil || n != 0 { t.Errorf("Read() after close\ngot %v, nil\nwant 0, %v", n, errClosedPipeWrite) } } func TestPipeBreakWithError(t *testing.T) { p := &pipe{b: new(bytes.Buffer)} io.WriteString(p, "foo") a := errors.New("test err") p.BreakWithError(a) all, err := ioutil.ReadAll(p) if string(all) != "" { t.Errorf("read bytes = %q; want empty string", all) } if err != a { t.Logf("read error = %v, %v", err, a) } if p.b != nil { t.Errorf("buffer should be nil after BreakWithError") } // Write should succeed silently. if n, err := p.Write([]byte("abc")); err != nil || n != 3 { t.Errorf("Write(abc) after break\ngot %v, %v\nwant 0, nil", n, err) } if p.b != nil { t.Errorf("buffer should be nil after Write") } // Read should fail. if n, err := p.Read(make([]byte, 1)); err == nil || n != 0 { t.Errorf("Read() after close\ngot %v, nil\nwant 0, not nil", n) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/pipe.go0000644061062106075000000000747413172163402022654 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "errors" "io" "sync" ) // pipe is a goroutine-safe io.Reader/io.Writer pair. It's like // io.Pipe except there are no PipeReader/PipeWriter halves, and the // underlying buffer is an interface. (io.Pipe is always unbuffered) type pipe struct { mu sync.Mutex c sync.Cond // c.L lazily initialized to &p.mu b pipeBuffer // nil when done reading err error // read error once empty. non-nil means closed. breakErr error // immediate read error (caller doesn't see rest of b) donec chan struct{} // closed on error readFn func() // optional code to run in Read before error } type pipeBuffer interface { Len() int io.Writer io.Reader } func (p *pipe) Len() int { p.mu.Lock() defer p.mu.Unlock() if p.b == nil { return 0 } return p.b.Len() } // Read waits until data is available and copies bytes // from the buffer into p. func (p *pipe) Read(d []byte) (n int, err error) { p.mu.Lock() defer p.mu.Unlock() if p.c.L == nil { p.c.L = &p.mu } for { if p.breakErr != nil { return 0, p.breakErr } if p.b != nil && p.b.Len() > 0 { return p.b.Read(d) } if p.err != nil { if p.readFn != nil { p.readFn() // e.g. copy trailers p.readFn = nil // not sticky like p.err } p.b = nil return 0, p.err } p.c.Wait() } } var errClosedPipeWrite = errors.New("write on closed buffer") // Write copies bytes from p into the buffer and wakes a reader. // It is an error to write more data than the buffer can hold. func (p *pipe) Write(d []byte) (n int, err error) { p.mu.Lock() defer p.mu.Unlock() if p.c.L == nil { p.c.L = &p.mu } defer p.c.Signal() if p.err != nil { return 0, errClosedPipeWrite } if p.breakErr != nil { return len(d), nil // discard when there is no reader } return p.b.Write(d) } // CloseWithError causes the next Read (waking up a current blocked // Read if needed) to return the provided err after all data has been // read. // // The error must be non-nil. func (p *pipe) CloseWithError(err error) { p.closeWithError(&p.err, err, nil) } // BreakWithError causes the next Read (waking up a current blocked // Read if needed) to return the provided err immediately, without // waiting for unread data. func (p *pipe) BreakWithError(err error) { p.closeWithError(&p.breakErr, err, nil) } // closeWithErrorAndCode is like CloseWithError but also sets some code to run // in the caller's goroutine before returning the error. func (p *pipe) closeWithErrorAndCode(err error, fn func()) { p.closeWithError(&p.err, err, fn) } func (p *pipe) closeWithError(dst *error, err error, fn func()) { if err == nil { panic("err must be non-nil") } p.mu.Lock() defer p.mu.Unlock() if p.c.L == nil { p.c.L = &p.mu } defer p.c.Signal() if *dst != nil { // Already been done. return } p.readFn = fn if dst == &p.breakErr { p.b = nil } *dst = err p.closeDoneLocked() } // requires p.mu be held. func (p *pipe) closeDoneLocked() { if p.donec == nil { return } // Close if unclosed. This isn't racy since we always // hold p.mu while closing. select { case <-p.donec: default: close(p.donec) } } // Err returns the error (if any) first set by BreakWithError or CloseWithError. func (p *pipe) Err() error { p.mu.Lock() defer p.mu.Unlock() if p.breakErr != nil { return p.breakErr } return p.err } // Done returns a channel which is closed if and when this pipe is closed // with CloseWithError. func (p *pipe) Done() <-chan struct{} { p.mu.Lock() defer p.mu.Unlock() if p.donec == nil { p.donec = make(chan struct{}) if p.err != nil || p.breakErr != nil { // Already hit an error. p.closeDoneLocked() } } return p.donec } lxd-2.0.11/dist/src/golang.org/x/net/http2/not_go19.go0000644061062106075000000000050513172163402023342 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 package http2 import ( "net/http" ) func configureServer19(s *http.Server, conf *Server) error { // not supported prior to go1.9 return nil } lxd-2.0.11/dist/src/golang.org/x/net/http2/not_go18.go0000644061062106075000000000117013172163402023340 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.8 package http2 import ( "io" "net/http" ) func configureServer18(h1 *http.Server, h2 *Server) error { // No IdleTimeout to sync prior to Go 1.8. return nil } func shouldLogPanic(panicValue interface{}) bool { return panicValue != nil } func reqGetBody(req *http.Request) func() (io.ReadCloser, error) { return nil } func reqBodyIsNoBody(io.ReadCloser) bool { return false } func go18httpNoBody() io.ReadCloser { return nil } // for tests only lxd-2.0.11/dist/src/golang.org/x/net/http2/not_go17.go0000644061062106075000000000462613172163402023350 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package http2 import ( "crypto/tls" "net" "net/http" "time" ) type contextContext interface { Done() <-chan struct{} Err() error } type fakeContext struct{} func (fakeContext) Done() <-chan struct{} { return nil } func (fakeContext) Err() error { panic("should not be called") } func reqContext(r *http.Request) fakeContext { return fakeContext{} } func setResponseUncompressed(res *http.Response) { // Nothing. } type clientTrace struct{} func requestTrace(*http.Request) *clientTrace { return nil } func traceGotConn(*http.Request, *ClientConn) {} func traceFirstResponseByte(*clientTrace) {} func traceWroteHeaders(*clientTrace) {} func traceWroteRequest(*clientTrace, error) {} func traceGot100Continue(trace *clientTrace) {} func traceWait100Continue(trace *clientTrace) {} func nop() {} func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { return nil, nop } func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) { return ctx, nop } func requestWithContext(req *http.Request, ctx contextContext) *http.Request { return req } // temporary copy of Go 1.6's private tls.Config.clone: func cloneTLSConfig(c *tls.Config) *tls.Config { return &tls.Config{ Rand: c.Rand, Time: c.Time, Certificates: c.Certificates, NameToCertificate: c.NameToCertificate, GetCertificate: c.GetCertificate, RootCAs: c.RootCAs, NextProtos: c.NextProtos, ServerName: c.ServerName, ClientAuth: c.ClientAuth, ClientCAs: c.ClientCAs, InsecureSkipVerify: c.InsecureSkipVerify, CipherSuites: c.CipherSuites, PreferServerCipherSuites: c.PreferServerCipherSuites, SessionTicketsDisabled: c.SessionTicketsDisabled, SessionTicketKey: c.SessionTicketKey, ClientSessionCache: c.ClientSessionCache, MinVersion: c.MinVersion, MaxVersion: c.MaxVersion, CurvePreferences: c.CurvePreferences, } } func (cc *ClientConn) Ping(ctx contextContext) error { return cc.ping(ctx) } func (t *Transport) idleConnTimeout() time.Duration { return 0 } lxd-2.0.11/dist/src/golang.org/x/net/http2/not_go16.go0000644061062106075000000000063413172163402023342 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.6 package http2 import ( "net/http" "time" ) func configureTransport(t1 *http.Transport) (*Transport, error) { return nil, errTransportVersion } func transportExpectContinueTimeout(t1 *http.Transport) time.Duration { return 0 } lxd-2.0.11/dist/src/golang.org/x/net/http2/http2_test.go0000644061062106075000000001147013172163402024006 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bytes" "errors" "flag" "fmt" "net/http" "os/exec" "strconv" "strings" "testing" "golang.org/x/net/http2/hpack" ) var knownFailing = flag.Bool("known_failing", false, "Run known-failing tests.") func condSkipFailingTest(t *testing.T) { if !*knownFailing { t.Skip("Skipping known-failing test without --known_failing") } } func init() { inTests = true DebugGoroutines = true flag.BoolVar(&VerboseLogs, "verboseh2", VerboseLogs, "Verbose HTTP/2 debug logging") } func TestSettingString(t *testing.T) { tests := []struct { s Setting want string }{ {Setting{SettingMaxFrameSize, 123}, "[MAX_FRAME_SIZE = 123]"}, {Setting{1<<16 - 1, 123}, "[UNKNOWN_SETTING_65535 = 123]"}, } for i, tt := range tests { got := fmt.Sprint(tt.s) if got != tt.want { t.Errorf("%d. for %#v, string = %q; want %q", i, tt.s, got, tt.want) } } } type twriter struct { t testing.TB st *serverTester // optional } func (w twriter) Write(p []byte) (n int, err error) { if w.st != nil { ps := string(p) for _, phrase := range w.st.logFilter { if strings.Contains(ps, phrase) { return len(p), nil // no logging } } } w.t.Logf("%s", p) return len(p), nil } // like encodeHeader, but don't add implicit pseudo headers. func encodeHeaderNoImplicit(t *testing.T, headers ...string) []byte { var buf bytes.Buffer enc := hpack.NewEncoder(&buf) for len(headers) > 0 { k, v := headers[0], headers[1] headers = headers[2:] if err := enc.WriteField(hpack.HeaderField{Name: k, Value: v}); err != nil { t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) } } return buf.Bytes() } // Verify that curl has http2. func requireCurl(t *testing.T) { out, err := dockerLogs(curl(t, "--version")) if err != nil { t.Skipf("failed to determine curl features; skipping test") } if !strings.Contains(string(out), "HTTP2") { t.Skip("curl doesn't support HTTP2; skipping test") } } func curl(t *testing.T, args ...string) (container string) { out, err := exec.Command("docker", append([]string{"run", "-d", "--net=host", "gohttp2/curl"}, args...)...).Output() if err != nil { t.Skipf("Failed to run curl in docker: %v, %s", err, out) } return strings.TrimSpace(string(out)) } // Verify that h2load exists. func requireH2load(t *testing.T) { out, err := dockerLogs(h2load(t, "--version")) if err != nil { t.Skipf("failed to probe h2load; skipping test: %s", out) } if !strings.Contains(string(out), "h2load nghttp2/") { t.Skipf("h2load not present; skipping test. (Output=%q)", out) } } func h2load(t *testing.T, args ...string) (container string) { out, err := exec.Command("docker", append([]string{"run", "-d", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl"}, args...)...).Output() if err != nil { t.Skipf("Failed to run h2load in docker: %v, %s", err, out) } return strings.TrimSpace(string(out)) } type puppetCommand struct { fn func(w http.ResponseWriter, r *http.Request) done chan<- bool } type handlerPuppet struct { ch chan puppetCommand } func newHandlerPuppet() *handlerPuppet { return &handlerPuppet{ ch: make(chan puppetCommand), } } func (p *handlerPuppet) act(w http.ResponseWriter, r *http.Request) { for cmd := range p.ch { cmd.fn(w, r) cmd.done <- true } } func (p *handlerPuppet) done() { close(p.ch) } func (p *handlerPuppet) do(fn func(http.ResponseWriter, *http.Request)) { done := make(chan bool) p.ch <- puppetCommand{fn, done} <-done } func dockerLogs(container string) ([]byte, error) { out, err := exec.Command("docker", "wait", container).CombinedOutput() if err != nil { return out, err } exitStatus, err := strconv.Atoi(strings.TrimSpace(string(out))) if err != nil { return out, errors.New("unexpected exit status from docker wait") } out, err = exec.Command("docker", "logs", container).CombinedOutput() exec.Command("docker", "rm", container).Run() if err == nil && exitStatus != 0 { err = fmt.Errorf("exit status %d: %s", exitStatus, out) } return out, err } func kill(container string) { exec.Command("docker", "kill", container).Run() exec.Command("docker", "rm", container).Run() } func cleanDate(res *http.Response) { if d := res.Header["Date"]; len(d) == 1 { d[0] = "XXX" } } func TestSorterPoolAllocs(t *testing.T) { ss := []string{"a", "b", "c"} h := http.Header{ "a": nil, "b": nil, "c": nil, } sorter := new(sorter) if allocs := testing.AllocsPerRun(100, func() { sorter.SortStrings(ss) }); allocs >= 1 { t.Logf("SortStrings allocs = %v; want <1", allocs) } if allocs := testing.AllocsPerRun(5, func() { if len(sorter.Keys(h)) != 3 { t.Fatal("wrong result") } }); allocs > 0 { t.Logf("Keys allocs = %v; want <1", allocs) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/http2.go0000644061062106075000000002323713172163402022753 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package http2 implements the HTTP/2 protocol. // // This package is low-level and intended to be used directly by very // few people. Most users will use it indirectly through the automatic // use by the net/http package (from Go 1.6 and later). // For use in earlier Go versions see ConfigureServer. (Transport support // requires Go 1.6 or later) // // See https://http2.github.io/ for more information on HTTP/2. // // See https://http2.golang.org/ for a test server running this code. // package http2 // import "golang.org/x/net/http2" import ( "bufio" "crypto/tls" "errors" "fmt" "io" "net/http" "os" "sort" "strconv" "strings" "sync" "golang.org/x/net/lex/httplex" ) var ( VerboseLogs bool logFrameWrites bool logFrameReads bool inTests bool ) func init() { e := os.Getenv("GODEBUG") if strings.Contains(e, "http2debug=1") { VerboseLogs = true } if strings.Contains(e, "http2debug=2") { VerboseLogs = true logFrameWrites = true logFrameReads = true } } const ( // ClientPreface is the string that must be sent by new // connections from clients. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" // SETTINGS_MAX_FRAME_SIZE default // http://http2.github.io/http2-spec/#rfc.section.6.5.2 initialMaxFrameSize = 16384 // NextProtoTLS is the NPN/ALPN protocol negotiated during // HTTP/2's TLS setup. NextProtoTLS = "h2" // http://http2.github.io/http2-spec/#SettingValues initialHeaderTableSize = 4096 initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size defaultMaxReadFrameSize = 1 << 20 ) var ( clientPreface = []byte(ClientPreface) ) type streamState int // HTTP/2 stream states. // // See http://tools.ietf.org/html/rfc7540#section-5.1. // // For simplicity, the server code merges "reserved (local)" into // "half-closed (remote)". This is one less state transition to track. // The only downside is that we send PUSH_PROMISEs slightly less // liberally than allowable. More discussion here: // https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html // // "reserved (remote)" is omitted since the client code does not // support server push. const ( stateIdle streamState = iota stateOpen stateHalfClosedLocal stateHalfClosedRemote stateClosed ) var stateName = [...]string{ stateIdle: "Idle", stateOpen: "Open", stateHalfClosedLocal: "HalfClosedLocal", stateHalfClosedRemote: "HalfClosedRemote", stateClosed: "Closed", } func (st streamState) String() string { return stateName[st] } // Setting is a setting parameter: which setting it is, and its value. type Setting struct { // ID is which setting is being set. // See http://http2.github.io/http2-spec/#SettingValues ID SettingID // Val is the value. Val uint32 } func (s Setting) String() string { return fmt.Sprintf("[%v = %d]", s.ID, s.Val) } // Valid reports whether the setting is valid. func (s Setting) Valid() error { // Limits and error codes from 6.5.2 Defined SETTINGS Parameters switch s.ID { case SettingEnablePush: if s.Val != 1 && s.Val != 0 { return ConnectionError(ErrCodeProtocol) } case SettingInitialWindowSize: if s.Val > 1<<31-1 { return ConnectionError(ErrCodeFlowControl) } case SettingMaxFrameSize: if s.Val < 16384 || s.Val > 1<<24-1 { return ConnectionError(ErrCodeProtocol) } } return nil } // A SettingID is an HTTP/2 setting as defined in // http://http2.github.io/http2-spec/#iana-settings type SettingID uint16 const ( SettingHeaderTableSize SettingID = 0x1 SettingEnablePush SettingID = 0x2 SettingMaxConcurrentStreams SettingID = 0x3 SettingInitialWindowSize SettingID = 0x4 SettingMaxFrameSize SettingID = 0x5 SettingMaxHeaderListSize SettingID = 0x6 ) var settingName = map[SettingID]string{ SettingHeaderTableSize: "HEADER_TABLE_SIZE", SettingEnablePush: "ENABLE_PUSH", SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS", SettingInitialWindowSize: "INITIAL_WINDOW_SIZE", SettingMaxFrameSize: "MAX_FRAME_SIZE", SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE", } func (s SettingID) String() string { if v, ok := settingName[s]; ok { return v } return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s)) } var ( errInvalidHeaderFieldName = errors.New("http2: invalid header field name") errInvalidHeaderFieldValue = errors.New("http2: invalid header field value") ) // validWireHeaderFieldName reports whether v is a valid header field // name (key). See httplex.ValidHeaderName for the base rules. // // Further, http2 says: // "Just as in HTTP/1.x, header field names are strings of ASCII // characters that are compared in a case-insensitive // fashion. However, header field names MUST be converted to // lowercase prior to their encoding in HTTP/2. " func validWireHeaderFieldName(v string) bool { if len(v) == 0 { return false } for _, r := range v { if !httplex.IsTokenRune(r) { return false } if 'A' <= r && r <= 'Z' { return false } } return true } var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n) func init() { for i := 100; i <= 999; i++ { if v := http.StatusText(i); v != "" { httpCodeStringCommon[i] = strconv.Itoa(i) } } } func httpCodeString(code int) string { if s, ok := httpCodeStringCommon[code]; ok { return s } return strconv.Itoa(code) } // from pkg io type stringWriter interface { WriteString(s string) (n int, err error) } // A gate lets two goroutines coordinate their activities. type gate chan struct{} func (g gate) Done() { g <- struct{}{} } func (g gate) Wait() { <-g } // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed). type closeWaiter chan struct{} // Init makes a closeWaiter usable. // It exists because so a closeWaiter value can be placed inside a // larger struct and have the Mutex and Cond's memory in the same // allocation. func (cw *closeWaiter) Init() { *cw = make(chan struct{}) } // Close marks the closeWaiter as closed and unblocks any waiters. func (cw closeWaiter) Close() { close(cw) } // Wait waits for the closeWaiter to become closed. func (cw closeWaiter) Wait() { <-cw } // bufferedWriter is a buffered writer that writes to w. // Its buffered writer is lazily allocated as needed, to minimize // idle memory usage with many connections. type bufferedWriter struct { w io.Writer // immutable bw *bufio.Writer // non-nil when data is buffered } func newBufferedWriter(w io.Writer) *bufferedWriter { return &bufferedWriter{w: w} } // bufWriterPoolBufferSize is the size of bufio.Writer's // buffers created using bufWriterPool. // // TODO: pick a less arbitrary value? this is a bit under // (3 x typical 1500 byte MTU) at least. Other than that, // not much thought went into it. const bufWriterPoolBufferSize = 4 << 10 var bufWriterPool = sync.Pool{ New: func() interface{} { return bufio.NewWriterSize(nil, bufWriterPoolBufferSize) }, } func (w *bufferedWriter) Available() int { if w.bw == nil { return bufWriterPoolBufferSize } return w.bw.Available() } func (w *bufferedWriter) Write(p []byte) (n int, err error) { if w.bw == nil { bw := bufWriterPool.Get().(*bufio.Writer) bw.Reset(w.w) w.bw = bw } return w.bw.Write(p) } func (w *bufferedWriter) Flush() error { bw := w.bw if bw == nil { return nil } err := bw.Flush() bw.Reset(nil) bufWriterPool.Put(bw) w.bw = nil return err } func mustUint31(v int32) uint32 { if v < 0 || v > 2147483647 { panic("out of range") } return uint32(v) } // bodyAllowedForStatus reports whether a given response status code // permits a body. See RFC 2616, section 4.4. func bodyAllowedForStatus(status int) bool { switch { case status >= 100 && status <= 199: return false case status == 204: return false case status == 304: return false } return true } type httpError struct { msg string timeout bool } func (e *httpError) Error() string { return e.msg } func (e *httpError) Timeout() bool { return e.timeout } func (e *httpError) Temporary() bool { return true } var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true} type connectionStater interface { ConnectionState() tls.ConnectionState } var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }} type sorter struct { v []string // owned by sorter } func (s *sorter) Len() int { return len(s.v) } func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] } func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] } // Keys returns the sorted keys of h. // // The returned slice is only valid until s used again or returned to // its pool. func (s *sorter) Keys(h http.Header) []string { keys := s.v[:0] for k := range h { keys = append(keys, k) } s.v = keys sort.Sort(s) return keys } func (s *sorter) SortStrings(ss []string) { // Our sorter works on s.v, which sorter owns, so // stash it away while we sort the user's buffer. save := s.v s.v = ss sort.Sort(s) s.v = save } // validPseudoPath reports whether v is a valid :path pseudo-header // value. It must be either: // // *) a non-empty string starting with '/' // *) the string '*', for OPTIONS requests. // // For now this is only used a quick check for deciding when to clean // up Opaque URLs before sending requests from the Transport. // See golang.org/issue/16847 // // We used to enforce that the path also didn't start with "//", but // Google's GFE accepts such paths and Chrome sends them, so ignore // that part of the spec. See golang.org/issue/19103. func validPseudoPath(v string) bool { return (len(v) > 0 && v[0] == '/') || v == "*" } lxd-2.0.11/dist/src/golang.org/x/net/http2/hpack/0000755061062106075000000000000013172163402022442 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/http2/hpack/tables_test.go0000644061062106075000000002120513172163402025302 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hpack import ( "bufio" "regexp" "strconv" "strings" "testing" ) func TestHeaderFieldTable(t *testing.T) { table := &headerFieldTable{} table.init() table.addEntry(pair("key1", "value1-1")) table.addEntry(pair("key2", "value2-1")) table.addEntry(pair("key1", "value1-2")) table.addEntry(pair("key3", "value3-1")) table.addEntry(pair("key4", "value4-1")) table.addEntry(pair("key2", "value2-2")) // Tests will be run twice: once before evicting anything, and // again after evicting the three oldest entries. tests := []struct { f HeaderField beforeWantStaticI uint64 beforeWantMatch bool afterWantStaticI uint64 afterWantMatch bool }{ {HeaderField{"key1", "value1-1", false}, 1, true, 0, false}, {HeaderField{"key1", "value1-2", false}, 3, true, 0, false}, {HeaderField{"key1", "value1-3", false}, 3, false, 0, false}, {HeaderField{"key2", "value2-1", false}, 2, true, 3, false}, {HeaderField{"key2", "value2-2", false}, 6, true, 3, true}, {HeaderField{"key2", "value2-3", false}, 6, false, 3, false}, {HeaderField{"key4", "value4-1", false}, 5, true, 2, true}, // Name match only, because sensitive. {HeaderField{"key4", "value4-1", true}, 5, false, 2, false}, // Key not found. {HeaderField{"key5", "value5-x", false}, 0, false, 0, false}, } staticToDynamic := func(i uint64) uint64 { if i == 0 { return 0 } return uint64(table.len()) - i + 1 // dynamic is the reversed table } searchStatic := func(f HeaderField) (uint64, bool) { old := staticTable staticTable = table defer func() { staticTable = old }() return staticTable.search(f) } searchDynamic := func(f HeaderField) (uint64, bool) { return table.search(f) } for _, test := range tests { gotI, gotMatch := searchStatic(test.f) if wantI, wantMatch := test.beforeWantStaticI, test.beforeWantMatch; gotI != wantI || gotMatch != wantMatch { t.Errorf("before evictions: searchStatic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) } gotI, gotMatch = searchDynamic(test.f) wantDynamicI := staticToDynamic(test.beforeWantStaticI) if wantI, wantMatch := wantDynamicI, test.beforeWantMatch; gotI != wantI || gotMatch != wantMatch { t.Errorf("before evictions: searchDynamic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) } } table.evictOldest(3) for _, test := range tests { gotI, gotMatch := searchStatic(test.f) if wantI, wantMatch := test.afterWantStaticI, test.afterWantMatch; gotI != wantI || gotMatch != wantMatch { t.Errorf("after evictions: searchStatic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) } gotI, gotMatch = searchDynamic(test.f) wantDynamicI := staticToDynamic(test.afterWantStaticI) if wantI, wantMatch := wantDynamicI, test.afterWantMatch; gotI != wantI || gotMatch != wantMatch { t.Errorf("after evictions: searchDynamic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) } } } func TestHeaderFieldTable_LookupMapEviction(t *testing.T) { table := &headerFieldTable{} table.init() table.addEntry(pair("key1", "value1-1")) table.addEntry(pair("key2", "value2-1")) table.addEntry(pair("key1", "value1-2")) table.addEntry(pair("key3", "value3-1")) table.addEntry(pair("key4", "value4-1")) table.addEntry(pair("key2", "value2-2")) // evict all pairs table.evictOldest(table.len()) if l := table.len(); l > 0 { t.Errorf("table.len() = %d, want 0", l) } if l := len(table.byName); l > 0 { t.Errorf("len(table.byName) = %d, want 0", l) } if l := len(table.byNameValue); l > 0 { t.Errorf("len(table.byNameValue) = %d, want 0", l) } } func TestStaticTable(t *testing.T) { fromSpec := ` +-------+-----------------------------+---------------+ | 1 | :authority | | | 2 | :method | GET | | 3 | :method | POST | | 4 | :path | / | | 5 | :path | /index.html | | 6 | :scheme | http | | 7 | :scheme | https | | 8 | :status | 200 | | 9 | :status | 204 | | 10 | :status | 206 | | 11 | :status | 304 | | 12 | :status | 400 | | 13 | :status | 404 | | 14 | :status | 500 | | 15 | accept-charset | | | 16 | accept-encoding | gzip, deflate | | 17 | accept-language | | | 18 | accept-ranges | | | 19 | accept | | | 20 | access-control-allow-origin | | | 21 | age | | | 22 | allow | | | 23 | authorization | | | 24 | cache-control | | | 25 | content-disposition | | | 26 | content-encoding | | | 27 | content-language | | | 28 | content-length | | | 29 | content-location | | | 30 | content-range | | | 31 | content-type | | | 32 | cookie | | | 33 | date | | | 34 | etag | | | 35 | expect | | | 36 | expires | | | 37 | from | | | 38 | host | | | 39 | if-match | | | 40 | if-modified-since | | | 41 | if-none-match | | | 42 | if-range | | | 43 | if-unmodified-since | | | 44 | last-modified | | | 45 | link | | | 46 | location | | | 47 | max-forwards | | | 48 | proxy-authenticate | | | 49 | proxy-authorization | | | 50 | range | | | 51 | referer | | | 52 | refresh | | | 53 | retry-after | | | 54 | server | | | 55 | set-cookie | | | 56 | strict-transport-security | | | 57 | transfer-encoding | | | 58 | user-agent | | | 59 | vary | | | 60 | via | | | 61 | www-authenticate | | +-------+-----------------------------+---------------+ ` bs := bufio.NewScanner(strings.NewReader(fromSpec)) re := regexp.MustCompile(`\| (\d+)\s+\| (\S+)\s*\| (\S(.*\S)?)?\s+\|`) for bs.Scan() { l := bs.Text() if !strings.Contains(l, "|") { continue } m := re.FindStringSubmatch(l) if m == nil { continue } i, err := strconv.Atoi(m[1]) if err != nil { t.Errorf("Bogus integer on line %q", l) continue } if i < 1 || i > staticTable.len() { t.Errorf("Bogus index %d on line %q", i, l) continue } if got, want := staticTable.ents[i-1].Name, m[2]; got != want { t.Errorf("header index %d name = %q; want %q", i, got, want) } if got, want := staticTable.ents[i-1].Value, m[3]; got != want { t.Errorf("header index %d value = %q; want %q", i, got, want) } } if err := bs.Err(); err != nil { t.Error(err) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/hpack/tables.go0000644061062106075000000002271513172163402024252 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hpack import ( "fmt" ) // headerFieldTable implements a list of HeaderFields. // This is used to implement the static and dynamic tables. type headerFieldTable struct { // For static tables, entries are never evicted. // // For dynamic tables, entries are evicted from ents[0] and added to the end. // Each entry has a unique id that starts at one and increments for each // entry that is added. This unique id is stable across evictions, meaning // it can be used as a pointer to a specific entry. As in hpack, unique ids // are 1-based. The unique id for ents[k] is k + evictCount + 1. // // Zero is not a valid unique id. // // evictCount should not overflow in any remotely practical situation. In // practice, we will have one dynamic table per HTTP/2 connection. If we // assume a very powerful server that handles 1M QPS per connection and each // request adds (then evicts) 100 entries from the table, it would still take // 2M years for evictCount to overflow. ents []HeaderField evictCount uint64 // byName maps a HeaderField name to the unique id of the newest entry with // the same name. See above for a definition of "unique id". byName map[string]uint64 // byNameValue maps a HeaderField name/value pair to the unique id of the newest // entry with the same name and value. See above for a definition of "unique id". byNameValue map[pairNameValue]uint64 } type pairNameValue struct { name, value string } func (t *headerFieldTable) init() { t.byName = make(map[string]uint64) t.byNameValue = make(map[pairNameValue]uint64) } // len reports the number of entries in the table. func (t *headerFieldTable) len() int { return len(t.ents) } // addEntry adds a new entry. func (t *headerFieldTable) addEntry(f HeaderField) { id := uint64(t.len()) + t.evictCount + 1 t.byName[f.Name] = id t.byNameValue[pairNameValue{f.Name, f.Value}] = id t.ents = append(t.ents, f) } // evictOldest evicts the n oldest entries in the table. func (t *headerFieldTable) evictOldest(n int) { if n > t.len() { panic(fmt.Sprintf("evictOldest(%v) on table with %v entries", n, t.len())) } for k := 0; k < n; k++ { f := t.ents[k] id := t.evictCount + uint64(k) + 1 if t.byName[f.Name] == id { delete(t.byName, f.Name) } if p := (pairNameValue{f.Name, f.Value}); t.byNameValue[p] == id { delete(t.byNameValue, p) } } copy(t.ents, t.ents[n:]) for k := t.len() - n; k < t.len(); k++ { t.ents[k] = HeaderField{} // so strings can be garbage collected } t.ents = t.ents[:t.len()-n] if t.evictCount+uint64(n) < t.evictCount { panic("evictCount overflow") } t.evictCount += uint64(n) } // search finds f in the table. If there is no match, i is 0. // If both name and value match, i is the matched index and nameValueMatch // becomes true. If only name matches, i points to that index and // nameValueMatch becomes false. // // The returned index is a 1-based HPACK index. For dynamic tables, HPACK says // that index 1 should be the newest entry, but t.ents[0] is the oldest entry, // meaning t.ents is reversed for dynamic tables. Hence, when t is a dynamic // table, the return value i actually refers to the entry t.ents[t.len()-i]. // // All tables are assumed to be a dynamic tables except for the global // staticTable pointer. // // See Section 2.3.3. func (t *headerFieldTable) search(f HeaderField) (i uint64, nameValueMatch bool) { if !f.Sensitive { if id := t.byNameValue[pairNameValue{f.Name, f.Value}]; id != 0 { return t.idToIndex(id), true } } if id := t.byName[f.Name]; id != 0 { return t.idToIndex(id), false } return 0, false } // idToIndex converts a unique id to an HPACK index. // See Section 2.3.3. func (t *headerFieldTable) idToIndex(id uint64) uint64 { if id <= t.evictCount { panic(fmt.Sprintf("id (%v) <= evictCount (%v)", id, t.evictCount)) } k := id - t.evictCount - 1 // convert id to an index t.ents[k] if t != staticTable { return uint64(t.len()) - k // dynamic table } return k + 1 } // http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-07#appendix-B var staticTable = newStaticTable() var staticTableEntries = [...]HeaderField{ {Name: ":authority"}, {Name: ":method", Value: "GET"}, {Name: ":method", Value: "POST"}, {Name: ":path", Value: "/"}, {Name: ":path", Value: "/index.html"}, {Name: ":scheme", Value: "http"}, {Name: ":scheme", Value: "https"}, {Name: ":status", Value: "200"}, {Name: ":status", Value: "204"}, {Name: ":status", Value: "206"}, {Name: ":status", Value: "304"}, {Name: ":status", Value: "400"}, {Name: ":status", Value: "404"}, {Name: ":status", Value: "500"}, {Name: "accept-charset"}, {Name: "accept-encoding", Value: "gzip, deflate"}, {Name: "accept-language"}, {Name: "accept-ranges"}, {Name: "accept"}, {Name: "access-control-allow-origin"}, {Name: "age"}, {Name: "allow"}, {Name: "authorization"}, {Name: "cache-control"}, {Name: "content-disposition"}, {Name: "content-encoding"}, {Name: "content-language"}, {Name: "content-length"}, {Name: "content-location"}, {Name: "content-range"}, {Name: "content-type"}, {Name: "cookie"}, {Name: "date"}, {Name: "etag"}, {Name: "expect"}, {Name: "expires"}, {Name: "from"}, {Name: "host"}, {Name: "if-match"}, {Name: "if-modified-since"}, {Name: "if-none-match"}, {Name: "if-range"}, {Name: "if-unmodified-since"}, {Name: "last-modified"}, {Name: "link"}, {Name: "location"}, {Name: "max-forwards"}, {Name: "proxy-authenticate"}, {Name: "proxy-authorization"}, {Name: "range"}, {Name: "referer"}, {Name: "refresh"}, {Name: "retry-after"}, {Name: "server"}, {Name: "set-cookie"}, {Name: "strict-transport-security"}, {Name: "transfer-encoding"}, {Name: "user-agent"}, {Name: "vary"}, {Name: "via"}, {Name: "www-authenticate"}, } func newStaticTable() *headerFieldTable { t := &headerFieldTable{} t.init() for _, e := range staticTableEntries[:] { t.addEntry(e) } return t } var huffmanCodes = [256]uint32{ 0x1ff8, 0x7fffd8, 0xfffffe2, 0xfffffe3, 0xfffffe4, 0xfffffe5, 0xfffffe6, 0xfffffe7, 0xfffffe8, 0xffffea, 0x3ffffffc, 0xfffffe9, 0xfffffea, 0x3ffffffd, 0xfffffeb, 0xfffffec, 0xfffffed, 0xfffffee, 0xfffffef, 0xffffff0, 0xffffff1, 0xffffff2, 0x3ffffffe, 0xffffff3, 0xffffff4, 0xffffff5, 0xffffff6, 0xffffff7, 0xffffff8, 0xffffff9, 0xffffffa, 0xffffffb, 0x14, 0x3f8, 0x3f9, 0xffa, 0x1ff9, 0x15, 0xf8, 0x7fa, 0x3fa, 0x3fb, 0xf9, 0x7fb, 0xfa, 0x16, 0x17, 0x18, 0x0, 0x1, 0x2, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x5c, 0xfb, 0x7ffc, 0x20, 0xffb, 0x3fc, 0x1ffa, 0x21, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xfc, 0x73, 0xfd, 0x1ffb, 0x7fff0, 0x1ffc, 0x3ffc, 0x22, 0x7ffd, 0x3, 0x23, 0x4, 0x24, 0x5, 0x25, 0x26, 0x27, 0x6, 0x74, 0x75, 0x28, 0x29, 0x2a, 0x7, 0x2b, 0x76, 0x2c, 0x8, 0x9, 0x2d, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7ffe, 0x7fc, 0x3ffd, 0x1ffd, 0xffffffc, 0xfffe6, 0x3fffd2, 0xfffe7, 0xfffe8, 0x3fffd3, 0x3fffd4, 0x3fffd5, 0x7fffd9, 0x3fffd6, 0x7fffda, 0x7fffdb, 0x7fffdc, 0x7fffdd, 0x7fffde, 0xffffeb, 0x7fffdf, 0xffffec, 0xffffed, 0x3fffd7, 0x7fffe0, 0xffffee, 0x7fffe1, 0x7fffe2, 0x7fffe3, 0x7fffe4, 0x1fffdc, 0x3fffd8, 0x7fffe5, 0x3fffd9, 0x7fffe6, 0x7fffe7, 0xffffef, 0x3fffda, 0x1fffdd, 0xfffe9, 0x3fffdb, 0x3fffdc, 0x7fffe8, 0x7fffe9, 0x1fffde, 0x7fffea, 0x3fffdd, 0x3fffde, 0xfffff0, 0x1fffdf, 0x3fffdf, 0x7fffeb, 0x7fffec, 0x1fffe0, 0x1fffe1, 0x3fffe0, 0x1fffe2, 0x7fffed, 0x3fffe1, 0x7fffee, 0x7fffef, 0xfffea, 0x3fffe2, 0x3fffe3, 0x3fffe4, 0x7ffff0, 0x3fffe5, 0x3fffe6, 0x7ffff1, 0x3ffffe0, 0x3ffffe1, 0xfffeb, 0x7fff1, 0x3fffe7, 0x7ffff2, 0x3fffe8, 0x1ffffec, 0x3ffffe2, 0x3ffffe3, 0x3ffffe4, 0x7ffffde, 0x7ffffdf, 0x3ffffe5, 0xfffff1, 0x1ffffed, 0x7fff2, 0x1fffe3, 0x3ffffe6, 0x7ffffe0, 0x7ffffe1, 0x3ffffe7, 0x7ffffe2, 0xfffff2, 0x1fffe4, 0x1fffe5, 0x3ffffe8, 0x3ffffe9, 0xffffffd, 0x7ffffe3, 0x7ffffe4, 0x7ffffe5, 0xfffec, 0xfffff3, 0xfffed, 0x1fffe6, 0x3fffe9, 0x1fffe7, 0x1fffe8, 0x7ffff3, 0x3fffea, 0x3fffeb, 0x1ffffee, 0x1ffffef, 0xfffff4, 0xfffff5, 0x3ffffea, 0x7ffff4, 0x3ffffeb, 0x7ffffe6, 0x3ffffec, 0x3ffffed, 0x7ffffe7, 0x7ffffe8, 0x7ffffe9, 0x7ffffea, 0x7ffffeb, 0xffffffe, 0x7ffffec, 0x7ffffed, 0x7ffffee, 0x7ffffef, 0x7fffff0, 0x3ffffee, } var huffmanCodeLen = [256]uint8{ 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, } lxd-2.0.11/dist/src/golang.org/x/net/http2/hpack/huffman.go0000644061062106075000000001205313172163402024416 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hpack import ( "bytes" "errors" "io" "sync" ) var bufPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, } // HuffmanDecode decodes the string in v and writes the expanded // result to w, returning the number of bytes written to w and the // Write call's return value. At most one Write call is made. func HuffmanDecode(w io.Writer, v []byte) (int, error) { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) if err := huffmanDecode(buf, 0, v); err != nil { return 0, err } return w.Write(buf.Bytes()) } // HuffmanDecodeToString decodes the string in v. func HuffmanDecodeToString(v []byte) (string, error) { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) if err := huffmanDecode(buf, 0, v); err != nil { return "", err } return buf.String(), nil } // ErrInvalidHuffman is returned for errors found decoding // Huffman-encoded strings. var ErrInvalidHuffman = errors.New("hpack: invalid Huffman-encoded data") // huffmanDecode decodes v to buf. // If maxLen is greater than 0, attempts to write more to buf than // maxLen bytes will return ErrStringLength. func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error { n := rootHuffmanNode // cur is the bit buffer that has not been fed into n. // cbits is the number of low order bits in cur that are valid. // sbits is the number of bits of the symbol prefix being decoded. cur, cbits, sbits := uint(0), uint8(0), uint8(0) for _, b := range v { cur = cur<<8 | uint(b) cbits += 8 sbits += 8 for cbits >= 8 { idx := byte(cur >> (cbits - 8)) n = n.children[idx] if n == nil { return ErrInvalidHuffman } if n.children == nil { if maxLen != 0 && buf.Len() == maxLen { return ErrStringLength } buf.WriteByte(n.sym) cbits -= n.codeLen n = rootHuffmanNode sbits = cbits } else { cbits -= 8 } } } for cbits > 0 { n = n.children[byte(cur<<(8-cbits))] if n == nil { return ErrInvalidHuffman } if n.children != nil || n.codeLen > cbits { break } if maxLen != 0 && buf.Len() == maxLen { return ErrStringLength } buf.WriteByte(n.sym) cbits -= n.codeLen n = rootHuffmanNode sbits = cbits } if sbits > 7 { // Either there was an incomplete symbol, or overlong padding. // Both are decoding errors per RFC 7541 section 5.2. return ErrInvalidHuffman } if mask := uint(1< 8 { codeLen -= 8 i := uint8(code >> codeLen) if cur.children[i] == nil { cur.children[i] = newInternalNode() } cur = cur.children[i] } shift := 8 - codeLen start, end := int(uint8(code<> (nbits - rembits)) dst[len(dst)-1] |= t } return dst } // HuffmanEncodeLength returns the number of bytes required to encode // s in Huffman codes. The result is round up to byte boundary. func HuffmanEncodeLength(s string) uint64 { n := uint64(0) for i := 0; i < len(s); i++ { n += uint64(huffmanCodeLen[s[i]]) } return (n + 7) / 8 } // appendByteToHuffmanCode appends Huffman code for c to dst and // returns the extended buffer and the remaining bits in the last // element. The appending is not byte aligned and the remaining bits // in the last element of dst is given in rembits. func appendByteToHuffmanCode(dst []byte, rembits uint8, c byte) ([]byte, uint8) { code := huffmanCodes[c] nbits := huffmanCodeLen[c] for { if rembits > nbits { t := uint8(code << (rembits - nbits)) dst[len(dst)-1] |= t rembits -= nbits break } t := uint8(code >> (nbits - rembits)) dst[len(dst)-1] |= t nbits -= rembits rembits = 8 if nbits == 0 { break } dst = append(dst, 0) } return dst, rembits } lxd-2.0.11/dist/src/golang.org/x/net/http2/hpack/hpack_test.go0000644061062106075000000005202113172163402025116 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hpack import ( "bytes" "encoding/hex" "fmt" "math/rand" "reflect" "strings" "testing" "time" ) func (d *Decoder) mustAt(idx int) HeaderField { if hf, ok := d.at(uint64(idx)); !ok { panic(fmt.Sprintf("bogus index %d", idx)) } else { return hf } } func TestDynamicTableAt(t *testing.T) { d := NewDecoder(4096, nil) at := d.mustAt if got, want := at(2), (pair(":method", "GET")); got != want { t.Errorf("at(2) = %v; want %v", got, want) } d.dynTab.add(pair("foo", "bar")) d.dynTab.add(pair("blake", "miz")) if got, want := at(staticTable.len()+1), (pair("blake", "miz")); got != want { t.Errorf("at(dyn 1) = %v; want %v", got, want) } if got, want := at(staticTable.len()+2), (pair("foo", "bar")); got != want { t.Errorf("at(dyn 2) = %v; want %v", got, want) } if got, want := at(3), (pair(":method", "POST")); got != want { t.Errorf("at(3) = %v; want %v", got, want) } } func TestDynamicTableSizeEvict(t *testing.T) { d := NewDecoder(4096, nil) if want := uint32(0); d.dynTab.size != want { t.Fatalf("size = %d; want %d", d.dynTab.size, want) } add := d.dynTab.add add(pair("blake", "eats pizza")) if want := uint32(15 + 32); d.dynTab.size != want { t.Fatalf("after pizza, size = %d; want %d", d.dynTab.size, want) } add(pair("foo", "bar")) if want := uint32(15 + 32 + 6 + 32); d.dynTab.size != want { t.Fatalf("after foo bar, size = %d; want %d", d.dynTab.size, want) } d.dynTab.setMaxSize(15 + 32 + 1 /* slop */) if want := uint32(6 + 32); d.dynTab.size != want { t.Fatalf("after setMaxSize, size = %d; want %d", d.dynTab.size, want) } if got, want := d.mustAt(staticTable.len()+1), (pair("foo", "bar")); got != want { t.Errorf("at(dyn 1) = %v; want %v", got, want) } add(pair("long", strings.Repeat("x", 500))) if want := uint32(0); d.dynTab.size != want { t.Fatalf("after big one, size = %d; want %d", d.dynTab.size, want) } } func TestDecoderDecode(t *testing.T) { tests := []struct { name string in []byte want []HeaderField wantDynTab []HeaderField // newest entry first }{ // C.2.1 Literal Header Field with Indexing // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.1 {"C.2.1", dehex("400a 6375 7374 6f6d 2d6b 6579 0d63 7573 746f 6d2d 6865 6164 6572"), []HeaderField{pair("custom-key", "custom-header")}, []HeaderField{pair("custom-key", "custom-header")}, }, // C.2.2 Literal Header Field without Indexing // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.2 {"C.2.2", dehex("040c 2f73 616d 706c 652f 7061 7468"), []HeaderField{pair(":path", "/sample/path")}, []HeaderField{}}, // C.2.3 Literal Header Field never Indexed // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.3 {"C.2.3", dehex("1008 7061 7373 776f 7264 0673 6563 7265 74"), []HeaderField{{"password", "secret", true}}, []HeaderField{}}, // C.2.4 Indexed Header Field // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.4 {"C.2.4", []byte("\x82"), []HeaderField{pair(":method", "GET")}, []HeaderField{}}, } for _, tt := range tests { d := NewDecoder(4096, nil) hf, err := d.DecodeFull(tt.in) if err != nil { t.Errorf("%s: %v", tt.name, err) continue } if !reflect.DeepEqual(hf, tt.want) { t.Errorf("%s: Got %v; want %v", tt.name, hf, tt.want) } gotDynTab := d.dynTab.reverseCopy() if !reflect.DeepEqual(gotDynTab, tt.wantDynTab) { t.Errorf("%s: dynamic table after = %v; want %v", tt.name, gotDynTab, tt.wantDynTab) } } } func (dt *dynamicTable) reverseCopy() (hf []HeaderField) { hf = make([]HeaderField, len(dt.table.ents)) for i := range hf { hf[i] = dt.table.ents[len(dt.table.ents)-1-i] } return } type encAndWant struct { enc []byte want []HeaderField wantDynTab []HeaderField wantDynSize uint32 } // C.3 Request Examples without Huffman Coding // http://http2.github.io/http2-spec/compression.html#rfc.section.C.3 func TestDecodeC3_NoHuffman(t *testing.T) { testDecodeSeries(t, 4096, []encAndWant{ {dehex("8286 8441 0f77 7777 2e65 7861 6d70 6c65 2e63 6f6d"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), }, []HeaderField{ pair(":authority", "www.example.com"), }, 57, }, {dehex("8286 84be 5808 6e6f 2d63 6163 6865"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), pair("cache-control", "no-cache"), }, []HeaderField{ pair("cache-control", "no-cache"), pair(":authority", "www.example.com"), }, 110, }, {dehex("8287 85bf 400a 6375 7374 6f6d 2d6b 6579 0c63 7573 746f 6d2d 7661 6c75 65"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "https"), pair(":path", "/index.html"), pair(":authority", "www.example.com"), pair("custom-key", "custom-value"), }, []HeaderField{ pair("custom-key", "custom-value"), pair("cache-control", "no-cache"), pair(":authority", "www.example.com"), }, 164, }, }) } // C.4 Request Examples with Huffman Coding // http://http2.github.io/http2-spec/compression.html#rfc.section.C.4 func TestDecodeC4_Huffman(t *testing.T) { testDecodeSeries(t, 4096, []encAndWant{ {dehex("8286 8441 8cf1 e3c2 e5f2 3a6b a0ab 90f4 ff"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), }, []HeaderField{ pair(":authority", "www.example.com"), }, 57, }, {dehex("8286 84be 5886 a8eb 1064 9cbf"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), pair("cache-control", "no-cache"), }, []HeaderField{ pair("cache-control", "no-cache"), pair(":authority", "www.example.com"), }, 110, }, {dehex("8287 85bf 4088 25a8 49e9 5ba9 7d7f 8925 a849 e95b b8e8 b4bf"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "https"), pair(":path", "/index.html"), pair(":authority", "www.example.com"), pair("custom-key", "custom-value"), }, []HeaderField{ pair("custom-key", "custom-value"), pair("cache-control", "no-cache"), pair(":authority", "www.example.com"), }, 164, }, }) } // http://http2.github.io/http2-spec/compression.html#rfc.section.C.5 // "This section shows several consecutive header lists, corresponding // to HTTP responses, on the same connection. The HTTP/2 setting // parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256 // octets, causing some evictions to occur." func TestDecodeC5_ResponsesNoHuff(t *testing.T) { testDecodeSeries(t, 256, []encAndWant{ {dehex(` 4803 3330 3258 0770 7269 7661 7465 611d 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 2032 303a 3133 3a32 3120 474d 546e 1768 7474 7073 3a2f 2f77 7777 2e65 7861 6d70 6c65 2e63 6f6d `), []HeaderField{ pair(":status", "302"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("location", "https://www.example.com"), }, []HeaderField{ pair("location", "https://www.example.com"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("cache-control", "private"), pair(":status", "302"), }, 222, }, {dehex("4803 3330 37c1 c0bf"), []HeaderField{ pair(":status", "307"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("location", "https://www.example.com"), }, []HeaderField{ pair(":status", "307"), pair("location", "https://www.example.com"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("cache-control", "private"), }, 222, }, {dehex(` 88c1 611d 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 2032 303a 3133 3a32 3220 474d 54c0 5a04 677a 6970 7738 666f 6f3d 4153 444a 4b48 514b 425a 584f 5157 454f 5049 5541 5851 5745 4f49 553b 206d 6178 2d61 6765 3d33 3630 303b 2076 6572 7369 6f6e 3d31 `), []HeaderField{ pair(":status", "200"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), pair("location", "https://www.example.com"), pair("content-encoding", "gzip"), pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), }, []HeaderField{ pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), pair("content-encoding", "gzip"), pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), }, 215, }, }) } // http://http2.github.io/http2-spec/compression.html#rfc.section.C.6 // "This section shows the same examples as the previous section, but // using Huffman encoding for the literal values. The HTTP/2 setting // parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256 // octets, causing some evictions to occur. The eviction mechanism // uses the length of the decoded literal values, so the same // evictions occurs as in the previous section." func TestDecodeC6_ResponsesHuffman(t *testing.T) { testDecodeSeries(t, 256, []encAndWant{ {dehex(` 4882 6402 5885 aec3 771a 4b61 96d0 7abe 9410 54d4 44a8 2005 9504 0b81 66e0 82a6 2d1b ff6e 919d 29ad 1718 63c7 8f0b 97c8 e9ae 82ae 43d3 `), []HeaderField{ pair(":status", "302"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("location", "https://www.example.com"), }, []HeaderField{ pair("location", "https://www.example.com"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("cache-control", "private"), pair(":status", "302"), }, 222, }, {dehex("4883 640e ffc1 c0bf"), []HeaderField{ pair(":status", "307"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("location", "https://www.example.com"), }, []HeaderField{ pair(":status", "307"), pair("location", "https://www.example.com"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("cache-control", "private"), }, 222, }, {dehex(` 88c1 6196 d07a be94 1054 d444 a820 0595 040b 8166 e084 a62d 1bff c05a 839b d9ab 77ad 94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07 `), []HeaderField{ pair(":status", "200"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), pair("location", "https://www.example.com"), pair("content-encoding", "gzip"), pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), }, []HeaderField{ pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), pair("content-encoding", "gzip"), pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), }, 215, }, }) } func testDecodeSeries(t *testing.T, size uint32, steps []encAndWant) { d := NewDecoder(size, nil) for i, step := range steps { hf, err := d.DecodeFull(step.enc) if err != nil { t.Fatalf("Error at step index %d: %v", i, err) } if !reflect.DeepEqual(hf, step.want) { t.Fatalf("At step index %d: Got headers %v; want %v", i, hf, step.want) } gotDynTab := d.dynTab.reverseCopy() if !reflect.DeepEqual(gotDynTab, step.wantDynTab) { t.Errorf("After step index %d, dynamic table = %v; want %v", i, gotDynTab, step.wantDynTab) } if d.dynTab.size != step.wantDynSize { t.Errorf("After step index %d, dynamic table size = %v; want %v", i, d.dynTab.size, step.wantDynSize) } } } func TestHuffmanDecodeExcessPadding(t *testing.T) { tests := [][]byte{ {0xff}, // Padding Exceeds 7 bits {0x1f, 0xff}, // {"a", 1 byte excess padding} {0x1f, 0xff, 0xff}, // {"a", 2 byte excess padding} {0x1f, 0xff, 0xff, 0xff}, // {"a", 3 byte excess padding} {0xff, 0x9f, 0xff, 0xff, 0xff}, // {"a", 29 bit excess padding} {'R', 0xbc, '0', 0xff, 0xff, 0xff, 0xff}, // Padding ends on partial symbol. } for i, in := range tests { var buf bytes.Buffer if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { t.Errorf("test-%d: decode(%q) = %v; want ErrInvalidHuffman", i, in, err) } } } func TestHuffmanDecodeEOS(t *testing.T) { in := []byte{0xff, 0xff, 0xff, 0xff, 0xfc} // {EOS, "?"} var buf bytes.Buffer if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { t.Errorf("error = %v; want ErrInvalidHuffman", err) } } func TestHuffmanDecodeMaxLengthOnTrailingByte(t *testing.T) { in := []byte{0x00, 0x01} // {"0", "0", "0"} var buf bytes.Buffer if err := huffmanDecode(&buf, 2, in); err != ErrStringLength { t.Errorf("error = %v; want ErrStringLength", err) } } func TestHuffmanDecodeCorruptPadding(t *testing.T) { in := []byte{0x00} var buf bytes.Buffer if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { t.Errorf("error = %v; want ErrInvalidHuffman", err) } } func TestHuffmanDecode(t *testing.T) { tests := []struct { inHex, want string }{ {"f1e3 c2e5 f23a 6ba0 ab90 f4ff", "www.example.com"}, {"a8eb 1064 9cbf", "no-cache"}, {"25a8 49e9 5ba9 7d7f", "custom-key"}, {"25a8 49e9 5bb8 e8b4 bf", "custom-value"}, {"6402", "302"}, {"aec3 771a 4b", "private"}, {"d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3", "https://www.example.com"}, {"9bd9 ab", "gzip"}, {"94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, } for i, tt := range tests { var buf bytes.Buffer in, err := hex.DecodeString(strings.Replace(tt.inHex, " ", "", -1)) if err != nil { t.Errorf("%d. hex input error: %v", i, err) continue } if _, err := HuffmanDecode(&buf, in); err != nil { t.Errorf("%d. decode error: %v", i, err) continue } if got := buf.String(); tt.want != got { t.Errorf("%d. decode = %q; want %q", i, got, tt.want) } } } func TestAppendHuffmanString(t *testing.T) { tests := []struct { in, want string }{ {"www.example.com", "f1e3 c2e5 f23a 6ba0 ab90 f4ff"}, {"no-cache", "a8eb 1064 9cbf"}, {"custom-key", "25a8 49e9 5ba9 7d7f"}, {"custom-value", "25a8 49e9 5bb8 e8b4 bf"}, {"302", "6402"}, {"private", "aec3 771a 4b"}, {"Mon, 21 Oct 2013 20:13:21 GMT", "d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff"}, {"https://www.example.com", "9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3"}, {"gzip", "9bd9 ab"}, {"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", "94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07"}, } for i, tt := range tests { buf := []byte{} want := strings.Replace(tt.want, " ", "", -1) buf = AppendHuffmanString(buf, tt.in) if got := hex.EncodeToString(buf); want != got { t.Errorf("%d. encode = %q; want %q", i, got, want) } } } func TestHuffmanMaxStrLen(t *testing.T) { const msg = "Some string" huff := AppendHuffmanString(nil, msg) testGood := func(max int) { var out bytes.Buffer if err := huffmanDecode(&out, max, huff); err != nil { t.Errorf("For maxLen=%d, unexpected error: %v", max, err) } if out.String() != msg { t.Errorf("For maxLen=%d, out = %q; want %q", max, out.String(), msg) } } testGood(0) testGood(len(msg)) testGood(len(msg) + 1) var out bytes.Buffer if err := huffmanDecode(&out, len(msg)-1, huff); err != ErrStringLength { t.Errorf("err = %v; want ErrStringLength", err) } } func TestHuffmanRoundtripStress(t *testing.T) { const Len = 50 // of uncompressed string input := make([]byte, Len) var output bytes.Buffer var huff []byte n := 5000 if testing.Short() { n = 100 } seed := time.Now().UnixNano() t.Logf("Seed = %v", seed) src := rand.New(rand.NewSource(seed)) var encSize int64 for i := 0; i < n; i++ { for l := range input { input[l] = byte(src.Intn(256)) } huff = AppendHuffmanString(huff[:0], string(input)) encSize += int64(len(huff)) output.Reset() if err := huffmanDecode(&output, 0, huff); err != nil { t.Errorf("Failed to decode %q -> %q -> error %v", input, huff, err) continue } if !bytes.Equal(output.Bytes(), input) { t.Errorf("Roundtrip failure on %q -> %q -> %q", input, huff, output.Bytes()) } } t.Logf("Compressed size of original: %0.02f%% (%v -> %v)", 100*(float64(encSize)/(Len*float64(n))), Len*n, encSize) } func TestHuffmanDecodeFuzz(t *testing.T) { const Len = 50 // of compressed var buf, zbuf bytes.Buffer n := 5000 if testing.Short() { n = 100 } seed := time.Now().UnixNano() t.Logf("Seed = %v", seed) src := rand.New(rand.NewSource(seed)) numFail := 0 for i := 0; i < n; i++ { zbuf.Reset() if i == 0 { // Start with at least one invalid one. zbuf.WriteString("00\x91\xff\xff\xff\xff\xc8") } else { for l := 0; l < Len; l++ { zbuf.WriteByte(byte(src.Intn(256))) } } buf.Reset() if err := huffmanDecode(&buf, 0, zbuf.Bytes()); err != nil { if err == ErrInvalidHuffman { numFail++ continue } t.Errorf("Failed to decode %q: %v", zbuf.Bytes(), err) continue } } t.Logf("%0.02f%% are invalid (%d / %d)", 100*float64(numFail)/float64(n), numFail, n) if numFail < 1 { t.Error("expected at least one invalid huffman encoding (test starts with one)") } } func TestReadVarInt(t *testing.T) { type res struct { i uint64 consumed int err error } tests := []struct { n byte p []byte want res }{ // Fits in a byte: {1, []byte{0}, res{0, 1, nil}}, {2, []byte{2}, res{2, 1, nil}}, {3, []byte{6}, res{6, 1, nil}}, {4, []byte{14}, res{14, 1, nil}}, {5, []byte{30}, res{30, 1, nil}}, {6, []byte{62}, res{62, 1, nil}}, {7, []byte{126}, res{126, 1, nil}}, {8, []byte{254}, res{254, 1, nil}}, // Doesn't fit in a byte: {1, []byte{1}, res{0, 0, errNeedMore}}, {2, []byte{3}, res{0, 0, errNeedMore}}, {3, []byte{7}, res{0, 0, errNeedMore}}, {4, []byte{15}, res{0, 0, errNeedMore}}, {5, []byte{31}, res{0, 0, errNeedMore}}, {6, []byte{63}, res{0, 0, errNeedMore}}, {7, []byte{127}, res{0, 0, errNeedMore}}, {8, []byte{255}, res{0, 0, errNeedMore}}, // Ignoring top bits: {5, []byte{255, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 111 {5, []byte{159, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 100 {5, []byte{191, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 101 // Extra byte: {5, []byte{191, 154, 10, 2}, res{1337, 3, nil}}, // extra byte // Short a byte: {5, []byte{191, 154}, res{0, 0, errNeedMore}}, // integer overflow: {1, []byte{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, res{0, 0, errVarintOverflow}}, } for _, tt := range tests { i, remain, err := readVarInt(tt.n, tt.p) consumed := len(tt.p) - len(remain) got := res{i, consumed, err} if got != tt.want { t.Errorf("readVarInt(%d, %v ~ %x) = %+v; want %+v", tt.n, tt.p, tt.p, got, tt.want) } } } // Fuzz crash, originally reported at https://github.com/bradfitz/http2/issues/56 func TestHuffmanFuzzCrash(t *testing.T) { got, err := HuffmanDecodeToString([]byte("00\x91\xff\xff\xff\xff\xc8")) if got != "" { t.Errorf("Got %q; want empty string", got) } if err != ErrInvalidHuffman { t.Errorf("Err = %v; want ErrInvalidHuffman", err) } } func pair(name, value string) HeaderField { return HeaderField{Name: name, Value: value} } func dehex(s string) []byte { s = strings.Replace(s, " ", "", -1) s = strings.Replace(s, "\n", "", -1) b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } func TestEmitEnabled(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) enc.WriteField(HeaderField{Name: "foo", Value: "bar"}) enc.WriteField(HeaderField{Name: "foo", Value: "bar"}) numCallback := 0 var dec *Decoder dec = NewDecoder(8<<20, func(HeaderField) { numCallback++ dec.SetEmitEnabled(false) }) if !dec.EmitEnabled() { t.Errorf("initial emit enabled = false; want true") } if _, err := dec.Write(buf.Bytes()); err != nil { t.Error(err) } if numCallback != 1 { t.Errorf("num callbacks = %d; want 1", numCallback) } if dec.EmitEnabled() { t.Errorf("emit enabled = true; want false") } } func TestSaveBufLimit(t *testing.T) { const maxStr = 1 << 10 var got []HeaderField dec := NewDecoder(initialHeaderTableSize, func(hf HeaderField) { got = append(got, hf) }) dec.SetMaxStringLength(maxStr) var frag []byte frag = append(frag[:0], encodeTypeByte(false, false)) frag = appendVarInt(frag, 7, 3) frag = append(frag, "foo"...) frag = appendVarInt(frag, 7, 3) frag = append(frag, "bar"...) if _, err := dec.Write(frag); err != nil { t.Fatal(err) } want := []HeaderField{{Name: "foo", Value: "bar"}} if !reflect.DeepEqual(got, want) { t.Errorf("After small writes, got %v; want %v", got, want) } frag = append(frag[:0], encodeTypeByte(false, false)) frag = appendVarInt(frag, 7, maxStr*3) frag = append(frag, make([]byte, maxStr*3)...) _, err := dec.Write(frag) if err != ErrStringLength { t.Fatalf("Write error = %v; want ErrStringLength", err) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/hpack/hpack.go0000644061062106075000000003351613172163402024067 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package hpack implements HPACK, a compression format for // efficiently representing HTTP header fields in the context of HTTP/2. // // See http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-09 package hpack import ( "bytes" "errors" "fmt" ) // A DecodingError is something the spec defines as a decoding error. type DecodingError struct { Err error } func (de DecodingError) Error() string { return fmt.Sprintf("decoding error: %v", de.Err) } // An InvalidIndexError is returned when an encoder references a table // entry before the static table or after the end of the dynamic table. type InvalidIndexError int func (e InvalidIndexError) Error() string { return fmt.Sprintf("invalid indexed representation index %d", int(e)) } // A HeaderField is a name-value pair. Both the name and value are // treated as opaque sequences of octets. type HeaderField struct { Name, Value string // Sensitive means that this header field should never be // indexed. Sensitive bool } // IsPseudo reports whether the header field is an http2 pseudo header. // That is, it reports whether it starts with a colon. // It is not otherwise guaranteed to be a valid pseudo header field, // though. func (hf HeaderField) IsPseudo() bool { return len(hf.Name) != 0 && hf.Name[0] == ':' } func (hf HeaderField) String() string { var suffix string if hf.Sensitive { suffix = " (sensitive)" } return fmt.Sprintf("header field %q = %q%s", hf.Name, hf.Value, suffix) } // Size returns the size of an entry per RFC 7541 section 4.1. func (hf HeaderField) Size() uint32 { // http://http2.github.io/http2-spec/compression.html#rfc.section.4.1 // "The size of the dynamic table is the sum of the size of // its entries. The size of an entry is the sum of its name's // length in octets (as defined in Section 5.2), its value's // length in octets (see Section 5.2), plus 32. The size of // an entry is calculated using the length of the name and // value without any Huffman encoding applied." // This can overflow if somebody makes a large HeaderField // Name and/or Value by hand, but we don't care, because that // won't happen on the wire because the encoding doesn't allow // it. return uint32(len(hf.Name) + len(hf.Value) + 32) } // A Decoder is the decoding context for incremental processing of // header blocks. type Decoder struct { dynTab dynamicTable emit func(f HeaderField) emitEnabled bool // whether calls to emit are enabled maxStrLen int // 0 means unlimited // buf is the unparsed buffer. It's only written to // saveBuf if it was truncated in the middle of a header // block. Because it's usually not owned, we can only // process it under Write. buf []byte // not owned; only valid during Write // saveBuf is previous data passed to Write which we weren't able // to fully parse before. Unlike buf, we own this data. saveBuf bytes.Buffer } // NewDecoder returns a new decoder with the provided maximum dynamic // table size. The emitFunc will be called for each valid field // parsed, in the same goroutine as calls to Write, before Write returns. func NewDecoder(maxDynamicTableSize uint32, emitFunc func(f HeaderField)) *Decoder { d := &Decoder{ emit: emitFunc, emitEnabled: true, } d.dynTab.table.init() d.dynTab.allowedMaxSize = maxDynamicTableSize d.dynTab.setMaxSize(maxDynamicTableSize) return d } // ErrStringLength is returned by Decoder.Write when the max string length // (as configured by Decoder.SetMaxStringLength) would be violated. var ErrStringLength = errors.New("hpack: string too long") // SetMaxStringLength sets the maximum size of a HeaderField name or // value string. If a string exceeds this length (even after any // decompression), Write will return ErrStringLength. // A value of 0 means unlimited and is the default from NewDecoder. func (d *Decoder) SetMaxStringLength(n int) { d.maxStrLen = n } // SetEmitFunc changes the callback used when new header fields // are decoded. // It must be non-nil. It does not affect EmitEnabled. func (d *Decoder) SetEmitFunc(emitFunc func(f HeaderField)) { d.emit = emitFunc } // SetEmitEnabled controls whether the emitFunc provided to NewDecoder // should be called. The default is true. // // This facility exists to let servers enforce MAX_HEADER_LIST_SIZE // while still decoding and keeping in-sync with decoder state, but // without doing unnecessary decompression or generating unnecessary // garbage for header fields past the limit. func (d *Decoder) SetEmitEnabled(v bool) { d.emitEnabled = v } // EmitEnabled reports whether calls to the emitFunc provided to NewDecoder // are currently enabled. The default is true. func (d *Decoder) EmitEnabled() bool { return d.emitEnabled } // TODO: add method *Decoder.Reset(maxSize, emitFunc) to let callers re-use Decoders and their // underlying buffers for garbage reasons. func (d *Decoder) SetMaxDynamicTableSize(v uint32) { d.dynTab.setMaxSize(v) } // SetAllowedMaxDynamicTableSize sets the upper bound that the encoded // stream (via dynamic table size updates) may set the maximum size // to. func (d *Decoder) SetAllowedMaxDynamicTableSize(v uint32) { d.dynTab.allowedMaxSize = v } type dynamicTable struct { // http://http2.github.io/http2-spec/compression.html#rfc.section.2.3.2 table headerFieldTable size uint32 // in bytes maxSize uint32 // current maxSize allowedMaxSize uint32 // maxSize may go up to this, inclusive } func (dt *dynamicTable) setMaxSize(v uint32) { dt.maxSize = v dt.evict() } func (dt *dynamicTable) add(f HeaderField) { dt.table.addEntry(f) dt.size += f.Size() dt.evict() } // If we're too big, evict old stuff. func (dt *dynamicTable) evict() { var n int for dt.size > dt.maxSize && n < dt.table.len() { dt.size -= dt.table.ents[n].Size() n++ } dt.table.evictOldest(n) } func (d *Decoder) maxTableIndex() int { // This should never overflow. RFC 7540 Section 6.5.2 limits the size of // the dynamic table to 2^32 bytes, where each entry will occupy more than // one byte. Further, the staticTable has a fixed, small length. return d.dynTab.table.len() + staticTable.len() } func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) { // See Section 2.3.3. if i == 0 { return } if i <= uint64(staticTable.len()) { return staticTable.ents[i-1], true } if i > uint64(d.maxTableIndex()) { return } // In the dynamic table, newer entries have lower indices. // However, dt.ents[0] is the oldest entry. Hence, dt.ents is // the reversed dynamic table. dt := d.dynTab.table return dt.ents[dt.len()-(int(i)-staticTable.len())], true } // Decode decodes an entire block. // // TODO: remove this method and make it incremental later? This is // easier for debugging now. func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) { var hf []HeaderField saveFunc := d.emit defer func() { d.emit = saveFunc }() d.emit = func(f HeaderField) { hf = append(hf, f) } if _, err := d.Write(p); err != nil { return nil, err } if err := d.Close(); err != nil { return nil, err } return hf, nil } func (d *Decoder) Close() error { if d.saveBuf.Len() > 0 { d.saveBuf.Reset() return DecodingError{errors.New("truncated headers")} } return nil } func (d *Decoder) Write(p []byte) (n int, err error) { if len(p) == 0 { // Prevent state machine CPU attacks (making us redo // work up to the point of finding out we don't have // enough data) return } // Only copy the data if we have to. Optimistically assume // that p will contain a complete header block. if d.saveBuf.Len() == 0 { d.buf = p } else { d.saveBuf.Write(p) d.buf = d.saveBuf.Bytes() d.saveBuf.Reset() } for len(d.buf) > 0 { err = d.parseHeaderFieldRepr() if err == errNeedMore { // Extra paranoia, making sure saveBuf won't // get too large. All the varint and string // reading code earlier should already catch // overlong things and return ErrStringLength, // but keep this as a last resort. const varIntOverhead = 8 // conservative if d.maxStrLen != 0 && int64(len(d.buf)) > 2*(int64(d.maxStrLen)+varIntOverhead) { return 0, ErrStringLength } d.saveBuf.Write(d.buf) return len(p), nil } if err != nil { break } } return len(p), err } // errNeedMore is an internal sentinel error value that means the // buffer is truncated and we need to read more data before we can // continue parsing. var errNeedMore = errors.New("need more data") type indexType int const ( indexedTrue indexType = iota indexedFalse indexedNever ) func (v indexType) indexed() bool { return v == indexedTrue } func (v indexType) sensitive() bool { return v == indexedNever } // returns errNeedMore if there isn't enough data available. // any other error is fatal. // consumes d.buf iff it returns nil. // precondition: must be called with len(d.buf) > 0 func (d *Decoder) parseHeaderFieldRepr() error { b := d.buf[0] switch { case b&128 != 0: // Indexed representation. // High bit set? // http://http2.github.io/http2-spec/compression.html#rfc.section.6.1 return d.parseFieldIndexed() case b&192 == 64: // 6.2.1 Literal Header Field with Incremental Indexing // 0b10xxxxxx: top two bits are 10 // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.1 return d.parseFieldLiteral(6, indexedTrue) case b&240 == 0: // 6.2.2 Literal Header Field without Indexing // 0b0000xxxx: top four bits are 0000 // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.2 return d.parseFieldLiteral(4, indexedFalse) case b&240 == 16: // 6.2.3 Literal Header Field never Indexed // 0b0001xxxx: top four bits are 0001 // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.3 return d.parseFieldLiteral(4, indexedNever) case b&224 == 32: // 6.3 Dynamic Table Size Update // Top three bits are '001'. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.3 return d.parseDynamicTableSizeUpdate() } return DecodingError{errors.New("invalid encoding")} } // (same invariants and behavior as parseHeaderFieldRepr) func (d *Decoder) parseFieldIndexed() error { buf := d.buf idx, buf, err := readVarInt(7, buf) if err != nil { return err } hf, ok := d.at(idx) if !ok { return DecodingError{InvalidIndexError(idx)} } d.buf = buf return d.callEmit(HeaderField{Name: hf.Name, Value: hf.Value}) } // (same invariants and behavior as parseHeaderFieldRepr) func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error { buf := d.buf nameIdx, buf, err := readVarInt(n, buf) if err != nil { return err } var hf HeaderField wantStr := d.emitEnabled || it.indexed() if nameIdx > 0 { ihf, ok := d.at(nameIdx) if !ok { return DecodingError{InvalidIndexError(nameIdx)} } hf.Name = ihf.Name } else { hf.Name, buf, err = d.readString(buf, wantStr) if err != nil { return err } } hf.Value, buf, err = d.readString(buf, wantStr) if err != nil { return err } d.buf = buf if it.indexed() { d.dynTab.add(hf) } hf.Sensitive = it.sensitive() return d.callEmit(hf) } func (d *Decoder) callEmit(hf HeaderField) error { if d.maxStrLen != 0 { if len(hf.Name) > d.maxStrLen || len(hf.Value) > d.maxStrLen { return ErrStringLength } } if d.emitEnabled { d.emit(hf) } return nil } // (same invariants and behavior as parseHeaderFieldRepr) func (d *Decoder) parseDynamicTableSizeUpdate() error { buf := d.buf size, buf, err := readVarInt(5, buf) if err != nil { return err } if size > uint64(d.dynTab.allowedMaxSize) { return DecodingError{errors.New("dynamic table size update too large")} } d.dynTab.setMaxSize(uint32(size)) d.buf = buf return nil } var errVarintOverflow = DecodingError{errors.New("varint integer overflow")} // readVarInt reads an unsigned variable length integer off the // beginning of p. n is the parameter as described in // http://http2.github.io/http2-spec/compression.html#rfc.section.5.1. // // n must always be between 1 and 8. // // The returned remain buffer is either a smaller suffix of p, or err != nil. // The error is errNeedMore if p doesn't contain a complete integer. func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) { if n < 1 || n > 8 { panic("bad n") } if len(p) == 0 { return 0, p, errNeedMore } i = uint64(p[0]) if n < 8 { i &= (1 << uint64(n)) - 1 } if i < (1< 0 { b := p[0] p = p[1:] i += uint64(b&127) << m if b&128 == 0 { return i, p, nil } m += 7 if m >= 63 { // TODO: proper overflow check. making this up. return 0, origP, errVarintOverflow } } return 0, origP, errNeedMore } // readString decodes an hpack string from p. // // wantStr is whether s will be used. If false, decompression and // []byte->string garbage are skipped if s will be ignored // anyway. This does mean that huffman decoding errors for non-indexed // strings past the MAX_HEADER_LIST_SIZE are ignored, but the server // is returning an error anyway, and because they're not indexed, the error // won't affect the decoding state. func (d *Decoder) readString(p []byte, wantStr bool) (s string, remain []byte, err error) { if len(p) == 0 { return "", p, errNeedMore } isHuff := p[0]&128 != 0 strLen, p, err := readVarInt(7, p) if err != nil { return "", p, err } if d.maxStrLen != 0 && strLen > uint64(d.maxStrLen) { return "", nil, ErrStringLength } if uint64(len(p)) < strLen { return "", p, errNeedMore } if !isHuff { if wantStr { s = string(p[:strLen]) } return s, p[strLen:], nil } if wantStr { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() // don't trust others defer bufPool.Put(buf) if err := huffmanDecode(buf, d.maxStrLen, p[:strLen]); err != nil { buf.Reset() return "", nil, err } s = buf.String() buf.Reset() // be nice to GC } return s, p[strLen:], nil } lxd-2.0.11/dist/src/golang.org/x/net/http2/hpack/encode_test.go0000644061062106075000000002356213172163402025275 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hpack import ( "bytes" "encoding/hex" "fmt" "math/rand" "reflect" "strings" "testing" ) func TestEncoderTableSizeUpdate(t *testing.T) { tests := []struct { size1, size2 uint32 wantHex string }{ // Should emit 2 table size updates (2048 and 4096) {2048, 4096, "3fe10f 3fe11f 82"}, // Should emit 1 table size update (2048) {16384, 2048, "3fe10f 82"}, } for _, tt := range tests { var buf bytes.Buffer e := NewEncoder(&buf) e.SetMaxDynamicTableSize(tt.size1) e.SetMaxDynamicTableSize(tt.size2) if err := e.WriteField(pair(":method", "GET")); err != nil { t.Fatal(err) } want := removeSpace(tt.wantHex) if got := hex.EncodeToString(buf.Bytes()); got != want { t.Errorf("e.SetDynamicTableSize %v, %v = %q; want %q", tt.size1, tt.size2, got, want) } } } func TestEncoderWriteField(t *testing.T) { var buf bytes.Buffer e := NewEncoder(&buf) var got []HeaderField d := NewDecoder(4<<10, func(f HeaderField) { got = append(got, f) }) tests := []struct { hdrs []HeaderField }{ {[]HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), }}, {[]HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), pair("cache-control", "no-cache"), }}, {[]HeaderField{ pair(":method", "GET"), pair(":scheme", "https"), pair(":path", "/index.html"), pair(":authority", "www.example.com"), pair("custom-key", "custom-value"), }}, } for i, tt := range tests { buf.Reset() got = got[:0] for _, hf := range tt.hdrs { if err := e.WriteField(hf); err != nil { t.Fatal(err) } } _, err := d.Write(buf.Bytes()) if err != nil { t.Errorf("%d. Decoder Write = %v", i, err) } if !reflect.DeepEqual(got, tt.hdrs) { t.Errorf("%d. Decoded %+v; want %+v", i, got, tt.hdrs) } } } func TestEncoderSearchTable(t *testing.T) { e := NewEncoder(nil) e.dynTab.add(pair("foo", "bar")) e.dynTab.add(pair("blake", "miz")) e.dynTab.add(pair(":method", "GET")) tests := []struct { hf HeaderField wantI uint64 wantMatch bool }{ // Name and Value match {pair("foo", "bar"), uint64(staticTable.len()) + 3, true}, {pair("blake", "miz"), uint64(staticTable.len()) + 2, true}, {pair(":method", "GET"), 2, true}, // Only name match because Sensitive == true. This is allowed to match // any ":method" entry. The current implementation uses the last entry // added in newStaticTable. {HeaderField{":method", "GET", true}, 3, false}, // Only Name matches {pair("foo", "..."), uint64(staticTable.len()) + 3, false}, {pair("blake", "..."), uint64(staticTable.len()) + 2, false}, // As before, this is allowed to match any ":method" entry. {pair(":method", "..."), 3, false}, // None match {pair("foo-", "bar"), 0, false}, } for _, tt := range tests { if gotI, gotMatch := e.searchTable(tt.hf); gotI != tt.wantI || gotMatch != tt.wantMatch { t.Errorf("d.search(%+v) = %v, %v; want %v, %v", tt.hf, gotI, gotMatch, tt.wantI, tt.wantMatch) } } } func TestAppendVarInt(t *testing.T) { tests := []struct { n byte i uint64 want []byte }{ // Fits in a byte: {1, 0, []byte{0}}, {2, 2, []byte{2}}, {3, 6, []byte{6}}, {4, 14, []byte{14}}, {5, 30, []byte{30}}, {6, 62, []byte{62}}, {7, 126, []byte{126}}, {8, 254, []byte{254}}, // Multiple bytes: {5, 1337, []byte{31, 154, 10}}, } for _, tt := range tests { got := appendVarInt(nil, tt.n, tt.i) if !bytes.Equal(got, tt.want) { t.Errorf("appendVarInt(nil, %v, %v) = %v; want %v", tt.n, tt.i, got, tt.want) } } } func TestAppendHpackString(t *testing.T) { tests := []struct { s, wantHex string }{ // Huffman encoded {"www.example.com", "8c f1e3 c2e5 f23a 6ba0 ab90 f4ff"}, // Not Huffman encoded {"a", "01 61"}, // zero length {"", "00"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendHpackString(nil, tt.s) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendHpackString(nil, %q) = %q; want %q", tt.s, got, want) } } } func TestAppendIndexed(t *testing.T) { tests := []struct { i uint64 wantHex string }{ // 1 byte {1, "81"}, {126, "fe"}, // 2 bytes {127, "ff00"}, {128, "ff01"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendIndexed(nil, tt.i) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendIndex(nil, %v) = %q; want %q", tt.i, got, want) } } } func TestAppendNewName(t *testing.T) { tests := []struct { f HeaderField indexing bool wantHex string }{ // Incremental indexing {HeaderField{"custom-key", "custom-value", false}, true, "40 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, // Without indexing {HeaderField{"custom-key", "custom-value", false}, false, "00 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, // Never indexed {HeaderField{"custom-key", "custom-value", true}, true, "10 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, {HeaderField{"custom-key", "custom-value", true}, false, "10 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendNewName(nil, tt.f, tt.indexing) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendNewName(nil, %+v, %v) = %q; want %q", tt.f, tt.indexing, got, want) } } } func TestAppendIndexedName(t *testing.T) { tests := []struct { f HeaderField i uint64 indexing bool wantHex string }{ // Incremental indexing {HeaderField{":status", "302", false}, 8, true, "48 82 6402"}, // Without indexing {HeaderField{":status", "302", false}, 8, false, "08 82 6402"}, // Never indexed {HeaderField{":status", "302", true}, 8, true, "18 82 6402"}, {HeaderField{":status", "302", true}, 8, false, "18 82 6402"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendIndexedName(nil, tt.f, tt.i, tt.indexing) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendIndexedName(nil, %+v, %v) = %q; want %q", tt.f, tt.indexing, got, want) } } } func TestAppendTableSize(t *testing.T) { tests := []struct { i uint32 wantHex string }{ // Fits into 1 byte {30, "3e"}, // Extra byte {31, "3f00"}, {32, "3f01"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendTableSize(nil, tt.i) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendTableSize(nil, %v) = %q; want %q", tt.i, got, want) } } } func TestEncoderSetMaxDynamicTableSize(t *testing.T) { var buf bytes.Buffer e := NewEncoder(&buf) tests := []struct { v uint32 wantUpdate bool wantMinSize uint32 wantMaxSize uint32 }{ // Set new table size to 2048 {2048, true, 2048, 2048}, // Set new table size to 16384, but still limited to // 4096 {16384, true, 2048, 4096}, } for _, tt := range tests { e.SetMaxDynamicTableSize(tt.v) if got := e.tableSizeUpdate; tt.wantUpdate != got { t.Errorf("e.tableSizeUpdate = %v; want %v", got, tt.wantUpdate) } if got := e.minSize; tt.wantMinSize != got { t.Errorf("e.minSize = %v; want %v", got, tt.wantMinSize) } if got := e.dynTab.maxSize; tt.wantMaxSize != got { t.Errorf("e.maxSize = %v; want %v", got, tt.wantMaxSize) } } } func TestEncoderSetMaxDynamicTableSizeLimit(t *testing.T) { e := NewEncoder(nil) // 4095 < initialHeaderTableSize means maxSize is truncated to // 4095. e.SetMaxDynamicTableSizeLimit(4095) if got, want := e.dynTab.maxSize, uint32(4095); got != want { t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) } if got, want := e.maxSizeLimit, uint32(4095); got != want { t.Errorf("e.maxSizeLimit = %v; want %v", got, want) } if got, want := e.tableSizeUpdate, true; got != want { t.Errorf("e.tableSizeUpdate = %v; want %v", got, want) } // maxSize will be truncated to maxSizeLimit e.SetMaxDynamicTableSize(16384) if got, want := e.dynTab.maxSize, uint32(4095); got != want { t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) } // 8192 > current maxSizeLimit, so maxSize does not change. e.SetMaxDynamicTableSizeLimit(8192) if got, want := e.dynTab.maxSize, uint32(4095); got != want { t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) } if got, want := e.maxSizeLimit, uint32(8192); got != want { t.Errorf("e.maxSizeLimit = %v; want %v", got, want) } } func removeSpace(s string) string { return strings.Replace(s, " ", "", -1) } func BenchmarkEncoderSearchTable(b *testing.B) { e := NewEncoder(nil) // A sample of possible header fields. // This is not based on any actual data from HTTP/2 traces. var possible []HeaderField for _, f := range staticTable.ents { if f.Value == "" { possible = append(possible, f) continue } // Generate 5 random values, except for cookie and set-cookie, // which we know can have many values in practice. num := 5 if f.Name == "cookie" || f.Name == "set-cookie" { num = 25 } for i := 0; i < num; i++ { f.Value = fmt.Sprintf("%s-%d", f.Name, i) possible = append(possible, f) } } for k := 0; k < 10; k++ { f := HeaderField{ Name: fmt.Sprintf("x-header-%d", k), Sensitive: rand.Int()%2 == 0, } for i := 0; i < 5; i++ { f.Value = fmt.Sprintf("%s-%d", f.Name, i) possible = append(possible, f) } } // Add a random sample to the dynamic table. This very loosely simulates // a history of 100 requests with 20 header fields per request. for r := 0; r < 100*20; r++ { f := possible[rand.Int31n(int32(len(possible)))] // Skip if this is in the staticTable verbatim. if _, has := staticTable.search(f); !has { e.dynTab.add(f) } } b.ResetTimer() for n := 0; n < b.N; n++ { for _, f := range possible { e.searchTable(f) } } } lxd-2.0.11/dist/src/golang.org/x/net/http2/hpack/encode.go0000644061062106075000000001573413172163402024240 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hpack import ( "io" ) const ( uint32Max = ^uint32(0) initialHeaderTableSize = 4096 ) type Encoder struct { dynTab dynamicTable // minSize is the minimum table size set by // SetMaxDynamicTableSize after the previous Header Table Size // Update. minSize uint32 // maxSizeLimit is the maximum table size this encoder // supports. This will protect the encoder from too large // size. maxSizeLimit uint32 // tableSizeUpdate indicates whether "Header Table Size // Update" is required. tableSizeUpdate bool w io.Writer buf []byte } // NewEncoder returns a new Encoder which performs HPACK encoding. An // encoded data is written to w. func NewEncoder(w io.Writer) *Encoder { e := &Encoder{ minSize: uint32Max, maxSizeLimit: initialHeaderTableSize, tableSizeUpdate: false, w: w, } e.dynTab.table.init() e.dynTab.setMaxSize(initialHeaderTableSize) return e } // WriteField encodes f into a single Write to e's underlying Writer. // This function may also produce bytes for "Header Table Size Update" // if necessary. If produced, it is done before encoding f. func (e *Encoder) WriteField(f HeaderField) error { e.buf = e.buf[:0] if e.tableSizeUpdate { e.tableSizeUpdate = false if e.minSize < e.dynTab.maxSize { e.buf = appendTableSize(e.buf, e.minSize) } e.minSize = uint32Max e.buf = appendTableSize(e.buf, e.dynTab.maxSize) } idx, nameValueMatch := e.searchTable(f) if nameValueMatch { e.buf = appendIndexed(e.buf, idx) } else { indexing := e.shouldIndex(f) if indexing { e.dynTab.add(f) } if idx == 0 { e.buf = appendNewName(e.buf, f, indexing) } else { e.buf = appendIndexedName(e.buf, f, idx, indexing) } } n, err := e.w.Write(e.buf) if err == nil && n != len(e.buf) { err = io.ErrShortWrite } return err } // searchTable searches f in both stable and dynamic header tables. // The static header table is searched first. Only when there is no // exact match for both name and value, the dynamic header table is // then searched. If there is no match, i is 0. If both name and value // match, i is the matched index and nameValueMatch becomes true. If // only name matches, i points to that index and nameValueMatch // becomes false. func (e *Encoder) searchTable(f HeaderField) (i uint64, nameValueMatch bool) { i, nameValueMatch = staticTable.search(f) if nameValueMatch { return i, true } j, nameValueMatch := e.dynTab.table.search(f) if nameValueMatch || (i == 0 && j != 0) { return j + uint64(staticTable.len()), nameValueMatch } return i, false } // SetMaxDynamicTableSize changes the dynamic header table size to v. // The actual size is bounded by the value passed to // SetMaxDynamicTableSizeLimit. func (e *Encoder) SetMaxDynamicTableSize(v uint32) { if v > e.maxSizeLimit { v = e.maxSizeLimit } if v < e.minSize { e.minSize = v } e.tableSizeUpdate = true e.dynTab.setMaxSize(v) } // SetMaxDynamicTableSizeLimit changes the maximum value that can be // specified in SetMaxDynamicTableSize to v. By default, it is set to // 4096, which is the same size of the default dynamic header table // size described in HPACK specification. If the current maximum // dynamic header table size is strictly greater than v, "Header Table // Size Update" will be done in the next WriteField call and the // maximum dynamic header table size is truncated to v. func (e *Encoder) SetMaxDynamicTableSizeLimit(v uint32) { e.maxSizeLimit = v if e.dynTab.maxSize > v { e.tableSizeUpdate = true e.dynTab.setMaxSize(v) } } // shouldIndex reports whether f should be indexed. func (e *Encoder) shouldIndex(f HeaderField) bool { return !f.Sensitive && f.Size() <= e.dynTab.maxSize } // appendIndexed appends index i, as encoded in "Indexed Header Field" // representation, to dst and returns the extended buffer. func appendIndexed(dst []byte, i uint64) []byte { first := len(dst) dst = appendVarInt(dst, 7, i) dst[first] |= 0x80 return dst } // appendNewName appends f, as encoded in one of "Literal Header field // - New Name" representation variants, to dst and returns the // extended buffer. // // If f.Sensitive is true, "Never Indexed" representation is used. If // f.Sensitive is false and indexing is true, "Inremental Indexing" // representation is used. func appendNewName(dst []byte, f HeaderField, indexing bool) []byte { dst = append(dst, encodeTypeByte(indexing, f.Sensitive)) dst = appendHpackString(dst, f.Name) return appendHpackString(dst, f.Value) } // appendIndexedName appends f and index i referring indexed name // entry, as encoded in one of "Literal Header field - Indexed Name" // representation variants, to dst and returns the extended buffer. // // If f.Sensitive is true, "Never Indexed" representation is used. If // f.Sensitive is false and indexing is true, "Incremental Indexing" // representation is used. func appendIndexedName(dst []byte, f HeaderField, i uint64, indexing bool) []byte { first := len(dst) var n byte if indexing { n = 6 } else { n = 4 } dst = appendVarInt(dst, n, i) dst[first] |= encodeTypeByte(indexing, f.Sensitive) return appendHpackString(dst, f.Value) } // appendTableSize appends v, as encoded in "Header Table Size Update" // representation, to dst and returns the extended buffer. func appendTableSize(dst []byte, v uint32) []byte { first := len(dst) dst = appendVarInt(dst, 5, uint64(v)) dst[first] |= 0x20 return dst } // appendVarInt appends i, as encoded in variable integer form using n // bit prefix, to dst and returns the extended buffer. // // See // http://http2.github.io/http2-spec/compression.html#integer.representation func appendVarInt(dst []byte, n byte, i uint64) []byte { k := uint64((1 << n) - 1) if i < k { return append(dst, byte(i)) } dst = append(dst, byte(k)) i -= k for ; i >= 128; i >>= 7 { dst = append(dst, byte(0x80|(i&0x7f))) } return append(dst, byte(i)) } // appendHpackString appends s, as encoded in "String Literal" // representation, to dst and returns the the extended buffer. // // s will be encoded in Huffman codes only when it produces strictly // shorter byte string. func appendHpackString(dst []byte, s string) []byte { huffmanLength := HuffmanEncodeLength(s) if huffmanLength < uint64(len(s)) { first := len(dst) dst = appendVarInt(dst, 7, huffmanLength) dst = AppendHuffmanString(dst, s) dst[first] |= 0x80 } else { dst = appendVarInt(dst, 7, uint64(len(s))) dst = append(dst, s...) } return dst } // encodeTypeByte returns type byte. If sensitive is true, type byte // for "Never Indexed" representation is returned. If sensitive is // false and indexing is true, type byte for "Incremental Indexing" // representation is returned. Otherwise, type byte for "Without // Indexing" is returned. func encodeTypeByte(indexing, sensitive bool) byte { if sensitive { return 0x10 } if indexing { return 0x40 } return 0 } lxd-2.0.11/dist/src/golang.org/x/net/http2/headermap.go0000644061062106075000000000264413172163402023637 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "net/http" "strings" ) var ( commonLowerHeader = map[string]string{} // Go-Canonical-Case -> lower-case commonCanonHeader = map[string]string{} // lower-case -> Go-Canonical-Case ) func init() { for _, v := range []string{ "accept", "accept-charset", "accept-encoding", "accept-language", "accept-ranges", "age", "access-control-allow-origin", "allow", "authorization", "cache-control", "content-disposition", "content-encoding", "content-language", "content-length", "content-location", "content-range", "content-type", "cookie", "date", "etag", "expect", "expires", "from", "host", "if-match", "if-modified-since", "if-none-match", "if-unmodified-since", "last-modified", "link", "location", "max-forwards", "proxy-authenticate", "proxy-authorization", "range", "referer", "refresh", "retry-after", "server", "set-cookie", "strict-transport-security", "trailer", "transfer-encoding", "user-agent", "vary", "via", "www-authenticate", } { chk := http.CanonicalHeaderKey(v) commonLowerHeader[chk] = v commonCanonHeader[v] = chk } } func lowerHeader(v string) string { if s, ok := commonLowerHeader[v]; ok { return s } return strings.ToLower(v) } lxd-2.0.11/dist/src/golang.org/x/net/http2/h2i/0000755061062106075000000000000013172163402022036 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/http2/h2i/h2i.go0000644061062106075000000003126513172163402023056 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !plan9,!solaris /* The h2i command is an interactive HTTP/2 console. Usage: $ h2i [flags] Interactive commands in the console: (all parts case-insensitive) ping [data] settings ack settings FOO=n BAR=z headers (open a new stream by typing HTTP/1.1) */ package main import ( "bufio" "bytes" "crypto/tls" "errors" "flag" "fmt" "io" "log" "net" "net/http" "os" "regexp" "strconv" "strings" "golang.org/x/crypto/ssh/terminal" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" ) // Flags var ( flagNextProto = flag.String("nextproto", "h2,h2-14", "Comma-separated list of NPN/ALPN protocol names to negotiate.") flagInsecure = flag.Bool("insecure", false, "Whether to skip TLS cert validation") flagSettings = flag.String("settings", "empty", "comma-separated list of KEY=value settings for the initial SETTINGS frame. The magic value 'empty' sends an empty initial settings frame, and the magic value 'omit' causes no initial settings frame to be sent.") flagDial = flag.String("dial", "", "optional ip:port to dial, to connect to a host:port but use a different SNI name (including a SNI name without DNS)") ) type command struct { run func(*h2i, []string) error // required // complete optionally specifies tokens (case-insensitive) which are // valid for this subcommand. complete func() []string } var commands = map[string]command{ "ping": {run: (*h2i).cmdPing}, "settings": { run: (*h2i).cmdSettings, complete: func() []string { return []string{ "ACK", http2.SettingHeaderTableSize.String(), http2.SettingEnablePush.String(), http2.SettingMaxConcurrentStreams.String(), http2.SettingInitialWindowSize.String(), http2.SettingMaxFrameSize.String(), http2.SettingMaxHeaderListSize.String(), } }, }, "quit": {run: (*h2i).cmdQuit}, "headers": {run: (*h2i).cmdHeaders}, } func usage() { fmt.Fprintf(os.Stderr, "Usage: h2i \n\n") flag.PrintDefaults() } // withPort adds ":443" if another port isn't already present. func withPort(host string) string { if _, _, err := net.SplitHostPort(host); err != nil { return net.JoinHostPort(host, "443") } return host } // withoutPort strips the port from addr if present. func withoutPort(addr string) string { if h, _, err := net.SplitHostPort(addr); err == nil { return h } return addr } // h2i is the app's state. type h2i struct { host string tc *tls.Conn framer *http2.Framer term *terminal.Terminal // owned by the command loop: streamID uint32 hbuf bytes.Buffer henc *hpack.Encoder // owned by the readFrames loop: peerSetting map[http2.SettingID]uint32 hdec *hpack.Decoder } func main() { flag.Usage = usage flag.Parse() if flag.NArg() != 1 { usage() os.Exit(2) } log.SetFlags(0) host := flag.Arg(0) app := &h2i{ host: host, peerSetting: make(map[http2.SettingID]uint32), } app.henc = hpack.NewEncoder(&app.hbuf) if err := app.Main(); err != nil { if app.term != nil { app.logf("%v\n", err) } else { fmt.Fprintf(os.Stderr, "%v\n", err) } os.Exit(1) } fmt.Fprintf(os.Stdout, "\n") } func (app *h2i) Main() error { cfg := &tls.Config{ ServerName: withoutPort(app.host), NextProtos: strings.Split(*flagNextProto, ","), InsecureSkipVerify: *flagInsecure, } hostAndPort := *flagDial if hostAndPort == "" { hostAndPort = withPort(app.host) } log.Printf("Connecting to %s ...", hostAndPort) tc, err := tls.Dial("tcp", hostAndPort, cfg) if err != nil { return fmt.Errorf("Error dialing %s: %v", hostAndPort, err) } log.Printf("Connected to %v", tc.RemoteAddr()) defer tc.Close() if err := tc.Handshake(); err != nil { return fmt.Errorf("TLS handshake: %v", err) } if !*flagInsecure { if err := tc.VerifyHostname(app.host); err != nil { return fmt.Errorf("VerifyHostname: %v", err) } } state := tc.ConnectionState() log.Printf("Negotiated protocol %q", state.NegotiatedProtocol) if !state.NegotiatedProtocolIsMutual || state.NegotiatedProtocol == "" { return fmt.Errorf("Could not negotiate protocol mutually") } if _, err := io.WriteString(tc, http2.ClientPreface); err != nil { return err } app.framer = http2.NewFramer(tc, tc) oldState, err := terminal.MakeRaw(int(os.Stdin.Fd())) if err != nil { return err } defer terminal.Restore(0, oldState) var screen = struct { io.Reader io.Writer }{os.Stdin, os.Stdout} app.term = terminal.NewTerminal(screen, "h2i> ") lastWord := regexp.MustCompile(`.+\W(\w+)$`) app.term.AutoCompleteCallback = func(line string, pos int, key rune) (newLine string, newPos int, ok bool) { if key != '\t' { return } if pos != len(line) { // TODO: we're being lazy for now, only supporting tab completion at the end. return } // Auto-complete for the command itself. if !strings.Contains(line, " ") { var name string name, _, ok = lookupCommand(line) if !ok { return } return name, len(name), true } _, c, ok := lookupCommand(line[:strings.IndexByte(line, ' ')]) if !ok || c.complete == nil { return } if strings.HasSuffix(line, " ") { app.logf("%s", strings.Join(c.complete(), " ")) return line, pos, true } m := lastWord.FindStringSubmatch(line) if m == nil { return line, len(line), true } soFar := m[1] var match []string for _, cand := range c.complete() { if len(soFar) > len(cand) || !strings.EqualFold(cand[:len(soFar)], soFar) { continue } match = append(match, cand) } if len(match) == 0 { return } if len(match) > 1 { // TODO: auto-complete any common prefix app.logf("%s", strings.Join(match, " ")) return line, pos, true } newLine = line[:len(line)-len(soFar)] + match[0] return newLine, len(newLine), true } errc := make(chan error, 2) go func() { errc <- app.readFrames() }() go func() { errc <- app.readConsole() }() return <-errc } func (app *h2i) logf(format string, args ...interface{}) { fmt.Fprintf(app.term, format+"\r\n", args...) } func (app *h2i) readConsole() error { if s := *flagSettings; s != "omit" { var args []string if s != "empty" { args = strings.Split(s, ",") } _, c, ok := lookupCommand("settings") if !ok { panic("settings command not found") } c.run(app, args) } for { line, err := app.term.ReadLine() if err == io.EOF { return nil } if err != nil { return fmt.Errorf("terminal.ReadLine: %v", err) } f := strings.Fields(line) if len(f) == 0 { continue } cmd, args := f[0], f[1:] if _, c, ok := lookupCommand(cmd); ok { err = c.run(app, args) } else { app.logf("Unknown command %q", line) } if err == errExitApp { return nil } if err != nil { return err } } } func lookupCommand(prefix string) (name string, c command, ok bool) { prefix = strings.ToLower(prefix) if c, ok = commands[prefix]; ok { return prefix, c, ok } for full, candidate := range commands { if strings.HasPrefix(full, prefix) { if c.run != nil { return "", command{}, false // ambiguous } c = candidate name = full } } return name, c, c.run != nil } var errExitApp = errors.New("internal sentinel error value to quit the console reading loop") func (a *h2i) cmdQuit(args []string) error { if len(args) > 0 { a.logf("the QUIT command takes no argument") return nil } return errExitApp } func (a *h2i) cmdSettings(args []string) error { if len(args) == 1 && strings.EqualFold(args[0], "ACK") { return a.framer.WriteSettingsAck() } var settings []http2.Setting for _, arg := range args { if strings.EqualFold(arg, "ACK") { a.logf("Error: ACK must be only argument with the SETTINGS command") return nil } eq := strings.Index(arg, "=") if eq == -1 { a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg) return nil } sid, ok := settingByName(arg[:eq]) if !ok { a.logf("Error: unknown setting name %q", arg[:eq]) return nil } val, err := strconv.ParseUint(arg[eq+1:], 10, 32) if err != nil { a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg) return nil } settings = append(settings, http2.Setting{ ID: sid, Val: uint32(val), }) } a.logf("Sending: %v", settings) return a.framer.WriteSettings(settings...) } func settingByName(name string) (http2.SettingID, bool) { for _, sid := range [...]http2.SettingID{ http2.SettingHeaderTableSize, http2.SettingEnablePush, http2.SettingMaxConcurrentStreams, http2.SettingInitialWindowSize, http2.SettingMaxFrameSize, http2.SettingMaxHeaderListSize, } { if strings.EqualFold(sid.String(), name) { return sid, true } } return 0, false } func (app *h2i) cmdPing(args []string) error { if len(args) > 1 { app.logf("invalid PING usage: only accepts 0 or 1 args") return nil // nil means don't end the program } var data [8]byte if len(args) == 1 { copy(data[:], args[0]) } else { copy(data[:], "h2i_ping") } return app.framer.WritePing(false, data) } func (app *h2i) cmdHeaders(args []string) error { if len(args) > 0 { app.logf("Error: HEADERS doesn't yet take arguments.") // TODO: flags for restricting window size, to force CONTINUATION // frames. return nil } var h1req bytes.Buffer app.term.SetPrompt("(as HTTP/1.1)> ") defer app.term.SetPrompt("h2i> ") for { line, err := app.term.ReadLine() if err != nil { return err } h1req.WriteString(line) h1req.WriteString("\r\n") if line == "" { break } } req, err := http.ReadRequest(bufio.NewReader(&h1req)) if err != nil { app.logf("Invalid HTTP/1.1 request: %v", err) return nil } if app.streamID == 0 { app.streamID = 1 } else { app.streamID += 2 } app.logf("Opening Stream-ID %d:", app.streamID) hbf := app.encodeHeaders(req) if len(hbf) > 16<<10 { app.logf("TODO: h2i doesn't yet write CONTINUATION frames. Copy it from transport.go") return nil } return app.framer.WriteHeaders(http2.HeadersFrameParam{ StreamID: app.streamID, BlockFragment: hbf, EndStream: req.Method == "GET" || req.Method == "HEAD", // good enough for now EndHeaders: true, // for now }) } func (app *h2i) readFrames() error { for { f, err := app.framer.ReadFrame() if err != nil { return fmt.Errorf("ReadFrame: %v", err) } app.logf("%v", f) switch f := f.(type) { case *http2.PingFrame: app.logf(" Data = %q", f.Data) case *http2.SettingsFrame: f.ForeachSetting(func(s http2.Setting) error { app.logf(" %v", s) app.peerSetting[s.ID] = s.Val return nil }) case *http2.WindowUpdateFrame: app.logf(" Window-Increment = %v", f.Increment) case *http2.GoAwayFrame: app.logf(" Last-Stream-ID = %d; Error-Code = %v (%d)", f.LastStreamID, f.ErrCode, f.ErrCode) case *http2.DataFrame: app.logf(" %q", f.Data()) case *http2.HeadersFrame: if f.HasPriority() { app.logf(" PRIORITY = %v", f.Priority) } if app.hdec == nil { // TODO: if the user uses h2i to send a SETTINGS frame advertising // something larger, we'll need to respect SETTINGS_HEADER_TABLE_SIZE // and stuff here instead of using the 4k default. But for now: tableSize := uint32(4 << 10) app.hdec = hpack.NewDecoder(tableSize, app.onNewHeaderField) } app.hdec.Write(f.HeaderBlockFragment()) case *http2.PushPromiseFrame: if app.hdec == nil { // TODO: if the user uses h2i to send a SETTINGS frame advertising // something larger, we'll need to respect SETTINGS_HEADER_TABLE_SIZE // and stuff here instead of using the 4k default. But for now: tableSize := uint32(4 << 10) app.hdec = hpack.NewDecoder(tableSize, app.onNewHeaderField) } app.hdec.Write(f.HeaderBlockFragment()) } } } // called from readLoop func (app *h2i) onNewHeaderField(f hpack.HeaderField) { if f.Sensitive { app.logf(" %s = %q (SENSITIVE)", f.Name, f.Value) } app.logf(" %s = %q", f.Name, f.Value) } func (app *h2i) encodeHeaders(req *http.Request) []byte { app.hbuf.Reset() // TODO(bradfitz): figure out :authority-vs-Host stuff between http2 and Go host := req.Host if host == "" { host = req.URL.Host } path := req.RequestURI if path == "" { path = "/" } app.writeHeader(":authority", host) // probably not right for all sites app.writeHeader(":method", req.Method) app.writeHeader(":path", path) app.writeHeader(":scheme", "https") for k, vv := range req.Header { lowKey := strings.ToLower(k) if lowKey == "host" { continue } for _, v := range vv { app.writeHeader(lowKey, v) } } return app.hbuf.Bytes() } func (app *h2i) writeHeader(name, value string) { app.henc.WriteField(hpack.HeaderField{Name: name, Value: value}) app.logf(" %s = %s", name, value) } lxd-2.0.11/dist/src/golang.org/x/net/http2/h2i/README.md0000644061062106075000000000462113172163402023320 0ustar stgraberdomain admins# h2i **h2i** is an interactive HTTP/2 ("h2") console debugger. Miss the good ol' days of telnetting to your HTTP/1.n servers? We're bringing you back. Features: - send raw HTTP/2 frames - PING - SETTINGS - HEADERS - etc - type in HTTP/1.n and have it auto-HPACK/frame-ify it for HTTP/2 - pretty print all received HTTP/2 frames from the peer (including HPACK decoding) - tab completion of commands, options Not yet features, but soon: - unnecessary CONTINUATION frames on short boundaries, to test peer implementations - request bodies (DATA frames) - send invalid frames for testing server implementations (supported by underlying Framer) Later: - act like a server ## Installation ``` $ go get golang.org/x/net/http2/h2i $ h2i ``` ## Demo ``` $ h2i Usage: h2i -insecure Whether to skip TLS cert validation -nextproto string Comma-separated list of NPN/ALPN protocol names to negotiate. (default "h2,h2-14") $ h2i google.com Connecting to google.com:443 ... Connected to 74.125.224.41:443 Negotiated protocol "h2-14" [FrameHeader SETTINGS len=18] [MAX_CONCURRENT_STREAMS = 100] [INITIAL_WINDOW_SIZE = 1048576] [MAX_FRAME_SIZE = 16384] [FrameHeader WINDOW_UPDATE len=4] Window-Increment = 983041 h2i> PING h2iSayHI [FrameHeader PING flags=ACK len=8] Data = "h2iSayHI" h2i> headers (as HTTP/1.1)> GET / HTTP/1.1 (as HTTP/1.1)> Host: ip.appspot.com (as HTTP/1.1)> User-Agent: h2i/brad-n-blake (as HTTP/1.1)> Opening Stream-ID 1: :authority = ip.appspot.com :method = GET :path = / :scheme = https user-agent = h2i/brad-n-blake [FrameHeader HEADERS flags=END_HEADERS stream=1 len=77] :status = "200" alternate-protocol = "443:quic,p=1" content-length = "15" content-type = "text/html" date = "Fri, 01 May 2015 23:06:56 GMT" server = "Google Frontend" [FrameHeader DATA flags=END_STREAM stream=1 len=15] "173.164.155.78\n" [FrameHeader PING len=8] Data = "\x00\x00\x00\x00\x00\x00\x00\x00" h2i> ping [FrameHeader PING flags=ACK len=8] Data = "h2i_ping" h2i> ping [FrameHeader PING flags=ACK len=8] Data = "h2i_ping" h2i> ping [FrameHeader GOAWAY len=22] Last-Stream-ID = 1; Error-Code = PROTOCOL_ERROR (1) ReadFrame: EOF ``` ## Status Quick few hour hack. So much yet to do. Feel free to file issues for bugs or wishlist items, but [@bmizerany](https://github.com/bmizerany/) and I aren't yet accepting pull requests until things settle down. lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/0000755061062106075000000000000013172163402022532 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/tmpl.go0000644061062106075000000020524413172163402024044 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build h2demo package main import "html/template" var pushTmpl = template.Must(template.New("serverpush").Parse(` HTTP/2 Server Push Demo
Note: This page exists for demonstration purposes. For the actual cmd/go docs, go to golang.org/cmd/go.
...

Command go

Go is a tool for managing Go source code.

Usage:

go command [arguments]

The commands are:

build       compile packages and dependencies
clean       remove object files
doc         show documentation for package or symbol
env         print Go environment information
bug         start a bug report
fix         run go tool fix on packages
fmt         run gofmt on package sources
generate    generate Go files by processing source
get         download and install packages and dependencies
install     compile and install packages and dependencies
list        list packages
run         compile and run Go program
test        test packages
tool        run specified go tool
version     print Go version
vet         run go tool vet on packages

Use "go help [command]" for more information about a command.

Additional help topics:

c           calling between Go and C
buildmode   description of build modes
filetype    file types
gopath      GOPATH environment variable
environment environment variables
importpath  import path syntax
packages    description of package lists
testflag    description of testing flags
testfunc    description of testing functions

Use "go help [topic]" for more information about that topic.

Compile packages and dependencies

Usage:

go build [-o output] [-i] [build flags] [packages]

Build compiles the packages named by the import paths, along with their dependencies, but it does not install the results.

If the arguments to build are a list of .go files, build treats them as a list of source files specifying a single package.

When compiling a single main package, build writes the resulting executable to an output file named after the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe') or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe'). The '.exe' suffix is added when writing a Windows executable.

When compiling multiple packages or a single non-main package, build compiles the packages but discards the resulting object, serving only as a check that the packages can be built.

When compiling packages, build ignores files that end in '_test.go'.

The -o flag, only allowed when compiling a single package, forces build to write the resulting executable or object to the named output file, instead of the default behavior described in the last two paragraphs.

The -i flag installs the packages that are dependencies of the target.

The build flags are shared by the build, clean, get, install, list, run, and test commands:

-a
	force rebuilding of packages that are already up-to-date.
-n
	print the commands but do not run them.
-p n
	the number of programs, such as build commands or
	test binaries, that can be run in parallel.
	The default is the number of CPUs available.
-race
	enable data race detection.
	Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64.
-msan
	enable interoperation with memory sanitizer.
	Supported only on linux/amd64,
	and only with Clang/LLVM as the host C compiler.
-v
	print the names of packages as they are compiled.
-work
	print the name of the temporary work directory and
	do not delete it when exiting.
-x
	print the commands.

-asmflags 'flag list'
	arguments to pass on each go tool asm invocation.
-buildmode mode
	build mode to use. See 'go help buildmode' for more.
-compiler name
	name of compiler to use, as in runtime.Compiler (gccgo or gc).
-gccgoflags 'arg list'
	arguments to pass on each gccgo compiler/linker invocation.
-gcflags 'arg list'
	arguments to pass on each go tool compile invocation.
-installsuffix suffix
	a suffix to use in the name of the package installation directory,
	in order to keep output separate from default builds.
	If using the -race flag, the install suffix is automatically set to race
	or, if set explicitly, has _race appended to it.  Likewise for the -msan
	flag.  Using a -buildmode option that requires non-default compile flags
	has a similar effect.
-ldflags 'flag list'
	arguments to pass on each go tool link invocation.
-linkshared
	link against shared libraries previously created with
	-buildmode=shared.
-pkgdir dir
	install and load all packages from dir instead of the usual locations.
	For example, when building with a non-standard configuration,
	use -pkgdir to keep generated packages in a separate location.
-tags 'tag list'
	a list of build tags to consider satisfied during the build.
	For more information about build tags, see the description of
	build constraints in the documentation for the go/build package.
-toolexec 'cmd args'
	a program to use to invoke toolchain programs like vet and asm.
	For example, instead of running asm, the go command will run
	'cmd args /path/to/asm <arguments for asm>'.

The list flags accept a space-separated list of strings. To embed spaces in an element in the list, surround it with either single or double quotes.

For more about specifying packages, see 'go help packages'. For more about where packages and binaries are installed, run 'go help gopath'. For more about calling between Go and C/C++, run 'go help c'.

Note: Build adheres to certain conventions such as those described by 'go help gopath'. Not all projects can follow these conventions, however. Installations that have their own conventions or that use a separate software build system may choose to use lower-level invocations such as 'go tool compile' and 'go tool link' to avoid some of the overheads and design decisions of the build tool.

See also: go install, go get, go clean.

Remove object files

Usage:

go clean [-i] [-r] [-n] [-x] [build flags] [packages]

Clean removes object files from package source directories. The go command builds most objects in a temporary directory, so go clean is mainly concerned with object files left by other tools or by manual invocations of go build.

Specifically, clean removes the following files from each of the source directories corresponding to the import paths:

_obj/            old object directory, left from Makefiles
_test/           old test directory, left from Makefiles
_testmain.go     old gotest file, left from Makefiles
test.out         old test log, left from Makefiles
build.out        old test log, left from Makefiles
*.[568ao]        object files, left from Makefiles

DIR(.exe)        from go build
DIR.test(.exe)   from go test -c
MAINFILE(.exe)   from go build MAINFILE.go
*.so             from SWIG

In the list, DIR represents the final path element of the directory, and MAINFILE is the base name of any Go source file in the directory that is not included when building the package.

The -i flag causes clean to remove the corresponding installed archive or binary (what 'go install' would create).

The -n flag causes clean to print the remove commands it would execute, but not run them.

The -r flag causes clean to be applied recursively to all the dependencies of the packages named by the import paths.

The -x flag causes clean to print remove commands as it executes them.

For more about build flags, see 'go help build'.

For more about specifying packages, see 'go help packages'.

Show documentation for package or symbol

Usage:

go doc [-u] [-c] [package|[package.]symbol[.method]]

Doc prints the documentation comments associated with the item identified by its arguments (a package, const, func, type, var, or method) followed by a one-line summary of each of the first-level items "under" that item (package-level declarations for a package, methods for a type, etc.).

Doc accepts zero, one, or two arguments.

Given no arguments, that is, when run as

go doc

it prints the package documentation for the package in the current directory. If the package is a command (package main), the exported symbols of the package are elided from the presentation unless the -cmd flag is provided.

When run with one argument, the argument is treated as a Go-syntax-like representation of the item to be documented. What the argument selects depends on what is installed in GOROOT and GOPATH, as well as the form of the argument, which is schematically one of these:

go doc <pkg>
go doc <sym>[.<method>]
go doc [<pkg>.]<sym>[.<method>]
go doc [<pkg>.][<sym>.]<method>

The first item in this list matched by the argument is the one whose documentation is printed. (See the examples below.) However, if the argument starts with a capital letter it is assumed to identify a symbol or method in the current directory.

For packages, the order of scanning is determined lexically in breadth-first order. That is, the package presented is the one that matches the search and is nearest the root and lexically first at its level of the hierarchy. The GOROOT tree is always scanned in its entirety before GOPATH.

If there is no package specified or matched, the package in the current directory is selected, so "go doc Foo" shows the documentation for symbol Foo in the current package.

The package path must be either a qualified path or a proper suffix of a path. The go tool's usual package mechanism does not apply: package path elements like . and ... are not implemented by go doc.

When run with two arguments, the first must be a full package path (not just a suffix), and the second is a symbol or symbol and method; this is similar to the syntax accepted by godoc:

go doc <pkg> <sym>[.<method>]

In all forms, when matching symbols, lower-case letters in the argument match either case but upper-case letters match exactly. This means that there may be multiple matches of a lower-case argument in a package if different symbols have different cases. If this occurs, documentation for all matches is printed.

Examples:

go doc
	Show documentation for current package.
go doc Foo
	Show documentation for Foo in the current package.
	(Foo starts with a capital letter so it cannot match
	a package path.)
go doc encoding/json
	Show documentation for the encoding/json package.
go doc json
	Shorthand for encoding/json.
go doc json.Number (or go doc json.number)
	Show documentation and method summary for json.Number.
go doc json.Number.Int64 (or go doc json.number.int64)
	Show documentation for json.Number's Int64 method.
go doc cmd/doc
	Show package docs for the doc command.
go doc -cmd cmd/doc
	Show package docs and exported symbols within the doc command.
go doc template.new
	Show documentation for html/template's New function.
	(html/template is lexically before text/template)
go doc text/template.new # One argument
	Show documentation for text/template's New function.
go doc text/template new # Two arguments
	Show documentation for text/template's New function.

At least in the current tree, these invocations all print the
documentation for json.Decoder's Decode method:

go doc json.Decoder.Decode
go doc json.decoder.decode
go doc json.decode
cd go/src/encoding/json; go doc decode

Flags:

-c
	Respect case when matching symbols.
-cmd
	Treat a command (package main) like a regular package.
	Otherwise package main's exported symbols are hidden
	when showing the package's top-level documentation.
-u
	Show documentation for unexported as well as exported
	symbols and methods.

Print Go environment information

Usage:

go env [var ...]

Env prints Go environment information.

By default env prints information as a shell script (on Windows, a batch file). If one or more variable names is given as arguments, env prints the value of each named variable on its own line.

Start a bug report

Usage:

go bug

Bug opens the default browser and starts a new bug report. The report includes useful system information.

Run go tool fix on packages

Usage:

go fix [packages]

Fix runs the Go fix command on the packages named by the import paths.

For more about fix, see 'go doc cmd/fix'. For more about specifying packages, see 'go help packages'.

To run fix with specific options, run 'go tool fix'.

See also: go fmt, go vet.

Run gofmt on package sources

Usage:

go fmt [-n] [-x] [packages]

Fmt runs the command 'gofmt -l -w' on the packages named by the import paths. It prints the names of the files that are modified.

For more about gofmt, see 'go doc cmd/gofmt'. For more about specifying packages, see 'go help packages'.

The -n flag prints commands that would be executed. The -x flag prints commands as they are executed.

To run gofmt with specific options, run gofmt itself.

See also: go fix, go vet.

Generate Go files by processing source

Usage:

go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]

Generate runs commands described by directives within existing files. Those commands can run any process but the intent is to create or update Go source files.

Go generate is never run automatically by go build, go get, go test, and so on. It must be run explicitly.

Go generate scans the file for directives, which are lines of the form,

//go:generate command argument...

(note: no leading spaces and no space in "//go") where command is the generator to be run, corresponding to an executable file that can be run locally. It must either be in the shell path (gofmt), a fully qualified path (/usr/you/bin/mytool), or a command alias, described below.

Note that go generate does not parse the file, so lines that look like directives in comments or multiline strings will be treated as directives.

The arguments to the directive are space-separated tokens or double-quoted strings passed to the generator as individual arguments when it is run.

Quoted strings use Go syntax and are evaluated before execution; a quoted string appears as a single argument to the generator.

Go generate sets several variables when it runs the generator:

$GOARCH
	The execution architecture (arm, amd64, etc.)
$GOOS
	The execution operating system (linux, windows, etc.)
$GOFILE
	The base name of the file.
$GOLINE
	The line number of the directive in the source file.
$GOPACKAGE
	The name of the package of the file containing the directive.
$DOLLAR
	A dollar sign.

Other than variable substitution and quoted-string evaluation, no special processing such as "globbing" is performed on the command line.

As a last step before running the command, any invocations of any environment variables with alphanumeric names, such as $GOFILE or $HOME, are expanded throughout the command line. The syntax for variable expansion is $NAME on all operating systems. Due to the order of evaluation, variables are expanded even inside quoted strings. If the variable NAME is not set, $NAME expands to the empty string.

A directive of the form,

//go:generate -command xxx args...

specifies, for the remainder of this source file only, that the string xxx represents the command identified by the arguments. This can be used to create aliases or to handle multiword generators. For example,

//go:generate -command foo go tool foo

specifies that the command "foo" represents the generator "go tool foo".

Generate processes packages in the order given on the command line, one at a time. If the command line lists .go files, they are treated as a single package. Within a package, generate processes the source files in a package in file name order, one at a time. Within a source file, generate runs generators in the order they appear in the file, one at a time.

If any generator returns an error exit status, "go generate" skips all further processing for that package.

The generator is run in the package's source directory.

Go generate accepts one specific flag:

-run=""
	if non-empty, specifies a regular expression to select
	directives whose full original source text (excluding
	any trailing spaces and final newline) matches the
	expression.

It also accepts the standard build flags including -v, -n, and -x. The -v flag prints the names of packages and files as they are processed. The -n flag prints commands that would be executed. The -x flag prints commands as they are executed.

For more about build flags, see 'go help build'.

For more about specifying packages, see 'go help packages'.

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-fix] [-insecure] [-t] [-u] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/<import-path>. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the most recent version of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

See also: go build, go install, go clean.

Compile and install packages and dependencies

Usage:

go install [build flags] [packages]

Install compiles and installs the packages named by the import paths, along with their dependencies.

For more about the build flags, see 'go help build'. For more about specifying packages, see 'go help packages'.

See also: go build, go get, go clean.

List packages

Usage:

go list [-e] [-f format] [-json] [build flags] [packages]

List lists the packages named by the import paths, one per line.

The default output shows the package import path:

bytes
encoding/json
github.com/gorilla/mux
golang.org/x/net/html

The -f flag specifies an alternate format for the list, using the syntax of package template. The default output is equivalent to -f ''. The struct being passed to the template is:

type Package struct {
    Dir           string // directory containing package sources
    ImportPath    string // import path of package in dir
    ImportComment string // path in import comment on package statement
    Name          string // package name
    Doc           string // package documentation string
    Target        string // install path
    Shlib         string // the shared library that contains this package (only set when -linkshared)
    Goroot        bool   // is this package in the Go root?
    Standard      bool   // is this package part of the standard Go library?
    Stale         bool   // would 'go install' do anything for this package?
    StaleReason   string // explanation for Stale==true
    Root          string // Go root or Go path dir containing this package
    ConflictDir   string // this directory shadows Dir in $GOPATH
    BinaryOnly    bool   // binary-only package: cannot be recompiled from sources

    // Source files
    GoFiles        []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
    CgoFiles       []string // .go sources files that import "C"
    IgnoredGoFiles []string // .go sources ignored due to build constraints
    CFiles         []string // .c source files
    CXXFiles       []string // .cc, .cxx and .cpp source files
    MFiles         []string // .m source files
    HFiles         []string // .h, .hh, .hpp and .hxx source files
    FFiles         []string // .f, .F, .for and .f90 Fortran source files
    SFiles         []string // .s source files
    SwigFiles      []string // .swig files
    SwigCXXFiles   []string // .swigcxx files
    SysoFiles      []string // .syso object files to add to archive
    TestGoFiles    []string // _test.go files in package
    XTestGoFiles   []string // _test.go files outside package

    // Cgo directives
    CgoCFLAGS    []string // cgo: flags for C compiler
    CgoCPPFLAGS  []string // cgo: flags for C preprocessor
    CgoCXXFLAGS  []string // cgo: flags for C++ compiler
    CgoFFLAGS    []string // cgo: flags for Fortran compiler
    CgoLDFLAGS   []string // cgo: flags for linker
    CgoPkgConfig []string // cgo: pkg-config names

    // Dependency information
    Imports      []string // import paths used by this package
    Deps         []string // all (recursively) imported dependencies
    TestImports  []string // imports from TestGoFiles
    XTestImports []string // imports from XTestGoFiles

    // Error information
    Incomplete bool            // this package or a dependency has an error
    Error      *PackageError   // error loading package
    DepsErrors []*PackageError // errors loading dependencies
}

Packages stored in vendor directories report an ImportPath that includes the path to the vendor directory (for example, "d/vendor/p" instead of "p"), so that the ImportPath uniquely identifies a given copy of a package. The Imports, Deps, TestImports, and XTestImports lists also contain these expanded imports paths. See golang.org/s/go15vendor for more about vendoring.

The error information, if any, is

type PackageError struct {
    ImportStack   []string // shortest path from package named on command line to this one
    Pos           string   // position of error (if present, file:line:col)
    Err           string   // the error itself
}

The template function "join" calls strings.Join.

The template function "context" returns the build context, defined as:

type Context struct {
	GOARCH        string   // target architecture
	GOOS          string   // target operating system
	GOROOT        string   // Go root
	GOPATH        string   // Go path
	CgoEnabled    bool     // whether cgo can be used
	UseAllFiles   bool     // use files regardless of +build lines, file names
	Compiler      string   // compiler to assume when computing target paths
	BuildTags     []string // build constraints to match in +build lines
	ReleaseTags   []string // releases the current release is compatible with
	InstallSuffix string   // suffix to use in the name of the install dir
}

For more information about the meaning of these fields see the documentation for the go/build package's Context type.

The -json flag causes the package data to be printed in JSON format instead of using the template format.

The -e flag changes the handling of erroneous packages, those that cannot be found or are malformed. By default, the list command prints an error to standard error for each erroneous package and omits the packages from consideration during the usual printing. With the -e flag, the list command never prints errors to standard error and instead processes the erroneous packages with the usual printing. Erroneous packages will have a non-empty ImportPath and a non-nil Error field; other information may or may not be missing (zeroed).

For more about build flags, see 'go help build'.

For more about specifying packages, see 'go help packages'.

Compile and run Go program

Usage:

go run [build flags] [-exec xprog] gofiles... [arguments...]

Run compiles and runs the main package comprising the named Go source files. A Go source file is defined to be a file ending in a literal ".go" suffix.

By default, 'go run' runs the compiled binary directly: 'a.out arguments...'. If the -exec flag is given, 'go run' invokes the binary using xprog:

'xprog a.out arguments...'.

If the -exec flag is not given, GOOS or GOARCH is different from the system default, and a program named go_$GOOS_$GOARCH_exec can be found on the current search path, 'go run' invokes the binary using that program, for example 'go_nacl_386_exec a.out arguments...'. This allows execution of cross-compiled programs when a simulator or other execution method is available.

For more about build flags, see 'go help build'.

See also: go build.

Test packages

Usage:

go test [build/test flags] [packages] [build/test flags & test binary flags]

'Go test' automates testing the packages named by the import paths. It prints a summary of the test results in the format:

ok   archive/tar   0.011s
FAIL archive/zip   0.022s
ok   compress/gzip 0.033s
...

followed by detailed output for each failed package.

'Go test' recompiles each package along with any files with names matching the file pattern "*_test.go". Files whose names begin with "_" (including "_test.go") or "." are ignored. These additional files can contain test functions, benchmark functions, and example functions. See 'go help testfunc' for more. Each listed package causes the execution of a separate test binary.

Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary.

The go tool will ignore a directory named "testdata", making it available to hold ancillary data needed by the tests.

By default, go test needs no arguments. It compiles and tests the package with source in the current directory, including tests, and runs the tests.

The package is built in a temporary directory so it does not interfere with the non-test installation.

In addition to the build flags, the flags handled by 'go test' itself are:

-args
    Pass the remainder of the command line (everything after -args)
    to the test binary, uninterpreted and unchanged.
    Because this flag consumes the remainder of the command line,
    the package list (if present) must appear before this flag.

-c
    Compile the test binary to pkg.test but do not run it
    (where pkg is the last element of the package's import path).
    The file name can be changed with the -o flag.

-exec xprog
    Run the test binary using xprog. The behavior is the same as
    in 'go run'. See 'go help run' for details.

-i
    Install packages that are dependencies of the test.
    Do not run the test.

-o file
    Compile the test binary to the named file.
    The test still runs (unless -c or -i is specified).

The test binary also accepts flags that control execution of the test; these flags are also accessible by 'go test'. See 'go help testflag' for details.

For more about build flags, see 'go help build'. For more about specifying packages, see 'go help packages'.

See also: go build, go vet.

Run specified go tool

Usage:

go tool [-n] command [args...]

Tool runs the go tool command identified by the arguments. With no arguments it prints the list of known tools.

The -n flag causes tool to print the command that would be executed but not execute it.

For more about each tool command, see 'go tool command -h'.

Print Go version

Usage:

go version

Version prints the Go version, as reported by runtime.Version.

Run go tool vet on packages

Usage:

go vet [-n] [-x] [build flags] [packages]

Vet runs the Go vet command on the packages named by the import paths.

For more about vet, see 'go doc cmd/vet'. For more about specifying packages, see 'go help packages'.

To run the vet tool with specific options, run 'go tool vet'.

The -n flag prints commands that would be executed. The -x flag prints commands as they are executed.

For more about build flags, see 'go help build'.

See also: go fmt, go fix.

Calling between Go and C

There are two different ways to call between Go and C/C++ code.

The first is the cgo tool, which is part of the Go distribution. For information on how to use it see the cgo documentation (go doc cmd/cgo).

The second is the SWIG program, which is a general tool for interfacing between languages. For information on SWIG see http://swig.org/. When running go build, any file with a .swig extension will be passed to SWIG. Any file with a .swigcxx extension will be passed to SWIG with the -c++ option.

When either cgo or SWIG is used, go build will pass any .c, .m, .s, or .S files to the C compiler, and any .cc, .cpp, .cxx files to the C++ compiler. The CC or CXX environment variables may be set to determine the C or C++ compiler, respectively, to use.

Description of build modes

The 'go build' and 'go install' commands take a -buildmode argument which indicates which kind of object file is to be built. Currently supported values are:

-buildmode=archive
	Build the listed non-main packages into .a files. Packages named
	main are ignored.

-buildmode=c-archive
	Build the listed main package, plus all packages it imports,
	into a C archive file. The only callable symbols will be those
	functions exported using a cgo //export comment. Requires
	exactly one main package to be listed.

-buildmode=c-shared
	Build the listed main packages, plus all packages that they
	import, into C shared libraries. The only callable symbols will
	be those functions exported using a cgo //export comment.
	Non-main packages are ignored.

-buildmode=default
	Listed main packages are built into executables and listed
	non-main packages are built into .a files (the default
	behavior).

-buildmode=shared
	Combine all the listed non-main packages into a single shared
	library that will be used when building with the -linkshared
	option. Packages named main are ignored.

-buildmode=exe
	Build the listed main packages and everything they import into
	executables. Packages not named main are ignored.

-buildmode=pie
	Build the listed main packages and everything they import into
	position independent executables (PIE). Packages not named
	main are ignored.

-buildmode=plugin
	Build the listed main packages, plus all packages that they
	import, into a Go plugin. Packages not named main are ignored.

File types

The go command examines the contents of a restricted set of files in each directory. It identifies which files to examine based on the extension of the file name. These extensions are:

.go
	Go source files.
.c, .h
	C source files.
	If the package uses cgo or SWIG, these will be compiled with the
	OS-native compiler (typically gcc); otherwise they will
	trigger an error.
.cc, .cpp, .cxx, .hh, .hpp, .hxx
	C++ source files. Only useful with cgo or SWIG, and always
	compiled with the OS-native compiler.
.m
	Objective-C source files. Only useful with cgo, and always
	compiled with the OS-native compiler.
.s, .S
	Assembler source files.
	If the package uses cgo or SWIG, these will be assembled with the
	OS-native assembler (typically gcc (sic)); otherwise they
	will be assembled with the Go assembler.
.swig, .swigcxx
	SWIG definition files.
.syso
	System object files.

Files of each of these types except .syso may contain build constraints, but the go command stops scanning for build constraints at the first item in the file that is not a blank line or //-style line comment. See the go/build package documentation for more details.

Non-test Go source files can also include a //go:binary-only-package comment, indicating that the package sources are included for documentation only and must not be used to build the package binary. This enables distribution of Go packages in their compiled form alone. See the go/build package documentation for more details.

GOPATH environment variable

The Go path is used to resolve import statements. It is implemented by and documented in the go/build package.

The GOPATH environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string. On Plan 9, the value is a list.

If the environment variable is unset, GOPATH defaults to a subdirectory named "go" in the user's home directory ($HOME/go on Unix, %USERPROFILE%\go on Windows), unless that directory holds a Go distribution. Run "go env GOPATH" to see the current GOPATH.

See https://golang.org/wiki/SettingGOPATH to set a custom GOPATH.

Each directory listed in GOPATH must have a prescribed structure:

The src directory holds source code. The path below src determines the import path or executable name.

The pkg directory holds installed package objects. As in the Go tree, each target operating system and architecture pair has its own subdirectory of pkg (pkg/GOOS_GOARCH).

If DIR is a directory listed in the GOPATH, a package with source in DIR/src/foo/bar can be imported as "foo/bar" and has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a".

The bin directory holds compiled commands. Each command is named for its source directory, but only the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The "foo/" prefix is stripped so that you can add DIR/bin to your PATH to get at the installed commands. If the GOBIN environment variable is set, commands are installed to the directory it names instead of DIR/bin. GOBIN must be an absolute path.

Here's an example directory layout:

GOPATH=/home/user/go

/home/user/go/
    src/
        foo/
            bar/               (go code in package bar)
                x.go
            quux/              (go code in package main)
                y.go
    bin/
        quux                   (installed command)
    pkg/
        linux_amd64/
            foo/
                bar.a          (installed package object)

Go searches each directory listed in GOPATH to find source code, but new packages are always downloaded into the first directory in the list.

See https://golang.org/doc/code.html for an example.

Internal Directories

Code in or below a directory named "internal" is importable only by code in the directory tree rooted at the parent of "internal". Here's an extended version of the directory layout above:

/home/user/go/
    src/
        crash/
            bang/              (go code in package bang)
                b.go
        foo/                   (go code in package foo)
            f.go
            bar/               (go code in package bar)
                x.go
            internal/
                baz/           (go code in package baz)
                    z.go
            quux/              (go code in package main)
                y.go

The code in z.go is imported as "foo/internal/baz", but that import statement can only appear in source files in the subtree rooted at foo. The source files foo/f.go, foo/bar/x.go, and foo/quux/y.go can all import "foo/internal/baz", but the source file crash/bang/b.go cannot.

See https://golang.org/s/go14internal for details.

Vendor Directories

Go 1.6 includes support for using local copies of external dependencies to satisfy imports of those dependencies, often referred to as vendoring.

Code below a directory named "vendor" is importable only by code in the directory tree rooted at the parent of "vendor", and only using an import path that omits the prefix up to and including the vendor element.

Here's the example from the previous section, but with the "internal" directory renamed to "vendor" and a new foo/vendor/crash/bang directory added:

/home/user/go/
    src/
        crash/
            bang/              (go code in package bang)
                b.go
        foo/                   (go code in package foo)
            f.go
            bar/               (go code in package bar)
                x.go
            vendor/
                crash/
                    bang/      (go code in package bang)
                        b.go
                baz/           (go code in package baz)
                    z.go
            quux/              (go code in package main)
                y.go

The same visibility rules apply as for internal, but the code in z.go is imported as "baz", not as "foo/vendor/baz".

Code in vendor directories deeper in the source tree shadows code in higher directories. Within the subtree rooted at foo, an import of "crash/bang" resolves to "foo/vendor/crash/bang", not the top-level "crash/bang".

Code in vendor directories is not subject to import path checking (see 'go help importpath').

When 'go get' checks out or updates a git repository, it now also updates submodules.

Vendor directories do not affect the placement of new repositories being checked out for the first time by 'go get': those are always placed in the main GOPATH, never in a vendor subtree.

See https://golang.org/s/go15vendor for details.

Environment variables

The go command, and the tools it invokes, examine a few different environment variables. For many of these, you can see the default value of on your system by running 'go env NAME', where NAME is the name of the variable.

General-purpose environment variables:

GCCGO
	The gccgo command to run for 'go build -compiler=gccgo'.
GOARCH
	The architecture, or processor, for which to compile code.
	Examples are amd64, 386, arm, ppc64.
GOBIN
	The directory where 'go install' will install a command.
GOOS
	The operating system for which to compile code.
	Examples are linux, darwin, windows, netbsd.
GOPATH
	For more details see: 'go help gopath'.
GORACE
	Options for the race detector.
	See https://golang.org/doc/articles/race_detector.html.
GOROOT
	The root of the go tree.

Environment variables for use with cgo:

CC
	The command to use to compile C code.
CGO_ENABLED
	Whether the cgo command is supported.  Either 0 or 1.
CGO_CFLAGS
	Flags that cgo will pass to the compiler when compiling
	C code.
CGO_CPPFLAGS
	Flags that cgo will pass to the compiler when compiling
	C or C++ code.
CGO_CXXFLAGS
	Flags that cgo will pass to the compiler when compiling
	C++ code.
CGO_FFLAGS
	Flags that cgo will pass to the compiler when compiling
	Fortran code.
CGO_LDFLAGS
	Flags that cgo will pass to the compiler when linking.
CXX
	The command to use to compile C++ code.
PKG_CONFIG
	Path to pkg-config tool.

Architecture-specific environment variables:

GOARM
	For GOARCH=arm, the ARM architecture for which to compile.
	Valid values are 5, 6, 7.
GO386
	For GOARCH=386, the floating point instruction set.
	Valid values are 387, sse2.

Special-purpose environment variables:

GOROOT_FINAL
	The root of the installed Go tree, when it is
	installed in a location other than where it is built.
	File names in stack traces are rewritten from GOROOT to
	GOROOT_FINAL.
GO_EXTLINK_ENABLED
	Whether the linker should use external linking mode
	when using -linkmode=auto with code that uses cgo.
	Set to 0 to disable external linking mode, 1 to enable it.
GIT_ALLOW_PROTOCOL
	Defined by Git. A colon-separated list of schemes that are allowed to be used
	with git fetch/clone. If set, any scheme not explicitly mentioned will be
	considered insecure by 'go get'.

Import path syntax

An import path (see 'go help packages') denotes a package stored in the local file system. In general, an import path denotes either a standard package (such as "unicode/utf8") or a package found in one of the work spaces (For more details see: 'go help gopath').

Relative import paths

An import path beginning with ./ or ../ is called a relative path. The toolchain supports relative import paths as a shortcut in two ways.

First, a relative path can be used as a shorthand on the command line. If you are working in the directory containing the code imported as "unicode" and want to run the tests for "unicode/utf8", you can type "go test ./utf8" instead of needing to specify the full path. Similarly, in the reverse situation, "go test .." will test "unicode" from the "unicode/utf8" directory. Relative patterns are also allowed, like "go test ./..." to test all subdirectories. See 'go help packages' for details on the pattern syntax.

Second, if you are compiling a Go program not in a work space, you can use a relative path in an import statement in that program to refer to nearby code also not in a work space. This makes it easy to experiment with small multipackage programs outside of the usual work spaces, but such programs cannot be installed with "go install" (there is no work space in which to install them), so they are rebuilt from scratch each time they are built. To avoid ambiguity, Go programs cannot use relative import paths within a work space.

Remote import paths

Certain import paths also describe how to obtain the source code for the package using a revision control system.

A few common code hosting sites have special syntax:

Bitbucket (Git, Mercurial)

	import "bitbucket.org/user/project"
	import "bitbucket.org/user/project/sub/directory"

GitHub (Git)

	import "github.com/user/project"
	import "github.com/user/project/sub/directory"

Launchpad (Bazaar)

	import "launchpad.net/project"
	import "launchpad.net/project/series"
	import "launchpad.net/project/series/sub/directory"

	import "launchpad.net/~user/project/branch"
	import "launchpad.net/~user/project/branch/sub/directory"

IBM DevOps Services (Git)

	import "hub.jazz.net/git/user/project"
	import "hub.jazz.net/git/user/project/sub/directory"

For code hosted on other servers, import paths may either be qualified with the version control type, or the go tool can dynamically fetch the import path over https/http and discover where the code resides from a <meta> tag in the HTML.

To declare the code location, an import path of the form

repository.vcs/path

specifies the given repository, with or without the .vcs suffix, using the named version control system, and then the path inside that repository. The supported version control systems are:

Bazaar      .bzr
Git         .git
Mercurial   .hg
Subversion  .svn

For example,

import "example.org/user/foo.hg"

denotes the root directory of the Mercurial repository at example.org/user/foo or foo.hg, and

import "example.org/repo.git/foo/bar"

denotes the foo/bar directory of the Git repository at example.org/repo or repo.git.

When a version control system supports multiple protocols, each is tried in turn when downloading. For example, a Git download tries https://, then git+ssh://.

By default, downloads are restricted to known secure protocols (e.g. https, ssh). To override this setting for Git downloads, the GIT_ALLOW_PROTOCOL environment variable can be set (For more details see: 'go help environment').

If the import path is not a known code hosting site and also lacks a version control qualifier, the go tool attempts to fetch the import over https/http and looks for a <meta> tag in the document's HTML <head>.

The meta tag has the form:

<meta name="go-import" content="import-prefix vcs repo-root">

The import-prefix is the import path corresponding to the repository root. It must be a prefix or an exact match of the package being fetched with "go get". If it's not an exact match, another http request is made at the prefix to verify the <meta> tags match.

The meta tag should appear as early in the file as possible. In particular, it should appear before any raw JavaScript or CSS, to avoid confusing the go command's restricted parser.

The vcs is one of "git", "hg", "svn", etc,

The repo-root is the root of the version control system containing a scheme and not containing a .vcs qualifier.

For example,

import "example.org/pkg/foo"

will result in the following requests:

https://example.org/pkg/foo?go-get=1 (preferred)
http://example.org/pkg/foo?go-get=1  (fallback, only with -insecure)

If that page contains the meta tag

<meta name="go-import" content="example.org git https://code.org/r/p/exproj">

the go tool will verify that https://example.org/?go-get=1 contains the same meta tag and then git clone https://code.org/r/p/exproj into GOPATH/src/example.org.

New downloaded packages are written to the first directory listed in the GOPATH environment variable (For more details see: 'go help gopath').

The go command attempts to download the version of the package appropriate for the Go release being used. Run 'go help get' for more.

Import path checking

When the custom import path feature described above redirects to a known code hosting site, each of the resulting packages has two possible import paths, using the custom domain or the known hosting site.

A package statement is said to have an "import comment" if it is immediately followed (before the next newline) by a comment of one of these two forms:

package math // import "path"
package math /* import "path" */

The go command will refuse to install a package with an import comment unless it is being referred to by that import path. In this way, import comments let package authors make sure the custom import path is used and not a direct path to the underlying code hosting site.

Import path checking is disabled for code found within vendor trees. This makes it possible to copy code into alternate locations in vendor trees without needing to update import comments.

See https://golang.org/s/go14customimport for details.

Description of package lists

Many commands apply to a set of packages:

go action [packages]

Usually, [packages] is a list of import paths.

An import path that is a rooted path or that begins with a . or .. element is interpreted as a file system path and denotes the package in that directory.

Otherwise, the import path P denotes the package found in the directory DIR/src/P for some DIR listed in the GOPATH environment variable (For more details see: 'go help gopath').

If no import paths are given, the action applies to the package in the current directory.

There are four reserved names for paths that should not be used for packages to be built with the go tool:

- "main" denotes the top-level package in a stand-alone executable.

- "all" expands to all package directories found in all the GOPATH trees. For example, 'go list all' lists all the packages on the local system.

- "std" is like all but expands to just the packages in the standard Go library.

- "cmd" expands to the Go repository's commands and their internal libraries.

Import paths beginning with "cmd/" only match source code in the Go repository.

An import path is a pattern if it includes one or more "..." wildcards, each of which can match any string, including the empty string and strings containing slashes. Such a pattern expands to all package directories found in the GOPATH trees with names matching the patterns. As a special case, x/... matches x as well as x's subdirectories. For example, net/... expands to net and packages in its subdirectories.

An import path can also name a package to be downloaded from a remote repository. Run 'go help importpath' for details.

Every package in a program must have a unique import path. By convention, this is arranged by starting each path with a unique prefix that belongs to you. For example, paths used internally at Google all begin with 'google', and paths denoting remote repositories begin with the path to the code, such as 'github.com/user/repo'.

Packages in a program need not have unique package names, but there are two reserved package names with special meaning. The name main indicates a command, not a library. Commands are built into binaries and cannot be imported. The name documentation indicates documentation for a non-Go program in the directory. Files in package documentation are ignored by the go command.

As a special case, if the package list is a list of .go files from a single directory, the command is applied to a single synthesized package made up of exactly those files, ignoring any build constraints in those files and ignoring any other files in the directory.

Directory and file names that begin with "." or "_" are ignored by the go tool, as are directories named "testdata".

Description of testing flags

The 'go test' command takes both flags that apply to 'go test' itself and flags that apply to the resulting test binary.

Several of the flags control profiling and write an execution profile suitable for "go tool pprof"; run "go tool pprof -h" for more information. The --alloc_space, --alloc_objects, and --show_bytes options of pprof control how the information is presented.

The following flags are recognized by the 'go test' command and control the execution of any test:

-bench regexp
    Run (sub)benchmarks matching a regular expression.
    The given regular expression is split into smaller ones by
    top-level '/', where each must match the corresponding part of a
    benchmark's identifier.
    By default, no benchmarks run. To run all benchmarks,
    use '-bench .' or '-bench=.'.

-benchtime t
    Run enough iterations of each benchmark to take t, specified
    as a time.Duration (for example, -benchtime 1h30s).
    The default is 1 second (1s).

-count n
    Run each test and benchmark n times (default 1).
    If -cpu is set, run n times for each GOMAXPROCS value.
    Examples are always run once.

-cover
    Enable coverage analysis.

-covermode set,count,atomic
    Set the mode for coverage analysis for the package[s]
    being tested. The default is "set" unless -race is enabled,
    in which case it is "atomic".
    The values:
	set: bool: does this statement run?
	count: int: how many times does this statement run?
	atomic: int: count, but correct in multithreaded tests;
		significantly more expensive.
    Sets -cover.

-coverpkg pkg1,pkg2,pkg3
    Apply coverage analysis in each test to the given list of packages.
    The default is for each test to analyze only the package being tested.
    Packages are specified as import paths.
    Sets -cover.

-cpu 1,2,4
    Specify a list of GOMAXPROCS values for which the tests or
    benchmarks should be executed.  The default is the current value
    of GOMAXPROCS.

-parallel n
    Allow parallel execution of test functions that call t.Parallel.
    The value of this flag is the maximum number of tests to run
    simultaneously; by default, it is set to the value of GOMAXPROCS.
    Note that -parallel only applies within a single test binary.
    The 'go test' command may run tests for different packages
    in parallel as well, according to the setting of the -p flag
    (see 'go help build').

-run regexp
    Run only those tests and examples matching the regular expression.
    For tests the regular expression is split into smaller ones by
    top-level '/', where each must match the corresponding part of a
    test's identifier.

-short
    Tell long-running tests to shorten their run time.
    It is off by default but set during all.bash so that installing
    the Go tree can run a sanity check but not spend time running
    exhaustive tests.

-timeout t
    If a test runs longer than t, panic.
    The default is 10 minutes (10m).

-v
    Verbose output: log all tests as they are run. Also print all
    text from Log and Logf calls even if the test succeeds.

The following flags are also recognized by 'go test' and can be used to profile the tests during execution:

-benchmem
    Print memory allocation statistics for benchmarks.

-blockprofile block.out
    Write a goroutine blocking profile to the specified file
    when all tests are complete.
    Writes test binary as -c would.

-blockprofilerate n
    Control the detail provided in goroutine blocking profiles by
    calling runtime.SetBlockProfileRate with n.
    See 'go doc runtime.SetBlockProfileRate'.
    The profiler aims to sample, on average, one blocking event every
    n nanoseconds the program spends blocked.  By default,
    if -test.blockprofile is set without this flag, all blocking events
    are recorded, equivalent to -test.blockprofilerate=1.

-coverprofile cover.out
    Write a coverage profile to the file after all tests have passed.
    Sets -cover.

-cpuprofile cpu.out
    Write a CPU profile to the specified file before exiting.
    Writes test binary as -c would.

-memprofile mem.out
    Write a memory profile to the file after all tests have passed.
    Writes test binary as -c would.

-memprofilerate n
    Enable more precise (and expensive) memory profiles by setting
    runtime.MemProfileRate.  See 'go doc runtime.MemProfileRate'.
    To profile all memory allocations, use -test.memprofilerate=1
    and pass --alloc_space flag to the pprof tool.

-mutexprofile mutex.out
    Write a mutex contention profile to the specified file
    when all tests are complete.
    Writes test binary as -c would.

-mutexprofilefraction n
    Sample 1 in n stack traces of goroutines holding a
    contended mutex.

-outputdir directory
    Place output files from profiling in the specified directory,
    by default the directory in which "go test" is running.

-trace trace.out
    Write an execution trace to the specified file before exiting.

Each of these flags is also recognized with an optional 'test.' prefix, as in -test.v. When invoking the generated test binary (the result of 'go test -c') directly, however, the prefix is mandatory.

The 'go test' command rewrites or removes recognized flags, as appropriate, both before and after the optional package list, before invoking the test binary.

For instance, the command

go test -v -myflag testdata -cpuprofile=prof.out -x

will compile the test binary and then run it as

pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out

(The -x flag is removed because it applies only to the go command's execution, not to the test itself.)

The test flags that generate profiles (other than for coverage) also leave the test binary in pkg.test for use when analyzing the profiles.

When 'go test' runs a test binary, it does so from within the corresponding package's source code directory. Depending on the test, it may be necessary to do the same when invoking a generated test binary directly.

The command-line package list, if present, must appear before any flag not known to the go test command. Continuing the example above, the package list would have to appear before -myflag, but could appear on either side of -v.

To keep an argument for a test binary from being interpreted as a known flag or a package name, use -args (see 'go help test') which passes the remainder of the command line through to the test binary uninterpreted and unaltered.

For instance, the command

go test -v -args -x -v

will compile the test binary and then run it as

pkg.test -test.v -x -v

Similarly,

go test -args math

will compile the test binary and then run it as

pkg.test math

In the first example, the -x and the second -v are passed through to the test binary unchanged and with no effect on the go command itself. In the second example, the argument math is passed through to the test binary, instead of being interpreted as the package list.

Description of testing functions

The 'go test' command expects to find test, benchmark, and example functions in the "*_test.go" files corresponding to the package under test.

A test function is one named TestXXX (where XXX is any alphanumeric string not starting with a lower case letter) and should have the signature,

func TestXXX(t *testing.T) { ... }

A benchmark function is one named BenchmarkXXX and should have the signature,

func BenchmarkXXX(b *testing.B) { ... }

An example function is similar to a test function but, instead of using *testing.T to report success or failure, prints output to os.Stdout. If the last comment in the function starts with "Output:" then the output is compared exactly against the comment (see examples below). If the last comment begins with "Unordered output:" then the output is compared to the comment, however the order of the lines is ignored. An example with no such comment is compiled but not executed. An example with no text after "Output:" is compiled, executed, and expected to produce no output.

Godoc displays the body of ExampleXXX to demonstrate the use of the function, constant, or variable XXX. An example of a method M with receiver type T or *T is named ExampleT_M. There may be multiple examples for a given function, constant, or variable, distinguished by a trailing _xxx, where xxx is a suffix not beginning with an upper case letter.

Here is an example of an example:

func ExamplePrintln() {
	Println("The output of\nthis example.")
	// Output: The output of
	// this example.
}

Here is another example where the ordering of the output is ignored:

func ExamplePerm() {
	for _, value := range Perm(4) {
		fmt.Println(value)
	}

	// Unordered output: 4
	// 2
	// 1
	// 3
	// 0
}

The entire test file is presented as the example when it contains a single example function, at least one other function, type, variable, or constant declaration, and no test or benchmark functions.

See the documentation of the testing package for more information.

`)) lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/server.key0000644061062106075000000000321313172163402024551 0ustar stgraberdomain admins-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAs1Y9CyLFrdL8VQWN1WaifDqaZFnoqjHhCMlc1TfG2zA+InDi fx2lgZD3o8FeNnAcfM2sPlk3+ZleOYw9P/CklFVDlvqmpCv9ss/BEp/dDaWvy1Lm J4c2dbQJfmTxn7CV1H3TsVJvKdwFmdoABb41NoBp6+NNO7OtDyhbIMiCI0pL3Nef b3HLA7hIMo3DYbORTtJLTIH9W8YKrEWL0lwHLrYFx/UdutZnv+HjdmO6vCN4na55 mjws/vjKQUmc7xeY7Xe20xDEG2oDKVkL2eD7FfyrYMS3rO1ExP2KSqlXYG/1S9I/ fz88F0GK7HX55b5WjZCl2J3ERVdnv/0MQv+sYQIDAQABAoIBADQ2spUwbY+bcz4p 3M66ECrNQTBggP40gYl2XyHxGGOu2xhZ94f9ELf1hjRWU2DUKWco1rJcdZClV6q3 qwmXvcM2Q/SMS8JW0ImkNVl/0/NqPxGatEnj8zY30d/L8hGFb0orzFu/XYA5gCP4 NbN2WrXgk3ZLeqwcNxHHtSiJWGJ/fPyeDWAu/apy75u9Xf2GlzBZmV6HYD9EfK80 LTlI60f5FO487CrJnboL7ovPJrIHn+k05xRQqwma4orpz932rTXnTjs9Lg6KtbQN a7PrqfAntIISgr11a66Mng3IYH1lYqJsWJJwX/xHT4WLEy0EH4/0+PfYemJekz2+ Co62drECgYEA6O9zVJZXrLSDsIi54cfxA7nEZWm5CAtkYWeAHa4EJ+IlZ7gIf9sL W8oFcEfFGpvwVqWZ+AsQ70dsjXAv3zXaG0tmg9FtqWp7pzRSMPidifZcQwWkKeTO gJnFmnVyed8h6GfjTEu4gxo1/S5U0V+mYSha01z5NTnN6ltKx1Or3b0CgYEAxRgm S30nZxnyg/V7ys61AZhst1DG2tkZXEMcA7dYhabMoXPJAP/EfhlWwpWYYUs/u0gS Wwmf5IivX5TlYScgmkvb/NYz0u4ZmOXkLTnLPtdKKFXhjXJcHjUP67jYmOxNlJLp V4vLRnFxTpffAV+OszzRxsXX6fvruwZBANYJeXUCgYBVouLFsFgfWGYp2rpr9XP4 KK25kvrBqF6JKOIDB1zjxNJ3pUMKrl8oqccCFoCyXa4oTM2kUX0yWxHfleUjrMq4 yimwQKiOZmV7fVLSSjSw6e/VfBd0h3gb82ygcplZkN0IclkwTY5SNKqwn/3y07V5 drqdhkrgdJXtmQ6O5YYECQKBgATERcDToQ1USlI4sKrB/wyv1AlG8dg/IebiVJ4e ZAyvcQmClFzq0qS+FiQUnB/WQw9TeeYrwGs1hxBHuJh16srwhLyDrbMvQP06qh8R 48F8UXXSRec22dV9MQphaROhu2qZdv1AC0WD3tqov6L33aqmEOi+xi8JgbT/PLk5 c/c1AoGBAI1A/02ryksW6/wc7/6SP2M2rTy4m1sD/GnrTc67EHnRcVBdKO6qH2RY nqC8YcveC2ZghgPTDsA3VGuzuBXpwY6wTyV99q6jxQJ6/xcrD9/NUG6Uwv/xfCxl IJLeBYEqQundSSny3VtaAUK8Ul1nxpTvVRNwtcyWTo8RHAAyNPWd -----END RSA PRIVATE KEY----- lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/server.crt0000644061062106075000000000224013172163402024550 0ustar stgraberdomain admins-----BEGIN CERTIFICATE----- MIIDPjCCAiYCCQDizia/MoUFnDANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJV UzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xFDASBgNVBAoT C0JyYWRmaXR6aW5jMRIwEAYDVQQDEwlsb2NhbGhvc3QxHTAbBgkqhkiG9w0BCQEW DmJyYWRAZGFuZ2EuY29tMB4XDTE0MDcxNTIwNTAyN1oXDTE1MTEyNzIwNTAyN1ow RzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQHEwJTRjEeMBwGA1UE ChMVYnJhZGZpdHogaHR0cDIgc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAs1Y9CyLFrdL8VQWN1WaifDqaZFnoqjHhCMlc1TfG2zA+InDifx2l gZD3o8FeNnAcfM2sPlk3+ZleOYw9P/CklFVDlvqmpCv9ss/BEp/dDaWvy1LmJ4c2 dbQJfmTxn7CV1H3TsVJvKdwFmdoABb41NoBp6+NNO7OtDyhbIMiCI0pL3Nefb3HL A7hIMo3DYbORTtJLTIH9W8YKrEWL0lwHLrYFx/UdutZnv+HjdmO6vCN4na55mjws /vjKQUmc7xeY7Xe20xDEG2oDKVkL2eD7FfyrYMS3rO1ExP2KSqlXYG/1S9I/fz88 F0GK7HX55b5WjZCl2J3ERVdnv/0MQv+sYQIDAQABMA0GCSqGSIb3DQEBBQUAA4IB AQC0zL+n/YpRZOdulSu9tS8FxrstXqGWoxfe+vIUgqfMZ5+0MkjJ/vW0FqlLDl2R rn4XaR3e7FmWkwdDVbq/UB6lPmoAaFkCgh9/5oapMaclNVNnfF3fjCJfRr+qj/iD EmJStTIN0ZuUjAlpiACmfnpEU55PafT5Zx+i1yE4FGjw8bJpFoyD4Hnm54nGjX19 KeCuvcYFUPnBm3lcL0FalF2AjqV02WTHYNQk7YF/oeO7NKBoEgvGvKG3x+xaOeBI dwvdq175ZsGul30h+QjrRlXhH/twcuaT3GSdoysDl9cCYE8f1Mk8PD6gan3uBCJU 90p6/CbU71bGbfpM2PHot2fm -----END CERTIFICATE----- lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/rootCA.srl0000644061062106075000000000002113172163402024434 0ustar stgraberdomain adminsE2CE26BF3285059C lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/rootCA.pem0000644061062106075000000000304213172163402024423 0ustar stgraberdomain admins-----BEGIN CERTIFICATE----- MIIEWjCCA0KgAwIBAgIJALfRlWsI8YQHMA0GCSqGSIb3DQEBBQUAMHsxCzAJBgNV BAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEUMBIG A1UEChMLQnJhZGZpdHppbmMxEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsGCSqGSIb3 DQEJARYOYnJhZEBkYW5nYS5jb20wHhcNMTQwNzE1MjA0NjA1WhcNMTcwNTA0MjA0 NjA1WjB7MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDVNhbiBG cmFuY2lzY28xFDASBgNVBAoTC0JyYWRmaXR6aW5jMRIwEAYDVQQDEwlsb2NhbGhv c3QxHTAbBgkqhkiG9w0BCQEWDmJyYWRAZGFuZ2EuY29tMIIBIjANBgkqhkiG9w0B AQEFAAOCAQ8AMIIBCgKCAQEAt5fAjp4fTcekWUTfzsp0kyih1OYbsGL0KX1eRbSS R8Od0+9Q62Hyny+GFwMTb4A/KU8mssoHvcceSAAbwfbxFK/+s51TobqUnORZrOoT ZjkUygbyXDSK99YBbcR1Pip8vwMTm4XKuLtCigeBBdjjAQdgUO28LENGlsMnmeYk JfODVGnVmr5Ltb9ANA8IKyTfsnHJ4iOCS/PlPbUj2q7YnoVLposUBMlgUb/CykX3 mOoLb4yJJQyA/iST6ZxiIEj36D4yWZ5lg7YJl+UiiBQHGCnPdGyipqV06ex0heYW caiW8LWZSUQ93jQ+WVCH8hT7DQO1dmsvUmXlq/JeAlwQ/QIDAQABo4HgMIHdMB0G A1UdDgQWBBRcAROthS4P4U7vTfjByC569R7E6DCBrQYDVR0jBIGlMIGigBRcAROt hS4P4U7vTfjByC569R7E6KF/pH0wezELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNB MRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMRQwEgYDVQQKEwtCcmFkZml0emluYzES MBAGA1UEAxMJbG9jYWxob3N0MR0wGwYJKoZIhvcNAQkBFg5icmFkQGRhbmdhLmNv bYIJALfRlWsI8YQHMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAG6h U9f9sNH0/6oBbGGy2EVU0UgITUQIrFWo9rFkrW5k/XkDjQm+3lzjT0iGR4IxE/Ao eU6sQhua7wrWeFEn47GL98lnCsJdD7oZNhFmQ95Tb/LnDUjs5Yj9brP0NWzXfYU4 UK2ZnINJRcJpB8iRCaCxE8DdcUF0XqIEq6pA272snoLmiXLMvNl3kYEdm+je6voD 58SNVEUsztzQyXmJEhCpwVI0A6QCjzXj+qvpmw3ZZHi8JwXei8ZZBLTSFBki8Z7n sH9BBH38/SzUmAN4QHSPy1gjqm00OAE8NaYDkh/bzE4d7mLGGMWp/WE3KPSu82HF kPe6XoSbiLm/kxk32T0= -----END CERTIFICATE----- lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/rootCA.key0000644061062106075000000000321313172163402024432 0ustar stgraberdomain admins-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAt5fAjp4fTcekWUTfzsp0kyih1OYbsGL0KX1eRbSSR8Od0+9Q 62Hyny+GFwMTb4A/KU8mssoHvcceSAAbwfbxFK/+s51TobqUnORZrOoTZjkUygby XDSK99YBbcR1Pip8vwMTm4XKuLtCigeBBdjjAQdgUO28LENGlsMnmeYkJfODVGnV mr5Ltb9ANA8IKyTfsnHJ4iOCS/PlPbUj2q7YnoVLposUBMlgUb/CykX3mOoLb4yJ JQyA/iST6ZxiIEj36D4yWZ5lg7YJl+UiiBQHGCnPdGyipqV06ex0heYWcaiW8LWZ SUQ93jQ+WVCH8hT7DQO1dmsvUmXlq/JeAlwQ/QIDAQABAoIBAFFHV7JMAqPWnMYA nezY6J81v9+XN+7xABNWM2Q8uv4WdksbigGLTXR3/680Z2hXqJ7LMeC5XJACFT/e /Gr0vmpgOCygnCPfjGehGKpavtfksXV3edikUlnCXsOP1C//c1bFL+sMYmFCVgTx qYdDK8yKzXNGrKYT6q5YG7IglyRNV1rsQa8lM/5taFYiD1Ck/3tQi3YIq8Lcuser hrxsMABcQ6mi+EIvG6Xr4mfJug0dGJMHG4RG1UGFQn6RXrQq2+q53fC8ZbVUSi0j NQ918aKFzktwv+DouKU0ME4I9toks03gM860bAL7zCbKGmwR3hfgX/TqzVCWpG9E LDVfvekCgYEA8fk9N53jbBRmULUGEf4qWypcLGiZnNU0OeXWpbPV9aa3H0VDytA7 8fCN2dPAVDPqlthMDdVe983NCNwp2Yo8ZimDgowyIAKhdC25s1kejuaiH9OAPj3c 0f8KbriYX4n8zNHxFwK6Ae3pQ6EqOLJVCUsziUaZX9nyKY5aZlyX6xcCgYEAwjws K62PjC64U5wYddNLp+kNdJ4edx+a7qBb3mEgPvSFT2RO3/xafJyG8kQB30Mfstjd bRxyUV6N0vtX1zA7VQtRUAvfGCecpMo+VQZzcHXKzoRTnQ7eZg4Lmj5fQ9tOAKAo QCVBoSW/DI4PZL26CAMDcAba4Pa22ooLapoRIQsCgYA6pIfkkbxLNkpxpt2YwLtt Kr/590O7UaR9n6k8sW/aQBRDXNsILR1KDl2ifAIxpf9lnXgZJiwE7HiTfCAcW7c1 nzwDCI0hWuHcMTS/NYsFYPnLsstyyjVZI3FY0h4DkYKV9Q9z3zJLQ2hz/nwoD3gy b2pHC7giFcTts1VPV4Nt8wKBgHeFn4ihHJweg76vZz3Z78w7VNRWGFklUalVdDK7 gaQ7w2y/ROn/146mo0OhJaXFIFRlrpvdzVrU3GDf2YXJYDlM5ZRkObwbZADjksev WInzcgDy3KDg7WnPasRXbTfMU4t/AkW2p1QKbi3DnSVYuokDkbH2Beo45vxDxhKr C69RAoGBAIyo3+OJenoZmoNzNJl2WPW5MeBUzSh8T/bgyjFTdqFHF5WiYRD/lfHj x9Glyw2nutuT4hlOqHvKhgTYdDMsF2oQ72fe3v8Q5FU7FuKndNPEAyvKNXZaShVA hnlhv5DjXKb0wFWnt5PCCiQLtzG0yyHaITrrEme7FikkIcTxaX/Y -----END RSA PRIVATE KEY----- lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/launch.go0000644061062106075000000002072113172163402024335 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main import ( "bufio" "bytes" "encoding/json" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "os" "strings" "time" "golang.org/x/oauth2" "golang.org/x/oauth2/google" compute "google.golang.org/api/compute/v1" ) var ( proj = flag.String("project", "symbolic-datum-552", "name of Project") zone = flag.String("zone", "us-central1-a", "GCE zone") mach = flag.String("machinetype", "n1-standard-1", "Machine type") instName = flag.String("instance_name", "http2-demo", "Name of VM instance.") sshPub = flag.String("ssh_public_key", "", "ssh public key file to authorize. Can modify later in Google's web UI anyway.") staticIP = flag.String("static_ip", "130.211.116.44", "Static IP to use. If empty, automatic.") writeObject = flag.String("write_object", "", "If non-empty, a VM isn't created and the flag value is Google Cloud Storage bucket/object to write. The contents from stdin.") publicObject = flag.Bool("write_object_is_public", false, "Whether the object created by --write_object should be public.") ) func readFile(v string) string { slurp, err := ioutil.ReadFile(v) if err != nil { log.Fatalf("Error reading %s: %v", v, err) } return strings.TrimSpace(string(slurp)) } var config = &oauth2.Config{ // The client-id and secret should be for an "Installed Application" when using // the CLI. Later we'll use a web application with a callback. ClientID: readFile("client-id.dat"), ClientSecret: readFile("client-secret.dat"), Endpoint: google.Endpoint, Scopes: []string{ compute.DevstorageFullControlScope, compute.ComputeScope, "https://www.googleapis.com/auth/sqlservice", "https://www.googleapis.com/auth/sqlservice.admin", }, RedirectURL: "urn:ietf:wg:oauth:2.0:oob", } const baseConfig = `#cloud-config coreos: units: - name: h2demo.service command: start content: | [Unit] Description=HTTP2 Demo [Service] ExecStartPre=/bin/bash -c 'mkdir -p /opt/bin && curl -s -o /opt/bin/h2demo http://storage.googleapis.com/http2-demo-server-tls/h2demo && chmod +x /opt/bin/h2demo' ExecStart=/opt/bin/h2demo --prod RestartSec=5s Restart=always Type=simple [Install] WantedBy=multi-user.target ` func main() { flag.Parse() if *proj == "" { log.Fatalf("Missing --project flag") } prefix := "https://www.googleapis.com/compute/v1/projects/" + *proj machType := prefix + "/zones/" + *zone + "/machineTypes/" + *mach const tokenFileName = "token.dat" tokenFile := tokenCacheFile(tokenFileName) tokenSource := oauth2.ReuseTokenSource(nil, tokenFile) token, err := tokenSource.Token() if err != nil { if *writeObject != "" { log.Fatalf("Can't use --write_object without a valid token.dat file already cached.") } log.Printf("Error getting token from %s: %v", tokenFileName, err) log.Printf("Get auth code from %v", config.AuthCodeURL("my-state")) fmt.Print("\nEnter auth code: ") sc := bufio.NewScanner(os.Stdin) sc.Scan() authCode := strings.TrimSpace(sc.Text()) token, err = config.Exchange(oauth2.NoContext, authCode) if err != nil { log.Fatalf("Error exchanging auth code for a token: %v", err) } if err := tokenFile.WriteToken(token); err != nil { log.Fatalf("Error writing to %s: %v", tokenFileName, err) } tokenSource = oauth2.ReuseTokenSource(token, nil) } oauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource) if *writeObject != "" { writeCloudStorageObject(oauthClient) return } computeService, _ := compute.New(oauthClient) natIP := *staticIP if natIP == "" { // Try to find it by name. aggAddrList, err := computeService.Addresses.AggregatedList(*proj).Do() if err != nil { log.Fatal(err) } // http://godoc.org/code.google.com/p/google-api-go-client/compute/v1#AddressAggregatedList IPLoop: for _, asl := range aggAddrList.Items { for _, addr := range asl.Addresses { if addr.Name == *instName+"-ip" && addr.Status == "RESERVED" { natIP = addr.Address break IPLoop } } } } cloudConfig := baseConfig if *sshPub != "" { key := strings.TrimSpace(readFile(*sshPub)) cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n - %s\n", key) } if os.Getenv("USER") == "bradfitz" { cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n - %s\n", "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAwks9dwWKlRC+73gRbvYtVg0vdCwDSuIlyt4z6xa/YU/jTDynM4R4W10hm2tPjy8iR1k8XhDv4/qdxe6m07NjG/By1tkmGpm1mGwho4Pr5kbAAy/Qg+NLCSdAYnnE00FQEcFOC15GFVMOW2AzDGKisReohwH9eIzHPzdYQNPRWXE= bradfitz@papag.bradfitz.com") } const maxCloudConfig = 32 << 10 // per compute API docs if len(cloudConfig) > maxCloudConfig { log.Fatalf("cloud config length of %d bytes is over %d byte limit", len(cloudConfig), maxCloudConfig) } instance := &compute.Instance{ Name: *instName, Description: "Go Builder", MachineType: machType, Disks: []*compute.AttachedDisk{instanceDisk(computeService)}, Tags: &compute.Tags{ Items: []string{"http-server", "https-server"}, }, Metadata: &compute.Metadata{ Items: []*compute.MetadataItems{ { Key: "user-data", Value: &cloudConfig, }, }, }, NetworkInterfaces: []*compute.NetworkInterface{ { AccessConfigs: []*compute.AccessConfig{ { Type: "ONE_TO_ONE_NAT", Name: "External NAT", NatIP: natIP, }, }, Network: prefix + "/global/networks/default", }, }, ServiceAccounts: []*compute.ServiceAccount{ { Email: "default", Scopes: []string{ compute.DevstorageFullControlScope, compute.ComputeScope, }, }, }, } log.Printf("Creating instance...") op, err := computeService.Instances.Insert(*proj, *zone, instance).Do() if err != nil { log.Fatalf("Failed to create instance: %v", err) } opName := op.Name log.Printf("Created. Waiting on operation %v", opName) OpLoop: for { time.Sleep(2 * time.Second) op, err := computeService.ZoneOperations.Get(*proj, *zone, opName).Do() if err != nil { log.Fatalf("Failed to get op %s: %v", opName, err) } switch op.Status { case "PENDING", "RUNNING": log.Printf("Waiting on operation %v", opName) continue case "DONE": if op.Error != nil { for _, operr := range op.Error.Errors { log.Printf("Error: %+v", operr) } log.Fatalf("Failed to start.") } log.Printf("Success. %+v", op) break OpLoop default: log.Fatalf("Unknown status %q: %+v", op.Status, op) } } inst, err := computeService.Instances.Get(*proj, *zone, *instName).Do() if err != nil { log.Fatalf("Error getting instance after creation: %v", err) } ij, _ := json.MarshalIndent(inst, "", " ") log.Printf("Instance: %s", ij) } func instanceDisk(svc *compute.Service) *compute.AttachedDisk { const imageURL = "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-stable-444-5-0-v20141016" diskName := *instName + "-disk" return &compute.AttachedDisk{ AutoDelete: true, Boot: true, Type: "PERSISTENT", InitializeParams: &compute.AttachedDiskInitializeParams{ DiskName: diskName, SourceImage: imageURL, DiskSizeGb: 50, }, } } func writeCloudStorageObject(httpClient *http.Client) { content := os.Stdin const maxSlurp = 1 << 20 var buf bytes.Buffer n, err := io.CopyN(&buf, content, maxSlurp) if err != nil && err != io.EOF { log.Fatalf("Error reading from stdin: %v, %v", n, err) } contentType := http.DetectContentType(buf.Bytes()) req, err := http.NewRequest("PUT", "https://storage.googleapis.com/"+*writeObject, io.MultiReader(&buf, content)) if err != nil { log.Fatal(err) } req.Header.Set("x-goog-api-version", "2") if *publicObject { req.Header.Set("x-goog-acl", "public-read") } req.Header.Set("Content-Type", contentType) res, err := httpClient.Do(req) if err != nil { log.Fatal(err) } if res.StatusCode != 200 { res.Write(os.Stderr) log.Fatalf("Failed.") } log.Printf("Success.") os.Exit(0) } type tokenCacheFile string func (f tokenCacheFile) Token() (*oauth2.Token, error) { slurp, err := ioutil.ReadFile(string(f)) if err != nil { return nil, err } t := new(oauth2.Token) if err := json.Unmarshal(slurp, t); err != nil { return nil, err } return t, nil } func (f tokenCacheFile) WriteToken(t *oauth2.Token) error { jt, err := json.Marshal(t) if err != nil { return err } return ioutil.WriteFile(string(f), jt, 0600) } lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/h2demo.go0000644061062106075000000003726013172163402024247 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build h2demo package main import ( "bytes" "crypto/tls" "flag" "fmt" "hash/crc32" "image" "image/jpeg" "io" "io/ioutil" "log" "net" "net/http" "os" "path" "regexp" "runtime" "strconv" "strings" "sync" "time" "go4.org/syncutil/singleflight" "golang.org/x/crypto/acme/autocert" "golang.org/x/net/http2" ) var ( prod = flag.Bool("prod", false, "Whether to configure itself to be the production http2.golang.org server.") httpsAddr = flag.String("https_addr", "localhost:4430", "TLS address to listen on ('host:port' or ':port'). Required.") httpAddr = flag.String("http_addr", "", "Plain HTTP address to listen on ('host:port', or ':port'). Empty means no HTTP.") hostHTTP = flag.String("http_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -http_addr.") hostHTTPS = flag.String("https_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -https_addr.") ) func homeOldHTTP(w http.ResponseWriter, r *http.Request) { io.WriteString(w, `

Go + HTTP/2

Welcome to the Go language's HTTP/2 demo & interop server.

Unfortunately, you're not using HTTP/2 right now. To do so:

  • Use Firefox Nightly or go to about:config and enable "network.http.spdy.enabled.http2draft"
  • Use Google Chrome Canary and/or go to chrome://flags/#enable-spdy4 to Enable SPDY/4 (Chrome's name for HTTP/2)

See code & instructions for connecting at https://github.com/golang/net/tree/master/http2.

`) } func home(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } io.WriteString(w, `

Go + HTTP/2

Welcome to the Go language's HTTP/2 demo & interop server.

Congratulations, you're using HTTP/2 right now.

This server exists for others in the HTTP/2 community to test their HTTP/2 client implementations and point out flaws in our server.

The code is at golang.org/x/net/http2 and is used transparently by the Go standard library from Go 1.6 and later.

Contact info: bradfitz@golang.org, or file a bug.

Handlers for testing

  • GET /reqinfo to dump the request + headers received
  • GET /clockstream streams the current time every second
  • GET /gophertiles to see a page with a bunch of images
  • GET /serverpush to see a page with server push
  • GET /file/gopher.png for a small file (does If-Modified-Since, Content-Range, etc)
  • GET /file/go.src.tar.gz for a larger file (~10 MB)
  • GET /redirect to redirect back to / (this page)
  • GET /goroutines to see all active goroutines in this server
  • PUT something to /crc32 to get a count of number of bytes and its CRC-32
  • PUT something to /ECHO and it will be streamed back to you capitalized
`) } func reqInfoHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "Method: %s\n", r.Method) fmt.Fprintf(w, "Protocol: %s\n", r.Proto) fmt.Fprintf(w, "Host: %s\n", r.Host) fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr) fmt.Fprintf(w, "RequestURI: %q\n", r.RequestURI) fmt.Fprintf(w, "URL: %#v\n", r.URL) fmt.Fprintf(w, "Body.ContentLength: %d (-1 means unknown)\n", r.ContentLength) fmt.Fprintf(w, "Close: %v (relevant for HTTP/1 only)\n", r.Close) fmt.Fprintf(w, "TLS: %#v\n", r.TLS) fmt.Fprintf(w, "\nHeaders:\n") r.Header.Write(w) } func crcHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "PUT" { http.Error(w, "PUT required.", 400) return } crc := crc32.NewIEEE() n, err := io.Copy(crc, r.Body) if err == nil { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "bytes=%d, CRC32=%x", n, crc.Sum(nil)) } } type capitalizeReader struct { r io.Reader } func (cr capitalizeReader) Read(p []byte) (n int, err error) { n, err = cr.r.Read(p) for i, b := range p[:n] { if b >= 'a' && b <= 'z' { p[i] = b - ('a' - 'A') } } return } type flushWriter struct { w io.Writer } func (fw flushWriter) Write(p []byte) (n int, err error) { n, err = fw.w.Write(p) if f, ok := fw.w.(http.Flusher); ok { f.Flush() } return } func echoCapitalHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "PUT" { http.Error(w, "PUT required.", 400) return } io.Copy(flushWriter{w}, capitalizeReader{r.Body}) } var ( fsGrp singleflight.Group fsMu sync.Mutex // guards fsCache fsCache = map[string]http.Handler{} ) // fileServer returns a file-serving handler that proxies URL. // It lazily fetches URL on the first access and caches its contents forever. func fileServer(url string, latency time.Duration) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if latency > 0 { time.Sleep(latency) } hi, err := fsGrp.Do(url, func() (interface{}, error) { fsMu.Lock() if h, ok := fsCache[url]; ok { fsMu.Unlock() return h, nil } fsMu.Unlock() res, err := http.Get(url) if err != nil { return nil, err } defer res.Body.Close() slurp, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } modTime := time.Now() var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.ServeContent(w, r, path.Base(url), modTime, bytes.NewReader(slurp)) }) fsMu.Lock() fsCache[url] = h fsMu.Unlock() return h, nil }) if err != nil { http.Error(w, err.Error(), 500) return } hi.(http.Handler).ServeHTTP(w, r) }) } func clockStreamHandler(w http.ResponseWriter, r *http.Request) { clientGone := w.(http.CloseNotifier).CloseNotify() w.Header().Set("Content-Type", "text/plain") ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() fmt.Fprintf(w, "# ~1KB of junk to force browsers to start rendering immediately: \n") io.WriteString(w, strings.Repeat("# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", 13)) for { fmt.Fprintf(w, "%v\n", time.Now()) w.(http.Flusher).Flush() select { case <-ticker.C: case <-clientGone: log.Printf("Client %v disconnected from the clock", r.RemoteAddr) return } } } func registerHandlers() { tiles := newGopherTilesHandler() push := newPushHandler() mux2 := http.NewServeMux() http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { switch { case r.URL.Path == "/gophertiles": tiles.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x return case strings.HasPrefix(r.URL.Path, "/serverpush"): push.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x return case r.TLS == nil: // do not allow HTTP/1.x for anything else http.Redirect(w, r, "https://"+httpsHost()+"/", http.StatusFound) return } if r.ProtoMajor == 1 { if r.URL.Path == "/reqinfo" { reqInfoHandler(w, r) return } homeOldHTTP(w, r) return } mux2.ServeHTTP(w, r) }) mux2.HandleFunc("/", home) mux2.Handle("/file/gopher.png", fileServer("https://golang.org/doc/gopher/frontpage.png", 0)) mux2.Handle("/file/go.src.tar.gz", fileServer("https://storage.googleapis.com/golang/go1.4.1.src.tar.gz", 0)) mux2.HandleFunc("/reqinfo", reqInfoHandler) mux2.HandleFunc("/crc32", crcHandler) mux2.HandleFunc("/ECHO", echoCapitalHandler) mux2.HandleFunc("/clockstream", clockStreamHandler) mux2.Handle("/gophertiles", tiles) mux2.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/", http.StatusFound) }) stripHomedir := regexp.MustCompile(`/(Users|home)/\w+`) mux2.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") buf := make([]byte, 2<<20) w.Write(stripHomedir.ReplaceAll(buf[:runtime.Stack(buf, true)], nil)) }) } var pushResources = map[string]http.Handler{ "/serverpush/static/jquery.min.js": fileServer("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", 100*time.Millisecond), "/serverpush/static/godocs.js": fileServer("https://golang.org/lib/godoc/godocs.js", 100*time.Millisecond), "/serverpush/static/playground.js": fileServer("https://golang.org/lib/godoc/playground.js", 100*time.Millisecond), "/serverpush/static/style.css": fileServer("https://golang.org/lib/godoc/style.css", 100*time.Millisecond), } func newPushHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for path, handler := range pushResources { if r.URL.Path == path { handler.ServeHTTP(w, r) return } } cacheBust := time.Now().UnixNano() if pusher, ok := w.(http.Pusher); ok { for path := range pushResources { url := fmt.Sprintf("%s?%d", path, cacheBust) if err := pusher.Push(url, nil); err != nil { log.Printf("Failed to push %v: %v", path, err) } } } time.Sleep(100 * time.Millisecond) // fake network latency + parsing time if err := pushTmpl.Execute(w, struct { CacheBust int64 HTTPSHost string HTTPHost string }{ CacheBust: cacheBust, HTTPSHost: httpsHost(), HTTPHost: httpHost(), }); err != nil { log.Printf("Executing server push template: %v", err) } }) } func newGopherTilesHandler() http.Handler { const gopherURL = "https://blog.golang.org/go-programming-language-turns-two_gophers.jpg" res, err := http.Get(gopherURL) if err != nil { log.Fatal(err) } if res.StatusCode != 200 { log.Fatalf("Error fetching %s: %v", gopherURL, res.Status) } slurp, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } im, err := jpeg.Decode(bytes.NewReader(slurp)) if err != nil { if len(slurp) > 1024 { slurp = slurp[:1024] } log.Fatalf("Failed to decode gopher image: %v (got %q)", err, slurp) } type subImager interface { SubImage(image.Rectangle) image.Image } const tileSize = 32 xt := im.Bounds().Max.X / tileSize yt := im.Bounds().Max.Y / tileSize var tile [][][]byte // y -> x -> jpeg bytes for yi := 0; yi < yt; yi++ { var row [][]byte for xi := 0; xi < xt; xi++ { si := im.(subImager).SubImage(image.Rectangle{ Min: image.Point{xi * tileSize, yi * tileSize}, Max: image.Point{(xi + 1) * tileSize, (yi + 1) * tileSize}, }) buf := new(bytes.Buffer) if err := jpeg.Encode(buf, si, &jpeg.Options{Quality: 90}); err != nil { log.Fatal(err) } row = append(row, buf.Bytes()) } tile = append(tile, row) } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ms, _ := strconv.Atoi(r.FormValue("latency")) const nanosPerMilli = 1e6 if r.FormValue("x") != "" { x, _ := strconv.Atoi(r.FormValue("x")) y, _ := strconv.Atoi(r.FormValue("y")) if ms <= 1000 { time.Sleep(time.Duration(ms) * nanosPerMilli) } if x >= 0 && x < xt && y >= 0 && y < yt { http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(tile[y][x])) return } } io.WriteString(w, "") fmt.Fprintf(w, "A grid of %d tiled images is below. Compare:

", xt*yt) for _, ms := range []int{0, 30, 200, 1000} { d := time.Duration(ms) * nanosPerMilli fmt.Fprintf(w, "[HTTP/2, %v latency] [HTTP/1, %v latency]
\n", httpsHost(), ms, d, httpHost(), ms, d, ) } io.WriteString(w, "

\n") cacheBust := time.Now().UnixNano() for y := 0; y < yt; y++ { for x := 0; x < xt; x++ { fmt.Fprintf(w, "", tileSize, tileSize, x, y, cacheBust, ms) } io.WriteString(w, "
\n") } io.WriteString(w, `


<< Back to Go HTTP/2 demo server`) }) } func httpsHost() string { if *hostHTTPS != "" { return *hostHTTPS } if v := *httpsAddr; strings.HasPrefix(v, ":") { return "localhost" + v } else { return v } } func httpHost() string { if *hostHTTP != "" { return *hostHTTP } if v := *httpAddr; strings.HasPrefix(v, ":") { return "localhost" + v } else { return v } } func serveProdTLS() error { const cacheDir = "/var/cache/autocert" if err := os.MkdirAll(cacheDir, 0700); err != nil { return err } m := autocert.Manager{ Cache: autocert.DirCache(cacheDir), Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("http2.golang.org"), } srv := &http.Server{ TLSConfig: &tls.Config{ GetCertificate: m.GetCertificate, }, } http2.ConfigureServer(srv, &http2.Server{ NewWriteScheduler: func() http2.WriteScheduler { return http2.NewPriorityWriteScheduler(nil) }, }) ln, err := net.Listen("tcp", ":443") if err != nil { return err } return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig)) } type tcpKeepAliveListener struct { *net.TCPListener } func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) { tc, err := ln.AcceptTCP() if err != nil { return } tc.SetKeepAlive(true) tc.SetKeepAlivePeriod(3 * time.Minute) return tc, nil } func serveProd() error { errc := make(chan error, 2) go func() { errc <- http.ListenAndServe(":80", nil) }() go func() { errc <- serveProdTLS() }() return <-errc } const idleTimeout = 5 * time.Minute const activeTimeout = 10 * time.Minute // TODO: put this into the standard library and actually send // PING frames and GOAWAY, etc: golang.org/issue/14204 func idleTimeoutHook() func(net.Conn, http.ConnState) { var mu sync.Mutex m := map[net.Conn]*time.Timer{} return func(c net.Conn, cs http.ConnState) { mu.Lock() defer mu.Unlock() if t, ok := m[c]; ok { delete(m, c) t.Stop() } var d time.Duration switch cs { case http.StateNew, http.StateIdle: d = idleTimeout case http.StateActive: d = activeTimeout default: return } m[c] = time.AfterFunc(d, func() { log.Printf("closing idle conn %v after %v", c.RemoteAddr(), d) go c.Close() }) } } func main() { var srv http.Server flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.") flag.Parse() srv.Addr = *httpsAddr srv.ConnState = idleTimeoutHook() registerHandlers() if *prod { *hostHTTP = "http2.golang.org" *hostHTTPS = "http2.golang.org" log.Fatal(serveProd()) } url := "https://" + httpsHost() + "/" log.Printf("Listening on " + url) http2.ConfigureServer(&srv, &http2.Server{}) if *httpAddr != "" { go func() { log.Printf("Listening on http://" + httpHost() + "/ (for unencrypted HTTP/1)") log.Fatal(http.ListenAndServe(*httpAddr, nil)) }() } go func() { log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key")) }() select {} } lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/README0000644061062106075000000000103513172163402023411 0ustar stgraberdomain admins Client: -- Firefox nightly with about:config network.http.spdy.enabled.http2draft set true -- Chrome: go to chrome://flags/#enable-spdy4, save and restart (button at bottom) Make CA: $ openssl genrsa -out rootCA.key 2048 $ openssl req -x509 -new -nodes -key rootCA.key -days 1024 -out rootCA.pem ... install that to Firefox Make cert: $ openssl genrsa -out server.key 2048 $ openssl req -new -key server.key -out server.csr $ openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 500 lxd-2.0.11/dist/src/golang.org/x/net/http2/h2demo/Makefile0000644061062106075000000000042113172163402024167 0ustar stgraberdomain adminsh2demo.linux: h2demo.go GOOS=linux go build --tags=h2demo -o h2demo.linux . FORCE: upload: FORCE go install golang.org/x/build/cmd/upload upload --verbose --osarch=linux-amd64 --tags=h2demo --file=go:golang.org/x/net/http2/h2demo --public http2-demo-server-tls/h2demo lxd-2.0.11/dist/src/golang.org/x/net/http2/gotrack_test.go0000644061062106075000000000137113172163402024376 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "fmt" "strings" "testing" ) func TestGoroutineLock(t *testing.T) { oldDebug := DebugGoroutines DebugGoroutines = true defer func() { DebugGoroutines = oldDebug }() g := newGoroutineLock() g.check() sawPanic := make(chan interface{}) go func() { defer func() { sawPanic <- recover() }() g.check() // should panic }() e := <-sawPanic if e == nil { t.Fatal("did not see panic from check in other goroutine") } if !strings.Contains(fmt.Sprint(e), "wrong goroutine") { t.Errorf("expected on see panic about running on the wrong goroutine; got %v", e) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/gotrack.go0000644061062106075000000000613013172163402023335 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Defensive debug-only utility to track that functions run on the // goroutine that they're supposed to. package http2 import ( "bytes" "errors" "fmt" "os" "runtime" "strconv" "sync" ) var DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1" type goroutineLock uint64 func newGoroutineLock() goroutineLock { if !DebugGoroutines { return 0 } return goroutineLock(curGoroutineID()) } func (g goroutineLock) check() { if !DebugGoroutines { return } if curGoroutineID() != uint64(g) { panic("running on the wrong goroutine") } } func (g goroutineLock) checkNotOn() { if !DebugGoroutines { return } if curGoroutineID() == uint64(g) { panic("running on the wrong goroutine") } } var goroutineSpace = []byte("goroutine ") func curGoroutineID() uint64 { bp := littleBuf.Get().(*[]byte) defer littleBuf.Put(bp) b := *bp b = b[:runtime.Stack(b, false)] // Parse the 4707 out of "goroutine 4707 [" b = bytes.TrimPrefix(b, goroutineSpace) i := bytes.IndexByte(b, ' ') if i < 0 { panic(fmt.Sprintf("No space found in %q", b)) } b = b[:i] n, err := parseUintBytes(b, 10, 64) if err != nil { panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) } return n } var littleBuf = sync.Pool{ New: func() interface{} { buf := make([]byte, 64) return &buf }, } // parseUintBytes is like strconv.ParseUint, but using a []byte. func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) { var cutoff, maxVal uint64 if bitSize == 0 { bitSize = int(strconv.IntSize) } s0 := s switch { case len(s) < 1: err = strconv.ErrSyntax goto Error case 2 <= base && base <= 36: // valid base; nothing to do case base == 0: // Look for octal, hex prefix. switch { case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'): base = 16 s = s[2:] if len(s) < 1 { err = strconv.ErrSyntax goto Error } case s[0] == '0': base = 8 default: base = 10 } default: err = errors.New("invalid base " + strconv.Itoa(base)) goto Error } n = 0 cutoff = cutoff64(base) maxVal = 1<= base { n = 0 err = strconv.ErrSyntax goto Error } if n >= cutoff { // n*base overflows n = 1<<64 - 1 err = strconv.ErrRange goto Error } n *= uint64(base) n1 := n + uint64(v) if n1 < n || n1 > maxVal { // n+v overflows n = 1<<64 - 1 err = strconv.ErrRange goto Error } n = n1 } return n, nil Error: return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err} } // Return the first number n such that n*base >= 1<<64. func cutoff64(base int) uint64 { if base < 2 { return 0 } return (1<<64-1)/uint64(base) + 1 } lxd-2.0.11/dist/src/golang.org/x/net/http2/go19_test.go0000644061062106075000000000251613172163402023525 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package http2 import ( "context" "net/http" "reflect" "testing" "time" ) func TestServerGracefulShutdown(t *testing.T) { var st *serverTester handlerDone := make(chan struct{}) st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) { defer close(handlerDone) go st.ts.Config.Shutdown(context.Background()) ga := st.wantGoAway() if ga.ErrCode != ErrCodeNo { t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) } if ga.LastStreamID != 1 { t.Errorf("GOAWAY LastStreamID = %v; want 1", ga.LastStreamID) } w.Header().Set("x-foo", "bar") }) defer st.Close() st.greet() st.bodylessReq1() select { case <-handlerDone: case <-time.After(5 * time.Second): t.Fatalf("server did not shutdown?") } hf := st.wantHeaders() goth := st.decodeHeader(hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"x-foo", "bar"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", "0"}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } n, err := st.cc.Read([]byte{0}) if n != 0 || err == nil { t.Errorf("Read = %v, %v; want 0, non-nil", n, err) } } lxd-2.0.11/dist/src/golang.org/x/net/http2/go19.go0000644061062106075000000000053313172163402022463 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package http2 import ( "net/http" ) func configureServer19(s *http.Server, conf *Server) error { s.RegisterOnShutdown(conf.state.startGracefulShutdown) return nil } lxd-2.0.11/dist/src/golang.org/x/net/http2/go18_test.go0000644061062106075000000000341313172163402023521 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.8 package http2 import ( "crypto/tls" "net/http" "testing" "time" ) // Tests that http2.Server.IdleTimeout is initialized from // http.Server.{Idle,Read}Timeout. http.Server.IdleTimeout was // added in Go 1.8. func TestConfigureServerIdleTimeout_Go18(t *testing.T) { const timeout = 5 * time.Second const notThisOne = 1 * time.Second // With a zero http2.Server, verify that it copies IdleTimeout: { s1 := &http.Server{ IdleTimeout: timeout, ReadTimeout: notThisOne, } s2 := &Server{} if err := ConfigureServer(s1, s2); err != nil { t.Fatal(err) } if s2.IdleTimeout != timeout { t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) } } // And that it falls back to ReadTimeout: { s1 := &http.Server{ ReadTimeout: timeout, } s2 := &Server{} if err := ConfigureServer(s1, s2); err != nil { t.Fatal(err) } if s2.IdleTimeout != timeout { t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) } } // Verify that s1's IdleTimeout doesn't overwrite an existing setting: { s1 := &http.Server{ IdleTimeout: notThisOne, } s2 := &Server{ IdleTimeout: timeout, } if err := ConfigureServer(s1, s2); err != nil { t.Fatal(err) } if s2.IdleTimeout != timeout { t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) } } } func TestCertClone(t *testing.T) { c := &tls.Config{ GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { panic("shouldn't be called") }, } c2 := cloneTLSConfig(c) if c2.GetClientCertificate == nil { t.Error("GetClientCertificate is nil") } } lxd-2.0.11/dist/src/golang.org/x/net/http2/go18.go0000644061062106075000000000241113172163402022457 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.8 package http2 import ( "crypto/tls" "io" "net/http" ) func cloneTLSConfig(c *tls.Config) *tls.Config { c2 := c.Clone() c2.GetClientCertificate = c.GetClientCertificate // golang.org/issue/19264 return c2 } var _ http.Pusher = (*responseWriter)(nil) // Push implements http.Pusher. func (w *responseWriter) Push(target string, opts *http.PushOptions) error { internalOpts := pushOptions{} if opts != nil { internalOpts.Method = opts.Method internalOpts.Header = opts.Header } return w.push(target, internalOpts) } func configureServer18(h1 *http.Server, h2 *Server) error { if h2.IdleTimeout == 0 { if h1.IdleTimeout != 0 { h2.IdleTimeout = h1.IdleTimeout } else { h2.IdleTimeout = h1.ReadTimeout } } return nil } func shouldLogPanic(panicValue interface{}) bool { return panicValue != nil && panicValue != http.ErrAbortHandler } func reqGetBody(req *http.Request) func() (io.ReadCloser, error) { return req.GetBody } func reqBodyIsNoBody(body io.ReadCloser) bool { return body == http.NoBody } func go18httpNoBody() io.ReadCloser { return http.NoBody } // for tests only lxd-2.0.11/dist/src/golang.org/x/net/http2/go17_not18.go0000644061062106075000000000253113172163402023512 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7,!go1.8 package http2 import "crypto/tls" // temporary copy of Go 1.7's private tls.Config.clone: func cloneTLSConfig(c *tls.Config) *tls.Config { return &tls.Config{ Rand: c.Rand, Time: c.Time, Certificates: c.Certificates, NameToCertificate: c.NameToCertificate, GetCertificate: c.GetCertificate, RootCAs: c.RootCAs, NextProtos: c.NextProtos, ServerName: c.ServerName, ClientAuth: c.ClientAuth, ClientCAs: c.ClientCAs, InsecureSkipVerify: c.InsecureSkipVerify, CipherSuites: c.CipherSuites, PreferServerCipherSuites: c.PreferServerCipherSuites, SessionTicketsDisabled: c.SessionTicketsDisabled, SessionTicketKey: c.SessionTicketKey, ClientSessionCache: c.ClientSessionCache, MinVersion: c.MinVersion, MaxVersion: c.MaxVersion, CurvePreferences: c.CurvePreferences, DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, Renegotiation: c.Renegotiation, } } lxd-2.0.11/dist/src/golang.org/x/net/http2/go17.go0000644061062106075000000000504713172163402022466 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package http2 import ( "context" "net" "net/http" "net/http/httptrace" "time" ) type contextContext interface { context.Context } func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { ctx, cancel = context.WithCancel(context.Background()) ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr()) if hs := opts.baseConfig(); hs != nil { ctx = context.WithValue(ctx, http.ServerContextKey, hs) } return } func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) { return context.WithCancel(ctx) } func requestWithContext(req *http.Request, ctx contextContext) *http.Request { return req.WithContext(ctx) } type clientTrace httptrace.ClientTrace func reqContext(r *http.Request) context.Context { return r.Context() } func (t *Transport) idleConnTimeout() time.Duration { if t.t1 != nil { return t.t1.IdleConnTimeout } return 0 } func setResponseUncompressed(res *http.Response) { res.Uncompressed = true } func traceGotConn(req *http.Request, cc *ClientConn) { trace := httptrace.ContextClientTrace(req.Context()) if trace == nil || trace.GotConn == nil { return } ci := httptrace.GotConnInfo{Conn: cc.tconn} cc.mu.Lock() ci.Reused = cc.nextStreamID > 1 ci.WasIdle = len(cc.streams) == 0 && ci.Reused if ci.WasIdle && !cc.lastActive.IsZero() { ci.IdleTime = time.Now().Sub(cc.lastActive) } cc.mu.Unlock() trace.GotConn(ci) } func traceWroteHeaders(trace *clientTrace) { if trace != nil && trace.WroteHeaders != nil { trace.WroteHeaders() } } func traceGot100Continue(trace *clientTrace) { if trace != nil && trace.Got100Continue != nil { trace.Got100Continue() } } func traceWait100Continue(trace *clientTrace) { if trace != nil && trace.Wait100Continue != nil { trace.Wait100Continue() } } func traceWroteRequest(trace *clientTrace, err error) { if trace != nil && trace.WroteRequest != nil { trace.WroteRequest(httptrace.WroteRequestInfo{Err: err}) } } func traceFirstResponseByte(trace *clientTrace) { if trace != nil && trace.GotFirstResponseByte != nil { trace.GotFirstResponseByte() } } func requestTrace(req *http.Request) *clientTrace { trace := httptrace.ContextClientTrace(req.Context()) return (*clientTrace)(trace) } // Ping sends a PING frame to the server and waits for the ack. func (cc *ClientConn) Ping(ctx context.Context) error { return cc.ping(ctx) } lxd-2.0.11/dist/src/golang.org/x/net/http2/go16.go0000644061062106075000000000051313172163402022456 0ustar stgraberdomain admins// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.6 package http2 import ( "net/http" "time" ) func transportExpectContinueTimeout(t1 *http.Transport) time.Duration { return t1.ExpectContinueTimeout } lxd-2.0.11/dist/src/golang.org/x/net/http2/frame_test.go0000644061062106075000000007220013172163402024035 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bytes" "fmt" "io" "reflect" "strings" "testing" "unsafe" "golang.org/x/net/http2/hpack" ) func testFramer() (*Framer, *bytes.Buffer) { buf := new(bytes.Buffer) return NewFramer(buf, buf), buf } func TestFrameSizes(t *testing.T) { // Catch people rearranging the FrameHeader fields. if got, want := int(unsafe.Sizeof(FrameHeader{})), 12; got != want { t.Errorf("FrameHeader size = %d; want %d", got, want) } } func TestFrameTypeString(t *testing.T) { tests := []struct { ft FrameType want string }{ {FrameData, "DATA"}, {FramePing, "PING"}, {FrameGoAway, "GOAWAY"}, {0xf, "UNKNOWN_FRAME_TYPE_15"}, } for i, tt := range tests { got := tt.ft.String() if got != tt.want { t.Errorf("%d. String(FrameType %d) = %q; want %q", i, int(tt.ft), got, tt.want) } } } func TestWriteRST(t *testing.T) { fr, buf := testFramer() var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 var errCode uint32 = 7<<24 + 6<<16 + 5<<8 + 4 fr.WriteRSTStream(streamID, ErrCode(errCode)) const wantEnc = "\x00\x00\x04\x03\x00\x01\x02\x03\x04\x07\x06\x05\x04" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } want := &RSTStreamFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x3, Flags: 0x0, Length: 0x4, StreamID: 0x1020304, }, ErrCode: 0x7060504, } if !reflect.DeepEqual(f, want) { t.Errorf("parsed back %#v; want %#v", f, want) } } func TestWriteData(t *testing.T) { fr, buf := testFramer() var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 data := []byte("ABC") fr.WriteData(streamID, true, data) const wantEnc = "\x00\x00\x03\x00\x01\x01\x02\x03\x04ABC" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } df, ok := f.(*DataFrame) if !ok { t.Fatalf("got %T; want *DataFrame", f) } if !bytes.Equal(df.Data(), data) { t.Errorf("got %q; want %q", df.Data(), data) } if f.Header().Flags&1 == 0 { t.Errorf("didn't see END_STREAM flag") } } func TestWriteDataPadded(t *testing.T) { tests := [...]struct { streamID uint32 endStream bool data []byte pad []byte wantHeader FrameHeader }{ // Unpadded: 0: { streamID: 1, endStream: true, data: []byte("foo"), pad: nil, wantHeader: FrameHeader{ Type: FrameData, Flags: FlagDataEndStream, Length: 3, StreamID: 1, }, }, // Padded bit set, but no padding: 1: { streamID: 1, endStream: true, data: []byte("foo"), pad: []byte{}, wantHeader: FrameHeader{ Type: FrameData, Flags: FlagDataEndStream | FlagDataPadded, Length: 4, StreamID: 1, }, }, // Padded bit set, with padding: 2: { streamID: 1, endStream: false, data: []byte("foo"), pad: []byte{0, 0, 0}, wantHeader: FrameHeader{ Type: FrameData, Flags: FlagDataPadded, Length: 7, StreamID: 1, }, }, } for i, tt := range tests { fr, _ := testFramer() fr.WriteDataPadded(tt.streamID, tt.endStream, tt.data, tt.pad) f, err := fr.ReadFrame() if err != nil { t.Errorf("%d. ReadFrame: %v", i, err) continue } got := f.Header() tt.wantHeader.valid = true if got != tt.wantHeader { t.Errorf("%d. read %+v; want %+v", i, got, tt.wantHeader) continue } df := f.(*DataFrame) if !bytes.Equal(df.Data(), tt.data) { t.Errorf("%d. got %q; want %q", i, df.Data(), tt.data) } } } func TestWriteHeaders(t *testing.T) { tests := []struct { name string p HeadersFrameParam wantEnc string wantFrame *HeadersFrame }{ { "basic", HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), Priority: PriorityParam{}, }, "\x00\x00\x03\x01\x00\x00\x00\x00*abc", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Length: uint32(len("abc")), }, Priority: PriorityParam{}, headerFragBuf: []byte("abc"), }, }, { "basic + end flags", HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), EndStream: true, EndHeaders: true, Priority: PriorityParam{}, }, "\x00\x00\x03\x01\x05\x00\x00\x00*abc", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Flags: FlagHeadersEndStream | FlagHeadersEndHeaders, Length: uint32(len("abc")), }, Priority: PriorityParam{}, headerFragBuf: []byte("abc"), }, }, { "with padding", HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), EndStream: true, EndHeaders: true, PadLength: 5, Priority: PriorityParam{}, }, "\x00\x00\t\x01\r\x00\x00\x00*\x05abc\x00\x00\x00\x00\x00", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded, Length: uint32(1 + len("abc") + 5), // pad length + contents + padding }, Priority: PriorityParam{}, headerFragBuf: []byte("abc"), }, }, { "with priority", HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), EndStream: true, EndHeaders: true, PadLength: 2, Priority: PriorityParam{ StreamDep: 15, Exclusive: true, Weight: 127, }, }, "\x00\x00\v\x01-\x00\x00\x00*\x02\x80\x00\x00\x0f\u007fabc\x00\x00", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded | FlagHeadersPriority, Length: uint32(1 + 5 + len("abc") + 2), // pad length + priority + contents + padding }, Priority: PriorityParam{ StreamDep: 15, Exclusive: true, Weight: 127, }, headerFragBuf: []byte("abc"), }, }, { "with priority stream dep zero", // golang.org/issue/15444 HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), EndStream: true, EndHeaders: true, PadLength: 2, Priority: PriorityParam{ StreamDep: 0, Exclusive: true, Weight: 127, }, }, "\x00\x00\v\x01-\x00\x00\x00*\x02\x80\x00\x00\x00\u007fabc\x00\x00", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded | FlagHeadersPriority, Length: uint32(1 + 5 + len("abc") + 2), // pad length + priority + contents + padding }, Priority: PriorityParam{ StreamDep: 0, Exclusive: true, Weight: 127, }, headerFragBuf: []byte("abc"), }, }, } for _, tt := range tests { fr, buf := testFramer() if err := fr.WriteHeaders(tt.p); err != nil { t.Errorf("test %q: %v", tt.name, err) continue } if buf.String() != tt.wantEnc { t.Errorf("test %q: encoded %q; want %q", tt.name, buf.Bytes(), tt.wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) continue } if !reflect.DeepEqual(f, tt.wantFrame) { t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) } } } func TestWriteInvalidStreamDep(t *testing.T) { fr, _ := testFramer() err := fr.WriteHeaders(HeadersFrameParam{ StreamID: 42, Priority: PriorityParam{ StreamDep: 1 << 31, }, }) if err != errDepStreamID { t.Errorf("header error = %v; want %q", err, errDepStreamID) } err = fr.WritePriority(2, PriorityParam{StreamDep: 1 << 31}) if err != errDepStreamID { t.Errorf("priority error = %v; want %q", err, errDepStreamID) } } func TestWriteContinuation(t *testing.T) { const streamID = 42 tests := []struct { name string end bool frag []byte wantFrame *ContinuationFrame }{ { "not end", false, []byte("abc"), &ContinuationFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: streamID, Type: FrameContinuation, Length: uint32(len("abc")), }, headerFragBuf: []byte("abc"), }, }, { "end", true, []byte("def"), &ContinuationFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: streamID, Type: FrameContinuation, Flags: FlagContinuationEndHeaders, Length: uint32(len("def")), }, headerFragBuf: []byte("def"), }, }, } for _, tt := range tests { fr, _ := testFramer() if err := fr.WriteContinuation(streamID, tt.end, tt.frag); err != nil { t.Errorf("test %q: %v", tt.name, err) continue } fr.AllowIllegalReads = true f, err := fr.ReadFrame() if err != nil { t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) continue } if !reflect.DeepEqual(f, tt.wantFrame) { t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) } } } func TestWritePriority(t *testing.T) { const streamID = 42 tests := []struct { name string priority PriorityParam wantFrame *PriorityFrame }{ { "not exclusive", PriorityParam{ StreamDep: 2, Exclusive: false, Weight: 127, }, &PriorityFrame{ FrameHeader{ valid: true, StreamID: streamID, Type: FramePriority, Length: 5, }, PriorityParam{ StreamDep: 2, Exclusive: false, Weight: 127, }, }, }, { "exclusive", PriorityParam{ StreamDep: 3, Exclusive: true, Weight: 77, }, &PriorityFrame{ FrameHeader{ valid: true, StreamID: streamID, Type: FramePriority, Length: 5, }, PriorityParam{ StreamDep: 3, Exclusive: true, Weight: 77, }, }, }, } for _, tt := range tests { fr, _ := testFramer() if err := fr.WritePriority(streamID, tt.priority); err != nil { t.Errorf("test %q: %v", tt.name, err) continue } f, err := fr.ReadFrame() if err != nil { t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) continue } if !reflect.DeepEqual(f, tt.wantFrame) { t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) } } } func TestWriteSettings(t *testing.T) { fr, buf := testFramer() settings := []Setting{{1, 2}, {3, 4}} fr.WriteSettings(settings...) const wantEnc = "\x00\x00\f\x04\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00\x00\x04" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } sf, ok := f.(*SettingsFrame) if !ok { t.Fatalf("Got a %T; want a SettingsFrame", f) } var got []Setting sf.ForeachSetting(func(s Setting) error { got = append(got, s) valBack, ok := sf.Value(s.ID) if !ok || valBack != s.Val { t.Errorf("Value(%d) = %v, %v; want %v, true", s.ID, valBack, ok, s.Val) } return nil }) if !reflect.DeepEqual(settings, got) { t.Errorf("Read settings %+v != written settings %+v", got, settings) } } func TestWriteSettingsAck(t *testing.T) { fr, buf := testFramer() fr.WriteSettingsAck() const wantEnc = "\x00\x00\x00\x04\x01\x00\x00\x00\x00" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } } func TestWriteWindowUpdate(t *testing.T) { fr, buf := testFramer() const streamID = 1<<24 + 2<<16 + 3<<8 + 4 const incr = 7<<24 + 6<<16 + 5<<8 + 4 if err := fr.WriteWindowUpdate(streamID, incr); err != nil { t.Fatal(err) } const wantEnc = "\x00\x00\x04\x08\x00\x01\x02\x03\x04\x07\x06\x05\x04" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } want := &WindowUpdateFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x8, Flags: 0x0, Length: 0x4, StreamID: 0x1020304, }, Increment: 0x7060504, } if !reflect.DeepEqual(f, want) { t.Errorf("parsed back %#v; want %#v", f, want) } } func TestWritePing(t *testing.T) { testWritePing(t, false) } func TestWritePingAck(t *testing.T) { testWritePing(t, true) } func testWritePing(t *testing.T, ack bool) { fr, buf := testFramer() if err := fr.WritePing(ack, [8]byte{1, 2, 3, 4, 5, 6, 7, 8}); err != nil { t.Fatal(err) } var wantFlags Flags if ack { wantFlags = FlagPingAck } var wantEnc = "\x00\x00\x08\x06" + string(wantFlags) + "\x00\x00\x00\x00" + "\x01\x02\x03\x04\x05\x06\x07\x08" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } want := &PingFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x6, Flags: wantFlags, Length: 0x8, StreamID: 0, }, Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}, } if !reflect.DeepEqual(f, want) { t.Errorf("parsed back %#v; want %#v", f, want) } } func TestReadFrameHeader(t *testing.T) { tests := []struct { in string want FrameHeader }{ {in: "\x00\x00\x00" + "\x00" + "\x00" + "\x00\x00\x00\x00", want: FrameHeader{}}, {in: "\x01\x02\x03" + "\x04" + "\x05" + "\x06\x07\x08\x09", want: FrameHeader{ Length: 66051, Type: 4, Flags: 5, StreamID: 101124105, }}, // Ignore high bit: {in: "\xff\xff\xff" + "\xff" + "\xff" + "\xff\xff\xff\xff", want: FrameHeader{ Length: 16777215, Type: 255, Flags: 255, StreamID: 2147483647}}, {in: "\xff\xff\xff" + "\xff" + "\xff" + "\x7f\xff\xff\xff", want: FrameHeader{ Length: 16777215, Type: 255, Flags: 255, StreamID: 2147483647}}, } for i, tt := range tests { got, err := readFrameHeader(make([]byte, 9), strings.NewReader(tt.in)) if err != nil { t.Errorf("%d. readFrameHeader(%q) = %v", i, tt.in, err) continue } tt.want.valid = true if got != tt.want { t.Errorf("%d. readFrameHeader(%q) = %+v; want %+v", i, tt.in, got, tt.want) } } } func TestReadWriteFrameHeader(t *testing.T) { tests := []struct { len uint32 typ FrameType flags Flags streamID uint32 }{ {len: 0, typ: 255, flags: 1, streamID: 0}, {len: 0, typ: 255, flags: 1, streamID: 1}, {len: 0, typ: 255, flags: 1, streamID: 255}, {len: 0, typ: 255, flags: 1, streamID: 256}, {len: 0, typ: 255, flags: 1, streamID: 65535}, {len: 0, typ: 255, flags: 1, streamID: 65536}, {len: 0, typ: 1, flags: 255, streamID: 1}, {len: 255, typ: 1, flags: 255, streamID: 1}, {len: 256, typ: 1, flags: 255, streamID: 1}, {len: 65535, typ: 1, flags: 255, streamID: 1}, {len: 65536, typ: 1, flags: 255, streamID: 1}, {len: 16777215, typ: 1, flags: 255, streamID: 1}, } for _, tt := range tests { fr, buf := testFramer() fr.startWrite(tt.typ, tt.flags, tt.streamID) fr.writeBytes(make([]byte, tt.len)) fr.endWrite() fh, err := ReadFrameHeader(buf) if err != nil { t.Errorf("ReadFrameHeader(%+v) = %v", tt, err) continue } if fh.Type != tt.typ || fh.Flags != tt.flags || fh.Length != tt.len || fh.StreamID != tt.streamID { t.Errorf("ReadFrameHeader(%+v) = %+v; mismatch", tt, fh) } } } func TestWriteTooLargeFrame(t *testing.T) { fr, _ := testFramer() fr.startWrite(0, 1, 1) fr.writeBytes(make([]byte, 1<<24)) err := fr.endWrite() if err != ErrFrameTooLarge { t.Errorf("endWrite = %v; want errFrameTooLarge", err) } } func TestWriteGoAway(t *testing.T) { const debug = "foo" fr, buf := testFramer() if err := fr.WriteGoAway(0x01020304, 0x05060708, []byte(debug)); err != nil { t.Fatal(err) } const wantEnc = "\x00\x00\v\a\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08" + debug if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } want := &GoAwayFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x7, Flags: 0, Length: uint32(4 + 4 + len(debug)), StreamID: 0, }, LastStreamID: 0x01020304, ErrCode: 0x05060708, debugData: []byte(debug), } if !reflect.DeepEqual(f, want) { t.Fatalf("parsed back:\n%#v\nwant:\n%#v", f, want) } if got := string(f.(*GoAwayFrame).DebugData()); got != debug { t.Errorf("debug data = %q; want %q", got, debug) } } func TestWritePushPromise(t *testing.T) { pp := PushPromiseParam{ StreamID: 42, PromiseID: 42, BlockFragment: []byte("abc"), } fr, buf := testFramer() if err := fr.WritePushPromise(pp); err != nil { t.Fatal(err) } const wantEnc = "\x00\x00\x07\x05\x00\x00\x00\x00*\x00\x00\x00*abc" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } _, ok := f.(*PushPromiseFrame) if !ok { t.Fatalf("got %T; want *PushPromiseFrame", f) } want := &PushPromiseFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x5, Flags: 0x0, Length: 0x7, StreamID: 42, }, PromiseID: 42, headerFragBuf: []byte("abc"), } if !reflect.DeepEqual(f, want) { t.Fatalf("parsed back:\n%#v\nwant:\n%#v", f, want) } } // test checkFrameOrder and that HEADERS and CONTINUATION frames can't be intermingled. func TestReadFrameOrder(t *testing.T) { head := func(f *Framer, id uint32, end bool) { f.WriteHeaders(HeadersFrameParam{ StreamID: id, BlockFragment: []byte("foo"), // unused, but non-empty EndHeaders: end, }) } cont := func(f *Framer, id uint32, end bool) { f.WriteContinuation(id, end, []byte("foo")) } tests := [...]struct { name string w func(*Framer) atLeast int wantErr string }{ 0: { w: func(f *Framer) { head(f, 1, true) }, }, 1: { w: func(f *Framer) { head(f, 1, true) head(f, 2, true) }, }, 2: { wantErr: "got HEADERS for stream 2; expected CONTINUATION following HEADERS for stream 1", w: func(f *Framer) { head(f, 1, false) head(f, 2, true) }, }, 3: { wantErr: "got DATA for stream 1; expected CONTINUATION following HEADERS for stream 1", w: func(f *Framer) { head(f, 1, false) }, }, 4: { w: func(f *Framer) { head(f, 1, false) cont(f, 1, true) head(f, 2, true) }, }, 5: { wantErr: "got CONTINUATION for stream 2; expected stream 1", w: func(f *Framer) { head(f, 1, false) cont(f, 2, true) head(f, 2, true) }, }, 6: { wantErr: "unexpected CONTINUATION for stream 1", w: func(f *Framer) { cont(f, 1, true) }, }, 7: { wantErr: "unexpected CONTINUATION for stream 1", w: func(f *Framer) { cont(f, 1, false) }, }, 8: { wantErr: "HEADERS frame with stream ID 0", w: func(f *Framer) { head(f, 0, true) }, }, 9: { wantErr: "CONTINUATION frame with stream ID 0", w: func(f *Framer) { cont(f, 0, true) }, }, 10: { wantErr: "unexpected CONTINUATION for stream 1", atLeast: 5, w: func(f *Framer) { head(f, 1, false) cont(f, 1, false) cont(f, 1, false) cont(f, 1, false) cont(f, 1, true) cont(f, 1, false) }, }, } for i, tt := range tests { buf := new(bytes.Buffer) f := NewFramer(buf, buf) f.AllowIllegalWrites = true tt.w(f) f.WriteData(1, true, nil) // to test transition away from last step var err error n := 0 var log bytes.Buffer for { var got Frame got, err = f.ReadFrame() fmt.Fprintf(&log, " read %v, %v\n", got, err) if err != nil { break } n++ } if err == io.EOF { err = nil } ok := tt.wantErr == "" if ok && err != nil { t.Errorf("%d. after %d good frames, ReadFrame = %v; want success\n%s", i, n, err, log.Bytes()) continue } if !ok && err != ConnectionError(ErrCodeProtocol) { t.Errorf("%d. after %d good frames, ReadFrame = %v; want ConnectionError(ErrCodeProtocol)\n%s", i, n, err, log.Bytes()) continue } if !((f.errDetail == nil && tt.wantErr == "") || (fmt.Sprint(f.errDetail) == tt.wantErr)) { t.Errorf("%d. framer eror = %q; want %q\n%s", i, f.errDetail, tt.wantErr, log.Bytes()) } if n < tt.atLeast { t.Errorf("%d. framer only read %d frames; want at least %d\n%s", i, n, tt.atLeast, log.Bytes()) } } } func TestMetaFrameHeader(t *testing.T) { write := func(f *Framer, frags ...[]byte) { for i, frag := range frags { end := (i == len(frags)-1) if i == 0 { f.WriteHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: frag, EndHeaders: end, }) } else { f.WriteContinuation(1, end, frag) } } } want := func(flags Flags, length uint32, pairs ...string) *MetaHeadersFrame { mh := &MetaHeadersFrame{ HeadersFrame: &HeadersFrame{ FrameHeader: FrameHeader{ Type: FrameHeaders, Flags: flags, Length: length, StreamID: 1, }, }, Fields: []hpack.HeaderField(nil), } for len(pairs) > 0 { mh.Fields = append(mh.Fields, hpack.HeaderField{ Name: pairs[0], Value: pairs[1], }) pairs = pairs[2:] } return mh } truncated := func(mh *MetaHeadersFrame) *MetaHeadersFrame { mh.Truncated = true return mh } const noFlags Flags = 0 oneKBString := strings.Repeat("a", 1<<10) tests := [...]struct { name string w func(*Framer) want interface{} // *MetaHeaderFrame or error wantErrReason string maxHeaderListSize uint32 }{ 0: { name: "single_headers", w: func(f *Framer) { var he hpackEncoder all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/") write(f, all) }, want: want(FlagHeadersEndHeaders, 2, ":method", "GET", ":path", "/"), }, 1: { name: "with_continuation", w: func(f *Framer) { var he hpackEncoder all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", "bar") write(f, all[:1], all[1:]) }, want: want(noFlags, 1, ":method", "GET", ":path", "/", "foo", "bar"), }, 2: { name: "with_two_continuation", w: func(f *Framer) { var he hpackEncoder all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", "bar") write(f, all[:2], all[2:4], all[4:]) }, want: want(noFlags, 2, ":method", "GET", ":path", "/", "foo", "bar"), }, 3: { name: "big_string_okay", w: func(f *Framer) { var he hpackEncoder all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", oneKBString) write(f, all[:2], all[2:]) }, want: want(noFlags, 2, ":method", "GET", ":path", "/", "foo", oneKBString), }, 4: { name: "big_string_error", w: func(f *Framer) { var he hpackEncoder all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", oneKBString) write(f, all[:2], all[2:]) }, maxHeaderListSize: (1 << 10) / 2, want: ConnectionError(ErrCodeCompression), }, 5: { name: "max_header_list_truncated", w: func(f *Framer) { var he hpackEncoder var pairs = []string{":method", "GET", ":path", "/"} for i := 0; i < 100; i++ { pairs = append(pairs, "foo", "bar") } all := he.encodeHeaderRaw(t, pairs...) write(f, all[:2], all[2:]) }, maxHeaderListSize: (1 << 10) / 2, want: truncated(want(noFlags, 2, ":method", "GET", ":path", "/", "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", // 11 )), }, 6: { name: "pseudo_order", w: func(f *Framer) { write(f, encodeHeaderRaw(t, ":method", "GET", "foo", "bar", ":path", "/", // bogus )) }, want: streamError(1, ErrCodeProtocol), wantErrReason: "pseudo header field after regular", }, 7: { name: "pseudo_unknown", w: func(f *Framer) { write(f, encodeHeaderRaw(t, ":unknown", "foo", // bogus "foo", "bar", )) }, want: streamError(1, ErrCodeProtocol), wantErrReason: "invalid pseudo-header \":unknown\"", }, 8: { name: "pseudo_mix_request_response", w: func(f *Framer) { write(f, encodeHeaderRaw(t, ":method", "GET", ":status", "100", )) }, want: streamError(1, ErrCodeProtocol), wantErrReason: "mix of request and response pseudo headers", }, 9: { name: "pseudo_dup", w: func(f *Framer) { write(f, encodeHeaderRaw(t, ":method", "GET", ":method", "POST", )) }, want: streamError(1, ErrCodeProtocol), wantErrReason: "duplicate pseudo-header \":method\"", }, 10: { name: "trailer_okay_no_pseudo", w: func(f *Framer) { write(f, encodeHeaderRaw(t, "foo", "bar")) }, want: want(FlagHeadersEndHeaders, 8, "foo", "bar"), }, 11: { name: "invalid_field_name", w: func(f *Framer) { write(f, encodeHeaderRaw(t, "CapitalBad", "x")) }, want: streamError(1, ErrCodeProtocol), wantErrReason: "invalid header field name \"CapitalBad\"", }, 12: { name: "invalid_field_value", w: func(f *Framer) { write(f, encodeHeaderRaw(t, "key", "bad_null\x00")) }, want: streamError(1, ErrCodeProtocol), wantErrReason: "invalid header field value \"bad_null\\x00\"", }, } for i, tt := range tests { buf := new(bytes.Buffer) f := NewFramer(buf, buf) f.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) f.MaxHeaderListSize = tt.maxHeaderListSize tt.w(f) name := tt.name if name == "" { name = fmt.Sprintf("test index %d", i) } var got interface{} var err error got, err = f.ReadFrame() if err != nil { got = err // Ignore the StreamError.Cause field, if it matches the wantErrReason. // The test table above predates the Cause field. if se, ok := err.(StreamError); ok && se.Cause != nil && se.Cause.Error() == tt.wantErrReason { se.Cause = nil got = se } } if !reflect.DeepEqual(got, tt.want) { if mhg, ok := got.(*MetaHeadersFrame); ok { if mhw, ok := tt.want.(*MetaHeadersFrame); ok { hg := mhg.HeadersFrame hw := mhw.HeadersFrame if hg != nil && hw != nil && !reflect.DeepEqual(*hg, *hw) { t.Errorf("%s: headers differ:\n got: %+v\nwant: %+v\n", name, *hg, *hw) } } } str := func(v interface{}) string { if _, ok := v.(error); ok { return fmt.Sprintf("error %v", v) } else { return fmt.Sprintf("value %#v", v) } } t.Errorf("%s:\n got: %v\nwant: %s", name, str(got), str(tt.want)) } if tt.wantErrReason != "" && tt.wantErrReason != fmt.Sprint(f.errDetail) { t.Errorf("%s: got error reason %q; want %q", name, f.errDetail, tt.wantErrReason) } } } func TestSetReuseFrames(t *testing.T) { fr, buf := testFramer() fr.SetReuseFrames() // Check that DataFrames are reused. Note that // SetReuseFrames only currently implements reuse of DataFrames. firstDf := readAndVerifyDataFrame("ABC", 3, fr, buf, t) for i := 0; i < 10; i++ { df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) if df != firstDf { t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) } } for i := 0; i < 10; i++ { df := readAndVerifyDataFrame("", 0, fr, buf, t) if df != firstDf { t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) } } for i := 0; i < 10; i++ { df := readAndVerifyDataFrame("HHH", 3, fr, buf, t) if df != firstDf { t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) } } } func TestSetReuseFramesMoreThanOnce(t *testing.T) { fr, buf := testFramer() fr.SetReuseFrames() firstDf := readAndVerifyDataFrame("ABC", 3, fr, buf, t) fr.SetReuseFrames() for i := 0; i < 10; i++ { df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) // SetReuseFrames should be idempotent fr.SetReuseFrames() if df != firstDf { t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) } } } func TestNoSetReuseFrames(t *testing.T) { fr, buf := testFramer() const numNewDataFrames = 10 dfSoFar := make([]interface{}, numNewDataFrames) // Check that DataFrames are not reused if SetReuseFrames wasn't called. // SetReuseFrames only currently implements reuse of DataFrames. for i := 0; i < numNewDataFrames; i++ { df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) for _, item := range dfSoFar { if df == item { t.Errorf("Expected Framer to return new DataFrames since SetNoReuseFrames not set.") } } dfSoFar[i] = df } } func readAndVerifyDataFrame(data string, length byte, fr *Framer, buf *bytes.Buffer, t *testing.T) *DataFrame { var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 fr.WriteData(streamID, true, []byte(data)) wantEnc := "\x00\x00" + string(length) + "\x00\x01\x01\x02\x03\x04" + data if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } df, ok := f.(*DataFrame) if !ok { t.Fatalf("got %T; want *DataFrame", f) } if !bytes.Equal(df.Data(), []byte(data)) { t.Errorf("got %q; want %q", df.Data(), []byte(data)) } if f.Header().Flags&1 == 0 { t.Errorf("didn't see END_STREAM flag") } return df } func encodeHeaderRaw(t *testing.T, pairs ...string) []byte { var he hpackEncoder return he.encodeHeaderRaw(t, pairs...) } lxd-2.0.11/dist/src/golang.org/x/net/http2/frame.go0000644061062106075000000012763513172163402023013 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "bytes" "encoding/binary" "errors" "fmt" "io" "log" "strings" "sync" "golang.org/x/net/http2/hpack" "golang.org/x/net/lex/httplex" ) const frameHeaderLen = 9 var padZeros = make([]byte, 255) // zeros for padding // A FrameType is a registered frame type as defined in // http://http2.github.io/http2-spec/#rfc.section.11.2 type FrameType uint8 const ( FrameData FrameType = 0x0 FrameHeaders FrameType = 0x1 FramePriority FrameType = 0x2 FrameRSTStream FrameType = 0x3 FrameSettings FrameType = 0x4 FramePushPromise FrameType = 0x5 FramePing FrameType = 0x6 FrameGoAway FrameType = 0x7 FrameWindowUpdate FrameType = 0x8 FrameContinuation FrameType = 0x9 ) var frameName = map[FrameType]string{ FrameData: "DATA", FrameHeaders: "HEADERS", FramePriority: "PRIORITY", FrameRSTStream: "RST_STREAM", FrameSettings: "SETTINGS", FramePushPromise: "PUSH_PROMISE", FramePing: "PING", FrameGoAway: "GOAWAY", FrameWindowUpdate: "WINDOW_UPDATE", FrameContinuation: "CONTINUATION", } func (t FrameType) String() string { if s, ok := frameName[t]; ok { return s } return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t)) } // Flags is a bitmask of HTTP/2 flags. // The meaning of flags varies depending on the frame type. type Flags uint8 // Has reports whether f contains all (0 or more) flags in v. func (f Flags) Has(v Flags) bool { return (f & v) == v } // Frame-specific FrameHeader flag bits. const ( // Data Frame FlagDataEndStream Flags = 0x1 FlagDataPadded Flags = 0x8 // Headers Frame FlagHeadersEndStream Flags = 0x1 FlagHeadersEndHeaders Flags = 0x4 FlagHeadersPadded Flags = 0x8 FlagHeadersPriority Flags = 0x20 // Settings Frame FlagSettingsAck Flags = 0x1 // Ping Frame FlagPingAck Flags = 0x1 // Continuation Frame FlagContinuationEndHeaders Flags = 0x4 FlagPushPromiseEndHeaders Flags = 0x4 FlagPushPromisePadded Flags = 0x8 ) var flagName = map[FrameType]map[Flags]string{ FrameData: { FlagDataEndStream: "END_STREAM", FlagDataPadded: "PADDED", }, FrameHeaders: { FlagHeadersEndStream: "END_STREAM", FlagHeadersEndHeaders: "END_HEADERS", FlagHeadersPadded: "PADDED", FlagHeadersPriority: "PRIORITY", }, FrameSettings: { FlagSettingsAck: "ACK", }, FramePing: { FlagPingAck: "ACK", }, FrameContinuation: { FlagContinuationEndHeaders: "END_HEADERS", }, FramePushPromise: { FlagPushPromiseEndHeaders: "END_HEADERS", FlagPushPromisePadded: "PADDED", }, } // a frameParser parses a frame given its FrameHeader and payload // bytes. The length of payload will always equal fh.Length (which // might be 0). type frameParser func(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error) var frameParsers = map[FrameType]frameParser{ FrameData: parseDataFrame, FrameHeaders: parseHeadersFrame, FramePriority: parsePriorityFrame, FrameRSTStream: parseRSTStreamFrame, FrameSettings: parseSettingsFrame, FramePushPromise: parsePushPromise, FramePing: parsePingFrame, FrameGoAway: parseGoAwayFrame, FrameWindowUpdate: parseWindowUpdateFrame, FrameContinuation: parseContinuationFrame, } func typeFrameParser(t FrameType) frameParser { if f := frameParsers[t]; f != nil { return f } return parseUnknownFrame } // A FrameHeader is the 9 byte header of all HTTP/2 frames. // // See http://http2.github.io/http2-spec/#FrameHeader type FrameHeader struct { valid bool // caller can access []byte fields in the Frame // Type is the 1 byte frame type. There are ten standard frame // types, but extension frame types may be written by WriteRawFrame // and will be returned by ReadFrame (as UnknownFrame). Type FrameType // Flags are the 1 byte of 8 potential bit flags per frame. // They are specific to the frame type. Flags Flags // Length is the length of the frame, not including the 9 byte header. // The maximum size is one byte less than 16MB (uint24), but only // frames up to 16KB are allowed without peer agreement. Length uint32 // StreamID is which stream this frame is for. Certain frames // are not stream-specific, in which case this field is 0. StreamID uint32 } // Header returns h. It exists so FrameHeaders can be embedded in other // specific frame types and implement the Frame interface. func (h FrameHeader) Header() FrameHeader { return h } func (h FrameHeader) String() string { var buf bytes.Buffer buf.WriteString("[FrameHeader ") h.writeDebug(&buf) buf.WriteByte(']') return buf.String() } func (h FrameHeader) writeDebug(buf *bytes.Buffer) { buf.WriteString(h.Type.String()) if h.Flags != 0 { buf.WriteString(" flags=") set := 0 for i := uint8(0); i < 8; i++ { if h.Flags&(1< 1 { buf.WriteByte('|') } name := flagName[h.Type][Flags(1<>24), byte(streamID>>16), byte(streamID>>8), byte(streamID)) } func (f *Framer) endWrite() error { // Now that we know the final size, fill in the FrameHeader in // the space previously reserved for it. Abuse append. length := len(f.wbuf) - frameHeaderLen if length >= (1 << 24) { return ErrFrameTooLarge } _ = append(f.wbuf[:0], byte(length>>16), byte(length>>8), byte(length)) if f.logWrites { f.logWrite() } n, err := f.w.Write(f.wbuf) if err == nil && n != len(f.wbuf) { err = io.ErrShortWrite } return err } func (f *Framer) logWrite() { if f.debugFramer == nil { f.debugFramerBuf = new(bytes.Buffer) f.debugFramer = NewFramer(nil, f.debugFramerBuf) f.debugFramer.logReads = false // we log it ourselves, saying "wrote" below // Let us read anything, even if we accidentally wrote it // in the wrong order: f.debugFramer.AllowIllegalReads = true } f.debugFramerBuf.Write(f.wbuf) fr, err := f.debugFramer.ReadFrame() if err != nil { f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f) return } f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, summarizeFrame(fr)) } func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) } func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) } func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) } func (f *Framer) writeUint32(v uint32) { f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) } const ( minMaxFrameSize = 1 << 14 maxFrameSize = 1<<24 - 1 ) // SetReuseFrames allows the Framer to reuse Frames. // If called on a Framer, Frames returned by calls to ReadFrame are only // valid until the next call to ReadFrame. func (fr *Framer) SetReuseFrames() { if fr.frameCache != nil { return } fr.frameCache = &frameCache{} } type frameCache struct { dataFrame DataFrame } func (fc *frameCache) getDataFrame() *DataFrame { if fc == nil { return &DataFrame{} } return &fc.dataFrame } // NewFramer returns a Framer that writes frames to w and reads them from r. func NewFramer(w io.Writer, r io.Reader) *Framer { fr := &Framer{ w: w, r: r, logReads: logFrameReads, logWrites: logFrameWrites, debugReadLoggerf: log.Printf, debugWriteLoggerf: log.Printf, } fr.getReadBuf = func(size uint32) []byte { if cap(fr.readBuf) >= int(size) { return fr.readBuf[:size] } fr.readBuf = make([]byte, size) return fr.readBuf } fr.SetMaxReadFrameSize(maxFrameSize) return fr } // SetMaxReadFrameSize sets the maximum size of a frame // that will be read by a subsequent call to ReadFrame. // It is the caller's responsibility to advertise this // limit with a SETTINGS frame. func (fr *Framer) SetMaxReadFrameSize(v uint32) { if v > maxFrameSize { v = maxFrameSize } fr.maxReadSize = v } // ErrorDetail returns a more detailed error of the last error // returned by Framer.ReadFrame. For instance, if ReadFrame // returns a StreamError with code PROTOCOL_ERROR, ErrorDetail // will say exactly what was invalid. ErrorDetail is not guaranteed // to return a non-nil value and like the rest of the http2 package, // its return value is not protected by an API compatibility promise. // ErrorDetail is reset after the next call to ReadFrame. func (fr *Framer) ErrorDetail() error { return fr.errDetail } // ErrFrameTooLarge is returned from Framer.ReadFrame when the peer // sends a frame that is larger than declared with SetMaxReadFrameSize. var ErrFrameTooLarge = errors.New("http2: frame too large") // terminalReadFrameError reports whether err is an unrecoverable // error from ReadFrame and no other frames should be read. func terminalReadFrameError(err error) bool { if _, ok := err.(StreamError); ok { return false } return err != nil } // ReadFrame reads a single frame. The returned Frame is only valid // until the next call to ReadFrame. // // If the frame is larger than previously set with SetMaxReadFrameSize, the // returned error is ErrFrameTooLarge. Other errors may be of type // ConnectionError, StreamError, or anything else from the underlying // reader. func (fr *Framer) ReadFrame() (Frame, error) { fr.errDetail = nil if fr.lastFrame != nil { fr.lastFrame.invalidate() } fh, err := readFrameHeader(fr.headerBuf[:], fr.r) if err != nil { return nil, err } if fh.Length > fr.maxReadSize { return nil, ErrFrameTooLarge } payload := fr.getReadBuf(fh.Length) if _, err := io.ReadFull(fr.r, payload); err != nil { return nil, err } f, err := typeFrameParser(fh.Type)(fr.frameCache, fh, payload) if err != nil { if ce, ok := err.(connError); ok { return nil, fr.connError(ce.Code, ce.Reason) } return nil, err } if err := fr.checkFrameOrder(f); err != nil { return nil, err } if fr.logReads { fr.debugReadLoggerf("http2: Framer %p: read %v", fr, summarizeFrame(f)) } if fh.Type == FrameHeaders && fr.ReadMetaHeaders != nil { return fr.readMetaFrame(f.(*HeadersFrame)) } return f, nil } // connError returns ConnectionError(code) but first // stashes away a public reason to the caller can optionally relay it // to the peer before hanging up on them. This might help others debug // their implementations. func (fr *Framer) connError(code ErrCode, reason string) error { fr.errDetail = errors.New(reason) return ConnectionError(code) } // checkFrameOrder reports an error if f is an invalid frame to return // next from ReadFrame. Mostly it checks whether HEADERS and // CONTINUATION frames are contiguous. func (fr *Framer) checkFrameOrder(f Frame) error { last := fr.lastFrame fr.lastFrame = f if fr.AllowIllegalReads { return nil } fh := f.Header() if fr.lastHeaderStream != 0 { if fh.Type != FrameContinuation { return fr.connError(ErrCodeProtocol, fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d", fh.Type, fh.StreamID, last.Header().Type, fr.lastHeaderStream)) } if fh.StreamID != fr.lastHeaderStream { return fr.connError(ErrCodeProtocol, fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d", fh.StreamID, fr.lastHeaderStream)) } } else if fh.Type == FrameContinuation { return fr.connError(ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID)) } switch fh.Type { case FrameHeaders, FrameContinuation: if fh.Flags.Has(FlagHeadersEndHeaders) { fr.lastHeaderStream = 0 } else { fr.lastHeaderStream = fh.StreamID } } return nil } // A DataFrame conveys arbitrary, variable-length sequences of octets // associated with a stream. // See http://http2.github.io/http2-spec/#rfc.section.6.1 type DataFrame struct { FrameHeader data []byte } func (f *DataFrame) StreamEnded() bool { return f.FrameHeader.Flags.Has(FlagDataEndStream) } // Data returns the frame's data octets, not including any padding // size byte or padding suffix bytes. // The caller must not retain the returned memory past the next // call to ReadFrame. func (f *DataFrame) Data() []byte { f.checkValid() return f.data } func parseDataFrame(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error) { if fh.StreamID == 0 { // DATA frames MUST be associated with a stream. If a // DATA frame is received whose stream identifier // field is 0x0, the recipient MUST respond with a // connection error (Section 5.4.1) of type // PROTOCOL_ERROR. return nil, connError{ErrCodeProtocol, "DATA frame with stream ID 0"} } f := fc.getDataFrame() f.FrameHeader = fh var padSize byte if fh.Flags.Has(FlagDataPadded) { var err error payload, padSize, err = readByte(payload) if err != nil { return nil, err } } if int(padSize) > len(payload) { // If the length of the padding is greater than the // length of the frame payload, the recipient MUST // treat this as a connection error. // Filed: https://github.com/http2/http2-spec/issues/610 return nil, connError{ErrCodeProtocol, "pad size larger than data payload"} } f.data = payload[:len(payload)-int(padSize)] return f, nil } var ( errStreamID = errors.New("invalid stream ID") errDepStreamID = errors.New("invalid dependent stream ID") errPadLength = errors.New("pad length too large") errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled") ) func validStreamIDOrZero(streamID uint32) bool { return streamID&(1<<31) == 0 } func validStreamID(streamID uint32) bool { return streamID != 0 && streamID&(1<<31) == 0 } // WriteData writes a DATA frame. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility not to violate the maximum frame size // and to not call other Write methods concurrently. func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error { return f.WriteDataPadded(streamID, endStream, data, nil) } // WriteData writes a DATA frame with optional padding. // // If pad is nil, the padding bit is not sent. // The length of pad must not exceed 255 bytes. // The bytes of pad must all be zero, unless f.AllowIllegalWrites is set. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility not to violate the maximum frame size // and to not call other Write methods concurrently. func (f *Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error { if !validStreamID(streamID) && !f.AllowIllegalWrites { return errStreamID } if len(pad) > 0 { if len(pad) > 255 { return errPadLength } if !f.AllowIllegalWrites { for _, b := range pad { if b != 0 { // "Padding octets MUST be set to zero when sending." return errPadBytes } } } } var flags Flags if endStream { flags |= FlagDataEndStream } if pad != nil { flags |= FlagDataPadded } f.startWrite(FrameData, flags, streamID) if pad != nil { f.wbuf = append(f.wbuf, byte(len(pad))) } f.wbuf = append(f.wbuf, data...) f.wbuf = append(f.wbuf, pad...) return f.endWrite() } // A SettingsFrame conveys configuration parameters that affect how // endpoints communicate, such as preferences and constraints on peer // behavior. // // See http://http2.github.io/http2-spec/#SETTINGS type SettingsFrame struct { FrameHeader p []byte } func parseSettingsFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 { // When this (ACK 0x1) bit is set, the payload of the // SETTINGS frame MUST be empty. Receipt of a // SETTINGS frame with the ACK flag set and a length // field value other than 0 MUST be treated as a // connection error (Section 5.4.1) of type // FRAME_SIZE_ERROR. return nil, ConnectionError(ErrCodeFrameSize) } if fh.StreamID != 0 { // SETTINGS frames always apply to a connection, // never a single stream. The stream identifier for a // SETTINGS frame MUST be zero (0x0). If an endpoint // receives a SETTINGS frame whose stream identifier // field is anything other than 0x0, the endpoint MUST // respond with a connection error (Section 5.4.1) of // type PROTOCOL_ERROR. return nil, ConnectionError(ErrCodeProtocol) } if len(p)%6 != 0 { // Expecting even number of 6 byte settings. return nil, ConnectionError(ErrCodeFrameSize) } f := &SettingsFrame{FrameHeader: fh, p: p} if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 { // Values above the maximum flow control window size of 2^31 - 1 MUST // be treated as a connection error (Section 5.4.1) of type // FLOW_CONTROL_ERROR. return nil, ConnectionError(ErrCodeFlowControl) } return f, nil } func (f *SettingsFrame) IsAck() bool { return f.FrameHeader.Flags.Has(FlagSettingsAck) } func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) { f.checkValid() buf := f.p for len(buf) > 0 { settingID := SettingID(binary.BigEndian.Uint16(buf[:2])) if settingID == s { return binary.BigEndian.Uint32(buf[2:6]), true } buf = buf[6:] } return 0, false } // ForeachSetting runs fn for each setting. // It stops and returns the first error. func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error { f.checkValid() buf := f.p for len(buf) > 0 { if err := fn(Setting{ SettingID(binary.BigEndian.Uint16(buf[:2])), binary.BigEndian.Uint32(buf[2:6]), }); err != nil { return err } buf = buf[6:] } return nil } // WriteSettings writes a SETTINGS frame with zero or more settings // specified and the ACK bit not set. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility to not call other Write methods concurrently. func (f *Framer) WriteSettings(settings ...Setting) error { f.startWrite(FrameSettings, 0, 0) for _, s := range settings { f.writeUint16(uint16(s.ID)) f.writeUint32(s.Val) } return f.endWrite() } // WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility to not call other Write methods concurrently. func (f *Framer) WriteSettingsAck() error { f.startWrite(FrameSettings, FlagSettingsAck, 0) return f.endWrite() } // A PingFrame is a mechanism for measuring a minimal round trip time // from the sender, as well as determining whether an idle connection // is still functional. // See http://http2.github.io/http2-spec/#rfc.section.6.7 type PingFrame struct { FrameHeader Data [8]byte } func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) } func parsePingFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) { if len(payload) != 8 { return nil, ConnectionError(ErrCodeFrameSize) } if fh.StreamID != 0 { return nil, ConnectionError(ErrCodeProtocol) } f := &PingFrame{FrameHeader: fh} copy(f.Data[:], payload) return f, nil } func (f *Framer) WritePing(ack bool, data [8]byte) error { var flags Flags if ack { flags = FlagPingAck } f.startWrite(FramePing, flags, 0) f.writeBytes(data[:]) return f.endWrite() } // A GoAwayFrame informs the remote peer to stop creating streams on this connection. // See http://http2.github.io/http2-spec/#rfc.section.6.8 type GoAwayFrame struct { FrameHeader LastStreamID uint32 ErrCode ErrCode debugData []byte } // DebugData returns any debug data in the GOAWAY frame. Its contents // are not defined. // The caller must not retain the returned memory past the next // call to ReadFrame. func (f *GoAwayFrame) DebugData() []byte { f.checkValid() return f.debugData } func parseGoAwayFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { if fh.StreamID != 0 { return nil, ConnectionError(ErrCodeProtocol) } if len(p) < 8 { return nil, ConnectionError(ErrCodeFrameSize) } return &GoAwayFrame{ FrameHeader: fh, LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1), ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])), debugData: p[8:], }, nil } func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error { f.startWrite(FrameGoAway, 0, 0) f.writeUint32(maxStreamID & (1<<31 - 1)) f.writeUint32(uint32(code)) f.writeBytes(debugData) return f.endWrite() } // An UnknownFrame is the frame type returned when the frame type is unknown // or no specific frame type parser exists. type UnknownFrame struct { FrameHeader p []byte } // Payload returns the frame's payload (after the header). It is not // valid to call this method after a subsequent call to // Framer.ReadFrame, nor is it valid to retain the returned slice. // The memory is owned by the Framer and is invalidated when the next // frame is read. func (f *UnknownFrame) Payload() []byte { f.checkValid() return f.p } func parseUnknownFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { return &UnknownFrame{fh, p}, nil } // A WindowUpdateFrame is used to implement flow control. // See http://http2.github.io/http2-spec/#rfc.section.6.9 type WindowUpdateFrame struct { FrameHeader Increment uint32 // never read with high bit set } func parseWindowUpdateFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { if len(p) != 4 { return nil, ConnectionError(ErrCodeFrameSize) } inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit if inc == 0 { // A receiver MUST treat the receipt of a // WINDOW_UPDATE frame with an flow control window // increment of 0 as a stream error (Section 5.4.2) of // type PROTOCOL_ERROR; errors on the connection flow // control window MUST be treated as a connection // error (Section 5.4.1). if fh.StreamID == 0 { return nil, ConnectionError(ErrCodeProtocol) } return nil, streamError(fh.StreamID, ErrCodeProtocol) } return &WindowUpdateFrame{ FrameHeader: fh, Increment: inc, }, nil } // WriteWindowUpdate writes a WINDOW_UPDATE frame. // The increment value must be between 1 and 2,147,483,647, inclusive. // If the Stream ID is zero, the window update applies to the // connection as a whole. func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error { // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets." if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites { return errors.New("illegal window increment value") } f.startWrite(FrameWindowUpdate, 0, streamID) f.writeUint32(incr) return f.endWrite() } // A HeadersFrame is used to open a stream and additionally carries a // header block fragment. type HeadersFrame struct { FrameHeader // Priority is set if FlagHeadersPriority is set in the FrameHeader. Priority PriorityParam headerFragBuf []byte // not owned } func (f *HeadersFrame) HeaderBlockFragment() []byte { f.checkValid() return f.headerFragBuf } func (f *HeadersFrame) HeadersEnded() bool { return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders) } func (f *HeadersFrame) StreamEnded() bool { return f.FrameHeader.Flags.Has(FlagHeadersEndStream) } func (f *HeadersFrame) HasPriority() bool { return f.FrameHeader.Flags.Has(FlagHeadersPriority) } func parseHeadersFrame(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) { hf := &HeadersFrame{ FrameHeader: fh, } if fh.StreamID == 0 { // HEADERS frames MUST be associated with a stream. If a HEADERS frame // is received whose stream identifier field is 0x0, the recipient MUST // respond with a connection error (Section 5.4.1) of type // PROTOCOL_ERROR. return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"} } var padLength uint8 if fh.Flags.Has(FlagHeadersPadded) { if p, padLength, err = readByte(p); err != nil { return } } if fh.Flags.Has(FlagHeadersPriority) { var v uint32 p, v, err = readUint32(p) if err != nil { return nil, err } hf.Priority.StreamDep = v & 0x7fffffff hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set p, hf.Priority.Weight, err = readByte(p) if err != nil { return nil, err } } if len(p)-int(padLength) <= 0 { return nil, streamError(fh.StreamID, ErrCodeProtocol) } hf.headerFragBuf = p[:len(p)-int(padLength)] return hf, nil } // HeadersFrameParam are the parameters for writing a HEADERS frame. type HeadersFrameParam struct { // StreamID is the required Stream ID to initiate. StreamID uint32 // BlockFragment is part (or all) of a Header Block. BlockFragment []byte // EndStream indicates that the header block is the last that // the endpoint will send for the identified stream. Setting // this flag causes the stream to enter one of "half closed" // states. EndStream bool // EndHeaders indicates that this frame contains an entire // header block and is not followed by any // CONTINUATION frames. EndHeaders bool // PadLength is the optional number of bytes of zeros to add // to this frame. PadLength uint8 // Priority, if non-zero, includes stream priority information // in the HEADER frame. Priority PriorityParam } // WriteHeaders writes a single HEADERS frame. // // This is a low-level header writing method. Encoding headers and // splitting them into any necessary CONTINUATION frames is handled // elsewhere. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility to not call other Write methods concurrently. func (f *Framer) WriteHeaders(p HeadersFrameParam) error { if !validStreamID(p.StreamID) && !f.AllowIllegalWrites { return errStreamID } var flags Flags if p.PadLength != 0 { flags |= FlagHeadersPadded } if p.EndStream { flags |= FlagHeadersEndStream } if p.EndHeaders { flags |= FlagHeadersEndHeaders } if !p.Priority.IsZero() { flags |= FlagHeadersPriority } f.startWrite(FrameHeaders, flags, p.StreamID) if p.PadLength != 0 { f.writeByte(p.PadLength) } if !p.Priority.IsZero() { v := p.Priority.StreamDep if !validStreamIDOrZero(v) && !f.AllowIllegalWrites { return errDepStreamID } if p.Priority.Exclusive { v |= 1 << 31 } f.writeUint32(v) f.writeByte(p.Priority.Weight) } f.wbuf = append(f.wbuf, p.BlockFragment...) f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...) return f.endWrite() } // A PriorityFrame specifies the sender-advised priority of a stream. // See http://http2.github.io/http2-spec/#rfc.section.6.3 type PriorityFrame struct { FrameHeader PriorityParam } // PriorityParam are the stream prioritzation parameters. type PriorityParam struct { // StreamDep is a 31-bit stream identifier for the // stream that this stream depends on. Zero means no // dependency. StreamDep uint32 // Exclusive is whether the dependency is exclusive. Exclusive bool // Weight is the stream's zero-indexed weight. It should be // set together with StreamDep, or neither should be set. Per // the spec, "Add one to the value to obtain a weight between // 1 and 256." Weight uint8 } func (p PriorityParam) IsZero() bool { return p == PriorityParam{} } func parsePriorityFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) { if fh.StreamID == 0 { return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"} } if len(payload) != 5 { return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))} } v := binary.BigEndian.Uint32(payload[:4]) streamID := v & 0x7fffffff // mask off high bit return &PriorityFrame{ FrameHeader: fh, PriorityParam: PriorityParam{ Weight: payload[4], StreamDep: streamID, Exclusive: streamID != v, // was high bit set? }, }, nil } // WritePriority writes a PRIORITY frame. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility to not call other Write methods concurrently. func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error { if !validStreamID(streamID) && !f.AllowIllegalWrites { return errStreamID } if !validStreamIDOrZero(p.StreamDep) { return errDepStreamID } f.startWrite(FramePriority, 0, streamID) v := p.StreamDep if p.Exclusive { v |= 1 << 31 } f.writeUint32(v) f.writeByte(p.Weight) return f.endWrite() } // A RSTStreamFrame allows for abnormal termination of a stream. // See http://http2.github.io/http2-spec/#rfc.section.6.4 type RSTStreamFrame struct { FrameHeader ErrCode ErrCode } func parseRSTStreamFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { if len(p) != 4 { return nil, ConnectionError(ErrCodeFrameSize) } if fh.StreamID == 0 { return nil, ConnectionError(ErrCodeProtocol) } return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil } // WriteRSTStream writes a RST_STREAM frame. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility to not call other Write methods concurrently. func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error { if !validStreamID(streamID) && !f.AllowIllegalWrites { return errStreamID } f.startWrite(FrameRSTStream, 0, streamID) f.writeUint32(uint32(code)) return f.endWrite() } // A ContinuationFrame is used to continue a sequence of header block fragments. // See http://http2.github.io/http2-spec/#rfc.section.6.10 type ContinuationFrame struct { FrameHeader headerFragBuf []byte } func parseContinuationFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { if fh.StreamID == 0 { return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"} } return &ContinuationFrame{fh, p}, nil } func (f *ContinuationFrame) HeaderBlockFragment() []byte { f.checkValid() return f.headerFragBuf } func (f *ContinuationFrame) HeadersEnded() bool { return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders) } // WriteContinuation writes a CONTINUATION frame. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility to not call other Write methods concurrently. func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error { if !validStreamID(streamID) && !f.AllowIllegalWrites { return errStreamID } var flags Flags if endHeaders { flags |= FlagContinuationEndHeaders } f.startWrite(FrameContinuation, flags, streamID) f.wbuf = append(f.wbuf, headerBlockFragment...) return f.endWrite() } // A PushPromiseFrame is used to initiate a server stream. // See http://http2.github.io/http2-spec/#rfc.section.6.6 type PushPromiseFrame struct { FrameHeader PromiseID uint32 headerFragBuf []byte // not owned } func (f *PushPromiseFrame) HeaderBlockFragment() []byte { f.checkValid() return f.headerFragBuf } func (f *PushPromiseFrame) HeadersEnded() bool { return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders) } func parsePushPromise(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) { pp := &PushPromiseFrame{ FrameHeader: fh, } if pp.StreamID == 0 { // PUSH_PROMISE frames MUST be associated with an existing, // peer-initiated stream. The stream identifier of a // PUSH_PROMISE frame indicates the stream it is associated // with. If the stream identifier field specifies the value // 0x0, a recipient MUST respond with a connection error // (Section 5.4.1) of type PROTOCOL_ERROR. return nil, ConnectionError(ErrCodeProtocol) } // The PUSH_PROMISE frame includes optional padding. // Padding fields and flags are identical to those defined for DATA frames var padLength uint8 if fh.Flags.Has(FlagPushPromisePadded) { if p, padLength, err = readByte(p); err != nil { return } } p, pp.PromiseID, err = readUint32(p) if err != nil { return } pp.PromiseID = pp.PromiseID & (1<<31 - 1) if int(padLength) > len(p) { // like the DATA frame, error out if padding is longer than the body. return nil, ConnectionError(ErrCodeProtocol) } pp.headerFragBuf = p[:len(p)-int(padLength)] return pp, nil } // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame. type PushPromiseParam struct { // StreamID is the required Stream ID to initiate. StreamID uint32 // PromiseID is the required Stream ID which this // Push Promises PromiseID uint32 // BlockFragment is part (or all) of a Header Block. BlockFragment []byte // EndHeaders indicates that this frame contains an entire // header block and is not followed by any // CONTINUATION frames. EndHeaders bool // PadLength is the optional number of bytes of zeros to add // to this frame. PadLength uint8 } // WritePushPromise writes a single PushPromise Frame. // // As with Header Frames, This is the low level call for writing // individual frames. Continuation frames are handled elsewhere. // // It will perform exactly one Write to the underlying Writer. // It is the caller's responsibility to not call other Write methods concurrently. func (f *Framer) WritePushPromise(p PushPromiseParam) error { if !validStreamID(p.StreamID) && !f.AllowIllegalWrites { return errStreamID } var flags Flags if p.PadLength != 0 { flags |= FlagPushPromisePadded } if p.EndHeaders { flags |= FlagPushPromiseEndHeaders } f.startWrite(FramePushPromise, flags, p.StreamID) if p.PadLength != 0 { f.writeByte(p.PadLength) } if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites { return errStreamID } f.writeUint32(p.PromiseID) f.wbuf = append(f.wbuf, p.BlockFragment...) f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...) return f.endWrite() } // WriteRawFrame writes a raw frame. This can be used to write // extension frames unknown to this package. func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error { f.startWrite(t, flags, streamID) f.writeBytes(payload) return f.endWrite() } func readByte(p []byte) (remain []byte, b byte, err error) { if len(p) == 0 { return nil, 0, io.ErrUnexpectedEOF } return p[1:], p[0], nil } func readUint32(p []byte) (remain []byte, v uint32, err error) { if len(p) < 4 { return nil, 0, io.ErrUnexpectedEOF } return p[4:], binary.BigEndian.Uint32(p[:4]), nil } type streamEnder interface { StreamEnded() bool } type headersEnder interface { HeadersEnded() bool } type headersOrContinuation interface { headersEnder HeaderBlockFragment() []byte } // A MetaHeadersFrame is the representation of one HEADERS frame and // zero or more contiguous CONTINUATION frames and the decoding of // their HPACK-encoded contents. // // This type of frame does not appear on the wire and is only returned // by the Framer when Framer.ReadMetaHeaders is set. type MetaHeadersFrame struct { *HeadersFrame // Fields are the fields contained in the HEADERS and // CONTINUATION frames. The underlying slice is owned by the // Framer and must not be retained after the next call to // ReadFrame. // // Fields are guaranteed to be in the correct http2 order and // not have unknown pseudo header fields or invalid header // field names or values. Required pseudo header fields may be // missing, however. Use the MetaHeadersFrame.Pseudo accessor // method access pseudo headers. Fields []hpack.HeaderField // Truncated is whether the max header list size limit was hit // and Fields is incomplete. The hpack decoder state is still // valid, however. Truncated bool } // PseudoValue returns the given pseudo header field's value. // The provided pseudo field should not contain the leading colon. func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string { for _, hf := range mh.Fields { if !hf.IsPseudo() { return "" } if hf.Name[1:] == pseudo { return hf.Value } } return "" } // RegularFields returns the regular (non-pseudo) header fields of mh. // The caller does not own the returned slice. func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField { for i, hf := range mh.Fields { if !hf.IsPseudo() { return mh.Fields[i:] } } return nil } // PseudoFields returns the pseudo header fields of mh. // The caller does not own the returned slice. func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField { for i, hf := range mh.Fields { if !hf.IsPseudo() { return mh.Fields[:i] } } return mh.Fields } func (mh *MetaHeadersFrame) checkPseudos() error { var isRequest, isResponse bool pf := mh.PseudoFields() for i, hf := range pf { switch hf.Name { case ":method", ":path", ":scheme", ":authority": isRequest = true case ":status": isResponse = true default: return pseudoHeaderError(hf.Name) } // Check for duplicates. // This would be a bad algorithm, but N is 4. // And this doesn't allocate. for _, hf2 := range pf[:i] { if hf.Name == hf2.Name { return duplicatePseudoHeaderError(hf.Name) } } } if isRequest && isResponse { return errMixPseudoHeaderTypes } return nil } func (fr *Framer) maxHeaderStringLen() int { v := fr.maxHeaderListSize() if uint32(int(v)) == v { return int(v) } // They had a crazy big number for MaxHeaderBytes anyway, // so give them unlimited header lengths: return 0 } // readMetaFrame returns 0 or more CONTINUATION frames from fr and // merge them into into the provided hf and returns a MetaHeadersFrame // with the decoded hpack values. func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) { if fr.AllowIllegalReads { return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders") } mh := &MetaHeadersFrame{ HeadersFrame: hf, } var remainSize = fr.maxHeaderListSize() var sawRegular bool var invalid error // pseudo header field errors hdec := fr.ReadMetaHeaders hdec.SetEmitEnabled(true) hdec.SetMaxStringLength(fr.maxHeaderStringLen()) hdec.SetEmitFunc(func(hf hpack.HeaderField) { if VerboseLogs && fr.logReads { fr.debugReadLoggerf("http2: decoded hpack field %+v", hf) } if !httplex.ValidHeaderFieldValue(hf.Value) { invalid = headerFieldValueError(hf.Value) } isPseudo := strings.HasPrefix(hf.Name, ":") if isPseudo { if sawRegular { invalid = errPseudoAfterRegular } } else { sawRegular = true if !validWireHeaderFieldName(hf.Name) { invalid = headerFieldNameError(hf.Name) } } if invalid != nil { hdec.SetEmitEnabled(false) return } size := hf.Size() if size > remainSize { hdec.SetEmitEnabled(false) mh.Truncated = true return } remainSize -= size mh.Fields = append(mh.Fields, hf) }) // Lose reference to MetaHeadersFrame: defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {}) var hc headersOrContinuation = hf for { frag := hc.HeaderBlockFragment() if _, err := hdec.Write(frag); err != nil { return nil, ConnectionError(ErrCodeCompression) } if hc.HeadersEnded() { break } if f, err := fr.ReadFrame(); err != nil { return nil, err } else { hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder } } mh.HeadersFrame.headerFragBuf = nil mh.HeadersFrame.invalidate() if err := hdec.Close(); err != nil { return nil, ConnectionError(ErrCodeCompression) } if invalid != nil { fr.errDetail = invalid if VerboseLogs { log.Printf("http2: invalid header: %v", invalid) } return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid} } if err := mh.checkPseudos(); err != nil { fr.errDetail = err if VerboseLogs { log.Printf("http2: invalid pseudo headers: %v", err) } return nil, StreamError{mh.StreamID, ErrCodeProtocol, err} } return mh, nil } func summarizeFrame(f Frame) string { var buf bytes.Buffer f.Header().writeDebug(&buf) switch f := f.(type) { case *SettingsFrame: n := 0 f.ForeachSetting(func(s Setting) error { n++ if n == 1 { buf.WriteString(", settings:") } fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val) return nil }) if n > 0 { buf.Truncate(buf.Len() - 1) // remove trailing comma } case *DataFrame: data := f.Data() const max = 256 if len(data) > max { data = data[:max] } fmt.Fprintf(&buf, " data=%q", data) if len(f.Data()) > max { fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max) } case *WindowUpdateFrame: if f.StreamID == 0 { buf.WriteString(" (conn)") } fmt.Fprintf(&buf, " incr=%v", f.Increment) case *PingFrame: fmt.Fprintf(&buf, " ping=%q", f.Data[:]) case *GoAwayFrame: fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q", f.LastStreamID, f.ErrCode, f.debugData) case *RSTStreamFrame: fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode) } return buf.String() } lxd-2.0.11/dist/src/golang.org/x/net/http2/flow_test.go0000644061062106075000000000240413172163402023711 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import "testing" func TestFlow(t *testing.T) { var st flow var conn flow st.add(3) conn.add(2) if got, want := st.available(), int32(3); got != want { t.Errorf("available = %d; want %d", got, want) } st.setConnFlow(&conn) if got, want := st.available(), int32(2); got != want { t.Errorf("after parent setup, available = %d; want %d", got, want) } st.take(2) if got, want := conn.available(), int32(0); got != want { t.Errorf("after taking 2, conn = %d; want %d", got, want) } if got, want := st.available(), int32(0); got != want { t.Errorf("after taking 2, stream = %d; want %d", got, want) } } func TestFlowAdd(t *testing.T) { var f flow if !f.add(1) { t.Fatal("failed to add 1") } if !f.add(-1) { t.Fatal("failed to add -1") } if got, want := f.available(), int32(0); got != want { t.Fatalf("size = %d; want %d", got, want) } if !f.add(1<<31 - 1) { t.Fatal("failed to add 2^31-1") } if got, want := f.available(), int32(1<<31-1); got != want { t.Fatalf("size = %d; want %d", got, want) } if f.add(1) { t.Fatal("adding 1 to max shouldn't be allowed") } } lxd-2.0.11/dist/src/golang.org/x/net/http2/flow.go0000644061062106075000000000212413172163402022651 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Flow control package http2 // flow is the flow control window's size. type flow struct { // n is the number of DATA bytes we're allowed to send. // A flow is kept both on a conn and a per-stream. n int32 // conn points to the shared connection-level flow that is // shared by all streams on that conn. It is nil for the flow // that's on the conn directly. conn *flow } func (f *flow) setConnFlow(cf *flow) { f.conn = cf } func (f *flow) available() int32 { n := f.n if f.conn != nil && f.conn.n < n { n = f.conn.n } return n } func (f *flow) take(n int32) { if n > f.available() { panic("internal error: took too much") } f.n -= n if f.conn != nil { f.conn.n -= n } } // add adds n bytes (positive or negative) to the flow control window. // It returns false if the sum would exceed 2^31-1. func (f *flow) add(n int32) bool { remain := (1<<31 - 1) - f.n if n > remain { return false } f.n += n return true } lxd-2.0.11/dist/src/golang.org/x/net/http2/errors_test.go0000644061062106075000000000102513172163402024254 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import "testing" func TestErrCodeString(t *testing.T) { tests := []struct { err ErrCode want string }{ {ErrCodeProtocol, "PROTOCOL_ERROR"}, {0xd, "HTTP_1_1_REQUIRED"}, {0xf, "unknown error code 0xf"}, } for i, tt := range tests { got := tt.err.String() if got != tt.want { t.Errorf("%d. Error = %q; want %q", i, got, tt.want) } } } lxd-2.0.11/dist/src/golang.org/x/net/http2/errors.go0000644061062106075000000001022313172163402023215 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "errors" "fmt" ) // An ErrCode is an unsigned 32-bit error code as defined in the HTTP/2 spec. type ErrCode uint32 const ( ErrCodeNo ErrCode = 0x0 ErrCodeProtocol ErrCode = 0x1 ErrCodeInternal ErrCode = 0x2 ErrCodeFlowControl ErrCode = 0x3 ErrCodeSettingsTimeout ErrCode = 0x4 ErrCodeStreamClosed ErrCode = 0x5 ErrCodeFrameSize ErrCode = 0x6 ErrCodeRefusedStream ErrCode = 0x7 ErrCodeCancel ErrCode = 0x8 ErrCodeCompression ErrCode = 0x9 ErrCodeConnect ErrCode = 0xa ErrCodeEnhanceYourCalm ErrCode = 0xb ErrCodeInadequateSecurity ErrCode = 0xc ErrCodeHTTP11Required ErrCode = 0xd ) var errCodeName = map[ErrCode]string{ ErrCodeNo: "NO_ERROR", ErrCodeProtocol: "PROTOCOL_ERROR", ErrCodeInternal: "INTERNAL_ERROR", ErrCodeFlowControl: "FLOW_CONTROL_ERROR", ErrCodeSettingsTimeout: "SETTINGS_TIMEOUT", ErrCodeStreamClosed: "STREAM_CLOSED", ErrCodeFrameSize: "FRAME_SIZE_ERROR", ErrCodeRefusedStream: "REFUSED_STREAM", ErrCodeCancel: "CANCEL", ErrCodeCompression: "COMPRESSION_ERROR", ErrCodeConnect: "CONNECT_ERROR", ErrCodeEnhanceYourCalm: "ENHANCE_YOUR_CALM", ErrCodeInadequateSecurity: "INADEQUATE_SECURITY", ErrCodeHTTP11Required: "HTTP_1_1_REQUIRED", } func (e ErrCode) String() string { if s, ok := errCodeName[e]; ok { return s } return fmt.Sprintf("unknown error code 0x%x", uint32(e)) } // ConnectionError is an error that results in the termination of the // entire connection. type ConnectionError ErrCode func (e ConnectionError) Error() string { return fmt.Sprintf("connection error: %s", ErrCode(e)) } // StreamError is an error that only affects one stream within an // HTTP/2 connection. type StreamError struct { StreamID uint32 Code ErrCode Cause error // optional additional detail } func streamError(id uint32, code ErrCode) StreamError { return StreamError{StreamID: id, Code: code} } func (e StreamError) Error() string { if e.Cause != nil { return fmt.Sprintf("stream error: stream ID %d; %v; %v", e.StreamID, e.Code, e.Cause) } return fmt.Sprintf("stream error: stream ID %d; %v", e.StreamID, e.Code) } // 6.9.1 The Flow Control Window // "If a sender receives a WINDOW_UPDATE that causes a flow control // window to exceed this maximum it MUST terminate either the stream // or the connection, as appropriate. For streams, [...]; for the // connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code." type goAwayFlowError struct{} func (goAwayFlowError) Error() string { return "connection exceeded flow control window size" } // connError represents an HTTP/2 ConnectionError error code, along // with a string (for debugging) explaining why. // // Errors of this type are only returned by the frame parser functions // and converted into ConnectionError(Code), after stashing away // the Reason into the Framer's errDetail field, accessible via // the (*Framer).ErrorDetail method. type connError struct { Code ErrCode // the ConnectionError error code Reason string // additional reason } func (e connError) Error() string { return fmt.Sprintf("http2: connection error: %v: %v", e.Code, e.Reason) } type pseudoHeaderError string func (e pseudoHeaderError) Error() string { return fmt.Sprintf("invalid pseudo-header %q", string(e)) } type duplicatePseudoHeaderError string func (e duplicatePseudoHeaderError) Error() string { return fmt.Sprintf("duplicate pseudo-header %q", string(e)) } type headerFieldNameError string func (e headerFieldNameError) Error() string { return fmt.Sprintf("invalid header field name %q", string(e)) } type headerFieldValueError string func (e headerFieldValueError) Error() string { return fmt.Sprintf("invalid header field value %q", string(e)) } var ( errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers") errPseudoAfterRegular = errors.New("pseudo header field after regular") ) lxd-2.0.11/dist/src/golang.org/x/net/http2/databuffer_test.go0000644061062106075000000001045413172163402025051 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package http2 import ( "bytes" "fmt" "reflect" "testing" ) func fmtDataChunk(chunk []byte) string { out := "" var last byte var count int for _, c := range chunk { if c != last { if count > 0 { out += fmt.Sprintf(" x %d ", count) count = 0 } out += string([]byte{c}) last = c } count++ } if count > 0 { out += fmt.Sprintf(" x %d", count) } return out } func fmtDataChunks(chunks [][]byte) string { var out string for _, chunk := range chunks { out += fmt.Sprintf("{%q}", fmtDataChunk(chunk)) } return out } func testDataBuffer(t *testing.T, wantBytes []byte, setup func(t *testing.T) *dataBuffer) { // Run setup, then read the remaining bytes from the dataBuffer and check // that they match wantBytes. We use different read sizes to check corner // cases in Read. for _, readSize := range []int{1, 2, 1 * 1024, 32 * 1024} { t.Run(fmt.Sprintf("ReadSize=%d", readSize), func(t *testing.T) { b := setup(t) buf := make([]byte, readSize) var gotRead bytes.Buffer for { n, err := b.Read(buf) gotRead.Write(buf[:n]) if err == errReadEmpty { break } if err != nil { t.Fatalf("error after %v bytes: %v", gotRead.Len(), err) } } if got, want := gotRead.Bytes(), wantBytes; !bytes.Equal(got, want) { t.Errorf("FinalRead=%q, want %q", fmtDataChunk(got), fmtDataChunk(want)) } }) } } func TestDataBufferAllocation(t *testing.T) { writes := [][]byte{ bytes.Repeat([]byte("a"), 1*1024-1), []byte("a"), bytes.Repeat([]byte("b"), 4*1024-1), []byte("b"), bytes.Repeat([]byte("c"), 8*1024-1), []byte("c"), bytes.Repeat([]byte("d"), 16*1024-1), []byte("d"), bytes.Repeat([]byte("e"), 32*1024), } var wantRead bytes.Buffer for _, p := range writes { wantRead.Write(p) } testDataBuffer(t, wantRead.Bytes(), func(t *testing.T) *dataBuffer { b := &dataBuffer{} for _, p := range writes { if n, err := b.Write(p); n != len(p) || err != nil { t.Fatalf("Write(%q x %d)=%v,%v want %v,nil", p[:1], len(p), n, err, len(p)) } } want := [][]byte{ bytes.Repeat([]byte("a"), 1*1024), bytes.Repeat([]byte("b"), 4*1024), bytes.Repeat([]byte("c"), 8*1024), bytes.Repeat([]byte("d"), 16*1024), bytes.Repeat([]byte("e"), 16*1024), bytes.Repeat([]byte("e"), 16*1024), } if !reflect.DeepEqual(b.chunks, want) { t.Errorf("dataBuffer.chunks\ngot: %s\nwant: %s", fmtDataChunks(b.chunks), fmtDataChunks(want)) } return b }) } func TestDataBufferAllocationWithExpected(t *testing.T) { writes := [][]byte{ bytes.Repeat([]byte("a"), 1*1024), // allocates 16KB bytes.Repeat([]byte("b"), 14*1024), bytes.Repeat([]byte("c"), 15*1024), // allocates 16KB more bytes.Repeat([]byte("d"), 2*1024), bytes.Repeat([]byte("e"), 1*1024), // overflows 32KB expectation, allocates just 1KB } var wantRead bytes.Buffer for _, p := range writes { wantRead.Write(p) } testDataBuffer(t, wantRead.Bytes(), func(t *testing.T) *dataBuffer { b := &dataBuffer{expected: 32 * 1024} for _, p := range writes { if n, err := b.Write(p); n != len(p) || err != nil { t.Fatalf("Write(%q x %d)=%v,%v want %v,nil", p[:1], len(p), n, err, len(p)) } } want := [][]byte{ append(bytes.Repeat([]byte("a"), 1*1024), append(bytes.Repeat([]byte("b"), 14*1024), bytes.Repeat([]byte("c"), 1*1024)...)...), append(bytes.Repeat([]byte("c"), 14*1024), bytes.Repeat([]byte("d"), 2*1024)...), bytes.Repeat([]byte("e"), 1*1024), } if !reflect.DeepEqual(b.chunks, want) { t.Errorf("dataBuffer.chunks\ngot: %s\nwant: %s", fmtDataChunks(b.chunks), fmtDataChunks(want)) } return b }) } func TestDataBufferWriteAfterPartialRead(t *testing.T) { testDataBuffer(t, []byte("cdxyz"), func(t *testing.T) *dataBuffer { b := &dataBuffer{} if n, err := b.Write([]byte("abcd")); n != 4 || err != nil { t.Fatalf("Write(\"abcd\")=%v,%v want 4,nil", n, err) } p := make([]byte, 2) if n, err := b.Read(p); n != 2 || err != nil || !bytes.Equal(p, []byte("ab")) { t.Fatalf("Read()=%q,%v,%v want \"ab\",2,nil", p, n, err) } if n, err := b.Write([]byte("xyz")); n != 3 || err != nil { t.Fatalf("Write(\"xyz\")=%v,%v want 3,nil", n, err) } return b }) } lxd-2.0.11/dist/src/golang.org/x/net/http2/databuffer.go0000644061062106075000000000766713172163402024026 0ustar stgraberdomain admins// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import ( "errors" "fmt" "sync" ) // Buffer chunks are allocated from a pool to reduce pressure on GC. // The maximum wasted space per dataBuffer is 2x the largest size class, // which happens when the dataBuffer has multiple chunks and there is // one unread byte in both the first and last chunks. We use a few size // classes to minimize overheads for servers that typically receive very // small request bodies. // // TODO: Benchmark to determine if the pools are necessary. The GC may have // improved enough that we can instead allocate chunks like this: // make([]byte, max(16<<10, expectedBytesRemaining)) var ( dataChunkSizeClasses = []int{ 1 << 10, 2 << 10, 4 << 10, 8 << 10, 16 << 10, } dataChunkPools = [...]sync.Pool{ {New: func() interface{} { return make([]byte, 1<<10) }}, {New: func() interface{} { return make([]byte, 2<<10) }}, {New: func() interface{} { return make([]byte, 4<<10) }}, {New: func() interface{} { return make([]byte, 8<<10) }}, {New: func() interface{} { return make([]byte, 16<<10) }}, } ) func getDataBufferChunk(size int64) []byte { i := 0 for ; i < len(dataChunkSizeClasses)-1; i++ { if size <= int64(dataChunkSizeClasses[i]) { break } } return dataChunkPools[i].Get().([]byte) } func putDataBufferChunk(p []byte) { for i, n := range dataChunkSizeClasses { if len(p) == n { dataChunkPools[i].Put(p) return } } panic(fmt.Sprintf("unexpected buffer len=%v", len(p))) } // dataBuffer is an io.ReadWriter backed by a list of data chunks. // Each dataBuffer is used to read DATA frames on a single stream. // The buffer is divided into chunks so the server can limit the // total memory used by a single connection without limiting the // request body size on any single stream. type dataBuffer struct { chunks [][]byte r int // next byte to read is chunks[0][r] w int // next byte to write is chunks[len(chunks)-1][w] size int // total buffered bytes expected int64 // we expect at least this many bytes in future Write calls (ignored if <= 0) } var errReadEmpty = errors.New("read from empty dataBuffer") // Read copies bytes from the buffer into p. // It is an error to read when no data is available. func (b *dataBuffer) Read(p []byte) (int, error) { if b.size == 0 { return 0, errReadEmpty } var ntotal int for len(p) > 0 && b.size > 0 { readFrom := b.bytesFromFirstChunk() n := copy(p, readFrom) p = p[n:] ntotal += n b.r += n b.size -= n // If the first chunk has been consumed, advance to the next chunk. if b.r == len(b.chunks[0]) { putDataBufferChunk(b.chunks[0]) end := len(b.chunks) - 1 copy(b.chunks[:end], b.chunks[1:]) b.chunks[end] = nil b.chunks = b.chunks[:end] b.r = 0 } } return ntotal, nil } func (b *dataBuffer) bytesFromFirstChunk() []byte { if len(b.chunks) == 1 { return b.chunks[0][b.r:b.w] } return b.chunks[0][b.r:] } // Len returns the number of bytes of the unread portion of the buffer. func (b *dataBuffer) Len() int { return b.size } // Write appends p to the buffer. func (b *dataBuffer) Write(p []byte) (int, error) { ntotal := len(p) for len(p) > 0 { // If the last chunk is empty, allocate a new chunk. Try to allocate // enough to fully copy p plus any additional bytes we expect to // receive. However, this may allocate less than len(p). want := int64(len(p)) if b.expected > want { want = b.expected } chunk := b.lastChunkOrAlloc(want) n := copy(chunk[b.w:], p) p = p[n:] b.w += n b.size += n b.expected -= int64(n) } return ntotal, nil } func (b *dataBuffer) lastChunkOrAlloc(want int64) []byte { if len(b.chunks) != 0 { last := b.chunks[len(b.chunks)-1] if b.w < len(last) { return last } } chunk := getDataBufferChunk(want) b.chunks = append(b.chunks, chunk) b.w = 0 return chunk } lxd-2.0.11/dist/src/golang.org/x/net/http2/configure_transport.go0000644061062106075000000000437313172163402026007 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.6 package http2 import ( "crypto/tls" "fmt" "net/http" ) func configureTransport(t1 *http.Transport) (*Transport, error) { connPool := new(clientConnPool) t2 := &Transport{ ConnPool: noDialClientConnPool{connPool}, t1: t1, } connPool.t = t2 if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil { return nil, err } if t1.TLSClientConfig == nil { t1.TLSClientConfig = new(tls.Config) } if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") { t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...) } if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") { t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1") } upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper { addr := authorityAddr("https", authority) if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil { go c.Close() return erringRoundTripper{err} } else if !used { // Turns out we don't need this c. // For example, two goroutines made requests to the same host // at the same time, both kicking off TCP dials. (since protocol // was unknown) go c.Close() } return t2 } if m := t1.TLSNextProto; len(m) == 0 { t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{ "h2": upgradeFn, } } else { m["h2"] = upgradeFn } return t2, nil } // registerHTTPSProtocol calls Transport.RegisterProtocol but // converting panics into errors. func registerHTTPSProtocol(t *http.Transport, rt http.RoundTripper) (err error) { defer func() { if e := recover(); e != nil { err = fmt.Errorf("%v", e) } }() t.RegisterProtocol("https", rt) return nil } // noDialH2RoundTripper is a RoundTripper which only tries to complete the request // if there's already has a cached connection to the host. type noDialH2RoundTripper struct{ t *Transport } func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { res, err := rt.t.RoundTrip(req) if err == ErrNoCachedConn { return nil, http.ErrSkipAltProtocol } return res, err } lxd-2.0.11/dist/src/golang.org/x/net/http2/client_conn_pool.go0000644061062106075000000001457013172163402025236 0ustar stgraberdomain admins// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Transport code's client connection pooling. package http2 import ( "crypto/tls" "net/http" "sync" ) // ClientConnPool manages a pool of HTTP/2 client connections. type ClientConnPool interface { GetClientConn(req *http.Request, addr string) (*ClientConn, error) MarkDead(*ClientConn) } // clientConnPoolIdleCloser is the interface implemented by ClientConnPool // implementations which can close their idle connections. type clientConnPoolIdleCloser interface { ClientConnPool closeIdleConnections() } var ( _ clientConnPoolIdleCloser = (*clientConnPool)(nil) _ clientConnPoolIdleCloser = noDialClientConnPool{} ) // TODO: use singleflight for dialing and addConnCalls? type clientConnPool struct { t *Transport mu sync.Mutex // TODO: maybe switch to RWMutex // TODO: add support for sharing conns based on cert names // (e.g. share conn for googleapis.com and appspot.com) conns map[string][]*ClientConn // key is host:port dialing map[string]*dialCall // currently in-flight dials keys map[*ClientConn][]string addConnCalls map[string]*addConnCall // in-flight addConnIfNeede calls } func (p *clientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { return p.getClientConn(req, addr, dialOnMiss) } const ( dialOnMiss = true noDialOnMiss = false ) func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) { if isConnectionCloseRequest(req) && dialOnMiss { // It gets its own connection. const singleUse = true cc, err := p.t.dialClientConn(addr, singleUse) if err != nil { return nil, err } return cc, nil } p.mu.Lock() for _, cc := range p.conns[addr] { if cc.CanTakeNewRequest() { p.mu.Unlock() return cc, nil } } if !dialOnMiss { p.mu.Unlock() return nil, ErrNoCachedConn } call := p.getStartDialLocked(addr) p.mu.Unlock() <-call.done return call.res, call.err } // dialCall is an in-flight Transport dial call to a host. type dialCall struct { p *clientConnPool done chan struct{} // closed when done res *ClientConn // valid after done is closed err error // valid after done is closed } // requires p.mu is held. func (p *clientConnPool) getStartDialLocked(addr string) *dialCall { if call, ok := p.dialing[addr]; ok { // A dial is already in-flight. Don't start another. return call } call := &dialCall{p: p, done: make(chan struct{})} if p.dialing == nil { p.dialing = make(map[string]*dialCall) } p.dialing[addr] = call go call.dial(addr) return call } // run in its own goroutine. func (c *dialCall) dial(addr string) { const singleUse = false // shared conn c.res, c.err = c.p.t.dialClientConn(addr, singleUse) close(c.done) c.p.mu.Lock() delete(c.p.dialing, addr) if c.err == nil { c.p.addConnLocked(addr, c.res) } c.p.mu.Unlock() } // addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't // already exist. It coalesces concurrent calls with the same key. // This is used by the http1 Transport code when it creates a new connection. Because // the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know // the protocol), it can get into a situation where it has multiple TLS connections. // This code decides which ones live or die. // The return value used is whether c was used. // c is never closed. func (p *clientConnPool) addConnIfNeeded(key string, t *Transport, c *tls.Conn) (used bool, err error) { p.mu.Lock() for _, cc := range p.conns[key] { if cc.CanTakeNewRequest() { p.mu.Unlock() return false, nil } } call, dup := p.addConnCalls[key] if !dup { if p.addConnCalls == nil { p.addConnCalls = make(map[string]*addConnCall) } call = &addConnCall{ p: p, done: make(chan struct{}), } p.addConnCalls[key] = call go call.run(t, key, c) } p.mu.Unlock() <-call.done if call.err != nil { return false, call.err } return !dup, nil } type addConnCall struct { p *clientConnPool done chan struct{} // closed when done err error } func (c *addConnCall) run(t *Transport, key string, tc *tls.Conn) { cc, err := t.NewClientConn(tc) p := c.p p.mu.Lock() if err != nil { c.err = err } else { p.addConnLocked(key, cc) } delete(p.addConnCalls, key) p.mu.Unlock() close(c.done) } func (p *clientConnPool) addConn(key string, cc *ClientConn) { p.mu.Lock() p.addConnLocked(key, cc) p.mu.Unlock() } // p.mu must be held func (p *clientConnPool) addConnLocked(key string, cc *ClientConn) { for _, v := range p.conns[key] { if v == cc { return } } if p.conns == nil { p.conns = make(map[string][]*ClientConn) } if p.keys == nil { p.keys = make(map[*ClientConn][]string) } p.conns[key] = append(p.conns[key], cc) p.keys[cc] = append(p.keys[cc], key) } func (p *clientConnPool) MarkDead(cc *ClientConn) { p.mu.Lock() defer p.mu.Unlock() for _, key := range p.keys[cc] { vv, ok := p.conns[key] if !ok { continue } newList := filterOutClientConn(vv, cc) if len(newList) > 0 { p.conns[key] = newList } else { delete(p.conns, key) } } delete(p.keys, cc) } func (p *clientConnPool) closeIdleConnections() { p.mu.Lock() defer p.mu.Unlock() // TODO: don't close a cc if it was just added to the pool // milliseconds ago and has never been used. There's currently // a small race window with the HTTP/1 Transport's integration // where it can add an idle conn just before using it, and // somebody else can concurrently call CloseIdleConns and // break some caller's RoundTrip. for _, vv := range p.conns { for _, cc := range vv { cc.closeIfIdle() } } } func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn { out := in[:0] for _, v := range in { if v != exclude { out = append(out, v) } } // If we filtered it out, zero out the last item to prevent // the GC from seeing it. if len(in) != len(out) { in[len(in)-1] = nil } return out } // noDialClientConnPool is an implementation of http2.ClientConnPool // which never dials. We let the HTTP/1.1 client dial and use its TLS // connection instead. type noDialClientConnPool struct{ *clientConnPool } func (p noDialClientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { return p.getClientConn(req, addr, noDialOnMiss) } lxd-2.0.11/dist/src/golang.org/x/net/http2/ciphers_test.go0000644061062106075000000003142213172163402024401 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import "testing" func TestIsBadCipherBad(t *testing.T) { for _, c := range badCiphers { if !isBadCipher(c) { t.Errorf("Wrong result for isBadCipher(%d), want true", c) } } } // verify we don't give false positives on ciphers not on blacklist func TestIsBadCipherGood(t *testing.T) { goodCiphers := map[uint16]string{ cipher_TLS_DHE_RSA_WITH_AES_256_CCM: "cipher_TLS_DHE_RSA_WITH_AES_256_CCM", cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM: "cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM", cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: "cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256", } for c, name := range goodCiphers { if isBadCipher(c) { t.Errorf("Wrong result for isBadCipher(%d) %s, want false", c, name) } } } // copied from https://http2.github.io/http2-spec/#BadCipherSuites, var badCiphers = []uint16{ cipher_TLS_NULL_WITH_NULL_NULL, cipher_TLS_RSA_WITH_NULL_MD5, cipher_TLS_RSA_WITH_NULL_SHA, cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5, cipher_TLS_RSA_WITH_RC4_128_MD5, cipher_TLS_RSA_WITH_RC4_128_SHA, cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, cipher_TLS_RSA_WITH_IDEA_CBC_SHA, cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_RSA_WITH_DES_CBC_SHA, cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DH_DSS_WITH_DES_CBC_SHA, cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DH_RSA_WITH_DES_CBC_SHA, cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5, cipher_TLS_DH_anon_WITH_RC4_128_MD5, cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DH_anon_WITH_DES_CBC_SHA, cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA, cipher_TLS_KRB5_WITH_DES_CBC_SHA, cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA, cipher_TLS_KRB5_WITH_RC4_128_SHA, cipher_TLS_KRB5_WITH_IDEA_CBC_SHA, cipher_TLS_KRB5_WITH_DES_CBC_MD5, cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5, cipher_TLS_KRB5_WITH_RC4_128_MD5, cipher_TLS_KRB5_WITH_IDEA_CBC_MD5, cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA, cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA, cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5, cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5, cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5, cipher_TLS_PSK_WITH_NULL_SHA, cipher_TLS_DHE_PSK_WITH_NULL_SHA, cipher_TLS_RSA_PSK_WITH_NULL_SHA, cipher_TLS_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_TLS_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_TLS_RSA_WITH_NULL_SHA256, cipher_TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256, cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256, cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256, cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256, cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_PSK_WITH_RC4_128_SHA, cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA, cipher_TLS_PSK_WITH_AES_128_CBC_SHA, cipher_TLS_PSK_WITH_AES_256_CBC_SHA, cipher_TLS_DHE_PSK_WITH_RC4_128_SHA, cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA, cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA, cipher_TLS_RSA_PSK_WITH_RC4_128_SHA, cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, cipher_TLS_RSA_WITH_SEED_CBC_SHA, cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA, cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA, cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA, cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA, cipher_TLS_DH_anon_WITH_SEED_CBC_SHA, cipher_TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256, cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384, cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256, cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384, cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256, cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384, cipher_TLS_PSK_WITH_AES_128_GCM_SHA256, cipher_TLS_PSK_WITH_AES_256_GCM_SHA384, cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, cipher_TLS_PSK_WITH_AES_128_CBC_SHA256, cipher_TLS_PSK_WITH_AES_256_CBC_SHA384, cipher_TLS_PSK_WITH_NULL_SHA256, cipher_TLS_PSK_WITH_NULL_SHA384, cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, cipher_TLS_DHE_PSK_WITH_NULL_SHA256, cipher_TLS_DHE_PSK_WITH_NULL_SHA384, cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, cipher_TLS_RSA_PSK_WITH_NULL_SHA256, cipher_TLS_RSA_PSK_WITH_NULL_SHA384, cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV, cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_TLS_ECDH_RSA_WITH_NULL_SHA, cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_ECDH_anon_WITH_NULL_SHA, cipher_TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA, cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA, cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA, cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA, cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA, cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA, cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDHE_PSK_WITH_NULL_SHA, cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256, cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384, cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256, cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384, cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256, cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384, cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256, cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384, cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256, cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384, cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256, cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256, cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384, cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_RSA_WITH_AES_128_CCM, cipher_TLS_RSA_WITH_AES_256_CCM, cipher_TLS_RSA_WITH_AES_128_CCM_8, cipher_TLS_RSA_WITH_AES_256_CCM_8, cipher_TLS_PSK_WITH_AES_128_CCM, cipher_TLS_PSK_WITH_AES_256_CCM, cipher_TLS_PSK_WITH_AES_128_CCM_8, cipher_TLS_PSK_WITH_AES_256_CCM_8, } lxd-2.0.11/dist/src/golang.org/x/net/http2/ciphers.go0000644061062106075000000010460713172163402023350 0ustar stgraberdomain admins// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 // A list of the possible cipher suite ids. Taken from // http://www.iana.org/assignments/tls-parameters/tls-parameters.txt const ( cipher_TLS_NULL_WITH_NULL_NULL uint16 = 0x0000 cipher_TLS_RSA_WITH_NULL_MD5 uint16 = 0x0001 cipher_TLS_RSA_WITH_NULL_SHA uint16 = 0x0002 cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0003 cipher_TLS_RSA_WITH_RC4_128_MD5 uint16 = 0x0004 cipher_TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005 cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x0006 cipher_TLS_RSA_WITH_IDEA_CBC_SHA uint16 = 0x0007 cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0008 cipher_TLS_RSA_WITH_DES_CBC_SHA uint16 = 0x0009 cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000A cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000B cipher_TLS_DH_DSS_WITH_DES_CBC_SHA uint16 = 0x000C cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x000D cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000E cipher_TLS_DH_RSA_WITH_DES_CBC_SHA uint16 = 0x000F cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0010 cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0011 cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA uint16 = 0x0012 cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x0013 cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0014 cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA uint16 = 0x0015 cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0016 cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0017 cipher_TLS_DH_anon_WITH_RC4_128_MD5 uint16 = 0x0018 cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0019 cipher_TLS_DH_anon_WITH_DES_CBC_SHA uint16 = 0x001A cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0x001B // Reserved uint16 = 0x001C-1D cipher_TLS_KRB5_WITH_DES_CBC_SHA uint16 = 0x001E cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA uint16 = 0x001F cipher_TLS_KRB5_WITH_RC4_128_SHA uint16 = 0x0020 cipher_TLS_KRB5_WITH_IDEA_CBC_SHA uint16 = 0x0021 cipher_TLS_KRB5_WITH_DES_CBC_MD5 uint16 = 0x0022 cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5 uint16 = 0x0023 cipher_TLS_KRB5_WITH_RC4_128_MD5 uint16 = 0x0024 cipher_TLS_KRB5_WITH_IDEA_CBC_MD5 uint16 = 0x0025 cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA uint16 = 0x0026 cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA uint16 = 0x0027 cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA uint16 = 0x0028 cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 uint16 = 0x0029 cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x002A cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5 uint16 = 0x002B cipher_TLS_PSK_WITH_NULL_SHA uint16 = 0x002C cipher_TLS_DHE_PSK_WITH_NULL_SHA uint16 = 0x002D cipher_TLS_RSA_PSK_WITH_NULL_SHA uint16 = 0x002E cipher_TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002F cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0030 cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0031 cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0032 cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0033 cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA uint16 = 0x0034 cipher_TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035 cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0036 cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0037 cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0038 cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0039 cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA uint16 = 0x003A cipher_TLS_RSA_WITH_NULL_SHA256 uint16 = 0x003B cipher_TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003C cipher_TLS_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x003D cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x003E cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003F cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x0040 cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0041 cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0042 cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0043 cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0044 cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0045 cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0046 // Reserved uint16 = 0x0047-4F // Reserved uint16 = 0x0050-58 // Reserved uint16 = 0x0059-5C // Unassigned uint16 = 0x005D-5F // Reserved uint16 = 0x0060-66 cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x0067 cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x0068 cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x0069 cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x006A cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x006B cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256 uint16 = 0x006C cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256 uint16 = 0x006D // Unassigned uint16 = 0x006E-83 cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0084 cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0085 cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0086 cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0087 cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0088 cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0089 cipher_TLS_PSK_WITH_RC4_128_SHA uint16 = 0x008A cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008B cipher_TLS_PSK_WITH_AES_128_CBC_SHA uint16 = 0x008C cipher_TLS_PSK_WITH_AES_256_CBC_SHA uint16 = 0x008D cipher_TLS_DHE_PSK_WITH_RC4_128_SHA uint16 = 0x008E cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008F cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0090 cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0091 cipher_TLS_RSA_PSK_WITH_RC4_128_SHA uint16 = 0x0092 cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x0093 cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0094 cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0095 cipher_TLS_RSA_WITH_SEED_CBC_SHA uint16 = 0x0096 cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA uint16 = 0x0097 cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA uint16 = 0x0098 cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA uint16 = 0x0099 cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA uint16 = 0x009A cipher_TLS_DH_anon_WITH_SEED_CBC_SHA uint16 = 0x009B cipher_TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009C cipher_TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009D cipher_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009E cipher_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009F cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x00A0 cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x00A1 cipher_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A2 cipher_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A3 cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A4 cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A5 cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256 uint16 = 0x00A6 cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384 uint16 = 0x00A7 cipher_TLS_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00A8 cipher_TLS_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00A9 cipher_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AA cipher_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AB cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AC cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AD cipher_TLS_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00AE cipher_TLS_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00AF cipher_TLS_PSK_WITH_NULL_SHA256 uint16 = 0x00B0 cipher_TLS_PSK_WITH_NULL_SHA384 uint16 = 0x00B1 cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B2 cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B3 cipher_TLS_DHE_PSK_WITH_NULL_SHA256 uint16 = 0x00B4 cipher_TLS_DHE_PSK_WITH_NULL_SHA384 uint16 = 0x00B5 cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B6 cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B7 cipher_TLS_RSA_PSK_WITH_NULL_SHA256 uint16 = 0x00B8 cipher_TLS_RSA_PSK_WITH_NULL_SHA384 uint16 = 0x00B9 cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BA cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BB cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BC cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BD cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BE cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BF cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C0 cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C1 cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C2 cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C3 cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C4 cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C5 // Unassigned uint16 = 0x00C6-FE cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV uint16 = 0x00FF // Unassigned uint16 = 0x01-55,* cipher_TLS_FALLBACK_SCSV uint16 = 0x5600 // Unassigned uint16 = 0x5601 - 0xC000 cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA uint16 = 0xC001 cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA uint16 = 0xC002 cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC003 cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC004 cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC005 cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA uint16 = 0xC006 cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xC007 cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC008 cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC009 cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC00A cipher_TLS_ECDH_RSA_WITH_NULL_SHA uint16 = 0xC00B cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA uint16 = 0xC00C cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC00D cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC00E cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC00F cipher_TLS_ECDHE_RSA_WITH_NULL_SHA uint16 = 0xC010 cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xC011 cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC012 cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC013 cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC014 cipher_TLS_ECDH_anon_WITH_NULL_SHA uint16 = 0xC015 cipher_TLS_ECDH_anon_WITH_RC4_128_SHA uint16 = 0xC016 cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0xC017 cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA uint16 = 0xC018 cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA uint16 = 0xC019 cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01A cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01B cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01C cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA uint16 = 0xC01D cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC01E cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA uint16 = 0xC01F cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA uint16 = 0xC020 cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC021 cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA uint16 = 0xC022 cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC023 cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC024 cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC025 cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC026 cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC027 cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC028 cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC029 cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC02A cipher_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02B cipher_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02C cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02D cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02E cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02F cipher_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC030 cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC031 cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC032 cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA uint16 = 0xC033 cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0xC034 cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0xC035 cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0xC036 cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0xC037 cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0xC038 cipher_TLS_ECDHE_PSK_WITH_NULL_SHA uint16 = 0xC039 cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256 uint16 = 0xC03A cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384 uint16 = 0xC03B cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03C cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03D cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03E cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03F cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC040 cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC041 cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC042 cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC043 cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC044 cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC045 cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC046 cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC047 cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC048 cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC049 cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04A cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04B cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04C cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04D cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04E cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04F cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC050 cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC051 cipher_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC052 cipher_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC053 cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC054 cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC055 cipher_TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC056 cipher_TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC057 cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC058 cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC059 cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05A cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05B cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05C cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05D cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05E cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05F cipher_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC060 cipher_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC061 cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC062 cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC063 cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC064 cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC065 cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC066 cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC067 cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC068 cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC069 cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06A cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06B cipher_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06C cipher_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06D cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06E cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06F cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC070 cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC071 cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC072 cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC073 cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC074 cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC075 cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC076 cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC077 cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC078 cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC079 cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07A cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07B cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07C cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07D cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07E cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07F cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC080 cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC081 cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC082 cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC083 cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC084 cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC085 cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC086 cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC087 cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC088 cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC089 cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08A cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08B cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08C cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08D cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08E cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08F cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC090 cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC091 cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC092 cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC093 cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC094 cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC095 cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC096 cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC097 cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC098 cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC099 cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC09A cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC09B cipher_TLS_RSA_WITH_AES_128_CCM uint16 = 0xC09C cipher_TLS_RSA_WITH_AES_256_CCM uint16 = 0xC09D cipher_TLS_DHE_RSA_WITH_AES_128_CCM uint16 = 0xC09E cipher_TLS_DHE_RSA_WITH_AES_256_CCM uint16 = 0xC09F cipher_TLS_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A0 cipher_TLS_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A1 cipher_TLS_DHE_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A2 cipher_TLS_DHE_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A3 cipher_TLS_PSK_WITH_AES_128_CCM uint16 = 0xC0A4 cipher_TLS_PSK_WITH_AES_256_CCM uint16 = 0xC0A5 cipher_TLS_DHE_PSK_WITH_AES_128_CCM uint16 = 0xC0A6 cipher_TLS_DHE_PSK_WITH_AES_256_CCM uint16 = 0xC0A7 cipher_TLS_PSK_WITH_AES_128_CCM_8 uint16 = 0xC0A8 cipher_TLS_PSK_WITH_AES_256_CCM_8 uint16 = 0xC0A9 cipher_TLS_PSK_DHE_WITH_AES_128_CCM_8 uint16 = 0xC0AA cipher_TLS_PSK_DHE_WITH_AES_256_CCM_8 uint16 = 0xC0AB cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM uint16 = 0xC0AC cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM uint16 = 0xC0AD cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 uint16 = 0xC0AE cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 uint16 = 0xC0AF // Unassigned uint16 = 0xC0B0-FF // Unassigned uint16 = 0xC1-CB,* // Unassigned uint16 = 0xCC00-A7 cipher_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA8 cipher_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA9 cipher_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAA cipher_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAB cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAC cipher_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAD cipher_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAE ) // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec. // References: // https://tools.ietf.org/html/rfc7540#appendix-A // Reject cipher suites from Appendix A. // "This list includes those cipher suites that do not // offer an ephemeral key exchange and those that are // based on the TLS null, stream or block cipher type" func isBadCipher(cipher uint16) bool { switch cipher { case cipher_TLS_NULL_WITH_NULL_NULL, cipher_TLS_RSA_WITH_NULL_MD5, cipher_TLS_RSA_WITH_NULL_SHA, cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5, cipher_TLS_RSA_WITH_RC4_128_MD5, cipher_TLS_RSA_WITH_RC4_128_SHA, cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, cipher_TLS_RSA_WITH_IDEA_CBC_SHA, cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_RSA_WITH_DES_CBC_SHA, cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DH_DSS_WITH_DES_CBC_SHA, cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DH_RSA_WITH_DES_CBC_SHA, cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5, cipher_TLS_DH_anon_WITH_RC4_128_MD5, cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, cipher_TLS_DH_anon_WITH_DES_CBC_SHA, cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA, cipher_TLS_KRB5_WITH_DES_CBC_SHA, cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA, cipher_TLS_KRB5_WITH_RC4_128_SHA, cipher_TLS_KRB5_WITH_IDEA_CBC_SHA, cipher_TLS_KRB5_WITH_DES_CBC_MD5, cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5, cipher_TLS_KRB5_WITH_RC4_128_MD5, cipher_TLS_KRB5_WITH_IDEA_CBC_MD5, cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA, cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA, cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5, cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5, cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5, cipher_TLS_PSK_WITH_NULL_SHA, cipher_TLS_DHE_PSK_WITH_NULL_SHA, cipher_TLS_RSA_PSK_WITH_NULL_SHA, cipher_TLS_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_TLS_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_TLS_RSA_WITH_NULL_SHA256, cipher_TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256, cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA, cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256, cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256, cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256, cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA, cipher_TLS_PSK_WITH_RC4_128_SHA, cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA, cipher_TLS_PSK_WITH_AES_128_CBC_SHA, cipher_TLS_PSK_WITH_AES_256_CBC_SHA, cipher_TLS_DHE_PSK_WITH_RC4_128_SHA, cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA, cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA, cipher_TLS_RSA_PSK_WITH_RC4_128_SHA, cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, cipher_TLS_RSA_WITH_SEED_CBC_SHA, cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA, cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA, cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA, cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA, cipher_TLS_DH_anon_WITH_SEED_CBC_SHA, cipher_TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256, cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384, cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256, cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384, cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256, cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384, cipher_TLS_PSK_WITH_AES_128_GCM_SHA256, cipher_TLS_PSK_WITH_AES_256_GCM_SHA384, cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, cipher_TLS_PSK_WITH_AES_128_CBC_SHA256, cipher_TLS_PSK_WITH_AES_256_CBC_SHA384, cipher_TLS_PSK_WITH_NULL_SHA256, cipher_TLS_PSK_WITH_NULL_SHA384, cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, cipher_TLS_DHE_PSK_WITH_NULL_SHA256, cipher_TLS_DHE_PSK_WITH_NULL_SHA384, cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, cipher_TLS_RSA_PSK_WITH_NULL_SHA256, cipher_TLS_RSA_PSK_WITH_NULL_SHA384, cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256, cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV, cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_TLS_ECDH_RSA_WITH_NULL_SHA, cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_ECDH_anon_WITH_NULL_SHA, cipher_TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA, cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA, cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA, cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA, cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA, cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA, cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA, cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA, cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA, cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, cipher_TLS_ECDHE_PSK_WITH_NULL_SHA, cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256, cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384, cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256, cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384, cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256, cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384, cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256, cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384, cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256, cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384, cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256, cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384, cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256, cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384, cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, cipher_TLS_RSA_WITH_AES_128_CCM, cipher_TLS_RSA_WITH_AES_256_CCM, cipher_TLS_RSA_WITH_AES_128_CCM_8, cipher_TLS_RSA_WITH_AES_256_CCM_8, cipher_TLS_PSK_WITH_AES_128_CCM, cipher_TLS_PSK_WITH_AES_256_CCM, cipher_TLS_PSK_WITH_AES_128_CCM_8, cipher_TLS_PSK_WITH_AES_256_CCM_8: return true default: return false } } lxd-2.0.11/dist/src/golang.org/x/net/http2/README0000644061062106075000000000116213172163402022234 0ustar stgraberdomain adminsThis is a work-in-progress HTTP/2 implementation for Go. It will eventually live in the Go standard library and won't require any changes to your code to use. It will just be automatic. Status: * The server support is pretty good. A few things are missing but are being worked on. * The client work has just started but shares a lot of code is coming along much quicker. Docs are at https://godoc.org/golang.org/x/net/http2 Demo test server at https://http2.golang.org/ Help & bug reports welcome! Contributing: https://golang.org/doc/contribute.html Bugs: https://golang.org/issue/new?title=x/net/http2:+ lxd-2.0.11/dist/src/golang.org/x/net/http2/Makefile0000644061062106075000000000005413172163402023013 0ustar stgraberdomain adminscurlimage: docker build -t gohttp2/curl . lxd-2.0.11/dist/src/golang.org/x/net/http2/Dockerfile0000644061062106075000000000272213172163402023351 0ustar stgraberdomain admins# # This Dockerfile builds a recent curl with HTTP/2 client support, using # a recent nghttp2 build. # # See the Makefile for how to tag it. If Docker and that image is found, the # Go tests use this curl binary for integration tests. # FROM ubuntu:trusty RUN apt-get update && \ apt-get upgrade -y && \ apt-get install -y git-core build-essential wget RUN apt-get install -y --no-install-recommends \ autotools-dev libtool pkg-config zlib1g-dev \ libcunit1-dev libssl-dev libxml2-dev libevent-dev \ automake autoconf # The list of packages nghttp2 recommends for h2load: RUN apt-get install -y --no-install-recommends make binutils \ autoconf automake autotools-dev \ libtool pkg-config zlib1g-dev libcunit1-dev libssl-dev libxml2-dev \ libev-dev libevent-dev libjansson-dev libjemalloc-dev \ cython python3.4-dev python-setuptools # Note: setting NGHTTP2_VER before the git clone, so an old git clone isn't cached: ENV NGHTTP2_VER 895da9a RUN cd /root && git clone https://github.com/tatsuhiro-t/nghttp2.git WORKDIR /root/nghttp2 RUN git reset --hard $NGHTTP2_VER RUN autoreconf -i RUN automake RUN autoconf RUN ./configure RUN make RUN make install WORKDIR /root RUN wget http://curl.haxx.se/download/curl-7.45.0.tar.gz RUN tar -zxvf curl-7.45.0.tar.gz WORKDIR /root/curl-7.45.0 RUN ./configure --with-ssl --with-nghttp2=/usr/local RUN make RUN make install RUN ldconfig CMD ["-h"] ENTRYPOINT ["/usr/local/bin/curl"] lxd-2.0.11/dist/src/golang.org/x/net/html/0000755061062106075000000000000013172163402021257 5ustar stgraberdomain adminslxd-2.0.11/dist/src/golang.org/x/net/html/token_test.go0000644061062106075000000003445313172163402023776 0ustar stgraberdomain admins// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "bytes" "io" "io/ioutil" "reflect" "runtime" "strings" "testing" ) type tokenTest struct { // A short description of the test case. desc string // The HTML to parse. html string // The string representations of the expected tokens, joined by '$'. golden string } var tokenTests = []tokenTest{ { "empty", "", "", }, // A single text node. The tokenizer should not break text nodes on whitespace, // nor should it normalize whitespace within a text node. { "text", "foo bar", "foo bar", }, // An entity. { "entity", "one < two", "one < two", }, // A start, self-closing and end tag. The tokenizer does not care if the start // and end tokens don't match; that is the job of the parser. { "tags", "bd", "$b$$d$", }, // Angle brackets that aren't a tag. { "not a tag #0", "<", "<", }, { "not a tag #1", "", "", }, { "not a tag #3", "ab", "a$$b", }, { "not a tag #4", "", "", }, { "not a tag #5", "", }, { "not a tag #6", "", "", }, { "not a tag #7", "a < b", "a < b", }, { "not a tag #8", "<.>", "<.>", }, { "not a tag #9", "a<<>>c", "a<<$$>>c", }, { "not a tag #10", "if x<0 and y < 0 then x*y>0", "if x<0 and y < 0 then x*y>0", }, { "not a tag #11", "<

", "<$

", }, // EOF in a tag name. { "tag name eof #0", "", }, { "tag name eof #4", `'. { "malformed tag #0", ``, ``, }, { "malformed tag #1", `

`, `

`, }, { "malformed tag #2", `

`, `

`, }, { "malformed tag #5", `

`, `

`, }, { "malformed tag #7", `

`, `

`, }, { "malformed tag #9", `

`, }, // Raw text and RCDATA. { "basic raw text", "", "", }, { "unfinished script end tag", "$a", }, { "'>' completes script end tag", "", "", }, { "self-closing script end tag", "", "", }, { "nested script tag", "", "", }, { "script/style mismatched tags", "" that closes the next token. If // non-empty, the subsequent call to Next will return a raw or RCDATA text // token: one that treats "

" as text instead of an element. // rawTag's contents are lower-cased. rawTag string // textIsRaw is whether the current text token's data is not escaped. textIsRaw bool // convertNUL is whether NUL bytes in the current token's data should // be converted into \ufffd replacement characters. convertNUL bool // allowCDATA is whether CDATA sections are allowed in the current context. allowCDATA bool } // AllowCDATA sets whether or not the tokenizer recognizes as // the text "foo". The default value is false, which means to recognize it as // a bogus comment "" instead. // // Strictly speaking, an HTML5 compliant tokenizer should allow CDATA if and // only if tokenizing foreign content, such as MathML and SVG. However, // tracking foreign-contentness is difficult to do purely in the tokenizer, // as opposed to the parser, due to HTML integration points: an element // can contain a that is foreign-to-SVG but not foreign-to- // HTML. For strict compliance with the HTML5 tokenization algorithm, it is the // responsibility of the user of a tokenizer to call AllowCDATA as appropriate. // In practice, if using the tokenizer without caring whether MathML or SVG // CDATA is text or comments, such as tokenizing HTML to find all the anchor // text, it is acceptable to ignore this responsibility. func (z *Tokenizer) AllowCDATA(allowCDATA bool) { z.allowCDATA = allowCDATA } // NextIsNotRawText instructs the tokenizer that the next token should not be // considered as 'raw text'. Some elements, such as script and title elements, // normally require the next token after the opening tag to be 'raw text' that // has no child elements. For example, tokenizing "a<b>c</b>d" // yields a start tag token for "", a text token for "a<b>c</b>d", and // an end tag token for "". There are no distinct start tag or end tag // tokens for the "" and "". // // This tokenizer implementation will generally look for raw text at the right // times. Strictly speaking, an HTML5 compliant tokenizer should not look for // raw text if in foreign content: generally needs raw text, but a // <title> inside an <svg> does not. Another example is that a <textarea> // generally needs raw text, but a <textarea> is not allowed as an immediate // child of a <select>; in normal parsing, a <textarea> implies </select>, but // one cannot close the implicit element when parsing a <select>'s InnerHTML. // Similarly to AllowCDATA, tracking the correct moment to override raw-text- // ness is difficult to do purely in the tokenizer, as opposed to the parser. // For strict compliance with the HTML5 tokenization algorithm, it is the // responsibility of the user of a tokenizer to call NextIsNotRawText as // appropriate. In practice, like AllowCDATA, it is acceptable to ignore this // responsibility for basic usage. // // Note that this 'raw text' concept is different from the one offered by the // Tokenizer.Raw method. func (z *Tokenizer) NextIsNotRawText() { z.rawTag = "" } // Err returns the error associated with the most recent ErrorToken token. // This is typically io.EOF, meaning the end of tokenization. func (z *Tokenizer) Err() error { if z.tt != ErrorToken { return nil } return z.err } // readByte returns the next byte from the input stream, doing a buffered read // from z.r into z.buf if necessary. z.buf[z.raw.start:z.raw.end] remains a contiguous byte // slice that holds all the bytes read so far for the current token. // It sets z.err if the underlying reader returns an error. // Pre-condition: z.err == nil. func (z *Tokenizer) readByte() byte { if z.raw.end >= len(z.buf) { // Our buffer is exhausted and we have to read from z.r. Check if the // previous read resulted in an error. if z.readErr != nil { z.err = z.readErr return 0 } // We copy z.buf[z.raw.start:z.raw.end] to the beginning of z.buf. If the length // z.raw.end - z.raw.start is more than half the capacity of z.buf, then we // allocate a new buffer before the copy. c := cap(z.buf) d := z.raw.end - z.raw.start var buf1 []byte if 2*d > c { buf1 = make([]byte, d, 2*c) } else { buf1 = z.buf[:d] } copy(buf1, z.buf[z.raw.start:z.raw.end]) if x := z.raw.start; x != 0 { // Adjust the data/attr spans to refer to the same contents after the copy. z.data.start -= x z.data.end -= x z.pendingAttr[0].start -= x z.pendingAttr[0].end -= x z.pendingAttr[1].start -= x z.pendingAttr[1].end -= x for i := range z.attr { z.attr[i][0].start -= x z.attr[i][0].end -= x z.attr[i][1].start -= x z.attr[i][1].end -= x } } z.raw.start, z.raw.end, z.buf = 0, d, buf1[:d] // Now that we have copied the live bytes to the start of the buffer, // we read from z.r into the remainder. var n int n, z.readErr = readAtLeastOneByte(z.r, buf1[d:cap(buf1)]) if n == 0 { z.err = z.readErr return 0 } z.buf = buf1[:d+n] } x := z.buf[z.raw.end] z.raw.end++ if z.maxBuf > 0 && z.raw.end-z.raw.start >= z.maxBuf { z.err = ErrBufferExceeded return 0 } return x } // Buffered returns a slice containing data buffered but not yet tokenized. func (z *Tokenizer) Buffered() []byte { return z.buf[z.raw.end:] } // readAtLeastOneByte wraps an io.Reader so that reading cannot return (0, nil). // It returns io.ErrNoProgress if the underlying r.Read method returns (0, nil) // too many times in succession. func readAtLeastOneByte(r io.Reader, b []byte) (int, error) { for i := 0; i < 100; i++ { n, err := r.Read(b) if n != 0 || err != nil { return n, err } } return 0, io.ErrNoProgress } // skipWhiteSpace skips past any white space. func (z *Tokenizer) skipWhiteSpace() { if z.err != nil { return } for { c := z.readByte() if z.err != nil { return } switch c { case ' ', '\n', '\r', '\t', '\f': // No-op. default: z.raw.end-- return } } } // readRawOrRCDATA reads until the next "</foo>", where "foo" is z.rawTag and // is typically something like "script" or "textarea". func (z *Tokenizer) readRawOrRCDATA() { if z.rawTag == "script" { z.readScript() z.textIsRaw = true z.rawTag = "" return } loop: for { c := z.readByte() if z.err != nil { break loop } if c != '<' { continue loop } c = z.readByte() if z.err != nil { break loop } if c != '/' { continue loop } if z.readRawEndTag() || z.err != nil { break loop } } z.data.end = z.raw.end // A textarea's or title's RCDATA can contain escaped entities. z.textIsRaw = z.rawTag != "textarea" && z.rawTag != "title" z.rawTag = "" } // readRawEndTag attempts to read a tag like "</foo>", where "foo" is z.rawTag. // If it succeeds, it backs up the input position to reconsume the tag and // returns true. Otherwise it returns false. The opening "</" has already been // consumed. func (z *Tokenizer) readRawEndTag() bool { for i := 0; i < len(z.rawTag); i++ { c := z.readByte() if z.err != nil { return false } if c != z.rawTag[i] && c != z.rawTag[i]-('a'-'A') { z.raw.end-- return false } } c := z.readByte() if z.err != nil { return false } switch c { case ' ', '\n', '\r', '\t', '\f', '/', '>': // The 3 is 2 for the leading "</" plus 1 for the trailing character c. z.raw.end -= 3 + len(z.rawTag) return true } z.raw.end-- return false } // readScript reads until the next </script> tag, following the byzantine // rules for escaping/hiding the closing tag. func (z *Tokenizer) readScript() { defer func() { z.data.end = z.raw.end }() var c byte scriptData: c = z.readByte() if z.err != nil { return } if c == '<' { goto scriptDataLessThanSign } goto scriptData scriptDataLessThanSign: c = z.readByte() if z.err != nil { return } switch c { case '/': goto scriptDataEndTagOpen case '!': goto scriptDataEscapeStart } z.raw.end-- goto scriptData scriptDataEndTagOpen: if z.readRawEndTag() || z.err != nil { return } goto scriptData scriptDataEscapeStart: c = z.readByte() if z.err != nil { return } if c == '-' { goto scriptDataEscapeStartDash } z.raw.end-- goto scriptData scriptDataEscapeStartDash: c = z.readByte() if z.err != nil { return } if c == '-' { goto scriptDataEscapedDashDash } z.raw.end-- goto scriptData scriptDataEscaped: c = z.readByte() if z.err != nil { return } switch c { case '-': goto scriptDataEscapedDash case '<': goto scriptDataEscapedLessThanSign } goto scriptDataEscaped scriptDataEscapedDash: c = z.readByte() if z.err != nil { return } switch c { case '-': goto scriptDataEscapedDashDash case '<': goto scriptDataEscapedLessThanSign } goto scriptDataEscaped scriptDataEscapedDashDash: c = z.readByte() if z.err != nil { return } switch c { case '-': goto scriptDataEscapedDashDash case '<': goto scriptDataEscapedLessThanSign case '>': goto scriptData } goto scriptDataEscaped scriptDataEscapedLessThanSign: c = z.readByte() if z.err != nil { return } if c == '/' { goto scriptDataEscapedEndTagOpen } if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' { goto scriptDataDoubleEscapeStart } z.raw.end-- goto scriptData scriptDataEscapedEndTagOpen: if z.readRawEndTag() || z.err != nil { return } goto scriptDataEscaped scriptDataDoubleEscapeStart: z.raw.end-- for i := 0; i < len("script"); i++ { c = z.readByte() if z.err != nil { return } if c != "script"[i] && c != "SCRIPT"[i] { z.raw.end-- goto scriptDataEscaped } } c = z.readByte() if z.err != nil { return } switch c { case ' ', '\n', '\r', '\t', '\f', '/', '>': goto scriptDataDoubleEscaped } z.raw.end-- goto scriptDataEscaped scriptDataDoubleEscaped: c = z.readByte() if z.err != nil { return } switch c { case '-': goto scriptDataDoubleEscapedDash case '<': goto scriptDataDoubleEscapedLessThanSign } goto scriptDataDoubleEscaped scriptDataDoubleEscapedDash: c = z.readByte() if z.err != nil { return } switch c { case '-': goto scriptDataDoubleEscapedDashDash case '<': goto scriptDataDoubleEscapedLessThanSign } goto scriptDataDoubleEscaped scriptDataDoubleEscapedDashDash: c = z.readByte() if z.err != nil { return } switch c { case '-': goto scriptDataDoubleEscapedDashDash case '<': goto scriptDataDoubleEscapedLessThanSign case '>': goto scriptData } goto scriptDataDoubleEscaped scriptDataDoubleEscapedLessThanSign: c = z.readByte() if z.err != nil { return } if c == '/' { goto scriptDataDoubleEscapeEnd } z.raw.end-- goto scriptDataDoubleEscaped scriptDataDoubleEscapeEnd: if z.readRawEndTag() { z.raw.end += len("</script>") goto scriptDataEscaped } if z.err != nil { return } goto scriptDataDoubleEscaped } // readComment reads the next comment token starting with "<!--". The opening // "<!--" has already been consumed. func (z *Tokenizer) readComment() { z.data.start = z.raw.end defer func() { if z.data.end < z.data.start { // It's a comment with no data, like <!-->. z.data.end = z.data.start } }() for dashCount := 2; ; { c := z.readByte() if z.err != nil { // Ignore up to two dashes at EOF. if dashCount > 2 { dashCount = 2 } z.data.end = z.raw.end - dashCount return } switch c { case '-': dashCount++ continue case '>': if dashCount >= 2 { z.data.end = z.raw.end - len("-->") return } case '!': if dashCount >= 2 { c = z.readByte() if z.err != nil { z.data.end = z.raw.end return } if c == '>' { z.data.end = z.raw.end - len("--!>") return } } } dashCount = 0 } } // readUntilCloseAngle reads until the next ">". func (z *Tokenizer) readUntilCloseAngle() { z.data.start = z.raw.end for { c := z.readByte() if z.err != nil { z.data.end = z.raw.end return } if c == '>' { z.data.end = z.raw.end - len(">") return } } } // readMarkupDeclaration reads the next token starting with "<!". It might be // a "<!--comment-->", a "<!DOCTYPE foo>", a "<![CDATA[section]]>" or // "<!a bogus comment". The opening "<!" has already been consumed. func (z *Tokenizer) readMarkupDeclaration() TokenType { z.data.start = z.raw.end var c [2]byte for i := 0; i < 2; i++ { c[i] = z.readByte() if z.err != nil { z.data.end = z.raw.end return CommentToken } } if c[0] == '-' && c[1] == '-' { z.readComment() return CommentToken } z.raw.end -= 2 if z.readDoctype() { return DoctypeToken } if z.allowCDATA && z.readCDATA() { z.convertNUL = true return TextToken } // It's a bogus comment. z.readUntilCloseAngle() return CommentToken } // readDoctype attempts to read a doctype declaration and returns true if // successful. The opening "<!" has already been consumed. func (z *Tokenizer) readDoctype() bool { const s = "DOCTYPE" for i := 0; i < len(s); i++ { c := z.readByte() if z.err != nil { z.data.end = z.raw.end return false } if c != s[i] && c != s[i]+('a'-'A') { // Back up to read the fragment of "DOCTYPE" again. z.raw.end = z.data.start return false } } if z.skipWhiteSpace(); z.err != nil { z.data.start = z.raw.end z.data.end = z.raw.end return true } z.readUntilCloseAngle() return true } // readCDATA attempts to read a CDATA section and returns true if // successful. The opening "<!" has already been consumed. func (z *Tokenizer) readCDATA() bool { const s = "[CDATA[" for i := 0; i < len(s); i++ { c := z.readByte() if z.err != nil { z.data.end = z.raw.end return false } if c != s[i] { // Back up to read the fragment of "[CDATA[" again. z.raw.end = z.data.start return false } } z.data.start = z.raw.end brackets := 0 for { c := z.readByte() if z.err != nil { z.data.end = z.raw.end return true } switch c { case ']': brackets++ case '>': if brackets >= 2 { z.data.end = z.raw.end - len("]]>") return true } brackets = 0 default: brackets = 0 } } } // startTagIn returns whether the start tag in z.buf[z.data.start:z.data.end] // case-insensitively matches any element of ss. func (z *Tokenizer) startTagIn(ss ...string) bool { loop: for _, s := range ss { if z.data.end-z.data.start != len(s) { continue loop } for i := 0; i < len(s); i++ { c := z.buf[z.data.start+i] if 'A' <= c && c <= 'Z' { c += 'a' - 'A' } if c != s[i] { continue loop } } return true } return false } // readStartTag reads the next start tag token. The opening "<a" has already // been consumed, where 'a' means anything in [A-Za-z]. func (z *Tokenizer) readStartTag() TokenType { z.readTag(true) if z.err != nil { return ErrorToken } // Several tags flag the tokenizer's next token as raw. c, raw := z.buf[z.data.start], false if 'A' <= c && c <= 'Z' { c += 'a' - 'A' } switch c { case 'i': raw = z.startTagIn("iframe") case 'n': raw = z.startTagIn("noembed", "noframes", "noscript") case 'p': raw = z.startTagIn("plaintext") case 's': raw = z.startTagIn("script", "style") case 't': raw = z.startTagIn("textarea", "title") case 'x': raw = z.startTagIn("xmp") } if raw { z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end])) } // Look for a self-closing token like "<br/>". if z.err == nil && z.buf[z.raw.end-2] == '/' { return SelfClosingTagToken } return StartTagToken } // readTag reads the next tag token and its attributes. If saveAttr, those // attributes are saved in z.attr, otherwise z.attr is set to an empty slice. // The opening "<a" or "</a" has already been consumed, where 'a' means anything // in [A-Za-z]. func (z *Tokenizer) readTag(saveAttr bool) { z.attr = z.attr[:0] z.nAttrReturned = 0 // Read the tag name and attribute key/value pairs. z.readTagName() if z.skipWhiteSpace(); z.err != nil { return } for { c := z.readByte() if z.err != nil || c == '>' { break } z.raw.end-- z.readTagAttrKey() z.readTagAttrVal() // Save pendingAttr if saveAttr and that attribute has a non-empty key. if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end { z.attr = append(z.attr, z.pendingAttr) } if z.skipWhiteSpace(); z.err != nil { break } } } // readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end) // is positioned such that the first byte of the tag name (the "d" in "<div") // has already been consumed. func (z *Tokenizer) readTagName() { z.data.start = z.raw.end - 1 for { c := z.readByte() if z.err != nil { z.data.end = z.raw.end return } switch c { case ' ', '\n', '\r', '\t', '\f': z.data.end = z.raw.end - 1 return case '/', '>': z.raw.end-- z.data.end = z.raw.end return } } } // readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>". // Precondition: z.err == nil. func (z *Tokenizer) readTagAttrKey() { z.pendingAttr[0].start = z.raw.end for { c := z.readByte() if z.err != nil { z.pendingAttr[0].end = z.raw.end return } switch c { case ' ', '\n', '\r', '\t', '\f', '/': z.pendingAttr[0].end = z.raw.end - 1 return case '=', '>': z.raw.end-- z.pendingAttr[0].end = z.raw.end return } } } // readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>". func (z *Tokenizer) readTagAttrVal() { z.pendingAttr[1].start = z.raw.end z.pendingAttr[1].end = z.raw.end if z.skipWhiteSpace(); z.err != nil { return } c := z.readByte() if z.err != nil { return } if c != '=' { z.raw.end-- return } if z.skipWhiteSpace(); z.err != nil { return } quote := z.readByte() if z.err != nil { return } switch quote { case '>': z.raw.end-- return case '\'', '"': z.pendingAttr[1].start = z.raw.end for { c := z.readByte() if z.err != nil { z.pendingAttr[1].end = z.raw.end return } if c == quote { z.pendingAttr[1].end = z.raw.end - 1 return } } default: z.pendingAttr[1].start = z.raw.end - 1 for { c := z.readByte() if z.err != nil { z.pendingAttr[1].end = z.raw.end return } switch c { case ' ', '\n', '\r', '\t', '\f': z.pendingAttr[1].end = z.raw.end - 1 return case '>': z.raw.end-- z.pendingAttr[1].end = z.raw.end return } } } } // Next scans the next token and returns its type. func (z *Tokenizer) Next() TokenType { z.raw.start = z.raw.end z.data.start = z.raw.end z.data.end = z.raw.end if z.err != nil { z.tt = ErrorToken return z.tt } if z.rawTag != "" { if z.rawTag == "plaintext" { // Read everything up to EOF. for z.err == nil { z.readByte() } z.data.end = z.raw.end z.textIsRaw = true } else { z.readRawOrRCDATA() } if z.data.end > z.data.start { z.tt = TextToken z.convertNUL = true return z.tt } } z.textIsRaw = false z.convertNUL = false loop: for { c := z.readByte() if z.err != nil { break loop } if c != '<' { continue loop } // Check if the '<' we have just read is part of a tag, comment // or doctype. If not, it's part of the accumulated text token. c = z.readByte() if z.err != nil { break loop } var tokenType TokenType switch { case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': tokenType = StartTagToken case c == '/': tokenType = EndTagToken case c == '!' || c == '?': // We use CommentToken to mean any of "<!--actual comments-->", // "<!DOCTYPE declarations>" and "<?xml processing instructions?>". tokenType = CommentToken default: // Reconsume the current character. z.raw.end-- continue } // We have a non-text token, but we might have accumulated some text // before that. If so, we return the text first, and return the non- // text token on the subsequent call to Next. if x := z.raw.end - len("<a"); z.raw.start < x { z.raw.end = x z.data.end = x z.tt = TextToken return z.tt } switch tokenType { case StartTagToken: z.tt = z.readStartTag() return z.tt case EndTagToken: c = z.readByte() if z.err != nil { break loop } if c == '>' { // "</>" does not generate a token at all. Generate an empty comment // to allow passthrough clients to pick up the data using Raw. // Reset the tokenizer state and start again. z.tt = CommentToken return z.tt } if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' { z.readTag(false) if z.err != nil { z.tt = ErrorToken } else { z.tt = EndTagToken } return z.tt } z.raw.end-- z.readUntilCloseAngle() z.tt = CommentToken return z.tt case CommentToken: if c == '!' { z.tt = z.readMarkupDeclaration() return z.tt } z.raw.end-- z.readUntilCloseAngle() z.tt = CommentToken return z.tt } } if z.raw.start < z.raw.end { z.data.end = z.raw.end z.tt = TextToken return z.tt } z.tt = ErrorToken return z.tt } // Raw returns the unmodified text of the current token. Calling Next, Token, // Text, TagName or TagAttr may change the contents of the returned slice. func (z *Tokenizer) Raw() []byte { return z.buf[z.raw.start:z.raw.end] } // convertNewlines converts "\r" and "\r\n" in s to "\n". // The conversion happens in place, but the resulting slice may be shorter. func convertNewlines(s []byte) []byte { for i, c := range s { if c != '\r' { continue } src := i + 1 if src >= len(s) || s[src] != '\n' { s[i] = '\n' continue } dst := i for src < len(s) { if s[src] == '\r' { if src+1 < len(s) && s[src+1] == '\n' { src++ } s[dst] = '\n' } else { s[dst] = s[src] } src++ dst++ } return s[:dst] } return s } var ( nul = []byte("\x00") replacement = []byte("\ufffd") ) // Text returns the unescaped text of a text, comment or doctype token. The // contents of the returned slice may change on the next call to Next. func (z *Tokenizer) Text() []byte { switch z.tt { case TextToken, CommentToken, DoctypeToken: s := z.buf[z.data.start:z.data.end] z.data.start = z.raw.end z.data.end = z.raw.end s = convertNewlines(s) if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) { s = bytes.Replace(s, nul, replacement, -1) } if !z.textIsRaw { s = unescape(s, false) } return s } return nil } // TagName returns the lower-cased name of a tag token (the `img` out of // `<IMG SRC="foo">`) and whether the tag has attributes. // The contents of the returned slice may change on the next call to Next. func (z *Tokenizer) TagName() (name []byte, hasAttr bool) { if z.data.start < z.data.end { switch z.tt { case StartTagToken, EndTagToken, SelfClosingTagToken: s := z.buf[z.data.start:z.data.end] z.data.start = z.raw.end z.data.end = z.raw.end return lower(s), z.nAttrReturned < len(z.attr) } } return nil, false } // TagAttr returns the lower-cased key and unescaped value of the next unparsed // attribute for the current tag token and whether there are more attributes. // The contents of the returned slices may change on the next call to Next. func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) { if z.nAttrReturned < len(z.attr) { switch z.tt { case StartTagToken, SelfClosingTagToken: x := z.attr[z.nAttrReturned] z.nAttrReturned++ key = z.buf[x[0].start:x[0].end] val = z.buf[x[1].start:x[1].end] return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr) } } return nil, nil, false } // Token returns the next Token. The result's Data and Attr values remain valid // after subsequent Next calls. func (z *Tokenizer) Token() Token { t := Token{Type: z.tt} switch z.tt { case TextToken, CommentToken, DoctypeToken: t.Data = string(z.Text()) case StartTagToken, SelfClosingTagToken, EndTagToken: name, moreAttr := z.TagName() for moreAttr { var key, val []byte key, val, moreAttr = z.TagAttr() t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)}) } if a := atom.Lookup(name); a != 0 { t.DataAtom, t.Data = a, a.String() } else { t.DataAtom, t.Data = 0, string(name) } } return t } // SetMaxBuf sets a limit on the amount of data buffered during tokenization. // A value of 0 means unlimited. func (z *Tokenizer) SetMaxBuf(n int) { z.maxBuf = n } // NewTokenizer returns a new HTML Tokenizer for the given Reader. // The input is assumed to be UTF-8 encoded. func NewTokenizer(r io.Reader) *Tokenizer { return NewTokenizerFragment(r, "") } // NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for // tokenizing an existing element's InnerHTML fragment. contextTag is that // element's tag, such as "div" or "iframe". // // For example, how the InnerHTML "a<b" is tokenized depends on whether it is // for a <p> tag or a <script> tag. // // The input is assumed to be UTF-8 encoded. func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer { z := &Tokenizer{ r: r, buf: make([]byte, 0, 4096), } if contextTag != "" { switch s := strings.ToLower(contextTag); s { case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp": z.rawTag = s } } return z } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/testdata/�������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�023070� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/testdata/webkit/������������������������������������������0000755�0610621�0607500�00000000000�13172163402�024355� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/testdata/webkit/webkit02.dat������������������������������0000644�0610621�0607500�00000004322�13172163402�026477� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#data <foo bar=qux/> #errors #document | <html> | <head> | <body> | <foo> | bar="qux/" #data <p id="status"><noscript><strong>A</strong></noscript><span>B</span></p> #errors #document | <html> | <head> | <body> | <p> | id="status" | <noscript> | "<strong>A</strong>" | <span> | "B" #data <div><sarcasm><div></div></sarcasm></div> #errors #document | <html> | <head> | <body> | <div> | <sarcasm> | <div> #data <html><body><img src="" border="0" alt="><div>A</div></body></html> #errors #document | <html> | <head> | <body> #data <table><td></tbody>A #errors #document | <html> | <head> | <body> | "A" | <table> | <tbody> | <tr> | <td> #data <table><td></thead>A #errors #document | <html> | <head> | <body> | <table> | <tbody> | <tr> | <td> | "A" #data <table><td></tfoot>A #errors #document | <html> | <head> | <body> | <table> | <tbody> | <tr> | <td> | "A" #data <table><thead><td></tbody>A #errors #document | <html> | <head> | <body> | <table> | <thead> | <tr> | <td> | "A" #data <legend>test</legend> #errors #document | <html> | <head> | <body> | <legend> | "test" #data <table><input> #errors #document | <html> | <head> | <body> | <input> | <table> #data <b><em><dcell><postfield><postfield><postfield><postfield><missing_glyph><missing_glyph><missing_glyph><missing_glyph><hkern><aside></b></em> #errors #document-fragment div #document | <b> | <em> | <dcell> | <postfield> | <postfield> | <postfield> | <postfield> | <missing_glyph> | <missing_glyph> | <missing_glyph> | <missing_glyph> | <hkern> | <aside> | <em> | <b> #data <isindex action="x"> #errors #document-fragment table #document | <form> | action="x" | <hr> | <label> | "This is a searchable index. Enter search keywords: " | <input> | name="isindex" | <hr> #data <option><XH<optgroup></optgroup> #errors #document-fragment select #document | <option> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/testdata/webkit/webkit01.dat������������������������������0000644�0610621�0607500�00000017347�13172163402�026511� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#data Test #errors Line: 1 Col: 4 Unexpected non-space characters. Expected DOCTYPE. #document | <html> | <head> | <body> | "Test" #data <div></div> #errors #document | <html> | <head> | <body> | <div> #data <div>Test</div> #errors #document | <html> | <head> | <body> | <div> | "Test" #data <di #errors #document | <html> | <head> | <body> #data <div>Hello</div> <script> console.log("PASS"); </script> <div>Bye</div> #errors #document | <html> | <head> | <body> | <div> | "Hello" | " " | <script> | " console.log("PASS"); " | " " | <div> | "Bye" #data <div foo="bar">Hello</div> #errors #document | <html> | <head> | <body> | <div> | foo="bar" | "Hello" #data <div>Hello</div> <script> console.log("FOO<span>BAR</span>BAZ"); </script> <div>Bye</div> #errors #document | <html> | <head> | <body> | <div> | "Hello" | " " | <script> | " console.log("FOO<span>BAR</span>BAZ"); " | " " | <div> | "Bye" #data <foo bar="baz"></foo><potato quack="duck"></potato> #errors #document | <html> | <head> | <body> | <foo> | bar="baz" | <potato> | quack="duck" #data <foo bar="baz"><potato quack="duck"></potato></foo> #errors #document | <html> | <head> | <body> | <foo> | bar="baz" | <potato> | quack="duck" #data <foo></foo bar="baz"><potato></potato quack="duck"> #errors #document | <html> | <head> | <body> | <foo> | <potato> #data </ tttt> #errors #document | <!-- tttt --> | <html> | <head> | <body> #data <div FOO ><img><img></div> #errors #document | <html> | <head> | <body> | <div> | foo="" | <img> | <img> #data <p>Test</p<p>Test2</p> #errors #document | <html> | <head> | <body> | <p> | "TestTest2" #data <rdar://problem/6869687> #errors #document | <html> | <head> | <body> | <rdar:> | 6869687="" | problem="" #data <A>test< /A> #errors #document | <html> | <head> | <body> | <a> | "test< /A>" #data < #errors #document | <html> | <head> | <body> | "<" #data <body foo='bar'><body foo='baz' yo='mama'> #errors #document | <html> | <head> | <body> | foo="bar" | yo="mama" #data <body></br foo="bar"></body> #errors #document | <html> | <head> | <body> | <br> #data <bdy><br foo="bar"></body> #errors #document | <html> | <head> | <body> | <bdy> | <br> | foo="bar" #data <body></body></br foo="bar"> #errors #document | <html> | <head> | <body> | <br> #data <bdy></body><br foo="bar"> #errors #document | <html> | <head> | <body> | <bdy> | <br> | foo="bar" #data <html><body></body></html><!-- Hi there --> #errors #document | <html> | <head> | <body> | <!-- Hi there --> #data <html><body></body></html>x<!-- Hi there --> #errors #document | <html> | <head> | <body> | "x" | <!-- Hi there --> #data <html><body></body></html>x<!-- Hi there --></html><!-- Again --> #errors #document | <html> | <head> | <body> | "x" | <!-- Hi there --> | <!-- Again --> #data <html><body></body></html>x<!-- Hi there --></body></html><!-- Again --> #errors #document | <html> | <head> | <body> | "x" | <!-- Hi there --> | <!-- Again --> #data <html><body><ruby><div><rp>xx</rp></div></ruby></body></html> #errors #document | <html> | <head> | <body> | <ruby> | <div> | <rp> | "xx" #data <html><body><ruby><div><rt>xx</rt></div></ruby></body></html> #errors #document | <html> | <head> | <body> | <ruby> | <div> | <rt> | "xx" #data <html><frameset><!--1--><noframes>A</noframes><!--2--></frameset><!--3--><noframes>B</noframes><!--4--></html><!--5--><noframes>C</noframes><!--6--> #errors #document | <html> | <head> | <frameset> | <!-- 1 --> | <noframes> | "A" | <!-- 2 --> | <!-- 3 --> | <noframes> | "B" | <!-- 4 --> | <noframes> | "C" | <!-- 5 --> | <!-- 6 --> #data <select><option>A<select><option>B<select><option>C<select><option>D<select><option>E<select><option>F<select><option>G<select> #errors #document | <html> | <head> | <body> | <select> | <option> | "A" | <option> | "B" | <select> | <option> | "C" | <option> | "D" | <select> | <option> | "E" | <option> | "F" | <select> | <option> | "G" #data <dd><dd><dt><dt><dd><li><li> #errors #document | <html> | <head> | <body> | <dd> | <dd> | <dt> | <dt> | <dd> | <li> | <li> #data <div><b></div><div><nobr>a<nobr> #errors #document | <html> | <head> | <body> | <div> | <b> | <div> | <b> | <nobr> | "a" | <nobr> #data <head></head> <body></body> #errors #document | <html> | <head> | " " | <body> #data <head></head> <style></style>ddd #errors #document | <html> | <head> | <style> | " " | <body> | "ddd" #data <kbd><table></kbd><col><select><tr> #errors #document | <html> | <head> | <body> | <kbd> | <select> | <table> | <colgroup> | <col> | <tbody> | <tr> #data <kbd><table></kbd><col><select><tr></table><div> #errors #document | <html> | <head> | <body> | <kbd> | <select> | <table> | <colgroup> | <col> | <tbody> | <tr> | <div> #data <a><li><style></style><title> #errors #document | | | | |
  • | | #errors #document | | | | | | x #errors Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. Line: 1 Col: 22 Unexpected end of file. Expected end tag (style). #document | | | --> x #errors Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. #document | | | x #errors Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. #document | | | x #errors Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. #document | | | x #errors Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. #document | | | #errors Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. Line: 1 Col: 20 Unexpected start tag (style) that can be in head. Moved. #document | | | #errors Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. Line: 1 Col: 28 Unexpected start tag (style) that can be in head. Moved. #document | | | #errors Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. #document | | | | | "x" | #errors #document | | | | | | "X" | <meta> | name="z" | <link> | rel="foo" | <style> | " x { content:"</style" } " #data <!DOCTYPE html><select><optgroup></optgroup></select> #errors #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> | <optgroup> #data #errors Line: 2 Col: 1 Unexpected End of file. Expected DOCTYPE. #document | <html> | <head> | <body> #data <!DOCTYPE html> <html> #errors #document | <!DOCTYPE html> | <html> | <head> | <body> #data <!DOCTYPE html><script> </script> <title>x #errors #document | | | | abc #errors #document | | | | | "abc" |
    | | | abc #errors #document | | | | | "abc" |
    | | | abc #errors #document | | | | |
    |
    | abc #errors #document | | | | | | | |

    #errors Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. Line: 1 Col: 20 Unexpected end tag (strong) in table context caused voodoo mode. Line: 1 Col: 20 End tag (strong) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 24 Unexpected end tag (b) in table context caused voodoo mode. Line: 1 Col: 24 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 29 Unexpected end tag (em) in table context caused voodoo mode. Line: 1 Col: 29 End tag (em) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 33 Unexpected end tag (i) in table context caused voodoo mode. Line: 1 Col: 33 End tag (i) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 37 Unexpected end tag (u) in table context caused voodoo mode. Line: 1 Col: 37 End tag (u) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 46 Unexpected end tag (strike) in table context caused voodoo mode. Line: 1 Col: 46 End tag (strike) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 50 Unexpected end tag (s) in table context caused voodoo mode. Line: 1 Col: 50 End tag (s) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 58 Unexpected end tag (blink) in table context caused voodoo mode. Line: 1 Col: 58 Unexpected end tag (blink). Ignored. Line: 1 Col: 63 Unexpected end tag (tt) in table context caused voodoo mode. Line: 1 Col: 63 End tag (tt) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 69 Unexpected end tag (pre) in table context caused voodoo mode. Line: 1 Col: 69 End tag (pre) seen too early. Expected other end tag. Line: 1 Col: 75 Unexpected end tag (big) in table context caused voodoo mode. Line: 1 Col: 75 End tag (big) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 83 Unexpected end tag (small) in table context caused voodoo mode. Line: 1 Col: 83 End tag (small) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 90 Unexpected end tag (font) in table context caused voodoo mode. Line: 1 Col: 90 End tag (font) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 99 Unexpected end tag (select) in table context caused voodoo mode. Line: 1 Col: 99 Unexpected end tag (select). Ignored. Line: 1 Col: 104 Unexpected end tag (h1) in table context caused voodoo mode. Line: 1 Col: 104 End tag (h1) seen too early. Expected other end tag. Line: 1 Col: 109 Unexpected end tag (h2) in table context caused voodoo mode. Line: 1 Col: 109 End tag (h2) seen too early. Expected other end tag. Line: 1 Col: 114 Unexpected end tag (h3) in table context caused voodoo mode. Line: 1 Col: 114 End tag (h3) seen too early. Expected other end tag. Line: 1 Col: 119 Unexpected end tag (h4) in table context caused voodoo mode. Line: 1 Col: 119 End tag (h4) seen too early. Expected other end tag. Line: 1 Col: 124 Unexpected end tag (h5) in table context caused voodoo mode. Line: 1 Col: 124 End tag (h5) seen too early. Expected other end tag. Line: 1 Col: 129 Unexpected end tag (h6) in table context caused voodoo mode. Line: 1 Col: 129 End tag (h6) seen too early. Expected other end tag. Line: 1 Col: 136 Unexpected end tag (body) in the table row phase. Ignored. Line: 1 Col: 141 Unexpected end tag (br) in table context caused voodoo mode. Line: 1 Col: 141 Unexpected end tag (br). Treated as br element. Line: 1 Col: 145 Unexpected end tag (a) in table context caused voodoo mode. Line: 1 Col: 145 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 151 Unexpected end tag (img) in table context caused voodoo mode. Line: 1 Col: 151 This element (img) has no end tag. Line: 1 Col: 159 Unexpected end tag (title) in table context caused voodoo mode. Line: 1 Col: 159 Unexpected end tag (title). Ignored. Line: 1 Col: 166 Unexpected end tag (span) in table context caused voodoo mode. Line: 1 Col: 166 Unexpected end tag (span). Ignored. Line: 1 Col: 174 Unexpected end tag (style) in table context caused voodoo mode. Line: 1 Col: 174 Unexpected end tag (style). Ignored. Line: 1 Col: 183 Unexpected end tag (script) in table context caused voodoo mode. Line: 1 Col: 183 Unexpected end tag (script). Ignored. Line: 1 Col: 196 Unexpected end tag (th). Ignored. Line: 1 Col: 201 Unexpected end tag (td). Ignored. Line: 1 Col: 206 Unexpected end tag (tr). Ignored. Line: 1 Col: 214 This element (frame) has no end tag. Line: 1 Col: 221 This element (area) has no end tag. Line: 1 Col: 228 Unexpected end tag (link). Ignored. Line: 1 Col: 236 This element (param) has no end tag. Line: 1 Col: 241 This element (hr) has no end tag. Line: 1 Col: 249 This element (input) has no end tag. Line: 1 Col: 255 Unexpected end tag (col). Ignored. Line: 1 Col: 262 Unexpected end tag (base). Ignored. Line: 1 Col: 269 Unexpected end tag (meta). Ignored. Line: 1 Col: 280 This element (basefont) has no end tag. Line: 1 Col: 290 This element (bgsound) has no end tag. Line: 1 Col: 298 This element (embed) has no end tag. Line: 1 Col: 307 This element (spacer) has no end tag. Line: 1 Col: 311 Unexpected end tag (p). Ignored. Line: 1 Col: 316 End tag (dd) seen too early. Expected other end tag. Line: 1 Col: 321 End tag (dt) seen too early. Expected other end tag. Line: 1 Col: 331 Unexpected end tag (caption). Ignored. Line: 1 Col: 342 Unexpected end tag (colgroup). Ignored. Line: 1 Col: 350 Unexpected end tag (tbody). Ignored. Line: 1 Col: 358 Unexpected end tag (tfoot). Ignored. Line: 1 Col: 366 Unexpected end tag (thead). Ignored. Line: 1 Col: 376 End tag (address) seen too early. Expected other end tag. Line: 1 Col: 389 End tag (blockquote) seen too early. Expected other end tag. Line: 1 Col: 398 End tag (center) seen too early. Expected other end tag. Line: 1 Col: 404 Unexpected end tag (dir). Ignored. Line: 1 Col: 410 End tag (div) seen too early. Expected other end tag. Line: 1 Col: 415 End tag (dl) seen too early. Expected other end tag. Line: 1 Col: 426 End tag (fieldset) seen too early. Expected other end tag. Line: 1 Col: 436 End tag (listing) seen too early. Expected other end tag. Line: 1 Col: 443 End tag (menu) seen too early. Expected other end tag. Line: 1 Col: 448 End tag (ol) seen too early. Expected other end tag. Line: 1 Col: 453 End tag (ul) seen too early. Expected other end tag. Line: 1 Col: 458 End tag (li) seen too early. Expected other end tag. Line: 1 Col: 465 End tag (nobr) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 471 This element (wbr) has no end tag. Line: 1 Col: 487 End tag (button) seen too early. Expected other end tag. Line: 1 Col: 497 End tag (marquee) seen too early. Expected other end tag. Line: 1 Col: 506 End tag (object) seen too early. Expected other end tag. Line: 1 Col: 524 Unexpected end tag (html). Ignored. Line: 1 Col: 524 Unexpected end tag (frameset). Ignored. Line: 1 Col: 531 Unexpected end tag (head). Ignored. Line: 1 Col: 540 Unexpected end tag (iframe). Ignored. Line: 1 Col: 548 This element (image) has no end tag. Line: 1 Col: 558 This element (isindex) has no end tag. Line: 1 Col: 568 Unexpected end tag (noembed). Ignored. Line: 1 Col: 579 Unexpected end tag (noframes). Ignored. Line: 1 Col: 590 Unexpected end tag (noscript). Ignored. Line: 1 Col: 601 Unexpected end tag (optgroup). Ignored. Line: 1 Col: 610 Unexpected end tag (option). Ignored. Line: 1 Col: 622 Unexpected end tag (plaintext). Ignored. Line: 1 Col: 633 Unexpected end tag (textarea). Ignored. #document | | | |
    |
    | abc #errors #document | | | | | | abc #errors #document | | | | | --> #errors Line: 1 Col: 64 Unexpected end tag (textarea). #document | | | | | #errors #document | | | | | " #data #errors #document | | | | | #errors #document | | | | | --> #errors Line: 1 Col: 10 Unexpected start tag (textarea). Expected DOCTYPE. Line: 1 Col: 49 Unexpected end tag (textarea). #document | | | | #errors Line: 1 Col: 10 Unexpected start tag (textarea). Expected DOCTYPE. #document | | | | " #data --> #errors Line: 1 Col: 8 Unexpected start tag (iframe). Expected DOCTYPE. Line: 1 Col: 41 Unexpected end tag (iframe). #document | | | | #errors Line: 1 Col: 8 Unexpected start tag (iframe). Expected DOCTYPE. #document | | | | #errors Line: 1 Col: 9 Unexpected end tag (strong). Expected DOCTYPE. Line: 1 Col: 9 Unexpected end tag (strong) after the (implied) root element. Line: 1 Col: 13 Unexpected end tag (b) after the (implied) root element. Line: 1 Col: 18 Unexpected end tag (em) after the (implied) root element. Line: 1 Col: 22 Unexpected end tag (i) after the (implied) root element. Line: 1 Col: 26 Unexpected end tag (u) after the (implied) root element. Line: 1 Col: 35 Unexpected end tag (strike) after the (implied) root element. Line: 1 Col: 39 Unexpected end tag (s) after the (implied) root element. Line: 1 Col: 47 Unexpected end tag (blink) after the (implied) root element. Line: 1 Col: 52 Unexpected end tag (tt) after the (implied) root element. Line: 1 Col: 58 Unexpected end tag (pre) after the (implied) root element. Line: 1 Col: 64 Unexpected end tag (big) after the (implied) root element. Line: 1 Col: 72 Unexpected end tag (small) after the (implied) root element. Line: 1 Col: 79 Unexpected end tag (font) after the (implied) root element. Line: 1 Col: 88 Unexpected end tag (select) after the (implied) root element. Line: 1 Col: 93 Unexpected end tag (h1) after the (implied) root element. Line: 1 Col: 98 Unexpected end tag (h2) after the (implied) root element. Line: 1 Col: 103 Unexpected end tag (h3) after the (implied) root element. Line: 1 Col: 108 Unexpected end tag (h4) after the (implied) root element. Line: 1 Col: 113 Unexpected end tag (h5) after the (implied) root element. Line: 1 Col: 118 Unexpected end tag (h6) after the (implied) root element. Line: 1 Col: 125 Unexpected end tag (body) after the (implied) root element. Line: 1 Col: 130 Unexpected end tag (br). Treated as br element. Line: 1 Col: 134 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 140 This element (img) has no end tag. Line: 1 Col: 148 Unexpected end tag (title). Ignored. Line: 1 Col: 155 Unexpected end tag (span). Ignored. Line: 1 Col: 163 Unexpected end tag (style). Ignored. Line: 1 Col: 172 Unexpected end tag (script). Ignored. Line: 1 Col: 180 Unexpected end tag (table). Ignored. Line: 1 Col: 185 Unexpected end tag (th). Ignored. Line: 1 Col: 190 Unexpected end tag (td). Ignored. Line: 1 Col: 195 Unexpected end tag (tr). Ignored. Line: 1 Col: 203 This element (frame) has no end tag. Line: 1 Col: 210 This element (area) has no end tag. Line: 1 Col: 217 Unexpected end tag (link). Ignored. Line: 1 Col: 225 This element (param) has no end tag. Line: 1 Col: 230 This element (hr) has no end tag. Line: 1 Col: 238 This element (input) has no end tag. Line: 1 Col: 244 Unexpected end tag (col). Ignored. Line: 1 Col: 251 Unexpected end tag (base). Ignored. Line: 1 Col: 258 Unexpected end tag (meta). Ignored. Line: 1 Col: 269 This element (basefont) has no end tag. Line: 1 Col: 279 This element (bgsound) has no end tag. Line: 1 Col: 287 This element (embed) has no end tag. Line: 1 Col: 296 This element (spacer) has no end tag. Line: 1 Col: 300 Unexpected end tag (p). Ignored. Line: 1 Col: 305 End tag (dd) seen too early. Expected other end tag. Line: 1 Col: 310 End tag (dt) seen too early. Expected other end tag. Line: 1 Col: 320 Unexpected end tag (caption). Ignored. Line: 1 Col: 331 Unexpected end tag (colgroup). Ignored. Line: 1 Col: 339 Unexpected end tag (tbody). Ignored. Line: 1 Col: 347 Unexpected end tag (tfoot). Ignored. Line: 1 Col: 355 Unexpected end tag (thead). Ignored. Line: 1 Col: 365 End tag (address) seen too early. Expected other end tag. Line: 1 Col: 378 End tag (blockquote) seen too early. Expected other end tag. Line: 1 Col: 387 End tag (center) seen too early. Expected other end tag. Line: 1 Col: 393 Unexpected end tag (dir). Ignored. Line: 1 Col: 399 End tag (div) seen too early. Expected other end tag. Line: 1 Col: 404 End tag (dl) seen too early. Expected other end tag. Line: 1 Col: 415 End tag (fieldset) seen too early. Expected other end tag. Line: 1 Col: 425 End tag (listing) seen too early. Expected other end tag. Line: 1 Col: 432 End tag (menu) seen too early. Expected other end tag. Line: 1 Col: 437 End tag (ol) seen too early. Expected other end tag. Line: 1 Col: 442 End tag (ul) seen too early. Expected other end tag. Line: 1 Col: 447 End tag (li) seen too early. Expected other end tag. Line: 1 Col: 454 End tag (nobr) violates step 1, paragraph 1 of the adoption agency algorithm. Line: 1 Col: 460 This element (wbr) has no end tag. Line: 1 Col: 476 End tag (button) seen too early. Expected other end tag. Line: 1 Col: 486 End tag (marquee) seen too early. Expected other end tag. Line: 1 Col: 495 End tag (object) seen too early. Expected other end tag. Line: 1 Col: 513 Unexpected end tag (html). Ignored. Line: 1 Col: 513 Unexpected end tag (frameset). Ignored. Line: 1 Col: 520 Unexpected end tag (head). Ignored. Line: 1 Col: 529 Unexpected end tag (iframe). Ignored. Line: 1 Col: 537 This element (image) has no end tag. Line: 1 Col: 547 This element (isindex) has no end tag. Line: 1 Col: 557 Unexpected end tag (noembed). Ignored. Line: 1 Col: 568 Unexpected end tag (noframes). Ignored. Line: 1 Col: 579 Unexpected end tag (noscript). Ignored. Line: 1 Col: 590 Unexpected end tag (optgroup). Ignored. Line: 1 Col: 599 Unexpected end tag (option). Ignored. Line: 1 Col: 611 Unexpected end tag (plaintext). Ignored. Line: 1 Col: 622 Unexpected end tag (textarea). Ignored. #document | | | |
    |

    #data

    | | |

    #data #errors Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. Line: 1 Col: 10 Expected closing tag. Unexpected end of file. #document | | | lxd-2.0.11/dist/src/golang.org/x/net/html/testdata/webkit/tables01.dat0000644061062106075000000000532213172163402026464 0ustar stgraberdomain admins#data

    #errors #document | | | | | | |
    #data
    #errors #document | | | | | | |
    #data #errors #document | | | |
    | | | foo="bar" #data
    foo #errors #document | | | | "foo" |
    | #data

    foo #errors #document | | | | |

    | "foo" #data

    #errors #document | | | | | | |
    #data
    #errors #document | | | | #data
    #errors #document | | | | |
    #data
    #errors #document | | | | #data
    B
    #errors #document | | | | | | |
    | "B" #data
    foo #errors #document | | | | | | |
    | "foo" #data
    A
    B #errors #document | | | | | | |
    | "A" | "B" #data
    #errors #document | | | | | | |
    #data
    foo #errors #document | | | | | | |
    | "foo" #data #errors #document | | | |
    | | | #data
    |
    #errors #document | | | | | | |
    | #data
    #errors #document | | | | | | |
    | | | ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/testdata/webkit/scripted/���������������������������������0000755�0610621�0607500�00000000000�13172163402�026172� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/testdata/webkit/scripted/webkit01.dat���������������������0000644�0610621�0607500�00000001105�13172163402�030307� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#data 13 #errors #document | | | | "1" | 4 #errors #document | | | | "1" |

    TEXT #errors #document | | | |

    | | id="B" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | BAR #errors #document | | | | "FOO" | QUX #errors #document | | | | "FOO" |

    Go 1 Release Notes

    Introduction to Go 1

    Go version 1, Go 1 for short, defines a language and a set of core libraries that provide a stable foundation for creating reliable products, projects, and publications.

    The driving motivation for Go 1 is stability for its users. People should be able to write Go programs and expect that they will continue to compile and run without change, on a time scale of years, including in production environments such as Google App Engine. Similarly, people should be able to write books about Go, be able to say which version of Go the book is describing, and have that version number still be meaningful much later.

    Code that compiles in Go 1 should, with few exceptions, continue to compile and run throughout the lifetime of that version, even as we issue updates and bug fixes such as Go version 1.1, 1.2, and so on. Other than critical fixes, changes made to the language and library for subsequent releases of Go 1 may add functionality but will not break existing Go 1 programs. The Go 1 compatibility document explains the compatibility guidelines in more detail.

    Go 1 is a representation of Go as it used today, not a wholesale rethinking of the language. We avoided designing new features and instead focused on cleaning up problems and inconsistencies and improving portability. There are a number changes to the Go language and packages that we had considered for some time and prototyped but not released primarily because they are significant and backwards-incompatible. Go 1 was an opportunity to get them out, which is helpful for the long term, but also means that Go 1 introduces incompatibilities for old programs. Fortunately, the go fix tool can automate much of the work needed to bring programs up to the Go 1 standard.

    This document outlines the major changes in Go 1 that will affect programmers updating existing code; its reference point is the prior release, r60 (tagged as r60.3). It also explains how to update code from r60 to run under Go 1.

    Changes to the language

    Append

    The append predeclared variadic function makes it easy to grow a slice by adding elements to the end. A common use is to add bytes to the end of a byte slice when generating output. However, append did not provide a way to append a string to a []byte, which is another common case.

        greeting := []byte{}
        greeting = append(greeting, []byte("hello ")...)

    By analogy with the similar property of copy, Go 1 permits a string to be appended (byte-wise) directly to a byte slice, reducing the friction between strings and byte slices. The conversion is no longer necessary:

        greeting = append(greeting, "world"...)

    Updating: This is a new feature, so existing code needs no changes.

    Close

    The close predeclared function provides a mechanism for a sender to signal that no more values will be sent. It is important to the implementation of for range loops over channels and is helpful in other situations. Partly by design and partly because of race conditions that can occur otherwise, it is intended for use only by the goroutine sending on the channel, not by the goroutine receiving data. However, before Go 1 there was no compile-time checking that close was being used correctly.

    To close this gap, at least in part, Go 1 disallows close on receive-only channels. Attempting to close such a channel is a compile-time error.

        var c chan int
        var csend chan<- int = c
        var crecv <-chan int = c
        close(c)     // legal
        close(csend) // legal
        close(crecv) // illegal
    

    Updating: Existing code that attempts to close a receive-only channel was erroneous even before Go 1 and should be fixed. The compiler will now reject such code.

    Composite literals

    In Go 1, a composite literal of array, slice, or map type can elide the type specification for the elements' initializers if they are of pointer type. All four of the initializations in this example are legal; the last one was illegal before Go 1.

        type Date struct {
            month string
            day   int
        }
        // Struct values, fully qualified; always legal.
        holiday1 := []Date{
            Date{"Feb", 14},
            Date{"Nov", 11},
            Date{"Dec", 25},
        }
        // Struct values, type name elided; always legal.
        holiday2 := []Date{
            {"Feb", 14},
            {"Nov", 11},
            {"Dec", 25},
        }
        // Pointers, fully qualified, always legal.
        holiday3 := []*Date{
            &Date{"Feb", 14},
            &Date{"Nov", 11},
            &Date{"Dec", 25},
        }
        // Pointers, type name elided; legal in Go 1.
        holiday4 := []*Date{
            {"Feb", 14},
            {"Nov", 11},
            {"Dec", 25},
        }

    Updating: This change has no effect on existing code, but the command gofmt -s applied to existing source will, among other things, elide explicit element types wherever permitted.

    Goroutines during init

    The old language defined that go statements executed during initialization created goroutines but that they did not begin to run until initialization of the entire program was complete. This introduced clumsiness in many places and, in effect, limited the utility of the init construct: if it was possible for another package to use the library during initialization, the library was forced to avoid goroutines. This design was done for reasons of simplicity and safety but, as our confidence in the language grew, it seemed unnecessary. Running goroutines during initialization is no more complex or unsafe than running them during normal execution.

    In Go 1, code that uses goroutines can be called from init routines and global initialization expressions without introducing a deadlock.

    var PackageGlobal int
    
    func init() {
        c := make(chan int)
        go initializationFunction(c)
        PackageGlobal = <-c
    }

    Updating: This is a new feature, so existing code needs no changes, although it's possible that code that depends on goroutines not starting before main will break. There was no such code in the standard repository.

    The rune type

    The language spec allows the int type to be 32 or 64 bits wide, but current implementations set int to 32 bits even on 64-bit platforms. It would be preferable to have int be 64 bits on 64-bit platforms. (There are important consequences for indexing large slices.) However, this change would waste space when processing Unicode characters with the old language because the int type was also used to hold Unicode code points: each code point would waste an extra 32 bits of storage if int grew from 32 bits to 64.

    To make changing to 64-bit int feasible, Go 1 introduces a new basic type, rune, to represent individual Unicode code points. It is an alias for int32, analogous to byte as an alias for uint8.

    Character literals such as 'a', '語', and '\u0345' now have default type rune, analogous to 1.0 having default type float64. A variable initialized to a character constant will therefore have type rune unless otherwise specified.

    Libraries have been updated to use rune rather than int when appropriate. For instance, the functions unicode.ToLower and relatives now take and return a rune.

        delta := 'δ' // delta has type rune.
        var DELTA rune
        DELTA = unicode.ToUpper(delta)
        epsilon := unicode.ToLower(DELTA + 1)
        if epsilon != 'δ'+1 {
            log.Fatal("inconsistent casing for Greek")
        }

    Updating: Most source code will be unaffected by this because the type inference from := initializers introduces the new type silently, and it propagates from there. Some code may get type errors that a trivial conversion will resolve.

    The error type

    Go 1 introduces a new built-in type, error, which has the following definition:

        type error interface {
            Error() string
        }
    

    Since the consequences of this type are all in the package library, it is discussed below.

    Deleting from maps

    In the old language, to delete the entry with key k from map m, one wrote the statement,

        m[k] = value, false
    

    This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.

    In Go 1, that syntax has gone; instead there is a new built-in function, delete. The call

        delete(m, k)

    will delete the map entry retrieved by the expression m[k]. There is no return value. Deleting a non-existent entry is a no-op.

    Updating: Running go fix will convert expressions of the form m[k] = value, false into delete(m, k) when it is clear that the ignored value can be safely discarded from the program and false refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.

    Iterating in maps

    The old language specification did not define the order of iteration for maps, and in practice it differed across hardware platforms. This caused tests that iterated over maps to be fragile and non-portable, with the unpleasant property that a test might always pass on one machine but break on another.

    In Go 1, the order in which elements are visited when iterating over a map using a for range statement is defined to be unpredictable, even if the same loop is run multiple times with the same map. Code should not assume that the elements are visited in any particular order.

    This change means that code that depends on iteration order is very likely to break early and be fixed long before it becomes a problem. Just as important, it allows the map implementation to ensure better map balancing even when programs are using range loops to select an element from a map.

        m := map[string]int{"Sunday": 0, "Monday": 1}
        for name, value := range m {
            // This loop should not assume Sunday will be visited first.
            f(name, value)
        }

    Updating: This is one change where tools cannot help. Most existing code will be unaffected, but some programs may break or misbehave; we recommend manual checking of all range statements over maps to verify they do not depend on iteration order. There were a few such examples in the standard repository; they have been fixed. Note that it was already incorrect to depend on the iteration order, which was unspecified. This change codifies the unpredictability.

    Multiple assignment

    The language specification has long guaranteed that in assignments the right-hand-side expressions are all evaluated before any left-hand-side expressions are assigned. To guarantee predictable behavior, Go 1 refines the specification further.

    If the left-hand side of the assignment statement contains expressions that require evaluation, such as function calls or array indexing operations, these will all be done using the usual left-to-right rule before any variables are assigned their value. Once everything is evaluated, the actual assignments proceed in left-to-right order.

    These examples illustrate the behavior.

        sa := []int{1, 2, 3}
        i := 0
        i, sa[i] = 1, 2 // sets i = 1, sa[0] = 2
    
        sb := []int{1, 2, 3}
        j := 0
        sb[j], j = 2, 1 // sets sb[0] = 2, j = 1
    
        sc := []int{1, 2, 3}
        sc[0], sc[0] = 1, 2 // sets sc[0] = 1, then sc[0] = 2 (so sc[0] = 2 at end)

    Updating: This is one change where tools cannot help, but breakage is unlikely. No code in the standard repository was broken by this change, and code that depended on the previous unspecified behavior was already incorrect.

    Returns and shadowed variables

    A common mistake is to use return (without arguments) after an assignment to a variable that has the same name as a result variable but is not the same variable. This situation is called shadowing: the result variable has been shadowed by another variable with the same name declared in an inner scope.

    In functions with named return values, the Go 1 compilers disallow return statements without arguments if any of the named return values is shadowed at the point of the return statement. (It isn't part of the specification, because this is one area we are still exploring; the situation is analogous to the compilers rejecting functions that do not end with an explicit return statement.)

    This function implicitly returns a shadowed return value and will be rejected by the compiler:

        func Bug() (i, j, k int) {
            for i = 0; i < 5; i++ {
                for j := 0; j < 5; j++ { // Redeclares j.
                    k += i*j
                    if k > 100 {
                        return // Rejected: j is shadowed here.
                    }
                }
            }
            return // OK: j is not shadowed here.
        }
    

    Updating: Code that shadows return values in this way will be rejected by the compiler and will need to be fixed by hand. The few cases that arose in the standard repository were mostly bugs.

    Copying structs with unexported fields

    The old language did not allow a package to make a copy of a struct value containing unexported fields belonging to a different package. There was, however, a required exception for a method receiver; also, the implementations of copy and append have never honored the restriction.

    Go 1 will allow packages to copy struct values containing unexported fields from other packages. Besides resolving the inconsistency, this change admits a new kind of API: a package can return an opaque value without resorting to a pointer or interface. The new implementations of time.Time and reflect.Value are examples of types taking advantage of this new property.

    As an example, if package p includes the definitions,

        type Struct struct {
            Public int
            secret int
        }
        func NewStruct(a int) Struct {  // Note: not a pointer.
            return Struct{a, f(a)}
        }
        func (s Struct) String() string {
            return fmt.Sprintf("{%d (secret %d)}", s.Public, s.secret)
        }
    

    a package that imports p can assign and copy values of type p.Struct at will. Behind the scenes the unexported fields will be assigned and copied just as if they were exported, but the client code will never be aware of them. The code

        import "p"
    
        myStruct := p.NewStruct(23)
        copyOfMyStruct := myStruct
        fmt.Println(myStruct, copyOfMyStruct)
    

    will show that the secret field of the struct has been copied to the new value.

    Updating: This is a new feature, so existing code needs no changes.

    Equality

    Before Go 1, the language did not define equality on struct and array values. This meant, among other things, that structs and arrays could not be used as map keys. On the other hand, Go did define equality on function and map values. Function equality was problematic in the presence of closures (when are two closures equal?) while map equality compared pointers, not the maps' content, which was usually not what the user would want.

    Go 1 addressed these issues. First, structs and arrays can be compared for equality and inequality (== and !=), and therefore be used as map keys, provided they are composed from elements for which equality is also defined, using element-wise comparison.

        type Day struct {
            long  string
            short string
        }
        Christmas := Day{"Christmas", "XMas"}
        Thanksgiving := Day{"Thanksgiving", "Turkey"}
        holiday := map[Day]bool{
            Christmas:    true,
            Thanksgiving: true,
        }
        fmt.Printf("Christmas is a holiday: %t\n", holiday[Christmas])

    Second, Go 1 removes the definition of equality for function values, except for comparison with nil. Finally, map equality is gone too, also except for comparison with nil.

    Note that equality is still undefined for slices, for which the calculation is in general infeasible. Also note that the ordered comparison operators (< <= > >=) are still undefined for structs and arrays.

    Updating: Struct and array equality is a new feature, so existing code needs no changes. Existing code that depends on function or map equality will be rejected by the compiler and will need to be fixed by hand. Few programs will be affected, but the fix may require some redesign.

    The package hierarchy

    Go 1 addresses many deficiencies in the old standard library and cleans up a number of packages, making them more internally consistent and portable.

    This section describes how the packages have been rearranged in Go 1. Some have moved, some have been renamed, some have been deleted. New packages are described in later sections.

    The package hierarchy

    Go 1 has a rearranged package hierarchy that groups related items into subdirectories. For instance, utf8 and utf16 now occupy subdirectories of unicode. Also, some packages have moved into subrepositories of code.google.com/p/go while others have been deleted outright.

    Old path New path

    asn1 encoding/asn1
    csv encoding/csv
    gob encoding/gob
    json encoding/json
    xml encoding/xml

    exp/template/html html/template

    big math/big
    cmath math/cmplx
    rand math/rand

    http net/http
    http/cgi net/http/cgi
    http/fcgi net/http/fcgi
    http/httptest net/http/httptest
    http/pprof net/http/pprof
    mail net/mail
    rpc net/rpc
    rpc/jsonrpc net/rpc/jsonrpc
    smtp net/smtp
    url net/url

    exec os/exec

    scanner text/scanner
    tabwriter text/tabwriter
    template text/template
    template/parse text/template/parse

    utf8 unicode/utf8
    utf16 unicode/utf16

    Note that the package names for the old cmath and exp/template/html packages have changed to cmplx and template.

    Updating: Running go fix will update all imports and package renames for packages that remain inside the standard repository. Programs that import packages that are no longer in the standard repository will need to be edited by hand.

    The package tree exp

    Because they are not standardized, the packages under the exp directory will not be available in the standard Go 1 release distributions, although they will be available in source code form in the repository for developers who wish to use them.

    Several packages have moved under exp at the time of Go 1's release:

    • ebnf
    • html
    • go/types

    (The EscapeString and UnescapeString types remain in package html.)

    All these packages are available under the same names, with the prefix exp/: exp/ebnf etc.

    Also, the utf8.String type has been moved to its own package, exp/utf8string.

    Finally, the gotype command now resides in exp/gotype, while ebnflint is now in exp/ebnflint. If they are installed, they now reside in $GOROOT/bin/tool.

    Updating: Code that uses packages in exp will need to be updated by hand, or else compiled from an installation that has exp available. The go fix tool or the compiler will complain about such uses.

    The package tree old

    Because they are deprecated, the packages under the old directory will not be available in the standard Go 1 release distributions, although they will be available in source code form for developers who wish to use them.

    The packages in their new locations are:

    • old/netchan
    • old/regexp
    • old/template

    Updating: Code that uses packages now in old will need to be updated by hand, or else compiled from an installation that has old available. The go fix tool will warn about such uses.

    Deleted packages

    Go 1 deletes several packages outright:

    • container/vector
    • exp/datafmt
    • go/typechecker
    • try

    and also the command gotry.

    Updating: Code that uses container/vector should be updated to use slices directly. See the Go Language Community Wiki for some suggestions. Code that uses the other packages (there should be almost zero) will need to be rethought.

    Packages moving to subrepositories

    Go 1 has moved a number of packages into other repositories, usually sub-repositories of the main Go repository. This table lists the old and new import paths:
    Old New

    crypto/bcrypt code.google.com/p/go.crypto/bcrypt
    crypto/blowfish code.google.com/p/go.crypto/blowfish
    crypto/cast5 code.google.com/p/go.crypto/cast5
    crypto/md4 code.google.com/p/go.crypto/md4
    crypto/ocsp code.google.com/p/go.crypto/ocsp
    crypto/openpgp code.google.com/p/go.crypto/openpgp
    crypto/openpgp/armor code.google.com/p/go.crypto/openpgp/armor
    crypto/openpgp/elgamal code.google.com/p/go.crypto/openpgp/elgamal
    crypto/openpgp/errors code.google.com/p/go.crypto/openpgp/errors
    crypto/openpgp/packet code.google.com/p/go.crypto/openpgp/packet
    crypto/openpgp/s2k code.google.com/p/go.crypto/openpgp/s2k
    crypto/ripemd160 code.google.com/p/go.crypto/ripemd160
    crypto/twofish code.google.com/p/go.crypto/twofish
    crypto/xtea code.google.com/p/go.crypto/xtea
    exp/ssh code.google.com/p/go.crypto/ssh

    image/bmp code.google.com/p/go.image/bmp
    image/tiff code.google.com/p/go.image/tiff

    net/dict code.google.com/p/go.net/dict
    net/websocket code.google.com/p/go.net/websocket
    exp/spdy code.google.com/p/go.net/spdy

    encoding/git85 code.google.com/p/go.codereview/git85
    patch code.google.com/p/go.codereview/patch

    exp/wingui code.google.com/p/gowingui

    Updating: Running go fix will update imports of these packages to use the new import paths. Installations that depend on these packages will need to install them using a go get command.

    Major changes to the library

    This section describes significant changes to the core libraries, the ones that affect the most programs.

    The error type and errors package

    The placement of os.Error in package os is mostly historical: errors first came up when implementing package os, and they seemed system-related at the time. Since then it has become clear that errors are more fundamental than the operating system. For example, it would be nice to use Errors in packages that os depends on, like syscall. Also, having Error in os introduces many dependencies on os that would otherwise not exist.

    Go 1 solves these problems by introducing a built-in error interface type and a separate errors package (analogous to bytes and strings) that contains utility functions. It replaces os.NewError with errors.New, giving errors a more central place in the environment.

    So the widely-used String method does not cause accidental satisfaction of the error interface, the error interface uses instead the name Error for that method:

        type error interface {
            Error() string
        }
    

    The fmt library automatically invokes Error, as it already does for String, for easy printing of error values.

    type SyntaxError struct {
        File    string
        Line    int
        Message string
    }
    
    func (se *SyntaxError) Error() string {
        return fmt.Sprintf("%s:%d: %s", se.File, se.Line, se.Message)
    }

    All standard packages have been updated to use the new interface; the old os.Error is gone.

    A new package, errors, contains the function

    func New(text string) error
    

    to turn a string into an error. It replaces the old os.NewError.

        var ErrSyntax = errors.New("syntax error")

    Updating: Running go fix will update almost all code affected by the change. Code that defines error types with a String method will need to be updated by hand to rename the methods to Error.

    System call errors

    The old syscall package, which predated os.Error (and just about everything else), returned errors as int values. In turn, the os package forwarded many of these errors, such as EINVAL, but using a different set of errors on each platform. This behavior was unpleasant and unportable.

    In Go 1, the syscall package instead returns an error for system call errors. On Unix, the implementation is done by a syscall.Errno type that satisfies error and replaces the old os.Errno.

    The changes affecting os.EINVAL and relatives are described elsewhere.

    Updating: Running go fix will update almost all code affected by the change. Regardless, most code should use the os package rather than syscall and so will be unaffected.

    Time

    Time is always a challenge to support well in a programming language. The old Go time package had int64 units, no real type safety, and no distinction between absolute times and durations.

    One of the most sweeping changes in the Go 1 library is therefore a complete redesign of the time package. Instead of an integer number of nanoseconds as an int64, and a separate *time.Time type to deal with human units such as hours and years, there are now two fundamental types: time.Time (a value, so the * is gone), which represents a moment in time; and time.Duration, which represents an interval. Both have nanosecond resolution. A Time can represent any time into the ancient past and remote future, while a Duration can span plus or minus only about 290 years. There are methods on these types, plus a number of helpful predefined constant durations such as time.Second.

    Among the new methods are things like Time.Add, which adds a Duration to a Time, and Time.Sub, which subtracts two Times to yield a Duration.

    The most important semantic change is that the Unix epoch (Jan 1, 1970) is now relevant only for those functions and methods that mention Unix: time.Unix and the Unix and UnixNano methods of the Time type. In particular, time.Now returns a time.Time value rather than, in the old API, an integer nanosecond count since the Unix epoch.

    // sleepUntil sleeps until the specified time. It returns immediately if it's too late.
    func sleepUntil(wakeup time.Time) {
        now := time.Now() // A Time.
        if !wakeup.After(now) {
            return
        }
        delta := wakeup.Sub(now) // A Duration.
        fmt.Printf("Sleeping for %.3fs\n", delta.Seconds())
        time.Sleep(delta)
    }

    The new types, methods, and constants have been propagated through all the standard packages that use time, such as os and its representation of file time stamps.

    Updating: The go fix tool will update many uses of the old time package to use the new types and methods, although it does not replace values such as 1e9 representing nanoseconds per second. Also, because of type changes in some of the values that arise, some of the expressions rewritten by the fix tool may require further hand editing; in such cases the rewrite will include the correct function or method for the old functionality, but may have the wrong type or require further analysis.

    Minor changes to the library

    This section describes smaller changes, such as those to less commonly used packages or that affect few programs beyond the need to run go fix. This category includes packages that are new in Go 1. Collectively they improve portability, regularize behavior, and make the interfaces more modern and Go-like.

    The archive/zip package

    In Go 1, *zip.Writer no longer has a Write method. Its presence was a mistake.

    Updating: What little code is affected will be caught by the compiler and must be updated by hand.

    The bufio package

    In Go 1, bufio.NewReaderSize and bufio.NewWriterSize functions no longer return an error for invalid sizes. If the argument size is too small or invalid, it is adjusted.

    Updating: Running go fix will update calls that assign the error to _. Calls that aren't fixed will be caught by the compiler and must be updated by hand.

    The compress/flate, compress/gzip and compress/zlib packages

    In Go 1, the NewWriterXxx functions in compress/flate, compress/gzip and compress/zlib all return (*Writer, error) if they take a compression level, and *Writer otherwise. Package gzip's Compressor and Decompressor types have been renamed to Writer and Reader. Package flate's WrongValueError type has been removed.

    Updating Running go fix will update old names and calls that assign the error to _. Calls that aren't fixed will be caught by the compiler and must be updated by hand.

    The crypto/aes and crypto/des packages

    In Go 1, the Reset method has been removed. Go does not guarantee that memory is not copied and therefore this method was misleading.

    The cipher-specific types *aes.Cipher, *des.Cipher, and *des.TripleDESCipher have been removed in favor of cipher.Block.

    Updating: Remove the calls to Reset. Replace uses of the specific cipher types with cipher.Block.

    The crypto/elliptic package

    In Go 1, elliptic.Curve has been made an interface to permit alternative implementations. The curve parameters have been moved to the elliptic.CurveParams structure.

    Updating: Existing users of *elliptic.Curve will need to change to simply elliptic.Curve. Calls to Marshal, Unmarshal and GenerateKey are now functions in crypto/elliptic that take an elliptic.Curve as their first argument.

    The crypto/hmac package

    In Go 1, the hash-specific functions, such as hmac.NewMD5, have been removed from crypto/hmac. Instead, hmac.New takes a function that returns a hash.Hash, such as md5.New.

    Updating: Running go fix will perform the needed changes.

    The crypto/x509 package

    In Go 1, the CreateCertificate and CreateCRL functions in crypto/x509 have been altered to take an interface{} where they previously took a *rsa.PublicKey or *rsa.PrivateKey. This will allow other public key algorithms to be implemented in the future.

    Updating: No changes will be needed.

    The encoding/binary package

    In Go 1, the binary.TotalSize function has been replaced by Size, which takes an interface{} argument rather than a reflect.Value.

    Updating: What little code is affected will be caught by the compiler and must be updated by hand.

    The encoding/xml package

    In Go 1, the xml package has been brought closer in design to the other marshaling packages such as encoding/gob.

    The old Parser type is renamed Decoder and has a new Decode method. An Encoder type was also introduced.

    The functions Marshal and Unmarshal work with []byte values now. To work with streams, use the new Encoder and Decoder types.

    When marshaling or unmarshaling values, the format of supported flags in field tags has changed to be closer to the json package (`xml:"name,flag"`). The matching done between field tags, field names, and the XML attribute and element names is now case-sensitive. The XMLName field tag, if present, must also match the name of the XML element being marshaled.

    Updating: Running go fix will update most uses of the package except for some calls to Unmarshal. Special care must be taken with field tags, since the fix tool will not update them and if not fixed by hand they will misbehave silently in some cases. For example, the old "attr" is now written ",attr" while plain "attr" remains valid but with a different meaning.

    The expvar package

    In Go 1, the RemoveAll function has been removed. The Iter function and Iter method on *Map have been replaced by Do and (*Map).Do.

    Updating: Most code using expvar will not need changing. The rare code that used Iter can be updated to pass a closure to Do to achieve the same effect.

    The flag package

    In Go 1, the interface flag.Value has changed slightly. The Set method now returns an error instead of a bool to indicate success or failure.

    There is also a new kind of flag, Duration, to support argument values specifying time intervals. Values for such flags must be given units, just as time.Duration formats them: 10s, 1h30m, etc.

    var timeout = flag.Duration("timeout", 30*time.Second, "how long to wait for completion")

    Updating: Programs that implement their own flags will need minor manual fixes to update their Set methods. The Duration flag is new and affects no existing code.

    The go/* packages

    Several packages under go have slightly revised APIs.

    A concrete Mode type was introduced for configuration mode flags in the packages go/scanner, go/parser, go/printer, and go/doc.

    The modes AllowIllegalChars and InsertSemis have been removed from the go/scanner package. They were mostly useful for scanning text other then Go source files. Instead, the text/scanner package should be used for that purpose.

    The ErrorHandler provided to the scanner's Init method is now simply a function rather than an interface. The ErrorVector type has been removed in favor of the (existing) ErrorList type, and the ErrorVector methods have been migrated. Instead of embedding an ErrorVector in a client of the scanner, now a client should maintain an ErrorList.

    The set of parse functions provided by the go/parser package has been reduced to the primary parse function ParseFile, and a couple of convenience functions ParseDir and ParseExpr.

    The go/printer package supports an additional configuration mode SourcePos; if set, the printer will emit //line comments such that the generated output contains the original source code position information. The new type CommentedNode can be used to provide comments associated with an arbitrary ast.Node (until now only ast.File carried comment information).

    The type names of the go/doc package have been streamlined by removing the Doc suffix: PackageDoc is now Package, ValueDoc is Value, etc. Also, all types now consistently have a Name field (or Names, in the case of type Value) and Type.Factories has become Type.Funcs. Instead of calling doc.NewPackageDoc(pkg, importpath), documentation for a package is created with:

        doc.New(pkg, importpath, mode)
    

    where the new mode parameter specifies the operation mode: if set to AllDecls, all declarations (not just exported ones) are considered. The function NewFileDoc was removed, and the function CommentText has become the method Text of ast.CommentGroup.

    In package go/token, the token.FileSet method Files (which originally returned a channel of *token.Files) has been replaced with the iterator Iterate that accepts a function argument instead.

    In package go/build, the API has been nearly completely replaced. The package still computes Go package information but it does not run the build: the Cmd and Script types are gone. (To build code, use the new go command instead.) The DirInfo type is now named Package. FindTree and ScanDir are replaced by Import and ImportDir.

    Updating: Code that uses packages in go will have to be updated by hand; the compiler will reject incorrect uses. Templates used in conjunction with any of the go/doc types may need manual fixes; the renamed fields will lead to run-time errors.

    The hash package

    In Go 1, the definition of hash.Hash includes a new method, BlockSize. This new method is used primarily in the cryptographic libraries.

    The Sum method of the hash.Hash interface now takes a []byte argument, to which the hash value will be appended. The previous behavior can be recreated by adding a nil argument to the call.

    Updating: Existing implementations of hash.Hash will need to add a BlockSize method. Hashes that process the input one byte at a time can implement BlockSize to return 1. Running go fix will update calls to the Sum methods of the various implementations of hash.Hash.

    Updating: Since the package's functionality is new, no updating is necessary.

    The http package

    In Go 1 the http package is refactored, putting some of the utilities into a httputil subdirectory. These pieces are only rarely needed by HTTP clients. The affected items are:

    • ClientConn
    • DumpRequest
    • DumpRequestOut
    • DumpResponse
    • NewChunkedReader
    • NewChunkedWriter
    • NewClientConn
    • NewProxyClientConn
    • NewServerConn
    • NewSingleHostReverseProxy
    • ReverseProxy
    • ServerConn

    The Request.RawURL field has been removed; it was a historical artifact.

    The Handle and HandleFunc functions, and the similarly-named methods of ServeMux, now panic if an attempt is made to register the same pattern twice.

    Updating: Running go fix will update the few programs that are affected except for uses of RawURL, which must be fixed by hand.

    The image package

    The image package has had a number of minor changes, rearrangements and renamings.

    Most of the color handling code has been moved into its own package, image/color. For the elements that moved, a symmetry arises; for instance, each pixel of an image.RGBA is a color.RGBA.

    The old image/ycbcr package has been folded, with some renamings, into the image and image/color packages.

    The old image.ColorImage type is still in the image package but has been renamed image.Uniform, while image.Tiled has been removed.

    This table lists the renamings.

    Old New

    image.Color color.Color
    image.ColorModel color.Model
    image.ColorModelFunc color.ModelFunc
    image.PalettedColorModel color.Palette

    image.RGBAColor color.RGBA
    image.RGBA64Color color.RGBA64
    image.NRGBAColor color.NRGBA
    image.NRGBA64Color color.NRGBA64
    image.AlphaColor color.Alpha
    image.Alpha16Color color.Alpha16
    image.GrayColor color.Gray
    image.Gray16Color color.Gray16

    image.RGBAColorModel color.RGBAModel
    image.RGBA64ColorModel color.RGBA64Model
    image.NRGBAColorModel color.NRGBAModel
    image.NRGBA64ColorModel color.NRGBA64Model
    image.AlphaColorModel color.AlphaModel
    image.Alpha16ColorModel color.Alpha16Model
    image.GrayColorModel color.GrayModel
    image.Gray16ColorModel color.Gray16Model

    ycbcr.RGBToYCbCr color.RGBToYCbCr
    ycbcr.YCbCrToRGB color.YCbCrToRGB
    ycbcr.YCbCrColorModel color.YCbCrModel
    ycbcr.YCbCrColor color.YCbCr
    ycbcr.YCbCr image.YCbCr

    ycbcr.SubsampleRatio444 image.YCbCrSubsampleRatio444
    ycbcr.SubsampleRatio422 image.YCbCrSubsampleRatio422
    ycbcr.SubsampleRatio420 image.YCbCrSubsampleRatio420

    image.ColorImage image.Uniform

    The image package's New functions (NewRGBA, NewRGBA64, etc.) take an image.Rectangle as an argument instead of four integers.

    Finally, there are new predefined color.Color variables color.Black, color.White, color.Opaque and color.Transparent.

    Updating: Running go fix will update almost all code affected by the change.

    The log/syslog package

    In Go 1, the syslog.NewLogger function returns an error as well as a log.Logger.

    Updating: What little code is affected will be caught by the compiler and must be updated by hand.

    The mime package

    In Go 1, the FormatMediaType function of the mime package has been simplified to make it consistent with ParseMediaType. It now takes "text/html" rather than "text" and "html".

    Updating: What little code is affected will be caught by the compiler and must be updated by hand.

    The net package

    In Go 1, the various SetTimeout, SetReadTimeout, and SetWriteTimeout methods have been replaced with SetDeadline, SetReadDeadline, and SetWriteDeadline, respectively. Rather than taking a timeout value in nanoseconds that apply to any activity on the connection, the new methods set an absolute deadline (as a time.Time value) after which reads and writes will time out and no longer block.

    There are also new functions net.DialTimeout to simplify timing out dialing a network address and net.ListenMulticastUDP to allow multicast UDP to listen concurrently across multiple listeners. The net.ListenMulticastUDP function replaces the old JoinGroup and LeaveGroup methods.

    Updating: Code that uses the old methods will fail to compile and must be updated by hand. The semantic change makes it difficult for the fix tool to update automatically.

    The os package

    The Time function has been removed; callers should use the Time type from the time package.

    The Exec function has been removed; callers should use Exec from the syscall package, where available.

    The ShellExpand function has been renamed to ExpandEnv.

    The NewFile function now takes a uintptr fd, instead of an int. The Fd method on files now also returns a uintptr.

    There are no longer error constants such as EINVAL in the os package, since the set of values varied with the underlying operating system. There are new portable functions like IsPermission to test common error properties, plus a few new error values with more Go-like names, such as ErrPermission and ErrNoEnv.

    The Getenverror function has been removed. To distinguish between a non-existent environment variable and an empty string, use os.Environ or syscall.Getenv.

    The Process.Wait method has dropped its option argument and the associated constants are gone from the package. Also, the function Wait is gone; only the method of the Process type persists.

    The Waitmsg type returned by Process.Wait has been replaced with a more portable ProcessState type with accessor methods to recover information about the process. Because of changes to Wait, the ProcessState value always describes an exited process. Portability concerns simplified the interface in other ways, but the values returned by the ProcessState.Sys and ProcessState.SysUsage methods can be type-asserted to underlying system-specific data structures such as syscall.WaitStatus and syscall.Rusage on Unix.

    Updating: Running go fix will drop a zero argument to Process.Wait. All other changes will be caught by the compiler and must be updated by hand.

    The os.FileInfo type

    Go 1 redefines the os.FileInfo type, changing it from a struct to an interface:

        type FileInfo interface {
            Name() string       // base name of the file
            Size() int64        // length in bytes
            Mode() FileMode     // file mode bits
            ModTime() time.Time // modification time
            IsDir() bool        // abbreviation for Mode().IsDir()
            Sys() interface{}   // underlying data source (can return nil)
        }
    

    The file mode information has been moved into a subtype called os.FileMode, a simple integer type with IsDir, Perm, and String methods.

    The system-specific details of file modes and properties such as (on Unix) i-number have been removed from FileInfo altogether. Instead, each operating system's os package provides an implementation of the FileInfo interface, which has a Sys method that returns the system-specific representation of file metadata. For instance, to discover the i-number of a file on a Unix system, unpack the FileInfo like this:

        fi, err := os.Stat("hello.go")
        if err != nil {
            log.Fatal(err)
        }
        // Check that it's a Unix file.
        unixStat, ok := fi.Sys().(*syscall.Stat_t)
        if !ok {
            log.Fatal("hello.go: not a Unix file")
        }
        fmt.Printf("file i-number: %d\n", unixStat.Ino)
    

    Assuming (which is unwise) that "hello.go" is a Unix file, the i-number expression could be contracted to

        fi.Sys().(*syscall.Stat_t).Ino
    

    The vast majority of uses of FileInfo need only the methods of the standard interface.

    The os package no longer contains wrappers for the POSIX errors such as ENOENT. For the few programs that need to verify particular error conditions, there are now the boolean functions IsExist, IsNotExist and IsPermission.

        f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
        if os.IsExist(err) {
            log.Printf("%s already exists", name)
        }

    Updating: Running go fix will update code that uses the old equivalent of the current os.FileInfo and os.FileMode API. Code that needs system-specific file details will need to be updated by hand. Code that uses the old POSIX error values from the os package will fail to compile and will also need to be updated by hand.

    The os/signal package

    The os/signal package in Go 1 replaces the Incoming function, which returned a channel that received all incoming signals, with the selective Notify function, which asks for delivery of specific signals on an existing channel.

    Updating: Code must be updated by hand. A literal translation of

    c := signal.Incoming()
    

    is

    c := make(chan os.Signal)
    signal.Notify(c) // ask for all signals
    

    but most code should list the specific signals it wants to handle instead:

    c := make(chan os.Signal)
    signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT)
    

    The path/filepath package

    In Go 1, the Walk function of the path/filepath package has been changed to take a function value of type WalkFunc instead of a Visitor interface value. WalkFunc unifies the handling of both files and directories.

        type WalkFunc func(path string, info os.FileInfo, err error) error
    

    The WalkFunc function will be called even for files or directories that could not be opened; in such cases the error argument will describe the failure. If a directory's contents are to be skipped, the function should return the value filepath.SkipDir

        markFn := func(path string, info os.FileInfo, err error) error {
            if path == "pictures" { // Will skip walking of directory pictures and its contents.
                return filepath.SkipDir
            }
            if err != nil {
                return err
            }
            log.Println(path)
            return nil
        }
        err := filepath.Walk(".", markFn)
        if err != nil {
            log.Fatal(err)
        }

    Updating: The change simplifies most code but has subtle consequences, so affected programs will need to be updated by hand. The compiler will catch code using the old interface.

    The regexp package

    The regexp package has been rewritten. It has the same interface but the specification of the regular expressions it supports has changed from the old "egrep" form to that of RE2.

    Updating: Code that uses the package should have its regular expressions checked by hand.

    The runtime package

    In Go 1, much of the API exported by package runtime has been removed in favor of functionality provided by other packages. Code using the runtime.Type interface or its specific concrete type implementations should now use package reflect. Code using runtime.Semacquire or runtime.Semrelease should use channels or the abstractions in package sync. The runtime.Alloc, runtime.Free, and runtime.Lookup functions, an unsafe API created for debugging the memory allocator, have no replacement.

    Before, runtime.MemStats was a global variable holding statistics about memory allocation, and calls to runtime.UpdateMemStats ensured that it was up to date. In Go 1, runtime.MemStats is a struct type, and code should use runtime.ReadMemStats to obtain the current statistics.

    The package adds a new function, runtime.NumCPU, that returns the number of CPUs available for parallel execution, as reported by the operating system kernel. Its value can inform the setting of GOMAXPROCS. The runtime.Cgocalls and runtime.Goroutines functions have been renamed to runtime.NumCgoCall and runtime.NumGoroutine.

    Updating: Running go fix will update code for the function renamings. Other code will need to be updated by hand.

    The strconv package

    In Go 1, the strconv package has been significantly reworked to make it more Go-like and less C-like, although Atoi lives on (it's similar to int(ParseInt(x, 10, 0)), as does Itoa(x) (FormatInt(int64(x), 10)). There are also new variants of some of the functions that append to byte slices rather than return strings, to allow control over allocation.

    This table summarizes the renamings; see the package documentation for full details.

    Old call New call

    Atob(x) ParseBool(x)

    Atof32(x) ParseFloat(x, 32)§
    Atof64(x) ParseFloat(x, 64)
    AtofN(x, n) ParseFloat(x, n)

    Atoi(x) Atoi(x)
    Atoi(x) ParseInt(x, 10, 0)§
    Atoi64(x) ParseInt(x, 10, 64)

    Atoui(x) ParseUint(x, 10, 0)§
    Atoui64(x) ParseUint(x, 10, 64)

    Btoi64(x, b) ParseInt(x, b, 64)
    Btoui64(x, b) ParseUint(x, b, 64)

    Btoa(x) FormatBool(x)

    Ftoa32(x, f, p) FormatFloat(float64(x), f, p, 32)
    Ftoa64(x, f, p) FormatFloat(x, f, p, 64)
    FtoaN(x, f, p, n) FormatFloat(x, f, p, n)

    Itoa(x) Itoa(x)
    Itoa(x) FormatInt(int64(x), 10)
    Itoa64(x) FormatInt(x, 10)

    Itob(x, b) FormatInt(int64(x), b)
    Itob64(x, b) FormatInt(x, b)

    Uitoa(x) FormatUint(uint64(x), 10)
    Uitoa64(x) FormatUint(x, 10)

    Uitob(x, b) FormatUint(uint64(x), b)
    Uitob64(x, b) FormatUint(x, b)

    Updating: Running go fix will update almost all code affected by the change.
    § Atoi persists but Atoui and Atof32 do not, so they may require a cast that must be added by hand; the go fix tool will warn about it.

    The template packages

    The template and exp/template/html packages have moved to text/template and html/template. More significant, the interface to these packages has been simplified. The template language is the same, but the concept of "template set" is gone and the functions and methods of the packages have changed accordingly, often by elimination.

    Instead of sets, a Template object may contain multiple named template definitions, in effect constructing name spaces for template invocation. A template can invoke any other template associated with it, but only those templates associated with it. The simplest way to associate templates is to parse them together, something made easier with the new structure of the packages.

    Updating: The imports will be updated by fix tool. Single-template uses will be otherwise be largely unaffected. Code that uses multiple templates in concert will need to be updated by hand. The examples in the documentation for text/template can provide guidance.

    The testing package

    The testing package has a type, B, passed as an argument to benchmark functions. In Go 1, B has new methods, analogous to those of T, enabling logging and failure reporting.

    func BenchmarkSprintf(b *testing.B) {
        // Verify correctness before running benchmark.
        b.StopTimer()
        got := fmt.Sprintf("%x", 23)
        const expect = "17"
        if expect != got {
            b.Fatalf("expected %q; got %q", expect, got)
        }
        b.StartTimer()
        for i := 0; i < b.N; i++ {
            fmt.Sprintf("%x", 23)
        }
    }

    Updating: Existing code is unaffected, although benchmarks that use println or panic should be updated to use the new methods.

    The testing/script package

    The testing/script package has been deleted. It was a dreg.

    Updating: No code is likely to be affected.

    The unsafe package

    In Go 1, the functions unsafe.Typeof, unsafe.Reflect, unsafe.Unreflect, unsafe.New, and unsafe.NewArray have been removed; they duplicated safer functionality provided by package reflect.

    Updating: Code using these functions must be rewritten to use package reflect. The changes to encoding/gob and the protocol buffer library may be helpful as examples.

    The url package

    In Go 1 several fields from the url.URL type were removed or replaced.

    The String method now predictably rebuilds an encoded URL string using all of URL's fields as necessary. The resulting string will also no longer have passwords escaped.

    The Raw field has been removed. In most cases the String method may be used in its place.

    The old RawUserinfo field is replaced by the User field, of type *net.Userinfo. Values of this type may be created using the new net.User and net.UserPassword functions. The EscapeUserinfo and UnescapeUserinfo functions are also gone.

    The RawAuthority field has been removed. The same information is available in the Host and User fields.

    The RawPath field and the EncodedPath method have been removed. The path information in rooted URLs (with a slash following the schema) is now available only in decoded form in the Path field. Occasionally, the encoded data may be required to obtain information that was lost in the decoding process. These cases must be handled by accessing the data the URL was built from.

    URLs with non-rooted paths, such as "mailto:dev@golang.org?subject=Hi", are also handled differently. The OpaquePath boolean field has been removed and a new Opaque string field introduced to hold the encoded path for such URLs. In Go 1, the cited URL parses as:

        URL{
            Scheme: "mailto",
            Opaque: "dev@golang.org",
            RawQuery: "subject=Hi",
        }
    

    A new RequestURI method was added to URL.

    The ParseWithReference function has been renamed to ParseWithFragment.

    Updating: Code that uses the old fields will fail to compile and must be updated by hand. The semantic changes make it difficult for the fix tool to update automatically.

    The go command

    Go 1 introduces the go command, a tool for fetching, building, and installing Go packages and commands. The go command does away with makefiles, instead using Go source code to find dependencies and determine build conditions. Most existing Go programs will no longer require makefiles to be built.

    See How to Write Go Code for a primer on the go command and the go command documentation for the full details.

    Updating: Projects that depend on the Go project's old makefile-based build infrastructure (Make.pkg, Make.cmd, and so on) should switch to using the go command for building Go code and, if necessary, rewrite their makefiles to perform any auxiliary build tasks.

    The cgo command

    In Go 1, the cgo command uses a different _cgo_export.h file, which is generated for packages containing //export lines. The _cgo_export.h file now begins with the C preamble comment, so that exported function definitions can use types defined there. This has the effect of compiling the preamble multiple times, so a package using //export must not put function definitions or variable initializations in the C preamble.

    Packaged releases

    One of the most significant changes associated with Go 1 is the availability of prepackaged, downloadable distributions. They are available for many combinations of architecture and operating system (including Windows) and the list will grow. Installation details are described on the Getting Started page, while the distributions themselves are listed on the downloads page.

    lxd-2.0.11/dist/src/golang.org/x/net/html/render_test.go0000644061062106075000000000544513172163402024134 0ustar stgraberdomain admins// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "bytes" "testing" ) func TestRenderer(t *testing.T) { nodes := [...]*Node{ 0: { Type: ElementNode, Data: "html", }, 1: { Type: ElementNode, Data: "head", }, 2: { Type: ElementNode, Data: "body", }, 3: { Type: TextNode, Data: "0<1", }, 4: { Type: ElementNode, Data: "p", Attr: []Attribute{ { Key: "id", Val: "A", }, { Key: "foo", Val: `abc"def`, }, }, }, 5: { Type: TextNode, Data: "2", }, 6: { Type: ElementNode, Data: "b", Attr: []Attribute{ { Key: "empty", Val: "", }, }, }, 7: { Type: TextNode, Data: "3", }, 8: { Type: ElementNode, Data: "i", Attr: []Attribute{ { Key: "backslash", Val: `\`, }, }, }, 9: { Type: TextNode, Data: "&4", }, 10: { Type: TextNode, Data: "5", }, 11: { Type: ElementNode, Data: "blockquote", }, 12: { Type: ElementNode, Data: "br", }, 13: { Type: TextNode, Data: "6", }, } // Build a tree out of those nodes, based on a textual representation. // Only the ".\t"s are significant. The trailing HTML-like text is // just commentary. The "0:" prefixes are for easy cross-reference with // the nodes array. treeAsText := [...]string{ 0: ``, 1: `. `, 2: `. `, 3: `. . "0<1"`, 4: `. .

    `, 5: `. . . "2"`, 6: `. . . `, 7: `. . . . "3"`, 8: `. . . `, 9: `. . . . "&4"`, 10: `. . "5"`, 11: `. .

    `, 12: `. .
    `, 13: `. . "6"`, } if len(nodes) != len(treeAsText) { t.Fatal("len(nodes) != len(treeAsText)") } var stack [8]*Node for i, line := range treeAsText { level := 0 for line[0] == '.' { // Strip a leading ".\t". line = line[2:] level++ } n := nodes[i] if level == 0 { if stack[0] != nil { t.Fatal("multiple root nodes") } stack[0] = n } else { stack[level-1].AppendChild(n) stack[level] = n for i := level + 1; i < len(stack); i++ { stack[i] = nil } } // At each stage of tree construction, we check all nodes for consistency. for j, m := range nodes { if err := checkNodeConsistency(m); err != nil { t.Fatalf("i=%d, j=%d: %v", i, j, err) } } } want := `0<1

    ` + `23&4

    ` + `5

    6` b := new(bytes.Buffer) if err := Render(b, nodes[0]); err != nil { t.Fatal(err) } if got := b.String(); got != want { t.Errorf("got vs want:\n%s\n%s\n", got, want) } } lxd-2.0.11/dist/src/golang.org/x/net/html/render.go0000644061062106075000000001562613172163402023077 0ustar stgraberdomain admins// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "bufio" "errors" "fmt" "io" "strings" ) type writer interface { io.Writer io.ByteWriter WriteString(string) (int, error) } // Render renders the parse tree n to the given writer. // // Rendering is done on a 'best effort' basis: calling Parse on the output of // Render will always result in something similar to the original tree, but it // is not necessarily an exact clone unless the original tree was 'well-formed'. // 'Well-formed' is not easily specified; the HTML5 specification is // complicated. // // Calling Parse on arbitrary input typically results in a 'well-formed' parse // tree. However, it is possible for Parse to yield a 'badly-formed' parse tree. // For example, in a 'well-formed' parse tree, no element is a child of // another element: parsing "" results in two sibling elements. // Similarly, in a 'well-formed' parse tree, no element is a child of a // element: parsing "

    " results in a

    with two sibling // children; the is reparented to the

    's parent. However, calling // Parse on "
    " does not return an error, but the result has an // element with an child, and is therefore not 'well-formed'. // // Programmatically constructed trees are typically also 'well-formed', but it // is possible to construct a tree that looks innocuous but, when rendered and // re-parsed, results in a different tree. A simple example is that a solitary // text node would become a tree containing , and elements. // Another example is that the programmatic equivalent of "abc" // becomes "abc". func Render(w io.Writer, n *Node) error { if x, ok := w.(writer); ok { return render(x, n) } buf := bufio.NewWriter(w) if err := render(buf, n); err != nil { return err } return buf.Flush() } // plaintextAbort is returned from render1 when a element // has been rendered. No more end tags should be rendered after that. var plaintextAbort = errors.New("html: internal error (plaintext abort)") func render(w writer, n *Node) error { err := render1(w, n) if err == plaintextAbort { err = nil } return err } func render1(w writer, n *Node) error { // Render non-element nodes; these are the easy cases. switch n.Type { case ErrorNode: return errors.New("html: cannot render an ErrorNode node") case TextNode: return escape(w, n.Data) case DocumentNode: for c := n.FirstChild; c != nil; c = c.NextSibling { if err := render1(w, c); err != nil { return err } } return nil case ElementNode: // No-op. case CommentNode: if _, err := w.WriteString("<!--"); err != nil { return err } if _, err := w.WriteString(n.Data); err != nil { return err } if _, err := w.WriteString("-->"); err != nil { return err } return nil case DoctypeNode: if _, err := w.WriteString("<!DOCTYPE "); err != nil { return err } if _, err := w.WriteString(n.Data); err != nil { return err } if n.Attr != nil { var p, s string for _, a := range n.Attr { switch a.Key { case "public": p = a.Val case "system": s = a.Val } } if p != "" { if _, err := w.WriteString(" PUBLIC "); err != nil { return err } if err := writeQuoted(w, p); err != nil { return err } if s != "" { if err := w.WriteByte(' '); err != nil { return err } if err := writeQuoted(w, s); err != nil { return err } } } else if s != "" { if _, err := w.WriteString(" SYSTEM "); err != nil { return err } if err := writeQuoted(w, s); err != nil { return err } } } return w.WriteByte('>') default: return errors.New("html: unknown node type") } // Render the <xxx> opening tag. if err := w.WriteByte('<'); err != nil { return err } if _, err := w.WriteString(n.Data); err != nil { return err } for _, a := range n.Attr { if err := w.WriteByte(' '); err != nil { return err } if a.Namespace != "" { if _, err := w.WriteString(a.Namespace); err != nil { return err } if err := w.WriteByte(':'); err != nil { return err } } if _, err := w.WriteString(a.Key); err != nil { return err } if _, err := w.WriteString(`="`); err != nil { return err } if err := escape(w, a.Val); err != nil { return err } if err := w.WriteByte('"'); err != nil { return err } } if voidElements[n.Data] { if n.FirstChild != nil { return fmt.Errorf("html: void element <%s> has child nodes", n.Data) } _, err := w.WriteString("/>") return err } if err := w.WriteByte('>'); err != nil { return err } // Add initial newline where there is danger of a newline beging ignored. if c := n.FirstChild; c != nil && c.Type == TextNode && strings.HasPrefix(c.Data, "\n") { switch n.Data { case "pre", "listing", "textarea": if err := w.WriteByte('\n'); err != nil { return err } } } // Render any child nodes. switch n.Data { case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "xmp": for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type == TextNode { if _, err := w.WriteString(c.Data); err != nil { return err } } else { if err := render1(w, c); err != nil { return err } } } if n.Data == "plaintext" { // Don't render anything else. <plaintext> must be the // last element in the file, with no closing tag. return plaintextAbort } default: for c := n.FirstChild; c != nil; c = c.NextSibling { if err := render1(w, c); err != nil { return err } } } // Render the </xxx> closing tag. if _, err := w.WriteString("</"); err != nil { return err } if _, err := w.WriteString(n.Data); err != nil { return err } return w.WriteByte('>') } // writeQuoted writes s to w surrounded by quotes. Normally it will use double // quotes, but if s contains a double quote, it will use single quotes. // It is used for writing the identifiers in a doctype declaration. // In valid HTML, they can't contain both types of quotes. func writeQuoted(w writer, s string) error { var q byte = '"' if strings.Contains(s, `"`) { q = '\'' } if err := w.WriteByte(q); err != nil { return err } if _, err := w.WriteString(s); err != nil { return err } if err := w.WriteByte(q); err != nil { return err } return nil } // Section 12.1.2, "Elements", gives this list of void elements. Void elements // are those that can't have any contents. var voidElements = map[string]bool{ "area": true, "base": true, "br": true, "col": true, "command": true, "embed": true, "hr": true, "img": true, "input": true, "keygen": true, "link": true, "meta": true, "param": true, "source": true, "track": true, "wbr": true, } ����������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/parse_test.go���������������������������������������������0000644�0610621�0607500�00000023635�13172163402�023770� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "bufio" "bytes" "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "runtime" "sort" "strings" "testing" "golang.org/x/net/html/atom" ) // readParseTest reads a single test case from r. func readParseTest(r *bufio.Reader) (text, want, context string, err error) { line, err := r.ReadSlice('\n') if err != nil { return "", "", "", err } var b []byte // Read the HTML. if string(line) != "#data\n" { return "", "", "", fmt.Errorf(`got %q want "#data\n"`, line) } for { line, err = r.ReadSlice('\n') if err != nil { return "", "", "", err } if line[0] == '#' { break } b = append(b, line...) } text = strings.TrimSuffix(string(b), "\n") b = b[:0] // Skip the error list. if string(line) != "#errors\n" { return "", "", "", fmt.Errorf(`got %q want "#errors\n"`, line) } for { line, err = r.ReadSlice('\n') if err != nil { return "", "", "", err } if line[0] == '#' { break } } if string(line) == "#document-fragment\n" { line, err = r.ReadSlice('\n') if err != nil { return "", "", "", err } context = strings.TrimSpace(string(line)) line, err = r.ReadSlice('\n') if err != nil { return "", "", "", err } } // Read the dump of what the parse tree should be. if string(line) != "#document\n" { return "", "", "", fmt.Errorf(`got %q want "#document\n"`, line) } inQuote := false for { line, err = r.ReadSlice('\n') if err != nil && err != io.EOF { return "", "", "", err } trimmed := bytes.Trim(line, "| \n") if len(trimmed) > 0 { if line[0] == '|' && trimmed[0] == '"' { inQuote = true } if trimmed[len(trimmed)-1] == '"' && !(line[0] == '|' && len(trimmed) == 1) { inQuote = false } } if len(line) == 0 || len(line) == 1 && line[0] == '\n' && !inQuote { break } b = append(b, line...) } return text, string(b), context, nil } func dumpIndent(w io.Writer, level int) { io.WriteString(w, "| ") for i := 0; i < level; i++ { io.WriteString(w, " ") } } type sortedAttributes []Attribute func (a sortedAttributes) Len() int { return len(a) } func (a sortedAttributes) Less(i, j int) bool { if a[i].Namespace != a[j].Namespace { return a[i].Namespace < a[j].Namespace } return a[i].Key < a[j].Key } func (a sortedAttributes) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func dumpLevel(w io.Writer, n *Node, level int) error { dumpIndent(w, level) switch n.Type { case ErrorNode: return errors.New("unexpected ErrorNode") case DocumentNode: return errors.New("unexpected DocumentNode") case ElementNode: if n.Namespace != "" { fmt.Fprintf(w, "<%s %s>", n.Namespace, n.Data) } else { fmt.Fprintf(w, "<%s>", n.Data) } attr := sortedAttributes(n.Attr) sort.Sort(attr) for _, a := range attr { io.WriteString(w, "\n") dumpIndent(w, level+1) if a.Namespace != "" { fmt.Fprintf(w, `%s %s="%s"`, a.Namespace, a.Key, a.Val) } else { fmt.Fprintf(w, `%s="%s"`, a.Key, a.Val) } } case TextNode: fmt.Fprintf(w, `"%s"`, n.Data) case CommentNode: fmt.Fprintf(w, "<!-- %s -->", n.Data) case DoctypeNode: fmt.Fprintf(w, "<!DOCTYPE %s", n.Data) if n.Attr != nil { var p, s string for _, a := range n.Attr { switch a.Key { case "public": p = a.Val case "system": s = a.Val } } if p != "" || s != "" { fmt.Fprintf(w, ` "%s"`, p) fmt.Fprintf(w, ` "%s"`, s) } } io.WriteString(w, ">") case scopeMarkerNode: return errors.New("unexpected scopeMarkerNode") default: return errors.New("unknown node type") } io.WriteString(w, "\n") for c := n.FirstChild; c != nil; c = c.NextSibling { if err := dumpLevel(w, c, level+1); err != nil { return err } } return nil } func dump(n *Node) (string, error) { if n == nil || n.FirstChild == nil { return "", nil } var b bytes.Buffer for c := n.FirstChild; c != nil; c = c.NextSibling { if err := dumpLevel(&b, c, 0); err != nil { return "", err } } return b.String(), nil } const testDataDir = "testdata/webkit/" func TestParser(t *testing.T) { testFiles, err := filepath.Glob(testDataDir + "*.dat") if err != nil { t.Fatal(err) } for _, tf := range testFiles { f, err := os.Open(tf) if err != nil { t.Fatal(err) } defer f.Close() r := bufio.NewReader(f) for i := 0; ; i++ { text, want, context, err := readParseTest(r) if err == io.EOF { break } if err != nil { t.Fatal(err) } err = testParseCase(text, want, context) if err != nil { t.Errorf("%s test #%d %q, %s", tf, i, text, err) } } } } // testParseCase tests one test case from the test files. If the test does not // pass, it returns an error that explains the failure. // text is the HTML to be parsed, want is a dump of the correct parse tree, // and context is the name of the context node, if any. func testParseCase(text, want, context string) (err error) { defer func() { if x := recover(); x != nil { switch e := x.(type) { case error: err = e default: err = fmt.Errorf("%v", e) } } }() var doc *Node if context == "" { doc, err = Parse(strings.NewReader(text)) if err != nil { return err } } else { contextNode := &Node{ Type: ElementNode, DataAtom: atom.Lookup([]byte(context)), Data: context, } nodes, err := ParseFragment(strings.NewReader(text), contextNode) if err != nil { return err } doc = &Node{ Type: DocumentNode, } for _, n := range nodes { doc.AppendChild(n) } } if err := checkTreeConsistency(doc); err != nil { return err } got, err := dump(doc) if err != nil { return err } // Compare the parsed tree to the #document section. if got != want { return fmt.Errorf("got vs want:\n----\n%s----\n%s----", got, want) } if renderTestBlacklist[text] || context != "" { return nil } // Check that rendering and re-parsing results in an identical tree. pr, pw := io.Pipe() go func() { pw.CloseWithError(Render(pw, doc)) }() doc1, err := Parse(pr) if err != nil { return err } got1, err := dump(doc1) if err != nil { return err } if got != got1 { return fmt.Errorf("got vs got1:\n----\n%s----\n%s----", got, got1) } return nil } // Some test input result in parse trees are not 'well-formed' despite // following the HTML5 recovery algorithms. Rendering and re-parsing such a // tree will not result in an exact clone of that tree. We blacklist such // inputs from the render test. var renderTestBlacklist = map[string]bool{ // The second <a> will be reparented to the first <table>'s parent. This // results in an <a> whose parent is an <a>, which is not 'well-formed'. `<a><table><td><a><table></table><a></tr><a></table><b>X</b>C<a>Y`: true, // The same thing with a <p>: `<p><table></p>`: true, // More cases of <a> being reparented: `<a href="blah">aba<table><a href="foo">br<tr><td></td></tr>x</table>aoe`: true, `<a><table><a></table><p><a><div><a>`: true, `<a><table><td><a><table></table><a></tr><a></table><a>`: true, // A similar reparenting situation involving <nobr>: `<!DOCTYPE html><body><b><nobr>1<table><nobr></b><i><nobr>2<nobr></i>3`: true, // A <plaintext> element is reparented, putting it before a table. // A <plaintext> element can't have anything after it in HTML. `<table><plaintext><td>`: true, `<!doctype html><table><plaintext></plaintext>`: true, `<!doctype html><table><tbody><plaintext></plaintext>`: true, `<!doctype html><table><tbody><tr><plaintext></plaintext>`: true, // A form inside a table inside a form doesn't work either. `<!doctype html><form><table></form><form></table></form>`: true, // A script that ends at EOF may escape its own closing tag when rendered. `<!doctype html><script><!--<script `: true, `<!doctype html><script><!--<script <`: true, `<!doctype html><script><!--<script <a`: true, `<!doctype html><script><!--<script </`: true, `<!doctype html><script><!--<script </s`: true, `<!doctype html><script><!--<script </script`: true, `<!doctype html><script><!--<script </scripta`: true, `<!doctype html><script><!--<script -`: true, `<!doctype html><script><!--<script -a`: true, `<!doctype html><script><!--<script -<`: true, `<!doctype html><script><!--<script --`: true, `<!doctype html><script><!--<script --a`: true, `<!doctype html><script><!--<script --<`: true, `<script><!--<script `: true, `<script><!--<script <a`: true, `<script><!--<script </script`: true, `<script><!--<script </scripta`: true, `<script><!--<script -`: true, `<script><!--<script -a`: true, `<script><!--<script --`: true, `<script><!--<script --a`: true, `<script><!--<script <`: true, `<script><!--<script </`: true, `<script><!--<script </s`: true, // Reconstructing the active formatting elements results in a <plaintext> // element that contains an <a> element. `<!doctype html><p><a><plaintext>b`: true, } func TestNodeConsistency(t *testing.T) { // inconsistentNode is a Node whose DataAtom and Data do not agree. inconsistentNode := &Node{ Type: ElementNode, DataAtom: atom.Frameset, Data: "table", } _, err := ParseFragment(strings.NewReader("<p>hello</p>"), inconsistentNode) if err == nil { t.Errorf("got nil error, want non-nil") } } func BenchmarkParser(b *testing.B) { buf, err := ioutil.ReadFile("testdata/go1.html") if err != nil { b.Fatalf("could not read testdata/go1.html: %v", err) } b.SetBytes(int64(len(buf))) runtime.GC() b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { Parse(bytes.NewBuffer(buf)) } } ���������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/parse.go��������������������������������������������������0000644�0610621�0607500�00000140162�13172163402�022724� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "errors" "fmt" "io" "strings" a "golang.org/x/net/html/atom" ) // A parser implements the HTML5 parsing algorithm: // https://html.spec.whatwg.org/multipage/syntax.html#tree-construction type parser struct { // tokenizer provides the tokens for the parser. tokenizer *Tokenizer // tok is the most recently read token. tok Token // Self-closing tags like <hr/> are treated as start tags, except that // hasSelfClosingToken is set while they are being processed. hasSelfClosingToken bool // doc is the document root element. doc *Node // The stack of open elements (section 12.2.3.2) and active formatting // elements (section 12.2.3.3). oe, afe nodeStack // Element pointers (section 12.2.3.4). head, form *Node // Other parsing state flags (section 12.2.3.5). scripting, framesetOK bool // im is the current insertion mode. im insertionMode // originalIM is the insertion mode to go back to after completing a text // or inTableText insertion mode. originalIM insertionMode // fosterParenting is whether new elements should be inserted according to // the foster parenting rules (section 12.2.5.3). fosterParenting bool // quirks is whether the parser is operating in "quirks mode." quirks bool // fragment is whether the parser is parsing an HTML fragment. fragment bool // context is the context element when parsing an HTML fragment // (section 12.4). context *Node } func (p *parser) top() *Node { if n := p.oe.top(); n != nil { return n } return p.doc } // Stop tags for use in popUntil. These come from section 12.2.3.2. var ( defaultScopeStopTags = map[string][]a.Atom{ "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template}, "math": {a.AnnotationXml, a.Mi, a.Mn, a.Mo, a.Ms, a.Mtext}, "svg": {a.Desc, a.ForeignObject, a.Title}, } ) type scope int const ( defaultScope scope = iota listItemScope buttonScope tableScope tableRowScope tableBodyScope selectScope ) // popUntil pops the stack of open elements at the highest element whose tag // is in matchTags, provided there is no higher element in the scope's stop // tags (as defined in section 12.2.3.2). It returns whether or not there was // such an element. If there was not, popUntil leaves the stack unchanged. // // For example, the set of stop tags for table scope is: "html", "table". If // the stack was: // ["html", "body", "font", "table", "b", "i", "u"] // then popUntil(tableScope, "font") would return false, but // popUntil(tableScope, "i") would return true and the stack would become: // ["html", "body", "font", "table", "b"] // // If an element's tag is in both the stop tags and matchTags, then the stack // will be popped and the function returns true (provided, of course, there was // no higher element in the stack that was also in the stop tags). For example, // popUntil(tableScope, "table") returns true and leaves: // ["html", "body", "font"] func (p *parser) popUntil(s scope, matchTags ...a.Atom) bool { if i := p.indexOfElementInScope(s, matchTags...); i != -1 { p.oe = p.oe[:i] return true } return false } // indexOfElementInScope returns the index in p.oe of the highest element whose // tag is in matchTags that is in scope. If no matching element is in scope, it // returns -1. func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { for i := len(p.oe) - 1; i >= 0; i-- { tagAtom := p.oe[i].DataAtom if p.oe[i].Namespace == "" { for _, t := range matchTags { if t == tagAtom { return i } } switch s { case defaultScope: // No-op. case listItemScope: if tagAtom == a.Ol || tagAtom == a.Ul { return -1 } case buttonScope: if tagAtom == a.Button { return -1 } case tableScope: if tagAtom == a.Html || tagAtom == a.Table { return -1 } case selectScope: if tagAtom != a.Optgroup && tagAtom != a.Option { return -1 } default: panic("unreachable") } } switch s { case defaultScope, listItemScope, buttonScope: for _, t := range defaultScopeStopTags[p.oe[i].Namespace] { if t == tagAtom { return -1 } } } } return -1 } // elementInScope is like popUntil, except that it doesn't modify the stack of // open elements. func (p *parser) elementInScope(s scope, matchTags ...a.Atom) bool { return p.indexOfElementInScope(s, matchTags...) != -1 } // clearStackToContext pops elements off the stack of open elements until a // scope-defined element is found. func (p *parser) clearStackToContext(s scope) { for i := len(p.oe) - 1; i >= 0; i-- { tagAtom := p.oe[i].DataAtom switch s { case tableScope: if tagAtom == a.Html || tagAtom == a.Table { p.oe = p.oe[:i+1] return } case tableRowScope: if tagAtom == a.Html || tagAtom == a.Tr { p.oe = p.oe[:i+1] return } case tableBodyScope: if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead { p.oe = p.oe[:i+1] return } default: panic("unreachable") } } } // generateImpliedEndTags pops nodes off the stack of open elements as long as // the top node has a tag name of dd, dt, li, option, optgroup, p, rp, or rt. // If exceptions are specified, nodes with that name will not be popped off. func (p *parser) generateImpliedEndTags(exceptions ...string) { var i int loop: for i = len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] if n.Type == ElementNode { switch n.DataAtom { case a.Dd, a.Dt, a.Li, a.Option, a.Optgroup, a.P, a.Rp, a.Rt: for _, except := range exceptions { if n.Data == except { break loop } } continue } } break } p.oe = p.oe[:i+1] } // addChild adds a child node n to the top element, and pushes n onto the stack // of open elements if it is an element node. func (p *parser) addChild(n *Node) { if p.shouldFosterParent() { p.fosterParent(n) } else { p.top().AppendChild(n) } if n.Type == ElementNode { p.oe = append(p.oe, n) } } // shouldFosterParent returns whether the next node to be added should be // foster parented. func (p *parser) shouldFosterParent() bool { if p.fosterParenting { switch p.top().DataAtom { case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: return true } } return false } // fosterParent adds a child node according to the foster parenting rules. // Section 12.2.5.3, "foster parenting". func (p *parser) fosterParent(n *Node) { var table, parent, prev *Node var i int for i = len(p.oe) - 1; i >= 0; i-- { if p.oe[i].DataAtom == a.Table { table = p.oe[i] break } } if table == nil { // The foster parent is the html element. parent = p.oe[0] } else { parent = table.Parent } if parent == nil { parent = p.oe[i-1] } if table != nil { prev = table.PrevSibling } else { prev = parent.LastChild } if prev != nil && prev.Type == TextNode && n.Type == TextNode { prev.Data += n.Data return } parent.InsertBefore(n, table) } // addText adds text to the preceding node if it is a text node, or else it // calls addChild with a new text node. func (p *parser) addText(text string) { if text == "" { return } if p.shouldFosterParent() { p.fosterParent(&Node{ Type: TextNode, Data: text, }) return } t := p.top() if n := t.LastChild; n != nil && n.Type == TextNode { n.Data += text return } p.addChild(&Node{ Type: TextNode, Data: text, }) } // addElement adds a child element based on the current token. func (p *parser) addElement() { p.addChild(&Node{ Type: ElementNode, DataAtom: p.tok.DataAtom, Data: p.tok.Data, Attr: p.tok.Attr, }) } // Section 12.2.3.3. func (p *parser) addFormattingElement() { tagAtom, attr := p.tok.DataAtom, p.tok.Attr p.addElement() // Implement the Noah's Ark clause, but with three per family instead of two. identicalElements := 0 findIdenticalElements: for i := len(p.afe) - 1; i >= 0; i-- { n := p.afe[i] if n.Type == scopeMarkerNode { break } if n.Type != ElementNode { continue } if n.Namespace != "" { continue } if n.DataAtom != tagAtom { continue } if len(n.Attr) != len(attr) { continue } compareAttributes: for _, t0 := range n.Attr { for _, t1 := range attr { if t0.Key == t1.Key && t0.Namespace == t1.Namespace && t0.Val == t1.Val { // Found a match for this attribute, continue with the next attribute. continue compareAttributes } } // If we get here, there is no attribute that matches a. // Therefore the element is not identical to the new one. continue findIdenticalElements } identicalElements++ if identicalElements >= 3 { p.afe.remove(n) } } p.afe = append(p.afe, p.top()) } // Section 12.2.3.3. func (p *parser) clearActiveFormattingElements() { for { n := p.afe.pop() if len(p.afe) == 0 || n.Type == scopeMarkerNode { return } } } // Section 12.2.3.3. func (p *parser) reconstructActiveFormattingElements() { n := p.afe.top() if n == nil { return } if n.Type == scopeMarkerNode || p.oe.index(n) != -1 { return } i := len(p.afe) - 1 for n.Type != scopeMarkerNode && p.oe.index(n) == -1 { if i == 0 { i = -1 break } i-- n = p.afe[i] } for { i++ clone := p.afe[i].clone() p.addChild(clone) p.afe[i] = clone if i == len(p.afe)-1 { break } } } // Section 12.2.4. func (p *parser) acknowledgeSelfClosingTag() { p.hasSelfClosingToken = false } // An insertion mode (section 12.2.3.1) is the state transition function from // a particular state in the HTML5 parser's state machine. It updates the // parser's fields depending on parser.tok (where ErrorToken means EOF). // It returns whether the token was consumed. type insertionMode func(*parser) bool // setOriginalIM sets the insertion mode to return to after completing a text or // inTableText insertion mode. // Section 12.2.3.1, "using the rules for". func (p *parser) setOriginalIM() { if p.originalIM != nil { panic("html: bad parser state: originalIM was set twice") } p.originalIM = p.im } // Section 12.2.3.1, "reset the insertion mode". func (p *parser) resetInsertionMode() { for i := len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] if i == 0 && p.context != nil { n = p.context } switch n.DataAtom { case a.Select: p.im = inSelectIM case a.Td, a.Th: p.im = inCellIM case a.Tr: p.im = inRowIM case a.Tbody, a.Thead, a.Tfoot: p.im = inTableBodyIM case a.Caption: p.im = inCaptionIM case a.Colgroup: p.im = inColumnGroupIM case a.Table: p.im = inTableIM case a.Head: p.im = inBodyIM case a.Body: p.im = inBodyIM case a.Frameset: p.im = inFramesetIM case a.Html: p.im = beforeHeadIM default: continue } return } p.im = inBodyIM } const whitespace = " \t\r\n\f" // Section 12.2.5.4.1. func initialIM(p *parser) bool { switch p.tok.Type { case TextToken: p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) if len(p.tok.Data) == 0 { // It was all whitespace, so ignore it. return true } case CommentToken: p.doc.AppendChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: n, quirks := parseDoctype(p.tok.Data) p.doc.AppendChild(n) p.quirks = quirks p.im = beforeHTMLIM return true } p.quirks = true p.im = beforeHTMLIM return false } // Section 12.2.5.4.2. func beforeHTMLIM(p *parser) bool { switch p.tok.Type { case DoctypeToken: // Ignore the token. return true case TextToken: p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) if len(p.tok.Data) == 0 { // It was all whitespace, so ignore it. return true } case StartTagToken: if p.tok.DataAtom == a.Html { p.addElement() p.im = beforeHeadIM return true } case EndTagToken: switch p.tok.DataAtom { case a.Head, a.Body, a.Html, a.Br: p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) return false default: // Ignore the token. return true } case CommentToken: p.doc.AppendChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true } p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) return false } // Section 12.2.5.4.3. func beforeHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) if len(p.tok.Data) == 0 { // It was all whitespace, so ignore it. return true } case StartTagToken: switch p.tok.DataAtom { case a.Head: p.addElement() p.head = p.top() p.im = inHeadIM return true case a.Html: return inBodyIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Head, a.Body, a.Html, a.Br: p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) return false default: // Ignore the token. return true } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: // Ignore the token. return true } p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) return false } // Section 12.2.5.4.4. func inHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: s := strings.TrimLeft(p.tok.Data, whitespace) if len(s) < len(p.tok.Data) { // Add the initial whitespace to the current node. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) if s == "" { return true } p.tok.Data = s } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta: p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() return true case a.Script, a.Title, a.Noscript, a.Noframes, a.Style: p.addElement() p.setOriginalIM() p.im = textIM return true case a.Head: // Ignore the token. return true } case EndTagToken: switch p.tok.DataAtom { case a.Head: n := p.oe.pop() if n.DataAtom != a.Head { panic("html: bad parser state: <head> element not found, in the in-head insertion mode") } p.im = afterHeadIM return true case a.Body, a.Html, a.Br: p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) return false default: // Ignore the token. return true } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: // Ignore the token. return true } p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) return false } // Section 12.2.5.4.6. func afterHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: s := strings.TrimLeft(p.tok.Data, whitespace) if len(s) < len(p.tok.Data) { // Add the initial whitespace to the current node. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) if s == "" { return true } p.tok.Data = s } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Body: p.addElement() p.framesetOK = false p.im = inBodyIM return true case a.Frameset: p.addElement() p.im = inFramesetIM return true case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title: p.oe = append(p.oe, p.head) defer p.oe.remove(p.head) return inHeadIM(p) case a.Head: // Ignore the token. return true } case EndTagToken: switch p.tok.DataAtom { case a.Body, a.Html, a.Br: // Drop down to creating an implied <body> tag. default: // Ignore the token. return true } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: // Ignore the token. return true } p.parseImpliedToken(StartTagToken, a.Body, a.Body.String()) p.framesetOK = true return false } // copyAttributes copies attributes of src not found on dst to dst. func copyAttributes(dst *Node, src Token) { if len(src.Attr) == 0 { return } attr := map[string]string{} for _, t := range dst.Attr { attr[t.Key] = t.Val } for _, t := range src.Attr { if _, ok := attr[t.Key]; !ok { dst.Attr = append(dst.Attr, t) attr[t.Key] = t.Val } } } // Section 12.2.5.4.7. func inBodyIM(p *parser) bool { switch p.tok.Type { case TextToken: d := p.tok.Data switch n := p.oe.top(); n.DataAtom { case a.Pre, a.Listing: if n.FirstChild == nil { // Ignore a newline at the start of a <pre> block. if d != "" && d[0] == '\r' { d = d[1:] } if d != "" && d[0] == '\n' { d = d[1:] } } } d = strings.Replace(d, "\x00", "", -1) if d == "" { return true } p.reconstructActiveFormattingElements() p.addText(d) if p.framesetOK && strings.TrimLeft(d, whitespace) != "" { // There were non-whitespace characters inserted. p.framesetOK = false } case StartTagToken: switch p.tok.DataAtom { case a.Html: copyAttributes(p.oe[0], p.tok) case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title: return inHeadIM(p) case a.Body: if len(p.oe) >= 2 { body := p.oe[1] if body.Type == ElementNode && body.DataAtom == a.Body { p.framesetOK = false copyAttributes(body, p.tok) } } case a.Frameset: if !p.framesetOK || len(p.oe) < 2 || p.oe[1].DataAtom != a.Body { // Ignore the token. return true } body := p.oe[1] if body.Parent != nil { body.Parent.RemoveChild(body) } p.oe = p.oe[:1] p.addElement() p.im = inFramesetIM return true case a.Address, a.Article, a.Aside, a.Blockquote, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Menu, a.Nav, a.Ol, a.P, a.Section, a.Summary, a.Ul: p.popUntil(buttonScope, a.P) p.addElement() case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6: p.popUntil(buttonScope, a.P) switch n := p.top(); n.DataAtom { case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6: p.oe.pop() } p.addElement() case a.Pre, a.Listing: p.popUntil(buttonScope, a.P) p.addElement() // The newline, if any, will be dealt with by the TextToken case. p.framesetOK = false case a.Form: if p.form == nil { p.popUntil(buttonScope, a.P) p.addElement() p.form = p.top() } case a.Li: p.framesetOK = false for i := len(p.oe) - 1; i >= 0; i-- { node := p.oe[i] switch node.DataAtom { case a.Li: p.oe = p.oe[:i] case a.Address, a.Div, a.P: continue default: if !isSpecialElement(node) { continue } } break } p.popUntil(buttonScope, a.P) p.addElement() case a.Dd, a.Dt: p.framesetOK = false for i := len(p.oe) - 1; i >= 0; i-- { node := p.oe[i] switch node.DataAtom { case a.Dd, a.Dt: p.oe = p.oe[:i] case a.Address, a.Div, a.P: continue default: if !isSpecialElement(node) { continue } } break } p.popUntil(buttonScope, a.P) p.addElement() case a.Plaintext: p.popUntil(buttonScope, a.P) p.addElement() case a.Button: p.popUntil(defaultScope, a.Button) p.reconstructActiveFormattingElements() p.addElement() p.framesetOK = false case a.A: for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- { if n := p.afe[i]; n.Type == ElementNode && n.DataAtom == a.A { p.inBodyEndTagFormatting(a.A) p.oe.remove(n) p.afe.remove(n) break } } p.reconstructActiveFormattingElements() p.addFormattingElement() case a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U: p.reconstructActiveFormattingElements() p.addFormattingElement() case a.Nobr: p.reconstructActiveFormattingElements() if p.elementInScope(defaultScope, a.Nobr) { p.inBodyEndTagFormatting(a.Nobr) p.reconstructActiveFormattingElements() } p.addFormattingElement() case a.Applet, a.Marquee, a.Object: p.reconstructActiveFormattingElements() p.addElement() p.afe = append(p.afe, &scopeMarker) p.framesetOK = false case a.Table: if !p.quirks { p.popUntil(buttonScope, a.P) } p.addElement() p.framesetOK = false p.im = inTableIM return true case a.Area, a.Br, a.Embed, a.Img, a.Input, a.Keygen, a.Wbr: p.reconstructActiveFormattingElements() p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() if p.tok.DataAtom == a.Input { for _, t := range p.tok.Attr { if t.Key == "type" { if strings.ToLower(t.Val) == "hidden" { // Skip setting framesetOK = false return true } } } } p.framesetOK = false case a.Param, a.Source, a.Track: p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() case a.Hr: p.popUntil(buttonScope, a.P) p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() p.framesetOK = false case a.Image: p.tok.DataAtom = a.Img p.tok.Data = a.Img.String() return false case a.Isindex: if p.form != nil { // Ignore the token. return true } action := "" prompt := "This is a searchable index. Enter search keywords: " attr := []Attribute{{Key: "name", Val: "isindex"}} for _, t := range p.tok.Attr { switch t.Key { case "action": action = t.Val case "name": // Ignore the attribute. case "prompt": prompt = t.Val default: attr = append(attr, t) } } p.acknowledgeSelfClosingTag() p.popUntil(buttonScope, a.P) p.parseImpliedToken(StartTagToken, a.Form, a.Form.String()) if action != "" { p.form.Attr = []Attribute{{Key: "action", Val: action}} } p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String()) p.parseImpliedToken(StartTagToken, a.Label, a.Label.String()) p.addText(prompt) p.addChild(&Node{ Type: ElementNode, DataAtom: a.Input, Data: a.Input.String(), Attr: attr, }) p.oe.pop() p.parseImpliedToken(EndTagToken, a.Label, a.Label.String()) p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String()) p.parseImpliedToken(EndTagToken, a.Form, a.Form.String()) case a.Textarea: p.addElement() p.setOriginalIM() p.framesetOK = false p.im = textIM case a.Xmp: p.popUntil(buttonScope, a.P) p.reconstructActiveFormattingElements() p.framesetOK = false p.addElement() p.setOriginalIM() p.im = textIM case a.Iframe: p.framesetOK = false p.addElement() p.setOriginalIM() p.im = textIM case a.Noembed, a.Noscript: p.addElement() p.setOriginalIM() p.im = textIM case a.Select: p.reconstructActiveFormattingElements() p.addElement() p.framesetOK = false p.im = inSelectIM return true case a.Optgroup, a.Option: if p.top().DataAtom == a.Option { p.oe.pop() } p.reconstructActiveFormattingElements() p.addElement() case a.Rp, a.Rt: if p.elementInScope(defaultScope, a.Ruby) { p.generateImpliedEndTags() } p.addElement() case a.Math, a.Svg: p.reconstructActiveFormattingElements() if p.tok.DataAtom == a.Math { adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments) } else { adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments) } adjustForeignAttributes(p.tok.Attr) p.addElement() p.top().Namespace = p.tok.Data if p.hasSelfClosingToken { p.oe.pop() p.acknowledgeSelfClosingTag() } return true case a.Caption, a.Col, a.Colgroup, a.Frame, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: // Ignore the token. default: p.reconstructActiveFormattingElements() p.addElement() } case EndTagToken: switch p.tok.DataAtom { case a.Body: if p.elementInScope(defaultScope, a.Body) { p.im = afterBodyIM } case a.Html: if p.elementInScope(defaultScope, a.Body) { p.parseImpliedToken(EndTagToken, a.Body, a.Body.String()) return false } return true case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul: p.popUntil(defaultScope, p.tok.DataAtom) case a.Form: node := p.form p.form = nil i := p.indexOfElementInScope(defaultScope, a.Form) if node == nil || i == -1 || p.oe[i] != node { // Ignore the token. return true } p.generateImpliedEndTags() p.oe.remove(node) case a.P: if !p.elementInScope(buttonScope, a.P) { p.parseImpliedToken(StartTagToken, a.P, a.P.String()) } p.popUntil(buttonScope, a.P) case a.Li: p.popUntil(listItemScope, a.Li) case a.Dd, a.Dt: p.popUntil(defaultScope, p.tok.DataAtom) case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6: p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6) case a.A, a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.Nobr, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U: p.inBodyEndTagFormatting(p.tok.DataAtom) case a.Applet, a.Marquee, a.Object: if p.popUntil(defaultScope, p.tok.DataAtom) { p.clearActiveFormattingElements() } case a.Br: p.tok.Type = StartTagToken return false default: p.inBodyEndTagOther(p.tok.DataAtom) } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) } return true } func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) { // This is the "adoption agency" algorithm, described at // https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency // TODO: this is a fairly literal line-by-line translation of that algorithm. // Once the code successfully parses the comprehensive test suite, we should // refactor this code to be more idiomatic. // Steps 1-4. The outer loop. for i := 0; i < 8; i++ { // Step 5. Find the formatting element. var formattingElement *Node for j := len(p.afe) - 1; j >= 0; j-- { if p.afe[j].Type == scopeMarkerNode { break } if p.afe[j].DataAtom == tagAtom { formattingElement = p.afe[j] break } } if formattingElement == nil { p.inBodyEndTagOther(tagAtom) return } feIndex := p.oe.index(formattingElement) if feIndex == -1 { p.afe.remove(formattingElement) return } if !p.elementInScope(defaultScope, tagAtom) { // Ignore the tag. return } // Steps 9-10. Find the furthest block. var furthestBlock *Node for _, e := range p.oe[feIndex:] { if isSpecialElement(e) { furthestBlock = e break } } if furthestBlock == nil { e := p.oe.pop() for e != formattingElement { e = p.oe.pop() } p.afe.remove(e) return } // Steps 11-12. Find the common ancestor and bookmark node. commonAncestor := p.oe[feIndex-1] bookmark := p.afe.index(formattingElement) // Step 13. The inner loop. Find the lastNode to reparent. lastNode := furthestBlock node := furthestBlock x := p.oe.index(node) // Steps 13.1-13.2 for j := 0; j < 3; j++ { // Step 13.3. x-- node = p.oe[x] // Step 13.4 - 13.5. if p.afe.index(node) == -1 { p.oe.remove(node) continue } // Step 13.6. if node == formattingElement { break } // Step 13.7. clone := node.clone() p.afe[p.afe.index(node)] = clone p.oe[p.oe.index(node)] = clone node = clone // Step 13.8. if lastNode == furthestBlock { bookmark = p.afe.index(node) + 1 } // Step 13.9. if lastNode.Parent != nil { lastNode.Parent.RemoveChild(lastNode) } node.AppendChild(lastNode) // Step 13.10. lastNode = node } // Step 14. Reparent lastNode to the common ancestor, // or for misnested table nodes, to the foster parent. if lastNode.Parent != nil { lastNode.Parent.RemoveChild(lastNode) } switch commonAncestor.DataAtom { case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: p.fosterParent(lastNode) default: commonAncestor.AppendChild(lastNode) } // Steps 15-17. Reparent nodes from the furthest block's children // to a clone of the formatting element. clone := formattingElement.clone() reparentChildren(clone, furthestBlock) furthestBlock.AppendChild(clone) // Step 18. Fix up the list of active formatting elements. if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark { // Move the bookmark with the rest of the list. bookmark-- } p.afe.remove(formattingElement) p.afe.insert(bookmark, clone) // Step 19. Fix up the stack of open elements. p.oe.remove(formattingElement) p.oe.insert(p.oe.index(furthestBlock)+1, clone) } } // inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM. // "Any other end tag" handling from 12.2.5.5 The rules for parsing tokens in foreign content // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign func (p *parser) inBodyEndTagOther(tagAtom a.Atom) { for i := len(p.oe) - 1; i >= 0; i-- { if p.oe[i].DataAtom == tagAtom { p.oe = p.oe[:i] break } if isSpecialElement(p.oe[i]) { break } } } // Section 12.2.5.4.8. func textIM(p *parser) bool { switch p.tok.Type { case ErrorToken: p.oe.pop() case TextToken: d := p.tok.Data if n := p.oe.top(); n.DataAtom == a.Textarea && n.FirstChild == nil { // Ignore a newline at the start of a <textarea> block. if d != "" && d[0] == '\r' { d = d[1:] } if d != "" && d[0] == '\n' { d = d[1:] } } if d == "" { return true } p.addText(d) return true case EndTagToken: p.oe.pop() } p.im = p.originalIM p.originalIM = nil return p.tok.Type == EndTagToken } // Section 12.2.5.4.9. func inTableIM(p *parser) bool { switch p.tok.Type { case ErrorToken: // Stop parsing. return true case TextToken: p.tok.Data = strings.Replace(p.tok.Data, "\x00", "", -1) switch p.oe.top().DataAtom { case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: if strings.Trim(p.tok.Data, whitespace) == "" { p.addText(p.tok.Data) return true } } case StartTagToken: switch p.tok.DataAtom { case a.Caption: p.clearStackToContext(tableScope) p.afe = append(p.afe, &scopeMarker) p.addElement() p.im = inCaptionIM return true case a.Colgroup: p.clearStackToContext(tableScope) p.addElement() p.im = inColumnGroupIM return true case a.Col: p.parseImpliedToken(StartTagToken, a.Colgroup, a.Colgroup.String()) return false case a.Tbody, a.Tfoot, a.Thead: p.clearStackToContext(tableScope) p.addElement() p.im = inTableBodyIM return true case a.Td, a.Th, a.Tr: p.parseImpliedToken(StartTagToken, a.Tbody, a.Tbody.String()) return false case a.Table: if p.popUntil(tableScope, a.Table) { p.resetInsertionMode() return false } // Ignore the token. return true case a.Style, a.Script: return inHeadIM(p) case a.Input: for _, t := range p.tok.Attr { if t.Key == "type" && strings.ToLower(t.Val) == "hidden" { p.addElement() p.oe.pop() return true } } // Otherwise drop down to the default action. case a.Form: if p.form != nil { // Ignore the token. return true } p.addElement() p.form = p.oe.pop() case a.Select: p.reconstructActiveFormattingElements() switch p.top().DataAtom { case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: p.fosterParenting = true } p.addElement() p.fosterParenting = false p.framesetOK = false p.im = inSelectInTableIM return true } case EndTagToken: switch p.tok.DataAtom { case a.Table: if p.popUntil(tableScope, a.Table) { p.resetInsertionMode() return true } // Ignore the token. return true case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: // Ignore the token. return true } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: // Ignore the token. return true } p.fosterParenting = true defer func() { p.fosterParenting = false }() return inBodyIM(p) } // Section 12.2.5.4.11. func inCaptionIM(p *parser) bool { switch p.tok.Type { case StartTagToken: switch p.tok.DataAtom { case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Thead, a.Tr: if p.popUntil(tableScope, a.Caption) { p.clearActiveFormattingElements() p.im = inTableIM return false } else { // Ignore the token. return true } case a.Select: p.reconstructActiveFormattingElements() p.addElement() p.framesetOK = false p.im = inSelectInTableIM return true } case EndTagToken: switch p.tok.DataAtom { case a.Caption: if p.popUntil(tableScope, a.Caption) { p.clearActiveFormattingElements() p.im = inTableIM } return true case a.Table: if p.popUntil(tableScope, a.Caption) { p.clearActiveFormattingElements() p.im = inTableIM return false } else { // Ignore the token. return true } case a.Body, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: // Ignore the token. return true } } return inBodyIM(p) } // Section 12.2.5.4.12. func inColumnGroupIM(p *parser) bool { switch p.tok.Type { case TextToken: s := strings.TrimLeft(p.tok.Data, whitespace) if len(s) < len(p.tok.Data) { // Add the initial whitespace to the current node. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) if s == "" { return true } p.tok.Data = s } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: // Ignore the token. return true case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Col: p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() return true } case EndTagToken: switch p.tok.DataAtom { case a.Colgroup: if p.oe.top().DataAtom != a.Html { p.oe.pop() p.im = inTableIM } return true case a.Col: // Ignore the token. return true } } if p.oe.top().DataAtom != a.Html { p.oe.pop() p.im = inTableIM return false } return true } // Section 12.2.5.4.13. func inTableBodyIM(p *parser) bool { switch p.tok.Type { case StartTagToken: switch p.tok.DataAtom { case a.Tr: p.clearStackToContext(tableBodyScope) p.addElement() p.im = inRowIM return true case a.Td, a.Th: p.parseImpliedToken(StartTagToken, a.Tr, a.Tr.String()) return false case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Tfoot, a.Thead: if p.popUntil(tableScope, a.Tbody, a.Thead, a.Tfoot) { p.im = inTableIM return false } // Ignore the token. return true } case EndTagToken: switch p.tok.DataAtom { case a.Tbody, a.Tfoot, a.Thead: if p.elementInScope(tableScope, p.tok.DataAtom) { p.clearStackToContext(tableBodyScope) p.oe.pop() p.im = inTableIM } return true case a.Table: if p.popUntil(tableScope, a.Tbody, a.Thead, a.Tfoot) { p.im = inTableIM return false } // Ignore the token. return true case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Td, a.Th, a.Tr: // Ignore the token. return true } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true } return inTableIM(p) } // Section 12.2.5.4.14. func inRowIM(p *parser) bool { switch p.tok.Type { case StartTagToken: switch p.tok.DataAtom { case a.Td, a.Th: p.clearStackToContext(tableRowScope) p.addElement() p.afe = append(p.afe, &scopeMarker) p.im = inCellIM return true case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Tfoot, a.Thead, a.Tr: if p.popUntil(tableScope, a.Tr) { p.im = inTableBodyIM return false } // Ignore the token. return true } case EndTagToken: switch p.tok.DataAtom { case a.Tr: if p.popUntil(tableScope, a.Tr) { p.im = inTableBodyIM return true } // Ignore the token. return true case a.Table: if p.popUntil(tableScope, a.Tr) { p.im = inTableBodyIM return false } // Ignore the token. return true case a.Tbody, a.Tfoot, a.Thead: if p.elementInScope(tableScope, p.tok.DataAtom) { p.parseImpliedToken(EndTagToken, a.Tr, a.Tr.String()) return false } // Ignore the token. return true case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Td, a.Th: // Ignore the token. return true } } return inTableIM(p) } // Section 12.2.5.4.15. func inCellIM(p *parser) bool { switch p.tok.Type { case StartTagToken: switch p.tok.DataAtom { case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: if p.popUntil(tableScope, a.Td, a.Th) { // Close the cell and reprocess. p.clearActiveFormattingElements() p.im = inRowIM return false } // Ignore the token. return true case a.Select: p.reconstructActiveFormattingElements() p.addElement() p.framesetOK = false p.im = inSelectInTableIM return true } case EndTagToken: switch p.tok.DataAtom { case a.Td, a.Th: if !p.popUntil(tableScope, p.tok.DataAtom) { // Ignore the token. return true } p.clearActiveFormattingElements() p.im = inRowIM return true case a.Body, a.Caption, a.Col, a.Colgroup, a.Html: // Ignore the token. return true case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: if !p.elementInScope(tableScope, p.tok.DataAtom) { // Ignore the token. return true } // Close the cell and reprocess. p.popUntil(tableScope, a.Td, a.Th) p.clearActiveFormattingElements() p.im = inRowIM return false } } return inBodyIM(p) } // Section 12.2.5.4.16. func inSelectIM(p *parser) bool { switch p.tok.Type { case ErrorToken: // Stop parsing. return true case TextToken: p.addText(strings.Replace(p.tok.Data, "\x00", "", -1)) case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Option: if p.top().DataAtom == a.Option { p.oe.pop() } p.addElement() case a.Optgroup: if p.top().DataAtom == a.Option { p.oe.pop() } if p.top().DataAtom == a.Optgroup { p.oe.pop() } p.addElement() case a.Select: p.tok.Type = EndTagToken return false case a.Input, a.Keygen, a.Textarea: if p.elementInScope(selectScope, a.Select) { p.parseImpliedToken(EndTagToken, a.Select, a.Select.String()) return false } // In order to properly ignore <textarea>, we need to change the tokenizer mode. p.tokenizer.NextIsNotRawText() // Ignore the token. return true case a.Script: return inHeadIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Option: if p.top().DataAtom == a.Option { p.oe.pop() } case a.Optgroup: i := len(p.oe) - 1 if p.oe[i].DataAtom == a.Option { i-- } if p.oe[i].DataAtom == a.Optgroup { p.oe = p.oe[:i] } case a.Select: if p.popUntil(selectScope, a.Select) { p.resetInsertionMode() } } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) case DoctypeToken: // Ignore the token. return true } return true } // Section 12.2.5.4.17. func inSelectInTableIM(p *parser) bool { switch p.tok.Type { case StartTagToken, EndTagToken: switch p.tok.DataAtom { case a.Caption, a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr, a.Td, a.Th: if p.tok.Type == StartTagToken || p.elementInScope(tableScope, p.tok.DataAtom) { p.parseImpliedToken(EndTagToken, a.Select, a.Select.String()) return false } else { // Ignore the token. return true } } } return inSelectIM(p) } // Section 12.2.5.4.18. func afterBodyIM(p *parser) bool { switch p.tok.Type { case ErrorToken: // Stop parsing. return true case TextToken: s := strings.TrimLeft(p.tok.Data, whitespace) if len(s) == 0 { // It was all whitespace. return inBodyIM(p) } case StartTagToken: if p.tok.DataAtom == a.Html { return inBodyIM(p) } case EndTagToken: if p.tok.DataAtom == a.Html { if !p.fragment { p.im = afterAfterBodyIM } return true } case CommentToken: // The comment is attached to the <html> element. if len(p.oe) < 1 || p.oe[0].DataAtom != a.Html { panic("html: bad parser state: <html> element not found, in the after-body insertion mode") } p.oe[0].AppendChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true } p.im = inBodyIM return false } // Section 12.2.5.4.19. func inFramesetIM(p *parser) bool { switch p.tok.Type { case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) case TextToken: // Ignore all text but whitespace. s := strings.Map(func(c rune) rune { switch c { case ' ', '\t', '\n', '\f', '\r': return c } return -1 }, p.tok.Data) if s != "" { p.addText(s) } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Frameset: p.addElement() case a.Frame: p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() case a.Noframes: return inHeadIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Frameset: if p.oe.top().DataAtom != a.Html { p.oe.pop() if p.oe.top().DataAtom != a.Frameset { p.im = afterFramesetIM return true } } } default: // Ignore the token. } return true } // Section 12.2.5.4.20. func afterFramesetIM(p *parser) bool { switch p.tok.Type { case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) case TextToken: // Ignore all text but whitespace. s := strings.Map(func(c rune) rune { switch c { case ' ', '\t', '\n', '\f', '\r': return c } return -1 }, p.tok.Data) if s != "" { p.addText(s) } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Noframes: return inHeadIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Html: p.im = afterAfterFramesetIM return true } default: // Ignore the token. } return true } // Section 12.2.5.4.21. func afterAfterBodyIM(p *parser) bool { switch p.tok.Type { case ErrorToken: // Stop parsing. return true case TextToken: s := strings.TrimLeft(p.tok.Data, whitespace) if len(s) == 0 { // It was all whitespace. return inBodyIM(p) } case StartTagToken: if p.tok.DataAtom == a.Html { return inBodyIM(p) } case CommentToken: p.doc.AppendChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: return inBodyIM(p) } p.im = inBodyIM return false } // Section 12.2.5.4.22. func afterAfterFramesetIM(p *parser) bool { switch p.tok.Type { case CommentToken: p.doc.AppendChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) case TextToken: // Ignore all text but whitespace. s := strings.Map(func(c rune) rune { switch c { case ' ', '\t', '\n', '\f', '\r': return c } return -1 }, p.tok.Data) if s != "" { p.tok.Data = s return inBodyIM(p) } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Noframes: return inHeadIM(p) } case DoctypeToken: return inBodyIM(p) default: // Ignore the token. } return true } const whitespaceOrNUL = whitespace + "\x00" // Section 12.2.5.5. func parseForeignContent(p *parser) bool { switch p.tok.Type { case TextToken: if p.framesetOK { p.framesetOK = strings.TrimLeft(p.tok.Data, whitespaceOrNUL) == "" } p.tok.Data = strings.Replace(p.tok.Data, "\x00", "\ufffd", -1) p.addText(p.tok.Data) case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) case StartTagToken: b := breakout[p.tok.Data] if p.tok.DataAtom == a.Font { loop: for _, attr := range p.tok.Attr { switch attr.Key { case "color", "face", "size": b = true break loop } } } if b { for i := len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] if n.Namespace == "" || htmlIntegrationPoint(n) || mathMLTextIntegrationPoint(n) { p.oe = p.oe[:i+1] break } } return false } switch p.top().Namespace { case "math": adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments) case "svg": // Adjust SVG tag names. The tokenizer lower-cases tag names, but // SVG wants e.g. "foreignObject" with a capital second "O". if x := svgTagNameAdjustments[p.tok.Data]; x != "" { p.tok.DataAtom = a.Lookup([]byte(x)) p.tok.Data = x } adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments) default: panic("html: bad parser state: unexpected namespace") } adjustForeignAttributes(p.tok.Attr) namespace := p.top().Namespace p.addElement() p.top().Namespace = namespace if namespace != "" { // Don't let the tokenizer go into raw text mode in foreign content // (e.g. in an SVG <title> tag). p.tokenizer.NextIsNotRawText() } if p.hasSelfClosingToken { p.oe.pop() p.acknowledgeSelfClosingTag() } case EndTagToken: for i := len(p.oe) - 1; i >= 0; i-- { if p.oe[i].Namespace == "" { return p.im(p) } if strings.EqualFold(p.oe[i].Data, p.tok.Data) { p.oe = p.oe[:i] break } } return true default: // Ignore the token. } return true } // Section 12.2.5. func (p *parser) inForeignContent() bool { if len(p.oe) == 0 { return false } n := p.oe[len(p.oe)-1] if n.Namespace == "" { return false } if mathMLTextIntegrationPoint(n) { if p.tok.Type == StartTagToken && p.tok.DataAtom != a.Mglyph && p.tok.DataAtom != a.Malignmark { return false } if p.tok.Type == TextToken { return false } } if n.Namespace == "math" && n.DataAtom == a.AnnotationXml && p.tok.Type == StartTagToken && p.tok.DataAtom == a.Svg { return false } if htmlIntegrationPoint(n) && (p.tok.Type == StartTagToken || p.tok.Type == TextToken) { return false } if p.tok.Type == ErrorToken { return false } return true } // parseImpliedToken parses a token as though it had appeared in the parser's // input. func (p *parser) parseImpliedToken(t TokenType, dataAtom a.Atom, data string) { realToken, selfClosing := p.tok, p.hasSelfClosingToken p.tok = Token{ Type: t, DataAtom: dataAtom, Data: data, } p.hasSelfClosingToken = false p.parseCurrentToken() p.tok, p.hasSelfClosingToken = realToken, selfClosing } // parseCurrentToken runs the current token through the parsing routines // until it is consumed. func (p *parser) parseCurrentToken() { if p.tok.Type == SelfClosingTagToken { p.hasSelfClosingToken = true p.tok.Type = StartTagToken } consumed := false for !consumed { if p.inForeignContent() { consumed = parseForeignContent(p) } else { consumed = p.im(p) } } if p.hasSelfClosingToken { // This is a parse error, but ignore it. p.hasSelfClosingToken = false } } func (p *parser) parse() error { // Iterate until EOF. Any other error will cause an early return. var err error for err != io.EOF { // CDATA sections are allowed only in foreign content. n := p.oe.top() p.tokenizer.AllowCDATA(n != nil && n.Namespace != "") // Read and parse the next token. p.tokenizer.Next() p.tok = p.tokenizer.Token() if p.tok.Type == ErrorToken { err = p.tokenizer.Err() if err != nil && err != io.EOF { return err } } p.parseCurrentToken() } return nil } // Parse returns the parse tree for the HTML from the given Reader. // The input is assumed to be UTF-8 encoded. func Parse(r io.Reader) (*Node, error) { p := &parser{ tokenizer: NewTokenizer(r), doc: &Node{ Type: DocumentNode, }, scripting: true, framesetOK: true, im: initialIM, } err := p.parse() if err != nil { return nil, err } return p.doc, nil } // ParseFragment parses a fragment of HTML and returns the nodes that were // found. If the fragment is the InnerHTML for an existing element, pass that // element in context. func ParseFragment(r io.Reader, context *Node) ([]*Node, error) { contextTag := "" if context != nil { if context.Type != ElementNode { return nil, errors.New("html: ParseFragment of non-element Node") } // The next check isn't just context.DataAtom.String() == context.Data because // it is valid to pass an element whose tag isn't a known atom. For example, // DataAtom == 0 and Data = "tagfromthefuture" is perfectly consistent. if context.DataAtom != a.Lookup([]byte(context.Data)) { return nil, fmt.Errorf("html: inconsistent Node: DataAtom=%q, Data=%q", context.DataAtom, context.Data) } contextTag = context.DataAtom.String() } p := &parser{ tokenizer: NewTokenizerFragment(r, contextTag), doc: &Node{ Type: DocumentNode, }, scripting: true, fragment: true, context: context, } root := &Node{ Type: ElementNode, DataAtom: a.Html, Data: a.Html.String(), } p.doc.AppendChild(root) p.oe = nodeStack{root} p.resetInsertionMode() for n := context; n != nil; n = n.Parent { if n.Type == ElementNode && n.DataAtom == a.Form { p.form = n break } } err := p.parse() if err != nil { return nil, err } parent := p.doc if context != nil { parent = root } var result []*Node for c := parent.FirstChild; c != nil; { next := c.NextSibling parent.RemoveChild(c) result = append(result, c) c = next } return result, nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/node_test.go����������������������������������������������0000644�0610621�0607500�00000007305�13172163402�023577� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "fmt" ) // checkTreeConsistency checks that a node and its descendants are all // consistent in their parent/child/sibling relationships. func checkTreeConsistency(n *Node) error { return checkTreeConsistency1(n, 0) } func checkTreeConsistency1(n *Node, depth int) error { if depth == 1e4 { return fmt.Errorf("html: tree looks like it contains a cycle") } if err := checkNodeConsistency(n); err != nil { return err } for c := n.FirstChild; c != nil; c = c.NextSibling { if err := checkTreeConsistency1(c, depth+1); err != nil { return err } } return nil } // checkNodeConsistency checks that a node's parent/child/sibling relationships // are consistent. func checkNodeConsistency(n *Node) error { if n == nil { return nil } nParent := 0 for p := n.Parent; p != nil; p = p.Parent { nParent++ if nParent == 1e4 { return fmt.Errorf("html: parent list looks like an infinite loop") } } nForward := 0 for c := n.FirstChild; c != nil; c = c.NextSibling { nForward++ if nForward == 1e6 { return fmt.Errorf("html: forward list of children looks like an infinite loop") } if c.Parent != n { return fmt.Errorf("html: inconsistent child/parent relationship") } } nBackward := 0 for c := n.LastChild; c != nil; c = c.PrevSibling { nBackward++ if nBackward == 1e6 { return fmt.Errorf("html: backward list of children looks like an infinite loop") } if c.Parent != n { return fmt.Errorf("html: inconsistent child/parent relationship") } } if n.Parent != nil { if n.Parent == n { return fmt.Errorf("html: inconsistent parent relationship") } if n.Parent == n.FirstChild { return fmt.Errorf("html: inconsistent parent/first relationship") } if n.Parent == n.LastChild { return fmt.Errorf("html: inconsistent parent/last relationship") } if n.Parent == n.PrevSibling { return fmt.Errorf("html: inconsistent parent/prev relationship") } if n.Parent == n.NextSibling { return fmt.Errorf("html: inconsistent parent/next relationship") } parentHasNAsAChild := false for c := n.Parent.FirstChild; c != nil; c = c.NextSibling { if c == n { parentHasNAsAChild = true break } } if !parentHasNAsAChild { return fmt.Errorf("html: inconsistent parent/child relationship") } } if n.PrevSibling != nil && n.PrevSibling.NextSibling != n { return fmt.Errorf("html: inconsistent prev/next relationship") } if n.NextSibling != nil && n.NextSibling.PrevSibling != n { return fmt.Errorf("html: inconsistent next/prev relationship") } if (n.FirstChild == nil) != (n.LastChild == nil) { return fmt.Errorf("html: inconsistent first/last relationship") } if n.FirstChild != nil && n.FirstChild == n.LastChild { // We have a sole child. if n.FirstChild.PrevSibling != nil || n.FirstChild.NextSibling != nil { return fmt.Errorf("html: inconsistent sole child's sibling relationship") } } seen := map[*Node]bool{} var last *Node for c := n.FirstChild; c != nil; c = c.NextSibling { if seen[c] { return fmt.Errorf("html: inconsistent repeated child") } seen[c] = true last = c } if last != n.LastChild { return fmt.Errorf("html: inconsistent last relationship") } var first *Node for c := n.LastChild; c != nil; c = c.PrevSibling { if !seen[c] { return fmt.Errorf("html: inconsistent missing child") } delete(seen, c) first = c } if first != n.FirstChild { return fmt.Errorf("html: inconsistent first relationship") } if len(seen) != 0 { return fmt.Errorf("html: inconsistent forwards/backwards child list") } return nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/node.go���������������������������������������������������0000644�0610621�0607500�00000011343�13172163402�022535� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "golang.org/x/net/html/atom" ) // A NodeType is the type of a Node. type NodeType uint32 const ( ErrorNode NodeType = iota TextNode DocumentNode ElementNode CommentNode DoctypeNode scopeMarkerNode ) // Section 12.2.3.3 says "scope markers are inserted when entering applet // elements, buttons, object elements, marquees, table cells, and table // captions, and are used to prevent formatting from 'leaking'". var scopeMarker = Node{Type: scopeMarkerNode} // A Node consists of a NodeType and some Data (tag name for element nodes, // content for text) and are part of a tree of Nodes. Element nodes may also // have a Namespace and contain a slice of Attributes. Data is unescaped, so // that it looks like "a<b" rather than "a&lt;b". For element nodes, DataAtom // is the atom for Data, or zero if Data is not a known tag name. // // An empty Namespace implies a "http://www.w3.org/1999/xhtml" namespace. // Similarly, "math" is short for "http://www.w3.org/1998/Math/MathML", and // "svg" is short for "http://www.w3.org/2000/svg". type Node struct { Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node Type NodeType DataAtom atom.Atom Data string Namespace string Attr []Attribute } // InsertBefore inserts newChild as a child of n, immediately before oldChild // in the sequence of n's children. oldChild may be nil, in which case newChild // is appended to the end of n's children. // // It will panic if newChild already has a parent or siblings. func (n *Node) InsertBefore(newChild, oldChild *Node) { if newChild.Parent != nil || newChild.PrevSibling != nil || newChild.NextSibling != nil { panic("html: InsertBefore called for an attached child Node") } var prev, next *Node if oldChild != nil { prev, next = oldChild.PrevSibling, oldChild } else { prev = n.LastChild } if prev != nil { prev.NextSibling = newChild } else { n.FirstChild = newChild } if next != nil { next.PrevSibling = newChild } else { n.LastChild = newChild } newChild.Parent = n newChild.PrevSibling = prev newChild.NextSibling = next } // AppendChild adds a node c as a child of n. // // It will panic if c already has a parent or siblings. func (n *Node) AppendChild(c *Node) { if c.Parent != nil || c.PrevSibling != nil || c.NextSibling != nil { panic("html: AppendChild called for an attached child Node") } last := n.LastChild if last != nil { last.NextSibling = c } else { n.FirstChild = c } n.LastChild = c c.Parent = n c.PrevSibling = last } // RemoveChild removes a node c that is a child of n. Afterwards, c will have // no parent and no siblings. // // It will panic if c's parent is not n. func (n *Node) RemoveChild(c *Node) { if c.Parent != n { panic("html: RemoveChild called for a non-child Node") } if n.FirstChild == c { n.FirstChild = c.NextSibling } if c.NextSibling != nil { c.NextSibling.PrevSibling = c.PrevSibling } if n.LastChild == c { n.LastChild = c.PrevSibling } if c.PrevSibling != nil { c.PrevSibling.NextSibling = c.NextSibling } c.Parent = nil c.PrevSibling = nil c.NextSibling = nil } // reparentChildren reparents all of src's child nodes to dst. func reparentChildren(dst, src *Node) { for { child := src.FirstChild if child == nil { break } src.RemoveChild(child) dst.AppendChild(child) } } // clone returns a new node with the same type, data and attributes. // The clone has no parent, no siblings and no children. func (n *Node) clone() *Node { m := &Node{ Type: n.Type, DataAtom: n.DataAtom, Data: n.Data, Attr: make([]Attribute, len(n.Attr)), } copy(m.Attr, n.Attr) return m } // nodeStack is a stack of nodes. type nodeStack []*Node // pop pops the stack. It will panic if s is empty. func (s *nodeStack) pop() *Node { i := len(*s) n := (*s)[i-1] *s = (*s)[:i-1] return n } // top returns the most recently pushed node, or nil if s is empty. func (s *nodeStack) top() *Node { if i := len(*s); i > 0 { return (*s)[i-1] } return nil } // index returns the index of the top-most occurrence of n in the stack, or -1 // if n is not present. func (s *nodeStack) index(n *Node) int { for i := len(*s) - 1; i >= 0; i-- { if (*s)[i] == n { return i } } return -1 } // insert inserts a node at the given index. func (s *nodeStack) insert(i int, n *Node) { (*s) = append(*s, nil) copy((*s)[i+1:], (*s)[i:]) (*s)[i] = n } // remove removes a node from the stack. It is a no-op if n is not present. func (s *nodeStack) remove(n *Node) { i := s.index(n) if i == -1 { return } copy((*s)[i:], (*s)[i+1:]) j := len(*s) - 1 (*s)[j] = nil *s = (*s)[:j] } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/foreign.go������������������������������������������������0000644�0610621�0607500�00000015401�13172163402�023240� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "strings" ) func adjustAttributeNames(aa []Attribute, nameMap map[string]string) { for i := range aa { if newName, ok := nameMap[aa[i].Key]; ok { aa[i].Key = newName } } } func adjustForeignAttributes(aa []Attribute) { for i, a := range aa { if a.Key == "" || a.Key[0] != 'x' { continue } switch a.Key { case "xlink:actuate", "xlink:arcrole", "xlink:href", "xlink:role", "xlink:show", "xlink:title", "xlink:type", "xml:base", "xml:lang", "xml:space", "xmlns:xlink": j := strings.Index(a.Key, ":") aa[i].Namespace = a.Key[:j] aa[i].Key = a.Key[j+1:] } } } func htmlIntegrationPoint(n *Node) bool { if n.Type != ElementNode { return false } switch n.Namespace { case "math": if n.Data == "annotation-xml" { for _, a := range n.Attr { if a.Key == "encoding" { val := strings.ToLower(a.Val) if val == "text/html" || val == "application/xhtml+xml" { return true } } } } case "svg": switch n.Data { case "desc", "foreignObject", "title": return true } } return false } func mathMLTextIntegrationPoint(n *Node) bool { if n.Namespace != "math" { return false } switch n.Data { case "mi", "mo", "mn", "ms", "mtext": return true } return false } // Section 12.2.5.5. var breakout = map[string]bool{ "b": true, "big": true, "blockquote": true, "body": true, "br": true, "center": true, "code": true, "dd": true, "div": true, "dl": true, "dt": true, "em": true, "embed": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "head": true, "hr": true, "i": true, "img": true, "li": true, "listing": true, "menu": true, "meta": true, "nobr": true, "ol": true, "p": true, "pre": true, "ruby": true, "s": true, "small": true, "span": true, "strong": true, "strike": true, "sub": true, "sup": true, "table": true, "tt": true, "u": true, "ul": true, "var": true, } // Section 12.2.5.5. var svgTagNameAdjustments = map[string]string{ "altglyph": "altGlyph", "altglyphdef": "altGlyphDef", "altglyphitem": "altGlyphItem", "animatecolor": "animateColor", "animatemotion": "animateMotion", "animatetransform": "animateTransform", "clippath": "clipPath", "feblend": "feBlend", "fecolormatrix": "feColorMatrix", "fecomponenttransfer": "feComponentTransfer", "fecomposite": "feComposite", "feconvolvematrix": "feConvolveMatrix", "fediffuselighting": "feDiffuseLighting", "fedisplacementmap": "feDisplacementMap", "fedistantlight": "feDistantLight", "feflood": "feFlood", "fefunca": "feFuncA", "fefuncb": "feFuncB", "fefuncg": "feFuncG", "fefuncr": "feFuncR", "fegaussianblur": "feGaussianBlur", "feimage": "feImage", "femerge": "feMerge", "femergenode": "feMergeNode", "femorphology": "feMorphology", "feoffset": "feOffset", "fepointlight": "fePointLight", "fespecularlighting": "feSpecularLighting", "fespotlight": "feSpotLight", "fetile": "feTile", "feturbulence": "feTurbulence", "foreignobject": "foreignObject", "glyphref": "glyphRef", "lineargradient": "linearGradient", "radialgradient": "radialGradient", "textpath": "textPath", } // Section 12.2.5.1 var mathMLAttributeAdjustments = map[string]string{ "definitionurl": "definitionURL", } var svgAttributeAdjustments = map[string]string{ "attributename": "attributeName", "attributetype": "attributeType", "basefrequency": "baseFrequency", "baseprofile": "baseProfile", "calcmode": "calcMode", "clippathunits": "clipPathUnits", "contentscripttype": "contentScriptType", "contentstyletype": "contentStyleType", "diffuseconstant": "diffuseConstant", "edgemode": "edgeMode", "externalresourcesrequired": "externalResourcesRequired", "filterres": "filterRes", "filterunits": "filterUnits", "glyphref": "glyphRef", "gradienttransform": "gradientTransform", "gradientunits": "gradientUnits", "kernelmatrix": "kernelMatrix", "kernelunitlength": "kernelUnitLength", "keypoints": "keyPoints", "keysplines": "keySplines", "keytimes": "keyTimes", "lengthadjust": "lengthAdjust", "limitingconeangle": "limitingConeAngle", "markerheight": "markerHeight", "markerunits": "markerUnits", "markerwidth": "markerWidth", "maskcontentunits": "maskContentUnits", "maskunits": "maskUnits", "numoctaves": "numOctaves", "pathlength": "pathLength", "patterncontentunits": "patternContentUnits", "patterntransform": "patternTransform", "patternunits": "patternUnits", "pointsatx": "pointsAtX", "pointsaty": "pointsAtY", "pointsatz": "pointsAtZ", "preservealpha": "preserveAlpha", "preserveaspectratio": "preserveAspectRatio", "primitiveunits": "primitiveUnits", "refx": "refX", "refy": "refY", "repeatcount": "repeatCount", "repeatdur": "repeatDur", "requiredextensions": "requiredExtensions", "requiredfeatures": "requiredFeatures", "specularconstant": "specularConstant", "specularexponent": "specularExponent", "spreadmethod": "spreadMethod", "startoffset": "startOffset", "stddeviation": "stdDeviation", "stitchtiles": "stitchTiles", "surfacescale": "surfaceScale", "systemlanguage": "systemLanguage", "tablevalues": "tableValues", "targetx": "targetX", "targety": "targetY", "textlength": "textLength", "viewbox": "viewBox", "viewtarget": "viewTarget", "xchannelselector": "xChannelSelector", "ychannelselector": "yChannelSelector", "zoomandpan": "zoomAndPan", } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/example_test.go�������������������������������������������0000644�0610621�0607500�00000001502�13172163402�024276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This example demonstrates parsing HTML data and walking the resulting tree. package html_test import ( "fmt" "log" "strings" "golang.org/x/net/html" ) func ExampleParse() { s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul>` doc, err := html.Parse(strings.NewReader(s)) if err != nil { log.Fatal(err) } var f func(*html.Node) f = func(n *html.Node) { if n.Type == html.ElementNode && n.Data == "a" { for _, a := range n.Attr { if a.Key == "href" { fmt.Println(a.Val) break } } } for c := n.FirstChild; c != nil; c = c.NextSibling { f(c) } } f(doc) // Output: // foo // /bar/baz } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/escape_test.go��������������������������������������������0000644�0610621�0607500�00000003535�13172163402�024113� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import "testing" type unescapeTest struct { // A short description of the test case. desc string // The HTML text. html string // The unescaped text. unescaped string } var unescapeTests = []unescapeTest{ // Handle no entities. { "copy", "A\ttext\nstring", "A\ttext\nstring", }, // Handle simple named entities. { "simple", "&amp; &gt; &lt;", "& > <", }, // Handle hitting the end of the string. { "stringEnd", "&amp &amp", "& &", }, // Handle entities with two codepoints. { "multiCodepoint", "text &gesl; blah", "text \u22db\ufe00 blah", }, // Handle decimal numeric entities. { "decimalEntity", "Delta = &#916; ", "Delta = Δ ", }, // Handle hexadecimal numeric entities. { "hexadecimalEntity", "Lambda = &#x3bb; = &#X3Bb ", "Lambda = λ = λ ", }, // Handle numeric early termination. { "numericEnds", "&# &#x &#128;43 &copy = &#169f = &#xa9", "&# &#x €43 © = ©f = ©", }, // Handle numeric ISO-8859-1 entity replacements. { "numericReplacements", "Footnote&#x87;", "Footnote‡", }, } func TestUnescape(t *testing.T) { for _, tt := range unescapeTests { unescaped := UnescapeString(tt.html) if unescaped != tt.unescaped { t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped) } } } func TestUnescapeEscape(t *testing.T) { ss := []string{ ``, `abc def`, `a & b`, `a&amp;b`, `a &amp b`, `&quot;`, `"`, `"<&>"`, `&quot;&lt;&amp;&gt;&quot;`, `3&5==1 && 0<1, "0&lt;1", a+acute=&aacute;`, `The special characters are: <, >, &, ' and "`, } for _, s := range ss { if got := UnescapeString(EscapeString(s)); got != s { t.Errorf("got %q want %q", got, s) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/escape.go�������������������������������������������������0000644�0610621�0607500�00000013645�13172163402�023057� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "bytes" "strings" "unicode/utf8" ) // These replacements permit compatibility with old numeric entities that // assumed Windows-1252 encoding. // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference var replacementTable = [...]rune{ '\u20AC', // First entry is what 0x80 should be replaced with. '\u0081', '\u201A', '\u0192', '\u201E', '\u2026', '\u2020', '\u2021', '\u02C6', '\u2030', '\u0160', '\u2039', '\u0152', '\u008D', '\u017D', '\u008F', '\u0090', '\u2018', '\u2019', '\u201C', '\u201D', '\u2022', '\u2013', '\u2014', '\u02DC', '\u2122', '\u0161', '\u203A', '\u0153', '\u009D', '\u017E', '\u0178', // Last entry is 0x9F. // 0x00->'\uFFFD' is handled programmatically. // 0x0D->'\u000D' is a no-op. } // unescapeEntity reads an entity like "&lt;" from b[src:] and writes the // corresponding "<" to b[dst:], returning the incremented dst and src cursors. // Precondition: b[src] == '&' && dst <= src. // attribute should be true if parsing an attribute value. func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference // i starts at 1 because we already know that s[0] == '&'. i, s := 1, b[src:] if len(s) <= 1 { b[dst] = b[src] return dst + 1, src + 1 } if s[i] == '#' { if len(s) <= 3 { // We need to have at least "&#.". b[dst] = b[src] return dst + 1, src + 1 } i++ c := s[i] hex := false if c == 'x' || c == 'X' { hex = true i++ } x := '\x00' for i < len(s) { c = s[i] i++ if hex { if '0' <= c && c <= '9' { x = 16*x + rune(c) - '0' continue } else if 'a' <= c && c <= 'f' { x = 16*x + rune(c) - 'a' + 10 continue } else if 'A' <= c && c <= 'F' { x = 16*x + rune(c) - 'A' + 10 continue } } else if '0' <= c && c <= '9' { x = 10*x + rune(c) - '0' continue } if c != ';' { i-- } break } if i <= 3 { // No characters matched. b[dst] = b[src] return dst + 1, src + 1 } if 0x80 <= x && x <= 0x9F { // Replace characters from Windows-1252 with UTF-8 equivalents. x = replacementTable[x-0x80] } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF { // Replace invalid characters with the replacement character. x = '\uFFFD' } return dst + utf8.EncodeRune(b[dst:], x), src + i } // Consume the maximum number of characters possible, with the // consumed characters matching one of the named references. for i < len(s) { c := s[i] i++ // Lower-cased characters are more common in entities, so we check for them first. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { continue } if c != ';' { i-- } break } entityName := string(s[1:i]) if entityName == "" { // No-op. } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' { // No-op. } else if x := entity[entityName]; x != 0 { return dst + utf8.EncodeRune(b[dst:], x), src + i } else if x := entity2[entityName]; x[0] != 0 { dst1 := dst + utf8.EncodeRune(b[dst:], x[0]) return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i } else if !attribute { maxLen := len(entityName) - 1 if maxLen > longestEntityWithoutSemicolon { maxLen = longestEntityWithoutSemicolon } for j := maxLen; j > 1; j-- { if x := entity[entityName[:j]]; x != 0 { return dst + utf8.EncodeRune(b[dst:], x), src + j + 1 } } } dst1, src1 = dst+i, src+i copy(b[dst:dst1], b[src:src1]) return dst1, src1 } // unescape unescapes b's entities in-place, so that "a&lt;b" becomes "a<b". // attribute should be true if parsing an attribute value. func unescape(b []byte, attribute bool) []byte { for i, c := range b { if c == '&' { dst, src := unescapeEntity(b, i, i, attribute) for src < len(b) { c := b[src] if c == '&' { dst, src = unescapeEntity(b, dst, src, attribute) } else { b[dst] = c dst, src = dst+1, src+1 } } return b[0:dst] } } return b } // lower lower-cases the A-Z bytes in b in-place, so that "aBc" becomes "abc". func lower(b []byte) []byte { for i, c := range b { if 'A' <= c && c <= 'Z' { b[i] = c + 'a' - 'A' } } return b } const escapedChars = "&'<>\"\r" func escape(w writer, s string) error { i := strings.IndexAny(s, escapedChars) for i != -1 { if _, err := w.WriteString(s[:i]); err != nil { return err } var esc string switch s[i] { case '&': esc = "&amp;" case '\'': // "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5. esc = "&#39;" case '<': esc = "&lt;" case '>': esc = "&gt;" case '"': // "&#34;" is shorter than "&quot;". esc = "&#34;" case '\r': esc = "&#13;" default: panic("unrecognized escape character") } s = s[i+1:] if _, err := w.WriteString(esc); err != nil { return err } i = strings.IndexAny(s, escapedChars) } _, err := w.WriteString(s) return err } // EscapeString escapes special characters like "<" to become "&lt;". It // escapes only five such characters: <, >, &, ' and ". // UnescapeString(EscapeString(s)) == s always holds, but the converse isn't // always true. func EscapeString(s string) string { if strings.IndexAny(s, escapedChars) == -1 { return s } var buf bytes.Buffer escape(&buf, s) return buf.String() } // UnescapeString unescapes entities like "&lt;" to become "<". It unescapes a // larger range of entities than EscapeString escapes. For example, "&aacute;" // unescapes to "á", as does "&#225;" and "&xE1;". // UnescapeString(EscapeString(s)) == s always holds, but the converse isn't // always true. func UnescapeString(s string) string { for _, c := range s { if c == '&' { return string(unescape([]byte(s), false)) } } return s } �������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/entity_test.go��������������������������������������������0000644�0610621�0607500�00000001776�13172163402�024174� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "testing" "unicode/utf8" ) func TestEntityLength(t *testing.T) { // We verify that the length of UTF-8 encoding of each value is <= 1 + len(key). // The +1 comes from the leading "&". This property implies that the length of // unescaped text is <= the length of escaped text. for k, v := range entity { if 1+len(k) < utf8.RuneLen(v) { t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v)) } if len(k) > longestEntityWithoutSemicolon && k[len(k)-1] != ';' { t.Errorf("entity name %s is %d characters, but longestEntityWithoutSemicolon=%d", k, len(k), longestEntityWithoutSemicolon) } } for k, v := range entity2 { if 1+len(k) < utf8.RuneLen(v[0])+utf8.RuneLen(v[1]) { t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v[0]) + string(v[1])) } } } ��lxd-2.0.11/dist/src/golang.org/x/net/html/entity.go�������������������������������������������������0000644�0610621�0607500�00000303327�13172163402�023132� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html // All entities that do not end with ';' are 6 or fewer bytes long. const longestEntityWithoutSemicolon = 6 // entity is a map from HTML entity names to their values. The semicolon matters: // https://html.spec.whatwg.org/multipage/syntax.html#named-character-references // lists both "amp" and "amp;" as two separate entries. // // Note that the HTML5 list is larger than the HTML4 list at // http://www.w3.org/TR/html4/sgml/entities.html var entity = map[string]rune{ "AElig;": '\U000000C6', "AMP;": '\U00000026', "Aacute;": '\U000000C1', "Abreve;": '\U00000102', "Acirc;": '\U000000C2', "Acy;": '\U00000410', "Afr;": '\U0001D504', "Agrave;": '\U000000C0', "Alpha;": '\U00000391', "Amacr;": '\U00000100', "And;": '\U00002A53', "Aogon;": '\U00000104', "Aopf;": '\U0001D538', "ApplyFunction;": '\U00002061', "Aring;": '\U000000C5', "Ascr;": '\U0001D49C', "Assign;": '\U00002254', "Atilde;": '\U000000C3', "Auml;": '\U000000C4', "Backslash;": '\U00002216', "Barv;": '\U00002AE7', "Barwed;": '\U00002306', "Bcy;": '\U00000411', "Because;": '\U00002235', "Bernoullis;": '\U0000212C', "Beta;": '\U00000392', "Bfr;": '\U0001D505', "Bopf;": '\U0001D539', "Breve;": '\U000002D8', "Bscr;": '\U0000212C', "Bumpeq;": '\U0000224E', "CHcy;": '\U00000427', "COPY;": '\U000000A9', "Cacute;": '\U00000106', "Cap;": '\U000022D2', "CapitalDifferentialD;": '\U00002145', "Cayleys;": '\U0000212D', "Ccaron;": '\U0000010C', "Ccedil;": '\U000000C7', "Ccirc;": '\U00000108', "Cconint;": '\U00002230', "Cdot;": '\U0000010A', "Cedilla;": '\U000000B8', "CenterDot;": '\U000000B7', "Cfr;": '\U0000212D', "Chi;": '\U000003A7', "CircleDot;": '\U00002299', "CircleMinus;": '\U00002296', "CirclePlus;": '\U00002295', "CircleTimes;": '\U00002297', "ClockwiseContourIntegral;": '\U00002232', "CloseCurlyDoubleQuote;": '\U0000201D', "CloseCurlyQuote;": '\U00002019', "Colon;": '\U00002237', "Colone;": '\U00002A74', "Congruent;": '\U00002261', "Conint;": '\U0000222F', "ContourIntegral;": '\U0000222E', "Copf;": '\U00002102', "Coproduct;": '\U00002210', "CounterClockwiseContourIntegral;": '\U00002233', "Cross;": '\U00002A2F', "Cscr;": '\U0001D49E', "Cup;": '\U000022D3', "CupCap;": '\U0000224D', "DD;": '\U00002145', "DDotrahd;": '\U00002911', "DJcy;": '\U00000402', "DScy;": '\U00000405', "DZcy;": '\U0000040F', "Dagger;": '\U00002021', "Darr;": '\U000021A1', "Dashv;": '\U00002AE4', "Dcaron;": '\U0000010E', "Dcy;": '\U00000414', "Del;": '\U00002207', "Delta;": '\U00000394', "Dfr;": '\U0001D507', "DiacriticalAcute;": '\U000000B4', "DiacriticalDot;": '\U000002D9', "DiacriticalDoubleAcute;": '\U000002DD', "DiacriticalGrave;": '\U00000060', "DiacriticalTilde;": '\U000002DC', "Diamond;": '\U000022C4', "DifferentialD;": '\U00002146', "Dopf;": '\U0001D53B', "Dot;": '\U000000A8', "DotDot;": '\U000020DC', "DotEqual;": '\U00002250', "DoubleContourIntegral;": '\U0000222F', "DoubleDot;": '\U000000A8', "DoubleDownArrow;": '\U000021D3', "DoubleLeftArrow;": '\U000021D0', "DoubleLeftRightArrow;": '\U000021D4', "DoubleLeftTee;": '\U00002AE4', "DoubleLongLeftArrow;": '\U000027F8', "DoubleLongLeftRightArrow;": '\U000027FA', "DoubleLongRightArrow;": '\U000027F9', "DoubleRightArrow;": '\U000021D2', "DoubleRightTee;": '\U000022A8', "DoubleUpArrow;": '\U000021D1', "DoubleUpDownArrow;": '\U000021D5', "DoubleVerticalBar;": '\U00002225', "DownArrow;": '\U00002193', "DownArrowBar;": '\U00002913', "DownArrowUpArrow;": '\U000021F5', "DownBreve;": '\U00000311', "DownLeftRightVector;": '\U00002950', "DownLeftTeeVector;": '\U0000295E', "DownLeftVector;": '\U000021BD', "DownLeftVectorBar;": '\U00002956', "DownRightTeeVector;": '\U0000295F', "DownRightVector;": '\U000021C1', "DownRightVectorBar;": '\U00002957', "DownTee;": '\U000022A4', "DownTeeArrow;": '\U000021A7', "Downarrow;": '\U000021D3', "Dscr;": '\U0001D49F', "Dstrok;": '\U00000110', "ENG;": '\U0000014A', "ETH;": '\U000000D0', "Eacute;": '\U000000C9', "Ecaron;": '\U0000011A', "Ecirc;": '\U000000CA', "Ecy;": '\U0000042D', "Edot;": '\U00000116', "Efr;": '\U0001D508', "Egrave;": '\U000000C8', "Element;": '\U00002208', "Emacr;": '\U00000112', "EmptySmallSquare;": '\U000025FB', "EmptyVerySmallSquare;": '\U000025AB', "Eogon;": '\U00000118', "Eopf;": '\U0001D53C', "Epsilon;": '\U00000395', "Equal;": '\U00002A75', "EqualTilde;": '\U00002242', "Equilibrium;": '\U000021CC', "Escr;": '\U00002130', "Esim;": '\U00002A73', "Eta;": '\U00000397', "Euml;": '\U000000CB', "Exists;": '\U00002203', "ExponentialE;": '\U00002147', "Fcy;": '\U00000424', "Ffr;": '\U0001D509', "FilledSmallSquare;": '\U000025FC', "FilledVerySmallSquare;": '\U000025AA', "Fopf;": '\U0001D53D', "ForAll;": '\U00002200', "Fouriertrf;": '\U00002131', "Fscr;": '\U00002131', "GJcy;": '\U00000403', "GT;": '\U0000003E', "Gamma;": '\U00000393', "Gammad;": '\U000003DC', "Gbreve;": '\U0000011E', "Gcedil;": '\U00000122', "Gcirc;": '\U0000011C', "Gcy;": '\U00000413', "Gdot;": '\U00000120', "Gfr;": '\U0001D50A', "Gg;": '\U000022D9', "Gopf;": '\U0001D53E', "GreaterEqual;": '\U00002265', "GreaterEqualLess;": '\U000022DB', "GreaterFullEqual;": '\U00002267', "GreaterGreater;": '\U00002AA2', "GreaterLess;": '\U00002277', "GreaterSlantEqual;": '\U00002A7E', "GreaterTilde;": '\U00002273', "Gscr;": '\U0001D4A2', "Gt;": '\U0000226B', "HARDcy;": '\U0000042A', "Hacek;": '\U000002C7', "Hat;": '\U0000005E', "Hcirc;": '\U00000124', "Hfr;": '\U0000210C', "HilbertSpace;": '\U0000210B', "Hopf;": '\U0000210D', "HorizontalLine;": '\U00002500', "Hscr;": '\U0000210B', "Hstrok;": '\U00000126', "HumpDownHump;": '\U0000224E', "HumpEqual;": '\U0000224F', "IEcy;": '\U00000415', "IJlig;": '\U00000132', "IOcy;": '\U00000401', "Iacute;": '\U000000CD', "Icirc;": '\U000000CE', "Icy;": '\U00000418', "Idot;": '\U00000130', "Ifr;": '\U00002111', "Igrave;": '\U000000CC', "Im;": '\U00002111', "Imacr;": '\U0000012A', "ImaginaryI;": '\U00002148', "Implies;": '\U000021D2', "Int;": '\U0000222C', "Integral;": '\U0000222B', "Intersection;": '\U000022C2', "InvisibleComma;": '\U00002063', "InvisibleTimes;": '\U00002062', "Iogon;": '\U0000012E', "Iopf;": '\U0001D540', "Iota;": '\U00000399', "Iscr;": '\U00002110', "Itilde;": '\U00000128', "Iukcy;": '\U00000406', "Iuml;": '\U000000CF', "Jcirc;": '\U00000134', "Jcy;": '\U00000419', "Jfr;": '\U0001D50D', "Jopf;": '\U0001D541', "Jscr;": '\U0001D4A5', "Jsercy;": '\U00000408', "Jukcy;": '\U00000404', "KHcy;": '\U00000425', "KJcy;": '\U0000040C', "Kappa;": '\U0000039A', "Kcedil;": '\U00000136', "Kcy;": '\U0000041A', "Kfr;": '\U0001D50E', "Kopf;": '\U0001D542', "Kscr;": '\U0001D4A6', "LJcy;": '\U00000409', "LT;": '\U0000003C', "Lacute;": '\U00000139', "Lambda;": '\U0000039B', "Lang;": '\U000027EA', "Laplacetrf;": '\U00002112', "Larr;": '\U0000219E', "Lcaron;": '\U0000013D', "Lcedil;": '\U0000013B', "Lcy;": '\U0000041B', "LeftAngleBracket;": '\U000027E8', "LeftArrow;": '\U00002190', "LeftArrowBar;": '\U000021E4', "LeftArrowRightArrow;": '\U000021C6', "LeftCeiling;": '\U00002308', "LeftDoubleBracket;": '\U000027E6', "LeftDownTeeVector;": '\U00002961', "LeftDownVector;": '\U000021C3', "LeftDownVectorBar;": '\U00002959', "LeftFloor;": '\U0000230A', "LeftRightArrow;": '\U00002194', "LeftRightVector;": '\U0000294E', "LeftTee;": '\U000022A3', "LeftTeeArrow;": '\U000021A4', "LeftTeeVector;": '\U0000295A', "LeftTriangle;": '\U000022B2', "LeftTriangleBar;": '\U000029CF', "LeftTriangleEqual;": '\U000022B4', "LeftUpDownVector;": '\U00002951', "LeftUpTeeVector;": '\U00002960', "LeftUpVector;": '\U000021BF', "LeftUpVectorBar;": '\U00002958', "LeftVector;": '\U000021BC', "LeftVectorBar;": '\U00002952', "Leftarrow;": '\U000021D0', "Leftrightarrow;": '\U000021D4', "LessEqualGreater;": '\U000022DA', "LessFullEqual;": '\U00002266', "LessGreater;": '\U00002276', "LessLess;": '\U00002AA1', "LessSlantEqual;": '\U00002A7D', "LessTilde;": '\U00002272', "Lfr;": '\U0001D50F', "Ll;": '\U000022D8', "Lleftarrow;": '\U000021DA', "Lmidot;": '\U0000013F', "LongLeftArrow;": '\U000027F5', "LongLeftRightArrow;": '\U000027F7', "LongRightArrow;": '\U000027F6', "Longleftarrow;": '\U000027F8', "Longleftrightarrow;": '\U000027FA', "Longrightarrow;": '\U000027F9', "Lopf;": '\U0001D543', "LowerLeftArrow;": '\U00002199', "LowerRightArrow;": '\U00002198', "Lscr;": '\U00002112', "Lsh;": '\U000021B0', "Lstrok;": '\U00000141', "Lt;": '\U0000226A', "Map;": '\U00002905', "Mcy;": '\U0000041C', "MediumSpace;": '\U0000205F', "Mellintrf;": '\U00002133', "Mfr;": '\U0001D510', "MinusPlus;": '\U00002213', "Mopf;": '\U0001D544', "Mscr;": '\U00002133', "Mu;": '\U0000039C', "NJcy;": '\U0000040A', "Nacute;": '\U00000143', "Ncaron;": '\U00000147', "Ncedil;": '\U00000145', "Ncy;": '\U0000041D', "NegativeMediumSpace;": '\U0000200B', "NegativeThickSpace;": '\U0000200B', "NegativeThinSpace;": '\U0000200B', "NegativeVeryThinSpace;": '\U0000200B', "NestedGreaterGreater;": '\U0000226B', "NestedLessLess;": '\U0000226A', "NewLine;": '\U0000000A', "Nfr;": '\U0001D511', "NoBreak;": '\U00002060', "NonBreakingSpace;": '\U000000A0', "Nopf;": '\U00002115', "Not;": '\U00002AEC', "NotCongruent;": '\U00002262', "NotCupCap;": '\U0000226D', "NotDoubleVerticalBar;": '\U00002226', "NotElement;": '\U00002209', "NotEqual;": '\U00002260', "NotExists;": '\U00002204', "NotGreater;": '\U0000226F', "NotGreaterEqual;": '\U00002271', "NotGreaterLess;": '\U00002279', "NotGreaterTilde;": '\U00002275', "NotLeftTriangle;": '\U000022EA', "NotLeftTriangleEqual;": '\U000022EC', "NotLess;": '\U0000226E', "NotLessEqual;": '\U00002270', "NotLessGreater;": '\U00002278', "NotLessTilde;": '\U00002274', "NotPrecedes;": '\U00002280', "NotPrecedesSlantEqual;": '\U000022E0', "NotReverseElement;": '\U0000220C', "NotRightTriangle;": '\U000022EB', "NotRightTriangleEqual;": '\U000022ED', "NotSquareSubsetEqual;": '\U000022E2', "NotSquareSupersetEqual;": '\U000022E3', "NotSubsetEqual;": '\U00002288', "NotSucceeds;": '\U00002281', "NotSucceedsSlantEqual;": '\U000022E1', "NotSupersetEqual;": '\U00002289', "NotTilde;": '\U00002241', "NotTildeEqual;": '\U00002244', "NotTildeFullEqual;": '\U00002247', "NotTildeTilde;": '\U00002249', "NotVerticalBar;": '\U00002224', "Nscr;": '\U0001D4A9', "Ntilde;": '\U000000D1', "Nu;": '\U0000039D', "OElig;": '\U00000152', "Oacute;": '\U000000D3', "Ocirc;": '\U000000D4', "Ocy;": '\U0000041E', "Odblac;": '\U00000150', "Ofr;": '\U0001D512', "Ograve;": '\U000000D2', "Omacr;": '\U0000014C', "Omega;": '\U000003A9', "Omicron;": '\U0000039F', "Oopf;": '\U0001D546', "OpenCurlyDoubleQuote;": '\U0000201C', "OpenCurlyQuote;": '\U00002018', "Or;": '\U00002A54', "Oscr;": '\U0001D4AA', "Oslash;": '\U000000D8', "Otilde;": '\U000000D5', "Otimes;": '\U00002A37', "Ouml;": '\U000000D6', "OverBar;": '\U0000203E', "OverBrace;": '\U000023DE', "OverBracket;": '\U000023B4', "OverParenthesis;": '\U000023DC', "PartialD;": '\U00002202', "Pcy;": '\U0000041F', "Pfr;": '\U0001D513', "Phi;": '\U000003A6', "Pi;": '\U000003A0', "PlusMinus;": '\U000000B1', "Poincareplane;": '\U0000210C', "Popf;": '\U00002119', "Pr;": '\U00002ABB', "Precedes;": '\U0000227A', "PrecedesEqual;": '\U00002AAF', "PrecedesSlantEqual;": '\U0000227C', "PrecedesTilde;": '\U0000227E', "Prime;": '\U00002033', "Product;": '\U0000220F', "Proportion;": '\U00002237', "Proportional;": '\U0000221D', "Pscr;": '\U0001D4AB', "Psi;": '\U000003A8', "QUOT;": '\U00000022', "Qfr;": '\U0001D514', "Qopf;": '\U0000211A', "Qscr;": '\U0001D4AC', "RBarr;": '\U00002910', "REG;": '\U000000AE', "Racute;": '\U00000154', "Rang;": '\U000027EB', "Rarr;": '\U000021A0', "Rarrtl;": '\U00002916', "Rcaron;": '\U00000158', "Rcedil;": '\U00000156', "Rcy;": '\U00000420', "Re;": '\U0000211C', "ReverseElement;": '\U0000220B', "ReverseEquilibrium;": '\U000021CB', "ReverseUpEquilibrium;": '\U0000296F', "Rfr;": '\U0000211C', "Rho;": '\U000003A1', "RightAngleBracket;": '\U000027E9', "RightArrow;": '\U00002192', "RightArrowBar;": '\U000021E5', "RightArrowLeftArrow;": '\U000021C4', "RightCeiling;": '\U00002309', "RightDoubleBracket;": '\U000027E7', "RightDownTeeVector;": '\U0000295D', "RightDownVector;": '\U000021C2', "RightDownVectorBar;": '\U00002955', "RightFloor;": '\U0000230B', "RightTee;": '\U000022A2', "RightTeeArrow;": '\U000021A6', "RightTeeVector;": '\U0000295B', "RightTriangle;": '\U000022B3', "RightTriangleBar;": '\U000029D0', "RightTriangleEqual;": '\U000022B5', "RightUpDownVector;": '\U0000294F', "RightUpTeeVector;": '\U0000295C', "RightUpVector;": '\U000021BE', "RightUpVectorBar;": '\U00002954', "RightVector;": '\U000021C0', "RightVectorBar;": '\U00002953', "Rightarrow;": '\U000021D2', "Ropf;": '\U0000211D', "RoundImplies;": '\U00002970', "Rrightarrow;": '\U000021DB', "Rscr;": '\U0000211B', "Rsh;": '\U000021B1', "RuleDelayed;": '\U000029F4', "SHCHcy;": '\U00000429', "SHcy;": '\U00000428', "SOFTcy;": '\U0000042C', "Sacute;": '\U0000015A', "Sc;": '\U00002ABC', "Scaron;": '\U00000160', "Scedil;": '\U0000015E', "Scirc;": '\U0000015C', "Scy;": '\U00000421', "Sfr;": '\U0001D516', "ShortDownArrow;": '\U00002193', "ShortLeftArrow;": '\U00002190', "ShortRightArrow;": '\U00002192', "ShortUpArrow;": '\U00002191', "Sigma;": '\U000003A3', "SmallCircle;": '\U00002218', "Sopf;": '\U0001D54A', "Sqrt;": '\U0000221A', "Square;": '\U000025A1', "SquareIntersection;": '\U00002293', "SquareSubset;": '\U0000228F', "SquareSubsetEqual;": '\U00002291', "SquareSuperset;": '\U00002290', "SquareSupersetEqual;": '\U00002292', "SquareUnion;": '\U00002294', "Sscr;": '\U0001D4AE', "Star;": '\U000022C6', "Sub;": '\U000022D0', "Subset;": '\U000022D0', "SubsetEqual;": '\U00002286', "Succeeds;": '\U0000227B', "SucceedsEqual;": '\U00002AB0', "SucceedsSlantEqual;": '\U0000227D', "SucceedsTilde;": '\U0000227F', "SuchThat;": '\U0000220B', "Sum;": '\U00002211', "Sup;": '\U000022D1', "Superset;": '\U00002283', "SupersetEqual;": '\U00002287', "Supset;": '\U000022D1', "THORN;": '\U000000DE', "TRADE;": '\U00002122', "TSHcy;": '\U0000040B', "TScy;": '\U00000426', "Tab;": '\U00000009', "Tau;": '\U000003A4', "Tcaron;": '\U00000164', "Tcedil;": '\U00000162', "Tcy;": '\U00000422', "Tfr;": '\U0001D517', "Therefore;": '\U00002234', "Theta;": '\U00000398', "ThinSpace;": '\U00002009', "Tilde;": '\U0000223C', "TildeEqual;": '\U00002243', "TildeFullEqual;": '\U00002245', "TildeTilde;": '\U00002248', "Topf;": '\U0001D54B', "TripleDot;": '\U000020DB', "Tscr;": '\U0001D4AF', "Tstrok;": '\U00000166', "Uacute;": '\U000000DA', "Uarr;": '\U0000219F', "Uarrocir;": '\U00002949', "Ubrcy;": '\U0000040E', "Ubreve;": '\U0000016C', "Ucirc;": '\U000000DB', "Ucy;": '\U00000423', "Udblac;": '\U00000170', "Ufr;": '\U0001D518', "Ugrave;": '\U000000D9', "Umacr;": '\U0000016A', "UnderBar;": '\U0000005F', "UnderBrace;": '\U000023DF', "UnderBracket;": '\U000023B5', "UnderParenthesis;": '\U000023DD', "Union;": '\U000022C3', "UnionPlus;": '\U0000228E', "Uogon;": '\U00000172', "Uopf;": '\U0001D54C', "UpArrow;": '\U00002191', "UpArrowBar;": '\U00002912', "UpArrowDownArrow;": '\U000021C5', "UpDownArrow;": '\U00002195', "UpEquilibrium;": '\U0000296E', "UpTee;": '\U000022A5', "UpTeeArrow;": '\U000021A5', "Uparrow;": '\U000021D1', "Updownarrow;": '\U000021D5', "UpperLeftArrow;": '\U00002196', "UpperRightArrow;": '\U00002197', "Upsi;": '\U000003D2', "Upsilon;": '\U000003A5', "Uring;": '\U0000016E', "Uscr;": '\U0001D4B0', "Utilde;": '\U00000168', "Uuml;": '\U000000DC', "VDash;": '\U000022AB', "Vbar;": '\U00002AEB', "Vcy;": '\U00000412', "Vdash;": '\U000022A9', "Vdashl;": '\U00002AE6', "Vee;": '\U000022C1', "Verbar;": '\U00002016', "Vert;": '\U00002016', "VerticalBar;": '\U00002223', "VerticalLine;": '\U0000007C', "VerticalSeparator;": '\U00002758', "VerticalTilde;": '\U00002240', "VeryThinSpace;": '\U0000200A', "Vfr;": '\U0001D519', "Vopf;": '\U0001D54D', "Vscr;": '\U0001D4B1', "Vvdash;": '\U000022AA', "Wcirc;": '\U00000174', "Wedge;": '\U000022C0', "Wfr;": '\U0001D51A', "Wopf;": '\U0001D54E', "Wscr;": '\U0001D4B2', "Xfr;": '\U0001D51B', "Xi;": '\U0000039E', "Xopf;": '\U0001D54F', "Xscr;": '\U0001D4B3', "YAcy;": '\U0000042F', "YIcy;": '\U00000407', "YUcy;": '\U0000042E', "Yacute;": '\U000000DD', "Ycirc;": '\U00000176', "Ycy;": '\U0000042B', "Yfr;": '\U0001D51C', "Yopf;": '\U0001D550', "Yscr;": '\U0001D4B4', "Yuml;": '\U00000178', "ZHcy;": '\U00000416', "Zacute;": '\U00000179', "Zcaron;": '\U0000017D', "Zcy;": '\U00000417', "Zdot;": '\U0000017B', "ZeroWidthSpace;": '\U0000200B', "Zeta;": '\U00000396', "Zfr;": '\U00002128', "Zopf;": '\U00002124', "Zscr;": '\U0001D4B5', "aacute;": '\U000000E1', "abreve;": '\U00000103', "ac;": '\U0000223E', "acd;": '\U0000223F', "acirc;": '\U000000E2', "acute;": '\U000000B4', "acy;": '\U00000430', "aelig;": '\U000000E6', "af;": '\U00002061', "afr;": '\U0001D51E', "agrave;": '\U000000E0', "alefsym;": '\U00002135', "aleph;": '\U00002135', "alpha;": '\U000003B1', "amacr;": '\U00000101', "amalg;": '\U00002A3F', "amp;": '\U00000026', "and;": '\U00002227', "andand;": '\U00002A55', "andd;": '\U00002A5C', "andslope;": '\U00002A58', "andv;": '\U00002A5A', "ang;": '\U00002220', "ange;": '\U000029A4', "angle;": '\U00002220', "angmsd;": '\U00002221', "angmsdaa;": '\U000029A8', "angmsdab;": '\U000029A9', "angmsdac;": '\U000029AA', "angmsdad;": '\U000029AB', "angmsdae;": '\U000029AC', "angmsdaf;": '\U000029AD', "angmsdag;": '\U000029AE', "angmsdah;": '\U000029AF', "angrt;": '\U0000221F', "angrtvb;": '\U000022BE', "angrtvbd;": '\U0000299D', "angsph;": '\U00002222', "angst;": '\U000000C5', "angzarr;": '\U0000237C', "aogon;": '\U00000105', "aopf;": '\U0001D552', "ap;": '\U00002248', "apE;": '\U00002A70', "apacir;": '\U00002A6F', "ape;": '\U0000224A', "apid;": '\U0000224B', "apos;": '\U00000027', "approx;": '\U00002248', "approxeq;": '\U0000224A', "aring;": '\U000000E5', "ascr;": '\U0001D4B6', "ast;": '\U0000002A', "asymp;": '\U00002248', "asympeq;": '\U0000224D', "atilde;": '\U000000E3', "auml;": '\U000000E4', "awconint;": '\U00002233', "awint;": '\U00002A11', "bNot;": '\U00002AED', "backcong;": '\U0000224C', "backepsilon;": '\U000003F6', "backprime;": '\U00002035', "backsim;": '\U0000223D', "backsimeq;": '\U000022CD', "barvee;": '\U000022BD', "barwed;": '\U00002305', "barwedge;": '\U00002305', "bbrk;": '\U000023B5', "bbrktbrk;": '\U000023B6', "bcong;": '\U0000224C', "bcy;": '\U00000431', "bdquo;": '\U0000201E', "becaus;": '\U00002235', "because;": '\U00002235', "bemptyv;": '\U000029B0', "bepsi;": '\U000003F6', "bernou;": '\U0000212C', "beta;": '\U000003B2', "beth;": '\U00002136', "between;": '\U0000226C', "bfr;": '\U0001D51F', "bigcap;": '\U000022C2', "bigcirc;": '\U000025EF', "bigcup;": '\U000022C3', "bigodot;": '\U00002A00', "bigoplus;": '\U00002A01', "bigotimes;": '\U00002A02', "bigsqcup;": '\U00002A06', "bigstar;": '\U00002605', "bigtriangledown;": '\U000025BD', "bigtriangleup;": '\U000025B3', "biguplus;": '\U00002A04', "bigvee;": '\U000022C1', "bigwedge;": '\U000022C0', "bkarow;": '\U0000290D', "blacklozenge;": '\U000029EB', "blacksquare;": '\U000025AA', "blacktriangle;": '\U000025B4', "blacktriangledown;": '\U000025BE', "blacktriangleleft;": '\U000025C2', "blacktriangleright;": '\U000025B8', "blank;": '\U00002423', "blk12;": '\U00002592', "blk14;": '\U00002591', "blk34;": '\U00002593', "block;": '\U00002588', "bnot;": '\U00002310', "bopf;": '\U0001D553', "bot;": '\U000022A5', "bottom;": '\U000022A5', "bowtie;": '\U000022C8', "boxDL;": '\U00002557', "boxDR;": '\U00002554', "boxDl;": '\U00002556', "boxDr;": '\U00002553', "boxH;": '\U00002550', "boxHD;": '\U00002566', "boxHU;": '\U00002569', "boxHd;": '\U00002564', "boxHu;": '\U00002567', "boxUL;": '\U0000255D', "boxUR;": '\U0000255A', "boxUl;": '\U0000255C', "boxUr;": '\U00002559', "boxV;": '\U00002551', "boxVH;": '\U0000256C', "boxVL;": '\U00002563', "boxVR;": '\U00002560', "boxVh;": '\U0000256B', "boxVl;": '\U00002562', "boxVr;": '\U0000255F', "boxbox;": '\U000029C9', "boxdL;": '\U00002555', "boxdR;": '\U00002552', "boxdl;": '\U00002510', "boxdr;": '\U0000250C', "boxh;": '\U00002500', "boxhD;": '\U00002565', "boxhU;": '\U00002568', "boxhd;": '\U0000252C', "boxhu;": '\U00002534', "boxminus;": '\U0000229F', "boxplus;": '\U0000229E', "boxtimes;": '\U000022A0', "boxuL;": '\U0000255B', "boxuR;": '\U00002558', "boxul;": '\U00002518', "boxur;": '\U00002514', "boxv;": '\U00002502', "boxvH;": '\U0000256A', "boxvL;": '\U00002561', "boxvR;": '\U0000255E', "boxvh;": '\U0000253C', "boxvl;": '\U00002524', "boxvr;": '\U0000251C', "bprime;": '\U00002035', "breve;": '\U000002D8', "brvbar;": '\U000000A6', "bscr;": '\U0001D4B7', "bsemi;": '\U0000204F', "bsim;": '\U0000223D', "bsime;": '\U000022CD', "bsol;": '\U0000005C', "bsolb;": '\U000029C5', "bsolhsub;": '\U000027C8', "bull;": '\U00002022', "bullet;": '\U00002022', "bump;": '\U0000224E', "bumpE;": '\U00002AAE', "bumpe;": '\U0000224F', "bumpeq;": '\U0000224F', "cacute;": '\U00000107', "cap;": '\U00002229', "capand;": '\U00002A44', "capbrcup;": '\U00002A49', "capcap;": '\U00002A4B', "capcup;": '\U00002A47', "capdot;": '\U00002A40', "caret;": '\U00002041', "caron;": '\U000002C7', "ccaps;": '\U00002A4D', "ccaron;": '\U0000010D', "ccedil;": '\U000000E7', "ccirc;": '\U00000109', "ccups;": '\U00002A4C', "ccupssm;": '\U00002A50', "cdot;": '\U0000010B', "cedil;": '\U000000B8', "cemptyv;": '\U000029B2', "cent;": '\U000000A2', "centerdot;": '\U000000B7', "cfr;": '\U0001D520', "chcy;": '\U00000447', "check;": '\U00002713', "checkmark;": '\U00002713', "chi;": '\U000003C7', "cir;": '\U000025CB', "cirE;": '\U000029C3', "circ;": '\U000002C6', "circeq;": '\U00002257', "circlearrowleft;": '\U000021BA', "circlearrowright;": '\U000021BB', "circledR;": '\U000000AE', "circledS;": '\U000024C8', "circledast;": '\U0000229B', "circledcirc;": '\U0000229A', "circleddash;": '\U0000229D', "cire;": '\U00002257', "cirfnint;": '\U00002A10', "cirmid;": '\U00002AEF', "cirscir;": '\U000029C2', "clubs;": '\U00002663', "clubsuit;": '\U00002663', "colon;": '\U0000003A', "colone;": '\U00002254', "coloneq;": '\U00002254', "comma;": '\U0000002C', "commat;": '\U00000040', "comp;": '\U00002201', "compfn;": '\U00002218', "complement;": '\U00002201', "complexes;": '\U00002102', "cong;": '\U00002245', "congdot;": '\U00002A6D', "conint;": '\U0000222E', "copf;": '\U0001D554', "coprod;": '\U00002210', "copy;": '\U000000A9', "copysr;": '\U00002117', "crarr;": '\U000021B5', "cross;": '\U00002717', "cscr;": '\U0001D4B8', "csub;": '\U00002ACF', "csube;": '\U00002AD1', "csup;": '\U00002AD0', "csupe;": '\U00002AD2', "ctdot;": '\U000022EF', "cudarrl;": '\U00002938', "cudarrr;": '\U00002935', "cuepr;": '\U000022DE', "cuesc;": '\U000022DF', "cularr;": '\U000021B6', "cularrp;": '\U0000293D', "cup;": '\U0000222A', "cupbrcap;": '\U00002A48', "cupcap;": '\U00002A46', "cupcup;": '\U00002A4A', "cupdot;": '\U0000228D', "cupor;": '\U00002A45', "curarr;": '\U000021B7', "curarrm;": '\U0000293C', "curlyeqprec;": '\U000022DE', "curlyeqsucc;": '\U000022DF', "curlyvee;": '\U000022CE', "curlywedge;": '\U000022CF', "curren;": '\U000000A4', "curvearrowleft;": '\U000021B6', "curvearrowright;": '\U000021B7', "cuvee;": '\U000022CE', "cuwed;": '\U000022CF', "cwconint;": '\U00002232', "cwint;": '\U00002231', "cylcty;": '\U0000232D', "dArr;": '\U000021D3', "dHar;": '\U00002965', "dagger;": '\U00002020', "daleth;": '\U00002138', "darr;": '\U00002193', "dash;": '\U00002010', "dashv;": '\U000022A3', "dbkarow;": '\U0000290F', "dblac;": '\U000002DD', "dcaron;": '\U0000010F', "dcy;": '\U00000434', "dd;": '\U00002146', "ddagger;": '\U00002021', "ddarr;": '\U000021CA', "ddotseq;": '\U00002A77', "deg;": '\U000000B0', "delta;": '\U000003B4', "demptyv;": '\U000029B1', "dfisht;": '\U0000297F', "dfr;": '\U0001D521', "dharl;": '\U000021C3', "dharr;": '\U000021C2', "diam;": '\U000022C4', "diamond;": '\U000022C4', "diamondsuit;": '\U00002666', "diams;": '\U00002666', "die;": '\U000000A8', "digamma;": '\U000003DD', "disin;": '\U000022F2', "div;": '\U000000F7', "divide;": '\U000000F7', "divideontimes;": '\U000022C7', "divonx;": '\U000022C7', "djcy;": '\U00000452', "dlcorn;": '\U0000231E', "dlcrop;": '\U0000230D', "dollar;": '\U00000024', "dopf;": '\U0001D555', "dot;": '\U000002D9', "doteq;": '\U00002250', "doteqdot;": '\U00002251', "dotminus;": '\U00002238', "dotplus;": '\U00002214', "dotsquare;": '\U000022A1', "doublebarwedge;": '\U00002306', "downarrow;": '\U00002193', "downdownarrows;": '\U000021CA', "downharpoonleft;": '\U000021C3', "downharpoonright;": '\U000021C2', "drbkarow;": '\U00002910', "drcorn;": '\U0000231F', "drcrop;": '\U0000230C', "dscr;": '\U0001D4B9', "dscy;": '\U00000455', "dsol;": '\U000029F6', "dstrok;": '\U00000111', "dtdot;": '\U000022F1', "dtri;": '\U000025BF', "dtrif;": '\U000025BE', "duarr;": '\U000021F5', "duhar;": '\U0000296F', "dwangle;": '\U000029A6', "dzcy;": '\U0000045F', "dzigrarr;": '\U000027FF', "eDDot;": '\U00002A77', "eDot;": '\U00002251', "eacute;": '\U000000E9', "easter;": '\U00002A6E', "ecaron;": '\U0000011B', "ecir;": '\U00002256', "ecirc;": '\U000000EA', "ecolon;": '\U00002255', "ecy;": '\U0000044D', "edot;": '\U00000117', "ee;": '\U00002147', "efDot;": '\U00002252', "efr;": '\U0001D522', "eg;": '\U00002A9A', "egrave;": '\U000000E8', "egs;": '\U00002A96', "egsdot;": '\U00002A98', "el;": '\U00002A99', "elinters;": '\U000023E7', "ell;": '\U00002113', "els;": '\U00002A95', "elsdot;": '\U00002A97', "emacr;": '\U00000113', "empty;": '\U00002205', "emptyset;": '\U00002205', "emptyv;": '\U00002205', "emsp;": '\U00002003', "emsp13;": '\U00002004', "emsp14;": '\U00002005', "eng;": '\U0000014B', "ensp;": '\U00002002', "eogon;": '\U00000119', "eopf;": '\U0001D556', "epar;": '\U000022D5', "eparsl;": '\U000029E3', "eplus;": '\U00002A71', "epsi;": '\U000003B5', "epsilon;": '\U000003B5', "epsiv;": '\U000003F5', "eqcirc;": '\U00002256', "eqcolon;": '\U00002255', "eqsim;": '\U00002242', "eqslantgtr;": '\U00002A96', "eqslantless;": '\U00002A95', "equals;": '\U0000003D', "equest;": '\U0000225F', "equiv;": '\U00002261', "equivDD;": '\U00002A78', "eqvparsl;": '\U000029E5', "erDot;": '\U00002253', "erarr;": '\U00002971', "escr;": '\U0000212F', "esdot;": '\U00002250', "esim;": '\U00002242', "eta;": '\U000003B7', "eth;": '\U000000F0', "euml;": '\U000000EB', "euro;": '\U000020AC', "excl;": '\U00000021', "exist;": '\U00002203', "expectation;": '\U00002130', "exponentiale;": '\U00002147', "fallingdotseq;": '\U00002252', "fcy;": '\U00000444', "female;": '\U00002640', "ffilig;": '\U0000FB03', "fflig;": '\U0000FB00', "ffllig;": '\U0000FB04', "ffr;": '\U0001D523', "filig;": '\U0000FB01', "flat;": '\U0000266D', "fllig;": '\U0000FB02', "fltns;": '\U000025B1', "fnof;": '\U00000192', "fopf;": '\U0001D557', "forall;": '\U00002200', "fork;": '\U000022D4', "forkv;": '\U00002AD9', "fpartint;": '\U00002A0D', "frac12;": '\U000000BD', "frac13;": '\U00002153', "frac14;": '\U000000BC', "frac15;": '\U00002155', "frac16;": '\U00002159', "frac18;": '\U0000215B', "frac23;": '\U00002154', "frac25;": '\U00002156', "frac34;": '\U000000BE', "frac35;": '\U00002157', "frac38;": '\U0000215C', "frac45;": '\U00002158', "frac56;": '\U0000215A', "frac58;": '\U0000215D', "frac78;": '\U0000215E', "frasl;": '\U00002044', "frown;": '\U00002322', "fscr;": '\U0001D4BB', "gE;": '\U00002267', "gEl;": '\U00002A8C', "gacute;": '\U000001F5', "gamma;": '\U000003B3', "gammad;": '\U000003DD', "gap;": '\U00002A86', "gbreve;": '\U0000011F', "gcirc;": '\U0000011D', "gcy;": '\U00000433', "gdot;": '\U00000121', "ge;": '\U00002265', "gel;": '\U000022DB', "geq;": '\U00002265', "geqq;": '\U00002267', "geqslant;": '\U00002A7E', "ges;": '\U00002A7E', "gescc;": '\U00002AA9', "gesdot;": '\U00002A80', "gesdoto;": '\U00002A82', "gesdotol;": '\U00002A84', "gesles;": '\U00002A94', "gfr;": '\U0001D524', "gg;": '\U0000226B', "ggg;": '\U000022D9', "gimel;": '\U00002137', "gjcy;": '\U00000453', "gl;": '\U00002277', "glE;": '\U00002A92', "gla;": '\U00002AA5', "glj;": '\U00002AA4', "gnE;": '\U00002269', "gnap;": '\U00002A8A', "gnapprox;": '\U00002A8A', "gne;": '\U00002A88', "gneq;": '\U00002A88', "gneqq;": '\U00002269', "gnsim;": '\U000022E7', "gopf;": '\U0001D558', "grave;": '\U00000060', "gscr;": '\U0000210A', "gsim;": '\U00002273', "gsime;": '\U00002A8E', "gsiml;": '\U00002A90', "gt;": '\U0000003E', "gtcc;": '\U00002AA7', "gtcir;": '\U00002A7A', "gtdot;": '\U000022D7', "gtlPar;": '\U00002995', "gtquest;": '\U00002A7C', "gtrapprox;": '\U00002A86', "gtrarr;": '\U00002978', "gtrdot;": '\U000022D7', "gtreqless;": '\U000022DB', "gtreqqless;": '\U00002A8C', "gtrless;": '\U00002277', "gtrsim;": '\U00002273', "hArr;": '\U000021D4', "hairsp;": '\U0000200A', "half;": '\U000000BD', "hamilt;": '\U0000210B', "hardcy;": '\U0000044A', "harr;": '\U00002194', "harrcir;": '\U00002948', "harrw;": '\U000021AD', "hbar;": '\U0000210F', "hcirc;": '\U00000125', "hearts;": '\U00002665', "heartsuit;": '\U00002665', "hellip;": '\U00002026', "hercon;": '\U000022B9', "hfr;": '\U0001D525', "hksearow;": '\U00002925', "hkswarow;": '\U00002926', "hoarr;": '\U000021FF', "homtht;": '\U0000223B', "hookleftarrow;": '\U000021A9', "hookrightarrow;": '\U000021AA', "hopf;": '\U0001D559', "horbar;": '\U00002015', "hscr;": '\U0001D4BD', "hslash;": '\U0000210F', "hstrok;": '\U00000127', "hybull;": '\U00002043', "hyphen;": '\U00002010', "iacute;": '\U000000ED', "ic;": '\U00002063', "icirc;": '\U000000EE', "icy;": '\U00000438', "iecy;": '\U00000435', "iexcl;": '\U000000A1', "iff;": '\U000021D4', "ifr;": '\U0001D526', "igrave;": '\U000000EC', "ii;": '\U00002148', "iiiint;": '\U00002A0C', "iiint;": '\U0000222D', "iinfin;": '\U000029DC', "iiota;": '\U00002129', "ijlig;": '\U00000133', "imacr;": '\U0000012B', "image;": '\U00002111', "imagline;": '\U00002110', "imagpart;": '\U00002111', "imath;": '\U00000131', "imof;": '\U000022B7', "imped;": '\U000001B5', "in;": '\U00002208', "incare;": '\U00002105', "infin;": '\U0000221E', "infintie;": '\U000029DD', "inodot;": '\U00000131', "int;": '\U0000222B', "intcal;": '\U000022BA', "integers;": '\U00002124', "intercal;": '\U000022BA', "intlarhk;": '\U00002A17', "intprod;": '\U00002A3C', "iocy;": '\U00000451', "iogon;": '\U0000012F', "iopf;": '\U0001D55A', "iota;": '\U000003B9', "iprod;": '\U00002A3C', "iquest;": '\U000000BF', "iscr;": '\U0001D4BE', "isin;": '\U00002208', "isinE;": '\U000022F9', "isindot;": '\U000022F5', "isins;": '\U000022F4', "isinsv;": '\U000022F3', "isinv;": '\U00002208', "it;": '\U00002062', "itilde;": '\U00000129', "iukcy;": '\U00000456', "iuml;": '\U000000EF', "jcirc;": '\U00000135', "jcy;": '\U00000439', "jfr;": '\U0001D527', "jmath;": '\U00000237', "jopf;": '\U0001D55B', "jscr;": '\U0001D4BF', "jsercy;": '\U00000458', "jukcy;": '\U00000454', "kappa;": '\U000003BA', "kappav;": '\U000003F0', "kcedil;": '\U00000137', "kcy;": '\U0000043A', "kfr;": '\U0001D528', "kgreen;": '\U00000138', "khcy;": '\U00000445', "kjcy;": '\U0000045C', "kopf;": '\U0001D55C', "kscr;": '\U0001D4C0', "lAarr;": '\U000021DA', "lArr;": '\U000021D0', "lAtail;": '\U0000291B', "lBarr;": '\U0000290E', "lE;": '\U00002266', "lEg;": '\U00002A8B', "lHar;": '\U00002962', "lacute;": '\U0000013A', "laemptyv;": '\U000029B4', "lagran;": '\U00002112', "lambda;": '\U000003BB', "lang;": '\U000027E8', "langd;": '\U00002991', "langle;": '\U000027E8', "lap;": '\U00002A85', "laquo;": '\U000000AB', "larr;": '\U00002190', "larrb;": '\U000021E4', "larrbfs;": '\U0000291F', "larrfs;": '\U0000291D', "larrhk;": '\U000021A9', "larrlp;": '\U000021AB', "larrpl;": '\U00002939', "larrsim;": '\U00002973', "larrtl;": '\U000021A2', "lat;": '\U00002AAB', "latail;": '\U00002919', "late;": '\U00002AAD', "lbarr;": '\U0000290C', "lbbrk;": '\U00002772', "lbrace;": '\U0000007B', "lbrack;": '\U0000005B', "lbrke;": '\U0000298B', "lbrksld;": '\U0000298F', "lbrkslu;": '\U0000298D', "lcaron;": '\U0000013E', "lcedil;": '\U0000013C', "lceil;": '\U00002308', "lcub;": '\U0000007B', "lcy;": '\U0000043B', "ldca;": '\U00002936', "ldquo;": '\U0000201C', "ldquor;": '\U0000201E', "ldrdhar;": '\U00002967', "ldrushar;": '\U0000294B', "ldsh;": '\U000021B2', "le;": '\U00002264', "leftarrow;": '\U00002190', "leftarrowtail;": '\U000021A2', "leftharpoondown;": '\U000021BD', "leftharpoonup;": '\U000021BC', "leftleftarrows;": '\U000021C7', "leftrightarrow;": '\U00002194', "leftrightarrows;": '\U000021C6', "leftrightharpoons;": '\U000021CB', "leftrightsquigarrow;": '\U000021AD', "leftthreetimes;": '\U000022CB', "leg;": '\U000022DA', "leq;": '\U00002264', "leqq;": '\U00002266', "leqslant;": '\U00002A7D', "les;": '\U00002A7D', "lescc;": '\U00002AA8', "lesdot;": '\U00002A7F', "lesdoto;": '\U00002A81', "lesdotor;": '\U00002A83', "lesges;": '\U00002A93', "lessapprox;": '\U00002A85', "lessdot;": '\U000022D6', "lesseqgtr;": '\U000022DA', "lesseqqgtr;": '\U00002A8B', "lessgtr;": '\U00002276', "lesssim;": '\U00002272', "lfisht;": '\U0000297C', "lfloor;": '\U0000230A', "lfr;": '\U0001D529', "lg;": '\U00002276', "lgE;": '\U00002A91', "lhard;": '\U000021BD', "lharu;": '\U000021BC', "lharul;": '\U0000296A', "lhblk;": '\U00002584', "ljcy;": '\U00000459', "ll;": '\U0000226A', "llarr;": '\U000021C7', "llcorner;": '\U0000231E', "llhard;": '\U0000296B', "lltri;": '\U000025FA', "lmidot;": '\U00000140', "lmoust;": '\U000023B0', "lmoustache;": '\U000023B0', "lnE;": '\U00002268', "lnap;": '\U00002A89', "lnapprox;": '\U00002A89', "lne;": '\U00002A87', "lneq;": '\U00002A87', "lneqq;": '\U00002268', "lnsim;": '\U000022E6', "loang;": '\U000027EC', "loarr;": '\U000021FD', "lobrk;": '\U000027E6', "longleftarrow;": '\U000027F5', "longleftrightarrow;": '\U000027F7', "longmapsto;": '\U000027FC', "longrightarrow;": '\U000027F6', "looparrowleft;": '\U000021AB', "looparrowright;": '\U000021AC', "lopar;": '\U00002985', "lopf;": '\U0001D55D', "loplus;": '\U00002A2D', "lotimes;": '\U00002A34', "lowast;": '\U00002217', "lowbar;": '\U0000005F', "loz;": '\U000025CA', "lozenge;": '\U000025CA', "lozf;": '\U000029EB', "lpar;": '\U00000028', "lparlt;": '\U00002993', "lrarr;": '\U000021C6', "lrcorner;": '\U0000231F', "lrhar;": '\U000021CB', "lrhard;": '\U0000296D', "lrm;": '\U0000200E', "lrtri;": '\U000022BF', "lsaquo;": '\U00002039', "lscr;": '\U0001D4C1', "lsh;": '\U000021B0', "lsim;": '\U00002272', "lsime;": '\U00002A8D', "lsimg;": '\U00002A8F', "lsqb;": '\U0000005B', "lsquo;": '\U00002018', "lsquor;": '\U0000201A', "lstrok;": '\U00000142', "lt;": '\U0000003C', "ltcc;": '\U00002AA6', "ltcir;": '\U00002A79', "ltdot;": '\U000022D6', "lthree;": '\U000022CB', "ltimes;": '\U000022C9', "ltlarr;": '\U00002976', "ltquest;": '\U00002A7B', "ltrPar;": '\U00002996', "ltri;": '\U000025C3', "ltrie;": '\U000022B4', "ltrif;": '\U000025C2', "lurdshar;": '\U0000294A', "luruhar;": '\U00002966', "mDDot;": '\U0000223A', "macr;": '\U000000AF', "male;": '\U00002642', "malt;": '\U00002720', "maltese;": '\U00002720', "map;": '\U000021A6', "mapsto;": '\U000021A6', "mapstodown;": '\U000021A7', "mapstoleft;": '\U000021A4', "mapstoup;": '\U000021A5', "marker;": '\U000025AE', "mcomma;": '\U00002A29', "mcy;": '\U0000043C', "mdash;": '\U00002014', "measuredangle;": '\U00002221', "mfr;": '\U0001D52A', "mho;": '\U00002127', "micro;": '\U000000B5', "mid;": '\U00002223', "midast;": '\U0000002A', "midcir;": '\U00002AF0', "middot;": '\U000000B7', "minus;": '\U00002212', "minusb;": '\U0000229F', "minusd;": '\U00002238', "minusdu;": '\U00002A2A', "mlcp;": '\U00002ADB', "mldr;": '\U00002026', "mnplus;": '\U00002213', "models;": '\U000022A7', "mopf;": '\U0001D55E', "mp;": '\U00002213', "mscr;": '\U0001D4C2', "mstpos;": '\U0000223E', "mu;": '\U000003BC', "multimap;": '\U000022B8', "mumap;": '\U000022B8', "nLeftarrow;": '\U000021CD', "nLeftrightarrow;": '\U000021CE', "nRightarrow;": '\U000021CF', "nVDash;": '\U000022AF', "nVdash;": '\U000022AE', "nabla;": '\U00002207', "nacute;": '\U00000144', "nap;": '\U00002249', "napos;": '\U00000149', "napprox;": '\U00002249', "natur;": '\U0000266E', "natural;": '\U0000266E', "naturals;": '\U00002115', "nbsp;": '\U000000A0', "ncap;": '\U00002A43', "ncaron;": '\U00000148', "ncedil;": '\U00000146', "ncong;": '\U00002247', "ncup;": '\U00002A42', "ncy;": '\U0000043D', "ndash;": '\U00002013', "ne;": '\U00002260', "neArr;": '\U000021D7', "nearhk;": '\U00002924', "nearr;": '\U00002197', "nearrow;": '\U00002197', "nequiv;": '\U00002262', "nesear;": '\U00002928', "nexist;": '\U00002204', "nexists;": '\U00002204', "nfr;": '\U0001D52B', "nge;": '\U00002271', "ngeq;": '\U00002271', "ngsim;": '\U00002275', "ngt;": '\U0000226F', "ngtr;": '\U0000226F', "nhArr;": '\U000021CE', "nharr;": '\U000021AE', "nhpar;": '\U00002AF2', "ni;": '\U0000220B', "nis;": '\U000022FC', "nisd;": '\U000022FA', "niv;": '\U0000220B', "njcy;": '\U0000045A', "nlArr;": '\U000021CD', "nlarr;": '\U0000219A', "nldr;": '\U00002025', "nle;": '\U00002270', "nleftarrow;": '\U0000219A', "nleftrightarrow;": '\U000021AE', "nleq;": '\U00002270', "nless;": '\U0000226E', "nlsim;": '\U00002274', "nlt;": '\U0000226E', "nltri;": '\U000022EA', "nltrie;": '\U000022EC', "nmid;": '\U00002224', "nopf;": '\U0001D55F', "not;": '\U000000AC', "notin;": '\U00002209', "notinva;": '\U00002209', "notinvb;": '\U000022F7', "notinvc;": '\U000022F6', "notni;": '\U0000220C', "notniva;": '\U0000220C', "notnivb;": '\U000022FE', "notnivc;": '\U000022FD', "npar;": '\U00002226', "nparallel;": '\U00002226', "npolint;": '\U00002A14', "npr;": '\U00002280', "nprcue;": '\U000022E0', "nprec;": '\U00002280', "nrArr;": '\U000021CF', "nrarr;": '\U0000219B', "nrightarrow;": '\U0000219B', "nrtri;": '\U000022EB', "nrtrie;": '\U000022ED', "nsc;": '\U00002281', "nsccue;": '\U000022E1', "nscr;": '\U0001D4C3', "nshortmid;": '\U00002224', "nshortparallel;": '\U00002226', "nsim;": '\U00002241', "nsime;": '\U00002244', "nsimeq;": '\U00002244', "nsmid;": '\U00002224', "nspar;": '\U00002226', "nsqsube;": '\U000022E2', "nsqsupe;": '\U000022E3', "nsub;": '\U00002284', "nsube;": '\U00002288', "nsubseteq;": '\U00002288', "nsucc;": '\U00002281', "nsup;": '\U00002285', "nsupe;": '\U00002289', "nsupseteq;": '\U00002289', "ntgl;": '\U00002279', "ntilde;": '\U000000F1', "ntlg;": '\U00002278', "ntriangleleft;": '\U000022EA', "ntrianglelefteq;": '\U000022EC', "ntriangleright;": '\U000022EB', "ntrianglerighteq;": '\U000022ED', "nu;": '\U000003BD', "num;": '\U00000023', "numero;": '\U00002116', "numsp;": '\U00002007', "nvDash;": '\U000022AD', "nvHarr;": '\U00002904', "nvdash;": '\U000022AC', "nvinfin;": '\U000029DE', "nvlArr;": '\U00002902', "nvrArr;": '\U00002903', "nwArr;": '\U000021D6', "nwarhk;": '\U00002923', "nwarr;": '\U00002196', "nwarrow;": '\U00002196', "nwnear;": '\U00002927', "oS;": '\U000024C8', "oacute;": '\U000000F3', "oast;": '\U0000229B', "ocir;": '\U0000229A', "ocirc;": '\U000000F4', "ocy;": '\U0000043E', "odash;": '\U0000229D', "odblac;": '\U00000151', "odiv;": '\U00002A38', "odot;": '\U00002299', "odsold;": '\U000029BC', "oelig;": '\U00000153', "ofcir;": '\U000029BF', "ofr;": '\U0001D52C', "ogon;": '\U000002DB', "ograve;": '\U000000F2', "ogt;": '\U000029C1', "ohbar;": '\U000029B5', "ohm;": '\U000003A9', "oint;": '\U0000222E', "olarr;": '\U000021BA', "olcir;": '\U000029BE', "olcross;": '\U000029BB', "oline;": '\U0000203E', "olt;": '\U000029C0', "omacr;": '\U0000014D', "omega;": '\U000003C9', "omicron;": '\U000003BF', "omid;": '\U000029B6', "ominus;": '\U00002296', "oopf;": '\U0001D560', "opar;": '\U000029B7', "operp;": '\U000029B9', "oplus;": '\U00002295', "or;": '\U00002228', "orarr;": '\U000021BB', "ord;": '\U00002A5D', "order;": '\U00002134', "orderof;": '\U00002134', "ordf;": '\U000000AA', "ordm;": '\U000000BA', "origof;": '\U000022B6', "oror;": '\U00002A56', "orslope;": '\U00002A57', "orv;": '\U00002A5B', "oscr;": '\U00002134', "oslash;": '\U000000F8', "osol;": '\U00002298', "otilde;": '\U000000F5', "otimes;": '\U00002297', "otimesas;": '\U00002A36', "ouml;": '\U000000F6', "ovbar;": '\U0000233D', "par;": '\U00002225', "para;": '\U000000B6', "parallel;": '\U00002225', "parsim;": '\U00002AF3', "parsl;": '\U00002AFD', "part;": '\U00002202', "pcy;": '\U0000043F', "percnt;": '\U00000025', "period;": '\U0000002E', "permil;": '\U00002030', "perp;": '\U000022A5', "pertenk;": '\U00002031', "pfr;": '\U0001D52D', "phi;": '\U000003C6', "phiv;": '\U000003D5', "phmmat;": '\U00002133', "phone;": '\U0000260E', "pi;": '\U000003C0', "pitchfork;": '\U000022D4', "piv;": '\U000003D6', "planck;": '\U0000210F', "planckh;": '\U0000210E', "plankv;": '\U0000210F', "plus;": '\U0000002B', "plusacir;": '\U00002A23', "plusb;": '\U0000229E', "pluscir;": '\U00002A22', "plusdo;": '\U00002214', "plusdu;": '\U00002A25', "pluse;": '\U00002A72', "plusmn;": '\U000000B1', "plussim;": '\U00002A26', "plustwo;": '\U00002A27', "pm;": '\U000000B1', "pointint;": '\U00002A15', "popf;": '\U0001D561', "pound;": '\U000000A3', "pr;": '\U0000227A', "prE;": '\U00002AB3', "prap;": '\U00002AB7', "prcue;": '\U0000227C', "pre;": '\U00002AAF', "prec;": '\U0000227A', "precapprox;": '\U00002AB7', "preccurlyeq;": '\U0000227C', "preceq;": '\U00002AAF', "precnapprox;": '\U00002AB9', "precneqq;": '\U00002AB5', "precnsim;": '\U000022E8', "precsim;": '\U0000227E', "prime;": '\U00002032', "primes;": '\U00002119', "prnE;": '\U00002AB5', "prnap;": '\U00002AB9', "prnsim;": '\U000022E8', "prod;": '\U0000220F', "profalar;": '\U0000232E', "profline;": '\U00002312', "profsurf;": '\U00002313', "prop;": '\U0000221D', "propto;": '\U0000221D', "prsim;": '\U0000227E', "prurel;": '\U000022B0', "pscr;": '\U0001D4C5', "psi;": '\U000003C8', "puncsp;": '\U00002008', "qfr;": '\U0001D52E', "qint;": '\U00002A0C', "qopf;": '\U0001D562', "qprime;": '\U00002057', "qscr;": '\U0001D4C6', "quaternions;": '\U0000210D', "quatint;": '\U00002A16', "quest;": '\U0000003F', "questeq;": '\U0000225F', "quot;": '\U00000022', "rAarr;": '\U000021DB', "rArr;": '\U000021D2', "rAtail;": '\U0000291C', "rBarr;": '\U0000290F', "rHar;": '\U00002964', "racute;": '\U00000155', "radic;": '\U0000221A', "raemptyv;": '\U000029B3', "rang;": '\U000027E9', "rangd;": '\U00002992', "range;": '\U000029A5', "rangle;": '\U000027E9', "raquo;": '\U000000BB', "rarr;": '\U00002192', "rarrap;": '\U00002975', "rarrb;": '\U000021E5', "rarrbfs;": '\U00002920', "rarrc;": '\U00002933', "rarrfs;": '\U0000291E', "rarrhk;": '\U000021AA', "rarrlp;": '\U000021AC', "rarrpl;": '\U00002945', "rarrsim;": '\U00002974', "rarrtl;": '\U000021A3', "rarrw;": '\U0000219D', "ratail;": '\U0000291A', "ratio;": '\U00002236', "rationals;": '\U0000211A', "rbarr;": '\U0000290D', "rbbrk;": '\U00002773', "rbrace;": '\U0000007D', "rbrack;": '\U0000005D', "rbrke;": '\U0000298C', "rbrksld;": '\U0000298E', "rbrkslu;": '\U00002990', "rcaron;": '\U00000159', "rcedil;": '\U00000157', "rceil;": '\U00002309', "rcub;": '\U0000007D', "rcy;": '\U00000440', "rdca;": '\U00002937', "rdldhar;": '\U00002969', "rdquo;": '\U0000201D', "rdquor;": '\U0000201D', "rdsh;": '\U000021B3', "real;": '\U0000211C', "realine;": '\U0000211B', "realpart;": '\U0000211C', "reals;": '\U0000211D', "rect;": '\U000025AD', "reg;": '\U000000AE', "rfisht;": '\U0000297D', "rfloor;": '\U0000230B', "rfr;": '\U0001D52F', "rhard;": '\U000021C1', "rharu;": '\U000021C0', "rharul;": '\U0000296C', "rho;": '\U000003C1', "rhov;": '\U000003F1', "rightarrow;": '\U00002192', "rightarrowtail;": '\U000021A3', "rightharpoondown;": '\U000021C1', "rightharpoonup;": '\U000021C0', "rightleftarrows;": '\U000021C4', "rightleftharpoons;": '\U000021CC', "rightrightarrows;": '\U000021C9', "rightsquigarrow;": '\U0000219D', "rightthreetimes;": '\U000022CC', "ring;": '\U000002DA', "risingdotseq;": '\U00002253', "rlarr;": '\U000021C4', "rlhar;": '\U000021CC', "rlm;": '\U0000200F', "rmoust;": '\U000023B1', "rmoustache;": '\U000023B1', "rnmid;": '\U00002AEE', "roang;": '\U000027ED', "roarr;": '\U000021FE', "robrk;": '\U000027E7', "ropar;": '\U00002986', "ropf;": '\U0001D563', "roplus;": '\U00002A2E', "rotimes;": '\U00002A35', "rpar;": '\U00000029', "rpargt;": '\U00002994', "rppolint;": '\U00002A12', "rrarr;": '\U000021C9', "rsaquo;": '\U0000203A', "rscr;": '\U0001D4C7', "rsh;": '\U000021B1', "rsqb;": '\U0000005D', "rsquo;": '\U00002019', "rsquor;": '\U00002019', "rthree;": '\U000022CC', "rtimes;": '\U000022CA', "rtri;": '\U000025B9', "rtrie;": '\U000022B5', "rtrif;": '\U000025B8', "rtriltri;": '\U000029CE', "ruluhar;": '\U00002968', "rx;": '\U0000211E', "sacute;": '\U0000015B', "sbquo;": '\U0000201A', "sc;": '\U0000227B', "scE;": '\U00002AB4', "scap;": '\U00002AB8', "scaron;": '\U00000161', "sccue;": '\U0000227D', "sce;": '\U00002AB0', "scedil;": '\U0000015F', "scirc;": '\U0000015D', "scnE;": '\U00002AB6', "scnap;": '\U00002ABA', "scnsim;": '\U000022E9', "scpolint;": '\U00002A13', "scsim;": '\U0000227F', "scy;": '\U00000441', "sdot;": '\U000022C5', "sdotb;": '\U000022A1', "sdote;": '\U00002A66', "seArr;": '\U000021D8', "searhk;": '\U00002925', "searr;": '\U00002198', "searrow;": '\U00002198', "sect;": '\U000000A7', "semi;": '\U0000003B', "seswar;": '\U00002929', "setminus;": '\U00002216', "setmn;": '\U00002216', "sext;": '\U00002736', "sfr;": '\U0001D530', "sfrown;": '\U00002322', "sharp;": '\U0000266F', "shchcy;": '\U00000449', "shcy;": '\U00000448', "shortmid;": '\U00002223', "shortparallel;": '\U00002225', "shy;": '\U000000AD', "sigma;": '\U000003C3', "sigmaf;": '\U000003C2', "sigmav;": '\U000003C2', "sim;": '\U0000223C', "simdot;": '\U00002A6A', "sime;": '\U00002243', "simeq;": '\U00002243', "simg;": '\U00002A9E', "simgE;": '\U00002AA0', "siml;": '\U00002A9D', "simlE;": '\U00002A9F', "simne;": '\U00002246', "simplus;": '\U00002A24', "simrarr;": '\U00002972', "slarr;": '\U00002190', "smallsetminus;": '\U00002216', "smashp;": '\U00002A33', "smeparsl;": '\U000029E4', "smid;": '\U00002223', "smile;": '\U00002323', "smt;": '\U00002AAA', "smte;": '\U00002AAC', "softcy;": '\U0000044C', "sol;": '\U0000002F', "solb;": '\U000029C4', "solbar;": '\U0000233F', "sopf;": '\U0001D564', "spades;": '\U00002660', "spadesuit;": '\U00002660', "spar;": '\U00002225', "sqcap;": '\U00002293', "sqcup;": '\U00002294', "sqsub;": '\U0000228F', "sqsube;": '\U00002291', "sqsubset;": '\U0000228F', "sqsubseteq;": '\U00002291', "sqsup;": '\U00002290', "sqsupe;": '\U00002292', "sqsupset;": '\U00002290', "sqsupseteq;": '\U00002292', "squ;": '\U000025A1', "square;": '\U000025A1', "squarf;": '\U000025AA', "squf;": '\U000025AA', "srarr;": '\U00002192', "sscr;": '\U0001D4C8', "ssetmn;": '\U00002216', "ssmile;": '\U00002323', "sstarf;": '\U000022C6', "star;": '\U00002606', "starf;": '\U00002605', "straightepsilon;": '\U000003F5', "straightphi;": '\U000003D5', "strns;": '\U000000AF', "sub;": '\U00002282', "subE;": '\U00002AC5', "subdot;": '\U00002ABD', "sube;": '\U00002286', "subedot;": '\U00002AC3', "submult;": '\U00002AC1', "subnE;": '\U00002ACB', "subne;": '\U0000228A', "subplus;": '\U00002ABF', "subrarr;": '\U00002979', "subset;": '\U00002282', "subseteq;": '\U00002286', "subseteqq;": '\U00002AC5', "subsetneq;": '\U0000228A', "subsetneqq;": '\U00002ACB', "subsim;": '\U00002AC7', "subsub;": '\U00002AD5', "subsup;": '\U00002AD3', "succ;": '\U0000227B', "succapprox;": '\U00002AB8', "succcurlyeq;": '\U0000227D', "succeq;": '\U00002AB0', "succnapprox;": '\U00002ABA', "succneqq;": '\U00002AB6', "succnsim;": '\U000022E9', "succsim;": '\U0000227F', "sum;": '\U00002211', "sung;": '\U0000266A', "sup;": '\U00002283', "sup1;": '\U000000B9', "sup2;": '\U000000B2', "sup3;": '\U000000B3', "supE;": '\U00002AC6', "supdot;": '\U00002ABE', "supdsub;": '\U00002AD8', "supe;": '\U00002287', "supedot;": '\U00002AC4', "suphsol;": '\U000027C9', "suphsub;": '\U00002AD7', "suplarr;": '\U0000297B', "supmult;": '\U00002AC2', "supnE;": '\U00002ACC', "supne;": '\U0000228B', "supplus;": '\U00002AC0', "supset;": '\U00002283', "supseteq;": '\U00002287', "supseteqq;": '\U00002AC6', "supsetneq;": '\U0000228B', "supsetneqq;": '\U00002ACC', "supsim;": '\U00002AC8', "supsub;": '\U00002AD4', "supsup;": '\U00002AD6', "swArr;": '\U000021D9', "swarhk;": '\U00002926', "swarr;": '\U00002199', "swarrow;": '\U00002199', "swnwar;": '\U0000292A', "szlig;": '\U000000DF', "target;": '\U00002316', "tau;": '\U000003C4', "tbrk;": '\U000023B4', "tcaron;": '\U00000165', "tcedil;": '\U00000163', "tcy;": '\U00000442', "tdot;": '\U000020DB', "telrec;": '\U00002315', "tfr;": '\U0001D531', "there4;": '\U00002234', "therefore;": '\U00002234', "theta;": '\U000003B8', "thetasym;": '\U000003D1', "thetav;": '\U000003D1', "thickapprox;": '\U00002248', "thicksim;": '\U0000223C', "thinsp;": '\U00002009', "thkap;": '\U00002248', "thksim;": '\U0000223C', "thorn;": '\U000000FE', "tilde;": '\U000002DC', "times;": '\U000000D7', "timesb;": '\U000022A0', "timesbar;": '\U00002A31', "timesd;": '\U00002A30', "tint;": '\U0000222D', "toea;": '\U00002928', "top;": '\U000022A4', "topbot;": '\U00002336', "topcir;": '\U00002AF1', "topf;": '\U0001D565', "topfork;": '\U00002ADA', "tosa;": '\U00002929', "tprime;": '\U00002034', "trade;": '\U00002122', "triangle;": '\U000025B5', "triangledown;": '\U000025BF', "triangleleft;": '\U000025C3', "trianglelefteq;": '\U000022B4', "triangleq;": '\U0000225C', "triangleright;": '\U000025B9', "trianglerighteq;": '\U000022B5', "tridot;": '\U000025EC', "trie;": '\U0000225C', "triminus;": '\U00002A3A', "triplus;": '\U00002A39', "trisb;": '\U000029CD', "tritime;": '\U00002A3B', "trpezium;": '\U000023E2', "tscr;": '\U0001D4C9', "tscy;": '\U00000446', "tshcy;": '\U0000045B', "tstrok;": '\U00000167', "twixt;": '\U0000226C', "twoheadleftarrow;": '\U0000219E', "twoheadrightarrow;": '\U000021A0', "uArr;": '\U000021D1', "uHar;": '\U00002963', "uacute;": '\U000000FA', "uarr;": '\U00002191', "ubrcy;": '\U0000045E', "ubreve;": '\U0000016D', "ucirc;": '\U000000FB', "ucy;": '\U00000443', "udarr;": '\U000021C5', "udblac;": '\U00000171', "udhar;": '\U0000296E', "ufisht;": '\U0000297E', "ufr;": '\U0001D532', "ugrave;": '\U000000F9', "uharl;": '\U000021BF', "uharr;": '\U000021BE', "uhblk;": '\U00002580', "ulcorn;": '\U0000231C', "ulcorner;": '\U0000231C', "ulcrop;": '\U0000230F', "ultri;": '\U000025F8', "umacr;": '\U0000016B', "uml;": '\U000000A8', "uogon;": '\U00000173', "uopf;": '\U0001D566', "uparrow;": '\U00002191', "updownarrow;": '\U00002195', "upharpoonleft;": '\U000021BF', "upharpoonright;": '\U000021BE', "uplus;": '\U0000228E', "upsi;": '\U000003C5', "upsih;": '\U000003D2', "upsilon;": '\U000003C5', "upuparrows;": '\U000021C8', "urcorn;": '\U0000231D', "urcorner;": '\U0000231D', "urcrop;": '\U0000230E', "uring;": '\U0000016F', "urtri;": '\U000025F9', "uscr;": '\U0001D4CA', "utdot;": '\U000022F0', "utilde;": '\U00000169', "utri;": '\U000025B5', "utrif;": '\U000025B4', "uuarr;": '\U000021C8', "uuml;": '\U000000FC', "uwangle;": '\U000029A7', "vArr;": '\U000021D5', "vBar;": '\U00002AE8', "vBarv;": '\U00002AE9', "vDash;": '\U000022A8', "vangrt;": '\U0000299C', "varepsilon;": '\U000003F5', "varkappa;": '\U000003F0', "varnothing;": '\U00002205', "varphi;": '\U000003D5', "varpi;": '\U000003D6', "varpropto;": '\U0000221D', "varr;": '\U00002195', "varrho;": '\U000003F1', "varsigma;": '\U000003C2', "vartheta;": '\U000003D1', "vartriangleleft;": '\U000022B2', "vartriangleright;": '\U000022B3', "vcy;": '\U00000432', "vdash;": '\U000022A2', "vee;": '\U00002228', "veebar;": '\U000022BB', "veeeq;": '\U0000225A', "vellip;": '\U000022EE', "verbar;": '\U0000007C', "vert;": '\U0000007C', "vfr;": '\U0001D533', "vltri;": '\U000022B2', "vopf;": '\U0001D567', "vprop;": '\U0000221D', "vrtri;": '\U000022B3', "vscr;": '\U0001D4CB', "vzigzag;": '\U0000299A', "wcirc;": '\U00000175', "wedbar;": '\U00002A5F', "wedge;": '\U00002227', "wedgeq;": '\U00002259', "weierp;": '\U00002118', "wfr;": '\U0001D534', "wopf;": '\U0001D568', "wp;": '\U00002118', "wr;": '\U00002240', "wreath;": '\U00002240', "wscr;": '\U0001D4CC', "xcap;": '\U000022C2', "xcirc;": '\U000025EF', "xcup;": '\U000022C3', "xdtri;": '\U000025BD', "xfr;": '\U0001D535', "xhArr;": '\U000027FA', "xharr;": '\U000027F7', "xi;": '\U000003BE', "xlArr;": '\U000027F8', "xlarr;": '\U000027F5', "xmap;": '\U000027FC', "xnis;": '\U000022FB', "xodot;": '\U00002A00', "xopf;": '\U0001D569', "xoplus;": '\U00002A01', "xotime;": '\U00002A02', "xrArr;": '\U000027F9', "xrarr;": '\U000027F6', "xscr;": '\U0001D4CD', "xsqcup;": '\U00002A06', "xuplus;": '\U00002A04', "xutri;": '\U000025B3', "xvee;": '\U000022C1', "xwedge;": '\U000022C0', "yacute;": '\U000000FD', "yacy;": '\U0000044F', "ycirc;": '\U00000177', "ycy;": '\U0000044B', "yen;": '\U000000A5', "yfr;": '\U0001D536', "yicy;": '\U00000457', "yopf;": '\U0001D56A', "yscr;": '\U0001D4CE', "yucy;": '\U0000044E', "yuml;": '\U000000FF', "zacute;": '\U0000017A', "zcaron;": '\U0000017E', "zcy;": '\U00000437', "zdot;": '\U0000017C', "zeetrf;": '\U00002128', "zeta;": '\U000003B6', "zfr;": '\U0001D537', "zhcy;": '\U00000436', "zigrarr;": '\U000021DD', "zopf;": '\U0001D56B', "zscr;": '\U0001D4CF', "zwj;": '\U0000200D', "zwnj;": '\U0000200C', "AElig": '\U000000C6', "AMP": '\U00000026', "Aacute": '\U000000C1', "Acirc": '\U000000C2', "Agrave": '\U000000C0', "Aring": '\U000000C5', "Atilde": '\U000000C3', "Auml": '\U000000C4', "COPY": '\U000000A9', "Ccedil": '\U000000C7', "ETH": '\U000000D0', "Eacute": '\U000000C9', "Ecirc": '\U000000CA', "Egrave": '\U000000C8', "Euml": '\U000000CB', "GT": '\U0000003E', "Iacute": '\U000000CD', "Icirc": '\U000000CE', "Igrave": '\U000000CC', "Iuml": '\U000000CF', "LT": '\U0000003C', "Ntilde": '\U000000D1', "Oacute": '\U000000D3', "Ocirc": '\U000000D4', "Ograve": '\U000000D2', "Oslash": '\U000000D8', "Otilde": '\U000000D5', "Ouml": '\U000000D6', "QUOT": '\U00000022', "REG": '\U000000AE', "THORN": '\U000000DE', "Uacute": '\U000000DA', "Ucirc": '\U000000DB', "Ugrave": '\U000000D9', "Uuml": '\U000000DC', "Yacute": '\U000000DD', "aacute": '\U000000E1', "acirc": '\U000000E2', "acute": '\U000000B4', "aelig": '\U000000E6', "agrave": '\U000000E0', "amp": '\U00000026', "aring": '\U000000E5', "atilde": '\U000000E3', "auml": '\U000000E4', "brvbar": '\U000000A6', "ccedil": '\U000000E7', "cedil": '\U000000B8', "cent": '\U000000A2', "copy": '\U000000A9', "curren": '\U000000A4', "deg": '\U000000B0', "divide": '\U000000F7', "eacute": '\U000000E9', "ecirc": '\U000000EA', "egrave": '\U000000E8', "eth": '\U000000F0', "euml": '\U000000EB', "frac12": '\U000000BD', "frac14": '\U000000BC', "frac34": '\U000000BE', "gt": '\U0000003E', "iacute": '\U000000ED', "icirc": '\U000000EE', "iexcl": '\U000000A1', "igrave": '\U000000EC', "iquest": '\U000000BF', "iuml": '\U000000EF', "laquo": '\U000000AB', "lt": '\U0000003C', "macr": '\U000000AF', "micro": '\U000000B5', "middot": '\U000000B7', "nbsp": '\U000000A0', "not": '\U000000AC', "ntilde": '\U000000F1', "oacute": '\U000000F3', "ocirc": '\U000000F4', "ograve": '\U000000F2', "ordf": '\U000000AA', "ordm": '\U000000BA', "oslash": '\U000000F8', "otilde": '\U000000F5', "ouml": '\U000000F6', "para": '\U000000B6', "plusmn": '\U000000B1', "pound": '\U000000A3', "quot": '\U00000022', "raquo": '\U000000BB', "reg": '\U000000AE', "sect": '\U000000A7', "shy": '\U000000AD', "sup1": '\U000000B9', "sup2": '\U000000B2', "sup3": '\U000000B3', "szlig": '\U000000DF', "thorn": '\U000000FE', "times": '\U000000D7', "uacute": '\U000000FA', "ucirc": '\U000000FB', "ugrave": '\U000000F9', "uml": '\U000000A8', "uuml": '\U000000FC', "yacute": '\U000000FD', "yen": '\U000000A5', "yuml": '\U000000FF', } // HTML entities that are two unicode codepoints. var entity2 = map[string][2]rune{ // TODO(nigeltao): Handle replacements that are wider than their names. // "nLt;": {'\u226A', '\u20D2'}, // "nGt;": {'\u226B', '\u20D2'}, "NotEqualTilde;": {'\u2242', '\u0338'}, "NotGreaterFullEqual;": {'\u2267', '\u0338'}, "NotGreaterGreater;": {'\u226B', '\u0338'}, "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'}, "NotHumpDownHump;": {'\u224E', '\u0338'}, "NotHumpEqual;": {'\u224F', '\u0338'}, "NotLeftTriangleBar;": {'\u29CF', '\u0338'}, "NotLessLess;": {'\u226A', '\u0338'}, "NotLessSlantEqual;": {'\u2A7D', '\u0338'}, "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'}, "NotNestedLessLess;": {'\u2AA1', '\u0338'}, "NotPrecedesEqual;": {'\u2AAF', '\u0338'}, "NotRightTriangleBar;": {'\u29D0', '\u0338'}, "NotSquareSubset;": {'\u228F', '\u0338'}, "NotSquareSuperset;": {'\u2290', '\u0338'}, "NotSubset;": {'\u2282', '\u20D2'}, "NotSucceedsEqual;": {'\u2AB0', '\u0338'}, "NotSucceedsTilde;": {'\u227F', '\u0338'}, "NotSuperset;": {'\u2283', '\u20D2'}, "ThickSpace;": {'\u205F', '\u200A'}, "acE;": {'\u223E', '\u0333'}, "bne;": {'\u003D', '\u20E5'}, "bnequiv;": {'\u2261', '\u20E5'}, "caps;": {'\u2229', '\uFE00'}, "cups;": {'\u222A', '\uFE00'}, "fjlig;": {'\u0066', '\u006A'}, "gesl;": {'\u22DB', '\uFE00'}, "gvertneqq;": {'\u2269', '\uFE00'}, "gvnE;": {'\u2269', '\uFE00'}, "lates;": {'\u2AAD', '\uFE00'}, "lesg;": {'\u22DA', '\uFE00'}, "lvertneqq;": {'\u2268', '\uFE00'}, "lvnE;": {'\u2268', '\uFE00'}, "nGg;": {'\u22D9', '\u0338'}, "nGtv;": {'\u226B', '\u0338'}, "nLl;": {'\u22D8', '\u0338'}, "nLtv;": {'\u226A', '\u0338'}, "nang;": {'\u2220', '\u20D2'}, "napE;": {'\u2A70', '\u0338'}, "napid;": {'\u224B', '\u0338'}, "nbump;": {'\u224E', '\u0338'}, "nbumpe;": {'\u224F', '\u0338'}, "ncongdot;": {'\u2A6D', '\u0338'}, "nedot;": {'\u2250', '\u0338'}, "nesim;": {'\u2242', '\u0338'}, "ngE;": {'\u2267', '\u0338'}, "ngeqq;": {'\u2267', '\u0338'}, "ngeqslant;": {'\u2A7E', '\u0338'}, "nges;": {'\u2A7E', '\u0338'}, "nlE;": {'\u2266', '\u0338'}, "nleqq;": {'\u2266', '\u0338'}, "nleqslant;": {'\u2A7D', '\u0338'}, "nles;": {'\u2A7D', '\u0338'}, "notinE;": {'\u22F9', '\u0338'}, "notindot;": {'\u22F5', '\u0338'}, "nparsl;": {'\u2AFD', '\u20E5'}, "npart;": {'\u2202', '\u0338'}, "npre;": {'\u2AAF', '\u0338'}, "npreceq;": {'\u2AAF', '\u0338'}, "nrarrc;": {'\u2933', '\u0338'}, "nrarrw;": {'\u219D', '\u0338'}, "nsce;": {'\u2AB0', '\u0338'}, "nsubE;": {'\u2AC5', '\u0338'}, "nsubset;": {'\u2282', '\u20D2'}, "nsubseteqq;": {'\u2AC5', '\u0338'}, "nsucceq;": {'\u2AB0', '\u0338'}, "nsupE;": {'\u2AC6', '\u0338'}, "nsupset;": {'\u2283', '\u20D2'}, "nsupseteqq;": {'\u2AC6', '\u0338'}, "nvap;": {'\u224D', '\u20D2'}, "nvge;": {'\u2265', '\u20D2'}, "nvgt;": {'\u003E', '\u20D2'}, "nvle;": {'\u2264', '\u20D2'}, "nvlt;": {'\u003C', '\u20D2'}, "nvltrie;": {'\u22B4', '\u20D2'}, "nvrtrie;": {'\u22B5', '\u20D2'}, "nvsim;": {'\u223C', '\u20D2'}, "race;": {'\u223D', '\u0331'}, "smtes;": {'\u2AAC', '\uFE00'}, "sqcaps;": {'\u2293', '\uFE00'}, "sqcups;": {'\u2294', '\uFE00'}, "varsubsetneq;": {'\u228A', '\uFE00'}, "varsubsetneqq;": {'\u2ACB', '\uFE00'}, "varsupsetneq;": {'\u228B', '\uFE00'}, "varsupsetneqq;": {'\u2ACC', '\uFE00'}, "vnsub;": {'\u2282', '\u20D2'}, "vnsup;": {'\u2283', '\u20D2'}, "vsubnE;": {'\u2ACB', '\uFE00'}, "vsubne;": {'\u228A', '\uFE00'}, "vsupnE;": {'\u2ACC', '\uFE00'}, "vsupne;": {'\u228B', '\uFE00'}, } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/doctype.go������������������������������������������������0000644�0610621�0607500�00000011475�13172163402�023265� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "strings" ) // parseDoctype parses the data from a DoctypeToken into a name, // public identifier, and system identifier. It returns a Node whose Type // is DoctypeNode, whose Data is the name, and which has attributes // named "system" and "public" for the two identifiers if they were present. // quirks is whether the document should be parsed in "quirks mode". func parseDoctype(s string) (n *Node, quirks bool) { n = &Node{Type: DoctypeNode} // Find the name. space := strings.IndexAny(s, whitespace) if space == -1 { space = len(s) } n.Data = s[:space] // The comparison to "html" is case-sensitive. if n.Data != "html" { quirks = true } n.Data = strings.ToLower(n.Data) s = strings.TrimLeft(s[space:], whitespace) if len(s) < 6 { // It can't start with "PUBLIC" or "SYSTEM". // Ignore the rest of the string. return n, quirks || s != "" } key := strings.ToLower(s[:6]) s = s[6:] for key == "public" || key == "system" { s = strings.TrimLeft(s, whitespace) if s == "" { break } quote := s[0] if quote != '"' && quote != '\'' { break } s = s[1:] q := strings.IndexRune(s, rune(quote)) var id string if q == -1 { id = s s = "" } else { id = s[:q] s = s[q+1:] } n.Attr = append(n.Attr, Attribute{Key: key, Val: id}) if key == "public" { key = "system" } else { key = "" } } if key != "" || s != "" { quirks = true } else if len(n.Attr) > 0 { if n.Attr[0].Key == "public" { public := strings.ToLower(n.Attr[0].Val) switch public { case "-//w3o//dtd w3 html strict 3.0//en//", "-/w3d/dtd html 4.0 transitional/en", "html": quirks = true default: for _, q := range quirkyIDs { if strings.HasPrefix(public, q) { quirks = true break } } } // The following two public IDs only cause quirks mode if there is no system ID. if len(n.Attr) == 1 && (strings.HasPrefix(public, "-//w3c//dtd html 4.01 frameset//") || strings.HasPrefix(public, "-//w3c//dtd html 4.01 transitional//")) { quirks = true } } if lastAttr := n.Attr[len(n.Attr)-1]; lastAttr.Key == "system" && strings.ToLower(lastAttr.Val) == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" { quirks = true } } return n, quirks } // quirkyIDs is a list of public doctype identifiers that cause a document // to be interpreted in quirks mode. The identifiers should be in lower case. var quirkyIDs = []string{ "+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//", } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/doc.go����������������������������������������������������0000644�0610621�0607500�00000006476�13172163402�022370� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package html implements an HTML5-compliant tokenizer and parser. Tokenization is done by creating a Tokenizer for an io.Reader r. It is the caller's responsibility to ensure that r provides UTF-8 encoded HTML. z := html.NewTokenizer(r) Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(), which parses the next token and returns its type, or an error: for { tt := z.Next() if tt == html.ErrorToken { // ... return ... } // Process the current token. } There are two APIs for retrieving the current token. The high-level API is to call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs allow optionally calling Raw after Next but before Token, Text, TagName, or TagAttr. In EBNF notation, the valid call sequence per token is: Next {Raw} [ Token | Text | TagName {TagAttr} ] Token returns an independent data structure that completely describes a token. Entities (such as "&lt;") are unescaped, tag names and attribute keys are lower-cased, and attributes are collected into a []Attribute. For example: for { if z.Next() == html.ErrorToken { // Returning io.EOF indicates success. return z.Err() } emitToken(z.Token()) } The low-level API performs fewer allocations and copies, but the contents of the []byte values returned by Text, TagName and TagAttr may change on the next call to Next. For example, to extract an HTML page's anchor text: depth := 0 for { tt := z.Next() switch tt { case ErrorToken: return z.Err() case TextToken: if depth > 0 { // emitBytes should copy the []byte it receives, // if it doesn't process it immediately. emitBytes(z.Text()) } case StartTagToken, EndTagToken: tn, _ := z.TagName() if len(tn) == 1 && tn[0] == 'a' { if tt == StartTagToken { depth++ } else { depth-- } } } } Parsing is done by calling Parse with an io.Reader, which returns the root of the parse tree (the document element) as a *Node. It is the caller's responsibility to ensure that the Reader provides UTF-8 encoded HTML. For example, to process each anchor node in depth-first order: doc, err := html.Parse(r) if err != nil { // ... } var f func(*html.Node) f = func(n *html.Node) { if n.Type == html.ElementNode && n.Data == "a" { // Do something with n... } for c := n.FirstChild; c != nil; c = c.NextSibling { f(c) } } f(doc) The relevant specifications include: https://html.spec.whatwg.org/multipage/syntax.html and https://html.spec.whatwg.org/multipage/syntax.html#tokenization */ package html // import "golang.org/x/net/html" // The tokenization algorithm implemented by this package is not a line-by-line // transliteration of the relatively verbose state-machine in the WHATWG // specification. A more direct approach is used instead, where the program // counter implies the state, such as whether it is tokenizing a tag or a text // node. Specification compliance is verified by checking expected and actual // outputs over a test suite rather than aiming for algorithmic fidelity. // TODO(nigeltao): Does a DOM API belong in this package or a separate one? // TODO(nigeltao): How does parsing interact with a JavaScript engine? ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/const.go��������������������������������������������������0000644�0610621�0607500�00000004634�13172163402�022743� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html // Section 12.2.3.2 of the HTML5 specification says "The following elements // have varying levels of special parsing rules". // https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements var isSpecialElementMap = map[string]bool{ "address": true, "applet": true, "area": true, "article": true, "aside": true, "base": true, "basefont": true, "bgsound": true, "blockquote": true, "body": true, "br": true, "button": true, "caption": true, "center": true, "col": true, "colgroup": true, "dd": true, "details": true, "dir": true, "div": true, "dl": true, "dt": true, "embed": true, "fieldset": true, "figcaption": true, "figure": true, "footer": true, "form": true, "frame": true, "frameset": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "head": true, "header": true, "hgroup": true, "hr": true, "html": true, "iframe": true, "img": true, "input": true, "isindex": true, // The 'isindex' element has been removed, but keep it for backwards compatibility. "keygen": true, "li": true, "link": true, "listing": true, "main": true, "marquee": true, "menu": true, "meta": true, "nav": true, "noembed": true, "noframes": true, "noscript": true, "object": true, "ol": true, "p": true, "param": true, "plaintext": true, "pre": true, "script": true, "section": true, "select": true, "source": true, "style": true, "summary": true, "table": true, "tbody": true, "td": true, "template": true, "textarea": true, "tfoot": true, "th": true, "thead": true, "title": true, "tr": true, "track": true, "ul": true, "wbr": true, "xmp": true, } func isSpecialElement(element *Node) bool { switch element.Namespace { case "", "html": return isSpecialElementMap[element.Data] case "svg": return element.Data == "foreignObject" } return false } ����������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�022710� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/�����������������������������������������0000755�0610621�0607500�00000000000�13172163402�024521� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/meta-content-attribute.html��������������0000644�0610621�0607500�00000005331�13172163402�032010� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-15"> <title>meta content attribute</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="The character encoding of the page can be set by a meta element with http-equiv and content attributes."> <style type='text/css'> .test div { width: 50px; }</style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css"> </head> <body> <p class='title'>meta content attribute</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">The character encoding of the page can be set by a meta element with http-equiv and content attributes.</p> <div class="notes"><p><p>The only character encoding declaration for this HTML file is in the content attribute of the meta element, which declares the encoding to be ISO 8859-15.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00C3;&#x0153;&#x00C3;&#x20AC;&#x00C3;&#x0161;</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-009">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-007<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-007" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li> <li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/meta-charset-attribute.html��������������0000644�0610621�0607500�00000005214�13172163402�031767� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <meta charset="iso-8859-15"> <title>meta charset attribute</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="The character encoding of the page can be set by a meta element with charset attribute."> <style type='text/css'> .test div { width: 50px; }</style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css"> </head> <body> <p class='title'>meta charset attribute</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">The character encoding of the page can be set by a meta element with charset attribute.</p> <div class="notes"><p><p>The only character encoding declaration for this HTML file is in the charset attribute of the meta element, which declares the encoding to be ISO 8859-15.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00C3;&#x0153;&#x00C3;&#x20AC;&#x00C3;&#x0161;</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-015">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-009<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-009" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li> <li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-content.html�����������0000644�0610621�0607500�00000005371�13172163402�031655� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-15"> <title>UTF-8 BOM vs meta content</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta content attribute declares a different encoding."> <style type='text/css'> .test div { width: 50px; }</style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css"> </head> <body> <p class='title'>UTF-8 BOM vs meta content</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta content attribute declares a different encoding.</p> <div class="notes"><p><p>The page contains an encoding declaration in a meta content attribute that attempts to set the character encoding to ISO 8859-15, but the file starts with a UTF-8 signature.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00FD;&#x00E4;&#x00E8;</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-038">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-037<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-037" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li> <li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-charset.html�����������0000644�0610621�0607500�00000005347�13172163402�031637� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <meta charset="iso-8859-15"> <title>UTF-8 BOM vs meta charset</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta charset attribute declares a different encoding."> <style type='text/css'> .test div { width: 50px; }.test div { width: 90px; } </style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css"> </head> <body> <p class='title'>UTF-8 BOM vs meta charset</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta charset attribute declares a different encoding.</p> <div class="notes"><p><p>The page contains an encoding declaration in a meta charset attribute that attempts to set the character encoding to ISO 8859-15, but the file starts with a UTF-8 signature.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00FD;&#x00E4;&#x00E8;</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-024">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-038<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-038" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li> <li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/UTF-16LE-BOM.html������������������������0000644�0610621�0607500�00000005172�13172163402�027132� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ÿþ<�!�D�O�C�T�Y�P�E� �h�t�m�l�>� � �<�h�t�m�l� � �l�a�n�g�=�"�e�n�"� �>� � �<�h�e�a�d�>� � �<�t�i�t�l�e�>�U�T�F�-�1�6�L�E� �B�O�M�<�/�t�i�t�l�e�>� � �<�l�i�n�k� �r�e�l�=�'�a�u�t�h�o�r�'� �t�i�t�l�e�=�'�R�i�c�h�a�r�d� �I�s�h�i�d�a�'� �h�r�e�f�=�'�m�a�i�l�t�o�:�i�s�h�i�d�a�@�w�3�.�o�r�g�'�>� � �<�l�i�n�k� �r�e�l�=�'�h�e�l�p�'� �h�r�e�f�=�'�h�t�t�p�:�/�/�w�w�w�.�w�3�.�o�r�g�/�T�R�/�h�t�m�l�5�/�s�y�n�t�a�x�.�h�t�m�l�#�t�h�e�-�i�n�p�u�t�-�b�y�t�e�-�s�t�r�e�a�m�'�>� � �<�s�c�r�i�p�t� �s�r�c�=�"�h�t�t�p�:�/�/�w�3�c�-�t�e�s�t�.�o�r�g�/�r�e�s�o�u�r�c�e�s�/�t�e�s�t�h�a�r�n�e�s�s�.�j�s�"�>�<�/�s�c�r�i�p�t�>� � �<�s�c�r�i�p�t� �s�r�c�=�"�h�t�t�p�:�/�/�w�3�c�-�t�e�s�t�.�o�r�g�/�r�e�s�o�u�r�c�e�s�/�t�e�s�t�h�a�r�n�e�s�s�r�e�p�o�r�t�.�j�s�"�>�<�/�s�c�r�i�p�t�>� � �<�m�e�t�a� �n�a�m�e�=�'�f�l�a�g�s�'� �c�o�n�t�e�n�t�=�'�h�t�t�p�'�>� � �<�s�t�y�l�e� �t�y�p�e�=�'�t�e�x�t�/�c�s�s�'�>� � �.�t�e�s�t� �d�i�v� �{� �w�i�d�t�h�:� �5�0�p�x�;� �}� � �<�/�s�t�y�l�e�>� � � � �<�l�i�n�k� �r�e�l�=�"�s�t�y�l�e�s�h�e�e�t�"� �t�y�p�e�=�"�t�e�x�t�/�c�s�s�"� �h�r�e�f�=�"�e�n�c�o�d�i�n�g�t�e�s�t�s�-�1�5�.�c�s�s�"�>� � �<�/�h�e�a�d�>� � �<�b�o�d�y�>� � � � �<�d�i�v� �c�l�a�s�s�=�'�t�e�s�t�'�>�<�d�i�v� �i�d�=�'�b�o�x�'� �c�l�a�s�s�=�'�Ã�SÃ�¬ Ã�a'�>�&�#�x�A�0�;�<�/�d�i�v�>�<�/�d�i�v�>� � � � �<�!�-�-� �N�o�t�e�s�:� � � �N�o� �e�n�c�o�d�i�n�g� �i�n�f�o�r�m�a�t�i�o�n� �i�s� �d�e�c�l�a�r�e�d� �i�n� �t�h�e� �H�T�T�P� �h�e�a�d�e�r� �o�r� �i�n�s�i�d�e� �t�h�e� �d�o�c�u�m�e�n�t�,� �o�t�h�e�r� �t�h�a�n� �i�n� �t�h�e� �B�O�M�.� �T�h�e� �t�e�x�t� �o�f� �a� �c�l�a�s�s� �n�a�m�e� �i�n� �t�h�e� �t�e�s�t� �c�o�n�t�a�i�n�s� �t�h�e� �f�o�l�l�o�w�i�n�g� �s�e�q�u�e�n�c�e� �o�f� �b�y�t�e�s�:� �0�x�C�3� �0�x�c�0� �0�x�5�3� �0�x�c�1� �0�x�C�3� �0�x�c�0� �0�x�A�C� �0�x�c�2�0� �0�x�C�3� �0�x�c�0� �0�x�6�1� �0�x�c�1�.� �T�h�e� �e�x�t�e�r�n�a�l�,� �U�T�F�-�8�-�e�n�c�o�d�e�d� �s�t�y�l�e�s�h�e�e�t� �c�o�n�t�a�i�n�s� �a� �s�e�l�e�c�t�o�r� �w�i�t�h� �a� �s�e�q�u�e�n�c�e� �o�f� �c�h�a�r�a�c�t�e�r�s� �t�h�a�t� �w�i�l�l� �o�n�l�y� �m�a�t�c�h� �t�h�e� �c�l�a�s�s� �n�a�m�e� �i�n� �t�h�e� �H�T�M�L� �i�f� �t�h�e� �p�a�g�e� �i�s� �r�e�a�d� �a�s� �U�T�F�-�1�6�B�E�.� � �-�-�>� � � � �<�s�c�r�i�p�t�>� � � �t�e�s�t�(�f�u�n�c�t�i�o�n� �(�)� �{� � � � � � �a�s�s�e�r�t�_�e�q�u�a�l�s�(�d�o�c�u�m�e�n�t�.�g�e�t�E�l�e�m�e�n�t�B�y�I�d�(�'�b�o�x�'�)�.�o�f�f�s�e�t�W�i�d�t�h�,� �1�0�0�)�;� � � �}�,� �'�A� �p�a�g�e� �w�i�t�h� �n�o� �e�n�c�o�d�i�n�g� �d�e�c�l�a�r�a�t�i�o�n�s�,� �b�u�t� �w�i�t�h� �a� �U�T�F�-�1�6� �l�i�t�t�l�e�-�e�n�d�i�a�n� �B�O�M� �w�i�l�l� �b�e� �r�e�c�o�g�n�i�z�e�d� �a�s� �U�T�F�-�1�6�.�'�)�;� � �<�/�s�c�r�i�p�t�>� � � � �<�d�i�v� �i�d�=�"�l�o�g�"�>�<�/�d�i�v�>� � � � �<�/�b�o�d�y�>� � �<�/�h�t�m�l�>� � �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/UTF-16BE-BOM.html������������������������0000644�0610621�0607500�00000005156�13172163402�027122� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������þÿ�<�!�D�O�C�T�Y�P�E� �h�t�m�l�>� � �<�h�t�m�l� � �l�a�n�g�=�"�e�n�"� �>� � �<�h�e�a�d�>� � �<�t�i�t�l�e�>�U�T�F�-�1�6�B�E� �B�O�M�<�/�t�i�t�l�e�>� � �<�l�i�n�k� �r�e�l�=�'�a�u�t�h�o�r�'� �t�i�t�l�e�=�'�R�i�c�h�a�r�d� �I�s�h�i�d�a�'� �h�r�e�f�=�'�m�a�i�l�t�o�:�i�s�h�i�d�a�@�w�3�.�o�r�g�'�>� � �<�l�i�n�k� �r�e�l�=�'�h�e�l�p�'� �h�r�e�f�=�'�h�t�t�p�:�/�/�w�w�w�.�w�3�.�o�r�g�/�T�R�/�h�t�m�l�5�/�s�y�n�t�a�x�.�h�t�m�l�#�t�h�e�-�i�n�p�u�t�-�b�y�t�e�-�s�t�r�e�a�m�'�>� � �<�s�c�r�i�p�t� �s�r�c�=�"�h�t�t�p�:�/�/�w�3�c�-�t�e�s�t�.�o�r�g�/�r�e�s�o�u�r�c�e�s�/�t�e�s�t�h�a�r�n�e�s�s�.�j�s�"�>�<�/�s�c�r�i�p�t�>� � �<�s�c�r�i�p�t� �s�r�c�=�"�h�t�t�p�:�/�/�w�3�c�-�t�e�s�t�.�o�r�g�/�r�e�s�o�u�r�c�e�s�/�t�e�s�t�h�a�r�n�e�s�s�r�e�p�o�r�t�.�j�s�"�>�<�/�s�c�r�i�p�t�>� � �<�m�e�t�a� �n�a�m�e�=�'�f�l�a�g�s�'� �c�o�n�t�e�n�t�=�'�h�t�t�p�'�>� � �<�s�t�y�l�e� �t�y�p�e�=�'�t�e�x�t�/�c�s�s�'�>� � �.�t�e�s�t� �d�i�v� �{� �w�i�d�t�h�:� �5�0�p�x�;� �}� � �<�/�s�t�y�l�e�>� � � � �<�l�i�n�k� �r�e�l�=�"�s�t�y�l�e�s�h�e�e�t�"� �t�y�p�e�=�"�t�e�x�t�/�c�s�s�"� �h�r�e�f�=�"�e�n�c�o�d�i�n�g�t�e�s�t�s�-�1�5�.�c�s�s�"�>� � �<�/�h�e�a�d�>� � �<�b�o�d�y�>� � � � �<�d�i�v� �c�l�a�s�s�=�'�t�e�s�t�'�>�<�d�i�v� �i�d�=�'�b�o�x�'� �c�l�a�s�s�=�'�ÃS�à ¬�Ãa�'�>�&�#�x�A�0�;�<�/�d�i�v�>�<�/�d�i�v�>� � � � �<�!�-�-� �N�o�t�e�s�:� � � �N�o� �e�n�c�o�d�i�n�g� �i�n�f�o�r�m�a�t�i�o�n� �i�s� �d�e�c�l�a�r�e�d� �i�n� �t�h�e� �H�T�T�P� �h�e�a�d�e�r� �o�r� �i�n�s�i�d�e� �t�h�e� �d�o�c�u�m�e�n�t�,� �o�t�h�e�r� �t�h�a�n� �i�n� �t�h�e� �B�O�M�.� �T�h�e� �t�e�x�t� �o�f� �a� �c�l�a�s�s� �n�a�m�e� �i�n� �t�h�e� �t�e�s�t� �c�o�n�t�a�i�n�s� �t�h�e� �f�o�l�l�o�w�i�n�g� �s�e�q�u�e�n�c�e� �o�f� �b�y�t�e�s�:� �0�x�C�3� �0�x�c�0� �0�x�5�3� �0�x�c�1� �0�x�C�3� �0�x�c�0� �0�x�A�C� �0�x�c�2�0� �0�x�C�3� �0�x�c�0� �0�x�6�1� �0�x�c�1�.� �T�h�e� �e�x�t�e�r�n�a�l�,� �U�T�F�-�8�-�e�n�c�o�d�e�d� �s�t�y�l�e�s�h�e�e�t� �c�o�n�t�a�i�n�s� �a� �s�e�l�e�c�t�o�r� �w�i�t�h� �a� �s�e�q�u�e�n�c�e� �o�f� �c�h�a�r�a�c�t�e�r�s� �t�h�a�t� �w�i�l�l� �o�n�l�y� �m�a�t�c�h� �t�h�e� �c�l�a�s�s� �n�a�m�e� �i�n� �t�h�e� �H�T�M�L� �i�f� �t�h�e� �p�a�g�e� �i�s� �r�e�a�d� �a�s� �U�T�F�-�1�6�B�E�.� � �-�-�>� � � � �<�s�c�r�i�p�t�>� � �t�e�s�t�(�f�u�n�c�t�i�o�n� �(�)� �{� � � �a�s�s�e�r�t�_�e�q�u�a�l�s�(�d�o�c�u�m�e�n�t�.�g�e�t�E�l�e�m�e�n�t�B�y�I�d�(�'�b�o�x�'�)�.�o�f�f�s�e�t�W�i�d�t�h�,� �1�0�0�)�;� � � �}�,� �'�A� �p�a�g�e� �w�i�t�h� �n�o� �e�n�c�o�d�i�n�g� �d�e�c�l�a�r�a�t�i�o�n�s�,� �b�u�t� �w�i�t�h� �a� �U�T�F�-�1�6� �l�i�t�t�l�e�-�e�n�d�i�a�n� �B�O�M� �w�i�l�l� �b�e� �r�e�c�o�g�n�i�z�e�d� �a�s� �U�T�F�-�1�6�.�'�)�;� � �<�/�s�c�r�i�p�t�>� � � � �<�d�i�v� �i�d�=�l�o�g�>�<�/�d�i�v�>� � � � �<�/�b�o�d�y�>� � �<�/�h�t�m�l�>� � ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/README�����������������������������������0000644�0610621�0607500�00000000671�13172163402�025405� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������These test cases come from http://www.w3.org/International/tests/repository/html5/the-input-byte-stream/results-basics Distributed under both the W3C Test Suite License (http://www.w3.org/Consortium/Legal/2008/04-testsuite-license) and the W3C 3-clause BSD License (http://www.w3.org/Consortium/Legal/2008/03-bsd-license). To contribute to a W3C Test Suite, see the policies and contribution forms (http://www.w3.org/2004/10/27-testcases). �����������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/No-encoding-declaration.html�������������0000644�0610621�0607500�00000004615�13172163402�032040� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <title>No encoding declaration</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="A page with no encoding information in HTTP, BOM, XML declaration or meta element will be treated as UTF-8."> <style type='text/css'> .test div { width: 50px; }</style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css"> </head> <body> <p class='title'>No encoding declaration</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">A page with no encoding information in HTTP, BOM, XML declaration or meta element will be treated as UTF-8.</p> <div class="notes"><p><p>The test on this page contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00FD;&#x00E4;&#x00E8;</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-034">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-015<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-015" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> �������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-content.html����������������0000644�0610621�0607500�00000005424�13172163402�031215� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" > <title>HTTP vs meta content</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="The HTTP header has a higher precedence than an encoding declaration in a meta content attribute."> <style type='text/css'> .test div { width: 50px; }.test div { width: 90px; } </style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css"> </head> <body> <p class='title'>HTTP vs meta content</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">The HTTP header has a higher precedence than an encoding declaration in a meta content attribute.</p> <div class="notes"><p><p>The HTTP header attempts to set the character encoding to ISO 8859-15. The page contains an encoding declaration in a meta content attribute that attempts to set the character encoding to ISO 8859-1.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00C3;&#x0153;&#x00C3;&#x20AC;&#x00C3;&#x0161;</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-018">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-016<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-016" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li> <li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-charset.html����������������0000644�0610621�0607500�00000005350�13172163402�031172� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <meta charset="iso-8859-1" > <title>HTTP vs meta charset</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="The HTTP header has a higher precedence than an encoding declaration in a meta charset attribute."> <style type='text/css'> .test div { width: 50px; }.test div { width: 90px; } </style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css"> </head> <body> <p class='title'>HTTP vs meta charset</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">The HTTP header has a higher precedence than an encoding declaration in a meta charset attribute.</p> <div class="notes"><p><p>The HTTP header attempts to set the character encoding to ISO 8859-15. The page contains an encoding declaration in a meta charset attribute that attempts to set the character encoding to ISO 8859-1.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00C3;&#x0153;&#x00C3;&#x20AC;&#x00C3;&#x0161;</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-037">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-018<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-018" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li> <li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/HTTP-vs-UTF-8-BOM.html�������������������0000644�0610621�0607500�00000005406�13172163402�030035� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <title>HTTP vs UTF-8 BOM</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="A character encoding set in the HTTP header has lower precedence than the UTF-8 signature."> <style type='text/css'> .test div { width: 50px; }</style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-utf8.css"> </head> <body> <p class='title'>HTTP vs UTF-8 BOM</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">A character encoding set in the HTTP header has lower precedence than the UTF-8 signature.</p> <div class="notes"><p><p>The HTTP header attempts to set the character encoding to ISO 8859-15. The page starts with a UTF-8 signature.</p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00FD;&#x00E4;&#x00E8;</code>. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.</p><p>If the test is unsuccessful, the characters &#x00EF;&#x00BB;&#x00BF; should appear at the top of the page. These represent the bytes that make up the UTF-8 signature when encountered in the ISO 8859-15 encoding.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-022">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-034<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#precedence" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-034" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li> <li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/testdata/HTTP-charset.html������������������������0000644�0610621�0607500�00000005071�13172163402�027620� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en" > <head> <title>HTTP charset</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <link rel='help' href='http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream'> <link rel="stylesheet" type="text/css" href="./generatedtests.css"> <script src="http://w3c-test.org/resources/testharness.js"></script> <script src="http://w3c-test.org/resources/testharnessreport.js"></script> <meta name='flags' content='http'> <meta name="assert" content="The character encoding of a page can be set using the HTTP header charset declaration."> <style type='text/css'> .test div { width: 50px; }</style> <link rel="stylesheet" type="text/css" href="the-input-byte-stream/support/encodingtests-15.css"> </head> <body> <p class='title'>HTTP charset</p> <div id='log'></div> <div class='test'><div id='box' class='ýäè'>&#xA0;</div></div> <div class='description'> <p class="assertion" title="Assertion">The character encoding of a page can be set using the HTTP header charset declaration.</p> <div class="notes"><p><p>The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector <code>.test div.&#x00C3;&#x0153;&#x00C3;&#x20AC;&#x00C3;&#x0161;</code>. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.</p><p>The only character encoding declaration for this HTML file is in the HTTP header, which sets the encoding to ISO 8859-15.</p></p> </div> </div> <div class="nexttest"><div><a href="generate?test=the-input-byte-stream-003">Next test</a></div><div class="doctype">HTML5</div> <p class="jump">the-input-byte-stream-001<br /><a href="/International/tests/html5/the-input-byte-stream/results-basics#basics" target="_blank">Result summary &amp; related tests</a><br /><a href="http://w3c-test.org/framework/details/i18n-html5/the-input-byte-stream-001" target="_blank">Detailed results for this test</a><br/> <a href="http://www.w3.org/TR/html5/syntax.html#the-input-byte-stream" target="_blank">Link to spec</a></p> <div class='prereq'>Assumptions: <ul><li>The default encoding for the browser you are testing is not set to ISO 8859-15.</li> <li>The test is read from a server that supports HTTP.</li></ul></div> </div> <script> test(function() { assert_equals(document.getElementById('box').offsetWidth, 100); }, " "); </script> </body> </html> �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/charset_test.go�����������������������������������0000644�0610621�0607500�00000017741�13172163402�025741� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package charset import ( "bytes" "encoding/xml" "io/ioutil" "runtime" "strings" "testing" "golang.org/x/text/transform" ) func transformString(t transform.Transformer, s string) (string, error) { r := transform.NewReader(strings.NewReader(s), t) b, err := ioutil.ReadAll(r) return string(b), err } type testCase struct { utf8, other, otherEncoding string } // testCases for encoding and decoding. var testCases = []testCase{ {"Résumé", "Résumé", "utf8"}, {"Résumé", "R\xe9sum\xe9", "latin1"}, {"ã“ã‚Œã¯æ¼¢å­—ã§ã™ã€‚", "S0\x8c0o0\"oW[g0Y0\x020", "UTF-16LE"}, {"ã“ã‚Œã¯æ¼¢å­—ã§ã™ã€‚", "0S0\x8c0oo\"[W0g0Y0\x02", "UTF-16BE"}, {"Hello, world", "Hello, world", "ASCII"}, {"GdaÅ„sk", "Gda\xf1sk", "ISO-8859-2"}, {"Ââ ÄŒÄ ÄÄ‘ ÅŠÅ‹ Õõ Å Å¡ Žž Ã…Ã¥ Ää", "\xc2\xe2 \xc8\xe8 \xa9\xb9 \xaf\xbf \xd5\xf5 \xaa\xba \xac\xbc \xc5\xe5 \xc4\xe4", "ISO-8859-10"}, {"สำหรับ", "\xca\xd3\xcb\xc3\u047a", "ISO-8859-11"}, {"latvieÅ¡u", "latvie\xf0u", "ISO-8859-13"}, {"Seònaid", "Se\xf2naid", "ISO-8859-14"}, {"€1 is cheap", "\xa41 is cheap", "ISO-8859-15"}, {"româneÈ™te", "rom\xe2ne\xbate", "ISO-8859-16"}, {"nutraĵo", "nutra\xbco", "ISO-8859-3"}, {"Kalâdlit", "Kal\xe2dlit", "ISO-8859-4"}, {"руÑÑкий", "\xe0\xe3\xe1\xe1\xda\xd8\xd9", "ISO-8859-5"}, {"ελληνικά", "\xe5\xeb\xeb\xe7\xed\xe9\xea\xdc", "ISO-8859-7"}, {"KaÄŸan", "Ka\xf0an", "ISO-8859-9"}, {"Résumé", "R\x8esum\x8e", "macintosh"}, {"GdaÅ„sk", "Gda\xf1sk", "windows-1250"}, {"руÑÑкий", "\xf0\xf3\xf1\xf1\xea\xe8\xe9", "windows-1251"}, {"Résumé", "R\xe9sum\xe9", "windows-1252"}, {"ελληνικά", "\xe5\xeb\xeb\xe7\xed\xe9\xea\xdc", "windows-1253"}, {"KaÄŸan", "Ka\xf0an", "windows-1254"}, {"עִבְרִית", "\xf2\xc4\xe1\xc0\xf8\xc4\xe9\xfa", "windows-1255"}, {"العربية", "\xc7\xe1\xda\xd1\xc8\xed\xc9", "windows-1256"}, {"latvieÅ¡u", "latvie\xf0u", "windows-1257"}, {"Việt", "Vi\xea\xf2t", "windows-1258"}, {"สำหรับ", "\xca\xd3\xcb\xc3\u047a", "windows-874"}, {"руÑÑкий", "\xd2\xd5\xd3\xd3\xcb\xc9\xca", "KOI8-R"}, {"українÑька", "\xd5\xcb\xd2\xc1\xa7\xce\xd3\xd8\xcb\xc1", "KOI8-U"}, {"Hello 常用國字標準字體表", "Hello \xb1`\xa5\u03b0\xea\xa6r\xbc\u0437\u01e6r\xc5\xe9\xaa\xed", "big5"}, {"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gbk"}, {"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gb18030"}, {"עִבְרִית", "\x81\x30\xfb\x30\x81\x30\xf6\x34\x81\x30\xf9\x33\x81\x30\xf6\x30\x81\x30\xfb\x36\x81\x30\xf6\x34\x81\x30\xfa\x31\x81\x30\xfb\x38", "gb18030"}, {"㧯", "\x82\x31\x89\x38", "gb18030"}, {"ã“ã‚Œã¯æ¼¢å­—ã§ã™ã€‚", "\x82\xb1\x82\xea\x82\xcd\x8a\xbf\x8e\x9a\x82\xc5\x82\xb7\x81B", "SJIS"}, {"Hello, 世界!", "Hello, \x90\xa2\x8aE!", "SJIS"}, {"イウエオカ", "\xb2\xb3\xb4\xb5\xb6", "SJIS"}, {"ã“ã‚Œã¯æ¼¢å­—ã§ã™ã€‚", "\xa4\xb3\xa4\xec\xa4\u03f4\xc1\xbb\xfa\xa4\u01e4\xb9\xa1\xa3", "EUC-JP"}, {"Hello, 世界!", "Hello, \x1b$B@$3&\x1b(B!", "ISO-2022-JP"}, {"다ìŒê³¼ ê°™ì€ ì¡°ê±´ì„ ë”°ë¼ì•¼ 합니다: 저작ìží‘œì‹œ", "\xb4\xd9\xc0\xbd\xb0\xfa \xb0\xb0\xc0\xba \xc1\xb6\xb0\xc7\xc0\xbb \xb5\xfb\xb6\xf3\xbe\xdf \xc7Õ´Ï´\xd9: \xc0\xfa\xc0\xdb\xc0\xdaÇ¥\xbd\xc3", "EUC-KR"}, } func TestDecode(t *testing.T) { testCases := append(testCases, []testCase{ // Replace multi-byte maximum subpart of ill-formed subsequence with // single replacement character (WhatWG requirement). {"Rés\ufffdumé", "Rés\xe1\x80umé", "utf8"}, }...) for _, tc := range testCases { e, _ := Lookup(tc.otherEncoding) if e == nil { t.Errorf("%s: not found", tc.otherEncoding) continue } s, err := transformString(e.NewDecoder(), tc.other) if err != nil { t.Errorf("%s: decode %q: %v", tc.otherEncoding, tc.other, err) continue } if s != tc.utf8 { t.Errorf("%s: got %q, want %q", tc.otherEncoding, s, tc.utf8) } } } func TestEncode(t *testing.T) { testCases := append(testCases, []testCase{ // Use Go-style replacement. {"Rés\xe1\x80umé", "Rés\ufffd\ufffdumé", "utf8"}, // U+0144 LATIN SMALL LETTER N WITH ACUTE not supported by encoding. {"GdaÅ„sk", "Gda&#324;sk", "ISO-8859-11"}, {"\ufffd", "&#65533;", "ISO-8859-11"}, {"a\xe1\x80b", "a&#65533;&#65533;b", "ISO-8859-11"}, }...) for _, tc := range testCases { e, _ := Lookup(tc.otherEncoding) if e == nil { t.Errorf("%s: not found", tc.otherEncoding) continue } s, err := transformString(e.NewEncoder(), tc.utf8) if err != nil { t.Errorf("%s: encode %q: %s", tc.otherEncoding, tc.utf8, err) continue } if s != tc.other { t.Errorf("%s: got %q, want %q", tc.otherEncoding, s, tc.other) } } } var sniffTestCases = []struct { filename, declared, want string }{ {"HTTP-charset.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, {"UTF-16LE-BOM.html", "", "utf-16le"}, {"UTF-16BE-BOM.html", "", "utf-16be"}, {"meta-content-attribute.html", "text/html", "iso-8859-15"}, {"meta-charset-attribute.html", "text/html", "iso-8859-15"}, {"No-encoding-declaration.html", "text/html", "utf-8"}, {"HTTP-vs-UTF-8-BOM.html", "text/html; charset=iso-8859-15", "utf-8"}, {"HTTP-vs-meta-content.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, {"HTTP-vs-meta-charset.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, {"UTF-8-BOM-vs-meta-content.html", "text/html", "utf-8"}, {"UTF-8-BOM-vs-meta-charset.html", "text/html", "utf-8"}, } func TestSniff(t *testing.T) { switch runtime.GOOS { case "nacl": // platforms that don't permit direct file system access t.Skipf("not supported on %q", runtime.GOOS) } for _, tc := range sniffTestCases { content, err := ioutil.ReadFile("testdata/" + tc.filename) if err != nil { t.Errorf("%s: error reading file: %v", tc.filename, err) continue } _, name, _ := DetermineEncoding(content, tc.declared) if name != tc.want { t.Errorf("%s: got %q, want %q", tc.filename, name, tc.want) continue } } } func TestReader(t *testing.T) { switch runtime.GOOS { case "nacl": // platforms that don't permit direct file system access t.Skipf("not supported on %q", runtime.GOOS) } for _, tc := range sniffTestCases { content, err := ioutil.ReadFile("testdata/" + tc.filename) if err != nil { t.Errorf("%s: error reading file: %v", tc.filename, err) continue } r, err := NewReader(bytes.NewReader(content), tc.declared) if err != nil { t.Errorf("%s: error creating reader: %v", tc.filename, err) continue } got, err := ioutil.ReadAll(r) if err != nil { t.Errorf("%s: error reading from charset.NewReader: %v", tc.filename, err) continue } e, _ := Lookup(tc.want) want, err := ioutil.ReadAll(transform.NewReader(bytes.NewReader(content), e.NewDecoder())) if err != nil { t.Errorf("%s: error decoding with hard-coded charset name: %v", tc.filename, err) continue } if !bytes.Equal(got, want) { t.Errorf("%s: got %q, want %q", tc.filename, got, want) continue } } } var metaTestCases = []struct { meta, want string }{ {"", ""}, {"text/html", ""}, {"text/html; charset utf-8", ""}, {"text/html; charset=latin-2", "latin-2"}, {"text/html; charset; charset = utf-8", "utf-8"}, {`charset="big5"`, "big5"}, {"charset='shift_jis'", "shift_jis"}, } func TestFromMeta(t *testing.T) { for _, tc := range metaTestCases { got := fromMetaElement(tc.meta) if got != tc.want { t.Errorf("%q: got %q, want %q", tc.meta, got, tc.want) } } } func TestXML(t *testing.T) { const s = "<?xml version=\"1.0\" encoding=\"windows-1252\"?><a><Word>r\xe9sum\xe9</Word></a>" d := xml.NewDecoder(strings.NewReader(s)) d.CharsetReader = NewReaderLabel var a struct { Word string } err := d.Decode(&a) if err != nil { t.Fatalf("Decode: %v", err) } want := "résumé" if a.Word != want { t.Errorf("got %q, want %q", a.Word, want) } } �������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/charset/charset.go����������������������������������������0000644�0610621�0607500�00000014073�13172163402�024675� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package charset provides common text encodings for HTML documents. // // The mapping from encoding labels to encodings is defined at // https://encoding.spec.whatwg.org/. package charset // import "golang.org/x/net/html/charset" import ( "bytes" "fmt" "io" "mime" "strings" "unicode/utf8" "golang.org/x/net/html" "golang.org/x/text/encoding" "golang.org/x/text/encoding/charmap" "golang.org/x/text/encoding/htmlindex" "golang.org/x/text/transform" ) // Lookup returns the encoding with the specified label, and its canonical // name. It returns nil and the empty string if label is not one of the // standard encodings for HTML. Matching is case-insensitive and ignores // leading and trailing whitespace. Encoders will use HTML escape sequences for // runes that are not supported by the character set. func Lookup(label string) (e encoding.Encoding, name string) { e, err := htmlindex.Get(label) if err != nil { return nil, "" } name, _ = htmlindex.Name(e) return &htmlEncoding{e}, name } type htmlEncoding struct{ encoding.Encoding } func (h *htmlEncoding) NewEncoder() *encoding.Encoder { // HTML requires a non-terminating legacy encoder. We use HTML escapes to // substitute unsupported code points. return encoding.HTMLEscapeUnsupported(h.Encoding.NewEncoder()) } // DetermineEncoding determines the encoding of an HTML document by examining // up to the first 1024 bytes of content and the declared Content-Type. // // See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool) { if len(content) > 1024 { content = content[:1024] } for _, b := range boms { if bytes.HasPrefix(content, b.bom) { e, name = Lookup(b.enc) return e, name, true } } if _, params, err := mime.ParseMediaType(contentType); err == nil { if cs, ok := params["charset"]; ok { if e, name = Lookup(cs); e != nil { return e, name, true } } } if len(content) > 0 { e, name = prescan(content) if e != nil { return e, name, false } } // Try to detect UTF-8. // First eliminate any partial rune at the end. for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- { b := content[i] if b < 0x80 { break } if utf8.RuneStart(b) { content = content[:i] break } } hasHighBit := false for _, c := range content { if c >= 0x80 { hasHighBit = true break } } if hasHighBit && utf8.Valid(content) { return encoding.Nop, "utf-8", false } // TODO: change default depending on user's locale? return charmap.Windows1252, "windows-1252", false } // NewReader returns an io.Reader that converts the content of r to UTF-8. // It calls DetermineEncoding to find out what r's encoding is. func NewReader(r io.Reader, contentType string) (io.Reader, error) { preview := make([]byte, 1024) n, err := io.ReadFull(r, preview) switch { case err == io.ErrUnexpectedEOF: preview = preview[:n] r = bytes.NewReader(preview) case err != nil: return nil, err default: r = io.MultiReader(bytes.NewReader(preview), r) } if e, _, _ := DetermineEncoding(preview, contentType); e != encoding.Nop { r = transform.NewReader(r, e.NewDecoder()) } return r, nil } // NewReaderLabel returns a reader that converts from the specified charset to // UTF-8. It uses Lookup to find the encoding that corresponds to label, and // returns an error if Lookup returns nil. It is suitable for use as // encoding/xml.Decoder's CharsetReader function. func NewReaderLabel(label string, input io.Reader) (io.Reader, error) { e, _ := Lookup(label) if e == nil { return nil, fmt.Errorf("unsupported charset: %q", label) } return transform.NewReader(input, e.NewDecoder()), nil } func prescan(content []byte) (e encoding.Encoding, name string) { z := html.NewTokenizer(bytes.NewReader(content)) for { switch z.Next() { case html.ErrorToken: return nil, "" case html.StartTagToken, html.SelfClosingTagToken: tagName, hasAttr := z.TagName() if !bytes.Equal(tagName, []byte("meta")) { continue } attrList := make(map[string]bool) gotPragma := false const ( dontKnow = iota doNeedPragma doNotNeedPragma ) needPragma := dontKnow name = "" e = nil for hasAttr { var key, val []byte key, val, hasAttr = z.TagAttr() ks := string(key) if attrList[ks] { continue } attrList[ks] = true for i, c := range val { if 'A' <= c && c <= 'Z' { val[i] = c + 0x20 } } switch ks { case "http-equiv": if bytes.Equal(val, []byte("content-type")) { gotPragma = true } case "content": if e == nil { name = fromMetaElement(string(val)) if name != "" { e, name = Lookup(name) if e != nil { needPragma = doNeedPragma } } } case "charset": e, name = Lookup(string(val)) needPragma = doNotNeedPragma } } if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma { continue } if strings.HasPrefix(name, "utf-16") { name = "utf-8" e = encoding.Nop } if e != nil { return e, name } } } } func fromMetaElement(s string) string { for s != "" { csLoc := strings.Index(s, "charset") if csLoc == -1 { return "" } s = s[csLoc+len("charset"):] s = strings.TrimLeft(s, " \t\n\f\r") if !strings.HasPrefix(s, "=") { continue } s = s[1:] s = strings.TrimLeft(s, " \t\n\f\r") if s == "" { return "" } if q := s[0]; q == '"' || q == '\'' { s = s[1:] closeQuote := strings.IndexRune(s, rune(q)) if closeQuote == -1 { return "" } return s[:closeQuote] } end := strings.IndexAny(s, "; \t\n\f\r") if end == -1 { end = len(s) } return s[:end] } return "" } var boms = []struct { bom []byte enc string }{ {[]byte{0xfe, 0xff}, "utf-16be"}, {[]byte{0xff, 0xfe}, "utf-16le"}, {[]byte{0xef, 0xbb, 0xbf}, "utf-8"}, } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/atom/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�022217� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/atom/table_test.go����������������������������������������0000644�0610621�0607500�00000010554�13172163402�024701� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by go generate gen.go; DO NOT EDIT. //go:generate go run gen.go -test package atom var testAtomList = []string{ "a", "abbr", "accept", "accept-charset", "accesskey", "action", "address", "align", "allowfullscreen", "allowpaymentrequest", "allowusermedia", "alt", "annotation", "annotation-xml", "applet", "area", "article", "as", "aside", "async", "audio", "autocomplete", "autofocus", "autoplay", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "challenge", "charset", "checked", "cite", "class", "code", "col", "colgroup", "color", "cols", "colspan", "command", "content", "contenteditable", "contextmenu", "controls", "coords", "crossorigin", "data", "datalist", "datetime", "dd", "default", "defer", "del", "desc", "details", "dfn", "dialog", "dir", "dirname", "disabled", "div", "dl", "download", "draggable", "dropzone", "dt", "em", "embed", "enctype", "face", "fieldset", "figcaption", "figure", "font", "footer", "for", "foreignObject", "foreignobject", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "headers", "height", "hgroup", "hidden", "high", "hr", "href", "hreflang", "html", "http-equiv", "i", "icon", "id", "iframe", "image", "img", "input", "inputmode", "ins", "integrity", "is", "isindex", "ismap", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "kbd", "keygen", "keytype", "kind", "label", "lang", "legend", "li", "link", "list", "listing", "loop", "low", "main", "malignmark", "manifest", "map", "mark", "marquee", "math", "max", "maxlength", "media", "mediagroup", "menu", "menuitem", "meta", "meter", "method", "mglyph", "mi", "min", "minlength", "mn", "mo", "ms", "mtext", "multiple", "muted", "name", "nav", "nobr", "noembed", "noframes", "nomodule", "nonce", "noscript", "novalidate", "object", "ol", "onabort", "onafterprint", "onautocomplete", "onautocompleteerror", "onauxclick", "onbeforeprint", "onbeforeunload", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncopy", "oncuechange", "oncut", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragexit", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onhashchange", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onlanguagechange", "onload", "onloadeddata", "onloadedmetadata", "onloadend", "onloadstart", "onmessage", "onmessageerror", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onoffline", "ononline", "onpagehide", "onpageshow", "onpaste", "onpause", "onplay", "onplaying", "onpopstate", "onprogress", "onratechange", "onrejectionhandled", "onreset", "onresize", "onscroll", "onsecuritypolicyviolation", "onseeked", "onseeking", "onselect", "onshow", "onsort", "onstalled", "onstorage", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onunhandledrejection", "onunload", "onvolumechange", "onwaiting", "onwheel", "open", "optgroup", "optimum", "option", "output", "p", "param", "pattern", "picture", "ping", "placeholder", "plaintext", "playsinline", "poster", "pre", "preload", "progress", "prompt", "public", "q", "radiogroup", "readonly", "referrerpolicy", "rel", "required", "reversed", "rows", "rowspan", "rp", "rt", "ruby", "s", "samp", "sandbox", "scope", "scoped", "script", "seamless", "section", "select", "selected", "shape", "size", "sizes", "slot", "small", "sortable", "sorted", "source", "spacer", "span", "spellcheck", "src", "srcdoc", "srclang", "srcset", "start", "step", "strike", "strong", "style", "sub", "summary", "sup", "svg", "system", "tabindex", "table", "target", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "translate", "tt", "type", "typemustmatch", "u", "ul", "updateviacache", "usemap", "value", "var", "video", "wbr", "width", "workertype", "wrap", "xmp", } ����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/atom/table.go���������������������������������������������0000644�0610621�0607500�00000065745�13172163402�023656� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by go generate gen.go; DO NOT EDIT. //go:generate go run gen.go package atom const ( A Atom = 0x1 Abbr Atom = 0x4 Accept Atom = 0x1a06 AcceptCharset Atom = 0x1a0e Accesskey Atom = 0x2c09 Action Atom = 0x25a06 Address Atom = 0x6ed07 Align Atom = 0x6d405 Allowfullscreen Atom = 0x1f00f Allowpaymentrequest Atom = 0x6913 Allowusermedia Atom = 0x850e Alt Atom = 0xb003 Annotation Atom = 0x1b90a AnnotationXml Atom = 0x1b90e Applet Atom = 0x30106 Area Atom = 0x34a04 Article Atom = 0x3f007 As Atom = 0xb902 Aside Atom = 0xc105 Async Atom = 0xb905 Audio Atom = 0xcf05 Autocomplete Atom = 0x2600c Autofocus Atom = 0xeb09 Autoplay Atom = 0x10608 B Atom = 0x101 Base Atom = 0x11504 Basefont Atom = 0x11508 Bdi Atom = 0x16103 Bdo Atom = 0x13403 Bgsound Atom = 0x14707 Big Atom = 0x15903 Blink Atom = 0x15c05 Blockquote Atom = 0x1680a Body Atom = 0x2804 Br Atom = 0x202 Button Atom = 0x17206 Canvas Atom = 0xbd06 Caption Atom = 0x21907 Center Atom = 0x20806 Challenge Atom = 0x28309 Charset Atom = 0x2107 Checked Atom = 0x46d07 Cite Atom = 0x55804 Class Atom = 0x5b905 Code Atom = 0x19004 Col Atom = 0x19703 Colgroup Atom = 0x19708 Color Atom = 0x1af05 Cols Atom = 0x1b404 Colspan Atom = 0x1b407 Command Atom = 0x1c707 Content Atom = 0x57f07 Contenteditable Atom = 0x57f0f Contextmenu Atom = 0x3740b Controls Atom = 0x1ce08 Coords Atom = 0x1da06 Crossorigin Atom = 0x1e30b Data Atom = 0x49904 Datalist Atom = 0x49908 Datetime Atom = 0x2a008 Dd Atom = 0x2bf02 Default Atom = 0xc407 Defer Atom = 0x19205 Del Atom = 0x44603 Desc Atom = 0x55504 Details Atom = 0x4607 Dfn Atom = 0x5f03 Dialog Atom = 0x16206 Dir Atom = 0xa303 Dirname Atom = 0xa307 Disabled Atom = 0x14d08 Div Atom = 0x15403 Dl Atom = 0x5e202 Download Atom = 0x45708 Draggable Atom = 0x18309 Dropzone Atom = 0x3f908 Dt Atom = 0x64702 Em Atom = 0x4202 Embed Atom = 0x4205 Enctype Atom = 0x27507 Face Atom = 0x20604 Fieldset Atom = 0x20e08 Figcaption Atom = 0x2160a Figure Atom = 0x23006 Font Atom = 0x11904 Footer Atom = 0xb306 For Atom = 0x23c03 ForeignObject Atom = 0x23c0d Foreignobject Atom = 0x2490d Form Atom = 0x25604 Formaction Atom = 0x2560a Formenctype Atom = 0x2710b Formmethod Atom = 0x28c0a Formnovalidate Atom = 0x2960e Formtarget Atom = 0x2a80a Frame Atom = 0x5705 Frameset Atom = 0x5708 H1 Atom = 0x14502 H2 Atom = 0x2c602 H3 Atom = 0x2f502 H4 Atom = 0x33902 H5 Atom = 0x34302 H6 Atom = 0x64902 Head Atom = 0x32504 Header Atom = 0x32506 Headers Atom = 0x32507 Height Atom = 0x12c06 Hgroup Atom = 0x2b206 Hidden Atom = 0x2bd06 High Atom = 0x2c304 Hr Atom = 0x14002 Href Atom = 0x2c804 Hreflang Atom = 0x2c808 Html Atom = 0x13004 HttpEquiv Atom = 0x2d00a I Atom = 0x601 Icon Atom = 0x57e04 Id Atom = 0xc302 Iframe Atom = 0x2e406 Image Atom = 0x2ea05 Img Atom = 0x2ef03 Input Atom = 0x43f05 Inputmode Atom = 0x43f09 Ins Atom = 0x1ec03 Integrity Atom = 0x22709 Is Atom = 0x14e02 Isindex Atom = 0x2f707 Ismap Atom = 0x2fe05 Itemid Atom = 0x37f06 Itemprop Atom = 0x55908 Itemref Atom = 0x3c107 Itemscope Atom = 0x66d09 Itemtype Atom = 0x30708 Kbd Atom = 0x16003 Keygen Atom = 0x3206 Keytype Atom = 0x7e07 Kind Atom = 0x18004 Label Atom = 0xda05 Lang Atom = 0x2cc04 Legend Atom = 0x18a06 Li Atom = 0x11102 Link Atom = 0x15d04 List Atom = 0x49d04 Listing Atom = 0x49d07 Loop Atom = 0xde04 Low Atom = 0x6b03 Main Atom = 0x1004 Malignmark Atom = 0x6d30a Manifest Atom = 0x30f08 Map Atom = 0x30003 Mark Atom = 0x6d904 Marquee Atom = 0x31b07 Math Atom = 0x32204 Max Atom = 0x33103 Maxlength Atom = 0x33109 Media Atom = 0x8e05 Mediagroup Atom = 0x8e0a Menu Atom = 0x37b04 Menuitem Atom = 0x37b08 Meta Atom = 0x4ac04 Meter Atom = 0xa805 Method Atom = 0x29006 Mglyph Atom = 0x2f006 Mi Atom = 0x33b02 Min Atom = 0x33b03 Minlength Atom = 0x33b09 Mn Atom = 0x29902 Mo Atom = 0x6302 Ms Atom = 0x67002 Mtext Atom = 0x34505 Multiple Atom = 0x35308 Muted Atom = 0x35b05 Name Atom = 0xa604 Nav Atom = 0x1303 Nobr Atom = 0x3704 Noembed Atom = 0x4007 Noframes Atom = 0x5508 Nomodule Atom = 0x6108 Nonce Atom = 0x56205 Noscript Atom = 0x1fe08 Novalidate Atom = 0x29a0a Object Atom = 0x25006 Ol Atom = 0x10102 Onabort Atom = 0x17607 Onafterprint Atom = 0x21e0c Onautocomplete Atom = 0x25e0e Onautocompleteerror Atom = 0x25e13 Onauxclick Atom = 0x61b0a Onbeforeprint Atom = 0x69a0d Onbeforeunload Atom = 0x6e10e Onblur Atom = 0x5c206 Oncancel Atom = 0xd308 Oncanplay Atom = 0x13609 Oncanplaythrough Atom = 0x13610 Onchange Atom = 0x40f08 Onclick Atom = 0x2dd07 Onclose Atom = 0x36007 Oncontextmenu Atom = 0x3720d Oncopy Atom = 0x38506 Oncuechange Atom = 0x38b0b Oncut Atom = 0x39605 Ondblclick Atom = 0x39b0a Ondrag Atom = 0x3a506 Ondragend Atom = 0x3a509 Ondragenter Atom = 0x3ae0b Ondragexit Atom = 0x3b90a Ondragleave Atom = 0x3d30b Ondragover Atom = 0x3de0a Ondragstart Atom = 0x3e80b Ondrop Atom = 0x3f706 Ondurationchange Atom = 0x40710 Onemptied Atom = 0x3fe09 Onended Atom = 0x41707 Onerror Atom = 0x41e07 Onfocus Atom = 0x42507 Onhashchange Atom = 0x4310c Oninput Atom = 0x43d07 Oninvalid Atom = 0x44909 Onkeydown Atom = 0x45209 Onkeypress Atom = 0x45f0a Onkeyup Atom = 0x47407 Onlanguagechange Atom = 0x48110 Onload Atom = 0x49106 Onloadeddata Atom = 0x4910c Onloadedmetadata Atom = 0x4a410 Onloadend Atom = 0x4ba09 Onloadstart Atom = 0x4c30b Onmessage Atom = 0x4ce09 Onmessageerror Atom = 0x4ce0e Onmousedown Atom = 0x4dc0b Onmouseenter Atom = 0x4e70c Onmouseleave Atom = 0x4f30c Onmousemove Atom = 0x4ff0b Onmouseout Atom = 0x50a0a Onmouseover Atom = 0x5170b Onmouseup Atom = 0x52209 Onmousewheel Atom = 0x5300c Onoffline Atom = 0x53c09 Ononline Atom = 0x54508 Onpagehide Atom = 0x54d0a Onpageshow Atom = 0x5670a Onpaste Atom = 0x57307 Onpause Atom = 0x58e07 Onplay Atom = 0x59806 Onplaying Atom = 0x59809 Onpopstate Atom = 0x5a10a Onprogress Atom = 0x5ab0a Onratechange Atom = 0x5c80c Onrejectionhandled Atom = 0x5d412 Onreset Atom = 0x5e607 Onresize Atom = 0x5ed08 Onscroll Atom = 0x5fc08 Onsecuritypolicyviolation Atom = 0x60419 Onseeked Atom = 0x62508 Onseeking Atom = 0x62d09 Onselect Atom = 0x63608 Onshow Atom = 0x64006 Onsort Atom = 0x64b06 Onstalled Atom = 0x65509 Onstorage Atom = 0x65e09 Onsubmit Atom = 0x66708 Onsuspend Atom = 0x67709 Ontimeupdate Atom = 0x11a0c Ontoggle Atom = 0x68008 Onunhandledrejection Atom = 0x68814 Onunload Atom = 0x6a708 Onvolumechange Atom = 0x6af0e Onwaiting Atom = 0x6bd09 Onwheel Atom = 0x6c607 Open Atom = 0x55f04 Optgroup Atom = 0xe008 Optimum Atom = 0x6cd07 Option Atom = 0x6dd06 Output Atom = 0x51106 P Atom = 0xc01 Param Atom = 0xc05 Pattern Atom = 0x4f07 Picture Atom = 0x9707 Ping Atom = 0xe704 Placeholder Atom = 0xfb0b Plaintext Atom = 0x19e09 Playsinline Atom = 0x10a0b Poster Atom = 0x2b706 Pre Atom = 0x46403 Preload Atom = 0x47a07 Progress Atom = 0x5ad08 Prompt Atom = 0x52a06 Public Atom = 0x57a06 Q Atom = 0x7701 Radiogroup Atom = 0x30a Readonly Atom = 0x34b08 Referrerpolicy Atom = 0x3c50e Rel Atom = 0x47b03 Required Atom = 0x23408 Reversed Atom = 0x9c08 Rows Atom = 0x3a04 Rowspan Atom = 0x3a07 Rp Atom = 0x22402 Rt Atom = 0x17b02 Ruby Atom = 0xac04 S Atom = 0x2501 Samp Atom = 0x4c04 Sandbox Atom = 0xf307 Scope Atom = 0x67105 Scoped Atom = 0x67106 Script Atom = 0x20006 Seamless Atom = 0x36508 Section Atom = 0x5bd07 Select Atom = 0x63806 Selected Atom = 0x63808 Shape Atom = 0x1d505 Size Atom = 0x5f104 Sizes Atom = 0x5f105 Slot Atom = 0x1df04 Small Atom = 0x1ee05 Sortable Atom = 0x64d08 Sorted Atom = 0x32b06 Source Atom = 0x36c06 Spacer Atom = 0x42b06 Span Atom = 0x3d04 Spellcheck Atom = 0x4680a Src Atom = 0x5b403 Srcdoc Atom = 0x5b406 Srclang Atom = 0x5f507 Srcset Atom = 0x6f306 Start Atom = 0x3ee05 Step Atom = 0x57704 Strike Atom = 0x7a06 Strong Atom = 0x31506 Style Atom = 0x6f905 Sub Atom = 0x66903 Summary Atom = 0x6fe07 Sup Atom = 0x70503 Svg Atom = 0x70803 System Atom = 0x70b06 Tabindex Atom = 0x4b208 Table Atom = 0x58905 Target Atom = 0x2ac06 Tbody Atom = 0x2705 Td Atom = 0x5e02 Template Atom = 0x70e08 Textarea Atom = 0x34608 Tfoot Atom = 0xb205 Th Atom = 0x13f02 Thead Atom = 0x32405 Time Atom = 0x11c04 Title Atom = 0xca05 Tr Atom = 0x7402 Track Atom = 0x17c05 Translate Atom = 0x1a609 Tt Atom = 0x5102 Type Atom = 0x8104 Typemustmatch Atom = 0x2780d U Atom = 0xb01 Ul Atom = 0x6602 Updateviacache Atom = 0x1200e Usemap Atom = 0x59206 Value Atom = 0x1505 Var Atom = 0x15603 Video Atom = 0x2d905 Wbr Atom = 0x57003 Width Atom = 0x64505 Workertype Atom = 0x7160a Wrap Atom = 0x72004 Xmp Atom = 0xf903 ) const hash0 = 0x81cdf10e const maxAtomLen = 25 var table = [1 << 9]Atom{ 0x1: 0x8e0a, // mediagroup 0x2: 0x2cc04, // lang 0x4: 0x2c09, // accesskey 0x5: 0x5708, // frameset 0x7: 0x63608, // onselect 0x8: 0x70b06, // system 0xa: 0x64505, // width 0xc: 0x2710b, // formenctype 0xd: 0x10102, // ol 0xe: 0x38b0b, // oncuechange 0x10: 0x13403, // bdo 0x11: 0xcf05, // audio 0x12: 0x18309, // draggable 0x14: 0x2d905, // video 0x15: 0x29902, // mn 0x16: 0x37b04, // menu 0x17: 0x2b706, // poster 0x19: 0xb306, // footer 0x1a: 0x29006, // method 0x1b: 0x2a008, // datetime 0x1c: 0x17607, // onabort 0x1d: 0x1200e, // updateviacache 0x1e: 0xb905, // async 0x1f: 0x49106, // onload 0x21: 0xd308, // oncancel 0x22: 0x62508, // onseeked 0x23: 0x2ea05, // image 0x24: 0x5d412, // onrejectionhandled 0x26: 0x15d04, // link 0x27: 0x51106, // output 0x28: 0x32504, // head 0x29: 0x4f30c, // onmouseleave 0x2a: 0x57307, // onpaste 0x2b: 0x59809, // onplaying 0x2c: 0x1b407, // colspan 0x2f: 0x1af05, // color 0x30: 0x5f104, // size 0x31: 0x2d00a, // http-equiv 0x33: 0x601, // i 0x34: 0x54d0a, // onpagehide 0x35: 0x68814, // onunhandledrejection 0x37: 0x41e07, // onerror 0x3a: 0x11508, // basefont 0x3f: 0x1303, // nav 0x40: 0x18004, // kind 0x41: 0x34b08, // readonly 0x42: 0x2f006, // mglyph 0x44: 0x11102, // li 0x46: 0x2bd06, // hidden 0x47: 0x70803, // svg 0x48: 0x57704, // step 0x49: 0x22709, // integrity 0x4a: 0x57a06, // public 0x4c: 0x19703, // col 0x4d: 0x1680a, // blockquote 0x4e: 0x34302, // h5 0x50: 0x5ad08, // progress 0x51: 0x5f105, // sizes 0x52: 0x33902, // h4 0x56: 0x32405, // thead 0x57: 0x7e07, // keytype 0x58: 0x5ab0a, // onprogress 0x59: 0x43f09, // inputmode 0x5a: 0x3a509, // ondragend 0x5d: 0x39605, // oncut 0x5e: 0x42b06, // spacer 0x5f: 0x19708, // colgroup 0x62: 0x14e02, // is 0x65: 0xb902, // as 0x66: 0x53c09, // onoffline 0x67: 0x32b06, // sorted 0x69: 0x48110, // onlanguagechange 0x6c: 0x4310c, // onhashchange 0x6d: 0xa604, // name 0x6e: 0xb205, // tfoot 0x6f: 0x55504, // desc 0x70: 0x33103, // max 0x72: 0x1da06, // coords 0x73: 0x2f502, // h3 0x74: 0x6e10e, // onbeforeunload 0x75: 0x3a04, // rows 0x76: 0x63806, // select 0x77: 0xa805, // meter 0x78: 0x37f06, // itemid 0x79: 0x5300c, // onmousewheel 0x7a: 0x5b406, // srcdoc 0x7d: 0x17c05, // track 0x7f: 0x30708, // itemtype 0x82: 0x6302, // mo 0x83: 0x40f08, // onchange 0x84: 0x32507, // headers 0x85: 0x5c80c, // onratechange 0x86: 0x60419, // onsecuritypolicyviolation 0x88: 0x49908, // datalist 0x89: 0x4dc0b, // onmousedown 0x8a: 0x1df04, // slot 0x8b: 0x4a410, // onloadedmetadata 0x8c: 0x1a06, // accept 0x8d: 0x25006, // object 0x91: 0x6af0e, // onvolumechange 0x92: 0x2107, // charset 0x93: 0x25e13, // onautocompleteerror 0x94: 0x6913, // allowpaymentrequest 0x95: 0x2804, // body 0x96: 0xc407, // default 0x97: 0x63808, // selected 0x98: 0x20604, // face 0x99: 0x1d505, // shape 0x9b: 0x68008, // ontoggle 0x9e: 0x64702, // dt 0x9f: 0x6d904, // mark 0xa1: 0xb01, // u 0xa4: 0x6a708, // onunload 0xa5: 0xde04, // loop 0xa6: 0x14d08, // disabled 0xaa: 0x41707, // onended 0xab: 0x6d30a, // malignmark 0xad: 0x67709, // onsuspend 0xae: 0x34505, // mtext 0xaf: 0x64b06, // onsort 0xb0: 0x55908, // itemprop 0xb3: 0x66d09, // itemscope 0xb4: 0x15c05, // blink 0xb6: 0x3a506, // ondrag 0xb7: 0x6602, // ul 0xb8: 0x25604, // form 0xb9: 0xf307, // sandbox 0xba: 0x5705, // frame 0xbb: 0x1505, // value 0xbc: 0x65e09, // onstorage 0xc0: 0x17b02, // rt 0xc2: 0x202, // br 0xc3: 0x20e08, // fieldset 0xc4: 0x2780d, // typemustmatch 0xc5: 0x6108, // nomodule 0xc6: 0x4007, // noembed 0xc7: 0x69a0d, // onbeforeprint 0xc8: 0x17206, // button 0xc9: 0x2dd07, // onclick 0xca: 0x6fe07, // summary 0xcd: 0xac04, // ruby 0xce: 0x5b905, // class 0xcf: 0x3e80b, // ondragstart 0xd0: 0x21907, // caption 0xd4: 0x850e, // allowusermedia 0xd5: 0x4c30b, // onloadstart 0xd9: 0x15403, // div 0xda: 0x49d04, // list 0xdb: 0x32204, // math 0xdc: 0x43f05, // input 0xdf: 0x3de0a, // ondragover 0xe0: 0x2c602, // h2 0xe2: 0x19e09, // plaintext 0xe4: 0x4e70c, // onmouseenter 0xe7: 0x46d07, // checked 0xe8: 0x46403, // pre 0xea: 0x35308, // multiple 0xeb: 0x16103, // bdi 0xec: 0x33109, // maxlength 0xed: 0x7701, // q 0xee: 0x61b0a, // onauxclick 0xf0: 0x57003, // wbr 0xf2: 0x11504, // base 0xf3: 0x6dd06, // option 0xf5: 0x40710, // ondurationchange 0xf7: 0x5508, // noframes 0xf9: 0x3f908, // dropzone 0xfb: 0x67105, // scope 0xfc: 0x9c08, // reversed 0xfd: 0x3ae0b, // ondragenter 0xfe: 0x3ee05, // start 0xff: 0xf903, // xmp 0x100: 0x5f507, // srclang 0x101: 0x2ef03, // img 0x104: 0x101, // b 0x105: 0x23c03, // for 0x106: 0xc105, // aside 0x107: 0x43d07, // oninput 0x108: 0x34a04, // area 0x109: 0x28c0a, // formmethod 0x10a: 0x72004, // wrap 0x10c: 0x22402, // rp 0x10d: 0x45f0a, // onkeypress 0x10e: 0x5102, // tt 0x110: 0x33b02, // mi 0x111: 0x35b05, // muted 0x112: 0xb003, // alt 0x113: 0x19004, // code 0x114: 0x4202, // em 0x115: 0x3b90a, // ondragexit 0x117: 0x3d04, // span 0x119: 0x30f08, // manifest 0x11a: 0x37b08, // menuitem 0x11b: 0x57f07, // content 0x11d: 0x6bd09, // onwaiting 0x11f: 0x4ba09, // onloadend 0x121: 0x3720d, // oncontextmenu 0x123: 0x5c206, // onblur 0x124: 0x3f007, // article 0x125: 0xa303, // dir 0x126: 0xe704, // ping 0x127: 0x23408, // required 0x128: 0x44909, // oninvalid 0x129: 0x6d405, // align 0x12b: 0x57e04, // icon 0x12c: 0x64902, // h6 0x12d: 0x1b404, // cols 0x12e: 0x2160a, // figcaption 0x12f: 0x45209, // onkeydown 0x130: 0x66708, // onsubmit 0x131: 0x13609, // oncanplay 0x132: 0x70503, // sup 0x133: 0xc01, // p 0x135: 0x3fe09, // onemptied 0x136: 0x38506, // oncopy 0x137: 0x55804, // cite 0x138: 0x39b0a, // ondblclick 0x13a: 0x4ff0b, // onmousemove 0x13c: 0x66903, // sub 0x13d: 0x47b03, // rel 0x13e: 0xe008, // optgroup 0x142: 0x3a07, // rowspan 0x143: 0x36c06, // source 0x144: 0x1fe08, // noscript 0x145: 0x55f04, // open 0x146: 0x1ec03, // ins 0x147: 0x23c0d, // foreignObject 0x148: 0x5a10a, // onpopstate 0x14a: 0x27507, // enctype 0x14b: 0x25e0e, // onautocomplete 0x14c: 0x34608, // textarea 0x14e: 0x2600c, // autocomplete 0x14f: 0x14002, // hr 0x150: 0x1ce08, // controls 0x151: 0xc302, // id 0x153: 0x21e0c, // onafterprint 0x155: 0x2490d, // foreignobject 0x156: 0x31b07, // marquee 0x157: 0x58e07, // onpause 0x158: 0x5e202, // dl 0x159: 0x12c06, // height 0x15a: 0x33b03, // min 0x15b: 0xa307, // dirname 0x15c: 0x1a609, // translate 0x15d: 0x13004, // html 0x15e: 0x33b09, // minlength 0x15f: 0x47a07, // preload 0x160: 0x70e08, // template 0x161: 0x3d30b, // ondragleave 0x164: 0x5b403, // src 0x165: 0x31506, // strong 0x167: 0x4c04, // samp 0x168: 0x6ed07, // address 0x169: 0x54508, // ononline 0x16b: 0xfb0b, // placeholder 0x16c: 0x2ac06, // target 0x16d: 0x1ee05, // small 0x16e: 0x6c607, // onwheel 0x16f: 0x1b90a, // annotation 0x170: 0x4680a, // spellcheck 0x171: 0x4607, // details 0x172: 0xbd06, // canvas 0x173: 0xeb09, // autofocus 0x174: 0xc05, // param 0x176: 0x45708, // download 0x177: 0x44603, // del 0x178: 0x36007, // onclose 0x179: 0x16003, // kbd 0x17a: 0x30106, // applet 0x17b: 0x2c804, // href 0x17c: 0x5ed08, // onresize 0x17e: 0x4910c, // onloadeddata 0x180: 0x7402, // tr 0x181: 0x2a80a, // formtarget 0x182: 0xca05, // title 0x183: 0x6f905, // style 0x184: 0x7a06, // strike 0x185: 0x59206, // usemap 0x186: 0x2e406, // iframe 0x187: 0x1004, // main 0x189: 0x9707, // picture 0x18c: 0x2fe05, // ismap 0x18e: 0x49904, // data 0x18f: 0xda05, // label 0x191: 0x3c50e, // referrerpolicy 0x192: 0x13f02, // th 0x194: 0x52a06, // prompt 0x195: 0x5bd07, // section 0x197: 0x6cd07, // optimum 0x198: 0x2c304, // high 0x199: 0x14502, // h1 0x19a: 0x65509, // onstalled 0x19b: 0x15603, // var 0x19c: 0x11c04, // time 0x19e: 0x67002, // ms 0x19f: 0x32506, // header 0x1a0: 0x4ce09, // onmessage 0x1a1: 0x56205, // nonce 0x1a2: 0x2560a, // formaction 0x1a3: 0x20806, // center 0x1a4: 0x3704, // nobr 0x1a5: 0x58905, // table 0x1a6: 0x49d07, // listing 0x1a7: 0x18a06, // legend 0x1a9: 0x28309, // challenge 0x1aa: 0x23006, // figure 0x1ab: 0x8e05, // media 0x1ae: 0x8104, // type 0x1af: 0x11904, // font 0x1b0: 0x4ce0e, // onmessageerror 0x1b1: 0x36508, // seamless 0x1b2: 0x5f03, // dfn 0x1b3: 0x19205, // defer 0x1b4: 0x6b03, // low 0x1b5: 0x62d09, // onseeking 0x1b6: 0x5170b, // onmouseover 0x1b7: 0x29a0a, // novalidate 0x1b8: 0x7160a, // workertype 0x1ba: 0x3c107, // itemref 0x1bd: 0x1, // a 0x1be: 0x30003, // map 0x1bf: 0x11a0c, // ontimeupdate 0x1c0: 0x14707, // bgsound 0x1c1: 0x3206, // keygen 0x1c2: 0x2705, // tbody 0x1c5: 0x64006, // onshow 0x1c7: 0x2501, // s 0x1c8: 0x4f07, // pattern 0x1cc: 0x13610, // oncanplaythrough 0x1ce: 0x2bf02, // dd 0x1cf: 0x6f306, // srcset 0x1d0: 0x15903, // big 0x1d2: 0x64d08, // sortable 0x1d3: 0x47407, // onkeyup 0x1d5: 0x59806, // onplay 0x1d7: 0x4ac04, // meta 0x1d8: 0x3f706, // ondrop 0x1da: 0x5fc08, // onscroll 0x1db: 0x1e30b, // crossorigin 0x1dc: 0x5670a, // onpageshow 0x1dd: 0x4, // abbr 0x1de: 0x5e02, // td 0x1df: 0x57f0f, // contenteditable 0x1e0: 0x25a06, // action 0x1e1: 0x10a0b, // playsinline 0x1e2: 0x42507, // onfocus 0x1e3: 0x2c808, // hreflang 0x1e5: 0x50a0a, // onmouseout 0x1e6: 0x5e607, // onreset 0x1e7: 0x10608, // autoplay 0x1ea: 0x67106, // scoped 0x1ec: 0x30a, // radiogroup 0x1ee: 0x3740b, // contextmenu 0x1ef: 0x52209, // onmouseup 0x1f1: 0x2b206, // hgroup 0x1f2: 0x1f00f, // allowfullscreen 0x1f3: 0x4b208, // tabindex 0x1f6: 0x2f707, // isindex 0x1f7: 0x1a0e, // accept-charset 0x1f8: 0x2960e, // formnovalidate 0x1fb: 0x1b90e, // annotation-xml 0x1fc: 0x4205, // embed 0x1fd: 0x20006, // script 0x1fe: 0x16206, // dialog 0x1ff: 0x1c707, // command } const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobro" + "wspanoembedetailsampatternoframesetdfnomoduleallowpaymentreq" + "uestrikeytypeallowusermediagroupictureversedirnameterubyaltf" + "ooterasyncanvasidefaultitleaudioncancelabelooptgroupingautof" + "ocusandboxmplaceholderautoplaysinlinebasefontimeupdateviacac" + "heightmlbdoncanplaythrough1bgsoundisabledivarbigblinkbdialog" + "blockquotebuttonabortrackindraggablegendcodefercolgrouplaint" + "extranslatecolorcolspannotation-xmlcommandcontrolshapecoords" + "lotcrossoriginsmallowfullscreenoscriptfacenterfieldsetfigcap" + "tionafterprintegrityfigurequiredforeignObjectforeignobjectfo" + "rmactionautocompleteerrorformenctypemustmatchallengeformmeth" + "odformnovalidatetimeformtargethgrouposterhiddenhigh2hreflang" + "http-equivideonclickiframeimageimglyph3isindexismappletitemt" + "ypemanifestrongmarqueematheadersortedmaxlength4minlength5mte" + "xtareadonlymultiplemutedoncloseamlessourceoncontextmenuitemi" + "doncopyoncuechangeoncutondblclickondragendondragenterondrage" + "xitemreferrerpolicyondragleaveondragoverondragstarticleondro" + "pzonemptiedondurationchangeonendedonerroronfocuspaceronhashc" + "hangeoninputmodeloninvalidonkeydownloadonkeypresspellchecked" + "onkeyupreloadonlanguagechangeonloadeddatalistingonloadedmeta" + "databindexonloadendonloadstartonmessageerroronmousedownonmou" + "seenteronmouseleaveonmousemoveonmouseoutputonmouseoveronmous" + "eupromptonmousewheelonofflineononlineonpagehidescitempropeno" + "nceonpageshowbronpastepublicontenteditableonpausemaponplayin" + "gonpopstateonprogressrcdoclassectionbluronratechangeonreject" + "ionhandledonresetonresizesrclangonscrollonsecuritypolicyviol" + "ationauxclickonseekedonseekingonselectedonshowidth6onsortabl" + "eonstalledonstorageonsubmitemscopedonsuspendontoggleonunhand" + "ledrejectionbeforeprintonunloadonvolumechangeonwaitingonwhee" + "loptimumalignmarkoptionbeforeunloaddressrcsetstylesummarysup" + "svgsystemplateworkertypewrap" ���������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/atom/gen.go�����������������������������������������������0000644�0610621�0607500�00000027304�13172163402�023325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore //go:generate go run gen.go //go:generate go run gen.go -test package main import ( "bytes" "flag" "fmt" "go/format" "io/ioutil" "math/rand" "os" "sort" "strings" ) // identifier converts s to a Go exported identifier. // It converts "div" to "Div" and "accept-charset" to "AcceptCharset". func identifier(s string) string { b := make([]byte, 0, len(s)) cap := true for _, c := range s { if c == '-' { cap = true continue } if cap && 'a' <= c && c <= 'z' { c -= 'a' - 'A' } cap = false b = append(b, byte(c)) } return string(b) } var test = flag.Bool("test", false, "generate table_test.go") func genFile(name string, buf *bytes.Buffer) { b, err := format.Source(buf.Bytes()) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := ioutil.WriteFile(name, b, 0644); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func main() { flag.Parse() var all []string all = append(all, elements...) all = append(all, attributes...) all = append(all, eventHandlers...) all = append(all, extra...) sort.Strings(all) // uniq - lists have dups w := 0 for _, s := range all { if w == 0 || all[w-1] != s { all[w] = s w++ } } all = all[:w] if *test { var buf bytes.Buffer fmt.Fprintln(&buf, "// Code generated by go generate gen.go; DO NOT EDIT.\n") fmt.Fprintln(&buf, "//go:generate go run gen.go -test\n") fmt.Fprintln(&buf, "package atom\n") fmt.Fprintln(&buf, "var testAtomList = []string{") for _, s := range all { fmt.Fprintf(&buf, "\t%q,\n", s) } fmt.Fprintln(&buf, "}") genFile("table_test.go", &buf) return } // Find hash that minimizes table size. var best *table for i := 0; i < 1000000; i++ { if best != nil && 1<<(best.k-1) < len(all) { break } h := rand.Uint32() for k := uint(0); k <= 16; k++ { if best != nil && k >= best.k { break } var t table if t.init(h, k, all) { best = &t break } } } if best == nil { fmt.Fprintf(os.Stderr, "failed to construct string table\n") os.Exit(1) } // Lay out strings, using overlaps when possible. layout := append([]string{}, all...) // Remove strings that are substrings of other strings for changed := true; changed; { changed = false for i, s := range layout { if s == "" { continue } for j, t := range layout { if i != j && t != "" && strings.Contains(s, t) { changed = true layout[j] = "" } } } } // Join strings where one suffix matches another prefix. for { // Find best i, j, k such that layout[i][len-k:] == layout[j][:k], // maximizing overlap length k. besti := -1 bestj := -1 bestk := 0 for i, s := range layout { if s == "" { continue } for j, t := range layout { if i == j { continue } for k := bestk + 1; k <= len(s) && k <= len(t); k++ { if s[len(s)-k:] == t[:k] { besti = i bestj = j bestk = k } } } } if bestk > 0 { layout[besti] += layout[bestj][bestk:] layout[bestj] = "" continue } break } text := strings.Join(layout, "") atom := map[string]uint32{} for _, s := range all { off := strings.Index(text, s) if off < 0 { panic("lost string " + s) } atom[s] = uint32(off<<8 | len(s)) } var buf bytes.Buffer // Generate the Go code. fmt.Fprintln(&buf, "// Code generated by go generate gen.go; DO NOT EDIT.\n") fmt.Fprintln(&buf, "//go:generate go run gen.go\n") fmt.Fprintln(&buf, "package atom\n\nconst (") // compute max len maxLen := 0 for _, s := range all { if maxLen < len(s) { maxLen = len(s) } fmt.Fprintf(&buf, "\t%s Atom = %#x\n", identifier(s), atom[s]) } fmt.Fprintln(&buf, ")\n") fmt.Fprintf(&buf, "const hash0 = %#x\n\n", best.h0) fmt.Fprintf(&buf, "const maxAtomLen = %d\n\n", maxLen) fmt.Fprintf(&buf, "var table = [1<<%d]Atom{\n", best.k) for i, s := range best.tab { if s == "" { continue } fmt.Fprintf(&buf, "\t%#x: %#x, // %s\n", i, atom[s], s) } fmt.Fprintf(&buf, "}\n") datasize := (1 << best.k) * 4 fmt.Fprintln(&buf, "const atomText =") textsize := len(text) for len(text) > 60 { fmt.Fprintf(&buf, "\t%q +\n", text[:60]) text = text[60:] } fmt.Fprintf(&buf, "\t%q\n\n", text) genFile("table.go", &buf) fmt.Fprintf(os.Stdout, "%d atoms; %d string bytes + %d tables = %d total data\n", len(all), textsize, datasize, textsize+datasize) } type byLen []string func (x byLen) Less(i, j int) bool { return len(x[i]) > len(x[j]) } func (x byLen) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byLen) Len() int { return len(x) } // fnv computes the FNV hash with an arbitrary starting value h. func fnv(h uint32, s string) uint32 { for i := 0; i < len(s); i++ { h ^= uint32(s[i]) h *= 16777619 } return h } // A table represents an attempt at constructing the lookup table. // The lookup table uses cuckoo hashing, meaning that each string // can be found in one of two positions. type table struct { h0 uint32 k uint mask uint32 tab []string } // hash returns the two hashes for s. func (t *table) hash(s string) (h1, h2 uint32) { h := fnv(t.h0, s) h1 = h & t.mask h2 = (h >> 16) & t.mask return } // init initializes the table with the given parameters. // h0 is the initial hash value, // k is the number of bits of hash value to use, and // x is the list of strings to store in the table. // init returns false if the table cannot be constructed. func (t *table) init(h0 uint32, k uint, x []string) bool { t.h0 = h0 t.k = k t.tab = make([]string, 1<<k) t.mask = 1<<k - 1 for _, s := range x { if !t.insert(s) { return false } } return true } // insert inserts s in the table. func (t *table) insert(s string) bool { h1, h2 := t.hash(s) if t.tab[h1] == "" { t.tab[h1] = s return true } if t.tab[h2] == "" { t.tab[h2] = s return true } if t.push(h1, 0) { t.tab[h1] = s return true } if t.push(h2, 0) { t.tab[h2] = s return true } return false } // push attempts to push aside the entry in slot i. func (t *table) push(i uint32, depth int) bool { if depth > len(t.tab) { return false } s := t.tab[i] h1, h2 := t.hash(s) j := h1 + h2 - i if t.tab[j] != "" && !t.push(j, depth+1) { return false } t.tab[j] = s return true } // The lists of element names and attribute keys were taken from // https://html.spec.whatwg.org/multipage/indices.html#index // as of the "HTML Living Standard - Last Updated 18 September 2017" version. // "command", "keygen" and "menuitem" have been removed from the spec, // but are kept here for backwards compatibility. var elements = []string{ "a", "abbr", "address", "area", "article", "aside", "audio", "b", "base", "bdi", "bdo", "blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "command", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "img", "input", "ins", "kbd", "keygen", "label", "legend", "li", "link", "main", "map", "mark", "menu", "menuitem", "meta", "meter", "nav", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "slot", "small", "source", "span", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "u", "ul", "var", "video", "wbr", } // https://html.spec.whatwg.org/multipage/indices.html#attributes-3 // // "challenge", "command", "contextmenu", "dropzone", "icon", "keytype", "mediagroup", // "radiogroup", "spellcheck", "scoped", "seamless", "sortable" and "sorted" have been removed from the spec, // but are kept here for backwards compatibility. var attributes = []string{ "abbr", "accept", "accept-charset", "accesskey", "action", "allowfullscreen", "allowpaymentrequest", "allowusermedia", "alt", "as", "async", "autocomplete", "autofocus", "autoplay", "challenge", "charset", "checked", "cite", "class", "color", "cols", "colspan", "command", "content", "contenteditable", "contextmenu", "controls", "coords", "crossorigin", "data", "datetime", "default", "defer", "dir", "dirname", "disabled", "download", "draggable", "dropzone", "enctype", "for", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "headers", "height", "hidden", "high", "href", "hreflang", "http-equiv", "icon", "id", "inputmode", "integrity", "is", "ismap", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "keytype", "kind", "label", "lang", "list", "loop", "low", "manifest", "max", "maxlength", "media", "mediagroup", "method", "min", "minlength", "multiple", "muted", "name", "nomodule", "nonce", "novalidate", "open", "optimum", "pattern", "ping", "placeholder", "playsinline", "poster", "preload", "radiogroup", "readonly", "referrerpolicy", "rel", "required", "reversed", "rows", "rowspan", "sandbox", "spellcheck", "scope", "scoped", "seamless", "selected", "shape", "size", "sizes", "sortable", "sorted", "slot", "span", "spellcheck", "src", "srcdoc", "srclang", "srcset", "start", "step", "style", "tabindex", "target", "title", "translate", "type", "typemustmatch", "updateviacache", "usemap", "value", "width", "workertype", "wrap", } // "onautocomplete", "onautocompleteerror", "onmousewheel", // "onshow" and "onsort" have been removed from the spec, // but are kept here for backwards compatibility. var eventHandlers = []string{ "onabort", "onautocomplete", "onautocompleteerror", "onauxclick", "onafterprint", "onbeforeprint", "onbeforeunload", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncopy", "oncuechange", "oncut", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragexit", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onhashchange", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onlanguagechange", "onload", "onloadeddata", "onloadedmetadata", "onloadend", "onloadstart", "onmessage", "onmessageerror", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onwheel", "onoffline", "ononline", "onpagehide", "onpageshow", "onpaste", "onpause", "onplay", "onplaying", "onpopstate", "onprogress", "onratechange", "onreset", "onresize", "onrejectionhandled", "onscroll", "onsecuritypolicyviolation", "onseeked", "onseeking", "onselect", "onshow", "onsort", "onstalled", "onstorage", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onunhandledrejection", "onunload", "onvolumechange", "onwaiting", } // extra are ad-hoc values not covered by any of the lists above. var extra = []string{ "align", "annotation", "annotation-xml", "applet", "basefont", "bgsound", "big", "blink", "center", "color", "desc", "face", "font", "foreignObject", // HTML is case-insensitive, but SVG-embedded-in-HTML is case-sensitive. "foreignobject", "frame", "frameset", "image", "isindex", "listing", "malignmark", "marquee", "math", "mglyph", "mi", "mn", "mo", "ms", "mtext", "nobr", "noembed", "noframes", "plaintext", "prompt", "public", "spacer", "strike", "svg", "system", "tt", "xmp", } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/atom/atom_test.go�����������������������������������������0000644�0610621�0607500�00000004162�13172163402�024550� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package atom import ( "sort" "testing" ) func TestKnown(t *testing.T) { for _, s := range testAtomList { if atom := Lookup([]byte(s)); atom.String() != s { t.Errorf("Lookup(%q) = %#x (%q)", s, uint32(atom), atom.String()) } } } func TestHits(t *testing.T) { for _, a := range table { if a == 0 { continue } got := Lookup([]byte(a.String())) if got != a { t.Errorf("Lookup(%q) = %#x, want %#x", a.String(), uint32(got), uint32(a)) } } } func TestMisses(t *testing.T) { testCases := []string{ "", "\x00", "\xff", "A", "DIV", "Div", "dIV", "aa", "a\x00", "ab", "abb", "abbr0", "abbr ", " abbr", " a", "acceptcharset", "acceptCharset", "accept_charset", "h0", "h1h2", "h7", "onClick", "λ", // The following string has the same hash (0xa1d7fab7) as "onmouseover". "\x00\x00\x00\x00\x00\x50\x18\xae\x38\xd0\xb7", } for _, tc := range testCases { got := Lookup([]byte(tc)) if got != 0 { t.Errorf("Lookup(%q): got %d, want 0", tc, got) } } } func TestForeignObject(t *testing.T) { const ( afo = Foreignobject afO = ForeignObject sfo = "foreignobject" sfO = "foreignObject" ) if got := Lookup([]byte(sfo)); got != afo { t.Errorf("Lookup(%q): got %#v, want %#v", sfo, got, afo) } if got := Lookup([]byte(sfO)); got != afO { t.Errorf("Lookup(%q): got %#v, want %#v", sfO, got, afO) } if got := afo.String(); got != sfo { t.Errorf("Atom(%#v).String(): got %q, want %q", afo, got, sfo) } if got := afO.String(); got != sfO { t.Errorf("Atom(%#v).String(): got %q, want %q", afO, got, sfO) } } func BenchmarkLookup(b *testing.B) { sortedTable := make([]string, 0, len(table)) for _, a := range table { if a != 0 { sortedTable = append(sortedTable, a.String()) } } sort.Strings(sortedTable) x := make([][]byte, 1000) for i := range x { x[i] = []byte(sortedTable[i%len(sortedTable)]) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, s := range x { Lookup(s) } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/html/atom/atom.go����������������������������������������������0000644�0610621�0607500�00000004421�13172163402�023507� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package atom provides integer codes (also known as atoms) for a fixed set of // frequently occurring HTML strings: tag names and attribute keys such as "p" // and "id". // // Sharing an atom's name between all elements with the same tag can result in // fewer string allocations when tokenizing and parsing HTML. Integer // comparisons are also generally faster than string comparisons. // // The value of an atom's particular code is not guaranteed to stay the same // between versions of this package. Neither is any ordering guaranteed: // whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to // be dense. The only guarantees are that e.g. looking up "div" will yield // atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. package atom // import "golang.org/x/net/html/atom" // Atom is an integer code for a string. The zero value maps to "". type Atom uint32 // String returns the atom's name. func (a Atom) String() string { start := uint32(a >> 8) n := uint32(a & 0xff) if start+n > uint32(len(atomText)) { return "" } return atomText[start : start+n] } func (a Atom) string() string { return atomText[a>>8 : a>>8+a&0xff] } // fnv computes the FNV hash with an arbitrary starting value h. func fnv(h uint32, s []byte) uint32 { for i := range s { h ^= uint32(s[i]) h *= 16777619 } return h } func match(s string, t []byte) bool { for i, c := range t { if s[i] != c { return false } } return true } // Lookup returns the atom whose name is s. It returns zero if there is no // such atom. The lookup is case sensitive. func Lookup(s []byte) Atom { if len(s) == 0 || len(s) > maxAtomLen { return 0 } h := fnv(hash0, s) if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { return a } if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { return a } return 0 } // String returns a string whose contents are equal to s. In that sense, it is // equivalent to string(s) but may be more efficient. func String(s []byte) string { if a := Lookup(s); a != 0 { return a.String() } return string(s) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/dns/�����������������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�021077� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/dns/dnsmessage/������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�023230� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/dns/dnsmessage/message_test.go���������������������������������0000644�0610621�0607500�00000070744�13172163402�026256� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package dnsmessage import ( "bytes" "fmt" "reflect" "testing" ) func mustNewName(name string) Name { n, err := NewName(name) if err != nil { panic(err) } return n } func (m *Message) String() string { s := fmt.Sprintf("Message: %#v\n", &m.Header) if len(m.Questions) > 0 { s += "-- Questions\n" for _, q := range m.Questions { s += fmt.Sprintf("%#v\n", q) } } if len(m.Answers) > 0 { s += "-- Answers\n" for _, a := range m.Answers { s += fmt.Sprintf("%#v\n", a) } } if len(m.Authorities) > 0 { s += "-- Authorities\n" for _, ns := range m.Authorities { s += fmt.Sprintf("%#v\n", ns) } } if len(m.Additionals) > 0 { s += "-- Additionals\n" for _, e := range m.Additionals { s += fmt.Sprintf("%#v\n", e) } } return s } func TestNameString(t *testing.T) { want := "foo" name := mustNewName(want) if got := fmt.Sprint(name); got != want { t.Errorf("got fmt.Sprint(%#v) = %s, want = %s", name, got, want) } } func TestQuestionPackUnpack(t *testing.T) { want := Question{ Name: mustNewName("."), Type: TypeA, Class: ClassINET, } buf, err := want.pack(make([]byte, 1, 50), map[string]int{}) if err != nil { t.Fatal("Packing failed:", err) } var p Parser p.msg = buf p.header.questions = 1 p.section = sectionQuestions p.off = 1 got, err := p.Question() if err != nil { t.Fatalf("Unpacking failed: %v\n%s", err, string(buf[1:])) } if p.off != len(buf) { t.Errorf("Unpacked different amount than packed: got n = %d, want = %d", p.off, len(buf)) } if !reflect.DeepEqual(got, want) { t.Errorf("Got = %+v, want = %+v", got, want) } } func TestName(t *testing.T) { tests := []string{ "", ".", "google..com", "google.com", "google..com.", "google.com.", ".google.com.", "www..google.com.", "www.google.com.", } for _, test := range tests { n, err := NewName(test) if err != nil { t.Errorf("Creating name for %q: %v", test, err) continue } if ns := n.String(); ns != test { t.Errorf("Got %#v.String() = %q, want = %q", n, ns, test) continue } } } func TestNamePackUnpack(t *testing.T) { tests := []struct { in string want string err error }{ {"", "", errNonCanonicalName}, {".", ".", nil}, {"google..com", "", errNonCanonicalName}, {"google.com", "", errNonCanonicalName}, {"google..com.", "", errZeroSegLen}, {"google.com.", "google.com.", nil}, {".google.com.", "", errZeroSegLen}, {"www..google.com.", "", errZeroSegLen}, {"www.google.com.", "www.google.com.", nil}, } for _, test := range tests { in := mustNewName(test.in) want := mustNewName(test.want) buf, err := in.pack(make([]byte, 0, 30), map[string]int{}) if err != test.err { t.Errorf("Packing of %q: got err = %v, want err = %v", test.in, err, test.err) continue } if test.err != nil { continue } var got Name n, err := got.unpack(buf, 0) if err != nil { t.Errorf("Unpacking for %q failed: %v", test.in, err) continue } if n != len(buf) { t.Errorf( "Unpacked different amount than packed for %q: got n = %d, want = %d", test.in, n, len(buf), ) } if got != want { t.Errorf("Unpacking packing of %q: got = %#v, want = %#v", test.in, got, want) } } } func checkErrorPrefix(err error, prefix string) bool { e, ok := err.(*nestedError) return ok && e.s == prefix } func TestHeaderUnpackError(t *testing.T) { wants := []string{ "id", "bits", "questions", "answers", "authorities", "additionals", } var buf []byte var h header for _, want := range wants { n, err := h.unpack(buf, 0) if n != 0 || !checkErrorPrefix(err, want) { t.Errorf("got h.unpack([%d]byte, 0) = %d, %v, want = 0, %s", len(buf), n, err, want) } buf = append(buf, 0, 0) } } func TestParserStart(t *testing.T) { const want = "unpacking header" var p Parser for i := 0; i <= 1; i++ { _, err := p.Start([]byte{}) if !checkErrorPrefix(err, want) { t.Errorf("got p.Start(nil) = _, %v, want = _, %s", err, want) } } } func TestResourceNotStarted(t *testing.T) { tests := []struct { name string fn func(*Parser) error }{ {"CNAMEResource", func(p *Parser) error { _, err := p.CNAMEResource(); return err }}, {"MXResource", func(p *Parser) error { _, err := p.MXResource(); return err }}, {"NSResource", func(p *Parser) error { _, err := p.NSResource(); return err }}, {"PTRResource", func(p *Parser) error { _, err := p.PTRResource(); return err }}, {"SOAResource", func(p *Parser) error { _, err := p.SOAResource(); return err }}, {"TXTResource", func(p *Parser) error { _, err := p.TXTResource(); return err }}, {"SRVResource", func(p *Parser) error { _, err := p.SRVResource(); return err }}, {"AResource", func(p *Parser) error { _, err := p.AResource(); return err }}, {"AAAAResource", func(p *Parser) error { _, err := p.AAAAResource(); return err }}, } for _, test := range tests { if err := test.fn(&Parser{}); err != ErrNotStarted { t.Errorf("got _, %v = p.%s(), want = _, %v", err, test.name, ErrNotStarted) } } } func TestDNSPackUnpack(t *testing.T) { wants := []Message{ { Questions: []Question{ { Name: mustNewName("."), Type: TypeAAAA, Class: ClassINET, }, }, Answers: []Resource{}, Authorities: []Resource{}, Additionals: []Resource{}, }, largeTestMsg(), } for i, want := range wants { b, err := want.Pack() if err != nil { t.Fatalf("%d: packing failed: %v", i, err) } var got Message err = got.Unpack(b) if err != nil { t.Fatalf("%d: unpacking failed: %v", i, err) } if !reflect.DeepEqual(got, want) { t.Errorf("%d: got = %+v, want = %+v", i, &got, &want) } } } func TestSkipAll(t *testing.T) { msg := largeTestMsg() buf, err := msg.Pack() if err != nil { t.Fatal("Packing large test message:", err) } var p Parser if _, err := p.Start(buf); err != nil { t.Fatal(err) } tests := []struct { name string f func() error }{ {"SkipAllQuestions", p.SkipAllQuestions}, {"SkipAllAnswers", p.SkipAllAnswers}, {"SkipAllAuthorities", p.SkipAllAuthorities}, {"SkipAllAdditionals", p.SkipAllAdditionals}, } for _, test := range tests { for i := 1; i <= 3; i++ { if err := test.f(); err != nil { t.Errorf("Call #%d to %s(): %v", i, test.name, err) } } } } func TestSkipEach(t *testing.T) { msg := smallTestMsg() buf, err := msg.Pack() if err != nil { t.Fatal("Packing test message:", err) } var p Parser if _, err := p.Start(buf); err != nil { t.Fatal(err) } tests := []struct { name string f func() error }{ {"SkipQuestion", p.SkipQuestion}, {"SkipAnswer", p.SkipAnswer}, {"SkipAuthority", p.SkipAuthority}, {"SkipAdditional", p.SkipAdditional}, } for _, test := range tests { if err := test.f(); err != nil { t.Errorf("First call: got %s() = %v, want = %v", test.name, err, nil) } if err := test.f(); err != ErrSectionDone { t.Errorf("Second call: got %s() = %v, want = %v", test.name, err, ErrSectionDone) } } } func TestSkipAfterRead(t *testing.T) { msg := smallTestMsg() buf, err := msg.Pack() if err != nil { t.Fatal("Packing test message:", err) } var p Parser if _, err := p.Start(buf); err != nil { t.Fatal(err) } tests := []struct { name string skip func() error read func() error }{ {"Question", p.SkipQuestion, func() error { _, err := p.Question(); return err }}, {"Answer", p.SkipAnswer, func() error { _, err := p.Answer(); return err }}, {"Authority", p.SkipAuthority, func() error { _, err := p.Authority(); return err }}, {"Additional", p.SkipAdditional, func() error { _, err := p.Additional(); return err }}, } for _, test := range tests { if err := test.read(); err != nil { t.Errorf("Got %s() = _, %v, want = _, %v", test.name, err, nil) } if err := test.skip(); err != ErrSectionDone { t.Errorf("Got Skip%s() = %v, want = %v", test.name, err, ErrSectionDone) } } } func TestSkipNotStarted(t *testing.T) { var p Parser tests := []struct { name string f func() error }{ {"SkipAllQuestions", p.SkipAllQuestions}, {"SkipAllAnswers", p.SkipAllAnswers}, {"SkipAllAuthorities", p.SkipAllAuthorities}, {"SkipAllAdditionals", p.SkipAllAdditionals}, } for _, test := range tests { if err := test.f(); err != ErrNotStarted { t.Errorf("Got %s() = %v, want = %v", test.name, err, ErrNotStarted) } } } func TestTooManyRecords(t *testing.T) { const recs = int(^uint16(0)) + 1 tests := []struct { name string msg Message want error }{ { "Questions", Message{ Questions: make([]Question, recs), }, errTooManyQuestions, }, { "Answers", Message{ Answers: make([]Resource, recs), }, errTooManyAnswers, }, { "Authorities", Message{ Authorities: make([]Resource, recs), }, errTooManyAuthorities, }, { "Additionals", Message{ Additionals: make([]Resource, recs), }, errTooManyAdditionals, }, } for _, test := range tests { if _, got := test.msg.Pack(); got != test.want { t.Errorf("Packing %d %s: got = %v, want = %v", recs, test.name, got, test.want) } } } func TestVeryLongTxt(t *testing.T) { want := Resource{ ResourceHeader{ Name: mustNewName("foo.bar.example.com."), Type: TypeTXT, Class: ClassINET, }, &TXTResource{loremIpsum}, } buf, err := want.pack(make([]byte, 0, 8000), map[string]int{}) if err != nil { t.Fatal("Packing failed:", err) } var got Resource off, err := got.Header.unpack(buf, 0) if err != nil { t.Fatal("Unpacking ResourceHeader failed:", err) } body, n, err := unpackResourceBody(buf, off, got.Header) if err != nil { t.Fatal("Unpacking failed:", err) } got.Body = body if n != len(buf) { t.Errorf("Unpacked different amount than packed: got n = %d, want = %d", n, len(buf)) } if !reflect.DeepEqual(got, want) { t.Errorf("Got = %#v, want = %#v", got, want) } } func TestStartError(t *testing.T) { tests := []struct { name string fn func(*Builder) error }{ {"Questions", func(b *Builder) error { return b.StartQuestions() }}, {"Answers", func(b *Builder) error { return b.StartAnswers() }}, {"Authorities", func(b *Builder) error { return b.StartAuthorities() }}, {"Additionals", func(b *Builder) error { return b.StartAdditionals() }}, } envs := []struct { name string fn func() *Builder want error }{ {"sectionNotStarted", func() *Builder { return &Builder{section: sectionNotStarted} }, ErrNotStarted}, {"sectionDone", func() *Builder { return &Builder{section: sectionDone} }, ErrSectionDone}, } for _, env := range envs { for _, test := range tests { if got := test.fn(env.fn()); got != env.want { t.Errorf("got Builder{%s}.Start%s = %v, want = %v", env.name, test.name, got, env.want) } } } } func TestBuilderResourceError(t *testing.T) { tests := []struct { name string fn func(*Builder) error }{ {"CNAMEResource", func(b *Builder) error { return b.CNAMEResource(ResourceHeader{}, CNAMEResource{}) }}, {"MXResource", func(b *Builder) error { return b.MXResource(ResourceHeader{}, MXResource{}) }}, {"NSResource", func(b *Builder) error { return b.NSResource(ResourceHeader{}, NSResource{}) }}, {"PTRResource", func(b *Builder) error { return b.PTRResource(ResourceHeader{}, PTRResource{}) }}, {"SOAResource", func(b *Builder) error { return b.SOAResource(ResourceHeader{}, SOAResource{}) }}, {"TXTResource", func(b *Builder) error { return b.TXTResource(ResourceHeader{}, TXTResource{}) }}, {"SRVResource", func(b *Builder) error { return b.SRVResource(ResourceHeader{}, SRVResource{}) }}, {"AResource", func(b *Builder) error { return b.AResource(ResourceHeader{}, AResource{}) }}, {"AAAAResource", func(b *Builder) error { return b.AAAAResource(ResourceHeader{}, AAAAResource{}) }}, } envs := []struct { name string fn func() *Builder want error }{ {"sectionNotStarted", func() *Builder { return &Builder{section: sectionNotStarted} }, ErrNotStarted}, {"sectionHeader", func() *Builder { return &Builder{section: sectionHeader} }, ErrNotStarted}, {"sectionQuestions", func() *Builder { return &Builder{section: sectionQuestions} }, ErrNotStarted}, {"sectionDone", func() *Builder { return &Builder{section: sectionDone} }, ErrSectionDone}, } for _, env := range envs { for _, test := range tests { if got := test.fn(env.fn()); got != env.want { t.Errorf("got Builder{%s}.%s = %v, want = %v", env.name, test.name, got, env.want) } } } } func TestFinishError(t *testing.T) { var b Builder want := ErrNotStarted if _, got := b.Finish(); got != want { t.Errorf("got Builder{}.Finish() = %v, want = %v", got, want) } } func TestBuilder(t *testing.T) { msg := largeTestMsg() want, err := msg.Pack() if err != nil { t.Fatal("Packing without builder:", err) } var b Builder b.Start(nil, msg.Header) if err := b.StartQuestions(); err != nil { t.Fatal("b.StartQuestions():", err) } for _, q := range msg.Questions { if err := b.Question(q); err != nil { t.Fatalf("b.Question(%#v): %v", q, err) } } if err := b.StartAnswers(); err != nil { t.Fatal("b.StartAnswers():", err) } for _, a := range msg.Answers { switch a.Header.Type { case TypeA: if err := b.AResource(a.Header, *a.Body.(*AResource)); err != nil { t.Fatalf("b.AResource(%#v): %v", a, err) } case TypeNS: if err := b.NSResource(a.Header, *a.Body.(*NSResource)); err != nil { t.Fatalf("b.NSResource(%#v): %v", a, err) } case TypeCNAME: if err := b.CNAMEResource(a.Header, *a.Body.(*CNAMEResource)); err != nil { t.Fatalf("b.CNAMEResource(%#v): %v", a, err) } case TypeSOA: if err := b.SOAResource(a.Header, *a.Body.(*SOAResource)); err != nil { t.Fatalf("b.SOAResource(%#v): %v", a, err) } case TypePTR: if err := b.PTRResource(a.Header, *a.Body.(*PTRResource)); err != nil { t.Fatalf("b.PTRResource(%#v): %v", a, err) } case TypeMX: if err := b.MXResource(a.Header, *a.Body.(*MXResource)); err != nil { t.Fatalf("b.MXResource(%#v): %v", a, err) } case TypeTXT: if err := b.TXTResource(a.Header, *a.Body.(*TXTResource)); err != nil { t.Fatalf("b.TXTResource(%#v): %v", a, err) } case TypeAAAA: if err := b.AAAAResource(a.Header, *a.Body.(*AAAAResource)); err != nil { t.Fatalf("b.AAAAResource(%#v): %v", a, err) } case TypeSRV: if err := b.SRVResource(a.Header, *a.Body.(*SRVResource)); err != nil { t.Fatalf("b.SRVResource(%#v): %v", a, err) } } } if err := b.StartAuthorities(); err != nil { t.Fatal("b.StartAuthorities():", err) } for _, a := range msg.Authorities { if err := b.NSResource(a.Header, *a.Body.(*NSResource)); err != nil { t.Fatalf("b.NSResource(%#v): %v", a, err) } } if err := b.StartAdditionals(); err != nil { t.Fatal("b.StartAdditionals():", err) } for _, a := range msg.Additionals { if err := b.TXTResource(a.Header, *a.Body.(*TXTResource)); err != nil { t.Fatalf("b.TXTResource(%#v): %v", a, err) } } got, err := b.Finish() if err != nil { t.Fatal("b.Finish():", err) } if !bytes.Equal(got, want) { t.Fatalf("Got from Builder: %#v\nwant = %#v", got, want) } } func TestResourcePack(t *testing.T) { for _, tt := range []struct { m Message err error }{ { Message{ Questions: []Question{ { Name: mustNewName("."), Type: TypeAAAA, Class: ClassINET, }, }, Answers: []Resource{{ResourceHeader{}, nil}}, }, &nestedError{"packing Answer", errNilResouceBody}, }, { Message{ Questions: []Question{ { Name: mustNewName("."), Type: TypeAAAA, Class: ClassINET, }, }, Authorities: []Resource{{ResourceHeader{}, (*NSResource)(nil)}}, }, &nestedError{"packing Authority", &nestedError{"ResourceHeader", &nestedError{"Name", errNonCanonicalName}, }, }, }, { Message{ Questions: []Question{ { Name: mustNewName("."), Type: TypeA, Class: ClassINET, }, }, Additionals: []Resource{{ResourceHeader{}, nil}}, }, &nestedError{"packing Additional", errNilResouceBody}, }, } { _, err := tt.m.Pack() if !reflect.DeepEqual(err, tt.err) { t.Errorf("got %v for %v; want %v", err, tt.m, tt.err) } } } func BenchmarkParsing(b *testing.B) { b.ReportAllocs() name := mustNewName("foo.bar.example.com.") msg := Message{ Header: Header{Response: true, Authoritative: true}, Questions: []Question{ { Name: name, Type: TypeA, Class: ClassINET, }, }, Answers: []Resource{ { ResourceHeader{ Name: name, Class: ClassINET, }, &AResource{[4]byte{}}, }, { ResourceHeader{ Name: name, Class: ClassINET, }, &AAAAResource{[16]byte{}}, }, { ResourceHeader{ Name: name, Class: ClassINET, }, &CNAMEResource{name}, }, { ResourceHeader{ Name: name, Class: ClassINET, }, &NSResource{name}, }, }, } buf, err := msg.Pack() if err != nil { b.Fatal("msg.Pack():", err) } for i := 0; i < b.N; i++ { var p Parser if _, err := p.Start(buf); err != nil { b.Fatal("p.Start(buf):", err) } for { _, err := p.Question() if err == ErrSectionDone { break } if err != nil { b.Fatal("p.Question():", err) } } for { h, err := p.AnswerHeader() if err == ErrSectionDone { break } if err != nil { panic(err) } switch h.Type { case TypeA: if _, err := p.AResource(); err != nil { b.Fatal("p.AResource():", err) } case TypeAAAA: if _, err := p.AAAAResource(); err != nil { b.Fatal("p.AAAAResource():", err) } case TypeCNAME: if _, err := p.CNAMEResource(); err != nil { b.Fatal("p.CNAMEResource():", err) } case TypeNS: if _, err := p.NSResource(); err != nil { b.Fatal("p.NSResource():", err) } default: b.Fatalf("unknown type: %T", h) } } } } func BenchmarkBuilding(b *testing.B) { b.ReportAllocs() name := mustNewName("foo.bar.example.com.") buf := make([]byte, 0, packStartingCap) for i := 0; i < b.N; i++ { var bld Builder bld.StartWithoutCompression(buf, Header{Response: true, Authoritative: true}) if err := bld.StartQuestions(); err != nil { b.Fatal("bld.StartQuestions():", err) } q := Question{ Name: name, Type: TypeA, Class: ClassINET, } if err := bld.Question(q); err != nil { b.Fatalf("bld.Question(%+v): %v", q, err) } hdr := ResourceHeader{ Name: name, Class: ClassINET, } if err := bld.StartAnswers(); err != nil { b.Fatal("bld.StartQuestions():", err) } ar := AResource{[4]byte{}} if err := bld.AResource(hdr, ar); err != nil { b.Fatalf("bld.AResource(%+v, %+v): %v", hdr, ar, err) } aaar := AAAAResource{[16]byte{}} if err := bld.AAAAResource(hdr, aaar); err != nil { b.Fatalf("bld.AAAAResource(%+v, %+v): %v", hdr, aaar, err) } cnr := CNAMEResource{name} if err := bld.CNAMEResource(hdr, cnr); err != nil { b.Fatalf("bld.CNAMEResource(%+v, %+v): %v", hdr, cnr, err) } nsr := NSResource{name} if err := bld.NSResource(hdr, nsr); err != nil { b.Fatalf("bld.NSResource(%+v, %+v): %v", hdr, nsr, err) } if _, err := bld.Finish(); err != nil { b.Fatal("bld.Finish():", err) } } } func smallTestMsg() Message { name := mustNewName("example.com.") return Message{ Header: Header{Response: true, Authoritative: true}, Questions: []Question{ { Name: name, Type: TypeA, Class: ClassINET, }, }, Answers: []Resource{ { ResourceHeader{ Name: name, Type: TypeA, Class: ClassINET, }, &AResource{[4]byte{127, 0, 0, 1}}, }, }, Authorities: []Resource{ { ResourceHeader{ Name: name, Type: TypeA, Class: ClassINET, }, &AResource{[4]byte{127, 0, 0, 1}}, }, }, Additionals: []Resource{ { ResourceHeader{ Name: name, Type: TypeA, Class: ClassINET, }, &AResource{[4]byte{127, 0, 0, 1}}, }, }, } } func largeTestMsg() Message { name := mustNewName("foo.bar.example.com.") return Message{ Header: Header{Response: true, Authoritative: true}, Questions: []Question{ { Name: name, Type: TypeA, Class: ClassINET, }, }, Answers: []Resource{ { ResourceHeader{ Name: name, Type: TypeA, Class: ClassINET, }, &AResource{[4]byte{127, 0, 0, 1}}, }, { ResourceHeader{ Name: name, Type: TypeA, Class: ClassINET, }, &AResource{[4]byte{127, 0, 0, 2}}, }, { ResourceHeader{ Name: name, Type: TypeAAAA, Class: ClassINET, }, &AAAAResource{[16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}}, }, { ResourceHeader{ Name: name, Type: TypeCNAME, Class: ClassINET, }, &CNAMEResource{mustNewName("alias.example.com.")}, }, { ResourceHeader{ Name: name, Type: TypeSOA, Class: ClassINET, }, &SOAResource{ NS: mustNewName("ns1.example.com."), MBox: mustNewName("mb.example.com."), Serial: 1, Refresh: 2, Retry: 3, Expire: 4, MinTTL: 5, }, }, { ResourceHeader{ Name: name, Type: TypePTR, Class: ClassINET, }, &PTRResource{mustNewName("ptr.example.com.")}, }, { ResourceHeader{ Name: name, Type: TypeMX, Class: ClassINET, }, &MXResource{ 7, mustNewName("mx.example.com."), }, }, { ResourceHeader{ Name: name, Type: TypeSRV, Class: ClassINET, }, &SRVResource{ 8, 9, 11, mustNewName("srv.example.com."), }, }, }, Authorities: []Resource{ { ResourceHeader{ Name: name, Type: TypeNS, Class: ClassINET, }, &NSResource{mustNewName("ns1.example.com.")}, }, { ResourceHeader{ Name: name, Type: TypeNS, Class: ClassINET, }, &NSResource{mustNewName("ns2.example.com.")}, }, }, Additionals: []Resource{ { ResourceHeader{ Name: name, Type: TypeTXT, Class: ClassINET, }, &TXTResource{"So Long, and Thanks for All the Fish"}, }, { ResourceHeader{ Name: name, Type: TypeTXT, Class: ClassINET, }, &TXTResource{"Hamster Huey and the Gooey Kablooie"}, }, }, } } const loremIpsum = ` Lorem ipsum dolor sit amet, nec enim antiopam id, an ullum choro nonumes qui, pro eu debet honestatis mediocritatem. No alia enim eos, magna signiferumque ex vis. Mei no aperiri dissentias, cu vel quas regione. Malorum quaeque vim ut, eum cu semper aliquid invidunt, ei nam ipsum assentior. Nostrum appellantur usu no, vis ex probatus adipiscing. Cu usu illum facilis eleifend. Iusto conceptam complectitur vim id. Tale omnesque no usu, ei oblique sadipscing vim. At nullam voluptua usu, mei laudem reformidans et. Qui ei eros porro reformidans, ius suas veritus torquatos ex. Mea te facer alterum consequat. Soleat torquatos democritum sed et, no mea congue appareat, facer aliquam nec in. Has te ipsum tritani. At justo dicta option nec, movet phaedrum ad nam. Ea detracto verterem liberavisse has, delectus suscipiantur in mei. Ex nam meliore complectitur. Ut nam omnis honestatis quaerendum, ea mea nihil affert detracto, ad vix rebum mollis. Ut epicurei praesent neglegentur pri, prima fuisset intellegebat ad vim. An habemus comprehensam usu, at enim dignissim pro. Eam reque vivendum adipisci ea. Vel ne odio choro minimum. Sea admodum dissentiet ex. Mundi tamquam evertitur ius cu. Homero postea iisque ut pro, vel ne saepe senserit consetetur. Nulla utamur facilisis ius ea, in viderer diceret pertinax eum. Mei no enim quodsi facilisi, ex sed aeterno appareat mediocritatem, eum sententiae deterruisset ut. At suas timeam euismod cum, offendit appareat interpretaris ne vix. Vel ea civibus albucius, ex vim quidam accusata intellegebat, noluisse instructior sea id. Nec te nonumes habemus appellantur, quis dignissim vituperata eu nam. At vix apeirian patrioque vituperatoribus, an usu agam assum. Debet iisque an mea. Per eu dicant ponderum accommodare. Pri alienum placerat senserit an, ne eum ferri abhorreant vituperatoribus. Ut mea eligendi disputationi. Ius no tation everti impedit, ei magna quidam mediocritatem pri. Legendos perpetua iracundia ne usu, no ius ullum epicurei intellegam, ad modus epicuri lucilius eam. In unum quaerendum usu. Ne diam paulo has, ea veri virtute sed. Alia honestatis conclusionemque mea eu, ut iudico albucius his. Usu essent probatus eu, sed omnis dolor delicatissimi ex. No qui augue dissentias dissentiet. Laudem recteque no usu, vel an velit noluisse, an sed utinam eirmod appetere. Ne mea fuisset inimicus ocurreret. At vis dicant abhorreant, utinam forensibus nec ne, mei te docendi consequat. Brute inermis persecuti cum id. Ut ipsum munere propriae usu, dicit graeco disputando id has. Eros dolore quaerendum nam ei. Timeam ornatus inciderint pro id. Nec torquatos sadipscing ei, ancillae molestie per in. Malis principes duo ea, usu liber postulant ei. Graece timeam voluptatibus eu eam. Alia probatus quo no, ea scripta feugiat duo. Congue option meliore ex qui, noster invenire appellantur ea vel. Eu exerci legendos vel. Consetetur repudiandae vim ut. Vix an probo minimum, et nam illud falli tempor. Cum dico signiferumque eu. Sed ut regione maiorum, id veritus insolens tacimates vix. Eu mel sint tamquam lucilius, duo no oporteat tacimates. Atqui augue concludaturque vix ei, id mel utroque menandri. Ad oratio blandit aliquando pro. Vis et dolorum rationibus philosophia, ad cum nulla molestie. Hinc fuisset adversarium eum et, ne qui nisl verear saperet, vel te quaestio forensibus. Per odio option delenit an. Alii placerat has no, in pri nihil platonem cotidieque. Est ut elit copiosae scaevola, debet tollit maluisset sea an. Te sea hinc debet pericula, liber ridens fabulas cu sed, quem mutat accusam mea et. Elitr labitur albucius et pri, an labore feugait mel. Velit zril melius usu ea. Ad stet putent interpretaris qui. Mel no error volumus scripserit. In pro paulo iudico, quo ei dolorem verterem, affert fabellas dissentiet ea vix. Vis quot deserunt te. Error aliquid detraxit eu usu, vis alia eruditi salutatus cu. Est nostrud bonorum an, ei usu alii salutatus. Vel at nisl primis, eum ex aperiri noluisse reformidans. Ad veri velit utroque vis, ex equidem detraxit temporibus has. Inermis appareat usu ne. Eros placerat periculis mea ad, in dictas pericula pro. Errem postulant at usu, ea nec amet ornatus mentitum. Ad mazim graeco eum, vel ex percipit volutpat iudicabit, sit ne delicata interesset. Mel sapientem prodesset abhorreant et, oblique suscipit eam id. An maluisset disputando mea, vidit mnesarchum pri et. Malis insolens inciderint no sea. Ea persius maluisset vix, ne vim appellantur instructior, consul quidam definiebas pri id. Cum integre feugiat pericula in, ex sed persius similique, mel ne natum dicit percipitur. Primis discere ne pri, errem putent definitionem at vis. Ei mel dolore neglegentur, mei tincidunt percipitur ei. Pro ad simul integre rationibus. Eu vel alii honestatis definitiones, mea no nonumy reprehendunt. Dicta appareat legendos est cu. Eu vel congue dicunt omittam, no vix adhuc minimum constituam, quot noluisse id mel. Eu quot sale mutat duo, ex nisl munere invenire duo. Ne nec ullum utamur. Pro alterum debitis nostrum no, ut vel aliquid vivendo. Aliquip fierent praesent quo ne, id sit audiam recusabo delicatissimi. Usu postulant incorrupte cu. At pro dicit tibique intellegam, cibo dolore impedit id eam, et aeque feugait assentior has. Quando sensibus nec ex. Possit sensibus pri ad, unum mutat periculis cu vix. Mundi tibique vix te, duo simul partiendo qualisque id, est at vidit sonet tempor. No per solet aeterno deseruisse. Petentium salutandi definiebas pri cu. Munere vivendum est in. Ei justo congue eligendi vis, modus offendit omittantur te mel. Integre voluptaria in qui, sit habemus tractatos constituam no. Utinam melius conceptam est ne, quo in minimum apeirian delicata, ut ius porro recusabo. Dicant expetenda vix no, ludus scripserit sed ex, eu his modo nostro. Ut etiam sonet his, quodsi inciderint philosophia te per. Nullam lobortis eu cum, vix an sonet efficiendi repudiandae. Vis ad idque fabellas intellegebat. Eum commodo senserit conclusionemque ex. Sed forensibus sadipscing ut, mei in facer delicata periculis, sea ne hinc putent cetero. Nec ne alia corpora invenire, alia prima soleat te cum. Eleifend posidonium nam at. Dolorum indoctum cu quo, ex dolor legendos recteque eam, cu pri zril discere. Nec civibus officiis dissentiunt ex, est te liber ludus elaboraret. Cum ea fabellas invenire. Ex vim nostrud eripuit comprehensam, nam te inermis delectus, saepe inermis senserit. ` ����������������������������lxd-2.0.11/dist/src/golang.org/x/net/dns/dnsmessage/message.go��������������������������������������0000644�0610621�0607500�00000141604�13172163402�025211� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package dnsmessage provides a mostly RFC 1035 compliant implementation of // DNS message packing and unpacking. // // This implementation is designed to minimize heap allocations and avoid // unnecessary packing and unpacking as much as possible. package dnsmessage import ( "errors" ) // Packet formats // A Type is a type of DNS request and response. type Type uint16 // A Class is a type of network. type Class uint16 // An OpCode is a DNS operation code. type OpCode uint16 // An RCode is a DNS response status code. type RCode uint16 // Wire constants. const ( // ResourceHeader.Type and Question.Type TypeA Type = 1 TypeNS Type = 2 TypeCNAME Type = 5 TypeSOA Type = 6 TypePTR Type = 12 TypeMX Type = 15 TypeTXT Type = 16 TypeAAAA Type = 28 TypeSRV Type = 33 // Question.Type TypeWKS Type = 11 TypeHINFO Type = 13 TypeMINFO Type = 14 TypeAXFR Type = 252 TypeALL Type = 255 // ResourceHeader.Class and Question.Class ClassINET Class = 1 ClassCSNET Class = 2 ClassCHAOS Class = 3 ClassHESIOD Class = 4 // Question.Class ClassANY Class = 255 // Message.Rcode RCodeSuccess RCode = 0 RCodeFormatError RCode = 1 RCodeServerFailure RCode = 2 RCodeNameError RCode = 3 RCodeNotImplemented RCode = 4 RCodeRefused RCode = 5 ) var ( // ErrNotStarted indicates that the prerequisite information isn't // available yet because the previous records haven't been appropriately // parsed, skipped or finished. ErrNotStarted = errors.New("parsing/packing of this type isn't available yet") // ErrSectionDone indicated that all records in the section have been // parsed or finished. ErrSectionDone = errors.New("parsing/packing of this section has completed") errBaseLen = errors.New("insufficient data for base length type") errCalcLen = errors.New("insufficient data for calculated length type") errReserved = errors.New("segment prefix is reserved") errTooManyPtr = errors.New("too many pointers (>10)") errInvalidPtr = errors.New("invalid pointer") errNilResouceBody = errors.New("nil resource body") errResourceLen = errors.New("insufficient data for resource body length") errSegTooLong = errors.New("segment length too long") errZeroSegLen = errors.New("zero length segment") errResTooLong = errors.New("resource length too long") errTooManyQuestions = errors.New("too many Questions to pack (>65535)") errTooManyAnswers = errors.New("too many Answers to pack (>65535)") errTooManyAuthorities = errors.New("too many Authorities to pack (>65535)") errTooManyAdditionals = errors.New("too many Additionals to pack (>65535)") errNonCanonicalName = errors.New("name is not in canonical format (it must end with a .)") ) // Internal constants. const ( // packStartingCap is the default initial buffer size allocated during // packing. // // The starting capacity doesn't matter too much, but most DNS responses // Will be <= 512 bytes as it is the limit for DNS over UDP. packStartingCap = 512 // uint16Len is the length (in bytes) of a uint16. uint16Len = 2 // uint32Len is the length (in bytes) of a uint32. uint32Len = 4 // headerLen is the length (in bytes) of a DNS header. // // A header is comprised of 6 uint16s and no padding. headerLen = 6 * uint16Len ) type nestedError struct { // s is the current level's error message. s string // err is the nested error. err error } // nestedError implements error.Error. func (e *nestedError) Error() string { return e.s + ": " + e.err.Error() } // Header is a representation of a DNS message header. type Header struct { ID uint16 Response bool OpCode OpCode Authoritative bool Truncated bool RecursionDesired bool RecursionAvailable bool RCode RCode } func (m *Header) pack() (id uint16, bits uint16) { id = m.ID bits = uint16(m.OpCode)<<11 | uint16(m.RCode) if m.RecursionAvailable { bits |= headerBitRA } if m.RecursionDesired { bits |= headerBitRD } if m.Truncated { bits |= headerBitTC } if m.Authoritative { bits |= headerBitAA } if m.Response { bits |= headerBitQR } return } // Message is a representation of a DNS message. type Message struct { Header Questions []Question Answers []Resource Authorities []Resource Additionals []Resource } type section uint8 const ( sectionNotStarted section = iota sectionHeader sectionQuestions sectionAnswers sectionAuthorities sectionAdditionals sectionDone headerBitQR = 1 << 15 // query/response (response=1) headerBitAA = 1 << 10 // authoritative headerBitTC = 1 << 9 // truncated headerBitRD = 1 << 8 // recursion desired headerBitRA = 1 << 7 // recursion available ) var sectionNames = map[section]string{ sectionHeader: "header", sectionQuestions: "Question", sectionAnswers: "Answer", sectionAuthorities: "Authority", sectionAdditionals: "Additional", } // header is the wire format for a DNS message header. type header struct { id uint16 bits uint16 questions uint16 answers uint16 authorities uint16 additionals uint16 } func (h *header) count(sec section) uint16 { switch sec { case sectionQuestions: return h.questions case sectionAnswers: return h.answers case sectionAuthorities: return h.authorities case sectionAdditionals: return h.additionals } return 0 } func (h *header) pack(msg []byte) []byte { msg = packUint16(msg, h.id) msg = packUint16(msg, h.bits) msg = packUint16(msg, h.questions) msg = packUint16(msg, h.answers) msg = packUint16(msg, h.authorities) return packUint16(msg, h.additionals) } func (h *header) unpack(msg []byte, off int) (int, error) { newOff := off var err error if h.id, newOff, err = unpackUint16(msg, newOff); err != nil { return off, &nestedError{"id", err} } if h.bits, newOff, err = unpackUint16(msg, newOff); err != nil { return off, &nestedError{"bits", err} } if h.questions, newOff, err = unpackUint16(msg, newOff); err != nil { return off, &nestedError{"questions", err} } if h.answers, newOff, err = unpackUint16(msg, newOff); err != nil { return off, &nestedError{"answers", err} } if h.authorities, newOff, err = unpackUint16(msg, newOff); err != nil { return off, &nestedError{"authorities", err} } if h.additionals, newOff, err = unpackUint16(msg, newOff); err != nil { return off, &nestedError{"additionals", err} } return newOff, nil } func (h *header) header() Header { return Header{ ID: h.id, Response: (h.bits & headerBitQR) != 0, OpCode: OpCode(h.bits>>11) & 0xF, Authoritative: (h.bits & headerBitAA) != 0, Truncated: (h.bits & headerBitTC) != 0, RecursionDesired: (h.bits & headerBitRD) != 0, RecursionAvailable: (h.bits & headerBitRA) != 0, RCode: RCode(h.bits & 0xF), } } // A Resource is a DNS resource record. type Resource struct { Header ResourceHeader Body ResourceBody } // A ResourceBody is a DNS resource record minus the header. type ResourceBody interface { // pack packs a Resource except for its header. pack(msg []byte, compression map[string]int) ([]byte, error) // realType returns the actual type of the Resource. This is used to // fill in the header Type field. realType() Type } func (r *Resource) pack(msg []byte, compression map[string]int) ([]byte, error) { if r.Body == nil { return msg, errNilResouceBody } oldMsg := msg r.Header.Type = r.Body.realType() msg, length, err := r.Header.pack(msg, compression) if err != nil { return msg, &nestedError{"ResourceHeader", err} } preLen := len(msg) msg, err = r.Body.pack(msg, compression) if err != nil { return msg, &nestedError{"content", err} } if err := r.Header.fixLen(msg, length, preLen); err != nil { return oldMsg, err } return msg, nil } // A Parser allows incrementally parsing a DNS message. // // When parsing is started, the Header is parsed. Next, each Question can be // either parsed or skipped. Alternatively, all Questions can be skipped at // once. When all Questions have been parsed, attempting to parse Questions // will return (nil, nil) and attempting to skip Questions will return // (true, nil). After all Questions have been either parsed or skipped, all // Answers, Authorities and Additionals can be either parsed or skipped in the // same way, and each type of Resource must be fully parsed or skipped before // proceeding to the next type of Resource. // // Note that there is no requirement to fully skip or parse the message. type Parser struct { msg []byte header header section section off int index int resHeaderValid bool resHeader ResourceHeader } // Start parses the header and enables the parsing of Questions. func (p *Parser) Start(msg []byte) (Header, error) { if p.msg != nil { *p = Parser{} } p.msg = msg var err error if p.off, err = p.header.unpack(msg, 0); err != nil { return Header{}, &nestedError{"unpacking header", err} } p.section = sectionQuestions return p.header.header(), nil } func (p *Parser) checkAdvance(sec section) error { if p.section < sec { return ErrNotStarted } if p.section > sec { return ErrSectionDone } p.resHeaderValid = false if p.index == int(p.header.count(sec)) { p.index = 0 p.section++ return ErrSectionDone } return nil } func (p *Parser) resource(sec section) (Resource, error) { var r Resource var err error r.Header, err = p.resourceHeader(sec) if err != nil { return r, err } p.resHeaderValid = false r.Body, p.off, err = unpackResourceBody(p.msg, p.off, r.Header) if err != nil { return Resource{}, &nestedError{"unpacking " + sectionNames[sec], err} } p.index++ return r, nil } func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) { if p.resHeaderValid { return p.resHeader, nil } if err := p.checkAdvance(sec); err != nil { return ResourceHeader{}, err } var hdr ResourceHeader off, err := hdr.unpack(p.msg, p.off) if err != nil { return ResourceHeader{}, err } p.resHeaderValid = true p.resHeader = hdr p.off = off return hdr, nil } func (p *Parser) skipResource(sec section) error { if p.resHeaderValid { newOff := p.off + int(p.resHeader.Length) if newOff > len(p.msg) { return errResourceLen } p.off = newOff p.resHeaderValid = false p.index++ return nil } if err := p.checkAdvance(sec); err != nil { return err } var err error p.off, err = skipResource(p.msg, p.off) if err != nil { return &nestedError{"skipping: " + sectionNames[sec], err} } p.index++ return nil } // Question parses a single Question. func (p *Parser) Question() (Question, error) { if err := p.checkAdvance(sectionQuestions); err != nil { return Question{}, err } var name Name off, err := name.unpack(p.msg, p.off) if err != nil { return Question{}, &nestedError{"unpacking Question.Name", err} } typ, off, err := unpackType(p.msg, off) if err != nil { return Question{}, &nestedError{"unpacking Question.Type", err} } class, off, err := unpackClass(p.msg, off) if err != nil { return Question{}, &nestedError{"unpacking Question.Class", err} } p.off = off p.index++ return Question{name, typ, class}, nil } // AllQuestions parses all Questions. func (p *Parser) AllQuestions() ([]Question, error) { qs := make([]Question, 0, p.header.questions) for { q, err := p.Question() if err == ErrSectionDone { return qs, nil } if err != nil { return nil, err } qs = append(qs, q) } } // SkipQuestion skips a single Question. func (p *Parser) SkipQuestion() error { if err := p.checkAdvance(sectionQuestions); err != nil { return err } off, err := skipName(p.msg, p.off) if err != nil { return &nestedError{"skipping Question Name", err} } if off, err = skipType(p.msg, off); err != nil { return &nestedError{"skipping Question Type", err} } if off, err = skipClass(p.msg, off); err != nil { return &nestedError{"skipping Question Class", err} } p.off = off p.index++ return nil } // SkipAllQuestions skips all Questions. func (p *Parser) SkipAllQuestions() error { for { if err := p.SkipQuestion(); err == ErrSectionDone { return nil } else if err != nil { return err } } } // AnswerHeader parses a single Answer ResourceHeader. func (p *Parser) AnswerHeader() (ResourceHeader, error) { return p.resourceHeader(sectionAnswers) } // Answer parses a single Answer Resource. func (p *Parser) Answer() (Resource, error) { return p.resource(sectionAnswers) } // AllAnswers parses all Answer Resources. func (p *Parser) AllAnswers() ([]Resource, error) { as := make([]Resource, 0, p.header.answers) for { a, err := p.Answer() if err == ErrSectionDone { return as, nil } if err != nil { return nil, err } as = append(as, a) } } // SkipAnswer skips a single Answer Resource. func (p *Parser) SkipAnswer() error { return p.skipResource(sectionAnswers) } // SkipAllAnswers skips all Answer Resources. func (p *Parser) SkipAllAnswers() error { for { if err := p.SkipAnswer(); err == ErrSectionDone { return nil } else if err != nil { return err } } } // AuthorityHeader parses a single Authority ResourceHeader. func (p *Parser) AuthorityHeader() (ResourceHeader, error) { return p.resourceHeader(sectionAuthorities) } // Authority parses a single Authority Resource. func (p *Parser) Authority() (Resource, error) { return p.resource(sectionAuthorities) } // AllAuthorities parses all Authority Resources. func (p *Parser) AllAuthorities() ([]Resource, error) { as := make([]Resource, 0, p.header.authorities) for { a, err := p.Authority() if err == ErrSectionDone { return as, nil } if err != nil { return nil, err } as = append(as, a) } } // SkipAuthority skips a single Authority Resource. func (p *Parser) SkipAuthority() error { return p.skipResource(sectionAuthorities) } // SkipAllAuthorities skips all Authority Resources. func (p *Parser) SkipAllAuthorities() error { for { if err := p.SkipAuthority(); err == ErrSectionDone { return nil } else if err != nil { return err } } } // AdditionalHeader parses a single Additional ResourceHeader. func (p *Parser) AdditionalHeader() (ResourceHeader, error) { return p.resourceHeader(sectionAdditionals) } // Additional parses a single Additional Resource. func (p *Parser) Additional() (Resource, error) { return p.resource(sectionAdditionals) } // AllAdditionals parses all Additional Resources. func (p *Parser) AllAdditionals() ([]Resource, error) { as := make([]Resource, 0, p.header.additionals) for { a, err := p.Additional() if err == ErrSectionDone { return as, nil } if err != nil { return nil, err } as = append(as, a) } } // SkipAdditional skips a single Additional Resource. func (p *Parser) SkipAdditional() error { return p.skipResource(sectionAdditionals) } // SkipAllAdditionals skips all Additional Resources. func (p *Parser) SkipAllAdditionals() error { for { if err := p.SkipAdditional(); err == ErrSectionDone { return nil } else if err != nil { return err } } } // CNAMEResource parses a single CNAMEResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) CNAMEResource() (CNAMEResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypeCNAME { return CNAMEResource{}, ErrNotStarted } r, err := unpackCNAMEResource(p.msg, p.off) if err != nil { return CNAMEResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // MXResource parses a single MXResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) MXResource() (MXResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypeMX { return MXResource{}, ErrNotStarted } r, err := unpackMXResource(p.msg, p.off) if err != nil { return MXResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // NSResource parses a single NSResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) NSResource() (NSResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypeNS { return NSResource{}, ErrNotStarted } r, err := unpackNSResource(p.msg, p.off) if err != nil { return NSResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // PTRResource parses a single PTRResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) PTRResource() (PTRResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypePTR { return PTRResource{}, ErrNotStarted } r, err := unpackPTRResource(p.msg, p.off) if err != nil { return PTRResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // SOAResource parses a single SOAResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) SOAResource() (SOAResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypeSOA { return SOAResource{}, ErrNotStarted } r, err := unpackSOAResource(p.msg, p.off) if err != nil { return SOAResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // TXTResource parses a single TXTResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) TXTResource() (TXTResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypeTXT { return TXTResource{}, ErrNotStarted } r, err := unpackTXTResource(p.msg, p.off, p.resHeader.Length) if err != nil { return TXTResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // SRVResource parses a single SRVResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) SRVResource() (SRVResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypeSRV { return SRVResource{}, ErrNotStarted } r, err := unpackSRVResource(p.msg, p.off) if err != nil { return SRVResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // AResource parses a single AResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) AResource() (AResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypeA { return AResource{}, ErrNotStarted } r, err := unpackAResource(p.msg, p.off) if err != nil { return AResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // AAAAResource parses a single AAAAResource. // // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) AAAAResource() (AAAAResource, error) { if !p.resHeaderValid || p.resHeader.Type != TypeAAAA { return AAAAResource{}, ErrNotStarted } r, err := unpackAAAAResource(p.msg, p.off) if err != nil { return AAAAResource{}, err } p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil } // Unpack parses a full Message. func (m *Message) Unpack(msg []byte) error { var p Parser var err error if m.Header, err = p.Start(msg); err != nil { return err } if m.Questions, err = p.AllQuestions(); err != nil { return err } if m.Answers, err = p.AllAnswers(); err != nil { return err } if m.Authorities, err = p.AllAuthorities(); err != nil { return err } if m.Additionals, err = p.AllAdditionals(); err != nil { return err } return nil } // Pack packs a full Message. func (m *Message) Pack() ([]byte, error) { // Validate the lengths. It is very unlikely that anyone will try to // pack more than 65535 of any particular type, but it is possible and // we should fail gracefully. if len(m.Questions) > int(^uint16(0)) { return nil, errTooManyQuestions } if len(m.Answers) > int(^uint16(0)) { return nil, errTooManyAnswers } if len(m.Authorities) > int(^uint16(0)) { return nil, errTooManyAuthorities } if len(m.Additionals) > int(^uint16(0)) { return nil, errTooManyAdditionals } var h header h.id, h.bits = m.Header.pack() h.questions = uint16(len(m.Questions)) h.answers = uint16(len(m.Answers)) h.authorities = uint16(len(m.Authorities)) h.additionals = uint16(len(m.Additionals)) msg := make([]byte, 0, packStartingCap) msg = h.pack(msg) // RFC 1035 allows (but does not require) compression for packing. RFC // 1035 requires unpacking implementations to support compression, so // unconditionally enabling it is fine. // // DNS lookups are typically done over UDP, and RFC 1035 states that UDP // DNS packets can be a maximum of 512 bytes long. Without compression, // many DNS response packets are over this limit, so enabling // compression will help ensure compliance. compression := map[string]int{} for i := range m.Questions { var err error if msg, err = m.Questions[i].pack(msg, compression); err != nil { return nil, &nestedError{"packing Question", err} } } for i := range m.Answers { var err error if msg, err = m.Answers[i].pack(msg, compression); err != nil { return nil, &nestedError{"packing Answer", err} } } for i := range m.Authorities { var err error if msg, err = m.Authorities[i].pack(msg, compression); err != nil { return nil, &nestedError{"packing Authority", err} } } for i := range m.Additionals { var err error if msg, err = m.Additionals[i].pack(msg, compression); err != nil { return nil, &nestedError{"packing Additional", err} } } return msg, nil } // A Builder allows incrementally packing a DNS message. type Builder struct { msg []byte header header section section compression map[string]int } // Start initializes the builder. // // buf is optional (nil is fine), but if provided, Start takes ownership of buf. func (b *Builder) Start(buf []byte, h Header) { b.StartWithoutCompression(buf, h) b.compression = map[string]int{} } // StartWithoutCompression initializes the builder with compression disabled. // // This avoids compression related allocations, but can result in larger message // sizes. Be careful with this mode as it can cause messages to exceed the UDP // size limit. // // buf is optional (nil is fine), but if provided, Start takes ownership of buf. func (b *Builder) StartWithoutCompression(buf []byte, h Header) { *b = Builder{msg: buf} b.header.id, b.header.bits = h.pack() if cap(b.msg) < headerLen { b.msg = make([]byte, 0, packStartingCap) } b.msg = b.msg[:headerLen] b.section = sectionHeader } func (b *Builder) startCheck(s section) error { if b.section <= sectionNotStarted { return ErrNotStarted } if b.section > s { return ErrSectionDone } return nil } // StartQuestions prepares the builder for packing Questions. func (b *Builder) StartQuestions() error { if err := b.startCheck(sectionQuestions); err != nil { return err } b.section = sectionQuestions return nil } // StartAnswers prepares the builder for packing Answers. func (b *Builder) StartAnswers() error { if err := b.startCheck(sectionAnswers); err != nil { return err } b.section = sectionAnswers return nil } // StartAuthorities prepares the builder for packing Authorities. func (b *Builder) StartAuthorities() error { if err := b.startCheck(sectionAuthorities); err != nil { return err } b.section = sectionAuthorities return nil } // StartAdditionals prepares the builder for packing Additionals. func (b *Builder) StartAdditionals() error { if err := b.startCheck(sectionAdditionals); err != nil { return err } b.section = sectionAdditionals return nil } func (b *Builder) incrementSectionCount() error { var count *uint16 var err error switch b.section { case sectionQuestions: count = &b.header.questions err = errTooManyQuestions case sectionAnswers: count = &b.header.answers err = errTooManyAnswers case sectionAuthorities: count = &b.header.authorities err = errTooManyAuthorities case sectionAdditionals: count = &b.header.additionals err = errTooManyAdditionals } if *count == ^uint16(0) { return err } *count++ return nil } // Question adds a single Question. func (b *Builder) Question(q Question) error { if b.section < sectionQuestions { return ErrNotStarted } if b.section > sectionQuestions { return ErrSectionDone } msg, err := q.pack(b.msg, b.compression) if err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } func (b *Builder) checkResourceSection() error { if b.section < sectionAnswers { return ErrNotStarted } if b.section > sectionAdditionals { return ErrSectionDone } return nil } // CNAMEResource adds a single CNAMEResource. func (b *Builder) CNAMEResource(h ResourceHeader, r CNAMEResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"CNAMEResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // MXResource adds a single MXResource. func (b *Builder) MXResource(h ResourceHeader, r MXResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"MXResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // NSResource adds a single NSResource. func (b *Builder) NSResource(h ResourceHeader, r NSResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"NSResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // PTRResource adds a single PTRResource. func (b *Builder) PTRResource(h ResourceHeader, r PTRResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"PTRResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // SOAResource adds a single SOAResource. func (b *Builder) SOAResource(h ResourceHeader, r SOAResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"SOAResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // TXTResource adds a single TXTResource. func (b *Builder) TXTResource(h ResourceHeader, r TXTResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"TXTResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // SRVResource adds a single SRVResource. func (b *Builder) SRVResource(h ResourceHeader, r SRVResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"SRVResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // AResource adds a single AResource. func (b *Builder) AResource(h ResourceHeader, r AResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"AResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // AAAAResource adds a single AAAAResource. func (b *Builder) AAAAResource(h ResourceHeader, r AAAAResource) error { if err := b.checkResourceSection(); err != nil { return err } h.Type = r.realType() msg, length, err := h.pack(b.msg, b.compression) if err != nil { return &nestedError{"ResourceHeader", err} } preLen := len(msg) if msg, err = r.pack(msg, b.compression); err != nil { return &nestedError{"AAAAResource body", err} } if err := h.fixLen(msg, length, preLen); err != nil { return err } if err := b.incrementSectionCount(); err != nil { return err } b.msg = msg return nil } // Finish ends message building and generates a binary packet. func (b *Builder) Finish() ([]byte, error) { if b.section < sectionHeader { return nil, ErrNotStarted } b.section = sectionDone b.header.pack(b.msg[:0]) return b.msg, nil } // A ResourceHeader is the header of a DNS resource record. There are // many types of DNS resource records, but they all share the same header. type ResourceHeader struct { // Name is the domain name for which this resource record pertains. Name Name // Type is the type of DNS resource record. // // This field will be set automatically during packing. Type Type // Class is the class of network to which this DNS resource record // pertains. Class Class // TTL is the length of time (measured in seconds) which this resource // record is valid for (time to live). All Resources in a set should // have the same TTL (RFC 2181 Section 5.2). TTL uint32 // Length is the length of data in the resource record after the header. // // This field will be set automatically during packing. Length uint16 } // pack packs all of the fields in a ResourceHeader except for the length. The // length bytes are returned as a slice so they can be filled in after the rest // of the Resource has been packed. func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int) (msg []byte, length []byte, err error) { msg = oldMsg if msg, err = h.Name.pack(msg, compression); err != nil { return oldMsg, nil, &nestedError{"Name", err} } msg = packType(msg, h.Type) msg = packClass(msg, h.Class) msg = packUint32(msg, h.TTL) lenBegin := len(msg) msg = packUint16(msg, h.Length) return msg, msg[lenBegin : lenBegin+uint16Len], nil } func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) { newOff := off var err error if newOff, err = h.Name.unpack(msg, newOff); err != nil { return off, &nestedError{"Name", err} } if h.Type, newOff, err = unpackType(msg, newOff); err != nil { return off, &nestedError{"Type", err} } if h.Class, newOff, err = unpackClass(msg, newOff); err != nil { return off, &nestedError{"Class", err} } if h.TTL, newOff, err = unpackUint32(msg, newOff); err != nil { return off, &nestedError{"TTL", err} } if h.Length, newOff, err = unpackUint16(msg, newOff); err != nil { return off, &nestedError{"Length", err} } return newOff, nil } func (h *ResourceHeader) fixLen(msg []byte, length []byte, preLen int) error { conLen := len(msg) - preLen if conLen > int(^uint16(0)) { return errResTooLong } // Fill in the length now that we know how long the content is. packUint16(length[:0], uint16(conLen)) h.Length = uint16(conLen) return nil } func skipResource(msg []byte, off int) (int, error) { newOff, err := skipName(msg, off) if err != nil { return off, &nestedError{"Name", err} } if newOff, err = skipType(msg, newOff); err != nil { return off, &nestedError{"Type", err} } if newOff, err = skipClass(msg, newOff); err != nil { return off, &nestedError{"Class", err} } if newOff, err = skipUint32(msg, newOff); err != nil { return off, &nestedError{"TTL", err} } length, newOff, err := unpackUint16(msg, newOff) if err != nil { return off, &nestedError{"Length", err} } if newOff += int(length); newOff > len(msg) { return off, errResourceLen } return newOff, nil } func packUint16(msg []byte, field uint16) []byte { return append(msg, byte(field>>8), byte(field)) } func unpackUint16(msg []byte, off int) (uint16, int, error) { if off+uint16Len > len(msg) { return 0, off, errBaseLen } return uint16(msg[off])<<8 | uint16(msg[off+1]), off + uint16Len, nil } func skipUint16(msg []byte, off int) (int, error) { if off+uint16Len > len(msg) { return off, errBaseLen } return off + uint16Len, nil } func packType(msg []byte, field Type) []byte { return packUint16(msg, uint16(field)) } func unpackType(msg []byte, off int) (Type, int, error) { t, o, err := unpackUint16(msg, off) return Type(t), o, err } func skipType(msg []byte, off int) (int, error) { return skipUint16(msg, off) } func packClass(msg []byte, field Class) []byte { return packUint16(msg, uint16(field)) } func unpackClass(msg []byte, off int) (Class, int, error) { c, o, err := unpackUint16(msg, off) return Class(c), o, err } func skipClass(msg []byte, off int) (int, error) { return skipUint16(msg, off) } func packUint32(msg []byte, field uint32) []byte { return append( msg, byte(field>>24), byte(field>>16), byte(field>>8), byte(field), ) } func unpackUint32(msg []byte, off int) (uint32, int, error) { if off+uint32Len > len(msg) { return 0, off, errBaseLen } v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3]) return v, off + uint32Len, nil } func skipUint32(msg []byte, off int) (int, error) { if off+uint32Len > len(msg) { return off, errBaseLen } return off + uint32Len, nil } func packText(msg []byte, field string) []byte { for len(field) > 0 { l := len(field) if l > 255 { l = 255 } msg = append(msg, byte(l)) msg = append(msg, field[:l]...) field = field[l:] } return msg } func unpackText(msg []byte, off int) (string, int, error) { if off >= len(msg) { return "", off, errBaseLen } beginOff := off + 1 endOff := beginOff + int(msg[off]) if endOff > len(msg) { return "", off, errCalcLen } return string(msg[beginOff:endOff]), endOff, nil } func skipText(msg []byte, off int) (int, error) { if off >= len(msg) { return off, errBaseLen } endOff := off + 1 + int(msg[off]) if endOff > len(msg) { return off, errCalcLen } return endOff, nil } func packBytes(msg []byte, field []byte) []byte { return append(msg, field...) } func unpackBytes(msg []byte, off int, field []byte) (int, error) { newOff := off + len(field) if newOff > len(msg) { return off, errBaseLen } copy(field, msg[off:newOff]) return newOff, nil } func skipBytes(msg []byte, off int, field []byte) (int, error) { newOff := off + len(field) if newOff > len(msg) { return off, errBaseLen } return newOff, nil } const nameLen = 255 // A Name is a non-encoded domain name. It is used instead of strings to avoid // allocations. type Name struct { Data [nameLen]byte Length uint8 } // NewName creates a new Name from a string. func NewName(name string) (Name, error) { if len([]byte(name)) > nameLen { return Name{}, errCalcLen } n := Name{Length: uint8(len(name))} copy(n.Data[:], []byte(name)) return n, nil } func (n Name) String() string { return string(n.Data[:n.Length]) } // pack packs a domain name. // // Domain names are a sequence of counted strings split at the dots. They end // with a zero-length string. Compression can be used to reuse domain suffixes. // // The compression map will be updated with new domain suffixes. If compression // is nil, compression will not be used. func (n *Name) pack(msg []byte, compression map[string]int) ([]byte, error) { oldMsg := msg // Add a trailing dot to canonicalize name. if n.Length == 0 || n.Data[n.Length-1] != '.' { return oldMsg, errNonCanonicalName } // Allow root domain. if n.Data[0] == '.' && n.Length == 1 { return append(msg, 0), nil } // Emit sequence of counted strings, chopping at dots. for i, begin := 0, 0; i < int(n.Length); i++ { // Check for the end of the segment. if n.Data[i] == '.' { // The two most significant bits have special meaning. // It isn't allowed for segments to be long enough to // need them. if i-begin >= 1<<6 { return oldMsg, errSegTooLong } // Segments must have a non-zero length. if i-begin == 0 { return oldMsg, errZeroSegLen } msg = append(msg, byte(i-begin)) for j := begin; j < i; j++ { msg = append(msg, n.Data[j]) } begin = i + 1 continue } // We can only compress domain suffixes starting with a new // segment. A pointer is two bytes with the two most significant // bits set to 1 to indicate that it is a pointer. if (i == 0 || n.Data[i-1] == '.') && compression != nil { if ptr, ok := compression[string(n.Data[i:])]; ok { // Hit. Emit a pointer instead of the rest of // the domain. return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil } // Miss. Add the suffix to the compression table if the // offset can be stored in the available 14 bytes. if len(msg) <= int(^uint16(0)>>2) { compression[string(n.Data[i:])] = len(msg) } } } return append(msg, 0), nil } // unpack unpacks a domain name. func (n *Name) unpack(msg []byte, off int) (int, error) { // currOff is the current working offset. currOff := off // newOff is the offset where the next record will start. Pointers lead // to data that belongs to other names and thus doesn't count towards to // the usage of this name. newOff := off // ptr is the number of pointers followed. var ptr int // Name is a slice representation of the name data. name := n.Data[:0] Loop: for { if currOff >= len(msg) { return off, errBaseLen } c := int(msg[currOff]) currOff++ switch c & 0xC0 { case 0x00: // String segment if c == 0x00 { // A zero length signals the end of the name. break Loop } endOff := currOff + c if endOff > len(msg) { return off, errCalcLen } name = append(name, msg[currOff:endOff]...) name = append(name, '.') currOff = endOff case 0xC0: // Pointer if currOff >= len(msg) { return off, errInvalidPtr } c1 := msg[currOff] currOff++ if ptr == 0 { newOff = currOff } // Don't follow too many pointers, maybe there's a loop. if ptr++; ptr > 10 { return off, errTooManyPtr } currOff = (c^0xC0)<<8 | int(c1) default: // Prefixes 0x80 and 0x40 are reserved. return off, errReserved } } if len(name) == 0 { name = append(name, '.') } if len(name) > len(n.Data) { return off, errCalcLen } n.Length = uint8(len(name)) if ptr == 0 { newOff = currOff } return newOff, nil } func skipName(msg []byte, off int) (int, error) { // newOff is the offset where the next record will start. Pointers lead // to data that belongs to other names and thus doesn't count towards to // the usage of this name. newOff := off Loop: for { if newOff >= len(msg) { return off, errBaseLen } c := int(msg[newOff]) newOff++ switch c & 0xC0 { case 0x00: if c == 0x00 { // A zero length signals the end of the name. break Loop } // literal string newOff += c if newOff > len(msg) { return off, errCalcLen } case 0xC0: // Pointer to somewhere else in msg. // Pointers are two bytes. newOff++ // Don't follow the pointer as the data here has ended. break Loop default: // Prefixes 0x80 and 0x40 are reserved. return off, errReserved } } return newOff, nil } // A Question is a DNS query. type Question struct { Name Name Type Type Class Class } func (q *Question) pack(msg []byte, compression map[string]int) ([]byte, error) { msg, err := q.Name.pack(msg, compression) if err != nil { return msg, &nestedError{"Name", err} } msg = packType(msg, q.Type) return packClass(msg, q.Class), nil } func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody, int, error) { var ( r ResourceBody err error name string ) switch hdr.Type { case TypeA: var rb AResource rb, err = unpackAResource(msg, off) r = &rb name = "A" case TypeNS: var rb NSResource rb, err = unpackNSResource(msg, off) r = &rb name = "NS" case TypeCNAME: var rb CNAMEResource rb, err = unpackCNAMEResource(msg, off) r = &rb name = "CNAME" case TypeSOA: var rb SOAResource rb, err = unpackSOAResource(msg, off) r = &rb name = "SOA" case TypePTR: var rb PTRResource rb, err = unpackPTRResource(msg, off) r = &rb name = "PTR" case TypeMX: var rb MXResource rb, err = unpackMXResource(msg, off) r = &rb name = "MX" case TypeTXT: var rb TXTResource rb, err = unpackTXTResource(msg, off, hdr.Length) r = &rb name = "TXT" case TypeAAAA: var rb AAAAResource rb, err = unpackAAAAResource(msg, off) r = &rb name = "AAAA" case TypeSRV: var rb SRVResource rb, err = unpackSRVResource(msg, off) r = &rb name = "SRV" } if err != nil { return nil, off, &nestedError{name + " record", err} } if r == nil { return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0')) } return r, off + int(hdr.Length), nil } // A CNAMEResource is a CNAME Resource record. type CNAMEResource struct { CNAME Name } func (r *CNAMEResource) realType() Type { return TypeCNAME } func (r *CNAMEResource) pack(msg []byte, compression map[string]int) ([]byte, error) { return r.CNAME.pack(msg, compression) } func unpackCNAMEResource(msg []byte, off int) (CNAMEResource, error) { var cname Name if _, err := cname.unpack(msg, off); err != nil { return CNAMEResource{}, err } return CNAMEResource{cname}, nil } // An MXResource is an MX Resource record. type MXResource struct { Pref uint16 MX Name } func (r *MXResource) realType() Type { return TypeMX } func (r *MXResource) pack(msg []byte, compression map[string]int) ([]byte, error) { oldMsg := msg msg = packUint16(msg, r.Pref) msg, err := r.MX.pack(msg, compression) if err != nil { return oldMsg, &nestedError{"MXResource.MX", err} } return msg, nil } func unpackMXResource(msg []byte, off int) (MXResource, error) { pref, off, err := unpackUint16(msg, off) if err != nil { return MXResource{}, &nestedError{"Pref", err} } var mx Name if _, err := mx.unpack(msg, off); err != nil { return MXResource{}, &nestedError{"MX", err} } return MXResource{pref, mx}, nil } // An NSResource is an NS Resource record. type NSResource struct { NS Name } func (r *NSResource) realType() Type { return TypeNS } func (r *NSResource) pack(msg []byte, compression map[string]int) ([]byte, error) { return r.NS.pack(msg, compression) } func unpackNSResource(msg []byte, off int) (NSResource, error) { var ns Name if _, err := ns.unpack(msg, off); err != nil { return NSResource{}, err } return NSResource{ns}, nil } // A PTRResource is a PTR Resource record. type PTRResource struct { PTR Name } func (r *PTRResource) realType() Type { return TypePTR } func (r *PTRResource) pack(msg []byte, compression map[string]int) ([]byte, error) { return r.PTR.pack(msg, compression) } func unpackPTRResource(msg []byte, off int) (PTRResource, error) { var ptr Name if _, err := ptr.unpack(msg, off); err != nil { return PTRResource{}, err } return PTRResource{ptr}, nil } // An SOAResource is an SOA Resource record. type SOAResource struct { NS Name MBox Name Serial uint32 Refresh uint32 Retry uint32 Expire uint32 // MinTTL the is the default TTL of Resources records which did not // contain a TTL value and the TTL of negative responses. (RFC 2308 // Section 4) MinTTL uint32 } func (r *SOAResource) realType() Type { return TypeSOA } func (r *SOAResource) pack(msg []byte, compression map[string]int) ([]byte, error) { oldMsg := msg msg, err := r.NS.pack(msg, compression) if err != nil { return oldMsg, &nestedError{"SOAResource.NS", err} } msg, err = r.MBox.pack(msg, compression) if err != nil { return oldMsg, &nestedError{"SOAResource.MBox", err} } msg = packUint32(msg, r.Serial) msg = packUint32(msg, r.Refresh) msg = packUint32(msg, r.Retry) msg = packUint32(msg, r.Expire) return packUint32(msg, r.MinTTL), nil } func unpackSOAResource(msg []byte, off int) (SOAResource, error) { var ns Name off, err := ns.unpack(msg, off) if err != nil { return SOAResource{}, &nestedError{"NS", err} } var mbox Name if off, err = mbox.unpack(msg, off); err != nil { return SOAResource{}, &nestedError{"MBox", err} } serial, off, err := unpackUint32(msg, off) if err != nil { return SOAResource{}, &nestedError{"Serial", err} } refresh, off, err := unpackUint32(msg, off) if err != nil { return SOAResource{}, &nestedError{"Refresh", err} } retry, off, err := unpackUint32(msg, off) if err != nil { return SOAResource{}, &nestedError{"Retry", err} } expire, off, err := unpackUint32(msg, off) if err != nil { return SOAResource{}, &nestedError{"Expire", err} } minTTL, _, err := unpackUint32(msg, off) if err != nil { return SOAResource{}, &nestedError{"MinTTL", err} } return SOAResource{ns, mbox, serial, refresh, retry, expire, minTTL}, nil } // A TXTResource is a TXT Resource record. type TXTResource struct { Txt string // Not a domain name. } func (r *TXTResource) realType() Type { return TypeTXT } func (r *TXTResource) pack(msg []byte, compression map[string]int) ([]byte, error) { return packText(msg, r.Txt), nil } func unpackTXTResource(msg []byte, off int, length uint16) (TXTResource, error) { var txt string for n := uint16(0); n < length; { var t string var err error if t, off, err = unpackText(msg, off); err != nil { return TXTResource{}, &nestedError{"text", err} } // Check if we got too many bytes. if length-n < uint16(len(t))+1 { return TXTResource{}, errCalcLen } n += uint16(len(t)) + 1 txt += t } return TXTResource{txt}, nil } // An SRVResource is an SRV Resource record. type SRVResource struct { Priority uint16 Weight uint16 Port uint16 Target Name // Not compressed as per RFC 2782. } func (r *SRVResource) realType() Type { return TypeSRV } func (r *SRVResource) pack(msg []byte, compression map[string]int) ([]byte, error) { oldMsg := msg msg = packUint16(msg, r.Priority) msg = packUint16(msg, r.Weight) msg = packUint16(msg, r.Port) msg, err := r.Target.pack(msg, nil) if err != nil { return oldMsg, &nestedError{"SRVResource.Target", err} } return msg, nil } func unpackSRVResource(msg []byte, off int) (SRVResource, error) { priority, off, err := unpackUint16(msg, off) if err != nil { return SRVResource{}, &nestedError{"Priority", err} } weight, off, err := unpackUint16(msg, off) if err != nil { return SRVResource{}, &nestedError{"Weight", err} } port, off, err := unpackUint16(msg, off) if err != nil { return SRVResource{}, &nestedError{"Port", err} } var target Name if _, err := target.unpack(msg, off); err != nil { return SRVResource{}, &nestedError{"Target", err} } return SRVResource{priority, weight, port, target}, nil } // An AResource is an A Resource record. type AResource struct { A [4]byte } func (r *AResource) realType() Type { return TypeA } func (r *AResource) pack(msg []byte, compression map[string]int) ([]byte, error) { return packBytes(msg, r.A[:]), nil } func unpackAResource(msg []byte, off int) (AResource, error) { var a [4]byte if _, err := unpackBytes(msg, off, a[:]); err != nil { return AResource{}, err } return AResource{a}, nil } // An AAAAResource is an AAAA Resource record. type AAAAResource struct { AAAA [16]byte } func (r *AAAAResource) realType() Type { return TypeAAAA } func (r *AAAAResource) pack(msg []byte, compression map[string]int) ([]byte, error) { return packBytes(msg, r.AAAA[:]), nil } func unpackAAAAResource(msg []byte, off int) (AAAAResource, error) { var aaaa [16]byte if _, err := unpackBytes(msg, off, aaaa[:]); err != nil { return AAAAResource{}, err } return AAAAResource{aaaa}, nil } ����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/dns/dnsmessage/example_test.go���������������������������������0000644�0610621�0607500�00000005056�13172163402�026257� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package dnsmessage_test import ( "fmt" "net" "strings" "golang.org/x/net/dns/dnsmessage" ) func mustNewName(name string) dnsmessage.Name { n, err := dnsmessage.NewName(name) if err != nil { panic(err) } return n } func ExampleParser() { msg := dnsmessage.Message{ Header: dnsmessage.Header{Response: true, Authoritative: true}, Questions: []dnsmessage.Question{ { Name: mustNewName("foo.bar.example.com."), Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, }, { Name: mustNewName("bar.example.com."), Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, }, }, Answers: []dnsmessage.Resource{ { dnsmessage.ResourceHeader{ Name: mustNewName("foo.bar.example.com."), Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, }, &dnsmessage.AResource{[4]byte{127, 0, 0, 1}}, }, { dnsmessage.ResourceHeader{ Name: mustNewName("bar.example.com."), Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, }, &dnsmessage.AResource{[4]byte{127, 0, 0, 2}}, }, }, } buf, err := msg.Pack() if err != nil { panic(err) } wantName := "bar.example.com." var p dnsmessage.Parser if _, err := p.Start(buf); err != nil { panic(err) } for { q, err := p.Question() if err == dnsmessage.ErrSectionDone { break } if err != nil { panic(err) } if q.Name.String() != wantName { continue } fmt.Println("Found question for name", wantName) if err := p.SkipAllQuestions(); err != nil { panic(err) } break } var gotIPs []net.IP for { h, err := p.AnswerHeader() if err == dnsmessage.ErrSectionDone { break } if err != nil { panic(err) } if (h.Type != dnsmessage.TypeA && h.Type != dnsmessage.TypeAAAA) || h.Class != dnsmessage.ClassINET { continue } if !strings.EqualFold(h.Name.String(), wantName) { if err := p.SkipAnswer(); err != nil { panic(err) } continue } switch h.Type { case dnsmessage.TypeA: r, err := p.AResource() if err != nil { panic(err) } gotIPs = append(gotIPs, r.A[:]) case dnsmessage.TypeAAAA: r, err := p.AAAAResource() if err != nil { panic(err) } gotIPs = append(gotIPs, r.AAAA[:]) } } fmt.Printf("Found A/AAAA records for name %s: %v\n", wantName, gotIPs) // Output: // Found question for name bar.example.com. // Found A/AAAA records for name bar.example.com.: [127.0.0.2] } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/dict/����������������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�021236� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/dict/dict.go���������������������������������������������������0000644�0610621�0607500�00000010753�13172163402�022516� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package dict implements the Dictionary Server Protocol // as defined in RFC 2229. package dict // import "golang.org/x/net/dict" import ( "net/textproto" "strconv" "strings" ) // A Client represents a client connection to a dictionary server. type Client struct { text *textproto.Conn } // Dial returns a new client connected to a dictionary server at // addr on the given network. func Dial(network, addr string) (*Client, error) { text, err := textproto.Dial(network, addr) if err != nil { return nil, err } _, _, err = text.ReadCodeLine(220) if err != nil { text.Close() return nil, err } return &Client{text: text}, nil } // Close closes the connection to the dictionary server. func (c *Client) Close() error { return c.text.Close() } // A Dict represents a dictionary available on the server. type Dict struct { Name string // short name of dictionary Desc string // long description } // Dicts returns a list of the dictionaries available on the server. func (c *Client) Dicts() ([]Dict, error) { id, err := c.text.Cmd("SHOW DB") if err != nil { return nil, err } c.text.StartResponse(id) defer c.text.EndResponse(id) _, _, err = c.text.ReadCodeLine(110) if err != nil { return nil, err } lines, err := c.text.ReadDotLines() if err != nil { return nil, err } _, _, err = c.text.ReadCodeLine(250) dicts := make([]Dict, len(lines)) for i := range dicts { d := &dicts[i] a, _ := fields(lines[i]) if len(a) < 2 { return nil, textproto.ProtocolError("invalid dictionary: " + lines[i]) } d.Name = a[0] d.Desc = a[1] } return dicts, err } // A Defn represents a definition. type Defn struct { Dict Dict // Dict where definition was found Word string // Word being defined Text []byte // Definition text, typically multiple lines } // Define requests the definition of the given word. // The argument dict names the dictionary to use, // the Name field of a Dict returned by Dicts. // // The special dictionary name "*" means to look in all the // server's dictionaries. // The special dictionary name "!" means to look in all the // server's dictionaries in turn, stopping after finding the word // in one of them. func (c *Client) Define(dict, word string) ([]*Defn, error) { id, err := c.text.Cmd("DEFINE %s %q", dict, word) if err != nil { return nil, err } c.text.StartResponse(id) defer c.text.EndResponse(id) _, line, err := c.text.ReadCodeLine(150) if err != nil { return nil, err } a, _ := fields(line) if len(a) < 1 { return nil, textproto.ProtocolError("malformed response: " + line) } n, err := strconv.Atoi(a[0]) if err != nil { return nil, textproto.ProtocolError("invalid definition count: " + a[0]) } def := make([]*Defn, n) for i := 0; i < n; i++ { _, line, err = c.text.ReadCodeLine(151) if err != nil { return nil, err } a, _ := fields(line) if len(a) < 3 { // skip it, to keep protocol in sync i-- n-- def = def[0:n] continue } d := &Defn{Word: a[0], Dict: Dict{a[1], a[2]}} d.Text, err = c.text.ReadDotBytes() if err != nil { return nil, err } def[i] = d } _, _, err = c.text.ReadCodeLine(250) return def, err } // Fields returns the fields in s. // Fields are space separated unquoted words // or quoted with single or double quote. func fields(s string) ([]string, error) { var v []string i := 0 for { for i < len(s) && (s[i] == ' ' || s[i] == '\t') { i++ } if i >= len(s) { break } if s[i] == '"' || s[i] == '\'' { q := s[i] // quoted string var j int for j = i + 1; ; j++ { if j >= len(s) { return nil, textproto.ProtocolError("malformed quoted string") } if s[j] == '\\' { j++ continue } if s[j] == q { j++ break } } v = append(v, unquote(s[i+1:j-1])) i = j } else { // atom var j int for j = i; j < len(s); j++ { if s[j] == ' ' || s[j] == '\t' || s[j] == '\\' || s[j] == '"' || s[j] == '\'' { break } } v = append(v, s[i:j]) i = j } if i < len(s) { c := s[i] if c != ' ' && c != '\t' { return nil, textproto.ProtocolError("quotes not on word boundaries") } } } return v, nil } func unquote(s string) string { if strings.Index(s, "\\") < 0 { return s } b := []byte(s) w := 0 for r := 0; r < len(b); r++ { c := b[r] if c == '\\' { r++ c = b[r] } b[w] = c w++ } return string(b[0:w]) } ���������������������lxd-2.0.11/dist/src/golang.org/x/net/context/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�021777� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/withtimeout_test.go������������������������������������0000644�0610621�0607500�00000001476�13172163402�025757� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package context_test import ( "fmt" "time" "golang.org/x/net/context" ) // This example passes a context with a timeout to tell a blocking function that // it should abandon its work after the timeout elapses. func ExampleWithTimeout() { // Pass a context with a timeout to tell a blocking function that it // should abandon its work after the timeout elapses. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() select { case <-time.After(1 * time.Second): fmt.Println("overslept") case <-ctx.Done(): fmt.Println(ctx.Err()) // prints "context deadline exceeded" } // Output: // context deadline exceeded } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/pre_go19.go��������������������������������������������0000644�0610621�0607500�00000007717�13172163402�023767� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 package context import "time" // A Context carries a deadline, a cancelation signal, and other values across // API boundaries. // // Context's methods may be called by multiple goroutines simultaneously. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // // WithCancel arranges for Done to be closed when cancel is called; // WithDeadline arranges for Done to be closed when the deadline // expires; WithTimeout arranges for Done to be closed when the timeout // elapses. // // Done is provided for use in select statements: // // // Stream generates values with DoSomething and sends them to out // // until DoSomething returns an error or ctx.Done is closed. // func Stream(ctx context.Context, out chan<- Value) error { // for { // v, err := DoSomething(ctx) // if err != nil { // return err // } // select { // case <-ctx.Done(): // return ctx.Err() // case out <- v: // } // } // } // // See http://blog.golang.org/pipelines for more examples of how to use // a Done channel for cancelation. Done() <-chan struct{} // Err returns a non-nil error value after Done is closed. Err returns // Canceled if the context was canceled or DeadlineExceeded if the // context's deadline passed. No other values for Err are defined. // After Done is closed, successive calls to Err return the same value. Err() error // Value returns the value associated with this context for key, or nil // if no value is associated with key. Successive calls to Value with // the same key returns the same result. // // Use context values only for request-scoped data that transits // processes and API boundaries, not for passing optional parameters to // functions. // // A key identifies a specific value in a Context. Functions that wish // to store values in Context typically allocate a key in a global // variable then use that key as the argument to context.WithValue and // Context.Value. A key can be any type that supports equality; // packages should define keys as an unexported type to avoid // collisions. // // Packages that define a Context key should provide type-safe accessors // for the values stores using that key: // // // Package user defines a User type that's stored in Contexts. // package user // // import "golang.org/x/net/context" // // // User is the type of value stored in the Contexts. // type User struct {...} // // // key is an unexported type for keys defined in this package. // // This prevents collisions with keys defined in other packages. // type key int // // // userKey is the key for user.User values in Contexts. It is // // unexported; clients use user.NewContext and user.FromContext // // instead of using this key directly. // var userKey key = 0 // // // NewContext returns a new Context that carries value u. // func NewContext(ctx context.Context, u *User) context.Context { // return context.WithValue(ctx, userKey, u) // } // // // FromContext returns the User value stored in ctx, if any. // func FromContext(ctx context.Context) (*User, bool) { // u, ok := ctx.Value(userKey).(*User) // return u, ok // } Value(key interface{}) interface{} } // A CancelFunc tells an operation to abandon its work. // A CancelFunc does not wait for the work to stop. // After the first call, subsequent calls to a CancelFunc do nothing. type CancelFunc func() �������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/pre_go17.go��������������������������������������������0000644�0610621�0607500�00000017673�13172163402�023767� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package context import ( "errors" "fmt" "sync" "time" ) // An emptyCtx is never canceled, has no values, and has no deadline. It is not // struct{}, since vars of this type must have distinct addresses. type emptyCtx int func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { return } func (*emptyCtx) Done() <-chan struct{} { return nil } func (*emptyCtx) Err() error { return nil } func (*emptyCtx) Value(key interface{}) interface{} { return nil } func (e *emptyCtx) String() string { switch e { case background: return "context.Background" case todo: return "context.TODO" } return "unknown empty Context" } var ( background = new(emptyCtx) todo = new(emptyCtx) ) // Canceled is the error returned by Context.Err when the context is canceled. var Canceled = errors.New("context canceled") // DeadlineExceeded is the error returned by Context.Err when the context's // deadline passes. var DeadlineExceeded = errors.New("context deadline exceeded") // WithCancel returns a copy of parent with a new Done channel. The returned // context's Done channel is closed when the returned cancel function is called // or when the parent context's Done channel is closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { c := newCancelCtx(parent) propagateCancel(parent, c) return c, func() { c.cancel(true, Canceled) } } // newCancelCtx returns an initialized cancelCtx. func newCancelCtx(parent Context) *cancelCtx { return &cancelCtx{ Context: parent, done: make(chan struct{}), } } // propagateCancel arranges for child to be canceled when parent is. func propagateCancel(parent Context, child canceler) { if parent.Done() == nil { return // parent is never canceled } if p, ok := parentCancelCtx(parent); ok { p.mu.Lock() if p.err != nil { // parent has already been canceled child.cancel(false, p.err) } else { if p.children == nil { p.children = make(map[canceler]bool) } p.children[child] = true } p.mu.Unlock() } else { go func() { select { case <-parent.Done(): child.cancel(false, parent.Err()) case <-child.Done(): } }() } } // parentCancelCtx follows a chain of parent references until it finds a // *cancelCtx. This function understands how each of the concrete types in this // package represents its parent. func parentCancelCtx(parent Context) (*cancelCtx, bool) { for { switch c := parent.(type) { case *cancelCtx: return c, true case *timerCtx: return c.cancelCtx, true case *valueCtx: parent = c.Context default: return nil, false } } } // removeChild removes a context from its parent. func removeChild(parent Context, child canceler) { p, ok := parentCancelCtx(parent) if !ok { return } p.mu.Lock() if p.children != nil { delete(p.children, child) } p.mu.Unlock() } // A canceler is a context type that can be canceled directly. The // implementations are *cancelCtx and *timerCtx. type canceler interface { cancel(removeFromParent bool, err error) Done() <-chan struct{} } // A cancelCtx can be canceled. When canceled, it also cancels any children // that implement canceler. type cancelCtx struct { Context done chan struct{} // closed by the first cancel call. mu sync.Mutex children map[canceler]bool // set to nil by the first cancel call err error // set to non-nil by the first cancel call } func (c *cancelCtx) Done() <-chan struct{} { return c.done } func (c *cancelCtx) Err() error { c.mu.Lock() defer c.mu.Unlock() return c.err } func (c *cancelCtx) String() string { return fmt.Sprintf("%v.WithCancel", c.Context) } // cancel closes c.done, cancels each of c's children, and, if // removeFromParent is true, removes c from its parent's children. func (c *cancelCtx) cancel(removeFromParent bool, err error) { if err == nil { panic("context: internal error: missing cancel error") } c.mu.Lock() if c.err != nil { c.mu.Unlock() return // already canceled } c.err = err close(c.done) for child := range c.children { // NOTE: acquiring the child's lock while holding parent's lock. child.cancel(false, err) } c.children = nil c.mu.Unlock() if removeFromParent { removeChild(c.Context, c) } } // WithDeadline returns a copy of the parent context with the deadline adjusted // to be no later than d. If the parent's deadline is already earlier than d, // WithDeadline(parent, d) is semantically equivalent to parent. The returned // context's Done channel is closed when the deadline expires, when the returned // cancel function is called, or when the parent context's Done channel is // closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { // The current deadline is already sooner than the new one. return WithCancel(parent) } c := &timerCtx{ cancelCtx: newCancelCtx(parent), deadline: deadline, } propagateCancel(parent, c) d := deadline.Sub(time.Now()) if d <= 0 { c.cancel(true, DeadlineExceeded) // deadline has already passed return c, func() { c.cancel(true, Canceled) } } c.mu.Lock() defer c.mu.Unlock() if c.err == nil { c.timer = time.AfterFunc(d, func() { c.cancel(true, DeadlineExceeded) }) } return c, func() { c.cancel(true, Canceled) } } // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to // implement Done and Err. It implements cancel by stopping its timer then // delegating to cancelCtx.cancel. type timerCtx struct { *cancelCtx timer *time.Timer // Under cancelCtx.mu. deadline time.Time } func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { return c.deadline, true } func (c *timerCtx) String() string { return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) } func (c *timerCtx) cancel(removeFromParent bool, err error) { c.cancelCtx.cancel(false, err) if removeFromParent { // Remove this timerCtx from its parent cancelCtx's children. removeChild(c.cancelCtx.Context, c) } c.mu.Lock() if c.timer != nil { c.timer.Stop() c.timer = nil } c.mu.Unlock() } // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete: // // func slowOperationWithTimeout(ctx context.Context) (Result, error) { // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) // defer cancel() // releases resources if slowOperation completes before timeout elapses // return slowOperation(ctx) // } func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { return WithDeadline(parent, time.Now().Add(timeout)) } // WithValue returns a copy of parent in which the value associated with key is // val. // // Use context Values only for request-scoped data that transits processes and // APIs, not for passing optional parameters to functions. func WithValue(parent Context, key interface{}, val interface{}) Context { return &valueCtx{parent, key, val} } // A valueCtx carries a key-value pair. It implements Value for that key and // delegates all other calls to the embedded Context. type valueCtx struct { Context key, val interface{} } func (c *valueCtx) String() string { return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) } func (c *valueCtx) Value(key interface{}) interface{} { if c.key == key { return c.val } return c.Context.Value(key) } ���������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/go19.go������������������������������������������������0000644�0610621�0607500�00000001246�13172163402�023110� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package context import "context" // standard library's context, as of Go 1.7 // A Context carries a deadline, a cancelation signal, and other values across // API boundaries. // // Context's methods may be called by multiple goroutines simultaneously. type Context = context.Context // A CancelFunc tells an operation to abandon its work. // A CancelFunc does not wait for the work to stop. // After the first call, subsequent calls to a CancelFunc do nothing. type CancelFunc = context.CancelFunc ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/go17.go������������������������������������������������0000644�0610621�0607500�00000005456�13172163402�023115� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package context import ( "context" // standard library's context, as of Go 1.7 "time" ) var ( todo = context.TODO() background = context.Background() ) // Canceled is the error returned by Context.Err when the context is canceled. var Canceled = context.Canceled // DeadlineExceeded is the error returned by Context.Err when the context's // deadline passes. var DeadlineExceeded = context.DeadlineExceeded // WithCancel returns a copy of parent with a new Done channel. The returned // context's Done channel is closed when the returned cancel function is called // or when the parent context's Done channel is closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { ctx, f := context.WithCancel(parent) return ctx, CancelFunc(f) } // WithDeadline returns a copy of the parent context with the deadline adjusted // to be no later than d. If the parent's deadline is already earlier than d, // WithDeadline(parent, d) is semantically equivalent to parent. The returned // context's Done channel is closed when the deadline expires, when the returned // cancel function is called, or when the parent context's Done channel is // closed, whichever happens first. // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { ctx, f := context.WithDeadline(parent, deadline) return ctx, CancelFunc(f) } // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). // // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this Context complete: // // func slowOperationWithTimeout(ctx context.Context) (Result, error) { // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) // defer cancel() // releases resources if slowOperation completes before timeout elapses // return slowOperation(ctx) // } func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { return WithDeadline(parent, time.Now().Add(timeout)) } // WithValue returns a copy of parent in which the value associated with key is // val. // // Use context Values only for request-scoped data that transits processes and // APIs, not for passing optional parameters to functions. func WithValue(parent Context, key interface{}, val interface{}) Context { return context.WithValue(parent, key, val) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/ctxhttp/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163402�023475� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go��������������������������������0000644�0610621�0607500�00000004422�13172163402�026563� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !plan9 package ctxhttp import ( "io" "io/ioutil" "net/http" "net/http/httptest" "testing" "time" "golang.org/x/net/context" ) const ( requestDuration = 100 * time.Millisecond requestBody = "ok" ) func okHandler(w http.ResponseWriter, r *http.Request) { time.Sleep(requestDuration) io.WriteString(w, requestBody) } func TestNoTimeout(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(okHandler)) defer ts.Close() ctx := context.Background() res, err := Get(ctx, nil, ts.URL) if err != nil { t.Fatal(err) } defer res.Body.Close() slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } if string(slurp) != requestBody { t.Errorf("body = %q; want %q", slurp, requestBody) } } func TestCancelBeforeHeaders(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) blockServer := make(chan struct{}) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cancel() <-blockServer io.WriteString(w, requestBody) })) defer ts.Close() defer close(blockServer) res, err := Get(ctx, nil, ts.URL) if err == nil { res.Body.Close() t.Fatal("Get returned unexpected nil error") } if err != context.Canceled { t.Errorf("err = %v; want %v", err, context.Canceled) } } func TestCancelAfterHangingRequest(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.(http.Flusher).Flush() <-w.(http.CloseNotifier).CloseNotify() })) defer ts.Close() ctx, cancel := context.WithCancel(context.Background()) resp, err := Get(ctx, nil, ts.URL) if err != nil { t.Fatalf("unexpected error in Get: %v", err) } // Cancel befer reading the body. // Reading Request.Body should fail, since the request was // canceled before anything was written. cancel() done := make(chan struct{}) go func() { b, err := ioutil.ReadAll(resp.Body) if len(b) != 0 || err == nil { t.Errorf(`Read got (%q, %v); want ("", error)`, b, err) } close(done) }() select { case <-time.After(1 * time.Second): t.Errorf("Test timed out") case <-done: } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go��������������������������0000644�0610621�0607500�00000003507�13172163402�027604� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !plan9,!go1.7 package ctxhttp import ( "net" "net/http" "net/http/httptest" "sync" "testing" "time" "golang.org/x/net/context" ) // golang.org/issue/14065 func TestClosesResponseBodyOnCancel(t *testing.T) { defer func() { testHookContextDoneBeforeHeaders = nop }() defer func() { testHookDoReturned = nop }() defer func() { testHookDidBodyClose = nop }() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) defer ts.Close() ctx, cancel := context.WithCancel(context.Background()) // closed when Do enters select case <-ctx.Done() enteredDonePath := make(chan struct{}) testHookContextDoneBeforeHeaders = func() { close(enteredDonePath) } testHookDoReturned = func() { // We now have the result (the Flush'd headers) at least, // so we can cancel the request. cancel() // But block the client.Do goroutine from sending // until Do enters into the <-ctx.Done() path, since // otherwise if both channels are readable, select // picks a random one. <-enteredDonePath } sawBodyClose := make(chan struct{}) testHookDidBodyClose = func() { close(sawBodyClose) } tr := &http.Transport{} defer tr.CloseIdleConnections() c := &http.Client{Transport: tr} req, _ := http.NewRequest("GET", ts.URL, nil) _, doErr := Do(ctx, c, req) select { case <-sawBodyClose: case <-time.After(5 * time.Second): t.Fatal("timeout waiting for body to close") } if doErr != ctx.Err() { t.Errorf("Do error = %v; want %v", doErr, ctx.Err()) } } type noteCloseConn struct { net.Conn onceClose sync.Once closefn func() } func (c *noteCloseConn) Close() error { c.onceClose.Do(c.closefn) return c.Conn.Close() } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go�������������������������������0000644�0610621�0607500�00000007057�13172163402�026551� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package ctxhttp // import "golang.org/x/net/context/ctxhttp" import ( "io" "net/http" "net/url" "strings" "golang.org/x/net/context" ) func nop() {} var ( testHookContextDoneBeforeHeaders = nop testHookDoReturned = nop testHookDidBodyClose = nop ) // Do sends an HTTP request with the provided http.Client and returns an HTTP response. // If the client is nil, http.DefaultClient is used. // If the context is canceled or times out, ctx.Err() will be returned. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { if client == nil { client = http.DefaultClient } // TODO(djd): Respect any existing value of req.Cancel. cancel := make(chan struct{}) req.Cancel = cancel type responseAndError struct { resp *http.Response err error } result := make(chan responseAndError, 1) // Make local copies of test hooks closed over by goroutines below. // Prevents data races in tests. testHookDoReturned := testHookDoReturned testHookDidBodyClose := testHookDidBodyClose go func() { resp, err := client.Do(req) testHookDoReturned() result <- responseAndError{resp, err} }() var resp *http.Response select { case <-ctx.Done(): testHookContextDoneBeforeHeaders() close(cancel) // Clean up after the goroutine calling client.Do: go func() { if r := <-result; r.resp != nil { testHookDidBodyClose() r.resp.Body.Close() } }() return nil, ctx.Err() case r := <-result: var err error resp, err = r.resp, r.err if err != nil { return resp, err } } c := make(chan struct{}) go func() { select { case <-ctx.Done(): close(cancel) case <-c: // The response's Body is closed. } }() resp.Body = &notifyingReader{resp.Body, c} return resp, nil } // Get issues a GET request via the Do function. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } return Do(ctx, client, req) } // Head issues a HEAD request via the Do function. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { req, err := http.NewRequest("HEAD", url, nil) if err != nil { return nil, err } return Do(ctx, client, req) } // Post issues a POST request via the Do function. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest("POST", url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", bodyType) return Do(ctx, client, req) } // PostForm issues a POST request via the Do function. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) } // notifyingReader is an io.ReadCloser that closes the notify channel after // Close is called or a Read fails on the underlying ReadCloser. type notifyingReader struct { io.ReadCloser notify chan<- struct{} } func (r *notifyingReader) Read(p []byte) (int, error) { n, err := r.ReadCloser.Read(p) if err != nil && r.notify != nil { close(r.notify) r.notify = nil } return n, err } func (r *notifyingReader) Close() error { err := r.ReadCloser.Close() if r.notify != nil { close(r.notify) r.notify = nil } return err } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go�����������������������������0000644�0610621�0607500�00000001206�13172163402�027067� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !plan9,go1.7 package ctxhttp import ( "io" "net/http" "net/http/httptest" "testing" "context" ) func TestGo17Context(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") })) defer ts.Close() ctx := context.Background() resp, err := Get(ctx, http.DefaultClient, ts.URL) if resp == nil || err != nil { t.Fatalf("error received from client: %v %v", err, resp) } resp.Body.Close() } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/ctxhttp/ctxhttp.go�������������������������������������0000644�0610621�0607500�00000004210�13172163402�025517� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 // Package ctxhttp provides helper functions for performing context-aware HTTP requests. package ctxhttp // import "golang.org/x/net/context/ctxhttp" import ( "io" "net/http" "net/url" "strings" "golang.org/x/net/context" ) // Do sends an HTTP request with the provided http.Client and returns // an HTTP response. // // If the client is nil, http.DefaultClient is used. // // The provided ctx must be non-nil. If it is canceled or times out, // ctx.Err() will be returned. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { if client == nil { client = http.DefaultClient } resp, err := client.Do(req.WithContext(ctx)) // If we got an error, and the context has been canceled, // the context's error is probably more useful. if err != nil { select { case <-ctx.Done(): err = ctx.Err() default: } } return resp, err } // Get issues a GET request via the Do function. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } return Do(ctx, client, req) } // Head issues a HEAD request via the Do function. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { req, err := http.NewRequest("HEAD", url, nil) if err != nil { return nil, err } return Do(ctx, client, req) } // Post issues a POST request via the Do function. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest("POST", url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", bodyType) return Do(ctx, client, req) } // PostForm issues a POST request via the Do function. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/context_test.go����������������������������������������0000644�0610621�0607500�00000035153�13172163402�025060� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package context import ( "fmt" "math/rand" "runtime" "strings" "sync" "testing" "time" ) // otherContext is a Context that's not one of the types defined in context.go. // This lets us test code paths that differ based on the underlying type of the // Context. type otherContext struct { Context } func TestBackground(t *testing.T) { c := Background() if c == nil { t.Fatalf("Background returned nil") } select { case x := <-c.Done(): t.Errorf("<-c.Done() == %v want nothing (it should block)", x) default: } if got, want := fmt.Sprint(c), "context.Background"; got != want { t.Errorf("Background().String() = %q want %q", got, want) } } func TestTODO(t *testing.T) { c := TODO() if c == nil { t.Fatalf("TODO returned nil") } select { case x := <-c.Done(): t.Errorf("<-c.Done() == %v want nothing (it should block)", x) default: } if got, want := fmt.Sprint(c), "context.TODO"; got != want { t.Errorf("TODO().String() = %q want %q", got, want) } } func TestWithCancel(t *testing.T) { c1, cancel := WithCancel(Background()) if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { t.Errorf("c1.String() = %q want %q", got, want) } o := otherContext{c1} c2, _ := WithCancel(o) contexts := []Context{c1, o, c2} for i, c := range contexts { if d := c.Done(); d == nil { t.Errorf("c[%d].Done() == %v want non-nil", i, d) } if e := c.Err(); e != nil { t.Errorf("c[%d].Err() == %v want nil", i, e) } select { case x := <-c.Done(): t.Errorf("<-c.Done() == %v want nothing (it should block)", x) default: } } cancel() time.Sleep(100 * time.Millisecond) // let cancelation propagate for i, c := range contexts { select { case <-c.Done(): default: t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) } if e := c.Err(); e != Canceled { t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) } } } func TestParentFinishesChild(t *testing.T) { // Context tree: // parent -> cancelChild // parent -> valueChild -> timerChild parent, cancel := WithCancel(Background()) cancelChild, stop := WithCancel(parent) defer stop() valueChild := WithValue(parent, "key", "value") timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) defer stop() select { case x := <-parent.Done(): t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) case x := <-cancelChild.Done(): t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) case x := <-timerChild.Done(): t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) case x := <-valueChild.Done(): t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) default: } // The parent's children should contain the two cancelable children. pc := parent.(*cancelCtx) cc := cancelChild.(*cancelCtx) tc := timerChild.(*timerCtx) pc.mu.Lock() if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { t.Errorf("bad linkage: pc.children = %v, want %v and %v", pc.children, cc, tc) } pc.mu.Unlock() if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) } if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) } cancel() pc.mu.Lock() if len(pc.children) != 0 { t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) } pc.mu.Unlock() // parent and children should all be finished. check := func(ctx Context, name string) { select { case <-ctx.Done(): default: t.Errorf("<-%s.Done() blocked, but shouldn't have", name) } if e := ctx.Err(); e != Canceled { t.Errorf("%s.Err() == %v want %v", name, e, Canceled) } } check(parent, "parent") check(cancelChild, "cancelChild") check(valueChild, "valueChild") check(timerChild, "timerChild") // WithCancel should return a canceled context on a canceled parent. precanceledChild := WithValue(parent, "key", "value") select { case <-precanceledChild.Done(): default: t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") } if e := precanceledChild.Err(); e != Canceled { t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) } } func TestChildFinishesFirst(t *testing.T) { cancelable, stop := WithCancel(Background()) defer stop() for _, parent := range []Context{Background(), cancelable} { child, cancel := WithCancel(parent) select { case x := <-parent.Done(): t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) case x := <-child.Done(): t.Errorf("<-child.Done() == %v want nothing (it should block)", x) default: } cc := child.(*cancelCtx) pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) } if pcok { pc.mu.Lock() if len(pc.children) != 1 || !pc.children[cc] { t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) } pc.mu.Unlock() } cancel() if pcok { pc.mu.Lock() if len(pc.children) != 0 { t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) } pc.mu.Unlock() } // child should be finished. select { case <-child.Done(): default: t.Errorf("<-child.Done() blocked, but shouldn't have") } if e := child.Err(); e != Canceled { t.Errorf("child.Err() == %v want %v", e, Canceled) } // parent should not be finished. select { case x := <-parent.Done(): t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) default: } if e := parent.Err(); e != nil { t.Errorf("parent.Err() == %v want nil", e) } } } func testDeadline(c Context, wait time.Duration, t *testing.T) { select { case <-time.After(wait): t.Fatalf("context should have timed out") case <-c.Done(): } if e := c.Err(); e != DeadlineExceeded { t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) } } func TestDeadline(t *testing.T) { t.Parallel() const timeUnit = 500 * time.Millisecond c, _ := WithDeadline(Background(), time.Now().Add(1*timeUnit)) if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { t.Errorf("c.String() = %q want prefix %q", got, prefix) } testDeadline(c, 2*timeUnit, t) c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) o := otherContext{c} testDeadline(o, 2*timeUnit, t) c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) o = otherContext{c} c, _ = WithDeadline(o, time.Now().Add(3*timeUnit)) testDeadline(c, 2*timeUnit, t) } func TestTimeout(t *testing.T) { t.Parallel() const timeUnit = 500 * time.Millisecond c, _ := WithTimeout(Background(), 1*timeUnit) if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { t.Errorf("c.String() = %q want prefix %q", got, prefix) } testDeadline(c, 2*timeUnit, t) c, _ = WithTimeout(Background(), 1*timeUnit) o := otherContext{c} testDeadline(o, 2*timeUnit, t) c, _ = WithTimeout(Background(), 1*timeUnit) o = otherContext{c} c, _ = WithTimeout(o, 3*timeUnit) testDeadline(c, 2*timeUnit, t) } func TestCanceledTimeout(t *testing.T) { t.Parallel() const timeUnit = 500 * time.Millisecond c, _ := WithTimeout(Background(), 2*timeUnit) o := otherContext{c} c, cancel := WithTimeout(o, 4*timeUnit) cancel() time.Sleep(1 * timeUnit) // let cancelation propagate select { case <-c.Done(): default: t.Errorf("<-c.Done() blocked, but shouldn't have") } if e := c.Err(); e != Canceled { t.Errorf("c.Err() == %v want %v", e, Canceled) } } type key1 int type key2 int var k1 = key1(1) var k2 = key2(1) // same int as k1, different type var k3 = key2(3) // same type as k2, different int func TestValues(t *testing.T) { check := func(c Context, nm, v1, v2, v3 string) { if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) } if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) } if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) } } c0 := Background() check(c0, "c0", "", "", "") c1 := WithValue(Background(), k1, "c1k1") check(c1, "c1", "c1k1", "", "") if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { t.Errorf("c.String() = %q want %q", got, want) } c2 := WithValue(c1, k2, "c2k2") check(c2, "c2", "c1k1", "c2k2", "") c3 := WithValue(c2, k3, "c3k3") check(c3, "c2", "c1k1", "c2k2", "c3k3") c4 := WithValue(c3, k1, nil) check(c4, "c4", "", "c2k2", "c3k3") o0 := otherContext{Background()} check(o0, "o0", "", "", "") o1 := otherContext{WithValue(Background(), k1, "c1k1")} check(o1, "o1", "c1k1", "", "") o2 := WithValue(o1, k2, "o2k2") check(o2, "o2", "c1k1", "o2k2", "") o3 := otherContext{c4} check(o3, "o3", "", "c2k2", "c3k3") o4 := WithValue(o3, k3, nil) check(o4, "o4", "", "c2k2", "") } func TestAllocs(t *testing.T) { bg := Background() for _, test := range []struct { desc string f func() limit float64 gccgoLimit float64 }{ { desc: "Background()", f: func() { Background() }, limit: 0, gccgoLimit: 0, }, { desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), f: func() { c := WithValue(bg, k1, nil) c.Value(k1) }, limit: 3, gccgoLimit: 3, }, { desc: "WithTimeout(bg, 15*time.Millisecond)", f: func() { c, _ := WithTimeout(bg, 15*time.Millisecond) <-c.Done() }, limit: 8, gccgoLimit: 16, }, { desc: "WithCancel(bg)", f: func() { c, cancel := WithCancel(bg) cancel() <-c.Done() }, limit: 5, gccgoLimit: 8, }, { desc: "WithTimeout(bg, 100*time.Millisecond)", f: func() { c, cancel := WithTimeout(bg, 100*time.Millisecond) cancel() <-c.Done() }, limit: 8, gccgoLimit: 25, }, } { limit := test.limit if runtime.Compiler == "gccgo" { // gccgo does not yet do escape analysis. // TODO(iant): Remove this when gccgo does do escape analysis. limit = test.gccgoLimit } if n := testing.AllocsPerRun(100, test.f); n > limit { t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) } } } func TestSimultaneousCancels(t *testing.T) { root, cancel := WithCancel(Background()) m := map[Context]CancelFunc{root: cancel} q := []Context{root} // Create a tree of contexts. for len(q) != 0 && len(m) < 100 { parent := q[0] q = q[1:] for i := 0; i < 4; i++ { ctx, cancel := WithCancel(parent) m[ctx] = cancel q = append(q, ctx) } } // Start all the cancels in a random order. var wg sync.WaitGroup wg.Add(len(m)) for _, cancel := range m { go func(cancel CancelFunc) { cancel() wg.Done() }(cancel) } // Wait on all the contexts in a random order. for ctx := range m { select { case <-ctx.Done(): case <-time.After(1 * time.Second): buf := make([]byte, 10<<10) n := runtime.Stack(buf, true) t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) } } // Wait for all the cancel functions to return. done := make(chan struct{}) go func() { wg.Wait() close(done) }() select { case <-done: case <-time.After(1 * time.Second): buf := make([]byte, 10<<10) n := runtime.Stack(buf, true) t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) } } func TestInterlockedCancels(t *testing.T) { parent, cancelParent := WithCancel(Background()) child, cancelChild := WithCancel(parent) go func() { parent.Done() cancelChild() }() cancelParent() select { case <-child.Done(): case <-time.After(1 * time.Second): buf := make([]byte, 10<<10) n := runtime.Stack(buf, true) t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) } } func TestLayersCancel(t *testing.T) { testLayers(t, time.Now().UnixNano(), false) } func TestLayersTimeout(t *testing.T) { testLayers(t, time.Now().UnixNano(), true) } func testLayers(t *testing.T, seed int64, testTimeout bool) { rand.Seed(seed) errorf := func(format string, a ...interface{}) { t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) } const ( timeout = 200 * time.Millisecond minLayers = 30 ) type value int var ( vals []*value cancels []CancelFunc numTimers int ctx = Background() ) for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { switch rand.Intn(3) { case 0: v := new(value) ctx = WithValue(ctx, v, v) vals = append(vals, v) case 1: var cancel CancelFunc ctx, cancel = WithCancel(ctx) cancels = append(cancels, cancel) case 2: var cancel CancelFunc ctx, cancel = WithTimeout(ctx, timeout) cancels = append(cancels, cancel) numTimers++ } } checkValues := func(when string) { for _, key := range vals { if val := ctx.Value(key).(*value); key != val { errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) } } } select { case <-ctx.Done(): errorf("ctx should not be canceled yet") default: } if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { t.Errorf("ctx.String() = %q want prefix %q", s, prefix) } t.Log(ctx) checkValues("before cancel") if testTimeout { select { case <-ctx.Done(): case <-time.After(timeout + 100*time.Millisecond): errorf("ctx should have timed out") } checkValues("after timeout") } else { cancel := cancels[rand.Intn(len(cancels))] cancel() select { case <-ctx.Done(): default: errorf("ctx should be canceled") } checkValues("after cancel") } } func TestCancelRemoves(t *testing.T) { checkChildren := func(when string, ctx Context, want int) { if got := len(ctx.(*cancelCtx).children); got != want { t.Errorf("%s: context has %d children, want %d", when, got, want) } } ctx, _ := WithCancel(Background()) checkChildren("after creation", ctx, 0) _, cancel := WithCancel(ctx) checkChildren("with WithCancel child ", ctx, 1) cancel() checkChildren("after cancelling WithCancel child", ctx, 0) ctx, _ = WithCancel(Background()) checkChildren("after creation", ctx, 0) _, cancel = WithTimeout(ctx, 60*time.Minute) checkChildren("with WithTimeout child ", ctx, 1) cancel() checkChildren("after cancelling WithTimeout child", ctx, 0) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/context/context.go���������������������������������������������0000644�0610621�0607500�00000004442�13172163402�024016� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package context defines the Context type, which carries deadlines, // cancelation signals, and other request-scoped values across API boundaries // and between processes. // // Incoming requests to a server should create a Context, and outgoing calls to // servers should accept a Context. The chain of function calls between must // propagate the Context, optionally replacing it with a modified copy created // using WithDeadline, WithTimeout, WithCancel, or WithValue. // // Programs that use Contexts should follow these rules to keep interfaces // consistent across packages and enable static analysis tools to check context // propagation: // // Do not store Contexts inside a struct type; instead, pass a Context // explicitly to each function that needs it. The Context should be the first // parameter, typically named ctx: // // func DoSomething(ctx context.Context, arg Arg) error { // // ... use ctx ... // } // // Do not pass a nil Context, even if a function permits it. Pass context.TODO // if you are unsure about which Context to use. // // Use context Values only for request-scoped data that transits processes and // APIs, not for passing optional parameters to functions. // // The same Context may be passed to functions running in different goroutines; // Contexts are safe for simultaneous use by multiple goroutines. // // See http://blog.golang.org/context for example code for a server that uses // Contexts. package context // import "golang.org/x/net/context" // Background returns a non-nil, empty Context. It is never canceled, has no // values, and has no deadline. It is typically used by the main function, // initialization, and tests, and as the top-level Context for incoming // requests. func Background() Context { return background } // TODO returns a non-nil, empty Context. Code should use context.TODO when // it's unclear which Context to use or it is not yet available (because the // surrounding function has not yet been extended to accept a Context // parameter). TODO is recognized by static analysis tools that determine // whether Contexts are propagated correctly in a program. func TODO() Context { return todo } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/codereview.cfg�������������������������������������������������0000644�0610621�0607500�00000000025�13172163402�023125� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������issuerepo: golang/go �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/�����������������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�021062� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_test.go�������������������������������������������������0000644�0610621�0607500�00000006404�13172163402�023076� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf_test import ( "fmt" "testing" "golang.org/x/net/bpf" ) var _ bpf.Instruction = unknown{} type unknown struct{} func (unknown) Assemble() (bpf.RawInstruction, error) { return bpf.RawInstruction{}, nil } func TestVMUnknownInstruction(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadConstant{ Dst: bpf.RegA, Val: 100, }, // Should terminate the program with an error immediately unknown{}, bpf.RetA{}, }) if err != nil { t.Fatalf("unexpected error: %v", err) } defer done() _, err = vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, }) if errStr(err) != "unknown Instruction at index 1: bpf_test.unknown" { t.Fatalf("unexpected error while running program: %v", err) } } func TestVMNoReturnInstruction(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.LoadConstant{ Dst: bpf.RegA, Val: 1, }, }) if errStr(err) != "BPF program must end with RetA or RetConstant" { t.Fatalf("unexpected error: %v", err) } } func TestVMNoInputInstructions(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{}) if errStr(err) != "one or more Instructions must be specified" { t.Fatalf("unexpected error: %v", err) } } // ExampleNewVM demonstrates usage of a VM, using an Ethernet frame // as input and checking its EtherType to determine if it should be accepted. func ExampleNewVM() { // Offset | Length | Comment // ------------------------- // 00 | 06 | Ethernet destination MAC address // 06 | 06 | Ethernet source MAC address // 12 | 02 | Ethernet EtherType const ( etOff = 12 etLen = 2 etARP = 0x0806 ) // Set up a VM to filter traffic based on if its EtherType // matches the ARP EtherType. vm, err := bpf.NewVM([]bpf.Instruction{ // Load EtherType value from Ethernet header bpf.LoadAbsolute{ Off: etOff, Size: etLen, }, // If EtherType is equal to the ARP EtherType, jump to allow // packet to be accepted bpf.JumpIf{ Cond: bpf.JumpEqual, Val: etARP, SkipTrue: 1, }, // EtherType does not match the ARP EtherType bpf.RetConstant{ Val: 0, }, // EtherType matches the ARP EtherType, accept up to 1500 // bytes of packet bpf.RetConstant{ Val: 1500, }, }) if err != nil { panic(fmt.Sprintf("failed to load BPF program: %v", err)) } // Create an Ethernet frame with the ARP EtherType for testing frame := []byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x08, 0x06, // Payload omitted for brevity } // Run our VM's BPF program using the Ethernet frame as input out, err := vm.Run(frame) if err != nil { panic(fmt.Sprintf("failed to accept Ethernet frame: %v", err)) } // BPF VM can return a byte count greater than the number of input // bytes, so trim the output to match the input byte length if out > len(frame) { out = len(frame) } fmt.Printf("out: %d bytes", out) // Output: // out: 14 bytes } // errStr returns the string representation of an error, or // "<nil>" if it is nil. func errStr(err error) string { if err == nil { return "<nil>" } return err.Error() } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_scratch_test.go�����������������������������������������0000644�0610621�0607500�00000011357�13172163402�024610� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf_test import ( "testing" "golang.org/x/net/bpf" ) func TestVMStoreScratchInvalidScratchRegisterTooSmall(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.StoreScratch{ Src: bpf.RegA, N: -1, }, bpf.RetA{}, }) if errStr(err) != "assembling instruction 1: invalid scratch slot -1" { t.Fatalf("unexpected error: %v", err) } } func TestVMStoreScratchInvalidScratchRegisterTooLarge(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.StoreScratch{ Src: bpf.RegA, N: 16, }, bpf.RetA{}, }) if errStr(err) != "assembling instruction 1: invalid scratch slot 16" { t.Fatalf("unexpected error: %v", err) } } func TestVMStoreScratchUnknownSourceRegister(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.StoreScratch{ Src: 100, N: 0, }, bpf.RetA{}, }) if errStr(err) != "assembling instruction 1: invalid source register 100" { t.Fatalf("unexpected error: %v", err) } } func TestVMLoadScratchInvalidScratchRegisterTooSmall(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.LoadScratch{ Dst: bpf.RegX, N: -1, }, bpf.RetA{}, }) if errStr(err) != "assembling instruction 1: invalid scratch slot -1" { t.Fatalf("unexpected error: %v", err) } } func TestVMLoadScratchInvalidScratchRegisterTooLarge(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.LoadScratch{ Dst: bpf.RegX, N: 16, }, bpf.RetA{}, }) if errStr(err) != "assembling instruction 1: invalid scratch slot 16" { t.Fatalf("unexpected error: %v", err) } } func TestVMLoadScratchUnknownDestinationRegister(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.LoadScratch{ Dst: 100, N: 0, }, bpf.RetA{}, }) if errStr(err) != "assembling instruction 1: invalid target register 100" { t.Fatalf("unexpected error: %v", err) } } func TestVMStoreScratchLoadScratchOneValue(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ // Load byte 255 bpf.LoadAbsolute{ Off: 8, Size: 1, }, // Copy to X and store in scratch[0] bpf.TAX{}, bpf.StoreScratch{ Src: bpf.RegX, N: 0, }, // Load byte 1 bpf.LoadAbsolute{ Off: 9, Size: 1, }, // Overwrite 1 with 255 from scratch[0] bpf.LoadScratch{ Dst: bpf.RegA, N: 0, }, // Return 255 bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 255, 1, 2, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 3, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMStoreScratchLoadScratchMultipleValues(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ // Load byte 10 bpf.LoadAbsolute{ Off: 8, Size: 1, }, // Store in scratch[0] bpf.StoreScratch{ Src: bpf.RegA, N: 0, }, // Load byte 20 bpf.LoadAbsolute{ Off: 9, Size: 1, }, // Store in scratch[1] bpf.StoreScratch{ Src: bpf.RegA, N: 1, }, // Load byte 30 bpf.LoadAbsolute{ Off: 10, Size: 1, }, // Store in scratch[2] bpf.StoreScratch{ Src: bpf.RegA, N: 2, }, // Load byte 1 bpf.LoadAbsolute{ Off: 11, Size: 1, }, // Store in scratch[3] bpf.StoreScratch{ Src: bpf.RegA, N: 3, }, // Load in byte 10 to X bpf.LoadScratch{ Dst: bpf.RegX, N: 0, }, // Copy X -> A bpf.TXA{}, // Verify value is 10 bpf.JumpIf{ Cond: bpf.JumpEqual, Val: 10, SkipTrue: 1, }, // Fail test if incorrect bpf.RetConstant{ Val: 0, }, // Load in byte 20 to A bpf.LoadScratch{ Dst: bpf.RegA, N: 1, }, // Verify value is 20 bpf.JumpIf{ Cond: bpf.JumpEqual, Val: 20, SkipTrue: 1, }, // Fail test if incorrect bpf.RetConstant{ Val: 0, }, // Load in byte 30 to A bpf.LoadScratch{ Dst: bpf.RegA, N: 2, }, // Verify value is 30 bpf.JumpIf{ Cond: bpf.JumpEqual, Val: 30, SkipTrue: 1, }, // Fail test if incorrect bpf.RetConstant{ Val: 0, }, // Return first two bytes on success bpf.RetConstant{ Val: 10, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 10, 20, 30, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_ret_test.go���������������������������������������������0000644�0610621�0607500�00000004471�13172163402�023752� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf_test import ( "testing" "golang.org/x/net/bpf" ) func TestVMRetA(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 9, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMRetALargerThanInput(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 2, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 255, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMRetConstant(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMRetConstantLargerThanInput(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.RetConstant{ Val: 16, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_load_test.go��������������������������������������������0000644�0610621�0607500�00000012251�13172163402�024072� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf_test import ( "net" "testing" "golang.org/x/net/bpf" "golang.org/x/net/ipv4" ) func TestVMLoadAbsoluteOffsetOutOfBounds(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 100, Size: 2, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 2, 3, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 0, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMLoadAbsoluteOffsetPlusSizeOutOfBounds(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 2, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 0, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMLoadAbsoluteBadInstructionSize(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Size: 5, }, bpf.RetA{}, }) if errStr(err) != "assembling instruction 1: invalid load byte length 0" { t.Fatalf("unexpected error: %v", err) } } func TestVMLoadConstantOK(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadConstant{ Dst: bpf.RegX, Val: 9, }, bpf.TXA{}, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMLoadIndirectOutOfBounds(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadIndirect{ Off: 100, Size: 1, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 0, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMLoadMemShiftOutOfBounds(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadMemShift{ Off: 100, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 0, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } const ( dhcp4Port = 53 ) func TestVMLoadMemShiftLoadIndirectNoResult(t *testing.T) { vm, in, done := testDHCPv4(t) defer done() // Append mostly empty UDP header with incorrect DHCPv4 port in = append(in, []byte{ 0, 0, 0, dhcp4Port + 1, 0, 0, 0, 0, }...) out, err := vm.Run(in) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 0, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMLoadMemShiftLoadIndirectOK(t *testing.T) { vm, in, done := testDHCPv4(t) defer done() // Append mostly empty UDP header with correct DHCPv4 port in = append(in, []byte{ 0, 0, 0, dhcp4Port, 0, 0, 0, 0, }...) out, err := vm.Run(in) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := len(in)-8, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func testDHCPv4(t *testing.T) (virtualMachine, []byte, func()) { // DHCPv4 test data courtesy of David Anderson: // https://github.com/google/netboot/blob/master/dhcp4/conn_linux.go#L59-L70 vm, done, err := testVM(t, []bpf.Instruction{ // Load IPv4 packet length bpf.LoadMemShift{Off: 8}, // Get UDP dport bpf.LoadIndirect{Off: 8 + 2, Size: 2}, // Correct dport? bpf.JumpIf{Cond: bpf.JumpEqual, Val: dhcp4Port, SkipFalse: 1}, // Accept bpf.RetConstant{Val: 1500}, // Ignore bpf.RetConstant{Val: 0}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } // Minimal requirements to make a valid IPv4 header h := &ipv4.Header{ Len: ipv4.HeaderLen, Src: net.IPv4(192, 168, 1, 1), Dst: net.IPv4(192, 168, 1, 2), } hb, err := h.Marshal() if err != nil { t.Fatalf("failed to marshal IPv4 header: %v", err) } hb = append([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }, hb...) return vm, hb, done } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_jump_test.go��������������������������������������������0000644�0610621�0607500�00000016227�13172163402�024135� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf_test import ( "testing" "golang.org/x/net/bpf" ) func TestVMJumpOne(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.Jump{ Skip: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMJumpOutOfProgram(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.Jump{ Skip: 1, }, bpf.RetA{}, }) if errStr(err) != "cannot jump 1 instructions; jumping past program bounds" { t.Fatalf("unexpected error: %v", err) } } func TestVMJumpIfTrueOutOfProgram(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.JumpIf{ Cond: bpf.JumpEqual, SkipTrue: 2, }, bpf.RetA{}, }) if errStr(err) != "cannot jump 2 instructions in true case; jumping past program bounds" { t.Fatalf("unexpected error: %v", err) } } func TestVMJumpIfFalseOutOfProgram(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.JumpIf{ Cond: bpf.JumpEqual, SkipFalse: 3, }, bpf.RetA{}, }) if errStr(err) != "cannot jump 3 instructions in false case; jumping past program bounds" { t.Fatalf("unexpected error: %v", err) } } func TestVMJumpIfEqual(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.JumpIf{ Cond: bpf.JumpEqual, Val: 1, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMJumpIfNotEqual(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.JumpIf{ Cond: bpf.JumpNotEqual, Val: 1, SkipFalse: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMJumpIfGreaterThan(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 4, }, bpf.JumpIf{ Cond: bpf.JumpGreaterThan, Val: 0x00010202, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 12, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 2, 3, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 4, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMJumpIfLessThan(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 4, }, bpf.JumpIf{ Cond: bpf.JumpLessThan, Val: 0xff010203, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 12, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 2, 3, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 4, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMJumpIfGreaterOrEqual(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 4, }, bpf.JumpIf{ Cond: bpf.JumpGreaterOrEqual, Val: 0x00010203, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 12, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 2, 3, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 4, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMJumpIfLessOrEqual(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 4, }, bpf.JumpIf{ Cond: bpf.JumpLessOrEqual, Val: 0xff010203, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 12, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 2, 3, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 4, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMJumpIfBitsSet(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 2, }, bpf.JumpIf{ Cond: bpf.JumpBitsSet, Val: 0x1122, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 10, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x02, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMJumpIfBitsNotSet(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 2, }, bpf.JumpIf{ Cond: bpf.JumpBitsNotSet, Val: 0x1221, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 10, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x02, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_instructions.go�����������������������������������������0000644�0610621�0607500�00000007111�13172163402�024657� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf import ( "encoding/binary" "fmt" ) func aluOpConstant(ins ALUOpConstant, regA uint32) uint32 { return aluOpCommon(ins.Op, regA, ins.Val) } func aluOpX(ins ALUOpX, regA uint32, regX uint32) (uint32, bool) { // Guard against division or modulus by zero by terminating // the program, as the OS BPF VM does if regX == 0 { switch ins.Op { case ALUOpDiv, ALUOpMod: return 0, false } } return aluOpCommon(ins.Op, regA, regX), true } func aluOpCommon(op ALUOp, regA uint32, value uint32) uint32 { switch op { case ALUOpAdd: return regA + value case ALUOpSub: return regA - value case ALUOpMul: return regA * value case ALUOpDiv: // Division by zero not permitted by NewVM and aluOpX checks return regA / value case ALUOpOr: return regA | value case ALUOpAnd: return regA & value case ALUOpShiftLeft: return regA << value case ALUOpShiftRight: return regA >> value case ALUOpMod: // Modulus by zero not permitted by NewVM and aluOpX checks return regA % value case ALUOpXor: return regA ^ value default: return regA } } func jumpIf(ins JumpIf, value uint32) int { var ok bool inV := uint32(ins.Val) switch ins.Cond { case JumpEqual: ok = value == inV case JumpNotEqual: ok = value != inV case JumpGreaterThan: ok = value > inV case JumpLessThan: ok = value < inV case JumpGreaterOrEqual: ok = value >= inV case JumpLessOrEqual: ok = value <= inV case JumpBitsSet: ok = (value & inV) != 0 case JumpBitsNotSet: ok = (value & inV) == 0 } if ok { return int(ins.SkipTrue) } return int(ins.SkipFalse) } func loadAbsolute(ins LoadAbsolute, in []byte) (uint32, bool) { offset := int(ins.Off) size := int(ins.Size) return loadCommon(in, offset, size) } func loadConstant(ins LoadConstant, regA uint32, regX uint32) (uint32, uint32) { switch ins.Dst { case RegA: regA = ins.Val case RegX: regX = ins.Val } return regA, regX } func loadExtension(ins LoadExtension, in []byte) uint32 { switch ins.Num { case ExtLen: return uint32(len(in)) default: panic(fmt.Sprintf("unimplemented extension: %d", ins.Num)) } } func loadIndirect(ins LoadIndirect, in []byte, regX uint32) (uint32, bool) { offset := int(ins.Off) + int(regX) size := int(ins.Size) return loadCommon(in, offset, size) } func loadMemShift(ins LoadMemShift, in []byte) (uint32, bool) { offset := int(ins.Off) if !inBounds(len(in), offset, 0) { return 0, false } // Mask off high 4 bits and multiply low 4 bits by 4 return uint32(in[offset]&0x0f) * 4, true } func inBounds(inLen int, offset int, size int) bool { return offset+size <= inLen } func loadCommon(in []byte, offset int, size int) (uint32, bool) { if !inBounds(len(in), offset, size) { return 0, false } switch size { case 1: return uint32(in[offset]), true case 2: return uint32(binary.BigEndian.Uint16(in[offset : offset+size])), true case 4: return uint32(binary.BigEndian.Uint32(in[offset : offset+size])), true default: panic(fmt.Sprintf("invalid load size: %d", size)) } } func loadScratch(ins LoadScratch, regScratch [16]uint32, regA uint32, regX uint32) (uint32, uint32) { switch ins.Dst { case RegA: regA = regScratch[ins.N] case RegX: regX = regScratch[ins.N] } return regA, regX } func storeScratch(ins StoreScratch, regScratch [16]uint32, regA uint32, regX uint32) [16]uint32 { switch ins.Src { case RegA: regScratch[ins.N] = regA case RegX: regScratch[ins.N] = regX } return regScratch } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_extension_test.go���������������������������������������0000644�0610621�0607500�00000002012�13172163402�025161� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf_test import ( "testing" "golang.org/x/net/bpf" ) func TestVMLoadExtensionNotImplemented(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.LoadExtension{ Num: 100, }, bpf.RetA{}, }) if errStr(err) != "extension 100 not implemented" { t.Fatalf("unexpected error: %v", err) } } func TestVMLoadExtensionExtLen(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadExtension{ Num: bpf.ExtLen, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 2, 3, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 4, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_bpf_test.go���������������������������������������������0000644�0610621�0607500�00000011566�13172163402�023732� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf_test import ( "net" "runtime" "testing" "time" "golang.org/x/net/bpf" "golang.org/x/net/ipv4" ) // A virtualMachine is a BPF virtual machine which can process an // input packet against a BPF program and render a verdict. type virtualMachine interface { Run(in []byte) (int, error) } // canUseOSVM indicates if the OS BPF VM is available on this platform. func canUseOSVM() bool { // OS BPF VM can only be used on platforms where x/net/ipv4 supports // attaching a BPF program to a socket. switch runtime.GOOS { case "linux": return true } return false } // All BPF tests against both the Go VM and OS VM are assumed to // be used with a UDP socket. As a result, the entire contents // of a UDP datagram is sent through the BPF program, but only // the body after the UDP header will ever be returned in output. // testVM sets up a Go BPF VM, and if available, a native OS BPF VM // for integration testing. func testVM(t *testing.T, filter []bpf.Instruction) (virtualMachine, func(), error) { goVM, err := bpf.NewVM(filter) if err != nil { // Some tests expect an error, so this error must be returned // instead of fatally exiting the test return nil, nil, err } mvm := &multiVirtualMachine{ goVM: goVM, t: t, } // If available, add the OS VM for tests which verify that both the Go // VM and OS VM have exactly the same output for the same input program // and packet. done := func() {} if canUseOSVM() { osVM, osVMDone := testOSVM(t, filter) done = func() { osVMDone() } mvm.osVM = osVM } return mvm, done, nil } // udpHeaderLen is the length of a UDP header. const udpHeaderLen = 8 // A multiVirtualMachine is a virtualMachine which can call out to both the Go VM // and the native OS VM, if the OS VM is available. type multiVirtualMachine struct { goVM virtualMachine osVM virtualMachine t *testing.T } func (mvm *multiVirtualMachine) Run(in []byte) (int, error) { if len(in) < udpHeaderLen { mvm.t.Fatalf("input must be at least length of UDP header (%d), got: %d", udpHeaderLen, len(in)) } // All tests have a UDP header as part of input, because the OS VM // packets always will. For the Go VM, this output is trimmed before // being sent back to tests. goOut, goErr := mvm.goVM.Run(in) if goOut >= udpHeaderLen { goOut -= udpHeaderLen } // If Go output is larger than the size of the packet, packet filtering // interop tests must trim the output bytes to the length of the packet. // The BPF VM should not do this on its own, as other uses of it do // not trim the output byte count. trim := len(in) - udpHeaderLen if goOut > trim { goOut = trim } // When the OS VM is not available, process using the Go VM alone if mvm.osVM == nil { return goOut, goErr } // The OS VM will apply its own UDP header, so remove the pseudo header // that the Go VM needs. osOut, err := mvm.osVM.Run(in[udpHeaderLen:]) if err != nil { mvm.t.Fatalf("error while running OS VM: %v", err) } // Verify both VMs return same number of bytes var mismatch bool if goOut != osOut { mismatch = true mvm.t.Logf("output byte count does not match:\n- go: %v\n- os: %v", goOut, osOut) } if mismatch { mvm.t.Fatal("Go BPF and OS BPF packet outputs do not match") } return goOut, goErr } // An osVirtualMachine is a virtualMachine which uses the OS's BPF VM for // processing BPF programs. type osVirtualMachine struct { l net.PacketConn s net.Conn } // testOSVM creates a virtualMachine which uses the OS's BPF VM by injecting // packets into a UDP listener with a BPF program attached to it. func testOSVM(t *testing.T, filter []bpf.Instruction) (virtualMachine, func()) { l, err := net.ListenPacket("udp4", "127.0.0.1:0") if err != nil { t.Fatalf("failed to open OS VM UDP listener: %v", err) } prog, err := bpf.Assemble(filter) if err != nil { t.Fatalf("failed to compile BPF program: %v", err) } p := ipv4.NewPacketConn(l) if err = p.SetBPF(prog); err != nil { t.Fatalf("failed to attach BPF program to listener: %v", err) } s, err := net.Dial("udp4", l.LocalAddr().String()) if err != nil { t.Fatalf("failed to dial connection to listener: %v", err) } done := func() { _ = s.Close() _ = l.Close() } return &osVirtualMachine{ l: l, s: s, }, done } // Run sends the input bytes into the OS's BPF VM and returns its verdict. func (vm *osVirtualMachine) Run(in []byte) (int, error) { go func() { _, _ = vm.s.Write(in) }() vm.l.SetDeadline(time.Now().Add(50 * time.Millisecond)) var b [512]byte n, _, err := vm.l.ReadFrom(b[:]) if err != nil { // A timeout indicates that BPF filtered out the packet, and thus, // no input should be returned. if nerr, ok := err.(net.Error); ok && nerr.Timeout() { return n, nil } return n, err } return n, nil } ������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm_aluop_test.go�������������������������������������������0000644�0610621�0607500�00000023245�13172163402�024300� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf_test import ( "testing" "golang.org/x/net/bpf" ) func TestVMALUOpAdd(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpAdd, Val: 3, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 8, 2, 3, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 3, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpSub(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.TAX{}, bpf.ALUOpX{ Op: bpf.ALUOpSub, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, 2, 3, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 0, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpMul(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpMul, Val: 2, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 6, 2, 3, 4, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 4, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpDiv(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpDiv, Val: 2, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 20, 2, 3, 4, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpDivByZeroALUOpConstant(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.ALUOpConstant{ Op: bpf.ALUOpDiv, Val: 0, }, bpf.RetA{}, }) if errStr(err) != "cannot divide by zero using ALUOpConstant" { t.Fatalf("unexpected error: %v", err) } } func TestVMALUOpDivByZeroALUOpX(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ // Load byte 0 into X bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.TAX{}, // Load byte 1 into A bpf.LoadAbsolute{ Off: 9, Size: 1, }, // Attempt to perform 1/0 bpf.ALUOpX{ Op: bpf.ALUOpDiv, }, // Return 4 bytes if program does not terminate bpf.LoadConstant{ Val: 12, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 3, 4, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 0, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpOr(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 2, }, bpf.ALUOpConstant{ Op: bpf.ALUOpOr, Val: 0x01, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x10, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xff, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 9, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpAnd(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 2, }, bpf.ALUOpConstant{ Op: bpf.ALUOpAnd, Val: 0x0019, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xaa, 0x09, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpShiftLeft(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpShiftLeft, Val: 0x01, }, bpf.JumpIf{ Cond: bpf.JumpEqual, Val: 0x02, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0xaa, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpShiftRight(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpShiftRight, Val: 0x01, }, bpf.JumpIf{ Cond: bpf.JumpEqual, Val: 0x04, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0xff, 0xff, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpMod(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpMod, Val: 20, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 30, 0, 0, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpModByZeroALUOpConstant(t *testing.T) { _, _, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpMod, Val: 0, }, bpf.RetA{}, }) if errStr(err) != "cannot divide by zero using ALUOpConstant" { t.Fatalf("unexpected error: %v", err) } } func TestVMALUOpModByZeroALUOpX(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ // Load byte 0 into X bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.TAX{}, // Load byte 1 into A bpf.LoadAbsolute{ Off: 9, Size: 1, }, // Attempt to perform 1%0 bpf.ALUOpX{ Op: bpf.ALUOpMod, }, // Return 4 bytes if program does not terminate bpf.LoadConstant{ Val: 12, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, 3, 4, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 0, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpXor(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpXor, Val: 0x0a, }, bpf.JumpIf{ Cond: bpf.JumpEqual, Val: 0x01, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0b, 0x00, 0x00, 0x00, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMALUOpUnknown(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.ALUOpConstant{ Op: bpf.ALUOpAdd, Val: 1, }, // Verify that an unknown operation is a no-op bpf.ALUOpConstant{ Op: 100, }, bpf.JumpIf{ Cond: bpf.JumpEqual, Val: 0x02, SkipTrue: 1, }, bpf.RetConstant{ Val: 0, }, bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/vm.go������������������������������������������������������0000644�0610621�0607500�00000007230�13172163402�022035� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf import ( "errors" "fmt" ) // A VM is an emulated BPF virtual machine. type VM struct { filter []Instruction } // NewVM returns a new VM using the input BPF program. func NewVM(filter []Instruction) (*VM, error) { if len(filter) == 0 { return nil, errors.New("one or more Instructions must be specified") } for i, ins := range filter { check := len(filter) - (i + 1) switch ins := ins.(type) { // Check for out-of-bounds jumps in instructions case Jump: if check <= int(ins.Skip) { return nil, fmt.Errorf("cannot jump %d instructions; jumping past program bounds", ins.Skip) } case JumpIf: if check <= int(ins.SkipTrue) { return nil, fmt.Errorf("cannot jump %d instructions in true case; jumping past program bounds", ins.SkipTrue) } if check <= int(ins.SkipFalse) { return nil, fmt.Errorf("cannot jump %d instructions in false case; jumping past program bounds", ins.SkipFalse) } // Check for division or modulus by zero case ALUOpConstant: if ins.Val != 0 { break } switch ins.Op { case ALUOpDiv, ALUOpMod: return nil, errors.New("cannot divide by zero using ALUOpConstant") } // Check for unknown extensions case LoadExtension: switch ins.Num { case ExtLen: default: return nil, fmt.Errorf("extension %d not implemented", ins.Num) } } } // Make sure last instruction is a return instruction switch filter[len(filter)-1].(type) { case RetA, RetConstant: default: return nil, errors.New("BPF program must end with RetA or RetConstant") } // Though our VM works using disassembled instructions, we // attempt to assemble the input filter anyway to ensure it is compatible // with an operating system VM. _, err := Assemble(filter) return &VM{ filter: filter, }, err } // Run runs the VM's BPF program against the input bytes. // Run returns the number of bytes accepted by the BPF program, and any errors // which occurred while processing the program. func (v *VM) Run(in []byte) (int, error) { var ( // Registers of the virtual machine regA uint32 regX uint32 regScratch [16]uint32 // OK is true if the program should continue processing the next // instruction, or false if not, causing the loop to break ok = true ) // TODO(mdlayher): implement: // - NegateA: // - would require a change from uint32 registers to int32 // registers // TODO(mdlayher): add interop tests that check signedness of ALU // operations against kernel implementation, and make sure Go // implementation matches behavior for i := 0; i < len(v.filter) && ok; i++ { ins := v.filter[i] switch ins := ins.(type) { case ALUOpConstant: regA = aluOpConstant(ins, regA) case ALUOpX: regA, ok = aluOpX(ins, regA, regX) case Jump: i += int(ins.Skip) case JumpIf: jump := jumpIf(ins, regA) i += jump case LoadAbsolute: regA, ok = loadAbsolute(ins, in) case LoadConstant: regA, regX = loadConstant(ins, regA, regX) case LoadExtension: regA = loadExtension(ins, in) case LoadIndirect: regA, ok = loadIndirect(ins, in, regX) case LoadMemShift: regX, ok = loadMemShift(ins, in) case LoadScratch: regA, regX = loadScratch(ins, regScratch, regA, regX) case RetA: return int(regA), nil case RetConstant: return int(ins.Val), nil case StoreScratch: regScratch = storeScratch(ins, regScratch, regA, regX) case TAX: regX = regA case TXA: regA = regX default: return 0, fmt.Errorf("unknown Instruction at index %d: %T", i, ins) } } return 0, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/testdata/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163402�022673� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/testdata/all_instructions.txt������������������������������0000644�0610621�0607500�00000001457�13172163402�027037� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This filter is compiled to all_instructions.bpf by the `bpf_asm` # tool, which can be found in the linux kernel source tree under # tools/net. # Load immediate ld #42 ldx #42 # Load scratch ld M[3] ldx M[3] # Load absolute ldb [42] ldh [42] ld [42] # Load indirect ldb [x + 42] ldh [x + 42] ld [x + 42] # Load IPv4 header length ldx 4*([42]&0xf) # Run extension function ld #len ld #proto ld #type ld #rand # Store scratch st M[3] stx M[3] # A <op> constant add #42 sub #42 mul #42 div #42 or #42 and #42 lsh #42 rsh #42 mod #42 xor #42 # A <op> X add x sub x mul x div x or x and x lsh x rsh x mod x xor x # !A neg # Jumps ja end jeq #42,prev,end jne #42,end jlt #42,end jle #42,end jgt #42,prev,end jge #42,prev,end jset #42,prev,end # Register transfers tax txa # Returns prev: ret a end: ret #42 �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/testdata/all_instructions.bpf������������������������������0000644�0610621�0607500�00000001000�13172163402�026747� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������50,0 0 0 42,1 0 0 42,96 0 0 3,97 0 0 3,48 0 0 42,40 0 0 42,32 0 0 42,80 0 0 42,72 0 0 42,64 0 0 42,177 0 0 42,128 0 0 0,32 0 0 4294963200,32 0 0 4294963204,32 0 0 4294963256,2 0 0 3,3 0 0 3,4 0 0 42,20 0 0 42,36 0 0 42,52 0 0 42,68 0 0 42,84 0 0 42,100 0 0 42,116 0 0 42,148 0 0 42,164 0 0 42,12 0 0 0,28 0 0 0,44 0 0 0,60 0 0 0,76 0 0 0,92 0 0 0,108 0 0 0,124 0 0 0,156 0 0 0,172 0 0 0,132 0 0 0,5 0 0 10,21 8 9 42,21 0 8 42,53 0 7 42,37 0 6 42,37 4 5 42,53 3 4 42,69 2 3 42,7 0 0 0,135 0 0 0,22 0 0 0,6 0 0 0, lxd-2.0.11/dist/src/golang.org/x/net/bpf/setter.go��������������������������������������������������0000644�0610621�0607500�00000000466�13172163402�022725� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf // A Setter is a type which can attach a compiled BPF filter to itself. type Setter interface { SetBPF(filter []RawInstruction) error } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/instructions_test.go���������������������������������������0000644�0610621�0607500�00000032571�13172163402�025224� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf import ( "fmt" "io/ioutil" "reflect" "strconv" "strings" "testing" ) // This is a direct translation of the program in // testdata/all_instructions.txt. var allInstructions = []Instruction{ LoadConstant{Dst: RegA, Val: 42}, LoadConstant{Dst: RegX, Val: 42}, LoadScratch{Dst: RegA, N: 3}, LoadScratch{Dst: RegX, N: 3}, LoadAbsolute{Off: 42, Size: 1}, LoadAbsolute{Off: 42, Size: 2}, LoadAbsolute{Off: 42, Size: 4}, LoadIndirect{Off: 42, Size: 1}, LoadIndirect{Off: 42, Size: 2}, LoadIndirect{Off: 42, Size: 4}, LoadMemShift{Off: 42}, LoadExtension{Num: ExtLen}, LoadExtension{Num: ExtProto}, LoadExtension{Num: ExtType}, LoadExtension{Num: ExtRand}, StoreScratch{Src: RegA, N: 3}, StoreScratch{Src: RegX, N: 3}, ALUOpConstant{Op: ALUOpAdd, Val: 42}, ALUOpConstant{Op: ALUOpSub, Val: 42}, ALUOpConstant{Op: ALUOpMul, Val: 42}, ALUOpConstant{Op: ALUOpDiv, Val: 42}, ALUOpConstant{Op: ALUOpOr, Val: 42}, ALUOpConstant{Op: ALUOpAnd, Val: 42}, ALUOpConstant{Op: ALUOpShiftLeft, Val: 42}, ALUOpConstant{Op: ALUOpShiftRight, Val: 42}, ALUOpConstant{Op: ALUOpMod, Val: 42}, ALUOpConstant{Op: ALUOpXor, Val: 42}, ALUOpX{Op: ALUOpAdd}, ALUOpX{Op: ALUOpSub}, ALUOpX{Op: ALUOpMul}, ALUOpX{Op: ALUOpDiv}, ALUOpX{Op: ALUOpOr}, ALUOpX{Op: ALUOpAnd}, ALUOpX{Op: ALUOpShiftLeft}, ALUOpX{Op: ALUOpShiftRight}, ALUOpX{Op: ALUOpMod}, ALUOpX{Op: ALUOpXor}, NegateA{}, Jump{Skip: 10}, JumpIf{Cond: JumpEqual, Val: 42, SkipTrue: 8, SkipFalse: 9}, JumpIf{Cond: JumpNotEqual, Val: 42, SkipTrue: 8}, JumpIf{Cond: JumpLessThan, Val: 42, SkipTrue: 7}, JumpIf{Cond: JumpLessOrEqual, Val: 42, SkipTrue: 6}, JumpIf{Cond: JumpGreaterThan, Val: 42, SkipTrue: 4, SkipFalse: 5}, JumpIf{Cond: JumpGreaterOrEqual, Val: 42, SkipTrue: 3, SkipFalse: 4}, JumpIf{Cond: JumpBitsSet, Val: 42, SkipTrue: 2, SkipFalse: 3}, TAX{}, TXA{}, RetA{}, RetConstant{Val: 42}, } var allInstructionsExpected = "testdata/all_instructions.bpf" // Check that we produce the same output as the canonical bpf_asm // linux kernel tool. func TestInterop(t *testing.T) { out, err := Assemble(allInstructions) if err != nil { t.Fatalf("assembly of allInstructions program failed: %s", err) } t.Logf("Assembled program is %d instructions long", len(out)) bs, err := ioutil.ReadFile(allInstructionsExpected) if err != nil { t.Fatalf("reading %s: %s", allInstructionsExpected, err) } // First statement is the number of statements, last statement is // empty. We just ignore both and rely on slice length. stmts := strings.Split(string(bs), ",") if len(stmts)-2 != len(out) { t.Fatalf("test program lengths don't match: %s has %d, Go implementation has %d", allInstructionsExpected, len(stmts)-2, len(allInstructions)) } for i, stmt := range stmts[1 : len(stmts)-2] { nums := strings.Split(stmt, " ") if len(nums) != 4 { t.Fatalf("malformed instruction %d in %s: %s", i+1, allInstructionsExpected, stmt) } actual := out[i] op, err := strconv.ParseUint(nums[0], 10, 16) if err != nil { t.Fatalf("malformed opcode %s in instruction %d of %s", nums[0], i+1, allInstructionsExpected) } if actual.Op != uint16(op) { t.Errorf("opcode mismatch on instruction %d (%#v): got 0x%02x, want 0x%02x", i+1, allInstructions[i], actual.Op, op) } jt, err := strconv.ParseUint(nums[1], 10, 8) if err != nil { t.Fatalf("malformed jt offset %s in instruction %d of %s", nums[1], i+1, allInstructionsExpected) } if actual.Jt != uint8(jt) { t.Errorf("jt mismatch on instruction %d (%#v): got %d, want %d", i+1, allInstructions[i], actual.Jt, jt) } jf, err := strconv.ParseUint(nums[2], 10, 8) if err != nil { t.Fatalf("malformed jf offset %s in instruction %d of %s", nums[2], i+1, allInstructionsExpected) } if actual.Jf != uint8(jf) { t.Errorf("jf mismatch on instruction %d (%#v): got %d, want %d", i+1, allInstructions[i], actual.Jf, jf) } k, err := strconv.ParseUint(nums[3], 10, 32) if err != nil { t.Fatalf("malformed constant %s in instruction %d of %s", nums[3], i+1, allInstructionsExpected) } if actual.K != uint32(k) { t.Errorf("constant mismatch on instruction %d (%#v): got %d, want %d", i+1, allInstructions[i], actual.K, k) } } } // Check that assembly and disassembly match each other. func TestAsmDisasm(t *testing.T) { prog1, err := Assemble(allInstructions) if err != nil { t.Fatalf("assembly of allInstructions program failed: %s", err) } t.Logf("Assembled program is %d instructions long", len(prog1)) got, allDecoded := Disassemble(prog1) if !allDecoded { t.Errorf("Disassemble(Assemble(allInstructions)) produced unrecognized instructions:") for i, inst := range got { if r, ok := inst.(RawInstruction); ok { t.Logf(" insn %d, %#v --> %#v", i+1, allInstructions[i], r) } } } if len(allInstructions) != len(got) { t.Fatalf("disassembly changed program size: %d insns before, %d insns after", len(allInstructions), len(got)) } if !reflect.DeepEqual(allInstructions, got) { t.Errorf("program mutated by disassembly:") for i := range got { if !reflect.DeepEqual(allInstructions[i], got[i]) { t.Logf(" insn %d, s: %#v, p1: %#v, got: %#v", i+1, allInstructions[i], prog1[i], got[i]) } } } } type InvalidInstruction struct{} func (a InvalidInstruction) Assemble() (RawInstruction, error) { return RawInstruction{}, fmt.Errorf("Invalid Instruction") } func (a InvalidInstruction) String() string { return fmt.Sprintf("unknown instruction: %#v", a) } func TestString(t *testing.T) { testCases := []struct { instruction Instruction assembler string }{ { instruction: LoadConstant{Dst: RegA, Val: 42}, assembler: "ld #42", }, { instruction: LoadConstant{Dst: RegX, Val: 42}, assembler: "ldx #42", }, { instruction: LoadConstant{Dst: 0xffff, Val: 42}, assembler: "unknown instruction: bpf.LoadConstant{Dst:0xffff, Val:0x2a}", }, { instruction: LoadScratch{Dst: RegA, N: 3}, assembler: "ld M[3]", }, { instruction: LoadScratch{Dst: RegX, N: 3}, assembler: "ldx M[3]", }, { instruction: LoadScratch{Dst: 0xffff, N: 3}, assembler: "unknown instruction: bpf.LoadScratch{Dst:0xffff, N:3}", }, { instruction: LoadAbsolute{Off: 42, Size: 1}, assembler: "ldb [42]", }, { instruction: LoadAbsolute{Off: 42, Size: 2}, assembler: "ldh [42]", }, { instruction: LoadAbsolute{Off: 42, Size: 4}, assembler: "ld [42]", }, { instruction: LoadAbsolute{Off: 42, Size: -1}, assembler: "unknown instruction: bpf.LoadAbsolute{Off:0x2a, Size:-1}", }, { instruction: LoadIndirect{Off: 42, Size: 1}, assembler: "ldb [x + 42]", }, { instruction: LoadIndirect{Off: 42, Size: 2}, assembler: "ldh [x + 42]", }, { instruction: LoadIndirect{Off: 42, Size: 4}, assembler: "ld [x + 42]", }, { instruction: LoadIndirect{Off: 42, Size: -1}, assembler: "unknown instruction: bpf.LoadIndirect{Off:0x2a, Size:-1}", }, { instruction: LoadMemShift{Off: 42}, assembler: "ldx 4*([42]&0xf)", }, { instruction: LoadExtension{Num: ExtLen}, assembler: "ld #len", }, { instruction: LoadExtension{Num: ExtProto}, assembler: "ld #proto", }, { instruction: LoadExtension{Num: ExtType}, assembler: "ld #type", }, { instruction: LoadExtension{Num: ExtPayloadOffset}, assembler: "ld #poff", }, { instruction: LoadExtension{Num: ExtInterfaceIndex}, assembler: "ld #ifidx", }, { instruction: LoadExtension{Num: ExtNetlinkAttr}, assembler: "ld #nla", }, { instruction: LoadExtension{Num: ExtNetlinkAttrNested}, assembler: "ld #nlan", }, { instruction: LoadExtension{Num: ExtMark}, assembler: "ld #mark", }, { instruction: LoadExtension{Num: ExtQueue}, assembler: "ld #queue", }, { instruction: LoadExtension{Num: ExtLinkLayerType}, assembler: "ld #hatype", }, { instruction: LoadExtension{Num: ExtRXHash}, assembler: "ld #rxhash", }, { instruction: LoadExtension{Num: ExtCPUID}, assembler: "ld #cpu", }, { instruction: LoadExtension{Num: ExtVLANTag}, assembler: "ld #vlan_tci", }, { instruction: LoadExtension{Num: ExtVLANTagPresent}, assembler: "ld #vlan_avail", }, { instruction: LoadExtension{Num: ExtVLANProto}, assembler: "ld #vlan_tpid", }, { instruction: LoadExtension{Num: ExtRand}, assembler: "ld #rand", }, { instruction: LoadAbsolute{Off: 0xfffff038, Size: 4}, assembler: "ld #rand", }, { instruction: LoadExtension{Num: 0xfff}, assembler: "unknown instruction: bpf.LoadExtension{Num:4095}", }, { instruction: StoreScratch{Src: RegA, N: 3}, assembler: "st M[3]", }, { instruction: StoreScratch{Src: RegX, N: 3}, assembler: "stx M[3]", }, { instruction: StoreScratch{Src: 0xffff, N: 3}, assembler: "unknown instruction: bpf.StoreScratch{Src:0xffff, N:3}", }, { instruction: ALUOpConstant{Op: ALUOpAdd, Val: 42}, assembler: "add #42", }, { instruction: ALUOpConstant{Op: ALUOpSub, Val: 42}, assembler: "sub #42", }, { instruction: ALUOpConstant{Op: ALUOpMul, Val: 42}, assembler: "mul #42", }, { instruction: ALUOpConstant{Op: ALUOpDiv, Val: 42}, assembler: "div #42", }, { instruction: ALUOpConstant{Op: ALUOpOr, Val: 42}, assembler: "or #42", }, { instruction: ALUOpConstant{Op: ALUOpAnd, Val: 42}, assembler: "and #42", }, { instruction: ALUOpConstant{Op: ALUOpShiftLeft, Val: 42}, assembler: "lsh #42", }, { instruction: ALUOpConstant{Op: ALUOpShiftRight, Val: 42}, assembler: "rsh #42", }, { instruction: ALUOpConstant{Op: ALUOpMod, Val: 42}, assembler: "mod #42", }, { instruction: ALUOpConstant{Op: ALUOpXor, Val: 42}, assembler: "xor #42", }, { instruction: ALUOpConstant{Op: 0xffff, Val: 42}, assembler: "unknown instruction: bpf.ALUOpConstant{Op:0xffff, Val:0x2a}", }, { instruction: ALUOpX{Op: ALUOpAdd}, assembler: "add x", }, { instruction: ALUOpX{Op: ALUOpSub}, assembler: "sub x", }, { instruction: ALUOpX{Op: ALUOpMul}, assembler: "mul x", }, { instruction: ALUOpX{Op: ALUOpDiv}, assembler: "div x", }, { instruction: ALUOpX{Op: ALUOpOr}, assembler: "or x", }, { instruction: ALUOpX{Op: ALUOpAnd}, assembler: "and x", }, { instruction: ALUOpX{Op: ALUOpShiftLeft}, assembler: "lsh x", }, { instruction: ALUOpX{Op: ALUOpShiftRight}, assembler: "rsh x", }, { instruction: ALUOpX{Op: ALUOpMod}, assembler: "mod x", }, { instruction: ALUOpX{Op: ALUOpXor}, assembler: "xor x", }, { instruction: ALUOpX{Op: 0xffff}, assembler: "unknown instruction: bpf.ALUOpX{Op:0xffff}", }, { instruction: NegateA{}, assembler: "neg", }, { instruction: Jump{Skip: 10}, assembler: "ja 10", }, { instruction: JumpIf{Cond: JumpEqual, Val: 42, SkipTrue: 8, SkipFalse: 9}, assembler: "jeq #42,8,9", }, { instruction: JumpIf{Cond: JumpEqual, Val: 42, SkipTrue: 8}, assembler: "jeq #42,8", }, { instruction: JumpIf{Cond: JumpEqual, Val: 42, SkipFalse: 8}, assembler: "jneq #42,8", }, { instruction: JumpIf{Cond: JumpNotEqual, Val: 42, SkipTrue: 8}, assembler: "jneq #42,8", }, { instruction: JumpIf{Cond: JumpLessThan, Val: 42, SkipTrue: 7}, assembler: "jlt #42,7", }, { instruction: JumpIf{Cond: JumpLessOrEqual, Val: 42, SkipTrue: 6}, assembler: "jle #42,6", }, { instruction: JumpIf{Cond: JumpGreaterThan, Val: 42, SkipTrue: 4, SkipFalse: 5}, assembler: "jgt #42,4,5", }, { instruction: JumpIf{Cond: JumpGreaterThan, Val: 42, SkipTrue: 4}, assembler: "jgt #42,4", }, { instruction: JumpIf{Cond: JumpGreaterOrEqual, Val: 42, SkipTrue: 3, SkipFalse: 4}, assembler: "jge #42,3,4", }, { instruction: JumpIf{Cond: JumpGreaterOrEqual, Val: 42, SkipTrue: 3}, assembler: "jge #42,3", }, { instruction: JumpIf{Cond: JumpBitsSet, Val: 42, SkipTrue: 2, SkipFalse: 3}, assembler: "jset #42,2,3", }, { instruction: JumpIf{Cond: JumpBitsSet, Val: 42, SkipTrue: 2}, assembler: "jset #42,2", }, { instruction: JumpIf{Cond: JumpBitsNotSet, Val: 42, SkipTrue: 2, SkipFalse: 3}, assembler: "jset #42,3,2", }, { instruction: JumpIf{Cond: JumpBitsNotSet, Val: 42, SkipTrue: 2}, assembler: "jset #42,0,2", }, { instruction: JumpIf{Cond: 0xffff, Val: 42, SkipTrue: 1, SkipFalse: 2}, assembler: "unknown instruction: bpf.JumpIf{Cond:0xffff, Val:0x2a, SkipTrue:0x1, SkipFalse:0x2}", }, { instruction: TAX{}, assembler: "tax", }, { instruction: TXA{}, assembler: "txa", }, { instruction: RetA{}, assembler: "ret a", }, { instruction: RetConstant{Val: 42}, assembler: "ret #42", }, // Invalid instruction { instruction: InvalidInstruction{}, assembler: "unknown instruction: bpf.InvalidInstruction{}", }, } for _, testCase := range testCases { if input, ok := testCase.instruction.(fmt.Stringer); ok { got := input.String() if got != testCase.assembler { t.Errorf("String did not return expected assembler notation, expected: %s, got: %s", testCase.assembler, got) } } else { t.Errorf("Instruction %#v is not a fmt.Stringer", testCase.instruction) } } } ���������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/instructions.go��������������������������������������������0000644�0610621�0607500�00000040722�13172163402�024162� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf import "fmt" // An Instruction is one instruction executed by the BPF virtual // machine. type Instruction interface { // Assemble assembles the Instruction into a RawInstruction. Assemble() (RawInstruction, error) } // A RawInstruction is a raw BPF virtual machine instruction. type RawInstruction struct { // Operation to execute. Op uint16 // For conditional jump instructions, the number of instructions // to skip if the condition is true/false. Jt uint8 Jf uint8 // Constant parameter. The meaning depends on the Op. K uint32 } // Assemble implements the Instruction Assemble method. func (ri RawInstruction) Assemble() (RawInstruction, error) { return ri, nil } // Disassemble parses ri into an Instruction and returns it. If ri is // not recognized by this package, ri itself is returned. func (ri RawInstruction) Disassemble() Instruction { switch ri.Op & opMaskCls { case opClsLoadA, opClsLoadX: reg := Register(ri.Op & opMaskLoadDest) sz := 0 switch ri.Op & opMaskLoadWidth { case opLoadWidth4: sz = 4 case opLoadWidth2: sz = 2 case opLoadWidth1: sz = 1 default: return ri } switch ri.Op & opMaskLoadMode { case opAddrModeImmediate: if sz != 4 { return ri } return LoadConstant{Dst: reg, Val: ri.K} case opAddrModeScratch: if sz != 4 || ri.K > 15 { return ri } return LoadScratch{Dst: reg, N: int(ri.K)} case opAddrModeAbsolute: if ri.K > extOffset+0xffffffff { return LoadExtension{Num: Extension(-extOffset + ri.K)} } return LoadAbsolute{Size: sz, Off: ri.K} case opAddrModeIndirect: return LoadIndirect{Size: sz, Off: ri.K} case opAddrModePacketLen: if sz != 4 { return ri } return LoadExtension{Num: ExtLen} case opAddrModeMemShift: return LoadMemShift{Off: ri.K} default: return ri } case opClsStoreA: if ri.Op != opClsStoreA || ri.K > 15 { return ri } return StoreScratch{Src: RegA, N: int(ri.K)} case opClsStoreX: if ri.Op != opClsStoreX || ri.K > 15 { return ri } return StoreScratch{Src: RegX, N: int(ri.K)} case opClsALU: switch op := ALUOp(ri.Op & opMaskOperator); op { case ALUOpAdd, ALUOpSub, ALUOpMul, ALUOpDiv, ALUOpOr, ALUOpAnd, ALUOpShiftLeft, ALUOpShiftRight, ALUOpMod, ALUOpXor: if ri.Op&opMaskOperandSrc != 0 { return ALUOpX{Op: op} } return ALUOpConstant{Op: op, Val: ri.K} case aluOpNeg: return NegateA{} default: return ri } case opClsJump: if ri.Op&opMaskJumpConst != opClsJump { return ri } switch ri.Op & opMaskJumpCond { case opJumpAlways: return Jump{Skip: ri.K} case opJumpEqual: if ri.Jt == 0 { return JumpIf{ Cond: JumpNotEqual, Val: ri.K, SkipTrue: ri.Jf, SkipFalse: 0, } } return JumpIf{ Cond: JumpEqual, Val: ri.K, SkipTrue: ri.Jt, SkipFalse: ri.Jf, } case opJumpGT: if ri.Jt == 0 { return JumpIf{ Cond: JumpLessOrEqual, Val: ri.K, SkipTrue: ri.Jf, SkipFalse: 0, } } return JumpIf{ Cond: JumpGreaterThan, Val: ri.K, SkipTrue: ri.Jt, SkipFalse: ri.Jf, } case opJumpGE: if ri.Jt == 0 { return JumpIf{ Cond: JumpLessThan, Val: ri.K, SkipTrue: ri.Jf, SkipFalse: 0, } } return JumpIf{ Cond: JumpGreaterOrEqual, Val: ri.K, SkipTrue: ri.Jt, SkipFalse: ri.Jf, } case opJumpSet: return JumpIf{ Cond: JumpBitsSet, Val: ri.K, SkipTrue: ri.Jt, SkipFalse: ri.Jf, } default: return ri } case opClsReturn: switch ri.Op { case opClsReturn | opRetSrcA: return RetA{} case opClsReturn | opRetSrcConstant: return RetConstant{Val: ri.K} default: return ri } case opClsMisc: switch ri.Op { case opClsMisc | opMiscTAX: return TAX{} case opClsMisc | opMiscTXA: return TXA{} default: return ri } default: panic("unreachable") // switch is exhaustive on the bit pattern } } // LoadConstant loads Val into register Dst. type LoadConstant struct { Dst Register Val uint32 } // Assemble implements the Instruction Assemble method. func (a LoadConstant) Assemble() (RawInstruction, error) { return assembleLoad(a.Dst, 4, opAddrModeImmediate, a.Val) } // String returns the the instruction in assembler notation. func (a LoadConstant) String() string { switch a.Dst { case RegA: return fmt.Sprintf("ld #%d", a.Val) case RegX: return fmt.Sprintf("ldx #%d", a.Val) default: return fmt.Sprintf("unknown instruction: %#v", a) } } // LoadScratch loads scratch[N] into register Dst. type LoadScratch struct { Dst Register N int // 0-15 } // Assemble implements the Instruction Assemble method. func (a LoadScratch) Assemble() (RawInstruction, error) { if a.N < 0 || a.N > 15 { return RawInstruction{}, fmt.Errorf("invalid scratch slot %d", a.N) } return assembleLoad(a.Dst, 4, opAddrModeScratch, uint32(a.N)) } // String returns the the instruction in assembler notation. func (a LoadScratch) String() string { switch a.Dst { case RegA: return fmt.Sprintf("ld M[%d]", a.N) case RegX: return fmt.Sprintf("ldx M[%d]", a.N) default: return fmt.Sprintf("unknown instruction: %#v", a) } } // LoadAbsolute loads packet[Off:Off+Size] as an integer value into // register A. type LoadAbsolute struct { Off uint32 Size int // 1, 2 or 4 } // Assemble implements the Instruction Assemble method. func (a LoadAbsolute) Assemble() (RawInstruction, error) { return assembleLoad(RegA, a.Size, opAddrModeAbsolute, a.Off) } // String returns the the instruction in assembler notation. func (a LoadAbsolute) String() string { switch a.Size { case 1: // byte return fmt.Sprintf("ldb [%d]", a.Off) case 2: // half word return fmt.Sprintf("ldh [%d]", a.Off) case 4: // word if a.Off > extOffset+0xffffffff { return LoadExtension{Num: Extension(a.Off + 0x1000)}.String() } return fmt.Sprintf("ld [%d]", a.Off) default: return fmt.Sprintf("unknown instruction: %#v", a) } } // LoadIndirect loads packet[X+Off:X+Off+Size] as an integer value // into register A. type LoadIndirect struct { Off uint32 Size int // 1, 2 or 4 } // Assemble implements the Instruction Assemble method. func (a LoadIndirect) Assemble() (RawInstruction, error) { return assembleLoad(RegA, a.Size, opAddrModeIndirect, a.Off) } // String returns the the instruction in assembler notation. func (a LoadIndirect) String() string { switch a.Size { case 1: // byte return fmt.Sprintf("ldb [x + %d]", a.Off) case 2: // half word return fmt.Sprintf("ldh [x + %d]", a.Off) case 4: // word return fmt.Sprintf("ld [x + %d]", a.Off) default: return fmt.Sprintf("unknown instruction: %#v", a) } } // LoadMemShift multiplies the first 4 bits of the byte at packet[Off] // by 4 and stores the result in register X. // // This instruction is mainly useful to load into X the length of an // IPv4 packet header in a single instruction, rather than have to do // the arithmetic on the header's first byte by hand. type LoadMemShift struct { Off uint32 } // Assemble implements the Instruction Assemble method. func (a LoadMemShift) Assemble() (RawInstruction, error) { return assembleLoad(RegX, 1, opAddrModeMemShift, a.Off) } // String returns the the instruction in assembler notation. func (a LoadMemShift) String() string { return fmt.Sprintf("ldx 4*([%d]&0xf)", a.Off) } // LoadExtension invokes a linux-specific extension and stores the // result in register A. type LoadExtension struct { Num Extension } // Assemble implements the Instruction Assemble method. func (a LoadExtension) Assemble() (RawInstruction, error) { if a.Num == ExtLen { return assembleLoad(RegA, 4, opAddrModePacketLen, 0) } return assembleLoad(RegA, 4, opAddrModeAbsolute, uint32(extOffset+a.Num)) } // String returns the the instruction in assembler notation. func (a LoadExtension) String() string { switch a.Num { case ExtLen: return "ld #len" case ExtProto: return "ld #proto" case ExtType: return "ld #type" case ExtPayloadOffset: return "ld #poff" case ExtInterfaceIndex: return "ld #ifidx" case ExtNetlinkAttr: return "ld #nla" case ExtNetlinkAttrNested: return "ld #nlan" case ExtMark: return "ld #mark" case ExtQueue: return "ld #queue" case ExtLinkLayerType: return "ld #hatype" case ExtRXHash: return "ld #rxhash" case ExtCPUID: return "ld #cpu" case ExtVLANTag: return "ld #vlan_tci" case ExtVLANTagPresent: return "ld #vlan_avail" case ExtVLANProto: return "ld #vlan_tpid" case ExtRand: return "ld #rand" default: return fmt.Sprintf("unknown instruction: %#v", a) } } // StoreScratch stores register Src into scratch[N]. type StoreScratch struct { Src Register N int // 0-15 } // Assemble implements the Instruction Assemble method. func (a StoreScratch) Assemble() (RawInstruction, error) { if a.N < 0 || a.N > 15 { return RawInstruction{}, fmt.Errorf("invalid scratch slot %d", a.N) } var op uint16 switch a.Src { case RegA: op = opClsStoreA case RegX: op = opClsStoreX default: return RawInstruction{}, fmt.Errorf("invalid source register %v", a.Src) } return RawInstruction{ Op: op, K: uint32(a.N), }, nil } // String returns the the instruction in assembler notation. func (a StoreScratch) String() string { switch a.Src { case RegA: return fmt.Sprintf("st M[%d]", a.N) case RegX: return fmt.Sprintf("stx M[%d]", a.N) default: return fmt.Sprintf("unknown instruction: %#v", a) } } // ALUOpConstant executes A = A <Op> Val. type ALUOpConstant struct { Op ALUOp Val uint32 } // Assemble implements the Instruction Assemble method. func (a ALUOpConstant) Assemble() (RawInstruction, error) { return RawInstruction{ Op: opClsALU | opALUSrcConstant | uint16(a.Op), K: a.Val, }, nil } // String returns the the instruction in assembler notation. func (a ALUOpConstant) String() string { switch a.Op { case ALUOpAdd: return fmt.Sprintf("add #%d", a.Val) case ALUOpSub: return fmt.Sprintf("sub #%d", a.Val) case ALUOpMul: return fmt.Sprintf("mul #%d", a.Val) case ALUOpDiv: return fmt.Sprintf("div #%d", a.Val) case ALUOpMod: return fmt.Sprintf("mod #%d", a.Val) case ALUOpAnd: return fmt.Sprintf("and #%d", a.Val) case ALUOpOr: return fmt.Sprintf("or #%d", a.Val) case ALUOpXor: return fmt.Sprintf("xor #%d", a.Val) case ALUOpShiftLeft: return fmt.Sprintf("lsh #%d", a.Val) case ALUOpShiftRight: return fmt.Sprintf("rsh #%d", a.Val) default: return fmt.Sprintf("unknown instruction: %#v", a) } } // ALUOpX executes A = A <Op> X type ALUOpX struct { Op ALUOp } // Assemble implements the Instruction Assemble method. func (a ALUOpX) Assemble() (RawInstruction, error) { return RawInstruction{ Op: opClsALU | opALUSrcX | uint16(a.Op), }, nil } // String returns the the instruction in assembler notation. func (a ALUOpX) String() string { switch a.Op { case ALUOpAdd: return "add x" case ALUOpSub: return "sub x" case ALUOpMul: return "mul x" case ALUOpDiv: return "div x" case ALUOpMod: return "mod x" case ALUOpAnd: return "and x" case ALUOpOr: return "or x" case ALUOpXor: return "xor x" case ALUOpShiftLeft: return "lsh x" case ALUOpShiftRight: return "rsh x" default: return fmt.Sprintf("unknown instruction: %#v", a) } } // NegateA executes A = -A. type NegateA struct{} // Assemble implements the Instruction Assemble method. func (a NegateA) Assemble() (RawInstruction, error) { return RawInstruction{ Op: opClsALU | uint16(aluOpNeg), }, nil } // String returns the the instruction in assembler notation. func (a NegateA) String() string { return fmt.Sprintf("neg") } // Jump skips the following Skip instructions in the program. type Jump struct { Skip uint32 } // Assemble implements the Instruction Assemble method. func (a Jump) Assemble() (RawInstruction, error) { return RawInstruction{ Op: opClsJump | opJumpAlways, K: a.Skip, }, nil } // String returns the the instruction in assembler notation. func (a Jump) String() string { return fmt.Sprintf("ja %d", a.Skip) } // JumpIf skips the following Skip instructions in the program if A // <Cond> Val is true. type JumpIf struct { Cond JumpTest Val uint32 SkipTrue uint8 SkipFalse uint8 } // Assemble implements the Instruction Assemble method. func (a JumpIf) Assemble() (RawInstruction, error) { var ( cond uint16 flip bool ) switch a.Cond { case JumpEqual: cond = opJumpEqual case JumpNotEqual: cond, flip = opJumpEqual, true case JumpGreaterThan: cond = opJumpGT case JumpLessThan: cond, flip = opJumpGE, true case JumpGreaterOrEqual: cond = opJumpGE case JumpLessOrEqual: cond, flip = opJumpGT, true case JumpBitsSet: cond = opJumpSet case JumpBitsNotSet: cond, flip = opJumpSet, true default: return RawInstruction{}, fmt.Errorf("unknown JumpTest %v", a.Cond) } jt, jf := a.SkipTrue, a.SkipFalse if flip { jt, jf = jf, jt } return RawInstruction{ Op: opClsJump | cond, Jt: jt, Jf: jf, K: a.Val, }, nil } // String returns the the instruction in assembler notation. func (a JumpIf) String() string { switch a.Cond { // K == A case JumpEqual: return conditionalJump(a, "jeq", "jneq") // K != A case JumpNotEqual: return fmt.Sprintf("jneq #%d,%d", a.Val, a.SkipTrue) // K > A case JumpGreaterThan: return conditionalJump(a, "jgt", "jle") // K < A case JumpLessThan: return fmt.Sprintf("jlt #%d,%d", a.Val, a.SkipTrue) // K >= A case JumpGreaterOrEqual: return conditionalJump(a, "jge", "jlt") // K <= A case JumpLessOrEqual: return fmt.Sprintf("jle #%d,%d", a.Val, a.SkipTrue) // K & A != 0 case JumpBitsSet: if a.SkipFalse > 0 { return fmt.Sprintf("jset #%d,%d,%d", a.Val, a.SkipTrue, a.SkipFalse) } return fmt.Sprintf("jset #%d,%d", a.Val, a.SkipTrue) // K & A == 0, there is no assembler instruction for JumpBitNotSet, use JumpBitSet and invert skips case JumpBitsNotSet: return JumpIf{Cond: JumpBitsSet, SkipTrue: a.SkipFalse, SkipFalse: a.SkipTrue, Val: a.Val}.String() default: return fmt.Sprintf("unknown instruction: %#v", a) } } func conditionalJump(inst JumpIf, positiveJump, negativeJump string) string { if inst.SkipTrue > 0 { if inst.SkipFalse > 0 { return fmt.Sprintf("%s #%d,%d,%d", positiveJump, inst.Val, inst.SkipTrue, inst.SkipFalse) } return fmt.Sprintf("%s #%d,%d", positiveJump, inst.Val, inst.SkipTrue) } return fmt.Sprintf("%s #%d,%d", negativeJump, inst.Val, inst.SkipFalse) } // RetA exits the BPF program, returning the value of register A. type RetA struct{} // Assemble implements the Instruction Assemble method. func (a RetA) Assemble() (RawInstruction, error) { return RawInstruction{ Op: opClsReturn | opRetSrcA, }, nil } // String returns the the instruction in assembler notation. func (a RetA) String() string { return fmt.Sprintf("ret a") } // RetConstant exits the BPF program, returning a constant value. type RetConstant struct { Val uint32 } // Assemble implements the Instruction Assemble method. func (a RetConstant) Assemble() (RawInstruction, error) { return RawInstruction{ Op: opClsReturn | opRetSrcConstant, K: a.Val, }, nil } // String returns the the instruction in assembler notation. func (a RetConstant) String() string { return fmt.Sprintf("ret #%d", a.Val) } // TXA copies the value of register X to register A. type TXA struct{} // Assemble implements the Instruction Assemble method. func (a TXA) Assemble() (RawInstruction, error) { return RawInstruction{ Op: opClsMisc | opMiscTXA, }, nil } // String returns the the instruction in assembler notation. func (a TXA) String() string { return fmt.Sprintf("txa") } // TAX copies the value of register A to register X. type TAX struct{} // Assemble implements the Instruction Assemble method. func (a TAX) Assemble() (RawInstruction, error) { return RawInstruction{ Op: opClsMisc | opMiscTAX, }, nil } // String returns the the instruction in assembler notation. func (a TAX) String() string { return fmt.Sprintf("tax") } func assembleLoad(dst Register, loadSize int, mode uint16, k uint32) (RawInstruction, error) { var ( cls uint16 sz uint16 ) switch dst { case RegA: cls = opClsLoadA case RegX: cls = opClsLoadX default: return RawInstruction{}, fmt.Errorf("invalid target register %v", dst) } switch loadSize { case 1: sz = opLoadWidth1 case 2: sz = opLoadWidth2 case 4: sz = opLoadWidth4 default: return RawInstruction{}, fmt.Errorf("invalid load byte length %d", sz) } return RawInstruction{ Op: cls | sz | mode, K: k, }, nil } ����������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/doc.go�����������������������������������������������������0000644�0610621�0607500�00000006217�13172163402�022164� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package bpf implements marshaling and unmarshaling of programs for the Berkeley Packet Filter virtual machine, and provides a Go implementation of the virtual machine. BPF's main use is to specify a packet filter for network taps, so that the kernel doesn't have to expensively copy every packet it sees to userspace. However, it's been repurposed to other areas where running user code in-kernel is needed. For example, Linux's seccomp uses BPF to apply security policies to system calls. For simplicity, this documentation refers only to packets, but other uses of BPF have their own data payloads. BPF programs run in a restricted virtual machine. It has almost no access to kernel functions, and while conditional branches are allowed, they can only jump forwards, to guarantee that there are no infinite loops. The virtual machine The BPF VM is an accumulator machine. Its main register, called register A, is an implicit source and destination in all arithmetic and logic operations. The machine also has 16 scratch registers for temporary storage, and an indirection register (register X) for indirect memory access. All registers are 32 bits wide. Each run of a BPF program is given one packet, which is placed in the VM's read-only "main memory". LoadAbsolute and LoadIndirect instructions can fetch up to 32 bits at a time into register A for examination. The goal of a BPF program is to produce and return a verdict (uint32), which tells the kernel what to do with the packet. In the context of packet filtering, the returned value is the number of bytes of the packet to forward to userspace, or 0 to ignore the packet. Other contexts like seccomp define their own return values. In order to simplify programs, attempts to read past the end of the packet terminate the program execution with a verdict of 0 (ignore packet). This means that the vast majority of BPF programs don't need to do any explicit bounds checking. In addition to the bytes of the packet, some BPF programs have access to extensions, which are essentially calls to kernel utility functions. Currently, the only extensions supported by this package are the Linux packet filter extensions. Examples This packet filter selects all ARP packets. bpf.Assemble([]bpf.Instruction{ // Load "EtherType" field from the ethernet header. bpf.LoadAbsolute{Off: 12, Size: 2}, // Skip over the next instruction if EtherType is not ARP. bpf.JumpIf{Cond: bpf.JumpNotEqual, Val: 0x0806, SkipTrue: 1}, // Verdict is "send up to 4k of the packet to userspace." bpf.RetConstant{Val: 4096}, // Verdict is "ignore packet." bpf.RetConstant{Val: 0}, }) This packet filter captures a random 1% sample of traffic. bpf.Assemble([]bpf.Instruction{ // Get a 32-bit random number from the Linux kernel. bpf.LoadExtension{Num: bpf.ExtRand}, // 1% dice roll? bpf.JumpIf{Cond: bpf.JumpLessThan, Val: 2^32/100, SkipFalse: 1}, // Capture. bpf.RetConstant{Val: 4096}, // Ignore. bpf.RetConstant{Val: 0}, }) */ package bpf // import "golang.org/x/net/bpf" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/constants.go�����������������������������������������������0000644�0610621�0607500�00000013632�13172163402�023432� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf // A Register is a register of the BPF virtual machine. type Register uint16 const ( // RegA is the accumulator register. RegA is always the // destination register of ALU operations. RegA Register = iota // RegX is the indirection register, used by LoadIndirect // operations. RegX ) // An ALUOp is an arithmetic or logic operation. type ALUOp uint16 // ALU binary operation types. const ( ALUOpAdd ALUOp = iota << 4 ALUOpSub ALUOpMul ALUOpDiv ALUOpOr ALUOpAnd ALUOpShiftLeft ALUOpShiftRight aluOpNeg // Not exported because it's the only unary ALU operation, and gets its own instruction type. ALUOpMod ALUOpXor ) // A JumpTest is a comparison operator used in conditional jumps. type JumpTest uint16 // Supported operators for conditional jumps. const ( // K == A JumpEqual JumpTest = iota // K != A JumpNotEqual // K > A JumpGreaterThan // K < A JumpLessThan // K >= A JumpGreaterOrEqual // K <= A JumpLessOrEqual // K & A != 0 JumpBitsSet // K & A == 0 JumpBitsNotSet ) // An Extension is a function call provided by the kernel that // performs advanced operations that are expensive or impossible // within the BPF virtual machine. // // Extensions are only implemented by the Linux kernel. // // TODO: should we prune this list? Some of these extensions seem // either broken or near-impossible to use correctly, whereas other // (len, random, ifindex) are quite useful. type Extension int // Extension functions available in the Linux kernel. const ( // extOffset is the negative maximum number of instructions used // to load instructions by overloading the K argument. extOffset = -0x1000 // ExtLen returns the length of the packet. ExtLen Extension = 1 // ExtProto returns the packet's L3 protocol type. ExtProto Extension = 0 // ExtType returns the packet's type (skb->pkt_type in the kernel) // // TODO: better documentation. How nice an API do we want to // provide for these esoteric extensions? ExtType Extension = 4 // ExtPayloadOffset returns the offset of the packet payload, or // the first protocol header that the kernel does not know how to // parse. ExtPayloadOffset Extension = 52 // ExtInterfaceIndex returns the index of the interface on which // the packet was received. ExtInterfaceIndex Extension = 8 // ExtNetlinkAttr returns the netlink attribute of type X at // offset A. ExtNetlinkAttr Extension = 12 // ExtNetlinkAttrNested returns the nested netlink attribute of // type X at offset A. ExtNetlinkAttrNested Extension = 16 // ExtMark returns the packet's mark value. ExtMark Extension = 20 // ExtQueue returns the packet's assigned hardware queue. ExtQueue Extension = 24 // ExtLinkLayerType returns the packet's hardware address type // (e.g. Ethernet, Infiniband). ExtLinkLayerType Extension = 28 // ExtRXHash returns the packets receive hash. // // TODO: figure out what this rxhash actually is. ExtRXHash Extension = 32 // ExtCPUID returns the ID of the CPU processing the current // packet. ExtCPUID Extension = 36 // ExtVLANTag returns the packet's VLAN tag. ExtVLANTag Extension = 44 // ExtVLANTagPresent returns non-zero if the packet has a VLAN // tag. // // TODO: I think this might be a lie: it reads bit 0x1000 of the // VLAN header, which changed meaning in recent revisions of the // spec - this extension may now return meaningless information. ExtVLANTagPresent Extension = 48 // ExtVLANProto returns 0x8100 if the frame has a VLAN header, // 0x88a8 if the frame has a "Q-in-Q" double VLAN header, or some // other value if no VLAN information is present. ExtVLANProto Extension = 60 // ExtRand returns a uniformly random uint32. ExtRand Extension = 56 ) // The following gives names to various bit patterns used in opcode construction. const ( opMaskCls uint16 = 0x7 // opClsLoad masks opMaskLoadDest = 0x01 opMaskLoadWidth = 0x18 opMaskLoadMode = 0xe0 // opClsALU opMaskOperandSrc = 0x08 opMaskOperator = 0xf0 // opClsJump opMaskJumpConst = 0x0f opMaskJumpCond = 0xf0 ) const ( // +---------------+-----------------+---+---+---+ // | AddrMode (3b) | LoadWidth (2b) | 0 | 0 | 0 | // +---------------+-----------------+---+---+---+ opClsLoadA uint16 = iota // +---------------+-----------------+---+---+---+ // | AddrMode (3b) | LoadWidth (2b) | 0 | 0 | 1 | // +---------------+-----------------+---+---+---+ opClsLoadX // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | // +---+---+---+---+---+---+---+---+ opClsStoreA // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | // +---+---+---+---+---+---+---+---+ opClsStoreX // +---------------+-----------------+---+---+---+ // | Operator (4b) | OperandSrc (1b) | 1 | 0 | 0 | // +---------------+-----------------+---+---+---+ opClsALU // +-----------------------------+---+---+---+---+ // | TestOperator (4b) | 0 | 1 | 0 | 1 | // +-----------------------------+---+---+---+---+ opClsJump // +---+-------------------------+---+---+---+---+ // | 0 | 0 | 0 | RetSrc (1b) | 0 | 1 | 1 | 0 | // +---+-------------------------+---+---+---+---+ opClsReturn // +---+-------------------------+---+---+---+---+ // | 0 | 0 | 0 | TXAorTAX (1b) | 0 | 1 | 1 | 1 | // +---+-------------------------+---+---+---+---+ opClsMisc ) const ( opAddrModeImmediate uint16 = iota << 5 opAddrModeAbsolute opAddrModeIndirect opAddrModeScratch opAddrModePacketLen // actually an extension, not an addressing mode. opAddrModeMemShift ) const ( opLoadWidth4 uint16 = iota << 3 opLoadWidth2 opLoadWidth1 ) // Operator defined by ALUOp* const ( opALUSrcConstant uint16 = iota << 3 opALUSrcX ) const ( opJumpAlways = iota << 4 opJumpEqual opJumpGT opJumpGE opJumpSet ) const ( opRetSrcConstant uint16 = iota << 4 opRetSrcA ) const ( opMiscTAX = 0x00 opMiscTXA = 0x80 ) ������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/bpf/asm.go�����������������������������������������������������0000644�0610621�0607500�00000002363�13172163402�022175� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bpf import "fmt" // Assemble converts insts into raw instructions suitable for loading // into a BPF virtual machine. // // Currently, no optimization is attempted, the assembled program flow // is exactly as provided. func Assemble(insts []Instruction) ([]RawInstruction, error) { ret := make([]RawInstruction, len(insts)) var err error for i, inst := range insts { ret[i], err = inst.Assemble() if err != nil { return nil, fmt.Errorf("assembling instruction %d: %s", i+1, err) } } return ret, nil } // Disassemble attempts to parse raw back into // Instructions. Unrecognized RawInstructions are assumed to be an // extension not implemented by this package, and are passed through // unchanged to the output. The allDecoded value reports whether insts // contains no RawInstructions. func Disassemble(raw []RawInstruction) (insts []Instruction, allDecoded bool) { insts = make([]Instruction, len(raw)) allDecoded = true for i, r := range raw { insts[i] = r.Disassemble() if _, ok := insts[i].(RawInstruction); ok { allDecoded = false } } return insts, allDecoded } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/README.md������������������������������������������������������0000644�0610621�0607500�00000001125�13172163402�021571� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go Networking This repository holds supplementary Go networking libraries. ## Download/Install The easiest way to install is to run `go get -u golang.org/x/net`. You can also manually git clone the repository to `$GOPATH/src/golang.org/x/net`. ## Report Issues / Send Patches This repository uses Gerrit for code changes. To learn how to submit changes to this repository, see https://golang.org/doc/contribute.html. The main issue tracker for the net repository is located at https://github.com/golang/go/issues. Prefix your issue with "x/net:" in the subject line, so it is easy to find. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/PATENTS��������������������������������������������������������0000644�0610621�0607500�00000002427�13172163402�021361� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Additional IP Rights Grant (Patents) "This implementation" means the copyrightable works distributed by Google as part of the Go project. Google hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer and otherwise run, modify and propagate the contents of this implementation of Go, where such license applies only to those patent claims, both currently owned or controlled by Google and acquired in the future, licensable by Google that are necessarily infringed by this implementation of Go. This grant does not include claims that would be infringed only as a consequence of further modification of this implementation. If you or your agent or exclusive licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that this implementation of Go or any code incorporated within this implementation of Go constitutes direct or contributory patent infringement, or inducement of patent infringement, then any patent rights granted to you under this License for this implementation of Go shall terminate as of the date such litigation is filed. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/LICENSE��������������������������������������������������������0000644�0610621�0607500�00000002707�13172163402�021326� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ���������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/CONTRIBUTORS���������������������������������������������������0000644�0610621�0607500�00000000252�13172163402�022172� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at http://tip.golang.org/CONTRIBUTORS. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/CONTRIBUTING.md������������������������������������������������0000644�0610621�0607500�00000002007�13172163402�022543� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Contributing to Go Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! ## Filing issues When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: 1. What version of Go are you using (`go version`)? 2. What operating system and processor architecture are you using? 3. What did you do? 4. What did you expect to see? 5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. ## Contributing code Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. **We do not accept GitHub pull requests** (we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/net/AUTHORS��������������������������������������������������������0000644�0610621�0607500�00000000255�13172163402�021365� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This source code refers to The Go Authors for copyright purposes. # The master list of authors is in the main Go distribution, # visible at http://tip.golang.org/AUTHORS. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021052� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/xts/��������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021670� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/xts/xts_test.go���������������������������������������������0000644�0610621�0607500�00000021570�13172163317�024101� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xts import ( "bytes" "crypto/aes" "encoding/hex" "testing" ) // These test vectors have been taken from IEEE P1619/D16, Annex B. var xtsTestVectors = []struct { key string sector uint64 plaintext string ciphertext string }{ { "0000000000000000000000000000000000000000000000000000000000000000", 0, "0000000000000000000000000000000000000000000000000000000000000000", "917cf69ebd68b2ec9b9fe9a3eadda692cd43d2f59598ed858c02c2652fbf922e", }, { "1111111111111111111111111111111122222222222222222222222222222222", 0x3333333333, "4444444444444444444444444444444444444444444444444444444444444444", "c454185e6a16936e39334038acef838bfb186fff7480adc4289382ecd6d394f0", }, { "fffefdfcfbfaf9f8f7f6f5f4f3f2f1f022222222222222222222222222222222", 0x3333333333, "4444444444444444444444444444444444444444444444444444444444444444", "af85336b597afc1a900b2eb21ec949d292df4c047e0b21532186a5971a227a89", }, { "2718281828459045235360287471352631415926535897932384626433832795", 0, "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", "27a7479befa1d476489f308cd4cfa6e2a96e4bbe3208ff25287dd3819616e89cc78cf7f5e543445f8333d8fa7f56000005279fa5d8b5e4ad40e736ddb4d35412328063fd2aab53e5ea1e0a9f332500a5df9487d07a5c92cc512c8866c7e860ce93fdf166a24912b422976146ae20ce846bb7dc9ba94a767aaef20c0d61ad02655ea92dc4c4e41a8952c651d33174be51a10c421110e6d81588ede82103a252d8a750e8768defffed9122810aaeb99f9172af82b604dc4b8e51bcb08235a6f4341332e4ca60482a4ba1a03b3e65008fc5da76b70bf1690db4eae29c5f1badd03c5ccf2a55d705ddcd86d449511ceb7ec30bf12b1fa35b913f9f747a8afd1b130e94bff94effd01a91735ca1726acd0b197c4e5b03393697e126826fb6bbde8ecc1e08298516e2c9ed03ff3c1b7860f6de76d4cecd94c8119855ef5297ca67e9f3e7ff72b1e99785ca0a7e7720c5b36dc6d72cac9574c8cbbc2f801e23e56fd344b07f22154beba0f08ce8891e643ed995c94d9a69c9f1b5f499027a78572aeebd74d20cc39881c213ee770b1010e4bea718846977ae119f7a023ab58cca0ad752afe656bb3c17256a9f6e9bf19fdd5a38fc82bbe872c5539edb609ef4f79c203ebb140f2e583cb2ad15b4aa5b655016a8449277dbd477ef2c8d6c017db738b18deb4a427d1923ce3ff262735779a418f20a282df920147beabe421ee5319d0568", }, { "2718281828459045235360287471352631415926535897932384626433832795", 1, "27a7479befa1d476489f308cd4cfa6e2a96e4bbe3208ff25287dd3819616e89cc78cf7f5e543445f8333d8fa7f56000005279fa5d8b5e4ad40e736ddb4d35412328063fd2aab53e5ea1e0a9f332500a5df9487d07a5c92cc512c8866c7e860ce93fdf166a24912b422976146ae20ce846bb7dc9ba94a767aaef20c0d61ad02655ea92dc4c4e41a8952c651d33174be51a10c421110e6d81588ede82103a252d8a750e8768defffed9122810aaeb99f9172af82b604dc4b8e51bcb08235a6f4341332e4ca60482a4ba1a03b3e65008fc5da76b70bf1690db4eae29c5f1badd03c5ccf2a55d705ddcd86d449511ceb7ec30bf12b1fa35b913f9f747a8afd1b130e94bff94effd01a91735ca1726acd0b197c4e5b03393697e126826fb6bbde8ecc1e08298516e2c9ed03ff3c1b7860f6de76d4cecd94c8119855ef5297ca67e9f3e7ff72b1e99785ca0a7e7720c5b36dc6d72cac9574c8cbbc2f801e23e56fd344b07f22154beba0f08ce8891e643ed995c94d9a69c9f1b5f499027a78572aeebd74d20cc39881c213ee770b1010e4bea718846977ae119f7a023ab58cca0ad752afe656bb3c17256a9f6e9bf19fdd5a38fc82bbe872c5539edb609ef4f79c203ebb140f2e583cb2ad15b4aa5b655016a8449277dbd477ef2c8d6c017db738b18deb4a427d1923ce3ff262735779a418f20a282df920147beabe421ee5319d0568", "264d3ca8512194fec312c8c9891f279fefdd608d0c027b60483a3fa811d65ee59d52d9e40ec5672d81532b38b6b089ce951f0f9c35590b8b978d175213f329bb1c2fd30f2f7f30492a61a532a79f51d36f5e31a7c9a12c286082ff7d2394d18f783e1a8e72c722caaaa52d8f065657d2631fd25bfd8e5baad6e527d763517501c68c5edc3cdd55435c532d7125c8614deed9adaa3acade5888b87bef641c4c994c8091b5bcd387f3963fb5bc37aa922fbfe3df4e5b915e6eb514717bdd2a74079a5073f5c4bfd46adf7d282e7a393a52579d11a028da4d9cd9c77124f9648ee383b1ac763930e7162a8d37f350b2f74b8472cf09902063c6b32e8c2d9290cefbd7346d1c779a0df50edcde4531da07b099c638e83a755944df2aef1aa31752fd323dcb710fb4bfbb9d22b925bc3577e1b8949e729a90bbafeacf7f7879e7b1147e28ba0bae940db795a61b15ecf4df8db07b824bb062802cc98a9545bb2aaeed77cb3fc6db15dcd7d80d7d5bc406c4970a3478ada8899b329198eb61c193fb6275aa8ca340344a75a862aebe92eee1ce032fd950b47d7704a3876923b4ad62844bf4a09c4dbe8b4397184b7471360c9564880aedddb9baa4af2e75394b08cd32ff479c57a07d3eab5d54de5f9738b8d27f27a9f0ab11799d7b7ffefb2704c95c6ad12c39f1e867a4b7b1d7818a4b753dfd2a89ccb45e001a03a867b187f225dd", }, { "27182818284590452353602874713526624977572470936999595749669676273141592653589793238462643383279502884197169399375105820974944592", 0xff, "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", "1c3b3a102f770386e4836c99e370cf9bea00803f5e482357a4ae12d414a3e63b5d31e276f8fe4a8d66b317f9ac683f44680a86ac35adfc3345befecb4bb188fd5776926c49a3095eb108fd1098baec70aaa66999a72a82f27d848b21d4a741b0c5cd4d5fff9dac89aeba122961d03a757123e9870f8acf1000020887891429ca2a3e7a7d7df7b10355165c8b9a6d0a7de8b062c4500dc4cd120c0f7418dae3d0b5781c34803fa75421c790dfe1de1834f280d7667b327f6c8cd7557e12ac3a0f93ec05c52e0493ef31a12d3d9260f79a289d6a379bc70c50841473d1a8cc81ec583e9645e07b8d9670655ba5bbcfecc6dc3966380ad8fecb17b6ba02469a020a84e18e8f84252070c13e9f1f289be54fbc481457778f616015e1327a02b140f1505eb309326d68378f8374595c849d84f4c333ec4423885143cb47bd71c5edae9be69a2ffeceb1bec9de244fbe15992b11b77c040f12bd8f6a975a44a0f90c29a9abc3d4d893927284c58754cce294529f8614dcd2aba991925fedc4ae74ffac6e333b93eb4aff0479da9a410e4450e0dd7ae4c6e2910900575da401fc07059f645e8b7e9bfdef33943054ff84011493c27b3429eaedb4ed5376441a77ed43851ad77f16f541dfd269d50d6a5f14fb0aab1cbb4c1550be97f7ab4066193c4caa773dad38014bd2092fa755c824bb5e54c4f36ffda9fcea70b9c6e693e148c151", }, } func fromHex(s string) []byte { ret, err := hex.DecodeString(s) if err != nil { panic("xts: invalid hex in test") } return ret } func TestXTS(t *testing.T) { for i, test := range xtsTestVectors { c, err := NewCipher(aes.NewCipher, fromHex(test.key)) if err != nil { t.Errorf("#%d: failed to create cipher: %s", i, err) continue } plaintext := fromHex(test.plaintext) ciphertext := make([]byte, len(plaintext)) c.Encrypt(ciphertext, plaintext, test.sector) expectedCiphertext := fromHex(test.ciphertext) if !bytes.Equal(ciphertext, expectedCiphertext) { t.Errorf("#%d: encrypted failed, got: %x, want: %x", i, ciphertext, expectedCiphertext) continue } decrypted := make([]byte, len(ciphertext)) c.Decrypt(decrypted, ciphertext, test.sector) if !bytes.Equal(decrypted, plaintext) { t.Errorf("#%d: decryption failed, got: %x, want: %x", i, decrypted, plaintext) } } } func TestShorterCiphertext(t *testing.T) { // Decrypt used to panic if the input was shorter than the output. See // https://go-review.googlesource.com/c/39954/ c, err := NewCipher(aes.NewCipher, make([]byte, 32)) if err != nil { t.Fatalf("NewCipher failed: %s", err) } plaintext := make([]byte, 32) encrypted := make([]byte, 48) decrypted := make([]byte, 48) c.Encrypt(encrypted, plaintext, 0) c.Decrypt(decrypted, encrypted[:len(plaintext)], 0) if !bytes.Equal(plaintext, decrypted[:len(plaintext)]) { t.Errorf("En/Decryption is not inverse") } } ����������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/xts/xts.go��������������������������������������������������0000644�0610621�0607500�00000010610�13172163317�023033� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package xts implements the XTS cipher mode as specified in IEEE P1619/D16. // // XTS mode is typically used for disk encryption, which presents a number of // novel problems that make more common modes inapplicable. The disk is // conceptually an array of sectors and we must be able to encrypt and decrypt // a sector in isolation. However, an attacker must not be able to transpose // two sectors of plaintext by transposing their ciphertext. // // XTS wraps a block cipher with Rogaway's XEX mode in order to build a // tweakable block cipher. This allows each sector to have a unique tweak and // effectively create a unique key for each sector. // // XTS does not provide any authentication. An attacker can manipulate the // ciphertext and randomise a block (16 bytes) of the plaintext. // // (Note: this package does not implement ciphertext-stealing so sectors must // be a multiple of 16 bytes.) package xts // import "golang.org/x/crypto/xts" import ( "crypto/cipher" "encoding/binary" "errors" ) // Cipher contains an expanded key structure. It doesn't contain mutable state // and therefore can be used concurrently. type Cipher struct { k1, k2 cipher.Block } // blockSize is the block size that the underlying cipher must have. XTS is // only defined for 16-byte ciphers. const blockSize = 16 // NewCipher creates a Cipher given a function for creating the underlying // block cipher (which must have a block size of 16 bytes). The key must be // twice the length of the underlying cipher's key. func NewCipher(cipherFunc func([]byte) (cipher.Block, error), key []byte) (c *Cipher, err error) { c = new(Cipher) if c.k1, err = cipherFunc(key[:len(key)/2]); err != nil { return } c.k2, err = cipherFunc(key[len(key)/2:]) if c.k1.BlockSize() != blockSize { err = errors.New("xts: cipher does not have a block size of 16") } return } // Encrypt encrypts a sector of plaintext and puts the result into ciphertext. // Plaintext and ciphertext must overlap entirely or not at all. // Sectors must be a multiple of 16 bytes and less than 2²ⴠbytes. func (c *Cipher) Encrypt(ciphertext, plaintext []byte, sectorNum uint64) { if len(ciphertext) < len(plaintext) { panic("xts: ciphertext is smaller than plaintext") } if len(plaintext)%blockSize != 0 { panic("xts: plaintext is not a multiple of the block size") } var tweak [blockSize]byte binary.LittleEndian.PutUint64(tweak[:8], sectorNum) c.k2.Encrypt(tweak[:], tweak[:]) for len(plaintext) > 0 { for j := range tweak { ciphertext[j] = plaintext[j] ^ tweak[j] } c.k1.Encrypt(ciphertext, ciphertext) for j := range tweak { ciphertext[j] ^= tweak[j] } plaintext = plaintext[blockSize:] ciphertext = ciphertext[blockSize:] mul2(&tweak) } } // Decrypt decrypts a sector of ciphertext and puts the result into plaintext. // Plaintext and ciphertext must overlap entirely or not at all. // Sectors must be a multiple of 16 bytes and less than 2²ⴠbytes. func (c *Cipher) Decrypt(plaintext, ciphertext []byte, sectorNum uint64) { if len(plaintext) < len(ciphertext) { panic("xts: plaintext is smaller than ciphertext") } if len(ciphertext)%blockSize != 0 { panic("xts: ciphertext is not a multiple of the block size") } var tweak [blockSize]byte binary.LittleEndian.PutUint64(tweak[:8], sectorNum) c.k2.Encrypt(tweak[:], tweak[:]) for len(ciphertext) > 0 { for j := range tweak { plaintext[j] = ciphertext[j] ^ tweak[j] } c.k1.Decrypt(plaintext, plaintext) for j := range tweak { plaintext[j] ^= tweak[j] } plaintext = plaintext[blockSize:] ciphertext = ciphertext[blockSize:] mul2(&tweak) } } // mul2 multiplies tweak by 2 in GF(2¹²â¸) with an irreducible polynomial of // x¹²⸠+ xâ· + x² + x + 1. func mul2(tweak *[blockSize]byte) { var carryIn byte for j := range tweak { carryOut := tweak[j] >> 7 tweak[j] = (tweak[j] << 1) + carryIn carryIn = carryOut } if carryIn != 0 { // If we have a carry bit then we need to subtract a multiple // of the irreducible polynomial (x¹²⸠+ xâ· + x² + x + 1). // By dropping the carry bit, we're subtracting the x^128 term // so all that remains is to subtract xâ· + x² + x + 1. // Subtraction (and addition) in this representation is just // XOR. tweak[0] ^= 1<<7 | 1<<2 | 1<<1 | 1 } } ������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/xtea/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022013� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/xtea/xtea_test.go�������������������������������������������0000644�0610621�0607500�00000016371�13172163317�024352� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xtea import ( "testing" ) // A sample test key for when we just want to initialize a cipher var testKey = []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF} // Test that the block size for XTEA is correct func TestBlocksize(t *testing.T) { if BlockSize != 8 { t.Errorf("BlockSize constant - expected 8, got %d", BlockSize) return } c, err := NewCipher(testKey) if err != nil { t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err) return } result := c.BlockSize() if result != 8 { t.Errorf("BlockSize function - expected 8, got %d", result) return } } // A series of test values to confirm that the Cipher.table array was initialized correctly var testTable = []uint32{ 0x00112233, 0x6B1568B8, 0xE28CE030, 0xC5089E2D, 0xC5089E2D, 0x1EFBD3A2, 0xA7845C2A, 0x78EF0917, 0x78EF0917, 0x172682D0, 0x5B6AC714, 0x822AC955, 0x3DE68511, 0xDC1DFECA, 0x2062430E, 0x3611343F, 0xF1CCEFFB, 0x900469B4, 0xD448ADF8, 0x2E3BE36D, 0xB6C46BF5, 0x994029F2, 0x994029F2, 0xF3335F67, 0x6AAAD6DF, 0x4D2694DC, 0x4D2694DC, 0xEB5E0E95, 0x2FA252D9, 0x4551440A, 0x121E10D6, 0xB0558A8F, 0xE388BDC3, 0x0A48C004, 0xC6047BC0, 0x643BF579, 0xA88039BD, 0x02736F32, 0x8AFBF7BA, 0x5C66A4A7, 0x5C66A4A7, 0xC76AEB2C, 0x3EE262A4, 0x215E20A1, 0x215E20A1, 0x7B515616, 0x03D9DE9E, 0x1988CFCF, 0xD5448B8B, 0x737C0544, 0xB7C04988, 0xDE804BC9, 0x9A3C0785, 0x3873813E, 0x7CB7C582, 0xD6AAFAF7, 0x4E22726F, 0x309E306C, 0x309E306C, 0x8A9165E1, 0x1319EE69, 0xF595AC66, 0xF595AC66, 0x4F88E1DB, } // Test that the cipher context is initialized correctly func TestCipherInit(t *testing.T) { c, err := NewCipher(testKey) if err != nil { t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err) return } for i := 0; i < len(c.table); i++ { if c.table[i] != testTable[i] { t.Errorf("NewCipher() failed to initialize Cipher.table[%d] correctly. Expected %08X, got %08X", i, testTable[i], c.table[i]) break } } } // Test that invalid key sizes return an error func TestInvalidKeySize(t *testing.T) { // Test a long key key := []byte{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, } _, err := NewCipher(key) if err == nil { t.Errorf("Invalid key size %d didn't result in an error.", len(key)) } // Test a short key key = []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77} _, err = NewCipher(key) if err == nil { t.Errorf("Invalid key size %d didn't result in an error.", len(key)) } } // Test that we can correctly decode some bytes we have encoded func TestEncodeDecode(t *testing.T) { original := []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF} input := original output := make([]byte, BlockSize) c, err := NewCipher(testKey) if err != nil { t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err) return } // Encrypt the input block c.Encrypt(output, input) // Check that the output does not match the input differs := false for i := 0; i < len(input); i++ { if output[i] != input[i] { differs = true break } } if differs == false { t.Error("Cipher.Encrypt: Failed to encrypt the input block.") return } // Decrypt the block we just encrypted input = output output = make([]byte, BlockSize) c.Decrypt(output, input) // Check that the output from decrypt matches our initial input for i := 0; i < len(input); i++ { if output[i] != original[i] { t.Errorf("Decrypted byte %d differed. Expected %02X, got %02X\n", i, original[i], output[i]) return } } } // Test Vectors type CryptTest struct { key []byte plainText []byte cipherText []byte } var CryptTests = []CryptTest{ // These were sourced from http://www.freemedialibrary.com/index.php/XTEA_test_vectors { []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, []byte{0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48}, []byte{0x49, 0x7d, 0xf3, 0xd0, 0x72, 0x61, 0x2c, 0xb5}, }, { []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, []byte{0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41}, []byte{0xe7, 0x8f, 0x2d, 0x13, 0x74, 0x43, 0x41, 0xd8}, }, { []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, []byte{0x5a, 0x5b, 0x6e, 0x27, 0x89, 0x48, 0xd7, 0x7f}, []byte{0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41}, }, { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48}, []byte{0xa0, 0x39, 0x05, 0x89, 0xf8, 0xb8, 0xef, 0xa5}, }, { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41}, []byte{0xed, 0x23, 0x37, 0x5a, 0x82, 0x1a, 0x8c, 0x2d}, }, { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x70, 0xe1, 0x22, 0x5d, 0x6e, 0x4e, 0x76, 0x55}, []byte{0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41}, }, // These vectors are from http://wiki.secondlife.com/wiki/XTEA_Strong_Encryption_Implementation#Bouncy_Castle_C.23_API { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0xDE, 0xE9, 0xD4, 0xD8, 0xF7, 0x13, 0x1E, 0xD9}, }, { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, []byte{0x06, 0x5C, 0x1B, 0x89, 0x75, 0xC6, 0xA8, 0x16}, }, { []byte{0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78, 0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x1F, 0xF9, 0xA0, 0x26, 0x1A, 0xC6, 0x42, 0x64}, }, { []byte{0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78, 0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A}, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, []byte{0x8C, 0x67, 0x15, 0x5B, 0x2E, 0xF9, 0x1E, 0xAD}, }, } // Test encryption func TestCipherEncrypt(t *testing.T) { for i, tt := range CryptTests { c, err := NewCipher(tt.key) if err != nil { t.Errorf("NewCipher(%d bytes), vector %d = %s", len(tt.key), i, err) continue } out := make([]byte, len(tt.plainText)) c.Encrypt(out, tt.plainText) for j := 0; j < len(out); j++ { if out[j] != tt.cipherText[j] { t.Errorf("Cipher.Encrypt %d: out[%d] = %02X, expected %02X", i, j, out[j], tt.cipherText[j]) break } } } } // Test decryption func TestCipherDecrypt(t *testing.T) { for i, tt := range CryptTests { c, err := NewCipher(tt.key) if err != nil { t.Errorf("NewCipher(%d bytes), vector %d = %s", len(tt.key), i, err) continue } out := make([]byte, len(tt.cipherText)) c.Decrypt(out, tt.cipherText) for j := 0; j < len(out); j++ { if out[j] != tt.plainText[j] { t.Errorf("Cipher.Decrypt %d: out[%d] = %02X, expected %02X", i, j, out[j], tt.plainText[j]) break } } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/xtea/cipher.go����������������������������������������������0000644�0610621�0607500�00000004604�13172163317�023620� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package xtea implements XTEA encryption, as defined in Needham and Wheeler's // 1997 technical report, "Tea extensions." package xtea // import "golang.org/x/crypto/xtea" // For details, see http://www.cix.co.uk/~klockstone/xtea.pdf import "strconv" // The XTEA block size in bytes. const BlockSize = 8 // A Cipher is an instance of an XTEA cipher using a particular key. // table contains a series of precalculated values that are used each round. type Cipher struct { table [64]uint32 } type KeySizeError int func (k KeySizeError) Error() string { return "crypto/xtea: invalid key size " + strconv.Itoa(int(k)) } // NewCipher creates and returns a new Cipher. // The key argument should be the XTEA key. // XTEA only supports 128 bit (16 byte) keys. func NewCipher(key []byte) (*Cipher, error) { k := len(key) switch k { default: return nil, KeySizeError(k) case 16: break } c := new(Cipher) initCipher(c, key) return c, nil } // BlockSize returns the XTEA block size, 8 bytes. // It is necessary to satisfy the Block interface in the // package "crypto/cipher". func (c *Cipher) BlockSize() int { return BlockSize } // Encrypt encrypts the 8 byte buffer src using the key and stores the result in dst. // Note that for amounts of data larger than a block, // it is not safe to just call Encrypt on successive blocks; // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). func (c *Cipher) Encrypt(dst, src []byte) { encryptBlock(c, dst, src) } // Decrypt decrypts the 8 byte buffer src using the key k and stores the result in dst. func (c *Cipher) Decrypt(dst, src []byte) { decryptBlock(c, dst, src) } // initCipher initializes the cipher context by creating a look up table // of precalculated values that are based on the key. func initCipher(c *Cipher, key []byte) { // Load the key into four uint32s var k [4]uint32 for i := 0; i < len(k); i++ { j := i << 2 // Multiply by 4 k[i] = uint32(key[j+0])<<24 | uint32(key[j+1])<<16 | uint32(key[j+2])<<8 | uint32(key[j+3]) } // Precalculate the table const delta = 0x9E3779B9 var sum uint32 = 0 // Two rounds of XTEA applied per loop for i := 0; i < numRounds; { c.table[i] = sum + k[sum&3] i++ sum += delta c.table[i] = sum + k[(sum>>11)&3] i++ } } ����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/xtea/block.go�����������������������������������������������0000644�0610621�0607500�00000003417�13172163317�023441� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Implementation adapted from Needham and Wheeler's paper: http://www.cix.co.uk/~klockstone/xtea.pdf A precalculated look up table is used during encryption/decryption for values that are based purely on the key. */ package xtea // XTEA is based on 64 rounds. const numRounds = 64 // blockToUint32 reads an 8 byte slice into two uint32s. // The block is treated as big endian. func blockToUint32(src []byte) (uint32, uint32) { r0 := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r1 := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) return r0, r1 } // uint32ToBlock writes two uint32s into an 8 byte data block. // Values are written as big endian. func uint32ToBlock(v0, v1 uint32, dst []byte) { dst[0] = byte(v0 >> 24) dst[1] = byte(v0 >> 16) dst[2] = byte(v0 >> 8) dst[3] = byte(v0) dst[4] = byte(v1 >> 24) dst[5] = byte(v1 >> 16) dst[6] = byte(v1 >> 8) dst[7] = byte(v1 >> 0) } // encryptBlock encrypts a single 8 byte block using XTEA. func encryptBlock(c *Cipher, dst, src []byte) { v0, v1 := blockToUint32(src) // Two rounds of XTEA applied per loop for i := 0; i < numRounds; { v0 += ((v1<<4 ^ v1>>5) + v1) ^ c.table[i] i++ v1 += ((v0<<4 ^ v0>>5) + v0) ^ c.table[i] i++ } uint32ToBlock(v0, v1, dst) } // decryptBlock decrypt a single 8 byte block using XTEA. func decryptBlock(c *Cipher, dst, src []byte) { v0, v1 := blockToUint32(src) // Two rounds of XTEA applied per loop for i := numRounds; i > 0; { i-- v1 -= ((v0<<4 ^ v0>>5) + v0) ^ c.table[i] i-- v0 -= ((v1<<4 ^ v1>>5) + v1) ^ c.table[i] } uint32ToBlock(v0, v1, dst) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/twofish/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022535� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/twofish/twofish_test.go�������������������������������������0000644�0610621�0607500�00000011365�13172163317�025614� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package twofish import ( "bytes" "testing" ) var qbox = [2][4][16]byte{ { {0x8, 0x1, 0x7, 0xD, 0x6, 0xF, 0x3, 0x2, 0x0, 0xB, 0x5, 0x9, 0xE, 0xC, 0xA, 0x4}, {0xE, 0xC, 0xB, 0x8, 0x1, 0x2, 0x3, 0x5, 0xF, 0x4, 0xA, 0x6, 0x7, 0x0, 0x9, 0xD}, {0xB, 0xA, 0x5, 0xE, 0x6, 0xD, 0x9, 0x0, 0xC, 0x8, 0xF, 0x3, 0x2, 0x4, 0x7, 0x1}, {0xD, 0x7, 0xF, 0x4, 0x1, 0x2, 0x6, 0xE, 0x9, 0xB, 0x3, 0x0, 0x8, 0x5, 0xC, 0xA}, }, { {0x2, 0x8, 0xB, 0xD, 0xF, 0x7, 0x6, 0xE, 0x3, 0x1, 0x9, 0x4, 0x0, 0xA, 0xC, 0x5}, {0x1, 0xE, 0x2, 0xB, 0x4, 0xC, 0x3, 0x7, 0x6, 0xD, 0xA, 0x5, 0xF, 0x9, 0x0, 0x8}, {0x4, 0xC, 0x7, 0x5, 0x1, 0x6, 0x9, 0xA, 0x0, 0xE, 0xD, 0x8, 0x2, 0xB, 0x3, 0xF}, {0xB, 0x9, 0x5, 0x1, 0xC, 0x3, 0xD, 0xE, 0x6, 0x4, 0x7, 0xF, 0x2, 0x0, 0x8, 0xA}, }, } // genSbox generates the variable sbox func genSbox(qi int, x byte) byte { a0, b0 := x/16, x%16 for i := 0; i < 2; i++ { a1 := a0 ^ b0 b1 := (a0 ^ ((b0 << 3) | (b0 >> 1)) ^ (a0 << 3)) & 15 a0 = qbox[qi][2*i][a1] b0 = qbox[qi][2*i+1][b1] } return (b0 << 4) + a0 } func TestSbox(t *testing.T) { for n := range sbox { for m := range sbox[n] { if genSbox(n, byte(m)) != sbox[n][m] { t.Errorf("#%d|%d: sbox value = %d want %d", n, m, sbox[n][m], genSbox(n, byte(m))) } } } } var testVectors = []struct { key []byte dec []byte enc []byte }{ // These tests are extracted from LibTom { []byte{0x9F, 0x58, 0x9F, 0x5C, 0xF6, 0x12, 0x2C, 0x32, 0xB6, 0xBF, 0xEC, 0x2F, 0x2A, 0xE8, 0xC3, 0x5A}, []byte{0xD4, 0x91, 0xDB, 0x16, 0xE7, 0xB1, 0xC3, 0x9E, 0x86, 0xCB, 0x08, 0x6B, 0x78, 0x9F, 0x54, 0x19}, []byte{0x01, 0x9F, 0x98, 0x09, 0xDE, 0x17, 0x11, 0x85, 0x8F, 0xAA, 0xC3, 0xA3, 0xBA, 0x20, 0xFB, 0xC3}, }, { []byte{0x88, 0xB2, 0xB2, 0x70, 0x6B, 0x10, 0x5E, 0x36, 0xB4, 0x46, 0xBB, 0x6D, 0x73, 0x1A, 0x1E, 0x88, 0xEF, 0xA7, 0x1F, 0x78, 0x89, 0x65, 0xBD, 0x44}, []byte{0x39, 0xDA, 0x69, 0xD6, 0xBA, 0x49, 0x97, 0xD5, 0x85, 0xB6, 0xDC, 0x07, 0x3C, 0xA3, 0x41, 0xB2}, []byte{0x18, 0x2B, 0x02, 0xD8, 0x14, 0x97, 0xEA, 0x45, 0xF9, 0xDA, 0xAC, 0xDC, 0x29, 0x19, 0x3A, 0x65}, }, { []byte{0xD4, 0x3B, 0xB7, 0x55, 0x6E, 0xA3, 0x2E, 0x46, 0xF2, 0xA2, 0x82, 0xB7, 0xD4, 0x5B, 0x4E, 0x0D, 0x57, 0xFF, 0x73, 0x9D, 0x4D, 0xC9, 0x2C, 0x1B, 0xD7, 0xFC, 0x01, 0x70, 0x0C, 0xC8, 0x21, 0x6F}, []byte{0x90, 0xAF, 0xE9, 0x1B, 0xB2, 0x88, 0x54, 0x4F, 0x2C, 0x32, 0xDC, 0x23, 0x9B, 0x26, 0x35, 0xE6}, []byte{0x6C, 0xB4, 0x56, 0x1C, 0x40, 0xBF, 0x0A, 0x97, 0x05, 0x93, 0x1C, 0xB6, 0xD4, 0x08, 0xE7, 0xFA}, }, // These tests are derived from https://www.schneier.com/code/ecb_ival.txt { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x9F, 0x58, 0x9F, 0x5C, 0xF6, 0x12, 0x2C, 0x32, 0xB6, 0xBF, 0xEC, 0x2F, 0x2A, 0xE8, 0xC3, 0x5A}, }, { []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, }, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0xCF, 0xD1, 0xD2, 0xE5, 0xA9, 0xBE, 0x9C, 0xDF, 0x50, 0x1F, 0x13, 0xB8, 0x92, 0xBD, 0x22, 0x48}, }, { []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, }, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x37, 0x52, 0x7B, 0xE0, 0x05, 0x23, 0x34, 0xB8, 0x9F, 0x0C, 0xFC, 0xCA, 0xE8, 0x7C, 0xFA, 0x20}, }, } func TestCipher(t *testing.T) { for n, tt := range testVectors { // Test if the plaintext (dec) is encrypts to the given // ciphertext (enc) using the given key. Test also if enc can // be decrypted again into dec. c, err := NewCipher(tt.key) if err != nil { t.Errorf("#%d: NewCipher: %v", n, err) return } buf := make([]byte, 16) c.Encrypt(buf, tt.dec) if !bytes.Equal(buf, tt.enc) { t.Errorf("#%d: encrypt = %x want %x", n, buf, tt.enc) } c.Decrypt(buf, tt.enc) if !bytes.Equal(buf, tt.dec) { t.Errorf("#%d: decrypt = %x want %x", n, buf, tt.dec) } // Test that 16 zero bytes, encrypted 1000 times then decrypted // 1000 times results in zero bytes again. zero := make([]byte, 16) buf = make([]byte, 16) for i := 0; i < 1000; i++ { c.Encrypt(buf, buf) } for i := 0; i < 1000; i++ { c.Decrypt(buf, buf) } if !bytes.Equal(buf, zero) { t.Errorf("#%d: encrypt/decrypt 1000: have %x want %x", n, buf, zero) } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/twofish/twofish.go������������������������������������������0000644�0610621�0607500�00000027277�13172163317�024566� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package twofish implements Bruce Schneier's Twofish encryption algorithm. package twofish // import "golang.org/x/crypto/twofish" // Twofish is defined in https://www.schneier.com/paper-twofish-paper.pdf [TWOFISH] // This code is a port of the LibTom C implementation. // See http://libtom.org/?page=features&newsitems=5&whatfile=crypt. // LibTomCrypt is free for all purposes under the public domain. // It was heavily inspired by the go blowfish package. import "strconv" // BlockSize is the constant block size of Twofish. const BlockSize = 16 const mdsPolynomial = 0x169 // x^8 + x^6 + x^5 + x^3 + 1, see [TWOFISH] 4.2 const rsPolynomial = 0x14d // x^8 + x^6 + x^3 + x^2 + 1, see [TWOFISH] 4.3 // A Cipher is an instance of Twofish encryption using a particular key. type Cipher struct { s [4][256]uint32 k [40]uint32 } type KeySizeError int func (k KeySizeError) Error() string { return "crypto/twofish: invalid key size " + strconv.Itoa(int(k)) } // NewCipher creates and returns a Cipher. // The key argument should be the Twofish key, 16, 24 or 32 bytes. func NewCipher(key []byte) (*Cipher, error) { keylen := len(key) if keylen != 16 && keylen != 24 && keylen != 32 { return nil, KeySizeError(keylen) } // k is the number of 64 bit words in key k := keylen / 8 // Create the S[..] words var S [4 * 4]byte for i := 0; i < k; i++ { // Computes [y0 y1 y2 y3] = rs . [x0 x1 x2 x3 x4 x5 x6 x7] for j, rsRow := range rs { for k, rsVal := range rsRow { S[4*i+j] ^= gfMult(key[8*i+k], rsVal, rsPolynomial) } } } // Calculate subkeys c := new(Cipher) var tmp [4]byte for i := byte(0); i < 20; i++ { // A = h(p * 2x, Me) for j := range tmp { tmp[j] = 2 * i } A := h(tmp[:], key, 0) // B = rolc(h(p * (2x + 1), Mo), 8) for j := range tmp { tmp[j] = 2*i + 1 } B := h(tmp[:], key, 1) B = rol(B, 8) c.k[2*i] = A + B // K[2i+1] = (A + 2B) <<< 9 c.k[2*i+1] = rol(2*B+A, 9) } // Calculate sboxes switch k { case 2: for i := range c.s[0] { c.s[0][i] = mdsColumnMult(sbox[1][sbox[0][sbox[0][byte(i)]^S[0]]^S[4]], 0) c.s[1][i] = mdsColumnMult(sbox[0][sbox[0][sbox[1][byte(i)]^S[1]]^S[5]], 1) c.s[2][i] = mdsColumnMult(sbox[1][sbox[1][sbox[0][byte(i)]^S[2]]^S[6]], 2) c.s[3][i] = mdsColumnMult(sbox[0][sbox[1][sbox[1][byte(i)]^S[3]]^S[7]], 3) } case 3: for i := range c.s[0] { c.s[0][i] = mdsColumnMult(sbox[1][sbox[0][sbox[0][sbox[1][byte(i)]^S[0]]^S[4]]^S[8]], 0) c.s[1][i] = mdsColumnMult(sbox[0][sbox[0][sbox[1][sbox[1][byte(i)]^S[1]]^S[5]]^S[9]], 1) c.s[2][i] = mdsColumnMult(sbox[1][sbox[1][sbox[0][sbox[0][byte(i)]^S[2]]^S[6]]^S[10]], 2) c.s[3][i] = mdsColumnMult(sbox[0][sbox[1][sbox[1][sbox[0][byte(i)]^S[3]]^S[7]]^S[11]], 3) } default: for i := range c.s[0] { c.s[0][i] = mdsColumnMult(sbox[1][sbox[0][sbox[0][sbox[1][sbox[1][byte(i)]^S[0]]^S[4]]^S[8]]^S[12]], 0) c.s[1][i] = mdsColumnMult(sbox[0][sbox[0][sbox[1][sbox[1][sbox[0][byte(i)]^S[1]]^S[5]]^S[9]]^S[13]], 1) c.s[2][i] = mdsColumnMult(sbox[1][sbox[1][sbox[0][sbox[0][sbox[0][byte(i)]^S[2]]^S[6]]^S[10]]^S[14]], 2) c.s[3][i] = mdsColumnMult(sbox[0][sbox[1][sbox[1][sbox[0][sbox[1][byte(i)]^S[3]]^S[7]]^S[11]]^S[15]], 3) } } return c, nil } // BlockSize returns the Twofish block size, 16 bytes. func (c *Cipher) BlockSize() int { return BlockSize } // store32l stores src in dst in little-endian form. func store32l(dst []byte, src uint32) { dst[0] = byte(src) dst[1] = byte(src >> 8) dst[2] = byte(src >> 16) dst[3] = byte(src >> 24) return } // load32l reads a little-endian uint32 from src. func load32l(src []byte) uint32 { return uint32(src[0]) | uint32(src[1])<<8 | uint32(src[2])<<16 | uint32(src[3])<<24 } // rol returns x after a left circular rotation of y bits. func rol(x, y uint32) uint32 { return (x << (y & 31)) | (x >> (32 - (y & 31))) } // ror returns x after a right circular rotation of y bits. func ror(x, y uint32) uint32 { return (x >> (y & 31)) | (x << (32 - (y & 31))) } // The RS matrix. See [TWOFISH] 4.3 var rs = [4][8]byte{ {0x01, 0xA4, 0x55, 0x87, 0x5A, 0x58, 0xDB, 0x9E}, {0xA4, 0x56, 0x82, 0xF3, 0x1E, 0xC6, 0x68, 0xE5}, {0x02, 0xA1, 0xFC, 0xC1, 0x47, 0xAE, 0x3D, 0x19}, {0xA4, 0x55, 0x87, 0x5A, 0x58, 0xDB, 0x9E, 0x03}, } // sbox tables var sbox = [2][256]byte{ { 0xa9, 0x67, 0xb3, 0xe8, 0x04, 0xfd, 0xa3, 0x76, 0x9a, 0x92, 0x80, 0x78, 0xe4, 0xdd, 0xd1, 0x38, 0x0d, 0xc6, 0x35, 0x98, 0x18, 0xf7, 0xec, 0x6c, 0x43, 0x75, 0x37, 0x26, 0xfa, 0x13, 0x94, 0x48, 0xf2, 0xd0, 0x8b, 0x30, 0x84, 0x54, 0xdf, 0x23, 0x19, 0x5b, 0x3d, 0x59, 0xf3, 0xae, 0xa2, 0x82, 0x63, 0x01, 0x83, 0x2e, 0xd9, 0x51, 0x9b, 0x7c, 0xa6, 0xeb, 0xa5, 0xbe, 0x16, 0x0c, 0xe3, 0x61, 0xc0, 0x8c, 0x3a, 0xf5, 0x73, 0x2c, 0x25, 0x0b, 0xbb, 0x4e, 0x89, 0x6b, 0x53, 0x6a, 0xb4, 0xf1, 0xe1, 0xe6, 0xbd, 0x45, 0xe2, 0xf4, 0xb6, 0x66, 0xcc, 0x95, 0x03, 0x56, 0xd4, 0x1c, 0x1e, 0xd7, 0xfb, 0xc3, 0x8e, 0xb5, 0xe9, 0xcf, 0xbf, 0xba, 0xea, 0x77, 0x39, 0xaf, 0x33, 0xc9, 0x62, 0x71, 0x81, 0x79, 0x09, 0xad, 0x24, 0xcd, 0xf9, 0xd8, 0xe5, 0xc5, 0xb9, 0x4d, 0x44, 0x08, 0x86, 0xe7, 0xa1, 0x1d, 0xaa, 0xed, 0x06, 0x70, 0xb2, 0xd2, 0x41, 0x7b, 0xa0, 0x11, 0x31, 0xc2, 0x27, 0x90, 0x20, 0xf6, 0x60, 0xff, 0x96, 0x5c, 0xb1, 0xab, 0x9e, 0x9c, 0x52, 0x1b, 0x5f, 0x93, 0x0a, 0xef, 0x91, 0x85, 0x49, 0xee, 0x2d, 0x4f, 0x8f, 0x3b, 0x47, 0x87, 0x6d, 0x46, 0xd6, 0x3e, 0x69, 0x64, 0x2a, 0xce, 0xcb, 0x2f, 0xfc, 0x97, 0x05, 0x7a, 0xac, 0x7f, 0xd5, 0x1a, 0x4b, 0x0e, 0xa7, 0x5a, 0x28, 0x14, 0x3f, 0x29, 0x88, 0x3c, 0x4c, 0x02, 0xb8, 0xda, 0xb0, 0x17, 0x55, 0x1f, 0x8a, 0x7d, 0x57, 0xc7, 0x8d, 0x74, 0xb7, 0xc4, 0x9f, 0x72, 0x7e, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34, 0x6e, 0x50, 0xde, 0x68, 0x65, 0xbc, 0xdb, 0xf8, 0xc8, 0xa8, 0x2b, 0x40, 0xdc, 0xfe, 0x32, 0xa4, 0xca, 0x10, 0x21, 0xf0, 0xd3, 0x5d, 0x0f, 0x00, 0x6f, 0x9d, 0x36, 0x42, 0x4a, 0x5e, 0xc1, 0xe0, }, { 0x75, 0xf3, 0xc6, 0xf4, 0xdb, 0x7b, 0xfb, 0xc8, 0x4a, 0xd3, 0xe6, 0x6b, 0x45, 0x7d, 0xe8, 0x4b, 0xd6, 0x32, 0xd8, 0xfd, 0x37, 0x71, 0xf1, 0xe1, 0x30, 0x0f, 0xf8, 0x1b, 0x87, 0xfa, 0x06, 0x3f, 0x5e, 0xba, 0xae, 0x5b, 0x8a, 0x00, 0xbc, 0x9d, 0x6d, 0xc1, 0xb1, 0x0e, 0x80, 0x5d, 0xd2, 0xd5, 0xa0, 0x84, 0x07, 0x14, 0xb5, 0x90, 0x2c, 0xa3, 0xb2, 0x73, 0x4c, 0x54, 0x92, 0x74, 0x36, 0x51, 0x38, 0xb0, 0xbd, 0x5a, 0xfc, 0x60, 0x62, 0x96, 0x6c, 0x42, 0xf7, 0x10, 0x7c, 0x28, 0x27, 0x8c, 0x13, 0x95, 0x9c, 0xc7, 0x24, 0x46, 0x3b, 0x70, 0xca, 0xe3, 0x85, 0xcb, 0x11, 0xd0, 0x93, 0xb8, 0xa6, 0x83, 0x20, 0xff, 0x9f, 0x77, 0xc3, 0xcc, 0x03, 0x6f, 0x08, 0xbf, 0x40, 0xe7, 0x2b, 0xe2, 0x79, 0x0c, 0xaa, 0x82, 0x41, 0x3a, 0xea, 0xb9, 0xe4, 0x9a, 0xa4, 0x97, 0x7e, 0xda, 0x7a, 0x17, 0x66, 0x94, 0xa1, 0x1d, 0x3d, 0xf0, 0xde, 0xb3, 0x0b, 0x72, 0xa7, 0x1c, 0xef, 0xd1, 0x53, 0x3e, 0x8f, 0x33, 0x26, 0x5f, 0xec, 0x76, 0x2a, 0x49, 0x81, 0x88, 0xee, 0x21, 0xc4, 0x1a, 0xeb, 0xd9, 0xc5, 0x39, 0x99, 0xcd, 0xad, 0x31, 0x8b, 0x01, 0x18, 0x23, 0xdd, 0x1f, 0x4e, 0x2d, 0xf9, 0x48, 0x4f, 0xf2, 0x65, 0x8e, 0x78, 0x5c, 0x58, 0x19, 0x8d, 0xe5, 0x98, 0x57, 0x67, 0x7f, 0x05, 0x64, 0xaf, 0x63, 0xb6, 0xfe, 0xf5, 0xb7, 0x3c, 0xa5, 0xce, 0xe9, 0x68, 0x44, 0xe0, 0x4d, 0x43, 0x69, 0x29, 0x2e, 0xac, 0x15, 0x59, 0xa8, 0x0a, 0x9e, 0x6e, 0x47, 0xdf, 0x34, 0x35, 0x6a, 0xcf, 0xdc, 0x22, 0xc9, 0xc0, 0x9b, 0x89, 0xd4, 0xed, 0xab, 0x12, 0xa2, 0x0d, 0x52, 0xbb, 0x02, 0x2f, 0xa9, 0xd7, 0x61, 0x1e, 0xb4, 0x50, 0x04, 0xf6, 0xc2, 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xbe, 0x91, }, } // gfMult returns a·b in GF(2^8)/p func gfMult(a, b byte, p uint32) byte { B := [2]uint32{0, uint32(b)} P := [2]uint32{0, p} var result uint32 // branchless GF multiplier for i := 0; i < 7; i++ { result ^= B[a&1] a >>= 1 B[1] = P[B[1]>>7] ^ (B[1] << 1) } result ^= B[a&1] return byte(result) } // mdsColumnMult calculates y{col} where [y0 y1 y2 y3] = MDS · [x0] func mdsColumnMult(in byte, col int) uint32 { mul01 := in mul5B := gfMult(in, 0x5B, mdsPolynomial) mulEF := gfMult(in, 0xEF, mdsPolynomial) switch col { case 0: return uint32(mul01) | uint32(mul5B)<<8 | uint32(mulEF)<<16 | uint32(mulEF)<<24 case 1: return uint32(mulEF) | uint32(mulEF)<<8 | uint32(mul5B)<<16 | uint32(mul01)<<24 case 2: return uint32(mul5B) | uint32(mulEF)<<8 | uint32(mul01)<<16 | uint32(mulEF)<<24 case 3: return uint32(mul5B) | uint32(mul01)<<8 | uint32(mulEF)<<16 | uint32(mul5B)<<24 } panic("unreachable") } // h implements the S-box generation function. See [TWOFISH] 4.3.5 func h(in, key []byte, offset int) uint32 { var y [4]byte for x := range y { y[x] = in[x] } switch len(key) / 8 { case 4: y[0] = sbox[1][y[0]] ^ key[4*(6+offset)+0] y[1] = sbox[0][y[1]] ^ key[4*(6+offset)+1] y[2] = sbox[0][y[2]] ^ key[4*(6+offset)+2] y[3] = sbox[1][y[3]] ^ key[4*(6+offset)+3] fallthrough case 3: y[0] = sbox[1][y[0]] ^ key[4*(4+offset)+0] y[1] = sbox[1][y[1]] ^ key[4*(4+offset)+1] y[2] = sbox[0][y[2]] ^ key[4*(4+offset)+2] y[3] = sbox[0][y[3]] ^ key[4*(4+offset)+3] fallthrough case 2: y[0] = sbox[1][sbox[0][sbox[0][y[0]]^key[4*(2+offset)+0]]^key[4*(0+offset)+0]] y[1] = sbox[0][sbox[0][sbox[1][y[1]]^key[4*(2+offset)+1]]^key[4*(0+offset)+1]] y[2] = sbox[1][sbox[1][sbox[0][y[2]]^key[4*(2+offset)+2]]^key[4*(0+offset)+2]] y[3] = sbox[0][sbox[1][sbox[1][y[3]]^key[4*(2+offset)+3]]^key[4*(0+offset)+3]] } // [y0 y1 y2 y3] = MDS . [x0 x1 x2 x3] var mdsMult uint32 for i := range y { mdsMult ^= mdsColumnMult(y[i], i) } return mdsMult } // Encrypt encrypts a 16-byte block from src to dst, which may overlap. // Note that for amounts of data larger than a block, // it is not safe to just call Encrypt on successive blocks; // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). func (c *Cipher) Encrypt(dst, src []byte) { S1 := c.s[0] S2 := c.s[1] S3 := c.s[2] S4 := c.s[3] // Load input ia := load32l(src[0:4]) ib := load32l(src[4:8]) ic := load32l(src[8:12]) id := load32l(src[12:16]) // Pre-whitening ia ^= c.k[0] ib ^= c.k[1] ic ^= c.k[2] id ^= c.k[3] for i := 0; i < 8; i++ { k := c.k[8+i*4 : 12+i*4] t2 := S2[byte(ib)] ^ S3[byte(ib>>8)] ^ S4[byte(ib>>16)] ^ S1[byte(ib>>24)] t1 := S1[byte(ia)] ^ S2[byte(ia>>8)] ^ S3[byte(ia>>16)] ^ S4[byte(ia>>24)] + t2 ic = ror(ic^(t1+k[0]), 1) id = rol(id, 1) ^ (t2 + t1 + k[1]) t2 = S2[byte(id)] ^ S3[byte(id>>8)] ^ S4[byte(id>>16)] ^ S1[byte(id>>24)] t1 = S1[byte(ic)] ^ S2[byte(ic>>8)] ^ S3[byte(ic>>16)] ^ S4[byte(ic>>24)] + t2 ia = ror(ia^(t1+k[2]), 1) ib = rol(ib, 1) ^ (t2 + t1 + k[3]) } // Output with "undo last swap" ta := ic ^ c.k[4] tb := id ^ c.k[5] tc := ia ^ c.k[6] td := ib ^ c.k[7] store32l(dst[0:4], ta) store32l(dst[4:8], tb) store32l(dst[8:12], tc) store32l(dst[12:16], td) } // Decrypt decrypts a 16-byte block from src to dst, which may overlap. func (c *Cipher) Decrypt(dst, src []byte) { S1 := c.s[0] S2 := c.s[1] S3 := c.s[2] S4 := c.s[3] // Load input ta := load32l(src[0:4]) tb := load32l(src[4:8]) tc := load32l(src[8:12]) td := load32l(src[12:16]) // Undo undo final swap ia := tc ^ c.k[6] ib := td ^ c.k[7] ic := ta ^ c.k[4] id := tb ^ c.k[5] for i := 8; i > 0; i-- { k := c.k[4+i*4 : 8+i*4] t2 := S2[byte(id)] ^ S3[byte(id>>8)] ^ S4[byte(id>>16)] ^ S1[byte(id>>24)] t1 := S1[byte(ic)] ^ S2[byte(ic>>8)] ^ S3[byte(ic>>16)] ^ S4[byte(ic>>24)] + t2 ia = rol(ia, 1) ^ (t1 + k[2]) ib = ror(ib^(t2+t1+k[3]), 1) t2 = S2[byte(ib)] ^ S3[byte(ib>>8)] ^ S4[byte(ib>>16)] ^ S1[byte(ib>>24)] t1 = S1[byte(ia)] ^ S2[byte(ia>>8)] ^ S3[byte(ia>>16)] ^ S4[byte(ia>>24)] + t2 ic = rol(ic, 1) ^ (t1 + k[0]) id = ror(id^(t2+t1+k[1]), 1) } // Undo pre-whitening ia ^= c.k[0] ib ^= c.k[1] ic ^= c.k[2] id ^= c.k[3] store32l(dst[0:4], ia) store32l(dst[4:8], ib) store32l(dst[8:12], ic) store32l(dst[12:16], id) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/tea/��������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021623� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/tea/tea_test.go���������������������������������������������0000644�0610621�0607500�00000005320�13172163317�023762� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tea import ( "bytes" "testing" ) // A sample test key for when we just want to initialize a cipher var testKey = []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF} // Test that the block size for tea is correct func TestBlocksize(t *testing.T) { c, err := NewCipher(testKey) if err != nil { t.Fatalf("NewCipher returned error: %s", err) } if result := c.BlockSize(); result != BlockSize { t.Errorf("cipher.BlockSize returned %d, but expected %d", result, BlockSize) } } // Test that invalid key sizes return an error func TestInvalidKeySize(t *testing.T) { var key [KeySize + 1]byte if _, err := NewCipher(key[:]); err == nil { t.Errorf("invalid key size %d didn't result in an error.", len(key)) } if _, err := NewCipher(key[:KeySize-1]); err == nil { t.Errorf("invalid key size %d didn't result in an error.", KeySize-1) } } // Test Vectors type teaTest struct { rounds int key []byte plaintext []byte ciphertext []byte } var teaTests = []teaTest{ // These were sourced from https://github.com/froydnj/ironclad/blob/master/testing/test-vectors/tea.testvec { numRounds, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x41, 0xea, 0x3a, 0x0a, 0x94, 0xba, 0xa9, 0x40}, }, { numRounds, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, []byte{0x31, 0x9b, 0xbe, 0xfb, 0x01, 0x6a, 0xbd, 0xb2}, }, { 16, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0xed, 0x28, 0x5d, 0xa1, 0x45, 0x5b, 0x33, 0xc1}, }, } // Test encryption func TestCipherEncrypt(t *testing.T) { // Test encryption with standard 64 rounds for i, test := range teaTests { c, err := NewCipherWithRounds(test.key, test.rounds) if err != nil { t.Fatalf("#%d: NewCipher returned error: %s", i, err) } var ciphertext [BlockSize]byte c.Encrypt(ciphertext[:], test.plaintext) if !bytes.Equal(ciphertext[:], test.ciphertext) { t.Errorf("#%d: incorrect ciphertext. Got %x, wanted %x", i, ciphertext, test.ciphertext) } var plaintext2 [BlockSize]byte c.Decrypt(plaintext2[:], ciphertext[:]) if !bytes.Equal(plaintext2[:], test.plaintext) { t.Errorf("#%d: incorrect plaintext. Got %x, wanted %x", i, plaintext2, test.plaintext) } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/tea/cipher.go�����������������������������������������������0000644�0610621�0607500�00000006023�13172163317�023425� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package tea implements the TEA algorithm, as defined in Needham and // Wheeler's 1994 technical report, “TEA, a Tiny Encryption Algorithmâ€. See // http://www.cix.co.uk/~klockstone/tea.pdf for details. package tea import ( "crypto/cipher" "encoding/binary" "errors" ) const ( // BlockSize is the size of a TEA block, in bytes. BlockSize = 8 // KeySize is the size of a TEA key, in bytes. KeySize = 16 // delta is the TEA key schedule constant. delta = 0x9e3779b9 // numRounds is the standard number of rounds in TEA. numRounds = 64 ) // tea is an instance of the TEA cipher with a particular key. type tea struct { key [16]byte rounds int } // NewCipher returns an instance of the TEA cipher with the standard number of // rounds. The key argument must be 16 bytes long. func NewCipher(key []byte) (cipher.Block, error) { return NewCipherWithRounds(key, numRounds) } // NewCipherWithRounds returns an instance of the TEA cipher with a given // number of rounds, which must be even. The key argument must be 16 bytes // long. func NewCipherWithRounds(key []byte, rounds int) (cipher.Block, error) { if len(key) != 16 { return nil, errors.New("tea: incorrect key size") } if rounds&1 != 0 { return nil, errors.New("tea: odd number of rounds specified") } c := &tea{ rounds: rounds, } copy(c.key[:], key) return c, nil } // BlockSize returns the TEA block size, which is eight bytes. It is necessary // to satisfy the Block interface in the package "crypto/cipher". func (*tea) BlockSize() int { return BlockSize } // Encrypt encrypts the 8 byte buffer src using the key in t and stores the // result in dst. Note that for amounts of data larger than a block, it is not // safe to just call Encrypt on successive blocks; instead, use an encryption // mode like CBC (see crypto/cipher/cbc.go). func (t *tea) Encrypt(dst, src []byte) { e := binary.BigEndian v0, v1 := e.Uint32(src), e.Uint32(src[4:]) k0, k1, k2, k3 := e.Uint32(t.key[0:]), e.Uint32(t.key[4:]), e.Uint32(t.key[8:]), e.Uint32(t.key[12:]) sum := uint32(0) delta := uint32(delta) for i := 0; i < t.rounds/2; i++ { sum += delta v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1) v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3) } e.PutUint32(dst, v0) e.PutUint32(dst[4:], v1) } // Decrypt decrypts the 8 byte buffer src using the key in t and stores the // result in dst. func (t *tea) Decrypt(dst, src []byte) { e := binary.BigEndian v0, v1 := e.Uint32(src), e.Uint32(src[4:]) k0, k1, k2, k3 := e.Uint32(t.key[0:]), e.Uint32(t.key[4:]), e.Uint32(t.key[8:]), e.Uint32(t.key[12:]) delta := uint32(delta) sum := delta * uint32(t.rounds/2) // in general, sum = delta * n for i := 0; i < t.rounds/2; i++ { v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3) v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1) sum -= delta } e.PutUint32(dst, v0) e.PutUint32(dst[4:], v1) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/��������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021647� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/transport_test.go���������������������������������������0000644�0610621�0607500�00000005025�13172163317�025273� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "crypto/rand" "encoding/binary" "strings" "testing" ) func TestReadVersion(t *testing.T) { longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] cases := map[string]string{ "SSH-2.0-bla\r\n": "SSH-2.0-bla", "SSH-2.0-bla\n": "SSH-2.0-bla", longversion + "\r\n": longversion, } for in, want := range cases { result, err := readVersion(bytes.NewBufferString(in)) if err != nil { t.Errorf("readVersion(%q): %s", in, err) } got := string(result) if got != want { t.Errorf("got %q, want %q", got, want) } } } func TestReadVersionError(t *testing.T) { longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] cases := []string{ longversion + "too-long\r\n", } for _, in := range cases { if _, err := readVersion(bytes.NewBufferString(in)); err == nil { t.Errorf("readVersion(%q) should have failed", in) } } } func TestExchangeVersionsBasic(t *testing.T) { v := "SSH-2.0-bla" buf := bytes.NewBufferString(v + "\r\n") them, err := exchangeVersions(buf, []byte("xyz")) if err != nil { t.Errorf("exchangeVersions: %v", err) } if want := "SSH-2.0-bla"; string(them) != want { t.Errorf("got %q want %q for our version", them, want) } } func TestExchangeVersions(t *testing.T) { cases := []string{ "not\x000allowed", "not allowed\n", } for _, c := range cases { buf := bytes.NewBufferString("SSH-2.0-bla\r\n") if _, err := exchangeVersions(buf, []byte(c)); err == nil { t.Errorf("exchangeVersions(%q): should have failed", c) } } } type closerBuffer struct { bytes.Buffer } func (b *closerBuffer) Close() error { return nil } func TestTransportMaxPacketWrite(t *testing.T) { buf := &closerBuffer{} tr := newTransport(buf, rand.Reader, true) huge := make([]byte, maxPacket+1) err := tr.writePacket(huge) if err == nil { t.Errorf("transport accepted write for a huge packet.") } } func TestTransportMaxPacketReader(t *testing.T) { var header [5]byte huge := make([]byte, maxPacket+128) binary.BigEndian.PutUint32(header[0:], uint32(len(huge))) // padding. header[4] = 0 buf := &closerBuffer{} buf.Write(header[:]) buf.Write(huge) tr := newTransport(buf, rand.Reader, true) _, err := tr.readPacket() if err == nil { t.Errorf("transport succeeded reading huge packet.") } else if !strings.Contains(err.Error(), "large") { t.Errorf("got %q, should mention %q", err.Error(), "large") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/transport.go��������������������������������������������0000644�0610621�0607500�00000022720�13172163317�024235� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bufio" "errors" "io" "log" ) // debugTransport if set, will print packet types as they go over the // wire. No message decoding is done, to minimize the impact on timing. const debugTransport = false const ( gcmCipherID = "aes128-gcm@openssh.com" aes128cbcID = "aes128-cbc" tripledescbcID = "3des-cbc" ) // packetConn represents a transport that implements packet based // operations. type packetConn interface { // Encrypt and send a packet of data to the remote peer. writePacket(packet []byte) error // Read a packet from the connection. The read is blocking, // i.e. if error is nil, then the returned byte slice is // always non-empty. readPacket() ([]byte, error) // Close closes the write-side of the connection. Close() error } // transport is the keyingTransport that implements the SSH packet // protocol. type transport struct { reader connectionState writer connectionState bufReader *bufio.Reader bufWriter *bufio.Writer rand io.Reader isClient bool io.Closer } // packetCipher represents a combination of SSH encryption/MAC // protocol. A single instance should be used for one direction only. type packetCipher interface { // writePacket encrypts the packet and writes it to w. The // contents of the packet are generally scrambled. writePacket(seqnum uint32, w io.Writer, rand io.Reader, packet []byte) error // readPacket reads and decrypts a packet of data. The // returned packet may be overwritten by future calls of // readPacket. readPacket(seqnum uint32, r io.Reader) ([]byte, error) } // connectionState represents one side (read or write) of the // connection. This is necessary because each direction has its own // keys, and can even have its own algorithms type connectionState struct { packetCipher seqNum uint32 dir direction pendingKeyChange chan packetCipher } // prepareKeyChange sets up key material for a keychange. The key changes in // both directions are triggered by reading and writing a msgNewKey packet // respectively. func (t *transport) prepareKeyChange(algs *algorithms, kexResult *kexResult) error { if ciph, err := newPacketCipher(t.reader.dir, algs.r, kexResult); err != nil { return err } else { t.reader.pendingKeyChange <- ciph } if ciph, err := newPacketCipher(t.writer.dir, algs.w, kexResult); err != nil { return err } else { t.writer.pendingKeyChange <- ciph } return nil } func (t *transport) printPacket(p []byte, write bool) { if len(p) == 0 { return } who := "server" if t.isClient { who = "client" } what := "read" if write { what = "write" } log.Println(what, who, p[0]) } // Read and decrypt next packet. func (t *transport) readPacket() (p []byte, err error) { for { p, err = t.reader.readPacket(t.bufReader) if err != nil { break } if len(p) == 0 || (p[0] != msgIgnore && p[0] != msgDebug) { break } } if debugTransport { t.printPacket(p, false) } return p, err } func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) { packet, err := s.packetCipher.readPacket(s.seqNum, r) s.seqNum++ if err == nil && len(packet) == 0 { err = errors.New("ssh: zero length packet") } if len(packet) > 0 { switch packet[0] { case msgNewKeys: select { case cipher := <-s.pendingKeyChange: s.packetCipher = cipher default: return nil, errors.New("ssh: got bogus newkeys message.") } case msgDisconnect: // Transform a disconnect message into an // error. Since this is lowest level at which // we interpret message types, doing it here // ensures that we don't have to handle it // elsewhere. var msg disconnectMsg if err := Unmarshal(packet, &msg); err != nil { return nil, err } return nil, &msg } } // The packet may point to an internal buffer, so copy the // packet out here. fresh := make([]byte, len(packet)) copy(fresh, packet) return fresh, err } func (t *transport) writePacket(packet []byte) error { if debugTransport { t.printPacket(packet, true) } return t.writer.writePacket(t.bufWriter, t.rand, packet) } func (s *connectionState) writePacket(w *bufio.Writer, rand io.Reader, packet []byte) error { changeKeys := len(packet) > 0 && packet[0] == msgNewKeys err := s.packetCipher.writePacket(s.seqNum, w, rand, packet) if err != nil { return err } if err = w.Flush(); err != nil { return err } s.seqNum++ if changeKeys { select { case cipher := <-s.pendingKeyChange: s.packetCipher = cipher default: panic("ssh: no key material for msgNewKeys") } } return err } func newTransport(rwc io.ReadWriteCloser, rand io.Reader, isClient bool) *transport { t := &transport{ bufReader: bufio.NewReader(rwc), bufWriter: bufio.NewWriter(rwc), rand: rand, reader: connectionState{ packetCipher: &streamPacketCipher{cipher: noneCipher{}}, pendingKeyChange: make(chan packetCipher, 1), }, writer: connectionState{ packetCipher: &streamPacketCipher{cipher: noneCipher{}}, pendingKeyChange: make(chan packetCipher, 1), }, Closer: rwc, } t.isClient = isClient if isClient { t.reader.dir = serverKeys t.writer.dir = clientKeys } else { t.reader.dir = clientKeys t.writer.dir = serverKeys } return t } type direction struct { ivTag []byte keyTag []byte macKeyTag []byte } var ( serverKeys = direction{[]byte{'B'}, []byte{'D'}, []byte{'F'}} clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}} ) // generateKeys generates key material for IV, MAC and encryption. func generateKeys(d direction, algs directionAlgorithms, kex *kexResult) (iv, key, macKey []byte) { cipherMode := cipherModes[algs.Cipher] macMode := macModes[algs.MAC] iv = make([]byte, cipherMode.ivSize) key = make([]byte, cipherMode.keySize) macKey = make([]byte, macMode.keySize) generateKeyMaterial(iv, d.ivTag, kex) generateKeyMaterial(key, d.keyTag, kex) generateKeyMaterial(macKey, d.macKeyTag, kex) return } // setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as // described in RFC 4253, section 6.4. direction should either be serverKeys // (to setup server->client keys) or clientKeys (for client->server keys). func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error) { iv, key, macKey := generateKeys(d, algs, kex) if algs.Cipher == gcmCipherID { return newGCMCipher(iv, key, macKey) } if algs.Cipher == aes128cbcID { return newAESCBCCipher(iv, key, macKey, algs) } if algs.Cipher == tripledescbcID { return newTripleDESCBCCipher(iv, key, macKey, algs) } c := &streamPacketCipher{ mac: macModes[algs.MAC].new(macKey), etm: macModes[algs.MAC].etm, } c.macResult = make([]byte, c.mac.Size()) var err error c.cipher, err = cipherModes[algs.Cipher].createStream(key, iv) if err != nil { return nil, err } return c, nil } // generateKeyMaterial fills out with key material generated from tag, K, H // and sessionId, as specified in RFC 4253, section 7.2. func generateKeyMaterial(out, tag []byte, r *kexResult) { var digestsSoFar []byte h := r.Hash.New() for len(out) > 0 { h.Reset() h.Write(r.K) h.Write(r.H) if len(digestsSoFar) == 0 { h.Write(tag) h.Write(r.SessionID) } else { h.Write(digestsSoFar) } digest := h.Sum(nil) n := copy(out, digest) out = out[n:] if len(out) > 0 { digestsSoFar = append(digestsSoFar, digest...) } } } const packageVersion = "SSH-2.0-Go" // Sends and receives a version line. The versionLine string should // be US ASCII, start with "SSH-2.0-", and should not include a // newline. exchangeVersions returns the other side's version line. func exchangeVersions(rw io.ReadWriter, versionLine []byte) (them []byte, err error) { // Contrary to the RFC, we do not ignore lines that don't // start with "SSH-2.0-" to make the library usable with // nonconforming servers. for _, c := range versionLine { // The spec disallows non US-ASCII chars, and // specifically forbids null chars. if c < 32 { return nil, errors.New("ssh: junk character in version line") } } if _, err = rw.Write(append(versionLine, '\r', '\n')); err != nil { return } them, err = readVersion(rw) return them, err } // maxVersionStringBytes is the maximum number of bytes that we'll // accept as a version string. RFC 4253 section 4.2 limits this at 255 // chars const maxVersionStringBytes = 255 // Read version string as specified by RFC 4253, section 4.2. func readVersion(r io.Reader) ([]byte, error) { versionString := make([]byte, 0, 64) var ok bool var buf [1]byte for len(versionString) < maxVersionStringBytes { _, err := io.ReadFull(r, buf[:]) if err != nil { return nil, err } // The RFC says that the version should be terminated with \r\n // but several SSH servers actually only send a \n. if buf[0] == '\n' { ok = true break } // non ASCII chars are disallowed, but we are lenient, // since Go doesn't use null-terminated strings. // The RFC allows a comment after a space, however, // all of it (version and comments) goes into the // session hash. versionString = append(versionString, buf[0]) } if !ok { return nil, errors.New("ssh: overflow reading version string") } // There might be a '\r' on the end which we should remove. if len(versionString) > 0 && versionString[len(versionString)-1] == '\r' { versionString = versionString[:len(versionString)-1] } return versionString, nil } ������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/testdata_test.go����������������������������������������0000644�0610621�0607500�00000004161�13172163317�025050� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: // ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three // instances. package ssh import ( "crypto/rand" "fmt" "golang.org/x/crypto/ssh/testdata" ) var ( testPrivateKeys map[string]interface{} testSigners map[string]Signer testPublicKeys map[string]PublicKey ) func init() { var err error n := len(testdata.PEMBytes) testPrivateKeys = make(map[string]interface{}, n) testSigners = make(map[string]Signer, n) testPublicKeys = make(map[string]PublicKey, n) for t, k := range testdata.PEMBytes { testPrivateKeys[t], err = ParseRawPrivateKey(k) if err != nil { panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) } testSigners[t], err = NewSignerFromKey(testPrivateKeys[t]) if err != nil { panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) } testPublicKeys[t] = testSigners[t].PublicKey() } // Create a cert and sign it for use in tests. testCert := &Certificate{ Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage ValidAfter: 0, // unix epoch ValidBefore: CertTimeInfinity, // The end of currently representable time. Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil Key: testPublicKeys["ecdsa"], SignatureKey: testPublicKeys["rsa"], Permissions: Permissions{ CriticalOptions: map[string]string{}, Extensions: map[string]string{}, }, } testCert.SignCert(rand.Reader, testSigners["rsa"]) testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] testSigners["cert"], err = NewCertSigner(testCert, testSigners["ecdsa"]) if err != nil { panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/testdata/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023460� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/testdata/keys.go����������������������������������������0000644�0610621�0607500�00000023527�13172163317�024773� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package testdata var PEMBytes = map[string][]byte{ "dsa": []byte(`-----BEGIN DSA PRIVATE KEY----- MIIBuwIBAAKBgQD6PDSEyXiI9jfNs97WuM46MSDCYlOqWw80ajN16AohtBncs1YB lHk//dQOvCYOsYaE+gNix2jtoRjwXhDsc25/IqQbU1ahb7mB8/rsaILRGIbA5WH3 EgFtJmXFovDz3if6F6TzvhFpHgJRmLYVR8cqsezL3hEZOvvs2iH7MorkxwIVAJHD nD82+lxh2fb4PMsIiaXudAsBAoGAQRf7Q/iaPRn43ZquUhd6WwvirqUj+tkIu6eV 2nZWYmXLlqFQKEy4Tejl7Wkyzr2OSYvbXLzo7TNxLKoWor6ips0phYPPMyXld14r juhT24CrhOzuLMhDduMDi032wDIZG4Y+K7ElU8Oufn8Sj5Wge8r6ANmmVgmFfynr FhdYCngCgYEA3ucGJ93/Mx4q4eKRDxcWD3QzWyqpbRVRRV1Vmih9Ha/qC994nJFz DQIdjxDIT2Rk2AGzMqFEB68Zc3O+Wcsmz5eWWzEwFxaTwOGWTyDqsDRLm3fD+QYj nOwuxb0Kce+gWI8voWcqC9cyRm09jGzu2Ab3Bhtpg8JJ8L7gS3MRZK4CFEx4UAfY Fmsr0W6fHB9nhS4/UXM8 -----END DSA PRIVATE KEY----- `), "ecdsa": []byte(`-----BEGIN EC PRIVATE KEY----- MHcCAQEEINGWx0zo6fhJ/0EAfrPzVFyFC9s18lBt3cRoEDhS3ARooAoGCCqGSM49 AwEHoUQDQgAEi9Hdw6KvZcWxfg2IDhA7UkpDtzzt6ZqJXSsFdLd+Kx4S3Sx4cVO+ 6/ZOXRnPmNAlLUqjShUsUBBngG0u2fqEqA== -----END EC PRIVATE KEY----- `), "rsa": []byte(`-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQC8A6FGHDiWCSREAXCq6yBfNVr0xCVG2CzvktFNRpue+RXrGs/2 a6ySEJQb3IYquw7HlJgu6fg3WIWhOmHCjfpG0PrL4CRwbqQ2LaPPXhJErWYejcD8 Di00cF3677+G10KMZk9RXbmHtuBFZT98wxg8j+ZsBMqGM1+7yrWUvynswQIDAQAB AoGAJMCk5vqfSRzyXOTXLGIYCuR4Kj6pdsbNSeuuRGfYBeR1F2c/XdFAg7D/8s5R 38p/Ih52/Ty5S8BfJtwtvgVY9ecf/JlU/rl/QzhG8/8KC0NG7KsyXklbQ7gJT8UT Ojmw5QpMk+rKv17ipDVkQQmPaj+gJXYNAHqImke5mm/K/h0CQQDciPmviQ+DOhOq 2ZBqUfH8oXHgFmp7/6pXw80DpMIxgV3CwkxxIVx6a8lVH9bT/AFySJ6vXq4zTuV9 6QmZcZzDAkEA2j/UXJPIs1fQ8z/6sONOkU/BjtoePFIWJlRxdN35cZjXnBraX5UR fFHkePv4YwqmXNqrBOvSu+w2WdSDci+IKwJAcsPRc/jWmsrJW1q3Ha0hSf/WG/Bu X7MPuXaKpP/DkzGoUmb8ks7yqj6XWnYkPNLjCc8izU5vRwIiyWBRf4mxMwJBAILa NDvRS0rjwt6lJGv7zPZoqDc65VfrK2aNyHx2PgFyzwrEOtuF57bu7pnvEIxpLTeM z26i6XVMeYXAWZMTloMCQBbpGgEERQpeUknLBqUHhg/wXF6+lFA+vEGnkY+Dwab2 KCXFGd+SQ5GdUcEMe9isUH6DYj/6/yCDoFrXXmpQb+M= -----END RSA PRIVATE KEY----- `), "ed25519": []byte(`-----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW QyNTUxOQAAACA+3f7hS7g5UWwXOGVTrMfhmxyrjqz7Sxxbx7I1j8DvvwAAAJhAFfkOQBX5 DgAAAAtzc2gtZWQyNTUxOQAAACA+3f7hS7g5UWwXOGVTrMfhmxyrjqz7Sxxbx7I1j8Dvvw AAAEAaYmXltfW6nhRo3iWGglRB48lYq0z0Q3I3KyrdutEr6j7d/uFLuDlRbBc4ZVOsx+Gb HKuOrPtLHFvHsjWPwO+/AAAAE2dhcnRvbm1AZ2FydG9ubS14cHMBAg== -----END OPENSSH PRIVATE KEY----- `), "rsa-openssh-format": []byte(`-----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAlwAAAAdzc2gtcn NhAAAAAwEAAQAAAIEAwa48yfWFi3uIdqzuf9X7C2Zxfea/Iaaw0zIwHudpF8U92WVIiC5l oEuW1+OaVi3UWfIEjWMV1tHGysrHOwtwc34BPCJqJknUQO/KtDTBTJ4Pryhw1bWPC999Lz a+yrCTdNQYBzoROXKExZgPFh9pTMi5wqpHDuOQ2qZFIEI3lT0AAAIQWL0H31i9B98AAAAH c3NoLXJzYQAAAIEAwa48yfWFi3uIdqzuf9X7C2Zxfea/Iaaw0zIwHudpF8U92WVIiC5loE uW1+OaVi3UWfIEjWMV1tHGysrHOwtwc34BPCJqJknUQO/KtDTBTJ4Pryhw1bWPC999Lza+ yrCTdNQYBzoROXKExZgPFh9pTMi5wqpHDuOQ2qZFIEI3lT0AAAADAQABAAAAgCThyTGsT4 IARDxVMhWl6eiB2ZrgFgWSeJm/NOqtppWgOebsIqPMMg4UVuVFsl422/lE3RkPhVkjGXgE pWvZAdCnmLmApK8wK12vF334lZhZT7t3Z9EzJps88PWEHo7kguf285HcnUM7FlFeissJdk kXly34y7/3X/a6Tclm+iABAAAAQE0xR/KxZ39slwfMv64Rz7WKk1PPskaryI29aHE3mKHk pY2QA+P3QlrKxT/VWUMjHUbNNdYfJm48xu0SGNMRdKMAAABBAORh2NP/06JUV3J9W/2Hju X1ViJuqqcQnJPVzpgSL826EC2xwOECTqoY8uvFpUdD7CtpksIxNVqRIhuNOlz0lqEAAABB ANkaHTTaPojClO0dKJ/Zjs7pWOCGliebBYprQ/Y4r9QLBkC/XaWMS26gFIrjgC7D2Rv+rZ wSD0v0RcmkITP1ZR0AAAAYcHF1ZXJuYUBMdWNreUh5ZHJvLmxvY2FsAQID -----END OPENSSH PRIVATE KEY-----`), "user": []byte(`-----BEGIN EC PRIVATE KEY----- MHcCAQEEILYCAeq8f7V4vSSypRw7pxy8yz3V5W4qg8kSC3zJhqpQoAoGCCqGSM49 AwEHoUQDQgAEYcO2xNKiRUYOLEHM7VYAp57HNyKbOdYtHD83Z4hzNPVC4tM5mdGD PLL8IEwvYu2wq+lpXfGQnNMbzYf9gspG0w== -----END EC PRIVATE KEY----- `), "ca": []byte(`-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAvg9dQ9IRG59lYJb+GESfKWTch4yBpr7Ydw1jkK6vvtrx9jLo 5hkA8X6+ElRPRqTAZSlN5cBm6YCAcQIOsmXDUn6Oj1lVPQAoOjTBTvsjM3NjGhvv 52kHTY0nsMsBeY9q5DTtlzmlYkVUq2a6Htgf2mNi01dIw5fJ7uTTo8EbNf7O0i3u c9a8P19HaZl5NKiWN4EIZkfB2WdXYRJCVBsGgQj3dE/GrEmH9QINq1A+GkNvK96u vZm8H1jjmuqzHplWa7lFeXcx8FTVTbVb/iJrZ2Lc/JvIPitKZWhqbR59yrGjpwEp Id7bo4WhO5L3OB0fSIJYvfu+o4WYnt4f3UzecwIDAQABAoIBABRD9yHgKErVuC2Q bA+SYZY8VvdtF/X7q4EmQFORDNRA7EPgMc03JU6awRGbQ8i4kHs46EFzPoXvWcKz AXYsO6N0Myc900Tp22A5d9NAHATEbPC/wdje7hRq1KyZONMJY9BphFv3nZbY5apR Dc90JBFZP5RhXjTc3n9GjvqLAKfFEKVmPRCvqxCOZunw6XR+SgIQLJo36nsIsbhW QUXIVaCI6cXMN8bRPm8EITdBNZu06Fpu4ZHm6VaxlXN9smERCDkgBSNXNWHKxmmA c3Glo2DByUr2/JFBOrLEe9fkYgr24KNCQkHVcSaFxEcZvTggr7StjKISVHlCNEaB 7Q+kPoECgYEA3zE9FmvFGoQCU4g4Nl3dpQHs6kaAW8vJlrmq3xsireIuaJoa2HMe wYdIvgCnK9DIjyxd5OWnE4jXtAEYPsyGD32B5rSLQrRO96lgb3f4bESCLUb3Bsn/ sdgeE3p1xZMA0B59htqCrvVgN9k8WxyevBxYl3/gSBm/p8OVH1RTW/ECgYEA2f9Z 95OLj0KQHQtxQXf+I3VjhCw3LkLW39QZOXVI0QrCJfqqP7uxsJXH9NYX0l0GFTcR kRrlyoaSU1EGQosZh+n1MvplGBTkTSV47/bPsTzFpgK2NfEZuFm9RoWgltS+nYeH Y2k4mnAN3PhReCMwuprmJz8GRLsO3Cs2s2YylKMCgYEA2UX+uO/q7jgqZ5UJW+ue 1H5+W0aMuFA3i7JtZEnvRaUVFqFGlwXin/WJ2+WY1++k/rPrJ+Rk9IBXtBUIvEGw FC5TIfsKQsJyyWgqx/jbbtJ2g4s8+W/1qfTAuqeRNOg5d2DnRDs90wJuS4//0JaY 9HkHyVwkQyxFxhSA/AHEMJECgYA2MvyFR1O9bIk0D3I7GsA+xKLXa77Ua53MzIjw 9i4CezBGDQpjCiFli/fI8am+jY5DnAtsDknvjoG24UAzLy5L0mk6IXMdB6SzYYut 7ak5oahqW+Y9hxIj+XvLmtGQbphtxhJtLu35x75KoBpxSh6FZpmuTEccs31AVCYn eFM/DQKBgQDOPUwbLKqVi6ddFGgrV9MrWw+SWsDa43bPuyvYppMM3oqesvyaX1Dt qDvN7owaNxNM4OnfKcZr91z8YPVCFo4RbBif3DXRzjNNBlxEjHBtuMOikwvsmucN vIrbeEpjTiUMTEAr6PoTiVHjsfS8WAM6MDlF5M+2PNswDsBpa2yLgA== -----END RSA PRIVATE KEY----- `), } var SSHCertificates = map[string][]byte{ // The following are corresponding certificates for the private keys above, signed by the CA key // Generated by the following commands: // // 1. Assumes "rsa" key above in file named "rsa", write out the public key to "rsa.pub": // ssh-keygen -y -f rsa > rsa.pu // // 2. Assumes "ca" key above in file named "ca", sign a cert for "rsa.pub": // ssh-keygen -s ca -h -n host.example.com -V +500w -I host.example.com-key rsa.pub "rsa": []byte(`ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgLjYqmmuTSEmjVhSfLQphBSTJMLwIZhRgmpn8FHKLiEIAAAADAQABAAAAgQC8A6FGHDiWCSREAXCq6yBfNVr0xCVG2CzvktFNRpue+RXrGs/2a6ySEJQb3IYquw7HlJgu6fg3WIWhOmHCjfpG0PrL4CRwbqQ2LaPPXhJErWYejcD8Di00cF3677+G10KMZk9RXbmHtuBFZT98wxg8j+ZsBMqGM1+7yrWUvynswQAAAAAAAAAAAAAAAgAAABRob3N0LmV4YW1wbGUuY29tLWtleQAAABQAAAAQaG9zdC5leGFtcGxlLmNvbQAAAABZHN8UAAAAAGsjIYUAAAAAAAAAAAAAAAAAAAEXAAAAB3NzaC1yc2EAAAADAQABAAABAQC+D11D0hEbn2Vglv4YRJ8pZNyHjIGmvth3DWOQrq++2vH2MujmGQDxfr4SVE9GpMBlKU3lwGbpgIBxAg6yZcNSfo6PWVU9ACg6NMFO+yMzc2MaG+/naQdNjSewywF5j2rkNO2XOaViRVSrZroe2B/aY2LTV0jDl8nu5NOjwRs1/s7SLe5z1rw/X0dpmXk0qJY3gQhmR8HZZ1dhEkJUGwaBCPd0T8asSYf1Ag2rUD4aQ28r3q69mbwfWOOa6rMemVZruUV5dzHwVNVNtVv+ImtnYtz8m8g+K0plaGptHn3KsaOnASkh3tujhaE7kvc4HR9Igli9+76jhZie3h/dTN5zAAABDwAAAAdzc2gtcnNhAAABALeDea+60H6xJGhktAyosHaSY7AYzLocaqd8hJQjEIDifBwzoTlnBmcK9CxGhKuaoJFThdCLdaevCeOSuquh8HTkf+2ebZZc/G5T+2thPvPqmcuEcmMosWo+SIjYhbP3S6KD49aLC1X0kz8IBQeauFvURhkZ5ZjhA1L4aQYt9NjL73nqOl8PplRui+Ov5w8b4ldul4zOvYAFrzfcP6wnnXk3c1Zzwwf5wynD5jakO8GpYKBuhM7Z4crzkKSQjU3hla7xqgfomC5Gz4XbR2TNjcQiRrJQ0UlKtX3X3ObRCEhuvG0Kzjklhv+Ddw6txrhKjMjiSi/Yyius/AE8TmC1p4U= host.example.com `), } var PEMEncryptedKeys = []struct { Name string EncryptionKey string PEMBytes []byte }{ 0: { Name: "rsa-encrypted", EncryptionKey: "r54-G0pher_t3st$", PEMBytes: []byte(`-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,3E1714DE130BC5E81327F36564B05462 MqW88sud4fnWk/Jk3fkjh7ydu51ZkHLN5qlQgA4SkAXORPPMj2XvqZOv1v2LOgUV dUevUn8PZK7a9zbZg4QShUSzwE5k6wdB7XKPyBgI39mJ79GBd2U4W3h6KT6jIdWA goQpluxkrzr2/X602IaxLEre97FT9mpKC6zxKCLvyFWVIP9n3OSFS47cTTXyFr+l 7PdRhe60nn6jSBgUNk/Q1lAvEQ9fufdPwDYY93F1wyJ6lOr0F1+mzRrMbH67NyKs rG8J1Fa7cIIre7ueKIAXTIne7OAWqpU9UDgQatDtZTbvA7ciqGsSFgiwwW13N+Rr hN8MkODKs9cjtONxSKi05s206A3NDU6STtZ3KuPDjFE1gMJODotOuqSM+cxKfyFq wxpk/CHYCDdMAVBSwxb/vraOHamylL4uCHpJdBHypzf2HABt+lS8Su23uAmL87DR yvyCS/lmpuNTndef6qHPRkoW2EV3xqD3ovosGf7kgwGJUk2ZpCLVteqmYehKlZDK r/Jy+J26ooI2jIg9bjvD1PZq+Mv+2dQ1RlDrPG3PB+rEixw6vBaL9x3jatCd4ej7 XG7lb3qO9xFpLsx89tkEcvpGR+broSpUJ6Mu5LBCVmrvqHjvnDhrZVz1brMiQtU9 iMZbgXqDLXHd6ERWygk7OTU03u+l1gs+KGMfmS0h0ZYw6KGVLgMnsoxqd6cFSKNB 8Ohk9ZTZGCiovlXBUepyu8wKat1k8YlHSfIHoRUJRhhcd7DrmojC+bcbMIZBU22T Pl2ftVRGtcQY23lYd0NNKfebF7ncjuLWQGy+vZW+7cgfI6wPIbfYfP6g7QAutk6W KQx0AoX5woZ6cNxtpIrymaVjSMRRBkKQrJKmRp3pC/lul5E5P2cueMs1fj4OHTbJ lAUv88ywr+R+mRgYQlFW/XQ653f6DT4t6+njfO9oBcPrQDASZel3LjXLpjjYG/N5 +BWnVexuJX9ika8HJiFl55oqaKb+WknfNhk5cPY+x7SDV9ywQeMiDZpr0ffeYAEP LlwwiWRDYpO+uwXHSFF3+JjWwjhs8m8g99iFb7U93yKgBB12dCEPPa2ZeH9wUHMJ sreYhNuq6f4iWWSXpzN45inQqtTi8jrJhuNLTT543ErW7DtntBO2rWMhff3aiXbn Uy3qzZM1nPbuCGuBmP9L2dJ3Z5ifDWB4JmOyWY4swTZGt9AVmUxMIKdZpRONx8vz I9u9nbVPGZBcou50Pa0qTLbkWsSL94MNXrARBxzhHC9Zs6XNEtwN7mOuii7uMkVc adrxgknBH1J1N+NX/eTKzUwJuPvDtA+Z5ILWNN9wpZT/7ed8zEnKHPNUexyeT5g3 uw9z9jH7ffGxFYlx87oiVPHGOrCXYZYW5uoZE31SCBkbtNuffNRJRKIFeipmpJ3P 7bpAG+kGHMelQH6b+5K1Qgsv4tpuSyKeTKpPFH9Av5nN4P1ZBm9N80tzbNWqjSJm S7rYdHnuNEVnUGnRmEUMmVuYZnNBEVN/fP2m2SEwXcP3Uh7TiYlcWw10ygaGmOr7 MvMLGkYgQ4Utwnd98mtqa0jr0hK2TcOSFir3AqVvXN3XJj4cVULkrXe4Im1laWgp -----END RSA PRIVATE KEY----- `), }, 1: { Name: "dsa-encrypted", EncryptionKey: "qG0pher-dsa_t3st$", PEMBytes: []byte(`-----BEGIN DSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,7CE7A6E4A647DC01AF860210B15ADE3E hvnBpI99Hceq/55pYRdOzBLntIEis02JFNXuLEydWL+RJBFDn7tA+vXec0ERJd6J G8JXlSOAhmC2H4uK3q2xR8/Y3yL95n6OIcjvCBiLsV+o3jj1MYJmErxP6zRtq4w3 JjIjGHWmaYFSxPKQ6e8fs74HEqaeMV9ONUoTtB+aISmgaBL15Fcoayg245dkBvVl h5Kqspe7yvOBmzA3zjRuxmSCqKJmasXM7mqs3vIrMxZE3XPo1/fWKcPuExgpVQoT HkJZEoIEIIPnPMwT2uYbFJSGgPJVMDT84xz7yvjCdhLmqrsXgs5Qw7Pw0i0c0BUJ b7fDJ2UhdiwSckWGmIhTLlJZzr8K+JpjCDlP+REYBI5meB7kosBnlvCEHdw2EJkH 0QDc/2F4xlVrHOLbPRFyu1Oi2Gvbeoo9EsM/DThpd1hKAlb0sF5Y0y0d+owv0PnE R/4X3HWfIdOHsDUvJ8xVWZ4BZk9Zk9qol045DcFCehpr/3hslCrKSZHakLt9GI58 vVQJ4L0aYp5nloLfzhViZtKJXRLkySMKdzYkIlNmW1oVGl7tce5UCNI8Nok4j6yn IiHM7GBn+0nJoKTXsOGMIBe3ulKlKVxLjEuk9yivh/8= -----END DSA PRIVATE KEY----- `), }, } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/testdata/doc.go�����������������������������������������0000644�0610621�0607500�00000000632�13172163317�024555� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This package contains test data shared between the various subpackages of // the golang.org/x/crypto/ssh package. Under no circumstance should // this data be used for production code. package testdata // import "golang.org/x/crypto/ssh/testdata" ������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/���������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022626� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/testdata_test.go�����������������������������������0000644�0610621�0607500�00000004261�13172163317�026030� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: // ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three // instances. package test import ( "crypto/rand" "fmt" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/testdata" ) var ( testPrivateKeys map[string]interface{} testSigners map[string]ssh.Signer testPublicKeys map[string]ssh.PublicKey ) func init() { var err error n := len(testdata.PEMBytes) testPrivateKeys = make(map[string]interface{}, n) testSigners = make(map[string]ssh.Signer, n) testPublicKeys = make(map[string]ssh.PublicKey, n) for t, k := range testdata.PEMBytes { testPrivateKeys[t], err = ssh.ParseRawPrivateKey(k) if err != nil { panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) } testSigners[t], err = ssh.NewSignerFromKey(testPrivateKeys[t]) if err != nil { panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) } testPublicKeys[t] = testSigners[t].PublicKey() } // Create a cert and sign it for use in tests. testCert := &ssh.Certificate{ Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage ValidAfter: 0, // unix epoch ValidBefore: ssh.CertTimeInfinity, // The end of currently representable time. Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil Key: testPublicKeys["ecdsa"], SignatureKey: testPublicKeys["rsa"], Permissions: ssh.Permissions{ CriticalOptions: map[string]string{}, Extensions: map[string]string{}, }, } testCert.SignCert(rand.Reader, testSigners["rsa"]) testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] testSigners["cert"], err = ssh.NewCertSigner(testCert, testSigners["ecdsa"]) if err != nil { panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/test_unix_test.go����������������������������������0000644�0610621�0607500�00000015534�13172163317�026246� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd plan9 package test // functional test harness for unix. import ( "bytes" "fmt" "io/ioutil" "log" "net" "os" "os/exec" "os/user" "path/filepath" "testing" "text/template" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/testdata" ) const sshd_config = ` Protocol 2 HostKey {{.Dir}}/id_rsa HostKey {{.Dir}}/id_dsa HostKey {{.Dir}}/id_ecdsa HostCertificate {{.Dir}}/id_rsa-cert.pub Pidfile {{.Dir}}/sshd.pid #UsePrivilegeSeparation no KeyRegenerationInterval 3600 ServerKeyBits 768 SyslogFacility AUTH LogLevel DEBUG2 LoginGraceTime 120 PermitRootLogin no StrictModes no RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile {{.Dir}}/authorized_keys TrustedUserCAKeys {{.Dir}}/id_ecdsa.pub IgnoreRhosts yes RhostsRSAAuthentication no HostbasedAuthentication no PubkeyAcceptedKeyTypes=* ` var configTmpl = template.Must(template.New("").Parse(sshd_config)) type server struct { t *testing.T cleanup func() // executed during Shutdown configfile string cmd *exec.Cmd output bytes.Buffer // holds stderr from sshd process // Client half of the network connection. clientConn net.Conn } func username() string { var username string if user, err := user.Current(); err == nil { username = user.Username } else { // user.Current() currently requires cgo. If an error is // returned attempt to get the username from the environment. log.Printf("user.Current: %v; falling back on $USER", err) username = os.Getenv("USER") } if username == "" { panic("Unable to get username") } return username } type storedHostKey struct { // keys map from an algorithm string to binary key data. keys map[string][]byte // checkCount counts the Check calls. Used for testing // rekeying. checkCount int } func (k *storedHostKey) Add(key ssh.PublicKey) { if k.keys == nil { k.keys = map[string][]byte{} } k.keys[key.Type()] = key.Marshal() } func (k *storedHostKey) Check(addr string, remote net.Addr, key ssh.PublicKey) error { k.checkCount++ algo := key.Type() if k.keys == nil || bytes.Compare(key.Marshal(), k.keys[algo]) != 0 { return fmt.Errorf("host key mismatch. Got %q, want %q", key, k.keys[algo]) } return nil } func hostKeyDB() *storedHostKey { keyChecker := &storedHostKey{} keyChecker.Add(testPublicKeys["ecdsa"]) keyChecker.Add(testPublicKeys["rsa"]) keyChecker.Add(testPublicKeys["dsa"]) return keyChecker } func clientConfig() *ssh.ClientConfig { config := &ssh.ClientConfig{ User: username(), Auth: []ssh.AuthMethod{ ssh.PublicKeys(testSigners["user"]), }, HostKeyCallback: hostKeyDB().Check, HostKeyAlgorithms: []string{ // by default, don't allow certs as this affects the hostKeyDB checker ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521, ssh.KeyAlgoRSA, ssh.KeyAlgoDSA, ssh.KeyAlgoED25519, }, } return config } // unixConnection creates two halves of a connected net.UnixConn. It // is used for connecting the Go SSH client with sshd without opening // ports. func unixConnection() (*net.UnixConn, *net.UnixConn, error) { dir, err := ioutil.TempDir("", "unixConnection") if err != nil { return nil, nil, err } defer os.Remove(dir) addr := filepath.Join(dir, "ssh") listener, err := net.Listen("unix", addr) if err != nil { return nil, nil, err } defer listener.Close() c1, err := net.Dial("unix", addr) if err != nil { return nil, nil, err } c2, err := listener.Accept() if err != nil { c1.Close() return nil, nil, err } return c1.(*net.UnixConn), c2.(*net.UnixConn), nil } func (s *server) TryDial(config *ssh.ClientConfig) (*ssh.Client, error) { return s.TryDialWithAddr(config, "") } // addr is the user specified host:port. While we don't actually dial it, // we need to know this for host key matching func (s *server) TryDialWithAddr(config *ssh.ClientConfig, addr string) (*ssh.Client, error) { sshd, err := exec.LookPath("sshd") if err != nil { s.t.Skipf("skipping test: %v", err) } c1, c2, err := unixConnection() if err != nil { s.t.Fatalf("unixConnection: %v", err) } s.cmd = exec.Command(sshd, "-f", s.configfile, "-i", "-e") f, err := c2.File() if err != nil { s.t.Fatalf("UnixConn.File: %v", err) } defer f.Close() s.cmd.Stdin = f s.cmd.Stdout = f s.cmd.Stderr = &s.output if err := s.cmd.Start(); err != nil { s.t.Fail() s.Shutdown() s.t.Fatalf("s.cmd.Start: %v", err) } s.clientConn = c1 conn, chans, reqs, err := ssh.NewClientConn(c1, addr, config) if err != nil { return nil, err } return ssh.NewClient(conn, chans, reqs), nil } func (s *server) Dial(config *ssh.ClientConfig) *ssh.Client { conn, err := s.TryDial(config) if err != nil { s.t.Fail() s.Shutdown() s.t.Fatalf("ssh.Client: %v", err) } return conn } func (s *server) Shutdown() { if s.cmd != nil && s.cmd.Process != nil { // Don't check for errors; if it fails it's most // likely "os: process already finished", and we don't // care about that. Use os.Interrupt, so child // processes are killed too. s.cmd.Process.Signal(os.Interrupt) s.cmd.Wait() } if s.t.Failed() { // log any output from sshd process s.t.Logf("sshd: %s", s.output.String()) } s.cleanup() } func writeFile(path string, contents []byte) { f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600) if err != nil { panic(err) } defer f.Close() if _, err := f.Write(contents); err != nil { panic(err) } } // newServer returns a new mock ssh server. func newServer(t *testing.T) *server { if testing.Short() { t.Skip("skipping test due to -short") } dir, err := ioutil.TempDir("", "sshtest") if err != nil { t.Fatal(err) } f, err := os.Create(filepath.Join(dir, "sshd_config")) if err != nil { t.Fatal(err) } err = configTmpl.Execute(f, map[string]string{ "Dir": dir, }) if err != nil { t.Fatal(err) } f.Close() for k, v := range testdata.PEMBytes { filename := "id_" + k writeFile(filepath.Join(dir, filename), v) writeFile(filepath.Join(dir, filename+".pub"), ssh.MarshalAuthorizedKey(testPublicKeys[k])) } for k, v := range testdata.SSHCertificates { filename := "id_" + k + "-cert.pub" writeFile(filepath.Join(dir, filename), v) } var authkeys bytes.Buffer for k, _ := range testdata.PEMBytes { authkeys.Write(ssh.MarshalAuthorizedKey(testPublicKeys[k])) } writeFile(filepath.Join(dir, "authorized_keys"), authkeys.Bytes()) return &server{ t: t, configfile: f.Name(), cleanup: func() { if err := os.RemoveAll(dir); err != nil { t.Error(err) } }, } } func newTempSocket(t *testing.T) (string, func()) { dir, err := ioutil.TempDir("", "socket") if err != nil { t.Fatal(err) } deferFunc := func() { os.RemoveAll(dir) } addr := filepath.Join(dir, "sock") return addr, deferFunc } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/session_test.go������������������������������������0000644�0610621�0607500�00000022113�13172163317�025676� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !windows package test // Session functional tests. import ( "bytes" "errors" "io" "strings" "testing" "golang.org/x/crypto/ssh" ) func TestRunCommandSuccess(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() err = session.Run("true") if err != nil { t.Fatalf("session failed: %v", err) } } func TestHostKeyCheck(t *testing.T) { server := newServer(t) defer server.Shutdown() conf := clientConfig() hostDB := hostKeyDB() conf.HostKeyCallback = hostDB.Check // change the keys. hostDB.keys[ssh.KeyAlgoRSA][25]++ hostDB.keys[ssh.KeyAlgoDSA][25]++ hostDB.keys[ssh.KeyAlgoECDSA256][25]++ conn, err := server.TryDial(conf) if err == nil { conn.Close() t.Fatalf("dial should have failed.") } else if !strings.Contains(err.Error(), "host key mismatch") { t.Fatalf("'host key mismatch' not found in %v", err) } } func TestRunCommandStdin(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() r, w := io.Pipe() defer r.Close() defer w.Close() session.Stdin = r err = session.Run("true") if err != nil { t.Fatalf("session failed: %v", err) } } func TestRunCommandStdinError(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() r, w := io.Pipe() defer r.Close() session.Stdin = r pipeErr := errors.New("closing write end of pipe") w.CloseWithError(pipeErr) err = session.Run("true") if err != pipeErr { t.Fatalf("expected %v, found %v", pipeErr, err) } } func TestRunCommandFailed(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() err = session.Run(`bash -c "kill -9 $$"`) if err == nil { t.Fatalf("session succeeded: %v", err) } } func TestRunCommandWeClosed(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } err = session.Shell() if err != nil { t.Fatalf("shell failed: %v", err) } err = session.Close() if err != nil { t.Fatalf("shell failed: %v", err) } } func TestFuncLargeRead(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("unable to create new session: %s", err) } stdout, err := session.StdoutPipe() if err != nil { t.Fatalf("unable to acquire stdout pipe: %s", err) } err = session.Start("dd if=/dev/urandom bs=2048 count=1024") if err != nil { t.Fatalf("unable to execute remote command: %s", err) } buf := new(bytes.Buffer) n, err := io.Copy(buf, stdout) if err != nil { t.Fatalf("error reading from remote stdout: %s", err) } if n != 2048*1024 { t.Fatalf("Expected %d bytes but read only %d from remote command", 2048, n) } } func TestKeyChange(t *testing.T) { server := newServer(t) defer server.Shutdown() conf := clientConfig() hostDB := hostKeyDB() conf.HostKeyCallback = hostDB.Check conf.RekeyThreshold = 1024 conn := server.Dial(conf) defer conn.Close() for i := 0; i < 4; i++ { session, err := conn.NewSession() if err != nil { t.Fatalf("unable to create new session: %s", err) } stdout, err := session.StdoutPipe() if err != nil { t.Fatalf("unable to acquire stdout pipe: %s", err) } err = session.Start("dd if=/dev/urandom bs=1024 count=1") if err != nil { t.Fatalf("unable to execute remote command: %s", err) } buf := new(bytes.Buffer) n, err := io.Copy(buf, stdout) if err != nil { t.Fatalf("error reading from remote stdout: %s", err) } want := int64(1024) if n != want { t.Fatalf("Expected %d bytes but read only %d from remote command", want, n) } } if changes := hostDB.checkCount; changes < 4 { t.Errorf("got %d key changes, want 4", changes) } } func TestInvalidTerminalMode(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() if err = session.RequestPty("vt100", 80, 40, ssh.TerminalModes{255: 1984}); err == nil { t.Fatalf("req-pty failed: successful request with invalid mode") } } func TestValidTerminalMode(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() stdout, err := session.StdoutPipe() if err != nil { t.Fatalf("unable to acquire stdout pipe: %s", err) } stdin, err := session.StdinPipe() if err != nil { t.Fatalf("unable to acquire stdin pipe: %s", err) } tm := ssh.TerminalModes{ssh.ECHO: 0} if err = session.RequestPty("xterm", 80, 40, tm); err != nil { t.Fatalf("req-pty failed: %s", err) } err = session.Shell() if err != nil { t.Fatalf("session failed: %s", err) } stdin.Write([]byte("stty -a && exit\n")) var buf bytes.Buffer if _, err := io.Copy(&buf, stdout); err != nil { t.Fatalf("reading failed: %s", err) } if sttyOutput := buf.String(); !strings.Contains(sttyOutput, "-echo ") { t.Fatalf("terminal mode failure: expected -echo in stty output, got %s", sttyOutput) } } func TestWindowChange(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() stdout, err := session.StdoutPipe() if err != nil { t.Fatalf("unable to acquire stdout pipe: %s", err) } stdin, err := session.StdinPipe() if err != nil { t.Fatalf("unable to acquire stdin pipe: %s", err) } tm := ssh.TerminalModes{ssh.ECHO: 0} if err = session.RequestPty("xterm", 80, 40, tm); err != nil { t.Fatalf("req-pty failed: %s", err) } if err := session.WindowChange(100, 100); err != nil { t.Fatalf("window-change failed: %s", err) } err = session.Shell() if err != nil { t.Fatalf("session failed: %s", err) } stdin.Write([]byte("stty size && exit\n")) var buf bytes.Buffer if _, err := io.Copy(&buf, stdout); err != nil { t.Fatalf("reading failed: %s", err) } if sttyOutput := buf.String(); !strings.Contains(sttyOutput, "100 100") { t.Fatalf("terminal WindowChange failure: expected \"100 100\" stty output, got %s", sttyOutput) } } func TestCiphers(t *testing.T) { var config ssh.Config config.SetDefaults() cipherOrder := config.Ciphers // These ciphers will not be tested when commented out in cipher.go it will // fallback to the next available as per line 292. cipherOrder = append(cipherOrder, "aes128-cbc", "3des-cbc") for _, ciph := range cipherOrder { server := newServer(t) defer server.Shutdown() conf := clientConfig() conf.Ciphers = []string{ciph} // Don't fail if sshd doesn't have the cipher. conf.Ciphers = append(conf.Ciphers, cipherOrder...) conn, err := server.TryDial(conf) if err == nil { conn.Close() } else { t.Fatalf("failed for cipher %q", ciph) } } } func TestMACs(t *testing.T) { var config ssh.Config config.SetDefaults() macOrder := config.MACs for _, mac := range macOrder { server := newServer(t) defer server.Shutdown() conf := clientConfig() conf.MACs = []string{mac} // Don't fail if sshd doesn't have the MAC. conf.MACs = append(conf.MACs, macOrder...) if conn, err := server.TryDial(conf); err == nil { conn.Close() } else { t.Fatalf("failed for MAC %q", mac) } } } func TestKeyExchanges(t *testing.T) { var config ssh.Config config.SetDefaults() kexOrder := config.KeyExchanges for _, kex := range kexOrder { server := newServer(t) defer server.Shutdown() conf := clientConfig() // Don't fail if sshd doesn't have the kex. conf.KeyExchanges = append([]string{kex}, kexOrder...) conn, err := server.TryDial(conf) if err == nil { conn.Close() } else { t.Errorf("failed for kex %q", kex) } } } func TestClientAuthAlgorithms(t *testing.T) { for _, key := range []string{ "rsa", "dsa", "ecdsa", "ed25519", } { server := newServer(t) conf := clientConfig() conf.SetDefaults() conf.Auth = []ssh.AuthMethod{ ssh.PublicKeys(testSigners[key]), } conn, err := server.TryDial(conf) if err == nil { conn.Close() } else { t.Errorf("failed for key %q", key) } server.Shutdown() } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/forward_unix_test.go�������������������������������0000644�0610621�0607500�00000007772�13172163317�026740� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd package test import ( "bytes" "io" "io/ioutil" "math/rand" "net" "testing" "time" ) type closeWriter interface { CloseWrite() error } func testPortForward(t *testing.T, n, listenAddr string) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() sshListener, err := conn.Listen(n, listenAddr) if err != nil { t.Fatal(err) } go func() { sshConn, err := sshListener.Accept() if err != nil { t.Fatalf("listen.Accept failed: %v", err) } _, err = io.Copy(sshConn, sshConn) if err != nil && err != io.EOF { t.Fatalf("ssh client copy: %v", err) } sshConn.Close() }() forwardedAddr := sshListener.Addr().String() netConn, err := net.Dial(n, forwardedAddr) if err != nil { t.Fatalf("net dial failed: %v", err) } readChan := make(chan []byte) go func() { data, _ := ioutil.ReadAll(netConn) readChan <- data }() // Invent some data. data := make([]byte, 100*1000) for i := range data { data[i] = byte(i % 255) } var sent []byte for len(sent) < 1000*1000 { // Send random sized chunks m := rand.Intn(len(data)) n, err := netConn.Write(data[:m]) if err != nil { break } sent = append(sent, data[:n]...) } if err := netConn.(closeWriter).CloseWrite(); err != nil { t.Errorf("netConn.CloseWrite: %v", err) } read := <-readChan if len(sent) != len(read) { t.Fatalf("got %d bytes, want %d", len(read), len(sent)) } if bytes.Compare(sent, read) != 0 { t.Fatalf("read back data does not match") } if err := sshListener.Close(); err != nil { t.Fatalf("sshListener.Close: %v", err) } // Check that the forward disappeared. netConn, err = net.Dial(n, forwardedAddr) if err == nil { netConn.Close() t.Errorf("still listening to %s after closing", forwardedAddr) } } func TestPortForwardTCP(t *testing.T) { testPortForward(t, "tcp", "localhost:0") } func TestPortForwardUnix(t *testing.T) { addr, cleanup := newTempSocket(t) defer cleanup() testPortForward(t, "unix", addr) } func testAcceptClose(t *testing.T, n, listenAddr string) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) sshListener, err := conn.Listen(n, listenAddr) if err != nil { t.Fatal(err) } quit := make(chan error, 1) go func() { for { c, err := sshListener.Accept() if err != nil { quit <- err break } c.Close() } }() sshListener.Close() select { case <-time.After(1 * time.Second): t.Errorf("timeout: listener did not close.") case err := <-quit: t.Logf("quit as expected (error %v)", err) } } func TestAcceptCloseTCP(t *testing.T) { testAcceptClose(t, "tcp", "localhost:0") } func TestAcceptCloseUnix(t *testing.T) { addr, cleanup := newTempSocket(t) defer cleanup() testAcceptClose(t, "unix", addr) } // Check that listeners exit if the underlying client transport dies. func testPortForwardConnectionClose(t *testing.T, n, listenAddr string) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) sshListener, err := conn.Listen(n, listenAddr) if err != nil { t.Fatal(err) } quit := make(chan error, 1) go func() { for { c, err := sshListener.Accept() if err != nil { quit <- err break } c.Close() } }() // It would be even nicer if we closed the server side, but it // is more involved as the fd for that side is dup()ed. server.clientConn.Close() select { case <-time.After(1 * time.Second): t.Errorf("timeout: listener did not close.") case err := <-quit: t.Logf("quit as expected (error %v)", err) } } func TestPortForwardConnectionCloseTCP(t *testing.T) { testPortForwardConnectionClose(t, "tcp", "localhost:0") } func TestPortForwardConnectionCloseUnix(t *testing.T) { addr, cleanup := newTempSocket(t) defer cleanup() testPortForwardConnectionClose(t, "unix", addr) } ������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/doc.go���������������������������������������������0000644�0610621�0607500�00000000455�13172163317�023726� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This package contains integration tests for the // golang.org/x/crypto/ssh package. package test // import "golang.org/x/crypto/ssh/test" �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/dial_unix_test.go����������������������������������0000644�0610621�0607500�00000005735�13172163317�026202� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !windows package test // direct-tcpip and direct-streamlocal functional tests import ( "fmt" "io" "io/ioutil" "net" "strings" "testing" ) type dialTester interface { TestServerConn(t *testing.T, c net.Conn) TestClientConn(t *testing.T, c net.Conn) } func testDial(t *testing.T, n, listenAddr string, x dialTester) { server := newServer(t) defer server.Shutdown() sshConn := server.Dial(clientConfig()) defer sshConn.Close() l, err := net.Listen(n, listenAddr) if err != nil { t.Fatalf("Listen: %v", err) } defer l.Close() testData := fmt.Sprintf("hello from %s, %s", n, listenAddr) go func() { for { c, err := l.Accept() if err != nil { break } x.TestServerConn(t, c) io.WriteString(c, testData) c.Close() } }() conn, err := sshConn.Dial(n, l.Addr().String()) if err != nil { t.Fatalf("Dial: %v", err) } x.TestClientConn(t, conn) defer conn.Close() b, err := ioutil.ReadAll(conn) if err != nil { t.Fatalf("ReadAll: %v", err) } t.Logf("got %q", string(b)) if string(b) != testData { t.Fatalf("expected %q, got %q", testData, string(b)) } } type tcpDialTester struct { listenAddr string } func (x *tcpDialTester) TestServerConn(t *testing.T, c net.Conn) { host := strings.Split(x.listenAddr, ":")[0] prefix := host + ":" if !strings.HasPrefix(c.LocalAddr().String(), prefix) { t.Fatalf("expected to start with %q, got %q", prefix, c.LocalAddr().String()) } if !strings.HasPrefix(c.RemoteAddr().String(), prefix) { t.Fatalf("expected to start with %q, got %q", prefix, c.RemoteAddr().String()) } } func (x *tcpDialTester) TestClientConn(t *testing.T, c net.Conn) { // we use zero addresses. see *Client.Dial. if c.LocalAddr().String() != "0.0.0.0:0" { t.Fatalf("expected \"0.0.0.0:0\", got %q", c.LocalAddr().String()) } if c.RemoteAddr().String() != "0.0.0.0:0" { t.Fatalf("expected \"0.0.0.0:0\", got %q", c.RemoteAddr().String()) } } func TestDialTCP(t *testing.T) { x := &tcpDialTester{ listenAddr: "127.0.0.1:0", } testDial(t, "tcp", x.listenAddr, x) } type unixDialTester struct { listenAddr string } func (x *unixDialTester) TestServerConn(t *testing.T, c net.Conn) { if c.LocalAddr().String() != x.listenAddr { t.Fatalf("expected %q, got %q", x.listenAddr, c.LocalAddr().String()) } if c.RemoteAddr().String() != "@" { t.Fatalf("expected \"@\", got %q", c.RemoteAddr().String()) } } func (x *unixDialTester) TestClientConn(t *testing.T, c net.Conn) { if c.RemoteAddr().String() != x.listenAddr { t.Fatalf("expected %q, got %q", x.listenAddr, c.RemoteAddr().String()) } if c.LocalAddr().String() != "@" { t.Fatalf("expected \"@\", got %q", c.LocalAddr().String()) } } func TestDialUnix(t *testing.T) { addr, cleanup := newTempSocket(t) defer cleanup() x := &unixDialTester{ listenAddr: addr, } testDial(t, "unix", x.listenAddr, x) } �����������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/cert_test.go���������������������������������������0000644�0610621�0607500�00000003775�13172163317�025165� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd package test import ( "bytes" "crypto/rand" "testing" "golang.org/x/crypto/ssh" ) // Test both logging in with a cert, and also that the certificate presented by an OpenSSH host can be validated correctly func TestCertLogin(t *testing.T) { s := newServer(t) defer s.Shutdown() // Use a key different from the default. clientKey := testSigners["dsa"] caAuthKey := testSigners["ecdsa"] cert := &ssh.Certificate{ Key: clientKey.PublicKey(), ValidPrincipals: []string{username()}, CertType: ssh.UserCert, ValidBefore: ssh.CertTimeInfinity, } if err := cert.SignCert(rand.Reader, caAuthKey); err != nil { t.Fatalf("SetSignature: %v", err) } certSigner, err := ssh.NewCertSigner(cert, clientKey) if err != nil { t.Fatalf("NewCertSigner: %v", err) } conf := &ssh.ClientConfig{ User: username(), HostKeyCallback: (&ssh.CertChecker{ IsHostAuthority: func(pk ssh.PublicKey, addr string) bool { return bytes.Equal(pk.Marshal(), testPublicKeys["ca"].Marshal()) }, }).CheckHostKey, } conf.Auth = append(conf.Auth, ssh.PublicKeys(certSigner)) for _, test := range []struct { addr string succeed bool }{ {addr: "host.example.com:22", succeed: true}, {addr: "host.example.com:10000", succeed: true}, // non-standard port must be OK {addr: "host.example.com", succeed: false}, // port must be specified {addr: "host.ex4mple.com:22", succeed: false}, // wrong host } { client, err := s.TryDialWithAddr(conf, test.addr) // Always close client if opened successfully if err == nil { client.Close() } // Now evaluate whether the test failed or passed if test.succeed { if err != nil { t.Fatalf("TryDialWithAddr: %v", err) } } else { if err == nil { t.Fatalf("TryDialWithAddr, unexpected success") } } } } ���lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/test/agent_unix_test.go���������������������������������0000644�0610621�0607500�00000003042�13172163317�026354� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd package test import ( "bytes" "testing" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" ) func TestAgentForward(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() keyring := agent.NewKeyring() if err := keyring.Add(agent.AddedKey{PrivateKey: testPrivateKeys["dsa"]}); err != nil { t.Fatalf("Error adding key: %s", err) } if err := keyring.Add(agent.AddedKey{ PrivateKey: testPrivateKeys["dsa"], ConfirmBeforeUse: true, LifetimeSecs: 3600, }); err != nil { t.Fatalf("Error adding key with constraints: %s", err) } pub := testPublicKeys["dsa"] sess, err := conn.NewSession() if err != nil { t.Fatalf("NewSession: %v", err) } if err := agent.RequestAgentForwarding(sess); err != nil { t.Fatalf("RequestAgentForwarding: %v", err) } if err := agent.ForwardToAgent(conn, keyring); err != nil { t.Fatalf("SetupForwardKeyring: %v", err) } out, err := sess.CombinedOutput("ssh-add -L") if err != nil { t.Fatalf("running ssh-add: %v, out %s", err, out) } key, _, _, _, err := ssh.ParseAuthorizedKey(out) if err != nil { t.Fatalf("ParseAuthorizedKey(%q): %v", out, err) } if !bytes.Equal(key.Marshal(), pub.Marshal()) { t.Fatalf("got key %s, want %s", ssh.MarshalAuthorizedKey(key), ssh.MarshalAuthorizedKey(pub)) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023462� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/util_windows.go��������������������������������0000644�0610621�0607500�00000006011�13172163317�026536� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows // Package terminal provides support functions for dealing with terminals, as // commonly found on UNIX systems. // // Putting a terminal into raw mode is the most common requirement: // // oldState, err := terminal.MakeRaw(0) // if err != nil { // panic(err) // } // defer terminal.Restore(0, oldState) package terminal import ( "golang.org/x/sys/windows" ) type State struct { mode uint32 } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd int) bool { var st uint32 err := windows.GetConsoleMode(windows.Handle(fd), &st) return err == nil } // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd int) (*State, error) { var st uint32 if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil { return nil, err } raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT) if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil { return nil, err } return &State{st}, nil } // GetState returns the current state of a terminal which may be useful to // restore the terminal after a signal. func GetState(fd int) (*State, error) { var st uint32 if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil { return nil, err } return &State{st}, nil } // Restore restores the terminal connected to the given file descriptor to a // previous state. func Restore(fd int, state *State) error { return windows.SetConsoleMode(windows.Handle(fd), state.mode) } // GetSize returns the dimensions of the given terminal. func GetSize(fd int) (width, height int, err error) { var info windows.ConsoleScreenBufferInfo if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); err != nil { return 0, 0, err } return int(info.Size.X), int(info.Size.Y), nil } // passwordReader is an io.Reader that reads from a specific Windows HANDLE. type passwordReader int func (r passwordReader) Read(buf []byte) (int, error) { return windows.Read(windows.Handle(r), buf) } // ReadPassword reads a line of input from a terminal without local echo. This // is commonly used for inputting passwords and other sensitive data. The slice // returned does not include the \n. func ReadPassword(fd int) ([]byte, error) { var st uint32 if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil { return nil, err } old := st st &^= (windows.ENABLE_ECHO_INPUT) st |= (windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT) if err := windows.SetConsoleMode(windows.Handle(fd), st); err != nil { return nil, err } defer func() { windows.SetConsoleMode(windows.Handle(fd), old) }() return readPasswordLine(passwordReader(fd)) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/util_solaris.go��������������������������������0000644�0610621�0607500�00000006447�13172163317�026535� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build solaris package terminal // import "golang.org/x/crypto/ssh/terminal" import ( "golang.org/x/sys/unix" "io" "syscall" ) // State contains the state of a terminal. type State struct { state *unix.Termios } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd int) bool { _, err := unix.IoctlGetTermio(fd, unix.TCGETA) return err == nil } // ReadPassword reads a line of input from a terminal without local echo. This // is commonly used for inputting passwords and other sensitive data. The slice // returned does not include the \n. func ReadPassword(fd int) ([]byte, error) { // see also: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libast/common/uwin/getpass.c val, err := unix.IoctlGetTermios(fd, unix.TCGETS) if err != nil { return nil, err } oldState := *val newState := oldState newState.Lflag &^= syscall.ECHO newState.Lflag |= syscall.ICANON | syscall.ISIG newState.Iflag |= syscall.ICRNL err = unix.IoctlSetTermios(fd, unix.TCSETS, &newState) if err != nil { return nil, err } defer unix.IoctlSetTermios(fd, unix.TCSETS, &oldState) var buf [16]byte var ret []byte for { n, err := syscall.Read(fd, buf[:]) if err != nil { return nil, err } if n == 0 { if len(ret) == 0 { return nil, io.EOF } break } if buf[n-1] == '\n' { n-- } ret = append(ret, buf[:n]...) if n < len(buf) { break } } return ret, nil } // MakeRaw puts the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. // see http://cr.illumos.org/~webrev/andy_js/1060/ func MakeRaw(fd int) (*State, error) { oldTermiosPtr, err := unix.IoctlGetTermios(fd, unix.TCGETS) if err != nil { return nil, err } oldTermios := *oldTermiosPtr newTermios := oldTermios newTermios.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON newTermios.Oflag &^= syscall.OPOST newTermios.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN newTermios.Cflag &^= syscall.CSIZE | syscall.PARENB newTermios.Cflag |= syscall.CS8 newTermios.Cc[unix.VMIN] = 1 newTermios.Cc[unix.VTIME] = 0 if err := unix.IoctlSetTermios(fd, unix.TCSETS, &newTermios); err != nil { return nil, err } return &State{ state: oldTermiosPtr, }, nil } // Restore restores the terminal connected to the given file descriptor to a // previous state. func Restore(fd int, oldState *State) error { return unix.IoctlSetTermios(fd, unix.TCSETS, oldState.state) } // GetState returns the current state of a terminal which may be useful to // restore the terminal after a signal. func GetState(fd int) (*State, error) { oldTermiosPtr, err := unix.IoctlGetTermios(fd, unix.TCGETS) if err != nil { return nil, err } return &State{ state: oldTermiosPtr, }, nil } // GetSize returns the dimensions of the given terminal. func GetSize(fd int) (width, height int, err error) { ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ) if err != nil { return 0, 0, err } return int(ws.Col), int(ws.Row), nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/util_plan9.go����������������������������������0000644�0610621�0607500�00000003754�13172163317�026102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package terminal provides support functions for dealing with terminals, as // commonly found on UNIX systems. // // Putting a terminal into raw mode is the most common requirement: // // oldState, err := terminal.MakeRaw(0) // if err != nil { // panic(err) // } // defer terminal.Restore(0, oldState) package terminal import ( "fmt" "runtime" ) type State struct{} // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd int) bool { return false } // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd int) (*State, error) { return nil, fmt.Errorf("terminal: MakeRaw not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } // GetState returns the current state of a terminal which may be useful to // restore the terminal after a signal. func GetState(fd int) (*State, error) { return nil, fmt.Errorf("terminal: GetState not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } // Restore restores the terminal connected to the given file descriptor to a // previous state. func Restore(fd int, state *State) error { return fmt.Errorf("terminal: Restore not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } // GetSize returns the dimensions of the given terminal. func GetSize(fd int) (width, height int, err error) { return 0, 0, fmt.Errorf("terminal: GetSize not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } // ReadPassword reads a line of input from a terminal without local echo. This // is commonly used for inputting passwords and other sensitive data. The slice // returned does not include the \n. func ReadPassword(fd int) ([]byte, error) { return nil, fmt.Errorf("terminal: ReadPassword not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } ��������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/util_linux.go����������������������������������0000644�0610621�0607500�00000000435�13172163317�026207� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package terminal import "golang.org/x/sys/unix" const ioctlReadTermios = unix.TCGETS const ioctlWriteTermios = unix.TCSETS �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/util_bsd.go������������������������������������0000644�0610621�0607500�00000000524�13172163317�025617� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd openbsd package terminal import "golang.org/x/sys/unix" const ioctlReadTermios = unix.TIOCGETA const ioctlWriteTermios = unix.TIOCSETA ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/util.go����������������������������������������0000644�0610621�0607500�00000010367�13172163317�024775� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux,!appengine netbsd openbsd // Package terminal provides support functions for dealing with terminals, as // commonly found on UNIX systems. // // Putting a terminal into raw mode is the most common requirement: // // oldState, err := terminal.MakeRaw(0) // if err != nil { // panic(err) // } // defer terminal.Restore(0, oldState) package terminal // import "golang.org/x/crypto/ssh/terminal" import ( "syscall" "unsafe" "golang.org/x/sys/unix" ) // State contains the state of a terminal. type State struct { termios syscall.Termios } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd int) bool { var termios syscall.Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd int) (*State, error) { var oldState State if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 { return nil, err } newState := oldState.termios // This attempts to replicate the behaviour documented for cfmakeraw in // the termios(3) manpage. newState.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON newState.Oflag &^= syscall.OPOST newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN newState.Cflag &^= syscall.CSIZE | syscall.PARENB newState.Cflag |= syscall.CS8 newState.Cc[unix.VMIN] = 1 newState.Cc[unix.VTIME] = 0 if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 { return nil, err } return &oldState, nil } // GetState returns the current state of a terminal which may be useful to // restore the terminal after a signal. func GetState(fd int) (*State, error) { var oldState State if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 { return nil, err } return &oldState, nil } // Restore restores the terminal connected to the given file descriptor to a // previous state. func Restore(fd int, state *State) error { if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&state.termios)), 0, 0, 0); err != 0 { return err } return nil } // GetSize returns the dimensions of the given terminal. func GetSize(fd int) (width, height int, err error) { var dimensions [4]uint16 if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&dimensions)), 0, 0, 0); err != 0 { return -1, -1, err } return int(dimensions[1]), int(dimensions[0]), nil } // passwordReader is an io.Reader that reads from a specific file descriptor. type passwordReader int func (r passwordReader) Read(buf []byte) (int, error) { return syscall.Read(int(r), buf) } // ReadPassword reads a line of input from a terminal without local echo. This // is commonly used for inputting passwords and other sensitive data. The slice // returned does not include the \n. func ReadPassword(fd int) ([]byte, error) { var oldState syscall.Termios if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); err != 0 { return nil, err } newState := oldState newState.Lflag &^= syscall.ECHO newState.Lflag |= syscall.ICANON | syscall.ISIG newState.Iflag |= syscall.ICRNL if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 { return nil, err } defer func() { syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0) }() return readPasswordLine(passwordReader(fd)) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/terminal_test.go�������������������������������0000644�0610621�0607500�00000016233�13172163317�026670� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package terminal import ( "bytes" "io" "os" "testing" ) type MockTerminal struct { toSend []byte bytesPerRead int received []byte } func (c *MockTerminal) Read(data []byte) (n int, err error) { n = len(data) if n == 0 { return } if n > len(c.toSend) { n = len(c.toSend) } if n == 0 { return 0, io.EOF } if c.bytesPerRead > 0 && n > c.bytesPerRead { n = c.bytesPerRead } copy(data, c.toSend[:n]) c.toSend = c.toSend[n:] return } func (c *MockTerminal) Write(data []byte) (n int, err error) { c.received = append(c.received, data...) return len(data), nil } func TestClose(t *testing.T) { c := &MockTerminal{} ss := NewTerminal(c, "> ") line, err := ss.ReadLine() if line != "" { t.Errorf("Expected empty line but got: %s", line) } if err != io.EOF { t.Errorf("Error should have been EOF but got: %s", err) } } var keyPressTests = []struct { in string line string err error throwAwayLines int }{ { err: io.EOF, }, { in: "\r", line: "", }, { in: "foo\r", line: "foo", }, { in: "a\x1b[Cb\r", // right line: "ab", }, { in: "a\x1b[Db\r", // left line: "ba", }, { in: "a\177b\r", // backspace line: "b", }, { in: "\x1b[A\r", // up }, { in: "\x1b[B\r", // down }, { in: "line\x1b[A\x1b[B\r", // up then down line: "line", }, { in: "line1\rline2\x1b[A\r", // recall previous line. line: "line1", throwAwayLines: 1, }, { // recall two previous lines and append. in: "line1\rline2\rline3\x1b[A\x1b[Axxx\r", line: "line1xxx", throwAwayLines: 2, }, { // Ctrl-A to move to beginning of line followed by ^K to kill // line. in: "a b \001\013\r", line: "", }, { // Ctrl-A to move to beginning of line, Ctrl-E to move to end, // finally ^K to kill nothing. in: "a b \001\005\013\r", line: "a b ", }, { in: "\027\r", line: "", }, { in: "a\027\r", line: "", }, { in: "a \027\r", line: "", }, { in: "a b\027\r", line: "a ", }, { in: "a b \027\r", line: "a ", }, { in: "one two thr\x1b[D\027\r", line: "one two r", }, { in: "\013\r", line: "", }, { in: "a\013\r", line: "a", }, { in: "ab\x1b[D\013\r", line: "a", }, { in: "Ξεσκεπάζω\r", line: "Ξεσκεπάζω", }, { in: "£\r\x1b[A\177\r", // non-ASCII char, enter, up, backspace. line: "", throwAwayLines: 1, }, { in: "£\r££\x1b[A\x1b[B\177\r", // non-ASCII char, enter, 2x non-ASCII, up, down, backspace, enter. line: "£", throwAwayLines: 1, }, { // Ctrl-D at the end of the line should be ignored. in: "a\004\r", line: "a", }, { // a, b, left, Ctrl-D should erase the b. in: "ab\x1b[D\004\r", line: "a", }, { // a, b, c, d, left, left, ^U should erase to the beginning of // the line. in: "abcd\x1b[D\x1b[D\025\r", line: "cd", }, { // Bracketed paste mode: control sequences should be returned // verbatim in paste mode. in: "abc\x1b[200~de\177f\x1b[201~\177\r", line: "abcde\177", }, { // Enter in bracketed paste mode should still work. in: "abc\x1b[200~d\refg\x1b[201~h\r", line: "efgh", throwAwayLines: 1, }, { // Lines consisting entirely of pasted data should be indicated as such. in: "\x1b[200~a\r", line: "a", err: ErrPasteIndicator, }, } func TestKeyPresses(t *testing.T) { for i, test := range keyPressTests { for j := 1; j < len(test.in); j++ { c := &MockTerminal{ toSend: []byte(test.in), bytesPerRead: j, } ss := NewTerminal(c, "> ") for k := 0; k < test.throwAwayLines; k++ { _, err := ss.ReadLine() if err != nil { t.Errorf("Throwaway line %d from test %d resulted in error: %s", k, i, err) } } line, err := ss.ReadLine() if line != test.line { t.Errorf("Line resulting from test %d (%d bytes per read) was '%s', expected '%s'", i, j, line, test.line) break } if err != test.err { t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err) break } } } } func TestPasswordNotSaved(t *testing.T) { c := &MockTerminal{ toSend: []byte("password\r\x1b[A\r"), bytesPerRead: 1, } ss := NewTerminal(c, "> ") pw, _ := ss.ReadPassword("> ") if pw != "password" { t.Fatalf("failed to read password, got %s", pw) } line, _ := ss.ReadLine() if len(line) > 0 { t.Fatalf("password was saved in history") } } var setSizeTests = []struct { width, height int }{ {40, 13}, {80, 24}, {132, 43}, } func TestTerminalSetSize(t *testing.T) { for _, setSize := range setSizeTests { c := &MockTerminal{ toSend: []byte("password\r\x1b[A\r"), bytesPerRead: 1, } ss := NewTerminal(c, "> ") ss.SetSize(setSize.width, setSize.height) pw, _ := ss.ReadPassword("Password: ") if pw != "password" { t.Fatalf("failed to read password, got %s", pw) } if string(c.received) != "Password: \r\n" { t.Errorf("failed to set the temporary prompt expected %q, got %q", "Password: ", c.received) } } } func TestReadPasswordLineEnd(t *testing.T) { var tests = []struct { input string want string }{ {"\n", ""}, {"\r\n", ""}, {"test\r\n", "test"}, {"testtesttesttes\n", "testtesttesttes"}, {"testtesttesttes\r\n", "testtesttesttes"}, {"testtesttesttesttest\n", "testtesttesttesttest"}, {"testtesttesttesttest\r\n", "testtesttesttesttest"}, } for _, test := range tests { buf := new(bytes.Buffer) if _, err := buf.WriteString(test.input); err != nil { t.Fatal(err) } have, err := readPasswordLine(buf) if err != nil { t.Errorf("readPasswordLine(%q) failed: %v", test.input, err) continue } if string(have) != test.want { t.Errorf("readPasswordLine(%q) returns %q, but %q is expected", test.input, string(have), test.want) continue } if _, err = buf.WriteString(test.input); err != nil { t.Fatal(err) } have, err = readPasswordLine(buf) if err != nil { t.Errorf("readPasswordLine(%q) failed: %v", test.input, err) continue } if string(have) != test.want { t.Errorf("readPasswordLine(%q) returns %q, but %q is expected", test.input, string(have), test.want) continue } } } func TestMakeRawState(t *testing.T) { fd := int(os.Stdout.Fd()) if !IsTerminal(fd) { t.Skip("stdout is not a terminal; skipping test") } st, err := GetState(fd) if err != nil { t.Fatalf("failed to get terminal state from GetState: %s", err) } defer Restore(fd, st) raw, err := MakeRaw(fd) if err != nil { t.Fatalf("failed to get terminal state from MakeRaw: %s", err) } if *st != *raw { t.Errorf("states do not match; was %v, expected %v", raw, st) } } func TestOutputNewlines(t *testing.T) { // \n should be changed to \r\n in terminal output. buf := new(bytes.Buffer) term := NewTerminal(buf, ">") term.Write([]byte("1\n2\n")) output := string(buf.Bytes()) const expected = "1\r\n2\r\n" if output != expected { t.Errorf("incorrect output: was %q, expected %q", output, expected) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/terminal/terminal.go������������������������������������0000644�0610621�0607500�00000053125�13172163317�025632� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package terminal import ( "bytes" "io" "sync" "unicode/utf8" ) // EscapeCodes contains escape sequences that can be written to the terminal in // order to achieve different styles of text. type EscapeCodes struct { // Foreground colors Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte // Reset all attributes Reset []byte } var vt100EscapeCodes = EscapeCodes{ Black: []byte{keyEscape, '[', '3', '0', 'm'}, Red: []byte{keyEscape, '[', '3', '1', 'm'}, Green: []byte{keyEscape, '[', '3', '2', 'm'}, Yellow: []byte{keyEscape, '[', '3', '3', 'm'}, Blue: []byte{keyEscape, '[', '3', '4', 'm'}, Magenta: []byte{keyEscape, '[', '3', '5', 'm'}, Cyan: []byte{keyEscape, '[', '3', '6', 'm'}, White: []byte{keyEscape, '[', '3', '7', 'm'}, Reset: []byte{keyEscape, '[', '0', 'm'}, } // Terminal contains the state for running a VT100 terminal that is capable of // reading lines of input. type Terminal struct { // AutoCompleteCallback, if non-null, is called for each keypress with // the full input line and the current position of the cursor (in // bytes, as an index into |line|). If it returns ok=false, the key // press is processed normally. Otherwise it returns a replacement line // and the new cursor position. AutoCompleteCallback func(line string, pos int, key rune) (newLine string, newPos int, ok bool) // Escape contains a pointer to the escape codes for this terminal. // It's always a valid pointer, although the escape codes themselves // may be empty if the terminal doesn't support them. Escape *EscapeCodes // lock protects the terminal and the state in this object from // concurrent processing of a key press and a Write() call. lock sync.Mutex c io.ReadWriter prompt []rune // line is the current line being entered. line []rune // pos is the logical position of the cursor in line pos int // echo is true if local echo is enabled echo bool // pasteActive is true iff there is a bracketed paste operation in // progress. pasteActive bool // cursorX contains the current X value of the cursor where the left // edge is 0. cursorY contains the row number where the first row of // the current line is 0. cursorX, cursorY int // maxLine is the greatest value of cursorY so far. maxLine int termWidth, termHeight int // outBuf contains the terminal data to be sent. outBuf []byte // remainder contains the remainder of any partial key sequences after // a read. It aliases into inBuf. remainder []byte inBuf [256]byte // history contains previously entered commands so that they can be // accessed with the up and down keys. history stRingBuffer // historyIndex stores the currently accessed history entry, where zero // means the immediately previous entry. historyIndex int // When navigating up and down the history it's possible to return to // the incomplete, initial line. That value is stored in // historyPending. historyPending string } // NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is // a local terminal, that terminal must first have been put into raw mode. // prompt is a string that is written at the start of each input line (i.e. // "> "). func NewTerminal(c io.ReadWriter, prompt string) *Terminal { return &Terminal{ Escape: &vt100EscapeCodes, c: c, prompt: []rune(prompt), termWidth: 80, termHeight: 24, echo: true, historyIndex: -1, } } const ( keyCtrlD = 4 keyCtrlU = 21 keyEnter = '\r' keyEscape = 27 keyBackspace = 127 keyUnknown = 0xd800 /* UTF-16 surrogate area */ + iota keyUp keyDown keyLeft keyRight keyAltLeft keyAltRight keyHome keyEnd keyDeleteWord keyDeleteLine keyClearScreen keyPasteStart keyPasteEnd ) var ( crlf = []byte{'\r', '\n'} pasteStart = []byte{keyEscape, '[', '2', '0', '0', '~'} pasteEnd = []byte{keyEscape, '[', '2', '0', '1', '~'} ) // bytesToKey tries to parse a key sequence from b. If successful, it returns // the key and the remainder of the input. Otherwise it returns utf8.RuneError. func bytesToKey(b []byte, pasteActive bool) (rune, []byte) { if len(b) == 0 { return utf8.RuneError, nil } if !pasteActive { switch b[0] { case 1: // ^A return keyHome, b[1:] case 5: // ^E return keyEnd, b[1:] case 8: // ^H return keyBackspace, b[1:] case 11: // ^K return keyDeleteLine, b[1:] case 12: // ^L return keyClearScreen, b[1:] case 23: // ^W return keyDeleteWord, b[1:] } } if b[0] != keyEscape { if !utf8.FullRune(b) { return utf8.RuneError, b } r, l := utf8.DecodeRune(b) return r, b[l:] } if !pasteActive && len(b) >= 3 && b[0] == keyEscape && b[1] == '[' { switch b[2] { case 'A': return keyUp, b[3:] case 'B': return keyDown, b[3:] case 'C': return keyRight, b[3:] case 'D': return keyLeft, b[3:] case 'H': return keyHome, b[3:] case 'F': return keyEnd, b[3:] } } if !pasteActive && len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' { switch b[5] { case 'C': return keyAltRight, b[6:] case 'D': return keyAltLeft, b[6:] } } if !pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteStart) { return keyPasteStart, b[6:] } if pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteEnd) { return keyPasteEnd, b[6:] } // If we get here then we have a key that we don't recognise, or a // partial sequence. It's not clear how one should find the end of a // sequence without knowing them all, but it seems that [a-zA-Z~] only // appears at the end of a sequence. for i, c := range b[0:] { if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '~' { return keyUnknown, b[i+1:] } } return utf8.RuneError, b } // queue appends data to the end of t.outBuf func (t *Terminal) queue(data []rune) { t.outBuf = append(t.outBuf, []byte(string(data))...) } var eraseUnderCursor = []rune{' ', keyEscape, '[', 'D'} var space = []rune{' '} func isPrintable(key rune) bool { isInSurrogateArea := key >= 0xd800 && key <= 0xdbff return key >= 32 && !isInSurrogateArea } // moveCursorToPos appends data to t.outBuf which will move the cursor to the // given, logical position in the text. func (t *Terminal) moveCursorToPos(pos int) { if !t.echo { return } x := visualLength(t.prompt) + pos y := x / t.termWidth x = x % t.termWidth up := 0 if y < t.cursorY { up = t.cursorY - y } down := 0 if y > t.cursorY { down = y - t.cursorY } left := 0 if x < t.cursorX { left = t.cursorX - x } right := 0 if x > t.cursorX { right = x - t.cursorX } t.cursorX = x t.cursorY = y t.move(up, down, left, right) } func (t *Terminal) move(up, down, left, right int) { movement := make([]rune, 3*(up+down+left+right)) m := movement for i := 0; i < up; i++ { m[0] = keyEscape m[1] = '[' m[2] = 'A' m = m[3:] } for i := 0; i < down; i++ { m[0] = keyEscape m[1] = '[' m[2] = 'B' m = m[3:] } for i := 0; i < left; i++ { m[0] = keyEscape m[1] = '[' m[2] = 'D' m = m[3:] } for i := 0; i < right; i++ { m[0] = keyEscape m[1] = '[' m[2] = 'C' m = m[3:] } t.queue(movement) } func (t *Terminal) clearLineToRight() { op := []rune{keyEscape, '[', 'K'} t.queue(op) } const maxLineLength = 4096 func (t *Terminal) setLine(newLine []rune, newPos int) { if t.echo { t.moveCursorToPos(0) t.writeLine(newLine) for i := len(newLine); i < len(t.line); i++ { t.writeLine(space) } t.moveCursorToPos(newPos) } t.line = newLine t.pos = newPos } func (t *Terminal) advanceCursor(places int) { t.cursorX += places t.cursorY += t.cursorX / t.termWidth if t.cursorY > t.maxLine { t.maxLine = t.cursorY } t.cursorX = t.cursorX % t.termWidth if places > 0 && t.cursorX == 0 { // Normally terminals will advance the current position // when writing a character. But that doesn't happen // for the last character in a line. However, when // writing a character (except a new line) that causes // a line wrap, the position will be advanced two // places. // // So, if we are stopping at the end of a line, we // need to write a newline so that our cursor can be // advanced to the next line. t.outBuf = append(t.outBuf, '\r', '\n') } } func (t *Terminal) eraseNPreviousChars(n int) { if n == 0 { return } if t.pos < n { n = t.pos } t.pos -= n t.moveCursorToPos(t.pos) copy(t.line[t.pos:], t.line[n+t.pos:]) t.line = t.line[:len(t.line)-n] if t.echo { t.writeLine(t.line[t.pos:]) for i := 0; i < n; i++ { t.queue(space) } t.advanceCursor(n) t.moveCursorToPos(t.pos) } } // countToLeftWord returns then number of characters from the cursor to the // start of the previous word. func (t *Terminal) countToLeftWord() int { if t.pos == 0 { return 0 } pos := t.pos - 1 for pos > 0 { if t.line[pos] != ' ' { break } pos-- } for pos > 0 { if t.line[pos] == ' ' { pos++ break } pos-- } return t.pos - pos } // countToRightWord returns then number of characters from the cursor to the // start of the next word. func (t *Terminal) countToRightWord() int { pos := t.pos for pos < len(t.line) { if t.line[pos] == ' ' { break } pos++ } for pos < len(t.line) { if t.line[pos] != ' ' { break } pos++ } return pos - t.pos } // visualLength returns the number of visible glyphs in s. func visualLength(runes []rune) int { inEscapeSeq := false length := 0 for _, r := range runes { switch { case inEscapeSeq: if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') { inEscapeSeq = false } case r == '\x1b': inEscapeSeq = true default: length++ } } return length } // handleKey processes the given key and, optionally, returns a line of text // that the user has entered. func (t *Terminal) handleKey(key rune) (line string, ok bool) { if t.pasteActive && key != keyEnter { t.addKeyToLine(key) return } switch key { case keyBackspace: if t.pos == 0 { return } t.eraseNPreviousChars(1) case keyAltLeft: // move left by a word. t.pos -= t.countToLeftWord() t.moveCursorToPos(t.pos) case keyAltRight: // move right by a word. t.pos += t.countToRightWord() t.moveCursorToPos(t.pos) case keyLeft: if t.pos == 0 { return } t.pos-- t.moveCursorToPos(t.pos) case keyRight: if t.pos == len(t.line) { return } t.pos++ t.moveCursorToPos(t.pos) case keyHome: if t.pos == 0 { return } t.pos = 0 t.moveCursorToPos(t.pos) case keyEnd: if t.pos == len(t.line) { return } t.pos = len(t.line) t.moveCursorToPos(t.pos) case keyUp: entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1) if !ok { return "", false } if t.historyIndex == -1 { t.historyPending = string(t.line) } t.historyIndex++ runes := []rune(entry) t.setLine(runes, len(runes)) case keyDown: switch t.historyIndex { case -1: return case 0: runes := []rune(t.historyPending) t.setLine(runes, len(runes)) t.historyIndex-- default: entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1) if ok { t.historyIndex-- runes := []rune(entry) t.setLine(runes, len(runes)) } } case keyEnter: t.moveCursorToPos(len(t.line)) t.queue([]rune("\r\n")) line = string(t.line) ok = true t.line = t.line[:0] t.pos = 0 t.cursorX = 0 t.cursorY = 0 t.maxLine = 0 case keyDeleteWord: // Delete zero or more spaces and then one or more characters. t.eraseNPreviousChars(t.countToLeftWord()) case keyDeleteLine: // Delete everything from the current cursor position to the // end of line. for i := t.pos; i < len(t.line); i++ { t.queue(space) t.advanceCursor(1) } t.line = t.line[:t.pos] t.moveCursorToPos(t.pos) case keyCtrlD: // Erase the character under the current position. // The EOF case when the line is empty is handled in // readLine(). if t.pos < len(t.line) { t.pos++ t.eraseNPreviousChars(1) } case keyCtrlU: t.eraseNPreviousChars(t.pos) case keyClearScreen: // Erases the screen and moves the cursor to the home position. t.queue([]rune("\x1b[2J\x1b[H")) t.queue(t.prompt) t.cursorX, t.cursorY = 0, 0 t.advanceCursor(visualLength(t.prompt)) t.setLine(t.line, t.pos) default: if t.AutoCompleteCallback != nil { prefix := string(t.line[:t.pos]) suffix := string(t.line[t.pos:]) t.lock.Unlock() newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key) t.lock.Lock() if completeOk { t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos])) return } } if !isPrintable(key) { return } if len(t.line) == maxLineLength { return } t.addKeyToLine(key) } return } // addKeyToLine inserts the given key at the current position in the current // line. func (t *Terminal) addKeyToLine(key rune) { if len(t.line) == cap(t.line) { newLine := make([]rune, len(t.line), 2*(1+len(t.line))) copy(newLine, t.line) t.line = newLine } t.line = t.line[:len(t.line)+1] copy(t.line[t.pos+1:], t.line[t.pos:]) t.line[t.pos] = key if t.echo { t.writeLine(t.line[t.pos:]) } t.pos++ t.moveCursorToPos(t.pos) } func (t *Terminal) writeLine(line []rune) { for len(line) != 0 { remainingOnLine := t.termWidth - t.cursorX todo := len(line) if todo > remainingOnLine { todo = remainingOnLine } t.queue(line[:todo]) t.advanceCursor(visualLength(line[:todo])) line = line[todo:] } } // writeWithCRLF writes buf to w but replaces all occurrences of \n with \r\n. func writeWithCRLF(w io.Writer, buf []byte) (n int, err error) { for len(buf) > 0 { i := bytes.IndexByte(buf, '\n') todo := len(buf) if i >= 0 { todo = i } var nn int nn, err = w.Write(buf[:todo]) n += nn if err != nil { return n, err } buf = buf[todo:] if i >= 0 { if _, err = w.Write(crlf); err != nil { return n, err } n += 1 buf = buf[1:] } } return n, nil } func (t *Terminal) Write(buf []byte) (n int, err error) { t.lock.Lock() defer t.lock.Unlock() if t.cursorX == 0 && t.cursorY == 0 { // This is the easy case: there's nothing on the screen that we // have to move out of the way. return writeWithCRLF(t.c, buf) } // We have a prompt and possibly user input on the screen. We // have to clear it first. t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */) t.cursorX = 0 t.clearLineToRight() for t.cursorY > 0 { t.move(1 /* up */, 0, 0, 0) t.cursorY-- t.clearLineToRight() } if _, err = t.c.Write(t.outBuf); err != nil { return } t.outBuf = t.outBuf[:0] if n, err = writeWithCRLF(t.c, buf); err != nil { return } t.writeLine(t.prompt) if t.echo { t.writeLine(t.line) } t.moveCursorToPos(t.pos) if _, err = t.c.Write(t.outBuf); err != nil { return } t.outBuf = t.outBuf[:0] return } // ReadPassword temporarily changes the prompt and reads a password, without // echo, from the terminal. func (t *Terminal) ReadPassword(prompt string) (line string, err error) { t.lock.Lock() defer t.lock.Unlock() oldPrompt := t.prompt t.prompt = []rune(prompt) t.echo = false line, err = t.readLine() t.prompt = oldPrompt t.echo = true return } // ReadLine returns a line of input from the terminal. func (t *Terminal) ReadLine() (line string, err error) { t.lock.Lock() defer t.lock.Unlock() return t.readLine() } func (t *Terminal) readLine() (line string, err error) { // t.lock must be held at this point if t.cursorX == 0 && t.cursorY == 0 { t.writeLine(t.prompt) t.c.Write(t.outBuf) t.outBuf = t.outBuf[:0] } lineIsPasted := t.pasteActive for { rest := t.remainder lineOk := false for !lineOk { var key rune key, rest = bytesToKey(rest, t.pasteActive) if key == utf8.RuneError { break } if !t.pasteActive { if key == keyCtrlD { if len(t.line) == 0 { return "", io.EOF } } if key == keyPasteStart { t.pasteActive = true if len(t.line) == 0 { lineIsPasted = true } continue } } else if key == keyPasteEnd { t.pasteActive = false continue } if !t.pasteActive { lineIsPasted = false } line, lineOk = t.handleKey(key) } if len(rest) > 0 { n := copy(t.inBuf[:], rest) t.remainder = t.inBuf[:n] } else { t.remainder = nil } t.c.Write(t.outBuf) t.outBuf = t.outBuf[:0] if lineOk { if t.echo { t.historyIndex = -1 t.history.Add(line) } if lineIsPasted { err = ErrPasteIndicator } return } // t.remainder is a slice at the beginning of t.inBuf // containing a partial key sequence readBuf := t.inBuf[len(t.remainder):] var n int t.lock.Unlock() n, err = t.c.Read(readBuf) t.lock.Lock() if err != nil { return } t.remainder = t.inBuf[:n+len(t.remainder)] } } // SetPrompt sets the prompt to be used when reading subsequent lines. func (t *Terminal) SetPrompt(prompt string) { t.lock.Lock() defer t.lock.Unlock() t.prompt = []rune(prompt) } func (t *Terminal) clearAndRepaintLinePlusNPrevious(numPrevLines int) { // Move cursor to column zero at the start of the line. t.move(t.cursorY, 0, t.cursorX, 0) t.cursorX, t.cursorY = 0, 0 t.clearLineToRight() for t.cursorY < numPrevLines { // Move down a line t.move(0, 1, 0, 0) t.cursorY++ t.clearLineToRight() } // Move back to beginning. t.move(t.cursorY, 0, 0, 0) t.cursorX, t.cursorY = 0, 0 t.queue(t.prompt) t.advanceCursor(visualLength(t.prompt)) t.writeLine(t.line) t.moveCursorToPos(t.pos) } func (t *Terminal) SetSize(width, height int) error { t.lock.Lock() defer t.lock.Unlock() if width == 0 { width = 1 } oldWidth := t.termWidth t.termWidth, t.termHeight = width, height switch { case width == oldWidth: // If the width didn't change then nothing else needs to be // done. return nil case len(t.line) == 0 && t.cursorX == 0 && t.cursorY == 0: // If there is nothing on current line and no prompt printed, // just do nothing return nil case width < oldWidth: // Some terminals (e.g. xterm) will truncate lines that were // too long when shinking. Others, (e.g. gnome-terminal) will // attempt to wrap them. For the former, repainting t.maxLine // works great, but that behaviour goes badly wrong in the case // of the latter because they have doubled every full line. // We assume that we are working on a terminal that wraps lines // and adjust the cursor position based on every previous line // wrapping and turning into two. This causes the prompt on // xterms to move upwards, which isn't great, but it avoids a // huge mess with gnome-terminal. if t.cursorX >= t.termWidth { t.cursorX = t.termWidth - 1 } t.cursorY *= 2 t.clearAndRepaintLinePlusNPrevious(t.maxLine * 2) case width > oldWidth: // If the terminal expands then our position calculations will // be wrong in the future because we think the cursor is // |t.pos| chars into the string, but there will be a gap at // the end of any wrapped line. // // But the position will actually be correct until we move, so // we can move back to the beginning and repaint everything. t.clearAndRepaintLinePlusNPrevious(t.maxLine) } _, err := t.c.Write(t.outBuf) t.outBuf = t.outBuf[:0] return err } type pasteIndicatorError struct{} func (pasteIndicatorError) Error() string { return "terminal: ErrPasteIndicator not correctly handled" } // ErrPasteIndicator may be returned from ReadLine as the error, in addition // to valid line data. It indicates that bracketed paste mode is enabled and // that the returned line consists only of pasted data. Programs may wish to // interpret pasted data more literally than typed data. var ErrPasteIndicator = pasteIndicatorError{} // SetBracketedPasteMode requests that the terminal bracket paste operations // with markers. Not all terminals support this but, if it is supported, then // enabling this mode will stop any autocomplete callback from running due to // pastes. Additionally, any lines that are completely pasted will be returned // from ReadLine with the error set to ErrPasteIndicator. func (t *Terminal) SetBracketedPasteMode(on bool) { if on { io.WriteString(t.c, "\x1b[?2004h") } else { io.WriteString(t.c, "\x1b[?2004l") } } // stRingBuffer is a ring buffer of strings. type stRingBuffer struct { // entries contains max elements. entries []string max int // head contains the index of the element most recently added to the ring. head int // size contains the number of elements in the ring. size int } func (s *stRingBuffer) Add(a string) { if s.entries == nil { const defaultNumEntries = 100 s.entries = make([]string, defaultNumEntries) s.max = defaultNumEntries } s.head = (s.head + 1) % s.max s.entries[s.head] = a if s.size < s.max { s.size++ } } // NthPreviousEntry returns the value passed to the nth previous call to Add. // If n is zero then the immediately prior value is returned, if one, then the // next most recent, and so on. If such an element doesn't exist then ok is // false. func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) { if n >= s.size { return "", false } index := s.head - n if index < 0 { index += s.max } return s.entries[index], true } // readPasswordLine reads from reader until it finds \n or io.EOF. // The slice returned does not include the \n. // readPasswordLine also ignores any \r it finds. func readPasswordLine(reader io.Reader) ([]byte, error) { var buf [1]byte var ret []byte for { n, err := reader.Read(buf[:]) if n > 0 { switch buf[0] { case '\n': return ret, nil case '\r': // remove \r from passwords on Windows default: ret = append(ret, buf[0]) } continue } if err != nil { if err == io.EOF && len(ret) > 0 { return ret, nil } return ret, err } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/tcpip_test.go�������������������������������������������0000644�0610621�0607500�00000000760�13172163317�024357� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "testing" ) func TestAutoPortListenBroken(t *testing.T) { broken := "SSH-2.0-OpenSSH_5.9hh11" works := "SSH-2.0-OpenSSH_6.1" if !isBrokenOpenSSHVersion(broken) { t.Errorf("version %q not marked as broken", broken) } if isBrokenOpenSSHVersion(works) { t.Errorf("version %q marked as broken", works) } } ����������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/tcpip.go������������������������������������������������0000644�0610621�0607500�00000027206�13172163317�023324� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "errors" "fmt" "io" "math/rand" "net" "strconv" "strings" "sync" "time" ) // Listen requests the remote peer open a listening socket on // addr. Incoming connections will be available by calling Accept on // the returned net.Listener. The listener must be serviced, or the // SSH connection may hang. // N must be "tcp", "tcp4", "tcp6", or "unix". func (c *Client) Listen(n, addr string) (net.Listener, error) { switch n { case "tcp", "tcp4", "tcp6": laddr, err := net.ResolveTCPAddr(n, addr) if err != nil { return nil, err } return c.ListenTCP(laddr) case "unix": return c.ListenUnix(addr) default: return nil, fmt.Errorf("ssh: unsupported protocol: %s", n) } } // Automatic port allocation is broken with OpenSSH before 6.0. See // also https://bugzilla.mindrot.org/show_bug.cgi?id=2017. In // particular, OpenSSH 5.9 sends a channelOpenMsg with port number 0, // rather than the actual port number. This means you can never open // two different listeners with auto allocated ports. We work around // this by trying explicit ports until we succeed. const openSSHPrefix = "OpenSSH_" var portRandomizer = rand.New(rand.NewSource(time.Now().UnixNano())) // isBrokenOpenSSHVersion returns true if the given version string // specifies a version of OpenSSH that is known to have a bug in port // forwarding. func isBrokenOpenSSHVersion(versionStr string) bool { i := strings.Index(versionStr, openSSHPrefix) if i < 0 { return false } i += len(openSSHPrefix) j := i for ; j < len(versionStr); j++ { if versionStr[j] < '0' || versionStr[j] > '9' { break } } version, _ := strconv.Atoi(versionStr[i:j]) return version < 6 } // autoPortListenWorkaround simulates automatic port allocation by // trying random ports repeatedly. func (c *Client) autoPortListenWorkaround(laddr *net.TCPAddr) (net.Listener, error) { var sshListener net.Listener var err error const tries = 10 for i := 0; i < tries; i++ { addr := *laddr addr.Port = 1024 + portRandomizer.Intn(60000) sshListener, err = c.ListenTCP(&addr) if err == nil { laddr.Port = addr.Port return sshListener, err } } return nil, fmt.Errorf("ssh: listen on random port failed after %d tries: %v", tries, err) } // RFC 4254 7.1 type channelForwardMsg struct { addr string rport uint32 } // ListenTCP requests the remote peer open a listening socket // on laddr. Incoming connections will be available by calling // Accept on the returned net.Listener. func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) { if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) { return c.autoPortListenWorkaround(laddr) } m := channelForwardMsg{ laddr.IP.String(), uint32(laddr.Port), } // send message ok, resp, err := c.SendRequest("tcpip-forward", true, Marshal(&m)) if err != nil { return nil, err } if !ok { return nil, errors.New("ssh: tcpip-forward request denied by peer") } // If the original port was 0, then the remote side will // supply a real port number in the response. if laddr.Port == 0 { var p struct { Port uint32 } if err := Unmarshal(resp, &p); err != nil { return nil, err } laddr.Port = int(p.Port) } // Register this forward, using the port number we obtained. ch := c.forwards.add(laddr) return &tcpListener{laddr, c, ch}, nil } // forwardList stores a mapping between remote // forward requests and the tcpListeners. type forwardList struct { sync.Mutex entries []forwardEntry } // forwardEntry represents an established mapping of a laddr on a // remote ssh server to a channel connected to a tcpListener. type forwardEntry struct { laddr net.Addr c chan forward } // forward represents an incoming forwarded tcpip connection. The // arguments to add/remove/lookup should be address as specified in // the original forward-request. type forward struct { newCh NewChannel // the ssh client channel underlying this forward raddr net.Addr // the raddr of the incoming connection } func (l *forwardList) add(addr net.Addr) chan forward { l.Lock() defer l.Unlock() f := forwardEntry{ laddr: addr, c: make(chan forward, 1), } l.entries = append(l.entries, f) return f.c } // See RFC 4254, section 7.2 type forwardedTCPPayload struct { Addr string Port uint32 OriginAddr string OriginPort uint32 } // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr. func parseTCPAddr(addr string, port uint32) (*net.TCPAddr, error) { if port == 0 || port > 65535 { return nil, fmt.Errorf("ssh: port number out of range: %d", port) } ip := net.ParseIP(string(addr)) if ip == nil { return nil, fmt.Errorf("ssh: cannot parse IP address %q", addr) } return &net.TCPAddr{IP: ip, Port: int(port)}, nil } func (l *forwardList) handleChannels(in <-chan NewChannel) { for ch := range in { var ( laddr net.Addr raddr net.Addr err error ) switch channelType := ch.ChannelType(); channelType { case "forwarded-tcpip": var payload forwardedTCPPayload if err = Unmarshal(ch.ExtraData(), &payload); err != nil { ch.Reject(ConnectionFailed, "could not parse forwarded-tcpip payload: "+err.Error()) continue } // RFC 4254 section 7.2 specifies that incoming // addresses should list the address, in string // format. It is implied that this should be an IP // address, as it would be impossible to connect to it // otherwise. laddr, err = parseTCPAddr(payload.Addr, payload.Port) if err != nil { ch.Reject(ConnectionFailed, err.Error()) continue } raddr, err = parseTCPAddr(payload.OriginAddr, payload.OriginPort) if err != nil { ch.Reject(ConnectionFailed, err.Error()) continue } case "forwarded-streamlocal@openssh.com": var payload forwardedStreamLocalPayload if err = Unmarshal(ch.ExtraData(), &payload); err != nil { ch.Reject(ConnectionFailed, "could not parse forwarded-streamlocal@openssh.com payload: "+err.Error()) continue } laddr = &net.UnixAddr{ Name: payload.SocketPath, Net: "unix", } raddr = &net.UnixAddr{ Name: "@", Net: "unix", } default: panic(fmt.Errorf("ssh: unknown channel type %s", channelType)) } if ok := l.forward(laddr, raddr, ch); !ok { // Section 7.2, implementations MUST reject spurious incoming // connections. ch.Reject(Prohibited, "no forward for address") continue } } } // remove removes the forward entry, and the channel feeding its // listener. func (l *forwardList) remove(addr net.Addr) { l.Lock() defer l.Unlock() for i, f := range l.entries { if addr.Network() == f.laddr.Network() && addr.String() == f.laddr.String() { l.entries = append(l.entries[:i], l.entries[i+1:]...) close(f.c) return } } } // closeAll closes and clears all forwards. func (l *forwardList) closeAll() { l.Lock() defer l.Unlock() for _, f := range l.entries { close(f.c) } l.entries = nil } func (l *forwardList) forward(laddr, raddr net.Addr, ch NewChannel) bool { l.Lock() defer l.Unlock() for _, f := range l.entries { if laddr.Network() == f.laddr.Network() && laddr.String() == f.laddr.String() { f.c <- forward{newCh: ch, raddr: raddr} return true } } return false } type tcpListener struct { laddr *net.TCPAddr conn *Client in <-chan forward } // Accept waits for and returns the next connection to the listener. func (l *tcpListener) Accept() (net.Conn, error) { s, ok := <-l.in if !ok { return nil, io.EOF } ch, incoming, err := s.newCh.Accept() if err != nil { return nil, err } go DiscardRequests(incoming) return &chanConn{ Channel: ch, laddr: l.laddr, raddr: s.raddr, }, nil } // Close closes the listener. func (l *tcpListener) Close() error { m := channelForwardMsg{ l.laddr.IP.String(), uint32(l.laddr.Port), } // this also closes the listener. l.conn.forwards.remove(l.laddr) ok, _, err := l.conn.SendRequest("cancel-tcpip-forward", true, Marshal(&m)) if err == nil && !ok { err = errors.New("ssh: cancel-tcpip-forward failed") } return err } // Addr returns the listener's network address. func (l *tcpListener) Addr() net.Addr { return l.laddr } // Dial initiates a connection to the addr from the remote host. // The resulting connection has a zero LocalAddr() and RemoteAddr(). func (c *Client) Dial(n, addr string) (net.Conn, error) { var ch Channel switch n { case "tcp", "tcp4", "tcp6": // Parse the address into host and numeric port. host, portString, err := net.SplitHostPort(addr) if err != nil { return nil, err } port, err := strconv.ParseUint(portString, 10, 16) if err != nil { return nil, err } ch, err = c.dial(net.IPv4zero.String(), 0, host, int(port)) if err != nil { return nil, err } // Use a zero address for local and remote address. zeroAddr := &net.TCPAddr{ IP: net.IPv4zero, Port: 0, } return &chanConn{ Channel: ch, laddr: zeroAddr, raddr: zeroAddr, }, nil case "unix": var err error ch, err = c.dialStreamLocal(addr) if err != nil { return nil, err } return &chanConn{ Channel: ch, laddr: &net.UnixAddr{ Name: "@", Net: "unix", }, raddr: &net.UnixAddr{ Name: addr, Net: "unix", }, }, nil default: return nil, fmt.Errorf("ssh: unsupported protocol: %s", n) } } // DialTCP connects to the remote address raddr on the network net, // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used // as the local address for the connection. func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) { if laddr == nil { laddr = &net.TCPAddr{ IP: net.IPv4zero, Port: 0, } } ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port) if err != nil { return nil, err } return &chanConn{ Channel: ch, laddr: laddr, raddr: raddr, }, nil } // RFC 4254 7.2 type channelOpenDirectMsg struct { raddr string rport uint32 laddr string lport uint32 } func (c *Client) dial(laddr string, lport int, raddr string, rport int) (Channel, error) { msg := channelOpenDirectMsg{ raddr: raddr, rport: uint32(rport), laddr: laddr, lport: uint32(lport), } ch, in, err := c.OpenChannel("direct-tcpip", Marshal(&msg)) if err != nil { return nil, err } go DiscardRequests(in) return ch, err } type tcpChan struct { Channel // the backing channel } // chanConn fulfills the net.Conn interface without // the tcpChan having to hold laddr or raddr directly. type chanConn struct { Channel laddr, raddr net.Addr } // LocalAddr returns the local network address. func (t *chanConn) LocalAddr() net.Addr { return t.laddr } // RemoteAddr returns the remote network address. func (t *chanConn) RemoteAddr() net.Addr { return t.raddr } // SetDeadline sets the read and write deadlines associated // with the connection. func (t *chanConn) SetDeadline(deadline time.Time) error { if err := t.SetReadDeadline(deadline); err != nil { return err } return t.SetWriteDeadline(deadline) } // SetReadDeadline sets the read deadline. // A zero value for t means Read will not time out. // After the deadline, the error from Read will implement net.Error // with Timeout() == true. func (t *chanConn) SetReadDeadline(deadline time.Time) error { // for compatibility with previous version, // the error message contains "tcpChan" return errors.New("ssh: tcpChan: deadline not supported") } // SetWriteDeadline exists to satisfy the net.Conn interface // but is not implemented by this type. It always returns an error. func (t *chanConn) SetWriteDeadline(deadline time.Time) error { return errors.New("ssh: tcpChan: deadline not supported") } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/streamlocal.go������������������������������������������0000644�0610621�0607500�00000005520�13172163317�024506� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ssh import ( "errors" "io" "net" ) // streamLocalChannelOpenDirectMsg is a struct used for SSH_MSG_CHANNEL_OPEN message // with "direct-streamlocal@openssh.com" string. // // See openssh-portable/PROTOCOL, section 2.4. connection: Unix domain socket forwarding // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL#L235 type streamLocalChannelOpenDirectMsg struct { socketPath string reserved0 string reserved1 uint32 } // forwardedStreamLocalPayload is a struct used for SSH_MSG_CHANNEL_OPEN message // with "forwarded-streamlocal@openssh.com" string. type forwardedStreamLocalPayload struct { SocketPath string Reserved0 string } // streamLocalChannelForwardMsg is a struct used for SSH2_MSG_GLOBAL_REQUEST message // with "streamlocal-forward@openssh.com"/"cancel-streamlocal-forward@openssh.com" string. type streamLocalChannelForwardMsg struct { socketPath string } // ListenUnix is similar to ListenTCP but uses a Unix domain socket. func (c *Client) ListenUnix(socketPath string) (net.Listener, error) { m := streamLocalChannelForwardMsg{ socketPath, } // send message ok, _, err := c.SendRequest("streamlocal-forward@openssh.com", true, Marshal(&m)) if err != nil { return nil, err } if !ok { return nil, errors.New("ssh: streamlocal-forward@openssh.com request denied by peer") } ch := c.forwards.add(&net.UnixAddr{Name: socketPath, Net: "unix"}) return &unixListener{socketPath, c, ch}, nil } func (c *Client) dialStreamLocal(socketPath string) (Channel, error) { msg := streamLocalChannelOpenDirectMsg{ socketPath: socketPath, } ch, in, err := c.OpenChannel("direct-streamlocal@openssh.com", Marshal(&msg)) if err != nil { return nil, err } go DiscardRequests(in) return ch, err } type unixListener struct { socketPath string conn *Client in <-chan forward } // Accept waits for and returns the next connection to the listener. func (l *unixListener) Accept() (net.Conn, error) { s, ok := <-l.in if !ok { return nil, io.EOF } ch, incoming, err := s.newCh.Accept() if err != nil { return nil, err } go DiscardRequests(incoming) return &chanConn{ Channel: ch, laddr: &net.UnixAddr{ Name: l.socketPath, Net: "unix", }, raddr: &net.UnixAddr{ Name: "@", Net: "unix", }, }, nil } // Close closes the listener. func (l *unixListener) Close() error { // this also closes the listener. l.conn.forwards.remove(&net.UnixAddr{Name: l.socketPath, Net: "unix"}) m := streamLocalChannelForwardMsg{ l.socketPath, } ok, _, err := l.conn.SendRequest("cancel-streamlocal-forward@openssh.com", true, Marshal(&m)) if err == nil && !ok { err = errors.New("ssh: cancel-streamlocal-forward@openssh.com failed") } return err } // Addr returns the listener's network address. func (l *unixListener) Addr() net.Addr { return &net.UnixAddr{ Name: l.socketPath, Net: "unix", } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/session_test.go�����������������������������������������0000644�0610621�0607500�00000046252�13172163317�024731� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh // Session tests. import ( "bytes" crypto_rand "crypto/rand" "errors" "io" "io/ioutil" "math/rand" "net" "testing" "golang.org/x/crypto/ssh/terminal" ) type serverType func(Channel, <-chan *Request, *testing.T) // dial constructs a new test server and returns a *ClientConn. func dial(handler serverType, t *testing.T) *Client { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } go func() { defer c1.Close() conf := ServerConfig{ NoClientAuth: true, } conf.AddHostKey(testSigners["rsa"]) _, chans, reqs, err := NewServerConn(c1, &conf) if err != nil { t.Fatalf("Unable to handshake: %v", err) } go DiscardRequests(reqs) for newCh := range chans { if newCh.ChannelType() != "session" { newCh.Reject(UnknownChannelType, "unknown channel type") continue } ch, inReqs, err := newCh.Accept() if err != nil { t.Errorf("Accept: %v", err) continue } go func() { handler(ch, inReqs, t) }() } }() config := &ClientConfig{ User: "testuser", HostKeyCallback: InsecureIgnoreHostKey(), } conn, chans, reqs, err := NewClientConn(c2, "", config) if err != nil { t.Fatalf("unable to dial remote side: %v", err) } return NewClient(conn, chans, reqs) } // Test a simple string is returned to session.Stdout. func TestSessionShell(t *testing.T) { conn := dial(shellHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() stdout := new(bytes.Buffer) session.Stdout = stdout if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %s", err) } if err := session.Wait(); err != nil { t.Fatalf("Remote command did not exit cleanly: %v", err) } actual := stdout.String() if actual != "golang" { t.Fatalf("Remote shell did not return expected string: expected=golang, actual=%s", actual) } } // TODO(dfc) add support for Std{in,err}Pipe when the Server supports it. // Test a simple string is returned via StdoutPipe. func TestSessionStdoutPipe(t *testing.T) { conn := dial(shellHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() stdout, err := session.StdoutPipe() if err != nil { t.Fatalf("Unable to request StdoutPipe(): %v", err) } var buf bytes.Buffer if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %v", err) } done := make(chan bool, 1) go func() { if _, err := io.Copy(&buf, stdout); err != nil { t.Errorf("Copy of stdout failed: %v", err) } done <- true }() if err := session.Wait(); err != nil { t.Fatalf("Remote command did not exit cleanly: %v", err) } <-done actual := buf.String() if actual != "golang" { t.Fatalf("Remote shell did not return expected string: expected=golang, actual=%s", actual) } } // Test that a simple string is returned via the Output helper, // and that stderr is discarded. func TestSessionOutput(t *testing.T) { conn := dial(fixedOutputHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() buf, err := session.Output("") // cmd is ignored by fixedOutputHandler if err != nil { t.Error("Remote command did not exit cleanly:", err) } w := "this-is-stdout." g := string(buf) if g != w { t.Error("Remote command did not return expected string:") t.Logf("want %q", w) t.Logf("got %q", g) } } // Test that both stdout and stderr are returned // via the CombinedOutput helper. func TestSessionCombinedOutput(t *testing.T) { conn := dial(fixedOutputHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() buf, err := session.CombinedOutput("") // cmd is ignored by fixedOutputHandler if err != nil { t.Error("Remote command did not exit cleanly:", err) } const stdout = "this-is-stdout." const stderr = "this-is-stderr." g := string(buf) if g != stdout+stderr && g != stderr+stdout { t.Error("Remote command did not return expected string:") t.Logf("want %q, or %q", stdout+stderr, stderr+stdout) t.Logf("got %q", g) } } // Test non-0 exit status is returned correctly. func TestExitStatusNonZero(t *testing.T) { conn := dial(exitStatusNonZeroHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %v", err) } err = session.Wait() if err == nil { t.Fatalf("expected command to fail but it didn't") } e, ok := err.(*ExitError) if !ok { t.Fatalf("expected *ExitError but got %T", err) } if e.ExitStatus() != 15 { t.Fatalf("expected command to exit with 15 but got %v", e.ExitStatus()) } } // Test 0 exit status is returned correctly. func TestExitStatusZero(t *testing.T) { conn := dial(exitStatusZeroHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %v", err) } err = session.Wait() if err != nil { t.Fatalf("expected nil but got %v", err) } } // Test exit signal and status are both returned correctly. func TestExitSignalAndStatus(t *testing.T) { conn := dial(exitSignalAndStatusHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %v", err) } err = session.Wait() if err == nil { t.Fatalf("expected command to fail but it didn't") } e, ok := err.(*ExitError) if !ok { t.Fatalf("expected *ExitError but got %T", err) } if e.Signal() != "TERM" || e.ExitStatus() != 15 { t.Fatalf("expected command to exit with signal TERM and status 15 but got signal %s and status %v", e.Signal(), e.ExitStatus()) } } // Test exit signal and status are both returned correctly. func TestKnownExitSignalOnly(t *testing.T) { conn := dial(exitSignalHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %v", err) } err = session.Wait() if err == nil { t.Fatalf("expected command to fail but it didn't") } e, ok := err.(*ExitError) if !ok { t.Fatalf("expected *ExitError but got %T", err) } if e.Signal() != "TERM" || e.ExitStatus() != 143 { t.Fatalf("expected command to exit with signal TERM and status 143 but got signal %s and status %v", e.Signal(), e.ExitStatus()) } } // Test exit signal and status are both returned correctly. func TestUnknownExitSignal(t *testing.T) { conn := dial(exitSignalUnknownHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %v", err) } err = session.Wait() if err == nil { t.Fatalf("expected command to fail but it didn't") } e, ok := err.(*ExitError) if !ok { t.Fatalf("expected *ExitError but got %T", err) } if e.Signal() != "SYS" || e.ExitStatus() != 128 { t.Fatalf("expected command to exit with signal SYS and status 128 but got signal %s and status %v", e.Signal(), e.ExitStatus()) } } func TestExitWithoutStatusOrSignal(t *testing.T) { conn := dial(exitWithoutSignalOrStatus, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("Unable to request new session: %v", err) } defer session.Close() if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %v", err) } err = session.Wait() if err == nil { t.Fatalf("expected command to fail but it didn't") } if _, ok := err.(*ExitMissingError); !ok { t.Fatalf("got %T want *ExitMissingError", err) } } // windowTestBytes is the number of bytes that we'll send to the SSH server. const windowTestBytes = 16000 * 200 // TestServerWindow writes random data to the server. The server is expected to echo // the same data back, which is compared against the original. func TestServerWindow(t *testing.T) { origBuf := bytes.NewBuffer(make([]byte, 0, windowTestBytes)) io.CopyN(origBuf, crypto_rand.Reader, windowTestBytes) origBytes := origBuf.Bytes() conn := dial(echoHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatal(err) } defer session.Close() result := make(chan []byte) go func() { defer close(result) echoedBuf := bytes.NewBuffer(make([]byte, 0, windowTestBytes)) serverStdout, err := session.StdoutPipe() if err != nil { t.Errorf("StdoutPipe failed: %v", err) return } n, err := copyNRandomly("stdout", echoedBuf, serverStdout, windowTestBytes) if err != nil && err != io.EOF { t.Errorf("Read only %d bytes from server, expected %d: %v", n, windowTestBytes, err) } result <- echoedBuf.Bytes() }() serverStdin, err := session.StdinPipe() if err != nil { t.Fatalf("StdinPipe failed: %v", err) } written, err := copyNRandomly("stdin", serverStdin, origBuf, windowTestBytes) if err != nil { t.Fatalf("failed to copy origBuf to serverStdin: %v", err) } if written != windowTestBytes { t.Fatalf("Wrote only %d of %d bytes to server", written, windowTestBytes) } echoedBytes := <-result if !bytes.Equal(origBytes, echoedBytes) { t.Fatalf("Echoed buffer differed from original, orig %d, echoed %d", len(origBytes), len(echoedBytes)) } } // Verify the client can handle a keepalive packet from the server. func TestClientHandlesKeepalives(t *testing.T) { conn := dial(channelKeepaliveSender, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatal(err) } defer session.Close() if err := session.Shell(); err != nil { t.Fatalf("Unable to execute command: %v", err) } err = session.Wait() if err != nil { t.Fatalf("expected nil but got: %v", err) } } type exitStatusMsg struct { Status uint32 } type exitSignalMsg struct { Signal string CoreDumped bool Errmsg string Lang string } func handleTerminalRequests(in <-chan *Request) { for req := range in { ok := false switch req.Type { case "shell": ok = true if len(req.Payload) > 0 { // We don't accept any commands, only the default shell. ok = false } case "env": ok = true } req.Reply(ok, nil) } } func newServerShell(ch Channel, in <-chan *Request, prompt string) *terminal.Terminal { term := terminal.NewTerminal(ch, prompt) go handleTerminalRequests(in) return term } func exitStatusZeroHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() // this string is returned to stdout shell := newServerShell(ch, in, "> ") readLine(shell, t) sendStatus(0, ch, t) } func exitStatusNonZeroHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() shell := newServerShell(ch, in, "> ") readLine(shell, t) sendStatus(15, ch, t) } func exitSignalAndStatusHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() shell := newServerShell(ch, in, "> ") readLine(shell, t) sendStatus(15, ch, t) sendSignal("TERM", ch, t) } func exitSignalHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() shell := newServerShell(ch, in, "> ") readLine(shell, t) sendSignal("TERM", ch, t) } func exitSignalUnknownHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() shell := newServerShell(ch, in, "> ") readLine(shell, t) sendSignal("SYS", ch, t) } func exitWithoutSignalOrStatus(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() shell := newServerShell(ch, in, "> ") readLine(shell, t) } func shellHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() // this string is returned to stdout shell := newServerShell(ch, in, "golang") readLine(shell, t) sendStatus(0, ch, t) } // Ignores the command, writes fixed strings to stderr and stdout. // Strings are "this-is-stdout." and "this-is-stderr.". func fixedOutputHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() _, err := ch.Read(nil) req, ok := <-in if !ok { t.Fatalf("error: expected channel request, got: %#v", err) return } // ignore request, always send some text req.Reply(true, nil) _, err = io.WriteString(ch, "this-is-stdout.") if err != nil { t.Fatalf("error writing on server: %v", err) } _, err = io.WriteString(ch.Stderr(), "this-is-stderr.") if err != nil { t.Fatalf("error writing on server: %v", err) } sendStatus(0, ch, t) } func readLine(shell *terminal.Terminal, t *testing.T) { if _, err := shell.ReadLine(); err != nil && err != io.EOF { t.Errorf("unable to read line: %v", err) } } func sendStatus(status uint32, ch Channel, t *testing.T) { msg := exitStatusMsg{ Status: status, } if _, err := ch.SendRequest("exit-status", false, Marshal(&msg)); err != nil { t.Errorf("unable to send status: %v", err) } } func sendSignal(signal string, ch Channel, t *testing.T) { sig := exitSignalMsg{ Signal: signal, CoreDumped: false, Errmsg: "Process terminated", Lang: "en-GB-oed", } if _, err := ch.SendRequest("exit-signal", false, Marshal(&sig)); err != nil { t.Errorf("unable to send signal: %v", err) } } func discardHandler(ch Channel, t *testing.T) { defer ch.Close() io.Copy(ioutil.Discard, ch) } func echoHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() if n, err := copyNRandomly("echohandler", ch, ch, windowTestBytes); err != nil { t.Errorf("short write, wrote %d, expected %d: %v ", n, windowTestBytes, err) } } // copyNRandomly copies n bytes from src to dst. It uses a variable, and random, // buffer size to exercise more code paths. func copyNRandomly(title string, dst io.Writer, src io.Reader, n int) (int, error) { var ( buf = make([]byte, 32*1024) written int remaining = n ) for remaining > 0 { l := rand.Intn(1 << 15) if remaining < l { l = remaining } nr, er := src.Read(buf[:l]) nw, ew := dst.Write(buf[:nr]) remaining -= nw written += nw if ew != nil { return written, ew } if nr != nw { return written, io.ErrShortWrite } if er != nil && er != io.EOF { return written, er } } return written, nil } func channelKeepaliveSender(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() shell := newServerShell(ch, in, "> ") readLine(shell, t) if _, err := ch.SendRequest("keepalive@openssh.com", true, nil); err != nil { t.Errorf("unable to send channel keepalive request: %v", err) } sendStatus(0, ch, t) } func TestClientWriteEOF(t *testing.T) { conn := dial(simpleEchoHandler, t) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatal(err) } defer session.Close() stdin, err := session.StdinPipe() if err != nil { t.Fatalf("StdinPipe failed: %v", err) } stdout, err := session.StdoutPipe() if err != nil { t.Fatalf("StdoutPipe failed: %v", err) } data := []byte(`0000`) _, err = stdin.Write(data) if err != nil { t.Fatalf("Write failed: %v", err) } stdin.Close() res, err := ioutil.ReadAll(stdout) if err != nil { t.Fatalf("Read failed: %v", err) } if !bytes.Equal(data, res) { t.Fatalf("Read differed from write, wrote: %v, read: %v", data, res) } } func simpleEchoHandler(ch Channel, in <-chan *Request, t *testing.T) { defer ch.Close() data, err := ioutil.ReadAll(ch) if err != nil { t.Errorf("handler read error: %v", err) } _, err = ch.Write(data) if err != nil { t.Errorf("handler write error: %v", err) } } func TestSessionID(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serverID := make(chan []byte, 1) clientID := make(chan []byte, 1) serverConf := &ServerConfig{ NoClientAuth: true, } serverConf.AddHostKey(testSigners["ecdsa"]) clientConf := &ClientConfig{ HostKeyCallback: InsecureIgnoreHostKey(), User: "user", } go func() { conn, chans, reqs, err := NewServerConn(c1, serverConf) if err != nil { t.Fatalf("server handshake: %v", err) } serverID <- conn.SessionID() go DiscardRequests(reqs) for ch := range chans { ch.Reject(Prohibited, "") } }() go func() { conn, chans, reqs, err := NewClientConn(c2, "", clientConf) if err != nil { t.Fatalf("client handshake: %v", err) } clientID <- conn.SessionID() go DiscardRequests(reqs) for ch := range chans { ch.Reject(Prohibited, "") } }() s := <-serverID c := <-clientID if bytes.Compare(s, c) != 0 { t.Errorf("server session ID (%x) != client session ID (%x)", s, c) } else if len(s) == 0 { t.Errorf("client and server SessionID were empty.") } } type noReadConn struct { readSeen bool net.Conn } func (c *noReadConn) Close() error { return nil } func (c *noReadConn) Read(b []byte) (int, error) { c.readSeen = true return 0, errors.New("noReadConn error") } func TestInvalidServerConfiguration(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serveConn := noReadConn{Conn: c1} serverConf := &ServerConfig{} NewServerConn(&serveConn, serverConf) if serveConn.readSeen { t.Fatalf("NewServerConn attempted to Read() from Conn while configuration is missing host key") } serverConf.AddHostKey(testSigners["ecdsa"]) NewServerConn(&serveConn, serverConf) if serveConn.readSeen { t.Fatalf("NewServerConn attempted to Read() from Conn while configuration is missing authentication method") } } func TestHostKeyAlgorithms(t *testing.T) { serverConf := &ServerConfig{ NoClientAuth: true, } serverConf.AddHostKey(testSigners["rsa"]) serverConf.AddHostKey(testSigners["ecdsa"]) connect := func(clientConf *ClientConfig, want string) { var alg string clientConf.HostKeyCallback = func(h string, a net.Addr, key PublicKey) error { alg = key.Type() return nil } c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() go NewServerConn(c1, serverConf) _, _, _, err = NewClientConn(c2, "", clientConf) if err != nil { t.Fatalf("NewClientConn: %v", err) } if alg != want { t.Errorf("selected key algorithm %s, want %s", alg, want) } } // By default, we get the preferred algorithm, which is ECDSA 256. clientConf := &ClientConfig{ HostKeyCallback: InsecureIgnoreHostKey(), } connect(clientConf, KeyAlgoECDSA256) // Client asks for RSA explicitly. clientConf.HostKeyAlgorithms = []string{KeyAlgoRSA} connect(clientConf, KeyAlgoRSA) c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() go NewServerConn(c1, serverConf) clientConf.HostKeyAlgorithms = []string{"nonexistent-hostkey-algo"} _, _, _, err = NewClientConn(c2, "", clientConf) if err == nil { t.Fatal("succeeded connecting with unknown hostkey algorithm") } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/session.go����������������������������������������������0000644�0610621�0607500�00000036112�13172163317�023664� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh // Session implements an interactive session described in // "RFC 4254, section 6". import ( "bytes" "encoding/binary" "errors" "fmt" "io" "io/ioutil" "sync" ) type Signal string // POSIX signals as listed in RFC 4254 Section 6.10. const ( SIGABRT Signal = "ABRT" SIGALRM Signal = "ALRM" SIGFPE Signal = "FPE" SIGHUP Signal = "HUP" SIGILL Signal = "ILL" SIGINT Signal = "INT" SIGKILL Signal = "KILL" SIGPIPE Signal = "PIPE" SIGQUIT Signal = "QUIT" SIGSEGV Signal = "SEGV" SIGTERM Signal = "TERM" SIGUSR1 Signal = "USR1" SIGUSR2 Signal = "USR2" ) var signals = map[Signal]int{ SIGABRT: 6, SIGALRM: 14, SIGFPE: 8, SIGHUP: 1, SIGILL: 4, SIGINT: 2, SIGKILL: 9, SIGPIPE: 13, SIGQUIT: 3, SIGSEGV: 11, SIGTERM: 15, } type TerminalModes map[uint8]uint32 // POSIX terminal mode flags as listed in RFC 4254 Section 8. const ( tty_OP_END = 0 VINTR = 1 VQUIT = 2 VERASE = 3 VKILL = 4 VEOF = 5 VEOL = 6 VEOL2 = 7 VSTART = 8 VSTOP = 9 VSUSP = 10 VDSUSP = 11 VREPRINT = 12 VWERASE = 13 VLNEXT = 14 VFLUSH = 15 VSWTCH = 16 VSTATUS = 17 VDISCARD = 18 IGNPAR = 30 PARMRK = 31 INPCK = 32 ISTRIP = 33 INLCR = 34 IGNCR = 35 ICRNL = 36 IUCLC = 37 IXON = 38 IXANY = 39 IXOFF = 40 IMAXBEL = 41 ISIG = 50 ICANON = 51 XCASE = 52 ECHO = 53 ECHOE = 54 ECHOK = 55 ECHONL = 56 NOFLSH = 57 TOSTOP = 58 IEXTEN = 59 ECHOCTL = 60 ECHOKE = 61 PENDIN = 62 OPOST = 70 OLCUC = 71 ONLCR = 72 OCRNL = 73 ONOCR = 74 ONLRET = 75 CS7 = 90 CS8 = 91 PARENB = 92 PARODD = 93 TTY_OP_ISPEED = 128 TTY_OP_OSPEED = 129 ) // A Session represents a connection to a remote command or shell. type Session struct { // Stdin specifies the remote process's standard input. // If Stdin is nil, the remote process reads from an empty // bytes.Buffer. Stdin io.Reader // Stdout and Stderr specify the remote process's standard // output and error. // // If either is nil, Run connects the corresponding file // descriptor to an instance of ioutil.Discard. There is a // fixed amount of buffering that is shared for the two streams. // If either blocks it may eventually cause the remote // command to block. Stdout io.Writer Stderr io.Writer ch Channel // the channel backing this session started bool // true once Start, Run or Shell is invoked. copyFuncs []func() error errors chan error // one send per copyFunc // true if pipe method is active stdinpipe, stdoutpipe, stderrpipe bool // stdinPipeWriter is non-nil if StdinPipe has not been called // and Stdin was specified by the user; it is the write end of // a pipe connecting Session.Stdin to the stdin channel. stdinPipeWriter io.WriteCloser exitStatus chan error } // SendRequest sends an out-of-band channel request on the SSH channel // underlying the session. func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error) { return s.ch.SendRequest(name, wantReply, payload) } func (s *Session) Close() error { return s.ch.Close() } // RFC 4254 Section 6.4. type setenvRequest struct { Name string Value string } // Setenv sets an environment variable that will be applied to any // command executed by Shell or Run. func (s *Session) Setenv(name, value string) error { msg := setenvRequest{ Name: name, Value: value, } ok, err := s.ch.SendRequest("env", true, Marshal(&msg)) if err == nil && !ok { err = errors.New("ssh: setenv failed") } return err } // RFC 4254 Section 6.2. type ptyRequestMsg struct { Term string Columns uint32 Rows uint32 Width uint32 Height uint32 Modelist string } // RequestPty requests the association of a pty with the session on the remote host. func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error { var tm []byte for k, v := range termmodes { kv := struct { Key byte Val uint32 }{k, v} tm = append(tm, Marshal(&kv)...) } tm = append(tm, tty_OP_END) req := ptyRequestMsg{ Term: term, Columns: uint32(w), Rows: uint32(h), Width: uint32(w * 8), Height: uint32(h * 8), Modelist: string(tm), } ok, err := s.ch.SendRequest("pty-req", true, Marshal(&req)) if err == nil && !ok { err = errors.New("ssh: pty-req failed") } return err } // RFC 4254 Section 6.5. type subsystemRequestMsg struct { Subsystem string } // RequestSubsystem requests the association of a subsystem with the session on the remote host. // A subsystem is a predefined command that runs in the background when the ssh session is initiated func (s *Session) RequestSubsystem(subsystem string) error { msg := subsystemRequestMsg{ Subsystem: subsystem, } ok, err := s.ch.SendRequest("subsystem", true, Marshal(&msg)) if err == nil && !ok { err = errors.New("ssh: subsystem request failed") } return err } // RFC 4254 Section 6.7. type ptyWindowChangeMsg struct { Columns uint32 Rows uint32 Width uint32 Height uint32 } // WindowChange informs the remote host about a terminal window dimension change to h rows and w columns. func (s *Session) WindowChange(h, w int) error { req := ptyWindowChangeMsg{ Columns: uint32(w), Rows: uint32(h), Width: uint32(w * 8), Height: uint32(h * 8), } _, err := s.ch.SendRequest("window-change", false, Marshal(&req)) return err } // RFC 4254 Section 6.9. type signalMsg struct { Signal string } // Signal sends the given signal to the remote process. // sig is one of the SIG* constants. func (s *Session) Signal(sig Signal) error { msg := signalMsg{ Signal: string(sig), } _, err := s.ch.SendRequest("signal", false, Marshal(&msg)) return err } // RFC 4254 Section 6.5. type execMsg struct { Command string } // Start runs cmd on the remote host. Typically, the remote // server passes cmd to the shell for interpretation. // A Session only accepts one call to Run, Start or Shell. func (s *Session) Start(cmd string) error { if s.started { return errors.New("ssh: session already started") } req := execMsg{ Command: cmd, } ok, err := s.ch.SendRequest("exec", true, Marshal(&req)) if err == nil && !ok { err = fmt.Errorf("ssh: command %v failed", cmd) } if err != nil { return err } return s.start() } // Run runs cmd on the remote host. Typically, the remote // server passes cmd to the shell for interpretation. // A Session only accepts one call to Run, Start, Shell, Output, // or CombinedOutput. // // The returned error is nil if the command runs, has no problems // copying stdin, stdout, and stderr, and exits with a zero exit // status. // // If the remote server does not send an exit status, an error of type // *ExitMissingError is returned. If the command completes // unsuccessfully or is interrupted by a signal, the error is of type // *ExitError. Other error types may be returned for I/O problems. func (s *Session) Run(cmd string) error { err := s.Start(cmd) if err != nil { return err } return s.Wait() } // Output runs cmd on the remote host and returns its standard output. func (s *Session) Output(cmd string) ([]byte, error) { if s.Stdout != nil { return nil, errors.New("ssh: Stdout already set") } var b bytes.Buffer s.Stdout = &b err := s.Run(cmd) return b.Bytes(), err } type singleWriter struct { b bytes.Buffer mu sync.Mutex } func (w *singleWriter) Write(p []byte) (int, error) { w.mu.Lock() defer w.mu.Unlock() return w.b.Write(p) } // CombinedOutput runs cmd on the remote host and returns its combined // standard output and standard error. func (s *Session) CombinedOutput(cmd string) ([]byte, error) { if s.Stdout != nil { return nil, errors.New("ssh: Stdout already set") } if s.Stderr != nil { return nil, errors.New("ssh: Stderr already set") } var b singleWriter s.Stdout = &b s.Stderr = &b err := s.Run(cmd) return b.b.Bytes(), err } // Shell starts a login shell on the remote host. A Session only // accepts one call to Run, Start, Shell, Output, or CombinedOutput. func (s *Session) Shell() error { if s.started { return errors.New("ssh: session already started") } ok, err := s.ch.SendRequest("shell", true, nil) if err == nil && !ok { return errors.New("ssh: could not start shell") } if err != nil { return err } return s.start() } func (s *Session) start() error { s.started = true type F func(*Session) for _, setupFd := range []F{(*Session).stdin, (*Session).stdout, (*Session).stderr} { setupFd(s) } s.errors = make(chan error, len(s.copyFuncs)) for _, fn := range s.copyFuncs { go func(fn func() error) { s.errors <- fn() }(fn) } return nil } // Wait waits for the remote command to exit. // // The returned error is nil if the command runs, has no problems // copying stdin, stdout, and stderr, and exits with a zero exit // status. // // If the remote server does not send an exit status, an error of type // *ExitMissingError is returned. If the command completes // unsuccessfully or is interrupted by a signal, the error is of type // *ExitError. Other error types may be returned for I/O problems. func (s *Session) Wait() error { if !s.started { return errors.New("ssh: session not started") } waitErr := <-s.exitStatus if s.stdinPipeWriter != nil { s.stdinPipeWriter.Close() } var copyError error for _ = range s.copyFuncs { if err := <-s.errors; err != nil && copyError == nil { copyError = err } } if waitErr != nil { return waitErr } return copyError } func (s *Session) wait(reqs <-chan *Request) error { wm := Waitmsg{status: -1} // Wait for msg channel to be closed before returning. for msg := range reqs { switch msg.Type { case "exit-status": wm.status = int(binary.BigEndian.Uint32(msg.Payload)) case "exit-signal": var sigval struct { Signal string CoreDumped bool Error string Lang string } if err := Unmarshal(msg.Payload, &sigval); err != nil { return err } // Must sanitize strings? wm.signal = sigval.Signal wm.msg = sigval.Error wm.lang = sigval.Lang default: // This handles keepalives and matches // OpenSSH's behaviour. if msg.WantReply { msg.Reply(false, nil) } } } if wm.status == 0 { return nil } if wm.status == -1 { // exit-status was never sent from server if wm.signal == "" { // signal was not sent either. RFC 4254 // section 6.10 recommends against this // behavior, but it is allowed, so we let // clients handle it. return &ExitMissingError{} } wm.status = 128 if _, ok := signals[Signal(wm.signal)]; ok { wm.status += signals[Signal(wm.signal)] } } return &ExitError{wm} } // ExitMissingError is returned if a session is torn down cleanly, but // the server sends no confirmation of the exit status. type ExitMissingError struct{} func (e *ExitMissingError) Error() string { return "wait: remote command exited without exit status or exit signal" } func (s *Session) stdin() { if s.stdinpipe { return } var stdin io.Reader if s.Stdin == nil { stdin = new(bytes.Buffer) } else { r, w := io.Pipe() go func() { _, err := io.Copy(w, s.Stdin) w.CloseWithError(err) }() stdin, s.stdinPipeWriter = r, w } s.copyFuncs = append(s.copyFuncs, func() error { _, err := io.Copy(s.ch, stdin) if err1 := s.ch.CloseWrite(); err == nil && err1 != io.EOF { err = err1 } return err }) } func (s *Session) stdout() { if s.stdoutpipe { return } if s.Stdout == nil { s.Stdout = ioutil.Discard } s.copyFuncs = append(s.copyFuncs, func() error { _, err := io.Copy(s.Stdout, s.ch) return err }) } func (s *Session) stderr() { if s.stderrpipe { return } if s.Stderr == nil { s.Stderr = ioutil.Discard } s.copyFuncs = append(s.copyFuncs, func() error { _, err := io.Copy(s.Stderr, s.ch.Stderr()) return err }) } // sessionStdin reroutes Close to CloseWrite. type sessionStdin struct { io.Writer ch Channel } func (s *sessionStdin) Close() error { return s.ch.CloseWrite() } // StdinPipe returns a pipe that will be connected to the // remote command's standard input when the command starts. func (s *Session) StdinPipe() (io.WriteCloser, error) { if s.Stdin != nil { return nil, errors.New("ssh: Stdin already set") } if s.started { return nil, errors.New("ssh: StdinPipe after process started") } s.stdinpipe = true return &sessionStdin{s.ch, s.ch}, nil } // StdoutPipe returns a pipe that will be connected to the // remote command's standard output when the command starts. // There is a fixed amount of buffering that is shared between // stdout and stderr streams. If the StdoutPipe reader is // not serviced fast enough it may eventually cause the // remote command to block. func (s *Session) StdoutPipe() (io.Reader, error) { if s.Stdout != nil { return nil, errors.New("ssh: Stdout already set") } if s.started { return nil, errors.New("ssh: StdoutPipe after process started") } s.stdoutpipe = true return s.ch, nil } // StderrPipe returns a pipe that will be connected to the // remote command's standard error when the command starts. // There is a fixed amount of buffering that is shared between // stdout and stderr streams. If the StderrPipe reader is // not serviced fast enough it may eventually cause the // remote command to block. func (s *Session) StderrPipe() (io.Reader, error) { if s.Stderr != nil { return nil, errors.New("ssh: Stderr already set") } if s.started { return nil, errors.New("ssh: StderrPipe after process started") } s.stderrpipe = true return s.ch.Stderr(), nil } // newSession returns a new interactive session on the remote host. func newSession(ch Channel, reqs <-chan *Request) (*Session, error) { s := &Session{ ch: ch, } s.exitStatus = make(chan error, 1) go func() { s.exitStatus <- s.wait(reqs) }() return s, nil } // An ExitError reports unsuccessful completion of a remote command. type ExitError struct { Waitmsg } func (e *ExitError) Error() string { return e.Waitmsg.String() } // Waitmsg stores the information about an exited remote command // as reported by Wait. type Waitmsg struct { status int signal string msg string lang string } // ExitStatus returns the exit status of the remote command. func (w Waitmsg) ExitStatus() int { return w.status } // Signal returns the exit signal of the remote command if // it was terminated violently. func (w Waitmsg) Signal() string { return w.signal } // Msg returns the exit message given by the remote command func (w Waitmsg) Msg() string { return w.msg } // Lang returns the language tag. See RFC 3066 func (w Waitmsg) Lang() string { return w.lang } func (w Waitmsg) String() string { str := fmt.Sprintf("Process exited with status %v", w.status) if w.signal != "" { str += fmt.Sprintf(" from signal %v", w.signal) } if w.msg != "" { str += fmt.Sprintf(". Reason was: %v", w.msg) } return str } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/server.go�����������������������������������������������0000644�0610621�0607500�00000042242�13172163317�023510� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "errors" "fmt" "io" "net" "strings" ) // The Permissions type holds fine-grained permissions that are // specific to a user or a specific authentication method for a user. // The Permissions value for a successful authentication attempt is // available in ServerConn, so it can be used to pass information from // the user-authentication phase to the application layer. type Permissions struct { // CriticalOptions indicate restrictions to the default // permissions, and are typically used in conjunction with // user certificates. The standard for SSH certificates // defines "force-command" (only allow the given command to // execute) and "source-address" (only allow connections from // the given address). The SSH package currently only enforces // the "source-address" critical option. It is up to server // implementations to enforce other critical options, such as // "force-command", by checking them after the SSH handshake // is successful. In general, SSH servers should reject // connections that specify critical options that are unknown // or not supported. CriticalOptions map[string]string // Extensions are extra functionality that the server may // offer on authenticated connections. Lack of support for an // extension does not preclude authenticating a user. Common // extensions are "permit-agent-forwarding", // "permit-X11-forwarding". The Go SSH library currently does // not act on any extension, and it is up to server // implementations to honor them. Extensions can be used to // pass data from the authentication callbacks to the server // application layer. Extensions map[string]string } // ServerConfig holds server specific configuration data. type ServerConfig struct { // Config contains configuration shared between client and server. Config hostKeys []Signer // NoClientAuth is true if clients are allowed to connect without // authenticating. NoClientAuth bool // MaxAuthTries specifies the maximum number of authentication attempts // permitted per connection. If set to a negative number, the number of // attempts are unlimited. If set to zero, the number of attempts are limited // to 6. MaxAuthTries int // PasswordCallback, if non-nil, is called when a user // attempts to authenticate using a password. PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error) // PublicKeyCallback, if non-nil, is called when a client // offers a public key for authentication. It must return a nil error // if the given public key can be used to authenticate the // given user. For example, see CertChecker.Authenticate. A // call to this function does not guarantee that the key // offered is in fact used to authenticate. To record any data // depending on the public key, store it inside a // Permissions.Extensions entry. PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error) // KeyboardInteractiveCallback, if non-nil, is called when // keyboard-interactive authentication is selected (RFC // 4256). The client object's Challenge function should be // used to query the user. The callback may offer multiple // Challenge rounds. To avoid information leaks, the client // should be presented a challenge even if the user is // unknown. KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) // AuthLogCallback, if non-nil, is called to log all authentication // attempts. AuthLogCallback func(conn ConnMetadata, method string, err error) // ServerVersion is the version identification string to announce in // the public handshake. // If empty, a reasonable default is used. // Note that RFC 4253 section 4.2 requires that this string start with // "SSH-2.0-". ServerVersion string // BannerCallback, if present, is called and the return string is sent to // the client after key exchange completed but before authentication. BannerCallback func(conn ConnMetadata) string } // AddHostKey adds a private key as a host key. If an existing host // key exists with the same algorithm, it is overwritten. Each server // config must have at least one host key. func (s *ServerConfig) AddHostKey(key Signer) { for i, k := range s.hostKeys { if k.PublicKey().Type() == key.PublicKey().Type() { s.hostKeys[i] = key return } } s.hostKeys = append(s.hostKeys, key) } // cachedPubKey contains the results of querying whether a public key is // acceptable for a user. type cachedPubKey struct { user string pubKeyData []byte result error perms *Permissions } const maxCachedPubKeys = 16 // pubKeyCache caches tests for public keys. Since SSH clients // will query whether a public key is acceptable before attempting to // authenticate with it, we end up with duplicate queries for public // key validity. The cache only applies to a single ServerConn. type pubKeyCache struct { keys []cachedPubKey } // get returns the result for a given user/algo/key tuple. func (c *pubKeyCache) get(user string, pubKeyData []byte) (cachedPubKey, bool) { for _, k := range c.keys { if k.user == user && bytes.Equal(k.pubKeyData, pubKeyData) { return k, true } } return cachedPubKey{}, false } // add adds the given tuple to the cache. func (c *pubKeyCache) add(candidate cachedPubKey) { if len(c.keys) < maxCachedPubKeys { c.keys = append(c.keys, candidate) } } // ServerConn is an authenticated SSH connection, as seen from the // server type ServerConn struct { Conn // If the succeeding authentication callback returned a // non-nil Permissions pointer, it is stored here. Permissions *Permissions } // NewServerConn starts a new SSH server with c as the underlying // transport. It starts with a handshake and, if the handshake is // unsuccessful, it closes the connection and returns an error. The // Request and NewChannel channels must be serviced, or the connection // will hang. func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) { fullConf := *config fullConf.SetDefaults() if fullConf.MaxAuthTries == 0 { fullConf.MaxAuthTries = 6 } s := &connection{ sshConn: sshConn{conn: c}, } perms, err := s.serverHandshake(&fullConf) if err != nil { c.Close() return nil, nil, nil, err } return &ServerConn{s, perms}, s.mux.incomingChannels, s.mux.incomingRequests, nil } // signAndMarshal signs the data with the appropriate algorithm, // and serializes the result in SSH wire format. func signAndMarshal(k Signer, rand io.Reader, data []byte) ([]byte, error) { sig, err := k.Sign(rand, data) if err != nil { return nil, err } return Marshal(sig), nil } // handshake performs key exchange and user authentication. func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) { if len(config.hostKeys) == 0 { return nil, errors.New("ssh: server has no host keys") } if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil && config.KeyboardInteractiveCallback == nil { return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false") } if config.ServerVersion != "" { s.serverVersion = []byte(config.ServerVersion) } else { s.serverVersion = []byte(packageVersion) } var err error s.clientVersion, err = exchangeVersions(s.sshConn.conn, s.serverVersion) if err != nil { return nil, err } tr := newTransport(s.sshConn.conn, config.Rand, false /* not client */) s.transport = newServerTransport(tr, s.clientVersion, s.serverVersion, config) if err := s.transport.waitSession(); err != nil { return nil, err } // We just did the key change, so the session ID is established. s.sessionID = s.transport.getSessionID() var packet []byte if packet, err = s.transport.readPacket(); err != nil { return nil, err } var serviceRequest serviceRequestMsg if err = Unmarshal(packet, &serviceRequest); err != nil { return nil, err } if serviceRequest.Service != serviceUserAuth { return nil, errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating") } serviceAccept := serviceAcceptMsg{ Service: serviceUserAuth, } if err := s.transport.writePacket(Marshal(&serviceAccept)); err != nil { return nil, err } perms, err := s.serverAuthenticate(config) if err != nil { return nil, err } s.mux = newMux(s.transport) return perms, err } func isAcceptableAlgo(algo string) bool { switch algo { case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519, CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01: return true } return false } func checkSourceAddress(addr net.Addr, sourceAddrs string) error { if addr == nil { return errors.New("ssh: no address known for client, but source-address match required") } tcpAddr, ok := addr.(*net.TCPAddr) if !ok { return fmt.Errorf("ssh: remote address %v is not an TCP address when checking source-address match", addr) } for _, sourceAddr := range strings.Split(sourceAddrs, ",") { if allowedIP := net.ParseIP(sourceAddr); allowedIP != nil { if allowedIP.Equal(tcpAddr.IP) { return nil } } else { _, ipNet, err := net.ParseCIDR(sourceAddr) if err != nil { return fmt.Errorf("ssh: error parsing source-address restriction %q: %v", sourceAddr, err) } if ipNet.Contains(tcpAddr.IP) { return nil } } } return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr) } // ServerAuthError implements the error interface. It appends any authentication // errors that may occur, and is returned if all of the authentication methods // provided by the user failed to authenticate. type ServerAuthError struct { // Errors contains authentication errors returned by the authentication // callback methods. Errors []error } func (l ServerAuthError) Error() string { var errs []string for _, err := range l.Errors { errs = append(errs, err.Error()) } return "[" + strings.Join(errs, ", ") + "]" } func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) { sessionID := s.transport.getSessionID() var cache pubKeyCache var perms *Permissions authFailures := 0 var authErrs []error userAuthLoop: for { if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 { discMsg := &disconnectMsg{ Reason: 2, Message: "too many authentication failures", } if err := s.transport.writePacket(Marshal(discMsg)); err != nil { return nil, err } return nil, discMsg } var userAuthReq userAuthRequestMsg if packet, err := s.transport.readPacket(); err != nil { if err == io.EOF { return nil, &ServerAuthError{Errors: authErrs} } return nil, err } else if err = Unmarshal(packet, &userAuthReq); err != nil { return nil, err } if userAuthReq.Service != serviceSSH { return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service) } s.user = userAuthReq.User if authFailures == 0 && config.BannerCallback != nil { msg := config.BannerCallback(s) if msg != "" { bannerMsg := &userAuthBannerMsg{ Message: msg, } if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil { return nil, err } } } perms = nil authErr := errors.New("no auth passed yet") switch userAuthReq.Method { case "none": if config.NoClientAuth { authErr = nil } // allow initial attempt of 'none' without penalty if authFailures == 0 { authFailures-- } case "password": if config.PasswordCallback == nil { authErr = errors.New("ssh: password auth not configured") break } payload := userAuthReq.Payload if len(payload) < 1 || payload[0] != 0 { return nil, parseError(msgUserAuthRequest) } payload = payload[1:] password, payload, ok := parseString(payload) if !ok || len(payload) > 0 { return nil, parseError(msgUserAuthRequest) } perms, authErr = config.PasswordCallback(s, password) case "keyboard-interactive": if config.KeyboardInteractiveCallback == nil { authErr = errors.New("ssh: keyboard-interactive auth not configubred") break } prompter := &sshClientKeyboardInteractive{s} perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge) case "publickey": if config.PublicKeyCallback == nil { authErr = errors.New("ssh: publickey auth not configured") break } payload := userAuthReq.Payload if len(payload) < 1 { return nil, parseError(msgUserAuthRequest) } isQuery := payload[0] == 0 payload = payload[1:] algoBytes, payload, ok := parseString(payload) if !ok { return nil, parseError(msgUserAuthRequest) } algo := string(algoBytes) if !isAcceptableAlgo(algo) { authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo) break } pubKeyData, payload, ok := parseString(payload) if !ok { return nil, parseError(msgUserAuthRequest) } pubKey, err := ParsePublicKey(pubKeyData) if err != nil { return nil, err } candidate, ok := cache.get(s.user, pubKeyData) if !ok { candidate.user = s.user candidate.pubKeyData = pubKeyData candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey) if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" { candidate.result = checkSourceAddress( s.RemoteAddr(), candidate.perms.CriticalOptions[sourceAddressCriticalOption]) } cache.add(candidate) } if isQuery { // The client can query if the given public key // would be okay. if len(payload) > 0 { return nil, parseError(msgUserAuthRequest) } if candidate.result == nil { okMsg := userAuthPubKeyOkMsg{ Algo: algo, PubKey: pubKeyData, } if err = s.transport.writePacket(Marshal(&okMsg)); err != nil { return nil, err } continue userAuthLoop } authErr = candidate.result } else { sig, payload, ok := parseSignature(payload) if !ok || len(payload) > 0 { return nil, parseError(msgUserAuthRequest) } // Ensure the public key algo and signature algo // are supported. Compare the private key // algorithm name that corresponds to algo with // sig.Format. This is usually the same, but // for certs, the names differ. if !isAcceptableAlgo(sig.Format) { break } signedData := buildDataSignedForAuth(sessionID, userAuthReq, algoBytes, pubKeyData) if err := pubKey.Verify(signedData, sig); err != nil { return nil, err } authErr = candidate.result perms = candidate.perms } default: authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method) } authErrs = append(authErrs, authErr) if config.AuthLogCallback != nil { config.AuthLogCallback(s, userAuthReq.Method, authErr) } if authErr == nil { break userAuthLoop } authFailures++ var failureMsg userAuthFailureMsg if config.PasswordCallback != nil { failureMsg.Methods = append(failureMsg.Methods, "password") } if config.PublicKeyCallback != nil { failureMsg.Methods = append(failureMsg.Methods, "publickey") } if config.KeyboardInteractiveCallback != nil { failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive") } if len(failureMsg.Methods) == 0 { return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false") } if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil { return nil, err } } if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil { return nil, err } return perms, nil } // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by // asking the client on the other side of a ServerConn. type sshClientKeyboardInteractive struct { *connection } func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) { if len(questions) != len(echos) { return nil, errors.New("ssh: echos and questions must have equal length") } var prompts []byte for i := range questions { prompts = appendString(prompts, questions[i]) prompts = appendBool(prompts, echos[i]) } if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{ Instruction: instruction, NumPrompts: uint32(len(questions)), Prompts: prompts, })); err != nil { return nil, err } packet, err := c.transport.readPacket() if err != nil { return nil, err } if packet[0] != msgUserAuthInfoResponse { return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0]) } packet = packet[1:] n, packet, ok := parseUint32(packet) if !ok || int(n) != len(questions) { return nil, parseError(msgUserAuthInfoResponse) } for i := uint32(0); i < n; i++ { ans, rest, ok := parseString(packet) if !ok { return nil, parseError(msgUserAuthInfoResponse) } answers = append(answers, string(ans)) packet = rest } if len(packet) != 0 { return nil, errors.New("ssh: junk at end of message") } return answers, nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/mux_test.go���������������������������������������������0000644�0610621�0607500�00000025215�13172163317�024053� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "io" "io/ioutil" "sync" "testing" ) func muxPair() (*mux, *mux) { a, b := memPipe() s := newMux(a) c := newMux(b) return s, c } // Returns both ends of a channel, and the mux for the the 2nd // channel. func channelPair(t *testing.T) (*channel, *channel, *mux) { c, s := muxPair() res := make(chan *channel, 1) go func() { newCh, ok := <-s.incomingChannels if !ok { t.Fatalf("No incoming channel") } if newCh.ChannelType() != "chan" { t.Fatalf("got type %q want chan", newCh.ChannelType()) } ch, _, err := newCh.Accept() if err != nil { t.Fatalf("Accept %v", err) } res <- ch.(*channel) }() ch, err := c.openChannel("chan", nil) if err != nil { t.Fatalf("OpenChannel: %v", err) } return <-res, ch, c } // Test that stderr and stdout can be addressed from different // goroutines. This is intended for use with the race detector. func TestMuxChannelExtendedThreadSafety(t *testing.T) { writer, reader, mux := channelPair(t) defer writer.Close() defer reader.Close() defer mux.Close() var wr, rd sync.WaitGroup magic := "hello world" wr.Add(2) go func() { io.WriteString(writer, magic) wr.Done() }() go func() { io.WriteString(writer.Stderr(), magic) wr.Done() }() rd.Add(2) go func() { c, err := ioutil.ReadAll(reader) if string(c) != magic { t.Fatalf("stdout read got %q, want %q (error %s)", c, magic, err) } rd.Done() }() go func() { c, err := ioutil.ReadAll(reader.Stderr()) if string(c) != magic { t.Fatalf("stderr read got %q, want %q (error %s)", c, magic, err) } rd.Done() }() wr.Wait() writer.CloseWrite() rd.Wait() } func TestMuxReadWrite(t *testing.T) { s, c, mux := channelPair(t) defer s.Close() defer c.Close() defer mux.Close() magic := "hello world" magicExt := "hello stderr" go func() { _, err := s.Write([]byte(magic)) if err != nil { t.Fatalf("Write: %v", err) } _, err = s.Extended(1).Write([]byte(magicExt)) if err != nil { t.Fatalf("Write: %v", err) } err = s.Close() if err != nil { t.Fatalf("Close: %v", err) } }() var buf [1024]byte n, err := c.Read(buf[:]) if err != nil { t.Fatalf("server Read: %v", err) } got := string(buf[:n]) if got != magic { t.Fatalf("server: got %q want %q", got, magic) } n, err = c.Extended(1).Read(buf[:]) if err != nil { t.Fatalf("server Read: %v", err) } got = string(buf[:n]) if got != magicExt { t.Fatalf("server: got %q want %q", got, magic) } } func TestMuxChannelOverflow(t *testing.T) { reader, writer, mux := channelPair(t) defer reader.Close() defer writer.Close() defer mux.Close() wDone := make(chan int, 1) go func() { if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { t.Errorf("could not fill window: %v", err) } writer.Write(make([]byte, 1)) wDone <- 1 }() writer.remoteWin.waitWriterBlocked() // Send 1 byte. packet := make([]byte, 1+4+4+1) packet[0] = msgChannelData marshalUint32(packet[1:], writer.remoteId) marshalUint32(packet[5:], uint32(1)) packet[9] = 42 if err := writer.mux.conn.writePacket(packet); err != nil { t.Errorf("could not send packet") } if _, err := reader.SendRequest("hello", true, nil); err == nil { t.Errorf("SendRequest succeeded.") } <-wDone } func TestMuxChannelCloseWriteUnblock(t *testing.T) { reader, writer, mux := channelPair(t) defer reader.Close() defer writer.Close() defer mux.Close() wDone := make(chan int, 1) go func() { if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { t.Errorf("could not fill window: %v", err) } if _, err := writer.Write(make([]byte, 1)); err != io.EOF { t.Errorf("got %v, want EOF for unblock write", err) } wDone <- 1 }() writer.remoteWin.waitWriterBlocked() reader.Close() <-wDone } func TestMuxConnectionCloseWriteUnblock(t *testing.T) { reader, writer, mux := channelPair(t) defer reader.Close() defer writer.Close() defer mux.Close() wDone := make(chan int, 1) go func() { if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { t.Errorf("could not fill window: %v", err) } if _, err := writer.Write(make([]byte, 1)); err != io.EOF { t.Errorf("got %v, want EOF for unblock write", err) } wDone <- 1 }() writer.remoteWin.waitWriterBlocked() mux.Close() <-wDone } func TestMuxReject(t *testing.T) { client, server := muxPair() defer server.Close() defer client.Close() go func() { ch, ok := <-server.incomingChannels if !ok { t.Fatalf("Accept") } if ch.ChannelType() != "ch" || string(ch.ExtraData()) != "extra" { t.Fatalf("unexpected channel: %q, %q", ch.ChannelType(), ch.ExtraData()) } ch.Reject(RejectionReason(42), "message") }() ch, err := client.openChannel("ch", []byte("extra")) if ch != nil { t.Fatal("openChannel not rejected") } ocf, ok := err.(*OpenChannelError) if !ok { t.Errorf("got %#v want *OpenChannelError", err) } else if ocf.Reason != 42 || ocf.Message != "message" { t.Errorf("got %#v, want {Reason: 42, Message: %q}", ocf, "message") } want := "ssh: rejected: unknown reason 42 (message)" if err.Error() != want { t.Errorf("got %q, want %q", err.Error(), want) } } func TestMuxChannelRequest(t *testing.T) { client, server, mux := channelPair(t) defer server.Close() defer client.Close() defer mux.Close() var received int var wg sync.WaitGroup wg.Add(1) go func() { for r := range server.incomingRequests { received++ r.Reply(r.Type == "yes", nil) } wg.Done() }() _, err := client.SendRequest("yes", false, nil) if err != nil { t.Fatalf("SendRequest: %v", err) } ok, err := client.SendRequest("yes", true, nil) if err != nil { t.Fatalf("SendRequest: %v", err) } if !ok { t.Errorf("SendRequest(yes): %v", ok) } ok, err = client.SendRequest("no", true, nil) if err != nil { t.Fatalf("SendRequest: %v", err) } if ok { t.Errorf("SendRequest(no): %v", ok) } client.Close() wg.Wait() if received != 3 { t.Errorf("got %d requests, want %d", received, 3) } } func TestMuxGlobalRequest(t *testing.T) { clientMux, serverMux := muxPair() defer serverMux.Close() defer clientMux.Close() var seen bool go func() { for r := range serverMux.incomingRequests { seen = seen || r.Type == "peek" if r.WantReply { err := r.Reply(r.Type == "yes", append([]byte(r.Type), r.Payload...)) if err != nil { t.Errorf("AckRequest: %v", err) } } } }() _, _, err := clientMux.SendRequest("peek", false, nil) if err != nil { t.Errorf("SendRequest: %v", err) } ok, data, err := clientMux.SendRequest("yes", true, []byte("a")) if !ok || string(data) != "yesa" || err != nil { t.Errorf("SendRequest(\"yes\", true, \"a\"): %v %v %v", ok, data, err) } if ok, data, err := clientMux.SendRequest("yes", true, []byte("a")); !ok || string(data) != "yesa" || err != nil { t.Errorf("SendRequest(\"yes\", true, \"a\"): %v %v %v", ok, data, err) } if ok, data, err := clientMux.SendRequest("no", true, []byte("a")); ok || string(data) != "noa" || err != nil { t.Errorf("SendRequest(\"no\", true, \"a\"): %v %v %v", ok, data, err) } if !seen { t.Errorf("never saw 'peek' request") } } func TestMuxGlobalRequestUnblock(t *testing.T) { clientMux, serverMux := muxPair() defer serverMux.Close() defer clientMux.Close() result := make(chan error, 1) go func() { _, _, err := clientMux.SendRequest("hello", true, nil) result <- err }() <-serverMux.incomingRequests serverMux.conn.Close() err := <-result if err != io.EOF { t.Errorf("want EOF, got %v", io.EOF) } } func TestMuxChannelRequestUnblock(t *testing.T) { a, b, connB := channelPair(t) defer a.Close() defer b.Close() defer connB.Close() result := make(chan error, 1) go func() { _, err := a.SendRequest("hello", true, nil) result <- err }() <-b.incomingRequests connB.conn.Close() err := <-result if err != io.EOF { t.Errorf("want EOF, got %v", err) } } func TestMuxCloseChannel(t *testing.T) { r, w, mux := channelPair(t) defer mux.Close() defer r.Close() defer w.Close() result := make(chan error, 1) go func() { var b [1024]byte _, err := r.Read(b[:]) result <- err }() if err := w.Close(); err != nil { t.Errorf("w.Close: %v", err) } if _, err := w.Write([]byte("hello")); err != io.EOF { t.Errorf("got err %v, want io.EOF after Close", err) } if err := <-result; err != io.EOF { t.Errorf("got %v (%T), want io.EOF", err, err) } } func TestMuxCloseWriteChannel(t *testing.T) { r, w, mux := channelPair(t) defer mux.Close() result := make(chan error, 1) go func() { var b [1024]byte _, err := r.Read(b[:]) result <- err }() if err := w.CloseWrite(); err != nil { t.Errorf("w.CloseWrite: %v", err) } if _, err := w.Write([]byte("hello")); err != io.EOF { t.Errorf("got err %v, want io.EOF after CloseWrite", err) } if err := <-result; err != io.EOF { t.Errorf("got %v (%T), want io.EOF", err, err) } } func TestMuxInvalidRecord(t *testing.T) { a, b := muxPair() defer a.Close() defer b.Close() packet := make([]byte, 1+4+4+1) packet[0] = msgChannelData marshalUint32(packet[1:], 29348723 /* invalid channel id */) marshalUint32(packet[5:], 1) packet[9] = 42 a.conn.writePacket(packet) go a.SendRequest("hello", false, nil) // 'a' wrote an invalid packet, so 'b' has exited. req, ok := <-b.incomingRequests if ok { t.Errorf("got request %#v after receiving invalid packet", req) } } func TestZeroWindowAdjust(t *testing.T) { a, b, mux := channelPair(t) defer a.Close() defer b.Close() defer mux.Close() go func() { io.WriteString(a, "hello") // bogus adjust. a.sendMessage(windowAdjustMsg{}) io.WriteString(a, "world") a.Close() }() want := "helloworld" c, _ := ioutil.ReadAll(b) if string(c) != want { t.Errorf("got %q want %q", c, want) } } func TestMuxMaxPacketSize(t *testing.T) { a, b, mux := channelPair(t) defer a.Close() defer b.Close() defer mux.Close() large := make([]byte, a.maxRemotePayload+1) packet := make([]byte, 1+4+4+1+len(large)) packet[0] = msgChannelData marshalUint32(packet[1:], a.remoteId) marshalUint32(packet[5:], uint32(len(large))) packet[9] = 42 if err := a.mux.conn.writePacket(packet); err != nil { t.Errorf("could not send packet") } go a.SendRequest("hello", false, nil) _, ok := <-b.incomingRequests if ok { t.Errorf("connection still alive after receiving large packet.") } } // Don't ship code with debug=true. func TestDebug(t *testing.T) { if debugMux { t.Error("mux debug switched on") } if debugHandshake { t.Error("handshake debug switched on") } if debugTransport { t.Error("transport debug switched on") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/mux.go��������������������������������������������������0000644�0610621�0607500�00000016342�13172163317�023015� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "encoding/binary" "fmt" "io" "log" "sync" "sync/atomic" ) // debugMux, if set, causes messages in the connection protocol to be // logged. const debugMux = false // chanList is a thread safe channel list. type chanList struct { // protects concurrent access to chans sync.Mutex // chans are indexed by the local id of the channel, which the // other side should send in the PeersId field. chans []*channel // This is a debugging aid: it offsets all IDs by this // amount. This helps distinguish otherwise identical // server/client muxes offset uint32 } // Assigns a channel ID to the given channel. func (c *chanList) add(ch *channel) uint32 { c.Lock() defer c.Unlock() for i := range c.chans { if c.chans[i] == nil { c.chans[i] = ch return uint32(i) + c.offset } } c.chans = append(c.chans, ch) return uint32(len(c.chans)-1) + c.offset } // getChan returns the channel for the given ID. func (c *chanList) getChan(id uint32) *channel { id -= c.offset c.Lock() defer c.Unlock() if id < uint32(len(c.chans)) { return c.chans[id] } return nil } func (c *chanList) remove(id uint32) { id -= c.offset c.Lock() if id < uint32(len(c.chans)) { c.chans[id] = nil } c.Unlock() } // dropAll forgets all channels it knows, returning them in a slice. func (c *chanList) dropAll() []*channel { c.Lock() defer c.Unlock() var r []*channel for _, ch := range c.chans { if ch == nil { continue } r = append(r, ch) } c.chans = nil return r } // mux represents the state for the SSH connection protocol, which // multiplexes many channels onto a single packet transport. type mux struct { conn packetConn chanList chanList incomingChannels chan NewChannel globalSentMu sync.Mutex globalResponses chan interface{} incomingRequests chan *Request errCond *sync.Cond err error } // When debugging, each new chanList instantiation has a different // offset. var globalOff uint32 func (m *mux) Wait() error { m.errCond.L.Lock() defer m.errCond.L.Unlock() for m.err == nil { m.errCond.Wait() } return m.err } // newMux returns a mux that runs over the given connection. func newMux(p packetConn) *mux { m := &mux{ conn: p, incomingChannels: make(chan NewChannel, chanSize), globalResponses: make(chan interface{}, 1), incomingRequests: make(chan *Request, chanSize), errCond: newCond(), } if debugMux { m.chanList.offset = atomic.AddUint32(&globalOff, 1) } go m.loop() return m } func (m *mux) sendMessage(msg interface{}) error { p := Marshal(msg) if debugMux { log.Printf("send global(%d): %#v", m.chanList.offset, msg) } return m.conn.writePacket(p) } func (m *mux) SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) { if wantReply { m.globalSentMu.Lock() defer m.globalSentMu.Unlock() } if err := m.sendMessage(globalRequestMsg{ Type: name, WantReply: wantReply, Data: payload, }); err != nil { return false, nil, err } if !wantReply { return false, nil, nil } msg, ok := <-m.globalResponses if !ok { return false, nil, io.EOF } switch msg := msg.(type) { case *globalRequestFailureMsg: return false, msg.Data, nil case *globalRequestSuccessMsg: return true, msg.Data, nil default: return false, nil, fmt.Errorf("ssh: unexpected response to request: %#v", msg) } } // ackRequest must be called after processing a global request that // has WantReply set. func (m *mux) ackRequest(ok bool, data []byte) error { if ok { return m.sendMessage(globalRequestSuccessMsg{Data: data}) } return m.sendMessage(globalRequestFailureMsg{Data: data}) } func (m *mux) Close() error { return m.conn.Close() } // loop runs the connection machine. It will process packets until an // error is encountered. To synchronize on loop exit, use mux.Wait. func (m *mux) loop() { var err error for err == nil { err = m.onePacket() } for _, ch := range m.chanList.dropAll() { ch.close() } close(m.incomingChannels) close(m.incomingRequests) close(m.globalResponses) m.conn.Close() m.errCond.L.Lock() m.err = err m.errCond.Broadcast() m.errCond.L.Unlock() if debugMux { log.Println("loop exit", err) } } // onePacket reads and processes one packet. func (m *mux) onePacket() error { packet, err := m.conn.readPacket() if err != nil { return err } if debugMux { if packet[0] == msgChannelData || packet[0] == msgChannelExtendedData { log.Printf("decoding(%d): data packet - %d bytes", m.chanList.offset, len(packet)) } else { p, _ := decode(packet) log.Printf("decoding(%d): %d %#v - %d bytes", m.chanList.offset, packet[0], p, len(packet)) } } switch packet[0] { case msgChannelOpen: return m.handleChannelOpen(packet) case msgGlobalRequest, msgRequestSuccess, msgRequestFailure: return m.handleGlobalPacket(packet) } // assume a channel packet. if len(packet) < 5 { return parseError(packet[0]) } id := binary.BigEndian.Uint32(packet[1:]) ch := m.chanList.getChan(id) if ch == nil { return fmt.Errorf("ssh: invalid channel %d", id) } return ch.handlePacket(packet) } func (m *mux) handleGlobalPacket(packet []byte) error { msg, err := decode(packet) if err != nil { return err } switch msg := msg.(type) { case *globalRequestMsg: m.incomingRequests <- &Request{ Type: msg.Type, WantReply: msg.WantReply, Payload: msg.Data, mux: m, } case *globalRequestSuccessMsg, *globalRequestFailureMsg: m.globalResponses <- msg default: panic(fmt.Sprintf("not a global message %#v", msg)) } return nil } // handleChannelOpen schedules a channel to be Accept()ed. func (m *mux) handleChannelOpen(packet []byte) error { var msg channelOpenMsg if err := Unmarshal(packet, &msg); err != nil { return err } if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { failMsg := channelOpenFailureMsg{ PeersId: msg.PeersId, Reason: ConnectionFailed, Message: "invalid request", Language: "en_US.UTF-8", } return m.sendMessage(failMsg) } c := m.newChannel(msg.ChanType, channelInbound, msg.TypeSpecificData) c.remoteId = msg.PeersId c.maxRemotePayload = msg.MaxPacketSize c.remoteWin.add(msg.PeersWindow) m.incomingChannels <- c return nil } func (m *mux) OpenChannel(chanType string, extra []byte) (Channel, <-chan *Request, error) { ch, err := m.openChannel(chanType, extra) if err != nil { return nil, nil, err } return ch, ch.incomingRequests, nil } func (m *mux) openChannel(chanType string, extra []byte) (*channel, error) { ch := m.newChannel(chanType, channelOutbound, extra) ch.maxIncomingPayload = channelMaxPacket open := channelOpenMsg{ ChanType: chanType, PeersWindow: ch.myWindow, MaxPacketSize: ch.maxIncomingPayload, TypeSpecificData: extra, PeersId: ch.localId, } if err := m.sendMessage(open); err != nil { return nil, err } switch msg := (<-ch.msg).(type) { case *channelOpenConfirmMsg: return ch, nil case *channelOpenFailureMsg: return nil, &OpenChannelError{msg.Reason, msg.Message} default: return nil, fmt.Errorf("ssh: unexpected packet in response to channel open: %T", msg) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/messages_test.go����������������������������������������0000644�0610621�0607500�00000014062�13172163317�025047� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "math/big" "math/rand" "reflect" "testing" "testing/quick" ) var intLengthTests = []struct { val, length int }{ {0, 4 + 0}, {1, 4 + 1}, {127, 4 + 1}, {128, 4 + 2}, {-1, 4 + 1}, } func TestIntLength(t *testing.T) { for _, test := range intLengthTests { v := new(big.Int).SetInt64(int64(test.val)) length := intLength(v) if length != test.length { t.Errorf("For %d, got length %d but expected %d", test.val, length, test.length) } } } type msgAllTypes struct { Bool bool `sshtype:"21"` Array [16]byte Uint64 uint64 Uint32 uint32 Uint8 uint8 String string Strings []string Bytes []byte Int *big.Int Rest []byte `ssh:"rest"` } func (t *msgAllTypes) Generate(rand *rand.Rand, size int) reflect.Value { m := &msgAllTypes{} m.Bool = rand.Intn(2) == 1 randomBytes(m.Array[:], rand) m.Uint64 = uint64(rand.Int63n(1<<63 - 1)) m.Uint32 = uint32(rand.Intn((1 << 31) - 1)) m.Uint8 = uint8(rand.Intn(1 << 8)) m.String = string(m.Array[:]) m.Strings = randomNameList(rand) m.Bytes = m.Array[:] m.Int = randomInt(rand) m.Rest = m.Array[:] return reflect.ValueOf(m) } func TestMarshalUnmarshal(t *testing.T) { rand := rand.New(rand.NewSource(0)) iface := &msgAllTypes{} ty := reflect.ValueOf(iface).Type() n := 100 if testing.Short() { n = 5 } for j := 0; j < n; j++ { v, ok := quick.Value(ty, rand) if !ok { t.Errorf("failed to create value") break } m1 := v.Elem().Interface() m2 := iface marshaled := Marshal(m1) if err := Unmarshal(marshaled, m2); err != nil { t.Errorf("Unmarshal %#v: %s", m1, err) break } if !reflect.DeepEqual(v.Interface(), m2) { t.Errorf("got: %#v\nwant:%#v\n%x", m2, m1, marshaled) break } } } func TestUnmarshalEmptyPacket(t *testing.T) { var b []byte var m channelRequestSuccessMsg if err := Unmarshal(b, &m); err == nil { t.Fatalf("unmarshal of empty slice succeeded") } } func TestUnmarshalUnexpectedPacket(t *testing.T) { type S struct { I uint32 `sshtype:"43"` S string B bool } s := S{11, "hello", true} packet := Marshal(s) packet[0] = 42 roundtrip := S{} err := Unmarshal(packet, &roundtrip) if err == nil { t.Fatal("expected error, not nil") } } func TestMarshalPtr(t *testing.T) { s := struct { S string }{"hello"} m1 := Marshal(s) m2 := Marshal(&s) if !bytes.Equal(m1, m2) { t.Errorf("got %q, want %q for marshaled pointer", m2, m1) } } func TestBareMarshalUnmarshal(t *testing.T) { type S struct { I uint32 S string B bool } s := S{42, "hello", true} packet := Marshal(s) roundtrip := S{} Unmarshal(packet, &roundtrip) if !reflect.DeepEqual(s, roundtrip) { t.Errorf("got %#v, want %#v", roundtrip, s) } } func TestBareMarshal(t *testing.T) { type S2 struct { I uint32 } s := S2{42} packet := Marshal(s) i, rest, ok := parseUint32(packet) if len(rest) > 0 || !ok { t.Errorf("parseInt(%q): parse error", packet) } if i != s.I { t.Errorf("got %d, want %d", i, s.I) } } func TestUnmarshalShortKexInitPacket(t *testing.T) { // This used to panic. // Issue 11348 packet := []byte{0x14, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0xff, 0xff, 0xff, 0xff} kim := &kexInitMsg{} if err := Unmarshal(packet, kim); err == nil { t.Error("truncated packet unmarshaled without error") } } func TestMarshalMultiTag(t *testing.T) { var res struct { A uint32 `sshtype:"1|2"` } good1 := struct { A uint32 `sshtype:"1"` }{ 1, } good2 := struct { A uint32 `sshtype:"2"` }{ 1, } if e := Unmarshal(Marshal(good1), &res); e != nil { t.Errorf("error unmarshaling multipart tag: %v", e) } if e := Unmarshal(Marshal(good2), &res); e != nil { t.Errorf("error unmarshaling multipart tag: %v", e) } bad1 := struct { A uint32 `sshtype:"3"` }{ 1, } if e := Unmarshal(Marshal(bad1), &res); e == nil { t.Errorf("bad struct unmarshaled without error") } } func randomBytes(out []byte, rand *rand.Rand) { for i := 0; i < len(out); i++ { out[i] = byte(rand.Int31()) } } func randomNameList(rand *rand.Rand) []string { ret := make([]string, rand.Int31()&15) for i := range ret { s := make([]byte, 1+(rand.Int31()&15)) for j := range s { s[j] = 'a' + uint8(rand.Int31()&15) } ret[i] = string(s) } return ret } func randomInt(rand *rand.Rand) *big.Int { return new(big.Int).SetInt64(int64(int32(rand.Uint32()))) } func (*kexInitMsg) Generate(rand *rand.Rand, size int) reflect.Value { ki := &kexInitMsg{} randomBytes(ki.Cookie[:], rand) ki.KexAlgos = randomNameList(rand) ki.ServerHostKeyAlgos = randomNameList(rand) ki.CiphersClientServer = randomNameList(rand) ki.CiphersServerClient = randomNameList(rand) ki.MACsClientServer = randomNameList(rand) ki.MACsServerClient = randomNameList(rand) ki.CompressionClientServer = randomNameList(rand) ki.CompressionServerClient = randomNameList(rand) ki.LanguagesClientServer = randomNameList(rand) ki.LanguagesServerClient = randomNameList(rand) if rand.Int31()&1 == 1 { ki.FirstKexFollows = true } return reflect.ValueOf(ki) } func (*kexDHInitMsg) Generate(rand *rand.Rand, size int) reflect.Value { dhi := &kexDHInitMsg{} dhi.X = randomInt(rand) return reflect.ValueOf(dhi) } var ( _kexInitMsg = new(kexInitMsg).Generate(rand.New(rand.NewSource(0)), 10).Elem().Interface() _kexDHInitMsg = new(kexDHInitMsg).Generate(rand.New(rand.NewSource(0)), 10).Elem().Interface() _kexInit = Marshal(_kexInitMsg) _kexDHInit = Marshal(_kexDHInitMsg) ) func BenchmarkMarshalKexInitMsg(b *testing.B) { for i := 0; i < b.N; i++ { Marshal(_kexInitMsg) } } func BenchmarkUnmarshalKexInitMsg(b *testing.B) { m := new(kexInitMsg) for i := 0; i < b.N; i++ { Unmarshal(_kexInit, m) } } func BenchmarkMarshalKexDHInitMsg(b *testing.B) { for i := 0; i < b.N; i++ { Marshal(_kexDHInitMsg) } } func BenchmarkUnmarshalKexDHInitMsg(b *testing.B) { m := new(kexDHInitMsg) for i := 0; i < b.N; i++ { Unmarshal(_kexDHInit, m) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/messages.go���������������������������������������������0000644�0610621�0607500�00000042442�13172163317�024013� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "encoding/binary" "errors" "fmt" "io" "math/big" "reflect" "strconv" "strings" ) // These are SSH message type numbers. They are scattered around several // documents but many were taken from [SSH-PARAMETERS]. const ( msgIgnore = 2 msgUnimplemented = 3 msgDebug = 4 msgNewKeys = 21 ) // SSH messages: // // These structures mirror the wire format of the corresponding SSH messages. // They are marshaled using reflection with the marshal and unmarshal functions // in this file. The only wrinkle is that a final member of type []byte with a // ssh tag of "rest" receives the remainder of a packet when unmarshaling. // See RFC 4253, section 11.1. const msgDisconnect = 1 // disconnectMsg is the message that signals a disconnect. It is also // the error type returned from mux.Wait() type disconnectMsg struct { Reason uint32 `sshtype:"1"` Message string Language string } func (d *disconnectMsg) Error() string { return fmt.Sprintf("ssh: disconnect, reason %d: %s", d.Reason, d.Message) } // See RFC 4253, section 7.1. const msgKexInit = 20 type kexInitMsg struct { Cookie [16]byte `sshtype:"20"` KexAlgos []string ServerHostKeyAlgos []string CiphersClientServer []string CiphersServerClient []string MACsClientServer []string MACsServerClient []string CompressionClientServer []string CompressionServerClient []string LanguagesClientServer []string LanguagesServerClient []string FirstKexFollows bool Reserved uint32 } // See RFC 4253, section 8. // Diffie-Helman const msgKexDHInit = 30 type kexDHInitMsg struct { X *big.Int `sshtype:"30"` } const msgKexECDHInit = 30 type kexECDHInitMsg struct { ClientPubKey []byte `sshtype:"30"` } const msgKexECDHReply = 31 type kexECDHReplyMsg struct { HostKey []byte `sshtype:"31"` EphemeralPubKey []byte Signature []byte } const msgKexDHReply = 31 type kexDHReplyMsg struct { HostKey []byte `sshtype:"31"` Y *big.Int Signature []byte } // See RFC 4253, section 10. const msgServiceRequest = 5 type serviceRequestMsg struct { Service string `sshtype:"5"` } // See RFC 4253, section 10. const msgServiceAccept = 6 type serviceAcceptMsg struct { Service string `sshtype:"6"` } // See RFC 4252, section 5. const msgUserAuthRequest = 50 type userAuthRequestMsg struct { User string `sshtype:"50"` Service string Method string Payload []byte `ssh:"rest"` } // Used for debug printouts of packets. type userAuthSuccessMsg struct { } // See RFC 4252, section 5.1 const msgUserAuthFailure = 51 type userAuthFailureMsg struct { Methods []string `sshtype:"51"` PartialSuccess bool } // See RFC 4252, section 5.1 const msgUserAuthSuccess = 52 // See RFC 4252, section 5.4 const msgUserAuthBanner = 53 type userAuthBannerMsg struct { Message string `sshtype:"53"` } // See RFC 4256, section 3.2 const msgUserAuthInfoRequest = 60 const msgUserAuthInfoResponse = 61 type userAuthInfoRequestMsg struct { User string `sshtype:"60"` Instruction string DeprecatedLanguage string NumPrompts uint32 Prompts []byte `ssh:"rest"` } // See RFC 4254, section 5.1. const msgChannelOpen = 90 type channelOpenMsg struct { ChanType string `sshtype:"90"` PeersId uint32 PeersWindow uint32 MaxPacketSize uint32 TypeSpecificData []byte `ssh:"rest"` } const msgChannelExtendedData = 95 const msgChannelData = 94 // Used for debug print outs of packets. type channelDataMsg struct { PeersId uint32 `sshtype:"94"` Length uint32 Rest []byte `ssh:"rest"` } // See RFC 4254, section 5.1. const msgChannelOpenConfirm = 91 type channelOpenConfirmMsg struct { PeersId uint32 `sshtype:"91"` MyId uint32 MyWindow uint32 MaxPacketSize uint32 TypeSpecificData []byte `ssh:"rest"` } // See RFC 4254, section 5.1. const msgChannelOpenFailure = 92 type channelOpenFailureMsg struct { PeersId uint32 `sshtype:"92"` Reason RejectionReason Message string Language string } const msgChannelRequest = 98 type channelRequestMsg struct { PeersId uint32 `sshtype:"98"` Request string WantReply bool RequestSpecificData []byte `ssh:"rest"` } // See RFC 4254, section 5.4. const msgChannelSuccess = 99 type channelRequestSuccessMsg struct { PeersId uint32 `sshtype:"99"` } // See RFC 4254, section 5.4. const msgChannelFailure = 100 type channelRequestFailureMsg struct { PeersId uint32 `sshtype:"100"` } // See RFC 4254, section 5.3 const msgChannelClose = 97 type channelCloseMsg struct { PeersId uint32 `sshtype:"97"` } // See RFC 4254, section 5.3 const msgChannelEOF = 96 type channelEOFMsg struct { PeersId uint32 `sshtype:"96"` } // See RFC 4254, section 4 const msgGlobalRequest = 80 type globalRequestMsg struct { Type string `sshtype:"80"` WantReply bool Data []byte `ssh:"rest"` } // See RFC 4254, section 4 const msgRequestSuccess = 81 type globalRequestSuccessMsg struct { Data []byte `ssh:"rest" sshtype:"81"` } // See RFC 4254, section 4 const msgRequestFailure = 82 type globalRequestFailureMsg struct { Data []byte `ssh:"rest" sshtype:"82"` } // See RFC 4254, section 5.2 const msgChannelWindowAdjust = 93 type windowAdjustMsg struct { PeersId uint32 `sshtype:"93"` AdditionalBytes uint32 } // See RFC 4252, section 7 const msgUserAuthPubKeyOk = 60 type userAuthPubKeyOkMsg struct { Algo string `sshtype:"60"` PubKey []byte } // typeTags returns the possible type bytes for the given reflect.Type, which // should be a struct. The possible values are separated by a '|' character. func typeTags(structType reflect.Type) (tags []byte) { tagStr := structType.Field(0).Tag.Get("sshtype") for _, tag := range strings.Split(tagStr, "|") { i, err := strconv.Atoi(tag) if err == nil { tags = append(tags, byte(i)) } } return tags } func fieldError(t reflect.Type, field int, problem string) error { if problem != "" { problem = ": " + problem } return fmt.Errorf("ssh: unmarshal error for field %s of type %s%s", t.Field(field).Name, t.Name(), problem) } var errShortRead = errors.New("ssh: short read") // Unmarshal parses data in SSH wire format into a structure. The out // argument should be a pointer to struct. If the first member of the // struct has the "sshtype" tag set to a '|'-separated set of numbers // in decimal, the packet must start with one of those numbers. In // case of error, Unmarshal returns a ParseError or // UnexpectedMessageError. func Unmarshal(data []byte, out interface{}) error { v := reflect.ValueOf(out).Elem() structType := v.Type() expectedTypes := typeTags(structType) var expectedType byte if len(expectedTypes) > 0 { expectedType = expectedTypes[0] } if len(data) == 0 { return parseError(expectedType) } if len(expectedTypes) > 0 { goodType := false for _, e := range expectedTypes { if e > 0 && data[0] == e { goodType = true break } } if !goodType { return fmt.Errorf("ssh: unexpected message type %d (expected one of %v)", data[0], expectedTypes) } data = data[1:] } var ok bool for i := 0; i < v.NumField(); i++ { field := v.Field(i) t := field.Type() switch t.Kind() { case reflect.Bool: if len(data) < 1 { return errShortRead } field.SetBool(data[0] != 0) data = data[1:] case reflect.Array: if t.Elem().Kind() != reflect.Uint8 { return fieldError(structType, i, "array of unsupported type") } if len(data) < t.Len() { return errShortRead } for j, n := 0, t.Len(); j < n; j++ { field.Index(j).Set(reflect.ValueOf(data[j])) } data = data[t.Len():] case reflect.Uint64: var u64 uint64 if u64, data, ok = parseUint64(data); !ok { return errShortRead } field.SetUint(u64) case reflect.Uint32: var u32 uint32 if u32, data, ok = parseUint32(data); !ok { return errShortRead } field.SetUint(uint64(u32)) case reflect.Uint8: if len(data) < 1 { return errShortRead } field.SetUint(uint64(data[0])) data = data[1:] case reflect.String: var s []byte if s, data, ok = parseString(data); !ok { return fieldError(structType, i, "") } field.SetString(string(s)) case reflect.Slice: switch t.Elem().Kind() { case reflect.Uint8: if structType.Field(i).Tag.Get("ssh") == "rest" { field.Set(reflect.ValueOf(data)) data = nil } else { var s []byte if s, data, ok = parseString(data); !ok { return errShortRead } field.Set(reflect.ValueOf(s)) } case reflect.String: var nl []string if nl, data, ok = parseNameList(data); !ok { return errShortRead } field.Set(reflect.ValueOf(nl)) default: return fieldError(structType, i, "slice of unsupported type") } case reflect.Ptr: if t == bigIntType { var n *big.Int if n, data, ok = parseInt(data); !ok { return errShortRead } field.Set(reflect.ValueOf(n)) } else { return fieldError(structType, i, "pointer to unsupported type") } default: return fieldError(structType, i, fmt.Sprintf("unsupported type: %v", t)) } } if len(data) != 0 { return parseError(expectedType) } return nil } // Marshal serializes the message in msg to SSH wire format. The msg // argument should be a struct or pointer to struct. If the first // member has the "sshtype" tag set to a number in decimal, that // number is prepended to the result. If the last of member has the // "ssh" tag set to "rest", its contents are appended to the output. func Marshal(msg interface{}) []byte { out := make([]byte, 0, 64) return marshalStruct(out, msg) } func marshalStruct(out []byte, msg interface{}) []byte { v := reflect.Indirect(reflect.ValueOf(msg)) msgTypes := typeTags(v.Type()) if len(msgTypes) > 0 { out = append(out, msgTypes[0]) } for i, n := 0, v.NumField(); i < n; i++ { field := v.Field(i) switch t := field.Type(); t.Kind() { case reflect.Bool: var v uint8 if field.Bool() { v = 1 } out = append(out, v) case reflect.Array: if t.Elem().Kind() != reflect.Uint8 { panic(fmt.Sprintf("array of non-uint8 in field %d: %T", i, field.Interface())) } for j, l := 0, t.Len(); j < l; j++ { out = append(out, uint8(field.Index(j).Uint())) } case reflect.Uint32: out = appendU32(out, uint32(field.Uint())) case reflect.Uint64: out = appendU64(out, uint64(field.Uint())) case reflect.Uint8: out = append(out, uint8(field.Uint())) case reflect.String: s := field.String() out = appendInt(out, len(s)) out = append(out, s...) case reflect.Slice: switch t.Elem().Kind() { case reflect.Uint8: if v.Type().Field(i).Tag.Get("ssh") != "rest" { out = appendInt(out, field.Len()) } out = append(out, field.Bytes()...) case reflect.String: offset := len(out) out = appendU32(out, 0) if n := field.Len(); n > 0 { for j := 0; j < n; j++ { f := field.Index(j) if j != 0 { out = append(out, ',') } out = append(out, f.String()...) } // overwrite length value binary.BigEndian.PutUint32(out[offset:], uint32(len(out)-offset-4)) } default: panic(fmt.Sprintf("slice of unknown type in field %d: %T", i, field.Interface())) } case reflect.Ptr: if t == bigIntType { var n *big.Int nValue := reflect.ValueOf(&n) nValue.Elem().Set(field) needed := intLength(n) oldLength := len(out) if cap(out)-len(out) < needed { newOut := make([]byte, len(out), 2*(len(out)+needed)) copy(newOut, out) out = newOut } out = out[:oldLength+needed] marshalInt(out[oldLength:], n) } else { panic(fmt.Sprintf("pointer to unknown type in field %d: %T", i, field.Interface())) } } } return out } var bigOne = big.NewInt(1) func parseString(in []byte) (out, rest []byte, ok bool) { if len(in) < 4 { return } length := binary.BigEndian.Uint32(in) in = in[4:] if uint32(len(in)) < length { return } out = in[:length] rest = in[length:] ok = true return } var ( comma = []byte{','} emptyNameList = []string{} ) func parseNameList(in []byte) (out []string, rest []byte, ok bool) { contents, rest, ok := parseString(in) if !ok { return } if len(contents) == 0 { out = emptyNameList return } parts := bytes.Split(contents, comma) out = make([]string, len(parts)) for i, part := range parts { out[i] = string(part) } return } func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) { contents, rest, ok := parseString(in) if !ok { return } out = new(big.Int) if len(contents) > 0 && contents[0]&0x80 == 0x80 { // This is a negative number notBytes := make([]byte, len(contents)) for i := range notBytes { notBytes[i] = ^contents[i] } out.SetBytes(notBytes) out.Add(out, bigOne) out.Neg(out) } else { // Positive number out.SetBytes(contents) } ok = true return } func parseUint32(in []byte) (uint32, []byte, bool) { if len(in) < 4 { return 0, nil, false } return binary.BigEndian.Uint32(in), in[4:], true } func parseUint64(in []byte) (uint64, []byte, bool) { if len(in) < 8 { return 0, nil, false } return binary.BigEndian.Uint64(in), in[8:], true } func intLength(n *big.Int) int { length := 4 /* length bytes */ if n.Sign() < 0 { nMinus1 := new(big.Int).Neg(n) nMinus1.Sub(nMinus1, bigOne) bitLen := nMinus1.BitLen() if bitLen%8 == 0 { // The number will need 0xff padding length++ } length += (bitLen + 7) / 8 } else if n.Sign() == 0 { // A zero is the zero length string } else { bitLen := n.BitLen() if bitLen%8 == 0 { // The number will need 0x00 padding length++ } length += (bitLen + 7) / 8 } return length } func marshalUint32(to []byte, n uint32) []byte { binary.BigEndian.PutUint32(to, n) return to[4:] } func marshalUint64(to []byte, n uint64) []byte { binary.BigEndian.PutUint64(to, n) return to[8:] } func marshalInt(to []byte, n *big.Int) []byte { lengthBytes := to to = to[4:] length := 0 if n.Sign() < 0 { // A negative number has to be converted to two's-complement // form. So we'll subtract 1 and invert. If the // most-significant-bit isn't set then we'll need to pad the // beginning with 0xff in order to keep the number negative. nMinus1 := new(big.Int).Neg(n) nMinus1.Sub(nMinus1, bigOne) bytes := nMinus1.Bytes() for i := range bytes { bytes[i] ^= 0xff } if len(bytes) == 0 || bytes[0]&0x80 == 0 { to[0] = 0xff to = to[1:] length++ } nBytes := copy(to, bytes) to = to[nBytes:] length += nBytes } else if n.Sign() == 0 { // A zero is the zero length string } else { bytes := n.Bytes() if len(bytes) > 0 && bytes[0]&0x80 != 0 { // We'll have to pad this with a 0x00 in order to // stop it looking like a negative number. to[0] = 0 to = to[1:] length++ } nBytes := copy(to, bytes) to = to[nBytes:] length += nBytes } lengthBytes[0] = byte(length >> 24) lengthBytes[1] = byte(length >> 16) lengthBytes[2] = byte(length >> 8) lengthBytes[3] = byte(length) return to } func writeInt(w io.Writer, n *big.Int) { length := intLength(n) buf := make([]byte, length) marshalInt(buf, n) w.Write(buf) } func writeString(w io.Writer, s []byte) { var lengthBytes [4]byte lengthBytes[0] = byte(len(s) >> 24) lengthBytes[1] = byte(len(s) >> 16) lengthBytes[2] = byte(len(s) >> 8) lengthBytes[3] = byte(len(s)) w.Write(lengthBytes[:]) w.Write(s) } func stringLength(n int) int { return 4 + n } func marshalString(to []byte, s []byte) []byte { to[0] = byte(len(s) >> 24) to[1] = byte(len(s) >> 16) to[2] = byte(len(s) >> 8) to[3] = byte(len(s)) to = to[4:] copy(to, s) return to[len(s):] } var bigIntType = reflect.TypeOf((*big.Int)(nil)) // Decode a packet into its corresponding message. func decode(packet []byte) (interface{}, error) { var msg interface{} switch packet[0] { case msgDisconnect: msg = new(disconnectMsg) case msgServiceRequest: msg = new(serviceRequestMsg) case msgServiceAccept: msg = new(serviceAcceptMsg) case msgKexInit: msg = new(kexInitMsg) case msgKexDHInit: msg = new(kexDHInitMsg) case msgKexDHReply: msg = new(kexDHReplyMsg) case msgUserAuthRequest: msg = new(userAuthRequestMsg) case msgUserAuthSuccess: return new(userAuthSuccessMsg), nil case msgUserAuthFailure: msg = new(userAuthFailureMsg) case msgUserAuthPubKeyOk: msg = new(userAuthPubKeyOkMsg) case msgGlobalRequest: msg = new(globalRequestMsg) case msgRequestSuccess: msg = new(globalRequestSuccessMsg) case msgRequestFailure: msg = new(globalRequestFailureMsg) case msgChannelOpen: msg = new(channelOpenMsg) case msgChannelData: msg = new(channelDataMsg) case msgChannelOpenConfirm: msg = new(channelOpenConfirmMsg) case msgChannelOpenFailure: msg = new(channelOpenFailureMsg) case msgChannelWindowAdjust: msg = new(windowAdjustMsg) case msgChannelEOF: msg = new(channelEOFMsg) case msgChannelClose: msg = new(channelCloseMsg) case msgChannelRequest: msg = new(channelRequestMsg) case msgChannelSuccess: msg = new(channelRequestSuccessMsg) case msgChannelFailure: msg = new(channelRequestFailureMsg) default: return nil, unexpectedMessageError(0, packet[0]) } if err := Unmarshal(packet, msg); err != nil { return nil, err } return msg, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/mempipe_test.go�����������������������������������������0000644�0610621�0607500�00000003744�13172163317�024701� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "io" "sync" "testing" ) // An in-memory packetConn. It is safe to call Close and writePacket // from different goroutines. type memTransport struct { eof bool pending [][]byte write *memTransport sync.Mutex *sync.Cond } func (t *memTransport) readPacket() ([]byte, error) { t.Lock() defer t.Unlock() for { if len(t.pending) > 0 { r := t.pending[0] t.pending = t.pending[1:] return r, nil } if t.eof { return nil, io.EOF } t.Cond.Wait() } } func (t *memTransport) closeSelf() error { t.Lock() defer t.Unlock() if t.eof { return io.EOF } t.eof = true t.Cond.Broadcast() return nil } func (t *memTransport) Close() error { err := t.write.closeSelf() t.closeSelf() return err } func (t *memTransport) writePacket(p []byte) error { t.write.Lock() defer t.write.Unlock() if t.write.eof { return io.EOF } c := make([]byte, len(p)) copy(c, p) t.write.pending = append(t.write.pending, c) t.write.Cond.Signal() return nil } func memPipe() (a, b packetConn) { t1 := memTransport{} t2 := memTransport{} t1.write = &t2 t2.write = &t1 t1.Cond = sync.NewCond(&t1.Mutex) t2.Cond = sync.NewCond(&t2.Mutex) return &t1, &t2 } func TestMemPipe(t *testing.T) { a, b := memPipe() if err := a.writePacket([]byte{42}); err != nil { t.Fatalf("writePacket: %v", err) } if err := a.Close(); err != nil { t.Fatal("Close: ", err) } p, err := b.readPacket() if err != nil { t.Fatal("readPacket: ", err) } if len(p) != 1 || p[0] != 42 { t.Fatalf("got %v, want {42}", p) } p, err = b.readPacket() if err != io.EOF { t.Fatalf("got %v, %v, want EOF", p, err) } } func TestDoubleClose(t *testing.T) { a, _ := memPipe() err := a.Close() if err != nil { t.Errorf("Close: %v", err) } err = a.Close() if err != io.EOF { t.Errorf("expect EOF on double close.") } } ����������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/mac.go��������������������������������������������������0000644�0610621�0607500�00000002502�13172163317�022735� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh // Message authentication support import ( "crypto/hmac" "crypto/sha1" "crypto/sha256" "hash" ) type macMode struct { keySize int etm bool new func(key []byte) hash.Hash } // truncatingMAC wraps around a hash.Hash and truncates the output digest to // a given size. type truncatingMAC struct { length int hmac hash.Hash } func (t truncatingMAC) Write(data []byte) (int, error) { return t.hmac.Write(data) } func (t truncatingMAC) Sum(in []byte) []byte { out := t.hmac.Sum(in) return out[:len(in)+t.length] } func (t truncatingMAC) Reset() { t.hmac.Reset() } func (t truncatingMAC) Size() int { return t.length } func (t truncatingMAC) BlockSize() int { return t.hmac.BlockSize() } var macModes = map[string]*macMode{ "hmac-sha2-256-etm@openssh.com": {32, true, func(key []byte) hash.Hash { return hmac.New(sha256.New, key) }}, "hmac-sha2-256": {32, false, func(key []byte) hash.Hash { return hmac.New(sha256.New, key) }}, "hmac-sha1": {20, false, func(key []byte) hash.Hash { return hmac.New(sha1.New, key) }}, "hmac-sha1-96": {20, false, func(key []byte) hash.Hash { return truncatingMAC{12, hmac.New(sha1.New, key)} }}, } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/knownhosts/���������������������������������������������0000755�0610621�0607500�00000000000�13172163317�024064� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/knownhosts/knownhosts_test.go���������������������������0000644�0610621�0607500�00000022213�13172163317�027667� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package knownhosts import ( "bytes" "fmt" "net" "reflect" "testing" "golang.org/x/crypto/ssh" ) const edKeyStr = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGBAarftlLeoyf+v+nVchEZII/vna2PCV8FaX4vsF5BX" const alternateEdKeyStr = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIXffBYeYL+WVzVru8npl5JHt2cjlr4ornFTWzoij9sx" const ecKeyStr = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNLCu01+wpXe3xB5olXCN4SqU2rQu0qjSRKJO4Bg+JRCPU+ENcgdA5srTU8xYDz/GEa4dzK5ldPw4J/gZgSXCMs=" var ecKey, alternateEdKey, edKey ssh.PublicKey var testAddr = &net.TCPAddr{ IP: net.IP{198, 41, 30, 196}, Port: 22, } var testAddr6 = &net.TCPAddr{ IP: net.IP{198, 41, 30, 196, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, }, Port: 22, } func init() { var err error ecKey, _, _, _, err = ssh.ParseAuthorizedKey([]byte(ecKeyStr)) if err != nil { panic(err) } edKey, _, _, _, err = ssh.ParseAuthorizedKey([]byte(edKeyStr)) if err != nil { panic(err) } alternateEdKey, _, _, _, err = ssh.ParseAuthorizedKey([]byte(alternateEdKeyStr)) if err != nil { panic(err) } } func testDB(t *testing.T, s string) *hostKeyDB { db := newHostKeyDB() if err := db.Read(bytes.NewBufferString(s), "testdb"); err != nil { t.Fatalf("Read: %v", err) } return db } func TestRevoked(t *testing.T) { db := testDB(t, "\n\n@revoked * "+edKeyStr+"\n") want := &RevokedError{ Revoked: KnownKey{ Key: edKey, Filename: "testdb", Line: 3, }, } if err := db.check("", &net.TCPAddr{ Port: 42, }, edKey); err == nil { t.Fatal("no error for revoked key") } else if !reflect.DeepEqual(want, err) { t.Fatalf("got %#v, want %#v", want, err) } } func TestHostAuthority(t *testing.T) { for _, m := range []struct { authorityFor string address string good bool }{ {authorityFor: "localhost", address: "localhost:22", good: true}, {authorityFor: "localhost", address: "localhost", good: false}, {authorityFor: "localhost", address: "localhost:1234", good: false}, {authorityFor: "[localhost]:1234", address: "localhost:1234", good: true}, {authorityFor: "[localhost]:1234", address: "localhost:22", good: false}, {authorityFor: "[localhost]:1234", address: "localhost", good: false}, } { db := testDB(t, `@cert-authority `+m.authorityFor+` `+edKeyStr) if ok := db.IsHostAuthority(db.lines[0].knownKey.Key, m.address); ok != m.good { t.Errorf("IsHostAuthority: authority %s, address %s, wanted good = %v, got good = %v", m.authorityFor, m.address, m.good, ok) } } } func TestBracket(t *testing.T) { db := testDB(t, `[git.eclipse.org]:29418,[198.41.30.196]:29418 `+edKeyStr) if err := db.check("git.eclipse.org:29418", &net.TCPAddr{ IP: net.IP{198, 41, 30, 196}, Port: 29418, }, edKey); err != nil { t.Errorf("got error %v, want none", err) } if err := db.check("git.eclipse.org:29419", &net.TCPAddr{ Port: 42, }, edKey); err == nil { t.Fatalf("no error for unknown address") } else if ke, ok := err.(*KeyError); !ok { t.Fatalf("got type %T, want *KeyError", err) } else if len(ke.Want) > 0 { t.Fatalf("got Want %v, want []", ke.Want) } } func TestNewKeyType(t *testing.T) { str := fmt.Sprintf("%s %s", testAddr, edKeyStr) db := testDB(t, str) if err := db.check("", testAddr, ecKey); err == nil { t.Fatalf("no error for unknown address") } else if ke, ok := err.(*KeyError); !ok { t.Fatalf("got type %T, want *KeyError", err) } else if len(ke.Want) == 0 { t.Fatalf("got empty KeyError.Want") } } func TestSameKeyType(t *testing.T) { str := fmt.Sprintf("%s %s", testAddr, edKeyStr) db := testDB(t, str) if err := db.check("", testAddr, alternateEdKey); err == nil { t.Fatalf("no error for unknown address") } else if ke, ok := err.(*KeyError); !ok { t.Fatalf("got type %T, want *KeyError", err) } else if len(ke.Want) == 0 { t.Fatalf("got empty KeyError.Want") } else if got, want := ke.Want[0].Key.Marshal(), edKey.Marshal(); !bytes.Equal(got, want) { t.Fatalf("got key %q, want %q", got, want) } } func TestIPAddress(t *testing.T) { str := fmt.Sprintf("%s %s", testAddr, edKeyStr) db := testDB(t, str) if err := db.check("", testAddr, edKey); err != nil { t.Errorf("got error %q, want none", err) } } func TestIPv6Address(t *testing.T) { str := fmt.Sprintf("%s %s", testAddr6, edKeyStr) db := testDB(t, str) if err := db.check("", testAddr6, edKey); err != nil { t.Errorf("got error %q, want none", err) } } func TestBasic(t *testing.T) { str := fmt.Sprintf("#comment\n\nserver.org,%s %s\notherhost %s", testAddr, edKeyStr, ecKeyStr) db := testDB(t, str) if err := db.check("server.org:22", testAddr, edKey); err != nil { t.Errorf("got error %q, want none", err) } want := KnownKey{ Key: edKey, Filename: "testdb", Line: 3, } if err := db.check("server.org:22", testAddr, ecKey); err == nil { t.Errorf("succeeded, want KeyError") } else if ke, ok := err.(*KeyError); !ok { t.Errorf("got %T, want *KeyError", err) } else if len(ke.Want) != 1 { t.Errorf("got %v, want 1 entry", ke) } else if !reflect.DeepEqual(ke.Want[0], want) { t.Errorf("got %v, want %v", ke.Want[0], want) } } func TestNegate(t *testing.T) { str := fmt.Sprintf("%s,!server.org %s", testAddr, edKeyStr) db := testDB(t, str) if err := db.check("server.org:22", testAddr, ecKey); err == nil { t.Errorf("succeeded") } else if ke, ok := err.(*KeyError); !ok { t.Errorf("got error type %T, want *KeyError", err) } else if len(ke.Want) != 0 { t.Errorf("got expected keys %d (first of type %s), want []", len(ke.Want), ke.Want[0].Key.Type()) } } func TestWildcard(t *testing.T) { str := fmt.Sprintf("server*.domain %s", edKeyStr) db := testDB(t, str) want := &KeyError{ Want: []KnownKey{{ Filename: "testdb", Line: 1, Key: edKey, }}, } got := db.check("server.domain:22", &net.TCPAddr{}, ecKey) if !reflect.DeepEqual(got, want) { t.Errorf("got %s, want %s", got, want) } } func TestLine(t *testing.T) { for in, want := range map[string]string{ "server.org": "server.org " + edKeyStr, "server.org:22": "server.org " + edKeyStr, "server.org:23": "[server.org]:23 " + edKeyStr, "[c629:1ec4:102:304:102:304:102:304]:22": "[c629:1ec4:102:304:102:304:102:304] " + edKeyStr, "[c629:1ec4:102:304:102:304:102:304]:23": "[c629:1ec4:102:304:102:304:102:304]:23 " + edKeyStr, } { if got := Line([]string{in}, edKey); got != want { t.Errorf("Line(%q) = %q, want %q", in, got, want) } } } func TestWildcardMatch(t *testing.T) { for _, c := range []struct { pat, str string want bool }{ {"a?b", "abb", true}, {"ab", "abc", false}, {"abc", "ab", false}, {"a*b", "axxxb", true}, {"a*b", "axbxb", true}, {"a*b", "axbxbc", false}, {"a*?", "axbxc", true}, {"a*b*", "axxbxxxxxx", true}, {"a*b*c", "axxbxxxxxxc", true}, {"a*b*?", "axxbxxxxxxc", true}, {"a*b*z", "axxbxxbxxxz", true}, {"a*b*z", "axxbxxzxxxz", true}, {"a*b*z", "axxbxxzxxx", false}, } { got := wildcardMatch([]byte(c.pat), []byte(c.str)) if got != c.want { t.Errorf("wildcardMatch(%q, %q) = %v, want %v", c.pat, c.str, got, c.want) } } } // TODO(hanwen): test coverage for certificates. const testHostname = "hostname" // generated with keygen -H -f const encodedTestHostnameHash = "|1|IHXZvQMvTcZTUU29+2vXFgx8Frs=|UGccIWfRVDwilMBnA3WJoRAC75Y=" func TestHostHash(t *testing.T) { testHostHash(t, testHostname, encodedTestHostnameHash) } func TestHashList(t *testing.T) { encoded := HashHostname(testHostname) testHostHash(t, testHostname, encoded) } func testHostHash(t *testing.T, hostname, encoded string) { typ, salt, hash, err := decodeHash(encoded) if err != nil { t.Fatalf("decodeHash: %v", err) } if got := encodeHash(typ, salt, hash); got != encoded { t.Errorf("got encoding %s want %s", got, encoded) } if typ != sha1HashType { t.Fatalf("got hash type %q, want %q", typ, sha1HashType) } got := hashHost(hostname, salt) if !bytes.Equal(got, hash) { t.Errorf("got hash %x want %x", got, hash) } } func TestNormalize(t *testing.T) { for in, want := range map[string]string{ "127.0.0.1:22": "127.0.0.1", "[127.0.0.1]:22": "127.0.0.1", "[127.0.0.1]:23": "[127.0.0.1]:23", "127.0.0.1:23": "[127.0.0.1]:23", "[a.b.c]:22": "a.b.c", "[abcd:abcd:abcd:abcd]": "[abcd:abcd:abcd:abcd]", "[abcd:abcd:abcd:abcd]:22": "[abcd:abcd:abcd:abcd]", "[abcd:abcd:abcd:abcd]:23": "[abcd:abcd:abcd:abcd]:23", } { got := Normalize(in) if got != want { t.Errorf("Normalize(%q) = %q, want %q", in, got, want) } } } func TestHashedHostkeyCheck(t *testing.T) { str := fmt.Sprintf("%s %s", HashHostname(testHostname), edKeyStr) db := testDB(t, str) if err := db.check(testHostname+":22", testAddr, edKey); err != nil { t.Errorf("check(%s): %v", testHostname, err) } want := &KeyError{ Want: []KnownKey{{ Filename: "testdb", Line: 1, Key: edKey, }}, } if got := db.check(testHostname+":22", testAddr, alternateEdKey); !reflect.DeepEqual(got, want) { t.Errorf("got error %v, want %v", got, want) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/knownhosts/knownhosts.go��������������������������������0000644�0610621�0607500�00000030220�13172163317�026625� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package knownhosts implements a parser for the OpenSSH // known_hosts host key database. package knownhosts import ( "bufio" "bytes" "crypto/hmac" "crypto/rand" "crypto/sha1" "encoding/base64" "errors" "fmt" "io" "net" "os" "strings" "golang.org/x/crypto/ssh" ) // See the sshd manpage // (http://man.openbsd.org/sshd#SSH_KNOWN_HOSTS_FILE_FORMAT) for // background. type addr struct{ host, port string } func (a *addr) String() string { h := a.host if strings.Contains(h, ":") { h = "[" + h + "]" } return h + ":" + a.port } type matcher interface { match([]addr) bool } type hostPattern struct { negate bool addr addr } func (p *hostPattern) String() string { n := "" if p.negate { n = "!" } return n + p.addr.String() } type hostPatterns []hostPattern func (ps hostPatterns) match(addrs []addr) bool { matched := false for _, p := range ps { for _, a := range addrs { m := p.match(a) if !m { continue } if p.negate { return false } matched = true } } return matched } // See // https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/addrmatch.c // The matching of * has no regard for separators, unlike filesystem globs func wildcardMatch(pat []byte, str []byte) bool { for { if len(pat) == 0 { return len(str) == 0 } if len(str) == 0 { return false } if pat[0] == '*' { if len(pat) == 1 { return true } for j := range str { if wildcardMatch(pat[1:], str[j:]) { return true } } return false } if pat[0] == '?' || pat[0] == str[0] { pat = pat[1:] str = str[1:] } else { return false } } } func (l *hostPattern) match(a addr) bool { return wildcardMatch([]byte(l.addr.host), []byte(a.host)) && l.addr.port == a.port } type keyDBLine struct { cert bool matcher matcher knownKey KnownKey } func serialize(k ssh.PublicKey) string { return k.Type() + " " + base64.StdEncoding.EncodeToString(k.Marshal()) } func (l *keyDBLine) match(addrs []addr) bool { return l.matcher.match(addrs) } type hostKeyDB struct { // Serialized version of revoked keys revoked map[string]*KnownKey lines []keyDBLine } func newHostKeyDB() *hostKeyDB { db := &hostKeyDB{ revoked: make(map[string]*KnownKey), } return db } func keyEq(a, b ssh.PublicKey) bool { return bytes.Equal(a.Marshal(), b.Marshal()) } // IsAuthorityForHost can be used as a callback in ssh.CertChecker func (db *hostKeyDB) IsHostAuthority(remote ssh.PublicKey, address string) bool { h, p, err := net.SplitHostPort(address) if err != nil { return false } a := addr{host: h, port: p} for _, l := range db.lines { if l.cert && keyEq(l.knownKey.Key, remote) && l.match([]addr{a}) { return true } } return false } // IsRevoked can be used as a callback in ssh.CertChecker func (db *hostKeyDB) IsRevoked(key *ssh.Certificate) bool { _, ok := db.revoked[string(key.Marshal())] return ok } const markerCert = "@cert-authority" const markerRevoked = "@revoked" func nextWord(line []byte) (string, []byte) { i := bytes.IndexAny(line, "\t ") if i == -1 { return string(line), nil } return string(line[:i]), bytes.TrimSpace(line[i:]) } func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error) { if w, next := nextWord(line); w == markerCert || w == markerRevoked { marker = w line = next } host, line = nextWord(line) if len(line) == 0 { return "", "", nil, errors.New("knownhosts: missing host pattern") } // ignore the keytype as it's in the key blob anyway. _, line = nextWord(line) if len(line) == 0 { return "", "", nil, errors.New("knownhosts: missing key type pattern") } keyBlob, _ := nextWord(line) keyBytes, err := base64.StdEncoding.DecodeString(keyBlob) if err != nil { return "", "", nil, err } key, err = ssh.ParsePublicKey(keyBytes) if err != nil { return "", "", nil, err } return marker, host, key, nil } func (db *hostKeyDB) parseLine(line []byte, filename string, linenum int) error { marker, pattern, key, err := parseLine(line) if err != nil { return err } if marker == markerRevoked { db.revoked[string(key.Marshal())] = &KnownKey{ Key: key, Filename: filename, Line: linenum, } return nil } entry := keyDBLine{ cert: marker == markerCert, knownKey: KnownKey{ Filename: filename, Line: linenum, Key: key, }, } if pattern[0] == '|' { entry.matcher, err = newHashedHost(pattern) } else { entry.matcher, err = newHostnameMatcher(pattern) } if err != nil { return err } db.lines = append(db.lines, entry) return nil } func newHostnameMatcher(pattern string) (matcher, error) { var hps hostPatterns for _, p := range strings.Split(pattern, ",") { if len(p) == 0 { continue } var a addr var negate bool if p[0] == '!' { negate = true p = p[1:] } if len(p) == 0 { return nil, errors.New("knownhosts: negation without following hostname") } var err error if p[0] == '[' { a.host, a.port, err = net.SplitHostPort(p) if err != nil { return nil, err } } else { a.host, a.port, err = net.SplitHostPort(p) if err != nil { a.host = p a.port = "22" } } hps = append(hps, hostPattern{ negate: negate, addr: a, }) } return hps, nil } // KnownKey represents a key declared in a known_hosts file. type KnownKey struct { Key ssh.PublicKey Filename string Line int } func (k *KnownKey) String() string { return fmt.Sprintf("%s:%d: %s", k.Filename, k.Line, serialize(k.Key)) } // KeyError is returned if we did not find the key in the host key // database, or there was a mismatch. Typically, in batch // applications, this should be interpreted as failure. Interactive // applications can offer an interactive prompt to the user. type KeyError struct { // Want holds the accepted host keys. For each key algorithm, // there can be one hostkey. If Want is empty, the host is // unknown. If Want is non-empty, there was a mismatch, which // can signify a MITM attack. Want []KnownKey } func (u *KeyError) Error() string { if len(u.Want) == 0 { return "knownhosts: key is unknown" } return "knownhosts: key mismatch" } // RevokedError is returned if we found a key that was revoked. type RevokedError struct { Revoked KnownKey } func (r *RevokedError) Error() string { return "knownhosts: key is revoked" } // check checks a key against the host database. This should not be // used for verifying certificates. func (db *hostKeyDB) check(address string, remote net.Addr, remoteKey ssh.PublicKey) error { if revoked := db.revoked[string(remoteKey.Marshal())]; revoked != nil { return &RevokedError{Revoked: *revoked} } host, port, err := net.SplitHostPort(remote.String()) if err != nil { return fmt.Errorf("knownhosts: SplitHostPort(%s): %v", remote, err) } addrs := []addr{ {host, port}, } if address != "" { host, port, err := net.SplitHostPort(address) if err != nil { return fmt.Errorf("knownhosts: SplitHostPort(%s): %v", address, err) } addrs = append(addrs, addr{host, port}) } return db.checkAddrs(addrs, remoteKey) } // checkAddrs checks if we can find the given public key for any of // the given addresses. If we only find an entry for the IP address, // or only the hostname, then this still succeeds. func (db *hostKeyDB) checkAddrs(addrs []addr, remoteKey ssh.PublicKey) error { // TODO(hanwen): are these the right semantics? What if there // is just a key for the IP address, but not for the // hostname? // Algorithm => key. knownKeys := map[string]KnownKey{} for _, l := range db.lines { if l.match(addrs) { typ := l.knownKey.Key.Type() if _, ok := knownKeys[typ]; !ok { knownKeys[typ] = l.knownKey } } } keyErr := &KeyError{} for _, v := range knownKeys { keyErr.Want = append(keyErr.Want, v) } // Unknown remote host. if len(knownKeys) == 0 { return keyErr } // If the remote host starts using a different, unknown key type, we // also interpret that as a mismatch. if known, ok := knownKeys[remoteKey.Type()]; !ok || !keyEq(known.Key, remoteKey) { return keyErr } return nil } // The Read function parses file contents. func (db *hostKeyDB) Read(r io.Reader, filename string) error { scanner := bufio.NewScanner(r) lineNum := 0 for scanner.Scan() { lineNum++ line := scanner.Bytes() line = bytes.TrimSpace(line) if len(line) == 0 || line[0] == '#' { continue } if err := db.parseLine(line, filename, lineNum); err != nil { return fmt.Errorf("knownhosts: %s:%d: %v", filename, lineNum, err) } } return scanner.Err() } // New creates a host key callback from the given OpenSSH host key // files. The returned callback is for use in // ssh.ClientConfig.HostKeyCallback. Hashed hostnames are not supported. func New(files ...string) (ssh.HostKeyCallback, error) { db := newHostKeyDB() for _, fn := range files { f, err := os.Open(fn) if err != nil { return nil, err } defer f.Close() if err := db.Read(f, fn); err != nil { return nil, err } } var certChecker ssh.CertChecker certChecker.IsHostAuthority = db.IsHostAuthority certChecker.IsRevoked = db.IsRevoked certChecker.HostKeyFallback = db.check return certChecker.CheckHostKey, nil } // Normalize normalizes an address into the form used in known_hosts func Normalize(address string) string { host, port, err := net.SplitHostPort(address) if err != nil { host = address port = "22" } entry := host if port != "22" { entry = "[" + entry + "]:" + port } else if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") { entry = "[" + entry + "]" } return entry } // Line returns a line to add append to the known_hosts files. func Line(addresses []string, key ssh.PublicKey) string { var trimmed []string for _, a := range addresses { trimmed = append(trimmed, Normalize(a)) } return strings.Join(trimmed, ",") + " " + serialize(key) } // HashHostname hashes the given hostname. The hostname is not // normalized before hashing. func HashHostname(hostname string) string { // TODO(hanwen): check if we can safely normalize this always. salt := make([]byte, sha1.Size) _, err := rand.Read(salt) if err != nil { panic(fmt.Sprintf("crypto/rand failure %v", err)) } hash := hashHost(hostname, salt) return encodeHash(sha1HashType, salt, hash) } func decodeHash(encoded string) (hashType string, salt, hash []byte, err error) { if len(encoded) == 0 || encoded[0] != '|' { err = errors.New("knownhosts: hashed host must start with '|'") return } components := strings.Split(encoded, "|") if len(components) != 4 { err = fmt.Errorf("knownhosts: got %d components, want 3", len(components)) return } hashType = components[1] if salt, err = base64.StdEncoding.DecodeString(components[2]); err != nil { return } if hash, err = base64.StdEncoding.DecodeString(components[3]); err != nil { return } return } func encodeHash(typ string, salt []byte, hash []byte) string { return strings.Join([]string{"", typ, base64.StdEncoding.EncodeToString(salt), base64.StdEncoding.EncodeToString(hash), }, "|") } // See https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/hostfile.c#120 func hashHost(hostname string, salt []byte) []byte { mac := hmac.New(sha1.New, salt) mac.Write([]byte(hostname)) return mac.Sum(nil) } type hashedHost struct { salt []byte hash []byte } const sha1HashType = "1" func newHashedHost(encoded string) (*hashedHost, error) { typ, salt, hash, err := decodeHash(encoded) if err != nil { return nil, err } // The type field seems for future algorithm agility, but it's // actually hardcoded in openssh currently, see // https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/hostfile.c#120 if typ != sha1HashType { return nil, fmt.Errorf("knownhosts: got hash type %s, must be '1'", typ) } return &hashedHost{salt: salt, hash: hash}, nil } func (h *hashedHost) match(addrs []addr) bool { for _, a := range addrs { if bytes.Equal(hashHost(Normalize(a.String()), h.salt), h.hash) { return true } } return false } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/keys_test.go��������������������������������������������0000644�0610621�0607500�00000032221�13172163317�024210� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "fmt" "reflect" "strings" "testing" "golang.org/x/crypto/ed25519" "golang.org/x/crypto/ssh/testdata" ) func rawKey(pub PublicKey) interface{} { switch k := pub.(type) { case *rsaPublicKey: return (*rsa.PublicKey)(k) case *dsaPublicKey: return (*dsa.PublicKey)(k) case *ecdsaPublicKey: return (*ecdsa.PublicKey)(k) case ed25519PublicKey: return (ed25519.PublicKey)(k) case *Certificate: return k } panic("unknown key type") } func TestKeyMarshalParse(t *testing.T) { for _, priv := range testSigners { pub := priv.PublicKey() roundtrip, err := ParsePublicKey(pub.Marshal()) if err != nil { t.Errorf("ParsePublicKey(%T): %v", pub, err) } k1 := rawKey(pub) k2 := rawKey(roundtrip) if !reflect.DeepEqual(k1, k2) { t.Errorf("got %#v in roundtrip, want %#v", k2, k1) } } } func TestUnsupportedCurves(t *testing.T) { raw, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) if err != nil { t.Fatalf("GenerateKey: %v", err) } if _, err = NewSignerFromKey(raw); err == nil || !strings.Contains(err.Error(), "only P-256") { t.Fatalf("NewPrivateKey should not succeed with P-224, got: %v", err) } if _, err = NewPublicKey(&raw.PublicKey); err == nil || !strings.Contains(err.Error(), "only P-256") { t.Fatalf("NewPublicKey should not succeed with P-224, got: %v", err) } } func TestNewPublicKey(t *testing.T) { for _, k := range testSigners { raw := rawKey(k.PublicKey()) // Skip certificates, as NewPublicKey does not support them. if _, ok := raw.(*Certificate); ok { continue } pub, err := NewPublicKey(raw) if err != nil { t.Errorf("NewPublicKey(%#v): %v", raw, err) } if !reflect.DeepEqual(k.PublicKey(), pub) { t.Errorf("NewPublicKey(%#v) = %#v, want %#v", raw, pub, k.PublicKey()) } } } func TestKeySignVerify(t *testing.T) { for _, priv := range testSigners { pub := priv.PublicKey() data := []byte("sign me") sig, err := priv.Sign(rand.Reader, data) if err != nil { t.Fatalf("Sign(%T): %v", priv, err) } if err := pub.Verify(data, sig); err != nil { t.Errorf("publicKey.Verify(%T): %v", priv, err) } sig.Blob[5]++ if err := pub.Verify(data, sig); err == nil { t.Errorf("publicKey.Verify on broken sig did not fail") } } } func TestParseRSAPrivateKey(t *testing.T) { key := testPrivateKeys["rsa"] rsa, ok := key.(*rsa.PrivateKey) if !ok { t.Fatalf("got %T, want *rsa.PrivateKey", rsa) } if err := rsa.Validate(); err != nil { t.Errorf("Validate: %v", err) } } func TestParseECPrivateKey(t *testing.T) { key := testPrivateKeys["ecdsa"] ecKey, ok := key.(*ecdsa.PrivateKey) if !ok { t.Fatalf("got %T, want *ecdsa.PrivateKey", ecKey) } if !validateECPublicKey(ecKey.Curve, ecKey.X, ecKey.Y) { t.Fatalf("public key does not validate.") } } // See Issue https://github.com/golang/go/issues/6650. func TestParseEncryptedPrivateKeysFails(t *testing.T) { const wantSubstring = "encrypted" for i, tt := range testdata.PEMEncryptedKeys { _, err := ParsePrivateKey(tt.PEMBytes) if err == nil { t.Errorf("#%d key %s: ParsePrivateKey successfully parsed, expected an error", i, tt.Name) continue } if !strings.Contains(err.Error(), wantSubstring) { t.Errorf("#%d key %s: got error %q, want substring %q", i, tt.Name, err, wantSubstring) } } } // Parse encrypted private keys with passphrase func TestParseEncryptedPrivateKeysWithPassphrase(t *testing.T) { data := []byte("sign me") for _, tt := range testdata.PEMEncryptedKeys { s, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte(tt.EncryptionKey)) if err != nil { t.Fatalf("ParsePrivateKeyWithPassphrase returned error: %s", err) continue } sig, err := s.Sign(rand.Reader, data) if err != nil { t.Fatalf("dsa.Sign: %v", err) } if err := s.PublicKey().Verify(data, sig); err != nil { t.Errorf("Verify failed: %v", err) } } tt := testdata.PEMEncryptedKeys[0] _, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte("incorrect")) if err != x509.IncorrectPasswordError { t.Fatalf("got %v want IncorrectPasswordError", err) } } func TestParseDSA(t *testing.T) { // We actually exercise the ParsePrivateKey codepath here, as opposed to // using the ParseRawPrivateKey+NewSignerFromKey path that testdata_test.go // uses. s, err := ParsePrivateKey(testdata.PEMBytes["dsa"]) if err != nil { t.Fatalf("ParsePrivateKey returned error: %s", err) } data := []byte("sign me") sig, err := s.Sign(rand.Reader, data) if err != nil { t.Fatalf("dsa.Sign: %v", err) } if err := s.PublicKey().Verify(data, sig); err != nil { t.Errorf("Verify failed: %v", err) } } // Tests for authorized_keys parsing. // getTestKey returns a public key, and its base64 encoding. func getTestKey() (PublicKey, string) { k := testPublicKeys["rsa"] b := &bytes.Buffer{} e := base64.NewEncoder(base64.StdEncoding, b) e.Write(k.Marshal()) e.Close() return k, b.String() } func TestMarshalParsePublicKey(t *testing.T) { pub, pubSerialized := getTestKey() line := fmt.Sprintf("%s %s user@host", pub.Type(), pubSerialized) authKeys := MarshalAuthorizedKey(pub) actualFields := strings.Fields(string(authKeys)) if len(actualFields) == 0 { t.Fatalf("failed authKeys: %v", authKeys) } // drop the comment expectedFields := strings.Fields(line)[0:2] if !reflect.DeepEqual(actualFields, expectedFields) { t.Errorf("got %v, expected %v", actualFields, expectedFields) } actPub, _, _, _, err := ParseAuthorizedKey([]byte(line)) if err != nil { t.Fatalf("cannot parse %v: %v", line, err) } if !reflect.DeepEqual(actPub, pub) { t.Errorf("got %v, expected %v", actPub, pub) } } type authResult struct { pubKey PublicKey options []string comments string rest string ok bool } func testAuthorizedKeys(t *testing.T, authKeys []byte, expected []authResult) { rest := authKeys var values []authResult for len(rest) > 0 { var r authResult var err error r.pubKey, r.comments, r.options, rest, err = ParseAuthorizedKey(rest) r.ok = (err == nil) t.Log(err) r.rest = string(rest) values = append(values, r) } if !reflect.DeepEqual(values, expected) { t.Errorf("got %#v, expected %#v", values, expected) } } func TestAuthorizedKeyBasic(t *testing.T) { pub, pubSerialized := getTestKey() line := "ssh-rsa " + pubSerialized + " user@host" testAuthorizedKeys(t, []byte(line), []authResult{ {pub, nil, "user@host", "", true}, }) } func TestAuth(t *testing.T) { pub, pubSerialized := getTestKey() authWithOptions := []string{ `# comments to ignore before any keys...`, ``, `env="HOME=/home/root",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`, `# comments to ignore, along with a blank line`, ``, `env="HOME=/home/root2" ssh-rsa ` + pubSerialized + ` user2@host2`, ``, `# more comments, plus a invalid entry`, `ssh-rsa data-that-will-not-parse user@host3`, } for _, eol := range []string{"\n", "\r\n"} { authOptions := strings.Join(authWithOptions, eol) rest2 := strings.Join(authWithOptions[3:], eol) rest3 := strings.Join(authWithOptions[6:], eol) testAuthorizedKeys(t, []byte(authOptions), []authResult{ {pub, []string{`env="HOME=/home/root"`, "no-port-forwarding"}, "user@host", rest2, true}, {pub, []string{`env="HOME=/home/root2"`}, "user2@host2", rest3, true}, {nil, nil, "", "", false}, }) } } func TestAuthWithQuotedSpaceInEnv(t *testing.T) { pub, pubSerialized := getTestKey() authWithQuotedSpaceInEnv := []byte(`env="HOME=/home/root dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`) testAuthorizedKeys(t, []byte(authWithQuotedSpaceInEnv), []authResult{ {pub, []string{`env="HOME=/home/root dir"`, "no-port-forwarding"}, "user@host", "", true}, }) } func TestAuthWithQuotedCommaInEnv(t *testing.T) { pub, pubSerialized := getTestKey() authWithQuotedCommaInEnv := []byte(`env="HOME=/home/root,dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`) testAuthorizedKeys(t, []byte(authWithQuotedCommaInEnv), []authResult{ {pub, []string{`env="HOME=/home/root,dir"`, "no-port-forwarding"}, "user@host", "", true}, }) } func TestAuthWithQuotedQuoteInEnv(t *testing.T) { pub, pubSerialized := getTestKey() authWithQuotedQuoteInEnv := []byte(`env="HOME=/home/\"root dir",no-port-forwarding` + "\t" + `ssh-rsa` + "\t" + pubSerialized + ` user@host`) authWithDoubleQuotedQuote := []byte(`no-port-forwarding,env="HOME=/home/ \"root dir\"" ssh-rsa ` + pubSerialized + "\t" + `user@host`) testAuthorizedKeys(t, []byte(authWithQuotedQuoteInEnv), []authResult{ {pub, []string{`env="HOME=/home/\"root dir"`, "no-port-forwarding"}, "user@host", "", true}, }) testAuthorizedKeys(t, []byte(authWithDoubleQuotedQuote), []authResult{ {pub, []string{"no-port-forwarding", `env="HOME=/home/ \"root dir\""`}, "user@host", "", true}, }) } func TestAuthWithInvalidSpace(t *testing.T) { _, pubSerialized := getTestKey() authWithInvalidSpace := []byte(`env="HOME=/home/root dir", no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host #more to follow but still no valid keys`) testAuthorizedKeys(t, []byte(authWithInvalidSpace), []authResult{ {nil, nil, "", "", false}, }) } func TestAuthWithMissingQuote(t *testing.T) { pub, pubSerialized := getTestKey() authWithMissingQuote := []byte(`env="HOME=/home/root,no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host env="HOME=/home/root",shared-control ssh-rsa ` + pubSerialized + ` user@host`) testAuthorizedKeys(t, []byte(authWithMissingQuote), []authResult{ {pub, []string{`env="HOME=/home/root"`, `shared-control`}, "user@host", "", true}, }) } func TestInvalidEntry(t *testing.T) { authInvalid := []byte(`ssh-rsa`) _, _, _, _, err := ParseAuthorizedKey(authInvalid) if err == nil { t.Errorf("got valid entry for %q", authInvalid) } } var knownHostsParseTests = []struct { input string err string marker string comment string hosts []string rest string }{ { "", "EOF", "", "", nil, "", }, { "# Just a comment", "EOF", "", "", nil, "", }, { " \t ", "EOF", "", "", nil, "", }, { "localhost ssh-rsa {RSAPUB}", "", "", "", []string{"localhost"}, "", }, { "localhost\tssh-rsa {RSAPUB}", "", "", "", []string{"localhost"}, "", }, { "localhost\tssh-rsa {RSAPUB}\tcomment comment", "", "", "comment comment", []string{"localhost"}, "", }, { "localhost\tssh-rsa {RSAPUB}\tcomment comment\n", "", "", "comment comment", []string{"localhost"}, "", }, { "localhost\tssh-rsa {RSAPUB}\tcomment comment\r\n", "", "", "comment comment", []string{"localhost"}, "", }, { "localhost\tssh-rsa {RSAPUB}\tcomment comment\r\nnext line", "", "", "comment comment", []string{"localhost"}, "next line", }, { "localhost,[host2:123]\tssh-rsa {RSAPUB}\tcomment comment", "", "", "comment comment", []string{"localhost", "[host2:123]"}, "", }, { "@marker \tlocalhost,[host2:123]\tssh-rsa {RSAPUB}", "", "marker", "", []string{"localhost", "[host2:123]"}, "", }, { "@marker \tlocalhost,[host2:123]\tssh-rsa aabbccdd", "short read", "", "", nil, "", }, } func TestKnownHostsParsing(t *testing.T) { rsaPub, rsaPubSerialized := getTestKey() for i, test := range knownHostsParseTests { var expectedKey PublicKey const rsaKeyToken = "{RSAPUB}" input := test.input if strings.Contains(input, rsaKeyToken) { expectedKey = rsaPub input = strings.Replace(test.input, rsaKeyToken, rsaPubSerialized, -1) } marker, hosts, pubKey, comment, rest, err := ParseKnownHosts([]byte(input)) if err != nil { if len(test.err) == 0 { t.Errorf("#%d: unexpectedly failed with %q", i, err) } else if !strings.Contains(err.Error(), test.err) { t.Errorf("#%d: expected error containing %q, but got %q", i, test.err, err) } continue } else if len(test.err) != 0 { t.Errorf("#%d: succeeded but expected error including %q", i, test.err) continue } if !reflect.DeepEqual(expectedKey, pubKey) { t.Errorf("#%d: expected key %#v, but got %#v", i, expectedKey, pubKey) } if marker != test.marker { t.Errorf("#%d: expected marker %q, but got %q", i, test.marker, marker) } if comment != test.comment { t.Errorf("#%d: expected comment %q, but got %q", i, test.comment, comment) } if !reflect.DeepEqual(test.hosts, hosts) { t.Errorf("#%d: expected hosts %#v, but got %#v", i, test.hosts, hosts) } if rest := string(rest); rest != test.rest { t.Errorf("#%d: expected remaining input to be %q, but got %q", i, test.rest, rest) } } } func TestFingerprintLegacyMD5(t *testing.T) { pub, _ := getTestKey() fingerprint := FingerprintLegacyMD5(pub) want := "fb:61:6d:1a:e3:f0:95:45:3c:a0:79:be:4a:93:63:66" // ssh-keygen -lf -E md5 rsa if fingerprint != want { t.Errorf("got fingerprint %q want %q", fingerprint, want) } } func TestFingerprintSHA256(t *testing.T) { pub, _ := getTestKey() fingerprint := FingerprintSHA256(pub) want := "SHA256:Anr3LjZK8YVpjrxu79myrW9Hrb/wpcMNpVvTq/RcBm8" // ssh-keygen -lf rsa if fingerprint != want { t.Errorf("got fingerprint %q want %q", fingerprint, want) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/keys.go�������������������������������������������������0000644�0610621�0607500�00000062475�13172163317�023167� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "crypto" "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" "crypto/md5" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/asn1" "encoding/base64" "encoding/hex" "encoding/pem" "errors" "fmt" "io" "math/big" "strings" "golang.org/x/crypto/ed25519" ) // These constants represent the algorithm names for key types supported by this // package. const ( KeyAlgoRSA = "ssh-rsa" KeyAlgoDSA = "ssh-dss" KeyAlgoECDSA256 = "ecdsa-sha2-nistp256" KeyAlgoECDSA384 = "ecdsa-sha2-nistp384" KeyAlgoECDSA521 = "ecdsa-sha2-nistp521" KeyAlgoED25519 = "ssh-ed25519" ) // parsePubKey parses a public key of the given algorithm. // Use ParsePublicKey for keys with prepended algorithm. func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) { switch algo { case KeyAlgoRSA: return parseRSA(in) case KeyAlgoDSA: return parseDSA(in) case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521: return parseECDSA(in) case KeyAlgoED25519: return parseED25519(in) case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01: cert, err := parseCert(in, certToPrivAlgo(algo)) if err != nil { return nil, nil, err } return cert, nil, nil } return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo) } // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format // (see sshd(8) manual page) once the options and key type fields have been // removed. func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) { in = bytes.TrimSpace(in) i := bytes.IndexAny(in, " \t") if i == -1 { i = len(in) } base64Key := in[:i] key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key))) n, err := base64.StdEncoding.Decode(key, base64Key) if err != nil { return nil, "", err } key = key[:n] out, err = ParsePublicKey(key) if err != nil { return nil, "", err } comment = string(bytes.TrimSpace(in[i:])) return out, comment, nil } // ParseKnownHosts parses an entry in the format of the known_hosts file. // // The known_hosts format is documented in the sshd(8) manual page. This // function will parse a single entry from in. On successful return, marker // will contain the optional marker value (i.e. "cert-authority" or "revoked") // or else be empty, hosts will contain the hosts that this entry matches, // pubKey will contain the public key and comment will contain any trailing // comment at the end of the line. See the sshd(8) manual page for the various // forms that a host string can take. // // The unparsed remainder of the input will be returned in rest. This function // can be called repeatedly to parse multiple entries. // // If no entries were found in the input then err will be io.EOF. Otherwise a // non-nil err value indicates a parse error. func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) { for len(in) > 0 { end := bytes.IndexByte(in, '\n') if end != -1 { rest = in[end+1:] in = in[:end] } else { rest = nil } end = bytes.IndexByte(in, '\r') if end != -1 { in = in[:end] } in = bytes.TrimSpace(in) if len(in) == 0 || in[0] == '#' { in = rest continue } i := bytes.IndexAny(in, " \t") if i == -1 { in = rest continue } // Strip out the beginning of the known_host key. // This is either an optional marker or a (set of) hostname(s). keyFields := bytes.Fields(in) if len(keyFields) < 3 || len(keyFields) > 5 { return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data") } // keyFields[0] is either "@cert-authority", "@revoked" or a comma separated // list of hosts marker := "" if keyFields[0][0] == '@' { marker = string(keyFields[0][1:]) keyFields = keyFields[1:] } hosts := string(keyFields[0]) // keyFields[1] contains the key type (e.g. “ssh-rsaâ€). // However, that information is duplicated inside the // base64-encoded key and so is ignored here. key := bytes.Join(keyFields[2:], []byte(" ")) if pubKey, comment, err = parseAuthorizedKey(key); err != nil { return "", nil, nil, "", nil, err } return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil } return "", nil, nil, "", nil, io.EOF } // ParseAuthorizedKeys parses a public key from an authorized_keys // file used in OpenSSH according to the sshd(8) manual page. func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) { for len(in) > 0 { end := bytes.IndexByte(in, '\n') if end != -1 { rest = in[end+1:] in = in[:end] } else { rest = nil } end = bytes.IndexByte(in, '\r') if end != -1 { in = in[:end] } in = bytes.TrimSpace(in) if len(in) == 0 || in[0] == '#' { in = rest continue } i := bytes.IndexAny(in, " \t") if i == -1 { in = rest continue } if out, comment, err = parseAuthorizedKey(in[i:]); err == nil { return out, comment, options, rest, nil } // No key type recognised. Maybe there's an options field at // the beginning. var b byte inQuote := false var candidateOptions []string optionStart := 0 for i, b = range in { isEnd := !inQuote && (b == ' ' || b == '\t') if (b == ',' && !inQuote) || isEnd { if i-optionStart > 0 { candidateOptions = append(candidateOptions, string(in[optionStart:i])) } optionStart = i + 1 } if isEnd { break } if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) { inQuote = !inQuote } } for i < len(in) && (in[i] == ' ' || in[i] == '\t') { i++ } if i == len(in) { // Invalid line: unmatched quote in = rest continue } in = in[i:] i = bytes.IndexAny(in, " \t") if i == -1 { in = rest continue } if out, comment, err = parseAuthorizedKey(in[i:]); err == nil { options = candidateOptions return out, comment, options, rest, nil } in = rest continue } return nil, "", nil, nil, errors.New("ssh: no key found") } // ParsePublicKey parses an SSH public key formatted for use in // the SSH wire protocol according to RFC 4253, section 6.6. func ParsePublicKey(in []byte) (out PublicKey, err error) { algo, in, ok := parseString(in) if !ok { return nil, errShortRead } var rest []byte out, rest, err = parsePubKey(in, string(algo)) if len(rest) > 0 { return nil, errors.New("ssh: trailing junk in public key") } return out, err } // MarshalAuthorizedKey serializes key for inclusion in an OpenSSH // authorized_keys file. The return value ends with newline. func MarshalAuthorizedKey(key PublicKey) []byte { b := &bytes.Buffer{} b.WriteString(key.Type()) b.WriteByte(' ') e := base64.NewEncoder(base64.StdEncoding, b) e.Write(key.Marshal()) e.Close() b.WriteByte('\n') return b.Bytes() } // PublicKey is an abstraction of different types of public keys. type PublicKey interface { // Type returns the key's type, e.g. "ssh-rsa". Type() string // Marshal returns the serialized key data in SSH wire format, // with the name prefix. Marshal() []byte // Verify that sig is a signature on the given data using this // key. This function will hash the data appropriately first. Verify(data []byte, sig *Signature) error } // CryptoPublicKey, if implemented by a PublicKey, // returns the underlying crypto.PublicKey form of the key. type CryptoPublicKey interface { CryptoPublicKey() crypto.PublicKey } // A Signer can create signatures that verify against a public key. type Signer interface { // PublicKey returns an associated PublicKey instance. PublicKey() PublicKey // Sign returns raw signature for the given data. This method // will apply the hash specified for the keytype to the data. Sign(rand io.Reader, data []byte) (*Signature, error) } type rsaPublicKey rsa.PublicKey func (r *rsaPublicKey) Type() string { return "ssh-rsa" } // parseRSA parses an RSA key according to RFC 4253, section 6.6. func parseRSA(in []byte) (out PublicKey, rest []byte, err error) { var w struct { E *big.Int N *big.Int Rest []byte `ssh:"rest"` } if err := Unmarshal(in, &w); err != nil { return nil, nil, err } if w.E.BitLen() > 24 { return nil, nil, errors.New("ssh: exponent too large") } e := w.E.Int64() if e < 3 || e&1 == 0 { return nil, nil, errors.New("ssh: incorrect exponent") } var key rsa.PublicKey key.E = int(e) key.N = w.N return (*rsaPublicKey)(&key), w.Rest, nil } func (r *rsaPublicKey) Marshal() []byte { e := new(big.Int).SetInt64(int64(r.E)) // RSA publickey struct layout should match the struct used by // parseRSACert in the x/crypto/ssh/agent package. wirekey := struct { Name string E *big.Int N *big.Int }{ KeyAlgoRSA, e, r.N, } return Marshal(&wirekey) } func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error { if sig.Format != r.Type() { return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type()) } h := crypto.SHA1.New() h.Write(data) digest := h.Sum(nil) return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig.Blob) } func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey { return (*rsa.PublicKey)(r) } type dsaPublicKey dsa.PublicKey func (r *dsaPublicKey) Type() string { return "ssh-dss" } func checkDSAParams(param *dsa.Parameters) error { // SSH specifies FIPS 186-2, which only provided a single size // (1024 bits) DSA key. FIPS 186-3 allows for larger key // sizes, which would confuse SSH. if l := param.P.BitLen(); l != 1024 { return fmt.Errorf("ssh: unsupported DSA key size %d", l) } return nil } // parseDSA parses an DSA key according to RFC 4253, section 6.6. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) { var w struct { P, Q, G, Y *big.Int Rest []byte `ssh:"rest"` } if err := Unmarshal(in, &w); err != nil { return nil, nil, err } param := dsa.Parameters{ P: w.P, Q: w.Q, G: w.G, } if err := checkDSAParams(&param); err != nil { return nil, nil, err } key := &dsaPublicKey{ Parameters: param, Y: w.Y, } return key, w.Rest, nil } func (k *dsaPublicKey) Marshal() []byte { // DSA publickey struct layout should match the struct used by // parseDSACert in the x/crypto/ssh/agent package. w := struct { Name string P, Q, G, Y *big.Int }{ k.Type(), k.P, k.Q, k.G, k.Y, } return Marshal(&w) } func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error { if sig.Format != k.Type() { return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) } h := crypto.SHA1.New() h.Write(data) digest := h.Sum(nil) // Per RFC 4253, section 6.6, // The value for 'dss_signature_blob' is encoded as a string containing // r, followed by s (which are 160-bit integers, without lengths or // padding, unsigned, and in network byte order). // For DSS purposes, sig.Blob should be exactly 40 bytes in length. if len(sig.Blob) != 40 { return errors.New("ssh: DSA signature parse error") } r := new(big.Int).SetBytes(sig.Blob[:20]) s := new(big.Int).SetBytes(sig.Blob[20:]) if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) { return nil } return errors.New("ssh: signature did not verify") } func (k *dsaPublicKey) CryptoPublicKey() crypto.PublicKey { return (*dsa.PublicKey)(k) } type dsaPrivateKey struct { *dsa.PrivateKey } func (k *dsaPrivateKey) PublicKey() PublicKey { return (*dsaPublicKey)(&k.PrivateKey.PublicKey) } func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) { h := crypto.SHA1.New() h.Write(data) digest := h.Sum(nil) r, s, err := dsa.Sign(rand, k.PrivateKey, digest) if err != nil { return nil, err } sig := make([]byte, 40) rb := r.Bytes() sb := s.Bytes() copy(sig[20-len(rb):20], rb) copy(sig[40-len(sb):], sb) return &Signature{ Format: k.PublicKey().Type(), Blob: sig, }, nil } type ecdsaPublicKey ecdsa.PublicKey func (key *ecdsaPublicKey) Type() string { return "ecdsa-sha2-" + key.nistID() } func (key *ecdsaPublicKey) nistID() string { switch key.Params().BitSize { case 256: return "nistp256" case 384: return "nistp384" case 521: return "nistp521" } panic("ssh: unsupported ecdsa key size") } type ed25519PublicKey ed25519.PublicKey func (key ed25519PublicKey) Type() string { return KeyAlgoED25519 } func parseED25519(in []byte) (out PublicKey, rest []byte, err error) { var w struct { KeyBytes []byte Rest []byte `ssh:"rest"` } if err := Unmarshal(in, &w); err != nil { return nil, nil, err } key := ed25519.PublicKey(w.KeyBytes) return (ed25519PublicKey)(key), w.Rest, nil } func (key ed25519PublicKey) Marshal() []byte { w := struct { Name string KeyBytes []byte }{ KeyAlgoED25519, []byte(key), } return Marshal(&w) } func (key ed25519PublicKey) Verify(b []byte, sig *Signature) error { if sig.Format != key.Type() { return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type()) } edKey := (ed25519.PublicKey)(key) if ok := ed25519.Verify(edKey, b, sig.Blob); !ok { return errors.New("ssh: signature did not verify") } return nil } func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey { return ed25519.PublicKey(k) } func supportedEllipticCurve(curve elliptic.Curve) bool { return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521() } // ecHash returns the hash to match the given elliptic curve, see RFC // 5656, section 6.2.1 func ecHash(curve elliptic.Curve) crypto.Hash { bitSize := curve.Params().BitSize switch { case bitSize <= 256: return crypto.SHA256 case bitSize <= 384: return crypto.SHA384 } return crypto.SHA512 } // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { var w struct { Curve string KeyBytes []byte Rest []byte `ssh:"rest"` } if err := Unmarshal(in, &w); err != nil { return nil, nil, err } key := new(ecdsa.PublicKey) switch w.Curve { case "nistp256": key.Curve = elliptic.P256() case "nistp384": key.Curve = elliptic.P384() case "nistp521": key.Curve = elliptic.P521() default: return nil, nil, errors.New("ssh: unsupported curve") } key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes) if key.X == nil || key.Y == nil { return nil, nil, errors.New("ssh: invalid curve point") } return (*ecdsaPublicKey)(key), w.Rest, nil } func (key *ecdsaPublicKey) Marshal() []byte { // See RFC 5656, section 3.1. keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y) // ECDSA publickey struct layout should match the struct used by // parseECDSACert in the x/crypto/ssh/agent package. w := struct { Name string ID string Key []byte }{ key.Type(), key.nistID(), keyBytes, } return Marshal(&w) } func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { if sig.Format != key.Type() { return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type()) } h := ecHash(key.Curve).New() h.Write(data) digest := h.Sum(nil) // Per RFC 5656, section 3.1.2, // The ecdsa_signature_blob value has the following specific encoding: // mpint r // mpint s var ecSig struct { R *big.Int S *big.Int } if err := Unmarshal(sig.Blob, &ecSig); err != nil { return err } if ecdsa.Verify((*ecdsa.PublicKey)(key), digest, ecSig.R, ecSig.S) { return nil } return errors.New("ssh: signature did not verify") } func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey { return (*ecdsa.PublicKey)(k) } // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey, // *ecdsa.PrivateKey or any other crypto.Signer and returns a // corresponding Signer instance. ECDSA keys must use P-256, P-384 or // P-521. DSA keys must use parameter size L1024N160. func NewSignerFromKey(key interface{}) (Signer, error) { switch key := key.(type) { case crypto.Signer: return NewSignerFromSigner(key) case *dsa.PrivateKey: return newDSAPrivateKey(key) default: return nil, fmt.Errorf("ssh: unsupported key type %T", key) } } func newDSAPrivateKey(key *dsa.PrivateKey) (Signer, error) { if err := checkDSAParams(&key.PublicKey.Parameters); err != nil { return nil, err } return &dsaPrivateKey{key}, nil } type wrappedSigner struct { signer crypto.Signer pubKey PublicKey } // NewSignerFromSigner takes any crypto.Signer implementation and // returns a corresponding Signer interface. This can be used, for // example, with keys kept in hardware modules. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) { pubKey, err := NewPublicKey(signer.Public()) if err != nil { return nil, err } return &wrappedSigner{signer, pubKey}, nil } func (s *wrappedSigner) PublicKey() PublicKey { return s.pubKey } func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { var hashFunc crypto.Hash switch key := s.pubKey.(type) { case *rsaPublicKey, *dsaPublicKey: hashFunc = crypto.SHA1 case *ecdsaPublicKey: hashFunc = ecHash(key.Curve) case ed25519PublicKey: default: return nil, fmt.Errorf("ssh: unsupported key type %T", key) } var digest []byte if hashFunc != 0 { h := hashFunc.New() h.Write(data) digest = h.Sum(nil) } else { digest = data } signature, err := s.signer.Sign(rand, digest, hashFunc) if err != nil { return nil, err } // crypto.Signer.Sign is expected to return an ASN.1-encoded signature // for ECDSA and DSA, but that's not the encoding expected by SSH, so // re-encode. switch s.pubKey.(type) { case *ecdsaPublicKey, *dsaPublicKey: type asn1Signature struct { R, S *big.Int } asn1Sig := new(asn1Signature) _, err := asn1.Unmarshal(signature, asn1Sig) if err != nil { return nil, err } switch s.pubKey.(type) { case *ecdsaPublicKey: signature = Marshal(asn1Sig) case *dsaPublicKey: signature = make([]byte, 40) r := asn1Sig.R.Bytes() s := asn1Sig.S.Bytes() copy(signature[20-len(r):20], r) copy(signature[40-len(s):40], s) } } return &Signature{ Format: s.pubKey.Type(), Blob: signature, }, nil } // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, // or ed25519.PublicKey returns a corresponding PublicKey instance. // ECDSA keys must use P-256, P-384 or P-521. func NewPublicKey(key interface{}) (PublicKey, error) { switch key := key.(type) { case *rsa.PublicKey: return (*rsaPublicKey)(key), nil case *ecdsa.PublicKey: if !supportedEllipticCurve(key.Curve) { return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported.") } return (*ecdsaPublicKey)(key), nil case *dsa.PublicKey: return (*dsaPublicKey)(key), nil case ed25519.PublicKey: return (ed25519PublicKey)(key), nil default: return nil, fmt.Errorf("ssh: unsupported key type %T", key) } } // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports // the same keys as ParseRawPrivateKey. func ParsePrivateKey(pemBytes []byte) (Signer, error) { key, err := ParseRawPrivateKey(pemBytes) if err != nil { return nil, err } return NewSignerFromKey(key) } // ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private // key and passphrase. It supports the same keys as // ParseRawPrivateKeyWithPassphrase. func ParsePrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (Signer, error) { key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase) if err != nil { return nil, err } return NewSignerFromKey(key) } // encryptedBlock tells whether a private key is // encrypted by examining its Proc-Type header // for a mention of ENCRYPTED // according to RFC 1421 Section 4.6.1.1. func encryptedBlock(block *pem.Block) bool { return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED") } // ParseRawPrivateKey returns a private key from a PEM encoded private key. It // supports RSA (PKCS#1), DSA (OpenSSL), and ECDSA private keys. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { block, _ := pem.Decode(pemBytes) if block == nil { return nil, errors.New("ssh: no key found") } if encryptedBlock(block) { return nil, errors.New("ssh: cannot decode encrypted private keys") } switch block.Type { case "RSA PRIVATE KEY": return x509.ParsePKCS1PrivateKey(block.Bytes) case "EC PRIVATE KEY": return x509.ParseECPrivateKey(block.Bytes) case "DSA PRIVATE KEY": return ParseDSAPrivateKey(block.Bytes) case "OPENSSH PRIVATE KEY": return parseOpenSSHPrivateKey(block.Bytes) default: return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) } } // ParseRawPrivateKeyWithPassphrase returns a private key decrypted with // passphrase from a PEM encoded private key. If wrong passphrase, return // x509.IncorrectPasswordError. func ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (interface{}, error) { block, _ := pem.Decode(pemBytes) if block == nil { return nil, errors.New("ssh: no key found") } buf := block.Bytes if encryptedBlock(block) { if x509.IsEncryptedPEMBlock(block) { var err error buf, err = x509.DecryptPEMBlock(block, passPhrase) if err != nil { if err == x509.IncorrectPasswordError { return nil, err } return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err) } } } switch block.Type { case "RSA PRIVATE KEY": return x509.ParsePKCS1PrivateKey(buf) case "EC PRIVATE KEY": return x509.ParseECPrivateKey(buf) case "DSA PRIVATE KEY": return ParseDSAPrivateKey(buf) case "OPENSSH PRIVATE KEY": return parseOpenSSHPrivateKey(buf) default: return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) } } // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as // specified by the OpenSSL DSA man page. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) { var k struct { Version int P *big.Int Q *big.Int G *big.Int Pub *big.Int Priv *big.Int } rest, err := asn1.Unmarshal(der, &k) if err != nil { return nil, errors.New("ssh: failed to parse DSA key: " + err.Error()) } if len(rest) > 0 { return nil, errors.New("ssh: garbage after DSA key") } return &dsa.PrivateKey{ PublicKey: dsa.PublicKey{ Parameters: dsa.Parameters{ P: k.P, Q: k.Q, G: k.G, }, Y: k.Pub, }, X: k.Priv, }, nil } // Implemented based on the documentation at // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { magic := append([]byte("openssh-key-v1"), 0) if !bytes.Equal(magic, key[0:len(magic)]) { return nil, errors.New("ssh: invalid openssh private key format") } remaining := key[len(magic):] var w struct { CipherName string KdfName string KdfOpts string NumKeys uint32 PubKey []byte PrivKeyBlock []byte } if err := Unmarshal(remaining, &w); err != nil { return nil, err } if w.KdfName != "none" || w.CipherName != "none" { return nil, errors.New("ssh: cannot decode encrypted private keys") } pk1 := struct { Check1 uint32 Check2 uint32 Keytype string Rest []byte `ssh:"rest"` }{} if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil { return nil, err } if pk1.Check1 != pk1.Check2 { return nil, errors.New("ssh: checkint mismatch") } // we only handle ed25519 and rsa keys currently switch pk1.Keytype { case KeyAlgoRSA: // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773 key := struct { N *big.Int E *big.Int D *big.Int Iqmp *big.Int P *big.Int Q *big.Int Comment string Pad []byte `ssh:"rest"` }{} if err := Unmarshal(pk1.Rest, &key); err != nil { return nil, err } for i, b := range key.Pad { if int(b) != i+1 { return nil, errors.New("ssh: padding not as expected") } } pk := &rsa.PrivateKey{ PublicKey: rsa.PublicKey{ N: key.N, E: int(key.E.Int64()), }, D: key.D, Primes: []*big.Int{key.P, key.Q}, } if err := pk.Validate(); err != nil { return nil, err } pk.Precompute() return pk, nil case KeyAlgoED25519: key := struct { Pub []byte Priv []byte Comment string Pad []byte `ssh:"rest"` }{} if err := Unmarshal(pk1.Rest, &key); err != nil { return nil, err } if len(key.Priv) != ed25519.PrivateKeySize { return nil, errors.New("ssh: private key unexpected length") } for i, b := range key.Pad { if int(b) != i+1 { return nil, errors.New("ssh: padding not as expected") } } pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize)) copy(pk, key.Priv) return &pk, nil default: return nil, errors.New("ssh: unhandled key type") } } // FingerprintLegacyMD5 returns the user presentation of the key's // fingerprint as described by RFC 4716 section 4. func FingerprintLegacyMD5(pubKey PublicKey) string { md5sum := md5.Sum(pubKey.Marshal()) hexarray := make([]string, len(md5sum)) for i, c := range md5sum { hexarray[i] = hex.EncodeToString([]byte{c}) } return strings.Join(hexarray, ":") } // FingerprintSHA256 returns the user presentation of the key's // fingerprint as unpadded base64 encoded sha256 hash. // This format was introduced from OpenSSH 6.8. // https://www.openssh.com/txt/release-6.8 // https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding) func FingerprintSHA256(pubKey PublicKey) string { sha256sum := sha256.Sum256(pubKey.Marshal()) hash := base64.RawStdEncoding.EncodeToString(sha256sum[:]) return "SHA256:" + hash } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/kex_test.go���������������������������������������������0000644�0610621�0607500�00000002062�13172163317�024024� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh // Key exchange tests. import ( "crypto/rand" "reflect" "testing" ) func TestKexes(t *testing.T) { type kexResultErr struct { result *kexResult err error } for name, kex := range kexAlgoMap { a, b := memPipe() s := make(chan kexResultErr, 1) c := make(chan kexResultErr, 1) var magics handshakeMagics go func() { r, e := kex.Client(a, rand.Reader, &magics) a.Close() c <- kexResultErr{r, e} }() go func() { r, e := kex.Server(b, rand.Reader, &magics, testSigners["ecdsa"]) b.Close() s <- kexResultErr{r, e} }() clientRes := <-c serverRes := <-s if clientRes.err != nil { t.Errorf("client: %v", clientRes.err) } if serverRes.err != nil { t.Errorf("server: %v", serverRes.err) } if !reflect.DeepEqual(clientRes.result, serverRes.result) { t.Errorf("kex %q: mismatch %#v, %#v", name, clientRes.result, serverRes.result) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/kex.go��������������������������������������������������0000644�0610621�0607500�00000033423�13172163317�022772� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/subtle" "errors" "io" "math/big" "golang.org/x/crypto/curve25519" ) const ( kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1" kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1" kexAlgoECDH256 = "ecdh-sha2-nistp256" kexAlgoECDH384 = "ecdh-sha2-nistp384" kexAlgoECDH521 = "ecdh-sha2-nistp521" kexAlgoCurve25519SHA256 = "curve25519-sha256@libssh.org" ) // kexResult captures the outcome of a key exchange. type kexResult struct { // Session hash. See also RFC 4253, section 8. H []byte // Shared secret. See also RFC 4253, section 8. K []byte // Host key as hashed into H. HostKey []byte // Signature of H. Signature []byte // A cryptographic hash function that matches the security // level of the key exchange algorithm. It is used for // calculating H, and for deriving keys from H and K. Hash crypto.Hash // The session ID, which is the first H computed. This is used // to derive key material inside the transport. SessionID []byte } // handshakeMagics contains data that is always included in the // session hash. type handshakeMagics struct { clientVersion, serverVersion []byte clientKexInit, serverKexInit []byte } func (m *handshakeMagics) write(w io.Writer) { writeString(w, m.clientVersion) writeString(w, m.serverVersion) writeString(w, m.clientKexInit) writeString(w, m.serverKexInit) } // kexAlgorithm abstracts different key exchange algorithms. type kexAlgorithm interface { // Server runs server-side key agreement, signing the result // with a hostkey. Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error) // Client runs the client-side key agreement. Caller is // responsible for verifying the host key signature. Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) } // dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement. type dhGroup struct { g, p, pMinus1 *big.Int } func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) { if theirPublic.Cmp(bigOne) <= 0 || theirPublic.Cmp(group.pMinus1) >= 0 { return nil, errors.New("ssh: DH parameter out of bounds") } return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil } func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) { hashFunc := crypto.SHA1 var x *big.Int for { var err error if x, err = rand.Int(randSource, group.pMinus1); err != nil { return nil, err } if x.Sign() > 0 { break } } X := new(big.Int).Exp(group.g, x, group.p) kexDHInit := kexDHInitMsg{ X: X, } if err := c.writePacket(Marshal(&kexDHInit)); err != nil { return nil, err } packet, err := c.readPacket() if err != nil { return nil, err } var kexDHReply kexDHReplyMsg if err = Unmarshal(packet, &kexDHReply); err != nil { return nil, err } kInt, err := group.diffieHellman(kexDHReply.Y, x) if err != nil { return nil, err } h := hashFunc.New() magics.write(h) writeString(h, kexDHReply.HostKey) writeInt(h, X) writeInt(h, kexDHReply.Y) K := make([]byte, intLength(kInt)) marshalInt(K, kInt) h.Write(K) return &kexResult{ H: h.Sum(nil), K: K, HostKey: kexDHReply.HostKey, Signature: kexDHReply.Signature, Hash: crypto.SHA1, }, nil } func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { hashFunc := crypto.SHA1 packet, err := c.readPacket() if err != nil { return } var kexDHInit kexDHInitMsg if err = Unmarshal(packet, &kexDHInit); err != nil { return } var y *big.Int for { if y, err = rand.Int(randSource, group.pMinus1); err != nil { return } if y.Sign() > 0 { break } } Y := new(big.Int).Exp(group.g, y, group.p) kInt, err := group.diffieHellman(kexDHInit.X, y) if err != nil { return nil, err } hostKeyBytes := priv.PublicKey().Marshal() h := hashFunc.New() magics.write(h) writeString(h, hostKeyBytes) writeInt(h, kexDHInit.X) writeInt(h, Y) K := make([]byte, intLength(kInt)) marshalInt(K, kInt) h.Write(K) H := h.Sum(nil) // H is already a hash, but the hostkey signing will apply its // own key-specific hash algorithm. sig, err := signAndMarshal(priv, randSource, H) if err != nil { return nil, err } kexDHReply := kexDHReplyMsg{ HostKey: hostKeyBytes, Y: Y, Signature: sig, } packet = Marshal(&kexDHReply) err = c.writePacket(packet) return &kexResult{ H: H, K: K, HostKey: hostKeyBytes, Signature: sig, Hash: crypto.SHA1, }, nil } // ecdh performs Elliptic Curve Diffie-Hellman key exchange as // described in RFC 5656, section 4. type ecdh struct { curve elliptic.Curve } func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { ephKey, err := ecdsa.GenerateKey(kex.curve, rand) if err != nil { return nil, err } kexInit := kexECDHInitMsg{ ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y), } serialized := Marshal(&kexInit) if err := c.writePacket(serialized); err != nil { return nil, err } packet, err := c.readPacket() if err != nil { return nil, err } var reply kexECDHReplyMsg if err = Unmarshal(packet, &reply); err != nil { return nil, err } x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey) if err != nil { return nil, err } // generate shared secret secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes()) h := ecHash(kex.curve).New() magics.write(h) writeString(h, reply.HostKey) writeString(h, kexInit.ClientPubKey) writeString(h, reply.EphemeralPubKey) K := make([]byte, intLength(secret)) marshalInt(K, secret) h.Write(K) return &kexResult{ H: h.Sum(nil), K: K, HostKey: reply.HostKey, Signature: reply.Signature, Hash: ecHash(kex.curve), }, nil } // unmarshalECKey parses and checks an EC key. func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) { x, y = elliptic.Unmarshal(curve, pubkey) if x == nil { return nil, nil, errors.New("ssh: elliptic.Unmarshal failure") } if !validateECPublicKey(curve, x, y) { return nil, nil, errors.New("ssh: public key not on curve") } return x, y, nil } // validateECPublicKey checks that the point is a valid public key for // the given curve. See [SEC1], 3.2.2 func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool { if x.Sign() == 0 && y.Sign() == 0 { return false } if x.Cmp(curve.Params().P) >= 0 { return false } if y.Cmp(curve.Params().P) >= 0 { return false } if !curve.IsOnCurve(x, y) { return false } // We don't check if N * PubKey == 0, since // // - the NIST curves have cofactor = 1, so this is implicit. // (We don't foresee an implementation that supports non NIST // curves) // // - for ephemeral keys, we don't need to worry about small // subgroup attacks. return true } func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { packet, err := c.readPacket() if err != nil { return nil, err } var kexECDHInit kexECDHInitMsg if err = Unmarshal(packet, &kexECDHInit); err != nil { return nil, err } clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey) if err != nil { return nil, err } // We could cache this key across multiple users/multiple // connection attempts, but the benefit is small. OpenSSH // generates a new key for each incoming connection. ephKey, err := ecdsa.GenerateKey(kex.curve, rand) if err != nil { return nil, err } hostKeyBytes := priv.PublicKey().Marshal() serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y) // generate shared secret secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes()) h := ecHash(kex.curve).New() magics.write(h) writeString(h, hostKeyBytes) writeString(h, kexECDHInit.ClientPubKey) writeString(h, serializedEphKey) K := make([]byte, intLength(secret)) marshalInt(K, secret) h.Write(K) H := h.Sum(nil) // H is already a hash, but the hostkey signing will apply its // own key-specific hash algorithm. sig, err := signAndMarshal(priv, rand, H) if err != nil { return nil, err } reply := kexECDHReplyMsg{ EphemeralPubKey: serializedEphKey, HostKey: hostKeyBytes, Signature: sig, } serialized := Marshal(&reply) if err := c.writePacket(serialized); err != nil { return nil, err } return &kexResult{ H: H, K: K, HostKey: reply.HostKey, Signature: sig, Hash: ecHash(kex.curve), }, nil } var kexAlgoMap = map[string]kexAlgorithm{} func init() { // This is the group called diffie-hellman-group1-sha1 in RFC // 4253 and Oakley Group 2 in RFC 2409. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16) kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{ g: new(big.Int).SetInt64(2), p: p, pMinus1: new(big.Int).Sub(p, bigOne), } // This is the group called diffie-hellman-group14-sha1 in RFC // 4253 and Oakley Group 14 in RFC 3526. p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16) kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{ g: new(big.Int).SetInt64(2), p: p, pMinus1: new(big.Int).Sub(p, bigOne), } kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()} kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()} kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()} kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{} } // curve25519sha256 implements the curve25519-sha256@libssh.org key // agreement protocol, as described in // https://git.libssh.org/projects/libssh.git/tree/doc/curve25519-sha256@libssh.org.txt type curve25519sha256 struct{} type curve25519KeyPair struct { priv [32]byte pub [32]byte } func (kp *curve25519KeyPair) generate(rand io.Reader) error { if _, err := io.ReadFull(rand, kp.priv[:]); err != nil { return err } curve25519.ScalarBaseMult(&kp.pub, &kp.priv) return nil } // curve25519Zeros is just an array of 32 zero bytes so that we have something // convenient to compare against in order to reject curve25519 points with the // wrong order. var curve25519Zeros [32]byte func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { var kp curve25519KeyPair if err := kp.generate(rand); err != nil { return nil, err } if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil { return nil, err } packet, err := c.readPacket() if err != nil { return nil, err } var reply kexECDHReplyMsg if err = Unmarshal(packet, &reply); err != nil { return nil, err } if len(reply.EphemeralPubKey) != 32 { return nil, errors.New("ssh: peer's curve25519 public value has wrong length") } var servPub, secret [32]byte copy(servPub[:], reply.EphemeralPubKey) curve25519.ScalarMult(&secret, &kp.priv, &servPub) if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { return nil, errors.New("ssh: peer's curve25519 public value has wrong order") } h := crypto.SHA256.New() magics.write(h) writeString(h, reply.HostKey) writeString(h, kp.pub[:]) writeString(h, reply.EphemeralPubKey) kInt := new(big.Int).SetBytes(secret[:]) K := make([]byte, intLength(kInt)) marshalInt(K, kInt) h.Write(K) return &kexResult{ H: h.Sum(nil), K: K, HostKey: reply.HostKey, Signature: reply.Signature, Hash: crypto.SHA256, }, nil } func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { packet, err := c.readPacket() if err != nil { return } var kexInit kexECDHInitMsg if err = Unmarshal(packet, &kexInit); err != nil { return } if len(kexInit.ClientPubKey) != 32 { return nil, errors.New("ssh: peer's curve25519 public value has wrong length") } var kp curve25519KeyPair if err := kp.generate(rand); err != nil { return nil, err } var clientPub, secret [32]byte copy(clientPub[:], kexInit.ClientPubKey) curve25519.ScalarMult(&secret, &kp.priv, &clientPub) if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { return nil, errors.New("ssh: peer's curve25519 public value has wrong order") } hostKeyBytes := priv.PublicKey().Marshal() h := crypto.SHA256.New() magics.write(h) writeString(h, hostKeyBytes) writeString(h, kexInit.ClientPubKey) writeString(h, kp.pub[:]) kInt := new(big.Int).SetBytes(secret[:]) K := make([]byte, intLength(kInt)) marshalInt(K, kInt) h.Write(K) H := h.Sum(nil) sig, err := signAndMarshal(priv, rand, H) if err != nil { return nil, err } reply := kexECDHReplyMsg{ EphemeralPubKey: kp.pub[:], HostKey: hostKeyBytes, Signature: sig, } if err := c.writePacket(Marshal(&reply)); err != nil { return nil, err } return &kexResult{ H: H, K: K, HostKey: hostKeyBytes, Signature: sig, Hash: crypto.SHA256, }, nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/handshake_test.go���������������������������������������0000644�0610621�0607500�00000031562�13172163317�025172� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "crypto/rand" "errors" "fmt" "io" "net" "reflect" "runtime" "strings" "sync" "testing" ) type testChecker struct { calls []string } func (t *testChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error { if dialAddr == "bad" { return fmt.Errorf("dialAddr is bad") } if tcpAddr, ok := addr.(*net.TCPAddr); !ok || tcpAddr == nil { return fmt.Errorf("testChecker: got %T want *net.TCPAddr", addr) } t.calls = append(t.calls, fmt.Sprintf("%s %v %s %x", dialAddr, addr, key.Type(), key.Marshal())) return nil } // netPipe is analogous to net.Pipe, but it uses a real net.Conn, and // therefore is buffered (net.Pipe deadlocks if both sides start with // a write.) func netPipe() (net.Conn, net.Conn, error) { listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { listener, err = net.Listen("tcp", "[::1]:0") if err != nil { return nil, nil, err } } defer listener.Close() c1, err := net.Dial("tcp", listener.Addr().String()) if err != nil { return nil, nil, err } c2, err := listener.Accept() if err != nil { c1.Close() return nil, nil, err } return c1, c2, nil } // noiseTransport inserts ignore messages to check that the read loop // and the key exchange filters out these messages. type noiseTransport struct { keyingTransport } func (t *noiseTransport) writePacket(p []byte) error { ignore := []byte{msgIgnore} if err := t.keyingTransport.writePacket(ignore); err != nil { return err } debug := []byte{msgDebug, 1, 2, 3} if err := t.keyingTransport.writePacket(debug); err != nil { return err } return t.keyingTransport.writePacket(p) } func addNoiseTransport(t keyingTransport) keyingTransport { return &noiseTransport{t} } // handshakePair creates two handshakeTransports connected with each // other. If the noise argument is true, both transports will try to // confuse the other side by sending ignore and debug messages. func handshakePair(clientConf *ClientConfig, addr string, noise bool) (client *handshakeTransport, server *handshakeTransport, err error) { a, b, err := netPipe() if err != nil { return nil, nil, err } var trC, trS keyingTransport trC = newTransport(a, rand.Reader, true) trS = newTransport(b, rand.Reader, false) if noise { trC = addNoiseTransport(trC) trS = addNoiseTransport(trS) } clientConf.SetDefaults() v := []byte("version") client = newClientTransport(trC, v, v, clientConf, addr, a.RemoteAddr()) serverConf := &ServerConfig{} serverConf.AddHostKey(testSigners["ecdsa"]) serverConf.AddHostKey(testSigners["rsa"]) serverConf.SetDefaults() server = newServerTransport(trS, v, v, serverConf) if err := server.waitSession(); err != nil { return nil, nil, fmt.Errorf("server.waitSession: %v", err) } if err := client.waitSession(); err != nil { return nil, nil, fmt.Errorf("client.waitSession: %v", err) } return client, server, nil } func TestHandshakeBasic(t *testing.T) { if runtime.GOOS == "plan9" { t.Skip("see golang.org/issue/7237") } checker := &syncChecker{ waitCall: make(chan int, 10), called: make(chan int, 10), } checker.waitCall <- 1 trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false) if err != nil { t.Fatalf("handshakePair: %v", err) } defer trC.Close() defer trS.Close() // Let first kex complete normally. <-checker.called clientDone := make(chan int, 0) gotHalf := make(chan int, 0) const N = 20 go func() { defer close(clientDone) // Client writes a bunch of stuff, and does a key // change in the middle. This should not confuse the // handshake in progress. We do this twice, so we test // that the packet buffer is reset correctly. for i := 0; i < N; i++ { p := []byte{msgRequestSuccess, byte(i)} if err := trC.writePacket(p); err != nil { t.Fatalf("sendPacket: %v", err) } if (i % 10) == 5 { <-gotHalf // halfway through, we request a key change. trC.requestKeyExchange() // Wait until we can be sure the key // change has really started before we // write more. <-checker.called } if (i % 10) == 7 { // write some packets until the kex // completes, to test buffering of // packets. checker.waitCall <- 1 } } }() // Server checks that client messages come in cleanly i := 0 err = nil for ; i < N; i++ { var p []byte p, err = trS.readPacket() if err != nil { break } if (i % 10) == 5 { gotHalf <- 1 } want := []byte{msgRequestSuccess, byte(i)} if bytes.Compare(p, want) != 0 { t.Errorf("message %d: got %v, want %v", i, p, want) } } <-clientDone if err != nil && err != io.EOF { t.Fatalf("server error: %v", err) } if i != N { t.Errorf("received %d messages, want 10.", i) } close(checker.called) if _, ok := <-checker.called; ok { // If all went well, we registered exactly 2 key changes: one // that establishes the session, and one that we requested // additionally. t.Fatalf("got another host key checks after 2 handshakes") } } func TestForceFirstKex(t *testing.T) { // like handshakePair, but must access the keyingTransport. checker := &testChecker{} clientConf := &ClientConfig{HostKeyCallback: checker.Check} a, b, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } var trC, trS keyingTransport trC = newTransport(a, rand.Reader, true) // This is the disallowed packet: trC.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})) // Rest of the setup. trS = newTransport(b, rand.Reader, false) clientConf.SetDefaults() v := []byte("version") client := newClientTransport(trC, v, v, clientConf, "addr", a.RemoteAddr()) serverConf := &ServerConfig{} serverConf.AddHostKey(testSigners["ecdsa"]) serverConf.AddHostKey(testSigners["rsa"]) serverConf.SetDefaults() server := newServerTransport(trS, v, v, serverConf) defer client.Close() defer server.Close() // We setup the initial key exchange, but the remote side // tries to send serviceRequestMsg in cleartext, which is // disallowed. if err := server.waitSession(); err == nil { t.Errorf("server first kex init should reject unexpected packet") } } func TestHandshakeAutoRekeyWrite(t *testing.T) { checker := &syncChecker{ called: make(chan int, 10), waitCall: nil, } clientConf := &ClientConfig{HostKeyCallback: checker.Check} clientConf.RekeyThreshold = 500 trC, trS, err := handshakePair(clientConf, "addr", false) if err != nil { t.Fatalf("handshakePair: %v", err) } defer trC.Close() defer trS.Close() input := make([]byte, 251) input[0] = msgRequestSuccess done := make(chan int, 1) const numPacket = 5 go func() { defer close(done) j := 0 for ; j < numPacket; j++ { if p, err := trS.readPacket(); err != nil { break } else if !bytes.Equal(input, p) { t.Errorf("got packet type %d, want %d", p[0], input[0]) } } if j != numPacket { t.Errorf("got %d, want 5 messages", j) } }() <-checker.called for i := 0; i < numPacket; i++ { p := make([]byte, len(input)) copy(p, input) if err := trC.writePacket(p); err != nil { t.Errorf("writePacket: %v", err) } if i == 2 { // Make sure the kex is in progress. <-checker.called } } <-done } type syncChecker struct { waitCall chan int called chan int } func (c *syncChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error { c.called <- 1 if c.waitCall != nil { <-c.waitCall } return nil } func TestHandshakeAutoRekeyRead(t *testing.T) { sync := &syncChecker{ called: make(chan int, 2), waitCall: nil, } clientConf := &ClientConfig{ HostKeyCallback: sync.Check, } clientConf.RekeyThreshold = 500 trC, trS, err := handshakePair(clientConf, "addr", false) if err != nil { t.Fatalf("handshakePair: %v", err) } defer trC.Close() defer trS.Close() packet := make([]byte, 501) packet[0] = msgRequestSuccess if err := trS.writePacket(packet); err != nil { t.Fatalf("writePacket: %v", err) } // While we read out the packet, a key change will be // initiated. done := make(chan int, 1) go func() { defer close(done) if _, err := trC.readPacket(); err != nil { t.Fatalf("readPacket(client): %v", err) } }() <-done <-sync.called } // errorKeyingTransport generates errors after a given number of // read/write operations. type errorKeyingTransport struct { packetConn readLeft, writeLeft int } func (n *errorKeyingTransport) prepareKeyChange(*algorithms, *kexResult) error { return nil } func (n *errorKeyingTransport) getSessionID() []byte { return nil } func (n *errorKeyingTransport) writePacket(packet []byte) error { if n.writeLeft == 0 { n.Close() return errors.New("barf") } n.writeLeft-- return n.packetConn.writePacket(packet) } func (n *errorKeyingTransport) readPacket() ([]byte, error) { if n.readLeft == 0 { n.Close() return nil, errors.New("barf") } n.readLeft-- return n.packetConn.readPacket() } func TestHandshakeErrorHandlingRead(t *testing.T) { for i := 0; i < 20; i++ { testHandshakeErrorHandlingN(t, i, -1, false) } } func TestHandshakeErrorHandlingWrite(t *testing.T) { for i := 0; i < 20; i++ { testHandshakeErrorHandlingN(t, -1, i, false) } } func TestHandshakeErrorHandlingReadCoupled(t *testing.T) { for i := 0; i < 20; i++ { testHandshakeErrorHandlingN(t, i, -1, true) } } func TestHandshakeErrorHandlingWriteCoupled(t *testing.T) { for i := 0; i < 20; i++ { testHandshakeErrorHandlingN(t, -1, i, true) } } // testHandshakeErrorHandlingN runs handshakes, injecting errors. If // handshakeTransport deadlocks, the go runtime will detect it and // panic. func testHandshakeErrorHandlingN(t *testing.T, readLimit, writeLimit int, coupled bool) { msg := Marshal(&serviceRequestMsg{strings.Repeat("x", int(minRekeyThreshold)/4)}) a, b := memPipe() defer a.Close() defer b.Close() key := testSigners["ecdsa"] serverConf := Config{RekeyThreshold: minRekeyThreshold} serverConf.SetDefaults() serverConn := newHandshakeTransport(&errorKeyingTransport{a, readLimit, writeLimit}, &serverConf, []byte{'a'}, []byte{'b'}) serverConn.hostKeys = []Signer{key} go serverConn.readLoop() go serverConn.kexLoop() clientConf := Config{RekeyThreshold: 10 * minRekeyThreshold} clientConf.SetDefaults() clientConn := newHandshakeTransport(&errorKeyingTransport{b, -1, -1}, &clientConf, []byte{'a'}, []byte{'b'}) clientConn.hostKeyAlgorithms = []string{key.PublicKey().Type()} clientConn.hostKeyCallback = InsecureIgnoreHostKey() go clientConn.readLoop() go clientConn.kexLoop() var wg sync.WaitGroup for _, hs := range []packetConn{serverConn, clientConn} { if !coupled { wg.Add(2) go func(c packetConn) { for i := 0; ; i++ { str := fmt.Sprintf("%08x", i) + strings.Repeat("x", int(minRekeyThreshold)/4-8) err := c.writePacket(Marshal(&serviceRequestMsg{str})) if err != nil { break } } wg.Done() c.Close() }(hs) go func(c packetConn) { for { _, err := c.readPacket() if err != nil { break } } wg.Done() }(hs) } else { wg.Add(1) go func(c packetConn) { for { _, err := c.readPacket() if err != nil { break } if err := c.writePacket(msg); err != nil { break } } wg.Done() }(hs) } } wg.Wait() } func TestDisconnect(t *testing.T) { if runtime.GOOS == "plan9" { t.Skip("see golang.org/issue/7237") } checker := &testChecker{} trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false) if err != nil { t.Fatalf("handshakePair: %v", err) } defer trC.Close() defer trS.Close() trC.writePacket([]byte{msgRequestSuccess, 0, 0}) errMsg := &disconnectMsg{ Reason: 42, Message: "such is life", } trC.writePacket(Marshal(errMsg)) trC.writePacket([]byte{msgRequestSuccess, 0, 0}) packet, err := trS.readPacket() if err != nil { t.Fatalf("readPacket 1: %v", err) } if packet[0] != msgRequestSuccess { t.Errorf("got packet %v, want packet type %d", packet, msgRequestSuccess) } _, err = trS.readPacket() if err == nil { t.Errorf("readPacket 2 succeeded") } else if !reflect.DeepEqual(err, errMsg) { t.Errorf("got error %#v, want %#v", err, errMsg) } _, err = trS.readPacket() if err == nil { t.Errorf("readPacket 3 succeeded") } } func TestHandshakeRekeyDefault(t *testing.T) { clientConf := &ClientConfig{ Config: Config{ Ciphers: []string{"aes128-ctr"}, }, HostKeyCallback: InsecureIgnoreHostKey(), } trC, trS, err := handshakePair(clientConf, "addr", false) if err != nil { t.Fatalf("handshakePair: %v", err) } defer trC.Close() defer trS.Close() trC.writePacket([]byte{msgRequestSuccess, 0, 0}) trC.Close() rgb := (1024 + trC.readBytesLeft) >> 30 wgb := (1024 + trC.writeBytesLeft) >> 30 if rgb != 64 { t.Errorf("got rekey after %dG read, want 64G", rgb) } if wgb != 64 { t.Errorf("got rekey after %dG write, want 64G", wgb) } } ����������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/handshake.go��������������������������������������������0000644�0610621�0607500�00000037075�13172163317�024140� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "crypto/rand" "errors" "fmt" "io" "log" "net" "sync" ) // debugHandshake, if set, prints messages sent and received. Key // exchange messages are printed as if DH were used, so the debug // messages are wrong when using ECDH. const debugHandshake = false // chanSize sets the amount of buffering SSH connections. This is // primarily for testing: setting chanSize=0 uncovers deadlocks more // quickly. const chanSize = 16 // keyingTransport is a packet based transport that supports key // changes. It need not be thread-safe. It should pass through // msgNewKeys in both directions. type keyingTransport interface { packetConn // prepareKeyChange sets up a key change. The key change for a // direction will be effected if a msgNewKeys message is sent // or received. prepareKeyChange(*algorithms, *kexResult) error } // handshakeTransport implements rekeying on top of a keyingTransport // and offers a thread-safe writePacket() interface. type handshakeTransport struct { conn keyingTransport config *Config serverVersion []byte clientVersion []byte // hostKeys is non-empty if we are the server. In that case, // it contains all host keys that can be used to sign the // connection. hostKeys []Signer // hostKeyAlgorithms is non-empty if we are the client. In that case, // we accept these key types from the server as host key. hostKeyAlgorithms []string // On read error, incoming is closed, and readError is set. incoming chan []byte readError error mu sync.Mutex writeError error sentInitPacket []byte sentInitMsg *kexInitMsg pendingPackets [][]byte // Used when a key exchange is in progress. // If the read loop wants to schedule a kex, it pings this // channel, and the write loop will send out a kex // message. requestKex chan struct{} // If the other side requests or confirms a kex, its kexInit // packet is sent here for the write loop to find it. startKex chan *pendingKex // data for host key checking hostKeyCallback HostKeyCallback dialAddress string remoteAddr net.Addr // bannerCallback is non-empty if we are the client and it has been set in // ClientConfig. In that case it is called during the user authentication // dance to handle a custom server's message. bannerCallback BannerCallback // Algorithms agreed in the last key exchange. algorithms *algorithms readPacketsLeft uint32 readBytesLeft int64 writePacketsLeft uint32 writeBytesLeft int64 // The session ID or nil if first kex did not complete yet. sessionID []byte } type pendingKex struct { otherInit []byte done chan error } func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport { t := &handshakeTransport{ conn: conn, serverVersion: serverVersion, clientVersion: clientVersion, incoming: make(chan []byte, chanSize), requestKex: make(chan struct{}, 1), startKex: make(chan *pendingKex, 1), config: config, } t.resetReadThresholds() t.resetWriteThresholds() // We always start with a mandatory key exchange. t.requestKex <- struct{}{} return t } func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport { t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) t.dialAddress = dialAddr t.remoteAddr = addr t.hostKeyCallback = config.HostKeyCallback t.bannerCallback = config.BannerCallback if config.HostKeyAlgorithms != nil { t.hostKeyAlgorithms = config.HostKeyAlgorithms } else { t.hostKeyAlgorithms = supportedHostKeyAlgos } go t.readLoop() go t.kexLoop() return t } func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport { t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) t.hostKeys = config.hostKeys go t.readLoop() go t.kexLoop() return t } func (t *handshakeTransport) getSessionID() []byte { return t.sessionID } // waitSession waits for the session to be established. This should be // the first thing to call after instantiating handshakeTransport. func (t *handshakeTransport) waitSession() error { p, err := t.readPacket() if err != nil { return err } if p[0] != msgNewKeys { return fmt.Errorf("ssh: first packet should be msgNewKeys") } return nil } func (t *handshakeTransport) id() string { if len(t.hostKeys) > 0 { return "server" } return "client" } func (t *handshakeTransport) printPacket(p []byte, write bool) { action := "got" if write { action = "sent" } if p[0] == msgChannelData || p[0] == msgChannelExtendedData { log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p)) } else { msg, err := decode(p) log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err) } } func (t *handshakeTransport) readPacket() ([]byte, error) { p, ok := <-t.incoming if !ok { return nil, t.readError } return p, nil } func (t *handshakeTransport) readLoop() { first := true for { p, err := t.readOnePacket(first) first = false if err != nil { t.readError = err close(t.incoming) break } if p[0] == msgIgnore || p[0] == msgDebug { continue } t.incoming <- p } // Stop writers too. t.recordWriteError(t.readError) // Unblock the writer should it wait for this. close(t.startKex) // Don't close t.requestKex; it's also written to from writePacket. } func (t *handshakeTransport) pushPacket(p []byte) error { if debugHandshake { t.printPacket(p, true) } return t.conn.writePacket(p) } func (t *handshakeTransport) getWriteError() error { t.mu.Lock() defer t.mu.Unlock() return t.writeError } func (t *handshakeTransport) recordWriteError(err error) { t.mu.Lock() defer t.mu.Unlock() if t.writeError == nil && err != nil { t.writeError = err } } func (t *handshakeTransport) requestKeyExchange() { select { case t.requestKex <- struct{}{}: default: // something already requested a kex, so do nothing. } } func (t *handshakeTransport) resetWriteThresholds() { t.writePacketsLeft = packetRekeyThreshold if t.config.RekeyThreshold > 0 { t.writeBytesLeft = int64(t.config.RekeyThreshold) } else if t.algorithms != nil { t.writeBytesLeft = t.algorithms.w.rekeyBytes() } else { t.writeBytesLeft = 1 << 30 } } func (t *handshakeTransport) kexLoop() { write: for t.getWriteError() == nil { var request *pendingKex var sent bool for request == nil || !sent { var ok bool select { case request, ok = <-t.startKex: if !ok { break write } case <-t.requestKex: break } if !sent { if err := t.sendKexInit(); err != nil { t.recordWriteError(err) break } sent = true } } if err := t.getWriteError(); err != nil { if request != nil { request.done <- err } break } // We're not servicing t.requestKex, but that is OK: // we never block on sending to t.requestKex. // We're not servicing t.startKex, but the remote end // has just sent us a kexInitMsg, so it can't send // another key change request, until we close the done // channel on the pendingKex request. err := t.enterKeyExchange(request.otherInit) t.mu.Lock() t.writeError = err t.sentInitPacket = nil t.sentInitMsg = nil t.resetWriteThresholds() // we have completed the key exchange. Since the // reader is still blocked, it is safe to clear out // the requestKex channel. This avoids the situation // where: 1) we consumed our own request for the // initial kex, and 2) the kex from the remote side // caused another send on the requestKex channel, clear: for { select { case <-t.requestKex: // default: break clear } } request.done <- t.writeError // kex finished. Push packets that we received while // the kex was in progress. Don't look at t.startKex // and don't increment writtenSinceKex: if we trigger // another kex while we are still busy with the last // one, things will become very confusing. for _, p := range t.pendingPackets { t.writeError = t.pushPacket(p) if t.writeError != nil { break } } t.pendingPackets = t.pendingPackets[:0] t.mu.Unlock() } // drain startKex channel. We don't service t.requestKex // because nobody does blocking sends there. go func() { for init := range t.startKex { init.done <- t.writeError } }() // Unblock reader. t.conn.Close() } // The protocol uses uint32 for packet counters, so we can't let them // reach 1<<32. We will actually read and write more packets than // this, though: the other side may send more packets, and after we // hit this limit on writing we will send a few more packets for the // key exchange itself. const packetRekeyThreshold = (1 << 31) func (t *handshakeTransport) resetReadThresholds() { t.readPacketsLeft = packetRekeyThreshold if t.config.RekeyThreshold > 0 { t.readBytesLeft = int64(t.config.RekeyThreshold) } else if t.algorithms != nil { t.readBytesLeft = t.algorithms.r.rekeyBytes() } else { t.readBytesLeft = 1 << 30 } } func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) { p, err := t.conn.readPacket() if err != nil { return nil, err } if t.readPacketsLeft > 0 { t.readPacketsLeft-- } else { t.requestKeyExchange() } if t.readBytesLeft > 0 { t.readBytesLeft -= int64(len(p)) } else { t.requestKeyExchange() } if debugHandshake { t.printPacket(p, false) } if first && p[0] != msgKexInit { return nil, fmt.Errorf("ssh: first packet should be msgKexInit") } if p[0] != msgKexInit { return p, nil } firstKex := t.sessionID == nil kex := pendingKex{ done: make(chan error, 1), otherInit: p, } t.startKex <- &kex err = <-kex.done if debugHandshake { log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err) } if err != nil { return nil, err } t.resetReadThresholds() // By default, a key exchange is hidden from higher layers by // translating it into msgIgnore. successPacket := []byte{msgIgnore} if firstKex { // sendKexInit() for the first kex waits for // msgNewKeys so the authentication process is // guaranteed to happen over an encrypted transport. successPacket = []byte{msgNewKeys} } return successPacket, nil } // sendKexInit sends a key change message. func (t *handshakeTransport) sendKexInit() error { t.mu.Lock() defer t.mu.Unlock() if t.sentInitMsg != nil { // kexInits may be sent either in response to the other side, // or because our side wants to initiate a key change, so we // may have already sent a kexInit. In that case, don't send a // second kexInit. return nil } msg := &kexInitMsg{ KexAlgos: t.config.KeyExchanges, CiphersClientServer: t.config.Ciphers, CiphersServerClient: t.config.Ciphers, MACsClientServer: t.config.MACs, MACsServerClient: t.config.MACs, CompressionClientServer: supportedCompressions, CompressionServerClient: supportedCompressions, } io.ReadFull(rand.Reader, msg.Cookie[:]) if len(t.hostKeys) > 0 { for _, k := range t.hostKeys { msg.ServerHostKeyAlgos = append( msg.ServerHostKeyAlgos, k.PublicKey().Type()) } } else { msg.ServerHostKeyAlgos = t.hostKeyAlgorithms } packet := Marshal(msg) // writePacket destroys the contents, so save a copy. packetCopy := make([]byte, len(packet)) copy(packetCopy, packet) if err := t.pushPacket(packetCopy); err != nil { return err } t.sentInitMsg = msg t.sentInitPacket = packet return nil } func (t *handshakeTransport) writePacket(p []byte) error { switch p[0] { case msgKexInit: return errors.New("ssh: only handshakeTransport can send kexInit") case msgNewKeys: return errors.New("ssh: only handshakeTransport can send newKeys") } t.mu.Lock() defer t.mu.Unlock() if t.writeError != nil { return t.writeError } if t.sentInitMsg != nil { // Copy the packet so the writer can reuse the buffer. cp := make([]byte, len(p)) copy(cp, p) t.pendingPackets = append(t.pendingPackets, cp) return nil } if t.writeBytesLeft > 0 { t.writeBytesLeft -= int64(len(p)) } else { t.requestKeyExchange() } if t.writePacketsLeft > 0 { t.writePacketsLeft-- } else { t.requestKeyExchange() } if err := t.pushPacket(p); err != nil { t.writeError = err } return nil } func (t *handshakeTransport) Close() error { return t.conn.Close() } func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error { if debugHandshake { log.Printf("%s entered key exchange", t.id()) } otherInit := &kexInitMsg{} if err := Unmarshal(otherInitPacket, otherInit); err != nil { return err } magics := handshakeMagics{ clientVersion: t.clientVersion, serverVersion: t.serverVersion, clientKexInit: otherInitPacket, serverKexInit: t.sentInitPacket, } clientInit := otherInit serverInit := t.sentInitMsg if len(t.hostKeys) == 0 { clientInit, serverInit = serverInit, clientInit magics.clientKexInit = t.sentInitPacket magics.serverKexInit = otherInitPacket } var err error t.algorithms, err = findAgreedAlgorithms(clientInit, serverInit) if err != nil { return err } // We don't send FirstKexFollows, but we handle receiving it. // // RFC 4253 section 7 defines the kex and the agreement method for // first_kex_packet_follows. It states that the guessed packet // should be ignored if the "kex algorithm and/or the host // key algorithm is guessed wrong (server and client have // different preferred algorithm), or if any of the other // algorithms cannot be agreed upon". The other algorithms have // already been checked above so the kex algorithm and host key // algorithm are checked here. if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) { // other side sent a kex message for the wrong algorithm, // which we have to ignore. if _, err := t.conn.readPacket(); err != nil { return err } } kex, ok := kexAlgoMap[t.algorithms.kex] if !ok { return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex) } var result *kexResult if len(t.hostKeys) > 0 { result, err = t.server(kex, t.algorithms, &magics) } else { result, err = t.client(kex, t.algorithms, &magics) } if err != nil { return err } if t.sessionID == nil { t.sessionID = result.H } result.SessionID = t.sessionID if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil { return err } if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil { return err } if packet, err := t.conn.readPacket(); err != nil { return err } else if packet[0] != msgNewKeys { return unexpectedMessageError(msgNewKeys, packet[0]) } return nil } func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) { var hostKey Signer for _, k := range t.hostKeys { if algs.hostKey == k.PublicKey().Type() { hostKey = k } } r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey) return r, err } func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) { result, err := kex.Client(t.conn, t.config.Rand, magics) if err != nil { return nil, err } hostKey, err := ParsePublicKey(result.HostKey) if err != nil { return nil, err } if err := verifyHostKeySignature(hostKey, result); err != nil { return nil, err } err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey) if err != nil { return nil, err } return result, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/example_test.go�����������������������������������������0000644�0610621�0607500�00000020746�13172163317�024701� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh_test import ( "bufio" "bytes" "fmt" "io/ioutil" "log" "net" "net/http" "os" "path/filepath" "strings" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/terminal" ) func ExampleNewServerConn() { // Public key authentication is done by comparing // the public key of a received connection // with the entries in the authorized_keys file. authorizedKeysBytes, err := ioutil.ReadFile("authorized_keys") if err != nil { log.Fatalf("Failed to load authorized_keys, err: %v", err) } authorizedKeysMap := map[string]bool{} for len(authorizedKeysBytes) > 0 { pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes) if err != nil { log.Fatal(err) } authorizedKeysMap[string(pubKey.Marshal())] = true authorizedKeysBytes = rest } // An SSH server is represented by a ServerConfig, which holds // certificate details and handles authentication of ServerConns. config := &ssh.ServerConfig{ // Remove to disable password auth. PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { // Should use constant-time compare (or better, salt+hash) in // a production setting. if c.User() == "testuser" && string(pass) == "tiger" { return nil, nil } return nil, fmt.Errorf("password rejected for %q", c.User()) }, // Remove to disable public key auth. PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) { if authorizedKeysMap[string(pubKey.Marshal())] { return &ssh.Permissions{ // Record the public key used for authentication. Extensions: map[string]string{ "pubkey-fp": ssh.FingerprintSHA256(pubKey), }, }, nil } return nil, fmt.Errorf("unknown public key for %q", c.User()) }, } privateBytes, err := ioutil.ReadFile("id_rsa") if err != nil { log.Fatal("Failed to load private key: ", err) } private, err := ssh.ParsePrivateKey(privateBytes) if err != nil { log.Fatal("Failed to parse private key: ", err) } config.AddHostKey(private) // Once a ServerConfig has been configured, connections can be // accepted. listener, err := net.Listen("tcp", "0.0.0.0:2022") if err != nil { log.Fatal("failed to listen for connection: ", err) } nConn, err := listener.Accept() if err != nil { log.Fatal("failed to accept incoming connection: ", err) } // Before use, a handshake must be performed on the incoming // net.Conn. conn, chans, reqs, err := ssh.NewServerConn(nConn, config) if err != nil { log.Fatal("failed to handshake: ", err) } log.Printf("logged in with key %s", conn.Permissions.Extensions["pubkey-fp"]) // The incoming Request channel must be serviced. go ssh.DiscardRequests(reqs) // Service the incoming Channel channel. for newChannel := range chans { // Channels have a type, depending on the application level // protocol intended. In the case of a shell, the type is // "session" and ServerShell may be used to present a simple // terminal interface. if newChannel.ChannelType() != "session" { newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") continue } channel, requests, err := newChannel.Accept() if err != nil { log.Fatalf("Could not accept channel: %v", err) } // Sessions have out-of-band requests such as "shell", // "pty-req" and "env". Here we handle only the // "shell" request. go func(in <-chan *ssh.Request) { for req := range in { req.Reply(req.Type == "shell", nil) } }(requests) term := terminal.NewTerminal(channel, "> ") go func() { defer channel.Close() for { line, err := term.ReadLine() if err != nil { break } fmt.Println(line) } }() } } func ExampleHostKeyCheck() { // Every client must provide a host key check. Here is a // simple-minded parse of OpenSSH's known_hosts file host := "hostname" file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) var hostKey ssh.PublicKey for scanner.Scan() { fields := strings.Split(scanner.Text(), " ") if len(fields) != 3 { continue } if strings.Contains(fields[0], host) { var err error hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes()) if err != nil { log.Fatalf("error parsing %q: %v", fields[2], err) } break } } if hostKey == nil { log.Fatalf("no hostkey for %s", host) } config := ssh.ClientConfig{ User: os.Getenv("USER"), HostKeyCallback: ssh.FixedHostKey(hostKey), } _, err = ssh.Dial("tcp", host+":22", &config) log.Println(err) } func ExampleDial() { var hostKey ssh.PublicKey // An SSH client is represented with a ClientConn. // // To authenticate with the remote server you must pass at least one // implementation of AuthMethod via the Auth field in ClientConfig, // and provide a HostKeyCallback. config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ssh.Password("yourpassword"), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } client, err := ssh.Dial("tcp", "yourserver.com:22", config) if err != nil { log.Fatal("Failed to dial: ", err) } // Each ClientConn can support multiple interactive sessions, // represented by a Session. session, err := client.NewSession() if err != nil { log.Fatal("Failed to create session: ", err) } defer session.Close() // Once a Session is created, you can execute a single command on // the remote side using the Run method. var b bytes.Buffer session.Stdout = &b if err := session.Run("/usr/bin/whoami"); err != nil { log.Fatal("Failed to run: " + err.Error()) } fmt.Println(b.String()) } func ExamplePublicKeys() { var hostKey ssh.PublicKey // A public key may be used to authenticate against the remote // server by using an unencrypted PEM-encoded private key file. // // If you have an encrypted private key, the crypto/x509 package // can be used to decrypt it. key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa") if err != nil { log.Fatalf("unable to read private key: %v", err) } // Create the Signer for this private key. signer, err := ssh.ParsePrivateKey(key) if err != nil { log.Fatalf("unable to parse private key: %v", err) } config := &ssh.ClientConfig{ User: "user", Auth: []ssh.AuthMethod{ // Use the PublicKeys method for remote authentication. ssh.PublicKeys(signer), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } // Connect to the remote server and perform the SSH handshake. client, err := ssh.Dial("tcp", "host.com:22", config) if err != nil { log.Fatalf("unable to connect: %v", err) } defer client.Close() } func ExampleClient_Listen() { var hostKey ssh.PublicKey config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ssh.Password("password"), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } // Dial your ssh server. conn, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatal("unable to connect: ", err) } defer conn.Close() // Request the remote side to open port 8080 on all interfaces. l, err := conn.Listen("tcp", "0.0.0.0:8080") if err != nil { log.Fatal("unable to register tcp forward: ", err) } defer l.Close() // Serve HTTP with your SSH server acting as a reverse proxy. http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { fmt.Fprintf(resp, "Hello world!\n") })) } func ExampleSession_RequestPty() { var hostKey ssh.PublicKey // Create client config config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ssh.Password("password"), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } // Connect to ssh server conn, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatal("unable to connect: ", err) } defer conn.Close() // Create a session session, err := conn.NewSession() if err != nil { log.Fatal("unable to create session: ", err) } defer session.Close() // Set up terminal modes modes := ssh.TerminalModes{ ssh.ECHO: 0, // disable echoing ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud } // Request pseudo terminal if err := session.RequestPty("xterm", 40, 80, modes); err != nil { log.Fatal("request for pseudo terminal failed: ", err) } // Start remote shell if err := session.Shell(); err != nil { log.Fatal("failed to start shell: ", err) } } ��������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/doc.go��������������������������������������������������0000644�0610621�0607500�00000001627�13172163317�022751� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package ssh implements an SSH client and server. SSH is a transport security protocol, an authentication protocol and a family of application protocols. The most typical application level protocol is a remote shell and this is specifically implemented. However, the multiplexed nature of SSH is exposed to users that wish to support others. References: [PROTOCOL.certkeys]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?rev=HEAD [SSH-PARAMETERS]: http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1 This package does not fall under the stability promise of the Go language itself, so its API may be changed when pressing needs arise. */ package ssh // import "golang.org/x/crypto/ssh" ���������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/connection.go�������������������������������������������0000644�0610621�0607500�00000006524�13172163317�024344� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "fmt" "net" ) // OpenChannelError is returned if the other side rejects an // OpenChannel request. type OpenChannelError struct { Reason RejectionReason Message string } func (e *OpenChannelError) Error() string { return fmt.Sprintf("ssh: rejected: %s (%s)", e.Reason, e.Message) } // ConnMetadata holds metadata for the connection. type ConnMetadata interface { // User returns the user ID for this connection. User() string // SessionID returns the session hash, also denoted by H. SessionID() []byte // ClientVersion returns the client's version string as hashed // into the session ID. ClientVersion() []byte // ServerVersion returns the server's version string as hashed // into the session ID. ServerVersion() []byte // RemoteAddr returns the remote address for this connection. RemoteAddr() net.Addr // LocalAddr returns the local address for this connection. LocalAddr() net.Addr } // Conn represents an SSH connection for both server and client roles. // Conn is the basis for implementing an application layer, such // as ClientConn, which implements the traditional shell access for // clients. type Conn interface { ConnMetadata // SendRequest sends a global request, and returns the // reply. If wantReply is true, it returns the response status // and payload. See also RFC4254, section 4. SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) // OpenChannel tries to open an channel. If the request is // rejected, it returns *OpenChannelError. On success it returns // the SSH Channel and a Go channel for incoming, out-of-band // requests. The Go channel must be serviced, or the // connection will hang. OpenChannel(name string, data []byte) (Channel, <-chan *Request, error) // Close closes the underlying network connection Close() error // Wait blocks until the connection has shut down, and returns the // error causing the shutdown. Wait() error // TODO(hanwen): consider exposing: // RequestKeyChange // Disconnect } // DiscardRequests consumes and rejects all requests from the // passed-in channel. func DiscardRequests(in <-chan *Request) { for req := range in { if req.WantReply { req.Reply(false, nil) } } } // A connection represents an incoming connection. type connection struct { transport *handshakeTransport sshConn // The connection protocol. *mux } func (c *connection) Close() error { return c.sshConn.conn.Close() } // sshconn provides net.Conn metadata, but disallows direct reads and // writes. type sshConn struct { conn net.Conn user string sessionID []byte clientVersion []byte serverVersion []byte } func dup(src []byte) []byte { dst := make([]byte, len(src)) copy(dst, src) return dst } func (c *sshConn) User() string { return c.user } func (c *sshConn) RemoteAddr() net.Addr { return c.conn.RemoteAddr() } func (c *sshConn) Close() error { return c.conn.Close() } func (c *sshConn) LocalAddr() net.Addr { return c.conn.LocalAddr() } func (c *sshConn) SessionID() []byte { return dup(c.sessionID) } func (c *sshConn) ClientVersion() []byte { return dup(c.clientVersion) } func (c *sshConn) ServerVersion() []byte { return dup(c.serverVersion) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/common.go�����������������������������������������������0000644�0610621�0607500�00000023314�13172163317�023471� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "crypto" "crypto/rand" "fmt" "io" "math" "sync" _ "crypto/sha1" _ "crypto/sha256" _ "crypto/sha512" ) // These are string constants in the SSH protocol. const ( compressionNone = "none" serviceUserAuth = "ssh-userauth" serviceSSH = "ssh-connection" ) // supportedCiphers specifies the supported ciphers in preference order. var supportedCiphers = []string{ "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128", } // supportedKexAlgos specifies the supported key-exchange algorithms in // preference order. var supportedKexAlgos = []string{ kexAlgoCurve25519SHA256, // P384 and P521 are not constant-time yet, but since we don't // reuse ephemeral keys, using them for ECDH should be OK. kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521, kexAlgoDH14SHA1, kexAlgoDH1SHA1, } // supportedHostKeyAlgos specifies the supported host-key algorithms (i.e. methods // of authenticating servers) in preference order. var supportedHostKeyAlgos = []string{ CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoRSA, KeyAlgoDSA, KeyAlgoED25519, } // supportedMACs specifies a default set of MAC algorithms in preference order. // This is based on RFC 4253, section 6.4, but with hmac-md5 variants removed // because they have reached the end of their useful life. var supportedMACs = []string{ "hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96", } var supportedCompressions = []string{compressionNone} // hashFuncs keeps the mapping of supported algorithms to their respective // hashes needed for signature verification. var hashFuncs = map[string]crypto.Hash{ KeyAlgoRSA: crypto.SHA1, KeyAlgoDSA: crypto.SHA1, KeyAlgoECDSA256: crypto.SHA256, KeyAlgoECDSA384: crypto.SHA384, KeyAlgoECDSA521: crypto.SHA512, CertAlgoRSAv01: crypto.SHA1, CertAlgoDSAv01: crypto.SHA1, CertAlgoECDSA256v01: crypto.SHA256, CertAlgoECDSA384v01: crypto.SHA384, CertAlgoECDSA521v01: crypto.SHA512, } // unexpectedMessageError results when the SSH message that we received didn't // match what we wanted. func unexpectedMessageError(expected, got uint8) error { return fmt.Errorf("ssh: unexpected message type %d (expected %d)", got, expected) } // parseError results from a malformed SSH message. func parseError(tag uint8) error { return fmt.Errorf("ssh: parse error in message type %d", tag) } func findCommon(what string, client []string, server []string) (common string, err error) { for _, c := range client { for _, s := range server { if c == s { return c, nil } } } return "", fmt.Errorf("ssh: no common algorithm for %s; client offered: %v, server offered: %v", what, client, server) } type directionAlgorithms struct { Cipher string MAC string Compression string } // rekeyBytes returns a rekeying intervals in bytes. func (a *directionAlgorithms) rekeyBytes() int64 { // According to RFC4344 block ciphers should rekey after // 2^(BLOCKSIZE/4) blocks. For all AES flavors BLOCKSIZE is // 128. switch a.Cipher { case "aes128-ctr", "aes192-ctr", "aes256-ctr", gcmCipherID, aes128cbcID: return 16 * (1 << 32) } // For others, stick with RFC4253 recommendation to rekey after 1 Gb of data. return 1 << 30 } type algorithms struct { kex string hostKey string w directionAlgorithms r directionAlgorithms } func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms, err error) { result := &algorithms{} result.kex, err = findCommon("key exchange", clientKexInit.KexAlgos, serverKexInit.KexAlgos) if err != nil { return } result.hostKey, err = findCommon("host key", clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos) if err != nil { return } result.w.Cipher, err = findCommon("client to server cipher", clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer) if err != nil { return } result.r.Cipher, err = findCommon("server to client cipher", clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient) if err != nil { return } result.w.MAC, err = findCommon("client to server MAC", clientKexInit.MACsClientServer, serverKexInit.MACsClientServer) if err != nil { return } result.r.MAC, err = findCommon("server to client MAC", clientKexInit.MACsServerClient, serverKexInit.MACsServerClient) if err != nil { return } result.w.Compression, err = findCommon("client to server compression", clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer) if err != nil { return } result.r.Compression, err = findCommon("server to client compression", clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient) if err != nil { return } return result, nil } // If rekeythreshold is too small, we can't make any progress sending // stuff. const minRekeyThreshold uint64 = 256 // Config contains configuration data common to both ServerConfig and // ClientConfig. type Config struct { // Rand provides the source of entropy for cryptographic // primitives. If Rand is nil, the cryptographic random reader // in package crypto/rand will be used. Rand io.Reader // The maximum number of bytes sent or received after which a // new key is negotiated. It must be at least 256. If // unspecified, a size suitable for the chosen cipher is used. RekeyThreshold uint64 // The allowed key exchanges algorithms. If unspecified then a // default set of algorithms is used. KeyExchanges []string // The allowed cipher algorithms. If unspecified then a sensible // default is used. Ciphers []string // The allowed MAC algorithms. If unspecified then a sensible default // is used. MACs []string } // SetDefaults sets sensible values for unset fields in config. This is // exported for testing: Configs passed to SSH functions are copied and have // default values set automatically. func (c *Config) SetDefaults() { if c.Rand == nil { c.Rand = rand.Reader } if c.Ciphers == nil { c.Ciphers = supportedCiphers } var ciphers []string for _, c := range c.Ciphers { if cipherModes[c] != nil { // reject the cipher if we have no cipherModes definition ciphers = append(ciphers, c) } } c.Ciphers = ciphers if c.KeyExchanges == nil { c.KeyExchanges = supportedKexAlgos } if c.MACs == nil { c.MACs = supportedMACs } if c.RekeyThreshold == 0 { // cipher specific default } else if c.RekeyThreshold < minRekeyThreshold { c.RekeyThreshold = minRekeyThreshold } else if c.RekeyThreshold >= math.MaxInt64 { // Avoid weirdness if somebody uses -1 as a threshold. c.RekeyThreshold = math.MaxInt64 } } // buildDataSignedForAuth returns the data that is signed in order to prove // possession of a private key. See RFC 4252, section 7. func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte { data := struct { Session []byte Type byte User string Service string Method string Sign bool Algo []byte PubKey []byte }{ sessionId, msgUserAuthRequest, req.User, req.Service, req.Method, true, algo, pubKey, } return Marshal(data) } func appendU16(buf []byte, n uint16) []byte { return append(buf, byte(n>>8), byte(n)) } func appendU32(buf []byte, n uint32) []byte { return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) } func appendU64(buf []byte, n uint64) []byte { return append(buf, byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32), byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) } func appendInt(buf []byte, n int) []byte { return appendU32(buf, uint32(n)) } func appendString(buf []byte, s string) []byte { buf = appendU32(buf, uint32(len(s))) buf = append(buf, s...) return buf } func appendBool(buf []byte, b bool) []byte { if b { return append(buf, 1) } return append(buf, 0) } // newCond is a helper to hide the fact that there is no usable zero // value for sync.Cond. func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) } // window represents the buffer available to clients // wishing to write to a channel. type window struct { *sync.Cond win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1 writeWaiters int closed bool } // add adds win to the amount of window available // for consumers. func (w *window) add(win uint32) bool { // a zero sized window adjust is a noop. if win == 0 { return true } w.L.Lock() if w.win+win < win { w.L.Unlock() return false } w.win += win // It is unusual that multiple goroutines would be attempting to reserve // window space, but not guaranteed. Use broadcast to notify all waiters // that additional window is available. w.Broadcast() w.L.Unlock() return true } // close sets the window to closed, so all reservations fail // immediately. func (w *window) close() { w.L.Lock() w.closed = true w.Broadcast() w.L.Unlock() } // reserve reserves win from the available window capacity. // If no capacity remains, reserve will block. reserve may // return less than requested. func (w *window) reserve(win uint32) (uint32, error) { var err error w.L.Lock() w.writeWaiters++ w.Broadcast() for w.win == 0 && !w.closed { w.Wait() } w.writeWaiters-- if w.win < win { win = w.win } w.win -= win if w.closed { err = io.EOF } w.L.Unlock() return win, err } // waitWriterBlocked waits until some goroutine is blocked for further // writes. It is used in tests only. func (w *window) waitWriterBlocked() { w.Cond.L.Lock() for w.writeWaiters == 0 { w.Cond.Wait() } w.Cond.L.Unlock() } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/client_test.go������������������������������������������0000644�0610621�0607500�00000005500�13172163317�024513� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "net" "strings" "testing" ) func testClientVersion(t *testing.T, config *ClientConfig, expected string) { clientConn, serverConn := net.Pipe() defer clientConn.Close() receivedVersion := make(chan string, 1) config.HostKeyCallback = InsecureIgnoreHostKey() go func() { version, err := readVersion(serverConn) if err != nil { receivedVersion <- "" } else { receivedVersion <- string(version) } serverConn.Close() }() NewClientConn(clientConn, "", config) actual := <-receivedVersion if actual != expected { t.Fatalf("got %s; want %s", actual, expected) } } func TestCustomClientVersion(t *testing.T) { version := "Test-Client-Version-0.0" testClientVersion(t, &ClientConfig{ClientVersion: version}, version) } func TestDefaultClientVersion(t *testing.T) { testClientVersion(t, &ClientConfig{}, packageVersion) } func TestHostKeyCheck(t *testing.T) { for _, tt := range []struct { name string wantError string key PublicKey }{ {"no callback", "must specify HostKeyCallback", nil}, {"correct key", "", testSigners["rsa"].PublicKey()}, {"mismatch", "mismatch", testSigners["ecdsa"].PublicKey()}, } { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serverConf := &ServerConfig{ NoClientAuth: true, } serverConf.AddHostKey(testSigners["rsa"]) go NewServerConn(c1, serverConf) clientConf := ClientConfig{ User: "user", } if tt.key != nil { clientConf.HostKeyCallback = FixedHostKey(tt.key) } _, _, _, err = NewClientConn(c2, "", &clientConf) if err != nil { if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) { t.Errorf("%s: got error %q, missing %q", tt.name, err.Error(), tt.wantError) } } else if tt.wantError != "" { t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError) } } } func TestBannerCallback(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() serverConf := &ServerConfig{ NoClientAuth: true, BannerCallback: func(conn ConnMetadata) string { return "Hello World" }, } serverConf.AddHostKey(testSigners["rsa"]) go NewServerConn(c1, serverConf) var receivedBanner string clientConf := ClientConfig{ User: "user", HostKeyCallback: InsecureIgnoreHostKey(), BannerCallback: func(message string) error { receivedBanner = message return nil }, } _, _, _, err = NewClientConn(c2, "", &clientConf) if err != nil { t.Fatal(err) } expected := "Hello World" if receivedBanner != expected { t.Fatalf("got %s; want %s", receivedBanner, expected) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/client_auth_test.go�������������������������������������0000644�0610621�0607500�00000037544�13172163317�025551� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "crypto/rand" "errors" "fmt" "os" "strings" "testing" ) type keyboardInteractive map[string]string func (cr keyboardInteractive) Challenge(user string, instruction string, questions []string, echos []bool) ([]string, error) { var answers []string for _, q := range questions { answers = append(answers, cr[q]) } return answers, nil } // reused internally by tests var clientPassword = "tiger" // tryAuth runs a handshake with a given config against an SSH server // with config serverConfig func tryAuth(t *testing.T, config *ClientConfig) error { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() certChecker := CertChecker{ IsUserAuthority: func(k PublicKey) bool { return bytes.Equal(k.Marshal(), testPublicKeys["ecdsa"].Marshal()) }, UserKeyFallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) { if conn.User() == "testuser" && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) { return nil, nil } return nil, fmt.Errorf("pubkey for %q not acceptable", conn.User()) }, IsRevoked: func(c *Certificate) bool { return c.Serial == 666 }, } serverConfig := &ServerConfig{ PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) { if conn.User() == "testuser" && string(pass) == clientPassword { return nil, nil } return nil, errors.New("password auth failed") }, PublicKeyCallback: certChecker.Authenticate, KeyboardInteractiveCallback: func(conn ConnMetadata, challenge KeyboardInteractiveChallenge) (*Permissions, error) { ans, err := challenge("user", "instruction", []string{"question1", "question2"}, []bool{true, true}) if err != nil { return nil, err } ok := conn.User() == "testuser" && ans[0] == "answer1" && ans[1] == "answer2" if ok { challenge("user", "motd", nil, nil) return nil, nil } return nil, errors.New("keyboard-interactive failed") }, } serverConfig.AddHostKey(testSigners["rsa"]) go newServer(c1, serverConfig) _, _, _, err = NewClientConn(c2, "", config) return err } func TestClientAuthPublicKey(t *testing.T) { config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(testSigners["rsa"]), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("unable to dial remote side: %s", err) } } func TestAuthMethodPassword(t *testing.T) { config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ Password(clientPassword), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("unable to dial remote side: %s", err) } } func TestAuthMethodFallback(t *testing.T) { var passwordCalled bool config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(testSigners["rsa"]), PasswordCallback( func() (string, error) { passwordCalled = true return "WRONG", nil }), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("unable to dial remote side: %s", err) } if passwordCalled { t.Errorf("password auth tried before public-key auth.") } } func TestAuthMethodWrongPassword(t *testing.T) { config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ Password("wrong"), PublicKeys(testSigners["rsa"]), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("unable to dial remote side: %s", err) } } func TestAuthMethodKeyboardInteractive(t *testing.T) { answers := keyboardInteractive(map[string]string{ "question1": "answer1", "question2": "answer2", }) config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ KeyboardInteractive(answers.Challenge), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("unable to dial remote side: %s", err) } } func TestAuthMethodWrongKeyboardInteractive(t *testing.T) { answers := keyboardInteractive(map[string]string{ "question1": "answer1", "question2": "WRONG", }) config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ KeyboardInteractive(answers.Challenge), }, } if err := tryAuth(t, config); err == nil { t.Fatalf("wrong answers should not have authenticated with KeyboardInteractive") } } // the mock server will only authenticate ssh-rsa keys func TestAuthMethodInvalidPublicKey(t *testing.T) { config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(testSigners["dsa"]), }, } if err := tryAuth(t, config); err == nil { t.Fatalf("dsa private key should not have authenticated with rsa public key") } } // the client should authenticate with the second key func TestAuthMethodRSAandDSA(t *testing.T) { config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(testSigners["dsa"], testSigners["rsa"]), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("client could not authenticate with rsa key: %v", err) } } func TestClientHMAC(t *testing.T) { for _, mac := range supportedMACs { config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(testSigners["rsa"]), }, Config: Config{ MACs: []string{mac}, }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("client could not authenticate with mac algo %s: %v", mac, err) } } } // issue 4285. func TestClientUnsupportedCipher(t *testing.T) { config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(), }, Config: Config{ Ciphers: []string{"aes128-cbc"}, // not currently supported }, } if err := tryAuth(t, config); err == nil { t.Errorf("expected no ciphers in common") } } func TestClientUnsupportedKex(t *testing.T) { if os.Getenv("GO_BUILDER_NAME") != "" { t.Skip("skipping known-flaky test on the Go build dashboard; see golang.org/issue/15198") } config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(), }, Config: Config{ KeyExchanges: []string{"diffie-hellman-group-exchange-sha256"}, // not currently supported }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err == nil || !strings.Contains(err.Error(), "common algorithm") { t.Errorf("got %v, expected 'common algorithm'", err) } } func TestClientLoginCert(t *testing.T) { cert := &Certificate{ Key: testPublicKeys["rsa"], ValidBefore: CertTimeInfinity, CertType: UserCert, } cert.SignCert(rand.Reader, testSigners["ecdsa"]) certSigner, err := NewCertSigner(cert, testSigners["rsa"]) if err != nil { t.Fatalf("NewCertSigner: %v", err) } clientConfig := &ClientConfig{ User: "user", HostKeyCallback: InsecureIgnoreHostKey(), } clientConfig.Auth = append(clientConfig.Auth, PublicKeys(certSigner)) // should succeed if err := tryAuth(t, clientConfig); err != nil { t.Errorf("cert login failed: %v", err) } // corrupted signature cert.Signature.Blob[0]++ if err := tryAuth(t, clientConfig); err == nil { t.Errorf("cert login passed with corrupted sig") } // revoked cert.Serial = 666 cert.SignCert(rand.Reader, testSigners["ecdsa"]) if err := tryAuth(t, clientConfig); err == nil { t.Errorf("revoked cert login succeeded") } cert.Serial = 1 // sign with wrong key cert.SignCert(rand.Reader, testSigners["dsa"]) if err := tryAuth(t, clientConfig); err == nil { t.Errorf("cert login passed with non-authoritative key") } // host cert cert.CertType = HostCert cert.SignCert(rand.Reader, testSigners["ecdsa"]) if err := tryAuth(t, clientConfig); err == nil { t.Errorf("cert login passed with wrong type") } cert.CertType = UserCert // principal specified cert.ValidPrincipals = []string{"user"} cert.SignCert(rand.Reader, testSigners["ecdsa"]) if err := tryAuth(t, clientConfig); err != nil { t.Errorf("cert login failed: %v", err) } // wrong principal specified cert.ValidPrincipals = []string{"fred"} cert.SignCert(rand.Reader, testSigners["ecdsa"]) if err := tryAuth(t, clientConfig); err == nil { t.Errorf("cert login passed with wrong principal") } cert.ValidPrincipals = nil // added critical option cert.CriticalOptions = map[string]string{"root-access": "yes"} cert.SignCert(rand.Reader, testSigners["ecdsa"]) if err := tryAuth(t, clientConfig); err == nil { t.Errorf("cert login passed with unrecognized critical option") } // allowed source address cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42/24,::42/120"} cert.SignCert(rand.Reader, testSigners["ecdsa"]) if err := tryAuth(t, clientConfig); err != nil { t.Errorf("cert login with source-address failed: %v", err) } // disallowed source address cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42,::42"} cert.SignCert(rand.Reader, testSigners["ecdsa"]) if err := tryAuth(t, clientConfig); err == nil { t.Errorf("cert login with source-address succeeded") } } func testPermissionsPassing(withPermissions bool, t *testing.T) { serverConfig := &ServerConfig{ PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) { if conn.User() == "nopermissions" { return nil, nil } return &Permissions{}, nil }, } serverConfig.AddHostKey(testSigners["rsa"]) clientConfig := &ClientConfig{ Auth: []AuthMethod{ PublicKeys(testSigners["rsa"]), }, HostKeyCallback: InsecureIgnoreHostKey(), } if withPermissions { clientConfig.User = "permissions" } else { clientConfig.User = "nopermissions" } c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() go NewClientConn(c2, "", clientConfig) serverConn, err := newServer(c1, serverConfig) if err != nil { t.Fatal(err) } if p := serverConn.Permissions; (p != nil) != withPermissions { t.Fatalf("withPermissions is %t, but Permissions object is %#v", withPermissions, p) } } func TestPermissionsPassing(t *testing.T) { testPermissionsPassing(true, t) } func TestNoPermissionsPassing(t *testing.T) { testPermissionsPassing(false, t) } func TestRetryableAuth(t *testing.T) { n := 0 passwords := []string{"WRONG1", "WRONG2"} config := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ RetryableAuthMethod(PasswordCallback(func() (string, error) { p := passwords[n] n++ return p, nil }), 2), PublicKeys(testSigners["rsa"]), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, config); err != nil { t.Fatalf("unable to dial remote side: %s", err) } if n != 2 { t.Fatalf("Did not try all passwords") } } func ExampleRetryableAuthMethod(t *testing.T) { user := "testuser" NumberOfPrompts := 3 // Normally this would be a callback that prompts the user to answer the // provided questions Cb := func(user, instruction string, questions []string, echos []bool) (answers []string, err error) { return []string{"answer1", "answer2"}, nil } config := &ClientConfig{ HostKeyCallback: InsecureIgnoreHostKey(), User: user, Auth: []AuthMethod{ RetryableAuthMethod(KeyboardInteractiveChallenge(Cb), NumberOfPrompts), }, } if err := tryAuth(t, config); err != nil { t.Fatalf("unable to dial remote side: %s", err) } } // Test if username is received on server side when NoClientAuth is used func TestClientAuthNone(t *testing.T) { user := "testuser" serverConfig := &ServerConfig{ NoClientAuth: true, } serverConfig.AddHostKey(testSigners["rsa"]) clientConfig := &ClientConfig{ User: user, HostKeyCallback: InsecureIgnoreHostKey(), } c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() go NewClientConn(c2, "", clientConfig) serverConn, err := newServer(c1, serverConfig) if err != nil { t.Fatalf("newServer: %v", err) } if serverConn.User() != user { t.Fatalf("server: got %q, want %q", serverConn.User(), user) } } // Test if authentication attempts are limited on server when MaxAuthTries is set func TestClientAuthMaxAuthTries(t *testing.T) { user := "testuser" serverConfig := &ServerConfig{ MaxAuthTries: 2, PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) { if conn.User() == "testuser" && string(pass) == "right" { return nil, nil } return nil, errors.New("password auth failed") }, } serverConfig.AddHostKey(testSigners["rsa"]) expectedErr := fmt.Errorf("ssh: handshake failed: %v", &disconnectMsg{ Reason: 2, Message: "too many authentication failures", }) for tries := 2; tries < 4; tries++ { n := tries clientConfig := &ClientConfig{ User: user, Auth: []AuthMethod{ RetryableAuthMethod(PasswordCallback(func() (string, error) { n-- if n == 0 { return "right", nil } return "wrong", nil }), tries), }, HostKeyCallback: InsecureIgnoreHostKey(), } c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() go newServer(c1, serverConfig) _, _, _, err = NewClientConn(c2, "", clientConfig) if tries > 2 { if err == nil { t.Fatalf("client: got no error, want %s", expectedErr) } else if err.Error() != expectedErr.Error() { t.Fatalf("client: got %s, want %s", err, expectedErr) } } else { if err != nil { t.Fatalf("client: got %s, want no error", err) } } } } // Test if authentication attempts are correctly limited on server // when more public keys are provided then MaxAuthTries func TestClientAuthMaxAuthTriesPublicKey(t *testing.T) { signers := []Signer{} for i := 0; i < 6; i++ { signers = append(signers, testSigners["dsa"]) } validConfig := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(append([]Signer{testSigners["rsa"]}, signers...)...), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, validConfig); err != nil { t.Fatalf("unable to dial remote side: %s", err) } expectedErr := fmt.Errorf("ssh: handshake failed: %v", &disconnectMsg{ Reason: 2, Message: "too many authentication failures", }) invalidConfig := &ClientConfig{ User: "testuser", Auth: []AuthMethod{ PublicKeys(append(signers, testSigners["rsa"])...), }, HostKeyCallback: InsecureIgnoreHostKey(), } if err := tryAuth(t, invalidConfig); err == nil { t.Fatalf("client: got no error, want %s", expectedErr) } else if err.Error() != expectedErr.Error() { t.Fatalf("client: got %s, want %s", err, expectedErr) } } // Test whether authentication errors are being properly logged if all // authentication methods have been exhausted func TestClientAuthErrorList(t *testing.T) { publicKeyErr := errors.New("This is an error from PublicKeyCallback") clientConfig := &ClientConfig{ Auth: []AuthMethod{ PublicKeys(testSigners["rsa"]), }, HostKeyCallback: InsecureIgnoreHostKey(), } serverConfig := &ServerConfig{ PublicKeyCallback: func(_ ConnMetadata, _ PublicKey) (*Permissions, error) { return nil, publicKeyErr }, } serverConfig.AddHostKey(testSigners["rsa"]) c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() go NewClientConn(c2, "", clientConfig) _, err = newServer(c1, serverConfig) if err == nil { t.Fatal("newServer: got nil, expected errors") } authErrs, ok := err.(*ServerAuthError) if !ok { t.Fatalf("errors: got %T, want *ssh.ServerAuthError", err) } for i, e := range authErrs.Errors { switch i { case 0: if e.Error() != "no auth passed yet" { t.Fatalf("errors: got %v, want no auth passed yet", e.Error()) } case 1: if e != publicKeyErr { t.Fatalf("errors: got %v, want %v", e, publicKeyErr) } default: t.Fatalf("errors: got %v, expected 2 errors", authErrs.Errors) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/client_auth.go������������������������������������������0000644�0610621�0607500�00000033353�13172163317�024504� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "errors" "fmt" "io" ) // clientAuthenticate authenticates with the remote server. See RFC 4252. func (c *connection) clientAuthenticate(config *ClientConfig) error { // initiate user auth session if err := c.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil { return err } packet, err := c.transport.readPacket() if err != nil { return err } var serviceAccept serviceAcceptMsg if err := Unmarshal(packet, &serviceAccept); err != nil { return err } // during the authentication phase the client first attempts the "none" method // then any untried methods suggested by the server. tried := make(map[string]bool) var lastMethods []string sessionID := c.transport.getSessionID() for auth := AuthMethod(new(noneAuth)); auth != nil; { ok, methods, err := auth.auth(sessionID, config.User, c.transport, config.Rand) if err != nil { return err } if ok { // success return nil } tried[auth.method()] = true if methods == nil { methods = lastMethods } lastMethods = methods auth = nil findNext: for _, a := range config.Auth { candidateMethod := a.method() if tried[candidateMethod] { continue } for _, meth := range methods { if meth == candidateMethod { auth = a break findNext } } } } return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", keys(tried)) } func keys(m map[string]bool) []string { s := make([]string, 0, len(m)) for key := range m { s = append(s, key) } return s } // An AuthMethod represents an instance of an RFC 4252 authentication method. type AuthMethod interface { // auth authenticates user over transport t. // Returns true if authentication is successful. // If authentication is not successful, a []string of alternative // method names is returned. If the slice is nil, it will be ignored // and the previous set of possible methods will be reused. auth(session []byte, user string, p packetConn, rand io.Reader) (bool, []string, error) // method returns the RFC 4252 method name. method() string } // "none" authentication, RFC 4252 section 5.2. type noneAuth int func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { if err := c.writePacket(Marshal(&userAuthRequestMsg{ User: user, Service: serviceSSH, Method: "none", })); err != nil { return false, nil, err } return handleAuthResponse(c) } func (n *noneAuth) method() string { return "none" } // passwordCallback is an AuthMethod that fetches the password through // a function call, e.g. by prompting the user. type passwordCallback func() (password string, err error) func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { type passwordAuthMsg struct { User string `sshtype:"50"` Service string Method string Reply bool Password string } pw, err := cb() // REVIEW NOTE: is there a need to support skipping a password attempt? // The program may only find out that the user doesn't have a password // when prompting. if err != nil { return false, nil, err } if err := c.writePacket(Marshal(&passwordAuthMsg{ User: user, Service: serviceSSH, Method: cb.method(), Reply: false, Password: pw, })); err != nil { return false, nil, err } return handleAuthResponse(c) } func (cb passwordCallback) method() string { return "password" } // Password returns an AuthMethod using the given password. func Password(secret string) AuthMethod { return passwordCallback(func() (string, error) { return secret, nil }) } // PasswordCallback returns an AuthMethod that uses a callback for // fetching a password. func PasswordCallback(prompt func() (secret string, err error)) AuthMethod { return passwordCallback(prompt) } type publickeyAuthMsg struct { User string `sshtype:"50"` Service string Method string // HasSig indicates to the receiver packet that the auth request is signed and // should be used for authentication of the request. HasSig bool Algoname string PubKey []byte // Sig is tagged with "rest" so Marshal will exclude it during // validateKey Sig []byte `ssh:"rest"` } // publicKeyCallback is an AuthMethod that uses a set of key // pairs for authentication. type publicKeyCallback func() ([]Signer, error) func (cb publicKeyCallback) method() string { return "publickey" } func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { // Authentication is performed by sending an enquiry to test if a key is // acceptable to the remote. If the key is acceptable, the client will // attempt to authenticate with the valid key. If not the client will repeat // the process with the remaining keys. signers, err := cb() if err != nil { return false, nil, err } var methods []string for _, signer := range signers { ok, err := validateKey(signer.PublicKey(), user, c) if err != nil { return false, nil, err } if !ok { continue } pub := signer.PublicKey() pubKey := pub.Marshal() sign, err := signer.Sign(rand, buildDataSignedForAuth(session, userAuthRequestMsg{ User: user, Service: serviceSSH, Method: cb.method(), }, []byte(pub.Type()), pubKey)) if err != nil { return false, nil, err } // manually wrap the serialized signature in a string s := Marshal(sign) sig := make([]byte, stringLength(len(s))) marshalString(sig, s) msg := publickeyAuthMsg{ User: user, Service: serviceSSH, Method: cb.method(), HasSig: true, Algoname: pub.Type(), PubKey: pubKey, Sig: sig, } p := Marshal(&msg) if err := c.writePacket(p); err != nil { return false, nil, err } var success bool success, methods, err = handleAuthResponse(c) if err != nil { return false, nil, err } // If authentication succeeds or the list of available methods does not // contain the "publickey" method, do not attempt to authenticate with any // other keys. According to RFC 4252 Section 7, the latter can occur when // additional authentication methods are required. if success || !containsMethod(methods, cb.method()) { return success, methods, err } } return false, methods, nil } func containsMethod(methods []string, method string) bool { for _, m := range methods { if m == method { return true } } return false } // validateKey validates the key provided is acceptable to the server. func validateKey(key PublicKey, user string, c packetConn) (bool, error) { pubKey := key.Marshal() msg := publickeyAuthMsg{ User: user, Service: serviceSSH, Method: "publickey", HasSig: false, Algoname: key.Type(), PubKey: pubKey, } if err := c.writePacket(Marshal(&msg)); err != nil { return false, err } return confirmKeyAck(key, c) } func confirmKeyAck(key PublicKey, c packetConn) (bool, error) { pubKey := key.Marshal() algoname := key.Type() for { packet, err := c.readPacket() if err != nil { return false, err } switch packet[0] { case msgUserAuthBanner: if err := handleBannerResponse(c, packet); err != nil { return false, err } case msgUserAuthPubKeyOk: var msg userAuthPubKeyOkMsg if err := Unmarshal(packet, &msg); err != nil { return false, err } if msg.Algo != algoname || !bytes.Equal(msg.PubKey, pubKey) { return false, nil } return true, nil case msgUserAuthFailure: return false, nil default: return false, unexpectedMessageError(msgUserAuthSuccess, packet[0]) } } } // PublicKeys returns an AuthMethod that uses the given key // pairs. func PublicKeys(signers ...Signer) AuthMethod { return publicKeyCallback(func() ([]Signer, error) { return signers, nil }) } // PublicKeysCallback returns an AuthMethod that runs the given // function to obtain a list of key pairs. func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod { return publicKeyCallback(getSigners) } // handleAuthResponse returns whether the preceding authentication request succeeded // along with a list of remaining authentication methods to try next and // an error if an unexpected response was received. func handleAuthResponse(c packetConn) (bool, []string, error) { for { packet, err := c.readPacket() if err != nil { return false, nil, err } switch packet[0] { case msgUserAuthBanner: if err := handleBannerResponse(c, packet); err != nil { return false, nil, err } case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { return false, nil, err } return false, msg.Methods, nil case msgUserAuthSuccess: return true, nil, nil default: return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) } } } func handleBannerResponse(c packetConn, packet []byte) error { var msg userAuthBannerMsg if err := Unmarshal(packet, &msg); err != nil { return err } transport, ok := c.(*handshakeTransport) if !ok { return nil } if transport.bannerCallback != nil { return transport.bannerCallback(msg.Message) } return nil } // KeyboardInteractiveChallenge should print questions, optionally // disabling echoing (e.g. for passwords), and return all the answers. // Challenge may be called multiple times in a single session. After // successful authentication, the server may send a challenge with no // questions, for which the user and instruction messages should be // printed. RFC 4256 section 3.3 details how the UI should behave for // both CLI and GUI environments. type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error) // KeyboardInteractive returns an AuthMethod using a prompt/response // sequence controlled by the server. func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod { return challenge } func (cb KeyboardInteractiveChallenge) method() string { return "keyboard-interactive" } func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { type initiateMsg struct { User string `sshtype:"50"` Service string Method string Language string Submethods string } if err := c.writePacket(Marshal(&initiateMsg{ User: user, Service: serviceSSH, Method: "keyboard-interactive", })); err != nil { return false, nil, err } for { packet, err := c.readPacket() if err != nil { return false, nil, err } // like handleAuthResponse, but with less options. switch packet[0] { case msgUserAuthBanner: if err := handleBannerResponse(c, packet); err != nil { return false, nil, err } continue case msgUserAuthInfoRequest: // OK case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { return false, nil, err } return false, msg.Methods, nil case msgUserAuthSuccess: return true, nil, nil default: return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) } var msg userAuthInfoRequestMsg if err := Unmarshal(packet, &msg); err != nil { return false, nil, err } // Manually unpack the prompt/echo pairs. rest := msg.Prompts var prompts []string var echos []bool for i := 0; i < int(msg.NumPrompts); i++ { prompt, r, ok := parseString(rest) if !ok || len(r) == 0 { return false, nil, errors.New("ssh: prompt format error") } prompts = append(prompts, string(prompt)) echos = append(echos, r[0] != 0) rest = r[1:] } if len(rest) != 0 { return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs") } answers, err := cb(msg.User, msg.Instruction, prompts, echos) if err != nil { return false, nil, err } if len(answers) != len(prompts) { return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback") } responseLength := 1 + 4 for _, a := range answers { responseLength += stringLength(len(a)) } serialized := make([]byte, responseLength) p := serialized p[0] = msgUserAuthInfoResponse p = p[1:] p = marshalUint32(p, uint32(len(answers))) for _, a := range answers { p = marshalString(p, []byte(a)) } if err := c.writePacket(serialized); err != nil { return false, nil, err } } } type retryableAuthMethod struct { authMethod AuthMethod maxTries int } func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok bool, methods []string, err error) { for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ { ok, methods, err = r.authMethod.auth(session, user, c, rand) if ok || err != nil { // either success or error terminate return ok, methods, err } } return ok, methods, err } func (r *retryableAuthMethod) method() string { return r.authMethod.method() } // RetryableAuthMethod is a decorator for other auth methods enabling them to // be retried up to maxTries before considering that AuthMethod itself failed. // If maxTries is <= 0, will retry indefinitely // // This is useful for interactive clients using challenge/response type // authentication (e.g. Keyboard-Interactive, Password, etc) where the user // could mistype their response resulting in the server issuing a // SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4 // [keyboard-interactive]); Without this decorator, the non-retryable // AuthMethod would be removed from future consideration, and never tried again // (and so the user would never be able to retry their entry). func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod { return &retryableAuthMethod{authMethod: auth, maxTries: maxTries} } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/client.go�����������������������������������������������0000644�0610621�0607500�00000020664�13172163317�023464� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "errors" "fmt" "net" "os" "sync" "time" ) // Client implements a traditional SSH client that supports shells, // subprocesses, TCP port/streamlocal forwarding and tunneled dialing. type Client struct { Conn forwards forwardList // forwarded tcpip connections from the remote side mu sync.Mutex channelHandlers map[string]chan NewChannel } // HandleChannelOpen returns a channel on which NewChannel requests // for the given type are sent. If the type already is being handled, // nil is returned. The channel is closed when the connection is closed. func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel { c.mu.Lock() defer c.mu.Unlock() if c.channelHandlers == nil { // The SSH channel has been closed. c := make(chan NewChannel) close(c) return c } ch := c.channelHandlers[channelType] if ch != nil { return nil } ch = make(chan NewChannel, chanSize) c.channelHandlers[channelType] = ch return ch } // NewClient creates a Client on top of the given connection. func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client { conn := &Client{ Conn: c, channelHandlers: make(map[string]chan NewChannel, 1), } go conn.handleGlobalRequests(reqs) go conn.handleChannelOpens(chans) go func() { conn.Wait() conn.forwards.closeAll() }() go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-tcpip")) go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-streamlocal@openssh.com")) return conn } // NewClientConn establishes an authenticated SSH connection using c // as the underlying transport. The Request and NewChannel channels // must be serviced or the connection will hang. func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) { fullConf := *config fullConf.SetDefaults() if fullConf.HostKeyCallback == nil { c.Close() return nil, nil, nil, errors.New("ssh: must specify HostKeyCallback") } conn := &connection{ sshConn: sshConn{conn: c}, } if err := conn.clientHandshake(addr, &fullConf); err != nil { c.Close() return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %v", err) } conn.mux = newMux(conn.transport) return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil } // clientHandshake performs the client side key exchange. See RFC 4253 Section // 7. func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error { if config.ClientVersion != "" { c.clientVersion = []byte(config.ClientVersion) } else { c.clientVersion = []byte(packageVersion) } var err error c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion) if err != nil { return err } c.transport = newClientTransport( newTransport(c.sshConn.conn, config.Rand, true /* is client */), c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr()) if err := c.transport.waitSession(); err != nil { return err } c.sessionID = c.transport.getSessionID() return c.clientAuthenticate(config) } // verifyHostKeySignature verifies the host key obtained in the key // exchange. func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error { sig, rest, ok := parseSignatureBody(result.Signature) if len(rest) > 0 || !ok { return errors.New("ssh: signature parse error") } return hostKey.Verify(result.H, sig) } // NewSession opens a new Session for this client. (A session is a remote // execution of a program.) func (c *Client) NewSession() (*Session, error) { ch, in, err := c.OpenChannel("session", nil) if err != nil { return nil, err } return newSession(ch, in) } func (c *Client) handleGlobalRequests(incoming <-chan *Request) { for r := range incoming { // This handles keepalive messages and matches // the behaviour of OpenSSH. r.Reply(false, nil) } } // handleChannelOpens channel open messages from the remote side. func (c *Client) handleChannelOpens(in <-chan NewChannel) { for ch := range in { c.mu.Lock() handler := c.channelHandlers[ch.ChannelType()] c.mu.Unlock() if handler != nil { handler <- ch } else { ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType())) } } c.mu.Lock() for _, ch := range c.channelHandlers { close(ch) } c.channelHandlers = nil c.mu.Unlock() } // Dial starts a client connection to the given SSH server. It is a // convenience function that connects to the given network address, // initiates the SSH handshake, and then sets up a Client. For access // to incoming channels and requests, use net.Dial with NewClientConn // instead. func Dial(network, addr string, config *ClientConfig) (*Client, error) { conn, err := net.DialTimeout(network, addr, config.Timeout) if err != nil { return nil, err } c, chans, reqs, err := NewClientConn(conn, addr, config) if err != nil { return nil, err } return NewClient(c, chans, reqs), nil } // HostKeyCallback is the function type used for verifying server // keys. A HostKeyCallback must return nil if the host key is OK, or // an error to reject it. It receives the hostname as passed to Dial // or NewClientConn. The remote address is the RemoteAddr of the // net.Conn underlying the the SSH connection. type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error // BannerCallback is the function type used for treat the banner sent by // the server. A BannerCallback receives the message sent by the remote server. type BannerCallback func(message string) error // A ClientConfig structure is used to configure a Client. It must not be // modified after having been passed to an SSH function. type ClientConfig struct { // Config contains configuration that is shared between clients and // servers. Config // User contains the username to authenticate as. User string // Auth contains possible authentication methods to use with the // server. Only the first instance of a particular RFC 4252 method will // be used during authentication. Auth []AuthMethod // HostKeyCallback is called during the cryptographic // handshake to validate the server's host key. The client // configuration must supply this callback for the connection // to succeed. The functions InsecureIgnoreHostKey or // FixedHostKey can be used for simplistic host key checks. HostKeyCallback HostKeyCallback // BannerCallback is called during the SSH dance to display a custom // server's message. The client configuration can supply this callback to // handle it as wished. The function BannerDisplayStderr can be used for // simplistic display on Stderr. BannerCallback BannerCallback // ClientVersion contains the version identification string that will // be used for the connection. If empty, a reasonable default is used. ClientVersion string // HostKeyAlgorithms lists the key types that the client will // accept from the server as host key, in order of // preference. If empty, a reasonable default is used. Any // string returned from PublicKey.Type method may be used, or // any of the CertAlgoXxxx and KeyAlgoXxxx constants. HostKeyAlgorithms []string // Timeout is the maximum amount of time for the TCP connection to establish. // // A Timeout of zero means no timeout. Timeout time.Duration } // InsecureIgnoreHostKey returns a function that can be used for // ClientConfig.HostKeyCallback to accept any host key. It should // not be used for production code. func InsecureIgnoreHostKey() HostKeyCallback { return func(hostname string, remote net.Addr, key PublicKey) error { return nil } } type fixedHostKey struct { key PublicKey } func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error { if f.key == nil { return fmt.Errorf("ssh: required host key was nil") } if !bytes.Equal(key.Marshal(), f.key.Marshal()) { return fmt.Errorf("ssh: host key mismatch") } return nil } // FixedHostKey returns a function for use in // ClientConfig.HostKeyCallback to accept only a specific host key. func FixedHostKey(key PublicKey) HostKeyCallback { hk := &fixedHostKey{key} return hk.check } // BannerDisplayStderr returns a function that can be used for // ClientConfig.BannerCallback to display banners on os.Stderr. func BannerDisplayStderr() BannerCallback { return func(banner string) error { _, err := os.Stderr.WriteString(banner) return err } } ����������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/cipher_test.go������������������������������������������0000644�0610621�0607500�00000006436�13172163317�024520� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "crypto" "crypto/aes" "crypto/rand" "testing" ) func TestDefaultCiphersExist(t *testing.T) { for _, cipherAlgo := range supportedCiphers { if _, ok := cipherModes[cipherAlgo]; !ok { t.Errorf("default cipher %q is unknown", cipherAlgo) } } } func TestPacketCiphers(t *testing.T) { // Still test aes128cbc cipher although it's commented out. cipherModes[aes128cbcID] = &streamCipherMode{16, aes.BlockSize, 0, nil} defer delete(cipherModes, aes128cbcID) for cipher := range cipherModes { for mac := range macModes { kr := &kexResult{Hash: crypto.SHA1} algs := directionAlgorithms{ Cipher: cipher, MAC: mac, Compression: "none", } client, err := newPacketCipher(clientKeys, algs, kr) if err != nil { t.Errorf("newPacketCipher(client, %q, %q): %v", cipher, mac, err) continue } server, err := newPacketCipher(clientKeys, algs, kr) if err != nil { t.Errorf("newPacketCipher(client, %q, %q): %v", cipher, mac, err) continue } want := "bla bla" input := []byte(want) buf := &bytes.Buffer{} if err := client.writePacket(0, buf, rand.Reader, input); err != nil { t.Errorf("writePacket(%q, %q): %v", cipher, mac, err) continue } packet, err := server.readPacket(0, buf) if err != nil { t.Errorf("readPacket(%q, %q): %v", cipher, mac, err) continue } if string(packet) != want { t.Errorf("roundtrip(%q, %q): got %q, want %q", cipher, mac, packet, want) } } } } func TestCBCOracleCounterMeasure(t *testing.T) { cipherModes[aes128cbcID] = &streamCipherMode{16, aes.BlockSize, 0, nil} defer delete(cipherModes, aes128cbcID) kr := &kexResult{Hash: crypto.SHA1} algs := directionAlgorithms{ Cipher: aes128cbcID, MAC: "hmac-sha1", Compression: "none", } client, err := newPacketCipher(clientKeys, algs, kr) if err != nil { t.Fatalf("newPacketCipher(client): %v", err) } want := "bla bla" input := []byte(want) buf := &bytes.Buffer{} if err := client.writePacket(0, buf, rand.Reader, input); err != nil { t.Errorf("writePacket: %v", err) } packetSize := buf.Len() buf.Write(make([]byte, 2*maxPacket)) // We corrupt each byte, but this usually will only test the // 'packet too large' or 'MAC failure' cases. lastRead := -1 for i := 0; i < packetSize; i++ { server, err := newPacketCipher(clientKeys, algs, kr) if err != nil { t.Fatalf("newPacketCipher(client): %v", err) } fresh := &bytes.Buffer{} fresh.Write(buf.Bytes()) fresh.Bytes()[i] ^= 0x01 before := fresh.Len() _, err = server.readPacket(0, fresh) if err == nil { t.Errorf("corrupt byte %d: readPacket succeeded ", i) continue } if _, ok := err.(cbcError); !ok { t.Errorf("corrupt byte %d: got %v (%T), want cbcError", i, err, err) continue } after := fresh.Len() bytesRead := before - after if bytesRead < maxPacket { t.Errorf("corrupt byte %d: read %d bytes, want more than %d", i, bytesRead, maxPacket) continue } if i > 0 && bytesRead != lastRead { t.Errorf("corrupt byte %d: read %d bytes, want %d bytes read", i, bytesRead, lastRead) } lastRead = bytesRead } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/cipher.go�����������������������������������������������0000644�0610621�0607500�00000041222�13172163317�023451� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "crypto/aes" "crypto/cipher" "crypto/des" "crypto/rc4" "crypto/subtle" "encoding/binary" "errors" "fmt" "hash" "io" "io/ioutil" ) const ( packetSizeMultiple = 16 // TODO(huin) this should be determined by the cipher. // RFC 4253 section 6.1 defines a minimum packet size of 32768 that implementations // MUST be able to process (plus a few more kilobytes for padding and mac). The RFC // indicates implementations SHOULD be able to handle larger packet sizes, but then // waffles on about reasonable limits. // // OpenSSH caps their maxPacket at 256kB so we choose to do // the same. maxPacket is also used to ensure that uint32 // length fields do not overflow, so it should remain well // below 4G. maxPacket = 256 * 1024 ) // noneCipher implements cipher.Stream and provides no encryption. It is used // by the transport before the first key-exchange. type noneCipher struct{} func (c noneCipher) XORKeyStream(dst, src []byte) { copy(dst, src) } func newAESCTR(key, iv []byte) (cipher.Stream, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err } return cipher.NewCTR(c, iv), nil } func newRC4(key, iv []byte) (cipher.Stream, error) { return rc4.NewCipher(key) } type streamCipherMode struct { keySize int ivSize int skip int createFunc func(key, iv []byte) (cipher.Stream, error) } func (c *streamCipherMode) createStream(key, iv []byte) (cipher.Stream, error) { if len(key) < c.keySize { panic("ssh: key length too small for cipher") } if len(iv) < c.ivSize { panic("ssh: iv too small for cipher") } stream, err := c.createFunc(key[:c.keySize], iv[:c.ivSize]) if err != nil { return nil, err } var streamDump []byte if c.skip > 0 { streamDump = make([]byte, 512) } for remainingToDump := c.skip; remainingToDump > 0; { dumpThisTime := remainingToDump if dumpThisTime > len(streamDump) { dumpThisTime = len(streamDump) } stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime]) remainingToDump -= dumpThisTime } return stream, nil } // cipherModes documents properties of supported ciphers. Ciphers not included // are not supported and will not be negotiated, even if explicitly requested in // ClientConfig.Crypto.Ciphers. var cipherModes = map[string]*streamCipherMode{ // Ciphers from RFC4344, which introduced many CTR-based ciphers. Algorithms // are defined in the order specified in the RFC. "aes128-ctr": {16, aes.BlockSize, 0, newAESCTR}, "aes192-ctr": {24, aes.BlockSize, 0, newAESCTR}, "aes256-ctr": {32, aes.BlockSize, 0, newAESCTR}, // Ciphers from RFC4345, which introduces security-improved arcfour ciphers. // They are defined in the order specified in the RFC. "arcfour128": {16, 0, 1536, newRC4}, "arcfour256": {32, 0, 1536, newRC4}, // Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol. // Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and // RC4) has problems with weak keys, and should be used with caution." // RFC4345 introduces improved versions of Arcfour. "arcfour": {16, 0, 0, newRC4}, // AES-GCM is not a stream cipher, so it is constructed with a // special case. If we add any more non-stream ciphers, we // should invest a cleaner way to do this. gcmCipherID: {16, 12, 0, nil}, // CBC mode is insecure and so is not included in the default config. // (See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely // needed, it's possible to specify a custom Config to enable it. // You should expect that an active attacker can recover plaintext if // you do. aes128cbcID: {16, aes.BlockSize, 0, nil}, // 3des-cbc is insecure and is disabled by default. tripledescbcID: {24, des.BlockSize, 0, nil}, } // prefixLen is the length of the packet prefix that contains the packet length // and number of padding bytes. const prefixLen = 5 // streamPacketCipher is a packetCipher using a stream cipher. type streamPacketCipher struct { mac hash.Hash cipher cipher.Stream etm bool // The following members are to avoid per-packet allocations. prefix [prefixLen]byte seqNumBytes [4]byte padding [2 * packetSizeMultiple]byte packetData []byte macResult []byte } // readPacket reads and decrypt a single packet from the reader argument. func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { if _, err := io.ReadFull(r, s.prefix[:]); err != nil { return nil, err } var encryptedPaddingLength [1]byte if s.mac != nil && s.etm { copy(encryptedPaddingLength[:], s.prefix[4:5]) s.cipher.XORKeyStream(s.prefix[4:5], s.prefix[4:5]) } else { s.cipher.XORKeyStream(s.prefix[:], s.prefix[:]) } length := binary.BigEndian.Uint32(s.prefix[0:4]) paddingLength := uint32(s.prefix[4]) var macSize uint32 if s.mac != nil { s.mac.Reset() binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum) s.mac.Write(s.seqNumBytes[:]) if s.etm { s.mac.Write(s.prefix[:4]) s.mac.Write(encryptedPaddingLength[:]) } else { s.mac.Write(s.prefix[:]) } macSize = uint32(s.mac.Size()) } if length <= paddingLength+1 { return nil, errors.New("ssh: invalid packet length, packet too small") } if length > maxPacket { return nil, errors.New("ssh: invalid packet length, packet too large") } // the maxPacket check above ensures that length-1+macSize // does not overflow. if uint32(cap(s.packetData)) < length-1+macSize { s.packetData = make([]byte, length-1+macSize) } else { s.packetData = s.packetData[:length-1+macSize] } if _, err := io.ReadFull(r, s.packetData); err != nil { return nil, err } mac := s.packetData[length-1:] data := s.packetData[:length-1] if s.mac != nil && s.etm { s.mac.Write(data) } s.cipher.XORKeyStream(data, data) if s.mac != nil { if !s.etm { s.mac.Write(data) } s.macResult = s.mac.Sum(s.macResult[:0]) if subtle.ConstantTimeCompare(s.macResult, mac) != 1 { return nil, errors.New("ssh: MAC failure") } } return s.packetData[:length-paddingLength-1], nil } // writePacket encrypts and sends a packet of data to the writer argument func (s *streamPacketCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { if len(packet) > maxPacket { return errors.New("ssh: packet too large") } aadlen := 0 if s.mac != nil && s.etm { // packet length is not encrypted for EtM modes aadlen = 4 } paddingLength := packetSizeMultiple - (prefixLen+len(packet)-aadlen)%packetSizeMultiple if paddingLength < 4 { paddingLength += packetSizeMultiple } length := len(packet) + 1 + paddingLength binary.BigEndian.PutUint32(s.prefix[:], uint32(length)) s.prefix[4] = byte(paddingLength) padding := s.padding[:paddingLength] if _, err := io.ReadFull(rand, padding); err != nil { return err } if s.mac != nil { s.mac.Reset() binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum) s.mac.Write(s.seqNumBytes[:]) if s.etm { // For EtM algorithms, the packet length must stay unencrypted, // but the following data (padding length) must be encrypted s.cipher.XORKeyStream(s.prefix[4:5], s.prefix[4:5]) } s.mac.Write(s.prefix[:]) if !s.etm { // For non-EtM algorithms, the algorithm is applied on unencrypted data s.mac.Write(packet) s.mac.Write(padding) } } if !(s.mac != nil && s.etm) { // For EtM algorithms, the padding length has already been encrypted // and the packet length must remain unencrypted s.cipher.XORKeyStream(s.prefix[:], s.prefix[:]) } s.cipher.XORKeyStream(packet, packet) s.cipher.XORKeyStream(padding, padding) if s.mac != nil && s.etm { // For EtM algorithms, packet and padding must be encrypted s.mac.Write(packet) s.mac.Write(padding) } if _, err := w.Write(s.prefix[:]); err != nil { return err } if _, err := w.Write(packet); err != nil { return err } if _, err := w.Write(padding); err != nil { return err } if s.mac != nil { s.macResult = s.mac.Sum(s.macResult[:0]) if _, err := w.Write(s.macResult); err != nil { return err } } return nil } type gcmCipher struct { aead cipher.AEAD prefix [4]byte iv []byte buf []byte } func newGCMCipher(iv, key, macKey []byte) (packetCipher, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err } aead, err := cipher.NewGCM(c) if err != nil { return nil, err } return &gcmCipher{ aead: aead, iv: iv, }, nil } const gcmTagSize = 16 func (c *gcmCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { // Pad out to multiple of 16 bytes. This is different from the // stream cipher because that encrypts the length too. padding := byte(packetSizeMultiple - (1+len(packet))%packetSizeMultiple) if padding < 4 { padding += packetSizeMultiple } length := uint32(len(packet) + int(padding) + 1) binary.BigEndian.PutUint32(c.prefix[:], length) if _, err := w.Write(c.prefix[:]); err != nil { return err } if cap(c.buf) < int(length) { c.buf = make([]byte, length) } else { c.buf = c.buf[:length] } c.buf[0] = padding copy(c.buf[1:], packet) if _, err := io.ReadFull(rand, c.buf[1+len(packet):]); err != nil { return err } c.buf = c.aead.Seal(c.buf[:0], c.iv, c.buf, c.prefix[:]) if _, err := w.Write(c.buf); err != nil { return err } c.incIV() return nil } func (c *gcmCipher) incIV() { for i := 4 + 7; i >= 4; i-- { c.iv[i]++ if c.iv[i] != 0 { break } } } func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { if _, err := io.ReadFull(r, c.prefix[:]); err != nil { return nil, err } length := binary.BigEndian.Uint32(c.prefix[:]) if length > maxPacket { return nil, errors.New("ssh: max packet length exceeded.") } if cap(c.buf) < int(length+gcmTagSize) { c.buf = make([]byte, length+gcmTagSize) } else { c.buf = c.buf[:length+gcmTagSize] } if _, err := io.ReadFull(r, c.buf); err != nil { return nil, err } plain, err := c.aead.Open(c.buf[:0], c.iv, c.buf, c.prefix[:]) if err != nil { return nil, err } c.incIV() padding := plain[0] if padding < 4 { // padding is a byte, so it automatically satisfies // the maximum size, which is 255. return nil, fmt.Errorf("ssh: illegal padding %d", padding) } if int(padding+1) >= len(plain) { return nil, fmt.Errorf("ssh: padding %d too large", padding) } plain = plain[1 : length-uint32(padding)] return plain, nil } // cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1 type cbcCipher struct { mac hash.Hash macSize uint32 decrypter cipher.BlockMode encrypter cipher.BlockMode // The following members are to avoid per-packet allocations. seqNumBytes [4]byte packetData []byte macResult []byte // Amount of data we should still read to hide which // verification error triggered. oracleCamouflage uint32 } func newCBCCipher(c cipher.Block, iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { cbc := &cbcCipher{ mac: macModes[algs.MAC].new(macKey), decrypter: cipher.NewCBCDecrypter(c, iv), encrypter: cipher.NewCBCEncrypter(c, iv), packetData: make([]byte, 1024), } if cbc.mac != nil { cbc.macSize = uint32(cbc.mac.Size()) } return cbc, nil } func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err } cbc, err := newCBCCipher(c, iv, key, macKey, algs) if err != nil { return nil, err } return cbc, nil } func newTripleDESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { c, err := des.NewTripleDESCipher(key) if err != nil { return nil, err } cbc, err := newCBCCipher(c, iv, key, macKey, algs) if err != nil { return nil, err } return cbc, nil } func maxUInt32(a, b int) uint32 { if a > b { return uint32(a) } return uint32(b) } const ( cbcMinPacketSizeMultiple = 8 cbcMinPacketSize = 16 cbcMinPaddingSize = 4 ) // cbcError represents a verification error that may leak information. type cbcError string func (e cbcError) Error() string { return string(e) } func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { p, err := c.readPacketLeaky(seqNum, r) if err != nil { if _, ok := err.(cbcError); ok { // Verification error: read a fixed amount of // data, to make distinguishing between // failing MAC and failing length check more // difficult. io.CopyN(ioutil.Discard, r, int64(c.oracleCamouflage)) } } return p, err } func (c *cbcCipher) readPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) { blockSize := c.decrypter.BlockSize() // Read the header, which will include some of the subsequent data in the // case of block ciphers - this is copied back to the payload later. // How many bytes of payload/padding will be read with this first read. firstBlockLength := uint32((prefixLen + blockSize - 1) / blockSize * blockSize) firstBlock := c.packetData[:firstBlockLength] if _, err := io.ReadFull(r, firstBlock); err != nil { return nil, err } c.oracleCamouflage = maxPacket + 4 + c.macSize - firstBlockLength c.decrypter.CryptBlocks(firstBlock, firstBlock) length := binary.BigEndian.Uint32(firstBlock[:4]) if length > maxPacket { return nil, cbcError("ssh: packet too large") } if length+4 < maxUInt32(cbcMinPacketSize, blockSize) { // The minimum size of a packet is 16 (or the cipher block size, whichever // is larger) bytes. return nil, cbcError("ssh: packet too small") } // The length of the packet (including the length field but not the MAC) must // be a multiple of the block size or 8, whichever is larger. if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 { return nil, cbcError("ssh: invalid packet length multiple") } paddingLength := uint32(firstBlock[4]) if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 { return nil, cbcError("ssh: invalid packet length") } // Positions within the c.packetData buffer: macStart := 4 + length paddingStart := macStart - paddingLength // Entire packet size, starting before length, ending at end of mac. entirePacketSize := macStart + c.macSize // Ensure c.packetData is large enough for the entire packet data. if uint32(cap(c.packetData)) < entirePacketSize { // Still need to upsize and copy, but this should be rare at runtime, only // on upsizing the packetData buffer. c.packetData = make([]byte, entirePacketSize) copy(c.packetData, firstBlock) } else { c.packetData = c.packetData[:entirePacketSize] } if n, err := io.ReadFull(r, c.packetData[firstBlockLength:]); err != nil { return nil, err } else { c.oracleCamouflage -= uint32(n) } remainingCrypted := c.packetData[firstBlockLength:macStart] c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted) mac := c.packetData[macStart:] if c.mac != nil { c.mac.Reset() binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) c.mac.Write(c.seqNumBytes[:]) c.mac.Write(c.packetData[:macStart]) c.macResult = c.mac.Sum(c.macResult[:0]) if subtle.ConstantTimeCompare(c.macResult, mac) != 1 { return nil, cbcError("ssh: MAC failure") } } return c.packetData[prefixLen:paddingStart], nil } func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error { effectiveBlockSize := maxUInt32(cbcMinPacketSizeMultiple, c.encrypter.BlockSize()) // Length of encrypted portion of the packet (header, payload, padding). // Enforce minimum padding and packet size. encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize) // Enforce block size. encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize length := encLength - 4 paddingLength := int(length) - (1 + len(packet)) // Overall buffer contains: header, payload, padding, mac. // Space for the MAC is reserved in the capacity but not the slice length. bufferSize := encLength + c.macSize if uint32(cap(c.packetData)) < bufferSize { c.packetData = make([]byte, encLength, bufferSize) } else { c.packetData = c.packetData[:encLength] } p := c.packetData // Packet header. binary.BigEndian.PutUint32(p, length) p = p[4:] p[0] = byte(paddingLength) // Payload. p = p[1:] copy(p, packet) // Padding. p = p[len(packet):] if _, err := io.ReadFull(rand, p); err != nil { return err } if c.mac != nil { c.mac.Reset() binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum) c.mac.Write(c.seqNumBytes[:]) c.mac.Write(c.packetData) // The MAC is now appended into the capacity reserved for it earlier. c.packetData = c.mac.Sum(c.packetData) } c.encrypter.CryptBlocks(c.packetData[:encLength], c.packetData[:encLength]) if _, err := w.Write(c.packetData); err != nil { return err } return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/channel.go����������������������������������������������0000644�0610621�0607500�00000037342�13172163317�023617� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "encoding/binary" "errors" "fmt" "io" "log" "sync" ) const ( minPacketLength = 9 // channelMaxPacket contains the maximum number of bytes that will be // sent in a single packet. As per RFC 4253, section 6.1, 32k is also // the minimum. channelMaxPacket = 1 << 15 // We follow OpenSSH here. channelWindowSize = 64 * channelMaxPacket ) // NewChannel represents an incoming request to a channel. It must either be // accepted for use by calling Accept, or rejected by calling Reject. type NewChannel interface { // Accept accepts the channel creation request. It returns the Channel // and a Go channel containing SSH requests. The Go channel must be // serviced otherwise the Channel will hang. Accept() (Channel, <-chan *Request, error) // Reject rejects the channel creation request. After calling // this, no other methods on the Channel may be called. Reject(reason RejectionReason, message string) error // ChannelType returns the type of the channel, as supplied by the // client. ChannelType() string // ExtraData returns the arbitrary payload for this channel, as supplied // by the client. This data is specific to the channel type. ExtraData() []byte } // A Channel is an ordered, reliable, flow-controlled, duplex stream // that is multiplexed over an SSH connection. type Channel interface { // Read reads up to len(data) bytes from the channel. Read(data []byte) (int, error) // Write writes len(data) bytes to the channel. Write(data []byte) (int, error) // Close signals end of channel use. No data may be sent after this // call. Close() error // CloseWrite signals the end of sending in-band // data. Requests may still be sent, and the other side may // still send data CloseWrite() error // SendRequest sends a channel request. If wantReply is true, // it will wait for a reply and return the result as a // boolean, otherwise the return value will be false. Channel // requests are out-of-band messages so they may be sent even // if the data stream is closed or blocked by flow control. // If the channel is closed before a reply is returned, io.EOF // is returned. SendRequest(name string, wantReply bool, payload []byte) (bool, error) // Stderr returns an io.ReadWriter that writes to this channel // with the extended data type set to stderr. Stderr may // safely be read and written from a different goroutine than // Read and Write respectively. Stderr() io.ReadWriter } // Request is a request sent outside of the normal stream of // data. Requests can either be specific to an SSH channel, or they // can be global. type Request struct { Type string WantReply bool Payload []byte ch *channel mux *mux } // Reply sends a response to a request. It must be called for all requests // where WantReply is true and is a no-op otherwise. The payload argument is // ignored for replies to channel-specific requests. func (r *Request) Reply(ok bool, payload []byte) error { if !r.WantReply { return nil } if r.ch == nil { return r.mux.ackRequest(ok, payload) } return r.ch.ackRequest(ok) } // RejectionReason is an enumeration used when rejecting channel creation // requests. See RFC 4254, section 5.1. type RejectionReason uint32 const ( Prohibited RejectionReason = iota + 1 ConnectionFailed UnknownChannelType ResourceShortage ) // String converts the rejection reason to human readable form. func (r RejectionReason) String() string { switch r { case Prohibited: return "administratively prohibited" case ConnectionFailed: return "connect failed" case UnknownChannelType: return "unknown channel type" case ResourceShortage: return "resource shortage" } return fmt.Sprintf("unknown reason %d", int(r)) } func min(a uint32, b int) uint32 { if a < uint32(b) { return a } return uint32(b) } type channelDirection uint8 const ( channelInbound channelDirection = iota channelOutbound ) // channel is an implementation of the Channel interface that works // with the mux class. type channel struct { // R/O after creation chanType string extraData []byte localId, remoteId uint32 // maxIncomingPayload and maxRemotePayload are the maximum // payload sizes of normal and extended data packets for // receiving and sending, respectively. The wire packet will // be 9 or 13 bytes larger (excluding encryption overhead). maxIncomingPayload uint32 maxRemotePayload uint32 mux *mux // decided is set to true if an accept or reject message has been sent // (for outbound channels) or received (for inbound channels). decided bool // direction contains either channelOutbound, for channels created // locally, or channelInbound, for channels created by the peer. direction channelDirection // Pending internal channel messages. msg chan interface{} // Since requests have no ID, there can be only one request // with WantReply=true outstanding. This lock is held by a // goroutine that has such an outgoing request pending. sentRequestMu sync.Mutex incomingRequests chan *Request sentEOF bool // thread-safe data remoteWin window pending *buffer extPending *buffer // windowMu protects myWindow, the flow-control window. windowMu sync.Mutex myWindow uint32 // writeMu serializes calls to mux.conn.writePacket() and // protects sentClose and packetPool. This mutex must be // different from windowMu, as writePacket can block if there // is a key exchange pending. writeMu sync.Mutex sentClose bool // packetPool has a buffer for each extended channel ID to // save allocations during writes. packetPool map[uint32][]byte } // writePacket sends a packet. If the packet is a channel close, it updates // sentClose. This method takes the lock c.writeMu. func (c *channel) writePacket(packet []byte) error { c.writeMu.Lock() if c.sentClose { c.writeMu.Unlock() return io.EOF } c.sentClose = (packet[0] == msgChannelClose) err := c.mux.conn.writePacket(packet) c.writeMu.Unlock() return err } func (c *channel) sendMessage(msg interface{}) error { if debugMux { log.Printf("send(%d): %#v", c.mux.chanList.offset, msg) } p := Marshal(msg) binary.BigEndian.PutUint32(p[1:], c.remoteId) return c.writePacket(p) } // WriteExtended writes data to a specific extended stream. These streams are // used, for example, for stderr. func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err error) { if c.sentEOF { return 0, io.EOF } // 1 byte message type, 4 bytes remoteId, 4 bytes data length opCode := byte(msgChannelData) headerLength := uint32(9) if extendedCode > 0 { headerLength += 4 opCode = msgChannelExtendedData } c.writeMu.Lock() packet := c.packetPool[extendedCode] // We don't remove the buffer from packetPool, so // WriteExtended calls from different goroutines will be // flagged as errors by the race detector. c.writeMu.Unlock() for len(data) > 0 { space := min(c.maxRemotePayload, len(data)) if space, err = c.remoteWin.reserve(space); err != nil { return n, err } if want := headerLength + space; uint32(cap(packet)) < want { packet = make([]byte, want) } else { packet = packet[:want] } todo := data[:space] packet[0] = opCode binary.BigEndian.PutUint32(packet[1:], c.remoteId) if extendedCode > 0 { binary.BigEndian.PutUint32(packet[5:], uint32(extendedCode)) } binary.BigEndian.PutUint32(packet[headerLength-4:], uint32(len(todo))) copy(packet[headerLength:], todo) if err = c.writePacket(packet); err != nil { return n, err } n += len(todo) data = data[len(todo):] } c.writeMu.Lock() c.packetPool[extendedCode] = packet c.writeMu.Unlock() return n, err } func (c *channel) handleData(packet []byte) error { headerLen := 9 isExtendedData := packet[0] == msgChannelExtendedData if isExtendedData { headerLen = 13 } if len(packet) < headerLen { // malformed data packet return parseError(packet[0]) } var extended uint32 if isExtendedData { extended = binary.BigEndian.Uint32(packet[5:]) } length := binary.BigEndian.Uint32(packet[headerLen-4 : headerLen]) if length == 0 { return nil } if length > c.maxIncomingPayload { // TODO(hanwen): should send Disconnect? return errors.New("ssh: incoming packet exceeds maximum payload size") } data := packet[headerLen:] if length != uint32(len(data)) { return errors.New("ssh: wrong packet length") } c.windowMu.Lock() if c.myWindow < length { c.windowMu.Unlock() // TODO(hanwen): should send Disconnect with reason? return errors.New("ssh: remote side wrote too much") } c.myWindow -= length c.windowMu.Unlock() if extended == 1 { c.extPending.write(data) } else if extended > 0 { // discard other extended data. } else { c.pending.write(data) } return nil } func (c *channel) adjustWindow(n uint32) error { c.windowMu.Lock() // Since myWindow is managed on our side, and can never exceed // the initial window setting, we don't worry about overflow. c.myWindow += uint32(n) c.windowMu.Unlock() return c.sendMessage(windowAdjustMsg{ AdditionalBytes: uint32(n), }) } func (c *channel) ReadExtended(data []byte, extended uint32) (n int, err error) { switch extended { case 1: n, err = c.extPending.Read(data) case 0: n, err = c.pending.Read(data) default: return 0, fmt.Errorf("ssh: extended code %d unimplemented", extended) } if n > 0 { err = c.adjustWindow(uint32(n)) // sendWindowAdjust can return io.EOF if the remote // peer has closed the connection, however we want to // defer forwarding io.EOF to the caller of Read until // the buffer has been drained. if n > 0 && err == io.EOF { err = nil } } return n, err } func (c *channel) close() { c.pending.eof() c.extPending.eof() close(c.msg) close(c.incomingRequests) c.writeMu.Lock() // This is not necessary for a normal channel teardown, but if // there was another error, it is. c.sentClose = true c.writeMu.Unlock() // Unblock writers. c.remoteWin.close() } // responseMessageReceived is called when a success or failure message is // received on a channel to check that such a message is reasonable for the // given channel. func (c *channel) responseMessageReceived() error { if c.direction == channelInbound { return errors.New("ssh: channel response message received on inbound channel") } if c.decided { return errors.New("ssh: duplicate response received for channel") } c.decided = true return nil } func (c *channel) handlePacket(packet []byte) error { switch packet[0] { case msgChannelData, msgChannelExtendedData: return c.handleData(packet) case msgChannelClose: c.sendMessage(channelCloseMsg{PeersId: c.remoteId}) c.mux.chanList.remove(c.localId) c.close() return nil case msgChannelEOF: // RFC 4254 is mute on how EOF affects dataExt messages but // it is logical to signal EOF at the same time. c.extPending.eof() c.pending.eof() return nil } decoded, err := decode(packet) if err != nil { return err } switch msg := decoded.(type) { case *channelOpenFailureMsg: if err := c.responseMessageReceived(); err != nil { return err } c.mux.chanList.remove(msg.PeersId) c.msg <- msg case *channelOpenConfirmMsg: if err := c.responseMessageReceived(); err != nil { return err } if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { return fmt.Errorf("ssh: invalid MaxPacketSize %d from peer", msg.MaxPacketSize) } c.remoteId = msg.MyId c.maxRemotePayload = msg.MaxPacketSize c.remoteWin.add(msg.MyWindow) c.msg <- msg case *windowAdjustMsg: if !c.remoteWin.add(msg.AdditionalBytes) { return fmt.Errorf("ssh: invalid window update for %d bytes", msg.AdditionalBytes) } case *channelRequestMsg: req := Request{ Type: msg.Request, WantReply: msg.WantReply, Payload: msg.RequestSpecificData, ch: c, } c.incomingRequests <- &req default: c.msg <- msg } return nil } func (m *mux) newChannel(chanType string, direction channelDirection, extraData []byte) *channel { ch := &channel{ remoteWin: window{Cond: newCond()}, myWindow: channelWindowSize, pending: newBuffer(), extPending: newBuffer(), direction: direction, incomingRequests: make(chan *Request, chanSize), msg: make(chan interface{}, chanSize), chanType: chanType, extraData: extraData, mux: m, packetPool: make(map[uint32][]byte), } ch.localId = m.chanList.add(ch) return ch } var errUndecided = errors.New("ssh: must Accept or Reject channel") var errDecidedAlready = errors.New("ssh: can call Accept or Reject only once") type extChannel struct { code uint32 ch *channel } func (e *extChannel) Write(data []byte) (n int, err error) { return e.ch.WriteExtended(data, e.code) } func (e *extChannel) Read(data []byte) (n int, err error) { return e.ch.ReadExtended(data, e.code) } func (c *channel) Accept() (Channel, <-chan *Request, error) { if c.decided { return nil, nil, errDecidedAlready } c.maxIncomingPayload = channelMaxPacket confirm := channelOpenConfirmMsg{ PeersId: c.remoteId, MyId: c.localId, MyWindow: c.myWindow, MaxPacketSize: c.maxIncomingPayload, } c.decided = true if err := c.sendMessage(confirm); err != nil { return nil, nil, err } return c, c.incomingRequests, nil } func (ch *channel) Reject(reason RejectionReason, message string) error { if ch.decided { return errDecidedAlready } reject := channelOpenFailureMsg{ PeersId: ch.remoteId, Reason: reason, Message: message, Language: "en", } ch.decided = true return ch.sendMessage(reject) } func (ch *channel) Read(data []byte) (int, error) { if !ch.decided { return 0, errUndecided } return ch.ReadExtended(data, 0) } func (ch *channel) Write(data []byte) (int, error) { if !ch.decided { return 0, errUndecided } return ch.WriteExtended(data, 0) } func (ch *channel) CloseWrite() error { if !ch.decided { return errUndecided } ch.sentEOF = true return ch.sendMessage(channelEOFMsg{ PeersId: ch.remoteId}) } func (ch *channel) Close() error { if !ch.decided { return errUndecided } return ch.sendMessage(channelCloseMsg{ PeersId: ch.remoteId}) } // Extended returns an io.ReadWriter that sends and receives data on the given, // SSH extended stream. Such streams are used, for example, for stderr. func (ch *channel) Extended(code uint32) io.ReadWriter { if !ch.decided { return nil } return &extChannel{code, ch} } func (ch *channel) Stderr() io.ReadWriter { return ch.Extended(1) } func (ch *channel) SendRequest(name string, wantReply bool, payload []byte) (bool, error) { if !ch.decided { return false, errUndecided } if wantReply { ch.sentRequestMu.Lock() defer ch.sentRequestMu.Unlock() } msg := channelRequestMsg{ PeersId: ch.remoteId, Request: name, WantReply: wantReply, RequestSpecificData: payload, } if err := ch.sendMessage(msg); err != nil { return false, err } if wantReply { m, ok := (<-ch.msg) if !ok { return false, io.EOF } switch m.(type) { case *channelRequestFailureMsg: return false, nil case *channelRequestSuccessMsg: return true, nil default: return false, fmt.Errorf("ssh: unexpected response to channel request: %#v", m) } } return false, nil } // ackRequest either sends an ack or nack to the channel request. func (ch *channel) ackRequest(ok bool) error { if !ch.decided { return errUndecided } var msg interface{} if !ok { msg = channelRequestFailureMsg{ PeersId: ch.remoteId, } } else { msg = channelRequestSuccessMsg{ PeersId: ch.remoteId, } } return ch.sendMessage(msg) } func (ch *channel) ChannelType() string { return ch.chanType } func (ch *channel) ExtraData() []byte { return ch.extraData } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/certs_test.go�������������������������������������������0000644�0610621�0607500�00000021106�13172163317�024355� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "crypto/rand" "reflect" "testing" "time" ) // Cert generated by ssh-keygen 6.0p1 Debian-4. // % ssh-keygen -s ca-key -I test user-key const exampleSSHCert = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgb1srW/W3ZDjYAO45xLYAwzHBDLsJ4Ux6ICFIkTjb1LEAAAADAQABAAAAYQCkoR51poH0wE8w72cqSB8Sszx+vAhzcMdCO0wqHTj7UNENHWEXGrU0E0UQekD7U+yhkhtoyjbPOVIP7hNa6aRk/ezdh/iUnCIt4Jt1v3Z1h1P+hA4QuYFMHNB+rmjPwAcAAAAAAAAAAAAAAAEAAAAEdGVzdAAAAAAAAAAAAAAAAP//////////AAAAAAAAAIIAAAAVcGVybWl0LVgxMS1mb3J3YXJkaW5nAAAAAAAAABdwZXJtaXQtYWdlbnQtZm9yd2FyZGluZwAAAAAAAAAWcGVybWl0LXBvcnQtZm9yd2FyZGluZwAAAAAAAAAKcGVybWl0LXB0eQAAAAAAAAAOcGVybWl0LXVzZXItcmMAAAAAAAAAAAAAAHcAAAAHc3NoLXJzYQAAAAMBAAEAAABhANFS2kaktpSGc+CcmEKPyw9mJC4nZKxHKTgLVZeaGbFZOvJTNzBspQHdy7Q1uKSfktxpgjZnksiu/tFF9ngyY2KFoc+U88ya95IZUycBGCUbBQ8+bhDtw/icdDGQD5WnUwAAAG8AAAAHc3NoLXJzYQAAAGC8Y9Z2LQKhIhxf52773XaWrXdxP0t3GBVo4A10vUWiYoAGepr6rQIoGGXFxT4B9Gp+nEBJjOwKDXPrAevow0T9ca8gZN+0ykbhSrXLE5Ao48rqr3zP4O1/9P7e6gp0gw8=` func TestParseCert(t *testing.T) { authKeyBytes := []byte(exampleSSHCert) key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes) if err != nil { t.Fatalf("ParseAuthorizedKey: %v", err) } if len(rest) > 0 { t.Errorf("rest: got %q, want empty", rest) } if _, ok := key.(*Certificate); !ok { t.Fatalf("got %v (%T), want *Certificate", key, key) } marshaled := MarshalAuthorizedKey(key) // Before comparison, remove the trailing newline that // MarshalAuthorizedKey adds. marshaled = marshaled[:len(marshaled)-1] if !bytes.Equal(authKeyBytes, marshaled) { t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes) } } // Cert generated by ssh-keygen OpenSSH_6.8p1 OS X 10.10.3 // % ssh-keygen -s ca -I testcert -O source-address=192.168.1.0/24 -O force-command=/bin/sleep user.pub // user.pub key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMN // Critical Options: // force-command /bin/sleep // source-address 192.168.1.0/24 // Extensions: // permit-X11-forwarding // permit-agent-forwarding // permit-port-forwarding // permit-pty // permit-user-rc const exampleSSHCertWithOptions = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgDyysCJY0XrO1n03EeRRoITnTPdjENFmWDs9X58PP3VUAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMNAAAAAAAAAAAAAAABAAAACHRlc3RjZXJ0AAAAAAAAAAAAAAAA//////////8AAABLAAAADWZvcmNlLWNvbW1hbmQAAAAOAAAACi9iaW4vc2xlZXAAAAAOc291cmNlLWFkZHJlc3MAAAASAAAADjE5Mi4xNjguMS4wLzI0AAAAggAAABVwZXJtaXQtWDExLWZvcndhcmRpbmcAAAAAAAAAF3Blcm1pdC1hZ2VudC1mb3J3YXJkaW5nAAAAAAAAABZwZXJtaXQtcG9ydC1mb3J3YXJkaW5nAAAAAAAAAApwZXJtaXQtcHR5AAAAAAAAAA5wZXJtaXQtdXNlci1yYwAAAAAAAAAAAAABFwAAAAdzc2gtcnNhAAAAAwEAAQAAAQEAwU+c5ui5A8+J/CFpjW8wCa52bEODA808WWQDCSuTG/eMXNf59v9Y8Pk0F1E9dGCosSNyVcB/hacUrc6He+i97+HJCyKavBsE6GDxrjRyxYqAlfcOXi/IVmaUGiO8OQ39d4GHrjToInKvExSUeleQyH4Y4/e27T/pILAqPFL3fyrvMLT5qU9QyIt6zIpa7GBP5+urouNavMprV3zsfIqNBbWypinOQAw823a5wN+zwXnhZrgQiHZ/USG09Y6k98y1dTVz8YHlQVR4D3lpTAsKDKJ5hCH9WU4fdf+lU8OyNGaJ/vz0XNqxcToe1l4numLTnaoSuH89pHryjqurB7lJKwAAAQ8AAAAHc3NoLXJzYQAAAQCaHvUIoPL1zWUHIXLvu96/HU1s/i4CAW2IIEuGgxCUCiFj6vyTyYtgxQxcmbfZf6eaITlS6XJZa7Qq4iaFZh75C1DXTX8labXhRSD4E2t//AIP9MC1rtQC5xo6FmbQ+BoKcDskr+mNACcbRSxs3IL3bwCfWDnIw2WbVox9ZdcthJKk4UoCW4ix4QwdHw7zlddlz++fGEEVhmTbll1SUkycGApPFBsAYRTMupUJcYPIeReBI/m8XfkoMk99bV8ZJQTAd7OekHY2/48Ff53jLmyDjP7kNw1F8OaPtkFs6dGJXta4krmaekPy87j+35In5hFj7yoOqvSbmYUkeX70/GGQ` func TestParseCertWithOptions(t *testing.T) { opts := map[string]string{ "source-address": "192.168.1.0/24", "force-command": "/bin/sleep", } exts := map[string]string{ "permit-X11-forwarding": "", "permit-agent-forwarding": "", "permit-port-forwarding": "", "permit-pty": "", "permit-user-rc": "", } authKeyBytes := []byte(exampleSSHCertWithOptions) key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes) if err != nil { t.Fatalf("ParseAuthorizedKey: %v", err) } if len(rest) > 0 { t.Errorf("rest: got %q, want empty", rest) } cert, ok := key.(*Certificate) if !ok { t.Fatalf("got %v (%T), want *Certificate", key, key) } if !reflect.DeepEqual(cert.CriticalOptions, opts) { t.Errorf("unexpected critical options - got %v, want %v", cert.CriticalOptions, opts) } if !reflect.DeepEqual(cert.Extensions, exts) { t.Errorf("unexpected Extensions - got %v, want %v", cert.Extensions, exts) } marshaled := MarshalAuthorizedKey(key) // Before comparison, remove the trailing newline that // MarshalAuthorizedKey adds. marshaled = marshaled[:len(marshaled)-1] if !bytes.Equal(authKeyBytes, marshaled) { t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes) } } func TestValidateCert(t *testing.T) { key, _, _, _, err := ParseAuthorizedKey([]byte(exampleSSHCert)) if err != nil { t.Fatalf("ParseAuthorizedKey: %v", err) } validCert, ok := key.(*Certificate) if !ok { t.Fatalf("got %v (%T), want *Certificate", key, key) } checker := CertChecker{} checker.IsUserAuthority = func(k PublicKey) bool { return bytes.Equal(k.Marshal(), validCert.SignatureKey.Marshal()) } if err := checker.CheckCert("user", validCert); err != nil { t.Errorf("Unable to validate certificate: %v", err) } invalidCert := &Certificate{ Key: testPublicKeys["rsa"], SignatureKey: testPublicKeys["ecdsa"], ValidBefore: CertTimeInfinity, Signature: &Signature{}, } if err := checker.CheckCert("user", invalidCert); err == nil { t.Error("Invalid cert signature passed validation") } } func TestValidateCertTime(t *testing.T) { cert := Certificate{ ValidPrincipals: []string{"user"}, Key: testPublicKeys["rsa"], ValidAfter: 50, ValidBefore: 100, } cert.SignCert(rand.Reader, testSigners["ecdsa"]) for ts, ok := range map[int64]bool{ 25: false, 50: true, 99: true, 100: false, 125: false, } { checker := CertChecker{ Clock: func() time.Time { return time.Unix(ts, 0) }, } checker.IsUserAuthority = func(k PublicKey) bool { return bytes.Equal(k.Marshal(), testPublicKeys["ecdsa"].Marshal()) } if v := checker.CheckCert("user", &cert); (v == nil) != ok { t.Errorf("Authenticate(%d): %v", ts, v) } } } // TODO(hanwen): tests for // // host keys: // * fallbacks func TestHostKeyCert(t *testing.T) { cert := &Certificate{ ValidPrincipals: []string{"hostname", "hostname.domain", "otherhost"}, Key: testPublicKeys["rsa"], ValidBefore: CertTimeInfinity, CertType: HostCert, } cert.SignCert(rand.Reader, testSigners["ecdsa"]) checker := &CertChecker{ IsHostAuthority: func(p PublicKey, addr string) bool { return addr == "hostname:22" && bytes.Equal(testPublicKeys["ecdsa"].Marshal(), p.Marshal()) }, } certSigner, err := NewCertSigner(cert, testSigners["rsa"]) if err != nil { t.Errorf("NewCertSigner: %v", err) } for _, test := range []struct { addr string succeed bool }{ {addr: "hostname:22", succeed: true}, {addr: "otherhost:22", succeed: false}, // The certificate is valid for 'otherhost' as hostname, but we only recognize the authority of the signer for the address 'hostname:22' {addr: "lasthost:22", succeed: false}, } { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() errc := make(chan error) go func() { conf := ServerConfig{ NoClientAuth: true, } conf.AddHostKey(certSigner) _, _, _, err := NewServerConn(c1, &conf) errc <- err }() config := &ClientConfig{ User: "user", HostKeyCallback: checker.CheckHostKey, } _, _, _, err = NewClientConn(c2, test.addr, config) if (err == nil) != test.succeed { t.Fatalf("NewClientConn(%q): %v", test.addr, err) } err = <-errc if (err == nil) != test.succeed { t.Fatalf("NewServerConn(%q): %v", test.addr, err) } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/certs.go������������������������������������������������0000644�0610621�0607500�00000034244�13172163317�023325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "errors" "fmt" "io" "net" "sort" "time" ) // These constants from [PROTOCOL.certkeys] represent the algorithm names // for certificate types supported by this package. const ( CertAlgoRSAv01 = "ssh-rsa-cert-v01@openssh.com" CertAlgoDSAv01 = "ssh-dss-cert-v01@openssh.com" CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com" CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com" CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com" CertAlgoED25519v01 = "ssh-ed25519-cert-v01@openssh.com" ) // Certificate types distinguish between host and user // certificates. The values can be set in the CertType field of // Certificate. const ( UserCert = 1 HostCert = 2 ) // Signature represents a cryptographic signature. type Signature struct { Format string Blob []byte } // CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore to indicate that // a certificate does not expire. const CertTimeInfinity = 1<<64 - 1 // An Certificate represents an OpenSSH certificate as defined in // [PROTOCOL.certkeys]?rev=1.8. type Certificate struct { Nonce []byte Key PublicKey Serial uint64 CertType uint32 KeyId string ValidPrincipals []string ValidAfter uint64 ValidBefore uint64 Permissions Reserved []byte SignatureKey PublicKey Signature *Signature } // genericCertData holds the key-independent part of the certificate data. // Overall, certificates contain an nonce, public key fields and // key-independent fields. type genericCertData struct { Serial uint64 CertType uint32 KeyId string ValidPrincipals []byte ValidAfter uint64 ValidBefore uint64 CriticalOptions []byte Extensions []byte Reserved []byte SignatureKey []byte Signature []byte } func marshalStringList(namelist []string) []byte { var to []byte for _, name := range namelist { s := struct{ N string }{name} to = append(to, Marshal(&s)...) } return to } type optionsTuple struct { Key string Value []byte } type optionsTupleValue struct { Value string } // serialize a map of critical options or extensions // issue #10569 - per [PROTOCOL.certkeys] and SSH implementation, // we need two length prefixes for a non-empty string value func marshalTuples(tups map[string]string) []byte { keys := make([]string, 0, len(tups)) for key := range tups { keys = append(keys, key) } sort.Strings(keys) var ret []byte for _, key := range keys { s := optionsTuple{Key: key} if value := tups[key]; len(value) > 0 { s.Value = Marshal(&optionsTupleValue{value}) } ret = append(ret, Marshal(&s)...) } return ret } // issue #10569 - per [PROTOCOL.certkeys] and SSH implementation, // we need two length prefixes for a non-empty option value func parseTuples(in []byte) (map[string]string, error) { tups := map[string]string{} var lastKey string var haveLastKey bool for len(in) > 0 { var key, val, extra []byte var ok bool if key, in, ok = parseString(in); !ok { return nil, errShortRead } keyStr := string(key) // according to [PROTOCOL.certkeys], the names must be in // lexical order. if haveLastKey && keyStr <= lastKey { return nil, fmt.Errorf("ssh: certificate options are not in lexical order") } lastKey, haveLastKey = keyStr, true // the next field is a data field, which if non-empty has a string embedded if val, in, ok = parseString(in); !ok { return nil, errShortRead } if len(val) > 0 { val, extra, ok = parseString(val) if !ok { return nil, errShortRead } if len(extra) > 0 { return nil, fmt.Errorf("ssh: unexpected trailing data after certificate option value") } tups[keyStr] = string(val) } else { tups[keyStr] = "" } } return tups, nil } func parseCert(in []byte, privAlgo string) (*Certificate, error) { nonce, rest, ok := parseString(in) if !ok { return nil, errShortRead } key, rest, err := parsePubKey(rest, privAlgo) if err != nil { return nil, err } var g genericCertData if err := Unmarshal(rest, &g); err != nil { return nil, err } c := &Certificate{ Nonce: nonce, Key: key, Serial: g.Serial, CertType: g.CertType, KeyId: g.KeyId, ValidAfter: g.ValidAfter, ValidBefore: g.ValidBefore, } for principals := g.ValidPrincipals; len(principals) > 0; { principal, rest, ok := parseString(principals) if !ok { return nil, errShortRead } c.ValidPrincipals = append(c.ValidPrincipals, string(principal)) principals = rest } c.CriticalOptions, err = parseTuples(g.CriticalOptions) if err != nil { return nil, err } c.Extensions, err = parseTuples(g.Extensions) if err != nil { return nil, err } c.Reserved = g.Reserved k, err := ParsePublicKey(g.SignatureKey) if err != nil { return nil, err } c.SignatureKey = k c.Signature, rest, ok = parseSignatureBody(g.Signature) if !ok || len(rest) > 0 { return nil, errors.New("ssh: signature parse error") } return c, nil } type openSSHCertSigner struct { pub *Certificate signer Signer } // NewCertSigner returns a Signer that signs with the given Certificate, whose // private key is held by signer. It returns an error if the public key in cert // doesn't match the key used by signer. func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) { if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 { return nil, errors.New("ssh: signer and cert have different public key") } return &openSSHCertSigner{cert, signer}, nil } func (s *openSSHCertSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { return s.signer.Sign(rand, data) } func (s *openSSHCertSigner) PublicKey() PublicKey { return s.pub } const sourceAddressCriticalOption = "source-address" // CertChecker does the work of verifying a certificate. Its methods // can be plugged into ClientConfig.HostKeyCallback and // ServerConfig.PublicKeyCallback. For the CertChecker to work, // minimally, the IsAuthority callback should be set. type CertChecker struct { // SupportedCriticalOptions lists the CriticalOptions that the // server application layer understands. These are only used // for user certificates. SupportedCriticalOptions []string // IsUserAuthority should return true if the key is recognized as an // authority for the given user certificate. This allows for // certificates to be signed by other certificates. This must be set // if this CertChecker will be checking user certificates. IsUserAuthority func(auth PublicKey) bool // IsHostAuthority should report whether the key is recognized as // an authority for this host. This allows for certificates to be // signed by other keys, and for those other keys to only be valid // signers for particular hostnames. This must be set if this // CertChecker will be checking host certificates. IsHostAuthority func(auth PublicKey, address string) bool // Clock is used for verifying time stamps. If nil, time.Now // is used. Clock func() time.Time // UserKeyFallback is called when CertChecker.Authenticate encounters a // public key that is not a certificate. It must implement validation // of user keys or else, if nil, all such keys are rejected. UserKeyFallback func(conn ConnMetadata, key PublicKey) (*Permissions, error) // HostKeyFallback is called when CertChecker.CheckHostKey encounters a // public key that is not a certificate. It must implement host key // validation or else, if nil, all such keys are rejected. HostKeyFallback HostKeyCallback // IsRevoked is called for each certificate so that revocation checking // can be implemented. It should return true if the given certificate // is revoked and false otherwise. If nil, no certificates are // considered to have been revoked. IsRevoked func(cert *Certificate) bool } // CheckHostKey checks a host key certificate. This method can be // plugged into ClientConfig.HostKeyCallback. func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error { cert, ok := key.(*Certificate) if !ok { if c.HostKeyFallback != nil { return c.HostKeyFallback(addr, remote, key) } return errors.New("ssh: non-certificate host key") } if cert.CertType != HostCert { return fmt.Errorf("ssh: certificate presented as a host key has type %d", cert.CertType) } if !c.IsHostAuthority(cert.SignatureKey, addr) { return fmt.Errorf("ssh: no authorities for hostname: %v", addr) } hostname, _, err := net.SplitHostPort(addr) if err != nil { return err } // Pass hostname only as principal for host certificates (consistent with OpenSSH) return c.CheckCert(hostname, cert) } // Authenticate checks a user certificate. Authenticate can be used as // a value for ServerConfig.PublicKeyCallback. func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error) { cert, ok := pubKey.(*Certificate) if !ok { if c.UserKeyFallback != nil { return c.UserKeyFallback(conn, pubKey) } return nil, errors.New("ssh: normal key pairs not accepted") } if cert.CertType != UserCert { return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType) } if !c.IsUserAuthority(cert.SignatureKey) { return nil, fmt.Errorf("ssh: certificate signed by unrecognized authority") } if err := c.CheckCert(conn.User(), cert); err != nil { return nil, err } return &cert.Permissions, nil } // CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and // the signature of the certificate. func (c *CertChecker) CheckCert(principal string, cert *Certificate) error { if c.IsRevoked != nil && c.IsRevoked(cert) { return fmt.Errorf("ssh: certicate serial %d revoked", cert.Serial) } for opt, _ := range cert.CriticalOptions { // sourceAddressCriticalOption will be enforced by // serverAuthenticate if opt == sourceAddressCriticalOption { continue } found := false for _, supp := range c.SupportedCriticalOptions { if supp == opt { found = true break } } if !found { return fmt.Errorf("ssh: unsupported critical option %q in certificate", opt) } } if len(cert.ValidPrincipals) > 0 { // By default, certs are valid for all users/hosts. found := false for _, p := range cert.ValidPrincipals { if p == principal { found = true break } } if !found { return fmt.Errorf("ssh: principal %q not in the set of valid principals for given certificate: %q", principal, cert.ValidPrincipals) } } clock := c.Clock if clock == nil { clock = time.Now } unixNow := clock().Unix() if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) { return fmt.Errorf("ssh: cert is not yet valid") } if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) { return fmt.Errorf("ssh: cert has expired") } if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil { return fmt.Errorf("ssh: certificate signature does not verify") } return nil } // SignCert sets c.SignatureKey to the authority's public key and stores a // Signature, by authority, in the certificate. func (c *Certificate) SignCert(rand io.Reader, authority Signer) error { c.Nonce = make([]byte, 32) if _, err := io.ReadFull(rand, c.Nonce); err != nil { return err } c.SignatureKey = authority.PublicKey() sig, err := authority.Sign(rand, c.bytesForSigning()) if err != nil { return err } c.Signature = sig return nil } var certAlgoNames = map[string]string{ KeyAlgoRSA: CertAlgoRSAv01, KeyAlgoDSA: CertAlgoDSAv01, KeyAlgoECDSA256: CertAlgoECDSA256v01, KeyAlgoECDSA384: CertAlgoECDSA384v01, KeyAlgoECDSA521: CertAlgoECDSA521v01, KeyAlgoED25519: CertAlgoED25519v01, } // certToPrivAlgo returns the underlying algorithm for a certificate algorithm. // Panics if a non-certificate algorithm is passed. func certToPrivAlgo(algo string) string { for privAlgo, pubAlgo := range certAlgoNames { if pubAlgo == algo { return privAlgo } } panic("unknown cert algorithm") } func (cert *Certificate) bytesForSigning() []byte { c2 := *cert c2.Signature = nil out := c2.Marshal() // Drop trailing signature length. return out[:len(out)-4] } // Marshal serializes c into OpenSSH's wire format. It is part of the // PublicKey interface. func (c *Certificate) Marshal() []byte { generic := genericCertData{ Serial: c.Serial, CertType: c.CertType, KeyId: c.KeyId, ValidPrincipals: marshalStringList(c.ValidPrincipals), ValidAfter: uint64(c.ValidAfter), ValidBefore: uint64(c.ValidBefore), CriticalOptions: marshalTuples(c.CriticalOptions), Extensions: marshalTuples(c.Extensions), Reserved: c.Reserved, SignatureKey: c.SignatureKey.Marshal(), } if c.Signature != nil { generic.Signature = Marshal(c.Signature) } genericBytes := Marshal(&generic) keyBytes := c.Key.Marshal() _, keyBytes, _ = parseString(keyBytes) prefix := Marshal(&struct { Name string Nonce []byte Key []byte `ssh:"rest"` }{c.Type(), c.Nonce, keyBytes}) result := make([]byte, 0, len(prefix)+len(genericBytes)) result = append(result, prefix...) result = append(result, genericBytes...) return result } // Type returns the key name. It is part of the PublicKey interface. func (c *Certificate) Type() string { algo, ok := certAlgoNames[c.Key.Type()] if !ok { panic("unknown cert key type " + c.Key.Type()) } return algo } // Verify verifies a signature against the certificate's public // key. It is part of the PublicKey interface. func (c *Certificate) Verify(data []byte, sig *Signature) error { return c.Key.Verify(data, sig) } func parseSignatureBody(in []byte) (out *Signature, rest []byte, ok bool) { format, in, ok := parseString(in) if !ok { return } out = &Signature{ Format: string(format), } if out.Blob, in, ok = parseString(in); !ok { return } return out, in, ok } func parseSignature(in []byte) (out *Signature, rest []byte, ok bool) { sigBytes, rest, ok := parseString(in) if !ok { return } out, trailing, ok := parseSignatureBody(sigBytes) if !ok || len(trailing) > 0 { return nil, nil, false } return } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/buffer_test.go������������������������������������������0000644�0610621�0607500�00000004254�13172163317�024513� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "io" "testing" ) var alphabet = []byte("abcdefghijklmnopqrstuvwxyz") func TestBufferReadwrite(t *testing.T) { b := newBuffer() b.write(alphabet[:10]) r, _ := b.Read(make([]byte, 10)) if r != 10 { t.Fatalf("Expected written == read == 10, written: 10, read %d", r) } b = newBuffer() b.write(alphabet[:5]) r, _ = b.Read(make([]byte, 10)) if r != 5 { t.Fatalf("Expected written == read == 5, written: 5, read %d", r) } b = newBuffer() b.write(alphabet[:10]) r, _ = b.Read(make([]byte, 5)) if r != 5 { t.Fatalf("Expected written == 10, read == 5, written: 10, read %d", r) } b = newBuffer() b.write(alphabet[:5]) b.write(alphabet[5:15]) r, _ = b.Read(make([]byte, 10)) r2, _ := b.Read(make([]byte, 10)) if r != 10 || r2 != 5 || 15 != r+r2 { t.Fatal("Expected written == read == 15") } } func TestBufferClose(t *testing.T) { b := newBuffer() b.write(alphabet[:10]) b.eof() _, err := b.Read(make([]byte, 5)) if err != nil { t.Fatal("expected read of 5 to not return EOF") } b = newBuffer() b.write(alphabet[:10]) b.eof() r, err := b.Read(make([]byte, 5)) r2, err2 := b.Read(make([]byte, 10)) if r != 5 || r2 != 5 || err != nil || err2 != nil { t.Fatal("expected reads of 5 and 5") } b = newBuffer() b.write(alphabet[:10]) b.eof() r, err = b.Read(make([]byte, 5)) r2, err2 = b.Read(make([]byte, 10)) r3, err3 := b.Read(make([]byte, 10)) if r != 5 || r2 != 5 || r3 != 0 || err != nil || err2 != nil || err3 != io.EOF { t.Fatal("expected reads of 5 and 5 and 0, with EOF") } b = newBuffer() b.write(make([]byte, 5)) b.write(make([]byte, 10)) b.eof() r, err = b.Read(make([]byte, 9)) r2, err2 = b.Read(make([]byte, 3)) r3, err3 = b.Read(make([]byte, 3)) r4, err4 := b.Read(make([]byte, 10)) if err != nil || err2 != nil || err3 != nil || err4 != io.EOF { t.Fatalf("Expected EOF on forth read only, err=%v, err2=%v, err3=%v, err4=%v", err, err2, err3, err4) } if r != 9 || r2 != 3 || r3 != 3 || r4 != 0 { t.Fatal("Expected written == read == 15", r, r2, r3, r4) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/buffer.go�����������������������������������������������0000644�0610621�0607500�00000004204�13172163317�023447� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "io" "sync" ) // buffer provides a linked list buffer for data exchange // between producer and consumer. Theoretically the buffer is // of unlimited capacity as it does no allocation of its own. type buffer struct { // protects concurrent access to head, tail and closed *sync.Cond head *element // the buffer that will be read first tail *element // the buffer that will be read last closed bool } // An element represents a single link in a linked list. type element struct { buf []byte next *element } // newBuffer returns an empty buffer that is not closed. func newBuffer() *buffer { e := new(element) b := &buffer{ Cond: newCond(), head: e, tail: e, } return b } // write makes buf available for Read to receive. // buf must not be modified after the call to write. func (b *buffer) write(buf []byte) { b.Cond.L.Lock() e := &element{buf: buf} b.tail.next = e b.tail = e b.Cond.Signal() b.Cond.L.Unlock() } // eof closes the buffer. Reads from the buffer once all // the data has been consumed will receive io.EOF. func (b *buffer) eof() { b.Cond.L.Lock() b.closed = true b.Cond.Signal() b.Cond.L.Unlock() } // Read reads data from the internal buffer in buf. Reads will block // if no data is available, or until the buffer is closed. func (b *buffer) Read(buf []byte) (n int, err error) { b.Cond.L.Lock() defer b.Cond.L.Unlock() for len(buf) > 0 { // if there is data in b.head, copy it if len(b.head.buf) > 0 { r := copy(buf, b.head.buf) buf, b.head.buf = buf[r:], b.head.buf[r:] n += r continue } // if there is a next buffer, make it the head if len(b.head.buf) == 0 && b.head != b.tail { b.head = b.head.next continue } // if at least one byte has been copied, return if n > 0 { break } // if nothing was read, and there is nothing outstanding // check to see if the buffer is closed. if b.closed { err = io.EOF break } // out of buffers, wait for producer b.Cond.Wait() } return } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/benchmark_test.go���������������������������������������0000644�0610621�0607500�00000004300�13172163317�025164� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "errors" "io" "net" "testing" ) type server struct { *ServerConn chans <-chan NewChannel } func newServer(c net.Conn, conf *ServerConfig) (*server, error) { sconn, chans, reqs, err := NewServerConn(c, conf) if err != nil { return nil, err } go DiscardRequests(reqs) return &server{sconn, chans}, nil } func (s *server) Accept() (NewChannel, error) { n, ok := <-s.chans if !ok { return nil, io.EOF } return n, nil } func sshPipe() (Conn, *server, error) { c1, c2, err := netPipe() if err != nil { return nil, nil, err } clientConf := ClientConfig{ User: "user", } serverConf := ServerConfig{ NoClientAuth: true, } serverConf.AddHostKey(testSigners["ecdsa"]) done := make(chan *server, 1) go func() { server, err := newServer(c2, &serverConf) if err != nil { done <- nil } done <- server }() client, _, reqs, err := NewClientConn(c1, "", &clientConf) if err != nil { return nil, nil, err } server := <-done if server == nil { return nil, nil, errors.New("server handshake failed.") } go DiscardRequests(reqs) return client, server, nil } func BenchmarkEndToEnd(b *testing.B) { b.StopTimer() client, server, err := sshPipe() if err != nil { b.Fatalf("sshPipe: %v", err) } defer client.Close() defer server.Close() size := (1 << 20) input := make([]byte, size) output := make([]byte, size) b.SetBytes(int64(size)) done := make(chan int, 1) go func() { newCh, err := server.Accept() if err != nil { b.Fatalf("Client: %v", err) } ch, incoming, err := newCh.Accept() go DiscardRequests(incoming) for i := 0; i < b.N; i++ { if _, err := io.ReadFull(ch, output); err != nil { b.Fatalf("ReadFull: %v", err) } } ch.Close() done <- 1 }() ch, in, err := client.OpenChannel("speed", nil) if err != nil { b.Fatalf("OpenChannel: %v", err) } go DiscardRequests(in) b.ResetTimer() b.StartTimer() for i := 0; i < b.N; i++ { if _, err := ch.Write(input); err != nil { b.Fatalf("WriteFull: %v", err) } } ch.Close() b.StopTimer() <-done } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022745� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/testdata_test.go����������������������������������0000644�0610621�0607500�00000004262�13172163317�026150� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: // ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three // instances. package agent import ( "crypto/rand" "fmt" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/testdata" ) var ( testPrivateKeys map[string]interface{} testSigners map[string]ssh.Signer testPublicKeys map[string]ssh.PublicKey ) func init() { var err error n := len(testdata.PEMBytes) testPrivateKeys = make(map[string]interface{}, n) testSigners = make(map[string]ssh.Signer, n) testPublicKeys = make(map[string]ssh.PublicKey, n) for t, k := range testdata.PEMBytes { testPrivateKeys[t], err = ssh.ParseRawPrivateKey(k) if err != nil { panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) } testSigners[t], err = ssh.NewSignerFromKey(testPrivateKeys[t]) if err != nil { panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) } testPublicKeys[t] = testSigners[t].PublicKey() } // Create a cert and sign it for use in tests. testCert := &ssh.Certificate{ Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage ValidAfter: 0, // unix epoch ValidBefore: ssh.CertTimeInfinity, // The end of currently representable time. Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil Key: testPublicKeys["ecdsa"], SignatureKey: testPublicKeys["rsa"], Permissions: ssh.Permissions{ CriticalOptions: map[string]string{}, Extensions: map[string]string{}, }, } testCert.SignCert(rand.Reader, testSigners["rsa"]) testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] testSigners["cert"], err = ssh.NewCertSigner(testCert, testSigners["ecdsa"]) if err != nil { panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/server_test.go������������������������������������0000644�0610621�0607500�00000014373�13172163317�025651� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent import ( "crypto" "crypto/rand" "fmt" pseudorand "math/rand" "reflect" "strings" "testing" "golang.org/x/crypto/ssh" ) func TestServer(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() client := NewClient(c1) go ServeAgent(NewKeyring(), c2) testAgentInterface(t, client, testPrivateKeys["rsa"], nil, 0) } func TestLockServer(t *testing.T) { testLockAgent(NewKeyring(), t) } func TestSetupForwardAgent(t *testing.T) { a, b, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer a.Close() defer b.Close() _, socket, cleanup := startOpenSSHAgent(t) defer cleanup() serverConf := ssh.ServerConfig{ NoClientAuth: true, } serverConf.AddHostKey(testSigners["rsa"]) incoming := make(chan *ssh.ServerConn, 1) go func() { conn, _, _, err := ssh.NewServerConn(a, &serverConf) if err != nil { t.Fatalf("Server: %v", err) } incoming <- conn }() conf := ssh.ClientConfig{ HostKeyCallback: ssh.InsecureIgnoreHostKey(), } conn, chans, reqs, err := ssh.NewClientConn(b, "", &conf) if err != nil { t.Fatalf("NewClientConn: %v", err) } client := ssh.NewClient(conn, chans, reqs) if err := ForwardToRemote(client, socket); err != nil { t.Fatalf("SetupForwardAgent: %v", err) } server := <-incoming ch, reqs, err := server.OpenChannel(channelType, nil) if err != nil { t.Fatalf("OpenChannel(%q): %v", channelType, err) } go ssh.DiscardRequests(reqs) agentClient := NewClient(ch) testAgentInterface(t, agentClient, testPrivateKeys["rsa"], nil, 0) conn.Close() } func TestV1ProtocolMessages(t *testing.T) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer c1.Close() defer c2.Close() c := NewClient(c1) go ServeAgent(NewKeyring(), c2) testV1ProtocolMessages(t, c.(*client)) } func testV1ProtocolMessages(t *testing.T, c *client) { reply, err := c.call([]byte{agentRequestV1Identities}) if err != nil { t.Fatalf("v1 request all failed: %v", err) } if msg, ok := reply.(*agentV1IdentityMsg); !ok || msg.Numkeys != 0 { t.Fatalf("invalid request all response: %#v", reply) } reply, err = c.call([]byte{agentRemoveAllV1Identities}) if err != nil { t.Fatalf("v1 remove all failed: %v", err) } if _, ok := reply.(*successAgentMsg); !ok { t.Fatalf("invalid remove all response: %#v", reply) } } func verifyKey(sshAgent Agent) error { keys, err := sshAgent.List() if err != nil { return fmt.Errorf("listing keys: %v", err) } if len(keys) != 1 { return fmt.Errorf("bad number of keys found. expected 1, got %d", len(keys)) } buf := make([]byte, 128) if _, err := rand.Read(buf); err != nil { return fmt.Errorf("rand: %v", err) } sig, err := sshAgent.Sign(keys[0], buf) if err != nil { return fmt.Errorf("sign: %v", err) } if err := keys[0].Verify(buf, sig); err != nil { return fmt.Errorf("verify: %v", err) } return nil } func addKeyToAgent(key crypto.PrivateKey) error { sshAgent := NewKeyring() if err := sshAgent.Add(AddedKey{PrivateKey: key}); err != nil { return fmt.Errorf("add: %v", err) } return verifyKey(sshAgent) } func TestKeyTypes(t *testing.T) { for k, v := range testPrivateKeys { if err := addKeyToAgent(v); err != nil { t.Errorf("error adding key type %s, %v", k, err) } if err := addCertToAgentSock(v, nil); err != nil { t.Errorf("error adding key type %s, %v", k, err) } } } func addCertToAgentSock(key crypto.PrivateKey, cert *ssh.Certificate) error { a, b, err := netPipe() if err != nil { return err } agentServer := NewKeyring() go ServeAgent(agentServer, a) agentClient := NewClient(b) if err := agentClient.Add(AddedKey{PrivateKey: key, Certificate: cert}); err != nil { return fmt.Errorf("add: %v", err) } return verifyKey(agentClient) } func addCertToAgent(key crypto.PrivateKey, cert *ssh.Certificate) error { sshAgent := NewKeyring() if err := sshAgent.Add(AddedKey{PrivateKey: key, Certificate: cert}); err != nil { return fmt.Errorf("add: %v", err) } return verifyKey(sshAgent) } func TestCertTypes(t *testing.T) { for keyType, key := range testPublicKeys { cert := &ssh.Certificate{ ValidPrincipals: []string{"gopher1"}, ValidAfter: 0, ValidBefore: ssh.CertTimeInfinity, Key: key, Serial: 1, CertType: ssh.UserCert, SignatureKey: testPublicKeys["rsa"], Permissions: ssh.Permissions{ CriticalOptions: map[string]string{}, Extensions: map[string]string{}, }, } if err := cert.SignCert(rand.Reader, testSigners["rsa"]); err != nil { t.Fatalf("signcert: %v", err) } if err := addCertToAgent(testPrivateKeys[keyType], cert); err != nil { t.Fatalf("%v", err) } if err := addCertToAgentSock(testPrivateKeys[keyType], cert); err != nil { t.Fatalf("%v", err) } } } func TestParseConstraints(t *testing.T) { // Test LifetimeSecs var msg = constrainLifetimeAgentMsg{pseudorand.Uint32()} lifetimeSecs, _, _, err := parseConstraints(ssh.Marshal(msg)) if err != nil { t.Fatalf("parseConstraints: %v", err) } if lifetimeSecs != msg.LifetimeSecs { t.Errorf("got lifetime %v, want %v", lifetimeSecs, msg.LifetimeSecs) } // Test ConfirmBeforeUse _, confirmBeforeUse, _, err := parseConstraints([]byte{agentConstrainConfirm}) if err != nil { t.Fatalf("%v", err) } if !confirmBeforeUse { t.Error("got comfirmBeforeUse == false") } // Test ConstraintExtensions var data []byte var expect []ConstraintExtension for i := 0; i < 10; i++ { var ext = ConstraintExtension{ ExtensionName: fmt.Sprintf("name%d", i), ExtensionDetails: []byte(fmt.Sprintf("details: %d", i)), } expect = append(expect, ext) data = append(data, agentConstrainExtension) data = append(data, ssh.Marshal(ext)...) } _, _, extensions, err := parseConstraints(data) if err != nil { t.Fatalf("%v", err) } if !reflect.DeepEqual(expect, extensions) { t.Errorf("got extension %v, want %v", extensions, expect) } // Test Unknown Constraint _, _, _, err = parseConstraints([]byte{128}) if err == nil || !strings.Contains(err.Error(), "unknown constraint") { t.Errorf("unexpected error: %v", err) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/server.go�����������������������������������������0000644�0610621�0607500�00000027566�13172163317�024622� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent import ( "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" "crypto/rsa" "encoding/binary" "errors" "fmt" "io" "log" "math/big" "golang.org/x/crypto/ed25519" "golang.org/x/crypto/ssh" ) // Server wraps an Agent and uses it to implement the agent side of // the SSH-agent, wire protocol. type server struct { agent Agent } func (s *server) processRequestBytes(reqData []byte) []byte { rep, err := s.processRequest(reqData) if err != nil { if err != errLocked { // TODO(hanwen): provide better logging interface? log.Printf("agent %d: %v", reqData[0], err) } return []byte{agentFailure} } if err == nil && rep == nil { return []byte{agentSuccess} } return ssh.Marshal(rep) } func marshalKey(k *Key) []byte { var record struct { Blob []byte Comment string } record.Blob = k.Marshal() record.Comment = k.Comment return ssh.Marshal(&record) } // See [PROTOCOL.agent], section 2.5.1. const agentV1IdentitiesAnswer = 2 type agentV1IdentityMsg struct { Numkeys uint32 `sshtype:"2"` } type agentRemoveIdentityMsg struct { KeyBlob []byte `sshtype:"18"` } type agentLockMsg struct { Passphrase []byte `sshtype:"22"` } type agentUnlockMsg struct { Passphrase []byte `sshtype:"23"` } func (s *server) processRequest(data []byte) (interface{}, error) { switch data[0] { case agentRequestV1Identities: return &agentV1IdentityMsg{0}, nil case agentRemoveAllV1Identities: return nil, nil case agentRemoveIdentity: var req agentRemoveIdentityMsg if err := ssh.Unmarshal(data, &req); err != nil { return nil, err } var wk wireKey if err := ssh.Unmarshal(req.KeyBlob, &wk); err != nil { return nil, err } return nil, s.agent.Remove(&Key{Format: wk.Format, Blob: req.KeyBlob}) case agentRemoveAllIdentities: return nil, s.agent.RemoveAll() case agentLock: var req agentLockMsg if err := ssh.Unmarshal(data, &req); err != nil { return nil, err } return nil, s.agent.Lock(req.Passphrase) case agentUnlock: var req agentUnlockMsg if err := ssh.Unmarshal(data, &req); err != nil { return nil, err } return nil, s.agent.Unlock(req.Passphrase) case agentSignRequest: var req signRequestAgentMsg if err := ssh.Unmarshal(data, &req); err != nil { return nil, err } var wk wireKey if err := ssh.Unmarshal(req.KeyBlob, &wk); err != nil { return nil, err } k := &Key{ Format: wk.Format, Blob: req.KeyBlob, } sig, err := s.agent.Sign(k, req.Data) // TODO(hanwen): flags. if err != nil { return nil, err } return &signResponseAgentMsg{SigBlob: ssh.Marshal(sig)}, nil case agentRequestIdentities: keys, err := s.agent.List() if err != nil { return nil, err } rep := identitiesAnswerAgentMsg{ NumKeys: uint32(len(keys)), } for _, k := range keys { rep.Keys = append(rep.Keys, marshalKey(k)...) } return rep, nil case agentAddIdConstrained, agentAddIdentity: return nil, s.insertIdentity(data) } return nil, fmt.Errorf("unknown opcode %d", data[0]) } func parseConstraints(constraints []byte) (lifetimeSecs uint32, confirmBeforeUse bool, extensions []ConstraintExtension, err error) { for len(constraints) != 0 { switch constraints[0] { case agentConstrainLifetime: lifetimeSecs = binary.BigEndian.Uint32(constraints[1:5]) constraints = constraints[5:] case agentConstrainConfirm: confirmBeforeUse = true constraints = constraints[1:] case agentConstrainExtension: var msg constrainExtensionAgentMsg if err = ssh.Unmarshal(constraints, &msg); err != nil { return 0, false, nil, err } extensions = append(extensions, ConstraintExtension{ ExtensionName: msg.ExtensionName, ExtensionDetails: msg.ExtensionDetails, }) constraints = msg.Rest default: return 0, false, nil, fmt.Errorf("unknown constraint type: %d", constraints[0]) } } return } func setConstraints(key *AddedKey, constraintBytes []byte) error { lifetimeSecs, confirmBeforeUse, constraintExtensions, err := parseConstraints(constraintBytes) if err != nil { return err } key.LifetimeSecs = lifetimeSecs key.ConfirmBeforeUse = confirmBeforeUse key.ConstraintExtensions = constraintExtensions return nil } func parseRSAKey(req []byte) (*AddedKey, error) { var k rsaKeyMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } if k.E.BitLen() > 30 { return nil, errors.New("agent: RSA public exponent too large") } priv := &rsa.PrivateKey{ PublicKey: rsa.PublicKey{ E: int(k.E.Int64()), N: k.N, }, D: k.D, Primes: []*big.Int{k.P, k.Q}, } priv.Precompute() addedKey := &AddedKey{PrivateKey: priv, Comment: k.Comments} if err := setConstraints(addedKey, k.Constraints); err != nil { return nil, err } return addedKey, nil } func parseEd25519Key(req []byte) (*AddedKey, error) { var k ed25519KeyMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } priv := ed25519.PrivateKey(k.Priv) addedKey := &AddedKey{PrivateKey: &priv, Comment: k.Comments} if err := setConstraints(addedKey, k.Constraints); err != nil { return nil, err } return addedKey, nil } func parseDSAKey(req []byte) (*AddedKey, error) { var k dsaKeyMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } priv := &dsa.PrivateKey{ PublicKey: dsa.PublicKey{ Parameters: dsa.Parameters{ P: k.P, Q: k.Q, G: k.G, }, Y: k.Y, }, X: k.X, } addedKey := &AddedKey{PrivateKey: priv, Comment: k.Comments} if err := setConstraints(addedKey, k.Constraints); err != nil { return nil, err } return addedKey, nil } func unmarshalECDSA(curveName string, keyBytes []byte, privScalar *big.Int) (priv *ecdsa.PrivateKey, err error) { priv = &ecdsa.PrivateKey{ D: privScalar, } switch curveName { case "nistp256": priv.Curve = elliptic.P256() case "nistp384": priv.Curve = elliptic.P384() case "nistp521": priv.Curve = elliptic.P521() default: return nil, fmt.Errorf("agent: unknown curve %q", curveName) } priv.X, priv.Y = elliptic.Unmarshal(priv.Curve, keyBytes) if priv.X == nil || priv.Y == nil { return nil, errors.New("agent: point not on curve") } return priv, nil } func parseEd25519Cert(req []byte) (*AddedKey, error) { var k ed25519CertMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } pubKey, err := ssh.ParsePublicKey(k.CertBytes) if err != nil { return nil, err } priv := ed25519.PrivateKey(k.Priv) cert, ok := pubKey.(*ssh.Certificate) if !ok { return nil, errors.New("agent: bad ED25519 certificate") } addedKey := &AddedKey{PrivateKey: &priv, Certificate: cert, Comment: k.Comments} if err := setConstraints(addedKey, k.Constraints); err != nil { return nil, err } return addedKey, nil } func parseECDSAKey(req []byte) (*AddedKey, error) { var k ecdsaKeyMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } priv, err := unmarshalECDSA(k.Curve, k.KeyBytes, k.D) if err != nil { return nil, err } addedKey := &AddedKey{PrivateKey: priv, Comment: k.Comments} if err := setConstraints(addedKey, k.Constraints); err != nil { return nil, err } return addedKey, nil } func parseRSACert(req []byte) (*AddedKey, error) { var k rsaCertMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } pubKey, err := ssh.ParsePublicKey(k.CertBytes) if err != nil { return nil, err } cert, ok := pubKey.(*ssh.Certificate) if !ok { return nil, errors.New("agent: bad RSA certificate") } // An RSA publickey as marshaled by rsaPublicKey.Marshal() in keys.go var rsaPub struct { Name string E *big.Int N *big.Int } if err := ssh.Unmarshal(cert.Key.Marshal(), &rsaPub); err != nil { return nil, fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err) } if rsaPub.E.BitLen() > 30 { return nil, errors.New("agent: RSA public exponent too large") } priv := rsa.PrivateKey{ PublicKey: rsa.PublicKey{ E: int(rsaPub.E.Int64()), N: rsaPub.N, }, D: k.D, Primes: []*big.Int{k.Q, k.P}, } priv.Precompute() addedKey := &AddedKey{PrivateKey: &priv, Certificate: cert, Comment: k.Comments} if err := setConstraints(addedKey, k.Constraints); err != nil { return nil, err } return addedKey, nil } func parseDSACert(req []byte) (*AddedKey, error) { var k dsaCertMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } pubKey, err := ssh.ParsePublicKey(k.CertBytes) if err != nil { return nil, err } cert, ok := pubKey.(*ssh.Certificate) if !ok { return nil, errors.New("agent: bad DSA certificate") } // A DSA publickey as marshaled by dsaPublicKey.Marshal() in keys.go var w struct { Name string P, Q, G, Y *big.Int } if err := ssh.Unmarshal(cert.Key.Marshal(), &w); err != nil { return nil, fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err) } priv := &dsa.PrivateKey{ PublicKey: dsa.PublicKey{ Parameters: dsa.Parameters{ P: w.P, Q: w.Q, G: w.G, }, Y: w.Y, }, X: k.X, } addedKey := &AddedKey{PrivateKey: priv, Certificate: cert, Comment: k.Comments} if err := setConstraints(addedKey, k.Constraints); err != nil { return nil, err } return addedKey, nil } func parseECDSACert(req []byte) (*AddedKey, error) { var k ecdsaCertMsg if err := ssh.Unmarshal(req, &k); err != nil { return nil, err } pubKey, err := ssh.ParsePublicKey(k.CertBytes) if err != nil { return nil, err } cert, ok := pubKey.(*ssh.Certificate) if !ok { return nil, errors.New("agent: bad ECDSA certificate") } // An ECDSA publickey as marshaled by ecdsaPublicKey.Marshal() in keys.go var ecdsaPub struct { Name string ID string Key []byte } if err := ssh.Unmarshal(cert.Key.Marshal(), &ecdsaPub); err != nil { return nil, err } priv, err := unmarshalECDSA(ecdsaPub.ID, ecdsaPub.Key, k.D) if err != nil { return nil, err } addedKey := &AddedKey{PrivateKey: priv, Certificate: cert, Comment: k.Comments} if err := setConstraints(addedKey, k.Constraints); err != nil { return nil, err } return addedKey, nil } func (s *server) insertIdentity(req []byte) error { var record struct { Type string `sshtype:"17|25"` Rest []byte `ssh:"rest"` } if err := ssh.Unmarshal(req, &record); err != nil { return err } var addedKey *AddedKey var err error switch record.Type { case ssh.KeyAlgoRSA: addedKey, err = parseRSAKey(req) case ssh.KeyAlgoDSA: addedKey, err = parseDSAKey(req) case ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521: addedKey, err = parseECDSAKey(req) case ssh.KeyAlgoED25519: addedKey, err = parseEd25519Key(req) case ssh.CertAlgoRSAv01: addedKey, err = parseRSACert(req) case ssh.CertAlgoDSAv01: addedKey, err = parseDSACert(req) case ssh.CertAlgoECDSA256v01, ssh.CertAlgoECDSA384v01, ssh.CertAlgoECDSA521v01: addedKey, err = parseECDSACert(req) case ssh.CertAlgoED25519v01: addedKey, err = parseEd25519Cert(req) default: return fmt.Errorf("agent: not implemented: %q", record.Type) } if err != nil { return err } return s.agent.Add(*addedKey) } // ServeAgent serves the agent protocol on the given connection. It // returns when an I/O error occurs. func ServeAgent(agent Agent, c io.ReadWriter) error { s := &server{agent} var length [4]byte for { if _, err := io.ReadFull(c, length[:]); err != nil { return err } l := binary.BigEndian.Uint32(length[:]) if l > maxAgentResponseBytes { // We also cap requests. return fmt.Errorf("agent: request too large: %d", l) } req := make([]byte, l) if _, err := io.ReadFull(c, req); err != nil { return err } repData := s.processRequestBytes(req) if len(repData) > maxAgentResponseBytes { return fmt.Errorf("agent: reply too large: %d bytes", len(repData)) } binary.BigEndian.PutUint32(length[:], uint32(len(repData))) if _, err := c.Write(length[:]); err != nil { return err } if _, err := c.Write(repData); err != nil { return err } } } ������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/keyring_test.go�����������������������������������0000644�0610621�0607500�00000003462�13172163317�026010� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent import "testing" func addTestKey(t *testing.T, a Agent, keyName string) { err := a.Add(AddedKey{ PrivateKey: testPrivateKeys[keyName], Comment: keyName, }) if err != nil { t.Fatalf("failed to add key %q: %v", keyName, err) } } func removeTestKey(t *testing.T, a Agent, keyName string) { err := a.Remove(testPublicKeys[keyName]) if err != nil { t.Fatalf("failed to remove key %q: %v", keyName, err) } } func validateListedKeys(t *testing.T, a Agent, expectedKeys []string) { listedKeys, err := a.List() if err != nil { t.Fatalf("failed to list keys: %v", err) return } actualKeys := make(map[string]bool) for _, key := range listedKeys { actualKeys[key.Comment] = true } matchedKeys := make(map[string]bool) for _, expectedKey := range expectedKeys { if !actualKeys[expectedKey] { t.Fatalf("expected key %q, but was not found", expectedKey) } else { matchedKeys[expectedKey] = true } } for actualKey := range actualKeys { if !matchedKeys[actualKey] { t.Fatalf("key %q was found, but was not expected", actualKey) } } } func TestKeyringAddingAndRemoving(t *testing.T) { keyNames := []string{"dsa", "ecdsa", "rsa", "user"} // add all test private keys k := NewKeyring() for _, keyName := range keyNames { addTestKey(t, k, keyName) } validateListedKeys(t, k, keyNames) // remove a key in the middle keyToRemove := keyNames[1] keyNames = append(keyNames[:1], keyNames[2:]...) removeTestKey(t, k, keyToRemove) validateListedKeys(t, k, keyNames) // remove all keys err := k.RemoveAll() if err != nil { t.Fatalf("failed to remove all keys: %v", err) } validateListedKeys(t, k, []string{}) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/keyring.go����������������������������������������0000644�0610621�0607500�00000010633�13172163317�024747� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent import ( "bytes" "crypto/rand" "crypto/subtle" "errors" "fmt" "sync" "time" "golang.org/x/crypto/ssh" ) type privKey struct { signer ssh.Signer comment string expire *time.Time } type keyring struct { mu sync.Mutex keys []privKey locked bool passphrase []byte } var errLocked = errors.New("agent: locked") // NewKeyring returns an Agent that holds keys in memory. It is safe // for concurrent use by multiple goroutines. func NewKeyring() Agent { return &keyring{} } // RemoveAll removes all identities. func (r *keyring) RemoveAll() error { r.mu.Lock() defer r.mu.Unlock() if r.locked { return errLocked } r.keys = nil return nil } // removeLocked does the actual key removal. The caller must already be holding the // keyring mutex. func (r *keyring) removeLocked(want []byte) error { found := false for i := 0; i < len(r.keys); { if bytes.Equal(r.keys[i].signer.PublicKey().Marshal(), want) { found = true r.keys[i] = r.keys[len(r.keys)-1] r.keys = r.keys[:len(r.keys)-1] continue } else { i++ } } if !found { return errors.New("agent: key not found") } return nil } // Remove removes all identities with the given public key. func (r *keyring) Remove(key ssh.PublicKey) error { r.mu.Lock() defer r.mu.Unlock() if r.locked { return errLocked } return r.removeLocked(key.Marshal()) } // Lock locks the agent. Sign and Remove will fail, and List will return an empty list. func (r *keyring) Lock(passphrase []byte) error { r.mu.Lock() defer r.mu.Unlock() if r.locked { return errLocked } r.locked = true r.passphrase = passphrase return nil } // Unlock undoes the effect of Lock func (r *keyring) Unlock(passphrase []byte) error { r.mu.Lock() defer r.mu.Unlock() if !r.locked { return errors.New("agent: not locked") } if len(passphrase) != len(r.passphrase) || 1 != subtle.ConstantTimeCompare(passphrase, r.passphrase) { return fmt.Errorf("agent: incorrect passphrase") } r.locked = false r.passphrase = nil return nil } // expireKeysLocked removes expired keys from the keyring. If a key was added // with a lifetimesecs contraint and seconds >= lifetimesecs seconds have // ellapsed, it is removed. The caller *must* be holding the keyring mutex. func (r *keyring) expireKeysLocked() { for _, k := range r.keys { if k.expire != nil && time.Now().After(*k.expire) { r.removeLocked(k.signer.PublicKey().Marshal()) } } } // List returns the identities known to the agent. func (r *keyring) List() ([]*Key, error) { r.mu.Lock() defer r.mu.Unlock() if r.locked { // section 2.7: locked agents return empty. return nil, nil } r.expireKeysLocked() var ids []*Key for _, k := range r.keys { pub := k.signer.PublicKey() ids = append(ids, &Key{ Format: pub.Type(), Blob: pub.Marshal(), Comment: k.comment}) } return ids, nil } // Insert adds a private key to the keyring. If a certificate // is given, that certificate is added as public key. Note that // any constraints given are ignored. func (r *keyring) Add(key AddedKey) error { r.mu.Lock() defer r.mu.Unlock() if r.locked { return errLocked } signer, err := ssh.NewSignerFromKey(key.PrivateKey) if err != nil { return err } if cert := key.Certificate; cert != nil { signer, err = ssh.NewCertSigner(cert, signer) if err != nil { return err } } p := privKey{ signer: signer, comment: key.Comment, } if key.LifetimeSecs > 0 { t := time.Now().Add(time.Duration(key.LifetimeSecs) * time.Second) p.expire = &t } r.keys = append(r.keys, p) return nil } // Sign returns a signature for the data. func (r *keyring) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) { r.mu.Lock() defer r.mu.Unlock() if r.locked { return nil, errLocked } r.expireKeysLocked() wanted := key.Marshal() for _, k := range r.keys { if bytes.Equal(k.signer.PublicKey().Marshal(), wanted) { return k.signer.Sign(rand.Reader, data) } } return nil, errors.New("not found") } // Signers returns signers for all the known keys. func (r *keyring) Signers() ([]ssh.Signer, error) { r.mu.Lock() defer r.mu.Unlock() if r.locked { return nil, errLocked } r.expireKeysLocked() s := make([]ssh.Signer, 0, len(r.keys)) for _, k := range r.keys { s = append(s, k.signer) } return s, nil } �����������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/forward.go����������������������������������������0000644�0610621�0607500�00000004246�13172163317�024746� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent import ( "errors" "io" "net" "sync" "golang.org/x/crypto/ssh" ) // RequestAgentForwarding sets up agent forwarding for the session. // ForwardToAgent or ForwardToRemote should be called to route // the authentication requests. func RequestAgentForwarding(session *ssh.Session) error { ok, err := session.SendRequest("auth-agent-req@openssh.com", true, nil) if err != nil { return err } if !ok { return errors.New("forwarding request denied") } return nil } // ForwardToAgent routes authentication requests to the given keyring. func ForwardToAgent(client *ssh.Client, keyring Agent) error { channels := client.HandleChannelOpen(channelType) if channels == nil { return errors.New("agent: already have handler for " + channelType) } go func() { for ch := range channels { channel, reqs, err := ch.Accept() if err != nil { continue } go ssh.DiscardRequests(reqs) go func() { ServeAgent(keyring, channel) channel.Close() }() } }() return nil } const channelType = "auth-agent@openssh.com" // ForwardToRemote routes authentication requests to the ssh-agent // process serving on the given unix socket. func ForwardToRemote(client *ssh.Client, addr string) error { channels := client.HandleChannelOpen(channelType) if channels == nil { return errors.New("agent: already have handler for " + channelType) } conn, err := net.Dial("unix", addr) if err != nil { return err } conn.Close() go func() { for ch := range channels { channel, reqs, err := ch.Accept() if err != nil { continue } go ssh.DiscardRequests(reqs) go forwardUnixSocket(channel, addr) } }() return nil } func forwardUnixSocket(channel ssh.Channel, addr string) { conn, err := net.Dial("unix", addr) if err != nil { return } var wg sync.WaitGroup wg.Add(2) go func() { io.Copy(conn, channel) conn.(*net.UnixConn).CloseWrite() wg.Done() }() go func() { io.Copy(channel, conn) channel.CloseWrite() wg.Done() }() wg.Wait() conn.Close() channel.Close() } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/example_test.go�����������������������������������0000644�0610621�0607500�00000001676�13172163317�026000� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent_test import ( "log" "net" "os" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" ) func ExampleClientAgent() { // ssh-agent has a UNIX socket under $SSH_AUTH_SOCK socket := os.Getenv("SSH_AUTH_SOCK") conn, err := net.Dial("unix", socket) if err != nil { log.Fatalf("net.Dial: %v", err) } agentClient := agent.NewClient(conn) config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ // Use a callback rather than PublicKeys // so we only consult the agent once the remote server // wants it. ssh.PublicKeysCallback(agentClient.Signers), }, HostKeyCallback: ssh.InsecureIgnoreHostKey(), } sshc, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatalf("Dial: %v", err) } // .. use sshc sshc.Close() } ������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/client_test.go������������������������������������0000644�0610621�0607500�00000022727�13172163317�025623� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent import ( "bytes" "crypto/rand" "errors" "net" "os" "os/exec" "path/filepath" "strconv" "testing" "time" "golang.org/x/crypto/ssh" ) // startOpenSSHAgent executes ssh-agent, and returns an Agent interface to it. func startOpenSSHAgent(t *testing.T) (client Agent, socket string, cleanup func()) { if testing.Short() { // ssh-agent is not always available, and the key // types supported vary by platform. t.Skip("skipping test due to -short") } bin, err := exec.LookPath("ssh-agent") if err != nil { t.Skip("could not find ssh-agent") } cmd := exec.Command(bin, "-s") out, err := cmd.Output() if err != nil { t.Fatalf("cmd.Output: %v", err) } /* Output looks like: SSH_AUTH_SOCK=/tmp/ssh-P65gpcqArqvH/agent.15541; export SSH_AUTH_SOCK; SSH_AGENT_PID=15542; export SSH_AGENT_PID; echo Agent pid 15542; */ fields := bytes.Split(out, []byte(";")) line := bytes.SplitN(fields[0], []byte("="), 2) line[0] = bytes.TrimLeft(line[0], "\n") if string(line[0]) != "SSH_AUTH_SOCK" { t.Fatalf("could not find key SSH_AUTH_SOCK in %q", fields[0]) } socket = string(line[1]) line = bytes.SplitN(fields[2], []byte("="), 2) line[0] = bytes.TrimLeft(line[0], "\n") if string(line[0]) != "SSH_AGENT_PID" { t.Fatalf("could not find key SSH_AGENT_PID in %q", fields[2]) } pidStr := line[1] pid, err := strconv.Atoi(string(pidStr)) if err != nil { t.Fatalf("Atoi(%q): %v", pidStr, err) } conn, err := net.Dial("unix", string(socket)) if err != nil { t.Fatalf("net.Dial: %v", err) } ac := NewClient(conn) return ac, socket, func() { proc, _ := os.FindProcess(pid) if proc != nil { proc.Kill() } conn.Close() os.RemoveAll(filepath.Dir(socket)) } } // startKeyringAgent uses Keyring to simulate a ssh-agent Server and returns a client. func startKeyringAgent(t *testing.T) (client Agent, cleanup func()) { c1, c2, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } go ServeAgent(NewKeyring(), c2) return NewClient(c1), func() { c1.Close() c2.Close() } } func testOpenSSHAgent(t *testing.T, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) { agent, _, cleanup := startOpenSSHAgent(t) defer cleanup() testAgentInterface(t, agent, key, cert, lifetimeSecs) } func testKeyringAgent(t *testing.T, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) { agent, cleanup := startKeyringAgent(t) defer cleanup() testAgentInterface(t, agent, key, cert, lifetimeSecs) } func testAgentInterface(t *testing.T, agent Agent, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) { signer, err := ssh.NewSignerFromKey(key) if err != nil { t.Fatalf("NewSignerFromKey(%T): %v", key, err) } // The agent should start up empty. if keys, err := agent.List(); err != nil { t.Fatalf("RequestIdentities: %v", err) } else if len(keys) > 0 { t.Fatalf("got %d keys, want 0: %v", len(keys), keys) } // Attempt to insert the key, with certificate if specified. var pubKey ssh.PublicKey if cert != nil { err = agent.Add(AddedKey{ PrivateKey: key, Certificate: cert, Comment: "comment", LifetimeSecs: lifetimeSecs, }) pubKey = cert } else { err = agent.Add(AddedKey{PrivateKey: key, Comment: "comment", LifetimeSecs: lifetimeSecs}) pubKey = signer.PublicKey() } if err != nil { t.Fatalf("insert(%T): %v", key, err) } // Did the key get inserted successfully? if keys, err := agent.List(); err != nil { t.Fatalf("List: %v", err) } else if len(keys) != 1 { t.Fatalf("got %v, want 1 key", keys) } else if keys[0].Comment != "comment" { t.Fatalf("key comment: got %v, want %v", keys[0].Comment, "comment") } else if !bytes.Equal(keys[0].Blob, pubKey.Marshal()) { t.Fatalf("key mismatch") } // Can the agent make a valid signature? data := []byte("hello") sig, err := agent.Sign(pubKey, data) if err != nil { t.Fatalf("Sign(%s): %v", pubKey.Type(), err) } if err := pubKey.Verify(data, sig); err != nil { t.Fatalf("Verify(%s): %v", pubKey.Type(), err) } // If the key has a lifetime, is it removed when it should be? if lifetimeSecs > 0 { time.Sleep(time.Second*time.Duration(lifetimeSecs) + 100*time.Millisecond) keys, err := agent.List() if err != nil { t.Fatalf("List: %v", err) } if len(keys) > 0 { t.Fatalf("key not expired") } } } func TestAgent(t *testing.T) { for _, keyType := range []string{"rsa", "dsa", "ecdsa", "ed25519"} { testOpenSSHAgent(t, testPrivateKeys[keyType], nil, 0) testKeyringAgent(t, testPrivateKeys[keyType], nil, 0) } } func TestCert(t *testing.T) { cert := &ssh.Certificate{ Key: testPublicKeys["rsa"], ValidBefore: ssh.CertTimeInfinity, CertType: ssh.UserCert, } cert.SignCert(rand.Reader, testSigners["ecdsa"]) testOpenSSHAgent(t, testPrivateKeys["rsa"], cert, 0) testKeyringAgent(t, testPrivateKeys["rsa"], cert, 0) } // netPipe is analogous to net.Pipe, but it uses a real net.Conn, and // therefore is buffered (net.Pipe deadlocks if both sides start with // a write.) func netPipe() (net.Conn, net.Conn, error) { listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { listener, err = net.Listen("tcp", "[::1]:0") if err != nil { return nil, nil, err } } defer listener.Close() c1, err := net.Dial("tcp", listener.Addr().String()) if err != nil { return nil, nil, err } c2, err := listener.Accept() if err != nil { c1.Close() return nil, nil, err } return c1, c2, nil } func TestAuth(t *testing.T) { agent, _, cleanup := startOpenSSHAgent(t) defer cleanup() a, b, err := netPipe() if err != nil { t.Fatalf("netPipe: %v", err) } defer a.Close() defer b.Close() if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment"}); err != nil { t.Errorf("Add: %v", err) } serverConf := ssh.ServerConfig{} serverConf.AddHostKey(testSigners["rsa"]) serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) { return nil, nil } return nil, errors.New("pubkey rejected") } go func() { conn, _, _, err := ssh.NewServerConn(a, &serverConf) if err != nil { t.Fatalf("Server: %v", err) } conn.Close() }() conf := ssh.ClientConfig{ HostKeyCallback: ssh.InsecureIgnoreHostKey(), } conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers)) conn, _, _, err := ssh.NewClientConn(b, "", &conf) if err != nil { t.Fatalf("NewClientConn: %v", err) } conn.Close() } func TestLockOpenSSHAgent(t *testing.T) { agent, _, cleanup := startOpenSSHAgent(t) defer cleanup() testLockAgent(agent, t) } func TestLockKeyringAgent(t *testing.T) { agent, cleanup := startKeyringAgent(t) defer cleanup() testLockAgent(agent, t) } func testLockAgent(agent Agent, t *testing.T) { if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment 1"}); err != nil { t.Errorf("Add: %v", err) } if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["dsa"], Comment: "comment dsa"}); err != nil { t.Errorf("Add: %v", err) } if keys, err := agent.List(); err != nil { t.Errorf("List: %v", err) } else if len(keys) != 2 { t.Errorf("Want 2 keys, got %v", keys) } passphrase := []byte("secret") if err := agent.Lock(passphrase); err != nil { t.Errorf("Lock: %v", err) } if keys, err := agent.List(); err != nil { t.Errorf("List: %v", err) } else if len(keys) != 0 { t.Errorf("Want 0 keys, got %v", keys) } signer, _ := ssh.NewSignerFromKey(testPrivateKeys["rsa"]) if _, err := agent.Sign(signer.PublicKey(), []byte("hello")); err == nil { t.Fatalf("Sign did not fail") } if err := agent.Remove(signer.PublicKey()); err == nil { t.Fatalf("Remove did not fail") } if err := agent.RemoveAll(); err == nil { t.Fatalf("RemoveAll did not fail") } if err := agent.Unlock(nil); err == nil { t.Errorf("Unlock with wrong passphrase succeeded") } if err := agent.Unlock(passphrase); err != nil { t.Errorf("Unlock: %v", err) } if err := agent.Remove(signer.PublicKey()); err != nil { t.Fatalf("Remove: %v", err) } if keys, err := agent.List(); err != nil { t.Errorf("List: %v", err) } else if len(keys) != 1 { t.Errorf("Want 1 keys, got %v", keys) } } func testOpenSSHAgentLifetime(t *testing.T) { agent, _, cleanup := startOpenSSHAgent(t) defer cleanup() testAgentLifetime(t, agent) } func testKeyringAgentLifetime(t *testing.T) { agent, cleanup := startKeyringAgent(t) defer cleanup() testAgentLifetime(t, agent) } func testAgentLifetime(t *testing.T, agent Agent) { for _, keyType := range []string{"rsa", "dsa", "ecdsa"} { // Add private keys to the agent. err := agent.Add(AddedKey{ PrivateKey: testPrivateKeys[keyType], Comment: "comment", LifetimeSecs: 1, }) if err != nil { t.Fatalf("add: %v", err) } // Add certs to the agent. cert := &ssh.Certificate{ Key: testPublicKeys[keyType], ValidBefore: ssh.CertTimeInfinity, CertType: ssh.UserCert, } cert.SignCert(rand.Reader, testSigners[keyType]) err = agent.Add(AddedKey{ PrivateKey: testPrivateKeys[keyType], Certificate: cert, Comment: "comment", LifetimeSecs: 1, }) if err != nil { t.Fatalf("add: %v", err) } } time.Sleep(1100 * time.Millisecond) if keys, err := agent.List(); err != nil { t.Errorf("List: %v", err) } else if len(keys) != 0 { t.Errorf("Want 0 keys, got %v", len(keys)) } } �����������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ssh/agent/client.go�����������������������������������������0000644�0610621�0607500�00000041445�13172163317�024562� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package agent implements the ssh-agent protocol, and provides both // a client and a server. The client can talk to a standard ssh-agent // that uses UNIX sockets, and one could implement an alternative // ssh-agent process using the sample server. // // References: // [PROTOCOL.agent]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent?rev=HEAD package agent // import "golang.org/x/crypto/ssh/agent" import ( "bytes" "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" "crypto/rsa" "encoding/base64" "encoding/binary" "errors" "fmt" "io" "math/big" "sync" "golang.org/x/crypto/ed25519" "golang.org/x/crypto/ssh" ) // Agent represents the capabilities of an ssh-agent. type Agent interface { // List returns the identities known to the agent. List() ([]*Key, error) // Sign has the agent sign the data using a protocol 2 key as defined // in [PROTOCOL.agent] section 2.6.2. Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) // Add adds a private key to the agent. Add(key AddedKey) error // Remove removes all identities with the given public key. Remove(key ssh.PublicKey) error // RemoveAll removes all identities. RemoveAll() error // Lock locks the agent. Sign and Remove will fail, and List will empty an empty list. Lock(passphrase []byte) error // Unlock undoes the effect of Lock Unlock(passphrase []byte) error // Signers returns signers for all the known keys. Signers() ([]ssh.Signer, error) } // ConstraintExtension describes an optional constraint defined by users. type ConstraintExtension struct { // ExtensionName consist of a UTF-8 string suffixed by the // implementation domain following the naming scheme defined // in Section 4.2 of [RFC4251], e.g. "foo@example.com". ExtensionName string // ExtensionDetails contains the actual content of the extended // constraint. ExtensionDetails []byte } // AddedKey describes an SSH key to be added to an Agent. type AddedKey struct { // PrivateKey must be a *rsa.PrivateKey, *dsa.PrivateKey or // *ecdsa.PrivateKey, which will be inserted into the agent. PrivateKey interface{} // Certificate, if not nil, is communicated to the agent and will be // stored with the key. Certificate *ssh.Certificate // Comment is an optional, free-form string. Comment string // LifetimeSecs, if not zero, is the number of seconds that the // agent will store the key for. LifetimeSecs uint32 // ConfirmBeforeUse, if true, requests that the agent confirm with the // user before each use of this key. ConfirmBeforeUse bool // ConstraintExtensions are the experimental or private-use constraints // defined by users. ConstraintExtensions []ConstraintExtension } // See [PROTOCOL.agent], section 3. const ( agentRequestV1Identities = 1 agentRemoveAllV1Identities = 9 // 3.2 Requests from client to agent for protocol 2 key operations agentAddIdentity = 17 agentRemoveIdentity = 18 agentRemoveAllIdentities = 19 agentAddIdConstrained = 25 // 3.3 Key-type independent requests from client to agent agentAddSmartcardKey = 20 agentRemoveSmartcardKey = 21 agentLock = 22 agentUnlock = 23 agentAddSmartcardKeyConstrained = 26 // 3.7 Key constraint identifiers agentConstrainLifetime = 1 agentConstrainConfirm = 2 agentConstrainExtension = 3 ) // maxAgentResponseBytes is the maximum agent reply size that is accepted. This // is a sanity check, not a limit in the spec. const maxAgentResponseBytes = 16 << 20 // Agent messages: // These structures mirror the wire format of the corresponding ssh agent // messages found in [PROTOCOL.agent]. // 3.4 Generic replies from agent to client const agentFailure = 5 type failureAgentMsg struct{} const agentSuccess = 6 type successAgentMsg struct{} // See [PROTOCOL.agent], section 2.5.2. const agentRequestIdentities = 11 type requestIdentitiesAgentMsg struct{} // See [PROTOCOL.agent], section 2.5.2. const agentIdentitiesAnswer = 12 type identitiesAnswerAgentMsg struct { NumKeys uint32 `sshtype:"12"` Keys []byte `ssh:"rest"` } // See [PROTOCOL.agent], section 2.6.2. const agentSignRequest = 13 type signRequestAgentMsg struct { KeyBlob []byte `sshtype:"13"` Data []byte Flags uint32 } // See [PROTOCOL.agent], section 2.6.2. // 3.6 Replies from agent to client for protocol 2 key operations const agentSignResponse = 14 type signResponseAgentMsg struct { SigBlob []byte `sshtype:"14"` } type publicKey struct { Format string Rest []byte `ssh:"rest"` } // 3.7 Key constraint identifiers type constrainLifetimeAgentMsg struct { LifetimeSecs uint32 `sshtype:"1"` } type constrainExtensionAgentMsg struct { ExtensionName string `sshtype:"3"` ExtensionDetails []byte // Rest is a field used for parsing, not part of message Rest []byte `ssh:"rest"` } // Key represents a protocol 2 public key as defined in // [PROTOCOL.agent], section 2.5.2. type Key struct { Format string Blob []byte Comment string } func clientErr(err error) error { return fmt.Errorf("agent: client error: %v", err) } // String returns the storage form of an agent key with the format, base64 // encoded serialized key, and the comment if it is not empty. func (k *Key) String() string { s := string(k.Format) + " " + base64.StdEncoding.EncodeToString(k.Blob) if k.Comment != "" { s += " " + k.Comment } return s } // Type returns the public key type. func (k *Key) Type() string { return k.Format } // Marshal returns key blob to satisfy the ssh.PublicKey interface. func (k *Key) Marshal() []byte { return k.Blob } // Verify satisfies the ssh.PublicKey interface. func (k *Key) Verify(data []byte, sig *ssh.Signature) error { pubKey, err := ssh.ParsePublicKey(k.Blob) if err != nil { return fmt.Errorf("agent: bad public key: %v", err) } return pubKey.Verify(data, sig) } type wireKey struct { Format string Rest []byte `ssh:"rest"` } func parseKey(in []byte) (out *Key, rest []byte, err error) { var record struct { Blob []byte Comment string Rest []byte `ssh:"rest"` } if err := ssh.Unmarshal(in, &record); err != nil { return nil, nil, err } var wk wireKey if err := ssh.Unmarshal(record.Blob, &wk); err != nil { return nil, nil, err } return &Key{ Format: wk.Format, Blob: record.Blob, Comment: record.Comment, }, record.Rest, nil } // client is a client for an ssh-agent process. type client struct { // conn is typically a *net.UnixConn conn io.ReadWriter // mu is used to prevent concurrent access to the agent mu sync.Mutex } // NewClient returns an Agent that talks to an ssh-agent process over // the given connection. func NewClient(rw io.ReadWriter) Agent { return &client{conn: rw} } // call sends an RPC to the agent. On success, the reply is // unmarshaled into reply and replyType is set to the first byte of // the reply, which contains the type of the message. func (c *client) call(req []byte) (reply interface{}, err error) { c.mu.Lock() defer c.mu.Unlock() msg := make([]byte, 4+len(req)) binary.BigEndian.PutUint32(msg, uint32(len(req))) copy(msg[4:], req) if _, err = c.conn.Write(msg); err != nil { return nil, clientErr(err) } var respSizeBuf [4]byte if _, err = io.ReadFull(c.conn, respSizeBuf[:]); err != nil { return nil, clientErr(err) } respSize := binary.BigEndian.Uint32(respSizeBuf[:]) if respSize > maxAgentResponseBytes { return nil, clientErr(err) } buf := make([]byte, respSize) if _, err = io.ReadFull(c.conn, buf); err != nil { return nil, clientErr(err) } reply, err = unmarshal(buf) if err != nil { return nil, clientErr(err) } return reply, err } func (c *client) simpleCall(req []byte) error { resp, err := c.call(req) if err != nil { return err } if _, ok := resp.(*successAgentMsg); ok { return nil } return errors.New("agent: failure") } func (c *client) RemoveAll() error { return c.simpleCall([]byte{agentRemoveAllIdentities}) } func (c *client) Remove(key ssh.PublicKey) error { req := ssh.Marshal(&agentRemoveIdentityMsg{ KeyBlob: key.Marshal(), }) return c.simpleCall(req) } func (c *client) Lock(passphrase []byte) error { req := ssh.Marshal(&agentLockMsg{ Passphrase: passphrase, }) return c.simpleCall(req) } func (c *client) Unlock(passphrase []byte) error { req := ssh.Marshal(&agentUnlockMsg{ Passphrase: passphrase, }) return c.simpleCall(req) } // List returns the identities known to the agent. func (c *client) List() ([]*Key, error) { // see [PROTOCOL.agent] section 2.5.2. req := []byte{agentRequestIdentities} msg, err := c.call(req) if err != nil { return nil, err } switch msg := msg.(type) { case *identitiesAnswerAgentMsg: if msg.NumKeys > maxAgentResponseBytes/8 { return nil, errors.New("agent: too many keys in agent reply") } keys := make([]*Key, msg.NumKeys) data := msg.Keys for i := uint32(0); i < msg.NumKeys; i++ { var key *Key var err error if key, data, err = parseKey(data); err != nil { return nil, err } keys[i] = key } return keys, nil case *failureAgentMsg: return nil, errors.New("agent: failed to list keys") } panic("unreachable") } // Sign has the agent sign the data using a protocol 2 key as defined // in [PROTOCOL.agent] section 2.6.2. func (c *client) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) { req := ssh.Marshal(signRequestAgentMsg{ KeyBlob: key.Marshal(), Data: data, }) msg, err := c.call(req) if err != nil { return nil, err } switch msg := msg.(type) { case *signResponseAgentMsg: var sig ssh.Signature if err := ssh.Unmarshal(msg.SigBlob, &sig); err != nil { return nil, err } return &sig, nil case *failureAgentMsg: return nil, errors.New("agent: failed to sign challenge") } panic("unreachable") } // unmarshal parses an agent message in packet, returning the parsed // form and the message type of packet. func unmarshal(packet []byte) (interface{}, error) { if len(packet) < 1 { return nil, errors.New("agent: empty packet") } var msg interface{} switch packet[0] { case agentFailure: return new(failureAgentMsg), nil case agentSuccess: return new(successAgentMsg), nil case agentIdentitiesAnswer: msg = new(identitiesAnswerAgentMsg) case agentSignResponse: msg = new(signResponseAgentMsg) case agentV1IdentitiesAnswer: msg = new(agentV1IdentityMsg) default: return nil, fmt.Errorf("agent: unknown type tag %d", packet[0]) } if err := ssh.Unmarshal(packet, msg); err != nil { return nil, err } return msg, nil } type rsaKeyMsg struct { Type string `sshtype:"17|25"` N *big.Int E *big.Int D *big.Int Iqmp *big.Int // IQMP = Inverse Q Mod P P *big.Int Q *big.Int Comments string Constraints []byte `ssh:"rest"` } type dsaKeyMsg struct { Type string `sshtype:"17|25"` P *big.Int Q *big.Int G *big.Int Y *big.Int X *big.Int Comments string Constraints []byte `ssh:"rest"` } type ecdsaKeyMsg struct { Type string `sshtype:"17|25"` Curve string KeyBytes []byte D *big.Int Comments string Constraints []byte `ssh:"rest"` } type ed25519KeyMsg struct { Type string `sshtype:"17|25"` Pub []byte Priv []byte Comments string Constraints []byte `ssh:"rest"` } // Insert adds a private key to the agent. func (c *client) insertKey(s interface{}, comment string, constraints []byte) error { var req []byte switch k := s.(type) { case *rsa.PrivateKey: if len(k.Primes) != 2 { return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes)) } k.Precompute() req = ssh.Marshal(rsaKeyMsg{ Type: ssh.KeyAlgoRSA, N: k.N, E: big.NewInt(int64(k.E)), D: k.D, Iqmp: k.Precomputed.Qinv, P: k.Primes[0], Q: k.Primes[1], Comments: comment, Constraints: constraints, }) case *dsa.PrivateKey: req = ssh.Marshal(dsaKeyMsg{ Type: ssh.KeyAlgoDSA, P: k.P, Q: k.Q, G: k.G, Y: k.Y, X: k.X, Comments: comment, Constraints: constraints, }) case *ecdsa.PrivateKey: nistID := fmt.Sprintf("nistp%d", k.Params().BitSize) req = ssh.Marshal(ecdsaKeyMsg{ Type: "ecdsa-sha2-" + nistID, Curve: nistID, KeyBytes: elliptic.Marshal(k.Curve, k.X, k.Y), D: k.D, Comments: comment, Constraints: constraints, }) case *ed25519.PrivateKey: req = ssh.Marshal(ed25519KeyMsg{ Type: ssh.KeyAlgoED25519, Pub: []byte(*k)[32:], Priv: []byte(*k), Comments: comment, Constraints: constraints, }) default: return fmt.Errorf("agent: unsupported key type %T", s) } // if constraints are present then the message type needs to be changed. if len(constraints) != 0 { req[0] = agentAddIdConstrained } resp, err := c.call(req) if err != nil { return err } if _, ok := resp.(*successAgentMsg); ok { return nil } return errors.New("agent: failure") } type rsaCertMsg struct { Type string `sshtype:"17|25"` CertBytes []byte D *big.Int Iqmp *big.Int // IQMP = Inverse Q Mod P P *big.Int Q *big.Int Comments string Constraints []byte `ssh:"rest"` } type dsaCertMsg struct { Type string `sshtype:"17|25"` CertBytes []byte X *big.Int Comments string Constraints []byte `ssh:"rest"` } type ecdsaCertMsg struct { Type string `sshtype:"17|25"` CertBytes []byte D *big.Int Comments string Constraints []byte `ssh:"rest"` } type ed25519CertMsg struct { Type string `sshtype:"17|25"` CertBytes []byte Pub []byte Priv []byte Comments string Constraints []byte `ssh:"rest"` } // Add adds a private key to the agent. If a certificate is given, // that certificate is added instead as public key. func (c *client) Add(key AddedKey) error { var constraints []byte if secs := key.LifetimeSecs; secs != 0 { constraints = append(constraints, ssh.Marshal(constrainLifetimeAgentMsg{secs})...) } if key.ConfirmBeforeUse { constraints = append(constraints, agentConstrainConfirm) } if cert := key.Certificate; cert == nil { return c.insertKey(key.PrivateKey, key.Comment, constraints) } else { return c.insertCert(key.PrivateKey, cert, key.Comment, constraints) } } func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string, constraints []byte) error { var req []byte switch k := s.(type) { case *rsa.PrivateKey: if len(k.Primes) != 2 { return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes)) } k.Precompute() req = ssh.Marshal(rsaCertMsg{ Type: cert.Type(), CertBytes: cert.Marshal(), D: k.D, Iqmp: k.Precomputed.Qinv, P: k.Primes[0], Q: k.Primes[1], Comments: comment, Constraints: constraints, }) case *dsa.PrivateKey: req = ssh.Marshal(dsaCertMsg{ Type: cert.Type(), CertBytes: cert.Marshal(), X: k.X, Comments: comment, Constraints: constraints, }) case *ecdsa.PrivateKey: req = ssh.Marshal(ecdsaCertMsg{ Type: cert.Type(), CertBytes: cert.Marshal(), D: k.D, Comments: comment, Constraints: constraints, }) case *ed25519.PrivateKey: req = ssh.Marshal(ed25519CertMsg{ Type: cert.Type(), CertBytes: cert.Marshal(), Pub: []byte(*k)[32:], Priv: []byte(*k), Comments: comment, Constraints: constraints, }) default: return fmt.Errorf("agent: unsupported key type %T", s) } // if constraints are present then the message type needs to be changed. if len(constraints) != 0 { req[0] = agentAddIdConstrained } signer, err := ssh.NewSignerFromKey(s) if err != nil { return err } if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 { return errors.New("agent: signer and cert have different public key") } resp, err := c.call(req) if err != nil { return err } if _, ok := resp.(*successAgentMsg); ok { return nil } return errors.New("agent: failure") } // Signers provides a callback for client authentication. func (c *client) Signers() ([]ssh.Signer, error) { keys, err := c.List() if err != nil { return nil, err } var result []ssh.Signer for _, k := range keys { result = append(result, &agentKeyringSigner{c, k}) } return result, nil } type agentKeyringSigner struct { agent *client pub ssh.PublicKey } func (s *agentKeyringSigner) PublicKey() ssh.PublicKey { return s.pub } func (s *agentKeyringSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) { // The agent has its own entropy source, so the rand argument is ignored. return s.agent.Sign(s.pub, data) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021710� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/xor_unaligned.go���������������������������������������0000644�0610621�0607500�00000002062�13172163317�025075� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64 386 ppc64le // +build !appengine package sha3 import "unsafe" func xorInUnaligned(d *state, buf []byte) { bw := (*[maxRate / 8]uint64)(unsafe.Pointer(&buf[0])) n := len(buf) if n >= 72 { d.a[0] ^= bw[0] d.a[1] ^= bw[1] d.a[2] ^= bw[2] d.a[3] ^= bw[3] d.a[4] ^= bw[4] d.a[5] ^= bw[5] d.a[6] ^= bw[6] d.a[7] ^= bw[7] d.a[8] ^= bw[8] } if n >= 104 { d.a[9] ^= bw[9] d.a[10] ^= bw[10] d.a[11] ^= bw[11] d.a[12] ^= bw[12] } if n >= 136 { d.a[13] ^= bw[13] d.a[14] ^= bw[14] d.a[15] ^= bw[15] d.a[16] ^= bw[16] } if n >= 144 { d.a[17] ^= bw[17] } if n >= 168 { d.a[18] ^= bw[18] d.a[19] ^= bw[19] d.a[20] ^= bw[20] } } func copyOutUnaligned(d *state, buf []byte) { ab := (*[maxRate]uint8)(unsafe.Pointer(&d.a[0])) copy(buf, ab[:]) } var ( xorIn = xorInUnaligned copyOut = copyOutUnaligned ) const xorImplementationUnaligned = "unaligned" ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/xor_generic.go�����������������������������������������0000644�0610621�0607500�00000001250�13172163317�024541� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sha3 import "encoding/binary" // xorInGeneric xors the bytes in buf into the state; it // makes no non-portable assumptions about memory layout // or alignment. func xorInGeneric(d *state, buf []byte) { n := len(buf) / 8 for i := 0; i < n; i++ { a := binary.LittleEndian.Uint64(buf) d.a[i] ^= a buf = buf[8:] } } // copyOutGeneric copies ulint64s to a byte buffer. func copyOutGeneric(d *state, b []byte) { for i := 0; len(b) >= 8; i++ { binary.LittleEndian.PutUint64(b, d.a[i]) b = b[8:] } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/xor.go�������������������������������������������������0000644�0610621�0607500�00000000626�13172163317�023053� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !amd64,!386,!ppc64le appengine package sha3 var ( xorIn = xorInGeneric copyOut = copyOutGeneric xorInUnaligned = xorInGeneric copyOutUnaligned = copyOutGeneric ) const xorImplementationUnaligned = "generic" ����������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/testdata/����������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023521� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/testdata/keccakKats.json.deflate�����������������������0000644�0610621�0607500�00001772176�13172163317�030110� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������„ù;¯¯oŽŠåþƒŽ-€—‡:ã…ÄäÀ‚lø’Œ2ÁßÝ= Љ^á×Áþï½XxYUO±HþÏü¿þÿñÿø¿ýËÿü¿üË¿üãßþ5ù¿½þûßÿùïùûéþïÿ÷ÿçÿoÿñ?þùóh½~Ī6UÆ¥‹òälaÖ< »H,0_>)I­¶ü_ÿ×ïúÿ·ÿïÿÿþ.ø?ôÿùoÿñÿÇÿoÿùûþñ÷ÓÿßþŸŸ_0gÓ/ŠÖtw95+øò¡?lΣž“bJô’gÞ_à__Ðýë êŽB\qrç˜×@0 —ªë5mÜ2ëó¨æBcÀFùøÔ¯Oxxõë#ð¹Ç܋ӌ<ºW]¨ÌQÝO’ÞÖE^ÛF#ü"‚Þ×Gà¹ÙO,’¹Åç<H.$0Tkt�v‡ ×)Ä!+jI½ó>Ù`ú¤·o®â+É„Š̘ó¸¯ô£¨�<�ò­'þñ!ïS™„‡ü²Å~}Ê­P3tHã ؆ ‹Ü,Ä~NÞঙ¡(à_Ÿò-Q=*{Kñëc¼Þ ÑeýÌ´%xVüFš–‰º„QkÁÓÄpGóãcäS¬ˆaÈÝλ{¿>]{Æ@<Š‹_<Ü[ÔrÃÊxŽAï>põýøý”íËwôü ’þÄGCxÀõF;Þp:‹%*ݘ&rZ×録�ÊÀ×}¿#Õ¬‡.;QÊ&¿>iE¯)%Å 瀒öiNÈ‹ó’=Qy0>agÀ_÷)åݱGDdŠ\zÂýSG8æÜlÍ”T†%ðª3A®J9/×ÖÇ—«_<üú¨OQoîŽôÜÇlï9üõYòÚöÕq/å,Ïmº ¼ì aE2Æ?—×VóñYñ)o©}ÜG@ûn}‡†}˜Ù öæ$ebW]Hö8!€—ØÆÓ³x@Ä…qЫô¥+„O¥§=%c"G¢cÇæzºï7h±#±ƒ"†òÔ.á$‘Á9J¬¦&õ¶œ&kôàË ?EÏ-nØ£­‘Ê%¶$•~Êß±xEûv×7}¸néUY÷ܼ(ïD̵yúùuô©ÿK"·WÝ îë{ˆ©q`D?Û?Šaí­¼Ýc³‰˜³ÚW­êÔÙí¨.²;hNÁïóûüSs” žEØ=ãùžXŠí¬9¡éO“uxÒg>Ä>¢atØ.ððU?x×:]ˆç‚à׊Ÿòç«pZ Úgz¶O(4ÎÁvç§ïÆ´ä‡á–ôzäÒQÖ•dÞØ�ˆ¡Ö×7¾Ï÷a¢ÎÓ%¢ø …HWé„aîÏWL³]²‰E’4™[Ä/}BNŒ©ª&íš±K+}}¥ÐgàÕ}{ûXVñ2ï‘[½ñÁCê [ùÃÄ#XÙ y€£ŸÆ¼—ؤ«äÄYäÝh’áaþé6úÝ3H18<TÔoÕ}MäAn‚Ú³‰sùí=z`΋w‚ãš<xHž.…f¼Ù>¿ôóõŒOûÍ^MoÌ{ûºòÖü=«\.y¬”¿ÃmÂA‹ÐZñ-Ñâˆa,!O$OâTÄ2íÝ ÜÓ¯oµïîbàrc‹P³hœÑ º˜=Íuäšiü~Ɔ¼—øJtZ‹èí±P®W{çza6I«1Ï•Ý-~ú’woN¦JLÖõ’bö²=‹EaI/áçÛBwÕ&ìZ> d} V¬`žZå$^°"KK…yÄ_ßôù½ÛU@&qö˜G¯ 4”Û(ö8—ߥrÿôUbÐ?·&É*¹×Ì[É !B�¢špfT/¾f.€Ï/Λz<</!TÄ“ºÉÚÇ•j§dÝ3å§3€ËA‘¾g2Çï2ô4Ñ›©m]QcËrö-ÝÔç7û§ÏVûsµÓ‹›æExÚ¹œBm¶ó\\a—–¡ðçW_m;wM逷ÕÍ4-ÛêtP¦4ñd=œÝºÂϯFýÎ�-Äb’ÛÏÉ"-ŸÄ†ß` ç3~L¶W"þ~¦>\ .¨^b#˜Üc)|‡œõø=ÜQ{4»¼®78¾÷õÝßc9œ_ßĨ÷]£u_!šA”ð>¥äã§WÖå²?¿Üù½i´Ss1¼·2Ç^8ì…ã¬@%\Qzä<_^GüýC¹y=äNjŸÓ{�‚>ŽéÜäR@—t]6; áýÔ8—½²ñk<â3­,*m–£ FÐY}a~}:Æ×ûõíßÃ?p¢«{!tÃÎ9ç¤?Ï0tvî­ýŽB \#²éçæBS]ì*¸b’LXš£åy-€/ÑV±Ñn&j»úç×ûgZ{W‚%hsÚ’Ý%DçG> QÄ4˜à®™¦¶›¥~oÜ-ýyNø?žâ…푙ƒº8èW@°7Ÿ›¨ïC]·uÀ,Œ–[mzã¦v"ú5ÌÆ…­Li6n4þìD bœc õÞx¿!xçþ*$ =×ôöQ$êÔò³x_|o%fý°ø2_<Øy¢Ü\¾NÂh¾nûæLöÝÑÑìŒ$ÔÂûÙ›*‰"@ä9wÄYŽÓÀÐË{n;¯„ïÓƒRd¦ø«†ïE†Ò¡¼mŽ7PmbOÚÂÛË-Tdà9¦ M\‰Opî´š–üε—‰]ÏúÌgæ-„–+Vóƒ2ÓZÜZ6ÏY©üªâ{÷Q4}wKEÜk“”À†W¶­‘Ò“(·CMÒ]Ù|ñ­ÔUÎû馇k‰E¾ùF¯\ÅàTq™Ä›ïÅy Ê»êú³éú¬ãóM?;ѰloÆÑàêNÆÏR‘“E ¶2÷áṺJŠé9Ë5½ø9í6£=}Oƒß-Åúë+i’®eÞ�xgoó`Êü3óÄwFJ Zµí¢ÛçZ·AªÂiòüݽ~GÛIy°Ó39Z‹vßÊûY §ƒ>¹}dÈO3wšsËd•/‡wÉÇíxbòë0¼O§2î£zÓuéFõãuT½E5…D0ÎÐÄö1–_ðø½«ŸÕ´líã$1¬Þ#Ù·©–¯3œÝ †X"@"Dò‚ïü³šï-ŽCíV-Ÿg<Áy/";Œ1WÕzšÞ&ôrEæ«jH;‹eÈà÷Ô&_ý|ûy†“Ç<\Ï9G™¥S!8|<Þêeè‰ ä¯ }Õó½÷±¬L¤mJãgjoß{ø ®TbÀ[u¶ÇG77H.Ÿà¨70øR¼§åû{8c‚4™ÐʯÅÝ ÊŸŽÍR£ÓŠŒ˜«¯Í¤ÌgEŸ.Ðî³A¦åy(«+ûȹÞãbg‹·9†CœÊˆƒÍS#.‚S«T„¦²Ÿi¥ë]PP%s§—¥í™*Æš1D%¡yÏKd¨ úL+ÌŸ~�¸oYàzû lG!¯–ŒèBxèÂÌØ»EöU`'2hç׫›ÓTåZ§?µåeE®nƒåÏûÃS)y]´¹¥oè9’†éÂ'SïÓ˜ ˆÙ Ÿ—Òîcyzhýö¨ÎǶçÅT–Â+çhZ]©!”CQI–åËù~³¼. DxF‘¢›hɰ„‰Q‹‚•2tä«.ùN$.ôµ·½šjÈq‚ÐÅž7ï±ç1^’‰ïmk1•øV³_Sj²„¦ÿªÌVpDÙ騢Ì"#[ç”®)aÙÄv:\fèWeúé'¡87Txw7ùîêD¡Q¥n'Ë{¡VHüÉlù´"À+›bjr2}Å/)û6´:aH³�[:˜éµô#lTÈ–[aN2§#8¾WX6Ÿµ}ûF‚bÒ–öî¸;öˆ¡Ñ¸Æ'†à*)²¿rè-y‚kV }p’°‰Ò`»Ød[ùû|ôòÝ>eEôëv)3x#Qú5Q S¸g0|UgŸ‚ö8ÍHp4è‘ ô;ÄÂÔÃÍ|QÒ=g‚o]üÍK¹¸c¨>óŒ”õUÔ…d‘àDÕÏú,¯ üÍn‰ ëÞ)¬"-÷ƒÁ¤ÁWøh.æ¾êóïiÂ/+ñãõ›’CÓ˺; z{J–l=à}" ^•~¸Lo¬íPŒÂ7«ßôÚxô *½ˆ‹Ÿ=�ûœ!©ßù=¯ÖÇ–$çD Èg\s¯ëa¼j‘ï ãÓUjCýÕðW`ãŽ~N•‚¶qíX™‰´Ò:fda28+½ö̽§¤ï)hGcÛ)æŽÄ…ÍÏÞívJ›Ž˜tZÇ-7‹üL*ZM• ý¾˜vuí¯>÷à;,ÊPŦ½N…SmŸËb³ /+ÔÙÒÄJØä¶]‚Gç1l®k} Üfæ’«A焇/í~oã<•£m*qzJ=2I—PM‰ž’j¤´0*P}Vùé4‘„QûØkÄP6nRµáhœ;[”ËL³âØ÷íE×{Ìð®òîÕÔØöQ¸ ¶ëOGß#Ï¢Ò®z/*òìÒ¼x0šU”¶žc$´Û}Õ‰úÄŽJƒk`Lö":·¦‰rî{†$Ë£S6^r®j&usXsõ!ïf{B§I”ébܽuô$Œ~º«fûÃç‹,Ô:Æa“ÍÅfÏŠMl}çmƒÄžG|UJŸî³ aˆ€Úš”`9ƒúç´Ú«÷‚Ä i¼G•™ä­ÀVD»Ù/FÆã5Ô©ÆQƒo ¬gÎÊÏyîÉ$™¡ô˜œ¸ImÙ¾>{îô`°ðÂdÃнبOVùÓ‡`ú :2['S:ÝZrÝ£ë8{$úN…Þ(Þú+L»‚®gó4´—R]«¢6Ò³°5¬t4™2Ëy•UÛ`„æzoõõYu¿éDQx´ŒS+>òUíût¤Yr­|º^�bøÎá {.·f‡âü)ð¾ä­†§®‘O;Ö*´Åž“ˆÓº#%éJºØ]«Xœ²=ºŸõ>7 žèZ .žLyss6CŠÄ�UÁ]Ë»—˜—Ÿõ~zÓnu£ƒ u_4¦1!³èȼjŒlʇ¸í=»k)†KK°yŠ7ÐÌ w[6Sfv…ŸM©VçÏŠa¶Ij™Ì–lÞ™¿¹ó³ʼndˆ äìÚ¤O=˧K=Ô’žŽÛ¬aÅ˺F‚gâ[é~3ê7þ–c¸ ²I^ذÖ㮵rIMî­IŸz+ò¢yW°J¯K³ñ÷Ý¡ÔZS•ȲÆ8ëô¶ ®GòÕ1³·Nwq̧ªõÓ¯¤åòTi᜛i}ÒÉ_¾LI[+ Ñâ®L‹kÕN6} ‹�å^S¹ ·>:tÛÄW×!À&a ¿7QU’]þ\– J æ%0T4É0Šf©çX[ÃgÕöé\†j‹ T‹icîªzNœûvƒ ›4¥Ïz¤:QT§i ­˜aÎ Ø"ætì9Âî°rN¿¬ˆc…§ù³-¡ E†0ƒm€·«mUäãv2>QÎfÍ,‡¯ºýÓÃè&qª’Œ [˜B.WãùB™Îãµ÷|P=”ݬtðõ;ØÌÐFdóχg“ÒϹ›W¸¯~çÉ6Úà¤æÈê ÈBìáC‰Inâ†Cë·¤-ànŸ•'-|öR2K†Qvê>GtsæTBª¡ |‚©6c®s8·#X,÷lq¶<=ëUt©•Zt“žçZ‰Fhô¢`ùïÚ»›KâÈ›¯ŸÒ4¤†¢ÀIn*MBV†õ3­qÕÆ¯Úã;}ÖX<¼‡sð^R¥ß‰Ô«§ÖÌážIÂCñr¦¦˜„¡aÂDH8ñAÃñS�:gqnpZ'Lˆé¿«'ïh= ð¡—™«ÍqBbÌÀØ4꜑GQaüQ½À§ÃXëЉMSô Å'1‡EO¸ó¤ÅÄŽ’KLOzs3-HOø;ÌzI ô(KË|X}Z2W‡_ø³áú+hœ÷{Þo”§`®u4ÎHÁíì:¬E€›•zz¥æõÊñ«~üôº Ò\/ÈÓFÓ©»nJ-÷ÖS¹à4Ï¨ÙØãLdlÅelÜG=—÷êMÏŠE²- ìÕžˆH½Æ®cœ%ÞÒåÚOדuË8y˜ÐÕg7¶°Ð(Ô{æ#»è ;ž¸c_Ч롮_¸oTÁ›=R2Gì0î})ZÏŒ:y÷¶R…jŽðþ4Î4E|qÆÃÁE#6‘@agIGkÑ7ÉqÉÁs˜ ð³ãI <WÙ«@‘ô,ÙoD9+‰ìàÌtS–>1øô¿ëGo·È=ð8ZDÆË<¤Ü§§)íÈRö±Ý©=ÑqØrYDÃwÉç›u ÃúºÞÉšE£©LO`-ÛõO%Äl—÷á<{aPÜ—n—O©L–É­ÂëÕ>~K4ú…:aÖò3*ykdüj*mÅõé#Á~GXÌWÕAc—ÉÒo™‰î�‡Ø¡+óíùØ&!yYÅIéÄñ[äãh»kZ£}æîQù3ÿxÜðø‚KY¾¹÷Æu ×龂¦Û·>i‡U_8¼OOd½8H•£Î>ÆQñÞèÞñ¤lUŠ­MôC O*ØÇÇ}¯žÅ6ñó”»U%cADyy}\¯^Äh?{ïfà”Æ,æ=0Ðú—bÕGnÏŠžPØU°LÛÔ*b/+$†R`Hg~!!ô­ˆv3åÎÅÎðo)§ÎJyÙÎäznŠ€ä¹oV=;dN–)š ­†_i¹‘¿ NëxM‹{¢eoªTš²Y0oŠq@Û,ß/,dõMú[3°\ó0ÄT}Y´Õ§º•‘‘8еý……~úd¼³N_Lyįu„»_£@{¥·œ;l–Éí [p†n-¹Þø>¢ ƉèðÉ7gkûžU–÷ݱÓxš™B’Äõ»£_h\’rAð&_h M) n’¤¼œ”’7Ï´ ,Þ°»Ç'ŸŽ‰\CŽxºC¥ïŽ=${w¬ö|zžl!¡Vc¼„sP­»æ rl*/L£èpĘaPÝ`óìéÈðtZcw€Òž©•ÛÐx9ú{#ëÀË®²u,"ëÉËÈÏÔ“v±x%.QŽ¥i[¾ð0ýÄcw¢+Ñ"b›¶EÀÍx†AžY'¢­Žh¬jÉék­Ö瀽$é^ïKÒ“òÔ+„Íጠ™Ý¦­5˜?åœfbÛ«@Ëôü™+(HJ¹xƒCÎé5×¥™EJ=läRÊk2ìÑýBÄ?]´RJ­d›“ïr©1fM“öLzØHæIG—D@CA§%…Z†äª“FêÔùSm+õ÷GÁ³Uñlï�„}™xJŽZß+ó¢y>‹ žùû>ýÖ¹'Hœ@Ž›ªO¾¸—=½kö¨‹†Ø… k¾0‰O?…½$Í5Fµéì,W¦E:•»åp¹*OeEu)ɶäÊ»Ê7å`µ$À¼—D\3R8ÜñZ¢J æ§vܽ1° ï÷ôù:¶Šö"ÉR‰¼ÑuºßC¬–Øö9²•Wà(¨(|:kÕM0ÞXÄ˶{,d66>’R¾o'tèô­fÕ¦¤ç¦=¬í®™B³êMz¼5�Ü7›ëfÝù&ã)H©i``Œ0ŸÙ°¿N@ n¬ŸžBü.ÂeTÂæqÂ=~øb¨˜°¤r´¯I`Áè—ï©À<"n¸YÊóê¨vÍ2‹²ÊÁµI#¹öŒû¥àeÅ»(Ÿ=ëȧ”©žGË+¬ç§lð£©2ß?»çóRG¹‰7q$d+›­{ í m<=æËáÍ×ûV%ÚŠ,.yµ*ø“qûB?ÝV‚l§+ J¬õU&$”;<E}ÇöF{jTÀ3³ã"Û_ U^cÁ­õLµÈ+oÀö€×ª1>Ũ !œ¯Õ·—émK¾¸›’H¬Ñ¤ LØ_ØXûVx³?àäQi(©z%C]']ˆ}ïÙ¥êg'RúôÝy*¯–Ü+ŽË›PÂ<½[ìލCBP¦ð;c£6ìÍ,#Ivîw}o|6Sì:¹D‘Bq»/Êõð…c¥ÔŽfI½¾xÚN­«×øüIq{þöš› Üë}4Yæ±K[ øòÅ‹xÄšHÅ³Ä MŸ^ߌ4ÁñÜA²CWå¨ ½):à6ÆðÍHœ žP¹x‹ûc‘ç ºIׯÑ;ð˜D”è¥<˜Õ½™ê¤Ð=¼à‡'xÛ×ø´¦H°¸&GD{~æ:ºÞ#‰—ë"³ïZuº[ÐR%½8ãhåVÙÃ!§®¾ðyŸ^ì† c)ÇÚ<‰s½bÙãYþÜšì]³V#ÛÖèÝSñ’gÓ—¥rÀ–)~,{¨y÷²Ö¬RñTœô¬VKJG7\–r£Gú Ý<±äEêh1ütå'n|ð„»ŽEÙß2¯´©¸—ÕÕó4ˆâx<®Ÿ}ºòÔ»Û{óĪÍï^¦1v’äiÑèyKŒ›xy¤õ°"È û€N:WŽœ*W"¦œžâëœpËz:'÷¶¢”@[«ãšñ ĽÀ’n" íßyœ3R¶s휷Öx4"ø wÊÅž’#Ä ˜»~zè'FF>«4&.*�ýÚ,¹"õ8¼ch>„a½"Œ–NÈd0Ò, X9>²X0æ1[#µF«%BÈÈ7¸L§/”LÙ§r2 ¨­“Icà+:îóòx›í"ï'Jjþñ…øxI)ÉŒG¾å0ND^T„¹©wõ$?'JÕO§V~~D±V8Çem&ï­ ê‚£ \bk»£Æ”½6ÝG[á|ÙE¦9š0xi%0¼\z=±ö ‚ -kçÙû;/½N¶s@­àª¨X0¯©0à¡2ÇRÔŸí¡Ûmá MUOw4ÚwÖþó¥:P‹½ÏnoŸžý ÉnVf9Qš,€••l•³=ù°žM8un’¸ŠLÔ¡ŸGÞÊC²çT ¸àþDâ•2hIGJKé$‡M»Ùc«•¦ÇÚu ÐkYjÏ‚ßõ5CnæéÏùbŸ©N½Aê][È%"dІ[;Hs’1ûV”º7øS<�í»×­¯L¨CŒÜV.³¤£î<†ø&€†éµE�×óëòó{x¼o¦ž³É�»jøIÎÚeΆ¢Ü´À0™Ë¦à¼ðxû¤2yÚÀ–è©{ë/õBü…ÕâuÕÅC—Ãpè¤`W‘+q^GÊáÑw)ùú x?±úôqõösQH°ºÐ)®š'étÌ=‘/CC,ñy¿@öÅ¥“6ÅHÙÙÚÉÇm¯Š¶Š¾N5pÜŒ%I“ᘂ·èóL‚ ×É+ÞÑã7e$O‹…ö§Wùr©”úë˜PP x ŠÐ=KO< . \k?sS|:zùˆ>£·ŒWò–ü:íñùŸæç]¢¯õøY*ël¾NÜ©©´kiÞð¢7œªÒÛ ø-3²? Ù˜5-AxGWý„e»v«™«ÉŽâÐOlˆ ®JO”û7^®C…ìZ@~ÿYdº`‚·º¹˜ò˳ >½F<[U.ýñ£Uè½]ÆÂ|›=A‡Ds­Î`–;x¼B~bî»±¯÷ꥑo<ezAVjÒóîeû;}S<Ù·.Ð8ƒnïµ½Þî‰Û7MøÀÁïÁÛ,¿'Tòå³ùéòúœÙdéšjí±öUø\N²{P?î½W#­çU_ˆáw27‘¥¡•ÁÆ}¢%&|÷PUpÞÓðu éSœ¾¤zkt¤o"Gçðf×êaÑ�9·äVñCdâR£ÍÄ'-H‚.*ƒc‡W@LR:›* |üâÞÈx™Ó ?îùía9¢ž+Æø�*ßµÍ&¼Í‡\©aцý…}ú}¡Ã,¦""⮉¿JêW@ á=b/Ûl¼uáAIl=IZi—érMtxíUq�7oº€3ÉÉÅc:ÇHøxyˆ-7Ó‚ÔS¦°µ<cۚĜÛó/0o&™q⪱(™;¼n ) 55vɸ=¾;´üFíÓùûXœ»ææu5(®M@¬.í‚\Ę-½–}¶ `†bêÈò^¢ÁÓÀw±WúL)‰û,_Ü %äkÀV†¾u#+Ç«ˆô¸³nÄé4±…‡V~k{•:!-"÷3¯"“¼N}ëB˜¬éñ¸™{+¤+Àáž0N‚)è|áÆúéiF×@ü`/Q*Çè‚p_Cp…Dœöõ“.vØU×.ÙŒuЬ¨Yå—…©”!Ý F=¼3%msTj×ÃLqúç›ïávº%sû‰L¾«Ê‘>*²ò ç*ƤËÙ6!þ…\ΰ½Â!‹§ÑàkE–ËwXðš®xOW"“ó\UáÓÛ¾/Ц»}!šBúâÜLÈñé,ó½èq€%t†SÙ€ƒ#éŒQyp³˜¶SMá9ÚŽÔg+ ”q7ƒ ïä‚oDŒ®–B,¶çy5§6m½Ô"]öÑ–«£‡÷r7ŸAúÑ‘þì¤;v³o‚º¹Jýº9ôt臢ï:z'búR>±úÄ.§¡TƒW±IãÈ|5ÞKIg€pÜ@tΑ­ï±[]v€« €KSO‹Ëm>«Z¡QI*Š´i6x€{2 30„Kp¹Á…¯¼ET qï•“0e  ¿ð|Slï§×Ù50Ùì³×æ'ìõŽÃQíÝ=ƒÌG{\N Ýüfuò ½ï«åâÝe8i÷z¹V÷^¹ÅÛçý´çØÏœ¶wpÙœ4Êj©¬NíA)æ"Á:Q­º­¥³ê«¾Zö[W棷Ê|·î‹Õ’})n`‘b5©� ëRrRzfz Ê1ѽ¯~vX÷Û«õY ͘Ý7Iõð¤-òƒ'Ê‘ZhÚ4ƺó‰ß÷”Y•*´ 8õ¦Wh*+ À¯áa°YÐî›LRæ‘�Gq+ˆª}1P/:œdˆüAÑL´ È…ÉùQÓZ´ÉоtxpËqÊUyõ€'–¼›Ëuá-ÇËè?o•n—Ë8hó@ø…`1{–³“áÉu½ô^¼Å‚KÂ×r„A_~_FÙ!Y¨SrçÒ£õ™ÛøFsšL—«½º,Š’©k”T„ËUíÁÔÕ¡'4"j›9ù:ü½0·‚bÔ×)ehJ,(í-ƒ®êò1*J£¾€Èœ ƒ÷J’:²£ 5¡“Îñ^üÌÆo€.&l«G^³âW…„¯1²&µJÑRê†ß·ToÝ÷¢Yù¢Ø‹¦çÖƒÏËÅ’š­ÎCcÓ¹Þh¥7ì’!6ù.â ¹ÇðBB… ÷±¼ÒÒÆ3 ªèÇZ ÒUF# ã ƒdš(@)ø`¹ùäe°*ï‚m¦!K"úNé…HÉïÝvÝ¡ve¬€) ‘û–9€ùSjp½×uÏâ„ÝŠ>g² O÷º:ï 6RL-@EïA³½ÞyØV#�9û §Uf§ªrÊ]R _1%4 ¸9 .“{³?º´•ˆ†| æÒNØ–ï…`?�¦C7Jì ¹Dë%áõ`Ù×܆äDº µ<ºá({ÓÜ™D»Ô´¥LóZõI/o+‡ÂÜh$¼ªDÑ–ýû^û˜[•^Ž«'ƒ“<“õ¡"tàð{ïW8á+­ÍlÂv‡?Ñòy×<*êÆíc¢7²ƒÛæï½wD ž"™âò¨„^õðÈÈi€å­aËØS"zÉ+¼¶àO§«^ïÏùͯô¥=vëH^Ì~Yí4,¥Å/ŽVzVÅßøX³á'’ŸÝ%Ýx¡Õ:•HKÕÀÏ2•éÍ ب^Ð׉‹WaÉPø,韪6¤Ñòó5À>´%n~ƒÛ\úlª÷èÜâÞ–;ös†²@6ï�Ü2’Mi4bÔÖQÐ…<›{sv¦ûzŠ*瞨ÿžN¦ˆ^uŸtºÎUò&-‘† ”0=ˆM€·NóJœeý KüžN@­ô]LÏáиµ§¢qé;7T_‡Ët8§ñw ¸¢¸Œ4qÕ«t©WÏt7HŽ´ºg•ð½¨U×Ï2—ãAhûµi<AV™·`€€ÛQêàz´éçYVޏé9Áo¤£”Z!Ÿþì8KîjÓ{œV&ÑIoÁj º.¦à’û!dÔ«ôþDóûŠ|ÈF-ÔÅÝ/ßy‡Í!ö‚G9ÊS­uwez¼ÅèM9…ùк2¸„ËC#À°ŠÂ.©$F¯±78Gh/ŸûÕQtïé(Ä=èe‰±òm7HpÉV-¡XurÚ)>2Yì9õÓ3šæoÔ”JWàŠV_4§¥ÏäCéGWʆ¬_x~ߗŶÂ"r^› ˼™Rç>æ=V3&ë{ýR|'º¦gžë©Æ9 ÇÈ‹ Öw锂)¤ò¶°Š3+dzë¥kj^;éT Úù1/_¥ ÌUØs®pÓìÎKÊ·$y…l­‹’PAã!ûóß׳eØ&§(¸Êñw(LûTŸít?y ZĨªŠ£ð…è÷¥Zß6vˆËÞ­c•À¼×¥<FjŽÊSÏ^<KV{Š1(¨9EOÚG 3è²XW,îh²Ê’J(Ø`2)‚Àúªg8#I�t0úÞ2ï+ÜÜf”ñÖ]\cP⌇nRAoKlt i§ßšþôÐl’xÕÃb«äI¸áüüÈ.© ¶ÀÚÖ7xtüí'¦ŸýHB^e R“jÉÄQ(:€ÃRz9¦äZ"²›ÎN¢ÄôúžÐU¾$d˜åE•AtÆ$ƒ‰®°^o¦ =1T€ª×Iê}á0úB R#%½•§t<Aù͵¶mûf4€–ö=,‚Œ5Ç<‚'/Û~æÎsÜçË0]«ŠŽvgOØsW¾Ø±Î2G¬/Tå»3ñĵ¨DŠºÑKÈ»€óãg÷¸€˜ýâ%ðÓê1«ê8ÐäkÇš^X׆—7o§éÚëáæ0)=0å(ŒxÆy½<1¬âJ�ü¹.QuH)–ñMØ{¨j`ßÇØmÜr35Z&º§«óï­ZÔ=‚¡ƒ­µ NÓ"áCÑcA6¤©®Štãxó‰«~÷(Æõz J8Â8Dɵ2‘5¢—ÛÂ]ÃQxYİ©†þÞƒ•ÂAyb5$'Jð.íòùª v=o¼k\Ü'd¯¸ž±ÅäcÜç ˜"‚qI€W2ûñ¸š&Qض%8ÀÔí£  ¶#l�9´‡øŒááOÅžB“ò-Ž\ ²Nú,5—BÍ+H^jÝÖ½/d¿/î&¾É·iìa<åµ¶Qµ÷ƒGW§Ç0dÓ]®#p<Ô”"È$š€é |¡KÊô^ RnyŸ[¡Qç`� Ï)Ò™´0-—\G4 ãù©�¢†$¸%ËîÛ]Yæ×¬1¾+Cqâ(㪓s|~ª¶®œ­ãÑm›¾·àWѦžÓÊøÊ»Ç™™é°î3Yù÷ôd­ Me/ž?• tu‡wpV#0ÃÄâ<mþ.Â3¸;_ëž¿y8íØÔŽ_Iíj»ZqM%€PËI¬«X 7;­3B Q·WÁâ ÷[äzÜû^œ,4X åØX²¼è11…&¬B©÷L<Öu}L 7zççŒ7éicÎïèålÜ®† ´)cŽ2Å Í«“oOpÿô HdÊzZä;—ú,Èyô½·lØú$<o¢Y¦†XJKï^¿Mñ5‘W@Oá1¡¾NÁuõ³xö ŒíË:¨•{.Üý`\žKQ¹‹m2–lê¾îK:NÛcv�Õ±ñ°¸ÉVôÌá±u×Ù| ¹/dô÷”µ¤=åÎ]qôtuyRpÏZ£žóÔã6úLñÙËÄG3¢ZŸ¸Ó+ T3HhðÀ»ûæ•Åf—J²©õJ¥­=„×á’-ZÞ¹5¨·5¯'%§¡àŽ˜¢ÛG·ðM6©']¬2wÄ,s„ÝæÃJkYd´‘’É–­´‘TØ'ƒ—¶™Õ,'M GlAŒ!ÌDýöÂÚyvšÕ˜f„)G×7�Ï^ÅRšíY‰-2}î>»Zíe‰=;/5¥‘/jl'¨¢·|¯ryýª‡uêŒß.¾•Ѭ0Êay@,OuÄv_ ÒfXHÖ ó1ÃÄÅ*U•rê¦Ë,JmÁKò‰%eDWœ+X•j°lO”`÷‘f2["#×S¹“•’ÜÆŸ¿¡ÀÄ«´Æ‡À ÷´•ÕBÎχi%Ö}¢åcüìo¾âøÞe Å¨ë3W¢Þ'Ðöœ:d°òqùEIdm§OðsŸ4~Ê{0¼Þ ^A ?[Ð;Œ¬M¸Gåy±†‰‡5¨nŽ 1o˜ýf îa\�ãœÞK¶°}§AN³Ñ*ÌŸÍÀ¤€d¡>l ùóŒq~áú3EÄ $Ñt¨Ã &áç%þp§ôÒSÑH½Ÿ½’}ñ…2Á§’Easa[ý5ê ?壠À:ÒvZº„G”m8õòðÍDÛ1ï¤Ðñ�Z7M­ñg<'Бó˜ì~.Æï÷ͳ".Ì»�ÆD.M ¨4\]qµqI‘Í>Ç{Þ¸¸‘¦ µŠYäÐÑxe‰4H¹×?s°¿õg‘³\=ï)<Å·¹Ëd£#Å™(Ÿ8ö<ÚÝÔà—{;zzî*U¹ÏR<·ÇúQì«íw0‹€Î—˜Ð…/…¢l,VïTÁ’éñn\!V/1¼[“»žmiZÊ×óä”;”ô ˆ«>x©Cõî=yüÆ4Â×ùA4H&*ÊÔ{ 6Ä8ÔõH鉽“'?‘®¢ë%ä^Ô×ñ²,M¹ OÙ“«|ŒÎfs²ˆs¿æÏî7YˆÓPðl AŠË‰ö£ FQr¡Gþ"N5aÊÿ Ê¢³ž»”Ç+WFˆPúÔµÚJÝ-…=ç½Ã}¤ŒÕoÛ3Žž¡ò8Q²‡ÇîË,Àz‡ŠJãÆ…}Éî7 (øN‰è¡XEí=â6s.Ël†QéÁªôQ¦ù…u?˜Ð8#ô1¬€×oßfoÁ3®„¤5æÐ“2·åÁþ…õûìƒ6"ér�É"éñ;c\Àá—ï¦# ‘aƒ4Ã1l9ƒÄ1Éz¼”ì˜NÃ^"|¨ÞºÄy<¶Š!£uÞ,9•×ÛÍDõ<“@Š‚Ci\\…²²kĽú´«Ù} ‚k”èBwä)¾&)ÍÈ2ñØÌ»>´™³Ÿ^½E~sO|Þm—Ô{8PbzʰªZu ™¥ï‘ÔÚòÙ¹£ž>†£Îõe'>¯©GfÇXö^/m¡¼ši;Ö<»WžÄÝ\s¾´I‘Ã)2‹¨2„‘³3%hBÂKƒÏc£ôf€–š‡ó•¼QXÎg̯Ù¹ECØ<Uc£Œf›)O¿ ¾§hºuð^?ó÷ÔÚ�žÁ@C=hOpoGqÔŸNÂìVtIœÈu¹frxÁÁ’`»œ@v£1¾Ý_x+|: ®Ê+³.9i³0L}s±2üš4¹s´í´`8f âi`N&„Ô¾JW È0}äÊ2"¤ÇOϦ¹æMµyD¬ ¿‡è–Ž9=’Ür$¯ÚI´�ÅOžO7ÓéúÖµ¶`¯Úæ<š8±Ý~u‹yæÅ³ÏÙæÞ‘?ø…¸‰‰ÜÓ¦kך—¹&ÑÚ)…il²Oµ“Ñà v÷|"þÙ%•ôÔ=5R%�%2úi-ðH¨høÑdó¬Y”ÿÕýްB$QÛP·q‰zyKŸ”×;R>UØd ÇÝmoNV#—ÒÀö]Ñx/­ -Â'šP JXkjdÖƒäÎp¶õªA•^–á2…#Ï ®Í•G¢#Aó)(‹ ÉOÌÑ_kìb?¾}Ô£¾çá#㤯¢`à= ¬FÏûÂÜôsÁÔ+îWm­Þ ˆj² ñ¶D³N®ĘÞVë3sP¼8²µŒ§ÌYƒ—žöt_ŠYç ½ÚFs†TÞlGl!#óžvjWOo@Y\"ö®YÝËÂà–Š×D¢9&Å›­72]¡Ùù 8_]½¼pïí:Ê•°®€°ø­ôè3¿{*È ÑM‚ ŽÐ ×;®:ú½ó}¡îŸÓ3Œ®×“&´¡¸Û!vƒÁèŠ@:í²Æi{œúàAaõ‹MäAs”†0ÇYΩ’÷¸ÛÃVÝ{óˆ03ÔQÙgAr±˜(Øïiõ ÊãÛžzMªdDƒ>‹\°{Û4`ÏßD&»ÁRf,hfÒ@Gß#�‡tÈÀÙE½Ÿ¸Sf-úX½ß7 Ù>}o0Ú:ò˜çUM>$ŒÛÏŸ=Tøý Ð�kÞyϦgwf£·èË hJ´I j u?1á\ïa^¸=ðNÝyâ>oðAñ¾×ÀÄ"sØÂ(úÆî9‹ ó{ü$Õ±GBÊxNΩ=—s�Ü,X=T 7žu -Åô<å Hè $Ÿ$¢’$Ä'PÕ°@ïùÒÏnÚ2�ƒfk8V‘ad°J�û†Ì·hÅ ©jwâ yøl§©O"ÊS±¤{;V-w4Þ³'Ñ>ɃÛÚÖÖNi¼¢ÄߥÚœúR\ÕÎSdU]AõÉ—¨Ç!gÉÍÎT\ȯ®£+3d(á–„î½lUÇ-Yät;j€-ö”‡[Žª¼5¯ž˜frÉ¡”‡èÙ3oÒ´†¨M+ïkg>aߟA½,,êµ69iÏž-fNºœ÷“§3Cq ¹ùÞ;³oð?;+,gÁ‚<ã(€žÒt«Aê\ WòºdE`µ +4­ÛJ<À“mz{Àø\äàDû™†ŒhÚ>4 ΣÄ¡À£Û 9“Ý‘—XØ´ŽDzu§§œ³â/Û0ÔÒ· ‚¹šO¥:°¤Iß›ÔáæôFy»ÏÑkð=jxÜ–0•’-…#¬¹R*?]'Æ»OÕŸ÷ƒvܪÐ~þ®ò8©h$kLeæ~ÔoíÓµ„ÔƒÐUf]áë¹öÁn4ÃÉŽ1TdbŒØÌ&w‹÷zS uÈ”1Pê)ÆÙãIZ†„¨šÂªbÉr¡=®Èm-HŸnÝXÌÊä¥lHm™5•Yj6Ä2å›}/íêÝ9e?½ôC .J#- ]žM†Ç‘½Ëù¤)«™f@Dê;xÊniµ@f¥’r=Úja7nìð…:„¹q}@Ÿý–J§¬w\U¶6f („ÐiM¦µNFθSÏ]ebãCŠêž18ÖØ+|A..>T8(2øfé¦Ô!½€Œü:%t.™¿îè Wn¬—¥z ¯”°Gž¨œÔÝS®§Xó`Ž×I�ë¹ÂæŒ�éèj0û½…'º±Qy<N–«.W8Ž?§WH²^ ã.¢ôB�±ôµTy ^†«ã­Ñ*üPî ?)àÏÖ‹0%E=•Ú ”Ë\ûQ“b }9`±*'¥’ =¯zˆã{€ σáq·) 9ÖÙ,©ˆ;„jÈA Š4tg5ᣠHZS.uíy„%SŽ4Ù;Ð:*Àr³"¾ñŽ´xuf¥9º(¨Œk€™ü‰¿º#S17,èKq/7áZ®}÷øJ%¼6ÇÆoÃNA& ¼e¤ßÆ}’ð>›p0¿Y…ްšTpEÀTÆwúö=ñ“»x-s�ºÞò,œ[;ÃÜM2+¡…c¤qú9„IW1 :‚báVö;ŸH6Ç¥)-tx´€Û€–úVì=Û¶ëZM;'q9{À»DÄ#4lõêé#WäÑz$a”%àiJÐØE¾õ6†áú!+nÿ¢!˜­Žz˜fn¸Ò¡…„Ô¡ôì‰+` …æ“ ó7 ŸíxݳÀÕ58SXz‹`õµe…µÍ°<?6Wæð°”ƒæ�FyÑ騺ÏÌw_- Ö{äãaìûHOîÖQI‘íÐrûN±Œ¦viš Ý¡oÉq.KvÙ ƒÐŸÀ¢Ó¬ì‘Ÿw a„TÙµ’ ‹f·Þ í,WÌÏfãˆb—#XEÉÎO",TÃ{éíõ¤¾AEd?n›Ô1EÙׇ“­\ñðâ“ùlÌ7 ˜Î[ºíOœºüê’®+‚JXý]Ùó!Òw@0\¡Ð…£åÍÏ›J^Æõ¦34ef$½í)€~¬Ym@¬˜NUîäåÂåm´½�N· "†ÊÑ”°—Oµ™?Nçxh Æ©œµ¸ûd´—WBí6�ž†¦¨ò½Î´�ФÞ2‘Gc2ê?­‰PƒaQ|T®ðîÑ»Ø,í!PbÜ“]•©¥6ø¤B?[´D.AéÙBq[†G^‘3½|p$ã*؇÷4—÷tü=·LlxÍËuîëÈØ«ø¤¯<Œ'×SÐ¥äñBŒ’\æ8I5Æd”´6Á�eMÒu‹—Ôð­€Õ )ƒ<v Ah¤j⥙zgˆnéºSX,ÂȬœ4¡å@²ø XÁívwš£Ôq¿ø9¬¶š¦¹ IºÒ¹«)¥½å¡„yø*T{pñ}’aŸÍÚl×áUSH±’…—QAbÑ0No9rx(‹8Ãñ+.&Ea<‹²HÝAW}@7¦ âaË©]˜–jì¼õÂÐ)m%÷ Ø÷uè s‘9ÚC[–’żgã;¶o܆O»U4*‘â«;ŠU_6š5 v±N!Pë™Ì ñì"PïÖ_t<ôvÞtÇzÇ.ï© ΀tpt³at~§lüˆ}ÒáßgZ3é=̇<(úx ‡’ö }ýM #Ááá³Ú3¦:N…½jÍÆ¯\ª½çšÃ!LÇ:–8s¤šU(ú®YXnò‹*HN*ÃV%²i¡—ïDoÜCëEQF=&”œPkC*z+À4 BL ÔHö †v>­“1åš Ÿx1\p;šBW?ç }cîh†ï„Œ†du1@´P_�kO@¼ìö€ü&Ä? aš‚ŠÌ¡tGÕ<W�o|Hït#Q¹$)gEÎY¶Ùö `¸HöQ7ä@÷`­¬ˆ1¸-¼±ºpd%2‡6FN yçö t—†ÏðL}æ¡<§NðyGDõvcj�å=+f›8Îzô¬e6Ò³F)}¶7—Ë­½‚ì¤Àk‹Míµž/;4¼_”P¿µ¶¥<"ÅTjz50‡:ÔFi>–²§é(ßý#>[9¼‡°Œà”ÏÄ_=ÐAOÍZ{û&%ªô\VëÅzâÙQ'À\¥<¥¦ª›õÒwE8 ·Èè%šB\Ž-»M±ÅX`^Š¢æ:É£ãÍ á-ý¬J-[ß>TÉS©÷ä½qЙ•{n#lÜvaAMêZ¶â„kíKOœQ*BKÔl‚t²ÅŠhÒ[5a~‘2‡×åÅÌ5¥x¡9YÌ/ظ±Ì‹0Vàü‹„ï=w9nTÎ,¾ iÀ3 ×±ÈS–ÒCx±qýÇPQ_Uö´Â¸“¢ÌC|ì¹ ¢Íz.ÌÌýtÑÑgE€ÔE.˜ žÑà zÅÚ:Rå"ØÂܬ2–áiß¾%’Îâ"¦�IÑx¾KXDó¢yò¶LÎZúÔƉ:Mûi'Å¡²ñDbêrŠßÏY|Æ,'Ù_giZöF_;<oÕy ¼>¨ ‚úI ~¶÷KÝz“ªªIDàø´0R˜š¶£2ÞAή]#7Gäó}˜Ý”â1A¦ÊÏCI¸Äº`P` 9™±Š–.Œ×&ö$øK6vGMð\®¯ìÌìRn³ŸkHSÞ3 # ñ6‹ÇWOD›•&ºÒë8·øU¦oz]E¿óU{Ô #Ô/6}ÃÞ1‡"­3l¬e4¨üÁ¢£¥£i´ˆ<’ ØÁ<ÂE ãK}Ì:ŸÄÐ÷|^õò°ÞA4örçeо-ã^O=§t1æ÷€Õg÷maW[‰d£€—Þ>›Z`í'â´£¶Ä÷Úž¸L–@Ìa9+‚è“'ú¨¨pû)/:<¿&~f­E™À"ñ¶‡Ùó4ïu5%¢jVú(y‹­¬Xçö¼WS²@¡ 0¢Ã<>³%¥ÀfÎÆ›h‡Yö'5!g$Hòt_žº#=5´êçT·AdIº{€5ë4ßÔ|¶|BµBôn%x¼©Ï:§vB1…ðFߺ j;x…‰„çR¨;¤+XZøYs_¯ÃàÖ¶º  \dmfå>µðsê’ •&¾÷’/.„_që=Ö×tž^ÓÒù¢íEíxï«|îa ”ë^§Î¬œHÃ>ÊÁ¥ NyWOÓßUGÛÑ@ÇÚ{>Ëð8—èfˆâg#'ö a2²nçó›ÞAdO´Ý}NÔ2,/Pltd?ÉáÏæ¯ìª±ßÛxQ8¦hÃXϺÖ:ÅZ/ß=ˆ7ÏEmÙc»õ†ú>Ð7g0ç¬ùl  ™YK€¼X‚a(¶,í"%/r¤ï=´'•ÛQøz÷Nòa¥4ö‚Ëm…CeEŸÅŠ/ðž­òR4û˜ÿâ¼3\8y^vͨà’Ëž på³Íz9±ÕRÚÌÞU~ªÃ’«÷Ï~“7 .boôˆiâò2îú6ÍÅ"5ýÔZÁ'=ï3l>Xç.ôâ¤GÛ­Ýe.œc²¨E£¯uš=1N: »Î4÷b“íÑ—¼=Ö-ë}wØ‘ÅÕˆÑwZÜÀKàæÌ, YŽlµR=­zÇç‘X3­‰»cï^×h@…¤U,ßRïÆj«õÃ)ßWîC8p«èkÁ:ÉÓ):ÌGï4äU‚&R¼[Õ¹¼ß ÉäG�Óá÷:ŸC½¡÷ÂŒ„J$Ìr%]£’ <¾ÍM¾—ób#eûìT'’Ôžé0;ãZ•©ÏxÝüØ'‘.�”7å:¯fI,¦è´Ä/G‚GÎâ ä–%tùÒáŽÎ V @¤½…W¸§”A„Ç:ŠŠ£& »™„ «¦&©ß»èTï¢12%©†Ož3€e”´  æ¾0Õ¶ ¤vïmí-9‰^1Ï#…ÇÑ•ÆÏb •Qôâuu”¾ØçÛ’c¬/·¢}çÞŸë€yìðY9z¾÷I‘~Fg-~%(Ïôùö=Ë·Ð|\~í‘f Ò¡042TF5žÝ†’,LX®œqfᩎxJ˜†e*äˆ[ùsœ}U)B‰úÄ,ÌC�·…GTÀsÂc*¨A)xûüùÅy߯Öx Ö†˜cšÄXN½4šZ15Ó²V¦jŽŠ’Å�±%RJ‰xSÅ%mn˜ˆ'ˆð^ËO’ìΓ< ì!Pîñ^yÀ#¥hÄÆDIuØq}{ýMÒgHè6ó—/Ò²$‡• ³(*ÝÀ¬‡»œ•5§ãx:Þ îœ¡â‚aBR¸ˆ…cà ÷jï<©9sjÜ#€¡¨,Ç} âúv²¬·¦jÛ䯂Î&©\¸¨ÀCÜ/á¼Q·õ…¾™Þe–.ÎÀÑð}ÃÁY¾¾Ùà$ç9[»‹¡s ¤Qí­ð#íÌ'|>‹]%Ò°‡ó~ïÓzj³^U&¸âñ²¾<!¸/yk±ì†YVUT¹òI“}ÆSŽzŠwGEO$ózÍ)ÞËMÙ�·­—[¡UÒ\™ëêíB:üà]<µX³ºl¹+: ±âE~8ÆÄÍ@›În4#ë¢ñ²g’u$±<$3Q·S^;©»0µ×-Z@ÉtÜÛ–ÛʶÅ!·ZCxŒ‡+ë»Rýh‡mì®Hø«Ã†¸ÕÄKä=®ÐËÍMJ DÂß´„¸îE€y+C%;‘U ø&Z=’ñÙû&Ê¿ƒC© _+C_¥ø¼±u¸xƒO<  Ç¡pŽVܧá…D%Œ8¸üyOä6ô±öóDz%´jëµ”¬U‹Ë¥©eYïÆyR 3É}]UZ¬k÷UÕ³Ë×yæ÷vUô¶‰íöíVå%.îQ ì¾\ÃØ(:y8™sx[7Lì8ÊZÆ<]\gz…o‰óO}‡§úL:*¢õHß4{¡}‹0À¼U•¤˜M{+¥SÅRû˜ ©¾©Šï!ñÆ^Ìì{Tæ5¼ù3z¼ãå×uJ4yüðµBãi¿9<S~G¡[a>¢#äzÛozÑèAÉ»±9ÁyuÈ–3*Úòô ëu”v*3‚aïu£—Áñ¹†“éõÕ{ Ûò´©9úÆwß]00ˆ×#¡§t®íÄ[(uÏqµ,º9]BŠU|½ØØ©FàùæŽÜ�5[¼·Æõ3ïyèüùG„kå‹ |±{–… ~O´ÍÛ!j²Ý¿È"ø ¯/‘ÌHOõvæ!ÛñZ,qà–™ìx¬8G®ój8ÚºØv¸H­ÀšŸ*é{1Ð-3ÔG„gûšß‹|µá24²juGAÌb3›%Y]O1Ž“S¬¨/Ȉ¶ÈÔ´µÏAÔà]盇›Ú4Ï<Úä¬ÊÙgܹ8‡WlͤúHÉ9D´Ý]HákÙD†…Š`OY¢k!8 üE:.1à)EŠVÙƒa*®!É.´ØÈ­½p€Øyßt}ÆŠáUé êK U:Í{Á£¡ Ö}L™9Ý{ºÆë§±ª†2ºanîýb¯Ü ¶3]‡æ &¨äÂ^{Ð;V5-Úô›Ðz<»ÎFÖ‘Áu¢T´9•.*OÓQ@íÚÒ8”b^<[+'¬óu$¶Ê2&d¤›Ì7Bhï]¸OéÍÁ“7<ÊÑF‘g¨íUùügÀè´"TVmó˜èíÜãÝhtLðGªcž@>eŸ„ágÀðGÝâ,ð„C‰ÆÎpm]9©Ü¥E*•¦^SòÑ ÒZ¨Â´H'EÂ4¤ÛÔ›VÚ}–§X+fŠ)¸"ûUæÚœ´®ࢡe‰.Rç<ÓÚ žC#Àkó|h|ö]Šgsßæíîó†ŒÝváË{-xò†ÆÉg¦»b @g€0)ú¤KŠ4PjË1ÂËË].ÊÒaÃ&0m�Éà"ÍÐ~Q–MIˆž`§×U†q$°¼’ZIœÎ¦Çølë“2úŒÚ¯ Á0ÄxÅè¹*nøm-“ŠáEb§#+»0æ’×s…#nNNÏÆ&à—ª°4†‹:œÝ¯.z ¥õP ®m͆‡ ÅVu2z·ƒÄÏêbêe[ðŒ.Å2ØÎ²†$Ì)wMõê•8ò¾è¤ Ô@¬Ý@ý¬ÍVcÈ-7¼Þ!² ¾tŠ302"R%<ëçž¦á £‘)еql?ßY“¿OòÒ¡èÎ4>Ó3Õ˜ù6â9¦îÒ½ù$?C‡`ÙTY/Ým=² ì¾B¿yp±P¶ôLt^?ëQP�¯i²A}�Á 7q {7ó܈Q„åñ•ö«Q–]Iqruí³Z¼á$2ï\O¹Ql|ÌgÃj2CèÀö´s:Å2 �½V~ÝÔgïˆø©ÆñÛ�ˆ=ÚŠçÄ£TŒì^åÓÃÄÝ~¨×ߘYI¬=-O5¬½`=Z'0‰Ë_´ñD†Eñ›'¢±Øá1­4ÀŠÚ@‚ý0½Ý÷“¶ŸöÈ1Á'¢¸NX˜Ïˆ]«éîíÕ¼ÜQqÂõ—¹öÆÁ(ádÉõüÐT°‡l¬pë±Ó™¼ìR7ç"8 ÀóâÕÒ#‚Ó¼ÞÀmO8b¼P¡Ç¼ÒËÏ£ŒÌPû^n¥MOôPdFº’ðÅó™x’•±ìB58 3i¹2 OŠœ't±+ǹ™‚’Q¦D„¤•|ñ©ÄO“ô™ŽÃ…‹×HÏRm1þŒÀ”ZÛ·íqY8‹á›¸ï#HmÔ iÇHšŒ¨Ì î)WX ¨«DÛiƒ×æËCÅqɧ4ûlà=Ti°×³U‘1½kG¢Û÷õôuè¡6ÏÂÎ:ÕºsÞ,N|. Æ!0ÖK®œ¸½«ìÒ²\¥›žÖp¥£Ì´L°†Ýoë)%¥ÒRÝ‚tç¯bí”Ì@™ky–ªØ‚˜ztP]\Lç‹lÑyÆ.K¿¨{º“¤Dó¢Ÿ×ƒRÀ×&ùÀu+fž=8˜‘Àì.ú¤N>#I§ép"IH:š:)€ús5‘gÃë'ÐDyÚ°Ö+Pï) ë­ÁËX·X‹›7˜êÞÉÏX±ýY%Ìh¦P°nž¯xb-4¶Á[|:¬š[ìµ³Q{¢‘í™›lW†‰‰i#mÏ$}öŠÂ\ckg GQR&‰_è .bV’^Bš…íÚ,¢…+àŸÑôž™4ÝⓜԚÄîbÒ:}ïgž´¾D¶PoŽÍDfx¯œTªxµ}ÐJûð´å;Oêg89Ór™V{„@2ú6BÇÊ*Ï®�ÐPh˜‹P¡©Ý©a9Å´°iöüÌ÷|èž €!D柽®X«=ë€õ<.RkF™"vdï'ÎÜáÝ/ŸašñÞk{/]¸Ï!¡IÔgÞŽxR‡¾ç ÷áõ®°’¯Ôœ•rA1ûã2–[Ó+|Ú:ð@AD­wOBa.ˆºžÆ¼6·{]É-ï%f^Èý´MchÂXŒ‰aë²TÎ73"ëoº€X÷¬ÝÉ‹’¸£â“>£OÛ”òަM­c¾k7ô«¢à|›~†³‰hЧñÞÁúºR:†•s„˜¼Ø£Ç)dqMú´æ5@”îl=cǰ¬zA§…ÓQé'n‘Ý#©…®Ü6>ìRÊÑ8¹õ¼_Ó¡tŸTŒ€Ÿ3s3Íš›c=t#År‘~µÕ$É-o°e¸lµ„QÁ}…ÇTœ Pq)ÅÌü @3k$àŠ xõŽ1ƒ»tXAÙC 1ý‚…£6™Îß&~èðI öMSZwÙ1cñÐîݱí󜸌6÷æã&€4žˆP^ìê Vâ"}/÷yÕkN© ½«öƒ>†% Ñœ¬&S9±+S\|¶]ç¢&ÌSºí‰çñ!ã휃Îx§&,>l¸´ŽËÕÖ\•Cïàt¡X])®9’ZZ‡ wªa;|rÛµÅóž%÷Û§M(ôºEzFé„0+(½Ò¨<,BûEcxYaÇþ¢Ÿ¼7Mz²ôà4µ‚Œ_çø+• ëÐà™‰ {ûMágtyû„*!Ùt‡èÞ;?–õ."¹2.©¶ÅmI¯J FQ^{—w\jŒïèáö‹{i ¸\„œë¤•҇ï2Ë öfFn°ê»p‚ƒ¤HwU9 Ï>ƒwT³{ð0žú‚ÌŠXw;4d(Tu¿1Û¾#lÕš{®ObÙ…ëC8wN‡”êfj‚ƒg^–Hz-ò÷ÁQP>Å òÚ³0ºé–t 1q¸àq(ìd3+€ zÌ5¼¢è|=³RýýC?û`º¨áœMÎE¤Þí†%gEªá‰R`¼p‡öÜ\-µßÓR�·ËŽ„£ëö墷aûˆŸTpÉÙ°:Åðy÷¼*Ö‡X.×Ää[Ђ]Œ‚gà 9LO{A‰Ó§½¸_\ˆŸkÀù²+¬á>‹”Þ„âóÚ·ì<a¥Ç²¹Ý%tìŠV­-M­K›ƒW£±ñp^Ò$µaõÕ…ïK³,ÊÃã›db>x:ì‡Ó?ÇöÔóü!ܳégóêúáú[Žæ^`#³½^ •/¾Ï:þ,W-쪡´XGWÜÒ‘˜{§@éX m:Å;©Ty‰Âªå‹EîãïÍé“…Išrõ“¶‚ǰž"1÷ž»€,@´òdÄ;|À÷ÀBœ€{«tÙÆ£ã¥lö)p$“ö›ª¶¤d° ÓLŽ}˜§ÂF¯ }.5ëÍ8ZirØœtj X†[Ä=ׇ¥\º^SÔÍX˜d‡î\“½lQxöZŸ%˜÷¾&YÿI¤Kï„÷sðñSk#ê@Œ–·*‹bÅjÞ•tµ›·}‰ŸÁæt¤©´ƒCÞµ’)Pô댴á¤"Cãƒ¢Ž‚})ÁÁá©*«¶…teûz‹„×Áy°·Œ^6ØÄA¼}t4z„Ïcýéæ@ú¼'¼÷„“w¦Ñï·Y:“‰¢]V¿MNræLãÚ°¡J¦`1ìëË.i°¯[93ŸXk;ß`�®QÍ•³ Þ0a±U:È‹ó|± ŽB®‘Þ)vRòv ÷Ýp¶4¨Qü¾‰— dW0!.\Ë…Aõã¨uŠÑâF¶yiËEõm­LŸ§ÏE©°v<<hÔf2g·ÈééÝ0bÒ©ž’>¾"ì\õI ]NE/0,†7šÅèñ^­À‹‘…¥*ÇÈ>µT�EDðX55d£—Ú™®¢Ñ÷B§ ;(D²^+ñ;ÜMzG#øœ– ö‰G]Æe ÖP\D’Us®Ò«FåA ½}YÖ—ëW‘§áðz¡‰âÕäAÔ˜;Ë›<F¥} yÁ[¿È´žFs*ŽkØ-<·7aí‚}¾à&—hœý°Û÷›Ìï=Mö2f$-“Z¼7t&‹".SÆòZÿ @Ÿögðˆ¯“¡Œ'й_>&5çÁÎ\¬w` °wa¾ÏžÖAÛ2ô(ƒÙ&{Z®¼e‡À[“Н¦ƒ”æk'|Ä úD¬Úh¡†wˆ ƒ„ÎËèBØ¥Ìkq© àˇ‹¡Þ72ÂjA:g ²œúÀVEï‚f Xû¼0<¼¡‹Ÿˆ54RÓxùÛ@tÌ{jÕ&ƒ?cÏÊx¾5 � Þˆ„W>Ξè³sÝq-Ñ)ŸÍè'ü{`| rãC£WÖ¶‚Î9 "×´–±Mž¿·ˆÚ[I´U À€VÕG*"—ªôÐݦü ‹E_yaƒÖ©Ë<;&×$(g?‰‚÷ªÄù²|ÌÏåÝBJ(:CËž¯¼Gj›GÝo)†kØÖø+7Õ„yÔkz ¡È~¦FMLŒoïæZù‘-Mšj =æZFÚ’™}}ïŠÄ³åÊiÄͲõž‰ÚÝÉO³G•^âÉ"G¹¶çaÈ€ëf—Lc@2'B…[Ÿ„¾÷i¶L¬e<[¦Ju|<™â‡lÅ╊ {öDÌ%£ö¦€%Au ÞEM¨GïA/פdß{Õ[>ƒPžã0Q †s͉/OÛLÇq9Óý½pm®M½§q±@¯ƒ\½GNPŸ’¨…ßÁ£ò¿šÛ‰Ë.(°áGAÁºpîuëþfJ-äY÷l+û#—|ò(Q²mˆ% áà4‹><9ÈçëïÉTНvQûæ/J)èAƆ±»Wxr:k0»È<Ï*mvÐTÒæ9ôÓþ¤T>£PqÜ–“óæ´ò:ú+Á9É囇™íÊUP‹=à™âjã­D¸Æô˜ôé©ÈŸñ‚¤¿õi˜)}Ûü¢3â= À’ã+žÞ+ð¼Ö!g5U7.|Â% ­ø @Z8U]K|…“1R¬B‰w6_äñ,#z:ÆäSMxôê-BÁižâ ÀV×S ™Gª 5v*Xùl íТ“\ž�Ø­?Œy~s5ö^ï/R#Í g¸÷:”È’<ФJqâ´ XhÌá,Øæ“ù$U?CQ†óÈ;vàõ¶ˆ¸·SµNàï>Î`š™ég‰VP&úÒŽ-#Ìu#žé#Š?+l K£º,äG”pýÌíÆ�m,íÁ‹ÍÇ%f{öŒjª&N—Óµqf?IÏxG5üÌNñ†ËB(±œô%ák½M{e XDÚFÛæÎù”ʹ4oæ=/Ob;¹•¿µñz„p«R­Æ ¡�fêâUfÙ±ÄÈàn"È‘OßÏxtò¸Þ<âÍlWf¯ÒñVtÌÑiHcáÞ±-g³ãoZ?ãѾÁFKHWí}ÊRöˆèBCë¨íôÁŒùØRvª.–bë£*àMÖÌ•0Gܨ{iõ„w–ñÂêiÊÁž`‚aRq Ï¡ F.›éÅáNÖkJ6k¦  }à,1¬ÈþÞÈ�9äðLF/¤|öÊé¨JàJÓ+ˆSÞØÌ’÷ãÑq—×>N+ÁÒáˆS×n `´[îêØmBaøÎ¯<©cÜE-ç*ìíHF•?ÿ™{­XìnL,ß$îBçc¨7ˆ¢ŠÔ˜÷ž&º5}kúiÂ-aÄËÓ9£c2ç6(kŒÌeвq"Ï€Œ‰kMP¼Ï¡tñQkš £»NÀ³_\“UR\ saÕ1 Wc=ÑÇDµ6bWªGϱ­Ê$z ëk'UÓœ'“_nMEH†ÅK#ÙÁÄsk‡:‰z|mú Ð›Þóçfûü­¨œâù m¯–vw¼÷à†eæ o^ír]§×Šû¶ÙQ !ÖzÌ¢ÊéO+v$èÈ|¡ORÓ6¢]Ï®fêmúh=GÙ}[÷I­F¦)ÄSˆÊJ+èT~AZ8#í]9I/ÔÆræM¸é™5Cýé½CByÎÆâd ÝI/¤†ò±¡ÞêÛ!è+Q-f}5/vÁÐj&aßøå8LÕôë¼bëV¸‚[J‡«'Ë;c$¦÷‰{ÆðøéÃ<o¾ÑITšF½Ìl!Ë—@"õ†j)(CΞP¿µƒSܧ×"ýJHEžßÖhæHËîœòÞZðóhŽòŠAx¿ûìS f «æÍº{,Îì4¼Ýo¦¯ÞµàwŸïð´5ï0ý]{¡ì{B)¯h4–á•“¢fÎ[°!hî[òÙÏ, Á¨æ¥›ÅQA‘X }Âû¦2$¾©*œ·D ´°΄{=.ä9ûtÚ96cNÑ7ã¥Öƒ¯iåBcTÏ«šT_Ú{šIHï=Š{±']Ïu쎥³±²Ë6Äã½ê.Êâg�óhp‹½d„µâ?Ï'¾³<­5º-Ï :WŠÄjYÓÞ"(4ÜýÌÆPM`mK2ï÷:çC)œ•9öTÃ0 5¥2 ú¶åŸ1J²S4ÙüÕ4“Çë;‹¥ti$2­49™ïtÈOÍ›añbú56ž—fZêCÎ$2kAi¥4fG«”5¥nµçk £nÔáoŒ¸£Š Ѷ<”Ñ…Ò¡.Uzö…ŒA>í÷\\A®»vÀµ©žô^(3Å›Ú0ÐBÎ#:,ë×# €}Û$x•èkD­‹ý Q5ÐëÞó /}Å víšúWØÀsȲ˜·úPJûù5)üEp=}¯™È¹È-Î:  gßX?IzVÇ¥=öMðg JÉاO“©]ú:Ûø€®…Ã鲊ŽÐbÉxß3—ñz®]#¬4œB÷ÞÉ£õ”‰'r ¬Ñ$¢XJ@bÍ_uJ¸, ‰YØ•°¾XÚ0â½Au•f,iA䯂ºö ¸¬™×1a[Õ1ˆ| n|(z9R<ìz®§£VócŠ”’ìxhI7Ç…†¿QElI‡‘âÄ:tÍšG!*îÅ%ÞÏÃ`(ÜLAágffòèEì 1;ÎVO ½Ž~P—+häp¢ A°øI1~ï ´«Vmãe˜ðæhƒXbJAø3¯W¯kO2lƒÛ÷щ²˜\Sº?aS¢ós vK—H‡CØ2ð?{ÈYì’×,¦æbÞ°uúpL“áðLØbcº(Ý¥f($@vP=•2$lúfh¼wŸê“¶•ć§ Kœùœ²VT±QWc—œ —–X›%*ß5‰’¦•Ý!Ÿn¾Ü�]ì[TÞ@Ã(<ÈЮY¹êžX1í!Ô¼`âŸF=HËî¯ÚûMÍ|=93c_z˜±Ÿc!™W¿çŸ$ÓgÈ:l!ï3ãp{6o<G*ü¬ÍPcJ Ý爹hÚSŠq'eêQàLœújå°•v4À{ÅuöªšÇ-|‘Ý Æd­%x¸»§±ÚÐ^½Õ œq‚ì%¥yÒ}¹fëæÊÏP•¶;½ÙÓj”«„ùܼœ ‰%f›LÐjW¿¬®½¹’j÷0çñÇ ž9­ýN›õTE×;.Ðö%«•äÛs¤ÄYM«àáœ0búI³'?'}óžÌ{NÇ·�Ô˜x¬óæ`dŸ]¶ I[¼o»æÏ¸ÇiÛ#XOÅèÜq8`®Ì!'צ¸ž)ò3ôÕ 7GXy¤s™VÒ¦e,Ðú˜Æë°okA£’å`àuÍ!CÁ\››ÜË·J=å+$™3Öë„ ŸS6úA¼GcÎ ·.io9Öò9ÛsÚ¡{l3ÈEÛòúb¶§yÝlî‚æ ¤à ÓKGˆ7É8›¥Ï4óÑ´?Üרâòþ,……j†íÁŒ&ªåÒ¸¢>¬2´þI´ºÊÓךÄP¯N_%s]Ø“¢É+Œ¿W6Ù t÷Iôû^háîFÏ1®r8/ƒlXÌ,TVÓ±…&|ƒIq$_:Óé™xðLç»X‚” ÛÊìB1�ºÄ-¹Ïwä½íg¸c¸sOY™ÞŠi¯ºC¼V§BÁ•]À„zŒí®’w^Zzt]:H1i±a­Cå—Ú:ɧÀ14X%ÏÔ){´OåT‘Ǽº‰Kj`ƒh[ÇëÂ:„Öß yîDV2îT�ùÕ5s™÷D(¡$"±ÿ¢c˜{X^"gQ¾W9DÛót·«1HÏ×éðMµRmºÇB0 eù<¢¼adYbŸ´ GÎ À>®} tųr÷Îo`-&T9»Ó¨‡¢ã‰SaPPŠXK!£PØ úUÉÛXÚd‡h*¹Þßiy²ø"¦Ö®ìͳ;'.B*:>I‹ÎäGônF †Y® AO&¨9žÞ{Ãy]¹´³EÞøªI3•i­GÓËDjyNƒ›¼ë1;/X—ë Ç%²­½Öaö¨9É'`¯ŸU[Äó–ªã"K÷‹ì}ì¹…Ÿr1sCFiox)ü’# ÄŠì‹O²å;ŒÍ ]¾{,Ön…bÆlÍ9H†ÇtC*/©äQR3¢ Jô=ãsb½Ý×+ kp~ô\BEY½‚/éÉ–6)CðA{T­j Ä8ÀÜ;/.Eéì·ûääÑÚÀd=µîîáTÐîÚbÜÄKJ04]…ɲ1?u„=p½G¾r°MhlTáaЭL(¦ÔË~Ö–¸råùHóãlˆÙNW&aãæ28& ¿Mßb”_t?yÚF­gë.às¬êåhÏ ±PÇ_IPp½'Ÿtëg,ãEaqÝ*iω˜G‚Ò·háÌmé§åUuÊFÞ{™C ¤Ä 5ŒÎHù\™¯¸ à-Ø‹vˇEš^Ïã‰p Þ=ÌW¤ñ”n0¢n{ž°==‘ DÝ ÎŽx‚¹W”7L£c'Wmg)F ¬!t«¹8P΂qb7ÐÙ\a“]A!¡w¾èxnY¡J”ȹò´Ã²fOK”fÒ�)ýA`©Šd‘Ѱroš£ò©ô r{ŃAíÜ_„÷¢xîèwÌ{LK(χD²ðØÃOOJZŸ¹õ'áFß÷a-(ë¡Úñ`{ ö¸ $¬ñ ªëaP9ÀˆW¯¥²6Ù®<kÀ"|f±~ + ç¹vе÷Æd35´‚ðFËX …ecgH­1¨"Ü¡Ý"Ì d<-Û’8¡) +{†+Š<3àrÐboµ’o@D_"êÊaÒ¥§N«œ®·420ËxÓÏ<°Ÿ˜cBf[X‰Ž2^§ôzQÏ*Á šÙN\*ðŸÊ,ÞL‹‰_\Žyÿœ¯’pBVr‘¨Ðó·ô^-o(D©Ë^ïsËOÊý3ªùÐ,[*»t€q8H¡ˆö@[Buʃ#MI“âÕxÊX¥¯MYv‡QOÑ7Æg‘Û )+á%>gu‘cÙç äe¦‰ëI\ò¬½|4a Š×›¡Bw¾U €”iŠ .»¶‡“hø'#ºWÏÌãb)[úTêÁ0°ôºTk;ÐäyW“¥e¬È+P U†÷4õ ñU¢Èé„Ô(Y4 P)LÁí‹MoZ¨$ É;˜ \Ògñó§w!KÈÒ]<|Ý ³:Ôõ¤ÀY^b¤?êü&ý3´õÓW59dÒÓÎ¥’ƒ€Qqç’¸†í`ǯŠ:§¯z¼åú‰«çÆžKiG9W%¥¤àŽº¸nË6Ù¹XÊ`Ò@ ¢ÑtsÜ*ž,V®×Ë®×:iÏkíøÀ9ŒƒãÝÙ¥/ÇÙÙúKæfWu“¬.$åŽ2¾±PkOâ²Jy¼µªŒÇ—ŸsCD‰T3ÜAÐziÎÎÍ3e1è8v¬K¯Ê@D z[l+Š1Ù|=Þ.érÂûE;ÌÌ P(œ€” où”‰¼{Òa,æ°ÍéáÄŸ´Çg|óòQ¯ò41¦[2r”TOìhÉd¬‡³Óþ‚×TH‡¹·&–0¥*dŠ5LÓìúâÉiµž-”Xvšw“¤^”‡»xv´E¡Ê½UU3a\Ž£ZÇ-&}Bå˜ÌÄê*r·5)|Å­³A=1)„K"Gî5=)ZÞf=‰x0l‹ÃS싼S% ÷à޹õ×ZÉÑUE{iá3´˜?zÕ&ZÃ09ê òÞBžö3—uâl^¨ŸCš‡Uáù3D}¸ñî!ŸŒ±ˆVh¥ô-Ê„+é|ïÉ>ƒœ Â{z¬¾ö«¡ûDi¢ÑûÓjŸðÁŽ:›½®çuÍuÎÅ:ïõ» ~ y&=P³¬it®vâéÀ0瀎ìo\Æ ™‰4›r+Å(íVójT¶Óú½0›ái{÷¼t-±n¤ûM½}#´A5ï‰øó}A^°Ù^öLo¹x])óÍÝ{S·£³Ï÷! „>·ík¦$#³ã .2’œ}Š…,â"/ÝY;ú„kLíÄØFýí&fñ ï „i?—ß«˜ÓìG7BøHœá&ߤ–{á¹0o6X³O|Rß‘.„_Ò3|5¯–­Ý“'œvÒ:kP^3ÄXL÷„d ‹Ä{Ê žgŒ£Û™qj2Hˆ,Që¤iÑ.²éã1ÃÞÔ¦83° ½±aö˜6ksA©g wnnž>ĨÕô´´ë…%=h/Ⱥg(KÏ÷âž¼iîPUá22päó½rÝ-ÈU&^\ tKxØ UÌ͆£Ýއ¹§9ý¤`ÝÉÒnåIŸØ@ˆ8P#Úw—È&ù…4Œ7]´$=*æŸóúá“~BHäñÖû­‘?ƒó¤ EÁç°WëÄôI>}†;°�m7 +W˺'¦ÇÝvNGT(/¯ë(¸‚1 Äߤæƒ&+¦…²{HýËé9¬A±Ò6¤$3š$U‘çô3é½e>sàó^²P#4v< UK®wþÒð°…ÈšrÂOO”Þõ¦fœ \Ã%T °4×ÃT4™§á5H(§Ç®zÂþì¢O}—®J^uÄ›%*§hÙMõí÷ðºòÆ5÷ÝÆÝ…×¬TS޼™À»¸É7cVÚ&/Cdð*s~f{ö^C€ Ú}¥Ò팒 }M]ê‹�ïlÐæ}Óÿ½›sßx /« =æ4Ê+ùñÃ2ë!_s…•ÙëL‹‚Ž|B9¯œ2´ÖŸ°nYït-ˆ•¿ÔÜsÒòò2,lV eÙŒ“MÈ4€ã-s–jyŠXAú Cxoí.«YSo-8цhêc. Vï—Ä$Ô|±(˜µ^(“X™óûi½‘ŽC„sCjK}‘V½ÓÕÝz4`$UÜ¡•¦mš‡P8ˆê\™qס‰*B¨füÄkÛ¨`9:Ž Ùü6ë­éÏ»Zr§¿Éöjq8¨e¡©ªÄ{]a6Ó£|¹A?Àßû:‰´}•¹n/È™õ!Æ[ 3:‚)kF10·±¦Ô‘¬U!Ø=ž~´¸„Õã9[§\õ¹<ì@Htça‰œù ¹Hûªç+U½^š¤z¢cik–%GW¸P«á†´¡l(á|¦s_½ic¾lÌE¼Äó¶xxÝN›EÏr¦D—”ý=Û…XE(…^pUÑÌ­ÃInOb›xK7·O‹ïð¥Ñæß{9oÎÅUgïñ<sL(óêm·0(ü}s³Ý·¹©HÖê{½ªX~à‚·`4Ç… %¶œ¯ö[òÞgÿ/JâwO–¶G\ÙCò {$kdVDߌtÜuâê*Ÿ)—4¾«¨gÎÈíë {[œÐ'7ÁXæ±j›tìKò¬Û®cJ9q_€µ¾ ¢™$Þ'c„bPyùÒü@€”¦¤äI¡ÄâN§n¿r#~\þ¨Å6¯oÒÈîT=ßcÚ d biNÖ·lØ4¦‡t8Îøt.^HCj‹ÕÅ®Ù:\˜[î’Õâ-’ötìyp¾´éªfµ}pûöO½õh“$ð§Žwżà!¨Ûæ ëŶÊ+“xðÊÜ‚ûõŒ|Š@>Cà ÖæPΛÖs/ï'òZp]uÎÊ£A×\SÎMl= !O°ýÁÞú 3Þc‘q8c {*<3JÐ3ûŒáJÛ†¦‹êÉÍ»šµ†äu­Áô´<Ò«£¸ÖV‰‡=Spg=Ä-¤žõôº+cg’JðíBó;(rÇl`]z‹‚µ»¥=‘–×}Güƺ+bëÄ{ Åãj²ßÅÁ’ŸÉòÂ[)ž­^Ë:þ|Ô.­^ S–›ßˆˆ-8%úvâÕd¼yõKMÊ¡+ =¸êô&VtÑâº=³_ÃÓ™2UJ¼yý)ýÞõÊiµDº .U®ÝŠ…Ã,#ÙJ™œó;ãsFÐma@Uð=šÑÕ(zµP†Èuš¦P©½ØÏ/]©/4qž¿“9©rFa·óEá5=¯´mm÷ŽpW¯* à1:!Û!E©«Þ{ ±€¶DÚµ]#ðµnv�{!P„û›ÚfŒ¨Ééx"‰ÂLˆr;°r„D^`xfÄúу ¶2Þ‡t —Ï€‘`¬¡ÕÂh‡˜Wf‹’HAžÑ%'Wºþ¼ãƒ -·n¾mÂ÷ŒêBWŽa:qÓ|ë?EÙ<ü‚ áyà -ÌtdBh¾Q–âHàÔ²4F+"LËj2˜ËxÚT#³«jÎÅß1Ã’·Qø³M|(T£lÅGÅ^¯Fê¢-°Å”8y³*wVÖW8VÓ‹ú(¬Ìë]úÙ±ô)Öֹ㫣ç 8×µÅP6´ò›°EÚŽù‘)ÑÕSÏ2™YùVø¥Î Îé%Š òÃ5’Z· 7¶î²ÒԹ܇úÌžQÁÓ:tDt¬Ë8+ª‹ì)âäZë9|}s‚6Ô%W±/ë§$C_û?SD®É[¸×¥Û/»@=Í^‘”{‚}FÄ›±ŒÇœ\//k,9eù‰­èlùú+K(è„õÖ®¦Ée,2€V$g~÷8k¹¹p,}$ÚVK_pºž«&*K#¹D_EÚSH³zB”ÒèÎÍ£ÙíºŠJª¶ýðm$ÂËô N*#TI©ìñËsà—2e¨÷,ÁÑ¢J+(S€´^')žˆ™bx åÕ¸—¦šç yžº!ØÀáµqK§=xVLAEŽ\½eŠ5kDØœ"¾²íïõLgúÛ>b#î†d‘VòŸ#ØCV•.O t{á/ê…÷ÙsbÐô8×Ú_ϧü3,äƒºÚ "³ÄÌ1:-‹4ð~[ó˜T½od "»KA©dîP´¡È˜UÝ2^‘ªEßLLžå<fŸ‰~ƒñsJI âZÉ=cšDµ]¾à ¥yðø:º2ˆËJ647‘r&õ¹ÄÜ+×](ñå€ÀÕB÷zàÙñ)^z Ò“]V\…UÀ½6å86áÚvت·7KâhL•øZå¡Ü «R‹¼qµÇÇÍ¥b´€SÁH‘ñ=¬|Áé|µ‘7p–‡¹†Fìós}Ô›ƒ Îtrpy;ÊŽy#v‹ÌruRv…`2ü½6ú”ÃcÑ}/îÕ¹¾wf…ïÞ¨uiM4žä²˜Ž”ã³¥RiUqé<ÚXÏ…"“ßé<Ö@aGa‡õX†ba±žl]ðᣂu_P€Qª‰“Í{îs®ùžÁ&‘(:í{®Þ¯É¡¾R¿4 ° àVœšÕÎæNçNå',AÁ‰TÔæè¶´ ¶çå»G6í@͹,‡)P»šØÏ+mÑä˜QÕ ÈÂùej*î¤:'Ç.ƒƒl¾—qöb®ôF�ƒ_d½h‹£Ÿ¹¡¥uJ¡Àù]Ñ‚æn^Å*¾Znè„o<eêK ß²ÙÂW°Zý91ÛpV™LÇݺ‚áËÈ1ÁEp…™¥—åÆdDTúúÌÞCIƒ3z=G³|ûl&ÁJ±c’E𞤈?W ç—5«¦‹=&§,’É››µ\‚ÓŽ<qE›ù'ÎùuN´µ†äú+¦`—j¨=©8ܹ÷x^=„nâ´H-¥}ÇOSÖg\°ÉÅ"d¦NŠÆÐrËŸ1Ââi>Íæ!M»¨÷Â%OE‡Ê:èzÆú=›®·§åÜ™}‘{¥ˆ^×w¶ïÕžÛÖL{ «s”ÙœÎ¢–uU¾hr•w”ŽÊ$¶VZ쀻Æ|ß’ðÏü¢uÆÐïœCÜ=¡ß *ˆ‰¥ßv3^Ûr“�‚¯㺌%;·Ú¬ – Ãszu…,Ë\GTœÄÈuš=T–å‚áåèVT=OÞÈ2£wv1Ý()6c®¶¼=MKÊ×q¼]޽,"óržêÌkÏ�ŽxaÍEÂO2Tø¸#Õ³°G3†õ=š¤ã®Q—]ÓÇucÆdIg¹ÑEÎJà†:WOi¥qTSgŒh¬#¾Ç=¸]~0‹]Ï+ßém³B« ®¾ý9hZÙâõvæ·T½€8iÕiØBËv~‡Ë“ó) ü •¥Èï¢yg�ìÁ�ÄŒƒÒGÁ,”§öª }ø=}T™Ò#œçoÄ·¥G¶áº¢«ø†ï.Ðh08ΜH虽ޛ ûˆ•Ȥˆ°_3{ÆŒFÍ…øÖ’/c¾»¥’CO7gì+ƒO·ŽKÂ)£JÒ`‹¢ibÅ“!Ü$¦x;LO ²7Ë Õ£—fħI,ÆöP,ùõ8 ±`“$19iï-ÖðÜ5J2®5H8aŒÀc¥xƒèåôªÍ3…•=(é…ÌyãîÏsTkvŒ<}.²ÒtÎG)z‘„l“϶AZRÈy?^û”½ï[äÞŠ&Ï‚´À£•öõ*!PÒL©mN["ubäÁðÂKæk£vdy.nâ¹Ú¾­—Íô¤uŸ¼A½¤쇪—%8GF.~4 lý ÜNß{4Ï-ïE4G`¯‹oR*L–¦Jò{øB%˜Ã8›žx,K BYÏN?:ŠEÈÀ 4—Ó2¢· Å/8¸§ïK ØlB$‚x üõ¤€ST f©‡jðž&aDqM‹�$J9‰?‚e|MDÕ�PýVòêŒSGð93œ´Ö¾j‹OLÈ÷s}»tÁö&Ìg8±ë¼p²Ÿ±ƒZ¹ƒ ¢Sà§0ø3h¾±w—ýª7…ìÙÞà¾#(ã}nâµÒî‰w+QP�âlù´è2º¸uõe,·èK²†ÃÖ 6Öm©[L¿Ö|,M貇øZ`½x_ÛNh&°:FÇS^×—â£äzæ²LéðÞã̓zsšÕb;ÒTè2³ëÏcfwW5“¹iu²XI°:•:='¼o&TF}¾xyÃXYÕw%ñ:ÐÝ[ ,&Ànê±ïxÅè„ÒHÖpÄÔÞð#z.`5{6ç…né¾t`ñì6×gIcôå.ÚŽ/•ËjAØÔ ‘7,zÀ”ü¥lý½m÷ø”ÆûŒœ»]å7—oR n@ì4lÏùðNqŸ9‚ w™�µG¯ŸèÎ<–ìî”¶{Õ.ב!B—þÊó¶†{ÍiÞ¤„“n…»Ó&¤ŸeF/ §nT?¥+Õöy‰>Iø�+˜E·Ž¤t ÕßdxE"ÆÊݼ¼+E_$_³Õ•ã‡)ùop”Y›ŒÒ¯ÙÀáàaòÃÚÕ,èzI:Sš¾@G…¯ÚZ^yac?·zñjºo8……%‹Ž% ŽúÒ åˆ_€& üP±f:¨Ö#Õ¨±&Dë TŒÕ³zUP-ž-x(g òæ[þ)}Çû²WÚú¨Ü6UËP2ðÌ~ƺ\0g^kI ³yB£•NŒÚy̰çBl‚î=KÅÑ/ó½ó´¥ô哌Q_G-T÷¸jØ:ŽwÊÀœ¹T“e\îM:ZC²ûvqOü ò2¨[8ÎÛtx l-5•·*JÜmç¸L¼¥j¤bŠ ‘ sø çmÔ½G÷·O.¶òô–‘›g5lI* g«žâ½t¼lç÷ ZB„ÁŸÉ-ÌãÕ‘\Þ}z¥öˆÎñ¥z¿Z^ïø9›´gÓ4h•§³u¯®¤ØÏaS¦uϵQu}‘uô{\•Ï:ÔEcÌÀ|±ÂHÎÎÝï 3ì­Û¶ú¡ -¾Ôð—->‘Á>³’a àãèýBÁ&f‰ü­)úayî8]ÐŽ<Ë{DpÙséï1 jD…=>?*Ì=¶­z2ݱÈsõØù.äÛ›âÎ-;fD«SΚ¶«­‡†m‹9¤âæ ýÙJµ²:º掳sòYU¹ÖšÙ*ZÕŠùÝ oŠ2´Õ�)`M«B†ôà^{¾#CÛì·6G}ÇU-’hk¦ ä¢À”ÚƒCÎþK t77ô^A?:w-·â™é•×îW¤i˜~*Äß¹C?éQ„‡ˆ"Ï<|݈8'½ !U´¤P°l)…nÐ0_6ê¼ Ëa³{"¯ë^ ñÞŸy[ŒÞ+ ïéŠB.U¦GwÜ¥;«Éšz S\ýpa\±Ø_él‹WAè@>¢y4‡&‹µ(†WB¹ªGãštêôÒû2»²_Ú ÊǼ[(O^ž#¥˜™Àò^ ¬§w6Š“8†áUrå«1]CŸìóÇ<Ì)1ävÞDüÖ’ áa é²Ç^Á>(MôâÌSñuÚÁ6WÆâzÍ[dÍ—Û®.¿[ŒÖbŒFÔ™Ü<0Yya’—ð˜+ꥆzåñ¼o‰}GS³°%(£dÑJ‘º7ÇÙÚS·žY :¿Œ‹ìj~oŒâèÂæ8¡îPv*ZG¦ê{nðÁµ¾Ê> ×öÔj�jéo-HÓà±Oa+ÎÞ®1>’s'œ=ÒÁ½1»várty2 ’ÓAþ,tŹMWoíud“¸e>Íôs‡wt[â¬Ý¯8++ËEŠ9/ÚHD=Ú’Øc豜¬F£©)SbxÖááqîƒoó€Ò©u›,33"^ÌœÇö0sšU¿ÅpO§¬³¶Îc ü%’|Z¥¯ -fžœ‰ÓE[N@Šw¼º¨K‘¾þ‰†Ô8jôœb‡6‹W¦¼‘I §Am «7ƒçd²_$-@™cÈ9ø½kÓ%í²ZÆi–¯gE­*)\¼ï:슘±�G“¯%º±ÂxHd2üñòKÈŠ5;lG벊›`˜ìñ= -‰|ÝÍ.I xÎ ‰G˜]~0qŽî-¾` 2‘ˆšb¹!~}e¥ã¹5¢Ü‰—*ÜÒ@87z«‡^—7µ]Y�äÈÌ;ò¢±ý¼•Ç”´Ÿ3цŽÜQ<xQ³k|¿Û Œ»»ÑÃ1LCZ9Q§FÑŠÊTòGñ Ý…ò[&Ÿq5%Ž/™€rµº×»jƆ|e'FQøIH¿Ž{Ü(£Šñ¸°ëæåãÞ×ôz¤Ã_t+IlgÀRZ,à]eƒUÂâ³ËGjš8ª. Ên%Õ#뫚¹ƒå‰-ùLž"á¥Îæt‰°òsÓ{ŽÚxªã¬ãRÒCio䔄ØaÀÜ^Ž·Øhܱ–?”Ò²±µ˜y'Р‚xq¢í¡ÅÒVÊ•,­wA•gƒ*¾f×!ã©ùx·^ó»Ù™½ZFÄ7#Œ ˆ+œü¦éyÒÁê/¡8íºÈñ”¢¤¢��nÞ}*öF<mfä]5!œß¦|/Êâ3¸rù†µÜ5æƒK›µë½8.¤ŽkY… —bWƒæ²-¢�¢#¦gÊÀ¯WÍ[še—Ê ïôëõ†‘Uñ^dÍ÷¦Å š ;È ½Õ죠~M‰gZ8ÃÆš#&Ï¥žæø[TzÚj£Îjb5ˬM#ó�WÙ5‹ÉÂò´Š7ŠÆoM^?{Ne´Po³LIoÔ7mT¶‚Gâ¤^Köƒ³æb[;ÖxGñè5½<o?ؓ艩Ã!_X„³ˆÔ3ïœ'S<6»/ $²6 _8WtÌ{c'úXBçÿôóO>&p ì;/bYdNÔ}–É&;Ôšö}£5xŸRyü¶ áÏ1o·aFkâ­ÃYeL'Ƙœmš 婎æ«>ÔJpŒDJe£‹b©nëtÙÅXäÕDCø\tG.ƒí57DÍ¢†u†ZœJ¢¨^£ÞëæRÆD¿zïÅ¥æ%jòU?BÚ;áhµ>ô§N*,âцˆc\w½±^?xAkÊd! ™É¾EÓø’ƈ/â%ÞªèÝ›Á'‚½o­•°(S^"�`‘›§‡%y‚CH3É"$éЦIÝèk`ˆ*‘|²aDP[݆ëá]ÕE·è<ãŸq ™!6<›=ƒBë#¸0¨‹ÆÆ !“&ó×À³ŸbÁïƒ~[cûø v˜:Îó{1ÀOtVá™”?0Ø{þ¬™¹ì‰Iáµ%º†¾ç’\®ün3YB2“îIHÚh) ‹òì2Ve¿Çíɼ;:2!šáê¬Ú$d%»!@s¥›]##š‹¯Â@ÕkÑ^{ÌÑm>Î:d|¤íþn”’Õ¹¡Ù‚Ž^2zu‘-á=c»,¥6Ûd¯þƒäžM–¾F¾­5ª“*Ë’4?á§ó¸Ûvé••‡Ã‘z©×)eÍŠY =ö[|%/¼;äÀÈŸB[ËHo½´š÷µ#ì_r9³.!Bê K˜œ ,•p|N´<:â¯=„<èS.ŸrIÍwï¦%‡ˆÙ1Wò^øØ+#¡í“XöØÈж¹«¤k5áa{7A€v¯{Vµà=xJ=;7,4ŽÂ«ùÚÇé °ÛØJмID  `Kɦš":Ó‚æRüX‚…".9Y06 Uç.Qï’e]ÌÎÒµµžÞ"OùRÏÄôUºÔÌt/¤¥/ŠœãÒøÆ­>Eáá!jG¬á8gxÌE„<ó”ãaIPð $óR)çÔ„G5 £ôÓ›Rs7)nÇá|pâØWÛô¼B5L,÷ÔE¢ô+ä´× Ù’ûóê2—Ójb:ï­7¦ÓzŸmФãí‹%Dð…øÌgÀ¸L|½µQ6+‚¥ ¦ò ’9ØE KÖRúœqÄ@jšá•csgÔp•/…`Aµ IR¼­ApVw½•µÃE»yËùp�Úcýú^²rçNav‰øòˆÒ!s•»î•)0[82NH=BcÇÍL«DÙv‚*iäÔ}°¹-I6 7× ÇRœÂHøÔAë5Iõ@fr ? “)Q½¨7ÈvoAßkJšTÝNáGK¬/¤¹•„¼n˜6 ïõDU€?@*¡zÕ¢ó¼ÛSK¢²�_¸oÖ -&$6-¬ýk¹Ú ì²`«QmŒ£äu{¬ íb2r!©ñ ö§dø3êÒø#{Ì­x4¡}ëЇL¤’È*Í¥˜™<:ÝÀqZI9B©éÝ ×g «e‚ avùBÛÀ“Ìé1¼Ãë¸ö–¬Y…`æXÞÈ› ªHÕy8<ZUè</²¸¢LŸrmˆˆ•ÀîêWѸû"¨8ñ‰ëi壓[†¼ôÜ-s¡zÁO'å¼X5q–³tB ƒÂºWTltj>ærKGš:‘÷†cŸ;Â9•öÈùúÞr³ƒVS7•s^<~¢ ïâ\YÜ6.—;y7¦8eQ&oq(G¼MÇ–€dàÎã—µ…kŸÀ¼ïÆô>C¯,Æ„¹Ûuf»-Që9póKžì!…‡Fù,=-…´ó%%’áöµŒŒÕJ6ŒË!„°À\«DؼÇMØñ’oo(«+^î�S`.#tOšŒgï«¶ñX^Tš”Qõò¨k__ôwo8#©rúÝÉ-4T{ÆÑBQ’Þèx‹�€_f–Éaå£WÛ‘Öã|9¯}ƒ1EEÓ m¸„8Õïà‘xEì°ƒ?E‡WÉËi4~t—+MW)R)ÉMÖt†5†8t‹Ñ”SŒE�Àò7v¥_ÎQV4\ q˜ôýœ•"Fé|N6gÕ Ý¹þÍBi¯ŽG$ÏÂ[#¾g%ùŒ¿í¦YOÙ‚Ýz¹|Þ B31¬hÀõ. „¬~Ž+º›pzál1×yk\ăý'éuÈE&G¥^¬´Ót¶§EÙÃ[oÙ©#"Üà’æeà»H2žw9׿-1ahvCô*|t¼:‰îsŘm2ÆêÁ¸O90É^soÑEuVCªºÔyœ�q½B7Oy„èbÓÆ-,%Ï=4`S'ÁY@k—AȧÑ3YTÞZ'Çq³Iùžw­ ¿©ÖWMP{õÐú¶ƒNyb×8ì÷>¦’ÊGeñÝd žBœ»»ã”ƒABŒyPDbù§pô;ã“K¤Wö(¯‰‰-ãE¥`u£ “Ñ,€”:q8†6ÉÙJ7y\Ý{å4¢ËnÕÄ,°ð=~Ä/wN‰Yb©Þ25FûxL3€)[¨‰Ól~Ø)ËýVŽE¼fæ…É”µLzUûë6¾£÷8ÞÀ<yan*û $ø Ž:ÁI“wܧz‘ÌÈÇ{<ª©%lzGáT.MßÖ>µK±^®yñ¼ÔÕÆ^Æœ4lë C×Ñ®b¯hµ¹¾¹q6Óbœó¶».ÅGž¢uVÆîõR¸ê˜ƒóžî¤ËïUÞù ¡OÛ°¶Ó³k"ƒ×x5EP(�Kš—P&FßÒñOéÜ\Nw Eåç{k«ô$枉a¹íð˜ÜùœM‚’ ©.Ñ[Gj޳pÞ'âu‰GµÇ·%Z {¦h Á®ÏåYî†+À Œ[ ¨›§Qëcó:åwv&ÐÀáZ`VPçeÒé=+ÅŠ¸]aÓ–-U‡íX÷ƒšuç‡< ,6ÜŽ+°¦�ÜÊË¡íqkºPY½+…æJÂãj”rvzl©þä™E÷ØÅt·ï‘” Ká>ß%«z2†ÑO#w±³¦1F-ŒºXR °H¦îùOß¹T ƒ(òsµ0ÃæP¦r¸¤ƒc^Ç;µ–ßáØ>Ãq¸+;aÜ0„<ÂsÒÝwË¢ZJÞÜ«ÁÐq´&~ƒéÐNÆG§¸o2W¥ß!ÂðZ'„J¶ ½å×0ý*iôê¤jƒ‹ÅåXÞ˜<î’G‰™òÔÞ° ˜ +¤ß›GÇSÈØ\–e Jj•¦®/Ú; žB+áàÉÄðMHmañviÃÀU« Ey“rgbe‰æË»Üy/”æ t|¤pËŸì1¢{ñ"æ9b"ŠÖ–%¹g®o >ÃRz™˜Öšs€KP<Fãžœ;Œ�íNŒûp¯Ù4@J¦=äÀá&Åþ•ðK>íc¢î3z]ÍånoÇÝd¸—æ e²=·<?åãß19³”Lt,UcðiV†ûØkI”(žuAÁtŒB´N¼S ;EÑu¸òŽf4uÔ7l“6‰8ñ"gÌ ÔS{ˆ:¡^ÝZ9×=NqŸ <(²Tñ×Ï^¾¤ã]8<Ñ÷Œ-èAJ^™Ýt¾(9°J×ú+ë*öê]I»ú“ÒMy¦˜PM=ƒ¬‹D­µ$1á+þpî53ÌïÙµ:LHzOèív«ßQîI€FǺ%bë Æ,æ¥Dhggc÷³=q Oö§÷b^„:•:÷KPªG(ñ.¯Ù¹ãq¥sÍž ìõ!Ì/sŽ@ 3¡>pkh¾("}]d§:ö´à jW7¯ø ÌÏÊ 5®JF-TÖ©Ñ,“F™lC¯ÇyyÖ˜Y=Žw-"^bÝpê7F²ãó@º¤zNšžÙeN>M©(êê›sæZ=îxl˜!—hsƧ ‚‘›pg1’ˆ¬ÂwíS@Ù–\òÓ@p$¼ÍÈZêÁêª:²¶×y¬æ RWØñÂÃ6Oô.ßäÕº¾§ˆêÒŠ–L miÀº/ÛQ-â4xòÖã¸÷m%Ä.°"`]«J=€”g‰ pe9>þÎ_ñË=D”µ7{ˆè^ƒ‹6‘HÍ€LÛä ÌQ““=I7^öóæÍ®ø¬ X…ŸnøÓáã´éÝÒeU©´A nð¢ÿ”Ãgtö¾ÃS»n÷Ð dewGGíÎâçJUj©¢Ëî¡Ç½z7oÒ8Lâz.TÕFW[„Ø‹@ÆáEcïìÛ4–Éf|V—¡PÔ½/ß‘<4­zƒ5¸*ï1•O-&²ô#D)ŽW@ÏE“ÒyÚeÔœj_½÷ˆCÔº·_¡¿yò|sùNƒŽSP%-S‘Ú1v“Æ– =™‡råaÙ4ù˜w3âÑë;4Õ| U�›ýÚ‚âew«÷–¨Ê°ú“7\‰¹ žÎÈìføwѸ®!Èž¾‹#ŸÝx­¹Y–¹ºË©dûSD©ÑÐèiH|ü’Ø#;«¹NOÒi˜óƱ…Â@‰~‹è3Doö€…aßEEpðyãxWɼ),yž.oMð¥8+¼5·cŠ :BÄ Ë–õ vb!cdB!Ê’uqER(ä­Ý3—"·7.¦©“¦/}Gljæ…XÊ“zÏD=Óa1sÞàE IÌ.âR·ß�2j\Y÷ëe/V:_ÖÜÀð²uöéÍw–Rñ(ªø´ª¦ƒDeYM·x†Î5“xgxÀÃÞ3 ²xÅsIŠ˜vFe! Tï¦0üø†·ÖC}$ºüd}¼[D¦= ^FÁaì]–™kþi˜ Clã˜;YôÑÏ8 qÃòPÇÙ§}Uôˆ ½ &cyN׎-I`‰¦çSFø½kæì·‘Z÷ž43k¯Î5ÝÙ¬»¿âé@º=83цfiô8Îá$Ö°¬ILGwLhïÎëpÈ¢6 Ñ×T‹rûúUÂ\=è¢%w»yž8/{ÒÃ⽤»‡» Ãè>Ê|4-þÔ^—dT‹©TŒÎœ˜‡ÊùLd"Õ]^õ*8Y½€*›ã™Ô£ÄÇíu¡YÀã<iK£äøÒ£’D½^:ä*¢Å­¿…»�vGó.ME¶½‘× ùòá`úðLïÓª|YÖ9¢Âáæ÷Ñ£×›y‘é6WÓ{ÐR±•~ÞÑO“ÿ@•%/3%Š{ƒôæ_N \5•©z‡Œ—Àûö#ú Ö€FsÆDNóÜU£Y|ù‘B×þWË·©ý ¶‘¢ž=Ê^ˆC¡k%~‹µë™å=¢ëõ\§+£AXÓ…LúøaCžù.í8%§Å6tApè®R政ó|»žÖÝÉ»þ–bÓ^ÞöÁƒ°U8_ÏRA$mH O6pÜGƒê¹ž†!ØB$ö-¼–2 µ¨ÉYQ½1�WôUÒz —ç!Õ½ˆ/_,È(’m.žZ^Éó휬ID¼í`|ý_x²Bëy‘D]ÄmŒÙkI(ȆÔc^+�*¨šÏUþ’’èùÆi$G¬Gh?åQ9‚©‡T˜Ûæ¨ó’^¼ü”Flv“ zÐÇ é%Ñ*.Ž4 °Ý_èRÚ3÷BÒŠ4š&O¸”…ü ¸³ÜLÊPçé ¼ v6 $F4`‹J½—ÓŽzÛUpÑïi™KX¨?\q7/ãÞ*ë}¦x³Y‹2KÇs•‡ö¨g‹=D¢ÍS-x1ØEU‘MÛ±7D}#Sƒ¤žÝY>nKXo¶Ñ yqWóPö|+تçÅ>õzölÚ1²FC¦`AÜÞóÌdy¿—5°†ˆEs±âc:.9áZ¬⤵ðæ±(Š„(ȾzUN¯˜ûåmÉZ ÆÄ/1EÀ±Ù©`ydG, �¡HÄrø6iúù¹7ô§˜Þ÷žúY7¦ÄíUÆËh“JWm†ii삆ó Vœðç/Dgd0œ¢¿¼Zžì8S ìÜî«ÓÀˆÖ^ª×”|o(Eo%™ÀÄîÍ®Ì=F̰\Põ|†bªK§3Ï›OÌ^àÁK€Ù48šg‘¤ÓÒc¾™ÅɈ†Q¶æƒ1sØÂóÌm«E8èz�¯`|žjÅZZºÔ1_tËÃØ¨q{37 áˆ3y>v[™í¸QŠ’£�#.¨«ä¼ùsgXixshIDk³Û-Yˆ¨ãbt= ‹Ým½#l¬×®vób{kµÎÁi=ÉéÎ�Y-²¨V%wÂ8Nô|ÀÈØËu “žÁ3mïo9}Æn±¼0¼îÜ{,Ó´{ð(ªwZKŸÅ&ª»xê¾ÈF0\½—’ú¤ßz›=ATuê�m/×í�<žÙy¨V|�ÚuÙš»lä X¼r‡PïbÇk |2·3›Hq'çΔ¼jU&d/’Ê´â'ž1æ„à�zRe³&% •.¯ñx•®nÄô»Í‰jlC¤'\ð†y“•E9®¨›ÊpÄS´jÔ°ÐoùíÐòt²;Ù(ßλbry �¯¨xIÁ1ý¼G‡ ü|­l’²pÇòaá�’ QÓy݉¦Ýª…Æ#êuŽŒy ~À?ýi®4]^2¾ÍE ªeå ][p¯‚SXI•¶û”|px‹:;D@•yÌ4<àA¬€5£ïÄø2±Ê0ÐûµpPprÝdF¹%šg@ _kº=@,@„yý”8 ØÑ‹&)½òQ‡î;×—ýÞ"èÅcD\{mÖHu2±¢V§‰Ø§ÁTU9Ìçñ´N_ƒê¸ 2¦ p¿ŽºyT.Þ„NÖ~r8…¦2mžÈRÒùæ*Á«sæM”¸½ôÙf_½÷^¹ä{gì 6 #`ùÎ9XÅÍ]5N÷Þl‰x t‚‰Ž,Ý‹Á´ã…ƒâá’ƒ€ìS¢B7o dÞ—þ|APX‚6[¯~Þô›lš‹P xxbÕˆ¸¯å…5¯½'2/ ^äòɽOIéûlyí(ÍþvŽÜ·—¬{G(É ,ÀؼZW[6VÛXŒ8»jij_¸¼¢yÏh˜ïAU¹;…(=iVfqC Ͱ|‹!bûpåÍîsJ|D œ7Ô/m\ñ B†eÌ%ØYO<½|BÊ <3S~±ü¦&“Iý€Ñ&e<Òí­K!Ž+µ£hô®LÊÓW÷èONœ€ún[žXFWZ›Z§M¼Î²÷ü¶ømdp:�Ù3ì•0Öƒˆv×ÙĬוo<N®-—ް{ÈN·ó)iÑ€O±Ó5îæMûMó)¼`é§å6?}Š=”á„[Ô ÄâÀì`¬ùöQÕLÀ§¨ì3”/ÅŠOÍÛÄò>Qñ]=‰ ¤k ¸w >ÑSï%ŽT¼r_ÇË~7'ýâ=:ä Äq×§¡"ˆ›wJÏý0ŸEÙb¢(,†ÏtwŸ�J@ð#¹³Ã.¤§anúÀm´²I H ör½·åˆJ°%²³]OÊ­S©ôêDøÍ€(ìtš#¼áŠÇ3E·¹í‘)«A pN””I· ,0&kµ¨w$¤ÓúØh�ïÑ¡{Ö¤n¤žÜÀ`¯˜HÇ]ªäAÔ8è/(ŠjÀ8f;¢™wòdSÓ‹  @»Þà°å áì‹}åïçþ‰Ä¥Æ'P|4„j7¤�ÞÉí\(–z惧QkŸ²òÏx>þG}è‰éªl' ÈqÈA_ö8kF ⎘ú ¢!á2±Xå;y;d‡GaÃv9o#ᤎnjݠ¨E4••ÖE‡X%ŒšòIsµ …=«*aªÐwØnK=Gý*d<s¢Ú¯.ÕWiˆÍ]áÖ5Ž·².쬳ç€4%ϽË1}Ba±qy¹½3ØÊåÃÚÇæO^b•ZÚÃ6ËÖÒâ ¹w@¥o²å±+òæ ˜{´€€‡(™‘Uq§éÍlLV È[¬ÑzÕÓ ù^Œ[§yƒ½&Î1wÛ§°Þo {bw÷—°lõ·xÈ€¸vKÉã"›ÅRÍ`AÃ¥µãÎç3lèû-¬Ï Î‰t.àõ ™ÚÞ *U&f“éÛè¯ÍÏ-Ž_Y¬2›–g«óI  ¿£( ‚7�t"]ãë×Q²›Zµš0°ö}µòÉ =`¹ž^H¯²:| §b õ6ã¶Ú\S— C•üÜȹæ,_½bºöLyÝÏsí#/UZ›w±8gƒò¼ô ÄòmtRW™§|¸Ö²TæÈ”ºÂîz<Ï�«‚‡Rs¢ýIÀ«rÅ<Ï}ZºQì¥ø@pøú#QN8¶m€.W¹–±§ýÂm–R À“2Ú’ê—fxb“Þ´µÜ€ÖOiÁ9›/ °IžÛ™<”p¿UØ¢#ÕÈÁË£oÏŠÏÈŽ®¸ÓûôRrÐïp6üͶ8\Ø@ª¹ËÜ:¿Š¹lÌS{ÔKj‚Ô)x:'ùDò åF³.^ö&'³A³¼ç’æO¯üg[SÀ+)º:" ^ABæ*[ì· V7¸ïM1·õThdÄ’¿B'ø Ô¯ &ŠÂ§6ˆ8Ä(MÉ2(kýx¹žñC;ÖyC2¨ebvOH;&^’AÒÜ>ôÓËu‹„éÛˆµG›"²ùÌ*y£Þëo6yÄŠ˜´"üdšPÌ¢h1¶òE΋Š[>Kz+¼Ì4ð襗£øð¶j:�R˜ã݃t´üW[Ìr˜¹;B‹óH(ëÂ;~¬Â`ÏTÅ%‚¿Äð½G÷»YNÝ·§¢à›j´Ï)¡[÷ø½xØ×È+OŽ+Úrd·j©�õQ=×Îs‘¦6>ñÆ}Ë8éK£<¡‹rã/„s¥‰1 GA Ç2o2; N•s5³žÆÀ ¦<4°yÀoSs$—%BóÀüƒð*Ïž³kt’U xÙ®ã"y£¡Nsö-ƒ¿"\x} Š¶Û‡¥ž½”yÒ7÷†÷‚FD* <ã§ú”Žpú#Å!€1|ÆcÏýø‘=ÔRmd›'rĆ]íºðP²ÜsÛNhYyÞézŠù@ŸÔ¡©®)ÌÊÏÙ0¤Û»E…0,÷ŽO$1,!à:(^.»W„¾:ŠOyágŒsÊ*£”Zæ «Þ'µº£�ÚSŸÀŽn5ˆ¤2ÌøF5?ÖÎ\Z¤môug›³ÄâvÛ~:Mg× nÄÃDhš vSàÞ“KöCSOŽ¥¢;™Ù9<œ=EÚ7Ž0™œÐðõ"ç©£° š§P¬àyæâCo¯–±RèlÒªð—0ðX÷Ìá‘¶<Ûxi~€Ùuý’dsád�êÑ•× ªì ëµá²æ‹4V|Ʊ™¼íü@£°²@Sq–»4P냊3uÝ‘‹²}Ø×c¡·¯I´ѵ‰5îH,ämM:6¬\ÄÏ@¿µÈ‡´ýxù´@@Dzu±‘ãµÇhdô�4| Œ>½\¯#D²¸ìƒp^D+¹* pÉáH¼¯ð=v+Á€}Œ]•©FÆ•ÐâYÈà‹þÞô@±šWæ£c–£KRK Åmè)ñ¨¸x¹.ÃS¤IŸêúX*°uQÕ祼ÓȈccÙ•™\j¢á°še9ñ~žj°XÆ™×Ãç„h¨ªb¦†�Rè“züpt®±§X¨.÷ÉðsŠ·XÊ$4‹Ï•K®PÄÌ6£Ñ¬—TF$q•,ÂÝã7S|âÌ ' .Ëfe’YÎ68GåùJTïAU`‰Ù¹áæ?±½KЊ´^zmŒ–h4¿$æxòXÆu1j[|ÛVnf‚Æ Þ>|”¨ßûŒöŠF‡a˜º¸o ò*'dä¶#ê4Š^©½j´s@T” Y=Ñr-LÃá{üÜ=ÛÊ‚"¸–Œö¥†zî¡'’Ò¨Š" ‚Án`·O².ž?L´T§‡uÖx8„ÉyÊ‹’…Á‹ôSx[ÜžÁŠ;^É›\,pÐ~1XðZŸT"<lŸ:"`H%ÎDQöâ‰HêpgzLB`‘ç>TlDz«Ú˜¸$ùð°{ö¨°‘ƒ³Ø'M„E‹ S4´€ø8²,KŽ|îP°V‡qpWJJlb%äÃ×õʳ9OýÆâ £ñ­ œ ÐeŠ×ý<ôöÉ;Ás¼))}Q¥ˆ‚¤ø‚Bɼîx„CúäiÞ§ÈX?}LÕ·'b®–Pú!:‡gGÇæaâc¾¬×=áúL¨”d3Þ3Æ3™çI6ðlÔäÙá›»L‘KYг<T—Íëwehè›Ãðä1ÔTŠ—:4T¾‹ê’j¸†÷2‚*^½îáÕÍ*™ª¬€7J `Bý– p̸ú^ã«Çf“¼wçô »è°˜÷iÄ*éMnÜk›ÚR–j“wÙ5>/j+ùˆûaw]ìB#¾Õ0¶ k¨Ãq‰ƒ6µE \_Ž&%Å»Y ‚áʃ Pd×о•²e*¸'sœ™Átœ6R —nHIdxÇØk%ˆ…?e¦@F4XqŒ-¸pg‡ƒé)¸¥²ÃõfAy>eö¾ã>’<w–7ǰ|n’ê;×ÇïÏB4}1Kíb¤å¹f¨SÌeƒ˜“8¥¢-ö=ôz\ 9íŽ×šëÒî¾±=„¹‰¹˜ØçÍoÇp€r_¸õô„Ÿ=u" µ.Ìz†w¹6‡ïM!:S oí½êçé&QiÊ¡: [›°€E'P�3¯³S§‹ñ �úÛ3Ü$Sè0„©—„t÷‡^L›P/º«•ç@?Ÿó§ºgĸ–-j["±J´U®]Ä&Š­šÃïðÞ’G“S.of+ íÐê Ê•4'¡îe4·ònŠ6�ì•ö1B¶êO¡!«?yë/ކ(Ìî“Ö£ÕÛ}QJ]¾\Oˆû;øËgð§&§» ¨0DŸÎLàÂ'ÇʲÜ54Û£AÅV�èÒ*8¼a¤­Ãf¼û\öQ¡Ù£‚6[›ÕòY€ô|SÏô®N3Å †¢ à4n°D&W>[HÓâ,ƒ~ᯑ—9V´ŠeÕ9Ï… ‚ÕÀ%ŽÇ®m^pu¥V!•œÊ®tÊhÇóQÝá1†"ââ÷ÌØšôrÀ#r`´‹¼²AÏ#íÉÁ¶Ñ¿PïNyÜC¯ð‰Úc’·,ÞÈh –`uT°= ‚Õ.¯=RŒ8€üZnûF¸|/Ä÷vAÁËNº"ˆsÂ@|Ô  Ûž6’¥âîÏS‘˜Jˆ½ æ‡Ý/»ø>)™°rœ×ëÇÞìJ§ßRÓÏ  ÈS3ñV˜¥º|w´³§B©ìÎéÙ;²[®a¦�}VéËŠwùÁòõú£dO¼Ú�L®é–À£µ‰Yá}!B" àíA#’:I-Z„ãnNYÍ,'{ö¢'c}zê fUl4Ú^>¶Èz…N5áØymAú ѹ5¼–âÍ—ZóºA÷dÒ/‰ë]RꉖTç°`�‹!¬>€¥BMíhø˜ 2çÆÉTÊá‰Ï˜GYbUw¬í«8wÜìÑêÇèü<‘ï¾-2DIìkÔ±›x!¯Y˜ö²“: H¸h€Zo '9Íî¡“º¸ûïœæWŒNOêÁ#"ªÊ ‡2©åñŽÈX/–ôŒÐä[lþék¡ñž š¼€£Ì¨À7µG«.¯CÎG!êÖj}–ä5iÑ0Vì›Vïȹûv£°ÉBí(NÜØŸs=´ªÐ¢=hÏNe*‰–Èl>ųzÒ¡Z&‡Áx÷VB(›÷n`firúkæcÛè©UÒ{’P  /=}DW8óhˆgb’oÎRÙ"Õ“ùòÑ¥ÏÔø¢¢Dx › `4lBá{½”-v2Fañbßz sœ›�öº”Së¤çP/!@zÈx_ânŽ5›Ö3nA(s[ã}|¾ÆÏÏ­Ù™RžíQÕŠEdíôÉâ±Ñ¦CóèÏ3¸°mP[€ˆråù½µ<h:7ºw%Θ[<ö)7û ŒPŸ(s¾—Ôæ…ô6·O\L²ˆ› œ¹IÝdF žæf4?§M)^m'­(“››úŒ4á@LL§‡CÇ‘ øJE°õ!¸¹è€@!¬æ³rÊð¼òè]—xÓkq{ìt}ƒd‡åÀù*âé½ìÈÇæ‹«  Ù#…—Ÿ@ÓÄP<,èÊš˜ôMd|‚úš³´º†û=šWà–-–Mä2¢ïP'ߎ¬‚í„…áÓ»‚=>žbð+~4'[ôò9‰^›2>L2w|í4:ÊÏÅLž¸A.§s1d%ʃ[´ð³=ˆe–t•¤\ˆE¸ïìù•§à½gKÈéW¿çF(yÆ#=^,ò,òÊ)ʦy„µû"sîø§àüs@Ðr…á0’ÄW/¼Êð‰½zÃÖinž©Ÿ¾Öç…&X,œTÙÔœä›qsðˆ™õ&Ð*oÓc'.u}Ux1Ö–x¾¹,þ2uFi#¬ÇëUÖD¾I`š·7iZÞ‡ °(š»ŠÈ†:y!¦ˆ2ݦhï6_Œ H(bÔ¦¢Vݤ3‹€\L@½F‡Á$f©@a_Tõ‹ }dõV䢳à–j†‚e�pWFV–<1w˜º#Øq¿×·&±WÌø°ÖƒÄíÖÑmåªÅ̵l½ÀC‘:XçxÈöªÖÚÕøPAkGîØõ^Z–úÎI»l!¢Õ­¡qü^áJ® M%kùˆg¼éç'øðNlmÊÆµß U}J.èSr è yìI‚ÎôÞl—€×�’ðH xÖ Fzyu”´h <ÞF‰R‘û@ÒèË>| 3¹Òð u%œš9OmˆGžìâ‘ó•—²y¾–‰÷PÉÒˆšœîžÐ’¤m*øhôîãà#´PàGêïHä…Ž'zS(âFAyÁˆ×`Œte¾ fÌïÜ6Ók×3C4<B·Ùd‹êí 7¾H`³õDÃWf"­/l½C•—˜ùÕÓ@:ç÷c¯Ï›*õà1Éa’-(•RŠ˜êµN½¡ÖÄ Wxh2n4¨e¾ÕðÐÑ­Û\„´)Ùo³9õQÇ Š@^˜A3yžýô¹íŽ÷ÐTOˆ-Lô4mPŸ¨S曘1É󵯥.| Å-k¯4‚¹I˜´E¹^'±•®š¬«ãòKöðxæR“³*4/Ç!¥]jž¼ܸ›lv”`ߨ{L™-ÍýnýA7ô¹ŠC* šyÕNž ¦`‰&m©s¼LŠXÒÉÈIM:ŽŠË;»Ê'¦)fE‰+ 7gÒ–ú ç‹“E°æÞ%^Kœ vŒ¸l+Ñ«"‹ÖÚJ Õuwu6Ç ·§¾–;¸°5ë$ÒÓ‰õ"â}® óùx ÷T‘ö›’g× {K.°3¤.ùT±ëâ¡Ê¼RÞ#)· ž;͈Ì!|Vó™Sß;'·Ïž!–F†Ÿ-ýn¯/_ -_’ö»¼u a?©Wbðâ=–W‚ån7ð-»ÏñÁ9Yt—<†ÛÚKdž{¥zÏŸ“æíÚ=�Ã\¬j1(é¶m½`ˆF«“Ú›±ÖJÝPï#ô¤âW#}A–åO—=T£Il,3;jšÈiÄ˨€•lÎQÐí^ mAI šó;«KXÔ.ÂÈyyB/ 7Ù˜_¦êcY»†•~ˆ[ÕËÔô žé0X¯m;5ö‹j¬íç j²M©­Ç;¼Röp„X‹Ê"Œ'Ay<õ»|×ÇX^ô8MïŠ7$å {Q`º-sÀ&Øó—2||åí‡Ò ¢++ç·µ²x%1jÂ!´ÓšàÄêõ¬ 0mP–ÇAîï}œA?dWž¸·ÞPnéÂôP !5šŸ'¾§â›»;ŸÂÃÏA"mÇŸ½ènÑ*œ«CŒ!‹yHå®î:Žp –Ç/ÖíÅÆ¦=M…¶GÊÚOß5îsv 5†sàÓ ÒÇ;7Gq˜HÛ¼> ö†‡ñÄDJwsx=RÓý–á²—Ôê®®yÚn"]@•sL6ÝqÞ;‡;Ù³Ä|kåq}ép¨sò Dw•m5ôU,Ü J)†ÖŒM‘A‹Ö3|.ü|_8r½­ØA¢,Þ|’#‹sŠ# Çk¶xÓ,ZÊîœ ]×¼�MÇ45OC%Üù4 ÕŒ–YNѪ™GOà í"­R)�d 1.tT«ÔñøÜÄkx‰€yq£ ¿GŠñ&±)Sa=ÛÃé+zaºe¨/°ÇUpä­õK©ú”½Oéé-Ãôõ$&S¬S–À2•œÀI»q˃¸B:Knï*éËdÍg"ˆú•ç À$*°8ÃNy˜3ö[+€£&¾†B¹i†q¹2h†~Œ­ì‹IR‚‡cëeçQW 'qp·}Ç£YýH¤ØÕ¯ŸÌ8î³-¤¬G™m,s289Ö{ýÆYËåõnd�°»Ú-Œ¿¼;¶šeo"ÐVêgÙâ!¸›µq¹ÉÓ[Md«kÐ$ %{‘0"oÒÏÆˆ8ŸwcÙlgâV{áS^VcTo,,Ciì‰Øž)b/Pxá.Û9ÁÏšëÜ1µ¿d·|/Z†Ù¸3ÉVµýîçåÇw¸F{"ç;q¿dõìi2RÕËÆðOñ1}7\T»6xÍ™WÌÀÂaýtæA` ÍäFŽë/ f U|øª ²Þ�Á²Ðý“!*°¸J S{íc¨·ïáŠ*"”¢0övŸß€Vû â�˜ËŠ™ûN$¶´±Ð;@gZÄç4°Óaˆ¼\VÒÃðBɲ¦¼8fÞ¨,ìFð0ËK÷"Á–§«ïñ›h{òÞ_¯$ ^¡È“z‹¬ÖaÌR@ñ^{CÏ32¾|ï*|Ì“µ¹Ùôeíf[‹Fã>NZ)3hxç³ &‰ýÚ¥¡9úaM·¢\ìv½[}ê�/·WŽaq»uŠ('‚£Š º;Tçê^.€—ÔÓj�Ý_ò‹§›qül&}ÆÂÓÅÄÕíqk pjª´‚ËÕwÛ…÷9fpr:F?ß›¥œÀwu�‹ž¥Õïð rÙ@£y¢{)>Ƶ%îR-b~j&î%°áÔ/8§êZ^Er;³³&&¡@¢°ø1ë�碟ª¶‰ñˆô»AǦXí¾YåM–ƒœwékHIEûfè½Ð)óXUFƒÞ³gá™XÕóÄÞ&Tåƒç1¦¯èœ3§U Ÿ×Kè ¡§d#nØïº¤Ì =Mh‡|Üð‡‡³rLßäC’DN¿»Ä; z™-¦ÍWи$ª†ãh×$üRè¤Çí£7˦÷ZTºÓ‰ÁfbÏtRÊúmÙ‚ -“;X ÞÕ1› ›Å4©ž¦ÔjìË íÝÊý?þÿüó¿þ§8þñoÿšü_HôŸÊø÷ÿ(ÓîZÏëpÇTŸ‰&(Ž*8ܽÙÇõâÒiò•Ãùã—âüT&À¯ç¡f.‰=l€<ìrÀVÉd¡$Te½èP�%N3Q™9v_cÑçLÔýsÑÇXº*<×;¤@7n§XJòNéJw·ß>¿¤5Ê/L¾SòÃ߉©šˆŸì«á³ ä‡}èÙ`‡ª†”Xƒ¥ÊÔ=|[¾Üã37á¹ÙOlZ\¢ÖIºÝ<ù¬_ê®’/ ®À[\‰U»Sj¤÷ñ9ß´qûæ~~HM½¼·;0Hˆ/–íîÍH-½š¸ZÑ4\·)K½· _îúí­„‡ü²Å~}R.tµ‰ÍË÷E£¬·§ä4ìIB!*>uö^‰²äÁFï[ÊzUö–âç’‹tä{l¼×MH÷gö ϲùµÛ¶x¿ÄW¨IuÍOëð 'ù5br·óîÞOy终Ké-—k}#o¥ERÄåÕÃîg9(¯úá1¡Ê\}½5ý”÷Ëwôü ’þü°p×½�i¯2ÚI§pWY0 ×8ìÐ÷3c,¡ÕÍÀº¿ð2ú~wªY]v¢”M~æØ,?÷a \Â4’"låê¾´~{.þ*^_²Óqð#z"_Nù)ùݱGDdŠ\zÂýSgÁÊÙÃ÷¼*0=Â3a}ΤÃÐ 5 ׆˜ßƒ0~=6±ûõqŸâßÜé¹ÙÞ'r¿wL§§2›9bK’õZµ`†oeÜÛÁ$Ù¥wæ—{KŸŸÏ@jwÀо[ß¡áŸØä°°' †m›¼@ï’+c’¶fêÍ’¾æ¤GÚ¬9|­øÕ|à{P¶§dLäHtìØ\O÷ýÑѹö¹ÉeÙ¶\ÄN¼“ €>­?Ãŵn�W·pXEþlHŸ¶Å {£5R¹äÁ–¤’ülã…©CxûžNöÛ²–àÔq!îRÐUîØxcˆ)öèùd§|}%}¾“K"·WÝ îë{ˆ©q`D?o^mk],zÓêÛdû"†R+—Ê-0Ú)¶jH*wž†Úçwú§&)<‹°{Æó=±ÛYsBûé‰m…´w4þº9²ÕÀ²‹/ »X±â‰Ù^ E'i})¾§Å }ðx¦iû„Bcàlw~}ë ÞÊ­†g¦÷ÔD$/!J¼]àæ°`‰æÕhïÆÀiSúúÖ÷ùŽLÔyºD´Éã*Ý€ð"LÂýùê𠶯fȧ÷=FSÕ>×wBX±ì§ž¨ZÓB†ç|}­Ðg×}{ûXVñ2ï‘[½ñÁCê [ù­Y\Å•yBÀGV®‡œ•Ń&ïQ¹€]a£g×§Kéw"ÅàðPQ¿U÷5‘¹ jÏ&Îå§gåÀòQ˜¨mP öö„ˆÓœeÔVÐf’í£œ°J½÷ùÅŸ¯l|ÚoöjzcÞÛו·æïYårÉcE ü‰r½-™%XW°×Y%R—Ê)í­¹(jÁ@ èO*úˆyÑ:@?¯âöÝ­ \nlñj3ZA³§¹Ž\3ÿŒt𠝵õXO_Cކ1G@=´g|nÙåÈU$Ux {Ÿ~æß äÁ›“©Ó°¥F½¤˜½lÏbQEÒKøépq"Õ"“Oµš§ñ<œ%õA<1š5};ªO‡KÕj 2¾¾;èó»·«€Lâì1^h(·=Pìq.)¾K=äþíËújû¬L®ÝeÄ…ƒÞQÙ°eõÞð$’V9þ!… B…[û}Qüüò¼é ÇÃóBE<Y¡›¬}\é ÖxJÖ=S~:‰Ø<M­öËbV@aŸ² oÕ÷˜º9¿&ßrÈ{¯…úóÛýÓ§«ý¹ÚéÅÆMó"<í\N¡6Ûy.®°K ËPøóë­CT€GêM•é»óU½´× È4°ÉòøT£c|ò2~=êwÆh!“ŒØ~Niù$6ü.�=Ÿ ðc²½ñ÷3mê,êËPÒ‘|'o\^6ŠG¼cI_VÚn>t²€à—´0 _ßÿ½^€ó¢ñë›õ¾k´î+D3ˆÒ§”|üôÊÚ¢\~vÎ2FªÁ"‹k5zCزÃ/VnC<[=AyBFØ/?+àïWÊÍë!w’PûœÞôq|Hç&—B¸¤ë²Ù ï÷føšDfßFÃä+ˆ¢¥Ë&<x^O­Ô%kŒ´=>¶ï|²À‰®î…Ð ;çœsþ<ÃÐÙ¹´ö; pȦþ½6Ë—p×O5<ò½ÂêGÙ–46A¼–2 ô„×i„‰û» ÿL‡ïJ°mN[²»d€èüÈ'! ˜æÜ5ÓÔv³³ÔïM ¦œ¡ÄòÛÄè™6غ(ÇÃTz (c›ÃÝxX!oœ’ó¾êø^•ÄÑu[ÌBÀh¹õ؆¡7nj!¢_ÓÈl\ØÊ”fãF#üž%ÅnaÙ{8‘ÞfjÛ$XTwƒqòÃõ†- Ó+N>+³÷UÉ÷veÖ‹/ó•Áƒ'ÊÍå+á$Œæë¶o`ÎdßÍÎHB-¼Ÿ=.D ]÷ÞÑHÑ`õM ¼Vß‘­(h+Û¤@19ÉÔXõ¯Z¾2J‡ò¶9Þ@µ‰ <i o/·XP‘ç˜64q%>Á¹ÓjZò;kÜÝpœõ4÷-`Ô{›Öí¨bÙI~( ;b&ëý髚ïNÑômÜa,q¯MR>^Ù¶VDJO¢Ü5IweóÅ·RW9ï§ ë‰Ôö úBpTÒ%X¡‘]«¾À|ï“EJmvÅòcaúTÚ÷ÚçÙ‰†e{3>ˆWw2~–Šœ,Jð°•¹ÏÕURLÈYv¨éÅϩܟ¾¨»žçBVAîë“rBWY¤ð¦%û”Û<³©±zPšŸ™*¾³7RêPЪmÝ>׺ R…N“çïîõ;ÚN*ȃžyÌÑZ´ûVÞÏšæH½å¥ÜÄV뎸y#öVxq)´/vϸŸQVPj—*|%\†O?ã>ª7}P—nT1^HÕ[TSHôãü˜HL1lc)ñßû}!×IÇ¡D¤é†ÊYìLR=íáiLs[Ô¬SoË]QËíáWUøé µ[=´|žñ罈Pì0Æ\Uëiz›@ÐË™¯ª!í,–!ƒßS›|õÓ#¼Ür€³^ÚW%èË×½öîù¥ôÊ6Pᡱæ;± _uѧGXV&Ò6¥ñ3µ·ï=| W*1à‹­:Û㣛$—OpTŽ|)ÞÓòý½ãlÉ#Ê7Ù ¢— ãKJ-’`Þ2™ţt:ÍgeŸnÑî³A¦åy(«+ûȹÞãbg‹·9†CœÊˆƒÍS#.‚S«T„¦²_µA¶ YäÜ©¨ÂÓ'Iη=oAÆýXÄ^óX¶ )%ÝúWmüé€ûø–®·ŸÀvðjɈ.„‡.ÌL€½[d_vB ƒv~½º9MU®uúS“h¹0U‰Fé©¶Ò´^HÃ3 {žhÊwïx&í«º÷é ÌÄlÏKi÷±<=´~{TçcÛƒóâ*Ká•s4­®Ôʃ¡¨$Ëòeˆ|¿ÙCö5Y£›™ [ d”<ÎJrØKVbHfˆ «ž•4oFñO‡”ï”áAòàB_{Û«¡) †÷']ìyó{ãu ™èñÞ¶S‰o5û5¥V KhúÏt‹Õ“÷Ç+å]HI¸—ªX9ŽdÏ(hÎ"ýºµÞƧ>õÓUNBqn¨ðînòÝÕ1ˆB£JÝN–÷B­ø“ÙòiE€W6ÅþÔädúŠ_RömhÿvÎÑ›h‘(¨Ï/Ùü5€S¢&˜HA8"„nïóâþ®ñÛ_“¶´wÇݱ—@ Æ5Æ81WyÄH‘ý•CoÉ\³탓„M”Î�ÛÅ&ÛÊŸZ!εÌÅ5¤šqªQHƒ™ÕŽ‹©Wåͬ³�ìé¯*íÓiЧ Ž=2~‡ø@˜z¸™/JºçLð­‹¿y)Wc Õço`ž‘²¾Šº,œ¨Ÿýß¹‚m#45VB©¨ô*†R¿ÅdI_o#ÞçICµÙâ³ú÷ã—•x‚ñúMÉ¡éeÝ‹½=%K¶ð>¯J?\¦7Öv(Fá›Õozm<z•^ÄÅOF#]Ì®.WFS‹ïPDP¨/ÑÄ€¢!j«.Iy"Yù«ÒøtŸÚPµüÀظ£ŸS¥ ­G\;Vf"­´ŽY˜ ÎÃJ¯=sï)é{ ÚÑØvй#qaó«Ö˜˜ª×k8�±F© ‚Ùê ûâ$¼kC˼&JwL}Å_Söƒït³(C›ö:Nµ}.‹Í&0¼¬PgK+a“Ûv ǰ¹®Yôp›™Kf¬¾´üÝW&KßsD–§Ú×]+ôлq€¯PKJC›eŒÞé‰t•ÎgµŸŽIµ ¹FÌeã&UŽÆ¹³E¹Ì4+ŽýxßÙQt½Ç ï*à^QMmop …«`ûÏœpE·V�eÒ¤qß„_À[ï§ÓbUzñšœ:½‘§ŸL}Õ‹úðŽJƒk`Lö":·¦‰rî{†$Ë£S6^r®j&usXsõ!ïf{B§I”ébܽuô$Œ~ºñÈë:i‡\Ä„Êy’…^r`ýçVx¬ïY>ß=GÐýª˜>]j.µ5)ÁrõÏ™µWï=‰Òx*3É[;­ˆv³_ŒŒÇk¨S%Œ£ßXÏ"œúÉò@>ÉÙ½××6¡*ݬ˜ Ù,ž¯ºJ¨l“<ëy_5ó§_Áôtd¶N¦t"ºµäºG×qöIô ¼Q¼õW˜v7]Ïæih/!¥ºVEm¤gakXéh2ÿ|ËÕXݧì!>…�šÇV@[ã!o[¢8»r6{§ZŠpü«ê÷é\³äZùt½�ÄðÃö\nÍÅùSà}É[ O]/"Ÿv¬;Th‹='§uGJÒ•t±»V±8e{t?Ù¶š%ŽpË´ÉÚGÝo¸_°Ciq¤]æñK"æ§‘ïå›Ïº?=l·ºÑAŒ„ºŽ/ Ó˜Ytd^5F6åCÜöžÝµÃ¥%Ø<Åhæ„»- ›)³ ;ȇÂϦT«ógå{þ$³)ó -Á Þ;,$ш¯eÏ>aÌ":ß¶XÒÔO˧›=Ô’žŽÛ¬aÅ˺F‚gâ[é~3ê7þ–c¸ ²I^ذÖ㮵rIMî­IŸz+ò¢yW°J¯K³qÎ :%øp_«y)ë<¨dµI:¶Só*1½£r‘(´ç߬맯IËå©ÓÂ9#6Óú¤“¿|; ˜’¶W¢Å]™תlúʼ¦rAo}t趉¯®C€MÂà÷urj^‰øSÆPB|*×LðšÆ÷áVËjå ŽŸõ;8#ÿL)öép†j‹ T‹icîªzNœûvƒ ›4¥Ïz¤:QT§i ­˜aÎ Ø"ætì9Âî°rN¿¬ˆc…§?»‹´Å®^ºï< Ò°¸YÜqžµ…€÷ˆ±dô >Ž¡OöýÓëè&qª’Œ [˜B.WãùB™Îãµ÷|P=”ݬtðõ;ØÌÐFdóχg“ÒϹ›W¸¯~çTžè¨ƒwBl[�QD0Þu€ìÌ7i©ê—€VLÆ=o^}"ðÜdðÙKÉ,zDÙ©ûÑÍ™S ©†.ð ¦ÚŒ¹ÎuàÜŽ`±Ü³ÅÙòô¬WÑ¥VhÑMz"œk%¡Ñ‹‚å?1P ‡!_Zýó9zIœä¨–È`zÏŒbžu¾[4£óâù|ñæ k,ÞÃ9x/)ÈÒïDêÕSkæƒpÏ$á¡x9SSLÂÐ0À a"$œø áÀø©?�³8ƒ78­&Äôß(¤Ïi™Î=Œxg|˜Ž¡¶f»è°Œè<Ø/EcÊå­âFÈ ŸNxb­@'6MуŸtÄ=}àΓ;BJ.1=éÍÍ´ <áï0ë%1У,-óaõiÉL\~á#̆믠q^ýô²Ô÷p78êéR³ùXÞ¬ö³$G‚}î{Y†yàæÞ[ü…~zâi®äé £éÔ]7¥–{k©\p šgÔlìq&2¶â26Ë{õ¦gÅ"ÙöjOD¤^c׃Ç1Î’Foéríýª@hê½N3ô*{¯^Šó"h­h“Áy=¤£/$èÓQ׋Ç/Ü7ªàÍF‡)™#v÷¾ ­gF¼{[©B5GxÚgš"¾8ãá࢛H °³¤£µè›ä¸äà9Ìøù:ö¯téÔGãð™¡ca7j@U¸ˆ[È Ž …t3ç‹OŸ¼~ôv‹¬Ñ±£Ed¼ÌÓAÊ}*qšòÑŽ,5lÛzч-—E4|—|¾YW:Üh¡¯ë¬iQ4šÊðÖ²]ÿ¾¼_ŒöF—Š‹h™öØVò r°Fä@aŸ(Ùó); UûBƒ?3kù•¼52~5•6âÆúô‘`¿#,æ«ê ±ËŽdé·ÌDw€CìЕùöü l“¼¬â¤tâø-òq´Ý5­Ñ>sw‰¨”ßY…u¥B ˜œWBÌ€'§UYÚæ˜G¦à’§¦"O¯¯B²¿ðxŸÞÉzq*G/|Œ£â½Ñ½ãIÙª[›è‡žT°Žû^=‹mâç(w«$JÆ‚ˆòòú¸^½:ˆÑ~öÞÍÀ) XÌ{` õ;Yμ»W B÷</Ò„!õésŒL)cgûpò0»X¶ïó½}+¤ÝL¹s±3¼Æ[Ê©³R^¶3¹žÛ†" yî›UÏ™“eŠfC«áGZn$ä/¨Ó:^SãâžhÙ›*•¦l Ç›bÐ6Ë÷ ËöyUÂ×ߌÒäÞÖ³§ê'úê)ÚT ñ8m©î&úé§ñÎ:}1å¿Öî6~U<Œí•Þrî°Y>$·ƒlÁ¸µL äzãûˆ6'¢Ã'ßœ­Aî{VYÞwÄNãif I×ïjŒ~ÏÝ‹’ÊÄ”TPÄňÃbŠ6sƒ¼x·|f¤A9Ë …>QùtVärÄÓ*=xwì!Ù»cµçÓód -°ã%œƒhÝ5WcS1xaE/€#Æ ƒê›gO·@†§Ó»”öL­Ü†ÆËÑŸy¬x@òl½hZ“A±ŸÜ+F ¦ˆ`"�ád¥àl*XÐ/\L?qÙèJ´H€Ø¦mp3žagÖ‰h«#«ZrúZ«õ9`/Iú£×û’tĤ<õ asø#hgf·ik ¦ÃO9§™ØöÄ*Ã2=æígK›¯’bÑ,höú•™¼~ª¯fQP=êÜqÛ¨Hü ÿtÛJ)µ’mN¾Ë¥Æ˜q4MÚ3iè `#™']� –j’«N©SçOµ­ÔßKÏVų½öeâ)9j}¯Ì‹æù,&xæÏND©Z;ª>Ýøò_‡i¯ À‹Á‰Ð(çÁ.=l°!¡úÂ&>}ö’4[ÔÕ¦³³\!˜véTî^”Ãeäª<•yÔ¥&sØ’+ï*ß”ƒÕ’�ó^qÍHápÇk] ˆ*%˜WXœÚq;ôÆÀ^(üt`:Â+u®È¶TÞ¸nƒ¾8wë ‹ºfAr/rzè(|:pÕM0ÞXÄ˶{,d66>’R¾o'tèô­fÕ¦¤ç¦=¬í®™B³êMz¼5�Ü7›ëfÝù&ã)H©i``Œ0ŸÙ°¿N@ n¬Ÿê:À5|0õn÷üùY^ÞœæóNæa¥67)_ŸŠŽùÄçÓ‹À<"n¸YÊóê¨vÍ2‹²ÊÁµI#¹öŒû¥àeÅ»(Ÿ=ëȧ”©žGË+¬ç§lð£©2ß?»çóRG¹‰7q$d+›­º21C¢<[F´g‘tÅ,mc_Îc¼½Ã;J=Êâ¤/„ðÓ•õ!Èvº² 4ÁZ_eBB¹CÀSÔwlo4°§F<3«Ñ1.²ý•På5ÜZÏT‹¼Rðlx­ãSŒšÂùZ}{™Þ¶ä‹»)‰ÄM Ê„ý‰QEE•º4=<å›:˜Ê¬Þ30É«| Iw·–#E¼@Øö…}úó<•WKîÇeˆM(ažÞ-ö GÔ!!(Sø±Qöf–‘$;÷»¾7>›)vÜ ¢ÇH¡¸ÝåzøÂ±RjG³¤Þ _<m§ÖÎÕk|þ¤¸ý§SŸ3j²Z&0ê$‹Ò1ÆÑ:ÞK¯¡%&$½—lð*ù %þtj¤ Žçî ’º*Gu°XèMÑ·1†oFâTð„ʽÀ[Ü‹<ÕMº~€ˆÞÇ$¢D/åÁ¬îÍT'…îá�?<)À۾Ƨ5E‚Å59"ÚC?=)öÏñ¨ˆ¢Ç$)EÇÕ²(QâUCá­¦yYÈënŸ8½OÏvı”cmžÄ¹^±ìñ,nMö.‡Y«‘mkôî©xɳÆéËR9`Ë?–=Ô¼{YkV©x*NzV«Ž%¥#‰›.K¹Ñ#}nžŒXò"u4~v·µn7aM­Š¦k3¨7Áú@梂ì´d–t‘Åèõ'RŸî½õîöÞ<±j3Ä»—iDŒ$yZ´z^çã&^i=¬2EÂ> “Ε#§Ê•ˆ)§§xÄz#ç#ܲ‡Îɽ­(%ÐÖê¸f<qg/°¤›ˆBûç|ºeräiä¢ë1o#3Â`¹@÷ Q³]ê\>Píüô(ÑO¬Œ|ViL\T�úµY>rEêqxÇÐ|ÃzE-É`¤Y°r|d±`Ìc¶FjVK6„*‘op™N_(™²OådP['“Æ>ÀWtÜçåñ6ÛE~æ& ìxƒOðxò5XEº:Æ“vk©­Öf˜Ä iéãY!ŸÊÒOGW~~D±V8Çem&ï­ ê‚£ \bk»£Æ”½6ÝG[á|ÙE¦9š0xi%0¼\z=±ö ‚ -kçÙû;/½N¶s@­àª¨X0¯©0à¡2ÇRÔŸðé£%T¢C)ˆŠ‡¬ꀨut¡M쯼-™|d†u,¿ð²Oo…d7+³Æœ¨MÀÊJ¶ÊÙž|XÏÀ&œ:7I\E&êÐÏ#oå!Ùsª\p"ñJ 4¤#¥¥ô‚ ’Cˆ¦Ýì±ÕJÓcí:èµ,µgÁïúš!7óô§ËOæ³f1B1RÍ2 Ò¼#7:Ђ«°—c©N6Çü3Wù§Ëƒ?Åо{ÝúÊ„:ÄÈm%á2«A:êÎcˆoh˜^[p=¿.?¿W€Çûfê9Kð�°«†Ÿä¬]æl(ÊM “¹l Î ·O*“§ l‰žº·>ðR/Ä_˜ñV!¦ÞÈk™ÞWÙÄ÷¸=»æPçU¿Wëáù£ù}böé÷êíçþ¢`u¡#4R\5OÓ)*è˜{"_2††Xâó~ì‹K'mŠ‘:²³µ’=ŽÛ^m}j>à¸K’&Ã1oÑç™A¯“W¼5¢‡GoÊHž %ìO/;¡E £`7oò£˜­gÄônŸH*]Ú{˜Yݨ}ýà.¿P‹Oç/Ñgò–ñJÞ’_§=>ãÓü<°Kôµ¾?+Ce­Ñ׉;5•v-Íû�^ô†SUzÛ‚¿eFö§!³¦%ï誟°l×n5s5ÙQúé‘­qÁUé‰rÿLå‘é^Xvq¾ùûµtîs $¹''6›S>Eú„^ÃÄ—§Ù÷}F<[U.ýñ£Uè½]ÆÂ|›=A‡Ds­Î`–;x¼B~bî»±¯÷ꥑo<ezAVjÒóîeû;}S<Ù·.Ð8ƒnïµ½Þî‰Û7MøÀÁïÁÛ,¿'Tòåû}cçcb•pj¨Gæ R»Àtƒ °ÀÍn‹©6{¶€ù…~'}YZl,@Ñ'ZÂaÂwUç= _7�š>ÅéKª·FGú&r$pov­msKn?D&.5ÚL|Ò‚$èò§:8fqxÄ$¥³©¢ÀÇ/9ÍðÓèþ]ÛË\:~ôм+Kàu%f6O 27ʦS£i4ˆèvß7ÈB‡ùÃq×Ä_%õ+ ð±—m¶Þºð $¶ž$­´ŽËt¹&:¼vƒª8€›7]À™Îäd‚âŽ1c$|¼<Ä–›iaAê)SØÚ ž±mMbaÎíyø{S (Ö¯ò=EŸÄ ÈK°„‘Ò6ÄkÔÓ–2ì×­ïœ>Ñûì},Î]sóº ” ×& €V—vA.bÌ–ÞŠ Ë>[0C± udy/Ñàià»Ø+}¦”Ä}–/n…ò5`+Cߺ‘•ãUDzÜY7ât ƒØÂC+¿µŒ½J‘ûJ„§Á2³ËѨªš¹sœ‡Êù¾ö{é‚ä¯;Õ3€á ?ÖOÏ3ºâ{ˆR9FÔ€û‚+$â´¯Ÿt±Ã®ºvÉ`¬ƒfEÈ*¿,„L¥ Aè5êá)ñh›£R»fŠÓ?_}·Ó-™ÛOdò]UŽôQ‘•o8W1&]ζ ñ/•ˆ˜—™r¢–©‰Ÿv\ßrä¥\mTcßVн @‘"ØþBðû2jºÛ¢)¤/ÎÍ„ŸÎ2ÏÑ‹XBg8• 88’Ε7û@‰a;Õ‘£íH}¶’@Aw3¨ðî@.øFÄèj)Äb{žWsúhÓÖK-Òem¹:jpx/wó¤ýÌÆ—y°!„Öù EÝ÷h_?œØf^T¨ƒ¨ ÖÃÔ9Cû…¡Ð'†9 ¥¼ŠMGæ«ñ^JÒ8„ã>�¢sŽl}Ýê²\U�\šzZ\nóYÅÐ JRQ¤M³ÁÜ“Q˜!¼Xª€Ë Æ(|å-¢Rðˆ{¯œlä€(c�…ø…ç›B`{¿7·&”™±k¤F!åsC“y*" L–Nèõž@­¡ø}}]¼» 'í^/×ê¿ ,Þ>ï§=ÇF€|æ´½ƒËæ¤QVKeu‚l‚H1 Ö‰jÕåh-U_õղߺ2½Uæ»Åp_¬–ì“Hq‹Ë@¨IPX—’“Ò3Ó¡Pމî}5?ÕXÂîHÄ ÃÖ»Ð98Ü3•¾‘Á#cNîBÏÉ8Úo>qüž:â"«RE‚v§Þô Meø5< V Ú}“IÊÀ<à(nQµ/êE‡“ ‘?(º“‰¹09?jZË€6Ú—n9N¹*¯ðÄ’ws¹.¼åxýç½RÃírm¨�¿Ä¦óyèwjè…>óÚD§Ûwàž‰¬7Ñ KíÆ8˵?¹Ú’ß^öDHê”ܹôÅh}æ6¾Ñœ&SÇåj¯.‹¢dê%•árU{0uuè ˆ…ÚfŽG¾/Ì­ õuJZÆŸ2 J@{Ë «º|ŒŠÒ(‚/ 2'èཅ’¤ŽìèBMè¤s¼¿°´MGÔÕǯ±3áhLÕDéÁÆ´öÜhº?.R!óûì3ß7aoÝ÷¢Yù¢Ø‹¦çÖƒÏËÅ’š­ÎCcÓ¹Þh¥7ì’!6ù.â ¹ÇðBB… ÷±¼ÒÒÆ3 ªèÇZ ÒUF# ã ƒdš(@)ø`¹ùäe°*ï‚m¦!K"úNé…H ýD“uÜÝ/³ßøš×“ É*”y0áãÀÞF$µpB<ò86¥>SwÐ'š{]÷)¦ ¢÷ Ù^ ïÆ<l«€œ}ÐÓ*³SU9å.)…¯˜Üœ„�—É=Ù]ÚJDC ¾ói'lË÷ °�ÓÆ¡%v\¢õ’ðz°ìknCr¢G]†ZÝ¿ð X„ÂN²xcSc•ûjä`Û„ï¹Ú#¶eÞ|rxú÷Ýù1·002*½ WO'y&ë5 B DèÀá÷:ß#®pÂWZ›Ù„í"æó®yTÔÚ;ÇDod·)Ìß{ïˆ<E2ÅåQ ½êá‘‘Ó�Ë[Ö±§Dô’/&VxmÁŸNW½ÞŸÉ<!}tDº»dÛÞ4ê¨vT�¨ªìvI)mr´>‘÷‰ègJ7^hµNå�ÒRuð³LezóÂB6ªôuââUX2>Kzǧª i4†ü|g °m‰„›ßà6—>›ê=:·¸·åŽýœ¡,Í;�·ŒdSµut!ÏæÞœé¾€†¢Ê¹'ê¿§$òQÎT`¸ö#Ž-äk)mWh·Výˆz–¤,¿0Åïi4ÐJßÅô[{*—¾SqCõu¸L‡s§À€+ŠËHW½JÇ‘zõLpƒäH«;pV ß‹Zx-ðœ!s9„¶_›ÆSAd•y»¸¥®G›~že创žüF:J©ò™ýÞÒ.¼]áÇ×YÜÒ36G£»«d›ï¡; ojy{­œ6}¡ú} ?ä£êâî—oŽ¼ÃŽæ{Á£å©Öº»2=Þbô¦œÂ|h]\Âå¡`XEa—T£×ˆØœ#´—‡Ïýá‹Ê(º÷tbŽô2‹D„Xù¶ƒ›N$¸ä‚¿�«–P,‚:9í™,öœú…ë²B=z) jðŸ³Ð»§‚çÃÅ. xônbHuÞŽÝ©~âú}?_sØ ‹Èym&,ófJû˜÷XÍP˜¬ïõKñèšžy®§ç€#/2XߥS ¦ÊÛ6Â*ά魗®©yì¤SA,häǼ|•.0OTaϹÂM³;/)#Ü’ä²µ.>HB \‡ìÏ! õ]±X/¥c7ܘêYèFÜXÄ™î3¥zk›%îŲßw}Û@Ø!. x·:ŒUó^[”Fð©9*O={ñ,AXí)Æ 8 æ=>iÌ Èb]±¸£É*sH*¡`ƒÉ¤뫞áŒ$ÐÁèwx˼¯ps›QÆ[wqA‰o0ºI½-±Ñ¦~k>úÓ 2gl \‡éyd2¸o�Ÿ´^ú²ÏQŸ›.Ô›žé”âOl?û–„¼Ê¤>&Õ’‰£Pt�‡¤ôrLÉ´Dd7D‰éõ=¡«|IÈ0Ë‹*ƒèŒI]a½Þ4Lzc¨�U¯“ÔûÂ7`ô…¤*FJz+Oéx‚ò›kmÛöÍh�-í'zX=kŽyO^¶;üÌ­(½#fš´å»@óTß=½µŒ º´yw¥ëøÈn± ¿Ð•ïÆTÔ¢b)êF/!ïΟÝãbö‹—À;L«Ç¬ªwâ@“¯kza`]^Þ¼¦k¯‡›Â¤ôÀ”£0âuOdäõòİŠ+ð äºDÕ!¥XÆ7a€=|kc·upËÍÔh™èž®Î¿ðYÅóZ’ò"^$¤Æ†òtI qy^…6l†ÌË :S⟞«ß½Œq½ÞÅ‚Ž0Q²C­Ldèå¶p×p^1lª¡¿÷`¥pPžX ɉ¼Ë@»|¾ª¨]Ïï÷ Ù+®gl±�ùØ÷¹¦ˆàCÜFà•Ì~<®¦‰E¶m 0u»ð(hƒí@í!>cxøÓ{%Žjç^êîUȵ4䢉h¯×LË¢;\º'p>­"ïïIÁ¾w}â›|›ÆÆSP^k+U{O0Øxtuz C6Ýå:ÇCM)‚L¢)!�(®Àº¤Lï*å–÷¹õqðœ"YáA ÓrÉuDÓ0žŸ jH‚[²ì¾Ý•e~Íã»2§!Ž2®:1Çgñ€ç\)Ø57H=Ûz7¡2±PcqwÕò’�ý^«=u:VàãOŒý{³Ö…¦²ÏŸJººÃ;8«˜abqž6á܃¯uÏß<œvlêǯ¤v5ƒ]­¸¦@¨å$VU,Ð›Ö ‡!¨Û«`q…û-r=î}/ N,†rl,Y^ô˜˜BV¡Ô{&ëº>¦…½C?gÞ4_(I~]‡†zøú¬Ôö¦Ÿ<H“n}*쉘¾71ÖcBñ²z…$2e=-òK}ä<úÞ[6l}ž7Ñ,SC, ¥¥w¯ß¦øšÈ« §ð˜‹P_§àºúY<ûÆ‚öeÔÊ=î~ðç|RTîb›Œ%›º¯û’ŽÓö˜@ul<,n²=sxlÝu6ßHîËYý=µ=b$Át€Ø¹Qj›À@¨ÐŠ’¿I)dÒÛ‡{º{a>Xû…s|ö<ñÑŒ¨Ö'îôŠDÕ Ò<0Âî¾ye±Ù㥒lj½Rikáu¸d‹–wGn êmÍëIÉ)d(¸#¦èöQÄ-|“MêI«Ì1Ëa·ù°…ÒZm¤dr‡e+m$öÉà¥mf5ËISAÂ[c3Q¿ý…´V¬¯Ó&ÚÛj÷n™P2ö³Øèm1Ì Ù“´åH|v¿ÚË{:v^j K#%^ÔØNPEoù^åòúUëÔ¿]|+£Ya”;Ãò€Xžê:‰ 쾤Ͱ¬æc†‰;‹Uª*åÔM—Y”ÚÜM=‚—ä! KÊ4ˆ®8W°*Õ`Ùž(Áî#Íd¶DF®§r'+%¹ý{jŸ}; ÷¼Àß…â©ðmµ£_°;+ÒH«@ŽÄ·m@û…5~öA_q|ï2ÐbÔõ™+Qïh{N 2Xù¸ü¢$²¶Ó'ø¹O?å½^oP¯ ÀÀŸ-èÆ�Ö&Ü£ò¼XÃÄÃT7GИ7Ì~³P÷0® €qN ï%[Xˆ¾Ó §Ùh•æÏf`R@²P6П—À8¿pýé!i5è¹[ñă^¦t ŸòË Vr;”;ª£×=\ñî}¡Mð©l‘FØ\ØV:ÈOù((°Ž´–.áeDN½<|3ÑvÌ;)tc<€Ö GSküÆÆ tä<&»Ÿ‹qà{ç}ó,‚ˆ ó.€1¤K(* WW\m\RäE`³ÏqÇž7.n¤)C­bgV§94G4^Y" RîõÏÞèûŠ )^ŠèeÌjj xFšò2ßô¼`+­"îäÅ�üÄû³7Ò¸ÜÛÑÓsW©Ê}–à¹=Öb_m¿ƒYèt¾$À„.|)ecÙ°z§ –Lwã ±úx‰áÝšÜõÌhKÓR¾ž'§Ü¡4€ O@|XÅðÁKªwï™Èã7¦¾Î¢™@2QQ¦Þ±©$Æ¡®GJOì<ùé'TÃ¥fÐYºž½+Ö×$MÝ“°CW•e"ôê!°£T|!Ο]r²§¡àÙ<‚—íGŒ&¢äBüEœj”#þA–Eg=w;(W®Œ¡ô©kµ•º[ {Î{ ‡ûH«ß¶g%<Cåq¢dÝ—Y€õ ”Æ û’ÝoPðÑC±ŠÚ{Ämæ\–Ù> £ÒƒUé£Móû¾9AÀQûÄ¡ÕÕBG`wãVŽnŠê½·¦•êÆ{]/²¾0ŸýòÑF$Cî Y$=~gŒ 8üò½Ât4Ò l€f8F‚-g8&Y—’ÓiØK„Ï"õÑ[—²1ÇV1dô Î›%§òz»™¨žgHQp(‹«PVv¸WŸv5»Dp]èŽ<Å×$¥™B&›yׇ6sö3¥8´AÑcT®?KÛáò¥qYõx+ë!€ýÞkoH3ÍÎq‰O¥ËgçäŽzúŽ:×—ø¼¦™cÙ{½´…òj¦uîXóì^\ytsÍùBÒ&E§È,¢ÊFÎΔ  / >Ò›ZjÎWòFa9Ÿ1¿f ä aóT2šm¦<yü.øž¢éÖÁ{ýÌßSkx õ =Á½Åñg•uâ¡Þ·wE6U§{=iì9(tUHC>´­ÉWò…»Â§Ã઼2ëB‘“6 ÃÔ7+ïI“;GÛN‹†c¶0 žædBHí«”qÕ€ ÓG®,#Bz¼ñôlškÞT›GĪð{ˆnéx‘Ó#É-GòªD Püä©ñt#1n o]k öªmnÁ£‰ÛíW·°¨‘g^<û|mîùƒ_È÷êÐŒ¼‡×(åî·cŠ‹Hòkg“iv!ME´YüùÏnª¤§Þè©‘*(‘ÑOkGBEÃ&›gÍ¢ü¯žèG¸p„"‰Ú†Ò¸KÔË[ú¤¼Þ‘ò)¨Â&y8îÖh{s²¹”¶ïŠÆ{i=Hh¶8Ñ„JPÂZS#³$w†³­W ªô²´—)y6`pÅh®< šOAYdèg_%Cn¸4T «Û•LqÈq$ç@áÉ}6 ƒòØ_¾ñâ/ìM?±L½â~åÐÖê­€¨&«oK4ëäšAŒémµ>3'Å‹#[ËxÊœ5x)áiO÷¥˜užÐk¡m4÷gxAåÍvÄÒ‰1"1ïig¡võô”Å%iïšÕ½,,n©xM$šcR¼Ùz#Óš¯€ÓùÕÕÛÈ ÷Þ®£\ ë ‹ßÊ7Â7ÒÐ#œÍ iè]«£ dš*NZÏÝz*17ô }ÿì°žy`t½ž4¡ÕÅØ± FWÒi‡5NÛãÔ «_l"º˜£4l„9ÎrN•¼Ç½Ø¶"èÞ›G„™¡ŽÊ> ’‹ÅDÁ~O«WP—ØöÔkR%#’´ðYäÚ€EØÛ¦{þ&Š0Ù –2cA›0“:ú8¤CÎ.êý¿„ó\ Š£sh4<Ñ4Á 73®Ôj€YšŸKri§á´´ôþñÙk…/Ðo� °Fà÷l:pv'a6z‹¾¬€¦D›” ¶ÑP÷SqÁõæ…ÛïÔ'îóï{ L,2‡-Œ¢oìž³˜0¿ÇORÍq{d!¤ŒçäœÚs9ÀÍ‚ÕCÕpãY·ÐRQLÏSž€„Ž @òI"*IB|U ôž/ý|žèuB«gv(gwû:¹#bÅ›OëB@ï?²°à³í¦>‰(OÅ’îíXµÜÑxÏžDû$nk[[;¥=òŠ—jpêK pU;O‘UuÕ'_¢‡œ%7;Sq!¿ºŽ®Ì¡„[º÷²U·td6Óí¨¶ØSn9ªòÖ4¼zbšÉ%‡"S¢wfϼIÓ¢6­8¼¯ø„}‘v€‚»«Exëd«A¢# ‹›>ÁQ¡tm—®Ùèñ€r蛄Ï ËY° Ï8  §4Ýj:蕼.YXíG Më¶ðd›Þ0>98Ñ~¦!#šv…Mƒó(qG(ðèvCÎdwä%6­#‘^Ýé)ç¬ø Ä6 µô-ƒ`®æ“A©,iÒ÷&u¸9½QÞîóEô|·%L¥dKá+d®T€þìÅý ýÑöÉ<^b©Â·"…J±Åöª`èÀK—GŸ4 ~¿º–zºÊ¬+|=×>Ø&c8Ù1&ŠÌCŒ›ÙäN`ñ^oj¡™2J=Å8{<IËÐ�USXU,Y.´Ç¹­éÓ­‹Y™œ£” ©-³¦2K͆X¦±|³ï¥=@½;§ì§—~haÃEi¤¥¡Ë³)Âð8²w9Ÿ4¥`5Ó ˆ¨@ýl 6À˜©QVoH“¥<tL‘ñŽâÒtãežbEÏs�Îo"€>û2•NY︪lmÌ8P¡?ÒšLkŒœ!p¦ž»ÊÄÆ‡Õ=cp¬±Wø‚\\|¨pPdðÍÒM©CzùtJè\2!~ÝÑA®ÜX/Kõ^(a<Q9©»§8\O±æÁ9†/“�Ös…ÍÒÑÕ`ö{ Otc£òxœ,W]®pNÃÛàâhIÃFÖ™³¶ÏÔß¡•uÞöä{’(} —í}ðI¶h„)(êé¬Ô¥\æÚ爚[èË‹U9)dèyÕCüß•x »íHIȱÎfIEÜ!T“Ø@ZP¤é¤;㨠mè@Òšr¨kÏ#,™r¤ÉÞÖQ–›ñw¤Å«3+5ÈáÐí@AeÄ€\ÌäOüՙйaAXú‹{ù»Y.Ž"”˜‚òQ!AmÎ hmCr‚kÕŠë»’wÁS"úIÆûlÖÁüf:ÂjRÁSßéÛ÷ÄOîâ ´@Ìèz˳pnì s 4ɬ„ŽuÆêç&]Å€èHŠ…[Ùï|"Ù—¦´ÐáÑn_�ZêKX±÷lÛ®k5íœÄåìïаի{¤\‘Gë‘X8„QBv–€§)AcùÖۆ뇬¸ý{zHO{Á ÙÝIII8úð¨B]ÊX©ö…N[53¨Äyßâ7Ÿm{ݳÀÕ58SXz‹`õµe…µÍ°<?6Wæð°”ƒæ�FyÑ騺ÏÌw_- Ö{äãaìûHOîÖQI‘íÐrûN±Œ¦viš Ý¡oÉq.KvÙ ƒÐŸÀ¢Ó¬ì‘Ÿw a„TÙµ’ ‹f·Þ í,WÌÏfãˆb—#XEÉÎOBò06܇mIÌ&ß=~Êæñǃ Ë»î®Aè¡V¼šö*@§ï0+Ÿ ücÓyK·¡â‰S—_]ÒuEP «¿+{>Dú†+ºp´¼ùySÉ˸Þ4b†¦ÌŒ¤·=Ð5« ˆөʼ\X£¼¶ÀéTÄPÙ#šöò©6sÃãÇé Ä8"•“ƒ¢wŸƒŒöòÊÀ@¨ÝÀÓÐU¾×Ù�šÔ[&òhLFý%‡½GŶo›®GöNêly^ @n O]i>ØGaï“ýlå¹¥g ÅmyEÎôòÁu’Œ«`ÞÓ\vÞÓñ÷PÜ2±á5/×¹¯#c¯â“¾ò0žP\LE@—’Ç 1Jr™ã$Õ“QÒÚ”5I×-^R÷VG€¤| òØ1¡‘ª‰—fê!¸¥ëNa±#³rÒl„–Éâ3`·Ø}ÜiŽRÇýâ)3¼µÐÐ9œg”g|õbLM÷+<¼{*ݹ·jtf”ßMÝ>›ºÙ®Ã«8¦,b% /£‚Ä¢a œÞräðPq†ãW\L.ŠÂxe‘º‚®ú€nMÄÖ%R»0- ÔØyë…¡SÚJî°ïëÐAæ"s ´‡¶(,%‹%xÏÆwlß< ¹ Ÿv«hT"ÅWw<«¾l4kìbB Ö3™â!ØE Þ­?í cwƒªÂJß:ñH˜…g¢×FYk9HdݨYd³d;–|Òâßgd3é=̇<(úx ‡’ö }ýM #Ááá³Ú3¦:N…½jÍÆ¯\ª½çšÃ!LÇ:–8s¤šU(ú®YXnò‹*HN*ÃV%²i¡—ïDoÜCëEQF=&”œPkC*z+À4 BL ÔHö †v>­“1åš Ÿx1\p;šBWõó½œßC¶¸Ó2‘Ý,‚Þ‚i³re}·¨-Ñí`yfLßÄø'1LRP‘9”: ƒç àRãén$*—$å¬È9ËÀ6»Ãž€ É>ê†<謕‘"·…7VެDæÐÆÈ‰!ïÜ”îÒðž©Ï<´‚çTà >ÞnL  ¼gÅ,`3ÇYžµÌFzÖ(¥Ïö&àr¹µWxm±©½Öóe‡†÷“¡ÇÔÇ¥õ*^dúóñéQcY@3² ¢µlÈsgJ—ùmeñÙòá=„e§|&þêrxjÖÚÛ7)Q¥ç²Z/ÖÏŽ:æ*å)5õPݬ—¾+Â1hp>DF/ÑàrìlÙmŠ-Æ�óR5×IofoégUjÙú¦ð¡JžJ½'ïƒÎ¬Üsaã¶ jŠØPײ'\k_zâŒRZ¢f¤“-V|D“nÜ ¨ ó‹°U1y£´€ /e¶a èžE'åÖ+ôeƒ"8—Ä¢Ïyá{¿^Ž•3 ¤‡oB0 èu,ò”¥ô^l\¿À1TÔW•=m 0î¤(ó{n‚hóƒž 3s?]´AôY u‘ &ƒg4xƒ^±¶ŽT¹¶07k Ì€exÚ·o‰¤³¸ˆ)@Rt#Þï’VѼhž¼-“³Ö0.µq¢EÓ~ZãIqh€l|‘˜ºÜ†â÷‹´|Šå»–Õ·#˜{ø<!nP‹ÆÄãx– Œµ×#ðI~Æ€KÝz“ªªIDàø´0R˜š¶£2ÞAή]#7Gäó}˜Ý”â1A¦ÊÏCI¸Äº`P` 9™±Š–.Œ×&ö$øK6vGMð\®¯ìÌìRn³ŸkHSÞ3 # ñ6‹ÇWOD›•&ºÒë8·øU¦oz]E¿óU{Ô #Ô/6}ÃÞ1‡"­3l¬e4ü^H&pkI æ¾L€@ÊþҶ …=q`EÑÖ-j…¬/RâÅ'Aô=ïW½<¬w †½Üy´o˸×SOÆ)]Œù=`õÙ}[ØÕV"Ù(`Æ¥·Ï¦Xû‰8í¨-ñ½¶'.“%sXΊ úä‰>**Ü~Ê‹ϯ‰ŸYkQ&°H¼ía¶À<Í{]M‰¨š•>JÞbk`ëÖy=ïÕT ,PèŒè0Ï,BI)°™³‡qãÄã&Úa–ýù†^k´lÖìu,'>Åd‹í fªÖÒ�C èbA‰)L!Á´oŠ>£¡Ú!z·<Þ€ÀÔgS;!Š˜Bx £o]е<‹ÂŒDÂs)ÔÒŒ,-ü¬¹¯×aHpk[ÝP.²Î6³rŸZø9uIÎJß{ɯ¸õH ëk:O¯ié|Ñö¢v¼÷U>÷0PÊõG¯SgVN¤aeÈàRP§¼«§é画Çíh cí=ŸexœKt3D?çîZPwkÏe… ±-ðN1s~ýÄ.çú@—q¨]:Yå›o’ø3$Ä+»„jì÷6^Ž)Ú0Ö3‚®µN±ÖËwâÍ3EQ[öØn}§¡¾ôÍÌ9k>hCfÖ /–`Š-K»HÉ‹é{íIåvT¾Þ½“|X)½àr[áPYÑgq„â ¼g«¼Í>æF9ï Nž—]3*¸ä²'(ÜEùl³^`Nl5¤”6³w•ŸªÄð£¤Çêý³­xƳ ± ¦¡[ ‰ZEô†¦VКž]‹ÇC²°òIÓûŒ ›Ö¹ ½8éQãvk÷@™ çã˜,jÑèkfOŒ“È®3ͽØd{tÇ%oφuËzßvdq5bôÖ7ð¸93KC–#[­BO«Þñy$ÖLkâîØ;×µFPE!éFË·Ô»±ÚjýpÊ÷ÆÆ•ûÎÜ*úZ°NòtJ§ÎóÑ; y•à€‰¯ÇÇVu.ï÷â3ƒõ*òÜ®Ô\¬xs¤M‰4Çßä35?nº[IŽ›’?…ÝÕ'Qò})Û'`§:‘¤öL‡ÙתL}ÞÀëæÇ>‰t¤¼)×y5Kb1E§%~8<rW ·,¡Ë—wt¦8X°bà�"è-¼Â=¥ "¤8ÖQT5ÙÍ$]55IýnÜE§z‘)I-0|òœ,£¤1÷…©¶%…°û{okoÉIôŠy)<Ž®4Îx»�­üÓúRå•û¹ƒk“ îäêpÐs|ܧÄÒZPü¨Ÿ$ Æ+µý¤J?#„³¿”gzŠ|ûžå[h>.?‚@ÈöH3éP*£ÏnCÉ�&,W·8³ðTG<%LC2rÄ­ü9ξª¡D}bæ!€ÛÂ#*à9á1Ô ‹¼}þüâ¼ock<kCÌ1Mb,'Œ^M­˜šiY+S5GEÉb€Ø©¥D¼Æ©â’67LÄaDx¯å'YÉ]¼.‚~U)SŠoIý”OšÕ£jÃx$†¥êÝø&ë3Lt›ùËHiY’ÃJY•n`ÖÃ]ÎÊšÓq<ïwN‹PqÁ0!)\ıa…{µwžÔœ95îÀPT–ãŒ>q };YÖ[SµmrcA g“T.\Tà!î—pÞ¨Ûú _‹Lï2Kgàhø¾áà,_ßlp’óœ­ÝÅй‡Ò€¨öVø‘væ>ŸÅ®‹?‰ØÃy¿÷uÞWÈa|ç6š™ZôN÷6Õ+›¯äñ‘ªÛì«èZ¯ù¤Ë>c…)G=Å»#ƒ¢'’ƒy½æïå¦l€ÛÖKŽ­Ð*i®Ìƒuõv!~ð.ÈZ¬Y]¶Ü•G†X ñ¢ ?câf Mg7š‘uÑxÙ3É:’X’™¨Û©¯Ô]˜Úë- d:îmËmHåÛâ[­!<ÆÃ•õ]©~´Ã6ö W$üÕaCÜjâ%òWèåæŽ&%†@"áï÷¹jpé’%­ÅÕ¦ÖG¯‡]ÁÀ‘­ô|o|0 ›Ãý“0ÿ¥‚|­X }•âóÆÖáâ >ñ€€>‡Â9ZupŸV„•0â<âòçIYÛÐÇÚÏË–ÐNd½ª^KÉZµè°\šZ–õnœ':“Ü÷ÐU¥Åºv_U=»|g~oWEo›ØnßnU^èâÕÀîË5¬¢“w“9‡·ucÀÄŽ£¬eÌÓÅu¦Wø–8ïðÔwxªÏ¤£"Zôg&dšSB¯4¹yæž¶bdi£Þâý‚Ÿªó5!ïcÎã©”¬ïLßQCâ½:™Ù÷©Ìkx“FxÇ˯ë”hòøá-j…>ÆÓ~sx¦0üŽB·Â&|D!GÈõ¶ßô¢Ñ;‚’wcs‚óê-gT´äéÖ ê(í:UfÂÞëF/ƒãs 'Óë«÷¶åiSsôï¿»``¯GBOé\Û‰·PêžãjYtsº„«øz±±SÀó͹j¶xoëi@ŽÆË­ÍA+ƒœgÏÍ}¿Õ2#!Œô6eç8ÈäT?I#ø ¯/‘ÌHOõvæ!ÛñZ,qà–™ìx¬8G®ój8ÚºØv¸H­ÀšŸ*é{1Ð-3ÔG„gûšß‹|µá24²juGAÌb3›%Y]O1Ž“S¬¨/Ȉ¶ÈÔ´µÏAÔà]盇›Ú4Ï<Úä¬ÊÙgܹ8‡WlͤúHÉ9D´Ý]HákÙD†…Š`OY¢k!8 üiö®Ÿ­Ìù9*qaw>¾8ÁMcÙ÷ÇæN•ñ/!VÓö?†W¥+¨/-Té4ï†&X÷1eætïè¯Oœ^@ĪÊ膹¹÷‹½ p+4Ø>Îtš7˜ ’ {íAïXeÔ´¸+–j;ÐoBêñì:YG׉vRÑJäTºh¨<MGµkKsàPŠyñ|Pl­`œt°ÎבØ*˘‘n2ß¡½wá>¥7O^ Ütrð(GEž¡n´WåóŸóX½•4à�1;Ï%…î‚5|çž•éÏìð™ÂÓÖwŸÄágñGÝâ,ð„C‰ÆÎpm]9©Ü¥E*•¦^SòÑ ÒZ¨Â´H'EÂ4¤ÛÔ›VÚ}–§X+fŠ)¸"ûUæÚœ´®ࢡe‰.Rç<ÓÚ žC#Àkó|h|ö]Šgsßæíîó†ŒÝváË{-xò†ÆÉg¦»b @g€0)ú¤KŠ4PjË1ÂËË].ÊÒaÃ&0m�Éà"ÍÐ~Qçˆ~Ô(6‡$0õ¸ÑùÞ£ó(&ÚèÎÞRª~¡Ï²u´>©£ÏH¢ý  CŒWŒž«â†ßÖ2©^$v:ò°² c.y=W8âæäôll�~© Kc¸¨ÃÙýꢗPZ¥°áÚÖlxÈPlU'£w;Hüü¨.¨^v°ÏèR,ƒí,kHœr×4\«^™#oá‹NÊ@ ÄÚ}ÔÏÚh5öÜrÃë-" JàK§8##"U³~îiÞ0™¢XÇöóÝë2dw‹H ûCj KL©U¼€Ãð”QÂâ=I—˳Oòø3œ–M•õÒÝÖ#ËÀî[!ô› eKÏDçõ³ðš&ÔÌzǰw3Ï€hÀEøQ_i°eÙ•'W×>«ÅN"óÎõ”ÅÆÇ|6, &3„lO;§Sì!Ã�ÐkåYÐM}öŽˆŸj¿ €Ø£­xN<JÅøÀîU>=LÜí‡úpý™‘•ÄÚÓòTÃÚ Ö©u“¸üÙï$bv»[Ó^>Å´‡±ÁÑöP‘ïõºÛTzLÛ2ÙŸeÔ·m>ø´M–ˆ >ÅuÂÀ|FìZMwo¯æåŽÂˆ®¿Ìµ7†@á'K®ç‡¦‚=d“`…[Îäõ`‡º9ç@Á‰�ù6˜¯¶Ðœæõn{‰ã… =æ•^~ed†Ú÷r+mz’ ‡"3Ò%„/žÏÄ㬌eªÁQ˜IË•ixRä<  ‹]9ÎÝÈ”Œ2%"Ì ­ä3ˆO%~šg-Œ*h¾FŠÞSÔ{ì 0ÒÕ°q/†rÚÓU ƒX±ùÞ}ø}|©:!íI“•Ä=å ‹u•h; mðÚ|y¨8.ù”ÆaŸÀƒ ¼‡* öúq¶*²#¦wíHtû¾~‚¾=ÔæYØY§ZwΛÅé€ÏE€Á!æÏ’ɵƒ·×ƒb•]Z–«tÓÓ®t”™– Ö°ûm=¥¤TZª[ðƒîœàU¬’(sM#ÏRÕ[ÓAª‹+‚é|‘MÃ!:ÏØeé…o vâ% U7š&F  AOv¶ùÀ#\¨Ê¥dÍç¥óI¡|F—NÓáD’t4uR4�õçj"φ×O ‰.ò´a­W ÞS@×[ƒ'–±n±7o0Õ½ ’Ÿ±bû³J˜ÑL¡`Ý<_ñÄZ:ilƒ·øtX5·Ø…k'f£ö6D#Û37Ù2® 9ÓFÚž+Húì…¹ÆÖÎŽ¢¤L¿ÐA\Ĭ*$-½„4 ÛµYD W@`¥é=3iºÅ'9©5‰ÝŤuúÞ/¹F¯ŒLßYÎãÀ²z›^ÖÈŸïe‹^,µ BÀå«û1úbδ\¦Õ!Œ¾ †ÐÁ1¤²Ê³+�4Ôæ"ThjwjFØCN1-l†=?ó=º§`‘9Ág¯+ÖÆjÏ:$`=‹ÔÚ£Q¦ˆÙû‰3wx÷Ëg˜æ@F¼÷ÚÞKîsHhõ™·#žÔ¡ï9è=Bx½+¬ä+5g¥\P̾Á¸ŒåÖô Ÿ¶<PQëÝ“P˜‹¢®§1¯Íí^WrË{‰Ùr¿hTõ¨"©Ü…§óÂvãZVÕ÷&]‚‘kûÞÓÇ2tº±Ÿ4}Ú©”w40mjõó]»¡_¥�çÛô3œMDSô8ÇðîÔוÒ1¬œ#ÄäÅ=N!‹kÒ§5¯¢tpgëè;†eÕë:-œŽJ<1p‹ìI-t Ìà¶ôa¿RŽÆÉ­çýš¥û¤büœ™›iÖÜë¡ )–‹ô«­n$Ivhy#€-Ã5`«%„@ˆ î+<¦â\€ŠK)>`æšY#ùs'%Ÿi3qÏŒÃ}ñˆÞ©·UOf='˜FM•ÖS@ËO">‰Ä¾iJë.;f,Ú½;¶}ž—ÑæÞ|ܰ€ÆÊ‹]ÁJ\¤oƒ€ãå>¯zÍ)U¡wÕ~°ÂǰD!š“Õd*'veŠ‹Ï¶ë\Ô„yJW =ñ<#d¼sÐïԄŇ —Öq¹Úš«rèœ.«+%Âu"GRKëáN5l‡On»¶xÞ³ä~û´ …^·HÏ(f¥W•‡Eh¿¨"c /+ìØ_TνçÁºk4q«ÝWlƒÎ™7Óà ¨d˜—ŽÛàœ‰ïÌ7•Ÿçíª|„dÓ¢{ïüXfÔ»ˆäʸ¤Ú·%=¼*)Eyí]Þq©1¾£‡Û/î¥âr r®“V;¾Ë,/Ø›¹Áªlì ~ "<’"ÝUå(<û ÞQtRÍîÁÃxê 2#(bÝíСPÕýÆlûްUkî¹>‰yd®áÜ9Rª›© žyUdX"éµ\ÈÜGAù_0 ÈkÌÀèþi°Tõz›(ßmóUU.; ?^ÖÖ.Õ& }ù˜¶_/Z½O2C?ûdº¨áœMÎE¤Þí†%gEªá‰R`¼p‡öÜ\-µßÓR�·ËŽ„£ëö墷aûˆŸTpÉÙ°:Åðy÷¼*Ö‡X.×Ää[Ђ]Œ‚gà 9LO{A‰Ó§½¸_\ˆŸkÀù²+¬á>‹”Þ„âóÚ·ì<a¥Ç²¹Ý%tìŠV­-M­K›ƒW£±ñp^Ò$µaõÕ…ïK³,ÊÃã›db>x:ì‡Ó?Ç|JG›Ø,’£õ†bh²Tðqê1°ÓÁ„Ì‘nk,m†/:¾ÏIþ,W-쪡´XGWÜÒ‘˜{§@éX m:Å;©Ty‰Âªå‹EîãïÍé“…Išrõ“¶‚ǰž"ñg>. ­<ñð=°'àÞ*]¶ñèx)›} Éd§ý¦ª-)lÂ4“cæ©°ÑãkBŸKÍz3ŽVš6'–á±CÏõa)×£®×u3&Ù¡;×d/[”ž½Vàg 潯IÖªhõvôèèkÙ mŽ¢OHB਀Pó±i ÓxÕäYÛ'¡ø€NGšJ;8ä]+™5@¿ÎHÞA*24>(ê(Ø—žª²j«1PHW¶¯·Hxœ{Ëèeƒ@ÄÛGG£GHñ<ÖŸnÞ¤Ï{Â{O8ygýx›¥3™(ÚeõÛä$gÎ4~  ªd þ¾ì‘‹ñºE3ó‰µF°ó @áÕ\9Ëà [¥ƒ¼(0Ï›à(äèb'%oÇpß gKƒÅ/JZnJÊ`>$9au’`obñݦšiì~ðh–ó€µSä“RúŒB}.J…µãáA£6“y<»ENOŸè†“Nõ”ôñyd'àªOÊHxèr*ª°xa1¼Ñ,@÷j^Œ,,U9Fö©¥("‚Ǫ©!Ó͸ÔÎt¾:ÝA!’õZ‰ßánÒ;Áç|´±O<êB0.[°Þ€â: ’¬‚œCp•FX5*Jèí˲¾\¿Š 8 ‡çÐ M7¨&¢ÆÜYÞä1*=è[È ÞúùNýUY0=fBoE=€ŽÞË#'úlP{³Ý£=˜Œ¾IýÞûd/cVAÒ2©Å{Cg²(á2e,¯õôiø:ʘq¢˜ûåcRsìÌÅz {æûìi´-C"<¨‘m²§EáÊ[v¼5©øúQ`:Hi¾vÂG ¢/AĪ jx‡Ø0Hè챌¾!„]ʼ—Ú�¾|¸ê-p##¬¤s– Ëù¨lUô.hÖ¸€µÏ Ãúø‰XC#5—¿ DǼ§Vm’1?Ç/ÊcÓJ}j}áÔ¦Öþ|¨&}@=…꽄ïg<@§õI+Æ#ˆÜÁ8äÐ蕵­ sN‚È5­el“çïm¢öGm•0 Uõ‘ŠÈ¥*=tA·)?èbÑW^Ø uê2ÏŽÉu' Ê™ÅO"†à½ªq¾,ósy·ŠÎÄвç+ÀæQ÷[Šáš¶5~ãÊM5aõšC(²Ÿ©QãÛ»¹VA~dK“¦ZBσ¹–‘¶df_ŸÃ»"ñl¹rñG³l½g¢€vwò“XY"¯®IE}4�ç­>°2J6v¬½ëºº89Ý„àÍObßû4a&Ö2ž-S¥:>žLñC¶bñJE…={"æ’Q{SÀ’ ºï‚¢&Ô£÷ —kR²ï=‡ê-ˆA(Ïq˜(ùæÄ—§m&ˆã¸œéþ^¸6צÞÓ¸X Œ×A®Þ#'¨OIÔÂïàÑ y_ÍíÄeØð£ `]8÷ºu 3¥ò¬{¶•ý‘K>yƒ(Ù6Ä’†F€ppšEžäóõ÷d*ÅW»¨}óµ Ä QÕwûЇ¯‡¨5ëB²®Ø/^¯ˆRy]íf\<ü¤V>#SqÜ–“óæ´ò:ú+Á9É囇™íÊUP‹=à™âjã­D¸Æô˜ôé©ÈŸ!ƒ¤¿õi˜)}Ûü¢3â= À’ã+žÞ+ð¼Ö!g5U7.|Â% ­ø @Z8U]K|…“1R¬B‰w6_äñ,#z:ÆäSMxôê-BÁižâ ÀV×S ™Gª 5v*Xùl íТ“\ž�Ø­?Œy~s5ö^ÿ^>t5‰ÓܶˆmÊÑX{}Ýjöbø9e¤ùÊyÞùwŸÕÏð”á<òN€x½-"îíT­Óø»G„3˜ffúY¢”‰¾´cˈs݈gúȇâÏ"ÃÒ¨. ùQ#%\?s»1@KE{ðbóq‰Y Æž=£šª‰‡ÓåtmœÙOÒ3^ÇQ ?³S¼á²ÐJ,'}IøZoÓ^‘¶A͹s>¥r.Í›y�AÏË“ØNAn%Áom¼ž0á#ܪT«1H(€™ºx•Yv,12¸›räÓ÷3Fu­3úZÑ­Q] Cwoo>@/·{Îe|½²þzGe!ø›Þϵo°ÑÃÒU{EŸ²”="ºÐÐ:j;}0c>¶”ª‹¥Øú¨ xÓ„5s%Ì7ê^Z=áe¼°zšr°'˜`˜Tès¨…B‚‘Ëfzq¸“õš’Íš)hC8K +²¿7²ÅÁ�@Î#9ü�“Ñ éŸ½rE:ª¸ÒôŠâ”76³äýxtÜåµÏŸK°4F8âÔµÛÆmÀ–»:v›P¾ó+OêwQ˹ {»’QgåÏ?½I¡�nð|uuž-£È;¹nÇÞ€J?g¦×ÖÒb_ø&ØôÓœZˆ—§sFÇdÎm QÖ™3Ê +dãDžך x!žCéâ£Ö4Fw€g¾"¸&«¤¸æÂªc@¯Æz¢‰&jmÄ®T4Žžc[•IôÖ+ÖNª¦9N&¿ÜšŠ ‹—>F(²#‚‰çÖu õøÚô@¡'6½‡gÏÍ÷ù[Q9ÅóÚ^-íîxïÁ ËÌÞ ½ÚåºN¯÷m³£B¬õ˜E/”Ó_¿·d+ìTc[’Ó‡gÁJoøií\k Þ›ÎWbô`£#>)öÏh5…x QYiÊ/H g„£½+'é…ÚXμ 7=³¦qh¸7½WcH(ÏÙXœ ¤;é…ÔP>6Ô[};¤}%ªÅ¬¯æÅ.ZÍ„#Ì࿇©š~WlÝ WpKépõäaygŒÄô>1cÏ?}˜çÍ7:‰JӨ׀™-dùH¤ÞcC­À½w0eÈyÀê·vpŠ;àôZ¤_ ©ÈóÛÍiÙSÞ[ ~ÍQ~C1ïwvðÀ×<vP·ˆÃ ‡ØêÑý&RâøNPòãÃ4ù&9¾CÖÖ¼Ãôwí…²ï ¥¼ ÑX†WvLŠš9 lÁ† ¹oÉgc<³€£š—nGEb)ô ï›Êxlø¦ªhpÞ1ÐnÀ8îõ¸çxìÓiçØŒ9EßtŽ—Zw ¾f¤• Q=¯VhRI|iïmh&!½÷(îÅžt=×±;–ÎÆÊ.ÛCŒ÷ª»(‹ŸÌ£Á-ö’ÖŠgü<ŸøÎò´Öè¶<+,è\)«eMCz‹ Ðhp÷3K›Íð+›- Ê䂯¡{V8ÞÄ`ºÅ«xæAÅî›/š|Æ-ÉNÑNdóWÓL¬ï,–Ò¥‘È´^TÐäd¾#Ð ?B>5o„EÄ‹éרx^š]h©9“Ȭ¥•Ò˜­RÖ”ºÕž¯-ŒºQ‡¿1âŽ*.DÛòPFH‡ºTéÙ2ù´ßsq¹îÚצzÒ{¡<ÌojÃ@ 9è°¬_$�öm“àU¢¯µ.ö+DÕ@¯wzÏ3¼ô7صkê_aÏ!ËbÞêC)!8ìçoÔ¤~ßgyHÝÇÕ¬Ó™›f¼iÎhÀ·3Á[k9Eç<ù¾‰öÏ\-™ûôi2µK_gе0Àa8]VÑZ,9ï{æò ^ϵËc„•†SˆàÞ;yão´ž2ñCN5šDK ÈA¬ù«N —4"1 »ÖKF¼7¨®ÒŒ%Í#ˆ\âUP×—5“à:&l«:1 Pƒo CÁE/GЇýAÏõtÔjž`L‘R’ÝÍ"鿏Ðð7* ˆ #Éà0RœX‡®Yó(DޏÄ{ây …›)(ü¤zNU¯eÞæ`s!TœÏ«rÌÍwÁÃn<Ò+}•ýJã±,–õ'Õø½ÓÒ®Zµ—aNÀ›£ b‰)áϼ^½®=ɰ nßG'bdÈbrMéþ„qL‰ÎÏ-Ø-]"aÈÀ{üì!g±K^³˜šWˆyÃÖéÃ=0ML†Ã3a‹é¢t—š¡�Ùuh@õTʰAèCš¡ñÞ}ªOÚVž.,qæsÊZQÅF]=\r6\Zbm–¨|Ô$JšVv‡|ºùrt±oQy £ðL C»fåªCxbÅ´‡Pó:€‰x´<{BLKJQ~U°üÈÙ‘à<\ãU«åë.jìþ$›>ÃØa yŸ‡Û3°yã9Rágm†³Pbè>GÌEÓžRŒ;)SgâÔW+‡­|ì´£Þ+®³WÕ<6há‹ìQ0&k-ÁÃÝ=EІöê­åŒd/)Í“îË%0[7·P~†ê ¨´ÝéÍÞ˜î,P£\%Èï àæåÌHH,‰0Ûd‚V»²øeuíÍ•T»‡9?nðÌiíwÚ¬§r(º.Ø‘p¶/Y­$'xÜž#%ÎjZ÷ç„Ó/º£jÏÒ„Y^²{fZ'°L+ c9@`•Ùó3]¡ñ#8ø¤›?cYL§m`=<£pÇeà€¹2‡œ\›âz¦ÈÏÐW/Üaå‘bÌeZ H›–±@ëc¯Ã¾­9 H–ƒ×5‡ smnr/ß*õ”¯dÎX¯?‚|NÙèñ9ƒÜº¤½åXSÈçlÏi‡î±Í m#<Êë‹Ùžæu³¸{šƒBB ƒL/!Þ$ãl–>ÓÌGGÐþüq_c‹Ëû³ª¶3š¨”Kãzˆú°ÊÐú'á…àO,µ†kwÜâR­·½×TÝA–ÑÜÏõaº/ÀNë“ð÷ÐÐÂÝžc\åp^Ù°˜Y¨*¬¦c Mø“âH¾t&¦Ó3ñà7™Îw±)A:·•Ù/„b�t+ˆ[ržïÈ{ÛÏpÇ0pçž²2;;½ Ó(^u‡x­N„‚+»€+õÛ]%ï¼´ôè$ºtbÒbÃZ‡Ê/µu’O1bh°:Kž©S:öhŸÊ©"!Žyu—ÔÀѶŽ×…u­¿òÜ ˆ¬dÜ©�.ò«kæ2î‰PBIDbÿiéŠáìs)…OçÞjsMµå3«e-%ò­ @Ê{ݰõ ¾)÷OÊM÷X†¡,ŸG”7Œ,Kì“ôÈØÇµ"®xVîÞù ¬Å„*gwõPt<q* Jk)d T¿*yKÛƒìM%×á;­b O_ÄÔÚ•½yÖcÇâÄEHRÇ'iÑ™üˆÞͨÁ0Ëu!èÉ5ÇÓ{o8¯+—öa¶È_5‰c¦2­õH`z™H-Ïip“w=fçëñrƒÃc=á¸D¶µ×:Ì5'ùìõ³j+‚‚xþÀRu\dé~‘þŽ¡=  ëÁ Eca¿¤"~/!tdÞÍt´¨|’.ß¡mŽPèòÝc±v{(3fkÎA2<¦RyI%’šùxpmP¢ïŸ#°èí¾ÈXYƒó£ç*Êê•ìxIO¶´yLù‚Ú£ÂhUKx$èÄæ&Øyq)Jg¿Ý7 'Ö&ëɨuw§‚v×ã&^€T‚¡é*L–ù©#ìë=:ð•ƒmBc£ ƒneB1 ^ö³æ°|À•“(χ@šgCÌvº2 7—éÄ1ùmú“ ü¢ÝåIô‡DôŒZ?ã„JTÔVðeµo¥Goúp@?i×ÏøÆ‹Âã6ºUÒž1¥oÑÂ!˜ÛÒOË«ê •¼÷2‡@H‰j$‘ò¹2_qÀ[°í–‹4½žÇá¼{˜¯Hã)Ý`DÝö<a{&z"ˆºAœñs¯(/n˜FÇN®ÚÎRŒ@XCèVsq¡<œãÄn ³+¸Â &»‚BBï|Ññܲ„C•(‘såi‡eÍž–(;̤R:ûƒÀRÈ"£aåÞ4Gå;Séä,4öŠƒÚ¹¿ïÓC+”’XÅMO PœE—ŠÌé¹èy°%ô˧ôì“x£ïû´”‰u‰Píƒx°½�{\P ÖøÕõ0‰ (ˆ`Ä«×RYlWž5`>³X¿†…ó\;ÅÚ{c²™ZAx£e,ƒ†Â²±3¤ÖTîÐnfˆ�2ž–mIáåÕ=ÃEžp 9h±·ZÉ· ¢/uå0éÒS'áUN×[˜e¼éç�ØOÌ1!³­¬DG¯Sz½¨g•`Íl'.øOmo¦ÅįG.ǼÎç:ʃÀ*bÞ挅Œ ¥Of#–yäAÛ( kñé#¯÷I½F:šåƒbKe—0)4�±ƒÀhK¨Ayp¤)iR¼O«ôµ)Ëî0ê 2úÆø,r$e%¼Äç¬.r,û„¼Ìt q=‰Kžµ—& DÑÃáÚ`3TèηjÁ‚2MÔe×öp² ãdD÷ê™yR,eKŸJ=–B—ª`m'�š<ïj²´ŒyŠ¡Êðž¦$¾JÙ!%+#£*…)¸±}± âM •4y³ëOú,~‘?“ ×XTÑÀ3Ï)} ï†û ZäÂG#–×d“%Ú7ùŸá®Ÿ¾ªÉ!“˜žp.•ŒŠ;—Ä5l;&xUÔA8ÍxÕã-×O\=7ö\J;ʹ*)%ˆ�wÔÅu[¶É®ÈÅR“b 刦›ãVñd±ît½^v½ÖI{^kÇÎaïÎ.}9ÎÎÖ_27»ª›4`u!)w< ð…X{—UÊã­Ue<¾üœ"J¤šá‚îÔKsvnžÙ(‹Alj ø³c]z•P"bÈÐÛb[98PŒÉæèñvI—Þ/ú;Ö/´ÒdóØp:Y¦5};½‹œø¸V'¦=Sóí<ÔïlŸ1ÏËG½ÊÓĘnÉÈQR=±£%“±ÎNû ^S!@æÞšX”ª)RÔ0Mo°ë{ˆ'§Õz¶PbÙiÞMzQîâÙÑ…*wôVUÍ„q9NŒje·˜ô =tD”c2««ÈÝÖ<¤<ò·ÎõĤ.‰u¸×ô¤hy›õ$âÁ°-O±/òNQ”4܃wzçv×^kI$wDWí¥…cÌÐbþ`èU›h9 Ã䨃Ê{#yÚÏ\Ö‰³y¡ü÷ž ªÉñq3¥ªdɘ֊!5°ˆ^ÁZ56ã¾tÍ/|>-@7„÷ôX}íVC÷‰ÒD£?ö§Õ>áƒu61z]Ïëšëœ‹uÞëwüòLz0 fYÓ.è\íÄÓ`ÎØß¸Œ2h6åVŠ/PÛ­æÕ¨l§õ{a6ÃÓöîyéZbÝH÷›>zûFhƒjÞñçû‚¼`³½ì™Þr7ðºRæ›»÷ ¦nGgŸïC8}nÛ×LIFfÇ'@\d$9û YÄ=D^º³vô טډ±úÛMÌâÞÓ~þ3ó—EÉ9: _½¬,åµ.ÒôWÉõ±¨y-ør<ÐF¶ËnÇïSøýBø%=ÃWójÙÚ=yÁi'­³å5CŒÕ¨ÁtOH¦°H¼§ âIqÀ8º§&ƒ„¸ÁµNª‘í"›>3ìMmŠ3ÛÐ&ai#±6”zÆpçææéCŒÚXAOK»±^XBЃö‚¬{†²Ôù|/îÉ›&àUQ.#gA>ß+×}Ñ‚\eâÅB·„‡ RÅÜlH1Úíx˜{šÓO Ö,áVžô‰ „ˆ5¢ qw‰l’_HÃxÓEKÒ£bþ9ïŸ:`ø,Åã!؇¸qFµ×‘$0IT©ûÀOŒãSôÁ´Ý(¬\-래nwÛ9Q¡¼¼®£à Æ8,“šš¬˜ Ëî!õ;,§ç°ÄRHÛd’Ìh’TE>žÓϤ÷–ùÌÏ{ÉBÐØñ€V-¹ÞùKÃÃ"_hÊ C6>=5Rz×›>˜q.hp9 —P5$ÀÒ\SÑdžZ„× ¡œ»ê û³‹>õ=^º*yÕo–¨œ¢e7Õ·ßÃëÊÔÜww^°RM9òfïâ&ߌYi›¼ ‘Á«Ìù9 $Ì‹(¸nT3Ñh¾ iˆX†Æ`Änwr$ûö¡ï]ŸûÆ«�yYMè1§Q^É–YÏùš+¬Ì^gZtäÊyå”É µþ„uËz§kA|¬ü¥æž“—'aid³‚d(ËfœlB¦o™³TËSÄ ¢ÐÇ�Â{k/pYÍšzkÁ‰6D{Psµz¿$&¡æ‹EÁ|¨õB™ÄÊœØOët"œªP[ê‹´ê®îÖ£#© àn ­4mÓÌ8„Ä€ÂATàÊŒ»MTB5ã'^ÛFËÑqÔHÈæ·YoMóg.@T}-TâÞ¸m›:‡’T•ó"êƒ'ié²¼™[ù‚°~ú‡DÚ¾Ê\·äŽÌúÀã-‡Á”5£˜‡[‹XSêHÖªìO¿@ Z\Âêq‡œ­S®z„\v $ºó°DÎü„\¤}Õó•ª^/MR=ѱ´µFË’£+Ü (‹ÕpCÚP6”p¾Ó‡¹¯ÞÆ´1_6æ"^ây[<¼n§Í¢g9S¢KÊþžmŒB¬"”B/¸ªhæÖá$·'1ŽM¼¥ÈÛ§ÅwøÒhs‹ï½œ7ç⪳÷xž9&‹yu„¶[þ¾ñàbèÓ·m7ÍöËÕ{Ê}[vjS2 (é•a@©Ç§ÞgDì¢$~÷di{Ä•=$Ÿà°G²FfEôíÁHÇ]'®®ò™rI㻊zæŒÜ¾Þ°·ÅÙ!�}rle«¶ÙH7À¾$Ϻ}á:¦$ð˜÷XëË šIâíp2F(…p‘—/ÍHiJJžJ,Þátê–ñ+7âÇåZlóú&ýìNÕó=¦ÐÐA–° –æa}ˆMcz@‡ãŒOçâ…4¤¶ØX]ìš­Ã…¹å.Y-Þ"iOÇžçK›®jVÛ·oÿT\6Iò�‰ýVµ¡B:ºñä!”ôMc¡P.w43yØ[›Wµõ�¾ïû"ŸaqPks( çMë¹—÷y-¸®:ç åÑ k®)ç&¶Œ'Øþ`o}Š…ï±È8œ1…„=ž%è™}Æp¥íCÓEõd‚æ]M‰ZCòºÖ`zZHéÕQ\k«ÄÞ)¸³bÈRÏz zÝ•±³I%øv¡ù¹c6°.½EÁZÝÒžHK Èë¾#~c]ˆ±uâ=Ðâq5Ùïâ`ÉÏdyá­ÏV¯‚å >j—V/© ËÍoDÄœ};ñj2Þ¼ú9;L=Rö ĈQx¯DÌ{+»çiq,ÏÔ¤ÌÔW@„¯Ká}ÊA¿w‡§rZ-‘.¨K•k·bá0ËH¶’E&'ÆÃüÎø\t›EP|ft5Š^-”!r¦)TêF/öó‹EW@ê Mœç/ÆdNªœQØíÆ|cQxMÏ+m[Ûý…#œÄÕ«ŠxŒNÅvHBêª÷H, -цvíC׈|­›€À^áþ¦¶#ª@r:Þ†H¢0F#¢Ü¬!‘Þƒ±~ô`‡­Œ÷!ÝÂå3`$khµ0Ú!æ•Ùb€$RgtÉÉ•®¿Ñ5îQÂ�èé¢-ML8¶ÏE;QUñðfñôžÏ"Ú· üSÏWhaž #Bó²G§–¥1ZaZV“Á\ÆÓ~¤™]Us¸(þŽ–¼ÂŸmâC¡e+8*öz5Rm-î äˆÀÉ›U¹³²†¸Â±š^ÔGa},Ø`^ïÒÏŽ¥O±¶Î_=OÀy¸®-†²ù •ÏØ„-Ò¶pÌL‰®žz–ùËÌÊ·Â/unpN/Q‘®‘ìк]¸±u—•¦Îå>ÔgöŒ žÖ¡#¢Û `]ÆYQ]dO'× XÏáë›´¡.¹Š}Y?%qЯ‘ísN«Øyò¥ )w \%vÞ µ„ì0Pfa–I~–ö%oÆ2sr½¼¬±ä”å'¶¢³uæë¯,¡ Ö[G¸š&—±È�Z‘œùÝãp¬å"ä±Dô‘h[-}Áéz®š¨,ä}9hO!Íê QJ£;7f·ë**©Úö÷‘/Óƒ@8©pŒP%]¤²Ç/Ï_ÊL”¡Þ³Goˆ*­<¢LnÐz¤x"fŠá1”Wã^šjžƒäyêj„`‡×Æ-öàIPX19npõ–)Ö¬asŠøÊ¶¿gÔ3éoûˆ¸"EZÉá§(ÅUvknà=ÁÕ>(DªÂç[ÑÖ‹Ù®oŠ­ÂÈŒ~ŠÂ?C¥A>¨«½ 2KÌ£Ó²@3 ë·5IÕû¶A"²»T”JæEŠŒYÕ-ã©ZôÍÄäYÁcö™è7ø0§4‘Ô ¡•Ü3¦ITÛå Rš¯£+ƒ¸¬dCs)gRŸK̽rÝØ…_\-t¯žo‘â¥"=ÙeÅUXÜ;ñÁaSŽc®m‡­z{³$ŽöXÁT‰¯UÊ­à`9°ê µÈW{|Ü\*Fû�X1ŒßÃÊœÎWy“gy˜khÄ>?g gͪ3Û3_Tšõ+ÕW¡# e·^ò­U˜“ŠÆ}¯£ƒ>eñXtß‹{u®ïYá»7j]Z'¹,¦„#åølE©TZU\:öÖs¡HÀä7D:5$PØQØaD=–¡XX¬'[|ø¨`Ý—�`”jâdóžûœk¾g°Id�ŠNûžC�„«÷krèÇc£/…Ô/ ì…¸§fµ³¹Ó¹Óß_ù KP°G"µ9º-m‚íyùî‘M»�Ps.Ëa Ô®&öóJ[49fT5(²p~F™šŠ»©ÎɱËÄà ›ïeœ½‡˜+½À äY/Úâ~¡þ -u=Ê`©Ð55¦0_ó2·%›Ö“Ʋ¨á§3Ì{¯÷K ßA³ÙÂW°Zý91ÛpV™LÇݺ‚áËÈ1ÁEp…™¥—åÆdDTúúÌÞCIƒ3z=G³|ûl&ÁJ±c’E𞤈?W ç—5«¦‹=&§,’É››µ\‚ÓŽ<qE›ù'ÎùuN´µ†äú+¦`—j¨=©8ܹ÷x^=„nâ´H-¥}ÇOSÖg\°ÉÅ"d¦NŠÆÐrËŸ1Ââi>Íæ!M»¨÷Â%OE‡Ê:èzÆú=›®·§åÜ™}‘{¥ˆ^×w¶ïÕžÛÖL{ «s”ÙOÏÐÚê‡1 /Ö½;nõÚc“è…hèy#J­tþÂæ[þ™/R´Îúsˆ› G#ô»"A1±ôÛnÆ c[nàRðUc\—±dçàV›ÔraxN¯®e™ëˆŠ“¸¹N³‡Ê²\0¼ÝŠªçÉYfôÎ.¦%Åf̵Ӗ·§iIù:Ž·Ë±—EdÞAÎSyàÀc�#¬¹HøI† w¤bVàhÆ¡¾G“ÔaÜ5ê²kú¸n̘,é,7ºÈY ÜPçê)­4ŽÊcêŒÍ€uÄ÷¸·ËfÑ¢£ëyå;½mVhÕ#¡ÓÕ·Ó¡õs¹�…<Þ·óŒQ³Op¥‚¸§Ÿ“ռ܋@qŸóŠÝ|ð)ü Ÿ¥Èï¢yg�ìÁ�ÄŒƒÒGÁ,”§öª }ø=}T™Ò#œçoÄ·¥G¶áº¢«ø†ï.Ðh08ΜH虽ޛ ûˆ•Ȥˆ°_3{ÆŒFÍ…øÖ’/c¾»¥’CO7gì+ƒO·ŽKÂ)£JÒ`‹¢ibÅ“!Ü$¦x;LO ²7Ë Õ£—fħI,ÆöP,ùõ8 ±`“$19iï-ÖðÜ5J2®5H8aŒÀc¥xƒèåôªÍ3…•=(é…Ìyãîϳ—ò>0¸ˆ;b…Ê\ÈI–ÓÆ Èjerª?› ¨\#yŸò ÷}û|ØSÑäYx´Ò¾^%äJšéA µÍiK¤NŒ<^xÉ|mÂŽ,ÏÅM<WÛ·õ²™ž´î“7¨—t‚ýPõ²çÈÈÅFÍ „Ûé{æ¹å½è‘æìuñMJ…ÉÒTI~_¨sgÓe T(ëÙéGG±„ærZFôv¡ø÷ô¢` ›BˆD„¿žT�pŠ Ô,õP ÞÓ$Œ(n¢³i€D)'ñG°Œ¯‰¨�ªßÊC^qê>g†“ÖÁÚWmqà‰ ù~¯ìO®0²„°OÒŸ�¡²JeHÓ=‘ä©Ñx‡Œ"³Xö)þ ¤ïEìÝe¿êM!{¶7¸ïÊxŸ›xm ´{âÝ E€8[>-:‚Œ.n]}Ë-ú’¬á°5Cu[êÓ¯5KºìÀ!¾X/Þ×¶Z  ¬ŽÑñ”×õ¥ø(¹ž¹,S:¼÷8Eó ÞœfµØŽ4ºÌìúó؇ÙÝUÍdnZ,Vì¤N¥NÏ /› •Q…/^Þ0VVõ]I¼t÷VÂ�‹ °›zì;B1:¡„t#’µ1µ7üˆž Øc ÆžÍy¡[º/X<»ÍõÙÀã_)Y…Œõ‡ožA®{5‹¶C•ÞY;£©mŠhÓW¨ŸyŸÑt·«üæòM*¡Á ¨‘†ã9ŸÞ)î3Gá. £ö¨ãõÝ™§1ðÂÁ’ÝÒv¯Úå:2BhãÒ_yÞÖp¯9Í›”p�r²Â­pwÚăô³ÌèäÔê§t¥Ú>/Ñ' àb³èÒ±‘”N¡ú;b€ ¯HÄX²;ƒ—w¥è‹dàk¶ºrü#%"ã Ž2k“Qú58<lC~X»š%]/ RgJÓ(â¨ðUCË+/lìçV/^M÷ §°°dÑ£ÔQ?Pº¡ñ Фù™Cµ&7 ùªƒ,X1ö…AV3søQIŠ¥vÕƒT" ZÒ¹o‘ø§HôïË^iè£rÛT-CÉÀ3OøërÁœa@x­%Îæ V:1jç1Þ ± º÷,Gw¼Ì÷BÌÓ–Ò—O2F}µ|PÝãªaë 8Þ)snäRM–q¹7éh ÉîSØÅ=ñ+ÈË ná8oÓá°µÔTÞª(q·ã>0ò–ª‘Š)&D6Ìá[$œ·Q÷QÜ[Ü>I¸8ØÊ7Ò[FnžEÔ|°%©$Lœ­zŠ÷Òñ²ß3\h >&·0WDry÷é•Ú#:Ç—êýjy½ãçÙ^Ûµ'l³‡¬‡F¯µmgÊ»¥ÝŽ,F#EÐ#ʤ0yø)ùŒ«C]4Æ ÌÈ!ŒäàìÜý:ÃÞºm«?€ÚÐâK Ùâ9ì3+Æ�>ŽÞ/lb–Èßš¢–玳ÑÕíȱ¼G— 1—þ¢FTØØãó£ÂÜcaÛª'Ó‹<Wý‘ïb@¾½)îܲã`F´:å¬i[±Úzhض˜C Y nÚo­”QK «£{aî8;'ŸU•k­™­¢U­˜ß=Áð÷¦Xa!C[ Ö´*dHÎáµç;2´Í~k³qÔw\Õ"‰¶fÚ0@. L©=9äì¿„ry²\–ú”ânwÁRmÇ,9ß©z;ÞFaœî*àÉUD~û‰~×£EžyøºqNz2BªìϦ `ÙR 'Ý a¾l:ÕyA>–Ãf÷D^×½â!¼?S·½W@ÞÓ…&>\ªLî¸KwV“5õ@¦¸úá¸b±¿ÒÙ¯‚Ð|D7òhMkQ ¯„rUÆ5éÔé¥÷eve¿´”y·Pž¼<?F*.J13å½6XOïl'q ëäÊWcº†>Ùçy˜SbÈí¼;ˆø­%ÂÃÒe½‚}PšèÅ™§âë´ƒm®Œ7Äõš·Èš/·]]~I%=ÃW‹@®‹1nW¼å‰ ¼Ò‰vãÓëVPõsgþ–ŠÑw„5 [òˆ2J­©{sœÝ©=…ðpë™Õ ó˸ȮæIñÆ(Ž.lŽSjáe§¢ud꡾WáöX\ë;¡LàrmO}  –þЂ4 ûV±âìí£á#9wÂÙ#ܳk.G—'"9äÏBWœÛtõÖ^G6‰[æÓÌ?¼ÞÑm‰³v¿â¬¬,)æ¼h#qLôhKb¡Çr²uŒ¦¦ L‰áY‡‡Ç¹¾ÍJ#¤ZÔm°pÌ̈x1sÛÀÌiVýÃ=²ÎÚ:)ðgNñ8*~Šd›K!ÓïzcbææÂsÅÆÀ÷wÁΉýS,þfã¨Ñs6ŠÚü-\™òF&œ>µ-¬Þ ž“É~u’´�eŽ!çàsô®M—´Ëj§Yü½žµª¤pñ¾ë°+ @`ÆM¾b”èÆ ã!‘ÉðÇË/!(vÖTì°=¬Ë*n‚a²Ç÷€´$òu7»$1à97$ `vùÁ<DÄE8º·ø‚-ÈD"Rh<Šåf„øô••ŽçÖˆr'^ªpKáÜèI¬z]ÞÔvd#3ïTdDÈ‹ÆöóVSÒ~ÎD8rgDñàEÍ®ñýlCké˜]{,cE¯ T^ÔìqRòî»È¾‡Gí9CnÕ=ð[.Ÿ±6%Ž/™€rµº×»jƆ|e'FQøIH¿Ž{Ü(£Šñ¸°ëæåãÞ×ôz¤Ã_t+IlgÀRZ,à]eƒUÂâ³ËGjš8ª. Ên%Õ#뫚¹ƒå‰-ùLž"á¥Îæt‰°òsÓ{ŽÚxªã¬ãRÒCio䔄ØaÀÜ^Ž·Øhܱ–?”Ò²±µ˜y'Р‚xq¢í¡ÅÒVÊ•,­wA•gƒ*¾f×!ã©ùx·^ó»Ù™½ZFÄ7#Œ ˆ+œü¦éyÒÁê/ÁŒ#½ÀÇ©±‰Ó¨^"w :O®À@XxL[»÷Ý­~Ëñp¹|ÃZîšFóÁ¥ÍÚõ^Rǃµ¬‡Â„K±«AsÙQ�ÑÓ3eà×+‰æ-ͲK劆wúõƒzÃȪx/²f‚{ÓbMÐä…ÞjöQP¿¦Ä3­œacÍ“çROsü-*=mµQg5±šeÖ¦€‘y€«ìšÅdayZE‚Eã·&¯Ÿ=§2Z(Ž·Y¦Š¤7ê›6*[Á#qR¯%ûÁYs±­k¼£xôš^ž·ìIôÄÔá/,ÂYDê™wΓŠ)›Ý—YN†/œ+:æ½±},¡óŽæ—ôªyŽ„‘L¹ÎwßèBæä­¬ç&^a-¢;辸oɼOÉ<~ÛŒ…ð礷Û0£5ñÖá¬2¦cLζ�MòTGóUŸ j%8F¢¥²ÑE±T·u:Šìb¬?òj¢!|.º#—Áöš¢fQCº C-N%QT¯Qïus)c¢_½÷âRó5yŠª!íp´ZúS'ñhCÄ1®»ÞÇX¯¼ 5å ²…Ìdߢi|IHcÄñoUôîÍàÁÞ·ÖJX”) /�°ÈÍÓÃ’<Á!¤™d’tè Ó¤nô5 0D•H¾wÄUÙ0"¨‰­nÃõp®ê¢[tžñÏAúG¡ãœl§¾ÉBËÌÝÎJ”#€›I˜}Áb£z™õ^}Š?C¯µ…ð8¶ß`‡©ã<¿3�üDgžIùƒ½çÏš™Ëž˜^ûP¢kè{.ÉåÊï6“%$31éž„¤–¢°(Ï.cUö{ܞ̻£#¢©ÎªMBV"°$0W¸Ù52¢¹ø* T½íµÇÝæã\¡CÆGÊÑîïF)Yš-èàèe!£WÙÞ3¶ËRj³Möê?HîáÙdékäÛZC¡:©²,Ió~:»ía—žQYy8©—zRÖ\¡˜¥Ðc¿ÅWøÂ»C ‰ü)´µŒôÖK«Yq_;ÂþÙž¶N¢Š˜D^¸°Ã»VóNX#tnמR†0¼N`Ÿ²!ø”Mj¾{7-‘8DÌŽ¹’÷ÂÇ^ mŸÄ²Ç¾@†¶Í]%]« Û» ´{ݳªïÁSêÙ¹a¡q^Í×>–àHg€ÝÆV‚æM"z`ˆH�[J6ÕÑ™4—âÇ,qÉÉ‚±QÀ¨:w‰|—,ëbvÖ®­õôyÊ—z&¦¯Ò¥f¦{!-}QäÏÆ7nõ) Q;b Ç9Ãc."ä™§ K‚‚o ™—J9§&„8ª¥ŸÞ”š»Iq;.çƒǾڦ—øàªab¹§(… _!§½NÈ–Ü_›Jl‹9bN$´¢Ñv<3;f¸œ•E4<ŽEsd~ô-œÏ <q™øzk£lVKLåA$s°‹ —¬/,.¤>ô9ãˆÔ4Ã+ÇæÎ¨á*_ Á‚j ’¤x[ƒà¬îz+k‡‹vó–óá�´Çúõ½dåÎÂìñå¥C*ç*wÝ!+S`¶pdœ,z„ÆŽ›™V‰²íUÒÈ%¨3ú`s[’l@n®Ž¥8…‘ð©ƒÖk “êÌä"@;~&S¢zQoíÞ.‚¾×”4©:»Â–X_Hs+9yÝ0m@Þ뉪�?~€TBõªEçy·§–De¾p߬AZLHlZ4Xû9CÍ“ÝTá ƒ¢€1l‘J0{øš«§ØBØV§ö:>¥ÃŸ‘˜ÆÙchÅ£ í[‡>Ü`"•Ä@Vi.ÅÌäÑéŽÓJÊJMïf¸F8Y-3 ³ËÚØžd–Há^?ĵ÷p°dÍ*3Ç ðF¦°ØlP¥@ªÎÃáÑr¨Bçy‘Å­Å`ú”kCD쨬ð�vW¿zŒÆÝAʼnO\O+Ü2ä¥ç>h™£Õ ~:)çÅr¨‰³œ¥³pÏl|\Ö½¢b£Só0—[:ÒÔ‰¼7ûÜ Ω´@Î×ïô–›´šÊ¸©œóÊàñ¥`xçÊ↴q¹ÜÉ?}‡m­O3’± œŠžÅc*sv³‡»9“Xä&[LÒæÝŸâyŸáXcÂÜí:³Ý–¨õ¸ù%OöÂC£Ç|–ž–BÚù’ÉpûZFÆj%Æe‚BX`®U"lÞã&l‡x É·7ŠÕ/w€)0—º'MƳ÷UÛx¬ ¯ ª@Mʨzy Ôµ¯‚/ú»7œ‘T9ýîäÀª=ãh¡(Iot¼E�À/3ËäÆ0òÑ«íHë‰q¾œ×¾Áˆ¢¢é†6\BœêwðH¼"vX‰ÁŸ¢Ã«äå´ ?ºË•¦«©”ä&kH:ÃCºE‹hÊ)Æ"�`yŽ»Ò/ç(+.Š8Lú~ˇ ÞéÃË£ ô%ÚÀGY§õ² KÝ9û%˜œ’n<s¶áû”|Æäö Ó¬§ìÁn½\>o¡™V4`ú …BV?ÇÝM8 ½p¶˜ë�‡<5.âˆÁÆÇµë‹LŽJ½Xi§élO-Š ³‡¶Þ*²SGD¸Á%ÌËÀw‘d =*îr®Í[bÂÐì†èUøèxu7ÜçŠ1ÛdŒÕƒqŸ r`’½":çÞ£‹ê¬†"Tu©ó8â0z…nžò ÑŦ[X>Jž{hÀ¦N‚7²€Ö.ƒO¢g²¨¼µNŽãf“ò=ïZ~S­¯š öê¡õ)lòÄ®qün^+¯x˜jrÅ×HT¯é•»>EB»#ãE?( Ò² –÷=œëw`Æ'—H¯ìQ$^1[Æ‹J#ÀêF'&£Y�)uâp m’³•n:ò¸º÷ÊiD—ݪ‰Y`á{üˆ_.(ÄR½ejŒ:÷'ð˜f�;S¶P§Ùü8°S–û­‹yÍÌ “)k˜ôªö×m|Gïq¼yòÂÜTö%@Iðu‚“')î¸Oõ"™‘÷xTSKØõŽ©\š$¾­}j—b½\óây©«½Œ9iØÖ†®£]Å^=Ðj?r}s'âl¦Å8çmw]Š<E묆 Ýë¥ qÕ1;ç=ÝI—ß+AMñwq/{üÚe²‡I)ð6± ÂHZ°ï‘à Õ³K"þ–Jèærºc(*‡8Ø[[¥'1÷LŒËÝh‡ÇäÎçl”lHu‰Þ:Rsœ…ó>¯H<ª=¾-ÑJ$Ø3¥@«hvµx.Ïr7\aÜŠ�AÝ<}ˆZ›×)¿³3 €×³‚:/{NïY)VÄí ›¶l©:lÇ2¸Ô ´¨;?äQhd±ávÄXñ€5@àT~Xm[Ó…Êê])4WW£”³ÓcKõ'Ï,ú¸Ç.. »}|  TX ÷!ø–(YÕ“1Œ.xê¹Ëˆ˜5팱 0jaÔÅ’Z¨€E2uÏúл ç虂9ÆAM˜®Z0 Ok ¤ B™'SXÏ;ë}ŠÈ>Ct¸+;aÜ0„<ÂsÒÝwË¢ZJÞÜ«ÁÐq´&~ƒéÐNÆG§¸o2W¥ß!ÂðZ'„J¶ ½å×0ý*iôê¤jƒ‹ÅåXÞ˜<î’G‰™òÔÞ° ˜ +¤ß›GÇSÈØ\–e Jj•¦®/Ú; žB+áàÉÄðMHmañviÃÀU« Ey“rgbe‰æË»Üy/”æ t|¤pËŸì1¢{ñ"æ9b"ŠÖ–%¹g®o >ÃRz™˜Öšs€KP<Fãžœ;Œ�íNŒûp¯Ù4@J¦=äÀá&Åþ•ð³å*?Îu~­„ ö²5€“–W™Þ±Jñcš»4¦{fÙHß³˜ÇéÌR2Ña°TÁ§Yî`¯%Q¢xÖÓ1 Ñ:ñN%ìE×áfÈ;šÑÔYPß°MÚ$âÄ[ˆœ1ƒRO]pì!ê„xuk=ä\÷8Å}2ð¢ÈRÅ_?{ù’ŽwáðDß3¶ )YxevÓù¢äÀ*]믬«Ø«wM$íêOH7å˜V`B5õ ².µJÔ’Ä„¯øÃ¹×t Ì0o¼g×ê0!é=¡·Û­~G¹'u�ë–ˆ­+³˜”¡ÝÏöÄ%<ÙŸÞ‹yêTêÜ/A©¡Ä»¼jdçŽÇ•Î5{‚²×‡0?ƒõô¶j´  iaM‘=jq›Iàâ¬K{B<|¹÷œ öSHñ¬Ÿ•j&\•ŒZ¨­S£5X&2Ù†^óò¬1³zïZD¼Äº'àÔoŒdÇç!tIõœ4?<³Ë.œ|šRQÔÕ/6ç̵zÜñØ0C.ÑæŒOA#7áÎb$Y…ïÚ!§4€²-¹<ä§ áHx›‘µÔƒÕUudm¯óXͤ®°ã…‡mžè]¾É«u}OÕ¥-™@ÛÒ€u_¶£ZÄiðä­Æ1pïÛJˆ!\`E ÀºV•2z�)Ïà2Êr|ü¿â—{ˆ.(koö+н/l"‘š™¶ÉA™£&'{’n¼Ì¶¶š3ƪâ¥,Øâ #$NKHpYÏðlÍóœf)62™¹ÏÍá3b{ßá©Ý 7„{è²²G»££vgñs¥*µTÑå ÷Ðã^½›7i&q=ªj £+Š-BìE ãð¢±wví Ëd 3>«ËP(êÞ—ïHšV½Á\•÷˜Ê§Yú¢Ç+ ç¢Ié<í2jNµ¯Þ{Ä!jÝÛ¯Ðß<y¾¹|§‰AÇ)¨’–)áHí»I cË…žÌC¹ò°lš|Ì»ñèuŒšj¾‡†ƒ*€Í~mAñ²»Õ{KTeX ýÉ®D\OgdöF³Ç |Ž»h\×dOßE‘Ïn¼ÖÜ,Ë\ÝåT²ý-&»€w»©`DÒY´ÜBöÜÍC_ÝNß‚º‘Í*Â)?BV«¾o1}†íͰ0컨Ž�>oï*™7…%ÏÓeà-° ¾g…·ævLTGˆXaÙ*g'f2F&¢,YgQ$…²AÞÚ=s)â|xãbš:iúÒwtœh^ˆ¥<¡÷L´Ñ33ç ^4ÁÄì¢!.uû £Æ•u¿^öb¥ó…`Í /[gŸÞ|g)¢ŠO«úh:HT–Õ´±eu‹g(á\3‰w†<ð0ì=Ó ‹W<—¤¡ˆ9agT¢@õn Ãoxëa=ÐG¢ËOÖÇ[°EdÚ“0àeæÀÞe™¹æŸ–¹0TÀ6޹“EÙÏ6G/ØlâPóÅ�íÅ›“c^´T‰ÊèQ…" Si¼÷)'üÞ]söÛÈG­{Oš™µWçšîlÖÝ_ñt Ýœ™hC ³4zçpkXÖ¤ ¦£;&´wçu8dQèkªE¹}ý*a®ˆž tÑ’»Ý< Oœ—=éañ^Ò]‹Ã]atHe>šj¯K2ªÅT*FgNÌÃå|&H2‘ê.¯zœ¬^@•ÍñLêQâãöºÐ¬àq‰´À¥Qr|éQI ¢ÞG/rÑâÖßÂ]�»£y—¦¢ ÛÞÈë ƒ|ùp0}x¦÷éNU¾,ë€QáðaÓ{ŒèÑëͼÈt›«é=h©ØÊ�H¿Uá¯i´ô¦ÉÅ^æˆà5j©ŸKv?‡Di$ÏEÅyj„Ÿ‚¢Ï�h4gLäÔ1Ï]5šÅ—_)tmàÕ¸|›Ú¯`)êÉÑ£ì…8ºVâ·X»žYÞ#º^Ïuqº2ä5]Ȥ6ä™ïÒŽSrZlC‡î*eNù;Ï·ëiÝܸëo(!6ˆàåm<[µóõŒ!DÒ†”ðdÇ}4¨^ëi‚-ôHbßÈ[a)³P‹šœÕ[pqE_%­—pyRÝ€(ðòł܈"Ùæòày å•<ßÎÉšD @ÄÛÆ×ù…'+¸>IÔEÜÆ˜½ö˜„Ò‰,aH=æµ ‚ªù\á/I¦T\ÓtËåNŠ ­åà ¢i¦£ÜšÓ‘×å͹ž¬‹Ê§¤ø3г›TЃ>^H/‰Vqyp¤i€}èþB—šÐž¹’ÞP< Ñ4y• ,äoÀå€`R†:OåU°³a` 1¢[T꽜vÔÛ®‚‹~OË\ê„ÀBýኻy·øðVAXï3Å›ÍZ”Y:Ƙ«<´G=[ì!mîȘjÁ‹Á.ªŠlÚŽ½!ê“™$õìnÌòq[šx³É ˆ;¸š‡²ç[ÁV=/.ð©×‹°×`ÓŽ‘5j2 âöîœg&ËCø½¬5D,š‹ÓqÉ GÐb¥'­…7EQ$DAöÕ«rzÅÜ/oKÖª`0. ~ŠÊ¦A ŸJ)làÖ’.ENI’k‚8í.­Gy`È£àSüÞ{ûûÞ{?ëÆ”¸½ÊxmRéªÍ0-]Ðp¾ÁŠþü…èŒ æƒSô—WË“g äƒÛ}uÑÚKõ‚’ï ¥è­$s˜Ø½±Ù•¹¡Çˆ– ªžÏ°BLuétæyó‰ùà <x #›Gó,’”`ZzÌ7³8¹�Ñ0ÊÖ|0fÎ`â[xž™ mµ]ൌÏS­XKK—:æ‹ny5noæF!Q`&ÏÇn+ó±½7JQòat�`Ä¥a•œ7n + o-‰hmvÛ¢% u\Œ.°t±»­w„õÚÕn^lo­Ö98­ç/Yé�ó¸Lî0«Žœì;àâ)3ßÝ{­Î}×£'8Ró-«Ïx.–†×Ûaeš¶cEõNké3£ØDuOÝÙ†k ÷RRŸtâ[o³§£"ˆJ N í庀Ç3;ÕŠ @».[s—‹Wîê]ìx ”OÆcàvf)îäÜ™ƒ’Wí£Ê„ì%CRYÀƒVüÄ3Æœ@OªlÖ¤¤¡ÒåÕ#¯rÀ5À˜~·™#Qmˆô„ Þ0o²²(Ç•µqSŽxŠVú-¿ZžNv'å›ÂyWL.à/)8¦ß÷èPŸ¯•m@RîX>,@r!j:¯;Ñ´[µÐxD½Î‘1OÁø—°�·ªŒÂne«Js=�åÀ{<µ1hD[L| nÊcw ¨ý),ÑÏ\õuv‰,€*ó˜ixÀƒXkF߉ñeb•` ÷-já" àäºÉ$4ŒrK4Ï€@¿Öt{€X€þóú)q°£3MRzå£Ýw®/û½EЋLj ¸öÚ¬‘ëd*„c5D­N±Oƒ©ªr˜Ïãi8¾ÕqAeLAà(~uó¨\¼ ¬ýäp LeÚ<‘¥¤óÍU‚VçÌ%š(q{é³Í¾zï½rÉ÷ÎØl@GÀòs°Š›»jœî½ÙðèYºƒi9Æ ÅÃ%Ù§D…nÞȼ/ýù‚ °m:¶^Ý/iùp¾è£¬ˆŽ: FV­´Žœ#yÃògîs[cïýÎWú>[a;J³¿Ý…#÷í%ëÞJ@F²‹06¯–ÁÕ–ÕÁ6#ήqÀì.¯¨DcÞ3æ{PUîN!JOšU§YœÆPC3,ßbˆØ>\y³ûœQ�Èç õKW|ƒas vÖO/Ÿ2(Ï Å”_,¿)…ÉdR`´It{ëRˆãJí(½+“òtçÕ=ú“ƒg£ ¾Û–'–ѕ֦Ö)ÁA¯³ì=?-~œ@ö {%Œõ ¢Ýu61ëuå“kË¥#ì²SÄí|JZ4àÓDì´A{E§yÓ~Ó<„F ïXúi9†ÍOߺ*IÈÂäzý.Es ;„q+¢E^�ƒ0 7Áí ŸXI÷Ô§¸ì3¼/ÅŠOÍÛÄò>Qñ]=‰ ¤k ¸w >ÑSï%ŽT¼r_ÇË~7'ýâ=:ä Äq×§¡"ˆ›wJÏý0ŸEÙb¢(,†ÏtwŸ�J@ð#¹³Ã.¤§anúÀm´²I H ör½·åˆJ°%²³]OÊ­S©ôêDøÍ€(ìtš#¼áŠÇ3E·¹í‘)«A pN””I· ,0&kµ¨w$¤ÓúØh�ïÑ¡{Ö¤n¤žÜÀ`¯˜HÇ]ªäAÔ8è/(ŠjÀ8f;¢™wòdSÓ‹  @»Þà°å áì‹}åÏ~æ­âé¶lMér)µkÃz 2láÈovô†·€-L&K·{—Æøñ? „ž˜®ÊvЇôeó±f"ÏÑ ê.‹U¾“·³Avèq6œa—ó6NêáøxÌØ-ŠZDSYi]tˆU¨)Ÿ4W RسªV¡zA}‡í¶ÔsÔ¯BÆ3w!ªýêRÝy•†ØÜÅ^`]#àáx+ëòÀÎ:{HXòÜ»Ó'[G‘—Û;ƒ­\>¬}lþä%V©¥=l³l--¾{Tú&«Q»"o¾0¹G»xˆ’Ywú˜ÞÌÆdU‚¼Å­W=mÁï51À¸uš7hÐ`âs·}Úëý²'v‡p L§ÒÅ_6kqvl#g“?@®P}¡’¥¤Rñè©–Œo ì3Ðs" x=h¦¶÷‚J•‰Ùdúöúkó3F‹cÆW«Ì¦åÙê|’‚‡Â¯Æ( ¨à �H×øúu”lã¦V­& ¬=FA_­|2HX.†§Ò«¬CÆ©ØB½Í8‚-‚6×GÇÄ%ÈÐC%?7òD®9ËW¯˜®=Ó@^÷sÇ\»ÄÈK•Öæ],ÎYÆ ¼G /=±|ÔUæé®µ,•9r¥€®°»Ï3Àªà¡TÇ„hðª\1Ïó@Ÿ–.G{)>~§þH”Žm ‹ÇU®eìi¿p›¥TCp礌¶¤ºÅ¥žØ¤7m-7 õSb­í:é™jã]àrq‘ôIM˜µTMœÒã±áÚ7ߟÑ]q§÷é¥ä -Þál.ø›mq¸°Ts—¹u~sÙ˜ ¦ö¨7–Ô©SðtNò‰äAËf]¼ìMNfƒfyÏ%ÍŸ^ù;榀WRtuD@½‚„ÌU¶Øo@¬npß›bnë©ÐȈ%…þN ñ¨'^ @L…OmqˆQš’e6PÖúñr=ã‡v¬ó†dPËÄìžvL¼$ƒ¤¹}:é§—!ê )Ò·k6Edó™UòF½×=Þlòˆ1/hEøÉ4¡˜EÑblå‹6œ·|(—ôV:y™iàÑ#J/GñámÕt�¤0=Æ»99èhù)²l Ç”"›”Ø[/ârŠŠ¸ä®süàÕ¼æŠT%è,$ÕÕÏð½—÷»YNÝ·§¢à›j´Ï)¡[÷ø½xØ×È+OŽ+Úrd·j©�õQ=×Îs‘¦6>ñÆ}Ë8éK£<¡‹rã/„s¥‰1 GA Ç2o2; N•s5³žÆÀ ¦<4°yÀoSs$—%BóÀüƒð*Ïž³kt’U xÙ®ã"y£¡Nsö-ƒ¿"\x} Š¶Û‡¥ž½”yÒ7÷†÷‚FD* <ã§ú”Žpú#Å!€1|ÆcÏýø‘=ÔRmd›'rĆ]íºðP²ÜsÛNhYyÞézŠù@ŸÔ¡©®)ÌÊýŒû"™€³YHø|YLbÊÑA‚Qecõ‚‡d]'-8à§Ì>ó˜9e•QJ-s‰Õ ï“Z]‚ˆÑ€Gí)O`G·DÒ™ f|£šŸ ëNg.-Ò6úº³ÍYbq»m?¦‡³ë7âŠa"4MP»)pïI‚%û¡©'ÇRÑÈÌìœ Ξ" íG˜LNèx‚z‘óTQØÍS(Vð<sñ¡ƒ·WËX)t6iUøËFx¬{æðH[žm¼´?Àìº~ÉN²¹ðN2�õèÊëUvŒõÚpYóE+>ãØLÞv~ QXY ©8Ë]¨õAÅ™ºîÈEÙ>ìë±ÐÛ×$ÚÆèÚDŠw$ò¶&V.â—Ь¡&­ëÑäÔ�Û ¤Ùr–L’ø<58¬Í�”×nެ•ßB£Ïà/×ë‘,.û œÑßÊCg® \r8ï+|Ý d0`cFeª‘q%´xÖ2ø¢¿7=P¬æ•ùè˜åè„ÔèAqzJ<*.^®Ëði’ħº>– lD]TuÀy)¯Ç42âÁXv%A&—šh8¬&DYN¼Ÿ§Ú,–qæõð9!ÚªªØŸÉ!€ú¤?Ý€kì)*†Ë}2üœâ­�–2 Íâ³Gå’+1³Íh4륕„‘I\%‹p÷ø ÇŸ83ÈÆIÇ„‹Æ²Y™¤A–³ ΑFy¾Õ{PXböDn¸ùOtï´"­—^£%ÍOOSháJB& .w<䵬g·aOw^jvtÎ*®Ž¸}KísP4: ÃÔÅ}«hW9!#·Q§QôJíU£Í˜¢¢¬�ÍꉖkaßãçàFèÙV6 Áµd´/%0Ôs=‘”FUa v»}’uñüaj¤¥:µ8¬³ÆÃ!œ€HÎk<¨P^ì”, ^¤—˜ÂsØâö VÜñJÞäbÁøƒƒö‹Á‚×ú¤áaÛøÔC*q&вODR?€;Óc‹<÷¡b;–]ÕÆüÃ%ɇ‡Ý³Ÿ@…œÅ>yh",Z\˜¢¡ÄÇ‘eYräs€‚µ:Œƒ+¸:PºPbk,!¾®W–˜Íyê'0mŒoMàl€.S¼îç [õO¢;fƒ ýØF< ÃYùÒ8™) Œ1&¢ì§ØX?}MÕ·'b®–Pú!:‡gGÇæaâc¾¬×=áúL¨”d3Þ3Æ3™çI6ðlÔäÙá›»L‘KYг<T—Íëwehè›Ãðä1ÔTŠ—:4T¾‹ê’j¸†÷2‚*^½îáÕÍ*™ª¬€7J `Bý– p̸ú^ã«Çf“¼wçô »è°˜÷iÄ*éMnÜk›ÚR–j“wÙ5>/j+ùˆûaw]ìB#¾Õ0¶ k¨Ãq‰ƒ6µE \_Ž&%Å»Y ‚áʃ Pd×о•²e*¸'sœ™Átœ6R —nHIdxÇØk%ˆ…¿äö<*‰^¶ˆø=L‹B¶©@§ >„'óØ<Vy¬öÁïoo{ßc’<w–7ǰ|n’ê;×ÇïÏR4}1Kíb¤å¹f¨SÌeƒ˜“8¥¢-ö=ôz\ 9íŽ×šëÒî¾±=„¹‰¹˜ØçÍoÇp€r_¸õô„Ÿ=u" µ.Ìz†w¹6‡ïM!:S oí½êçé&QiÊ¡: [›°€E'P�3¯³S§‹ñ �úÛ3Ü$Sè0„©—„t÷‡^L›P/º«•ç@?Ÿó§ºgĸ–-j["±J´U®]Ä&Š­šÃïðÞ’G“S.of+ íÐê Ê•4'¡îe4·ònŠ6�ì•ö1B¶êOÁуüs;ÔÆ Y´• .}|ËûgqXƒ“ß$›?'ËOÁÉç€@;MNwPaˆ>œ™À…OŽ•d¹kh¶GƒŠ­�Ð¥UpxÃH[†Íx÷¹ ì£B³Gl¶6«å'²�éù¦ž=è]gŠ EÀiÜ`‰L®>|¶¦ÅYýÂ_#/s¬:h˪sž «K'\Û¼àêJ­B*9•5\é”ю磺Ãc E:Å!Åï™±5éå€G&äÀ2hyd‚žGÛ“ƒm£~¡Þò¸‡::^áµÇ$oY¼‘Ñ,Áê¨`;{«]^{¤q�ùµÜöpù^ˆï!ì‚‚—tEç„ø6¨@·=m$KÅ]þ)¹ÌHœ¨( ¬W®W}ž¼¡‰æ×û8¥DfÄ$ÀPËóiŸ}JN?G…€"OÍÄ[a”êòuÜÑΞF¥²;§gïüÉn¹†™ôX¥/[(>ÜåË×ë’=òj0¹¦[Ö&f…÷…‰(T€·=ŽHê$µhŽ»9e5³œhìÙsˆžŒõé©'˜U±Ñh{ùØ"kè:Õ„cçµéƒDçRÔx 8ðZŠ7s4^jÍëÝ“I¿$®wI©O$ZRÂ,†Z°ú�– 5µ_ ác.Èœb$SQ(‡'>ce‰Uݱ¶¯âÜq³G;¨£óóD¾ø¶È%±¯ePÇnâ…¼faÚËNê, Aà¢j½1œä4»‡6Lêâî?sœx?Å4u–nL+w),Jþ««z__•Š- øè`>äoÑù§Ï…Æ{6hòŽ2£ D�ßÔ­º¼9…¨[o¨õY’פEÃX±o6Z½#ç^ìÛÂ&µ£8pcÎõЪB‹Rô =;•©D$Z"³ùÏêI‡j™NãÝ[ } lÞ»™i¤É鯙m£§VIKìIB‚¾ôô]áÌC !ž‰9H¾9KeˆTSLæËG—>S㋊ à%l*€Ñ|°q…ïõR¶ØÉ…]tÄ‹}wêe0ÌqnØë"PftL­“žC½„�é!ã~‰»9ÖlZÌ ¸¡Îm÷ñù??·fgJy¶GU+‘µÓ'‹ÇF›AÌ ?ï¡ísŽ…‹;)™Õ}*”¼`¡ž(?âÁ”7�9³Ð Ÿ²³ÏñÁõ‰2ç{Im^@osûÄÅ$‹¸É0À™›ÔM¦á`êinFóãqÚ´‘âØ6�yÒŠ2¹¹©ÏHDÁÄtz8t©€¯T[‚›‹Âj¾1+§ Ï+Þu‰×1±·wÀN×7HvXœ¯"žÞËŽ|l¾¸ºð°=Rxù ô0M Å®¬)Iß$AÆ'¨¯9K«kH°ßó¡ynÙb)ÑD.#úuòíÈ*ØNXH>½+Øãã)¿âGs²%A/Ÿ“èµ)ãÃ$sÇ×N££ü\Ìä‰är:·C6P¢<¸E ?ÛƒXfIWIÊ…xQ„ûΞ_y Þ{&°„œ~õsn¿»‡#Õ§òÀ°Þ÷ªz³UëæÍ£3—'­8ç"qð)<ÿ$´\a8Œ$ñÕ ¯2|b¯Þ°ušÛƒgꧯõy¡  gU65'ùf@Ü<bf}€ ´ÊÛô˜„ƉK]_•^Œµ%žoÇ@.‹¿LQÚÄëqÆz•5‘oR ˜æíMÚŸ¦÷!ƒ,Šæ®"²¡N^ˆé#¢ D·)Ú»Í#Š@£5¤©¨U7éÌ" WP¯Ña0‰Y*PØUýâBY@½¹è,¸¥š¡`�ÜÕ‡‘•%O̦îvÜÄï5Á­Iì3>ìƒõ q»ut[¹j1s-[/ðP¤Ö¹²½ªµv5>TÐÁ‘;v½—–¥¾sÇ.[H‡hukh¿WÁ‚›™—/·={Htôq´HI«nÛ”ƒ‰ÅN«G¼b€³ûÎwAŸÒK@gÈc÷Ht¦÷f»¼„GJÀ³^À0ÒË«{¤¤Ekàñ6J”ŠÜ’ž@_öáK˜É•†g¨+ àÔÌáx lC<²ðd÷ˆœ¯¼”Í3ðµL¼‡J–FÔät÷„–$mSÁG£w'É …ò�?RG"/t<Ñ›BŸ0 2È F¼;`¤+óU0c~ç¶™n\»ž¢áºEÈ&[ToO¸ñ=@›­'ê¾2i}a몼Ä̯žÒ9¿×{}ÞT©I“lA©”R|ÀT¯uê µ&¹Â+@“q£A- 𭆇¦ˆnÝæ"¤MÉn|›Í©ª8NXPò šÉóì§ï4œ/iAÍlè«J¥GGÝ’‚µðÝ¢+Ö³²Eÿj¸ð9\·¬½Òæ&aFÐåzÄ~Tºj²®ŽË/ÙÃã™KMÎJ¨Ð¼4‡”v©yònpãnr°ÙQN€}cï1e¶4÷»õÝlÐç*©€hæU;y‚˜‚%:˜´¥Îñ2)bI'#'5é8*.ïì*Ÿ˜zT4¦˜%®€ÜœI[Bê+œs,NÀ:˜{ ”x-q*Ø1â²­D¯Š,Zk+)T×ÝiÔÙ+ÜžúZîà^ÀÖ@@®“XHO'Ö;ˆ ‹ö¹&Ìçã)ÜSEÚoJž]ƒî-]¸ÀκäSÅ®ˆ‡*óJy¤Ü2txî4 L<"2‡ð XÍ;dN5~7ûžÜ>{†X~¶ôS~LáÒ·£ѬÓÈô0^C\ØÇ{ 4!öª:]ëá·ü>Ç ç<~dÑ]ònk,C`î•ê=Nš·kOô� Sp±ªEÄ ¤Û¶õ‚!­NjoÆZ+uC½Ð“Š_ôY–?]ö|P5Ž&±±Ìì¨i"§s,£ �V²9GA·{e,¶u%5hÎï¬.aQ»#çå ½,Üdc~™ªee8ìTú!nU/SÓƒ x¦Ã`½´íÔØ/ª±¶Ÿ7¨É6¥¶ïðJÙÃA~lb`-*‹0žåMðÔïBð]c=zÑã4½+Þ”'ìEé¶Ìcl˜`Ï_Êðñ•·J/ˆ®¬œßÖÊâ•Ĩ=‡LÐNOh‚Cª×³2À´AY¹øû^ñÐ(È»5‹{Šù �RÛF‰M;‡"ø^QÁ"ð§�ñsàHÛñg/º[´ ç*ÅcÈbRy†«»Ž#¨åñ‹u{±±iOS¡€í‘²öÓw»ÄœÝBáø4¨ô1ÄÎÍQfÒ6¯O‚½áÃ!FA<1уÒÝ^Ôt¿e†D¸ì%µº«k^†€¶›HÅcå“Mw\£÷ÎáNÄFö,1ßZy\_:ꜼÁÑ]e[ } wƒRŠ¡5cSdТõŒŸ ?ߎ\o+v(‹7ŸäÈbÅœâHÃñš-Þ4‹–²;§ÂFWÅ5/@Ó1MÍÓP w> h5£e–S´jæCÅÑÓðGB»H«T �ÙBŒ Õ*µD<>7ñZ�^"`^ÜhÃïÑ㤯ÞŸµ¤™{r=.Òg‘°ž/€¡%²1®àMÇΗŸ¤÷)A½e˜¾žÄdŠuÊX¦’Ø"i7nbWHgÉí]%}™¬ùìQQ¿ò⼘DgØ)sÆ~kpÔÄ×P(7Í0.WÍб•}1IJ°ópl½@ ì<êŠá$Žà¶ïx”#«‰»úõ“Ç}¶…”õà(³eN§1'Âz¯ß8k¹¼Þl ��ÖcW»…ñ—wÇV³ÌàMÚJýì1›@<w³6.·"yz ²‰lµs šd¡d"FäMúÙçó®c,›íLÜj/|bÊËjŒê…e(=ÛÃ3Eì /Üe;'øYÓc;¦6Ãã—ìâ–ï¥SËð [w&Ùª¶ßé/‚fùMí›Þ`ÙG�Ühw •ÄzÓGHÙíqRÌ-´Óá¼O2}7bT»6xÍ™WÌÀÂaýtæA` ÍäFŽë/ f U|øª ²Þ�Á²Ðý“!*°¸J S{íc¨·ïáŠ*"”¢0övŸß€Vû â�˜ËŠ™ûN$¶´±Ð;@gZÄç4°Óaˆ¼\VÒÃðBɲ¦¼8fÞ¨,ìFð0ËK÷"Á–§«ïñ›h{òÞ_¯$ ^¡È“z‹¬ÖaÌR@ñ^{CÏ32¾|ï*|Ì“µ¹Ùôeíf[‹Fã>NZ)3hxç³ &‰ýÚ¥¡9úaM·¢\ìv½[}ê�/·WŽaq»uŠ('‚£Š º;Tçê^.€—ÔÓj�Ý_2lÄc!J¿²ba‡Òy�ÄTÏ#gr‚ëdôñ±l¨²ö§ ßç8ÂÉéý|o–rßÕ,z–V¿Ã'ÈYdæ‰î¥ø×N”¸Kµˆù©™ »–À†S¿àœªkyÉ=ìÌNÌš˜P„‰ÂâǬœ‹~ªÚ&Æ#Òï›bµûf•7YrNÜ¥¯!yü%훡÷B§ÌcU zÏž…gbUÏ{›P•žÇ˜¾¢sΜV-|^/¡'„ž6’¸a¿C|è2s€ô4¡òqÀÎÊ1}“Ij9ý^ìï0èe¶˜6_Aã’¨Ž£]“ðK¡“zg´Þ,›ÞkQéN'›‰=ÓI)ë·e .h´Lî` 4€xWÇl.l>Ó¤zšR«U°/ƒ¶w+·þW.üçŸÿõ?Åñû×äÿÂþþ©Œÿßzd+§Iù“}gˆ`ãBûšžK ¦@ff¼kÅYêÝpNÊfCvFÒ—SÏ®´ÄGàËC?• ðóz³kÇö¸çUñôÃepä§þÂîtY»‚…ÈqnÁìZ:#Ç÷,sD÷dÖ:¬<vøZ9}Î\Ý?ó÷Œ£BL7ìÝX6dȼ$pBqXÑ©ñÇA µ–‰†!f“ÌÖ7纂mú:“¡æãK¿ÓùÃßI ßé=׫ð§ùÃáÁ¤ƒÅZì{>™½µrõú`ÎuÒPð”n!¤Îu ÔìVÁŒßÒ—{}æ8<7û‰íU«zî!àç"^È*!ÙÕžïáäE Žf5¾»g¹ V]$GúzÝövùÇç~wüÆí›ûùÁKÏGïøÑ°$Ã61T ö*Éèa“`vj. ã:5êK¼#)¬½sð$€FFK"‡øøàïÞ@xÈ/[ì'Æ:C;à§ï¹X¢L^žƒ°×®„‘yGÖ³ºÊºòÂë2y¼¹q†àÞdG!{ß}}ò÷SÓ¨²·ôsãü¢·| oÚÒh2™ ý¢S«aS—ßF‘²§?Ô9´€¨Òr·‡cŽ: Š÷47ý gÑOcr·óîÞ¯Ïö˜º×åWOoRƒ´·EòÕÔEk¾§‹ÊÚkÀïôžÇÈäùÞ-*Üc;µ¸çaM_³¼¾O¯Èwôü ’þ ÊÓ‡csJ½ÓT£o×é!§Ãéf¯õ“ fc¶�°Í: BÔ…àiæéª|úb¿ð6úö Õ¬‡.;QÊ&¿>veŽ$°¯_.Ôx‘ÙÁ¥°Dšœ9F%w9Ì”ø>A³ G­ç胸ܩ(Ûñ…¹>ÉݱGDdŠ\zÂýû²âÚ|ÆWT‹þ®©0N‚àxâÉ<!F•\§‹â(j£w£4ɤ I#{˜#J3ï†ôëãýóãsw¤çn<f{ŸÈáÏÏtGŽmê /ícgsjŠô&Û¥hYÆGR4ƒ^tr/ðêŠ} ÌO\¤A_Â×â >Ÿ©Ô>î€#  }·¾CÃ?‡Êv*o“–‘k£ô‚œ¯ÒË Åyìl¾#€Ã^y&ø¢ÉiA¦4dZ­òÍÞMó‰|5wø^|ØS2&r$:vl®§û~“à CLÒ�¨Ä;·¶‰«Nóv,«|õm*¶ËF5ºÓ ^?n†ZåkÕ“«^{UOB¿jÀÏÇË-nØ£­‘Ê%¶$•äw̪Åj…ŒÖ«EH#[J †‘g9Ô@®ñ¼ÕvÍîtÉdÛcKΫ·o%W-_µûÀ'ôùŽ/‰Ü^uƒº[¬ï!¦Æýªãv—ö˜IPÈßB%=k¥#}ï °›µøÊ+ÁTZŽ l²Ì\öçl[1Ï¢^ƒ÷µ–YÔgŸOZ(<‹°{Æó=±ÛYsBÓŸŒ¸û†°‘u9ÛìƒÖp Qh£heß'ŠÅ.ÁVׯ)lÍcSx¯æ˜ oXkI½™¾*áÏ×í´´Ïô mŸPh œƒíίZf­ä=RyD½ê±ªvÏ_ø=‘õ:>BŠ·96´^ —&»O§ILú™ôsÈ|Ñ©Ÿµ¼Ïwn¢ÎÓ%¢ø …HWé„aîO×zXÖ5¯Ä)mV,Zo ½Ip²²[ÝòÞó­(XÕðrºÇÂæU pÝ1Üu¾xù|ñ ûöö °¬âeÞ#·zデÔ¶ò3Uç™à®®I&µè>FmÀ¨IËÅ›.‹ì‡\…Gþ`Ä33ÛìhA‡è0 Qìâüa¿Ï7£ß=œƒÃc@EýVÝ×Dä&¨=›8—ŸžŒÚ/íl½Ò6‘[BLkèÜe k­ùgƒtö#¥ÊÏä © R8ä^fÜ6ãJïÏŠ>]`|ÚoöjzcÞÛו·æïYårÉcE ü9²#F¾kÄÉ£=™-Ë-yJyíd”îêkç/¥1ÞDûi>†.v-'éÖÉz;eò«&ûîö.7¶ø5 Æ­ ‹ÙÓ\G®™ÆFö <@ƒ'¶æÅU(5 woo}Œ‘‡Œd|}ÊMªóª’ŠÄ=Y×5GÖ-Âwdú:?µçß �äÁ›“©Ó°¥F½¤˜½lÏbQEÒKøUWø­£=í>ë[ÃÑñ‚ˆÇ۹÷.&ë0Ånߺái(‘ê «ÐÍÛ­©}A}-EEx_u}Öµ]dgyôº@C¹íbsIñ]ê!·þôò™�y ýÀÂçžô•¸Ã…eë¥Õ Ž£–ïºÛuå5¥Í«Ù¸Õ%aßm’ï‹ýgeyÓA‡ç%„Šx²B7Yû¸ÒA­ñ”¬{¦ütÂÙ3/zFS®K[ ªû@Ytó•uŽ�ƽ¤¬"Aå 1È©ÈiM*[àF¡þ¬íÓ7¬ÚŸ«^lÜ4/ÂÓÎåj³çâ »¤° …?«c;|Åhó´¦xeFO=\<!¼ŸVŒËà‘¼Dsóð ÒöDnvv#ì[Nq0=Ž #ý¬õ;㵋IFl?'‹´|~€žÏø1Ù^‰øû9Mèô<ärÁ„ÃLÞ·ïλ%€ûÙb Õl’Ø8,ÛJ¨èËbÞÍ5´žÒ2Ð. W žw_õѧ—ÀyÑøõMŒzß5Z÷¢D éSJ>~zemQ.û³¯•—+ßr£ß‘£y’hvAg¹ 3ûPWjØò‰ÂöíBЫ°ñùó¦<j9Qòáý¬¿]%”›×Cî$¡ö9½ èãøÎM.„pI×e³ÞÏÏ’´`KÞ«BùÇ «D –ÁcÏŒ}Ìà8<gX/—k%i©Á‡8¡Þ[†‚šÏß§¿�'ººB7ìœsÎAúsð Cgç~`ÐÚï(Â5"›ú÷Ú$%´ÞÓ‘îñƒ KZ¶€@\€Ãê«ë‡‡D]ÙƒÀmovÏÜ ‡/Ò®+gOPåÖw•ŸNãïJ°mN[²»d€èüÈ'! ˜æÜ5ÓÔv³³ÔïMbe®e{tÁ¨mëgD»š^q诈®FÒ±ƒ'äî ñd6ÀŸÓóÒ9ÓÎêÛýªS>='Ž®Û:`FË­Ç6 ½qS»ýšFfãÂV¦47á§»R_{¢§!ê¼  �ÁxèàÍÅL{SÈÔ‚r‹QÎòXdâ)jG¨TÓàÑó8ByvEŸŒê§ûÌúañe¾2x°óD¹¹|%œ„Ñ|Ýö ̙컣£ÙI¨…÷3¿Ç›ìéÈ! ï-wmÏ“¥Ñex-ïÁe܆ æco@HSC2‰Zu<|¨ª¸öteËì«Vûô!¥CyÛo ÚÄž´…·—[,¨ÈÀsLš¸ŸàÜi5-ùåtî)¨ÂñP7s¦D²“ì ó-EF×#On"1*­Ó–I˜§Oú²¨p ™·”_Õú§#M߯ÆR÷Ú$å#°á•mkE¤ô$ÊíP“tW6_|+u•óö§7Q B*ö‘?*¶Ms¯Â^§x³›Cª,1Šs<:¾‹";ÀY˜‚£XÕ!D˜Â·>ëýô¦g'–íÍø \ÝÉøY*r²(ÁÃVæ><<WWI1] gÙ¡¦¿·F2Î>;–Í)ú”sZ;%àI˜ÎE3³ÚM&Ôr^‹íÌã·Ô£èÅ—¤m›5ècnF_Ç÷l…”:´jÛE·ÏµnƒT!„Óäù»{ý޶“ ò`§gs´í¾•÷³æy˜L/Ñ8ªú:œ“ŠL ÑV¬†Tºe: TÇ+Œrb ª¸mY+Êß5¬#Eiô°¿¯7ÌðéWaÜGõ¦êÒê!Æë©z‹j ‰þ`œ3 ‰)†mc,%¾àñ{÷ûBk0Æ•g¶¹–.”X…Q©ªr±÷HRõH_lH”t¦Ó�Þ”G{Û¥Þ:kæÀ§§—ÌûU5~:—CíV-Ÿg<Áy/";Œ1WÕzšÞ&ôrEæ«jH;‹eÈà÷Ô&_ýô°ô{©~'Å[õ6§¢ŸÞβ;ejKÄs¸vñzþ(°8X LC„ÀÚCß4òÓ¯ºéÓÃ,+i›Òø™ÚÛ÷>È…+•ðÅVíñÑÍ ’Ë'8*Ç ¾ïiùþ¾1ˆ£Œyv†(q”õ:»Œ­³;»˜î•ùEÓdG†æBÝ ˜©èÕ#²yf/cì³òO7k÷Ù S‹ò¼G”Õ•}ä\ïŽq±³ÅÛÃ!NeÄÁæ©Á©U*BSÙOÖe P†^=¾‡nxi�a#‡{Ñ ãÅEÃè†úÀEµ ^½(kvrÆã§äáWíüék€ûø–®·ŸÀvðjɈ.„‡.ÌL€½[d_vB ƒv~½º9MU®u?SJ[%¨ºãT0n´Ú{½ÄÅ�Ô:RM¢ýä‘bOµLð-#lΘÈ>¼Â1›Š4¾Iòûªþ}:³1äóRÚ},O­ßÕùØö༸€ÊRxåM«+5„ò`(*ɲ|"_ýf_¨“r•sð+Üœ§®§вË]RkK‘˜BÁíêïáXÔÒ=­Gv×¢>o�kåÝÁ|Õ/ß)̓äÁ…¾ö¶WCS@ 9îOºØóæ=ö<Æë@2Ñã½m-¦ßjökJ­@–ÐôŸnÏ« ò.Ñ{Ï­7kñ™<t× kº’{p¨<!Ì CIZ€\Ì]4æ¹÷âæÙÚ6¶= ‚þD@?]ï$ç† ïî&ß]ƒ(4ªÔídy/Ô ‰?™-ŸVxeSìO@N¦¯ø%e߆öOçß·ÀÝ•AUCŽN §1ûÖ°[©‡‰gûŠr¦vïl×^0gZ¢Ú¾Å©â9[é@ôw4îŸ|û_‚bÒ–öî¸;öˆ¡Ñ¸Æ'†à*)²¿rè-y‚kV }p’°‰Ò`»Ød[ù …(Ò:äÒkæf™ ÓöÅ2Çv�Ù£åw¡[nR^殓ôøÁ–öãqà{«{êžñ…‚}:!Úã4#ÁÑ G&ÐïS7óEI÷œ ¾uñ7/åâjŒ¡úü Ì3RÖWQ’E‚U?=Én¯gèÁ™R÷òÉ¡^ÛbÏV[ öÄku÷{]D.‰p»V¨ÞÒùLñ’˜2ä ÿžRý²O0^¿)94½¬»sÑ ·§dÉÖÞ'¢àUé‡ËôÆÚÅ(|³úM¯G¯ Ò‹¸ø}).Iz;R{þ´ ñøžOÒ\Ó@eÛS˜—ctµœVïΗJ•“™ÅSC"2,\˜£úB">ݱ6Ô_­?p6îèçT)hë׎•™H+­cF&ƒó°ÒkÏÜ{Júž‚v4¶bîH\ØüÂÂ'ßñ`"cÐbwÕ öTÖ8óMs³…%"÷¥´¡…˜S?ëemö¸ÊyŠ#%Ñ©þ>°xðe¨bÓ^§Â©¶Ïe±Ù†—êlib%lrÛ.Á£ó6×5‹>n3sɌՠsÂ×v¿¯‡ƒqûR.¸zžódZžw)«ƒ…Ò<È‹°éwùožCêú%7É%Ö–½°Ø}¢ú^Jã|¢ñ阑„QûØkÄP6nRµáhœ;[”ËL³âØ÷íE×{Ìð®òîÕÔØöQ¸ ¶ÿÌQÊw ÂÙ«nW`Ðiך‚M‹<éÙ0c³X/ƒa¹*²5ñrTÞ±÷õ{.-ç$ô…êw‚>* ®1Ù‹èÜš&ʹî’,NÙxɹª™ÔÍaÍmÔ‡¼›=ì &Q¦‹q÷ÖÑ“°ß·XŽ™JÆ(Y׸ׂ‰Ãp÷æûÖ ¼–w(’)—ÃŒúàÝÔ` ƒ½a|•í>z,à‰Ó_ˆÐ§‹nÃE" ¶&%XŽÃ >2íÕ{Aâ†4Þ£ÊLòÖN`+¢Ýì#ãñêT ã¨Á7Ö³g…~f­`ócB´oÀ‡¨°¨—}ˬ€¡µ2øbKr7õáEbïÌí£`; —ÓçdýøÓOaú :2['S:ÝZrÝ£ë8{$úN…Þ(Þú+L»‚®gó4´—R]«¢6Ò³°5¬t4ùçôi…FUŒXÈ&‹²½Ø¸~TÛ—·ÇøÞŸ„nÙjÖ¿ëßIsç­ºÀ^–&ïâ¾PyŸÎ:K®•@× @ ß9\aÏåÖlàPœ?Þ—¼ÕðÔõ"òiǺC…¶ØsqZw¤$]I»k‹S¶G÷ÓS*™¶32£%ÖÒ5[ð¹ŸZL…3µ2â6qùˆ–\Bd€c(ííú·ZÞ§ÇîV7:ˆ‘P×ñEƒÁa2‹ŽÌ«ÆÈ¦|ˆÛÞ³»–b¸´›§xÍœp·Ea3e–aùPøÙ”juþDFäæh›l˜_IIìU”Ž /I-œÜ)[œUX<9^$–m )Ž­Í:ƒë<\ÅÂ&Ì× _ÈȧÛ>Ô’žŽÛ¬aÅ˺F‚gâ[é~3ê7þ–c¸ ²I^ذÖ㮵rIMî­IŸz+ò¢yW°J¯K³qvfÁäcŒ[™„½MÝÉ!À¼ô‡Úì’:g‡§fVJ™ ºUHçÝd®Ë‰–#×6úé»ÒryªÇ´pΈʹ>éä/ߎ‚¦¤­À…hqW¦Åµj'›>…E€‡ò�¯©\Ð[Ÿ�ºmâ«ë`“0Ÿ‰G×/¤_ØHm^=BY°ž’XX6ˆ>QTôS[ Æ!x­½ÏláL�"Ä_é“¥3tpä/tìÓ Õ¨Ó:5ÆÜUõœ8÷í7iJŸõ.Hu:£"¨NÓZ1Ü"°EÌéØs„Ýaåœ~YÇ OvíÂágbÝcäj…TP'ˆç6{=p©99y¯ s,à@·«ðÞsO`Œé§inÏÅØ ×>_–z1Ý$#NU’1a SÂåj<?`B(Óy¼öžªG‚²›•¾~§›Ú(�‚lx6ãùãlRú9wóª7àÕï9àí\Ê»íÕ— ÅÛ±HP˜³ñÜAÒ­ªàų ò*ÙJ·¥]‰…~¬›ÖæþÐmÍû¡ïä+ƒÏ^JfÉÐ#ÊNÝçˆnΜJH54pO0ÕfÌu®çv‹åž-Ζ§g½Š.µ2@‹nÒá\+Ñ^,ÿ‰‘Éß—Ä”³yÙº飮º3CÏÀ¢UÚêËþzêadãúNPt2ðгݨÏé ¾Ó°aÅÃ{8ï%YúH½zjÍ<àqî™$</gjŠIæx!L„„4?õ sgá§u„˜þ¥öÁÕZy.×ÈuùS²j= )UVºðáâ(õ´&«‰_‘øƒbí2�>Z›ã•û¼† |:õ‰µþÕ›¦èA‹O:b‹ž>pçI‹‰!%—˜žôæfZžðw˜õ’èQ––ù°ú´d&®¿ðfÃõWÐ8¯~zÒ#®D~ÃÕ%ûd;³QÛÎTr.×Ì!€4FÏÒÓÓ¤‚#Ž”·8ü:Їb^¬Ü§š?={ƒ4× òt…Ñtê®›R˽µÆT.8†Í3j6ö8[q÷QÏå½zÓ³b‘l‹{µ'"R¯±ëÁãgI£·t¹ö31*õsÁaÄ4×Ùד¶±‰{uù”LñNûÞJàN$JÁtpR•¦öÝ´ qs µëæ'RôéÞ¨ëÅãîUðf£C”Ì;Œ{_ …Ö3£NÞ½-‡T¡š#<9‹cš"¾8ãá࢛H °³¤£µè›ä¸äà9Ìø™!O^áä¥ÚNÔ G’}vòÖä-ƒ̼|†Uº v WÕŽÃ'ÀÒ\¥†«aü‰Õ§_?z»EÖè‰Ø€ÇÑ"2^æé å>•8MùhG–¶íN½è‰ŽÃ–Ë"¾K>߬«�n´Ð×õNÖ´(Me xkÙ®¡•„%2;~ûðŠ ƒ/_À#H/¥ëÜHt™tYžÜ[2( x•o»M«Ƀôîb,ÎÈ¿•ÅŸŽžµüŒJÞ¿šJ›@qc}úH°ßóUuÐØeG²ô[f¢;À!vèÊ|{~6„IH^VqR:qüù8ÚîšÖhŸ¹»DTþÌ™ü°VÔ,AvÇQ“0TcÔ¡êÐ¥ûx †<.€®0-LÔÝ &È}Ëedo¥öYôÓÃ/¼Þ§·³^¤ÊQç ã¨xotïxR¶*ÅÖ&ú¡„'ìc‡ã¾WÏb›øù�ÊÝ*‰’± ¢¼¼>®W¯b´Ÿ½w3pJcóhýNæcpæo)¨À$áVô*„ŠzÝ2^'Pð3”¸*¤"Bà™7ýšTÊrÝC ;=úA ãcË|_ˆ }+¬ÝL¹s±3¼Æ[Ê©³R^¶3¹žÛ†" yî›UÏ™“eŠfC«áGZn$ä/¨Ó:^SãâžhÙ›*•¦l Ç›bÐ6Ë÷ 3-뎜™»}ZçҢ彪‹…õ44 Ãrêhù•ÄxÈÅ ×`Ч-¤êÊ׉†|a¦Ÿ~ï¬ÓSñkánãWÅÃ(Ð^é-ç›åCr;Èœa€[ËA®7¾hƒq":|òÍÙä¾g•å}7Aì4žf¦$qý®Æè§—­ î $AÁ½ÐCx'zþ„@wä½"`{]eøtîhS<ÞÞ2»ÑEQDZ44y¿OÔ>¹†ñt‡JÞ{HöîXíùô<ÙBB ¬Æx ç ZwÍäØT ^˜FÑ àˆ1àºÁæÙÓ-áé´Æî�¥=S+·¡ñrt~âæ}®ê¸îº[ÈJg¨aîmñ!ÀÙ¤Ùä½—*ÏM¹Ø€±_p6z�ðn ‚%Ån¦Ÿ¸íNt%Z$@lÓ¶¸Ï0È3ëD´ÕU-9}­Õú°—$ýÑë}I:bRžz…°9|ƒ´3³Û´µ†Óá§œÓLl{bÈa™ž?sÁ vkžÔÉíÞˆc€Âiœ Ngƒ](êCiFð’=ï¨%8#wE+\¡¸¦`ö/ä¾/Š•Rj%Ûœ|—K1ãhš´gÒÐÀF2O:º 2� :-)Ô2$W4R§ÎŸj[©¿—8 ž­Šg{ ìËÄSrÔú^™ÍóYLðÌŸ™6’«XOhKZ×éшJˆqž#&¦Lø™ñ¨¬½a²“Raà˜‰°;ا·aŸÉãû {Iš-jŒjÓÙY®L;Št*w/Êá2rUžÊŠ<êR“9lÉ•w•oÊÁjI €y/‰¸f¤p¸ãµ.D•Ì+,Ní¸zc`/~vˆ!Ž£KT“ÄÆ¥Óõ]:¶Çž #+ή뺶aq¬YõÌHÈE*£'HOàKyú}µ¬º æÁ«“xÙv…Ì¦ÑÆGRÊ÷ ò„¾5ìÁ”ôÜ´‡µÝ5ShV½ B·€ûfsݬ;ßd<)5 Œñæ3ö× (Áõóåž=›9}L@aõÞ¹<Û{t½æùü %} û*îqà %¿°†ªàœÌ EC2zôÎ}â÷½í0ˆn–ò¼ºª]³Ìâ¬rpmÒH®=ã~)xYñ.ÊgÏ:²Å)eª'ÄÑòÊëù)¼ÅhªÌ7ÇÏîù¼ÔQ`@nâà E ÙÊfû99¾Z=ºà·Pz£±4Ù.A(û<QÙHé"ÈU€ Ôì™sU¶)4o™çæ\ ÌÁ‚ß—Q}²®,(M°ÖW™PîðõÛ ì©QÏÌjtŒ‹l%Ty·Ö3Õ"¯¼Û^«Æø£&„p¾Vß^¦·-ùânJ"±F“‚2aªòa!ÚÓwv/Ôi9Fjˆo1 °Æ‘Õ (£(ѪŒY}1cî¥ÅàÀ®Š‹ÍJ_~ßR穼Zr¯8.Cl @ óôn±g8¢ A™ÂïŒÚ°7³Œ$Ù¹ßõ½ñÙL±ëä^=F Åí¾(×ÃŽ•R;š%õ^øâi;µv®^ãó'ÅíùS‰fÇútÈ-à(å^ftxêKDx=*mJ0³ Ã‚h½¯,&¼¤ÞZø“�„xXõ…â÷õi‚ã¹;ƒd‡®ÊQ,zStÀmŒá›‘8<¡r/ð÷Ç"ÏAu“®_# ¢wà1‰(ÑKy0«{3ÕI¡{xÀO ð¶¯ñiM‘`qMŽˆöüÌÏÒ;\Æêâ4£³uûp4ïÆ©Œ<^ Þ½~Ù] ÑR¬K¼ü,ëUfÁ Žë’®Jè(-ñŽß÷Z7LK9ÖæIœëËÏòçÖdïr˜µÙ¶F—<kœ¾,•¶LñcÙCÍ»—µf•Чâ¤gµêXR:’¸éಔ=ÒèæÉˆ%/RGóˆá’øö"«| [e9¥`5˜«%&Û¯›£ UÖPý±É8Q‚µ™Ÿòc¬¥Üí‰øDòûÂPïnïÍ«6C¼{™FÄØI’§EK çu.1nâå‘ÖÊ S$ì:é\9rª\‰˜rzŠG¬7r>Â-ëqèœÜÛŠRm­ŽkƃwöKº‰(´o\v ž<ÃÙô¾#„QñqûFñÍ‹•Œn÷§‰L‚QÕ÷"À40[²û„|ß¼Ø/,E?±4òY¥1qQè×fùÈ©ÇáCó! ëa´tB&ƒ‘faÀÊñ‘Å‚1Ù©5Z-Ùª@F¾Áe:}¡dÊ>•“a@m L;ø�_ÑqŸ—ÇÛly?ÑtCÄ$Ðk}îg>ÍÕ]3V¶ãŒ‘q‚ŽN]˜ øÈ)o¦d%Ó„ o!–¸Û~wœï+²òó#еÂ9.3h3yoU]à[Û5¦ìµé>Ú çË.2ÍÑ„ÁK+áåÒ뱈í°giY;φÜïÜyéu¶jWEÅ‚yM…•9–¢îÏÞãb|2`B�ÃNŒñÒpEÜáÞ­ùó ~SÇs¼lüº:×§q¼17äb/#€§_?q,‰™ùTç÷Ýù’ݬÌs¢:4Y�++Ù*g{òa=›pêÜ$q™¨C?¼•‡dÏ©pÁý‰Ä+5dÐ’Ž”–Ò .H!šv³ÇV+Mµë ×²Ôž¿ëk†ÜÌÓ_ˆÞܾÃ~ÆÜÔñÒŠu©„Ì^†4Õ,ÑõÌõžÐÙíY«øÒYEy¨í{v¦{¡0iJþ9Ù|_ªÁŸâhß½n}eBbä¶’p™Õ uç1Ä74L¯-¸ž_—Ÿß+Àã}3õœ%xH�ØUÃOrÖ.s6妆É\6ç…ÇÛ'•ÉÓ¶DOÝ[x©â/LŸj>TÉ”'äÛëQ™�›…¡Ç47ýÆôˆUEœEÈ2õÑjÝÛ9z '»{`—N†>1ýìGêíçþ¢`u¡#4R\5OÓ)*è˜{"_2††Xâó~ì‹K'mŠ‘:²³µ’=ŽÛ^m}j>à¸K’&Ã1oÑç™A¯“W¼5¢‡GoÊHž %ìo/m6êÅc‡ÔU­“«ÜðkZRK‚;`䬿YZ੹ôj*‹k·×=ù²¦ê¥~¡ú} /Ñgò–ñJÞ’_§=>ãÓü<°Kôµ¾?+Ce­Ñ׉;5•v-Íû�^ô†SUzÛ‚¿eFö§!³¦%ï誟°l×n5s5ÙQúé‘­qÁUé‰òÏÉv5·ÓgÊ‘d?wZªÆUÇè¨xÕ¸„™u¯»ìM=ãWíƒh16½',µq<I_`ð>`ijUåÒ?Z…ÞÛe,Ì·ÙStH4×ê f¹ƒÇ+ä'æ.±ûz¯^ùÆS¦d¥&=ï^¶¿Ó7Å“}ë3èö^Ûëힸ}Ó„\ü¼ÍÒñ{B%ïQ>›_È:­À{A|¾»8‡þ\¥'¬”%Í'1âÆ!‡‡§äª¬ø`A ïj¢ŽêÚDë/dñ{R2‘¥¡•ÁÆ}¢%&|÷PUpÞÓðu éSœ¾¤zkt¤o"Gçðf×êaÑ�9·äVñCdâR£ÍÄ'-H‚.ª…c‡W@LR:›* |üâÞÈx™Ó ?îŸØZ¨£/< 䑼z¹¯¥¬edO#’3¶öê½§´ë· Ü)JƬ±/c|åfLÚÃÀÒ/¾°%øtt˜ÅTDDÜ5ñWIý $¼Gìe›íƒ·.<(‰€­'I+í€cã2B®‰¯Ý *àæMp¦39™ ¸cLç /±åfZXzʶö‚gl[“X˜s{^ãþÞ´ã†îÒÆ=}õ(Œn²Íš7‹œH1†ZÆ•—ÅâI£]ðΪæÌÓUnr±”wj÷>Ñýì`},Î]sóº ” ×& €V—vA.bÌ–ÞŠ Ë>[0C± udy/Ñàià»Ø+}¦”Ä}–/n…ò5`+Cߺ‘•ãUDzÜY7ât ƒØÂC+¿µŒ½J‘û™º6]ÙNbë Å™Èäñ£5¦mƃ]2d0CÏ.áKDÎð9öòu~³Ì‡_ø²~z®Ñ5?Ø‹@”Ê1º Ü×\!§}ý¤‹vÕµK¶�c4+jDVùe!d*eB7¨QïL‰GÛ•Úõ0Sœþùú{¸nÉÜ~"“ïªr¤Š„¬|ùŠ1ér¶Mˆ!éóJa;E`Íu‚‡'EJÔÄœ§Y@¨W;™Çãæ oçcm!ÍJéûôÞ÷ÙÕLwûB4…ôŹ™ãÓYæ9zÑã�Kè §²GÒ£òàf(01l§šÂ!r´©ÏV((ãnÞÈ߈]-…XlÏójNmÚz©Eºì£-WG ïån>ƒô£#ý™ÈÔºø8¹«.omÓr…»ÖŒÎ ¦E@Ž;ÀD_ƒ_¿0°¾ å(’¶§¥Àq÷<÷Óƒ…>1Îi(ÕàUlÒ82_÷R’Æ ÷sdë{ìV—àªàÒÔÓâr›Ï*†VhT’Š"mš àžŒÂ áÅR\n`0Fá+o•‚GÜ{åd#‡Ì@(Ä/<ßÛÏÜ[U2c Nד¾#,cûVf‘Íj×hM‡PHÇ”9 ÆÒ…l[JÞ…ÄM<½!H£/”õ³Ó-Þ]†“v¯—kõ_…oŸ÷Óžc#@>sÚÞÁesÒ(«¥²:A¶A¤˜‹ëDµêr´–Ϊ¯újÙo]™Þ*óÝb¸/VKöI¤¸EŠe Ô¤(¬KÉIé™éP(ÇD÷¾šŸ8¯×64máB3)°õº& ú‡4g8Ð,`ó?RߪȎäHÝïH®ì¶¦ÏŽdœ?qþžÚâ"«RE‚v§Þô Meø5< V Ú}“IÊÀ<à(nQµ/êE‡“ ‘?(º“‰¹09?jZË€6Ú—n9N¹*¯ðÄ’ws¹.¼åxýçýRÃírm¨�¿¦ÜÍ£ %!ÂJ‹TBB»Áâó0¯t¾µ;äb{×—w5Fá.¯ô¢ÉFÕìÅ#xDx“_HÛg÷cO„d¡NÉK_ŒÖgnãÍi2u\®öê²(J¦®QRy.WµSW‡žÐˆX¨mæxäëð÷ÂÜ ŠQ_§”¡eü)» ´· ºªËǨ("ø"s‚Þ[(IêÈŽ.Ô„N:Ç{ñ»¢)¶˜D¯ZGCð¶´36ÞYgé˶v�ÕÎxoöÄz“÷´6\ÌYy¨—O*ßóûœîü{9ÞºïE5²ò;D±MÏ­Ÿ—Š%5[‡Æ¦s½ÑJoØ%Clò]Ärá…„ Aïcx¤¥gTѵ@¤«ŒFÆÉ4Q€RðÁróÉË`UÞ7;ÛLCþ–DôÒ ‘ú™ë’^bžú”Js˜=Æ]Gj3=ëb=ðx€�›ô ið\‰óá€õF°U×¶w"%¦ùz}¡ô‰ö^Wç=ÁFŠ©¨è=h¶û1Ûj gô´ÊìTUN¹KJá+¦„†7'!Àe`rOcöG—¶ÑЂoÁü@Ú Ûò½ðìÀ´qèF‰$—h½$¼,ûšÛœèQ—¡GwãOu“o¼Á¸V�•”=Ûç€Îníp4,p :pŠ€Æ†1Òno^zvóƒÛœWËb‹gŽô0<Çìo‡ÏÞø˜[•^Ž«'ƒ“<“õ¡"tàð{ïW8á+­ÍlÂvKjæó®yTÔÚ;ÇDod·)Ìß{ïˆ<E2ÅåQ ½êá‘‘Ó�Ë[Ö±§Dô’/&VxmÁŸNW½ÞßøD¥ó´½“Ö“ò.0¾aØUo7oÚÏl™-È}¬á©hUÐjp½” á 9÷HŠ>ÿì’éÆ ­Ö©@ZªÎ�~–©Lo^XˆÀFõ‚¾N\¼ K†ÂgIïøTµ!ÆŸï¬öÑ -‘póÜæÒgS½Gç÷¶Ü±Ÿ3”²yà–‘lJ££¶Ž‚.äÙÜ›³3ÝÐÃPT9÷Dý÷´¸»%Ú¼ò.¹Âe/%ˆ›ˆä†êëñð¶8}c4”ó I’½Пö{´y�‚#¨Óñ…9~O‹ Vú.¦çphÜúR.}§â†êëp™ç4þNW—‘&®z•Ž#õê™.àÉ‘Vwାµ*ðZà9Cær<m¿6§‚ È*óv p;J\6ý<ËÊ7='øt”R+ä3ûé-Îo±Þúƒ5·Æ°çO%Ÿ{ñÁñdʉ°Ö´‚ùe4Èj‡°3="u6éuC0_¨Ógç<ä£êâî—oŽ¼ÃŽæ{Á£å©Öº»2=Þbô¦œÂ|h]\Âå¡`XEa—T£×ˆØœ#´—‡Ïýá‹Ê(º÷tbŽô2‹D„Xù¶ƒ›N$¸ä‚¿�«–P,‚:9í™,öœú…û`Ã¥Kû sí]DNŒ )/¹Ö3;‹C(@`4@ã0Gæ÷*bò¸Ê «e}Œ¨²]âq~áΟ=tYÌa+,"çµ™°Ì›)uîcÞc5Ca²¾×/Åw¢kz湞jœzŒ¼È`}—N)˜B*oÛ«8³B¦·^º¦æe°“N± móòUºÀ<Q…=ç 7ÍŒpK’WÈÖºø 5p4²?ÿ…¼æNß{¤EϹa`àiHuƒPí ¼Ë7h‰UEvJF—Ï´®‘}>ˆÛÂlX¯;HUå/äßg7Õ· „â²€w«ÃX%0ïµEi‘š£òԳτ՞b ŠjNÑã“öÈ :,Ö‹;š¬2‡¤ 6˜LŠ °¾êÎH�Œ~‡·Ìû 7·e¼u×”øã¡›TÐÛhÚé·æ£¿°Ï.ä^¤Çîè6 k¡Ë^2¾QÀÒö±´Yéưôwæöî@ÜÁŤ‹]N«@ ?±ÿì«ò*Kú˜lTK&ŽBÑÒË1%БÝtv%¦×÷„®ò%!Ã,/ª ¢3&Lt…õzÓ0eè Œ¡T½NRï ߀ÑZª)é­<¥ã Êo®µmÛ7£´´Ÿèaô`¬9æ<yÙî?'Ò‹gOcÊ6Iä âÎÜY7)-’vd÷å,ª‚V?„ÎÅ ×mB\¸‰|`]>s¤|wXž¸ ¢ƒHQ7z yp~üì³_¼ÞaZ=fU½š|íXÓ ëÚðòæí4]{=|Ø&¥¦…¯Ãx"#¯—'†U\ €_¸ ×%ª)Å2¾ {U­�ìá[ã»­ƒ[n¦FËD÷tuþé<uo«î5añ ?>Eµ@ V5¬²ãçÓ"”SäùÔ/ì½ôF"K̇MŽ «/›à ýëõ.”p„qˆ’je"kD/·…»†£ð²ˆaS ý½+…ƒòÄjHN”à]ÚåóU @ízÞx׸¸OÈ^q=c‹ÈÇþ¸Ï0Eâ6’�¯döãq5M,¢°mKp€©Û…GAlGØ�rhñÃû™vÊ,5–óàŒ¹'‡#: I%<]LóàavŠÇé¬6lö`N8PO'/@ЊC ?6yù™ëí{—+¾É·iìa<åµ¶Qµ÷ƒGW§Ç0dÓ]®#p<Ô”"È$š€é |¡KÊô^ RnyŸ[¡Qç`� Ï)Ò™´0-—\G4 ãù©�¢†$¸%ËîÛ]Yæ×¬1¾+Cqâ(㪓s|~¾|¥—«(ºæ¦¬æaù‚4ÐqS¼›;ÿÀ…sM¹ÒSu˜€(ŠÓ<[¥Ë7ð´6âÓ…ü{šµÖ…¦²ÏŸJººÃ;8«˜abqž6á܃¯uÏß<œvlêǯ¤v5ƒ]­¸¦@¨å$VU,Ð›Ö ‡!¨Û«`q…û-r=î}/ N,†rl,Y^ô˜˜BV¡Ô{&ëº>¦…½ó{‡#šà‹nÔkù&wÜÜ; 6ªÃÞÞ`G¾—Í:¥“áÒñ¬m!Ÿe‘Õ!ô˜Âåó¼OüÓ‹4 ‘)ëi‘ï\ê³ çÑ÷Þ²aë“@ð¼‰f™bY(-½{ý6Å×D^ �=…Ç\„ú:×ÕÏâÙ€0´/ë Vî ¸p÷ƒqy.Eå.¶ÉX²©ûº/é8mÙTÇÆÃâ&[Ñ3‡ÇÖ]gó€ä¾ÐßSo“Öd?y‹9 -$/)BUKÕðue'½!-=åm[¿®ä9›ó0ƒ  ‘S±wšþÅC|ödñÑŒ¨Ö'îôŠDÕ Ò<0Âî¾ye±Ù㥒lj½Rikáu¸d‹–wGn êmÍëIÉ)d(¸#¦èöQÄ-|“MêI«Ì1Ëa·ù°…ÒZm¤dr‡e+m$öÉà¥mf5ËISAÂ[c3Q¿ýÅŽK]dRét3‚¬] hྎðÑ.3ç•´„z,y{7[*VíZÖh%L|vçÚË{:v^j K#%^ÔØNPEoù^åòúUëÔ¿]|+£Ya”;Ãò€Xžê:‰ 쾤Ͱ¬æc†‰;‹Uª*åÔM—Y”ÚÜM=‚—ä! KÊ4ˆ®8W°*Õ`Ùž(Áî#Íd¶DF®§r'+%¹ý{+áÒ—âØÇ÷ã¡Ö.ïH6É{ª”)Xs8´ü|¢ºÉøñs›#(ô‰Ó+}¢âê/ÕAM¿¸ÀÏ>í+Žï]ZŒº>s%ê}mÏI¡C+—_”DÖvú?÷Iã§¼÷�Ãë êò³½ÃÀÚ„{Tžk˜xXƒêæó†Ùoö�êÆU00Ωá½d Ñwä4­òÀüÙ L HêÚ?¯çþûn îù ãÍÃàëØ.EÔ„ìbbËÌÒ«±¼'ãðÆÙ}¨&Ò›'“…¿Ø ÏŽ]"°¹°­þuŸòQP`i;-]Â#ʈ6œzyøf¢í˜wRèÆx�­ަָ3Œ èÈyLv?ãÀ÷ÎûæYæ]�c"H—&PT®®¸Ú¸¤È‹ÀfŸãŽ=o\ÜHS†ZÅάN rhŽh¼²D¤ÜëŸ=cËÕ¼}x†à~ÖŠã[¨³ž¹Ç"n–ÀÌ%Œå8¬-Mïid?¥=óVŒ>ùøìÝ´»©Á'.÷vôôÜUªrŸ¥xnõ£ØWÛï`:/ 0¡ _ EÙX6¬Þ©‚%ÓãݸB¬>^bx·&w=3ÚÒ´”¯çÉ)w( èV1|ðR‡êÝ{&òøi„¯óƒh&LT”©÷@l*‰q¨ë‘Ò{'O~12…ï=z�憗¢ƒpµVõ�¨ßSzýÞztD… ‘š¦é¹? âXÚwue‚ûÐBÌÆ¿áÏ.>YˆÓPðl AŠË‰ö£ FQr¡Gþ"N5aÊÿ Í¢³ž»”Ç+WFˆPúÔµÚJÝ-…=ç½Ã}¤ŒÕoÛ3Žž¡ò8Q²‡ÇîË,Àz‡ŠJãÆ…}Éî7 (øN‰è¡XEí=â6s.Ël†QéÁªôQ¦ùp!rJѬZg«Ó–5ž�¢DŠm{wR™¶KKu·ZLjÖ[}(‹iòšo±„Þ'ﳟ?Úˆ¤sÈ]X�$‹¤ÇïŒq‡_¾W˜Ž€F„ Ð ÇH°å Ç$ëñR²Cb: {‰ðYD >zëC6æñØ*†ŒÔy³äT^o7ÕóL) ¥qqÊÊ®÷êÓ®f÷®Q¢ Ý‘§øš¤4#SÈÄc3ïúÐfÎ~¦¬à<Ú!ò,^ÏX,ì: yA™-iØµŠž7ÝfGë)>ÄäX£Í·„| )ÄØ/|¾X‘ÏÎÎõô 4u®/;ñyM=2;Ʋ÷zi äÕLëܱæÙ½¸ò$&èæšó…¤MŠN‘YD•!Œœ)A^|¥7´Ô<œ¯äÂr>c~ÍÈ-Âæ©e4ÛLyòø]ð=EÓ­ƒ÷ú™¿§Öð êA{‚{;Šãï¿C4òaX•aå=Ôb7£Ý™hI&!DTˆƒ;Oô´#)Š_¤SK¿÷�òEÞ\}ñ¢ðé`¸*¯ÌºPä¤ÍÂ0õÍÅÊðkÒäÎѶÓb€á˜- ˆ§9™Rû*e\5 Ãô‘+ˈo<=›æš7Õæ±*ü¢[:^äôHrË‘¼j'Ñ?yj<ÝHL§è[×Ú‚½j›[ðhâÄvûÕm ,jä™Ï>d›{Gþà3J( ¬»'ò3U`éW‚WÁ¥óì‘…2¼»ÄTZUÈŠ,<özyx¼éQk#x÷ÉÌg·WÒSoôÔH•�”Èè§µÀ#¡¢áG“ͳfQþWoô#\8 ‘DmCiÜÆ%êå-}R^ïHùTa“<wk´½9Y\JÛwEã½´$´[œhB%(a­©‘Y’;ÃÙÖ«UzYZ„ËŽ<0¸b4W‰Žͧ ,2ô³ïÃ’eå¸Hªš•Í[`ª£8e¯ÜP©ˆóÍc0¼óF°“ÒªÒ, "_ ›U¹Ï9Åô“ÁÔ+îWm­Þ ˆj² ñ¶D³N®ĘÞVë3sP¼8²µŒ§ÌYƒ—žöt_ŠYç ½ÚFs†TÞlGl!#óžvjWOo@Y\"ö®YÝËÂà–Š×D¢9&Å›­72]¡Ùù 8_]½¼pïí:Ê•°®€°øýr²âF°8óõÄ{Y¥=Ê^4HÀ£’˜´UÏȽbOÞX"ž©¿§TR:ì=ÓðôsnñÏà™F×ëIZPÜí»Á`tE vYã´=N}ð °úÅ&ò ‹9JÃF˜ã,çTÉ{Ü‹ía+‚î½yD˜ê¨ì³ ¹XLì÷´zåq‰mO½&U2"‰A ŸE® X„½m°ço¢“Ý`)3´ 3i £ï€C:dàì¢ÞÏ×Ãñ„I²V´ÚKPÄT(²2#‰ª)­w¥Iop$»çå[“d}UÅâ úòb>ù‰Ï, |~Ph€5ï¼gÓ³; ³Ñ[ôe4%Ú¤µ†ºŸŠƒ˜pˆ®÷0/Üx§î<qŸ7ø xßk`b‘9la}c÷œÅ„ù=~’jŽ‹Ø# !e<'çÔžË9�n¬ª†Ϻ…–Šbzžò$t’OQIâ¨jX ÷|éCHÉOi¹,›ÈƒNÙÆmÔµ2ªæ%ÓR¿6LT¯T—#ô' ‹$S<M<ë‡ùÁ|Æ‚Ô'å©XÒ½«–;ïÙ“hŸäÁmmkk§´G^QâïRmN}©®jç)²ª® úäKÔã³äfg*.äW×Ñ•2”pKB÷^¶ªã–΃¬ÀÆrº5À{ÊÃ-GUޚƀWOL3¹äPaÊCôÎì™7iZCÔ¦‡÷µ³�Ÿ°ïÏᓉ#™+S¤àQcáfñ8‚Vß«„?«¶’¾÷€IJըW(¶à¸&Y#Ô#óò›¤Ï„�ËY° Ï8  §4Ýj:蕼.YXíG Më¶ðd›Þ0>98Ñ~¦!#šv…Mƒó(qG(ðèvCÎdwä%6­#‘^Ýé)ç¬ø Ä6 µô-ƒ`®æ“A©,iÒ÷&u¸9½QÞîóEô|·%L¥dKá+d®T€ÊÏ„í‰(ŽãöRìE žOw¬�€=v}¹ÍÙà«Ô†r^Ú}ÑPS\Å*ºõøAOÛ'M¨ßo‰®%¤„®2ë _ϵv£ÉNvŒ ¤"ócÄf6¹X¼×›Z¨C¦ŒRO1ÎOÒ2$4@Õþ9s– íqEnkAútëÆbV&ç(eCjˬ©ÌR³!–i,ßì{iPïÎ)ûé¥ZØpQiièòlŠ0<Žì]Î'M)XÍ4"*P¿ˆòÀ€`Ç-Cvà‡ÁŠãë´AÏ4Áwº‰¤ÊY†PºžX=¥w}´Æ«ªS)Áü Ã9>‰¢ÏÜ@¥SÖ;®*[³Bè´&ÓZ'#g܃©ç®2±ñ!EuÏkì¾ *|³tSê^@Fþ@:—Lˆ_wt+7ÖËR=†×JØ#OTNêî)×S¬y0GŽáËÆ$€õ\asF€‡tt5˜ýÞÂÝØ¨<'ËU—+GûٟƦå:fÝ úi¦Î 2;KÓD‹eÌ’ ÓÔržKÍÅ ~¶Ad»Þh¡|RÅŸaJ Šz:+µA)—¹ö9¢&ÅúrÀbUNJ'$z^õ?Æ÷�A%žÃãn;Rr¬³YRwÕ$6ƒi:éÎ8jÂG:´¦\êÚóK¦i²w uT€åfE|ãiñêÌJ r8t;PP1 ×�3ùuG¦bnXЖþâ^þ<Z•ødl5¦ªà bž%!û¼8Òk¥>ögxp@ÔŠt gÔøÈ¸/àD½ù$ë}†‰`~³ a5©àŠ€©Œïôí{â'wñZ æ�t½åY8· v†¹šdVB Ç: Hãõs“®b@t$Å­ìw>‘lŽKSZèðh·/�-õ%¬Ø{¶m×µšvNârö€w‰ˆGhØêÕ=ÒG®È£õH,Â(!;KÀÓ” ±‹|ëm ÃõCVÜþE×Uï9Ì€®-—¥<—N©¦b÷®À$8tl+^ÈÚ•1N3"Ç׃¶,ج¬åòmƒï3V¬{¸z g Ko¬¾¶¬°¶–çÇæÊ–rÐÀ(/:Ý�U÷™Ùãî«Ôz|<Œ}éÉÝ:*)²Znß)–ÑÔ.M„¢;ô-9ÎeÉ.{aºãXT`š•}#’ãó®S!Œ°@ƒ*Û¢VtÑìÖÛ¡¡ãŠùÙlÜãQìr«(ÙùI³gve{¶T7òå5lëÐö½tË‚+¬–=ë˜A–W¾ä­ŽâÉ*‚3“å¥þÄb? “Ï€qƒ±€é¼¥ÛŽPñĩ˯.éº"¨„Õß•="}à ]8ZÞü¼©äe\o1CSfFÒÛžèÇšÕÄŠéTåN^.¬QÞFÛ àt *b¨ìM {ùT›¹áñãtއb‘ÊÉAQ‹»ÏAF{ye` ÔnàihŠ*ßëì@ �Mê-y4&£þó]‡¿&õˆÎè±zu1,;¶-â.ë+bC¸Ý°äé"�À®«~™Ë«/1ê=.·oKÔϨ!‘KPz¶PÜ–á‘WäL/\'ɸ öá=Íeç=Å-^órû:2ö*>é+ã ÅõÇTt)y¼£$—9NR1%­M0@Y“tÝâ%5|+`uHÊÇ C©šxi¦Þâ€[ºî‹02+'ÍFhy ,>Vp{€ÝÇæ(uÜ/~‘ö ŸŠ4W4ðÎÕÁ©;¨ØƒÊI.SòM²3ŠfiLWÕ^¯ˆ¡öØY¨¡‘1¸ÙC¬OÒì3t˜í:¼Šc É"V²ð2*H,¦Àé-Geg8~ÅÅä¢(Œç`Q©á` (àªè¦Ñ´A<lY"µ Ó²@·^:¥­äžû¾d.2§@{hËÂR²X‚÷l|ÇöÍ’Ûði·ŠF%R|uǃ@±êËF³†áÀ.Ö)j=“9!‚]êÝú‹68¯4Â7 Ë‹ÜäT—½iNÍØ t‚:™x uaÀ Ï.ª¸”ˆØƒvä~Û‹ðI›Æ2ÑޓÁ|˜Áƒ¢ÇÐq(iÒ×ß:Òì>«=cªãTØ{ ÖlüÊ¥Ú{ž¡9Ât¬S`‰3GªY…¡ŸáZð‘…å&¿x ‚ä 2lU"›zùNôÆ=´^õ`ÔcBÉ µ6¤¢·L*Ä´@dbhçáÓŠ1S¡©ð‰Ã·£é tõsëò«éæ”1¼âœÞm!FÎy8ï/P:“ß.’9ÇÔÑFZ.öÛ%‘ mÔ]Á½oâü“8¦ )¨ÈJwÔYÐÁsp©ñƇôN7•K’rVäœe`›ÝaOÀ�†‹duCtÖÊŠHƒÛ« GV"shcäÄwnJwiø ÏÔgÚ ÁsªáŸwDTo7¦PÞ³b°ã¬GÏZf#=k”Òg{p¹ÜÚ+ÈN ¼¶ØÔ^ëù²CÃû9Ÿme=#”ô+ß7¢XDP8Íj`É.gU€&ÌÒL‚ËOíâ‰<‚¶Ç¬2p ß2># ¼‡°Œà”ÏÄ_=ÐAOÍZ{û&%ªô\VëÅzâÙQ'À\¥<¥¦ª›õÒwE8 ·Èè%šB\Ž-»M±ÅX`^Š¢æ:É£ãÍ á-ý¬J-[ß>TÉS©÷ä½qЙ•{n#lÜvaAMêZ¶â„kíKOœQ*BKÔl‚t²ÅŠhÒ[5a~‘7§çP:¢}—.O’,éI ¬6 ¢]³„ßS)í1…{ÅmCH|ä§Ö«R·Pv¢Úb{_ä!|ßOÊq£rfôðMHF˜½ŽEž²”‹ë8†Šúª²§ ÆeâcÏMm~Ðsafî§‹6ˆ>+¤.rÁdðŒoÐ+ÖÖ‘*Áæf ”° Oûö-‘t1HŠnÄ;ð]òÀÊ šÍ“·erÖ&Ð¥6NÔ¡hÚOk<) ¯ S—ÛPü~Úæ†mÌ›ÇøCÁ iG~SöVæ-˜.4J¨:I³aYcÐu´Ö亖™8¼VD¡¶Oúð3¦\êîЛTUM"ǧ…‘ÂÔ´•ñâpöpí¹9"ŸïÃì¦2¥P~~JÂ%Öû€kÈÉŒU´ta¼6±'Á_²±;júƒçr}|Å`gf—r›ý\Cšòži‰·Y<¾z"Ú¬4Ñ•^‡À¹À¯2}Óë*ú¯Ú£^¡~±éöŽ9iac-£)à÷ÂØ£Î=®Æ’ýQÀpáÄTª+ ®p°)CYÛVÏ$F¡  £ÊZĪk&d½Q)…òOé{_Rõò°ÞA4örçeо-ã^O=§t1æ÷€Õg÷maW[‰d£€—Þ>›Z`í'â´£¶Ä÷Úž¸L–@Ìa9+‚è“'ú¨¨pû)/:<¿&~f­E™À"ñ¶‡Ùó4ïu5%¢jVú(y‹­¬Xçö¼WS²@¡ 0¢Ã<>³%¥ÀfÎÆ›h‡Yö÷~òÁrPÓJQ´CÓ˜Bgâbð3Û•Xžyæ·ôZRIß’ç1fÍ::™+`®„V}Sø]ÕÑ»•àñ¦>ëœÚ QÄÂ[}ë‚~¨íàYf$žK¡îf¬`iágÍ}½C‚[Ûê.€r‘u¶™•ûÔÂÏ©K‚tVšøÞK¾¸~Å­÷@JX_ÓyzMKç‹¶µã½¯ò¹‡R®?z:³r" û(C—‚:å]=MW=nGkïù,Ãã\¢›!ú9ïY+'Lcsô½Ë¢!:¥Æ0±ÌW;0†ä“ôxœr ÍÍ_6½9~'Y lr8â¸öj>Iäϯ쪱ßÛxQ8¦hÃXϺÖ:ÅZ/ß=ˆ7ÏEmÙc»õ†ú>Ð7g0ç¬ùl  ™YK€¼X‚a(¶,í"%/r¤ï=´'•ÛQøz÷Nòa¥4ö‚Ëm…CeEŸÅŠ/ðž­òR4û˜ÿñ¼3\8y^vͨà’Ëž på³Íz9±ÕRÚÌÞU~ªÃ’«÷Ï~¸.ã yCãg¡d䨔ŽÊÍ·M-Nê§zöú.L°ŠbaÀpÓoèúâ1 ä˜89Ö}Óø>ãÌæƒuîB/NzÔ¸ÝÚ=PæÂù8&‹Z4úZ§Ù㤲ëLs/6ÙÝqÉÛ³aݲÞw‡Y\}§µÁ ¼nÎÌÒåÈV+…ÐÓªw|‰5Óš¸;öNàu­Q€TQHºQÅò-õn¬¶Z?œò½±qå>„󷊾¬“<Ò©sÁ|ôNC^%8`"Åëñ±UËû½˜¦@z&Ô=/Ûèe4pA±PM©Qœ·´>/Ü3Ç8¦¥´YXr}æIo.ªØà\¤±?‰”ï£ØHÙ>;Õ‰$µg:ÌθVeêó^7?öI¤ @ åM¹Î«Y‹):-ñ Ä‘à‘³¸¹e ]¾t¸£3ÅÁ‚iDoáî)e!Å±Ž¢â¨ Èn&!誩Iêwã.:Õ»hŒLIjá“ç `%-(ˆ¹/Lµ-()„€Ýß{[{KN¢WÌóHáqt¥qƳØhå_T^n–¨Ûql‡Çké¾+±uJUeó‚»5¯,Ûê:®¢rTä3ÃŽ—»D3^ìä{ŸTêgÄqÖâW‚òLO‘oß³| ÍÇåGÙÉa" C#CeTãÙm(À„åjÀùgžêˆ§„i¨Q¦Bޏ•?ÇÙW•"”¨OÌÂ<p[xäA<'<¦‚t‘‚·ÏŸ_œ÷mlbmˆ9¦IŒå„ÑKC ©S3-keªæ¨(Y ["¡”ˆ×8U\Òæ†‰x"l€ïµðOƒ}ËB…CnÉÖΨ·Ðš›EͲp°äÞ㜖—¡{ÜnÚ}Osö£Ÿk ë¤Û7™Ÿa§ÛÌ_¾@JË’V‚Ì¢¨t³îrVÖœŽãéx'¸sBX„Š{~„ Iá"Ž +Ü«½ó¤æÌ©q�†¢²gô)ˆkèÛɲޚªm“ P8›¤rá¢q¿„óFÝÖ^øZdz—Yº8GÃ÷ gùúfƒ“œçlí.†Î=$Dµ·Â´3Ÿðù,v•XüIÈÎû½/Õ&÷Û—öv°XéhJîú=@«öŽ­yr’^ï¶$ð9(ä¾J¼KTZ„Õ@íML‹ï·iŸ±Ç”£žâÝ‘AÑÉÆÁ¼^sŠ÷rS6Àmë%ÇVh•4WæÁºz»?xd-Ö¬.[îÊ£C¬„xцŽ1q3Ц³ÍȺh¼ì™dI,ÉLÔíT„×Nê.Líu‹P2÷¶å6¤r‡mqÈ­ÖãáÊú.‚T?Úa{…+þê°!n5ñy+ôrsG“C ‘P~¿O,l>d/9f=<wNr׿¬TÇ%REiNGï¢_&.(w4Wô¥©^]åÊ'¡þ€JùZ±ú*Åç­ÃÅ|â}8…s´êà>­/$*aÄyÄåÏó² ·¡µŸ?–-¡ÈzU½–’µjÑa¹4µ,ëÝ8O t&¹ï¡«J‹uí¾ªzvù:ÏüÞ®ŠÞ6±Ý¾Ýª¼$ÐÅ=ªÝ—kXE'ï'soëÆ€‰GY˘§‹ëL¯ð-qÞá©ïðTŸIGE´ý~£ V\DÏD™K*1S=1úN4,[-6øÅºÆk•ö&TšéNÐ a×O#øtŸ>ý¤4¾£Ä{u2³ï=R™×ð&'ŒðŽ—_×)ÑäñÃ[Ô }Œ§ýæðLaø…n…MøˆBŽëm¿éE£w%ïÆæçÕ![Ψh;ÈÓ+¬ÔQÚuªÌ „½×^ÇçN¦×Wï-lËÓ¦æèß ~wÁÀ ^„žÒ¹¶o¡Ô=ÇÕ²èæ"t )Vñõbc§ç›;rÔlñÞ×/R1¶hQH)CØýé ©iX “EEn”V² Œ§¯ˆr³ãa–=ŠeSaö~™ôE*Ág(z}‰dÀ@zª·3Ùžˆ×b‰Ë�·´ÈdÇcÅ9rWÃÑÖåÀ¶ÃEjÖüTIß‹n)˜¡>"<Û×ü^ä«—¡‘U«; b›Ù,ÉêzŠqœœbE}Až@´E¦¦­}¢�ï:ß<ÜÔ¦|æÑ¦ gUÎ>ãÎÅ9¼ dk&ÕGJîøÈ!¢íîB _CÈ&2,T{Ê] ©ÀIàϬû&ŠôJVÏVæö’ï.„ÌÓ‰ì½ZÓ³·Wí‰9êëOTùm°)èó=KfŠ8V]ŠoZ?ãÑðªtõ¥…*æ½àÑÐë>¦Ìœî½]ãõ‰Ó ‚XUCÝ07÷~±Wn…ÛÇ™®CóTra¯=諌šwÅRmúMè@=ž]g#ëÈà:ÑN*Z‰œJ •§é( vmiJ1/žŠ­Œ“Öù:[e2ÒMæ!´÷.ܧôæàÉ‹›Nåh£È3Ôöª|þ‹ØšJsöĵTÀ‰{±L\ÖrY‹‹7w|æ*yC³ê²‘ÂÒÊn»úc‘-ø$?ƒ’?êg'J4v†kËèÊIå.-šP©4õš’nÖB¦@:)¦!ݦ޴Òî³|8ÅZ1SLÁÙ¯2׿¤u�í -Kt‘:ç™Ö¾Pð†X›çCã³ïR<›û6owŸ7dì¶û _ÞkÁ“7 0N>3Ý:„IÑ']R$ R[žˆ^^îºpQ–6iHi†ö‹Úй­»”•qnŽB¼g‡4ˆ„p6ÊÐaÐ73íö9ÄÅó(\z`wnW¤ä3‡×@ßÔÒgdÒ~ †!Æ+FÏUqÃok™T /;yXÙ…1—¼ž+qsrz66 �¿T…¥1\Ôáì~uÑK(­‡RØpmk6<d(¶ª“Ñ»$~~T T/;Ø‚gt)–Áv–5$aN¹k®U¯ÌÀ‘·ðE'e bí¾�êgm´û@n¹áõ–‘¥ð¥Sœ‘‘*áY?÷4 oLQ¬cûùn-ú(ÐÎIƒR“ÕÐu@äz•Áqç¡5¡B­t»×d”¥ÂŸËFi‘K3ë¿UìoCæÏð$X6UÖKw[,»o…Ðo\,”-=×ÏzDÀkšlP@0èMÃÞÍ<w�¢GáGy|¥=Âj”eWRœ\]û¬o8‰Ì;×SnóÙ°€šÌ:°=íœN±‡ H�@¯•dA7õÙ;"~ªqü6�b¶â9ñ(ã»Wùô0q·êÃõ7fFVkOËS k/X¤Ö Lâò½°Ã¨½œAœDƒ\u&³wANµÔVGï±T ò= M&ä ~tà†zK¹ù“ÞŸ¶Ì1Á'¢¸NX˜Ïˆ]«éîíÕ¼ÜQqÂõ—¹öÆÁ(ádÉõüÐT°‡l¬pë±Ó™¼ìR7ç"8 ÀóâÕÒ#‚Ó¼ÞÀmO8b¼P¡Ç¼ÒËÏ£ŒÌPû^n¥MOôPdFº’ðÅó™x’•±ìB58 3i¹2 OŠœ't±+ǹ™‚’Q¦D„¤ÿ¬ñ©ÄOsÖH²ª‡ òàá ±!5ó'AœOUR¯B‘Ç7õáØ–_ÌÓ‚ ³.—'O¿ þ>®ÕFvŒ¤ÉˆÊ âžr…Å€ºJ´6xm¾<T—|Jã°OàÁÞC•{ý8[ÙÓ»v$º}_?A_‡jó,ì¬S­;çÍâtÀç"À`ŒógùäÚÁ‰ÛëA±Ê.-ËUºéi W:ÊLËkØý¶žRR*-Õ-øAwNð*ÖNÉ ”¹¦‘g©ê-ˆé GÕÅÁt¾È¦ágì²ô‹âvgÀJ¡‰ÓÒ¾KV«eHtoÚè)KÏ2¿œE9¾éç+JÊËm÷±žá[ú¦X>£U§ép"IH:š:)€ús5‘gÃë'ÐDyÚ°Ö+Pï) ë­ÁËX·X‹›7˜êÞÉÏX±ýY%Ìh¦P°nž¯xb-4¶Á[|:¬š[ìµ³Q{¢‘í™›lW†‰‰i#mÏ$}öŠÂ\ckg GQR&‰_è .bV’^Bš…íÚ,¢…+ °Òôž™4ÝⓜԚÄîbÒ:}ïÉoÈAê�è|ãøÀGJð¬)çV2+S„ž´Gº3BðSduRÚt9!Žl+ü$Y?CÖ™–Ë´Ú#’Ñ·Á:8†TVyv€†z@Ã\„ MíNÍ{È)¦…Mðçg¾çC÷T� !2'øìuÅÚXíY‡¬çq‘Z{4ʱ#{?qæï~ù ÓȈ÷^Û{éÂ} M¢>óvÄ“:ô=½G¯w…•|¥æ¬” ŠÙ7—±Üš^áÓÖ "j½{ s±@Ôõ4æµ¹ÝëJny/1;ðBîÍŽš©SQªLî+L·y»æ&ÍÅ«WÙÐ3ýÄkô)†FŸÀÐ@<ºn{Àb\€ROä“f£O»–òަM­c¾k7ô«¢à|›~†³‰hЧñÞÁúºR:†•s„˜¼Ø£Ç)dqMú´æ5@”îl=cǰ¬zA§…ÓQé'n‘Ý#©…®Ü6>ìRÊÑ8¹õ¼_Ó¡tŸTŒ€Ÿ3s3Íš›c=t#År‘~µÕ$É-o°e¸lµ„QÁ}…ÇTœ Pq)ÅÌü @3k$ñÑHR‚M¨f-ÑÀL­‰<`³"›åàb|à)z©æ-Kg]tÁ/keÅÝ^fÉø!ï÷{vø$û¦)­»ì˜±xh÷îØöyN\F›{óqÀOD(/vu+q‘¾ Ž—û¼ê5§T…ÞUûÁ Ã…hNV“©œØ•).>Û®sQæ)]öÄóxŒñvÎAg¼S6\ZÇåjk®Ê¡wpºP¬®”׉I-­C†;Õ°>¹íÚâyÏ’ûíÓ&zÝ"=£tB˜”^iT¡ý¢ŠŒ1¼¬°cRÍЯ@SäÛ¡*xÎÕëu qÃêC €#2ÁEâz8\Ïo@H­éB…·—•¡f˜á›êÏöö U>B²éѽw~,3ê]Dre\Rm‹Û’^•Œ¢¼ö.ï¸ÔßÑÃí÷Ò@q¹9×I+‹ße–ìÍŒÜ`Õ 6vá?I‘îªrž}ï(:©f÷àa<õ™±îvhÈP ¨ê~c¶}Gت5÷\ŸÄ<² ׇpîœ)ÕÍÔϼ*2,‘ôZ.ä  |Š/äµ f`tÿ4pÞ„K¾–Í]µ‘ÜØz¶’­’àHõÈCÎq„k;(Ñuí™R ôËT6ö"¹ù$;ô³O§‹ÎÙä\DêÝnXrVD ž(†À wxaÏÍÕRû=-p»ìH8ºn_.z¶øI—œ k S ŸwÏ«b}ˆårML¾-ØÅ(x®Ãô´”8}Ú‹ûÅ…ø¹œ/»ÂnQá³HéM(>¯½qËÎVz,›Û]BÇ®hÕÚÒÔº¤±9x5çå MRKV_]ø¾4Ë¢<<¾I&惧Ã~8ý{=Òx˜O÷AÀÓ’d|¦¶^¶V8‘AÁø· PŠ#;ä%ºÚмæ³9Ú'bÙ7q¾ÄÐï}ÑÍð}. ðg¹jaW ¥Å:ºâÞöxŒÄÜ;JÇ‚XhÓ)ÞI¥ÊKV-_,r'hNœ,LÒ”«Ÿ´<†õ‰¹÷Üd¢•'#Þá¾âÜ[¥Ë6/e³O#™ì´ßTµ%%ƒM˜frìÃ<6z|Mès©YoÆÑJ“Ãæ¤SÁ20Ü"vè¹>,åzÔõš¢nÆÂ$;tçšìe‹ÒÀ³× ü,Á¼÷5ÉúOÂ)‡ØÑ�¨ý�<æ›Â‰hl©uíe"יּè.Q¦n©¿sÍ ´‡ù2¹²Ãú%Ô'áøÐNGšJ;8ä]+™5@¿ÎHÞA*24>(ê(Ø—žª²j«1PHW¶¯·Hxœ{Ëèeƒ@ÄÛGG£GHñ<ÖŸnÞ¤Ï{Â{O8ygýx›¥3™(ÚeõÛä$gÎ4~  ªd þ¾ì‘‹ñºE3ó‰µF°ó @áÕ\9Ëà [¥ƒ¼(0Ï›à(äèb'%oÇpß gKƒÅ/ʇ_Ø3‰Ö|™1˜o‡gùaR%Í!YmÐT5À–d[yÞD MŠáSõæ~eSÁqôX?)§Ï¨Öç¢TX;4j3™Ç³[äôô‰n1éTOI_‘Gv®ú¤Œ„‡.§¢ ‹ÃÍâôx¯VàÅÈÂR•cdŸZ*€""x¬š2ÑŒKíLWÑè{¡SÐ"Y¯•øî&½£|ÎGKûÄ£.ã²ë (®"É*È9Wi„U£òˆ „Þ¾,ëËõ«È€Ópx½ÐDqƒjò jÌåM£Òƒ¾…¼à­_¤Ã{.1 Á¼{Oyÿ@Aß|*&ÒÀ9O|†\òŠæ½yØ£†»¦÷i©<eLô¦oÒ¿÷fÙ˘U´LjñÞЙ,ŠD¸LËkýƒ }ÚŸÁ#¾N†2fœ(æ~ù˜Ôœ;s±ÞÂÞ…ù>{ZmËУjd›ìiQ¸ò–oM*¾~˜Rš¯ðƒèK±jC …Þ!6 :{,£oa—2¯Å¥6€/.†z ÜÈ«éœ%Èr>ê[½ š5.`íóÂðð†.~"ÖÐHMãåoÑ1ï©U›dÌϱ¬Ë»ãÏûTдÂJ‰4ýÏ+ÍZ_÷â9CòÜ^Jz’ùHŸÄ+4ÎoÐm{!~çýýÖù3¾Áø@äÆ! ‡F¯¬msD®i-c›<o3µ·8’h«€­ªTD.Ué¡ ºMùA‹¾ò­S—yvL®;IPÎ,~1ïUˆóeù˜ŸË»…”Pt&†–=_yÔ6ºßR × °­ñWnª ó¨×ôB‘ýLš˜ßÞ͵ ò#[š4 Ôz̵Œ´%3ûú Þ‰g˕ӈ8šeë=´»“_Ä»™éM£KP‰y ¿¥ë‹§ g¯ŸÍ¹(Òy´Jð@ƾ' ÏG{2a“‹;Œ>‰ïÓä™XËx¶L•êøx2ÅÙŠÅ+Aö쉘KFíMK‚ê¼ ŠšPÞƒ^®Iɾ÷ª·| ¡ <Ç`¢ çš_ž¶™ Žãr¦û{áÚ\›zOãb0^¹zœ >%Q ¿ƒG/ä5>~5·—]P`Ã6‚‚uáÜëÖý%Ì”Z ȳîÙVöG.ùäQ ¢dÛK=ÂÁi}xrÏ×ß“©_í¢öÍŸÔó½÷ŸÝ^ûJåðÆîkUÅ4Ã\o·'ž¥†Â³=,“§&º{äûrVeërÁÝ5uÍx¿©—ÏHW·åä¼9­¼ŽþJpNrùæaf{†rÔbx¦¸ÚøB«®1=f}z*ògø éo}fAJÆ6¿èŒxσ°ƒ„äøŠ§÷ <¯uHãYMÕ Ÿp (D+>NU×_ádŒ«PbÆ Çy<ˈžŽ1ùÆÔ@½z‹CP°Cš§8(°ÕõTBæ‘jB V>h;´è$—'�6Aëcžß\½×û‹|AG °7¡ÐP1Æ#‡”7yå'cR“Jl‘º0jd¼7¤»)X«/­¨v={6PÉòI¾~†» ç‘wìÀëmqo§j6Àß="|œÁ43ÓÏ­ Lô¥[F ˜ëF<ÓG>Ü–FuYÈ)áú™ÛÚX*Úƒ›KÌ5öìÕTM<œ.§kãÌ~’žñ:Žjø™â —…Pb9éKÂ×z›öÊ@°ˆ´"¶Íó)•siÞÌz^žÄv r+ ~kãõ„ áV¥ZABÌÔū̲c‰‘ÁÝD#Ÿ¾ú½®éMï<ßËG#/[öXWéÛĉ€ïèuéã7jÇWæÞÂÞÊbá'Tt`œ/Moû%Óÿóö 6zXBºj¯èS–²GDZGm§fÌÇ–²Su±[Uoš°f®„9âFÝK«'¼³ŒVOSö “Š}µPH0rÙL/w²^S²Y3mèg‰aEö÷F¶8�Èy$‡`2z!Ýà³W®HGUWš^±@œòÆf–¼Ž»¼öùsx –ÆGœºvÛX�£ ØrWÇn Ãw~åIã.j9Wao—@2ê¬üýœçÓÝôö©PöM·ß2¯Ìë|˦šn}ª›+Ëf°$4tCéB¨J¼«ú4ÀÉÛȾçyÓOóGh #^žÎ“9·DqXcdÎ(€®mŒydL\k‚â…x¥‹ZÓ\ÝužøŠàš¬’âZ˜ «Ž½ë‰>&š¨µ»REÐ8zŽmU&ÑcX¯X;©šæt8™ürk*B2,^ú¡ÈŽ&ž[;Ô)HÔãkÓ�…žØôž=7{ÜçoEåÏgh{µ´»ã½/0,3Oxƒôj—ë:½VÜ·ÍŽb±Öc½PNI@ÂXŒÕ#Ƥ8“ÞØy&š j€Ë;¢=¨ºgó°kÚkŠºè¸EBA8ÔLÁ6>%àŸÑo ñ¢²Ò :•_ÎG{WNÒ µ±œynzfMãÐpoz¯ÆPž³±8HwÒ ©¡|l¨·úvH$úJT‹Y_Í‹]0´š G˜Á7~9S5ý:¯Øº®à–ÒáêÉÃòΉé}bÆž1<~ú0Ï›ot•¦Q¯3[Èò%H½!ƆZ{ï` Êó€'ÔoíàwÀéµH¿R‘ç·5š9Ò²;§¼·ü<š£ü†b^ïïxM˜å8¯PXùPV¸N9@¹²E¨Þ#싮Ί»g7f³’­ÁïÔò!mb \Žš©Š ¾CàÖ¼Ãôwí…²ï ¥¼ ÑX†WvLŠš9 lÁ† ¹oÉgc<³€£š—nGEb)ô ï›Êxlø¦ªhpÞ1ÐnÀ8îõ¸çxìÓiçØŒ9EßtŽ—Zw ¾f¤• Q=¯VhRI|iïmh&!½÷(îÅžt=×±;–ÎÆÊ.ÛCŒ÷ª»(‹ŸÌ£Á-ö’ÖŠgü<ŸøÎò´Öè¶<+,è\)«eMCz‹ Ðhp÷s0kxxL{1ÞÄYÄ*ŽÕéïY¾a%r*Î*ÍÒhÅÁ#x®Éw/,Ÿ—¿®Ï³ìƒÏ8(Ù)šÀ‰lþjšÉc‚õÅRº4™Ö‹ š‚œÌw:äGȧæÍ‚°ˆx1ýÏK³ -õ!g™‚µ ´R³£UÊšR·Úóµ…Q7êð7FÜQÅ…h[ÊèÂ�éP—*=ûBÆ Ÿö{.® ×];àÚTOz/”‡™âMmh!ç–õë‘À¾m¼Jô5¢ÖÅ~…¨èõNïy†—¾â»vMý+là9dYÌ[}(%‡ýüšþ‚ãS]º”xË1MI mÏ|Å« ö‘^lˆÛI ¦5ÅM[ñZV´Ù[æÏbï²o!|ÔÌ}ú4™Ú¥¯³èZà0œ.«è-–œ÷=sy¯çÚå1ÂJÃ)Dpï¼ñ7ZO™x‚!§ÀM"Š¥ä ÖüU§„Ë‘˜…] ë‹¥ #ÞTWiÆ’æD.ñ*¨k‚ËšIp¶Uƒ¨Á7Ð¡àÆ‡¢—#ÅÃþ çz:j5O0¦H)Éî‡f‘ts\høPĆ‘dp)N¬C׬y¢â^\â=ñ< †ÂÍ~ˆµu%™·fv°ä‚e[‘Éñn¹Õ#k×öñ¼—âöš„,xn5’A+÷Ë=5‡O)à÷NP»jÕ6^†9oŽ6ˆ%¦„?ózõºö$Ã6¸}ˆ‘!‹É5¥ûÆ1%:?·`·t‰t8„= ïñ³‡œÅ.yÍbj^!æ [§÷À41Ï„-6¦‹Ò]j†BdסÕS)C¡i†Æ{÷©>i[I|xº°Ä™Ï)kEu5öpÉÙpi‰µY¢òmP“(iZÙòéæË ОEå 4ŒÂ3 íš•«á‰ÓBÍë�&þÙ ®ç�˜Ž_¥ö£Q‹B§+„{sGèQ²§úèª õa™ìD PakqHíÚË«‡ñÝ è3,¶÷™q¸=›7ž#~Öf¨1 %†îsÄ\4í)Ÿ“2õ(p&N}µrØÊÇN;à½â:{UÍcƒ¾Ènc²Ö<ÜÝÓXmh¯ÞjPÎ8Aö’Ò<é¾\³us åg¨ ‰JÛÞìéÎ5ÊUÂüÎ�n^ÎŒ„Ä’³M&hµ+‹_V×Þ\Iµ{˜óøû3ÚœÖ~§Íz*‡¢ë‚ hû’ÕJr‚Çí9R⬦UppN1ý’CPæ4PUXH>/`~»šåÆsÏqˆ)˜®äF›MiV|òéàÉʺ= ;”vF²ƒdxTßràÏØÇiÛ#XOÅèÜq8`®Ì!'צ¸ž)ò3ôÕ 7GXy¤s™VÒ¦e,Ðú˜Æë°okA£’å`àuÍ!CÁ\››ÜË·J=å+$™3Öë„ ŸS6úA¼GcÎ ·.io9Öò9ÛsÚ¡{l3ÈEÛòúb¶§yÝlî‚æ ¤à ÓKGˆ7É8›¥Ï4óÑ´?Üרâòþ,Š…j†íÁŒ&ªåÒ¸¢>¬2´þ)螺-È`>BÜÌx[O(�˜?îó)Ë Þ0%Ãs¤+09eä‚`<é àšJùÄûháîFÏ1®r8/ƒlXÌ,TVÓ±…&|ƒIq$_:Óé™xðLç»X‚” ÛÊìB1�ºÄ-¹Ïwä½íg¸c¸sOY™ÞŠi¯ºC¼V§BÁ•]À„zŒí®’w^Zzt]:H1i±a­Cå—Ú:ɧÀ14X%ÏÔ){´OåT‘Ǽº‰Kj`ƒh[ÇëÂ:„Öß yîDV2îT�ùÕ5s™÷D(¡$"±ÿl{Zxd½ÕOÔÅ}•lÈgD#ÅÓ/R0qÈÝêÁ‰<+jµ6 ´Ú ·ló 0ë¶€¬oIø§$L÷X†¡,ŸG”7Œ,Kì“ôÈØÇµ"®xVîÞù ¬Å„*gwõPt<q* Jk)d T¿*yKÛƒìM%×á;­b O_ÄÔÚ•½yÖcÇâÄEHRÇ'iÑ™üˆÞͨÁ0Ëu!èÉ5ÇÓ{o8¯+—öa¶È_5‰c¦2­õÈ?{H¤–ç4¸É»³ó‚õx¹Áᱞp\"ÛÚkfš“|öúYµAA<`©:.²t¿D±bÆ´6YúDà�xWX8×£¦u4ÄT^ߡǾk¿Ì‡SF!o}%Š‚TÚÏ\Öø{¾ïP9G(tùî±X»=г5ç Ó ©¼¤’GIÍ|<8ˆ6(Ñ÷ŒÏ‰Xôv_d¬€¬ÁùÑs eõJv¼¤'[Ú<¦| ÁíQa´ª%<tâ�s켸¥³ßî“Gk“õdÔº»‡SA»k‹q/ @*ÁÐt&ËÆüÔöÀõøJÈÁ6¡±Q…‡A·2¡˜NP/ûYsX>àÊI”çC ͳ!f;]™„›Ët☀ü6}‹IP~æ ãb9�ñ³’Ä'ãq¹ý´Ñ "YÞ;¿$ÀGS#°ò$¼×âa̼9ë>B? û”…~ÆK^·Ñ­’öœˆy$(}‹ÁÜ–~Z^U©lä½—9BJÜP#Á舔ϕùŠ›�Þ‚½h·|X¤éõ<žÇàÝÃ|EOé#ê¶ç Û3ÑÉ@Ô ‚àìˆ'˜{EyqÃ4:vrÕv–ò`ÂB·š‹Óåá,'v]ÁV0Ùz狎ç–%ªD‰œ+O;,kö´DÙa& ÒÙ–ªè@ +÷¦9*ß™JÏ g¡±W<ÔÎýy¨²Ùp+<"ž56ƒ4Ã’2c%¬"N¯…"í£ˆ`ÂgÕ±ô°™Vñ2ôͻǺÝ7üíö4›}´ L¬K„jăí€Øã‚’`°Æ'¨®‡Id@Aä�#^½–ÊÚhd»ò¬‹ð™Åzø5¬(œçÚ)ÖÞ“ÍÔÐ Â-c4–!µÆ Šp‡v‹0C €€ñ´|lKâ/¦€¬ì®(òÌ€cÈA‹½ÕJ¾}�}‰¨+‡I—ž: ¯rºÞÒÈÀ,ãM?ðÀ~bŽ ™m`%:ÊxÒëE=«ƒ8hf;q©Àj´x3-&~=r9æ ¿[ɑǪ¡<¼í'’0,uÒ‰Ô\=ëžO7O:‹æ±]\ÏžZ…›z•CGº½â{ÚßÒðÏÈéC³|Pl©ìÒÆá … vØm Õ!(Ž4%MŠWã)c•¾6eÙF=AFߟEnƒ¤¬„—øœÕEŽeŸƒ—™$®'qɳöòÑ„(z8\l† ÝùV-x�RP¦)‚ºìÚNv¢ácœŒè^=3CŠ¥léS©cÀÀÒCèR¬í@“ç]M––±"¯@1TÞÓÔƒÄW‰";¤R£deÒ`4@¥07¶/6A¼i¡’€&ï`6pýIŸÅÏ»†7q-<¨Õ7Ĺëc»¡D䩿Œ rµt$fÐÔŠ¶¥arbŇ6#Ö·:U^Æ·8üÓ7ž¾ªÉ!“˜žp.•ŒŠ;—Ä5l;&xUÔA8ÍxÕã-×O\=7ö\J;ʹ*)%ˆ�wÔÅu[¶É®ÈÅR“b 刦›ãVñd±ît½^v½ÖI{^kÇÎaïÎ.}9ÎÎÖ_27»ª›4`u!)w< ð…X{—UÊã­Ue<¾üœ"J¤šá‚îÔKsvnžÙ(‹Alj ø³c]z•P"bÈÐÛb[98PŒÉæèñvI—ÞÏÛg?š]Åž°8á}oú-c\Ée[’ÖÃÙUópx5x{¸G¨;—žK‡E±Nзw„~zGùü¹OšÓ-9Jª'v´d2ÖÃÙiÁk*$ƒÈÃÜ[K˜R2EЦé v}ñä´ZÏJ,;Í»ÉR/ÊÃ]<;Ú¢PåŽÞªª™0.ljQ­Œã“>¡‡ŽˆrLæ@bu¹Ûš‡”G¾âÖÙ ž˜Â%‘£÷šž-o³žD<¶Åá)öEÞ)Š’†{ðNïÜÎáÚk-‰äŽèª¢½´pŒZÌ ½j“-‡a˜uPyo!Oû™Ë:q6/ÔÏáÕPàFûâå£ ¢½®2â»x~ö:u ù8"[Þ¤WƒÇêRX4j»‰«öщ¿N;šÏáUà3jº!¼§Çêkð°ºO”&ý±?­ö 쨳‰Ñëz^×\ç\¬ó^¿ËàÇgÒƒ5ËšvAçj'ž�sè(ÀþÆeœé@³)·R|Øn5¯Fe;­ß ³ž¶wÏK×ëFºßôÑÛ7BTóžˆ?ßä›íeÏô–»×•2ßܽg0u;:û|‘@èsÛ¾fJ22;>â"#ÉÙ§XÈ"î!òÒµ£O¸ÆÔNŒmDÐßnbŸðÎ@˜öóŸ3Ë¥^@°øãy'¾fµ¯R•ê]V£1Éå…ÐîŽÁ%dŽfø­Úq©±&¶ŸµÔΛ(@[ø”~GÓ~IÏðÕ¼Z¶vOžDpÚIë¬AyÍc5j0Ý’),ï)ƒxRœ0ŽngÆ©É !n°D­“j¤E»È¦Ç {S›âÌÀ6ôƆIØcÚH¬Í¥ž1ܹ¹yú£6VcÐÓÒn¬–ô ½ ëž¡,u>ß‹{ò¦ ¸CUT…ËÈÀYÏ÷Êu_´ W™xqÐ-áaƒT17RŒv;æžæô“‚u'Kg¸•'}b!â@hCÜ]"›äÒ0ÞtÑ’ô¨˜ï—HÞ’3Ý. Z££ŸŠy#E¼'QýÜÀ™Ÿ'âÙ-¡¥ò “8[ð ÷lw¦yŧHè3¤‚h»QX¹ZÖ=1Ý8î¶s:¢Byy]GÁŒqX þ&54Y1-–ÝCêwXNÏa 2ˆ¥¶É %™Ñ$©Š|<§ŸIï-ó™Ÿ÷’…¡±ã­Zr½ó—†‡-D¾Ð”†l|zj¤ô®7}0ã\Ðàr.¡jH€¥¹¦¢É<µ¯AB9=vÕög}ê{¼tUòª#Þ,1P9EËnªo¿‡×•76¨¹ï6î.¼`¥šräÍÞÅM¾³Ò6y"ƒW™ós–Á«°Ñ{hÆ!wðë—nÏÍÒÁǘñµ¼7. öâ.YN8¡¡&ñ!"«J Ú¾eò½+ußx /« =æ4Ê+ùñÃ2ë!_s…•ÙëL‹‚Ž|B9¯œ2´ÖŸ°nYït-ˆ•¿ÔÜsÒòò2,lV eÙŒ“MÈ4€ã-s–jyŠXAú Cxoí.«YSo-8цhêc. Vï—Ä$Ô|±(˜µ^(“X™óûi½‘ŽC„sCjK}‘V½ÓÕÝz4`$UÜ¡•¦mš‡P8ˆê\™qס‰*B¨füÄkÛ¨`9:Ž Ùü6ë­iþœk´¸39¼Ý1òú9ÍU/½{T$ MjiÎÆCÂÍÒ8Ýï8‹PˆòÍ£d¾¡®QAù ë§ŸxH¤í«Ìu{AîȬ 1ÞRp˜ÑLY3Šy¸µˆ5¥Žd­úÁîñô Ô Å%¬wÈÙ:åªGÈ%àa—�B¢;K4àÌOÈEÚ'P=_©êõÒ$ÕK[k´,9ºÂÝ€²X 7¤ eC ç0}˜ûêmLðec.â%ž·ÅÃëvÚ,z–3%º¤ìïÙÆ(Ä*B)ô‚«ŠfnNr{ãØÄ[º¼}Zx‡/6·øÞËys.®:{ç™cB±˜WGh»…Aáïmj<ϸSM7ŠK¥›Ž’ 6lywnFÌ;l¯ú Ð4ì5 &Ñøh­ $É|Jå}FØ.JâwO–¶G\ÙCò {$kdVDߌtÜuâê*Ÿ)—4¾«¨gÎÈíë {[œÐ'7ÁXæ±j›tìKò¬Û®cJ9q_€µ¾ ¢™$Þ'c„bPyùÒü@€”¦¤äI¡ÄâN§n¿r#~\þ¨Å6¯oÒÈîT=ßcÚ d biNÖ·lØ4¦‡t8Îøt.^HCj‹ÕÅ®Ù:\˜[î’Õâ-’ötìyp¾´éªfµ}pûöOåõh“$ð—X*m¸4OBµ½Éˆ Ý dàÁ¤# iVóª€ûô#ܧÃ+o†ÑÌZ8rÁ¹¬<ß;ë§Xä3ÌjmÎeá¼i=÷ò~"¯×U眡<tÍ5åÜÄÖ‚òÛì­A±0ã=‡3¦°§Â3£=³Ï®´}`hº¨žLм«)QkH^×LO É#½:Škm•xØ3wÖC ÙBêYOA¯»2vv ©d�ß.4¿ƒ"wÌÖ¥·(Xë±[ÚiiyÝwÄo¬ ±"¶N¼Z<Ž &û],ù™,/¼•âÙêU°|¡ãÏGíÒê2µa¹ùˆØ‚S¢o'^MÆ›W?c­wJ 5"N©ZšÕZ›?\/6d çl–=tÉ=´ÛÏ‹Ùú¬)àHr^¬E/g\¬ð§\ô{÷z*§Õéb €ºT¹v+³Œd+Ydrb<ÌïŒÏA·Y„UÁ÷hFW£èÕB"×išB¥nôb?¿Xt¤¾ÐÄyþbLæ¤Ê…ÝnÌ7…×ô¼Ò¶µÝ_8ÂI\½ª(€Çè„Pl‡!¤®zïÄÚmh×>tÀ׺ Øq�ì…@îoj›1¢ $§ãmˆ$ 3a4"ÊíÀÊyá=˜ëG&|ØÊxÒ-\>F‚±†V £b^™-H"yF—œ\éúS0Åþ¢ PgÞ“B]¬�MhÈa–Ðy0xo°Ã%B€8p½óù¨¬"Œîôø~ Æ?ó<p…æ :2!4ß(Kq$pjY£¦e5Ìe<íGª‘ÙU5瀋âï˜aÉÛ(üÙ&>ªQ¶â£b¯W#uÑØâJŽœ¼Y•;+kˆ+«éE}ÖÇ‚ æõ.ýìXúkëÜñÕÑóœ‡ëÚb(›ZùŒMØ"m ÇüÈ”èê©g™¿Ì¬|+üRççôEùáÉ­Û…Yiê\îC}fϨài:"º ÖeœÕEöqr­€õ¾¾9Aê’«Ø—õS2@à#—‘`ëV·ÛvèŒrÞ‰¾S‡á®ý:¥F^Vl‡¦fY9J‰ û»«Ã}JÆ>£îÍXÆcN®——5–œ²üÄVt¶Î|ý•%tÂzë×@Óä2@+’3¿{޵\„\8–ˆ>m«¥/8]ÏU•¥‘\¢¯"í)¤Y=!JitçæÑìv]E%UÛ~ø6áez'Žª¤‹Töøå9ðK™‰2Ô{–àè Q¥•G”)À Z¯“OÄL1<†òjÜKSÍs<O]làðÚ¸¥Ó< +¦ "Ç ®Þ2Åš5"lN_Ùö÷Œz¦3ým±wC²H+ùÏAÚ$ÔðÎ÷š;FÂТ½;wOÔi¦¦ÔŽ :ï´—=ó|vÔ›©%eDo…G{ê»1ùgè5ÈuµDf‰™ctZh†aý¶æ1©zß6È@Dv— ‚RÉÜ¡hC‘1«ºe¼"U‹¾™˜<Ë!xÌ>ýâæ”&’Ä#´’{Æ4‰j»|ÁAJóàñute—•lhn"åLês‰¹W®»PâË«…îõÀ³ã-R¼ô@¤'»¬¸ «€{'>8lÊqlµí°Uoo–ÄÑ+˜*ñµÊC¹, V¤yãj›KÅh�+¦‚‘"ã{Xù‚Óùj#o2à,s Øç—l(œÝ*=yË}—µ®< ®;Jî}8wÖ\#¼g»<ürm¡ #¦ÕøPg=|õ½ ú”ÍcÑ}/îÕ¹¾wf…ïÞ¨uiM4žä²˜Ž”ã³¥RiUqé<ÚXÏ…"“ßé<Ö@aGa‡õX†ba±žl]ðᣂu_P€Qª‰“Í{îs®ùžÁ&‘(:í{®Þ¯É¡¾R¿4 ° àVœšÕÎæNçNå',AÁ‰TÔæè¶´ ¶çå»G6í@͹,‡)P»šØÏ+mÑä˜QÕ ÈÂùej*î¤:'Ç.ƒƒl¾—qöb®ôF�ƒ_d½h‹£ŸÂ±ÞSÌí2¬‘I¬Ž±D`O1¶—bæaI“ iv½·¯žÐDd%ˆ¿Á/á(|áf _Ájõç4ÆlÃYe2wë †/#ÇX @Âf–^–“Qéë3{% ÎèõÌòí³™+ÅŽ=JÁ{’"þ\ž_Ö¬š.ö˜œ²H&onÖr N;òÄmæ;8œ8ç7Ö9ÑÖ’믘‚]ª¡ö<¤âpçÞKàyõº‰Ó"µ”ö?MYŸqÁ&‹™:)CË-Æ‹§ù4›‡4í¢Þ —<*ëx ëë÷lºÞž–sgöEî•"z]ßÙ¾W{l[3í®ÎQf?#qvÔÜÄÚ�Jx€W>1%γv$>C„»©¸«M€éeäÉþV•=ÀŸÍÍ›µKÓoéøg¾IÑ:cèwÎ!n‚ÐïŠÄÄÒo»/Œm¹I€ HÁWq]Æ’ƒ[mVPË…á9½ºB–e®#*Nâ ä:Í*ËrÁðrt+ªž'od™Ñ;»˜n”›1×N[Þž¦%åë8Þ.Ç^‘y9Ouæ5‚g�GŒ<Œ°æ"á'*|Ü‘jˆYX£C„úMR‡qרˮéãº1c²¤³Üè"g%HpC«§´Ò8*©3F4ÖßãÜ.?˜E‹Ž®ç•ïô¶Y¡U„NWßN‡þÀøx__4ñû3Üš*Õ‰¬ÊÛ+�||u%c£T‡c=ð8­Òöêù¡lµúàÅ“ðµOñàg8.E~Í8ã�` f”8âf¡<ͰW]èÃïé£Ê” à<#¾-•h 8² ‡Ð= ]Å7|wFƒÁypæDB7ÈìmôÞ<XØG¬D&E4€ýšÙã0f4j.Ä·–|óÝ-•zº9c_„œxºu\NU’[Mû+ž á¶ 1ÅÛazJ½ùXV¨½4#>Mb1¶‡bɯÇIˆ›$±ˆÉI{o±†×à®Q’q­A cì�+ÅD,§Vmž)¬ìAI/dÎwž%£ÍbÂñ¢l_à«×ÛeÌÍŠ¨Q‘¦EÓ¹wgî—F†#b{ $»I"qô¾Û½ïÛõÞŠ&Ï‚´À£•öõ*!PÒL©mN["ubäÁðÂKæk£vdy.nâ¹Ú¾­—Íô¤uŸ¼A½¤쇪—%8GF.~4 lý ÜNß{4Ï-ïE4G`¯‹oR*L–¦Jò{øB%˜Ã8›žx,K BYÏN?:ŠEÈÀ 4—Ó2¢· Å/8¸§ïK ØlB$‚x üõ¤€ST f©‡jðž&aDqM‹�$J9‰?‚e|MDÕ�PýVòêŒSGð93œ´Ö¾j‹OLȧ?sOCµ¼T+€¾–{ýö=Û›èÌóöëœSof(m; ôƒ÷NZZÄÌ…_Z}ÏYÊŸù½ˆ½»ìW½)dÏö÷Aïs¯ ”vO¼[¡ˆ‚g˧EGÑÅ­«/c¹E_’5¶æ`(°1°nKÝbúµæciB—8Ä×ëÅûÚvB 4Õ1:žòº¾%×3—eJ‡÷§hÔ›Ó¬Û‘¦B—™]›à0»»ª™ÌM«“ÅJ‚ý€Ô©Ôé9áEx3¡2ê£ðÅËÆÊª¾+‰×îÞJ`1vS}ÇC(F'”nD²–€#¦ö†Ñs{¬Áس9/tK÷¥‹g·¹>xüSBS"fÄ=Ühkãø “S’ºÌ–OBNÊÒ<·ë5ˆNUN̤Y]†FCæ§„ÞgtÞí*¿¹|“Jhpjd§aãxΧ€wŠûÌd¸Ëè¨=êxýDwæi ¼p°dw§´Ý«v¹Ž Ú¸ôWž·5ÜkNó&%€œ¬p+Ü6ñ ý,3z9u£ú)]©¶ÏKôI¸XÁ,º…tl$¥S¨þŽ Ã+1V†ìÎàå])ú"øš­®?äHɇÈxƒ£ÌÚd”þ‡¶ÃÁÃ6䇵«Y"Ðõ’ u¦4}"Ž _µ1´¼òÂÆ~nõâÕtßp K1J@õ¥Ê¿�Mø9¸®Ì€‰ôy9U[äŽ^)vì»sVìÈkÉ O¯~ 1EüÀÞ3rAp0| dÒk4-ß"òOé;Þ—½ÒþÐGå¶©Z†’gž8ð3Öå‚9ÀðZKÍ­tbÔÎc†=btïY*Žîx™ï…˜§-¥/ŸdŒú:jù ºÇUÃÖAp ¼SæÜÈ¥š,ãroÒÑ’ݧ°‹{âW—AÝÂqÞ¦Ãak©©¼UQân;Ç}` ä-U#SLˆl˜Ã·H8o£î=¢¸·¸}’pq°•o¤·ŒÜ<‹¨ù`KRI˜8[õ ï¥ãe;¿g¸Ð"|þLn)`¯&ˆäòîÓ+µGtŽ/ÕûÕòzÇ/ ^–reTï<ó¥ç=óf«51zK÷+1e|˜9摎@ÆkëåÁÇýd¶{/^è·Œä3NuÑ30_l ‡0’ƒ³s÷;è {ë¶­þ�FhC‹/5üe‹Oä@°Ï¬dø8z¿P°‰Y"kŠ~Xž;ÎFW#´#OÄò\6Ä\ú{ ˆQacÏ s…m«žLw,ò\=öG¾‹ùö¦¸sËŽƒÑꔳ¦mÅjë¡aÛb)d¸9h¿A¶RF-¬Žî…¹ãìœ|VU®µf¶ŠVµb~÷Ãß›b…… m5@ XÓª!=8‡×žïÈÐ6û­ÍÆQßqU‹$ÚšiÃ�¹(0¥ö ä³ÿlj["ºŒI¶y )·¼èˆ,-›ˆ¶|G˜G¯6+’ßÝ)Óò˜™_¤0¼Æìc•HîO!ég°>ŠðQ䙇¯礗!#¤Ê‚– –-¥pâÑm�æË¦Säc9lvo@äuÝk!ÂÓ•c‹Ñ{ä=]QhâÃÅ¡Êô莻tg5YSdŠ«.Œ+û+mñ*ÈGt#æÐd±ÅðJ(Wõh\“N^z_fWöK{A9ð˜w åÉËóc¤â¢3XÞ«aƒõôÎFqÇ0¼J®|50¦kè“}þ˜‡9%†ÜλƒˆßZ’!<,!]öØ+Ø¥‰^œy*¾N;ØæÊxC\¯y‹¬ùrÛÕåçˆ/§§Q9ÞÓfý(�ÓG_㥓ùópAV|P'󊫊'ô £èÅ Pé°Sµ?„ôï“©}Gl³°%(£dÑJ‘º7ÇÙÚS·žY :¿Œ‹ìj~oŒâèÂæ8¡îPv*ZG¦ê{nðÁµ¾Ê> ×öÔj�jéo-HÓà±Oa+ÎÞ®1>’s'œ=ÒÁ½1»várty2 ’ÓAþ,tŹMWoíud“¸e>Íôs‡wt[â¬Ý¯8++ËEŠ9/ÚHD=Ú’Øc豜¬F£©)SbxÖááqîƒoó€Ò©u›,33"^ÌœÇö0sšU¿ÅpO§¬³¶Îc ü%¦BÁºð:å£xù 7ڵ˸_Í<Ó"idïT-ªÏäAAšÛÜL&{Þ{¾U;öÆ?ÅäŸa;Ž=g£Ø¡ÍߢÁ•)odÈéc`PÛÂêÍà9™ìW'I Pær>GïÚtI»¬–qšåÀßëÙAQ«J ï»»¢�f,ÀÑä+F‰n¬0™ ¼üòbgMÅÛÑú¬â&&{|HK"_w³KžsCAb@ÁÑ�f—ÌCD\„£{‹/Ø‚L$"…¦Á£XnFˆ_A_Yéxn(w⥠·4ΞÁê¡×åMm×A�92óŽ@EF„¼hl?oå1%íçL´a#wF^ÔlàßÏ6÷lìÝL$F {0²"èãK—¸ƒ+q.ˆ¸™Š‡é€¼-嘉�ÃMÆ0d)«Ž5ïÛ›ü3vç¢Äñ%³b�P®V÷zWÍØ¯ìÄ( ? é×qûeT1vݼ|Üûš^tø‹n%‰í XJ‹¼«l°JX|vùHMGÕÅ`CÙ­¤z$b}U3w°<1°%ŸÉ³Sdc ¼ÔÙœ.VbnzïÁQO•`œu\Jz(휒PÃ; ˜ÛË1°ã6�;Öòç‘RZÖ"¶3ïTO"N´=´X:ÐJ¹’¥õÎ!¨òlPÅ×ì:d<5ïÖkÀc>`7» ³Wëшøf„±q…“ß4=O:Xý%¨(‡Àðé^zh²ÌÎŒÃù€Ò sƒI×ÈL2—ß`F•ðP‰¹r€ô‚<®êGõäX3~ðø à\¾a-wM£ùàÒfíz¯Ž ©ãÁZÖCaÂ¥ØÕ ¹l‹(€èˆé™2ðë•Dó–fÙ¥rEÃÇ;ýúA½adU¼Y3Á½i1ˆ&èòBo5û(¨_Sâ™Öΰ±æˆÉs©§9þ•ž¶Ú¨³šXÍ2kSÀÈ<ÀÕFvÍb²°<­"Á¢ñ[“×ÏžS-ÇÛ,Ó@EÒõM•­à‘8©×’ýହØÖŽ5ÞQ<zM/ÏÛö$zbêpÈá,"õÌ;çIÅÍîK‰¬@'ÃÎóÞØ‰>–ÐyÇ?%ÅÎO�¯\Àe+dÕ<œk *ß³]ãÈpšb;:šçîȰPØu�ƒ^sâ>O$ïSRß6c!ü9õí6ÌhM¼u8«ŒéÄØ“³-@¤<ÕÑ|ÕgƒZ Ž‘èA©ltQ,ÕmŽ"»뼚hŸ‹îÈe°½æ†¨YÔP nÂP‹SIÕkcÔ{Ý\ʘèWクԼDMž¢êGH{'­Ö‡þÔÁI…E<ÚqŒë®÷1Öë/hMy‚,D!3Ù·h_ÒñE¼Ä[½{3øD°÷­µeŠÂK�,róô°$Opi&Y„$ºÂ4©}M Q%’ïqU6Œjb«Ûp=Ü£«ºèg¿DÕãÍk›‚ðæUC‚OW»À£Ÿ(À¬gª˜Ãu·³Á·ð¤;mŽ:Ó·¨ð3”[[cûø v˜:Îó{1ÀOtVá™”?0Ø{þ¬™¹ì‰Iáµ%º†¾ç’\®ün3YB2“îIHÚh) ‹òì2Ve¿Çíɼ;:2!šáê¬Ú$d%»!@s¥›]##š‹¯Â@ÕkÑ^{ÌÑm>Î:d|¤íþn”’Õ¹¡Ù‚Ž^2zu‘-á=c»,¥6Ûd¯þƒäžM–¾F¾­5ª“*Ë’4?á§ó¸Ûvé••‡Ã‘z©×)eÍŠY =ö[|%/¼;äÀÈŸB[ËHo½´š÷µ#ì_²ÊôÉÊêjÉW Àu']MíOâµ$œ¿š÷"1Ek%Du‘·ÕaQ¾¦÷*‘î [ϧ¬>e•šïÞMK$³c®ä½ð±WFBÛ'±ì±/¡msWI×jÂÃön‚�í^÷¬jÁ{ð”zvnXh…Wóµ%8Ò`·±• y“ˆ"À–’M5Et¦Í¥ø± E\r²`l0ªÎ]¢ß%˺˜5¤kk=½Ežò¥ž‰é«t©™é^HK_9Ç3¤ñ[}ŠÂÃCÔŽXÃqÎð˜‹yæ)ÆÃ’ àHæ¥RΩ !Žj@Fé§7¥ænRÜŽ Âùàı¯¶é%>x…j˜XD!èWÈi¯²%÷§_åÖ;§È Q‹‡zÖ…f;¯#Œ°\0Kb„¢n[‡2Wî1B¡(½‹±:œ2®+ÙüÖgPŸ¸L|½µQ6+‚¥ ¦ò ’9ØE KÖRúœqÄ@jšá•csgÔp•/…`Aµ IR¼­ApVw½•µÃE»yËùp�Úcýú^²rçNav‰øòˆÒ!s•»î•)0[82NH=BcÇÍL«DÙv‚*iäÔ}°¹-I6 7× ÇRœÂHøÔAë5Iõ@fr ? “)Q½¨7ÈvoAßkJšTÝNáGK¬/¤¹•„¼n˜6 ïõDU€?@*¡zÕ¢ó¼ÛSK¢²�_¸oÖ -&$6-¬ý’Ö5^Ûaœv äàS*z„íQ€õœwr€Ò§f+&¼óòpi+õ©õ8j ïzúw+äÏÈNãì1´âÑ„ö­Cn0‘Jb «4—bfòètÇi%奦w3\#œ¬–‚„Ùå mlO2K¤Çð¯âÚ{8X²f‚™cx#SXl6¨R Uçáðh9T¡ó¼ÈâVˆb0}ʵ!"vTVx�»«_=Fãî‹ âÄ'®§•NnòÒs´ÌQ„ê?”ób9ÔÄYÎÒY¸g6>®  ë^Q±Ñ©ù ˜Ë-iêDÞŽ}îçTÚ çëwzËÍZMeÜTÎyeðø‰R0¼‹seqCÚ¸\î䟾åÏW`¶ð.ÚÓt«ñ·ÜÞì ½�‚©­·iãm“ÏwÌPü),ÈK;ÃÁˆ÷)®÷Þe1&ÌÝ®3Øm‰ZÏ›_òd)<4zÌgéi)¤/)‘ ·¯ed¬V²a\&!„æZ%Âæ=nÂvˆ·|{C¡X]ñr˜s¡{Òd<{_µÇÚðÊ  Ô¤Œª——@]û*ø¢¿{ÃI•ÓïNl¡¡Ú3ŽŠ’ôFÇ[�ü2³Ln ó(½ÚŽ´žçËyíŒ(*šnhÃ%Ä©~ç�Ä+"`‡•ü):¼J^NÛ ñ£»\iºJ‘JIn²†¤3¬1Ä¡[´ˆ¦œb,�–縱+ýr޲¢áR ˆÃ¤ï—¼@ĵºÌãø ¡Ž>Ž~±=Ã-L""¼Ì7˜à(C»µ¢þZžy'õÌí§¼ä3Æ·o˜f=evëåòy+Íİ¢ ÔO ¸p(,²ú9®ènÂQè…³Å\8äi¬qG 6>®]‡\drTêÅJ;Mg{jQ™=ì°õV‘:" Þ(`^¾‹$é)Pq—pmÞ6€f7D¯ÂGÇ«“¸á>WŒÙ&c¬Œûd“ìÑ9÷]Tg5¡ªKÝ˜Ç ‡!Ð+tó$÷Hˆ.6mÜÂò!PòÜC6u¼‘´v$€|ú=“Eå­ur7›”ïyךð›j}ÕµW­Oa;è”'vãgsLßãA‚ 4QÜi5 DÅÙkAAÒ~YG’—j:D Yã~ìÜpÁðxdøDû}7Gýôøäé•=ŠÄk"FbËxQiXÝèDÃd4 ¥NŽ¡Mr¶ÒMGW÷ÞC9è²[51 ,|ñËÅSb–Xª·LQçþÓ `gÊjâ4›vÊr¿•cQ#¯™ya2eí“^Õþºïè=Ž70ÏC^˜›Ê¾( >ƒ£NpRã$Å÷©ÞC$3òñjj Û@ ÞQ@8•K“Ä·µOíR¬—k^</uµ±—1' ÛzÂÐu´«Ø«ZíG®oîDœÍ´ç¼í®Kñ‘§hÕ°¡{½$®:fç༧;é²úSb ƒ÷®CÆ4†±#‘`öqB Jû Õ#èVô¸å>œ£yïuŒÉ«F8)bƒ}KÌ?%vs9Ý1•Cœ ì­­Ò“˜{&F„ån´Ãcrçs6 J6¤ºDo©9ÎÂyŸˆ× $Õß–h%ì™R U4»Z<—g¹®�ƒ0nE€ nž>D­Íë”ßÙ™@‡kYA—=H§÷¬+âv…M[¶T¶cÜjZÔò(4²Øp;b¬xÀš p*?,‡¶Ç­éBeõ®š+ «QÊÙé±¥ú“g}ÜcÐݾG>P*,…û|K”¬êÉF<uŽÜeÄNÌšvÆXµ0êbI-TÀ"™ºç?}Ì^äùK;܃ï¹Fò¼[ÏÔÅ|no÷©UGl4ó‚äÑ@ØC-sa š¢–.\¨ O‘ÙgÈwe'Œ†GxNz¢ûbY”BKÉ›{5:ŽÖÄo0ÚÉøè÷Mæªô;D^ë„Pɶ¡·ü¦_%ÞATmp±¸Ë“Ç]ò(1SžÚ6³£a…ô{óèx ›Ë²ŒAI­ÁTÂõe@{ÄSHc%<™¾ ©-Œ"žÂ.m¸ÊÀaõ@¡(¯qRîL¬,Ñ|y—;ï…Ò„Žnù“=Ft/^„Ã<GLäCÑÚ²$÷Ì•à­ÁgXJ/ÓZsp‰�ŠÇhÜ“s‡ Ý‰qî5›èA‰Ã´‡8ܤØÃ¿~ɬŸ"Ñ�”âZÌI¾’òT ¶l€Çð2‚Ýh9=“íÖ7sår"‰ ¥5¯Fò™³:�ò÷šÂ¿ã~f)™è0XªÆàÓ¬ ÷ °×’(Q<ë‚‚é…hx§vŠ¢ëp3äÍhê,¨oØ&mqâ-DΘA©§.8öuB¼ºµr®{œâ>xQd©â¯Ÿ½|IÇ»px¢ï[Ѓ”,¼2»é|Q r`•®õWÖUìÕ»&’võ'¤›òL+0¡šzY‰Z%jIbÂWüáÜk:f˜7Þ³ku˜ôžÐÛíV¿£Ü“:�ŽuKÄÖŒYÌJ‰ÐÎÎÆîg{âžìOïżu*uî— TPâ]^5²sÇãJçš=AÙëC˜ŸM³v¹Q‡§MøtŸj3g„§195Lmž Ó ‹lÊê®+BX¢Ö‘Jó@vEün+7°úShñüŸ•j&\•ŒZ¨­S£5X&2Ù†^óò¬1³zïZD¼Äº'àÔoŒdÇç!tIõœ4?<³Ë.œ|šRQÔÕ/6ç̵zÜñØ0C.ÑæŒOA#7áÎb$Y…ïÚ!§4€²-¹<ä§ áHx›‘µÔƒÕUudm¯óXͤ®°ã…‡mžè]¾É«u}OÕ¥-™@ÛÒ€u_¶£ZÄiðä­Æ1pïÛJˆ!\`E ÀºV•2z�)Ïà2Êr|ü¿â—{ˆ.(koö+н/l"‘š™¶ÉA™£&'{’n¼ÌI¼Øäˆ¹ÒGÈVÈ_¢®îmäúÞjÝ}íž»…*ˆÉtG=ݳ™Ô äé4Œ½öφÃçà}‡§v+Üî¡ÈÊ5ÚÅÏ•ªÔRE—'ÜC{õnÞ¤q˜8Äõ\¨ª)Œ®(¶±ŒÃ‹ÆÞÙ=¶7h,“)Ìø¬.C¡¨{_¾#yhZõkp=TÞc*ŸZLdéGˆR¯€ž‹&¥ó´Ë¨9Õ¾zuo¿Bóäùæò&?¦ JZ¦„#µcì&5Œ-z2åÊòiò1ïfÄ£×1vhªùª �6ûµÅËîVï-Q•a%ô'o¸5rA<‘ÙÍ+ð9î¢q]C=}5F>»ñZs³,su—SÉö·ØÄÃ}åêB )WªO,g>2ŸskAÂè^=’g丩â(–¼qlAƒäYàÁ°Ë¦Æ·ØàsØì þ‹ŠààóÆñ®’ySXò<]Þ›àKqVxknÇAu„ˆ–-ëìÄ,BÆÈ„B”%ëâ,ФP6È[»g.Eœo\LS'M_úŽŽÍ ±”'#ôž‰6z¦Ãbæ¼Á‹&’˜]4Ä¥n¿dÔ¸²î×Ë^¬t¾¬¹áeëìÓ›ï,¥âQTñiUM‰Ê²š6¶¬nñ %œk&ñÎð€†½gdñŠç’41'ìŒÊB¨ÞMaøñ o=¬‡úHtùÉúx ¶ˆL{¼Œ‚ÃØ»,3×üÓ:† ØÆ1w²è£ß»ÍàˆzNÉ)›zk‘4e•k+îe“À3.ˆtSMüX@(-«¶¶Ì€"î¦Uò§Üð{÷ÏÙo#µî=ifÖ^kº³Yw=ÄÓt{pf¢ 1ÌÒèqœÃI¬aY“.˜Žî˜ÐÞ×áEm@¢¯©åöõ«8„¹"z>0ÐEKîvó$<q^ö¤‡Å{Iw-wA†Ñ!}”ùhZü©½.ɨS©91 ”ó™ ÉDª»¼êUp²zU6Ç3©G‰ÛëB³:€Çy$Ò—FÉñ¥G98$9(ˆz½tÈUD‹[ w9�ìŽæ]šŠ6l{#¯0 òåÃÁôá™Þ§;Uù²¬rD…ÇMï1¢G¯76ó"Óm®¦÷ ¥b+ ýàBl…öÁEùf<™fA®g$–ó”3ø¼˜{ÐŒÃò,÷æ&̈́㠉“EÉÛ…·ªŸ‚£ÏÐhΘȩcž»j4‹/¿ RèÚÀ?‚«qù6µ_Á6RÔ“£GÙ q(t­Äo±v=³¼Gt½žëâte4ÈkºI?lÈ3ߥ§ä´Ø†.0ÝUÊœòwžo×Óº;¹q×ß2PBl:ÁËÛ>x¶jçëC*ˆ¤ )áÉŽûhP½ ×Ó0[è‘ľ%·ÂRf¡59+ª·"à⊾JZ/áò<¤º7�Qà勹E²ÍåÁó@Ë+y¾“5‰@€ˆ·Œ¯ò OV(p} /’¨‹¸1{í1 ¥YÂzÌk@Uó¹ Â_’3‹Ý>Fdt¬3î÷ðÊ" <àÅ’Ïñå̾ûzœ ûub œ rM¤¾“áw™•Àñ)9þØM*èA/¤—D«¸<8Ò4À>t¡KMhÏÜ Io(Ðhš<áJPò7àÎr@0)C§ƒò*ØÙ00Ñ€-*õ^N;êmWÁE¿§e.uB`¡þpÅݼŒ[|x« ¬÷™âÍf-Ê,cÌUÚ£ž-ö‰6wdLµàÅ`UE6mÇÞõIŒL ’zv7fù¸-aM¼ÙFƒäÄ\ÍCÙó­`«žøÔëEØk°iÇÈ5™‚q{wÎ3“å!ü^ÖÀ"ÍÅŠé¸ä„#h±Rˆ“Ö›Ǣ(¢ ûêU9½bî—·%kU0¿DÇ£/d‹'ß:?ƒ{¨KíY§bI:ïF_‹±”˜S)þ)ÓÓèöÏ[×bà…ž†ÊëvøÝû¾<ëÆ”¸½ÊxmRéªÍ0-]Ðp¾ÁŠþü…èŒ æƒSô—WË“g äƒÛ}uÑÚKõ‚’ï ¥è­$s˜Ø½±Ù•¹¡Çˆ– ªžÏ°BLuétæyó‰ùà <x #›Gó,’”`ZzÌ7³8¹�Ñ0ÊÖ|0fÎ`â[xž™ mµ]ൌÏS­XKK—:æ‹ny5noæF!Q`&ÏÇn+ó±½7JQòat�`Ä¥a•œ7n+ o-‰hmvÛ¢% u\Œ.°t±»­w„õÚÕn^lo­Ö98­çÏ<çè¾yKm÷ÞûÞò"> ãèÔDÞ‘tUTãdt ½Ëóa;½Þ&J€Ý¥¬­ü–Ýçø –†×Ûaeš¶cEõNké3£ØDuOÝÙ†k ÷RRŸtâ[o³§£"ˆJ N í庀Ç3;ÕŠ @».[s—þ\ŸWîê]ìx ”OÆcàvf)îäÜ™ƒ’Wí£Ê„ì%CRYÀƒVüÄ3Æœ@OªlÖ¤¤¡ÒåÕ#¯rÀ5À˜~·™#Qmˆô„ Þ0o²²(Ç•µqSŽxŠVú-¿ZžNv'å›ÂyWL.à/)8¦ß÷èPŸ¯•m@RîX>,@r!j:¯;Ñ´[µÐxD½Î‘1OÁøg“çæ#Ré€Û{ÕZƒ–„~°ú<ºhü‰Tí:d…ÇÝæÓYæ§;5ÒîïùíÌËœ7ŸÂýÌuoQg§‘Ȩ2™†<ˆ°fô_&Vzߢ. N®›LBÃ(·Dó ôkM·ˆè0¯Ÿg;:cÑ$¥W>êÐ}gàú²ß[½xŒ‚k¯Í)°N¦B8VCÔê4û4˜ª*‡ù<žÖ‰ãkPTæÁdA�ŽâÁQ7ÊÅ›ÐÉÚï@¢°ÀT¦ÍYJ:ß\%8`uÎ\¢‰·—>Ûì«÷Þ+—|ïŒ=@Át,ß9«¸¹«ÆéÞ›-ñoN0Ñ‘¥{1˜–c¼pP<\r}JTèæ-ÌûÒŸ/ KЦcëÕýô¼n¹¾=©t{ÉheÜQX¯OÝŒçáA98¤Ì; \µãŠóî̾yôÞ5B¥xq>ƒ©çõ)=}Ÿ­¶¥Ùßî‘ûö’uï% #YE›WËàjËÆê`‹gW8`ö —WT¢1ï ó=¨*w§¥'ͪÓ,Nc¨¡–o1Dl®¼Ù}N‰(�ä‚ó†ú¥+¾AȰŒ¹;뉧—OH”g†bÊ/–ß”Âd2©¿0Ú¤ŒGº½u)Äq¥vÞ•IyºóêýÉʼn³ÑPßmËËèJkSë”à ‰×YöžŸÀ¿ N {†½ÆzÑî:›˜õºòÇɵåÒvÙ)âv>%-ði"vڠƽ¢Ó¼i¿iB#…w,ý´Ãæ§ïE1k½¦†SiÀ<>ȧ}XJ:2uX´gǯ;YQn®Î&£'ß$Ñr\0 ;~ϳö9\,ÅŠOÍÛÄò>Qñ]=‰ ¤k ¸w >ÑSï%ŽT¼r_ÇË~7'ýâ=:ä Äq×§¡"ˆ›wJÏý0ŸEÙb¢(,†ÏtwŸ�J@ð#¹³Ã.¤§anúÀm´²I H ör½·åˆJ°%²³]OÊ­S©ôêDøÍ€(ìtš#¼áŠÇ3E·¹í‘)«A pN””I· ,0&kµ¨w$¤ÓúØh�ïÑ¡{Ö¤n¤žÜÀ`¯˜HÇ]ªäAÔ8è/(ŠjÀ8f;¢™wòdSÓ‹  @»Þà°å áì‹}åÏ~ɯ³ß#";„~Á2š<F5hÞÅ{":ìC`jë(·ß âð#Ó 8ršU~Kš÷ÝvýsÌÿ“Hè‰éªl' ÈqÈA_ö8kF ⎘ú ¢!á2±Xå;y;d‡GaÃv9o#ᤎnjݠ¨E4••ÖE‡X%ŒšòIsµ …=«*aªÐwØnK=Gý*d<s¢Ú¯.ÕWiˆÍ]áÖ5Ž·².쬳ç€4%ϽË1}Ba±qy¹½3ØÊåÃÚÇæO^b•ZÚÃ6ËÖÒâ ¹w@¥o²å±+òæ ˜{´€€‡(™‘Uq§éÍlLV È[¬ÑzÕÓ ù^Œ[§yƒ½&Î1wÛ§°Þo {bw÷—�A–¯œw}Âí 9ÐQ¬¬‡VA@?æçA!áÑOf¨AOjD¼´Ú\³ÏDõ|ûŸœHç^š©í½ Reb6™¾}þÚüŒÑâ˜ñ•Å*³iy¶:Ÿ¤à¡ð«1Š*x@'Ò5¾~%Û¸©U« kQÐW+Ÿ Ò–‹áé…ô*«ÃÇq*¶Po3Ž`‹à¯fqtL\‚ =Tòs#Oäš³|õŠéÚ3 äu?w̵KŒ¼TimÞÅâœe Ê{òÒ3Ë·ÑI]ežNðáZËR™#wP è »ëñ<¬ JuÌAˆö'¯Êó<ôiérD±—âÁáwêD9áØ¶ºx\åZÆžö ·YJ0D�wNÊhKª[\šQà‰MzÓÖrZ?%¨û”Û®¤ï±¾÷‚0oM‡.ßZï\ǼÐ<œ¶5O@ã±°½s8ªbê~“'ÊÜoµz¾%Ÿ£ºâNïÓKÉA[¼ÃÙ\ð7Ûâpa©æ.sëü*æ²1LíQo,© R§àéœäɃ–ͺxÙ›œÌÍòžKš?½òwœmM¯¤èêˆ €z ™«l±ß €XÝà¾7ÅÜÖS¡‘Kþ ý@â+PO¼€˜( ŸÚ â£4%Ël ¬õãåzÆíXç È –‰Ù=!í˜xIIsûtÒO/CÔ-R¤o#ÖmŠÈæ3«äz¯{¼Ùä+b^Њð“iB1‹¢ÄØÊm8/*nùP4.é­tò2ÓÀ£G”^ŽâÃÛªé�HazŒws rÐÑòS„Oly˜¯ˆ&¶!½‡ ÏE ­-ß"³?\Èx¯dk/¼ »GL”©‡KÍTc¿Dð}×ð»YNÝ·§¢à›j´Ï)¡[÷ø½xØ×È+OŽ+Úrd·j©�õQ=×Îs‘¦6>ñÆ}Ë8éK£<¡‹rã/„s¥‰1 GA Ç2o2; N•s5³žÆÀ ¦<4°yÀoSs$—%BóÀüƒð*Ïž³kt’U xÙ®ã"y£¡Nsö-ƒ¿"\x} Š¶Û‡¥ž½”yÒ7÷†÷‚FD* <ã§ú”Žpú#Å!€1|ÆcÏýø‘=ÔRmd›'rĆ]íºðP²ÜsÛNhYyÞézŠù@ŸÔ¡©®)ÌÊÏYxåÚ¸ €|°œ22Ãtø\ªs�°¯Å-¾XW<ˆ|˜NÀ½ADÀg¡¯ÞImÓ· ‘>ó 9e•QJ-s‰Õ ï“Z]‚ˆÑ€Gí)O`G·DÒ™ f|£šŸ ëNg.-Ò6úº³ÍYbq»m?¦‡³ë7âŠa"4MP»)pïI‚%û¡©'ÇRÑÈÌìœ Ξ" íG˜LNèx‚z‘óTQØÍS(Vð<sñ¡ƒ·WËX)t6iUøËFx¬{æðH[žm¼´?Àìº~ÉN²¹ðN2�õèÊëUvŒõÚpYóE+>ãØLÞv~ QXY ©8Ë]¨õAÅ™ºîÈEÙ>ìë±ÐÛ×$ÚÆèÚDŠw$ò¶&V.~Þ? «2&SÇa§U0J�K)ž(Ç«Izó4¯ã'8¡$”.ß…>2¦€a*ÞÜ;½˜û"}&r½ŽÉâb°Âyý­<t檀À%‡#ñ¾Â÷Ø­@ö1vaT¦WB‹gm ƒ/ú{ÓÅj^™ŽYŽ.AH-·¡§Ä£ââåº O‘&I|ªëc©ÀFÔEUœ—òzL##ŽŒeWdr©‰†ÃjB”åÄûyª]Àbg^Ÿ¢ ªŠý™$H¡OêñÃÑ ¸Æžb¡b¸Ü'ÃÏ)Þþ1Å$4‹Ï•K®PÄÌ6£Ñ¬—TF$q•,ÂÝã7S|âÌ ' .Ëfe’YÎ68GåùJTïAU`‰Ù¹áæ?Q¾KЊ´^zmŒ–h4¿÷ƒû”ÍÃ+¡kb¬”õ¶f(K�vÕž×™¯«N؈°¼2¼FZµ„X {Á¨cønÁû[ŠŸ#Š¢Ña¦.î[Eƒ¼Ê ¹íˆ:¢Wj¯mÆehVO´\ Ópø?7B϶²` ®%£})¡ž{艤4ª¢ƒ`°Øí“¬‹çS#-Õ©Åa5áDr^ãA…òb§dað"½ÄžÃ·g°âŽWò& Æ´_ ¼Ö'•ÛÆ§ŽR‰3Q”½x"’úÜ™“Xä¹Û±ìª6æ.I><ìžý*läà,öÉCaÑâ - >Ž,Ë’#Ÿ{¬Õa\ÁÕÒ…›Xc ùðu½²ÄlÎS?±8èhc|kgt™âu?tTò /—Ä…îõqÈÃó„d³çègq+ðL—HÆ£”öq-“ȆFW3¿Üƒ‡A0›´Í§Y?}QÕ·'b®–Pú!:‡gGÇæaâc¾¬×=áúL¨”d3Þ3Æ3™çI6ðlÔäÙá›»L‘KYг<T—Íëwehè›Ãðä1ÔTŠ—:4T¾‹ê’j¸†÷2‚*^½îáÕÍ*™ª¬€7J `Bý– p̸ú^ã«Çf“¼wçô »è°˜÷iÄ*éMnÜk›ÚR–j“wÙ5>/j+ùˆûaw]ìB#¾Õ0¶ k¨Ãq‰ƒ6µE \_Ž&%Å»Y ‚áʃ Pd×о•²e*¸'sœ™Átœ6R —nHIdxÇØk%ˆ…¿ä8o¸^¸yn-­]^©Û¤í-=êRÈ9i•³~ïõuHRÒ¶�@{š{x‚=€eã#û”ãû[x”ä¹³¼9†ås“Tß¹>~–¤é‹Yj#-Ï5Cb.Äœ<À©(•m±ï¡×ã XÈiw¼Ö\Gv÷í!ÌMìÈÅ|À>7hl~;†”û‚Àm¬§'üì©‹Y¨uaÖ3|¤¸Ëµ9|o Ñ™bxkïU?O7iŒJSÕIØÚt€,:ؘy:]Œo�Ðßžá&qà˜B‡€!L½4¸ ¤»?$ðbÚ„zÑ]­<úùœ?Õ=#ƵlQ;؈U¢­rí"6!À€TlÕ~‡÷–<º˜œry3[Qh‡ÞPU®¤©8 ¥p¿(+ ¹•wS´`¯´²U ò›ðñQˆ9Æ\tÌ€ À«…±Ýñ–¤²Þ'6â¢ÈTØw{›5Çàe0¤ËsI~Í®pß¹Q>Úirº«€ CôàÌ.|r¬ Ë]C#°=Tlu�€.­‚ÃFÚ0lÆÛ¸Ïaš=*(`³µY-?‘HÏ7õìAïê8ƒPÌ`(š�NãKdrõá³…4-Î2èþy™cÕA«XVó\È X \âx<áÚæWWjRÉ©¬áH§Œv<Õc(Ò))~ÏŒ­I/<2!–A»Èë ûô<òØžlð õî”Ç=Ô)Ðñ Ÿ¨=&yËâŒÖ` VGÛùØÓ XíòÚ#ňȯå¶o„Ë÷B|a¼ì¤+‚8' Ä·AÍ�ºíi#Y*îþ<ñ½ÁSRu_õˆ’ëžg—YO6´5\£³ösÑCŸ+r÷+‡î8j!}a-ÐBÃïü¨Ÿ£L@‘§fâ­0Juù:îhgO#„RÙÓ³wþd·\ÃLú ¬Ò—-îòƒåëõGÉžyµ ˜\Ó-Gk³ÂûB„D*ÀÛƒG$u’Z´ÇÝœ²šYN4öì9DOÆúôÔ̪Øh´½|l‘5ô j±óÚ‚ôA¢s)j<x-Å›9/µæuƒîɤ_×»¤Ô'-©ÎaÁ�C-X}�K…šÚ/Ðð1dÎ1’©(”ß1²ÄªîXÛWqî¸Ù£ÔÑùy"ß |[dˆ’Ø×2¨c7ñB^³0íe'u pÑ�µÞNršÝC &uq÷Ÿ92Ay̼ )‡3ºò‘ìJ°_gêRCªÊ¥#*à{oÄ^ä%º©NÉÁ#m)ç b/s¥oŸTÿôÉÐxÏM^ÀQfTà›Ú£U—×!ç£uë µ>Kòš´h+öÍF«wäÜ‹}»QØä¡v'nìϹZUhQŠ´g§2•DKd6ŸâY=éP-“É`¼{+¡”Í{70349ý5ó±môÔ*i‰=I(PЗž>¢+œy4Ä31É7g©ì‘jŠÉ|ùèÒgj|QQ¢ƒ¼„M0š6¡ð½^Ê;£°‹Žx±ïN½ †9ÎM�{]ÊŒŽ©uÒs¨— =d¼À/q7ÇšMë„· ”À¹­ñ>>_ãççÖìL)Ïö¨jÅ"²vúdñØhÓ!ˆù�ô§Wìê° ˜?õ€,vˆ­ î~2wG×INzOœIžj‡saë«MöêÜΠ쀀ǴÝçñ)KûoŒPŸ(s¾—Ôæ…ô6·O\L²ˆ› œ¹IÝdF žæf4?§M)^m'­(“››úŒ4á@LL§‡CÇ‘ øJE°õ!¸¹è€@!¬æ³rÊð¼òè]—xÓkq{ìt}ƒd‡åÀù*âé½ìÈÇæ‹«  Ù#…—Ÿ@ÓÄP<,èÊš˜ôMd|‚úš³´º†û=šWà–-–Mä2¢ïP'ߎ¬‚í„…áÓ»‚=>žbð+~4'[ôò9‰^›2>L2w|í4:ÊÏÅLž¸A.§s1d%ʃ[´ð³=ˆe–t•¤\ˆE¸ïìù•§à½gKÈéW?ýÒ’Û£ÏV4»Ñ³•½úâÝÄ™ˆš5÷À+¾”à®Þ‚hóv]¸»{"5QåS˜þ9èh¹ÂpIâ«^eøÄ^½aë4·ÏÔO_ëóB,ΪljNòÍ€¸9xÄÌú�h•·é1 Œ—º¾*¼kK<ߎ\™:£´‰ÖãŒõ*k"ߤ@0ÍÛ›´?ÍïCXÍ]EdC¼ÓGDˆnS´w›/F$F1jHSQ«nÒ™E@® & ^£Ã`³T °/ªúÅ…>²€z+rÑYpK5CÁ2�¸«#+Kž˜; LÝ츉ßk‚[“Ø+f|ØëAâvëè¶rÕbæZ¶^à¡H¬s <d{Ukíj|¨ 5‚#wìz/-K}ç$Ž]¶ÑêÖÐø÷ª¼=#é=}GXȼµ•0wùMoöÈÁ›¾RÂ8»‡þ¦A-F¥ `Î/èöU°'¾ÓOi}J3!Ý#IЙޛíð@)ÏzÃH/¯î‘’­ÇÛ(Q*rHz}Ù‡/a&Wž¡®$€S3‡ã)° ñÈ“]Ü#r¾òR6ÏÀ×2ñ*YQ“ÓÝZ’´MÞ}œ`$ƒÊüHý‰¼ÐñDo E|Â(È /ñ쀑®ÌWÁŒùÛfºqízfˆ†Gè!›lQ½=áÆ÷� l¶ž¨søÊL¤õ…­w¨ò3¿zHçü^cìõyS¥<&9L²¥RJñS½Ö©7Ôšä ¯�MƵ,À·š"ºu›‹6%»ñm6§>ªâ8aAÈ 3h&ϳŸ¾X9ÉXbùêxh #ùÝáB>P |®C2ÒùfeJ–erí!è[)7ËÄŠø!Nø~Š[Ö^is“0#h‹r½Nb?*]5YWÇå—ìáñÌ¥&g%Th^CJ»Ô<y7¸q79Øì('À¾±÷˜2[šûÝúƒn6ès‡T@4óª<ALÁLÚRçx™±¤“‘“št—wv•OL=*SÌŠW@nΤ-!õÎ9'‹`̽J¼–8ìqÙV¢WE­µ•ªëî4êl ŽnO}-wp/`k ×I,¤§ëD†Eû\æóñî©"í7%Ï®A÷–.\`gH]ò©b× ÄC•y¥¼GRn:<wš&™Cø¬æ2§¿›}OnŸ=C, ?[ú)Ïc„uÁ¶*åNTÏ\Û~4{§ýzø¤6ÚëE¹Ô9c Ä\'µ»­‘ÇSsb› ]|è[žŸcs?²è.y ·µ –Ž!0 ÷Jõž?'ÍÛµ'z�†)¸XÕ"bPÒmÛzÁV'µ7c­•º¡ÞGèIůFú‚,ËŸ.{>¨G“ØXfvÔ4‘Óˆ9–Q�+Ùœ£ Û½2Û:ƒ’4çwV—°¨]„‘óò„^n²1¿LÕDz2v *ý·ª—©éA<Óa°^ÚvjìÕXÛÏÔd›R[wx¥ìá ?61°•EO‚ò&xêw!ø®±½èqšÞoHÊö¢Àt[æ€16 L°ç/eøøÊÛ¥DWVÎokeñJbÔ„C&h§'4Á‰!ÕëY`Ú ,ƒ\üÙÜo@"ÞµŽå·î{ã)p’Ĩ¦ — C彨ÔjHâЖf Š3®âÛ?ñs JÛñg/º[´ ç*ÅcÈbRy†«»Ž#¨åñ‹u{±±iOS¡€í‘²öÓw»ÄœÝBáø4¨ô1ÄÎÍQfÒ6¯O‚½áÃ!FA<1уÒÝ^Ôt¿e†D¸ì%µº«k^†€¶›HÅcå“Mw\£÷ÎáNÄFö,1ßZy\_:ꜼÁÑ]e[ } wƒRŠ¡5cSdТõŒŸ ?ߎ\o+v(‹7ŸäÈbÅœâHÃñš-Þ4‹–²;§ÂFWÅ5/@Ó1MÍÓP w> h5£e–S´jæCÅÑÓðGB»H«T �ÙBŒ Õ*µD<>7ñZ�^"`^ÜhÃïÑÈ/Ig$åÕÅK`KTÙ–^ÞqÅg >}ËõÜÑ jw/™ Ÿ0qIø™â,•r ’öñ~J”Þ§Dõ–aúz“)Ö)K`™JN`‹¤Ý¸eˆA\!%·w•ôe²æ³GDýÊ‹ó`Xœa§<Ìû­ÀQ_C¡Ü4ø\4C?ÆVöÅ$)ÁÎñõ²ó¨+†“88‚Û¾ãQެ~$Rìê×Of÷ÙRÖƒ£Ì6–9œÆœë½~ã¬åòz7²�X]íÆ_Þ[Í2ƒ7h+õ³ÇlñÜÍڸ܊äé-È&²ÕÎ5h’…’=ˆH‘7égcDœÏ»Ž±l¶3q«½ð‰)/«1ª7–¡4öDlϱ(¼p—íœàgMuî˜Ú _²‹[¾—N-Ãl Ü™d«Ú~§?ïæÎ7Šƒ+ F{¸.Zäéh¼”wÔ/,d°O@vIy­2âQM?cÆKÃx$v47ù)R¦ïFjw¯9cãŠX8L¢ŸÎ<L¡™ÜÈq}à¥Á,᱊_5AÖ@"Xz¸wÒ!DW)aj¯} õö=\QE„RBÆÞîóÐj_A�sY1s߉Ė6zè C‹ø¼ƒv: ‘—ËJz^(YÖ”ÇÌõ€…ÝÀ¾ fyé~B$Øòtõ=~ÍcOÞ;â«à•¤¡Ã+yRo‘Õ:ŒY (0Þk/cÈáyæAÆ—ï]…y²67›¾¬ÝlkÑhÜÇÉB+eÍïÜ `vÁ$±_»44Gß#¬éV”‹½Ó®w«OàåöÊ1,n·NåDpTQAw‡ á\ÝËð’zZ  ûK¦H>­ˆ¦T…,ÅÆñüõeN§=ÇQ|Çs£'c^…®œ«Ž ÎÒÓŠi;¡¯˜§Lv¿Ûýû—89£ŸïÍRNà»:€EÏÒêwø9‹l Ñ<ѽãÚ‰w©1?5“aרpêœSu-¯"¹‡Ù‰YŠP QXü˜u€sÑOUÛÄxDúÝ cS¬v߬ò&ËAΉ»ô5$¿¤¢}3ô^è”y¬*£AïÙ³ðL¬êyboªòÁóÓWtΙӪ…Ïë%ô„ÐÓF²7ìwˆ]Rfž&´C>nøÃÃY9¦oò!I "§ß‹]â½ÌÓæ+h\UÃq´k~)tRãŒöÑ›eÓ{-*ÝéÄ`3±g:)eý¶lÁ–ɬïê˜Í…ÍÇbšTOSjµ öeÐönåÖÿÊ¥ÿüó¿þ§8þñoÿšü_éŸÊø÷ÿíŽT㌻“8#[ÚKÔ¦Ñ%MtÃ:œPß-‰K, N7>“vHE)Bâ<<¹x¸¼ñ€š³Eü�#&¤txÐÄÅ•§‡ôCÜŸÊøõ 98®ÛK¬”IM2¦ó[™nÖ¥]8Ê6Z ¥wI+9»Ý6£U,D¯Þ(²èµ®ƒ„•ƒ 1€vSEÄfÈG%Ÿ3c÷¯J2!ÈUòÆ›@“7Õ¦VB@L¤n†Ï2¤Ëëµÿùâ­÷h€hÇ$›‡nJ'ÆPOdÅkàk޳ž7&ɀܕ|O'Í.‚é“"爈ê^Û½÷¼1é`@Á›SLPÙ€¦îÁÑ©¡ó+¢!p ìûÓÛöíã~áÊ)\L$57Ö*•¦âõQÌwÅs³ŸÜÌ«Ws{¢å„Ãzï ²`ˆ±| ù)û¼~ʃïr2(É ëîÈCɱ>š«£Éóî4ͺ•µ*æ­÷ð±¢å;üÊ,߉¥qûæ~$þ#ý­[(˜Ö!š¾ŠÁ¥ ÍWoñºõj1)”c´ÒÞU£\,·`ÐΛN‚Ü”Bˆ"¶Ž}€7ïžSÛGAß½ð_¶Ø¯’?© ¤,ۜҤ·‹ƒ&Ù$Þ}t/b;æGì›ÐS<†b¢–ÇÞ‚•=06�Ï0îøFÇáÓªv°Õjv9¸Êºý*éÛ ôªì-ÅOž�;¸Îx»å¥Üíãk|ç•»Sk“À@Ùá¯cU=ܵôUéL—¢n½…5RxTÇ75C-Åσ`õ8b–äÝGQòi ˆaÈÝλ{?ÓÀ˜ÛèÖ 5hÊ×=h«Ýk ¯ñ–áz÷H�Mh‚ráuñ“›G+ìí\Tïüæ±Ö+‘nqo­@F¦ÃTñ+$êú(Kß§×å;zþIHš8r‡`k ±&`XR¤G¼Â6Š·h•‚¾ƒ@1zòrŒcÜT‚€«Êå êU),°KÞèê>æUÎL³5.¯]»YÑuûjGFß¾§šõÐe'JÙä§ST¯Ð±V8B‰°ÃÊ ãu÷'ªåGRK_‘ßݾÆí—Ò{p(ZLlkШ^A©§ãx‹gl袾¯Nûi»cˆÈ¹ô„ûç;³6[†í ßs}O\[È­ÄCU»; ‡êÆÇ«ZGoÅ#H¶p4ÓŠBGÆ6¨Q÷L&Só’›]ÉSS>ò¯âü³¸Üé¹ÙÞ'rø«¼“9 ¡ ·ÁÌ 5RcJ–JÍjtôòEàää™;ê±ità` ÛEc\Ï*\êl…ÓŒœ„ÁÙ[†£‚§ÆÏ“9^?ïòâÓF¤öqQ�í»õþU C"£m ¿çãéÈ Õ ½ ï $é\YˆA3˜vZžW¤öY\ÝãšœtB~/ZÞ©ß›q€Bé—•ã–cÉņiøÅ§£¤=%c"G¢cÇæzºï7‰òšì5Ïé8½“›ëâ©��b[´Dô¤«¼¦aˆô¥óóÂÀËjX„ rCBì8Ñ@¦]Ùתêõªr¯ù¾jÄOsá7ìQŒÖHå’[’J?mÀÔˆ5…D°È9}û^[½ó~½)ÂY¯ ûˆ®èÔUr€Ú½ èÄøA»¤0ú)Ý‹Àhå.ñ®>äÑñ·ÆóU%}úÌ%‘Û«nPw‹õ=ÄÔ80¢ßu¢¢³Ñšà³¼€†>ÔæªÉ™j¥ç\4@>;/Îü¥Ìu çöĉÍTO&<¼1ñ+Ù9íËÓÃ}K’ó¤ÚŸu~ZŽP*xa÷Œç{b)¶³æ„ö³'†¾·Ü¥¶DHoCçvz…‡¹ŸÂ!“«„É QßHœ²Í¸d>åpð|"ùÂʺRâ|ñ±mîyA¹SxÎ%Í~UÊŸîã´´Ïô mŸPh œƒíÎÏjŒü^ûœ`²ºø>¸Ã™¤ŠfO²„Óvõ§0�»À3]p |r^e]eID$1 G-vù�J \ê«Ö÷éC&ê<]"ŠZˆäq•n@x&áþL;§‘O…¬Ñmu’<vfp·'‘WyŸªù–èšr¸¼æ0˜Ûz`Sˆ‚-»$zR’Ò–oôe¿6óOfåÓ‘@÷íí`YÅ˼GnõÆ©3lzö¶fDaVª½Z*>˜|è7«iÛGµ²ñ.3>dNçz ¨Øm³u1=vËæ6]ªDÉþLÐcçgµ@xôsDÿÎ@¤*ê·ê¾&ò 7AíÙĹàO†ÆÄíÑ+£G\Ý+(‡m’Kµfg´Ã÷V6½š*}ôAÄí£rO Y¤›¼¬÷p̨_FÚX¼"3÷M2Ã„Ç GŸºÔø´ßìÕôƼ·¯+oÍß³Êå’ÇŠ@ùÓ™ã:'l“»´ìZQf!ԇشl jij’2c^N¹È˜ÂŸ¼ Ù»2A¥*è‘ÒÅ$Ú÷0 Þ‘‹¶]c~ªÚ¾Ó’Ë->BÍB qF+èbö4בk¦ñû/³À¡/RÎä8&ðì½{‘ ˜TåLë­°:¼¸·øL:ˆ2°F@¡˜ÐÎØ¼½§H ¥Ñ©Ï —­hçQ|ö]ÿNP ÞœL•˜†-5ê%Åìe{‹Â(’^ÂÏT…³Jt­×ÔÖ4%ÝÒ 3gAáºïÕfMK™<Œ$H6œ¨³™u¢íÈ×K¾/¡žÞ &eÖ^š«8غÛáû¬;è³îí* “8{Ì£×Êm{œKŠïR¹öe%׿)·ázÒ7oÖ%-gÐ,—èðàžš,Î[¼6Sfã7JŽžq\¡Åvkö®IgÓÜž £U(™œrÚŒŽÒ¨À0Øç…>+Ï›z<</!TÄ“ºÉÚÇ•j§dÝ3å§“;>íÇ wûÝhFo¾ÇL;mZo#šjšcìŠRKäµIøA¸Heµ¬6<¯5=9ÖØ*r«Ëvèºns<B¼ï³öO_³j®vz±qÓ¼O;—S¨Ívž‹+ì’Â2þ¬þ•ëÕÅ\©©m©B^4C8﨔ހ =Ë’gjsõB¶¸ßéœò kŸÈBõÒ)©¼+º^vŽzuÀbP˜eñæÔæ«zÔïŒÝB,&±ýœ,ÒòIlø]�z>àÇd{%âïç´HˆL׈§ð ç’Y›P/…£ŠÇ¬Õš‹Rà+åÁ Âpà™šPãL{qlwot±$—I™+½ #â-0nö£O þªŸ>½΋ƯobÔû®Ñº¯Í JxHŸRòñÓ+k‹rÙŸúOa{t)¾ðW!2¥¡¥Ñ¨Š@½Di€é]tiÛc „V ¾è÷Ø^½•:=ÎǺ½:™[¢ƒÏÆ{œ£;Y6ûþv½Pn^¹“„Úçô€ ãC:7¹Â%]—Íhx¿00’ä2&ë§MVóÖDe¦.š\]Ͱ¹²žª«'§×Lö‘dJÇB¶Û4S»< Ky%­yÃéaÙ_¼OÿNtu/„nØ9眃ôçà†ÎÎýÀ µßQ„kD6ý>m4Å–!ƒ#¥ åñ]”™R¨?å'@›ªjkç�Û”1ÐÞ‘æúä ÞDi¬îR‡®=»ªI‘˜&—Žj¡CIíüDáÓ ý] – ÍiKv— ù$D!Ó<b‚»fšÚnv–ú½i/pë€G˜[çˆúl6æ©tM¢j©Ñö³îy / Y÷Üe-€K¨ù¨ùÖˆ 5(,Ë鑇hµ2&уCB¥¶j#ýÂA>=1Ž®Û:`FË­Ç6 ½qS»ýšFfãÂV¦47á§"(CZ¯á8ÚÏҵߌ’bZt<¸.F®¾Ê¨3²“jƒ='ë ›KtrX™Ù•îjå^÷^ªžqš,E8 WKk‚BÜw_Hè§;Îúañe¾2x°óD¹¹|%œ„Ñ|Ýö ̙컣£Ù™?'§¿'\o¸£âs°©b¬~ŒÂÓªàEtÏÀ5³x4ò`•)°D㽤c5¸¥²Ÿ2ôË ÎgÅ‘žæð{:“ïLo¦¾°°OŸT:”·ÍñªMlàI[x{¹%À‚Š <Ç´¡‰+ñ ÎVÓ’ßY¹®mB}žð#Ðp°–à }$}w±ƒ¬óLU6€HÑ °Êš×n4Ð\¥oŠöˆ%U«Ù_â€{ywLŒ(²¼˜ýBÃ?³hú6î0–Џ×&) ¯l[+"¥'Qn‡š¤»²ùâ[©«œ÷³‹Fòsy¥=ãï‘^UUª8¯Ï[W+ÕnóÖºoœgê¬Â¨@Õçþ\n#Ë©TPøâYå‘"aÇ`š¯ |âñéÏN4,Û›ñA4¸º“ñ³TädQ‚‡­Ì}xx®®’bº@βCM/èçySúb0ÓîH£¢ rƒÎª«AIÈç`Õ…p¤=p£*‘‚ lZ”ƒ« ýdé*¨ïΙ¨f*;‹X‚=_•âÏ\ß³3RêPЪmÝ>׺ R…N“çïîõ;ÚN*ȃžyÌÑZ´ûVÞOLBU|8êÕöÍD¦ABõÍ;'N”Qƒ$ó|¹!¶¨@;;ºÚ°4YP9±&Bx(Ó·Ê7·#9}ª(c¿ü”áÓOøêMÔ¥ÕCŒ×RõÕýÁ8?f@S ÛÆXJ|Áã÷®~¦¯¬ÔŠóCŸ£rç­pO¹w× „–<ɨy‡XìaºÆÚ�'DSG3]¥XùêÞkÝ–zz횂̆ï–2™¾PÁOgu¨Ýê¡åóŒ'8ïE„b‡1æªZOÓÛ‚^®È|U ig± üžÚ䫟+ýTIR³#©£#Ýß=²æ&wËN`*£Åe ­ QŠAeIÎô¢,â}ÁÖc:QJÝ ,\ê©‘Æ¡¨[,_¸Ð§ÇZV&Ò6¥ñ3µ·ï=| W*1à‹­:Û㣛$—OpTŽ|)ÞÓòþé-ÖãÆ–˜ÅZlŠ´bƒ+Éó’4½ºLßK$y°\èO-Þ6&N"z"Dî ¾)–€[²Z0¡mpÒì¼'~iòjZðð™O·m÷Ù S‹ò¼G”Õ•}ä\ïŽq±³ÅÛÃ!NeÄÁæ©Á©U*BSÙÏÎLX³³Ï_'ú©ˆ«ZMQ¿Ç‚ÒÔ“&y¶OĬN`ù9NI‰,r®™+^‚‘><¯)‘é:·ؒµ§š_Øð§ïîã[¸Þ~ÛQ«%#ºº03ön‘}Ø Úùõêæ4U¹ÖéÏD[¢¤RÁOC=9`ÃŽ”¹y¢xåN<õuð}¢Æ’jû‚.K•8FF@gLRü¨E—¤£$ÙÉ¿V#‘¾Lˆ/tÞ§3³A>/¥ÝÇòôÐúíQm΋ ¨,…WÎÑ´ºRC(†¢’,Ë—!òýVÏk'¹‰´î!Hð I£ŠÂ3¨¹£¡IÎg¤iï"K˜¸»úQÀ“h¬zz¸x×,v÷LõÞ=·˜ÌÀaÜÎpÍdh+øôbùN¹$.ôµ·½šjÈq‚ÐÅž7ï±ç1^’‰ïmk1•øV³_Sj²„¦ÿBÈß“1Õd˜�ñ8_ï:Û–¸²ä^ã‚°ÀÂè3¤>T–QngQ'"#†h­8@ew7Ÿº«"JQE"é7)Z_é§+Ÿ„âÜPáÝÝ仫c…F•º,ï…Z!ñ'³åÓŠ�¯lŠýý™ÇÉô¿¤ìÛÐþÙ¹hšUúmÇf©ÞÑ DȘ¹„y§‹ã¦óÒѾ·«È³u-ÂÒÏGÙÙIj:4AÍ:)>W†Š® ÛiП}ûs‚bÒ–öî¸;öˆ¡Ñ¸Æ'†à*)²¿rè-y‚kV }p’°‰Ò`»Ød[ù ¥.E„ëTÖ§|º,@Ýh\�ðœÚ€r‚ÌÑjf«yÒ.p�——.D¨æfóÍ`^ xAhf¡Ã  1ykþ…’}:5Úã4#ÁÑ G&ÐïS7óEI÷œ ¾uñ7/åâjŒ¡úü Ì3RÖWQ’E‚õ;îq’ÇkÝ?,~~j((Ù]Éí¨ª„çú2Ð_xóIzÈiIÄp×Ã#HOœ#Éõw˜:Ö>kïÊzïùÙ†Þ¬Ïã/œüÓ³Ç/+ñãõ›’CÓ˺; z{J–l=à}" ^•~¸Lo¬íPŒÂ7«ßôÚxô *½ˆ‹_Hq´åÂ9 ÅÄP8¤ÒÓ¥ÒCH޽¼Ñx³ƒ” 1!Û+ Óì ³Ïmbà ?xÂ\ûúy Yír/ä绋O÷® õWkÀ\;ú9U Úzĵce&ÒJ똑…Éà<¬ôÚ3÷ž’¾§ m§˜;6?g±ò´¡sÁÈÑiª–ÒÐby-éõ,ôõ"=j!eßMõàDÒp‚ÔGÕ±·¢=¶¤ÓO7,íZüòø0-IÎu{mõ}`õà;]/ÊPŦ½N…SmŸËb³ /+ÔÙÒÄJØä¶]‚Gç1l®k} Üfæ’«A焇/í~_ÿKz÷ˆO´ÖÁJQÛnò¹Zâ $ª?yׯWs˜,²ˆh:-gr%dÈ£+=B穊\Fi­¸0ЪH ¶“cí'ZŸŽIµ ¹FÌeã&UŽÆ¹³E¹Ì4+ŽýxßÙQt½Ç ï*à^QMmop …«`ûÏœ‰è]š´ÏS2ò3LóbšïËL²iVíè2·£WÆ÷0,èS/uß©"™OZ§XTßÚ[>ŒÁ_x¡~O(G¥Á50&{[ÓD9÷À=C’åÑ)/9W5“º9¬¹úw³‡=¡Ó$Êt1îÞ:zF?»!ÜóðÎT†uRTñ)Q)5ãz¤.AõÇ,Å ÔdIÂÞ  ’'M)ÓÑÌŒ±#FNŠÚè jË ðŠ~,Ÿ £O—߆‹0D@mMJ°‡A}dÚ«÷‚Ä i¼G•™ä­ÀVD»Ù/FÆã5Ô©ÆQƒo ¬gÎ ýÌYa/\9®-ó¡ÊÛ§¾àG‘wc 8ï-Ÿ0Õ¾ÊFv³¤M«7£Õpj^ ž úH|O aË= i@…¡4ÀN}bÆŸ~ÓOБÙ:™Ò‰èÖ’ë]ÇyØ{$Ñw*,ðFAðÖ_aÚÝt=›§¡½„”êZµ‘ž…­a¥£Éüóm–N¢¢àõ ³3©ós@ŒdxZ”²òÎvZÛª]%ÖøôZÄ­ÍêÚ°D·ÕäÒƒ/¹/1 Ú D€SÌ©=¿P{ŸÎ?K®•@× @ ß9\aÏåÖlàPœ?Þ—¼ÕðÔõ"òiǺC…¶ØsqZw¤$]I»k‹S¶G÷{³p‚e­Ð_¿%#œ(ÉÝf `ó}F5GdïQç‹GŠÍOoò…#ñöJ�ú>j/ÛeÇÀ 3z™ÁDœ>{Ÿ¸}ö€ÝêF1ê:¾h08LcBfÑ‘yÕÙ”qÛ{v×R —–`óo ™î¶(l¦Ì2ì  ?›R­ÎŸÈµ=º’;líALx›ÇÒ ±,’a²ðfÇù¡›×ŽÌWÕ`iÜ$êfˆlp®¡3¹AZƒô=¤E\ÔY¸‰/ä¾/大ã6kX±Æ²®‘ 䙸VºßŒú¿å.ˆl’6¬õ¸k­\R“{kÒ§ÞŠ¼hÞ¬ÒëÒlÜ_Ø ŽŒÌØ`h¹Õ¾d?š¨—s1·ºÞkXà}Dm§ÛGÆ›Ç!ƒt­¼hg‘» á…ÆKkk[aŒ±*:‚õ/ì¾oÒryªÇ´pΈʹ>éä/ߎ‚¦¤­À…hqW¦Åµj'›>…E€‡ò�¯©\Ð[Ÿ�ºmâ«ë`“0Ÿè9Ò3(d)]¬†v™ª‹Ó¦‹]KZUCÇî8õ¨¶¹èŽˆ7TWÏË6§÷ ËHÈ&H ËŒói¬DMA‰|¡÷}µ4T[\ ZLëÔsWÕsâÜ·{dxܤ)}Ö» Õ錊 :MKhÅ sNˆÀ1§cÏv‡•súeE+<ÍŸxO«™2æ½Í n# Â§ÑÔTÁ:ŒEAÄý“CNá8*DôÔ•\œA#—»½ö5ëk¹à‰¤x˜Q€ü}ç|ßwNºIFœª$c¦„ËÕx~À„P¦óxí=Te7+|ýN63´Q�ÙðlÆó!ÆÙ¤ôsîæU#nÀ«ßsqm„¥YQÈ Ñ-�’³7 «3P‚\!¾JJ@ê7{} Çî6:e ‰³ðª9¢fƒFk ^F¦UPí\Žè}"ø=9Èà³—’Y2ôˆ²S÷9¢›3§R \àLµsëÀ¹Áb¹g‹³åéY¯¢K­ Т›ôD8×J4B£ËϪœ>åböŠ !ÀçÞ4w›l¼<å;>BX)•+–ÅÚÜÙQ -&v0R p~á4fõøm<´HÞEà'°‹Óý…a|O†5ïá¼—déw"õê©5ó€ÇA¸g’ðP¼œ©)&ah˜Gà…0N|Ðp`üÔ€ÎYœA„œÖ búo¹lÂï…Š€^æ¼K¨ÓúhýÑ<aÙÞ#s±·ìŠFÇúöíU4…`_s£Ö €« Üò½-ñ ôê—Ïq_uù¾¾žXë_­±iŠ´ø¤#æ°èéwž´˜ØRr‰éIon¦)à ‡Y/‰ei™«OKfâêð a6\óê§'n ¨Õ™RR`‰çh¤£&x,Ô¼w¾RöúªWŸñ[ î.ì¡e¾€LP¾²xÔ'¡2O‚�ð½ÆÌŒ„xù…ã÷½vƒ4× òt…Ñtê®›R˽µÆT.8†ÍóÏSö8[q÷QÏå½zÓ³b‘l‹{µ'"R¯±ëÁãgI£·t¹¿ou°Ä£�•PÎbàYÕíÌÙ蚆à ÍTÝN÷ìZÈk£|¸ÀhIÄDRïÄΈóº’ó¬ŸØ–ÄÓImá*øBòû‹º^<~á¾Qo6:ôHɱø÷¥Ph=3êäÝÛrHª9Âû«(ŽiŠøâŒ‡ƒ‹Fl"ÂÎ’ŽÖ¢o’ã’ƒç0à–Î@Jˆ6Ád+„cÈŒ^ÇF©m"ÛùÔŸÞ½¼’÷°¹gxè]b9’ Âh>ê[ô_‡ÐÚcîO,?ûÌõ£·[džˆ x-"ãežRîS‰Ó”vd©aÛØîÔ‹žè8l¹,¢á»äóͺ ÐáF }]ïdM‹¢ÑTæÏ°–íú§2;ã@K+²üLûO­šÔ+FàG¬ï=mÖ3Þ2£ u†Ö¦ë<Eõvn_727^»rèzsÆ>ºÁ¸ÎÄ ô¸/4¿¯ÈYËϨ䭑ñ«©´ 7Ö§ûa1_U]v$K¿e&ºb‡®Ì·çW`C˜„äe'¥Ço‘£í®iö™»KDåïÞs¦hg1éϤ8ß2hGç¹æºl‡¡/ÁÀÊÛvÚµ„£A;ÂTÌíñHí×'€1VfïÙÞÏž8 ¤'®¿/<ß÷ÝY/Rå¨ó…qT¼7ºw<)[•bkýP“ ö±Ãqß«g±Mü|�ån•DÉXQ^^׫W1ÚÏÞ»8¥1‹y ´~O6QÞ†Ðá`Ç…%J]sAʬhÊšT9h¹l÷n¬ÏRZ È8ñø61!(ÐÚò] IIVšºbuÚ®ƒ>ñúBTè[¡ífÊ‹á5ÞRN•ò²ÉõÜ6És߬zvÈœ,S4+Z ¿8Òr#!AÖñš÷DËÞT©4e³`8Þ〶Y¾Ÿ )Ë8!M*Âv)šyuÙcà ÑÕÎLò(mç®ö! °áãÖÇx³Ãã½F®Í‚´ñØ+èq t9Á4½'Â2_˜~ß¶ãuúbÊ#~­#ÜmüªxÚ+½åÜa³|HnÙ‚3 pk™@ ÈõÆ÷m0ND‡O¾9[ƒÜ÷¬²¼ï&ˆÆÓÌ’$®ßÕý|û{/K{ÒÃ(xÀŸ*¼B;à–‘±mâ~ÎjÈ‹(Æü,•·5R²ŠA.Øi{2³Z]à‚üÁºžû½ÉºžànøDÕ?»<×#žîPéÁ»cÉÞ«=Ÿž'[HhÕ/á”@뮹‚›ŠÁ Ó(z1fT7Ø<{º2<–ÀØ ´gjå64^ŽþÌóÉ‹ê£wcÑ67(*lUX´Œs«dÔdìÅ{‚ÉBgÅq ¹8¶×o¡YÕ¶,M[ɶñ±¼~§i¡K­_¸š~âº;Ñ•h‘�±MÛ"àf<à ϬÑVG4VµäôµVësÀ^’ôG¯÷%éˆIyêÂæð FÐÎÌnÓÖ L‡ŸrN3±í‰U ‡ezþÌ¥Êb‹íT{¤÷M žyvO€](>]3(‧yè¥H«âï\ÕAwǹ9×�éZd5ßu´.p/¹Á{tœõÙ­¾/î•Rj%Ûœ|—K1ãhš´gÒÐÀF2O:º 2� :-)Ô2$W4R§ÎŸj[©¿—8 ž­Šg{ ìËÄSrÔú^™ÍóYLðÌŸn ‘„]XŒ©[jã4o^�r™tT×Ëwû0€5§!ðFg” ‰I Y¿Ò€lÁ}ÇÒQ¨$­ŽÁ—lrùb¾°ï›Í^’f‹£Útv–+ÓŽ"ÊÝ‹r¸Œ\•§²"º”Àd[rå]å›r°Z’`ÞK"®)îx­‹Ñ@¥ó ‹S;n‡ÞØ …Ÿ ì ÑŸñ«|UFx¬c…ÅΧu=r&ñpûðŽŠI8/ §ð€%L ‚O"Mê@Þ Úö(ÂôŠYøBÏÍõËkõûª_ũ7V'ñ²í ™M£¤”ïä :}k†Y5‚)é¹ik»k¦Ð¬z„o �÷ÍæºYw¾Éx RjãÌg6ì¯P‚ëç”`P^¸LÔ}1Ê`;xÍo‘Ý^¿0›ŒS`ÐËÓgcg#¯œJÚ{žÙóZÞD=¬.3,ýó)ŽÀ«©G×HÜŸø~oó�Ì#↛¥<¯îj×,³x «\›4’kϸ_ ^V¼‹òÙ³ŽlqJ™ê q´¼²Áz~Êo1š*óÍñ³{>/u›øpCGB¶²Ùú§÷6_-“ˆ¾'“óúPn‘—f½Ç/v›j™ Ôaeç ÀKä0kŸñãhY0dŠP ¹A‚&µ ègfVÌLÛüºýSÁøÙÕô!Èvº² 4ÁZ_eBB¹CÀSÔwlo4°§F<3«Ñ1.²ý•På5ÜZÏT‹¼Rðlx­ãSŒšÂùZ}{™Þ¶ä‹»)‰ÄM Ê„ý‰q.¯ŠöÅ›BÈåFVJU’Þ^¨|Ó6¨àÉG×ÉýŽñ<n±@o£“Ÿ,Ÿl¨%oõib¢.=!é§¥žs¶¥‡~aLŸýmžÊ«%÷Šã2Ħ”0Oï{†#ê”)üÎØ¨ {3ËH’û]ߟÍû+eAô)·û¢\_8VJíh–Ô{á‹§íÔÚ¹zÏŸ·ÿìt9ékÞË«óžURÙô…ú­ÍãbuD[1‹|¸3~i„áËÅ „$Õ1�vCÍ";£ê M¶wgÚçÂÊó:vð eþìtHÏÝ$;tUŽê`±Ð›¢nc ßŒÄ©à •{1€·¸?yª›tý½ID‰^ʃYÝ›©N ÝÃ+�~xR€·}OkŠ‹krD´‡~Nm¢1‘às�XkÈñ Ÿ¾FŒ“|waã6ðÚŠ¦—Fýå.ê{ÜL+UÄ"ÙžÌJ/+s³ÞÕÀË §ÑBóH)©ö/œßgÏsı”cmžÄ¹^±ìñ,nMö.‡Y«‘mkôî©xɳÆéËR9`Ë?–=Ô¼{YkV©x*NzV«Ž%¥#‰›.K¹Ñ#}nžŒXò"u4~!üx¹•ÆÂõ1VÖª²sù UÑÀeí¼°žìDÛ {8”N>FW5²`Î8±yÜ®\ƒ@=…;[í9â)¼½ŸHû÷æêÝí½ybÕfˆw/Óˆ;Iò´h ô¼Î%ÆM¼<ÒzXdŠ„}@'+GN•+SNOñˆõFÎG¸e=“{[QJ ­ÕqÍxâÎ^`I7…¶üº*§6C.šrì=…RK§÷À�·"ßõÙãW24û–¥ºMlÎLç)FÌø‹äÞ£t?=¨¸!Ž6öpÝ7Sõ™4D?±6òY¥1qQè×fùÈ©ÇáCó! ëa´tB&ƒ‘faÀÊñ‘Å‚1Ù©5Z-Ùª@F¾Áe:}¡dÊ>•“a@m L;ø�_ÑqŸ—ÇÛly?=„Ô«é-Í$ªYYr/#bÄ{NƒV9Ø(í.‡CÑ ®b­qóÎz%ÔÞuWLv ôBënPªêë"X šÀñoeëgGT~~D±V8Çem&ï­ ê‚£ \bk»£Æ”½6ÝG[á|ÙE¦9š0xi%0¼\z=±ö ‚ -kçÙû;/½N¶s@­àª¨X0¯©0à¡2ÇRÔŸ dy9àRå¦AÞ2uœÔÉê†]5¿&~zG4aJµušø.í¢iUîØ¶ÉÀ%Aø9¾�ñ éR¬×]©Oí oûì¯ìfeÖ˜Õ¡ÉXYÉV9Û“ëØ„Sç&‰«ÈDúyä­<${N•€ îO$^©!ƒ&t¤´”^pArÑ´›=¶Ziz¬]Ç�½–¥ö,ø]_3äfžþÌ|7’Ìo^ÙE¥O!uûaÔQœ4‘6*+=zFÜå¦`¡b÷<‹ ç•Uµ>ÎçÍwZÁYˆIyLlFØÑ ñ…¸vIð§x�Úw¯[_™P‡¹­$\f5HGÝy ñM� Ók‹�®ç×åç÷ ðøÏО³É�»jøIÎÚeΆ¢Ü´À0™Ë¦à¼ðxû¤2yÚÀ–è©{ë/õBü9£¶CWÖX 5–šõãšõA4Á•·ºÐðŠ-mùeÜÉІ¯µ8:¹E£ø³AŸ^÷Í�`¶ê÷‘6¼Ý Züsÿto?÷…« ¡‘âªy˜NQAÇÜù’14ÄŸ÷ d_\:iSŒÔ‘­ìqÜöªh«èëTóÇÍX’4Ž)x‹>Ï$z¼â­=<zSFò´X(azy¾u¹s}NК™Õ)Æ]ç‘A†c"GTBQc}|Ú­]áŠ+*FÒ¼ !Ïü.,«ÓÙ FÛ‡æIG¥øƒ÷…z|vÎò}F!o¯ä-ùuÚãó7>ÍÏ»D_ë+ð³2TÖÙ}¸SSi×Ò¼àEo8U¥·-0ð[fd²1kZ‚ðŽ®ú ËvíV3W“Å¡ŸÙ:\•ž(ÿ¾™†å•Ùpœ¼\OAŠ´™öí €ì,ºXÂ3 vi⯒1//ö¤T ®e3™×v–uÀ™FͶ¬ù®±8Ìp~ànð>fijUåÒ?Z…ÞÛe,Ì·ÙStH4×ê f¹ƒÇ+ä'æ.±ûz¯^ùÆS¦d¥&=ï^¶¿Ó7Å“}ë3èö^Ûëힸ}Ó„\ü¼ÍÒñ{B%ïQ>û} (º–ÈÇIªÚA Œö,ÈeU¡Ô õñ"BD×Qpa˩ک#m­ø|ôØ)}BÍdó¡É»¡ÅÊ&맇åú…<~Oš&²4´2ØX€¢O´„Äïª Î{¾n�4}ŠÓ—ToŽôMäHàÞìZ=,Ú ç–Ü*~ˆL\j´™ø¤IÐåOõpÌâð ˆIJgSE_Ü/sšá§Ñý{H5Îó·4Ähån\·ìEBndàÅž¢Ë"/›¦—άE‚'"Ö2UµÅJ i¥_F‰ù‹CJ6‡[Noü {‚O·A‡YLEDÄ]•Ô¯€@Â{Ä^¶Ù>x냒Øz’´Ò86.Ó!äšèðÚ ªâ�nÞtg:““ Š;ÆtŽ‘ðñò[n¦…©§Lak/xƶ5‰…9·ç5^àïK ?}ò”·j‚©aÿ�mÏtu°)5—é×ëp¼Î@ç¶WÝ…YîoI§GžË°‹�EÈZÖÒbý)bul+¸Þq|¢ÿÙaûXœ»ææu5(®M@¬.í‚\Ę-½–}¶ `†bêÈò^¢ÁÓÀw±WúL)‰û,_Ü %äkÀV†¾u#+Ç«ˆô¸³nÄé4±…‡V~k{•:!-"÷sn:±Ë@IsZîÖp”J¸G™ÔDÔcLJçÙ_ñppdBÍ„ªk[(.hÝ®£#Ùµ”S«Ýˤ<„y—ì§²ó…?ë§ç]ñƒ½D©£ jÀ} ÁqÚ×OºØaW]»d 0ÖA³¢Fd•_B¦R† tƒõðΔx´ÍQ©]3Å)æ{·Ó-™ÛOdò]UŽôQ‘•o8W1&]ζ ñÏ ÈN,Wå!Ó`oÔíè˜eóÄžè°XªËž MJ ½á#ŽÌXx‡}â!aÀS•½7G§¼ª\/€Uá9ž9+}1ð>»®én_ˆ¦¾87r|:Ë<G/z` áþø=8’Ε7û@‰a;Õ‘£íH}¶’@Aw3¨ðî@.øFÄèj)Äb{žWsúhÓÖK-Òem¹:jpx/wó¤ýœ­ˆ3_Ùkyë÷@^iÖTëió¾Çªy½ …"f2 긢g Üäb^Àej¼Cï®»mí,›K‰me2z-1J#P„ýÅÐ'9 ¥¼ŠMGæ«ñ^JÒ8„ã>�¢sŽl}Ýê²\U�\šzZ\nóYÅÐ JRQ¤M³ÁÜ“Q˜!¼Xª€Ë Æ(|å-¢Rðˆ{¯œlä€(c�…ø…ç›B`{?½HAz5-Ó‹„äY\7RÈC,Íš^bîÈn´Gê @sè /‰ðƒ§­)}¾‹ÛasNÍ|®úÌÝ>;±~vâÅ»ËpÒîõr­þCÀâíó~ÚslÈgNÛ;¸lNeµTV'Èö ˆs‘`¨V]ŽÖÒYõU_-û­+óÑ[e¾[ ÷ÅjÉ>‰7°H± „šT�…u)9)=3= å˜èÞW?QK é˜8ê<,á:ÔWðÔÊ!#ü :ÃNż8ÛæíÛ+À¤vz §OL8ó)¨u‘9åuQQmª¾ð³�%e½ÆO¾§Þ¸ÈªT‘ ]À©7½BSY~ ƒÈ‚vßd’208Š[ATí‹zÑá$CäŠîd¢E.LΚÖ2 M†ö¥Ãƒ[ŽS®Ê«<±äÝ\® o9^FÇ:¨Ôp»\ÆA›*ÀωŒ8âa2"@½<¼=|1• € ÉXFéGhË  4FÔ=œÄ«Â1¼CÒ©#—*×Ë9â,c¦uÃø¨î‹ ûìÎì‰,Ô)¹sé‹ÑúÌm|£9M¦ŽËÕ^]EÉÔ5J*Âåªö`êêÐ µÍ|þ^˜[A1êë”2´ >z[PÚ[]ÕåcT”F|‘9Aï-”$udGjB'ã½øÅÅh ÔC¬jÿ3§pq1Å 4“T`°¼ì3ˆÇ·%®bö§™6…¬èK5j-¡LµºÄƒÑÔ‹ÇÅÔDQ¾€" ðÙ§ý{Ã<ÞºïE5²ò;D±MÏ­Ÿ—Š%5[‡Æ¦s½ÑJoØ%Clò]Ärá…„ Aïcx¤¥gTѵ@¤«ŒFÆÉ4Q€RðÁróÉË`UÞ7;ÛLCþ–DôÒ ‘úù2’ü °z“; /m!†®x0÷‚¸F—È%Õ¤âÄsðJÌ,TuêT?=É£-[wÆuUw÷ºÍ§c~oÈž£(Óg¯údc¯«óž`#ÅÔTô4Û‹áݘ‡m5³zZevª*§Ü%¥ðSBÀ›“à20¹§1û£K[‰hhÁ·`~ í„mù^xö`Ú8t£Ä’K´^^–}ÍmHNô¨ËP‹À£»ñæI�¢söp1îÞ €*?÷>× VÞˆ%©`"8!†ºjdV®'>:t1„8ÂJhNÛˆž}+\¹¯5›ÚVñꃇÏÞý˜[•^Ž«'ƒ“<“õ¡"tàð{ïW8á+­ÍlÂvKjæó®yTÔÚ;ÇDod·)Ìß{ïˆ<E2ÅåQ ½êá‘‘Ó�Ë[Ö±§Dô’/&VxmÁŸNW½Þ_Œ@øËÇäšÜEt%qæ‹ø–x9‡ æ1‡Û@¦^ú ¯‚ê9Ü3 z8= ôÛN ©ÅZ—Éd‡ª%pJ§ Vj!„?ùìâéÆ ­Ö©¾¢Î�~–©Lo^XˆÀFõ‚¾N\¼ K†ÂgIïøTµ!ÆŸï¬öÑ -‘póÜæÒgS½Gç÷¶Ü±Ÿ3”²yà–‘lJ££¶Ž‚.äÙÜ›³3ÝÐÃPT9÷Dý÷´Ê�/ìTÀ%zì=µp—yl©¯›CQìM÷ª,*¢¢f\2T Ä«QzúÊKˆÂ’:š,Š:\¡Á¨ç½÷"£ç¾8Áïi4ÐJßÅô[{*—¾SqCõu¸L‡s§À€+ŠËHW½JÇ‘zõLpƒäH«;pV ß‹Zx-ðœ!s9„¶_›ÆSAd•y»¸¥®G›~že创žüF:J©ò™ýô®%rƒHÄî` ÔÈBïhXþƒZœ+wÈûÔÄÈ”ŒÊÓ{¶u<‡–y]sc"‰Ÿ:U¯¥°£‹ õ9á+ôÙٹè…º¸ûå›#ï°£9Ä^ð(Gyªµî®L·½)§0ZÂC—pyhVQØ%•Äè5"öçíåásø¢2Šî=…˜£½Ì"!V¾íঠ.¹à/Àª%‹ NN;ÅG&‹=§~ñr§i{›OV²ºÐøz©Ö´„ޝY9o‡0ž‘=ãí]Ê ÌxóYú]’tÍèÖ`‚›²u& DŒdŒ‚÷)U|ñŸ=~YÌa+,"çµ™°Ì›)uîcÞc5Ca²¾×/Åw¢kz湞jœzŒ¼È`}—N)˜B*oÛ«8³B¦·^º¦æe°“N± móòUºÀ<Q…=ç 7ÍŒpK’WÈÖºø 5p4²?ÿÅÌCç 5‰µ%?ºv ²w1×ÈT±ºT¼^-ØáA}³}äÉÅÀ‹cåºThRéOÒ…ÞE£R¡Bâ¾ù|1ï³ÛëÛÂqYÀ»Õa¬˜÷Ú¢4‚ÇHÍQyêÙ‹g ÂjO1Å5§èñIûd@ëŠÅMV™CR L&EX_õ g$ €F¿Ã[æ}…›ÛŒ2Þº‹k J|ƒñÐM*èm‰4íô[óÑ_ÜăփÊ>Ä}Oî1ð¹™ÄEóø>‚ŽDC‘[3£z Z•/çŒÐÀO÷žØ{/ëÏ!Ùh ,ëáÈž¤ºPì@‘ö'7Ÿ}_B^e R“jÉÄQ(:€ÃRz9¦äZ"²›ÎN¢ÄôúžÐU¾$d˜åE•AtÆ$ƒ‰®°^o¦ =1T€ª×Iê}á0úB R#%½•§t<Aù͵¶mûf4€–ö=,‚Œ5Ç<‚'/ÛýçDF­ŒÀ&(ˆ Vèƒôß65›@-G&y>eͲíé™ÍPÔv}3â¢OÆíðIK1 ;‹ªè(ÚmØ|±#ß €'.¨¨EÅ RÔ^BÞœ?»ÇÄì/w˜VYUïÄ&_;ÖôÂÀº6¼¼y;M×^6…Ié)GaÄë0žÈÈëå‰aWà.Èu‰ªCJ±ŒoÂÞCU+�{øÖ8Ænëà–›©Ñ2Ñ=];LeÊò>š¼^d™|G~uÜþ¶l^m—CòÓ¢®(ßI4ÎÍe1¿! Ê””mçç>¯ ˆÏ-žr%úÊwjÖï,À¸^ïbA G‡(Ù¡V&²Fôr[¸k8 /‹6ÕÐß{°R8(O¬†äD Þe ]>_Õ�Ô®çw‹û„ì×3¶X€|ìû\SDð!n# ðJf?WÓÄ" Û¶˜º]x´Áv„ ‡öŸ1<ü™ ‚"P¢9­L ÝGȮ߹uÕ»™©”œ7]¯ïúMK˜RU?Lñá4÷ÍE¡ÜzÕ¯ûŵ•g©ƒJª«@Â+AGÏ/†ì{W/¾É·iìa<åµ¶Qµ÷ƒGW§Ç0dÓ]®#p<Ô”"È$š€é |¡KÊô^ RnyŸ[¡Qç`� Ï)Ò™´0-—\G4 ãù©�¢†$¸%ËîÛ]Yæ×¬1¾+Cqâ(㪓s|~¾"Õ»™Tí‚àœùÞ®èížk?qwWû³3hK‡àk.^ÁÂ鎵ÒÀZã·ÎJÞ´œÁ‘ä^/ûU“›6]}ö ÿÞXëBSÙ‹çO%]ÝáœÕÌ0±8O›¿‹ð îÁÎ׺çoN;6õƒãWR»šÁ®V\S Ôr«Ç*èÍNk†ÃŒHÔíU°¸Âý–¹÷¾' C96–,/zLL¡ «Pê=u]ÓÂÞù½C[¢ã%á&QnfáÕà¡‘T™Öʦ®žô}¼.þ.ÆWæ±½`}À7ê~€,ËʳG/f[QC!šlGîÝktðºO–üÓë4 ‘)ëi‘ï\ê³ çÑ÷Þ²aë“@ð¼‰f™bY(-½{ý6Å×D^ �=…Ç\„ú:×ÕÏâÙÀ0´/ë Vî ¸p÷ƒqy.Eå.¶ÉX²©ûº/é8mÙTÇÆÃâ&[Ñ3‡ÇÖ]gó€ä¾Ðß[tÖ~KÍ[di/£Gôq`MìÌ“§/ÅBЩÝâÙóJÁä'­—Kxbâpß=²(u§Â9³0mêxLŹÀŸ<Ågf͈j}âN¯H4PÍ ý¡Á#ìî›W›=^*ɦÖ+•¶ö^‡K¶hywäÖ ÞÖ¼ž”œB†‚;bŠnEÜÂ7Ù¤žt±ÊܳÌv›[(­e‘ÑFJ&wX¶ÒFRaŸ ^ÚfV³œ4$±1†0õÛ_LuÁ07·©T%¾Í×÷üF™ Ë[m- óé3Ê+%¦²|ÆÓ56Ù˜i§,|ãÇC6h÷¼Åìê¦ÛÉž.L|¦‡ÚË{:v^j K#%^ÔØNPEoù^åòúUëÔ¿]|+£Ya”;Ãò€Xžê:‰ 쾤Ͱ¬æc†‰;‹Uª*åÔM—Y”ÚÜM=‚—ä! KÊ4ˆ®8W°*Õ`Ùž(Áî#Íd¶DF®§r'+%¹?ÝO,r M Ô°ÊžS †³ Šäb¾© DZÕ«AqgYhŠ¥C¢ô–×ÂpAÊ|ºmEDÜ;Oê•$½G:-ÑXª_\ágŽðÇ÷.-F]Ÿ¹õ>¶ç¤Ð!ƒ•Ë/J"k;}‚Ÿû¤ñSÞ{€áõõ Œ�ùÙ‚€Þa `mÂ=*Ï‹5L<¬AusyÃì7{�uãª�çÔð^²……è; ršVy`þl&$ õaÍŸŽó ÿ9ÕªG»ùx¾×›b1Ú°vkÃüO"ÄkWañ•hÍi*•WéX3vçBl?à¹3H•F픾ϴ^=”qÖO¶è3Q”H#l.l«¿Fä§|XGÚNK—ðˆ2¢ §^¾™h;æº1@놣©5~ãŒã:r“ÝÏÅ8ð½ó¾yAÄ…yÀ˜Ò¥ •†«+®6.)ò"°Ùç¸cÏ7Ò”¡V±3«Sƒš#¯,‘)÷úçµoúÅ>|mñò•ŽAðmÖÓ d¾Âï”w¼üHŸœs¡NÁ;pXÉóBÑ5§Ô…BLJÆk~}²Ö盂÷É×g¶ ÝM >q¹·£§çþçÞû,5Às{¬žÚ~³8Ð è|I€ ]øR(ÊÆ²aõN,™ïÆbõñû5¹ë™Ñ–¦¥|=ON¹Ci�AŸ€ø°Šáƒ—:TïÞ3‘ÇoL#|D3d¢¢L½bSHŒC]”žØ;yò‹1j¿'z‚Öys8»J¸s[Ô�“ï±ÈHÐÜ$’Ÿ³¹˜/‡Ê°©…ÄpÏì[+µ¢‡GÞòЖyÓÞr�Óûæcü™2& q žMÁ#Hq9Ñ~4Áh"J.ôÈ_Ä©&L9âäYtÖs·ƒòxåÊJŸºV[©»¥°ç¼× p¸”±úm{ÆQÂ3T'JöðØ}™X¯ñP±@iܸ°/Ùý†ß)=«¨½GÜfÎe™íÃ0*=X•>êÑ4¿8ã\ô”ó8s\ý H`?=ÕÇ8()&˜æâåE/‰žƒŠIñ ½6a4’fõgE+†¹ªVŠ‘1É‹êñ<O拳÷™7mDÒ9ä.,�’EÒãwƸ€Ã/ß+LG@#  h†c$Ør‰c’õx)Ù!1†½Dø,"P½u‰!óxlCFê¼Yr*¯·›‰êy&‡Ò¸¸ ee׈{õiW³û@×(Ñ…îÈS|MRš‘)dâ±™w}h3g?{Ùñ"Å+µqT¹˜yÁ3"AocÉW8/iÒ!PÇFÞb4Ž¢­ð‰nå3µÑDzáz»¹*Û/Do¸f‘ܯZ¿X“ÏäÁõô 4u®/;ñyM=2;Ʋ÷zi äÕLëܱæÙ½¸ò$&èæšó…¤MŠN‘YD•!Œœ)A^|¥7´Ô<œ¯äÂr>c~ÍÈ-Âæ©e4ÛLyòø]ð=EÓ­ƒ÷ú™¿§Öð êA{‚{;ŠãÏ ’É^m“[ïˆ:u0Ø Z!,_ä”N5ð5œiê{GhZ'bÏH£\ñÚŠ¨ZB´—Ç'É7Žd¼C"ªU¸v¡]èñ¦ðé¸*¯ÌºPä¤ÍÂ0õÍÅÊðkÒäÎѶÓb€á˜- ˆ§9™Rû*e\5 Ãô‘+ˈo<=›æš7Õæ±*ü¢[:^äôHrË‘¼j'Ñ?yj<ÝHL§è[×Ú‚½j›[ðhâÄvûÕm ,jä™Ï>d›{Gþàs^]µ¬SË W%â›OpHf-³ÌÃWœ×kŽÔ�‰»µÐku~&MÚf!@Áóš*¡‘éÅ»‡î8J–}4÷›¹Ï4¢¤§Þè©‘*(‘ÑOkGBEÃ&›gÍ¢üèG¸p„"‰Ú†Ò¸KÔË[ú¤¼Þ‘ò)¨Â&y8îÖh{s²¹”¶ïŠÆ{i=Hh¶8Ñ„JPÂZS#³$w†³­W ªô²´—)y6`pÅh®< šOAYdH~&Isšë,XKŸÜH@è `ãºFzv®à¦cw74bÍ"G ¯‹ö¶ž´¸á‘¿{Z@báü^²aìeñšªÖþâÎô“;ÁÔ+îWm­Þ ˆj² ñ¶D³N®ĘÞVë3sP¼8²µŒ§ÌYƒ—žöt_ŠYç ½ÚFs†TÞlGl!#óžvjWOo@Y\"ö®YÝËÂà–Š×D¢9&Å›­72]¡Ùù 8_]½¼pïí:Ê•°®€°øýòò°ï{±T¼u‘yí>+ø*a¨}– ôøôR’ú]ÈÉ”T–Dcj4ê>—H cÈ*Z­E¡÷d'–k¥W…€xSle¿ØóÏ„â™F×ëIZPÜí»Á`tE vYã´=N}ð °úÅ&ò ‹9JÃF˜ã,çTÉ{Ü‹ía+‚î½yD˜ê¨ì³ ¹XLì÷´zåq‰mO½&U2"‰A ŸE® X„½m°ço¢“Ý`)3´ 3i £ï€C:dàì¢ÞOç4¦¡Ç‡Åüâ`î1¨DEVìDœ’æ°tø+±QXI©g„œCÈ.Ñó ôµ$©5±,;ª É™ùª-Û¼Sât÷‡äû™0ã3«_ ß�`À;ïÙtàìNÂlô}YM‰6)Am£¡î§â &"‚ë=Ì ·Þ©;OÜç >(Þ÷˜Xd[Eߨ=g1a~Ÿ¤šã"öÈBHÏÉ9µçr€›«‡ªáƳn¡¥¢˜ž§< Aä“DT’„øªè=_úÅ`Ø4)èâ;«»Ãë|a¡²¬ÉéØ7ú$HžPœ¾ÉwkïQƒ' Žö.×Ó:~øÖÎpwß‹@6»ûÂGåƒAøŒ-©O"ÊS±¤{;V-w4Þ³'Ñ>ɃÛÚÖÖNi¼¢ÄߥÚœúR\ÕÎSdU]AõÉ—¨Ç!gÉÍÎT\ȯ®£+3d(á–„î½lUÇ-Yät;j€-ö”‡[Žª¼5¯ž˜frÉ¡”‡èÙ3oÒ´†¨M+ïkg>aß_$ÎJ˜oö¾<ò8ª½Ú.Îlßèœç—pÆ­Æ#TÕ¹[³/º$M‡ùÎÍfc½ÅžИš)Z†‚‚&-ÞÅo? ,gÁ‚<ã(€žÒt«Aê\ WòºdE`µ +4­ÛJ<À“mz{Àø\äàDû™†ŒhÚ>4 ΣÄ¡À£Û 9“Ý‘—XØ´ŽDzu§§œ³â/Û0ÔÒ· ‚¹šO¥:°¤Iß›ÔáæôFy»ÏÑkð=jxÜ–0•’-…#¬¹Rú3Ë0guR¤§A¼¾B¨}é°Žç�¸UÁÜ0¯ÂSCŠ(K„/ÞéÓ¬^͹èhƒVæýÀžèå¹§"#{'¬„*k«‡Õû¤õû-Òµ„ÔƒÐUf]áë¹öÁn4ÃÉŽ1TdbŒØÌ&w‹÷zS uÈ”1Pê)ÆÙãIZ†„¨šÂªbÉr¡=®Èm-HŸnÝXÌÊä¥lHm™5•Yj6Ä2å›}/íêÝ9e?½ôC .J#- ]žM†Ç‘½Ëù¤)«™f@Dêg(½¬'ZOÉAý‰— $Í«CÀòº2ÝsÍ‘qgSéÇgÔë)gõZJX2P¡ ]V#²”ˆð­¼9 hØàÌ©µåXŒO"é3×Pé”õŽ«ÊÖÆl…ú#­É´ÖÉÈ÷`깫Ll|HQÝ3Ç{…/ÈÅŇ Eß,Ý”:¤‘?A§„Î%â×äÊõ²TáõöÈ•“º{ŠÃõkÌ‘cø²1 `=WØœà!] f¿·ðD76*ÇÉrÕå ÇÑ~Q)uõði ôA3ë+Íñ*U¢È"5Pƒƒz¸Žð¦€,l÷6¡¢³jò=+`6‘ )ºîã�y¹~Õ{&”þI%F„)(êé¬Ô¥\æÚ爚[èË‹U9)dèyÕCüß•x »íHIȱÎfIEÜ!T“Ø@ZP¤é¤;㨠mè@Òšr¨kÏ#,™r¤ÉÞÖQ–›ñw¤Å«3+5ÈáÐí@AeÄ€\ÌäOüՙйaAXú‹{ù;ì ûÒfBRš”–rßqÇÎb™œ R°Jõ­J¥Í ÃõžÝV9ÆEítc÷kµ¨GA›JM&J“‘Èè·dßd¾Ï°ÌoV¡#¬&\0•ñ¾}Oüä.ž@ Ä€®·< çVÁÎ0·@“ÌJháX§i\ ~aÒU ˆŽ„ X¸•ýÎ'’ÍqiJ -àö ¥¾„{϶íºVÓÎI\Îð.ñ [½ºGúÈy´‰…C%dg xš4v‘o½?ˆ²âö/::¤ÉÞE”ëãDW~¯p,�¡Vd°ÖôÞêÆiÉfÙ…ÅÎ d>K‚§~�°({;>žªÇX¨aÖʳX[ ßt~ÆžuÏWÔàLaé-‚Õ×–Ö6ÃòüØ\™ÃÃRšåE§ ê>3{Ü}µ€Z±ï#=¹[G%E¶CËí;Å2šÚ¥i‚Pt‡¾%ǹ,Ùe/ Bw|‹ L³²oDr|Þu*„hPe[ÔJ‚.šÝz;4´³`\1?›{<"Š]Ž`%;? v؉5~áK¯¼uíibk­â.ÃuvT¢½]$6¢6?7¶$zJx•ý´´{6X=XX“­–´0Ùu•oBå3�Ý`,`:oé¶#T<qêò«Kº®*aõweχHßÁp…BŽ–7?o*y×›FÌД™‘ô¶§�ú±fµ±b:U¹“— k”·Ñö8Ý‚Š*{DSÂ^>Õfnxü8ã¡G¤rrPÔâîsÑ^^µÛ�xš¢Ê÷:;Ð@“zËDɨÿ¢Ôžê›îöòæÀ¶&g½•ÖDñYm{¹±çîÙÉ»ÕaÎã@›·èX]ížlÑÆârq•¯±ÔêÕ¾�oNus>)ÕÏ($‘KPz¶PÜ–á‘WäL/\'ɸ öá=Íeç=Å-^órû:2ö*>é+ã ÅõÇTt)y¼£$—9NR1%­M0@Y“tÝâ%5|+`uHÊÇ C©šxi¦Þâ€[ºî‹02+'ÍFhy ,>Vp{€ÝÇæ(uÜ/~‘ ÷0‹¡—\Ù'ÍUäP¡èLxê½ÝÑÞ‡ð4¸ûe°»)šÙËÛ.æò€]»3íEõÝ|Ô oP¨B¨£Ì¨£„á“Tû Ef»¯â˜B²ˆ•,¼Œ ‹†)pzË‘ÃCYÄŽ_q1¹( ã9X”EêF8 ¸êºi4m[–Hí´,Pcç­†Ni+¹gÀ¾¯C™‹Ì)ÐÚr °”,–à=ß±}ó€ä6|Ú­¢Q‰_Ýñ P¬ú²Ñ¬a8°‹u ZÏdNˆ‡`z·þ|«b’xõ®#ý¢á©ÖÈu¾ÐÁ.s 5ã$¤”S Á·LƒAé¶•ïÍ8{°1ã+œÌ ‚©~ú<JÍ^p¯AI|ۯƣ2ÑޓÁ|˜Áƒ¢ÇÐq(iÒ×ß:Òìޟל1Õq*ì=Pk6~åRí=ÏÐa:Ö)°Ä™#Õ¬BÐÏp-øÈÂr“_<PAr P¶*‘M ½|'zãZ/Šz0ê1¡ä„ZRÑ[¦bZ F²1´óðiŘŒ)ÐTøÄ‹á‚ÛÑtºú9ÒR°©�Ñ<Ð^ß;¨•·n{/ñµÑ¬dÂÀ–l/PtÎ%W¢åƒ¢»$TŽÀB3×쬴XY¸~}ಔ^ë•]ßÄú'±LRP‘9”: ƒç àRãén$*—$å¬È9ËÀ6»Ãž€ É>ê†<謕‘"·…7VެDæÐÆÈ‰!ïÜ”îÒðž©Ï<´‚çTà >ÞnL  ¼gÅ,`3ÇYžµÌFzÖ(¥Ïö&àr¹µWxm±©½Öóe‡†÷‹ÚZ_|¥&v·Âer:³‘VÚž=x8ë</ôI:éXf-î^—•½RêÔ|+G6âR·½½HÁXµ8oǶΠjUa?©ÏÈï!,#8å3ñWô@ÃS³ÖÞ¾I‰*=—Õz±žxvÔ 0W)O©©‡êf½ô]ŽAƒó!2z‰¦Ð�—cgËnSl1Ö�˜—¢¨¹Nòèx3CxK?«RËÖ7…UòTê=yotfåžÛ·]XPSĆº–­8áZûÒg”ŠÐ5› l±â#štãV@@M˜ŸNÛêÛ…qR0žwïUŠk:WöñÒ"ûÜ”Jyy±ÜØä2À¦.S+=éN²V{·Ej"ñ$ËZ¦7b³ÅÓDгÉú1~‘‹ð}+ÇÊ™ÒÃ7! aô:yÊRz/6®_à*ê«Êž6PwR”yˆ=7A´ùAÏ…™¹Ÿ.Ú ú¬ºÈ“Á3¼A¯X[Gª\[˜›5PfÀ2<íÛ·DÒY\Ä )ºïÀwÉ+ƒh^4OÞ–ÉYk˜@—Ú8Q‡¢i?­ñ¤84@6¾‚HL]nCñûE¯ø£y“Ô 1Q”i}¹DJgé«O•`T êÆX8Þ‘÷(Lc7jÁøÃ}ëöçÄ<Oµ^ÖyÏÈvgÆ'½ø£.uwèMªª&ãÓÂHajÚŽÊxq8{¸vÜ‘Ï÷avSŠÇ@™R(??%áë‚}@5ädÆ*Zº0^›Ø“à/ÙØ5ýÁs¹>¾b°3³K¹Í~®!MyÏ4Œ€ÄÛ,_=mVšèJ¯CàÜ àW™¾éuýÎWíQ/ŒP¿Øô {ÇŠ´Î°±–Ñð{¡^ô„¬¤ýuFаœù0qS0%‰LÑ;7ÁN;ixNÅÐJ»í9 >EcÄàýFQz–¥8êÞ!ÊS=&Sþ$˜¾÷MU/ëDƒa/w^íÛ2îõÔ“qJc~X}vßvµ•H6 ˜qéí³©Ö~"N;jK|¯í‰Ëd Ä–³"ˆ>y¢Š ·Ÿò¢ÃókâgÖZ” ,o{˜-0Oó^WS"ªf¥’·ØØAÁºu^`Ï{5( º€#:Ìã3‹PR læìaÜ8ñ¸‰v˜eŽBÞºì³ÏÑ0#ôi ”ðÝ#ÊU¾�¦d̶š«ôs~ª9Œ—è1žLpò¼æŽúA%ÁÂ�c:ÈŒ~°CªôMñg´"T; DïV‚ǘú¬sj'DSoaô­ ú¡¶ƒgQ˜‘Hx.…ºC𱂥…Ÿ5÷õ: nm«»�ÊEÖÙfVîS ?§. ÒYiâ{/ùâBø·Þ)a}Mçé5-/Ú^ÔŽ÷¾ÊçJ¹þèuêÌʉ4ì£ \ ê”wõ4ý]uô¸ t¬½ç³ s‰n†(~öá0ÏyÕïàú½fiÕÀΧJ6þ 2Åh6 U;Ü1 {Αúƒ`A¨;zql°Ò¦ôPp�• çÏ$ZÙê¢ñÛ¨ù3dÅ+»„jì÷6^Ž)Ú0Ö3‚®µN±ÖËwâÍ3EQ[öØn}§¡¾ôÍÌ9k>hCfÖ /–`Š-K»HÉ‹é{íIåvT¾Þ½“|X)½àr[áPYÑgq„â ¼g«¼Í>æF?ï Nž—]3*¸ä²'(ÜEùl³^`Nl5¤”6³w•ŸªÄð£¤Çêý³sú{?9>4‹@ -z¢2‘ª ‚ª(š Ô^+œ0Ú’úÜjY†ÒûT š¦’ZFBŽüÕÚ9WP`�sG¯ŒÃ'Íï3nm>Xç.ôâ¤GÛ­Ýe.œc²¨E£¯uš=1N: »Î4÷b“íÑ—¼=Ö-ë}wØ‘ÅÕˆÑwZÜÀKàæÌ, YŽlµR=­zÇç‘X3­‰»cï^×h@…¤U,ßRïÆj«õÃ)ßWîC8p«èkÁ:ÉÓ):ÌGï4äU‚&R¼[Õ¹¼ß‡ƒÛ'äáöÜÂz)ý½\~UÆBd&Ó¥€1=DåîñÔ(Á=ZcQZN{9/Ç#:J¢¾é§ •tü޸Ϋ¦=¦þ$Z¾zb#eûìT'’Ôžé0;ãZ•©ÏxÝüØ'‘.�”7å:¯fI,¦è´Ä/G‚GÎâ ä–%tùÒáŽÎ V @¤½…W¸§”A„Ç:ŠŠ£& »™„ «¦&©ß»èTï¢12%©†Ož3€e”´  æ¾0Õ¶ ¤vïmí-9‰^1Ï#…ÇÑ•ÆÏb •QwŠ­‹Xá+’MÈ… Õ6 „³e¯(üÑ>Åw/¢£_ÂŽÝDä±:>Šãcˆ›FÕÌHî‰ÃC"xõ2�eãå'ÕúÁœµø• <ÓSäÛ÷,ßBóqùB¶Gr˜H‡ÂÐÈPÕxvJ°0a¹p>Ä™…§:â)aj”©#nåÏqöU¥%ê³0ÜyPÏ © ]¤àíóçç}[ãXbŽic9aôÒhjÅÔLËZ™ª9*JÄ–HE(%â5N—´¹a"ž Â{-?É&}‹ ƒË*ñØg¦(„·8œz (™ì \ìDZžÌ]4Úì±ö¾’iÜ•#>1¿ÅÀ]/ÁÃràW]Ue¥)�)ßd†±n3ù)-KrX 2‹¢Ò Ìz¸ËYYs:ާãàÎ a*î!ø&$…‹X86¬p¯öΓš3§Æ=ŠÊrœÑ§ ®¡o'Ëzkª¶Mn,H@ál’Ê…‹ <ÄýÎu[_xák‘é]féâ  ß7œåë› Nrž³µ»:÷@ÕÞ ?ÒÎ|Âç³ØUbñ'1{8ï÷¾Z�e’’Uq8…Re0(˜Â9ÎÈÐÒ¬ž`¸ª@ðÅ{}ç²o:‡¦`‹=Û¸ÒšyÛ)Læ—¥”§%ÜN'þI·}Æ2SŽzŠwGEO$ózÍ)ÞËMÙ�·­—[¡UÒ\™ëêíB:üà]<µX³ºl¹+: ±âE~8ÆÄÍ@›În4#ë¢ñ²g’u$±<$3Q·S^;©»0µ×-Z@ÉtÜÛ–ÛʶÅ!·ZCxŒ‡+ë»Rýh‡mì®Hø«Ã†¸ÕÄKä=®ÐËÍMJ DÂßï»Èœ¼o«ï‡nÖáù°p²²é¶cð$x¦ÏÞ¬ ;Ezd6O Q_†iA‰cô“ŽÝkÁrK²AìX¹ $D’t7yßÖ´RA¾V,†¾JñycëpñŸx@@ŽCá­:¸O+ ‰JqqùóÔ,ÈmècíçeKh'²^U¯¥d­ZtX.M-Ëz7ΓIî{èªÒb]»¯ªž]¾Î3¿·«¢·Ml·o·*/ tqj`÷åÖÀFÑÉ»ÀÉœÃÛº1`bÇQÖ2æéâ:Ó+|Kœwxê;<ÕgÒQ­G?ßø£kÐ鋨·¯Š_ `=MMcÕ}&"tSäÑóÊ=¡EËËNqbv÷ÀÜqAE;E‰ Ç›N×{réÛÒã;ªI¼±W'3ûÞ#•y orÂïxùuM?¼E­ÐÇxÚoφßQèVØ„(ä¹Þö›^4zGPònlNp^²åŒŠ¶ƒ<½Â:A¥]§ÊŒ @Ø{Ýèep|®ádz}õÞ¶<mj޾ñÝ@àw âõHè)k;ñJÝs\-‹nN B—b_/6vªx¾¹#7@Íï­qý":=:ÊÈx–ýÝ1Vv• ˆ’÷^(faEQÎy¨9)ÄH4lÙµ-f„gÕ2QðbñÞ-÷ë[x¶Ì ûžïɈ°ö}bŸ¡íõ%’y�é©ÞÎ<d{"^‹%.ÜÒ"“çÈu^ G[—Û©XóS%}/º¥`†úˆðl_ó{‘¯6"\†FV­î(ˆYlf³$«ë)ÆqrŠõyÑ™š¶ö9ˆz�¼ë|ópS›ò™G›‚œU9ûŒ;çð*­™T)¹ã#‡ˆ¶» )| !›È°Pì)Kt-¤'¿h7o‰ôž{ƒ–ªUt™v—„H# ×YgËâ±aJ\SA”yô½©ûz©Ü¡N>iƒéÈw³æ7>C½r›Ñ‘=¿iÿŒoëÒÔ—ªtš÷‚GC¬û˜2sº÷t×'N/ bU etÃÜÜûÅ^¸lgºÍLPÉ…½ö w¬2jZÜKµè7¡õxv¬#ƒëD;©h%r*]4Tž¦£€Úµ¥9p(żx>(¶V0N:XçëHl•eLÈH7™o„ÐÞ»pŸÒ›ƒ'/n:9x”£"ÏP7Ú«òù/âûÞ Í¾a5F0rÛ••.~}‘g¾*ƒƒ·v…‡\J3QÎÍf§Yï4^<óv ¿=óõF¼Æpð.“%šœOâñ3Èù£nqx¡Dcg¸¶Œ®œTîÒ¢ •JS¯)ùèi-TaÚ¤“"aÒmêM+í>ˇS¬3Å\‘ý*smNZ×pÑÎвD©sžií Ï¡`ˆµy>4>û.ų¹oóv÷yCÆn»¿ðå½<yÃ�ãä3Ó]1P 3@˜}Ò%E(µå‰áåå® eé°a˜6€dp‘fh¿¨geÚÜq‘Á/Š<ó9a"N‰Øxð0´Ø`ßa¿¨ìxF½}÷öMà°¶ö˜¡ì\Ý ~€¯«²W¦â“zúŒtÚ¯ Á0ÄxÅè¹*nøm-“ŠáEb§#+»0æ’×s…#nNNÏÆ&à—ª°4†‹:œÝ¯.z ¥õP ®m͆‡ ÅVu2z·ƒÄÏêbêe[ðŒ.Å2ØÎ²†$Ì)wMõê•8ò¾è¤ Ô@¬Ý@ý¬ÍVcÈ-7¼Þ!² ¾tŠ302"R%<ëçž¦á £‘)еql?ß}ÈkƒÈê‚*w”  >izʽޠƒs  ´i…qTϪnY"é"]%}xj¸VÂçF®±ÅÞvBn›/“;GÔ‚|’ÏŸáN°lª¬—î¶Yvß ¡ß<¸X([z&:¯Ÿõˆ((€×4Ù >€`Л8†½›yî�DŽ(ÂòøJ{„Õ(Ë®¤8¹ºöY-Þp™w®§Ü(6>æ³a5™!t`{Ú9b�€^+?È‚nê³wDüTãøm�ÄmÅsâQ*Æv¯òéaân?Ô‡ëoÌŒ¬$Öž–§Ö^°H­˜Äå/ú“Ù@éd¥£Yøa ½£”Xí ŒT®“Híë%EŒW5ªpäMñ|€{z¥­Qp¤eÎ8ƒ`¢¦ÒAÛGf¾½vê}ßô?ø´}–ˆ?iŠâ:a `>#v­¦»·WórGaÄ ×_æÚC p„“%×óCSÁ²I°Â­ÇNgòz°CHÝœs ˆàD€üÌ‹W[hHNóz·=áDˆñB…óJ/?22Cí{¹•6=IÐC‘éHÂÏgâqHVƲ Õà(̤åÊ4<)ržÐÅ®çnd JF™fVòħ?ÍÿñÆÀ¦¯®3ñ+åqz¯m­r)»œ.\YÔEÅ ‘û“"°4Rzôtm˜zጜöÿO˜ãV„@�½4{È÷?’%Ç#ýÌé?AUÐ,òNÑáˆWöí7€ïãimÔÉÓŽ‘4Q™AÜSª°PW‰¶ƒ§ ^›œ‡Šã’¬o–6ðUŒ›)[ÉÓ»v$º}¹YÐסçµyvÖ©ÖÓfQ: »!„À�qêsí Äíõx±J.-KUºéi W:Jô–¬a7o±¾|©o_Ý‚tç­bí”Ì@™kÚó,U=°1ôèxuqõ`:9²ßPˆ¹ìûyбI\Ž eØe¸h÷ƒ'éÐ9­SiߦK¡„ï{í¯ïH]0„#MÞÂVªpÞÇ Pù²¬-^Å‚q~Ïè×i:”ø$$Mý)€:»šÛÐú ô{yÚ°Ö+PÌ èzkÀbëkqéîmÄFŠíl•0£™ò‚tó|ÅkßIcð>@Ö!ÕÜ"ª˜ÚÛlÏÜ$˸2¤HLLicWôÙ«æ[;c8Š’2ùˆCq³ªði=ÐKH³°]›E´p|¤ozÏLúÝ"KNjMbwÑÓ:eþ…`"ù™â…C›7iŸpó+H}!¼(`i½‰E–¼J¦Þ¾EÝÊ¡Ün»£ŒÑ*PŸÛgo©BY s§CqÚ¿‹Ÿ~†À3-—i5~OFyƒ tp _YåÙ�êÁ¢z¨Ð¯Ý_ÂRŠia¿!Øó3ßóyÇ*�†™tÆ]±6V{Ö!ëyTO­=eê‘#y³8Q‡ws²ašÃ³G{ÜÆœ.ÔçÐOÔgxG<_‡2;èñCàÞÒç+5g¥TPD¾A¸„åÖ Y[DÔz÷$æbá½.Öns;îJjaN̼Ÿ÷÷*•ñ`b¤Þó¸)"I‘m eaMkÚn2Y‰“«m†UvôHŸ¸ÙBug2>¡Ž(ÕxaZ×êVPZ´‘YlÞüÉÀÞç:òŽz›Z=Ft×nèWõR€’7ý gÑ=Nƒ øàN}]_:†•S„˜pì=¦”gqý”µ† Jw¶î±‘cXVqG¼ÓÂé¨ôÀ·Èî‘ÔB×À jHò )¥hœÜboîw(Ý'#àçDÔôfÍͱ]àžb¹Hsmuã“$‡lª[-yQÁ}…ÆTœ Pq_Š˜ùAàͬ‘ÄŸ‡†¹÷С4*Ò‰@£^§÷ø‚%qÕÖ{ÙÖç^¬žÁÖÌììQT£" ‹½Äž1®”Y‚Âξ!%äaN§'WšãŸ>!`ßôKë.;",š·{wdËž—ÑæÞtÔ`&"”»:ƒôQ=åœË^ÅM)U¡wÕ~°BG°ï…hNV?S9±+S\dÛ®sQ¢)]öÄó`BÈàsÐïÔ„EƆKë¸\mÍU9ôJ—«+%Bu"÷¤ö­C†û«!;d¹íÚ¢a¶¤æeí‡ò¸[¤gô<ÌŠ—^i¯<,B›£êaxYaÇþ| Ö·œˆiqSÑÕ”°Ürá&™¢^mH ºðæetò<s×ÞGg�Nùêx`­E Üê`ØšÆ~7Ĉ/ÁÔž¹Äâ9}SøŒˆ¼,¯’>›îÝãó#™QïzO®ŒJªmq[Òëò¡(­ñå•!ßcÜæ8NÅ¥xH¹þ´²Èáð/³¼`ofä«8ÈÈ…üDh$Eº«ÊQh– ø^t¾šÝÆ`õ™±îvhÈP ¨êæ1Û¾{ت5Ç®,1üì•ÎÒ!¥ºéõƒ6¯Š K|z-‚Ëp/^²"Á€p»`ö�F÷Ï‹­»Ðlõæu™Âë,¡lnÖ0óæÁ"Œ¡]â @ô:n<KsùöÓEMàU»ŠpdaØtZº§OˆiÃÞ÷1è…~æ„tQÃ9›œ‹H½Û KÊŠTÃ}!ÀáÆn®–ÚÌZ àvÙ‘pïº}©oØò#– *9Ò@1tÞ=\Eʈårýèù´`¡à¸B=Ö^ÐGéÓ^Ôâçp¾ä k¸õ Ù"¥7¡è¼öÆ-;OH“lnwÉ;rE«Ö–~­û46¯Fcƒq8ç¾É×R«¯.|9Ͳ^Ý$=¢Ö!?œöŸÝý À^j‚§¶ñƒõÀZ²ÔÁ¨¤ÅgÚþô0×LúðÉòó\L ë0®…žÇgp‚pÈlØ}|ì’*†ûŠÞÂSÄûâ@ð}p¶\µ°«†Ò"]qoHc{bî¥cñHÞ¦¿à“JNR-_¬ç>Î'hþüY˜¤)U³´0ÁzŠÄ³»€,@´Òd2Ð1Xˆ? Þ*]²ñèà”Í>Фg§ÍSÕ–/ lÂ4“bóTÈÓõCŸKÍâG+M ›“N ËÀp‹ØyìÊXJů‹ûEÝŒ…IvèÎõ3Î}lÜ Ä–`ÞËýdý'ˆçI¨rä]³üLT¼*7r”mÂ^_ø%ì67خɈéÔÅÉ Fºã/ŸMnØ¡J Ò‹®õdä¡M»éò”vøïs>èH¿Ò ák}¦ð ¹3Ò†vðÕ34:¨×Q°œžª²j«1Pø®l¹·žÐ:8 ö–=Î;€8^~÷Fïá öXgݼHf¡=JÚ™F?o³tz&ŠvYÍ›”ω2´aCõ™‚ů/¹P¤Ábp·Rf²Xk9Ý`�®½š+'¼¡‡EVé æÉ± Žò\#½S줄w —o([Ô^ü\ϱè6DXVèa&äø¥IHÅóvb9c 7hÞpXzì|}xnðv0ðm/{¾Ý˜ê{¨p.à A© ÛOï3Jö¹è+¬7j3™G³[Ï+‹nØ£§S=%}tõ<²pÕ'e$<t)UH¼À°x4‹Ѓ¹V€cda_•cdŸZ*€""x¬šÒ{3.µ3]õF™C§ ;^ˆdqë#>ÜÍÇ÷FîíƒXºŒË,P\Ä'« çT¥VJ#‚zËYÖ—ëW‘§áÀ½ÐïÅ ª CÔ˜; O¡>†¾…¼ ­_(´ÓàÑ>0}¼N’±ž[©ZQíI0§†à{ç¹³EEìÌb5ðÌú‰¼®¶QšvÛÑ{Ñ›F•«l¦<‹Î…‡ß(¾ß³—0« ßÒS æyg²(á2e$ÜúÿIѧ øÑu”áD5'ÓSû™‹Å {æËÆZmKУ 5²ýŒµ^¸Ò–mM*ró L)MnÈ@”D¬ÚÞB í<2Œ'ïŒIFyÂî˼—Ú�ºd\ õ¸‘R‹§s– KɯlUô.Þ¬QiŸ†‡7t‹XCãë7^ΈŽy¬Vm’1?kg†ÊjDã]î’F‘ 6%¡‹¿\z‘+¸Ú}%ÏäÄÏØ{§ü´œ‰/›‘$'JD2½ï"ò½]ëTרd|×ñ¬ ëûAô/a| rãB£WÖ¶âS>ˆ\ÓZÂ6agÞ Dí-Š|o«€�­ªï©ˆ\ª>Ft›òƒ.åò­S—a;z®;ù œHü$b0WˆÓeù˜Ÿ ßBJ(:=‚–=_a~j›÷ºy_ Õ ­+õ« ó(îÇ¡H~¦öúÑ#ä½›k$~¶oÒ4PK{Õ¾-™Yî3pà«'ž-WþF|ÀÑ,[MÐîN~Þ)Šyû :ûÀ6SXÌc!9¢ç9Zί™NÄ¢uœ«¼QAÉ>Þ÷ê´óÍÞf'jUøyÏæ=Ýí{×ÁyË ÜÇŸ0˜?—=Ò2š-S}ut4™â‡dE╊ {Æ"æ’Q{S@’ º|ñ¢&Ô£÷ —jR²Ù¡zËb Âs\�&JÁp®)‘ó´Íq—2ݙõ©6õXãbáapÇsõ9Ae}¢~ü8„™¸ævⲋ lˆßF¼ ]8÷ºuç„™R‹aëžm%çç’,üb%Ûæ‘¤¡=~ðppšDO’}Y¦R|µëµïϦjÔ>eQY–+?VZ‘{ κÃŽ½Ïx9i\BšÚÄ©Iƒ>ŸéE‘§V©®÷ŸƒÒ=hî' õ˜Â[e‰ý;rÊgä,ŠÛòç´9­´ŽÎ%8'¹tØٞ¡TµØž)®6>Ъñ®Ñc"e=¡ÁNt^Ÿ†YRÆØ&ŽÎf ÀŽ'OŽ®hz¯ÀóZçi°ÕTݸ`Ð •€B´"C€´Pªº–ø %a¤X…>"ÜÙpäÈ£YBôtŒISMàÇÅ‹ó¡`çižâ ÀV«„ ?Õ„;¬dh;´è|.,�6ñÖcØo®Æ˜{¿W`ch—Ñà^>÷Q x­Ü‹I ÕSŽaÇyÛ…ˆ>9¦%Wvz¡ªÝâóÒS½U6P„›qÀéDÇŠfÈæ°´9¾ç†~†Ï §>r õ¶ˆ8Þ©Zà|ü2eЛ™i¶D+(å´#ˈsÝ6åçóâÄ7†¥½º,$~/ášÍíÆ�m,c“©Ä,PcÏØ^MÕãtù»6Êl–ô î¸WClvŠ7TzðËŸr>äÖÛ4.ÁzOÛÞƒˆms§d}åTš7Ã�ñØËó‘‚ÜJ‚ßÚx±ÐC~¸U©VcP�3uÁ•Yv$12¸›rϧïg …æݨü„BÈUI:˜ô¦ÚbÒ¯6ÞZUë>“À5bë.¦³Ü~CvG“Õ×q í /‚¬¡Ñ¬±m®MeL¾y|ÆÐåÁFKHWíe%)ã÷Þ…†Ö½¶S†ó±}Ù©ºXŠ­üª€6MH3WÂq£ŽÓŠ…v–ðŠ5å`O0Á0_Q Ï¡ÊŒ\2Ó‹Ã,î—dÖôâm(ƒ“Ä"9óÈÀsÉ!LB/|7ÈÆåŠï^•À•¦W,<Já±™}ÞL£ã.Ü>1ˆ"AÒáˆS×n `o¶ÜÕ±Ûä…!Ÿ_y¾Žqµœ«0Þ} uVÎþs¹� ¾Ë€Ä|7@‘Œ¥ì€J¼&æ Ëïåç#UâÇxwõîÍ\¾'tÛõÛH!¼ yõÕ½Ò0)ÜËŒò—Fù Äôs¹ ´„=ZšÎ“9·DqX#$Ê(€®mŒaƒgô¨ÖÅ ñJùµ¦¹ºë°øŠàš¬>ŵ0RƒÇ5Ö}ôÞD­Ø•*‚Æ=vl«2‰Ãâ"í|ÕoN‡’ž_nMEH†§=ÙÁÄsk‡:‰bº6å�(ôÄ~ÌxÆnÆÔç¼¢rŠç3o{µ´»ƒ™Ã2ó„6ž^íR]§×Šû¶Ù½˜‡Xë1‹^(§?W `ë¸Ä&ÛæÛgñR¦ìù&ÅŠíÎæ2’ÊÎ!¤«V¼WA+oÕm ß¾˜Ä¡=uö.(BîHʈآ5YäŽî÷IÄ?£éâ)De¥t*q<-œŠö®œ|jc9ÃnzfýÆ¡áxz¯Æð¡°“‘ø3î|Ró’ÉPo•wžHô•¨‘r Ç.ZÍ„#Ì _ŽÃTMsçY·Âܾt¸ba,˜^3òŒ¡ñSÆ<oºÑIÔ7z ˜Ùò,9á‰Ï#l¨8æƒ)(CÊšP¿µƒSÜÜ"Í%OEØok4s¤ewNio-ˆ=š¢üæÅ ðïÂÝ‘Šw ÎŒføÊáB©ä‘gÖKsŸ÷RZëQè›Gâ¬äkø6Щ!Ÿ!9M›½7¨µg‘¢Yº÷Ð8>‘ÄwHÝ>Lçk/”e–—Â5ðFc ¸ìè)jæL€‚æò>ŸñÌ‚7Õ´ïfqTP$ö…²ÐòT“A"OU½Áá}ðÁÛ ØN÷z\žçx,ë´SlÆœ¢o:§Ö¯ÙÓʅƨ®•7©O|ßohæÃÇÌ/ŽcOºØu쎤³±²Ë6ă¹ºëeÀðÜ"/!­`#ödñ¥i­Ñma+,è\©'VKš†A¡Ñàîg—)ÒMÑ*­s˜À‘Ts†ÈÕ²q‹mG)’Vån-À:mCÏaåCiâ$”´HaÑÒ¦óU €jÃ=c[|=mf ?óÃg\•ìM D2皦ç1AÊg±/]ß3-ŽŠ79™|tžßC:5o„EÄ‹inl</Í.´TFÊ|Ϭ¥õ¥9Z¥¬éëVc_[u{Îc:ª¨mËC ] êR¥g9d ’µ™]\A®»vÀµ_±ô^( Ñ žÚ0ÐBÊ{ï°¬¹G�û¶ŸàU¢¯½×ºØ\ˆª^|zì^ÊE víšúÿÃØ!Ëbx•QJ6;šþ‚âÛå§ïM–ÛF†ô�1b¼ÛÔÂѹȡÙñGÁ^æÍG(Ð!ò „¶fÃwLO—©nùêÉM>yÒ:4™ô¨Ö—óÊgpMÉXVÖ¤×.}mtð®…�ÃßeÕ»‡ûœ€–Ù\‚{®]˜VN!‚zï„Çy´XéÑAN5šDI ÈA¬9W§„ËÚ{bv%¤û6ìÑÞ ºJ–4 R‰WA]{<¸¬™×1![Õ1ˆä7:½)r†žëé¨Õ<Á˜zúòÙ1xhÖ“nŠ çQElI‡‘¢Ä:tÍ~!*îE%Þìa0/ÜLAáÁx(“ÄÙ×£oFѶGœTmÄú©aZ±«Hy³×£ÂçC9ÀXUÓ�‰Ëa*hšžÜd#šu°Pö–ÓÇú“ ~¿©jW­Úg˜? ÍѱĔ‚p6/.îÚ“ Û öåw"ö IL®_º³Žé{ççä–.‘‡°ÏÀ{üŒ‘²È%¯ILÍ+ļaë”qL“àðLÈbcº^ºKͼ�Ùuh@õÔ—!aƒÐ‡oæ÷.«²´­$2ž.ì£Lö—µ¢Šº{¸ÏÉpß>Ò&‰JÞxýDŸ¦•Ý!nrn€.ö-*m až dh׬\uM¬˜ö<Ô¼ G? 6æðbßÞ® 7§Q$¿¥˜Êc ó±vŠuku0´QÊâLܱ-ë8Ÿ×Çö€Ÿ¾UEp~×R#ûζнùËû ³‡-ÏûÌ(ÜØÀ†Çs¤ÂÏÚ 5f¡ÄÐ}îÕ›ö”"ÜI™â8§¾Z9dåc§ À\Tg\Õ46há‹äQ0&k-ACÝ=õ  ‹WãåŒ?ÈÞ§oXº/÷Ùº¹…ªƒB¢¾íNoòÆt'¥*¡@â3€Ι‘Ø'Bd“ ZíJâ—Õµ7WRíæ4ÎÔà™ÓÚ|Ú¤§r(º.Ø‘p¶œ¤V’4nìøg5­‚z„r½Ÿ\R&ö*_…ïÔX w«Y°SbÔwã"‡pHçi[ë£Ã&~,* #d®æ8†¯öŒˆÞ³SÁ0Öçî6Ì/e/æ“ }ÆÚ˜8Êÿ¹‡Åx*ön`À—€æÊ"prmŠŠM1ØÐW/Üa…ŸbÌeZ H›–‘@+ӯþ­9 H’ƒîšC‚‚¹679N^}=å+O2g¬×ùɃÿÙÐèÁüÆœ@n]Òx)Ö’Œýí¼c²¤zÛüòúb¶§iÝlîAsRž<‚AŒô8!x’p6KÙ4“ß=hggêklqáÿGòj†ŒaFÕâå¾q=De¬2´þ fÓi6rAÌ�O·ÕïÔ6Þ7úVYäaõdñÕ8aFå—8R6 g](ƒ„3Bè"D–VP|©£ñè�-ï;·ðwÀE w·ÇŽq•CyφÄÌBUa5[Þ„oÐSIN§GïôL<ˆG Óé.öAJ<ÛÊly1�ºZrØw„y› w wŽ•”ÈÉ_ ˜FѪ;·ú+x(¸² ¸‚PLØî*y祥÷N¢K_LZlXë¼òKm¤S Œ˜7X%lê/{´OåTñ!Žyu?*©÷¶u¼.¬CÞ:Ï<Ͻ€ÈJ  z~uMTf@=úPñ‘ÿ"£*ØO†hÊžN=MœÛ·Ñ3Âì€.%å^ÖYJ[LÑ„ÉÆ­‡8‡¼×6 *ÝVþÒ¦…ÓZ úÝà™4Á¨Ûû&ãŸdL÷H AY²G”7Œ,I,K zä ,S-¿HxW4+w|~k1¡JÙöz^t°ø+Œ/E¬¥P^Ø úU oìÛ$‡èWr½¾Ó*²ÈSkWÆÃÖcGâêá+::I‹Î$~oF †H® AO&^S°óP^Wî[Æl_5‰#zeZë‘ÿã%ñµ°¿ÁMÚõ˜Ò£¥&=¡¸D²5n"š“dãf«¶zPì –ªã"ûîš4a•÷ØÎžKï›ñD�’ÖÅ勆'‹7àÖ5„O82Öé5%^ÏyykÏØlÓK¿±ì"`©Î# Â*þF#ß¡wK>&±vc”3fkNñdhL7¤òò•ðË×DGƒƒhƒ}ltþDo—; cd Îï±K¨(©WBãåcÙÒ¦1¥#:h {«ZB#Á ˜›`çE¥(Í»< 'üÖ&‹eÔº»‡RA»k‹p/ @*ÁÐt&ËÆüÔöÀõøøJÈÁöC#{ÝJÅtâõ’Ÿ5…%UN¢°Ïibʆ˜ít¥'dÔT¦Gžß¦oÑ”_l®ŸªÀÑSrÊ2£“^…‹ST©Žx¾wèmIÏQÚRQ澌·"6œ¸ïÅ:;Ƽ©íž…»�`Ø®P5_tüd£Ÿñ—…Æmt«¤='bø Jߢ…Cµ¥Ÿ–WÕA*ÙóÞËœòôQC¡S ¾dW¢+êÀ ÆÑnÉXOÓ‹=X„bðŽ1¹žë»Áˆºía!c=‘ DÝx”Á‚¹W//nèŽ\µ¥0Œ@XCèVSQÚCaœ£ÄnxgWp…ôì z'G»e …ê{‰”+¬–5{Z¢ä0“øÒÉKUt ëÙRêMsTº3•žAÊB#¯`ÔÎßï»Ô«;Û²w}‡ÉÊw¬çl¾éð,øX¦ùœQ{ °ô\õÆÛËXÑ–"]™gâ@½ýÞÊh»­îçû ÂM>ZP&Ö%òj‚a{ ö¨ $¬‘Õõ0ß3xñžŒxõZ*i£=Û¶¬‡lëá×°¢pžk§X{<&›©¡o´ŒdÐPH6væ©5Æ«wh·3D€2ž–L¶O“1deÏpE‘fæ8†´¯VÒ-Dô%¢®æ»ôÔIàÊéâ}#³„7ÍàÍbŽ ™m`%:JxÒëõzV â ™íÄ¥ýkµà™¿¹ó†ŸOyAA\ÞJQgH­|7ˆÏ7Ûd°÷fO•ßÕ³{Ð%ªÁý.½R÷úhaEÛÌ£/³µÞY=¶ÙtR»›§±Æ=W d@¸ßtü3û¼Y:(²Tré�£pB;ì¶„ê†{š’&E«ÁJX¥Ü¦$»C¨'Hèã³Hm/+ÙI]äH–äy™é@âz>*ak/MˆzŒCµAf¨Ð¼jA‚2ý"^—]ãd'2ádD÷ê™y¾Ø—-}*Å0$=]ª‚´ý¼Éó®~––±"\ ªÌšzÈ•(²ótBjôYÙi°7ðJa nl96A¼ßBåƒ7y³ë,}?Ü%>Îaa¨Ó¤oÈr_[Âø-x‘JÔ³‡þx˜ $Ý­€!œ» Úñ_£oY…Ѓ‘Ø™¢‡HË/ùÎV®šœgÒÓN¥’ƒ€Qqç’¸†í`G¸êu<œ&¼êñ–kWÏ=—ÒŽrªÊ—’þÞÜQ×mÙ~võ\,e0ß@ ¢Ü{ÓMq«x²X wº^œ]Ü:iìµvtàFAÁwvéKqv¶ÎIÔäªnÒ€Õ…O©ƒA&0À7J`%.«”Æ[«Êh|‰"J¤šàâÝ©—æìܰÙ(‰Alj 8Û‘îãJ(1$èm±­(Â$ó ôàݧK ü‹IÓùÁôsß~]úÜØßÃ(~õ¶ºrâ7ñšíò *X—­c§©7œaÑì+~ÆšMÓ'J¶X/Èp|œêÀB¶ùûÞú9{ÊG½ÊÓÄèÝ>{Ž’ê‰-™„Å8;í´¦òdp�iˆzkb¦T…L=E Óô»>F<9­Ö³…ËNóîg©åá.žmQ¨r÷xUÕL—âÄ^­Œã=eyŒŽˆrôÌá‰ÕUänk¾¼ç+n ê‰ùB¨$rÔá¸K½¥mÒ“†![š"_¤zQÒp |zçv×^kùžÜ½wUÑ^Z8F-æ ó¸Ú¤@Ëa&GT˜Gò´Ù\ÖeÓBùÏù°Ð­ÕBè¯ùÞ e R`ûhz‰oòÞu+cqd:îs0¨•É0>$Óï~ój*/Y”Às¬¡‘*]cLHÀž-}ø ÌZ€nÌz¤¾Æ«¡ûDßD£39kµOø`GMŒ^{]SS‘sóeä™ô`@Í’¦]¼sµO €9t çqHïð€f¿ÜJñ…—@v«y5*ÛiÍf34m|ì¥k‰u#Ý<}—GÞÆ«aqöåx^°Ù^Ʀ·Ô ´®/“çŽÙ`êvt–}áž@(»m_ÓËgÏìèÕ³'9ËŠ…$â"œî¤}B5¦vbd#‚λ‰YtB;aÚì?;W‡‘H.Z E ¢¶‘‚ô rh/m”>{‰@M™Þá<oŒ 0×^ßKJÐØl]€pž‡›K3VôrÀ_Q¨BPå'!üŽÎ!ÄùØk¸–¬Ý“&üí¤uÖ pÄXL÷„d ‰³ˆç‹³�ÂÑíÌ85|ˆ$QëO5Ò¢]dÓÇc†¼_›âÌÀ6ôƆIÓÛH¬Í}=c¸ssÃʈQ«1èii7Ö ûô ½ ëØPöu²ïűðôêPU¡²gà$Hç{åº-HU&^T ïöáaƒT5¾ív<Ì=Íi–‚u–Np+,}b!âðÑæQw‰l>¿†ñ~-ùøÑýBÔáO…BÿçíµÐÃ'³a©.x-udô¶ŸÓ*»ñc$ˆõ|hˆQÎ- ç‘\�É31äf‹N†'“7üÑû Ñ`Ún/¬\-ëXL7ŽºíüÝ{…Ây]÷‚*ã°@œ'5úYÑ[(,;Æ×|XþØa 2IáÛ~)I„&ùªžç4›ôÞ9Ðyï³P{häxðV-©øœÓð°å=_è—†dtzjO_oú`ƹ Áå\BÕ<’¦bLE“aµ¯Á‡rzäª'äl}ê{´ïª„«#xö¼ò-»©¾ÍŒ×•76¨¹|w^°Rýr„gïâ&yƬ´M8Cdð*sà÷ûP-¥ìÀj‘ÀSÅ~ËûR€ú覡<Í€¦æ~ mn»Úu§Øh-sP/šŒŠŸCŒ^“Á¬òÖCåªÜzߌ¾ßšÝ7¸„³ú¡ÇœFy%11–YÏÈó5WX™½Î´(èH–—Ãå/“@k…tËz§kA|¬œSsÏŸ</Ox†¥‘M ’¡$›q² ™p´eNR-¬ˆï…2tí­qà’šõë­oC´•‰ ^«7ç£'¯ébQ0µ8”žX™ÓùiñHÇ!¹¡ÊkKåH«Þéên½7`Oª¨C+MÛ43!1 pÕ#¨2ã®CU䡚‹×¶½‚¥è¸×øÌo³xMó'¤Š¦ t*'X§xyèL,Òµ$›5„#uäNdAê/pctɸúß½×ý¨GÈ×’ 0z:ætÉJ ðf?!‘~Î#‰´åÊ\7ŽçŽDÊ`ˆÁû‚Âì݃)kB10·±~©#Y«>ò`÷hš5Þâ>¬wÈÙ:¥*~H%àa—�òDwK4àÌOž‹´O zr©êõ¾ÉW,:–¶ÖhYrï wÊb5Üðm(J8Ý€)c.oL= ËÆ\ÄK<o Æëö·Y-gJtŸ’3ÛÆ(Ä*B)ô‚«ŠfnNR{>± ÞwyËZx‡œö6·è˜sxÎÅUgi؊ļ:BÛ- ߨÏB¥ 1\Iõ$/ø­·gdcÎÔÜX£C³Gw)Ý.%?Wf…:W‹GEìuKo-&"¡K^³^>0—ËÍ…ôêOJÌŸù¨^>âcÙ·=âJ’,8䑤‘Y}{0Òq׉««t¦TÒÈWQlNHíë {[”Ð'7AXæ±j›ïÈ÷ [·/\Ç”Qâr€µrÆ{3ùh;ü!B¸'§ùÀÓ7%%,…‹w8ºeÄåöˆ©œ_‹m^ߤ3ÈîT±ïÑÛ $ ‹GÒ” ¤¼dØoLÞá8!ë\pHCj‹ÕÅ®Ù:\˜[î>«Å[|ÚÓ±çAÉiÓUMjËpË‹»ÅoóIà/LBdlÆn yL[Vò‚:_íéf=¦WHDÓ¹9Ê ºï¹âõ¦>ºñr)V17’—¤LŠpÈâ7ï-ÈÌ`Hjv&b’ϰ=¨µ9/ ‡§õÜË›E¸×U眠<tÍ5åÜÄÖ‚òÛöÖçA‘á1‰ŒÃ½0V¡™Ñ=³lWÚ>0oº^±L¼á«)QkHZ×LO É{zu/®µU‚±g î¬çdËSÏb½îÊØÙ|%È»ÐÄõÜ1H÷ñ¢`­ÇniO¤¥äuß=â±.ÄŠØ:ñhñ¸5Ù|q°ÏÏdiWŠf«WÁ’CÇÙGíÒŠéµa¹ùˆØ‚¿DßN¼š ®_œžgIë O…—+¸»ÍàðXÎ:.Ò›€ï½’L÷åxO°ß uËøF„©9êòéÈ3 7™)ÅDê»-Äq…oNúýv}*§Õéb €º¯ríV,f Ÿ­d=“£!â3:W Ý&Tß{3ºõ¸Ê©NÓ*u£›ýbÑðõ…&;ǘÌI• ¹Ý˜o, ­éy¥mk»s8ÂI\qU�úC(²Ã!O]õ˜AbmßÛЮet@nÝì8�òBxî<µMQ’ÓÁ"‰Bô0åv`å¾ç†Ç0#Öü&|ÈÊhß-\²ჱ†V {;he¶ ßS¶wII•®?Aån6 LÐc9­³g=èσ!¬^ƒ-Ì€Nb*³`«ØÅÅ“µöôà\ Ä­~#ƒ³4‘è€î †ñÌ&‚Î.k甂b\y ÂŽôšn”¤((µ,Ðê=LËêg0—ÁÚüT#³«jÎÅùˆ`Ÿ·½p¶Md”W£dE÷м¸Fê¢-°Åô9"PÒfU!®P¬¦×ë{a}$Ø`^|égGÒ§X[çŽ\÷Øp×µÅP6ZéŒLÈ"m Çüžé{W¬žeΙYÉ+Ä©sƒsz‰"ˆÄ¸ödç­Û…YwYiê\.£²Û+`­CGD·AÁºŒ³zu‘=õ(©VÀz¹oNÐæuÉU,gý$5ˆ¡heKÐ/]¶«¨êèÉ̈¶÷Ûwq­KSw¼òÝ D´ÔývyÊàÞ«àÇÅG–p¸¶IÈê<IXÇFEGß3Ê>£øÍX%çe%¥,±ØŠÎÖ™¯sYBA'¬·ŽP ô›\ÂzЊωø˜Â±–ê!Ž%¢DÛj)¥ë¹j¢’4>—è«ÈAc…4+–÷RÝ©i4»]WQŸªm3òF"p¦Ç¡|…cUÒE*{üòˆSf¢ õؽ!ª´òÞË -î|Š'b¦óòjÜKSÍsðyžºÚC°Ãk£–Nc`‰VôâÕsÜ ê-S¬Y{›RÄÀW¶Ù^Ït¦óö=²GÝ$Òú~¡Âv7w™îŽ\Gx‘}PÚ1àÔSaÆM,‡m"+Ü,yJi0ý²ro sõ°†&Jc¸™ç½vY%ýŸ²¦Ñ€øJÊ?Qùg(7H†ºÚ‹÷Ì3ÇÞiY  †5o ÓSõ¾mˆì.}%s‡¢ õŒHÕ-ƒë©ZôÍÄäYÎ&ò™hdD¢”~Ojï¡•½ITÛ¥ Чo˜®£+ãPYɆæ&¾œIe—˜ãrÝØ…_ \-t/Ï^|ÁéøXvIqV÷N|pÈ”âÈ„jÛa«xoö‰£1)˜ê£kF¹,x¤:øZ„ÇÕ˜ŽšJÅÞ2�)¦‚=EBf¬ä tºÚÈ› 8ËÃ\C{äó³ëÉ›±ûŸÈXV†|Èi1'¦z£Ö�„ɆÝq$¨cMìMt6\ØI„ôÈCËÀxÒ{Ó/²<ÇWÞ—)¢$ï“U¼OVL¢ËÇu®ÌgVÈÇ£Ö¥5Ñx’Kbúp¤ÙVô•J«ŠKç½åÀb— ˜Ä󞓆 9 9Œ¨Ç ‰õdë‚Ý+X÷}� 0újâdóØ}Î5™ 6ß3�EËì�áêÍýšil”Sžú¥a€q(€[QjV;™û;÷÷ÿ'±Ä òH|õÚÝöm‚íyùî=›vxM¹$‡)P»šØì•¶hrD¨jPωíej*î¤:%Å.=}°ÉœqÆŒ˜+½@ Ï/²8ÚâÞ/Xé¹Ë/Í:JÉm:Œ0Ä1$&jÜ|@‘Ýn@#;GÏyˆm‰[j[‹Ò‹zsî-Ú†�;‚Ù+%gæ£Âæ7Ú~Ÿ¹Já;¨7Yø V«³¿1"Ê*“é¸[W0äŒ#\|�®0³³ÜèÙ{¯”û̘QÒàìqÏ=ƒYºe›I°RìØ{I"x,)âì ý²fÕt±Çä”D2is³–JpÚ‘&®ÞfòÁáÄ9ñXçD[kH®sÑ r©†ÚóŠÃcN áb„îGi‘Zú–XSÖg\°Ÿ‹EÈLÔCË-g#„ÅÓdͦyšvQÌá’§¢óÊ:t=cýئ‹÷´œ:³/r¯ÑëúΖ¹ö4ȶfÚ]¢Ì~Ñâ Åæ*’µšÉ·˜TzÑ#oÐ<\˜›3žhPmºŸÊ�ë#¯Úⵡ…e{îÀÈ`¯^`®"TŒò¯¥ <Ñû¦åŸù*E댠ùœBÜ=¡ùê *ˆ‰¥ßv^ÙR?*x ¾j„ë2–äÔj³‚Z.ìë I–¨î½¢|TT§Ùóʲ\0¼ÝêU ,zg½}ŠM˜k§-¼§iù’;Ž¶Ë±—Ddø ‡Ug¸<(b €1Âšê ±d¨ÐQGª!faŽfÌ{¨Ìoòuuºìš2Õ=Ëw–]ÏI$¸¡Îë[i¦×#šëˆÌÔƒÛå³hÑÑÅ^ɧ·M ­zOÞé*ïthý¼ë ”J)CÑÝ@¢øKáãö+’Fˆ²+¶§ª LC K —(ÚÜ{ÅZRVܰì ó) ×äNÓ>›hæ¦Åq}€ò‰ ?Ã{)_4màŒ€1 @Ì8ècpÄÌBaÍ0®.ô!fåW™Ò#”ç<âÛR‰F€#ÛpÝÑUtCwho0(Îü=y7Hämy–é{&õÞ�67‘ÇaÌhÔ\ˆoíó%L¾ÛWrèéæ„}erâéÖqùpÊ^åÓ ‹zÓœ‹&C¨-ž˜âíÐc}½É$+¯øqš=:ÍGbdŒbIÜãO ö“Äzôüiï-ÖÐÜ5J®5HøÃ;�&}ÁƒèåêÍ3…”<^>™óÆÝû9»¤ÅY”'ÊE7>ç ¨d°ô• G Ü,Mà îhY(2Ä÷zç‘)é*¦Ý½�YxH©F ÍûÐci5cá;Æëû~[ÆžŠ~ži÷VÚ׫乀>Íôx µMiûžú#¤ÁðÂK¢k{!äHÂ.nâ¹Ú¾­—M¥uYxP/ß 6£êe Î={.~oÈ š!ÜN™ù »åqôHSöºøæK…ÉÒTIbF• £ìÇbà±$ e=;Íï^,BÆCs9-{w¡ˆƒ‚zúNQ°ŠÌF!D" „sO*�ø‹ Ô,õP ÚÓ|QÔïM‹�$JùçKÈýÞ«€j^a¤ÕAçDpÒ:XËÕž˜¬?{"©="[ =x«À‚ù| QãY9’NßÑŠÚ´¢ß‘!€‘u˜cE;§˜Kãj-L¶;P²rÅTð�<¡<ÚO`ôè™#öî²¹zSž±í .߃2Zv¯ ”vO¼[y N–¬õîAFµ®rÆR‹r>k8lÍÁP # Ý–ºÅôkM&é‡.;pˆÜëEËm;¡š@ꬴ®œâ£ÏõÌeé¥3SŠæAñœfµØŽô+t™Ùuö؇ÙÝUÍ$ê·:Y¤O°žú+õÇþð"¼é¡*¿ðÅËÂʪ¾+ î@wo}`1vSL¾ã!/F'ôá»ÉÚ1µ7Äï± “aÏæpè–.§‰g·¹² 0ý^‘g†” Xžœ Ú{¹ÒÜÄù\¯@üѸfüÿhàÙžPÕ}-*«,9ßâÞ,¹ © —fE²ƒ$²Ô71þŒö»]å7—<© n@íÙiØ8žÓ)àâ²9‚ u™À»×u´~¢;Öäî/m÷ª]®#C äm\:—çm õš¿áI xþ¬p+ÜýmâAúYfôRêF5ë»RmNôɇ ¸XA$º…ïÈž”N¡:ß#€ ¯HÄX™gwœw¥è‹ÏÀ×lu刑"%‘ðG‰´Ÿ½ôk2p8`lCb¬]Í.Ω3¥é /â^!WA —66»×tßP IÖ»G(u¯ôݼñ Ð|¿&»ÔÆìŠ•ÎÌØnçÅËðHbæôR¹Ä9dÆLÆ”¶@Õ§ Ë7Pi…Ó(·óX*B‡„$œxýæI†º<ŒÚ÷Ì?‘)-g¯´3ú¨Üö«–yI@3,ÄFºT0g^kù@góäVú#ÔÎ#‚=—G&èÞ³¯(ºƒ3™CÌÓö¥/dŒú:jù ºÇUÃÖAP ð)Qn侚,£rï§£5OvYa÷į /ãu Åy› „­¥¦ÒVE‰»íõ)<o©©˜¢‡H†9t‹‡7ê˜ß‹ãÅí“„‹ƒ­ä‘Þ²çæYï5lIêz”­zŠÇéxÙN̆ -!B‡àlrû†i5A$—vY¯Ôø½säTo®¥õŽŸy ˜z†6-h9Ò·Éß9žÂƒ’}Þþ64ø¢éÃeê1t¸iwf»O©·'[’)óånX­ªtŸœÎªä�|2“ϸ?¯ëÑÅRásprêæƒÎ0^·muyZt©áœ->‘A>³’aàãèÍ¡`³ï9¯)úayî8Ù»y;Â"–ÇïÁeCÌ¥3 jD…1ß+Ì=²­b™îX¤¹br~¾‹É{SÔ¹eGA„huJYÓ¶bµÅhض˜ó²@Ü´y¬”PK «£{aî(;'٪ʵÖÌVѪVÌïX0œyŠ2´Õ�_ÀšV…ÌÓƒsàöä{†¶Ù¼6÷úŽªZ$ÑÖLž‹½Ô„œçä¿ Å«a–¡Îp±èÊŒ &èµ W Àˆvì<“E«ù YA[� 3õõ~Í´¤o.0ÐÂPß*i6}BÓÏà/ÂCD‘f¹礗 #¤ÊâíS(X²” ~·h˜œýNu8žåÙñ€w·<š‡§+G£ÇÏ{º¢ÐćŠB•¿;êÒÕ$M=)ªf\W,r.mñ*H~ïFøÍ¡Éb-Šá•¼\Õ{ãšïÔ§÷evesÇË&Ú-Îó#|EõRÌL`i¯† ÖÓ;ÅŸ8†áUR%×À˜®¡Oö9 QJÌs;ïŽ÷ˆ×òcÉÓ%½‚e(Mô¢ÌSñõ·ƒm®„7Š›¶ž5]n»ºü¢wp0`ÚÉÜ$”ÔjÞBÚã£Jh;ºØÝ÷ò \5²¦•<$QÒ8¬Q']–¸pÑn¤¢¼Õ£6¼ŽÖOjö¾+€YØ>({I¢•"u<GÙÚSŒ[lVƒNœq‘]M ù‚Ç^Ü»°9JE¨…;”ŠÖ‘)Fe®pcR@†kå“— tð\ÛSÔ�ÔÒy-ž¦“Oa)ÎÞ®<ä'çþpöžîÙµ •£ Ë€HNÇs¶Ð§6]½5îÈ~â–Éšéç|ï¶ÄI»¹(++ËùEŠ9-ÚHD½ÇoKb Çr²uìMMA˜>¶sä̓—öðÕ¢n¿ ÇÌŒŽ™óØž�"J³j^ ÷ô—uÖÖyô¾ó‡ãeÆPgs¼z—`>ˆâçøØç|Š4»F*‡R[‰ªV�¶Øq^ÕîFš¶óNÏ%\„íôø¹ ¿—&aûXé_Ï'6ÿ,q¯Ñs6ŠÚœ ®Li#óœ2ÚVoÍÉdsä[€2Çsð¹Çצû´Ëj §Iœ¹gE­*_¸xßuØÕ @ ÂMº"”èÆ £y"“áLKœ Š5;d÷벊úÁÐ3¦cxZÉÝM.ùðœ  î `vùÁ0"â"Ü;^ä ‹g")o<Šäfäô••ŽçÖˆR'^ªPKÃùѓx°zèuySÛuð‰hG "#B8ÛÏ[iLŸ6;½·a#wö^0pÔlàÝÏ5êO©ZK1±.§pÈFM—cÕ„7æ`äµì!Uе³ r¶ÉH®¨!ÃsjâdžvÜïêtÜD4 ÜôA¶3ˆi~sû¬¹(qtI¤�/W«{½«flž¯ìÄ( ±„4wS3¼Œ*£"À®N¦^îÇ=ÒáÝú$¶3`_Z,à]eƒUÂ"Û%?5MUƒ %·’ꑈõUÍÜÁòÄÀ–d¶S$#xx©³9]"¤4¨3ý6š*Á8블ôз7rúä50ØaÀÜ^޵ØhÜ‘–³GJiY‹ØZÌð 4¨ žDœh{h‘t •R%IëC¼Ê³A_³ëñÔdÚ-nÀ#: 7»xf\ëшÈ3BØ€¸BI<ýØóìï÷4a'b'=cÒ3»‡BïdÄ—§œÄö<Ä)¡þg]žÜ»] ºÅb{xêhIFQ_’4+ÄeŒsÍ3Þ0¿þŸÊ7¬å®ßh2\Ú¬]ïuÀQáë`XËbz¸/v5Þ\¶E@tÄôLøõJ¢yK“ì¾rEC¦æf(BRÅãÈš êM‹A4Aw½Õì{ñšû%ži1P†5ELžK±æ8/êcmµQ'5±š%Ò~#À«äšEÏÂò´ê nÔ¿5áfceo¡(x³LŸÞ¨oÚ¨lÄIqK6ÃYS‘­ið½àÇý8ÏÛö$zbêpž/,ÂYDê™wKÅÍ.§DÖF ?C§ŠŽa;Q& >ú¹R/ïV’¡6¦•#>è»`¬RñSÚ= &b qB*?€:t4óð\Ã�*y¼êUð|™Ÿ«º(">ð¨®4»áÏüfÀŸä˜x›°.oêvf´&xÎ*c:1öÀäl Ð_žêhrõÙ V‚c$z¼T²wQ$ÕmŽ"»ëü¼ú½yÈ.º#—AÆM Q³¨¡ðº†ZœJ¢¨^¡wS)a¢_1s\j^¢&M½j~øöN(Z­ÕÁŸ ‰x´!âÕ]/7Ç[Sšx¢™ä[o9¾±GÁ‰·*zÇ3È"ØËk­ëeŠ'�Ösóô°|žàÒôdòé¼+L“ºQî'@U"É|ª²aDP[݆Šqï]ÕE·è°QüBGW|ó†Ñ¼ÇvtØ cEPÙnxø^õ詘5fkl.O1½†Gœ]‹V¯wà‘§hvUù»j  )k!w±OtøY¬-„Ʊ}ø v˜:ûqÌ�‹Î*°I9ƒÁ;[Q‹IáµÏKt evI*WâÛL’ÌÄ|Ç’6ZŠB¢4»„UÙÌÔžD»£#¢©NªýäY‰Àn<¹ÒÀÍ®‘ÍE®0PõZ4n¹w›L¹ò ù)E»ó¾$ujh²x÷8 ½ºžíÃc#»,}m¶I^ýÿIŽñl²”é¶ÖP^TY–¤ù ±S·1véÙ++‡{ê¥^§/k®PÌR“ß"—rxwÈá{Î m-#½Åi5+îk÷°±ƒÂZuU#ä’£ƒ#Ø'­ï¦ë àpÝ0Ü{-]l£´y)þò]­°PÒÕUg<R‡ã~mÑáäÞ`3cy÷Z÷“݃Ov©ÉÇ7-‘8ï9æJ‡qÙ“·}KËm›»út­&<lï& wϪ0ëëÙ¹!yã(´šÜ>–àøÎ�»¬Íû‰è!âØÒgSý":ÓâÍ¥ø‘É‹¸¤$ÁØ( T»D ºK’u1;kH×Öb½Ešò}=ÓWéR3Ó½–¾(rŽgøÆ7n•…†æ½vÄŠs&ª÷fX 0KâÝ@í+¥œšGQ H(ÍzSjî&Eí¸ ” 'Ž}µý8‘ Õ0±ÜS¼‚~…”Æ-¹¿à“ôR>Ï1lJ7µÐ:•Ìròq^vx;ÙÀìœ š ¾C8[ÒäðÞAöîpt‰/ùPfAìmïqÜ4Y<Á'áO¿á}‰‰ËDî­²Y,m0†H¢ }€T²¾°¸ÊèsF©i†WŽMQCU¾/ ª-ž<ɼ5Nêî ·²v¸h7¼”ŒÐë×ÇIJ;…Ù%âK#ú ^Ñ8U¹ëγ2" GÂÉ)~h丙i•(Ûþ J©uF6·%Ÿ ÈÍu‘¥>duÐâ†gR=™TÐŽXÃdJT/ŠÉŽw”¹_¾IÕÙíâ·”CšZŸƒ<¯zÇ=QàG øJ^qµè°w{jIT ‡ûf ¾Å„Ä~‹k¿è)–§ÉƒÉâ¡`.Ìèn>yJ;¹@OLmi^ÂÞ{Déx¶d¡ÏÁ ¦&ËYlÄ¥A ¥„L…¦iÌ6PàøáÅ1}Ò£ÏJñÆù ´â½ í[‡>Ü ÷TI¥©3“F§(N+_޼Ôôn‚k„3Õ2A0»äÐÆ6ð|f‰ øðš!טq°dÍ*3Ç ðF¦°ÈlP¥@ªÎÃßR¨Bçy=‹[y/Ó§\"bGe…°»š‹ º/â%²¸žVò;¹%ÈKÏeh™{ªÄ:)çEr¨‰³”¥³pl6>®  ë^Q±Ñ©É ˆÊ-ßÔ‰0Ųû„óWÚ çëwzKMZýʨ_9å•‹¾ à‹s%q÷q¹ÔI?ç^9[½x޾P™ŒÒO¦£xj–qñ” Ì[V¤ž\…Q0é{ýâÄmš„�•1 ú5¼ ë¤Gl—/“ W«l°ÝÖ?ññg¹Å˜0w»Îl ·}¯õ¨‰“&{ž£=&:KOKyÚÉùŸáöµŒŒÕJ6ŒËÄC!¹V‰°a¦~ØÁ I·7/«+8w€^`.!tOšŒg/WÛx¬ ­ ª@Mʨzy Ôµ¯‚/:e䫜æ;9°…†jϸ·P/ŸÞèx‹�€_f–ÉaÞK~\Û‘Öãt9ܾAˆ¢¢é†6Tò(ÕxEì>gE®¤¥´7~ï.Wú]¥H¥$õ³†|gXcˆónÑ"úåa=� aÇ]iι— —õ(Lú~Þ&dGÇEÍŒW•¯é•%àbë“k§÷²¢z¬ƒÔ•¼€ÂØÃhBT%Iê¡ !#eÊJ³­Ê¸X2™Ó¾ê˜�òÉO>kFû†i+y@[/•¯ 4=‚ XxÍA…óÂ!«ÙqEwî…^8YÌu€CžÆÕ£ˆÁF¦ÚuÈEzŽúz±ÒNÓÉX-êAf9lñ*’¿Žˆp}˜—|‘Ï@z TÜå\›¶Ä„  É Ñ«ßÑê$n¸Ïa¶É©á² R`>ãzïœz ì]Tg5ÔCU—º1x†ð¸ÐÍó0?yïbÓÆ-,á%Í1©?ÁY@k—Á¬Œè™$*¼ÖIqÔdR¾ç]kB<ÕÊÕj¯­Oa;Þ)Mì…ýè$`A×( ¹öL¬ß`%\Ïa<êp;R1yæ¾Ô*Ah¬M:H7/hÊ7±”ŒÝ^÷oôZël?% è ÝW3®|Ÿ�õ»p Ë%>.ã‰×ï>² ŽJ{€ÕþÞг7 ¥þ(CûÉÙJ÷»çquÌŒrÑe·jbXÈLŒðˆsAqçôIì+^zQçÎLo°3e 5qšÌ;e©yåHÔž×Ìp˜LY{À¤Wµs·ÑÝc¦àaá07•å( :ƒ{àOò)î¸Oõâ3{>ÞãQýZÂ6^ï( œÊ¥I"o-«]ŠõR {©«qÆœ4lë A×½]Å^=Ðj¿çÊs'âd¦E8çmw]Šü<E묆 Ý‹SðQÕ9å±î¤Ëï'å~4 ‹{©Åö‚hg•cïÌHINµ•…WlÙ‚$ḥ‚…}Rš4j² YWø�­éF{éO ¶u5-U%m- }ôO‚7—ÓÿÓ³råyk«ô$枉½‡åno‡ÆäÎçlôÙ<Õ}×ñ5ÅY8-‹xÝ@â½Ú£Û­„À{¦/Ð*‚\-Ø…-wÃ`Æ­ ¨›§Ï{­LæuJ|v&Ð@áZ`VPçe éÙJ±"nWÈ´eKÕa;–Àý f E݉‘F¡‘ĆÚC`ÅÖ�:P‰±Ú˜ZÓå•_)4U><ªF)'L–ê,l}ÔcÐݾ÷|  TH —|KôYËF°:Eîb'fM;a,ŒZØë"I-TÀz2uì?ç ÁX¥ŠKÏÛ ¬zŠðäbºÎI¢cš ­_( ž‚XE3/eª%W’¹ëRꘜo ¶Å\dDg €“=ÀïþkŸ%$Ü•üaÜ„ðÃó§'º|K¢/´ôyS¯Aǽ5ñL‡ögtï—'sUš†Ö:!T²m/qÃ4W¾Ñ;¨“ª *—#á1aê~‰™Âj<df÷†Ò‡ßÑ6•e>µJS W΀öVH#}8x21tR[õh »´aà*‡ÔåEy?¥ÎÄÊMλÜa}s:>R¸å,{„è^´‡yŽ˜H‡¢µeùÜ3W‚¶Ù°ôq&¦µæà¾P4öÆ=)wÚý.ã^“i€”8L{ÈÃMŠ1þÿ„ŸuD``2ЦPXºqÞ‘°J˜0‰òã8|-¬ na»iDO{õñJš'¯WI«{]'£+Ž¢ÚD¶á(ÖÓÞ¤A}2ôï:’YúLt,Uc5+Ã}Œ[%Šf]P0£­ïTÂNQtnæyGš: *Ù¤M"NðB䌔zê‚cÏ{Ð�\·Öóœê˜RÜ'O êYª87'ç;Ú…Ãe6²x )YxevÓÉQr`•®õÿ³®b¯øú=iWg9xº)üÀ´ª_Ï éâ{­µObÂWœqŽû ÷ìZ&äc–Ç»Ýêw/÷¤@£cݱuc“A_"´““‘ûÙž¸„'9ëq G¨¿R§æ}Å%øòª‘œ:˜*jöe¯a~At2yéÞ2ŒA/ÔžÌv t4È<­šÈ{ { ÏuûvCq6$j§ x˜^¿j xàÇ ï©¢=¦yê]×®ùûþŸÅ„­ü¡fÂUɨ…ê½õ×h –ùFéÙ†^ÓÒ¬‘zíZDpb øk{²ãÃø@º¤zNšÏì² 'YS*êu5Çæœ¹V;fÈ%ÚœÑ)¨`ä&ÜYŒ$"?«ð];¤”P²}.ŒÄNo3²öõ`uUݳ6î<Ró©+ìàð°MÀ½Kž¼ZWfET—V´¤Ú–¤ËÙŽj§A“·vG@½¼•ópáÖµª”=HaK\€Ë(Ëñq>ç"Î=D”5ž=Ä t¯ÁÅ ›H|M€ô¶ŸƒEMNöä»ñ2ÿ¹šŸ;?®t‘4mc‡RÐó£·Áj•åUtí7Bµ•à ÷)‹¾'·mPYvÓÊ/ž”VÀÑJmE¼÷d3¾;²ÃgEñ¾ÃS»j÷Ð $%wGGíÎ"v}Uj©¢Kî¡G½z7<i&q=ªj £+Š-òÈëŒGcïìÉd ²Õe(Ôë^N¾'Œ¦U<Xƒë¡ÂL¯|j1‘¤ù!JQpÁcÍ—NÓ.£æ¯–‹™…¨uos¡ó°°o.Ýib¼#¦¯ò-½„{jGØýÔ0¶\Ë0Ê•‡e¿I&Ú Ì~Ü1vhªÉŒ†ƒ*€M~mñ‚³»Õ{KTeH: U¢F.ˆ§y£“ã.Õ5Ä3V¾¨±ç³Üš›e™«»”úlbÜ 2æfåeñ'ǯ§{¸§x=kѪ[YÐʼn…—-¯ì®:A .göZÌÈc«Ô{Þ5 ¹eÖß?ËÊfXö]TE�7Žw• Oa {º ð™ §8)ðšÛÑ‹xu+,[Ö3È‘È3Bz(ïeɺ8‰âS(¤­Ý3—z”Œ7.¦©“¦œ¾£ãï ‡X ËÈc6ÑFÏtX̼èó$f q_·ß�j\Y7÷’é;_ÒÜÀÿ¯ëäÓ›|–RÁ/ªè´ªïMÇ•%5mlYÝ¢™—p®™v†<ð0ŒÙ4žÍåÓPÄœ°³W¢ðŠo Ãnh‹±”ŸèËúx ¶ˆL{> àŒ‚ÃØ»,3×Ì~“T*`GÔI¢üìgwîMfÛ[=/Ðl~`úÈLINnÀÔŽó¼Ë­RYÜro ¨1¯Â†>@ÈMqžþtt`$Ø•eãÜ©øM<KÆOŽø};¡lÞH~­{,MDÚ«sýîlÖݹçÑtà»=83ц"iô8Ê¡|¤aY“.˜Žî˜ÐÞ×áõÚà‰r¿Z”[n®8„¹z}` ëís·–ðÄáìI æ|w-wñ £Cú^&¿iqVã.ɨS©91 ”ó™x’‰¯îòªWÁŸTÙͤÞKdj¯ Íê�§‘H Ü7ú9=ÊÁ!Ÿƒ‚¨÷=N‡\E´¸u^¸Ë w4ïÒT´!ÛánÀ0HNÆÁô¡™^Öªä,ë€Q¡ð!ÓcBôèõÆ&Z¤w›«é=h©ØJ�ø~.ëº^*µ­zNàþèD3ƒ¦Š'ö¦&ˆ�&¬ð"öºü5©sKJJ¦òZ·FyPDgÜ{ëë®`åJDºÜuÞ§k\áý ò}@{sFïùëvW&ñ%Ž÷º6ð@5.ݦ6lã‹b¹Ç/{!å]ë#^¬]Ï,ï]/v]œ®Œa°~2é㇠yæ»oÇ_RZlC…îêËœr>OÞõ´îNjÜu^‚—›ïçm0„­ÚÀùzÆ<ħ )áIŽËoP½ ×Ó0[?‰å} ¼BRf¡59+ª·"à⊾ú´8áò<¤º7�Q€“cAnDñÙæÒày å•°oçdM"<@ÄÛBnFâð$…WáÈ÷ºµf¯1=yéïYÂ<õn@U󹊇?ïËÉb¹ÆçÑüªæÕ¼­»«1< ½³2mΛ¹«‘wôVÜ3„©w &#i‘ c³ë]ªg3ÚŽVY*„¿B-Ùâ;ú$IŸU†Ü¤â1ôÑBzI´Š Ã=MìCwÝ×ͽðéÍ †7š&,T JòœÜIŽóe¨Ót¼¼ r2 |„h@•zœÓŽzÛUpÑÌZæR',ÔWÜÍ˨Ҷ ÂzÙo6kQf߯\å¡ñëÙ"‘hsGÂT Z rQU$Óvì QŸÄÈÔxRlwc–Lm kâM6O8 îàjeÏ·‚¬z8.Õ‹#ŒlÚ1²FB¦`AÜøÎif²<„˜³Ö±Þ\¬ø˜ŽKN8‚é ñ§µÀÃ$Š"! ²\\勨9oKÖª`0. ~Þ]°¼ÇBSý¹.Àtà]¤ž“1ó ]ŸÇF@¹Ÿ-ñ¬½D ¹,ç3Ÿ¤³¼öðжžW¬ã¥X V§ÛO”ü}waëÆ”¸½ÊàŒ6©tÕ&˜–Æ.h8ß Å gç‘Ád8Eç¼Zšì8Sx>عÝW§­½¯¸!^Òñ¼½•$J�;›]™+Ç„˜a¹ êɆbªûNgØ›NÌ/ð€ G6 î [äÓÓÒc¾™EIˆ†Q¶æƒ1süÈÂóÌm«E(Þõ�^+Àø°jÅZZºÔ]t clÔ¸ñÌB8¢ÀLžÝV&“ñÛKÑçCè�@ˆûNT„Trx¬¬4ðZ¾÷Öf·-Z²QÇÅÞö€.v·õŽ‘^»Ú ÇöÖjƒ¿õü¹¾•d,‹Þro´kC=†Ó§m6Îç›ubXé7ûXÔ€ OÕ.ðÍNU×Þ=tHÆHõ¶²€J]Ux#ˆòÍò³Þˆå…áuçv“L¿íØ~Q½ÓZÊf/6QÝÅS—#Áp ô8%•¥y½ÍXGEõúë�m/×í�<šÙaT+:€íºlÍ]²ç X´r‡P|±ã5P>L@íD&RÔI¹3%\í£JÉKæIe Z‹gŒùCp�=©²Y“’†J.~4^å€k€1Í·™#Qmˆ… xˆ6II”âÊáµQ¿2ñ­5,ô[â·4äþl”n ‡¯è¹0�×+Ú§à˜~Þ£ó ü|­lòeáŽ%cá�>—÷ú×hÚ­Zhð{½N‘1¬àô æÌ@ËÃ…9•Ê}Œ`oìô´;í”õñv¼²:¯F=Pxk²ËêyŒG{'½$@Ž\4°©; Ù{œ•2Wgý¦èg®äEÆ÷,àU潡G X3Ê'F—‰Uö�½oQ '×M&¡a”Z¢iš[Ó±�æ5ë£, G'¬7ùÒ+ùuèò¸r6ó"è"®q›5¾À:™ ¡X Q«ÓDìÓ WU9DçÁZ'ŽÜ :.¨Dƒ)H‚�EAQ7üÊÅû¡?k¿9ˆÂS™6O$)éä¹JpÀꜹD}Ô^ʶÙWÌÌå’Ìgä 6 #`Éç¤âæ®§{<[âÞ`¢#ûŽc0-Çhá h¨ä ûô½B7o $ZNg_’x›Ž­W÷³ƒ;7(<¾�Q�ÀNî=WË3‹ˆ`ZBêD£ç&ÚLón ûÂßPZf¡ôó£ñ¦Ø¯N/hGOu-œ?%ºú^åÊŸ«¼¥Éywážûö>ëÞ‘—€ „Ï ,ÀȼZW[6VÛHìQvÕˆfs¸p½a¶7DÇPUîþBô±4©N“øC Ͱäűe\áÙe‰ü^�ÈåÍkNWäAȰŒ¹;ë ÖK–§J3óbÊ/–xJa2é©óØÛ|üt{ëRŕڽhô®Ì—§;\Ç?ÊF @åÛËèJkSë” xÜYÆì'°E¼‘Aé�ÏØ°WÂH"Ú]g³¸+y<N®-÷ÝÃîyvЏ¬Oë øô{äoã5îÕ;Í›ö›¦yhOO€¤YË1l~ÎÍbQÂ@5ÁÀE°•w‰’Ó1ÊÄÇ›–xáï“!£ŒÇöÊíóªaÌ›¦¶¸.ªDOÛò¡=ÔOœöY~öÅŠOÍÙÄÒ<dQñ]=‰xù®-àø|¢§˜G*¸Ü×ñ²ùæ¤9˜ß!U ¶ˆ»²†¾AôؼÓÇî‡ÉeSˆ‰¢°>ÓÝ}(Aüäλ|p𱄹)ƒÛhe?1xZ°—ë½-÷^é=l‰ìÅl#דr'ëÔÄWzu"Ä3 { æ<TÁ4SïÁmn{dÊj¼8/_Vä»U 1Y«E½{òtZ™ÜžÀÀãwèžµ©©'70Øk#&Òq—ªyPjôÀE5`³ÑÌ;i²_?Ž x€v½A+`KBÙÊål¿x&ACeÕ¥-% Ì€0Ã;u$A"xÐô¶xÔýÞÀ°Ô³ÃÇE$]î±ÔÕœœü�žV½ì—\X(-V¥üÉÓ?kÐø?¡ÐÓUÙN@‘£ƒ¾ìq:ÒŒ@Ä1õ¹7ˆ:.=«äÞÙxvèq/l(Ã.‡7NŠq|<fìöŠZD¿²Òºè«„QS:iª|alU%¤òŠãô¶Û¾ž{Í2ž¹ QíW—êN«o™»8Ö5Ž·’. 쬓ç€ôKšãË1eya±q/òr{g°•ʇ´ÌY8±J-±Í²µ´èBŽ^)OV£0¹"mr˜À¿Ý�<DÉŒ¬Š;ez<³1YU€ ¼X£ÅÕÓÉÜ�Æ­Ó¼Aãñ�=Ê1w[ÖXoȞ؇û (§8Ä²Ø O´­?ˆÓf#/you<4·^¥“º½àxñèÍ“«ÄñÕ«{ö6œl€ùÜAøX’ãoˆ˜¸íÁûúYˆ(ñ x14½6æx¥JÈdú–ÛüŒÐâˆËb•È´<[NRðPˆkìEÁ+àx'Ò5¾~%Û¸©U« kL(è«•,ƒäbhz!½Êê 2NÅŠ7ãl=hsMqtLÜz¨ÏÏíy"Õœ%½kÏ4îfw̵KŒ¼TimÚÅ¢œ%Œ—Ç„Ó3Ë·ÑŸºÊ°NÐáZ˾2Gêx) +ä®GÃX4/Õ1!ÚY¸Êó<”µt)¢ÈK‘ApˆOŸ(%Ù6@«\Ëks¸Í¾TCp§|mùê÷Í(ÐÄæãik¹­ý9C-�µ‰k—1Kºž9›§”È€õ[pB'™Y=¿óÉË&K9÷«ëÞ»%qŽ©ÁG:÷ˆ¤�ž² ˜ßb;S?±Äª•ïŸÕ]q§—õRrÐïp6œg[.l ÕÜen¸b.sÁÔøõÆ>5Á×)x:'É"yÐr£Yœ½‰@IdÐ$Ì.iÎzå|”mý¸¤ÞÕ½g�¯Wð!Q•-6¯�ˆÕ .óQ[O…FFìs.t>D.PO¼€˜¨>µñ…ØKÓg™ /kýh©ØˆÑŽtxž€ j™˜ËÓŽ ÎgonY`@'ýô2DÝ"!Eú6bߦˆl²Y%ms÷x“ ?Rļx+B,ÓÅ,ê ÆVr´ápTÜÒ¡h\>^é¤%züø½ôrÚVMÀ¦Gx7G -?‘*ÐYAˆŠ3B‰qòtl²“…² ­ì¥`’¾$Xo¥×"¨/‰«Dè-C°gFâRº¹6ð{¹MÛDÞv\bjñ�X^}! ø¾ ùÀÝ,¥.ï©(ø¦Ú[v‚ÆLcèÖ}~Œ}´ÂrTÑ–#»Uû Pù»vž‹ôk£o\^¢ÀIß7Jº(7Î!”+ý±�rz,ó&³£àT)W3‹E0N(0…ÑÀ†-€xRs$—$BóÀü‚ƒF•f ÏÉ5:ŸU xÙ®ãâóFC¦ì[çzpû@m·KØ8eXúfãxh/Þè€H„ÇÃàñô‡>¥ã(Ÿâ<€1d£1v?âgŒZê¡dÃ"÷Á°³«]%Ë=·qBËÊ󤊓AYêÐT×fåg—G@×x#-R™â‹käL‚0¬d=ôÿÉ WÁ4ix aB¹G‚ÖÃÐ%ÛÒc=GÀH@ùYkûÙå\BË4õeÊÄãO¦ø>ó¨ùË*{)µDñL¬ÞвÔê>ˆ=�àמÂt;ºÕ ’vHT0ãÕÄ.¤;¹oñm£¯;Ùœ%µÛ6ëôcœ]p#®&ò¦Ôn ³$X’šzRì«w23;g‚‡³§øæ-#L&%t° ^$Sž* ¹ yÊ‹<Ï\dtðöj+…Î~ZÎÙèLºgü´…mƒÓ ü�³ëš“üÉæŸ<È�Ô{W^'¨²ƒÏH¯ —49ÒH‘b3iÛ‰A£°I _Q–»4¼V†Š3uÝ‘‹gû?ÆBo¹Ÿh¡k¿§¨q÷ÄBxkÒ±aåâçýh©aó®IÔjìuÃC49z3+4ûT^ !mцzÎÌé‹IÀ ÈØ',˜öâÌì2‹Þêò!_èȬ­ïÔóþ†ú>‹“\¯#D’¸,C8-¢ó £Uîs¸'ÞWÈLn2°LØ…Q™jϨZ<k |Ñ™§ŠÔ¼2ù‘Ü»yj ¡¨ =%ø-ÕexŠô“DV]K²÷º^Õå¥pidÄ‚‘ìJ‚Lîë÷†ÂjB”äÄ›=Õ.`±Œ2¯‡Î¢ ªŠýYBŸÔ#ÆÑ ¸Æž"yEp¹,Cì/x°”ž¼Ydc¸W.¹ò"f¶ íÍzé@åÃÈù¨Jᎉ‡bŠNœdã¤bÂEcɬLÒ ËÉçžFyr‰ê1T–˜±È 5ý£åKЊ´ÞÇm„–ho~ÎÔx¹–p–ŽzCÃð fú^æÉKåUržNyvDy¼«ÓV}Y1œ$÷ ÌE5´ Z™ÞœAjïpÕS‘Ôû¦úY¡í†aêâò*äUNÈÈmGÔiÔãRãj´s@T”x³z¢åZ˜†CÇÄn=ÛÊ‚àEPí³·œ깇žøôª( ìvû$éâ9cj¤¥úkqX' Æy8‘”×xP¡´Ø)Y´ø81…æ°Å VÜñJxr±`œá ýb°€[Y*ÛÆ§î= H}”‰¢äE‘¯àÎôèÉ‹<÷yEv$»ªùÿ]òùÐ{6 TØÈÁY, £‰hQaІ<:Š,Ë’{>Ç^V‡QPUJJlb%$#wqYb6婟ÀXt´òšÀÙÀ»Lñºü™S«ÇÖš$n&(EÇâ®ß±bò-3e{Ç¿¹Ê{ffè³`ü8õÑÝ0¥�¦ 3s¤u6µ?\r(èr´WÁAß9•ôs®ªúöDÌÕ>”fD§ðìèØ<Ld¢Ëâî uP6y¥O6ƒÙÏdØóÙ�Û¨ Û!ÏÀ]¦È¥ì‹³<T—Ík¾/ÊÐ:Ð7+†€…éÔTŠ—:<h¨ä‹ê’j¸æŒx\Ü=T£:°Y%S•À£oL^óRŽU7r1™MÒÞ?.ìz—€EopY; VŸî¼ÉÇmS[JRm—]ãÃQ[I÷¨±»ëz`‘WÃÈN$¬¡Ç%ÚÔàåúRôÓ§x7ûâÁÐ@åÁ(’khßJÙÒ+8–9ÊLŠ w”6R —nøò=Ãë< Ä^+A,ü9[¯—< ¨M€Tû\gìmSÝ{'Ug· È1„¥©Vê%d%QIh7î½™>/SåD^Y</2—Ve8*ã< ØAïýäÊßµŠFŸ°; Ï,›¤úÎõÿ4M_ÌR»ia× õsÙ æÏüÕK}ˆ¶ØÇèÅT 9íŽ×šëÒî¾±=s;r1ÈçÌoÇpàår<pëé ?cu‘÷,Ôº0‹ ù)îRmO!:½ÚÚãjöt“ƨ4¥P„­MXÀz'P�3ÜÙ©ÓEÈ€Î{†›Ç: aŠÓàâá»ûÿx1mòzÑ]­<š}ÎYuÏáZ¶¨l‰@Äê{[åÚõÈä¤b«æïóè¢ç/—6³åí<ž×ñ*WÒTüÉK¡æ(+xs+|SoÀ¸´²U‚=Š=ЧCW=L’Ak»Ë¸œïNH߉v¸×7Hª½`ƒi¹¬¥ðS|—7lYYðDñ` ·"Þ"wº[ç¡‚•Ï‚õvúù»«€ Cô Ì*d9R ¥®y#°=¯Èê��]Z‡6ìikÀmã² Âò+4ãWP@fk³Z~" ž<ÅÆÐ»:N /f0M�§qƒ$2©úm!M‹² šÃ¹‘–(V´ŠdÕ)Ïå©K'\ÛpPu¥Vá+9•5\é”ÑöQÝ¡1‚z:E!EÌfdýôrÀ#r` ´ëyd‚žGËÁ¶½âPïNaêy\È¢Æô„—Ä ­Á¬îl'“§AÚåµGŠ= x~-·}#T¾â{» àe']rÂ@|Ô  ÛXŸ¥âîϪãzIÌô<vÄb3y1‰O¦1r®[Ho¬j¼ÉR–²`ÖœÎ$Pœfå—‚ã)úö (Mòàä5 ƒŽôCÚÌÖZ‘O²úYµêyj&Þ Q T—¯ãŽvö4Bè+»óÇÆç,»åf ÐgP`•¾d¡È¸K K×ëü’<òj0©¦[ï­MÌ -‡ÈQ¨�oǯó©E‹PÜÍ)©™åDcÏžCôd¬OO±`VÅF£í%“EÖ<.ôWŽ×OJQƒ p€[Š6s48µ†»A÷dÒ/_¾T‰–T§° �‹y-X}�û 5µ9Љ 2çÆá>SQ(Ÿ1²ÄªîX[®8wÜìÑŽ×LèÄžHǼõ QûZuì&8„›„Þ^v¾þ`ToàµÞNRš£=uq÷ß9–øqA€ÆÕ¼ËpÌ»]‚*GÔ6Í ¨Óìmç¦b!õŒ­²ëM•P9y‚œ/%tuA lZs×ÎDëÝ÷É7Zÿœ³¡Álƒ&p/3ª@§öÞª wÈù(„@ÝzC­Ï>á~Zo+–g£Õ;rŽcy7 û¹@¨Ý‹“7rv*F« ­—¢íÙ©ôJäDKd6âY±t¨–ÉáDÞñJ(ƒ’yïf¦=MJç&:²žZ}Zb,  Êéé#ºB™‡ðæÑLÌAÒÍY*¹@¤šb]ò»ô™_T”è �/!SŒ¦ƒC(dî}Ùb'c/ì¢#8–ïÔË`ˆâܰ×E ÌÞÑkôœ×û =d¼À/q7ÇšL‹Á €ZJàÜÖh™Î׈ýÜšœ^ ÛÞ«Z±ˆ¬>Y<²·éè�ôgž]ƒ¸"¼tô[ƒ&•)–î{[ž~©:%÷GºÃÞËÙPêPÉ‘Ó «Ô·Óo<œœiáH-&:¬z„ï1ÄLʱñ'[û¬_öPY”(™óµyaÀãÍ퓬Gý œ¨ŸºÉ4Œ@±æf41¿M)Zm–V”ÉÍMe{šp &¦ÓC¡ãø èJE°•Ü\t@ V“GĬüex^yô®KpÇ4ÆZÜÞù»¾Ág‡å@ÉÁzœÉd¾¸ºÀXH)´Ä=ô&æcAWÖ”À¤o>ABTnÊÒêš'ØÌ>o¸À-[,%ú=—åCäYÛ ‰‡¬w{t4EàWÄoN¶$'û½6%dÌgîÈíot”ØÅLXÜ —Ò©ídÃK†[´ð³=ˆ%’t•|¹õpùŒýÊSð˜M`RúÕ/¸RqЬÏ.s6ýù“I¢4i™ÔnÔˆ§³ ¢idË“ –u8MS`À'£v]Í]ú2›ùmo»Z¾FuÖÚÒåö²?áúgÓr…¡°'‰\^eÈb\<dæÆÀ¦~Ê­ì…&X$”¯²_S>ß ˆ›~D¤ ˜ðViû1=!€ñG¥®\e€cm‰çÛ1K✩3ú61Âzœ°¸²&’'‚ÞðÞ¤±´â2xÀ¢hî*"êä…˜ò{/ÑmêíÝ&ÇÈ€„"¼QŒš§©¨U7éD" WPÜè0˜H*PÈUýâBùY@ñŠ\tܾšyA2�¸«Œ‘•%,æSwvÜÄûÁ­Iì2öÁz<q»ut[¹j1s-[/ðP|¤s 4ÏöªÖÚÕèPAkGîÈõ8-K}ç$Ž\¶ð¢Õ­¡ÑïSBdñË89©–{ï½6ö{lž�ÇÐT:Ên£c;0†p ×U¯UEuói$£é‹“TœNF잇g¤6~TXÐ_F}Ò÷I7 Ü#Ÿ ÓcžíðÀ'4RžÅCø8¯ŽŸ>­·¼Q¢¯žû@>èË>ä„™\i`C]I�Mާ@6FXvqï=§+/%ó ä– fÔgiïõówÇòöIÚ¦‚Fï2%Ø“A ¥â§Î÷D8t<Ñû…"² !^ƒ¾+óU0#âsÛL7ª]Ï ÑðÝzH&[¯xO¨‘ðÍ‹:…¯ÌDZ_Øz‡*í#".ÖÀwṈ×çý*õ€éÉa>[ÐWúR|ÀT¯uŠçµ&Æs.@“q{ƒZà[ Œ¦ˆnÝæ"Oû%¹Ñm6¥ò«¢8!AÈ 3hzžg?ç.ø ¦CçÏÄŸ½Ú«ŠG|H ‘`Á¬,!Q˜š÷ŽI)kŒ=}4™¾*ívÄAÑÈ à!p5Uë4ª Ì'ü(?ð>€ÏrVԲƥDý„A[”Š;<ò{¥«&ëê¸ÄIl.59+¡ò†ÓhRÚ¥†…opãnr°ÉQN€|cée¶45ß:C7ô¹ŠC* šyÕNž ¦`‰æÛR§à̱O'#'5ßQT\ÞÙU²˜zT4¦˜ÕK\¹9“¶„T.œs,JÀ:˜ã…—x-q*Ø1â²­ïqÕ³h­­|¡ºîþFLÁ±ÂÕ×r÷¶rý‰…ôtbñAdX´ÏõÃdO¡žª§ÍSÂv º·ïÂvæ©K²*vq ª —ÒÞ“rÈС¹Ó,0ñˆÈœ‡<`5|H”jÄ7Ë,·llˆ¥‘ágû~òÍÇ3šDtϣѤ‡·Ñe2tÉû¹%QLóìåa½Mz©§¹·&¾O®ý€iô°Þ.`,R¹iíe¾Œ’¾ÎesÿæûYÓœòˆŸEw ÜÖ6X:†À—ê±³?ÍÛ5=�Ã\¬j1(é¶m½ ˆF«“Ú›±ÖJÝPï{èùЏFúâY–³.y2T£Il,9jšÈiÄɨ€•lνx·{e$lë JjМø¬.aQ»FçÉã,Ü$#âLU&Y »†•fÄ­ê¥×¡Øt¬×ámûklŽj¬mö5Ù~©­G;´RÆ8HL!Ö¢²ãù ¼°ú]òõ?ŽÓ»â ùò„¼^`º-QÀ&;§ ]yû¡ô‚èÊÊùm­,^IŒC8d‚vzB?81|Å=+ô6^–ÇA.þ܃;rwzIÃBnOJë¾íhÝÊ&#wAÜa“�Y|´£{ªï=`–[~b-¨šÏìí™z l¼€+6ÅíÔþŒŸ…-mÇÙ8º[´ ç*ÅcžÅ0¾ò WwG8PË#ŽuãØØ4ÖT( 㧤ÍÊ׸ûˆ²[^c8²Æ+e‚ع¹‡Yo›Ö'Áxèp¡ ž˜èAén­GjºßA"\ö>µº«kZ‚€¶›HÅ#¥“Mw\{Ìçp'âðFö,1y­<®/uNx°@tWÉVC¹bánPJ1´flê´h±=Av!öåp¤â­ØÁ÷°h“%G3^Ì)Ž4­ÙâM“h)¹S*ltU\Óô;zSÃ*áN§­fo‰ä­šèPqô4œŸ¼]|«¯�²å.tT«Ô¾GãsÜÀ‰€yq£ ¿«[_&laÇÁk`Ý+ÂÄêÄdS9óm4ìC™´‘|ŽV^gc=VȨE³¯*Av® 8ˆC²‚%—ºŽÌøhcq&}~üIXo ¦¯'1éÅúËXz%'°õ¤Ý¨e¸B:InïêSÎ$M6~ï5—å À$*8ÁNy˜6¯À½~t …rÓãreÐÍ„­ä‹ù¤;ÇÖ ÊΣ®NâàÜöRd5?‘"W¿f™q\¶-|Y ÷2ÛHædps"¬÷šÇIË…{7²á�¹Ú-ŒsÞYÍ÷{ ­¯Ù˜È‚ÜÍÚ¨Üê ë-È&’ÕÎ5h> }Æ‘0"<égcïQ²waÙlgâV{!‹)-©ª7–¡4öDlÍÔ#/Pàp—íœ ¶~L:wôÚ 8ÉÅ-™Ó_ËÐ Yuæ³Um¿Ó_ˆ_­áÿ—Ù7Õ7L£ì1ÿÿ˜ö|}(†—8�DF±ÿÿóG ja ÜDtR‡n«|8î¸Oí‰Ú=àYX£Þ§k0Ÿˆé} T»2à¦LŒ+" ¡0‰faLy3¹‘ãÊà¥A$᱊Œ\ý ‹ð=X’ǸwÒ!ïX\¥„©qûê-3®¨"BéCÂÞîóÐj_A�sY1s߉˶?Âì×¶f5h_Ü x@ÈdÉá ¯Üÿnø÷’œMk'Gë쬨Ojò„ø�ýÁÐ"²wÐÀN‡!¾}e%=8”,kÊëÅ zÀÂn`Ä» ‚÷„Óý„H°…u•ùñD¿1æ£wo%ièð EXŠŸZ‡½'ÌíerÞ°y½Kæ«ð1ϧýú™rÖn¶µh4.¿|B+eýøÜ `vÁ$±¹]úEÖt+ÊÅÞiß*«pn¯ÜƒÅíÖ)¢œˆUTÐÝ¡B8Wǹ�^R¬Õ�º®-ÖËk0¤fDA=òè±×´q–õ€ìxEŠâÆ/÷a¤7Éx»H²“çtW•‡:w±”îJà€ªMwZù,ªí®é3Æüùœ{ùÒ1š}o–rùê�=K«ù_Ù@£y¢{)òõ¥×¥Zô«™Ìs- §æx9U×Âùzž¿çôž&&¡@¢<ñ{O^.ú©j›Ø‘ætlŠÕî›Õ·ùä çÄ]úòsRÑò 1‡N™Çª>4è=c ÏĪãM¨JöS.:™Óª…ìÅ =!ÄÚH6â†Í‡Èè2s€ÄšÐɯ àWúbú&Ij_úqìÒÛy —ÙbÚï —DÕpíšäq ¿8£eâÙgzÜ¢ÒNl&öL'¥¬yË\Ðh¹ƒ5Ð�â]Ý{æòÌÇbšTOSjµ –3h{·rëÿæâþýïÿ Çüë?ó¿ÉÿIÆ¿ÿ¿pÛES%¯û9Ù(*°˜‚¸¼{åït¯Ú} S7ûRuôuán†;�W<„×W»7”꺀—œâëùôE§'î»È[zRÞíöšÞ´Rùjä%IV ¦ø„q û“!YM~.E•s£s™ý$Röª¬º¹$FžÏE? Eh¯Æ®Ã„z)H°‰Ö“Ö—c*'Jç©wwz�XOœ,·sª¥8rfÍ^îÚî±uÁu†©ÕâMj0Æ\ÙÆØc/ ÕÀ¬Ü‡z4{âò¼|è›=ÚÔW@Å—pìöžÂ’3y ÷®wÃpQ†¢ûÀ#5iÏvx¯-ïPÞ«àöÇ9U­ˆR9¬AãŠq=çiMÊ@‘.ePþŽðè¸Þ´ÄÛ|¹[Š/í°pö½p< z GËBºÓú°BüXyÜãV ܤ>õm µkç=ʼ#õ…BÈ»V'(¡—o ŸÍí‚Ö­Q=$6Âá$mà•—&û`í¥e4gȶÈpÈÆ Î@ÉÆøkYïux™¿ªð”¼(Ÿ¾#{=·%ö.ÇöˆymÓšÁ�îͺ®æ;kí^2™¬Õ%äw˜‡>i{3ÍmeP²e*^w<­ÍG»ëy>÷ÖŒ;€^|�E(o‡@Šù-c±¤Ê;Jiæ ÆœfAšI •Ê0“¥6ŒJ|v€¿Ú$Ïp�§M¬âûÅ׋õPλ§RÎÕªZ[¯Hx¯C£e‹cÕ©²rèy>¼!_F+^Âå2)•µyQRLc/@u­õIÈä‘öKM:À]}ÚÖE©­Q¸m9 ïˆý½ÍR$ñG&h¥ÎAÞÆÌÏá'ß(¤n0Àä³T弚™YÀMºwj¢vÖQg™ò$à(:¸‹‰tÍZ}Q–M¥6ê)sñàÆÛI½‚çðÌi¤*æØÈ!bÝKdœ íœ C¬‰úÃ|̯ɳ˴$§^ÝéŒJt&G÷ã3Rw8ŠWó®ñåš(ïmóÄ¨è‚Æð\.CãhiOŽÇ�,ª”ñmÕ+5*±¼·í2IÇØk F=° „j~-ºYú8Ÿ—?Óä÷Æ9ø¥½<ƒ7OW?¢2Ñ]R¼;ú+Ï­C MÍÇr´¹# Õ¶@žH®9bFîÇÅs±–[H÷jzÏÚal“©”(è˜õ:@—> >Å(›}¸@ÊeÊÞâOò@$.¹MCFgâ¬Hž%©läYR‡ëy)¬MëÖkIݽҫ’ºYÂ[ƾ©- ‚Ê2½ˆðJ\!GIb-pÞ˵П T)­lkÝ {Ž¢ÎæfqŒXÙÞvðpQ€Ä¼&¨tÉ#YiÚÖcw˜¶¨¹ëŽÍIüK’î¿$èP¡ªPÐ|²ìÈK&nøðäÝ�fÅ­?ÏÞr||½Äí|Ô»ü’ÙtÝå]gÙäíY)lßÖÁ\Ÿ¸ÕË{âI®·ÏðÕ±=Iç0©RÙ'®í¸i¨uJ:ö’CR€ŸÛ(ùÆJÌ Õ‹VoïÍQ•,~§CJ’úÀçJL7ʘ‰•ˆµuŒC!1Ò4ß%ŽŒe²Ñ´m¼šcSp¶==IðÞ+SëÜÒ¦çt|o`9f™É{˜ôI> ÄtºƒŠ6IJö<£,Ü”£ÓÓdÙWN9s¨…žÆgñ¢ P¶?~‰ Á(|Óº(Û¶U¸3´UXo*Û¸{_DvG™êqpÑY¶X9Œ< ¦YšºLÅž{Çn™Š4;ˆLè"9(wY¬”¢çöªòøÖÅ’­´A‚} =<„^42ÅŽ›ðî ‡\iÇÀlÉC%5jÍÜòV|hÅ(:L„½Ú×Ör/ÈhÜšÆÏý°¼^ƒtÆÒ“ ¶sОœ4TíÆ ›”Uy:|‡ˆu£e”6nüèú˜æ6«ÀarZ ÊS"À´3DÔ:Õ÷òÀǸüxÊ´u?”Ї #Àò†yï$:Z…Ž3ˆkã5Tˆo’kArI˜G$yG0F“ªgZA_gsÏ)9qÖ½]‹Û“·µ¯ŸÎùÃI¾¿ž3þý%ui2«F–˜?¶ëN(12Ié}‘3ÉãfN oFn†ÌŸô¹?xºò´×ôöÔ#e­FYÓ®lŒ0^Ñ XE6‰²-› ”|þÈÅ ÷p-wÌQ}#t,ÛŒ‡íü½Þ¤Õ  >¬|’ëXbWÖu·ˆ¼tܯ…ÊÝø*@וœA‰¨êB€–uÜÝù½|¾N Ü™] €ADÃï­­‰×0fÖ ©ó§ˆ7ÐïìFÐÞE'æ¨H¢fÀwDúŠq³y`'Q]8¯258=Ö(([B%¶)*»Ó‡I8i»åü@ÉŠÏ(´€œW` …XYÈ MBÔ Ã0îëaßûìVn \·žg±*‚Ëž ¬=L9Ä‹©3~ÏôÚ8ßÓ:¦+1óh¤ZÙ·šîw©Ù.×ýÖ@ ·Šv¹ª®×°^º/�°òféà¶±m¬ºÞ‡BUݨ™ jyûæUн,¸ÞãåXªjôBÜÎ`jO0Ó>ŠWvåk ^R$ã¬rÝÖP¨¹  *Cr™ôÜ!CQ©vAD‚œ<±Ž‘µ‹Ã1/'ïz×Ö#þ(ß,׆kM¡ŸX…ôãæ7ô–ºEHŠóéËPŒ±eê§Û,q—+ZІ¶÷4¯ãj%Ò†Þð“¢½çIK”%síUnl¥[‡–úNŸº…´&êì‚<%&úÀä{çfÎ&%[á¶Öumƒ yCP°ŽÎÝ«×]Bðˆ®úÉ,Ã#>Äjg‹ó `&H!'ý\„G…ŸÖcSpñ‡$©5Œ¦#ºSeèyáÛðD­ªØç‰ŒÅW©Þ˜FopÄ<‹+oàIÍë+^\`ÖgþK¼åAL•,‚?i‰À!S¤µuM'^,R¡ãNeKÒF©:IT]tóºO®š\IÊCk·˞x�’†ß8½[ˆ¼â£çúpÉÌ„Ž`Ÿ·]£¾ç˜€ 85ë=2ÒwýÉ›=mE(PØÆã{»Myc×#ºÑô�$3ëƒïlè,ú"Ül„—Ô¼Aúb¼6ÆðA‡>Ä-N§nòTjÀ}ÍÂ$8n—@Î ŠnÀ}ôº[I”¼% ÚËywÕŸá<Fš.QöÔÇGO"{�ÈW±Éó½mÞ‡"ÐØ°Œô!p‰F´FÜÖ^Ù ¿Æâ‡ÂöÂ[Ö¶´Õi“nL¼]‰¨a4‹ž–#èdc¼çëÚå§Ûp¥`cÐñ¼³Ñ¨À¢�½J)^«€”—.²æË±|rcùä®Ê“¦—¯×ϼ…ÖÀR•O}ÕŸÎãG «ˆ´—s̓næ¸T.–ït9Ø”Þ<œ¼ì( ާͼ…é¬ñDÏ#§˜Íiýîhß*•Ê #Ã!ÌÓG;² œ|o”·oîOP¬®ŠaòpŠ8Ö‹Å݉ÓÍ5d” h猪XĤ=öÔê Ëù`’ªŒÃrŽ,Ì„ó”L©¡b}•ø9ÎvþˆÂ.Ó6ŠØYŒJƒ¥¬ÀÉØ[ÓöDJoÉwI¸¡‡ý^’_ šê8 wxJ«@ò²3òRûIåÖIæQÅмGÈ)?îš„ ªFA»¿mWÛ»vÒ®GIkO›3Eñ.·‹õ®ŒëÝ<%&b~H ÖÖ›´U}á¾hÆÔ¯ÖgWG "ÌUó7ò¹‚ Íó}¥ýÀ{Íâ†é¦+& ’F/f$Ÿºx€¼�¶Y÷€A1×× ð8u�Çì꽆%/ˆwûÞ³ZgTšvU µdر# è’LD;Žal£²]£tlÐb3(X¹Å‰e=Dtò­Ci1T¬¼k‡Ž‡û¦9S®ÖæÔÊäu%c™ìJWš§GRº$kÕe*I2ì*)êªXƒ¾†ÖŽÅŸ)lØ’šöc›P’í}þ®Ê™}ÍŸMðRˆz·€î«DFíxZ7ª¹ó’Ú Òg'§€³ qí°±ý=¢m\=dõ3P}mñ|™8+ >âð>$.}bÅgmËS0ÐÐXFlnÒ¥ê² jéYÞWÏßäf’ wFk4X^Å]C$¼E•1By9_óÉ÷nððq¶Ø_¤ø¸i«¥t£¤0o9n¼ÒkÃwƒ-2fNÀ[šgàš÷néx†¨-s„·¢c_`¤µHVv¿vœAs÷Cƒ÷FAa©¢ï†-ŒC[,Àæ¦Uzî½Ê¼4àÐ'iðäMPЦÄöAfE ÄPè]/èÀð7(>…¢®Ž³ðdEËus弌×å¨54ˆØ¤ªf.ÀªÈt‘ÝA t©y¾ÝÌ0fBغÍAzKŒéÍÑA9iQ†>ap°.$©p·ÆkWvضBº„ší4±²Ì�m€à�µ”-|eìú)Œ\¾a^)“ôŽí*|Ü‹S‹¯cR鑦äp-öšäÓ¨r‚“›ŒxøðP­ãYd„Ƙ#û­5KÕÝúË'ŒÁ.qt0“ØAGí;7ï,cü}`€ˆˆ™æÇŻʒu¥‚ÞtÉ·ÛÛy‹Íɺ…ÈØ»/8ŒŒtàÑ‹í[¿™æo'‘÷ÎãVü¤Gr«aZ+Fîí€ (‰º†Ì4î+–È1€S¾ôXéÞß…zn%Wf®5iÔõ–rf½`´øéâKÔ›¯M*«c×^&»A«áH<j—¢ ìmhlQ˜æ˜—f»e‹@(`Áôƒ¥Z]6ÂñÜ 'ZÅå¨åbÚAî´MŸ6.èÄIú'õíé)ߟbõªŒ—âïï(ò¬²_ó\€7¦e¥Êsc‰sOÔeê8²VÒ6^0W¿‡”²<aüƨ†<»QO9[ MqâéULZ›S^TãéÓEëbl[ؘ«)´í¬Ô©íé¥Üî};|xG|ø1ÄOQ«'Ù.g‘åPØáÖkpžµ*OoÙ%]5‰zºŸMwS±"!aßã¦aàz¶¾éÐ}í­Û¥Å\gïx€=áÆEÇ´V‰uŽAÙ¨dÐçnk³l'kµ‡‚a;Šô¢ƒ0æîzŒðd&^Ÿ<¦ôHm TwÃBŽÇǼȴiNALï¤Ræ±ðŠÌ.˜æ™[Õ»ŠÅïaÖ=Ò›¥[œW(ïeÂó:‰š¦Ñ÷Þ…º"&_TªîmP®7Dl_c>­5RG½¼n(@mñÂeê6PYìëmܶÜ:Ö“ù%†zL¹»^s^v CM“ÐéCÁ›€©J;çŽmÛÕ r¦+Lá!WȘ1§÷Äš¤‘Qø~8¤ëòdl$¼è™-„Ñ•YZHq)2Àa_§ð:Ó3z‚ç[ï*…IÉ5²Êd“µ®áT’–CÔú: úéè+ê¶—cˆ… Í㬂Ó+V¡Êôúº¢Nj Fô¤Ó:^ÌñN]·"#¾öçð éÝÛ½^j‡H˸lƒ¨†(9ÓG£%±SYcÐ…Í>PýB1 _·¿Ý½¿X 3{’.oÜèέ9$obÎ]³ù=·9bég©àÙv¼°(ŽˆjD�¹‹¡ h¼+ùâi$½–¹+ŽÀb+wÀYÃÚ M3Šˆóõ¾çŽº+áÐ ¤2WE…Ï ßöÃà wbª†b¯¼ˆ°ÜqØ’s‰a*¤©ó›Íeën:Ÿ·uº>áyµtìøN½ôª¹Ñ;ÊSÄÆmŒ9™ž)#<y^4¶ 7,%Pc ‚°Ãü §^™©Ïys /òÀ$Ä{xˆÏ„æÂC—×v¯ yƒ¥Y³³¾ì Ý>ã€38Ô Æ®ËYÃg³í;D³2Œ·,ºÝLµW ª6z/²v¥+Ÿp½—þ¨±ÑÈahj W¶oû™#Ì=orñr…Þj'Þ­Jµ¹ƒ˜ùJ y¼=2%·c¤™ÝALyºÛK÷E„â\ZWŒÏú8�8ì– Tgg«‘¯Ï²S?#–˜®v8%µg6aކÏ(A^ÑÈ#ˆ¦EBí~™CÑFÏG ™Æ0ƒzwÙØ´)Ù/§Ô_Ó3²^3º^ª©>slĸâ'¤å›y8G¸âBD¶•«xIm;­¤p¦Y˜Wž£CO@Ø{°GÑ›áv–=—@žö î;ÄM”(ºw—[Šn¼ŽŠJÃdO:æ‰Z^² Ž—jš°¢üÅ '±³ é_°à„.°p-<¸Ú2Ó^é ª¹r²_‘²v±Úë冰<y4 õ.:Þ2ÀÁéÕð °ÁègqJhéUuæ<… %" |ü¤£êä(f½ºÃ}ßálÙåº#8 Øb¥Q’ZS™Ž×ø9‹y±æ:Òƒ{þŸõXc€;º˜žYAÊëÇ„ l:‹X¹ÙÍ’Ä7øÂOOm‰à½ê瘵:Ë ¢žßô‹Äz —ÁðvŸ8�?Šˆ­Ç„íÝhgv”ÂbyM½Á¡Ce/±^·Ð¢ïºñòÛK±= އÏ,Ï5ƒÙïyÄ ¤ÛNßö5VŸ5Ú°Av³»1•’))"å.«äÌF«adÃéy›TB®§ô�H³š:òóRD'U“… ¾icç|.O u‰^¨@[ð�îùÅq3¨21‹› h Æ"wˆ^_Ù»2*Ö¾löÊà ‹[¹Íƒ' 7C˜gûJƒÈóŠ&ì(ß{)ÃÎ/¢uø$mk/²|T›Ìq+À%™öyóczà¨0ãÏ“alWN|Œ5ŠíFñž¼t'ðf~�‘kIoDL!5‡«uC±½ºíì¤lRŸAŒ‹?ZR3Z@w-){ì^Î@­‰2”Û 2(|‘Œ{O‡ôÏ»õ”÷lë,±ä� çµW—F×@=õ·–ìàÕ̰}ï}T³]v¢ô™üE ´LÉ·´¿›ÞÛØSzz¡C`Þ:Ý2Q²|¸%YµIo‡ÙÜC&&Úo–í½x/\[»xàe¶Ê´Õ(9j˜K_ËÄð¼·ÝÖšþ ÑÚe¯ËbN-¤<ŽªÛþÝUxë$.Ý{¯ä) ¨©‚œM€t)þ¨á¢·#`´ïx˜iߎ¶÷<¿HÖZÝ‹”7 $|¼¡dJ’O ‹«²14qM*x2ïLB· •ó›3¢œç7vHÔãsê ïªáT% &Üë§W©d~Ñ”Õ×q©Wä�‘DÞ#¹®<ÈiAråÑ÷ºáŠÇ±rÃaCˆr«(Á0¢è¹-? y¶ÀÒ=ë×ÌEæÈ„Ó*Ï]ðŸ\ébÙ„°§@—6Pêdo@9ïÁ{\ô;™Ÿ^F"€7²à“wî!¹XV¨E–\j÷&ĵl÷až•® "8¾ÔäîàCKÜ)Ð÷›Ocëø¡L‡×°¼k¢MÄóM9ö–iˆy‡®ÅÐlþ2“kÓrw�,¡–jQ•ƒðÌ¢mɹü‘šË¸õ›MzÏÞº éÄzÞä¯ÚtSC¼£SÏÊ)ë–ƒ¹S®Êðvc¢æ¹¾ô£:£;P´0-ž…b±“K*w¼N1"WÞêDT  W£E˜1†€;xsØáüì-åœIŒNË“Ìàyc(>‡¼´8|Ѳ;ÆDD¦øJO^ÇŸ¸ˆ4¤S É$Le*‚ΆˆE-£ûÓ×6¶ïÞ^3äÝS p õ"rFpŠžé•v(SNÉ;Ô»Ã~C¡È­ÕÜ!mù­ßJh»¶¿lœ¨Ôp¶ÓUîT~{o Z.‚9U¡EâŽl8%3\©ïJ­Øa€ÛžÖ9 ¤­Ð‹–¡V7wßò ŠJÙ3xx·”¢Õ¼~ËAઠÃp>•S€®Sò&WÏ»¼P*Q2LniN 69ÄÁwov NlW„+2Ù !æuS¶øD‹¨¼bª“î׎üØY«„KÉÌ68µh2§{ê­ËÍÖÀk¤k¥¹›žè567­ˆ[†âp”w­Ä!¾Øæ"l ‰âô$NCiÇàúœ®{æâêò�è]â­ÎOÕó@Û~L"üD,+C‡áÁkÇ×–n¯iØ%ÂÓE§Äˆ¢ÜYšœK]fEÍÚ4˜l ï\Äø‰Û3ž8È2À§y»8¸s¡4˜SðôÈ9"gý¹®ùПŸpºìÁ˜¡ ¤Œ  ò‹íË¢d×Kì3[{fµ®;,§Íá,‹!@ÝõúªùHL'æA¼ó˜&ˆ]õC¶>´Ú’•e„çžÐÛ¬üòU—Ê£{SÀQÆËÛ2Å(â !ÏœÂR¡i¯ Ô¸Ù»?—bÛŒyB¹‘‚²ø¢Æ4¬ÊA”ÖC#P~_¸ø'.¹;Òs7³½,rø/q~hÆW›¾m0 ŠçÓò¶†àÆ^ݯÖÁ³â«ÛCC³ÃÚÀ¸¦b¨>e¨•ÃÀQ1ªk8ÙüéÃøÖ3¬š¸†Š/YH‚ÏŸ¶z†ó䦖¢Gôs }›z`ž‘ï@t E‚ö1¦…O³6`xËK |eg¢Ð©iðRÓµÐ{ÔrJ^⣜…J!ê '}\O©AŸx@ß ôÊl® p´ä=Û©”‡W¤[‚ è£ú®æÙ]ñµ¤ñÁ7í-é¢ ì½\£Ø;ïç™èÉXa‹˜–ÍBÌ2¶­hå Œò Ô¶žÃø#ˆ©ÆB/F2Ú®= 6ÚPW=誋ðHóqy%`FËÁud×05ƒ®PË3GÇrlsKßëË×{²'ÔXI-ëXäñyäSjÄ󮇇@:oD8Ï`¶Zn^Ø;‘# t½5(ã|1ûï-_>(©‚ z¯òUà¹;JeÇÃ%¡°¦{è0¹\NÌÅOœ)éì�]N#nŠZ3†©‹M 8Þ–šÄ8„9Š‚’Þ' Ñ.hÒ¼ÛµN"x[Îeh‰é$I¡2ÔØØ ¤âÛ2Äì¡xB˜ýÐ/9Õèàs%äŸó$^,YŠ@n“K{ѹV_Ã$„"W•>¹�ÉÜ7 ¸3·àÏB"Õ82M¯ç¥A˜ª*}ðúÅ‹Ôòë€#  å[ß¡y³öqO.êI/j#µ8†¼&Šl ¢¸y¾�Y›zmÆdó „¦…îøIù=®CÞä …6Oðc57²šâ–Àak˜—˜Õ¹›M–­O½ˆ_Âa¼’„[PÅ×d(N±j´¹  «'¤Ä†ö0w|°ˆúPµí.q(é]‹ùQ7ûy˜óØ=ŸA$ôÇ37™ÄDIv3‰¬’¢-ˆi”æ !z $`/¸1ÞŽˆ»‚Ía¤²ÐñJ{À­²¿)aŒ^Ikk ýtÞ4ÇË—êL÷‚!zÑ•ˆòÊq ˜Á±YºÏ Ö…¦(© >‘@Lk,ÔãõmÞölQA4õðJ’ÇïVº-›”šU)Ûám#8¥P‚<8h燧¾gÍms BäûôyY’NOÜ¿‡g\{/DG›ã:X§Ã6ž¤i½¢âÙžTÄ—1¨ò\Š|ö dJähPýF/OÍ[wÞ“|¯eRKL®ûJùŽöª¥úH�@—îÍ·BRem;1 ¿6‹|&ï¬ú" 4ˆLl¯ã¿„4i…·wç”ýhiÀÊ(¥MÚ°ôáÜÔ½3æ}$0´UÛ4óªäª^F<8J© ïÞ>Ø|åpÔþûÁöš†ŽZ°¼Dô-kBŠ%PóÚ›|H®²(Í$8oJ5§o¯ÕzÏ€pÅà¦ë\©JʱXq¿€Aà/aÒXÉ‘#Ñ=Ç~źü÷Sä#{¸ÖåRÌ 7ïqlãÈ=#˸Ž6|´§Ï, æ©™ B*Í…æÞ“Jt¯ˆ€ï[­šLœd‹’‚Àv/•v8^d1·Ý¹F“FÏ™vº¨òWÚ·ñH8ŸêÚåô®WѨù> ò‘8:HamcÿEˆOÈFª§‹ ò)©«Ôô6ò³#¥Ñ!¢Á®t1 g+“‘fᨙé|ÔÏÔË<zOéD#^—Ñ{NÆ+Æ�JµoÛòîäÊz°Ô“™ÝÂLÜ¥"z׌)*Ó½,0«xAïQ¾›è”zjÛ(z9ðÐ1ð!oxãÒ9]oåu©ÐÓx ­ï• fJ;`a^ðù¬•¬Ê ,t» ãM ·éJãAʃ±WÓØXGù6Y4¬Ÿ<ÏË’³…`²íeöŒžr òË‚s$rxØÓÉ[EÌ”#yA¹Ôg´VìXû–8Ë+Xu(Ë7¬Å)†Zf¢çg¯ÚMgѱ™_ƒµå{D qþ2Q¯çNÌóè\Dé`ôÑqšÅ‘Õ>À"ÓnFγ¶‚$¸…a˜j*K> ôzVÙ…‰íèlGrgÖ(gMt’C©i1*Âs1)&OŸE²äÜin·ÃIJ8 Ã,ô«Ë9Î'“J;üÄʽYˆÌFß½W Ǥ¥y‚¯±øU~ƒôeÌkqÃÅhÔW°%©$)36ù|ÝuÎYW¼ŽÐ@ÃŽ'$ç»ûÀÞtG^ûkv~éhoOžqóˆrÍë0æé΀­ìò;ji|ŒªEYAðú:C“A.ß+LÂùæAR·Ú³x2å ÁútTb<e{8„¨ÆåáËa讵+„ˆ:¾>Fq´zÔô sL¹ÜW/‰3Ü´ÇK¯ kº{F,J ùø^¡Úéá@Ĩ”[ÜzYð3ÒSvox¢áÒÍ>ALœÌ …¼å„VÒ&ã¾À{­rj"Ù·{ø<ž–ã@Sšz‚î*Ч-‰bÏÄQ‰$ÆrH¦’8 +ë4д^ð-À4�ì¤$LÊk0Áô@€)ßãíçê'ãËnrÔ|CÔ‚Ûwû “a‹ï.RñQó=«|%´HZÅçé eVqø�JÆCÎr®‘3agÞú$׊½\‘÷VbAª}œ\áõÎÌÍUŒ“€"ãâÜõ¨0¼ ×’HíB¢"FDš‰qÕCÊ9*€0†C}ÐO uA‰ÚÀýáy §L.rea§9î]^ ©cÚõ£3šáO½Ç5áitGK&¯ ±Œ°ICsìQ¶Y!M²Ñ‘ð H$öX½HŽTr2ÃIb,´ñ`ä¨_j«çœc-ŽÓÃ)m,ÏèÎKÝðúR†àK™K"7®nPw‹õ=ÄÔ80¢¿œy —Cå8ÊÛ¯@rÈžê)‡Ë³˜“j{£éÏXšri£+íBìUaSúŽ%ÅÀD¼ª>‘tu‰íZ‡öÎR¨,nÐ7›D¼N²Ï• ‰7 ä‘-˜”â€/Ç4:·`0UqZXñq·²£ÖâÕq¸àƒ”õ;P{ÝÞœ/ GâÕÖ¡2Æ+o×»6oT(Š3‘”Ë´Œ§Râ½v¬’ Í^f¨ [Dvò žÛ*±/Ú.’ïZΛàªHÂxUÊžW/_DêöÈÅ2æ!àJêBà1ß/¡gÝœ'·}꯰m†”yŒÅ›ånôÉn¹´Åcã±kôd¬Ù:œ•›7ñFžÙ·54ƒ¶gžÀ‰U–úµöK2.­~òVGa’aýià‹bŸÜЩDšÎ‡Ä�Æ|^$tC\GµÊð¤'uBFW 6]}ËãÕ³ KB¶šlCÖŽÃpÇuAHYôb,Íc¼g„%ËÙN³êŽëôVöûsÇ÷W) k[à¥n*Ü+´¸èTšÌJîËYÙ' ¬ï’ûå£ã‡ƒ×CËrûHÀ®ÈœìDëZàArg°>Ù)|,†’ôÚmLä&°PT“ ï!ì5R&âуú;~(2jKÛÀÛÔE½+/y�Î,ÓÞôhç(fY?H%ë69Ã^s‘¦Y,úéŒ9#” žEØ=ãÉ,–b;kNhú§4£´³Au úlرwjˆŽ¦²r·aƒ/âÞ­zá‰LXNâzF<ú‚uß–µÀØŠŸdˆ=X~ªU]Úóåˤ6¯ìÝMûòÚêU4G±f‡p×ÈË iß:{Õ|#oûŒâÓõ¾{íåªØ12L Å–Ãíìí¯,pðœßùœÆÙÓdäª�“â*ƒKN€CÀ[ÑX–åµ›¡zJTRÔ„µäÞÐÖiu–]Æóô½õ˜hÃ{�ØB ¼9°ý¬¸ë‰vŸ¸Ï mész„ÐùL-«ð)½ŽÊͨ•íò©òyÓaí~ZÍÍü`#Ùô&'^NÆ)’Û¶[lCÒ¡ÇúÔႊÐtäŠÏ4|º¤= ÞÈäæïSâM‘ ÕMåCμX´Û“IˆðÓ|€E°á.7áþP9JΰÔz]OàíÉ¡B¡wú0kk¢ßc$§nNê)âE°ê­UG*’J´‚¥h)E±ôtΜ Ë­ånw¯æÞ=Ýz(¤ní�]œ}kyǨ#`ú³§²úõØ…×eŠÔ(¶MX½‚Œ'KƒÃê€Wš@¢6gòø•"]È´ˆ<†Ú5XÅJ¯·8Ææc6B-÷B šÓõ›™ÁGÔóp»|é顱“±ä=O±LŸA ­©ŽÈFtÀÚolmÅ2Èý’æé—4N‹AËÀo¦iû„Bcàlwþ|=Rû!¡N˽Niº{÷ž³Ý;ãÖdÈ×ÔÚ(ûPK;®ž¦5NF“ø{CÒ>m×ÇçBûB¤¸ƒX»û]Em+GÀÊ8Ûƒ]Yö›ôŠÄkŸ*�rs(K’ú¼º‰GãE¤PǭݼÖ^ÓÑ@«Ïhðš(0›DP’µPž¹Ô ·îó®G†ºÂS^æ0\(ÍÜfWï8C“¶¦·á“—®°°•Èex¶{¨“ h•ïòz=”ü”U)©6a:Ý^Ú{ü8ÙÌŽN&‰_´´˜=–’0ÃäLÑ­Îŵ=Ï}‡ç ÔH곸Ú)8<vØØ¬BÉ‘›è¢.«í•€çûj­qe2ú‡õµÙ)ñ={0‰nJèi^«Ö´‘$·n+÷ïøSxššvðPrð!Èôܬ‰ð0KUúϯ×ÈIr`¯Ì(^±¯?Ü~†KêûY¸P^<±áF ‘}S ¦v±zœkªNDÆ©ª‘Eèl|1Ð%z)2|,ܺûp_ƒ¨÷™]ØHyó¥ùË%©ñÍœ-®=t½gª/×_Q™æ {°WSeáÀQ(¸J%…Öl/.¬Üz$»�šû€)$»êä=â~-/jvd•¯8_58˜žÐ$W–>_é«e7`»cVg`'�wv ããæVy®á›/€-d¾¬aþ²ÆDýM—ˆ"C ‘ð«Ò /Â$Ü¿´ÉjtÊòz üÎÝŒ²7qaµI3 Noc±.H†�ú/ëŒèã^0;5uPR!„ªyj·¥¼±°%�¶¹ÂCüES+“c\êaji¼§Sc5ü:ò†G©j5F6Éô� ëEë³J|#}£Ïn/ß8¨‡[Š¡ª²dJçÕI“Ãæ™J²‡c†ÚÛ)2ð¸‡9õ©ÕÕ{o9ãYw¿5`B×Ћð|¤!è¡R›’ñ¸ÑðÌÃb´wâùùÕíöSÜÙ¬›Mx>u†¶ï‚±iÐö ¾€,35g³Bš[z‚è°HÞ•“’Èì=Ï<Ø­¦<{Ϧ§q%Áoámô�¿‘D¡½g7ìñHõ—“ò¥6T0�¹s2›MˆŸBe•Ö5Gú5”>ïÁW Ï.¢Æ(E«/²®¹GŽós|“]¢7>íÊËþ|ø�#}}°Ðc N™:¥÷“î)6Þã õ›¾gcþl_f”«Æ U„hÓ×>ƒÝsWk%Ùv­üÞÉ—9TG-ï¹RIè‚ç<jL°^RÛ%!–fô2lç1¯dÏ3H6S¡7ÏÒ+`äå°°Êd%{/4D˜_–'ô¥¢ñˆ(RõNYJà–¦™×0ö½&]×âyg8­ýjMÆV×6JŽ{‚ˆäJ"ðìѳ%!¨ÈTà/m„¾´]Þ[x²Š—yLnÅデÔ¶ò—7u]Wò°Q=´éÑ» àÆÚ$À—ôPRBsòñQ•ÎO¨ô¥Î}UVš‰ÚÈŠQÍÏG…¦ë0Ê•¬D€3åÐä¢P aaÒxltE­mñ{•¹tÉèYÛ(‘23lý¼\ŸqÔÒX¨²…Œgð¸Ø Ÿ°®=Æ—®»´áA×Iiþ¢D^ãu$ì!³ý¢Ñ%ݵÏX£l²_ZÉë>Ú—‹„Ú{&‘ @K«vŽò6jä%Ï‹$µnRZ‡8/·qÔLjå±psNQ3cÞ*™¤>°± §:o ä÷ê-…öóœX@¥Êö8¬§.ÏÞž…å ¯zf ½YÇ2õðEâ…æXrâ;{6àHKP.ÐÏû™¢Y½¸R¸w=PŽ)®Ä+VjJðj­½¦Uk#«$1 M dêTjN1î=$LãÕnS](RAAìiÁ×&­ûH‰`æMr"µÓCc‘ac>9\‘*ËÀÊÆ~ܸ Ryò®½ºîl1:åÎ\—,yPù3gíÍÏ:©Ê>ˆ|H¦.åÅÄB+´©  G´m71$/Ä�BWrGmYWh:x8Ù–ÆÐ;<™Iï­úl.&¯@X>½þI£í!ÚÈ©ÆEê]k†õaÛFÎrr€¥ußê–øƒAcÁgž}»Ï×óË…/o–ãÅÏ9Q¿U÷5†Ü5¶‰sÁ¿ÄÙ— §(Vàæëý‚Â䥯a›½g £žâ çzdß1NBœ?Mnà·¶YǬ7 Adô V…t¥" a=ê5wj¯$µ6?¼B^íj ׿N „g…÷@Ï·3‘uÞB‰=MyIµÆ‹¼*®Ü/û€‰%ª®Š¶ím»óxä® IoWª Sõ@Ðr½:âLdv{[n`¢œB¹J×®j\0q½«6ë07ŽÔi’lç7Pôâ­¢Þ: xD?m²©~`¨'—蘭© RööÍT0³-Ñ–‹¯.R—ÃD ¯R`ˆ»€?Œ–^E%ƒëà‘ )Ø.¤#Ä~¥\Ÿ?¿Ä´âš§uŽËRká˜â1e®)ñ&—ú³ÛÊØ£Õ Ä>C3MÚMÆF¢•¼Ô t•ÉVVWBÊxÝKø@&Hô2/ë¬uÈÒ3°¥†Ø,íÁ!f°Ú™*ÚS¤·V¾MQœu‘;ôbë^[÷³ž ¤@ÝÊ—9ú”¦uì½Èb1¥¨¸ +ÏRŠÛ+•¥5¸Ýw”ùF‡ÝÔ©vÝFZQÜ KQrÃrWvŸ41!ÇLÏHø”„cʶØ<ìP澚ix7trîŽCÄœ|ÇÈ0$´$ àñžUŒó¾=}Ô¡î¾p+M¯pÔRùî‘Fòƒ) ²Þ^ ßA‰ÉÌWŽq;ºY)¥u|ûVÝ?Åñ/qƧýf¯¦7†y¹+oÍ™­r_ ?E üËÇSCdå­7«. 4Bý`¦ž@uNÐ5ÊÜK5 Xã¥ÍÚº`‹i¢g£ìX˜Ê`Î¥ËùpÓ4h•¤Š†RÚBu¥9—’{ M‘ª±Œ2?d¼™VÓ3|ËÒ Œ/†£Ži§ç˜_‰¨z£<y™!×Çu‘¾ë%¤¬o¥K2âÐw‹Ü%Aqr—ûíÊŒ®×ì=Ìx AôôË—r‚×ÐÏ—à-¿=€t~IÂÎb{ôPîWˆË{,œ„¯8i¹UD™f³U(ö$v…Ž8t¢0ØeÉÓTØ›FÕôá+}èš—çd‰ ]râ|lbôƆvQiA.²‡û1êÚºÑp³a‚lÁ´m )n<†y’j”Ý’ìí:êOv"ª 0zÖu¡!´¨¯T'­´t@ŸkÕë»òP|+o;€X.ÆÊ ±R/Bæ.+8æN=s±)¢ì) ÞyôPpLˆÞjì1Ð!íR€¸Æ ÝÓˆÓëk±‡Pµ¬æh@8Çïjº'F ÅóÒàœ_¢Ù{ü¼ñ´àpð ¯=Çy]y¶j«äBŸ>!bq¬(_áUŽggàI}`b/™š…™ûÙL!¹ YÏ˘Z6Ý,ëù̈ª9ñ±äãFõéxÃ^gkq$wˆt£nåÚ.ïurÁUã½áÔNÖØÏW•é—9bàrc‹L¨Y4þÐ ºÞó4בëGã÷—:}3©ðä!z…'«».·]˜²Jc©\ ®ÛÙJF-ÔóÊ·Eï„õ ñå8Ð"å9&(i 6ÚÆÎžô Ƴ3.^}…Q‡ÕŠÉ;ô’²Å5–÷6úº½=òÔ—‘HP–J6}ê€øžîí”­ŽÎ¤S¤,˲êq]‹H¨±gÜB*Ö«¨È¢�ðéW^W†¦¸›Ý«~;tpPÏAýá² £I®ÅFC¼);"Œ~ÑýtÛhóE« ùø$ëçà³|ñmô2Õá¹’@`´ØÈ„;L˜ëŽÔêmr'š/&ÊsÖ\‡óvœSDŸ&™õ2b{+IÇŒF4ï²_^7ÓâÈÌ<µ×Mi«hð~ÑJ|RK×ßãy—ˆ@ä0ûͤ(‰Q_O€[XÕXù¤-]$‡-ÓËŽun´v<Ç æjÄëÇ-Jʆå2]­è©>ÝŸ˜FDù�ž=ZÓéÑÑSÈè-'j¬2£©v¹A¢„0*h¸õr{èn* O““É|àX‹¬âɃy3i©SUö&f_¤^(8µOTä6^ï)·ñã~^ø(Uë-Í>µ-·-«y^艂 >´ó³8]»„é„·N œxÎH+pöÕ€{Ÿ®Èµ?Î’¬X’šdfi Q/eñjŠÞ)í’–µ¦8ÔÅ 9¢&ºE4¹ÆC¤Ý/uœ¿ÔIž“©Ó°¥F½¤˜½lÏz¢0Ф—ð—;~SP׌K/˜]œÇŸ±È …êãqÅPe -í£"Z¼º×ãïð•VÄ!WÏšZ‘ëÙ ¾‡7¢SLÉÙý */½#.0¥·ˆG¨„ºUL]Qˆ±áÑx‡SžYH%."׈ÔH,ÎMkÇfè™áŸ–Ú ‚®Ž =õ|ØýÎÉÒçôî|¡dùí•NXȘ* ‘³[dbD©‘¶³ÒÛÑ w}/Ï3¦!8$ŽÅ6xU@É$|<MnÒ{kF}v/‚ônÒV_¹ÔžÛëòHÆÅŠõ4ŸÉåêˆY,½Ý‰Q%ž¥½a„Íä㩜tiY³X%zªL$û@�3'*&À¼{¯ýŒ„’•Ó„ó´ &¼ ÖÅ@¯»¹R“í®ª³vÆ„«^“l Ù0‹ñ[´ÙãØBM“" Âåxö’S5òÕk­“ì3ºÌ¡‰…Ü~Fïl…±Œ6çßZÀëö˜8-‚C¶4š‡~|•Ì:ÏN6_rdÓ4邞Îsa“·o;Õ¨Ìßr >)2Àë-8|¯±çâ)—Õˆôa§Ç¬d¾«àz»Î±æÁÂÛ/ØXŸ Ñ-ãæà^|¬£&#}qoƒÕõ0'jÅóˆ,È+à=§×i²ê¢gàõð8Ç ä‹SHt(ÕÔÑhÍ_•›”DTXuî (‡:!ð«W˜x¥xR_î}º³]dgüÞèu†¾6Å%õîR_ë_ò(·C½ž­ä@tÉØ±…’½†‡ûtøˆ.*"г–h›|V¨š6´DX¹ØNˆp‚å¬ðžÐ¤?WX1]„§’„¶Uù˜Ú–4ŸÀ]O _Ž™èŽ„(Éhѳ5…}]S¡V7Þú%3‰ßÓò‡\t@Ö;U&¶bT0 P,@�5f^/tПɘ-ô=ZÛlxœ€P/qº%ÔO"¡w†‹¶ŽWÆÏ½)L@):°q’ú1±,¨Úàð•b´ rΕÙ{F^ÉÎ:b»>qgo„_×£.u¢àÏÃ7÷RCçž7E©Y¥^²cJ )bùábóSÌG gÒeÅ/ŠÍãõH?g%e}"°8Ou¼ó5í™pùLñ¥¿v™»QE¼Ë7é!zlñ@ºy„Lx»$¦µ:Ÿ¾‰uàzÔlª\”ô€^ÍVVL³JøHB§­+¶“Œ¸9;9Ñ:Q(²$WoÐÙëõÕH´—±ic•˜c„Éž¦¶�2P ­'sîal)Ž%¬Æ3ƒž€T)}ððÙë¾h0…ðtµgªÐK^KS|s u³ðÄ¥¼ Š”+2úí\\¨U AA¤© ogÜœæaý0~ìk)fx¯ßRÖ®˜:FbK¸ãjùNa!òëôêÅiCd—4kÁSy_|Ê“7ÄoÞpB¨ˆçSè&kW:¨µ7%ëž)ò—=Ôõâ®&üGÜÉ d7èZf†N/Ų([eÇ ~ã+‚m@S8uÛWBBœXÀýÒÁ ðìð,[Ò:À8Rå¤<ß'8ÙÊ3ø­Š#c<Ü!S!å}F­'ÁOÂ=ôíùƒp S~Ëó(ºj€Ä0r²0¦v"¢±ª#ŸR–6Ì¢¤Ê¦®m^”É%Šð „µ¾&ä#é¼j3œXe¼TI=¡Ë°^&„0ú%½éÝ•h¦lw¾½_$$Ù×î­Bía*YXFƒšûú¸=_vŠš4:¿¸Õ>´cØFé1=UoÁò¥#KѨlɼm c!ïX߬ZĨÓ¯¿ ÌÐuÕªƒ£ƹa¾{,—þš¸ñå‚zÌ2Ó `» ÅjÜÄ‚ÝÒRž –<•[Ô~“r8þRk ƒ =áC0ëišŽ°GÁù ºE¨nýQôœK€àãJ>k>³kµç|& 9]u>Ï™Ôr‰÷ºÆ¼|vTÚ‹–ÞÐñŠhxVÁÅHuuÁ¢Y"šæª ï…C¢ÔH¼ì9iÛ'2¯›¹“‘ò‰ÊÕxQÆzÆ2«ZXt)fŽoS I$-LêÈ,H®¢)ìúlôÊ=‡ºw¨õZm|[¦‡m ¹Á|ï_†PY›•¯?šë*Yã ƒ€ñá 7D”eV»hXÞUßöø—=Víìj§7ýµs_ µÙ»¸Â.)ìƒÂ?õÙ¤ÔFÎÎÄWÞ‹rüô¨$s®?§€½~žü·qKg¾€*Ù´µá|7Q‹öÂL«–ƒühíçCñiž †n_Ó¦s×–áKòÕN¬'Éý°QÞ£'àSH£/ÀwLCºR¤°¼C݆0– ä9Ç>žW3>^SÔ@OÍ\Þè‡:¾1ša”‹]‰Ò~[‹µÔ-×o¢x˜E³Uj1 V\Þ¹µXm“ÇFÈeÆÝ¡fl§ì®? âÕQ?ŠŠôx–0ᆖ£ø –¤á ÔÃx³N¦ú5H’6—Ôp+œ  ©š”¹tSÂ@ í5Õ ²ä–È9Ê“ðÀª€Ô" ª=xgÍT¼T< �¾ÚÝ~3‹á(qšT=‚ºé0ìç»úÄ!ëÂÂAd‰Ç5¡¸lA  ŒVÐ0O¸¨bí€õàò“ÆŒ Ó#Z@'顎0HˆKÈVïÇä·Tb+ä³Y4øˆ§ÐÔw"_ï RìdºS;ûFp±ŒÍ™%{ˆF¡4ú  ”´uD%zÓ¯n4ɇHÕDÞácE$xã|[vø‹¼n‡«Ÿ>—ðyp:0™²éÒÂÓèžd‰œÙµ´i=s.õ¦ãhNMä’å= Þ|®‰þØ/Fa†êÑ­¼ð“˜ÊÇ"ˆ®øFõ¡·Ýàä‡ ]¾1ñ¥ê—>—-ôÄ$#¶ÙÉ"-YbÃï0ГMàñ#Û+ç÷—?b:¹S€òFäìlÄzE§¼äÖðËõ)L¯tüÝ;oÅ7{î"ñ"4'×$Bf0ÔãÍZz:…’"Ö{(KDèåKºŽÄ•¦ÀÅ}+Çd“—k>P²ÈOp„.ÊwW%JxÁÓ3Áɱh\zäI¤:¶ñ:žžŠ¼(AçAØRðzæ`+éÄý‘Ô‰³ƒ:L-0Á`Í–Î1±de&oz!fE©3‘ ªè-ì”àVt_9¾§º§0ÛG0P["´æþ6ô=…ô&¸Ÿœ Àˆ9Ù(ÌÕv)“!zÂ�©¡êL¡Ôt†DÖÎ&ì¡X|O¶Šfw\d [F`X?ºša„+›=¥Á¢xUpù4kW!RÇš:F³ŠÜ¶(�^ã†JͬI$£ »¼Ø·s{˜of21èZ1<+­AÇ!^Ï•ÏsËáÆ8ÃÒmNíwRD çU çB /äXo6 ?Ñp%9Q=ÈÖB®q›¢é—2«„ú(3kz¬Ûô¼î7Éû²6%=maÇ^THòzD ÁhÄP‡aÕ¾çÊUö䌄a|n4.2ñµ#««æ£~{Û2äìDáµ };Vn$«Ü&;OƧPŒÌ5œ£DóPÞ"€6ª“é„ffàV_k«Œ<§žÃÖ–Ä*Í×pϲSA6ÖXb?§â/à¼hüú&F½ï­û Ñ ¢ä )+å»ÇzemQ.û—@˜]Ï‘îi¬�\R`aå“7 •²=~3t'à]æ€{«Ù`ÄÓúºNøµÛœ€Bb›ë†9sÕd ù¼Kñ€©Î™Ø™£Y€ÔwåWÔ³jïT[¸F„מ•Ü38yN¯ðI=Ë{/˜ÁÓå©j�¾8dkÝÆð§XO9²¨šL>Mb±ª‹‹¾õšÃP™§vŽ/¢f:–!t :PrðŒFˆ^Hë`ëQ…ÍnVãd~C¤ýÊ8³…‘7âéNî"(¶ô¿~9Äa4¯iŽ- #E¸'zúe>@ÍÔ]K^±î. O.ØfÄ{8ˆÊòÜA•¶ÞBø¹Ÿq«‰j$wû½^z§+Ëp‘¯íšŠ#ž9x‘0̳Iº$rµµ–«Ì“è¬GƼTSìù‚v­Aå)×%z»Œí#_Éž8àÕTaj/{œoŸ…xøØ²ß¥«k7‡¹?z!ô"EV4½yôeã•çvRCDMw«ôЋ®•°>1—›Ùw\b/Uµip_+â\pG Æô>Dè÷65ìCÉ:°f˜`V¶T-ÞKŽE ‰­mC*]ú¼æö2ÉL¯ xÐÂõc ¢d2k윕p×s�=�ãx¶.” L%‰ˆÝœ=*÷ŠÄA 憱¡c÷uÊuϘñ|¸{• ü”µflfsσùè}u}ýÖCî$¡–˜}éÜäR@—t]6; ÿœ‚Ú�(i{çiaäCV>×Ò£ ê4½}AŽ ¨k’$Mô´ ·_•TÂ�¤`ˆ›Ç¬š/ŽX³ƒžšÐ*Â#+nç–u”sSY-z¦]¸)ûP° ×<®+Qw@hË;:ð(£ èábW¶ÎffÄTXì7ViÊ×4$…‚¬¦V:½‰é¹åehŒ°[Yø¢€ñªO…Óðiн‡Z/m¥ú<(º‘UîfEæŒ9Ú@} Ǹ¡½€õ’0,ÙŽ{PÖæÐ’B£{ß\H¿GµÚU(vé«4�oˆß3ŒÔ–˜‡çOzvU×—Ù¯¢î¥‹ÔNt+ðœáKõ�¢w.>ËŒÏú& ƒña9‹D†çÍ/…o,qp9LýtØ—I7•¨&;±S´^0ä“#w¦ jD>’3�#؆Ì}p «—/%_)¸Ù335S*"˜|þø�$¿}›‰ÑoxIq 5#Pdñ˜#�–h"’i?AK@1'¦÷Æß<z–À&|­ù^£ÉÅú[µ(Ø6Qž`³SÞds ¦î„JåôflÛà“žX…&ŠeSi¯ŽxÀžŽ[<‘vxxËYÝØ-%}0A”o†t4«•À…8ò,ÈÍ ãhP€Cî^ñz&0r‹_cbXlE<¿¾Ö¬—V‘ÖÞÁƒÔNøeÃçô]Ý ¡vÎ_ÎA:;x†¡?Í`ÐÚ|á‘Mý—BK”m·1…lES#®£-þ,eæÍÑcÝTœl“Wð Éx)÷M=ÍÛ-*Ä_Æ9AŠø ÌDeX(<2§Ô·.<!4ŒÓáª*9Ny (<„¬·„Ä︩[z¼žf[?izò@V Å¥Þ3g§¤yxª<¡/'½Œ¢TœÈ”Úƒ h-C‡7°ÃH^t ‹´¥ÅŠhÚB¹u£à Ð6†Y&ßëŒLÒx”» #.RÕ.o2Õ@/Ïj: ñªÑ—„Ì6ª¢.£MmC(Õ›/^ó)-¨®bBάº Âvt ¨ÓAÔÖ®µ94N[±%¢àÏ 8ØÄê‘p6§§^(ñJßK3xAEsqƒw{€Ù‘7mÌL [zˆ‹›ÕdP<©G£Ot-l”•<õ(P¸:çønt ¶Ë�ÝWèÕ‹û¤=òrï )§À¦FªÌÇ®EXÍQ*ãX{ù¤sBбºŸ]6B=îW©C2oÑË«Ë^c!�§Ò;ŸiO°Âb9á×ék õ\y°ùˆcG®@˜¦úÅ-¤Óø#Õ‰FâUœ)_Èë0è[q‹ÉLC bð³Œ$r miËVä®ðn2<Ù‹Ç–ŒöcUÔ1¥LÖ¼í,r¦‡'uÖfçΞ±:h.¼ãÐNlgöO…üK!ç+Á´9mÉî’¢ó#Ÿ„(z4Là®Mm÷ó'Eñ—C׳9N÷¢çz/¢±²J3Ò—8[‚•µ$÷P5‰pÞ˜7/ã;sàK4ðŠc�¸q…}`p´X»ûä eŽŠ¤‘\7?âç$Õ0½ïuª’N›nŒ‘˜,éÌ" \f ”àË]zÙQmÀ/Q({¡Š‡ª´æéÆk(%ËÎhÍÒvÙ1è5%¦h?R2p„GÎ iAøüÖE}¯èEÔó|"è^)ñ˜W“ÊÞHg 1ˆ*‡3NNØ<™“qÁ­¼ëƒW(oSÉ +çŠÜå Î\çñ‰ ÜÚ󤎻 Aòf^VÉ¥µpŸ®™† qªƒÙ.ÏS{×¢­tmg}nø;á¬vj®÷^ælžˆÜ™J£¾£ðÍ+YÔ݉ÛǼëÃÏý¦‰žàéóÇ€Vòbßò»\RÆz*š–o€üù´ �·,‡¦¯‹˜-í%åúN‰cIÕx¬'«ßB>0yPa!“¯z[g¶zcëá£=ôަôЧÉÛ /#ô.*¥WˆÂµÔ<e;"^ö½‡¡ ÞNÓ*«ž;ô<㡦½5ì“Tëe†ŠWSÎR/äÅvO/cµÑÛŽDÞå§Sh¨}#+0×^‹ëšaÛ»1îKU”/ïØ®FGÕd÷ <HË1ë!§_  ÒP¶Ñk~¤ ‹z5•T¸ÈU»sZ_‰~9G×m0 £åÖc†Þ¸©]„ˆ~M#³qa+Sšð§D‘<úÆ©u/¥ð. Haû@[^ö+c²RnÆY¼„W F.Fœvu+÷P ­âÆÙ¬µ›¦õÐ T=§i_cGM››PÌài`xä3£"a‚¼™ål<K?ÐÛ›uxbÁãuŠ£Î.…[mÅîDå5}‘y&eý^Ë<aËÇ­ŽÈëéÁ£âËG¶¯ñÙbQ<Š×€&¹Å‘õP™€ØÔüéÞ2Îô1±xK =ÏY°”°Óä)˧®ƒþŒ-¦ghïÌ9÷’ƒ$ïà¥t¾E÷SÄlâ ê&Ïv@£cІ¬JçPåÊ¥çL,| cÇ8\MÚVo±mÚH%æ4 BÜjêÁ]¿ºÕx·o‚Áyâ¡+WdÚ–ÐHךÂʾäàÐ$zÑц7ÔèÌx&^¾ª\ žƒÆE°ÙLœÉÞäøŽ+öóV\r÷³Ê·˜MÏ’ ^õ(Fím’Ĺ‘T”°â…%y€ç“1¯QE•öNy´-ÞÊ“îûbž‰»*Æ{ êA£?$M"mš­TH‘-ã<,N%y޶8éŤïUØYP<åÁµæ€”¤ªò~ŒDb¨ •ù<™­¥×“ š˜¢‚o«Ûð’ò°M±mÓ–x?|VÖgSd:˜e@ր䤓îâÈò¶ öK"å/‰fý°Þer0ì°èëW¾NòÐ|Ý–æL–ïèhvFjõ/‹ºTvfb'® cáÍÔ. lÉA“"äÆy´@²¾|ðúõÖ(?–{qØk \#y‡Z(#³c±†Ö ¶»QV‡ÎXh‰¤ZrAG4ZÊ+¯Ÿ‘µÀM0zcO èÁ ÜÞËÚ±âî‡òxÝeg�®ð¡*Ú(¿WÄ¢‹¢Rk´ÂþvZW6 Ø ‹<P`^½2¸»Gdøpa.‘’ˆ½Ay®ýÐ5+]ªtÞÔÞƒØ9¬2—œ©Ek]5 J®E¢H˲ßϺtƒf ®±KÔO6K’¡�AÜfkÆx&©yt<ù0EÐiÝ<úž<@e™¥iñÛÎÉÈXd’É:<€MÀ× {o”ßÝ<„@åç­TZZ-7o´³ø©Fb+lÏ §èGæ¿ÂWb”gGƒj³ÂJÉ<bª7ù2LÍùš¡4ùàzÖ˜ˆå‰Ê O`¸X–f§½º˜‡0WÀSWÄ|}ï„AÑZ5«„y)r«©+…gf¼ ޽+rl°¡ìIMLÅØœo®B>çéŠPÆ÷P«;œ°‚÷ª,pXåÜ­÷Ax­°äs%‹vá /Öq ^¾!Ú£÷Š‹Vâ]N ¼ƒ¾–Í1S#r/Üã–I³AÒÑ)ÛÌѤ:¹F_QÊ[QÃé.…ó™=T&µ,{”/PDïË"£/‹”…·_ð@µ‰ °´…·—[,¨È�;¦ M\‰O¼Üi5-É?'#Ë·Ôg £fYLHRmþˆÓ—ÉU—ÙÁí‚îÈ9¦‹¶ûÝ#ˆy� þ&´²»JŸr3šLá…SF¤ šq^>ËÉ6Æœè3ª[C““ÀE'Ñ IèÚMÐ’Î^ ¶€WÈì³Cï^ZŽâEK/œ"=Uµ ¥®>{ÒwŽ/¥L�äÊf Œmc/‡GØ»Ò/=á¸$ÎØ)Àdšƒùi÷®ÙÛí3 •HäÊó¸Ùe™¾å¾Âa‰]‹™uktËÁ>PBkÆ~rˆ.«¯”d¬ZË3KÄ€P¤ÉVyqF©u¬{‰j<ŒpMs/^²ƒ yp¹‹h–Å»}ƒ¼¦¦¤Œ/{ƒ’-ÝâÙµvpiBB`³J¾=âm‘ìöZv%gŸ¶Ê^Îw®Ð6¬ ®ÞGåÛw›‘=T÷ع²w¯Š‡xÌjÖDûL‘«éxàÙ¢¿çg2¹Ü FµÎï$FÁIÛè(>Evw+ŽkÜ*ÄuÓË®4†qxÓfsQ–³-œ:y9аb`áh÷¨_d½|´¢¢sʺ"X9¸\T™¯­Ò\¬“žÛ j¬+À!—Ê‘)$ÂëÍ¥å\ž‡@¥P»j),º°Ô°’´MùrKÞ`­Vxžáƒ×zìrÈoXjLI5gJr_7/Öž¼G¦Vã%¦!Ï}iäð¥QÑômÜa,½^›¤d›·²m­ˆ”žD¹j’îúÌy¥®rxÿò”h;«g"½©šà*êE/¦¦?)AÇGfÁS´X `pã‘>Ä”™éWúF–òX{€»È+tçœ9óY[Ÿîí‹§/sEWWžõùŠ7ÁHžX&¨[˜¯o²ÆÓÙM½Ç®Y‹\Šä†p&yNÙ@1à8³;ý2Žü¹¬2Ãe ‘WÌ0á>@ç1‚á@¤k¦@•ÌÒÉ)è+½p]DW|>“žR¬¢Jc¯¯«½Üí Äm’, ¨Q®5àfŸLˆÉ¶Nßቬ6M'o¯\qêá¶Õ€G#Ç!>Í @‚0Œ{W·ÎD>²]ç×#h}v¥FàO od,M±ËK…xVÒ…Õf— ˆz¯Ö‹Ùb¡âkH·~ÔQÑQ^'W#&òðz`Ë .éX©$Óì½Úk÷A´TOÒŒ£Â o ¸mç ebÒ¯‘Þ/·ìÆH¼Ç§Pר›èÊ-„mÔ¨o ´Rü½ñ½¶Ìœ•j÷d•\(g²žûÃLài&¶i[ì”…¢ÉØnyâé›CG=Wò|à²W!S‘#‹2_s&Õ>}*²£ÝÍ6ôº3a7~R.µdq¶Kµá`çYbm½6ç+ôÈ5ÑÝÀ÷…e‚¼‡ìꄵ%,ð$ñIt1”=7È-9´|”hûxÊõv_ å˸ùôÈ¿<b;Ѱlï‡ ÑàêNöØRñå%`l}¯ÏÕURLÈŸìPý)Ò ©ƒïPv°ø9�õ¡Q¨¶O°úNõ¹Ý<”{¸iŽmO,f¢VóÀÙèJ3@ —Úà “NÀÙY~0ž,‘ám8Ñ‹Z}ý×%öú¢§A ì+ )G¸}d¯bËf}¢ M.¬]˜šcâãìvzg¥D½ìŠÊOײַ³< ˜±z²ÊÞÈÙF²Åj³t0×;Ôå‘­áÞ‰æk40ÛÍŽÆ^‹¶^™YS9UÎEGÉѼ �èÛ¥8ÔC2îŒ(6QºcÜmxz%·pä3CÅ›+Ki8w`7î¯{„hgD(0¥È¸ø½·¥¤#RЫ¸?ƒhdóEÒSyò,з²uËjß`ô Ü£ë¤~t“2[ê›wrVªÛ|SMçéÉõ)…€9í¬EM=Ó Ã\V@gl‡@ ‘÷Hu9›5í<# é*®&¤=£D? ¥ÝU{¾‡©¥úê=ízÄ;Þ/ï–î… ×öȨ°¡´Ë½•žš�ŠÆÑ—ÞzaŽD–î¬ó› ¡#îž*ñ$IPMa†¦wœÆ0N@¬ƒñš(¡° ,øÊAF–«Ï‚<8BÑ~>uà„VúÊHË…ÈR.ÇëUÖ´€º�úlæ ÞÄ<owZÇU±[‘ÐR]3[5ºcÔ|(2¼´µ›-Å‘žû\0 _å—H¡_" RêPЪmݲkÝ©BÈKv¾ãæ£í¤‚<Øé~/Z‹vy…ÿ4ÉõͰ<¦Å<ÆS§Æç»>y¡¼0ìÕ3†ÞÚhŠˆa (6}°ÓnÁt< ©ŽÊ@ï?Y’\¯Ö‘»´”kºÛ—N­ð^æ{šÛâ—²0|\ µ| Y^€½§%«O6¨­áˆº¶€£ŠMqÍõfa-ó™Ÿ6Õ{b:+Ön.‹eQë᳂J­jIà‡ÏÄŠ´ë±<§ ’Uòƒ|ÕSôxxí2·ÆÎŽ78©y¦&ØòåЪž ˪¶G&<«ÍSKšÑС‡ó%J–Ðö81‰‹rÔP¨#ñê\ênöTè)Eå™ê@”>Ãä¶—LÙÎKµC¾ªþì%`ÒúÎ)\´¿JFÙ:÷GJfˆ”] Þ–}%ùÔ}\:|µÝì„ÙK{®1qŽY�¼wÍ ”ží5ÙÍ£E¥ð'¥ªO•-s–CÑH^;ŒOÓ=¬*ëj¶p[xÙÀDº² ¸>.^#¿#ž™zü$°ñV¤v~Ø‚‘o‰‰ŸRÙZ�îK�ÉŠ ˜@—KúÖeÝŠÜ¡7::çÙÉôà©\1;Äëß• Vª™g6ÊA²G¼¡>É+’䱚Ô}*JLbiÂï•ð”ð»ë}ƒñÄô‰µÉ@,¬ ú„ Ý&ž˜�<¸4ò—Ž¥ë8á…ó->LzÀ_&…½>*ž>¨K7*F î©âE5…Dgü ‰)†mc,%r¼ñã«?'%”*˜Õ$·góTž¼Ú)!£T;®ï1¦•…w†%‹p[¢Õ»{¸Gµ,¢g-|É~ 0EldH;¤~OŠ,Ë#•XÌß´ÕF â.'<÷´½Hz¼ˆŠ§óÚÔžOq-³Ã&¬We829#ôã.áP?›*ïÙ÷ž>´Òq|é˹u=.2¤¸í‘Â-Í3tê=2 VAÀ*|€³’ŽâGKU×Eàb)]¦QïèQ¢°¦ÊàÛ»Ú¹×ê&S¯0@Ö^r[Õó—ZNÒÄpÀ–TzZÁ\¯ŸÒ M'ëÐë 4RËžH_ÓÕ®¬¸ÛªH,´Äpan¯“ð]Üj­êÖ¼Sà³Ië w“ƒaq$8p€šë­¹[ÊZsFí¨Òwo¬Ö½z7…S„˜‹ÝdšÚžŽGLd÷5• éx¶”rUÚG‡ñ*¾c,éÅR· œÚí-ÕÜJïu‹¨ÇÎ$2Â"‘S€ †0~é-‰¾wlûÞ¯FÔÏuœµ&EW&Ö:Ø|FôµÀ8ô*‚l•R«Š.uÏÃÙµæç$ZD&ðt¶è94øiãêó³ÍE:Y—g,¨‡aÒ 5yë<§ãܽ¨­HÃt>Ü5¦\tÖÛƒDBæÍwž/÷ñæ6¼S«Œ0 z4�=âø êÕ=Yd3b¥/•¾Tr¨Ýê¡}ç,8Ì¡ØasU­§‰7 ÷UdrUCÚY샌Ǭ6ɹ½‚‘xÏŠÚ õ”±ÁôÌm=‹]÷²¶´}Ëפ }wôÆ|éV½Ž\vͳÂÉͱg*ÏÐ,4ÏâT_�\KE˜è ßé}-*L -7¤ži˜ú¢Ÿì“áÙ­+ŸN4u-ñÔ“‹iñ¼Ø’UÞ¬c ÝäÁSa+;¢‘¤w^šÍ¾ÖjeÏ(ö‰÷Ùº ¢¬×ëôR½Bª_ ¿JzºŒ/_7ÕCÇ9ž§lLøΑݟ҃Êâ#*ÊwͬýB¬ë¹Iƒ6ÀÃu°&®µÍ( !öÃŒhf£>FK‡×?ìÎÝ¡až² ¡êÙ>¾ðg%­-yò­¾8IBj&CÊå<.€½ÕŽÅmÉN°kz°ºæSÒUŽ& w;@˜É‚%_ËcÐÝG«¹·¼ù–Ý+ÁXdÂ;¸Ì×dé­ËLÌp-ú½ÁlÍZ âöµrÂØ÷+oq™—6ê-õËd¨0QÍyU(¤•çN0¶¾,bçø|'‹éuC;ÀTn{;•¢ 徯 ˜ëÐ,¸y2AYþ’¡­‚D»óù{Õx§eK£Ɯˆ¦ÍŽË;³àDˆœöšâ¶§ÈpMràùî@ÛH¹h£©7WG‘8â¡6ƒ7í;ª›¾ö•|¥&ŒžÕìÓs”¯ù\-+rɃøzÈPn„‰×ü5¹Dðå’ee"mSÚcSãefdÈ…+•ðÅVíñÑÍ ’K•{ |)˜µ|çý%“²£šDÆÕÕÍÁA¿@¤ÑW Z›'`0ÏÐCÅok’ÅqòZƒ}/CžòÞ<zôöV(¸Æ´ÉõÑÍì¤ XlT§4îmÈ™VK<ZÑÊã4£;@9`JTG…gö|a_PÇNö#$õ6¶qy/àfü°Š¢uŽ5žÂšl(Ç›á[©¢Gç#ÊTnù–ÑuæºTù¥ÖƒÎY¢¾'¦ÀDfýHP¨]íݻчњåÍâèûˆfž²M¢¿@èãêy¬Üs äo-PäÕÁ+ ¿ÕcW yç*­^½jÔ<%¯qBãÜjú!œ•ùÄxβžðž¡ƒ¿ X‰XÆî}ŒµWûPÖª‡ÉçžäIôðA;H”Œ äÇD@Y�4¾~‹t˜œ/üMÉA*ZäÅ^�È“}„¬íØ&�ûô¥¦Úr<»æxE^�êD^ϧŸÏ.j^$"™ «sÝpB´‘ZŽP2[×(š'<ŠáIdU1áèéÛ¾hyÂüòzüÔL8î)ÅK+«ò;¤2 ¾3õËÓ³z½·a†rk0Þ묞[Nª]GH. €¹ø®ý(úü9¨ <NÿÅl}^ŽØ£X½ J°XÉ<³Üó¤ NMßgK€ ^•|§W)#<Ü<ñ ³GeœÁ=+·)‰ö¦K÷S&ÿ’©Ýg7‚L-Êó˜(«+ûÈ_ðÝÃÅÎos ‡8•V£W§V©MeÙTË3•µ‘ÕNïTRÙ!”TJØ èqcž&R¸À RȦX·ÜmÑT=òuibQË9"b@ÄÀ–¦7Ì?u‘_P×U+¸øFªÕÍVã#™ Å=KǬ€^Æ Kétάº Œê)'ƒu°XŠä&Z|xÀº’nÉG=WÅ“—ûž5Þ”ÔLÌÖ#4à—ÑG]e üœÉÒµûLL\´äIÑås££’y,zOØŠÍbÅ«Üߺ€¸¤].$[©ßU®p¡Ñó±®wIÏ8˜„ž8Ë!»„Fbž,¢‘Éå‰ÙdÎóÍg@%“³oÈŠ“–RõÜ»'E}d8gRÆ+m'ºf;Ýcñ"ÅF"oŸ±1Ž_ÇÜ£zU ç—µ‰›BÅoðÖR ìÕ©wj&IâLÈ8$ƒbNº@ˆººÖTfG22½Ê &„í‚ðQgÖˆËç¾»¦ëSé€dz:”i¡*÷:èe)+Á$.Z2³\”Õ#Í')›rÛßPð…];ëa°”æÌ–* ßÑQ:ö%Æi±´à€Õ:¡ÞZã‚PpÑ6mÅCî‰Iv¨-¿ÛñæGm0Ï-J,¡+ ´Ù†´Úm*gæu…ÒËø:’XwYûk·pâ¾îæz¹Ý‚ñHﲞ¼}ÖUwµÅœ!µ…“Câüj»¿lzúeàò»}×Û,°…@ oµdDÂCf&ÀøŸ¯ÂsB ƒöǽº9MU®uú—NôÌÛt]-Ø6¸áùsÅUX•`ÀB4«iÄ÷®æ*Ÿ‹OV2¶“ìø1ž·‡kA²IÝÈß´µ?Q¨G-NK%­¯ÇÅ„7&4ÃH)‡—»ÝȆv€U‹òI,-¤ßz$3g>ajª4Xq~o;]-ùVyä”PW#îê-×e­½½°G~rSÒ#@‰è�°  óPšº†»lë2ÑI»e» h©9†‘ø<0½;wœXu”ÉuĵÆ@Z&·3êä°¦i¶’²Â2¯½÷¸Pž¨¦k¶Ÿvƒ©<€ ƒBÊ9_˜ËîÔ”€ {;"3JœÄÊq%ŠPK¹ ¡6¢,]Ae‡÷@vr!½Dr|›R˜I••VóU†%�l‘j�€mÚ ãÕ;u.#‹‘… Gw«3‡ea»Í¯Â³:a-€˜ià×–‹ÜÓßùòɯZ~bIs!8J5}soÈžqÕ¼â¬!æ\f^zán„+õšOž¦ÃU"Ϛƈ›t¼˜ ~EJØjʯ&<^í¼~òòä±X©¸ÒhïHÀË*Æ©)®RÛ£|(çuCì©¡¬kÏéI‡ïk\D+tæ‚çOÐ-µ(„7WÐÂf ¸m¸Ý“Ä÷ iðFÑ'6¤9÷Ù&œðÞ-¡¶a ׈F}éÄü¥Ó{ôžA²—Ò.?a=´æ=ªó±íÁḀÊRàòM«+5„Â0•dY¾"ùïéIµ…äu¡6[•¾µ)ÓN29ä‡1ÙÐài‹öTõypÜÂ- 1û„ql#‚¬W±?"ÓË à‹dq9ØÌ™xX2²3~ô+烛DcP>ë‰Wðøq¥¯ôõ-FÉøq ƒd :-]$@´ú[x²†*-«å(éÍ€È+Øu}õ¦À­!´„oâžFd.sÀYhÝÍ!˜h¾§S©¤Ô5)pÂnbº0•âží<(·ô“ÆMLÊ}Î5rµ‘NkÇgZ xÑ¢ß`° P®é5"ˆÉ+0|àŠëªëQ4ÍáíVI¨hò¼…©Ç—šB/µª‹”æµ2n»_Ü¢!¤ LiÜ9Û¸�‚-ïj3¯d†k‡Ï—Q-¾¼Ä÷ðŽSOx³ÇîÅuÑããá.ï°`Ã$ž7ïì½Móº~p~õ2ÃŽŽrž®gÆØú{.B[Ø)HWD:F¤ìŠòð=WŽ~ØËï¯.pÄ΢æÉuKwH¼4¬ÝQ}Æiq*« åMøð …_TÜ“Q7•¬EGêDŽbd5/X:[á­â:U/!sbLã‘0Z, „ÖÄužYM E #úÈöÐ…½Ù¶BÌRÔµ‡!bB7þØ ½oŠútKE°™£S)Ugl¶’Ùæ¼)6”Ÿ–úãC¥±p›8‘BúòIèË'õ a¸PnoãšjÈqgAèzž7ÌÏó^’‰ÞÛÛÖzTâ[ýüšR+ðIhúßÛ:ò‚H@GyöœuK žKq=xwgœ¦Ùhì”c±PEêꆅ:‡Âi.GùRÇŒ;Ü›.Id¦IµË÷n–Ȥæ=…Æ  YtÙÉN( ÑÊq?}ÑRŽÚóLÈqð–âz͓弅ž¬hëÞ$s»4N#7Ÿyn.* zìóX8ðL—e5øå;ÊÜRMtI€ÂZO¯¶Œ|¬/è)[.“V…·É²xèð”g jðÐí»÷æ 6c0ÝxÕ§‡wI$Né¥ÞH#›¨<?#iV¯y ¥a/M‚Úû�籡ñú„ðŠ…ÌShžÅs¹e)ÃIwV‰¯ì +5îŽÆO¢!'äP|»•»Â™Î7䡜v¡5öéV*Ÿ:ÛÖ0MaÞu5¬•ìú´Ì ²W S„ÛRpÞÑN½]…öL.¯«aâ÷ˆßˆW,@÷옑à™Gæ«£;d›J.àp„ÈËÞKvM[ƒŒ|úš<Ž´ƒí½}›CÕià„, tcJªÒïŒLaú_'¯Ã 0²#3—!‹½çØfýÞ‚ÍKsËn0º×O*ÄÞõôêq«u•§èƒg^y¨Û§çûP3,{Ž«—Z¥«ÃÄùz£Vi=¢óU2dxŠåõ}T70,8v)LèeĈ ¥ð%ÔI(Î ÞÝMò]ÝQhT©ÛÉò^¨g™-ŸV಩ç¬F 'ÓW“²oCþ2êŠ@Ç!‡ò¼WÙæ]:+À90½Ìpf³ ³G׈º"qvÃïyå¥B<3ÇR·§ ¯,]Õ=i[ÁN3À§½òMÔ£Ušu¦PÌv¿vSæ˜ñ~ñ˜ÑÔÝGó$joµ÷©0¾”{bJ”j°DkÐß¿P58,ˆÎâ€÷,^ð *ÀÛgå� ´SÎÄAäž´ÅZÙ—ïX͆ŠXARœëõ>4¾ÌåÙšŽèH“M;^3XÚCçsÀåAÄ])Ä(Šgz‡QR y.^:m{`>‹ÔM\¸Ð¤KhºFÓL\ë§Yh•l¹s4Šò‚ØWèi¦øX¹2 ÒÊ$ÒèEjP²÷jì•¡>GÚºkî_QÄ]zÝâÄ-¹œU)“Ë úB…ý•*?+\“§q§Y³®‹c÷�tšöåÙvª8q²&û•{{v‚vµÌ3—©—e^…hü„Ûò.]À•™çmÉóÎBs ·¬m++›t»˜apŒóŒÓÞ¥› „¤Säú‚? ›Vœ¬`²ipIÍæ•>ÍAdÝfÙµê‹Styâ¤.ò¢ƒP�÷½çM©sVr$U¿›Q;B{¨ÜÓ5>y€Ü¢ÓŸR·v’Ÿ<ÇQ0/ÕÍŒI¢《ìÒ†or‚;´|°Ðo:W4ùJ(âÓ¨ïïã ŠI[Ú»ãîØK †Fãc/1W߈‘âs.‡Þ\³탓„M”Î�ÛÅ&ÛÊ¿”Ú2~¹¹H÷É{Á¶¤½Wëñ¤×za$l°I„é®Í-\@2И»w§\hoŒ·-VòZì0Ù½ÉPf¯Ýcl²Î‡®`(ºñ )㘂"ý| ;_•Dö4Û£ðaÓÙ¬+Æ[±Ò”Ãû�¶k–>— šÛ ;é P!uxAùÞib<K³¹¨Ø#U~(¦¥ä–^v”¨­¶ãÀD’ÅŠÊá£Ógü@¥¡ uË*Ï™„„+ÛpJùd,â4üàæl£ƒ?±žP§9ƒ¦Œ:õqX ?íçMws|ûÜ9µüଠÖs⻚'b-JWh2x?Q&œßbJ)­Æí‹3kÌwórÊÕhÐ oÔ4ZØLæÂ By‘‹ê‘>¥ jhîégy÷`ú €e+áÏ8çãzƒZn·ç@nAA½ª!4¦ÊÆ¢Ú¸¡sjt¯ß“: "ÐZ* ¤†™[ÕJUö-Ýt%.™ªÙ6¨4~<- Ü–mÓŒaçÍ~ùSÖ×îû 35ð.=ó!S¬§liúŒé=€nˆ@¨HÞ Ž ô;¿ÌWŠÏs�×úµ‡*lè«"&Rñ˜“7‚ŽlÑ#’"…E¶ƒ—afÙwæB$H‘…´MlÍ>ÅUMΦ^Ó(2fF£®¬4þÛÁ„ß—R¦_J¡ñK3 b2æCdG=¯ß»(éž3A^çᔋ«±Õç<0l¤O¹¢.$‹'ªþrJá½,éÇ#”]¥›«©}%¯_¤AêÖ†d'M$e_{xÂd›…ëê=`H÷àŒÅÔÄD2rÞ3ÞH†7t²¯…}0½¦l†xnàcn ‹Hìôd(óEßÛqOôó¤k²`4žn¼òV×z¦Œm=Ó¢¢þí…ÐPã4鎜”ƒ6’!r xPa%l5Aîj¶¿4o*nÞfì㉷êzB®¢“:.µ5‹ÐÌl�Bæú@BžÅ‰µP4ï—/#@V< Љî]wÄ˦Ã&)=0†«<:gƒŒp)3W1GÚ£p.rÌd§[•IÖsÀÌwd^M”"Õ)âE6´«ë¾ÁŽQj¯Œ,:ä`sÙÞ)5ÄD‚Ânœ’¾@VL|câå“NÎç÷DH¢¨Þ£Ü@´¡|²°ÕÞÉ ¼nÝu AuuÅÐ8i%é®cñŠ5¯6¸ÍS;z£“=jüÑŒ±öbt¾ì8Q1ºÔÀ.í\F;÷ªV&Aôšjèˆ 3  h4ß~ás‘á¹/ß¹æb:å´„P¡’F³:a£(ár±ÝÓ�¾³VGnHðR`a€Z£m\es·%ËcÝäèØæ;%\a~u LÑsøÀ:^¾ÄöË¥½RPªxÈ z™ëçÌŽù4J™ooó¶^½¾|Hâ€6SÏ^‹¤rÃÅß—SÎ_N_Vâ 7OÉ¡éeÝ‹ñž’å³ð>¯J?ÜG<Öv(Fá›Õ<½6½‚Jqñ§T¾ˆ “€ñÞ¶Á– dÓÁÛ=TÂ'DGë¾içsyA™µ&›0¨1Q8ø–‚ßó£²(òbO.{Þw£7<62žmÅxŸóÔÂGþ£3æ9®ê0:ê*[v©ÞCJF·†Q¹ÉÔ%É$vD jªŠöWËFÆë 8œd£Y^s"ª‡õ¦&mø°JªæmÞ0»æ­Z©¨–÷ö0[EÓÆ£õJ§w"9çFÕX;Ó™iÝÙ3’À®·;æÒNI¦l°(ùÞH=ϺîÞúH«–<BÎg–©!Ð)Bù% 3Ùú‡‰uW%¹6]™»”2qðÅ{%ÎþJXîPOmÛWryâ]; ó5™÷bؽ¤SÞ{â/aœ0•z ÚŸ_„)‹írÌëܹ(íƒ,£[›†Žc¼hÙ¤‘£ñÝ)êZÄVš§}Äž!B¤²Ïu†¹Âådë»íås xçS´xz hòžß®³ZC3ê+áQV>^·#À ŠØk4¯¶wU÷ÌI@™IÅõ½*¦”ZF­˜‡÷€pk*5^hs¡m.ê`"äs4|¹/Fr4‰ '=s®/[°U^ ÌqfÙY5vrtjøÎu‡é,En̳XPËŒz×/µ¦Æ¯õ5g¢^Ô¼ƒ Nyenv*#k–#jÜú)UЗTµ¡ÎµÁž½Žf§JA[¸v¬ÌDZi3²0ÆJ¯=sï)écíhl;ÅÜ‘¸°ù˪—pb×wU `Úî‚Pˬ稘Ë÷ìÄâÅ98÷ô¯ò´Ýs¸=/õ>26‡Ô”»‡…#ö‚i Œi=°Ày‰/˜qÈÎ.×5Ì×Y+†ýAN\nÛó«:×LŠPyMÛùŠÞÛ¤Á'0·yizåñËq’îÌõ½w¦`X¯ c%‰ÂNòÜ÷è]qdásWu-W~ίUjÜ©ƒxM¡bÌÇ@ʼh96Öct#Öƒ¥^Ud““2©à+ÀøÊŠ¿”¨\îÓæ|þäU€§å¹cÕ‚²òmÏKá"#M‘Û†[©29†7{Yáq&ÓÀHïDôEÄ Àc|Œ´¨£†¡‘–êà…!–ÆŽó¨ºkvÛ"¿]‰vîÑ|,½-Ë”_uçcŽ™—´`áæîˆ©€ùTq‰1Ý~¥hw‹¸g0í¯˜¡ƒØæ.‹BdZö¼rÙsÅzàdJñ’XÆÐ"ÝÔ«^Ѥå’#‰_y]ÜpZ€ò£Í}Ň³QöYìmA`»¿:›ÜÚ¦LÞì!³´e™†×írBóHû a݅âV0é>ϸG¯ŸÈ–uÏÚå%jŽëóŒFí}n±&¯^sðòy¡“àló³¦+4´5ÑP6#˜aNy÷F[8‹Þ\« ÐKÀz°škð¬A’;+ÐM«Tár׳ÜTÔ‡U ðe•-ÊPŦq§Â©¶Ïe=³ /+ÔÙÒÄJØ|m»Lç1Ï\×,ú@^›™Kf¬rÚ þ¥•xC±P5¾iÓuxVo |FÐ;•%d^”Ò`£\ô0Lðä�°FlÙ#kåh,±|ïxëEÚ©i¤nÁ9W_¸´f9.‡ÇÉNÊ:½~¸ÁǸbV�±Ø¯ ŽÙAÍF´Ù­Ùg„€¬&ö^D¾?9©ulK†WòäQ…™Ììi9zÝSËs­X“›n–-™gcuK‚v%•B$m”IAÙæORêø’XÖœ6ÕÀ‘Ùï¡ _àÎETãkEIµœe¾Ô÷´ˆÜ—¢•ã1¶&‡Ä (dÄi„c"Üv?XŠn3g”ç¨5D~c.®ÏäFuºÍw9S6¦¡0àÊSû¨¥íÞB KXŠDM¯U_–_É,´Í¹S§ÚÒ¯’ªˆ·ÝÓHª–(K÷×Q®Ù¾ ét U»±vƒät õF<¬&o\ùEA›0W¾{¹ä³×ov_Šk=r/çñ袂¼¥ìà’®áëª^ &ÌÂÕ…iyâÜháèÃâ’£*�y…¯­/ è½œ›i{Þd J_ŸS>°cnáW+ƈP“ÛÇÕ;€˜bê X<žžZ—Dó2£” <„Xw î|:•@&Ô§àL¯Sˆý“¼!^)樳Kc²¶³Œ’ÈÞü„”0ç,V¡K\’ ¼Ó€\Û,8>µò/­" £–Ÿá«s@Ù¸IÕ†£ñ×Ù¢¯Ì4+îù½å³=¢èb~ø*p¯¨¦Æ¶7^ …«`»þåÕÀ² ´P Þ)7”¹¼õ Ð1+µ®M¤GT28R]Þoë8ºunýŠÑCðaˆªb›ÑPÌqÖ³02ïX£Ò›xýBýêæapS Ù ´>ÄØ¦¬])UC$Ázó‚€:æ]![½œ7‰à$|ç³9“«±hý�«Ñg÷(£ÒoàI‚óH ]ÅòŠ^ê®ÙÃ÷¨:ßP hœÅËVWcv {!Ý‚lìxqÊüÞ(1 Ð&®iºƒ:<:½öˆÆÃ0ß>ÚzlkbâIAn'µÏ.Fy9¯,ªƒŽÎ2Þ9©Wç6ÙFDZ¥½"|ˆl· »ž¸lùÒÚ»ã­M=ãYt„ƒ1„G(Fšz£Ôµ4“ëÍ�ôLO\-¨¯Ö’P|«2ˆTtÇõQªÚ!¡±H9`¼íöªË2A¥Þ5|±·}î‘Ý{¥½ýÈOºr{W1Ò­‡® v]D¡;,žR#¶©JÖ*ä¤Ò$Ü=uªG­“†ÎH uÍÏžã‚=}](“;ï ÕÜ)õ¼ˆn¦HO’Nì6•ÜA´2 ´"é!£èc½ ñy‡ø0/JëP‰ºÄj¥C»h9ŸÆé¥S̽[JÞ}öøqK§º:5´—ùK(ºTÞ{N.‹ýRÑÄ=Û±Ò½éåƒ!–ÉéÁV7Ï!F·ÈÊó{1_^¡~yÕ~T¯Æd/¢skš(çÜ3$Ÿ0>#xKþªú‘º9¬¹úw?c¡Ó$Êt±×½uÄFù—X¸¹2'ÌÊv/\TÜ\Jª‘Ffîm½Ä[å‚k@ã›Ã™tAw o”3≈:Ñ[šŽT«Ìš#¢¦|Èñ´GLÌ_¹à °ZÎ9yXk«Ð[’”SªÌ©¥0Ú|$¨Y&¯óYŽ?Íà¾QB§²Qß…µÔvap†ÁÍ©—(>îkp"xëbF*ÙU©ÁvÄâô08ÀÑ*"%0Ì;ƒexàèqÄÌË´G¨eM¾;%í÷\Ð%F+£€§ÕnŠ+—Ç^¥0¬ª<­½¥»*™Ì ì-%ëc×xd-óšz- ÀBÖÂ$½õ¢Á*„TyŽe6=f.îä( ”"žU`Ø ¿ÎàºN‘W³"ÄÓÊ9¡wÅão3°×:Ýù5f‘XAvôŠ­uØuƒÞá«x&yÝ ßÙ8tÍÓe—QïädQVô—#´ ÷œzÆŸ:'._.ÒP=:ÌQ ;œ¥ŒY‡V®)ñ‹‡th[T”shöÎé*›_¡oJAwüê]CysŠ@úô9ZYH’¼§»è"Ïy)IÛeÝ@s±Õðh|)a“ RÄ»ž¤C9I;‹›e€­ó [Ê7HrÊýð5ÊôAO«>CÓ¿Ó†ÚÅõµr&^"[lï4ÑM]F—]¡ i³BÙöv¾ HVލ~ÐCöä6¼ð­ÜÜ—XÄ_bmÃE" ¶&%XŽÃ 2™€öê1#HÜ3Uf’·v³"ÚÍæn¨S%Œ£ßXÏ"œúˬô|6,™] Ö/i&,ù-Ñé!n&áä]ùö†-ÓˆÍt°ÄæR6pÖ<�ouô)À#Ø}ê=4[²ÏwÌH[ü]Ç#6Æk¦O³ì$(÷HyN ‡)A¢µ‘ ‘ZÔmš>+ȽÈhoÕª³Úó¦ó-ŠÑÌæÇu‚nT«¤Ä¸üÐßi›²E)Ù‹ “Ò#Y}ª>Ã×iU7V®Üpr^‚N>—æ´ë@îz†Ó¸™A!þy*ÚÝ_[è“•yW’O…6<K)ÛÛ]štýX^yTN¡œUÌrìÕÔ‚Kä5XÜPâÓŽ[päA€–¬ÉŠ"Ù‹ánñì` >ià7Ó¬oŸïsÁ,gì}8¼xûÌ÷LÖ.,Ê0É9ÓkI‰¨¨ò@]l}GM¥£Á‹R…`Eݬq™Â2ù¥+œ=NUµFÅ×°iºeÀOj”çq!9â«–Nb{œŒ÷ž2N<ìkãe½7ôàÙ>77†ÔB¡4«B°À…`‚"÷ñXЩÑr§À'ã4=èÙ./g-ÊÊXŸ·½`ð€,æ}8›æŽªÁ›t+Ÿï+, W ¼§:u‹Éi oÊŸX“øá[©ÁÕçê±u©S%K©ô*½Á²,¹M=±Þá­Íˆ(»âå€Â>hä`|ˆ–oÐYœiâI3yàË׃©oXŽüˬG_fÁ4 :¾gÒ‰èÖòÕ1]Çy3IôÊàQ¼u.L»‚.¶a í%¤Tת¨ô,l +Í÷þœ´æ2<”²x4JA_ ÍÊò¨,7@F-žï¬9¦0 N>UŒ—LON×FËÙŠ¦9!…^ˆGq©:Úô³q•¢— %:1X¹ºÊ7IoÈ.ÞËuÕ‹ö™°jÑ“´3ïö[”P l*t§é­žgéýäI¬»SoUgû»µå\ùŠëÑBa""lñÐZ1kz°O³»Ü¥á2ó!•]˜ôù¤ŒâÏä×rØ&OuQ³MjÄÖ#Ÿtï¸ÁÄ×ÎKç¢[0UÄQ¯ñwæÛ@Ëxùö”x†Í©ðœë-í,ÇS”ÑÊrwM EË'¹·#Å:fïFЍ+tO“–AˆUµ Æ£S«y×1œ„NWÕǵY† ¤™„TãÝí¸»¤²|ò^€1ìÛ(Ü_¬Óú%_:ñ@^f–u{ô?]WWRèž`sÈôÜ¥›çL­”$Š`i zn¼k0„^Šª»¥Vz†8LØ,wÔÝoÕß mÉV+oC½êRÚÔ®{&¥¸Z‹r½ö°˜Æç‰›)¡þôNéNlÄ’ˆ­çøu™èi’\/€óW¦½ô^¤e y ¯)ã.˜ÕSã÷‡’ÓrI:ÔöHÛfDiÎùÅAc6“½´™.CqœÂÑ«äòªPVšîíØÚ§mÀͼr \…'A,déK-†/µfɵ’ t½�ÄÏá {.·f‡âœÞr¾­V׋HÖŽu‡ m1vqZw¤$]I»k‹ÓgL÷—[×¢JÃC^ž,GßøTg ˜r38.݃¶{;|“˜.Ìoði,DgNˆArïß,ÖîÞ·ìsr¤­ÞÆ.H®3…õ4Xp¸Ê+Â}•v•`Pdðž‚SãØ¥”y•16K Yƒ¬Rðì‚ðÕ é„¿âе‡õžÅ¬p<{ïLââB(RZìeáêªåuŸ‚™îÃPÁ^L¼VÍ–ÚÖfɈ”3}Yù€Wmã±ó ³b«¯ZÑä\±ÊÆ£”Î\ræèŒÇØ«/^$ð{SóÀ€`J%ËŠ²^d4Å Úô5ˆ»B ô»~áZ@Pì'×Ð/µÆïj[óqÎØ†‚7Nf¬ì–…µÈìÓrßÈÆ¨µuO¯\Ï(U’‘¤OÅLã<ú ï%EQ¹‘1¬P*4¶‡o2õÄõu½pK@™¡°óç4ú¢Ç½Ó…D/<ëðd‚•#QœÆF‚¹¨xo9LF6Ÿãó Ì’RL x#¬oh†Ì1ô)#J£WÈêîÖ&á,zGn‰ê¼Üˆtζ ¢=¿g3mE4p¨dM²Ëj v®³5NjÉñz¥Ÿbê)’Nµ“¾ÒKé¨8ÏŽ›I¦Ëá÷ª#M“Ðñqc—¼{gÏm‰<R ½CçbIø#äR¾{‹PM“Nöl#^ûñÊeÔ~ºåŸ/Ä­nt#¡®{ ‡ið=Ñ‘ájŒlJFÜöžÝµÃ¥%Ø<Åè÷î¶(l¦Ì2ì å±M©VçŸreö³»¸ÔSŽâ1b±v«Ýw×ô€9kápð1`)ì»mðÎ}!¥ª-¦3Þ³æÚÈŠGõXŸ j€Øzµ=¼L&ê E"6‡\þÝiŽ×EÛÙÓä.Ê”}BXs½Ô‹ø­<zºË§øŠ ÉWl¨!Ÿ‚¡"rè9H0Æ›nˆ¼Þ·Yh)—4Y‹š&‘`(<„ýžÊ4AÍXÇv: m ƒ”¨+V¥Æ»Gä†5£¼´Œáb&;–ïBÚxk:Q*¶â¨\éq¨M¹z‚S"kò c À­”Éš…Ã÷&¢=’GÏ4[¯ÐÄëuáz¸&œdSúèaFn©Î¼fF"4Ðd'îËÖÔ)}ƒbÄLÁCRd\xsî÷½oÌMm»ç •uÏ{r¡óê¾�jwi6h:*€ " ƒp}k6ïŠ7±ºÄ;ú&BZ¯\îUɯõâ'"ÝÃ%N1ÉLU])mE¼oÖY7Öù½Ãä|¤YmyþRªú6Škœ‘‹D¡Åëmäëös…JÖDÈRŠ |ÊuD%M­ÓÒ/…~¾Íuó«¢UƼfÕ2¹~BQÍQÎ/ÂìÍ>`¡UÜF¥ëî‚ ®—ξ5×$ëü8z…Wö‘öQ…áZ³œ¢QìNN½¸ÖH;#bÜËZÓ`rðQ– ´M›/¹D¿äbÔ’žŽÛ¬yŠ5–u) lâ[é~3ê7Îûb^Ad“pØ<-~]kå’š¯·&}ŠW„£ß®`•^—fãþe׋cržÛü4ÈO)[Øo´¥iõšh]z4"¡ ³ ½öÓ# Ö®×L¸ñ‚ˆœÌÒ¯Eßé4‹” tq[a-3‰Î*ËÖ 9éë�Ð3Oõxáò<WYפyèõ€î©—¢­¶ÌÓvyìÏÞõuFæ«ÑXôN5€À¡(hÊ—™Kxµwœè!HÇ»‡FâyÀ>`-Žæ©RÈ)„¨í¦¿.MZ*GƒÓX{1ÅæÆ‹GÙ!!Ì$†ƒ�½ó¨Qp‡_ÄIn‡¹ 2mãz{Æ¥ôÛYör“UH"žðŒ±ôÞu¤{\<Õ-òÀ@m”¨Q¯çpæ\óV`¸ÍEƒïùí¿ºY}xùÂò:ÁV“Æž£XÉÃ_”n¡l_YS_yR‹ÅJ옗áÁŒ}`½Z¤c ÃÛNB˜üØ"¨žåE›ŠH–p*™œàÑË'ktq¡RÉïhˆ½O�ÂÅÉ‚<¢Mx‹u‹ë¾EC¶âbïÖJß3¼'m–fûñôe\9oÞKó+e¥”V?ÒÇu õª='9‚Zµ¸½è€=’Y‹ô½‡¬ÅLÐG%¹Åëuƒ”e¯Ržq„•…µ“³7ÝŽºÅÈÖcv*×çoƒxXŠ;ö„ÖôŽž&L&vœÎcª;§rÝîç…戴8ãÖu½—:ò&Ää]=æ/»”¿ì’–ËS½G ç±­O:9'ï(x`JÚ \QˆÖëÊ´¸Ví|¦¬°À( xMå‚ÞÊt趉\×!ðLÂ@þÒ ÛÛ•_ᥠ¡ á “ ™‡Ìð²ÈÜàÓæ%BsK¿×y¦l^³‚Ö6ýv*¬=lj)hçÔ°šÝ˜+4¢JœÐÅW˜!`=¨ÞnvÙ‹¼'[ Ó+Xøðw„±6ŒÍ{2èOD ª6¸y¶  ]‘ûÞ¥#F\Ÿ”Ä>S{Å…ü€ÆAª=¡z W†gëÄ{sdöÞGxJއ#JG×ݵ=q‰»xô€S²å4¯YÛ-jïil•€Jva´Šœ]ÓlòŒå<OÊuÆTÛÆ-vmr)IAëxðƺ*Z±§ÝE^Åð2Ì`úÎCr¢µØTW¥ªÂì§ü2Eg%OÉžÖ# ×û¸,-Ϻù–ÚlN²sÔÝöSÔˆlC“‡ˆ!Nôœ@°j DE„�y4ùñë >;Î4ő瞷4¡Uë€p ëô@*¸ rB¸FN¯fó [ʤ;pж„ý=ÃÑŠ˜whxƒ€ÆÙ÷®Ù&Pct\Ôš×Ýd€Pg£-×M|FBì‘=wõ°çÔëk&B¡8‚;PnwÏkJíqÒ»…ŽdxYÅ·coz˜<Ö9@¡0Å*¸©Ÿ Ó¦¿×"ø ÇàL^G>õ³¶ÁdªZ >rbÇòÎß­æAËNàÁ¾¸´G$ɱ(Ïïl2w¤ŒvÛÝ•¦ð% Ñ‹ÙâëûÒËèK/CµÅªÅ´N1wU=§—Ë»÷‚ ï5iJŸõ.HuúCEP¦%´zæœáYÄœŽ±#ìÎÓ—ÓœqO5ÿôkòùfN½I :·ECÄ·(óÔe m«nÀªÔ§èiÀ»×ó¶Õ¢´:�Œ6`»náèšOäá_ê‘Tëæq KrZ/FîË+WLš®àpbÖµ<3FGå– Ú)ä ß„éGùê6y 7ÚO<MPÌ ÀŒXü¡ÝN2ink<Ö…›‡—‹^\jÓÏÇV¸T©ÓY^ãÁ‰@H£Ù‰ûS’a¨æâ•foND÷n¹\¦—Hevnë {f˜?êQË<¦:6BóC3Ã'~†ãÏAüâ®fc4³™4í,9<_Q™~ï0QlÜPrÕ²"Z°Æh‡¯‹qÚø¥Ò“wè¼4J/“)Ï%øù[f°QJæ…׈R®°D˜?—×u)]j[xý´¯Vò°Ñ;b\­ (T'`Ów”Ý&¹Š…‘2%ÚÌã~ØcÃ`íº㎺¦¯(¸18¬QP ’*^½zë¦/šÞk´Šr• ‚ÓÍÒ6"ôD§V4KËAßg&×’°¢%4^ìI”ú”´nÈùÕÛä.}å ÙaàòC}nßðb¢ˆoÍn…J’æŒö€SÀ«K—±Äļö=¥ tÁd ¥‡¯+3C–Ÿ>Šm—QKUI5鲑6kã'æZS>¡L [¬Ë"w%ìe~ùåðåÝäCœª${„-B.WƒýàB™¿5fT}nV:Èͧ›Ú(�‚ÏðlÆ“ãlRšýu¿U£×€W6 ¦ •lxŒÜá’l…ÁèÀ’“ë^•È2{Å`9ª‡ñjw—ÎpÐätpTš‹ÈÒ#†œ² yöP湆@ÚÓTèè¾àAYÖ)u"¯DãÉE1Áçó.¶L»P¯ R õ ˆ t8Èlh äzôø²¬ËqÃå\Ò“}©ÏøûïÏÚQÇvؽx¢ØÎê$°&¨¡tÍpÝœK-!w'´(V ÊÕ ™¤\±°Å#=Ó ‹. ' ¥>¿½-x Þ]ðF)˜çQ½ƒW£”-Û'IÁÐÄ€g‚×Oó9ïžh ‘Ñ“.6µwðš÷꩚ó@ôˆk 1gqU½gÃü´¹Ú´“ÍûÎÎ&l—&7Zj;nÏ*ï :öÑœd¯OÖgȇ´$žŒŒd"Ÿb˜ ]mac•R–ÇK•Bm–œ™ŽºsŸ×–Î>Z,¹6 ä¥Z,«ží¼1æsÚéíˆ ÖLU`Þ»#Ý{Õ Ž‰qXö‚Z}ˆ‘'h˜tÌ‹«v8óÑ€Ô¦°¥Owª{ïiAµ _®5¾@©06¯K£­aˆ«”\önzèÜ ž‰îï(C@ML Â#ãÌ -âdK¹Á("g]§±ŠÝ«Ó*´Òx8:‹ŠÑáZUp×—2.2Œ«ëîô†ð¦!Õ¬yôÃ:#<V[Të·QðDÝ>ó/ÁBÙ8%³dˆ‰²S—ÑÍßK%¤¸@LµsëÀ¹Ázrl‹³åéY\Ñ¥VhÑMz"/×J4B£Ëÿ4,ÈNøqëé6J‘Ö½Q¼‡ã8¬ wL:L 7ï"ßäIåm†_ì»R]™´ £SéToŸöŽÜZ4œÀ/ËgòàFМ_Zdá@µŠ Ò ð Ä’ !^ÝvG¢žÉ3 ~|éΰn.iÀZjÁ«ô„ÔI‹ {â”ú"h_xƒYÛ¹‚Û1Ï!Jæž|1燀ÝGB-tj3×fòÆA=© Ìß3½-œì‰„zë¦,ø¨¶á^SG ál6¹š@S3'EQ óœtGXŽØ�×f¨<~ÎÏÜ'+EÒ²…ár@ØH/W!íùÓ.ë½3àó¤ÊN}Žlñ[‹mPæ’åŒ#ÉÛ®Q[CjOƒŸå¼óöy“ò\S'LH(¶zœû‚F“;ÑDЬε™— –1p“´®YÈ…pÍ¥?ŒÛg=@ºrv޳ëüÈz Œ¤OCøm°³÷*ê5¢Ÿ=-|t@bAR>ñ¦.uáñ¥Ê&m¡ƒh7k@­ùDMÏ–â­€G‹çxøeGRS#î>ˆ)ô‡;Im -çÔ0m²ƒÆ€`\KÁKy&[O¤º™©× {6Û=5'E~HøCrw#½Võˆº¶rz Šœ°Ê¥;VYJeML³ÌØ ' K�Ãí¼rÔ¥uw:NAA&õaÏ—a¡_†µaã1ÎsR¥ß‰«õ{ážIò†‚s¦¦Ƀ†a/„‰pz öXtÎâ "Üà´N!¦ÿ­Ø Áâð{Mû€SÇ£ECÚÕzZ˜+2Ñ!Èt‰»øv½ŒBÁxœ–yLh—Â@tœžCü4–¤‡tDË-pcV®|ݯÆñ!ŽÆŠ¡†ÙkÆô³ƒUZ0=i�‘I`šY°qB£ºÛ«*xxe(ÂÚÉð<dºØÁ*šŸ ê4c–ùӔǠI‚ÂrP/Ò9îQ䆨çS†Lä`Y(¬xÚj‹‰+åüâx@ñµ§÷"dã”Ä$õMãù¥y+¬{Újûçm-jU§:ìªTÉcÂ¥h§çeƒÏ­6[`»øåñ˜FÔîCeìä÷îÉ(Uè-›õ&�b@_NnU ôØN}rË`Äæ|¢SÏEßHúÖ$“aN/r¹2WDùã™R‡aÙl¯Nž\¼¤«Xh“~nG¸S´[ àÞëîºz!4EÕ¨«Äi4ùž›ËsáÈô ‘ÎJ´`»ÚÒ|À[QXœæÈ»LŽiüŸ¡9°H>¡]×: ŠÍ€ ýJó9£š>Û»wóÈÝ4fØ‘™ T£lgnÈü…’ zh¼z‹¡;ˆŒ8…&+t@Ä@uF‡.ßf-,Û68iµiÂo´$pEŠ&dXωú²"Ø ÎO0Å«¯ŠÓ¦£=•%žäjJ¨‹u>i¦iê“]ȼ‰Ú{iú½jpÇŒÅøK±kýY›¦èA‹,1‡E¬ îoÒbbGHÉ%¦'½_?Z‚7á|˜ÅIˆ)KË|žú´d&®Îãð‘÷ ×¹ q¸ò/ÇŠ°hGýR^ï\ù®S(·_?ƒ4 $ŠyÍuns)dQ˜KWí’� vÎ`'®%Tr˜ya† $Û´D ‹.9]‚ Fi jŽ[±XXôZL[=f·y’Að=Åb|'ø¶ 9ð`u¯,HÝ£qµÀê-Î>ö€¦ª’~É<ÙQP°G…Åݼ&íâШ¨!m!Íõ=h²w+éÇT‘I‹í„Œžåâ‹å–£tœ¨™>ótÓ—ÒMÎ9y½'0æl³Avºúâ½k4Þz�Ñ"}û¢ÌêžDºÊì„û¼*}H¢³ºeO[Ÿi¼i±p¦àp…H%ÀÖÎ3§Ù5«WÃF^ù(aÒ=‘ ©†€)¨t÷Ú¶Ñ‘Ë�hüºÀÃd8£•à‚¸omƒUr«†õ¨Œ5CöšÓãæ´x¤Ò¹Ï€`ŸÌóŽÔBB >-b™æ“ŠÂv õ—-‘]‡fGª‡Ž®äÅh<ªHÑ Vøžž¡ŸÚH¯åS²}8¾ÊÅ•)ëQV†Åí4ôúé)Àypþ r‹:;_åN¢_ -OuáIO_ƉҾZ*@'Ý=éƒq˜DTSYV{B¤ÜžÑHLg<áóäÌØ¨“眯陔‚К ¶ kHý³xy‚´8´3Æãµ`õ@.NønyÜJÀL“¢‰¨ ßž¾Ü©G_Ž!}9¶AšëyºòÐtê®›R˽µÆT.^Ì4Ï¨ÙØ{™ø°÷aã2õ\OÏŠE>[Ø«=‘âÆ.~1þ$xérí/É -¥ë:v8EÊÛû6bc ‡·gbó­§F¾˜jX zù†ÇvËMà ÐÈU.Þ„ ð3€19¢-èÆˆìì{¸^S—¨ú˜zŒ‚Óè)¸Û£j—±l±ÖÏ,ÞD�DÍš<­�ŽHAW©c¼…Ý*ãw*F@G8/ƒÎœ ÆøYØ[_Å«ÚHQËJǸ„'§¼”†Îa7Žêgà šëSñ@Yõªå©BuJ·J©¸ö˜¬8“M[½³Á´ƒ6zÜ>`-š[¼Ís€ Žâaõˆ3Œ]šè4xÙwgÃW¦¹U’ø”FomV¡hù,RëÇ…"=x]dÔp8!ô÷juÐæU…Q3OAaE¼ÔÚ {Ã(pÈ´‹-Ƭâˆî9¿­×(ñ”"xÈåå¶’Úª·_Hì„OÌ4ÆÉ›á%¯*ò\9جê§é¸$ „ÆüÜÖ5äÂfUÛ¸’ Û·qKæMÞ [zpfÁœ%èV”š:+¾çê´Y†@«c›^•j^0U‡§££9pÉ‘ÒS^ë8r%és¯=ðó�¦{—-â¾\Ò¼ä Ât´êÈ~\Öw¸ý& Oß{F%j�rÔµŽ33,°vYb–OÈñLãõ¿PìçPJ}ÎW|‡,½õ˜¨Wº/67úÕHD;Çù’ŒàK2ÔõzãîUÀ³Ñ¡GJæˆöz9…B‹Í¨óíÞ–CªPÍžÀœÅ=š¢wqöæÅ+±‰ ;K:Z‹¾É—/ÞfüiÙ`šgøssR™uÇsC+‘|ØhŽl¯<Ú¨§°7^?uÛçúª‰keH$¹–߇WìòxB›yÎ6_›±IÖ¡û=/+Ö)™±¬z– ̤´™êûÂq!5÷“'Ì.ÇðLw*⚪¨2#'·9On^*ð®OÉ@ æÙÎP<Pu­g!*oi+khÑË<\=íœðJªe¹Ï±(³3Úñ;²÷¬xqØqT†^Ì l©ž´6yìº,¨\ç›,DÒe!šÛH,&ms¯vd˜_¬›pdA­f':ò>½Ê¡³Ê›* ES>vAßÄí©||ÖSÕÙ¬±¡ñc)3ZïÞ0•¬œ8«—ÍëM(r)yÈWÛ�T5´Ëh§²ånýxS¨}p:„å3U rbÞm-›lÑt“¶x¼3ŒÒ·F²V@—@õ%˜'ÆóÑyøÜâÙ¥½µ™}ŒÍR OÂΘ4ü‰)%Þc_„:¹C)ËGf™:‘^Aî’9ïÉÄíã”á˜gÛØòt¬ Ci1…—pá`#éQ0ÙlžÜÓg¼vÌ P$MgÍ7ÌU¥^m"‡±ErÀwÏ�ÁèÊ[*<wµ@ë*ƒ÷¨™±”³x;{T­+$Øt—®^4˜Fx ç¸�èã`O{ùØ<¯°+ãª^ļø´Ì?_—ÍÄ»EÖè‰Ø€÷¢Ed¼ÌÓAÊ}*qš’iG–¶íÙz‹ŽÃ–Ë"òå;߬«�×h¡ÜÅ'kZ¦2okŸ]ÿ¥Ù0S é.ÌBZ˜e_´í½§ÑC½“Ý Y[mˆä Iç#M¢Ú=×½köòf¨á<si%J4BŽ02 ´ôùLà@S¶bN¾nL 1Ô6)6¾ºå9.4euAt06¿s{‡F$DiŽŒ¿ÀñNÛÅ«YŒinÄæ¦îUÐG¤ñœ¥·` V!Û…Üœ½Ÿmöî„ë…³i¶RÒÛ§êÀ[#ࢣ±N¦ioÄD©�tÜf|Èì=O]iá”§CáGÅ­ØBÑ"õXÚc:ÖeæZο}ÝúGY¦Öš™Ï)9ø±.S{Õ†›îœÄë”á¹Q¶¼µT‹õàm Á¦ƒ×]|ÅÇGH÷ÆmCÞpB¼åy¤`A¼Õü¼D5Þv!Ö–B¹ôˆÎ‹ ©K âŠ3_t|ÏVònú6¢ "‚·â+y‘[UŸ½Çf`÷¥Rˆ„Éʽ#ÙzA4Sjù&PË﨑9^8¶¥^.,òÑap©1ÚkÜ) ™F°W—§T¦ó”Þ€ÊYX:Ur@oï">mpŒ7¬wZZŒÜž®˜¬ÀÉ]íÖ­B›¹o”}y¨w6ñ=æl¢®áÉæìU¥y\ÏëPã”¶K›-‰Û\(ÚØ0/DÝäŽá¾GŸ„x«Ä/Ñ&îQ °^k%ÆNA®>þÔìé—fYûب„×È×TÚŠÛSV&Áæ#¬÷®ªƒÆ.;òIó¾Gt8ôº2yϯÀ†0 ÉË*NJ'îñâ»mwMk´lî.•ò—gºM®þÒžŸk$½"T#+cM̦Æ}U¹ƒ}Óg16˜ÁG9l€§ì¹Énú”eE^½1¤r‹¡ÁØg¯`㉡Â]AOè5f AœË«GŒ¥nÂ1Mƒ‡Þw¹Ï¨—»Í2ìõqF í=Ú%ú¼Õa˜ßcSR±Ö»1­rù¬/.ñ(‹Î{¹·²’EÒ‚KLkx‡¸F "9è p¿Ãèr¤˜N€ Ðm¸Ç ‡<¯{µoÛ|®ñ)&§‚#Ô æåë$,ô¶9¹¹ª¿F5ÂÞbà‹™g�Î=·W‡#v–eªR¹7ÐÏS²€wØ–ë‘hAÊ€ ª0úÈÜvïp&Û%rF†©ÞCzíP*7 ÖµCí&ï¨vÉp‡üvA½f^ó1GØc}v„§²µ|õòqÀŽ[&D*)¿U¹s: ‡:b…ËêÃX1QäDBm‰sͪÎçTO/ š=T¡Ù¹7Ë ^&XǺ¦õe¶Œ°‚º&WÓ�4ôHõ±Yž9 ÝŠwåt$Ea‘;“›–ñD<jÙIÖßFÕê—ºîã¯*´R+É8Õ¨wè‘irÄä�ŠÈ¸´”^+·9µ°`Èî*¶'’mzçHhÒ4Z®´ª›©È€©û3>5®E:ñ|2éæµ†ý ¢É¦QB—,×gÌ_ž=½8H•£N{QÁ<ºwoR¶*ÅÖ&šQ“ –ŸÃ½>.¶Ø¦Ç>€r·J¢dOQ8¯ï×AŒ6óÍÀ) X 3hÁŸ¢ÝÁËÒzH<“y2U,צµom¨ŠÈ”íÔÍ£JÝy¼êBÕÁÌÙ^Ìã0ÓŠÈÂGb¨Må¦6Vö½’Ômõ@AâÃI{x‚qá¯Ûüš’+‘¯¨ç¶c;8ƒö(œÚHb–¿1çÄ3xP602ì»×Z ¹ÉÚD$ꪽ=éaÓDÉ^äHÊÌ¢Æz«i½VeúÌŸeÀ\Göq-c¼ô ©ôz êk5ƒÔl²ÀNI=LBùxñðUWoEC"­a$Ù’IÜ,®IB>ïrØbn w[ý^µS€à›æ‡cÄ!¸éš#1ü¤ç /hˆh$ó;`!âaMŸJï±õªöHÂy@ܼZm¨±šwU ³'žp$O"ìK»*°àZW¿V¢ñô{0þ̪ÖÎ^ k‡=lyÌVæhÙïœh$´¤uÄ_Œvûé°4;9>±u{HýÞ)m‹úçžϪ…㨕ª©‹èîó¹Ûæêǯ*äÅ–"¿º™Fª¡÷êîäŒßä›ö8±”H6w§ÊYÕåŽ7;@ÚÆêç<;êä|r@gÂQîGÌ7MŠõ¸Fµî$5HD%Á«=åÜÉÍ$%Ÿ [‹õ=²æèÛd ëÆƒë™dN¢×µŒÊW¦þVR Y5ÅuÙ{äŠÌW¢0>EúžÐÚÍôu.v†×xK9uV gû#×sÛP$ÏåYõì9ÙGÑOÁÐjÇ‘– 9uZ75.ñT©4e?Áp¼©‡ÚfÉ™& @,h =tô[¥3P±¶’¸Òp£v<Àœv^l¹Ø>’¼$œ‚w‡¹gCº+Ä£½N8ÔÎÔü.­hEÊBá 2ôùꤓÑdIù”9OfÛƒ:xÁ#íVLhMXžò¸I_AŒbâØ&-}I{)ÅWÑļiZÔrKLƒÀƲyöHð¨»cͳýæµl®C§ª¤[ Ú¦ô ¡5¡ä>ïæwd¢ïaÁûé”Ñ{~U7OA3åji¤æ!#¦‹Õk_‹¤;,€}¿Ëm’ñâ¥<= !ÄèÏö½·âË“Ê÷JJìªqqˈšYû3@í[‡Óˆ«Wº ý´ršêJ€«ÍÌÞ«Œ’P‰sU±z¯†¯ßÜh÷ñxj¦spoîlµhÃòùîòspŸ·g4¢‚%j¼©wó˜!ϳƒGÒÁw™4$ðá²B»xš5k€–ÔKòÖ:9 ’V˜}Ðü�Ÿ¾}DI÷´,À¢’Ý»<*E`nÜr£§R^Ct˜úÀOºE‡ Ì„¦ß>z(í"‘¯ü ñ3‹|›…ð‚Ïç ÓÍ»× üI‰ÍºJj ÕàÊŠœzkå.ÂksY~÷Äé$pRÌZ+öÒ/Þp¢ÖÍì(IÃ+5mX{Až³J‘œ[Mî½D»,v�zÁ[OIeðË4…/Ó‚Ï:}1…éqëÈë¶ÇUo ´Wz˹ÃfùÜ>‹—a€[û‚\o|™hãáDtø$ÏÙä2[eyßMÐsO3SH’¸æ«1úK5Gjä2ÏÝU'ØÄ>_¸×йÖ5”Ëñ�-gÁD¯ZLXüA Ì4Ù=ô7ÇÞ¸8:˜qo–üA¶½3Ë¡0«Ù|m/:ac1›¯vO‰®ªåñ«ÄšIM•gWg{½iݾ º'[c‰ÕôôÄrÝkƒHÇc¤y¯O‘@¢y¤vJ—ÅÁÒzi($¸ër{û] ùà(d—¤ÑÈTÖè…h`âÇò¤{¦ycí:B¡ ¡·É+w’w{bê¸ 7‰.˜èÛx/äõdjE?piÛ‹Úð'Ü›ÏýÞøî>£‡„ê%Ùý8jpâxonÚ³-·ºXŠñWnKnínû¨T/…¡”[žÄ«^°—¹\u†xÓ–§k]pχÎMù]ódqÚ0 Ê:1Q#+À2/ã�È”CWqSØ{² «¨ûhl£Rª`ܯ ¤xÄ"æ„•–…yžûë¦f¸Z)~ŠÏ FP Þkò†ªèâ)‘=Æ5Á‘޲£:`2;»#ãëæ‰7ûr¨CIÁ{ÑT$×4šWM8)Ž(_±Ï’gê{sq*}—"D7jyÕÖ¶Ê\³Ÿ06@ZP1¡­lÒ ^MXt{ë2œDiªÊa­®Ýñà°“@-³]KÙC+WÄõS x6¢RiªæÈÏ.§ŠíÔsMhÝ‚\“ÎàÆV)O?Uó/ÕðÕ#žîPéß=ÉÞ«=Ÿ–-$´Àj N8%кëWAŽMõÀ Ó(z1f¨n<óìéÈðtZ{î�¥=S+·¡Á9:¹Öy‰î[ã=÷‚¶|ÕÌtôÄøŒ%«J&ŸD„€±Â΋ç'„Uè!óäÍ+¦=£5àýe(q×ö©ºá‘ÉY¸‘t¾d;›¤âx×’�Ë®‰±Á*eN…hZά’¡þBìÞˆÒiïqž¬"x±ú#mÁ]Œ&Á'ïp3)çE>Zɹy�¤Ã%šÄá¢É ^bȤu’­ ó>¢Š2ÍܼàL§Rã1¢ìµd0ýÂaíý=gXl~›jYgäÒ·-ïeÐßž¿¼ÔÒÍg”y÷tZœ€¡¯ !¹ìFªÑ“ÔÎë`ór«0óΓI^t•š«€7;cWÎf`« ÕÀé¸fiœC¢Œ7ã˜Ûnúx4h™ÅÁ²‚/b ì.›&MЩýAØ&ñF´ -Isï�·â$uhÁ¤sÓÛ25ª=‚õ ¬H;Jh€œcåæÚã"¾Ü7á<²/¶Ø‰šsvSˆ|Œž›ŠÆó¾•©×¸ñnÂ@:££ Vç�L^Ð…Š:U£¾—@ìAôÐÊë'ϼ@Éwïm"n€_‡wÀCn O­h¿qÏâ1@Õ[±FÐK5VŒÆ‘×õfÅÔAéRž—¨¼ZhprJ@‰µâ{d¯¹kÑžÜ+°L�ài;ÓþzV„s"H¯ïp0›½ÂÌÚHµ}¾\3ýtmw¢+Ñ"b›¶EÀÍÞÌa³ND[ÑXÕ’Sn­VvÀ^’t&îå$1)O½BØœwƒ´3³Û´µ†Óá§/§=Û«À–éiɆ 9 €¨ïá’{>‘ÉNcRDmkÈs…ÄT¡¼Ç­£•,À+­ŽÇñ2™«\#Âú€˜á݆ "RÛ£&]aWÉ9•à:Ka-‰ðMÒÛ"ˆ}0¯2É£U°(u·‹}µxô¼wÚ±Ú£¢jWó; gÓi¸ÛþŒPFí¢¬‰™ Å: 9YøÌ+Ž „âA4A{5·náþ´ªŒ}u"mÙA¶Ð±_™éG{ÈXá!ûÑïFŠmn“_æ.´ ˜ Oçs¾¶V®DVº&PüPÜGTÔ6—v4wüÂm$Ò:’‡m–Šà)<~ú`ƒ–å;k—÷"ܰò) @*OØO)ÇH2ÕâÈ<DOò[ ¼„kNêt¥ÀÇ�7" øº·9ÙM·åÕ{ÃWC#§†ïàð^ãj’‡4/•è¸pçìÛÎã¼·žen:ëoð=4ØèúâÜÅó=&æöI÷x#˜6Ú9’ĈSù*d÷UȽ¢mR!WOGñ»{ÍÖ&’-´g 9ìùº¨liY - Êsr$ÊÒÔTO­ÊJñ1R’µcVsa0¥‘Áo¥V.|®[Êœ¸ ”ëB#%ôÑmD’‹!þó¢¹DÛ8î9C¾GÒ²Îo=ä´{ØêèF} ¼±�ü™ÙOè Ê\rø’ÍùK¶J)µ’í—ï.—cÆÑ4iϤ¡'àɰtt@d�4tZR¨eH®:i¤N³j[©3'Ž‚g«âÙÞÈó}ô¦ä¨•¹Ì‹†}<ó/ÛêÙ!Žú3Pž‰2u Ðê5̺hØÆÌ¡‹²ODì•w†Â:/»7Ÿ¯©×1«9&U.GkŸ­xÜ:µÞ%ϳn¼�:P\þ?D<4Þrà zØÖ›FU'ïÂIIgÀ{ŸÉ.ŸÄÛ‹wF€ØYNŽÀ‘¦ÛxB>ò2iA<ê˜!À ¨'’›ëáÍ=óöæQéå­Z³â ÙÈ¥È× h”<ý FC­ŽlfŠTDµ¨Ü&.¹á©‘Î_Im`D?\3E©…|ï^ÎEb»4qè\jð<~ âgGH ¢£BÂsÐÜè¿Êa`Æ¥s\ÃTQ5™1öHñk•)3œ‰p#WÖ’Á~øX”é­rl¸Fò+ÝÎ+xàav¬MÍ]�ùlº¯¹m…O7$í"sGÝ"DŽWwOâò¥)>´+ƒ§ !¨œiÉ!tI‚”RN Œ\ -ÀIÖýò@ÃÐ'·§–ßÄKÌåÅŒ"OöÓ÷V÷z MÆ|“Q�,¬Ðãux‹qÊ{1ä“úÆ·Ìè Ç ža]ˆÖ¬ñ#© ¤ËòÖ‡U³3,öœS7´Ö2_y¥À!”2CA�K›GÛ;ˆ&ðO ’NM ˆ)[ßPÊs{ã]óòÁ!˜ätºÁt€6ôY×"†5¾†V¹q6¬Ú‡€ö×wÅ_¶}Ù{Iš-jÕ¦³³\!í(Ò©Üq”Ãe䪰ʊ0u)ɶä _%O9X-I¼·—D¯f¤p^·.D• ÖKí¸â10þK·`Z¥'yÇü@é­0,ŠŠà‹½¸r®sŒ0 íHõaZ»g<¥Çòåõ¼x>=ÁvÐÖe÷“]íºžkpõë;n„0læmT="éá‚Ã&eãç(}V÷,ÞÛéçýYž í+"h!}£ÖNi«t1Äõ¨ÒS‹¦.AÃ:l¶•„E“´KD„5™02@j†îöG_Š’øIÆÕÈ2MÔg,ë8")Ë–ÜÉ‘£ÞAÅ©bª›Ë=ïn~gåvâÌã˪Rp€×H…Œ¦oF´Lëf¶sО±È»jé‡iI¾á'OѰêú,z\±ú?'zºÐò¨’V�’†éµ™?Œ·Í¯mŸ\ÓÜi²¿³’•éÀ³³¬.¡ÄG ϯ7ž[³>YÌ÷‚ëV<F;Dq@º¡HFLêHð¯0ŽÑ45¿õkÁ ŸJÖšKnÝ3Y\é¬àö…' 7ǃ›–{ëâ¥èIîù°ªãÖŠž#¨ÐHÑæµ¦Ç9(Ésâí=îé~kbÚÏ:Þ_x¥t Nù)ÊH°i=ªZDœÙ²l­Èö>Õ>«÷|‰¤f'‡“Zš‚ÑÁw­††VbÒ�¡WUô´o%H|%Iu¡õÀBÞë°k¸‘XP‹—uuÛ^ÇóÙüeŸ¬Ad"2?ÒFYËët0’Ù&ö‡oÃiöC7øœÜê&Þ¼±: ζã'd66>’R¾<ø&tè”× ³jSÒsÓk»k¦Ð¬z„øm Àë›Íu³îäÉ`)5 Œñ‚÷Îlžs' Äk¬¿|ãûp;o´|Å^sæ@ò§«6’}úÞ¨©J¢Çî`¼çþ¢ ŽñÎb¹$í ^ÒMNçœÐسÈx’OlMÅïHžWDF¼MÝÈ›Ž¤ÂÉ(õ‹Žg6ÓØ™uöCð[ˆ°cÖ©ÊÍBN#‚Þ§{ˆ€ä Y3oR/|ˆñ-Ó:qð{-,›•!(¨!õ|pÙ¥9:-Ë_g1yhß“"èêvÑ"²†ªBÜE„}Â㫼ʲX½ø|sÑý‰õSÊ¥4 ÛÛ»ç9”}ɃFð­â=¶Ö}Ѽ\Õ¬ÖVJ˜šË -"°%Îçp^â#ôdƶ|G¡ý¸Ðž¦ÒaC�H×…QªV±ŽM#q¿Þé°‹¶ˆ×±O%ñeå)»D3Ñ0�qdÛUôóVgxõì½L}oÎìøŒŸ íÊkÒKå!Á†hÏéˆÜ}£ø:[Z“ëw±t+¸ˆã² Ðeºï¡’p0¡^Ñ3´HqRšÈÇ2– ¤Õmñ¼úUËH¥óKË,Ée^¯H¼N(•Ù÷ädŒ®k;�¡úyI=[<x½ã¡Ú„U_J¶§°­l°=ßr5·.z–”«’06ýö˜ ñ‘Ô` OqVa£MÅåRÛì5õ‚gâZ©«ðÅÓ'²-Ué‰Ù,rØ ëŽtßè›j;›fÚ4œö‹Cq<~ùé›ù�æqóúIy^ƒjׯPøT®MɵgÜ//+ø¢|ö¬#[œR¦zB-¯l°ØOŸ/FSeòÜc;öáÔQx€¯én(âHÈVö³þK¸ÀÇÑœ´‹IÊššAËïÉZãdœ³S“^…Úã}é-ƒÄ)¼*n¦â;çî5 …’9U»LáI—ì”Û ð»µÄ­ɉå¹ôöñ *»`UmĘeÃGºxjoSm'eTÛáÉ[8Š-yqA<ˆÃH ð½µZ4÷¦3{l­ÌÅ/8Þ;Í|‹ÐX‘á<H©­¾ä`.{‰xhÅa´ ;|tõºzNtFdÜ\%§^ÈZà›ÝHÞŽç‰cK/ð ±Oì:hÓà˜Km§@§]`pN´Ýünâ<>Ð çb˜ ê㖔ͤA³­tüÐÏouîi@³Ã²ß2h¹t\Ožˆgà –6f£¿ÜI+€öE- 3¯ F*6([;T‚H ƒ—¦h.éó¬4_[YCf Š•p`­\ª~â«’v–I‘MÛ^Wkžž‰Ô0íœBÁ�Ë‹á:}Û üÉZTÅÂÒÖ…C›÷Í×Ó^¿J¦™‰ÑÕÔÛÆ@pýèPXJ ´²]x5Œ“ü*¤wó°p®Þz”»âH#À\ƒ¾ñÞƒÓ¸z8ÐlÛ´¼)jD{ønYtá!X¢…’\¨»òÃX)»…<éN}}3ª ‚—ý<zÙ•«_='°7Æ#u•#ðª¦$ qxÂ_m_j’^^òŠ•J­»ŽH +Ñ—p¨_Â)#Èvº>Ai‚µ¾Ê„„r‡�VT¾g<ØS£ž™ÕèÙÎ%Ty·Ö3õË‚7`{�·jŒO=Ô„—ÜêÛûˆ·%9î¦$k4)(ö/ãä|» S†”³fò°ØCº·cFàÞt.ŠÒ¡3$4†¦ :ÖRi�â,çkpË—žˆ4ü2ƒµ‹°ª™t(«)Wð½R09çtªìl3ì·ÕÆ“”ØAX¯ 6bÉUáa‘ x1Ü󺽄s„sºÁåj¤éX‚zb,e‡äøkæDwГgZïžÐ*æ¹8Â<2qrŠ\…;v·¶ydä¨}!KÞQÃqãPnÉmˆ;1bÌÎoq¢Q©O ð¥]Ff äÃ7Ì­µv jŽV·e7ÉTù^c¾—µ 0=+z#­—ÉOP–N:¯ M¦èRY2‚¥ü S#|õ–­‡Õ„c…}›¯ø5½5“`–ª§ÉÌWÐSï"} ûU¿e²T„˜u¾M/�íó¯²5ßeÀ-*{=¤Ï‹ÚðñÎÙORÝ¢7¢g˵ƒDeŽçø^I0fmÎ[íÐ…¦1xÅÞ´wk$:bg)¹,t5ZPšÄùU€]²,™>§ù\¶(âR ²­° ŸºŒ²p^E.»@îVjÓ‘Р÷ hììšA'Õcª7Àk¶nœ¨°:„ô6(o«ç“q­'$ÀcqÌ›V˜¤ý‚�póЇA�V€²@$Þ½Üh²­©·["36öfÒ‘&ÜïX¾Œ#þ2nX…kɽâ^bÓ�J˜§w‹±áˆ:$eÊã³gÔ†½™e$ùü5_ÏfŠ]çëÑ{H¡¸ÝåzÈáX)µ£YRÌá‹§íÔÚ¹zì,õÚó/åîT b!”€!¶ù˜82L…•D·Î*(™4ó ¢i BÊÖé›Q ¬gï"ø!Â)D%Jýˆ0×(´~Ž%¤†€­‘\w¢EÏŸ™&\Ÿ¯Ç‹öÍ1³I~ï¼Íµ¶¬Pëuòòáë½xÅôtœÖ z^k°ÜXùA§å®Tª–ÉXv^ÎnAumšXÛ—«ÀÞÀ»v.¥wŠ{19¨/ÄêÓÐ)ú©ñ8^›Î¦*Ž®>·æ×ê!í­ku3?_7ÒëÉCñÆ{ò^B>2óè$ÃÓ’]4ÄœZDBÕí3­êÀº.…qf†Úìή^j2“Lâgwùʦo©8¡k–¼ –ûŽã{ÛBŽ0DjZúÚÖ¸N‚cmäÑ$q¦a‹i'û6^‘ò XBo;>³œF’£(²¾eXèYynRƱŒ” .®©TnîÍÙ›ÙMÎÔfƒ$ÑšÔxŠÝï† N`Z Š%…Ëã•ßÓÂ[2JiÕG<¶¹þBl ï”LÀË쌎°ù´ôöZN„ºžo‚^ÓTj“‡Ã¸ƒ .K$ŽTÔ[}h‡fAðÛÜ)¯…×[ÂEïFÒÕ€”àÛKÈ2¢¥ÂÁ&nØBô‹F]åÑgÍu­®R±Ð<e؂ثôðÑMSwIKUUîõ­^È1´+†ò}*÷èK9¤‰ìî$;tUŽê`±Ð›¢nc yFâTð„ʽ€·¸óaÕMºæF@DïÀ{$¢DœÂ0«{3ÕI¡{xðO 𶯑µ¦H°^MŽˆöÐ_ÎA¿3rN}Ú&¶½¡#3‚ ‘° h*ë¦pŠ&ü^Ýã4DzéÇË$GÒÒ½BW,Ö%ƲJkéÕÕˆï*‘"ÆiÞ>N]ãçª0ÐÊSúÞ!8» ³eààÉÈ!Ú¾]_j¡ÈZt7…Øö§Ãss‘ªc]_¾yÁ@g9�·îj!zyf êÁ. Dª-=t89,œ÷ÊkKÎÞ¶£W“ö*œ�jù*óTöTF�t¦â˜„KÉ€¾|U3R!ñŒýeT6C‚*oH[ó‘&Y  Yê­´§Ãô{„•Ó»¢V©®…pŒxà7™ &¯ÔØìÔ;3Ÿ„<¸GçNší†..�{kvÇOðæZÎZWåÅ“Ærß.±~3 D3àÂE®KA×y9À„™[li•ò:go£¯äuÈfeÛá Š,›–ë jPÚÒèÎY¬…qBFm‘yÒªä^bg;¶Œì>/œyÆ^á]’È:A=L.šdrA`òéÌBMÒK¯í*-­ga3•¼ÙF¾Z¢š&”`»… áÃEêt¤ÓŠhuÅrû@³Ê=ÂÔŸÏ`ÝC d ^â#9~|9˜ÃÓ®÷ v./»mÊÐÈc4d�.§A<c¢¹f#΋¥sØÛ¼†ÔA&’Lºœ@ ™@¿œcørÎ ÆRîi¿IœëËÏrvk2¾œ÷´ŸmÞ±Š—°5N_–ÊÁ³Lñ{²‡šwœµf•Чâ¤gµêXR:’¸éಔ=ÒèæùK8RGóèÁ_Ò¹÷ <6÷©Ê§Ï%8ì -øqÜKÇî4ÖN²GàêÐËÙÝH@¸¸—s6M 6d’äâ åw {±ÄòÈa[I^]ãøŒÑgM_1´î¯SÄãÚc 2NýejÎ5íH¥èÇtCŒYy]$P:o_ub<ÏV<öF0sÅh>wðx×ÐÌ JYÀZd”qƒ^nô6{Ês0`F|C«‡_E\=ÅIÓ³‹„õ§(¥Ý««ÑûÖˆû©(¶‘>ÎYnæB¼^Wòxó�C2žVáÒkè ŸËa\°í�9™òi|%º¨ýXYûa‡«*¹=-9yFê wËú¦¶èÞä!¼!¾>©„ä nõQ,}ÏÃ÷0áˆê £®Z^ f²‘Ùñ ÎKŸ Œà çý4ùÊÚ+ŽÌаÒÛÚÝæã“³SåF‚;²ö™N"âÞd{oŠ›ü¼áAÒƒ5 È9êàr%ˆx‚œ{Û|L²Ø»oêΠûô±®+Ô£ó$ù·>-r"åÀÆ *W"xG¯Ý iÜ·äNRã$c*Íxó=Ç{Òè€ôžâôŽø ÚyKÕ¼•ƒ#sp9À‚)Ú$Wà€ÌZ’7ÇLî›®t‘e~­àdÄhês«hk$ì4§D&ð%(ÅnÞ»»¦ÂMÔ¡Lœ©”rÈz]½x”ó)I·Åw{<,Vm†xÇ™Fô°“$O‹–@Ïë\bÜÄË#­çý¸-’ç:é¯räT_%bÊé)=½‘ó‘ײ‡þòõ¶¢”@[«ãš½Aˆ;ãÀ’n" mùË:‚óëôj&ãÕÞñ듽µÓäwÅVù’s‹óªKÞÔI«pÓ\ã=ôä$ â•#“ÈêÐñŠhC—’´~ÙKÕ“‡û¢u÷Æ¢Ïcè^ºS:hÄœ©Ò‘K(l©šŠ‚Š\ö˜+±=¥—¹a°"hêvnyœáØvt¸ ‰ x”/Öc°•vL°¢ÐEŽÒèe—#yÅ嘉ÚÄÎs€/}R…+_/·¦)rW4d•µöl”wQâ>HÂ|ÏèEPξ`bry2)·Çl=¾m9nÓæ<ic"u#§=»B•(}e‡L‘(ç­vá£ËÜÕ^‰:07©ctÕ˜Ìñ(÷šÆSÑ9ÄÆËØ:a^ „T»¹”6È[N~üê_ÇOZ3Éâ×ýÞ÷º€ë°U>j(X }Ìاë5ùtIÑG¸J€ß•°jT³GKÎnŠ/Åé\t¦ö&RX¨M«Š?¾™wÊð^r(F,—Þ³…«‡µÆöL‘(ÅBX �täbÓ %ÈÆÉó^¼Í¼$3À ŒÉc⺩wyP É� îÁ5Ç@®Ø¦*Âȹú0nVZ�•ç`V¨sCpõ”Sƒ0ÜèJg Þ»ÖI0ζ›ÄtK}¯Q·g Uü ‡`ã•Ô—u¢ŸÖù¬Ò˜¸¨�4·Y2¹"õ8ð=èwóôŠ0Z:!ó‘faÀʽ#‹{oÌÖH­ÑjɆP2’÷Ñ)‡’éó©œ jë|ðHc‹îõyyðf»ÿ¥ÝÁò¡ó¼·^ržYö xëŠ öqѾõ쇞:Aë%ss\pä(vk£,,'dí ò”´úIÐë º†X ¶yLu+¼÷øJÂÍ€ÏúiGÆc»—@¶`©HÖà$¨ÎãíÆ+viRœT9΋¦Žg&÷bôѾ¹FBͪêöR‡spLrÔªiTVaè½ew¼^Ú+v¢EdÅ’Uæ—K³ÒLJâ£^€B Á–†\Ï,ç…“D<ñ³{ÏEVùÎ}b) V_Xö=Î> }”7+†èâŽ\ÎÇF[=ð¶:Ôð^¸tÄtVÐí0̆åk&™çS;ó¸ è™áÎ%_¸ÇòÊÒ›Q¤á,~1üVuŒئg<‰{ ¡²î’‡´ÚÊÒ0AÒ«rro µA@ÍÓƒ.ÔÒQËTš Ž<„Ô[Õn¢èC©B6ˈi–Žg.:ë"ýà¥ì¶MBœø1ÃD/0L`íÆÂx+r¶Î بSBUw™ÈàˆFÉO^¢¯²=mœnˆ3ë͚ȓ@Ûë'uëŒPÏÔŽÆeAìÑ´bKÐ9¸ÏNB—i9)¥bmAz] é N™¾:Æd•íör³kyø"H†E·!`¶H‰\ybŸP½‚€@Zàª-¬yï9*ℽÜÇvÝô¨ëàK;å/íô±Q¬ν2ƒ6æT]ptKlmwÔ˜2nÓeÚ —]dš£ ƒ—Vóö•^El‡±A¤eí° ¹ß¹¿%î$l;ÔŠW æ5o¨Ì±uÿò=Þs@åž±½€ìl”aê ˆ¦»7ŠH ßÅ,âZ¿ŠÌ”c³§K±"qñ¥ "GsÜ,üõ;Blí]Ñ\•ƒRn–Š9á§,ꧤìÛŽWêâOœúô•€-pFuqø{hÐêû€¡ühb+éùÇî¼¼ Ö€$“ÁÄÆ¦8Ãòéîìæ áw�Œ6¶¬­|Å,\o¦,¡°\r»æ‚Œv¯&Ýq(kÍr:-I[`Vyö0‡"-¶ã¢•=DnD7Ó›±¹·¢:¨¾$ ãï)šÅ³cs˦¸¸šÝÀ˜ñ!VºÆ)ƒ%«Ú'‡Ï”%®QÊô¦_ëD¿Ó‰àz�LïP¸ôŠüœ%óM»<›UÇ6¤Uçé±/ÚUî…Ô>¬ç•CÚ7ÜãªåFÃdÛk᡾ª*î/ðV -Xç’Qi?{ؼ=Lg2¯‡¥¨ ñ!Zdáy·sƒ?ua›ìî 6+µr•Ro|ªó¤%Æš·Vx¡mëùs…ݾÛž´†.ž½ »œäáww-`€xl…Z£¡!Ò¾Ôv¥|¼ó»¿‹pÛ¥î‚+s¨;sh&yûÂM_¶ªúS:{,îÃÕ’Å5ó\Â@oÌÉGkîãáDÛó€"[¥:æ?öÒ‡I݇1È]'ûÊ.î0®V�vXO!INôÍYºGîçtgôå’ݬÌÚ{‰êÐdOŸ’­¾lÏwXl`N›$®"uèç‘·ÂHÆN•€ î,\jø@H:RZJ/^A¾¢i7ãgµÒÄO»îôZ–[<¾¾~›yú—x¢&Þ«Àdþú`ГšùêB¨ˆaõõŒÙmòƒQQ.ô"²ÒÉ­\Ÿ•cäå»<'¸}ÞŠijutML›o#¸»UP¯O½ÆÙß[PL•4hÒ¥[nÏx–IíÁòša[€h•Œí{ʬå Ь$µzFDÀ‚G­­+½„FJÞòµãÔjL'ðc·q? *i"~|ýø)¼dxÊeM}hq‡{1§÷AóXÙn>^n×¢M÷$ ~×´ï¼±M^s"”3猹:‹Íu ³¸ƒ5¢$Õ(*ê/öÕ¨+“ Q9wõj%úXÖ6ðZIñ‹ Z}•okÖ0s½¥¶;Àmr¬KÉ“M¬”ÌÊìÇó”ð©>ßm„#²„ ³z¬Ài–±!ˆÄ%ò–ãb¨ åÍ+q9ê`xá…Tå`k&E´ß è8¯4ÔR+ɾK#É•X°ÇîÁÎdˆiÀ‰B€mt|C+ܹlò°ÁÚoª™uŸ¨*ÚOS+’”ÛÆ•Û¶cðƒ •¶X}zmã•WùDÈ$³–ê27î¬L — |T-^Úɬ;Í–g�u”UÀIVòàZÅÈreIL7ó²[-‚ ·éЮn‰’®–=\)ì{/È`êI¦y‘ïMhˆÂ„i¦ßpŠBRÌ"5[>|X%‡ç7†ù%žÃ—xà¬x�ÚwÜ­\&Ô!Fn+ —Y ÒQwCï&€æ·EÀ+öëòóã¼·<SìOâ ÉÀsÕ𓜵˜ E¹iyd.›‚ÃáÁËR™oÚÀ–ˆÕ½•ÁK½ÿ2oLoA§YqÌæPB¼‹·ü!Èw%v7–ØžêÀ[z/sRÐè=E¨µîé!D‰cõãÞ{o–j…rnDO\íüj^ÍÍŽ8=kîF`÷|³päž¶=éç6ãB!¡ 1Ïàômû¢r Æi¨º[?ïˆ .¢x½B»ô8SòD ¶^^yI⿚õ{âp’ƒ!8^;åw»²];øI N°²eWua‰ÌM¤<líP-v¼½ÄÚÇtµOiûÞ°æ8 [59È«|Д�Oy÷œnïš!tϳ¢XÞCELÏv.Ÿƒ² ¡”l‡“º«C•ñ•d;3l¸ð·À2ŒÀeë+Dº51–3ÏmÖ…æHwcòí´-A¹Y²Xج?vUÒ|÷@ „í<;F`DqP)lcfÜŠ®({¤\°˜á½K^dGÅ‚Yh´Rð‹„m¾à2Viö‹"Sm~Ý+ö|c÷tbà(tº¦§žñ6–± 2™ ©xêÛZ$†Þæ #¡×Þ6ËÅ,°†ŸþnûžÈ5°½±ž·:6YÞÞlö ]˜†wzqˆçi:<.“T2M¡œîÄU¡™´ü®sBØ gÖ…ßé¬çL¬¿Ì;-ÞΙ™ÙÑÝ„Ý!Âïú8.˜èã½ÑîÕ™ÃOóüóUëíçÎQH°ºÐ)®š'étïõDr> ±DöæÀç‹K'mŠ‘:²³µ’=ŽÛ^m}j>à¸K’&ób xчM‚ ×É+xˆñˆ§Œ„µžPÂò_ê°¹N—¤ßk®åéÐ>To•½y³*W47¡…]÷ž8ž(.PƸõQˆ‘ÞÓ Õ¢E­ˆDì86ùŒTiਘj‹‰Üͪ\òå•P«G½I}VBåXN›¢á°Ô70dÊ<ÐãZfpõŽïHÑï�àΜD˜c1»ž¼„U¹~f‡N¼ …oSÓ¦m==”Á$ƒ‰Ó X´+•š_ #Ëè ‹¢„šÄfXÆq2¦?-X…�EKªŠŠ¬²áR3c;ì~ºzçäUdE:£H,ùNüù‹ã½Äfy£#Eõ‚mwI@gÙ´êÙȵdCVØy‰–‹[úm)ö;ŽÅ]-×ðò–Îh ÑÎÑ·¼Þë‘çy9Øe2\t‚b>Jžh€s¢U‡fÁã•îë^RnqŠÂ–~R/±\¢Ò–£):Þ…¯ÆÖÖy@œ< Ñé3µ\Êk„× ”Ù˜/( ž¿l ,'‚åpq£@ÑÙÌØwbl’ï̶ƑêaEÀœ]œËf:]éÔT0U`¿CâòJ|ý²|…JmÓðá*æÕP¼Tìz*Á(»?žS”œHFqvir„¥”Æ1’ï ælt.¿Š¾¹ä~”>¨ˆšâ»Ïø±?Õ·Á€}H“¬${…ððÅòº >ŠÃŠ:YLo!ØÐ·N¼¹'®úd01Ï—z¡_ê•(…ð>¼^òë4~ç<>ýØ»D¹• ü¬ õélr'îÔTÚµô[àè §ªô¶ƒ÷=|β1kZ‚ÀGWÍòd»v«ß«&;ŠC?=²u WpUz¢¯ÿtïê' ÈëÄãrÀë2ySË’÷Œ#A®)çüOÀ¦0!¹´,XXÓé™Ú˜æÛ%êZD>9ïGUç“. ð”�Œ<¦Äµ!ÒeÏÈîÅ«¡=¼žF3[|Vüf†IZNF]†ßÈi ±øM¾ãìíiâ.[=~ ×§ï½.ŠJtÀL‡†ó$ö$| •J£´ê1" [ðžºùëzt¦’"ó@ÑŒ;óºô“ó f&860¨ÇëÚä8°8RÒ{ðX߸®;!ÚÚ”Ôð=•Ù›)—è°&Б{þÔîžë«x‹–‰AŽ”§ÛPX2ÝÖ�ÓàMÓݹŒ»tå+É™“sTäׄïÚ°\xñvUÑc‰‡î~þ¨ç°†]¹¼Œ`™#‰ í6OF9€Ð[%Ù书¡¹ŸÕM¡Q!9ÆÑ˜<§š¸Ð|(˼¸ì7bîCm!üÔé0ž{÷Óí¸µõµ` ÆÀ{"M#Ê—\¥4-r¼Úþ›Ý²ŠˆÕ‘·VIä@"Ÿa^ñ«Ês£óWL!ÀbSVš7øN-6/y‚¥â5W­Á±²Õ¨z!a¤™¥è³¾%NªF‘«xêí+g?õH€,¼@½GxÛ ¦o¦uTô­eæë|ÙÛUàγ-Ž"âãwFëîðç wijUåÒù1­Bïí>,LÞì):$škõf¹ƒ÷VÈOÌ]b7–{¯8|ƒõY©Ig;ŸòÔ›ì[hœA7æ6îힸåiB?Þ,?*a¦d›¿'>­k(|SãšÝ*^‹¶¡[vãJ87¦eyo¿H€'âÏΠÔžBv4³-ùÆë¹ïËzÓ¾ËMÏ|Õ)|;‰Á5®D…ÞI�±œƒ#ÜÖ¼wGbÁûÂÄ7ÂyÙ”t7=‹¥‡–ÜÞ°›DºHÑ$´§Ck?•5]¯gY\‘:áNn0MtŠù¯ã ÕJ;ç)Ë–áªá+œ(qâ@•—þTjåáˆJ‘¡ÄEKÛåvßâ*icGÚÚÝs'U*p.'« ]W)“wko_<]¶½8ÜDA7?5Ì4¢dÆPئ´¦æž§Üȧ¼ÕyW{ȶñ$µà¡*¨è¥AX›áŽUÁ”­1ßöè3§éš˜4±7f級¬…r¶çΛ¸Bt©Àù )µŽ•GÜh{fŽ•\’ÁÆüÉñóuZ¥N8¼9+&X”‹iPÌ'å÷<€¨t£æãsáƒ3¹ŠnyžÓ‹ŽSê¶z/G[a¯2ŸXr\ ²gÙ.Mèfz@˜Ógxˆ Э·DyÆQú¢€“´ ‡6SKäEN¼q¶ãäë;�¬òÑ*Zk“@JpMzÊ/f5ƪ™NÔ¯ L÷¢ŸRu5ÄÝw¢EÜYvâ<¾Ú4ÝÚ›>¢šÔdzQêB)“þpg ‚²!&ÆéIBÕÈ¥ ˜!Š(î­5r! >£ø’éK>4‘¥¡•ÁÆeÑ’&ïŽQUp˜5|Ý�hú§/©xŽ”'r$pov­‹¶�È_KnÕcÄG¯Ôh3‘¥IÐàÞ. GR:›* ïÇñÈx™ÓÌcî?í[2Öž÷â= |ËOoZŠPêÅÀ#Ýw: tŽÚ{/¯µ­"ŽŸ7­£É¬Ü—‰–³¾ ´zœ€ˆŽœ'^ í%y1Äæ9èHÏ^ÅÁƒ¬²¨±ºçÐÔ´Šk2V‰øœ¥–_•¡?3{Êåð^¬?TP¯¾y–µš›º“¯Å«.$Í,EêÁš) „ïÅQLâ"V¦Z<K¡]’f zÉ’”ÓWmÀÉÀy΄W¯Læ6ÃâT¥6J­hÅI‚Q&/}#õ|Iô¹©-° {6¡D•9eja™rú“8Ûfz]�R­¯ÈN×ĨD-b¬Ä+L"º+o8p²—:‚(CÝÆÏÉô9Øõ…UʮәŸ?©¾TQ–œ§':²Äb\â8Ú¬PÑ£!Žöh/gÍÊ"u¸Éð( -Ò¹îiî#/p¥S)껆åÒD»YrÀô¸›˜-+3‰Þ NIæúé eäLe´à½ÒǬ³WÝÞjÍíÆÄòóê“Eޙ怉ém:i}2K[y°oÀ¦6„;lŠR×iÊDLÐè4 †ÅϹýé½²bÐ .ÚÏüÅŒ]–fd\L5ä²´²@“XYƒ*ö˜œ ìþòïÊŠê4]< ‘-FUmß*^5M�ÙqJ_a ú;绽­ ÍÑí¢ü´à󵋳˜ŠˆˆûËZ%5Hxg›-¯Ë”DÀÖ“¤•vÀ±q™!×Dn7¨Š¸áé‚—éœLPÜ1¦sŒäÝÛ7ô,7Ó‚ÔS¦°µ<cÛšÄÂüµç5^`Ú_úA9±š8ÝqòåxÊlÄœ¡Â{C†d¾ÑH¢£¯›y8¸ÇM™*¢¼pÚ-¸ à%ž‡íÃ>ÇHh¾B6 |N4CsÚ|#"+Ò}…nä¢ëÕðAñЮ î¾%ÚA‡ƒZE}•ËÔÜš6‰$ ¥Ì‘Ñú”¤÷z�ÞÅSÅA}§¦ÙÞNÀOO¼ºŠNñ^°¬Ú“×.ÜýœGÁ¦+@SßDfRp×»`í#ƒ×þŒì2;/Ë¥ÕHÖ3:Ó25<Ð"Zê´Ü…DÔ8)fs‰ j’„VŸ6 )sTzÈ,ÚCÚ…‚Kõ)ò:$"ŒÃÇ9ô&~¶ŒÆƒ£%û‚›!`å2Ä2BEyó«ÝRD¼Sa¢âÜ¥a;ê~€UË”§†'Näc:ÖuÓëÄäF{.ƒ‹Þ› í&*ËžÈúà¨vìã9wŠ¿|j늣¯²5ùEVƒ=MP©šqÕ¤g áa÷ziS ÇKL]]RÞ¤%C\ë!áäÓlzŒq$ܦk@|yÃR»ü‚z¹C}íÙúÅn;ÀYù>ØSåJC^ˆ^i>°Š'˜ ÞûU'™×;9­›ƒõ„jð™‹M¼RdâTuš`:ž eV£íµÄÝ¥Ýc-ɬ|Ç ok-'R–lž¹ö… ×3&àynÈò8N>õó/ýúžøëšîj4ÐW¸6t°º´ rc¶Ä+ /Hž,Û‚€Š]¨ãæDÖ@¾Ø+eSJz}–·B É Øú oÝÈÊñ*"=î¬q:íØ£•ßZÆ^¥NH‹Èýå£Zõ» )åä´ù*b†‚ƒ™ø¶ ë¾Î&ÂâÛpôxA5/[ãàÆTJñmÙ>M9öëÚ×Û­& ä4…Ît!½} ì´Bk›Ð¡wFéÌ:03¦$Õ"¢®L“tÔía…<!ÓωâõÑTFêÛ¬8 †ìèt»•¾K ŽwïÉÛÇŸçJHׂë3}hO’ZõU—áH°5m3†SY`òT¹ž]Á{„°|+>½F¢â¦¶ÇÆîÝ Îٱ݅ã0Z‹nY!—u°<sm«‡öú‘É#^<ÁS­ƒ`È ¶iî:A翃߈±sBŒAö¹4”9òXÛ3ÐxÜ›ÐÝ\8x&‡ R2ð^J/ž÷«¶ŒîhïÛšR:ov–ìá«Ý.5‡g„ƒvTþàexVE¹¢#X1dz'Å�hb0ftæ/s;‰y…Âúê ‚™žAÇ-ìmc®«Ú(ÞrE/ÁÎ:¿×'„{TZ(}§â‹N¤‡6‡Èjrbî‰\q|ñ^•ºä˘š Í(·£Í[ Ok}�ެAý¦`âÀúî)žÖQâeǦø˜ðSàç´c}Of-Çž±=t eUp¼Ê¹ÉTQfŸÅ[µ,Q $|· ' »k—¦”gCIƒ$¬îÙ¨E„Ü>v¨Ë;µç–Zm¨» :Ð%Ù/ÿž~ùF×@a/Q*Çè‚p¹!^…Dœö5K×sØU×.ÙŒuЬ¨Y}œ…©”!Ý F=ogJ<Úæ¨Ô®ç=ŠS,LfÆítË÷ÚOd’¯*Gú¨HÈÊ7üU=Lºœmz ¸Í¼²xJñd;Y€ƒsFsϦ°±ýÉ;|ÂÍOucEÓGjèù«HàJ²‡¨¡ =áTZFA6´üÞÀ½b ±“ê ‹zÆ´´Ô8çËú”ü‰åÖ³FÅó ÒðGÓäÉËá¯X!%­#ùá»}QEh,¯i¥·_ÃðH#j0íÃh3Cj@Ã}ìÖpEôÊNO›‹5§©²ò.t©NB=¯÷<²:;ßðf7)°v6×ÛE!ØtN,÷°´}Q±7*ø`ÖOƒÒñ¸7‚Žo±'˜_ŒŠ`§—†¤Ѷ å$q¿­cr†f*ÚÇrž V#¢8Å0ª“nwGì±yé󤟾—íöൿô§ÎA Z,LÜmȯ:¥NgJ‹.YnŽ¥Bk°ë½Cmt~áÒ’^Xô¡èɽPa±î:ÊYbëy†9~Û7Œ†½úuêÎAÔlèÜ=£Y_Zœ'Ý'²¶ŽÙ2chÍqTƒELïá–*¹¢ŒUkÌnô;„GJÎþvTÞ<?206A8§åw°¹º5×y:O!ÂSr}íÉõšç.½Gg¦zéEÅÚƒ‡µ 4£ýÆZßs©[Ž-;ÐÂÓ7 åe¡Ò8ѱë^PÂé#2”B òæ¡‹í=6|gcp)‚¯«F¯»3;L�÷…òL=@Zl‰.¿ñ"Ï5 Z²/™¿4Ýí ÑRŽs3!GÖÙ÷戣ǖМÊIgŒ ÃÍ2(<z°j ‡ø¢íH}¶’@AîfPáÝ\¼£«¥‹ía¯~é£M[œZ¤û|´åê¨Á9w“ ÒŽôO‡$LXÞ3eK$UJK| „©C [ƒ%¦{ãÉSl‰€É;ÖP³UœŒäœ!N,Îiµ„ š>‡ oHß -¨EwÅH§Ä)VT…>É5Y>×èò‹òÖF•g³6@ECNÛ/œªÊ†²ëzl6Þ:g‡ù˜÷ºù¼s|Y‡‹%è 1écº¨Í6Ð8Úe°¦zrïè=U¦Šš¦ŸÝ|£{ýàšW8n:µ.e}˜æyo¯ÕËG‡8,ÃÊ}¨Áñ\a Ç5)ø5¼U+ŒIàí9›ù*uHt¤ …¥ð!•®R.âC[õè~›ý ¯¿® D†%X Ê—ÇÜd ¤Ó)j\Áa‰à¦p„cÎAÔkx˜FMOý ñ%ã[ª¸<EÝg+(·DÈšOºâ  ycƒÝÅ1¼Ê`3‰N¸*ˆÕ¶-Qz`ÇÚ`,€›Æè×ʘ M¾&KÈJ*ØãíMÁ성¹…®ÛL€ÞÝ=zê= ö.Bu­R3©r<f¿¥ËÝÄð”Ó-`QP_©ðŸcÁNf‹·Š{×ä¥hìKƒ€ä ge°íÝz7`Ø*%½ÃÖQ0g:¯ …D–ì2D4"u2óÒi]ßæZЩ?¼;Ž ÑWIˆ,@s=²Åõµ_$Öëš×îO;ó–½§ãÓC" ¦Ô(Küe Ð§9 ¥o›4ŽÌWƒ9%iü„ã2�Ñù‹le~nuÙ®*�.M=-.·ÉV1´B£’TiÓÏ€÷df`/–*àrãary‹¨0½Þ+'9$x(c�…‡'O!<ã¿IǀВR#Ñóø’ŠFi3X.èêÖ³ÈQ÷vÌðŽ5¶ÚÂ*Ê1Fæ û4½x^â¬õ¼z3u…ÓLv�/f­!ý=-„”£$Þ£„Y1•¬}ÛkürÞ{!„c '.ñ^JIr;Ýš8÷tÎ+¶uÐDÀtj^G+#Ñý¢ѸP)ˆ¢T[)A2¡µílZ×eAÜš(™t¾”ÓY2ï0†$ÛðjQÐQ?‘ }ÓýJZ\\©J÷ag½p~ò�Ç‚¦ŒYVÙå=m½÷XÁGÛ†\P­Ç½Ù2¯CÒ†É\Æ™$seh|Œ3 3Ô0ù9­ ³Ìî9”5&3Åò:B›¼YÎ"Z]¹d »WܤÖWH¯ß³®…0Ëè7Œlæ0CP´ÐhŽûÒ·5àÞ<ºç#2ž«Œ§(Ï”ãF] EýÙ ëà*€œ›;‡¨sª£ Ã&ÎYiÇ”v’X>ñÐÉ(Ùç©#{ƒCW äR˜'Dó8å±±ŒÖøê€:êúùsóh™õ£‡fÆÇ÷Œ_Ùªse ׿*GðL{Ö¸ì¬'FZ"ª–ÕÓÖÓèb ¦%×™¥¤¬nÃaóhRšéöÜ#˜ñžž•Q<RwY,µ‘«¶Ù'tîÌÇܯô±És$g^ùRPáKÁÅ»ËpÒîõr­þ dÁËÞ¬=÷Œ�ß™Óöî3'²Z*«|ÆDйH°NT«.GkéO•«¯öù­ë{G¼úÞÝb¸/VKöI¤¸EŠe Ô¤(¬KÉIé™éP苉îåš¿,Ãr›×¶’©P…ðä4ÚÁ¸0Iî5G}~ñÌ%¤Òwrá/U*¼ˆ|óe‰[¡¾}Ó`{“40Ͳƒ$œì‰´°Ä€±<Ê·7ŽxŒ±7jã½NU|,xšé›­Õì†/ï¡g²L*±^yO´«^^G²·¬¶Èà�,øÙð#XY ¾N*å3¶ùjO¥¯D7šW/€jâ4÷’ò¼ ˜²%Õ{¸„Iï„õš{+jS’áñ¼™³:}%¬ç‰cïâDÛ ´dq»š˜Uð ¸f¼7ÁƒGØQ ãíó!ï™{‚dzÑöX<ºYÔyv#³-î©U0Œ.f‰åMÞ1ÑÅ(¬¿MpRŒYUÒëž“аiëÞÖç\–mOÓiñqƒ¼rè›~®ÈQdVqêŽ"J[¬ZÃÉåÐÏO°ÞÈ#Å©š<,aÀgúÉ< °M {as›ÖLM(¸öv}É8¤ c'ñU¼õ™ &mÒyh=d/`Ø»Ìȼ­ÙFž V-˜wi=#ïɉ+¶<Yðã�E-È’„4+8ÄÜ— ÚÄŽj»gnŠyàh®³Ã¹ê­BÞõ 9^ë’çî&\œÚS3éŒê"‡ µ8"#‰ÝæNYrHn%ùöD¹íIE§ËÈÂ@“¢N€Í¶R²Ê•ýtпԸȪT‘ ]À)ž^¡©¬€¿Æx dA»<™¤Þ p·‚¨ZŽâèp’!r†¢;™hA‘ “󣦵 h“¡åt`¸}qúªòŠáM,y÷+×ޜѱ*5¯].ã Íà/ %¯Ï»”í5p<¨iiÈè NH«” Tã@±—ihŽ€£|¬]T‘³â^Øš`øu¸w§sìô‹‚zéÌ_ôvRYßy>tr©šG…+»¤YpNJzŒ‹¡G—:¦FÕlU™w4uj_”«_ÓYé«cy²¾ÝÄÓJZx/ë¸À—(ºLçºÇ£}gÚlãH¨fûÉÔR¤TUZq[PW<y›\ùæØG[t ;I£c™¼ˆBPDÚ{UJ ¸ûï<W6nnàH}Ì èºˆºŠ:êÚÖð^ß”I9]kénîiXò ™MjËÚV8rª…“’<¡ ,µ@}¯GÝV}è±2ÇËõÁ%;/:öwRølÙ_@7Ù„¦‡a‘wô&±²',ˆ=dœÔÄ,aóÀˆõ ˆÓ›SM{²4nÝõKüzÏhùœ»ßŽp�ø<ŽdÓ-}é¶Ð“JtQŠH殾þBëxݼ®Ä3퀛öeÀÔ=×vã*+\ïm¦ÃlÔF'¾Gž](ÜyÃK= .ôy»(©H컦šežRÜ„æ²õ²h«:‘~„ŠQÒ^;©0�3oò5ÆpiÎÑHsª z01cuÞ¥·C�’ Ö’!<@±8 ÷âyÐÙnLµaÎã=R\|¯^Žr•n0ë!’ûbšòÃ~¡®î8J_š~Iø<ò uJî\úb´²¹oôK“©{åj\—EQ2u’úárU{0uuˆ…FÄBm3Ç#¹Ã™ÃÜ ê¡r§”¡e¼#Þ‚ÐÞ2èª.£¢4Šx™tÀ¼P’Ô‘]¨ tŽÇñ—…Ëdkš rNÊŽ­×ÄgŽÊ ;‚‘ç”…ˈÛi¨¡›È=J ‡gTÞ{Š1€ñ&üA麅Òãó @PÇ W÷ 1!ËcœöéôÞËn€r-gb §“\tº+çš”‡-ÏxG’ÖaŠðYíZ@GÅe ñ™dõ´d¿~@v:̯¨K´¢|T76/N)étdŒÜ6jJl÷!Î#y5jdž•(p&4ylG÷Ùl¾½"&çR Ï3ß'ç5ŠÖ±6ï]2’÷ÃpHׇ ·ð¢ôÉ <hÈRÁ~Ø[ëGY)¶,Ô°~ËxÙW/<É42«»s(óÅLÉÛ6ееG¶®8õáêQ>IŸNWÓ¨S ;ç€m ‡{Èo“®,.3R޲­ A²°ç9ZC“.à«ÙÞèºy¬|(a`¶o‡Ÿ8ðô܂ԼX·Šz2qäýh÷|°„¨n¾¾çv±¸Tó–߀ —€ÞÑ.v7ä*J ­Ú`œ1Æí1¨é;Jx8!>{+}sLÝÚzòh^×¢oꊿy ‡çM �i !Ã9ïµS²_¥s:çÓÑá¶7#J‰p6½#@®ÚÃÀw{æJ'È…áá¯Rßñ<_Çq¢¾ú•ÚôDq++ÜŠÀ щÙñA”åÎÁó3u6Tz¤o:óËBçÏ©p¼u™£Ÿ>>D1Ž&öFëAö2B±¤~V硱é¯x´ÒvÉ›|‘CŽpH¨ôòS�. -m<£ Šæ§"]e4ò`\aL(öõ;ጧú–‡`gûÑó’ˆò)qˆ”Ð_’/çc ­D§|/zO8_±’ªc RX6UCΈ։µ©¼ÊéF~¾¯ÏPtÏvx3œïc:Š-ÞPnŽ“¥¬‰5ÖÙ>¾jð`¢ì«EÔ¤}î¡ÈåX3}úJU<@15ÀžXõÃVä^&…Î;Jn‹iÙ˜à`¬´:Ë^œ+—0Zu/rП´kÉI“½.RT{¼Itôø-)îó¢p©ç€aĉ»ýDw�µf=ë™r¾”—¢¡"¶z#0-ËTºúL÷¹O4r”ÚF pÄŸø‹xX'¯ )‘ø�ÛaÉ zÄ<·óºŒ©±æš†K.iRj¾,8ªiŽIÞÒŒy×Ñ•8W¸ÉÙÇê#x“®X>=JLœºLF‰ÕGžåæ—aSüÆ6V÷½ÓQæRÚ|PgâË¡5(´Œ†²š9cª‡×Z2uÇaFQõ (nš«ùD€^hhôiˆÕú¥Zò§Þ¬!)ÃÞÍ(¸:ˆN&Bj÷jH¦§£,?$ì0\nÎw-«[dh0,/îå³dU9´èÖvà©+Œpä+A«‹—l4«ÇƒShÚ;GÂGäò¼@圃szú "Z½—˜‚[˜ýNÇÚÊJª±Ás²†Ð0ìQw{Ň>‘ð:…Ïxìœ ÉÖ]_/¾ ZØLצ©Ž@ÂÃ/ ƒ>5Üëê<l¤˜Z€ŠÞƒ~Æ1o7†±­F�r–¡§Uf§ªrÊ]R ¹%4 ¸9 îƒGîiï9Ó¥­D4´ /˜H;a[2‡`3À£C7Jì ¹Dë%yëñd¹_’1ujxt7þåáíC–¤.w÷Æ+·4` -V€‚¤Ñ§sEï\Cü€0ŸUL?’ÒŒõ† R -ÙÇ}µ*èSU{€vhÜ/·š`ð A¿g°Ø×úØ#ü½ |&úÐðMQ§ï{þbWÉàµ#§>­âç2yÒ³xD;ž÷ʨô&Dª°¨ç * [÷3JÆjþž»¸a$ïC”5Õ€âuöÍÞÖzhÜVµƒ S~Ý„n× .Ç&—²÷LÜ—Qôù!»­ó½4{çKõ&š^1 ʼnrµé ?kC¯›šâ}/^ºàÖƒtJeœWȼobˆ^á9¾Y6›LòêèRÂózZœoßE íM@ÈS Sd~$¤ gåÛbÈ3ü@¬Ž³^m¾ Â+'¤ãgÑõ]¢£=c;ñÔ·púäR¨%öa(…`f*“òÌ;Òí„<k¦×0o:•8yÞë篎XŒq2œ)<DíÆôJ´#ò±:â<|0ø²dÊWw¸ÂŠ3ŃôF²álWÑTvœ:iÀƒœ!nC:lêµÕ©yfëÇYÓ>\CSUz:kAþ@ß¼ív€Ð'‘¸þ,Ä™ ¹ºcÜ'õ*AQ‘[é®d"ÅÉ8— G˜Ç6 p{²¢ômóí’ž7öyu®Ó[«BÏU%ë YϳÚ`2‰GJñá¡|yÈïµ<xøP‰€p\=8 ›¬Ô<J B‡~ÜÉL¯Â ¹´6³ Û,©ß;ïx5LAÝX ½sˆGvp›Âœ™ùˆ<E2Å…©„¸€zÞÈÈi€å­aË+q¾‹‰•·¶à¬ÓUÜû—ˆœ@Øò}Azk” ‚ãzÙ&Å,Ñ“6}Tà\í"q”AÍMÍèÍG +ù^¡8_ W᡾|µþæ ž,ñ0#œ½"uhð'å SÜLÌç"áMõR =ôÚoˆc#Ä==ot 4_°0V0m ¿Çïꙹ02據'‡þ„_¡]K?¨‡çÚì§€Ú„›¬Ä-tR2ƒ”û^ÏDÔLª W»1B!‹ÅÐLOJ´Pî·yVsjgüò4'3ƒLõžªH‡’¾z~¤i‡“S!¥)¥ïÞ],€ã)<Á]ÔЕ!Â]ìJ²ÇQ\©†›+Áöî L&]h˜µ…±¶7–A&¾°¹8 šæAtÚb‹üf­q‚aªÌ<×Óäb^å#Ox„D½°,-jv™nö§ò%°ü€Å¢;uàl5üôÈ@Ù™jeÞóB?ï¶ÓgÁ”Ã×YO7õÎÔÉÞS*ßÀh^©©5>ö™@Π; 7j}IM-4€¢+^‰sPv‰æ³]=;MÐII¤"Ø®þ$7¶s!î#·´ù¬[@¥ë45Á¯FU)ß.ƒ½gOšÃdHcÊZ¸Y^6«qEß!ù4A+u»V 2I,èCÙlÇ 7Œ²xOªûؽNEVËí<¡D’0ÛjÊÉ+Ÿàܧˆþ%bº½…VëÔ@Zªþ�ü,SñpXˆÀFõ‚r'.^…åƒB¶$¾wªÚFcøØwÖ�ûhЖH^?Ü~¥lS½GçÇ[îØìÊŸyà–‘lJ£ÑCm]ȳ9ž³3]èyPT9Ç¢.÷ç«y�ü|G°5]¡lçQ)3’ÒX·ê ׋ŠÌêÝΣ M(9ìJz|,ÄTãšb•Þ9È‘;dA­Ï­(yõJ«[Ú -MàL؉7. –[xøõùñÂð{稴¶n¥ÈRKº—x µyÚ÷5(×¼"­tZfåzÜÏžl<Ù~e™OWó�(!3gõ Qò`ã0[Ê{îm�Q—ÕFŸÔƒl_ª’5ÕrºÎzýú1È‘<µÛ½F:l›C;ÚTÀbg±xEî3±fF ~Ë ® ’çwB·Œˆë“Þ%Ä58kŸk»¤kæ<ŸSrï±·ö xòÜYJ¿âQá—[ïZ1¤ë•95f7Y¼JM“0FÒš·Œî— «Q$òž>ÕÙ‡=ƒÉC¬+ži+ëG®oçÖ0žT¢'ϳ·œ]öºÓÜ­à^:ÕUÉcÈ+·Ú,Ûgàì\Å›´h}Ç1YFOküÍ ™bÞ[[qÚ¨¼•V•¬~Ç8á­lÎ*Uj­9w³·]˜Ó´D&À0`׈´ð—{\!È_„ÜáYQÙNñã9ÀC Êz–Øl«Lâ+/œ65Xo ³«Ù„28^ö=[)k‹îpYƒŒ�Æ{[oD_@â9^;KÇR\¿8¤Œ„YRº &m¤·íMmïåÚlf}™ˆúe"€Z)_LÏáиµ§¢½R>7T_‡Ët8§q>…¸¢¸iâªWé^¤^±éniuÎ*!sÔª�·�ûƒÌ}ÁÚ~m¬‚ øT†w p;J\6ý<ËÊ7='t”R+$›ýùv¶d­§V™@oƒ(ƒ²LV‡¥ÈV›÷Ý…Üø(®4Â^G×>eNŽ&�«´8õÇx­¼€:YáOÑ@†¬¼€õÀmÎf"¼ªªÐž9?ei¾xàP°©b[@y3Eúꇜ¼{É ¤'è±Ö¨ù®F\#mèB›K2FWóšAwÁ»<™WJ1ÂX#¸y).vâ"Ï:¶—t!F+UŸ£•Ä\×LK饔Êcz· ´áÏ­ÃrÇæ²Éx¢&jF¨Ë¡3kЀA¥pv§l« Ÿ¿ççòdÜrH/†m€­ïtyû='¢jKÜǺ]i$FóÎ2”pÄ8#","èÐ5Àž¤JQ<·[ó öòMß|˜`|É Ù†ùòõ¡Ö¶sI‹NÓ3­ÁÆ 4ñæN)\˜ðWX0]'¡Ly-å1–y+eò fì,:Þ<<SÏY<a-¥Ó±BÒ$_.ÊW6wxÀzqÓVEô<.9àx=hL®J½ˆÎõ•Xú¡‡¾ì`*¯Eä^ö §›ÊWšV§°mîIw¬£ÂœHíPøKª³h?d\æaÏâ˜Ô4Ë":^OeÀŽT�kÞ7ªp,DµXàùæ•®é 0‹Ëkrä±Í3y'– ÊÜÁIû†Íw˜G[FÔWf¢C}ªHü¥âáë0j¡®×ÍÉsäv4‡Ø å(¬ZëîúˆßÖCoÊ)LFëB`|à.ŒF€a…]RI½FÄxpŽÐ8Ù‘£2ŠŽYG!戡÷=‘ˆ+ßvpÓ‰—\p°j Å"¨“ÓNñ‘ÉzžSN‹Äû8dÂÓâÜA£šÄüÂÏt÷½Âq&OlOB†Ð–Çk÷�å>xå탅ò°"މ%„ìJ-k¹dëMmWÀª ¼ºÜÈÞxÉælDE,ïè£tuƒd²9Êü¡‰y}HfªÍ «› ÞT·ÏýH'¤¦0Øj÷) µ£?É2ð—+=?Hw1 ®TK4 cÌQÃ"ŸßÀp…`¶Á”¡y9:ZAmg÷n˜Ô ]}ÏßÁ»vëÕÝHEy[-Fö¼Ð˜©½åh|­ÕÀ^é-1®Î�ÌUFÚìG ‘‰Þá¼…’ÏÕdTKŠTS™ .œ`¨ÍdöÛ±s/Ü©9¤7@MÇ•ônèp’úš¡sÝäJXå¨ÞK>Ʊ¢©ÓW†à2³»[ZQçqÌÄ'2“ìÀëºTá+ûY+ƒ�½Mà¾÷n‰Ûž(¾émÓÐëw&½åô| ‹Ö$ò)Ì=›ß1½iÝÀG§Ì,ÞëOcÆ;cÙçª(*˜ø¸?»«Ã“0Ð@Ùj¶çêièGî–Ùî>ÔvÛ×x¾Ò7%óŠÚ°{ ¡³Ðé2Ë™Q’#I=ýXLŠ5…ù,øáÊJW Òc8Z~¥³«ˆn®IŒ0â½²§ë̺ËÑ=”"6npc!„“Ÿ=a™$î/}¹¸OÌa+,"‡ÛLž Ï”úë{oï©Ê#ëãæ߉®év=Õ8ôáÈxÊ—N)˜B*¼m„U/³B¦·8]Só2ž“N=AÛ ¿÷ö]¥ ‹*ìù«pÓìÎKÊ·$áÂg­‹ I¨‹ Áøœý/»\˜$±[“/u\âÕÀ#PW³gçcC5†OrÆP¯‚²¥ÙÃzŸˆ?á�H8CIzbÐåñ¨örrDJ& ‌µv×¢ÓÎè ±._Í"Ó¥Žt€¯Ÿ= \vYYPé;…HâÌCãÀ!ò•,"]µ€Æwhä\ ü¸½¨(_· ;'I²9Á ¸8²§—Gº* 1¥~B©Bæh‡ï) cÃw¼¼Ø`xº¾z  êÇ)áø_h¬Ê¢…]më<˜É«—ÞMÌ‹ëüÙ LReYd(Ì HåŒÆiÄYÅê u·WzïÛ'~ojz…t«M(úà {"xÅ3Ò]ž®#S6$dbAÈ{@*7|…oŸWªY= †¸ÀÓcžS Žs~J¦6¸XâÂwÖYáùz¸zèaù2OºóU…ÉY!M„ oÉs�ÇØ70ÕSi=‡uÉA`< =Zù^‡÷ÒÄ8Ç(ì¤?°‚ˆ\sB© €‘Ãz›¥s(&cCåM¯¹Dh…Ø2oéqœìd¦¨’mñH¿×?ÃðVFoHœ<‘Îë•®ETiäô <Qm ‰Á)ÂÒÛ²X � ‚Î'½9iRD åôd£Ü處hšR¶pÆxîøT¢çÉ a›­ó¥É½Ûr Bæ³!ÿ’‘áKFåm ì—¼[‡UÃÜ¥oŒÔõM±q°%ÈScÅÔœ"~'í#tYOW,îh²Ê’J(žÁdÒïZûªg^F’À¯<͇·ï-nn?”ñÖ]\{ ôn0ݤ‚xKlt i§yÍGÿ²1^¾é™=4ÛíËÆq{HϺÎ{™%rîú1y�jªÇº¯�ˆ¼=*�Ë.ÎÖØÙÒ^ZI;—Ž19SQO+'f£*¦!1Àî=ôuêÇÌIžK,óžu½©á%�kæaãîz ïe¼‰ÂN GÍ^ 3\<;Õ¶e§sÌ÷h|P’³™æÄ˜Ä {€½…Ö«ÌlÔ1ÕÖ ‚5·ýM +ç’ë‚d$Ý~´8Ê%…IÈ$­Ê†mWÚÒÙɘ¡ÙU$s+J&J„{¬oGaà GW(¿jcxEÌ )éùüÆ\ÂY;HoBÑš(¶æ‰9Û¹<S?}””phð²dñç{ç$öÐr Àç‚Îït×^ã*ä“Ù!wR“Ö´`œ½ƒ‰ÇÕT½ sÑÑ[pàIÖF©JÔ3^Sq"¿{nMb„¾.Г[ñšÛKrû‰TåK(ˆË8»Gò¸3ÓÈ iâYï"¼˜Õ—)yâðΫè^»M–KvÒª§{G›87òy„¸X ®î±öX· ÓÔ:“ƒáDeH¦'ª¦•—£Ü (^•¢èœ•«¶ËGÏÂÈÎêZîÔ$¤ÞT•íUãÛäÌh„x»„Æ%¸<r0ÚS9£x)Ný~Uϲy˜ý b»d5_)*®UëÄ m’ݷʳÆ|ÏŽ8<Ÿâ§þe£„pe Rß#Õ’‰£Pt�RâSr-ÙMN¢ôˆûXè*9 ̾E•Aô‡I]a½Þ42ôÆPª¸“ÔûÂ7`”C R#%½õMéx‚>žkmÛöÍh�-m=,‚Œ5Ç<Îv‡¿t„ɨ &”›cùôWzp8ö[ˆätæµó•^&аZ´…ÍöÎ3I²â1ÂÓ7ûŽ3éƒã¶YÎ eòÚÜcm#Ðöìí%<{ñ„ŠöF™ÕÍÁ¤ÄÅž°a¢G=:Æ>hö† ªã ² ÙG|3µ™æ:Ûó–¸öuÝ*K[Ÿ½Ulå·¬f´ç­4™‹ €pã,€d»ËÊõJ×wÝO›í´ØVLùdÍEÕ}¬\9q±SÐ)T Ïðµp?/Ëœtj„V± ÉîÅeš¦Ìý|ž^äb²Ÿ(9w?áº']òÖRŒ%D6ÒŒ¶/¬`v㸭¯M$‡)9a6kwÞ* Jñ¾!ÝzW§J=Ø;y’ãñ^Û6öêÖ¡0ßlg/2Ÿ—ë—KólSØÓ*(3ÏÃ!rÝ$x@^êþ„`¤¸’(¯¶¹Ýoo÷ªÙmM‰êmØdÅØ>mÛ›÷Œo[cĤ&Û` èÑãnF~’o&õ°qèDØK-±ÂÌozIò’ œuläj€yS‰ô=ƒâÎÔu[(ª½NóÕ„²•Ô’õÀ³:Îî"Â'Ñáõ °Mî†ÄA¶YèŒÇ W0›C ZsžéáKÔ$`r¦Ë’¦SO®x)i½±ó¼\ŠÌ,ïÑçtî–‹ge! }_:Ê÷æM\PQ‹ŠA¤¨qBÞœßc;~ôž_pÂÛy´zï©ê8Ð$·cM/ ¬kç ï4]{126…Iéé‹Âî°7‘‘×û&橸ÀãpÁW—¨:¤û'ŒU­�Œ‘×^ŒÝÖÁíëG–‰îéêï/¥eÁIÆÛ9°å@}šl TKÒòø\§Ò^<[wzz×±‰!ˆ™ü.Éf¨¹HŒëÁ{cèÜ!.>%GÏÒyãÊE&Ò˼‡þD;+› Ãæ|û„üD‹(ƒ¬ ätJ›V¹æéå«5œ¤ $MÛi¡àÀò†rJè¦EÒØÒΚ‡ìnØ=¯èžŽÂ’_úóV[?)”Gaº‚4eBIÁ8uzW} y;ó,†×µ¼=²S©2S¤Ñ¨±¤f˜{…Ï#žYR䨱Ÿ°ô¦šJÔ3Ç2÷â½ÂgµX¯|â5Vˆccý ŽR*hÏŠ2¢ÖÍuÔú–ù¹Åpíe„ARòÊó&pͶj¶IýE²›»ZGî¹eì«lpÀçGcøZ;2‡z-ãyÎq]¾>uïZ[¢1°Ý£1°�î ˜v‡}yô’Ÿ$©ÓE#ZmnùIŠøžÑ{Õš#&0Gd´ý,‰üÕÉÃ{b ÇoF€ ‰;êÙ)?blø²Ö1k©­¯K,(÷k&‚•ƒ’épÞÂôªbd4®+OÜ‘9‘H•Â; îÛcšÖ¾³˜Ç·‹ï¡ÕlÖzëŽ °o™ØZ>o•NL+bôy½HÔÁEx ú¹èã@RœË b â3}\B*NàÅ-1Ýàüå£~ïb®_,(áÈÃ!ÊçP+Y#z¹-¯k^^=ØTCgfX)«!9Q¾ ´KöU @íbo¼k\\2®WlÏb’ŸóësLAFÜFx+™Ío\M‹(lÛ`êv)hãÙ6€#²=`üKÈ!k個¹}ïÉm?|˜³òœÊ|šÕ‰F®×`¡ê]sØâ X`oÕV§Ýi(6Ȧëä×(NG;ç„¡ÅÏñÜ^¶.!¸•r&¦LK43䜨¢„…𽄏¶g¥}X·ÐðX)`VVs»ñXy±Þ Ñf¸ŽçXS2¦‚Z>f¿¾X®*zOò-“i½Í„\ÙÍìSgd‚C›n/c.�ÚLFö©XL“úƒ~æ‚u, .A‚.Ø}‘OêéÊoîæÃv°!&Ä Z ﲑySj™ˆYªúœ”1köj�̈hA’�êHæ’JPI³Â2RhÑ€qyËË8{¹MÑúVxFýW¬8éø•åÁ¯QQl–éMOáÐÙŠïÖr]·SñréÈêåd3S™ûS¢­žð½”çB6ܰFB:Ñ7xø–XñÕÂK‹^R¤Âë(}1¯©rÈ7Ô×\bˆ8ÄÐô‹ ©¶Lg)¦3:öÀe²K6Ís`°>Wr [²†ƒÐh²0¶­lƒWwž.ö”ž¿§~BñöúÍù;É(ycOó ¿a}îE΢à@M ¥×3ߣÙÍs…Œ¼éкQÒ;ÝÖ%†hqOìÉ� ºŒ¼dŸ×®M/2Ÿ88ê½¼§pk¾ÎOÙšz"[¶ÒMó‚?'H£/!M|óݦ={SP^k+U{,ÏÞèêô†lºËuއšR™DSB�P ]/tI™*å–÷¹õ½ ysŠtf…-ö•\G4ÍÃóSD IpË'»¼»²ïq?ñ]ŠÓGWŒ˜{gÁðçYÞ„³xHÐbÌOhËps×qcÖÓût÷-½`~ø& ÇÌÁá59ºî{œ‹ûÐD ÷J|Ö\ö‰ej*ÖHÔwG˜Ž¸Â(ß`û]Á­†#7û@<+´µÈŽ^}ðD T†Û‚Ÿ¯[›º•B®_<å­Ø‹°‚¨Ð×–b—±y;.†'wQŽŒžé|ÝDj÷ŒÞZ2ÙZÏÙU%¨•÷Ô²ëbh׸߫Eàx¢=ž¯8—Ý íZ¼$éºÒ]¥½ñ% g¤ÇŒ#ý‚¡­æî™º–¯QÓ{Lb~ S<Mx< ož¼(<aÆ®ž|D{pÝ.<{QkT^LÁ{S•À…›/°S …Š]Ôß¾ãY�BE‡˜›/j†hDß²w+QMuœ…tkO“C] ¿váªÎ¤>e$ŸfÚçÅ€`v†=Xs›‡ÁjÜSOžKg?i–-ÚÑš8Ï®` ÚX±ìXÈÒ–z´[®ææMï˜L¦)Ý„ùì ,æ>,…ÚÍ#;[J1l¦fä'Ò䆢„óBT¯sk•·$D®<£°ŽÇÃ’ãaËZSÙ‘gñPE¤ãdUÚ®¾R‹9]iœä¥WB¬ËÇjiohðNb WGb‘Y ,ŸT±…lî® °ˆ¾š‹¨)™†BëV¸ž«ñ`—UÌHà.]Ÿ'‡éðe$[ëBS;«¡«;ðÁYÀÌ£'þ¦Íù"<ãõ`'·î9ã´cS3Üã’ÚÕŒçjõj*„ZNbõžŠz?§5Ãy!¨Û«`qå5ï|ů—9 N,†rl,Ÿpô˜˜BV¡³‰Çº®iáFïÐ_J.®âq¾À°1Ô<}¨P;á0eà×eÌé·Œ‡5‘Xª^œ¡©ýšnóm£(K>vá"݇4X!‡HˆÞ!Á&™z4×`ŸÇ (Þ¨ªM=íG € ±'Q/}–/ªAFÈXÚ|}PĞ߃­—¾¯ëiÎãÔ:k‰’h¼°WqÁ;Ši¬ç¢ ë5ÀÝ¡ka±5+þ^îáÅô†žb•»òÝôè¼£ª7EÑÛ¥j°.‘J)·€ô´Ö˜t££(¡Â±´c#+³8Xð!9ž{ ¯€¶¦�è…?e„ââÜ–Lè´T]Š9í§ô<Ú2Ê.4½oÎðTÁRÊôÌÉ”ËaÇO´¤zçšCïN<Ö7© ØØß™††Ò¼—‡³d/úÁcU•Sè€Ë'eÜM óüaîxWàåãçÙ|æ¬}œPüJ›TŠ2±Ã^‚Á!Á·yƵß6¼ä´õõæÆ›b”Ä,ôâÆ[Œ§çx·v”˜Ž²tïñaá:P¬-RZ8ºuÁiãær)Ýr?ªV ©žFï´ë{Ñ—qÑ+œ‡¶r8Š\]Ãq»/žÐó^‰‰}æ÷VBë1r Ç"O”ãADÓœ¯®>â§[#$US*æDÁ0$†¯ìYÒÜôŸÎX¤®ÆæY™ò@²F7öêlÌŒÆ~*éŸom H|”ÅZä;—Êäo”™÷¶²‚çMô“©¡' ¥¥wܼ)¾&Â5�Ä ü^*w ®«ŸÛ8 ZÎ:¨•c—×Í0.ìRTîb›K6u¹û’î¥í½ç�ªcãaq“­è™óÆÖ]g“@r9dTî/'Ãi-ácÑíÐÆK(ñ}ˆM¤lÌngnÛ9o–ÅCÔÑ~ïòm«ÛฉQ«³E.‚ÃÑóFÌM| iõnwE¯éR#Ùc±Ðºb^³ I¿¢G%~„N9d/˽ˆ¦ƒŸú "efCèôx–) „ó./ÏëβˇÄg4 ˆ8a{Ð-ÔRN„Ï_*‰6“)­°fjàl8Â5‘áùãIŒ >†‡Þ±€ódfÚžæi]�Ž [ä¼:'q4ôP¥³óPS÷F‡À2äÂú=è|ïµ#4Fîå"ÝË$µî¸Î‚²7T¶r¯�¬ÇAd YU:ZÞµ£§¼í‰†I3Ý­À ±£¯Þ³3‘n3“ÞeøJ° ÉI ñî鄽öhvy»ƒõ–ÎËÇxûrÀ"9î™ªÌ <<º:áI=¼²ÐÀW1½T‰ºL"÷¢r>ÎÝ< •~ÚyIgW±y¶ÑaKe O³v�Nbp&‡!²ß‘Õ3AÛPª–'»s]¹Mð.ðj¨ð5i\4ÑÓ9.mËM±Øy ü3hP|ðų˜¦7 Z0{›`±~#¦&¶‘,bÍR*!‘?2ÊV'Cµ\bˆ.œ‘ƒ¼,-TxÄ{žw1‡ŠD|˜v¤esOÙŒŒx¸0¯±¤Yô]L’' –Bu¿FÔ”–Ïi2ôËIñÑŒ¨Vwâ"Ñ@5ƒtF#ìî.‹Í/•|¦Ö+•¶ÆÜá’-ZÞ¹5¨·5Ü“’Sø àŽE·"n!O6©']¬¾×³ïEØm2¶PZËâC)™Üy²•6’ Ë2xi›Yý䤩 áèYÐÃ÷ˆš÷/)G^ƒ>¤ÔDNêò¦¢ê.ò²FåéäêÇ¢¼*å`'á Î|íaU“tc àTûÐÊ{‚›Š¦=õWÖÍ"LjîÖJ~ÆÝŸqfN@À#Ž·¹ÝÁâì׬òeIT3zö_¸;•©&î(ôPPkh· >Mj¨I%ßÁEEŠ C);½/ŸﵡyMè­Âƒ×aT3©¹˜Rͧr¢HqV$é(@5O{øEr7Mò˜Ž?:÷ÞDÆí,íØ˜£lY¾Íª!\Z›åmÎM( zÏBÞôÄXU!œWõØz7fß+Ëâ݌Չ!Ë`,™ÌÂ[ÁžÙT‰V¶ƒ¯ÆõI&C˜p¢+<³–—úv­©µó=ˆHGb¨ ç$F÷4¼‚ž ;�m^oJ 0M½4E}WÅ3©s…R‹OñÉ ._r>×É׬ÀˆÑªZk (ŒÄ{ÈTÚ»»„Õ0 ¦M×¾}–¨©]&t/Ê/qsÜÓ†Ÿ2×)¾“Bð¥+>$t¨˜fdYC^‹´áõL ³¹Ï L¦— CT ­ù7%䲋ÔZ×FÓ*¥¡a ß;0Ë!æËºhç]¤¹®M^vÔfƒÜáë €4é'èñœbƒdÙBãNû•Ð \1pÝ¢‡«:óZ‰ëôt= @ü2€¿¤¬½,1~¡c祲4RâEíUÄûŽ+÷­_õ<:{¼‹¼2šF¹3Oè «®“¸À.· m†…dݼwïÁÄÅ*U•¾ÔM—Y”ÚÜM=Nò‰%}4ˆ®8W°*Õ`Ùž(ñÜGú‘Ù¹žÊ¬”ä6þe¥‚¨$q´)ëëiya5Ð`VfÝ}ï!yÂSM머„ýèè€X3F#á!n¿õŠç8ör ^í;ËRXÊlËÀQº£ àê*x83¤g&—.CÒ.‹]ý8èÙÅà2À*7JZX£ ^íOóq­2ÁÅ2•~š �ÞÑŠ”žjÍ‘4Ü(�(JcgÖ‹`™¦€Ë7¯wíù¼°”‰Å Q.Iü¤"÷d‰›éI×S$!+Ë*›¾!J$¾¨“ÅE£¤ò,àã7 «…ÃwèºÜ`‚'ã‚zÈÔLzÏã•‹¨±"H„úÓ¨7ï½2¾H ]—VeÍcq´'�B„o[ÁØò#U„3A]=•û…Øñk·sõð)0l«{Î ¬Å¦ñ‚¦2ºŠ>~C¼Ì ørÆĉñ0Nz˜ŽDÏ7¼-嬢¹÷ F_®FžÏºú]‰ƒÍ,4§L62…µ”ç5.–ßT3žáæY‡¾¨VÄ»íÓW·´žk% dcñw¹MTg`ø{cH¯|Ì.tÀ´¦ò5W¸ÂÊbOÝrqô0èh¶Ðº£[øUmW;µž÷h¢#A“l V ÏO©å¡º;49OžÍ¼—V‡Nì•¶uè¥Þo‘Uy`ñq ‹÷Ú"yDô¤ìè ûåø�{tz‹¡÷½¡F}hžûÄ—•H_VúŠ#óe Å¨+›+Q/ ´±“B‡ Vò+¿(‰¬íô‰Çî“öX߆ê>¶½ÃÀÚ„c*Ï‹5L<¬AusáyÏoö�êãª�<œSÃã|¢|ä4­Â`Î6“’…ÊØ@³ÉãÃõ/-íF,Ûå!¬±ª5(DRϳAÚz—™,ê ¹äR£TÏi¸­¥Hvõ8uI! ;QÜǤø´G¼t¤’âœk•³„ A9¡KKµ4ÅrÝã¸kCyt”TŠqgFÛ$ Ф±v‡°ý¼âEÄŒW[½)†®uƒ®_œ!Õ™Òè¼2òÔ¬DL)«°}R¡Olã 5{AM<¼YOd-wœá©‘A.¡öÈ)M²¾Iª7¦›*Pe2®ÆžF4¶à-Âò\ ¡‡"Zöžœ˜fû&ì²' Çø–û$1¬¸Îf^xHÝ“ž[…UU~+õüjÖ©º•.;üÀ|nO†iqD)¶jsOŸ]ú©Â*ðFÄ{dá s»°ñ$j\§Ú+ƒãõ us”K*ŸÖúÖ4™2–J¿° B§dÞ m ¶Ì’ðM@Úk6ݶSKš«×•kHÏ&Ô÷úƒžÅs¾¡™„Ê‘zp€.Êñ<Ñúy)ª¢Á-ÊAœ²tÃóg(ÓO:ütÉž³½yÄm­§oM‘؉E¸`ó1\ö“¶¥¡ 9Ú¸aee(v6°l*ÖŽgfâ0&™­@C(h¡¹Öª,fí!œNëo9ÎÛWž¢×þŒœ™ »NAûqQ½u¡ç¸÷‹ÑMæc\Ú ˜Ž,C{ó¥%Áçd)Ò› ÛêܨƒõÖ‘¶ÓÒ%0QF´áç!ÏDÛ½·“B7öкáhjíñøÃƒq‚9Énv±È|Þ7lD¯0ï&‚tiE¥áꊫKŠpöó¹×±ç‹iú V±3«SƒúE4^Y" Rîõ_^vÃK©ì&]‡{æøV@‘s…%Àµ-µ¸-=²‡ TKïÀ¥pÍN¼Ñ˜W†‰ÉmÝI°¡. zcDs‰†^/Q£VÓ[.Éd³U XSAr]+›øõ‰'ÙÁÓ*EÁÄ;Éí¤S¾E1ìÜ6|q®ó ª+5Pªå=xá'¢cIHµN|d™Dè5") m’ŒQîãt·ªâô¹Õ›M{‚[js8scc4¯oð <_¢æˆŒðÌÀrÊ㥅®ß£^ÛY q q|æ)n©tìûrÉ…¶á©p2 • ¶DÈ#” »7™™…î3¥ª²àZ†Me ‰r¾æÔšNÐýˆ^†ÅÉ39}&Û„)„š1€ôüŠE]lmT;§iΙ'¢õ9ôI¬Õ4©÷޽w °‘ÙW;á«Ùh3žÏl—óâzå!#¿v{L4-š©Ës¥ý²AÆ»¶ìÄ&]”@:™‚¯]Õ»ñÚœDE©Çr3ÌÂ#Ž^‰cŽö&ë<bO¦rÝ8Nˆ™XºSãá‘5ÜI$I”‹8ÄJÕÀ}ŠÜ«w’9ZÖúÒh’žl�hø@T>s3¦=EÜ"é7AFFÌhCJRô®Ã®n ¯Açi<`â;™:�z½ ã0¢ƒÓ�*ת?½ô//iwSã¸ïè鹫Tå²¥xn5S,×6Ìâ@' ¿KLèBN¡(ˆÕ;U°|Äo7®«ï-=à[“»žmiZJîa9}JÊâóT 8u¨ø˜M„i„¯?†èG ™¨(SÌ 6ôp¨‹I‰Åø„å/1or‡4ȦåÒPF³±Zò–¼ ÆGÐѨ¹S ,ÍETQ"Q:ƒZwf²ôÒ‘x ] 9Snªoåà…cñ“¦ÊìukŽž¬I4P}}ŽÚ´s]:þƒäH~z¯D÷½º÷ЭºKšª·}²‡Û 6ÏÊa@‚(JïC}¨DéÜICq)&*½)ô‚Ë7Œ! ØkàLJÀÉŸ‡Åu¨añªsÍEªãBÛŽ#àœ€ÌÞ8á£mǰ«²8c”B%¡=y«-¥"ïí¡ >K¼Ý4Qnxûc©âàS5‰ÑžíÙeRlù³xÕ ƒËÞ“}/ž6G”åÖÑì ¸>á9›[uªhr<îSgRGõ |Jâ‰¹Ú Ïn¹‘qá‚fZB²Î¶—e‚/‘‘OGS}{Ê‚7u…xYR)Â`ˆPýží‰I >|ꆞÇKžÝlCU6'j“¹ã�ñ‚âò¶ðTGm²Ã2Â] qš›^J¼ª¹w l Öîôe\…ZW¤…:ª¤=ÄG™So¤MZüUW¼�”c…ÛÒ£W0¯ê-­•µ(J¶ïÙµ¶Í³¾' ҔȚ  3pƒèÏÓÀ.çù<~91* šÜÏ�9 ^'=}cCXtW´0ù&* h & µŽ¾Ä|ú%æd!NCÛ0AŠË‰6ÓÄCQr!&çˆSM˜rÄyYtÖs·ƒÂoåÊJY]«­ÔÝRžç07.“>¬æmÏ8J`C}ãDù<<v9³�‹ ”Æíöås¿y€‚|JDŒbµÇôÚÌ_Yfû<•¬Jõhš?Í|&WlÎ:=RýR�*×gU�ďнH¨íØÆ Ï"%"”\øæ.B‹õâÔÎØTb‹¦úà< BŒ±Û¢He_pêÖgyLd#±1IO*“G²èŽÄªä*9Ó¢cÈe#®ù!« :AÓFc_ ®æL4<K;Dz|r¡ä=jåH†ÕH$¨šp­Ž7°€c)p’œ|žs¦Ê¾^Ò GW'Ï×Èœ2NU'ùH–qš<ßsò C«Üá*¯@Ô¾í[:Ï–bGóѵÀ‹m4àň¼ógê+~èâ;Æ83}&ëEJXU‹Ì„Ö“k¢ØÄ„ïLå#ãž´õBš¶¸5=t<9š¯”ñØ‚h�>IB‘®ñÐD3ÀÂé‘‘£ åºÚ#¢+&ŸBņ¬ˆ†< Ý+S†½)ëôÅÊv=~ê§H;…Kià\q²ç“ˆø´Maú˜I;Ã@£vébõT3¯™Hújø…UÕUºQ²Õ¼]˜ÚjÛsI|!…,Àž^R-Œj/&SøÍåhqyºW¹ÕsO ã¬�]:+ä®±IöxMÆ3ÇyS¡æb€ƒóÓ‘6}”t@Ö¯ûÖïMpA“Ò•eG ¼u§çµêGZÞ÷ÄMK—w0ì]1Wô»7mcZë‹ç´¼ó-€ï1L(Û.éârߌO«½£lù2“ùËL¦H:‡Ü…@²HâÇgp'sa:i6H@?¸‡[þ@âÉzpJvHL§a/²E*¯K Ù˜?«2b¨ó~’Sy½Ý¨Ø3 ¤(^(‹«PVv¸WŸvõsˆx5Jt¡;ŠÜ$¥™B&›yׇ6sö—šáC–­„,¤XG=q~fÙÀ6t«‡òp^á"¾´ÚäŠZsxÁ=+Ûüöœ `^,A’Ûï8ê˜Ï÷DøYÂAœR]q‹œÁæµ%ÜÒh2Q-ÕšI!©p¯%Gâ7ÙÐ{²ÀR½§Cá t·ˆæ0\,  ®êx' °äBžÝ] bôp­*_½o½¡ž©¶¹O» û­ªWöšB†žŒ(Ýrö†]½×ñ@¬M¶™›ÕÌ –:dNU·MˆI¨á»c¡]‰[ž&sz.èK¯Í×ÝéÅ+W&[?E÷±3(ŒïT£ö'~xú8¡×cÝRŸlÓ‚˜Ê¤ Jð>)s» È7ÛjOQÔ­ÛØZHæÌÉDæQQ/'wƒáLú¤XÙž*ê8ŒÇsk4œÀpã{Îòò˜wPݲÉbغJÔˆ„Çtä*ˆ)iwRÂÁMÄ ×Cȯp“\¼ícçWè;yŠŸ1ٛͼÑÕcvaÛÐÌçBOC–븛jÆcÕr²×Þ>kÑg÷Ð_䩨ôYß¡TCbÁÁII_  {/ÏÊ|Vú4ŸEHìÕ¥§y—n¼4q÷'Û7mŒ‰PW"ÂñÔ_ÑóÇóNê* ßn‚˜¬_Ï ÜNA¾×¾æ—0³Œï&Ii¡;ćü{ÒúRóu+ 4u®ïszç5Ådv˘{i „k¦uîžæÙq\yÒ#è~5ç I›9/EfU†0rv¦MHÞÒ {l”Þ ÐR¿yÉ%< û’í=îg¯ECžyªÆFÍö£<áÇïXÑt뀹ٜY­ € Š¡=Á½ÅQÿÞ˜‡´wÐDÈd¶œöç{·Ð×düĸžÐõ“Q|2µH—æ¤3Œ•݉Þ Ðà-•íõÖ@•(©Ú3¯t/I¤”C0œ:‡IJ±éÅ#bÑå-Yðìæ¿ä'K) ËœÙ:ý˜åyhGÐúIT)¦Rö¹‡Hm6<Œk« {`aÇbpO˜WàQZ …ìÚhI‘ùl¥HÜ•ÓåLéÈãÕ¸æ¹É„é¹0Có)˦ gÔÔ…“,IަXF®†l@¢Qð” VeôðW¤LQ ‰)Oœ·n‹¯äù€{³; ;v†^$–­&g<ð´;‡­BE8_ó }KDuÈ®µ§íµx¬zk®HÎ3B`^p¼Á#{8¯Ctß“÷"7ÅüÙA§r^=å÷¦PIÞPÓa¾´Ë2Û~ëûÐl^ðiÂÑ Ãwµwa-×uò”ÌÀ[bH»©öç¤{wNKõ´&éø ´‹À¥¿9#Ôd“žƒ|Vð< ä°­9léFŒ!Fà­á\‰Žy܃vWƒÖ^³çiaÕ7o«GV©/¢^YTµ'\_Z󪔧…湬 >¾%ä^"»ïÙåé«‚ÉkÌÐ å·3:¸”ºã'fΛSè`Óªfä(”›ÏÑU ¨=Ÿ=$ürSáó…Ž«ÂeÖ…"'m†©<+ó¸Ióu޶Ö˜³…�Á˜“ !µ\)㪦L®OF„ôÞëÙô«á©6ˆUÿnéx‘Ó#ùZŽ„«D Pü„ÕÞt#=:Ý@ߺÖìUÛܦ‰Ûm®Û@XÔÈ3¯7Ë>ølŽœá/9M%Ù—d—_6êƒV©|~r!‹NìoÖÝíàD³æ„4¥bׂ’ä=†¸wC=üÆúJXƒ3jÌæ»Vë.© æ`áEwµ¾q¸7*rRïµ×šy�µsÍó©®«“αe½g/X‰š TÔÕìeîÚzkº[N=~´ZŒõ=Z¦a ?a˜å•ˆWú8¯ïáC�3dõv,X20¬¥Ux+$ê”yhÔ;›3HÏ£\g”%¦9 Ë#õÙé·8Æ\ ¶£åËAÃà­ŽZbÉÓ7Ø–Íq HÕÑDƒÚfª©$$(ñÜ”äZ,À¯ÔòµY±¾�äÜÝ <~+`Íž¢vO+X7ñaŒ©QuäèI—chŸÍlŠìLðj‹¡ŒS@Ù,€•á:”ÊyOß¶½ïæÖ4A¹ QÕè„qÌéZ¹ß$ËÍ-Ý^íyÆó§‡£­!.òܺ ´bTGW;’PŒ3”foë²²[×½ÏΈ»¸è \iôõuŽ;Lˆ®­<ÇcõY­œ|Aïè :×aHT±‚`c Ïá2Ó‘ÂC¯wî,@«‚Ü´·Û–ŽºN‚fjuF£¢J8ëÔœ©™ã„Ûû–îò!!E„HœÄZ.Èn¢o¼Æ;žXZÎ펤›gü)§É©¤§Þè©‘*(‘ѬµðFBEÃ&ûÍšEùÏ£h&\8 ‘DmCiÜÆ%ê}[ÊR^|¤ïTaóy8îÖh{¿|jäRؾ+Ìi=Hh¶8Ñ„JPò´¦Ff=Hî g[¯T‰³´÷Q8¾Ù€Á£¹òHt$èw úD†ä/;É`WyùñD_z:‰fº†ÄèÄÂ#ItT3Í@kõëºö®èêa²¥?ÛÇy¤Æ¯½g“%—\ÄÀ|œL–A]¹:õÐ;ó½Ðrq*`d'SDDkv#Їœ ¦¶õ&F$ù%¾Mw²îíÜNíjW./“ÀB©Z¨Cˆ×ƒÒÒÈÅõ dŸõ„™P_wbcòch / O}¯³` ]H6¸ß¢ÀnyåÓ~Ù¼¾y); i!½Kéå»ã[yÂJœ]T#ñºêÉ«¡³ÎRðÉÇ ØÈØxbaÞr\áùü5'«?xÈ/0Fª „xoh{²íáÐè%gÇâ<xV&e)}çt¾“vÔëì ºMg­TS¸ôfûE"$¯6HØ(¶çn�éµfÑé«7N€¶0q›%|Bè{ô^{¼PÑhŠSÇ,Î.Þ[;KVzŠæKøìpåN^¾õ«šñ,{¶Ò¦T<<*5s-d 8‰ùˆPÐÄAH0tÅ[d~ÕFNzo2 ]cvØf®¬&b-bWáæu?¬áz!:y:g1œ²üØø„t:ÙÆúelA€ñnŒEò¬åJ²¢Œ‡^µÂ 7¯õÌ4˜JÛ­µÞ0Æ{‚M#Îü|ž[´Àð[í"1ÓbrŒ–Ù¶.°zåËNÓO;S¯^s9´µz+ ªÉ*o‰f\?{Ä[­læ$ xqdk¬ïe ^Jxërþ2~BÜBÛhîlxAåýìèYH'ƈÄ0kg¡võô”Å%iïšÕq–Àk©à&Í1©·Ùz#Óš\ðÒ×oä…{o×Q®„u„Åß“§ ¥–ÛÀšA@Te[HY‚•ØÄ6Û ÝèN†2­ˆÊ…ôËKA¤¥’ Éñ…{›=Ę”G\…T“z’}ér|®}gRk)¿D;y@¿È.u!Þ| 3’Ü+<ö@3—ÕÔ ¤3ä˜Yº¼i¿¥¡=ZM¹Ù£W'ÈlT r‹e)“¯˜}aw<YK$Àˆ‰aÁKž£ÍÓPž‚Ì‘r6µ¡ÌAÙêù�³B£æóФì‡*ÛxovØJ0¨ý4“V.kÍ&8=Ÿ$³øÎ‰/£¾¦ªhV 'yõ”‚tÐÎåùÞ^!ŒÆª³V¯­%<‹P^ìï" œx)‰#rR¶·“¢®„ݼa$’ b±õ¬(é(É«0RÖ8XÕS}ú”^úpÇDÓP¶ÚÇÌ3²ã¡ÌJ5?½pG½v­°wœ—ïi>ê™Ì»“‰xA*Dc™Ì£tšw¶&žóÞä¾V¦‡îÁM“Ç/çèÂV^%»Š)0I¤W6“z¼wXa5lW.$‡œÏËè¾ÜŠibó^ŽÞa’}Zøê­`6®5(í#Ïd†sÛum¦pKçZìV•öP_â3‘Õ®tàƒM}ë&5E¡:Lïê85ÚåiÏUO>=%ÌôŠ·â%Ù2[h6š?)ë1ä;_z:éé™F×ëIZP¯Û!vãÑtÚ!dÓö8õCa5Ç&¾As”†0ÇÙ—S%̯ÛÃVÝ{óˆ03ÔQŸÏ‚äb=¢x~¿@ ¿Ûžâ&U2"‰A ŸÅW°{Û4`ì<Q„ùÜ`)3´ 3i £ À!2pvQïïé5_FT°@7ÔñákÖæ2æó3œ%Å F 2Uñ7<Ü#ö֢ŴñHüqÎËÓ¸—0÷RPÁÉ5îõ\ fÀ›�B“=Š„¢ÈÝ ÎqIÒµx!Uñ̈5}$h:gù˜Y"Q¶›¢ìÆïÊÁˆ&H”ì«W”à µ’ꪢ÷Š%òJr³—}å‰ô[Ëçv1Ý‘"fL¹]Êwkßâ%x׌g6«èù5jê(øËШÑ-!6 ?lxšÆohÊØa6›Èïæò¢ú``äL™äÎóÌ<'Rß–ð)- Ú&÷eÉÊ`ŠRiñ×Õ oÒ9_÷&÷Ü‘²¼uuÍäÌ6kx4„ïÊ*- ,mžá‰Þܬ‚‘³÷äÃè̶]Ö÷”‰Çxߣ—+/BëÉŠ£ p¼\x“ÛÒ `ر‡=5k«÷N÷‘¤‹<€U‰™ê˜ -òÄ]ÀK|©tFXÝb–ÚïéKx;aú74žEå«Òª‹ Ã{+s93uPõh*¶GÅ&ÉõÝú±÷Râ“ãëdÚ௹³03&(³‹ž÷Ûƒ”ZQ×}1äÀ³c ,v·ìQ¶Â.È·…~½„G*Ó#z�ŽBžÄ×i²¡ó°sBãD ‰Œ£/¼çq�9y#×=¡Ä’Úh•39z´_~}ù)ïý Ð�kø¼gÓáewf£·(g4%Ú¤µ†ºŸŠƒ˜¼\ïyoáöÀ;u‡Å}x¡Þ27<z"sØòP”ÇŽý‰É{Ì%Õ±GBÊÞœœS{îËp³xê¡j¸ÁÖ-´TÓÃú& ¡#(|’ˆJ’Y ªa˜}éÏ 4B2�Å7åFøtx)*hó­¡.†Îr6 w‚îqgÍUìX„°$¬¼}”•´ižÚÖOƒí,mà¼u|Hæ]]/’tD¡†é<wJ»T¹ägª좡#:ó •߯<…%Qõ’²jëY|¥æFï¦YÂK¡´0ŠÍ+#ŽI<{‚øHGÄm×çNñÍÈ[ð×EI@ñ`ù‰&Îëô k ï&óP«äx¥&CÇÔÇÇFe oî颔;â>ëEĦTïªòÎè:VÂÈfŸ–Æë¿}ƹë³×*O®Ý¸Ì·av–ŒkAyH¼¡^$=r}u^¶5p¶ÔïŠÒvR`²hö/ýdÕUÈB›6úĵ „ãôìÕ{ÆÉc­åÎÞÕE\‘t²9½ä6°ç™j=¤C[!¼ÇŒ„s;â‰Æ¸÷ž¬çÔ£w2ã;ÒÞ\ŠmÌ~5þ†î%Y%+…xdú33ÄnÈ3ÝE¦Ý=ì�nè«"·Êº,OrLëÁâS5à'ЦHi¬ CU³ˆù¬32»+ð8³}žSJ¢.t[1)¨ÜËU jÁªª°ãã²@˜6`bÐS\Ù+]àÍlÓK[×Ö})Zþ^ ÕÌ9ò")ñ…MF™»½ˆ²›¾B~„㉪þ§eÓÛžÔ)˜.ˆ‹œÃø$¿ƒA�¾Me‰(OÅ’îíXµÜÑ`6–hŸ|ƒÛÚÖÖNiL^Qâ|©¶§¾Ô�WµÃŠOUWP}’õ^ÈY¾~þ¨^á㺎®Ì¡„[:ælUÇ-†¬ÀÆrº5Àc}óZŽª¼5í^±˜f¾’C„)Ñ;36oÒ´†¨M«Þ×þÞÉóý Q l/ÂÚ•ï.àU4S¤d í“–¶Ñu~cOH¥¥ÌÁ¿Ý`­»‡ÇR¢¤"Ò7t"¬’w!Ê–Œ&1ËÎ ¢ÌAôôÆ vÞ™w W€>íÝ6wÍœÚìT},óJªzªp÷tdt³nà¡ 87Ý[.ÕÑ)=ÃAJ6 ÐÔ:ÖB�èÙ€ÕJ4DFÑÓ̾˜Éœå ÑÀ}zïøyTêã@h&Dt™ˆ.‘·tz r1¾�W*^sœØÕAñ8uZGe™º˜.`PC•ÎaTŸ+{ ­ >XН4 ÁEëP x;+O»S¶ …Ð6–Mt¬ÄºkÜ’¯Âv=Á›c”0ÉAÐqž!­·÷ø‘êsÑâa={(‡; ÒÕÍmÞÒÐÃ…q½#,›�K&”DÆ,³­#Poìe cGfkÉ[Ÿn¦á@Î{!Π¾{éH¯ô5E Uà[ºdº³œc|DVælˆù_mjf†MF’$Ä.Y²Þfó6¾â·±¤xN┌тB$¤º†·C€ÚÑ?¾G ¯Vßk50ZïX"S£—k'BsL©žVnÒciïJ\É]4ƒ$Ξ=bj_%\;Ôµ<±{ò�0HÅAÃh‡,¤"é^¸šÖ=;Úó~$®o$bnœÇÇlðQÿBöeÁ‚°½(€žÒt«Aê\ .á.YXm&y Më¶ x²M¼ÙEN´Ù4dDÓ®Ñ4^%îÝnÈ™ìŽpbaÓ:éÕž¾œç@lÃPKß2ˆ÷ªßÉ T–4)ó„ Îë—Þ(¼Ë¾ˆ^ƒÌÔÀ¯-a*%[ GžBæJ¨üÅ(SîñT¦á.¼‹bÖº,{=— �Õ:+däa„”Ì4æ¥H¾•æ³ZÕ*Æ{Ë;svàNz^шú z½šF¦Q·„׫±ÀÔêƒx ›YÇáð±= ªnÝTÌ”'ÇGþfêFŠÑð;3}Œ†NÑj k° ,T7Ú`1¹ª_3¿¤>¶íb´ú°±§æ½y›$/.r·3œ©^‡\bya¿Az+­ùB YžÕ€GYæÁE.ð ø=eK¡,<Âbñ `‡qËz*i!PpäýöÝé+„y}cœÇbÆó.'|R†FñÕs]51B,7ÇÜ´=¡$Y$åÊÕ‰yoµ€”‡™O¹û̳Ù2ǧ%’!n̦¡H Ó:¥ {®/?  h(¬ç2kLÃO¢MUÊÕÛß4 ,?ßà͇ÄÓàðDr%ZØšÌeDZ‡=_ ¬!x|¦ ÛƒÁ§ä®^ ³ôpR5Ëciw’šá¼ ÃÆU\†ð›J@ÚæÝýl/ÓÂ_˘!ÁãG>¸*W:\¯ÆÝ­BöÊ^°®‡f /ž†¹4Rsz>£NáÒó½z TîÏ“t<�NãÅ[Ñ¡œJØ$];}P©ƒÑ¬³¯•Ì®9ðð–ì à;ÎG5Ë/‚ n 6uûÉ'£¨ß³(]KH1„®¾§+ïz®}°MÆp²cL ßz±™Mî̽©…:dú0PŠãŒß$탄¨šÂªz’åB{¯"·µ }ºuc1+óå(eCjˬ©ÌR?C,ÓØw³Ìi ¨wç”Ízé‡6¯(´4tßlŠ<àÙ»/YšR°úÑ ˆ¨@ý©,h¼UžZ5‘|8“.é˜X)[Ø¥/¸¬0“ršÊo—qîžÒ ë~ÃEµUq÷ØŽZ¯ñÑ“Œv›³®à&|[ÂNæ©Xаƒñj+Œ©4 ÃÌÜd<ñ”¬¤÷©EêT·—¼1“µ—‚Æqýäí®Ag1Ÿ5íæCìã<tß cˆf$¼Kƒkò}¯D+«XP„k~@¨—Xá¹Ï%Ø Ÿ7[–ÜU¼IœT¦=N]“ ¡õìzáOËÓ‚Vï½"ž¤n^& ÝÊCBQ¬y/u,æTÐê�®ß‹ªð‰LX"}…¦"kE:&; ü amÀàEù>Q&18e±óÇœS3‚äg|‘寅¦Ð 02¡ÈJ×B°÷ÔJŒDžô–l½|QbKóV»Êëvá c,°É½nckÕ@ÍüV)r¨+‚ ž Ð=H‚+Nv¢†aQ»Ô4Ý Œ—Öz›öòÕ1èÁ­BÕ‚Ž·¡TØ>Ù—¾DP®MÍZÑŠ»Õ 6É¥Ü9Ä–jˆt*왯®¹®#יŰk­Ë_»?Šçixó²µ|9·톜ý&D|ZfŠ»3üå]>ÆM i#å{bOОgtÀ«“·ïŽŸg4¨Èöó“ŠÉ²ä~•.”” ñÚ!"½XPÚâŽ~BJü)•NY︪lmÌ8P¡3iM¦µNFθǣž»ÊÄFFŠêž1¸§±WÈA..>T8(2ȳtSê^@FÎ ‚N K&ô¸;:Èõ5g©Þî%ì•“ºcÅyÅŠ5 sä¾Ï `±+lμ!]÷üxE76*ï“åªËŽ£ýEi)Ao&?[Ôt©5ÅtÑ—í0Ñ >[ɨôŽó™¿ŽU+'¨dN‡Ã¼}7þÄ'îµ¹Ôxšu(½ÍC< Q“}IW!8 0 �êî 5d0¯Œ^­ X”cï÷VSp†Õn•¤ ¢ ò¼ÊÛÕ%“œ¶êVÞ2·èGã BŒæ:ýº±†yJ¹ªh£uñZS8í±’ô8biÕÁ{iOw,/Ì0`̬‘XeQ‘¯StÊPø¢Yô$”FÁ#Æz,Hæp1›v{¢ÀàlŸC™€Ç=xåÊ#½ÀÑ"h¶ ™_ øÎîdë µäGˆ„»DdͶOì2¨Œñ²^@ˆuO¼gÅT¾Ž7±×AŒ7C\9ÐjF„ZÝ]AM›õò!õ¡Ît É½s}ü–€ÓTìQð¬nk•‰Z< e¹ {ýì ?z‹B@Œ‚Fc÷FAázžLb½¢+¾\ÂÖÈÄÀÀJ&³=C`¹#µUµi¸$Ѻ'Y—  bχši³›:⥔æ\ä4™®Åv쎢äqu^eô6¿yÏ×õ©k„n„9ØŽÚ¬{#Ú0ôuïMdðëëÐkUÙ¬6X%|“ÏzlK/˜RSü”÷xE ’ÌÊØt—ÏëeÕÑMoœ8D¼ä -’·‰X<»¯–ÐÛœ@GP%úISR¼Iú¤ôÑ¥SQÔÓY© J¹ïÕ²#jRl¡ï X¬ÊIé„$CÏ«züT‚=ðë¶#%!Ç:›%q‡PMzrЂ"M'ÝGMÈ´¡IkúÊ@]{˜°dÊ‘&{ZGžÜ¬ˆoð‘Ö[Y©ÁÝTFðÕÀ{ä,ÎuG¦bnXЖÎqœ/›ˆx`ÖŠPÊ(ŸI€%B29o¬=H‚®W|ûB»Ì'fRÓ×1ËSߨ‡¥d:åGÜ w\O^×z޵¯`–[‰“,BQD"x†–0îÌ�œõÕ³â,Í>@H�º©ÐÄ…éÐ>÷ÛaÐX€ßöS¹ldK5œÌe¼ç¼¸ªÈ]JÍS(lOž¾±¶2|¡c;­Sw8Å`  ØŸT²˜¨ÓŠXŽ®Tä´Û4Ùf¿Wï¶—'Š›ŠTmuâ!îcx6âuj}Ï“³˜=“§¨mÕüT³Xj°Ä1O×Wß5ó œÛè*¤9„%{h-ˆ  €Mt¥"L‚·÷cZ®žìm=¨ª~IlãL‚°êWhæ ü”u…èuç³7Ùú é{p¤— {Èå}™J\ŸQC4<{wcû”}Î'í2bâhTÑXíè@ã\rvEž @ F ykÀn`Pº{v5bímR9®ß<‡.W‹ÒqØg]ûÈ0÷ô=N¯°IZQ9€©(¼qxÔ'Æ$ºæ€u!+ÂCâh í 1mÞ£§øâv³%Øè!º*9Ë ƒ{í,´,\û†Ça#Þ=ZÜ;7ó|÷ÆÜÔ—Nuá5±_ItSïHÏê< Il^òqn¥žñ\Ú|bËé÷˜è]¡ç'¦ _˜Æ{<«ÐV“ ®˜úOy™ÅOî‚Z æ�t½…-üµ v†¹šdVBË‹uÆjv“þ… A±p+›Ï'ò™ãÒ”:0-àö ¥rŠ1Û¶]×jÚ9‰ËÃÛ%¢7B󬸎I™\ñ“X8„QBv–€§)AcùõkƧ¸ý§æ@¯Y¦Ã…ñ›pŽ‘=¶ð„¶6·Ïš|ã–ŠZ£¸ÜÉA”�<V襣Èì³mß[õ%'¾—ÕïïèLøÝMlÕ€’ìµûYU—9Š…¹©jøŒ<¨LVÌ ŽÃÛxR·ÏKÓy‡~íVØd/¾fô­~ðÐ2d/oQoÙ>ñë‡ù" �)N”= ß›JÄ¡‚{I"\ÇW„ Îf4¼oø­È¡{——…-ƒ•3ØÝì¬ílÙŽæ˜/„ÿÜ'&ín8 ÷PÁ4e°Î1qç9Ñ4‘xÜüÒiD`ü&E ÷“åƒSx¸€ö’Ö'#ý&Î$`;åžÛJVw4$lŠÕ…²Ý» WùµŸ7ÊŽöáÅ6¥r)j¾–ÕWºÙ{º”̈¤qœ³~Vd´Y‚7ùt¢Ê}ÚCÜ·`lÔk«Þ£!j&†“™'Ü­¦}Ë*1OؘrR<­çÒéÌÛYŸ"¸ 2Ú3“cnWÀ5cr˜`<MÝr­çìF©Õ0/ AZœ«ûm蛣é„zQNNï$™¯b˜‘²²ÒÌå:õI:W™Øâs‡'{áz/Íp9ØUš1ä£s5*/9¨öGçòš@‡N×ÞTM“jLª©j°í t:u'Ð+É×ì’1„Jo<ßø7§þÅéºg«j¼LyÒ[«Ü–Öö» ¿g®ï…‡¥ô x(n€ªËfƯûjµ˜ÉÇÞ/“žÜ­£’â³CËí;Å2šÚ¥i‚Pt‡¾%ǹ,Ù}^„îÈ‹ feyDr|ø: 4¨²-j%AÍn½ÚŸ`\½Ç6ÇoD»Á*JvþõáNé»D§ÔÉœ\ѯ¶à5V3k.zÛNCåg\®gaÂé5L•¯&k¡9QñŒ•‡z~AtâÕ®‰Þî´ð¦%gyƒ‰•ÕGµÚM#IÁ]ð…?™79Q8%¼šô<‰é…ÝécˆFÖë¥mäfÇÑÇ':x†åenÑ+s€öÁ>áeµ¾œ®Öuº ËÁÓžèeÚ=+ }ç o0¶Ë}Ê1Y®ñ)… �\Kßœ€òð#¾Ó!F–'+{ÑE¤3_wßµCëñ¡A¾™yÀƒ#{Ù'¨¼°iáb4UïÅ;}i ª9ê}$y0O`™,e*êõê‹ZšòlÍÂ-Ú§¤N£;0TÎ]ä%z˜ÇÇspyAKrÆâ袼#¦—Ô'jõ=|‚ؤ£–5Rø êNŽ_KDæ�ÄÃM;òt„¬õŽwÁX\Ÿ…2Æã½H%x…\U䎨ö´^>ì’wGº•ÏL‰’ÊÔ''³-[ߌ÷#¦Ç[VÊ OÍO)̹µïñB–ÑèÆ#ðÌ#ll¥Š§BÚ­56Ëǽv:";Äšª˜uµ¶¼€Tž]—-K%‚¿ÃÑ€êI”Bv›½:‰éÆ”ÔzsmþŠ‰Ø€ÒN—U‹—}R³f]Ì_iÚ•2ë<º‡ :Ú:ß7ð€„¥¼Qß'¨¢_ Þ`,`úÛÒmG¨`qêò«Kº®*yê|eìC¤|@0¯B¡ GËû±7•pÆõ¦Ñ{Д™‘ÄÛS�ÍO³Ú€žb:U¹“—ËÓ(o£ípº1ÔçM {ɪý^?~é/ Ä^Dê˵¸Ë2ÚûVBí6�XCSTßqgZ�hRo™Ó˜ŒúŸO~EŒ F"-): Uº¹7Ñ̃èí™öÊë<eòL8МnßjFâÆTdξzà®öÂjØËc7ïi¿­é°z²ÛMMŒÁØk@ ¹¡´îxN¹äL‹i•ó^@ÑpÉRÝsÛ9혷¥ÂozŸ‹]–\*á<ÊL(¬E`¡äå!¢(Xbó%—e$zèÛɳê°O8E�Ó1‡ô-QIj,A¾“'ÁÂPT ý@,­¾×Šz:5磻ñ´×·Ö«¬ª}Œ`Ûýž<½„+¥ç€möT]žsM¼8@ô~¢½»å½êkí’°\ù²¥ÚŠpµDíð]âHòTÈÀ×GL\Voö^Ñãç^öȒמ•Tdá.’Np´>`‚îG;½D“”ž†ƒ=&޾\ôl¸¦$y½fCŽOƒïZµ`æåKç Ôv§-yÙkô÷DÄC"A«æˆ'Bйö,Ïæ„¿Ž¥˜¢á|-ÍÐf&›Ò¡§“¹xŠÌß³�c@»+=ú©æz¤LÆ4……¸ˆÕR#Ê´ìÄ™—EÕþ^=4ãôl1¯»Gøp ¹è|n§˜Ùûñ>Æ!½RÎXÙp9Ô|âbË\‘ÎÊ@.ž´ÓÐ[–zup°¥cüj’«¢c•pŒßËÕx}ÝX†»ý Þ^Á«©I}uhý:³†ÁÁ»6i4¬¿gTå/R%r JÏêµexäù#N†ë$WÁ><ÖÜçoOÇ™QÜ2±ûí«s_LJ½Š,}åaoBq]JÞ[ˆQ’Ë'©Æ˜Œ’Ö& ¬Iºnñ’šw+`uHúîðs Ah¤jzK3ÅgˆnéºSXOäá{ú’f#´<HÙà)¸1`÷½Ns”º×¡ªkD EŶÏ[#¡B ®¥±“‚TÔ«—Ÿ¬\ØK‘b+²¿b9As²é„w÷rÕÀýÙˆ’ Rv>³µ‡O9™ÚJ½\ÍiPò'£|uo7¯Æ”™`g„9/Ù≜Vk¤;ilaqËêÒñ»çP)óø½ç·ö&m#3´9‘3 BKrÄ$ˆ9#Ò¯V±l©3îÌ3‹t–Àe^Gè&vƒbª^9PxqOÉJpªõõùp6ä¼ð·Ýó2 ]Z<‹ˆXߣ7ræJAs·`«`�Cíøi&.cN[¿�yÀ²ûä¹uÎí3Æ·gÁ^jçâ!8€iûæÅV60læq+™©èÞ"<Þu¥é&65šº‹3r5ðw{ïÑéƒÇެØ9MàÑïÑE˜÷Ö.­—”'¦;zÊÛèˆ~&QÀ^š>Ì>¬S–Èd‰'WN«‡„ãŽAæiÑ{d­zQܶT Aäç"/úeŒÇÝ #‚Èé½¾ gf9«… ÐÓ ‚]È{¤Ç§0^nmO ÁBë½RÅ<Äó™™BJ¤ÂÐ~ÊñD-€‡‰'5†Ç^!pIG4�¥*¨¡o6u§Öê#O™ÓPŸ’× s¥~(iç •wÄþN'9¶Ò­zœ¸h@ô½m)TÔ`§³È‡ÏJÛ€Ú”±h6Âí„Ã>Q5úBÕl×+îQH=% /£‚Ä¢y8½åøÂCŸˆ?¸Çõê‘‹¢<<‹²HÝAWe ›FÓñ°}©]˜–jÏ߇¡SÚJî<_îÐÁ÷ŠÌ)Ðm_ <)Y,Ácß±åa ¹ Ÿv«hT"E®»7«¾ÏhÖ0ž‹u ZÏdNˆ‡`z·þŪÕ)ãQ³,šªÚ?¯Wàs( ¢ ik·q²£Ú &æ�ÒÅ0«tµ ˆ7’Æ�'¥_0…I³y¯¨¨Ç>}› ï [[^ øB•¥d¥ªB8äó«³~59xo‹ j+P€¸絿„tgx­™l3ÀIoz¯ç Ùò†¢9%¬¸d®VGÙjöTÕ]t›ž‰¹÷nô¥<ìçÀjÏý†P^¥g7åè=Q5’G¨óW饱ûå°æ¨Ê²<Èržá¾å¦.oÃE`b–•»©ÅžË‰“‚wl4i©©?ŠWxþбjÌ„£Åô¨¶|…ëmK-Ýf{ÏcèCà‚䘸bç’çZ÷ÁŠœ¥3áÊ¢V kòÐÙñ´º=]ˆ; GA¿ówÄ#¸r1ñ�â¹ljXG‡ç *ZýÕ¥ñÀöxèØ—‹«ÀÐۙnjB[%“ÉVw¾/8¾°,¢‡s¸D-ªÏ‘ÖEa5v™ÈÄ×Ótá ª¬ £•^I«OtÇ[T“Ÿ1 TåQ>OØS=^NmºûCÎ!Ák±+ܬ¢¬‡\ÄÛóŒE5<à9>6÷{Ì,Ï$»skƒÚ„�n<cß˧dDGDÞ|σØ@$ÏSU�Jß<íÁ˜BŒ ±¡R-hs'Æ.3 ™íÒ‡L™Ö)ä¬KpŒøh£ ¾YuøbµÌp¤÷d03Þ (¿1tJÚƒôuž@G:‚ÂC¶Ú³Gu/öÔúÙ﫽‡ Íá¦cKü½H5«P ô3\‹wda¹ù8TœTæY•Ȧ…^ò‰Þ¸‡GQFñ#”œPkC*âx4 B¨‘Œ!†vY+ÆdLßM…OpÌ+¸M¡«ú V©‡m”!›œ¥[WT$€‡¼ÍHô镺«Ì•ây7ÀiÔº®h>Ó|fÂì Ç\¯ØÛS´5I„5ÓÄ^SLVFkï:å{Nl »9±–#ð”N9²÷Èæ¼f³€B%zÕ¿· ˆ…‘2„o/Œ`Õ=º¦­[� šÖpfY¨É¹œi‹ß[£×JTèAMłϑ)'öŘáªÛ«…ð.oìgüéFC®¤2M8´U;¿KÓR+u7šz-½G¦YlwÊgöJƶ„Ÿj5À»ù‘ÏÒ\È{5˜=·íüBÔ‘À…ß²'ÞL¡#In ˜‹ GîLÙRøŒ÷ƒÈÂÆ=šgLGvM&€VÊÄ¢ïÚöõ17†ù[«¨JÔS¤%߈¡E—™Lzr«²Ë0’ÎbêÏhF W_p^rK<ó)¹Ýœ]ÝÇ4�,áfqà[‘ô°º'!±m0²Q@&¶½#ÆÁˆØeÈ”—žl§ñl(S‡r¬Öú½7™ïQq‹¦Ý34;v6†Z3Ú‚7ÀëTÄn™*IË9�'ò@¡5C̆0µ_ÙÉA•Xá:ä^^.‹G$~ÏoË&",¥Ex*Ÿò jßãzv}’W)Z;â«ÙCF#ôeîD¼LlNzlãˆ1ÏQ]³ ˜0@ºóVÿ„õÑ„Td¥;ê¬è๸€Ôx##ñéF¢¾’¤œ92°ýÜaOÀ�æÉ2uCtÖÊŠHÑ·« ǧDæÐöð%†ð¹1”îÒ¼3<SŸa´vªy >|DT¼S(ÌVï ØŒÀ½,&¶–ÙHÏ¥ôÙÞÜWníd'^[ÏÔ¸õ|ŸCÿEëðøE@vµ)Õ½:~N»æ¬:Os×׿IX{öäF*±�A¥L<]§¦ö±sEt&¿—•-‹'Ç—$›ï¶øº\ «ìTÕ]ŒÓônÊp¾=±ÈG Ù+½‚õ ›ÈGÚ˜©¡[˜‹[´½QFr­M.y>I¾;ñJ PÊaáÕ´ñF ¹ó˪¸ÙzBô kâà‚·¤ã‰’„<X_�……-0Á]:éë&X¸òA’›0šÆ&y#OúqÝ o5{©ß»TÃuÛ»eàÑ—ðvƒL¢•r&‰¥:ˆGœbADÍ{fE(N}JTFX‡öé £MÙ¼ìºÉl%JQPÄ»ð$%¯lä]c•ÆŽÆ [t™`‹ Zœçå5ÁˆHq|}Ð]™šÊ 5 I[Þžv>A¢óô ŽÕ¬÷ ™Ÿ’:8xxv4¼&ëÝ@å­ŠæÂB,r¶£–'óÎ ïʱùÙäVCX>ô¦ÐÃ;v1Z®¬Í §B³âr¨¹¦‹¸–’  ³Wä~²E;8\O•qÞÌìÐ8©7B�s9²> >ˆCÓÝ2¥XÍxºP½äfíBÒÇáï‘Ùâ+İÀa•‹ÛÊ’à—³¢'ëIî–=¤M«�Œ#1@iìÓºL #çggJÐ °§ÎËÇß3q–ŠâzÎt 3( õIkè­ÀŒ°Á)ÙĹô@ð…§f­ñò¤D•žËjq¬'žuÌU +5õPݬ—òá4ø;ć^¢)4ðʱ³e·)¶Ö�˜—¢¨¹N¾Ññ~Â[š­J-[y UòTŠY˜ÇAgVŽÝFž½¶ jŠØPײ'\k_bñ‡RZ¢f¤“-Vïˆ&Ý^+  &Ì_¸š%¢ØÜ<H‹~<Ê݆ԱØiÚ)¢2àŠóž)Y$ɸd‚b¹iº@ñkÙ4Ö·OJUã=Ídkq‰­;§÷^Ã3Æš‚xðLú1™unùëòP™D:…TÖ]¡gdöf_¾™]R]‚…l`+RX(ãÃÇ%Y¾»ËŽçnàÖp®/z5Æ¥ çCäçÛëk«} ƒø˜Ì¤!7óÆÏ‹¦Û;SáUû]Y’Ó¥R`ÕË|vÏúÂÀô‘[È£îx­'Íz©£ôdì~y˜@àËcg2éÖ'ýÎõƒB‘%¡¡Ú¦PË õ7‡äzáG2ºa4­C-y˜(FÕòô=%Ì÷nÉÙ;£nÛfŸ‰ñëhåb¯ ¿|T:Aµ×fvZú0jFèaõ¦´ÐT¬Qµáh7öš›Ð ûò"ÂY^哼:o~û˜¥Tà@;° ©<ݪɭ7„ñ¢ˆÝY#_Ó°Æ—< €ßxX´!8¡Ú–MO%í j Üt—ÝK{1œâ‘Îæ°=ã\õx„w¥w¨"‹ì¢fëQ,¶+=ð~aµÛʱ<¦ô"Mª½Ž¼0½«äì­¼Å(w:p‘,ÜxÃrAñ¼U›qÜÔÔõä„sÃm$ÆÞ”#³?¾)š£Ò‡mj˜œå�ÑáÉçle˜õô©a¦xeJ"–Þú®ü…«—ãFåÌé!OHF˜qÇ⛲”‹kCEåªìi…q'EFäç¹ ¢ýz.ÌÌýtÑÑgE€ÔE.°Ñà zÅÚ:Rå"ØÂܬ¾X†§}ËK$õŠHŠnø.y`e G¿ÉÛ29k èR'êP4mÖOŠC|ö® S÷µ¡øýÅ+ÃÃ2kJ÷¬È‡ùÄT¨d^l2ÝžÔ @ѱHl'M! +Ô¨vp#)€TÃów.zý,Ë›}e–ÌDÜCãfž7¼ ÉgJwìs¹<Ê\ì,Ó•ˆ,à¼ZöP¯KŒé>’L×ÇŽUN›G]kÃÜgŸ]‰¥vµZw¿8˜]X8$¼øðÎ<\}&}µÃ u0ªg@˜A–C5¯Í—$tºyù®ÅÎÞÃÚ‘ê#ŽvòGÖØ*5‰ÓÑl¤¬Š'W|[b02Ïìí{CÓb†;úp9[Ò©ž“Ÿy%<Ò:ã嬔t$+@E2‰Æ6:ywOuÍ-CB¿Üò Q)¬ñ±ó)¾ä6=9g¢Õ&†÷¢ßÜúðà[œ2–qBª¾¥G™Ò‚QÛ}Êõ\Âä-Ý _l®šâè(À&HäêðhSƒKtŽ÷^•½(~i½â¾|þøAlˆ‹î�Á–ˆλ®{óP“ÓK÷å k €0ë YÎÜ')âØî̪ˆt×€ä§i%³ãZ1ÆÀá•Ñ<ô1¿µ©ÎQV»ñN)½«[Ø7@¥ƒo¨¢ë�4±ûuêúºúÍ®yà%RAˆ+bY K°Ê@”¦ÕsŸ¨Ó‚Š`×ôŽé"~Øí{øÜ  %D AfØJG¸Ûx`x§ßœz,ÄØslúäé‹×KÝâIUÕ$"pd-Œ”GMÛQ|‡³‡k×øúE$û2f7¥x D)…>ö{¡$¯Äº`(°†œÌžŠ–.Œ×&ö$8ç³çŽšÎÀ.×÷®ؙ٥Üf³kHS›†x›¿+Ñ~J]éu/·W¦oz]Eóùª1õÂ5Ǧoß{¡Hë6Ö2šTþöa ¦qÙ *䥛à%öµ+3yz¥ëÞ)à ÚÚsþ*PéxMjlÍéaÊh͢(qãfãW¤~ñd—¸Fù%äËÚ%m~Q×ö6ù±eÕ¦ÛCÌ2tí¥.ÓÃWE½—ÜW:H½YÃ…C®ˆ Ú¹À{†kõlݱ©<œÔ{Y†$óÔùK¦ÀQ]×ù-^‘±”t‰wAº¶_ò 7ñJT Ó·î±\ H(M ¬ôc´ªy­YwA¼¥ÕƧ3PêØÑÖœ ;<h}®°DM‘”ì¢I\Ó  £!vÚ%'æ¨ Î+uyÑGStÚ/¹DÌEЄ<µ¯�´„~¸†<×3Aö07nIΗÆÇ“ÌRSÂ*Ý`Nè(!Ps§À B_HGk n-]gTÌ…W­ ¥L“øŠ¤×sá: ·wàRòl– FïSöª”„çƒØnÅW1ױ݉µó†ÝI ˆðÑéå´Q—‘E|ò.´à5—øÃ«¨†fÄÁ€xñJØ—D¡ì’&†?owÅ–ËÄØZÓÌ�>ô«Åháȃ*¬ ŸÇ¯À©KdJ05²dÒc—ùž�eaŒRë³ì‘æ˜5?IPã\ßÜ�Õx7Ž c§(Jî å6“zm&½‡ÏT£Ž€‰Ww>%ø6ª8‹¢Á°÷u^-oÙëõÔ“qJ{žúìòvµ•H6 ˜½Ò[¶©…§Í"N;jKï¸Åe²bËŸ"ˆ²°(SQá6ë[t`¿¦Çf­E™ðD‚·ç= ÌÓ<îjJDÕ¬ôQò[;(X7°Î ìa®©@Y Ð Ñyo|fJJá™ùó°×8Á¯‰vÞ“ý“Øn»¡L䌩4ÈI ˆ g¢‡-¼=6È—¬nL|‹%œâmsž¸Ñn¢QÒ“Q”dÂþ™¡ÍRRµ2˜Ð¦‰]˜•.³±3}Ðp¡tÈAÕëªÝÚw ÙSw“b8Åî_€GŽlºœÇîxÒ¶ñ y`j¢Ÿ%7§\‘7fË«§¡ä$ ‹Ò(.+XAö ¢[3^›qMa4ï{ÚsSš/ö4}ÇwsƒZTÁÐÓ6 5°S´îÎe’Ñ;æ,ߺ”7®O.îX™Ë÷àyÐÝ]dzê]®Ue¥7PY([æo Ùݱoi“ÑòÙ«-®ÕN1ÃÓkØtRQ29|±õ2 _ äè!·½ëUç/XÐʉ¹<;Ûj´Ûy¨a–ÅŽÙl$oIÀçqD¼ÛyÄWj9M"d2¶K‹×pÌ­´3i�MVî#–FôŒ"•³1 ŸJ+ž‡çèŠr: Qr6@M†5:WZ„~ÓP®—xAƒvO¬Yëíˆ=z8÷Ê¡ ‰wâ‘#†@Œµ*AÝH˜ð«w§8ÚûJ»/ˆ·³äfb `¶€™WiB KSÝëØ åŃb¾ãë(ž¶€·au-Ïž8ÍŒE#Ê©ÎÃócUóØÁåä¾Éw7¢fŽ ‹~~=ujÌüp˜:E€|C{BÏE×AÆøIN ‘3â7±þE,¡Ú!z·ðÛ€ÀT¶Î©EL!¼…Q^ôCmÏ¢0#‘ð\ u‡4{ –~Ö¯¯×aHpk[ÝP.²Î6³rY-üœº$Hg¥és¾‹ y\¯õ¤ä)7§×´tr´qÔŽ÷r%»‡R®3q§Î¬œHÃ2eÈàRP§ðk:_uô¸ t¬1ûì~¹D7C!ËÈüP&/ýbw4Êèʯ•SéßÛŠæy£ÖM€=oq ÚÌÕh e°EÕ‹çî5SÓ<üæÆéjVÒáQ ¼,9¥'¾*óts‚Ýaa€H(Òƒ%;jD:ÛÀ¯ùÉCH3F'!±Êƒu®õˆèT5áÆ'lúù9=k"ë‡OÞ<7_µDuõV•>àXÔË¢KMz¨ Ïúí:¸)Áµ#×»÷ôÎ;œµ‹±ø¿ì~áD»É¦N¯{#³’}P¢EjzõéÐÃC?ŽŽ2°à«Ã©æ3· ´íÌaIfC r£ïûòl•äœq ¥J±'tó(ó4‰Ù®MÂeßkº2¯ÇóúN êÝK "Kô \K×ó|„{’zkß{m{ÇóÄZÄ=bd¡L‰ [T3GÀ_ Pøf‘ÑÛâÁZ{W·†+GÐÂG¢à¼²ÕÀÝJTà°'ÔÏÅ=Àó »;J'Ž¥½Îuféù*ôA—äÉF>~è¼h5Nì;Y³uÓÏö±)ŠðãyT– æÊn•ôÈ\›jƲI¤ör¹VâR Õ¸Up}+n(§¹Nj5Áóùˆ¤^Õ!ã%Ëêœ+…Äűe`ÍJ^ª@„Ø;¥÷ÞÝ?7èíËdz7Dˆçô<jÞ+¾D efwÖÉ¥JÖü!AÔD>&‰õ=Ç>ýœc¹ìª±™78 ÇmA×Z§Xë%Cðüªª¶Ïc»•OC}”ç æüi² ´á{OK€¼žÄƒ¡Ø²´‹”¼È‘>f4–Êí¨äÞ½“d¬”Æ^p¹­p¨¬è³8Bñ…·g«o)úù˜£¦óð.œ°—]?TpÉ}ž på³ýôsb«!¥´ßó®òS•˜Ç”ÄO½ï/fC$ŒƒzÞÃôhÀ7Šðp&<.¤%ͪdÉöÑ®mámÂ<ö’g´{ É’Îå<,®!dp} vo;d’î6�W:vßä(�Ù˃±w·}yÈØ¯ôÝ»Ü Ð÷mIÁÅz°yï†MÞ:%’ßÏ[å’dHÕE¥WŽ\óM‰$¼îÅuŠ·,-m³$ïáK*-È]uóJ©Ü ÝWßKŽ­»˜n‚/²kx­³Ôcϰø]F=sI�òJç‚öG$Š'Ó®± 2lBnó~Tëxuz Oç«ÂÌ1Ø|%ÙÃÞÒ@·ó Ø@§Qb34 יذʜfš�EC‰/|=Þ9Á *_4«4cFø]‰b_ÕÛGv桨O1hÅ'ÒÂMÞkÀ¦™çHÙ‡ü”ËÆë9¢ç9И Rú0«£¯Ö ;Ee#±g˜xÞùÌíLüyO¡3ÐêÁ¡¦K"Wá[Ÿ¤ òËíÃ�-pn#zZ£ù0¹ÌÜšg{—O_'™ž>SÝZVéG>ò\×õhߟHP# ¾PpÚÍ9Ÿ‹My% Ù&¥OÓÉ»ó®AYÅRÅŽx•lÌ(¯ˆSvæ&“7*â1æ]&ª ,Êéñ2¦Zã&!`¤bsàHº‹Yãå«…„sly•qQå2)Ñ2p¯(³KG'ù òOf™¿˜ÝdX]èõ’˜·[»Ê\^ò‹É¢¾Öéç‰qÒÙu¦¹›Ï˜î^ ïÙ<ݲ^¾ÃެW}§µñÞ¸ù{O²ŸÕJ!ô´êÝ;ÄšiMÜý]p×h@…¤U컥ÞÕVkÆ)ß×ׇpÎp«èkñtòM§tê\¼wħ!\ ˜HÁ=>¶ªsyÛA»æÈkÞG=>PdõÙôGÑ%ëžÝÜ’ "¿íÇ$‡4ÝÝp™!E«çÛëÍ(ŠÄsu—fJ¼’œ!òQMœ¹_¬£ö^÷ÛM~0Öö ŸÜi>^aZ#¹®©{ ‚÷¢ È |ô\ˆ°lz`lYÊ\(ô¹€gÑj•»˜P§v‹¬¢(7Ýe«¯xPÍÎUÎu»z•D8˜øÛ(¯¥ì·BõÂú܇`˜ÁÃÁdŸß@°ÆàMUÑ0Á#\öZã£^Kd'×’ ˆ’ 1ÔQËÕ2ÁÆ:éüHË_ß±Ó9ÍEy×Ü› 82™gyïz¸—3ØarŒ¥´«Ù<:�%—Þ`¿$PëÈ8[EÌ)æ`ÈQ¢f·ädé/òâ Ø#éÚi¦‡ëf¯tr¢9ÈäCdÂÈêºG…«ÏUMbÄ÷l)u©ª±d•zÇ£¹6LnÒ8kã…ÌÝÄz#P 2Å{$4Á¤zg¦D.÷Ž:ô¬v^¥;V[¸ÒyÙ\†æBÑP†ÙCåÅb{ ­†ÛÝ›ÊÓj÷R^®`Yp^³<Ìåcôð%vP¢EzEvI¾e6\|«oL\õjÆ”p…iØ ãS€s¿iîµ×Úh$¯Ù1(ÇvoÁL„“«X²“7ÆËÛ×ÌUË8úMå3j ÕLh‚ã×® ¸i\+u÷ ­Ð´(6R¶,`§:‘¤Æ¦óž?\«2õáî~ü|éHߦ\çÕ,‰Å–øâH¼‘³¸¹}ºïÒáŽÎ V @¤½å­¼žÒ"¤8ÖQT/j²û‘tÕÔ$5߸‹Nõ.ÚÃGIjá“çÀ2JZPs9Lµ-()„à¹3óÖÞ’“èÕ{äÀ/ºÒ^[ì´¾¿¨85ï¥0hçMÄ©É{ò$5h.„ÔC¾`E5…J§Êq• ‚x4½*‡P’‡õÌÏ´jAz¼}QWŒ`…ì‘^Ý3I9ð¼narq}Ú¥€ð4Î^%Ñ¡IÕ-?.åMÜ O+[bô%Oý’Ë•î©?—ð—ñÒVãDeÁ½ñ#Îb¹7â4¸1'æuí ‘AËcªü¶’u ³ÐìíTÑ4+¾˜¡ËA–HFDÞu?~13 ¬� ´ôÌŸXXq­Ú^o_6ùĽóòn³‡l ¤Î ÝÔ­ŠšC{²p*Ïèboõjc+æº9#‚pÈ« q|+ ”U%TÍÑ{}Õ¯ýMßöÑ鱩ow·ë JryØ ÏɹѸ‡¹ вŒ9Bómñ¾Yh^Û^ÊZÏ+‚X Î.m!ÝlÉô‘´ÅÆ´>{ÜAb1¨täJ[ F´4½òænS(Y¢¢q Õ, 3X²$lk\˜ó¦0/¬÷Ù6¹Í)mâ:n`?’! ™,¥…X…àËzd=}K•z¦Ðtgc”ïJMì̦¤r4@´j^ $$ñœrÚËê×û®­¶éÁŽN ·’µ—<+H!”ÇBÝA»|èr, ²Â]!Êfâù°œoõÞt@òs±?Ð>/˼{ÅõI­Âµþ´— °é)¾[fK^èw¯ü!Û#_˜H‡ÂÐÈPÕxvJ<y„åjð’gXuÄSÂ4Ô(S!GÜÊÙq–«R„•Å,ÌC�·å0T�;á=*¨A)àeg¿8ïÛØÄÚsL“Ë #NC ©S3-k}Tý¢¢d1@l‰T„R"¸qª^I›&â‰<D`nùÛv…ž·Aô»‚qñÁÅö3Ý}å1ù^´âÜQ±¹\³'—Ž[cDxÌë»^¾qÖˆÛçÒÖ èÃ÷ð�–‘P)¥¿gÁy†6ùAàî˜sÓU^hˆ]ÅÙ¢oÅM2FuÛ¨eOÅË8s¡˜(y̹¯ùºïšAŸ€³-‘×t¼"2…J~aÆ‚õŒ¡6öùk×è¥Ò©î|R)Oiжor‰¤o7›í-lb–uÂ>N§Ó~twÎÏÊœM³›u¹Üö)ÒH.ÝTð5éH38RÁ†˜ÍDÈ ŸÓ¢C?K Qd¸vß: #{1xør³<øˆa‡kÄdò½‚¥‘§÷fÏ­R^º£—ÃÞî¹HÍ Ýqê�ï‡Ü{Ö0«júU‰fú«®. ‘OÒ sB@½‡/5TeøÕQ+†;Áú% ì:—:×!ÃD}ï=£µZ1ènjS€‚ÞT|ï®Í­Œß½¡Ç*ÊI#áÀ1Aͨàö²má!¿ê—-OuW›•°I2ryï4Ÿä ÑKÅ`–xJÑà¤ðœ­ŽÊ,Q¦±ÝòàÌ…Eßú]úïB,EØó»áõ�Œëåeq*з÷”™ \Îé®"†!ŠOƒÒ·62ûH<(ß¡ú³Ç¦/žùsc!¹rð¦ 8¼–±|êY–˺„·Yì£j)ù­aÛmæœHiY’ó” ³(*ÝÀ¬çuùÓ§9÷¦ƒOpç„°÷ü’ÂE,V^¯öKÍ™Sã Ee9Î(+ˆk(ïdYoMÕ¶É (œMR¹¼¢q¿„óFÝV/ä™Þ}Oº^ކ/Ï‹—åë› Nrž³µ»:ÇH ˆj¼ò˜´3YÞù,v•Xüˆ7ÆáÖ¿¸ ËÛÜ´^�§„=bêg7J:¥h“ÛС¦ã«oÙ§^.>ðÃØãŠƒ2bÍ„%‘5yRÒõkQ6Yžõà=i¸X…&To*à›z3nÈ U‡û0Þ�/.$qm¯ ZpBA0¹:ì0í'H?*PáEã'FÂÝ&úKXù9šÕ[1Ã}/–Ýtû±©œ4 =V|'0äåy¸Ië~Sn·ÌñðÝÊÛÙñ;AV®òÞò¨{|ð;§ÍÒoÙ¤ ®åB6^;–+½tVìïÙNÍ‹–0—1 ŠÔå 6}TŒÛÅ»Q-«ÑUƺ$Há:/鵋\­z`ÖÍË´ç-í\Á&oB Ëïí®ä“¡(ò ß´ËÐ[H+¶™ujGˆ)\è m6¼§úÐWnB GY=ŸÖj°>9â•ЬH]MyŠûä ôxù ²ä+õé�µWƒ‰ïi ¾•’yÕBìg¯Õ°­½Ü;”ßc"Y|“,­4Q¢ñ–õ]( §Pqå)Ï-Q¼åç+ˆ.œê• éòmÄs&æó—{Æêìóžw¿¨{"„Ï6à™¢…DÒ8c¢Ø±úJ˜ J5¿BÂ"±Òpz<äÐ|Œ[®âNËYW,†s]4Û’últ]í¼dÁ&çÎ'ß3z°ß³­é·¦/ŠïŽ ŠX$ózÍ)˜sS6Àm‹óÅVh•ô«Ìƒuõv!ÇÀ ²kV—-wåQ‡!VBoÑæ1Ž=zý€6 ü¹ÑŒ¬ˆgÏäÓ‘ÄòÌDÝNEàvRwyÔ^·h%Óq¼-·!•;χÜj ®¬ï"H5Óγ1.\‘p®Ã†¸ÕÄK|{¯B/7w4)1 ÿžo1=䩸q=`7/|+bÏÃìñc„=àBNç€Æx‰~M×*²„¢é3¯ D&K#æªuEM–Ç‹AQQ¶-,c `Aç*¸g�½¥ä‚ÈÑŽjsDõ^Ï›3Å{–Oì¥ÉI£fÒ3­GI*D®bùêH›çAFãXñ\ǵ$ïf¿‡Z¨bœdýH%ò„Và ‰ð1UÝR60‹”J”#w¹ûTuÀôK¸iyžëë·KWàr5eá^8_¢)&‡b�úÉÖm?¬E—ƒ`9î‹“$Ìlœy‡÷Ú*.A@ƒ”OŸú.Ï«%Îí•2ØG>w üÄ­_¾ÕT¸Ë׋Â×>ËìÉ|'égAHl!¯™K*£îPºõl÷²“Ï•CÅËY•gO¼Hh@ öØ+’X;MF©wƒ€Œ*š ôæÅMúäð`¿Ìn£ˆažx<„´xÙ±@im=pÊ×fÁIò k˜ú £n+ç{A7£¯f¡±Æ¼¯U¤z€–Lží*^®rºuç4°\ེB?"ÎtSGE;‚v|%!îûT•½ê¥«C=~˜< ¡×Rr!Íè\÷Ë’ºv‹‰oÀ3¼Q?;ƒ—ö.Ý8XûøAòzª‡OúEpÃËzêùt³÷-ÙÚU¡Gar"wðƒ=ñ÷9•ö{¾õïY©à»V¬}•âÃcëpÁƒ,ЇãP8G«îÓŠÀ!Q #þF\6Ä< rúž6;?ÙÚ‰,®êµ”¬U‹Ë¥©}²ÞÃR 3ùú]UZ¬k—«Ší’;ÏüxWEo›žÝònU^èâÕÀ.çÖÀFÑ _àdÎámÝ<zŽ£OËÞ›®Wgz…¼ôòO}çMõ™tTDë‘þ=ã^+R<ÉôhQCªö„87«%.Usø At”Ft0T†UÂÍ‚Ü,‚}¸ÞÝj—H!­9XBÅôZk'u‚õ ~ø+1Í$±—ßïÄz½¾³ Ûª“§ HØò¡��ö^ù8åÛ<ih(!vÔR­²ïÒR!°±væGy)BsLr]t*F¾GÆW ²[… †1$SœŸ¨à¿¼ÄG"gf}zAóKVä!ÖÞËj€kÖiÞM±9+õw+ÞùÜí!±¨¹CÛ•ÜÍH×+ßU]}—4ß3õlJŽ÷:è¡Ä¨à(ª&&Õlà¦<{º©Å aµkp°üfˆ÷rÐ+f—š/§â­e¼e {%ñ\ÙRa&<áÙOxñ¬c%Ûð„¦àNTQ£á­ûcÓ=AÚ®¥Aˆ@I¬S…Mgâ§ ÝùhU‘Öo,b÷yq— ^í«ãG#“éynJR`ýZ™©¸Z”Ãô†ºû-Á«Ó•ò È.Á¡\f*&UÁõ*«§5fÐ$:=2µÛÅäPKœ¯ Œ…<‚ãæez=¶…4j©N…‰I®5½«‘¬ ܶ2ÊáZyCc†›ˆÊœ‘[ ŠcLñ\µ ‘ÆcãUBO½€LÕ“Þæ Üê¦W‚�盫9]WnÕËï…?Sêï7¾We<Æu2³ÌL*à <9a„wowMÞc¼E­P~xÚ<‡g óø(t+lÂGr„\o›§øJøÆæ‡ëðYΨh;ëÖ ê(í:UfÂw£—Á½s 'Óë+æ…mamê}ã»ðø.</&!V:×vz[(uì¸ZÝ/]Bê©øz={N5ì›;rÔÏ‚yíÕ_èÊÃÑ­½ƒ<gëºÇ΃ÓBEk1¯¥Ÿs‘¸¸Â«5,h±l°—ïA9jÕ®£2¢2q¶äùJ1¯›l¤Þ ·ð2<è$y7G|©oC$`¸ÓuHf ¥ÒÙy)ݾ§2ô¢ä•0äôãoänöI3H½n~*ÕÏÛô‚÷UáÚ×+åɶüò×\°—:ÎpòÌÔ$q#=D+çUà£5 æõ »CÁYyïÓäG×Ìõà!݆£ÕZȵ¯&ú‹÷ XT Üjöb¼²“ò¤sQ!±»~—…¦Ô•Ù«&·ø ‡¯ðy®<xïÑ”½å`‰æó…f¦ÀLÅ­7Nk¶8ƒ›OY›Dl•¦ñÅóuIË…ª·×wººŠéGoƒU%‹²<rj›²í>k¡©LK¸mHiÃ+óõ;ð¶c‚†N¡vX2ž¨VzòpŸÉ-#?-¥½6Ba“§/°‡_oÛ^F ú+WݤfFÂ|/ÊɆž’>‡1Êô|£ZËEC›LzX Ý¢< ²€böl&”ÙÐÖ¶?ií¶¬Õ&°c`wbÛÅ8jÆé Ë!8=µxˆtŠç‹O‰å $frHÀ•Ú¢öZøQ ”—'÷‚çC2 «¹÷ÎëœM–8QY8ÊÆ÷è1*œ#¢©ÎÃôhå'èh¹œï ]øB—ûÉ<àé©ÞÎ0>c¯Å—×Ò"“üçÈu¸æE[—óW¤V`ýX•”9º¥`†úˆðl¹s$×F„ËÐȪÕ½'6³Y’ÕÅŠq/_ŠõyÑ™š¶ö9ˆz�ðuò0njÓ@²y´)ÈY•?ŸqõrÞ*­™T)¹#“CDÛÝ…rCÈ&>X¨ˆç)Kt-¤'±Ë'zT™3TJ|ªü§JvBäj@ú­8ÙãÚW ÊBÑý¦ë»¶Ê±¼˜wXø…Dó8„Ìùræ� qжéyÊÖ¬È䥂äé ¸ž>$t•Òå^¤eÖ†2ŒtÑBe›æJ|Š, õ2ÑäÙB!€« <’lO åò|ZY•‰È8½®„j‰»<™€“ZoÛMòBŸ’zO„Ì„Ã\)›6T׌óVÊ­«M |0ÃO–ÞLóD±F aÊ{Óë‰aø _†À{ñ6ÄÓ¬§..Þuj’¿Ý}Þ¶Ôv`޹¡Ôê È£­ôò½ç‰‰A¨A’ü(# ×NŸjNà^ó0/Ð ]¤Väö¢g*¶hg‘81ÄòcA/Zë;î;8yz~êHêk˜›úLMíd8æ½h3ÁˆRoçç18œLš0LÀz£¹ 4¼pì•´×ÛçXP„:à*—£…rÒNJ…Š@âÛçk“÷ôâ(­<g C$`©Ì¥_>©Ø-Úˆ÷ÞÁò'·O'pèä”ô^7_<×åq”ÓòBòŒÆ—Çð\åyÞ°£ ì¹ë¼™²3"¡²·qÌcNÔÁ"·ˆÞ:ðn‰ï—¿Õ6e !;ìmYé; D”Ò{Ãurgò”MrkÊ9 ÷É[ܹ.x>ÕäÃ;÷HFû±ÅQ¿Zµový‹Ýy«ÒÔ—ªtšÇñFC¬ûeætïèÚ[Ÿ8½€ ˆU5”Ñ sso޽ p+4ؾ—é:4<˜ ’ {íA|OeÔ´^W,Õv ß„¿Ùõgd¯N´“ŠV"§ÒEC…5Ô®-Íá…R û ØZÁ8é`¯#=«,{„é&“GùÂ}JoX8n:_¼Ñmy†ºÑ^•ìÁ{(/ïŒÃûéà;¯- ÜìBeqÂê¸>ð¸VÃ3ªëáµ1ˆ|néÑ6ƒÄ×€A%®g9f"ý4}d®Kg\D )@÷žÅPW R·4ºZ¾p‘àøâl¥V{½­óŒ™ ¶­7k?xœ›Ý×ÏËXÆÄ-Й"¤v "ÙÌ«G€3ûfy‰ ±fUGL룤š)õ8løð‚¯¨ROp®ï2+¡­ae²;²à=íåÓömy]¢×D¤¿‹gOüŒÁŠ7Ù GZ€âto5’R±2£l'íS¥N›ë¾}Žb‡ROÕ‰O¥ôTÜÌHÁ¨"4�ùÔÜ ·9ÓD¨˜™÷{‘B칓8—^±#Z‡`]o5`DóMLÁk¶eŠæ÷jÓƒŸ+¾—æë[þšV«iMâu¿\j¨I±W]¨kÍlòÜìËãi ŸTµpòÂgv©ó2&Ï„Pã¶v›ï Ä£g;Ø©½J‰D˜×n�„1ðV²o$hNõ6ÃPx•Ø%Ÿï%ϼ]/$ åVˆ£Ø„ÖPE $Ê6ÞˆŒ {Ö˜d³Yþà-»-‚)¤Ž§½6U—2Ôä(ä¡hôæ ì÷Ü\¦AË D aéëSÔŽ6W½êåIð „­« ±%y{e~ä“$i„ô /ê¼ÎÔ-þX^(ÑØ®íC×—TîÒ¢ •JSÜ”ïèi-TaÚ¤“"aÒmЧ•vÙ’qêiÅL=ŠW‘Í•¹6'­k¸hghY¢‹Ô9lZË¡à94bm؇ÆgùR<ûõmÞî²7dì¶;‡ïÛkÁž0N>3Ý:„IÑ']R$ R[žˆ^^îºpQ–6iHi†ö½ÃŒÏ‡„1nz«ŒßCR›—Eþ¢çíè,ìmIù³Ãë®õÄ# "~vÍ[XEo—$ «Þµ¿â‘rfËK¶ Uf8%–~½VìtÝcêËOsw¥I6ú¸ß#G)C wºš“TRЬö[3¿“ž~¬ò ª|P]ò=€ ,Ð\ÜÊ}OûYÖ¬ ¯:¤EÔ²ž¶[â]ªØ3´lTÏFíºª“f=Çä­E>H¸ÜõWå!íGf„C²"¨¦ ÀAÌ´ïì-—±¿B÷·IÔÂZÓæYxé)0:¬[ 6 WÀ¾ÉW»¼’˜*ºH›¢ë~q>ÈC~ýÔ–ˆ²:Ý·à‘«Ñ4><0Z(5–ÐTTœ‹”7Ì#ïR(Òš¼×FÒ°ÃÜÁHF0ÅTð)<ž~c ‡OÙS=‹Uɸ„;æÁùÕ¯™ë%¾!{Ξ¯JÄ«º$âyÙuë-jKj°WAÜ`9ºT«ëkœ8¹;;H§;èÞ>�·¡¼ÙQ^^®W’ïL• į/Sc]c]&ÏfúN{S¨Qî(£·=‡Û›ÚF D§Xs¸ˆÉŒÖã1Š <ò=œ7׆OõÂ9U…\ß`ÝH¿® Ô¼©±.«[q §*[ó‡[ûTÄÎ_º]!”ú ŽXž§°4OŒÚ²<N>é%þ¢W›  Cì­±«â†ßÖ>R1¼Hìt|óô¹<Ì%/v…£×/_z66 ÀãT…¥1\ÔyÙÍuÑK(­‡RØpmk6oÈPlU'£w;Hüü¨.¨8;žÅ›Ñ¥Ø¶³OCæôuMõê•8¾-äè¤ Ô@¬] fks ÕX¹} Ü["D”"ð.â ŒŒˆT ÏšÝÓ4¼a42E±6î™ÿ‰/¼{«×Lœ§Ín(Å•Âô¬¯º¹È’&ÌûòüÖרŒ:úìñ˜˜W¬ì¶“/›íM?’%6»ä{6ɹú<©á-eÇÒ§×rù#óÒž§Úc¤"ä]º´f¤G³L"üR0ªë•ÐFAÊ‘T¦ä›s®bˆx¾V“Q‘sVC —ýÉZz4ã=QЊ›|Я'3¡HJ‹*7#Êâ9Ì{I¨æuvãPT†¼¼ŠpEBY€íÔ%Œ˜³ñ*5,ÁB3R)/eËÛ¦.±íú�Š…™^T»ˆ÷ {ú»C Õ§‰I^‚dÀ­°ÒY¶x.«· ‡a³Ê+Üͪóeø39êâðôY™¬ÙÞͤEHœ†ËÚpíXeTD©tÐgJD·¢“¬zéÆ``ˆzGˆ•@žúÞ>H>"¾§Ê¥¯ÔÊT—ÕMR³è6O¹Ÿ¸å»çFƒë¤Cë­`q(ÑžÂ÷´Ë €dMÉ7žUï�Ö{±øvçû�ËüÙC7©:Œ ²Št[™á½|ŠåZ»ˆá%¬¤ƒ w EñxÚ¤Ç ?²§Œøîù¾-‡Wy C`‹¥û:0ðE¥fð^˜r à#+R޳\ìu¦î]°qÒzüºeˆ¡ œ_à&Ü˶¹3ªë7óŒù5²:e’µj“ó=Æ‘Êéëçø‰ï£/|˦Êzén‹É2°ûVý†áb¡l‰Mt¸ÙzDÀkšlP Þ Ð›¸¿l±;�Ñ€#Š<¦¼w¥=òÔ(Ë®¤^¾êZ¶Z¼yIdÞ¹žr£ØÈïÍP“B‡g¬Ó)Æøà� �ˆ[CtSŸñ=V{¼{´ìôF©2Øq%ëaân3*ã:™‘•ÄkyªaíÅÓ©u“¸ü‹_ir„W+Ôäâ±­å›ò¶Ø42ûÊÓOÜ$•�kùà]GbgúŠS"ÞµvÜpW¾“}G(‚Üu΢>—´½DŒŽå*KÄçÖ™œàÓ©°»cÝ7ôRÉzPâÞ£T©nv—Ë÷“@â’·ÈjvÞ|wa±áiº–ç]ÁnÜ ù€·;–ïÛ2CLŠUæ0Ò8wž:CÆ#D|´ÝÍ+Z·=”ÙžšàáÉÆlŠxQ0Íóšä¦¬Õ™BZài‡Ì±y Ý$qÚ{×¶àu×éôÜÙjTé;_Ó(¦×“—¡bKU›=€¹é)š׃È+:Rª­c¶t;Æ}NFw7qœ0 Å5½Æ„ôZ¯­\âÅŒŸ?Ë:Š€ÖÙ{ásTÌ˰¯IR'–í°FŸ^“i��„ô1cå»$ãà Éz„³‘’Q}„Á›Å¸sâjœ¼Þ-ç þ04f¡Ñv;|Îý)Æ%ÎYðÑ@<£´=‚*P&C’ÒçØr ç.Ò3¯³¹9Ôp@ÞØ†‘¹ä]èûËÊ‘}¢"wëCv§}{ðÈMyÜÎ\O«{нjÉ«W2C“Í6Ê`ÐÞ{whz´¥[V³55`Œ¼rª…ðžã¡“òñˆ±&ƒˆƒòp¬°ó3Ó#ב̰:޳R–½Šy˜F1u: ŠruËá>Ÿü2|ñëO"&Þ‰(®Ö�&=×jºã½Î…'\çÌ5C p„“%×óCSÁ²I°Â-~NgÂ=Ø!¤nþr ˆàD€œá ×Ái^oà¶'œ=¼P!~o¥÷±G™¡öqn¥MOôPdFº’¼ ö™à’•±Ï…jpfÒreXŠüMèbWŽ¿n|”eJDÞi%Ÿ@d•°¿�†L|Šº± Íýä–*½Õ¥œÅWÑ‚®#ˤS$í”ûÃ5†`ÿ%ÔUÊ{44䪨°9¯ …¡œéäêm2LŸ5ê…‘!¡œ<µ›ÍxVò Ù¨”�žRÖù8Þs{¾›ˆ¡xFJúN*Wn‡v˜2žöbb ÍÑS˜9žíÉeY"¸g#¢n=ïq±]y‰°r–õÉÆ4ô ŽBñ«¦aõécÒ€¶éëÓ5y€M\)Í^ÜJк>C°î^¬7´\ Ï2K¸ÞùÜŠUˆCg=Ïð·-³Îyâ1ñâÊNwÚ]-`°“ÛΉŸíÞ’â.Û3aÙ²gqQÊOÏ·ÃL6ÑC|mYÝš@˜x96x¥cœ:™ ï±ài1cf½ŒÜ¹4äg+Ùä^•R`û€ª§â¦c©L?ÊVÊwy±-\7‰½/B¡”šïü&ˆë*Áð±ïÄaÓœU¥jš64vD÷™“ƒàAºT BñŒá>K³¬AØÄ; m£J­-a¡7Ëju€<Ð@ЛæÕí‘ZÛ©­"ƒÚÔ…Cƒ‚äWÛtýܧ_äΪ�EÛra}KêL¤‰`OE;ü\\-5L5ŒÂ= ®^Âꤗ©"<¢¯Eׇ“‹X{úäê ¢@—ª¾F|õåÖçT;ê^XtÕ›êä—ü °LµQ'¤#i2¢2ƒ¸§¯Âb@]%ÚH¼69Ç%Yi–6ðUŒ›_¶*>‡‡˜Þµ#ÑíËÍ‚¾=ÔæYØY§Zwþ6륲‹À{!0ð8•\;^âözP¬>—–}Uºéi W:úí#XÃnÞb¥¤TZª[ðƒîœx«X;%3PæšFž¥ª¶ ¦ƒTWÓÉ‘MóBtØžËÒ_/Ya¿J²iö#¨Pæ»[8E¸ ˆb§!|ý¸8® 8ƒì °y¨5K;ªZצ4ôl/ÑM<U–p€%Ð`¹:DÖVB3ÛOÉÖÅÕmåšæ`aîYÕš „â#ǾÐuÝ‹çYLf)\,³Oõe€–Hõ yŠtê¢AðÊÀè»GÁãu<G“BL¡}½¹­‡ /­.ƒê$6WÚRošnsÛmÈõ ©-^*¹ÝGÝàŽ Øb/Ý+c(JNR:˜ Òâa‚€½Âs'ÊžÃT5îªÔvJ•gÇD0öðÞúÔX! 3¯²&3ÞlÜ™?c.8Q²ÞÅ œå‡sÓc¹Ó=µÀ»9:­{±ÑøðöY©íœ'Ö›¨.8¥¬÷ðøµCqÜ›‘¶þå.©XRnû‰×bÑÕ–No9åÀÈ"oë¼¾JæGÔù@�å½QæéõÔGMÀÝÙêEì7=µõ�öQ§éÁc|Å XÉFèúÄÌÚƒHhê¡oíh3ú$’€WJ1NÃÑ®¤JNÑÀé’ïØ®—ÊS@)Ó— ‰Ú,¹ÅŠªø¶ò•[]á$^d¢Æ§tO¨­#Öù2òr¯’>J¹m|Öª¾ËG¸¹:dÂY(ĸK¥Ò÷4ÌÒ¦{UäòJVoΣdcÉ`«Ôæ" †¼fø$Xô‹àNÓy‰$!éhê¤h�êìj"lóÖO ‰.ò´a­W ˜ÐõÖ€Å2Ö-Öâ†SÝÛ ÛSlg«„ÍЧ›ç+žXK'mÀK€¬óTsë¹¼Ú‰Ù¨½ ÑÈöÌÍgW†/ÓFÚØ$}öŠÂ\ckg GQR&éqè .bV’^Bš…íÚ,¢…+ <¥é=3iºE–œÔšÄîz¤uÊüÂ×²Ùør<_7G….N\†ö²Šïe·½àYŒLKòîš}Ö‡8›æÅM‡dó²d§ÀS@Ψ JQÍsÁqñÅ™âÔˆ1ÎAÏ�d�JCª„ÉÚÄDD\™=⧺GT¥ïÈL/Òü%éë}(þ\á^¦*ÁCÊNx›Mý¼R©£ã ’Ï»áz:‡‘½£QŽôsð+ © ÒIºyÚÊÛÝÀ±ôÀ‡žZ‚ÆŒòÒÜÜŽ¥d0•sKij„èðs~e‡œ Oá)3»AaÅ£¨çä’‰€Qº€Sتùb/Š`›WPö„uÝ¥"ömbŸWŸèà� f¾ò‰b·P^³÷Ô;g1›´Þx.ó,ý‹zØy­Ïe¤Â ÅÊó\è¤ÓªsÁÃíy‡ìÊ»Pˆ‘XÙŒŽ­j[¥ÍÊY¦©e¤Ž&ÞLD`«§´ËÏwô’Õ¼xÙ[Þ¸B$§õÆ|²WÛ¡Ð«Ž—¼wÅÌÂ+Œ4É€XîÉeÊ›$™®XfIgç7IxvOG‹ßúë§hEÙA™ñLÃFÄC”®¸‰ÄÅJ{O7Gãe‹¥œœíݸf?.€csoNá`ãt!†·×W(8ÁØÁQˈ‚iø`„íÁ)ÊêóÉ%~›Y¦ì äݒ«ZoDÀÆÑì1:Œ©è˜©YR+ôåŠ:{4 ‚Ö¯R-ÀJ‚¨/¿ç`å/„Ï´\¦Õ˜HFyãAèàRYåÙ�êÍ{E¨ÐÔîÔa_ŠiaÓ<Øó3ßó¡c�CˆÌ‰wÆ]±6V{Ö!ëy¯H­=eŠžãófñ÷:¼›“ ÓÈèíqsº¼>‡„&QŸáñ¤evÐcBàÞ•§ä+5g¥¯ Þó‡û°Üš¸µu€AAD­wOBa.ˆºXc¸Íí¸+_ sbvà…Ü_ [iÝP8vS¨F"Áǃî•b6¤µœNÄ72OÛjQȧ’ñ(ýQæÂN÷s.!ÀW‹¶ØŽýH»ïNöQ‡KÒP ]k/›f×Ña yö“‹·çD)*L ÌE!IÚ.Ë•çåÂ쨕Í&o¤£(oê!•l{R‚Õ¼A³ãjËÛÓ… ¡×6Ìr^„S©ëy‘7Y"°˜ª ¡6:oîM¸•®RŸ9¦J%#šå”BY§¿k¹ÛÄÁ ­‹- äJé¥X.„8€Wž·³¾Êö 6|Ë’�Ø¥nuqmui¦1�׬¦^ª4¬X®QA'W–.m3œÒ½·®rÀ~ª·Èðâ^ËܳxŒò¡95Ý2”.—í2Ç% 5л´ØlKÄdñâ0·vÙ92²Ã&kxYŧIMŠ/}xî—4¥;+KéÈíu=‘;ô)ÏO—£jy¸W[¡G¼lïm쾃Êž¼×s¦SÐGÆU%Žd¯|[VÆi•Y‚Ë}J CéL;iíE (æ”#¿ŠÀÛ(^á¨ÝØ?dX²w†Ñ*êÙ2#žI1ÙÒF/rétòeAµÇÀ.KŠF&\)#̨ x8¨ÜÚŠAWÏ›(څظ+g4ˆ»=P•¦ÐÞØu\w€ˆ±mš9AÏ'ÃF_ “”w4<ÚÔê±÷îÚ ýª(^ò¦Ÿál"š¢Çið>¸S_WJǰò!&{Ä/…,®IYk¸¢tpgëˆí9†ewNG¥ž¸Ev¤ºf¼¶ôy~!¥/'·Ø››¥û¤büü½×fÍͱ]àH±\¤¹¶º‘$ŸC �¶Ì«[-!BTp_yc*þ Pq)ÅÌü @3k$ñ/ˆuÚ»‡ò”.Œ¼öndÛG}ˆ±1ì¥sb€Â–¬òŒ_6A›¦Ç8b/)ŒÁfœm·ùÖ›DîpôzØ<†FÆÓ¨¼-yì5¨ÌP\›º<ìô(-SĦ‹§r4rŒkQö ø•ù¬W8LM¡}2ŽÏqvõî™<i³+j¨³X:köá •(c O„‰x{Æ=h¸Š2óœ…#RXë4rH_c9K”Ôëzô{·*ЃÄRl[f!œØJL@]Ò[-JØ<jF/ëVøùEíÀ¤O‹Ù»"l‹¨¯Œš¦z%ðYkÝJf’ƒ¥P:/’‹l]QÍ1÷ãg¥xc¸¯@­qFÚÌä ¾s h¹s×ÂAR,¨7/»½Â}‡›XëE'ÔÑ¡%¸iɦ9¡Âl$DÍók8­{ƒK®eù8%òæ¸L$r‹Þƒ Ój„:$¶ÝB*Am"·Q{¢qhQþ’ì� ì1yÛCÍã© _|¶fxmÇ;XfѯՌ“òiJgå!t·1M`@>2Ï÷Fó8€Ì-tÓtÜ@+B_À‚nÀ mî<ÌÃq5v4° ¾ô‡ÙœÄB¦Ñþ^Ñ9K^¸µcÕ�e&v²cVA‘D`Ã*úÓœÓ#™AJx”D¯Þø õó$]ØØ“„ÅÌÈþ„Øáb웦´î²{ë íÞݳeωËhsïw¯ `íMDè[ìꌧôŠ”7^p.{÷K© ½«öƒ•w–(Ds²šLåÄ®Lq‘m»ÎEMÞ›ÒhO<~¼s:ãš°ÈØpi—«­¹*‡ÞñÒ…bu¥D^È‘ÔÒ:d¸SͳC–Û®­7Ì–¯yY›Pˆ»EzFé„0+(½Ò¨<,B›£ŠìaxYaÇþE1X/êJ{úfW;° �_"ðeâ>ªÈÇOí:íôM±²C©5ƒl£nQ­‚ªzEÖ^/åFÁe3ÑëâgÉTxª'ìOÛ\µvqUÇÂQÜM±¦uN?ï ']‚*ägV‘”@bq东GæÍ«Ídjqy¨ŠBŽãÞÂNgKÏ &ŽlH÷Á †xÇOå<-3j3ÀaãóIFŽ,–q(ímìw³Ò,|½c7Ë ‰³#q. êó#7ƒÌc}ÖªM5ÝÌöÛ·r•ùB«KçZ\q9lOLoPöŒ_5ÄÓób+Sµ|„Š,/jx®n,îU¬v/8¯gjGN£5-ðòÒ–[LñhZªví ÷ŠÓ=†×¦uïV!ç‡p”Ÿ#ëvÚ+2s’ÃJAi×ÇÒM7ª  ùÜØ½zäYKÁ#)Â*U ÓGî¼Ñ€5»„w^¸SVGA<aÕƒ6Nàp<vßÎÎØ9xû½×Å�~Sx¶cyyêeß­ˆÚë~øÜâÉ5i2 eV[•é…évQêé ¬ÊL„+{YUvdoÝb¸oòù/i<%{/lÅÙ UÔÃU-iÐÛ 7«{ƒ¤_ w`5V›®Sa£¥U<ß Û×å…b¤fúœÚxjJ.wSô›bÿ¢˜—…*™lºCtÏïÉŒz‘\Ù+©¶ÅmI¯JЇ¢o/ï^©=ä#ÆmŽã4PÜW„/×I+ë9òe–ìÍŒÜ`dzçòüˆ¼‘é®*Gy³lÀGÑI5»ŒÁê 2#(bÝíСPÕÍc¶}Gت5Ç®,1LváÊçþÒ!¥º5Á›WE†%’^Ë…°à2%+r<nÌÀ辿0FíÌ�j`&¹Jæz9“éîÒèÞ·'0 –ðHŠ�¸¯úu%Ë»|T5êyÏñÌoLÅ18'/ !)C&6c}€T[æ‘a••‘¶ofÊÅÎ#μq¯Hz'°yphãâ´Î¦ëzK<»Ÿnei¹h/Ús6yi;ωjý-/øQ¾{3BÃ5ç09 (èœ€ÂØÃFHŽ^òæ ¦¨”)#Ž—ùœ°çPí>p™ùÖs†¦fÙ‚žæÐ’3*‘›mñ®‡$ä…EÌÙNhöæ°yûqEîÌ­]>·ŠV�ÒJH U‹¨gTATÜwï”𵌽†1ón®èU| nPH]o鑽»™ôÉG÷ `]äæÞ$[u2CF ‰Ös%ÉAÏzð\dŸ=µt¿E¢–& CXß¹îåãw4i;3¯œQ¹E­È…ö’”ò â8V |ŠÌweoñàømyíH¿Ãí, \ ìyZºiB ärªÖ¼(±F`´¨Âb‰÷(í–B•Að…Vb5©¾ÃN?´Œð9ñ¤Ru±ð•wyQyÐé·\*Ìd]"Ì®ü÷Z™ÚÚÐ «AGZҡߥòcêË^h10T²€7{N Y/x4èy\DJ½EâºײwïØ«¥©ï!¹6‡?2ëö³¾Ç/â¹{ï<ƒéx Ÿ‡~a|领s69‘z·–/+"P O”C€Ã8ŒÝ\-µ™µÀí²#áèº}_oØ2=–ŠWr6ObÞy÷pÕSF,—kzä[Ђ]ÏÀr±ö‚ÒKŸözÍq!~®çû\a ·¨-Rzê×Þ¸eçÉSâ'›Û]B÷\Ѫµ¥©uIcsðj46‡s&©¥«¯.|9Ͳ(ïÝä£÷Xçùá´ÿÉñþÈLSMHæÇ9¢>ikò|MWP¦-y˜2ºVžÆ¾¾Ì²„°ˆŠ.Õ`˜5 RAq\-x±¦Ç¬ ÝS뱨Œ=?Ì |µ¨}º5zggî7•ÕŠ(þ÷q“Øöb"ÑÚ¹P“¤ë¢e7¼v“«©¨ß5nÕM­áŒò«Ô*Zê>ÖÁƹ˜Ö3[K §×8"©ìålûÂOh€FôQj<z+îÙ…øÈƒL¨Ö%™Œu•À­$Í9’£ $1D?=m‡@Îr¶¶Y»[ÒE(l({/Èx®S‚‡Ñû5{ÕòãMÖ×WÂgÁ\û© ª×L·ÛÛq{FÆ/µÛŸŠé+¡wõ&L(ù¦P-M}CÛ†ÌjV0V�Máƒ2Ez ;ÍÂ< o‚Djz<Ô<ÞDDdjÍv'àòÕí{®ÐöƒdJ˜‘¦‚lŽÆC‡<ÒMŸYÐÛ©>Ê%à\Ýt)ÌÈ¡¦$£˜Ê7ºzYJäΨ#òÈâ-Ç)®–§ú¬óL3 86wí{”-Þo=4ùù +®OY¼€lªŽ>MXd«gj–Á¸µ¯h½“A}”=j WFË ä)ê{²Ý6Fè…EsIHÔt3$B¥3I§É2õu޼™“©´Àýüe<ï}a5͸Qý¼)L­Bù–ÆOçB÷0¥òùÚãGöP¾8~À_o€³åª…]5”ÖÓÑ÷†4~c$æÞ)P:ô„6‚O*U8Qžjùb‘û8Ÿ 918Y˜¤é«fi+àë)sÌî²�Ñú&#øáƒ…8Áë­Ò}6œ²Ù§ð"ÙióTµ%å›0Í|±Œy*ψß5¡Ï¥fñŒ£•æ ›“N ËÀp‹Ø!ve,}ÅÔÅMQ7ca’ºsMÆÙ¢4ÀÆ­ðØÌ{¹IÖÿYœÁÔ„ Ž7Â'¶â¢: M–í¨_º{è=ìËçaäõ2žQdçËL&]ê<Äì$¬G/¥]ìæ™]’žéÊ{«ö»é;xòÓ£ž`P§Ü‚Ó‹ ‹´&1ÂEð°ÛÖ4kNÞ$¾§àO˜3 Û.%¯ËŠìúÙ*ÏÜ:™û»„çQ¾æ¢¦ôBû-6.*.™©<ï[.]•wb ƒb€‚´¡®t¢ºXUí vBðejZGk=ž B§%Ìd zà—�Šv±°[wTû4´´jØcŒÁL–¸O_ ™QyÉ= m;ƒâ{t2Ý{ú(Ÿ0Æ3ß9œ#7@ŒäÃ-èP̵ ±)¼m÷J¤Zd!Pöì׿cø”ɼÂL}(åH>• [›–‹3Ì;éV•XetÕ‡âg}Éî8{OëA>e’fŠ}Õë¸í„%^º‹-WÑ1ñ"^7öc B ³°yÑ-ôæQ¸mÁ˜4¬�ÐÞÕ›FH SmB4$„L£x¤ÙBöjG‰z€+ˆ[¡‡Ay4ç:ïIaŽl²FÏfèÛ°"÷WM´1@SäÍ yñ쬼dýÚíY¸ HO·Ä›%k¸ËjH´gy¹¼ÄîþÌò"rÞËôéJdÄdÕ¬w4ÉÑÛ¸UÚT«÷Ós»X1£\µThz©Yp@ Ÿ #}ÎÇ:ÒTÚñBøZɨš;#mÞR‘¡½ƒ¢Ž‚å”xñÂSUVm5 éÊ–{‹ä­ƒ¿ÁÞ2âl°ˆƒàe:=B öXgݼHfy{,/ßÎ4ú1x›¥?2Q´ËjÞ|Iþ^¦=mØP%S°˜çëû\^¤Ábp·þkxþn0� רæÊŸ Þ<ÂzVé æÉ± ŽB®‘Þ)vRÂ;†Ë7/[Ô(þ"y¨N Ùi“ÛGP£n»ƒöj¡€I.ôíÔ£Y‰`ÛzÂ@W›…b T­ë±Ð•ë^­Ž%x‡Ç²KæÉ®ëò¤'†Œ’ùÅö;[•ÃF$ˆ2ò2ß\KŒÎ†Z¾GÜñÄ£!|cކlBD¶Å'Ò8¸²åÑ»]EµYÔÆU&K µ~ïÒÛ˜%’8ûå3K™€§ykGÏ\¾?6¥u­—µp%žYo®:³?yÆòø\¸„PK°í(¹Ñ½öëvrÒ‚,}){¡nͬ@§X‡yÞ…Y]?zDO&¤¤4·„á�§“ìjø³š´ø‹Ô¥±W Ï2–&ü^Ft‘/oj½ÚŠY‡4 ö2hxQÊF_{Pê–ÞJÆ’>_ÌËÛ´f/øž=i#ÀTÑ;ÈÅH=IoFI²‡ô¤Ò“Óø¬z£› o+蘚¶T%÷ Êßš ÖK~>{eÀUO+mÔªfÊ…18ô½DФJ“xpNÁ¢¦�E}YùI§Ö9ô潃qó… ÒG@é›!�eø4:ÄíÙ¸T¿ºâ~,”lÝ‘•<bIÌÑØåÜÉvDʆLï KXPY¼éíÃ98‡‹|[Ï Öx²†‹¬gJ@:è0'gù³$ë»W ¾pÐïM\Tq?L”`Cënè)CŒ(ëS°¼9ÙO’ ¾HîsQ*¬µ™Ì{³[äÄÊ¢Ftª§¤ï]‘Gv®ú¤Œ„‡îKE•'^`Xx4ë  s­�ÇÈÂR•cdŸZ*€""x¬š>£—Ú™®¢QæÐ)è ‘,n¥Ç‡»I|4‚ìïh bY<êB0.[°x@qIVAÎ!^•FX5ê”Ð[β¾\¿Š 8 vè…&ŠT†¨1÷'<y•úòâmý…2Å¡H f¿•“Ñ{êB«— ¹FPñâÞ.òÕî¨`L>ønP…Œ]—§¥áÑ�™S˜…uI`9ÜÀm8¼?·Š-¢$b[ùâÂF²ZÂX{åbt‘KøDÇ›X®^Ͼ—ÆOžÎ¸Ð‘IÈPçȺy)FøƒMóÑ"]êë'yŒ[%„²ŒJ€)>ÎŽ$Ä–˜þ0ôÁ”ÞØÉ÷G\ða0æu˜rSÍQÁegX½ŒópT³+BáÈl8c• ¨èNsTÂW/Šœ[suÃÍžj6kHaTÛ¬û½UÄw«¸æŠ{ÎxÞ¢ÁØ ˜(`xA¯½” ·dôÅ’Ïë§p¼ÏO͸5™aÔ›<|Mï½Mײ\LCiµ2`4ƒ"Pùžì)öð$[é°RD{&#yp{Èf·©4Ï_ÙÒ÷H”˲¤c²(­ ã49òÑJ ïô„F~®©ìÕçfŸÑN4D2$åéB¶0ÖBVe9ÍhÒMvlV•·Û‰Ï„T¥M…2¼Š"ã§Æ/Ì1&m«¼šõ*)Ú„…÷¹ö3ާ§²9† !]iá*yÁRŒåÅ£áÔk0æ5‹D7Ÿµ~jXêɡܒq=®“iÕR!­Àœí$•[|`//I€úÞs§€‡à¹{xÑê{iÙ8ÆîØ Aß(ûÊ”½³ ’ö‘Z0É¢H„Ë”=áÖièÓÎLï:”½‡õ^sò#5ƒ¹X|` °wa¾l¬uжz¡F¶ÉX‹ÂõmÙ!¼­IEn¦ÀtÒävB¦¢œ bÕ†@ 5o‡žaÐ?å!„]ʼ—Ú€wɸê-p##O-Hç,Aö%Sتè]Ь½‚§}^ÞÐõXÄ©i¼œ7óX­Ú$cð/–ÛÞøe– *Ô8-s¿Î[Ee¯….D5âÕÓR1uVãâ‚ È mpy[ãÏjœ8rj^)$æàõyj–/dÚ†å›ÚÙ+~¯Ÿ<Ím)«3ÒZUs¶ì¡QžÐ^A†|b—³�°×ÅÀb‹¥½Ãx‰@ût-‚¦àm$C[Du’R°/š‚€ÊÕéó+†D±bé³@L“702çl¨)†HµY̧xg’9 •W)ÀÆÒ·ô–WaÕöE<%Ê{‰3š¬RÃòf^K¥ õÜ;œÏ4ÕšÞŠÈIö‘T/®È=0ªÈljÈí.mË|Üå„ ó,‰f_ÞK ˆB,CÇfª2Ï„Daæ{�L„«¯ÆoÜFùáU¼¶î禖"ó`ž°ˆBÍs˜ò憌qêçÂÊLªe!^d°&e3צWoJ're€º×{}ÙM6­›)|"OW°<[üqNQ«†Û1¥8T ¼äzœq(9=°ô†‚-LÙhIç½C®@æ8”¤Àãl(2(ízý€¤#ö‘²,^%ôÌÄZ =¦ v:_‹pI@ƒ1’ÉâMÕù%D+Ù$H._\ÇìEƒ@0jCNã„[’$Av%w»Ñ)‚«õKË Ï—ð,Ôtý–Ä,‹NÔ;ìt}¢´x@ï½™‘”þdùéË0>¹ƒqøB£WÖ¶‚Î_D®iíÃ6agÞ Dí­I´U ð�­ªTD.U‰Ñݦü ë‰ryaƒÖ©Ë°Ý#×$(Oü$b˜«ÄßeùØ/r·ŠþèAËž¯0“šÀæQ7/żšgkÇõ5Õ„y7ñƒP|~¦FMòÞ͵ >&[š4 Ôb÷jÒ–Ì,÷8ð‰g˕ӈ8še뱉ÚÝÉ_0s‚íaæÈ?P¦Ø†Ã�f0»R®[œn3îwÀ²‘Ño–ó•„¾Ü3ÃD,+V†%(¬tÞ±¼ÝG"†Ù÷Øö!Þ{ÄG8ªTš'gjÐ\Z&F„{§0YòÑ’#ˆÇì’K½7‹Üïé „Àv?Õ²XW|w[e@× ØL3Ï%«äY’ó‚jé/Â;jÙXi·è‘Ç(¸¯#ê€N¯¼²,&žgR¢|«þbpð�’VIA!ÃØ«§ùÙ³¸¬ê\tA·:M^{“ìÈ1«™Ç©0¬(µ£6ˆzŠöúM¾€gõp·#çÀ$¬šTçµMlEZgq\1/ÃëÀÆ\I{ÕɾCExó¶ Qx–‹ ¼ù<=LiÑðŒYÐs'ÐnÇ-µv²!’ûhA¯›¹âD!d_7†ò³çä6 ätïÚéâ2ÕñèDnÑ!:–^¾”XÁ¦õà3ôgtq‰¢\lYïø[¢ù‹÷žF©™ƒ¼ES>¡–{û^{‘¨ù½Gû^w†µúa,ˆ¯A?d„9žµGQ-+Þd'Ã-u¾Ý¸öÅ~·KÓëo ¨©¶‘͇´Øûµ®„¥-3-n'=4Ÿ—×­V%R(ÚßÓÅœ\ã=¨Å lÍM±³î¢WÊEç슽(A·géa‰šn˜±úRtŽ Þs[¦~ƒþ 3óÌýèiÙ›-S¥ºwo2ÅŸÕ¯TQØ31—ŒÚ›‚' ª`À5¡½½¯&%û˜ª·| ¡ <Ç`¢ çú%rž¶™ Žã¾LwæpíW›z¬q±@ÜA®Þ#'¨¬$jáwÀÄ!ÜÈkn'.»^@ÍcÚЧ ç^7°îœ0Sj1 lݳ­Ï™\’…)Q²mèI1áàôe<9Höuf™JñÕ.jßü‹æ‰XBÕ5zÇe&íͬ]qÈ!sDÏ|&ËËÕöuš?ØëWq6W‰lÞ< ”FÙ3Tà¶ ™kF;ä“’l, º<¢;o‰A\7dÂïÍc}ЮÑ0ÖL¸Ž)¡îMÓtjHMŠ^˜løHœi noK ¼5x0¸JºíÑ7+L‡eúòJàΊŸèKˆ%ˆ2g°R[—uˈ»K£I#Š^é8yðv“ ޵Mk‘«N¶Zrgm‰N‚pÒTãÜ÷Ywzv¼ºâQ´®¹`¹pâ– ‰ÌŸº™¼bëÈ1ÄCÆ!›s«*ëe(¼+”óË-! ßK¦7Ý+%z±h04¨Ñø{Øw„‰f0×õb»«®ÕV£;¶u#òtEl7)shí§ÓÝ Ý<j}SË.>a)!ÒZ .‘ò¤gf¼ct^Ó2B·u‘Šc—·Z¾q`x°m޵>×Üèà±I/ªà¼.5LÐ'•ù&÷Ê»¥ãK`öM9Úë@ig³*8>q‹9+餙—Òk1çR}‘nì ”de&¥wQ@ ÕPñ$/«znž%9;eœà]‘<Úîy"îC=¡U̘Èc]¯l‹Ž­ïNküÎ^ÍÅDS*¾­k|cÔÜGÅ8E̤–çÖðl+?iú¢¹^Ü–“¿Íi}ëè\‚s’ûn3Û3ôUA-ö€gŠ«O ´jáÚ#~OAYOEÞ`'H:¯OÃ,H)cl?ŽÎfŒ7€$$÷®Þô^çµi°ÕTݸ`¼“W ÑŠ ÒòRÕµÄW^>Œ«Pzw69òÞìCôtŒISM`ââÅ¡@(Ø!ÍSØêb•aRM¨±SÁJ¶¶C‹Nra° ZgŒa¿¹cîý ç.K<¿WœA¾; ä¶÷¬å0`ÞákBΧ'|r©ÏͧN×tÅ Œvô¡ÄVûÀŽ)ÐÆ(GÞ&Õ wX[e?bG8¨ñ[d~máÎïñrn _Hi+]UòIK uGŸ˜Fà$q. “ÝÛ4ˆeY¬cºw„£öòñFneÝq¾·w«ØÔ–=¥òL¬ÃmOLÊÐq- ¨òy̬¢Ï¬ì†%¦ <•¾Çøêîa¿‹#¢ºJň×&J™fŠhr#8ìµy¼¨ÙÑ¢oÕ-ð.Gßw—&†Á‘Ž˜f*›]ñ‰ é‘.â€_34 Ñ;XblË=óÙÖsN«Ú ×”½3µSïѳîL39kÃÎÐ5ZÄ xfm.¹“1~ˆÉÃÙÚ¥šËG‚L„À+ïAh°æ¤Ú¨[+A 6¸Âažåq¨ßæŠ%'3{iä"ªŠ¹Ïs6‚¤Ê9Ð,´[(NYÞñD´‹¨Î'у2 Pr„î˜fo,V—ªóÙ9 âê !å~w­Œâ~ÛýÌ$OVžbÉn„œËE*RˆÑÑ0ÃÜ8là£HºZ6ísF}|Ñ`ÕáE£ÛÞDõ)ÁqÁóž›Ä‘pÀ^Ó»>ÎÓ—œ§äLñÌ£„ý!•{ÓÌ<Lí åU*Y í+š0½G÷îg…/œ3üð <‡·ÞÇ;Uë´ÎÇDÈ/ãÑÌL³%ZA™(§Ý³Œ0×`S&Š¥˜×–FuYø˜)ášÍíÆ�m,c“_‰Y Æž±QMÕãt9]ÛËl–ô î8ªylvŠ7¯,ô€ËI9 ¹õ6Ë@°ˆ´"¶Íý%+•¿Ò¼b/Ozv r+ ~kãÅò™p«R­Æ ¡�fê‚+³ìžÄÈàn"È‘O_ýÅs€_ë»ÝXÄa^«ÞìjT$ xƒ€¤rNR®`­Ø7ˆ[ùú¦ üUGåKÇ™´¡}ø",»–=Ùr½^5¦ènÓe“C‡N䔈ò{ÜÚ"rÏ8óâBeËÈ|ªÓ|ß4#s¹bôCH"®$Æ"Cã#0š-Ö›N'û¡kãæÓTAÒE>¢Xй.Üêå;6bàp{¼êâÌœN;á̤îðxž·˜o„0ñâ5=×+„U§­$·{&VžÜ{ÂÜ“ð¨Ÿ-¾#ÆÜçueVð€ìù@è³âœ'Ñfá}š¦áoó=”°ÉâEÏ™°rÎå•m7¸‡© O‹j–¯¯³B4d¯< ð0öY`Éó*ÌõE~’.gëg’É2d’g7q碧ªÚ.áJÚ%ÌÀWù¤„Þ‰l‡á,ÂB\¤û¾èÄ5t(v —uÚìqìjW“óF ì«|Aä÷$ŠMë•8ù8÷° Dg°†¢?]dl­¸ƒ@­ì3�„„3A„µØd¿þ]{5¨qG^Ò¬Ä<lå•Gb4ÉâZm/µ¶vˆL(Aj0gYfC{ŠyñR6ÁajHæ“Úƒ=d±V ¤À`ËÁ$ã ÞÍi#6˜ŠùÎKÔñö'ÐE!º¥X@œ›±`í¦*e÷ÞÒIå7ÏþÅóò`£‡%¤«öв>)c"ºÐÐ:j;e˜1[ÊNÕÅRleª‚·iò4s%Ì7ê8­XÞÎ>¼°bM9ØL0Lªès¨…B‚‘ûÌôâp'‹›ò™õ£  eð'1Oñ9óÈÖ‹�äo$ç1`>ôBºA6.W¤£*+M¯X —Âc3KÞüFÇ]¸}bEâIc„#N]»m,€Ñl¹«c· …!Ÿ_yRǸ‹ZÎUïHF•³ÿ48ô ÚNÞ[ ¸Ô& §k�îuz×Ô×g4X¨I¸�×– ÌQ“˜Ã.Êã‘mÕÂû<Tû³m® DÏ·=rG®ƒ ´òÂø;§ªÍ. Ô R‹œ@õºâƒ‚µmÌm�­õÁ*Ûƒ2Á09Ei 3éðw,„´|/xM&Α„ùa]ÅšÑu +ÀÐáñÒèGUä¼Jí@ZH¯Ë"h8ž7©&àd&Dí¡œ½ ‡ÏƒÊ’öÆoUß±ë{!"™ØO&ÑÇ=9Þ‹Ãl6%ë—{&“ñ¨ ôݼÉ.]�Œ¶™%3S€÷VmKâA€]7–’•d¢Q!!¼{û°uËËhÑ;£ùí ®'p°g¤åb-šeë¼¾KB[|Ýk{­OQÞ-±¦] À*ÞƒpC<…ÛÝ 8=}£NôŽ÷f¯5íc' *H_iɧim)`¢· DmƒºENÒ`kÔdö6Î-…ºô½i©‰èäª]a7¸‚À 4GÈH™4ƒ*¢àqí:@ñ¶n«æ Øâ Ôµå]´[Gñm ê .šÇ‚›éÞ–á)†“¥¹-ú›1k¦±Àµ.Þ¡Á£ÞfÊñW{¯tÌuå;»kòô£3gÕ%+ &\ÝV8=Ñz(ÓhWJ‚¶õe¼ÌI¤o M¿€.„–0zû¦sFÇdÎm QÖ¾—Q6�]!Û'Âd^­ Šâ9”.2µ¦¹<t× `+ðÁ5Y%ŵ0—§:Ä5Ö}h¢ÖFìJAãˆÛªL¢Ç°¸žvR5Íé¼|ä—[S’aÁéc„";"˜xníP§ Qü®M9� =±‰ÏØÍøõ9¯¨œâù m¯–vw03p`Xfž¼ Ò«ÝW×éµâ¾mvCˆµ³è…rúÑ.çÔy˜otÊ×Z{8Zærn¦Åƒ¸íÌ&¼cÕ»ÒÓe©ÏbÜŸãQ€Ï(HöÛóHÀ§€®NwØ û4`$)Ü$Üòƒ'f);„MÕH'…>£z¢eù$%)‰./Sê-ï;ŒÄæ&ž÷öV,àâÒÀæ`A»ø0ä0ÏŠÄ|·Ÿ—‹Ê<ž U ·{†0þÜÑ4³ôÞXw–¢á+4yüBœ1ΚFÅLÊj;§1Ëç–]÷*|ÞÓL´m³‹$/m©ñ³1¹®yÏϬ …½ ú1Ú‘Èãsé \Ü(ÔSM%>yvtùæ.Ûóž&%"Äæ…Tk'ëI{�‡óI+×]t… 5Ä-ËÁ(yƒ‰=s ªçF\%ùçKñ%—WSÛ–jF&{y_ù+ÆHK5J®¨>ÌG¤Ú~ø¶Yçxžs#ZŠ¢Ã "õv€è׬*c¡@¼±×Ñ9�8s‡±D,ßs’f“6iPÆï±¶É+d”áál"nxèÒTú¤¹´°Ÿûoz4­ ×0l”ܽ;ünBŶÞs4¼šM~Ï‹í̦µ§Çœ¶1ß“¡É×ô$J¿Í¦,ǰ©L’m H¥Oœ6qm"Vwmzù&ÔqÔžÇ;ÏØ‰”’—D‰e Õj%R³œBŠñš•Ej—½ø$Úù‹è)ÄSˆÊJ+èÔÇAZ8#/Ú»r’8ÔÆr†'Üô̚ơáxz¯ÆPØŸ=q2î$©¡äg¨·Ê;¤}%ªõžr Ç.ZÍ„#Ì _ŽÃTMsçÕ³n…+¸¥t¸ba,˜^³çóÆOó¼ßN¢Ò4ê5`f Yr‰=l¨8æƒ)(׿¸µƒSÜ'n‘æRöÛÍiÙÓ··=úEù Å ðßß¡¬s ‘+Ða'ˆÄ¸r KBi; Ó‰P …f`r¥{‘ðj%–äD¸û5éʸ'É‹÷àݱ5r»mò $?I~ùf†(³ÚrŠÕ¡ý.A*üX.$ëâ³¼%µ’ç¶Ìò¥>2zÛGˆâ3Nfå1ïŽØ gYÀlÖä‰3ÔíùPž\çë ¼ÔM-g%Þ&“(ÕP˜KôåFIæ«WIÕ”ÂΕÄÝ á¡Ñ#–¥Oì™^C©$«€ÎãéN4˜4ìš;¾|\͉öDõu7ùÕ¼}ZÚƒð)CË ¡8¶&û8½S\MJƒÏäÀÌÐ;døn˜=Û X× åmÌÓ°Qk¾z÷`«¤Z¨"2Ý0ð¬ ?}s$Ëõ0=”bñ¬,w`9š²tˆ¨I[ëËä5umw¸—÷N;ÏH°Æ+¶ò5kH6O1¯ ¨;â0ÕâÚ¶3NûÙ¥M 5ÂÖSxBûÀÈ£Q·M¬²÷Ó2¹‡›mH2[-5ï κ3ÞvÎ*I{BðM Øâµ¨‡³†ËÙsÕäß…auø<©&&Ñæ Ä~ýüÌÂùᩯmÆ)øZMøØœ‰c‘‰"hJ›œö{ˆZÖ¤1œ s AUóf¶=/îÄw_,­9P·Él㎮F¸˜ñ½×þ^wÅ8uâ÷ßK­áÃt¾öBYf¡®}Àe÷HQ3gäY<CÐ\^òÙÏ, Á¨~K7‹£‚"±Êò–§2ø$òT /Ñú¥—Àá^ yŽÇ²Nû‹Í˜SôMÁ©u÷À׌´r¡1ª‡k…&•Ä—öxC3 ‰™)ŽcOºØuìîIgce—mˆ!sue=6€aÜz^2ò´‚í±'‹ïì›Öݶ‚Ε"±Ú§iH¼ wùÓXùVÔ©„šÞSë ºªÔÛKm~}F2±’zÁQ§  8JO‚T�òº3.û¶ö¬?œj.£ P¾{hQ郂M×iSlé’ëþ°Ù¤P‹ØüÆ‚Ám`ÂâRuRˆ!Û¬–{»ÞÔ¬Àí3j–Zz7kÝPZ® �6l³#‘4ÕæþªŠÎ´Œ×¶ä­wPdÙsŒ*ˆE@PÉÞC«Ýœ„‡xt*ÁA´ëOf R±3O,¨õõ¶E3l#iªÏÀn§fn?0ÊVYCÀâ¶|WLX—A´üÅÚÓÁ©ØcGí´ô£œÐ´Ï9 D8;Zïn‡»Ž¢N@´A{©'½êuœGË uó¨C¥'‘(NËóçªbÛ ËûªËK1v‰ï‹\¡^%ós!›0I|@ëwôñžª½‚Z/ñ:h»½‚$ÏçÚ«“cý ü4_ò³ueä‡üVŸ_+'¥§*ƒ+Ýq3ÞŒÐö‚?Fr|ˆÃºk}ŠXô,GPªñÊ ’UàFW¡ÒK«pVúLRµß¡ææàF³1A†3tráÊã–&´'à 9ðD 7ëhs’RÐH`^jŽ?î<J6*™ÎçýŒvZÙàéVuçÍC]Þ|Õ‘é3L†RT•‘KÚt¥¡rS]ŽK^h‘UðsÉ7½µ½ÅÉ¿˜f€/¦%;E^â3çš~ä1ñ”Ïb)]‰L‹£‚¦ '“@G€üß©y?AXD¼˜æÆÆóÒìBKe|™D¦`-(­”öž£UÊšR·ûÚ¨u8Ñë¨z…h[úÐå¤C]ªô,‡ŒA²6³‹+Èu׸6Kï…¾y‚§6 ´ðå–5÷H`ß6 ^%úQëbs!ªzñé±gx)×k°k×ÔßÁØ!Ëbx•QJ›GM ÿ‚Úβ(”¤fߢô—ÉfbkF©v¥¹[ø¶a^–nv¿§ðŽûÉz“hÕÚAb#Bª¤®lÚ{O`º*] 6Õ9!/áÑž<Ä’› ÷"æâ‰ÚDî¶ñè%g Žãí^/@'Þ#ÏUKó&Mê²çT+îq/·‚¢d±¦?„siJ»H{¶¾ Õ% —qJøÌ›yiªN¬Ab„Îâ&qÊós‹x{·A�F®iŸœN…RN• J‘”\;öt–¥` ¶œ´ÐúQº¾ƒØ ?Õ}ym¯/]‚Ê@Ÿ0#¿ô’í6OÞ(#3œ <ö]‘Ž›ñ‡uh(re§³k–*ô) ïDY¤œ4ÍN$¿.!îtØG,‘ò&l«_¶$‰  'òCMJ¸Wï¡€v?~DQ+œùU [B<u«×oÂ’€»25^¬kÉ >™¸º™õUAÍc@é§@•!~e ÇdjEžZe’Ì»­[ÞiKîš(É¡sfv» Ǥ!ÙJKqølŸHâ+}pV†—ùI?tØuE{'QQ Ò÷î½óª½½Ù'éYo&æ‘nx‡=¨÷ºhr êÀt7zMyØë<á¬*Ðq܃â¹êb+`Ös$"‚¤îÌŽÐ+4ƒ¾©æUòª¤zH´Ðù/'ÏÑßCí_P§d,+k>j—¾Î¶w@×ò�Ã鲊ŽÐbɼe6†àžk~+ §ñzï„Çy´X½‰9ÖhQOJ@b͹:%\ЈÄ,ìJžr,m½½Au•~XÒoñ•xÔµÁeÍ$¸ŽÉ³Uƒ¨AèPp{‡¢—#õæ9CÏõtÔjž`L‘R’ƒ‡f‘t¿¸ÐpPĆ‘|à0R/±]³†)DŽ^‰÷{ …›)(üEu+ɶ½Õ Á-XW)¤#¢ñ#H‹.'Â"öôQƒt0Œ\;﫳$p}7€èoD ^;t2‚2©XìÐM„˜Ë£‹âñE¬ÅH8HO¯ë° G'ئÝJô5¾ˆ@æ}çâoª UAEm[ðnáÄQVZ­5†À�o�ÙØSÞñ‡M(²h þŠv©y IŸwU…awWâd«+ÚÏcLŽž¥r#C‹ö’Ж紺Öôòɰ¹Cq²Í›¶P·ÀÀàÖo`"“­ªV'æ‹®u¶¢ue6Ï£“8{EYGÎŽü ø…C%†M骥Û=s*«‰H]²s:|oªuŒ¨¤g!ÈìˆÁÔð޹ÑIåd;.+!ƒµÔfH½_…Õbx • ËØ3¿šì¥â kŸ¥AÓt-Èyg#<i¨Â[8xI�Ø›¡Ô®If·-±Øñ ìJ†Ÿìcx-ÏÂó½=éÎz# ²2%IÚ/¡¦ð#¿ž§ûÈJ&Ä_fOóÄó�1 }#—BÆ8Í\¾çŠ”™=UܸH±Ì€‹šjoô¶P)ø±\lT¶×ôƒ­í~Õ:}s$9ÕÅdf©wÜ %á(†yžïM¬Ícy|~'"‰)bŠWK3ªï=p‚y[ðh,E§,2­û=† yÆò∡.²uz`|á“jÔ/ªA»jÕ68ÜàmŽ6ˆ%¦„³yqqמdØÆk_¦12|brMéÎòpL‰ÎÏ-ž[ºD:Â÷øãËz.yýÄÔ¼B̶N÷À41žÉ³Ø˜.Jw© ]‡TO¥ „>¤ï]Vei[Id<]Xz™ì”µ¢Šº{¸äÏpiéi?‰JÞ &QÒ´²;|§›œ ‹}‹ú6Ð0 Ï2´kV®:äM¬˜öj^<zùÖr]IÞ$혗å«75olĪîY‘”I¿óBLwIÇ�ÐÉÍSªHyô S‰•Ñ.8…Œ0øÈ­²g<õ§¹ÎãÖ$¨Æ‡5Oñòdç5ÐËÐl\ð�¶0¾Ò™D| cïh¢ÞõçôÖ'ºôPòbé•g[9CLóÎROË„·š€ïð¨û3 z¹~R­p©X‰–bé)ϰ©ã*egè™ßš¯t#††\ÊévñY“ˆP!=N¬|ˆ¡}mó`ƒ^Õ!/ ÷¹+ä+.á·ì 8qÓZ>°˜™"±;~ûFg–Î5%2;ñöæ4S™3ãpÞ"{aÖ¹v¶4 ù‹êÖÁñÙi%ääiVžÔùl*Xi»¶y¬m>¢€‡U«Pi,'ŠŽ€SËfœ¹¯{lò­6+I1×{«ÖUà.BZúÊ ˆ/[Ʊ煌çƒkQZ_G™5Ø\®—u(¦±ùŠ Ã’g›Mîõ]±Àú£+0*6ÓÇ ÈÊ4"i_s8'Aí.í`Ë­ œÃöÀDr{xìsÏÆöÁæã³GmÁ{³£mǺÞᎱ",Ê“Y-]‚Â>Uy“ôt:–Ï»ÓkKCó(_£4Óê¹5íâà[»}¸xz¡âGKÉôP؉»GkÃSïÊ7µy¥<µû½‡Üð>±&þÂú°…¼Ïì…ØðxŽTøY›¡Æ,”ºÏÑ{EÓžRwR¦˜gâÔW+çYùØiG0׫3®ê76há‹Ï ¢`LÖZâÍëîi,‚64.^ Ê'È^R–îË%0[7·Ðdž꠨´Ýéý¼1ÝŸ@¾*yÏ�n8gFBbIä=›LÐj×'~Y]{s%ÕîaþÆù5xæ´6ŸöÓS9]ìH¸@[ΧV’oÜØ‘g5­âõÈË £Gq vï¥5…{Ř<bhܪÍç’‰@!àZÅQ5÷ªQÙ_´éˆ„n¢¼fc-¾MÐJsžèì’ð$®ÌÑ!”ówFÃ%¤À»  ú˜o@©ÐŸˆ7Þ(Ž›ËT�ŸLÁkÞ+Åbb"óT±J7®Óa!¤- VñBö¢>ÃzöÌI2Ä¢‚³ä.�4oÖSÑÕ@øùD”-VÂó *d¨…É+cztOéäYg;eÊrÑ\SÙ;9FàJ¼Ux çËæá "#6;Ô¯ã zóe%Ñ¡‡Ù»\1yL»UôÎÆ8ì ÐkD~]· víÑ ›­Ö¹Ñ& LƒÒKiÈÒqw™Ây‚ohyä-¾ºqBŠ©LKªS�‚ÀU² 'xRˆ§ïÉ\Û늴“~}ü"`}Hã2ª ¯×”µµÒ¥öæ]l¯{ÆëÚîw~ê<ëÖÉ{ ŒõeI™«K%�;‰xo‹ŒW<6Òr‚M¾ 6Ì= ¥´Å..òÀ†aKdí$ÏyÝšucsåVÞIBÏÍÝ— ;«cc‡I)_iâ¹Øj�¼YkÌ©´4;·ýòÎjÉ—Ÿ`s6ØsxTŽ wHyÅ]XÁgˆ‘z”Å(ÖeM—ÅèÁ/Á„Þë=Oe¡wûZOµe÷ÜTåÛ‚¸ËêlW[(ÐérXÛ\45÷O®}q÷Ò¶G°OÅèÜq¼€¹2‡œ\›zŦøØÐW/Üa…I1æ2­¤MËž@+?¯Ã¾­9 È'Ü5‡ æÚÜä8y•zÊWH2g¬×™„ Ù)ý ˜iÌÈ­Kï‹5…dÆN;tül_Ñ6S^_Ìöô[7[;FЄz0ˆAðˆÓ‚'Îf)›f2A;;¿¾Æ–]‡'T3Ïf4Q-(—Æõ•±ÊÐúO°mßU1GÑ¡2© nŸ2]yW1†ÆÕ!´¤ö[+Ì¡a|çiÞ=rœ•ÀB±[ïŒJE7ôOJ¯–Ž5³‘7ôÞÖØ¥„½óÚ­Ly$ÞX™ýÊgmp¹Œ^ƒ ÇÓ¾Ùwð"ï¶_Xä¾F]9âô<·; [šâ‘^´ålQ™Gº¯tjJàšªš_Ó>“CÃñm¥fz‰¤Å2¯ñ•îÛ‹¾Šò’º4N´x[µˆêR–¤{HML¼¡ñ*½,`ýõ¢êLYûóYT6æÊB5~ôP4”¥9×ìKC:Ài eSd°Ê7Í'8éÁFÆü<h­D$e¦˜ÈM¸[Æf{Çî>ad(}@lÓ3MWÄbìÓ‚Ñ/¶ÝÍÚŒbªöÊ£eù"òôÉ2àv®žF«u.tpeß-|Mö�£û• £Ž&ñ<ä=ÀÖÇ~´òBÌ/žzÓ㽉'´’½3ò9Ÿœ:0yU’$ ˆ6/ e.Ÿ¿Qv¾]`zlÊ$HÃ8 Ì•êGöxŒž^÷ñÙ“Ó¾œ¤ÇÁ„u#ø7+Ã'Åê&V”‹{ßKL[D5€«€~³ïÅ\ÅæS¥§ì`x6„ #SO Jš‹8'WHëhHm“ X0HòÓI&ån¢z?DyˆxÚbç ˳azÊâlþ^0¢…»±c\å¼¼ ²ybf¡ª°šŽ-4á)Ž$§?ztz&G Óß],AJÎme6‡P €n½–\öaÞfÃÃÀc}úž?'¾@1z«îÜêT@(¸² ¸‚Pü°ÝUòÎKKN¢K)&-6¬u¨üR['ß)<Œ¬Î6uJÇíS9A$|c^ÝôJj`ƒh[ÇëÂ:„Öy†<÷"+îTÀ+ò«ë÷Ê ^O„J"Òó¿È.uCô8¡Íë†'ï,oÊÁ´¥ô-Í1ð½Á‡œ<+ö„1È6Ž[-E¸ÚiÃú%¶Z´#uLª0©#+V@ÜÛAj1$÷dÜ;½¶7wžùºȽ;v¤/ Nâ…,Dßëñâ¡TA·¾çN^á¸%•~¶V/E Ýs¸Yä¶·›:œbôEöâLî²ôbL$ú;ØxúÀ]O‘$5}\[�ÜÖw¡‡"@©t`(eÁòÁ¤Í>‡ø´¸r]X)€5.±ÐEl_áCÝñ;¬Ƈ¶×4v>IÔ«³ðÄ‘</ï8tJY•ÒÕébÈ5Kõ¯Eogõ 4O øÁkª]h·Ó~1pI{voj˜�‹“õ½gRÒuœÓ*€×t> Ž|®™ùÒ¯D|³6Õ [¯àÙlJã›4àåcœkÚðý<ãwÃù¶&žA÷k7JÆæ†¹‡ØtRÖ^5mÕœñxê‘iä{o½š ùR/O L²ÒBÝLÝâ"#¦öŠÀ,nÒS– +mÞW•/ë #ʳj÷Ûu!¯Ê y.dõJ2«zÁÏÐBÜÙõ¸ÞÐÈiL=&‚É÷Ü÷=—î Àà�2ˆ—ñ΀ýžìK)øäELýØ�®ÖΠF³ærIg:¤“-ð½ âQ£ÀÖû&Û?É6Ý{B0Ê’=¢¼adŸÄ²´ GÎ Àò«eŠºz³rÇç7°ª/»Ó¨‡¢ƒÅ©0((E¬¥ð¡PØ úU o,m>‡h*¹ÞßiaY䈩µ+ãaë±{âôŠ ¤î¤Eg>&â›QƒyO® AO&¨_°ó¼¼®\ZÆl_5‰{Ê´Ö#ág"µ°ÓàæÛõ˜ާ÷ö58ðÓ“—øl[ç=š“dãf«¶"(vKÕq‘¥û íÝ9gäìÊ»Kš±€e <H»Õ[ð=£¢”ŽóÚ2mP`Åžše×s !Ô(VEa܆ATÊ=’ `䈀† #ÏO4CS•¯Ôàâ<¼Š^Uw 76âT&ÔÆ—»Žú¶;¢u¨ñ9w½(²£-—4—Í’Hzbov¶Í{ÈÀ—ÚÐÇü³-]µ×»i5R¨÷\HLahù½êrwš‡ž-LXµ²òý=qYc.•Ý|üžÝåÝ1©–æŒ8.S²¶<•n:xsüúe¾‹Œf³QYÙZ}ÜJ¬Â\a›öY°WÉJ;O=b{—ÂíqïVÜË×SÛûHYª$P,0Rs¼ìê÷\ÃæÌ¥€ö˜ j«Føá®ÄÜC!(÷}PóL«y` :r¹éj‘trVOÕ–z¤ý¤œŽÒõFj”ðRoÙÔ÷|L–›QoX LÔ瘈yêLyá ¨3!,Ç€«÷Ë:lpUªé¾x„¦“/^$ß\ n{%ò:(û ’–•vã\Pʨ4nU»*!9mnžgçDæ‡õÊ´`f7‚8}a¦yµb.n¢j ê®N/²na›=œ¨‚çv2/Ó”” I–’!)+umPMؽ‚ÑÔ™£¨|švŽÏ_€«äÄv›Vµ~¢-ßKÇ9B¡K>~bíÆ(3fkþ‚dÞ˜nHå%•0%õ{÷Ñ%úØÞ9=„'z»Ü+ kp~Ä.¡¢O½â9^Ë–öÓwâ´G…Ѫ–¼‘`ЉÌM°óz¥(Í»< 'Lk“Å2jÝÝóRA»këá&^€T‚¡é*L–ù©#ìë1øJÈÁ6¡=£ ƒn}„b:A½ÏÏú…%ëœDaéÇ/b¶Óõ‘<{ýÊtâùmúÖ#Aù‹mÅÒ…À{éµ÷Ü•íRä#‘W¸g{éê‘« J' ÛǾΠ¥ÊìóD€õÒÈóÄÌoËËÉ*âJa•ÓimÙÑŽ±ÀÆ.$F²åé«R·„äUÄz¦TauÓº„´³xnÜïéÓ,ÞT|•¸^!âG<Ø@-ö°PdwF7œ[ú«åG,8çz´[6創ÎB™2{îyË{§Þ ˜A{1?NSòÇ}ÈŽÎ/c_"ø¼)-'•³§/ÄÙ'©ÅDJ€+ÄM¤`v76ç!wJEhVhû=Žj$E¿äõÒ½7°S¦“Î[ÜÃ'¦,(ǽ4ûÄ&^½š[ß—¶€È@HiO.·‹C%àE&ÈAË&hÀ>àF‘Tvà^bx1�˜xÖt¨ëˆ7d’zEA÷®± Õô¹Û¾ºGvóôy¼<(rc¸¨ø„ƒâ1X Z°(¾Lxf¨ E̪ʗ³DAðt;Ń›·ß¨Ú» Q43ÈîÇšÖ‚°xžáµ³Ú©dhøÎ^À\ä[ÖkiP}鞨iû>A[²©³ d—RýX˜EJÍ-pÁÄéõ¶»ò -®0ª¤èx²:¯’Ίn >l8�`[í¦Çòd‚í@]ØÉ †¼§«Tì,ùÖzT ^4Ô`ùÓfb(B‚žCjV*„»¥Q,=ØKÒ–·x‚C4¿gmå/¶ß¢<qÝ*iω&Aé[´pˆ÷ÚÒOË«ê õyïeÒk¨‘xè/)Ùõ½«×À ÆÑnÉX¤éÅ,òbðŽ1¹Hƒ•n0¢n{Xž±‰žH¢nÄËŽ`ÁÜ+Ê‹›G£c'Wmg) #ÖºÕ¯^¡0΂½Än ³+¸ÂŠGv…„ÞÉÑÁnYòB•(ñå k‡eÍž–ès˜I¤ôç ¥*:EFóôõ¦9ê»3•žÁ—…ö¼‚aP;÷Ïy›W”(ÂbÉ$w|Þ’8ºYAŒì­ˆ÷ÁSÒ›{I ÌòpÞ%tj¼ë,‰ Ø¡¤™÷ŽMýD©¦u›ÇëGñ\©‰h6~©íÇwKÔˆÞlÌj�Ò$pfa85ñÄqe§ù¨öµâ #O2ÌÜ<'!«¨y[èóº×Mó¸‰|R$d©™ÃonÖŸÂT ×SO÷–KÃÝ-€·î/ò–ëY‰O>y;Wäu’Ò]›+G;ÛÈL7¥ù°\– hN}ç%ð’²G¡44¦P1¿Ÿ=jxC`¨¸r*ã+Œ+-6Q —U¡ÛOòɦWTæN³Ø>ÒW 4¥ qÅd2ä ½€‹–øp_½iîÝ ÅÄÀxüFÈx”{šÌU·óu`m¸)ùcdj{pÜï ¸êÄA×,¬p±-Œ¯@» '¶ÛÍÙ–¾MH kÝ4j³Á ± …Q#Ý’Ãáz ¢E¥6Ñôf^¼$xHqÅãÁÓ»4<ÖU›ÇÀ7³çÖâõ0xNF¹*ŽDS‹Òê²VÙ­P§úå|6<ÛG‡Ï©ÏÄDÑ£°¶¯Ýg¢á1&87Âi'…ªq‰Ø–ÇUè¥!wŠ*±ÏÔßUÂkâ© Óq_½7á·æ’<÷ŒºÆIQi¡) ivËP„®0‡emÅÎ?ÊlÍ—� ý¬‘½sñn£/¸ûùhA™X—Õ2Ãö@콂’x`,¨®‡Id@Aä�#^½–ú´ÑÈv…­‹Íb=üVÎsíkÇd35´‚ðFËž Ê“!µÆ Šp‡v‹0C €€ñ´äg?Í€“1deÏpEñÍ 8†´¯V¾[ˆèKD]9LºôÔIàÊé⥑ه7ÍàÍbŽ ™m`%:úð:¥×‹zV qÐÌvâRá ã¬Ï´˜øõÈå˜7üE÷½œÉä甊}Ï›Bßc¶ R¦åÞ§ÅÃÄǘ]@yk¹UþæÄƒÀ¯|OülhòHP݈+COr‡ÁbŽx%#dw›ô騖&ÂØÍ j¬V­‡¼Gê­s^]‹ !u(î’xöÆS±û{«ˆIƒÈh.¢}kmnÍS(â‰÷"é^\�áá2Á‰uöàÞÐ(Œ÷<ÎÁ;[ƒÐ sKÁ.Sçq`¸V5„Ö7.)37óNDAA׎ÐÉÕ†iÀ®o¾·Oh™æ8*ð»! Ó ì‡yõÉ]M¼Ös‘‰E‹_ å†æDß'¸Kƒv•¡õòŒ4 ‹öðú•O/+& ¬ºË.dzz\5óÄÒ_ªgÈ ÕEÏbKVŽA¯åƒ2­),ß’÷Fly²<D™á.aóí‘ÙKf]êB<p"}.i8ñ:Õú´»}Ë—™GÀ7áI–DÞY,˜Þ ôp˜…Gµ¾·ÇXL/Ôq’<_õÝåË ˆ…d7ÇÄjx·ï梬" ßEå{¸RHOr½C{Ã^ýˆcƒUÉÎ ²i¼Ä Ö7a=w±ç¯›¬/^ÀZ$-D¾JËŒn‘Ì’Çu6&†óvšÄ÷:–æ5ÎãiçÍ<‘A#Ézî )—<Gú`Y=nï¥Eªu‘G¼zÑȇ’ ÏÜò}ÒíðE·;ƒz–ú\:À^8H¡ˆö@[Bu Ѧ¤I½Õ`}X¥Ü¦Ov硞àCߟÅ×IY œÈþÔEîɲƒ—™$®'½¶öòÑ„(bœWÏ º“W-Þ�¤ LSuÙµ1Nv¢!?œŒè^=3CŠ¥léS)†1xð¤‡Ð¥*ž¶�Mžw5YZÆŠpb¨>`ÖÔƒD®D‘Ò ©Q²2i0 R˜‚[ŽMoZ¨$ É;˜ \gé³øsî.íΜØ)+õ'*bì ¸ï‘@ó¥Ô㇠ò r4gÏÆWºw’D'´«Ïð-FxaœÃ{uð¨£(ED=4‘)÷”.DÕHŽ<ŽˆÁíeZ©æ‘WEB!©Oy=—CÚ╽l>ÉLÀ´T=¦ä”¢È$UŸ÷,²Š›TB»ß†l" XVBcÕø^й°:.bvJ†F {ôðë9ŃÉWÊâwoÛ:Kv ßɶò wµ×„…Úõ¾¼HC; œáÈëçWÅü,PÆ W ßxÃf–bËȸ!ÀšxPf j,S…dX’…£:§%iEÛœeEÒŒ3? †4Ô¨Žð]ȇï±dË;–Š´y”Ý ñ”¸å1>¤µ£µ»“CZ*Ä8n=éÄñˆ{Áí[ð¼öl çðÁ+ë0 ²Gz|ZÞs•£í£Wb„)ÌXìa××E!¤³Ù‡–I¶5à[8f‚Þ©|Ãz™‰ñ‚ËÝáí-é:AT“à剗/,õd§ X‡çNõsÃÛ0Jî‡syŒáÀ“ÙYØH¼*!JeFn¥Söòy’æÀk^‚ëi&ï ƒx ÜS­ñš¤o§y¡Ï»,ÔcÛ$€{4Ïu +sßúKÛD¸yÚ‘v5SþäÞóÀ;ÂæÒÇOýj='•#áoÿœ»Y¹jrȤ¦'ü•JFÅKⶃÝ#à*ê œ~xÕã-×,®ž{.¥å¯*)%ˆ�wÔÅu[¶É®ÈÅR“b 刦ûÅ­âÉb%Üézqvq뤱×Ú½a/^ð]ú¾8;[ç|¯Ÿ«ºIV’¾™À�ßX(5–¸¬Ò7ÞZUöÆ÷±¿†ˆ©~pAwê¥9;7l6úÄ ãDPœíž.q%”ˆ>èm±­¨‡ùÌ7ЃwI÷%ð_|“aJ§'l¾\ÁC¿;^pv!ºøB` m_-ÀEÏâÕÛÌgû æ  |K¬¸Ÿ^­½&ö+×xiÉœL(ñÊœòԟs–ÌàkRÆ—ÉÞ` ¿®ƒÒÑ“€hKE„wNýö­xª½óM€vÙW»HX ѧñ=ïi„;pÕ‹k!J„“E%8Ì}iç)µ‹SþŽQ..I» UóeQ§õ.×tƒÛé ¡ LŠ˜ —…MwVÖY >É—=¯/Lº<Ü�}OGº´ ˜'XqH `WŽáQŒnÓp™öôóÚÍç»|oyl ´t°Â=³V¨ÀXí5ŽqëÔ£èór/h÷d¬ a¬äyY÷ü<hôÅv=k 4zB—DöræÜk´GÓ´Èà™oŒ6E³²Ù¬ìhÜÀ¼ðv�oÑn7!-8Oò^¶_ì{«àø2œïv)BØjî˜hÆ™(0bY›¸Áxöš6Ä[B˜WSóðØÒ|pbß2cD7GÙPÆR'lúÖ ©\-+&’ûÛ”{^ÙN¢]Ë,§6]¬¹ƒv|ឃ½Wl.¯W@`ê@ñàV‡?hb~móË+,³v ßš¤ôËâ}†›Œ·¯Ž šÍn––Àæ$—ž™]å+ÆçõðpAÄÑ{•ã`x@M…Ø2ÊoËç“ïÐÏÙ»|Ô«<MìÑ-9Jª'v´d>,ÆÙiçxk*$ƒøæ½ÞšX”ª)RÔ0Mo°ëcÄ“Ój=[(±ì4ï& H½(wñìh‹B•;âUU3y¸/NŒje·) 1:"Ê=2««ÈÝÖ<¤<ò·ÎõĤW9êpÜÄR´oûéIÃ<[œ7õ|ñíEIÃ1ðéÛ9\{­%‘Ü]U´—޽-æ C\mR å0&GT˜Gò´Ù\Öée¿…ò¿�Ç '똾Æ'£pûP0KšX#ÞP¿È¥P#8Ÿ4€AÞàœgš™à¸SäÆ9{#æõ”£ûÒ†N—à"wžE°‡ $—÷«z"Øêã>ýöi–='¸q‡{¡Ê—u uAv$ó¶z÷±µp½µŠ ±ƒ„”Œ¤ÉìUCÑ÷2`ÒÞ³uI~H‚u‰õBxuáà´ŸGÆÌT­é!I ÉQ£iq4ÀlºÜÁ²€ß ,ˆåññÐÜK”¹FÍê<p@ôZÌ4hKäIÆ Erä~Qº6µÉ(7¼–í÷XjIªa@ý%ß]s84á�¾1¤±+vUcáä®ÖÞ'‚`¤¶Ä¢&�”ío’4M÷çéy+¡ô³„wu5­g5î)¡µéˆgò’Ø•”VYè<4Ë¡¨&ìBàù”úíp apź8ʪMvâîj¹?~ÁòÖM<oìM¿Å pŲA‘€ä­CÆOÔÚÜe3ë&jÓ•ùÖ§x0ÐíŽõ¹OI£ø›»5˜ÔDZ¤ë/¦"âLÛˆE”_«6±¡Æ^ÎÎóÆç£É×Y*ï¤dö”x7ŽÍnÛOÄß[#œ;-Ç—"MÍú†dCSÞòj?†Sè î²æ v¤ Ar*9Öœ‰ ›ö,Í5:»<Ý[ªAœ¨Ç_€ ðàZ€nÌzO} «¡ûDi¢Ñù9kµOø`GMŒ^{]¿:õt˜›/ãñƒ<“ ¨Ù§it®vâéð`Ξó¸Œ>:¤ Ù”[)¾@ Ïn5¯Fe;­™ÃlæM{éZbÝH7OñòmP ³ˆ³/yÁf{›Þ¾nxëJ™<wÌS·£³ìËG¡ì¶}ý(ÉÈìÞ Ð+2’œeÅÂ'â"œîO;úäÕ˜Ú‰=tÞMÌz'og L›]þ"\Ðè¦ãR() nê(‹ßÎ>Ö•(2ˆ‡Ñ%v«ìЬm‚ÏÕÕµçgòm­ OJ·HÌ7a¯YaCjà–(Vª=PŒ1MTÇøëõE¯XÂÕæ¦¡$—#Á&¢.T¥¤L^Wˆv×à{.¯’ÒAÑ%´Ý-¤ÃèüNDÁêœÊɳd€q]G̹žìì¢Â]èC„i΋ŠkÁˆƒŽD`Ž–R*qVdc‚Gµ†°Å”ÁÔÖöÌt³ nïÙ ³­÷†“êÚ î3颣м2S€RV³K|U…1ɤä~Lo[­#Íü½ì”Rçš–ÊiQJðŠèøŠì¸6hëÞ³ ”×óÆ|BÖ´ÃÍÓa(—ç¬W4ýÜô-âã…\! ýDYç¡Ê4*·œÙŽ`<–!É÷èܺ+mÞFm„™!lhØ>r}ì…$�¤wô 8AW©É"À(ÆúcÝu¸HHzÍåP‘/¬Yªñ`ƒ”€E¸´v «°ÌŸAµ,ã•è†3^á:«à£|otˆ¬]Â`.h %VObËTû b9·‹«ÌâÕ»z 2„@‡É[š°pZcþ˜Þ8{A;´'?w¯¶ÁJ%àN´6•xén›A‘Í®êˆp;`øØ¢õJ1¼ŽºˆH·ZQð“pü^]†<NbC®áÚgížoÁi'­³…ûAŒÕ¨ÁtOH¦<‘`ÖâIqðpt;3NM qãIÔ:©FZ´‹lúxÌ<ojSœØ†ÞØ0 ãG‰µ¹ Ô3†;77¬Œ¿T­Æ §¥ÝX/,!èA{AÖ±¡,u²ïűð4ÁëPUyedàOðï•ër´à«2ñzB·„‡ Rõ^?CŠÑnÇÃÜÓœf)Xw²ô·ÂÒ'6"Ôˆ6ôºKd“üBÆ›.Z’˜ê½û ñ™*ü\„[53&D#OÞ¾IfX(Ì÷r˜“XS[ÐÈå60ÆSÏiJ5ÕE§È²9ÂÊ UYÙ9Mó­8óñ笘ðSýi‘ͤi쨔í‚ ˜ÝNªÇx•¼ôxˆd÷QÝ!1èÙ)A×cçQÛ{YÛ£&$@�öÄIK”Ñ*á¾q.|’OsÙ³h˜¸jµÊ2ÍÏç¢åÙeUà8“ŸÎ*=e BÆ´»x‡:8Oûõ‡ÂZ—_WàÞ™¡„¸N?`ÑELmIVÔ,2±ÑˆºÂ}Ƥá¯_Üã9m¼Ô盎Ö÷J3ßÖ ¯A—ä­{[ÐÉÝ/lØñ˜޳èwm wO&pm‚'\ü<†¼8�V§tfÎÆ!Gk'. n«s_¾zÀt‘@�…¨”'åDDÚ æžÚrΫÉgÏqø*ųv8vï…Ëö¦-½¸JXOPHŽ� °ÁŒ§.uÏò¢B.ß*§9LÇÝåØÄÃ� A·à;˜”è֜ؗc\Sßž÷Í{ïÜÈ|%º™åja•ÈÅîËÝx$*žǦ›Ta=n}™Ð"+Ò¨0ºÌà6Ð2 n°³„`7ˆšJ¯$º|µ¼ã6v!ÓØCs»cŠy¯èr½èÁc{zÙ¤ë>G6Ž(o 0Þ|"Nð…8X€¶…•«e‹éƽn;§#*Îë:ŠWñ0 ÄyR“¡ÉêÑBaÙ1Róa9±ÃdГBÚ&ƒ€”|M’ªÈÇsšMzoß;sxç½d¡FhÏñ€V-_ñ9§áa ‘/4å„á³wzj¤Ä×›>˜q.hp9.¡jHàI¿bLE“aµ¯AB9½çª'ÏÙ.úÔ÷ÞÒU WGð,= rŠ–ÝTßfÆëÊÔ\¾» ¯X©¦á™À»¸Iž1+mÎÀ¼Êø‹ñ—À¦íKì vp¡(Š=pº"UoÇ`(GŽœ�óOM‚C>ìDÜ]&ÒGÏáIà 9+Y Å.¿¢À!Àædn}ž¹’ÀÒȸ¨%J×èñîEGUê íU_r`$¶Â(ô>ê=POt¼”~Ædïö©w&ª»µä ¹×€jãÐã;}™¦kL'ÓwŠÐ™ï9iš‹®¬ÊM]ØÝ;8tÙ·xc¸�€4NoÌ÷9vWD˜Þ¨«#’ÓKë霮gß… ³k {G÷´•RäE¯ƒ5`®A+¾Ìîmí|vÔ¡\DÂV­Ad<"–Õ¸6Bø e·() ´íq¿ÝKatºÅ G‹ðòä¶|g>4Ðs¦Y'Žê1X•‹g;/=Þ¨[?Þ†r†Ïl2(}sÛÄÍM50ϱÂé1Œá½»çOscÝvϦó¶WNlYŒí­ùc|tA”%y³öÀ´Ô–YBw¨Úm‘µ²{óp©k=Ø_ÉBõ“9ëçgqEmPóAÑÀê=}VÔ*Ù¦D/„ˆßËÜzœ”hÜñRã5ºmX½ºäö޶AJã#Ý3Þ]âyÇ$Ý ùR8èU(ð³Ó¢~X€ðêÅ{áZ ECZ"|y6%,œèé#´éÌrêÌ•ö ±ùjÑ°Š¥í™‰¼µoÆý‹qqßà ÎjB9òÊDZÌzFÈ×\aeö:Ó¢ #Y(‡Ë)óÖ:ËÓ-ë®ñ±rNÍ='- /O ÃÒÈ~ ’¡O6ãd2 àÞ–ù“jaE¬ åÐ!oo÷©YSo-8цh*¿W@­ÞœôH¨ßÅ¢`2jqè#±2 ÏO‹G:Î U¨-•#­z§«»õhÀHª^7†Vš¶ifBb@á ªG¼ÊŒ»MTB5{,^ÛFû¢ã¨‘ð™ßfñšæ_»z›¨îœa ð‹U§tFq)݃¸ZÖ´'xÄÓµ´DÄû¸›ÞR»Äú+/ˆE¹“[!’„7è=èFî$©à]ƒmò\g^¾™ÊÁšˆð­ÍÞèZ}ÍP²óžÊKÆ~/Ø×iižÉ,¥÷;lÌÍ5�Øë»˜|·ÀD¹‰PŽ¶Ý»ÐDlk3²Td–†(uÒÉõ6eÛ:[º¦-”©JØŒ"!DÛ^tˆÄå¾c 1å=· ŽæK¨ñ]³‰¸‡Ä†0åEÆ…çnžcÜç~„Y-(¯HÕËâœxŒ›ñ¥j’É;•²ïC§–MíÐ4ŒÛ–ë™R ± Ö½ìC¦ ÓYÂì-B|º‘™uôÐ@ÛÔR•¨Õt“µ j)í"À’k”ëðÑí"ÊSšÆ'ªgúŽ»(òu—ºO¬1ÙÑPæ !HǼÆXàS%g\×P™’(S^tµ‹£âºÖÆWÕàÍSÎ/œ–”ΤW—ø¬nO¦ì£ ìô¾M®dV0£)èð°Q³\9 ›øõVß3‘4ÊëF×–!�··EV` ðRo98§³=*õ] sSi€?— 6Ôŧ…õ·–í9‰oË „‹Ö!h‰®V(;V¼ñ¦yj©LZö•)ÌÓ{”äzyb \ÚD;„�º I†‡ŒrΧ•Ÿ?ýœÇ=$Ò–+sÝ8ÈßSC ^ŠftSÖÅÀ<ÜZÄšRG²V}„`÷Þ4jÐâV;äl¾*&|%àa—�B¢;Œ%pæ'ä"í¨ž\ªz½4IÅ¢cik–%GW¸P«á†´¡ÏPÂß ˜2ærñÆ´=‚wÙ˜‹x‰çmÁxÝN›El9S¢KúœÙ6F!VJ¡\U4sëpòµ'=›à¥È[ÖzwÈi´¹õŽ9‡ç\\uöø ›cB=1¯ŽÐv ƒÂGQÎ1vùRß.*âÆö^ºŸÃ\çøXŽÆjzDð »ä"cœo¬zØáh<C³ÅïDà´&²òéÉa{IÕHIäV2­šp>@ÍB5W'Ù|üê9‚”d­Zrk;ÞÊL7æ¼ÍQ’¢€‡7r¸‡~œ¹(»ÝTz’üž®Ô¾›#@Šwz´’pŽ^û˜*ŠÔÚ¡ìÞÃ¥Wbñ†‘uj¼òéÓA ä¹'ÝW»«T÷ཙ!Eä]ƒHeÜnÂÄíõ/’#T–½<+3©(ŸÙº½DwR’­¾ì§úʧZN×¢TgŒWÖkä£>N]nÆyL"?®‹êiÄιÉkc¹Ÿ¦—WÇ r rÝþ®ôgIJ­E®Ø¼e’‡;Ýø sË´V¸wÎU…_ØÃÞedî†õì‹]Ê#ÓâI%Å}ê}0A$ýÂZ1Ý6½aOÙÓ¸ ÷µìPkO™êú«V§ˆÂwê=)~ªàÎ&ìÈx‹S^Má3Ã= 5> ÝÛ'@…œ–läoW«*]Ÿp¹§_¡ ÛB¶s/lôœ=;¥FÙyÉ©—`à8I@ê Aop5´dÃI0Õü±Åj%ù{Ú/–Lª\k›"pœöŠ¡o5\‚yçúRvÛ V5FÍ:w‘áMjUɬÁËîÝÌ‚qÎ÷bÆÁƒBõ¥À½êõˆ%2¹™ZùžÉ™¿(ÇDz´=âú<$YpžG>ÌŠèÛƒ‘Ž»N\]}gúJù*ŠÍ¾öý]öÖËè“›xXæ±j›tÏ—„­Û®cJï½Äå�kå ¢™¤·NöêÁ/ÂÂÉi~ @JSRÂR(±x‡Ó©[ö¸Üèñ+gj±Íë›tÙ*ö½G¡¡ƒO‚žôK§¼Ï°iLèpü!ë\pHCj‹ÕÅ®Ù:\˜[î’Õâ-’ötìy¼ä´éª~jËpË‹»Å´I’øç\ŽREœDvÌæÛ£Å—ýðèM̾ N1ׯ–¦eë ¦Ãçfbò"Y¨¥8hÒ“GrŸÖÑ¢³V­ô‚1%f¸ ’n‚å<7¶–9—Æ´ë~ ’<]x 4qǹó¼eqT¤_Û”g¤6@.Õ+–Ûéô~Eý4Ò*<ó©�JÆ»÷ hÀ¹(-[úº=%q<Âã2å õ\˜åM¤¾§�ÛÍ›{1Ë­InÍ<°ìªÝ¾|Þ³òÐvñMjêd R• f Û8ðFßD'Cfõ+ÆÙ‹ž1êHÄI^éç:<Ï|•ØÑ‹æiñ]é æPÇÅPz5§]Ùs²x°á} ¯‰°¬c”õ•7åá †¤£5l¸®Ïj#>Ã,°gÜ-kK´µßh$¤�|Du]Ð3sø3ÛÛýâ±êÜ”ÄÝÅŠÓFYœÄó6E’ë§wÆ ¯¯Ô¥ ¢î¸éñ‘ÑDa¥&‰ÂgåÞ§3 [êúr˜Ê8�$¥SŽÜëÁK¸¯;«$R)m¤"q†'6Ùö¤7'VÁmžgöð úXC„º+”>öAyآŧ%mføÌ0xx/&æBI^9�Äc\$jä Œ„gíN”ô–M êÉÀ¤Q$æ>Š‹Øê&½ïŠV{ïW<ä¡2ØTE·@[SÎMÕu¯OÌ…¾0ÔÚœÊÂái=÷òfnÁuÕ9P ºæšrnbëñòÛöÖçwš÷ðø‰ŒÃÙ£0Vy3£=³l®´}`hº¨X&højJÔò­k ¦§…ä‘^ŵ¶J0öLAÀõЃl!õ,VÐ뮌H*@Þ…~|PäŽÙðt‰k=vK{"-- ¯ûŽu!VÄÖ‰÷@‹ÇÔdóÅÁ’ŸÉ¾^©7[½ –:Î>j—Vø¨ ËÍoDÄœ};ñj2x¸þœÍ-1ûžöK¥$>KZD¶£˜r×÷¢­×2R×_•B³‰Ø[åe ; zkJçYÚöiÞà<mŒ�©Jd{hî0„&7Ö"¦GŒÁ–µ]|5ÊÎÚèÕ Âa˜Í¦’ òévÕã™í“q-ÀÚ7ÉÎŽE2¢`Ø»KÈ”¢™Å¦ ª³O"Ÿ–;øàÜ»×(G„úzÛÑ‘Yæl@×¢&-"µùÈ<ÔKÍ®ÌÛQ¬'éʘ-»iØe5ˆÆi1OBÛ®›ÆÆ_jr 1À¾›SNJ[ž˜h‰x ªè·… JõäH{w|äÍJ=¢zU|Xá±y-ÇC{ߊ[ŒÎÆp:ÛòYÇ.ÄËa§qž`ë,(UŒq¹ß)Ò+\„ëmo©ÇœØƒK]Á 'ÂKÉŽÉsJsW+©Ôê*赈S.L6,ð”¯M�YŸ<ÃŽéö:*a`qr‘»Q¼·€oÛä† *¡wë²¾S”bázâ­ˆGT1ˆ•ÃÏ•8LÍ9ÏÚK f‰²è ÑÕ¹#Šõ«önU]U(·Š8g=nItùžNôu[ïÞCU€ ~ôX¯ ±ƒ5Xï½J‰Ñ’wAà燗þ”„˜ÙûÜÒ;l {]W‚K6»Šá¼y9ƒ¢o…´ÛíºŸkÛ‰<„'tòɹÂç~*§Õéb €ºT¹v+³ÉV²ÈäÄÞ¼Çgï\á!èöy€ªà{4£«QĵP†øê4M¡R7z±Ù/]©/4qØ9ÆdNªü¡<·óEykz^iÛÚîŽpW\ÀêÙ!E©«3H, -цv-£kÄ�rë&`Ç</Špç©í‡U 9¼!’(ïF#¢Ü¬!‘ÃŒX31Lø<+{ËH·pÉ ÆZ-Œv轕Ùz�I¤ ltùòUºþ:hûéj3íXZ`§ ªŸGVä ¬â4ƒ‚¯ç’¬A%É 'ÂîYïà¼ÓØñôÝ~’"ŒQäfà�©šÞÝ ïQ+äCH<ΈÝHôÇÔ /=0^•>çH= ÷¢(p@�؆}¡xã²ÚÇîðð€œ•ßΪ“µ5ñU¿—¤é–QJ� Ï[m·öb0úMû-µMy2Ç¡z†÷5�¿]º{ªÝODƒöÅ *cðhð»Ø”b5AXä°Æ0h 2-)CšºëŽSJÈ~ÏC{³½zaîHÕf”jLš]þŽá©“LœÅ{Hbp§]ãaö^¯½ˆ|.ÏÝ=cÏê²%¼ŠUí-©*'Ýœô•Eq&J¦óØpíã‹Ü^ïÚ&S XHU){ݹAã—MÏcëÉ^0�3‚'ì^EF!pØ[DÓ£\8Q°À v]K²6©&¶u» 9~¹„x;¶/ØE‰Ï7—ӱﺸòy,jt”ÈÍ*OõÃUrC懷ýVÒuV®º¶2›a áÕk¨nÏ›åÀ"Éd£Ú½À¡¼”˜pØÃô÷�ÈŸ'¡DÃÅMî ö(]WÉ™|›:í«&Ë’,.†ˆI[·/§Gh/—‘Kw™30F=„}}&x–³5¯·’Þ]»ùLÜ)¼·ÙÑÜkV»§PjªÒ[Yͯ¾A÷OÐÙWhaXÐñB¿}R/^jYÚC+"LËj2˜Ë`m&ÕÈ쪚sÀ_¾î=Xò6 gÛDF¡}Voਞ×H]´¶¸ƒ’#ÂË·Y•;+kˆ+/VÓ‹ú(¬ï 6˜_úÙ=éS¬­sG®#öÆum1”M†ÖwöLžEÚŽù‘)Ñ«g™sfVòÊãÔ¹Á9½DÄǸF²Cëváö¬»¬4u~W©lÆF¬uèˆè6(X—qVTÙSôòÕ XÏ!÷Í ÚP—\ÅrÖŸ¤g—êó–T7Ä|Ñ|˜³ ¬(J=ÕAjpÔÐO*Ý„ënçT ¯ØË€,è ³_9@eÏKt T&W!¶2pÍuÔ^´ÓžÑ7tSmü®cÙ[õÇCxH"\a–È êT27.ÇX[ƒ;ð:_©Í¢{‚°q<“Ç*cŠ,'ç ;Cç÷"g_ô[ËVf·PÚ·û|ñ*Ž¢J®Æ âåÛŠ&i Ì3ñäz\l*ûÂÍ„ÇAºK†Ž; –žÏéê9½h8Z H¼åáÓn²cÛÎgÅg”ˆP¯ÜPöMMeVÁŠCóÌtÙö*…b–õž‹£¼©{çKvJ(‚õÐäñ†:ˆé(EK&¼Ž Ïx¥V|—€1•s‘i8ÏÖb@ð´Z'iDmß²èc%“ÉdMèUõ¦aS¿»@KÄåF#u¦y(S<èq}êÚ^ ˜ú®@Òž€{ÇM§ùÛ¼zYU¥5ÝfÒÙ»jTk&%P¨Ã–B²žÌl°W˜t,¥G<º‡‰î B>tÆÂžïÖEØ«èYJ¤-êÝŽ§ˆÉ‘*QUŠÓ]Þ™1\ð&z‰Ç^åÀZÄõ+ž•C6mÎYY½hŠ{S+¢yª¬Ï\ ,éqÈÒ]¦£(CuЃ™Õ•–´fdá7"}Iï=¨•n4‚tÔeP¾i¨bi˜H&ý$Ýô‹ô›± ~/_q^ÖX¾”},¶¢³uæë\–PÐ ë­#¯š&÷a‘´"ù{|ü±öá+KD‰¶ÕRŽ—®çª‰ú¤‘\¢¯"Ò¬XˆRÝ_¿Ñìv]E%UÛfäDàLyI…c„*é"•=~ySf¢ õؽ!ª´òˆ2^ƒw’≘)†ÇP^{iªy’ç©«‚ ^Ûké4– °zTä¸ñª·L±fû¥ˆ¯l;³QÏt¦óöÑ3zÝO¤•þœÓ]¥½ˆjN~cÓ@œù€a à ˜“A_©ÂÒ-žM–›°lXEà—ˆ)@ÃÍÁ ÆUè/,Ræå“–x‹ è®­ÀFÃ0¨˜ HûžQœÏ“$´8’ƒ<…¶E¯ºŒÇ \Å ^YßÀk¥m`ÅóŽ~Ãå³0½-[€þLŸ“ùNì<ÕÖñÐw™„~‚¯%Ëö–¶ÓÙ‹ z²ßЭ-ò½Yuö[ÀQg< o—^±E-Ð;Æ»aáÒV2yÞ+F1-)™8<7r8ï¸;á˜Ø�×]l[µ}ú ódvV ˆ’š 1,®æ4.(g[«Nìì"r*Š,y›Æ¹7È{ø,¨'ªhBÝVBæ. õÓ©mǤ¦„ËÏ"_;9#½Ü!VsîS+íô…FB@%–ˆåµØ�@ÍRY $'.»ªˆh h1ö󷆛UªÓÔ¨¥¯A¹Ê½]åæÁfùå-ÅCª5.‘Êiî`nò˜ðµá„ÌöÌ <yâT]D)jŒÍáÛn^ˆj˜×1GZBе²›#*µ¡´nÉB� .Šôvlˆîm[ŒÅ#KSÂg»—UµÐÚìÔÕ‹(—Ñe$¬È³Âû[ºš7ž‰•¿ãå ­al;²Ô±¡sïàe˜R¸fšlǽ’õ÷Äàðõ¦õ£'DŸ¨;¡n uµDf‰™ctZh†aÍ[ÃT½od "»KA©dîP´¡ÈÞSuËà"U‹¾™˜<Ë!à÷|&š‘á½”&’Ä#´’c{4‰j»ïâ) ¿ëèÊ ¯¬dCs)gRÙ%æ¸\7v¡Ä÷®ºƒg/Rpz ËîS\…UÀ½œgúâžÉ«m‡­â½YGã§`ªô®UåVp°€žê µ«ñ»×¯TŒ–žb*)>dÆJŽ—þ®6ò&Îò0×ÐèùüźfùÁ±”+ é{´rÐ1n$éÍí.µÝ²c¶‹àÐä; ¸R¾ðØTÔËyo9ò¸xÜÑœ—'Yå’$½Ëx†�Žf¶yßH§g?ëJœ"):¥ÇoFüMÙè2Ùž<S`6z3cs;ú‚+QŠn‚¹ßƒ¾Ü3Íè~ÞXÚÏÓߦaÉáªtD패 >K®ÅV†ãm×ÑÂКC>é÷”ѧ߃®EsœëškÒ% é˜ `Eo> ¶ÄÂg<ލž˜å½iBv ð£YAX_/>î¬Å6rÕ{¶I‡ Üïf˜&b{ 7½!‡_8Ápõ]·ôã:ó¯Ýñ}Á¢–æ®,h=èo›Ÿ*q\Æc¸åD¤©bôz”{ÄLÚ²H5Äï^ ¯13ؽbŲõ¶;="‹P…5óÅ~J)Ƕœ ¢̵HÚ¾óœ+e Ï›ÞM ÌË» ”ÞJ¡®WJ* ðF‹Ø_[¿‡Sp¢[r<Pœ6%â‰Âûøä>mu $½}iWÕ`ÔI‚©;° Óåµ›|®ÊÒ`÷h$S$ÁQÅìnf{Ý ¾¨ÊÙ‡+puä!´†|ãXJzÉ<abâGh;`Pa;LãmÓk† °ÎÙ‚â–0€YÇéâM4Õ=ˆó§Ž8‹Ë0QiOÕ¨låaèã{¢ÛýÉzÐ'ëüD—9Žë\™Ï¬G­Kk¢ñ$÷‰)áH9²­(•J«ŠKçÑr`± Eæã!Òá§!òå9Œ¨Ç>¨'O¬'[|ÞQÁº/(À(ÕÄÉæ±ûœk2l€¢Ó2;@¸zs“CóåR¿4 0p«—šÕþÌÎ~?Ë“ x‰TÔæè¶´ ¶çå»G6í@ýrŸ¦@íjb³Wڢɽ‡ªEþØ(SSqw Õ_¾Ø}ôÀA 6™3Θs¥7ùEG[ý ûÆØŠ¬‰ø­6¶@/Ô9ûlQ1:@ÓÛ`‹¼WÅýŒ8’¦ ¦e ‘s¹ý?-À€Û–Ì<±á0/W+ a_5öué©z‡ò<²ž=@^¥gÁ^þøe1º¡l„á”&Z"™eÍiiIÀÛº‡x4Á…Ð/jç(§]ƒ¢½ùõÁŽª½VVïÓ(Ž×±Ù”³õ -ÄÀ]“¼Á¦Û_*¥K¨ÃÍ55C2ï»È"îÍY}¿[pA;“Ø[Zk®;_œwQoý8&�]3«c¦6|#(Ú$ñ]¥¤­ôÃxZ=Ú3z(“OÉŽ©”H6ëÐS "n_ùÚk?{ilÌÄOÞ£ÉìÈxŒ+ámÈ—W Bgk,•8LܵЅñ(c9l³%ìlÒUÔZÐYpû ²âàП¬›p»pBUC°8g¹ÊÜ$à`[.·qÔÕÌ`Tõ„¬§<€ V¯æf›�”DŒŠ~6C­²ÚÑýú’AZeaó‰Ë<Ù¼-ñÃl£1^·¡V¹£F,zr׳/D"YΧ‹‚:wBêeé²ú¹&=YÌc²¦žto ŸÐ{ÏMqªŸ§/ ƒÐÔ°&€r.HåUjBûÕCãôdW «š›>¯�Ìa¡±HhE�À«ÒCÒ�º‘/ؾ¥ý,|«ÕÙiì=›—U&Óq·®`È9öDp‘�$\af‰³Ü•rŸ3Jœ÷̾[¶™+ÅŽ=Ê'‚Ç’"ή@ì—5«¦‹=&§O$ómnÖ¾œv|W´™|p8qþx¬s¢­5$×¹Ås©†ÚóŠÃcNxÃÅÝôÒ"µ”–ﱦ¬Ï¸`“‹EÈL¡å–³=„ÅÓdÍ~CšvQÌá’§¢Ce ºž±~lÓÅ{Zþ:³/r¯ÑëúΖ¹ö4žmÍ´ºú‹2û‹ö:¡ì4bìy±Eãª1X¤L =å…ŒëÖ¯°¦ðH ç¹;heœL ¤õÝ…uÑÛ ³†yqŒ|'Í6êá '±¶6E;”wïêé †¯ÕÉ8^’Å¿›ÒŠØ0 xÓ Ýo õÎÈÒèHM‰=ø¹•Ö '&_à¾$¶â ²Mòñ§Ùªb¡ÐUËý<íÛ&ž'ФRCÊH¥NäÜ0US×CRËÍ\KˆJŸ>ƒÄ—·ÓEH(ðúnÍõïË ‡ë±p½¡žè\–Ù0FV¶Yà×HÈj‰l¢þ /õüåvªNÌ ”°¿‹£$çº`õÔ¬-–{O6Ì©Eß\= ÑJ“™¨¹DX:s7g”zb®¶ÒD}£Øa:ñ¬‡]O‚XÊE®88rZß:¿K˜ÒSnÊZ]k@ùv­«¯^v»:…/Ââó7/õ¹¥À»‘g©;Aðº9Ü"C•ÓëÕÌsIŒ×â™Ý zµ¼m§‹Ú�ËRÓÛ¤v¦ÎÒ{ÇdwÃs¢½Æz¯Ù®/¯-­Ä‰ÁTvÐã]èÁ@Ï (Æ ti¶ËZáð4g%,š„©\=U$Ð ßš"±*ºævÝÓµÖ}¸f¢í}kÍÎÔ“áæ£$¶3vœ�‘±˜t’õ‹(»Ä£‡ØÈÏSšíué›vÿ¢ýR´Î4Ÿ¿7AFh¾"A1±ôÛî‡öl_“À+ _µ‡ë2–Ï_¼V›ÔryÀN\Wødß«#ª—ô*ðÕiöPY– †—£[Qõ°ðȾ‡ÞÙõèFI±æÚi ïiZRrǽírì}"2|ê3Üž/b €1ÂúÉcÉPy÷:R 1 +p4cˆP™i’:ìuºìšò«³G–t–]äO ÜP犕VG…uƈfÀ:"óëÁíòƒY´èèb¯äÓÛ~ ­z$tºÊ;Zá¾ÆEdárîeîœh1PÑqâ5æçñ\0ޱ��Þ ¦ïqÇ;ú�qŽü…º#xα頚,ϽÑ $V8%Lt°d×dÐlâ9 7!S1°+P­hô!,2XÒæ1JÒ²y­¼~Á’tÀKbø¶iiqGŸº2½äw.‘¯X=C€Ò÷¶£.,@#BXY Ê ÊQ¼µÃ_?ó,QÝD™1ï¹h$^JêMDoéîI’Q°“Í,,ÖqACW©Aç¡:C뺯˜e7í0Çk ¯xžÛ‹Nlh¡ ìæ:ÑY±ƒ<9qns¸ÑÏÆc8]Q»§NÝi¬çê¹wU¹—èí¾Ü©–§�îÉqE‹3"è pû:ˆÚ; ϨÂå€öQâEâíâbPœëÝ–Û6ã»âæc}Y¯{½Ä\ÞMCAƒÙ0‰L^ÆÊ¸J‡c% =uòµe’“Én.{>‹¾Úê©$eÔÈû€)Pm»4"8.¯³„Zt‚‚Uåuãc,òW9Â*úØ[™ÜÆÂy¶“t0”‚}ã†2”¯À¸„†}x MŠs !œ‘œ‰CœL@½rDKrÈ4½4³Ò²p½ãÜ]¢Þd=„«¤;µšy×±P´3 e¨FY&Š&‹Ï¦„d–Ye»Š&?qGý½_ôÛÀ�c€˜qPbpÄÌBaÍ0®.ôyÌÊT™Ò#/ÏyÄ·¥íŽlÃ!tDW½›wwFƒñòà̉„nð=o#æaXX¦§D&E4€ÍýžÇaÌhÔ\ˆo-ù>L¾[*9ôtó‡}erâéÖqI8eTIÏ¢hšžs½É×$¦x;X ²7ùÉ §½Ó¤'öŒQ,÷8 =Á&I,z䤽·XóÖà®QòáZƒ„ÆØðS D,'«6Ï”§Ïƒ’8dÎwï/Þ_½%„…+{"ê€I$p¸¦Í29éb÷1»2”½‘¼Ñ¡Ñ˞Ƃ¾”w¬)ôúPKk:KTï% È2ÓŽ­{CŒGícÖ7ü¤‘G=m|úÉe†#Ò9Œ£f-ðÙcÙY;S¡¹¶¼Óòåiâ„6¿‰ÿÝÁ«5W{Hú â]ÇJ×°³¼&wØÝMÚ‰Äðld‘gµIM¨©`ÆÍ�ÌÜ`}*¬(±¹l7ÚmÑÉo`HÛbß½0öÔÐCÇp.)ßÜq ÓŽ‚Ö×RMIsøBѳ–Ù|“ôµå`õ±¿x:§Òí+½=ÁYMÍhZª>èø2ߎsת—w8¥Ÿ;«a÷P”Á^¥©tq­ ¾°ð«{ÌcƒNq//ƒµŸˆwˆgГå -òZeD‚Ø[4À<ÁÚ38¥DÑ€lïEâ™\m+h¾z7=3AO6µæªæà£ó&¢eIT=¿mÑa÷¤,U{¶ž¯c,«ÊLò NžÄ\ˆ…mÞ–"ˆFàc�Ϻ°eѪ‹8¼‰z¸+58;gF/W1¡ë @ÎØ~ˆ…ÚIЪ‘޵¯$=c^ßê¼ áŠZæwQpöVÂ"¯ãÙà=mîñÎÄ-J¢ÌD“;ZÎG.ÎÑ h\ÛX©Ë´/¢9 RTëª!ú°üi>ÒOÞ‰¿xï`ì©hò,H <Zi_¯r%Íô Ú~iK¤Nß`xáå{×F!Ïñ »¸‰çjû¶^ö#–ÖeáA½¤lFÕËœ##?…gÍn§ÌLÃny=Ò/{]|“Ra²4Uò1#‡J¼ö²‰ÅÀcŸ*”õì4ÓQ,B¡¹œ–ñ.ÔãxñzúNQ°ê™BˆDÐçžT�pŠ Ô,õP·§IQ¯‰Î¦E�¥œÄ™`rQ5�Tó ã[qêˆwþœ´ÖrµÅ'&$ë_À+ÊÕ1Ž¡óìœeAE™&§ÕQ!¤EÒÝú-¤—’ƒHÔñò©¯i )§«`.ì´�Ÿfƒš-òó˜ À§ k¢¤Š¢D3,^Ö¹¼u8Ég9f˜QSÌèg£Ž†¸¹¶ãl,‰k÷òâ!*U]m˜ô ÎUçכà°)<%)’éü+c»×ÕØŸí\]¦éÒ+1™=ϺR;”wÃ1÷ZH½ûå¾3zË>z ¹B”bº…4Ž6ÍŽÌžp] HÍNÐhyå…‚ŠîÁ ¬Ã8Tñke"Ü(Ïu2{­µ!NAð®vµsç(B F“&Åàt*#l¸<1ÉÇt±‘kºd‹íAEÆ!‡*0}”ÆAîf1t5†*FðÈ/W…ÕÝЩ)¼¬èfÙ¨îÆõ9ïb™—¨ð½éç·Ì�½'ðžŽE±y«9n'ჾ—®HÜM8<’è€HÅûRÉßë‘#I ,x霖ùÎ= ˆrÐbÄcYKž¬Â{íÏ_–Ã#Þó½zÕÚ}R urZèRþvjßAYFüaƒF)\£ï…nûbJÛ.ÔØ$"Dj,í9”?-Òº³U±ôåž;AÔð«ì²É‚…Gv„ì·d,0ÐÒ †”,€Ø!cÔ°p(uÞD$d,Ø8ÉY}Ê‘@rÞ!=±ñ¬Àâžr‡}ÿè x戽»l®Þ2¶½Áå#({ËnâµÒî‰w+QP�âÏ’µè2º^ë*gìkQN²†ÃÖ …gžnKÝbúµ&?iB—8DnõzËm;¡šðÔ1:XߺrŠ’ë™Ë>Jf~)šÅsšÕb;ÒTè2³ëì± ³»«šù^Óêd=%Áf u*ub'¼ïG¨•)|ñòæaeUß•w »·XL€Ý?ßñŠÑ %¤‘¬%xS{ó˜ˆ]Àøi<ìÙÝÒåtxâÙm®lüþ"ÞŸgÂke5[Y±¸®^ Dô%TlBV†1’yÎù&]ŒÃ»MØAŒ/êøLñ#ú++|ÂÞ‘ƒyðè>Mäaȉ½>8]wˈË0ïúMãv—¿g|ȱå¯ÕÝ©¯]SÞ£:xb³Îó¼KoUî|ûµ'àVN6ÄÕ†Âʈœ ¹y*x½UÛt7¥JRLbpÆjXLjÄ!%bBÁCPºo€^H¶< ¼�)ä±»sMfÀ3_í¶òç qò´MÌíD‰¨âNíèCTÙñ#˜Ä‡jÇsÉ-MÇ–ÆÎôxSgÌÀèöH³_¶Ê&5âó°áØ_EÒ³P©°ú¡à˜Æ'Ó̹_Jï»»âíÌ%=¿Ô„}€ª'‰Dô!§DÞã·ñ|˽ýÅ^\àµ%TÌyDΛ~ä¨Úž÷Þ¬‹ÂΆo?Ã$Šç$Ä.Å µÄËz®pÆNÀ­‡es¥“ûåÂkŒî‡m$šáBÐä•T6/âA™½t jï<Þ¶"Y”5ͪ ƃ”ö’Þ˜š,šài\dxÆœx?ÕC4“h’ÝK1Ã6Þ»íl C\¬‘P›CÇ/ø&¤ò=.r±Äí JÑéÞ¾�æ ä7ÍV Œ&ž(Ø,®wˆ¤>ï’aʳ›r`‰ã¤ÓæýÂÖ°Aƒ‚ò“x†/âw»Êo.yR n@ì4lÏß)àâ²9‚Ìë2:jº·~¢;ÖÏÝ)m÷ª]®#C „6.Ëó¶æõšÓ𤄓n…»Ó&¤ŸeF/àKݨf¥+ÕöáDŸ$dÀÅŠ÷D·îIéªóÑÈðŠDŒ•!»3à¼+E_$_³Õ•{Œ/R’Þàè{Úd”~ý Ûð1Ö®f‰@'AêLiúErµ=háòÂÆf·âàšî›—òäI=”€:j¥Ê¿�M˜¿§¬t„2A*¬Wh!gzίîÅí”ThÚÈ K*HVÕ;%+ Póâ}ýÊBb$Àν™ñ¥Lp ^{5³@hÇ ^Qò&îáÆÙÌ6¼zj~4!3~5e‰ œã)÷¦ß[Káη%Ð ¯ZDXòé9XöJjÆ<ypø£|dº<�žR«ôëh–kŽ´wQ«íˆ/Þ´L&¢V+œºÍÙÔ&Àɉgdµ&[=Èš“Äó2e}*¯ÒpñN›|üeÉæƒXê�JML}¡B’a›u|-ZOÈXÕø"v†Ì"÷ÉSápJ„&ª<»™eÀ^µu`–÷»V!¯>3+øèEWÄ-#_½‘Gq>Ç-²®÷nû¹/Àœ†v7kŠòÑ3ŒGK˜,ÂøPÆûáì¼DÅ…“=¶ó«ŸÓXbòìòé Èa¬BÚN´û%�ÁãèN/À1Ë»¥×É%&Y‡Ëd¤E†·fwp똞 šíS‘I‹x ݲQeÁe‹çlLj׬„ä8$F1Ï+éá(œ±ÜÞiqíÉ›%ñŽé[ªáŠÕöö·m¦µáž.ä…WO¡NƪG…ï"±oqkäôCøP¤ðtû2mµ‡Wh¢À[=øE ·(ù½½—¡šÁ—¡œâÆ5t“§’ªÏøØŒÖ«Çd3ŒÑ¾§dj"ñŒÜ]òÍîkžoäýyå{ËÙ+íŒ>*·MÕ2”Þ ‹Ãc{º¯`Î0 ¼Ö’@gó„F+jç½{.ôLнg©^tg2‡˜§-¥ï;ÉõuÔòAu«†­ƒx1À§ÞË\ªÉ²WîM:ZC²Ë »¸'~yÔ-/ÎÛtÞ@ØZjêÛª(q·{}` ä-U#SŸaλEÂá:f¢8^Ü>I¸8ØJé-#7Ï"êw°%©$^¶ê(§ãeûc6\h ‘wÎ&·0üVDrß.ë•#§zsí[ïø‹ù'N³' Û¯MÐȺæN&Dq_ÂÅÞí‘7ècEA†$$%•K÷F©Ø|9Ò7NÏü̳Ã+SvÔBƒííší!s%!TÞÖuFûLÚb–´ºcæú.´Çëç›V‚^Û†RVâl'dWJhÑyYº“ÊVPKmuìA2ž-—)E@2¸jn‡önÁ^œuו¿taÔgŽx;V¾ünPú’«ðAĽΠ±Àó925Úlšv³Øc z9Ú‰{M”]õ„'¼V, ÛòV÷H†è ‚*϶¾y‚âÑÑÓ-øÚÛ6š¤šå’è"‡ì|~méVª/)¶&|°ŸœMãdÖ¨ÔÍ+çÆ‡¼j‡¼véŽMX +My#‡…¼Ç;9Ïéll<ï™R1šÓtn”2³gåÚÉ×í�ÁÅá¯+hû‰ÈŠ7 ±‘®ƒ½~Ñ®¨2ÎÕ¢b]Ñû8±Þ®Q’©¨ƒú{¼ŠàÑ›dÖóxó½‚Ú÷h[cè!#ùL޾À¹ç•i²/Åêñz[ê[ÐIÆHvôe¯ã¹´Ä ¯£×4›¥…v6Oé)z0<�$éUãZcž¦#¥DÖ®W'!%±Åüb‚ÏñɬýJsaÌ[Ua5Üæ|BmìX<¾ªofªîÑgîÍ7õèUõ6šh5³Cóí@#/ò¼OæE¿˜ꢱ÷ཋ |!ÉÁŸ¿n>è ãuÛVg€ÚÐz—ÎÙâ9ÏgV2ìø8zs(ØÄ,‘󚢖çŽ?£«Ú±<&‚ˆ˜Kg~€¨6Æïü¨0÷ž<Û*–éŽÅ7WüœÉw1 yoêunÙ½xÑêôeMÛŠÕ£aÛb)d¸9hóà³Ò‡ZYÝ s÷²s’­ª\kÍl­jÅüŽÙ§žÂB†¶ ¬iUÈœ·'ÚfóÚlõÝ«j‘D[3m …G©=9äÏÿ‚Þ¤CŸSƒ*6EOÂ3y¿�J:-­¤tk˜üªznez³Re¶È&¯io¯Ëž(àœtñLž8B•G¶»¾gA-æùŽnóAïœøIFˆÿn×ñš¯2EhU”s!°ß6µ\ 2[8ƒ„Qk° ‹†žm :W6ïàáºìªûÚž­·[gp—æ<",)@¡{‘ÂNwYžAž~ËhN¶ïm´W?Ùl2Âï0´ýíÎ+[5Mö¡jZˆœPT[=�‹X}í ªžù Á4Zå½<>`G}"u¼îI[•XÌT{Pg3.‰—LÆâñzðÜù‰.Óz˜VÍBt%>É^QEʱȈ|/l¨ªôº¦$áÍYö>,yôÐÝRÑ—×Y÷-‹ƒyqV\òèð ú¡nÿŽ¡ÅÐ3(Á Íx»4×íªw…å¹—Àüä<¤tì-]¦GݹÜ!7¾gõ̃—’ºž—\¬žìé%&Z:‰äÆžø%WF§ß,ëŽômÔu5AÍd=s¤Kæ‚ÄŒH=„>X­‰‡¥yK”Gáì¥º7n,Z2zië=‰®*V{ ·Eƒjv ‰rÏÁu2£ç¨ÀoT[<|ü4†ó°ñÅë×±åf³Ð·÷¯H<øé¬[ >¡ÎÀ×o͸ T$‡½öJ—‡ƒSWzB}½[ñ½c:÷ ½òôG"Šo†‘»qNúû* ZR(Øg)…L·h˜œM§:äc9Ïìx@„»Ž[è áéÊ=‹Ñãòž®(4ñyõBõÓÝëÒÕ|šz S¯šqa\±žsél‹WAè@2Ñ0Í¡Éb-Šá•P®êѸ&:qz_fW6§qPð{»…ÂÂy~©^QŠ™ ìÛ«yëéâ$Žax•¯’k`L×Ð'ûœß›÷RbÈí¼;ˆ¯%c é>½‚e(Môz™§âë´ƒm®oè÷Û"ëw¹íêò'õ¼¦âÇJ§(ÝÝVï,}cÝ_O⥶‹.Í+³–W±ÑÏ÷Œ(¤÷1úÃXœ¼£Ï„îóhD°f‰d{È«%hòº÷ 5_.øf<ó¸\LOE¹n´koßÇLàI’¯ßŽ’ª‰Ú\¬Ú‘)aj^ìéÎÓ{]¨ÑQWå<E-¨@ÔH'›ôú—WQ!1Zø¥±·æòò‹>¾>¸J4|ªÀVœ>;øÞ$ZJ7Uo8¼ù…¹MÓm+÷p‹ètXûz­TÜÊ-3,+M¢^a[¡g؉OrÉfäºä[|$[³1•v™ƒoÊuüø¹¸çà†êrÚd Tr¾�›Ú*’C/w±Õ8Æ K—¬þSîm­¬.ôÞž‹¨¦Y¹ ì1øS(±Î±(�`#žA4 ¯êÍœäaÓë5»¬KåF¬È¦êògÖ×¥–†£u6G÷ÊN../3İñ(áyÐjµ˜j„ƒÊ‹<ÀÆt†ÑBuum9pãª|;ËQ¨hAV²–#œFçQËs³o Úê³ÌGïÌSu×±W(l_9&àžòu°ðÕN£4¾|qšíU‘Ð[ÈëèxF†q¤|W¡^Ÿh÷ÓÝôáu¸g>#‡¨™kH;pºpõ{Äç•2AÜ¡˜\AN÷rBUèµ~Roô½‚5 [òˆ2Ê'Z)RÇs/»S{ q‹ÍjÐg\dW?†¤à1Š£ ›{©µp‡²SÑ:2ŨÌnüáZù„2ák{*ƒ€Z:/ iðó)¬zг·k ™äÜ gtpoÌ®]^9º° ˆät³…®økÓÕ[ãŽl·LÖL?wà£ÛÚÍõ²²²œ)RÌߢDÄ="¦-‰½=–“Õ¨c45aJØ:<<Î}7(jQ·iÀÂ13#‚cæ<¶'བྷfÕ¼îé”uÖÖyÿÄþ-Z—F8¿ÍÔ~HÁOðeñr < =Vy{jˆ+¡Þ7ÔO&¥xÝ ¬Ç<¯�Fö‚¨›yg„"ã’Dñ´©æyM >dÙ‘‡ër´ð0JhýQV/#Ö'h=‹ÑÓ9wžŽ—S’DLÉUu‚†xäÛ~àkZðÚOûµô"ÎÁˆ>1†çœDÀÖBç-ŠÎ~€À¨6^ ÉÕlUžÊÆèPÕûv5ÙÊxZìæD™ÀÙg{î]K‚*{c3% Ñ%Ð\€œ?tv:G‘'h‚³¸#©Or5¹YôÊFäü!Sg³ ¹Å^›qGMÜ&‹Bv™¹ö‰^VÕ<w¬Íp�E¥§,Õ‡CÀìÙu—ƒð�ÀëÒ(üfõ…¾çš'ME6ö©•ys¡Q!SÛ? jWÝ09C$7ŒéjR}ãA­Íãî«ÚjkjyBô°âMÆŽyHqÊÄ8+½~�î†òœ¶ÍýJœˆšg܃pk°ûqÚ@š-×PJ3z•EÃÒvì¼…·ûΉ›Zw»ß>Æc½·À¥^¾Kh‘“hÑ^gû@úéË÷ñ½¨ƒž‹0×§ om¶ ð±L0“‘¨òu=ßÙ z݈}œ‹B•k´éøò5 �]VâT7Ô U³ê<öU ;É1º‹é'MÖܸ2ó"•­˜4VùÙ%"·qi£W€¶Ÿd%æ‚ÖÄ'ö_ØÇQ£çlÔshs^4¸2}™rʨmaõf¼9™l®“¤(s 9Ÿ#¾6]Ò.«}8ýäÀ™{vPÔª’ÂÅû®Ã®(�á=,ÀÑ|W%º±ÂÞÈäÏ°Ç É ØYS±ó숱.«^Ì#ãw ¤%‘ÜÝÏ%éž¿†‚Ä€‚£Ì.?FD\„£ãEŽgA&‘BÓàQOnFèqA_YéxnèëÄK•×Ò@87z«‡^—7µ]Y�äøÞÛ¨ÈˆŽÆöóÖ7¦¤Íþˆ6,päΈ‚£f×Þù_ÜSíef›§—îk¢Lɰ¨© è L&sZsÉÑ=§=�´nï1 »z V›…“X(°Â\³[n§²¹§&œã °Íõ.|‡V¹\òX=y£®È‚’”4ˆ¸8Èõ™1kË{AÎõúmÕù8ãpäã³¶èx’½I4íÛx½GÇÒLõÐ[ èX@|iAÃ×t¦Ígó,™«J…By’ô¾w··ÔJÇÉNq†RÐLL„gÕŽ­vü|‚`m¢÷Þ„WÖK²,Y|Ê/&_K¹7àj€2êÁ°«‰ ¢ñAL¡K±öÌdäŠ \(ŠÌj`=`¯1ÓI)|)ap¤õâmv=£òâxœz$TÍrFhEqc–8Û] .žá좆 ”Õ,Ó¢$²B%C˜”ï1Iº¼mt�8}Ö³t±­7¯…ÉV«‰ÕÓ°ï´ÅØô Óæ°²4¬ò…F £"Røba\Ȧ’dz¦œÑwù üù.\²#<44Å稸MaFh7+li %É•‡¼N¯«qÞŒE5–rø Ê#ßpz™ATË£',åI$º‹Œ»5è7¨ÌO=—gÖM|ÙU®ÑYºPäÄxÑ,_A2ëStÀ&g»‚'[S m©6„š¼™¶À®4ÚóXãÍ‘Ôо[H~9„4ùͽqŸ‹÷.ßS �ÊÕê^ïªò•Ey,!Íǯ(£êá½z€]7œüz¹‰{¤Ã9º•$¶3`)-ð®²Á*a‘í’IMGÕÅ`á…>·’ꑈõUÍÜÁòÄÀ–d¶S|ö€ðRgsºDž¾¡÷š˜ŽÚÞT ÆYÇ¥¤‡ÒÞÈ) 50ØaÀÜ^ŽÝk°Ñ¸{ZÎ)¥e-bk1Ã'Р‚xq¢í¡õ¤­ôU>i½sª<Tñ5»OM~»Å xï<7» 3®õhDäyØ€¸òòñ4±'¬þ9ß“aúÓÛ0–gLbáØÔ—jäÁíé®'v >£tÉáÄIÈ¥¢-ƒÁyXv(d$%BÓ¹9ÚÊD�+hÀÅNŒ ),†‡jA/ȲI÷½M§×Fƒ Iõ\‚´fÇW"9ºÆZAµN.ŸrÛŠ+d` Ú:3¸Ž²W×”²wÎn-uÒP?Þ¨Y™î苘"2—ñ“G–ÇX/g$’äHåF·tÄî”Mnjg¶kP{!´§5WRË.êæt½¯Ã¸À)ßAëxK‘PH:Ö 0ë³…à�ÝÐ1Úñ‰¼#{o(ø. •b÷âò ^LG7oj ?·- U.ól&i[×À¢ j=Þjc+5ñ*…¶wNá4:½².“GHûv›_è#J~ÇÐìÙ“œŠáËP¦§½æO¸ººß´«ýÞXä‰êqÍ«¦®_¨j»1Æq1”Oh¢È¹Ÿø!D 5õnëºT£–¿´QÕ§~ûæEj5†&b¾0‚wÑ¢ø–¶Û‹*°‰âÖ\€!ÑØ¥ÞTŠ4dQ BO:lÄbZÔ¶‘RÚÌj ¨›¼‹eÎ÷3¡Ê2åÝ KÜyL3özfCü•?öñG¦E"O‰Z‚lˆ�. ÞãLny8ñ”PP'ËqáÆC›ž ·ŽÙa–ŒµT}‚úþ+ß°–»¦Ñd¸´Y»Þë€{…ÔÁ°–Å(p)v5h.Û" :bz¦ üz%Ѽ¥ŸìR¹¢!¿æf(ž‡O#k&^oZ ¢ ºƒpè­f57%ži1¼ ë1y.Ś㼨ÄÚj£þÔÄjö=m \m|®Y,,O«Hp£hüÖ„›Êh¡^ðf™*’Þ¨oÚ¨lʼn“â–l†³~õlíž7qž·ìIôÄÔá/,ÂYDê™wKÅÔ›]N‰¬@'CÃ<v¢ü$tøÞ_ä?Soö: ©Èœ¼»"OFŒl-KG™hã6äÍæâJNP:Û¥ 律ZêÏ[ ;ă.y2¤*Ö+Í Å¼©jóÕd±³Þˆ­>Ÿ¡(Úa›“ xJzZ3ƒ\eŒ–a”ë@0 ™s‹3ü ƒTT›#Zž HnUXGs˜Ãʀ튄ÚZ-Ó0L=¢š•²"+”p+‰hÃÃ#ØòZ#š©{mz±)^°…øBj/š$äày1ìC*ÉCÁ¨ÒÉØˆBn"ŽÄõ–ÇcêiS±Ç©ÜºrÆZÖjÐík¦Ò\"Ez/å-÷Có ‰à'™š¯8Ü'd±¤)Nm*—UQÙ™éѬÚt¤ã]bº€–ßÄTÕ<á}=Ïýw¶#yëa´©nå[\•‚î½§á´àÈF�œ·Ïo¼ÐVSòv„v™#@Â{ÑbvTB%ŸÃ>ê^wD‡ë=ÄiÚÆ§©!ý´øy@ÛÒ /›ÔISwyúÞ«5&ʲ¦’ (êöFU‹÷E$µ ‹ê¾ÊÀÈÁPNdŸ¤y¦…få´)œ¥P™>`Á±m„Ê&²^cù ¢1£@³ÂÓ}¾’„k cB@r%´ñØ¢øŽ‘ÒÛqObÄò¥Y +‘¼vc“{ˆ9Tàöhj¦[G‹Ÿ{è#›/ò ø“|~¼ý°.oêvf´&xÎ*c:1öÀäl Ð)Ou4¹úlP+Á1=(õ]Ô“ê¶NG‘]Œu&¯&BvѹŒgܯ!j5¨›0ÔâTEõÚêq÷+}˜èWÌ—š—¨ù¦¨š iïäE«õ¡³:8©<6D{u×Ë‹›ƒÖôM…(dæó-šFNB£wœx«¢w<ƒ,‚½¼ÖJX”) œ�XäæéaIžàÒd’tè Ó¤n”›D•H2½ªlÔÄV·yŸGWuÑ-:l/þB3xÒn縈BÞ–ØÁ#«³éê<~ç\B€’ç¾êôa,ÏÃqˆŒÂ—oW7¢éÁâ³1³›Öâê}çxGk‰R19®ÇŽ:˜spÒWwé¶IŸ<fÞkF«¬Em–š…®W YƒqOø¤R(¼‡]g’[ uØIûmaa§¾Z›6Áó,aq�hòxæO"¹9 8€E‡}ä«îÝ€‹"²pÎLˆ`€a{ªáf^¥•žç#c‰hÓ:e¼|^ èà ¼ךm+\œ:.Dtrï(­µk›àòpQù¹O<j!ÓÇbC&$ä^ ±=—‰éA‘“q]o Ëe:äõF=3Ä\­rJ¼Ð>b ©~õÈÞàæ‰î½:T»zou Ž1‘pV¢â6, ýªš Ë,g¢꘤OM MÒÎÄÐmÍ4Kìí’÷ «ŸS{{]ùC™¡äœ¹÷dÐG:LØ”ñ´$«¹åP•TFãq›¹EJqç YzÚÅ9ZváK÷0Š™ )xi8R®/#¬°Ä§R^tŸj¼R�v$#+"v¨hY°C¥)‰mDZœ¾s|Õ¤züÄ(Œ^={5ÇQ¸û†—x‚ihýB–ñŽC+ŽOž(`8<ÕK‹R%ë<÷Ì^´åðÕ™Ri‹ØÔð¶òä¨c¾¡DÒüر¬ñ}¤/ô­-äcûø v˜:ûqÌ�<U`“rƒ=v¶~˜^ûP¢k(³K¾r}|›ù$$31éXBÒFKQžè›Ý‡UÙ̯=ßÛ™ÍpHõ§Ú$d%»!@s¥›]##š‹\a êµhÜst›ür…2é‹vç¥|ꯡŸq>ôê"[Âc{vYJm¶ù¼úW’c<›,åÆw[k(T'U–%i~òX‡_·1vé••‡Ã‘z©×)eÍŠY ñó[ä’@ï90$rVhké-N«Yq_;Âþ‹}{«FËZd<Â#î¨]ó8ã˜ÜŸ<ˆvQÂÇÖ";çóJÒ¦ ˆIѳtL`ϤÏQ›^ÂÌ%aNG˜ö±¥†ØreÐrÓ´C4 Ú­IlИ‰ô†Ê&Ë(-&´qs¸…\?“Lõ`DO¬%'Lsó!9 Ó÷zWÄ´Þ ,½NU6ˆœ$Ø×Nó�¸¨¦OD5OˆZ8n»Ïa8µ Ǻs°ˆgff& šîDÒPòá̵¸áäN¯4Šwv£ïaTIqÖ< 1®”yÊ,kW“±YÀqš^dÖ ñ‚cÒÙAài™éSÕS¢¹g7o˜öt G›œÍÐNpèéðCãpAžÅcqS^ǘ%Ž­ö‘¥~2Uw¯­-}D ·ÏèÈ=Øl)›ºVÅ£ž ?[tIwß”\#Œ $\~¾ýº^¾W&ïA!£çËZ1]q¿‚cÌjÿ]ÚŽ',õ6=|sÑU®ÊÂG¦Ê^8 uÓZ-õ±ÛS>ŒÃA»™aáZ,XŸ{ìÅkQÀœÃ‘È»aHþŽ’ OŸY+ûƸHÄõ²“†•ß¡3zá„E<Y8ÿ•€æ¹€†ˆ<J¨˜ôl\SF%šÎ8ڇʔÉ8e×ö¹”Kc„gŒ…R¼ˆ¨ô$Dœ# Ñ¡[l-¨¾‘QlR¤í'¶Î,¡{‡ðÉ>Á'û©ÉÇ7-‘8Dï9æJ‡q mŸÄ>åÀm›»JºV¶whÇݳªÌÀJ=;7Ohå­&·%8Ò`·=+Aó&=0D$€-%›jŠèL šKñ{O(âò匂‡ªs—(ðîòɺ˜5¤kk±Þâ›ò¥ž‰é«t©™é^HK_9Ç3¤ñ[eEy󆨱æÅù~¯ˆðͰ>À`, ŠwùÞRéË© ¡Õ€¥YoJÍݤ^;.ÈK†ǾÚ&NdàB5L,÷ÔE¢ô+|iÜ Ù’ûü5'OÇ‹|  a¶!<¬xCÝ)÷@ß³[ò6› [Xè ±6cÇìC7(§Ä*Ú¢Âê>K^«Þ|ÓyϞ͵Ñ0[Ÿ·0Ÿ06–¼5Ó(èÑ£mõÀ¹vôG¯sD圄{Xø2ú­Üš®ÙÉBköLµDû€sÆ$íJÙ³•g Q—zŽsè¬奄×ÞÁãu|8Ï6ÅÁÜqhÖ8Þ¾÷ò¨ŸÂùnÜD$ªÞ»òƒ¨= 9]Eiðu§ˆÄ{=s¯:–ŸØ½‰7¦Û2ÇJh²Ó2Ë„©•,ºiÍ´½I¼ÛÆ€ˆšìZßá†F±1?'¢¶Ù÷Léä™5†ÍläeR�Ü‘<{{ýò Ð[|CÕu§¼÷diq±�!÷SÃxÔÝ9Önx{Ü¡Qût½À›Î ¸Xä}_ͳ4®õxÂãís}Êq Ï�sÑÊ@ÒUÚzcÇqùêo)? ~¢»Ã^O,Ju=êÕ¶{@;R=êGèöìN!÷²µ®œ„ªUŽtúÙÖò„ùë4–xÁåéïÆŸùÄBX^¤¡¾C]‹õaõðæBRîL�­wÝs¬w9AbB{l“î ꙾ÌeM¨«çrW‹ò”Q4V–ˆîŸ/áîÛóaR}ÉÍÄo-T7^‚vP½xí—jˆã!ÈMPŠÓÉì7dßðûü—‰Ü[e³"XÚ`* ‘ïÅsQ|%ë ‹ ©Œ>g/b 5Íðʱ_gÔ¼*_ Á‚j ’¤à­Að§îz+k‡‹vÃû’q�Úcýú8Ÿ¾ÎÂìñ}#J‡¨Þø«rײ2…÷,NH1¡=ÇÍL«DÙv‚*i|%¨3ʰ¹-I6 7× ÷¤^ÊCBV-n “êÌ|E€v5L¦Dõ¢xðÙñ.‚27%MªÎn§<¦¥§Ò¯•„¼nm@÷DU€ßc@*¡âjÑaïöÔ’¨,@÷ͤńĦEƒµ?é—Úî|>ïhÜú*#Zp8ÁÞSã6ßs©¢§ë—Ê5;Q3€S ËzLU*uC*™/g¦=¸å•(x€¿6:SŽ ·cŽ UïUÝ!äY;ˆç›}°¡OÞ°Ï3ʔঠ¤¡Ót°x³!’‘¼ì¡ëF/{Ø/¥úŽç•&c³€“¾°‰zž-íû�Û’Ál§§4Yë…’A!8œ™úNã©àà Ñ…)AoÜ GÕ{x@º)>Fðîšcð¦‚Þ#‘{‰‘¹“±‰Ë÷še3Zø{QIö€¦žA@GÕ\å&Çí¾}]e¼è`'ò’� _›¼j¡(^^j×3eyÀGƒ¾«TJí§&G»£«”ùÁˆæÕÚpøvm¦/¾–z½ðøõƒÜw›oG:ÞKhÓƒkô»áÊ‹WRÔô¦Ý†G·Z{S×Då†V|A”ŽßóHöôj¤öz…± è a%eò°µü:Ë=sS]9¸Â—;Lн Å.\ޤP½âݦ¡'‘ ”GíHÊáÛzÆÏýaSÞx>MÞ$r 1(¢ÖWjU Û¸Œr¬Â§ù6%ûŒço!f_ø¼Ù]Žè Ÿò¨Gâ»J碱“Üꥨ#˜ß€ö;wÊ£¼ô;dLÞñÍ&rƒ1:Y3Ç¡e¢z»uîןô?ý¢ŸÆ™ŒßhÅ£ í[‡>ÜxD*‰O¥_)fænxqZI9B©éÝ®Î@VË AÂì’CÛÀ“̉ðá5C ®1ã`ÉšUfŽàLa=³A•©:¦}¡ çE·BƒéS® ±£²ò°»š‹Ú뾪—ÈâzZÉtrû /=—¡eŽ"T/뤜דCMœ}Y: Çfããªè °îšL`ð^¹¥#Mó¼Xv'@8§Ò^�9_¿ÓÛ×ÏA«©ì5•¿¼2àÇ¢øâ\Ÿ¸!m\îë|ÎýÛ– ¼M0+»êO‡ Í å\DiN�ͺ‰f®¢ewǼ¥D7ÒZZVr3‰Ñ!á.¸C”—æU\/Ûô @Ï\Ümhà“ïèöÙl×ÔAæ#¬PE½<Þî€jºì^™ôXäÁãCÈJ©) ½W%Õx™â‘A™!S(·ý˜`49e-f ‹±ÛÒ,+Ô Kjp(AWÃpmyWÖº/ ^5”c¤*,fóíBá@³=aÔF #‚œªNQòhb“EËÖK ÍÌô‘Cãщ|;Å©µË¥ eL‰ç#•iâyz:Wµêz§é£$(öãö ðª‚ÒÈéC¹�’xÎ ç^Z™x“)5b'·E·P¡Ž™@ ˆCˆMcÖÍ*Uºè/ȰOäT<ñŽåymܘór#冤$…Ú³mÖ¢ÀÑ"¾qaªHëª7®9Lú¨åž1ì.Kf§PŒ¿ƒº×£¢ÏÙÙsĬWáÍÃ2h†™CWo<)ËÊ×çòº`Gj6”ûàÚ:³p€Îb¨ràbç؃'¤þ«±çI€Š>ÂñQw”†:g¨bh¸äA27_&šë´~UëÌl#D~þ–åu0�5¿“qÛðP²óè“R›ÕqJ§p‚'‚qlÖ«­8Ó¨p3õê|'Tü¡-oÉ'þÌ_øËbL˜»]g6<·%j=‡×óMö£¿w–ž–BÚÉI‰d¸}-#cµ’ ã2A!O`®U"l˜_¶CðB¾Û Åê Îx˜ûº'MƳ—«m<Öæ­ ª@Mʨzy Ôµ¯‚/:ÏËHªœæ;9°…†jÏ8Z(JÒo�ðËÌ2¹1Ì£dâÚŽ´ž_âr¸}ãa ŠŠ¦Ú¼z©~ç�Lâ°ó”8+:påÛ—¶AãGw¹Òt•"•’¯É’ΰÆ‡nÑ"šrêa�<aÇ]iÎ9ÊŠ†K¢&}ò¯2Oo” ß”RϹ2¬&¡õpÕD-"F÷–¶§¡lÈ«…ì}öèa(by¤˜ä‰SªŽU!3n¾ˆ‘HkqSâ÷Fù˜[ÞL”ßú=±$V]àB©¸¸¶Æâ°©·Üù„LfP+ Ïw\Ò AôÂn)ñ¬Ok*À Â:y¤µ HQâì^_¶‘16Xè{=NnÝŒWï¬KÑåºwq«m€¹WlðëxÚØNˆ²%%‰yïZ 8$6|a«àŒ..ÅXžC¥6mA–sï>QÅ{ܳ¼.•{—',Þs rø*ÈÂGtRÚKÝóue3ÌDãîÃÚÎjFÛ[j– XÌ[q_„hŸTcyotѶ³ªIfœ»-’;aQ�ßÄ�òd·œ†¦Õv6º¤½÷»èJuÂz;mØöŽv¡3½ãBáQîêÄU£ÔʺÅÀqX•ϲz1ÜÌ tX3¾æ>—ØFx‰Ï€»£ LŸÄ’'V@p êI!‚H1ʶW¤e/ ÃË“­l0¥Áµ\x4õ`îÚñQ0‹’¶­@Õ9Ì\–Â[¦W-&̵@J\;¨Íƒ7=�ˆ­|yZ¥·E¸p òdüJ£ÏÛÜA¾À§U2<Øõv <ñýb9w·WÝÚ ±˜üž1 R$–ˆvõ”§­é4¿’üä_è‹ÿö Ó,ÖçñÜz_ùð B?z°¢ Ô,¯p(,²šWt7á(ôŸÅ\8äi¬½¢1ØÈ¯vrñ‘£R/VÚiú3V‹"Èìy[¼ŠÏ©#"Ü€GÉ�ó2/’ ¤§@Å]N`Àµß–˜<èç†èUÈtou7Üçêa¶ÉØS‡Ë2ø“Œ‹èüõ]Tg5¡ªKÝ˜Ç Ð C .tó$f¢‹M·°dÊ7ÇhðLod­] YÑ3Ÿ¨ðZç‹{ýLÊ÷¼kMOµr5Aí£õ)l¾‰]{ñçÇ*©g“¬” ¬ÃlÏd“g;Äöƒ+m»T?µÜ²ÒÅ Lã»';Ea5„#ŽRòzßÀbëaij‚É é'6;“ÞQ1Ï×ܺ…K©kÂz˜Øvâ½Y¬Q¿T7À÷Ö5—õ™uƒZ³CSÍÞt@ú€#((1Þ‹åÑ÷w%™÷ém‚ÒÉSãyXØ‚—§Á ú\¢H±×ò­4<G©lên~™í ÁX{ ЭÕkt'q íR¡5¶1\ C/A`^ñ{/I º´4VéÞ[·U¹FQZ|ÎÇ/ÆÐ2–’=,yë]0¾°Í»>Þ¶çÓÊoŒ°D•NÃkF€v0&ˆ«aÌ!ãlB¥J\NôÞA¡çŠ–å¦<r0ZÎg\Va(îTc¯o„Šnƒ½RyM žÀãœsÅ VJÅ%ÀËïÀ.†E$žì~4sGo"óÚ­_cgà&«aÂ[aÅ>|kº¯Ñ,zÂ&D6Ë×@DtËä¹¼¸Ö»F}¾ÔI©p  o„óÉYžÞ‚ÙK5Ss•z‡/L÷î©ÔsŽ!Å¥(TèéÀ§î®¦+é"F¬|ã!]IuÅYÉ¡÷BÖB`A¹S ²|œ«0ž*. Ü“‘¥<¤Å Ç0xÇ¢!/ýnΨ.ÂnìÅë÷®+{A_Ãè»À5Æ ¹¦ÖxêÄEæ|/xÉN«×½ð¾?þè÷ÂY.‘¸Œ)¯‰Ò³ ŽJ#ÀêF'šGF³�RêôÂ1´IÎVºéÈãê˜å4¢ËnÕÄ,°ù1=ÎÅSzOb©x5F; ü"Ø™²…š8ýÌïvʾæ•{¢F^3Ãa2eí“^ÕÎÝöîˆù {‡¹©,'@I¼38ê'µ—¤¸ã>Õ{ˆdF>ÞãQM-aÔ; §ri’È[Ëj—b½¯†ƒ½ÔÕÆ8cN¶õäA×Ñ®b¯hµ¹ò܉ø3Óz8çmw]ŠLž¢uVó Ý‹S^Õ½ç/^ëNº¬þùðTƒ…!›8 f˰dràsÓ5ÀäXmNØEŽxϲíQìfáᣙ& .b4e@PØ<ÀÈá‰ÉWm@5µråz ÌÙÌ( ën¹„ûúí½ÙçmçæóRµõÚ+|ßÛô à÷”´7—X}<îb~¤í1–†î)dÔˆ:Ïü]¢æ…W>0Èm°e‰ßm?`ö—ô‚ýÙ.&¤Å¹`Xˆ‡›ëI¢àãæëš¨Á½­Ýè‰@�¼îÒ Z°x¥‡Êö»‹^ h\ßW,¯§1ÃÇ[ʇð€^€û‚JS ’˜©Æ¢Õ {J³,ïyË"×9À MÈ—˜!V]Ø~ 5û¢"dX D—Ú{èx½²Mô Ì>§xƒ·ÌOÙc¢è¹ÂbΓ%F „™Á~ã¬OŽBS9S.¨Üï­ß6)»L<ö—zÍ-×qIxy¦²žâ´È `TÆïX!ðB Q:Ô¾Š|ËÍMš6Tàçn©Ikîn)EåÆìåxîá–tÕñ=—2ÅÛ°}F‘\}à'O…àÅ7ù›yZ!ÌÍ£]¶¤¥¸ð˜$:3szüñ›¼žêê% 1-¢Å7UUèÚèÓ5Rž‰Þ®ãª áy¤f¤W–GÚ/lÎÜÀsdTˆP‹IÒ!¤ìÙç lCçâünþÙn.§;†¢rèåÂóÖVéIÌ=#Âr7Úycrçs6 J6¤ºD¼ŽÔï'Í[ñºÄ£Ú{·%Z {¦h ñ\-Ø…-wÃ`Æ­ÔÍÓ‡¨•Ÿy>>;“�hxáZ`VPçe éÄl¥X·+Ï´eKÕa;öûAÍ@‹º?Æ7 Ol^;b¬xÀš ¼ÔÇXmüZÓ…ÊŠ¯úUÞ«F)Nü,ÕYØ,ú^]\@wûù@¨<)\Fð-Q²*–1Œ.`õ¹û;1kÚÆ‚À¨…QדÔB,’©cÿó€¶O1UÂEôRW€9‚dMu öøf'2ªRA£óFÑè\OÎŽu ‹Ô;É8 ªìÅ%‚èH·V"žó ßdÍ']í£šì¯«f7uL­û¡\ Ÿ$ 0³Ÿµè$¢Úƒ4 á&÷b,ÑÛa,Ú›Õ&›áz³QÝ$I€Ãí&ëôŒòÐ^8)`)È8ËìZeo1B=ªš€añ‹ó|ñÞ¼êœêvÙÉÞëHK³%]òušB±m좎h2º÷ ‹ÔEÞë ÷©)]¨ym¸ ‰*×ô4U §L ßMã JÓ5Cfb[‚ñ`ͳQß‹BE4?Uz£0Îo¯[ W´OÇ/½”c¦ÉW<üee[Q/`d‚Õs¯díy—ÇVB4¦†• ¯Õ¹ ‚÷ù8mu!x/<yûü’Ç(ø¬¬òŒåÞÂÓm ‡§ù‹…ÜY/¶-»EórŽŠ¡…PCmæâ ty®Ûêრ¬½¾ â¥f ±Î•\ƒ|âvH€Ö‡Ë]ƒœ‚{K67m·j}Ì­4zG~ˆù‡±ålpàÀˆ¿ dJßÒ§æôp‘ì$ék± _ÈSK.B`´™)p‹Ò.¯%sÜ*ŸL£–¥SwXrpuãmñÿ\ôì&Ÿ÷Ùìs îúœ0n„0á9é‰.Ä>Q -%ï׫ñ ãhMüÓ¡ìâòd®Jó!¼µN•lâ}Ü0Í•¿ÊBTm¼zârOxLøu Sb¦°Ï3³£y éÇÃto ö+˲Jj•¦®œí¬ö”pðdbÞMHma½)ìÒ†« œ§(å5Nú:+K49ïr‡9”æ t|¤pËYö¢{½E8ÌsÄÄw(Z[–äž¹ok K‰31­5ç�— Þ{¾ÜyÐþ ã^?Ó�=(q˜ö‡›cüá¯6p`(³O4èÆ�éM«?õÛmЄ6îóœ™ia·ÂôáA·±YyŒ‡¨h*cÁeç\û(=.yÊ #B î)i‘hÉ•n×¥Xg“é%luÒØû´DÓ‰MÕae•òGMoýn·Ýýdè›-MÊYê½AîGB]ÏÄ…à UŽ…Ẍ#X_.æct�ô—©°— ˆžähÌg•P/Èg¬ôÝrY--D=¢ºÞôÝ& ©µ†XÄçdÏ`@pHC�€d#¹ß¦öDnß³^8Ï^¯{[‹c J"!ܦç5ÓŽÒÙa/V°ôl7¤ñ#;åQ�¾#Tgäx`ä^̾,ü›nâC.€Ãk�ŒÁ3ChS¡íSá{Ånäox<É÷J@µ™Fr4|Q¦Ò}ƒdy6¢4ªŸ¿l–²C Ê™Ãü„5‚øð{(„ÎÍ=ë4"°pkN3´¬5â²K„ˆ{A£¸–3!„†Ù»SQ1½ó(c‘ž(ނӰæ^.Ø.Öà#SÙ·‚¯U°ž[íB$p®¾%qpAËÛ| ‚¨Ñ7twÞââKJÏÃ:ÖM²%]_p䣄TJ?íî:Ž7™üÎü)Uu2䜽wn¸Ð�>Q7ê*ªª=VË·áA­8=ÒC/e™Ìv׋ó†~•¯Q…$4DºÓ},ZøÙü{œYJ&:,Uc5+Ã}Œ[%êͺ `:F!Z'Þ©„¢è:Ü yG?4õ'¨<Ï&mq‚"gÌ ÔS{ˆ:¡¸n­‡üÕñKqŸ <(²Tqn6NNº· ‡'ÊlÏ‚R²ðÊ즓£ÈUºÖïXW±W|M$íê,¤›Â¦˜PM=ƒO‰Z%jIbÂWœqŽ›Ná=ïÙµ:LHbâÝnõ;Ê=©ÐèX·Dl]Á˜ÅdPJ„öçÏžûÙž¸„çsÖãŽP§RÍ JÅ„|yÕøüuð«ôW³'({}óç^`ÉqhñQ‹'Èë¾Ì$ÇWJ ÂÍÑû<”û=ß–ñðV=Ûg/¼7°ó½–Ó †8RÊkÙ:ƒZPôm[ÑFi|Ed%òôr¶œ·hâq…ǶëÁ©+†›Pv¹Ÿ³ÖUJW=Àe&k*Y‰6%bñH­}BjCÀ[&’Æg!й2O±Ôîegg´é{Ý=¤€;d^Ò6šÏ| _µp,YXçãë‚XåÈ~É%€+ã‹KæÂïí¨´éñmsX€Ä OrT­š“ÅÉãrNr8¹š„Xˆ{›ˆy7¢.iÈÛ×ϵ8†:l5)U‹2M'æhÈú²›˜^&:-ïiÆy*™¿x&ìXÒ‹ß»Ã:Ø™Cõ¤Z ƒF뮀£—pÕrò´!è ¯cªˆÅ“%1B•´}qÊ'¶TÞ;>Ôƒ@²32›:5Ùí®P£ -ệ¬ÃÕˆ¥¹¹%ƒPwïb¤Ê޲œ„§ ÑT!‘dÃÇ”\ð@HqrA‹ˆ—À‘R©¸ß½ãìz3¤Ü…Ç%¾w”Ø‘ÝlÊ©®Ép݆A®ê| iL‡¯¤&Û3ë²ÕѸmQž…61EAvŠÞò™o¿aÛôòy‰õR) nøEC@èzÁ£Á©¹=×IgÇktæO½Fé”=É»M}ïè|+†´½¯a[?Ö³ÏFŸ‹a¶rBÍ„«’Q Õ£uj´ˤÑG¶¡×ão߬½÷ÔãÞ®E'Ö±€SóÉŽ#tIõœôc<³Ë.œdM©(êjŽÍ9s­w¼g˜!—hsöNA#7áÎb$™¬Âwíð¥4€>[ra|¬ á/ð6#k©««êÈÚ¸óžš/H]a‡‡mžè]òäÕº2+¢º´¢å#ж4xºœí¨qoòÖã¼^ÞJˆ!\xŠ@€u­*eÄ�)l‰ pe9>Îç\sÑeg±ÝkpñÂ&©à£mú]zÔädOÒ—ù_­À49ü‘ê)/LtñZn&v(ä[ÜÂ$Þq‚לâ¯W:Šm¤Ÿ’†ä¬Ü˜€ø¨;?qxàêìúÐWTkK'\Ò´žNøx¼î6”Òf¤*),|Ý`xuíï¹æ•pWߊ?ô Á´¯ÎD†(âw¤B}ÒÍϵEp(DîJ`CwÝ$ÙÓä5{%»ÞÒ7N&L]©B,g«.õNa«—zÆ;„rF0UÙÜëaX­ LÜtç“]D¯dVw%œ«g¯©g­ÓªMpä™&blçz.…ÛúÆA룣6ÀÔH† »òÀŸ¹jl" l¤UˆÔbcU¬Ý©‹õ‹--0nP<òÁ°¨÷²|èÁü‘tœ…ªƒu)¼«<n¤lÎD9@€Çà †µëú»<º�ËUùMá`jq<N‹ Eí~Ï©·ü¥÷%õA¼.µ™¼¾èq²1MPÅrY'U®éØ{<t–¢F¼I]-ˆúh¨cã|ùÆp‘lı«ê…9ÕŠP4Lq<9ié6ÏÐÜuÞ×ÌxçWgä4æ“ ¤„Z›œ¼òÎÜ;Qx#õÕ#²$1yt¡ »öR®WW;xöðßÑÂΩƒÀìÐûÒ˜•¬²®¥½NÛ*ÒÇãJcE˜KÙ·/¥Þ´î Ü[Ù¯Vàð¹"ö¾ÃS»•×î¡øôyÔ¸;:jwÖcWªRKÝ7áz¯Wï†'í…‰C\Ï…ªšÂèŠb‹Ðó"qàhìÝ{ƃöd2å=d«ËP(ê^N>FÓ*¬ÁõPa~T>µ˜ø¤™¥^p±‹&¥¿i—Ñß•s13½µîm.töÍ}wštUÒ>J8R»‡Ý¤†±åB,Ã(W–M“üÞn`F0qÇØ¡©&3ª �öók ÎîVï-Q•yJè,<¯5rA<ýá{ÞhÆOáã.Ú«k2V¾¨1òÙ nÍͲÌÕÝ—J¶þw3€Óh|ň¼ãæ+×2Bï¬)w‹Ñ;ùºÐµlÓ…6á{Í™Öêôn Òœ8à‚ió=~ÔÈeŽÉä!ºÉbùú*8õU1ƒ ñtO)>m!òkìaÒ3Y4Àƒ,ËI‹eS¼nžn#).²g¶¥)û"$"ÇÇKžh‚sš"ƒyÁðkKz1àJ£ éÉ.·£¾UÕúI¯²æž¢àH¾¨CÓGõ&ÔÂßÒbt03ÀYª¿x øõrD°ÝÛéµ{@ ÕuçOQ¦²L™ZÆiF­ã•?-Ž ¶²Ay¼`".‘SV)Ùq‚Qèý2U@öE’:‡ª8 �°P¼Ç¨AˆJÜšúž@½ Ói5y#‘ð" ÂaÖ˜ž{RÍu*†Ï ’€ú†tV oÕ=:T·Z(V&]$5·}Áxfr¸‹-#–…wù«ªpYÌúnd<Ë<épËL#í̘êÕK°óð"gÞÞ7^è1€Z›³3Ö[n*æÓêß5­B¼zp}9I]HœuB¬ǧ*Gë<I¿{éd¤Ò!‡&uØ`Mí ’)½°t½|Œ’Î#t÷eÚzÃìyAÑ4òƒÑ*Ã,]/©)m Œ‘mµf·‰ö¹Ô¡÷^K;ß{ÇJ)(š/U5Ø÷¥Nâ˜ïfð¹,Þì þ‹ŠxðÎÇ»J†§°„=]xá™ §øSà5·{Au„ˆ–-ëÏé=²‡Pˆ²d]ü‰")” ¾­Ý3—¢—Œ7.¦©“¦œ¾£ãDÃ!–Â2BÌ&Ú虋™ÃƒM0$1»hˆKÝ~øPãʺ¹÷y=¥ó…xš^¶þ|z“ÏR*˜¢êVõÑt¨ìSÓÆ–Õ­7C çšIogÞ€†1›Yp½¹$ EÌ ;£²*¾) ¿wó¶‹Q@™D÷±¬·`‹È´'a�gæÀÞe™¹f6M¾ÂPÛ¸÷:Ÿ(“ýݪ²eê2JBhøÒ¾¦ö9,S*p‘MrFKàžÃêH#xÈǃyÏFßó%´É,x}MD‚®Áð¦YKÆÂ•µÊ4ë@ïaí{<ç­“`YÞº*ô¦³â©­–±)ÀšË&Ô<vH°±|À€Ñp�P”* Ũ*’‹…ã—]½Ï&KR™e (8[oÅâ §°6ßÕëÄ�ÁéS(ÞÂÓk‰¹j©Á¢­h£±’é÷ÖŸ¨V«¾nCäÍÑ7$Ûƒ¡)Mâ³ôÆi½‹*ÕäuTKx _v± $Ë“WÃ,ñS$gH°˜ÅòuÞ›Tdž«ã·|Ï‘ssÀ5’Í-oÀ«,5:EY³ ¢baNJ´ýÎi§ö5=BOyN¹ó¼^ðÖ¥J?÷ö ±î »u4\â§ðGvä K ãÚwwFK Ám' ÛŽ.ºG‚l%6øÃñÊ@¥zÎäV¬U=5„ồr®‘þ„Ÿá«¡àq~†‡ñhßÖ3Ø„pSM.ïȞфœa>¾ä*X¼™T'4HŠ‹¥hª¾`í!Wq•4˜l¢t¬~n¥ ê ôàÎ- ´CÞ”;MviD#aq*?-LyHõVÇ̃î.Ôñùl{Å{û€¨“‹Dˆ;„Õ{<2EëÄlQó©ÈC~|~ã/bfJ¼a¥Wµ==~éßñÍRWl'Iýlø¹6¦—ÍÉÔºÇÒï=íÕ¹¦;›uwî¡7H·g&Úóž4zÜËyIOò&]0Ý1¡½;¯Ã!‹Ú€D¹©å–›+a®ˆØºhÉÝnX‡³'=,˜“îZî‚ £Cú(“iZœÕ¸K2ªÅT*FgNÌÃå|&H2‘ê.¯zœ¬8 ÊæÞLêQ"¿öºÐ¬xão$Ò—Fɑӣ’D½8rÑâÖyá.๣y—¦¢Í³½î ƒädLŸ7Ó˺S•œe#*/|žéñCôèõÆ~oñÑm®¦÷ ¥bë@ú«!àZÏêƒ ªAF€\°×½ð�3UTç¶�Ù2æjƒ°îI!Bu4”åh_ ˜KësÇZ  W­ÞÈ}ðêF!'Ûlú%Fç<@™GÐjÞ5TÆîkˆjUÙש®{Èe»CƧæÝüœd-Ú‘4.b°œxßyv%OÖ 3&EÓšF1Wm„p3×%?ßÃJ*Í7…¸ˆ(˜hO«¼“ˆƒ‡ó ’$ãp¬"rjs94í{à %‚¥AÕR¯2ôñÆÂ®¯ù†Ž· ]ŒaŠN°,¼k&]|Š´Ç(ÞhD=š>«f/\Òµ5 •nuåàè!·0]‰ú!uºžtê¤ÕSaÁ§Ðù„dšâ¥çF‹À½ •J=©r–ÚXo ,*Σ\h…²J¦+™‡lŠò^Ü>~ªGk—Ã= ;ý®]]5}‡Ñ_wǽ(¶žµ=ÛM}ׄޡ;{†IB¤ú^Ú½ÝeB6ÕÞ§vs“š‘ ÙùŠÜ[Y©æŽ`êÌóÍP¬½Á|ë÷nœ8Ÿ¢Ñ.”[ƾx(±é¨1~¾t[O:žÑö«@¤•Ç;gï½°2qAKQ.gn°)™>Q†·›¥'j#Ðlf1�ÎÑÁÓ“Ù˜'ì^’P±“ôæ@òMkBIô.íMÅTêQZt‡pø>P’Ÿ >È€Fsöˆœ:†ÝU£Ÿø>"…® ü\ûnS› ¶‘¢XŽ˜²âPèZéñbízfyèz±ëâte4ƒ5]Ȥ6ä™ïÒŽS¾´Ø†.0ˆº«”9å|ž¼ëiݯq×yPBl:çm0„­ÚÀùzÆ "iCJx>ÇeT/Èõ4 Áb’X^á•'ejQ“³¢z+b�.®è«¤Å —ç!Õ½ˆœ r#Šd›ûÏ-¯„};'k�o;r3>ϧPàÊ IÔE¯íaö?J'²„!õn@Uó¹ ¿ZBˆ©>->|)¦E3|U‚u/pÏ$Ÿ¿DH/™'%»ðXøAøD‚¾ËŽÒNVÖÒ¥z&¡Ã¶©7ãy^몈‡‚<2 eÉ„ÚíòTA¢vÞ¦ôÎóD] –¶y± 4+xI³‹­ªS¨OãR«a,Éw°v³_XyÆåñgO´¥ ¾öŒ7A|Å»@æ„Y: Œ’•-}o¤ËÀ¤VR‡)£ªCëÞ ;R³3½{þ–Çø®dg,çqëÂ(W­ ¹'ÇÉld#ßC«aWZ<’}Ï„½hŸ2Qžõ ¸âªW¥7³Xa² BƒˆHà:sÀ¨™eبŽ›±md¨l;†œÁI*Õ\Ä”®oÃM0<\š¹*wè23Êx Åýè™õkï k{ŒtÒo±Û(·ì‡´Ác‰ zØ lÖ)s¨J'×î/‹iÇr²V»pW…ocµzžô¼ L.qeIˆ-O“ö^Iû“gývéyK»O™4È”ÝÖþ¸xÖi9|y’]¯_ÅšpŠA]ʽò†n;ع3íKê{ÙÛ\żˆ­ïÕÔy¬à(�è°X(eÒ‰u4Ý»žÁ2Í^ 2ò#LÍ™Á0(”G5oY'RP¡0Eú¸ý%ç` DªŠ0k"¥àªÙ¸w¨ÜÜìÑuUÑC69Šûl ïs•üܤ‚úÞþˆVqa8Ò4À>tçÐ¥&46÷BÒ M–W ú„œÜŸ&e¨¿é ¼ŠçÏ00¢Á³¨ÔãœvÔÛ®‚‹fÖ2—:!°Pg\q7/{->o« ¬—Mñf³e–îaÌUSÏÖó‰6w|˜jñ㹨*>Óvì QŸÄÈÔ )¶»1K~m kâýl4H8 îàjeÏ·âYõp\ «G7Ø´cdÚ ™‚qã;3“å!9k` ‹æbÅÇt\r´žRˆ“Ö?Q Qåâ*'®÷šó¶d­ ã⯦ ®èÇE®®Çïæ±¿KÎŒ&€âwë6VÙÊ®*ŠÏAˆ©°«xŠLq¸kSÞ³•’âõv€ç€1³múB*Ãqž:=!Òð/‡yøÒJ!¡fmG6HýREʧ›Ú”កNc§›F=£ØGb®WØâ*æ«�/Ó™Õ0iŽÄW B"T‹1*e¸ôu„9Ñ‚=C•Ö‹b3[tM¨Ñ1:•ª×¶N x$ªv èJàgᮈiZ̓¨Y/˜G-ÌɯåúÐr.#&$N�ß jÒ¼ißhò,¹X0ƒ)ººèyíYG"Å*eÄÐ$‹»çXþ"Ãpƹyav\¼Í‹®Ùº´Ts.[n{2Rϼæ>©Õ§ÑoVÂÊnêIÕHÔ-*²ö½”4¡°»‘R—~±/8çæµµ#çºn©Ð PYn8Ô#¿·¨çþÚZçT6qS¼dU\(±q¶Ëuü¹‚Å¢­Ñž_>/m j¨�%B”æ'ÎýP¢O=ð9x¨¼\eyC|¬<¡5Ð7{ÖØ1Aú.<ÊN5u°Rký|çX#ç5lå Ç#ª#C Øç¹¨‰—5É‘£u^Hè7FMdYÍ­âž Š"¾tJŸ!«!êKè—óÂf#/�“ùØ<îiDcÓ2o JbáØ.ôúl ü¹T6¶nL‰Û« Îh“JWíÓÒØ çOqÂÙ9Dgd0NÑ9¯öMvœ)vn÷Õi`Dk/7å;JÑ[É÷ÀÄŽÇfWæ „ø!fX.¨z²…a…˜êÒé {¿sÆ <àÈ‘Mƒ£a‹$%˜–óͬ—¯�Ñ0ÊÖ|0fÎ`‚éYxž™ mµÈ ºÀkV­XKK—º÷.º…16jÜxæF!Q`&ÏÇn+“Ÿñ¥(ù<t�xˆK'*òTrx¬ Vx-‰hmvÛ¢% u\Œ.°t±»­wäÙÓkW»áØÞZ­spZÏ?ß ùzR 0„}5ÕÇ£gk.TÄ&³³)Zö\M'Ò£‡D:0vJÀ4ÕDÒU¸ã4¾ZkRTÏ8Øðð¸Utõ´ÌB±M^šÃÞ“ðK9…2£zèSþt¨‡Ì¯‹è¥I&Wx)W¾­Gs)Ó²Ø-•ÈjGn#ÚÎæµ»à6Ù‰K·ÓùÜýu¤=ÈÏœ’æ7ÃØJ3)È*,XÉ.>‹ƒ3™.Z[’N¢-TŠmì <<¤fqX~“¦E%þXJ\D^:Y%Ì á‚Úëô\1@4ïÍi˜#;=îAmã@04p$Å<¿ejÕ4qÀG›ïå½gÄã{ Ø’+ô"Ê™Iuð9p¹›<ƒ¡äÍ}­²§un†ø"¨™†X´·‰î¼ Ú†-9†œ¨‹Š²´öŒÏ­Ÿ92¢Ø�‡©u0Ò[TÐá^Ìõ1gë‹+z㉀Ô÷ô*Lnîq&ô"” .¢îRè¼=„nÌJ=SÜ¥Ãåâ°IÄë|ëÌé3˜ŠSRï\ß3ŸÇî½¶NŒÁZÙ´œyHݬ+©,è’’š.èÔpl̳HÕÇSˆ2kéy̲ƒpG±0jÔ]'w­¬9!OÃÞSOcKK:z™³ŽÉo9†6ºwÞ)w7 õ½| Í°}OßC«õ¡px?™Ïpmƒ(P¸ ù»-|®—ÅòÂðºs;ŒŸLÓvìSTï´–²Å&ª»xêrd#®ç¯tÈëmÆ:*‚¨êÔÚ^®Ûxof‡Q­Þh×ekî>#Áz+wÅ;^å“Á^û{&R¯óåΔpµê#|^2$•oÐê±xƘ‚èI•Íš”4Tºp1½ñ*\܈i¾Í‰jlC$–WÀóÞæÓ'úâÊÚ^SŽxŠVúíãÚ7?wÈFßMáðÕ#à¢zK Žéwà=:Tàçke”…;–Œ…H.DMçu'šv«LÔë/2†üàýÕh¶±“Â,…ïðõ^ƒ_lë!Ö:¬”Ys÷‘±@¯kLjmŠw=΢IÅxñdfëF‰ü¥;öNºt’¦§‘‘Ñëѵ*Ï×f‚åF¸ƒ:HŠèðÌ|ά5d1A2+ì”@[ë½8¬éÜš:®{[h¥çíû &§òÍL¹Â±zÛk‘RÉ=§ _;ÑÒ÷UÌ…¼œIøRóžsì>­äÐçÏ•ƒ÷±m(ŽŽJ÷ f Ÿ&6o–RY‰,)%-Ñ«y"žÚOYŸÈ=uÁy†Ä jvèoƒûœh /ƒQ¥‘+ËNZŠ—ùž2³.8+?ƒUH~ªòŠf(VA” ŸÃçb(š›é9Ÿ­g+@õù“X ƒv¸g47sÑïmÏcg57pk›åE…z”ðŒzÞ¡ªŸ$¼†~Îô"‚OXo7xß\y6I�Ð@ôC½+Qþ!Ú¦GÞ~N>¹ý"Å^¼ähè8³®hïÚN¥óÒòˆõáÙrElÓ.ö$dã]YdßÔ1Õ‚3\ÜÛóÕ®}ÞÄãZþžû輦‹Í .OÑÒ’yy þì¶[Øñ"o Õ…šÔ<0ÀKü9K‰'w1j$eõÓt.”~Ë�¾Ï ¡tŠDË£¹Ÿ½õG>øÖFEAš9Ð Ü´K²³y¢9_}6ÑϽ/êì4Y�Uæ½Gó<è)`Í(ŸØ»L¬2 ô¾E-\œ\7™„†Ñ×ýf@ ¹5Ý Й0¯YéeÁsô‡E“”^ÉÔ¡ËgàÊÙÌ‹ üApÛ¬‘ëd*äÅjˆZ&bŸÆ£ªÊyï<XëÄ‘TÇõ½Á|‚�/êqÄ‹ºa*oB'k¿9ˆÂS™6O|RÒÉs•à€Õ9s‰&J¯½”m³¯˜™Ë%™Ïž(Ø€Ž€%Ÿ¿x*nîªqºÇ³%>à-Ð &:²tƒi9öêÍ+9È>%*tó–À÷–ÓÙåIЦcëÕýÕ¦ ž·âK9Zóƒݱ¤^Ý= 7i4$o±„ :GPiÑQ]TiH¨vÃiër¦ÁÌA†´ ÂÃÙ0GR-\£ë0³á4FåIõ”aq9K_ãç·äãybö@Ë—ºN]_ûã‡ÝÜ>“¼7$üè:Ÿ¦>` ¸:¾½Ü]²hÀòÒôÁ&“}]¼^‡6îð®òÈêR%iß”/¹¸y‡Èé5ò$\’ˆFp¹"UYrpñŒ×ëÃêX®ó÷†ëêܼy^MûµÁŽ•íäAÞÒ…¾iuçvÃF69® g^áÄa° “æ°ÎÙ‚Ï3q/YK _K­<kMhÅy}Äzø”,xÁÊºÒØÝ긤¯¢ß´c£ÊF% ‡°°£k÷wW3Ö;‚~Xh³2Ó:o).E·íH6¶°TÏ–uG¸qøeƒ±á<i±ò¶W­~¢H;ÀTw²êú8ùÊqi&èîp—ßNd<Qó¡›^PPœ|•6Ë(¯%} U^ø,ºêI¿y¯öQ¾ò¡²ªÆÒºîmNGýÔ.Xœ¼¢‚f ×yÛÙªv› “]{íaïçK}òšÚ@LâòRàçPiVÓ+–#ß5{:§'‘yÏGÂ…Œû"úÚ¯q;糌öyV÷ã\ˆYTv£…æàŒÆƒ§¨ ÙàtuJÁTã—XÚH ¾È*ùÙ”??%µ£ôsÞ]8rß^²î¡TxHV`Ñ�öÌ«epµecu°í‰ÑË®qÀl.*Ñf£yïªÊÝ)D‰¥Ÿêô§1ÔÐ K^ [Æž]vJd¢�‹—7Ôœ6®Èƒas vÖ¬—,¤ôÍ Å”_ìã)…É|¤Î`´ILº½u)ôâJí(½+“òt‡ë˜~œ;½l´�T¾ma±Œ®´6µN‰4ÁeÌ~[72^:�öJØÓƒˆv×ÙÄ,îJ“kË¥#ì²SÄíd%-ði¢ç´A{E§yÓ~Óoøž4k9†ÍŸï†Àí|OH–íiŸ[¼šHÞ|tìýޏk=_eðÛ¹Ôµ4†8 F�lLP‰s·è" ¤bMX[^ ¼:Ñ ›§ÛÎ)ÂJenjÄ›ÁÜkÄJŠG Ï UU}µl³ 1ŠyYïå#ïñzæ‘ýì"h+̬b#ߤ—ÏÎæYõzM=ª÷ÞÕÛâiA/è6„¾ó5Fºç}“ÏÕúüœ2Ñš_cÔÜ«†!¦›d7žÙ~¢üXr“ÔÆ’Uƒdp£v[Õ (&!œêY 2¾bìl´êju¼ ›½Ü™‚ÓÔ¸¹~‘eOØ`]àœ6§ƒ=u))ÖîÅ»ÂíOÅó)_á‹;Šeº R#†¼e)OR ëÕÓt¥}2ƒç)yµ;Û-˜.bÄd8wå{­ŠÒL/Å’Æ”Šud‚Â&oe,iOˆfŽfrÏßæ”‘ ¬ØÖÇ!„V^8%aê„O²a£pEw€P·CÑÑ^¡¾®w/ ±©7ˆ&‹ÚÖÚS;×W‰,ýªžÚåkÀÑQºjŽ]¯=£vlر!Þ!—Á`ÍÃÌd¼4y½¯%Œ!Ùê$ÎöÑf§'»‹Q¾ œK’~ütÙ¤-\Ù 0ö»×Ï,ôͲ(¤8/âFkbÚX?>Bì1`6Ĉë{0Œç¾V3 /Ø9§0Ôç{Ï`ŸËç¥Añ©™x6±oYT|WO"(éÚŽOÁ'zŠ9!p¤‚Ë}/›oNšƒ™_b‹¸+k(…¢Çæ»&[”M!&ŠÂbøLw÷  Äc’;;ìòÁAbsS·ÑÊ&1 -ØËõÞ–#*=–È^̶çzRîÏ:5‘J¯Näñ ˆÂH§9Ï«à7SDp›Û™²”�çDIY‘t«ðÆd­õŽ„tZù¹‘� à1ºgí@êFêÉ öÚˆ‰tÜ¥jAAƒø‚¢¨Œc¶#šyç›ljâ¨P�´ë·¶¯B^öE„r9Û_íA8_¿c¼KL¤ÑÝ8Z(‹¤]øžaRÈ»÷F‰SÊŸ�HÚµ;óòJ5„U´ŒïsŸ)I‘ã ‹ØÏ¡|§U±Ì$ÞÔå•%'9¼È:1ÝAŒ·®ÐÛx2ÑBä/,îå€ôÌ-{ó)L¾Ìˆ{žš9/ØÆÏu)5É—Ä3bŒ6—‘}Ú͂ř!I¦¨´ÂÜ€÷`uNaP`žóÓiîñ˜0P˜‹³^°ç;ÒÈ¢}{è®4YëœàIT÷nɇ2 bŠîl<D ÕúÕ¬ a8[Ìmx”»øEË’²\ö ûÎ)„=k»k"ݧâV/LâèMj_ðãèKŠE?líaš!ÚNNK{Ù½Foy%د»ÃÅvëˆ:L1ËóÎÞs6ÈÇ$lÕk;힬'œ¥|¢T›®ÝÏYÕPà­ì¹×­HH2 â‚ÉÉ,sBs•ÎC6àBg‹”÷š—À’-P´Ø{T²¨v…Á2  —@ö-k?™æ FD·mÇí”ÚW´‰#oUŸAQêN¥7 ì’Ze´ÕM¸ ¯NqàÌÒº2ò"JÀÊûØžž,˜$,—)Ç>xƒF¡á¸Wîl¤0_z§RTXÌUß4Ëö¬ÀApä#’Ö:ˆP:à@í ›ÆM|“:sºn€o[º¨Ü_ ¤À|¶ÿ\Cÿ=1]•í¹rЗ=þîiF ⎘ú ¢!á>zb•|Â;d‡Gaó2ìrx#á¤ÇÇcÆn PÔ"šÊJë¢C¬FMßI¿jA c«*y*TÐwØnK=GÍ2ž¹ QíW—êþViè™»8Ö5Ž·>Ý7°³þ<¤ ,ß_Ž) …ÅVÄQäåöÎ`ë+Ÿ§}Ïœ…«ÔÒÛ,[Kë]Èñ•òd5 ?W|›&0Ç´€€‡(™‘Uq§üˆg6&« „k´¸zÚâA27=€që4oÐ xôrÌÝ–µÖ›²'v‡pÿÜ;(§a¥¯šÙË–,è}Šzˆlqg·ÍÖ…¢`ö úeÄŘõ»8Ï5žE£{â=CÕ¼×^duä°¨TðœŒPe ¢|ÈØóâºI„†xl9£ÊRËY£×|NÂÒ<à9^íVïZÜlð.1$Õ›…¢wŒ¤)×/¬¸xe =^çUÖ¶r¼SxüøPýºTÍÉ×☠…tÃM.¶#œ”½¢õsTÈÆn(s@™È&Òe/ì½¢bgZ€ó Xt¨K­ ~™^ ›C2´@mëMÊ¥¶ –Å–6!rªÐ­F”ä„’»ÂïÊBà€€Í9ïÌžqùÏãT‹#J8Q‰|úv‘(Ó´¦Ýq‹|d›3u;Þ³•zx¬1/º9øX�b>*Õ @ET=bMi+Bòçå×p ô“a<#÷˜ŠUÔ£¬7Ô¦iåkˆóbÌ´R€zcöØj…k¿ÁÃ%.Ì�;Ûá•ò·e)­É¾0MXKU" UTaFXb³ÃóbÄËlnµ]ãäêÆX$À©d¯Ÿ­QF…biªÆŽt3ÞmÞ38÷go¤&}Jg¨_uŽ¿w\Ñ5¯ P<Dó¿¾K‡.½q'¤ÏÞ�Ð5§‰³÷’0ºR½QÍ@qóU¨WܸgÈ÷ˆY)Üóù;}¢ÞÎ1GIàk²¹Ïvü»A|.¤_" x1ô£6æ R}ôžÉô-:·ùÙC‹{¹,Vß3-ÏV')x(kŒ¢€ øwP‘®ñõë(ÙÆM­ZMX㇂¾ZÉ2H O.æM/¤WYòƒŒS±…âÍ8‚-‚6×GÇÄ%ÈÐC%?7òÄWs–\\®=Ó@¸›Ý1×.1òR¥µß.ÖËÙ‡AyL œžX¾Nê*Ã:ñ×Z–Ê_¥€®<w½7l€Uñ†Rs¢%€«\1Ïó@YK÷EÔóRdœÇ§Î$úîÙ6@×W¹–1Öæp›¥TCpImIu‹K3 ob“xÚZn@ëÏÑnÝÆ·fV4ùÛ;÷çon{‰˜ÓÁî‚*kËêÀïÙfM<Úx„/õ%»`õ´²7m=¬gNѲò�3Z`Xµy” á{Õ=°£CR”»7P*[e:Â0pÛÛd–Ž/rýÔ€d¶-×ÔØ \ĆölâaT£<e,Êgzô–nQ}K°Þ"&0B»è›æ:¼‚SԾ͢×çL`}˜#¨Ý˜ãM¼gn ¢ÜÈ�Õ¢=eý(õ’à`ÕEªô¥¾R;†,1î…máä”÷B¼^²“ê.<_—U»WÉ›¨†ã‘à¯4E=ÁBZt˜Ü1KMUH|g§Âr€KòÁsÛƒÙäàJe9¿e[ǤnÎhu—‡ÖÓyVë˜ bB€ ÛoãîÁäk¹f¾½z‡ïr¤“Ú‰›®çqΦ¬ÂrzOÐZ©¼h„ñlám7åˆ2å ¢áQUf7‰PlÐ],£ª¥&ÙÄ®…�%)˜¦GlOí]ÜP!&¼©fك𵈵|M±EJÃà‘:Ôè-úô^=óÕwÞ†m�âaºî0žpôŽ;àxAoÔ^„zÒ¾– K •¨v<Õ·…Þº<x¯Nž8rò(ºÝ»¨±3(ÚòˆÔv!mU)M!=XÙå÷¦ë•´Õu˜?¦2ßé ={¢ZYš·yú¶# mO>[D|®¦ÑwzY/%mñ~·ºà<Ûâpa©æ.së+æ²1L©7–Ô©SðtN’Eò åF³.8{áå{ý„Ù%ÍY¯œïe[S�—]‘P¯ á{U¶Ø¼ V7¸ÌSïµõThdÄ’s¡ó $rzâµ�ÄDQøÔÑ 1JS²ÌÊZ¿·¯Ø£ÝÓá!Ô21;ÒŽ N2Hš[ÐI?½ Q·HH‘¾XcÚ‘M6«|ÅÜ=ÞÏ„é)b^Њ<–iB1‹¢ÄØJŽ6ŽŠÛw(—Ä+oߣ&&J/GñyÛªé�HazïæÈAGËŸMBñÜìK"@¶Âvi‰ÃѲ‰s›zéàι34Å{*5f‡ãÏ€ ß#º—­èH:lÓ¼ Ì@w·ø¢õõ¹±Âƒ¢«¢4”8fç}É͸vÎQ·n4õŠm+p¹cÕ¦!²àÊýf=ÃQ*s:éy…Í'œ¬ˆÁL» úê¾÷^̰ãt+›£R²rPL/^h©°Œ³Žö>ñŠM 8rÜž±.ÓØöÆËÌAø´LÁˆEjöå#ÓN_¿kÞg–Âþ^?Ü�uÕÙ¶ÍÍ3Î{/Æ ç1™˜v cïñ ©_Q4ÚÁ2 ²r;Vb亮¸J&«ÝƒŠsm©UO”`Ïùu¸êÓÕƒ}ÐÌd+jxôN/Ž©ÌHW„?‘+K\Õ+oàhS/!}Êä@C¨¦O`§©ã‰%çë$hgÖžGÔ%ã;ç4݉Åä€h¼,µ¬2ùô‘öšXŽÐ+¯Áâ4k™ÐµÝ‹¥ÐW@…`ggÜñ'”Ç`2­cq»ºŸp<Ùà#j”Ñx+‹¿zñ¥—qu»U¨"=«—%óNÞîFU,w¢–Í-ëf2NOÆ‹¢±e1NXÄ}b  ·ïÕ’RÚªxŒÕ0‘i÷CÖƒ4r|¸1µ'q·´Þ>Þ”\tx¡K%w¥ç†ì;>\Ù„k ®XGüùŽø\RƒÜ;Ôå=ßT£eÐHÁo ݺïÀƒ±¯ñ­°Ü«hˑݪ¥T¦b×Îs‘¦¶wâËû^à¤/¾ ]”ç—+M±�rz,ó&³£àT_®f‹` œ¼ÀF¶€Çk/5ÇArŸ„Ch˜¾xãê›1<®ÑIV)àe¸Ž‹ä†:ý²o8à÷9€*Ún–2°qʰôÍÆñ¼½ Ñ‘ ÂàñtBŸÒq‚—Τ80†loŒÝï1£–zhã³a‘£‡`ØÙÕ® Œ’åžÛþKxYyã‚T±b2(Kš*àýÂ0+÷W›x±ýd=q¾{i(€Ò{ ,)yCƒk´O´¦Î^Ï©j¦àšÕ¼jh†ˆÀC¤ÅÓš1£œµÍ°<(÷t7Á€byª|WÊ×|Ù¯Áó5½B*S|ÁXøŒ9ذ’m39QkK îNæªhM4ž×óŒ'Õ+�)±Wð@cYá.×}ŒÓÈÚéÚðy¹OíÕ Q!:X:CÉ‹yýÀcc+îô=±ÙHc>‚Åɧvd­YzCSAÓ"•ðÌÞàܹºìJ5ùëŽ±Öæùá#|Â>)Z ¸R¿âbষ®êŠZ´ûð¸tav§¾&Ä5B¿Õ-ʺ¡Ê©zˆlhvHï+›Ýáˆw�ï‘ÄòVàl™(uE?€¨§¦ž—å#C\·6dµv/Å2µ‡”BÆ¥±�³‘ƒ³Å½G7(å;Ј ¼,Ö¿ð 4F*ü,Xf¿¯BA[ͱ™÷ Yåø%°ùb׺ ›߃Duhµy SXÙÝ Ã€™éתè[6SY r™>ãïR˜oV=-^>6¡#ºÄ÷ÞkE¡³Cß1gO| ÇedŸ6_S`ŸW¼Àó%Á7\ªPH%0Heï: 3Þy„hó~n£J×µOˆ|\Vj�, íÕ€®t•-#èËeçW÷NÒ¬™óé -öÃÏ6ô¹0§¬2J©}/ÈÄjæ-K­.AÄèÀ�S{ ¿ØÑ­‘´Ã÷ f|£ú±ËÓÎ\Z¤môu6g‰õÚm›ušg× nÄÃDh~Ø8fI°|~hêùb©èdfvÎgO‘†–Ç&ó%t° ^$¿<Ux(ÏÍS(Vð<s‘ÑÁÛ«e¬:›´*œ³Ñøéž90i Û§øf×5çs’Í>!È�Ô£+¯TÙA²§×†û49Òž"Û‹Í|Ûþ4 ‹áð 4ÕËr—je¨8S×¹![ƾ ½å&Ñ´‡®M¤¨qGb!¼5騰r5Ѝ®<#p9Þ•¢¢g'aÖÖ·n5JY‰¯Qq`m žf‘m8ƒÕ`;59DØæFs‰áŽî‹Ä7Æc‰K$ÞuOüùÚó+ä,*…ÕÃE÷7¡OqÈ©\fšøÝj[·2W¼zäWÍ à¾ ä¯4•T1Qy7AŽ ‹wŽy;œôéÉËåÕÍG°“ôçf\w\!5b (A0 ú!+UG×›íQU6§·‹/¦nß.’¤žqîœ�3= Ï]Ão|lÜi�¡1ø˜ÍG'ýC„"Ù$-_¡yßCÏñ#f²ª h(ðœ,²ZIöΞXÑÅ.ªÛ¢§Ï=ÐXœÁ›Y[KçÕˆdÃéahc°Â I‰ò´ZµVQ߀÷”  â&En‡´Ú£GMÈÝ/pÙ߆ӮŠiÚ!¨¸?ö@Mi¶ÁgNOgŽMì½{Á‹L¨CÙˆÄb‚�[Ïqõ‘›®Ì {Á¼ã˜ýâhbŽ÷=o pò9W[…콫”`‡ÕW¹‰ *TÙ:³gJ¥UñöM0qšÍÃy@pU¯öÙZ€¤>…ÆRâGv£¾¤/’Jø*o&øúF!·©€¹ƒ0ÍŠ¤ õ© ›œÀ€‰ô){¯K¥±r°­±ªæ1­ŒÎY"F>A‹œ×vê=ÄZ~ï—ôÉd³Â”¿ë–†àH*ûlô¹¸–ëu„È'.ËþÑy…Ñß« \r8ï+d~n2°ü° £2ÕÈ^%´xÖ>ðEgž¨§æ•ÉtïÉÑ%©%C½6ô”`ªWo_]†§H“$²êúX*<#ꢪƒ——Â=¦‘÷ìÉ®$ÈäRÍ « Ñ''Þì©v‹e/ózÞ9!Úªª˜?×@�)ôI½Ç8ºרSO¨\.Ë<v ^,}$4‹l Gå’+1³ýÐhÖK* # ’^•,Â?žSïÄßÙ8ix1ᢱϬLÒ ËŸ ΑFyr‰ê1T–˜±ÈÍë'Ú| Z‘ÖKÜöÐæ¯Váò4µIâq2ß…5$ÄéRE;vûs‰J{ZU¢Ð©dÒïÆÊE +Fù–õ=´&|¶5‡ŽP÷lFôL,ð™´\:O_>ÛÆÐ*šy­Ú8ïÁãlöj»ÍC¹0 ±A\6¤l·x¼Êäo€K´fêê•h¿žÕ({СӢôòá£Ú÷òò¹æàÝ f·Rda«”ØÉ*(¥/RBä‚䞤DC¨= |H©©oàØ ‡™¹›ôÙV_²Š‹êë -@P>…ËäÊp/ˆ†ð÷€•‘ˆ0%–Þ©^Ž7¨wÇ ‘+m?ØšÙ$\ì›Ñ’[ÎÕÄÆëxä›2^a]8¯š!üF¿�‘bN axÑ û^u\«U3Zz&'#T/'áC¡gbCñùyF<~ŒwLõ^JŸóc‘Wh}ë ªÑ‡^H^ù„]äÀSƒ®uèÕÁ%ÒÄñ¤.ó0®z39‰Äêmug[ZùÛÇÙi#ÂýÞtåns j!Ì‚VÏNC 4g8B…•RߥÉ5Ì« }dUx)Ó%¬ú`£ Xl€xÃit,¼@Pmqr­ÍV²Ñí„(>ënÃ^ñ(œÄõ€\hI蓇CïAµ¿°ƒ8b¿Œy¤WAÈýV[4vTé4Ô7ö˜J›®Bx,&‰íÙ[²ïVñ¹ÂV4: ÃÔÅåU4È«œ‘ÛŽ¨Ó(âRãj´s@T” Y=Ñr-LÃyÇÜ=ÛÊâE¼Z2ZN õÜCO$¥QEƒÝÀnŸ|ºxΘi©N-ëOƒq' òå5Tè[ì”,Œ·Hœ˜òæ°Å VÜñJxr±`œá ýb°€[Y*ÛÆ§Ž¤ÒËDÑçõ&"©àÎô EžûP=»'»ªù«K’Ï›çžÍ6rpËÂh"O´^aІлY–%G>ÇO«Ã^¼ŠW(](±‰5–ŒÜÅe‰Ù/OýÆâ £í!¯ œ ÐeŠ×å_ÍÂðšòÔBRö¡‘ÆšÀ…Jym?ÄôIâ'CnÔ�¢ŠvpÝí B€pºRÁ¹ îá=qvMoyCcwM-~¤ÙŒ• ²Å®;œèk|ƒý°7•a}ØÆ½e´Å0òm&j_h ¸ä «°“òpÍá“,H'ÃQ¡¨X:ÔÇ%mž•¥UÙǘ¼ï=³‹Å+¤k~2 y£tKöj„È¥Nº¢øåCªZö~¥ž<©ëLeãV¯*:ÊB^—¾²µu¥Ðr±Ú¥íÓdõÑ2;7ª3òÛ‚Ëñ(Übܸ—A{a”Ä5¼£{T÷ø˜Œ5uCšpÓÜ’u¤rÙùX!Oùü”ªe-rNm/#gKꉧø{ÝË4 GÏR@GŒ2?QÅ)‹³¼IìkPya/^½t¢ÚÊ=¬÷†6ÓXSrírHíP}{qŠkŽå%\>ã71¯`Æà½\Ü{U­}òªžãƒ<²hH8ÇðdI™ËGõˆ uO¥~Ú÷ ïž½Uon*èG˜ðJÛj°6|®K Áç@&çIó�žõÕ–‡O½äž­¼¹7Ï´3Ï…)\ÅÄ^­ÁsjBê�{Œ½$Ï%÷È�'¯»GçUËj޳•ΩR¿‘Eñèà ëh} É3«l|÷¢B»é¸5üLQލz5Ʊ|6‹§Ÿï Ußžˆ¹ZBiFôž›‡‰üÞeq÷Ì uP6¡R’Í`¶‡g2ìI6À6jÂvÈ3p—)r)K¿üÀ â¸l^óP”¡u oVÌ~PSi(^ê@ÐPÉ Õ!%Õp ÌA\Ü=¯Fu`³J¦*+€GiL¨y_ŽÙ«>näâg6ùö°‹.ëÑà²v@¬’îÐäÁqÛÔ–>©6áË®ñᨭ|G¯±»ëz`‘WÞHXCŽK´©-:�åú¾hRR¼›¥ ˜7Py°ŠÏ5´o¥l•ËÜËÌñè^Ú\H)\º!%‘áuÞ Ä^+A,ü«]´l" V- âœ?yšš#h:Ùo߃­„©O‘xçˆIrÜ+Eh´ç¾”«i{²üA9HêF»dßš¼!kK³ãºyóž ±â CtR4(dGà½Î€¤¨85J!¶ÃÊn-ùAñÃ.û‰X‹Ûop”vS™CïA¾dF£¢5˜¤ãÙd:ów‚Ï;TS™ØN§@42—ÄÂq246<YNVÎ*=®X¸Èײšv¡ç)ZÛ2»Ø™Üv_³.û•²¯½œ±õíÔ¢ôëÇ›Ð[¬ýR¸3¼\¹y,i^"ú¸ˆ©kÁR¯ð]–î…i½Åsºã)Ðsý汿ðÃiØŠ~õÜ ß8W{*è–K&¡àÒDqɂ̓·4úb(‰ß>ÔÒ~ä[€'ÔB|icjúvVn[xìí­° ›…O´y™Êjì•<oG-zÀŽ„ Ùgâ/sAÝ»$cëÑ3à,3â•Ãæ'Òˆ»%!)IÈÌ‚+B[«1Úì ½çáµg´•–ÌíÉé#·˜îëc¥�?à¼öb†æ«-&/ƒÄ-+TWK$eÔ»øT)ÍP(£ .[†0kK‘Ç‘^’KxãEi¦ôÓ Ò¤ ­<Cen0z©iöf[5Íàkœ6]Z¼_(àE…Ó£º&lËW gI©Ë½ßí‚¿×Úo”„ÝŸð܃}ç&©¾s}aý©¦/f©]Œ´°k†:Å\6ˆ9y€SQ*!Úb£¿ XÈiw¼Ö\Gv÷í!ÌMìÈÅdx>7hÏüv (—ƒÀm¬§'üŒÕEˆ,Ôº0‹ ™w_mÎ;žBôG1ok«ÙÓM£Òô…ê$lm:À@lÌpg§N×C�tÞ3ܤ8¦Ð!`Sœ„t÷«^L›P/º«•ç@³Ï9«î=\˵ƒ-ˆX%Ú*×.z&Š­šóøðxÉ£ë‘SîÛÌVÚ!ê Ê•4'¡”×e4·Â7E�Æ¥}![õφq£Ym>r§j¹K@q¨þ·ÅÖi5Vï…¾}ή ‰¾õRKG¶gô|Etè¼vž‘N +™½¥ÊS%¹NH„^쬇žëà A±-{÷HéXaJçÅèÚíS¶ lꓵ#…§z“ôxÂ]<_ËÎ¥·WÙ†zyu%™Bè‚¢ò ˜S¯IV×£Áqë–J,tÏ5³’K1˜¼~ñÚ.¡ÓTé ¿J“;BN8ÀÜÇ"ÍÂUjöŒpî=Óº âÖ©¸áÚ=£áé*MH‚¶0R8 ýk  Û”çå¶g&PáUS¾Š ’±&Á÷TìJ-<+ 1îªÊŸ¹)Sø68Ý<í›GéØÂQVש½=ì¡ïî@?#È¥R‚dÈj·&W|™ôˆvÆ#—§<öK1åõd]”©‹ mU6*du’EÏY7Ÿß#ܵ/qòò;l$ á!Ľ‘¹{Ïhç Žlˆ X^�ý\ã£Ky䢛ûì XÓFí ¡­îY”ˆ|õÞšÂPAÞ>.=é÷z.6Ê�îPß`˜?¨‰·æÂNU)ÓÛµfü^Ž+ 9L¶´&‡¾£çÌm»–­í>^ŽEÆÃÁF†è£kÏÃŹÒo³1Ø ²ËqÚJô„RŒßùÚ:¨ž¶i à›Ô`0âÇÞä@ Ÿ C>Ü´ÓätW†è3ð2^!Ë=}²¯kh¶GƒêY� K«à¼ #m ˜gö¶qÙa™ ͘ žÙÚ¬–ŸÈ¤'O±1ô®N?Š EÀiÜx™¯úm!Mëe4‡sãÛ÷bÕA«ž¬úËs!ƒxjà÷Æ®m8^u¥V!•œÊ®tÊhû¨î¼±E:õBê1›=kÒËLÈ} ]äu}zyÏX¶F‡zw ¿êèàB5~$¼O¼ñ¡5X‚ÕQÁvòó4ˆ§vyí‘bôȯå¶oä•ï…øÂ.(xÙIW½œ0ß5è6ÖF²TÜ}µŒÜI[ábnÞÆiò| Yz:® k‚Þ1N*ˆxv{¿«Ç㲇òf{¸Â>(¸5�ÌEP­„:¨›D˜3Ps©A½«‘íòn ZÌ\¡…ï̲EB©ÔÝ{!CfÛzMa}á)çÆ“nï ¥Ê+E›Z–dÕ88iM3µ+è¨i—×Î={rF4)ýpPÐÑHPü‚µ}!Ï(t;ðÞ¶9Íó}ËÂÙAå“Ô<tëÑÐÔºœÈÓ¯g¹¸$]½k½9R÷¡%® ®­D½XÕЦ^ˆ×u§Œ}XVî‰ú$&ןêÒ[|måÝÝqQÚ IäDïjFˆ _Ü«¥ÆhÐD}ËÀLBûhGN·Z1o•é1(IS ñN(nÊøhN¦¾žZ5îÔ¬óÌž3²êS²β"AsjÂ)«$á×Dö ½ñéŠ?sºaf¢¤ÀÊ Ë£d‚óÃY…l86² #ò~%Óõ†L¼Ôp}‹A0í©ê>×—uý¶w%òÚêqœ”(®D Ë15ÈèÕ�M† ?r¸‡CâSyn(Ûq»r·(X•Œ+Á$\¶yŠ-ÅÌ\L-bhß�܆ò›iR¡²2»$›b,3w"®åâ³ÙáW¢ùjlKH Ô£xˆ\bç-˜!?DõAbà’}l—w‹ï]‹=Ø5ÍÏ–¡Ÿ«î€"OÍÄ[y/PªË×qG;{!”ÊîœØøœe·\ÃLú ¬Ò÷Y(2î>†}×ëLù<òj`¾šn <Z›˜•·"$¢PÞÄ/" ©“Ô¢E^ÜÍéS3ˉƞ=‡èÉXŸžbÁ¬ŠFÛK~YC\èTŽ×¤ ‰þJQƒà�·ÔÛÌÑàÔîÝ“I¿¤W|I©,-©þÂâX ´`õ,jjs !¿W97ôLE¡X|Æ <Ê«ºcm¹âÜq³G;¨ù¡?öÄwÈ[dˆ’Ø×2¨c7Á!ÜOíe'u ¼¢j½1œ|ivŒ6ÔÅÝÿÜcÄí½ãÛÛ‹W‚ÄÓÐ0ïz(®eôÔá±Õ©†q_Øn²1ãjør1A%ªJæS©õÜ@Þ‘w!p¨# w cÍcÓäZÚf_“³ùº.H[*po�OúÙ<œŽ 1,D0–{ÈÒM8YÊn/x€äÍÊÓº„Y!~«w1;ÌÁžïEHyØ�JÇz� &¾&­Y_Ã\rK]jt@»Ž°ªfL›‰>ëõàä¾aŽyÈk ¸„€¶yï„äè‹öWgðlÉÇ%¬¸:î=á÷ðÙƒã>Çò‡‡–QmÀuØâx¼“D$€=–°r‰ ÆuEMíHÇýŒdt-L+õ=ŽAß+'žj%µµfÉ+9žä"­36—lܰyk>†ö‚“M]…%­/F«½ûxíèÇøx§+ÚÍ Æ«x½s¼):Ç ºqZ¨ê”Mà礜B9‹ý*/ÉMð=¯É&ÕqbYVE캠èö^|¢j©šå¶MÔ÷Jx|Çz¶¥M¶_ÉÛ†¹_#efŠZÛÃlïèD²hK¿ìNNUE}pTZaAS'í7ÂÒäo®U6ÆÄ‹Ë,N4òŸ?àU´1Çqè¾´¦Ó»cDÁr9ç¢ôëñ¦2 (e¡nxì¥&p±6¿›†¾3BƒÙM8à(3ª@§öhÕ…;ä|B n½¡ÖgI¸I‹æaÅòl´zGÎq,ïFa“ „ÚQœ ¸=gÅhU¡E)zОú¨D$Z"³ß)žK‡j™NÄÃ;^ eÐgÞ»™i¤ùҹ߻g=µJZb,  Êéé#ºò2†ÞLÌA¾›³Ôç‘jŠùÞ%Ó¥ÏÔø¢¢DÇ/ÕòL0úlB!s/e‹ŒQØEGp,ß©—Á¼ç&€½.eF÷¨uÒs¨— =d¼À/q7Çú™ƒ„ÁkA(s[{Ëï|í±Ÿ[?”¶GU+‘µÓ'‹÷Œ6‚Þ;�ý«m¬Rß2j$(^îÜj¯ªh5Èà¥è¼9¹«B~ï*ûM5T„'�–ƒYMã&›)…ƒ¸v‚û(WVCv »·xyÁ$ʶZ0»<ªŠ §Ð^¨Zã{%qT²x ]8çcq¥ÑœÛÛ7ÊðF/œ3Ü®×Ww¸a£sg±…hù 9ä\"Ž\¹™¢ã¡æ£ëT*èÞZ»K^ÍK²õq¾Æž'ÈìÇE€;+^”4;¡b “w×q`Ã4» h1tœ9'Z•!ø²ÊD.žPqp+bâÄ<‹M÷' ž­îÐïÅ” ?M°ÑFôôÈdLXf}ìTRðlCíéJçö±)¯f±mùS}ÏaJŒêål)»ÕªòϡΫÜÁfCß4Üç Î�›î­'w Λ»ºÛ>$ ©€â6ÓâÀãHËåÌãvÔuú¸ûÑqPÕõ£â5ÖÝwoÒf™1å5ì+eªÉaI>G‰ ä Úò�M0ðèA†-;‘nŸR¼yáÓÀñz·Ùß3V÷‡)»ð<ïìQCX_hUœäbÐûÉyx5& j1”‡+*š-vtgì}P3n “˜1k“u9kW6ZžÏ_¿gHà(3™í½;lÏû%9ÌZkYdf?µŒÓýÙ6ìsým„Ê¢ï%sR›onŸ¸˜dÑk2 ð÷šÔM¦á`Š57£¿qÚ´‘z+°m�ÂÒŠ2¹¹©l¤ ¢`b:=/t©à]©¶2‚›‹Âjòˆ˜•S†ç•GïºwLc¬Åí<§ë$;,‡—\¬ÇÙ‘üÌW ŸGÊÛÇ=&†‚± +kJ`Ò7Ið! *÷ËÒêlf.pËK‰&rQ>ÔIÞ‘U°° d½+Ø{÷¦øÕcš“- âd'ÑkÓ‡ŒIæŽÜN££]̄Šr_úk£Ù@‰Âp‹~¶±ïIºJR.G.Ÿ±_y ³ ,áK¿ú³qˆˆ({ôHnÌaû¹Â:öÛ ™°ŠÚ‰6¶dµ!ÀëÆzc´GdíÔñVkPJ›çõAE—æ‰à†²41oª-ТÕa0Þ „ž¹³âŠÖ¨ {{)¨ÅyçÁ6 LKXçÏ3¸Ú'|5\úƒ«0ãAî§€$“ÁrÌB^s!-èj¦Ã“³ˆ€Ò{„ùÝ‘>=ED"¯Ã“–š«>%s ·÷Ì´J<èÁ?dðWᯫšM—;"4g¢ý1NrÓs zW÷(1Ë÷ÙF¢O>?anæËrÏqÛ–;§®ÅŽ!ÍTÓ0¿µC?lxyŽ"h0@Çš)YÏE·*}«•¹í½]òÝ¢ÜÒ‘CõfëÚäÛíaüêæÒýB_j‰9ŠHk‰5½Ð|bé˼ÊZðR¦ÑNÏá’Ú‡t^?ê1}§Ý‡z2F§(Æ¥!O†ˆ¢=…ßFP¬k•àä3ßzæ G¾Ã‘~bGÄ ¯£‘Øð½1Ècɶƒ!kqàîˆ §¤¹¢JJ÷új*° šŽDQÓ‘º–èð9Źdð¥æ­Vâ.?8ê[PÍŒ,BxºŽ¡”7‰@Z¯8Cn*ƒäàîu¶Xbs+Œê¬É;ÆDónÑŒçi”`n¼Y:9y¤Òךð�õ 19`{{€¥âL 1ÞÅgãðÏE¸–+Ì #Iäâð*CãâyÖin lê§ÜÊ^h‚õäeU6õKòÍ€¸9`zï)&ÐêÛ&~$`œ^©+WàÅX[âùv ä>qÎÔ¥MŒ°X\YÉ“ñhxoÒXZqxÀ¢hî*â3ÔÉ 1e"Ê@t›¢½ÛäPŨ!ME­ºIOäª`Š“Þ“ ”狪~q¡LP¼"·T3O�w•1²²„ÅÜa`êŽ`ÇMü¸ nMb¯ÞCÆ>X·[G·•«3ײõEêx:×ð†l¯j­]í*hàÈÝs=NËRß9‰{.[H‡hukh/â¯Ö!ýz,÷f|!îñK'R©~•!á‘;ÜËëÒjâþžº¤øJ—Ð%›ûv©½u„¯9ÃD?Kš¹~‚ : /ªà’©^áCéæeHÅaÇj»�³Ž½ÙÔëñ"^o»³ãu%,·`ôU‰«Üà¾yOÄÆ'ÍaáŠóªÙ½TçË1‘!,£åœ—Ï„í°·ˆšvb|Â4^jl& Ê=ÓÕY³‚]m›&¿ÂÆêbªsd€Mbƒr; ºùÞ$Ò´{PkÓ 1=ç­LüRRi»ªÃñª¢€�%VDZo; ið¿Ç‚²Å6ìom°N—YáÉÍ”—t›—7Cn£iYt«átæÊà6È Ž¬íÅxñÝ«Wc⥿|CxD[<óÊý²ð±E–Fg­ßöÚ’Cê«w þ0†ß³Bº+vR À‰Y´õ#6×¶¦·}‰8’Ãa.TÊ4ì7Æ >ýhMû…â‚2ª—‡ß¤ß6‚ß#&qô²%°{—ó„DÌJ®ã°o^Ü*Ë+2~JÍ¢å7õ2Iè>Ð=¬;7͸î¨Ú§Û.ÖéE½~¯Ð@F'UŸ®ÏÃ`….­ÚàŽnHÉ’Ž>yn&ÃêªB//vý:m“¢½–ãeÓ,s= ŸÂ#»Xfƒy»šÅ^ŒÚûô³u}¶ŽôyÏ=’ýól—€×�’¼‘ð,˜‡ÄyuLJZ´¼Q¢Tä>Ä¿íCN˜É•6Ô•pê÷Âñž ½‘–]Ü#òwå¥Ï<¹e‚•,¨É鎅–$mSáÅ]~ñŒdÐBßÀcRç#Oô¦PD–‡‚„ã!^ƒ<¤+óU0{Ïm3Ý^ízfˆ†Gèá3Ù¢â=yÌ€6[,ê/|e&ÒúÂÖ;TßÒ{‹5ÎscìõyS¥ð#9L²¥RJñS½Ö)jM r.@“q£A- ð­FSD·nsÒ¦|nï6û¥2U½8y‚"fÐ<Ïþ|wøî°·tØ›¾{ÜEá¨Î¼Ë½ëe²øZJI;#õ.ÃëB_P©»µì×I+ûl1ž'šÖµ>Í*u[WËÓŠ-¹J±{†j}„¢-.rdWëžä°êhp˜§-1@»„GBÏ4‹½­ë8#2x¸ ›;/!ý© žh±¹;ž’{Ø’š_ö‹3Mca…I |ϸ#Ï‘Q$ÈáÉÅ#׺š¶g[à6å·¶f‰îM ÛÎþ(‘@Ø&Ô,9ò˜†‰ví)OI©¡KƒMÛUÓ@VSõë^�ƒ¦w4yí׊¢¯ËzaãA™´f9:To/5›KZ1ÆÞc4•;k‰¦&”¯ÓÞÿ쥘<ásÂŽ÷Š’^²…ª¹v_0섎:Ú(±“³§†3¯Do¨½žÈ|'¹ b ><§ Lcžð‚à’Þ¬U«¸#«ÔÃf>õÑ虾܊”ÔãÜl£9u †7¨±%E¥Ñ·ïæz£0ü¹(H»rÉÕtV²¶‹Gœ?èדÁü:tN§‘ÑÔ¬ÆAM”ÐD†mÀtNtr'‘8ßha[é‚Àé< nQ²Tj±æçéù¹åĈ<^å—-¯sG´vBl=¥�·Ã6�ÁwÄlB²KO‰ b}¼d¨Ó½[Ìä¶äß 2vw¼m4Bu}žö´·@ ýé×»ƒ�>—ãõZÖ¸4â½&yA[ôwÐó£ÒU“uuÜÇù<<Ø\jrVB…†ÓÞ8¤´K ßàÆÝä`?G9ç{ü(³¥_ó­3t?ƒ>WqHD3¯ÚÉÄ,ÑÁ¤-õœIK:9©I÷¢âòή’ÅÔ£¢1Ŭ(qäæLÚR¹pα^>Q�¬ƒ9^ Äk‰SÁŽ—m%â*²h­­¤P]w§Q¦àXáÆêk¹ƒ{[¹Nb!=X|ísM˜ìã)¯§Š´yJØ®A÷–.\`gH]’U±‹ñPe¸ôí‘”Û@†Î›;͈Ì!ä«áÃ÷RíñÍ2Ë-bidøÙÒŸí£u…î¦ ]_ âk&‹¼iÁãQ±€²YU¤”§ƒ:b;'yòʦïÂá¼ó$LƒZ*$ lk ~&WFÐë§¼ÀD®gÂȯèpšmx�w4Á¯_)úpÛµ§ämÎYùK ìºÉyðhŒZaåî1åÆ3m…Ά`s˜8H½¾ÕÇ¡‰×ªï-"â3Ö”Ô³|DóɺvK¯ÏP®·uh»(Ø0Ð ¿�:pÁ@pÞ}±~ÅF¡r‚­+¢}¼¹"- 9½³k¦Šé>ñHpêÞZ’nê]¼¢•V\içÝ£1ë !U%(©X1™ùŠðú‘äÚâHÐ[ê)>ÃÆÙzõ Š(wÜ0ÂººWU8�³>½Û{cò¢ wçé¾U}%¨–¢7ø˜åUP8K5²ž/ŠÔ2ôÑ®½¥· |hòü½¬-D|dëJÜÖ'NPŒ­ìœ×«Ï¸” ±`Ψ_cíi½·…–ÊWË>ê«p}©„|¡afIæ¥r¢å…�8­v¿™ã7÷´^,zØ£×›ðÊ}èʯââ06{T(“¼±^>qiÛÞå~€Úîòìeg5Á2Ì&W_ZqD0Ž×€Úó4¼W ;wëÒÖÎÛ'§Ì}x/ùñP!m¾÷âÁ{ò< ^s‹<þnŸkryÉ¢»„ÜÖ6X:†À<8.Õcg'ÍÛ5=�Ã\¬j1(é¶m½xV'µ7c­•º¡ÞGèIõ¸Fú‚,ËY÷y2T£Ilì{ÏPÓDN#枌*�XÉæÝî•=!°­3(©AóÇgu ‹ÚE9œ'ÄY¸ùì=ÎTå'+ó®!A¥q«z51T�›Îëu m§Ææ¨ÆÚfoP“mJm½·óVÊ?ƒkQY„ñ$(oV¿ A¾¾‡ÅÄÑã4½+Þ”'Ï‹Ómß {† ÆÎ)óî]yû¡ô‚èÊÊùm­,^IŒC8d‚vzBœRqÏÊÀ£ Êò8ÈÅ?÷Vô;Aó )šå PÍÇR(A) Ê1lÛþ‚5U^‰¡Ýí“àÛ~<oJr$ò¶e.T9ñˆW ¶6²Z„±°Ê¾Äí\B; Œ ™ƒéySM4Žú^Œä i+j‰< Þ4ö5æÖ£“çKä"Ï5l‹5&ê=)Åà’0“.ŒB^J©6ÅÇ´$»èÄmÂóÐzyØL"º5õ™ÏÍf&P¾j,SÅ©¡Â›1B·Æ% ™  ^ÉaŸB34|Uyï­¾CE}§o;Dۦ؇TVˆ?}ôj«Ÿ:o•»È\¡d Œ\EDoß̺û…»„;uªêðœSc%6ÙrÁØETs WÜ,×J?wêr¹Ï„ÅôT:½ Þy�³u_=K61vcÊŽG¥(ò¬ìnjbíÝÖP¤Ã‹ÂGx^vZãP½,Dh<SÍ£rè“¶ Ó˃œ7«r^i¤ª$úšHf ’Ѓl©wÏÄ^ž?|Sò`䶘ªèÊŠguH¦ºõ˜_Fu`¥¢–‹ç8YGªjß@:½$#%~ã/Þ{úbª&ˆ=ÀR9®Kx«G”ܤÊRÖÔ­ÏÔÖã(Ýô‘ö襦ú”Epäݼ½@Gõ¤”Ç´Í@GE`šÓ¯ÁÍF/-i–`À¹‹õÕAWÌ»Ó`‘˜.�àÑ»Ÿ ?æi;ÎÆÑÝ¢U8W)†CÃHå®î:Žp –÷8ÖccÓXS¡à“>mV¾Æ]z/»…Ã_ kP)?ˆ›£8Ì ¤í·> Æó‡ ≉”îæ¼õHM÷Û÷ .{I­îêú타¶›HÅ{úrL6Ýq˜ÏáNÄFö,1y­<®/uNx°@tWŸ­†rÅÂÝà­›"ƒ-6d—Ǿޝx+v(ëm²äÈbÅœâHý5[¼é'ZúÜ_*ltU\¿hºGSÃ*áþNZÍhß“S´ê÷ƒeô4œIhi•J [èáBGµJ-ÑŸ›à�NÌ‹m¸¿?aÍà¹4´HId$¤¹8–ãöj2¨ÑD½sȘwúX îM?ˆ*DØwq¬²àÏpâ)*‰_KŸÜ#åÒ#è±ËÞÎÊW÷ñÓAø­¡,òÀX à²ÑóõuãuÔƒóÎJid¯Òç9-ƒï9ψ«©E‰æ³2+iÏ5{NvðlFASº—ê¸2픵`Þ3…eRÑÎÞmUyz¤Ökß¡jôàß%—år¶Q~Á!Äi+$Õ){Ëš@Žóu‡Æ[æ7ÖU¸8{L¢DÙ°H¯͵ñeà–Ö×cº Î õx†Àz¨¬’=Æã‰“i¾‘°ÅH¨°w"^\»®fH¯±¦CæÑ0€9õ¿ª®^[º¸h܆€Wo|Û˜ÞËWgÂÐc3Kz£½h? ¡4Ûðö4.Õx‘\m¦©wkùQP8†V«¸¢š·é£²@ž§2ËUÔSÍ \"£ñ>ѽ±ÞIŠ÷¶¢\s¤’CçX#^úÚmßêŠÓJ¾dC3y+÷j•fÜ êž‹¹ãçáÀQö’eax¿p›"ÀCTî~”³Ž½Ï{aŒ1žr‹‰ƒÝâE¤’¾~Çi¾ðÀ3šg‘œ‘"p—»“dõ ?I/Ú×H&êÅ^˜&¬tb:y3§Ÿ-„ø³…èíƒéëIÌG±NYû¨ä¶HÚíµ =WH’Û»JÊ™O“)‚¨¹¼^Þ�L¢Â°Sæ›× à¨é]C¡Üôƒq¹2èÍ[Ÿ/&I vŽ­”G]=8‰ƒ#¸í»7ú"«™Dê¹ú5ËŒã²m!e1e¶=™“Áỉ°ÞkZ.Ü»‘ �ðôž«ÝÂ8çÝ=«Ù÷À›´•šß3`w³¶WnEÂz ²‰Ïjç4ÉBÉ"F„'ýlŒè%{×=,›íLÜj/d1}ûÔª7–¡4öDlÏ›)z^ Àá.Û9ñØšøéÜ=j3¼Çù\Ü’9Zæ >KxI¶ªíwúWA}Dó�¤ö4µÌßáK˜JÄÎVBó¥Î·U`ϵ!»é ¡ØCz‹5ü²»ñ¦º»qI£—<«÷bC<Œ¨ò¡q†?ÜÌz¯°´÷¤k°K!;`ƒO¥mrðesyÞe=d|¤¹ æB“E~…¢œöLØAŒ-Y6tiUï k¦tuOjL–G… °zìÞdJÑ<Z@kIÇ °Ë�ozã„Á¶Êfj|«év*ŠP¸]ïѼ™gÛ,€ Яqž$» ÍòA5<âkšÐ( ÁYa�t^mSlC CܾwŒ¬Må£Jš8Ð '‡paBÕβ¼Âgd<ô"'aiÉù©éö6Œ·GÊjó&"f÷Íf BÍ;‹GJþR!—:n†‘à©M Ãy©sýò)„nÛi/z$ÅÑyg±hqd²¦ð‰Ú"xêkƒ÷ȵùTŸæe`?ÛG)Eu€‚ï]b†VQ/× %ÈÓã£ç}›C¤’kïî=uRæ.F.ß –-Ö}±¬)ù‚Ǥ’0Ñ‹ÄlGÄÛhŠE°Wôc§+»Ó'ˆlý–Þ<|Á–¥í`íýª}ÑÅ…2¸³ 'ŠBå¾¼eˆá�îGÙÒv§¬oÛ›]ØÞ#ÍTÍÊÛT ÑŽ¦<£œ¢¶’jÜëkßã;OÊ-ÿl"¾?d¡Ú<î—‰±qõ<yaÍ:ØB3¹‘ãÊà¥ñž„Ç*2r5A ìbÜ;颋«”05nC½eÆUD(%DyØÛ}~Zí+ˆ`.+fî;‘ØÒö„ø�ýÁÐ"²wÐÀN‡!¾}e%=8”,kÊëÅ zÀÂn`Ä» ‚÷„Óý„H°…u•ùñD¿1æ£wo%ièð EXŠŸZ‡½'ÌíerÞ°y½Kæ«ð1ϧýú™rÖn¶µh4.¿|B+eýøÜ `vÁ$±¹]úEÖt+ÊÅÞiß*«pn¯ÜƒÅíÖ)¢œˆUTÐÝ¡B8Wǹ�^R¬Õ�º¶¦§kRaÎs|bñä‚å‰víów+øvë‚‚ITìqe¶‹oçZëÚÎpø&8•¾K±!z¸´$ío¯^½£—rj,@Yú„H™µœã™ò›1]{‡c«ýVÎÜ_B(VäÃ;…ÙEE‰j §½–p®3¼lîqläâÆ¸¾ÝÎãª}F‡Þ×ó]ÅN*Xà"Òüà’úõt+6ï˜hÈS÷Wª=nM�¡@›‰šÂSšÒM:îÏLÁJªøÞ;\}QzQmJ•zÞq>k¤·lÇ çt„á[Iv„²}fü-–OAf«è{7H)[zñ2Õ€w$@š_êÁ „®šEÕæ~ýÊqÏÊ9Yäö¡—Ü û;ŽJ:bòh¶Hj“‡ Zµ¹÷ÒâTÈ•i£à½³ÙŠíí—–q85Ä‚×ÅÖŽK¸CPAÜZÜxPdC+=Ä•#%³¼™¥9#V<´‚ð ÚòÒ‘ÇÓ–ÌWÞX÷q$¤«v¾´’*ýÇ$Ë ·[Èq„ªŠOCÎE@‚µO=,8ìå9‡i´Ô4Òz?eñ7W¯ÏìÊ6÷¥ïx¯…á�‚_ži{0,Éj˹Š8÷ã¤÷ù�ä‘Ú»©}îݶá)åj…-,P©DíN‹ï¡#2"^‡¬ÔXG+”q㹑|¶þ\§¿|é;7K9|u�‹ž¥Õ|È‚/‹l Ñ<ѽùáÚ‰ÒëR-zÕLæ¹–À†Ss¼œªkáŠ|=ÏßszOŠP Qžø½§/ýTµMìHó :6Åj÷ÍêÛ|rsâ.} ùÆ9©hy†˜C§ÌcUôž±…gbU‹ñ&T%{Œ)¿ÌiÕBö℞bm$qÃæCdt H™9@bMh‡ä×ð«‡?}1}“Œ$5ˆ/ý8véç¬^f‹i¿+h\UÃq´k’Ç)tRü⌖‰gŸéq‹Jw:=°™Ø3”²æ-[pA£}äÖ@ˆwuï™Ë3‹iR=M©Õ*XΠíÝÊ­ÿÛ‹üóïÿo8þã_ÿ™ÿµ$úO2þýÿ5ÖŠ*¨t|ô^½Û2~»Eü®GhS©Ë©šLYwÄ”nL¦yf¼á  0F­$èôÚ ›ƒ-²Ø•‚6»^Ys-2n¨¢^á 1 ê¶bÉ}Ó`D¯}ƒâYí9WÃf¹’Ë{Û&ÂzâWÖd&ýœ•Z�aœµÑ¥Qq%DˆR«µÏõÞ Bì+¼™àWšÛ¬ž4J˜Ö ­b­T“ׯÖMÔFÍèá 9E6ŠWê½Y–±ÐâãÊë{³¼X‘¬]ë†ON:3÷!ïø›,.ˆ8ßp€å*px\8~}ï^—¼+ߨ¢M‚WÓap¹"Lžg'/›T‹œ1ú™y¢Üû¼;k.Wv’˜™¡óðmv{@<m´×Ó—åNÍb"·õr'tØì.ôÔEª>õ"ð%<k„Î75¼OAß[™âR läÞ´gSoúŒHu›¹`×ÌRæA¾—`õì1Ëtû5.£Â¢?óC<`³YIÇŒKNê+hA1!Î(¶µ/Ÿ¶fkšø3ä,cÝ.{'EŽž+V½*™TÛ<«Ì…“+|Sæ÷²YΛ³åg€Ø“ž™‚*ÜljנzljJ]¤oTÉ8—®ÛUNѳ–¬‘¸Ç Œ»GP`º‰DˆßcÜ#ãš,¨Ü‡ú^xðÞ'nVÐä…7¨ÚZÑMâ Êé'¶dGùÑ\>; À_cêLÈÔ©„Ù¾¥|j<ï-[œ9ê RÕj1½-YnÞ”•GÑ/µÖÄÕmSdéM,{Ú¼{½:~P O`;£ã:àëÊS#BPSñâ1¶·#ì�ƒ¡W‹àáˆ3QlG¸Oà ŞÊËÉ¡‡ýâ¥Äu´ß{挊ϗ™ÞYžMöÝ†Šæk  ’W â†ûT5¸PŸ>(�yµŒ—,Ãm3 ™„áy>Ëh£´›ºš—Zu+yqÏCF2–¬.¬±âM¼í{:§“„´HEÌŽÂ(ºÁêöž–NîS¤Š{ÜŠŠªÂôî)º2L<¸ Ê73CçÏ\™õˆèÄ‹‡5X ´`½•ðH+�$12–ãqZ£Ï=c–:6I@Ü07wÂ¹í²¤* ^ѹ4ïf#yLuHp‹ž"8î£YM<þÌêŠdkVŽ žšší*ëô>Áç¿,˜S§$@æÝëâ*·· GfŒ ÞÛ–#á}@V4e£ó. ä§Ô諈~uÒó¼XÞXÒ@.Õaß¼]÷<Ã*UЂ²ÀÙkSjWÆ*·hp+l˘5b‚êIÖXœT¤ ƒw¼Q¤÷n{õ9Ðs“L ŠÊng€—äÝI#’`L£OnÒÝ$\;W™`8¶Iˆxœ7Pæõyr9Þ€<3@õ×’ø—$ÝIRÊÛÙ#g‘ÝàÒ>O¦¯:ê‘ÏS ER‹ J9gn®ÓL !#°°õŽ ãצiï&䢚{ÈÅœ)'IÐ1à:Ó4Á@‹õÌÖ›9³0ÛÙÑÇ,ËPë4çC:¥IóÀvã–|èVÄö…¡‹·ŽZ3ÕRóŒ‰ö‚²1«1IYfî‹©€`©œç;b(­ÎU¼Ž»ùˆ·OUœsÀ'ެ5yúE]¬ÚžòzZãSUÌ•»uò¶Ç3²) †dºÎfåB²@eÅ,Ø­ûlÄaš 4ju‚ÖæB³„ÊôÌs?òPÚlCÑe…z |·ÛnD)ºöì‘Ë2 w¶pøùØŒlOÆEØËGçÃ$h¸øêÚ‘:vy8Ë/#aâe$7‰_+YUG˜­[?Gh‡fqAõ͇Ǭ/01^¹{Ï#\¢§~|ˆr‹ÄÈØÀ€"ËX$¾ä™�°±gõMÓ}åå gÓz26C3)V¥Áb¹!2<¸Së"ÊÞÈ&÷Ñ’’€ç¬^l$|Ù¼‡âÛÔ#Ô„¶;¸)kÅÍõR¹Ð‰—Š,SÞ 7•‘'Tƒ;°ÑVQ%ÎÆo`w;.P_3åM ÃÈQ»ù{îÐÁ”ËÝ›vwtÜ^žyÄý^­ƒpB°D¾<#€‘÷˜ "ѷϽ7^GÐãÑ, —@Íýõ‹Æ¿7ù§u𦮊`9÷ÁA²Ý†iBÔË„(Øw' Ë;f´ànn‰-™UÝb÷>mŽàÇãÏ»¸½Ç (Ý,à8ÕЊhX/ˆà6$&ÖeÆŽ” ¢VâĢݡžV¯p;$ÇMd3©ÇDhkÍ#U ³ÖY$�~édýÞÝši+|+•³/îîçi53à9¢ Wèch¥AЂTf9Àp»hnH&X̨ܒàꚺ•(•­À®-b{m.¾l²ØŽëLÒ¶Ôh ÍÍYõrs_¼Gl±={s¯¶ÀR°eâ•‘2ŠÐ¿!ÃÔÓ±ºiCü‹kóÓ‡5 KÅRÔ0cP“ˆøôQxV˜ð‘N仉7Fá8ÃúfoÈõ$Ÿ0ÑLëZ›‰<n“<-xẻìQ~û«5•5‘U»Gp‘;†£ŒN“U°øˆC!¥g¼g §•k<5(ðH¹?É ™¬Y·¤ìÝxl ‘Š&S%Ïo®È¼ê(™úÅÂfG?-^}9×i/{+OØC7Íu"Í©t±w žºêT§q(óïI²<Î+4Ðz gùá›_Ü[Ikײá6ŽÌ†½ZÀQ³Ãø¥â>:/ÒN=žv¼µ{"žI‡.®ã‘¾ \½M‹;ÙÈNÁhz²ÞÛe•ÞýÀä{çfÎ&½vÕ(/\÷•³<çDÝS~R7Åö op]S¦{àß Ó ‘up½w‘ÃÒ÷‰^œãUSW¶9Ä.6ƒ½rÂFò×ÒLvŒ7¬,²gÅ›0:²Ä‘rÙéjÞ˜òЙßêC¢™Û! ¼Ö�!»°„‚`, ~‘÷*ŸÚ¸/º]WãBdqÆöµétG;í‚n«I,™xºK”_ÆÌ±Ž6p(áxÜ»í`ŒÑcOõR¿½õ¬mb'»F2kâuæƒ2S™Ô…¶BN«;ÆìŒÇÉUeæ}›lØëEIìS/HÏÞÛ³z™‘å›Îd>Jx2ƒoQÒ—®¤Ç+ó 50¯ÆšÀQ”ÒïzªE—ò½á#Œ—v­±ó8%TŒ ¸9Áy«Ä1«;F`Ÿ§ÍV‘˵J*è¾ ´CŨǖ<`C&Áñf)·–% мÏ[1ÎöHkw»ý%˜®½ëÓËZi’ä2Qΰ¾×î‡.:Ñ^L|ÆÚË 2”¹%:8)B&á‹¶¢ó Ì}!¡¶Œçl^¿ÞVðwâ,lj+ XsV«ÌO6ÙѪ!‡^v§v¹ù><  BYi¤¾W<ÄE¡í)œíµºo¶Á_˜»Í¦k9¦°D…úU.zqÁ#žµµÆÜ½6 Wæ^¼ó‹N¾7ºÛ7÷÷c§<Ù­2:íòñvD:�ðy9±‘3n½yiJ$Skv¶ ªf:Ú8 èâ8“ß µ’r^Jè‹f^Ä“E>\ÑŸ2¿g}/XcV­�y0¹B=EÏE*ïI’Iù¶YE§’X&í»êëÓ2ê{CUÌ…Â…º![^Š5Î(éjOí�Ö =C±Æ0¶÷ n2¯Y³âz˜„Ù¬@(ëV‰Évª¹¾’ãw@ÚTûÈc]l˜ñ=Ø:ÍâÖGQèóò q'¦ î1 nBçìWêŠêœvo$‹-ÀU¾÷<Ípúê…8*`Œ.ß —Í©GDÛ(^¡ Üp¤å ¦+^rPùÐí1¥t¤ˆÆê€'e“‘x0éDˆ‹E½„K'bz¤ >îöEƒßáÜéÂÝɲ†"?í ³GLüT•´×J-_Õ²Ã2I ºQæZ¯ÄDHcðÜ®b$?‚ä Dñ)•ò‡!eó6ïuK¼AœVÛõ†ëäËÕ˜8Ö´5@×|o.sa|öœ2Å ²Ê`®_èöÍ{'zª!VNIƒÛ ªgôÄÓ„-C±”4ßXæ<hò´÷ž¹ÒúSžw¢T¸“¶öÄËÒ<š·äLI¢ ÷BQ“E®Bf8Kض Ó.fMg®ËËÚxC–\ʇÄ_ |ïög‹ýEŠn·m @­Â¨ù›.€H|Å×ãõWŽ–á^¬=¢gëj¨Gêö ú霎¬rFËêSy ]ýŽk9#@JÎâÊ4Ò‚)bóÒ×ñ.«xˆ ›áb7jÐFÆNgÕÛÓb7( *&¥æ `µ¨ôÌ[1×kö3ŒìÑy×#�Çgê °êtׇ/x_2$Ö?G3©b€]]‚ a‚ë¢v­º¾çP²{ïUû¬Ó[|Åœ–‹7[N÷öÞò@ÑÍʃ‚áöÉšÔ#’d$L‹Û±OÀ×1‡/ëÀ‘‚¯«Z²Ž òù˜ FFãë» Î-2LV71„Tè1”~σƮG;,±5gÒÙN<§×÷Li›åÎ+ì¢v:l1=W„*Vµ‡½úr`D/°T–¤à¥,{OÁT³ZU5.<3~˜mT\$1*€/ÉÀ·œdnZâ%Ÿl8“ÍZ+àsV€œëÅ#cp}>­bCÖeÆUyµ³ §"¯º²Ãˆ“`}zµèLyù`–…ÐÜSºÝûÍÓÃ’l:éÓ-[u÷ݨå¨öºñt¨Xi|µ•V+4/ê¢†Š¦ÞMûùÚ¤¿É¢—`¨„ÆŒéç)0e‘¤þT‘V[—ëÊzÈw_¦t?3»F¼TÎÈ&êIµ¥èBOÛˆ¥N°­_¤|ŠÕ¨2^Š?>@¢ØHÝ3¨Ö&Úm¬g·ã•²o§ù½yÍ2A¹·±¾$£@ýKòvîÍÍíÐìÏ7hžk ¬½»SµäÇñG(2^©"@ç�sHX¡¼ðÄÔ×LÊñ\Šû2¼=àÙÂ…ÕN: ¤º ?÷È &qeQå-±®ìWˆú"&:ûÒÀPWnD–‡¨a »¾à[ö)ŽmxÀÜy5 ÏpOÅ3]—Cƒ%ªjgSô¥ ;%²í¹°[J÷TË£jÊ­~¤²†5>¢ÇBØï §½A“ë>ɬ=2õY_¾&¼ƒGNÁˆS¤êÀåUÊyÞMﻓÀ°ô÷†²®¼ÕÓ" ³}Ú¯ôÞee°pÎlO^¾ylÉ\0O9Â2VÁ«ïÞ�ã‹�©¨ñÛ†X ÓÍ ³’YßÏ^#LìÒÐ6†Ö{êaþö^V¿©ÞΨ{o}v#1o6Ó0é–)_A+˜cGÒˆ!“y·u=Ž|¥k$X¡ËK—­ ÅMžëX"ˆêCž=€Ã Ψ¥†<~Nì’Ø:òØÏ¦93Ÿ¯Ý‹¬G jîyåùo’Š«SÒ Tå¯~|¡Ïd@ïB†À‡³Û,Pß+"ʾy›¤ç%Í.a‰wf päme+$kcE®É6}'æ´Œ;ØçêÙ32•Nð~ô6v˜ðÑ/TÃðuûÛÝû‹O¾~É·«½§Þ&šhÕsZôÄÁ9ÞµùZàJdl¤Ú(‰fjL‰' ÂE<Í]ª®S =~qÏê"¯Ð`˜S|ªÏpï{W‰çÎÌÌÛ÷˜°pH[pS»_ç\Œµà -?¡ºèhÉd±æX§«§K©<˜©a†{oÔä àA†¨<–Eôl2ízû© >‘"ûS“ÐuC`ÖiZ#H™1ÞùÑÃV°J»W3„\¼ (2íÔñ¦)=æ!?`¨……Òi[A—6z¬ÜI·0ï£1ù{"·o°w}JAßÌ(X¡jåss &æMß6{)ä�/¹L7jß{6ÚIÐâ\T¥š×ƒÌŒ¶oâ¿C—!Ê€Í$ÑvôÊS™,ÓÓ”èÈLAŽ“õyB£Gû,µÈË%0{c]|¶¤‰ï˜€ë™ÐDïÌQ8‡…³Er Œõòu ž;’ñ“T< -tÄ4zk®S8 xAx ¦ýäÑehìáyÄ[H¾ÒF“°ñ©ç3–GûˆL°»“v9Ž7E{-‚±5”D{€³\©ÒÚªÅ3ᥦ#öGaÜbƒfèfxRöÆ‘‚Ø ÞA.<¤GBwwaV³ny>?¢'Õ÷Ê-kwÒÒh‹“¶T6¹·Úº³î™[Emø"/'ÙÓ'§±o¹RÄ“i°NckžDyÈ#ÈV”¿Xáä# v$!ý +¥¬t]}¯;³H@óâå×ò,°¬jZ‘YóôkêX Ï‘Óq'¥ùüzÝiÆ_‘ˆ\Z!�Ú3NÛl©2'n ›}\Û¼Y}&X72 ‰“¶1ü^eGdN˜“X 9ÑKTRÞ«ÙÂg`ìk“Í%J"¬þKg¼þ<N'’¼ä%Ê)^&’ú>ÏÜâWïzê à-Á³-¡öx8­p×8x½kªoвtº±‚Ø(Ýó¨çIÞŃܜÊ5A“×utáöžÏf:Ñ-¹¹»*Ø{ªÄÏK;Ok|,f‘oJçÁYø;1D43•±‘ŽR„Ë똵÷:¦Þ ö&Š®ÐsK˜Áõ—ƒ‘=mMu–zÀÁº:µý83=³¬%Ô³H…CÊk 3ƒn…ð°ñ•̨.ÌSWˆy€žÝW@—öjÒÀzBÇ.O¢øÕ¾=Ù²&2yÐá6Í"Ztâþ$©bMT;Í¥[ 4û½7HK“Ï2,ñ•†0€ó`J€ï¼Ê³—°Ø"©5ðôð1o«¡Ä«(™½Êª÷”yù…Ž.å\†`j’¾ÌI·(¾{ÎÙ‡$¼‹ÑWTë«B\KbkIj‘¦|<ôŒ0DDm™…æâd ÁoÓ¯N˜¨ê•K[‹*W Ï»§ÌïÅSë½Z…È(€&DtÀ~÷T*MÈ Êt?`1úÞû¨f1ºìDé3ùó)ts›A¶»k•šŸ¶æ» £À~?Ïšzfû€øU³@$õeãÕnAuµ5…q¡zÞ£ÀÙÅ<pÒx2iÑRg}/ ñ[S2ëƒé&ØPÞWKœ¦š´-ðŽ # _¸Ýø ó¼ÔƒÀÖóí²"дÄêõäÈ0‹ |T¹Bxͬg®XÖöÄQ˜=œG¢ Ÿï('Kó#Xˆ:–ÈpIÆâiî… QÇéx×<»¯˜Ÿ®epˆG?>-1&\6Å…9ãÃà§È-ê®óðt‹J%ä:)ŠÝÌŒ%JõùJOWHƒœ =X_²Yç Éyk¾ÊæãF˜î­h²ý.h$³‘«÷NÇG–c–ÕZܬkæé¥ä oŽ+y×ÚY ©Fîn µ‚ÞªòXúºØ–r°ê›Fܘ}/aºÞ–âÍ醕jEÅq¾h.1OŸÇ ƒœiø†ŠT§¤\r]»‹¢žWÕ븈&W´x×F%x„j¼öxXoa}KMÌ,;–KÌÓfyúJ²l¨Ñ³ Uw9—ÞǬVÒùŒ3Ž Æ{e’“ãñ­9¨cË0l÷ƒ;|´›³W“-N‚-añ §…Šn1_H›WM^¦DÙ>Oñ¼7¹!O÷Jôa(¿;&ê+yƒB›(•ÅO¼d+ŽÚ±6ÐâðEËî™â+=yárf4Û{ƒµä°vñæDÅlÍ»p)o˜¨€°•@'8Ot+øœ‚Ú[NG‰bZÝlâPÚKÝEpWd|Ù€v Ro8µÇ×ûH|eX»oAÇtºÑ;Ü¸ç• ¿°·µï©å<_Áƒd­ aKu@OÇ8š�#ÞŒ“kÁcf€gbäWzÂø(43ª\™½-ï²¾vxb~yBà4\åy ú�/ƒ,ƒ¯”ÒÞÒÆíS[sz‚è"¨Ž™j¼0Ÿ>“EOtœº { D`•ýJ¥¡5€×1$_« ¾¾amt—p#}ëÔ+Ê.&QwEÊvL $GÅþšLà Š , ïÄ “é™Ô³bæGìîŠ7Ò,"8²Ø>GPÝü¬lùŠÎDO€¼xyÙøØ²(,±k³­Y¸¹ UË¥n…î´9@Zdü5J¿Œ4S¨É¸æ ØæÌºèzªî¯Ö𙽗Èfa8l¤ž3Æ í„P˜qYé| §Tˆñº3ûÝ/ÞЋ<ã âÍZýÄY,&7^¿~ôººý…Û^QÖ c[ƒ+q¦ú\ôZ´¸âQxÇÔ›O£M9/mÖŒ6 3®�¹X­“.€ÜÎ̵ްuLÞ»Ýu(êå Ê-¸óõ†`öÉ1=¹°­Âc—2ç uHU yTºO¸<îQy ëûÄÅ?qÉÝ‘ž»ñ˜íe‘ÿx¸'$äQï]½F‹¾mz´ˉSejѤÞå¹-ØÅEÒÍÐ<Ê& Äè„,ëh5b7»k7Y1ÕäZ~&VM‘iÅþŒcáÜÅ©/ºß°•'død[¼Gz-[*ïÀn?®Ëz‚~Ç^⤄MÕVeÙž—é£0÷Œ®3O/í&ö– ¯çu…¦AºñÓ 犷g\„QwoyoP€=ÕÆÆ•³àh{=‹šÄÍèYîç!H`Èqnï̇,Þ2Ý«·ñ€±ÜEÊ»O)é4©|{yÚ€û4hT›Ç°Á5Çóz#%3ƒo>–"Ô8XæÀ·o.ñp…óFú{¯TÙU"5iã¹Ó5Ÿç=¾A¤7þð𘯇â Xï\p€eåœí³�¬�Ö‘¸ï+YbG™ q–½¡k=4õSÁÆ-„ y|é3ó¬AΖ÷b“ž–¢œSÝ€­Þ¶Ò\ÏðIxÍÕë*¸~$±:B¹(Z§[HÖ~ÀRÓ…4åÜ´Ëæ�½O³.œè᭱Σk XRÎLåGkÕZÇÇyŒë´$ÚoFgvЏž‚JÏœy5f‹ž?xãV³+vn{WªýfŸÑ‘Ë­= u®!0*¨2ï·k˜, ]ÖD[ ޽õzÊ£+ï ç¸f¤?`±%{íY^ï}ðúÅ‹Ôòë€#  å[ß¡yƒ}¨á¤òž:ëËØ=Z÷YC<®DÝgácmö {zµU6ŸsôtÆ€ó³Ú…8óza4p�Ù#,@øî=«H [¿ª™Nµî*;/ê,$ˆ–¼“XYXÌOuù,ahŠm„ˆ ƒ‡]Gß]ßöf{_MÙ¹9w!×óx×¶[–ïUÌl‡‚°s‡V™u.!*Q̘%`»"ð{ úì-.L(Ç„SF@A1[ÎÕ<°ÉÁÜi!GNÛ³Û(¸{®“P©µìŠ ?ÔEȰĠmz•y\†Hfù�ou·¸„Þ`•=6÷S™ÚÛ.6Euiõ7%Ú Gzh]^ÓµW$ó 'Õ‘·$˜E>[-™63•°D» ×Ì@Lœ²óS4„îô–{.À)p€¸D‚1´ä€ß܆sñlÒ”B@cúÓ#m0r`o4¢ 1³C4€ª–Ԫæ×êVÅæˆ4 3)Ô¸£DDöœÎt'WpŠîÂ+ׇ$)åM¸€O†wDnÏ”mÎï/¹Œu„)Qï–ëͨ\¡ÓÞÑ«3c¥á;µ…z̵@Ýï*ütFNç&7±à¶gR¼‡FêQƒ˜¶/‹žÈèx/6<XN(Ž×W™/^Á4—ËÅ­„{³•öéÎ<.e®. L�J𮄧…Aö  “ÆJöˆ‰î9ö+Ö忇Ƈs¦’ ’ùÍ{š£R'ÇL:ô8— chêMÌe92à˜9SŠ?¤ógk³ø@ÃN¼­7òå ÁÛhCƒÁ\zÈÆÊ}®Á‚’%KêO+žìp¼ŠQ Š*(ÕÖl#Ïm<÷7Ûï <‡J‹Z OÍÄ£>qôî!oP§-æK8t„9ôë¨: 1Ø3]3âr¡ ^4„V`w»¢ýÜy$ Ôâ¬Ãú$Γ±@ÓYºgo¤k’ÔÝ%Éo—ý–·DÂÕìžg’ ¦t­ô{·°¾¾l¥Bð†£síÐ8&9ºš5ÊÝ ±Ç(N_xŸeÂ<D>Ñ3wˆ— î9™ aêd¹�5šÅmI(<Ùj®ÝôröÞ{I-ÏQHœ%Ý6˜Êá½­y9í’¬"§Ë'RrqáDùž÷U¦ÀˆÃ’…¼Ê|5õnŠˆtg(ýüDÛP 97õµ½»ËÖ7ý®õÊG ªÊ­â=º|6™ÉŒΕ¢æ˜K2x¼Àj)Å®ÔÐì{óªVo¦4bŸô#¾)!ìÙë}0€bëäð J8­1‹ Y1ÍñäI€¾7CYy‘<ÓX+‚XbÜ©+$›m©=Ö¤»óVT™²¼ˆ',M/+xg<°ÓÐ ÃU!‰C ’Uki±xú¦ù4 :äˤ/c^‹ö(Fk¤¾†-I%ùKºÍ{ÃRT®6tŸ «©M÷f<`Jq9ëa­ƒ•ž£~˜üZ3g šÕ_½[á¦d¦ôl¡hŒ‡7Ø»»§-‰C~vƒk.ÏÆ¼bzsäAA‰-ÙãGóÆdY°÷Z”g¦µ^Á$ͽ~/ÔÅ×£<™` ‹z®jù-F U«ÁÒɤ`b92ž]Â¥…<¿ˆyèlͪòÚÑ‘¤›£y=WZ÷Ì `À%ê9Áíh½Á|,ÒT£‹iC‚%^e˜NæñŽl#¸¸-† vÂöI PEà2P ò–âpãN<,ÒÑ·±!h—)Õþ’ž*Á•TldcϱÈÓ<ᵓ‰ê‡:ôZ¼¡ â‡å[ÄKaÎgXÒ åc'6ÄÖ_¿ÍCß8ÑXI‹y Æq‰9+¢‡† {醞ë#÷Fì½›ƒç~㢼ڤÖÊÏÎ|,‰x*çlu•e[C¨B3F¯˜±g”¡Ä´¨ƒª­å ±×Ô dÖl`†ÏdÚ¥4ÁŸ�ÜC2ßn$L”yüL•Fw×ßÔV’B£±6(Ók.ç[“4¡µƒÇEâ侫aAZQív®Aý&â±›f˜3ð²—Oü¥µÌT“Ì4´Õ^Mâ=ÐŽ=K:ÂE~[#{ný‘;p± , àK‚/e.‰Ü¸ºAÝ-Ö÷SãÀˆþrF 1šìÂ$66ùUW.JêH 3· µT^‹EAÅ6»tÛÓ„töªv×®L‹»PëU®WŒ`ŒY€ØÂL$êàÁ u¸>3±¯zo1 ßL¢wSÙ»YØzô.MÐgÉÁÛMR[kßBê+ ö“;f}¾ç†W ÇM;Œ:O ÔâÉÆ&fí-Jb¾‘ö\-j ì6£z<IˆÒ~ F qT†¾¤ÛCò|å@ýÄlÇ^RU·uÚ”ãPWîQ¶ß{…OÄÂÅ´ç KÅ´ÝTEû`#½]`°ÖG¾ïR{±x:î jžNÖËŠ5à~B-Ä—¼HWŠA1á³öÆÖÍ%=û„òD°W)'ž*t¼R×Dà>ö€Îh`r…E^A¿ÕIk¯­—ɺÆf‘X°x…!¢i¨OŠªêÞ=–§Gfz‰D ‚ïªð({Cý±Â™¹«e¥½'„0ŽVFPo<½Ù‰ß ù&%Wz„*<A nÈyá¾Ù²£Øxbšïu 7ÕÖ.ìÖŠ¸ùRñKÁõ} gm„boKó¢'·ÒË÷I¬–>ª¬¼}Bnöz†]±,‹äâ;*’ OÓn{1MÇyd�÷JúˆøáNœ½‘×yŒƒOºÕ¶Ï/B8;UÃî¼Ns£´Ö¸ÚìH§†äØW-ƒg Dh^×Èè§3þåŒP*xa÷Œ'³XŠí¬9¡é_Ò¸¥@l SÁIˆ*uǃà#=Ðt‹ áeç¶KUrEòœ/nßYeÉ,a×+ó§gOÑ1¼xÖjÝrOÓDèm )ù)ÛÓWǼÕóîq«ÁB¨Î[· ì%z ~’(´]×ÅÄt;K†üüÉAƒ>4^ÛÝ-…Ó’ôéÈܰíä౨7s3µó(8‹ûÕë|Œ›höÞ¾D©|\¬#áØ1Íb‰ôšQÈL¥ž¹Aï4ÔD—½¾”¡�{ÑhäÑ4ûÒ0+a.{_™Îö”š†=B3zb⶯éa4ʸZšž´ÕI'Ð#•aD߻Ъã¤ùÙY¾,ÓÞÒ,oÄîI-##$LÄ8µ±‘܇뺓ÅâÕ³ÀÔâûæ=õiv©É†|§eÜð¼|çélwlÛ((ðÅÃÌJGÉ”í¸´ÞÛ£†-øÍ„Ü% å%òÂD‡ä¡ajfÅÓƒbå,°}”y=<ñP”Î�:‘1ª“vøïb1SOá IãÓ¥uH»Ê ApeË;»‡ÃÍ [˜Y8˜ §VqŒ Ée:ÒÅÅ>„“nÞÎ³Ž DP^:‡l¼á÷.´0!|f Ë•Ÿœi]›Æë÷¼5OœÞeÔ^ŠÑÒa…ÓäM¯7àÃñDnt¯žŒz½dDæâ0|ÉuŠ +̦Þó%ÍÓ/iœƒ–ßLÒö …ÆÀ9ØîüùzQ ƒ:Àe¯æðI.¿�H¸|æf0™oQÕÃÝ8Ñ ³€uá@€®°âÌŽçÖŒ¨lpÞ‚‰ô,@¾f¨’ë«YÉ´eU\ëz6MË' SÉÆÏv·ãœ^öxÜÛÜ3µÜz1ÏÏ`RØî)åkô×ÕL�l»®õ¶‰–ŠŽ(ö”SÈ  Id^<}œ»ÊææÎOÛÄ—ðB{ìðÝš®p·ô¸t ¿ÕÅÄ|IèÏ"Âr/&•ß8 ]Õ¹¯äFà6+Ë=D¿=8Õ±ö]c!%ZÜØÃÔØ¶ ,U¢Ã*±CpЫ.ð” ƒwl¤ãýê24i‡\’õ*ž>;3ìX}%–¹ûäåIh³*t½xŽ€ �½ñ0¬[”0ò™yyœæ¼’‹Ú3í>,Z0M5Oã5Y_- v¿#,=-ëN ¯&&±ugÃÀ#ÔX.ÑñWÝä:ÇÝ’ªÖü”ï‹{gÞ|áo¸‚vÉKŠËkÂû¡å^ãŠÎˆ<>‰ImçzC(nC»Æp m—£”ú*<ÏØèY©Ÿy¾èJ–ÐsL¢÷Ôæ±ˆ©{=â’÷¤/SmÍÓ!¤ƒÆÀ’2M‘bv5*pФ¦!Ù%Å;°Ë÷iQûà8=’æ¬å„3åkÀŒƒ4~k‡`½Ïyšèå;f{–U‘=zÖcOöËæ/kLÔßt‰(2´ ¿*Ý€ð"LÂýK›£€°E˜í—œÄƺËk©ƒ¾ ‡]ÞX²âq¥,ÉË�ùn¨£yØW¬*Y³ ÷ªZŸI“ª ·ö)©ÓAkêh!.-ä&£¼7=í‚#_a؈ç“yåÔoòvJ,<3^ç¸î¬COº×R$@Zíyë*jQ:©Â;Áì{(ZÉÔE¤µoƒ(ÞÆÂUcÔœš¾·h%Áœ@Ò-¯�Éà˜… …lji ,R0šÚ¹W¯vß;QKÜ|ƒö,jp¦Ÿ¼¸z¢,¢é‹û S (ù\¦v ü¥’"ð yJ¢; ¿§Jˆä¶ÑSëEŠOÄòùé6 ¾ë™’™�‘ˆÖ ±{GëI&WîÁúš 1"ᄺ€^‰´ß{!’ŸÕT-p3•Q¨ªéc€Ž·;³@1Õ²ûC¸)Ò.Ü’ËÉóª•*!60_&ó%§± ¹SÙÝóŽF ªów•™h÷hvuHýŒõ½Ç—s­ ]²l†ˆá[˃±‹…à9½:àñ‹aW­|€¯#Ùî ä]jœØÁ¸®×­a*>áƒb`v+•µfYЫgï¦E‹öVë±FÍá÷œ{8ýAê´eà D²¤Å±½ªGƒ\µ.}%Z•ÙlöRï]\ÓÛ3·%ï]ßO7J7j as‡°v–/m„¾´]Þ[x²Š—yLnÅデÔ¶ò—7u¼»ò*·óÅ’;›CâX h¬eÀaV ÒžY›%ÃóNQ…¡ŠÚE|òtü¶mHù(Áèrêh^BjÀްy CMÀ«§&æÙÌI5­V´G!ZOê™áN¡Ç†_­_qÏ´·2æ´ Û&M-š¢fBvqža˜’ŠYJ–¤až½GvÚÌFõŽð*‰‰Q“Tk\_í“ð› „$•÷dÐÒJð$fëâ8²6ŸuÎ{åGð(ùF®õ˜¯Ž2– o´‘ÝçÜ*˜ú�/®íð9q[CdžŽ½8Þç¦õü ë¶:Ífêé{«PYkE»‰Ò*[�„}W´å Å!jµp¬OØ=IUa!¦ÓcOE2ô­¾Tì%›¤Gü�ý cGG^h#¯³æÌ=u6§%°@u‚[àV؈x ú`]@:üXm)‘èöáᨙÇy@mèX)…“÷$Ê»èÆ¨óÒC½xxh€<‘Í¥þfwî²úÞÓxg">YpªÑòš0y|Öªe§v³IR‡CîÑKƒ°™°]P�®P¤n—nÇ4™wt&èo¢w)^µF‚¶‡êãPz xlá­4bœ0šb)7Y�<3ÞoBs/»^Ô[^zÌVí·/¬Ø}<eR—Ã<w<,’®Ü[¶Ïµ;-Õøy…{ßkä4á4Þyoؼ7öÆ„äá—7 _Þ,)Æ õ[u_aÈMPc›8üKœÔ°{ê®ÞW#Ò¯›Áú]˜çC1^®H 0ÔUÀÖ]Èj&Ì”v/±¥xãy  Ò¨È`Ós]ƒFwk�¥0¶—äÑl"öÞ¥<y*Sà´»PŽÄLûÔª‡YðPèz„Õm–s ή®ëM6cìœ1 n;³á<YÞä·ê!˜ÙÓ0¾}r/œÁD¬ j‘Í’Õ»6ì6]6Ñ]‚“kJüíÅ µ”:™ñÚÚÂ/‘hôúžÅkC\šTqÚ—ÄÃŽ ÒÕ¸q¡'0IíuƒsÉkç¼76O J)é^-ÉkâaÇ|œåã…Êi^ ÒøX¸šsÝZ–˸µß¬VsqUÝ‹vKÎq~¼HrÒ×7ž¸¾LzƦÆj2:+kK*7º9¦T4;`k—ójŸ‡œ¥2HT½‡É¦þÞÜÓ “ÈѺ|A Ág&•ôRˆú]ZÁc7GÙŠZyXŒÇ¼¨ÕÒÐØ÷pû½U]qÏ™1X‹+ÒÝ%œ›cÈ×Âã‹=GÎ^LÏÏÊáyà6 ÒË Zyó6‰0lŽ¢JE87½†b›Kí]&$´²šÜ«é#÷Ý7áÐO—A=fd…äÏ™®iÛùeMâÞ„¼wâb6øôSÝï]E_1M@ìU8¸Ü^)‡§³up¼ZyÊÐuË"•/ªeFªûSÿg|Úoöjzc˜—»òÖœÙ*÷•ðSʿ̙4U�‚¡½ ‘~FÜçRX!ï‘ùÝÐ6ˆ•§›Nµ]DøÁEŠŽ>˜{õÎOòaúWð­§‹VÍ >Ë!¬”¾ðâ$`äºú…Jª¾{¯ö=ºXѺg.ÂÓq=›´f˜²D;«˜#lŠòBcpû$«¼*óôÑ[1(2¶mà~²6+›” ˜:·ïy(„3+ �ÌÌ›ÎêéìöÇÈ+ºKÍ|::}ì&»ÓÍ»cŠ¥´˜ï¹†î"Ù8‹>x|Xo(Bˆ¶<:ØfF®ÌÁ¨$hCF4Ý& Œó‹@{L/fžée ¦ ÂÁµô ®•Í¿!e®Áî ËÇO.Ùðy“ÍÄÀ©3Ä"Ô6  ¼BS·V=J�0*%–mP”ðI1¸§·~¿º¾õëz˜>ï6 = =wÖÈV_+¸”4†®SÕ¹Q€¶#3lÿ•"2$EmCÄ6 PÞG²¯õpŽœˆzÇ>(ÇŒ Īåh](ôF mÅ‹·»zŒ3è­ƒŽSÞz!G$¤ š†âR†¢±ný3o½¹ ``ê¢eÜ D[&åí!Š´£:Ê@÷”GÊbªÆŠ]¿G‹ c®Œ’@ sÈN¥þrV©`0ÙA€qËzún:0ëÉ›À°N~‚×DZ#ÆýJµ°•ÈÊúTÌæ�…€3Þ—9¦_æˆË-2¡f!ÐøC+èzÏÓ\G®ß_ꜻ% ‡K+g½…¨%$\{gYÃPǦ +OÊh®!qŽ`ú¹RÕ ¶ñ”iÂRUÃ#ò—)—Š’÷å¡l¢á£³¾y¾÷b¶.I)æ~̯qsŒ"9MùÔ töƒÂ'ïÁ ‰2—½['ÓV}$•âÞ†æóbs^û”Ô•¦Üƒ“�tlçÖro&LÎY¡Ò¹2<§-½:Wó a¦)§ ôØ|óÞ“öä[÷æ ,¤Èw…àÌŸkd·{eðË}Ù3—®oÇß %¥÷y¯÷Å(ÌÐxáiµ›E4—mUÙ0X‹®h­Ï ¡a>G(ªêß§/Áf”¨õ`{s^Q޲*„O¢u[µøCeͶW5 +¡¹Ó-æÀ¸åh;y1¬ûŒü�Þk…¨òC{Š{P’Ó�Ó…§OBTtŽ’±Cà©Õ I¥OQiYî¢â x Ð>© t_Ë@F™J4º�%å�©õ]ܘ”<yõ²ïŠ™Ÿ¡Ø4™ é£Ç@ Öf`0lÑí‘W‰Ž@qvqÐ1‡ÅµpP�„¾Ï¡Ë9²f,–ÔÄ|÷Yô+5N’|°Ä�u©©ÑeY¡ªhŽk} ©G$÷�A¥$Þk·—RûXéJ¸DHÈeÉP¶^›lØä‘U°¼º Š);ª~òÌVPÞ,ÝF^;[:¹ûk¬ÏôñÚ—:Î_ê$ÏÉT‰iØR£^RÌ^¶g=QEÒKøËšZ,½g~Ø¢™]r‘†‰´õ5˜Ž†¥‡•|it*3¹“œF´ƒ¬ãÕ›ÖÁ!¿¦«éÀ1³WSMZ´Â Ï=œI†· 5ŽÚ@ñ†5ØÁÌÃÚáE‹Icb[u'Dm²˜vdÌ“"à×–’³¸V:¬=Êæ(ÁˆÊÕãƒh+ÍTš’‚"ªÕ©˜AñÖ@v`v”i`òºOÁ_à«ùC ~°†fVVq/4* ˜S×yÜTa°úBÜ’dKâ¹ïÒ»zml³ŸÙºÊI™_¡ÖZ£9’‹•wi2[å5öœÅ;¥CáÄõú‰lëÃ=\4-y©åt“÷†ˆ]ðÚªá´ü¥È�?ºz,jÉ^+?(Œ†�©á(ôW²”ñóÃgɉy¯‰¹¥éh«yJ¾ë=Ì%éÝ~>®:Æ6J]QrÞõ¼€ 1èŽùn±ž” ø†<æ…¨1 îlU#êØ§r¯¡¬Øo!‰â-›¯¶¯–u¼cÔgUpƒrÓÄ«ÌOB.³µÓúìYàÜ„®§‡pAn< |&å—:¶“„bž‚¹°¥1a³–×x|ia—:ˆ#Mª/½ T…õ™�Ç”$=z¯Îß<mK”yëj” ŠXÁu%”ž¶ú^p>ÄŒ„€6JM Dݪäʾµc-ÑGÖGbùZô•+Ç{å×OòsÚ útg» È$Îø½Ñë }m Š=þJêÝ¥¾Ö¿ä‘`’[)’Ø[`z$üZeK²š§ôbá5:ùº™ƒT¬m£èxc ì’-_ÆCTŒæ89¯mèÕ¦:¶1 n f�˜=Ñy-”d5«ÇR«9Mp«3PÍõF—ßlóî{IÜJL˜åÆP‰‹¯F™mi´{'»4(™ÕÛÃÏQæÜËó-Cõ(‘Ù8‹*SRœ+ÙVÊsÈxñ(Ì€pn”‘Ëá|L¦$ùâ”vhoýáVm*@u Õ[ºIr{'ì�ÒD¢¦•’cöXÞ[?.i£(¦ëì¾Mm+™Íñ”ÄA:úØtëuÀ#¹w×ìʧQb‹„È Û'='mNuœAŒV¸ÌÍÌãeÈ».(\9ÊJMPú°Ô!sºsÞ½Ò7‚K3H8ËÐX.T£é4èžò1$J[Ï5ë´Çí]Ã{4ƒ¹'Ú*9Þª7O ñ =*®È~3)´Ï o…í5[›Õ9Ïì=Gàq±Ÿy§e¹Zdàjá©ã§ÊíØ+ Ïù¹Y.·è!ßòI·_<0êµØ—¯–!&€Ü±ìMÔÌË„öt?Ä ßŠWdx'GÌ¢…“Þ–~Ïì^´Ã{"‡c0"fÒv•¡Ýá ɶ{¼BŽxy"À¼­±ÌÄnU6„¯Ž¼›‘»Fš¶r]iž#%pÎ͇<ð)OÞt¿yà ¡"žO¡›¬}\é ÖÞ”¬{¦È_ö°+R½äg ÄuÁW­…´Àqt* Ý›cwFìn0ó”ô嬽â¦È4[ijȆ`MŒô‘)öÈ6 `ÑÈ¥C¯lò$7ŠØÓΨÇd Y¹’O’Ví\Ö…çDZêÖ2x#oRA¾†»9ŠñŠÛ4¶rÑ9•ÀzݦóŽ«Í öùõ)¼cé(Œ²ñ¤Ž¡¶…ØVÂúzŸk²xÍp¥�ØÀ«vª{Åé=<•–.qýr…Ÿ=m}¯^a…·i䘨õ;ÐZ.Ê!T~µ 0‹ÛqÖiöÞöTïkñbAŒ•“xÓÓÒ!5`àÔ'‰™ˆò`Ðâµ]¿‚KœûŠ6¼˜Üåµ'VjnY9?~u—§Ájc»½lGSm×G{KHøØ©”ñ¹x °˜ñ7ßCa—ågɉG·ÕÁ îäo‚: L:LßÃÁMjÚt·$˜“X¾6Ëx…n¨S[áj„¢.:‰ŠÛy÷ðé”"™.SÁ�©ÓQ`[pv†ÖÉäyNZ/Ç-ªµÔÃ(˜à©âî[w¬:&•Ö2ä‡%Ó§È cô*Áµè`”­c®=”fÌ€EéõÄ–4æs*§„ˆQ¼–K-ÚHò XWÒùØàäQå¦w…/<>ËÒ§"«!´›Æûfjp3¦3ä=tþ´Ç¿ì±jgW;½Ø¸é·¬ûR¨ÍvØÅvIaþ©™�ÉââBb»ÊR‰•¿µ;�š#›…TÊF3=^œš¢ мÕ_!(¼GF°")u9 mÕ¶È*B8LÕ–‡ˆ§_*¤B:ÆÎ‘BnÊ ¿(å€OØV œm/ŽE_<ÄçXÌ9Nh�pð"#Þ»ªˆ,Õá‘E°éŒÝ. „%Ý{Šî&H£¬]9Æ1[àt–†K»ÏòÌÊ¡(Mß,ØÅzIÂF4Êt¼ y5ÇÒyœŽFy“2ZlUø1¸DÔå.‡>‘Ñ}&J™ý"’ñÝyÐÅ4Ø*ñLea]ÂÑ`fø63UaÕ™B€ñ*î ÉSs”Þ÷Jhv*²—çVe8R{•ˆLkfgê̲qX¹ËOtVëã�¿†¦lTêÊ,éz‚Ï»æûä¡o nGsÈ" [ç :Ä3W†€w«YM‘ƒÆèv02Z¹s%ùB\i^hUkŒcªÙÊ8® ]ìÜPJ{ (nwÕ:qyùd»±Ô|`@à, Æû¸tóõ+Õ×cv­�Ü$öÈIôH d“qÏ’éu›Ø:ÖX5ƒ‡ûd±¬>*Õ˜Îaq™>}ìí-CÓ*˜œz/E¦V.Wb–*Žä<`ƽ2[¢‘7ÁÂ1¸”Q™ŠIZÍF¼d5àG…[GÎ<6%ý}N>¨_ú\¶Ð“ŒØf'‹´d‰ ¿ À@O6Çl¯Dœß_þ<¸Á—J‰ä#ív®/c×çZeeñšCRMvœäuÎòY ËÄ>n¿ž7’g ùÒ´È05åŰÚÅm’ÎAWøtC(P Œ…n<Ø\e¶ÚYNS!ä+ñ¬ádϪ瓒Ýù8ºê¦Èò¢¼vK‡Ž·ÔTÑa]…€«Õe/ú<½„(ñ®\¼üY+?b˜n?y.¡;•@NζiÄ%CÒ«ÜóæÞà # ´ë…Ý ˜_†5V›± îºcïµ^M¦²Î€]ï ÏPxÕD/“(Ô4ߌ 5hëÑñ<vá3ZæMäØA£:êðy/OÜÍË—Ô{™×‰õ)ä0‚é5oÔıBŸäo‚ï£]ÊãÂ-w|qôf&íjC’¡Eý…û`:_]‡à<Å—¥wÎóŒ29a‹Jýå`Ö¹I [¬ÙŠÜ#¨ñ:¤Eã3”B¿ãõN££¥ÈÀ‹4îá™»Œ¢ÁfoÅ(Tì‘“"œÇmõ´E[^¿Í—ý€ÃÆØž$^QH¾È}>nÇ‚çÚ¬Ô5q°V YÞ½Né¨j9ó±f=¹Z,æ~ª(‘çv5­$\ª¤ú¹+ øKq·W¾3Kö�ŠÑì¸0 öHÄá0Šn|Ž5èRØÐO¤Æl牅[Â{;¾þ,edž²+’ o!ðƒ/ˆ¿üó¢ñë›õ¾k´î+D3ˆ’7¤¬”ï땵E¹ìŸï¯!–7€%õ®®šWφŽ<÷f훉ú½Éè$Ñ~$$ Óq‘œMð²(ŸSä# Õãy.C(åüF¹„êu“â>7%öân >›Ö~zedÁn2þäM°ðóºƒgölß¾w¥"ѧ²†®ÌȘ¸âEd‚`zœ‰|T0~ÇfTÇ'¢¤.éí‹‘ÚŒÒáŒÚ]O-¿Å¾·ù–DÛS3¤¥â=ÍöÊÓyÒfZ"úD_·D€ff_X®áê ¦YWƆBõÒ¼F\KÍ¡gn|úP'œ¬Gz6³^Ëæ’ç[yÊJê"b„çê§ð� §¢ÛÇo&‚c"œìUï e8qI0ùüá p%>nš7„~à *t'OÏë½m÷î·1åÉ‚oËÝ¡BŽÂM›-ýü x¸EQ<éÒÎbKßBÎKgçG¡ ß¿õá`êÉG%«s¤CqLÕ~k­ü&–3îE&¢µ5ä­" 晼~þyVG§/ÍW˜n¨cŽãM*xÏæ¨ÆB.g©1÷¥:¸3Á%qò+]j4ÐD˜bõñ´ÒEïUoÞ<슱à¼`1 jŠˆiô÷LætJ-I-:I=d²½D®¥€4~ïuÍy ’ƒËKæâÕ©Gu”¡š¾™ HÇÛ‡÷žÛ½} 1/\–êl†^ø£Ž«/Þ÷WçÐ×o=äNjÙ‰@ÐÇ‘‘ÎM.„pI×e³øïÍë˜ÕªrŸ›„ñPßä’-ÀåÎö{-]þbkA¶ùyBÑ#ì÷r”*•W¡ÂÉøI{PU²‚ƳÄå 0'é³=°†ì 9vE±„V^xðæPôÞSF€µÐx÷Ö‚%´7"§òhßpqNÊð«°'³\ÄB°íÀØÙ›ž­1çôÚj#×i„ª‹‚“_š`ž.T¼¨‹ƒ_’&x)9Úulá‹Ðge{iï1»8˜çŽÞÆK=¢ÅE® uë~]Ò|chÀøšƒce@g†ù6 ›·6—ñ¥Ufá UDå3-ŠlðǘìÍL4T•6nk¶r(²´‰˜ûÜ–©v‰ÎE«xYµ*8ø¹ÉÆ>¯·&ü†:àQ±0*^ô®CAÚÅqÀ #:$dÚ$j6ðV*ñúöäž'.Å-?O{R 4¼Ó€Ð@Ç¥$™çàAp¬#)áËôD­+„yÒ’O£\»êxw}N#ê=”,©(rÛpÒJöŠûÑuâ ëÐ;žð™|yom³8Ôźâ$`­°|SÊZ¦ÊnÌ<ùJ j©Ëža§DäyÀ“Ðu8%h£ gg#H’6üLjÐd¯Oêák/¨v¡²ªÆQÑ›Š> ô3´Ö¥L¸)VyÐdˆLúÐneQÞÍ$Îè;ä&ÙÇ/ädfêe‡ê—A ŸSÐKtu/„nØ99éìà†þü5ƒAkóQ„kD6õ_ Õ›æÇ•Cæû#\ç*µŽí꙲dëjÙòÜX,+Èî£ ÙAW×%z°DÏ€ï�P6¯h76 +Ѫeœ«‰’FG`hŽÁéöhU“ÝÊNÖôaób>ãúenL75[¸Zzü uÞS™t€àcE0è»|œ®sRnÝd6Ú®­@t}_f/ÖÚ>m÷ËDLº Ì F‹ØæÙÐCµepo'ªÊnÖ¹|dsFõ0ãìæš<J׋…í‚w³eŒÒ?Lu¯ÓŽçµ™îêÕj�º]·vy\±¤ú)ªìSw™aPÃÝgDþ$°: ©8…‰œ _ínUò"YØœÄ-›r$Y¢NÆ1.”V(‘Â\Ò‰F†Õ±1Hò6§²>uØðº­_'Ý‹§z½'=–ÙêÙ½r0›æ ÀËÃ*¿èí×hJ“kþNPŸ‰ã>n¦êG¾x$†)b´&»ï$áD¢0ðÞv5Þ5¼¨ySp`™³£wOÆÇù2†ÉŠÐŒwÓ7#ÓToOË=PHe:Éßf!ˆ–V'Ä…º%÷}@±’ùB:îí |ÃET9IINwþ:ômØá™ðË *9Æ{¿«„—ƒ/¨vÅHå&Ï$Ì:6¼©wfì¬…Š‘(y:„m.â®hÐ΋ ¸Äo…üK!ç+Á«§-Ù]2@t~ä“…@†éÜõ£©í~þ¤(þtè,ùî´­äy¼ºÊ ž»{h AæýR‚Ëçj*oÀwéÙu“Ñva›cùlÛW¸w§J…-Žð¤J¢éÈf`{‹¸³Þò¨1ošÉ\@Ô‚!Õï±N“…¸ Y˜²âhùÅ@Ã-r!<#Ø>ãz]šõ dM9Ï£\Ï]£ðæP°åy3}ß;Zñ´1}Á …m¡L}ÔÌ:Á”ïØÓ{Œ^‡<2M§èƵ²ðÚÎ÷Ö ®¡†™ˆ;Ë£ò=^¡Ñà—¸mÔùª¤Fqš;w1‘äí=DäÇÆ–飳·¢ûäVmdMÑGs|o^Ž´?¸3±àËMy7ÉÛgö`× $3¦"rg©…$PC9wÐÎʃ HsQGMÜ3ø­ ¾:¶C9L?ÐÉ®ŒÁ8Y(Á3@­Ž!PΆ޹«èvôÚã–5Fš(—Âd½_‘òð{\+A”:;wRanjô^¶x´”Ù#M)ò×…s„V37W‡´|[É´ô]M®Hciä%“ëe€º4¯Ú¾T¨…10ê—ãµqœÏãªòû@÷.DAÒ£_«ze–©X½Ò²@&B65{Ú¥huÈŽ½ÏÔWÒó=ç0ßL?ÑÔ£5ŠÑöv0Š ˆÍÕV\XÍ “ÈVHÅ*énæ„€äË!Ñ/‡â躭f!`´ÜzlÃÐ7µ‹ѯid6.leJ³q£þ|—m2tª*¥Å¼ä7EÎ"O üüx,pYö¡Ø.`àÈÄ6°Õa‹ÊYÉÛGùZžokŽ31èD’u‹æV3SqùUɤ´I,ÖB ±V(<â·zù ÞXϱL 4%ÜŒr£"6Z+Em¸P7ƒç-!]?x¡ÇD .i¤ÎÀ KÁW ½q4²”±|¸ï²\áwizòl±}¼šÂ¡"^×@úNÕ–JiŠõö^ë³ZÊ1ÙW¾M5…bä~¦ï 0€ÕµÑ5ƒ‰Ñ†Ð#™CÓ³”‚-8ÐÌ®Ìc.Ù*^p€êu‡ºs3ÎlN”“Ü4àPÓ°†›Õ¤™‡yû°»/Æ¥XÉhïŒCl™Aóc61pг¦-xpžC…ž˜:Kªì" Cäg@!ZdÀº£oS«\ßYXÏ"bFêqÔ´mÁC<¯³‘Ç58…bŽô¤‰#‰·ý‘¤©œ4¬œd·®Î™ØÍZÌZŽ7? ”rRäIg€ã• §¾`Å’-BPF¡i«{"!e‰Ê€t˜{¼£ÛGÔq½€èîKQÞ(Ž)¶±¹u¸ã*3Ï£ŽÂèm¾·¶0l>ûX/�<*wdp€Eß)ïË7²Dîc8ùæ\&@;ò:Œ:õ!³S¥R‹X¯õz¸î—DÊ_Íúa½Ëä2`ØaÑׯ|%œä¡ùº-Ì™,ßÑÑìŒ$Ôë_±GÒ$<ל87tï=®¦"B×3.űÏÙðmÂ�€W2y{‹.Hö»‘÷¶#»™¦2ßN°ñƒSk*‡H÷TeoªFÍçùfø4¦ Þˆ¿(ßËÁã.€`Äò‹ fʶ°Yt²‚ÒJ.Ü80¿á7!ò^DE ­‰ZO/'™²9Á8û;Ô§€ÀiÙ~O‚{Ìõ3vЈùUgs,×£å ”|]cÙè·¸\Q÷ä®_2àæ3ߪÂ.mÞˆÖ‚‡­­á8!L´y²Æ „~ /Ki„—<QïB{atL™ÀY§ûB:2û²^²+_¼’y®‘69)Uçƈ¡ŠªEÇ'´n¨C›-o4ã”ÏDøöPYÔdvv¤ù!Jðc[³3²ì‘|ØçáÍ÷tª@mdùyéeŒ—ÁV°‘3²JˆY—ôußFÆö#ÇaŠ;÷æ¬j«M*„R\!t•î¦`ƒiT|ÄWü ¨´c¯Cк§¡À‰3D�Ǹ˜EA•‘¶´-¡X£;kž¸°öáܳÙTÛ¬Ùcœæ–}®FáñÜJmWm4Ò;k ü é{Õ)iÚ´:â7I*&ªƒ’jîqþ0Ð_x …î8`BÉÁµçÞŒˆÅË)—ôÑM”¾*M'”·«ÑMÔõ¼zaíí¯@BÁzàÃ_}Y¤t(¼ý‚ªMl€¥-¼½Ü`AEØ1mhâJ|âåN«iIþ9‰yѼB.Œ~Óû s©šn¬×G_Ï#_K1Øœ½w¡Ä¥B‚AøhHVž¾•‡D#$@ç Óo Pã.ö¨¼6ö s÷ØWôtK£p3ñ¦Á+/ݼÒ&�c)ðKR®}SOûÉVÎ_ÄJ�>ô‹ƒFï½ À®yøˆÇ­W¤² g0e½¥V¾ô0ûÍZÕºDÏKž�„( ‘«5ÉçÇÒ\ÎØ¶¸ŽhKc*ì4“‡e¶òÎ\_£Ýb—ÍÝ{6ÉzvR0µçøŠaFí¥üb»[ÔeAâDVà•Ô±i$â-º½MͶ ¦»ÑayÇZð†G6“|ñ¹ï«ÞâQ{Fo@aïÅTÅí±ñ©ÉtË»›¨ ÓÞïQ¾;¥5ÈvÂ…ÀG)1Ý| YÕnþ4಼Æ4^‚®Ÿ·¥Ž‡\Ù|ŽÑníZÌLè2ëÅÝæœ0Æ”üâìåÚ: åiXn`„ÛÀè±”w.'DÏó OT°…¾ê£xµý†äMeùÍ‹dÏÇpž7&&uÇ*µ~ØØÖ¥=v2=EÉóhÒ×51R9¸ú½Éa¤Õ™YÇ·ï=Ôæ~< M«‹Š—Û‡w  c^–û棳%³:ÂL{oŒ^°½—/ñÆ”ës±E}ïà²×«üñ³é~à˧8n)|ç zþ¥‘×FEÓ·q‡±Tôzm’’ lÞʶµ"Rzåv¨Iºë3_䕺ÊáýË£¬gdï^[ÚK•CÍí*XxCæœ—í¯ž«G.G1b—^§Œ>ÝJoQè†çÅ6éÆLQk-A(%~Áˆ°ÇûüÜǧ°Ùß¼M6òãW$¼ÐU­Ú—$©tuòtkßøÚ Ŷ¼÷’œÞ,S #wD_+®·©9¹±j²Š7"·PYÊk¡|çUO€ýñ+Œ–¸D¼>sÓ84¤Õó+©‡ h󖮣³ í€jd=_˜7æiXPDÈÏ×1¸¹Ûº+Ý€,ÀûèöÞ¨èCÆ©Šòð-#yÅ ¶‘¤Iv2Ç^ut»T †¹‚åݱK!99(ö–pÏ4Zû,?ZW`i (zíÌ­UÀ(X›,ÖžèÓ|¡ñTrñHàQ.qSB”ÆÖ¼=Öu7ÌœWâTÍ¥Á52lééÐé“[©â¼2R<Z¢†íôVÏ|¼ÔR…žÖ©É’'ZÓyg— ªEà9¾Á”5×-·FXR×G §'[è°É>«ùL b©ñÌ,€Áê<{óvÞd©zº#LšDß!ï«A«§±i8k¯Ö¶^ ʲ°0ך£ùãÅUs­½ÁÍö-pñ˜'ô¬äÞÔQÔ€h™5U¸“æ¾°íœNÏd!–#CŸ8Ö¸Ç9¾gFÙ­�u²›ñé‘yÄv¢aÙÞ¢ÁÕì±¥âË'JÀØú^ž««¤˜.?Ù¡&úS¤öžÙ�ˆwç0mÎZ¹}Ü6znjð2™kAà±ÔÙÐÅÝ»x½øhŸomfi`eÇyðëz/sÍÝ6ÌßB"n% ¾HE™óTÚå¬X±êųKŒ~õN3ÝKØj$–èY 2² ½\ŸÝÒSÐÎCaé8fçy •‚lûç©{¾ñ²&ŸqΔ…ÈlÈ{lAcÎM 5:3ž,åÎ#åĆ~õJ¼J.*RW¶WÐõbš´C()¼L›Ÿ…×u9¿í#ÈÄD¬Öy1×ôö,=Ó7žj@»‚+½DˆBng8”Uƒiî÷öÕ8š3¹õ» ¿ëYÍ=™”x¾û½wì9ª·‹­Yßшsë U™W·)á.ZÂ’ŸÑõ>æ—®åhÀѼ+¾¼ƒ¶ï)Ø‹ÕÂz ô¬U=•ÄW­/Jê)bf‰YŒ’SN—qˆ— Kƒ:Æšo�·ˆÕ6?4à»}ÇðW9­›E ±¤Ã±µÃ5®ÓLg²–ˆÁ78Ö•ÅT|ÁNñ¤VëZ½Býî˜ë†ÌkÑ!A’áVåH'À†@±ÜaÞ‹ ]C#’,h³…4àq©Õº«Kð*ZMš"«ŒÕnµ(g©^]˜Îs!<ås.Ið0ì 47ÙÞ¼¾¬ËÓnö"sO`0ù‰®¯,Ž>ÇÀGIa–/‘B¿D¤Ô¡ UÛ.ºe׺ R…—&ì|ÇÍGÛIy°Ó3ü^´íò ÿic¿<âWkâQ š)akâC¼,'”´˜Õò¤ l¯«c¼TRÔ:A&Y€Å›îF¼Ó;_*Z–Îa$÷s¦àL4#ïŠ7:NÕød;èð¹Áôˆè3ac«èsx»+[S}Èõr,vŠ” òê­ŽÌrv¥.X=)èKî™Åî—Ð۶΀Éó|‘0ÞZר¾²¶‚r`%‚»¼uõ}ØïÖ«ls\qB»%ßΰTS+Íxò0ÇmT<?LRZë&©Ù ‡²büiÎP9v!3_ø»âp.]D2tߌ{à ãÂ'µb ürf|߃ª$àÀ Ä5 ½Jw´xà¶}Ò›a’îSzžé‰P)g4ô€¦0ëP®ûH‡Æ3�Î<᱉|f%K:à%: ™—Š[ô\݆_h‘GÜéÀÎPvíT76$WL²ù@•JL�ÄÄ;M>U:5z º˜°‹í#Øó¢òYpg¹fúÀk|}ÍxàÏÞ ™ŒÉµxÆCÆ÷V©‘„Õ¶Å)BÍEm-ÏeÒ_Þ[7#„5{$ÆDK‚Á‚´Â…®aýÊ B;}Äȇͻ2`^9ǃ:CμÞÀÞî)Rz­ïPNÀ9NìžÕn#ˆ£¾1ò–¨Y=!½÷p­$£ÙX <{Š=d·ß£[ t)ü2é™öú¨xú .ݨ1¸ ¤ŠÕaüñ{€$¦¶±”ÈñƯþœ” „bæ 6œµ¼¨Ë–|èdÝ4)VU&ï2[¿éµêÙt }Ê¥Rž¼–š$FZpîêáLâN]ž4h6Çék󧺲¬ ƒ:´X;0 WOËùÄió …0°Ï Nã£hÙ{Sm±øD*Št_¼&j§:ÜuyF}À)Á€ÞúhçªÈƒˆÐMŽ`ÚÞ{°Ó»°J]bC•ü.q=ÏrÅÒ¯Øw8: [Çc(�‰bk.+•ºÌšÃÓÇð”ì3 Çðkd/.Åö‹UX}óî*;ÅGU¡­Q$Üâ¸Ï•s}°}Ä‹±‹rŽ_¤iCÍ(]U“‚Ë1…d‚›(àuc¿ZyXBºŽè>ù¼`Îîx,›»¦Î§Þ±6ÀÐdŒ_>–8…6ÆÈÖÓ@¶‡O·w¬Ó¼-ɧˆ»S3õ¶rÔk5ÔB*ÓøœÜ”¿Z«ÃRÆ"j"5K®g{ Ý oŒžiÄu>–|HÏAíü [ 3ëeñ"EÍ Cœ' i¯[>ƪ~òú<ß–ÑJ[¦†R¡.Rã» W6ÃægfëüžGür3„ˆæ/†* ×åŽâvìuä‘¢½Š~åÙRxÍuÖnZ’gJÚ‰²{#,œ=ôÒ”ß:âSAÖ+ô˜é7¬mÔ6¸aËŒL$iZ"‰QD:’fWX2ü¥Ò—Jµ[=´ï<ƒ‡9";ìa®ªõ4ñ&ô¾ŠL®jH;‹}ñ˜Õ&¹þþƽNI&|Ë:ã]çZ<<ÈÅ„íY/—Ù”˜mã̃ OѤ3J[oX3Ò1ã.žpMÖfé%ž&óÀ2…™‡<¦Ï©n\EJŽbÝUe‚}|Dï­ç¸Ø“Ø Úwµïœ1Éü½Ñš;wÀ¨”Òp:f}¤nVož*™Zë¤^ ¹{mÒ‹"9,MbOíÉF3 Ó¿ %Þ¹´Ù]öhˆŸékµÔ^Ç-o¢­8C²„I8‚¹Œ“¶œº^>/±+Ó¬Gm5ìFÖǽ\óøú4mÆÔÌÀœœÁÍãÖö€p sÅ7„®ûž #01ÊÍ,ç=õ$°‘ ÁXä±”‡PUóÌÍqN‹I8äZ#)U™¯µ(²û2}kAøén,k^t VÉëÞðæÞ†j^pçÇ–Éšt„º£b¶¢HQ̸·ö°OvóžùIRˆëI* Be‘™‚^k¿½:b¡6–ó~ND‹LlSL— —:±Û;wÐÍX2ŒÄ—ñ.ãžÀÝkpA”ÇïÙl¯s½‘9p‰x5o¤M¤BVw¸ž^ï”z“õk‡çþ‚à¹yc¶Œ9å¹´G{uì‘q¡ÑÔ¡æF%öŒeØhQ5 èÔ�?TtD0%Ì§ÍØaîÓê"›²†f£Zàamu“;Îni±ÈÓ“_.|¹dY™HÛ”öØÔx™ráJ%|±Ug{|tsƒä’Gå^Ã_ f-ßyÉdÞ60pSrW}+’ z°ºâí WgzMƒ/KKŸ»ƒ{׎œ-áYU#¾YpyÁ©³ 1ƒ“K» 3ÁM¯ 8Ú hs—îŤÒDnH“6\‚KÃ!ù•¼…òZhl§ƒRã±8}é²hÎîBB#ÏäœeáH I!üÖŽH¥cÇnÅ­¶G ¼Œb›YÚzŸtH ·v¨ëñKÑ>J!“NM÷§‚g¾~]Žêë3~cöäÀàíb>(I|#§e½ù¸»óÕ¼§Eà“-n¾.uÈVP¼ãvöfݪóJw¢�-͉¡”y$VÇñ{¨Xi×ÁŽO-vCdž>&0õ޶}­ºÁÛ]Æ~‡Ç@[Û æ®t¸4×Þ£×ônWpnߨÔ3‹žu'®«ô,}·Çƣ췜~ÑàoVûüNM}ð„ïá3ã|c¢ŽA¸qÀàë[…€]–w¦‰÷ØîPèX&Š ·lÖº Ø–MŸÀ£w-ÝÒË2ªÙC‹Øf—“>}(wHï©LÇ=™ òçho«k2&Q.Ÿ B)¯UÊ wPdIô «a4-Úˆ‡‚\Ûh7)=ãÔ¾§[¼�/e¤pƒaÝB/ýÆÉ.åE€¾8|`¶Øû” c¦¯�o48 ½AúÚòm’1€ž 6=QBÇ+Ôз¶ß2ù—Lí>»djQ?)«+ûÈ_ðÝÃÅÎos ‡8•V£W§V©MeÙäj/·3àöÅL9J;:™¼­ÝG›êþ@§vÏUeô®µ%I·5¶½nÓ…=^C³»$M'çš¿³'À~÷°“Ûù@d¶°Ï´ŽerBP=BD2oÓ5‘¢ywp¸¯Meˆ }AOÍâ)³¼G@©Qê¯h»0rçM¡ø ë š~PÊéN"Œ•2ycç4Õ ïP´â#ýµá£„ñCi™œB¥DOÀ8ÞÂÅe…<0¥Ä€Žk uèP,ð¾§³¥–‘ltOÃoÊyú^ß9·n »gmi&[ŽÒt°¾Æ‡u7…d§ïüÎ}bs¶[  U¬Wx­Î*ò Ú›kU*á‰]¥ÊÛ¨×8#˜„Ü»ð.Ÿ]¦Œ¨ §–Š5ÖK´=¡S¦¶¢Þrº5¦•‹ŽJxu¨¦Y`ü¢»ïÎÆÊtÎyßD\&i°I—lÚɼúeN+T—¸„f›{Ë/9“•OqØÀ·ð̼óyNq£¤?7LTD˜¹fЩ>’bQć¡ð-’¸‹ú9X¬¨s±½©¹ w³»¥ð~ï={¤Ý”ƒ•»§æ5u7U¸Oœ¬—B— �œw3! ¯•m¯èá\T”äìèd=n“Õ®%ÐÙ}kÁ™Lp5þ¬ô4Pª¸ƒÞùá™F‡»Ç{f¯‡¸Ô½àÌ-©ŒsPÈ$G›û=í¹Âš È^ñÞ/›ž~Ù¸ünŸÀõ6 lG!È[-Ñ…ðÐ…™ 0¾Åç«ðœÈ ýq¯nNS•kþ¥ty®"Ç1N3Ük°Û›èDk~?ïcád§ÎcÓºaS;–=mÍl£ª÷S0¯ëÑE– ‚à1/¥£ñC×§f`±¨nõôL:BFÓ¼Ü268R4©¯ºQz¯3µ©Kð@Œ¤‘®ÒµæÁ«··Ùèç‚R×3…h4¢åÔ˜7œ#³Ä¦}`¯ìŠËfʯ¨¹Ò³ å±±‹Þ±õ¼BPP¤³åprGô ö|#›íp)‚‚Uð1mM%ª˜+=Pg^2+šŽi {!ytRXø®­-ïôÁºð”¾mA»y$8HPrÚhÓåpõ¢s^©`±–ãÑQÅ `™qäÌå÷8}÷¬/Y¤#¸ß>¬°kXšHLÈã©îê©{ñ^`KnǾâyí+çãkrúÀ|Õ5±fdõ‰·8XªÆy\ÀðV=,{¡ (42uª2äÕ¬ê¶XõpM XiÇÃóá>×Y‘çSr5XÎÉQý"ÔSc¤ÞREF)ŽšéÈã~ûSÃCKÊÇôx½K¹<†b_zéºE8щõkm{Q¯I_ùÛƒs‰Ò΃˜1³û´ÛÃtu«˜ ööñÓÇsÛæê9B[-‚#} dV(åŠ|9Âþž« šì½©Â'×ÏžZjç“5äŠð~"oä88à¥W$—}êÄü¥Ó{ôžA²—Ò.?a=´æ=ªó±íÁḀÊRàòM«+5„Â0•dY¾"ùïé).9'äµy` ˆËk7pvÛø²î:°­@ qšâ]Ãb7RfôŽ>®NÎ÷Ü`ÊNò¢…¼êë—o–ÝÃ¥í¡7=ŒŠ¥lªWPI‚×Þ‹hÚ)"6/õn]>ì¾È+£0|Ï-­÷®ôï• {‚ß o×SZÝn]R3ÖB& à|Óïá[†‡ô¼t ÑPµžñ¥ç:3äoÜ´B,÷›©Y±gàO•¹ŒÃØn-^â˜Óª†Tㄨõab¿~o÷AtqˆÖ5“è-Á]ox]OÎÃm™Ødn\1«.‹Pë’GÖÝhà[”ëë:B^?Þ!¯ ÷õˆ ŽƒökñY{¬StÄU%¦ ¨@Æ2WøÍ)0jp=8;b‡"ªxÙl×2KݳE–lM,’÷VøŠ „ºÄ‘1ÐdA QôŽ+GóÉœTgÂUú¨%:>8DKˆ»€rSH2E®+5•¨ƒéÁ{eƒˆò=¿X±§#“£ð=9†hD]±ŒR3&ÅdŒàDû©´´×�‹4zYÙ›KV¡Æƒ|ÏS ‡’ ù¹)¾A¬L1THÁw\Êh/íUÑôå­V*>½zŽ.†$ЧAâ¢òÆ™÷öbÚç½&c ÝÇþˆÛ<È|t¥HÍ›oܾ|úòI=H.”ÛÛ¸†¦€rÜYºžç óó¼‡×d¢÷ö¶µ•øV?¿¦Ô |šþ÷·'ôm_L|¡¯F a/²Ä£'¢ó;A6ÁñÆ@U¤±s0ƒ 8dE`æqŽŽ‰pS÷†™Öƒ:èBÁH·{Ò[UðÝ·<q”¶áJ‘«|pÔýçbíöh3°‡5q5Ghˆß›» Ÿ‘Xè¸GÉÉñ²{cµh‚5E'ùQò[–´@‰<z‡~Ò-R¯AUãaðA^½9©FH;Œ´šNd #Çᡵ‚àdPçxks ôå�X¯÷š.¥í�=á·ü6ú¶7XŸE{ÚS}ZÀ<7¥³•1o„³? ¤¤TòR®BØ”|‡ÏŦ|,¤gÓÞE… R“FÁÈ1ú’…Ô­éÆ‹óê8ÂgÈ8IÒ!Ge§}ã\/�3à1KY*’¼8>{:×8<‰é}év(ûx8ŸƒwßRGFBb… ¡j„î¬,r‰LŽP´gDUÜ’º÷Q‹¡4Çæ7lBÝÙ³ð“}Jz{dÝ­9 #©,s˜¶RЏ€vôBW]iú> í>(OñbFžuç$¼ @©@ò;k¶¹3£Õ—cÛÎVÁšª¥Ëó¦=}û•€±Ü™3>ôD©TŽR¥Ž¨°w¼Ö¤]¨ÀÃ`¹!½¡Æ kðBE¼“,k/ R޳= Ž¥\¼\¿„Røê$ç† ïî&ù®î(4ªÔídy/Ô ‰³Ì–O+pÙÔsV#“é«ÇIÙ·¡ý÷æîT^$"�éÞ[˜»d÷áeßá$$“‡äÍÌÝ*ðVnÅߨ]Ýpѳm¸ÌÀëâÉèß>ÐXçbcLn1ÑQŠp& á¡ùLæú¡èȉ.ùß«a‹§€ ¯:"êâ©Äè»W!9‡'‹Æ1'Ö!¹ÒêoúžmÜSšÂe1_߉Æîƒ|9ñV£œ.€³ŠØ£À7w¶f<ÔîÇœÍȹªá®Ïg`ªÞø¥¦¼Á3’D“>GÈ À¡˜~µ ˇ‘òÀ»ËBŽùhû)ëDœÄÐ4N¶Ì RY{T­wú)hž+Æf¼"óéiÚàÇ"‡æ;J—ƆñeLÛÏÌ."ã!ž³ûk§tªÅŒK´]ÁY‰Ì2AgG‰{õÞT;‚§ QÎóx<!ùRF|zÊ—Ÿ :DLÔK¹è,ô †‹Å¢©¨S/Š&'{µoËlÀ¦uÙ]½wÇ…“u‚ó9Xï5ÝhDö•Nƒͺ½žË\ƒuÁJdêò €^d7ñ> x«-¯MJ„ÜQJ)¨Í 6tbë ƒnÔÊËpHï7>)wDOÇ'+“.o)®H,'‚!ŽÑ—A\üj0c³4„YÃãzéÚ$âz.Ä£b&bcÔ‡Hº|Ÿ{мµ9õ o,{"%ûŽF »Ýò}õý}<A1iKEwÇ^14×{‰!¸úFŒŸs9ô–°àšhœ$l¢tØ.6ÙVþ¥T=$hA]KƒeçCé®Åf|‹\ig…÷Þ`ñeæp,aÈJéc)Œ¼ž­|Ù#9k �Õ<êìOlôÒ½/d%ºzÝtÔ1ÕKsyIf$‚‡CËZù ‰k³<öM-‡w‡Öଋq‘½ËølõÎ9°ñáäY>=ÚYÁ¾ÂnØÑ°-£¥¼zG³Å aÏGaôâ´[`Œ#ÓöHy©jtZœ^³dú¼|$âôöj¹³•æyòs/¼‡{ÓRóF‰ Aoá'ÃÞ;`DIN‡ º× ,m¡Öeytï¹ÅôŤ¬åœãƒÀ­'¶ 3V®~Kc(Ä9ÌK¥“sROáò4ŒÙGÆÊ4‹ÚP…_B,ɈÂKß\ñ àìK˜^½;À#!Õ³ªºzŒÌ¢Žö@e4qÃÇgÝc ŒŒ±à‰UØpŸ?z‡ðFŠŒ2ü…¤B†Ð3v:€™"à÷(؆ |¢\Ã.z…"çžD43,?9>xQOðª0¼î)ÌKtVÔr{kûñ¦,n %JmÕkËQrÚ%t‰‹>·ñƒ¬§”üb[ž0oq”ìP(é ¾÷N, =4õ‰] ”` ù3ô¡´¬ñ{æš6G%H`Ô‘XòXìÈZË%’ZC´î2-@GX[Í\K}çÞÆëVh õ/¥L¿”Bã—f$8ÄdÍ÷K飞×ï]”tÏ™ ¯‹ópÊÅÕØƒês6Ò§\Q’E‚U9uñÞÅÆ5?¦²êòâ­´Ê“¡F'."«JQr#5–Çü65J #`s^ŽLhg4Ô…Ý&Þss'6§%æ1c°}ëoä„,ñ¤n¼í¼ –O»9£ûñ†f“‰›ÓcfÁºé‚�Úʸv7 éAÀH_)xË¡ÉdJ7Ý•º-öFŒájØ„Äã ôp'”)¡5é‚0¼8Ô ÓδÑP²¯‚VXŸKhVŒÏ´ ¼˜M<žå!ZÝ¡0 ȱ7±ÕTX-òPª6`Û’.#-ˆ.%y¸Ö˜vŽQㄈaç{»yÇ{sâW …]ŠE«â÷ðVrAyJ©÷½h<~‘"7 'ÁúDìµ 0tIÕžÝóq»‡y´á%±q°jÕb#q‚¬úÑUên±¯™ FƒÝ2«[ÙkÆ ð)%¿\Œ 1˜=“ê»Ô€PÚx˜óhŸf ú·™]¤ŽËãÐ }þõ[+H9xPTŒáõ0z‘™yÍy¢`ªËó=‚;¢æãcGq—¶¹7p{ŠÈˆy+€?Æ÷š1W¥:—@㦱]_Ïà” L.÷ܳ¤‡¼/¦Rwl8ÜÊAl—¬Þir6¤19émNzKɉXMÒݲ¬õ#_à~=Š)ã'‹X/»TÕœÃsAœnaA»·[ßÝëY¯A‹O§œ¿œ¿¬Ä nž’CÓ˺; â=%Ëg=à}" ^•~¸x¬íPŒÂ7«yzm<z•8ââÏwß”¨•‡ ²’àÃrà0ò„T­ž¡"›gNžÇøäÍI^"ÌÅuw7"ÌäÃ|ò0öœ°-´¤Æðåò{ëIñHZû5¼Õ­²FØWû„MÔä,Ë06@•an»'çÌú±ÌXx¶-•íúëð îĨF|H�œ\jLÞô@±§�L©‘DåÛ¦˃!§&z¢irðÔ%ù|pãyuÓèÚîû ¾ÀHæ¼ÑWöv„ÃCºžŸ iX Á,"œ9ô±ÕXßUwê°é°zY==æ®{­{Eñ.[#Ȧ‹å=¶öJçaÄ};°ž[ê\9a @ðîB’Ñ‘Ú4"ú²¶ŽSVx¼GŠ%é·sC/‹ÎJ{‡yìlX7<X`ð}ûÊdBpl^€RôâdF›íê8:å¦j©oßÝ_ã,C:¨Æ66œ =£T hÙP‹d¹gñxm‰žyR'<š¨ð1mzo¬Å©ŒžÇ�# «ž‹tʼ^$rä,1¡êþLeY/Š«§úW1à&Lšˆe©s†YàbùÆSq‚ž‡Rö`Ï«ü!±˜­Hâ‹Yî §èTî’sÇDá‡b׬F£5j#Ï»ÒöÑæu\ÏYصÓçP©eÛ#Í£lïùÑ[<1gE?Žs»½%ï1ÅšÕ/©‚¾¤ª u®5x ®ðìu4;U Úzĵce&ÒJ똑…Éà0Vzí™{OI+hGcÛ)æŽÄ…Í߯¿14¯v¯³– IµBaiÏ>?½-™D9±çæ²Ú!ðØ¤‚|:i z(eÅØgª=xÏ.}û1k›‡UѨ§¢éKÒGùZZó™r&œ˜ZNJ÷äƒÊîÉ34†‡ÝàëdTjBHA·h@z9³iüž8n ‚Û øåúÈ(Ø.ŒG˜VE"ïxaË�z,íHA½Ðv)2ÓWS'4¢´€Òs|´íðÂçjì=Á¸(ó@u˜d/n1ó嵋sûñHpVºæ­á¥™Ç#ÕæVÐÔç͘jÊ)ûr›ÌFçÉ0Âv*Šž÷íà›œs Ê”¸À×ìÏs1ÏÞ6©_Ì«}1GÝ‚ýbS‚ƒýzèù@¼´ˆ#Õ« (°cÅØÇ´ÏóÍ]Ù²¢‹ƒcý”SNú­n feÑà£AXȬÉ3?è+ãÙ=ó®.&ªšð·b¨Ç-j±1ÃXïVQXÜ5Uò’ÃP÷¼KR¶*9鹦J`õN=ÑW“v°ÔG>$Vó» Þ—›ël¿ƒ_;]“¶ÙØ›y(0ò&€>$ Ô›T­lÁÖèÍ•÷ÎE#_…<íyj[0äH[Ôó§ÂæVRýÅI—îtª=ògCïÂe±;˜9xŠª¦Šy‰çųÑ]”m´z²>Š}Гl`Ìô5U1À—U¶(C›Æ §Ú>—õÌ&0¼¬PgK+aóµí0Ç<s]³èymf.™±tNxÈi'ø—V1SÚM¶øÂú,¹€¸¸«¸Á*e$ß±Ô…YÛ@-ZÑt¸Ã•<Ô–†’ŶIâñö6ZéIÎ`@¤my¨Š¸ÅëœÏàÚ<G«²—mMÍãcϺ´‘9 .bî)ýx.–Ù3töù´Ž¿G|õ’”´:Av%Ðî™ÊĹ›™i­Sˆóè©0ÿÎ@rñâ:ði%-4ŒžîÊñfØl<{BLNDª6a|ì · f b“+^•Srl[Ñîôèʪ[o'Mà’Tâlý!RÔÛç¢Ù©c¾0ÖâäB/ÕÜÔͦU"ú§ðT9®æ F¢/on[£ì£ôGÐ’û؇¼³ž¶K‰NI?¨ÄsU¿À±‚.Èf6gƒÆ~”½Ø‚”&Èû° úÆø­4…¾×¤¬9èNhZ‰²ÖíLvIPD! „© xvÇG–š ¦zÑ$ñx•…õPO±¤·]Èk`l:oêR‹¹>£ÅåœÖnŸy G¥R›-—«±Næ–¾w{]ËÐ^ýÞ3¦ ¿{0Êc4à‘»KÎx ½Oø¹Lù#QH¼(í6fV•ªEÎÕÕÄÞ…æ ÷z[/Ú¸Þ i¢<‘‡rÐd}Úk©Søµµ<9VëÅÓuI„ÌvÍ—òzžà¸Ê9úmH¬®ñÑ,Sã.aÌ–‚j»~jå_ZEF-?ÃW#怲ñ#ºáhüu¶è+3ÍŠ{~oùl(º˜ß¾JÜ+ª©±íDá*Ø®NWIÓƒà*sjï`ªbŒöÌ]=Ô¢ö4k¤wE{¬Ž NÝ^>_ ëHqs„àÐàÞ3I‰–W‡ÊƒoŸÂ6ð%snx×U¥ú<Y½Ý}¹ŠÝ„Ænc¬xöP˜c p ì¼6®Zy‚�©ˆÐdÕ,ð¼Ñ”ÁÛËs4Kß~+ O˜C{4ž<Ì)¢ZˆJÃbCŽêÙÅ&$Þf¦`$ƒÍŒº÷îËŒ¿WÅìNª–„ÂÃhAù쨬¥]æÎÀª)=òF…Æ_�oƒóàÂãдc ÛÊ836£�‡¾+\KHö(í°þÕ…å&Ÿ^_ÒBêÙ"Bzm¿gjÞ­;? Ù8´Â2IV’VÛ79Û9©ik&2iÆ$ìeaªTšÄ¼`½´ð€nïX W{Â製C>I…a~§¨ÔG£ù–ÒŽR«r²·å¸ø gŽC�<# §kËsÂ\F~ƒôrSËÆE@'c x'É ¶á­3?WÝL‡”Ç)áO'¯í8P†é"‰ÝÀšèQÉ^ŒÏÎË—ÓÅÃñ.éfïÅ‘w¾b5í^[P€¹\bK¥ ­õÔ—Ua–|OΟb¶‹yÍè»'ƒÖ›ÈúrÁ ž¼cU{j—PZZº[—ÀQ«øÞ8Ãn,ÛAÄäÁÇ+òPE8€É"+¡ysäS7¼˜\ìèËûò õË«ö£Òx50&{[ÓD9Çàž!ù„éôÁ[òWÕÔÍaÍmÔ‡¼ûy &Q¦‹½î­#–0Ê¿Äj DSo‹}nZšuœ”uœ ¯ëÞ´:5{#,cº¹B<ÀC�{÷6Ýê&»0² RÌV_k”.E“!(u{½syj7ÛÏižÊð(¬­¾ V¾`/‘µ}˜ÐY2$µi=ÝNã¥K�MÞV¬ÅŠ5 ¶ŠQ®Ñ'ªšÏ1xm_Ñ2œ…–^ _ÚácU.ß½¸ëTç¢Ð!­J¬c¹·SêÙ-mÑàF\m›}¤ïuD³M/x¿dOÁ$Q‚ÆC­ºå^L¡T(žQxB<û<»©V…NpŸ¶Ê{ã’Vpz“ËiëܬÌüVº9›]@ú€i{ýª8+ PËò^ξ%>7œ¤qu|‰�í´JýÄà Ñ,Ë0U¡ŠÉ9¹ðÔÑ”p÷–X»5:­!nU3 ¢JÖZ"Ÿ,B,¾7ôzï.–Ÿ×*¡˜eøDqÜcXÛÏÛ«lݳËÔ.’_)L>·R´Ñ»óôqs|£{/‘)+ªÇQâøJeŠXQ‰äНõéhãO™Ø*[<®4ë`­²„\ióA1V•€®É€§B9jφ �2P´h@¦<²2ðxð(d(tÌü­ºÑewtu1×)ÁG<'&lïzN±&ºZŒ’÷šôBH^ rU­hÃãG✰—Fª¦eGækÈh€£¡ŽŒTsàö°¹ y³®¾Ä"þk.µ5)Ár•É´WAâ†4˜©2“¼µžÑn6ÇÈxpC*a5øÆÀzá¬Ðßfåµ¼n™ZV ;å‘ÒzV‡S63 #¼“æöÚlgÙžÙTËI¥7òÈ'Õ Û›•w…Õ• 9¯XHÒl0„’°RVL²"Ó=c\(1—‡ _Õ–ÕP<Âg‡¡ ¢Úä܃èD{ñ¼1ÐôÕÖ ÚÜw£—c¶i$´kdá+Å=÷ÔVBêjái³y»—C ô;«6P=îZx˜®¦ÌB‘Wµ Özi¦@Ù{‘údö^v¨•â{À0˜ª‡w"á½°¦yž½ z täè{Þ—wx¬)‚%«—úÁêuê)ͽš™½V=ö†A®­z®'•ÓI ãì{¥šMó^¤p&fwI›¼ǃÒ3§ç¾VNmö€ïÁÂ+™W× ‡%(ž;ÛYlö@¦&ð&ñÓcz'éèÍŠ0*;©1Ó2aVGºÜ1åÆG ”ï¤V²¼¥ zªÅVêL ž™úb( dk˜²”„7ëè‹¶„™‡eÝWîËÆRGf* ¼Éo¦ÀùÔ½œX0‹2Yø±qV&˜C<Ù5¶­âkeÕyç믱Èö®”oÝa(mÄ0CdzøDFÎU½.Ø'Œ$Ü0 ŒlqUïá¶žç­”2ŸÎÅñx&R;Hºêñª³ìZ²¥;çIèx"‰ßÛ!Ô‚Ôf{:¬V»12Œ\l2ñ„Ѹžn˜¨Hû—Y¾Ì‚it|Ï:¥Ñ­å«cºŽó0f’è;•'À£ xë\˜v7]lÃÚKH©®UQéYØV:šïýù6Œ59.ã»bî QsE!-™ qžG•’ê¼Ù1ÌØ0½-N6ÉÛpi§0ä:ýÄôxé^¶Ôú‘m\R� ôÇÉŠEhX+0¼&忢 ×™º[£ïT~q 8x†Ï3(Øžòˆë¨õ8²mÚ·&àžRæÆ¼µÐLÀ€IY©Ï¸ëí{Uc϶¯Îa—x8\Nñ–øvj¯žÛðNçâ1Ī‚aÛ õeÐ,˜¬âx{ð.ΪÙ0¡Ès äËÙg€¶ssë-XÜOrKÏÓW‡GãJžoOJ_Ð#I;rX¾¸¾žU„ îJ7'Û Î#b'Æ×|q˜³*¥v¾8–KFðàyÓeŒÇMQ5:û¾µnîáÂãöÊ;E7ñˆ²ØãDV/`~Ž—Õ!¦`P5â{¹‹Á©ì¼âü”+�¯ëY¹ø/&à¦ïÖpL¤Hbœ„ZyxKŽõÆ;^¡^.€±fZñ1l4Þx¤-¹¸ u5^ólª7ž(!qÛ¨¿)bI>ò8:Gb†ZÚ!/àȘj“zWðj=±"´–™ Òß4A>¥–0ˆ½›~çñ,2"èÕÒ•ª ƒí>;®v°·/ÔÝP5‡’EÛˆõ¥ÿ§tJ™E‚û%ºÞX$u½ôëj 5BeR'eM» L2cvö¾ÔbøRk–\+™@× @ ù®°çrk6p(ÎYá-çÛj`u½ˆdíXw¨Ðc'§uGJÒ•t±»V±8}Æt¹µE¼]ÚÑÝ“¸?÷’Tý•¾ä×éÊK/ÓÔ19Èò®Æsv ¸ˆëŽv@$v]ËËg»uÎ"Y`v—Á„­*›pÂÆGôàŽ¬ùÈBM2ÊŒDŸ!»ht%PÞ£ôã2ã‘eUË•à¦n6ÓÜJê´‘Só¢„WLšEÉV4ÄüYß.)ͦ\àëQ®ˆµK£‡ìىÄ9/òé¯+£œ5(·‰ 𲻇ìjª…” Qd[„ªgäì6FHP™Ù(ˆ‹•ɮҾ!; fÊØhÊ@·³{3…Z–ÓäýÞ‰{œÛǤâÊ-?Ì׈8©ƒduí= æ¶Ezï‰ÃÄéƒw4TÂ̼¢é4ÚŽ£'bd¦è€iƒ˜ˆ™EF&N¢7&ç Ö8ø¦³Ú(w_Øáëb-%†Ä&¬]@ÒÎMìxšŒ}Ê^ ;– ¸ð¦Kp©Ùsµ;ºëc L.åœæ¢ÎHAôáR _·Æ}ÃMª¡ç&LL„|¯À´}³½K_^/$¼R}Ú#ïà±L¿Œ[~+çM•UÔ@2ÎïlD}vµÚ”æO9”çCŒéÂH´>¹E}Ñùð]oöfÉEeÓ k?±¦  ‰¤ŽÎðä×âDÕÁh1{ï ²&*ª{/ÕÁKÛ÷¸Þ›RÍ7œ~‹6tÒõé–¾·ºÑAŒ„ºî]4¦=Â÷DG†«1²)qÛ{v×R —–`óo ßK¸Û¢°™2˰ƒd”Ç6¥ZÊe‚@¢Âã.*R°jæçiT¤¯À…™²øxÐËëj©ß•£õ‘·‹[v–.i¢t*Oò´Í8p ±¸–º »s€™¦’‰Êù uG(ȼÅRøå+„A£GEe×\޵)šº§œ3ö²‡ttgÒÜ…}*É2UëtÛ;¡[áw ʽê`ÏÛ¥µíwÞ[-š€ê´ª Nκ¾3Ð;.©#9i–!jLÜö8¦ŠzVg\rì×-B%ô>…0Ã(A�®Q ’x�ûÞt Ë7 >ÏZ–Lº=¹µ%ÇžJ½d²#¬»8T…ɱ~Ñ29ê"kâ bVšéD§ÈÅÔ'&Ši°ë„zÑ=ã…pOY$IÍúâ™h¾}°´hÍ ù\¡P1„#³ì•ÐÚÊc(¦­ÜglÞãexq•g3û´ÅX K,Þ>Ãx;ëÈï¢óµo=¬“{˜ê¸ëÇòŒÇ1Íxã¼uWX¥D­ºÛl<ÚˆÛO(@õ˜:oÝK8e½íªå!¦5¿D¶x’dEã±Á›ä¢Aˆ‡«±q=˜›0• /àg²TaR`�^“¸x_Á¨íèƒ3½c]±»2z:"/EäáyLÐn6Zk‚À‰k °jBúv-[F`qáÄ•"Š$îo\•J?×—$÷jpb{}Ÿð—\¢_r1jIOÇmÖ<Å˺F‚6ñ­t¿õç}1¯ ²I8lž¿®µrIÍ×[“>Å+ÂÑoW°J¯K³qÿ²Káõ•¬¼ñ×=ÛEÔÒ&«v2—0eãÆ«C³€,"…�ƒ&Ê4ØÉÍC {Š×­Iï©MÇÝzYDß>œYÑÅ¥sH™D)•„ŽçÔf[»¾júì1H5V_m[XWf„'<”ž�Á:ÕX�Et‡Ü÷i À ña#-6·pÅtyM€6áA4ëseûmñj x¹�е­Ž9þ~Éuò®Øvœ€mƒ\ù ¿)ÚÓòWn.äÑtY)¸¡Tf&Ü�ŽÝHòf¹Ïûé é»\ŒÛlÂ¥`d»êRàd¦›^›ŽÖ1<óÁŠxïå=†1PAw.S5%Ù\DK…c®“ÞhØÈh˜4(·[.irØ—)êÕº/ÜKØ@)¼ú‚^ˆ¿{ѲÇ/VKQuò†ÁÌY•–-¨O®@£Œ%Ö¾'nX³™ÓªJMsCÏkñ"fØÊm*½$¼ä!àcõM9”‚¥ã7|¼—joÝ3çXŒR Iê•…¼æ;èô{4Ïø¦_ãƒîSÛ¬™‡rk/`NëÝKkÓÓè>t\‰:ÀœÃ©{©æÙwÌ-àB “™ïÒSª½ÛhÎòó`1ÕNáá´9̹ø; �‰“¬m ´³=á÷Bž31=fa�®åÞÚƒk8ðŒŽˆBÏ” ™_K‡9è½Ï×¢ò—]Òryª÷háü!ö£õI'çäLI[+ Ñz]™תϔ…¯©\Ð[Y€Ý6‘ë:žIÈŸ“ñ’æ<õ}N²xÖ·ã9\¡kºÇ$5„ë0ª\i†9Ði£| Ú»„öq—½ÀxRz2÷F†ó>|Ç;†`ÍoìÙj ÁرpªFˆjg…7ÈÁ<,rÄdßJžŒxZкᯟˆMß =w—´®ÄgÚ“ƒRM·‡køz^vºÞ,—¢ÕíCÀ‡™²ë¤',8<×p°5›]OÓK³BÇÆ±( Ï¢eü:ûÒôÍ?Å¥‰mW‘˜3L'S¥= ×FáÖ'7™Íô°Žl½•sö]”àͱ™T¨¦6]ê¾ ¼(‹™¹³§oq•ábœÚ)¡3nX*H­Ð"¼éÊÖ‘0¤ó Üv²¹Øì£�#xV/C§ÃnJèY¬¡Ã¬³«“YŒÇ‰^pú¸6(ÀJ9¾—U~iõ˜¶zÝ­k6ÈøåÓF>ÅçZ—¢JgIûb¡UNŸ°ù9¡5nØ®Í…Ž®"¿@oë[ zºˆƒÐ&ê†kKF8͇“Wh(xÏÀÃ!RØÄ=ÏzóÝÐÀ€6<í\>Ór—¨w‹˜/îwPñŒ$èÆ­æÐËíð}\\À¯ ¨sõ»dz  ì kïž(dï«q›0n¿ ™„V_Øæ"–vŽª­à|!ÈV'̆øv_!çu‚¦Ö=ð©…—þ¥—Ñ—^†j‹ T‹icîªzN/—wïÞkÒ”>ë]êô‡Š :MKhõÌ9!³ˆ9cGا/§9+âžkþå×Àõ yMz.Ù+Ÿn™˜Îã–ʾä‰ÓÙô³‚Ò2ÖÓ³@ÞõŠ&Ùê \s,ŠŽ˜ JlWƒ@²d)ÊCݨèt³}Ška‚X‘ˆšeDcëSKXho¹U-ƒ/Ž»nõš«^¿-AC~BÛ0µbû zã‘ ÂÜôTÏ£FŠ©náæê0:5Q²PV½¨n{SÎÌM»º=é¾p±cáA5¶ó¶7 ”Ù!a¸ Mï³wÔ ¢ À[ò}´ô¡û_RàÖ)—têχg4b¦—p,ÃÝL(¡2ù¼SS—$ua%ׯ 'Ä{B-O‡2¯˜øåÓ@Á} Ö#tèîQ?z…çI¨y¼ŠÈ®t[ ‚Ü4t„.Ñ}§dQ>èÞ(oä–]x0®!¢Vo¨UíâÁ „;B¬š÷jY?á‡Æm˜AJÓââ� |Ùc Ý®Vmž;Û*a@XüÒìÐé½}Ä".¥ŒoçyÙÖ“×§¡lo›÷˜ç‡THÒÕO!GG÷¶<”YÄìš pÒH,Õ+ Î3MÓ59"” .;x„¨,<ÑâíÑ¢/öñNôu­¦ãªLÖ£¥£cˆÚ¾§²<BÐ`ЯVÔcžx¹�¹âË{Aüì9³«'k‘diëO¡5¯:…lòd¤8Ë·ºçlHObò¤oýíÓ”ö˜½p“eC;ìn|#öå—×_t“Œ8UI [™B.×Bü€ ¡žð>4c¯lPZÎ63¬Qùá½OAŒ{“ÚâÜÍk¸¯Þü'Ø1Îzç¼—ÌÒ,¼\ .2‡Û,’>"=Cï@Ä‘ qlÁ¤–šÝ4;,ê{gog¨qÖÞñ¾”‰×jÇUp]2¼2à÷ŽG›ájh¤GôØœì ÅÌ1XU’¹ðA6¯I#¬,ëƒÝs™c!’&lé(Ó­l¢æ-[ƒ5P3ÏXE´.';LܰJ%ý;¿—EANYb… ÆÍhiÃüòõ6]I©QyÄ™ WnÉÅFÍ+ é·O³”hL¨WBM`¥ — %ÞÓ2½šÓoÞrC ”ø zR  ööêžÚbXê•Ä ƒÄôK-ð-b"ç=fº—ã75?Ä �Ñ­–1mïÞéI½FªÚ‚‡š°¶x¶¬OùöGX?ÍeZßg+|[3 :»fʶzÄL“'»bT¯”ä¸v‚«EçB¯‡Ë$°mñyUÁ10Ç:?Ñ'rojƒWߎéf# ­ <ÔRÉuNÔ˶}úæ½fG”À〆’M¨^ âG鯼dЈˀ«/œ"€§êdÀ…%ü•Ï™iM]‡¾Þ|¹²{ –…÷òÕ·Ä÷Ý]‡5™­õp?}–Ö}CE]g1Ia×èiž¶¶z×kàŽkÊìØ©ÛJ$x¹z‘AÃ4½¦ä‰üHwjŸ¾c‘H &7voˆ‹º:‰Õ+§oÁüK°ÐAy’šY:$DÙi+Žèϙө†.PÓÞÌs›ëÀ¹Åb=y‹³åéYRÑe¯à‹n²SåÜWj½¨Xþ¯aÉÛÛ œhé*–ó´_±"ÐhV^éQá)—Éœ5FœÉT“.¿“dC6ï38®É8ÄêÓ;Ú”†+]'M]A|§÷èèt_QåÂ#žÀ†¢âÆðw3$w0pس$ÎItÍï(¬-Â)B ¸/KJ†™¹HwÄs ·ƒ,Ezt ¥ ©û¡n>¥dLOÎTdÝê�¸ÞGļ§Dy5÷Z L Ãzà¦2g9†¦èaÍ™ œã»ÀmPíNyR†‹yVkwÆaY Í!„¹Úóž²H¬66�yÂðƒ}=и¥¯øE=}ë5„™†MKGSCó8»hÜ_— À‹ê'gmaNˆ^T<7|2œÏ¶¼Æ¼/C€eJAìiÅ骷-ìÒD,=eMˆKvà2j³y¹çË‘z z\<ôv MÅ.^Z±&Ü&š*³¤’·NŠ…+$> k'HV'Û,±Hö‡èT.¬†ºÞ…íí8,ç2÷ÎqÄïf# , |­@³‘áA Ïe¬O QV›Û:”ø{ <Q¸0ÒÌHbIÐWo‘Þ5kä ð+Ì€‰E¸÷’Ï&®E“ü½‡¨íÁâEÀ׉ïÁc$°àŠ5iH¯¦ça QK[½ƒùrÖç¡¿õ³‹|¦Ä×N°ßßÀ¾ ë‡5/OpD’‚^újI‰½fð8÷LR É™šbR††/„‰Ðp⃆ƒÇb.�6÷âDøƒ³:eBLÿ_1±c^¹ãdÙÉV,“,ƒa”ehêŒÖ{:Ocq]ÉYã½²%y ¤éw@âmD-A RþZ“:ÀŠ»ý¢xªÄLd‡ìøµlÑ •ªÓR²�lRíFÉ@² ÖÓëj–¬±·YsšõŠž·¼!ÙEzŠšÔ!•¡š€ áµWdNGÌ΄pëDàú¤BŸñu2寉ˆaá<?n_qƒ+¥‹dηj¹=ÜÈF7¬W}gT�Lâ²/+ZZ=Î(LÇž±Óö[ÕeÓº|H’*åÜ$úHs^XøÛ“ të'ë…¥Üô”™éyAZá¼kóRµƒâÅ e¤“–‡{XÇÍ­ÛëdQ©(rV#ùP  \}󼬂9ú°P vŽm@"¨vl±Ð_¥ÁoPªP:?åEYètM˜ÁÕÎx[˜ûP µ_ëÑ©4?®Ö¬e!$©Î€¨‘3 …q®~á ‘!=>®4Öº–Ö‹tÊþäDcÍÁ¨Õ¶;XvgqÕ,‚ô1wè-½@ð2(çS¡DG½E^ïÍž¯¬F«RyC4Ì“õÜ..k…Zh$^Úâ^õÈ}E±Ïî¡ O?=mÙ —\†bÖëÐDú潩Š(‹›¶žÎ¨>zQ¼2«/Ìg`Ϲ1Z^a”ëµÁj°ȃæÆç•àŠ)È—b§¯ígMl>CZíˆ9,pçÉ;JF®1=éÍÍ´ <ár˜%I $”eõ|Ø|Z3׆%|”ùáº4ŽTþçØ{õ$l¼9˜kž†sCƒ„ÔŒ“‘§”êLw› ½µ·Ùp¶Æð²µ™Ãø‰,Y§µ‚ ï:š®ŒÄ—­I<Sñór¢;w™~üD¸°%ݽ_>ó6-Š}"惸b^ª]êÄ<ƒ,·Ñ‡¾,&NX/¶Ä-Pð êÊúÙHñjñY¯ámM-D³ à<[5e\¿_þBÁËV:Ûjçº6ת‰\žU{l®ð´Sל•4?›×ˆ&¾EŽZ¦`Y#ÌQ¤£>¢= ËšîKŠ7Í2âcƒ/Nck€¾Æ4éEêQµ�³Evwí¢š­J0¶§úz]bË-Ž;›ÝF±‰ÊÌré®:¼0™K “@¨ÓsË,åP$f6Ù$èIÖ¼ÊÑÚwæf®vNÊ!µ¯¤l¨}�Oì*r×óUÒ<°ï‚j¡(0!£Æ„-V’;c:E}Ú¨g'É"¶Á]²neŒ•d.½ %zC ‘ôй¸Ò²×WœÜl´ßhOùÔTÄhlÙîÝÄ"‰²ªTøEŽË-f>ãVdÁí&æ`}Ó[ÏÃòÜcM:mÜâ7 !\­€R}U2ß=d4.ÕĬЫÊhœ¢¶�áØM¹üáÝ%éÓ‚yYèhè«Òò²µÆÂáæ…eÌ”P?Jñ÷Öky–âË1¤/Ç6Èr½ ÏVŸMÝuSZ¹·Õ<Ó ŽáÁç5{œ‰Œm¸Œ+ÔsyR2ýó7ù-*ìÕžªjIc—€pŒ³æ#YºÜ÷ŸdNum¬ù,ÆÍÔ8¬Þ#¾«Êpó‡tôšß ÒN+V/çÀ…o†É‡×~ðЪB³ &Úð8_µÏ!£>Ô Òí«+G]¼~Ѐ’ëž"Ä8“2—¾¬Ëg°©óR×$ýf)äd‡–7œB&ËÙ‹ÚŠ/¯‹"4_ž=³H’«‡ŒNÌé4í,í\<÷\R«Xz£‹oöE^×¥YÃ$ •u‰Éih­|Q—O£±íî¦ÊYÈ_»’¥i.Ó2¿¦:´æÒ%Ñ÷N ô°üº2`…l«¡;Ê‹’Ê E•Ò—˜Wi„ræ7`o"ƒ2 é%¤Õóuup2W{]ƒI¦L€Ä\²µ¼ŠO<qð< ÔÕÒZ}u}±Ÿ™È*J–LÖ)&1A†iœS¨ Q ˜,N wTù)91`­^àt+¼Cqª—vÃéõ±Ÿ"Ø u徎;éº'1âÀ4f Õ/›j;÷ZíQçkÃô³Ä‹a¡l\ƒÐ⼇ˆ§µ�Fžák£If¶fpkŽ¢éŠÉwĵi錄I¡W†Ý̳Û{·výµðÁ{s4‡›rÆ¢òžÜò{¤Û]>rò %] †ívsF&y&%Å=t&S´tÏ%bƒß€Õ­Í¹{¼tòiŒ‰œà6¢2Þ'çè„-àjÛ1lÝi5×Ýû¨—çK2‚/ÉÐÖ‹Ç/Ü7ª@f£ÃŽŒž#v<î•T +y:y÷¶Ò”jŽðæ^ÓñÅ=.} ï^ÒѾè›ä¸äà9ÌøÏ23$[z“Þh�e>°cºqòZÐô2…§e +ângšy — � Úå \ÜRÜ$^éÞ‘cLxƒ¼ž>Os“UIÓW ¬ÚOû½Õæ‰Þ‡×ô\ÓyH¥B™Þ+2Ú…Ôª7Ð$;ú.wä¦ÂFož¬íí–fl̉·a´ø£>.R´©"‡ÇôxÉ‚UdéáØÁ™Ôú4±m6�pܰQºð4›c¡YW“À“ÐEà vx·F|lâ÷"ýj îî=Ð'&ë€ ¹#G&T‘ÔúëT�•Fá$FBðÓÆFƧeèXîN ût×8ƒ0¶«/C8†&R¡½¡t„ €ÏÞŒRN]œiT]ÚØó* ÷G±ÛSÅÓìXŠ7 HyÜÆiE<�)hb~“œ;ˆJ¦µœ"3wïÜ'žªï{ÂPÁ2¹JQiÅð ‹‚²4зH EÃU¥¤ÛÈB0úJH½®Ôâ±8ëéQt¼^x⾸©-ÛF-ÏßkWÜ€¶G²oE'OÅq¡r÷NFF–v·ŠYïQ8„o<[q{ðÔ�Ï9i¨'1åYâF@/H‹Ú»«ˆÌò š/Ò<ófãáL9óèyÏïÅ>á…*½`]Ñ‹çÓE¹ƒ4×Ó)ª¦j‹q¤#þ\¯äáH ÚÓáryBÏl´Rꎒ/>-óÏ×e ÉnÑkôDlÀãhU¯çé å>•8M)´£K Ûßy‘¨Ã–ë">”K>߬«�n|aÒ%§û¬(ŸéðÖò»þO³½ÜŽAº^?Õ³}ï‘{l£È:LãêsÖ°'(!L˜ÎTòö4*|I„&Â`&m}iU5Ó÷…™¦Ÿ>”Åwë·“ª˜Ýh‡§°¡Îqw$ô¦q½€,œTÞȈ5âŠ×ò¹+"Žò1æ“xÔjú¢Í± jtä¥4e(qõ¢ ˜ß;ò鈦ˆ=õ&$CYN[‡­¾=Ç–…£ºÈÕµB˜&Ù„¨©–çŸyôõQVÈ{"®AÒ¥oX敯(oˆµ>¤ ×RñëvÆâeľ»d4 AóXî1‰æ“7aÀÏAÚR.½! 1ßh²žµdy”I?VT¢äUŠÅ¨Èy÷ºYì$Ó»w¸6ž*òK²€×7ï^naê㌇-©Ï S9¢kMè�Á$^&›Ìôd?m•W3e€xd¥&Ý' ªÓàÕäÀ«   DbËïM«Á g¨;˜ËãB¹}ËqѤ¾I/&|Ž0€Ö`F¶€ÉlýñpA“Ì0ƒY²[ #®:Æ;’<‡KT�sç„MLo€TaŸ“"d›Žá³Bˆ&¬&lû ÓX£•'a7‰´È°!ZÑ­Y¾è*:ÓÅÁ甋Ðý°VqFä¡/ÝÆE?Ð ©¨´¢—¤«:IþTÝÛwÊÝì²c¯ÞEzì¼GÝæŸ›Û—fYËò¨TöÑc©©|¨þØÄ„[ް˜¯ªƒæ]v$kË2ݱCW¦ìù¼!LBòz§eDzÈÇÑï®i­<w׈Jýϳ3éâ°ø\ËäÙ9|ùÌw1œâå“ÕAÃw÷$™‰âЋeÅ&Wå=’ûÐ "+â-g£ä¾y³�Ö« ,ñ‚;x¦Äf=°¯ðØeÕõìQ¥?4Àu|ÕcLï8ßå›eͳ„Ÿ>žjχ*½®À|ö®MíBoä•ÁJ˜£‡n-8ÉœÂù&ˆC)l1™pº×ÅéÉUR¹¥Îu8¨äÉ ’xON`ðìóÞ‡[Ï–){fBΊ^)ªO¬ñ©3Æ3•ö Å {~‚{v¦Ò™]p”¥3†RUL³`׌óHƒ!ŠxÎKÝ„‰¶hü8Þjò1I™ø3Cª•Ä–W`÷Z«-&¤ž÷åÖ#‰KŠVª)U…~EA¶;ö�N‡i({Ìw8mÖ¯ó‚_ìÀ„vHu8êÝ›ÒM¬&5Ñ=.ËGžwÒIÐvNîwp'õ¦ÎÙ“·UŒ³Ü»Þ�翪 yñ2|¢²!ö1¡Öyí oT&C„&‡q-Ñç:®2É‘gâñ½Ñ¢æ-^+ �GDƒKEYØÚ<yë34¶m—ÈÉ¡®.ïUK`1Ðõ“tOJGv…ÇŒAܬ/Kv‡Ïä.~1 DŽ ¢¸H#xð"€ âm¿Ó|˜ï °T¯ë°sÅÛÑe‚M²fpìEc.#¼¶ŽZ<…I¶/ÏD¾<c»8HÓ£N ŸÇQ!2¶w<©[•úöM´ †'¬°ÃqŸ”¼Ø&@½[#5z¬ˆ¨’×Ç%%uc-OäfàŒæ)¼x`ÿŠÖã:[1©Žyf ÅHZÚ.‹¥¾—cãÙoe%C¼ØÚE¶cÓu Íç¥&nI=JsÍ-‡| OK:J¹ÂxÂà^µûôŽ1öcA”&/Z‚Ó7AjY€…y;“Qq®7 ³\áSìY³ êl}…Ô‚«5¹ú*ø•ñkÄy÷fIh+îÑ0)·Ž;3:Þå¤ N‚à ¼†ó‰ÉRÅÂôõìšêcÒ ¦¬¹ái»Üur\ó#óÒó”æ pˆ>‘3¯Æ5Ób‹‘y25›w@Qš_ÊC’^ zôdBÁ^;�ÛN¦$BîÃu~ 1µ2Íêsbþ8h"в×ks2LÍÞSôBƒ×¾ÈõNêz/qdÙ+ª(¶ˆ_E·Ù=0Ö´VÆÚèò€\gîy½¬ÞçØúL‚¹rü)S=Äãs÷Ç;âé\VÔ ¼–Ìç$·%Ýý€Ö©÷�®&Øï¢ölù%¶X˜-qøö€> ê.M/˜7ÂL¯”Uået¿ÓKr»Øl²µÄ¾r›buÆ{š@Éûü¬.J¹³µcqʦM÷±ÖS‰tÞJ8½{%\lDê_ãm k¨¿¼²°ÈÀÝ ãÉ),S¹O(¨�ŠâÑš±Bõà{¯@¥Wu¶Ž™\q!ŸlÕñ–=éÂ{«xá xÛ´_¢)}ohíïw.v†×xk9uVªd;“ÛùÛ0$Ï•YóìÐ9]¦h6xøjXâÈÊ)¹u¾ij\ÜS«'Seڔ͊áxSŒÖï¥ügZ€rú=ö4oô.W™ÎjPè �Jë¬øU=YÃ@§j$¼·$©ÓЫñêpÞðš ¢Kˆ(§›<â|ÜKB÷П#¶;dŸ2¨³Ö Âu½)C6"xÂw*É«w¤éQ äcæÐï¦8‹RÕíN…¹÷"ˆÙ—‚TM-–È^$§º.S¹7=Qª}Z³ŸG‰ñZèÕðiE…ä:—Vpo=»*¬'0[ï–½:A“«JÑ6òv ϯ7D»\ÆëFq/ð¡KšµZ1&ä•Ûõ$Ý<y¸ ²Sj"@šXõ‚RQ§êh˜«Lt•Ò_½rj‘Þe2‹ ;ŸÌÖ Fz¥˜¥­;«,RL­É”Ewû[I£c˜…ºÆ èÉŒ‘650ÞÆ9)Àhs8õ‹gFp%†­ÏÕV1Ú®ñ$ƒ5K¼£À~ˆLâ§¼‰)u1ÅÈuWWJX4ÊÎ- ¡Ÿ+²Ÿ»êœkTfªã”¤í•>û Ùôxß YgÖ»êÊ1šÚÁ[jæ#1¼ôˆÙ#'ͦ†Û Ÿ#âBF| †‡ývû·v]:£,ú¦u7PÅØ%½ (¡Ãy®Ž|{‹$q¦õHGf5ráaÊY d&Y°žÌÞ\ò3èð®uÐT˜­b@\�Ô«uè+,+B#@{:'$Ÿ[šÁ—i!÷:}1Uˆ¥m”»K£B{¥·ž;l–éí ¿àŒ¸µL ävã+DŒÑá“2÷öA®È«,ï» b§ñ|ï$i\ËÕ<úO5zu„ž€Hª(UXÏW2í=~\Eï.,5¤Þ!tã@rðåS>á× ¨BC¯‘ø”ïÞØ“b?2xe¯O0€`Xý´†k„d8NÞ z»¤rëâcÓs¹¨eBµFÕ¢7\JµOõU&¥³Û°úøµ‹KV%ÔZ·ð„ÚáKÁ>ÇéÕ}ÎdÆÜÁd �RøèƒGjð\UcB$Ú¼“‹MÊ»}L¾ñ`2¡‰ÜX6Qµ ÏvÂÄG êÔ¯£gJThBîxr†ÍÝ»>Ó^ðt2Yñ4GÀhMß³}7zá Žì%‹ènJž;L†ƒ Ι3œ'g²™ÜÙ¼ö6¦ÍáÔ 1®»‹›Aûž$Åcßã»>.ñrÇó‰£k¾WÄ^j ¡ãˆ šñߺåš&u:½rÁ-Mbé’Ž2~WÒ:@¤SÒF“Bp<è¡W´ºœ<öìÝã›j¯OU핞U­S&­ç´Ð$tÅ=ô&Œ3ö�e¦R üÈè]gíœ>H‰å÷ «OtwŸkӔƀÎùHú*ŠQxÙÖâ,i%‚ÇôÛÛ³ê%*᫈ݬ™Ìgj&J§"›éÚ+ªQiΉD½Ï‚ ±Õ$ŠCVät¢xÇ…[ò[Uªi©Ü£—0¢Çs¤¹®äŸªù—jÈ5äˆg;Tv wì¡Ù»ójϧGt _`5†$œƒXÝ5WcS1xa>Š^�GŒ³ ~ž=Ý žNKðØ ¬gjõ6,$Çæ_×®—PÙ(•x^=»r¶-Q7{ÑêÕŠóvíl¶ÂCÊ’ù鳂ɋt0qobFõ’öRfŽ…)¾ÝA¡LÖ„'ïÀW—#IÜæéI¼®±;­£Ìì@´¬¶}þ &Zɹ]`½- 8¸Ï€ù±)ÎkÍ‚O]Êô4ΰ\GÞULÍkqv™;F@ªÑÓŒž›zÈÑܬ§<&<S<ùìÕaª[ë®Åä•2ªË3i‡fE¬O<ç!’‹ós.ÃɱV¡êç‡ÊɹCo‘ÌAý,”H}èÉ!¶OKjÍÈZ´Áôáy̱oÎísîJSJUA·‰u†×ï=~Dƒ Ñì¨JvêlHUãg­þÔËájØ9ô­!½÷2Î^#©óí•=en0%·>~€"P˜/…gI@W7hŒùÒx—¶ZÀÑDEçˆøŽ8f×l3 žÃ ð„€;¬×™WŒ£îõ¡ÆÂ¸zó­ ùK*_ö­#[´e•â=ã÷d0Q,°PbÒTÁ7Ì:k¯ËVHùN¸NçåóL÷fÛª}¬eET/û@G ÕyrÊø•5{&[1S\@Ø3t¾*%À°Ùi‡i«„)™GÙ¦"ªØÍ^Äy �xéjCH !*¼|§ó‹^ Ásƒ„ ÂÙªÜg±ª9q ñ¬ŸÖÀ—kÏ>]ÛèJ|‘�±MÛªàïñ ƒÊ{ˆomÔbÍJϤ­ÚÄ{IÓ…¤W’lôiyÚÂæð FÐÎÌnÓÖ>T˜?ãœfâ·§¯9^¦çûO¶ZgܨӛÉLJÏ":!;÷L× iµ%%T-L¥tJ‰«@„±^ $ ߑʉ0‰kIZº?À¼tBlÑV.IlIôG׿:&2[:K, ˆG1`tÖÇáÀÕÌ "=ëŒÀ¨š÷Þ‡X¾wAƒ}øPˆâíÈYA “Š›`K“È”¿[qKÞz>Ã¥¯{ÁQwÕ)ow»Q:©i°ßÊc¸'í÷øÕ,¿QöI'Ê ,‡ðôÒ7O®7=±©o)â ,žõŠzÌÖ}I×èOžtdf\ÚÓñ.E…ðón Ñ &5<?º].²7~õ^b–+ “+\@y+ ø'‘¥á‚z¸Ðö–8hœÖ“5^jSª-dX^°{TŒq4o®Iæ!å³Î`¦ ªbïó˜p ª—£¦RÄú˜´ ûì°ãŠMöw½ ½òô.ÖýùªUJíæ²KÍÅJ Îùºœ–>x £\öƪ0÷øÅ³b?ÈM{mió?X~5ÏÅD3ÊÔ±Ù4Ö±Ëlìc1»ÓôŽJ¥2šŽº¤<Kì¹¼&ž„+<ÍW±•ŠÙk ˆ±Ü/Qò:íYíˆÑNWvõ‹²)blƒé‘¬ªKhä†,sÈí|¾up{ÍÝòΚ!4$cŽЂZLÓ6H­Ù¬¥•Ë®ÙËöÐw¼õá„ìÒ[Wé/Ù\¾d«Ô²WºÍÉw¹Ô3ŽÏ’öž6ôð#ÑŽ®� /)ìeh®9Y¤M‹Y¿2IÏ6Ã{{ ìËÄSzÔ&RÏ‹F|<ó?Ûäuýˆ‘Üâ{þkË&‹%•¼x¥cè5/Qç@G—U©é)¶Å«¦V¦¥âô`©ÈW{( S¦c'2Q¶ôâÑÕ‚ÂZ>S~»ÃW¨.±cØ\t¶ éJ<çZ—Ë\Å`,LH‡M!BO£]›×œ"ñEŸ[ŠÐTÖI„�Å›å£èŒ³]ÒÝ“¨èWü¦E"2m¸˜&)‹³q­ÒŽÃž2]¢¯Bá* o‘ÈÛ%èx0—y’`ƒù VBò)ª$E¡>æ«&|%¯Ø\ “q(¦ÐnÞRp+¶êª,ªè»€Ð€=ïW¯D¹—˜RÑEƒxÍ;Ú$ æíV¯1ªå„@o|2­Áq»ÑâÔ×DpG~úÞ{3#œ™]Cœ†éòx¤û�ÙcÃÉß#§u 9`sÞ*ëŽ ÇD\0§°&f*A»«n]³£/Ÿ¾g”ÀrŽ78ᘷóÆrSãöÁLïcOÁS>C¬ ·Í3œõÖ#¡ 8„7“òÉ%5„Ëô–¾wV¼/7¼«{â9¬ÒˆÔì]ž˜Ýd¿¡¨ö P)¸ªhO¢Ô# ueS¡&‘®c�hèÆ®‚–EOŠî ‹W°êY˜û^.BáðvЖÅc“N zѲ»Ç1ôl'ûϽԌ'ç/Oûe2–VéáÉ­qñHÇ™K ¸ô{9Oʾl ú² ö’,[í1Ú›ÎÎrƒ`Ú1¤3½“(‡ËÈ5ÓUê2‚§sØš«r•2åðjI �ó^qÍháp‡´-D•Œ§uÜÉ<xò¯nêwhûÐv¥å—AñÊã D}Ïžn,'lB%z)btT2b¿Q!òàƒ—siˆ`O§Kxt|Û¢a÷,I‘ | xçÓz¼*°fwoÇ`žaËðªì¥‰·vV"Ãc¼¦*eE±=Û”;Î×Çî&o›´Ù_ØCRImYÅX’µ©™o¬@OM^çæä«d-ÑÛÝ}"Õ°ÏÆ7­\º‡Õ1¨² É KÓQľÉ÷Ìê–Ý@:p9Õ“õ7B¶³1/WN À•ß¾XR€×G§ÛÕ˜°(­]Î.“Û Ø®®NH½T‘EBtvoo2üe¤âL#>î®]Р=<“JÂØú.™ø©gCÊÊØãV$Ä” F2F*›F f›W[uLÚÔ2$ÞR@€º × ˜¶úÉÆòñÁŽ{ysPׂ9 1!ŒŠ)ìù¬ Ö;Ûª>š ½w›=ð$)m…öjù5qldæÚÂâb– ×ÂÁ¼Qcyú"Ÿf§Žb—RDø{,»~0®ŠÔ.–;6EI'Ê…·$O]©ƒî°Š…cbìxëYI,qÜ#w°WƒuW…eæcï]„@Å€Pƒí\©•åeò»@φXYùM†ŸLiò«ž40§»ÁìÁ­‹ ˆ‡·hølî&Õí¡Â•óÑÃÚQjœ{~T§ô¡›|nnũ7¯NC²ß +½7o|4µ|e'lèLö=̪QLMÏÍ'XÛ]3…ïUo‚’ðÖ�pßl®¿×2b eÏc¼€ùÞvéÔàÆúÏ7 <°~È~f¬DÕ#"«ñšêùI;[´û“—¨ �ºiÞ–[Îû5¸÷$•ø1Â(?<f«&C‹§B@>âwAJ<ó¼ ÇÕ¯õO…DÞ"’£;N4‘98Àd? Qåe2.Zp<yб®ï©éÞ;oe¸ç¹GÀ‘P¤œäK±Ö 7dwöÞš"a)>u¢˜ªŒ{&ŠrllqO˜dýB¡®ƒ’!D•Ht÷E×%c€ñÊl#ó"l[Ð¥áV“{¹€Ì:N¤"_¾[›¢6¬–œ´¹™’’(íÜÅyݧ•vÉ‘´IFD®0rrðâ^°©ƒ‰@y˜q?Ð$yFѾäûÞ ¾áÈ.~5I³÷\^#Í;tH{ÕÏý…Žåú[ËC“%§Æ}ÆDéÇîjm*ñÞ­Ÿå38 D�±·oa35çm´^$¾£n/Ñcð®´÷°³„å^§u'?LëÇÈ ª‰<Ú/0tjB"å:Ÿ5ÙÚèö±paÄÊó$IÕÛ–A[zày�XåÙüïs’ªll0µP—B„8¼Ð)Èœ….åÚ÷Ö½Ó9ÝÔxqýâ>ô+6´J^•¤º˜»g˜B»¸1ƒ)ŒýÒ™DH 'öåèõ¨£Ó«+j¿)H;ˆax¯Åq®*(-oàqe˜#fÏîNæäõ¾~°ÒûTÛu£1¯èÁ Á¢[~úæ_¾Àóˆ¸áf-Ï«0ëšeVdÓƒë§äÖ3î—Š—rQ>{¯#[R§zB_^½Á?ã²M•)s,ïÄGÒÆ€¹‰7 q4t+›_ÿ'ÜT+tgî¾³E×g+¬×¯Ût«‹Þ$zº{Î.† ×ÙÉ`1¸¯:IyZ�«œd(ç>î鵂ÐtÖÑ}Jóh-"û€Q)æ1‹úféŒ]øØÓev‡³}1pÅù|]øÈÐO…ýQ2²œIÚSä)ÎB¾"6ÃaÞ %Ø´_nžŠJé1XƒÈ€J‘X,tjžCÇ//ÓÁÌ7��‡Q+Él€Qiа\Á)-ùKbÝÓi!¥ÌjDeA`ÑágÑ&uÍX¸È8 $8r.!ˆˆüvÉyošõ6U¤™â­%¦ûŠ�€K¨bFƒ£i& L˜ºÎH;™ªô: 7�‹ Àûc"S8×Ç ŽÔÖ²f0´¼«³ýx襉ê>P‹_ÁÆÈ©†ÕvƒUvXmé Çäò@a³Y• &Ëy¼÷ÃC¦ÐgiÕ`‰•g£iÊêFÈ™^f¥‰4¡_Öñ<í*~§‘ø©{ãaá<;r=<í¼UFÚ×tðòhí–M1÷2°6é ä 6e¿·\սə‘o3y\èÓE1|™ûhæ¹<Dé§["LwMÃ5jˆï‚Ü b:p£ó$˜Ä‘)WhR{–Í{¸ o™Z6îq¥”)Ý¡m<«9z*®ý¶ÏÚfÞàkÊ(ÑVñzÛîë©_¡} g‚ ÛéÆŠÚûú*ÊÄÐäøÉX`O)xfV£c\d»”Rå5ܾž©V•2ðl6‹ñ)FKå”6ß^&ÙÖ”¸›ÒH¬±¤ LØÿŒ{Ù ¯a&=†�³"ÞÑ hIã`€a`s*pDFJ-`5Á”z¾Ü:GáVEÑ5[Q[>±ÓLäÇ ´f˜ÞŒÎQ-ó.ErLÝ®Jù*GôB„Ç:ç·› ¼¸¢g!¯eˆ«Ù+ÁÆgR$Ѿ¯X^€Í¡„/cw쑪_ؽ{¹L<–ƼXGÌHK(fÏC¨˜ø£W†©S ï04Ha$RéÂAÌ<‹Sm»¬%6Ÿc ¯kB"³vœ ˆÙ½æ7gÚ«t¯8¬$†#93n™”7"+Öm?O\ÐS •y V„¡DééRŸ¾lä{·ÌTÏ`¼æ÷ʹ24¯¨cj„ž›ÎQ›wÑ5`©zÄK•,Os9­±çªñ¨‹kT2Œàö wÜ‘A9t¡ô­\ƪs_V!Õ µ´I»Ùp‰f€éźöw®}VÁÏ¿sfäÙÚÎl>D±…óbƒ4”²~´˜¼"…aùô©’ÄÙôn妃ÄÓ1¸"_44±r‡£4¬½Î1I<f2 HŽ9¿¨¾4lFí#5F¡P{Ìì‡nµP‘R9=Ñ’à,^#Ï _Ï»Ñ:lE:s U©{—êð€ “•_‚ËOÓxÏUòrÂòVüêÜ[Pãê—O/ò±¥¿ôHÔ4GB„Û ¬Óò{oÓ½‰à)¾û2Žä˸S©%÷ŠãzˆM¨ñ<½[Ÿ<5‡„ Le¹Çúaof=Òdç–ë“ñÙL}×ɽ vŒ†Û}Qn‡Ž•Z;–¥%¾xÖNmk×(.ZÜžÿ)wТüz±8‘ .T,oH¼Ó§Ïé®¶<Í�æufûo›?¼”:¯bÆxäõʈñ,¤×DfÅöTÞµ2KÉ,ð—†Ã£¯<WÙI&}¼,ûtNlÁçÉ1ú°ßb˜ªBΠ‰g;šÕ¡¼r“sß%?O]¸æê.îe±HeÛK¾Xm×€ÃØ~ë</(£“µsŸð¹L2¬!ç?TxÛ†­úä=¬y¦΂:¾"`{¨° ]KÌù×ÝžqÌH`á)¾›Åk­`{ØXŒ /Ìfè Ñ¡ìq‡®½ÈÂd‡‹ 4m%"yï¶âm$·;‚ÌëÝ(þMζ0|H½bœËÉŽévñ-¥Æ5ˆu:ê-„j§{:^©åë€ê B¶,(>^`)#c¹vçw47n/<‹YG¯’‡¯qÏÚ!  BlP[JQxq 3lRù…ÎÎÙ+óQ†¸Äì˜r55[G3K‰ÌY™}‹)¥¹½P#!˜l´P/ºÞÞ^ÎÉN[²HK $¾ƒ}÷`ö½™H'Ñ7=ê¦Îh%ü¼Ô 4—c Ÿ‚UP Zé Àì9v·aQ’uoÖ‡²Œ¡1y]¥y¦wœâq‚ˆÙÓ˜7Xaö<®+]w‘ ÍÒ›Áו™V’½ g2¥èZñJâ4Ú¥øK9¦/å&8ÄÝ4;lMê`±Ð›¢ncʌƙâ)•{1€·º «ŠƒÙ&]K# ¢wà1©‘¤ ÌÚÞLuRØ^°àiÞö5ŠÕ)×ä¨Zýçñ=Ý©=¦8ÀU 2‹Ð¾ŠÔƒ'¾±X],RÆá«òÅwc'±¾ñ¹:n¦JkhZ¶«0gñAvo‚ŠÓGuÑ{ÁØ&<ö¨ÝTkìm7l‡(µ &<îÇRA†î+‰Åc.‡Ò:±z(ZûÒk§¡R³­’ÔŽ*DÕ-Ï!hÁéQÈ•‹…Û°»{µ]ˆV�l•ŠAÈR\ölÖ4λŶv^5ˆgŒ¥êÄã­‘tªØ®ñµb°qÃ¥…²+§:;²/Ÿº®p ó:Ì¥¿ÐÄ{z°7)×ûóëÐXT'=¾S¡œ*Ûmd$?œ'ío¬­DÙmêÛ‘`ÂZ»T´ÂLb‰âvM½xز¨µr6oh= ß º#EŸDªÜ¸:ðV±á<>È7ªo`ñµsÓ›é•ÇžØÛçàºïÝ$O{´“A¤É[Ò»ô¡k7 )Êܯ˜JÚƒu³"¸‚¼ "M bkC÷|9̰_X2©ïHH°2×^¤FÒ›®>CÉÍ<‚ÚCµ2¬Kâ«]—y–ûGÐÜC èrX­#0×á\ÃÙN§a!0Vô™U½Ä=Éjoón/£ “F©2'hÀ"™©„à†eíÊ.uäqû{Yùj²Þ¾(ì|@C+½›˜œtË%@¯fÚ–náË9/çüa¼ÔckžÄ¹^}ÙãY.þšž\³U#¿­±;1õRyÓ—ezÀ/SýX÷ÐòN²ö½JÃ3u²{µæXZ6š¸ùËåFöAúódÄR‰´±<bøO:È£ÇGìÏë¼¶#Hä3~Ê;åщ¹T \N{:³ÞºÄkAáÔJ¬#`S9~åñòtÞTšRÂØi£ÏÃ=<LH pÍL²¡6›|+ø›åR ùúm SóAßÝ‘½¥ê÷p†‚Ì–Ú$2äøP¯úaªa˜/äSÈ~*P±öD92eP‡nsÃbW‚z=ä"¤�7‹Îò‘Md¹Ë‹e’çQ7�¼YM!ÒÂÕ`ظ$õfn±ÃáLg4¼™CHœäéÉ<|³¹Ï+y<_º?$˜HGu¬Ñ`!ÊæÄ÷¬¹_Ú$ÃÈ8¯/d?fn,óÁÎgEI'wp+ñ–´„]a$´20óÑ›Z[ò²÷ÚûÍdÝV_æÙ+߯Ś1/¡ØW¤e 4Cu½×ÚÕ·Ú¯e™Ì€ÞæRsÀ{íûÌÒå‹1¯ö[ß¹é¥v`Ò¦Û.mgR7(’´*šÀºÔ³‡@ÉgÙÃ3ÖÁüj–7Ä"Ž‹…qœ‚ï»±yÍœûÅ-‰d­<,´Äê~\õ*×2ø¹Ï°D×ÓG1B”WLÛ½w-T¯,¤P…ÜNzRŸ² 4]¾ ßG¹Kåã U–zé´å@MOI­‘•Š`h5†ÇøN·™íÁ%½N‹¡S7'NÜ„ðžèÎ Æ}R{“Hg|éð,E<¤\à¦Z†ôÏ{ŸÒù—tPr·'#úªßC¼“ÌGÄØIšgEK`çu®1þÔË#_‚N‘²ؤsåè™q%bêÙ±Ýèù(·®Ç¡sroj)ôksÜ÷xâîI`i7…µþgÝ»Æ{×ôˆø™µŸ0øKn•ÔôL0Ü"¶‡!$\eÔo Â\ªŽÍ»¬ê¡µQÇ1©GPCÇ ÕgD©W¨° Iæûølòœ¸†S”œ9÷;mš‚[ðí{V1²/ËA&I¨„ðAcx?WR³¹œl}c˜J-îtbK‘·ÔY[QßjÂ@úŠRŒËO•··D3ñô)üy9)E½Yž­ÅÎGcø`l,ñ5ðf\TpÄ5v¥‘ì ÄÙ *Æãâ ±«#±ybS\z x<[È«=×_·£Ó„äc¤™: <Q—àgaûÔµ{ž@3ܾ1F@ v{É4Q 9¦\§# ±V-EFæhjV€ê•Í3‘Ò§2 ÓŽ§q…ï^³¯‘ÐK™0«~2¹ß’Ü9˜‚¶¶°bªdAç�ÎŒ§†A. Ÿ<3ð´)CóG¢¼ …È!øè½µVD&�O.°+ÓÝ9½È,4ñâ8­˜avgxZ^­ %3t ²­oª‡©“£ám¿&OѸYTæb8 ;b{µ1më&O¶h^rJ/E·l_ù+1£›y,iÒZ÷ŒÂÝýЉŶL¤Éo¬ÆªŒF3'ïö jÊÓ!îÙ¼(Cg°W jJÞwÇY)Û0dw}Mü°¶—Âè§ujŸÖ=òY£yêj ÐÒï¥RƒCó! Ûa´vB&Ã#Ë€Õ㣠yÞÛGö_-½!4…Œ”Áe:“0zÆ>•“ñ€úu20Yì �JÑqŸ—‡l¶«ÊÚaM‹pùáZÊk}?¼¶c-@¼–(ìõ43>L‹}Ë£ n:«dïi«3dXÝúÌ! 4ßó‡@¬FøÞ:½[(õöÖ”�®×ã€DìühZgò¦¿‡—Tïá=Pñ^áì‚£Õ”`äëg[yëõt‘ð€BVð1ñvTg\Þ¥ãíPæ{šICm‚ójdÓ k´Iºo²ñn.[Œ^s¸¦à®né[¢XL¬`¤¶› 4Ð!«ÜC°¹ÒÚË7[ôàÂð­÷] GnèÄî>¶­Ì‹pyéÆwV·›„´›H/L”§9'X÷é!µæ;Xk$B®yµ0¶â¹‘¸pç{¥¾™ü^¾A±Œ·*–‘ u¯Ý±C"*6à¥Ùë,n“±'Ë©/l›ùll%)÷ ¢Ì©Ý÷(Þã4z ÆÈœ»Ûòô]Dl¾¤ð|ÎÍ,Cq»¢K ÎD™|•Gp1ÇÐ9aywÑv°LÉt `‡D‹5†Ê„&¾zÃFåïZ±6nïžF½Ûœg2<—ï°óš”ŽV;…“8äíÎH¹ošÀê킌E$¤m¼*’ê.ŽËˆÇU3ôBŸ›ÙÊ 0akÆ+K}×}ã}éY ªçx .p\{î±¾}ço`[y*âì9½‡0},vÔ£<õ¥É—vÆâGû ç¸Þƒ~OEVÑlÁÑ.±­ÝÑbêI?[¡­p¾ì¢g9–0xùJax¹ìz^Äv<yù²vä ¹ß¹ó’tö;´ ®ŠŠ…ç5x¨žcÚÿX¿tZÁG=Þ'Ø9<¸›Ð–î*"@¥w<ÞcÓîd0á‘»ào²$‚2$žîòhù8<%ZÍf+À’ÂHG~ÏìA 2jsƒfÜ—­z°/Ô}7G'jk5»y‰¬^‰aИ$u¹ÛJ9¢ãë{GÁÒúF§i�–w‰¥ôEYÙÒ(‹ û³žâ§d$k*,ë>ª‹äBñ:×H"´°øÙÃòh}ëÏ®ØpdzE-xœj¶ ›ß¬>â ÐÜS³FÃ8;éÂŽ÷^5¼³àe]!ìšÀÖ8°× $bG؉4]8Ï}º@¸¥dÁâ>¯,é�0b¡;6±Þv$HíAYŒ‡zfÛv†1 ;uØ1Q9épPE!ÏÀµçØ™À®g+üqÅhà1àøT oò”Øk^”÷ЧA‰@§Õ¾Ä>á§£0¢STyÌ!‚‡!b÷äÞŠŽF…Š/àæÙÊØ(iñKÓg1ä0eSxô2Æeeâõë…¼N®î|ÏØîø©µu¥«Îh©>¡÷¶Ó’0è=P§×°r¢™ú–t¯Êôɇ‘P´5}RFl´ù,û®P±@\öñ=¨ÁÚ3 "BϺ½LÖ¥ü½dÇ·¡a|l„yk׫oBFá=¼ÀÈÂjÙxÕ¼ÕÕÔ´mþê&U·ÌAךh˜È s›©}y÷èË;)¤w³:û˜Í¡é°±Ñ[ãlO>,yð&œ:7IÝT'êÐÏ#oUž8U.¸‹jHÙCK íHm-»à‚äP¢iOøÕj“°uô¾,{ò‚åúš!7óì?ñesÚœé¤ÞX3Ïk<ŠŠK±‡½ßÄIÛÎ`»h ñxºJ…ôCµB$£G;õ8mQ¶_r„Ã$£±Øà1CóUø›WÒbebQ/5¶¬Ð$ªêUÓHTR|FrD)©î�"oŸ‚Žê™¿¿ ŽÁL›ó}\ÙÖë.öŠ!ž¡‚±¡˜’ceÇ™ÙË|¨h­÷`hÞ »ùÙ kŒ%äqg)ó¦fèÌë"�S¥Öº¸EÍ%65q$އ%ä}3Hþ(b_?¤(~o9Tra7ìBµÞ«B¹˜ÒMÐÑæž,5©má›Ò ¯�âÂJÁñåX“h(ÓÎÚ'Ú8Y¬4 ‡¦U;h0M­ôBZÞ࢟¼®£‹‡!R ÞR¹ÊOµŒŠÇâéÓµé§;}¯‰#ï()À®v¾ÞÉ ÷“—„„¶/û…QPo 3vÝeš¢JDÌu"#ô©ÉøáTPM\6dvD†âæ2>Í!Põõ –½SgEP³4ÜÖ>9Ä\¾…Û$‡¥çìQ÷®Æ{„Á!|i÷aÊÆ6©0¢T‹a´Ù*ëaæ?§šôœz Œü@GŒûèf+1GH¯ŸMAOs™Ëö,óE¾±HãR?É~§…KǧïÝéÍ#ª^_¡b´0`‰ïk¬Ã—xàbx�ÖwÒmRO©Cù[M¸ÌjÐŽºóâ›�&é\â×åç'x¼2Sâ¬ÁCz�Àn~š³ï2gÃPoZa˜žë¦âHxÈŠV&O?xK$æÞ&àe^ˆÿ™}‘ ò\„çjçšD@¯zíÑà‘Ó¤$1')Œº½¥½>iö2ª›lY£U -#87&<ÄïˆÍÆ2ÁuWÒ ¿ñV¶©HÒšs¿ˆ As^*UÁ\q,¬´tzÙµ‘¦Á­ÌõÆ®ýÚÌè%]ÞsĆƒ”˜�!± Ý(3_¯"%<P¬W”mR´¬q%~G1/¥phß !„›™4IL?D‰ë÷*weN…EºÑÓÑr¢Ã¡&°%Gö PßøsP„uìá³>äAß§º*–8»ÓJ:5îJ‰3æÝ½Ôq½Ê-^ÍhÄ yÙz“ RPï­ä¾> s‰9¸ Æ%肈ƒÙsgMÏ“R¾¶æa¯dFõÄ µ€õV5h0(Xñ眇K�XÒ%ÑCj&ìäË}*å‰|.V�|þ¦w+KƒýZXííeRºG‹÷ùµŸê†=X\2†Ô´cÀæoÖMÄ ô6ÌV®ÇïžNúUG7¿A'o|\-ÙfžÙC…Ë'ùªådÒ²|´ tÓ<°²6'|gs^Å3PÐÜ[ŽW³ËÁ£¯À3‡'»üpWxè¦öÑY\(Üá;£®Õ~€w‡@ª¨NÑ[•;â~MöÂk7r¬×ý˜ SÝ߫Ʈ"Ùâ`q<.CCû4Ï?_µÞ~î…k a‘êfy˜NQAÇÜ)ÉúÅ[Ù—NûFÚèÎÖFhö8n{Uô«èë´çŽ›±¤ùt8¦@}äiô:y…ì#<’©G*V¬”°òŸzT~*Ä)ø&ÊéMx6áÖkì9añ#¿/;0öXé&Fl}„ ‘êîsÀ÷N*d„ºÌŽË]7½!X”žÅ`³Ò=~~œÆ½‰ûŒ²7õ‰Ysº¿Gþ¨ÑÆ=¬2™\c¦ • ×]\2]ã‚Á¹yòaéˆ[u[Ÿ“¶9´HǺ¯*œÇ̉tn5H0Pjïy—n‡¾z/Æ:±ãÌÕ³·dƒÞ"Hâ´FëãIÚÒ3â‘Gc#e›Öë•òSó™Î"HËŽƒ—lÍã1H56~ôz?„5¾ò¤QÓ–pb'¾W�¸"íú°Ü5³eQÎM±;´wŠ5¢Æ5<:ÏÍêµñ9ì²NÑ-¾Ñ¹Cy¡a`—pK´Z×î#|ú¦· Z%°Ìж£6—PO ˆNpGvL - è‘á;¦1:rW Üšnú g$§ÎWY‚"<ˆR^Íóx tnþZLÛó*x€‚Ï4±÷qñŒ_ÊÿX~ÅÎê•o˜À 2>Æ>‘gFy[UÄÐTäã"Úz¼ Œ¹/ä´ˆ†s_¯z[—l ªO§’Y´ÂD!µž(½s¶syïÕX;œÎ›(8Æ×¥iÆÃõމ” 7µGóÔêHŒb1¶-2/T=OüXª…„æƒ~Ö·Îbô˜ëÔ‹òõó|›xjˆ3÷¥^Ø—zå£&Be¯T–ü:Ÿð¹ŒO³x`—š´Iß«‡Æ6[cÒ‰;5•ïZ›W�$zé*½ß–eFv±ÐÙg¥rtÕ¢¬Ûµ[Í\Mï(ýìè­qÁUÙ©qÿç^+à.ã‘åü$Ïy±ËšÏçá•<FŠP¥Ò7G)§„ „Ýj£rTƒ>ï‘]Æ{·M„gŽQZviÛ„ËÞ¢U7Y¾i¬ÂI.£[ íÓšcX¬ì ²}Y@)0™ ýenç?œdu{»>î¢ q%,vB¤ä%—µÔ Æ!çÐ™Ž±“8è™ä]gìÛŽ÷¤eÙ,ÔÁÜh»'œÞcÓ8éÚÔ-¨v¹pl´K룱ä íPë7ðPÚ<tÃòµ»àã5£^B@¿R¤Þ÷xGžR_Öˆ’E âCo}”!Ù¿H5H/Ú(sI š¹LŽXú‘kì38#˜¼nbŠ$p·T¥¡èn…HA—G"ˆÖ¶t¨—^ËoÞ–à0›snô“é7vò€[Ÿ·-nxÜXj, :·ìoºÅ-åÁ­î=À´4Ù…säDY}2 ²„AAÀbq‘ˆ³OÁ™šjÈPžºÚhÇoò¯SbÓ1Àï]&‰÷ãÀݼ€;Ƈ’úŠ`/0�Ÿ%½jxHÝF3ÈäLåÁ&„è{,d…éš°l×åùž> 5°×R[—µ@bYx”cråëlˆn,ðäÆÙH@§¶e<ic]À|—‹¢Þéã^,%“è„i¼§Þ8rºTÒ Ç˜ì�Á¥¬$Vž_Iï=…÷Èç wÔ³ÍôÒ……Ö ÷v S6{ ‚‰æÚœ!à½ÜÁãUòÓç®±+½W’|CŒI‚^ÙÓ9Év9“)žì[WhœA"ý¤·{âV¦ \üd³lüD©T„RÞü'»5¦’ms4ócÏp8ÞŒ¾ÃeËVqòV9¡½gìjõˆ€^ÄHÏIn<.¯ØlŽƒ³PQÑ:ƒÕ^º,QõÙž·˜šå/)xX9dÒ$å ,Ô™ÉîdÜ%’ã9æeL5äÀBí¨"šÐÓ‘kDcÏãì m·izYVwÙ¬Ó÷8�̰fŽX3ÙüX^‰’É ëEùiÀMЬ€þD,1xr ZŠ]&‚ÌQ*3ݘ B¬âiô«Ãj8w'›ÔX ?ì›{D<EP,eìQ ÞU®- +ë2­­$84¹™N´Cfñð]‡Ë ã!4hK Uúâú2Þª{Ce:&Õà+\¨ˆj6¸<dFíuï5å&¨êËLßä-K世˜ˆå…5"$ª·\Ìõ¨•ƒ M×@Ù«l)fRC($1°gîò”WʦiÉ“ Yé ×"ª#ê|WxzƹҟÎq°‚»u–%Ö�]ÓátB÷ø‹bE [<¯nVÆlS6`*‹}lZ^†«úÔµ^:¿ 9+j9Æ´Jê“$u­‡Êm�:J6Õ(‚O^תïÜu:ÜE¤Ô¼öîåêl¶L˜7MEŒ©åîžó„z2¸5÷H¬¯ö¥ßTƒôöqè¦qn—Çï”åeð¨€F••ŸR¯å ­ʇô%>Õ¥¡ÕÁÆTµRާ|'h¦8"¾þ�hú §/©d™LähàÞì¾,Ú ÿUWÅ‚ÈÄe6E[‘]äŽY¤€˜´l6M øXâdt¼žÓ ‹E÷¿öYz‹Ö>TpÜuT0ÜyN'Uš}ÊÁÕQå¤×/:HÛ&Œ¡ž+ºZX/‘…Åè‚-šðyeð©áË+Ë:±YÚ}ÃT•ɬFÞ‚‡w .èªÖŠk“ ÆQ©“l‰Ïæ¦YϘùg†ª–bhˆèK+r/@t z).H€±êFè`—ædlVîÒBnð†Ænc=HÖÆçYäš ÀÐ,›]ñ°¬lFŒÔ]CR¼ÎÂaWWzKk‹åÛ un›,ºŠÑ9;ó^¬À‚WÛfÛ•2΢ö½cyžBîsª6RÖ1ÓzXoç¸å"àÐÏLJÎÙŽÈPÚ�6®¨Hª¢¼Þ{UÉ€Wk˜‹^w tfˆXÞ‰ sö°1í-ÞŒ7‰¶Tˆ•O5¼=”í»fòµF ñä7æÀb±Ö8.ÍSå}½DøPuÚ/WÕ»Ô-~Uè;=G}~`Pĉù4k®•]I¦±T…ÇåôÈ{V2¢<E‰ŽÎð|9ÍysX¶d×ÅŒå阎M=í±«ıÙgµ¬f ̈= ÃD¿Z»]a^ucUX®èzIÇ*ÈWyÁ%ŽgVTmUÂ#™JKê‡Gžó@¯Öê&Ôo%8[Þ<Hl)®yì­ª>g† mîŒùæ‰×+vbGpÓžǺ¤èf—èo}Iê½ú²à󵋳˜†ˆˆ»O]*©¥€@Ã{ôIö{+ ëʃšØvš´Ú8o\§CÉ-ÑAÚTÅÜÈtg:“ÓSTwŒéœGÊÇËCür3_¼ óÔ)lëÏØ~Múâ9·ç5^`¾ÿôS<žePFf- †ôžTr½Ú‹<C_aF¡‡ÌîT nñàÕ An–òôe§y·u[22ÃÓTô¡-l8Ȧ…ò f` ©b¿kÑrÈ+_ÒIWrXCÜÇqs¾,Yd4] M G´ÏE^ñ¥={/»ñx|m7CrSÆÐÉ:ÈÝAš»SÃHÃMx”Z( @éªú<ò�FÝ�24^ Rr$snïî*=¯ Ô¬3¡'¶Òašïm íè ЮD”œ^Þ:ËÙ÷4#LÍQâ½ÜµÂÚ|ˆ½V$Tmüιòixò-po0Ê™¬ÞM³š0<6r~MžWKRã‘Ã=’âIÛìÐìk]‚OP¢F]$çÍ$®âœZg"FÆ2Qt&ÇšžŒÎš_׳¦ÃÅ@4«uî2v¹mQruOF÷ŒÉW§³æ-4±,ÝÓʺíÏA¡"œjÍÄŠ[a:ëmžL¿ç¦ÀG±Å‡ªžW‚Åï±¼HÞµòlxV§9øøé8^¬L›‰ÇákŠ”n„³Y`))Çä‘s”§•U¡Ž-u»F­Fv-lá¬FÛPäf4U=<0Òk¥—ŸÃ©8Sw\¸È G†<"4S|OÑ`ÂßœÓ ÓÓëWž ÞÆS¯ÉC#'Æ×†^jªâšk™q<Ó‰OýüK¿>V箹‘®ÆÆ…û& €Ö–vA/bÞ[’URÖ•· ðê»0GV‘Äbr±W&Ï(‰û^JÜ*%¤4`Cßú£WŽWéq÷º§Sñ1è[|å·/c¯Ò&´UõþóO…{1´ðÁ5ñŽò¼\ï4<Ž×SõèÈð)ä«!ë;5BÊ~UXè@|‚Ž®Ùý€çDðHŸä3—á1??ÊÇÍ.XVz ðGܱ9ª·3U<ˆßòùÁ…›*Å󜌖-Z}`4å¨&•²¦ÀL¥WËã¾—u¢”À»½Z¼Ï%hZU·;ô¡$¶6v -‚+u¤Þ"àö(_[ö¼Å±½ís¬|¦Nk}û`•Øe4ž'#±Ì 6Î6Ôá‘=°Ã¶<I›¾Å}$:¯®*lÒ0öè•ôØSz5VŠøVö×… y’Z=¤xpø á0¬/Cw¸×PÔ³[µ›*ä…eÎ<Üx>b¨kê*÷F¼°ú–Ä[x<·”5J$/h;­!Æ›[Eª˜©¨cPdHBá8鹾Ћœ’¹ŠÜ3­^j"ÙÛx®ÜÝOžUé´>-Ù4½ÔH›ë5–=gxÔUY­™©œ{Ú%C‘†<�*;É¡RûÖ$šš½/ãÞ Á¥zo¶Œ×(ãn[cP™¢ç Ðõ>�°cÄèÓ‹g‰'×Oú£‡ ”Vwäc°§’%<ç� ýÊèÜUŸäF‹TÀh_G@g ^óFõÀ9ÈëÄÜBޏÌk»î3+: ¾ eòˆîÅL_'Ú O{ÍñHàÍmxX\ÌE/“§T$N.šbåS.E™}ùÇöå<ºb½D­œGÔ€+ ÁqÖ×¢]ì°kn]ºë`YQ£ºÆ’…i”¡Ý`zxgJ=úÍQÙ»fŠ3,LÁíô—Ìí§:)W•£}T¤ôÊ7œ«“.gû)ñbÁ°È¬¦ „ÁÚ›ŸU€8¾Mº5÷$d*ïvDVÇÜ Þ‰2wÎ@\{ß4kPhl@¨!×8ø‹W·§ÈpuÝxý¨Ô'¸Z’ÉQG·äâUCJ¦úÓL*ÛÅÅê¢0…‡Î™Ê¹ŽAÛ–«/&rðÑ=:M }•—²af·†X þèiÂÉØˆ_ø¸Ap[G æé<ŠBì`pe±ñgÑ(XŽ·‡ïƵ㱃8‰së‰×&5mÀîÑ–x”…[z`5Åî[ aV]!â&A¡×óÒãu¨1ñBÁd‰+ã‡u7Y>ˆLN€–‡÷Ö—Ìá%”8D5°V®Ûɳ{w @Uû–¡¤Á `Òá¨l¨ŒF8O"1°ìã W)ÑjÚ«ªGNOxZC¨ŽMˆ0ñ‹­MIS‹xà ©M¹7–Òk·!M Öž b:G$d±Œp8.3ü¶WvÅ€-ïrøùcÆ,«Â®Ìz r•!ïÚĵøašË¾Åî““¡G¨žl¥¢¸âZÜL>UJýL£ß¢±‚¨¿0©kPÅ-nÞ[M Ä~ ^ñòÎFÖ¾ˆ Q]ìÕfsÝÛÌí®£ÂgpKZÙ+Ò—¶XÚäÓ ð&l¨ìrù½^©ì×k’ñòÌw¹™ÞJít?¥É)b¯T^h çËs ^p‡Öý% È—€ÏvûB-•Lâü=%G±Yæ9’èq€%t†3Ý€ƒ#íŒ1¸Y&†í´gpˆýŽÌg+ Œq7ƒ ïô‚oT]-…¾ØñjNkÚ’´"[ö±Ö«£‘ÜMy~tdÿhA—Áøõ*GF:¨ÓùÆ.$F6iÊ2ZJv]‹²Ì+›R­šM~GJ¶Ú o 9l)¯LÙI‹9 Ý`™Ÿ‹€`ÜKu ívä8¬êšŽ0ÊcuöŽÊ­,oÌ(šVGT™©2ANHûpÕ’(ºúbÁ_`[˜lE<4Q mŠà¡´l!¡ÁoÊ•©¿à+?Vníä†h‰`£Á™’'A^·KoÎò¼6·Èdg ¦$²u‘Ôð)ÖpV v¤ãYk3GfÜ#³.Iò]²£Ð‡ùN:ŠâImAfŽ MËÆÞ½·ƒluNš. ‚ x Uþnì:™h%¥dW¡_¾na&á@ó¨ÁÈI•pZà¤$CHˆxÖÐ|6¶ÐÉâˆ0>­“©íBž­ÛAù"r6ñ&aŠuÝòãb¤1TœêXl½�xÃ/¢I¦%ÁCŸ>°¹7 [4PYúß‚”9^‘„èq%ϼÃ@‡ª&& 0rU.�ž/6[a¼Nó*}ápõœ•T9üŒ< C ô¡#Âu—:9zÚà“—ŒN4¥ÚRV‡šð¬ÞKøãv_·¾�êIHϡݵS5V·yúÖeE«�›áAˆËø\Ñ„—é¹ _ñ!PSë@yêªéF,¼{(¸¬TS æ€Phðe Ò§9 e¼†MGÏ×B$5iœÂq€èœ#ÛDØ_]v€›)€kSO«ëmÊ«Z¥1M*Š|Óü@�÷t f`/–*àrƒ1 ¥¼UM „¸÷Êé0e  KxÊ?ùOAz öôôdêÙ°Ðæº÷¹Zñƒp¢÷–$ñBnA“™ê„âëJ{3ËTi)ÉDÃ/GRv/ –n9Õ\ðÕ>¦Ó&U8óRM›äØOÀµ[T±Yk`ÉŒ1|d×Íçé®nW¡Ì«44 ¦‚»v>zëhó–…­‰]óeù[é}ê©éœrcìŒcç¾²ƒ=¤oGJÐo±JÂd°×{²wV(RùÀ¶ÞHË’W»¹‹t[[ðFX–,†¾U=9&—J8G}³|ؾ°âO¦dMWI8œêF_Æ>ôZp–Œæ¸–e,ø82Œ3Ä'S&ŠQe#n& ¯4U˜†½Üp!›p† ’ˆ¿±Í ôDP¹à„siÄ:Á7 ˜¯ R=�UgVñP7±+;Q¬™©zQ‰…{•>{úÓEøí+£) \(¡²sD„cmën*»Iùç¸jlÒ[ŒçÅ#¢}4ë+ÒÞvt["ËCŒðËGæñ-µUÇ<j Àº¸Ž÷Ÿ§¸>š~„þÌVù0-Céô¡±âš?UÊ£ËJ‹HY^he×q˜f{70ðH}F#­R‡îr RZœ„_H wö\£ �öDB¼Œn}ÃÈ�¶P¢9/БÊxÓ»�b=b®ûÕ\œú±›5sî{Sñ=‚f™Ü½Tz&ø¥ Á—‚‹w—ádÝëåVýè…¬x‹õ?ä{NÛ;¸üœ,êÕR½:E~Ad˜‹ëDµæz´/ͤújÙoݘdùn1Ü«5û4RýÁ‹Ô—P“`°®¥§e÷ž(…qLt¯ÔüçàœÝøÉ>s`,è%mŒ8 m PÞt¨·Å`ë@ísÄ]„Ü—`ÍÏ’ E„yˆ·’EÚ{`DJ¯ý0AøAWw=æÔ!/`íœT£¸n`:Ñ)ê¿bÁl*hm‹h£ÊREU†ˆõ$Tô¼s€ö¡™}ÍpkÂÚû¨Ë0¼ÁÂfÇ _—sx6)½C)ÎYº³}ö|¾ñ[ZÞÁY͹„zÍ$L°dDL‰2œ$úêÀ_m“,«ÍçÊlAÝ ÞȪ¸e#Ž žM(€ž·Ò¤=§¨×CàÕQž\ôVŸÖÕ½¥8ìgšÀÁUEÊ^Á¨ {x }z/–ÐFc÷N ;Äé©‹#ú&Û›g^Mô:è#"nïÈ—bèȬȅ¹§GQ=ô!^ƒãyá 0—9¬×‹-¸±‡ÂMAíãDÝhˆ¸‘E ›#PäöØÜJf[ÚK•–_XO çy‹ y¼g±9››Éf8¦t`=¦*‰ga§gÔ7ª1X 0´vhæÊâké-(—Ãðjy¡êä˜{’…i�;¼ ÎfÕi²^¡ÞŒíÓlÎ~7ð¢0˜Çe±b.¦ÚAJwú�¡vâ^´è.><©~4èû|Ç&ÆW ó=%:[Žj&x×p ƒÅ±ëlü0Ù>ô/-.²*M5hpJ¦Wi*+ À¯A0Ø€^ЮL&óh€£ú+ˆª•(‰'"(ºÓ‰VT½xz~Ô´/úéÐJ:ÜrœqU^ ðÄ’ws¹-ÈrHFÇ:˜Öp»^ÆA?4€ÿ$äö@؉3:QS/m^™÷âéŠöB‹*rÐÛŒ Äâ”iØMöö47ÏXÈ#¸°ÊvæÆÉ{8P·Y'XÞd ˆz>Û!ó(»´µ#«°ùÑy½µO°Ý`Q¹vfó¶ul­a›xÜ©:朚B™ -¬{ºG§A· ‚ÒàH è«=¶’i.­g•³²ÄS`¢ÖF5ßz“™±“¸„N1_Hv¿}+‘/ •m¼¥a‰M=צⲘ;DÛV|Ç ZÌäùs "˜ŒT5Ò44ÊÎ}�½u¹Â1ézÔådÝî(!pÔGº,Oe|xVÄop0‹½ª©Pß«ÂjŽÉWõÖøž·žpúÓzUˆ°0zo$;Ɔ™ é=O0¶ŸÃæ’í–[o^ECˆP³®YVÁJƒ´"Ù;8v¤ÔÚõE7å /+u}¬#ô\Ϧ´V!²˜À`Ceâ]{Y ¹Bl†¯œ M1Q,¼ÅÝIs)y¨jéÍrÓ žÏñªSŸ\z`“+)v Œ Å3ó®B)ÜÉâËuZ}ýÄ‘HÛPkj¤'Õ²Ž1Æ6ï{M>s®”žyþø…àt¶\‹.¿¨1EÚ,”–ãÑ'žÜ'ú_Ð0Ê9žfïØKÈÈ2a>&PcZ½GHTÆÙxTÝ“Q#×úbm¦‘ÎuÝcyõ%á³/ Ù!Y©SsçÒ£ ßhΧSÇåö¤.‹¢tê5árÍz0mmH”Fõ…½Í”‰ç¯ M:µ¾ >’-(ë­]Õåó¨(EðDæˆ,”&udGZB'ãIüû:TÃÂ1?Ì«`ïÕ›ÐU«€!' úŠKáÀ7=„mU*;R7Dk°«³¯ Æp•c°x=,±…¬ñRÀKm˜èkÖå±Çïe‘ãCzéJ“b| 6´7C hJx士(©²Pˆ¡;ðe8ߊP”¼³ƒë–LMY\&ê{’1yÃ0Œ<Ôp±5˜.æÉ�‡´ÖÓ°ñ°êÕ>Òà~SävbÏ#*’x‡—ˆj Iº¢å–ò²Q_Ÿã„Vè!XÌ3ˆ06Âfó¼áÝ<—Äw(¹;“Û4¥uwÕÍ‘3)ôù{Š�”ód¦—¦‹^>´} 'Í˶’«Z Ò¿™ÒÃgÕ2Çå.7ÒM›cà h;IKÄ4çîÉ9ƒÔ³0.m #\ÔžH½wé`UUa)o‡”1hÄJÞ8ùîTLCûè³ÇºþÀÉÎ)æÙ©w¾ãt¸ÎMìl¬fOcŽfxG<MºLŒBˆ×n¯à &ÕåêNSi›KdÚQ|Å¥tÀ¢ž§¾·Ý øn§j£‘K¡84­[…(J­dž&Šºç3}äïI7± N‹¬É>í#~ÌÐ<$D={Ú…óŸà$ÃqL°Î»×cÉ(1@3`x®L<¶�*SC³üZ½Þ{Àªå*7l×8û¨÷˜!ž5]Úõc±¨‡åp:QÚ9�ÞìO,Uôyó`è—….Ÿ[áxÛŠD5²±¢>‰&ñÆ×ƒâõõ%5¿:‹Mç’±JoØ¥‡Øä»ˆz ¡aJÐ+l�R@VÖx‚*ZØ T»êÑ(øÁ =KT TXn>• 6ã•!ØÙfrYR59# ÕRúOC¡Ô@íÆ©lµ»'N:%NyåO)wFËOnE‹ û)>µó´Û(Ä|¸»$˜¦†·&0SJú€E®†xSu"©…®/»ô'ÉA•ƒ -Œ|�ÕDvDaýüáK ÀÑ$¼‰s6�•KŠNÆÙZsµëŽs£*Í/ ñžâµÏë)¸Œ6´9 |!mCÖ‰ž¢.ï6Ÿ¾Ñ7Qcuƒ«½)d Ùí¤4§ìn->€þ@¥æƒ#im´õA:5¤©ríê"¼]ÆÖƒô R¥(¹»‘GÝâ4÷¬l2W…ið5ÉS©zÖó‚‘{PŒ q¨XüM`“¦¼œ±ÅÙË×6Ô´ŒÆv;©ïŦ5áù¼çýë¥Þê‰Z=™ï·=ëwQd*`$•EÆ(¢Lò2D IÎÖ¼+°œä-¬&X›­¨ãCš®t, ¸J–ö5Œöã½á*‹î¶æA—PϨSï55‡c|¨üXÉZ!öÎgŽŸ' ½EqrˆNät–+N,�b<+‹t%¾G{ê€ )Ž…ùÄ=ÛªÐTE¼r=µX97i†5Û§K`Z×›IS"@ jÞ—­sîÃk4T2!iuÏî^„l陀3¶KÜsÅä}“;ìf~ƒ*^Ìœ€jŽ…Ó™�‹B±mu{FP`>“ó¥aЧ†{]'ŠS PÑ{Ðü$†wcûÕ(@Î ô´éìTUN¹kj¡SBÀ?'%Àe`rÏÇìB—o5¢¡eáù¶öK‘ðl`Ú8ôG‰¤—øzIy=XWšû!9‘P×C+îÆÿ<¬ÉàÍ›Y¢ŠC/BÖ{y©Îí•×\FÝf¯åtõŒd›°a‚dùº>fmThš—MMGc0&rŸAƒÓ{:*í»- B8ÊV˜!©“:<¡ø òÖÝ‹ ƒÍ+¢èN© aëèÀL“q›uó’Û\[.w J×¥švêÑV óv=¡(ð¤5\¼Ì†5°m1Ú|Ey®a›¹ ¤+\"÷ éI]>2ŒŠÍY:kQ7.à½g葎µ)¯º•pÚØØ$`xš rkù‚ݱÇqBß«“лgQ¦½`T¥÷Áí8Þpî¨)) ‰§"g¡5¾—³Œ ©/œ¹ùN/¦aÌ›;ˆX*fKrü TÙ="„ÅÖD{æ¤yñŸ¾.˜Å·’ô°=rw·V) B)Êb#•1Ë#/yà¦Õiƒxõˆ‚¸ž¦4"¾ªí£E”ZõÎ6ðÆÙl»dnSŸG¢r­ÍÏ%<8cÔt\ØöWû\D ‹i—4®»Û«,2¥Q\‡I!<”°xŽ„ß<È÷¦ß½ç KsÅ9•YílúÆ�å1úCq{‰•\Óå¬R'‡éQ§â •€Õ ¼záþA]¹Ê„5Ë€s:y½yôP7Þ6½›T\Yëz,@y9àöœð­XÁ9xè�_ s+#£‘4�á¸y28©<]¨aPJ B?é!®pB)«ÍlÂv‡—ÔÌç\#TÔÖ;ÇD2ºƒÛÏEDŽhÁS5S]…JI ¨‡GGÏ^Þ>l'FD’|1±Êû\lºJzÿqe’ƒ*ëù ·?y­nÀÊꊻϨy"KŠëm)”<v!nI©…”1»·è6�n'3pŒÙ½¸Âóëëc´\ã–}ƒ¤0±Ï/dèÙžhsûž$¿l „ýÐðè`ïðV}Ëf1×ü8P¯ŽDÞñ=jT—·¥º@aõÝq¡]Ñ#´æÝÓæÌhÄàã{%¯¢‘9¢OyñT_O£·NIZ¿}1óÐÍ¥Çy„—7sÐô–ì’@êÅkcV já}û"VÓõeï2švD’€õÉLnƒA÷[ŒnIrGÓ·êŽ^‰Á+í刼ùŠ+ƒ!kÔó…éIâ³ÝD‘W‚Ož…\±½§—1èá!qÞ¥! È]ûìg˼š×Ú8¤˜Dcã÷ìá¼'øDƒÍÔ±Uýi«fnn6†¸û³]=:>Hx�¦�¼çݨ˜e%6êoî<²}§ÙEkHÃØ_ª9i°-ÞÞ>XJ唯(]Ñ<ËÁcÚ]ä(É÷'³G:_k'<*㸲ÜeÕ™‘Ûf=ä~²N´zÔÄ©´EMKe„`ZS‡±‡ÆÖéÈK7&¤¿hÂŽ•˜§®Ÿ® ºÍk¿eV1-vO8—;kIqF¯d7èÕ£ Æ|Ì•õ˜®ÏU±d‡<ù†gP†jôˆ_Öu¸lWû§ˆþ%búã…¶×i@VfÎ�~/Ó˜d$^¨ÂFõ‚I'.^ÅK†ByIr|fÖæ!‹ïìì£Á·DÊÍ2¸Íeò¦zÎ_œl¹c‹3Ô äç€[tS1ZÛØBÞ›“¹wÏVzŠ*çDÍõþ31‹ÒÌ^3 ¯ú”Ž.:…ˆ¨ ^Òe^ošZIGǤBľŠÈ‚jìwÏ©Ûk†šZ""â\H„Ò„yBQ+§+6 6z¬)àÃ=R «5ƒ¨†ÓÔÍwØ™®Q «±cobòåЈl²UŸŸxf=mÜ<hJOÁeÆ÷›;Ü  =gˆ2¬+›T(Kç»VÚùøæé’cs¢(C´”ÙC_P_|øLbêä¹­—sc¤öÀ­½2_¾%…0£ óB"’³Yñçý ä Äê•Ú¥“dؾˆîk3ä"Ÿ{Ï_Ú„=P ó7΢wxèo¶(¢ÍN˺znÑ5dF‰ÉO‡ õŒÃ/šËòd¥0HúèšáÂJÔ-V`%QÞ„¤Ô-wIw§E±<“÷êEéÃk½@TŠEÅæºÜTÛ¹7+¼ÚËu\CjB{FO`7/•»„Õz4|£O€9zÍn¹k¯YK#`MhtIŸ7¤˜‚æIèH¯¹écnÌzZuø«Ã²@äíÂ1ßÔ:¤àºÁ8�YÒ@ó5Ñ“ŽÄZjx­OœŠ—éW%´.á¢4†ªÅN§Ÿïs4/Uê•±ëØ»†ËÔ®„¾2Ë…çkÓ>E¢ÑHïâAñ‹õ—d¯9!uÑ•&Z¯/qt4¯b†m¿÷Øp@a$á=Âiñ2®dTçí/ѾL°ÀW&Ós84þÚÓðq™œ©?4_‡Ët8§q9\5\Fš¸ê5:Ž´+y¶€¤GVݳF(µ¦ ­ ιaí×ÏBLÙtd7ànG™ƒÛѦŸg½rÄMÏ –ÑŽ2jƒ”÷þ};Á“}#*À#<p½Ï›³—j 0ùgÑÒ"vËÁ>®†ÌÙÜ.í¥!Ú73ènQ}sQÒ—Ñs§37«\ cZºC Xε^±ê¦j®éÃÜœ,q«ñH$…9CŠdúÚ'òù1ñ‹¯š“óŸi“¯ûž\ËzsÃc‰Y'‡‰m'Šä®M½-¨ò#5¤·ƒ—ø/ tn3êˆ�¸7+ñÄh-’0î¯_¼§§]¨|†$ß–væ“æ'÷º§g¶dGÅ#"B¸”`p÷ŽÌ=°eëç-\æâ]ð'ûat]Yž§ÊNÆ\Nh‘ïÙQ,5EŸèc| XÅ’=¾,mïļOðQÔ.+“3Êë•UCwÕ#¶á”-[`'0”ÔY(Ðb|$¶Ø{ždý™h0ÒŒ˜y¯€¯G_.Ùó6Ž"£4“׆½:;€Š¡Øo /q¹jÐÁ !yˆ²2ÜYÓÜæØrMÙ†Ða–¦Wj±hž¤‹“(ÔaÅÉe *èéã8“yí]Þšœtn‚†%¡"šxf¾é¶Ð¤ƒ5Ð —&Œ-#µ;qÊeè�^<½^₆é“Ô&4ôÜ�»ÇážG½ºÎ:³§c·*àæôîÒ÷Õp2s¼NòpB™Õdôlæ]ì†]¸AK7GíWá›àm<Ľ›ïÍ—Š$_*rÇ£VêânI™#ïxGsˆ½àQŽ*fµînLÂ[ŒÞ”S˜‚¯ AÁ5\Æ«(ìÒJbôÕ'ƒs„OòPÜ%*£èDl bŽz™U#B_ù¶ƒ?›HpÍ—€W­aXuzÖ©>:Yì9õŸ‹ž ÐLšƒ/»*ìFpýÉæ$ viÌ ³éA# ź/T‚z\±v²xñu‘Z^^¿ÂÁ|"ÚÄŽöŽI“ ñ^ëR½ öÔ^ë{ÞQ¡ãçBÛÉÙH;¡² í{l4 Þ‡x}òš%yÔŽŠrÑ=ÑçVØêµ6þ˜qÉáA“H�”Í, q‘*ª]5ˆ>ÕÅÒ@b ƒÅ¹Téìš㻙Ã~™Ù²åb‰^B©d€¾Ù ‚3H�-h$}ÁGG6¥ƒ ü ÊšÛù´¡�Y¢U}V]±cÖP{Ë\’;ÚŒC~xOJ"m°[‡/jqßnѹ1m*;>2O½ Ô“‰Å³=sr!è`{…ÒToÝí„Z8pácÜŽ2¢thŸ[ý©@CôäK»X.”NF¯ñf—çønȓξ´íHª+Ñ=s`W5ÏìVô§Z/©eGàèÙ’Ö¢È;DÆ“ÔV9®)‡‘µEfGpR,§®•áC§ã£âpΪw¤%Ùž¼tÜÅ·ºQeöM¥¦8AÛ{—3] T–öò` ¨gµ2œûÕ±¶×Îa ¢0CŽ¿GmkŽ—`EOëî‘0N"Hæªh±É1ÛS!qË£îkó°iêÞb‡q²3ÓXÖ‰( #‚׋L_..ësØŠ‘#ýž²ŽÌ”9÷1ï±½‡Êôú¤%Õw¢kzFÜÎ,Î=F%2ØäÒ)SÉT¶agVèô–¤[Z^;ÙT+¾ òc^¾JWQ3Øs®ðgÙ—”þ’T ùµ- $¡.‚… »ø2–‰ð-%pH½ O%ëµÆGšÀ'?í*èåÈ59ã‰A§mAhÔ´N@¿Åå™¶®©ò3œ ¬×-aÀ„f•%)lUkÄ0˜¶óÝ£ì=z̾il§’w«1JƒC–•žäOJÇè[\‹>‹d&îxîù²ÈÍÃPŒ¨vx. ^;™a I‘«ìI²Ìòd·Ó¥;:L)à } ·óöˆ3dby¯.yͪqG¤…lèíÈMBIUe(L?0™%¶Xtß„BȲl´p–*lOÂ~9ïÀbØc…±Ñ‹â³¶® oEÅÕ+8ÞÞ~/w1Æ9;GÄ%~Í~“$±ËîO%œàõÍää.¯Îõ~PâN¯‰è¹Ù²ì^Óô3ášdHN»­Ò­WáÆ}ðÎnŽ wüY´o³ i ›ín’e‘× ï»i/¹g”ÔÙ`ƒ°˜Þ¶ËZ“&m÷°ÈžnJA!RÙ"èœ ¿q>^ÕÉ©8•ö4_êgÙª™W˜LŒMïåÒ«£'4àw;>Çá­mPCé1”‡ Å×—#öBJhrâ={'¯Þ‰ÐÈœ¤Ì£ÕÜÎW”ü<â.¹g'PžL"Øu‡ù¸ o²@u8³H•ú‘ÈŽ=ÕlªX+€.Œ‹¼Ýbd]à'½Ü“"Ëh› e‹ü%£À—Œ&Û@Ø¡® x·6ŒU #Ò/Ê"xÙs4ž’'!/AٞƠ: å Ÿ¶BfÐ)d±­¾¸£ÉªçTJÁ&“"~¬žáŒ$°Áh9¼e^)ÜÜfÔù…÷1ñ † ?­ ÙÒ76дӲÏÇþµupº%Š´h{Ô~¾Øcê¾P½¾ªÁ<)–:Q}9x¤ê5–éæU˜¼iÖqe‘ŠÙÖæç3 BôîIßÚe;ä"ŠM5 éíâ¼ÜÇ KC-K8îÕî/¢CÖ±ÉKaS5Êž$èê~sÓÚ6›>3E ¤,f+K¨lpfèì7C N¶’ÌêƒW,‚0¢çûœ÷]×ÅËè4_ß5j/£7«Õ2wã¹ÔîðÎagô)pF¤°âã$˜F˜ãµš4*E_õ Y5Óð€C|R\o^8Yàð]Z„8;¡¡¡Ë¢Á¿F<Ä÷¢gKnÆÕëññœèžpµãÂæ¨KDL‚ÜÃM ”óñ\|³àÖsÍxÝ%^Jþ¯Î§¯B¶ùo†NIÚ°7޼v€ëâs´ek·±âÕ±*ÆfÒ~ Ó)ánï„íྲྀ‡X6]i³mŒ~•å¹uZÅÊßÄåD:Gï‰IÔ´D9Ùr›É˜i(1§í†CYÔ¦?áÇD“8cÄšOÐ8Ì"$šÕäÙ8•[¼ÄR„:Á6uM}koG�{x?e<,™}º®`SàtÅEbƒ„îNŽ¡6^çøöйWéI¼ôC1 ±¨W‰':Ï:R€È3xì9[×ë[:ÒÔSkB%—|D’/ãÓ·þe£†Je)RÓ³Ò‰£0t�2’œgä Vªº›ÎNjÄ$}¢t•’„ ³¼h:ˆÎ˜ô`¢+^¯7 S†Â<4€*é$ó¾ð “°‚4ÃHMoã)O0–¹¶~Û¾ `e-j‡EЃ±Ï1@T²Ýá?_ö°> †ó‡ÝÌîö<± i,5 çZ¨0@È’E¢>W Òi—LHý®Ð [ûI#Šûðˆ ¬cÁPÔcQH°içD<Z*¤Åg ÖW¦Á‡©J &%‹ú,çåë# …ò ؼ�”7"{hÀ8“:Oš5É¢$ç$ÍX](àM¾÷ ¤Qøž±ÖžZc§ÃìâôÉuBwÂé·FO»ÎdœDùžI‰zö–;:±HÈ=|§$З3ŇؘTdqpÏ*¦ÚwLøŠëuœ§ ¤(7n»f]¬ ¾Â•Ù˜6EÇ]&ÊÃ©Ž™4ˆîO©€‰¡ Dëð-lW'ù™V€&Í ­a¸_€ÛpKÐ>nØ;ΫæGøE™‹Øl^¼`^•á&̵Âr<Ѹ›W^ƒ[þèÆ¨*ô”]Ì<±.0åI]ÅcÖ©ñ–gx\lKÀĦ¤VÊrá'Å­P,ò|/É|c'¶ÂM@d¦wN’¶+Ö _ËJÖ¾.‰�En†ºÇÃñœm…(©{ˆ()€“W67£†šÇ$a»¸û5Tó¸½~AŒUÕÞ´#„´Ó^¤ Òú6’w½8w%Çò€Ðß#÷“ÄwK´„P?¾²Œ‡¯dÍßWR5¾°7ð@òÂR°ç´6ÚÊCæõ!9¯“ ¢òëF†gcÐó¥£~_`x₊ZMDªù#IÈ»€ócy'\@Ì~! ¼Ã´vÌfv§4)íXÓ ëÖ y#;M×^‚‚Mñ´ìàGa„t<žÈÈëå‰aS7` WäºD³!£XF™x"hö à Ê>Žy·upËÍÔø2Ñ=ÝœÿóñåÌ–wωÀO!/ÞÛ<?‹k ØÅW‡Ïp»‚û[*‹²CÅËÁ›E|ƒ–Ü‚» A”Ú¯â½`0Õ~Ú÷œ¥ð,†–91ñ¥x,´Nñ9§Ú޾çÃÆ0øt2ìæ•³ˆø-Tö¶JZ^œ«Ós¦}báþHâ³ Æó‹Ü²f°¼AŒÈÊíãl_R±ŠÇvÞ²ÑnáeOæ´Ïjûñ*Mg¼&G¨˜ó‰¨²6ÍWvF°¸²¦ìèѳÖÅŒ VõTËÉ4³šh‚×Xž5+rØj¹M›%h?É¥m›8øtP)çÐ/^P<˜åŠeð€qcG}¹Äî¡™oŸÍXŠÆèap?~%JÃdéÇQ¸åa˜¶r±iÄúê%{ qeŒ*™‰Æ“$)ûz›*œ55 8 \À„Rc ¯Bå(§ÕÚÙpï²Ì¶|D‹Xg{ø|q.<)^Jœ–‡%+[•&/¾ŒI,2ÛE¿³‘´ÕÈ3 «c`´›îzW§hîL'=„¦ñžâ!èì°ÎzÁHA©<UX2bXÅ(3ư°µ¬A‡;e”]t.zŽÇì7ÃËÁêª'í%@ˆ*›·ö$žF ärp*š=ÎxÐWQÔlÞÁ5ÅñË㉾€4^Í~žÒÜ%!_>Ú÷-†q½äbÁG‡(Ù¡V'²Fír[¹k8 /‹6í¡‹¬ªè«!=5¹ |—âk€Ö%Þx׸¸¢ô¤¸äñ‹HaîsLUEAÜFRàÕÌ·g‰Eoû%8ÀÔí‚Pп#ì_ Ÿ ÊcüOÈ{VÂÖ¤ u4Oæ�•ñíø4äªrRŸs¬`´ÁAÝò½PG UÌ ¬Y%XÅL1€º±jë&è5öp€Ÿ.ç9¨m¹S®`à9-1Ǩ‚*Y–Põ¨ )æó=zÒÕ/^yØ£N"éŠ Y6/6bö‘pt‚b÷ïGÊ¥ëýžmç&ó\³£–E²T9«ð-36™ºj7�Õ8 °™Ï­ô˜¡Úƒy)Š´̓ A³JhÉÀç•d�,€/(Ľv§,�ðLçSq šŒ‘êáÏAV…FP+a±IàUd¾rÑ>1XƒÈvך7ÆÑQÝa8ÖLv ¨äeòä•f…ꋇ›“¸µÙòîyqíÕ‘ƒr(‰G°ì;Úð7.òø‘ç;­d²zÏY-d™ìéŠqH£OÉÊébÖ€šy˜•á£%¦’Íâ~¼/¬ÙfÚÅ‚Fƒ™mcµ½’›ÄP¥†;ۥǠcó‘ÜFc½çܶh-X @8ÁO"=Ãb€rÀK³Ø5 út�}O@ç¢3«%�UàHnÕM–½}Äî@4£•r6ú,Ýü1={Di ÈXs«:Üë=ô³Ýˆ‹Mò…'Õëv,Y)]N‹J‘Ý´ «|bVQì7|ýÐ'’KýP8³Œâ} ùèKȧ¾É·ùØãñ”×¾Õˆª=Q ~<¶6=C7Ýõ:ÇÞQ=¦„� @º_èÒzvh”[Þç¯ðQç`�)ÏÒ½WxÐÊ´\zÑ4Œçg ˆšà/Ywewu™¥Ùb|W‡â,ÔQÇÍ&#æø^ü»E¶?è¾'/œÞâÀ/NvpÒÂ!$T¾”Ytå@zãÖ¦€0%(„¤Ãbz‡doSçÚ7 §d‚ùRý4u¡M,Ÿ¬Ö9< x=4òŒ 5€Êçh@2†T¹:C,lŠ’™¶ÕJ i¡kh_‘=‹„ÓEZvX–ÞeT+éÑKºU]‚)°q™*¸pæd69qT{ý$ß”ÏÓ3ƒ'ööv`<žåôëwdÊS•ž½:›9ç>ƒ5LÖbݯ#=tpÜGD)qíË©;k VDÙÑѲOC„Bêmú9R°` yL²-¤ñÑ[wÏ}"¶V#˜å{cÏJÁ\’‘ª’¡qª¹Å0o¼´a(ë³—•-îù¨2’Û™_ÈÈžB¥¥5mQ=S¬‡¥O(ÜŸCÏVç¡gy§¯æ9CìMéhǼv®=«™%#À÷2†hg°«G Ê‰Ž™H4—°©jc_B!Z)Ðdð˜Ê[Æg|rµ¨ð¦±+o üD‚8ld˜n΃m œFt÷œ—Ûx’êð]«¤$°TÏ;Io  Jœ|ûð÷ªwD—%^X¿„SßSf3CBtaç'v­W¶ôÂv×yýMÂÃw+ýîmü±½3b[6%éSR S»÷SIxŒ¿«œn{x/ ¯óës‹tø2R^ÛBS= q1 B7wƒ{5 3L¬ÎÓÏå"<ƒ{°SÚö\FpÚ±©Ž¥´v-ƒÝ^qM%€Rëi¬›¾@ovÚ÷p˜‰º½ W¹eyK¸W$œ.4¼Êyó’U¢çé3hÂ*Ôyê±nëó¬p£wèÿo‘ÉsDñ^¤¾ê^Ú–}m¤¸¡¾"ç£{l°Ej½º£àTÁ¡s´Í0›M»©dbÝ$ } åjJ¬ù^íH©«Á!â¥C„å(‚iZ†¾xÁ"MÖpÕá¤X&íY‰S«H’„i ûÀRAžOùqô ŽrÑ¡y†ØÆ‹Ü Kîͦ‡Ü$XŽÏ)ß!Óööòµ>†8;˜VÁôZ¸…òÉ6¡-L-Í ½Ý[/�¦‹J`ÞáµÚóé™.rïÕóÁ’©L­S¼y¤FÎý€|LKÂKêÐBɇÃ5/éu‹wÖZÍJj¦Xø©‘úâÓJl»Wkóv º´Z‚¬·aBRˆT嶇晙-’^rӕˆAh!F¶íù›YrÕ*¦­ôrß ?MÂA}Pë‰=D�±N†Å=v´®"œ–ù¬“%òµDŸž¼w ørÐ…£Õa*¯C6ìq<¦™œ§¸˜Ôë+sż ó%ðȉ8à ӷê~38£{„*<Ä> -m K6„ÓÝÞþœE6Ýý?"ôE,^^Ûî™"}²Æ¶%ÐIBWŒN[Ñ€o˜,YÇ]Ò½ÃË£™×M­¾™ÇBÄ»ÏJ·P^ÞSÂ:<§çôŠ_š¯æMó Ÿ”Ap¹£É ‹t€S"~ºÔO¥Ž�A9CïhrRíÉ}*éŸom HdÊ+òK“ä<&"ËÛDÁó&šujˆu¡¬ìNZ6Õ÷©J �‰0¡I§âºù½÷æ­dÔꉂ+w Œ«¸•»¾MÆÒýå®/é8ß³˜Í7Ù†ž9<oÝm6å�4Wr@WÁôþs2q�¹›Àji°Ù›¨¬S‚²y{f1¸i­²p-÷ãL«·žw©"¤o ×Êì½µî)Ûbõ„«Ž»ƒ©ó(\eQàç&ÈtùÊ ffFÓ½B¹×Y3=êÔ® ÈÌu\RxÐÝ­ád¥`¨+tšÅÙJ.€ùË•<NÔ¢—²â‘’ ˜k´Ä—€Ô·ìUX, ¡¥“ÝTâ¬ÔE¢­ –tg}Å$e³5iŠL„¯H¶p›ÔdIéI`)ylž’¨³.ŸŸØ‚z—ë€3ÏZ`â‚÷ØÚWúfz`A\ýÆ$üµYYååKp:¦QTWÚ`LvzAYr·øŠc<Ðû€º�ºpñ†©Ê h.Lž’¯Éœõ“rzÍó¦ŸöÆôª<ɱ#Vrè< óÃX U @Ûχ‚wb@ÌÖö,¢(fªÊÏ à=èX/@¦Q²ÕRœ ƒ\WÖ|lu„¹Ø|!�´PŽobÙX5 Æc‘e£PäÅÂÁÎ>UqÑÜ'=Á÷øò6=ª‰§ÂQÓ´ef-ä”s»—«š{+gKJ\VÏÍ[îÚÇÛ &³ +µ€…Èzg ¼¢ë`º'¨µ·—!žsBÓ{¢MïQûº°—"F<í„é¡^d#¥1 WáÊœ³ãD…ÚÝn¢o]áeæô[Þ%B–Gé¯ÃÉjÓ—“a_NªeDµ‰º“©Ú{.ø@àv÷Ô‹Í/Óäg¯W+ß>A×lµòîÈ­A»­‘žÔœB†‚;bŠnCÜB™l2OºXcîˆYæˆw›‚­”¯u‘ñ–Nî°nåMƒ¼|›YÍzÚTpÄ/ˆ1”™¨eÿ“rɇ­&È*ÖAo"úCßÎËî CzBx[3ÃHq²öùYq½Ý‡ {ìØ…TÎØý +ø™Þ³`{Ìù4Ö¯t¸ÚN¦kK³F áÐIViOá“Užà \d› gÜAýV“”Ë[\è@¹w�˜ôrõЖ¦€$­ÐŒÓÍ)²îÍÚQ6ö­†j_©Ëy›V0‹t´˜g\6¾ŸH‰J÷fg3å’~ê§2&¢ð½�å~K]šyžÓ]–ýˆ<è^ÔibƽÕ`é‡Ô;씌ÖâooaíP¬=Õh­œå– Ùh%ô6V»ýáÎв¡íôÙ{É$ˆCÉ\šîÃ9Ô�4vÁj�t€ÖžÌ‹JF‘@Fäè±VáÄqÐ ,·Ù^?hÜõ3.÷A§–x„[õDÞ™ÁšU5¤ös¥Açr°WÍÅq€Çäp<ðš¦õáhÛÀ=Íõí+Bܤ÷˜×¤­[®"øxc³’T„‰«`ëc„kÛˆ`Ýב:(²ðXº™Ê¦…ŠÅ^€ç{/·lB CÌ"ÎYB †åü:û5ÑRôv s‹¤¦1<GzÐØ(ˆDdJÐ[#/ßÕ�åˆSϒǾÉáL¬J(+*ºäçC6FQÒ+äÇO+—oSWÛ Äƒ|;"Ž›÷CÊ�ù’²ö²ô ‡Í;/{ K£¥^ÔØNPE²|R¹¼~ÕÃ6ueeu,+åΰ «˜­“ºÂ®´"mÆ Íºa>f˜¸y÷bªÊ8mÓuµ6wÓ·@’<Ô@cɘÑ ç Ö´^¶'j°ûh3½·DÜÎôNWKsÿµ’ׂ‹Ôµ™‚Ì:^m¢Áˆe¯f\ÊË�—ë›"šå6=á‡Õ›šzÍalI„GžËód‡XË­/ôx òÕpç‚­‹oiÄ4i÷â ºd®½UÛ8ÊʈU6žê·ÑÔÏÚßͼ…ew©x˜Å<iW¦ÝYc½”ÃÕø†sœ=<fãÖ‰D{áuÇ¥&™Œ–- B1˜eÊ[`¸~\«[IoœÇÔL�kóñ²uCœçój8¹y-E%û†íd¹›Ñí î¼|ÁvÅ£×§Hf‘g\q€+è¾ÃQˆBgúüž{)71p“¶ŠN/ðµå}þ€ƒN¯hýf͸XáBî¥Ò(bªu“9³ît„xÛ‚åN-.85<uãåi ‹Zmçì ÏÃ]Ñ~QIÆ™Ž´ˆçZ¯ª§Råž*ì©Á¥Ž·&%©ø¢B óåÞ&ñM³©.ã]^Ú»VÕG¯}€š¯xö5²°Ÿ1qyÔëxz­0µ¾7‚U½gl€wµœÅ‘ ',Ç<—ôÐSâÆ¾a߬P3UF9ÖaCâW›â»;­¤3»ž%udÈØWЦU½€Þ»É½,‘Þ弬è½~¬¼ïà@X¿³²ÂI’Ã$ãŽ÷xO/ârm¢¨ 0âðDŽÅ(Ö™ª(žðöœ|Y‰ôe¥¯:Š\¾s“çFÔ+ ýÄÉ C+…Ë/J#k;}‚Å}ò±ï `xÉ ]AÁƒG€,oAÁî0°6á„Êób&Ö ùs‹‘aö›=€:Á¸*�Æ9{x’üâ…šœ9ÍF› <—7“ š…&Ø@³)ã,áöÿüùqé“tÁvß#,K‚D�#e–“ÛÕ0Ë"417TÌŠÛ§NÉ@Ô„ÒƒˆÖ©•=§QfBªr£"5ÕqW[Š£‚>kWxµY°—Jy-´ÁÍãÞ³yreSSoR,#i®^5?És —ÅEȉ¯'’zžPhøØÅ|Áve­ê¡×^²cg-úF<¾ƒ7½…1óâKÏ´ÒÔH”¤Ý`"e›8HR@mCð³N‘ÕAÁAc;ƒÇjqÔûùLàíò3sX{B„˜±WOm/¦S@ŸdËåB¾yôæ…b#Ú‘©Å„ÍjNú.VßP 7³Ÿ‡¾Ù&–%>ML83ÞÚ®ðfE Yl¬ˆõªñÝ×J^hŠ¡¢÷ª£šQÛÝðæmYÅKÅÆ4^(°|\(=Ħì\"Iïó ÂõÉÄ¥;ú´â˜ L 4‚¬5;†ƒ“?5yÆÃu»DX—ÏàÃ7B(ÝKפϸ±H÷ì‘[Õ[‰§Á… ïÒrÞ³NY‚‘õœy¹'÷PWÛkÌ×ybô‰¼£Çׂ÷ R·nzÅ€ÉzO¤P×MçéÓèW„øÚÖ·¬ôqxEPÁÂãÆËæ'íõrÑZL²0Rt_Z޾zÊwBÃÊG,l £.ñî%ÒJó‹£µdV$ ›*¼h¤ÝdûÒ’às³Tm„Í…msi´A㣠À:²vZº!ʈ~8%y(3Ñï˜wRéæñ�¾n8šÚÇ2Îx0N0`£ç1Ù-®EÎûF^æ]�c"h—%PT>\[u{㚪Í>Ç{Þ¸¸‘Ïj ;³:-È¡9¢ñê%Ò å^ÿç%bëË—'ên¼@â¬GéV]ŽÏX¦zKùQù1ÜÜ4SzN-§×ØÈ{¾Éœ×`ü‹pu,çí&÷ó»<½d †à~áLj‰NŠFèÕÏ^?Ý"¤‚tQ�2\�'>!—jš¾kkʲ§IÒ}s0«gƒ›áá(l¿¡†n)[!UˆΖ2 ö{û@H¼ë޵ÉÛP¾Š‡qé™ÑŒqÝ¢+—OiŸ ]Ì¦× /£)sƒXËÑ>RI ÛÍ­é‘9Œlôò¹m ¼±•6ÂR‚[æÉ¦ñœ^ÖØ\ÝyE¡óâõu™JZ¿T­ÀC5u¥¸”3|~)§½Çü -òP¸_E9=~a=d}ãü(›ÑÅ�¶ºhzÁ2ß5¨æ+#zø¦|QõavNÈø$)\ù«„’w)ƒ)AÞ¾ëÓš=Ø~‘É~xÊ→ú ´CªGaÎa-hñ5r%«q^‰lüþg+û.Y9Þ\«ß¾£Éœžë§¶“§5É>¶¸å‰àÐÇ*GYïÅ/U÷3nÏ~Ü6Ž˜K¥¤´v³ýbiãÇÃÁ=Ž¥D‘uÙuð×ö8sŽ[¬e­q™ּ:ï¼qeSEe8í=_YT;ÂXtoøX­ „1ßiaY_>ˆÇ–¾g½‡%ª›O0ð n÷ˆ!1ÂÞz³�g,o¢)ôPÞ§—þå%ínZð©ëÉŽ»iU®¼´�Ïíy-+µ-³8Ð è|I€ ](©õæeÃÚ¼dÞ+Äêã%¹}z×3c­MK)=¢gÜa4€`¢ >lúP@Ò†JNä© Ë<‹ðuˆfÍDC}SHŒC]BF¢ONEÿÓ¸­ÄK6°NÙ¤/‰)—í¨Wè ¼{RÆ1Oànƒ" üjßV>P‘ fl®d–WP" ·lõ"˜%‹Ö#ó¦Nô1:Þe¿{!Oã![ÜK@÷Ãdó÷‚HÝðõSÂ>ÚŽ$8¾Á¢J‰=iA‚~†¥¯Ÿöz¾¢ wjµ6œ†åÎNè1¦uǘλ`6 _}Ühd14j QÛ;ú¢šbMÁqóB•ò?¾t “ð< Ø:Ÿ§¦œïa^··àÛƒµw’›Þ·{µðmõÙîyÚ2�»HDq„)!©»“ ž‡ªH¼:¹XêniFÝ—ÙM’ïe"'åÞšœ‘æÛSyqÓü„»Qù±„T#!”Ïhi/Ha@:‰šeäJÍõƒ;Ÿc Tò Üx“ôe^ëË}§woÅÄž"ÉÀsD–Mñ+ŽW¹âåJàõboM¨ž²!®ÏsJò~§8ŒO\aåÆ0…ÉĬãƒÁªWšŽXÍ 7`GpÀ½¨öº§Õíq¯iÈ#@ݵT}ãQ²Dû€QKà–D?« ;ó RÝ=2âUÆy<¨˜ï˜P jÆÑ¹3ï½mƸq+å¼Òâ&æÇû#tÈÆcnü´’ÂËã>ã©€wqfº”4Žœ~Á?Á2Poþ“íKÌÉBœ†yS ©®§ÖBŒOÕÈ•„\"Î,aÊäeѽž»TáÕ«GˆP&æVýÊÜ_*{ŽHƒÂá cµl{ÆQ‚<4'JöðØ•Ì,i<4,0\Ø—ì~ÀŠrFD‚ú*jOˆû=çz™íÃ0¦=X•>æÑ4ÿš)º0ó®7u1V§Úz€G½©²¥{¢ò ôÓ.·7iÛÓÑ[ø^V4ÓãöÍyå§Çe:Ïî2Wëm­)‹ðFD̨ôráBˆTáy±tyFìDßuÈÒuÙUÂ@»4u¾ÆšØm3‚]¡ìÑÖC'â Ê&‹b‚j `UhÕz¹ê ›[vöZŸòCÃ=ƒ]–Ërâlؽ$&éð¦ÜW çIÞ›Ô¤e?§ K·T°9܇o-/]«“I£Ÿß¾žõ;µÈwçÃÅX®õxe ¦Žm8‚¸+#œüÁÌ–Rve¼Îus_b`“Q㇚Éñ)Ÿ‘.y$f¨ù ÙMM¾*"qð¢#\Y‡¥C?Ù`* c+n, &e—âz)¶¡iÉÏE½ÜØT­À¼¸µx ‘.CÛ‚Õ7jp(o{M� rº)Úv›‡-Zp÷":ľÉ)­YAgñ \†iÓýM)Ê¢¢·UÅGj5­G‚_KPÑÁó gïÉžY&½G††)èN€a}kB-JbÕ)òrW.¼U=4Ale´dß …Œ¼jÓ·÷^(ÂCñBÓq9ëh‰ôÙEËGž6ú®¹Þ¤?R˜ª‡w‹yúF“ÑL:`”ªP‘‡é:(‘˜â…9Ê[`€¦ vãØ/3E¾ÌÚˆ¤sÈ]X�¤IÂrq‡%E Óð‘aƒ4Ã1l9ƒÆ1ézHjvhLçÃ^"”hB²®1ôæy¿Š¡GuÞ¬9•×ÛÍD%žI EÁa4®nJYÙ5ê^}ÖÕì>Á5Fta;*†Ò¤e™JO=6ó®ß̽ÿÔÜÃ(tŒl‚–ØÅc\¶reÃhß0˜ÄÔj7{ÒúŽT×!¢GôÑ@\jùkÖ®^'>Ò ÷PQä¥}7A©šOŠ,&çë‘…AÞ~íUÌDX$¹³) ~€EÈ0ê‹¡葨Y¼9w΢89·™ºÁ‰wèô޹ܕ¡Š"<£Šz¤jöž®m%ߊž? x´Äb@KDýÞÜx7„ÖãÁ"Æãƒ(¦íéz‚·£®=Ïx©�͈눃Œ1\ÊV†nU½Þá‹Çé§^k6óruV[K,@õ<ßiñv¯i¸îÔ­´Û°3¬ uÄŠì±fª–³XØ´b+ Œ¥gCtñ¨=‘0“­WVÍöZœºÈœ “%#AQìòä9ˆÌ^.ì!¨£3$6á=ÑAŠ×±'åO6�d¤Îíæ=('ÈÈÄÛBN¨™0“­ï¢¸¢ÒÞµãÒSÓÃc~žFБ¥Ç€¬±áø9À2]À,u¢Ã½ ºrp0¿¾ÌƒmlÙÄyF£…œeÞ«Wìt÷–4 £ß­÷à</yfÀg› ‚¶¸ôÒÞóqÙá÷Ú‹§È˜º ͧœúÌ»%Sä™8§^ØÕÎz6›U 8r•:àƒðŒ¢ÑÊ‹VFÅ{׊"çé±Í2É=“]ð"ørÞ‚§Œù,‹!¢%¨¿Çx2çȪ!PŸ›¦Ò—šÜQb¢ÐpÔ¹¾ìÄç5%ôÞ1Öé¥-| R3msÇ–÷NâÊ“˜ ›kÎ’6)r8UgM‡0rv¦Ÿ’òÒ xl”Ý ÐRópJ©ŒÁrÊc–æÈ­úK‹ÅF=šm¦<– >1|¶u Òò\Ä^?�y0ÐPí îí¨ŽöŸ›‰HbcŒù:Ž9 õØÈ2%4VÖ̀rÌ–ØN6§cý¥]•.ƒªÞ;q}8õ'Šœ=”tëNŸYÝÛ~Ifî} ›‰–ÄP#à‹øÔê`cšÉ4kGËÙ„É`î•z`Àóî8£¢A Ó'd¯oµeñ Â1+¶�î¢ñ ÇSR{ìÛ]Ïmë"kQ¯µP‹˜]ѪüZaÚbëF—ûúÕ }Øo:_Œ¾x ¢òì½bè™7 ñ8×tlŽ/´ÆÁúx¦4»®4g3ý™­a ͽŠå¥ˆ':†LÀú0t:å¥=^b•i`¼É„åI)³É˜{T àñ“ig,‡uxž“o=‰Ú‘E3}Ãìöcm¤r­Å츰\jšÔ¥ºæ!yƳ¶ö:Uö,ò '\#ky¥»àÊpG”áJÙˆÜj0³gÁx¶†¢Í«¤§kd±o®G_£¹K›caÍó‘TàŽj ymÚÍZ£´oiàÚ½¨ƒ:€¦žŽV6¥&wázU#"çÏ(`‚ž× ,VÔ±{kØ’òzê*ã£Ñcª!{%ó^>ë+P?µUì{¼ožvHŠ¥là«Ó§Noø½ÇG[šª$¹9ásN”owIÙ—ŠÞœîº«á{ZãFt<ƒ‘Ñöå¦Áç ×Tê½.T=í÷âašÌÅê°4YrçX¿³b€á˜- ±ÀœL­•J7 Èx&äÆ:ªdÇb÷¦¹F¦úyD¬)‹ úKÇ‹œMn=R©vR+@õS±ÇÓÄt¶¾um­Økos „&NßnKÝ¢EÞóâYñA~sräÿnœùÔây/V¿wÑ.‰ŠrüzÇU €Éç$ÅmÃÈúM„¦±ÃÞ¸°\jðËBo÷NqöŒµ6(~,žIݼh…ïv|$¡‚ë&ðç@>0÷Gñ20i±ØÕ”-Ýór&F åZ»£%­»«ä]<øÙPºig§ÎƒŒ«œùÀ1ìž„‰Ì r2¾wB„¤’ï:¨S;IpTÚWM)|¨ò® `*ë°°ú ”Š ô],ˆÔqMêô{@·Uïùà@Iq‡w¾¼!EÒ°­9 óÅ]í'•dɺ(NÏåŒ\F/ñuµ…*8õHÃ8ݪcðóYdTpPU°ò­²ªòÙ:Õ$/=d…=ÍCŸì‡ ´Ï@eóÈ—Ic×HÐ>],®• ±åj…°J ¥}…oêtÑ }÷Æ[»æ‚d,:xÈÏÎZµ7Á«æ’_Ÿ=K’Y§#öçjVâd‚¯ƒŒ‘R(¡:</q¼zÐ4cŒyû}ðpN¸ÂÁ—Ê9L•G¯·ôäÉ¢¥xP:_ÐË~+›Ô¶‡·–Vt;ÜÎÁ©?Þ¥ÔnP}E3ÔE–0 š‡èêó¡6 >£×Ïy¸‹ÛØf–E8ç&Çét‚ÈF"ï ž;…¦¼‚y–'ï]çmÊNÄ£o¢-S‹Jf– 7Wì‚‚¾¤Ê}ô)§ÉidgÞèi‘¦¨‘ÑbµÀ£ajáG“ͳïEùÏ£h!\8 ÕDë‡Ú¸KÔË[&Z^rd|f°É@Ž»5ÖÞœl\ËÛwÕB$_¾ˆ·8Ñ„FPÊVS£³¤wgÛ®ÌH²¬—)y6`põÑ\y$:4Ÿ±êþg§AÌ[:c}ˈñ8MtÍ8¨§e4½ã¼ˆ =ûq­c>ÑŠ¥rv”Tz÷|Ô1î‰I_ëªM,Ý I­Q�7íå]Gðj0¹<u‘—-6žØ½HÀ¬˜Àç¼aØŒ¶'»Þcѯ©`Y ®lFMÂÃxà*ÇyÎuʲ²¦ãž gCB‡ò†ºÜxÞ{AÆC·DÎçoÆ…G!Z—%ãÒ ¨*PŸòð=òÜ{ ,ð2`ZüP7éÑž<¯°7) Ô>rÀ~¨µ«€¡ gEÈ&ØtWB“ \¢âãt~pêÀj!D6SP³òF’ôÙkÓÁN •Ác>x;ànªÔÄäfa`ï²çø•Ž˜¦’%9hu¥ù;à ‚V.g1}± ÃH87«\œ°5‰½„ÜÏg¥'“['ÚFSÚ,µ”‰_¾ÕqXoœ’0µ%/šSh juH£]]»Gæ(¬•ù ¡ó†º!FÔXàQ€„É•ÈÂKóÅŒƒ5.—·ýte0p9püô¬¬CbÒ&Ú—ÚMļt)ê*: (z޳§*Ã#>#Czoû R ‚€„cxYs…ìõ>·Ñp:@‚‰,l˜‰MA`Êgk’úJå:1bmŠ>c¢š$oÊwîì½wþba>_ëÏ>íTL»â–rè׿m€hO× dK-ëôšA“lµÉ{N †Go_†sÖॆç[I}¯ó”¤•¶ñ¹Ëà *o~GüB;1F5FÄ: ­«§7 ^\"õî{u’…¥À­ÒDj9O‹7ÛntºÂ²S 8¥®d#/Ü{»Žr5^W@¼øó<0†±Âç/—ÈŸ*äìPSåtI—áf÷9 êhËÐ5áñMbç âYMtŒ­§½?Ïzôô=Ë÷D¸ û+ö*ÓõÅ­-�Ý>-‡›~œCÐ^p9¦×^½{]¤¢'¤nYþ¢ãN‰Ç²ïÁ‘D måÔ$½a4ϧÚ4×ÜlpËïµ'Æ¡˜ž¡¾¾{–8¯=í*A}Ôiôh1vÔÙ˜ eR-&¶R,h¡ c  € ê :ô^ú¥¨Aa=ÔG¯ $}ø Âd-å´v‰˜V] æ6nˆÕb+l§=;y›CøÆü¬üXÙÖ_Ü,Z²ê>t}(|oàu$Á;Ãò('V9H Ç¹È†Í{M)ZÛÌëiûÒmöVñ, v»Sá-sŸ¼Û$›·ö.ýW‰&Éøi«ËäS-î’n·î#"&îÖ™n à’W¹Vðj™lܬå=ÒNÝtQ)}˜Ïe/4€o‰-”,hP¡OpS:„¿Wà¦¸Æb*ÚF ²^ *°F§MZÙrlÀìuΠ깦da/ªœwµËÞ\>¾Ü IzÓ‘¢°¬m0Ñ'¬!èT·1§'á­4e¦GÛÓJ»oˆ›^¾xÀOÏ6y�ï8––¨ãE–úœÃÝÔÓR?‰üÒÓåKOÏ<xt½ž4aÕÅØ± ®´óBÖ8mSVKl"º>Gm؈ç8Ë9U*½ØoUѽ73Ã}4‹‰‚ýĪWQ…Kßö”4™Ñ#Ò|á³Èµ‹°·MO\&Š0Ù,eÆ‚5a& tô 8¤CÎ.Úýë'×c`ºjQ(©×Ödœ•Ž‘ÝEñê‘ô„¶*9\½“µT@Ç›±„0i£kņ+x!=\Ùc¡ NE�h‹µx~ã±ïeN“——cÙEÆUòì°µ ¤Wóº‚ÕmùÓ:qF!sRE±Ëzõœ Éænãõã—o´ví=%i)åè}]’e|•¨: È £›Žþ¸=E¯œ›¶1)±fF4³ª[Ml°!¶$ E9Ðæ‰ìb¤à#ዎpÒÐ€àŒ…ÕºC·~úòуe r|æ(‡oï2¹h‚n¬*µ§ïQ±êkº`¨×/6ÎôqÝ«+�„Ê™âòXƒx<Pç~M­E¥™X°#æï]™˜<²GH˜B‚!Ž# ©»�¸¸`ï,ß.nJ¹Ã�ÜsÔË0õœ˜1aäH~Å·Ubêš”Oja›Ê«·nüŒíÑQã²"®!¶½×T4Ö²Â/¨—D.vv2ß² êæyk&êŽXi@Sk¤è]˜>>/÷ó9zÌåÜBÐE€:µÝ¶€b¦¯'—û% Íêæyul ä»,¸äW$V†èÝjà¯àôñÕnÔ@K=P¤My.ã:žûtÁÏm$%Gšäu]ä½&¸Q¦4hF$±.}Ôï%kWG›Ö ܼMÁäӔ܃ZÀ–9Ë=À�|L¼ø(ÙðËÏ /?•/Ðo� `‚œ÷l:pv'a6z«IV@Sâ›Ô ~caîgê O9T×{˜n¼ÓvDÝGŠW¤‰Uç°•QMæ8ëSfM{Ž‹Ø£ ¡õxNÏ©=—s�ü½`ó0{¸!¯[i©(¦GŒ' ¡#(|’ˆJ“E¡ªaD|é_A«’墼Ü;\q±,ÝM0ÉV×B之ľ{ÞfÇ”YàN±ö ÄA=©Êr»�s¾Wj,ðêœií*=¬x¡9Ûé¼mÔ‡„’䩌ÉxÂú”�€n*…ï­ñ;¡x=R´âí/O²Ší™QÓ¾ñh骓=ˆlJ$z®£Ú‚ÒrVLžvÃòÃìe‘âÚÅGóxãRúnÐÁàÁ¾>ñzDÓÛðÔ¶p4ÖÅqöˆk.$zÉÅóK¢4˜`ôdçê¨1M™ÁjeÕ¢Z‹ êysô;…ë­ nù õs ÁÜ oÈÜg¤×þ:½ëàõLTØâ‘¬ói¼—ÔjèÆnä)½°�èÌ”£"µp`0Íh»|Þ ¥”‚h7Ë»±ÖïÚÞ]—"ñõrÑK›‡[þtÝÒ »ŠF,ŒùzáJ°òàèv.}ãáÓgvÏýÎÏK37÷„†nÓ=¨ ‚LJ¹Q;gBÁÆFgq‚ÆLÅI?írÑ·ÖÎÚrðôb¾žâ�ä«(¡™XH*7“Ú']ÂÙ9öºÌÝ6µ«}`»_^i5Ë¢Â6ÙÊØøèAk²Q’wøŽjB°ÎKâWE’‰>‚SJkQåä§Ióœ8ãyùžX. Ƀœ–ð"ƒ ¿ÇNUàÍ'ô@ólw>E�ø"4M4¢< K»·cíåÎÑhŸäÁmëׯò yE©Ë¥½ 8󥸪1d3[EóII´ãÐ{ÉÍÎT\ÈR×Ñ•:”pKJ'’mæ¸e#Ø8@N·c°õ‰ñpëQ•·åcÀ+Ñg™\z¨Š0å¡v÷ž<o²| Q›¯8¼¯ø”}ÿCtF®_Žà³× ç1œÉ!QóÔÌŸH…*±¥"¼>Ñœ+ŽÒˆ˜=Ü5…gDEE ífòRT0’„sNö]õ-Ñ»KŠÐJŽ›j­\t®çö@ÆqïðÜ»ËÕøI¦ÅÇ_Å«óõ/éݱn×gôrp/A´WAo÷?èKy^]’‚O™'ò¾´‰ˆâ”{‡ßþUß'm!×’y™ýº�ÒY/!ÄœO7¨, %YVNpvÖùÚ)VŽ[ï9?~i>×±™Ü½æ´<JÏíéàK‹+HG©{xMHóÐhÇáÁËLEéÑ2§ ­OϘ»Ü‹9"Ãkk[¢Ú‡áAy(d.”Þ”‘ï(9Xè¾t6ÓIâ­Ace{ñví1£Yž1áYã‡ÝÛQôÛìØM¼ðåxöÀ޶Ѕ!Ϥë¹'‰a=¶ ôg7âøkk‰zéëêÆAÑ¢zÏæ•ÖÀªÌ•ÝóöQ{Ç},,ØÁjµîoÚuCP h1¦@yÃÔ�{uÊÍ3vÖ)]á0ÅzUI —½PCïˆA%TNŒ3ôn1ù½á.œ¢C«Õï6A´‹Ìô 4(zu¬bó¹ (‘ñ0¶‚Û2UZëÜ[~d/ß#Mƒ[Êw4¡8Ó§šfY³˜fùnPÑ¢n÷1‡3xƒ¼Wð¨! ËY° ò8  §,ýÕ u.”J—®*¬µ²AÓú[ <Ý&ÙFqÕƒSky:jù®PðYp%î(Ýnè=Ý•Ħu$²«;;ãœU—@ì‡a/}ëA0Wóé V–6™È„¢ 7§7ªìŠ/¢× 5÷K˜JÍÖÂQ6È\­�ÓwÑE‰ 5Xƒ™g“ ¯Çô p¶‰ñfS®1�åãP˜Ã=œÜbá;wõw!šò 2|ÎÅ¥·}ÙÀÓû ª†œáå¹Ê»‚JÎJ¾ ¡ÅÀ1\J—Tñ”z¶€"õpÁp�WKÌ(¦Õu' -¬ìÚö¼ _•[ *½{ûd[RyZÊM»^ª„¡. `›ʬâ{ÖSl0–vò!‘•>´»qn0G.cìٳʦÒ‡.+•©…»å¸{p§þh¼ž/0³ÚÓ ]J»z7ü|˜€ŽÃt®’0ø.y2T¶DÄ­AeÞx5†È;:o½Q!V±;¸YCt‡~Rí2o´¹ÌðM÷‹=ݼ`¢{3nœ©B.ã«;LDG,¶ ú4JÌÉ8îÒ“ ú¡¼¦L0 #»zQ`;¨;Ñ©ò3‰72”tŠØSÑø>£½ lja%¥„á;šêþžîvÍòö#$”©—áØŽ#ȇSÄðÄ*uëzù¹?›óçšÓ ²±èÛOßs¶¸§h§„š4öZZž"Xúq>Œ:çåb„1¼œ©@,2*ác¼ŽåÔ‰'o·®ÝÑÎx9¼ã¬œpàâ±Äm7Mƒ^ Á­=>åð»uò®ˆâÝ­u|›eîÀÌ1>Ú.z,âïïzJÖy|™ßdWOë;··õ½‹¢}ï¢t­¡%¶Æl«|=×>ØOçádÇ<…4dbŒØÌ&w‚"½i…6ôŒ1PK ãžð$-CBTMaU±f¹ÒW䶤O·m,ferŽQ6¤µÎ>ÓYj~ˆõ,–oV$Ÿ�ÚÝ9e‹]úá‹7\”¬,ly6U„#{—S´)«™f@Õê?H—ý¹î›Ûå¼*[­5 æ0nnt/e½}T`›Ï‰\ ÔH‡)Iª×K€L¶ Mf܎ѳoÂí×G8=¡Ì#®IÀ3 #ñÐWŽ«(Oµ§3(Þ.œ9®l&:#B?ò*ˆDšYµÓY*9o|ŽË­Œk#!â)iµä®œ—t•„v¯}©WVfÏ )ºtÑKRC-R8!tK¡{œ´0‘Šï[ÈÛ|ìùœÁÏo&Û‹Æß‰ ¤ïël¦Îgxnj˜3ãÌl芽O#wwdv0Ú„ªm w€…ž•Ù8úú Ì×xBç²^@6b¬Ë5E¯®È÷)¾:3ªŠÈåä¶ðȤð}–zÁY×Á\hé±Ë[ä®›Æ<p›2Õ\ e¾p2dEn<|V )ç—'Éw0Ì=#N*wéøžT‚óðÄ-¼Ùó¾3›8¬Û§ ë)ñ4°ÒOé©_ÐBJ§ep¼èÁSÝ©ÄWÙÖë<³#½4uWPâ m¹cút}Ÿ·« =ÑX[¡Nm".Cyu³+¬}²—{ó@ùñ´¿%¨7Œý†_À†òb•ªØN‡¼¬Òmå Åw¨¾êýD½ïáuº–ÁKVÊH.?94\.wå³*C7©¤™(}Û“ /¹3gû‘•¢wÉÍìŽ%Ë'¤$_RÙÔë7Ó­Ù %t!«É|m“‘3þKöÜU&6 RT÷̃c‹½B ruõ¡ÂAÕA™¥›2‡ôzäªè”йô”Xº£ƒÜ¸±$Ë줌°GEMOëN ‡K kæÈ1|ù1)`‰lÎ(𭳟,ˆÚÆFåñ8½\s½Âq|ÿQjvRF&za7ª›d¸àœYûœ 2ï)'6è´éYÞlÌ!azHb"÷ެŽÙÓšd ²ÄBy£Œo¸bdX¶«ˆØŒ‹%†Ïì@gö¥™¡í;‚jsä- rG(ÂxQkgÐ7gM7«æEg D8Á óL„®4ÑÃ-²~]æ \ùòYÎ×»¤scññXˆTÛºë:æy¯wÈS8bi/ó1Ëϧ¥îÈÒœ{pn¦ ºñ¶)o%˜m—z‰ ¥ ÷;aóÜu÷Çç‘™¡0)žy-¬Dú+¥ÆÓðy�{Qú’àtº_{êªõ&'ìâEͪÂÑ z‚gðÖñ‰¸jê!Äm û«VŒ³¹%O†¼ÚŒl!}5÷u%cœ‰åb^Ör]á‘ɧ½5[z§W5:ë3¥i)ªÛ Æ#£äMêT뇈‹÷ú”ÓœASžAÄÔܘ̹zD%%P’ùƒåÛNkx‘#|ÁC8MOóÙ†N…J†À·Ýôg*Õ‰P¼Í]êu‘ó¬fvËz•Y-¸ƒX;¸ZÍAn×H“j.:E¦QnHhz ±Ï/Õœ j¬¸"\;•> jãPë!TL¶‡¬FÜ&!=.ZàYýÒ»FŽËìÄùéÜCÕjÍç¸ôh‹se¹/q|8ê ¤ð“R¦/J¦¢¨§³ÒŒr™kÅ-)¶Ð—«rR;!é¡çU±0Š�‚iˆƒp÷;2Rr¬{³dªîfIü@ZQµé´;㨠…6l iŸq=0·!,r¤ÉÞ¶1Ö›Uõ 9²âµ™Õäpèv  zÄ€\Ìä¢.uGÏôùÂ>xé'ùÿ±‰B®Ž[KÆŠDرvŽà¼š'PûRêâZhê,˜Nd:ŸÈ8RWœqd4?k‰^î70do^ˆƒ¦á @¿8¡æW èmÏõ•%Њ•%ÊS0B0Åe,r�aCP—DHx5í*-¶ÆïÞ„¼”¦9½\/ÀØnñ…l€†w „Ó¶úq‘äb?à« ¤ÃÜ×ÄÉ÷¼¥ªŽ©šMÙŽ8 µ&Ɔ˜k¾î]~†.‰P»c“oÉSÈ`ïêmÜKHè‡óMºÃ^?%K8Ü9¼SÉ-DAˆ{ņSš¹›Ã˜2âa]nª6d³½ð™ À£Fª½Oη!zh'°d•Èp;”_qµ´=@ v¶%ÊR%éxqؘ§x•IYÇ{kŽ^“ǯ·e¬g:<#¤î0[Ôß(y¥Þœ…:YÙX D‰´±÷ª&œPg.M [0JUF–s½Ìäª]\ºd?`2ÖLÕè4 0Ÿãè>}è–\ùfÖýNÅÁr=*9žTLC¶`íÒóå­Äâ9l K_==òfm--}0t`Cz¢µu2KÏužTÇáÚEn-å*Â:ôòYA{Bç=3ˆDõ+;.|ûÈiÑ|ºcŸM=\v)•ã,ŠyÞnn¨=,=eü„‚™”çU9•(÷9Å1WDùªU€µ2Ö˜œ}ï¥_˜³ÌtÄ«I7Lc”3YõÓ»…Vˆ9�[o•ÎmŠñü>ͬ„VŽuÐÆjqˆ§]Å€èH†…[Ùr>‘ü—¦¬ÐAh·/�_š$¬>‘·ý®k-ß9©ë=Þ%"¥áWR'dBnÈc%¤/âQBv–‚ç3‚Æ.ò-Ù†kA6ÜþÓXö¾kâTš§ÎnûàÉP?äBt秃ùÞùµ7IJytj¼8u š€)”¹ºÎÔ=Ȇ¦A;^—µ{sšì2Àñ¸(y“g¦tß=#¯ä%XUãÊ1«fªºÂÞʧá™"í–вƒÀÞ½…À™ÈètâWlÈ�PiªÑ®jJ%ÛVâjQfýÞ©çÓWO›ktîœér`;£ñ%Â;PŠM³ƒ—1Íf:îdÖĨp¡¹ï™¯&ÙKOáÎg¹ÑºsŒóZé¨ :¶PûäkÔ¨vÊ»m/ŸóˆŸZÚhºGus\åÀy¥‰U=¯d1P"šˆá¡ µ½ä¸|ḭ̈rKÜ‘ƒÐ2É‹G½#Š¢\<«¯ðr¼„²w –0üqÕ•‚‰±p‹õp ­ËF¿=ÌÔ¼Qç3×$¸«×`Î�d=ä#*÷YšØß\ Ós�XDûµ.'ŸIH'TeØB½c{3ŒF<Ó(ï⮩M'ÍlÀÂßÎyN/ö“š|ÕÖ6JÆË=ï½|^Sü†­Ùç Æ¶ÛMhy?õrv)ʾ°ëבe#ܶ»uFõjõBϳ¬(Sô—x™ó¤K̉æž`£tn„öî%´[ñ̢–³»äèŒóy…’­UãýðTß³³†MWçì µüæÔ¿8]÷,pó@ ÎTÖÞ"X“~YñúͰŠ?7æðx©ÍŒ*ÑéÐlå½'Ü}µ€V"äãñØWÈNïÖÑÈßáËí;Ãz4µKÓaè}KŽsYºË^„î( ‹L³º2ª9>rñ ,¨²_Ôj‚-¾wëíÐÐΊqÅ,o6NxT »áU”îü *< yhå:òœ“ß9­ÙÈiAåºÇ;ܳ¬ãÔ e2d�~˜rC`€ |6è¯wìåv!–¤”&ãMÍIRae4ì4վǀÏo…5@Ë!o¢‡^ucëK„ã:>r­r˜h9ì; ‚ƒ;DÊnõNÞ{ž€{¥‡àVKÄ{3à´€OuGñåXò ñ Ê{†ZOÎj˜ýpVù¡f2V¶Ë½ÕÚ™ÎSÓ'FVÄÓ$o w}ç½gpÊûîVì©I&£F&ä jÆ4“Ò„†¡¶ãŽ^ÞB˜>õ{Äf«0÷ní¨— ¸·.qJ't°4ì<dt¬Ýëa²¤!€E!uç‹®*g[›HÔ}žÆ^à/î °0G•\qì´™KÚ›ñ(,1@¸|Ü«W¹ëïÆc¤´d¢·]jšžr´0ÞÆcq²>¶*Áb²aJ"%ˆ&)cLxx[”QÎâëXvþÒüì9êJž¥©Ó&ÛD­NWἨIu<«¦Üy©,Íœ>è<ºsBÇàP¯7æ¹É›ð|³£@8¯,ÂÆJgŸÎàÓu‚GüJ•Ð;žððùäQ‹m±›*©í†ÁB8N½2M¶ R8#`¾y‘'ÉÖôªö%׫Áuäã¤ÄÞ*Šx1 {t …ç{P5ûÀP<güD^btA|‚ªöê Æ¦ó–m;B…¨S—_]ÒuEP)›ËÕ"“‚á ƒ.+oo*•ŒëÍGÌД™‘$ÛS�-lYý€Ø0ªÜÉË•-ÊûÑö8Ý‚©>4öˆ¦„½³fnNç| #Ò89(jqWt¬—WÂÞm�ˆ…¥šñIg¾�°¤ÞzªBótÌÿ#U]^ž½Û%{ö ´WÀèU� Ä¤ÑØ\r“‘}é»É>9 ãÖX…YjÔpÓ·v8+ç ¸ùøn*ËIDö=ñGȃ¯’q©šã¶F¼�‡TÀöE ¦u€ÐHt‘Wáµ'¥ŸdH¤ß¡?%XË@“wò¦D¨®è=Z__¢›§qî(Çd�¼PªjÖ†š' –ÛS©3ÏÛ\ïã±îØ4Ï‹• ºxèWºYô ©ždq)aIëèìEd4?µŒ4ÅwlËh uvh”naåê í) ÃÔ«ƒ'B¯©'áÁé>_ž'ýÉL…H]ˆ?£Èðë–—\o½g¡$>€½‹8O3úŠö¹U>ÑòU“c.H¯Gû<Tò]‘rÃÛö+®YŠ™ œª fºzÂü�}„›†šÁô…Ʀ q2†«\QW„ôŽ›³­3“ܦJ«O©fX iâS0mA[{bžÕ0HOÒ¡j"3&Å“ ÕRS…38HJv¢$‰Í­¯'ÒfG#¼õ®:–½P|ö„âñ>}IŠû(YièP`7fŽ@N(Ô^¸#>Øìa‚— ­—ØËT*âMo±¼ ¹‹>á:ÔÜ=Ô•FÖÂ+<ATäÜ £¨pCØÓÂÏü iS:ECsÄø“T“/R5r Êî-÷ËðÈ+r&Ië$7Å><±\vÞ³qT™Ø ÍËuîëÈØk(ÚW' ×…©èRóx!ÆH/sœ´c2JÛš`€²&éºÕKkøVáÕ ƒ ;†"4R5ñÒLÉ=Äé¶SX¬ÊÈlœ4aå@º(ØÀŸ�vw>G­ã–øÕÕ7óæž(È) @9¼0ÆS¡T&C˜÷fJêε檣üHY)“'’ “¥ß»3ÃâL‘e¨)DHï-ÓE…¹ „Ø ñ»Cì<ËðbâSZ&^¦ÛW•6"ˆ»ËÝ÷�‰&µnÛ+h!ÆHa&Ù4t½¸’•ö”|ù¨@‘¢$!£Eßûú0¿�‘•2-'f{*€=ÐiÒ§C”DfÏ7e©U\³¦s7çö ±cF¬÷t ï� À)A€c!^Söê _u=|VÝž»¤è$†Ù˜"vœ!ϽX‘Ë}fN§ v¯‹{H•-ÙÀN¤´Ñû‘^À»g• ¶­ ^ôÆ‚úf¶žÇ*c% /=,½›Vêy› ådB@•ÔÂÐ̃aÁÙJŠq"€Y—Ѫ¡ lwØÚëõÐQ\f -ò`+. ´½«ž1äÇð²æZ¥a­ízÁØÒ÷¶w‘¶üu qÝ`Û•?"{/¡€„;c”ÑSW!€ùÒîñòSUų}èôÝœt©'§ñ‘'>æHgÍÇu„Û€¼'Eu]\‡l‘þˆ#U,ÍÑÆë×öÂÑÄk/ÝÌt÷ú„cÌÞé…LzÅâ¾Åð{úº`yÛÆ»üF\lù™Ã³a¡›ƒZéBÖ1¿<íàË«G~nƒŸ¨>úBõ½]©8¦Ð,b£^ ‹†)pzË‘ÃÃXÕŽ¥¸˜\ •ñ^Ô‹´px ¨àftÓø¬A=Þ²FZæË{ì¼%ñÐ)ßjî=`_é°Aæ¢çøßr ²–.–âÉßy+#@z>í¯¢Ñˆ ¥îx(Ö|ùÑìÃp`×שöz&sB=»Ì»í?V­ Buº<͸lúN¿åɈ4›3 ÒQ}·xò PàÝ,—¾¥]iËŽWðž‘\6éÙ"Ÿ` …•@ÊÜÓ3ìQ%œpjˆqj|ÉfÛÆbËJ^d}¨µ!B[Ý wt–3°N•Ò@wDö8tˆ¿ÞUéJ~Êe©3v0·¦uýñ+xŒ@\VóÂMšö9Yô.ñõÊ«À’› ¼p1IÂ}ƒïž5V9¼Ù5{EA¥–Â)¢©^:\±J/¯ f_¸û‹T•í´ ›ÃIÄ×á¹Ûس˜—Ñ{F3æ6XE…‡Ä/ª¦ã’)­,Âë½õ-(…çFyù^Ä�úÒ#<ÅÎÇœR{ö*íz‹jL Ed5ÙöCšôK–J満Áƒó2íÓGåêú¼e`ï¹^ ?€LÕ¡1†)§Ø—ñè})(Ù‰[IYrô‚U×a9t_ Ú<Å †{ç¥'£Iù”18·®o[Éø^pûíÑ`­l'µ­5eߘ‹÷¦i×iAXñ¸ÀC6$Kæ= «#F8 ®Kéà,'sÂ¥ &“…Ü›ó»d(lÜ·ìÒo…^R%Oħ™±CkcÙó{B­¯ ¹À]âÆ”æ%bÆCöšÑö ¼'`ÂŒ7#ðÄŸàäªr¥ˆ<SÓ EäoV¾X­÷p´÷t03xPMx:%íAúºL #Á᡼Ú{Luœ{öšK¹V{<|‡0ëXêÌ‘ö^…¡ßÃ}ÁG/^n²„€)’S€éð«RÝ|a—rj7îa%QÔƒQ„šöú!É*0 ˜Ó5Òˆ¡A±Šy:Ïx”¦Â'$† nÇÒAéªþƒµ›6d÷\^ô亚mù]"¤À‹ÐºˆÈ·³JfŽÓ,†vä"4“AHÒ Žê^Ž˜;gÚ™CoR ;‹Ø™™ü°|RÚü™¥?¸tñ|QáSÜwú*lqiöˆb;‘¹QUüÂ9„ÊT+5Çå4Îìæ„^ÇA'˜¡ ̽‰<~ž:’E¼ÖÏO¢Y™…J1©”‘@œq�ŸE2ÚÐ)Ö™tA6õ½l¿²³ x`HV“ †8ƒFë¥<¶¹dý †TqòŒÄ7ÆÔñ±S 1 ‚¯ ‹ð¬æô£ÇýÓÏ™`ûÖñ½l°×é©€iû�¶zWv9®Ý^ó¼Ü,ãðy•³H8—¢YÕdãé{œ�¤Ñ þÀœ 3iXfÎ;ûè°®foZ,&Ý›,€Q\¨6eñ$U€©ÔÜ ƒ¯sQ’£‡ƒŸAߪŸç¬2’;9$ëâ”?pt®À¾<uzVpïI‹Bp ¾¼‹|«& XCiHw}•è ‡ÁS¯"­‡L¼Ìõóä´"³Ð,3alZäãN’÷ÜžõÞòж¬Ÿö™úK¤ç×ñ»"U{’!‘Æ s£ÞGWÔ£@K„Af} ŒŽOÜf”kz>8ö4FÕ‰È<iR˜Ç&šÅëãpð «ÂÊ4¡™CéŽ6k6xn�® 5Þ(Hr¶‘h\š”³ªç¬Ûì{ `¸HW¨ò@¡{°VWU‹ü-ȼºpd#zý91TΟ@Ù. ßÃ{æ3‚ï”@œj8ÁGŽˆJvcj�Uä³Â›Q8Î’×:éYc”>Û›€Ë寽‚Þi×?{Òv¾ìÐ ÿÑŠô"C»üö§§¼^ÕƒI~f˺­Þ„ ¯„ Ÿõõº‚'wŒ ’¢.k‡r¼”7”RÈÉú¦Ä΢¢¡Ã5õœÐ_]·XxÏL¾3mÞPqL~´wшVÅ÷\jÄôÉÕH,F‰®. úé«}“íd)ò¶Ó–ÒªD À0æÔܤùùA¢ó쮋¨‰oÓ…îêAô†-C€²š‰ØuZ5›‡jõ"jAîª>~)BøSÔ¤ÙFŒ^”¨o�§ƒ� ˜OÄxcy]Ùñª;×íqc*6un…@·‡Ï&®f+Œf¾‘·hÇa²¹´µ‰W±¶‘†KÓá>1é¤[zluEžL¦¯Ÿnî¾8·£^Ý;Ìœ2Ÿ„bJ©sO~‡c6Ès²½¦ Q#Y˜¼uá”xº‘6iF<оz­ íð0L‰°¥^ôì‘kR?‚ÎZnv7rÅPz‚×±±þ, ú¼üv¬Ñͬµl’ÆãÛa›�¡h•B}ø$I…–ìhG‚2.Ÿ†ë­R aÓÅ»z¼ýÆ .ÄðÊà ¬Ãë=sr–.u.Û«aL;W·´ïÀ­ÔÖÛBJÜ÷Žô\¨PŽåèåLÈÛåNZ•ªô+ï¤w7Ø$DOuÓ{÷ˆ•µ+™—5ߨÙ3qEǬڛjÆv49|.ï“Ö°/ZAaÁ)å©K Ø"‡§eí“•I*;×µ’XO¼wÔ 0W©bÔÔCu³^&W„ó Áù½ÔRi€Ë±³u·)¶k�ž—¡Ús›ä±ñf†ðÖ–We/Ûd MóLKDEÆÁfVOüòã~/¨)bÃÜê­:á¾ö%QgÔŠ°R{o‚l²õѤ?n´„ù×—4·`Åy©R‚Â/ª¢_:ìUû€1”w⃳"ê3­;4?ª´er°µ}Ãf£œŒQMíå™ýúÕ‘ÜðÅ<ËÕœ‡ *Xnð<æáR­ªîÚÕf€uߪßôCÀ0Ùõæhê7ž€õ¢úŒˆ¹Aü-Ûb“Ê“EŠztxQyc ÷:nÖgDfgÂÌ]€BZ‹£<kCO’Ø|bpÍ!8“ŠÞjH1ížGQ¼åd>åÚHL�j|“ aPI¤ŸWÖYa»Yz6Æ5¾&9äN¦1…™|âK 1<ñ’t”Ö4NJÞª­ÁÌó0ðSØ@a|[“‡¤Õ.ÑËïØwo=«¨°º±ÈssðZüê°C‹ŒŸAô¨(TéñC’ž ªÚ;ìÇeíSù°(“Ø3ÉJ�^<ß+¾`lÌÇF-­·8IÃýx¥Z)`5ÂÍ`¼‘^‹u¿õ˜¢¥¡ƒ÷V�°¨¬ÄvuÕRDŸ—”Oc^27GHïë•(GG …gìuz†ù䢴Mšò©îÛæ )"ÔÇàU#Žªœuã;ªOËÉûHÞÙ0áéU&‰^CqàÞc•Š#U Û3¦ ¾9’8%o·-§÷¢ô6Ï3ô§A_v>/â¢g«†‚Ï ßg~Ò16B\ú´µE£4s,i¾pE/\½7*gÈeB0â= éXä©—ÚCx±q-óÐФ*{úÁ¸“¡Ž {n‚Z³@ÏÅ{Ïýlñ ¢Ïª™«^0=Gƒ7èûÖ‘*á-ÌÍ>0fÀzxÖ·²DÚY\Ä ©¶rà»ä•A4Í“·õô^[<….{ãD†ÏZ¬Æ“âðòã+ˆÄ´å~¨~ÿñz•bÎ’¡Áœ9s®¥q[\ï•æ°W¦Á‹ñ!¢×޼½Ð*î)¼ÑæTÓx"b¥2ÂäžÓ½TWé²%áÓ€•h!¿PLrö™ët-÷%´Fd… ǦÅèÜ0Áž@Ì>»s]@c;}SQ4'l²M.zÐ0SÆà!¸b'ÍÅô^‚©ËëXîž>Džm®=ÍLl­ÀÆXÐÝ2;[ Ççõ è <¦;\É.a_QÉ[l|š„›,§dPÐF:/wÑŠ Äì•È=:dåê‡sÖÂb[* 6ËÍžQ¾Ö-omÐÇåj».ÒéŒ5"4ì5->¬'†z¢6´ˆ¸ïvu€ð•D•=¨½ÕšëEqkä¶ YÆ$h~¯I<ñ5 ÈCè${ëšÔ‹/'Ù^Ùfs>ÈÔ[~Α ÈÐÂô Vc¹4x–˜yHHóz²8ëÉ´ð`l0ù$ ®nd•CÍìaÞ–Îlª)+SšÁ[Z$‡Ù%pÎSi{»­ÔØ9Õ¤ jh¨í2_µ‘Qhháæ\‚{\¬¹2¬6È¢ £ø¤Zô‘ÚT‹\¤ÔõÂŒø±¶žg ®a{D \§âÁ ,ÔÉ$P`Û[xE™·È.Ö®hÒÀ‚ kxv1 æñÄ`.1ü”Îã2ï¼O^‘¾x½´Ý!™43K"G±ÂHejڎʃ8œ=ÜwÜ‘â+˜Ý”ê1AÏ(ŒÅÃH¹ôuÁ P` 9½Ç¦V¶0^›Ø“à’üØ-]@\¯¯Þ½÷.õ6[ÜB›òäY<Rï÷BøJT­Ùh¢+½s+€¥2}Óë*ZÎמP/ŒRKlúÆ“cCZgØØ—Ñ`ú°R¡�Žá¯š«b+3òÑ"©ê[ «ÞðP5lËÐà‡[˜‰('‚Q’âÅ#D¥L†Ùd[áJÁLŠ‹*6ÛFùÀxüyúüx¹ IاâÚ~ÄSÄ‚»O8.Ï_b±FoÞ 0ÆÉ-‰®„œ&™’[w€\P3iå]Äè“C}4™¬ºâSj¡5¹ZGÔweЀ,G™¡èÅî;­<í—MèÖ ÷^¶©p6¿(ÌÞ@îyÚé ãahìÜ¡‚, ™*¾‘1ãp&d|+”Q~fØEå%šyæ|Šƒ! á‰0R‰¯Õð±“æÍ‹]Hfé}:r ÖŽ"HsJ–s'GìˆuØ–¤ÂÖWì�ÀÏ˜Éø…ƒàáÊòkÂå‡Z9Kjp¦x®bt,·.änRq¸F–´ŠB+§ßù!v>Ó ¢³TJù‚Ȳ*DÏâ1%Lr2‘Èø ;ùx¨¯ºâ‰“h@Ãçž*6 1mòŒ×#}É<¶•¦ÉgBž=üÆ,ì•w„…ŸYÝÙ^c d©>&$ƒ-éb¾“ŦàíN'ìžÁŠ4’l~ÙƒéèC÷$+¢Èœß½72�©4 A²§ÚOÙÍÞÊ’ËôÃXŸÞx júà_3%Ÿ4Ý:¾Sœ£å&?]·ÎgðÖ≪{Î`V=q©à„o2?%ø6ª$K¢áa/w^­l=îõ´ÓqJ×Ç,l>»²…]ýJ5Þã²[yS l-ªN;ö–ø¤Ÿ¨ëd)Ä–³!¨‰ŠšPQá¶/:ˆ_Ë{mE™Àª!ÛÃüó,OºšÑ,+}Œ¼õíƒwP°þàu^`HMê…-`À¨ óøÌ"”–¿çìñ¸qB¸‰v˜uÿ#V»ªƒo‡ÀäI""Àb<—Ñj°œ »ö o\«›¾]&3=y›ë7ää1Cd È–U£;• hOÙq¤¹;L/¥'›˜­8X¨ÖáA•ÆTÖô{åOh¥¸ÝwcšJásjÉÏé!âòkt¨ˆ[T(<EpÌÑ@Æ4À×[~u†f­¸j{è&¥yc=M©t²d 8:Ï\½ Àó4R¬½ô:TÉ‚{'ÕÄæ„ZÞ?dÄÛ b¼Å"Þw¦Lð‘ÆÛ¼Ò÷rÍ1Þ4`7·R†¨X=¢’,5B,q º�ß·/_= H?ã õxAl™瘕f Gc%V)ÒÌÞ¡ÁÐŽm=à½02gXÎè×!ièO;¢e‰¶{'–:mZ1,„Î^¦¢o³·f÷hÓ¬6ÏYI=N¸rwèãsËñ"ÙÇéÇ5¯Ó´‡0›&ò-Û@’²Ñs?Ì$«‡Â’ƒ²Ç@•gLo$•‚'°ËÙW)$ìéºÖƒñjhÀ#y~q÷ØÖœ}·uU¹ÓîÑ)fN¾ã¶¨�¨~ ã`•;kÓXtU•Â×\WÚWž1¾3¨äÝ”y(ru/ÎMßKIJp§UØ¥3ÕóÈç¬Ò¢‹8½&̓DÌÒcòŽ0ù´ªܺq„¿½ÆGUΖX|r|÷M¬Khۄ7 0M^çÔN¨!¦Þ˜¬+ú¡µƒgQ¼Gªá¹æù¼|á÷šûz†·¶Í]õ"ëÞfV®Ø ?§. ²YmâI¾¸P–â¶ÐR6i:O¯ií”è'Q;Þ+•âŒr]H:mfõTV(C—‚:U®ÄÒ媣ÇßÑ@Ç>ŸeÎ%º¢øÙÎè{’³c˜RMP Ï×AùUcŠHïYdzEé¹5²÷e²uY,tu+¨ñЫÐxl¾©“ÛBÏ÷éç«q˜9ßã(’ƒŽèI¨ÎžpÖ*o˜ä2ëÞkï=1ªE…‰$›“å‹xÍx=ôÈa]¬PÏî¼9jéÁ\¬H¯¾N§³³gôÞz–¼öÆ7 VšCì ¼øfør…½›6¶½Ÿ =½>ƒeòŠßP¾¸’sPƒ#X)ë~ucMÏï�³Rð„Ub2Aà­¶³˜ 6Éà‚ÊS¦—âNØØê®ÐèðžmŽY„Íh¹éZXy ëKûF†ô@]ɳÃaËÇêÁ¾n°d”qXæ¢4Þm­]Ê.ôÎ&ö¬9R™©ÚG&ÐÞq¤ßª ¸çí+âÀšA`.ت}J¹z¯³ç…g[E¨bêˆî r‡ô¸ÆÛEôΑWÞàur‰mô gm”} |‘¬á®¶úÈz•¿U}« =“M-ï¨ÏX=†av¦*àé¥(áPˬŒ XŸî&cú 06ÛJm5„2ÞÕÒThjï´y[ÞÓ5Ó,¹¾óv…ß«HŒ4öA¨¢¬:.·'êæMîaÜl1ΚaÔ®¾bÌ0èÙº§, Mïí2· c 䲎]à½!4²¶×“ü}"Ëö¹ÇJ½K¨ÆÙ(œgø†±ätíëÔ×v)'2ò ÕÞ²Çv›œ…ù ˜Ì=˜s¶”7ЙÙJ¼Xƒa(¶^¾‹Ô¼ÈÑ>|¢•ÛQ(½{§)X©½àz[áPYÑ÷âÕxï­ñR4û<GK—‘{¸p*^ïšÑÀ5—=Áà.Êg›ísb«!µ¬™½«üÌ4†…’„Íûþc6®ž]€õž¤÷Ëè™eRYQÇé{¢E¡×ÕH¼íàÅBBżž˜Ö<÷¢‰çÌ¡÷ªA't £QçÉn^—V ½’"¨\ö¦3Gª'ùÒ² ±Î±¡çSF$$D}MA²+ySÑ ªð@\“Â`}µã!><yŽnj$O›ð’ÞEPS,és b½‚Ư©Ú@<õŲ‹£S§Kxî“àápyöè%å0ás¢Ç§âgÙépù³Qds_C®zsKuìN7?¡P9Z crWÎÓöcHLaf~R’fè>ûøÞã;K}–0ÇmÝJÈÏ;§¸Æ'ÈåÙTŒ)Aú;rsžx§cK|GÙK9zý° € 8v“š—_ñb£d¯HjÚ .&\µç´#v ¹r»€‘òP°Ñ€+±³Ðã0\~-U°9r/–yÞÛ~…„ç¥MÂa*1„þæ”:Âv3´%¹åÞ£�ày5ï.oŒ]Þ‹±24ÎymL)àA¤ðÐ}“hÌuAÛ]q3ÚÖH'Äp,ÏM6ø¢DE€DÈdZßIÁm°¾Raíñ4¿þÙQ[×Öºá»+r=qèº ¡d Ç|®ïiwÐr¦1õÉhJn.=5òäÎW5Aɱ£_/”4ÓŽ´ŒËÄ¢¦Ø'³"_Ìn ¬szq’Pãv[÷@=WNá˜,jµèk›fOŒÓÈ®{–{±ÉOèŽKeï ÛÖë•;ìÈâjÄè;« nà%ðç̬ YŽüjµzÚìŽÏ#±fÚwçÉ)H×> °€* MT±|K½km¯§|oÞ¸q¹À­¡ï ¶IžNí´¹`>’³P©L¤Ÿ·fsyÛÿA;Š´çV —%àsé½wðÖI£§» úöƯ‡C±vBª›@'Ljèe‹’¤¯Ñƒ0$3;7ƒ'Gôh­;‰Ó}4Ag´D¦Oùˆ‰¢¿:àñNŒ)g'½Œ²ãLJ],ðºÅM! ÓYé’¥¥^ù´°KSÐúÃÔiÕ÷´ò ”/‚k£T¿ d@î%ÞYRÔ{g¢×òžâØÜ0pXê¾óÂ1»\Xª‡ø¨IF#zÔÙ.¡Ô^W9‹ƒ4Ú b©‡á¶½^›éð(Ȇ+ާê8\ó�„)3šk…Æå™BŒtt•,B‡?›9ƒ1Ê‚ÈxIÀJ÷€4‚[7s§c"‹rCüÔ.Ôº/qÚ´¼^ ±­êwxʯkf8ØÍmMWýP;خД-Ñâ(<p‚çÃ^¹@ó«ƒT“ׯ3ÀªÎ~JñÐÐn££I3šàeÙr9©<rÏgU©ÙWÐé9_N¡FO! N‡B=؃�Ux¶o¯”©#C¤£r7P¶v÷Þ¢½íòz“¤ýf«•.ŸžÉ«²‡à/a®Qïxî,yõ½À#yèÇj#’œD>Eͽïùve+Ò›å#\çó‡Ò0fÏX C‘x£—ñTêñÖȇ<yºFmã¨5@ÉÕ…T> >{/cÖKòA p°ãN[ãK˜5Êü„Vé ZÔ7ZoEáÙD’=y6Ìθ¯ê™ H7 û$Ò ñ¦^çÕ,é‹):+õ ÄÑàÑ{qz˶|épG÷  V8€j#z+¯rOƒ*Îë(*Žš€ìfR‚®šš¤–wµ©ÞÅÇÈ”d/0|òœ^Fi+*b®Ä3ë”JÀî"²µ·ä¤vÅ<BÂÑ•3äÅ.@ÿGíÕŠÂ ÒÊlÚšA$¶*òL«Â½yW{-§‡ÁÇÙî¬Ø}…MªŽ>w«s 9àÅsyÙ7¯nÄ%ü¬£J–éèቋÕU@-@9è£F}9¬*Øï®óP-ËLÅóM€¨?äóEØGÚú4Àm˜Íu„wÌ©ð”EùÁ»Åw0ì1.ñ–ÔÕlƒÁ¨—•}'Ô{Cá„ $5Í‚L[¸ $˜S¬¹:½Ù\©<jÔ©ÚxÚ1™ÈÂÐ" Â9!F¢€™ÆÙ2€´“Ë(sæóFBe1Z+tÔ¬<+Jà”OÐÄí¶U,,¿7á€7¾¯ìfŸ+†š‚:ðãák øà000Y—¶¶Aô• LštÝ7 àwûØa;ß²ϒ‡àX ”\ò”<MþuSª_sa: ¶!ª"è»XxÔ>A<*Ìv|)"D-ÄKS0Nhîñ”É¡ÀXð0šúáÖ’=âç@‹[×éF@/)r+ç|'Ò€Ãy¡¦j]Š'RϲêtÑWU©axŸ¾Wa†Ä% ’y„ð΄Á^¹ç,ŸßðY¨vOä¼E–ŽÓ]ƒ³ÉçÀ”ƒí:¡š08� å-ÔἸwÊ@æö(FdEò¥)a9=èÖ×íi‡öTší¬_:ñ%¸W½É·»áÐÖ!oÞ)Âl×Aé ;p€€;q¦o…C/È'µ_Ô:[±”¢Ê³3ä[‘—²Ð|\~í‘ïj‡ÁÐèP=ªñì~¨ÀÊ„åö€SgÄlÔSãYØ£LƒõW.޳R•ª”h¢ïÅóPÀmåQ '<¦‚_€µ@V\üâ¼ock<kCŸc>y9ñHò!ÐÔê³÷¬^S5GEéb€¾%2UJÆ©âÒ~þ0O• ‚Hë¿Øš©oÑmE>Ž;|$·¨dðƒi^ˆ>Á¦¶.cX?­h÷cQ|5Ž©;~"˜7 ‚²MöVé=7lY>Ÿì>œ2HÈÙ‡gí ÒíbŒ~PÞ,…DUáìvâkÁø‚}îYGÛ(P].Þ$¿™JÏ‹¥×·¥PõbœüFÓ^Gó{x— ¯_Ê»4ÇDV7ÄÊg/NnQ&+†SV‡²Où cÜE9N<PD19ŒÜc¤K¯<¢ëí¤’ÚÆôq'Ï÷e7ºËìÊÈ¢³¥’óFlÇ~+P‹qGïQVheJ „•bbF©rËö<܉#º^õ\ ã4ZQ˜§Òâm¾{°o¨)QŒ2€ZmÇ%ª´ÙԬ˓çÒÕIR<èÍl‹Ö>…3wìjæáo$Ÿ@?JÕGRÓŠFeJÝÀ£§vR%úp±ˆNAÒªl|<^>vз8´…: ÃêZÒ3—×Ë9:–n8¯Ï©ô0ﹿŒ¨¨ä-ñìKr"UBJµK<í]F{#ûˆ‚6(Ô(xL()0¬‚e¶±æ<@'Ø3D0ùú%eæ]¹Ò ^'* ÔÇrÛ^Á,RUmÖŠAõ³¬ºr!v Š`ƒù¢ˆTѽÍp4àAàs[3b@¹‹×Ã4Ém‹ÝM´éUÇe®üLò1¯!Çc  –¬£�½olý Ûî÷\R)_–æ°dE¥?x¯‡»œ-§ãx:äwN ‹Ðpï— LH W}áØ°Ê½Ö;¢5÷œ÷`(*ËqÆÄ@ÝÂd'ëõÖTm?½yA ÷&©\¹¨ÀCÝ/á¼Ñ¶M ¥U§w™µ‹3p,|e88Ë×7œô<gkw1lN@íÉ* YgŠòù,v•¾øÿGÚþã¶ïÃì¸ï˜E/:� ÍM µÀ )Ù#Ðr‰} `òš“XàõÈÖh©S3•©J+Ø ZÅ prޱ8Ù²-·ºQå^Ôï±(’ÚóeÚ­\Ã`%¦ÑZ•ìGxóôÑ”SðƆ8f‘ÀTæ®õŃ.K8 œÙtÃÛ» \kZqÚŒjR½è^¼õ^ž”[äÏüX­iÏù á ×5 ìØ’õÅĬøaïp»el2ÍFÒ+8R|áÙE´Öñ`F´×—Y…“éi‘”‰I8¤–ÝeÑF;¨ö$Z­µÁ•¡¥¯×ÓP¥¤9*Ðr±Ú\ôœÎ RÑ‚ânš&E~„3ošBjâå{Úø$AŽÎžºà‚ƒ·ú[,‰·DAÍ.!²'x†iÒÎ –ÂÕÇ諼’¶A(ƒ»¡¯®«ÃB¢s[I“C¼G=•`“-D<Kí8‚]GÊÇ»}l€µmG.ðáõ„eG,?*ÑkpC ÓU†S¾{d§ÍìYb¾VM­ŠBôðV¬!)ž&zußøKå¢|»KšèPZýÆdôÝù^9K,@»=œ¹EÞöWªÇûJÕz-{Å´;Ѿ03Ok™xEêè&w"�Oâ)Tp^“£Ö&¦‰8+h³9†Wœ&Ç�ùè'·Ï¾¸}ÆQbxwô HT³q0¯÷9…HnêøÛ’äØ «ÒæÊ<X7oW²a¹Ð}±ïÕeë]yÔaè+%^|Âó˜¸hó³?šÑõj!Ù3É6šXš™hÛiÒNæ®Líu‹/ t:N¶õ6´r‡ßâ¿Ú‡ Œ‡«ë»Z-´Ãož®j¸ÔaCÜZâ%òWØåæŽ%%†B"áÿûíMIמ»*ÉC¸°ÃˆH_½8Ý£êî&.Kèv¼˜º3®È6ˆ„Ë—— k¯*,U~“/©^H J­»ãˆîH¼™ÒçOXN%:Ÿ½OƲ gÂÚmrÜjo+Û⪷U ‹®ìa';ëöy¿~&!o8bg̰ÚCÞV‹`íqäeÛs¯îÉV1µð304DIg±ÏÀ°Eäcßf¦k¶;aÈS¸ò•!ÒÇIï(�ëi›ûpM+yKµ£yϵ£ &٫㠟¡-Xgb÷{CÚ:ê<°X=o Æ/}ò-ÄSxƒè9Í–5°²\qOzÞâö¸�æJØãç!Û “²'O…D\k5"eý0„QŒ–±Ô<héÐÚGL{MÒéwñ¼‡±ÀÍìèl.6$í<¯gÖÚ0·Ë8RJª¯d»oó¸TD¥«¥)9uÌkKP¾kÄ3wŸ¤ª“°Î'}ypi§§¶(«ªõ8B�•‘dĪ:ÁUÞƒ×øìØšs5ÜÎ^¸$ó‘R¹=õžzCWcl`E+|¯£ëâ -ûf§‡³vм|^)¨9êp«¶èøžó!*sû<X.¿kIîžm5Š·£x„ZÞdÅ ÃNÛ<M‹ÁµÝ‚É ÝTXÙ™å{oÆ®™$Šzñe±àËŽ™4Ú}ÒŸàú÷¬L‘¯ ‹¡¯R}dÞ:\È ¨ôá8ÎÑšƒû´!HhTÂ/À꺡ϳ ·¡­Å…uKi'²¤ª÷¥f­½èx¹4µ¬ëÝ8¢6“Ü'èfÚúºv¥ªä]Jç=?Ù5µÛ&~·²[•—¶¸G5°+¹k`£èT.p2çð¶n0±ã[=æéâºgW(Kœwxæ;<Õ÷´£"ÚŽþÝqŸøl´­¥»ÛF³Œ½Ô"#eÔñÐ÷ÌzÉ•Ïg@^r©§ 1½U#}4õ6Ý­Îæë…np^hJ+Ó¼R5sR=•†i$“ÝðXÒØ|/ÝU«Ÿl"˜vD4Ô:¾9æ)#9Ø:1n)qµ@¶õÀFpJ~k9cAÔà·Š4AjÝü”-™äØ‚©äÉ1²É[Ó«#ïFÚC• ^ˆuäÓ¶¸N@9Ô£;¾Óº´Œfï²Ø§c†¢Õ5-FËi×SóœµE*&tñl5æËƒÇ ¡Êµ ßΖ­¶·&+[g%”½3Œ,Æ—ég�êQƒ‰;wƒ}/‡¬ŒÉ¤ˆ;a·p,¥®qã‰S7s¢Ô Ÿí…¥¼IèÅô °˜Sh­]òqžØÂï3ù½Ü\MJŒµI:|Œ$½™jJ™,ÆT‹Ø·å×Ü‘PÒ¢ù‚¹ì¡0ešÙåÝÚ 5šGïž[DÄ£f-©È¡79iI²�êÑ…[±òÀRžµÖ= œ~Ðqg9µX@¡ U9Žš£°5}Dü®Ò!E9#:%�ä%ws†öe½ƒ¦Z`ÃwüâæÊ3P„žÊ¬‘ƒ¾x9%=ysõÒ⨠7¦•!cÛû ®=uEjÉlW“`}¹$*4cŽPoæÉØùf¾BNØLžç)Nl’UîìøMn|ŸÊ4džÔéÌŠ™Ž4ÈäÄ#¼ãeé:#š<¼E«0a<k™Ã{Ãr¶oÂG r”Ün[¦É”ÊÍ›S©C~9cjí bWX§hc´ëT™{Ò^ŽÏ-œž]_‰,l«XSsôïË]00¨—’[;ñj8®Õ‹nN B×ÐbS_/~ìT£ ¾¹£7@Í/Döqý‡.‚Å £ÍŠqË™{ìÚ¯hÈÇ|¶À³¸žÝÃ^4Üœ o!â=`bÊâ<NëÂÞÓ!h,®r !n «=¨S9q€®ó¥¸HiëÚ'þ  NŸsòsU¯¤Gæ©ð$Œáô¨Ëj2¦d™ö4¿B†¨ #Z0»ÐCõ>7îFg17S"¥Pà5Ô•¾½8 uÞY«-ãBñ(K£ªœ`†ÑæÙ²Ç#„Š;áɮҸ n¾ôÆ»z*`êXA á(¿ÀØ~úÅlÞxÔòi»·0,û Û8Á”fšÃ‚—ºÆ&Ók§=…œÂñµUt1%0é\jÃÇüvغw„zŽw ±k1cƒN¶‡û\º¬áAð(öÈè¾~*<ìZqB@âOžvÖÆUù;µvS&-'k¦%/\©C÷8€J{€`ï^5»“w>zmjËO}f°÷1,ef«l>Ü£Ü0¬d;~ $UÞcO³(àvÇz'“"ž6’Ëãí]¤Hv\±½½ôZÎ{wàê3*`Z‚7Ëz†N¬£D˜YK%µFûnÖksBîÕLå•§<ĈâjˆØ÷Æ1�(ºŸ‚>›b<6*ˆÕFd,ÐGã6’o¤”ùñÛ’y« 3àJ /Ž‹ŠSÉðiˆ½MRÄív=C+®·V9 ±|N»FúÂ�A‚ë]øBWúéy�Ù™ÝÎòU¯ÅR×nmÕÉaÃ9r©áè×åð‹`‘½‚×,fd"1Э3ÔG„÷VšE"¥6"\‡F×^ÝQ³¾™ÍÒ¬.1ŒãäÔWÔä D[ôìY[Ÿƒš€\§Œà¦5 ¤<~z¯ÊÙgܹ8‡×€Þ¾§ÕGFî(äÑïîB ¥!t*‚=u‰®•Lá4ð?vÑ8:áBT‘=‚߯ª¿ åy\Ñ 9µfð s”Çá(1âô½¥çÈX‘-‡òö_ÞõÁåÃ…š¨`/òëÊ ¤#‰«ÈÅ÷âüUaæC¼n}#uåIÌ¡nçx⮳fÁÓû|¢ÌCß¡y¬ 7Š1ˆö¤UâcPY”Ú˜0÷€9÷`:óí½¬_Û·³±¤9œ‚D¬ð­“eú²ž½ð¼^±› xdöÞRƒzœ’æa¥:GmÞÀYúñµfÐVŸ<,ãKZ³Ù¥ÛCÂ71$«DUJ7 Hò óUL5˜=o=мכ<þˆø‰ˆEPJÝ,¯¯;îå»Ð7…!&aM›¹áA±ÇsƼöÀ‰ó{€ñ*fðõëpöLàÖš’j•}ì1¢¼Ïâ™ú qÍ*5}í=º “Ñ¢øŽ1«’ýp^Âå£uB%ÎݪŜêª=›…ëSͧ—zo=â@4¥ g‚Ui²Õ®ÕZÂ=¥Áéʵž¤´§ÀëÅk)Zg&ÇN“¦#¾ñŒ‹°Vã<BÈÏð5¬X+š/”°¿'b Og‹ç™ÊÄ&·çòl«·>åc¹Ù1Д 6f;(VÝÐÙãÚ|ÉöÞaœ,¤Í�ï04¹Þ3lñäáÖÚG勵ë4w Ý»9„«…çÍG@ã "—\-س-™§QõÍ®±;¼¦]A}ùÂŒÎò$x,,áuSfN÷Þíãõ‰³ ‚X³‡:¶ñü¹·Ä^ø+|°}œé642˜`š {íArl:ö¬¸+–j;ÐoÂJxv½Ž ®S뤢ÕÈ©tµ0KG{×/Ÿ‡QŒ„ø ¾}ãdƒu¾ŽÄ¯²2ÒM¦Œ>‘ ÷)»9•¸éäà1Ž~ym£½*Åÿ…¤Hñü0ãÖ߯yA§ ª>é!Ô—s•¤š2S/p{¢äE=¯ÙWüÍŽ3 àd…¹ {‹#ÕžOoßêÛ·ežæ+·7¼Æàm¿‡@Ê>ª¬MÁÌ¡L¡ŒìÚ%Gœ÷ N׌öí´È‹Ð[­~hýªÅ©z_–ø0·×eÚ˲q*›òJ-¤�S«u\,~Á#¯q`÷U‡r;Ò¢?eM0¢ÎµZyä"O¤-Ó¬b•ïYÅŒäžÏudx;] KCˆ­VøQsi#yï½·Wq&H[ˆÇ¶âryÂ)Ð'ÒÖ<äÏð¢ë¡Dó”Á@<‚g/W° âµ›>tmŒ”'+ÍóÀÒØV’ø™5Ýq¶l̼<£“·öðäñR‰¿4ͪë|Ò;`¼Ì÷4T7Bª9àUlÛI»Ìé[.Êu1øyvã½°IsXÙ›¦¡ª'DýJb%-»kXÉ^¥yÎEÝ¢=~27wKÃtHΛŽVÎMƒ0²L#õªyÜÅ¥²Ød Þ²Þ©Éå.tXà—f,‘¤’K™~ŽÝïJeŸM$à…qÈrˆ�G‹ÒöÁÍiyêKJ5€,Ƽ\Ô:L~³°m°÷”_¼3¯7qT 4Kâý0qÕÂÑÜgfîáÑa„0cW_UÜ »“0?–¦wqûè™ÕD¿+ ü„í ^êVgQ#šw÷-£'•»¶ZB¥Ñ”4%Ý í 3˜~ÚI‘0 éoJ¦vå¥à[ÅL1WdKeî›Ó¶}¸øîáËR[¤Î‘gµžC£ÀûF|h|V.Õ³¹oóvW¼!c·Ý%|y¯Oe`œ|fº+ l“¢O»´HÁµ¶<#¼¼Ümá¢^:l¼ Ì7€ôà"ßÃ÷½þÈ3´T'=¬XXGMá/‹At8n!žwˆ½‘0qëãNÄò†!jÃH_1¥ÜZ{·qó†•õsû"–›ÖH«êÃy&k´¥l`ôX‰2ÔwºˆQ×#±´E÷Š¢YÊÃ÷\6‚Wò¥E\¶±kèË ”ºvµõî6šá@ƒK:é')‹Ç‰u çó¸R“‘™„ã±å­?if·}4ûY¯‹S½ zÞiØ÷¤4wÈ!m_h€µ4Ÿ’¶v±ÓªæA¶vlÞ´d?9”>$ˆ[3ÁÁ‰‡ýŒÈ5JõX:/C§c½‰ 9Öiec1±$lòõÇ•÷èŠeYˆšr2’ž²äÓ²£Áˆñs¡©¹‹Û„€3{/øM«œ!ÃÎ{Íô3¡_ˆO< ˆ×·c¯j´{ç’EBdWøñ˜]Óq‘ÖóKÌØ¸Œ|(›$$€†í=îGrû¨›Ñ`ôÌØË+uØ=,( MÂw» #Ó-HCOAÄ£¸›`¹Ý¹aÜL³\àE”n)ß™Z§åbâÖêaEO-k ÔäÑ3èWu ¸]FL4ƒÏŸrqåIïAÞI¨6Ó1e“§H½Ãõ¾à[SyëÍ3¬¨±AÇm+}”O;^g7ÌcªpI¯—–åèáa·MSµiÐ\!r¨RÓ~M ôv€w·oì…Å'½$_ôZKAÂÃÐÇ«ÄÍpÃok™L^$v:ò°±+c.y‰qsrz66)�KšÁÒ<\´áì–ºè%Ô¶C-l¸~ûÞðÐC}k6½ÛAêçGu±@%ÙÁ/xÆ–bÞβ…&ÌwMõÙÕ{àÈ[(ÑIhX»@-¯Ÿ­Å è-7Ho©½ T¾tŠ{ðè‘á½÷|Þ0™jXÇïß½·`—õ04X†‚ß(ñ°æ¡ò5 5Èꘋ³hØq {ªÄJ æB—ð•X3JcBB¡êSÈkF7¡[m-¹±•&̘Ö)ex%¸wƒ‚‚¢²«:9jöºŸh s§™RBОW³v€ç ¼Ü1Ëk{•ÛïzLÊÙÙ<ý¦oI Fìv¡\èbã4v}7©D÷D³{iúVJ±Ú³2˜Ý·7b$£ùÎÑÐc.ß‹ h=+¬¥'A9pX®»ðB”¢ž.B%€5–Ùñ™Q3Ìy!….Þ5N?0�7êL”y—Žï`7È·ÇãÆ÷ÙZïI¸%êÜõNG6Éê’?g³÷^„Ÿ'Û¤"Ui%ô*˜@b*“ß¿S”®äŽê=Úfe |¤DêÙRºö4{?´Ülö¸hb- [6Îð.„‰„¹Ý Ö,°×´[Ñé|;öNŸ™c"wD\¿Æ†›¥§2WùEYEÛrÑÉe§ž™<~^ >MokPÙä~izÇÀ¹ŽÞ­dò²Q—ò¢¶Mž%15æ:VJ±jÇT?&$%òT·…¼éð=µEJqÆû€O°”&…²cȵ=‘s‚Èa4C±wì¹( `'Ünµ—:Vµ­5õs÷8œšl<ŠãXÚ¥àzž£¤ùpõxö_¦/|ëMÕ륻-¡—Ý·Jè7 õ–ä©´¼UðúõM�‚9ÀnâönF܈Q•…òøÊz”íQÖ»ÒâäêZyµxÃIô¼s=õưQ˜ï +ØÓB~bÓ©Oá� �HÚX º©ïɱ˜Å±l�Äm…8ñ£À;©;LÜmA\—yïÑ+}båik/Ø´Ö žÆåüb,Ç=IIXl�6F!N#lPXx‹¸§µèlõк`ÕÔ\šUwãhmMùKà8PßLyûõc3 Îj5 lõ³3 GaUèe„Gu1°è›X€žo'Òt§Ê‘¶‘³žè#ßádòMÔWÑRŒ¡ç]^9!ïj…Ü:(¿„j”Ußíg*ÅlËP™C¯E°Ï󂑉Xzåõò?¢8k 41/…DnC, OT¬ÈŽ—Ê1¸7tÑvN-}ˆRõñö›`J[Áâ£Æ÷:ãh»)qs g®A²ç`ÉZ €—µÐ½`¦Àíóh˜4gyŒ=K퓜;hŽ<”‚÷R²¨ƒï1¼ÛFå—•*æ¦ÉÈ0ìÛ-a«âé[C®¾ úu^c²²jyÅÛ˜íÕ4Îy]¯Ž:f-VâéTv3.È¡¦7Ðêï�*Xîí¤HÌ´¦Â!C¼šÙ9êb¶É^©<w¯ÆWô-h•¾â{j/¶,Z€Ågï‘×¥³ÓiµO_5øš‚å8T/ôÃë`Û͆öHjÏ�ªA5|Î’x—B™$qoó¬ÝIâ½¥­Ù(êð'ÛÇQŒžü§Ì„4kŸµäÈ;áíÛi·]Ü` Þ—³ùVº¸/äµ\lÎëðÜ0þþ¤€–ïð“_/~5b‚OÕp°0å»UÓìÕHîŒ:áºdî“qxŽpºäv~øL±‡Þ$¼Â-a§{*=Ø¡dþœs ˆàT\€Œ„Ô>$!‚³¼ÞÀmO8Ub¼0%a^íeñ¨Gï¡õIn回$è¡ÈŒt $å ñ™ÍÊXv¥ƒ™|¹: ¢EΓ�¶Ø•ãÜLAɨSªÊ ÚF>(¦ñþØóèÝbI®§<xÏÅáHÝ’t° TÏ4³(¯o"‹•¦ìð&/m  'ѵ™Î(Í=’†õ#"v(©ôj⣰7jÛ$˜ O–žsŠ!„+3{Œ—Ž«BûÜØm(·£±–E€°œ·ùùF6?Àbh‡ÓBBÇ�<Ô|Ïú/Ÿ(W„^túúR'µ&Þ´‹×ÌJÊÛÍIÄVì'܃ÚLuA8ðŽ„ÊÜÌÀ@‹âš-—CšPI±$6Þ{œˆ/ú Tqyš]Ù“œê¦ È­ÖG%íT¢Ò[ÌP}Ž…•ªÞ´€Û8ÎïvYÊ Iu^m=T]µé!¡wo­¢Y†„‘¶ÈR€€_ÞzÅÌéÌÛE^Û’x|[ó¨ûv ÖÙož¿LÊãT 1QaÎ-ì;yëkÏÂYú )]+o#=J˜ªÚ¤Ý³ìVÒ1:&¨áY69¶?ZÞ"Ô€V¨@=v|äÝ.¨•ãh8·MÊ”,ª(‚óÜIo_€Ô¯?­ÕL»7ݶ{aÂnϱñ* Ž ÆØ¤@rjcÍÔ;�8„WÅfãôä¹¢ŠïðÔ�ù2ªaû¼ë†÷†ôN¨Ž;3– ò»·Nwãâ[µa(V Y¯@uŸ‰‰� 'S)^‹êÌäòÇ´lÀÅTê^Q=¶YSñþØ¿�¦Ú¨S²ŽÑ|:j:ƒ¸g\ñbÀÜ4ú5xmJŽkŠÑ8¬(là š6<iál3dFLïÚÑèö•E_‡êçYØYgVwΛÅé€âªÀð!XÒÈ­ƒ·×ƒb][—«lÓó5\Ù3-ìÃnÙ£¤4Zª[ðƒîœà5¬Ò¨ç–<ËÌÞ‚>ôè º¸"˜N‰lµ‘Ç®Kÿœëú²uÓ¢K·²9´`ïÈ\¡9$Ïñy©æ8¸¿È1µ¨h=–‹ä"sÂ3§Ö¡f¢cy—Ï2ݳ/cÇ9x‘ìÞÉ›+%nPƒIe}Á/Ÿˆ{)^ÚSç~ù‰¡õJ˜—´žÈÑ•9=/$¾÷\ZÎàAûè…‰[Ñè-ò«õч '¯ûM7�âMıÎÉÄ¢\ð{F핳ñ™èŽ=u,ö¥bñˆ|óÈ2¶ûhÃw4ïT$31Á¢×“¡Ël±Â€†àžEÃ…tèE\  “�=ÁÑ–1ÆŠ±UÃaÌ©Áà ªò8ñ¶j9÷2‹[©¡ êµdt1PPf¢PZDîðbvk)Sz ¬ÆÓsQMt:s\ á±íÕ[@ÑkO²“llú²€¦g Ck÷æ=<'/¾wêˆoKž¥ ñ™o7 ½‰ i Ú{-c¯˜øõ,<dŽV¥D°R;dx¡Ôê=Ê+½®ó^#“7wó¼òøì ­èËÛ5PpIÐcô€7W—¹'¤‘v®Äyïµ÷x‹œàŒ"®X[DúEjºnvê{�šÇÈÔ ÆAqžƒ‚ PBˆ<àð&ΩL/ž:Ã<󉛘£Èg ÉÏž7xÇ PeLAé”UOÎ{ Ãç=k!do1`Þñ$X³õ=å(+},%|ª{>ÃîÑ«xŸ«}Üùl8‘44Ÿ9>�sq{ªò†×O¡‰.ò¬a_¯B‰ ÛíÑ—±þb_ÜÈ`š{?H–džíò*aÆ2•‚mó|Õk鴱ȠذYn±+×NÌFím¨E¶gnò˸zÈ‘˜˜o´Ÿ¸¦Ï^Q<·ØÚ™‡c¨©“Ä6ˆ‹˜U…dE`—ïÅÛ}³ˆ/Ü�i€¦÷ÞÓ¦[ÍI«Iì.&«3‘ÿæ(¤[£z:^û¢ßb{ñpã¢Ö;±».’~8nrkUÍFNÊbÉü¤ ˆAÏ ·æ½YDR~|J Êš+•€Ø†*gJh½êiêjýö Éß[‘RzÍÀÞI@¥"ºñê_• Æ#ÍZÁMTв™6 ‚ç°|·\d ÒËbZgšùJ­Ðß›˜I0ÐWñÄJ'¾€1Ë÷¸Žå°b™hÁ«~.| ô¼izÝ, Í‘x™@QM`fb,_kÁÜùM‰héX•¨ìœóX³¿îðeÇ6ÍaGlŸæ²j¾¡«“ç\ð¸1cø5Ź‚áF Ù †føoA“º†‘ëÛó>¯BŸ¢wÌQ‰Ï×E@ jo· Ü©y[BÁgËj»òŠÏ¼çN “¥ž`µ»ÀMk~çóÖO5·Ô»`LO÷É•.V.‘:£Œ–Órü~Ï)‹ej¶H}¡†‰Dẩ2å÷tpfŽo)cI’Ñ×R¦ ½,k0 Ð;Á·ª‰$7ò5v·Çó§qŠ4/ã­ (>.æ³uÜKÉï)ÝP„nsx >zº5„ê„)’C8ãÄ,X¨).TÅãu‹N·ïÉÐ^?²-~ÆÞU¥„w(‹0ûÝU׋-7y0‰Bl þ¶¹f˜mDö9ˆÊ$¦ï%IŒÉO„M¾¾gå:mOtL6Âç!Õ«¼w€퀆¹ šú„=äÔg…Mðç÷|χNLBdNð=éŠ}ójïuhÀzÙkF"vdoQgîðnIy˜ÏñžôIWîsHhRóÙQOê0;!é]e#_­¹WÆÅìŒËXþš¤P¬m@À@Õ^Á\,u‰ÅH?']É­"‰Ùzÿ1#ÂÇ™÷‚…ж c0å-´`hÇâ„ö]hWxf<8¹Š|Û1+›…FœaæZ³.ÃÏëFzî)-@Ý¡â¼N‘Ѫ}ÙèÛ¨UŠ@5 ¼0÷ƒñ yxÄéÔ´Øöq”^¸x«„ »£6÷ÑKK»ìŽ¥ÄåQ/¦¥0A]uU_œvÓWÀ$5¸Ùw>ålOê©9³øXÄó±x‰ƒÃkC1@Òô^°Œð´ÌóÍz Öâˆ~´`õXë›2™Á.¡#SÞ¢AÙfy,¿U® ÄD5ØH†M>�8P¼#Hš…œU®®½V|&¯³Ü\ŠžÊÑêNÂVZDP YnSÔ [Ñ’Ê$¼ÅÖàs ÉbEˆðäjÄßcnC°ìzCïÍëúÖš²‡o|ÆÌë7Bí¤‹XU4®¬Îw1Êgìñ@üIñêÔÚ>™ÀC„>OÝì~©g&F…˜â D}¦#S²² ŠŠ<ÎfÑÏíæ\òEîMÎSAIëvÚtÙâÄÇëþ†ƒŒ±¬›rÈZµƒ½­Ðñô9Á­ûl†å&Á2CS4Dš(²È£ÂB.<±I�Lã†æ1Eí²b×*NnÝS’®t“^«§ð“{ä­ý=—੊¹y‚îNó¸½ lmßU×CI\N—¥ÛḦ„O†}1LZÞÑÀ´iÕó˜ïÚúUQ*pʦßÃÙD|†g! rpg¾n”ŽñÊ9BŸJì‘p*½¸&«‘ˆ²Á­#yì/«¤#è¬p:*=ðô¿ÈîÑ´B·À î7>ìZÆÑ8¹%ÞÒt¨Ý§£àçÌÜL³ÏŸc ºÂ‘a¹jKmu#i²C«Œ¶×À[+%B4p_åy¦Îh¸”êïùA eÖhâßÂ:,Ûš-‚::ëXäã�?œPLÇÙàªÖCxl³çéþvog½Êà‰í¦TÁ!ãŠ5ß´——WpîIƒÕÅ#”“�s4“wF;~LűïÂ\kù½ ¸y,òöå‹Û}5§O_³Û¬ °Þ8=Ö^ºõðC¯9€ã9­AƒyAÉjê²»AE/Ri‡1„¶àP|®jª Ã�L6ûV¼_л9<5rŒ~4<wo0IÉÁh'Þà»wÞ‘½€èï!lLS u{C$ Þ² 9_ïÓ51ïÜÖxÆ®×ÁÅx¸Ól5Ô¼ÇõpPŽÄ‹–!õè:Üñ ”3xgðÉà>ºw¢ý9Ëuð 0ü|´ä=¡ Ù©a6aŽg†˜NÎôDö":‹‚¬}£àb¬£jwRJÖvxöqèí Ͻ¦Mraç ì+:lübnÐÉß;§7nàhò¦T‹ìò¬…œË®kužA�Ýó×KOàJ‹è–¢FÕ™ðžaèqAµàކšéÈ«@"~bªÒmYÏP=^õ¬žÆ»yi½7¤ÒåÚ¢'èžðÜ‚[- IàÁ{˜² lsØQ$Kèà)¼rç˜ÓoFõy¤MÅ•ZoÚ(j@aOFõ®[×8«¾Ì¼zç(èW1½3övm÷U?à Ø{.Ÿ;|BŒ}Ó”¯»Þ1cñÐîÝñ[ñœ¸Œ~îÍÇM� øx"Âx±«3؈‹L68$W¼JšS«Âîªý`•a‰B-'«é™ž¾«g¸(o»ÎÕž2OÙ*´'ž‡0B†ìœƒÍx§%, 6\¾ŽËµ¶\ÓCïàt¥X[-U®S=ÒZZ‡ wªáw(zÛµÅ#ò’[V¬ •¤[µgŒN ³‚Ò+•Ç‹°–¨¢Ç^¯°cÿ£œ·vQ$(žÑ‚=>*ÁF|ÑnhþàR3-Z€ØÒúã˜(åÊskÆ4ZïJ3”×ôÚ½…iù]Ý¡ °cŽÃ½%}W´Þ±:™šœ°)x¹ûÌÅÄÒÉZð _zQŸ&½á·¾*s“léÖ«Ñž>Ç“¦“útT0ÈBئá¯XÀdÅ«eo·ƒ«ÒAK§ãÝË»Xðå‘zK™§þä‘êA¤”²©ÏË5œx{B††]Mà0ýªÕ‹çÞ;) Òž‹3ÁãºK>h@¡5ìZœ+@ÓùÄK­=F+ÝÅlêÅz`_¾z L)c&тϮ •ñŒîUžNìQ<#z;¶e(Ó"êÐN‚~çn‹ v^µ£æ—›¯—T‘ÅöúÜh3•%ƒ>ªzÔþÚ¨<‚vЧ ¤yÏ;ŬEL½ZP< j|b1K{9Ñõ‚CŒðõÆxÃŽ²7íÓÆWï6i#œ pö¶àî]9‘u޹ö<ó,ïYjíöj‘²Ç½Ú"g챪ï¸D;¶ƒÂ±oŠ—`ò3hNp=ÁßP³;˜ê¤SNYJ/y„Þ—–Ët„  ·)ôªIÃ5äåA˜ò[§WÜ/ªß.û‘ÇëÚÈÊöî‰GÛd4¬ÞÌKkGç(K^ò šv£4¤6ü4¤{¨Þ¨ð7ÅþE±¬(U !½éµ=9?Öó."½z\Zý·5=¼*)ÕxŸ\ÞqÙc”#Ám‰“|`¸\„œëd•҇r™å{3£7X%Á]9ÁA•GSµ»ª•gåE'Õ솘/茢êën‡† Àªn™÷¶ïÛ¬æÄM4Fè]¸ ¹s:¤V7SÈóªÈx‰d×z¡¢¸GA)† *íŠÙÝ÷Æyp'´«P pdâWKÓàB"B¡æ¬¢îù«0eL�Ñ~†+ÊlÁŽ]¯ •_Å6h&‘½Ø°~5¯SõÏôã²æËä„¡ž§†Ã„×Åï%VúkŸ¸làyõªÒÈÈüÍÃÂ2ð:·{i1µþ*ô` p¾´‚V˜bðY�2ÁRlu¥ \#Dæ-5lSí&*ËMy°2ÄÊ bWîºoæœ96b<ŸB™à:nf‰%zçò^¦¿€Œ ¡Ý²Ø‚E©-»žÉL¨i{µë7sŒxè›Bô×£zך‚w³ †ó‘\ÚÍ$ç¶´À¢,Àñã>LŸ¥×ËáÖYm©Õc¯á–tªfKA9ñ{ÏQ·é½Ò”ƒ×áá$}P;0R¼½|eššûÈiíWÝ1Èkc² J¨ÁÊg Î0-#áx‡TÀ&ª"#Φ c÷¼zH,™¬ó©að%dÈÖ†§1õj¸/¢¦t0l¾BS<á#JeXrÂ#vp}hApYñ$·,næ5ç1r‰M ÊhIm* . n§¥1ט¼7û¼WƒŠÇ_>ðrÆäW²<†6°|í¿^5b=zKêGµ¦nÃÔ÷Žq òqti5pã”æå+l€à™h­K s†ͨ ÅTÜK}hî6š'y2“Bs—ìã°/Œ/]íáÜ›œ‹H»Û—œhOCAÂ$žøs{i-be�þ.;Ž®Û—‹dã­‹Vpé½a tŠáóî‘*6A,×kbò-hÅ.FÅ{à9Lb½`ÄéÓ^Üêçp¾ìûp‹ åEjoBñyí¿ì<e#aÝÜîR:vÃWm­MmK›ƒWc±!8’C€4I­EX}uá+ù^åáñM21ˆ ûá´ÿÇqèÚÈb@—³=¹žˆ‘„‚€(†—U�cc©PvNd>üÞ’jÍLà ’h~Y¼ 1ÁúDÞF\´o\zs?]FÑb(Û/jJrïµ ì(•$wq ÆtÁŽlßäu4HìKßÉëÀäF§þZÝ,²ËxŠò:!×ñ9uª×&‘Ø«¸}}zZü¬rnb«¡&wªœir{Æ#‹†ÑÄ&„¬[lW9|FžnÈÍU†#E{ÄË’µ$Æ×yQhhp)l…µŽB�Aé§�š|=d·p=›c fº²=DSOÙi<žÖК ,r5 ´­¤Fnˆ¤‘±DòÒ»h§“ÙÕÒà®ÚJHªKm¸­V °§EWƶëæy[Ëz¯üùeRÛ8?ëö}üœÞaüÊ.ÏÌàÇÝ ÅmbÁ8|ÛÚúNF9Ù—ÌP¨‰—áÈs!Ì¢%ï]vÜAÑ"˜³°±É¾ˆ6ž'ýêªõ^ßí‹&IõjêEÑ+@SF}!ZFVÜèCÚe!ð$×bøØk?«ƒéíZy«J¾°˧ŒWUnR iY=<žÎ7¥œ‡’Šm«ë ÒõØ4k„ÏðúïÕ<T}ÒÕ£<uŠøhÍbY ã˜9¹•7|-o³ØÇ0‘Ó“ŠF¯T0 ¡¾8f/Ž7ÀååÚ‹wÕPVlc«î ù„ç‘>÷N…²yA¬´érZi*‰Êfå‹EîãrŠÏIÀéÅÓ|ÆÕ¢ý „a=UcNÄ]Aà7׌C>êÜ[eËo<:$u³Ï€#™ÞYËTõKJ†7ñ,“cóLù‘ð5¡Ï¥eÉŒã+KŽ7§/Ã_ĉ›`—P—4EÝÌ‹§Ùa;×ô$[äI°¼„ç½Ò¤ëÿ‚ÜÔš„ªYr5œñj�vhÓ$4mÁÌ'!&³%Ä¥�Íמ½œçnÎòèÑÚxÇÛ=°œ¥qhÏgû±+’d6‹ãK›Ö„tŸòÅH¹~º~±ÅÂÏÖ»_(1>œ"šÂn‹á1x«WøV5 ò‰7 ¤ ‘ÇBá¶s¯Ó¼6S‰$Oc=´ëU U‹- –l…½qƒ¨ß<‡Á»¹èN +eƒlo:‚fP'C,_×ò ·!of¨¾u˜>DV‘“Üצºb¦2­¨HB}ùÊZ(ž¾ÂQzððv= oÖa ôV‰îHkÛÝ;Á“êÆ"ÔªµÔPª›œJV=#7´©øõ4z[Hêº<øBüMr_-Þ ANqÉöj4ÎèšýÅUQ_ȸ¡ƒÁy¬+¸½˜”.ã¹LÛ;¸×”œ*‡ÅW¦ƒiQr”KqœæÝÔÏa��^@„7ÜÖej$¦ZïDÜS2—<›ëu¦�¬Gµ~¼�¯ß«À¾É’µju*ë‘÷®» U¢ýÁ­‘1WÀyÒCÓ™<#/8ôí Ò<¯Ç§>ÂàïDÍ™… I–‘F"Þ‹ž\c¦]w9}ï¹åk× ºmÃ2s– oÒ…t âs™Y7š@zA¼œ«I°è.çfê£|—ù 5«ª³;}á>AFúÜm´©¬ƒCåÚèP´tF¾á¤¢‡Š: VRƒƒÃÓL×ÞZ ÒÕ[é-R^çÁÞz$Ùð BVèhì)Äc]ló@úˆ(ï‰ròÎ4ú x¿—ÎôÔð]VË&'9sæckØ0£gðbØ×—]9òÁbH·*rfо¶v¾Á�(ÜG5WÎ:xÄůÒA% ž§Ä&8*¹Ez§¾ÓRÙy¸rÃÙÚ`â?’‹»YZœ6hS“ ºót�_5¢Ÿá*Õή±Ü¨õ3´µœÜ ƒGY²‹ãÕ]ìpÇðhzâ¡¡ÝXR ©£±Ÿ³®Š  ã Ý2ðØ*ómÖëëz@+5©íLU¥M²m”bÞé®Yoe¹B±•’¡Ë™|/g¶õ”o©gîÄÖx˜¡p”Ø9#ÚCUóÔÐ74²ÐÔÓN8nù0ÃÚˆ*µ® ðSsÛ‡?iåú4Ÿ¦Méù=Y›àRJJE„†z/q W#v «žgpªX<yiƒ×²¼\¹}¾Ç¬0ª=H²T»Sî(í§£ø°Ï4l–5¯7¤·IouÌß;É–¢¡›LØðkð)à›¼æ”¤ X7íˆzf§Êeî 6¯`ÕïÏÎa¬6|†ŸÔ¸b"Ò T$é^^8È<TqÇ�ËWç¨G`'™ˆOYœZEÙk×—š:)`š&ê‘éui" ¶XER’Es[@GÓfZÞ-FÔÀdñüòåK|8"Ú»Š‘Lãø/bN) ¥b…IšCôeEâ:®’C»ìpWÚH8Ô °zè Tî‰<ñðHìQÊ=.*ˆ#@…pyøBAÃ!ÉÅV}¦ˆ6ã®k9'æ.3…NnO2fœ%´R$m9ŒFÐäóéöõàÆJê€èsOôfÜÊîO’ ¾Hîs5*¬{3™Ç³[ä$&j˜lª§´¯È#;×|RGÃÖÓÐ”Õ ƒŒeñ�zˆÔ*HŒ.,U9FöÙK0Dµg™æÑŒkíLWјHØt…j–´Ëán’¢8-A¬¨G](Æe+– ®"éè9WYÄ«FãQE »•ŸJ¹~pâÐ M7hO¢æ¹³Êä1 ô-äoý‡2&mi¾e2ëÉi pšÊщ{üÞ;­ÐÉá¶ 6zxHÏèŽ×'4²*Û‚¹ c(Is4ä=C¼¸@º`3ÊY[\AªY^€Œh°”�«�WÍ3ykˆ²)>ӘώÛïîf5›ÄNÎUœq÷•øœ%Sooà ç êåë¨Ñ,"gŸmCÕv|CŽs èÔ÷üÁ�’m¢ç *½`l&L›Ä:3x/uÏPÕ%IbûÞð#oؾ†¨ó᫊!ƒK¹C®™JsV {›uyÔÅÂzdû¶ÉôÞ¼'b‹êpƒOÞúÃy9¸Ô˜±`ÞÉçåô@¹qï-<íW"G}†3#¾¯¢æB7¹áÔ[2šê1`õË®·4ð µáø¹U€ßÖ€»ºdg\mʹ¶{ÛÃ!ÙèòK1lZa|o·`=“‚QOsµØ=ì'Ñä¸@eoü x�iVB¨°¸ ’4t]´ST€\<Ÿ M¤µ<0!imHx\7à°zNÐÝ»Ýrà ªZäµŸÊø{ª ©Ñá6áËhç‡á„}¹ŒT!h)FôÜŠ!Êm0,¨=ߎÂ/)%§šêØJä18ÕT < ˜¶‘M¡ó|Õú¦-(*¶hØé›`‹ë9O¾,æ\zFB¦–<Õ5›$ âåˆVn×* %¥zH÷²¡LÙ˘U´LöBdèž.ªF¸N=Viû‘†>íò@ˆ¯“¡3NsK “=çÁÎ\,9x`°wñ|å‰ÕA¿eè1ݦ'Vn¼õ·& ¥…ÓAËRÚ …Ô$AõU?Z¨áâ‡AJ÷„uL†v)óZ]køRp1Ì[áFGÙ^ͽ]N¡>xkjwA³ Øú¼0<¼¡‹Eõ54RÓx¹l :扽꧃ÿ²¼ö6® ÔÜ ¶R|°à<5å‰7‘!û4«.ŸÍD½æž~o¶ýÕÞJfV¾6Ë>E î¢ç÷ÒSƱ¢÷…wÓU* ènÁ,¼8@c£›•@#è‚ä&ëÒÑ+ˆpØçüž´ßPÇx�lÏãƒÊH_rzCòpŠâxlW'ÆFy<Hƒ¹°ÍÜ¢îÉ^Ø#b_ za¸£A:˜ô°‚ÞËŠ™— ³xÛ#m5a¨†^÷Âvß’<$ì ÏŽZ;Ç¡äç.'•‚óV´ëe•Í2ø”²ƒTŸðd7Bg8ê#׫ì(tΔØFßð¤¢(B6Á.Zôe^é€ç“Î&fS¾´®a´ªwf}¶Ï"ÉÑ„‘W+å]ÄäCˆ�GÁ(Ù>Ù¡g<¦š�Û6èÜé/àÉ¿ª–Ñð;ªñ“70G+Èñ@¨„ÃGnE¢O•Ï ¬’´1 ]¹zUEo`öVÍk˵S ˆ˜[¸lÝXäéó-;x²K»WµÖJë… v 2Kgâ’MòœgÞ{O.o+û1®PLeLh­íD?¼kXÓÐN0î'¾}A`"x¾aÆ{†óKƈÊö,mT^=ö,z¥p9´­-/6,*Æž©4Ò81eyÆkç< (?ˆ¥ò3ª7™Ì2íG–¼i”!ÌWù éUô½ë2Lúd™í‹eˆÜÁ8ä°èÕ}[A眑û¬–±ŸŠ‹l¢õGm•0à«ê#SÕK3tES~ÐÅjR^Ø`uæ:òŽÉm' Ê™ÕO#†@¤ê@/Ëçù¹Ê-¤†¡31´îùªÙSØ<ê–¥®à·eܸ©&žGI“0„!û={ÔÄÄ({7צÈBoiòY •’x0×2Җάô=p+RÏÖ+§Qp|/ÛNžà»;ýæG ç¦tüIë,HEÊ+¡Ý5jsÍV $'Õ\ÛJšË“´(Ǫ‹NE¸¤ÉsN»_߉c§QKg?b••d¡zìÝ#‹!h„J²ŠîCÙ{m1ûTÇ“† gXÒ¹0ˆWü\“ÎÊí8VCŸ,N4Uàî1Ž æ^Nïòêe É£ŒI‡º6z¶‚3c�3÷|8xw5#ÚŸ>‡‡cöÊÝ6«Öž¾TÊ ';Ó}Já¤Ägˆ.¥$¦ÅçT¹æ·tÛ¨ïm+C쬃 ñìŠíÕiï˘æÊ=‘nf•x ù;%›4§�ó:¨¡]¦ÁS{4c—˘öÆM¬žÌxf -<¯|-£�îñ\@A<¦Zö[ÞŽóë€—êæø Í"+/BÊ{X'Öæ§oÚµB¦¡ ø< ff{uàüÄWnrsð A'#EmÒ¡œNd/•§Â#N¨’±·'æõZê,s=˜1¡7œQŒíœ³‹»ðxÁ¶…ØoW6(üÙ­m§Î>[¦2U“½Îd²<VŒÛâátÝçéK6„…êLžjy/ã±, ¦hê nSÇÞU¿Ö™ ì=CƒwÜ7éÕ†¹A4­Ü9õÉ ’SBÎr<tàÝçÕvvCñ¶c”Ä@œ§îÅZ³æM5Â¥¿y¹–²ä9ˆ´3Ûˆ¬=Û´}eý ³ÈÌÍÄVgë™QO¦ú!¿bõJCPƒ½'ªÏ5£ö¦€5ÁlÈEM˜GïA/פfŸˆCõ–Ä „ç¸L”ÁùæDɳ~OÇq9Ó]$ÜškÓN,.C:ÈÍ{ôMŒÔ^øI¨4 KÍíÄe¼a¡ `[8÷ºu—„™²*¯{¶]È5E…b5û ±æÃGB@88Íj‚§)¾.¢S©¾ÖEí›ÿÑœ<Ú×Ó Ì,Æô.±0§âõ¸h惲q1/Ɍ◺¹olö=|e÷š×M·¤‘9Í̳ñgú lPxv.ÞQE%Ûc©¸SG[’GÂ…ÇtÚ‰DY&ï&- œsávE´$ÉÀÚ—Íz:Ø^w¡ ôŠ1Ê{Í#¢­J° ®A³‘4yYìiL'ôÖÌ3.C Žxõž¤:ÉÓ!2<»_d¨ûÁ,"?µ-«PßÕ#¸’” VŸ'¼RFó,@†øF';¶ëÅUêèͤcŸ’2E>ëæˆÍ~,óø&ªüQ ù².%KÀ¼ºLŽU^}¹-­í' ·ÌÊ&¶2Oö0QÀ¶’À¨|Íf¡¯G"ÅdâNE ¤É:Sn] ÐÛ¢‘J›ç1©8Âó~HñbÚÝ…–\hã8€tÈoN4uÆÖoh~…½}AgdVn=ýªí§ôåéË$¥ÖªÐ$Ö'VÑnQùÎ;`!‡OgG B>x8Kh;XÈÏÅž’)w[_r+%SŽuBõR¤’<m÷ƒ|‘sšÓ¢kb¾¥*ù5�hF_òL‘°1$HåUePUQÓ¢õLŒÀƒ×j'Ñ ­ô¬=j³¹ˆc–\Üž!vòŒ“Âz¿›S¢…uÙ”—œ`ª2wgõ&‘Y"õØ:EžD´è¤´Î5"{=*`Sxwœ¸oá•ðUè'ÍJ_4Çm99oN¯£K)Îi.ßf¶gWA-ö€gªÛŸ@h³ Â}LÂl`bgª<Ø š.ëÓ0 Z&Û,Ñ!â€ÁØAJz|ÅÓ{ž×6d!¯¦êƃO¹ ¢ ´•ÓÌ­ÔW9#õU1ãΆ£DÏ2¢§cLÊ<{` BR²8;dy†ƒ []b:Bf 5ïL±RÞ@¿Ãä* ð&h]0FüæjžHï8s¼>mÁëŒC.¤”wÈ-ÍÊ€‡OÞ蓟-zÐM7/&õ¡Œf×ó|Çðœ _&-pʼn=6#XEJË”U]ªå—OXßjã¡Õä#±÷êZº³yyú$—pÞªêí­])$ц#Ç\?Žë§Q«/ŒÇ…Þ@é÷é ±¼´ gZ¼­}¬—è<Së½GG[ÉÜf‡«OV™´Ä!y¾‚ŒƒÐd=M‚Œ°ä‹yižÅç²~r# ÏÓÌø½y@0koÑg L­F£ÜYGNû%i9'^{½&µ™¼n{*ÐHþºù½l„á ÷^�çÈcLlx^œnŒ»ÍbæQÖɈw?Ê#¢ÛàHš§=ï0t¸Æû,ÎTßá¿j¿({ÏM†¸f(:Šz(‚ýÉÕŒÞpy·¾2"k�}’´ÈHqbÈÃ;Œ›ê �vú”AÞ!’_”7äËʇ‘(ÅI”} þÞ:2¾¸Èzø²](�lø®j'ròpìPpäµo¶Ÿ`<$!ï¹o#¹í°3˜ó-3¥‘ª³ö¨dÂk@3V(W¼ð£J°›T+t8Ä C«RÜ Oº­¦‹Ý{ –ìO¥Uxkã•óÓt¬w½ê³2×sŽÎ*¸"Ýaçª$M²é‘§A7'˜Ç–Ø7Š*Œœ8Xd}KYp µŒÇïV¾q6øÂ9ÃyTNx½_DœìT­Ó¸œ¡pÓÌLËK|õÔ$ßñˈç¶òLȇb)†ã壺,d¡FJ¸–çïæ¾yiø$6…Kß ´Ø{ò¨¦jBpºœ®g¶hz†tÕ°¼w†7\/ì€ËÉ$ ¥í6ŸÔÅ"²~D±ýÜ9ŨœËòf H¼<‰ßè­&øí/Q&­J{5 `¦.¤2ëkŒî&‚ùôÕ<óSv³kË ¤á;¸ARy$³Í¾�‡–Ç6Ï€<àBû¢ú¶·¥7QêC“´Ú¨EæÄ‰ç#;k‡®p×ra_º•èt[&Þ¡ÎZ=¯ê »xG–ì{° mS*'§‡€òŒŽÙÎhKïu½B ¸¬ñwl¹Ã¬±S÷8æd·å7^W±´$D¡ì¡ïÌ©™usáœAYr!£Ðg´j²xâ*ûÚðø–]ö‹»ôž)ˆKˆô™ÇÛìA®À–J" 85Yϯ4¶E•¤Ó˧.EÐHv… 5ÜþߤE¿„F-koÇIOãx3N˜á<ëÂ…tÈŠSê÷êeÇ�B¯Õ=d£— Ãr†T…hœùøˆ.ׄžË<]ìÒì©n‚ä,;>|(@ˆ„Ur~úl÷:²¸.r¨G¶À…§]Lx•ôÁX%ãùt“s‘ž“µäTž0nÑá,®\”4 rÇP;„ùÓ Ô{ȸgLFY5^'©ƒ1,¬ýgÅŸZû�wÈ ޏÌLµ6«3º˜ßÞ8½ç}ïNiL©zμ XâL�¬M`_ªÈlã->P»›Ø|#¨çr¦œ#÷äÉ�ø3­Ë½«ÔÙˆQâTKëð¨DÌË…x'£—Æ’ V6Oü›gÿâye°Ñã%¤›õª‰±Ö"º°°:êw&0ó|ÞRvš-–a›PðæS¶ÌÕxޏQ'ùJ”w–ñâ•XêÁžbÂäâ@ŸC+TRŒ\~Ï.w²¤)ù½f Ú0gaCv‘Ñ-�rÍaLF/¤”'å†tT¥peé Ä©2ofÉ[xlÜUÚ'Q5X#qêÚ߯<Ú€-wsì~JñPί<©cÜÕ^ÎU<Ù%ÐŒºW.þÿþ옉ˬ Üx Ƥðõ<yih­ ÷ü5sê㢋užz9¾«`IW/;hå©xµ�D.©›ï° ÚU£sž)ƒä‰>4Ä9Ó¤k1àc&ó|ôçIèöGÖ¹«¢˜å>ç®Ü- ,`ÚÊÄb)£âcúD³Lœû]Û$z7‘æÅB€,5h¨ÄyètáÒ`ÏŒ2Œ˜r©íÅõùpu?¸ äxåïXîœc¸a¶@yÄn@Â0/øm?=Ö´Å“L¿[HRÎ$Äi�jmX(Ì~`«<u3]X@ (Þœ—1e}/Þ ÞÉŽŒÈîˆ ÷­]BØEpîõÝA±« 6Š(Ôx;ǯnÛ2ÇE6|Ƙ ÷=žà é2VÑ·Ì Æ8”62ã™ÜùfžÐ²l'R<Í›º¤­ˆgØ%5Ê•ò‚+\"k"©¬!D�”¬%øŽyáü0À«î9/ÌM‚:CÈcvå×q¯¬h0¸‹‚øB;‘;H¼ p‹å™á½6Ž+Pr\xäh­1áÇ6¹gx9.û(¨,Õ âºvÙ .6d±§Ç퇇¾Ñ,˜·¥üžU(¾A ¿|I"ØîªJH<ŸÛfÁ#öWHD€H«\¶d\žã’bwo¢nRókcª²·Ÿ@?ûºZã/OçŒÍÓ9‰ê°‘9£Þ�t…ncœª< ÇĵOQ½Ï¡lQ¨-Ÿ+£»M€¼_Uܧkd¸/ž+›Í’š×}L4QûFß•‚Å‘8ö«z=KŠ­“ªiΆ“É/·¦"4ã…¤Ï#TÝQÅÄó×u%|ýL Ð›Dðžø{Â}.«¦gx>CÛkeÝ"/3Oyƒìj—ë:½VÝ·ß;Š!ÄZYôB=ûw‡&Msçµ@}Ù-óÖÜxHtG#ô…¾<Y_mÛNÖ-v0ÁU ó4ßÊyÀ©xQòf@;Iͱ¦]y<^×HÂ¤ÕÆb“­Nú) ÀmÒnг'o1üÅÍ\¥|Ó~°Ë]ádÃñLp}›Å Rîm¾'¶¢úÞÍò‚´<"VB3LìË€9ÏÈAt  ا‡ïD¸´¡1³6Î`•} ƒÃØ<©ñ)Ú¼Ûjž Ñí&ƒJ1Tk÷RB_uºÝØj9ònÁ‡Áv¯µö�|^γ|PË=|ð�_àJâ‡/œˆw¯nw^5‚oô îº`v¬ŠÑ‹‡ÀQ“ƆÀÀ© î·‡p»ÌÐr¬)ÇÖØ Ö.aS0`ª\cH.NHÊ1 cá© Óäïè*gv*s0tAa9Ì]áÖûÑùò!Iu¶<ÕàLò,ê¶h¾µãàd/z~cÏ-^òÙÜŽõ(å¥l„¼NµÁžCØÞ ¨´=MÏôè½×(LLÚbÒæªúÂÁ{¹¡På•= Où)Ï¢Fð$¹†ÛäÚ ¨v}Ó„ é9ï<Üè ¨Ðz@0*êwÙúj‚ÏŽ7gäÁëp ìL³W“»áÍ*q3÷:…ý¥ë0¸¢µÉ]x÷*,)÷ôCz3ù\f·U^‹%8:ˆZØÉH¥,Ì£äO¢]¾ˆžB<ƒ¨¬|Æd…3ÊÑÞ•“$ao^ÎÈ„?»÷šÆ¡ádz¯æ!¡Šócuz ÝIZC)üÐnMvÈ4úJÍŠÙ¤Fb¾š G˜A¿‡©š–Î+~ÝWpKép%*XÞ£1½¢ï±g Ÿ æyóM¢Ñ4Ú5`f+½”R-bl¨U8‘ƒ)¨‡œ<a~ûÎpœ¤U[JÉTÅok,s´uwÎxo_°x4Gù Å Èÿß¡aåÅZc?/7kïŽá ‡§Ýî NFÛΤfoz,ß›<Šz®³xw‚E†©šw ­΢O²¸XÄq‡âubâãNêyð.ËWÔ…ßÓ07­=íöä>¥†íÉ×Ý07žé½Ðóº1ð嫊äê�—¼µÕi µ(¾”‰ŠIàò•"â{}Àܘ^5@Å)úfY“ˆ’!aÝŽ÷¢ãHuD¢Wö4¯õ=Ô'çôpám†;Áƒïªîf`±‚:0dYÞ,«u;’ÕäÒªæÈÊ8 Ý É«~Ú,6Yoân0ãöža.àùìâˆ=ÅG¨lØ•²FVõìµRÒÓtâ……ð<Ì_pÆÐ4›Ò ²·èDêz]˜ñXFJO»à©ä›8y¬Ñ¸`b-IûT’B]ØxGÚÛÁ^¼#‚Yt”5S@øef_²Øp!Ùõ(žêª‘¦UgÖ“ƒµ¨Ä{š2Úb¤K§¹HÒÛ²iù€\=¹€»º �ex\°ç¥¿j#º°ÌãÌ K£à0 ¤L¼÷iUv5 |•Y¦o×Û[P]4$eº(gžÒp~‹÷tœÊQ¢‚´¹Nq ½·Gçü½„‡6|n0ëá)þÚã¡Ä¾ö<)A!|åú¢å,üÆ’ËŠfìÝÙ²<tµ›8³q½‹bô(x3d°™&P»[ûéø>n¦ËµêŠ(¥J ÐX,ƒÔ;&CËœ P~ÁÁreÉgc<³€£š—nÇUc)L”W¦2„$ÊT Ž,í,3á^+yŽÇŠM;ÇfÌú¦sHZÝ1ø¾GV¹ÐÕ#µJ“FêK{²a™„$"'±§]â6³±²ëmèC ‘ê.ÊŸe0Bƒ[쥣lòX<E}gyÚjl[åt®é«eˇ$‹`Ðøà.ÿe:5B´y&„Ÿ»`ØDC•”bi 4w€`>J4×™..`t;Ä¥yÓe®xîž³æ $ñjÐZ'|ZÌÇ™Wòf(cyrúÝ; —µ2®B%ν½_?a¥|%€1´¯ç€ pÕ ŒusºõÝR¤æ„Ý›@¥vÕŽ¿'ï5Lã ‹Š¨5ìmz °“ãÆk ÷$ß΃H Á$Ç8æG‹^i[$=hiÄ]èh}„Cצ³ÙÇ {$¯SÑí…ŠJžx© yFÖ ì@û@äê‹zˆÆ•i»ìnHÇă‹FoÐ쬒´Dp:¼Ê„u ‰”†jß}€] š-,0Þ öÌå¹½‘›o5³G“Þb>KÜï. Dña&¾ŒÖ7š! ¨œîo“ÍHyrØ6¶«fí­ĉ¢M^ð3|�U²Rî;j}Áz1°**Ch~«§½`NÎÎn9ª%m&JVâȾMjuÇ%oAú*bª×êA×"\¨H ˆÄƒáÌ+£R$>*áãrzÚCƒÀæn’!‰e¬LÇ8´¦ñ#ÎÍØ|ðMÇòJ¶-<ïYƒÄ½˜Š Yµ¦8vôÌÒÓÑn&9(\ª¸èÒˆ‡×ú’jÐÍ D$9Ÿ4XùÎÒÒJ,`oI‰¢­…²{.3ö6º}1-�_Lkvª%p"?—šfò˜`“{±”®DÏJ¢‚¦ 'SŽÀFüùìy³","^LKcãyYváKäL¢gðZQÛ(³ã«Ô}FÝöÄ÷-Œù£—yÄU\ˆoËÃ] êÒ´g%t¤X‹¸º^wí€[S‰ö^3…Lm<°BÎ#:¬×Ò£ €}Û¤x•èûˆÚ[ Ñ,ÐKÎN<Ãˤ¸á]»¥ý ‡¬#k‚ZJpØâ2ö´ð?¨ãÖxl±†:ÊRøø•ìöq šÑˆé8 ®H«®0RÒ‰9dP¸ÈÃr×›ÇÜœ™ÆÝ ¶a.¬ Âòt¼oéÐáÅäeWd"›gÞië ì1¾:í$Dº×n#­¡ íkã{:JýÞÓèÀ\DÂÍêFõ#™Sô€ØŽ÷æéÐÒ¡Àí–É[È+agÍèÞ PNo9ÏÎÁÑ'åÙÀ3³\Á ÉzñVYD‰£7ÅõYKdÏÛ±7$“™ó^D fŽ»ó>`·0òóCE6Š;pwS{NM<Â#¬a”@TƒqóVò¼V %k ¦²-^0RÏà ÙZ0Ïê“@I#yÔZ*O 5ÉßFÚcŠ>yú�Ç+O× –­ÊßÞ\wʆӉtŽr‘§óÜ’bözK‘6oPáÈÕŠRWíÒÙjÜsóógK§z^8]’£Ýåa6ŠH>àžãWdoM€8\OOW<‰ßI»ð[xr)}ÎÀ0©.¶& œÄ;´‹´+dbƒð´üË Ç&Ó«¦à]Zö£[·§ÀØØF”wsDïdºÊ„Pìü C¹:öiÎËëöW 9ì/ÛËóM>è5²®åE^DÕGÏaاWŽ3-CMÐ…¢â)äð•ÞC\<dcĨM—õ¨Gþª¤BÔdʘûæjÿ‚:5s`ÅÄ’©]û:ûñ]+†Óeá‹%gày®!=׮« gÁ½w*ã2VbL<ÁSðŸFk)èAìs©N ×|Dú^¼+e“XÚxÄ{ƒæ¦ÍXÚ<ŠÈ¥^uíApY3 nó”ߚ̓P¨Aè0ðLJj—£ÅÃ.Ðs=µ–§Sd”ôNÀòH»9.,\Æ ±a4F‹ëÐ-k„BMÝ‹K½'ÄãÁPø{ÿR½ýFѪèÙî«5¤u»ž‡»à›R]š"J°.÷„ÙÑ`5ŸP¯ˆ0ÅÉÕÍ£ seŸ×dÈåî$Æ]]G¢/8œo7P‚ë«<«óYÆpɪ;³pêŠÐD‡y¢Zs•—é\OzBŽÇOûzѶŠ&|U*YEM|àZõø»µƒAwu ï̸|Ø}ì×±O±®Ô¬2à-rÕóÄØ7ЭÂõ¸ŸÔ„>”¨VPe(KAcâr.—ÚíØC8NõVŸ:=‡ªõNG&ô"M)´g‹Óåè½ؤÞÙÕ7ka38’È+‹}Rýº7—ú¥¨¼§F>7=­ÚVì§¢jfNÃ*–v–é¥oDvš­ ¥¢±‚ºIL˪n=ï`˜zó–ÑA³D$d‘€á%Í:£6÷:nÜñ9_]ÄÄ©Åðò1tÍ}weè<ô$0*FJº¶´€ÒÑÒ9³J‘ 'òò‡cÁ[1§Ëìg¯nÛ¸›§(UÜ vdtC@° Ÿ•<g'‰6;œˆ€.îmÙÄ r8Öõ#&1åÇÈõÞ‘â#ƒ$Ü·62äãnL%2ï°Ùñ|ŸåÆy|¯ú1›ˆG†pYB¤—›á¼#KÌäò~)ýzKŸ\S‘Yƒ½qN屘»Î�÷í‚÷I5ÚÕ`]µö6$ã9oŽ5èKL-—ç%¿‘œf¼ n_¡S}ôõé5¥»(ã<#:?ÁþÒ5Òáö€xßä,vÍkÖgÏ+ôyÃÖ™à<KL†Ã{Ê/6¦‹Ò]k†BtסÍÓ(Cã BÒ ÷®˜‰ö[M<[XâLqÊZ5ÃF[‹=\r~¸´ÄÖ¬Q)Ô¤F–¯ÞòÙ¦äØbߢñ>ŒÂ{ Ö5«WÊ«Ïz-¯˜øÿ ¢KµGÀåû ¯)Öü�ñYy- +ݪjÇA=¸+öÌ›ÉÅ¢Kæjš¬<©ãÊž{¦žF,b7æʦö.8ø4ˬÁ!͇X0%“¹lKßø´ufwVnjp<(™ÀärÃÜ…²U>&ãIó™{Ú³ÏVkBòJ²Ÿgíx<÷J;ŒxæÒw;ÅÏ0ŸÓò6&Þ!£âf°&¸e#¶ðÍcì=Fî÷ô9îé#Qð „x6ã±]·/ ß¡#`9•M÷fΘ¡ö•í&½íÇïbrl$êÑqž;3;bOº¼Õ·kJ/^]à{íá=ŠåÄåè^S´Ã$Á'Ò,wœ�üBsÈÁ68•³Ÿ¿ç/™iFúém7ÖËÆµI†µH±éöÇæM¨°[üð©Óèª+V©…v— ­Œ‹Ñˆ/ÌC,¡Ã²K˜Êذ¶²X{UðJ ¦£ü�5ÐíõcS=OòÓMõEã=5*6uȬöë^Ãèq®–Ùv²ö{Só ÈÕ½:@ß{YVš:µŽf‹¸C¦r½9oÞ”µ³XdÑO§0Ö¨n;&çT¥'ŽTûÌ8íÄKžxmuÊôŠ îE=ª“EÂzO‡ ¶œfžôݹu“¯˜¤…†¶ÙT„6½¨S襬í éjWHfF]Ù>S¸kz8ù½W“|a}ØJÞ÷‡?yðFÆs´Âïõ{h1 ¥Ý爹hÚS‹q'uJ(p&Î|­rø•Ï;ëh�‘âº'UÍó_ø"ûƒ(˜§ûZƒ‡»{‹ >)Y Ê'È^2ÑîË%xoýù cyh‰FÛÞìéÎ 5ÆUÊ,÷�n$gFCcI•ùM&Xµ«_V×Þ\iµ{<çqáÏœ¶–³f;ÓCµuÅŽ„ |+ÉöJs‚Ç‘Hœµ|Ü£œ˜þãúÝPL<òƒÉQrëñÞwº/¸öüŒìž&b\qvqÌ#멵“@9O †aHÈÆe[rÍ èa¸5NzÈY0#óå3IŒ|P5‘£ÕEE 9Æér9b6ØqŠ<ÂlËcý.ØD›/²5UJŒ@™ˆL‡wj¥½ÕKÇs]mèÒ±éèmÎZ¨ ìð%·‹¤)nž¸$íSáa#£wÔՒ΂zɆVÑó6½É Yæ ö:>=Ðð[ÉÜÀäCk7ã;m“ÛQñ&0¦8h”Ü«œ2h‰e/ÙÇá­É'gL®”˜ôs1**˜\�¶-1Ë~]“Är4kdƒòLÎN"=o Œ¨;¦2œÉœ™‰4ÍžÝÄ*Øöš!ëZÞ¾ŒiN4 ½‡"°²¾¸ÓȲq0Œçx† '®jÖÈœ4EèSëcrR´$$Fiï–3<Ÿk=[EÈI'Y÷Öœšp=r}£,OEV x¾í—oðux¾f²†”tÕ~»Œü¢H°é(k½ˆõ gLŒ?=J5–.y¤:t‡˜õ&[Æž.2²4ÉÝ+PoºˆW ] eÝ<O3u_4E›ÏÝÄ„.? *¶”Þm]–ÝöÙ÷ó»ûàØ>~,íŒ ÝT¶Œr 2îóÞ³EÜm¨ŸŸìÀõË«ÒcÏmmœ2̃Óü“k¦/®câ8ßö(–à™>ºw\˜«ç“û¦¸ä²<ôµ ް*ds™¯´ŸÕc…6a¯Ã¾­9‹ HÖƒéšC†‚¹~þô$ezÊWI3g^¯ )AŠS6úAˆÐ<gÐ[×|²û RœŸ8íÐ ¿ä¢m¡¼¾˜íi^oîÁrRI‰aƒ€IÒB&g³Lže A»¸p_c««è®+Õ ?K´”Kãvˆ&Xõðõ¿`ï%GiLû±ÒëçË.…}Hý]Ì_BsâMÜU¼xóèç|1¢(ÐÒ*n^Ê6»^ÛùsQšíÔ8ðÅÑÙ¯ná*L“'22ífF/—Vïd/θQ†ûªdõñÅ �f ª=•=Á”_3YÆÒ JzUI6Tœýâô=‚ ÈUM5–<[áž+¢°ëÝð$R”í‘BмU¹ÆN߯ÎîŽOQEÔü�ñåV­ j²’H©^ñ¾f(@ky³„‚Aq¤Å)<Øç®¼í^)4É…¯+>×*4—X«4‡'z@!éj€£ Þ$UaÔãeoÌ^.¢/­¢ZLÂÕw<Ù.ºky̨èúˆKŸ>~=W½3åxîãØ[([§PøØä1VƒÃ“$œ ?óˆ3rX‘h,ÕÞâQ¢v†—Y&õ²˜1ñQ*wïá“t:;!'Ä7XŒ¶sÐn›µD¾�àÇa ûŽG±"Ü{è®ZÂ-na8™=1}!͘Ēßl"⬒†!J„!‘g=¸z§\.TÇOg콘²ÜÊ]•gFea´líÜÓ{6^mŒØÏ`ŸK÷ ’¾­E¹ UØvFûýtˆê!Þ‹{ÞÓ%®+-Àöpõömž,4‹ŒÊ¢¾x¥Ž™ -{!/»Ë„öy_}‚-ßF|áîÄ1®r8/ƒÞ°¾÷ÂÌ`-[iÂ7˜ GSÒ™˜Îî©Ë(d:ߍÙÜVfK(Å�ØV·æ*ˆï¨È¶<Üy¸sblÌÎNrú,Š×Ü!¤Í©€Pqup¡„±ÝMóÎËÊŽN£Ë)&_l¼¶¡òKk›ä3`Œ¬ÎRy攎=Ögz¦ŠHÈ󼺉Kk`ƒhÛÆëâu(­Ë yîDV2îT�ùÕ5s½Üa„šˆÄþÙñ‚h—»ÅD>SÉeÚ$»ðP#E%@:”W‹ëèsdVbÑ^°B<e»Cí¬ Ø)Ínm I4îZŠxH/b³7Ãõ¥S2Áñ6vUYùÞÎòMDá¾` Î{ÙEoÞt¼>wqµv€¤÷ìTâBt� —W,)*b:€rò„uÛäôêvŒ((¤R7=qY™^Oe¿^W5Ýò#nA•¼m˜]tßWÙQ«N|²(·×;ÀQ>“ÍÉ$Ô[&MœÎë)$’)(ÇÛ!Ãy=·îçK'+é`äc–Ïž-ùÈš7o¼”×ì"W`´zb&å©Î‰Î–“‘Û:ðk{qŽ™{pÖ“´Ãy¯ƒi¦1DJOF-` iE‡,À+!Zi¬“Âë%8€ÚA— â@`oÒ†¤ 0Ë<õNe},2¹ ãL¾ºË¨Œ4‚LEÛR®Ò„Õ4}H!µF´Lõ³½×èN#~æo6Ý ´›O—f¤ºñ­–uËQ›¼Ç;Ç z)ÞÊàÛǸ. ê6œWŒÀx÷4k¼'çõ®»åˇž¾Ü$ÑÞ¥xÕK¾ç9Ý„  ·EOP ËZ£_­ÞSˆU5l&%¾öÆF2ò]šH‹{Ã�%‘¿Ò±ÄŸ©áM[À¹)†%ë!{•¯…>$‡Û“°o²ý“ìg{¬ÃP/Å#ÊF—5V´=rV¸V(èŠgõNÎo`_L˜qv磊Q§Â  T}­…ŒJñͯJeci{¢©ôz#|§M¨è¢DLí»z2òzÞ±:qRÖñi¾èL"¹{0Ìz]v:AÍ!v"Ãy]¹´‚Ùª2¾ö4Ž™êY­G“d"µŠÓà&ïzÌŽÛñrƒƒ°r\"¿}Ò6Ì5§) OZ^õ+‚‚xi6®ºtÿ¡M­Ô R½ÚëÃKÙÂ3çS%©k>ʶ "$=Ó¤x¯ÐñÔs$ÄÙ 9k_’éF™úÙ½‘z5Ac¾O&]N^‡E¿CêS|€øêíîx½·œ{`«”Sç»–8ËÛº¬r1ÍÏîØ¤2ñ©L³›„ÂÁ®,vCÚ–» ø«{•šúѼFÂŒ  <º‹ÒÓ·_h¼6ÅsÔµÊGSªZÑ Ü™-U>•£ÛÖºâcvÒZ4hˆºpPí€`{`#^I±ä {2Úz²]í§ÏÓIzÄ(Ð×=ÊÞ$cT«ãó ¦°•á“xï âVñøÇ‹Ž7ÙÔ>°p-š�äF·”vô&Q^žêÞU¶8Jljˆ‘2˜x¼K\|ònMWZÀ’ýÅùÒÖjß,?Ó£yI`š¶0ìee©×¼Í]X¬ÃÌn›OwzIa4ð%¾´®T|æ"®çèa ðI•pskÛ>.{ƒièùt¯#—©JáÍ`u! â-Ce»Ì¶À€0I;«4·í¼˜GúÊ=ZMSð岺fÔvÜ£‹£Ô˜Üc`ƒ×Tfȵ­¹8ÓÛÌ/ð8<ý4Óê|O&@Ýø]&<„ƒ¦K8›^ß{º—c ø6éeÍ´;î ]ïId“¨8OzE)LN7#ô ¶á¾„ÜL»O´õûè8G¨t)'¬¯ý *ÅÌ{ûœƒtxžmhå%• %5óñà ¾A>y|NŒÀj·+± ºÎÄ5LÍ+!Øñ’D·¬yžñ1´GÅ£5+åѰ‰ÌMxçÅe¨-»2 §Bû&Ktìuw§u×ã&^>�­„‡ÏÖ`²Þ<?s„=p;¡_ =Ø&|ü¨ÂãA·1¡>› ^ö{ÍñR€+'QŇ@›…³!f;ݘ”7׳‰còÛô-&Eýmà• ¥•få|B¢O4s¡ a{ê5?#Zx‚˜Yª“¹¹Ï·ùYÁ‘ù­�ù³¤(AãæÃÇt¥~µdüâÜ[Ø]‘;Öt®^J=›Jä(r{¼iaÛJ6 àrÕŠÆ/§]9-€L¶½mßÀ<, ¾ÌµGÜàõ:›ŒçÝ›V~VŠIýÚXã^g(äK<xÇf×£ýBî¿A ¶zÆ.€•÷­à$ù;ÃA¾*|R¢x “˜xÔT,æ‘´ðÜ2Œä­¸Ç[%Y— ¬î8ðÙ<ôØK—<J¦É'9N«/Ò™îGßí¨®Œd>„M-¨÷¢ÌÞvmœ:½È9»´ Ÿ½iH>^—Ñ\ò±g½xñÀ`¥r¥a‚ñ\òYÓ{oÐÁÜð €´m“ elm ‹^=Ï5@Ñe*Ë¡d£º3ˆ.Úëi³çXšKñì€$n2Þtƒ¥ßë­)¦$—(CÊ·ª=¨wŠé„CÌÅÍ:q#/«l¨TÑ"7 1íÉÓñá(sã=[ÉÉõP†‚t9ËŒyJ .¹´ÏŸ+y,p›Lí²RÅp b<†•!’[�·°ò£w–A†ÍÐú^‰ `Ñì¨3Ô°7²  ÆEÙvØë½}†‡ÞpœñÞØ8íŽ^£³Ð‹Œ{ñ’9éŠä¥Qµ±ŠÄÊÝ …×*í{Èàb?Ù6ùb›•ÆßØVi{NÄ)jßâ ‡`î—~V^UiüÈ{/s”Œ¸¡FƒÑ9)ÅùŠ›�dáI´¿,²ôQå¼L)²£Œ¨ÛQ~òÔN5Ñ6‚³#D1÷Šòâ†ilÞéU¿{©£¯!l«¹8¡ ÎÂãÄn {Wp…Lï ½S¢Cüe)‡Q"çªXÇËš=+5v˜ÉHéìe¦6E†{ó9ß=ÓžAÎÂÇ^!0hûÜÖÁo ´žQY¤¢Í,>R,»~†ø†ðñÂðºñ$Ô}G:à²Bê8¶yÌ»ýé£~×^ÜAР!YîÄü!ÓS^_sä‰ñ¬fÈæÔM>Sˆ$ZÀdޏ„�%1e´Ú Xz« K{õÝÄ/ñdz…€Ä´¡ä±B,%œ U¢uåI!ûšá$M€¼óÕlÅ+¦‡ÁÉpÝ*‡κZ'ñªfÉbù�+GâeóBi½•ÑÑdÑŠž&5snžÇ¨¬˜OIçæLŸìpb±G@C¢çf*aÛð¨g.ŽÇé[Z³ó|HT'-sìwQ(¯jdÀeƒÂ;Zò°Ú8 ³ jpJ×|3` F*î‘-1ùY’?Y;’b1È7Ê8Õ:R0FÍÚvj#ëáRµ`Iâ«ñTx)šQÆÞ"-ª3áZuHÈ¢t,ó]{žiÓ"UjÅÖ8Wúžõ3O­«88¤®oûE•R©¸OõabqÇ{ï•›÷áêEŠ .žòº aÈ àŽ©Rï¹§Cñžj=µÀ8Ò­V‚Þ³yx#˜9ô^fQU»UÄ+KÖ–ÆôòYë÷×½ÃÓ\0â‘¿Uî#Iº ŽÃÜ{‘0ýü=\()S¯“à³IÛÓ@¤½g7é }//�]¿lQí–›ð`è×ÏðùàÎ`Ò²Ãýè îf+¨§¯K•jB`{ ö¸ 4^£(šÛa=  r€Q¯Þ—ÆÖøèíª¼,By/ÖïaÕà<÷aíÉ<ÝL « ¼±z¬ƒ•ucgÈ^cPE¸Cû‹x€�BÇó¥ð[RGL]Ý{¸jÈ3C�Ž¡­OÖ*ùV�"úÑV“.=m¤rºdit`–ñ¦Å<°EŸcBf¿x¥6ÆxÚëE=kƒ8øÞÛ‰KVÁÙ2ÓúÔ¯G/çyÃtã³v�Ë�#ñÃÞ»>¨N@­`ºéìGÈ;bmžü^6# x.«4w ¥Xc˜ c PÉ£2Ö­y%žóÄÂnºš3“gH´àFÞ ìsØF8JÛí%©÷Ö:<Xж·2ùOéET… «¨r`Jˆ¡õê¬È ÇÞ¸ÞÐpå‹ +n—¡Í cºbî:]™Fšw¯¬5Î)—Ü$Ù¬ŒƒfK9Œß0qk’ØV½ô·ý@|®·q:ljãN 4<›q`QìB²Õ<¨¬œÖ{ô´ÆfŸÀäº.æ#äŽUÊñ% Œí×§#­7î^aölMËZiˆ•ouxPˆó± KÒ1uAl™Ú51ׂÂU–D ¸‰pÜ‹R› çn{×bP@/¥|é<ü=TQ0œ9%SšAÉä÷LfWÏÖ¯;ÉîA¿Ÿ{æÏN6·ýéH2-Dù a0YepÌ=@çæŽAu€¶«Šç¬×Ò]t²Â8ˆ±é-7;j‰<=&vˆúª&呾w™Nq^ÈKí“xÏ\ÆyÅÏ °ÐÁj=Øñóc e_‘„S|r½Å¤¼½ù˜QgLu#­J#¹ìê ¦¯8wøc4c]ß«Mo­J€¡™c†Íã)ÜHƒG«U7£7xžÈ°ïa|ÒíðE·ÍòAñKc×xZø�ôö@¿„êPT#KͧÅk!ÆXeÒÏXw‡ÑN‘Ñ7Æg‘ûARV‚$г¹ê±®8(y½g‰ëI\*¯½|,a ЇkƒßCƒî”µ<�©¨ÓA]ïú NvâCaœŒè^»÷<)–²µÏ´æk¡kU°µ�Mžw5½|«*†aÆ bi‰R‰ª;dZcôêhã*ƒ)¸y+± êM •4y³ë¢}/þÃû4:-«eîíj^T §²jçšæLgh;¸Ù΢iÈ)Ê›•¨ ô·rŠÊ:¼{MpxqïI¹å´èù,“)Á+M.!âæz°‘Q$ÞTx¨çêϘÛã( %·Mß¾•îœŠÍ /2QØè¬‹RI5~aE# ’IÅõÇÎu#½Ë® fï*p£ðŨ]´y´0jö27í –‘@çT-?P$¡yœDÚªož¿Êv í%¨@M¡7[%A䪆äFF“/Ÿ§¿ó…WÒuN,²v•Ü^òun�q€4zŠØœ S{h*ãtfùB«›b²Q˰$£�ª¤NHWf©•ÀÅ1 ­ŸawddI2ˆºç…ƒ¢C{N]Ï£×Ã~47MÒérwçܳ~!¬‘­ƒ.>Ì®%›—±Œï"âÓVÞÓ|×ý$å Þ�»‘Áóö|O wŸj`[_Ä.=•ÝÝ|ÓqÅNGzª <Ê;t11“Û%ˆØßÆc4Žâ·œdyêÌë îp×)[Ù¢÷FDÄnxëäLSlh¾Î˜äöƒêà§æ ,n[ô²NdP!Û¦¡8¤ » >[+ÇÈ÷NUò7H€^:嵐)-¯2ýF5 @JZ´o3ÄSÛ™÷æ=÷âžœyî’›=Ê¥ÀŒ¬�Í#9yw×I›¹;ý·îÝbR59ô´¦'œË4£âÎ5q¶Ã;&*ê œf¼êñÖkQ7Ï=ײŽr®JJM'"ÀsuÛÖmzWäúR“b õˆ¦›ãÖðt±îl½$»¤mò‰×¾ãçxr÷.}9îÝ[—dnv3Ú€Õ…dÜ! à ¥°O4.«ŒÇÛªêñø²87D”j5ÃÝ™—åìÜÈ{c¬:NÕåÛ’TB=PÕ‡ ½­o+Š1ùùzÈ.Ùr‚üÇwzó uQCy`“*$6ƒ§Cæ9ˆ<q™žk‹Ò¦¦«dz´6ØW†Ï—Æ Ô’Üòbž¸☠öê¹BÁ¾ç€Ä�ÌÓ¨Ëòà=Cì(Í ÇzØQp<…'áÜ©uüÞÕ£zïjˆRÆ ÀõÝìÛ(t÷WTv|ٞǾUÚy]ÇVýÊÅJ†“Ó)^Jí³DSOTyÅtÊrƒÜbV‡ÜÈ�|ÞÊ]ª Æ4Y œ]l1oýõŒá曲ÑphóÈÑ!?…Ò’ˆäÇ“‹LŽØ:yU;ĸO VìcNÑKÛ}/KvaLº�²ß¶ºå0×)˜‘¹bDÆ®€L®íë¼2®Î÷„RóõóyÁ\ =½p^ ´lfW MYÖNf‚ù¤V/æÀÐ�é±øM[¼îèIŽ]ꃰpxé;©³Ç½IȆñöEâ;õUk!£ãš5™„Ϩ…ïA iXðPŽWÓæ@›CÙÖ*oÎí?z(|+Ï\Ð='÷vÊRã=˜°ÐFs(.âQi Õ°×\éhæÀäŽI95¤Üia%¾ó ’·4Ž—¸ro¹LöaòÉ¡»ú€�Ð+Ñ®«Ü×mÒHZn¯ûX‘[à�¼©ÃJã›Ô±¼òíé:ɃÂ@MMÝ Ïaüä;ìs÷.ó*ϧé–9jš'v´f2–àì´Kð>SÒÁäaî­‰%L­ "C‹gé ïúñô¬Úî-”¾ì|ÞM/ í¢<ÜÕ³£_šÞ‘¬™½§ŒËqú¨VÇq‹ÉDIÐQé9¾ºŠÜmËCÊ#_õ×Ù`ž˜Ê¥‘c'M¢EËÛl§ÃoqxŠ}‘wŠ¢´áäìÎß9\{íK"½#ºªh/+œÇ ­Ï†¤úi•Ã0LŽ9˜ŠŒ"äYËs]'Îæ…òÿ�³#gÄÛÂÃÝS³Ùm<÷õ‰˜Œ³\æU`«{-êS¸Ð®MæºÖêÌl§Fp"w¬–tøæ;”(†Ýµ£Ûõ{wXŠ£YÕ›¹÷ݯö¶œæÜšAêô è´ðÅË·Å*±û¤Î\ õÖP«ße©EÒúf+²]¼åàx o^#ޝ•q@6$&øP>€.{ÑþÀ_4IJ\Éî¡¿5 xfn,VïhÂ˵§wÛ…¦˜°ûÕsâñc¦;Íz-2qnT†ÃBœf»I%¯£ŸŸŒBÊ ¼¹÷2Н:=]i´k¡ æÞô>o~p½Ïò¶û†KŠÅú…1 Çø „`}—%9ËÏ™FhüºÏnÜ„¯MËB§žû)k=ƒ÷–Ï¢°¨ŠjȪé1BÜCŒHuPNϲaîȧåýF„8™a€[ë,©¨Wøè)[f«OÌëtŽ÷3Ì:l½hŒìµ{âOúñƒº¼Þx,´(úBçõ!ë½Ó%¿dE,ÞëLòœD*?¢¨Òu CMB¾I¬Ç6™PèûÞFN¸q5Øl§QUà™0°Òº¾L÷rr‚c#©eØ—5ô\×7Æ’»2Èr…””_΃shì[‰~ ‹EþöäÝš’jæ x›õ`™¸Ü6ÚÓÃ|’×Í{òÄJÄ|²Nßû\A¾�·ô‡ bÇæû„ð°ºO&]ØÅª}Â;êÞÄØu‰×5×9Ûˆ´\ CÞÓ ¨Y¶|tnïÔÓ`ÎØe\Ç ™‰,›r+Õ(ß­åÕ˜nçk‘xo†§ŸœxپĺÑn™>’•QÚ U_ ò‚Íözòì–»×2eîDLÝŽÍŠ¯ )„‰¿ík¦¤GïŸqÑ#ÍY1,dU÷P•tgëèS®yöN¿QE—ÝÄ,>åxÖâúáÓ”¬Í&Ò²c$ÐEOë¡ñi»¹s\>¹NIP-2]_ŸE·mVˆ§ˆƒtHZ±“-fº·´‚³w7rÛiÊn©6³V˜ƒ÷à=ÚnØ"J1‚Ü<o¼ŽúfúQ#W˜Kω…míbº_pdÄs Ü«Ú—µ¨-sæ-¼–(Hm;{~Cx!ƒ¶-o„мÊ“›Òß²8+�ôö³xÎ:c–¾ aS!œ=TéB’o€±5˜¨93 ±¥q!²û¼Bð&©÷.›½Fø¶xí �­èDCà¿Ô³–zêHáöZì7|ˆ€šÞ‚û¤‚1ê[¨•|ídì[FòRcP ¯:Ló±H<ÄÛÝSÂ2l¹zy¨èZýÚÂàšLßó™pCä£]}ûß¶ƒ”$’_œURtSa\÷£3ºDµ®åÇøjV¢vãÆY5–‰@Ø_Wé Òñ¡£Ôů¹SK"<úU�»JÀ[Ì'~« ¸;iWüŸ÷êkzÌÂù<¬¯’Ï›¶ßÑÍrÁ ¿Ú›4 ˆd9¯ÙݶÙÉ ö¶ôãWŽÁ[g\H˜¬4è7˜:Ÿ9“cf@óçSÉöÜ3”i†iÏ!ÛÌ*ñäw2B+(tÁìÜÛ;¼Ê u!‚œå¹&½»î¸&à—œ\RÜd”³Ëi½_¤7´Ó'áø}º eI’‡R#µüÚ=yÁi'_g ª4CÌ«±Ó=¡™Êª!b êIq/€ql;3ΞâkÔ:™E¾hWÝôñ˜aoêg83° ½±ñ4ž0m$Öæ‚QÏ<ܹ¹Ĩµô|ùn^/,!ØA{AÖÉC]êß‹•iî0S3åzôÀY‘Ï÷Êm%Z‘«žzqÒ-áaƒV17?¤ëv<Ì=ËiÑ‚u§—Îp«¢}úBÕñ qw©n’_hÃxÓEk’P1߈ëh®Æ{‚ôøµÎs|¶¨T£|eZ¤uê1sñ&hWŽ\^öbiJ)jBB>y‘#}§!Þ’mŒ\7ßsö¨Ócne}½8ˆƒ8K¯fàÙ#° ÇoÕý\[ù¥Ø‘=5xäâK6!£a„ä`ì‘Ñh„À/7&pÄ &ý¶&ŸÑkt<ߪ÷NxÖìbLöp^—™-òeïV¿,k臉— sd¹’} Œ_”ãÔùÙÛê¡ôylÏlèÚdS„R*a™qßð6d¡¡×dT¼”,Sµ-ˆInUÌæ£‡R+]’-*³5&Û‡Šègï‰I xú[÷P#‹)B4_Öm™;Dñ·Á%‘~¹ë»Ö|Ê!ƒÀ€Ä]W¡Ï:�µ.&A˜±#OÔcèõšÉÐX·ïÚŽ©–¹’D½‚â‘ÆHÐm`ªä#N—‹„ÏŒžfÒc,¤×¢2øª†éÞ‹š!"ìâg’@<â‰GM-„¼¬‚˜oå€ýù곋<)— ç3ÙARÝ}‘baÏè†BÇ;~r/ûˆVÈÛš¶’ò½ÇyΜ‘¯°ƒ jûÝ<÷)ã<粈ÅÊ”tËg‡ê+sí[N¤³ú:^w˜óÔ–½zJi5º‡äÕ–ÃÂ’›ëýl^’,éÛöÄ S&Æ`¡ åé'â_ˆÃ °öGñÊíeè³ãîwNGT¨’×u\Á‡ê2i)ÐôŠi¡°Þ RËa9‰Ã>È ÖBÚ¦©ÉŒO“ªÈÇsZžöÞ2ßsàó^zað±ã­½ä’sɇ‡­D¾Ð”ùñÙÙ##¹ÞôÁŒsÅ—Ãp UC ¬Í%˜†OGìEx êÙ±›²Ë»è3ß㥫R©ŽYb rŠÖÝ4ßÁëÊ›7h¹rw^°ZM9*3wq“2ó^Y?• ÕÁ«Ìÿ/– óšA[ó~¸cA@ÉÞªrÎF—ìt8Û}ÊV0t—¯Ïioãм<}f*aeÂë¦fçý#§…¦LÅñ)0FÕñ›˜=ä…¢ÉV^4ÎfÓuÌ\àš({Ïmg¯©˜ãv>›è BËG¶†É+YZOÐ-RÖïHe˜µ@y7®K+‡! ±mg£R5¤ «úçKb,Aà7Í$Ì1Íš¬î@áUQƒ ×NJ€¯¶ 'w³hué:„Ghú½½®B¸¡a"fÒË|T륷§WÝíl8[†Å†W›<Ú‡|ò×säÔ^Õ™j¾ d FF @âÕËizNëDBà[áýØ.#t“ ó&A¶ü@EJ½(&u„=Ã¥GÞQ> $?ƒU;5–|ŒÌ šWïÎÎA+^I™¼˜®rH=̇¡² Q!²‚»³RÏóùs3ƒDEK®3y/æIˆ’¨ ÷8y� ÅÀó �ÁrµRr;I[ÒóB[É×¹1ƒ:äÙ2=žÑU~áâQ~·ÏdUn{AWjã=%µ£ç¿‰¨™=Ñk¹±ˆ)M–“É•+^b›²gO uó=+{$ÐAm¡Ûλñüz²^êk rÃC]]Ë…åijuñÑÙs<wI…9ßç½öš8콌c«�¦‰=zuR¢ælù͸1®îR*YMè1gQ^É‚õ^Ï(ù>7X½Î|QБ¢”#å”É`µ.ʶõz§kA}^¹¤åž“—'ÐòÈfÍ0ÖÍ8Ý„Ìp¼õœµZÅ+ˆÂ„:”÷öIಽ×Ô[ N´¡Öƒ&ÌÔæ-ILJÍ‹Š)h%aLúê9/°Ÿ•Œv"œ?4¥~iùªwººÛŽiU�wcXå³~–‡P8ˆæ\™q×a‰¦Jhﱨ×ö£‚åè8j$äç·Y²Ïò?ÈiÄ;˜èqï>$LÖAá~HhÈaNù^ç{zà•ïÁ Ц»š=V}l<¡“Ü{Ãçú4 ¹qßQZK=Bš1|)8âö¤,1Ú¸1‹zßaÂ¥…tº�& !¼w䨣c©B’ɘïÜŸó#Zó¬6—€wÆ» :ïxTô˜Ë¥`– YKj˜ËUÀe5_¡e£ лº¾Ã\ëp>8¹Þ7V&8Ds0ž`6Þ§¼”šhÓ �ÞÉOŸp Zó‹›ÖÜáYb™%Μf®›0ˆ4)ï™;&žºïâM¸]9cû¸¾®Ç“ ‘],Ó/Žé²–ôöJej$P’d[µdd{/FêexzÍ‚-“¬ÕÔ¾Ú]KÑ•[ñaF5„€züzQ†:ºpÞ.ïóz=i7H}À~^AËz¯ÆÍ$õäžîªÅÙkÁf˜k°ó¶~¨Fà‰Xc¼ˆŽuud"NE'ìU½`½~Y´KØ<\˜<230–ë'œ¬çúB–k²Æid»ƒ¸ :pÓµ9I#N‚$t=sãÁ¢^™PY/‡¼ç;–j|ƒÐs,m8ÏK,·žJßm@î€9›¦Ô›èVWJ¹§z€¸}9 ;è˜ …·‰Ç)¨åD˜mŸ IÊšÂ<©–· ºécAj@`ÓÄíÁÎVçt‚³Ë>!gûÜÇ=4ò­Tæú“ wd6‡²ïÑL½fÔÏÃ_«¾¦´Ñ¬5%Ø=ž–@ Z\Âêq‡œ­3®B.w  ¤¶#Xj÷ü”\µ}ÍSÊÌ®—&©Dm^¾}/K®p7 ^¬…?¤ ã‡Î7ðL0WJ6¦ðec.â%ž÷ ÁëvÚ,’—3¥¶dì"oc b ¡ zÁÍÔ2·'¹=‰qÞ„,Ý@ÞŠÞ¡ä£Í->‘™su³ÙyŽ Åú¼:ÂÚ_<(dúr»§£¾ï ‘„[1¶,‡zåÒ[n¤¶ xN<HO a'¸B-È�µªQö‘%ÛÈH¤øÔ í{²ÃVãÔßÀD>;5Ã,™°ÍXÙ o&/Õ±ížZ5ßWµp#ˆ×‹ˆº·ÇZ3Fl³OÇIBõ¶¦±e‘#òÊ R̺¢w¡¤^U>ÂJ1…¾KV3v_€¤ô†ò“&˜ª%h[)¥Ä×MsoÓèáeÞnnOƒÉQ ¦˜U#æ-ÂñÌsáš-7'æÈÐ{ k¨Ihí‘ûÖÓ܃Ì]ΩšRüu‘…¶©OÙƒmr[ã¼Ò"‘PxµÌàØpƒ’ê¹²R&´œQ·!Ž·;½ËRÖÈÇ€}yî„ rö¢tß 7Ç;£‚ ¨Yµ®Âaªà 9ƒ4é¬y”ÑàÊo‡e8‚¹äᄪQ%RG…§Að¾’W·²«Ñsq¦Ì“MYe&ü*`\´ÐZ}`¶µ—!Ó¸<ŸJgð$/rb¼d™ñ<1Η¹â£Øow§EKkäbµläõ‹ÀPÛWãä³K˜Ò’ÍÕµ(WÁÎTën ï]sF�*Sï”F7pÂ^­Þ¹ òÁ<qd©÷`AY° [8ß5쩤ûÅI49²m½;“uGA~],Eâ4LÙ ï“r‘/Ê»(‰åD—¶GÝØCS‡=’-2+¢oF;î:qmï—ö¯%Ϲ}½ao‹³Cúô&øÖóX{›tìK*¯Û®cJ9q%àµIÑLo‡Óc„b0W•”|~ @FSZ*Z¨±x‡Ói[¥ü — µ¾Íë›tÝ*ñ=¦°°AÖxA¬Í Ê&Ë›æÙa�Ž3ŠÍ…„6¤µ¾yu±ûÞ:\<¹K¯o‘¬§cσSòMW5Û[[YÜ (¡MÒ<Àÿ÷re™l+ô 3Bò¥ào¼ú½Ç!ZÞiÊuÁ¯®r\C»oóXï6Þ"BÒLž>À::Ç|TŠiv ,NŒ‚^5o²P†ÍEAŸ†’8Hós”Êát‰y˜ÙûAÐ9EÞF6•~Œ]‘ÇÑÙž¾RæÎy¯åBAj`4ñÃÆ\yôHîÑÊ{*`ÏJ{î»_˜™tô3nQ†+£i¢ÜWÜV2¥Á!t†"“/2›{”/ ^KgÙ‹z,ØÎɳþŒœ[6e‹Ë=ÂÞZ<Àç½dÉG#<˜F+C6†ÆFú¦P4=v÷Ê›=3ÆâÀ*¢ä./84-w¢÷y¾óÞ<q—3Þ×±÷ø=àÓÁ~\´.v©yÀJÞïpŸwd¿^  ç¢zi‹õjçDy{Ì!=Òû½«G/Í=[§n—ŠúéLƒÌÕs# Q{’JG[„Š5ÁO®´ì½3»ؠDègËeɲB/êh9ô oûí®œTá„bÞ¹¨ âDn;Ô¸° à‡…¬égŠÓÞ1×ÇáÃéê<“ϸH%´.‹ EVÆé=i°–î­×Ô  i,`=Ù ŠYOµ)ÜÛ¾ òÚxM¼6Ùýbt´Áºx;µïÙ!gèQG¶Ÿè›^WG­t>ˆ(œÞÉÔ¶ äPÞ{ëÛ„¼ÄOUyˆPæs¥/Ì­6瀲pdÚν¼EUZqÝlÎÊ£Áö¹¥ž?}ëÁyŠí{ëCP¬Ìxªãp)4ž˜òÌAϬ<†+kš.*Ñ ¹šR{ ÉëVƒéùBóÈ®ŽâÚÚ4{¦ àîõC¶’y–ØuWÆÎ$• ìB³¹c6°-É¢b­ÇnYOäË×}G,óº+bëÔ{ Õãj²åâ`Éïéò‚¬ÏV¯ÁK {—¯$©–?¿QÕ·à”èÛ‰W“!#õç2°ªòèr'߯A椮³.k¥® ¢nŒ´�á#Ý猭õŽ%¤�ãn£N•Ô‰Zâ¹óÁ*†„ÇÔd;K×õÍ0RÈäêSÊ)µ&Q3?~Æ„1œQ« ãüIhê vѹ˜¿å]~•$öÀ$ù!ÝZéDTY»5—+¯8vF3¯cŒ•žp’@ÁC¼¹¾†Ì¶´ÕsÇ¢\Dâ{jnÆã‚:¥ÛÅ�YdNjî>#¯áª´C33D!ä‘È®tõeÍ3&xÑqX-Ç#œ‹ä×ø@ïIÚoî1œÂÊ1”.4GeAÂ=ü$°'K_ö[Y�V8oðǯ¬»<_‹Ï(°iº6¼TÒFÍ3Ýæ¢lìÇ™V,Ìâ<ºýÞŽ3Õãdh{´1uðžO5A¥&+òvp š¦Áš?|™Y; ‚»"jˆ[3íï&¹”D‰|^«½ZìաʧIjl¸N'|,@ Qa‰(ìQÞ‹!†iŠ”2óÎÍöñYa‹ÊÊà #î#”Þ—F-ÏfÈWPiw×ã ÛOBj×ë‘…„Õ¯¼Hvs~%`N³:pøò.£éuX©&h+Ûsè{ÎUÁíÇ „É0ŠÎ1-žé¢H8q̈A'ÎD@nõñuÆc@Ú0…€W×"bŽœ^®€êu'‰íð<沘)6³OÎ ¾8÷3=«ÖH× hK•ûnõ…Ã,#½Õ,zzúx˜åŸ0‚m³*šïÑŒ­E‘ÔB=D®³|•¶Ñ‹-~±èH}a‰#.1Oç´Ê•ýÝ<ßXTÞgç•oÛÚ]ÂNãJª¢�„Ñ ¡øR„’¹Ù‰€Æ¾%Ú°®t‹@iÛì8�öB w™ÚfŒ¨Íé ÕDe&ŒFD½X=B"/xx3úZH`‡_=^Aº…KyÀH0¯¡íÅ£b^-H"ýñÌÉ•nÿÞo3s¡!»€Hƒ ýˆÜwVÝ#k Â2œžÓzžtyC ²ËøB x(ìfè¬wÚ–¿Óu{WÜ:(ùÂ''ê½MO-…Å×{ü²[Ñ,Ÿ$¿‡D}}á¹ÆS#.4žµmu{8h44ÐIÂx¸ÈAµFlð-ÙhKøÍCÄ:zN÷Ô( r-Ñ"Ó´ ÆL€Ã6œ–Éšß™/Fçê]äò^ö  a°ñÛvš �¾00Òõ#i¶èmèòa—×ä ´[Ê­yàó`(^�ÆXtª‡ôÌpÎ-^£Cl?km†ô8,)&!®jÜŽÂ}y$L—×+{÷¦íTS Á[5¢j4á0oÉÇo¾x—™:#ué”|ÑðØËCÎHv…À™ÎÛ53nS… —JÕäMÜé1fÒ¾fï3~”r*œ¤öÆ7_ò£7ٌ΢ ÍBVGvç5š„$ÅkÖIí¬νlÑa}¦ÌEý¨SÐZß=H^Ój¾‚—«èeúÐLn£i%–2G_N0»Eƒ$v–A�_da£¬\q™û+ ΕtM|tkŽÜB@6«‹ÇUO•=¸x$_´K7¿uhÌš¾,õ0„¦ò …¤§gîJ`EÅž ¦™«•O*XÒê!ó ãBÄCéåÐ 8$ÛoÐýtñÀUZQtdBh¾1ÖâHà´zù_a¾¬¦sb-d™]Us¸¨.Ç KÞÂåm¢ Rñ+8*ö’­‹~­î`äˆÀÉ›U¹³ºq•c-½¨âõ±bÃó’K¿w¬}†µuî(u$ž€#¸n­uS ïñS~‘o çùÑ3¢+1Ïz.™Y)«,isƒsv‰ªˆ,¸t‡Öß…?~ÝõÊÒærMÞ“GbuèˆèoP±.ã^Q]dO'×*¼žCé›S|C]z+Yÿ“~ªêšC}&„oµ“˜1¶ eûI½ŠåÁy"ëe~雉V®Ì"Y »P¬eŽ7ž’Jbµk$-öPqSæµïQEh܈ >eÈ‘Ôg ý¬PÒ BÇWhïJæ*ï{;ІY�O#²®U¬]cj䨓—=ŸOѶÇ>n Tê7XJŽ*ÉLŠaoORâT›?0w#�j$S| 0@“–Ä![Ö·ýl62à‰¼ôi<gÝ*[ö qÂ]`7M­¶Ìy’ÅñòjÏÚ¨ušS^õôÌv‰¾:e¶;gœz{ÑûL¸ÈUAFBÑpdݤìví ìå»7Hz`¬Rš1Ý#å¸1¥‡ë¨üòjcß mSÏ„æ¢6Ùb©X=ŒMÂW¶Jp=+bM¯#wCÒ2ïäð820èMÞ4¿êt| ,©r£¬uÀ„¡ñ”ŽHÄ&q±áâuÐrè„-T¨Ÿ wɶRÛP£øZBJ<&VSÈB|BØ’Ð ªÓ^2äïÌ®ïíäcŠzüzb.é1u•™ã ÑK†¯T¤ ‘Š) až2$·º=/ñ=’¥++»€‘kuÐ `pÅð¢V¦‰Œ•2Ï=èÇ`DâyƒÒ0}翆ñÈôt,1ÕÙÒ3 Ü+޽œ,êŠ%y»²îðIú³/ÒoæesrI^Ö¼äÔeÑ·j³uÏ×¥^BA'¬·r 4M.cÑhCrf9áp¬å"äÂy‰è£Ño­L‚ÓíÜ,ÑXÉ5ú*rð‰A¾W¢D©îÜ<–Ýnkhdö¶e#$Óƒ@9©p¡iºje_žÿò6õÐN^‚£7D•UQ¦7XI'žê{†á1”Wã^–ö<ÉóÌíÂ8¼~ÜÚùDƒâSP‘ãWo=Ú}DØœª|uÛEõLgºlñ#î†dÕ6røuW"]ö˜uwÌçôž«Ò¶*½Ú…>Á½J{xØ$ºÇ\í½}ÜWoÓ‰Œ÷üôd©a€ypÎrX·s‹Vàˆvâ¤+®ðNóšw TâÐÙ–IsÌWD$3r³ ìå[Û¼\9|ì'%tŠ®yÌr»KÎ~¹i LÇ­ÍCäÆ ôœÕh‘ úñCxoxµ«Ö¹d41aŽ^Õ*&áR•Yµª’8Ñ O©† Œ2Õ#[Nah²‰Õê}ç܃½œšŒ3Ý„sãùl€Á®ßÛRÝ9ŒâÒyà¬í¦¡Ôb,OŸØ»,ª¤D¼ºwc0ÉR8%ñJ ÇÇ“!µe®¶f°¦#ˆàIvgÈ4É©¼ŒØwšÝÊUÎu!©D«¡Y*-ûvA)ëB¯õN)ìuÒU½ì{H%*ß Y¶4; ¼‚eA7Ë8}®4'½äMáq )p‡ÌÅÖû†$}ù½Lʺr*¨(¤¹(¡¦Œpʤ°xI;J´,â(«1Èt™Ê/•°Jê9vu颳ʭ%)<J¥V_äsR¾Î ^—ÐxM|J÷Ž}0e߀_^îqv] ?|/Ú^è`g[[³\½Ì=ÈRlqhQ„ŽÃã^Fì Æu˜‡ÕÃWªÃéiíöýâö,¯ü9XäHÊ2™rÁ.ª›‘ùè{T#ߨ»|¡þ êj/ˆÞKÌœGgõb�ßÃx-[#LfÞ· :‘ÝeŠ`T:w¨ÖPô˜ÍüeH‘Ù‹¾™˜¼—C Ì>-ƒ‚¿Ù§6‘Ö á+=yL“ho—/8Èh„¯£+ƒ¸^é†å&RΤ‰kÌI¹mìB©/®º—€g‡,RHz ’è.®ÁàÞ©?ã8~ʵí°U²7Kêø„ žñµ© Þ*› R«Ê¸=áãæ2}´À†iðÈQ+%8¯6ò&îåaîÃGìóëj˜¼>>ú–iÞÆ¦gÙ©çn*D÷ú¸UYŸŠÌªBÉyN•Ìý.RÞ ë¤Ê�SÒês¨Þ9iˆ%Y”Ãg–/Êá]aΙ CÕéù˃|wdú¼ãe) xY¡>DF¼Ý0J¯hÌÊ3ÁÞB€9N_uŸ[>KV+_Fê|‚ÂÅsøŽTçr4 7¨Ñx¼ÛX©2ºÕ: ‚z‘Uy®ÖËž×O-ß;ªmNàhpq¨lÇ1Áó Õ"*³Õj0~3‰„Þ²Þù¸¦ÌË]bÅûi˃aC{ÙL×îHÞ² æ¤ŠÆ÷ÝÎeUà Ù«ãÔWÕ©¯ Gm™£ y.uÕŽ3à€§æñ T’SÖè#›då ½‡,ÆÛ êåv§ÑˆW]Œ3 FÂ^FJ/Oo:˜i#ŠÖxLëb:XkÃç¹VÔí¦€‚$O´¥à#àxaþòµ[ßj<~“XïüBpçDÎÙ^™nzUP)¹&ïøâ½-¸P¶FЕ³‰£°È {„uûÒRœ$ù¡ÆxÁµA›+úôª¬�s æ¬uzÏ›Ü}fDõ Í«5GÎcóª%hYkZÄÖÍ„¹Ÿˆ)˜…¬:½$8^n'˜&Y¶âŠѨ›Î5BóFäÕÍ›D-‡äÆöúÇã’ïK*ò¾OÖƒ>YV[‘8©s¹÷ ådìuYM4žæ²>#-Gy«FeÚfêÚy´XâJ‘€É2D6¨ì¨ì0jËP¬¬¯'Û|ø¨`Ý—� `ŒjâtóÄ}Î-El=�C§q€pó–&‡ž7&©d~ù0àI€¿â´¬v~îtîôûÉ¢¬AÁ‰TÔÏÑßÒ&¼=/ß=zÓ®�ÔœËz˜ µk‰-^ùŸ3š=(zá,2- wÒœ“c—‰ÁÁ6E2î‰ æjo0(ùE–D¿8úvfâ—;Cmv$ÎYÓf¯DA•žãa¿ RóW!Ö¬UO3‹qMŒáqbzïÀ¦s =¶\×ÁŠÚÌ+»Š“}YÙÅQg£á΃snM’ .d.ë)úø0¹·Ä¶Wcî=ÒH( -glê†É% Ul·©7 -,×Õ¬LîÀä@=:Ùi'9] Ûº`É—5G©]“”çØ5(ìN˜Œ!àco5BY¨.ªdÒµ¦O¸5is¢K.ÉTh³Adúë»Ã¾P +“ K±ãDöë"+%]Kˆ{¸ºúrN’/Ë{,ÐnçUJ³#!™ï«õ³çër_­õ ÿ|+ÏrÞÁ`n.’©žpŽu-´Ó*‡f] .xf [:8/‰u¶()rot¬¼Yû…(]&܆»quî,3¼xwÈö¹o²P[a "“x¡Ô‹´š‡»i u1žT!œKr.\�Åb³³š‹—¸�öÞøM<´>áMÜšªk —+,z#"y\4€é&HÉ)Ê®HÇ!üøÀòÞpƒ«Éåe—{?À°ÄÙ9’—¥¨«×íîqñd‘Ægôfæ|VUzò î¨ì²Göh"¦›]á܈"B¾z=eî &nú0!*2J‡&[!*Ñl õt|³Ù˜Iˆ¥MŸ=Oèy_°|J›_ø*V›‹Ó<æ7œUO§ãnÝà¡dä<VÅEÐpƒ™%ÉòÇôˆ¨LúÞAÍ÷HzŽÌò­¼™„W†{”¬Š'šª.n@â—5kÏ{žž±j&onÖr)N;òÄm¦Nœ³ÌëœèךëRLÁ®ÕP{Zq¸s" <R‚ÐMœ¿à­‹¥®Ï¸b“ë‹Ð™:-š‡/·\#,ž¥X6Y¾‹ ×<Sª×!`ëë'oºdÏʹó§Ð^¢×õÝ[‘Ú³à·5ÓèæõÞ´_G«‡@€/ÞóÌ€uwѱÀ=¢0²Z»0ž}–²¢œLim1qš"ÛYc,#: §bÕÃîK!<�9žÖbN®':/,kÓõc8ª¦5 )$Ü• /úÞk�Rذ̰»Ç0K´5MÛ•Ï/¤Þ Ao/¤ˆtãSŠ•Ž×¤u/˪¹CUÌÎÔnE¡Š´Y"Þd©§Èc$Ÿ©:Û«ltá³È¦rK=äMSÚÆèL„-9Æ^|pq‡cý¦ÁdK¬íäTÚ=Åx3*­Ú+~0½2ZîŒl4Ë>>] · ë¯2¶­S®%×4‰ £¥êei¯gA=\Xß™xE¶,NÚ)¤qF<9Tw~.·ÌW²&`¾è¡aÕÞšz†I9̶r†î“š¸rÔ¼Aã±H]²vs­M²ã<f§ÙViÉí^¨Ø¬H<KÇCƒ>> t…@g~¦›´ª„¹c]q§Ëúf+FFk^!OGÉqÖ6t?—6Õ†ï”=¶ Ô´®3ÑœƒO§õFˆL…NâÞÃÕ  Ö²fœ}EÝlz|/�ÕLí‚v•¦mfQÄi©Û3vò!z,·¦0î-¤?ó”Qs]yTG´¬QžÖ.ãâŒR·'‘GÆÁ÷=]Á±b¿ÉpI(Z@¬‹S \íSÇß´ûí—ju¡åœCý)z4BË)èÓ—~ÛÍxñø-7)pøÚc\×yÉÎÁmoVÑÊ•Aœ¤®u™ëˆŠ“¸¹Î²‡êe¹bx9ú+ªQ]fôÎ.¦#ÃfÌ}g­²gù’R:Ž·Ë±—Uuä GÌf¤<8b€`Äk.RÍ0å㎴‡˜…8–1Dh"4I»Æ\wŸ ×Í{L/é^nt‘³$øC›+1ZmSaêŒQûy‹(Â=¸]~0‹/:ºÄ+åì¶Ù ÍŽ”ÎÖ~jYý‹û#fà×k.=[»Ë‡R0Qðtg][<vî…cq{…Ø’+vˆrÁz K€ƒ€Vs¡e„¿¸1ÎyŒrõ†¬A ‡“..å‹–"föë %³¦W›Ux ¢ ‰pÌŠVóÞ¾ñ×�|ØËp$+WQq4qÓš>,¨×7ù¨Qâ‰(Òè%Á”÷cË×�Aˆ7µ0D[›lÆŸ÷*M>ƒÌ€MUÀ½|bï•k>¶"7ðgE,$ƒÝòÌ�60fvñì×…  ÄÑÆi‹zP¹é¥ÈDíX„0әܙÕý¬yaUj7ϳgï¡IºòÍ{P”;ã#T¸¯ÓºA"–ÈÄÓNîUÈ3ÐzÖœê£=ƒÂ±ƒU`½³ýbzŽ}ùñ¾žŠå`¦ dÓT•¼›%Ü@rgRü°á q/ -¥!OÜb°�ߺ9:¨ÅÖ�†F¹ù[ˆsì(*Ÿ}öhðñùÖÀ ɆH2ŠÈ|‹RêÆŠ¨©Þ›£µàú´¦B1xωk|²"ÀeqŒ«ÚøíòË£·úu–µSéÊÞ3¨¡ÜA{e›¦ý¨¢”[=Ñ’èõÆ¡TjŽU¤¾§+ ó\$‡fEºbÜ U^'& ‘8'Šõ£È-×µ7oÛîtLêQÍ¥%vd{9æ�Ûܽ­}Y•ò*¨é5%<Cz×eAŸ¸£}á^†,Í8ã�ð fŒq³PÅ2žTú°ˆ U¦öh�繌ú¶VâcÀÑm8„î…è*¾á» |4œ÷œH陽‰ŒÀ ±=-¢lifر¨¹PßZòeL¹[*=ôôçŒ}õ ôÔÓ_Ç%áÔ£J²àEÓÄ.Å“¡Ü/HŸáí0‰do ë*•ä{ÄgI¬Ÿ ¾déqRbÅ&M,br²Þ[¬á}pרɸ¯Aà cÞ… ¢–“Ä«~ž©lìAI:ç»÷ïüRYºÍgŸŸ¿r%$1qõç°(œº0ýFL0¶ð­è¢?B·9EVNË{Àö*ˆÙvÌ7”•Df"Ò¯„ÞkgV÷{I9G›ƒš“4¶óºÓ²ŸÛ¬'Ê»c ýÎ79})ÓGÍ}í\˜4¸ ѬzŒ�M¢/¾íªA¦D¸e§|›!«ýޱ_Íú‰T™o›™-æ&g.³­¼Ø«¥j×Áúìô°:ÚFÎ6Äyö7¸Ns3¸Ði¾qga¥£tÒb.:‡‘£UG…ꦱ®Vuö˜2²açUé5é°Þ9—Í0TÞœD’·RÙ‘«Â­Úà³Kfâm¶ì¡Õ4òò§œÖËò‹A-Þ]Ï\O.3>ä…Õvì@†wWš›ä€×ƒ1ŒèD§4®º8÷˜ûÈ*{.¿GV\òž3îTå>(¥Ã#D{Fm®W®ÄOhRèužÃ”/KX„¨Â#x"5´r-0Ègkú `Ñi­h1Å›…3CSˆª)W—¤yëâá./dØ^Üù’Ü;žG ¾Í Û„Nœ¥)/7ò|ö¦–L(ãMΈ>1"·Rãná—O„QÖ); JèÌÎÅ€Ú¯âòñ††**^0ºàaÅìk¾Ð™çæÁ%:sf š¹¦Ì™©%¨·T­®[ÒˆÚö½»“|ñÞ!ØSÑäY/ðhµ}½JÉŒ,Óƒ@k›ó-‘91ò`xá%óõ£Pvdý£žkíÛvÙL¢m+*ƒvI§Ø‚f—¥8G\ýh ø=hðw&"4â/O¢G›#°×Õ7) &ËÒ4Y%Lƒ9g“èe 4¨×³ÓBG±„Ïõ¬‘ìB±÷ô¡b)¿7¡A<.=i�àhYæñå, #Š›èÞ´*@¢–“º,£4U@µ¬ òÚŒSGð93œ¶ ÖJõ‹OLH±ÿ€7hs\¥ÇacÓ¸zóÐ…î\øc#̨£Š o…é‡!ü"çeÇK ä\tBÒO–Q^Uš:"årP†.õø.Ó"©÷¼;õÕÌ(=~úP9´œ¹»Õ–_Aš R˜Ì˾KN³‘f[b6>LˆÝß²‡|•½I±cœS!;TEÔ XÊÕî"µ^‡ "¤9ÄGlXð]€ØúJ^B#¦ƒ¾’º”ÎÛÖ ó¦óÃý¥Ò.Ù皇ožùÞc|ÄBûl ýÊk¨x{çOº˜žá<€v_zS;¥¯ëvÓÜÌ]^#ˆu¼¥FÚ†@]'ö@›t³YNzazÁÖ/ò1š˜–xRyºG ˆ:ܽéÀV˜õ-ƒ¼'û¤JÎÃî÷ð`«†xcLCV»à¼jf—\ƒW=’ŸÂ@—§+oÌf†”ù"߈ór˜nØëxÁNgÂ=©¬-¹œÛU“©ØóÒ£½hb«¡ÞE76n²êÅmw±h-G¾AxÜ•¯µÅŽÐxªq# öŒ` ”Ë]Ýöq¡¯£X>:Š·bíÅ@iË×AÉû22ý-Y£˜‘b/V TåðÛ"¿ˆ>z5Åëò¢£õ]–Àû•:òp”Í ÕÊ̕쭉…Æó¡%…»³”À{• QïeI\ÕÏ–FâuXÊ’MÅ<&ÈOà™¾€‰Ø»Ë–êM¥'oopåêñŠ?õÚ@m÷Ä»UŠ((�u~)Vt]ܶ&Ë­&I¯á°-ÀÛ¶Ö-¦_[ kºîÀ!J+¬¯ôÛ +°6Çèãu“T#·{®Ë”"©–%s–Õúv´©Ðuf×Åcfw×,“¹im²ø7L2§2'q‹ðfBc4¡ðÅËÆÊª¾+ é@wo# x1濾}ÇC)Æ&ŒnT³–€#¦ö†…H\á [0ölŽ„mÙJ:°zv?7yÂÿ?¾§±â·ñ žIE†T·¾Íñ…=@¸1ÆF/éë†`F%PÉÅç‚ÖlÕü´ /|œ—.šçF¥Ü)÷á¼Ѐ|+å£$HÒ'ÕÛæh׻ձȬv9IŒÑ¼ݱ\¥ ;Ó÷†C+¡)5§·Ä½0I9ÚWŽòˆRü-oÚ²¼ž&u…�d(™VÖæËð×Cx—ÂDThokŽªÆ4{-p¼‰ÇdVéÂ,œ“GäEo¶g¾òà…©¥¨Ô«¯}Fñ„Lúվ钛\}TcìƒD€!îëw2 UCE1 4Š>ZkëjuãÓÛ›E›qN§µÊ«o¤�²ù¡°í{øÏ`¶–Š‚µuঙLDPmDN K¥ú›”=Ð* ŒÒ"à½ÐêŠf0P:øÄˆi1XÈå\ëe² Á¥m‰>¼ÌZ÷sí5Éw{.9‰•™R<ïEk’yòáyêë¡.Œž‘5ñ5"Uj<4Q=&cLžÀmº—î47°…ÜR®I¼$ï•ò­.>9P'ó³$©ä¾dÈ5pgŽÐçÆyq’D…) 8d³Awœ„¼EÐg6Ztõ%>Œ~C’Ïñ|�ýõkfÄ—|§ò¸F Qž]É–Iî¬f,MÝ.€=Ü—Ñ}{ÏHÏÜë½®~ªZ¶Íã3P¦}'‹×D§f¥áuoÇö“x/âw»Êo.eÒÜ€=zgñÆñœÏ�ï Wž#èp×S £ö¨ãõSÛ±pxÉîNùv¯Úõ:2BiãÒ¥<ok¸÷9Lj8�9½Â­pwÚăô{™Ñ ÈiÕbteÖ>’è“„¸XÁ¬¶…tüH˦Ð\Ž Ã+1V‡ÞÝÉ»2ôEzàûÞÚê± Gj "ã Ž1[Ó£ôk~àp ØY°v-Kº$ ÒfÊÒ(â¨PªC«”6¶ø+ ©é¾áTVÖ,:bÔ€:j£ÊQ¿�K˜ÿ}ŽØe¥LÈäpÞ`mq‡ƒoŸ½Bãó¼yfO²=±ó&eBÊ¢úÔs=• áų¬MkC×Ü ¯F8 |/Yê6„OyH‘˜xu_ŒÉÅ!cŒ¼±J—~›ü8¨•H&¤ m"÷ÑUóμvôq´õ§Wó„…$Æ# €ªÞ{ËöîaT¿ËNàÅ qgx³~ BêWÝÊ­žâœvÝÏ'&Š|"¦øA,Sãnà-ƒÞ£Á`nï\;ó6¢0õÑÀÞ(D€±xòÀª S”HÞóAš«4îÚHL¾ sH–÷p¢r9J¦£1°!e!è|7(¨CI¨«HÔaAÞ“,Á‚w]v†ÛmÙE+žï­ŠäÄ‘nÃÎ;h²òŽ!í×'’ÔRâ4é@Š÷õÑä2¿GZ‘ñìT=(~ÇÌ£\ÍMJ9‘‰¼™¯cs¥HÎ:pð¥xdÇp°—ÃÞ³û´Ó"Ä •Ûh¬çí©=cÛ¹Ð=;P%�Ò–ªJbsM7:ÉbÊÅq!tI==ÄàE∀fFqoL¯ðï٣Aó20Nßf£:˜°BÎU(Ód".©‘b!8M‘Xe+ʃ7¡–¬K&¡;+ޤυ^‰WGTäEÁu­HÂê//ÅÏMf§ªJï"AUˆÇ«F”Ó4KeM{î=î´P¾yö0xLìÝö±îèoäýy“ã•ìÕvAÓÛ¦jJžu`ylËsÂk_ØlžÒX¥£u3ì¹?E÷ž¥âèÉ }žo)}ù4cÌ×ÑÊÍ=®¶‚c@Θs#—j²—{“ÕîŠÁ.î©_A^u+Çy?ˆ·/-·*JÝßÎq<ò֪ъ)&D~˜Ã·H8²Q'B'‹Û§ [)£½õÈŸg5li)g›ÝÓt¼lg‘‡ ­¡Ê‡àòô–Fx-A5—wÅ®ì Ñ9Jš·ÔòzÇÌSÓZÞÝ4¨ܓ¼ÌQåî„™ä\MÝY®-C\iÁYŲ·™Ä`YUˆ*únõzÃàmõò[¹È¤<D”Tzk@çï¬Tº_†Ðsx‰°jµZÕ<x;ÀDGãïÔ¸ò´¨²äze³Žä™'q7œ$æN¯"’0ðÜVåNe±Îë®aqÚ]2¬Þkå$ëÔ¹2è"{4,=‚*þø‚ŠùòÊÁ<CE½Ѭؚã=®D2US|ª7º–ðÐÉlÏrí(]-3Õº<…º—dïùªêMiä‰mó$ÞfݽÃ^™:&‹é \îŒ0÷©h¥çO~#yiSaN… ™þt(ÒÝ5×xİ-ÊÜAìú=dÂKôà ¾½ìGun;Ïvkî ÇÂ`]‹ÁSÎJ`’£y= ¤Ä>ÃÎY9 ÄA¿×é {1µãàíPÐh»•LÅ[¬—•ú–Ž¦Â»K@0Ñv <{ YÚÆ°‡[¨JÇ'k^i†è­"­Is¡ã›¨V[´{«KÙlêZç/gš,Êan‰hk‘»›R+]ÙÜ_"&äcÞrœàG1âOMõ”±N2×H]�!Þ6„â½keíW \XØÝlIuñ4Ìõ±1$¾êJÍzª-ë"¸ó\ùN¬3Å!à‘çËæ°f�ªÌˆé€‰½•oæÕ¾˜ê¢yÌÀ|±ÊHÎÎÝrÐOÖß¶¹�ŒÒ†_Z¸d«Oä@°Ï¬f<ðqô–0x³D.û ý°<wœ]ÒŽŠêË"¸lˆ¹tD‹¨xó„Ï s•ßV‰Nw,ò\ »ïb@ÊÞwn½ã`F|uÆYÓoõÕ–àÃ~‹9dêÏÁZù•1Z)dut/Ìg礼ªr«}ï­á«Z}~'Šá"Sl°amöYU蜃´§=|›-ûfã¨ï¸ªUß¾g äjÀ”ÖƒCÎþôËæ`ÙcÏœ†er5�¯» mžŠÏò‘†1gpH5,>³¥¹¬¹®óâ´b®ikØ�êÓ.fgG j*Ów,вcsÝdWO½ôfÎØõYšÔ°<1Š;dF¤n%�²7Þñ•} ¨“ÕÖ lÏ¥IÇÅÌ3R[�÷¢ÙU¼ëâÍŽaÃENœÍª š´U{:íñ¬G„lç^¾|ñfǃm!yᬶL¨­“¿–$„ªaë…e«w”Œ!zVÙØ™Å-6ÒN¢Ë«S35�É1>·ÌÏ™X¬1#à°Ù¹ïa?U?“D” �QA0­)Ç,Ç ß‘—8 𣋿¨±m…“ÂÑÖ]Ö2ú’rŠ9aùƳëNûiÔ]RÛº m%–Ÿ(¹îñIØYˆíâ̾ð>?­z�«ñ\5Nvlëêi/Œ>.ô|ZË.(pÙâ-[>Óç/ážÑ?[ð‡=ñlö­PKÎãK‰á‹&};ØmÍVEÍTxï‰Ìt*W**ñ;T÷ÓËׯÆeå>yùðé$&ß`qBÐÄzŠ˜ÅÃò·Z èá9>\ï¸u…ì7@/l¬…‹Ž©,:56:'`—qÍÅ( <=àC9¤;Ï™l$÷Ôxð.»–ØQü1‰uÄÔ †ˆµé© iè¼4>¡7ù‚þ(ÂCÕg¥ç´—!#´ê-,¿Ô ¡Û�|˜’Mg6äórø½“Ué:i%³Õãc'ä=]QøÔ‡‹ÃŒI莻lg-ÙÒtŠ«Æ ‹]Êf[½ ÂRˆnThŸ.Ö¢>¼RÊ5;·¤3'IïËìÊ–|”¼[¨¢’çÇHÅE©ï=…å½~°žÞÙ¨Nꯒ+¥æÙ>ôÉ>æaN!çÝAIJ/é!–’-{ì¬@Y¢gž©¯Óösc¼!.iÞ¢×|¹íæúõÁq’RºüÊžŠÂs*XW•KrÂmí…w#§ÉÕìhI zÄÊwy¨î¼Ï y6ÁdÕ¹ïtÇ9ã¥Ñ\ >Étõ}&!WâsI8óàøqf l ξÅÌǧx.sl54½Vüæ%"R[[ìÕcé^ÊBR|—Ë~p¬A)LŠ]r‚yoàpí„©+νœ®O_¥ÞÀFjq“«PÖdF›â&h²+(šS1±“‘<ÍÝRörz²Ç¯ˆøÌ’©axNôø0PP®aÝŸ/º+•ôÔ8Ù[>@è”ha}n=káÁÎòM9–¹ËÞ]r¡Íã¡âXå&MÃã‚¢y±Â ‰¯å=OÞpwŠ­{í 1©¹A«Ù~ãF ï ¯,·j%&^O¾Q>m¢d=w¾Øç–ÇNÏŠó9Õnµ úˆ[3%ïK1X’P¬«}ª¶láè %Pίå²yƒßvºH0FßbÃ6F)ÐúGpøñy?1À3̨d <TÞ͈jTÈt·:(@–IÒ¢'°«¨Ö·ä¨¸“$IýÔøtÅôb,ÂGh:ß™Aјå€a$·•ã¥3š†3´’pæ’1Kà3ƒ»;®xïj’#?å˾·ŒÑs{ &Gð(ïah>Ø|2E²z5lc—ÏÁu@×1†EâÐ�ÞoÔ+<½: 8ú¢>©ô}‚}/Þ’GÔ£dµJÕ:™ãìNë)Á-y¯%ã"»š’BæQ]¼9NC¨…;ÔŠ¶Ñ)A©ð'l€×&§” |@níiö�ì¥Ë¾ ËÂ>…Ul8{»ñ¡ž;áì‘ îÍ{×®\Ž®¢ª9äòÂVûÙÚ퓎lR™b™~î G·¥ÎÖ-ÅYYY.©ÏyñFÄ1‘ЖÆCÏËÉj´y45ñŒäuxxœû lP>BªEÛ¦Ž™3ç±=ÌœïUËb¸§SÖ½~ÇøöÜÏ›k$$X ˆ1¦Û«*3S¶"R£C"Ñ\¾#_;P'“b§ª1¼H´‘™„â|t.vñöõ*Ÿ¤¾F¦ ‚ÛÇ~޾áB)hÂç{´H÷¤NhÉñ|šv^õnѥݸZ½ÌPeujD,ê«2]²z¢Á±8#Ï1L·5GjòfqS GAö 6ŽeQ•¬Ð)s“ÃEç<¬þa¤yÑ<5ÒöÂk8ØH_ëp›ÙUsîÒ³\³È£EÈ¥1p’w<½þ,}“k×v°yô\ÞuPRFÜÌæˆ6^ ñ#ÐÌó| ¨1õÞIŠÌVEBØ‹÷ s‰ºÏÁXDûEÀÜiÒBX@ÉÔºW„ ‰”Kö4P?›ÊÆÌ—p[ Ø­“ÉÒÓŽ^”Ö)ãàˆ,àjšEÕËjšk ^Ç­ !Ì›ç ­°†ÍñHÏüÀBè½zõv˜¯NèeG¾¸ z+÷,ë ’˜3Öi•µ™æ <OKIãÃMQiËdnM¢ˆ¹WÛ¥ˆMZóD™vÚî„‘†r!gdàì…z* ºb¸_ »X”4bl::%·…�²H_ÈIdEh“Û‰à8 žA>vc#Ïñ\ì~›½w0ž<®‹Ö ðÔŒÞYb=c Q$ð�FÞE6a_ÀÔಽ! ²g$êÃkïOì¾°£FÏÙ(vèç²øàêodè™00ØÛÂêÍà9l©û… ê9†žƒÏ‘\?[²®WË8Ízà"=;¨öª’ÂÕû®ã]Q�3àXò£F7V<R ^–„0쬩Øáw$X—UÜÃô„O€¬4Rº›]“ðœ  Ž0»ü`qŽN%ø=ÕˆTšb½%–‚¾zeã¹5j܉—¦ÜÚ@87vk‡^—7µ]Y�äÈÌ; *ÑØ~ÞÆóŒ¬Å™hãŽÞ=¢¨ÙÀ}|þ÷˜ÓÙ¯–r³5H˜ëufÝàsE(4õ° |‰K¬ù3¬©]+quˆX#SØãtK×iƒ@hxàÂÏ`ïR-ÐOP2ÚŽÃ÷ 4Ɖä` ®Ç’²iï x@øRMCS’s}ÒÜäâ¤)Þ\]Pâ#¸K.¥\éÍöÐú-2>2|á(ø^½˜ ªè‡{ÍMÇ]çLQqƒEßÁ³öêCËë*“÷ªW½Oµd`Ëã¦1p¾Ð&@kõ®ïHÓdóà´9®” …2âaMmÊ{FUW€T‡ÀÃÒÔYÊ£¼F•æ õ^”ÛãJr(¸zÑÍþ–TAg*É]n%¸\wáàÉ6@îÈÞG®²Q;žB×áÓ‡¹z.ZöÞI9Ð�æ^(ÅÝ•e_%ÈŠ‘YFÇËÐH®'¹¥Á²|¤ÞÝ®P—;bý±MéjM>ÎF£ FH¼@SÔ¾V2¿Ñê‰\»5%U¿'3®FÌY±·§½»O’ÅãÄÜ^AÕá%Y­uϪÖ%‘ðn—g4§Ä­Ô切ä\¤ù=Nlà^Ö"5Ô—–´fhjqõ·›Wú�÷"ª`Óp%÷¶ºMEa"BA…^÷ë z¾ô²Ô[/i´ …) uaO¶t1Jè4ÃÔB—…Èá"à š$žT‚•S³åës7¹áúæÞ¿¸ÏEãKfÃ� \«îõ®šyC¾ºc¨,ÚÒqÂ-@UŒÇÅ€]7’½Ò$=ÚáÝFÛ°”/ð®²áU¢¼K!{–8f®8Œý•VF¬¯Yæ–'¶¦<•w†ü/m6§K•‡˜›DŽúñT)ƽŽKM£½Ñ3Rjx‡s{9Þq?€7wlåâ‘ZV¯Uß¾˜‘Sh0E<8µö°bíÀWÆ•¬mwA•÷M}ß»OKáÝ’<æö÷.è=©õhD”el@\åd™&ñ¤ƒµÿÀ·',l"…á“Øâ\ˆ8:Q5²LxÅÏw§ø±=”Ç$‘O– ÛØ¼Ì°$/(\‹÷]è»è`퇪Œ8­¼‘“MN©ßÜk÷ˆ—|÷Ðßd¦dsc2 V³u=¡s(r Ø±¹.Á .;|˜`RpÈEç\ø˜aöˆ’ýµRï½C\GâN Æz&!óÀ»-$É—‹eë##M¦ÚS‡–0;7vd1‡®°–sÔl{Ž`W$¼Ã©1ìŠu<]¯RŒûaºù=xmm§<î‹îA»Ö·z¯‚Ôbµ‘ˆn×ß füô‰F³C«žˆƒ“9¼€¨Ò®–Óö…j³¨µ~ T]Tª4’'D Cü.[k[mA¥³å¸i8ÏÑ‘&ž7ŸÎŸ¿­gòhjkŠàæ<¤í‘¿=LcUhI ‰w‹'áJAøV”)E´gGžùëËD™ 'ƒÙ`ÂD»uY§¡Â‚¦]ã(ÊJñq]°d‹ž‰NHÛ:çíÑÒçÏjtyŸ³#ø—[™ªŸW‰Êá>»¬E?.³NñÆš,¬qÝÑé�£ô0” h£°F]Ï0ØÆgìy€Àó §–à¡<°Q¥˜Ç¹z°èDðp._ä+£ÕFòloÉqÖ³‰ 5i¶WMOH&—ã-k%ZzT¢öÕ›Ø]*§OðþÀçò×z×4–—oö]ïuÀq!uìËT&\Š] šË~1=Süz5ñyk³îR¹áCá–(F6ÓȚ î̓øÝA%ìÖ²‚ZšïY pÆ›×1y®%–ã²h$ÖöÆœíé«Yfk \kd·,¦/ϪHq£hüö©´<qªG Å!›õ,ÐìÆ|óéVðhœ–´f Ük.~ûŽ-ä(„¤Iò¼ý`O£'¦‡|aîE¤ÝóÎÁ­˜ây³+ù@#k#Ðé¡„ÿ@‘y§&¬a#Çÿ‘ÿkIOÈzX‰¶0Ö(ÂTlD¬‰bçÉ’ö\ç€õDÔ ›:íÔúÏAŸ dÐ÷€D¡2Eßî³Wï \ ‡5ÝÆ[Û(YW±G ©=Gß{K¢ÙÍY¥›1>¡ørß•�ó^UuÕƒëÆUE™žôúé*¢m¥Ø,µóóˆ§ éÄk®)Úz¹J׌²þlòå»�"ëá– W÷wh¤È5“ÍÄëúø‡Ê´ú m¸U¡ l5 ;NQ †cÏöÊh,ÁR†fMäI¶¡,¨z¡x nÓ„ôîsKðzB¯_=0Ú{;"{€jŽM—ЈZöL)Îæ�7\‹ UξžD<Èk}ãKms°Z¥"ÐT¼C¯é…wNÛñä±£1yÁVNÁV)…‘h§æá(Ù2KÐýz@“Ei‚ÜŠE_ֻ¥ZU>x…}±Ã›„!ìNfñXÏbHÎßq±ô¼‚6V6G�ËlÍyÚ'Vmb¢/ê´jöìÁn°žN[}qtçKÆ¢îÝCæ…ÃOWç´®½^zÜ<ê«‹:€½=et+‰7!Æ»Ócù„ì¹û¹ƒ·Â¹½!j„K™7;%§¬r‹[(.g¢Oœý°ŸÃ3l]\‘Ð(í'K>¯ºù,{WV98µ—dãõÔbåºr«=0ÏÞî)F}É{¦ï‹üòI¾°l3ÂåMÝnÌՄ¬Ã½Ê˜NŒ=xzo ð)RžÙXJõ½A«ÇHô 4~tQ¬Õý:Uw1Ö…¼šhÅÕvô2øIsCÔ,ZP7aØ‹3MT³ëÇh'Ý\ƘèW"—–—hÉST-„´wÊÑöúÐÅœLYÕ£"ÎãºëÆ’ }ÆôB 2“}‹¦Q’æ_„$ÞšÚÌ ¨b¯ìk#,ÊTI�,òçéñ’<Á!´™t’lè óiݘ4)0D•jŠqU6Œ*Zb›¿áÜ£«ºèVyÿ¢ß@ò ;H˜u\¸ ¥á0-# sʚ܂ˆã7$k#÷CÅe½‹bSNp›dŽM<Pw<AÙ—hmX(ÊäÅ7ƒ9B ££`kt½ö¨ƒœ û¢ÊºàÄ4³‘¤t_ÈMu¨Kvså€`_Ìèðp½[ì=c™Uõ2Z ¬¦³ÈÚ\Ã=¤W;GC)V<bWú˜|^ûÈ.6›iÞ‹ 릀 o§XšsÍøúfvë-?õh�^ÊÄ™3HîðœYQ|+0à}&F ÛqmÉ‹eR´9júš—ÂÜ=‚š·ê‚â8±˜ >ØÏ’¼„¼ý†ÒަSnöµ÷i´“­Í‘XϾ7êÄ3¸Ðð4òœÕÖcG˜ž%¿­ÊÇÓ¶/PK_eÎ"çKz–™"jK¼"*#B›3O|dߢë+šhÌ3D§®‘ÝÂÜ/’ÎÆÂýá²Ëä ÚíÊö"Ší¨,v’oæÑ„0;D]‘Ë�†/ †êâóy)î)HžÃ´Õ£·ù^ ƒ^±ßLaï½3²”ȶeiNÛ1† F8à ’Ô³�Ý®p÷zã`ñ K  ;¹‰!º¸ccà!Œá*™æÃ}9­ž<òRíÆÅ"ßôô°ÏÒ$£â­ã/�rz½HZ`â¡öð ùÙËÓä!àÐZI²Oô‘¾ÐýByÛ‡Ào°ã™ãˆŸÄ �‹Ú¬<-x°'.¯™¹žèÓÂkJt qM.7–ÛLÖÐÌĤ Í7V†Êj<»ŒUÙ"ܞ̻c£jiÎfMJ¯Ta7Ha®,p³ktÔrQ*˜y->i9ºMá\¥CF!ãhw¹1J6ç†ætp$YÈèÕEo O¿Ë2ê÷6Ù«-9Á{“eÒÈ·µ•ê´êei>?e±î~‚]vꕇÑy™×eÍê{©$ì·(¥ÞzðÈÅ _ëhoI¾šU÷}GØÿ²Ï§;çÚµ¡ÑsµYµ”a‰Ž„,Û1Ü]Æ€cäzö ôU=ÊçTϸãåBÓCî4}BâŠÓÜ âžh¡ì S¼­¾öZv=kŠ€­_°ã>;í8ëÃs†…Éyoh+à`¯R¨ µ¼½×•©µÌ\Lr$Ü’÷éÊuµFÖ¹[º Q“¨ßÞ`@€'Äõ¼C+[­î·¡ø^Èíˆk;õî½[¸3]"ËÅóaY½÷êò¼¤Ý±.îY?OböðA‚p¬ ;{ƒ¬Xàí’0y¿#u¸r�€.Åå]Ÿٓ멬z SÐS±ŒWû,†\Ðæ“)›ìnÀDm@Š|÷F’™ï³¥%°elSK¾•Ì£¹˜ÄÛИŠì+;À|z¡=ñÌOÀ3 ŸÁN΃ ¶Ýf‘ Ku«¡©ˆ='_õ!G$¿‚ÍFt­} Ý1hË»\l˜ïÙ¬8029ÑEÜ[yï™txèE…,Ï'ŽCfÚ›/Cât¢‹;ù•î ½z)©—pĆ‚¦é+³¸†‘#«šMO³èk„jãèbŒ¡³]w;™"!Ñß[¿¢4Ág‚˜ïºiÆx¬C”žCÕÊfxÁå+Ò#<|µØ÷Z5A®³Ì_½‘J:Ó·£{ïØ–gÅžûv wíƒJši欓fÖ˜QöÀ+›^‚àÈþdŸà“ý´”“›ÖH"fÇ\Í“ðyR”¶OcÙc%¡ßæ®‘í« ·wøNºgÍ D@ŒzvnXi•×RÚç%8Ò=ÀîǯŸ7©ÚÁCDØ2zSMù‚æRýXƒ•".9Y16 Íæ.Qï’u]ß»×nm%v‹<åK=ÓWéZ3Ó½/}Qõï!oÜš*Q;b Ç9ƒ0òŒ†`iPð $óRçÔ„G5 £¶ØMÙsZÜŽ Ê)pêØWÛ$‰RhË=mÀ€(ý 9ŸtB¶æþÏvo[@+s/-9zè[ô3mд§ÒçÆï¦ô“âM“‹ü2½¯mŸÉÂ# G°‰7B�þÀßôéyö!ÈËW¢èkΫÙ6‡{Xù¶_ ú!-»ÍÕKIÝ™ððÎUÍb §6ž´‡Wý21$«žq`>ŸÜ·rw9í08x£¥[·øTÇ {o·°¨éQŒõˆ@ÀµñrËT¿ÑáAxç EØ{ÜÊš ã[}ÏŸ1>‘sHÐÎN^…0OÐsÝè‚yO'¯û¡ÜØ·"¬úEžÃ{ÝBOQ¯µ¡gõFúÖ6m†Ž9iŽ=ùܪʳRt¼ª©s|b_E6sÁªW¸“ù¢AÀfålC¹Ü8Û”…ÈúÒ+=9.ògðÞ(•˜¸»î©ÎÝ‘Y?2i±=Mî2V÷Átk§Á‰…ž07ŒNæêœ.µç/uF6t©ä­]ßjÍÛjÓd –̰áQ¼ÓÎ;íæWH4ÏåA?~L‹þa8LÊö=}ërø‚5Õeku 'ò´@¥çhã¾G­>Çt‡ÀâæÖftt #X)^H¸˜(ÖÖq‘Á¡ÇË8ë…[ä=Y“ pÕv‚{ÊGÔöWfIž@ˆôœÜììh½ ÊPó©ÐÕrEmxu²‘s¡4’#áÇÓIjéü<áFï~ÿ‚â2Qzk£Þ¬*–5<SHæ`W#@.]_X\Hô¹Çiù^96wF WùR(T¿ %M Ùgsw°[Ýw¸ønd9 =Ö¯O’;w ³KÕ—G¨xœ«Üm‡^=掌“ZBøØq3óU¢n;A•6r)ÚŒ lnkÒЛë„c-Ne$s°’zZ=™\øŽÅâ锚]” ò;ÙE0‘¦¤I³ÙíTZb“Ðæ6rPòºaÚ€<鉪�?@*¥’jµïö´Ò¨,@ ÷ͤńĦÅûþ£»4Þc –h8Û¼÷Þ9ÕÏé¸|ý¦\#™ícqŒˆc¢\sàÇ6$´OÀ§ÊCuü°¡PÚîÙóΞ£ãnJ|Ìëý ZQ0áÑ îÓÈñݹ{¢s€FM›þ^¾±ÇÕÆãÐp8õL/N{¶hïE/4ç5·àYÞö _�Æ\"aJ•Êé§xïrI²“½ZîNœYL]cGá¤ËÕHJÖXŒ×'«‹Ì“ñšàãåuôðwƒD™õHóH$^'¢m`‘8(Ƕ¨PМ  /¹‘¼óv}¥ìhF<ê0—{�qûèHK b}r'X9ì ¿$#6/ôò㧤MýänKò…9—[vÚÎ{¼ÑAŒØò«UŬ7 °Íp›&ÈwaX“®ö0ý]¾¡ð'oE¦2¥ÚTY¼¼é=<~~•h/º¤„z´È�müô²±^¤Ä9%:Èy¸—z¨ ȰXQêœçÐò™ f¡˜È<ÉGÓ“¤<¯CˆçâuÂOb¹(qŽ�±7Ó°êMo±T”ÙYâ¾ØÇ{Ö"™q,’Óû&ò‰bN¼S®@+ h‰‡kOí*ßÓÃÀ§(hÍê¯éZAøØ‡ÊÔAZÞ$¯kF”¼ÃÌšèq„µRÞùX઼ÈhÖZ^½˜U"ÊÛ}…!;J–#£&ˆl§D/µê“~¶/úi\è ó@MXß:ôá™&²isf&M7pœURŽRZz7Ã5Â=еz]JXc?ð¤÷IäðZ ÷‰à`é¾W¡˜9¯�ot ‹ß4-ЪópZ3è</zq«D1˜>åÖ;¦«<€ÝÕRÂø¸û"¨8QÔí¬Rèô–!/=W uŽ"Ì.XlRÏ‹õÐg9Ëfáä½ñq3t0X÷ŠŠNK!xÀ\þÒ‘¦NUd8VÜ Ω¬@Ï×ïì–›¬šêqS9çÕaQ£`‹scõ‡´q¹ÜÉÿîý6aC$�6Wë»MîA7Tçîw*¬€Gç¹ZV[öþúänWŠd,ô1Ü tÜ?.XDà¹\?@¹+Ød'f^æp~ mBLŒÎÙnæoöÖÔ=Dº¡öJ®`¦Ç¥NŽÐOQû9>ž¬à~y-^ÏFŽžuÂê$Y™EÒ^ª$`·¤!•œГ(Bt5çpóî† Ö)¼Ç {¬$×Ï_¨”E×&à6”fzqK6 :*>+}`4-OhöÒ]®ý)sœ@¸®ëlçÆžC_çã§d(·ºÏ2lL€o©O«K8×VÖâ­ñ['­)4ð·Å4<Õ}”Ge$Ù% Ïq_›[AqzÂJmáȸ�°?÷ê5«L=t]²çÈm@૽¥P°fÈB’ÄùÝs F — c’D!�¥Ï¹Ž"‹c.r{º½bì6•fyƒôiÉqž-Í¡jŒ¿;>Ýžá×÷ÒÓÄj£¶YôU¥Ž†8J4ß‘ ‚²Jd“Ì]›–J•G=‰XV"»‰ÅtÝ:QW ÂÚ2®s…’Ћiôgm)Žõž¬°y<©Ñ|•/Ñ6`ày)’w¾l4ØmÐ.?ÎåÞ•º×å"èóòÁdèš®LF0ïùrkŒ FðêÄSî,„Çï,î +Y†k¢ïù齘ùÄ_ä ]Œ‰çþ®3Øßµ7Kòd>æß^*Y§$%ÒÃíkW«Ù0®„Ê smñF„›°B’oo( «+$w€)0—º'ŸŽg¯T¿ñØ7¼:h 5©cæå¥P×¾¾èr2œ‘T9-wzðª=ãh¡(Énl¼UÀ/3ëéÍÃ<J!©íÈ×ã|9Ò¾Áˆjjéßp)qšß9€zEì°ƒ‹¡ƒTòr¾ ?ºËÕ¦«T­Ôä¦×tkâÐ-¾ˆ¦œb,�Ö_Òvµ%ç(+.Š8žöýÇÿ³v]ú{“03/àQÍ;±McdYc®¤&x]c!Nüº™’c ìB11¥¢ Õ‡=ØsWHÀ“Æ3´y³õEQ£ª‘œ1ú"Õ¾-Kg{¡à peëš.~pµ`þöÚ¶w—Þ+ñ![¤v‚€X{ í¡SnÀ¸ @{=ü°ïõs:„òÞQ~ÐG¯ž´9Q ”)WÍ0y®¦¡<OGåýÚ£DlAßÙ´Xºu6GøróA‡è»™|\î½È˜¸TÒ–Ä:#&+káÈØ¥Toá­›EÁ‚"#Pœ/åÛ&„à£åð½#Z N3~60àY ȹ)£à»î;Æ7©™²ø*=˜ºíÌh1Až¹µÃÑ{oB.)YÈS^îcPšml!µHÝ]À§áb7y1”C¹qv9wN:è²yo=+æõk“\x=š¡GEÒÍ®¯Š8NœdóuB»t÷„ªÃæKi~�nøÄ¼‰JÌŒdó(r±Ì¥™éHYk^³ÏÂK(Ò¶$ƒ}°54iDÙÕi#¤³´"õÖH(á½ Í=8:Â'|i‡ªÔúŠÀ}ÜðxIXÅkºD|0ŠûåÚ±7[«ÈˆMLu"FM@ðYsÛñUwW¤-†=°«r¶&¼…,zö¡Â Ø{ÙûLuÓå ‡Ò>ùWúâ¿}ãY–{@°¿^.YEh&†U X …à¡xÕâ¸j» G…™;Ê[ Fónß¡Eåν/:+ø)¨|«| ]¡Nsà§±Fõ(b°‘©vr‘ž£¾^¬´Ót2V‹zÙC[¼Šä¯#"Ü€GŸæe _ä3žw9צ-1!hrCô*äw´:‰îsE˜m2FêA¸,ƒ˜Ï¸Þ;§Þ{ÕY õPÕ¥nÌã…!<.tó| ÌO޻شq KFxIsŒdêOðFÐÚeð$+#z&‰ ¯uR5™”ïyךOµrõƒÚ+FëSØŽwJ»Fa _._Í÷XéMQë%ŒžR»$HÅAxû½Ìœ ïmOô²_7÷ئK¾¨*Î7@„Ø—v¸ã6)Æ«$Îà­PØ“«É•zb<wÞa„ËÅHòr… L+;1<ÖJ&ÑV…W•ÛE`l–i‹òµ”/±mR¡gðq³«áíkR�b8d¹@Ì.ëÇ’·d¨¶å¹p'¥rOdÏò£¨të·^&†ñàAQ>!Wœí,ÃËùPwÞÈ´/7‚õ°  ³•@ïcyI¨.€¯%8º”�ÜÑ<3¥£`3•‚�B{ò¦ÍÑ‰Ž¬•w_ˆLA6™ZÂA<w%Q¤‘úÍàãUM‹M ™Ú“õ’‰Ú‰³§ Ã'›£VÄ7À|!ªPBbn#—Áó2²ï:1fÀ©æ|ü*ãLýô½ÈpYRJHŠp3ÇÍ¥3†}½äÖ�<lޏt^r>ÛyÐ’ÇÙËw–'Vϰ  $rù¡C¢±nQfe0O¥ÔQ°X¢Nð;†ÛËdz;“”gIæ–¥E#‡Ïšº³4š˜ «L'“.éé]܈—¸øyp ×E„ÍyE`ä¿Q :Â3mz‚YäøöÙe.4Iz×EkÆ<ا«£±ž¬òtì$Ý; ÃVX¦×ËäÇЯkîåØ*ô¡¦?ÿ>þè·ðE–K|\Æ/¯ß#|d•ö�«ý½¡go@JýQ8†ö“³•îwÏãê˜å4¢ËnÕÄ,°™áç‚âÎé#’ØW¼ô£Î˜Þ `gÊjâ4™vÊRóÊ‘¨=¯™á0™²ö€I¯jçn£»ÇLÁÃÂan*Ë Pt÷:ÁŸåSÜqŸê=Ägö|¼Ç£úµ„m ¼ÞQ@8•K“DÞZV»ë¥öRWãŒ9iØÖ‚®{»Š½z Õ~Ï•çNÄÉL‹pÎÛîºùyŠÖY º§à£ª#r ÊcÝI—Õ?ïÿPφeq›D½"àtx€ÈÉ¡9·0MY€äx?¨hÖH‹8»5š7Øw±¯I®W÷Éбré<WÜ÷¨ém(T½G÷ƒz؈”ßkœÕƒs´ÀÑ”)«ô~x¯ìöÞ·P<×@bÃ’Å‚W&WQ0‰·Å*ŽÖE|øY¢ÃVv…Ç9Gñf=¢–�º Æ¥„˜¢ÛR[›áz¥Eˆ}±¶ýUŒvK>.*èHzâAÜ”ŒW¶'À ûjRÀ 1„Ûé®û^=6rÝ:¹sâþÔ£ÅèP"£X4˜Å®<� !jÓÕQá:Íñ¦¬dW4W¤rñj³¦Qd›µa •]ð˜5ûÕ¡áD\õÕ¾œ«\N%·âwËØ²ëûrÐ1ÆÎ¡ ‹·ßäõà€öë0T€]Õg§<êíJl²âÂô±¡û`ú´CÁ f‹¶- j~2ºE­wM¼ìœ$ø¬¤³.% 26_‚3\ɃÄô)®>g_Úc½ç ¤%ˆS¼$e2¹ÕEåNdÁeʤ`Íœ‰=W BH©áÙQž‹é;*_=²~ã5莜ö¨aVÐΊ‚,OŒ“®ääÍz"ä‘õ-~ŽCN6Çå#3òT[†Éa–+`¹¡ž<Dè#uË|·ær‚ÞýŽ&å=Tâ’‡èÄ~0sÁðÍBè$S¼øF€"àærºc^TΣ\ om•žÄÜ3±÷°ÜííИÜùœM‚>›§ºïñ:¾¦8 §e¯H¼W{t[¢•ø`ÏôZEC«»°ån¸ ¸Õuóôy¯•ɼN‰ÏÎ$�(\ Ì ê¼Œ!ý1[)VÄí ™¶l©:lÇ¸Ô ´¨;1Ò(4’ØP;b¬xÀš P*1–CSkº¼²â+…¦Ê‡GÕ(åäÉR…Í¢zìâºÛ÷ž” Iá2‚o‰>«bÃèV§È]BìĬi'ŒQ {]$©… XO¦ŽýÏ=@ƒ€ÕŒPìÁˆ«‚ÈÃ}<ôŒe. üÍ«~”„*ÍNجžà>a/[íUf€$äR èAµäœf^,Ž÷X—Ë ª\…õ´ Ëäe³ƒ(>$¶Wt½£áÊ ´Ú,z5njFøv¬s"ŸŸe¸ =•|ì.\½oŶR`ZLiߣG~õ€ÞTë4@“!”†é¡qƸ`VÎl+vÎ!´_\â£kØrÜÎãF-y©wKƒÈcØ›³Ï«€ßs‘L\['Ï yD(5pNΤ˜âò"ßSÕQqP•h޲s˜6N •#šä[BkÉUt0ÖŸ6 +”…Û{1Ä£µÌ¨ÙE[ùŽ–ø|•4µqn8{ëuÌ‚`¿=xØæ jxfâÍ%1Ä8óöZƒ©uE»aé6!ÔϬŽ'ýUÜP–Q1íó€jÏ-xch~¹õn1!1¸POé½q´¼{³6™¡ÇiO¶j¼ã:ÚQÒ7.›ŸÜ3?|Î9áyQ…äîæÐ³4äÒá˜RÔ_¿©‹Çx®:«%{CºNðÒg”KÞô»&jQuc´~ꠦȔ,ê ¨sñ]A|±ñ„ðj‡ž¨åYa”$§¡8 êÄ1®ùÚ>{â霯§ª¢ÑoàE])ŽMM¸©¸dÉlª�MŠ‘?!`Ÿ8Ü•üaÜ„ðÃó§'º|K¢/´ôyS¯Aǽ5ñL‡ögtï—'sUš†Ö:!T²m/qÃ4W¾Ñ;¨“ª *—#á1aê~‰™Âj<df÷†Ò‡ßÑ6•e>µJS W΀öVH#}8x21tR[õh »´aà*‡ÔåEy?¥ÎÄÊMλÜa}s:>R¸å,{„è^´‡yŽ˜H‡¢µeùÜ3W‚¶Ù°ôq&¦µæà¾P4öÆ=)wÚý.ã^“iüRV¦=äÀá&ÅOø EoC\4XèzTÌM=*ÇðÄ\OŒÈ4Š©Œ ®Ii¸áS�cJ®,+§‡Å£¸EÅÓ…¯ARÜ"κ’ÊçÖÞ¬3<+bìÂ`MÎ�½«F)M�ÉÚ'ÀƦ1B©™µÑ&^TÇl:··÷–T-‘Á\¨`à™Ïñ»2�ªBE˜|9òø½„íncGß*ž{Ê9ú¨bZÈpã`ÆnóãŤw„! êu®ÖF¦ÉÐY ½CW›}=Ž Ä%Ãé¦l)û~)_" ÇÕt"r{‚lUVQcböÜüfúnÄï^A¤â(¨5qø^•\—‘:ÒYø>$„·lI3Š©uSω§”joR÷l†Pz…^’©Àœ €¿ìíêñŠ $qî‚Jh0N*iGM»pVøµ…öó}ö:Zæp0¢7N¤JLÌu«G]p²ÃâqæÂãÀ:.Ì›§{ð¬å¬1²/´T·/{¸_uGú*ĬÜõ,ÌÁš™Âø0>$ÒÇvB];îÁNh*ƒï=쀇ÏJeF8V›>^èq½N&«È¥‰êóˆKÐ]H´mÈ·*¶d}2œ"}܇  ñͳ‹ò)iî§Ì×þÞ":QÑCõl{#Æ>øJžÝÈf½xP,’=3š Âbú=•r£•§ºáwª.Çϸî{ðoœYúLt,Uc5+Ã}Œ[%Šf]P0£­ïTÂNQtnæyGš: *Ù¤M"NðB䌔zê‚cÏ{Ð�\·Öóœê˜RÜ'O êYª87'ç;Ú…Ãe6²x )YxevÓÉQr`•®õ{ÖUì_¿'íê,O7…˜V`Bõë$]|¯U¢öILøŠ3Îq¿S ‚áñž]«Ã„|Ìòx·[ýîåžÔht¬["¶®`Ìb2èK„vr2r?Û—ð$g=ŽáõWêÔœ ¯ø¡_^5’SS¥SÍž ìõ!ÌŸbX«fZ …³²ÜýxúÕ5z>€)ßÊ1Ø^ A|Ôò†KðqÏ;‘t òÚðVÖ}qÊ÷jF„ã a=cl†kÁ³9tÈ\}‡APYOoÕFP›—ó†€d4of@'S¢Dkéн«åE@œv‚¢7=$ŽÂ ôÆÞåÀö±=„‚·àÒkÊÞâjÚòœÂ// ÃpÛ¥P9ÙÃL�ƒ§ý”­·…^è:ìÒUi¹CÍ ­˜»9†!Á-˜Y×uI{7ÏÁÝ|Ô2œbSÑ9Ší „¡2Q„€Cº½.Ï_q"Ÿæ‚H»¼‚0ßÎTCðÜÞ·æM`Ø â—œB,â1†;¤ýPy:žâ;°>V¹x ‰ávÆúrh–ħ£#^d?#Õ[Qn(z…Ë£²Ç ÅR/sS3¨EŸî0´„•p>0¾'r­Mt6+$%ÀxôÀåoÍÆXöF±øÚZ7ñót7…ÅGP@io"Êè¦?¤è÷¬@” è¹²Ç<Ùƒðšx5m,[ÎöEô-lwàâ\MvTuHAÔÛñ5n—Šjß  ¥£}OÁ›¹‘Þâ‘*á£m(È'4kS8ýœÅð”+›®'6ÛÈjŠ_&Å›¹6|Š3]ïÜS ¤¶£ÖÚÇ}CîY]˜Šœ¥IöpG’¹tÝ9šâ¤Ï•‚ >Å0[ùCÍ„«’Q Õ{ë¯Ñ,óÒ³ ½§¥Y#"õ8ÚµˆàÄ:ð×<ödLJñtIõœ41žÙeN²¦TÔëjŽÍ9s­w<2ÌK´9£SPÁÈM¸³ID~Vá»vH)  dû\‰5$œÞfdíëÁꪺgmÜy¤æ RWØÁáa›€'z—<yµ®ÌЍ.­hI´- H—³Õ"Nƒ&oí0Ž€zy+!æá)¬kU){ –¸�—Q–ãã|ÎEœ{ˆ.(k<{ø‹6¯ÁÅ ›H|M€ô¶ŸƒEMNöä»ñ2ÿ ÇPœš6î쯥ReЀ|ÔÑy1sÔtˆ�Ð’‰=m)ëÖÃ÷T&tS’Õ:3È :Ëó`Î…RMXó{Ëq¹ýuÁ ÔàG_yôã«^ÏÃi-¤iÅc@Ô,ÁrÈ>ð´ŒÊi%ôI“-î¬:¶ðx4Jѯ©›¹*€9ÏìÚ…X›×ùïâÒ¦,4 ˆsÆ GÕž¼[hË^MA,‚KrMØ‘~0I8MrûfÊî€ ÷°áÞvAc ˆ°½73’äs&¾ôدY™n.O8WÄ/Ša‹|jõ‰®O˜Â{¥¾xN‰<6µW“-`úf]Ãk+:xr!9nS/5ÓùÁ}‹.”CHŸ¤‡Pm×cßYUrPµ~;èr-ê¹â‹R’bY7Ρ Á»Ò.Ïùè±w¼E˜rèÑ\pÕÇøP€F¯§`Ï;Íhs²W˜ÊÕ*gïÕA_‰}vǧt(û¹Ö`V {8Í) ]H¹+BWŸÎ>$ÈQº WH§hºð¡WïÉ`NŽE±ùIÇ8)“dt4lí{qÉÁ%ÇOh2^ùË"÷æy¸q÷¼›‰QÚÓ¨0ÑxOV ¼n$ <´›!T\µÕT@÷Â÷´È(Ž8…Ãïd^ñ‹—é£ ü Yi.Y:bÛ4PÍ5 ÃH1œSU Fú¡FÎì¼/8|*bï;<µ[¡†p@Rò¨qwtÔî,b×W¥–*º4ázÔ«wÓFaâ×s¡ª¦0º¢Ø"¼È8p4öÎî‘ñ ‘L¦![]†B½îåä{ÂhZŃ5¸*ÌôʧIš¢<vÑ|é4í2jþj¹˜ùQˆZ÷6: ûæÒ&Æ;bzñ*ßÒK¸§v„ÝO cËå± £\yXö›d¢ÝÀŒàÇc‡¦šÌh8¨‚�Øä×/8»[½·DU†ô¡³ðP%jä‚x:!‘7š1)Ð9î¢Q]C<cå‹{>»Á­¹Y–¹ºK©ÏöOÄ ÁÍ´‡!D˜=£$önßÂS'–Z¥t ó¤¨Z:S,å›3+–šØ=ó†yâ¯÷¤x\cÌÖ”‰Ÿ f¯¼Ã“©BMÒ®}£—,Â@éwÀ)s�BË—™+�$#Æ�åÅÉåžYÃ5pS¶5ØaX< àjÑÉw.`jØRfãÉØy]3Òmêû¬3›+õò“ê¢:í£Ûèî:MérÖÜñÚ‹l8|§î¤i8Þ1F~Q+鄸"vûåºf™ñÀ8±´^Zã{”LSå’#ÏØAëQRÕ>{T;Â~ÜÊ$´ûÜ$™Ó“ …&¯6|C÷2ÞZªW'ÄNzsS•_OîŒm w2¨–F±?Ï[}.¥QýrC{ô¥<òp{÷@ûIÐÍ«ã‘T&vNA‘»{OHÈ­­¦¡èÆ8¶0ÏÑòz†®í].U¶ˆ„ŠsÙc]³Ã'úróû7%>™$§93Y1Z.ºj3ñî%T¾CÛ>ë€Õ«~°õË%’½ÇRÇK»â*(nölHªv”Ý%}Èd™ºI`)¼idÖ©7 7ø¢¦fkä!ìåö;xê]vÞ[,Sá^Ô>$ë‘ä6«ýðå›7’q·MÃsoT#ž(µËò˜Ô”j˜‰­ì�yö¦?dBº†gF4‚õæá±©êdiëÑ $‘¬SÛËšo|ÊâͰ0컨Š�:oï*žÂötà2ANqRà5·£ñê"VX¶¬g?"‘g„ôPÞË’uqŧP6H[»g.õ(o\LS'M9}GÇß±–‘Çl¢žé°˜9<xÑæIÌ.â¾n¿$Ô¸²nî%/Òw¾¤¹áeëäÓ›|–RÁ/ªè´ªïMÇ•%5mlYÝ¢™—p®™v†<ð0ŒÙ4žÍåÓPÄœ°³W¢ðŠo Ãnh‹±”ŸèËúx ¶ˆL{> àŒ‚ÃØ»,3×Ì~“T*`GÔI¢üìO XµðEç¯Éú¸eÞNsI>¸o$Ô½«ô4Ö<n*ÖÆ¨’†¢É™ ¹ö–\35s§y¦Å|%×òx• ‹ãz(š1'ÆŽ®¼m¬¹º}†VQ¬£µQ£dnЇjH´KޥޣÆûÔŠ°àXä"¡]ËV«hg§ßŒkûžžÖieô5çƒUxfqЭOŽÉÁÚ« …uVBjÖÔÔs¾€Í­Ë ƒÞ-oñ”ƒÃ°Û¢/ÓwyNÆu´ð˜rÌmýeé`ö1=yO!ºCí2æ1Zz²b1¦P@Mî’)-ÊË7õÖËœ_.H‚œ¥ Ƶû‰iǹ­‹“lòÔ2f#=,¶Ü©›çRÊîeŠô@—D"½Àž A`‚‘nb<¸}Ä*žÛ/åÎåj'v“Vi—Šå s"±“f|C·ŠÁ·5 ,{CX?�òÔ)/IŠ_Ò ½ñ"ÑUÎhjš÷Ø/ÆÅmæPN=І'¹É°¡m¦^¢ÃIT6> )ŽÅÈ*·Ó J(,Fnn§c㫇ïàP�cˆž@•€Å3_xv€…A yÝ{ˆ5JEófÅr z¡à¥KJ!‡ÞÀPG„¨]Ä€ôø=˜j":a“pE¹ÝÇò\1zöYvó˜Ï:�â�?µñ£lÞH~­{,MDÚ«sýîlÖݹçÑtà»=83ц"iô8Ê¡|¤aY“.˜Žî˜ÐÞ×áõÚà‰r¿Z”[n®8„¹z}` ëís·–ðÄáìI æ|w-wñ £Cú^&¿iqVã.ɨS©91 ”ó™x’‰¯îòªWÁŸTÙͤÞKdj¯ Íê�§‘H Ü7ú9=ÊÁ!Ÿƒ‚¨÷=N‡\E´¸u^¸Ë w4ïÒT´!ÛánÀ0HNÆÁô¡™^Öªä,ë€Q¡ð!ÓcBôèõÆ&Z¤w›«é=h©ØJ�øþ¼yX~»\%Q<ã>Xjbú”!‚‡’�jìI$mØì8!â›gDqÍ'Ñvh“µ;„°€ã/òa?l>‡=ÕO³âù®[ÞØ³™~¦: †TÈ {ïI<‰H¸ÔÞéw=‘f\{®oÞ¶ïòÁÙ^óH5ÑÄ nަ;$ Hd<šá”ô˜U¦QYÙæ¬'`/q©ÙÇSüQ< ¶õçë®ö–µÊko�}#{ãâ¾Ê„(¸ò†¾´ÇÝ*þ43´fR÷ávÙÀ˜Ýª`÷“í§ÐØŒÇsé/”òíîA6´â£ {šð(4Añ­Wj‡{#½µÎÂCãÒê´ð¶^9C“¤”ºÌ˜Gs}²B(bµQ©Ç%ã Ï­z»ˆï‚Ï „yÇE{<‘̸… F^ÏmnäqmLž­–Z¤–;&™'>áYC zÌadÄM:k8øÉš"]ž ÛCÛkÞÇiŠ]¬Áù²h¡˜Ò“{R¶:Æ^D=ÛR�|¯mOØ€–ý§^JúÑ–D¾Fã¹PͱçsPý6˜ÑÍd]‡Rž«°…C{„½R™X&¢Œ×މòÄã]÷ÑøOáBÚótÑ{ûº}›üöNhÊ¥Ut{‰!(„eh©ú…5Õ¬÷M‡0F±n>vŠy–b\§„lV¯Ø{[o’ÞQË’^m»×'Þ§@´7gôž¿ŽawÕh_âxO¡k\K·©ÍÛø¢XîñË^ˆCy×úˆk×3Ë{D׋]§+£A¬ß…LúøaCžùîÛñ—”ÛÐA¡»ú2§œÏ“w=­»“w—à%ĦÃ{ÀyÛ a«6p¾ž1OñiCJx’ãòT/Èõ4 Á–ÇOby¯”Y¨EMΊꭈ¸¸¢¯>-N¸<©î @àäXQ|¶¹4xhy%ìÛ9Y“ñ¶ƒ›‘8<I¡À•A8ò½®Gm„ÙkLO^ú{–0O=†[PAÕ|®âá_H0 ŒR˜ç)fhÛp°ôàÁ*“úó Ïwœ–óðГO;M(§ 2aˆxpÅËkP¥�W ã ˆ;À4à°ê ®{n° ©”‚½"]Ä.=”I­¤Z|lT»Ñ’ùL:ÇBÈÉsëŒS “Ș—¸g©Mž†ÒìËn’Ô78ª%·/˜ºíÑ:€‰DƒáS8Lnš�à9w|š.@P fã:[×q"DwŸôØYØ+åë’ô•4O—]·"”`Â=ø¶Íö-uCd⡽Pšdž×v!m¬¦]üÖ+Ìe³DJw‰Ÿ+]ß ªç»B2”³@u¿÷2Ò}ÂÎy>¿.ˆ§™×±'ÝÄÎôXcÇ. ².¬–hÇž&,9? ¦J·Þg`a5.§Lá½Îéçowœ¨˜zY€YÀ‹žÇËÔe|ÝëBÜäP,ô\öè²7íN0âpy€ø¡R¡†bÁ…/뺢ä¾㉷oŽ i ªòå2¥Ú nËë)²˜°È^Í£¼$Nñò¾›iêð«å”EŠʾDGyÇ=ôºÆ9› #šžlØÞsƒ#mC €îGBQk1|&,Vs÷¼¢dÎMKÄ´›ìŠ ^àÔ1p‘6M¨±MO¼Dè zt$>(lxsCÒ︹¸;ð*?‘@Ÿ*™Ü¤â1ôÑBzI´Š Ã=MìCwÝ×ͽðéÍ †7š&,T JòœÜIŽóe¨Ót¼¼ r2 |„h@•zœÓŽzÛUpÑÌZæR',ÔWÜÍ˨Ҷ ÂzÙo6kQf߯\å¡ñëÙ"‘hsGÂT Z rQU$Óvì QŸÄÈÔxRlwc–Lm kâM6O8 îàjeÏ·‚¬z8.Õ‹#ŒlÚ1²FB¦`AÜøÎif²<„˜³Ö±Þ\¬ø˜ŽKN8‚é ñ§µÀÃ$Š"! ²\\勨9oKÖª`0. þ„ÂKbš{. *´¸í//öì²uÎ^äÂ%¥—„á¼7²€¶=‚Ò°aÃÚ-Ôo@F¢Å@‰“\yn%Þ cÍPËçlÇKÍ>5õpë’½îyä+d5ñÍ]åÌðÜÎNdÅm{ šD‡¤ÖçØú“µÄëëz2«ûl´µÞ6‚¢í#؉7rwŒx7Õ”¼ø�)Eç½g-^à”Ü€6 ]Ë%Ör…ÁâBÇ ¥Æé!Ía—Lvîb$7~nœ%î^ûÌ—@ˆ³ç~Éäɼh€ÌV2zóð³åÓȘ·Àd|‚BW[V%‰Ëd¥È;z€Ã§H²‡»/` úÉô;¥²ñ>Œ±Øz§h@Îo¡=6Ù+íR •š‡î¸IףʌB=éÂÃUq¢€5¡ 6‰VS)ì(] i„»Ç*·OÈSæTÉoìÌœ­Ü¡QŸ[íq¨Ç@6»Zåéu‚ߦ‡ƒèt¡¡v1f'©UOT‘½ šw½ÁVÒY¶Æ|(Wåòní\3ö¬IA£ÓbÌq°Ûƒ†½+Ø Š/ß(ªÃôͯùÏ(˜ßÏ{àPÛ–O¢•OŸé½4y$ÝT¿ ñ7ˇu‹„RÐj>6%Çs¤'Ã4ÀxT½teXT–Ë9‚= DŸPàO©llݘ·WœÑ&•®ÚÓÒØ ç¤8áì¢32˜ §èœWK“g Ï;·ûê40¢µ÷7ÄK:ž—¢·’D `bÇc³+sò˜3,T=Ù°BLußé {Ó‰9ãpäȦÁ½a‹|ú`ZzÌ7³(©�Ñ0ÊÖ|0fÎ`‚Yxž™ mµÅ»ÀkV­XKK—:¢‹naŒ7ž¹QG˜Éó±ÛÊd2>p{)ú|�q߉ŠJƒõƒ•žCË÷ÞÚì¶EK"ê¸Ø»ÀÐÅî¶Þ2ÒkW»áØÞZ­sð·ža!‡g"2 §f³î½kkUNqï-÷Ö9¡yÄ@žÛ³Ø*zØÌo®œšÕ´Q´@}½Îy3àqáì.g­^ÀÔÂÞõÖq—Uðxz!XK5aø3«=·SÈ}µéš-ЩªY÷Lï]rã–”7YNSqÇ,×ôs0¾ãŠ0A/æ[Ž‚áåsêÛX|{FúÄTS¸6ýMÑ•Ø3=¶fôš‘{ÐŽ¬mñ¦Ë—_[ÖAáI¡?3í*ŒV©læT§m—+½ ïpyS.V†ê(AÓžì•N–€ Ý¥å4›mä²pË¢_ŒòΠØà^š×=GV?ä±h ™WR¿TÝET#lyý˜»7KÒŠ]D¸ˆ’cÉuDÉkÔŠçø’Ý£±<íµó3Ê€¬{Ѷ9þΪ­‘Æ4¼+8}U>Rç離¡°QEÇTð;à+Èg>÷Õí&<ˆK§Qâ¼UÙŽµ0ã»$}Ó’ +7ª¡÷`åZó å„ÛC>îC¬C5‚òUÓ vÚ¬#” ){tW³:A¸}T«­1Þíï#ªr<'C…•` ]ê´qÜߌœfÕ‘ó‰Gðˆt¬f§³•Ÿ ?~jê‚@UD‘ÜÃ4ìÁøJ9»P2[å†CùñÍÁ«µ ]TìÒ ް™ôÓ+)žxßXøÔËbyaxݹÆ$Óo;ö€_Tï´–²Ù‹MTwñÔåÈF0\=NIeéD^o3ÖQD} þ:@ÛËu;�fvÕŠ @».[s—ì9­Ü!_ìx ”OP;‘‰uRîÌA Wû¨ÒCò’yRY@ƒVÄâcþ@OªlÖ¤¤¡Ò…‹W9ààFLómæHTcâc¡¢MR¥¸rxmÔ¯ G<E«F ý–xç-M'¹?¥›Âá+z. ÀõŠö)8¦ß÷è¼?_+Û€|Y¸cÉX8€Ïå½~çu'šv«ü^¯Sd +øý}Dz”›¨;íyÒ±P†ù‚ŽèE6À£ªH]ve³‰>!°"qyVÇ7™lt«ÐÓ+ÑD̓SA�bLÞÙÅ�:oµéYÑÕ’óØC2çòPl†÷‹Ž£ <µØc hF~¯0(^¨ð� ó€^oÉÊí¦ôƒnx7œÆ¦|Tu÷ŒÀåq^Q¾¸¸pÒFkIwªK¸æñë¿­ñ7ç~6×t†Ò^`Sx¯¨KÏ ý<üöÂP;¡‹’ËOøÄ¦Þ½*¥ç‘Iž–q[³ôÀc¹Øb¢Ï›ÑKÙûÖVÁâl»Iî½%\}`ÀFZÌ·¸”jÖy§x¢î´zÚõÌŸs‚Ô½âž(§7û@ü²HäµHÍc©Ì*WFfF@0µ¬Í¸Oï(Ç&I[¤jNS´Xš­s™pÚÒóåÜE7~=¹yˆÊúŽRê11-2^ žVÜ‘i„G¡ÕqgL¿ì­á{o|³Àßê»»ˆ¾锵ærU$=ìÉHZ¿±ÀGWú,Ma(ù!ÍMJÀc¹z¯Ø×·åÄwqkwy´jÎÖ=·È"dÞâ&^?¶QO÷zF—Þ­ h©tÄ ‰ã€÷D¼ý—"›ÙƒŠ´ˆÈå²ÖE¥ ÏÄí6Šb”d�››4Ä£b<ÀF8£ŒnÖîz'n˜©Ð=Þ½¸Ù+ZC+ùƒè§WàEÆ÷,àU潡G X3Ê'F—‰Uö�½oQ '×M&¡a”Z¢iš[Ó±�æ5ë£, G'¬7ùÒ+ùuèò¸r6ó"è"®q›5¾À:™ ¡X Q«ÓDìÓ WU9DçÁZ'ŽÜ :.¨Dƒ)H‚�EAQ7üÊÅû¡?k¿9ˆÂS™6O$)éä¹JpÀꜹD}Ô^ʶÙWÌÌå’Ìgä 6 #`Éç¤âæ®§{<[âÞ`¢#ûŽc0-Çhá h¨ä ûô½B7o $ZNg_’x›Ž­W÷çÎðz,÷…Ⱦ~}ÓMÆ9Ëz/®ìíkpY8xÏ19]ÒßËÇ…•XõEt§�VJº6>p¡óC{WmѤ.+ öY8kûåëI6)è~£Dïh‡u‡¦ÓäÙle­Huî{¾ÍÏß«A7ŵóõn‡xÓ¬(f÷r…].³$òæ¶Ž$œmvåöÛ°×ø‰§@FÑ4ÍÊ¥žMƒ;"zJHºKlO¶·Øê O…Ãk«#æTOÈÀN×3~UO¯öaó„>=Õ†"‚~¢1FU{¶cà_½S©ÈÍf‰Dìp}]¢Æî¢ó*kÉ¡ê‰òéë�e ó{0%»7ܼGE:%{U+Í‹O¨éNÄ3CÒ!žÈ#ã¨yÏÇ£.â¤[ÙM··Û;•7¹J ù`‚ßsôôÙw©Þ’D¼·þ<${WsléØŽYÀœ€ 2ë@»À„^ $Pz3X9éëÒ€y#Ñ„T|o(=k#|×h–œÀ§+;Ÿ•ŸvH‘txéƒtÄÎ\æ’¹|çª|¥æW8F3sqýì—/S1ÒGÅÚèRöšh©NïÁÛSÅìe_#Í^ÞC ½×Q!øîë~znjwŠLš­¶4ûd´%ÃXóŠŠX99ŽRœŒ¡™ÞŽƒÖ êf=‰Ä&cq¶Ý£ÖOžÑeˆ@œ=ˆ¹îO4(ž’ÚQšœwî¹oï³îy ¨@ø¬À¢ŒÌ«epµecu°ÄeW8`6‡ ×+Ñf{Ct Uåî/DK“ê4‰¿1ÔÐ K^ [Æž]ö—Èï€\PÞ¼æ´qE„ ˘K°³ž`½dyJ 43/¦üb‰§&“ž:€½Í—ÁO··.åQ\©Ý‹FïÊ|yºÃuü~qî²ÑPù¶…Å2ºÒÚÔ:%(Þw–1û lodP:À36ì•0Òƒˆv×ÙÄ,îJ“kË}÷°{ž"n'ëÓz>ýùÛx{õNó¦ý¦iÚSà iÖr úÆåÜxüˆ_J{Ž’¯øˆ>ÇŸ3­kHÈ%ˆ¡é÷L˜.r×Û–Ç=‰xè~¼&43ÍÄ0ÏÊ™YòÀWà%Pº˜8Yh>ž¹Q.éÀÒè‰z÷l.eÞKˆ»NW˜>Bí÷Vl’Äã lûÔpºP z]A'£—"ÅÅÊÉŸ hJÜ“%e”2«7Ç!Lȇç…mƳP=èü:‡ê:O&׳bÌ^ÀÌ<Ä— 'hJЄž˜4'²zžIì»tÔhؼ^á]œ/D/ÃÖóŵN‚ÝÌè³P§)ËWpÏ‹ ëj$õuèv{ñà½AÂ"a­êNž>Tz1y—hVزž2¿¹×‰€Ž„Ѧ¹âÏn6“îÞE¸ü¢dªzB€£n÷¥ø‹»F3{SXuÙoó_…áKxÛë‹Vïih¦ªû‚WȦ‚:h5$ UeŽ"Fa‰GÑÓà mÍå…ßCµqg ßapG¦GC5ˆOpnK4QáH„`ŠŠæ© ¿»I©2e²‡n8óò˜€ó�*E ´ƒjó�ÏÇL•óžeŽJë(^îãU¹-&„¼ÕN¡÷vyæ¥H§Üت`¶!zÃÍär½åçú2»Ç{Ã̘Bµz²b¡ng•ºb‰ïìêšgÓ ˆDXVzC‹¹yVJÚ'ìS>ï‹Ÿš ²‰¥yÈ¢â»zñò][Àñ)øDO1'ŽTp¹¯ãeóÍIs0¿Cª@lwe }!‚è±y§Ý“-ʦEa1|¦»ûP‚øÉvùààcsS·ÑÊ~bð´ `/×{[î½Ò{ØÙ‹ÙF®'åNÖ©‰¯ôêDˆg@ö@:Íx¨‚i¦ÞƒÛÜöÈ”Õx pþ^¾¬Èw«@c²V‹z÷äé´2¹=7€ÇïÐ=kR7ROn`°×FL¤ã.U ò Ô8è/(ŠjÀ8f;¢™wÒd¿~ ð�ízƒVÀ–*„²/"”ËÙþÂ/¾ŠSow”f)46§Íw%ËBù“®<+ÔǸ£œd¢¹åš€KV½/2íõ˹~³¡Ø°8‚’ôˆ«,&qä’höŽuøà€Ìéq-ßös1ñz³dîk¸Ób¤چeNùt$Ù«N°ùxM£f0:Ùl.E4$ 4! *¼–}×­BVé„KQôúEh½yôt¡Ë’SL±(nÁÐ轺Ge%3•ÈÂèLu$à'‚ÑÈà =ö{tÓ}Ï@±ü! Ûw\õ)] äèQ³½šÌ1Sؼކx^É€F)ЊZ&™<öÂ5½²+'g)ÈxМÉH´}¹ßVWÇ"¤úë2K{k­¾ˆÎ΄ÌxgÐU-HCC©”9šÁžüf,ü0ÅtNléîäD£Wæ1(&¹ÖK).¼Y]"‰^Æ'QŸW¤ûë¾!¾§ZãeJñFÞ´wï8´¼íRzØGEˆó@âòü&éý‚î <:¹FÙr¸„ÃîºM”neʪG‘Êyç8C’ÏçÅRÖBS´§ié•L NAäÃdÚ×`®¥‰D‚†r>Oöž{³*a=‘46Z‰ÑDUÅ öñ´Æâ±|XBxr-‰N ¥7™S÷�;bö=ÌIõÊKVäsE²«còÐ.Å^ò=r½RBl¥ïÝÁ?5ôø/ÂCOLWe;EŽBú²ÇéH3wÄÔçÞ ê<|¸ôH¬’Oxgã١ǽ°¡ »ÞH8)Æññ˜±Û(jýÊJë¢C¬FM餩Zð…±U•Ê+ŽÐwØnûzî5WÈxæ.Dµ_]ª;­¾ydîâX×x8ÞJº4°³NžÒ,iŽ/Ç”å…ÅVĽÈËíÁV*Ò>2gáÄ*µ4Æ6ËÖÒ¢ 9>x¥<YÂ䊴Éasüvð%3²*î”éñÌÆdU‚ðbWO[$s?·NóÇô(ÇÜmY;`½y {bwî_€ð*\|xí± Gc±éÆM7Ó¸´û²HcmÙœºzÈ�Ýä°V¢à¼Øû‰Û�–®í ?ܧ ±ÎPœê‰¾•`É“>#ÞwÐ ÓþC£;¤]q;w»°'Í×o£ ¤…Ù¹²C°ÌœwàÉ•›ï‹‡¨-îZ.õ¸êÉÃÛ­m*7ÕJä[¶]XÇÉQ¯G d–75"ËHʉ‡uÞ>{U‡WǘNýbÇ™„B9Á8«óÐIê{ùˆî0GÄéÒÀ¦�|iw$ÃPÆÖ‘^ao8¿á$+Á0µ2Šw�ŽA³jzЃñzt Owåœ Âß¡@Út?åFVA³¬ðn ¨NÇ Çœ·áË6o\¤!=$ 24‚ eDº*7ÛkF…IØ£ÜÙpËP öœñµ®ÈÇ!gÐ;kÐ K³Ýeá[âÁxäÍ…ÔÏë­tò-¥õQ‡ÑQ`HÅÆšzìS>7§Ðcò¦ -Ž5ÍW©ïnúõ;ƒ¼ª—8‡Û¬ÄÕÐ7ƒýÍõÝ@è"^sÒ«bî„d’mêº&á÷… z³<甡4/ )^OH³É<Eg‘8½8¹@—`€Xçµr2¸¡ÄKÕ;&šÙÖõŒ(ô,{îŠjq™q}|Ä} IÈH§qbÝCJ€’oêdÎJ |ø¡30,b&8¨•M­ÒzâSHSâ;ðbhzmÌñJ•‘Éô-:·ù¡Å!—Å*‘iy¶:¤à¡ר‹‚WÀðN¤k|ý:J¶qS«VÖ˜PÐW+YÉÅÐôBz•Õ!dœŠ-oÆ=ØzÐæšâ蘸2ôPŸŸÛóDª9K..zמi ÜÍî˜k—y©ÒÚ´‹E9K/§g –o£?u•a Ãµ–}eŽÔñR@WÈ]† °*h^ªcB´³p•+æy(kéRD‘—"ƒàŸ:?QJ8²m€.W¹–1Öæp›}©†àNù2ÚòÕ-î›Q ‰ÍÇÓÖrZ"ÝML‘C‚Ϯ粔œ<ŒªfBZ}kY¥4 (ëËRìù àœ€®¢Ž n!mžº>®2Æ…jbb7@q{‹|Î…Û¸ïrËŸŸ<ÜÞX[Ù«ç8·2®5¾%ØÇÍ:Á»×ö&_4Ùæ.Øþ¦'Õ-ÞúfáB…>‹RX1¤1šoagÈÞ³‚yq±p8Š¢s½(«‘eª0Ͻ»ôr/’áT4ÒŸ$XË.A<í]ä»§ÁI52îÑîé8ÏОÍÀuÃÌ`çÛ ‘×ç=iK PLúZ#[ å±LÖP( ç¸>7ÒÁÚk®&Ùc39xh•o+î.Þ‹ée‰U> ~«Ï†ü1Ü)ö£’5¹·Nr#Ú*·5�¸«¡Ðæ¯ôÙ¤Ûîã¡—.cé,G†ÑÒ»mðxº_ÃõŒ½G -Êb»ìK€Ò ™;)a·!¬ÎÐOC¢yh)X$L/|Jnœp³«±^‰•²SÇÒˆï™.úùÕ%1®RDÒ„«/¡ä3}ó(¦J÷j*y7ŒåѼmË8H4d硃 À¸®Òd‡¬­kÐ|8-y~uXBîϼϙW”^¤^S?´¦nqloßœÄVÑõ:?Õçv¥š ²E`;)>õzvÍÇgcº|ƒCN\ÏM‚äÌHÛÚe3A`žš3}#">Õ4ºâN/ë¥ä -Þál.8϶8\Ø@ª¹ËÜ:qÅ\6æ‚©ñë}j‚¯SðtN’Eò åF³.8{’È I˜]ÒœõÊù(ÛúpI½«{Ï�^¯àC¢*[l^«\æ)¢¶ž ŒØç\è|‰\ žx-�1Q/|jã= ±—¦Ï2^ÖúÑR±£éð<Ô21;–§œÏ ßܲÀ€NúéeˆºEBŠômÄ¿MÙd³JÚ(æîð&~¤ˆyñV„X¦ŠYÔAŒ­ähÃᨸ¥CѸ|¼ÒIKôøñ{éå(>´­š€/LðnŽ@:Zþ„Ħ<(ëM0öÃ\[i‡ A†‘ ‡Q?v[`ð„A›g1ÁÀm´ô‘¢±dq3nÂÇ‘»®ŠNs¦¤cL¥%Þ<úBplJ”að˜ÕÆ hÁñqÐcÌ=ò+;€ƒ]MÕ6z‡ä/LgŸ8âúbå)¼#ï‹·¡Ù§[Û=úú9Ù4)6 kxQ÷‰ë½*ÀÌ[õAòÅ«™’Š r娩ªøÅÖZ[ÄÕ¼ŠDᛲS·z€ 4!ó²·¯‹±õYÑsã�Dm9Iýª¨ èêÕÄ+•Ån°V\ÌQk8)–&êp\ÑÞm|01D-“žŒð$ç±…Ï>ô•ËÔÞÎÒƒô„Ií€;ÛÞ-$ܺ=dºšžÈ£›%}£e V®=“堇ΖµIÒV¼ZF9øÕ<oy,cò­—ؽ&Œˆsìô|/HÕ‰ffãj[ÞëxÏ1ð=X“ó›ý"qRõ±È­Up¾@A^‘ð™d— 0÷»É­0ëôu$ôy›!MáØk:/žšWËà¼âäd„ÙV ˜¾ Ȳ‰ó±[ÃÂÄ}¯®iô¶uÄ."(dMà{3t—zЯÞ ´¯ŸËã”\=|ì¥nŽçÅiÒ.,n ºÄ€¢ãPÖÀOØÀSŽ5g—ˆÞä°½î‘xõXßæ†F¶ Ã$>%5øÀÝ,¥.ï©(ø¦Ú[v‚ÆLcèÖ}~Œ}´ÂrTÑ–#»Uû Pù»vž‹ôk£o\^¢ÀIß7Jº(7Î!”+ý±�rz,ó&³£àT)W3‹E0N(0…ÑÀ†-€xRs$—$BóÀü‚ƒF•f ÏÉ5:ŸU xÙ®ãâóFC¦ì[çzpû@m·KØ8eXúfãxh/Þè€H„ÇÃàñô‡>¥ã(Ÿâ<€1d£1v?âgŒZê¡dÃ"÷Á°³«]%Ë=·qBËÊ󤊓AYêÐT×fåþÔÕIž/óñ85€Hƒ$¯Üè ùÌöLµºé8j�Ó‹”ÕÈ'…Ü©O:ÐE—É{ÛP¹Æ¤N!¯Ì3¡Ùo«´˜ƒB^c6«°#<yH(Ëbys‰.¢2¡¥õ’‹taêJa\EAõ¦w¿å¬ÑĘ0ß*<K•¡p‘\±1bZ¿³-½µ0¶ÀCvÅ#H~Þ—q ¾´Í͇­-}/tÌŒ%r»É¢m=R¸L躎œÕIz7.¸ëç’FxPNÛ¬Ò„žu)ÅÚ¨½Œ1�ó‹�ºß æ8m‹³ñã­)Š3}îv”Üëeéw³ûÐß›¹xi´.‡øæ¥.<j}�¢¶Ä$ÝöÖÔC*y%ßLŽnTÀÓ‡3ðÔŸžF÷Ë^›È¬ŒCn£ÖCäY9µP‹²|ÛíÈôª+#¨y±3G§l"ÀKt‘w”1yžâ°;‹%NÚÈâAÔmL=ZêáÚGå—Έ!>bâž ãsLÄÏ3‘zot›ØSÞ˜ŠòÁ´s€x* ’9ɰy1ÖˆÏã(YÞ•`H¥*¾±|'ŽV‹”e '¾çž„ &ÙÀò²upzTö!²«4çœy…Ó–­ßó4Ô¬jSM¬,tqelïJJôJqN¼éw©Ø¤)ÚÏã‰uÃÛ‰¨V‡ÌézñÜãø>}„ùË*{)µDñL¬ÞвÔê>ˆ=�àמÂt;ºÕ ’vHT0ãÕÄ.¤;¹oñm£¯;Ùœ%µÛ6ëôcœ]p#®&ò¦Ôn ³$X’šzRì«w23;g‚‡³§øæ-#L&%t° ^$Sž* ¹ yÊ‹<Ï\dtðöj+…Î~ZÎÙèLºgü´…mƒÓ ü�³ëš“üÉæŸ<È�Ô{W^'¨²ƒÏH¯ —49ÒH‘b3iÛ‰A£°I _Q–»4¼V†Š3uÝ‘‹gËØ×c¡·ÜO´еßSÔ¸{b!¼5騰rŠë7…–Á€ˆ‡T0âtŠFøä=×jðEÒy†¡–ËRnnj‹–éëO§gѵÇô<^5{ óËÕô)Ó¾=¸]Ýãr(Y Ý“rÈ•pðBÜä%pðp ìëVkÆÐºÅSAfhu|}BJqAsx+8(ˆsš”š©B~¬›o�’N¹žtÇ®ç€,=TŽpkRrÛ7„“f;yJoÌvßðŽpÄ«ä€$ž1¦émQ› ±Áñ¦Z"ˆ{’«øLPMÓ<«8â"ž2î7vƒ™¤kÏùbŸ¼¹·Dãê í”… ‹Ü€Å¥‘­ÓÂY$3þQ7C[nÝý½zcèïj£è¨¯vvñÅ8r£a>°ë° Å-{;= Ò´T(Ä A™"Pí}ç³Ô2†ò½Ý'á:@‚Qñ€ îâbg¦ŒØ ÔÆoqpÌÓìp›y‰v,s†•ÚFMW €2^ £éó¾p¹ #¢º-+Mks%+ÛzK'­¯S^2¬>¶p~Ç}ê)œÈ¹E"äð$¡j(鑼ôib^Ž· •[Å+°a÷8ËRÏ¢‚Ð~Ø·háD•råb&ØlH×ñ¼XMIP‹g’VR‘-XSK;³Á™­tÍM˜›%DÄôùæ>;ÁRÉÜ ^OC£È¨… ßï}â}Šk¹^Gˆ$q1X†pZDçF'ª ÜçpO¼¯™Ü d0`™° £2ÕžQ%´xÖø¢3O©yeò;"¹w òÔCQzJð+*ZªËðé'‰¬º>– dïu½ªÊKáÓȈ##Ù•™Ü×ï …Õ„(ɉ7{ª]Àbe^?D;@Usr BŸÔ#ÆÑ ¸Æž"yEp¹,Cì/x°”ž¼Ydc¸W.¹ò"f¶ íÍzé@åÃÈù¨Jᎉ‡bŠNœdã¤bÂEcɬLÒ ËÉçžFyr‰ê1T–˜±È 5‰v _‚V¤õ>n#´D{ó§Â~çZÎn àÏYÂo'ZÔ ]oIÚgS0[bÈí=ÑÁ\õL5“{’"Qf^6ÄÚÆD©çìJ6´/eDvpÝD1…5_Zc�€WÕö#ÚœyüÆ.›RÞkÔÕ§§ºSúòÖ•`_ug ,sFŸÒpoÜsÈ—ö²Þ  Г£7kÈ®¶~ÀóLÙý^¦¬¾)/%~n œFö(«lQ‚¥N*´íe†Ð”RxB8ÉÊÎDPД$껥åN!ד¹~ikàX¾¿nnÄ2ÑÂ0ÓÓé·±Dd¾i{æ0$©äŒ%#c¼­ûªÀ¨Dž[*cTkžI Òy»›4Ùk|CñÆÎAÁßVd¼4W`¯‹ÔÄf?ö ½Z¯JzñÔ¿VjŽB|9†åÛü2ÒîÙ»'Ž!+m‰0Ñq˜äº@\ûÒ#÷y õ2Š>Ķ‰Ñ½zjã÷ªÙK2M­ÏŸFꇮٞÆ]•hû¾„ÛTŽ2Cm5Þ ×J…ˆí@‰s\–û€¤MìU•D¬êZOô1Ûñáál)²€o-»LÑV¸‚µÛl*\&ÂWŠô2<^°âBâçÊöª­´µéÔAуñB…¢çüõ ì ?} GJËn—SU10é÷Æhƒ¡%­ø.Á˜iH:Úc7VGµ_ûí;¸ûFŧÂV´w†©‹Ë«hW9!#·Q§QK«ÑfÌQQVàÍꉖka;¸=ôl+‚AµÏÞrJ`¨çzâÓ7ª¢ƒ`°Øí“¤‹çŒ©‘–ê¯Åa4çáDR^ãA…Òb§daÐâãÄšÃ76XqÇ+áÉÅ‚q†ƒö‹Áne©D`lŸº÷€ õQ&Š’MD¾f€;Ó£',òÜçÙ‘ìª6æ¯.ù|hÈ=›*läà,–…ÑDH´¨0EC E–eÉ=Ÿã/H«Ã(¨‚ª¥ %6±Æ’‘»¸,1›òÔO`,:ÚyMàlà]¦x]þ íDA5AÖfsææëàΖyT5¥Ü ùæ@^Y‡ÚŠ%›^>jjTh62ìÊi°dMkX(ïõ"²ÎÖ·Æ‹Pê­W…$l½n¥ übt ‰¸ ^=ôÆQu]Zo»î×<Û@\q«.öŠeÅgCêh>zƒ”°3“,/9+KU»ä¹Ï ¤À ©×FÌ«ö~,üâV�†:º]ñ6ÞóÕ­+›i!d/!Øw·(T~ �¶C‹Y¹¡Ff:,Œ #rÄNûñ;ë2{w :€0(šC2;Æä"bZØ–L fé^u¢¥B!…Jl¸ bó¬$J„w»'²ü‹- @Ë9•È>õí±Ì(ºmV/“†óª*pr'ôòÚž‚seη5ˆ7¾8”'¥<ñj[ùfö®&‚žvN딃½dr BˆVò“Fd›x4æ\íˆÑjÛEÒ:_ÀꙀçð¶~åFé~yÊš{JêœUUᙞejÙ<ÚsJ8 �ÕŠÓþÞ½S<èxºðˆ²Œ}=MDùjÊ€¢g(ù•E­rÕ$GÀÕ¤È ‘,ÑIÌ…­v>ôyø¶ÌpûöY=•ô]ÏŽ‰#®¼gÑEè[WÉa½f¨³9Y÷dÎ*Hí¥%m³NÞzÙÝ#BÅ«À“êô˜â‘{Í蘭{…þæ#b®ö¡4#:…gGÇæa"]wÏP¨ƒ²É+}²ÌFx&ÞÏØFMØyî2E.e_œåÁ â¸l^ó=xQ†Ö¾Y1,Lï—Ji(^êð ¡’,ªCJªá˜3âUpq÷PêÀf•LUV�¾0yÍK8fT}ÜÈÅd6I{wþ¸°ë]½Áeí€X}ºó&7·Mm)Iµ _vGm%Ý£Æfì®ë]hD^ #;‘°†:—8hS[t€—ëKÑOŸâÝì‹C• H®¡}+eK¯àXæ(3)‚ÞQÚ\H)\ºáË÷ ¯ó({­±ðO_ÈÑ\V©î~öpã.°›ÄcX@„DG¢ÜB+‚?>KŽê|® ”c`Òª@”%²ñ”ÜpfDƒiDý\í=â.ã¤sa^³%¤|±WIjGiÊ“àÙO 2EE?ÜóG‹«mÔ``$Zêþ<³µýäÞ{Ç-^D½‰™JÌÓD—î)µÝO©¬ë�€…ÌÁ‘Û¬ß{¼¢Hóº¦Ù7Õ�fa@‹#’Üý„äƒÆÚ5¾aGeÄÜÓˆEL´;Ñ—›jn|7Jµ `¯Ráä镼əbܶõ‡šýÒ¢jŸ-¡äÛçg úÓÅ£ ÈÔi“ÃY?Gìê‡2"‹§Ã'š9äxWò"ÙÜS“—AcµbÕïLñ¥¢dÛËÛ6ÅX¸§`8žÔ‡WìÊa#y°ËrÅ™°`°båžÙ ûÎÕ™ÌyÓa*I‘*JS¼^2#wÁy¹ÎÖºY2Ó“¶!ŒÝÚï`U×sÅDgå¹²ÜfÂúaËéA e•½s °¤H»¤¶õj{õÈÆË±wÐâu>(Sâ2‹*‹ i2ŽÌ4 Y¡»¾"Å}C‹ê—` ɨ7b&aæ‚p^í „$]È2&D‹àº"Nì£çŒÎKš–0©³f)Sø8“ùí4ãÓ~§VXœ0»Ÿ¸ào­M£OØ„ç–ÎMR}çúˆaTÓ³Ô.FZØ5CýÅ\6ˆùó�õR¢-ö1z1UÀBN»ãµæ:‚´»olÏÃÜÄŽ\Lò¹A#óÛ1x¹ÜÆzzÂÏX]ä= µ.ÌbC~Š»T›CÇSˆN/†¶ö¸š=ýX•¦ª“°µé� Xï `c†;;uºy�ÐyÏpóQà˜B‡€!Lq\<|w¿JàÅ´ÉëEwµòhö9gÕ={„kÙ¢v°%«ïm•k×#“Š­šC|x¼Ï£‹ž¿\ÚÌV”·óx^Ç«\ISñ'/…š£¬àÍ­ðM½ �ãÒ>BÈVý×#·³&ÐZkŠR]. ¦ëô"ZÞ«iä«lÔwñ¬ “7uÆt™  íÕˆ†¨–WÃC àôí©'{©Ï_@"ßÓ—²¯áŠŒˆªæ1=2‚¾a¸FÅ&Û-k ÓÊÂC…Nó«Ð>$R=_“ëÇüöuåòI+»ªÖµ]ʤÛZà ;ê‹77¢õª‹œŠîÂ]Ê3Á…„ D›Ú¢„)ráð6Ë¥‹ëö£‡e¢`.+K½H9²¾(I/�M²ïyÏ 5l>k¤Ðº˜gFõJJÕâ.À~O_´ƒ˜Íª½b.Æ(¤|S:jn6Ñ °‘'Gãž´{£g³lÂXNŠ'¼*›~¦sY/PyÑ™+'�³KÉ8ËdÖí;’Àzí‡ˆÉ ÚÞòÆ¥¸Áè¦êž\;šøCîD{W·ØZÈl*ôŽä± ŸQô2ÉY ˜Ëô(û¾ ,ey’n.G ʬ­Õ¸u‰ÑÖ+Oëó-‰ôXcGï¨0 ç{øê¥›ú±¿…S/Þ÷–ߎŸ`““ÉÅ%K#Q ŸZÔaLÇ"Ì™Ÿ-€#Ö Üä£U“ ÷¼fa—ºgØ~S„šôÊÛF§Œ¼(˜²ýÊZo]Ó™¯M9„†â‰†<XóKÄêÑ‚<ªõµê�=QwtžÙgnpkk@'VÚµ0JöîÑ{õ ùÜo§Ÿ¿» ¨0DŸÊL B–#¥�Yêš7Û£ñЬ�Ð¥UphÞ¶ ™Ñ6.» ,¿B3~d¶6«å'²�éÉSl ½«SàòbCÑp7H"“ªÙÒ´(Ë 9œi‰bÕA«HVò\žA¸ÄÑxµ UWj¾’SYÃ5Ní`Õ#¨§SRÄlFÖO/<2!–@»ž×Aö!èy䑱lÛ!õ×)ÐÁ…,jLOxI¼‘Ð,Áê^Áv2y©]^{¤Ø£€ç×rÛ7Bå{!¾‡° ^vÒñ(' Ä·AÍ�ºµñY*îÒ_Èn< |T0ã.ÀwšÅ—ðdÈžîÕ¹ @¯T®Û¶vØ™ú…µ3b‰-tQð•«rPÕ5x\òº‰‹_õ:òlU€\Úã8›Z#;9µ'}¦óR cBëzD(uãQÐêH˜¦j¦<&²ŽæfxFÔ~úÔ<®Ý!0qp… ë D˜G³‡c¯ð´ùõ99�%¹ö̧A=“q óàÝ׌¯§uémÚQøãwÎÃÇ5¬1»‘ƒP†¶•ùô;¾Çdž$ã>‹&u5L6ÍSÈæ<?<ìì“1}‰$ÅŒÝÆ üá+¶mP´¬ M3Æ­·àƒž™h$V|o&+Þ[êë ¬£¹£óÕ~~säÓ܆±žgY»<È@ ‡Ä®ô’ÅÀ3ëÙ0Œ”K:fÛÛÙØÇì‡Wnbؤ„5Ó ��ÄWmžg|PžX5»ØÜN�² }–gþ¸«ªn !ÆõeµeîÞÂ3N‘¬Ì:HrôXÖê=HžòâðÝV_ )»é@³G0×öŽ%Ó@ùøµ<KYa£z§>Ø^ 5T,^ûjï5é£"OÕ§ºÙ›ÔÔÇ}¢JÏÖ|›¢W„qÙ‘ßí‘Cž âN´’=¾D%çãÂÁ®¦Ãvyð¼+ÒG³cW¼Õâ ÆaŒOdè§ê¨ç©™x+DR]¾Ž;ÚÙÓ¡¯ìΟ³ì–k˜)@ŸAUú’…"ã.1,]¯óKòÈ« À¤šn ¼·61+´"OD¡¼=SD@¾Î§-Bq7§¤f–={Ñ“±>=Å‚Y¶—LYó¸Ð_M8v^[<eHt*E &Àn)ÚÌÑàÔîÝ“I¿|T|ùRY$ZR‚�,æ ´`õì+ÔÔæ@C&*Èœ‡GøLE¡X|Æ <Ê«ºcm¹âÜq³G;^3¡{"òÖ3DIìkÔ±›ànz{Ùù: ž P½×zc8IivŒ6ôÔÅÝóOhè5®â¼êg2#Ùóú9!¬j“мé@tÎŒÍÍÊç ‰¹ØfrüŒ‹rµ„; ÚÉû]nƒ›c5++õîà‰À8±ê^k…™G'i¦&­PÊd˜ò²Ý‹v]B»¶¼ƒ²(ìg®yK'k—v#ï†ôWy�˜tb}Ž»•¸U ™£x´ðú8¥Êê!îc²‡Lv¹æd~Ï ËfmÖYœ,Ù©¡uÎ÷©Û\ˈ #‘hB³ñÅ#g e…SJbtŒ '›º¾9IØÁgÞwXNùö’—Xz‰SZžP=ï±³H\î¶xã¹q˜¤Åkå”Ë=9)²$úžËTÁQÊQM­«±°ŽÎ‘s3Œh=×!ˆDd7¬F_džGÄíÞôOçÒÀ%2îl8Bkè²^„¯+Ny­'=ö÷š çêÒà|9š¦VD§¹Ã¯ßÅkW€vÑ46‰<VUôfb#Õ^àMØåÛŠ|VµX[6»Œ.ÑH A1"K3oaðI±Ë{(›ˆ^ùxâøy"çx™PÓ/r 5H\;Ü–¤—“œ½€ú¬È6w_Žî°‘.Þƒ„ð™ÜV|¹‹ö‚ i•…ưÏáÚ^„¾šÃþ �Ö÷`"ÂÅœÞ])s^O¹™!?]”YpL‹‘/A†Ñ¾¡áŸ{Fh0Û  ÜËŒ*䩽·êÂr> !P·ÞPë³O¸ŸÖŠåÙhõŽœãXÞÂ~.j÷âdÀœŠÑªBë¥èA{v*½y Ñ™M§xV,ªer8„w¼Ê dÞ»™iO“Ò¹‰Žl£§VŸ–KB‚rzúˆ®Pæ!¼y4sts–J.©¦˜D—ü.}¦Æ%:ÀKÈT�£é`ã ™{_¶ØÉØ »èŽå;õ2¢87ìu(³wôZ'=çõ>H/ðKÜͱ&Ób0ƒ0 „8·5Z¦ó5b?·&§—¶÷ªV,"k§Oìm:Ä#:�ýó<¥ˆ(¹ïF˜Ÿ› øR¤Øœ§¢X?uW´ôIå öw’޶04·Œ}G„Ç#Ka’|™ÊÊ-žÜ’¹àëqB{×Ôý(4={ê:ÅTÄ±ÎætL^ð#ƒ(‚)G}PqªP’éoS;\E'ŸĤËò6 ôÛÌ{™³“¯¡r. õ¬_.Ť&j ˆ`YÓ“çÎ=± «îb£CeÇç"¢È0ÄbÃË!߀$Ž’†ñ»zÂDÉø°Lý š�ÁÊ=SmusVê8ÓYò_Èá™å{Z!f\#[ÆvÊ,ãÀŒl»ä…Ï<ÞqAaÐcƒbáóÃ* ËwªYHGû�¨ÃæÅKsóÅ×Ë–Šq}ûdÜ ¡žÍ1\›LŽXE�¿åÎÍ z;ò:ËïfCv„Ô bãFÄ'�¾´y"™I4Æû^ ­x°î[¢s!ÏÝej“¿ÁòRšw¦!ÑÚíqò…AY2Ê{îx«ªÄSÄ�SD¥/u 憽߭ð"s)\ËPµÁ³æÂ·šà–±“ìéóy`þzl–7<_ÌÓí вî^šÛyÁFáZ»s¾fB¯ÆðJ 4‚Š ê<•[‰B• õŠªQ!vvUg[Ó§o »vý 9½ʛĞY'çc”xË6RŽC_ë˵}rÏ8äö©¿í¡²(Q2çkó€ǛÛ'.&Yú8Q?u“i8bÍÍhb›6R´Û ,­(“››Êö4á@LL§‡BÇñЕŠ`+#¸¹è€@!¬&ˆYùËð¼òè]—àŽiŒµ¸½òw}ƒÏË’+‚õ8;’É|qu±<Rh‰zèMÌ Æ‚®¬)Iß|‚„,¨Ü”¥Õ5O°™}Þp[¶XJô{.#ʇ:É;² ¶Yï öèhŠÀ¯ˆßœlI<Nö'zmJȘÏÜ‘Ûßè(±‹™°¸A.¥SÛ#Ȇ—( ·hág{K$é*ùr!8êáòû•§à1›À>¤ô«¿ÀAUGpyñ;–öÙök´¬Ç™¤FA†ò¼+<u¢W„DHd¬G%€Ì²„W¦m¬í ä©`lÊËʸÅá€]éBV$?Å ±–Þöa%B“ŽH� ˜©p›·@OØ&¢5°è5¾1ŠgüRrÙ¨$ÁS˜…½j›¥Bf±·Ë*4Ýy2uìLû:îQ[KÚ/Àh^ªÞÕ%É¢ªßN4ˤÙ\<Q>p4:Ã29`¨ÖnäxÄ*Ñøj÷Ð[¨goïݱj¾CõGc*±À9Чõh¦ÓëHò<^]y†¼9ÞyÂwÙòú Ûíí¡ì!^n„ÚµöC_ë¬ò¤Ç]5gǘùòQTé-Š—Ööý"f2³ Ϙ'8(TuQ• £Ç•¬ùL06Öh…ÐLêðd•Ø–ÑeÁ¼Î„’¢Ó|G+¨_®À¹Û«~¦,wd‘¹×Ô†0‹ŠÏ‘4Ÿú hUïËäySвSh8w<ÇgÃq híœfpãlvÙ£Š¼û½×”àᇖ0‰Ãõœ ­¬©ÉÞͽä+VG0A]Êé<Õ÷ÐÓH9B5y4^3Óš^/"Ê]m|õk æíšr-»’Iì@Vg¬D§ð½#ϳ½¶Z¿H\Á2˽º‹©Ø‘¬Â÷ÀúÈÏ®¢ÒlÌôæ¨.³?ÁáŸ"\ˆž$rqx•!‹qñuš›ú)·²š`‘Pv¼Ê~Mù|3 nø‘2`Â[¥íÇô„�Æ•ºr•^Œµ%žoÇ@.‰s¦ÎèÛÄëqÂâÊšHžzÃ{“ÆÒŠËHà‹¢¹«ˆd¨“bÊï½ D·©·w›#ŠðF1jž¦¢Vݤ‰€\L@q£Ã`>"©@!ß_LÄ…ò³€â¹è,¸}5ó‚d�pW#+KX̦î츉÷ƒ[“Ø+"dìƒõxâvëè¶rÕbæZ¶^à¡ø:HçhžíU­µ«Ñ¡‚ÖŽÜ‘ëqZ–úÎI¹lá <D«[C£ˆ?ÑñîªAéÖ¼±éiS¥7ƒÕ S×ÙÂñžÏ3ÇÒ¬Ê�&"Øsp\T¿Î“‹¯È½Pý…¤ÒJ‰¥iðp 8¾Šh×RDM°T.w!S÷áÊÃ…ëiçÖIŸxæÁª© ‡»Oz/Uæ€k¶úqRreSÁ+Öh_—š`Ç©}ÌÓjåÕëÜmh‚HÃcõI7¡ÌáM\¾ ßhâÞM*k³¯ÆAÜâ�«Ê&ß5-5)£Üs}ÔÝ#û¼rm4¤öÉÕ”1`šŒ¤Ø ? N«]Þ!è¶ê*Rj„>G²\V?q–œä‹|‰uênâ“Æ’¹ÊãvO=Rß#ÉIRw ›ò1#mA{’ð–Ëô4cݧu䤒ƒV%Ö¨Ûe¶¼7VR> FÏI%@tÍ™ø{›g ªèsSùÔ¤xsô´Þž?]“ðªñÆM”FWžÇAêñËaMk–[û q®:Ý'ˆÞÆ&ç ÔúRXVBò¾J—£K‰ˆ-2‡ƒyG2¦©T€  zMÅ"À¦bo‘•;\Ý�ž9GN¡r±—SluFÞæìÒ)ej'h+IÄ{2UÉÙ\vô«h!*äÂñU&%¸–Dîò$¡{wÒ{¦7L–uùNûRíòñÔƒâÌÙèõUï,â_™€•?Ñï èyäùól—€×�>¡‘ð,ÂÇyuüôi½5ðà}õÜò±@_ö!'ÌäJêJøk¢p<²y4²À²‹{ï9]y)™g ·L0£>K{¯Ÿ¿;–·OÒ6|4z—)(Áž Z( ?u¾'¡ã‰Þ/‘…P@8ñì€ð]™¯‚ŸÛfºQízfˆ†GèÖC2ÙzÅ{BÌ€l¶XÔ)|e&ÒúÂÖ;Tiq±¾sbnŒ½>ïW©LOóÙ‚¾Ò—â¦z­S<¯51ž+pšŒÛÔ²�ßj`4Etë6yÚ/Én³)•_Å Š@^˜AÓó<ûsï¨|…½Uꉑgé7mÔEhà³7'Ó‚p]ðrO ‹ZÖžø¸N;ì”P*3"T¬¿~wh{òÈVóx$lyxeûm†/ 6¡3¼‘ºÓÕ#QÉR†¨Óó&e-:UQ`k…& ʳ{ãs( §Ç<·4#ŠvKQ“J¾<3i†k†„žB9Û5u6Ú·™Àéd@ܺ kÐ~ý˜ ØÖŽðBÀò‡ÕѼ‡¥´I3>18C .¡{æh0¢CºñTÏ©ì08œ¥0HϺZ°×…YëoTŠv[ ŠôTT"°s‚ï…žI¬‹×Yf¼ðzÇg'M¨ÖȲO›áteºÇ­ý±ÜyEYƲ= UôÝ¡«Ö[–*z¦;†Ð‰Ï“ú]F9á¥^RáSrh®Üy4®—íxáí8 ˜*H‹§Âz ²ž§‹òОŒ¿xhzžÝœ»Jà >%å@yìYÜ)ª�ÑB°^Y#ÔÉl¿yõ²æ s_Ie¹(¹æD{È#NP6²Oàæ@·ì&€‹²_¾ÌÒÝ&¥IƼñ·È;b›”e­‚�Çé`˜zè%¬RÖ¬Н»ÀMH£·¹úb"jI(W¬®(oŸlߣÔ> ” €½>‰–7/¢E ¡E)àɃAmã}óð)Ç‹ZÖ¸4‚¨Ÿ!h‹RqçƒG~¯tÕd]—8ÉÃͥ&g%TÞpCJ»Ô°ð nÜM69Ê oì1½Ì–¦æ[gè&ƒ>WqHD3¯ÚÉÄ,ÑÁ|[êœù"öéd䤿;ŠŠË;»JSŠÆ³z‰+ 7gÒ–Ê…sŽEI¢�Xs¼ð¯%N;F\¶õ=®z­µ•/T×Ýߨ“)8V¸±úZîà^ÀÖ@@®?±žN,>ˆ ‹ö¹~˜ìã)ÔSõ´yJØ®A÷ö]¸ÀÎ<uIVÅ.ÄC•áRÚ{Rn:4wš&™ó¬†‰Røf™å– ±42ülߟø`Ç>Ó};˜¸e J/©z9æ îtÔ|#b „<ÊN"åVº H÷Ø÷e± •ì£ö—xÚ¤›•…÷šTŸ p¼¶@SX2”­tÈ |'K‹i>¸³ïÒnº*÷ÑIN½wyV½zðnÏMØÍïi[ÛÔ 02•Á(éCË:ÛÓ åò²æ Vfâì.y´ÒÕíøSùö2ŽñnŠ|b|d!ckɧ{å=Qy% {>¾k3hRñ"+1ØáE é¾×‹iJÄ’˜[Þ2çYd=<¡M`}ÓÙçy¸Qøl:Ükö¦b•ÇÕÃ.0 OdÛÜ3²7!þž…¬çÇÌî±wB‚—€756Î T&Πwi~¥­>Å7ÇÐÈJèýæ…ö`J5.âf¨•=‹—”v•à!îCW"røÞY^qD&5Ó‚ÕÐøÅm8<¤Fã!›Š«öí!ôšôL‘w´�« %_ðI ïLX­½•ó`z¾ëšØ1ï®T:nà6¹ÒU6ùPgO­G‡„4¶³;™&ÓS ½%fggF¡zÃÜ̯f­Om½"‚7ćºÑF n,ù<Þ~Ñ[ÇPÂq/H»µ14ËiÛ›Åež/áÐöI•DÖãzÝà+˜Q=RÕ—ñÞ*x§-eæŽQ³@@´WÔ¿×éÚ’ÒÔ©Ä…Fô¾ññ©ÉòˆŸEw ÜÖ6X:†À—ê±³?ÍÛ5=�Ã\¬j1(é¶m½ ˆF«“Ú›±ÖJÝPï{èùЏFúâY–³.y2T£Il,9jšÈiÄɨ€•lνx·{e$lë JjМø¬.aQ»FçÉã,Ü$#âLU&Y »†•fÄ­ê¥×¡Øt¬×ámûklŽj¬mö5Ù~©­G;´RÆ8HL!Ö¢²ãù ¼°ú]òõ?ŽÓ»â ùò„¼^`º-QÀ&;§ ]yû¡ô‚èÊÊùm­,^IŒC8d‚vzB?81|Å=+ô6^–ÇA.þ ‹mÍSv±•{²TÕVO¤}ÇÎyÐkË­íöÝ,Lídyp<üĹG2Ò’ìÕ�LwE³9²Å†i™€«û´’9uƶe\9†ÚÃö~œwRäÂBå’xvm’ðb!†%¦ðà n¼µ˜6ÂR| ¡u4G0 g¢Nœ UÁñ˜6ÛPaZÑŸ¼4¯�hFƾ{¬Ø Þæƒ%¾à( VˆdÉrÀ’UãÂϳOdë>ßV{úTep5µ|+‡ÊqHÍ  ™€*žò<™ÛE®g¾ïkšå‹ÞäméHØÙʈ}‘ekž¼¬Ç´è.*è½:† úà<Î[؃´#s: ³óBØmϬ~PoÖ‡rÖh_Úš/÷65DNx<¶VóG.˜“¬0 “/,yËf*ÕÑöá+V¯õµ‰ÉÓÐbeèØÛbÂS”Èfr¶¨Va«yÆŽ†Ç¹™ùö`ƶ»8kê-X– “ N×Áâ»Aâ‹—rá¼é^䯖7P‡»¸òßÍ()½‰9,ó5( y6é†s©ÝÂV’ x–hÔi¼Œ•Ax,¹F€h¬Î:Ð#|häÕc(gŽÁW o×N âIØa Ei$Ï]$¬N-±e#’)á Ê…=´”º}­bQMÍ|n³óho[0•?‚ŸÂ<mÇÙ8º[´ ç*ÅcžÅ0¾ò WwG8PË#ŽuãØØ4ÖT( 㧤ÍÊ׸ûˆ²[^c8²Æ+e‚ع¹‡Yo›Ö'Áxèp¡ ž˜èAén­GjºßA"\ö>µº«kZ‚€¶›_:‰â‘RŽÉ¦;®=æs¸qx#{–˜¼V×—‡:'<X º«d«¡\±p7(¥Z36õ Z´Øž »ûr8RñVìà{ X´É’#‹/æGŽÖlñ¦I´”Ü)6º*®iú½©a •p§Ó€V³·DrŠVMt¨8zÎOÞ.¾ÕW �Ùò:ªUjߣñ¹ nàDÀ¼¸Ñ†û{ÌçaשþRƒcÜ/(¶/˜a;ù]À¸Î›&À½Íß (ÂG]§·ñ1´Tšß“ž:Ò«`‡õ©‡ˆ•¼æïá ‹xPÊÓ ’ Íl÷ñ�7×:É âÝÅä‰"Ö £š²Ž¶4éÕxs‚è¡Neæ®B¡è,‹oyfÖPj3iXO½Â–æ­ÇÃÎÙ… Âñ*®GÚ‹w ‡·„_¾%_bu+ô¬7}ñÒŸºÙÅ¡©nW3-¹Å²csiN‹ë!‚£çƒÒ jïo¼j(a±gÈ{öÞ:kõ>D_‘ÌØhcnIÑÁ yÕÂÉ Uï…[æëT{«Ñ¯Œ¨]á^¼æ{è"VVñ°™ÔJÇn úXx·"Z²ÇŠ)Ñ8ã-”£ÃÜ0ÄS|Æw'Hi'þøÍ "à§5<¾ç¤²<ëÊͤ×pÓT.¾»´/úíè©ÀSM+ây +;L¾ 8ïV+&¤*âˆùZö¤‚Ɖs‰dÓ¤¼ã*6?™I}±4oÈø-ɱkÍ¡¼'¢¯Èšâ†¼üÄzg80ü~o A"¸æšF"–*#”ÝR[.Ñߤ_Î=j‹Òq T¦1A.º¬Tò×Ý«e VÙp®h:}1v8=Ï€ŒçeùâÆå•Í6\È»fÑŽµëI‡>HÖÞð<Ý(qO20ÆO„<þDˆÞL_ObÒ‹õ—%°ôJN`ëI»QË<q…t’ÜÞÕ§œIšlü"Þk./Ê€IT q‚ò0'l^+€{ýè å¦ ÆåÊ  š [ÉóI vŽ­”G]œÄÁ=¸í;¥Èj~"E®~Í2ã¸l[ø²îe¶‘ÌÉà4æDXï5“– ÷ndà � =rµ[ç¼;²š%ï÷@[_³1‘ #¸›µQ¹ÕÖ[M$«kÐ|úŒ!"aDxÒÏÆÞ£dï:Â_ƒ3q«½Å”–ÔÕ ËP{"¶‡fê‘(p¸ËvN[?&;zm†Gœäâ–Ìé¯eh,:óÙª¶ßé_ñ5Ñ‚ØEµ˜«Ë­–éîdFÎÍ/SüØÔç1&¸FRÚ¨¿™ »B"y§$Û4bNΕš”1íºG~B Ì·N€a˜ý%Ú“¦W'òâzU¥ã^ã3v¦ò åq‘Å §Mâ³Q]Œ}VzõhCú2= Bµ”õŒbέخLا¨Ùôò´4ûJû'»Ôò­€½<Xð\bªƒ–®ÇˆˆçÁuõšO§ÚvHÞsM$à!G6oJ=*Pš ÍÅWŽã¾NðxhP¹áÆŠ«×ÓN£ËZU‚Dz8ú´ÅºÐí:±<„ž{¡Ü”O‚x{µàEÉ/¶Í¡Ç%YW˜CèùAe*yQ°£=f*±q1LmhÉ”z9I‰{Íx¤a 0ð®KDvGP_ëx¼Íj…'XÀDZä"7’ò "vÞIJ»)»IòæãÇ`.Z2MA•¸†7À-„Žb/'`ƒx¬T6EÓåa>çÕ” ¯6àœx«âéŭܧ†bÙ F(Q±/c3&¸õŠVjBi®3‡û@kM–îQ">·òW­Š^º“¦0/Ç ·©øåãm\0¨^Øm›ÖÖÃØ—Zi—YöfБ½7œÛ2W':3€ÐýDݰ½oÜÌ/Ó&‡ø©s,Bã(l1 #œœ,›‚ºXÜN‹k|B„Þ÷! Õî„ ¸)cãŠH(L¢YgSÞLnä¸2xiIx¬"#W?Èâ|–ä1îtÈ{W)ajÜ>†zËŒ+ªˆPú…°·ûü´ÚWÀ\VÌÜw"±¥äñ:Á¼Edïx;†HKe%=ú,kÊ‹b†G=`a70‚.^‘pºŸ¼'ØÂºÊL<Ñ4ÆÂ|®‚VòÍ;¼B–âERë0")xÁÜ^FCÃæñŒ.™¯ÂÇ<I›šL9k7ÛZ4—)IÞJ™A“�ŸÌ.˜$6·KCSôñÚnE¹Ø;íâ[eu�Îí•#XÜnz/'‚¢êtw¨<œ«ã\�/)Öj�Ý?1’‚Åi‹Dû”ÓõÁ³*âÁÃÞwÄœñ¼Ï‰íØÉ¢÷ˆm®¥ú.+¢žžGæ3’}4à~—@;¯BIØ +<\Fä¢ÓŒÅÞ €²Á¦ ²°†B\\‚ÖáÝ8¿éÇÙ9û¬&u©¤î¹iâ{ô¶˜Mç.NÚ&Ë#Wì–Äç@ -8vOY7$°j…rFËf^)„î+º]Õ·íõÆŒß›Ì VêA‘œ=5äKŠtQ:W$A*¨�ªSNâîýã]¤&gW‰*Ù³Ì&N|lW™Æk#»RCOVi€›¤-¼:ñéQ£Œ>‚’v‘ˆit–ç“lî[ƒ¥$â¨ôæÝLY¨Jï0xä!uÜÃÓa¦ttP>´ÜŽÀKŸÖ¼Ê©%$?rÕ{ïTÕð‰ÔC0á¥qœ^“^?ô(!^-ŠLÁu²æ7sm¸Š†=ðn±¦®ÐLJÚ„wxÓŽäZ˜vÑ'ç‰"ú¦"'j£Hñs³Ä©—6‹"¹8®Y½M,p¼o·ÃÉÏCøÑžÒ<E$¯Ì“‰Cà.ÉËMІŠò6/f´Ði ™Í*ó$*=¼Xõ¥Ai+Û×7 —£ï`¼S-Ídš…5/ ôÞN½‡SüœiTè™+>ÓÁšP ˜ˆ®”õçu)ŒæûœÅŸ:’Ò1š}oöåòÕ,z–Vó! RÖ³FóD÷Rdµ}Ô¥ZˆÕL†\K`Ã_sPNÕµpER9‘?"ML¨‡‰BâG¤”‹~ªÚ&F#Ò|ƒŽýbµûf•6IrNÜ¥¯!iœóÕ[žyÌ¡S汪„½glá™XÕÃb¼ UÉÀcÊõÎ)sZµ½8¡'ä±6>qÃæCdt H™9ÀÇšÐÉÔ𫇓RLß$ã“DJ?ŽÝG;z™-¦MWиOT ÇÑ®Ÿ§¼“bг·üx–L[TºÓÍĞ餔5oÙ‚ Ú[zî` o�ñ®ŽÈ\È|,¦ŸêiJ­VÁrÆÛÞ­Üú¿ù÷ÿßÿüóï÷?��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/shake.go�����������������������������������������������0000644�0610621�0607500�00000003467�13172163317�023344� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sha3 // This file defines the ShakeHash interface, and provides // functions for creating SHAKE instances, as well as utility // functions for hashing bytes to arbitrary-length output. import ( "io" ) // ShakeHash defines the interface to hash functions that // support arbitrary-length output. type ShakeHash interface { // Write absorbs more data into the hash's state. It panics if input is // written to it after output has been read from it. io.Writer // Read reads more output from the hash; reading affects the hash's // state. (ShakeHash.Read is thus very different from Hash.Sum) // It never returns an error. io.Reader // Clone returns a copy of the ShakeHash in its current state. Clone() ShakeHash // Reset resets the ShakeHash to its initial state. Reset() } func (d *state) Clone() ShakeHash { return d.clone() } // NewShake128 creates a new SHAKE128 variable-output-length ShakeHash. // Its generic security strength is 128 bits against all attacks if at // least 32 bytes of its output are used. func NewShake128() ShakeHash { return &state{rate: 168, dsbyte: 0x1f} } // NewShake256 creates a new SHAKE128 variable-output-length ShakeHash. // Its generic security strength is 256 bits against all attacks if // at least 64 bytes of its output are used. func NewShake256() ShakeHash { return &state{rate: 136, dsbyte: 0x1f} } // ShakeSum128 writes an arbitrary-length digest of data into hash. func ShakeSum128(hash, data []byte) { h := NewShake128() h.Write(data) h.Read(hash) } // ShakeSum256 writes an arbitrary-length digest of data into hash. func ShakeSum256(hash, data []byte) { h := NewShake256() h.Write(data) h.Read(hash) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/sha3_test.go�������������������������������������������0000644�0610621�0607500�00000021707�13172163317�024143� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sha3 // Tests include all the ShortMsgKATs provided by the Keccak team at // https://github.com/gvanas/KeccakCodePackage // // They only include the zero-bit case of the bitwise testvectors // published by NIST in the draft of FIPS-202. import ( "bytes" "compress/flate" "encoding/hex" "encoding/json" "fmt" "hash" "os" "strings" "testing" ) const ( testString = "brekeccakkeccak koax koax" katFilename = "testdata/keccakKats.json.deflate" ) // Internal-use instances of SHAKE used to test against KATs. func newHashShake128() hash.Hash { return &state{rate: 168, dsbyte: 0x1f, outputLen: 512} } func newHashShake256() hash.Hash { return &state{rate: 136, dsbyte: 0x1f, outputLen: 512} } // testDigests contains functions returning hash.Hash instances // with output-length equal to the KAT length for both SHA-3 and // SHAKE instances. var testDigests = map[string]func() hash.Hash{ "SHA3-224": New224, "SHA3-256": New256, "SHA3-384": New384, "SHA3-512": New512, "SHAKE128": newHashShake128, "SHAKE256": newHashShake256, } // testShakes contains functions that return ShakeHash instances for // testing the ShakeHash-specific interface. var testShakes = map[string]func() ShakeHash{ "SHAKE128": NewShake128, "SHAKE256": NewShake256, } // decodeHex converts a hex-encoded string into a raw byte string. func decodeHex(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } // structs used to marshal JSON test-cases. type KeccakKats struct { Kats map[string][]struct { Digest string `json:"digest"` Length int64 `json:"length"` Message string `json:"message"` } } func testUnalignedAndGeneric(t *testing.T, testf func(impl string)) { xorInOrig, copyOutOrig := xorIn, copyOut xorIn, copyOut = xorInGeneric, copyOutGeneric testf("generic") if xorImplementationUnaligned != "generic" { xorIn, copyOut = xorInUnaligned, copyOutUnaligned testf("unaligned") } xorIn, copyOut = xorInOrig, copyOutOrig } // TestKeccakKats tests the SHA-3 and Shake implementations against all the // ShortMsgKATs from https://github.com/gvanas/KeccakCodePackage // (The testvectors are stored in keccakKats.json.deflate due to their length.) func TestKeccakKats(t *testing.T) { testUnalignedAndGeneric(t, func(impl string) { // Read the KATs. deflated, err := os.Open(katFilename) if err != nil { t.Errorf("error opening %s: %s", katFilename, err) } file := flate.NewReader(deflated) dec := json.NewDecoder(file) var katSet KeccakKats err = dec.Decode(&katSet) if err != nil { t.Errorf("error decoding KATs: %s", err) } // Do the KATs. for functionName, kats := range katSet.Kats { d := testDigests[functionName]() for _, kat := range kats { d.Reset() in, err := hex.DecodeString(kat.Message) if err != nil { t.Errorf("error decoding KAT: %s", err) } d.Write(in[:kat.Length/8]) got := strings.ToUpper(hex.EncodeToString(d.Sum(nil))) if got != kat.Digest { t.Errorf("function=%s, implementation=%s, length=%d\nmessage:\n %s\ngot:\n %s\nwanted:\n %s", functionName, impl, kat.Length, kat.Message, got, kat.Digest) t.Logf("wanted %+v", kat) t.FailNow() } continue } } }) } // TestUnalignedWrite tests that writing data in an arbitrary pattern with // small input buffers. func testUnalignedWrite(t *testing.T) { testUnalignedAndGeneric(t, func(impl string) { buf := sequentialBytes(0x10000) for alg, df := range testDigests { d := df() d.Reset() d.Write(buf) want := d.Sum(nil) d.Reset() for i := 0; i < len(buf); { // Cycle through offsets which make a 137 byte sequence. // Because 137 is prime this sequence should exercise all corner cases. offsets := [17]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1} for _, j := range offsets { if v := len(buf) - i; v < j { j = v } d.Write(buf[i : i+j]) i += j } } got := d.Sum(nil) if !bytes.Equal(got, want) { t.Errorf("Unaligned writes, implementation=%s, alg=%s\ngot %q, want %q", impl, alg, got, want) } } }) } // TestAppend checks that appending works when reallocation is necessary. func TestAppend(t *testing.T) { testUnalignedAndGeneric(t, func(impl string) { d := New224() for capacity := 2; capacity <= 66; capacity += 64 { // The first time around the loop, Sum will have to reallocate. // The second time, it will not. buf := make([]byte, 2, capacity) d.Reset() d.Write([]byte{0xcc}) buf = d.Sum(buf) expected := "0000DF70ADC49B2E76EEE3A6931B93FA41841C3AF2CDF5B32A18B5478C39" if got := strings.ToUpper(hex.EncodeToString(buf)); got != expected { t.Errorf("got %s, want %s", got, expected) } } }) } // TestAppendNoRealloc tests that appending works when no reallocation is necessary. func TestAppendNoRealloc(t *testing.T) { testUnalignedAndGeneric(t, func(impl string) { buf := make([]byte, 1, 200) d := New224() d.Write([]byte{0xcc}) buf = d.Sum(buf) expected := "00DF70ADC49B2E76EEE3A6931B93FA41841C3AF2CDF5B32A18B5478C39" if got := strings.ToUpper(hex.EncodeToString(buf)); got != expected { t.Errorf("%s: got %s, want %s", impl, got, expected) } }) } // TestSqueezing checks that squeezing the full output a single time produces // the same output as repeatedly squeezing the instance. func TestSqueezing(t *testing.T) { testUnalignedAndGeneric(t, func(impl string) { for functionName, newShakeHash := range testShakes { d0 := newShakeHash() d0.Write([]byte(testString)) ref := make([]byte, 32) d0.Read(ref) d1 := newShakeHash() d1.Write([]byte(testString)) var multiple []byte for _ = range ref { one := make([]byte, 1) d1.Read(one) multiple = append(multiple, one...) } if !bytes.Equal(ref, multiple) { t.Errorf("%s (%s): squeezing %d bytes one at a time failed", functionName, impl, len(ref)) } } }) } // sequentialBytes produces a buffer of size consecutive bytes 0x00, 0x01, ..., used for testing. func sequentialBytes(size int) []byte { result := make([]byte, size) for i := range result { result[i] = byte(i) } return result } // BenchmarkPermutationFunction measures the speed of the permutation function // with no input data. func BenchmarkPermutationFunction(b *testing.B) { b.SetBytes(int64(200)) var lanes [25]uint64 for i := 0; i < b.N; i++ { keccakF1600(&lanes) } } // benchmarkHash tests the speed to hash num buffers of buflen each. func benchmarkHash(b *testing.B, h hash.Hash, size, num int) { b.StopTimer() h.Reset() data := sequentialBytes(size) b.SetBytes(int64(size * num)) b.StartTimer() var state []byte for i := 0; i < b.N; i++ { for j := 0; j < num; j++ { h.Write(data) } state = h.Sum(state[:0]) } b.StopTimer() h.Reset() } // benchmarkShake is specialized to the Shake instances, which don't // require a copy on reading output. func benchmarkShake(b *testing.B, h ShakeHash, size, num int) { b.StopTimer() h.Reset() data := sequentialBytes(size) d := make([]byte, 32) b.SetBytes(int64(size * num)) b.StartTimer() for i := 0; i < b.N; i++ { h.Reset() for j := 0; j < num; j++ { h.Write(data) } h.Read(d) } } func BenchmarkSha3_512_MTU(b *testing.B) { benchmarkHash(b, New512(), 1350, 1) } func BenchmarkSha3_384_MTU(b *testing.B) { benchmarkHash(b, New384(), 1350, 1) } func BenchmarkSha3_256_MTU(b *testing.B) { benchmarkHash(b, New256(), 1350, 1) } func BenchmarkSha3_224_MTU(b *testing.B) { benchmarkHash(b, New224(), 1350, 1) } func BenchmarkShake128_MTU(b *testing.B) { benchmarkShake(b, NewShake128(), 1350, 1) } func BenchmarkShake256_MTU(b *testing.B) { benchmarkShake(b, NewShake256(), 1350, 1) } func BenchmarkShake256_16x(b *testing.B) { benchmarkShake(b, NewShake256(), 16, 1024) } func BenchmarkShake256_1MiB(b *testing.B) { benchmarkShake(b, NewShake256(), 1024, 1024) } func BenchmarkSha3_512_1MiB(b *testing.B) { benchmarkHash(b, New512(), 1024, 1024) } func Example_sum() { buf := []byte("some data to hash") // A hash needs to be 64 bytes long to have 256-bit collision resistance. h := make([]byte, 64) // Compute a 64-byte hash of buf and put it in h. ShakeSum256(h, buf) fmt.Printf("%x\n", h) // Output: 0f65fe41fc353e52c55667bb9e2b27bfcc8476f2c413e9437d272ee3194a4e3146d05ec04a25d16b8f577c19b82d16b1424c3e022e783d2b4da98de3658d363d } func Example_mac() { k := []byte("this is a secret key; you should generate a strong random key that's at least 32 bytes long") buf := []byte("and this is some data to authenticate") // A MAC with 32 bytes of output has 256-bit security strength -- if you use at least a 32-byte-long key. h := make([]byte, 32) d := NewShake256() // Write the key into the hash. d.Write(k) // Now write the data. d.Write(buf) // Read 32 bytes of output from the hash into h. d.Read(h) fmt.Printf("%x\n", h) // Output: 78de2974bd2711d5549ffd32b753ef0f5fa80a0db2556db60f0987eb8a9218ff } ���������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/sha3.go������������������������������������������������0000644�0610621�0607500�00000013153�13172163317�023100� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sha3 // spongeDirection indicates the direction bytes are flowing through the sponge. type spongeDirection int const ( // spongeAbsorbing indicates that the sponge is absorbing input. spongeAbsorbing spongeDirection = iota // spongeSqueezing indicates that the sponge is being squeezed. spongeSqueezing ) const ( // maxRate is the maximum size of the internal buffer. SHAKE-256 // currently needs the largest buffer. maxRate = 168 ) type state struct { // Generic sponge components. a [25]uint64 // main state of the hash buf []byte // points into storage rate int // the number of bytes of state to use // dsbyte contains the "domain separation" bits and the first bit of // the padding. Sections 6.1 and 6.2 of [1] separate the outputs of the // SHA-3 and SHAKE functions by appending bitstrings to the message. // Using a little-endian bit-ordering convention, these are "01" for SHA-3 // and "1111" for SHAKE, or 00000010b and 00001111b, respectively. Then the // padding rule from section 5.1 is applied to pad the message to a multiple // of the rate, which involves adding a "1" bit, zero or more "0" bits, and // a final "1" bit. We merge the first "1" bit from the padding into dsbyte, // giving 00000110b (0x06) and 00011111b (0x1f). // [1] http://csrc.nist.gov/publications/drafts/fips-202/fips_202_draft.pdf // "Draft FIPS 202: SHA-3 Standard: Permutation-Based Hash and // Extendable-Output Functions (May 2014)" dsbyte byte storage [maxRate]byte // Specific to SHA-3 and SHAKE. outputLen int // the default output size in bytes state spongeDirection // whether the sponge is absorbing or squeezing } // BlockSize returns the rate of sponge underlying this hash function. func (d *state) BlockSize() int { return d.rate } // Size returns the output size of the hash function in bytes. func (d *state) Size() int { return d.outputLen } // Reset clears the internal state by zeroing the sponge state and // the byte buffer, and setting Sponge.state to absorbing. func (d *state) Reset() { // Zero the permutation's state. for i := range d.a { d.a[i] = 0 } d.state = spongeAbsorbing d.buf = d.storage[:0] } func (d *state) clone() *state { ret := *d if ret.state == spongeAbsorbing { ret.buf = ret.storage[:len(ret.buf)] } else { ret.buf = ret.storage[d.rate-cap(d.buf) : d.rate] } return &ret } // permute applies the KeccakF-1600 permutation. It handles // any input-output buffering. func (d *state) permute() { switch d.state { case spongeAbsorbing: // If we're absorbing, we need to xor the input into the state // before applying the permutation. xorIn(d, d.buf) d.buf = d.storage[:0] keccakF1600(&d.a) case spongeSqueezing: // If we're squeezing, we need to apply the permutatin before // copying more output. keccakF1600(&d.a) d.buf = d.storage[:d.rate] copyOut(d, d.buf) } } // pads appends the domain separation bits in dsbyte, applies // the multi-bitrate 10..1 padding rule, and permutes the state. func (d *state) padAndPermute(dsbyte byte) { if d.buf == nil { d.buf = d.storage[:0] } // Pad with this instance's domain-separator bits. We know that there's // at least one byte of space in d.buf because, if it were full, // permute would have been called to empty it. dsbyte also contains the // first one bit for the padding. See the comment in the state struct. d.buf = append(d.buf, dsbyte) zerosStart := len(d.buf) d.buf = d.storage[:d.rate] for i := zerosStart; i < d.rate; i++ { d.buf[i] = 0 } // This adds the final one bit for the padding. Because of the way that // bits are numbered from the LSB upwards, the final bit is the MSB of // the last byte. d.buf[d.rate-1] ^= 0x80 // Apply the permutation d.permute() d.state = spongeSqueezing d.buf = d.storage[:d.rate] copyOut(d, d.buf) } // Write absorbs more data into the hash's state. It produces an error // if more data is written to the ShakeHash after writing func (d *state) Write(p []byte) (written int, err error) { if d.state != spongeAbsorbing { panic("sha3: write to sponge after read") } if d.buf == nil { d.buf = d.storage[:0] } written = len(p) for len(p) > 0 { if len(d.buf) == 0 && len(p) >= d.rate { // The fast path; absorb a full "rate" bytes of input and apply the permutation. xorIn(d, p[:d.rate]) p = p[d.rate:] keccakF1600(&d.a) } else { // The slow path; buffer the input until we can fill the sponge, and then xor it in. todo := d.rate - len(d.buf) if todo > len(p) { todo = len(p) } d.buf = append(d.buf, p[:todo]...) p = p[todo:] // If the sponge is full, apply the permutation. if len(d.buf) == d.rate { d.permute() } } } return } // Read squeezes an arbitrary number of bytes from the sponge. func (d *state) Read(out []byte) (n int, err error) { // If we're still absorbing, pad and apply the permutation. if d.state == spongeAbsorbing { d.padAndPermute(d.dsbyte) } n = len(out) // Now, do the squeezing. for len(out) > 0 { n := copy(out, d.buf) d.buf = d.buf[n:] out = out[n:] // Apply the permutation if we've squeezed the sponge dry. if len(d.buf) == 0 { d.permute() } } return } // Sum applies padding to the hash state and then squeezes out the desired // number of output bytes. func (d *state) Sum(in []byte) []byte { // Make a copy of the original hash so that caller can keep writing // and summing. dup := d.clone() hash := make([]byte, dup.outputLen) dup.Read(hash) return append(in, hash...) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/register.go��������������������������������������������0000644�0610621�0607500�00000000635�13172163317�024067� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.4 package sha3 import ( "crypto" ) func init() { crypto.RegisterHash(crypto.SHA3_224, New224) crypto.RegisterHash(crypto.SHA3_256, New256) crypto.RegisterHash(crypto.SHA3_384, New384) crypto.RegisterHash(crypto.SHA3_512, New512) } ���������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/keccakf_amd64.s����������������������������������������0000644�0610621�0607500�00000034256�13172163317�024470� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!appengine,!gccgo // This code was translated into a form compatible with 6a from the public // domain sources at https://github.com/gvanas/KeccakCodePackage // Offsets in state #define _ba (0*8) #define _be (1*8) #define _bi (2*8) #define _bo (3*8) #define _bu (4*8) #define _ga (5*8) #define _ge (6*8) #define _gi (7*8) #define _go (8*8) #define _gu (9*8) #define _ka (10*8) #define _ke (11*8) #define _ki (12*8) #define _ko (13*8) #define _ku (14*8) #define _ma (15*8) #define _me (16*8) #define _mi (17*8) #define _mo (18*8) #define _mu (19*8) #define _sa (20*8) #define _se (21*8) #define _si (22*8) #define _so (23*8) #define _su (24*8) // Temporary registers #define rT1 AX // Round vars #define rpState DI #define rpStack SP #define rDa BX #define rDe CX #define rDi DX #define rDo R8 #define rDu R9 #define rBa R10 #define rBe R11 #define rBi R12 #define rBo R13 #define rBu R14 #define rCa SI #define rCe BP #define rCi rBi #define rCo rBo #define rCu R15 #define MOVQ_RBI_RCE MOVQ rBi, rCe #define XORQ_RT1_RCA XORQ rT1, rCa #define XORQ_RT1_RCE XORQ rT1, rCe #define XORQ_RBA_RCU XORQ rBa, rCu #define XORQ_RBE_RCU XORQ rBe, rCu #define XORQ_RDU_RCU XORQ rDu, rCu #define XORQ_RDA_RCA XORQ rDa, rCa #define XORQ_RDE_RCE XORQ rDe, rCe #define mKeccakRound(iState, oState, rc, B_RBI_RCE, G_RT1_RCA, G_RT1_RCE, G_RBA_RCU, K_RT1_RCA, K_RT1_RCE, K_RBA_RCU, M_RT1_RCA, M_RT1_RCE, M_RBE_RCU, S_RDU_RCU, S_RDA_RCA, S_RDE_RCE) \ /* Prepare round */ \ MOVQ rCe, rDa; \ ROLQ $1, rDa; \ \ MOVQ _bi(iState), rCi; \ XORQ _gi(iState), rDi; \ XORQ rCu, rDa; \ XORQ _ki(iState), rCi; \ XORQ _mi(iState), rDi; \ XORQ rDi, rCi; \ \ MOVQ rCi, rDe; \ ROLQ $1, rDe; \ \ MOVQ _bo(iState), rCo; \ XORQ _go(iState), rDo; \ XORQ rCa, rDe; \ XORQ _ko(iState), rCo; \ XORQ _mo(iState), rDo; \ XORQ rDo, rCo; \ \ MOVQ rCo, rDi; \ ROLQ $1, rDi; \ \ MOVQ rCu, rDo; \ XORQ rCe, rDi; \ ROLQ $1, rDo; \ \ MOVQ rCa, rDu; \ XORQ rCi, rDo; \ ROLQ $1, rDu; \ \ /* Result b */ \ MOVQ _ba(iState), rBa; \ MOVQ _ge(iState), rBe; \ XORQ rCo, rDu; \ MOVQ _ki(iState), rBi; \ MOVQ _mo(iState), rBo; \ MOVQ _su(iState), rBu; \ XORQ rDe, rBe; \ ROLQ $44, rBe; \ XORQ rDi, rBi; \ XORQ rDa, rBa; \ ROLQ $43, rBi; \ \ MOVQ rBe, rCa; \ MOVQ rc, rT1; \ ORQ rBi, rCa; \ XORQ rBa, rT1; \ XORQ rT1, rCa; \ MOVQ rCa, _ba(oState); \ \ XORQ rDu, rBu; \ ROLQ $14, rBu; \ MOVQ rBa, rCu; \ ANDQ rBe, rCu; \ XORQ rBu, rCu; \ MOVQ rCu, _bu(oState); \ \ XORQ rDo, rBo; \ ROLQ $21, rBo; \ MOVQ rBo, rT1; \ ANDQ rBu, rT1; \ XORQ rBi, rT1; \ MOVQ rT1, _bi(oState); \ \ NOTQ rBi; \ ORQ rBa, rBu; \ ORQ rBo, rBi; \ XORQ rBo, rBu; \ XORQ rBe, rBi; \ MOVQ rBu, _bo(oState); \ MOVQ rBi, _be(oState); \ B_RBI_RCE; \ \ /* Result g */ \ MOVQ _gu(iState), rBe; \ XORQ rDu, rBe; \ MOVQ _ka(iState), rBi; \ ROLQ $20, rBe; \ XORQ rDa, rBi; \ ROLQ $3, rBi; \ MOVQ _bo(iState), rBa; \ MOVQ rBe, rT1; \ ORQ rBi, rT1; \ XORQ rDo, rBa; \ MOVQ _me(iState), rBo; \ MOVQ _si(iState), rBu; \ ROLQ $28, rBa; \ XORQ rBa, rT1; \ MOVQ rT1, _ga(oState); \ G_RT1_RCA; \ \ XORQ rDe, rBo; \ ROLQ $45, rBo; \ MOVQ rBi, rT1; \ ANDQ rBo, rT1; \ XORQ rBe, rT1; \ MOVQ rT1, _ge(oState); \ G_RT1_RCE; \ \ XORQ rDi, rBu; \ ROLQ $61, rBu; \ MOVQ rBu, rT1; \ ORQ rBa, rT1; \ XORQ rBo, rT1; \ MOVQ rT1, _go(oState); \ \ ANDQ rBe, rBa; \ XORQ rBu, rBa; \ MOVQ rBa, _gu(oState); \ NOTQ rBu; \ G_RBA_RCU; \ \ ORQ rBu, rBo; \ XORQ rBi, rBo; \ MOVQ rBo, _gi(oState); \ \ /* Result k */ \ MOVQ _be(iState), rBa; \ MOVQ _gi(iState), rBe; \ MOVQ _ko(iState), rBi; \ MOVQ _mu(iState), rBo; \ MOVQ _sa(iState), rBu; \ XORQ rDi, rBe; \ ROLQ $6, rBe; \ XORQ rDo, rBi; \ ROLQ $25, rBi; \ MOVQ rBe, rT1; \ ORQ rBi, rT1; \ XORQ rDe, rBa; \ ROLQ $1, rBa; \ XORQ rBa, rT1; \ MOVQ rT1, _ka(oState); \ K_RT1_RCA; \ \ XORQ rDu, rBo; \ ROLQ $8, rBo; \ MOVQ rBi, rT1; \ ANDQ rBo, rT1; \ XORQ rBe, rT1; \ MOVQ rT1, _ke(oState); \ K_RT1_RCE; \ \ XORQ rDa, rBu; \ ROLQ $18, rBu; \ NOTQ rBo; \ MOVQ rBo, rT1; \ ANDQ rBu, rT1; \ XORQ rBi, rT1; \ MOVQ rT1, _ki(oState); \ \ MOVQ rBu, rT1; \ ORQ rBa, rT1; \ XORQ rBo, rT1; \ MOVQ rT1, _ko(oState); \ \ ANDQ rBe, rBa; \ XORQ rBu, rBa; \ MOVQ rBa, _ku(oState); \ K_RBA_RCU; \ \ /* Result m */ \ MOVQ _ga(iState), rBe; \ XORQ rDa, rBe; \ MOVQ _ke(iState), rBi; \ ROLQ $36, rBe; \ XORQ rDe, rBi; \ MOVQ _bu(iState), rBa; \ ROLQ $10, rBi; \ MOVQ rBe, rT1; \ MOVQ _mi(iState), rBo; \ ANDQ rBi, rT1; \ XORQ rDu, rBa; \ MOVQ _so(iState), rBu; \ ROLQ $27, rBa; \ XORQ rBa, rT1; \ MOVQ rT1, _ma(oState); \ M_RT1_RCA; \ \ XORQ rDi, rBo; \ ROLQ $15, rBo; \ MOVQ rBi, rT1; \ ORQ rBo, rT1; \ XORQ rBe, rT1; \ MOVQ rT1, _me(oState); \ M_RT1_RCE; \ \ XORQ rDo, rBu; \ ROLQ $56, rBu; \ NOTQ rBo; \ MOVQ rBo, rT1; \ ORQ rBu, rT1; \ XORQ rBi, rT1; \ MOVQ rT1, _mi(oState); \ \ ORQ rBa, rBe; \ XORQ rBu, rBe; \ MOVQ rBe, _mu(oState); \ \ ANDQ rBa, rBu; \ XORQ rBo, rBu; \ MOVQ rBu, _mo(oState); \ M_RBE_RCU; \ \ /* Result s */ \ MOVQ _bi(iState), rBa; \ MOVQ _go(iState), rBe; \ MOVQ _ku(iState), rBi; \ XORQ rDi, rBa; \ MOVQ _ma(iState), rBo; \ ROLQ $62, rBa; \ XORQ rDo, rBe; \ MOVQ _se(iState), rBu; \ ROLQ $55, rBe; \ \ XORQ rDu, rBi; \ MOVQ rBa, rDu; \ XORQ rDe, rBu; \ ROLQ $2, rBu; \ ANDQ rBe, rDu; \ XORQ rBu, rDu; \ MOVQ rDu, _su(oState); \ \ ROLQ $39, rBi; \ S_RDU_RCU; \ NOTQ rBe; \ XORQ rDa, rBo; \ MOVQ rBe, rDa; \ ANDQ rBi, rDa; \ XORQ rBa, rDa; \ MOVQ rDa, _sa(oState); \ S_RDA_RCA; \ \ ROLQ $41, rBo; \ MOVQ rBi, rDe; \ ORQ rBo, rDe; \ XORQ rBe, rDe; \ MOVQ rDe, _se(oState); \ S_RDE_RCE; \ \ MOVQ rBo, rDi; \ MOVQ rBu, rDo; \ ANDQ rBu, rDi; \ ORQ rBa, rDo; \ XORQ rBi, rDi; \ XORQ rBo, rDo; \ MOVQ rDi, _si(oState); \ MOVQ rDo, _so(oState) \ // func keccakF1600(state *[25]uint64) TEXT ·keccakF1600(SB), 0, $200-8 MOVQ state+0(FP), rpState // Convert the user state into an internal state NOTQ _be(rpState) NOTQ _bi(rpState) NOTQ _go(rpState) NOTQ _ki(rpState) NOTQ _mi(rpState) NOTQ _sa(rpState) // Execute the KeccakF permutation MOVQ _ba(rpState), rCa MOVQ _be(rpState), rCe MOVQ _bu(rpState), rCu XORQ _ga(rpState), rCa XORQ _ge(rpState), rCe XORQ _gu(rpState), rCu XORQ _ka(rpState), rCa XORQ _ke(rpState), rCe XORQ _ku(rpState), rCu XORQ _ma(rpState), rCa XORQ _me(rpState), rCe XORQ _mu(rpState), rCu XORQ _sa(rpState), rCa XORQ _se(rpState), rCe MOVQ _si(rpState), rDi MOVQ _so(rpState), rDo XORQ _su(rpState), rCu mKeccakRound(rpState, rpStack, $0x0000000000000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x0000000000008082, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x800000000000808a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x8000000080008000, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x000000000000808b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x0000000080000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x8000000080008081, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x8000000000008009, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x000000000000008a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x0000000000000088, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x0000000080008009, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x000000008000000a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x000000008000808b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x800000000000008b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x8000000000008089, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x8000000000008003, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x8000000000008002, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x8000000000000080, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x000000000000800a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x800000008000000a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x8000000080008081, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x8000000000008080, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpState, rpStack, $0x0000000080000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) mKeccakRound(rpStack, rpState, $0x8000000080008008, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP) // Revert the internal state to the user state NOTQ _be(rpState) NOTQ _bi(rpState) NOTQ _go(rpState) NOTQ _ki(rpState) NOTQ _mi(rpState) NOTQ _sa(rpState) RET ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/keccakf_amd64.go���������������������������������������0000644�0610621�0607500�00000000465�13172163317�024626� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!appengine,!gccgo package sha3 // This function is implemented in keccakf_amd64.s. //go:noescape func keccakF1600(a *[25]uint64) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/keccakf.go���������������������������������������������0000644�0610621�0607500�00000023343�13172163317�023633� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !amd64 appengine gccgo package sha3 // rc stores the round constants for use in the ι step. var rc = [24]uint64{ 0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A, 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, } // keccakF1600 applies the Keccak permutation to a 1600b-wide // state represented as a slice of 25 uint64s. func keccakF1600(a *[25]uint64) { // Implementation translated from Keccak-inplace.c // in the keccak reference code. var t, bc0, bc1, bc2, bc3, bc4, d0, d1, d2, d3, d4 uint64 for i := 0; i < 24; i += 4 { // Combines the 5 steps in each round into 2 steps. // Unrolls 4 rounds per loop and spreads some steps across rounds. // Round 1 bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] d0 = bc4 ^ (bc1<<1 | bc1>>63) d1 = bc0 ^ (bc2<<1 | bc2>>63) d2 = bc1 ^ (bc3<<1 | bc3>>63) d3 = bc2 ^ (bc4<<1 | bc4>>63) d4 = bc3 ^ (bc0<<1 | bc0>>63) bc0 = a[0] ^ d0 t = a[6] ^ d1 bc1 = t<<44 | t>>(64-44) t = a[12] ^ d2 bc2 = t<<43 | t>>(64-43) t = a[18] ^ d3 bc3 = t<<21 | t>>(64-21) t = a[24] ^ d4 bc4 = t<<14 | t>>(64-14) a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i] a[6] = bc1 ^ (bc3 &^ bc2) a[12] = bc2 ^ (bc4 &^ bc3) a[18] = bc3 ^ (bc0 &^ bc4) a[24] = bc4 ^ (bc1 &^ bc0) t = a[10] ^ d0 bc2 = t<<3 | t>>(64-3) t = a[16] ^ d1 bc3 = t<<45 | t>>(64-45) t = a[22] ^ d2 bc4 = t<<61 | t>>(64-61) t = a[3] ^ d3 bc0 = t<<28 | t>>(64-28) t = a[9] ^ d4 bc1 = t<<20 | t>>(64-20) a[10] = bc0 ^ (bc2 &^ bc1) a[16] = bc1 ^ (bc3 &^ bc2) a[22] = bc2 ^ (bc4 &^ bc3) a[3] = bc3 ^ (bc0 &^ bc4) a[9] = bc4 ^ (bc1 &^ bc0) t = a[20] ^ d0 bc4 = t<<18 | t>>(64-18) t = a[1] ^ d1 bc0 = t<<1 | t>>(64-1) t = a[7] ^ d2 bc1 = t<<6 | t>>(64-6) t = a[13] ^ d3 bc2 = t<<25 | t>>(64-25) t = a[19] ^ d4 bc3 = t<<8 | t>>(64-8) a[20] = bc0 ^ (bc2 &^ bc1) a[1] = bc1 ^ (bc3 &^ bc2) a[7] = bc2 ^ (bc4 &^ bc3) a[13] = bc3 ^ (bc0 &^ bc4) a[19] = bc4 ^ (bc1 &^ bc0) t = a[5] ^ d0 bc1 = t<<36 | t>>(64-36) t = a[11] ^ d1 bc2 = t<<10 | t>>(64-10) t = a[17] ^ d2 bc3 = t<<15 | t>>(64-15) t = a[23] ^ d3 bc4 = t<<56 | t>>(64-56) t = a[4] ^ d4 bc0 = t<<27 | t>>(64-27) a[5] = bc0 ^ (bc2 &^ bc1) a[11] = bc1 ^ (bc3 &^ bc2) a[17] = bc2 ^ (bc4 &^ bc3) a[23] = bc3 ^ (bc0 &^ bc4) a[4] = bc4 ^ (bc1 &^ bc0) t = a[15] ^ d0 bc3 = t<<41 | t>>(64-41) t = a[21] ^ d1 bc4 = t<<2 | t>>(64-2) t = a[2] ^ d2 bc0 = t<<62 | t>>(64-62) t = a[8] ^ d3 bc1 = t<<55 | t>>(64-55) t = a[14] ^ d4 bc2 = t<<39 | t>>(64-39) a[15] = bc0 ^ (bc2 &^ bc1) a[21] = bc1 ^ (bc3 &^ bc2) a[2] = bc2 ^ (bc4 &^ bc3) a[8] = bc3 ^ (bc0 &^ bc4) a[14] = bc4 ^ (bc1 &^ bc0) // Round 2 bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] d0 = bc4 ^ (bc1<<1 | bc1>>63) d1 = bc0 ^ (bc2<<1 | bc2>>63) d2 = bc1 ^ (bc3<<1 | bc3>>63) d3 = bc2 ^ (bc4<<1 | bc4>>63) d4 = bc3 ^ (bc0<<1 | bc0>>63) bc0 = a[0] ^ d0 t = a[16] ^ d1 bc1 = t<<44 | t>>(64-44) t = a[7] ^ d2 bc2 = t<<43 | t>>(64-43) t = a[23] ^ d3 bc3 = t<<21 | t>>(64-21) t = a[14] ^ d4 bc4 = t<<14 | t>>(64-14) a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+1] a[16] = bc1 ^ (bc3 &^ bc2) a[7] = bc2 ^ (bc4 &^ bc3) a[23] = bc3 ^ (bc0 &^ bc4) a[14] = bc4 ^ (bc1 &^ bc0) t = a[20] ^ d0 bc2 = t<<3 | t>>(64-3) t = a[11] ^ d1 bc3 = t<<45 | t>>(64-45) t = a[2] ^ d2 bc4 = t<<61 | t>>(64-61) t = a[18] ^ d3 bc0 = t<<28 | t>>(64-28) t = a[9] ^ d4 bc1 = t<<20 | t>>(64-20) a[20] = bc0 ^ (bc2 &^ bc1) a[11] = bc1 ^ (bc3 &^ bc2) a[2] = bc2 ^ (bc4 &^ bc3) a[18] = bc3 ^ (bc0 &^ bc4) a[9] = bc4 ^ (bc1 &^ bc0) t = a[15] ^ d0 bc4 = t<<18 | t>>(64-18) t = a[6] ^ d1 bc0 = t<<1 | t>>(64-1) t = a[22] ^ d2 bc1 = t<<6 | t>>(64-6) t = a[13] ^ d3 bc2 = t<<25 | t>>(64-25) t = a[4] ^ d4 bc3 = t<<8 | t>>(64-8) a[15] = bc0 ^ (bc2 &^ bc1) a[6] = bc1 ^ (bc3 &^ bc2) a[22] = bc2 ^ (bc4 &^ bc3) a[13] = bc3 ^ (bc0 &^ bc4) a[4] = bc4 ^ (bc1 &^ bc0) t = a[10] ^ d0 bc1 = t<<36 | t>>(64-36) t = a[1] ^ d1 bc2 = t<<10 | t>>(64-10) t = a[17] ^ d2 bc3 = t<<15 | t>>(64-15) t = a[8] ^ d3 bc4 = t<<56 | t>>(64-56) t = a[24] ^ d4 bc0 = t<<27 | t>>(64-27) a[10] = bc0 ^ (bc2 &^ bc1) a[1] = bc1 ^ (bc3 &^ bc2) a[17] = bc2 ^ (bc4 &^ bc3) a[8] = bc3 ^ (bc0 &^ bc4) a[24] = bc4 ^ (bc1 &^ bc0) t = a[5] ^ d0 bc3 = t<<41 | t>>(64-41) t = a[21] ^ d1 bc4 = t<<2 | t>>(64-2) t = a[12] ^ d2 bc0 = t<<62 | t>>(64-62) t = a[3] ^ d3 bc1 = t<<55 | t>>(64-55) t = a[19] ^ d4 bc2 = t<<39 | t>>(64-39) a[5] = bc0 ^ (bc2 &^ bc1) a[21] = bc1 ^ (bc3 &^ bc2) a[12] = bc2 ^ (bc4 &^ bc3) a[3] = bc3 ^ (bc0 &^ bc4) a[19] = bc4 ^ (bc1 &^ bc0) // Round 3 bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] d0 = bc4 ^ (bc1<<1 | bc1>>63) d1 = bc0 ^ (bc2<<1 | bc2>>63) d2 = bc1 ^ (bc3<<1 | bc3>>63) d3 = bc2 ^ (bc4<<1 | bc4>>63) d4 = bc3 ^ (bc0<<1 | bc0>>63) bc0 = a[0] ^ d0 t = a[11] ^ d1 bc1 = t<<44 | t>>(64-44) t = a[22] ^ d2 bc2 = t<<43 | t>>(64-43) t = a[8] ^ d3 bc3 = t<<21 | t>>(64-21) t = a[19] ^ d4 bc4 = t<<14 | t>>(64-14) a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+2] a[11] = bc1 ^ (bc3 &^ bc2) a[22] = bc2 ^ (bc4 &^ bc3) a[8] = bc3 ^ (bc0 &^ bc4) a[19] = bc4 ^ (bc1 &^ bc0) t = a[15] ^ d0 bc2 = t<<3 | t>>(64-3) t = a[1] ^ d1 bc3 = t<<45 | t>>(64-45) t = a[12] ^ d2 bc4 = t<<61 | t>>(64-61) t = a[23] ^ d3 bc0 = t<<28 | t>>(64-28) t = a[9] ^ d4 bc1 = t<<20 | t>>(64-20) a[15] = bc0 ^ (bc2 &^ bc1) a[1] = bc1 ^ (bc3 &^ bc2) a[12] = bc2 ^ (bc4 &^ bc3) a[23] = bc3 ^ (bc0 &^ bc4) a[9] = bc4 ^ (bc1 &^ bc0) t = a[5] ^ d0 bc4 = t<<18 | t>>(64-18) t = a[16] ^ d1 bc0 = t<<1 | t>>(64-1) t = a[2] ^ d2 bc1 = t<<6 | t>>(64-6) t = a[13] ^ d3 bc2 = t<<25 | t>>(64-25) t = a[24] ^ d4 bc3 = t<<8 | t>>(64-8) a[5] = bc0 ^ (bc2 &^ bc1) a[16] = bc1 ^ (bc3 &^ bc2) a[2] = bc2 ^ (bc4 &^ bc3) a[13] = bc3 ^ (bc0 &^ bc4) a[24] = bc4 ^ (bc1 &^ bc0) t = a[20] ^ d0 bc1 = t<<36 | t>>(64-36) t = a[6] ^ d1 bc2 = t<<10 | t>>(64-10) t = a[17] ^ d2 bc3 = t<<15 | t>>(64-15) t = a[3] ^ d3 bc4 = t<<56 | t>>(64-56) t = a[14] ^ d4 bc0 = t<<27 | t>>(64-27) a[20] = bc0 ^ (bc2 &^ bc1) a[6] = bc1 ^ (bc3 &^ bc2) a[17] = bc2 ^ (bc4 &^ bc3) a[3] = bc3 ^ (bc0 &^ bc4) a[14] = bc4 ^ (bc1 &^ bc0) t = a[10] ^ d0 bc3 = t<<41 | t>>(64-41) t = a[21] ^ d1 bc4 = t<<2 | t>>(64-2) t = a[7] ^ d2 bc0 = t<<62 | t>>(64-62) t = a[18] ^ d3 bc1 = t<<55 | t>>(64-55) t = a[4] ^ d4 bc2 = t<<39 | t>>(64-39) a[10] = bc0 ^ (bc2 &^ bc1) a[21] = bc1 ^ (bc3 &^ bc2) a[7] = bc2 ^ (bc4 &^ bc3) a[18] = bc3 ^ (bc0 &^ bc4) a[4] = bc4 ^ (bc1 &^ bc0) // Round 4 bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] d0 = bc4 ^ (bc1<<1 | bc1>>63) d1 = bc0 ^ (bc2<<1 | bc2>>63) d2 = bc1 ^ (bc3<<1 | bc3>>63) d3 = bc2 ^ (bc4<<1 | bc4>>63) d4 = bc3 ^ (bc0<<1 | bc0>>63) bc0 = a[0] ^ d0 t = a[1] ^ d1 bc1 = t<<44 | t>>(64-44) t = a[2] ^ d2 bc2 = t<<43 | t>>(64-43) t = a[3] ^ d3 bc3 = t<<21 | t>>(64-21) t = a[4] ^ d4 bc4 = t<<14 | t>>(64-14) a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+3] a[1] = bc1 ^ (bc3 &^ bc2) a[2] = bc2 ^ (bc4 &^ bc3) a[3] = bc3 ^ (bc0 &^ bc4) a[4] = bc4 ^ (bc1 &^ bc0) t = a[5] ^ d0 bc2 = t<<3 | t>>(64-3) t = a[6] ^ d1 bc3 = t<<45 | t>>(64-45) t = a[7] ^ d2 bc4 = t<<61 | t>>(64-61) t = a[8] ^ d3 bc0 = t<<28 | t>>(64-28) t = a[9] ^ d4 bc1 = t<<20 | t>>(64-20) a[5] = bc0 ^ (bc2 &^ bc1) a[6] = bc1 ^ (bc3 &^ bc2) a[7] = bc2 ^ (bc4 &^ bc3) a[8] = bc3 ^ (bc0 &^ bc4) a[9] = bc4 ^ (bc1 &^ bc0) t = a[10] ^ d0 bc4 = t<<18 | t>>(64-18) t = a[11] ^ d1 bc0 = t<<1 | t>>(64-1) t = a[12] ^ d2 bc1 = t<<6 | t>>(64-6) t = a[13] ^ d3 bc2 = t<<25 | t>>(64-25) t = a[14] ^ d4 bc3 = t<<8 | t>>(64-8) a[10] = bc0 ^ (bc2 &^ bc1) a[11] = bc1 ^ (bc3 &^ bc2) a[12] = bc2 ^ (bc4 &^ bc3) a[13] = bc3 ^ (bc0 &^ bc4) a[14] = bc4 ^ (bc1 &^ bc0) t = a[15] ^ d0 bc1 = t<<36 | t>>(64-36) t = a[16] ^ d1 bc2 = t<<10 | t>>(64-10) t = a[17] ^ d2 bc3 = t<<15 | t>>(64-15) t = a[18] ^ d3 bc4 = t<<56 | t>>(64-56) t = a[19] ^ d4 bc0 = t<<27 | t>>(64-27) a[15] = bc0 ^ (bc2 &^ bc1) a[16] = bc1 ^ (bc3 &^ bc2) a[17] = bc2 ^ (bc4 &^ bc3) a[18] = bc3 ^ (bc0 &^ bc4) a[19] = bc4 ^ (bc1 &^ bc0) t = a[20] ^ d0 bc3 = t<<41 | t>>(64-41) t = a[21] ^ d1 bc4 = t<<2 | t>>(64-2) t = a[22] ^ d2 bc0 = t<<62 | t>>(64-62) t = a[23] ^ d3 bc1 = t<<55 | t>>(64-55) t = a[24] ^ d4 bc2 = t<<39 | t>>(64-39) a[20] = bc0 ^ (bc2 &^ bc1) a[21] = bc1 ^ (bc3 &^ bc2) a[22] = bc2 ^ (bc4 &^ bc3) a[23] = bc3 ^ (bc0 &^ bc4) a[24] = bc4 ^ (bc1 &^ bc0) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/hashes.go����������������������������������������������0000644�0610621�0607500�00000003565�13172163317�023523� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sha3 // This file provides functions for creating instances of the SHA-3 // and SHAKE hash functions, as well as utility functions for hashing // bytes. import ( "hash" ) // New224 creates a new SHA3-224 hash. // Its generic security strength is 224 bits against preimage attacks, // and 112 bits against collision attacks. func New224() hash.Hash { return &state{rate: 144, outputLen: 28, dsbyte: 0x06} } // New256 creates a new SHA3-256 hash. // Its generic security strength is 256 bits against preimage attacks, // and 128 bits against collision attacks. func New256() hash.Hash { return &state{rate: 136, outputLen: 32, dsbyte: 0x06} } // New384 creates a new SHA3-384 hash. // Its generic security strength is 384 bits against preimage attacks, // and 192 bits against collision attacks. func New384() hash.Hash { return &state{rate: 104, outputLen: 48, dsbyte: 0x06} } // New512 creates a new SHA3-512 hash. // Its generic security strength is 512 bits against preimage attacks, // and 256 bits against collision attacks. func New512() hash.Hash { return &state{rate: 72, outputLen: 64, dsbyte: 0x06} } // Sum224 returns the SHA3-224 digest of the data. func Sum224(data []byte) (digest [28]byte) { h := New224() h.Write(data) h.Sum(digest[:0]) return } // Sum256 returns the SHA3-256 digest of the data. func Sum256(data []byte) (digest [32]byte) { h := New256() h.Write(data) h.Sum(digest[:0]) return } // Sum384 returns the SHA3-384 digest of the data. func Sum384(data []byte) (digest [48]byte) { h := New384() h.Write(data) h.Sum(digest[:0]) return } // Sum512 returns the SHA3-512 digest of the data. func Sum512(data []byte) (digest [64]byte) { h := New512() h.Write(data) h.Sum(digest[:0]) return } �������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/sha3/doc.go�������������������������������������������������0000644�0610621�0607500�00000006166�13172163317�023015� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package sha3 implements the SHA-3 fixed-output-length hash functions and // the SHAKE variable-output-length hash functions defined by FIPS-202. // // Both types of hash function use the "sponge" construction and the Keccak // permutation. For a detailed specification see http://keccak.noekeon.org/ // // // Guidance // // If you aren't sure what function you need, use SHAKE256 with at least 64 // bytes of output. The SHAKE instances are faster than the SHA3 instances; // the latter have to allocate memory to conform to the hash.Hash interface. // // If you need a secret-key MAC (message authentication code), prepend the // secret key to the input, hash with SHAKE256 and read at least 32 bytes of // output. // // // Security strengths // // The SHA3-x (x equals 224, 256, 384, or 512) functions have a security // strength against preimage attacks of x bits. Since they only produce "x" // bits of output, their collision-resistance is only "x/2" bits. // // The SHAKE-256 and -128 functions have a generic security strength of 256 and // 128 bits against all attacks, provided that at least 2x bits of their output // is used. Requesting more than 64 or 32 bytes of output, respectively, does // not increase the collision-resistance of the SHAKE functions. // // // The sponge construction // // A sponge builds a pseudo-random function from a public pseudo-random // permutation, by applying the permutation to a state of "rate + capacity" // bytes, but hiding "capacity" of the bytes. // // A sponge starts out with a zero state. To hash an input using a sponge, up // to "rate" bytes of the input are XORed into the sponge's state. The sponge // is then "full" and the permutation is applied to "empty" it. This process is // repeated until all the input has been "absorbed". The input is then padded. // The digest is "squeezed" from the sponge in the same way, except that output // output is copied out instead of input being XORed in. // // A sponge is parameterized by its generic security strength, which is equal // to half its capacity; capacity + rate is equal to the permutation's width. // Since the KeccakF-1600 permutation is 1600 bits (200 bytes) wide, this means // that the security strength of a sponge instance is equal to (1600 - bitrate) / 2. // // // Recommendations // // The SHAKE functions are recommended for most new uses. They can produce // output of arbitrary length. SHAKE256, with an output length of at least // 64 bytes, provides 256-bit security against all attacks. The Keccak team // recommends it for most applications upgrading from SHA2-512. (NIST chose a // much stronger, but much slower, sponge instance for SHA3-512.) // // The SHA-3 functions are "drop-in" replacements for the SHA-2 functions. // They produce output of the same length, with the same security strengths // against all attacks. This means, in particular, that SHA3-256 only has // 128-bit collision resistance, because its output length is 32 bytes. package sha3 // import "golang.org/x/crypto/sha3" ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/scrypt/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022376� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/scrypt/scrypt_test.go���������������������������������������0000644�0610621�0607500�00000010602�13172163317�025307� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scrypt import ( "bytes" "testing" ) type testVector struct { password string salt string N, r, p int output []byte } var good = []testVector{ { "password", "salt", 2, 10, 10, []byte{ 0x48, 0x2c, 0x85, 0x8e, 0x22, 0x90, 0x55, 0xe6, 0x2f, 0x41, 0xe0, 0xec, 0x81, 0x9a, 0x5e, 0xe1, 0x8b, 0xdb, 0x87, 0x25, 0x1a, 0x53, 0x4f, 0x75, 0xac, 0xd9, 0x5a, 0xc5, 0xe5, 0xa, 0xa1, 0x5f, }, }, { "password", "salt", 16, 100, 100, []byte{ 0x88, 0xbd, 0x5e, 0xdb, 0x52, 0xd1, 0xdd, 0x0, 0x18, 0x87, 0x72, 0xad, 0x36, 0x17, 0x12, 0x90, 0x22, 0x4e, 0x74, 0x82, 0x95, 0x25, 0xb1, 0x8d, 0x73, 0x23, 0xa5, 0x7f, 0x91, 0x96, 0x3c, 0x37, }, }, { "this is a long \000 password", "and this is a long \000 salt", 16384, 8, 1, []byte{ 0xc3, 0xf1, 0x82, 0xee, 0x2d, 0xec, 0x84, 0x6e, 0x70, 0xa6, 0x94, 0x2f, 0xb5, 0x29, 0x98, 0x5a, 0x3a, 0x09, 0x76, 0x5e, 0xf0, 0x4c, 0x61, 0x29, 0x23, 0xb1, 0x7f, 0x18, 0x55, 0x5a, 0x37, 0x07, 0x6d, 0xeb, 0x2b, 0x98, 0x30, 0xd6, 0x9d, 0xe5, 0x49, 0x26, 0x51, 0xe4, 0x50, 0x6a, 0xe5, 0x77, 0x6d, 0x96, 0xd4, 0x0f, 0x67, 0xaa, 0xee, 0x37, 0xe1, 0x77, 0x7b, 0x8a, 0xd5, 0xc3, 0x11, 0x14, 0x32, 0xbb, 0x3b, 0x6f, 0x7e, 0x12, 0x64, 0x40, 0x18, 0x79, 0xe6, 0x41, 0xae, }, }, { "p", "s", 2, 1, 1, []byte{ 0x48, 0xb0, 0xd2, 0xa8, 0xa3, 0x27, 0x26, 0x11, 0x98, 0x4c, 0x50, 0xeb, 0xd6, 0x30, 0xaf, 0x52, }, }, { "", "", 16, 1, 1, []byte{ 0x77, 0xd6, 0x57, 0x62, 0x38, 0x65, 0x7b, 0x20, 0x3b, 0x19, 0xca, 0x42, 0xc1, 0x8a, 0x04, 0x97, 0xf1, 0x6b, 0x48, 0x44, 0xe3, 0x07, 0x4a, 0xe8, 0xdf, 0xdf, 0xfa, 0x3f, 0xed, 0xe2, 0x14, 0x42, 0xfc, 0xd0, 0x06, 0x9d, 0xed, 0x09, 0x48, 0xf8, 0x32, 0x6a, 0x75, 0x3a, 0x0f, 0xc8, 0x1f, 0x17, 0xe8, 0xd3, 0xe0, 0xfb, 0x2e, 0x0d, 0x36, 0x28, 0xcf, 0x35, 0xe2, 0x0c, 0x38, 0xd1, 0x89, 0x06, }, }, { "password", "NaCl", 1024, 8, 16, []byte{ 0xfd, 0xba, 0xbe, 0x1c, 0x9d, 0x34, 0x72, 0x00, 0x78, 0x56, 0xe7, 0x19, 0x0d, 0x01, 0xe9, 0xfe, 0x7c, 0x6a, 0xd7, 0xcb, 0xc8, 0x23, 0x78, 0x30, 0xe7, 0x73, 0x76, 0x63, 0x4b, 0x37, 0x31, 0x62, 0x2e, 0xaf, 0x30, 0xd9, 0x2e, 0x22, 0xa3, 0x88, 0x6f, 0xf1, 0x09, 0x27, 0x9d, 0x98, 0x30, 0xda, 0xc7, 0x27, 0xaf, 0xb9, 0x4a, 0x83, 0xee, 0x6d, 0x83, 0x60, 0xcb, 0xdf, 0xa2, 0xcc, 0x06, 0x40, }, }, { "pleaseletmein", "SodiumChloride", 16384, 8, 1, []byte{ 0x70, 0x23, 0xbd, 0xcb, 0x3a, 0xfd, 0x73, 0x48, 0x46, 0x1c, 0x06, 0xcd, 0x81, 0xfd, 0x38, 0xeb, 0xfd, 0xa8, 0xfb, 0xba, 0x90, 0x4f, 0x8e, 0x3e, 0xa9, 0xb5, 0x43, 0xf6, 0x54, 0x5d, 0xa1, 0xf2, 0xd5, 0x43, 0x29, 0x55, 0x61, 0x3f, 0x0f, 0xcf, 0x62, 0xd4, 0x97, 0x05, 0x24, 0x2a, 0x9a, 0xf9, 0xe6, 0x1e, 0x85, 0xdc, 0x0d, 0x65, 0x1e, 0x40, 0xdf, 0xcf, 0x01, 0x7b, 0x45, 0x57, 0x58, 0x87, }, }, /* // Disabled: needs 1 GiB RAM and takes too long for a simple test. { "pleaseletmein", "SodiumChloride", 1048576, 8, 1, []byte{ 0x21, 0x01, 0xcb, 0x9b, 0x6a, 0x51, 0x1a, 0xae, 0xad, 0xdb, 0xbe, 0x09, 0xcf, 0x70, 0xf8, 0x81, 0xec, 0x56, 0x8d, 0x57, 0x4a, 0x2f, 0xfd, 0x4d, 0xab, 0xe5, 0xee, 0x98, 0x20, 0xad, 0xaa, 0x47, 0x8e, 0x56, 0xfd, 0x8f, 0x4b, 0xa5, 0xd0, 0x9f, 0xfa, 0x1c, 0x6d, 0x92, 0x7c, 0x40, 0xf4, 0xc3, 0x37, 0x30, 0x40, 0x49, 0xe8, 0xa9, 0x52, 0xfb, 0xcb, 0xf4, 0x5c, 0x6f, 0xa7, 0x7a, 0x41, 0xa4, }, }, */ } var bad = []testVector{ {"p", "s", 0, 1, 1, nil}, // N == 0 {"p", "s", 1, 1, 1, nil}, // N == 1 {"p", "s", 7, 8, 1, nil}, // N is not power of 2 {"p", "s", 16, maxInt / 2, maxInt / 2, nil}, // p * r too large } func TestKey(t *testing.T) { for i, v := range good { k, err := Key([]byte(v.password), []byte(v.salt), v.N, v.r, v.p, len(v.output)) if err != nil { t.Errorf("%d: got unexpected error: %s", i, err) } if !bytes.Equal(k, v.output) { t.Errorf("%d: expected %x, got %x", i, v.output, k) } } for i, v := range bad { _, err := Key([]byte(v.password), []byte(v.salt), v.N, v.r, v.p, 32) if err == nil { t.Errorf("%d: expected error, got nil", i) } } } var sink []byte func BenchmarkKey(b *testing.B) { for i := 0; i < b.N; i++ { sink, _ = Key([]byte("password"), []byte("salt"), 1<<15, 8, 1, 64) } } ������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/scrypt/scrypt.go��������������������������������������������0000644�0610621�0607500�00000013541�13172163317�024255� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package scrypt implements the scrypt key derivation function as defined in // Colin Percival's paper "Stronger Key Derivation via Sequential Memory-Hard // Functions" (https://www.tarsnap.com/scrypt/scrypt.pdf). package scrypt // import "golang.org/x/crypto/scrypt" import ( "crypto/sha256" "errors" "golang.org/x/crypto/pbkdf2" ) const maxInt = int(^uint(0) >> 1) // blockCopy copies n numbers from src into dst. func blockCopy(dst, src []uint32, n int) { copy(dst, src[:n]) } // blockXOR XORs numbers from dst with n numbers from src. func blockXOR(dst, src []uint32, n int) { for i, v := range src[:n] { dst[i] ^= v } } // salsaXOR applies Salsa20/8 to the XOR of 16 numbers from tmp and in, // and puts the result into both both tmp and out. func salsaXOR(tmp *[16]uint32, in, out []uint32) { w0 := tmp[0] ^ in[0] w1 := tmp[1] ^ in[1] w2 := tmp[2] ^ in[2] w3 := tmp[3] ^ in[3] w4 := tmp[4] ^ in[4] w5 := tmp[5] ^ in[5] w6 := tmp[6] ^ in[6] w7 := tmp[7] ^ in[7] w8 := tmp[8] ^ in[8] w9 := tmp[9] ^ in[9] w10 := tmp[10] ^ in[10] w11 := tmp[11] ^ in[11] w12 := tmp[12] ^ in[12] w13 := tmp[13] ^ in[13] w14 := tmp[14] ^ in[14] w15 := tmp[15] ^ in[15] x0, x1, x2, x3, x4, x5, x6, x7, x8 := w0, w1, w2, w3, w4, w5, w6, w7, w8 x9, x10, x11, x12, x13, x14, x15 := w9, w10, w11, w12, w13, w14, w15 for i := 0; i < 8; i += 2 { u := x0 + x12 x4 ^= u<<7 | u>>(32-7) u = x4 + x0 x8 ^= u<<9 | u>>(32-9) u = x8 + x4 x12 ^= u<<13 | u>>(32-13) u = x12 + x8 x0 ^= u<<18 | u>>(32-18) u = x5 + x1 x9 ^= u<<7 | u>>(32-7) u = x9 + x5 x13 ^= u<<9 | u>>(32-9) u = x13 + x9 x1 ^= u<<13 | u>>(32-13) u = x1 + x13 x5 ^= u<<18 | u>>(32-18) u = x10 + x6 x14 ^= u<<7 | u>>(32-7) u = x14 + x10 x2 ^= u<<9 | u>>(32-9) u = x2 + x14 x6 ^= u<<13 | u>>(32-13) u = x6 + x2 x10 ^= u<<18 | u>>(32-18) u = x15 + x11 x3 ^= u<<7 | u>>(32-7) u = x3 + x15 x7 ^= u<<9 | u>>(32-9) u = x7 + x3 x11 ^= u<<13 | u>>(32-13) u = x11 + x7 x15 ^= u<<18 | u>>(32-18) u = x0 + x3 x1 ^= u<<7 | u>>(32-7) u = x1 + x0 x2 ^= u<<9 | u>>(32-9) u = x2 + x1 x3 ^= u<<13 | u>>(32-13) u = x3 + x2 x0 ^= u<<18 | u>>(32-18) u = x5 + x4 x6 ^= u<<7 | u>>(32-7) u = x6 + x5 x7 ^= u<<9 | u>>(32-9) u = x7 + x6 x4 ^= u<<13 | u>>(32-13) u = x4 + x7 x5 ^= u<<18 | u>>(32-18) u = x10 + x9 x11 ^= u<<7 | u>>(32-7) u = x11 + x10 x8 ^= u<<9 | u>>(32-9) u = x8 + x11 x9 ^= u<<13 | u>>(32-13) u = x9 + x8 x10 ^= u<<18 | u>>(32-18) u = x15 + x14 x12 ^= u<<7 | u>>(32-7) u = x12 + x15 x13 ^= u<<9 | u>>(32-9) u = x13 + x12 x14 ^= u<<13 | u>>(32-13) u = x14 + x13 x15 ^= u<<18 | u>>(32-18) } x0 += w0 x1 += w1 x2 += w2 x3 += w3 x4 += w4 x5 += w5 x6 += w6 x7 += w7 x8 += w8 x9 += w9 x10 += w10 x11 += w11 x12 += w12 x13 += w13 x14 += w14 x15 += w15 out[0], tmp[0] = x0, x0 out[1], tmp[1] = x1, x1 out[2], tmp[2] = x2, x2 out[3], tmp[3] = x3, x3 out[4], tmp[4] = x4, x4 out[5], tmp[5] = x5, x5 out[6], tmp[6] = x6, x6 out[7], tmp[7] = x7, x7 out[8], tmp[8] = x8, x8 out[9], tmp[9] = x9, x9 out[10], tmp[10] = x10, x10 out[11], tmp[11] = x11, x11 out[12], tmp[12] = x12, x12 out[13], tmp[13] = x13, x13 out[14], tmp[14] = x14, x14 out[15], tmp[15] = x15, x15 } func blockMix(tmp *[16]uint32, in, out []uint32, r int) { blockCopy(tmp[:], in[(2*r-1)*16:], 16) for i := 0; i < 2*r; i += 2 { salsaXOR(tmp, in[i*16:], out[i*8:]) salsaXOR(tmp, in[i*16+16:], out[i*8+r*16:]) } } func integer(b []uint32, r int) uint64 { j := (2*r - 1) * 16 return uint64(b[j]) | uint64(b[j+1])<<32 } func smix(b []byte, r, N int, v, xy []uint32) { var tmp [16]uint32 x := xy y := xy[32*r:] j := 0 for i := 0; i < 32*r; i++ { x[i] = uint32(b[j]) | uint32(b[j+1])<<8 | uint32(b[j+2])<<16 | uint32(b[j+3])<<24 j += 4 } for i := 0; i < N; i += 2 { blockCopy(v[i*(32*r):], x, 32*r) blockMix(&tmp, x, y, r) blockCopy(v[(i+1)*(32*r):], y, 32*r) blockMix(&tmp, y, x, r) } for i := 0; i < N; i += 2 { j := int(integer(x, r) & uint64(N-1)) blockXOR(x, v[j*(32*r):], 32*r) blockMix(&tmp, x, y, r) j = int(integer(y, r) & uint64(N-1)) blockXOR(y, v[j*(32*r):], 32*r) blockMix(&tmp, y, x, r) } j = 0 for _, v := range x[:32*r] { b[j+0] = byte(v >> 0) b[j+1] = byte(v >> 8) b[j+2] = byte(v >> 16) b[j+3] = byte(v >> 24) j += 4 } } // Key derives a key from the password, salt, and cost parameters, returning // a byte slice of length keyLen that can be used as cryptographic key. // // N is a CPU/memory cost parameter, which must be a power of two greater than 1. // r and p must satisfy r * p < 2³â°. If the parameters do not satisfy the // limits, the function returns a nil byte slice and an error. // // For example, you can get a derived key for e.g. AES-256 (which needs a // 32-byte key) by doing: // // dk, err := scrypt.Key([]byte("some password"), salt, 16384, 8, 1, 32) // // The recommended parameters for interactive logins as of 2017 are N=32768, r=8 // and p=1. The parameters N, r, and p should be increased as memory latency and // CPU parallelism increases; consider setting N to the highest power of 2 you // can derive within 100 milliseconds. Remember to get a good random salt. func Key(password, salt []byte, N, r, p, keyLen int) ([]byte, error) { if N <= 1 || N&(N-1) != 0 { return nil, errors.New("scrypt: N must be > 1 and a power of 2") } if uint64(r)*uint64(p) >= 1<<30 || r > maxInt/128/p || r > maxInt/256 || N > maxInt/128/r { return nil, errors.New("scrypt: parameters are too large") } xy := make([]uint32, 64*r) v := make([]uint32, 32*N*r) b := pbkdf2.Key(password, salt, 1, p*128*r, sha256.New) for i := 0; i < p; i++ { smix(b[i*128*r:], r, N, v, xy) } return pbkdf2.Key(password, b, 1, keyLen, sha256.New), nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/scrypt/example_test.go��������������������������������������0000644�0610621�0607500�00000001213�13172163317�025414� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package scrypt_test import ( "encoding/base64" "fmt" "log" "golang.org/x/crypto/scrypt" ) func Example() { // DO NOT use this salt value; generate your own random salt. 8 bytes is // a good length. salt := []byte{0xc8, 0x28, 0xf2, 0x58, 0xa7, 0x6a, 0xad, 0x7b} dk, err := scrypt.Key([]byte("some password"), salt, 1<<15, 8, 1, 32) if err != nil { log.Fatal(err) } fmt.Println(base64.StdEncoding.EncodeToString(dk)) // Output: lGnMz8io0AUkfzn6Pls1qX20Vs7PGN6sbYQ2TQgY12M= } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022317� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa20_test.go�������������������������������������0000644�0610621�0607500�00000007273�13172163317�025163� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package salsa20 import ( "bytes" "encoding/hex" "testing" ) func fromHex(s string) []byte { ret, err := hex.DecodeString(s) if err != nil { panic(err) } return ret } // testVectors was taken from set 6 of the ECRYPT test vectors: // http://www.ecrypt.eu.org/stream/svn/viewcvs.cgi/ecrypt/trunk/submissions/salsa20/full/verified.test-vectors?logsort=rev&rev=210&view=markup var testVectors = []struct { key []byte iv []byte numBytes int xor []byte }{ { fromHex("0053A6F94C9FF24598EB3E91E4378ADD3083D6297CCF2275C81B6EC11467BA0D"), fromHex("0D74DB42A91077DE"), 131072, fromHex("C349B6A51A3EC9B712EAED3F90D8BCEE69B7628645F251A996F55260C62EF31FD6C6B0AEA94E136C9D984AD2DF3578F78E457527B03A0450580DD874F63B1AB9"), }, { fromHex("0558ABFE51A4F74A9DF04396E93C8FE23588DB2E81D4277ACD2073C6196CBF12"), fromHex("167DE44BB21980E7"), 131072, fromHex("C3EAAF32836BACE32D04E1124231EF47E101367D6305413A0EEB07C60698A2876E4D031870A739D6FFDDD208597AFF0A47AC17EDB0167DD67EBA84F1883D4DFD"), }, { fromHex("0A5DB00356A9FC4FA2F5489BEE4194E73A8DE03386D92C7FD22578CB1E71C417"), fromHex("1F86ED54BB2289F0"), 131072, fromHex("3CD23C3DC90201ACC0CF49B440B6C417F0DC8D8410A716D5314C059E14B1A8D9A9FB8EA3D9C8DAE12B21402F674AA95C67B1FC514E994C9D3F3A6E41DFF5BBA6"), }, { fromHex("0F62B5085BAE0154A7FA4DA0F34699EC3F92E5388BDE3184D72A7DD02376C91C"), fromHex("288FF65DC42B92F9"), 131072, fromHex("E00EBCCD70D69152725F9987982178A2E2E139C7BCBE04CA8A0E99E318D9AB76F988C8549F75ADD790BA4F81C176DA653C1A043F11A958E169B6D2319F4EEC1A"), }, } func TestSalsa20(t *testing.T) { var inBuf, outBuf []byte var key [32]byte for i, test := range testVectors { if test.numBytes%64 != 0 { t.Errorf("#%d: numBytes is not a multiple of 64", i) continue } if test.numBytes > len(inBuf) { inBuf = make([]byte, test.numBytes) outBuf = make([]byte, test.numBytes) } in := inBuf[:test.numBytes] out := outBuf[:test.numBytes] copy(key[:], test.key) XORKeyStream(out, in, test.iv, &key) var xor [64]byte for len(out) > 0 { for i := 0; i < 64; i++ { xor[i] ^= out[i] } out = out[64:] } if !bytes.Equal(xor[:], test.xor) { t.Errorf("#%d: bad result", i) } } } var xSalsa20TestData = []struct { in, nonce, key, out []byte }{ { []byte("Hello world!"), []byte("24-byte nonce for xsalsa"), []byte("this is 32-byte key for xsalsa20"), []byte{0x00, 0x2d, 0x45, 0x13, 0x84, 0x3f, 0xc2, 0x40, 0xc4, 0x01, 0xe5, 0x41}, }, { make([]byte, 64), []byte("24-byte nonce for xsalsa"), []byte("this is 32-byte key for xsalsa20"), []byte{0x48, 0x48, 0x29, 0x7f, 0xeb, 0x1f, 0xb5, 0x2f, 0xb6, 0x6d, 0x81, 0x60, 0x9b, 0xd5, 0x47, 0xfa, 0xbc, 0xbe, 0x70, 0x26, 0xed, 0xc8, 0xb5, 0xe5, 0xe4, 0x49, 0xd0, 0x88, 0xbf, 0xa6, 0x9c, 0x08, 0x8f, 0x5d, 0x8d, 0xa1, 0xd7, 0x91, 0x26, 0x7c, 0x2c, 0x19, 0x5a, 0x7f, 0x8c, 0xae, 0x9c, 0x4b, 0x40, 0x50, 0xd0, 0x8c, 0xe6, 0xd3, 0xa1, 0x51, 0xec, 0x26, 0x5f, 0x3a, 0x58, 0xe4, 0x76, 0x48}, }, } func TestXSalsa20(t *testing.T) { var key [32]byte for i, test := range xSalsa20TestData { out := make([]byte, len(test.in)) copy(key[:], test.key) XORKeyStream(out, test.in, test.nonce, &key) if !bytes.Equal(out, test.out) { t.Errorf("%d: expected %x, got %x", i, test.out, out) } } } var ( keyArray [32]byte key = &keyArray nonce [8]byte msg = make([]byte, 1<<10) ) func BenchmarkXOR1K(b *testing.B) { b.StopTimer() out := make([]byte, 1024) b.StartTimer() for i := 0; i < b.N; i++ { XORKeyStream(out, msg[:1024], nonce[:], key) } b.SetBytes(1024) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa20.go������������������������������������������0000644�0610621�0607500�00000003555�13172163317�024123� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package salsa20 implements the Salsa20 stream cipher as specified in https://cr.yp.to/snuffle/spec.pdf. Salsa20 differs from many other stream ciphers in that it is message orientated rather than byte orientated. Keystream blocks are not preserved between calls, therefore each side must encrypt/decrypt data with the same segmentation. Another aspect of this difference is that part of the counter is exposed as a nonce in each call. Encrypting two different messages with the same (key, nonce) pair leads to trivial plaintext recovery. This is analogous to encrypting two different messages with the same key with a traditional stream cipher. This package also implements XSalsa20: a version of Salsa20 with a 24-byte nonce as specified in https://cr.yp.to/snuffle/xsalsa-20081128.pdf. Simply passing a 24-byte slice as the nonce triggers XSalsa20. */ package salsa20 // import "golang.org/x/crypto/salsa20" // TODO(agl): implement XORKeyStream12 and XORKeyStream8 - the reduced round variants of Salsa20. import ( "golang.org/x/crypto/salsa20/salsa" ) // XORKeyStream crypts bytes from in to out using the given key and nonce. // In and out must overlap entirely or not at all. Nonce must // be either 8 or 24 bytes long. func XORKeyStream(out, in []byte, nonce []byte, key *[32]byte) { if len(out) < len(in) { in = in[:len(out)] } var subNonce [16]byte if len(nonce) == 24 { var subKey [32]byte var hNonce [16]byte copy(hNonce[:], nonce[:16]) salsa.HSalsa20(&subKey, &hNonce, key, &salsa.Sigma) copy(subNonce[:], nonce[16:]) key = &subKey } else if len(nonce) == 8 { copy(subNonce[:], nonce[:]) } else { panic("salsa20: nonce must be 8 or 24 bytes") } salsa.XORKeyStream(out, in, &subNonce, key) } ���������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa/����������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023422� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa/salsa_test.go���������������������������������0000644�0610621�0607500�00000003247�13172163317�026121� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package salsa import "testing" func TestCore208(t *testing.T) { in := [64]byte{ 0x7e, 0x87, 0x9a, 0x21, 0x4f, 0x3e, 0xc9, 0x86, 0x7c, 0xa9, 0x40, 0xe6, 0x41, 0x71, 0x8f, 0x26, 0xba, 0xee, 0x55, 0x5b, 0x8c, 0x61, 0xc1, 0xb5, 0x0d, 0xf8, 0x46, 0x11, 0x6d, 0xcd, 0x3b, 0x1d, 0xee, 0x24, 0xf3, 0x19, 0xdf, 0x9b, 0x3d, 0x85, 0x14, 0x12, 0x1e, 0x4b, 0x5a, 0xc5, 0xaa, 0x32, 0x76, 0x02, 0x1d, 0x29, 0x09, 0xc7, 0x48, 0x29, 0xed, 0xeb, 0xc6, 0x8d, 0xb8, 0xb8, 0xc2, 0x5e} out := [64]byte{ 0xa4, 0x1f, 0x85, 0x9c, 0x66, 0x08, 0xcc, 0x99, 0x3b, 0x81, 0xca, 0xcb, 0x02, 0x0c, 0xef, 0x05, 0x04, 0x4b, 0x21, 0x81, 0xa2, 0xfd, 0x33, 0x7d, 0xfd, 0x7b, 0x1c, 0x63, 0x96, 0x68, 0x2f, 0x29, 0xb4, 0x39, 0x31, 0x68, 0xe3, 0xc9, 0xe6, 0xbc, 0xfe, 0x6b, 0xc5, 0xb7, 0xa0, 0x6d, 0x96, 0xba, 0xe4, 0x24, 0xcc, 0x10, 0x2c, 0x91, 0x74, 0x5c, 0x24, 0xad, 0x67, 0x3d, 0xc7, 0x61, 0x8f, 0x81, } Core208(&in, &in) if in != out { t.Errorf("expected %x, got %x", out, in) } } func TestOutOfBoundsWrite(t *testing.T) { // encrypted "0123456789" cipherText := []byte{170, 166, 196, 104, 175, 121, 68, 44, 174, 51} var counter [16]byte var key [32]byte want := "abcdefghij" plainText := []byte(want) defer func() { err := recover() if err == nil { t.Error("XORKeyStream expected to panic on len(dst) < len(src), but didn't") } if plainText[3] == '3' { t.Errorf("XORKeyStream did out of bounds write, want %v, got %v", want, string(plainText)) } }() XORKeyStream(plainText[:3], cipherText, &counter, &key) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go��������������������������������0000644�0610621�0607500�00000013145�13172163317�026056� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !amd64 appengine gccgo package salsa const rounds = 20 // core applies the Salsa20 core function to 16-byte input in, 32-byte key k, // and 16-byte constant c, and puts the result into 64-byte array out. func core(out *[64]byte, in *[16]byte, k *[32]byte, c *[16]byte) { j0 := uint32(c[0]) | uint32(c[1])<<8 | uint32(c[2])<<16 | uint32(c[3])<<24 j1 := uint32(k[0]) | uint32(k[1])<<8 | uint32(k[2])<<16 | uint32(k[3])<<24 j2 := uint32(k[4]) | uint32(k[5])<<8 | uint32(k[6])<<16 | uint32(k[7])<<24 j3 := uint32(k[8]) | uint32(k[9])<<8 | uint32(k[10])<<16 | uint32(k[11])<<24 j4 := uint32(k[12]) | uint32(k[13])<<8 | uint32(k[14])<<16 | uint32(k[15])<<24 j5 := uint32(c[4]) | uint32(c[5])<<8 | uint32(c[6])<<16 | uint32(c[7])<<24 j6 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24 j7 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24 j8 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24 j9 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24 j10 := uint32(c[8]) | uint32(c[9])<<8 | uint32(c[10])<<16 | uint32(c[11])<<24 j11 := uint32(k[16]) | uint32(k[17])<<8 | uint32(k[18])<<16 | uint32(k[19])<<24 j12 := uint32(k[20]) | uint32(k[21])<<8 | uint32(k[22])<<16 | uint32(k[23])<<24 j13 := uint32(k[24]) | uint32(k[25])<<8 | uint32(k[26])<<16 | uint32(k[27])<<24 j14 := uint32(k[28]) | uint32(k[29])<<8 | uint32(k[30])<<16 | uint32(k[31])<<24 j15 := uint32(c[12]) | uint32(c[13])<<8 | uint32(c[14])<<16 | uint32(c[15])<<24 x0, x1, x2, x3, x4, x5, x6, x7, x8 := j0, j1, j2, j3, j4, j5, j6, j7, j8 x9, x10, x11, x12, x13, x14, x15 := j9, j10, j11, j12, j13, j14, j15 for i := 0; i < rounds; i += 2 { u := x0 + x12 x4 ^= u<<7 | u>>(32-7) u = x4 + x0 x8 ^= u<<9 | u>>(32-9) u = x8 + x4 x12 ^= u<<13 | u>>(32-13) u = x12 + x8 x0 ^= u<<18 | u>>(32-18) u = x5 + x1 x9 ^= u<<7 | u>>(32-7) u = x9 + x5 x13 ^= u<<9 | u>>(32-9) u = x13 + x9 x1 ^= u<<13 | u>>(32-13) u = x1 + x13 x5 ^= u<<18 | u>>(32-18) u = x10 + x6 x14 ^= u<<7 | u>>(32-7) u = x14 + x10 x2 ^= u<<9 | u>>(32-9) u = x2 + x14 x6 ^= u<<13 | u>>(32-13) u = x6 + x2 x10 ^= u<<18 | u>>(32-18) u = x15 + x11 x3 ^= u<<7 | u>>(32-7) u = x3 + x15 x7 ^= u<<9 | u>>(32-9) u = x7 + x3 x11 ^= u<<13 | u>>(32-13) u = x11 + x7 x15 ^= u<<18 | u>>(32-18) u = x0 + x3 x1 ^= u<<7 | u>>(32-7) u = x1 + x0 x2 ^= u<<9 | u>>(32-9) u = x2 + x1 x3 ^= u<<13 | u>>(32-13) u = x3 + x2 x0 ^= u<<18 | u>>(32-18) u = x5 + x4 x6 ^= u<<7 | u>>(32-7) u = x6 + x5 x7 ^= u<<9 | u>>(32-9) u = x7 + x6 x4 ^= u<<13 | u>>(32-13) u = x4 + x7 x5 ^= u<<18 | u>>(32-18) u = x10 + x9 x11 ^= u<<7 | u>>(32-7) u = x11 + x10 x8 ^= u<<9 | u>>(32-9) u = x8 + x11 x9 ^= u<<13 | u>>(32-13) u = x9 + x8 x10 ^= u<<18 | u>>(32-18) u = x15 + x14 x12 ^= u<<7 | u>>(32-7) u = x12 + x15 x13 ^= u<<9 | u>>(32-9) u = x13 + x12 x14 ^= u<<13 | u>>(32-13) u = x14 + x13 x15 ^= u<<18 | u>>(32-18) } x0 += j0 x1 += j1 x2 += j2 x3 += j3 x4 += j4 x5 += j5 x6 += j6 x7 += j7 x8 += j8 x9 += j9 x10 += j10 x11 += j11 x12 += j12 x13 += j13 x14 += j14 x15 += j15 out[0] = byte(x0) out[1] = byte(x0 >> 8) out[2] = byte(x0 >> 16) out[3] = byte(x0 >> 24) out[4] = byte(x1) out[5] = byte(x1 >> 8) out[6] = byte(x1 >> 16) out[7] = byte(x1 >> 24) out[8] = byte(x2) out[9] = byte(x2 >> 8) out[10] = byte(x2 >> 16) out[11] = byte(x2 >> 24) out[12] = byte(x3) out[13] = byte(x3 >> 8) out[14] = byte(x3 >> 16) out[15] = byte(x3 >> 24) out[16] = byte(x4) out[17] = byte(x4 >> 8) out[18] = byte(x4 >> 16) out[19] = byte(x4 >> 24) out[20] = byte(x5) out[21] = byte(x5 >> 8) out[22] = byte(x5 >> 16) out[23] = byte(x5 >> 24) out[24] = byte(x6) out[25] = byte(x6 >> 8) out[26] = byte(x6 >> 16) out[27] = byte(x6 >> 24) out[28] = byte(x7) out[29] = byte(x7 >> 8) out[30] = byte(x7 >> 16) out[31] = byte(x7 >> 24) out[32] = byte(x8) out[33] = byte(x8 >> 8) out[34] = byte(x8 >> 16) out[35] = byte(x8 >> 24) out[36] = byte(x9) out[37] = byte(x9 >> 8) out[38] = byte(x9 >> 16) out[39] = byte(x9 >> 24) out[40] = byte(x10) out[41] = byte(x10 >> 8) out[42] = byte(x10 >> 16) out[43] = byte(x10 >> 24) out[44] = byte(x11) out[45] = byte(x11 >> 8) out[46] = byte(x11 >> 16) out[47] = byte(x11 >> 24) out[48] = byte(x12) out[49] = byte(x12 >> 8) out[50] = byte(x12 >> 16) out[51] = byte(x12 >> 24) out[52] = byte(x13) out[53] = byte(x13 >> 8) out[54] = byte(x13 >> 16) out[55] = byte(x13 >> 24) out[56] = byte(x14) out[57] = byte(x14 >> 8) out[58] = byte(x14 >> 16) out[59] = byte(x14 >> 24) out[60] = byte(x15) out[61] = byte(x15 >> 8) out[62] = byte(x15 >> 16) out[63] = byte(x15 >> 24) } // XORKeyStream crypts bytes from in to out using the given key and counters. // In and out must overlap entirely or not at all. Counter // contains the raw salsa20 counter bytes (both nonce and block counter). func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { var block [64]byte var counterCopy [16]byte copy(counterCopy[:], counter[:]) for len(in) >= 64 { core(&block, &counterCopy, key, &Sigma) for i, x := range block { out[i] = in[i] ^ x } u := uint32(1) for i := 8; i < 16; i++ { u += uint32(counterCopy[i]) counterCopy[i] = byte(u) u >>= 8 } in = in[64:] out = out[64:] } if len(in) > 0 { core(&block, &counterCopy, key, &Sigma) for i, v := range in { out[i] = v ^ block[i] } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go������������������������������0000644�0610621�0607500�00000001374�13172163317�026216� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!appengine,!gccgo package salsa // This function is implemented in salsa2020_amd64.s. //go:noescape func salsa2020XORKeyStream(out, in *byte, n uint64, nonce, key *byte) // XORKeyStream crypts bytes from in to out using the given key and counters. // In and out must overlap entirely or not at all. Counter // contains the raw salsa20 counter bytes (both nonce and block counter). func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { if len(in) == 0 { return } _ = out[len(in)-1] salsa2020XORKeyStream(&out[0], &in[0], uint64(len(in)), &counter[0], &key[0]) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa/salsa208.go�����������������������������������0000644�0610621�0607500�00000011567�13172163317�025320� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package salsa // Core208 applies the Salsa20/8 core function to the 64-byte array in and puts // the result into the 64-byte array out. The input and output may be the same array. func Core208(out *[64]byte, in *[64]byte) { j0 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24 j1 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24 j2 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24 j3 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24 j4 := uint32(in[16]) | uint32(in[17])<<8 | uint32(in[18])<<16 | uint32(in[19])<<24 j5 := uint32(in[20]) | uint32(in[21])<<8 | uint32(in[22])<<16 | uint32(in[23])<<24 j6 := uint32(in[24]) | uint32(in[25])<<8 | uint32(in[26])<<16 | uint32(in[27])<<24 j7 := uint32(in[28]) | uint32(in[29])<<8 | uint32(in[30])<<16 | uint32(in[31])<<24 j8 := uint32(in[32]) | uint32(in[33])<<8 | uint32(in[34])<<16 | uint32(in[35])<<24 j9 := uint32(in[36]) | uint32(in[37])<<8 | uint32(in[38])<<16 | uint32(in[39])<<24 j10 := uint32(in[40]) | uint32(in[41])<<8 | uint32(in[42])<<16 | uint32(in[43])<<24 j11 := uint32(in[44]) | uint32(in[45])<<8 | uint32(in[46])<<16 | uint32(in[47])<<24 j12 := uint32(in[48]) | uint32(in[49])<<8 | uint32(in[50])<<16 | uint32(in[51])<<24 j13 := uint32(in[52]) | uint32(in[53])<<8 | uint32(in[54])<<16 | uint32(in[55])<<24 j14 := uint32(in[56]) | uint32(in[57])<<8 | uint32(in[58])<<16 | uint32(in[59])<<24 j15 := uint32(in[60]) | uint32(in[61])<<8 | uint32(in[62])<<16 | uint32(in[63])<<24 x0, x1, x2, x3, x4, x5, x6, x7, x8 := j0, j1, j2, j3, j4, j5, j6, j7, j8 x9, x10, x11, x12, x13, x14, x15 := j9, j10, j11, j12, j13, j14, j15 for i := 0; i < 8; i += 2 { u := x0 + x12 x4 ^= u<<7 | u>>(32-7) u = x4 + x0 x8 ^= u<<9 | u>>(32-9) u = x8 + x4 x12 ^= u<<13 | u>>(32-13) u = x12 + x8 x0 ^= u<<18 | u>>(32-18) u = x5 + x1 x9 ^= u<<7 | u>>(32-7) u = x9 + x5 x13 ^= u<<9 | u>>(32-9) u = x13 + x9 x1 ^= u<<13 | u>>(32-13) u = x1 + x13 x5 ^= u<<18 | u>>(32-18) u = x10 + x6 x14 ^= u<<7 | u>>(32-7) u = x14 + x10 x2 ^= u<<9 | u>>(32-9) u = x2 + x14 x6 ^= u<<13 | u>>(32-13) u = x6 + x2 x10 ^= u<<18 | u>>(32-18) u = x15 + x11 x3 ^= u<<7 | u>>(32-7) u = x3 + x15 x7 ^= u<<9 | u>>(32-9) u = x7 + x3 x11 ^= u<<13 | u>>(32-13) u = x11 + x7 x15 ^= u<<18 | u>>(32-18) u = x0 + x3 x1 ^= u<<7 | u>>(32-7) u = x1 + x0 x2 ^= u<<9 | u>>(32-9) u = x2 + x1 x3 ^= u<<13 | u>>(32-13) u = x3 + x2 x0 ^= u<<18 | u>>(32-18) u = x5 + x4 x6 ^= u<<7 | u>>(32-7) u = x6 + x5 x7 ^= u<<9 | u>>(32-9) u = x7 + x6 x4 ^= u<<13 | u>>(32-13) u = x4 + x7 x5 ^= u<<18 | u>>(32-18) u = x10 + x9 x11 ^= u<<7 | u>>(32-7) u = x11 + x10 x8 ^= u<<9 | u>>(32-9) u = x8 + x11 x9 ^= u<<13 | u>>(32-13) u = x9 + x8 x10 ^= u<<18 | u>>(32-18) u = x15 + x14 x12 ^= u<<7 | u>>(32-7) u = x12 + x15 x13 ^= u<<9 | u>>(32-9) u = x13 + x12 x14 ^= u<<13 | u>>(32-13) u = x14 + x13 x15 ^= u<<18 | u>>(32-18) } x0 += j0 x1 += j1 x2 += j2 x3 += j3 x4 += j4 x5 += j5 x6 += j6 x7 += j7 x8 += j8 x9 += j9 x10 += j10 x11 += j11 x12 += j12 x13 += j13 x14 += j14 x15 += j15 out[0] = byte(x0) out[1] = byte(x0 >> 8) out[2] = byte(x0 >> 16) out[3] = byte(x0 >> 24) out[4] = byte(x1) out[5] = byte(x1 >> 8) out[6] = byte(x1 >> 16) out[7] = byte(x1 >> 24) out[8] = byte(x2) out[9] = byte(x2 >> 8) out[10] = byte(x2 >> 16) out[11] = byte(x2 >> 24) out[12] = byte(x3) out[13] = byte(x3 >> 8) out[14] = byte(x3 >> 16) out[15] = byte(x3 >> 24) out[16] = byte(x4) out[17] = byte(x4 >> 8) out[18] = byte(x4 >> 16) out[19] = byte(x4 >> 24) out[20] = byte(x5) out[21] = byte(x5 >> 8) out[22] = byte(x5 >> 16) out[23] = byte(x5 >> 24) out[24] = byte(x6) out[25] = byte(x6 >> 8) out[26] = byte(x6 >> 16) out[27] = byte(x6 >> 24) out[28] = byte(x7) out[29] = byte(x7 >> 8) out[30] = byte(x7 >> 16) out[31] = byte(x7 >> 24) out[32] = byte(x8) out[33] = byte(x8 >> 8) out[34] = byte(x8 >> 16) out[35] = byte(x8 >> 24) out[36] = byte(x9) out[37] = byte(x9 >> 8) out[38] = byte(x9 >> 16) out[39] = byte(x9 >> 24) out[40] = byte(x10) out[41] = byte(x10 >> 8) out[42] = byte(x10 >> 16) out[43] = byte(x10 >> 24) out[44] = byte(x11) out[45] = byte(x11 >> 8) out[46] = byte(x11 >> 16) out[47] = byte(x11 >> 24) out[48] = byte(x12) out[49] = byte(x12 >> 8) out[50] = byte(x12 >> 16) out[51] = byte(x12 >> 24) out[52] = byte(x13) out[53] = byte(x13 >> 8) out[54] = byte(x13 >> 16) out[55] = byte(x13 >> 24) out[56] = byte(x14) out[57] = byte(x14 >> 8) out[58] = byte(x14 >> 16) out[59] = byte(x14 >> 24) out[60] = byte(x15) out[61] = byte(x15 >> 8) out[62] = byte(x15 >> 16) out[63] = byte(x15 >> 24) } �����������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa/salsa2020_amd64.s�����������������������������0000644�0610621�0607500�00000032747�13172163317�026225� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!appengine,!gccgo // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // func salsa2020XORKeyStream(out, in *byte, n uint64, nonce, key *byte) // This needs up to 64 bytes at 360(SP); hence the non-obvious frame size. TEXT ·salsa2020XORKeyStream(SB),0,$456-40 // frame = 424 + 32 byte alignment MOVQ out+0(FP),DI MOVQ in+8(FP),SI MOVQ n+16(FP),DX MOVQ nonce+24(FP),CX MOVQ key+32(FP),R8 MOVQ SP,R12 MOVQ SP,R9 ADDQ $31, R9 ANDQ $~31, R9 MOVQ R9, SP MOVQ DX,R9 MOVQ CX,DX MOVQ R8,R10 CMPQ R9,$0 JBE DONE START: MOVL 20(R10),CX MOVL 0(R10),R8 MOVL 0(DX),AX MOVL 16(R10),R11 MOVL CX,0(SP) MOVL R8, 4 (SP) MOVL AX, 8 (SP) MOVL R11, 12 (SP) MOVL 8(DX),CX MOVL 24(R10),R8 MOVL 4(R10),AX MOVL 4(DX),R11 MOVL CX,16(SP) MOVL R8, 20 (SP) MOVL AX, 24 (SP) MOVL R11, 28 (SP) MOVL 12(DX),CX MOVL 12(R10),DX MOVL 28(R10),R8 MOVL 8(R10),AX MOVL DX,32(SP) MOVL CX, 36 (SP) MOVL R8, 40 (SP) MOVL AX, 44 (SP) MOVQ $1634760805,DX MOVQ $857760878,CX MOVQ $2036477234,R8 MOVQ $1797285236,AX MOVL DX,48(SP) MOVL CX, 52 (SP) MOVL R8, 56 (SP) MOVL AX, 60 (SP) CMPQ R9,$256 JB BYTESBETWEEN1AND255 MOVOA 48(SP),X0 PSHUFL $0X55,X0,X1 PSHUFL $0XAA,X0,X2 PSHUFL $0XFF,X0,X3 PSHUFL $0X00,X0,X0 MOVOA X1,64(SP) MOVOA X2,80(SP) MOVOA X3,96(SP) MOVOA X0,112(SP) MOVOA 0(SP),X0 PSHUFL $0XAA,X0,X1 PSHUFL $0XFF,X0,X2 PSHUFL $0X00,X0,X3 PSHUFL $0X55,X0,X0 MOVOA X1,128(SP) MOVOA X2,144(SP) MOVOA X3,160(SP) MOVOA X0,176(SP) MOVOA 16(SP),X0 PSHUFL $0XFF,X0,X1 PSHUFL $0X55,X0,X2 PSHUFL $0XAA,X0,X0 MOVOA X1,192(SP) MOVOA X2,208(SP) MOVOA X0,224(SP) MOVOA 32(SP),X0 PSHUFL $0X00,X0,X1 PSHUFL $0XAA,X0,X2 PSHUFL $0XFF,X0,X0 MOVOA X1,240(SP) MOVOA X2,256(SP) MOVOA X0,272(SP) BYTESATLEAST256: MOVL 16(SP),DX MOVL 36 (SP),CX MOVL DX,288(SP) MOVL CX,304(SP) ADDQ $1,DX SHLQ $32,CX ADDQ CX,DX MOVQ DX,CX SHRQ $32,CX MOVL DX, 292 (SP) MOVL CX, 308 (SP) ADDQ $1,DX SHLQ $32,CX ADDQ CX,DX MOVQ DX,CX SHRQ $32,CX MOVL DX, 296 (SP) MOVL CX, 312 (SP) ADDQ $1,DX SHLQ $32,CX ADDQ CX,DX MOVQ DX,CX SHRQ $32,CX MOVL DX, 300 (SP) MOVL CX, 316 (SP) ADDQ $1,DX SHLQ $32,CX ADDQ CX,DX MOVQ DX,CX SHRQ $32,CX MOVL DX,16(SP) MOVL CX, 36 (SP) MOVQ R9,352(SP) MOVQ $20,DX MOVOA 64(SP),X0 MOVOA 80(SP),X1 MOVOA 96(SP),X2 MOVOA 256(SP),X3 MOVOA 272(SP),X4 MOVOA 128(SP),X5 MOVOA 144(SP),X6 MOVOA 176(SP),X7 MOVOA 192(SP),X8 MOVOA 208(SP),X9 MOVOA 224(SP),X10 MOVOA 304(SP),X11 MOVOA 112(SP),X12 MOVOA 160(SP),X13 MOVOA 240(SP),X14 MOVOA 288(SP),X15 MAINLOOP1: MOVOA X1,320(SP) MOVOA X2,336(SP) MOVOA X13,X1 PADDL X12,X1 MOVOA X1,X2 PSLLL $7,X1 PXOR X1,X14 PSRLL $25,X2 PXOR X2,X14 MOVOA X7,X1 PADDL X0,X1 MOVOA X1,X2 PSLLL $7,X1 PXOR X1,X11 PSRLL $25,X2 PXOR X2,X11 MOVOA X12,X1 PADDL X14,X1 MOVOA X1,X2 PSLLL $9,X1 PXOR X1,X15 PSRLL $23,X2 PXOR X2,X15 MOVOA X0,X1 PADDL X11,X1 MOVOA X1,X2 PSLLL $9,X1 PXOR X1,X9 PSRLL $23,X2 PXOR X2,X9 MOVOA X14,X1 PADDL X15,X1 MOVOA X1,X2 PSLLL $13,X1 PXOR X1,X13 PSRLL $19,X2 PXOR X2,X13 MOVOA X11,X1 PADDL X9,X1 MOVOA X1,X2 PSLLL $13,X1 PXOR X1,X7 PSRLL $19,X2 PXOR X2,X7 MOVOA X15,X1 PADDL X13,X1 MOVOA X1,X2 PSLLL $18,X1 PXOR X1,X12 PSRLL $14,X2 PXOR X2,X12 MOVOA 320(SP),X1 MOVOA X12,320(SP) MOVOA X9,X2 PADDL X7,X2 MOVOA X2,X12 PSLLL $18,X2 PXOR X2,X0 PSRLL $14,X12 PXOR X12,X0 MOVOA X5,X2 PADDL X1,X2 MOVOA X2,X12 PSLLL $7,X2 PXOR X2,X3 PSRLL $25,X12 PXOR X12,X3 MOVOA 336(SP),X2 MOVOA X0,336(SP) MOVOA X6,X0 PADDL X2,X0 MOVOA X0,X12 PSLLL $7,X0 PXOR X0,X4 PSRLL $25,X12 PXOR X12,X4 MOVOA X1,X0 PADDL X3,X0 MOVOA X0,X12 PSLLL $9,X0 PXOR X0,X10 PSRLL $23,X12 PXOR X12,X10 MOVOA X2,X0 PADDL X4,X0 MOVOA X0,X12 PSLLL $9,X0 PXOR X0,X8 PSRLL $23,X12 PXOR X12,X8 MOVOA X3,X0 PADDL X10,X0 MOVOA X0,X12 PSLLL $13,X0 PXOR X0,X5 PSRLL $19,X12 PXOR X12,X5 MOVOA X4,X0 PADDL X8,X0 MOVOA X0,X12 PSLLL $13,X0 PXOR X0,X6 PSRLL $19,X12 PXOR X12,X6 MOVOA X10,X0 PADDL X5,X0 MOVOA X0,X12 PSLLL $18,X0 PXOR X0,X1 PSRLL $14,X12 PXOR X12,X1 MOVOA 320(SP),X0 MOVOA X1,320(SP) MOVOA X4,X1 PADDL X0,X1 MOVOA X1,X12 PSLLL $7,X1 PXOR X1,X7 PSRLL $25,X12 PXOR X12,X7 MOVOA X8,X1 PADDL X6,X1 MOVOA X1,X12 PSLLL $18,X1 PXOR X1,X2 PSRLL $14,X12 PXOR X12,X2 MOVOA 336(SP),X12 MOVOA X2,336(SP) MOVOA X14,X1 PADDL X12,X1 MOVOA X1,X2 PSLLL $7,X1 PXOR X1,X5 PSRLL $25,X2 PXOR X2,X5 MOVOA X0,X1 PADDL X7,X1 MOVOA X1,X2 PSLLL $9,X1 PXOR X1,X10 PSRLL $23,X2 PXOR X2,X10 MOVOA X12,X1 PADDL X5,X1 MOVOA X1,X2 PSLLL $9,X1 PXOR X1,X8 PSRLL $23,X2 PXOR X2,X8 MOVOA X7,X1 PADDL X10,X1 MOVOA X1,X2 PSLLL $13,X1 PXOR X1,X4 PSRLL $19,X2 PXOR X2,X4 MOVOA X5,X1 PADDL X8,X1 MOVOA X1,X2 PSLLL $13,X1 PXOR X1,X14 PSRLL $19,X2 PXOR X2,X14 MOVOA X10,X1 PADDL X4,X1 MOVOA X1,X2 PSLLL $18,X1 PXOR X1,X0 PSRLL $14,X2 PXOR X2,X0 MOVOA 320(SP),X1 MOVOA X0,320(SP) MOVOA X8,X0 PADDL X14,X0 MOVOA X0,X2 PSLLL $18,X0 PXOR X0,X12 PSRLL $14,X2 PXOR X2,X12 MOVOA X11,X0 PADDL X1,X0 MOVOA X0,X2 PSLLL $7,X0 PXOR X0,X6 PSRLL $25,X2 PXOR X2,X6 MOVOA 336(SP),X2 MOVOA X12,336(SP) MOVOA X3,X0 PADDL X2,X0 MOVOA X0,X12 PSLLL $7,X0 PXOR X0,X13 PSRLL $25,X12 PXOR X12,X13 MOVOA X1,X0 PADDL X6,X0 MOVOA X0,X12 PSLLL $9,X0 PXOR X0,X15 PSRLL $23,X12 PXOR X12,X15 MOVOA X2,X0 PADDL X13,X0 MOVOA X0,X12 PSLLL $9,X0 PXOR X0,X9 PSRLL $23,X12 PXOR X12,X9 MOVOA X6,X0 PADDL X15,X0 MOVOA X0,X12 PSLLL $13,X0 PXOR X0,X11 PSRLL $19,X12 PXOR X12,X11 MOVOA X13,X0 PADDL X9,X0 MOVOA X0,X12 PSLLL $13,X0 PXOR X0,X3 PSRLL $19,X12 PXOR X12,X3 MOVOA X15,X0 PADDL X11,X0 MOVOA X0,X12 PSLLL $18,X0 PXOR X0,X1 PSRLL $14,X12 PXOR X12,X1 MOVOA X9,X0 PADDL X3,X0 MOVOA X0,X12 PSLLL $18,X0 PXOR X0,X2 PSRLL $14,X12 PXOR X12,X2 MOVOA 320(SP),X12 MOVOA 336(SP),X0 SUBQ $2,DX JA MAINLOOP1 PADDL 112(SP),X12 PADDL 176(SP),X7 PADDL 224(SP),X10 PADDL 272(SP),X4 MOVD X12,DX MOVD X7,CX MOVD X10,R8 MOVD X4,R9 PSHUFL $0X39,X12,X12 PSHUFL $0X39,X7,X7 PSHUFL $0X39,X10,X10 PSHUFL $0X39,X4,X4 XORL 0(SI),DX XORL 4(SI),CX XORL 8(SI),R8 XORL 12(SI),R9 MOVL DX,0(DI) MOVL CX,4(DI) MOVL R8,8(DI) MOVL R9,12(DI) MOVD X12,DX MOVD X7,CX MOVD X10,R8 MOVD X4,R9 PSHUFL $0X39,X12,X12 PSHUFL $0X39,X7,X7 PSHUFL $0X39,X10,X10 PSHUFL $0X39,X4,X4 XORL 64(SI),DX XORL 68(SI),CX XORL 72(SI),R8 XORL 76(SI),R9 MOVL DX,64(DI) MOVL CX,68(DI) MOVL R8,72(DI) MOVL R9,76(DI) MOVD X12,DX MOVD X7,CX MOVD X10,R8 MOVD X4,R9 PSHUFL $0X39,X12,X12 PSHUFL $0X39,X7,X7 PSHUFL $0X39,X10,X10 PSHUFL $0X39,X4,X4 XORL 128(SI),DX XORL 132(SI),CX XORL 136(SI),R8 XORL 140(SI),R9 MOVL DX,128(DI) MOVL CX,132(DI) MOVL R8,136(DI) MOVL R9,140(DI) MOVD X12,DX MOVD X7,CX MOVD X10,R8 MOVD X4,R9 XORL 192(SI),DX XORL 196(SI),CX XORL 200(SI),R8 XORL 204(SI),R9 MOVL DX,192(DI) MOVL CX,196(DI) MOVL R8,200(DI) MOVL R9,204(DI) PADDL 240(SP),X14 PADDL 64(SP),X0 PADDL 128(SP),X5 PADDL 192(SP),X8 MOVD X14,DX MOVD X0,CX MOVD X5,R8 MOVD X8,R9 PSHUFL $0X39,X14,X14 PSHUFL $0X39,X0,X0 PSHUFL $0X39,X5,X5 PSHUFL $0X39,X8,X8 XORL 16(SI),DX XORL 20(SI),CX XORL 24(SI),R8 XORL 28(SI),R9 MOVL DX,16(DI) MOVL CX,20(DI) MOVL R8,24(DI) MOVL R9,28(DI) MOVD X14,DX MOVD X0,CX MOVD X5,R8 MOVD X8,R9 PSHUFL $0X39,X14,X14 PSHUFL $0X39,X0,X0 PSHUFL $0X39,X5,X5 PSHUFL $0X39,X8,X8 XORL 80(SI),DX XORL 84(SI),CX XORL 88(SI),R8 XORL 92(SI),R9 MOVL DX,80(DI) MOVL CX,84(DI) MOVL R8,88(DI) MOVL R9,92(DI) MOVD X14,DX MOVD X0,CX MOVD X5,R8 MOVD X8,R9 PSHUFL $0X39,X14,X14 PSHUFL $0X39,X0,X0 PSHUFL $0X39,X5,X5 PSHUFL $0X39,X8,X8 XORL 144(SI),DX XORL 148(SI),CX XORL 152(SI),R8 XORL 156(SI),R9 MOVL DX,144(DI) MOVL CX,148(DI) MOVL R8,152(DI) MOVL R9,156(DI) MOVD X14,DX MOVD X0,CX MOVD X5,R8 MOVD X8,R9 XORL 208(SI),DX XORL 212(SI),CX XORL 216(SI),R8 XORL 220(SI),R9 MOVL DX,208(DI) MOVL CX,212(DI) MOVL R8,216(DI) MOVL R9,220(DI) PADDL 288(SP),X15 PADDL 304(SP),X11 PADDL 80(SP),X1 PADDL 144(SP),X6 MOVD X15,DX MOVD X11,CX MOVD X1,R8 MOVD X6,R9 PSHUFL $0X39,X15,X15 PSHUFL $0X39,X11,X11 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X6,X6 XORL 32(SI),DX XORL 36(SI),CX XORL 40(SI),R8 XORL 44(SI),R9 MOVL DX,32(DI) MOVL CX,36(DI) MOVL R8,40(DI) MOVL R9,44(DI) MOVD X15,DX MOVD X11,CX MOVD X1,R8 MOVD X6,R9 PSHUFL $0X39,X15,X15 PSHUFL $0X39,X11,X11 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X6,X6 XORL 96(SI),DX XORL 100(SI),CX XORL 104(SI),R8 XORL 108(SI),R9 MOVL DX,96(DI) MOVL CX,100(DI) MOVL R8,104(DI) MOVL R9,108(DI) MOVD X15,DX MOVD X11,CX MOVD X1,R8 MOVD X6,R9 PSHUFL $0X39,X15,X15 PSHUFL $0X39,X11,X11 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X6,X6 XORL 160(SI),DX XORL 164(SI),CX XORL 168(SI),R8 XORL 172(SI),R9 MOVL DX,160(DI) MOVL CX,164(DI) MOVL R8,168(DI) MOVL R9,172(DI) MOVD X15,DX MOVD X11,CX MOVD X1,R8 MOVD X6,R9 XORL 224(SI),DX XORL 228(SI),CX XORL 232(SI),R8 XORL 236(SI),R9 MOVL DX,224(DI) MOVL CX,228(DI) MOVL R8,232(DI) MOVL R9,236(DI) PADDL 160(SP),X13 PADDL 208(SP),X9 PADDL 256(SP),X3 PADDL 96(SP),X2 MOVD X13,DX MOVD X9,CX MOVD X3,R8 MOVD X2,R9 PSHUFL $0X39,X13,X13 PSHUFL $0X39,X9,X9 PSHUFL $0X39,X3,X3 PSHUFL $0X39,X2,X2 XORL 48(SI),DX XORL 52(SI),CX XORL 56(SI),R8 XORL 60(SI),R9 MOVL DX,48(DI) MOVL CX,52(DI) MOVL R8,56(DI) MOVL R9,60(DI) MOVD X13,DX MOVD X9,CX MOVD X3,R8 MOVD X2,R9 PSHUFL $0X39,X13,X13 PSHUFL $0X39,X9,X9 PSHUFL $0X39,X3,X3 PSHUFL $0X39,X2,X2 XORL 112(SI),DX XORL 116(SI),CX XORL 120(SI),R8 XORL 124(SI),R9 MOVL DX,112(DI) MOVL CX,116(DI) MOVL R8,120(DI) MOVL R9,124(DI) MOVD X13,DX MOVD X9,CX MOVD X3,R8 MOVD X2,R9 PSHUFL $0X39,X13,X13 PSHUFL $0X39,X9,X9 PSHUFL $0X39,X3,X3 PSHUFL $0X39,X2,X2 XORL 176(SI),DX XORL 180(SI),CX XORL 184(SI),R8 XORL 188(SI),R9 MOVL DX,176(DI) MOVL CX,180(DI) MOVL R8,184(DI) MOVL R9,188(DI) MOVD X13,DX MOVD X9,CX MOVD X3,R8 MOVD X2,R9 XORL 240(SI),DX XORL 244(SI),CX XORL 248(SI),R8 XORL 252(SI),R9 MOVL DX,240(DI) MOVL CX,244(DI) MOVL R8,248(DI) MOVL R9,252(DI) MOVQ 352(SP),R9 SUBQ $256,R9 ADDQ $256,SI ADDQ $256,DI CMPQ R9,$256 JAE BYTESATLEAST256 CMPQ R9,$0 JBE DONE BYTESBETWEEN1AND255: CMPQ R9,$64 JAE NOCOPY MOVQ DI,DX LEAQ 360(SP),DI MOVQ R9,CX REP; MOVSB LEAQ 360(SP),DI LEAQ 360(SP),SI NOCOPY: MOVQ R9,352(SP) MOVOA 48(SP),X0 MOVOA 0(SP),X1 MOVOA 16(SP),X2 MOVOA 32(SP),X3 MOVOA X1,X4 MOVQ $20,CX MAINLOOP2: PADDL X0,X4 MOVOA X0,X5 MOVOA X4,X6 PSLLL $7,X4 PSRLL $25,X6 PXOR X4,X3 PXOR X6,X3 PADDL X3,X5 MOVOA X3,X4 MOVOA X5,X6 PSLLL $9,X5 PSRLL $23,X6 PXOR X5,X2 PSHUFL $0X93,X3,X3 PXOR X6,X2 PADDL X2,X4 MOVOA X2,X5 MOVOA X4,X6 PSLLL $13,X4 PSRLL $19,X6 PXOR X4,X1 PSHUFL $0X4E,X2,X2 PXOR X6,X1 PADDL X1,X5 MOVOA X3,X4 MOVOA X5,X6 PSLLL $18,X5 PSRLL $14,X6 PXOR X5,X0 PSHUFL $0X39,X1,X1 PXOR X6,X0 PADDL X0,X4 MOVOA X0,X5 MOVOA X4,X6 PSLLL $7,X4 PSRLL $25,X6 PXOR X4,X1 PXOR X6,X1 PADDL X1,X5 MOVOA X1,X4 MOVOA X5,X6 PSLLL $9,X5 PSRLL $23,X6 PXOR X5,X2 PSHUFL $0X93,X1,X1 PXOR X6,X2 PADDL X2,X4 MOVOA X2,X5 MOVOA X4,X6 PSLLL $13,X4 PSRLL $19,X6 PXOR X4,X3 PSHUFL $0X4E,X2,X2 PXOR X6,X3 PADDL X3,X5 MOVOA X1,X4 MOVOA X5,X6 PSLLL $18,X5 PSRLL $14,X6 PXOR X5,X0 PSHUFL $0X39,X3,X3 PXOR X6,X0 PADDL X0,X4 MOVOA X0,X5 MOVOA X4,X6 PSLLL $7,X4 PSRLL $25,X6 PXOR X4,X3 PXOR X6,X3 PADDL X3,X5 MOVOA X3,X4 MOVOA X5,X6 PSLLL $9,X5 PSRLL $23,X6 PXOR X5,X2 PSHUFL $0X93,X3,X3 PXOR X6,X2 PADDL X2,X4 MOVOA X2,X5 MOVOA X4,X6 PSLLL $13,X4 PSRLL $19,X6 PXOR X4,X1 PSHUFL $0X4E,X2,X2 PXOR X6,X1 PADDL X1,X5 MOVOA X3,X4 MOVOA X5,X6 PSLLL $18,X5 PSRLL $14,X6 PXOR X5,X0 PSHUFL $0X39,X1,X1 PXOR X6,X0 PADDL X0,X4 MOVOA X0,X5 MOVOA X4,X6 PSLLL $7,X4 PSRLL $25,X6 PXOR X4,X1 PXOR X6,X1 PADDL X1,X5 MOVOA X1,X4 MOVOA X5,X6 PSLLL $9,X5 PSRLL $23,X6 PXOR X5,X2 PSHUFL $0X93,X1,X1 PXOR X6,X2 PADDL X2,X4 MOVOA X2,X5 MOVOA X4,X6 PSLLL $13,X4 PSRLL $19,X6 PXOR X4,X3 PSHUFL $0X4E,X2,X2 PXOR X6,X3 SUBQ $4,CX PADDL X3,X5 MOVOA X1,X4 MOVOA X5,X6 PSLLL $18,X5 PXOR X7,X7 PSRLL $14,X6 PXOR X5,X0 PSHUFL $0X39,X3,X3 PXOR X6,X0 JA MAINLOOP2 PADDL 48(SP),X0 PADDL 0(SP),X1 PADDL 16(SP),X2 PADDL 32(SP),X3 MOVD X0,CX MOVD X1,R8 MOVD X2,R9 MOVD X3,AX PSHUFL $0X39,X0,X0 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X2,X2 PSHUFL $0X39,X3,X3 XORL 0(SI),CX XORL 48(SI),R8 XORL 32(SI),R9 XORL 16(SI),AX MOVL CX,0(DI) MOVL R8,48(DI) MOVL R9,32(DI) MOVL AX,16(DI) MOVD X0,CX MOVD X1,R8 MOVD X2,R9 MOVD X3,AX PSHUFL $0X39,X0,X0 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X2,X2 PSHUFL $0X39,X3,X3 XORL 20(SI),CX XORL 4(SI),R8 XORL 52(SI),R9 XORL 36(SI),AX MOVL CX,20(DI) MOVL R8,4(DI) MOVL R9,52(DI) MOVL AX,36(DI) MOVD X0,CX MOVD X1,R8 MOVD X2,R9 MOVD X3,AX PSHUFL $0X39,X0,X0 PSHUFL $0X39,X1,X1 PSHUFL $0X39,X2,X2 PSHUFL $0X39,X3,X3 XORL 40(SI),CX XORL 24(SI),R8 XORL 8(SI),R9 XORL 56(SI),AX MOVL CX,40(DI) MOVL R8,24(DI) MOVL R9,8(DI) MOVL AX,56(DI) MOVD X0,CX MOVD X1,R8 MOVD X2,R9 MOVD X3,AX XORL 60(SI),CX XORL 44(SI),R8 XORL 28(SI),R9 XORL 12(SI),AX MOVL CX,60(DI) MOVL R8,44(DI) MOVL R9,28(DI) MOVL AX,12(DI) MOVQ 352(SP),R9 MOVL 16(SP),CX MOVL 36 (SP),R8 ADDQ $1,CX SHLQ $32,R8 ADDQ R8,CX MOVQ CX,R8 SHRQ $32,R8 MOVL CX,16(SP) MOVL R8, 36 (SP) CMPQ R9,$64 JA BYTESATLEAST65 JAE BYTESATLEAST64 MOVQ DI,SI MOVQ DX,DI MOVQ R9,CX REP; MOVSB BYTESATLEAST64: DONE: MOVQ R12,SP RET BYTESATLEAST65: SUBQ $64,R9 ADDQ $64,DI ADDQ $64,SI JMP BYTESBETWEEN1AND255 �������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/salsa20/salsa/hsalsa20.go�����������������������������������0000644�0610621�0607500�00000010002�13172163317�025357� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package salsa provides low-level access to functions in the Salsa family. package salsa // import "golang.org/x/crypto/salsa20/salsa" // Sigma is the Salsa20 constant for 256-bit keys. var Sigma = [16]byte{'e', 'x', 'p', 'a', 'n', 'd', ' ', '3', '2', '-', 'b', 'y', 't', 'e', ' ', 'k'} // HSalsa20 applies the HSalsa20 core function to a 16-byte input in, 32-byte // key k, and 16-byte constant c, and puts the result into the 32-byte array // out. func HSalsa20(out *[32]byte, in *[16]byte, k *[32]byte, c *[16]byte) { x0 := uint32(c[0]) | uint32(c[1])<<8 | uint32(c[2])<<16 | uint32(c[3])<<24 x1 := uint32(k[0]) | uint32(k[1])<<8 | uint32(k[2])<<16 | uint32(k[3])<<24 x2 := uint32(k[4]) | uint32(k[5])<<8 | uint32(k[6])<<16 | uint32(k[7])<<24 x3 := uint32(k[8]) | uint32(k[9])<<8 | uint32(k[10])<<16 | uint32(k[11])<<24 x4 := uint32(k[12]) | uint32(k[13])<<8 | uint32(k[14])<<16 | uint32(k[15])<<24 x5 := uint32(c[4]) | uint32(c[5])<<8 | uint32(c[6])<<16 | uint32(c[7])<<24 x6 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24 x7 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24 x8 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24 x9 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24 x10 := uint32(c[8]) | uint32(c[9])<<8 | uint32(c[10])<<16 | uint32(c[11])<<24 x11 := uint32(k[16]) | uint32(k[17])<<8 | uint32(k[18])<<16 | uint32(k[19])<<24 x12 := uint32(k[20]) | uint32(k[21])<<8 | uint32(k[22])<<16 | uint32(k[23])<<24 x13 := uint32(k[24]) | uint32(k[25])<<8 | uint32(k[26])<<16 | uint32(k[27])<<24 x14 := uint32(k[28]) | uint32(k[29])<<8 | uint32(k[30])<<16 | uint32(k[31])<<24 x15 := uint32(c[12]) | uint32(c[13])<<8 | uint32(c[14])<<16 | uint32(c[15])<<24 for i := 0; i < 20; i += 2 { u := x0 + x12 x4 ^= u<<7 | u>>(32-7) u = x4 + x0 x8 ^= u<<9 | u>>(32-9) u = x8 + x4 x12 ^= u<<13 | u>>(32-13) u = x12 + x8 x0 ^= u<<18 | u>>(32-18) u = x5 + x1 x9 ^= u<<7 | u>>(32-7) u = x9 + x5 x13 ^= u<<9 | u>>(32-9) u = x13 + x9 x1 ^= u<<13 | u>>(32-13) u = x1 + x13 x5 ^= u<<18 | u>>(32-18) u = x10 + x6 x14 ^= u<<7 | u>>(32-7) u = x14 + x10 x2 ^= u<<9 | u>>(32-9) u = x2 + x14 x6 ^= u<<13 | u>>(32-13) u = x6 + x2 x10 ^= u<<18 | u>>(32-18) u = x15 + x11 x3 ^= u<<7 | u>>(32-7) u = x3 + x15 x7 ^= u<<9 | u>>(32-9) u = x7 + x3 x11 ^= u<<13 | u>>(32-13) u = x11 + x7 x15 ^= u<<18 | u>>(32-18) u = x0 + x3 x1 ^= u<<7 | u>>(32-7) u = x1 + x0 x2 ^= u<<9 | u>>(32-9) u = x2 + x1 x3 ^= u<<13 | u>>(32-13) u = x3 + x2 x0 ^= u<<18 | u>>(32-18) u = x5 + x4 x6 ^= u<<7 | u>>(32-7) u = x6 + x5 x7 ^= u<<9 | u>>(32-9) u = x7 + x6 x4 ^= u<<13 | u>>(32-13) u = x4 + x7 x5 ^= u<<18 | u>>(32-18) u = x10 + x9 x11 ^= u<<7 | u>>(32-7) u = x11 + x10 x8 ^= u<<9 | u>>(32-9) u = x8 + x11 x9 ^= u<<13 | u>>(32-13) u = x9 + x8 x10 ^= u<<18 | u>>(32-18) u = x15 + x14 x12 ^= u<<7 | u>>(32-7) u = x12 + x15 x13 ^= u<<9 | u>>(32-9) u = x13 + x12 x14 ^= u<<13 | u>>(32-13) u = x14 + x13 x15 ^= u<<18 | u>>(32-18) } out[0] = byte(x0) out[1] = byte(x0 >> 8) out[2] = byte(x0 >> 16) out[3] = byte(x0 >> 24) out[4] = byte(x5) out[5] = byte(x5 >> 8) out[6] = byte(x5 >> 16) out[7] = byte(x5 >> 24) out[8] = byte(x10) out[9] = byte(x10 >> 8) out[10] = byte(x10 >> 16) out[11] = byte(x10 >> 24) out[12] = byte(x15) out[13] = byte(x15 >> 8) out[14] = byte(x15 >> 16) out[15] = byte(x15 >> 24) out[16] = byte(x6) out[17] = byte(x6 >> 8) out[18] = byte(x6 >> 16) out[19] = byte(x6 >> 24) out[20] = byte(x7) out[21] = byte(x7 >> 8) out[22] = byte(x7 >> 16) out[23] = byte(x7 >> 24) out[24] = byte(x8) out[25] = byte(x8 >> 8) out[26] = byte(x8 >> 16) out[27] = byte(x8 >> 24) out[28] = byte(x9) out[29] = byte(x9 >> 8) out[30] = byte(x9 >> 16) out[31] = byte(x9 >> 24) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ripemd160/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022561� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ripemd160/ripemd160block.go���������������������������������0000644�0610621�0607500�00000010241�13172163317�025630� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // RIPEMD-160 block step. // In its own file so that a faster assembly or C version // can be substituted easily. package ripemd160 // work buffer indices and roll amounts for one line var _n = [80]uint{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, } var _r = [80]uint{ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, } // same for the other parallel one var n_ = [80]uint{ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11, } var r_ = [80]uint{ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11, } func _Block(md *digest, p []byte) int { n := 0 var x [16]uint32 var alpha, beta uint32 for len(p) >= BlockSize { a, b, c, d, e := md.s[0], md.s[1], md.s[2], md.s[3], md.s[4] aa, bb, cc, dd, ee := a, b, c, d, e j := 0 for i := 0; i < 16; i++ { x[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24 j += 4 } // round 1 i := 0 for i < 16 { alpha = a + (b ^ c ^ d) + x[_n[i]] s := _r[i] alpha = (alpha<<s | alpha>>(32-s)) + e beta = c<<10 | c>>22 a, b, c, d, e = e, alpha, b, beta, d // parallel line alpha = aa + (bb ^ (cc | ^dd)) + x[n_[i]] + 0x50a28be6 s = r_[i] alpha = (alpha<<s | alpha>>(32-s)) + ee beta = cc<<10 | cc>>22 aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd i++ } // round 2 for i < 32 { alpha = a + (b&c | ^b&d) + x[_n[i]] + 0x5a827999 s := _r[i] alpha = (alpha<<s | alpha>>(32-s)) + e beta = c<<10 | c>>22 a, b, c, d, e = e, alpha, b, beta, d // parallel line alpha = aa + (bb&dd | cc&^dd) + x[n_[i]] + 0x5c4dd124 s = r_[i] alpha = (alpha<<s | alpha>>(32-s)) + ee beta = cc<<10 | cc>>22 aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd i++ } // round 3 for i < 48 { alpha = a + (b | ^c ^ d) + x[_n[i]] + 0x6ed9eba1 s := _r[i] alpha = (alpha<<s | alpha>>(32-s)) + e beta = c<<10 | c>>22 a, b, c, d, e = e, alpha, b, beta, d // parallel line alpha = aa + (bb | ^cc ^ dd) + x[n_[i]] + 0x6d703ef3 s = r_[i] alpha = (alpha<<s | alpha>>(32-s)) + ee beta = cc<<10 | cc>>22 aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd i++ } // round 4 for i < 64 { alpha = a + (b&d | c&^d) + x[_n[i]] + 0x8f1bbcdc s := _r[i] alpha = (alpha<<s | alpha>>(32-s)) + e beta = c<<10 | c>>22 a, b, c, d, e = e, alpha, b, beta, d // parallel line alpha = aa + (bb&cc | ^bb&dd) + x[n_[i]] + 0x7a6d76e9 s = r_[i] alpha = (alpha<<s | alpha>>(32-s)) + ee beta = cc<<10 | cc>>22 aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd i++ } // round 5 for i < 80 { alpha = a + (b ^ (c | ^d)) + x[_n[i]] + 0xa953fd4e s := _r[i] alpha = (alpha<<s | alpha>>(32-s)) + e beta = c<<10 | c>>22 a, b, c, d, e = e, alpha, b, beta, d // parallel line alpha = aa + (bb ^ cc ^ dd) + x[n_[i]] s = r_[i] alpha = (alpha<<s | alpha>>(32-s)) + ee beta = cc<<10 | cc>>22 aa, bb, cc, dd, ee = ee, alpha, bb, beta, dd i++ } // combine results dd += c + md.s[1] md.s[1] = md.s[2] + d + ee md.s[2] = md.s[3] + e + aa md.s[3] = md.s[4] + a + bb md.s[4] = md.s[0] + b + cc md.s[0] = dd p = p[BlockSize:] n += BlockSize } return n } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ripemd160/ripemd160_test.go���������������������������������0000644�0610621�0607500�00000003377�13172163317�025670� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ripemd160 // Test vectors are from: // http://homes.esat.kuleuven.be/~bosselae/ripemd160.html import ( "fmt" "io" "testing" ) type mdTest struct { out string in string } var vectors = [...]mdTest{ {"9c1185a5c5e9fc54612808977ee8f548b2258d31", ""}, {"0bdc9d2d256b3ee9daae347be6f4dc835a467ffe", "a"}, {"8eb208f7e05d987a9b044a8e98c6b087f15a0bfc", "abc"}, {"5d0689ef49d2fae572b881b123a85ffa21595f36", "message digest"}, {"f71c27109c692c1b56bbdceb5b9d2865b3708dbc", "abcdefghijklmnopqrstuvwxyz"}, {"12a053384a9c0c88e405a06c27dcf49ada62eb2b", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"}, {"b0e20b6e3116640286ed3a87a5713079b21f5189", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"9b752e45573d4b39f4dbd3323cab82bf63326bfb", "12345678901234567890123456789012345678901234567890123456789012345678901234567890"}, } func TestVectors(t *testing.T) { for i := 0; i < len(vectors); i++ { tv := vectors[i] md := New() for j := 0; j < 3; j++ { if j < 2 { io.WriteString(md, tv.in) } else { io.WriteString(md, tv.in[0:len(tv.in)/2]) md.Sum(nil) io.WriteString(md, tv.in[len(tv.in)/2:]) } s := fmt.Sprintf("%x", md.Sum(nil)) if s != tv.out { t.Fatalf("RIPEMD-160[%d](%s) = %s, expected %s", j, tv.in, s, tv.out) } md.Reset() } } } func TestMillionA(t *testing.T) { md := New() for i := 0; i < 100000; i++ { io.WriteString(md, "aaaaaaaaaa") } out := "52783243c1697bdbe16d37f97f68f08325dc1528" s := fmt.Sprintf("%x", md.Sum(nil)) if s != out { t.Fatalf("RIPEMD-160 (1 million 'a') = %s, expected %s", s, out) } md.Reset() } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ripemd160/ripemd160.go��������������������������������������0000644�0610621�0607500�00000004654�13172163317�024630� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ripemd160 implements the RIPEMD-160 hash algorithm. package ripemd160 // import "golang.org/x/crypto/ripemd160" // RIPEMD-160 is designed by by Hans Dobbertin, Antoon Bosselaers, and Bart // Preneel with specifications available at: // http://homes.esat.kuleuven.be/~cosicart/pdf/AB-9601/AB-9601.pdf. import ( "crypto" "hash" ) func init() { crypto.RegisterHash(crypto.RIPEMD160, New) } // The size of the checksum in bytes. const Size = 20 // The block size of the hash algorithm in bytes. const BlockSize = 64 const ( _s0 = 0x67452301 _s1 = 0xefcdab89 _s2 = 0x98badcfe _s3 = 0x10325476 _s4 = 0xc3d2e1f0 ) // digest represents the partial evaluation of a checksum. type digest struct { s [5]uint32 // running context x [BlockSize]byte // temporary buffer nx int // index into x tc uint64 // total count of bytes processed } func (d *digest) Reset() { d.s[0], d.s[1], d.s[2], d.s[3], d.s[4] = _s0, _s1, _s2, _s3, _s4 d.nx = 0 d.tc = 0 } // New returns a new hash.Hash computing the checksum. func New() hash.Hash { result := new(digest) result.Reset() return result } func (d *digest) Size() int { return Size } func (d *digest) BlockSize() int { return BlockSize } func (d *digest) Write(p []byte) (nn int, err error) { nn = len(p) d.tc += uint64(nn) if d.nx > 0 { n := len(p) if n > BlockSize-d.nx { n = BlockSize - d.nx } for i := 0; i < n; i++ { d.x[d.nx+i] = p[i] } d.nx += n if d.nx == BlockSize { _Block(d, d.x[0:]) d.nx = 0 } p = p[n:] } n := _Block(d, p) p = p[n:] if len(p) > 0 { d.nx = copy(d.x[:], p) } return } func (d0 *digest) Sum(in []byte) []byte { // Make a copy of d0 so that caller can keep writing and summing. d := *d0 // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64. tc := d.tc var tmp [64]byte tmp[0] = 0x80 if tc%64 < 56 { d.Write(tmp[0 : 56-tc%64]) } else { d.Write(tmp[0 : 64+56-tc%64]) } // Length in bits. tc <<= 3 for i := uint(0); i < 8; i++ { tmp[i] = byte(tc >> (8 * i)) } d.Write(tmp[0:8]) if d.nx != 0 { panic("d.nx != 0") } var digest [Size]byte for i, s := range d.s { digest[i*4] = byte(s) digest[i*4+1] = byte(s >> 8) digest[i*4+2] = byte(s >> 16) digest[i*4+3] = byte(s >> 24) } return append(in, digest[:]...) } ������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/poly1305/���������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022346� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/poly1305/sum_ref.go�����������������������������������������0000644�0610621�0607500�00000011333�13172163317�024336� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !amd64,!arm gccgo appengine nacl package poly1305 import "encoding/binary" // Sum generates an authenticator for msg using a one-time key and puts the // 16-byte result into out. Authenticating two different messages with the same // key allows an attacker to forge messages at will. func Sum(out *[TagSize]byte, msg []byte, key *[32]byte) { var ( h0, h1, h2, h3, h4 uint32 // the hash accumulators r0, r1, r2, r3, r4 uint64 // the r part of the key ) r0 = uint64(binary.LittleEndian.Uint32(key[0:]) & 0x3ffffff) r1 = uint64((binary.LittleEndian.Uint32(key[3:]) >> 2) & 0x3ffff03) r2 = uint64((binary.LittleEndian.Uint32(key[6:]) >> 4) & 0x3ffc0ff) r3 = uint64((binary.LittleEndian.Uint32(key[9:]) >> 6) & 0x3f03fff) r4 = uint64((binary.LittleEndian.Uint32(key[12:]) >> 8) & 0x00fffff) R1, R2, R3, R4 := r1*5, r2*5, r3*5, r4*5 for len(msg) >= TagSize { // h += msg h0 += binary.LittleEndian.Uint32(msg[0:]) & 0x3ffffff h1 += (binary.LittleEndian.Uint32(msg[3:]) >> 2) & 0x3ffffff h2 += (binary.LittleEndian.Uint32(msg[6:]) >> 4) & 0x3ffffff h3 += (binary.LittleEndian.Uint32(msg[9:]) >> 6) & 0x3ffffff h4 += (binary.LittleEndian.Uint32(msg[12:]) >> 8) | (1 << 24) // h *= r d0 := (uint64(h0) * r0) + (uint64(h1) * R4) + (uint64(h2) * R3) + (uint64(h3) * R2) + (uint64(h4) * R1) d1 := (d0 >> 26) + (uint64(h0) * r1) + (uint64(h1) * r0) + (uint64(h2) * R4) + (uint64(h3) * R3) + (uint64(h4) * R2) d2 := (d1 >> 26) + (uint64(h0) * r2) + (uint64(h1) * r1) + (uint64(h2) * r0) + (uint64(h3) * R4) + (uint64(h4) * R3) d3 := (d2 >> 26) + (uint64(h0) * r3) + (uint64(h1) * r2) + (uint64(h2) * r1) + (uint64(h3) * r0) + (uint64(h4) * R4) d4 := (d3 >> 26) + (uint64(h0) * r4) + (uint64(h1) * r3) + (uint64(h2) * r2) + (uint64(h3) * r1) + (uint64(h4) * r0) // h %= p h0 = uint32(d0) & 0x3ffffff h1 = uint32(d1) & 0x3ffffff h2 = uint32(d2) & 0x3ffffff h3 = uint32(d3) & 0x3ffffff h4 = uint32(d4) & 0x3ffffff h0 += uint32(d4>>26) * 5 h1 += h0 >> 26 h0 = h0 & 0x3ffffff msg = msg[TagSize:] } if len(msg) > 0 { var block [TagSize]byte off := copy(block[:], msg) block[off] = 0x01 // h += msg h0 += binary.LittleEndian.Uint32(block[0:]) & 0x3ffffff h1 += (binary.LittleEndian.Uint32(block[3:]) >> 2) & 0x3ffffff h2 += (binary.LittleEndian.Uint32(block[6:]) >> 4) & 0x3ffffff h3 += (binary.LittleEndian.Uint32(block[9:]) >> 6) & 0x3ffffff h4 += (binary.LittleEndian.Uint32(block[12:]) >> 8) // h *= r d0 := (uint64(h0) * r0) + (uint64(h1) * R4) + (uint64(h2) * R3) + (uint64(h3) * R2) + (uint64(h4) * R1) d1 := (d0 >> 26) + (uint64(h0) * r1) + (uint64(h1) * r0) + (uint64(h2) * R4) + (uint64(h3) * R3) + (uint64(h4) * R2) d2 := (d1 >> 26) + (uint64(h0) * r2) + (uint64(h1) * r1) + (uint64(h2) * r0) + (uint64(h3) * R4) + (uint64(h4) * R3) d3 := (d2 >> 26) + (uint64(h0) * r3) + (uint64(h1) * r2) + (uint64(h2) * r1) + (uint64(h3) * r0) + (uint64(h4) * R4) d4 := (d3 >> 26) + (uint64(h0) * r4) + (uint64(h1) * r3) + (uint64(h2) * r2) + (uint64(h3) * r1) + (uint64(h4) * r0) // h %= p h0 = uint32(d0) & 0x3ffffff h1 = uint32(d1) & 0x3ffffff h2 = uint32(d2) & 0x3ffffff h3 = uint32(d3) & 0x3ffffff h4 = uint32(d4) & 0x3ffffff h0 += uint32(d4>>26) * 5 h1 += h0 >> 26 h0 = h0 & 0x3ffffff } // h %= p reduction h2 += h1 >> 26 h1 &= 0x3ffffff h3 += h2 >> 26 h2 &= 0x3ffffff h4 += h3 >> 26 h3 &= 0x3ffffff h0 += 5 * (h4 >> 26) h4 &= 0x3ffffff h1 += h0 >> 26 h0 &= 0x3ffffff // h - p t0 := h0 + 5 t1 := h1 + (t0 >> 26) t2 := h2 + (t1 >> 26) t3 := h3 + (t2 >> 26) t4 := h4 + (t3 >> 26) - (1 << 26) t0 &= 0x3ffffff t1 &= 0x3ffffff t2 &= 0x3ffffff t3 &= 0x3ffffff // select h if h < p else h - p t_mask := (t4 >> 31) - 1 h_mask := ^t_mask h0 = (h0 & h_mask) | (t0 & t_mask) h1 = (h1 & h_mask) | (t1 & t_mask) h2 = (h2 & h_mask) | (t2 & t_mask) h3 = (h3 & h_mask) | (t3 & t_mask) h4 = (h4 & h_mask) | (t4 & t_mask) // h %= 2^128 h0 |= h1 << 26 h1 = ((h1 >> 6) | (h2 << 20)) h2 = ((h2 >> 12) | (h3 << 14)) h3 = ((h3 >> 18) | (h4 << 8)) // s: the s part of the key // tag = (h + s) % (2^128) t := uint64(h0) + uint64(binary.LittleEndian.Uint32(key[16:])) h0 = uint32(t) t = uint64(h1) + uint64(binary.LittleEndian.Uint32(key[20:])) + (t >> 32) h1 = uint32(t) t = uint64(h2) + uint64(binary.LittleEndian.Uint32(key[24:])) + (t >> 32) h2 = uint32(t) t = uint64(h3) + uint64(binary.LittleEndian.Uint32(key[28:])) + (t >> 32) h3 = uint32(t) binary.LittleEndian.PutUint32(out[0:], h0) binary.LittleEndian.PutUint32(out[4:], h1) binary.LittleEndian.PutUint32(out[8:], h2) binary.LittleEndian.PutUint32(out[12:], h3) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/poly1305/sum_arm.s������������������������������������������0000644�0610621�0607500�00000027122�13172163317�024201� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm,!gccgo,!appengine,!nacl #include "textflag.h" // This code was translated into a form compatible with 5a from the public // domain source by Andrew Moon: github.com/floodyberry/poly1305-opt/blob/master/app/extensions/poly1305. DATA ·poly1305_init_constants_armv6<>+0x00(SB)/4, $0x3ffffff DATA ·poly1305_init_constants_armv6<>+0x04(SB)/4, $0x3ffff03 DATA ·poly1305_init_constants_armv6<>+0x08(SB)/4, $0x3ffc0ff DATA ·poly1305_init_constants_armv6<>+0x0c(SB)/4, $0x3f03fff DATA ·poly1305_init_constants_armv6<>+0x10(SB)/4, $0x00fffff GLOBL ·poly1305_init_constants_armv6<>(SB), 8, $20 // Warning: the linker may use R11 to synthesize certain instructions. Please // take care and verify that no synthetic instructions use it. TEXT poly1305_init_ext_armv6<>(SB), NOSPLIT, $0 // Needs 16 bytes of stack and 64 bytes of space pointed to by R0. (It // might look like it's only 60 bytes of space but the final four bytes // will be written by another function.) We need to skip over four // bytes of stack because that's saving the value of 'g'. ADD $4, R13, R8 MOVM.IB [R4-R7], (R8) MOVM.IA.W (R1), [R2-R5] MOVW $·poly1305_init_constants_armv6<>(SB), R7 MOVW R2, R8 MOVW R2>>26, R9 MOVW R3>>20, g MOVW R4>>14, R11 MOVW R5>>8, R12 ORR R3<<6, R9, R9 ORR R4<<12, g, g ORR R5<<18, R11, R11 MOVM.IA (R7), [R2-R6] AND R8, R2, R2 AND R9, R3, R3 AND g, R4, R4 AND R11, R5, R5 AND R12, R6, R6 MOVM.IA.W [R2-R6], (R0) EOR R2, R2, R2 EOR R3, R3, R3 EOR R4, R4, R4 EOR R5, R5, R5 EOR R6, R6, R6 MOVM.IA.W [R2-R6], (R0) MOVM.IA.W (R1), [R2-R5] MOVM.IA [R2-R6], (R0) ADD $20, R13, R0 MOVM.DA (R0), [R4-R7] RET #define MOVW_UNALIGNED(Rsrc, Rdst, Rtmp, offset) \ MOVBU (offset+0)(Rsrc), Rtmp; \ MOVBU Rtmp, (offset+0)(Rdst); \ MOVBU (offset+1)(Rsrc), Rtmp; \ MOVBU Rtmp, (offset+1)(Rdst); \ MOVBU (offset+2)(Rsrc), Rtmp; \ MOVBU Rtmp, (offset+2)(Rdst); \ MOVBU (offset+3)(Rsrc), Rtmp; \ MOVBU Rtmp, (offset+3)(Rdst) TEXT poly1305_blocks_armv6<>(SB), NOSPLIT, $0 // Needs 24 bytes of stack for saved registers and then 88 bytes of // scratch space after that. We assume that 24 bytes at (R13) have // already been used: four bytes for the link register saved in the // prelude of poly1305_auth_armv6, four bytes for saving the value of g // in that function and 16 bytes of scratch space used around // poly1305_finish_ext_armv6_skip1. ADD $24, R13, R12 MOVM.IB [R4-R8, R14], (R12) MOVW R0, 88(R13) MOVW R1, 92(R13) MOVW R2, 96(R13) MOVW R1, R14 MOVW R2, R12 MOVW 56(R0), R8 WORD $0xe1180008 // TST R8, R8 not working see issue 5921 EOR R6, R6, R6 MOVW.EQ $(1<<24), R6 MOVW R6, 84(R13) ADD $116, R13, g MOVM.IA (R0), [R0-R9] MOVM.IA [R0-R4], (g) CMP $16, R12 BLO poly1305_blocks_armv6_done poly1305_blocks_armv6_mainloop: WORD $0xe31e0003 // TST R14, #3 not working see issue 5921 BEQ poly1305_blocks_armv6_mainloop_aligned ADD $100, R13, g MOVW_UNALIGNED(R14, g, R0, 0) MOVW_UNALIGNED(R14, g, R0, 4) MOVW_UNALIGNED(R14, g, R0, 8) MOVW_UNALIGNED(R14, g, R0, 12) MOVM.IA (g), [R0-R3] ADD $16, R14 B poly1305_blocks_armv6_mainloop_loaded poly1305_blocks_armv6_mainloop_aligned: MOVM.IA.W (R14), [R0-R3] poly1305_blocks_armv6_mainloop_loaded: MOVW R0>>26, g MOVW R1>>20, R11 MOVW R2>>14, R12 MOVW R14, 92(R13) MOVW R3>>8, R4 ORR R1<<6, g, g ORR R2<<12, R11, R11 ORR R3<<18, R12, R12 BIC $0xfc000000, R0, R0 BIC $0xfc000000, g, g MOVW 84(R13), R3 BIC $0xfc000000, R11, R11 BIC $0xfc000000, R12, R12 ADD R0, R5, R5 ADD g, R6, R6 ORR R3, R4, R4 ADD R11, R7, R7 ADD $116, R13, R14 ADD R12, R8, R8 ADD R4, R9, R9 MOVM.IA (R14), [R0-R4] MULLU R4, R5, (R11, g) MULLU R3, R5, (R14, R12) MULALU R3, R6, (R11, g) MULALU R2, R6, (R14, R12) MULALU R2, R7, (R11, g) MULALU R1, R7, (R14, R12) ADD R4<<2, R4, R4 ADD R3<<2, R3, R3 MULALU R1, R8, (R11, g) MULALU R0, R8, (R14, R12) MULALU R0, R9, (R11, g) MULALU R4, R9, (R14, R12) MOVW g, 76(R13) MOVW R11, 80(R13) MOVW R12, 68(R13) MOVW R14, 72(R13) MULLU R2, R5, (R11, g) MULLU R1, R5, (R14, R12) MULALU R1, R6, (R11, g) MULALU R0, R6, (R14, R12) MULALU R0, R7, (R11, g) MULALU R4, R7, (R14, R12) ADD R2<<2, R2, R2 ADD R1<<2, R1, R1 MULALU R4, R8, (R11, g) MULALU R3, R8, (R14, R12) MULALU R3, R9, (R11, g) MULALU R2, R9, (R14, R12) MOVW g, 60(R13) MOVW R11, 64(R13) MOVW R12, 52(R13) MOVW R14, 56(R13) MULLU R0, R5, (R11, g) MULALU R4, R6, (R11, g) MULALU R3, R7, (R11, g) MULALU R2, R8, (R11, g) MULALU R1, R9, (R11, g) ADD $52, R13, R0 MOVM.IA (R0), [R0-R7] MOVW g>>26, R12 MOVW R4>>26, R14 ORR R11<<6, R12, R12 ORR R5<<6, R14, R14 BIC $0xfc000000, g, g BIC $0xfc000000, R4, R4 ADD.S R12, R0, R0 ADC $0, R1, R1 ADD.S R14, R6, R6 ADC $0, R7, R7 MOVW R0>>26, R12 MOVW R6>>26, R14 ORR R1<<6, R12, R12 ORR R7<<6, R14, R14 BIC $0xfc000000, R0, R0 BIC $0xfc000000, R6, R6 ADD R14<<2, R14, R14 ADD.S R12, R2, R2 ADC $0, R3, R3 ADD R14, g, g MOVW R2>>26, R12 MOVW g>>26, R14 ORR R3<<6, R12, R12 BIC $0xfc000000, g, R5 BIC $0xfc000000, R2, R7 ADD R12, R4, R4 ADD R14, R0, R0 MOVW R4>>26, R12 BIC $0xfc000000, R4, R8 ADD R12, R6, R9 MOVW 96(R13), R12 MOVW 92(R13), R14 MOVW R0, R6 CMP $32, R12 SUB $16, R12, R12 MOVW R12, 96(R13) BHS poly1305_blocks_armv6_mainloop poly1305_blocks_armv6_done: MOVW 88(R13), R12 MOVW R5, 20(R12) MOVW R6, 24(R12) MOVW R7, 28(R12) MOVW R8, 32(R12) MOVW R9, 36(R12) ADD $48, R13, R0 MOVM.DA (R0), [R4-R8, R14] RET #define MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) \ MOVBU.P 1(Rsrc), Rtmp; \ MOVBU.P Rtmp, 1(Rdst); \ MOVBU.P 1(Rsrc), Rtmp; \ MOVBU.P Rtmp, 1(Rdst) #define MOVWP_UNALIGNED(Rsrc, Rdst, Rtmp) \ MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp); \ MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) // func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]key) TEXT ·poly1305_auth_armv6(SB), $196-16 // The value 196, just above, is the sum of 64 (the size of the context // structure) and 132 (the amount of stack needed). // // At this point, the stack pointer (R13) has been moved down. It // points to the saved link register and there's 196 bytes of free // space above it. // // The stack for this function looks like: // // +--------------------- // | // | 64 bytes of context structure // | // +--------------------- // | // | 112 bytes for poly1305_blocks_armv6 // | // +--------------------- // | 16 bytes of final block, constructed at // | poly1305_finish_ext_armv6_skip8 // +--------------------- // | four bytes of saved 'g' // +--------------------- // | lr, saved by prelude <- R13 points here // +--------------------- MOVW g, 4(R13) MOVW out+0(FP), R4 MOVW m+4(FP), R5 MOVW mlen+8(FP), R6 MOVW key+12(FP), R7 ADD $136, R13, R0 // 136 = 4 + 4 + 16 + 112 MOVW R7, R1 // poly1305_init_ext_armv6 will write to the stack from R13+4, but // that's ok because none of the other values have been written yet. BL poly1305_init_ext_armv6<>(SB) BIC.S $15, R6, R2 BEQ poly1305_auth_armv6_noblocks ADD $136, R13, R0 MOVW R5, R1 ADD R2, R5, R5 SUB R2, R6, R6 BL poly1305_blocks_armv6<>(SB) poly1305_auth_armv6_noblocks: ADD $136, R13, R0 MOVW R5, R1 MOVW R6, R2 MOVW R4, R3 MOVW R0, R5 MOVW R1, R6 MOVW R2, R7 MOVW R3, R8 AND.S R2, R2, R2 BEQ poly1305_finish_ext_armv6_noremaining EOR R0, R0 ADD $8, R13, R9 // 8 = offset to 16 byte scratch space MOVW R0, (R9) MOVW R0, 4(R9) MOVW R0, 8(R9) MOVW R0, 12(R9) WORD $0xe3110003 // TST R1, #3 not working see issue 5921 BEQ poly1305_finish_ext_armv6_aligned WORD $0xe3120008 // TST R2, #8 not working see issue 5921 BEQ poly1305_finish_ext_armv6_skip8 MOVWP_UNALIGNED(R1, R9, g) MOVWP_UNALIGNED(R1, R9, g) poly1305_finish_ext_armv6_skip8: WORD $0xe3120004 // TST $4, R2 not working see issue 5921 BEQ poly1305_finish_ext_armv6_skip4 MOVWP_UNALIGNED(R1, R9, g) poly1305_finish_ext_armv6_skip4: WORD $0xe3120002 // TST $2, R2 not working see issue 5921 BEQ poly1305_finish_ext_armv6_skip2 MOVHUP_UNALIGNED(R1, R9, g) B poly1305_finish_ext_armv6_skip2 poly1305_finish_ext_armv6_aligned: WORD $0xe3120008 // TST R2, #8 not working see issue 5921 BEQ poly1305_finish_ext_armv6_skip8_aligned MOVM.IA.W (R1), [g-R11] MOVM.IA.W [g-R11], (R9) poly1305_finish_ext_armv6_skip8_aligned: WORD $0xe3120004 // TST $4, R2 not working see issue 5921 BEQ poly1305_finish_ext_armv6_skip4_aligned MOVW.P 4(R1), g MOVW.P g, 4(R9) poly1305_finish_ext_armv6_skip4_aligned: WORD $0xe3120002 // TST $2, R2 not working see issue 5921 BEQ poly1305_finish_ext_armv6_skip2 MOVHU.P 2(R1), g MOVH.P g, 2(R9) poly1305_finish_ext_armv6_skip2: WORD $0xe3120001 // TST $1, R2 not working see issue 5921 BEQ poly1305_finish_ext_armv6_skip1 MOVBU.P 1(R1), g MOVBU.P g, 1(R9) poly1305_finish_ext_armv6_skip1: MOVW $1, R11 MOVBU R11, 0(R9) MOVW R11, 56(R5) MOVW R5, R0 ADD $8, R13, R1 MOVW $16, R2 BL poly1305_blocks_armv6<>(SB) poly1305_finish_ext_armv6_noremaining: MOVW 20(R5), R0 MOVW 24(R5), R1 MOVW 28(R5), R2 MOVW 32(R5), R3 MOVW 36(R5), R4 MOVW R4>>26, R12 BIC $0xfc000000, R4, R4 ADD R12<<2, R12, R12 ADD R12, R0, R0 MOVW R0>>26, R12 BIC $0xfc000000, R0, R0 ADD R12, R1, R1 MOVW R1>>26, R12 BIC $0xfc000000, R1, R1 ADD R12, R2, R2 MOVW R2>>26, R12 BIC $0xfc000000, R2, R2 ADD R12, R3, R3 MOVW R3>>26, R12 BIC $0xfc000000, R3, R3 ADD R12, R4, R4 ADD $5, R0, R6 MOVW R6>>26, R12 BIC $0xfc000000, R6, R6 ADD R12, R1, R7 MOVW R7>>26, R12 BIC $0xfc000000, R7, R7 ADD R12, R2, g MOVW g>>26, R12 BIC $0xfc000000, g, g ADD R12, R3, R11 MOVW $-(1<<26), R12 ADD R11>>26, R12, R12 BIC $0xfc000000, R11, R11 ADD R12, R4, R9 MOVW R9>>31, R12 SUB $1, R12 AND R12, R6, R6 AND R12, R7, R7 AND R12, g, g AND R12, R11, R11 AND R12, R9, R9 MVN R12, R12 AND R12, R0, R0 AND R12, R1, R1 AND R12, R2, R2 AND R12, R3, R3 AND R12, R4, R4 ORR R6, R0, R0 ORR R7, R1, R1 ORR g, R2, R2 ORR R11, R3, R3 ORR R9, R4, R4 ORR R1<<26, R0, R0 MOVW R1>>6, R1 ORR R2<<20, R1, R1 MOVW R2>>12, R2 ORR R3<<14, R2, R2 MOVW R3>>18, R3 ORR R4<<8, R3, R3 MOVW 40(R5), R6 MOVW 44(R5), R7 MOVW 48(R5), g MOVW 52(R5), R11 ADD.S R6, R0, R0 ADC.S R7, R1, R1 ADC.S g, R2, R2 ADC.S R11, R3, R3 MOVM.IA [R0-R3], (R8) MOVW R5, R12 EOR R0, R0, R0 EOR R1, R1, R1 EOR R2, R2, R2 EOR R3, R3, R3 EOR R4, R4, R4 EOR R5, R5, R5 EOR R6, R6, R6 EOR R7, R7, R7 MOVM.IA.W [R0-R7], (R12) MOVM.IA [R0-R7], (R12) MOVW 4(R13), g RET ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/poly1305/sum_arm.go�����������������������������������������0000644�0610621�0607500�00000001316�13172163317�024341� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build arm,!gccgo,!appengine,!nacl package poly1305 // This function is implemented in sum_arm.s //go:noescape func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]byte) // Sum generates an authenticator for m using a one-time key and puts the // 16-byte result into out. Authenticating two different messages with the same // key allows an attacker to forge messages at will. func Sum(out *[16]byte, m []byte, key *[32]byte) { var mPtr *byte if len(m) > 0 { mPtr = &m[0] } poly1305_auth_armv6(out, mPtr, uint32(len(m)), key) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/poly1305/sum_amd64.s����������������������������������������0000644�0610621�0607500�00000005740�13172163317�024337� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!gccgo,!appengine #include "textflag.h" #define POLY1305_ADD(msg, h0, h1, h2) \ ADDQ 0(msg), h0; \ ADCQ 8(msg), h1; \ ADCQ $1, h2; \ LEAQ 16(msg), msg #define POLY1305_MUL(h0, h1, h2, r0, r1, t0, t1, t2, t3) \ MOVQ r0, AX; \ MULQ h0; \ MOVQ AX, t0; \ MOVQ DX, t1; \ MOVQ r0, AX; \ MULQ h1; \ ADDQ AX, t1; \ ADCQ $0, DX; \ MOVQ r0, t2; \ IMULQ h2, t2; \ ADDQ DX, t2; \ \ MOVQ r1, AX; \ MULQ h0; \ ADDQ AX, t1; \ ADCQ $0, DX; \ MOVQ DX, h0; \ MOVQ r1, t3; \ IMULQ h2, t3; \ MOVQ r1, AX; \ MULQ h1; \ ADDQ AX, t2; \ ADCQ DX, t3; \ ADDQ h0, t2; \ ADCQ $0, t3; \ \ MOVQ t0, h0; \ MOVQ t1, h1; \ MOVQ t2, h2; \ ANDQ $3, h2; \ MOVQ t2, t0; \ ANDQ $0xFFFFFFFFFFFFFFFC, t0; \ ADDQ t0, h0; \ ADCQ t3, h1; \ ADCQ $0, h2; \ SHRQ $2, t3, t2; \ SHRQ $2, t3; \ ADDQ t2, h0; \ ADCQ t3, h1; \ ADCQ $0, h2 DATA ·poly1305Mask<>+0x00(SB)/8, $0x0FFFFFFC0FFFFFFF DATA ·poly1305Mask<>+0x08(SB)/8, $0x0FFFFFFC0FFFFFFC GLOBL ·poly1305Mask<>(SB), RODATA, $16 // func poly1305(out *[16]byte, m *byte, mlen uint64, key *[32]key) TEXT ·poly1305(SB), $0-32 MOVQ out+0(FP), DI MOVQ m+8(FP), SI MOVQ mlen+16(FP), R15 MOVQ key+24(FP), AX MOVQ 0(AX), R11 MOVQ 8(AX), R12 ANDQ ·poly1305Mask<>(SB), R11 // r0 ANDQ ·poly1305Mask<>+8(SB), R12 // r1 XORQ R8, R8 // h0 XORQ R9, R9 // h1 XORQ R10, R10 // h2 CMPQ R15, $16 JB bytes_between_0_and_15 loop: POLY1305_ADD(SI, R8, R9, R10) multiply: POLY1305_MUL(R8, R9, R10, R11, R12, BX, CX, R13, R14) SUBQ $16, R15 CMPQ R15, $16 JAE loop bytes_between_0_and_15: TESTQ R15, R15 JZ done MOVQ $1, BX XORQ CX, CX XORQ R13, R13 ADDQ R15, SI flush_buffer: SHLQ $8, BX, CX SHLQ $8, BX MOVB -1(SI), R13 XORQ R13, BX DECQ SI DECQ R15 JNZ flush_buffer ADDQ BX, R8 ADCQ CX, R9 ADCQ $0, R10 MOVQ $16, R15 JMP multiply done: MOVQ R8, AX MOVQ R9, BX SUBQ $0xFFFFFFFFFFFFFFFB, AX SBBQ $0xFFFFFFFFFFFFFFFF, BX SBBQ $3, R10 CMOVQCS R8, AX CMOVQCS R9, BX MOVQ key+24(FP), R8 ADDQ 16(R8), AX ADCQ 24(R8), BX MOVQ AX, 0(DI) MOVQ BX, 8(DI) RET ��������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/poly1305/sum_amd64.go���������������������������������������0000644�0610621�0607500�00000001266�13172163317�024501� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!gccgo,!appengine package poly1305 // This function is implemented in sum_amd64.s //go:noescape func poly1305(out *[16]byte, m *byte, mlen uint64, key *[32]byte) // Sum generates an authenticator for m using a one-time key and puts the // 16-byte result into out. Authenticating two different messages with the same // key allows an attacker to forge messages at will. func Sum(out *[16]byte, m []byte, key *[32]byte) { var mPtr *byte if len(m) > 0 { mPtr = &m[0] } poly1305(out, mPtr, uint64(len(m)), key) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/poly1305/poly1305_test.go�����������������������������������0000644�0610621�0607500�00000011773�13172163317�025241� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package poly1305 import ( "bytes" "encoding/hex" "flag" "testing" "unsafe" ) var stressFlag = flag.Bool("stress", false, "run slow stress tests") var testData = []struct { in, k, correct []byte }{ { []byte("Hello world!"), []byte("this is 32-byte key for Poly1305"), []byte{0xa6, 0xf7, 0x45, 0x00, 0x8f, 0x81, 0xc9, 0x16, 0xa2, 0x0d, 0xcc, 0x74, 0xee, 0xf2, 0xb2, 0xf0}, }, { make([]byte, 32), []byte("this is 32-byte key for Poly1305"), []byte{0x49, 0xec, 0x78, 0x09, 0x0e, 0x48, 0x1e, 0xc6, 0xc2, 0x6b, 0x33, 0xb9, 0x1c, 0xcc, 0x03, 0x07}, }, { make([]byte, 2007), []byte("this is 32-byte key for Poly1305"), []byte{0xda, 0x84, 0xbc, 0xab, 0x02, 0x67, 0x6c, 0x38, 0xcd, 0xb0, 0x15, 0x60, 0x42, 0x74, 0xc2, 0xaa}, }, { make([]byte, 2007), make([]byte, 32), make([]byte, 16), }, { // This test triggers an edge-case. See https://go-review.googlesource.com/#/c/30101/. []byte{0x81, 0xd8, 0xb2, 0xe4, 0x6a, 0x25, 0x21, 0x3b, 0x58, 0xfe, 0xe4, 0x21, 0x3a, 0x2a, 0x28, 0xe9, 0x21, 0xc1, 0x2a, 0x96, 0x32, 0x51, 0x6d, 0x3b, 0x73, 0x27, 0x27, 0x27, 0xbe, 0xcf, 0x21, 0x29}, []byte{0x3b, 0x3a, 0x29, 0xe9, 0x3b, 0x21, 0x3a, 0x5c, 0x5c, 0x3b, 0x3b, 0x05, 0x3a, 0x3a, 0x8c, 0x0d}, []byte{0x6d, 0xc1, 0x8b, 0x8c, 0x34, 0x4c, 0xd7, 0x99, 0x27, 0x11, 0x8b, 0xbe, 0x84, 0xb7, 0xf3, 0x14}, }, { // This test generates a result of (2^130-1) % (2^130-5). []byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, []byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, []byte{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, }, { // This test generates a result of (2^130-6) % (2^130-5). []byte{ 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, []byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, []byte{0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, }, { // This test generates a result of (2^130-5) % (2^130-5). []byte{ 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, []byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, }, } func testSum(t *testing.T, unaligned bool) { var out [16]byte var key [32]byte for i, v := range testData { in := v.in if unaligned { in = unalignBytes(in) } copy(key[:], v.k) Sum(&out, in, &key) if !bytes.Equal(out[:], v.correct) { t.Errorf("%d: expected %x, got %x", i, v.correct, out[:]) } } } func TestBurnin(t *testing.T) { // This test can be used to sanity-check significant changes. It can // take about many minutes to run, even on fast machines. It's disabled // by default. if !*stressFlag { t.Skip("skipping without -stress") } var key [32]byte var input [25]byte var output [16]byte for i := range key { key[i] = 1 } for i := range input { input[i] = 2 } for i := uint64(0); i < 1e10; i++ { Sum(&output, input[:], &key) copy(key[0:], output[:]) copy(key[16:], output[:]) copy(input[:], output[:]) copy(input[16:], output[:]) } const expected = "5e3b866aea0b636d240c83c428f84bfa" if got := hex.EncodeToString(output[:]); got != expected { t.Errorf("expected %s, got %s", expected, got) } } func TestSum(t *testing.T) { testSum(t, false) } func TestSumUnaligned(t *testing.T) { testSum(t, true) } func benchmark(b *testing.B, size int, unaligned bool) { var out [16]byte var key [32]byte in := make([]byte, size) if unaligned { in = unalignBytes(in) } b.SetBytes(int64(len(in))) b.ResetTimer() for i := 0; i < b.N; i++ { Sum(&out, in, &key) } } func Benchmark64(b *testing.B) { benchmark(b, 64, false) } func Benchmark1K(b *testing.B) { benchmark(b, 1024, false) } func Benchmark64Unaligned(b *testing.B) { benchmark(b, 64, true) } func Benchmark1KUnaligned(b *testing.B) { benchmark(b, 1024, true) } func unalignBytes(in []byte) []byte { out := make([]byte, len(in)+1) if uintptr(unsafe.Pointer(&out[0]))&(unsafe.Alignof(uint32(0))-1) == 0 { out = out[1:] } else { out = out[:len(in)] } copy(out, in) return out } �����lxd-2.0.11/dist/src/golang.org/x/crypto/poly1305/poly1305.go����������������������������������������0000644�0610621�0607500�00000002401�13172163317�024166� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package poly1305 implements Poly1305 one-time message authentication code as specified in https://cr.yp.to/mac/poly1305-20050329.pdf. Poly1305 is a fast, one-time authentication function. It is infeasible for an attacker to generate an authenticator for a message without the key. However, a key must only be used for a single message. Authenticating two different messages with the same key allows an attacker to forge authenticators for other messages with the same key. Poly1305 was originally coupled with AES in order to make Poly1305-AES. AES was used with a fixed key in order to generate one-time keys from an nonce. However, in this package AES isn't used and the one-time key is specified directly. */ package poly1305 // import "golang.org/x/crypto/poly1305" import "crypto/subtle" // TagSize is the size, in bytes, of a poly1305 authenticator. const TagSize = 16 // Verify returns true if mac is a valid authenticator for m with the given // key. func Verify(mac *[16]byte, m []byte, key *[32]byte) bool { var tmp [16]byte Sum(&tmp, m, key) return subtle.ConstantTimeCompare(tmp[:], mac[:]) == 1 } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022155� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/safebags.go������������������������������������������0000644�0610621�0607500�00000003455�13172163317�024266� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "crypto/x509" "encoding/asn1" "errors" ) var ( // see https://tools.ietf.org/html/rfc7292#appendix-D oidCertTypeX509Certificate = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 22, 1}) oidPKCS8ShroundedKeyBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 2}) oidCertBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 3}) ) type certBag struct { Id asn1.ObjectIdentifier Data []byte `asn1:"tag:0,explicit"` } func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) { pkinfo := new(encryptedPrivateKeyInfo) if err = unmarshal(asn1Data, pkinfo); err != nil { return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error()) } pkData, err := pbDecrypt(pkinfo, password) if err != nil { return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error()) } ret := new(asn1.RawValue) if err = unmarshal(pkData, ret); err != nil { return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error()) } if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil { return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error()) } return privateKey, nil } func decodeCertBag(asn1Data []byte) (x509Certificates []byte, err error) { bag := new(certBag) if err := unmarshal(asn1Data, bag); err != nil { return nil, errors.New("pkcs12: error decoding cert bag: " + err.Error()) } if !bag.Id.Equal(oidCertTypeX509Certificate) { return nil, NotImplementedError("only X509 certificates are supported") } return bag.Data, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/pkcs12_test.go���������������������������������������0000644�0610621�0607500�00000021423�13172163317�024650� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "crypto/rsa" "crypto/tls" "encoding/base64" "encoding/pem" "testing" ) func TestPfx(t *testing.T) { for commonName, base64P12 := range testdata { p12, _ := base64.StdEncoding.DecodeString(base64P12) priv, cert, err := Decode(p12, "") if err != nil { t.Fatal(err) } if err := priv.(*rsa.PrivateKey).Validate(); err != nil { t.Errorf("error while validating private key: %v", err) } if cert.Subject.CommonName != commonName { t.Errorf("expected common name to be %q, but found %q", commonName, cert.Subject.CommonName) } } } func TestPEM(t *testing.T) { for commonName, base64P12 := range testdata { p12, _ := base64.StdEncoding.DecodeString(base64P12) blocks, err := ToPEM(p12, "") if err != nil { t.Fatalf("error while converting to PEM: %s", err) } var pemData []byte for _, b := range blocks { pemData = append(pemData, pem.EncodeToMemory(b)...) } cert, err := tls.X509KeyPair(pemData, pemData) if err != nil { t.Errorf("err while converting to key pair: %v", err) } config := tls.Config{ Certificates: []tls.Certificate{cert}, } config.BuildNameToCertificate() if _, exists := config.NameToCertificate[commonName]; !exists { t.Errorf("did not find our cert in PEM?: %v", config.NameToCertificate) } } } func ExampleToPEM() { p12, _ := base64.StdEncoding.DecodeString(`MIIJzgIBAzCCCZQGCS ... CA+gwggPk==`) blocks, err := ToPEM(p12, "password") if err != nil { panic(err) } var pemData []byte for _, b := range blocks { pemData = append(pemData, pem.EncodeToMemory(b)...) } // then use PEM data for tls to construct tls certificate: cert, err := tls.X509KeyPair(pemData, pemData) if err != nil { panic(err) } config := &tls.Config{ Certificates: []tls.Certificate{cert}, } _ = config } var testdata = map[string]string{ // 'null' password test case "Windows Azure Tools": `MIIKDAIBAzCCCcwGCSqGSIb3DQEHAaCCCb0Eggm5MIIJtTCCBe4GCSqGSIb3DQEHAaCCBd8EggXbMIIF1zCCBdMGCyqGSIb3DQEMCgECoIIE7jCCBOowHAYKKoZIhvcNAQwBAzAOBAhStUNnlTGV+gICB9AEggTIJ81JIossF6boFWpPtkiQRPtI6DW6e9QD4/WvHAVrM2bKdpMzSMsCML5NyuddANTKHBVq00Jc9keqGNAqJPKkjhSUebzQFyhe0E1oI9T4zY5UKr/I8JclOeccH4QQnsySzYUG2SnniXnQ+JrG3juetli7EKth9h6jLc6xbubPadY5HMB3wL/eG/kJymiXwU2KQ9Mgd4X6jbcV+NNCE/8jbZHvSTCPeYTJIjxfeX61Sj5kFKUCzERbsnpyevhY3X0eYtEDezZQarvGmXtMMdzf8HJHkWRdk9VLDLgjk8uiJif/+X4FohZ37ig0CpgC2+dP4DGugaZZ51hb8tN9GeCKIsrmWogMXDIVd0OACBp/EjJVmFB6y0kUCXxUE0TZt0XA1tjAGJcjDUpBvTntZjPsnH/4ZySy+s2d9OOhJ6pzRQBRm360TzkFdSwk9DLiLdGfv4pwMMu/vNGBlqjP/1sQtj+jprJiD1sDbCl4AdQZVoMBQHadF2uSD4/o17XG/Ci0r2h6Htc2yvZMAbEY4zMjjIn2a+vqIxD6onexaek1R3zbkS9j19D6EN9EWn8xgz80YRCyW65znZk8xaIhhvlU/mg7sTxeyuqroBZNcq6uDaQTehDpyH7bY2l4zWRpoj10a6JfH2q5shYz8Y6UZC/kOTfuGqbZDNZWro/9pYquvNNW0M847E5t9bsf9VkAAMHRGBbWoVoU9VpI0UnoXSfvpOo+aXa2DSq5sHHUTVY7A9eov3z5IqT+pligx11xcs+YhDWcU8di3BTJisohKvv5Y8WSkm/rloiZd4ig269k0jTRk1olP/vCksPli4wKG2wdsd5o42nX1yL7mFfXocOANZbB+5qMkiwdyoQSk+Vq+C8nAZx2bbKhUq2MbrORGMzOe0Hh0x2a0PeObycN1Bpyv7Mp3ZI9h5hBnONKCnqMhtyQHUj/nNvbJUnDVYNfoOEqDiEqqEwB7YqWzAKz8KW0OIqdlM8uiQ4JqZZlFllnWJUfaiDrdFM3lYSnFQBkzeVlts6GpDOOBjCYd7dcCNS6kq6pZC6p6HN60Twu0JnurZD6RT7rrPkIGE8vAenFt4iGe/yF52fahCSY8Ws4K0UTwN7bAS+4xRHVCWvE8sMRZsRCHizb5laYsVrPZJhE6+hux6OBb6w8kwPYXc+ud5v6UxawUWgt6uPwl8mlAtU9Z7Miw4Nn/wtBkiLL/ke1UI1gqJtcQXgHxx6mzsjh41+nAgTvdbsSEyU6vfOmxGj3Rwc1eOrIhJUqn5YjOWfzzsz/D5DzWKmwXIwdspt1p+u+kol1N3f2wT9fKPnd/RGCb4g/1hc3Aju4DQYgGY782l89CEEdalpQ/35bQczMFk6Fje12HykakWEXd/bGm9Unh82gH84USiRpeOfQvBDYoqEyrY3zkFZzBjhDqa+jEcAj41tcGx47oSfDq3iVYCdL7HSIjtnyEktVXd7mISZLoMt20JACFcMw+mrbjlug+eU7o2GR7T+LwtOp/p4LZqyLa7oQJDwde1BNZtm3TCK2P1mW94QDL0nDUps5KLtr1DaZXEkRbjSJub2ZE9WqDHyU3KA8G84Tq/rN1IoNu/if45jacyPje1Npj9IftUZSP22nV7HMwZtwQ4P4MYHRMBMGCSqGSIb3DQEJFTEGBAQBAAAAMFsGCSqGSIb3DQEJFDFOHkwAewBCADQAQQA0AEYARQBCADAALQBBADEAOABBAC0ANAA0AEIAQgAtAEIANQBGADIALQA0ADkAMQBFAEYAMQA1ADIAQgBBADEANgB9MF0GCSsGAQQBgjcRATFQHk4ATQBpAGMAcgBvAHMAbwBmAHQAIABTAG8AZgB0AHcAYQByAGUAIABLAGUAeQAgAFMAdABvAHIAYQBnAGUAIABQAHIAbwB2AGkAZABlAHIwggO/BgkqhkiG9w0BBwagggOwMIIDrAIBADCCA6UGCSqGSIb3DQEHATAcBgoqhkiG9w0BDAEGMA4ECEBk5ZAYpu0WAgIH0ICCA3hik4mQFGpw9Ha8TQPtk+j2jwWdxfF0+sTk6S8PTsEfIhB7wPltjiCK92Uv2tCBQnodBUmatIfkpnRDEySmgmdglmOCzj204lWAMRs94PoALGn3JVBXbO1vIDCbAPOZ7Z0Hd0/1t2hmk8v3//QJGUg+qr59/4y/MuVfIg4qfkPcC2QSvYWcK3oTf6SFi5rv9B1IOWFgN5D0+C+x/9Lb/myPYX+rbOHrwtJ4W1fWKoz9g7wwmGFA9IJ2DYGuH8ifVFbDFT1Vcgsvs8arSX7oBsJVW0qrP7XkuDRe3EqCmKW7rBEwYrFznhxZcRDEpMwbFoSvgSIZ4XhFY9VKYglT+JpNH5iDceYEBOQL4vBLpxNUk3l5jKaBNxVa14AIBxq18bVHJ+STInhLhad4u10v/Xbx7wIL3f9DX1yLAkPrpBYbNHS2/ew6H/ySDJnoIDxkw2zZ4qJ+qUJZ1S0lbZVG+VT0OP5uF6tyOSpbMlcGkdl3z254n6MlCrTifcwkzscysDsgKXaYQw06rzrPW6RDub+t+hXzGny799fS9jhQMLDmOggaQ7+LA4oEZsfT89HLMWxJYDqjo3gIfjciV2mV54R684qLDS+AO09U49e6yEbwGlq8lpmO/pbXCbpGbB1b3EomcQbxdWxW2WEkkEd/VBn81K4M3obmywwXJkw+tPXDXfBmzzaqqCR+onMQ5ME1nMkY8ybnfoCc1bDIupjVWsEL2Wvq752RgI6KqzVNr1ew1IdqV5AWN2fOfek+0vi3Jd9FHF3hx8JMwjJL9dZsETV5kHtYJtE7wJ23J68BnCt2eI0GEuwXcCf5EdSKN/xXCTlIokc4Qk/gzRdIZsvcEJ6B1lGovKG54X4IohikqTjiepjbsMWj38yxDmK3mtENZ9ci8FPfbbvIEcOCZIinuY3qFUlRSbx7VUerEoV1IP3clUwexVQo4lHFee2jd7ocWsdSqSapW7OWUupBtDzRkqVhE7tGria+i1W2d6YLlJ21QTjyapWJehAMO637OdbJCCzDs1cXbodRRE7bsP492ocJy8OX66rKdhYbg8srSFNKdb3pF3UDNbN9jhI/t8iagRhNBhlQtTr1me2E/c86Q18qcRXl4bcXTt6acgCeffK6Y26LcVlrgjlD33AEYRRUeyC+rpxbT0aMjdFderlndKRIyG23mSp0HaUwNzAfMAcGBSsOAwIaBBRlviCbIyRrhIysg2dc/KbLFTc2vQQUg4rfwHMM4IKYRD/fsd1x6dda+wQ=`, // empty string password test case "testing@example.com": `MIIJzgIBAzCCCZQGCSqGSIb3DQEHAaCCCYUEggmBMIIJfTCCA/cGCSqGSIb3DQEHBqCCA+gwggPk AgEAMIID3QYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQIIszfRGqcmPcCAggAgIIDsOZ9Eg1L s5Wx8JhYoV3HAL4aRnkAWvTYB5NISZOgSgIQTssmt/3A7134dibTmaT/93LikkL3cTKLnQzJ4wDf YZ1bprpVJvUqz+HFT79m27bP9zYXFrvxWBJbxjYKTSjQMgz+h8LAEpXXGajCmxMJ1oCOtdXkhhzc LdZN6SAYgtmtyFnCdMEDskSggGuLb3fw84QEJ/Sj6FAULXunW/CPaS7Ce0TMsKmNU/jfFWj3yXXw ro0kwjKiVLpVFlnBlHo2OoVU7hmkm59YpGhLgS7nxLD3n7nBroQ0ID1+8R01NnV9XLGoGzxMm1te 6UyTCkr5mj+kEQ8EP1Ys7g/TC411uhVWySMt/rcpkx7Vz1r9kYEAzJpONAfr6cuEVkPKrxpq4Fh0 2fzlKBky0i/hrfIEUmngh+ERHUb/Mtv/fkv1j5w9suESbhsMLLiCXAlsP1UWMX+3bNizi3WVMEts FM2k9byn+p8IUD/A8ULlE4kEaWeoc+2idkCNQkLGuIdGUXUFVm58se0auUkVRoRJx8x4CkMesT8j b1H831W66YRWoEwwDQp2kK1lA2vQXxdVHWlFevMNxJeromLzj3ayiaFrfByeUXhR2S+Hpm+c0yNR 4UVU9WED2kacsZcpRm9nlEa5sr28mri5JdBrNa/K02OOhvKCxr5ZGmbOVzUQKla2z4w+Ku9k8POm dfDNU/fGx1b5hcFWtghXe3msWVsSJrQihnN6q1ughzNiYZlJUGcHdZDRtiWwCFI0bR8h/Dmg9uO9 4rawQQrjIRT7B8yF3UbkZyAqs8Ppb1TsMeNPHh1rxEfGVQknh/48ouJYsmtbnzugTUt3mJCXXiL+ XcPMV6bBVAUu4aaVKSmg9+yJtY4/VKv10iw88ktv29fViIdBe3t6l/oPuvQgbQ8dqf4T8w0l/uKZ 9lS1Na9jfT1vCoS7F5TRi+tmyj1vL5kr/amEIW6xKEP6oeAMvCMtbPAzVEj38zdJ1R22FfuIBxkh f0Zl7pdVbmzRxl/SBx9iIBJSqAvcXItiT0FIj8HxQ+0iZKqMQMiBuNWJf5pYOLWGrIyntCWwHuaQ wrx0sTGuEL9YXLEAsBDrsvzLkx/56E4INGZFrH8G7HBdW6iGqb22IMI4GHltYSyBRKbB0gadYTyv abPEoqww8o7/85aPSzOTJ/53ozD438Q+d0u9SyDuOb60SzCD/zPuCEd78YgtXJwBYTuUNRT27FaM 3LGMX8Hz+6yPNRnmnA2XKPn7dx/IlaqAjIs8MIIFfgYJKoZIhvcNAQcBoIIFbwSCBWswggVnMIIF YwYLKoZIhvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0BDAEDMA4ECJr0cClYqOlcAgIIAASCBMhe OQSiP2s0/46ONXcNeVAkz2ksW3u/+qorhSiskGZ0b3dFa1hhgBU2Q7JVIkc4Hf7OXaT1eVQ8oqND uhqsNz83/kqYo70+LS8Hocj49jFgWAKrf/yQkdyP1daHa2yzlEw4mkpqOfnIORQHvYCa8nEApspZ wVu8y6WVuLHKU67mel7db2xwstQp7PRuSAYqGjTfAylElog8ASdaqqYbYIrCXucF8iF9oVgmb/Qo xrXshJ9aSLO4MuXlTPELmWgj07AXKSb90FKNihE+y0bWb9LPVFY1Sly3AX9PfrtkSXIZwqW3phpv MxGxQl/R6mr1z+hlTfY9Wdpb5vlKXPKA0L0Rt8d2pOesylFi6esJoS01QgP1kJILjbrV731kvDc0 Jsd+Oxv4BMwA7ClG8w1EAOInc/GrV1MWFGw/HeEqj3CZ/l/0jv9bwkbVeVCiIhoL6P6lVx9pXq4t KZ0uKg/tk5TVJmG2vLcMLvezD0Yk3G2ZOMrywtmskrwoF7oAUpO9e87szoH6fEvUZlkDkPVW1NV4 cZk3DBSQiuA3VOOg8qbo/tx/EE3H59P0axZWno2GSB0wFPWd1aj+b//tJEJHaaNR6qPRj4IWj9ru Qbc8eRAcVWleHg8uAehSvUXlFpyMQREyrnpvMGddpiTC8N4UMrrBRhV7+UbCOWhxPCbItnInBqgl 1JpSZIP7iUtsIMdu3fEC2cdbXMTRul+4rdzUR7F9OaezV3jjvcAbDvgbK1CpyC+MJ1Mxm/iTgk9V iUArydhlR8OniN84GyGYoYCW9O/KUwb6ASmeFOu/msx8x6kAsSQHIkKqMKv0TUR3kZnkxUvdpBGP KTl4YCTvNGX4dYALBqrAETRDhua2KVBD/kEttDHwBNVbN2xi81+Mc7ml461aADfk0c66R/m2sjHB 2tN9+wG12OIWFQjL6wF/UfJMYamxx2zOOExiId29Opt57uYiNVLOO4ourPewHPeH0u8Gz35aero7 lkt7cZAe1Q0038JUuE/QGlnK4lESK9UkSIQAjSaAlTsrcfwtQxB2EjoOoLhwH5mvxUEmcNGNnXUc 9xj3M5BD3zBz3Ft7G3YMMDwB1+zC2l+0UG0MGVjMVaeoy32VVNvxgX7jk22OXG1iaOB+PY9kdk+O X+52BGSf/rD6X0EnqY7XuRPkMGgjtpZeAYxRQnFtCZgDY4wYheuxqSSpdF49yNczSPLkgB3CeCfS +9NTKN7aC6hBbmW/8yYh6OvSiCEwY0lFS/T+7iaVxr1loE4zI1y/FFp4Pe1qfLlLttVlkygga2UU SCunTQ8UB/M5IXWKkhMOO11dP4niWwb39Y7pCWpau7mwbXOKfRPX96cgHnQJK5uG+BesDD1oYnX0 6frN7FOnTSHKruRIwuI8KnOQ/I+owmyz71wiv5LMQt+yM47UrEjB/EZa5X8dpEwOZvkdqL7utcyo l0XH5kWMXdW856LL/FYftAqJIDAmtX1TXF/rbP6mPyN/IlDC0gjP84Uzd/a2UyTIWr+wk49Ek3vQ /uDamq6QrwAxVmNh5Tset5Vhpc1e1kb7mRMZIzxSP8JcTuYd45oFKi98I8YjvueHVZce1g7OudQP SbFQoJvdT46iBg1TTatlltpOiH2mFaxWVS0xYjAjBgkqhkiG9w0BCRUxFgQUdA9eVqvETX4an/c8 p8SsTugkit8wOwYJKoZIhvcNAQkUMS4eLABGAHIAaQBlAG4AZABsAHkAIABuAGEAbQBlACAAZgBv AHIAIABjAGUAcgB0MDEwITAJBgUrDgMCGgUABBRFsNz3Zd1O1GI8GTuFwCWuDOjEEwQIuBEfIcAy HQ8CAggA`, } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/pkcs12.go��������������������������������������������0000644�0610621�0607500�00000022250�13172163317�023610� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package pkcs12 implements some of PKCS#12. // // This implementation is distilled from https://tools.ietf.org/html/rfc7292 // and referenced documents. It is intended for decoding P12/PFX-stored // certificates and keys for use with the crypto/tls package. package pkcs12 import ( "crypto/ecdsa" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/hex" "encoding/pem" "errors" ) var ( oidDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 1}) oidEncryptedDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 6}) oidFriendlyName = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 20}) oidLocalKeyID = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 21}) oidMicrosoftCSPName = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 311, 17, 1}) ) type pfxPdu struct { Version int AuthSafe contentInfo MacData macData `asn1:"optional"` } type contentInfo struct { ContentType asn1.ObjectIdentifier Content asn1.RawValue `asn1:"tag:0,explicit,optional"` } type encryptedData struct { Version int EncryptedContentInfo encryptedContentInfo } type encryptedContentInfo struct { ContentType asn1.ObjectIdentifier ContentEncryptionAlgorithm pkix.AlgorithmIdentifier EncryptedContent []byte `asn1:"tag:0,optional"` } func (i encryptedContentInfo) Algorithm() pkix.AlgorithmIdentifier { return i.ContentEncryptionAlgorithm } func (i encryptedContentInfo) Data() []byte { return i.EncryptedContent } type safeBag struct { Id asn1.ObjectIdentifier Value asn1.RawValue `asn1:"tag:0,explicit"` Attributes []pkcs12Attribute `asn1:"set,optional"` } type pkcs12Attribute struct { Id asn1.ObjectIdentifier Value asn1.RawValue `asn1:"set"` } type encryptedPrivateKeyInfo struct { AlgorithmIdentifier pkix.AlgorithmIdentifier EncryptedData []byte } func (i encryptedPrivateKeyInfo) Algorithm() pkix.AlgorithmIdentifier { return i.AlgorithmIdentifier } func (i encryptedPrivateKeyInfo) Data() []byte { return i.EncryptedData } // PEM block types const ( certificateType = "CERTIFICATE" privateKeyType = "PRIVATE KEY" ) // unmarshal calls asn1.Unmarshal, but also returns an error if there is any // trailing data after unmarshaling. func unmarshal(in []byte, out interface{}) error { trailing, err := asn1.Unmarshal(in, out) if err != nil { return err } if len(trailing) != 0 { return errors.New("pkcs12: trailing data found") } return nil } // ConvertToPEM converts all "safe bags" contained in pfxData to PEM blocks. func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) { encodedPassword, err := bmpString(password) if err != nil { return nil, ErrIncorrectPassword } bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) if err != nil { return nil, err } blocks := make([]*pem.Block, 0, len(bags)) for _, bag := range bags { block, err := convertBag(&bag, encodedPassword) if err != nil { return nil, err } blocks = append(blocks, block) } return blocks, nil } func convertBag(bag *safeBag, password []byte) (*pem.Block, error) { block := &pem.Block{ Headers: make(map[string]string), } for _, attribute := range bag.Attributes { k, v, err := convertAttribute(&attribute) if err != nil { return nil, err } block.Headers[k] = v } switch { case bag.Id.Equal(oidCertBag): block.Type = certificateType certsData, err := decodeCertBag(bag.Value.Bytes) if err != nil { return nil, err } block.Bytes = certsData case bag.Id.Equal(oidPKCS8ShroundedKeyBag): block.Type = privateKeyType key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password) if err != nil { return nil, err } switch key := key.(type) { case *rsa.PrivateKey: block.Bytes = x509.MarshalPKCS1PrivateKey(key) case *ecdsa.PrivateKey: block.Bytes, err = x509.MarshalECPrivateKey(key) if err != nil { return nil, err } default: return nil, errors.New("found unknown private key type in PKCS#8 wrapping") } default: return nil, errors.New("don't know how to convert a safe bag of type " + bag.Id.String()) } return block, nil } func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) { isString := false switch { case attribute.Id.Equal(oidFriendlyName): key = "friendlyName" isString = true case attribute.Id.Equal(oidLocalKeyID): key = "localKeyId" case attribute.Id.Equal(oidMicrosoftCSPName): // This key is chosen to match OpenSSL. key = "Microsoft CSP Name" isString = true default: return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String()) } if isString { if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil { return "", "", err } if value, err = decodeBMPString(attribute.Value.Bytes); err != nil { return "", "", err } } else { var id []byte if err := unmarshal(attribute.Value.Bytes, &id); err != nil { return "", "", err } value = hex.EncodeToString(id) } return key, value, nil } // Decode extracts a certificate and private key from pfxData. This function // assumes that there is only one certificate and only one private key in the // pfxData. func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) { encodedPassword, err := bmpString(password) if err != nil { return nil, nil, err } bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) if err != nil { return nil, nil, err } if len(bags) != 2 { err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU") return } for _, bag := range bags { switch { case bag.Id.Equal(oidCertBag): if certificate != nil { err = errors.New("pkcs12: expected exactly one certificate bag") } certsData, err := decodeCertBag(bag.Value.Bytes) if err != nil { return nil, nil, err } certs, err := x509.ParseCertificates(certsData) if err != nil { return nil, nil, err } if len(certs) != 1 { err = errors.New("pkcs12: expected exactly one certificate in the certBag") return nil, nil, err } certificate = certs[0] case bag.Id.Equal(oidPKCS8ShroundedKeyBag): if privateKey != nil { err = errors.New("pkcs12: expected exactly one key bag") } if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil { return nil, nil, err } } } if certificate == nil { return nil, nil, errors.New("pkcs12: certificate missing") } if privateKey == nil { return nil, nil, errors.New("pkcs12: private key missing") } return } func getSafeContents(p12Data, password []byte) (bags []safeBag, updatedPassword []byte, err error) { pfx := new(pfxPdu) if err := unmarshal(p12Data, pfx); err != nil { return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error()) } if pfx.Version != 3 { return nil, nil, NotImplementedError("can only decode v3 PFX PDU's") } if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) { return nil, nil, NotImplementedError("only password-protected PFX is implemented") } // unmarshal the explicit bytes in the content for type 'data' if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil { return nil, nil, err } if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 { return nil, nil, errors.New("pkcs12: no MAC in data") } if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil { if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 { // some implementations use an empty byte array // for the empty string password try one more // time with empty-empty password password = nil err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password) } if err != nil { return nil, nil, err } } var authenticatedSafe []contentInfo if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil { return nil, nil, err } if len(authenticatedSafe) != 2 { return nil, nil, NotImplementedError("expected exactly two items in the authenticated safe") } for _, ci := range authenticatedSafe { var data []byte switch { case ci.ContentType.Equal(oidDataContentType): if err := unmarshal(ci.Content.Bytes, &data); err != nil { return nil, nil, err } case ci.ContentType.Equal(oidEncryptedDataContentType): var encryptedData encryptedData if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil { return nil, nil, err } if encryptedData.Version != 0 { return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported") } if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil { return nil, nil, err } default: return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe") } var safeContents []safeBag if err := unmarshal(data, &safeContents); err != nil { return nil, nil, err } bags = append(bags, safeContents...) } return bags, password, nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/pbkdf_test.go����������������������������������������0000644�0610621�0607500�00000002475�13172163317�024641� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "bytes" "testing" ) func TestThatPBKDFWorksCorrectlyForLongKeys(t *testing.T) { cipherInfo := shaWithTripleDESCBC{} salt := []byte("\xff\xff\xff\xff\xff\xff\xff\xff") password, _ := bmpString("sesame") key := cipherInfo.deriveKey(salt, password, 2048) if expected := []byte("\x7c\xd9\xfd\x3e\x2b\x3b\xe7\x69\x1a\x44\xe3\xbe\xf0\xf9\xea\x0f\xb9\xb8\x97\xd4\xe3\x25\xd9\xd1"); bytes.Compare(key, expected) != 0 { t.Fatalf("expected key '%x', but found '%x'", expected, key) } } func TestThatPBKDFHandlesLeadingZeros(t *testing.T) { // This test triggers a case where I_j (in step 6C) ends up with leading zero // byte, meaning that len(Ijb) < v (leading zeros get stripped by big.Int). // This was previously causing bug whereby certain inputs would break the // derivation and produce the wrong output. key := pbkdf(sha1Sum, 20, 64, []byte("\xf3\x7e\x05\xb5\x18\x32\x4b\x4b"), []byte("\x00\x00"), 2048, 1, 24) expected := []byte("\x00\xf7\x59\xff\x47\xd1\x4d\xd0\x36\x65\xd5\x94\x3c\xb3\xc4\xa3\x9a\x25\x55\xc0\x2a\xed\x66\xe1") if bytes.Compare(key, expected) != 0 { t.Fatalf("expected key '%x', but found '%x'", expected, key) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/pbkdf.go���������������������������������������������0000644�0610621�0607500�00000013037�13172163317�023576� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "bytes" "crypto/sha1" "math/big" ) var ( one = big.NewInt(1) ) // sha1Sum returns the SHA-1 hash of in. func sha1Sum(in []byte) []byte { sum := sha1.Sum(in) return sum[:] } // fillWithRepeats returns v*ceiling(len(pattern) / v) bytes consisting of // repeats of pattern. func fillWithRepeats(pattern []byte, v int) []byte { if len(pattern) == 0 { return nil } outputLen := v * ((len(pattern) + v - 1) / v) return bytes.Repeat(pattern, (outputLen+len(pattern)-1)/len(pattern))[:outputLen] } func pbkdf(hash func([]byte) []byte, u, v int, salt, password []byte, r int, ID byte, size int) (key []byte) { // implementation of https://tools.ietf.org/html/rfc7292#appendix-B.2 , RFC text verbatim in comments // Let H be a hash function built around a compression function f: // Z_2^u x Z_2^v -> Z_2^u // (that is, H has a chaining variable and output of length u bits, and // the message input to the compression function of H is v bits). The // values for u and v are as follows: // HASH FUNCTION VALUE u VALUE v // MD2, MD5 128 512 // SHA-1 160 512 // SHA-224 224 512 // SHA-256 256 512 // SHA-384 384 1024 // SHA-512 512 1024 // SHA-512/224 224 1024 // SHA-512/256 256 1024 // Furthermore, let r be the iteration count. // We assume here that u and v are both multiples of 8, as are the // lengths of the password and salt strings (which we denote by p and s, // respectively) and the number n of pseudorandom bits required. In // addition, u and v are of course non-zero. // For information on security considerations for MD5 [19], see [25] and // [1], and on those for MD2, see [18]. // The following procedure can be used to produce pseudorandom bits for // a particular "purpose" that is identified by a byte called "ID". // This standard specifies 3 different values for the ID byte: // 1. If ID=1, then the pseudorandom bits being produced are to be used // as key material for performing encryption or decryption. // 2. If ID=2, then the pseudorandom bits being produced are to be used // as an IV (Initial Value) for encryption or decryption. // 3. If ID=3, then the pseudorandom bits being produced are to be used // as an integrity key for MACing. // 1. Construct a string, D (the "diversifier"), by concatenating v/8 // copies of ID. var D []byte for i := 0; i < v; i++ { D = append(D, ID) } // 2. Concatenate copies of the salt together to create a string S of // length v(ceiling(s/v)) bits (the final copy of the salt may be // truncated to create S). Note that if the salt is the empty // string, then so is S. S := fillWithRepeats(salt, v) // 3. Concatenate copies of the password together to create a string P // of length v(ceiling(p/v)) bits (the final copy of the password // may be truncated to create P). Note that if the password is the // empty string, then so is P. P := fillWithRepeats(password, v) // 4. Set I=S||P to be the concatenation of S and P. I := append(S, P...) // 5. Set c=ceiling(n/u). c := (size + u - 1) / u // 6. For i=1, 2, ..., c, do the following: A := make([]byte, c*20) var IjBuf []byte for i := 0; i < c; i++ { // A. Set A2=H^r(D||I). (i.e., the r-th hash of D||1, // H(H(H(... H(D||I)))) Ai := hash(append(D, I...)) for j := 1; j < r; j++ { Ai = hash(Ai) } copy(A[i*20:], Ai[:]) if i < c-1 { // skip on last iteration // B. Concatenate copies of Ai to create a string B of length v // bits (the final copy of Ai may be truncated to create B). var B []byte for len(B) < v { B = append(B, Ai[:]...) } B = B[:v] // C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit // blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by // setting I_j=(I_j+B+1) mod 2^v for each j. { Bbi := new(big.Int).SetBytes(B) Ij := new(big.Int) for j := 0; j < len(I)/v; j++ { Ij.SetBytes(I[j*v : (j+1)*v]) Ij.Add(Ij, Bbi) Ij.Add(Ij, one) Ijb := Ij.Bytes() // We expect Ijb to be exactly v bytes, // if it is longer or shorter we must // adjust it accordingly. if len(Ijb) > v { Ijb = Ijb[len(Ijb)-v:] } if len(Ijb) < v { if IjBuf == nil { IjBuf = make([]byte, v) } bytesShort := v - len(Ijb) for i := 0; i < bytesShort; i++ { IjBuf[i] = 0 } copy(IjBuf[bytesShort:], Ijb) Ijb = IjBuf } copy(I[j*v:(j+1)*v], Ijb) } } } } // 7. Concatenate A_1, A_2, ..., A_c together to form a pseudorandom // bit string, A. // 8. Use the first n bits of A as the output of this entire process. return A[:size] // If the above process is being used to generate a DES key, the process // should be used to create 64 random bits, and the key's parity bits // should be set after the 64 bits have been produced. Similar concerns // hold for 2-key and 3-key triple-DES keys, for CDMF keys, and for any // similar keys with parity bits "built into them". } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/mac_test.go������������������������������������������0000644�0610621�0607500�00000002122�13172163317�024300� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "encoding/asn1" "testing" ) func TestVerifyMac(t *testing.T) { td := macData{ Mac: digestInfo{ Digest: []byte{0x18, 0x20, 0x3d, 0xff, 0x1e, 0x16, 0xf4, 0x92, 0xf2, 0xaf, 0xc8, 0x91, 0xa9, 0xba, 0xd6, 0xca, 0x9d, 0xee, 0x51, 0x93}, }, MacSalt: []byte{1, 2, 3, 4, 5, 6, 7, 8}, Iterations: 2048, } message := []byte{11, 12, 13, 14, 15} password, _ := bmpString("") td.Mac.Algorithm.Algorithm = asn1.ObjectIdentifier([]int{1, 2, 3}) err := verifyMac(&td, message, password) if _, ok := err.(NotImplementedError); !ok { t.Errorf("err: %v", err) } td.Mac.Algorithm.Algorithm = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}) err = verifyMac(&td, message, password) if err != ErrIncorrectPassword { t.Errorf("Expected incorrect password, got err: %v", err) } password, _ = bmpString("Sesame open") err = verifyMac(&td, message, password) if err != nil { t.Errorf("err: %v", err) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/mac.go�����������������������������������������������0000644�0610621�0607500�00000002002�13172163317�023236� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "crypto/hmac" "crypto/sha1" "crypto/x509/pkix" "encoding/asn1" ) type macData struct { Mac digestInfo MacSalt []byte Iterations int `asn1:"optional,default:1"` } // from PKCS#7: type digestInfo struct { Algorithm pkix.AlgorithmIdentifier Digest []byte } var ( oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}) ) func verifyMac(macData *macData, message, password []byte) error { if !macData.Mac.Algorithm.Algorithm.Equal(oidSHA1) { return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String()) } key := pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20) mac := hmac.New(sha1.New, key) mac.Write(message) expectedMAC := mac.Sum(nil) if !hmac.Equal(macData.Mac.Digest, expectedMAC) { return ErrIncorrectPassword } return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/internal/��������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023771� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/internal/rc2/����������������������������������������0000755�0610621�0607500�00000000000�13172163317�024457� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/internal/rc2/rc2_test.go�����������������������������0000644�0610621�0607500�00000003077�13172163317�026542� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package rc2 import ( "bytes" "encoding/hex" "testing" ) func TestEncryptDecrypt(t *testing.T) { // TODO(dgryski): add the rest of the test vectors from the RFC var tests = []struct { key string plain string cipher string t1 int }{ { "0000000000000000", "0000000000000000", "ebb773f993278eff", 63, }, { "ffffffffffffffff", "ffffffffffffffff", "278b27e42e2f0d49", 64, }, { "3000000000000000", "1000000000000001", "30649edf9be7d2c2", 64, }, { "88", "0000000000000000", "61a8a244adacccf0", 64, }, { "88bca90e90875a", "0000000000000000", "6ccf4308974c267f", 64, }, { "88bca90e90875a7f0f79c384627bafb2", "0000000000000000", "1a807d272bbe5db1", 64, }, { "88bca90e90875a7f0f79c384627bafb2", "0000000000000000", "2269552ab0f85ca6", 128, }, { "88bca90e90875a7f0f79c384627bafb216f80a6f85920584c42fceb0be255daf1e", "0000000000000000", "5b78d3a43dfff1f1", 129, }, } for _, tt := range tests { k, _ := hex.DecodeString(tt.key) p, _ := hex.DecodeString(tt.plain) c, _ := hex.DecodeString(tt.cipher) b, _ := New(k, tt.t1) var dst [8]byte b.Encrypt(dst[:], p) if !bytes.Equal(dst[:], c) { t.Errorf("encrypt failed: got % 2x wanted % 2x\n", dst, c) } b.Decrypt(dst[:], c) if !bytes.Equal(dst[:], p) { t.Errorf("decrypt failed: got % 2x wanted % 2x\n", dst, p) } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go����������������������������������0000644�0610621�0607500�00000014275�13172163317�025505� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package rc2 implements the RC2 cipher /* https://www.ietf.org/rfc/rfc2268.txt http://people.csail.mit.edu/rivest/pubs/KRRR98.pdf This code is licensed under the MIT license. */ package rc2 import ( "crypto/cipher" "encoding/binary" ) // The rc2 block size in bytes const BlockSize = 8 type rc2Cipher struct { k [64]uint16 } // New returns a new rc2 cipher with the given key and effective key length t1 func New(key []byte, t1 int) (cipher.Block, error) { // TODO(dgryski): error checking for key length return &rc2Cipher{ k: expandKey(key, t1), }, nil } func (*rc2Cipher) BlockSize() int { return BlockSize } var piTable = [256]byte{ 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, } func expandKey(key []byte, t1 int) [64]uint16 { l := make([]byte, 128) copy(l, key) var t = len(key) var t8 = (t1 + 7) / 8 var tm = byte(255 % uint(1<<(8+uint(t1)-8*uint(t8)))) for i := len(key); i < 128; i++ { l[i] = piTable[l[i-1]+l[uint8(i-t)]] } l[128-t8] = piTable[l[128-t8]&tm] for i := 127 - t8; i >= 0; i-- { l[i] = piTable[l[i+1]^l[i+t8]] } var k [64]uint16 for i := range k { k[i] = uint16(l[2*i]) + uint16(l[2*i+1])*256 } return k } func rotl16(x uint16, b uint) uint16 { return (x >> (16 - b)) | (x << b) } func (c *rc2Cipher) Encrypt(dst, src []byte) { r0 := binary.LittleEndian.Uint16(src[0:]) r1 := binary.LittleEndian.Uint16(src[2:]) r2 := binary.LittleEndian.Uint16(src[4:]) r3 := binary.LittleEndian.Uint16(src[6:]) var j int for j <= 16 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = rotl16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = rotl16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = rotl16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = rotl16(r3, 5) j++ } r0 = r0 + c.k[r3&63] r1 = r1 + c.k[r0&63] r2 = r2 + c.k[r1&63] r3 = r3 + c.k[r2&63] for j <= 40 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = rotl16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = rotl16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = rotl16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = rotl16(r3, 5) j++ } r0 = r0 + c.k[r3&63] r1 = r1 + c.k[r0&63] r2 = r2 + c.k[r1&63] r3 = r3 + c.k[r2&63] for j <= 60 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = rotl16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = rotl16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = rotl16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = rotl16(r3, 5) j++ } binary.LittleEndian.PutUint16(dst[0:], r0) binary.LittleEndian.PutUint16(dst[2:], r1) binary.LittleEndian.PutUint16(dst[4:], r2) binary.LittleEndian.PutUint16(dst[6:], r3) } func (c *rc2Cipher) Decrypt(dst, src []byte) { r0 := binary.LittleEndian.Uint16(src[0:]) r1 := binary.LittleEndian.Uint16(src[2:]) r2 := binary.LittleEndian.Uint16(src[4:]) r3 := binary.LittleEndian.Uint16(src[6:]) j := 63 for j >= 44 { // unmix r3 r3 = rotl16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = rotl16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = rotl16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = rotl16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } r3 = r3 - c.k[r2&63] r2 = r2 - c.k[r1&63] r1 = r1 - c.k[r0&63] r0 = r0 - c.k[r3&63] for j >= 20 { // unmix r3 r3 = rotl16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = rotl16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = rotl16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = rotl16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } r3 = r3 - c.k[r2&63] r2 = r2 - c.k[r1&63] r1 = r1 - c.k[r0&63] r0 = r0 - c.k[r3&63] for j >= 0 { // unmix r3 r3 = rotl16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = rotl16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = rotl16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = rotl16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } binary.LittleEndian.PutUint16(dst[0:], r0) binary.LittleEndian.PutUint16(dst[2:], r1) binary.LittleEndian.PutUint16(dst[4:], r2) binary.LittleEndian.PutUint16(dst[6:], r3) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/internal/rc2/bench_test.go���������������������������0000644�0610621�0607500�00000001057�13172163317�027127� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package rc2 import ( "testing" ) func BenchmarkEncrypt(b *testing.B) { r, _ := New([]byte{0, 0, 0, 0, 0, 0, 0, 0}, 64) b.ResetTimer() var src [8]byte for i := 0; i < b.N; i++ { r.Encrypt(src[:], src[:]) } } func BenchmarkDecrypt(b *testing.B) { r, _ := New([]byte{0, 0, 0, 0, 0, 0, 0, 0}, 64) b.ResetTimer() var src [8]byte for i := 0; i < b.N; i++ { r.Decrypt(src[:], src[:]) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/errors.go��������������������������������������������0000644�0610621�0607500�00000001357�13172163317�024026� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import "errors" var ( // ErrDecryption represents a failure to decrypt the input. ErrDecryption = errors.New("pkcs12: decryption error, incorrect padding") // ErrIncorrectPassword is returned when an incorrect password is detected. // Usually, P12/PFX data is signed to be able to verify the password. ErrIncorrectPassword = errors.New("pkcs12: decryption password incorrect") ) // NotImplementedError indicates that the input is not currently supported. type NotImplementedError string func (e NotImplementedError) Error() string { return "pkcs12: " + string(e) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/crypto_test.go���������������������������������������0000644�0610621�0607500�00000006231�13172163317�025065� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "bytes" "crypto/x509/pkix" "encoding/asn1" "testing" ) var sha1WithTripleDES = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3}) func TestPbDecrypterFor(t *testing.T) { params, _ := asn1.Marshal(pbeParams{ Salt: []byte{1, 2, 3, 4, 5, 6, 7, 8}, Iterations: 2048, }) alg := pkix.AlgorithmIdentifier{ Algorithm: asn1.ObjectIdentifier([]int{1, 2, 3}), Parameters: asn1.RawValue{ FullBytes: params, }, } pass, _ := bmpString("Sesame open") _, _, err := pbDecrypterFor(alg, pass) if _, ok := err.(NotImplementedError); !ok { t.Errorf("expected not implemented error, got: %T %s", err, err) } alg.Algorithm = sha1WithTripleDES cbc, blockSize, err := pbDecrypterFor(alg, pass) if err != nil { t.Errorf("unexpected error from pbDecrypterFor %v", err) } if blockSize != 8 { t.Errorf("unexpected block size %d, wanted 8", blockSize) } plaintext := []byte{1, 2, 3, 4, 5, 6, 7, 8} expectedCiphertext := []byte{185, 73, 135, 249, 137, 1, 122, 247} ciphertext := make([]byte, len(plaintext)) cbc.CryptBlocks(ciphertext, plaintext) if bytes.Compare(ciphertext, expectedCiphertext) != 0 { t.Errorf("bad ciphertext, got %x but wanted %x", ciphertext, expectedCiphertext) } } var pbDecryptTests = []struct { in []byte expected []byte expectedError error }{ { []byte("\x33\x73\xf3\x9f\xda\x49\xae\xfc\xa0\x9a\xdf\x5a\x58\xa0\xea\x46"), // 7 padding bytes []byte("A secret!"), nil, }, { []byte("\x33\x73\xf3\x9f\xda\x49\xae\xfc\x96\x24\x2f\x71\x7e\x32\x3f\xe7"), // 8 padding bytes []byte("A secret"), nil, }, { []byte("\x35\x0c\xc0\x8d\xab\xa9\x5d\x30\x7f\x9a\xec\x6a\xd8\x9b\x9c\xd9"), // 9 padding bytes, incorrect nil, ErrDecryption, }, { []byte("\xb2\xf9\x6e\x06\x60\xae\x20\xcf\x08\xa0\x7b\xd9\x6b\x20\xef\x41"), // incorrect padding bytes: [ ... 0x04 0x02 ] nil, ErrDecryption, }, } func TestPbDecrypt(t *testing.T) { for i, test := range pbDecryptTests { decryptable := testDecryptable{ data: test.in, algorithm: pkix.AlgorithmIdentifier{ Algorithm: sha1WithTripleDES, Parameters: pbeParams{ Salt: []byte("\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8"), Iterations: 4096, }.RawASN1(), }, } password, _ := bmpString("sesame") plaintext, err := pbDecrypt(decryptable, password) if err != test.expectedError { t.Errorf("#%d: got error %q, but wanted %q", i, err, test.expectedError) continue } if !bytes.Equal(plaintext, test.expected) { t.Errorf("#%d: got %x, but wanted %x", i, plaintext, test.expected) } } } type testDecryptable struct { data []byte algorithm pkix.AlgorithmIdentifier } func (d testDecryptable) Algorithm() pkix.AlgorithmIdentifier { return d.algorithm } func (d testDecryptable) Data() []byte { return d.data } func (params pbeParams) RawASN1() (raw asn1.RawValue) { asn1Bytes, err := asn1.Marshal(params) if err != nil { panic(err) } _, err = asn1.Unmarshal(asn1Bytes, &raw) if err != nil { panic(err) } return } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/crypto.go��������������������������������������������0000644�0610621�0607500�00000007321�13172163317�024027� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "bytes" "crypto/cipher" "crypto/des" "crypto/x509/pkix" "encoding/asn1" "errors" "golang.org/x/crypto/pkcs12/internal/rc2" ) var ( oidPBEWithSHAAnd3KeyTripleDESCBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3}) oidPBEWithSHAAnd40BitRC2CBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 6}) ) // pbeCipher is an abstraction of a PKCS#12 cipher. type pbeCipher interface { // create returns a cipher.Block given a key. create(key []byte) (cipher.Block, error) // deriveKey returns a key derived from the given password and salt. deriveKey(salt, password []byte, iterations int) []byte // deriveKey returns an IV derived from the given password and salt. deriveIV(salt, password []byte, iterations int) []byte } type shaWithTripleDESCBC struct{} func (shaWithTripleDESCBC) create(key []byte) (cipher.Block, error) { return des.NewTripleDESCipher(key) } func (shaWithTripleDESCBC) deriveKey(salt, password []byte, iterations int) []byte { return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 24) } func (shaWithTripleDESCBC) deriveIV(salt, password []byte, iterations int) []byte { return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) } type shaWith40BitRC2CBC struct{} func (shaWith40BitRC2CBC) create(key []byte) (cipher.Block, error) { return rc2.New(key, len(key)*8) } func (shaWith40BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte { return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 5) } func (shaWith40BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte { return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) } type pbeParams struct { Salt []byte Iterations int } func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) { var cipherType pbeCipher switch { case algorithm.Algorithm.Equal(oidPBEWithSHAAnd3KeyTripleDESCBC): cipherType = shaWithTripleDESCBC{} case algorithm.Algorithm.Equal(oidPBEWithSHAAnd40BitRC2CBC): cipherType = shaWith40BitRC2CBC{} default: return nil, 0, NotImplementedError("algorithm " + algorithm.Algorithm.String() + " is not supported") } var params pbeParams if err := unmarshal(algorithm.Parameters.FullBytes, &params); err != nil { return nil, 0, err } key := cipherType.deriveKey(params.Salt, password, params.Iterations) iv := cipherType.deriveIV(params.Salt, password, params.Iterations) block, err := cipherType.create(key) if err != nil { return nil, 0, err } return cipher.NewCBCDecrypter(block, iv), block.BlockSize(), nil } func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) { cbc, blockSize, err := pbDecrypterFor(info.Algorithm(), password) if err != nil { return nil, err } encrypted := info.Data() if len(encrypted) == 0 { return nil, errors.New("pkcs12: empty encrypted data") } if len(encrypted)%blockSize != 0 { return nil, errors.New("pkcs12: input is not a multiple of the block size") } decrypted = make([]byte, len(encrypted)) cbc.CryptBlocks(decrypted, encrypted) psLen := int(decrypted[len(decrypted)-1]) if psLen == 0 || psLen > blockSize { return nil, ErrDecryption } if len(decrypted) < psLen { return nil, ErrDecryption } ps := decrypted[len(decrypted)-psLen:] decrypted = decrypted[:len(decrypted)-psLen] if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 { return nil, ErrDecryption } return } // decryptable abstracts an object that contains ciphertext. type decryptable interface { Algorithm() pkix.AlgorithmIdentifier Data() []byte } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/bmp-string_test.go�����������������������������������0000644�0610621�0607500�00000003173�13172163317�025631� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "bytes" "encoding/hex" "testing" ) var bmpStringTests = []struct { in string expectedHex string shouldFail bool }{ {"", "0000", false}, // Example from https://tools.ietf.org/html/rfc7292#appendix-B. {"Beavis", "0042006500610076006900730000", false}, // Some characters from the "Letterlike Symbols Unicode block". {"\u2115 - Double-struck N", "21150020002d00200044006f00750062006c0065002d00730074007200750063006b0020004e0000", false}, // any character outside the BMP should trigger an error. {"\U0001f000 East wind (Mahjong)", "", true}, } func TestBMPString(t *testing.T) { for i, test := range bmpStringTests { expected, err := hex.DecodeString(test.expectedHex) if err != nil { t.Fatalf("#%d: failed to decode expectation", i) } out, err := bmpString(test.in) if err == nil && test.shouldFail { t.Errorf("#%d: expected to fail, but produced %x", i, out) continue } if err != nil && !test.shouldFail { t.Errorf("#%d: failed unexpectedly: %s", i, err) continue } if !test.shouldFail { if !bytes.Equal(out, expected) { t.Errorf("#%d: expected %s, got %x", i, test.expectedHex, out) continue } roundTrip, err := decodeBMPString(out) if err != nil { t.Errorf("#%d: decoding output gave an error: %s", i, err) continue } if roundTrip != test.in { t.Errorf("#%d: decoding output resulted in %q, but it should have been %q", i, roundTrip, test.in) continue } } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pkcs12/bmp-string.go����������������������������������������0000644�0610621�0607500�00000002725�13172163317�024574� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "errors" "unicode/utf16" ) // bmpString returns s encoded in UCS-2 with a zero terminator. func bmpString(s string) ([]byte, error) { // References: // https://tools.ietf.org/html/rfc7292#appendix-B.1 // https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane // - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes // EncodeRune returns 0xfffd if the rune does not need special encoding // - the above RFC provides the info that BMPStrings are NULL terminated. ret := make([]byte, 0, 2*len(s)+2) for _, r := range s { if t, _ := utf16.EncodeRune(r); t != 0xfffd { return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2") } ret = append(ret, byte(r/256), byte(r%256)) } return append(ret, 0, 0), nil } func decodeBMPString(bmpString []byte) (string, error) { if len(bmpString)%2 != 0 { return "", errors.New("pkcs12: odd-length BMP string") } // strip terminator if present if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 { bmpString = bmpString[:l-2] } s := make([]uint16, 0, len(bmpString)/2) for len(bmpString) > 0 { s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1])) bmpString = bmpString[2:] } return string(utf16.Decode(s)), nil } �������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pbkdf2/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022222� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pbkdf2/pbkdf2_test.go���������������������������������������0000644�0610621�0607500�00000006275�13172163317�024772� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pbkdf2 import ( "bytes" "crypto/sha1" "crypto/sha256" "hash" "testing" ) type testVector struct { password string salt string iter int output []byte } // Test vectors from RFC 6070, http://tools.ietf.org/html/rfc6070 var sha1TestVectors = []testVector{ { "password", "salt", 1, []byte{ 0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71, 0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06, 0x2f, 0xe0, 0x37, 0xa6, }, }, { "password", "salt", 2, []byte{ 0xea, 0x6c, 0x01, 0x4d, 0xc7, 0x2d, 0x6f, 0x8c, 0xcd, 0x1e, 0xd9, 0x2a, 0xce, 0x1d, 0x41, 0xf0, 0xd8, 0xde, 0x89, 0x57, }, }, { "password", "salt", 4096, []byte{ 0x4b, 0x00, 0x79, 0x01, 0xb7, 0x65, 0x48, 0x9a, 0xbe, 0xad, 0x49, 0xd9, 0x26, 0xf7, 0x21, 0xd0, 0x65, 0xa4, 0x29, 0xc1, }, }, // // This one takes too long // { // "password", // "salt", // 16777216, // []byte{ // 0xee, 0xfe, 0x3d, 0x61, 0xcd, 0x4d, 0xa4, 0xe4, // 0xe9, 0x94, 0x5b, 0x3d, 0x6b, 0xa2, 0x15, 0x8c, // 0x26, 0x34, 0xe9, 0x84, // }, // }, { "passwordPASSWORDpassword", "saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, []byte{ 0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b, 0x80, 0xc8, 0xd8, 0x36, 0x62, 0xc0, 0xe4, 0x4a, 0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70, 0x38, }, }, { "pass\000word", "sa\000lt", 4096, []byte{ 0x56, 0xfa, 0x6a, 0xa7, 0x55, 0x48, 0x09, 0x9d, 0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25, 0xe0, 0xc3, }, }, } // Test vectors from // http://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors var sha256TestVectors = []testVector{ { "password", "salt", 1, []byte{ 0x12, 0x0f, 0xb6, 0xcf, 0xfc, 0xf8, 0xb3, 0x2c, 0x43, 0xe7, 0x22, 0x52, 0x56, 0xc4, 0xf8, 0x37, 0xa8, 0x65, 0x48, 0xc9, }, }, { "password", "salt", 2, []byte{ 0xae, 0x4d, 0x0c, 0x95, 0xaf, 0x6b, 0x46, 0xd3, 0x2d, 0x0a, 0xdf, 0xf9, 0x28, 0xf0, 0x6d, 0xd0, 0x2a, 0x30, 0x3f, 0x8e, }, }, { "password", "salt", 4096, []byte{ 0xc5, 0xe4, 0x78, 0xd5, 0x92, 0x88, 0xc8, 0x41, 0xaa, 0x53, 0x0d, 0xb6, 0x84, 0x5c, 0x4c, 0x8d, 0x96, 0x28, 0x93, 0xa0, }, }, { "passwordPASSWORDpassword", "saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, []byte{ 0x34, 0x8c, 0x89, 0xdb, 0xcb, 0xd3, 0x2b, 0x2f, 0x32, 0xd8, 0x14, 0xb8, 0x11, 0x6e, 0x84, 0xcf, 0x2b, 0x17, 0x34, 0x7e, 0xbc, 0x18, 0x00, 0x18, 0x1c, }, }, { "pass\000word", "sa\000lt", 4096, []byte{ 0x89, 0xb6, 0x9d, 0x05, 0x16, 0xf8, 0x29, 0x89, 0x3c, 0x69, 0x62, 0x26, 0x65, 0x0a, 0x86, 0x87, }, }, } func testHash(t *testing.T, h func() hash.Hash, hashName string, vectors []testVector) { for i, v := range vectors { o := Key([]byte(v.password), []byte(v.salt), v.iter, len(v.output), h) if !bytes.Equal(o, v.output) { t.Errorf("%s %d: expected %x, got %x", hashName, i, v.output, o) } } } func TestWithHMACSHA1(t *testing.T) { testHash(t, sha1.New, "SHA1", sha1TestVectors) } func TestWithHMACSHA256(t *testing.T) { testHash(t, sha256.New, "SHA256", sha256TestVectors) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/pbkdf2/pbkdf2.go��������������������������������������������0000644�0610621�0607500�00000004664�13172163317�023733� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package pbkdf2 implements the key derivation function PBKDF2 as defined in RFC 2898 / PKCS #5 v2.0. A key derivation function is useful when encrypting data based on a password or any other not-fully-random data. It uses a pseudorandom function to derive a secure encryption key based on the password. While v2.0 of the standard defines only one pseudorandom function to use, HMAC-SHA1, the drafted v2.1 specification allows use of all five FIPS Approved Hash Functions SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 for HMAC. To choose, you can pass the `New` functions from the different SHA packages to pbkdf2.Key. */ package pbkdf2 // import "golang.org/x/crypto/pbkdf2" import ( "crypto/hmac" "hash" ) // Key derives a key from the password, salt and iteration count, returning a // []byte of length keylen that can be used as cryptographic key. The key is // derived based on the method described as PBKDF2 with the HMAC variant using // the supplied hash function. // // For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you // can get a derived key for e.g. AES-256 (which needs a 32-byte key) by // doing: // // dk := pbkdf2.Key([]byte("some password"), salt, 4096, 32, sha1.New) // // Remember to get a good random salt. At least 8 bytes is recommended by the // RFC. // // Using a higher iteration count will increase the cost of an exhaustive // search but will also make derivation proportionally slower. func Key(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte { prf := hmac.New(h, password) hashLen := prf.Size() numBlocks := (keyLen + hashLen - 1) / hashLen var buf [4]byte dk := make([]byte, 0, numBlocks*hashLen) U := make([]byte, hashLen) for block := 1; block <= numBlocks; block++ { // N.B.: || means concatenation, ^ means XOR // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter // U_1 = PRF(password, salt || uint(i)) prf.Reset() prf.Write(salt) buf[0] = byte(block >> 24) buf[1] = byte(block >> 16) buf[2] = byte(block >> 8) buf[3] = byte(block) prf.Write(buf[:4]) dk = prf.Sum(dk) T := dk[len(dk)-hashLen:] copy(U, T) // U_n = PRF(password, U_(n-1)) for n := 2; n <= iter; n++ { prf.Reset() prf.Write(U) U = U[:0] U = prf.Sum(U) for x := range U { T[x] ^= U[x] } } } return dk[:keyLen] } ����������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/otr/��������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021656� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/otr/smp.go��������������������������������������������������0000644�0610621�0607500�00000027316�13172163317�023015� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file implements the Socialist Millionaires Protocol as described in // http://www.cypherpunks.ca/otr/Protocol-v2-3.1.0.html. The protocol // specification is required in order to understand this code and, where // possible, the variable names in the code match up with the spec. package otr import ( "bytes" "crypto/sha256" "errors" "hash" "math/big" ) type smpFailure string func (s smpFailure) Error() string { return string(s) } var smpFailureError = smpFailure("otr: SMP protocol failed") var smpSecretMissingError = smpFailure("otr: mutual secret needed") const smpVersion = 1 const ( smpState1 = iota smpState2 smpState3 smpState4 ) type smpState struct { state int a2, a3, b2, b3, pb, qb *big.Int g2a, g3a *big.Int g2, g3 *big.Int g3b, papb, qaqb, ra *big.Int saved *tlv secret *big.Int question string } func (c *Conversation) startSMP(question string) (tlvs []tlv) { if c.smp.state != smpState1 { tlvs = append(tlvs, c.generateSMPAbort()) } tlvs = append(tlvs, c.generateSMP1(question)) c.smp.question = "" c.smp.state = smpState2 return } func (c *Conversation) resetSMP() { c.smp.state = smpState1 c.smp.secret = nil c.smp.question = "" } func (c *Conversation) processSMP(in tlv) (out tlv, complete bool, err error) { data := in.data switch in.typ { case tlvTypeSMPAbort: if c.smp.state != smpState1 { err = smpFailureError } c.resetSMP() return case tlvTypeSMP1WithQuestion: // We preprocess this into a SMP1 message. nulPos := bytes.IndexByte(data, 0) if nulPos == -1 { err = errors.New("otr: SMP message with question didn't contain a NUL byte") return } c.smp.question = string(data[:nulPos]) data = data[nulPos+1:] } numMPIs, data, ok := getU32(data) if !ok || numMPIs > 20 { err = errors.New("otr: corrupt SMP message") return } mpis := make([]*big.Int, numMPIs) for i := range mpis { var ok bool mpis[i], data, ok = getMPI(data) if !ok { err = errors.New("otr: corrupt SMP message") return } } switch in.typ { case tlvTypeSMP1, tlvTypeSMP1WithQuestion: if c.smp.state != smpState1 { c.resetSMP() out = c.generateSMPAbort() return } if c.smp.secret == nil { err = smpSecretMissingError return } if err = c.processSMP1(mpis); err != nil { return } c.smp.state = smpState3 out = c.generateSMP2() case tlvTypeSMP2: if c.smp.state != smpState2 { c.resetSMP() out = c.generateSMPAbort() return } if out, err = c.processSMP2(mpis); err != nil { out = c.generateSMPAbort() return } c.smp.state = smpState4 case tlvTypeSMP3: if c.smp.state != smpState3 { c.resetSMP() out = c.generateSMPAbort() return } if out, err = c.processSMP3(mpis); err != nil { return } c.smp.state = smpState1 c.smp.secret = nil complete = true case tlvTypeSMP4: if c.smp.state != smpState4 { c.resetSMP() out = c.generateSMPAbort() return } if err = c.processSMP4(mpis); err != nil { out = c.generateSMPAbort() return } c.smp.state = smpState1 c.smp.secret = nil complete = true default: panic("unknown SMP message") } return } func (c *Conversation) calcSMPSecret(mutualSecret []byte, weStarted bool) { h := sha256.New() h.Write([]byte{smpVersion}) if weStarted { h.Write(c.PrivateKey.PublicKey.Fingerprint()) h.Write(c.TheirPublicKey.Fingerprint()) } else { h.Write(c.TheirPublicKey.Fingerprint()) h.Write(c.PrivateKey.PublicKey.Fingerprint()) } h.Write(c.SSID[:]) h.Write(mutualSecret) c.smp.secret = new(big.Int).SetBytes(h.Sum(nil)) } func (c *Conversation) generateSMP1(question string) tlv { var randBuf [16]byte c.smp.a2 = c.randMPI(randBuf[:]) c.smp.a3 = c.randMPI(randBuf[:]) g2a := new(big.Int).Exp(g, c.smp.a2, p) g3a := new(big.Int).Exp(g, c.smp.a3, p) h := sha256.New() r2 := c.randMPI(randBuf[:]) r := new(big.Int).Exp(g, r2, p) c2 := new(big.Int).SetBytes(hashMPIs(h, 1, r)) d2 := new(big.Int).Mul(c.smp.a2, c2) d2.Sub(r2, d2) d2.Mod(d2, q) if d2.Sign() < 0 { d2.Add(d2, q) } r3 := c.randMPI(randBuf[:]) r.Exp(g, r3, p) c3 := new(big.Int).SetBytes(hashMPIs(h, 2, r)) d3 := new(big.Int).Mul(c.smp.a3, c3) d3.Sub(r3, d3) d3.Mod(d3, q) if d3.Sign() < 0 { d3.Add(d3, q) } var ret tlv if len(question) > 0 { ret.typ = tlvTypeSMP1WithQuestion ret.data = append(ret.data, question...) ret.data = append(ret.data, 0) } else { ret.typ = tlvTypeSMP1 } ret.data = appendU32(ret.data, 6) ret.data = appendMPIs(ret.data, g2a, c2, d2, g3a, c3, d3) return ret } func (c *Conversation) processSMP1(mpis []*big.Int) error { if len(mpis) != 6 { return errors.New("otr: incorrect number of arguments in SMP1 message") } g2a := mpis[0] c2 := mpis[1] d2 := mpis[2] g3a := mpis[3] c3 := mpis[4] d3 := mpis[5] h := sha256.New() r := new(big.Int).Exp(g, d2, p) s := new(big.Int).Exp(g2a, c2, p) r.Mul(r, s) r.Mod(r, p) t := new(big.Int).SetBytes(hashMPIs(h, 1, r)) if c2.Cmp(t) != 0 { return errors.New("otr: ZKP c2 incorrect in SMP1 message") } r.Exp(g, d3, p) s.Exp(g3a, c3, p) r.Mul(r, s) r.Mod(r, p) t.SetBytes(hashMPIs(h, 2, r)) if c3.Cmp(t) != 0 { return errors.New("otr: ZKP c3 incorrect in SMP1 message") } c.smp.g2a = g2a c.smp.g3a = g3a return nil } func (c *Conversation) generateSMP2() tlv { var randBuf [16]byte b2 := c.randMPI(randBuf[:]) c.smp.b3 = c.randMPI(randBuf[:]) r2 := c.randMPI(randBuf[:]) r3 := c.randMPI(randBuf[:]) r4 := c.randMPI(randBuf[:]) r5 := c.randMPI(randBuf[:]) r6 := c.randMPI(randBuf[:]) g2b := new(big.Int).Exp(g, b2, p) g3b := new(big.Int).Exp(g, c.smp.b3, p) r := new(big.Int).Exp(g, r2, p) h := sha256.New() c2 := new(big.Int).SetBytes(hashMPIs(h, 3, r)) d2 := new(big.Int).Mul(b2, c2) d2.Sub(r2, d2) d2.Mod(d2, q) if d2.Sign() < 0 { d2.Add(d2, q) } r.Exp(g, r3, p) c3 := new(big.Int).SetBytes(hashMPIs(h, 4, r)) d3 := new(big.Int).Mul(c.smp.b3, c3) d3.Sub(r3, d3) d3.Mod(d3, q) if d3.Sign() < 0 { d3.Add(d3, q) } c.smp.g2 = new(big.Int).Exp(c.smp.g2a, b2, p) c.smp.g3 = new(big.Int).Exp(c.smp.g3a, c.smp.b3, p) c.smp.pb = new(big.Int).Exp(c.smp.g3, r4, p) c.smp.qb = new(big.Int).Exp(g, r4, p) r.Exp(c.smp.g2, c.smp.secret, p) c.smp.qb.Mul(c.smp.qb, r) c.smp.qb.Mod(c.smp.qb, p) s := new(big.Int) s.Exp(c.smp.g2, r6, p) r.Exp(g, r5, p) s.Mul(r, s) s.Mod(s, p) r.Exp(c.smp.g3, r5, p) cp := new(big.Int).SetBytes(hashMPIs(h, 5, r, s)) // D5 = r5 - r4 cP mod q and D6 = r6 - y cP mod q s.Mul(r4, cp) r.Sub(r5, s) d5 := new(big.Int).Mod(r, q) if d5.Sign() < 0 { d5.Add(d5, q) } s.Mul(c.smp.secret, cp) r.Sub(r6, s) d6 := new(big.Int).Mod(r, q) if d6.Sign() < 0 { d6.Add(d6, q) } var ret tlv ret.typ = tlvTypeSMP2 ret.data = appendU32(ret.data, 11) ret.data = appendMPIs(ret.data, g2b, c2, d2, g3b, c3, d3, c.smp.pb, c.smp.qb, cp, d5, d6) return ret } func (c *Conversation) processSMP2(mpis []*big.Int) (out tlv, err error) { if len(mpis) != 11 { err = errors.New("otr: incorrect number of arguments in SMP2 message") return } g2b := mpis[0] c2 := mpis[1] d2 := mpis[2] g3b := mpis[3] c3 := mpis[4] d3 := mpis[5] pb := mpis[6] qb := mpis[7] cp := mpis[8] d5 := mpis[9] d6 := mpis[10] h := sha256.New() r := new(big.Int).Exp(g, d2, p) s := new(big.Int).Exp(g2b, c2, p) r.Mul(r, s) r.Mod(r, p) s.SetBytes(hashMPIs(h, 3, r)) if c2.Cmp(s) != 0 { err = errors.New("otr: ZKP c2 failed in SMP2 message") return } r.Exp(g, d3, p) s.Exp(g3b, c3, p) r.Mul(r, s) r.Mod(r, p) s.SetBytes(hashMPIs(h, 4, r)) if c3.Cmp(s) != 0 { err = errors.New("otr: ZKP c3 failed in SMP2 message") return } c.smp.g2 = new(big.Int).Exp(g2b, c.smp.a2, p) c.smp.g3 = new(big.Int).Exp(g3b, c.smp.a3, p) r.Exp(g, d5, p) s.Exp(c.smp.g2, d6, p) r.Mul(r, s) s.Exp(qb, cp, p) r.Mul(r, s) r.Mod(r, p) s.Exp(c.smp.g3, d5, p) t := new(big.Int).Exp(pb, cp, p) s.Mul(s, t) s.Mod(s, p) t.SetBytes(hashMPIs(h, 5, s, r)) if cp.Cmp(t) != 0 { err = errors.New("otr: ZKP cP failed in SMP2 message") return } var randBuf [16]byte r4 := c.randMPI(randBuf[:]) r5 := c.randMPI(randBuf[:]) r6 := c.randMPI(randBuf[:]) r7 := c.randMPI(randBuf[:]) pa := new(big.Int).Exp(c.smp.g3, r4, p) r.Exp(c.smp.g2, c.smp.secret, p) qa := new(big.Int).Exp(g, r4, p) qa.Mul(qa, r) qa.Mod(qa, p) r.Exp(g, r5, p) s.Exp(c.smp.g2, r6, p) r.Mul(r, s) r.Mod(r, p) s.Exp(c.smp.g3, r5, p) cp.SetBytes(hashMPIs(h, 6, s, r)) r.Mul(r4, cp) d5 = new(big.Int).Sub(r5, r) d5.Mod(d5, q) if d5.Sign() < 0 { d5.Add(d5, q) } r.Mul(c.smp.secret, cp) d6 = new(big.Int).Sub(r6, r) d6.Mod(d6, q) if d6.Sign() < 0 { d6.Add(d6, q) } r.ModInverse(qb, p) qaqb := new(big.Int).Mul(qa, r) qaqb.Mod(qaqb, p) ra := new(big.Int).Exp(qaqb, c.smp.a3, p) r.Exp(qaqb, r7, p) s.Exp(g, r7, p) cr := new(big.Int).SetBytes(hashMPIs(h, 7, s, r)) r.Mul(c.smp.a3, cr) d7 := new(big.Int).Sub(r7, r) d7.Mod(d7, q) if d7.Sign() < 0 { d7.Add(d7, q) } c.smp.g3b = g3b c.smp.qaqb = qaqb r.ModInverse(pb, p) c.smp.papb = new(big.Int).Mul(pa, r) c.smp.papb.Mod(c.smp.papb, p) c.smp.ra = ra out.typ = tlvTypeSMP3 out.data = appendU32(out.data, 8) out.data = appendMPIs(out.data, pa, qa, cp, d5, d6, ra, cr, d7) return } func (c *Conversation) processSMP3(mpis []*big.Int) (out tlv, err error) { if len(mpis) != 8 { err = errors.New("otr: incorrect number of arguments in SMP3 message") return } pa := mpis[0] qa := mpis[1] cp := mpis[2] d5 := mpis[3] d6 := mpis[4] ra := mpis[5] cr := mpis[6] d7 := mpis[7] h := sha256.New() r := new(big.Int).Exp(g, d5, p) s := new(big.Int).Exp(c.smp.g2, d6, p) r.Mul(r, s) s.Exp(qa, cp, p) r.Mul(r, s) r.Mod(r, p) s.Exp(c.smp.g3, d5, p) t := new(big.Int).Exp(pa, cp, p) s.Mul(s, t) s.Mod(s, p) t.SetBytes(hashMPIs(h, 6, s, r)) if t.Cmp(cp) != 0 { err = errors.New("otr: ZKP cP failed in SMP3 message") return } r.ModInverse(c.smp.qb, p) qaqb := new(big.Int).Mul(qa, r) qaqb.Mod(qaqb, p) r.Exp(qaqb, d7, p) s.Exp(ra, cr, p) r.Mul(r, s) r.Mod(r, p) s.Exp(g, d7, p) t.Exp(c.smp.g3a, cr, p) s.Mul(s, t) s.Mod(s, p) t.SetBytes(hashMPIs(h, 7, s, r)) if t.Cmp(cr) != 0 { err = errors.New("otr: ZKP cR failed in SMP3 message") return } var randBuf [16]byte r7 := c.randMPI(randBuf[:]) rb := new(big.Int).Exp(qaqb, c.smp.b3, p) r.Exp(qaqb, r7, p) s.Exp(g, r7, p) cr = new(big.Int).SetBytes(hashMPIs(h, 8, s, r)) r.Mul(c.smp.b3, cr) d7 = new(big.Int).Sub(r7, r) d7.Mod(d7, q) if d7.Sign() < 0 { d7.Add(d7, q) } out.typ = tlvTypeSMP4 out.data = appendU32(out.data, 3) out.data = appendMPIs(out.data, rb, cr, d7) r.ModInverse(c.smp.pb, p) r.Mul(pa, r) r.Mod(r, p) s.Exp(ra, c.smp.b3, p) if r.Cmp(s) != 0 { err = smpFailureError } return } func (c *Conversation) processSMP4(mpis []*big.Int) error { if len(mpis) != 3 { return errors.New("otr: incorrect number of arguments in SMP4 message") } rb := mpis[0] cr := mpis[1] d7 := mpis[2] h := sha256.New() r := new(big.Int).Exp(c.smp.qaqb, d7, p) s := new(big.Int).Exp(rb, cr, p) r.Mul(r, s) r.Mod(r, p) s.Exp(g, d7, p) t := new(big.Int).Exp(c.smp.g3b, cr, p) s.Mul(s, t) s.Mod(s, p) t.SetBytes(hashMPIs(h, 8, s, r)) if t.Cmp(cr) != 0 { return errors.New("otr: ZKP cR failed in SMP4 message") } r.Exp(rb, c.smp.a3, p) if r.Cmp(c.smp.papb) != 0 { return smpFailureError } return nil } func (c *Conversation) generateSMPAbort() tlv { return tlv{typ: tlvTypeSMPAbort} } func hashMPIs(h hash.Hash, magic byte, mpis ...*big.Int) []byte { if h != nil { h.Reset() } else { h = sha256.New() } h.Write([]byte{magic}) for _, mpi := range mpis { h.Write(appendMPI(nil, mpi)) } return h.Sum(nil) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/otr/otr_test.go���������������������������������������������0000644�0610621�0607500�00000035162�13172163317�024057� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package otr import ( "bufio" "bytes" "crypto/rand" "encoding/hex" "math/big" "os" "os/exec" "testing" ) var isQueryTests = []struct { msg string expectedVersion int }{ {"foo", 0}, {"?OtR", 0}, {"?OtR?", 0}, {"?OTR?", 0}, {"?OTRv?", 0}, {"?OTRv1?", 0}, {"?OTR?v1?", 0}, {"?OTR?v?", 0}, {"?OTR?v2?", 2}, {"?OTRv2?", 2}, {"?OTRv23?", 2}, {"?OTRv23 ?", 0}, } func TestIsQuery(t *testing.T) { for i, test := range isQueryTests { version := isQuery([]byte(test.msg)) if version != test.expectedVersion { t.Errorf("#%d: got %d, want %d", i, version, test.expectedVersion) } } } var alicePrivateKeyHex = "000000000080c81c2cb2eb729b7e6fd48e975a932c638b3a9055478583afa46755683e30102447f6da2d8bec9f386bbb5da6403b0040fee8650b6ab2d7f32c55ab017ae9b6aec8c324ab5844784e9a80e194830d548fb7f09a0410df2c4d5c8bc2b3e9ad484e65412be689cf0834694e0839fb2954021521ffdffb8f5c32c14dbf2020b3ce7500000014da4591d58def96de61aea7b04a8405fe1609308d000000808ddd5cb0b9d66956e3dea5a915d9aba9d8a6e7053b74dadb2fc52f9fe4e5bcc487d2305485ed95fed026ad93f06ebb8c9e8baf693b7887132c7ffdd3b0f72f4002ff4ed56583ca7c54458f8c068ca3e8a4dfa309d1dd5d34e2a4b68e6f4338835e5e0fb4317c9e4c7e4806dafda3ef459cd563775a586dd91b1319f72621bf3f00000080b8147e74d8c45e6318c37731b8b33b984a795b3653c2cd1d65cc99efe097cb7eb2fa49569bab5aab6e8a1c261a27d0f7840a5e80b317e6683042b59b6dceca2879c6ffc877a465be690c15e4a42f9a7588e79b10faac11b1ce3741fcef7aba8ce05327a2c16d279ee1b3d77eb783fb10e3356caa25635331e26dd42b8396c4d00000001420bec691fea37ecea58a5c717142f0b804452f57" var aliceFingerprintHex = "0bb01c360424522e94ee9c346ce877a1a4288b2f" var bobPrivateKeyHex = "000000000080a5138eb3d3eb9c1d85716faecadb718f87d31aaed1157671d7fee7e488f95e8e0ba60ad449ec732710a7dec5190f7182af2e2f98312d98497221dff160fd68033dd4f3a33b7c078d0d9f66e26847e76ca7447d4bab35486045090572863d9e4454777f24d6706f63e02548dfec2d0a620af37bbc1d24f884708a212c343b480d00000014e9c58f0ea21a5e4dfd9f44b6a9f7f6a9961a8fa9000000803c4d111aebd62d3c50c2889d420a32cdf1e98b70affcc1fcf44d59cca2eb019f6b774ef88153fb9b9615441a5fe25ea2d11b74ce922ca0232bd81b3c0fcac2a95b20cb6e6c0c5c1ace2e26f65dc43c751af0edbb10d669890e8ab6beea91410b8b2187af1a8347627a06ecea7e0f772c28aae9461301e83884860c9b656c722f0000008065af8625a555ea0e008cd04743671a3cda21162e83af045725db2eb2bb52712708dc0cc1a84c08b3649b88a966974bde27d8612c2861792ec9f08786a246fcadd6d8d3a81a32287745f309238f47618c2bd7612cb8b02d940571e0f30b96420bcd462ff542901b46109b1e5ad6423744448d20a57818a8cbb1647d0fea3b664e0000001440f9f2eb554cb00d45a5826b54bfa419b6980e48" func TestKeySerialization(t *testing.T) { var priv PrivateKey alicePrivateKey, _ := hex.DecodeString(alicePrivateKeyHex) rest, ok := priv.Parse(alicePrivateKey) if !ok { t.Error("failed to parse private key") } if len(rest) > 0 { t.Error("data remaining after parsing private key") } out := priv.Serialize(nil) if !bytes.Equal(alicePrivateKey, out) { t.Errorf("serialization (%x) is not equal to original (%x)", out, alicePrivateKey) } aliceFingerprint, _ := hex.DecodeString(aliceFingerprintHex) fingerprint := priv.PublicKey.Fingerprint() if !bytes.Equal(aliceFingerprint, fingerprint) { t.Errorf("fingerprint (%x) is not equal to expected value (%x)", fingerprint, aliceFingerprint) } } const libOTRPrivateKey = `(privkeys (account (name "foo@example.com") (protocol prpl-jabber) (private-key (dsa (p #00FC07ABCF0DC916AFF6E9AE47BEF60C7AB9B4D6B2469E436630E36F8A489BE812486A09F30B71224508654940A835301ACC525A4FF133FC152CC53DCC59D65C30A54F1993FE13FE63E5823D4C746DB21B90F9B9C00B49EC7404AB1D929BA7FBA12F2E45C6E0A651689750E8528AB8C031D3561FECEE72EBB4A090D450A9B7A857#) (q #00997BD266EF7B1F60A5C23F3A741F2AEFD07A2081#) (g #535E360E8A95EBA46A4F7DE50AD6E9B2A6DB785A66B64EB9F20338D2A3E8FB0E94725848F1AA6CC567CB83A1CC517EC806F2E92EAE71457E80B2210A189B91250779434B41FC8A8873F6DB94BEA7D177F5D59E7E114EE10A49CFD9CEF88AE43387023B672927BA74B04EB6BBB5E57597766A2F9CE3857D7ACE3E1E3BC1FC6F26#) (y #0AC8670AD767D7A8D9D14CC1AC6744CD7D76F993B77FFD9E39DF01E5A6536EF65E775FCEF2A983E2A19BD6415500F6979715D9FD1257E1FE2B6F5E1E74B333079E7C880D39868462A93454B41877BE62E5EF0A041C2EE9C9E76BD1E12AE25D9628DECB097025DD625EF49C3258A1A3C0FF501E3DC673B76D7BABF349009B6ECF#) (x #14D0345A3562C480A039E3C72764F72D79043216#) ) ) ) )` func TestParseLibOTRPrivateKey(t *testing.T) { var priv PrivateKey if !priv.Import([]byte(libOTRPrivateKey)) { t.Fatalf("Failed to import sample private key") } } func TestSignVerify(t *testing.T) { var priv PrivateKey alicePrivateKey, _ := hex.DecodeString(alicePrivateKeyHex) _, ok := priv.Parse(alicePrivateKey) if !ok { t.Error("failed to parse private key") } var msg [32]byte rand.Reader.Read(msg[:]) sig := priv.Sign(rand.Reader, msg[:]) rest, ok := priv.PublicKey.Verify(msg[:], sig) if !ok { t.Errorf("signature (%x) of %x failed to verify", sig, msg[:]) } else if len(rest) > 0 { t.Error("signature data remains after verification") } sig[10] ^= 80 _, ok = priv.PublicKey.Verify(msg[:], sig) if ok { t.Errorf("corrupted signature (%x) of %x verified", sig, msg[:]) } } func setupConversation(t *testing.T) (alice, bob *Conversation) { alicePrivateKey, _ := hex.DecodeString(alicePrivateKeyHex) bobPrivateKey, _ := hex.DecodeString(bobPrivateKeyHex) alice, bob = new(Conversation), new(Conversation) alice.PrivateKey = new(PrivateKey) bob.PrivateKey = new(PrivateKey) alice.PrivateKey.Parse(alicePrivateKey) bob.PrivateKey.Parse(bobPrivateKey) alice.FragmentSize = 100 bob.FragmentSize = 100 if alice.IsEncrypted() { t.Error("Alice believes that the conversation is secure before we've started") } if bob.IsEncrypted() { t.Error("Bob believes that the conversation is secure before we've started") } performHandshake(t, alice, bob) return alice, bob } func performHandshake(t *testing.T, alice, bob *Conversation) { var alicesMessage, bobsMessage [][]byte var out []byte var aliceChange, bobChange SecurityChange var err error alicesMessage = append(alicesMessage, []byte(QueryMessage)) for round := 0; len(alicesMessage) > 0 || len(bobsMessage) > 0; round++ { bobsMessage = nil for i, msg := range alicesMessage { out, _, bobChange, bobsMessage, err = bob.Receive(msg) if len(out) > 0 { t.Errorf("Bob generated output during key exchange, round %d, message %d", round, i) } if err != nil { t.Fatalf("Bob returned an error, round %d, message %d (%x): %s", round, i, msg, err) } if len(bobsMessage) > 0 && i != len(alicesMessage)-1 { t.Errorf("Bob produced output while processing a fragment, round %d, message %d", round, i) } } alicesMessage = nil for i, msg := range bobsMessage { out, _, aliceChange, alicesMessage, err = alice.Receive(msg) if len(out) > 0 { t.Errorf("Alice generated output during key exchange, round %d, message %d", round, i) } if err != nil { t.Fatalf("Alice returned an error, round %d, message %d (%x): %s", round, i, msg, err) } if len(alicesMessage) > 0 && i != len(bobsMessage)-1 { t.Errorf("Alice produced output while processing a fragment, round %d, message %d", round, i) } } } if aliceChange != NewKeys { t.Errorf("Alice terminated without signaling new keys") } if bobChange != NewKeys { t.Errorf("Bob terminated without signaling new keys") } if !bytes.Equal(alice.SSID[:], bob.SSID[:]) { t.Errorf("Session identifiers don't match. Alice has %x, Bob has %x", alice.SSID[:], bob.SSID[:]) } if !alice.IsEncrypted() { t.Error("Alice doesn't believe that the conversation is secure") } if !bob.IsEncrypted() { t.Error("Bob doesn't believe that the conversation is secure") } } const ( firstRoundTrip = iota subsequentRoundTrip noMACKeyCheck ) func roundTrip(t *testing.T, alice, bob *Conversation, message []byte, macKeyCheck int) { alicesMessage, err := alice.Send(message) if err != nil { t.Errorf("Error from Alice sending message: %s", err) } if len(alice.oldMACs) != 0 { t.Errorf("Alice has not revealed all MAC keys") } for i, msg := range alicesMessage { out, encrypted, _, _, err := bob.Receive(msg) if err != nil { t.Errorf("Error generated while processing test message: %s", err.Error()) } if len(out) > 0 { if i != len(alicesMessage)-1 { t.Fatal("Bob produced a message while processing a fragment of Alice's") } if !encrypted { t.Errorf("Message was not marked as encrypted") } if !bytes.Equal(out, message) { t.Errorf("Message corrupted: got %x, want %x", out, message) } } } switch macKeyCheck { case firstRoundTrip: if len(bob.oldMACs) != 0 { t.Errorf("Bob should not have MAC keys to reveal") } case subsequentRoundTrip: if len(bob.oldMACs) != 40 { t.Errorf("Bob has %d bytes of MAC keys to reveal, but should have 40", len(bob.oldMACs)) } } bobsMessage, err := bob.Send(message) if err != nil { t.Errorf("Error from Bob sending message: %s", err) } if len(bob.oldMACs) != 0 { t.Errorf("Bob has not revealed all MAC keys") } for i, msg := range bobsMessage { out, encrypted, _, _, err := alice.Receive(msg) if err != nil { t.Errorf("Error generated while processing test message: %s", err.Error()) } if len(out) > 0 { if i != len(bobsMessage)-1 { t.Fatal("Alice produced a message while processing a fragment of Bob's") } if !encrypted { t.Errorf("Message was not marked as encrypted") } if !bytes.Equal(out, message) { t.Errorf("Message corrupted: got %x, want %x", out, message) } } } switch macKeyCheck { case firstRoundTrip: if len(alice.oldMACs) != 20 { t.Errorf("Alice has %d bytes of MAC keys to reveal, but should have 20", len(alice.oldMACs)) } case subsequentRoundTrip: if len(alice.oldMACs) != 40 { t.Errorf("Alice has %d bytes of MAC keys to reveal, but should have 40", len(alice.oldMACs)) } } } func TestConversation(t *testing.T) { alice, bob := setupConversation(t) var testMessages = [][]byte{ []byte("hello"), []byte("bye"), } roundTripType := firstRoundTrip for _, testMessage := range testMessages { roundTrip(t, alice, bob, testMessage, roundTripType) roundTripType = subsequentRoundTrip } } func TestGoodSMP(t *testing.T) { var alice, bob Conversation alice.smp.secret = new(big.Int).SetInt64(42) bob.smp.secret = alice.smp.secret var alicesMessages, bobsMessages []tlv var aliceComplete, bobComplete bool var err error var out tlv alicesMessages = alice.startSMP("") for round := 0; len(alicesMessages) > 0 || len(bobsMessages) > 0; round++ { bobsMessages = bobsMessages[:0] for i, msg := range alicesMessages { out, bobComplete, err = bob.processSMP(msg) if err != nil { t.Errorf("Error from Bob in round %d: %s", round, err) } if bobComplete && i != len(alicesMessages)-1 { t.Errorf("Bob returned a completed signal before processing all of Alice's messages in round %d", round) } if out.typ != 0 { bobsMessages = append(bobsMessages, out) } } alicesMessages = alicesMessages[:0] for i, msg := range bobsMessages { out, aliceComplete, err = alice.processSMP(msg) if err != nil { t.Errorf("Error from Alice in round %d: %s", round, err) } if aliceComplete && i != len(bobsMessages)-1 { t.Errorf("Alice returned a completed signal before processing all of Bob's messages in round %d", round) } if out.typ != 0 { alicesMessages = append(alicesMessages, out) } } } if !aliceComplete || !bobComplete { t.Errorf("SMP completed without both sides reporting success: alice: %v, bob: %v\n", aliceComplete, bobComplete) } } func TestBadSMP(t *testing.T) { var alice, bob Conversation alice.smp.secret = new(big.Int).SetInt64(42) bob.smp.secret = new(big.Int).SetInt64(43) var alicesMessages, bobsMessages []tlv alicesMessages = alice.startSMP("") for round := 0; len(alicesMessages) > 0 || len(bobsMessages) > 0; round++ { bobsMessages = bobsMessages[:0] for _, msg := range alicesMessages { out, complete, _ := bob.processSMP(msg) if complete { t.Errorf("Bob signaled completion in round %d", round) } if out.typ != 0 { bobsMessages = append(bobsMessages, out) } } alicesMessages = alicesMessages[:0] for _, msg := range bobsMessages { out, complete, _ := alice.processSMP(msg) if complete { t.Errorf("Alice signaled completion in round %d", round) } if out.typ != 0 { alicesMessages = append(alicesMessages, out) } } } } func TestRehandshaking(t *testing.T) { alice, bob := setupConversation(t) roundTrip(t, alice, bob, []byte("test"), firstRoundTrip) roundTrip(t, alice, bob, []byte("test 2"), subsequentRoundTrip) roundTrip(t, alice, bob, []byte("test 3"), subsequentRoundTrip) roundTrip(t, alice, bob, []byte("test 4"), subsequentRoundTrip) roundTrip(t, alice, bob, []byte("test 5"), subsequentRoundTrip) roundTrip(t, alice, bob, []byte("test 6"), subsequentRoundTrip) roundTrip(t, alice, bob, []byte("test 7"), subsequentRoundTrip) roundTrip(t, alice, bob, []byte("test 8"), subsequentRoundTrip) performHandshake(t, alice, bob) roundTrip(t, alice, bob, []byte("test"), noMACKeyCheck) roundTrip(t, alice, bob, []byte("test 2"), noMACKeyCheck) } func TestAgainstLibOTR(t *testing.T) { // This test requires otr.c.test to be built as /tmp/a.out. // If enabled, this tests runs forever performing OTR handshakes in a // loop. return alicePrivateKey, _ := hex.DecodeString(alicePrivateKeyHex) var alice Conversation alice.PrivateKey = new(PrivateKey) alice.PrivateKey.Parse(alicePrivateKey) cmd := exec.Command("/tmp/a.out") cmd.Stderr = os.Stderr out, err := cmd.StdinPipe() if err != nil { t.Fatal(err) } defer out.Close() stdout, err := cmd.StdoutPipe() if err != nil { t.Fatal(err) } in := bufio.NewReader(stdout) if err := cmd.Start(); err != nil { t.Fatal(err) } out.Write([]byte(QueryMessage)) out.Write([]byte("\n")) var expectedText = []byte("test message") for { line, isPrefix, err := in.ReadLine() if isPrefix { t.Fatal("line from subprocess too long") } if err != nil { t.Fatal(err) } text, encrypted, change, alicesMessage, err := alice.Receive(line) if err != nil { t.Fatal(err) } for _, msg := range alicesMessage { out.Write(msg) out.Write([]byte("\n")) } if change == NewKeys { alicesMessage, err := alice.Send([]byte("Go -> libotr test message")) if err != nil { t.Fatalf("error sending message: %s", err.Error()) } else { for _, msg := range alicesMessage { out.Write(msg) out.Write([]byte("\n")) } } } if len(text) > 0 { if !bytes.Equal(text, expectedText) { t.Fatalf("expected %x, but got %x", expectedText, text) } if !encrypted { t.Fatal("message wasn't encrypted") } } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/otr/otr.go��������������������������������������������������0000644�0610621�0607500�00000106245�13172163317�023021� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package otr implements the Off The Record protocol as specified in // http://www.cypherpunks.ca/otr/Protocol-v2-3.1.0.html package otr // import "golang.org/x/crypto/otr" import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/dsa" "crypto/hmac" "crypto/rand" "crypto/sha1" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/hex" "errors" "hash" "io" "math/big" "strconv" ) // SecurityChange describes a change in the security state of a Conversation. type SecurityChange int const ( NoChange SecurityChange = iota // NewKeys indicates that a key exchange has completed. This occurs // when a conversation first becomes encrypted, and when the keys are // renegotiated within an encrypted conversation. NewKeys // SMPSecretNeeded indicates that the peer has started an // authentication and that we need to supply a secret. Call SMPQuestion // to get the optional, human readable challenge and then Authenticate // to supply the matching secret. SMPSecretNeeded // SMPComplete indicates that an authentication completed. The identity // of the peer has now been confirmed. SMPComplete // SMPFailed indicates that an authentication failed. SMPFailed // ConversationEnded indicates that the peer ended the secure // conversation. ConversationEnded ) // QueryMessage can be sent to a peer to start an OTR conversation. var QueryMessage = "?OTRv2?" // ErrorPrefix can be used to make an OTR error by appending an error message // to it. var ErrorPrefix = "?OTR Error:" var ( fragmentPartSeparator = []byte(",") fragmentPrefix = []byte("?OTR,") msgPrefix = []byte("?OTR:") queryMarker = []byte("?OTR") ) // isQuery attempts to parse an OTR query from msg and returns the greatest // common version, or 0 if msg is not an OTR query. func isQuery(msg []byte) (greatestCommonVersion int) { pos := bytes.Index(msg, queryMarker) if pos == -1 { return 0 } for i, c := range msg[pos+len(queryMarker):] { if i == 0 { if c == '?' { // Indicates support for version 1, but we don't // implement that. continue } if c != 'v' { // Invalid message return 0 } continue } if c == '?' { // End of message return } if c == ' ' || c == '\t' { // Probably an invalid message return 0 } if c == '2' { greatestCommonVersion = 2 } } return 0 } const ( statePlaintext = iota stateEncrypted stateFinished ) const ( authStateNone = iota authStateAwaitingDHKey authStateAwaitingRevealSig authStateAwaitingSig ) const ( msgTypeDHCommit = 2 msgTypeData = 3 msgTypeDHKey = 10 msgTypeRevealSig = 17 msgTypeSig = 18 ) const ( // If the requested fragment size is less than this, it will be ignored. minFragmentSize = 18 // Messages are padded to a multiple of this number of bytes. paddingGranularity = 256 // The number of bytes in a Diffie-Hellman private value (320-bits). dhPrivateBytes = 40 // The number of bytes needed to represent an element of the DSA // subgroup (160-bits). dsaSubgroupBytes = 20 // The number of bytes of the MAC that are sent on the wire (160-bits). macPrefixBytes = 20 ) // These are the global, common group parameters for OTR. var ( p *big.Int // group prime g *big.Int // group generator q *big.Int // group order pMinus2 *big.Int ) func init() { p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16) q, _ = new(big.Int).SetString("7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA36046511B993FFFFFFFFFFFFFFFF", 16) g = new(big.Int).SetInt64(2) pMinus2 = new(big.Int).Sub(p, g) } // Conversation represents a relation with a peer. The zero value is a valid // Conversation, although PrivateKey must be set. // // When communicating with a peer, all inbound messages should be passed to // Conversation.Receive and all outbound messages to Conversation.Send. The // Conversation will take care of maintaining the encryption state and // negotiating encryption as needed. type Conversation struct { // PrivateKey contains the private key to use to sign key exchanges. PrivateKey *PrivateKey // Rand can be set to override the entropy source. Otherwise, // crypto/rand will be used. Rand io.Reader // If FragmentSize is set, all messages produced by Receive and Send // will be fragmented into messages of, at most, this number of bytes. FragmentSize int // Once Receive has returned NewKeys once, the following fields are // valid. SSID [8]byte TheirPublicKey PublicKey state, authState int r [16]byte x, y *big.Int gx, gy *big.Int gxBytes []byte digest [sha256.Size]byte revealKeys, sigKeys akeKeys myKeyId uint32 myCurrentDHPub *big.Int myCurrentDHPriv *big.Int myLastDHPub *big.Int myLastDHPriv *big.Int theirKeyId uint32 theirCurrentDHPub *big.Int theirLastDHPub *big.Int keySlots [4]keySlot myCounter [8]byte theirLastCtr [8]byte oldMACs []byte k, n int // fragment state frag []byte smp smpState } // A keySlot contains key material for a specific (their keyid, my keyid) pair. type keySlot struct { // used is true if this slot is valid. If false, it's free for reuse. used bool theirKeyId uint32 myKeyId uint32 sendAESKey, recvAESKey []byte sendMACKey, recvMACKey []byte theirLastCtr [8]byte } // akeKeys are generated during key exchange. There's one set for the reveal // signature message and another for the signature message. In the protocol // spec the latter are indicated with a prime mark. type akeKeys struct { c [16]byte m1, m2 [32]byte } func (c *Conversation) rand() io.Reader { if c.Rand != nil { return c.Rand } return rand.Reader } func (c *Conversation) randMPI(buf []byte) *big.Int { _, err := io.ReadFull(c.rand(), buf) if err != nil { panic("otr: short read from random source") } return new(big.Int).SetBytes(buf) } // tlv represents the type-length value from the protocol. type tlv struct { typ, length uint16 data []byte } const ( tlvTypePadding = 0 tlvTypeDisconnected = 1 tlvTypeSMP1 = 2 tlvTypeSMP2 = 3 tlvTypeSMP3 = 4 tlvTypeSMP4 = 5 tlvTypeSMPAbort = 6 tlvTypeSMP1WithQuestion = 7 ) // Receive handles a message from a peer. It returns a human readable message, // an indicator of whether that message was encrypted, a hint about the // encryption state and zero or more messages to send back to the peer. // These messages do not need to be passed to Send before transmission. func (c *Conversation) Receive(in []byte) (out []byte, encrypted bool, change SecurityChange, toSend [][]byte, err error) { if bytes.HasPrefix(in, fragmentPrefix) { in, err = c.processFragment(in) if in == nil || err != nil { return } } if bytes.HasPrefix(in, msgPrefix) && in[len(in)-1] == '.' { in = in[len(msgPrefix) : len(in)-1] } else if version := isQuery(in); version > 0 { c.authState = authStateAwaitingDHKey c.reset() toSend = c.encode(c.generateDHCommit()) return } else { // plaintext message out = in return } msg := make([]byte, base64.StdEncoding.DecodedLen(len(in))) msgLen, err := base64.StdEncoding.Decode(msg, in) if err != nil { err = errors.New("otr: invalid base64 encoding in message") return } msg = msg[:msgLen] // The first two bytes are the protocol version (2) if len(msg) < 3 || msg[0] != 0 || msg[1] != 2 { err = errors.New("otr: invalid OTR message") return } msgType := int(msg[2]) msg = msg[3:] switch msgType { case msgTypeDHCommit: switch c.authState { case authStateNone: c.authState = authStateAwaitingRevealSig if err = c.processDHCommit(msg); err != nil { return } c.reset() toSend = c.encode(c.generateDHKey()) return case authStateAwaitingDHKey: // This is a 'SYN-crossing'. The greater digest wins. var cmp int if cmp, err = c.compareToDHCommit(msg); err != nil { return } if cmp > 0 { // We win. Retransmit DH commit. toSend = c.encode(c.serializeDHCommit()) return } else { // They win. We forget about our DH commit. c.authState = authStateAwaitingRevealSig if err = c.processDHCommit(msg); err != nil { return } c.reset() toSend = c.encode(c.generateDHKey()) return } case authStateAwaitingRevealSig: if err = c.processDHCommit(msg); err != nil { return } toSend = c.encode(c.serializeDHKey()) case authStateAwaitingSig: if err = c.processDHCommit(msg); err != nil { return } c.reset() toSend = c.encode(c.generateDHKey()) c.authState = authStateAwaitingRevealSig default: panic("bad state") } case msgTypeDHKey: switch c.authState { case authStateAwaitingDHKey: var isSame bool if isSame, err = c.processDHKey(msg); err != nil { return } if isSame { err = errors.New("otr: unexpected duplicate DH key") return } toSend = c.encode(c.generateRevealSig()) c.authState = authStateAwaitingSig case authStateAwaitingSig: var isSame bool if isSame, err = c.processDHKey(msg); err != nil { return } if isSame { toSend = c.encode(c.serializeDHKey()) } } case msgTypeRevealSig: if c.authState != authStateAwaitingRevealSig { return } if err = c.processRevealSig(msg); err != nil { return } toSend = c.encode(c.generateSig()) c.authState = authStateNone c.state = stateEncrypted change = NewKeys case msgTypeSig: if c.authState != authStateAwaitingSig { return } if err = c.processSig(msg); err != nil { return } c.authState = authStateNone c.state = stateEncrypted change = NewKeys case msgTypeData: if c.state != stateEncrypted { err = errors.New("otr: encrypted message received without encrypted session established") return } var tlvs []tlv out, tlvs, err = c.processData(msg) encrypted = true EachTLV: for _, inTLV := range tlvs { switch inTLV.typ { case tlvTypeDisconnected: change = ConversationEnded c.state = stateFinished break EachTLV case tlvTypeSMP1, tlvTypeSMP2, tlvTypeSMP3, tlvTypeSMP4, tlvTypeSMPAbort, tlvTypeSMP1WithQuestion: var reply tlv var complete bool reply, complete, err = c.processSMP(inTLV) if err == smpSecretMissingError { err = nil change = SMPSecretNeeded c.smp.saved = &inTLV return } if err == smpFailureError { err = nil change = SMPFailed } else if complete { change = SMPComplete } if reply.typ != 0 { toSend = c.encode(c.generateData(nil, &reply)) } break EachTLV default: // skip unknown TLVs } } default: err = errors.New("otr: unknown message type " + strconv.Itoa(msgType)) } return } // Send takes a human readable message from the local user, possibly encrypts // it and returns zero one or more messages to send to the peer. func (c *Conversation) Send(msg []byte) ([][]byte, error) { switch c.state { case statePlaintext: return [][]byte{msg}, nil case stateEncrypted: return c.encode(c.generateData(msg, nil)), nil case stateFinished: return nil, errors.New("otr: cannot send message because secure conversation has finished") } return nil, errors.New("otr: cannot send message in current state") } // SMPQuestion returns the human readable challenge question from the peer. // It's only valid after Receive has returned SMPSecretNeeded. func (c *Conversation) SMPQuestion() string { return c.smp.question } // Authenticate begins an authentication with the peer. Authentication involves // an optional challenge message and a shared secret. The authentication // proceeds until either Receive returns SMPComplete, SMPSecretNeeded (which // indicates that a new authentication is happening and thus this one was // aborted) or SMPFailed. func (c *Conversation) Authenticate(question string, mutualSecret []byte) (toSend [][]byte, err error) { if c.state != stateEncrypted { err = errors.New("otr: can't authenticate a peer without a secure conversation established") return } if c.smp.saved != nil { c.calcSMPSecret(mutualSecret, false /* they started it */) var out tlv var complete bool out, complete, err = c.processSMP(*c.smp.saved) if complete { panic("SMP completed on the first message") } c.smp.saved = nil if out.typ != 0 { toSend = c.encode(c.generateData(nil, &out)) } return } c.calcSMPSecret(mutualSecret, true /* we started it */) outs := c.startSMP(question) for _, out := range outs { toSend = append(toSend, c.encode(c.generateData(nil, &out))...) } return } // End ends a secure conversation by generating a termination message for // the peer and switches to unencrypted communication. func (c *Conversation) End() (toSend [][]byte) { switch c.state { case statePlaintext: return nil case stateEncrypted: c.state = statePlaintext return c.encode(c.generateData(nil, &tlv{typ: tlvTypeDisconnected})) case stateFinished: c.state = statePlaintext return nil } panic("unreachable") } // IsEncrypted returns true if a message passed to Send would be encrypted // before transmission. This result remains valid until the next call to // Receive or End, which may change the state of the Conversation. func (c *Conversation) IsEncrypted() bool { return c.state == stateEncrypted } var fragmentError = errors.New("otr: invalid OTR fragment") // processFragment processes a fragmented OTR message and possibly returns a // complete message. Fragmented messages look like "?OTR,k,n,msg," where k is // the fragment number (starting from 1), n is the number of fragments in this // message and msg is a substring of the base64 encoded message. func (c *Conversation) processFragment(in []byte) (out []byte, err error) { in = in[len(fragmentPrefix):] // remove "?OTR," parts := bytes.Split(in, fragmentPartSeparator) if len(parts) != 4 || len(parts[3]) != 0 { return nil, fragmentError } k, err := strconv.Atoi(string(parts[0])) if err != nil { return nil, fragmentError } n, err := strconv.Atoi(string(parts[1])) if err != nil { return nil, fragmentError } if k < 1 || n < 1 || k > n { return nil, fragmentError } if k == 1 { c.frag = append(c.frag[:0], parts[2]...) c.k, c.n = k, n } else if n == c.n && k == c.k+1 { c.frag = append(c.frag, parts[2]...) c.k++ } else { c.frag = c.frag[:0] c.n, c.k = 0, 0 } if c.n > 0 && c.k == c.n { c.n, c.k = 0, 0 return c.frag, nil } return nil, nil } func (c *Conversation) generateDHCommit() []byte { _, err := io.ReadFull(c.rand(), c.r[:]) if err != nil { panic("otr: short read from random source") } var xBytes [dhPrivateBytes]byte c.x = c.randMPI(xBytes[:]) c.gx = new(big.Int).Exp(g, c.x, p) c.gy = nil c.gxBytes = appendMPI(nil, c.gx) h := sha256.New() h.Write(c.gxBytes) h.Sum(c.digest[:0]) aesCipher, err := aes.NewCipher(c.r[:]) if err != nil { panic(err.Error()) } var iv [aes.BlockSize]byte ctr := cipher.NewCTR(aesCipher, iv[:]) ctr.XORKeyStream(c.gxBytes, c.gxBytes) return c.serializeDHCommit() } func (c *Conversation) serializeDHCommit() []byte { var ret []byte ret = appendU16(ret, 2) // protocol version ret = append(ret, msgTypeDHCommit) ret = appendData(ret, c.gxBytes) ret = appendData(ret, c.digest[:]) return ret } func (c *Conversation) processDHCommit(in []byte) error { var ok1, ok2 bool c.gxBytes, in, ok1 = getData(in) digest, in, ok2 := getData(in) if !ok1 || !ok2 || len(in) > 0 { return errors.New("otr: corrupt DH commit message") } copy(c.digest[:], digest) return nil } func (c *Conversation) compareToDHCommit(in []byte) (int, error) { _, in, ok1 := getData(in) digest, in, ok2 := getData(in) if !ok1 || !ok2 || len(in) > 0 { return 0, errors.New("otr: corrupt DH commit message") } return bytes.Compare(c.digest[:], digest), nil } func (c *Conversation) generateDHKey() []byte { var yBytes [dhPrivateBytes]byte c.y = c.randMPI(yBytes[:]) c.gy = new(big.Int).Exp(g, c.y, p) return c.serializeDHKey() } func (c *Conversation) serializeDHKey() []byte { var ret []byte ret = appendU16(ret, 2) // protocol version ret = append(ret, msgTypeDHKey) ret = appendMPI(ret, c.gy) return ret } func (c *Conversation) processDHKey(in []byte) (isSame bool, err error) { gy, in, ok := getMPI(in) if !ok { err = errors.New("otr: corrupt DH key message") return } if gy.Cmp(g) < 0 || gy.Cmp(pMinus2) > 0 { err = errors.New("otr: DH value out of range") return } if c.gy != nil { isSame = c.gy.Cmp(gy) == 0 return } c.gy = gy return } func (c *Conversation) generateEncryptedSignature(keys *akeKeys, xFirst bool) ([]byte, []byte) { var xb []byte xb = c.PrivateKey.PublicKey.Serialize(xb) var verifyData []byte if xFirst { verifyData = appendMPI(verifyData, c.gx) verifyData = appendMPI(verifyData, c.gy) } else { verifyData = appendMPI(verifyData, c.gy) verifyData = appendMPI(verifyData, c.gx) } verifyData = append(verifyData, xb...) verifyData = appendU32(verifyData, c.myKeyId) mac := hmac.New(sha256.New, keys.m1[:]) mac.Write(verifyData) mb := mac.Sum(nil) xb = appendU32(xb, c.myKeyId) xb = append(xb, c.PrivateKey.Sign(c.rand(), mb)...) aesCipher, err := aes.NewCipher(keys.c[:]) if err != nil { panic(err.Error()) } var iv [aes.BlockSize]byte ctr := cipher.NewCTR(aesCipher, iv[:]) ctr.XORKeyStream(xb, xb) mac = hmac.New(sha256.New, keys.m2[:]) encryptedSig := appendData(nil, xb) mac.Write(encryptedSig) return encryptedSig, mac.Sum(nil) } func (c *Conversation) generateRevealSig() []byte { s := new(big.Int).Exp(c.gy, c.x, p) c.calcAKEKeys(s) c.myKeyId++ encryptedSig, mac := c.generateEncryptedSignature(&c.revealKeys, true /* gx comes first */) c.myCurrentDHPub = c.gx c.myCurrentDHPriv = c.x c.rotateDHKeys() incCounter(&c.myCounter) var ret []byte ret = appendU16(ret, 2) ret = append(ret, msgTypeRevealSig) ret = appendData(ret, c.r[:]) ret = append(ret, encryptedSig...) ret = append(ret, mac[:20]...) return ret } func (c *Conversation) processEncryptedSig(encryptedSig, theirMAC []byte, keys *akeKeys, xFirst bool) error { mac := hmac.New(sha256.New, keys.m2[:]) mac.Write(appendData(nil, encryptedSig)) myMAC := mac.Sum(nil)[:20] if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 { return errors.New("bad signature MAC in encrypted signature") } aesCipher, err := aes.NewCipher(keys.c[:]) if err != nil { panic(err.Error()) } var iv [aes.BlockSize]byte ctr := cipher.NewCTR(aesCipher, iv[:]) ctr.XORKeyStream(encryptedSig, encryptedSig) sig := encryptedSig sig, ok1 := c.TheirPublicKey.Parse(sig) keyId, sig, ok2 := getU32(sig) if !ok1 || !ok2 { return errors.New("otr: corrupt encrypted signature") } var verifyData []byte if xFirst { verifyData = appendMPI(verifyData, c.gx) verifyData = appendMPI(verifyData, c.gy) } else { verifyData = appendMPI(verifyData, c.gy) verifyData = appendMPI(verifyData, c.gx) } verifyData = c.TheirPublicKey.Serialize(verifyData) verifyData = appendU32(verifyData, keyId) mac = hmac.New(sha256.New, keys.m1[:]) mac.Write(verifyData) mb := mac.Sum(nil) sig, ok1 = c.TheirPublicKey.Verify(mb, sig) if !ok1 { return errors.New("bad signature in encrypted signature") } if len(sig) > 0 { return errors.New("corrupt encrypted signature") } c.theirKeyId = keyId zero(c.theirLastCtr[:]) return nil } func (c *Conversation) processRevealSig(in []byte) error { r, in, ok1 := getData(in) encryptedSig, in, ok2 := getData(in) theirMAC := in if !ok1 || !ok2 || len(theirMAC) != 20 { return errors.New("otr: corrupt reveal signature message") } aesCipher, err := aes.NewCipher(r) if err != nil { return errors.New("otr: cannot create AES cipher from reveal signature message: " + err.Error()) } var iv [aes.BlockSize]byte ctr := cipher.NewCTR(aesCipher, iv[:]) ctr.XORKeyStream(c.gxBytes, c.gxBytes) h := sha256.New() h.Write(c.gxBytes) digest := h.Sum(nil) if len(digest) != len(c.digest) || subtle.ConstantTimeCompare(digest, c.digest[:]) == 0 { return errors.New("otr: bad commit MAC in reveal signature message") } var rest []byte c.gx, rest, ok1 = getMPI(c.gxBytes) if !ok1 || len(rest) > 0 { return errors.New("otr: gx corrupt after decryption") } if c.gx.Cmp(g) < 0 || c.gx.Cmp(pMinus2) > 0 { return errors.New("otr: DH value out of range") } s := new(big.Int).Exp(c.gx, c.y, p) c.calcAKEKeys(s) if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.revealKeys, true /* gx comes first */); err != nil { return errors.New("otr: in reveal signature message: " + err.Error()) } c.theirCurrentDHPub = c.gx c.theirLastDHPub = nil return nil } func (c *Conversation) generateSig() []byte { c.myKeyId++ encryptedSig, mac := c.generateEncryptedSignature(&c.sigKeys, false /* gy comes first */) c.myCurrentDHPub = c.gy c.myCurrentDHPriv = c.y c.rotateDHKeys() incCounter(&c.myCounter) var ret []byte ret = appendU16(ret, 2) ret = append(ret, msgTypeSig) ret = append(ret, encryptedSig...) ret = append(ret, mac[:macPrefixBytes]...) return ret } func (c *Conversation) processSig(in []byte) error { encryptedSig, in, ok1 := getData(in) theirMAC := in if !ok1 || len(theirMAC) != macPrefixBytes { return errors.New("otr: corrupt signature message") } if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.sigKeys, false /* gy comes first */); err != nil { return errors.New("otr: in signature message: " + err.Error()) } c.theirCurrentDHPub = c.gy c.theirLastDHPub = nil return nil } func (c *Conversation) rotateDHKeys() { // evict slots using our retired key id for i := range c.keySlots { slot := &c.keySlots[i] if slot.used && slot.myKeyId == c.myKeyId-1 { slot.used = false c.oldMACs = append(c.oldMACs, slot.recvMACKey...) } } c.myLastDHPriv = c.myCurrentDHPriv c.myLastDHPub = c.myCurrentDHPub var xBytes [dhPrivateBytes]byte c.myCurrentDHPriv = c.randMPI(xBytes[:]) c.myCurrentDHPub = new(big.Int).Exp(g, c.myCurrentDHPriv, p) c.myKeyId++ } func (c *Conversation) processData(in []byte) (out []byte, tlvs []tlv, err error) { origIn := in flags, in, ok1 := getU8(in) theirKeyId, in, ok2 := getU32(in) myKeyId, in, ok3 := getU32(in) y, in, ok4 := getMPI(in) counter, in, ok5 := getNBytes(in, 8) encrypted, in, ok6 := getData(in) macedData := origIn[:len(origIn)-len(in)] theirMAC, in, ok7 := getNBytes(in, macPrefixBytes) _, in, ok8 := getData(in) if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 || !ok7 || !ok8 || len(in) > 0 { err = errors.New("otr: corrupt data message") return } ignoreErrors := flags&1 != 0 slot, err := c.calcDataKeys(myKeyId, theirKeyId) if err != nil { if ignoreErrors { err = nil } return } mac := hmac.New(sha1.New, slot.recvMACKey) mac.Write([]byte{0, 2, 3}) mac.Write(macedData) myMAC := mac.Sum(nil) if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 { if !ignoreErrors { err = errors.New("otr: bad MAC on data message") } return } if bytes.Compare(counter, slot.theirLastCtr[:]) <= 0 { err = errors.New("otr: counter regressed") return } copy(slot.theirLastCtr[:], counter) var iv [aes.BlockSize]byte copy(iv[:], counter) aesCipher, err := aes.NewCipher(slot.recvAESKey) if err != nil { panic(err.Error()) } ctr := cipher.NewCTR(aesCipher, iv[:]) ctr.XORKeyStream(encrypted, encrypted) decrypted := encrypted if myKeyId == c.myKeyId { c.rotateDHKeys() } if theirKeyId == c.theirKeyId { // evict slots using their retired key id for i := range c.keySlots { slot := &c.keySlots[i] if slot.used && slot.theirKeyId == theirKeyId-1 { slot.used = false c.oldMACs = append(c.oldMACs, slot.recvMACKey...) } } c.theirLastDHPub = c.theirCurrentDHPub c.theirKeyId++ c.theirCurrentDHPub = y } if nulPos := bytes.IndexByte(decrypted, 0); nulPos >= 0 { out = decrypted[:nulPos] tlvData := decrypted[nulPos+1:] for len(tlvData) > 0 { var t tlv var ok1, ok2, ok3 bool t.typ, tlvData, ok1 = getU16(tlvData) t.length, tlvData, ok2 = getU16(tlvData) t.data, tlvData, ok3 = getNBytes(tlvData, int(t.length)) if !ok1 || !ok2 || !ok3 { err = errors.New("otr: corrupt tlv data") return } tlvs = append(tlvs, t) } } else { out = decrypted } return } func (c *Conversation) generateData(msg []byte, extra *tlv) []byte { slot, err := c.calcDataKeys(c.myKeyId-1, c.theirKeyId) if err != nil { panic("otr: failed to generate sending keys: " + err.Error()) } var plaintext []byte plaintext = append(plaintext, msg...) plaintext = append(plaintext, 0) padding := paddingGranularity - ((len(plaintext) + 4) % paddingGranularity) plaintext = appendU16(plaintext, tlvTypePadding) plaintext = appendU16(plaintext, uint16(padding)) for i := 0; i < padding; i++ { plaintext = append(plaintext, 0) } if extra != nil { plaintext = appendU16(plaintext, extra.typ) plaintext = appendU16(plaintext, uint16(len(extra.data))) plaintext = append(plaintext, extra.data...) } encrypted := make([]byte, len(plaintext)) var iv [aes.BlockSize]byte copy(iv[:], c.myCounter[:]) aesCipher, err := aes.NewCipher(slot.sendAESKey) if err != nil { panic(err.Error()) } ctr := cipher.NewCTR(aesCipher, iv[:]) ctr.XORKeyStream(encrypted, plaintext) var ret []byte ret = appendU16(ret, 2) ret = append(ret, msgTypeData) ret = append(ret, 0 /* flags */) ret = appendU32(ret, c.myKeyId-1) ret = appendU32(ret, c.theirKeyId) ret = appendMPI(ret, c.myCurrentDHPub) ret = append(ret, c.myCounter[:]...) ret = appendData(ret, encrypted) mac := hmac.New(sha1.New, slot.sendMACKey) mac.Write(ret) ret = append(ret, mac.Sum(nil)[:macPrefixBytes]...) ret = appendData(ret, c.oldMACs) c.oldMACs = nil incCounter(&c.myCounter) return ret } func incCounter(counter *[8]byte) { for i := 7; i >= 0; i-- { counter[i]++ if counter[i] > 0 { break } } } // calcDataKeys computes the keys used to encrypt a data message given the key // IDs. func (c *Conversation) calcDataKeys(myKeyId, theirKeyId uint32) (slot *keySlot, err error) { // Check for a cache hit. for i := range c.keySlots { slot = &c.keySlots[i] if slot.used && slot.theirKeyId == theirKeyId && slot.myKeyId == myKeyId { return } } // Find an empty slot to write into. slot = nil for i := range c.keySlots { if !c.keySlots[i].used { slot = &c.keySlots[i] break } } if slot == nil { return nil, errors.New("otr: internal error: no more key slots") } var myPriv, myPub, theirPub *big.Int if myKeyId == c.myKeyId { myPriv = c.myCurrentDHPriv myPub = c.myCurrentDHPub } else if myKeyId == c.myKeyId-1 { myPriv = c.myLastDHPriv myPub = c.myLastDHPub } else { err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when I'm on " + strconv.FormatUint(uint64(c.myKeyId), 10)) return } if theirKeyId == c.theirKeyId { theirPub = c.theirCurrentDHPub } else if theirKeyId == c.theirKeyId-1 && c.theirLastDHPub != nil { theirPub = c.theirLastDHPub } else { err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when they're on " + strconv.FormatUint(uint64(c.myKeyId), 10)) return } var sendPrefixByte, recvPrefixByte [1]byte if myPub.Cmp(theirPub) > 0 { // we're the high end sendPrefixByte[0], recvPrefixByte[0] = 1, 2 } else { // we're the low end sendPrefixByte[0], recvPrefixByte[0] = 2, 1 } s := new(big.Int).Exp(theirPub, myPriv, p) sBytes := appendMPI(nil, s) h := sha1.New() h.Write(sendPrefixByte[:]) h.Write(sBytes) slot.sendAESKey = h.Sum(slot.sendAESKey[:0])[:16] h.Reset() h.Write(slot.sendAESKey) slot.sendMACKey = h.Sum(slot.sendMACKey[:0]) h.Reset() h.Write(recvPrefixByte[:]) h.Write(sBytes) slot.recvAESKey = h.Sum(slot.recvAESKey[:0])[:16] h.Reset() h.Write(slot.recvAESKey) slot.recvMACKey = h.Sum(slot.recvMACKey[:0]) slot.theirKeyId = theirKeyId slot.myKeyId = myKeyId slot.used = true zero(slot.theirLastCtr[:]) return } func (c *Conversation) calcAKEKeys(s *big.Int) { mpi := appendMPI(nil, s) h := sha256.New() var cBytes [32]byte hashWithPrefix(c.SSID[:], 0, mpi, h) hashWithPrefix(cBytes[:], 1, mpi, h) copy(c.revealKeys.c[:], cBytes[:16]) copy(c.sigKeys.c[:], cBytes[16:]) hashWithPrefix(c.revealKeys.m1[:], 2, mpi, h) hashWithPrefix(c.revealKeys.m2[:], 3, mpi, h) hashWithPrefix(c.sigKeys.m1[:], 4, mpi, h) hashWithPrefix(c.sigKeys.m2[:], 5, mpi, h) } func hashWithPrefix(out []byte, prefix byte, in []byte, h hash.Hash) { h.Reset() var p [1]byte p[0] = prefix h.Write(p[:]) h.Write(in) if len(out) == h.Size() { h.Sum(out[:0]) } else { digest := h.Sum(nil) copy(out, digest) } } func (c *Conversation) encode(msg []byte) [][]byte { b64 := make([]byte, base64.StdEncoding.EncodedLen(len(msg))+len(msgPrefix)+1) base64.StdEncoding.Encode(b64[len(msgPrefix):], msg) copy(b64, msgPrefix) b64[len(b64)-1] = '.' if c.FragmentSize < minFragmentSize || len(b64) <= c.FragmentSize { // We can encode this in a single fragment. return [][]byte{b64} } // We have to fragment this message. var ret [][]byte bytesPerFragment := c.FragmentSize - minFragmentSize numFragments := (len(b64) + bytesPerFragment) / bytesPerFragment for i := 0; i < numFragments; i++ { frag := []byte("?OTR," + strconv.Itoa(i+1) + "," + strconv.Itoa(numFragments) + ",") todo := bytesPerFragment if todo > len(b64) { todo = len(b64) } frag = append(frag, b64[:todo]...) b64 = b64[todo:] frag = append(frag, ',') ret = append(ret, frag) } return ret } func (c *Conversation) reset() { c.myKeyId = 0 for i := range c.keySlots { c.keySlots[i].used = false } } type PublicKey struct { dsa.PublicKey } func (pk *PublicKey) Parse(in []byte) ([]byte, bool) { var ok bool var pubKeyType uint16 if pubKeyType, in, ok = getU16(in); !ok || pubKeyType != 0 { return nil, false } if pk.P, in, ok = getMPI(in); !ok { return nil, false } if pk.Q, in, ok = getMPI(in); !ok { return nil, false } if pk.G, in, ok = getMPI(in); !ok { return nil, false } if pk.Y, in, ok = getMPI(in); !ok { return nil, false } return in, true } func (pk *PublicKey) Serialize(in []byte) []byte { in = appendU16(in, 0) in = appendMPI(in, pk.P) in = appendMPI(in, pk.Q) in = appendMPI(in, pk.G) in = appendMPI(in, pk.Y) return in } // Fingerprint returns the 20-byte, binary fingerprint of the PublicKey. func (pk *PublicKey) Fingerprint() []byte { b := pk.Serialize(nil) h := sha1.New() h.Write(b[2:]) return h.Sum(nil) } func (pk *PublicKey) Verify(hashed, sig []byte) ([]byte, bool) { if len(sig) != 2*dsaSubgroupBytes { return nil, false } r := new(big.Int).SetBytes(sig[:dsaSubgroupBytes]) s := new(big.Int).SetBytes(sig[dsaSubgroupBytes:]) ok := dsa.Verify(&pk.PublicKey, hashed, r, s) return sig[dsaSubgroupBytes*2:], ok } type PrivateKey struct { PublicKey dsa.PrivateKey } func (priv *PrivateKey) Sign(rand io.Reader, hashed []byte) []byte { r, s, err := dsa.Sign(rand, &priv.PrivateKey, hashed) if err != nil { panic(err.Error()) } rBytes := r.Bytes() sBytes := s.Bytes() if len(rBytes) > dsaSubgroupBytes || len(sBytes) > dsaSubgroupBytes { panic("DSA signature too large") } out := make([]byte, 2*dsaSubgroupBytes) copy(out[dsaSubgroupBytes-len(rBytes):], rBytes) copy(out[len(out)-len(sBytes):], sBytes) return out } func (priv *PrivateKey) Serialize(in []byte) []byte { in = priv.PublicKey.Serialize(in) in = appendMPI(in, priv.PrivateKey.X) return in } func (priv *PrivateKey) Parse(in []byte) ([]byte, bool) { in, ok := priv.PublicKey.Parse(in) if !ok { return in, ok } priv.PrivateKey.PublicKey = priv.PublicKey.PublicKey priv.PrivateKey.X, in, ok = getMPI(in) return in, ok } func (priv *PrivateKey) Generate(rand io.Reader) { if err := dsa.GenerateParameters(&priv.PrivateKey.PublicKey.Parameters, rand, dsa.L1024N160); err != nil { panic(err.Error()) } if err := dsa.GenerateKey(&priv.PrivateKey, rand); err != nil { panic(err.Error()) } priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey } func notHex(r rune) bool { if r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F' { return false } return true } // Import parses the contents of a libotr private key file. func (priv *PrivateKey) Import(in []byte) bool { mpiStart := []byte(" #") mpis := make([]*big.Int, 5) for i := 0; i < len(mpis); i++ { start := bytes.Index(in, mpiStart) if start == -1 { return false } in = in[start+len(mpiStart):] end := bytes.IndexFunc(in, notHex) if end == -1 { return false } hexBytes := in[:end] in = in[end:] if len(hexBytes)&1 != 0 { return false } mpiBytes := make([]byte, len(hexBytes)/2) if _, err := hex.Decode(mpiBytes, hexBytes); err != nil { return false } mpis[i] = new(big.Int).SetBytes(mpiBytes) } for _, mpi := range mpis { if mpi.Sign() <= 0 { return false } } priv.PrivateKey.P = mpis[0] priv.PrivateKey.Q = mpis[1] priv.PrivateKey.G = mpis[2] priv.PrivateKey.Y = mpis[3] priv.PrivateKey.X = mpis[4] priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey a := new(big.Int).Exp(priv.PrivateKey.G, priv.PrivateKey.X, priv.PrivateKey.P) return a.Cmp(priv.PrivateKey.Y) == 0 } func getU8(in []byte) (uint8, []byte, bool) { if len(in) < 1 { return 0, in, false } return in[0], in[1:], true } func getU16(in []byte) (uint16, []byte, bool) { if len(in) < 2 { return 0, in, false } r := uint16(in[0])<<8 | uint16(in[1]) return r, in[2:], true } func getU32(in []byte) (uint32, []byte, bool) { if len(in) < 4 { return 0, in, false } r := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3]) return r, in[4:], true } func getMPI(in []byte) (*big.Int, []byte, bool) { l, in, ok := getU32(in) if !ok || uint32(len(in)) < l { return nil, in, false } r := new(big.Int).SetBytes(in[:l]) return r, in[l:], true } func getData(in []byte) ([]byte, []byte, bool) { l, in, ok := getU32(in) if !ok || uint32(len(in)) < l { return nil, in, false } return in[:l], in[l:], true } func getNBytes(in []byte, n int) ([]byte, []byte, bool) { if len(in) < n { return nil, in, false } return in[:n], in[n:], true } func appendU16(out []byte, v uint16) []byte { out = append(out, byte(v>>8), byte(v)) return out } func appendU32(out []byte, v uint32) []byte { out = append(out, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) return out } func appendData(out, v []byte) []byte { out = appendU32(out, uint32(len(v))) out = append(out, v...) return out } func appendMPI(out []byte, v *big.Int) []byte { vBytes := v.Bytes() out = appendU32(out, uint32(len(vBytes))) out = append(out, vBytes...) return out } func appendMPIs(out []byte, mpis ...*big.Int) []byte { for _, mpi := range mpis { out = appendMPI(out, mpi) } return out } func zero(b []byte) { for i := range b { b[i] = 0 } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/otr/libotr_test_helper.c������������������������������������0000644�0610621�0607500�00000014012�13172163317�025711� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This code can be compiled and used to test the otr package against libotr. // See otr_test.go. // +build ignore #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <proto.h> #include <message.h> #include <privkey.h> static int g_session_established = 0; OtrlPolicy policy(void *opdata, ConnContext *context) { return OTRL_POLICY_ALWAYS; } int is_logged_in(void *opdata, const char *accountname, const char *protocol, const char *recipient) { return 1; } void inject_message(void *opdata, const char *accountname, const char *protocol, const char *recipient, const char *message) { printf("%s\n", message); fflush(stdout); fprintf(stderr, "libotr helper sent: %s\n", message); } void update_context_list(void *opdata) {} void new_fingerprint(void *opdata, OtrlUserState us, const char *accountname, const char *protocol, const char *username, unsigned char fingerprint[20]) { fprintf(stderr, "NEW FINGERPRINT\n"); g_session_established = 1; } void write_fingerprints(void *opdata) {} void gone_secure(void *opdata, ConnContext *context) {} void gone_insecure(void *opdata, ConnContext *context) {} void still_secure(void *opdata, ConnContext *context, int is_reply) {} int max_message_size(void *opdata, ConnContext *context) { return 99999; } const char *account_name(void *opdata, const char *account, const char *protocol) { return "ACCOUNT"; } void account_name_free(void *opdata, const char *account_name) {} const char *error_message(void *opdata, ConnContext *context, OtrlErrorCode err_code) { return "ERR"; } void error_message_free(void *opdata, const char *msg) {} void resent_msg_prefix_free(void *opdata, const char *prefix) {} void handle_smp_event(void *opdata, OtrlSMPEvent smp_event, ConnContext *context, unsigned short progress_event, char *question) {} void handle_msg_event(void *opdata, OtrlMessageEvent msg_event, ConnContext *context, const char *message, gcry_error_t err) { fprintf(stderr, "msg event: %d %s\n", msg_event, message); } OtrlMessageAppOps uiops = { policy, NULL, is_logged_in, inject_message, update_context_list, new_fingerprint, write_fingerprints, gone_secure, gone_insecure, still_secure, max_message_size, account_name, account_name_free, NULL, /* received_symkey */ error_message, error_message_free, NULL, /* resent_msg_prefix */ resent_msg_prefix_free, handle_smp_event, handle_msg_event, NULL /* create_instag */, NULL /* convert_msg */, NULL /* convert_free */, NULL /* timer_control */, }; static const char kPrivateKeyData[] = "(privkeys (account (name \"account\") (protocol proto) (private-key (dsa " "(p " "#00FC07ABCF0DC916AFF6E9AE47BEF60C7AB9B4D6B2469E436630E36F8A489BE812486A09F" "30B71224508654940A835301ACC525A4FF133FC152CC53DCC59D65C30A54F1993FE13FE63E" "5823D4C746DB21B90F9B9C00B49EC7404AB1D929BA7FBA12F2E45C6E0A651689750E8528AB" "8C031D3561FECEE72EBB4A090D450A9B7A857#) (q " "#00997BD266EF7B1F60A5C23F3A741F2AEFD07A2081#) (g " "#535E360E8A95EBA46A4F7DE50AD6E9B2A6DB785A66B64EB9F20338D2A3E8FB0E94725848F" "1AA6CC567CB83A1CC517EC806F2E92EAE71457E80B2210A189B91250779434B41FC8A8873F" "6DB94BEA7D177F5D59E7E114EE10A49CFD9CEF88AE43387023B672927BA74B04EB6BBB5E57" "597766A2F9CE3857D7ACE3E1E3BC1FC6F26#) (y " "#0AC8670AD767D7A8D9D14CC1AC6744CD7D76F993B77FFD9E39DF01E5A6536EF65E775FCEF" "2A983E2A19BD6415500F6979715D9FD1257E1FE2B6F5E1E74B333079E7C880D39868462A93" "454B41877BE62E5EF0A041C2EE9C9E76BD1E12AE25D9628DECB097025DD625EF49C3258A1A" "3C0FF501E3DC673B76D7BABF349009B6ECF#) (x " "#14D0345A3562C480A039E3C72764F72D79043216#)))))\n"; int main() { OTRL_INIT; // We have to write the private key information to a file because the libotr // API demands a filename to read from. const char *tmpdir = "/tmp"; if (getenv("TMP")) { tmpdir = getenv("TMP"); } char private_key_file[256]; snprintf(private_key_file, sizeof(private_key_file), "%s/libotr_test_helper_privatekeys-XXXXXX", tmpdir); int fd = mkstemp(private_key_file); if (fd == -1) { perror("creating temp file"); } write(fd, kPrivateKeyData, sizeof(kPrivateKeyData) - 1); close(fd); OtrlUserState userstate = otrl_userstate_create(); otrl_privkey_read(userstate, private_key_file); unlink(private_key_file); fprintf(stderr, "libotr helper started\n"); char buf[4096]; for (;;) { char *message = fgets(buf, sizeof(buf), stdin); if (strlen(message) == 0) { break; } message[strlen(message) - 1] = 0; fprintf(stderr, "libotr helper got: %s\n", message); char *newmessage = NULL; OtrlTLV *tlvs; int ignore_message = otrl_message_receiving( userstate, &uiops, NULL, "account", "proto", "peer", message, &newmessage, &tlvs, NULL, NULL, NULL); if (tlvs) { otrl_tlv_free(tlvs); } if (newmessage != NULL) { fprintf(stderr, "libotr got: %s\n", newmessage); otrl_message_free(newmessage); gcry_error_t err; char *newmessage = NULL; err = otrl_message_sending(userstate, &uiops, NULL, "account", "proto", "peer", 0, "test message", NULL, &newmessage, OTRL_FRAGMENT_SEND_SKIP, NULL, NULL, NULL); if (newmessage == NULL) { fprintf(stderr, "libotr didn't encrypt message\n"); return 1; } write(1, newmessage, strlen(newmessage)); write(1, "\n", 1); fprintf(stderr, "libotr sent: %s\n", newmessage); otrl_message_free(newmessage); g_session_established = 0; write(1, "?OTRv2?\n", 8); fprintf(stderr, "libotr sent: ?OTRv2\n"); } } return 0; } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022522� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/write_test.go���������������������������������������0000644�0610621�0607500�00000015322�13172163317�025245� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package openpgp import ( "bytes" "io" "io/ioutil" "testing" "time" "golang.org/x/crypto/openpgp/packet" ) func TestSignDetached(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) out := bytes.NewBuffer(nil) message := bytes.NewBufferString(signedInput) err := DetachSign(out, kring[0], message, nil) if err != nil { t.Error(err) } testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyId) } func TestSignTextDetached(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) out := bytes.NewBuffer(nil) message := bytes.NewBufferString(signedInput) err := DetachSignText(out, kring[0], message, nil) if err != nil { t.Error(err) } testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyId) } func TestSignDetachedDSA(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyPrivateHex)) out := bytes.NewBuffer(nil) message := bytes.NewBufferString(signedInput) err := DetachSign(out, kring[0], message, nil) if err != nil { t.Error(err) } testDetachedSignature(t, kring, out, signedInput, "check", testKey3KeyId) } func TestSignDetachedP256(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(p256TestKeyPrivateHex)) kring[0].PrivateKey.Decrypt([]byte("passphrase")) out := bytes.NewBuffer(nil) message := bytes.NewBufferString(signedInput) err := DetachSign(out, kring[0], message, nil) if err != nil { t.Error(err) } testDetachedSignature(t, kring, out, signedInput, "check", testKeyP256KeyId) } func TestNewEntity(t *testing.T) { if testing.Short() { return } // Check bit-length with no config. e, err := NewEntity("Test User", "test", "test@example.com", nil) if err != nil { t.Errorf("failed to create entity: %s", err) return } bl, err := e.PrimaryKey.BitLength() if err != nil { t.Errorf("failed to find bit length: %s", err) } if int(bl) != defaultRSAKeyBits { t.Errorf("BitLength %v, expected %v", int(bl), defaultRSAKeyBits) } // Check bit-length with a config. cfg := &packet.Config{RSABits: 1024} e, err = NewEntity("Test User", "test", "test@example.com", cfg) if err != nil { t.Errorf("failed to create entity: %s", err) return } bl, err = e.PrimaryKey.BitLength() if err != nil { t.Errorf("failed to find bit length: %s", err) } if int(bl) != cfg.RSABits { t.Errorf("BitLength %v, expected %v", bl, cfg.RSABits) } w := bytes.NewBuffer(nil) if err := e.SerializePrivate(w, nil); err != nil { t.Errorf("failed to serialize entity: %s", err) return } serialized := w.Bytes() el, err := ReadKeyRing(w) if err != nil { t.Errorf("failed to reparse entity: %s", err) return } if len(el) != 1 { t.Errorf("wrong number of entities found, got %d, want 1", len(el)) } w = bytes.NewBuffer(nil) if err := e.SerializePrivate(w, nil); err != nil { t.Errorf("failed to serialize entity second time: %s", err) return } if !bytes.Equal(w.Bytes(), serialized) { t.Errorf("results differed") } } func TestSymmetricEncryption(t *testing.T) { buf := new(bytes.Buffer) plaintext, err := SymmetricallyEncrypt(buf, []byte("testing"), nil, nil) if err != nil { t.Errorf("error writing headers: %s", err) return } message := []byte("hello world\n") _, err = plaintext.Write(message) if err != nil { t.Errorf("error writing to plaintext writer: %s", err) } err = plaintext.Close() if err != nil { t.Errorf("error closing plaintext writer: %s", err) } md, err := ReadMessage(buf, nil, func(keys []Key, symmetric bool) ([]byte, error) { return []byte("testing"), nil }, nil) if err != nil { t.Errorf("error rereading message: %s", err) } messageBuf := bytes.NewBuffer(nil) _, err = io.Copy(messageBuf, md.UnverifiedBody) if err != nil { t.Errorf("error rereading message: %s", err) } if !bytes.Equal(message, messageBuf.Bytes()) { t.Errorf("recovered message incorrect got '%s', want '%s'", messageBuf.Bytes(), message) } } var testEncryptionTests = []struct { keyRingHex string isSigned bool }{ { testKeys1And2PrivateHex, false, }, { testKeys1And2PrivateHex, true, }, { dsaElGamalTestKeysHex, false, }, { dsaElGamalTestKeysHex, true, }, } func TestEncryption(t *testing.T) { for i, test := range testEncryptionTests { kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex)) passphrase := []byte("passphrase") for _, entity := range kring { if entity.PrivateKey != nil && entity.PrivateKey.Encrypted { err := entity.PrivateKey.Decrypt(passphrase) if err != nil { t.Errorf("#%d: failed to decrypt key", i) } } for _, subkey := range entity.Subkeys { if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted { err := subkey.PrivateKey.Decrypt(passphrase) if err != nil { t.Errorf("#%d: failed to decrypt subkey", i) } } } } var signed *Entity if test.isSigned { signed = kring[0] } buf := new(bytes.Buffer) w, err := Encrypt(buf, kring[:1], signed, nil /* no hints */, nil) if err != nil { t.Errorf("#%d: error in Encrypt: %s", i, err) continue } const message = "testing" _, err = w.Write([]byte(message)) if err != nil { t.Errorf("#%d: error writing plaintext: %s", i, err) continue } err = w.Close() if err != nil { t.Errorf("#%d: error closing WriteCloser: %s", i, err) continue } md, err := ReadMessage(buf, kring, nil /* no prompt */, nil) if err != nil { t.Errorf("#%d: error reading message: %s", i, err) continue } testTime, _ := time.Parse("2006-01-02", "2013-07-01") if test.isSigned { signKey, _ := kring[0].signingKey(testTime) expectedKeyId := signKey.PublicKey.KeyId if md.SignedByKeyId != expectedKeyId { t.Errorf("#%d: message signed by wrong key id, got: %v, want: %v", i, *md.SignedBy, expectedKeyId) } if md.SignedBy == nil { t.Errorf("#%d: failed to find the signing Entity", i) } } plaintext, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("#%d: error reading encrypted contents: %s", i, err) continue } encryptKey, _ := kring[0].encryptionKey(testTime) expectedKeyId := encryptKey.PublicKey.KeyId if len(md.EncryptedToKeyIds) != 1 || md.EncryptedToKeyIds[0] != expectedKeyId { t.Errorf("#%d: expected message to be encrypted to %v, but got %#v", i, expectedKeyId, md.EncryptedToKeyIds) } if string(plaintext) != message { t.Errorf("#%d: got: %s, want: %s", i, string(plaintext), message) } if test.isSigned { if md.SignatureError != nil { t.Errorf("#%d: signature error: %s", i, md.SignatureError) } if md.Signature == nil { t.Error("signature missing") } } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/write.go��������������������������������������������0000644�0610621�0607500�00000026630�13172163317�024212� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package openpgp import ( "crypto" "hash" "io" "strconv" "time" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/packet" "golang.org/x/crypto/openpgp/s2k" ) // DetachSign signs message with the private key from signer (which must // already have been decrypted) and writes the signature to w. // If config is nil, sensible defaults will be used. func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { return detachSign(w, signer, message, packet.SigTypeBinary, config) } // ArmoredDetachSign signs message with the private key from signer (which // must already have been decrypted) and writes an armored signature to w. // If config is nil, sensible defaults will be used. func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) { return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config) } // DetachSignText signs message (after canonicalising the line endings) with // the private key from signer (which must already have been decrypted) and // writes the signature to w. // If config is nil, sensible defaults will be used. func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { return detachSign(w, signer, message, packet.SigTypeText, config) } // ArmoredDetachSignText signs message (after canonicalising the line endings) // with the private key from signer (which must already have been decrypted) // and writes an armored signature to w. // If config is nil, sensible defaults will be used. func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { return armoredDetachSign(w, signer, message, packet.SigTypeText, config) } func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { out, err := armor.Encode(w, SignatureType, nil) if err != nil { return } err = detachSign(out, signer, message, sigType, config) if err != nil { return } return out.Close() } func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { if signer.PrivateKey == nil { return errors.InvalidArgumentError("signing key doesn't have a private key") } if signer.PrivateKey.Encrypted { return errors.InvalidArgumentError("signing key is encrypted") } sig := new(packet.Signature) sig.SigType = sigType sig.PubKeyAlgo = signer.PrivateKey.PubKeyAlgo sig.Hash = config.Hash() sig.CreationTime = config.Now() sig.IssuerKeyId = &signer.PrivateKey.KeyId h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType) if err != nil { return } io.Copy(wrappedHash, message) err = sig.Sign(h, signer.PrivateKey, config) if err != nil { return } return sig.Serialize(w) } // FileHints contains metadata about encrypted files. This metadata is, itself, // encrypted. type FileHints struct { // IsBinary can be set to hint that the contents are binary data. IsBinary bool // FileName hints at the name of the file that should be written. It's // truncated to 255 bytes if longer. It may be empty to suggest that the // file should not be written to disk. It may be equal to "_CONSOLE" to // suggest the data should not be written to disk. FileName string // ModTime contains the modification time of the file, or the zero time if not applicable. ModTime time.Time } // SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase. // The resulting WriteCloser must be closed after the contents of the file have // been written. // If config is nil, sensible defaults will be used. func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { if hints == nil { hints = &FileHints{} } key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config) if err != nil { return } w, err := packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), key, config) if err != nil { return } literaldata := w if algo := config.Compression(); algo != packet.CompressionNone { var compConfig *packet.CompressionConfig if config != nil { compConfig = config.CompressionConfig } literaldata, err = packet.SerializeCompressed(w, algo, compConfig) if err != nil { return } } var epochSeconds uint32 if !hints.ModTime.IsZero() { epochSeconds = uint32(hints.ModTime.Unix()) } return packet.SerializeLiteral(literaldata, hints.IsBinary, hints.FileName, epochSeconds) } // intersectPreferences mutates and returns a prefix of a that contains only // the values in the intersection of a and b. The order of a is preserved. func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) { var j int for _, v := range a { for _, v2 := range b { if v == v2 { a[j] = v j++ break } } } return a[:j] } func hashToHashId(h crypto.Hash) uint8 { v, ok := s2k.HashToHashId(h) if !ok { panic("tried to convert unknown hash") } return v } // Encrypt encrypts a message to a number of recipients and, optionally, signs // it. hints contains optional information, that is also encrypted, that aids // the recipients in processing the message. The resulting WriteCloser must // be closed after the contents of the file have been written. // If config is nil, sensible defaults will be used. func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { var signer *packet.PrivateKey if signed != nil { signKey, ok := signed.signingKey(config.Now()) if !ok { return nil, errors.InvalidArgumentError("no valid signing keys") } signer = signKey.PrivateKey if signer == nil { return nil, errors.InvalidArgumentError("no private key in signing key") } if signer.Encrypted { return nil, errors.InvalidArgumentError("signing key must be decrypted") } } // These are the possible ciphers that we'll use for the message. candidateCiphers := []uint8{ uint8(packet.CipherAES128), uint8(packet.CipherAES256), uint8(packet.CipherCAST5), } // These are the possible hash functions that we'll use for the signature. candidateHashes := []uint8{ hashToHashId(crypto.SHA256), hashToHashId(crypto.SHA512), hashToHashId(crypto.SHA1), hashToHashId(crypto.RIPEMD160), } // In the event that a recipient doesn't specify any supported ciphers // or hash functions, these are the ones that we assume that every // implementation supports. defaultCiphers := candidateCiphers[len(candidateCiphers)-1:] defaultHashes := candidateHashes[len(candidateHashes)-1:] encryptKeys := make([]Key, len(to)) for i := range to { var ok bool encryptKeys[i], ok = to[i].encryptionKey(config.Now()) if !ok { return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys") } sig := to[i].primaryIdentity().SelfSignature preferredSymmetric := sig.PreferredSymmetric if len(preferredSymmetric) == 0 { preferredSymmetric = defaultCiphers } preferredHashes := sig.PreferredHash if len(preferredHashes) == 0 { preferredHashes = defaultHashes } candidateCiphers = intersectPreferences(candidateCiphers, preferredSymmetric) candidateHashes = intersectPreferences(candidateHashes, preferredHashes) } if len(candidateCiphers) == 0 || len(candidateHashes) == 0 { return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms") } cipher := packet.CipherFunction(candidateCiphers[0]) // If the cipher specified by config is a candidate, we'll use that. configuredCipher := config.Cipher() for _, c := range candidateCiphers { cipherFunc := packet.CipherFunction(c) if cipherFunc == configuredCipher { cipher = cipherFunc break } } var hash crypto.Hash for _, hashId := range candidateHashes { if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() { hash = h break } } // If the hash specified by config is a candidate, we'll use that. if configuredHash := config.Hash(); configuredHash.Available() { for _, hashId := range candidateHashes { if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash { hash = h break } } } if hash == 0 { hashId := candidateHashes[0] name, ok := s2k.HashIdToString(hashId) if !ok { name = "#" + strconv.Itoa(int(hashId)) } return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)") } symKey := make([]byte, cipher.KeySize()) if _, err := io.ReadFull(config.Random(), symKey); err != nil { return nil, err } for _, key := range encryptKeys { if err := packet.SerializeEncryptedKey(ciphertext, key.PublicKey, cipher, symKey, config); err != nil { return nil, err } } encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config) if err != nil { return } if signer != nil { ops := &packet.OnePassSignature{ SigType: packet.SigTypeBinary, Hash: hash, PubKeyAlgo: signer.PubKeyAlgo, KeyId: signer.KeyId, IsLast: true, } if err := ops.Serialize(encryptedData); err != nil { return nil, err } } if hints == nil { hints = &FileHints{} } w := encryptedData if signer != nil { // If we need to write a signature packet after the literal // data then we need to stop literalData from closing // encryptedData. w = noOpCloser{encryptedData} } var epochSeconds uint32 if !hints.ModTime.IsZero() { epochSeconds = uint32(hints.ModTime.Unix()) } literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds) if err != nil { return nil, err } if signer != nil { return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil } return literalData, nil } // signatureWriter hashes the contents of a message while passing it along to // literalData. When closed, it closes literalData, writes a signature packet // to encryptedData and then also closes encryptedData. type signatureWriter struct { encryptedData io.WriteCloser literalData io.WriteCloser hashType crypto.Hash h hash.Hash signer *packet.PrivateKey config *packet.Config } func (s signatureWriter) Write(data []byte) (int, error) { s.h.Write(data) return s.literalData.Write(data) } func (s signatureWriter) Close() error { sig := &packet.Signature{ SigType: packet.SigTypeBinary, PubKeyAlgo: s.signer.PubKeyAlgo, Hash: s.hashType, CreationTime: s.config.Now(), IssuerKeyId: &s.signer.KeyId, } if err := sig.Sign(s.h, s.signer, s.config); err != nil { return err } if err := s.literalData.Close(); err != nil { return err } if err := sig.Serialize(s.encryptedData); err != nil { return err } return s.encryptedData.Close() } // noOpCloser is like an ioutil.NopCloser, but for an io.Writer. // TODO: we have two of these in OpenPGP packages alone. This probably needs // to be promoted somewhere more common. type noOpCloser struct { w io.Writer } func (c noOpCloser) Write(data []byte) (n int, err error) { return c.w.Write(data) } func (c noOpCloser) Close() error { return nil } ��������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/s2k/������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023221� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/s2k/s2k_test.go�������������������������������������0000644�0610621�0607500�00000006254�13172163317�025315� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package s2k import ( "bytes" "crypto" _ "crypto/md5" "crypto/rand" "crypto/sha1" _ "crypto/sha256" _ "crypto/sha512" "encoding/hex" "testing" _ "golang.org/x/crypto/ripemd160" ) var saltedTests = []struct { in, out string }{ {"hello", "10295ac1"}, {"world", "ac587a5e"}, {"foo", "4dda8077"}, {"bar", "bd8aac6b9ea9cae04eae6a91c6133b58b5d9a61c14f355516ed9370456"}, {"x", "f1d3f289"}, {"xxxxxxxxxxxxxxxxxxxxxxx", "e00d7b45"}, } func TestSalted(t *testing.T) { h := sha1.New() salt := [4]byte{1, 2, 3, 4} for i, test := range saltedTests { expected, _ := hex.DecodeString(test.out) out := make([]byte, len(expected)) Salted(out, h, []byte(test.in), salt[:]) if !bytes.Equal(expected, out) { t.Errorf("#%d, got: %x want: %x", i, out, expected) } } } var iteratedTests = []struct { in, out string }{ {"hello", "83126105"}, {"world", "6fa317f9"}, {"foo", "8fbc35b9"}, {"bar", "2af5a99b54f093789fd657f19bd245af7604d0f6ae06f66602a46a08ae"}, {"x", "5a684dfe"}, {"xxxxxxxxxxxxxxxxxxxxxxx", "18955174"}, } func TestIterated(t *testing.T) { h := sha1.New() salt := [4]byte{4, 3, 2, 1} for i, test := range iteratedTests { expected, _ := hex.DecodeString(test.out) out := make([]byte, len(expected)) Iterated(out, h, []byte(test.in), salt[:], 31) if !bytes.Equal(expected, out) { t.Errorf("#%d, got: %x want: %x", i, out, expected) } } } var parseTests = []struct { spec, in, out string }{ /* Simple with SHA1 */ {"0002", "hello", "aaf4c61d"}, /* Salted with SHA1 */ {"01020102030405060708", "hello", "f4f7d67e"}, /* Iterated with SHA1 */ {"03020102030405060708f1", "hello", "f2a57b7c"}, } func TestParse(t *testing.T) { for i, test := range parseTests { spec, _ := hex.DecodeString(test.spec) buf := bytes.NewBuffer(spec) f, err := Parse(buf) if err != nil { t.Errorf("%d: Parse returned error: %s", i, err) continue } expected, _ := hex.DecodeString(test.out) out := make([]byte, len(expected)) f(out, []byte(test.in)) if !bytes.Equal(out, expected) { t.Errorf("%d: output got: %x want: %x", i, out, expected) } if testing.Short() { break } } } func TestSerialize(t *testing.T) { hashes := []crypto.Hash{crypto.MD5, crypto.SHA1, crypto.RIPEMD160, crypto.SHA256, crypto.SHA384, crypto.SHA512, crypto.SHA224} testCounts := []int{-1, 0, 1024, 65536, 4063232, 65011712} for _, h := range hashes { for _, c := range testCounts { testSerializeConfig(t, &Config{Hash: h, S2KCount: c}) } } } func testSerializeConfig(t *testing.T, c *Config) { t.Logf("Running testSerializeConfig() with config: %+v", c) buf := bytes.NewBuffer(nil) key := make([]byte, 16) passphrase := []byte("testing") err := Serialize(buf, key, rand.Reader, passphrase, c) if err != nil { t.Errorf("failed to serialize: %s", err) return } f, err := Parse(buf) if err != nil { t.Errorf("failed to reparse: %s", err) return } key2 := make([]byte, len(key)) f(key2, passphrase) if !bytes.Equal(key2, key) { t.Errorf("keys don't match: %x (serialied) vs %x (parsed)", key, key2) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/s2k/s2k.go������������������������������������������0000644�0610621�0607500�00000015773�13172163317�024264� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package s2k implements the various OpenPGP string-to-key transforms as // specified in RFC 4800 section 3.7.1. package s2k // import "golang.org/x/crypto/openpgp/s2k" import ( "crypto" "hash" "io" "strconv" "golang.org/x/crypto/openpgp/errors" ) // Config collects configuration parameters for s2k key-stretching // transformatioms. A nil *Config is valid and results in all default // values. Currently, Config is used only by the Serialize function in // this package. type Config struct { // Hash is the default hash function to be used. If // nil, SHA1 is used. Hash crypto.Hash // S2KCount is only used for symmetric encryption. It // determines the strength of the passphrase stretching when // the said passphrase is hashed to produce a key. S2KCount // should be between 1024 and 65011712, inclusive. If Config // is nil or S2KCount is 0, the value 65536 used. Not all // values in the above range can be represented. S2KCount will // be rounded up to the next representable value if it cannot // be encoded exactly. When set, it is strongly encrouraged to // use a value that is at least 65536. See RFC 4880 Section // 3.7.1.3. S2KCount int } func (c *Config) hash() crypto.Hash { if c == nil || uint(c.Hash) == 0 { // SHA1 is the historical default in this package. return crypto.SHA1 } return c.Hash } func (c *Config) encodedCount() uint8 { if c == nil || c.S2KCount == 0 { return 96 // The common case. Correspoding to 65536 } i := c.S2KCount switch { // Behave like GPG. Should we make 65536 the lowest value used? case i < 1024: i = 1024 case i > 65011712: i = 65011712 } return encodeCount(i) } // encodeCount converts an iterative "count" in the range 1024 to // 65011712, inclusive, to an encoded count. The return value is the // octet that is actually stored in the GPG file. encodeCount panics // if i is not in the above range (encodedCount above takes care to // pass i in the correct range). See RFC 4880 Section 3.7.7.1. func encodeCount(i int) uint8 { if i < 1024 || i > 65011712 { panic("count arg i outside the required range") } for encoded := 0; encoded < 256; encoded++ { count := decodeCount(uint8(encoded)) if count >= i { return uint8(encoded) } } return 255 } // decodeCount returns the s2k mode 3 iterative "count" corresponding to // the encoded octet c. func decodeCount(c uint8) int { return (16 + int(c&15)) << (uint32(c>>4) + 6) } // Simple writes to out the result of computing the Simple S2K function (RFC // 4880, section 3.7.1.1) using the given hash and input passphrase. func Simple(out []byte, h hash.Hash, in []byte) { Salted(out, h, in, nil) } var zero [1]byte // Salted writes to out the result of computing the Salted S2K function (RFC // 4880, section 3.7.1.2) using the given hash, input passphrase and salt. func Salted(out []byte, h hash.Hash, in []byte, salt []byte) { done := 0 var digest []byte for i := 0; done < len(out); i++ { h.Reset() for j := 0; j < i; j++ { h.Write(zero[:]) } h.Write(salt) h.Write(in) digest = h.Sum(digest[:0]) n := copy(out[done:], digest) done += n } } // Iterated writes to out the result of computing the Iterated and Salted S2K // function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase, // salt and iteration count. func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) { combined := make([]byte, len(in)+len(salt)) copy(combined, salt) copy(combined[len(salt):], in) if count < len(combined) { count = len(combined) } done := 0 var digest []byte for i := 0; done < len(out); i++ { h.Reset() for j := 0; j < i; j++ { h.Write(zero[:]) } written := 0 for written < count { if written+len(combined) > count { todo := count - written h.Write(combined[:todo]) written = count } else { h.Write(combined) written += len(combined) } } digest = h.Sum(digest[:0]) n := copy(out[done:], digest) done += n } } // Parse reads a binary specification for a string-to-key transformation from r // and returns a function which performs that transform. func Parse(r io.Reader) (f func(out, in []byte), err error) { var buf [9]byte _, err = io.ReadFull(r, buf[:2]) if err != nil { return } hash, ok := HashIdToHash(buf[1]) if !ok { return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1]))) } if !hash.Available() { return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hash))) } h := hash.New() switch buf[0] { case 0: f := func(out, in []byte) { Simple(out, h, in) } return f, nil case 1: _, err = io.ReadFull(r, buf[:8]) if err != nil { return } f := func(out, in []byte) { Salted(out, h, in, buf[:8]) } return f, nil case 3: _, err = io.ReadFull(r, buf[:9]) if err != nil { return } count := decodeCount(buf[8]) f := func(out, in []byte) { Iterated(out, h, in, buf[:8], count) } return f, nil } return nil, errors.UnsupportedError("S2K function") } // Serialize salts and stretches the given passphrase and writes the // resulting key into key. It also serializes an S2K descriptor to // w. The key stretching can be configured with c, which may be // nil. In that case, sensible defaults will be used. func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error { var buf [11]byte buf[0] = 3 /* iterated and salted */ buf[1], _ = HashToHashId(c.hash()) salt := buf[2:10] if _, err := io.ReadFull(rand, salt); err != nil { return err } encodedCount := c.encodedCount() count := decodeCount(encodedCount) buf[10] = encodedCount if _, err := w.Write(buf[:]); err != nil { return err } Iterated(key, c.hash().New(), passphrase, salt, count) return nil } // hashToHashIdMapping contains pairs relating OpenPGP's hash identifier with // Go's crypto.Hash type. See RFC 4880, section 9.4. var hashToHashIdMapping = []struct { id byte hash crypto.Hash name string }{ {1, crypto.MD5, "MD5"}, {2, crypto.SHA1, "SHA1"}, {3, crypto.RIPEMD160, "RIPEMD160"}, {8, crypto.SHA256, "SHA256"}, {9, crypto.SHA384, "SHA384"}, {10, crypto.SHA512, "SHA512"}, {11, crypto.SHA224, "SHA224"}, } // HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP // hash id. func HashIdToHash(id byte) (h crypto.Hash, ok bool) { for _, m := range hashToHashIdMapping { if m.id == id { return m.hash, true } } return 0, false } // HashIdToString returns the name of the hash function corresponding to the // given OpenPGP hash id. func HashIdToString(id byte) (name string, ok bool) { for _, m := range hashToHashIdMapping { if m.id == id { return m.name, true } } return "", false } // HashIdToHash returns an OpenPGP hash id which corresponds the given Hash. func HashToHashId(h crypto.Hash) (id byte, ok bool) { for _, m := range hashToHashIdMapping { if m.hash == h { return m.id, true } } return 0, false } �����lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/read_test.go����������������������������������������0000644�0610621�0607500�00000123255�13172163317�025033� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package openpgp import ( "bytes" _ "crypto/sha512" "encoding/hex" "io" "io/ioutil" "strings" "testing" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" ) func readerFromHex(s string) io.Reader { data, err := hex.DecodeString(s) if err != nil { panic("readerFromHex: bad input") } return bytes.NewBuffer(data) } func TestReadKeyRing(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(testKeys1And2Hex)) if err != nil { t.Error(err) return } if len(kring) != 2 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB || uint32(kring[1].PrimaryKey.KeyId) != 0x1E35246B { t.Errorf("bad keyring: %#v", kring) } } func TestRereadKeyRing(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(testKeys1And2Hex)) if err != nil { t.Errorf("error in initial parse: %s", err) return } out := new(bytes.Buffer) err = kring[0].Serialize(out) if err != nil { t.Errorf("error in serialization: %s", err) return } kring, err = ReadKeyRing(out) if err != nil { t.Errorf("error in second parse: %s", err) return } if len(kring) != 1 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB { t.Errorf("bad keyring: %#v", kring) } } func TestReadPrivateKeyRing(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) if err != nil { t.Error(err) return } if len(kring) != 2 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB || uint32(kring[1].PrimaryKey.KeyId) != 0x1E35246B || kring[0].PrimaryKey == nil { t.Errorf("bad keyring: %#v", kring) } } func TestReadDSAKey(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(dsaTestKeyHex)) if err != nil { t.Error(err) return } if len(kring) != 1 || uint32(kring[0].PrimaryKey.KeyId) != 0x0CCC0360 { t.Errorf("bad parse: %#v", kring) } } func TestReadP256Key(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(p256TestKeyHex)) if err != nil { t.Error(err) return } if len(kring) != 1 || uint32(kring[0].PrimaryKey.KeyId) != 0x5918513E { t.Errorf("bad parse: %#v", kring) } } func TestDSAHashTruncatation(t *testing.T) { // dsaKeyWithSHA512 was generated with GnuPG and --cert-digest-algo // SHA512 in order to require DSA hash truncation to verify correctly. _, err := ReadKeyRing(readerFromHex(dsaKeyWithSHA512)) if err != nil { t.Error(err) } } func TestGetKeyById(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) keys := kring.KeysById(0xa34d7e18c20c31bb) if len(keys) != 1 || keys[0].Entity != kring[0] { t.Errorf("bad result for 0xa34d7e18c20c31bb: %#v", keys) } keys = kring.KeysById(0xfd94408d4543314f) if len(keys) != 1 || keys[0].Entity != kring[0] { t.Errorf("bad result for 0xa34d7e18c20c31bb: %#v", keys) } } func checkSignedMessage(t *testing.T, signedHex, expected string) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) md, err := ReadMessage(readerFromHex(signedHex), kring, nil, nil) if err != nil { t.Error(err) return } if !md.IsSigned || md.SignedByKeyId != 0xa34d7e18c20c31bb || md.SignedBy == nil || md.IsEncrypted || md.IsSymmetricallyEncrypted || len(md.EncryptedToKeyIds) != 0 || md.IsSymmetricallyEncrypted { t.Errorf("bad MessageDetails: %#v", md) } contents, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("error reading UnverifiedBody: %s", err) } if string(contents) != expected { t.Errorf("bad UnverifiedBody got:%s want:%s", string(contents), expected) } if md.SignatureError != nil || md.Signature == nil { t.Errorf("failed to validate: %s", md.SignatureError) } } func TestSignedMessage(t *testing.T) { checkSignedMessage(t, signedMessageHex, signedInput) } func TestTextSignedMessage(t *testing.T) { checkSignedMessage(t, signedTextMessageHex, signedTextInput) } // The reader should detect "compressed quines", which are compressed // packets that expand into themselves and cause an infinite recursive // parsing loop. // The packet in this test case comes from Taylor R. Campbell at // http://mumble.net/~campbell/misc/pgp-quine/ func TestCampbellQuine(t *testing.T) { md, err := ReadMessage(readerFromHex(campbellQuine), nil, nil, nil) if md != nil { t.Errorf("Reading a compressed quine should not return any data: %#v", md) } structural, ok := err.(errors.StructuralError) if !ok { t.Fatalf("Unexpected class of error: %T", err) } if !strings.Contains(string(structural), "too many layers of packets") { t.Fatalf("Unexpected error: %s", err) } } var signedEncryptedMessageTests = []struct { keyRingHex string messageHex string signedByKeyId uint64 encryptedToKeyId uint64 }{ { testKeys1And2PrivateHex, signedEncryptedMessageHex, 0xa34d7e18c20c31bb, 0x2a67d68660df41c7, }, { dsaElGamalTestKeysHex, signedEncryptedMessage2Hex, 0x33af447ccd759b09, 0xcf6a7abcd43e3673, }, } func TestSignedEncryptedMessage(t *testing.T) { for i, test := range signedEncryptedMessageTests { expected := "Signed and encrypted message\n" kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex)) prompt := func(keys []Key, symmetric bool) ([]byte, error) { if symmetric { t.Errorf("prompt: message was marked as symmetrically encrypted") return nil, errors.ErrKeyIncorrect } if len(keys) == 0 { t.Error("prompt: no keys requested") return nil, errors.ErrKeyIncorrect } err := keys[0].PrivateKey.Decrypt([]byte("passphrase")) if err != nil { t.Errorf("prompt: error decrypting key: %s", err) return nil, errors.ErrKeyIncorrect } return nil, nil } md, err := ReadMessage(readerFromHex(test.messageHex), kring, prompt, nil) if err != nil { t.Errorf("#%d: error reading message: %s", i, err) return } if !md.IsSigned || md.SignedByKeyId != test.signedByKeyId || md.SignedBy == nil || !md.IsEncrypted || md.IsSymmetricallyEncrypted || len(md.EncryptedToKeyIds) == 0 || md.EncryptedToKeyIds[0] != test.encryptedToKeyId { t.Errorf("#%d: bad MessageDetails: %#v", i, md) } contents, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("#%d: error reading UnverifiedBody: %s", i, err) } if string(contents) != expected { t.Errorf("#%d: bad UnverifiedBody got:%s want:%s", i, string(contents), expected) } if md.SignatureError != nil || md.Signature == nil { t.Errorf("#%d: failed to validate: %s", i, md.SignatureError) } } } func TestUnspecifiedRecipient(t *testing.T) { expected := "Recipient unspecified\n" kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) md, err := ReadMessage(readerFromHex(recipientUnspecifiedHex), kring, nil, nil) if err != nil { t.Errorf("error reading message: %s", err) return } contents, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("error reading UnverifiedBody: %s", err) } if string(contents) != expected { t.Errorf("bad UnverifiedBody got:%s want:%s", string(contents), expected) } } func TestSymmetricallyEncrypted(t *testing.T) { firstTimeCalled := true prompt := func(keys []Key, symmetric bool) ([]byte, error) { if len(keys) != 0 { t.Errorf("prompt: len(keys) = %d (want 0)", len(keys)) } if !symmetric { t.Errorf("symmetric is not set") } if firstTimeCalled { firstTimeCalled = false return []byte("wrongpassword"), nil } return []byte("password"), nil } md, err := ReadMessage(readerFromHex(symmetricallyEncryptedCompressedHex), nil, prompt, nil) if err != nil { t.Errorf("ReadMessage: %s", err) return } contents, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Errorf("ReadAll: %s", err) } expectedCreationTime := uint32(1295992998) if md.LiteralData.Time != expectedCreationTime { t.Errorf("LiteralData.Time is %d, want %d", md.LiteralData.Time, expectedCreationTime) } const expected = "Symmetrically encrypted.\n" if string(contents) != expected { t.Errorf("contents got: %s want: %s", string(contents), expected) } } func testDetachedSignature(t *testing.T, kring KeyRing, signature io.Reader, sigInput, tag string, expectedSignerKeyId uint64) { signed := bytes.NewBufferString(sigInput) signer, err := CheckDetachedSignature(kring, signed, signature) if err != nil { t.Errorf("%s: signature error: %s", tag, err) return } if signer == nil { t.Errorf("%s: signer is nil", tag) return } if signer.PrimaryKey.KeyId != expectedSignerKeyId { t.Errorf("%s: wrong signer got:%x want:%x", tag, signer.PrimaryKey.KeyId, expectedSignerKeyId) } } func TestDetachedSignature(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) testDetachedSignature(t, kring, readerFromHex(detachedSignatureHex), signedInput, "binary", testKey1KeyId) testDetachedSignature(t, kring, readerFromHex(detachedSignatureTextHex), signedInput, "text", testKey1KeyId) testDetachedSignature(t, kring, readerFromHex(detachedSignatureV3TextHex), signedInput, "v3", testKey1KeyId) incorrectSignedInput := signedInput + "X" _, err := CheckDetachedSignature(kring, bytes.NewBufferString(incorrectSignedInput), readerFromHex(detachedSignatureHex)) if err == nil { t.Fatal("CheckDetachedSignature returned without error for bad signature") } if err == errors.ErrUnknownIssuer { t.Fatal("CheckDetachedSignature returned ErrUnknownIssuer when the signer was known, but the signature invalid") } } func TestDetachedSignatureDSA(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyHex)) testDetachedSignature(t, kring, readerFromHex(detachedSignatureDSAHex), signedInput, "binary", testKey3KeyId) } func TestMultipleSignaturePacketsDSA(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyHex)) testDetachedSignature(t, kring, readerFromHex(missingHashFunctionHex+detachedSignatureDSAHex), signedInput, "binary", testKey3KeyId) } func TestDetachedSignatureP256(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(p256TestKeyHex)) testDetachedSignature(t, kring, readerFromHex(detachedSignatureP256Hex), signedInput, "binary", testKeyP256KeyId) } func testHashFunctionError(t *testing.T, signatureHex string) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) _, err := CheckDetachedSignature(kring, nil, readerFromHex(signatureHex)) if err == nil { t.Fatal("Packet with bad hash type was correctly parsed") } unsupported, ok := err.(errors.UnsupportedError) if !ok { t.Fatalf("Unexpected class of error: %s", err) } if !strings.Contains(string(unsupported), "hash ") { t.Fatalf("Unexpected error: %s", err) } } func TestUnknownHashFunction(t *testing.T) { // unknownHashFunctionHex contains a signature packet with hash // function type 153 (which isn't a real hash function id). testHashFunctionError(t, unknownHashFunctionHex) } func TestMissingHashFunction(t *testing.T) { // missingHashFunctionHex contains a signature packet that uses // RIPEMD160, which isn't compiled in. Since that's the only signature // packet we don't find any suitable packets and end up with ErrUnknownIssuer kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) _, err := CheckDetachedSignature(kring, nil, readerFromHex(missingHashFunctionHex)) if err == nil { t.Fatal("Packet with missing hash type was correctly parsed") } if err != errors.ErrUnknownIssuer { t.Fatalf("Unexpected class of error: %s", err) } } func TestReadingArmoredPrivateKey(t *testing.T) { el, err := ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKeyBlock)) if err != nil { t.Error(err) } if len(el) != 1 { t.Errorf("got %d entities, wanted 1\n", len(el)) } } func TestReadingArmoredPublicKey(t *testing.T) { el, err := ReadArmoredKeyRing(bytes.NewBufferString(e2ePublicKey)) if err != nil { t.Error(err) } if len(el) != 1 { t.Errorf("didn't get a valid entity") } } func TestNoArmoredData(t *testing.T) { _, err := ReadArmoredKeyRing(bytes.NewBufferString("foo")) if _, ok := err.(errors.InvalidArgumentError); !ok { t.Errorf("error was not an InvalidArgumentError: %s", err) } } func testReadMessageError(t *testing.T, messageHex string) { buf, err := hex.DecodeString(messageHex) if err != nil { t.Errorf("hex.DecodeString(): %v", err) } kr, err := ReadKeyRing(new(bytes.Buffer)) if err != nil { t.Errorf("ReadKeyring(): %v", err) } _, err = ReadMessage(bytes.NewBuffer(buf), kr, func([]Key, bool) ([]byte, error) { return []byte("insecure"), nil }, nil) if err == nil { t.Errorf("ReadMessage(): Unexpected nil error") } } func TestIssue11503(t *testing.T) { testReadMessageError(t, "8c040402000aa430aa8228b9248b01fc899a91197130303030") } func TestIssue11504(t *testing.T) { testReadMessageError(t, "9303000130303030303030303030983002303030303030030000000130") } // TestSignatureV3Message tests the verification of V3 signature, generated // with a modern V4-style key. Some people have their clients set to generate // V3 signatures, so it's useful to be able to verify them. func TestSignatureV3Message(t *testing.T) { sig, err := armor.Decode(strings.NewReader(signedMessageV3)) if err != nil { t.Error(err) return } key, err := ReadArmoredKeyRing(strings.NewReader(keyV4forVerifyingSignedMessageV3)) if err != nil { t.Error(err) return } md, err := ReadMessage(sig.Body, key, nil, nil) if err != nil { t.Error(err) return } _, err = ioutil.ReadAll(md.UnverifiedBody) if err != nil { t.Error(err) return } // We'll see a sig error here after reading in the UnverifiedBody above, // if there was one to see. if err = md.SignatureError; err != nil { t.Error(err) return } if md.SignatureV3 == nil { t.Errorf("No available signature after checking signature") return } if md.Signature != nil { t.Errorf("Did not expect a signature V4 back") return } return } const testKey1KeyId = 0xA34D7E18C20C31BB const testKey3KeyId = 0x338934250CCC0360 const testKeyP256KeyId = 0xd44a2c495918513e const signedInput = "Signed message\nline 2\nline 3\n" const signedTextInput = "Signed message\r\nline 2\r\nline 3\r\n" const recipientUnspecifiedHex = "848c0300000000000000000103ff62d4d578d03cf40c3da998dfe216c074fa6ddec5e31c197c9666ba292830d91d18716a80f699f9d897389a90e6d62d0238f5f07a5248073c0f24920e4bc4a30c2d17ee4e0cae7c3d4aaa4e8dced50e3010a80ee692175fa0385f62ecca4b56ee6e9980aa3ec51b61b077096ac9e800edaf161268593eedb6cc7027ff5cb32745d250010d407a6221ae22ef18469b444f2822478c4d190b24d36371a95cb40087cdd42d9399c3d06a53c0673349bfb607927f20d1e122bde1e2bf3aa6cae6edf489629bcaa0689539ae3b718914d88ededc3b" const detachedSignatureHex = "889c04000102000605024d449cd1000a0910a34d7e18c20c31bb167603ff57718d09f28a519fdc7b5a68b6a3336da04df85e38c5cd5d5bd2092fa4629848a33d85b1729402a2aab39c3ac19f9d573f773cc62c264dc924c067a79dfd8a863ae06c7c8686120760749f5fd9b1e03a64d20a7df3446ddc8f0aeadeaeba7cbaee5c1e366d65b6a0c6cc749bcb912d2f15013f812795c2e29eb7f7b77f39ce77" const detachedSignatureTextHex = "889c04010102000605024d449d21000a0910a34d7e18c20c31bbc8c60400a24fbef7342603a41cb1165767bd18985d015fb72fe05db42db36cfb2f1d455967f1e491194fbf6cf88146222b23bf6ffbd50d17598d976a0417d3192ff9cc0034fd00f287b02e90418bbefe609484b09231e4e7a5f3562e199bf39909ab5276c4d37382fe088f6b5c3426fc1052865da8b3ab158672d58b6264b10823dc4b39" const detachedSignatureV3TextHex = "8900950305005255c25ca34d7e18c20c31bb0102bb3f04009f6589ef8a028d6e54f6eaf25432e590d31c3a41f4710897585e10c31e5e332c7f9f409af8512adceaff24d0da1474ab07aa7bce4f674610b010fccc5b579ae5eb00a127f272fb799f988ab8e4574c141da6dbfecfef7e6b2c478d9a3d2551ba741f260ee22bec762812f0053e05380bfdd55ad0f22d8cdf71b233fe51ae8a24" const detachedSignatureDSAHex = "884604001102000605024d6c4eac000a0910338934250ccc0360f18d00a087d743d6405ed7b87755476629600b8b694a39e900a0abff8126f46faf1547c1743c37b21b4ea15b8f83" const detachedSignatureP256Hex = "885e0400130a0006050256e5bb00000a0910d44a2c495918513edef001009841a4f792beb0befccb35c8838a6a87d9b936beaa86db6745ddc7b045eee0cf00fd1ac1f78306b17e965935dd3f8bae4587a76587e4af231efe19cc4011a8434817" const testKeys1And2Hex = "988d044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd0011010001b41054657374204b6579203120285253412988b804130102002205024d3c5c10021b03060b090807030206150802090a0b0416020301021e01021780000a0910a34d7e18c20c31bbb5b304009cc45fe610b641a2c146331be94dade0a396e73ca725e1b25c21708d9cab46ecca5ccebc23055879df8f99eea39b377962a400f2ebdc36a7c99c333d74aeba346315137c3ff9d0a09b0273299090343048afb8107cf94cbd1400e3026f0ccac7ecebbc4d78588eb3e478fe2754d3ca664bcf3eac96ca4a6b0c8d7df5102f60f6b0020003b88d044d3c5c10010400b201df61d67487301f11879d514f4248ade90c8f68c7af1284c161098de4c28c2850f1ec7b8e30f959793e571542ffc6532189409cb51c3d30dad78c4ad5165eda18b20d9826d8707d0f742e2ab492103a85bbd9ddf4f5720f6de7064feb0d39ee002219765bb07bcfb8b877f47abe270ddeda4f676108cecb6b9bb2ad484a4f0011010001889f04180102000905024d3c5c10021b0c000a0910a34d7e18c20c31bb1a03040085c8d62e16d05dc4e9dad64953c8a2eed8b6c12f92b1575eeaa6dcf7be9473dd5b24b37b6dffbb4e7c99ed1bd3cb11634be19b3e6e207bed7505c7ca111ccf47cb323bf1f8851eb6360e8034cbff8dd149993c959de89f8f77f38e7e98b8e3076323aa719328e2b408db5ec0d03936efd57422ba04f925cdc7b4c1af7590e40ab0020003988d044d3c5c33010400b488c3e5f83f4d561f317817538d9d0397981e9aef1321ca68ebfae1cf8b7d388e19f4b5a24a82e2fbbf1c6c26557a6c5845307a03d815756f564ac7325b02bc83e87d5480a8fae848f07cb891f2d51ce7df83dcafdc12324517c86d472cc0ee10d47a68fd1d9ae49a6c19bbd36d82af597a0d88cc9c49de9df4e696fc1f0b5d0011010001b42754657374204b6579203220285253412c20656e637279707465642070726976617465206b65792988b804130102002205024d3c5c33021b03060b090807030206150802090a0b0416020301021e01021780000a0910d4984f961e35246b98940400908a73b6a6169f700434f076c6c79015a49bee37130eaf23aaa3cfa9ce60bfe4acaa7bc95f1146ada5867e0079babb38804891f4f0b8ebca57a86b249dee786161a755b7a342e68ccf3f78ed6440a93a6626beb9a37aa66afcd4f888790cb4bb46d94a4ae3eb3d7d3e6b00f6bfec940303e89ec5b32a1eaaacce66497d539328b0020003b88d044d3c5c33010400a4e913f9442abcc7f1804ccab27d2f787ffa592077ca935a8bb23165bd8d57576acac647cc596b2c3f814518cc8c82953c7a4478f32e0cf645630a5ba38d9618ef2bc3add69d459ae3dece5cab778938d988239f8c5ae437807075e06c828019959c644ff05ef6a5a1dab72227c98e3a040b0cf219026640698d7a13d8538a570011010001889f04180102000905024d3c5c33021b0c000a0910d4984f961e35246b26c703ff7ee29ef53bc1ae1ead533c408fa136db508434e233d6e62be621e031e5940bbd4c08142aed0f82217e7c3e1ec8de574bc06ccf3c36633be41ad78a9eacd209f861cae7b064100758545cc9dd83db71806dc1cfd5fb9ae5c7474bba0c19c44034ae61bae5eca379383339dece94ff56ff7aa44a582f3e5c38f45763af577c0934b0020003" const testKeys1And2PrivateHex = "9501d8044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd00110100010003ff4d91393b9a8e3430b14d6209df42f98dc927425b881f1209f319220841273a802a97c7bdb8b3a7740b3ab5866c4d1d308ad0d3a79bd1e883aacf1ac92dfe720285d10d08752a7efe3c609b1d00f17f2805b217be53999a7da7e493bfc3e9618fd17018991b8128aea70a05dbce30e4fbe626aa45775fa255dd9177aabf4df7cf0200c1ded12566e4bc2bb590455e5becfb2e2c9796482270a943343a7835de41080582c2be3caf5981aa838140e97afa40ad652a0b544f83eb1833b0957dce26e47b0200eacd6046741e9ce2ec5beb6fb5e6335457844fb09477f83b050a96be7da043e17f3a9523567ed40e7a521f818813a8b8a72209f1442844843ccc7eb9805442570200bdafe0438d97ac36e773c7162028d65844c4d463e2420aa2228c6e50dc2743c3d6c72d0d782a5173fe7be2169c8a9f4ef8a7cf3e37165e8c61b89c346cdc6c1799d2b41054657374204b6579203120285253412988b804130102002205024d3c5c10021b03060b090807030206150802090a0b0416020301021e01021780000a0910a34d7e18c20c31bbb5b304009cc45fe610b641a2c146331be94dade0a396e73ca725e1b25c21708d9cab46ecca5ccebc23055879df8f99eea39b377962a400f2ebdc36a7c99c333d74aeba346315137c3ff9d0a09b0273299090343048afb8107cf94cbd1400e3026f0ccac7ecebbc4d78588eb3e478fe2754d3ca664bcf3eac96ca4a6b0c8d7df5102f60f6b00200009d01d8044d3c5c10010400b201df61d67487301f11879d514f4248ade90c8f68c7af1284c161098de4c28c2850f1ec7b8e30f959793e571542ffc6532189409cb51c3d30dad78c4ad5165eda18b20d9826d8707d0f742e2ab492103a85bbd9ddf4f5720f6de7064feb0d39ee002219765bb07bcfb8b877f47abe270ddeda4f676108cecb6b9bb2ad484a4f00110100010003fd17a7490c22a79c59281fb7b20f5e6553ec0c1637ae382e8adaea295f50241037f8997cf42c1ce26417e015091451b15424b2c59eb8d4161b0975630408e394d3b00f88d4b4e18e2cc85e8251d4753a27c639c83f5ad4a571c4f19d7cd460b9b73c25ade730c99df09637bd173d8e3e981ac64432078263bb6dc30d3e974150dd0200d0ee05be3d4604d2146fb0457f31ba17c057560785aa804e8ca5530a7cd81d3440d0f4ba6851efcfd3954b7e68908fc0ba47f7ac37bf559c6c168b70d3a7c8cd0200da1c677c4bce06a068070f2b3733b0a714e88d62aa3f9a26c6f5216d48d5c2b5624144f3807c0df30be66b3268eeeca4df1fbded58faf49fc95dc3c35f134f8b01fd1396b6c0fc1b6c4f0eb8f5e44b8eace1e6073e20d0b8bc5385f86f1cf3f050f66af789f3ef1fc107b7f4421e19e0349c730c68f0a226981f4e889054fdb4dc149e8e889f04180102000905024d3c5c10021b0c000a0910a34d7e18c20c31bb1a03040085c8d62e16d05dc4e9dad64953c8a2eed8b6c12f92b1575eeaa6dcf7be9473dd5b24b37b6dffbb4e7c99ed1bd3cb11634be19b3e6e207bed7505c7ca111ccf47cb323bf1f8851eb6360e8034cbff8dd149993c959de89f8f77f38e7e98b8e3076323aa719328e2b408db5ec0d03936efd57422ba04f925cdc7b4c1af7590e40ab00200009501fe044d3c5c33010400b488c3e5f83f4d561f317817538d9d0397981e9aef1321ca68ebfae1cf8b7d388e19f4b5a24a82e2fbbf1c6c26557a6c5845307a03d815756f564ac7325b02bc83e87d5480a8fae848f07cb891f2d51ce7df83dcafdc12324517c86d472cc0ee10d47a68fd1d9ae49a6c19bbd36d82af597a0d88cc9c49de9df4e696fc1f0b5d0011010001fe030302e9030f3c783e14856063f16938530e148bc57a7aa3f3e4f90df9dceccdc779bc0835e1ad3d006e4a8d7b36d08b8e0de5a0d947254ecfbd22037e6572b426bcfdc517796b224b0036ff90bc574b5509bede85512f2eefb520fb4b02aa523ba739bff424a6fe81c5041f253f8d757e69a503d3563a104d0d49e9e890b9d0c26f96b55b743883b472caa7050c4acfd4a21f875bdf1258d88bd61224d303dc9df77f743137d51e6d5246b88c406780528fd9a3e15bab5452e5b93970d9dcc79f48b38651b9f15bfbcf6da452837e9cc70683d1bdca94507870f743e4ad902005812488dd342f836e72869afd00ce1850eea4cfa53ce10e3608e13d3c149394ee3cbd0e23d018fcbcb6e2ec5a1a22972d1d462ca05355d0d290dd2751e550d5efb38c6c89686344df64852bf4ff86638708f644e8ec6bd4af9b50d8541cb91891a431326ab2e332faa7ae86cfb6e0540aa63160c1e5cdd5a4add518b303fff0a20117c6bc77f7cfbaf36b04c865c6c2b42754657374204b6579203220285253412c20656e637279707465642070726976617465206b65792988b804130102002205024d3c5c33021b03060b090807030206150802090a0b0416020301021e01021780000a0910d4984f961e35246b98940400908a73b6a6169f700434f076c6c79015a49bee37130eaf23aaa3cfa9ce60bfe4acaa7bc95f1146ada5867e0079babb38804891f4f0b8ebca57a86b249dee786161a755b7a342e68ccf3f78ed6440a93a6626beb9a37aa66afcd4f888790cb4bb46d94a4ae3eb3d7d3e6b00f6bfec940303e89ec5b32a1eaaacce66497d539328b00200009d01fe044d3c5c33010400a4e913f9442abcc7f1804ccab27d2f787ffa592077ca935a8bb23165bd8d57576acac647cc596b2c3f814518cc8c82953c7a4478f32e0cf645630a5ba38d9618ef2bc3add69d459ae3dece5cab778938d988239f8c5ae437807075e06c828019959c644ff05ef6a5a1dab72227c98e3a040b0cf219026640698d7a13d8538a570011010001fe030302e9030f3c783e148560f936097339ae381d63116efcf802ff8b1c9360767db5219cc987375702a4123fd8657d3e22700f23f95020d1b261eda5257e9a72f9a918e8ef22dd5b3323ae03bbc1923dd224db988cadc16acc04b120a9f8b7e84da9716c53e0334d7b66586ddb9014df604b41be1e960dcfcbc96f4ed150a1a0dd070b9eb14276b9b6be413a769a75b519a53d3ecc0c220e85cd91ca354d57e7344517e64b43b6e29823cbd87eae26e2b2e78e6dedfbb76e3e9f77bcb844f9a8932eb3db2c3f9e44316e6f5d60e9e2a56e46b72abe6b06dc9a31cc63f10023d1f5e12d2a3ee93b675c96f504af0001220991c88db759e231b3320dcedf814dcf723fd9857e3d72d66a0f2af26950b915abdf56c1596f46a325bf17ad4810d3535fb02a259b247ac3dbd4cc3ecf9c51b6c07cebb009c1506fba0a89321ec8683e3fd009a6e551d50243e2d5092fefb3321083a4bad91320dc624bd6b5dddf93553e3d53924c05bfebec1fb4bd47e89a1a889f04180102000905024d3c5c33021b0c000a0910d4984f961e35246b26c703ff7ee29ef53bc1ae1ead533c408fa136db508434e233d6e62be621e031e5940bbd4c08142aed0f82217e7c3e1ec8de574bc06ccf3c36633be41ad78a9eacd209f861cae7b064100758545cc9dd83db71806dc1cfd5fb9ae5c7474bba0c19c44034ae61bae5eca379383339dece94ff56ff7aa44a582f3e5c38f45763af577c0934b0020000" const dsaElGamalTestKeysHex = "9501e1044dfcb16a110400aa3e5c1a1f43dd28c2ffae8abf5cfce555ee874134d8ba0a0f7b868ce2214beddc74e5e1e21ded354a95d18acdaf69e5e342371a71fbb9093162e0c5f3427de413a7f2c157d83f5cd2f9d791256dc4f6f0e13f13c3302af27f2384075ab3021dff7a050e14854bbde0a1094174855fc02f0bae8e00a340d94a1f22b32e48485700a0cec672ac21258fb95f61de2ce1af74b2c4fa3e6703ff698edc9be22c02ae4d916e4fa223f819d46582c0516235848a77b577ea49018dcd5e9e15cff9dbb4663a1ae6dd7580fa40946d40c05f72814b0f88481207e6c0832c3bded4853ebba0a7e3bd8e8c66df33d5a537cd4acf946d1080e7a3dcea679cb2b11a72a33a2b6a9dc85f466ad2ddf4c3db6283fa645343286971e3dd700703fc0c4e290d45767f370831a90187e74e9972aae5bff488eeff7d620af0362bfb95c1a6c3413ab5d15a2e4139e5d07a54d72583914661ed6a87cce810be28a0aa8879a2dd39e52fb6fe800f4f181ac7e328f740cde3d09a05cecf9483e4cca4253e60d4429ffd679d9996a520012aad119878c941e3cf151459873bdfc2a9563472fe0303027a728f9feb3b864260a1babe83925ce794710cfd642ee4ae0e5b9d74cee49e9c67b6cd0ea5dfbb582132195a121356a1513e1bca73e5b80c58c7ccb4164453412f456c47616d616c2054657374204b65792031886204131102002205024dfcb16a021b03060b090807030206150802090a0b0416020301021e01021780000a091033af447ccd759b09fadd00a0b8fd6f5a790bad7e9f2dbb7632046dc4493588db009c087c6a9ba9f7f49fab221587a74788c00db4889ab00200009d0157044dfcb16a1004008dec3f9291205255ccff8c532318133a6840739dd68b03ba942676f9038612071447bf07d00d559c5c0875724ea16a4c774f80d8338b55fca691a0522e530e604215b467bbc9ccfd483a1da99d7bc2648b4318fdbd27766fc8bfad3fddb37c62b8ae7ccfe9577e9b8d1e77c1d417ed2c2ef02d52f4da11600d85d3229607943700030503ff506c94c87c8cab778e963b76cf63770f0a79bf48fb49d3b4e52234620fc9f7657f9f8d56c96a2b7c7826ae6b57ebb2221a3fe154b03b6637cea7e6d98e3e45d87cf8dc432f723d3d71f89c5192ac8d7290684d2c25ce55846a80c9a7823f6acd9bb29fa6cd71f20bc90eccfca20451d0c976e460e672b000df49466408d527affe0303027a728f9feb3b864260abd761730327bca2aaa4ea0525c175e92bf240682a0e83b226f97ecb2e935b62c9a133858ce31b271fa8eb41f6a1b3cd72a63025ce1a75ee4180dcc284884904181102000905024dfcb16a021b0c000a091033af447ccd759b09dd0b009e3c3e7296092c81bee5a19929462caaf2fff3ae26009e218c437a2340e7ea628149af1ec98ec091a43992b00200009501e1044dfcb1be1104009f61faa61aa43df75d128cbe53de528c4aec49ce9360c992e70c77072ad5623de0a3a6212771b66b39a30dad6781799e92608316900518ec01184a85d872365b7d2ba4bacfb5882ea3c2473d3750dc6178cc1cf82147fb58caa28b28e9f12f6d1efcb0534abed644156c91cca4ab78834268495160b2400bc422beb37d237c2300a0cac94911b6d493bda1e1fbc6feeca7cb7421d34b03fe22cec6ccb39675bb7b94a335c2b7be888fd3906a1125f33301d8aa6ec6ee6878f46f73961c8d57a3e9544d8ef2a2cbfd4d52da665b1266928cfe4cb347a58c412815f3b2d2369dec04b41ac9a71cc9547426d5ab941cccf3b18575637ccfb42df1a802df3cfe0a999f9e7109331170e3a221991bf868543960f8c816c28097e503fe319db10fb98049f3a57d7c80c420da66d56f3644371631fad3f0ff4040a19a4fedc2d07727a1b27576f75a4d28c47d8246f27071e12d7a8de62aad216ddbae6aa02efd6b8a3e2818cda48526549791ab277e447b3a36c57cefe9b592f5eab73959743fcc8e83cbefec03a329b55018b53eec196765ae40ef9e20521a603c551efe0303020950d53a146bf9c66034d00c23130cce95576a2ff78016ca471276e8227fb30b1ffbd92e61804fb0c3eff9e30b1a826ee8f3e4730b4d86273ca977b4164453412f456c47616d616c2054657374204b65792032886204131102002205024dfcb1be021b03060b090807030206150802090a0b0416020301021e01021780000a0910a86bf526325b21b22bd9009e34511620415c974750a20df5cb56b182f3b48e6600a0a9466cb1a1305a84953445f77d461593f1d42bc1b00200009d0157044dfcb1be1004009565a951da1ee87119d600c077198f1c1bceb0f7aa54552489298e41ff788fa8f0d43a69871f0f6f77ebdfb14a4260cf9fbeb65d5844b4272a1904dd95136d06c3da745dc46327dd44a0f16f60135914368c8039a34033862261806bb2c5ce1152e2840254697872c85441ccb7321431d75a747a4bfb1d2c66362b51ce76311700030503fc0ea76601c196768070b7365a200e6ddb09307f262d5f39eec467b5f5784e22abdf1aa49226f59ab37cb49969d8f5230ea65caf56015abda62604544ed526c5c522bf92bed178a078789f6c807b6d34885688024a5bed9e9f8c58d11d4b82487b44c5f470c5606806a0443b79cadb45e0f897a561a53f724e5349b9267c75ca17fe0303020950d53a146bf9c660bc5f4ce8f072465e2d2466434320c1e712272fafc20e342fe7608101580fa1a1a367e60486a7cd1246b7ef5586cf5e10b32762b710a30144f12dd17dd4884904181102000905024dfcb1be021b0c000a0910a86bf526325b21b2904c00a0b2b66b4b39ccffda1d10f3ea8d58f827e30a8b8e009f4255b2d8112a184e40cde43a34e8655ca7809370b0020000" const signedMessageHex = "a3019bc0cbccc0c4b8d8b74ee2108fe16ec6d3ca490cbe362d3f8333d3f352531472538b8b13d353b97232f352158c20943157c71c16064626063656269052062e4e01987e9b6fccff4b7df3a34c534b23e679cbec3bc0f8f6e64dfb4b55fe3f8efa9ce110ddb5cd79faf1d753c51aecfa669f7e7aa043436596cccc3359cb7dd6bbe9ecaa69e5989d9e57209571edc0b2fa7f57b9b79a64ee6e99ce1371395fee92fec2796f7b15a77c386ff668ee27f6d38f0baa6c438b561657377bf6acff3c5947befd7bf4c196252f1d6e5c524d0300" const signedTextMessageHex = "a3019bc0cbccc8c4b8d8b74ee2108fe16ec6d36a250cbece0c178233d3f352531472538b8b13d35379b97232f352158ca0b4312f57c71c1646462606365626906a062e4e019811591798ff99bf8afee860b0d8a8c2a85c3387e3bcf0bb3b17987f2bbcfab2aa526d930cbfd3d98757184df3995c9f3e7790e36e3e9779f06089d4c64e9e47dd6202cb6e9bc73c5d11bb59fbaf89d22d8dc7cf199ddf17af96e77c5f65f9bbed56f427bd8db7af37f6c9984bf9385efaf5f184f986fb3e6adb0ecfe35bbf92d16a7aa2a344fb0bc52fb7624f0200" const signedEncryptedMessageHex = "848c032a67d68660df41c70103ff5789d0de26b6a50c985a02a13131ca829c413a35d0e6fa8d6842599252162808ac7439c72151c8c6183e76923fe3299301414d0c25a2f06a2257db3839e7df0ec964773f6e4c4ac7ff3b48c444237166dd46ba8ff443a5410dc670cb486672fdbe7c9dfafb75b4fea83af3a204fe2a7dfa86bd20122b4f3d2646cbeecb8f7be8d2c03b018bd210b1d3791e1aba74b0f1034e122ab72e760492c192383cf5e20b5628bd043272d63df9b923f147eb6091cd897553204832aba48fec54aa447547bb16305a1024713b90e77fd0065f1918271947549205af3c74891af22ee0b56cd29bfec6d6e351901cd4ab3ece7c486f1e32a792d4e474aed98ee84b3f591c7dff37b64e0ecd68fd036d517e412dcadf85840ce184ad7921ad446c4ee28db80447aea1ca8d4f574db4d4e37688158ddd19e14ee2eab4873d46947d65d14a23e788d912cf9a19624ca7352469b72a83866b7c23cb5ace3deab3c7018061b0ba0f39ed2befe27163e5083cf9b8271e3e3d52cc7ad6e2a3bd81d4c3d7022f8d" const signedEncryptedMessage2Hex = "85010e03cf6a7abcd43e36731003fb057f5495b79db367e277cdbe4ab90d924ddee0c0381494112ff8c1238fb0184af35d1731573b01bc4c55ecacd2aafbe2003d36310487d1ecc9ac994f3fada7f9f7f5c3a64248ab7782906c82c6ff1303b69a84d9a9529c31ecafbcdb9ba87e05439897d87e8a2a3dec55e14df19bba7f7bd316291c002ae2efd24f83f9e3441203fc081c0c23dc3092a454ca8a082b27f631abf73aca341686982e8fbda7e0e7d863941d68f3de4a755c2964407f4b5e0477b3196b8c93d551dd23c8beef7d0f03fbb1b6066f78907faf4bf1677d8fcec72651124080e0b7feae6b476e72ab207d38d90b958759fdedfc3c6c35717c9dbfc979b3cfbbff0a76d24a5e57056bb88acbd2a901ef64bc6e4db02adc05b6250ff378de81dca18c1910ab257dff1b9771b85bb9bbe0a69f5989e6d1710a35e6dfcceb7d8fb5ccea8db3932b3d9ff3fe0d327597c68b3622aec8e3716c83a6c93f497543b459b58ba504ed6bcaa747d37d2ca746fe49ae0a6ce4a8b694234e941b5159ff8bd34b9023da2814076163b86f40eed7c9472f81b551452d5ab87004a373c0172ec87ea6ce42ccfa7dbdad66b745496c4873d8019e8c28d6b3" const symmetricallyEncryptedCompressedHex = "8c0d04030302eb4a03808145d0d260c92f714339e13de5a79881216431925bf67ee2898ea61815f07894cd0703c50d0a76ef64d482196f47a8bc729af9b80bb6" const dsaTestKeyHex = "9901a2044d6c49de110400cb5ce438cf9250907ac2ba5bf6547931270b89f7c4b53d9d09f4d0213a5ef2ec1f26806d3d259960f872a4a102ef1581ea3f6d6882d15134f21ef6a84de933cc34c47cc9106efe3bd84c6aec12e78523661e29bc1a61f0aab17fa58a627fd5fd33f5149153fbe8cd70edf3d963bc287ef875270ff14b5bfdd1bca4483793923b00a0fe46d76cb6e4cbdc568435cd5480af3266d610d303fe33ae8273f30a96d4d34f42fa28ce1112d425b2e3bf7ea553d526e2db6b9255e9dc7419045ce817214d1a0056dbc8d5289956a4b1b69f20f1105124096e6a438f41f2e2495923b0f34b70642607d45559595c7fe94d7fa85fc41bf7d68c1fd509ebeaa5f315f6059a446b9369c277597e4f474a9591535354c7e7f4fd98a08aa60400b130c24ff20bdfbf683313f5daebf1c9b34b3bdadfc77f2ddd72ee1fb17e56c473664bc21d66467655dd74b9005e3a2bacce446f1920cd7017231ae447b67036c9b431b8179deacd5120262d894c26bc015bffe3d827ba7087ad9b700d2ca1f6d16cc1786581e5dd065f293c31209300f9b0afcc3f7c08dd26d0a22d87580b4db41054657374204b65792033202844534129886204131102002205024d6c49de021b03060b090807030206150802090a0b0416020301021e01021780000a0910338934250ccc03607e0400a0bdb9193e8a6b96fc2dfc108ae848914b504481f100a09c4dc148cb693293a67af24dd40d2b13a9e36794" const dsaTestKeyPrivateHex = "9501bb044d6c49de110400cb5ce438cf9250907ac2ba5bf6547931270b89f7c4b53d9d09f4d0213a5ef2ec1f26806d3d259960f872a4a102ef1581ea3f6d6882d15134f21ef6a84de933cc34c47cc9106efe3bd84c6aec12e78523661e29bc1a61f0aab17fa58a627fd5fd33f5149153fbe8cd70edf3d963bc287ef875270ff14b5bfdd1bca4483793923b00a0fe46d76cb6e4cbdc568435cd5480af3266d610d303fe33ae8273f30a96d4d34f42fa28ce1112d425b2e3bf7ea553d526e2db6b9255e9dc7419045ce817214d1a0056dbc8d5289956a4b1b69f20f1105124096e6a438f41f2e2495923b0f34b70642607d45559595c7fe94d7fa85fc41bf7d68c1fd509ebeaa5f315f6059a446b9369c277597e4f474a9591535354c7e7f4fd98a08aa60400b130c24ff20bdfbf683313f5daebf1c9b34b3bdadfc77f2ddd72ee1fb17e56c473664bc21d66467655dd74b9005e3a2bacce446f1920cd7017231ae447b67036c9b431b8179deacd5120262d894c26bc015bffe3d827ba7087ad9b700d2ca1f6d16cc1786581e5dd065f293c31209300f9b0afcc3f7c08dd26d0a22d87580b4d00009f592e0619d823953577d4503061706843317e4fee083db41054657374204b65792033202844534129886204131102002205024d6c49de021b03060b090807030206150802090a0b0416020301021e01021780000a0910338934250ccc03607e0400a0bdb9193e8a6b96fc2dfc108ae848914b504481f100a09c4dc148cb693293a67af24dd40d2b13a9e36794" const p256TestKeyHex = "98520456e5b83813082a8648ce3d030107020304a2072cd6d21321266c758cc5b83fab0510f751cb8d91897cddb7047d8d6f185546e2107111b0a95cb8ef063c33245502af7a65f004d5919d93ee74eb71a66253b424502d3235362054657374204b6579203c696e76616c6964406578616d706c652e636f6d3e8879041313080021050256e5b838021b03050b09080702061508090a0b020416020301021e01021780000a0910d44a2c495918513e54e50100dfa64f97d9b47766fc1943c6314ba3f2b2a103d71ad286dc5b1efb96a345b0c80100dbc8150b54241f559da6ef4baacea6d31902b4f4b1bdc09b34bf0502334b7754b8560456e5b83812082a8648ce3d030107020304bfe3cea9cee13486f8d518aa487fecab451f25467d2bf08e58f63e5fa525d5482133e6a79299c274b068ef0be448152ad65cf11cf764348588ca4f6a0bcf22b6030108078861041813080009050256e5b838021b0c000a0910d44a2c495918513e4a4800ff49d589fa64024ad30be363a032e3a0e0e6f5db56ba4c73db850518bf0121b8f20100fd78e065f4c70ea5be9df319ea67e493b936fc78da834a71828043d3154af56e" const p256TestKeyPrivateHex = "94a50456e5b83813082a8648ce3d030107020304a2072cd6d21321266c758cc5b83fab0510f751cb8d91897cddb7047d8d6f185546e2107111b0a95cb8ef063c33245502af7a65f004d5919d93ee74eb71a66253fe070302f0c2bfb0b6c30f87ee1599472b8636477eab23ced13b271886a4b50ed34c9d8436af5af5b8f88921f0efba6ef8c37c459bbb88bc1c6a13bbd25c4ce9b1e97679569ee77645d469bf4b43de637f5561b424502d3235362054657374204b6579203c696e76616c6964406578616d706c652e636f6d3e8879041313080021050256e5b838021b03050b09080702061508090a0b020416020301021e01021780000a0910d44a2c495918513e54e50100dfa64f97d9b47766fc1943c6314ba3f2b2a103d71ad286dc5b1efb96a345b0c80100dbc8150b54241f559da6ef4baacea6d31902b4f4b1bdc09b34bf0502334b77549ca90456e5b83812082a8648ce3d030107020304bfe3cea9cee13486f8d518aa487fecab451f25467d2bf08e58f63e5fa525d5482133e6a79299c274b068ef0be448152ad65cf11cf764348588ca4f6a0bcf22b603010807fe0703027510012471a603cfee2968dce19f732721ddf03e966fd133b4e3c7a685b788705cbc46fb026dc94724b830c9edbaecd2fb2c662f23169516cacd1fe423f0475c364ecc10abcabcfd4bbbda1a36a1bd8861041813080009050256e5b838021b0c000a0910d44a2c495918513e4a4800ff49d589fa64024ad30be363a032e3a0e0e6f5db56ba4c73db850518bf0121b8f20100fd78e065f4c70ea5be9df319ea67e493b936fc78da834a71828043d3154af56e" const armoredPrivateKeyBlock = `-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1.4.10 (GNU/Linux) lQHYBE2rFNoBBADFwqWQIW/DSqcB4yCQqnAFTJ27qS5AnB46ccAdw3u4Greeu3Bp idpoHdjULy7zSKlwR1EA873dO/k/e11Ml3dlAFUinWeejWaK2ugFP6JjiieSsrKn vWNicdCS4HTWn0X4sjl0ZiAygw6GNhqEQ3cpLeL0g8E9hnYzJKQ0LWJa0QARAQAB AAP/TB81EIo2VYNmTq0pK1ZXwUpxCrvAAIG3hwKjEzHcbQznsjNvPUihZ+NZQ6+X 0HCfPAdPkGDCLCb6NavcSW+iNnLTrdDnSI6+3BbIONqWWdRDYJhqZCkqmG6zqSfL IdkJgCw94taUg5BWP/AAeQrhzjChvpMQTVKQL5mnuZbUCeMCAN5qrYMP2S9iKdnk VANIFj7656ARKt/nf4CBzxcpHTyB8+d2CtPDKCmlJP6vL8t58Jmih+kHJMvC0dzn gr5f5+sCAOOe5gt9e0am7AvQWhdbHVfJU0TQJx+m2OiCJAqGTB1nvtBLHdJnfdC9 TnXXQ6ZXibqLyBies/xeY2sCKL5qtTMCAKnX9+9d/5yQxRyrQUHt1NYhaXZnJbHx q4ytu0eWz+5i68IYUSK69jJ1NWPM0T6SkqpB3KCAIv68VFm9PxqG1KmhSrQIVGVz dCBLZXmIuAQTAQIAIgUCTasU2gIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AA CgkQO9o98PRieSoLhgQAkLEZex02Qt7vGhZzMwuN0R22w3VwyYyjBx+fM3JFETy1 ut4xcLJoJfIaF5ZS38UplgakHG0FQ+b49i8dMij0aZmDqGxrew1m4kBfjXw9B/v+ eIqpODryb6cOSwyQFH0lQkXC040pjq9YqDsO5w0WYNXYKDnzRV0p4H1pweo2VDid AdgETasU2gEEAN46UPeWRqKHvA99arOxee38fBt2CI08iiWyI8T3J6ivtFGixSqV bRcPxYO/qLpVe5l84Nb3X71GfVXlc9hyv7CD6tcowL59hg1E/DC5ydI8K8iEpUmK /UnHdIY5h8/kqgGxkY/T/hgp5fRQgW1ZoZxLajVlMRZ8W4tFtT0DeA+JABEBAAEA A/0bE1jaaZKj6ndqcw86jd+QtD1SF+Cf21CWRNeLKnUds4FRRvclzTyUMuWPkUeX TaNNsUOFqBsf6QQ2oHUBBK4VCHffHCW4ZEX2cd6umz7mpHW6XzN4DECEzOVksXtc lUC1j4UB91DC/RNQqwX1IV2QLSwssVotPMPqhOi0ZLNY7wIA3n7DWKInxYZZ4K+6 rQ+POsz6brEoRHwr8x6XlHenq1Oki855pSa1yXIARoTrSJkBtn5oI+f8AzrnN0BN oyeQAwIA/7E++3HDi5aweWrViiul9cd3rcsS0dEnksPhvS0ozCJiHsq/6GFmy7J8 QSHZPteedBnZyNp5jR+H7cIfVN3KgwH/Skq4PsuPhDq5TKK6i8Pc1WW8MA6DXTdU nLkX7RGmMwjC0DBf7KWAlPjFaONAX3a8ndnz//fy1q7u2l9AZwrj1qa1iJ8EGAEC AAkFAk2rFNoCGwwACgkQO9o98PRieSo2/QP/WTzr4ioINVsvN1akKuekmEMI3LAp BfHwatufxxP1U+3Si/6YIk7kuPB9Hs+pRqCXzbvPRrI8NHZBmc8qIGthishdCYad AHcVnXjtxrULkQFGbGvhKURLvS9WnzD/m1K2zzwxzkPTzT9/Yf06O6Mal5AdugPL VrM0m72/jnpKo04= =zNCn -----END PGP PRIVATE KEY BLOCK-----` const e2ePublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- Charset: UTF-8 xv8AAABSBAAAAAATCCqGSM49AwEHAgME1LRoXSpOxtHXDUdmuvzchyg6005qIBJ4 sfaSxX7QgH9RV2ONUhC+WiayCNADq+UMzuR/vunSr4aQffXvuGnR383/AAAAFDxk Z2lsQHlhaG9vLWluYy5jb20+wv8AAACGBBATCAA4/wAAAAWCVGvAG/8AAAACiwn/ AAAACZC2VkQCOjdvYf8AAAAFlQgJCgv/AAAAA5YBAv8AAAACngEAAE1BAP0X8veD 24IjmI5/C6ZAfVNXxgZZFhTAACFX75jUA3oD6AEAzoSwKf1aqH6oq62qhCN/pekX +WAsVMBhNwzLpqtCRjLO/wAAAFYEAAAAABIIKoZIzj0DAQcCAwT50ain7vXiIRv8 B1DO3x3cE/aattZ5sHNixJzRCXi2vQIA5QmOxZ6b5jjUekNbdHG3SZi1a2Ak5mfX fRxC/5VGAwEIB8L/AAAAZQQYEwgAGP8AAAAFglRrwBz/AAAACZC2VkQCOjdvYQAA FJAA9isX3xtGyMLYwp2F3nXm7QEdY5bq5VUcD/RJlj792VwA/1wH0pCzVLl4Q9F9 ex7En5r7rHR5xwX82Msc+Rq9dSyO =7MrZ -----END PGP PUBLIC KEY BLOCK-----` const dsaKeyWithSHA512 = `9901a2044f04b07f110400db244efecc7316553ee08d179972aab87bb1214de7692593fcf5b6feb1c80fba268722dd464748539b85b81d574cd2d7ad0ca2444de4d849b8756bad7768c486c83a824f9bba4af773d11742bdfb4ac3b89ef8cc9452d4aad31a37e4b630d33927bff68e879284a1672659b8b298222fc68f370f3e24dccacc4a862442b9438b00a0ea444a24088dc23e26df7daf8f43cba3bffc4fe703fe3d6cd7fdca199d54ed8ae501c30e3ec7871ea9cdd4cf63cfe6fc82281d70a5b8bb493f922cd99fba5f088935596af087c8d818d5ec4d0b9afa7f070b3d7c1dd32a84fca08d8280b4890c8da1dde334de8e3cad8450eed2a4a4fcc2db7b8e5528b869a74a7f0189e11ef097ef1253582348de072bb07a9fa8ab838e993cef0ee203ff49298723e2d1f549b00559f886cd417a41692ce58d0ac1307dc71d85a8af21b0cf6eaa14baf2922d3a70389bedf17cc514ba0febbd107675a372fe84b90162a9e88b14d4b1c6be855b96b33fb198c46f058568817780435b6936167ebb3724b680f32bf27382ada2e37a879b3d9de2abe0c3f399350afd1ad438883f4791e2e3b4184453412068617368207472756e636174696f6e207465737488620413110a002205024f04b07f021b03060b090807030206150802090a0b0416020301021e01021780000a0910ef20e0cefca131581318009e2bf3bf047a44d75a9bacd00161ee04d435522397009a03a60d51bd8a568c6c021c8d7cf1be8d990d6417b0020003` const unknownHashFunctionHex = `8a00000040040001990006050253863c24000a09103b4fe6acc0b21f32ffff01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101` const missingHashFunctionHex = `8a00000040040001030006050253863c24000a09103b4fe6acc0b21f32ffff0101010101010101010101010101010101010101010101010101010101010101010101010101` const campbellQuine = `a0b001000300fcffa0b001000d00f2ff000300fcffa0b001000d00f2ff8270a01c00000500faff8270a01c00000500faff000500faff001400ebff8270a01c00000500faff000500faff001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400000000ffff000000ffff000b00f4ff428821c400000000ffff000000ffff000b00f4ff0233214c40000100feff000233214c40000100feff0000` const keyV4forVerifyingSignedMessageV3 = `-----BEGIN PGP PUBLIC KEY BLOCK----- Comment: GPGTools - https://gpgtools.org mI0EVfxoFQEEAMBIqmbDfYygcvP6Phr1wr1XI41IF7Qixqybs/foBF8qqblD9gIY BKpXjnBOtbkcVOJ0nljd3/sQIfH4E0vQwK5/4YRQSI59eKOqd6Fx+fWQOLG+uu6z tewpeCj9LLHvibx/Sc7VWRnrznia6ftrXxJ/wHMezSab3tnGC0YPVdGNABEBAAG0 JEdvY3J5cHRvIFRlc3QgS2V5IDx0aGVtYXhAZ21haWwuY29tPoi5BBMBCgAjBQJV /GgVAhsDBwsJCAcDAgEGFQgCCQoLBBYCAwECHgECF4AACgkQeXnQmhdGW9PFVAP+ K7TU0qX5ArvIONIxh/WAweyOk884c5cE8f+3NOPOOCRGyVy0FId5A7MmD5GOQh4H JseOZVEVCqlmngEvtHZb3U1VYtVGE5WZ+6rQhGsMcWP5qaT4soYwMBlSYxgYwQcx YhN9qOr292f9j2Y//TTIJmZT4Oa+lMxhWdqTfX+qMgG4jQRV/GgVAQQArhFSiij1 b+hT3dnapbEU+23Z1yTu1DfF6zsxQ4XQWEV3eR8v+8mEDDNcz8oyyF56k6UQ3rXi UMTIwRDg4V6SbZmaFbZYCOwp/EmXJ3rfhm7z7yzXj2OFN22luuqbyVhuL7LRdB0M pxgmjXb4tTvfgKd26x34S+QqUJ7W6uprY4sAEQEAAYifBBgBCgAJBQJV/GgVAhsM AAoJEHl50JoXRlvT7y8D/02ckx4OMkKBZo7viyrBw0MLG92i+DC2bs35PooHR6zz 786mitjOp5z2QWNLBvxC70S0qVfCIz8jKupO1J6rq6Z8CcbLF3qjm6h1omUBf8Nd EfXKD2/2HV6zMKVknnKzIEzauh+eCKS2CeJUSSSryap/QLVAjRnckaES/OsEWhNB =RZia -----END PGP PUBLIC KEY BLOCK----- ` const signedMessageV3 = `-----BEGIN PGP MESSAGE----- Comment: GPGTools - https://gpgtools.org owGbwMvMwMVYWXlhlrhb9GXG03JJDKF/MtxDMjKLFYAoUaEktbhEITe1uDgxPVWP q5NhKjMrWAVcC9evD8z/bF/uWNjqtk/X3y5/38XGRQHm/57rrDRYuGnTw597Xqka uM3137/hH3Os+Jf2dc0fXOITKwJvXJvecPVs0ta+Vg7ZO1MLn8w58Xx+6L58mbka DGHyU9yTueZE8D+QF/Tz28Y78dqtF56R1VPn9Xw4uJqrWYdd7b3vIZ1V6R4Nh05d iT57d/OhWwA= =hG7R -----END PGP MESSAGE----- ` ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/read.go���������������������������������������������0000644�0610621�0607500�00000032421�13172163317�023766� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package openpgp implements high level operations on OpenPGP messages. package openpgp // import "golang.org/x/crypto/openpgp" import ( "crypto" _ "crypto/sha256" "hash" "io" "strconv" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/packet" ) // SignatureType is the armor type for a PGP signature. var SignatureType = "PGP SIGNATURE" // readArmored reads an armored block with the given type. func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) { block, err := armor.Decode(r) if err != nil { return } if block.Type != expectedType { return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) } return block.Body, nil } // MessageDetails contains the result of parsing an OpenPGP encrypted and/or // signed message. type MessageDetails struct { IsEncrypted bool // true if the message was encrypted. EncryptedToKeyIds []uint64 // the list of recipient key ids. IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message. DecryptedWith Key // the private key used to decrypt the message, if any. IsSigned bool // true if the message is signed. SignedByKeyId uint64 // the key id of the signer, if any. SignedBy *Key // the key of the signer, if available. LiteralData *packet.LiteralData // the metadata of the contents UnverifiedBody io.Reader // the contents of the message. // If IsSigned is true and SignedBy is non-zero then the signature will // be verified as UnverifiedBody is read. The signature cannot be // checked until the whole of UnverifiedBody is read so UnverifiedBody // must be consumed until EOF before the data can be trusted. Even if a // message isn't signed (or the signer is unknown) the data may contain // an authentication code that is only checked once UnverifiedBody has // been consumed. Once EOF has been seen, the following fields are // valid. (An authentication code failure is reported as a // SignatureError error when reading from UnverifiedBody.) SignatureError error // nil if the signature is good. Signature *packet.Signature // the signature packet itself, if v4 (default) SignatureV3 *packet.SignatureV3 // the signature packet if it is a v2 or v3 signature decrypted io.ReadCloser } // A PromptFunction is used as a callback by functions that may need to decrypt // a private key, or prompt for a passphrase. It is called with a list of // acceptable, encrypted private keys and a boolean that indicates whether a // passphrase is usable. It should either decrypt a private key or return a // passphrase to try. If the decrypted private key or given passphrase isn't // correct, the function will be called again, forever. Any error returned will // be passed up. type PromptFunction func(keys []Key, symmetric bool) ([]byte, error) // A keyEnvelopePair is used to store a private key with the envelope that // contains a symmetric key, encrypted with that key. type keyEnvelopePair struct { key Key encryptedKey *packet.EncryptedKey } // ReadMessage parses an OpenPGP message that may be signed and/or encrypted. // The given KeyRing should contain both public keys (for signature // verification) and, possibly encrypted, private keys for decrypting. // If config is nil, sensible defaults will be used. func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) { var p packet.Packet var symKeys []*packet.SymmetricKeyEncrypted var pubKeys []keyEnvelopePair var se *packet.SymmetricallyEncrypted packets := packet.NewReader(r) md = new(MessageDetails) md.IsEncrypted = true // The message, if encrypted, starts with a number of packets // containing an encrypted decryption key. The decryption key is either // encrypted to a public key, or with a passphrase. This loop // collects these packets. ParsePackets: for { p, err = packets.Next() if err != nil { return nil, err } switch p := p.(type) { case *packet.SymmetricKeyEncrypted: // This packet contains the decryption key encrypted with a passphrase. md.IsSymmetricallyEncrypted = true symKeys = append(symKeys, p) case *packet.EncryptedKey: // This packet contains the decryption key encrypted to a public key. md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId) switch p.Algo { case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal: break default: continue } var keys []Key if p.KeyId == 0 { keys = keyring.DecryptionKeys() } else { keys = keyring.KeysById(p.KeyId) } for _, k := range keys { pubKeys = append(pubKeys, keyEnvelopePair{k, p}) } case *packet.SymmetricallyEncrypted: se = p break ParsePackets case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature: // This message isn't encrypted. if len(symKeys) != 0 || len(pubKeys) != 0 { return nil, errors.StructuralError("key material not followed by encrypted message") } packets.Unread(p) return readSignedMessage(packets, nil, keyring) } } var candidates []Key var decrypted io.ReadCloser // Now that we have the list of encrypted keys we need to decrypt at // least one of them or, if we cannot, we need to call the prompt // function so that it can decrypt a key or give us a passphrase. FindKey: for { // See if any of the keys already have a private key available candidates = candidates[:0] candidateFingerprints := make(map[string]bool) for _, pk := range pubKeys { if pk.key.PrivateKey == nil { continue } if !pk.key.PrivateKey.Encrypted { if len(pk.encryptedKey.Key) == 0 { pk.encryptedKey.Decrypt(pk.key.PrivateKey, config) } if len(pk.encryptedKey.Key) == 0 { continue } decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key) if err != nil && err != errors.ErrKeyIncorrect { return nil, err } if decrypted != nil { md.DecryptedWith = pk.key break FindKey } } else { fpr := string(pk.key.PublicKey.Fingerprint[:]) if v := candidateFingerprints[fpr]; v { continue } candidates = append(candidates, pk.key) candidateFingerprints[fpr] = true } } if len(candidates) == 0 && len(symKeys) == 0 { return nil, errors.ErrKeyIncorrect } if prompt == nil { return nil, errors.ErrKeyIncorrect } passphrase, err := prompt(candidates, len(symKeys) != 0) if err != nil { return nil, err } // Try the symmetric passphrase first if len(symKeys) != 0 && passphrase != nil { for _, s := range symKeys { key, cipherFunc, err := s.Decrypt(passphrase) if err == nil { decrypted, err = se.Decrypt(cipherFunc, key) if err != nil && err != errors.ErrKeyIncorrect { return nil, err } if decrypted != nil { break FindKey } } } } } md.decrypted = decrypted if err := packets.Push(decrypted); err != nil { return nil, err } return readSignedMessage(packets, md, keyring) } // readSignedMessage reads a possibly signed message if mdin is non-zero then // that structure is updated and returned. Otherwise a fresh MessageDetails is // used. func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) { if mdin == nil { mdin = new(MessageDetails) } md = mdin var p packet.Packet var h hash.Hash var wrappedHash hash.Hash FindLiteralData: for { p, err = packets.Next() if err != nil { return nil, err } switch p := p.(type) { case *packet.Compressed: if err := packets.Push(p.Body); err != nil { return nil, err } case *packet.OnePassSignature: if !p.IsLast { return nil, errors.UnsupportedError("nested signatures") } h, wrappedHash, err = hashForSignature(p.Hash, p.SigType) if err != nil { md = nil return } md.IsSigned = true md.SignedByKeyId = p.KeyId keys := keyring.KeysByIdUsage(p.KeyId, packet.KeyFlagSign) if len(keys) > 0 { md.SignedBy = &keys[0] } case *packet.LiteralData: md.LiteralData = p break FindLiteralData } } if md.SignedBy != nil { md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md} } else if md.decrypted != nil { md.UnverifiedBody = checkReader{md} } else { md.UnverifiedBody = md.LiteralData.Body } return md, nil } // hashForSignature returns a pair of hashes that can be used to verify a // signature. The signature may specify that the contents of the signed message // should be preprocessed (i.e. to normalize line endings). Thus this function // returns two hashes. The second should be used to hash the message itself and // performs any needed preprocessing. func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) { if !hashId.Available() { return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId))) } h := hashId.New() switch sigType { case packet.SigTypeBinary: return h, h, nil case packet.SigTypeText: return h, NewCanonicalTextHash(h), nil } return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType))) } // checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF // it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger // MDC checks. type checkReader struct { md *MessageDetails } func (cr checkReader) Read(buf []byte) (n int, err error) { n, err = cr.md.LiteralData.Body.Read(buf) if err == io.EOF { mdcErr := cr.md.decrypted.Close() if mdcErr != nil { err = mdcErr } } return } // signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes // the data as it is read. When it sees an EOF from the underlying io.Reader // it parses and checks a trailing Signature packet and triggers any MDC checks. type signatureCheckReader struct { packets *packet.Reader h, wrappedHash hash.Hash md *MessageDetails } func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) { n, err = scr.md.LiteralData.Body.Read(buf) scr.wrappedHash.Write(buf[:n]) if err == io.EOF { var p packet.Packet p, scr.md.SignatureError = scr.packets.Next() if scr.md.SignatureError != nil { return } var ok bool if scr.md.Signature, ok = p.(*packet.Signature); ok { scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) } else if scr.md.SignatureV3, ok = p.(*packet.SignatureV3); ok { scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignatureV3(scr.h, scr.md.SignatureV3) } else { scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature") return } // The SymmetricallyEncrypted packet, if any, might have an // unsigned hash of its own. In order to check this we need to // close that Reader. if scr.md.decrypted != nil { mdcErr := scr.md.decrypted.Close() if mdcErr != nil { err = mdcErr } } } return } // CheckDetachedSignature takes a signed file and a detached signature and // returns the signer if the signature is valid. If the signer isn't known, // ErrUnknownIssuer is returned. func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { var issuerKeyId uint64 var hashFunc crypto.Hash var sigType packet.SignatureType var keys []Key var p packet.Packet packets := packet.NewReader(signature) for { p, err = packets.Next() if err == io.EOF { return nil, errors.ErrUnknownIssuer } if err != nil { return nil, err } switch sig := p.(type) { case *packet.Signature: if sig.IssuerKeyId == nil { return nil, errors.StructuralError("signature doesn't have an issuer") } issuerKeyId = *sig.IssuerKeyId hashFunc = sig.Hash sigType = sig.SigType case *packet.SignatureV3: issuerKeyId = sig.IssuerKeyId hashFunc = sig.Hash sigType = sig.SigType default: return nil, errors.StructuralError("non signature packet found") } keys = keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign) if len(keys) > 0 { break } } if len(keys) == 0 { panic("unreachable") } h, wrappedHash, err := hashForSignature(hashFunc, sigType) if err != nil { return nil, err } if _, err := io.Copy(wrappedHash, signed); err != nil && err != io.EOF { return nil, err } for _, key := range keys { switch sig := p.(type) { case *packet.Signature: err = key.PublicKey.VerifySignature(h, sig) case *packet.SignatureV3: err = key.PublicKey.VerifySignatureV3(h, sig) default: panic("unreachable") } if err == nil { return key.Entity, nil } } return nil, err } // CheckArmoredDetachedSignature performs the same actions as // CheckDetachedSignature but expects the signature to be armored. func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { body, err := readArmored(signature, SignatureType) if err != nil { return } return CheckDetachedSignature(keyring, signed, body) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/���������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023771� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/userid_test.go�������������������������������0000644�0610621�0607500�00000004404�13172163317�026654� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "testing" ) var userIdTests = []struct { id string name, comment, email string }{ {"", "", "", ""}, {"John Smith", "John Smith", "", ""}, {"John Smith ()", "John Smith", "", ""}, {"John Smith () <>", "John Smith", "", ""}, {"(comment", "", "comment", ""}, {"(comment)", "", "comment", ""}, {"<email", "", "", "email"}, {"<email> sdfk", "", "", "email"}, {" John Smith ( Comment ) asdkflj < email > lksdfj", "John Smith", "Comment", "email"}, {" John Smith < email > lksdfj", "John Smith", "", "email"}, {"(<foo", "", "<foo", ""}, {"René Descartes (العربي)", "René Descartes", "العربي", ""}, } func TestParseUserId(t *testing.T) { for i, test := range userIdTests { name, comment, email := parseUserId(test.id) if name != test.name { t.Errorf("%d: name mismatch got:%s want:%s", i, name, test.name) } if comment != test.comment { t.Errorf("%d: comment mismatch got:%s want:%s", i, comment, test.comment) } if email != test.email { t.Errorf("%d: email mismatch got:%s want:%s", i, email, test.email) } } } var newUserIdTests = []struct { name, comment, email, id string }{ {"foo", "", "", "foo"}, {"", "bar", "", "(bar)"}, {"", "", "baz", "<baz>"}, {"foo", "bar", "", "foo (bar)"}, {"foo", "", "baz", "foo <baz>"}, {"", "bar", "baz", "(bar) <baz>"}, {"foo", "bar", "baz", "foo (bar) <baz>"}, } func TestNewUserId(t *testing.T) { for i, test := range newUserIdTests { uid := NewUserId(test.name, test.comment, test.email) if uid == nil { t.Errorf("#%d: returned nil", i) continue } if uid.Id != test.id { t.Errorf("#%d: got '%s', want '%s'", i, uid.Id, test.id) } } } var invalidNewUserIdTests = []struct { name, comment, email string }{ {"foo(", "", ""}, {"foo<", "", ""}, {"", "bar)", ""}, {"", "bar<", ""}, {"", "", "baz>"}, {"", "", "baz)"}, {"", "", "baz\x00"}, } func TestNewUserIdWithInvalidInput(t *testing.T) { for i, test := range invalidNewUserIdTests { if uid := NewUserId(test.name, test.comment, test.email); uid != nil { t.Errorf("#%d: returned non-nil value: %#v", i, uid) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/userid.go������������������������������������0000644�0610621�0607500�00000006676�13172163317�025632� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "io" "io/ioutil" "strings" ) // UserId contains text that is intended to represent the name and email // address of the key holder. See RFC 4880, section 5.11. By convention, this // takes the form "Full Name (Comment) <email@example.com>" type UserId struct { Id string // By convention, this takes the form "Full Name (Comment) <email@example.com>" which is split out in the fields below. Name, Comment, Email string } func hasInvalidCharacters(s string) bool { for _, c := range s { switch c { case '(', ')', '<', '>', 0: return true } } return false } // NewUserId returns a UserId or nil if any of the arguments contain invalid // characters. The invalid characters are '\x00', '(', ')', '<' and '>' func NewUserId(name, comment, email string) *UserId { // RFC 4880 doesn't deal with the structure of userid strings; the // name, comment and email form is just a convention. However, there's // no convention about escaping the metacharacters and GPG just refuses // to create user ids where, say, the name contains a '('. We mirror // this behaviour. if hasInvalidCharacters(name) || hasInvalidCharacters(comment) || hasInvalidCharacters(email) { return nil } uid := new(UserId) uid.Name, uid.Comment, uid.Email = name, comment, email uid.Id = name if len(comment) > 0 { if len(uid.Id) > 0 { uid.Id += " " } uid.Id += "(" uid.Id += comment uid.Id += ")" } if len(email) > 0 { if len(uid.Id) > 0 { uid.Id += " " } uid.Id += "<" uid.Id += email uid.Id += ">" } return uid } func (uid *UserId) parse(r io.Reader) (err error) { // RFC 4880, section 5.11 b, err := ioutil.ReadAll(r) if err != nil { return } uid.Id = string(b) uid.Name, uid.Comment, uid.Email = parseUserId(uid.Id) return } // Serialize marshals uid to w in the form of an OpenPGP packet, including // header. func (uid *UserId) Serialize(w io.Writer) error { err := serializeHeader(w, packetTypeUserId, len(uid.Id)) if err != nil { return err } _, err = w.Write([]byte(uid.Id)) return err } // parseUserId extracts the name, comment and email from a user id string that // is formatted as "Full Name (Comment) <email@example.com>". func parseUserId(id string) (name, comment, email string) { var n, c, e struct { start, end int } var state int for offset, rune := range id { switch state { case 0: // Entering name n.start = offset state = 1 fallthrough case 1: // In name if rune == '(' { state = 2 n.end = offset } else if rune == '<' { state = 5 n.end = offset } case 2: // Entering comment c.start = offset state = 3 fallthrough case 3: // In comment if rune == ')' { state = 4 c.end = offset } case 4: // Between comment and email if rune == '<' { state = 5 } case 5: // Entering email e.start = offset state = 6 fallthrough case 6: // In email if rune == '>' { state = 7 e.end = offset } default: // After email } } switch state { case 1: // ended in the name n.end = len(id) case 3: // ended in comment c.end = len(id) case 6: // ended in email e.end = len(id) } name = strings.TrimSpace(id[n.start:n.end]) comment = strings.TrimSpace(id[c.start:c.end]) email = strings.TrimSpace(id[e.start:e.end]) return } ������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/userattribute_test.go������������������������0000644�0610621�0607500�00000013361�13172163317�030265� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/base64" "image/color" "image/jpeg" "testing" ) func TestParseUserAttribute(t *testing.T) { r := base64.NewDecoder(base64.StdEncoding, bytes.NewBufferString(userAttributePacket)) for i := 0; i < 2; i++ { p, err := Read(r) if err != nil { t.Fatal(err) } uat := p.(*UserAttribute) imgs := uat.ImageData() if len(imgs) != 1 { t.Errorf("Unexpected number of images in user attribute packet: %d", len(imgs)) } if len(imgs[0]) != 3395 { t.Errorf("Unexpected JPEG image size: %d", len(imgs[0])) } img, err := jpeg.Decode(bytes.NewBuffer(imgs[0])) if err != nil { t.Errorf("Error decoding JPEG image: %v", err) } // A pixel in my right eye. pixel := color.NRGBAModel.Convert(img.At(56, 36)) ref := color.NRGBA{R: 157, G: 128, B: 124, A: 255} if pixel != ref { t.Errorf("Unexpected pixel color: %v", pixel) } w := bytes.NewBuffer(nil) err = uat.Serialize(w) if err != nil { t.Errorf("Error writing user attribute: %v", err) } r = bytes.NewBuffer(w.Bytes()) } } const userAttributePacket = ` 0cyWzJQBEAABAQAAAAAAAAAAAAAAAP/Y/+AAEEpGSUYAAQIAAAEAAQAA/9sAQwAFAwQEBAMFBAQE BQUFBgcMCAcHBwcPCgsJDBEPEhIRDxEQExYcFxMUGhUQERghGBocHR8fHxMXIiQiHiQcHh8e/9sA QwEFBQUHBgcOCAgOHhQRFB4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e Hh4eHh4eHh4e/8AAEQgAZABkAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYH CAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHw JDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6 g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk 5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIB AgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEX GBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKT lJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX2 9/j5+v/aAAwDAQACEQMRAD8A5uGP06VehQ4pIox04q5EnHSvAep+hIIl4zVuMHGPWmRrUWtalaaN pU2oXsgSGJSxPr6ClvoitErs0Itqjc7BQOpPAFYmrfEnwjojtHNqaXEynBjtx5hH4jj9a8B8d+Od W8UXZjWR4LJT+7t0Jwfc+prnIdO1CWZEW2mZ3HyDactXXDB3V5s8evm1namj6r0H4weCLtxG+ova ueP30RA/MV6not1bX0Ed1ZzxzwyDKvGwZSPqK+Ff+ES8R8t/ZV2oHUmM10Hgbxp4m8BatEfNnWBH /eWshOxx9Kmpg4te49RUM1kn+8Wh9zQ4P1FaMC7l465rjPh14y0fxnoseoaXOpfaPOgJ+eI98j09 67W19M15bi4uzPSqTU480WXkjZkAyAR61DPE6OCSOalWRRgZxjvTb598sfU4FBwx5uY4T4feIm8P TeJbAgc65NIM+8cX+FFeLfF3Vr3SfiNrMFrMypJMJcDPUqP8KK+kpVFyLU+ar037SXqX4hxVpMY7 1UhPpVlT2rybKx9smWYz3NeH/EDVLzxt40j8O6bITaQybPlbKkjq39K9O8fasdH8IahfKxWQRFIy Ou9uB/OuE/Z/0y3j1d9TuyoZCMs5xjuea1pLli5nn46q240l13PcfhN8EvDNtpcEl/CklyVBLuMk mvU/Dfwo0BL/AO13FjEDD/qyV7Vn+CvGPg8zRpJrVm8ikLtEg6+1ew2dxZ3EQaJgysuQPasH7eXW 1zzsbVhT92kk/PsYieEND+zlPs6c/wCyAPyryH4wfCPRtW0u6j+xRLOxLxSoADkDpXY+MPjJ4c0S 9k082d3O8ZKkxw5XI96ytK+IGk+IpFjRpod+Qq3C7QT6A1E6NenaXbqRg6rlLlqS0fRnxjpd1r/w w8afa7GWRPKbZLGeBKmeVNfZngLxNaeKfDdprVjxHcLlkJ5Vh1H5185/tDad9h8XOsqAw3Cb0cjq CfX61P8AsveKf7L8T3fhe5nxa3g324YniQdh9R/KuivTdSmp9TXB1/Z1nRlsfU249QBx1pWfcwI7 Cq6u2Ovamb9rYz16V5x7Psz5q/aJhZfibcupIElvE3H+7j+lFbXx9szP45jlUfeso8/99OKK9elL 3EeNVopzZVharCtxVRGGMk02S5JyFOB69zWTieypnL/GksfB+0cr9oQt69awPhPpD69Y3Ky3DWth CWluGU4LAdq3vibGs/g68BJygVxjrwRW5+ztoRv/AAs8EeCZnO/J/hzz/Kumi4wp3kePjlOdZKPY ml8Mvo6WM9ppi7J0EkQYMzkb1X0wW+bJHGACa+ivg14huZPCkjXUO6SImIYOQAP6UQ2sGneHmiWF CYoSAAuM8etXfhBpMr+EZ3SSNRcMx6ZxWdes6ytBGSwkMNFuo7pnP614Ut9Zn1C4uLySKcwObGFA Qnm4+XcR71h+CfDHiKCQWuv2YWFtw+bBZQD8rcE8n2Ney+GbGGQSM6I7xvtI681rXdp8hKRRp6t3 FYPE1VDlsY1nQjWdl+J8w/tOeDZZ/AMd/EGefTHyxxyYjwfyODXg3waRh8UtEcFh+8Jb8FNfZPxh Ak8J6nbPIsiyW7LnseK+Ofh99ptPHFnf2lu0y2twGcKuSEPB/Q1WHk50miq1o14TXU+xop+On61H NMC6Nis1LgsAcUTSt1APFcXJZn0EqmhyvxA037friTYziBV6f7Tf40Vr3k4aXLx5OMZIzRXZB2ik efJXbPHJJcnaD9aN2R1qoGO8/WkuLlIV+YjdjpXSonQ5lTxfiTwzqCnkeQxx9BWx+zPrQsrBFYja zEfrXL6lfie3khcjY6lSPUGud+G3iA6FrY0uQ/KJsA9gCa0jSvFpnBi6tpKSPu++nsIfDFxeXciR qIicscY4rxTwB8RUkn1axsPEf2LTYx85kTGzqCUP8VcJ47+JOs+I0Hhq1njjt/ufIeSvq1VtE+Gs eoaUbSHUrkHdu3WtuX5Ix81XRh7OL5jirVpV5Whdn0F8C/iX4auVn0i612T7bASoe8wjTAd89K9g vtSt5NMa4t5lkRhgOh3Dn6V8aaz8KZrIR3OlQ6r56LySmSxxz06Vo/CHx34h0rxBP4XvJ5AjK2RP nEbAEj6ZxjPrWM6fMmoswqJxqJ1VZnqHxn1NLPwveqWHmNC2BnnNcD8DfDkGi+CH1m+ijN1qMzNA 4GSIiAMf+hVxPxU8Tapc3c0F9MGCn5GU5BX0Pau3+HmrT3XgXSIJCBHDGdgAx1NYSpezha52Yauq 1dya2Wh2onAIwTj1p0lxxWWLkhRyCKWa5O3ORXOos9KVQluZm83j0oqi84JyWH50Vdmc7ep43d3I t1Z2Iz2FYdxeSTsxyRnvTdVuDNcNluM9KrKcg817NOnZGNbEXdkNckjrXGeIIprPxFFdRHAlIwem COtdmxrG8Q2cd/ZNExw45RvQ1bVjim+dWNzw7eaTD4mN3dndCQCo6hmI5zXpj/Ea/wBHjkh0kwRW xXEfl4yTxXzXZalJDL9nuWKMmRnHcV2Hh3WreCyYXW2SWQhd5P3F6n+lS43d2cTm6d7Ox9EWPxH1 ODQxPqWpCaSU/ukUc4z3/WvKW8UhviAdaMewYZG98gj9c1ymoa8LyWOJHwkTDaVPb0qpr+q2m6Nb cfvNo349az9mou9iZVXNWbub3jm98/Vza2ReV7lsJg/e3dsV654UR9N0K0sZP9ZDGFbHr3rzL4P+ H7rXfEEWr3I3W1qf3IYdW9fwqDxf4k8UeH/G95p08kscHmk25dPlZT0we9YTj7SXKjpw1aNG8mj3 FLv5ccU959ycnmvKPDnxB82YQarGsZPAlTp+IrvIr1ZIgySKwIyCOhFYTpyg9T0qWIhVV4svzPvf IdhgY4orPachj81FRdmtzxqdiZmJ9aQEgdqZcPtmbJ71DJcAZ5r20kkeXJtsfPIQDwPzrG1a+S3i LyHAHvmp7y7HOD1rlNdm+1T7Acovf3o+J2RMpezjzMvrob67pX9o2ShZlYgg/wAWKxZLLWLZ/Ke3 mVh14yK9M+BMC3dre2ko3LHKCB7EV7EngeGQJdQ7HyBkMKS0djgq1W3c+XtK03U522RwzsTwNiEk ntXoHgf4calql9El/G8UZbLfLyfr7V9FeGvh+s+0Lbxxcglu2K1NW1nwN4Gk/wBLuI57tV5jjwzE /QVNS+0dWYRqNvXRFv4eeCodKsY1ggVIY1G3K4z714h+1Jqul3GpwaXYeXJLbzgyyrg4b+6D+HNb vjz436zq9m+naHF/ZdkeGfOZXH17V4Vqt2b29K+ZuOc5bnce5zWdPBShL2lTfojSeJhy+zp/NjVz 1Bwa6DSfFGq6fbJFDKrov8DjPFcu97ZxsUe4jVhwVJ5Bpp1mwQiLewJPXacVq6fNpYyjOUXdHoKf EG8VQHsInbuVcgflRXnt5fIs2FYHgcgUVi8LG+xusdW/mN7U2KgEVkTzPt60UVfQ9eHxGHrV1MGi iD4V25x1qvdgLAMd6KK0pbHm4x++dp8FtUubLxJ5EIjMc+A4Za+qfD8pe1JZVOBmiinW3RyRPMfi R8QPE638+k2l6LK0Hylbddhb6nOa80mlkcmWR2kcnlnOSaKK7qCXKcNdu5narcSrAoBxvODWJIga VckjDdqKKwq/EaQ0gUdbjQ6mr7QGBUcd6tPBC6gtGpOOuKKKie5qn7qIpEXd0HSiiimSf//Z` �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/userattribute.go�����������������������������0000644�0610621�0607500�00000004746�13172163317�027235� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "image" "image/jpeg" "io" "io/ioutil" ) const UserAttrImageSubpacket = 1 // UserAttribute is capable of storing other types of data about a user // beyond name, email and a text comment. In practice, user attributes are typically used // to store a signed thumbnail photo JPEG image of the user. // See RFC 4880, section 5.12. type UserAttribute struct { Contents []*OpaqueSubpacket } // NewUserAttributePhoto creates a user attribute packet // containing the given images. func NewUserAttributePhoto(photos ...image.Image) (uat *UserAttribute, err error) { uat = new(UserAttribute) for _, photo := range photos { var buf bytes.Buffer // RFC 4880, Section 5.12.1. data := []byte{ 0x10, 0x00, // Little-endian image header length (16 bytes) 0x01, // Image header version 1 0x01, // JPEG 0, 0, 0, 0, // 12 reserved octets, must be all zero. 0, 0, 0, 0, 0, 0, 0, 0} if _, err = buf.Write(data); err != nil { return } if err = jpeg.Encode(&buf, photo, nil); err != nil { return } uat.Contents = append(uat.Contents, &OpaqueSubpacket{ SubType: UserAttrImageSubpacket, Contents: buf.Bytes()}) } return } // NewUserAttribute creates a new user attribute packet containing the given subpackets. func NewUserAttribute(contents ...*OpaqueSubpacket) *UserAttribute { return &UserAttribute{Contents: contents} } func (uat *UserAttribute) parse(r io.Reader) (err error) { // RFC 4880, section 5.13 b, err := ioutil.ReadAll(r) if err != nil { return } uat.Contents, err = OpaqueSubpackets(b) return } // Serialize marshals the user attribute to w in the form of an OpenPGP packet, including // header. func (uat *UserAttribute) Serialize(w io.Writer) (err error) { var buf bytes.Buffer for _, sp := range uat.Contents { sp.Serialize(&buf) } if err = serializeHeader(w, packetTypeUserAttribute, buf.Len()); err != nil { return err } _, err = w.Write(buf.Bytes()) return } // ImageData returns zero or more byte slices, each containing // JPEG File Interchange Format (JFIF), for each photo in the // the user attribute packet. func (uat *UserAttribute) ImageData() (imageData [][]byte) { for _, sp := range uat.Contents { if sp.SubType == UserAttrImageSubpacket && len(sp.Contents) > 16 { imageData = append(imageData, sp.Contents[16:]) } } return } ��������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/symmetrically_encrypted_test.go��������������0000644�0610621�0607500�00000005373�13172163317�032342� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto/sha1" "encoding/hex" "golang.org/x/crypto/openpgp/errors" "io" "io/ioutil" "testing" ) // TestReader wraps a []byte and returns reads of a specific length. type testReader struct { data []byte stride int } func (t *testReader) Read(buf []byte) (n int, err error) { n = t.stride if n > len(t.data) { n = len(t.data) } if n > len(buf) { n = len(buf) } copy(buf, t.data) t.data = t.data[n:] if len(t.data) == 0 { err = io.EOF } return } func testMDCReader(t *testing.T) { mdcPlaintext, _ := hex.DecodeString(mdcPlaintextHex) for stride := 1; stride < len(mdcPlaintext)/2; stride++ { r := &testReader{data: mdcPlaintext, stride: stride} mdcReader := &seMDCReader{in: r, h: sha1.New()} body, err := ioutil.ReadAll(mdcReader) if err != nil { t.Errorf("stride: %d, error: %s", stride, err) continue } if !bytes.Equal(body, mdcPlaintext[:len(mdcPlaintext)-22]) { t.Errorf("stride: %d: bad contents %x", stride, body) continue } err = mdcReader.Close() if err != nil { t.Errorf("stride: %d, error on Close: %s", stride, err) } } mdcPlaintext[15] ^= 80 r := &testReader{data: mdcPlaintext, stride: 2} mdcReader := &seMDCReader{in: r, h: sha1.New()} _, err := ioutil.ReadAll(mdcReader) if err != nil { t.Errorf("corruption test, error: %s", err) return } err = mdcReader.Close() if err == nil { t.Error("corruption: no error") } else if _, ok := err.(*errors.SignatureError); !ok { t.Errorf("corruption: expected SignatureError, got: %s", err) } } const mdcPlaintextHex = "a302789c3b2d93c4e0eb9aba22283539b3203335af44a134afb800c849cb4c4de10200aff40b45d31432c80cb384299a0655966d6939dfdeed1dddf980" func TestSerialize(t *testing.T) { buf := bytes.NewBuffer(nil) c := CipherAES128 key := make([]byte, c.KeySize()) w, err := SerializeSymmetricallyEncrypted(buf, c, key, nil) if err != nil { t.Errorf("error from SerializeSymmetricallyEncrypted: %s", err) return } contents := []byte("hello world\n") w.Write(contents) w.Close() p, err := Read(buf) if err != nil { t.Errorf("error from Read: %s", err) return } se, ok := p.(*SymmetricallyEncrypted) if !ok { t.Errorf("didn't read a *SymmetricallyEncrypted") return } r, err := se.Decrypt(c, key) if err != nil { t.Errorf("error from Decrypt: %s", err) return } contentsCopy := bytes.NewBuffer(nil) _, err = io.Copy(contentsCopy, r) if err != nil { t.Errorf("error from io.Copy: %s", err) return } if !bytes.Equal(contentsCopy.Bytes(), contents) { t.Errorf("contents not equal got: %x want: %x", contentsCopy.Bytes(), contents) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/symmetrically_encrypted.go�������������������0000644�0610621�0607500�00000016114�13172163317�031276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "crypto/cipher" "crypto/sha1" "crypto/subtle" "golang.org/x/crypto/openpgp/errors" "hash" "io" "strconv" ) // SymmetricallyEncrypted represents a symmetrically encrypted byte string. The // encrypted contents will consist of more OpenPGP packets. See RFC 4880, // sections 5.7 and 5.13. type SymmetricallyEncrypted struct { MDC bool // true iff this is a type 18 packet and thus has an embedded MAC. contents io.Reader prefix []byte } const symmetricallyEncryptedVersion = 1 func (se *SymmetricallyEncrypted) parse(r io.Reader) error { if se.MDC { // See RFC 4880, section 5.13. var buf [1]byte _, err := readFull(r, buf[:]) if err != nil { return err } if buf[0] != symmetricallyEncryptedVersion { return errors.UnsupportedError("unknown SymmetricallyEncrypted version") } } se.contents = r return nil } // Decrypt returns a ReadCloser, from which the decrypted contents of the // packet can be read. An incorrect key can, with high probability, be detected // immediately and this will result in a KeyIncorrect error being returned. func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.ReadCloser, error) { keySize := c.KeySize() if keySize == 0 { return nil, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(c))) } if len(key) != keySize { return nil, errors.InvalidArgumentError("SymmetricallyEncrypted: incorrect key length") } if se.prefix == nil { se.prefix = make([]byte, c.blockSize()+2) _, err := readFull(se.contents, se.prefix) if err != nil { return nil, err } } else if len(se.prefix) != c.blockSize()+2 { return nil, errors.InvalidArgumentError("can't try ciphers with different block lengths") } ocfbResync := OCFBResync if se.MDC { // MDC packets use a different form of OCFB mode. ocfbResync = OCFBNoResync } s := NewOCFBDecrypter(c.new(key), se.prefix, ocfbResync) if s == nil { return nil, errors.ErrKeyIncorrect } plaintext := cipher.StreamReader{S: s, R: se.contents} if se.MDC { // MDC packets have an embedded hash that we need to check. h := sha1.New() h.Write(se.prefix) return &seMDCReader{in: plaintext, h: h}, nil } // Otherwise, we just need to wrap plaintext so that it's a valid ReadCloser. return seReader{plaintext}, nil } // seReader wraps an io.Reader with a no-op Close method. type seReader struct { in io.Reader } func (ser seReader) Read(buf []byte) (int, error) { return ser.in.Read(buf) } func (ser seReader) Close() error { return nil } const mdcTrailerSize = 1 /* tag byte */ + 1 /* length byte */ + sha1.Size // An seMDCReader wraps an io.Reader, maintains a running hash and keeps hold // of the most recent 22 bytes (mdcTrailerSize). Upon EOF, those bytes form an // MDC packet containing a hash of the previous contents which is checked // against the running hash. See RFC 4880, section 5.13. type seMDCReader struct { in io.Reader h hash.Hash trailer [mdcTrailerSize]byte scratch [mdcTrailerSize]byte trailerUsed int error bool eof bool } func (ser *seMDCReader) Read(buf []byte) (n int, err error) { if ser.error { err = io.ErrUnexpectedEOF return } if ser.eof { err = io.EOF return } // If we haven't yet filled the trailer buffer then we must do that // first. for ser.trailerUsed < mdcTrailerSize { n, err = ser.in.Read(ser.trailer[ser.trailerUsed:]) ser.trailerUsed += n if err == io.EOF { if ser.trailerUsed != mdcTrailerSize { n = 0 err = io.ErrUnexpectedEOF ser.error = true return } ser.eof = true n = 0 return } if err != nil { n = 0 return } } // If it's a short read then we read into a temporary buffer and shift // the data into the caller's buffer. if len(buf) <= mdcTrailerSize { n, err = readFull(ser.in, ser.scratch[:len(buf)]) copy(buf, ser.trailer[:n]) ser.h.Write(buf[:n]) copy(ser.trailer[:], ser.trailer[n:]) copy(ser.trailer[mdcTrailerSize-n:], ser.scratch[:]) if n < len(buf) { ser.eof = true err = io.EOF } return } n, err = ser.in.Read(buf[mdcTrailerSize:]) copy(buf, ser.trailer[:]) ser.h.Write(buf[:n]) copy(ser.trailer[:], buf[n:]) if err == io.EOF { ser.eof = true } return } // This is a new-format packet tag byte for a type 19 (MDC) packet. const mdcPacketTagByte = byte(0x80) | 0x40 | 19 func (ser *seMDCReader) Close() error { if ser.error { return errors.SignatureError("error during reading") } for !ser.eof { // We haven't seen EOF so we need to read to the end var buf [1024]byte _, err := ser.Read(buf[:]) if err == io.EOF { break } if err != nil { return errors.SignatureError("error during reading") } } if ser.trailer[0] != mdcPacketTagByte || ser.trailer[1] != sha1.Size { return errors.SignatureError("MDC packet not found") } ser.h.Write(ser.trailer[:2]) final := ser.h.Sum(nil) if subtle.ConstantTimeCompare(final, ser.trailer[2:]) != 1 { return errors.SignatureError("hash mismatch") } return nil } // An seMDCWriter writes through to an io.WriteCloser while maintains a running // hash of the data written. On close, it emits an MDC packet containing the // running hash. type seMDCWriter struct { w io.WriteCloser h hash.Hash } func (w *seMDCWriter) Write(buf []byte) (n int, err error) { w.h.Write(buf) return w.w.Write(buf) } func (w *seMDCWriter) Close() (err error) { var buf [mdcTrailerSize]byte buf[0] = mdcPacketTagByte buf[1] = sha1.Size w.h.Write(buf[:2]) digest := w.h.Sum(nil) copy(buf[2:], digest) _, err = w.w.Write(buf[:]) if err != nil { return } return w.w.Close() } // noOpCloser is like an ioutil.NopCloser, but for an io.Writer. type noOpCloser struct { w io.Writer } func (c noOpCloser) Write(data []byte) (n int, err error) { return c.w.Write(data) } func (c noOpCloser) Close() error { return nil } // SerializeSymmetricallyEncrypted serializes a symmetrically encrypted packet // to w and returns a WriteCloser to which the to-be-encrypted packets can be // written. // If config is nil, sensible defaults will be used. func SerializeSymmetricallyEncrypted(w io.Writer, c CipherFunction, key []byte, config *Config) (contents io.WriteCloser, err error) { if c.KeySize() != len(key) { return nil, errors.InvalidArgumentError("SymmetricallyEncrypted.Serialize: bad key length") } writeCloser := noOpCloser{w} ciphertext, err := serializeStreamHeader(writeCloser, packetTypeSymmetricallyEncryptedMDC) if err != nil { return } _, err = ciphertext.Write([]byte{symmetricallyEncryptedVersion}) if err != nil { return } block := c.new(key) blockSize := block.BlockSize() iv := make([]byte, blockSize) _, err = config.Random().Read(iv) if err != nil { return } s, prefix := NewOCFBEncrypter(block, iv, OCFBNoResync) _, err = ciphertext.Write(prefix) if err != nil { return } plaintext := cipher.StreamWriter{S: s, W: ciphertext} h := sha1.New() h.Write(iv) h.Write(iv[blockSize-2:]) contents = &seMDCWriter{w: plaintext, h: h} return } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/symmetric_key_encrypted_test.go��������������0000644�0610621�0607500�00000006021�13172163317�032317� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/hex" "io" "io/ioutil" "testing" ) func TestSymmetricKeyEncrypted(t *testing.T) { buf := readerFromHex(symmetricallyEncryptedHex) packet, err := Read(buf) if err != nil { t.Errorf("failed to read SymmetricKeyEncrypted: %s", err) return } ske, ok := packet.(*SymmetricKeyEncrypted) if !ok { t.Error("didn't find SymmetricKeyEncrypted packet") return } key, cipherFunc, err := ske.Decrypt([]byte("password")) if err != nil { t.Error(err) return } packet, err = Read(buf) if err != nil { t.Errorf("failed to read SymmetricallyEncrypted: %s", err) return } se, ok := packet.(*SymmetricallyEncrypted) if !ok { t.Error("didn't find SymmetricallyEncrypted packet") return } r, err := se.Decrypt(cipherFunc, key) if err != nil { t.Error(err) return } contents, err := ioutil.ReadAll(r) if err != nil && err != io.EOF { t.Error(err) return } expectedContents, _ := hex.DecodeString(symmetricallyEncryptedContentsHex) if !bytes.Equal(expectedContents, contents) { t.Errorf("bad contents got:%x want:%x", contents, expectedContents) } } const symmetricallyEncryptedHex = "8c0d04030302371a0b38d884f02060c91cf97c9973b8e58e028e9501708ccfe618fb92afef7fa2d80ddadd93cf" const symmetricallyEncryptedContentsHex = "cb1062004d14c4df636f6e74656e74732e0a" func TestSerializeSymmetricKeyEncryptedCiphers(t *testing.T) { tests := [...]struct { cipherFunc CipherFunction name string }{ {Cipher3DES, "Cipher3DES"}, {CipherCAST5, "CipherCAST5"}, {CipherAES128, "CipherAES128"}, {CipherAES192, "CipherAES192"}, {CipherAES256, "CipherAES256"}, } for _, test := range tests { var buf bytes.Buffer passphrase := []byte("testing") config := &Config{ DefaultCipher: test.cipherFunc, } key, err := SerializeSymmetricKeyEncrypted(&buf, passphrase, config) if err != nil { t.Errorf("cipher(%s) failed to serialize: %s", test.name, err) continue } p, err := Read(&buf) if err != nil { t.Errorf("cipher(%s) failed to reparse: %s", test.name, err) continue } ske, ok := p.(*SymmetricKeyEncrypted) if !ok { t.Errorf("cipher(%s) parsed a different packet type: %#v", test.name, p) continue } if ske.CipherFunc != config.DefaultCipher { t.Errorf("cipher(%s) SKE cipher function is %d (expected %d)", test.name, ske.CipherFunc, config.DefaultCipher) } parsedKey, parsedCipherFunc, err := ske.Decrypt(passphrase) if err != nil { t.Errorf("cipher(%s) failed to decrypt reparsed SKE: %s", test.name, err) continue } if !bytes.Equal(key, parsedKey) { t.Errorf("cipher(%s) keys don't match after Decrypt: %x (original) vs %x (parsed)", test.name, key, parsedKey) } if parsedCipherFunc != test.cipherFunc { t.Errorf("cipher(%s) cipher function doesn't match after Decrypt: %d (original) vs %d (parsed)", test.name, test.cipherFunc, parsedCipherFunc) } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/symmetric_key_encrypted.go�������������������0000644�0610621�0607500�00000011307�13172163317�031263� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto/cipher" "io" "strconv" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/s2k" ) // This is the largest session key that we'll support. Since no 512-bit cipher // has even been seriously used, this is comfortably large. const maxSessionKeySizeInBytes = 64 // SymmetricKeyEncrypted represents a passphrase protected session key. See RFC // 4880, section 5.3. type SymmetricKeyEncrypted struct { CipherFunc CipherFunction s2k func(out, in []byte) encryptedKey []byte } const symmetricKeyEncryptedVersion = 4 func (ske *SymmetricKeyEncrypted) parse(r io.Reader) error { // RFC 4880, section 5.3. var buf [2]byte if _, err := readFull(r, buf[:]); err != nil { return err } if buf[0] != symmetricKeyEncryptedVersion { return errors.UnsupportedError("SymmetricKeyEncrypted version") } ske.CipherFunc = CipherFunction(buf[1]) if ske.CipherFunc.KeySize() == 0 { return errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[1]))) } var err error ske.s2k, err = s2k.Parse(r) if err != nil { return err } encryptedKey := make([]byte, maxSessionKeySizeInBytes) // The session key may follow. We just have to try and read to find // out. If it exists then we limit it to maxSessionKeySizeInBytes. n, err := readFull(r, encryptedKey) if err != nil && err != io.ErrUnexpectedEOF { return err } if n != 0 { if n == maxSessionKeySizeInBytes { return errors.UnsupportedError("oversized encrypted session key") } ske.encryptedKey = encryptedKey[:n] } return nil } // Decrypt attempts to decrypt an encrypted session key and returns the key and // the cipher to use when decrypting a subsequent Symmetrically Encrypted Data // packet. func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) ([]byte, CipherFunction, error) { key := make([]byte, ske.CipherFunc.KeySize()) ske.s2k(key, passphrase) if len(ske.encryptedKey) == 0 { return key, ske.CipherFunc, nil } // the IV is all zeros iv := make([]byte, ske.CipherFunc.blockSize()) c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv) plaintextKey := make([]byte, len(ske.encryptedKey)) c.XORKeyStream(plaintextKey, ske.encryptedKey) cipherFunc := CipherFunction(plaintextKey[0]) if cipherFunc.blockSize() == 0 { return nil, ske.CipherFunc, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc))) } plaintextKey = plaintextKey[1:] if l, cipherKeySize := len(plaintextKey), cipherFunc.KeySize(); l != cipherFunc.KeySize() { return nil, cipherFunc, errors.StructuralError("length of decrypted key (" + strconv.Itoa(l) + ") " + "not equal to cipher keysize (" + strconv.Itoa(cipherKeySize) + ")") } return plaintextKey, cipherFunc, nil } // SerializeSymmetricKeyEncrypted serializes a symmetric key packet to w. The // packet contains a random session key, encrypted by a key derived from the // given passphrase. The session key is returned and must be passed to // SerializeSymmetricallyEncrypted. // If config is nil, sensible defaults will be used. func SerializeSymmetricKeyEncrypted(w io.Writer, passphrase []byte, config *Config) (key []byte, err error) { cipherFunc := config.Cipher() keySize := cipherFunc.KeySize() if keySize == 0 { return nil, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc))) } s2kBuf := new(bytes.Buffer) keyEncryptingKey := make([]byte, keySize) // s2k.Serialize salts and stretches the passphrase, and writes the // resulting key to keyEncryptingKey and the s2k descriptor to s2kBuf. err = s2k.Serialize(s2kBuf, keyEncryptingKey, config.Random(), passphrase, &s2k.Config{Hash: config.Hash(), S2KCount: config.PasswordHashIterations()}) if err != nil { return } s2kBytes := s2kBuf.Bytes() packetLength := 2 /* header */ + len(s2kBytes) + 1 /* cipher type */ + keySize err = serializeHeader(w, packetTypeSymmetricKeyEncrypted, packetLength) if err != nil { return } var buf [2]byte buf[0] = symmetricKeyEncryptedVersion buf[1] = byte(cipherFunc) _, err = w.Write(buf[:]) if err != nil { return } _, err = w.Write(s2kBytes) if err != nil { return } sessionKey := make([]byte, keySize) _, err = io.ReadFull(config.Random(), sessionKey) if err != nil { return } iv := make([]byte, cipherFunc.blockSize()) c := cipher.NewCFBEncrypter(cipherFunc.new(keyEncryptingKey), iv) encryptedCipherAndKey := make([]byte, keySize+1) c.XORKeyStream(encryptedCipherAndKey, buf[1:]) c.XORKeyStream(encryptedCipherAndKey[1:], sessionKey) _, err = w.Write(encryptedCipherAndKey) if err != nil { return } key = sessionKey return } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/signature_v3_test.go�������������������������0000644�0610621�0607500�00000005320�13172163317�027770� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto" "encoding/hex" "io" "io/ioutil" "testing" "golang.org/x/crypto/openpgp/armor" ) func TestSignatureV3Read(t *testing.T) { r := v3KeyReader(t) Read(r) // Skip public key Read(r) // Skip uid packet, err := Read(r) // Signature if err != nil { t.Error(err) return } sig, ok := packet.(*SignatureV3) if !ok || sig.SigType != SigTypeGenericCert || sig.PubKeyAlgo != PubKeyAlgoRSA || sig.Hash != crypto.MD5 { t.Errorf("failed to parse, got: %#v", packet) } } func TestSignatureV3Reserialize(t *testing.T) { r := v3KeyReader(t) Read(r) // Skip public key Read(r) // Skip uid packet, err := Read(r) if err != nil { t.Error(err) return } sig := packet.(*SignatureV3) out := new(bytes.Buffer) if err = sig.Serialize(out); err != nil { t.Errorf("error reserializing: %s", err) return } expected, err := ioutil.ReadAll(v3KeyReader(t)) if err != nil { t.Error(err) return } expected = expected[4+141+4+39:] // See pgpdump offsets below, this is where the sig starts if !bytes.Equal(expected, out.Bytes()) { t.Errorf("output doesn't match input (got vs expected):\n%s\n%s", hex.Dump(out.Bytes()), hex.Dump(expected)) } } func v3KeyReader(t *testing.T) io.Reader { armorBlock, err := armor.Decode(bytes.NewBufferString(keySigV3Armor)) if err != nil { t.Fatalf("armor Decode failed: %v", err) } return armorBlock.Body } // keySigV3Armor is some V3 public key I found in an SKS dump. // Old: Public Key Packet(tag 6)(141 bytes) // Ver 4 - new // Public key creation time - Fri Sep 16 17:13:54 CDT 1994 // Pub alg - unknown(pub 0) // Unknown public key(pub 0) // Old: User ID Packet(tag 13)(39 bytes) // User ID - Armin M. Warda <warda@nephilim.ruhr.de> // Old: Signature Packet(tag 2)(149 bytes) // Ver 4 - new // Sig type - unknown(05) // Pub alg - ElGamal Encrypt-Only(pub 16) // Hash alg - unknown(hash 46) // Hashed Sub: unknown(sub 81, critical)(1988 bytes) const keySigV3Armor = `-----BEGIN PGP PUBLIC KEY BLOCK----- Version: SKS 1.0.10 mI0CLnoYogAAAQQA1qwA2SuJwfQ5bCQ6u5t20ulnOtY0gykf7YjiK4LiVeRBwHjGq7v30tGV 5Qti7qqRW4Ww7CDCJc4sZMFnystucR2vLkXaSoNWoFm4Fg47NiisDdhDezHwbVPW6OpCFNSi ZAamtj4QAUBu8j4LswafrJqZqR9336/V3g8Yil2l48kABRG0J0FybWluIE0uIFdhcmRhIDx3 YXJkYUBuZXBoaWxpbS5ydWhyLmRlPoiVAgUQLok2xwXR6zmeWEiZAQE/DgP/WgxPQh40/Po4 gSkWZCDAjNdph7zexvAb0CcUWahcwiBIgg3U5ErCx9I5CNVA9U+s8bNrDZwgSIeBzp3KhWUx 524uhGgm6ZUTOAIKA6CbV6pfqoLpJnRYvXYQU5mIWsNa99wcu2qu18OeEDnztb7aLA6Ra9OF YFCbq4EjXRoOrYM= =LPjs -----END PGP PUBLIC KEY BLOCK-----` ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/signature_v3.go������������������������������0000644�0610621�0607500�00000007540�13172163317�026737� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "crypto" "encoding/binary" "fmt" "io" "strconv" "time" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/s2k" ) // SignatureV3 represents older version 3 signatures. These signatures are less secure // than version 4 and should not be used to create new signatures. They are included // here for backwards compatibility to read and validate with older key material. // See RFC 4880, section 5.2.2. type SignatureV3 struct { SigType SignatureType CreationTime time.Time IssuerKeyId uint64 PubKeyAlgo PublicKeyAlgorithm Hash crypto.Hash HashTag [2]byte RSASignature parsedMPI DSASigR, DSASigS parsedMPI } func (sig *SignatureV3) parse(r io.Reader) (err error) { // RFC 4880, section 5.2.2 var buf [8]byte if _, err = readFull(r, buf[:1]); err != nil { return } if buf[0] < 2 || buf[0] > 3 { err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0]))) return } if _, err = readFull(r, buf[:1]); err != nil { return } if buf[0] != 5 { err = errors.UnsupportedError( "invalid hashed material length " + strconv.Itoa(int(buf[0]))) return } // Read hashed material: signature type + creation time if _, err = readFull(r, buf[:5]); err != nil { return } sig.SigType = SignatureType(buf[0]) t := binary.BigEndian.Uint32(buf[1:5]) sig.CreationTime = time.Unix(int64(t), 0) // Eight-octet Key ID of signer. if _, err = readFull(r, buf[:8]); err != nil { return } sig.IssuerKeyId = binary.BigEndian.Uint64(buf[:]) // Public-key and hash algorithm if _, err = readFull(r, buf[:2]); err != nil { return } sig.PubKeyAlgo = PublicKeyAlgorithm(buf[0]) switch sig.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA: default: err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo))) return } var ok bool if sig.Hash, ok = s2k.HashIdToHash(buf[1]); !ok { return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2]))) } // Two-octet field holding left 16 bits of signed hash value. if _, err = readFull(r, sig.HashTag[:2]); err != nil { return } switch sig.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r) case PubKeyAlgoDSA: if sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r); err != nil { return } sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r) default: panic("unreachable") } return } // Serialize marshals sig to w. Sign, SignUserId or SignKey must have been // called first. func (sig *SignatureV3) Serialize(w io.Writer) (err error) { buf := make([]byte, 8) // Write the sig type and creation time buf[0] = byte(sig.SigType) binary.BigEndian.PutUint32(buf[1:5], uint32(sig.CreationTime.Unix())) if _, err = w.Write(buf[:5]); err != nil { return } // Write the issuer long key ID binary.BigEndian.PutUint64(buf[:8], sig.IssuerKeyId) if _, err = w.Write(buf[:8]); err != nil { return } // Write public key algorithm, hash ID, and hash value buf[0] = byte(sig.PubKeyAlgo) hashId, ok := s2k.HashToHashId(sig.Hash) if !ok { return errors.UnsupportedError(fmt.Sprintf("hash function %v", sig.Hash)) } buf[1] = hashId copy(buf[2:4], sig.HashTag[:]) if _, err = w.Write(buf[:4]); err != nil { return } if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil { return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize") } switch sig.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: err = writeMPIs(w, sig.RSASignature) case PubKeyAlgoDSA: err = writeMPIs(w, sig.DSASigR, sig.DSASigS) default: panic("impossible") } return } ����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/signature_test.go����������������������������0000644�0610621�0607500�00000004672�13172163317�027371� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto" "encoding/hex" "testing" ) func TestSignatureRead(t *testing.T) { packet, err := Read(readerFromHex(signatureDataHex)) if err != nil { t.Error(err) return } sig, ok := packet.(*Signature) if !ok || sig.SigType != SigTypeBinary || sig.PubKeyAlgo != PubKeyAlgoRSA || sig.Hash != crypto.SHA1 { t.Errorf("failed to parse, got: %#v", packet) } } func TestSignatureReserialize(t *testing.T) { packet, _ := Read(readerFromHex(signatureDataHex)) sig := packet.(*Signature) out := new(bytes.Buffer) err := sig.Serialize(out) if err != nil { t.Errorf("error reserializing: %s", err) return } expected, _ := hex.DecodeString(signatureDataHex) if !bytes.Equal(expected, out.Bytes()) { t.Errorf("output doesn't match input (got vs expected):\n%s\n%s", hex.Dump(out.Bytes()), hex.Dump(expected)) } } func TestSignUserId(t *testing.T) { sig := &Signature{ SigType: SigTypeGenericCert, PubKeyAlgo: PubKeyAlgoRSA, Hash: 0, // invalid hash function } packet, err := Read(readerFromHex(rsaPkDataHex)) if err != nil { t.Fatalf("failed to deserialize public key: %v", err) } pubKey := packet.(*PublicKey) packet, err = Read(readerFromHex(privKeyRSAHex)) if err != nil { t.Fatalf("failed to deserialize private key: %v", err) } privKey := packet.(*PrivateKey) err = sig.SignUserId("", pubKey, privKey, nil) if err == nil { t.Errorf("did not receive an error when expected") } sig.Hash = crypto.SHA256 err = privKey.Decrypt([]byte("testing")) if err != nil { t.Fatalf("failed to decrypt private key: %v", err) } err = sig.SignUserId("", pubKey, privKey, nil) if err != nil { t.Errorf("failed to sign user id: %v", err) } } const signatureDataHex = "c2c05c04000102000605024cb45112000a0910ab105c91af38fb158f8d07ff5596ea368c5efe015bed6e78348c0f033c931d5f2ce5db54ce7f2a7e4b4ad64db758d65a7a71773edeab7ba2a9e0908e6a94a1175edd86c1d843279f045b021a6971a72702fcbd650efc393c5474d5b59a15f96d2eaad4c4c426797e0dcca2803ef41c6ff234d403eec38f31d610c344c06f2401c262f0993b2e66cad8a81ebc4322c723e0d4ba09fe917e8777658307ad8329adacba821420741009dfe87f007759f0982275d028a392c6ed983a0d846f890b36148c7358bdb8a516007fac760261ecd06076813831a36d0459075d1befa245ae7f7fb103d92ca759e9498fe60ef8078a39a3beda510deea251ea9f0a7f0df6ef42060f20780360686f3e400e" ����������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/signature.go���������������������������������0000644�0610621�0607500�00000052362�13172163317�026331� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto" "crypto/dsa" "crypto/ecdsa" "encoding/asn1" "encoding/binary" "hash" "io" "math/big" "strconv" "time" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/s2k" ) const ( // See RFC 4880, section 5.2.3.21 for details. KeyFlagCertify = 1 << iota KeyFlagSign KeyFlagEncryptCommunications KeyFlagEncryptStorage ) // Signature represents a signature. See RFC 4880, section 5.2. type Signature struct { SigType SignatureType PubKeyAlgo PublicKeyAlgorithm Hash crypto.Hash // HashSuffix is extra data that is hashed in after the signed data. HashSuffix []byte // HashTag contains the first two bytes of the hash for fast rejection // of bad signed data. HashTag [2]byte CreationTime time.Time RSASignature parsedMPI DSASigR, DSASigS parsedMPI ECDSASigR, ECDSASigS parsedMPI // rawSubpackets contains the unparsed subpackets, in order. rawSubpackets []outputSubpacket // The following are optional so are nil when not included in the // signature. SigLifetimeSecs, KeyLifetimeSecs *uint32 PreferredSymmetric, PreferredHash, PreferredCompression []uint8 IssuerKeyId *uint64 IsPrimaryId *bool // FlagsValid is set if any flags were given. See RFC 4880, section // 5.2.3.21 for details. FlagsValid bool FlagCertify, FlagSign, FlagEncryptCommunications, FlagEncryptStorage bool // RevocationReason is set if this signature has been revoked. // See RFC 4880, section 5.2.3.23 for details. RevocationReason *uint8 RevocationReasonText string // MDC is set if this signature has a feature packet that indicates // support for MDC subpackets. MDC bool // EmbeddedSignature, if non-nil, is a signature of the parent key, by // this key. This prevents an attacker from claiming another's signing // subkey as their own. EmbeddedSignature *Signature outSubpackets []outputSubpacket } func (sig *Signature) parse(r io.Reader) (err error) { // RFC 4880, section 5.2.3 var buf [5]byte _, err = readFull(r, buf[:1]) if err != nil { return } if buf[0] != 4 { err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0]))) return } _, err = readFull(r, buf[:5]) if err != nil { return } sig.SigType = SignatureType(buf[0]) sig.PubKeyAlgo = PublicKeyAlgorithm(buf[1]) switch sig.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA: default: err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo))) return } var ok bool sig.Hash, ok = s2k.HashIdToHash(buf[2]) if !ok { return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2]))) } hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4]) l := 6 + hashedSubpacketsLength sig.HashSuffix = make([]byte, l+6) sig.HashSuffix[0] = 4 copy(sig.HashSuffix[1:], buf[:5]) hashedSubpackets := sig.HashSuffix[6:l] _, err = readFull(r, hashedSubpackets) if err != nil { return } // See RFC 4880, section 5.2.4 trailer := sig.HashSuffix[l:] trailer[0] = 4 trailer[1] = 0xff trailer[2] = uint8(l >> 24) trailer[3] = uint8(l >> 16) trailer[4] = uint8(l >> 8) trailer[5] = uint8(l) err = parseSignatureSubpackets(sig, hashedSubpackets, true) if err != nil { return } _, err = readFull(r, buf[:2]) if err != nil { return } unhashedSubpacketsLength := int(buf[0])<<8 | int(buf[1]) unhashedSubpackets := make([]byte, unhashedSubpacketsLength) _, err = readFull(r, unhashedSubpackets) if err != nil { return } err = parseSignatureSubpackets(sig, unhashedSubpackets, false) if err != nil { return } _, err = readFull(r, sig.HashTag[:2]) if err != nil { return } switch sig.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r) case PubKeyAlgoDSA: sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r) if err == nil { sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r) } case PubKeyAlgoECDSA: sig.ECDSASigR.bytes, sig.ECDSASigR.bitLength, err = readMPI(r) if err == nil { sig.ECDSASigS.bytes, sig.ECDSASigS.bitLength, err = readMPI(r) } default: panic("unreachable") } return } // parseSignatureSubpackets parses subpackets of the main signature packet. See // RFC 4880, section 5.2.3.1. func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) { for len(subpackets) > 0 { subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed) if err != nil { return } } if sig.CreationTime.IsZero() { err = errors.StructuralError("no creation time in signature") } return } type signatureSubpacketType uint8 const ( creationTimeSubpacket signatureSubpacketType = 2 signatureExpirationSubpacket signatureSubpacketType = 3 keyExpirationSubpacket signatureSubpacketType = 9 prefSymmetricAlgosSubpacket signatureSubpacketType = 11 issuerSubpacket signatureSubpacketType = 16 prefHashAlgosSubpacket signatureSubpacketType = 21 prefCompressionSubpacket signatureSubpacketType = 22 primaryUserIdSubpacket signatureSubpacketType = 25 keyFlagsSubpacket signatureSubpacketType = 27 reasonForRevocationSubpacket signatureSubpacketType = 29 featuresSubpacket signatureSubpacketType = 30 embeddedSignatureSubpacket signatureSubpacketType = 32 ) // parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1. func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) { // RFC 4880, section 5.2.3.1 var ( length uint32 packetType signatureSubpacketType isCritical bool ) switch { case subpacket[0] < 192: length = uint32(subpacket[0]) subpacket = subpacket[1:] case subpacket[0] < 255: if len(subpacket) < 2 { goto Truncated } length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192 subpacket = subpacket[2:] default: if len(subpacket) < 5 { goto Truncated } length = uint32(subpacket[1])<<24 | uint32(subpacket[2])<<16 | uint32(subpacket[3])<<8 | uint32(subpacket[4]) subpacket = subpacket[5:] } if length > uint32(len(subpacket)) { goto Truncated } rest = subpacket[length:] subpacket = subpacket[:length] if len(subpacket) == 0 { err = errors.StructuralError("zero length signature subpacket") return } packetType = signatureSubpacketType(subpacket[0] & 0x7f) isCritical = subpacket[0]&0x80 == 0x80 subpacket = subpacket[1:] sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket}) switch packetType { case creationTimeSubpacket: if !isHashed { err = errors.StructuralError("signature creation time in non-hashed area") return } if len(subpacket) != 4 { err = errors.StructuralError("signature creation time not four bytes") return } t := binary.BigEndian.Uint32(subpacket) sig.CreationTime = time.Unix(int64(t), 0) case signatureExpirationSubpacket: // Signature expiration time, section 5.2.3.10 if !isHashed { return } if len(subpacket) != 4 { err = errors.StructuralError("expiration subpacket with bad length") return } sig.SigLifetimeSecs = new(uint32) *sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket) case keyExpirationSubpacket: // Key expiration time, section 5.2.3.6 if !isHashed { return } if len(subpacket) != 4 { err = errors.StructuralError("key expiration subpacket with bad length") return } sig.KeyLifetimeSecs = new(uint32) *sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket) case prefSymmetricAlgosSubpacket: // Preferred symmetric algorithms, section 5.2.3.7 if !isHashed { return } sig.PreferredSymmetric = make([]byte, len(subpacket)) copy(sig.PreferredSymmetric, subpacket) case issuerSubpacket: // Issuer, section 5.2.3.5 if len(subpacket) != 8 { err = errors.StructuralError("issuer subpacket with bad length") return } sig.IssuerKeyId = new(uint64) *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket) case prefHashAlgosSubpacket: // Preferred hash algorithms, section 5.2.3.8 if !isHashed { return } sig.PreferredHash = make([]byte, len(subpacket)) copy(sig.PreferredHash, subpacket) case prefCompressionSubpacket: // Preferred compression algorithms, section 5.2.3.9 if !isHashed { return } sig.PreferredCompression = make([]byte, len(subpacket)) copy(sig.PreferredCompression, subpacket) case primaryUserIdSubpacket: // Primary User ID, section 5.2.3.19 if !isHashed { return } if len(subpacket) != 1 { err = errors.StructuralError("primary user id subpacket with bad length") return } sig.IsPrimaryId = new(bool) if subpacket[0] > 0 { *sig.IsPrimaryId = true } case keyFlagsSubpacket: // Key flags, section 5.2.3.21 if !isHashed { return } if len(subpacket) == 0 { err = errors.StructuralError("empty key flags subpacket") return } sig.FlagsValid = true if subpacket[0]&KeyFlagCertify != 0 { sig.FlagCertify = true } if subpacket[0]&KeyFlagSign != 0 { sig.FlagSign = true } if subpacket[0]&KeyFlagEncryptCommunications != 0 { sig.FlagEncryptCommunications = true } if subpacket[0]&KeyFlagEncryptStorage != 0 { sig.FlagEncryptStorage = true } case reasonForRevocationSubpacket: // Reason For Revocation, section 5.2.3.23 if !isHashed { return } if len(subpacket) == 0 { err = errors.StructuralError("empty revocation reason subpacket") return } sig.RevocationReason = new(uint8) *sig.RevocationReason = subpacket[0] sig.RevocationReasonText = string(subpacket[1:]) case featuresSubpacket: // Features subpacket, section 5.2.3.24 specifies a very general // mechanism for OpenPGP implementations to signal support for new // features. In practice, the subpacket is used exclusively to // indicate support for MDC-protected encryption. sig.MDC = len(subpacket) >= 1 && subpacket[0]&1 == 1 case embeddedSignatureSubpacket: // Only usage is in signatures that cross-certify // signing subkeys. section 5.2.3.26 describes the // format, with its usage described in section 11.1 if sig.EmbeddedSignature != nil { err = errors.StructuralError("Cannot have multiple embedded signatures") return } sig.EmbeddedSignature = new(Signature) // Embedded signatures are required to be v4 signatures see // section 12.1. However, we only parse v4 signatures in this // file anyway. if err := sig.EmbeddedSignature.parse(bytes.NewBuffer(subpacket)); err != nil { return nil, err } if sigType := sig.EmbeddedSignature.SigType; sigType != SigTypePrimaryKeyBinding { return nil, errors.StructuralError("cross-signature has unexpected type " + strconv.Itoa(int(sigType))) } default: if isCritical { err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType))) return } } return Truncated: err = errors.StructuralError("signature subpacket truncated") return } // subpacketLengthLength returns the length, in bytes, of an encoded length value. func subpacketLengthLength(length int) int { if length < 192 { return 1 } if length < 16320 { return 2 } return 5 } // serializeSubpacketLength marshals the given length into to. func serializeSubpacketLength(to []byte, length int) int { // RFC 4880, Section 4.2.2. if length < 192 { to[0] = byte(length) return 1 } if length < 16320 { length -= 192 to[0] = byte((length >> 8) + 192) to[1] = byte(length) return 2 } to[0] = 255 to[1] = byte(length >> 24) to[2] = byte(length >> 16) to[3] = byte(length >> 8) to[4] = byte(length) return 5 } // subpacketsLength returns the serialized length, in bytes, of the given // subpackets. func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) { for _, subpacket := range subpackets { if subpacket.hashed == hashed { length += subpacketLengthLength(len(subpacket.contents) + 1) length += 1 // type byte length += len(subpacket.contents) } } return } // serializeSubpackets marshals the given subpackets into to. func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) { for _, subpacket := range subpackets { if subpacket.hashed == hashed { n := serializeSubpacketLength(to, len(subpacket.contents)+1) to[n] = byte(subpacket.subpacketType) to = to[1+n:] n = copy(to, subpacket.contents) to = to[n:] } } return } // KeyExpired returns whether sig is a self-signature of a key that has // expired. func (sig *Signature) KeyExpired(currentTime time.Time) bool { if sig.KeyLifetimeSecs == nil { return false } expiry := sig.CreationTime.Add(time.Duration(*sig.KeyLifetimeSecs) * time.Second) return currentTime.After(expiry) } // buildHashSuffix constructs the HashSuffix member of sig in preparation for signing. func (sig *Signature) buildHashSuffix() (err error) { hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true) var ok bool l := 6 + hashedSubpacketsLen sig.HashSuffix = make([]byte, l+6) sig.HashSuffix[0] = 4 sig.HashSuffix[1] = uint8(sig.SigType) sig.HashSuffix[2] = uint8(sig.PubKeyAlgo) sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash) if !ok { sig.HashSuffix = nil return errors.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash))) } sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8) sig.HashSuffix[5] = byte(hashedSubpacketsLen) serializeSubpackets(sig.HashSuffix[6:l], sig.outSubpackets, true) trailer := sig.HashSuffix[l:] trailer[0] = 4 trailer[1] = 0xff trailer[2] = byte(l >> 24) trailer[3] = byte(l >> 16) trailer[4] = byte(l >> 8) trailer[5] = byte(l) return } func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) { err = sig.buildHashSuffix() if err != nil { return } h.Write(sig.HashSuffix) digest = h.Sum(nil) copy(sig.HashTag[:], digest) return } // Sign signs a message with a private key. The hash, h, must contain // the hash of the message to be signed and will be mutated by this function. // On success, the signature is stored in sig. Call Serialize to write it out. // If config is nil, sensible defaults will be used. func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) { sig.outSubpackets = sig.buildSubpackets() digest, err := sig.signPrepareHash(h) if err != nil { return } switch priv.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: // supports both *rsa.PrivateKey and crypto.Signer sig.RSASignature.bytes, err = priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, sig.Hash) sig.RSASignature.bitLength = uint16(8 * len(sig.RSASignature.bytes)) case PubKeyAlgoDSA: dsaPriv := priv.PrivateKey.(*dsa.PrivateKey) // Need to truncate hashBytes to match FIPS 186-3 section 4.6. subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8 if len(digest) > subgroupSize { digest = digest[:subgroupSize] } r, s, err := dsa.Sign(config.Random(), dsaPriv, digest) if err == nil { sig.DSASigR.bytes = r.Bytes() sig.DSASigR.bitLength = uint16(8 * len(sig.DSASigR.bytes)) sig.DSASigS.bytes = s.Bytes() sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes)) } case PubKeyAlgoECDSA: var r, s *big.Int if pk, ok := priv.PrivateKey.(*ecdsa.PrivateKey); ok { // direct support, avoid asn1 wrapping/unwrapping r, s, err = ecdsa.Sign(config.Random(), pk, digest) } else { var b []byte b, err = priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, nil) if err == nil { r, s, err = unwrapECDSASig(b) } } if err == nil { sig.ECDSASigR = fromBig(r) sig.ECDSASigS = fromBig(s) } default: err = errors.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo))) } return } // unwrapECDSASig parses the two integer components of an ASN.1-encoded ECDSA // signature. func unwrapECDSASig(b []byte) (r, s *big.Int, err error) { var ecsdaSig struct { R, S *big.Int } _, err = asn1.Unmarshal(b, &ecsdaSig) if err != nil { return } return ecsdaSig.R, ecsdaSig.S, nil } // SignUserId computes a signature from priv, asserting that pub is a valid // key for the identity id. On success, the signature is stored in sig. Call // Serialize to write it out. // If config is nil, sensible defaults will be used. func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error { h, err := userIdSignatureHash(id, pub, sig.Hash) if err != nil { return err } return sig.Sign(h, priv, config) } // SignKey computes a signature from priv, asserting that pub is a subkey. On // success, the signature is stored in sig. Call Serialize to write it out. // If config is nil, sensible defaults will be used. func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey, config *Config) error { h, err := keySignatureHash(&priv.PublicKey, pub, sig.Hash) if err != nil { return err } return sig.Sign(h, priv, config) } // Serialize marshals sig to w. Sign, SignUserId or SignKey must have been // called first. func (sig *Signature) Serialize(w io.Writer) (err error) { if len(sig.outSubpackets) == 0 { sig.outSubpackets = sig.rawSubpackets } if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil && sig.ECDSASigR.bytes == nil { return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize") } sigLength := 0 switch sig.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: sigLength = 2 + len(sig.RSASignature.bytes) case PubKeyAlgoDSA: sigLength = 2 + len(sig.DSASigR.bytes) sigLength += 2 + len(sig.DSASigS.bytes) case PubKeyAlgoECDSA: sigLength = 2 + len(sig.ECDSASigR.bytes) sigLength += 2 + len(sig.ECDSASigS.bytes) default: panic("impossible") } unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false) length := len(sig.HashSuffix) - 6 /* trailer not included */ + 2 /* length of unhashed subpackets */ + unhashedSubpacketsLen + 2 /* hash tag */ + sigLength err = serializeHeader(w, packetTypeSignature, length) if err != nil { return } _, err = w.Write(sig.HashSuffix[:len(sig.HashSuffix)-6]) if err != nil { return } unhashedSubpackets := make([]byte, 2+unhashedSubpacketsLen) unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 8) unhashedSubpackets[1] = byte(unhashedSubpacketsLen) serializeSubpackets(unhashedSubpackets[2:], sig.outSubpackets, false) _, err = w.Write(unhashedSubpackets) if err != nil { return } _, err = w.Write(sig.HashTag[:]) if err != nil { return } switch sig.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: err = writeMPIs(w, sig.RSASignature) case PubKeyAlgoDSA: err = writeMPIs(w, sig.DSASigR, sig.DSASigS) case PubKeyAlgoECDSA: err = writeMPIs(w, sig.ECDSASigR, sig.ECDSASigS) default: panic("impossible") } return } // outputSubpacket represents a subpacket to be marshaled. type outputSubpacket struct { hashed bool // true if this subpacket is in the hashed area. subpacketType signatureSubpacketType isCritical bool contents []byte } func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) { creationTime := make([]byte, 4) binary.BigEndian.PutUint32(creationTime, uint32(sig.CreationTime.Unix())) subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, false, creationTime}) if sig.IssuerKeyId != nil { keyId := make([]byte, 8) binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId) subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyId}) } if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 { sigLifetime := make([]byte, 4) binary.BigEndian.PutUint32(sigLifetime, *sig.SigLifetimeSecs) subpackets = append(subpackets, outputSubpacket{true, signatureExpirationSubpacket, true, sigLifetime}) } // Key flags may only appear in self-signatures or certification signatures. if sig.FlagsValid { var flags byte if sig.FlagCertify { flags |= KeyFlagCertify } if sig.FlagSign { flags |= KeyFlagSign } if sig.FlagEncryptCommunications { flags |= KeyFlagEncryptCommunications } if sig.FlagEncryptStorage { flags |= KeyFlagEncryptStorage } subpackets = append(subpackets, outputSubpacket{true, keyFlagsSubpacket, false, []byte{flags}}) } // The following subpackets may only appear in self-signatures if sig.KeyLifetimeSecs != nil && *sig.KeyLifetimeSecs != 0 { keyLifetime := make([]byte, 4) binary.BigEndian.PutUint32(keyLifetime, *sig.KeyLifetimeSecs) subpackets = append(subpackets, outputSubpacket{true, keyExpirationSubpacket, true, keyLifetime}) } if sig.IsPrimaryId != nil && *sig.IsPrimaryId { subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}}) } if len(sig.PreferredSymmetric) > 0 { subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric}) } if len(sig.PreferredHash) > 0 { subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash}) } if len(sig.PreferredCompression) > 0 { subpackets = append(subpackets, outputSubpacket{true, prefCompressionSubpacket, false, sig.PreferredCompression}) } return } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/reader.go������������������������������������0000644�0610621�0607500�00000004233�13172163317�025564� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "golang.org/x/crypto/openpgp/errors" "io" ) // Reader reads packets from an io.Reader and allows packets to be 'unread' so // that they result from the next call to Next. type Reader struct { q []Packet readers []io.Reader } // New io.Readers are pushed when a compressed or encrypted packet is processed // and recursively treated as a new source of packets. However, a carefully // crafted packet can trigger an infinite recursive sequence of packets. See // http://mumble.net/~campbell/misc/pgp-quine // https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-4402 // This constant limits the number of recursive packets that may be pushed. const maxReaders = 32 // Next returns the most recently unread Packet, or reads another packet from // the top-most io.Reader. Unknown packet types are skipped. func (r *Reader) Next() (p Packet, err error) { if len(r.q) > 0 { p = r.q[len(r.q)-1] r.q = r.q[:len(r.q)-1] return } for len(r.readers) > 0 { p, err = Read(r.readers[len(r.readers)-1]) if err == nil { return } if err == io.EOF { r.readers = r.readers[:len(r.readers)-1] continue } if _, ok := err.(errors.UnknownPacketTypeError); !ok { return nil, err } } return nil, io.EOF } // Push causes the Reader to start reading from a new io.Reader. When an EOF // error is seen from the new io.Reader, it is popped and the Reader continues // to read from the next most recent io.Reader. Push returns a StructuralError // if pushing the reader would exceed the maximum recursion level, otherwise it // returns nil. func (r *Reader) Push(reader io.Reader) (err error) { if len(r.readers) >= maxReaders { return errors.StructuralError("too many layers of packets") } r.readers = append(r.readers, reader) return nil } // Unread causes the given Packet to be returned from the next call to Next. func (r *Reader) Unread(p Packet) { r.q = append(r.q, p) } func NewReader(r io.Reader) *Reader { return &Reader{ q: nil, readers: []io.Reader{r}, } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/public_key_v3_test.go������������������������0000644�0610621�0607500�00000004476�13172163317�030130� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/hex" "testing" "time" ) var pubKeyV3Test = struct { hexFingerprint string creationTime time.Time pubKeyAlgo PublicKeyAlgorithm keyId uint64 keyIdString string keyIdShort string }{ "103BECF5BD1E837C89D19E98487767F7", time.Unix(779753634, 0), PubKeyAlgoRSA, 0xDE0F188A5DA5E3C9, "DE0F188A5DA5E3C9", "5DA5E3C9"} func TestPublicKeyV3Read(t *testing.T) { i, test := 0, pubKeyV3Test packet, err := Read(v3KeyReader(t)) if err != nil { t.Fatalf("#%d: Read error: %s", i, err) } pk, ok := packet.(*PublicKeyV3) if !ok { t.Fatalf("#%d: failed to parse, got: %#v", i, packet) } if pk.PubKeyAlgo != test.pubKeyAlgo { t.Errorf("#%d: bad public key algorithm got:%x want:%x", i, pk.PubKeyAlgo, test.pubKeyAlgo) } if !pk.CreationTime.Equal(test.creationTime) { t.Errorf("#%d: bad creation time got:%v want:%v", i, pk.CreationTime, test.creationTime) } expectedFingerprint, _ := hex.DecodeString(test.hexFingerprint) if !bytes.Equal(expectedFingerprint, pk.Fingerprint[:]) { t.Errorf("#%d: bad fingerprint got:%x want:%x", i, pk.Fingerprint[:], expectedFingerprint) } if pk.KeyId != test.keyId { t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyId) } if g, e := pk.KeyIdString(), test.keyIdString; g != e { t.Errorf("#%d: bad KeyIdString got:%q want:%q", i, g, e) } if g, e := pk.KeyIdShortString(), test.keyIdShort; g != e { t.Errorf("#%d: bad KeyIdShortString got:%q want:%q", i, g, e) } } func TestPublicKeyV3Serialize(t *testing.T) { //for i, test := range pubKeyV3Tests { i := 0 packet, err := Read(v3KeyReader(t)) if err != nil { t.Fatalf("#%d: Read error: %s", i, err) } pk, ok := packet.(*PublicKeyV3) if !ok { t.Fatalf("#%d: failed to parse, got: %#v", i, packet) } var serializeBuf bytes.Buffer if err = pk.Serialize(&serializeBuf); err != nil { t.Fatalf("#%d: failed to serialize: %s", i, err) } if packet, err = Read(bytes.NewBuffer(serializeBuf.Bytes())); err != nil { t.Fatalf("#%d: Read error (from serialized data): %s", i, err) } if pk, ok = packet.(*PublicKeyV3); !ok { t.Fatalf("#%d: failed to parse serialized data, got: %#v", i, packet) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/public_key_v3.go�����������������������������0000644�0610621�0607500�00000017750�13172163317�027070� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "crypto" "crypto/md5" "crypto/rsa" "encoding/binary" "fmt" "hash" "io" "math/big" "strconv" "time" "golang.org/x/crypto/openpgp/errors" ) // PublicKeyV3 represents older, version 3 public keys. These keys are less secure and // should not be used for signing or encrypting. They are supported here only for // parsing version 3 key material and validating signatures. // See RFC 4880, section 5.5.2. type PublicKeyV3 struct { CreationTime time.Time DaysToExpire uint16 PubKeyAlgo PublicKeyAlgorithm PublicKey *rsa.PublicKey Fingerprint [16]byte KeyId uint64 IsSubkey bool n, e parsedMPI } // newRSAPublicKeyV3 returns a PublicKey that wraps the given rsa.PublicKey. // Included here for testing purposes only. RFC 4880, section 5.5.2: // "an implementation MUST NOT generate a V3 key, but MAY accept it." func newRSAPublicKeyV3(creationTime time.Time, pub *rsa.PublicKey) *PublicKeyV3 { pk := &PublicKeyV3{ CreationTime: creationTime, PublicKey: pub, n: fromBig(pub.N), e: fromBig(big.NewInt(int64(pub.E))), } pk.setFingerPrintAndKeyId() return pk } func (pk *PublicKeyV3) parse(r io.Reader) (err error) { // RFC 4880, section 5.5.2 var buf [8]byte if _, err = readFull(r, buf[:]); err != nil { return } if buf[0] < 2 || buf[0] > 3 { return errors.UnsupportedError("public key version") } pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0) pk.DaysToExpire = binary.BigEndian.Uint16(buf[5:7]) pk.PubKeyAlgo = PublicKeyAlgorithm(buf[7]) switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: err = pk.parseRSA(r) default: err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) } if err != nil { return } pk.setFingerPrintAndKeyId() return } func (pk *PublicKeyV3) setFingerPrintAndKeyId() { // RFC 4880, section 12.2 fingerPrint := md5.New() fingerPrint.Write(pk.n.bytes) fingerPrint.Write(pk.e.bytes) fingerPrint.Sum(pk.Fingerprint[:0]) pk.KeyId = binary.BigEndian.Uint64(pk.n.bytes[len(pk.n.bytes)-8:]) } // parseRSA parses RSA public key material from the given Reader. See RFC 4880, // section 5.5.2. func (pk *PublicKeyV3) parseRSA(r io.Reader) (err error) { if pk.n.bytes, pk.n.bitLength, err = readMPI(r); err != nil { return } if pk.e.bytes, pk.e.bitLength, err = readMPI(r); err != nil { return } // RFC 4880 Section 12.2 requires the low 8 bytes of the // modulus to form the key id. if len(pk.n.bytes) < 8 { return errors.StructuralError("v3 public key modulus is too short") } if len(pk.e.bytes) > 3 { err = errors.UnsupportedError("large public exponent") return } rsa := &rsa.PublicKey{N: new(big.Int).SetBytes(pk.n.bytes)} for i := 0; i < len(pk.e.bytes); i++ { rsa.E <<= 8 rsa.E |= int(pk.e.bytes[i]) } pk.PublicKey = rsa return } // SerializeSignaturePrefix writes the prefix for this public key to the given Writer. // The prefix is used when calculating a signature over this public key. See // RFC 4880, section 5.2.4. func (pk *PublicKeyV3) SerializeSignaturePrefix(w io.Writer) { var pLength uint16 switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: pLength += 2 + uint16(len(pk.n.bytes)) pLength += 2 + uint16(len(pk.e.bytes)) default: panic("unknown public key algorithm") } pLength += 6 w.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) return } func (pk *PublicKeyV3) Serialize(w io.Writer) (err error) { length := 8 // 8 byte header switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: length += 2 + len(pk.n.bytes) length += 2 + len(pk.e.bytes) default: panic("unknown public key algorithm") } packetType := packetTypePublicKey if pk.IsSubkey { packetType = packetTypePublicSubkey } if err = serializeHeader(w, packetType, length); err != nil { return } return pk.serializeWithoutHeaders(w) } // serializeWithoutHeaders marshals the PublicKey to w in the form of an // OpenPGP public key packet, not including the packet header. func (pk *PublicKeyV3) serializeWithoutHeaders(w io.Writer) (err error) { var buf [8]byte // Version 3 buf[0] = 3 // Creation time t := uint32(pk.CreationTime.Unix()) buf[1] = byte(t >> 24) buf[2] = byte(t >> 16) buf[3] = byte(t >> 8) buf[4] = byte(t) // Days to expire buf[5] = byte(pk.DaysToExpire >> 8) buf[6] = byte(pk.DaysToExpire) // Public key algorithm buf[7] = byte(pk.PubKeyAlgo) if _, err = w.Write(buf[:]); err != nil { return } switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: return writeMPIs(w, pk.n, pk.e) } return errors.InvalidArgumentError("bad public-key algorithm") } // CanSign returns true iff this public key can generate signatures func (pk *PublicKeyV3) CanSign() bool { return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly } // VerifySignatureV3 returns nil iff sig is a valid signature, made by this // public key, of the data hashed into signed. signed is mutated by this call. func (pk *PublicKeyV3) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) { if !pk.CanSign() { return errors.InvalidArgumentError("public key cannot generate signatures") } suffix := make([]byte, 5) suffix[0] = byte(sig.SigType) binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix())) signed.Write(suffix) hashBytes := signed.Sum(nil) if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { return errors.SignatureError("hash tag doesn't match") } if pk.PubKeyAlgo != sig.PubKeyAlgo { return errors.InvalidArgumentError("public key and signature use different algorithms") } switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: if err = rsa.VerifyPKCS1v15(pk.PublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil { return errors.SignatureError("RSA verification failure") } return default: // V3 public keys only support RSA. panic("shouldn't happen") } } // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this // public key, that id is the identity of pub. func (pk *PublicKeyV3) VerifyUserIdSignatureV3(id string, pub *PublicKeyV3, sig *SignatureV3) (err error) { h, err := userIdSignatureV3Hash(id, pk, sig.Hash) if err != nil { return err } return pk.VerifySignatureV3(h, sig) } // VerifyKeySignatureV3 returns nil iff sig is a valid signature, made by this // public key, of signed. func (pk *PublicKeyV3) VerifyKeySignatureV3(signed *PublicKeyV3, sig *SignatureV3) (err error) { h, err := keySignatureHash(pk, signed, sig.Hash) if err != nil { return err } return pk.VerifySignatureV3(h, sig) } // userIdSignatureV3Hash returns a Hash of the message that needs to be signed // to assert that pk is a valid key for id. func userIdSignatureV3Hash(id string, pk signingKey, hfn crypto.Hash) (h hash.Hash, err error) { if !hfn.Available() { return nil, errors.UnsupportedError("hash function") } h = hfn.New() // RFC 4880, section 5.2.4 pk.SerializeSignaturePrefix(h) pk.serializeWithoutHeaders(h) h.Write([]byte(id)) return } // KeyIdString returns the public key's fingerprint in capital hex // (e.g. "6C7EE1B8621CC013"). func (pk *PublicKeyV3) KeyIdString() string { return fmt.Sprintf("%X", pk.KeyId) } // KeyIdShortString returns the short form of public key's fingerprint // in capital hex, as shown by gpg --list-keys (e.g. "621CC013"). func (pk *PublicKeyV3) KeyIdShortString() string { return fmt.Sprintf("%X", pk.KeyId&0xFFFFFFFF) } // BitLength returns the bit length for the given public key. func (pk *PublicKeyV3) BitLength() (bitLength uint16, err error) { switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: bitLength = pk.n.bitLength default: err = errors.InvalidArgumentError("bad public-key algorithm") } return } ������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/public_key_test.go���������������������������0000644�0610621�0607500�00000017752�13172163317�027521� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/hex" "testing" "time" ) var pubKeyTests = []struct { hexData string hexFingerprint string creationTime time.Time pubKeyAlgo PublicKeyAlgorithm keyId uint64 keyIdString string keyIdShort string }{ {rsaPkDataHex, rsaFingerprintHex, time.Unix(0x4d3c5c10, 0), PubKeyAlgoRSA, 0xa34d7e18c20c31bb, "A34D7E18C20C31BB", "C20C31BB"}, {dsaPkDataHex, dsaFingerprintHex, time.Unix(0x4d432f89, 0), PubKeyAlgoDSA, 0x8e8fbe54062f19ed, "8E8FBE54062F19ED", "062F19ED"}, {ecdsaPkDataHex, ecdsaFingerprintHex, time.Unix(0x5071c294, 0), PubKeyAlgoECDSA, 0x43fe956c542ca00b, "43FE956C542CA00B", "542CA00B"}, } func TestPublicKeyRead(t *testing.T) { for i, test := range pubKeyTests { packet, err := Read(readerFromHex(test.hexData)) if err != nil { t.Errorf("#%d: Read error: %s", i, err) continue } pk, ok := packet.(*PublicKey) if !ok { t.Errorf("#%d: failed to parse, got: %#v", i, packet) continue } if pk.PubKeyAlgo != test.pubKeyAlgo { t.Errorf("#%d: bad public key algorithm got:%x want:%x", i, pk.PubKeyAlgo, test.pubKeyAlgo) } if !pk.CreationTime.Equal(test.creationTime) { t.Errorf("#%d: bad creation time got:%v want:%v", i, pk.CreationTime, test.creationTime) } expectedFingerprint, _ := hex.DecodeString(test.hexFingerprint) if !bytes.Equal(expectedFingerprint, pk.Fingerprint[:]) { t.Errorf("#%d: bad fingerprint got:%x want:%x", i, pk.Fingerprint[:], expectedFingerprint) } if pk.KeyId != test.keyId { t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyId) } if g, e := pk.KeyIdString(), test.keyIdString; g != e { t.Errorf("#%d: bad KeyIdString got:%q want:%q", i, g, e) } if g, e := pk.KeyIdShortString(), test.keyIdShort; g != e { t.Errorf("#%d: bad KeyIdShortString got:%q want:%q", i, g, e) } } } func TestPublicKeySerialize(t *testing.T) { for i, test := range pubKeyTests { packet, err := Read(readerFromHex(test.hexData)) if err != nil { t.Errorf("#%d: Read error: %s", i, err) continue } pk, ok := packet.(*PublicKey) if !ok { t.Errorf("#%d: failed to parse, got: %#v", i, packet) continue } serializeBuf := bytes.NewBuffer(nil) err = pk.Serialize(serializeBuf) if err != nil { t.Errorf("#%d: failed to serialize: %s", i, err) continue } packet, err = Read(serializeBuf) if err != nil { t.Errorf("#%d: Read error (from serialized data): %s", i, err) continue } pk, ok = packet.(*PublicKey) if !ok { t.Errorf("#%d: failed to parse serialized data, got: %#v", i, packet) continue } } } func TestEcc384Serialize(t *testing.T) { r := readerFromHex(ecc384PubHex) var w bytes.Buffer for i := 0; i < 2; i++ { // Public key p, err := Read(r) if err != nil { t.Error(err) } pubkey := p.(*PublicKey) if !bytes.Equal(pubkey.ec.oid, []byte{0x2b, 0x81, 0x04, 0x00, 0x22}) { t.Errorf("Unexpected pubkey OID: %x", pubkey.ec.oid) } if !bytes.Equal(pubkey.ec.p.bytes[:5], []byte{0x04, 0xf6, 0xb8, 0xc5, 0xac}) { t.Errorf("Unexpected pubkey P[:5]: %x", pubkey.ec.p.bytes) } if pubkey.KeyId != 0x098033880F54719F { t.Errorf("Unexpected pubkey ID: %x", pubkey.KeyId) } err = pubkey.Serialize(&w) if err != nil { t.Error(err) } // User ID p, err = Read(r) if err != nil { t.Error(err) } uid := p.(*UserId) if uid.Id != "ec_dsa_dh_384 <openpgp@brainhub.org>" { t.Error("Unexpected UID:", uid.Id) } err = uid.Serialize(&w) if err != nil { t.Error(err) } // User ID Sig p, err = Read(r) if err != nil { t.Error(err) } uidSig := p.(*Signature) err = pubkey.VerifyUserIdSignature(uid.Id, pubkey, uidSig) if err != nil { t.Error(err, ": UID") } err = uidSig.Serialize(&w) if err != nil { t.Error(err) } // Subkey p, err = Read(r) if err != nil { t.Error(err) } subkey := p.(*PublicKey) if !bytes.Equal(subkey.ec.oid, []byte{0x2b, 0x81, 0x04, 0x00, 0x22}) { t.Errorf("Unexpected subkey OID: %x", subkey.ec.oid) } if !bytes.Equal(subkey.ec.p.bytes[:5], []byte{0x04, 0x2f, 0xaa, 0x84, 0x02}) { t.Errorf("Unexpected subkey P[:5]: %x", subkey.ec.p.bytes) } if subkey.ecdh.KdfHash != 0x09 { t.Error("Expected KDF hash function SHA384 (0x09), got", subkey.ecdh.KdfHash) } if subkey.ecdh.KdfAlgo != 0x09 { t.Error("Expected KDF symmetric alg AES256 (0x09), got", subkey.ecdh.KdfAlgo) } if subkey.KeyId != 0xAA8B938F9A201946 { t.Errorf("Unexpected subkey ID: %x", subkey.KeyId) } err = subkey.Serialize(&w) if err != nil { t.Error(err) } // Subkey Sig p, err = Read(r) if err != nil { t.Error(err) } subkeySig := p.(*Signature) err = pubkey.VerifyKeySignature(subkey, subkeySig) if err != nil { t.Error(err) } err = subkeySig.Serialize(&w) if err != nil { t.Error(err) } // Now read back what we've written again r = bytes.NewBuffer(w.Bytes()) w.Reset() } } const rsaFingerprintHex = "5fb74b1d03b1e3cb31bc2f8aa34d7e18c20c31bb" const rsaPkDataHex = "988d044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd0011010001" const dsaFingerprintHex = "eece4c094db002103714c63c8e8fbe54062f19ed" const dsaPkDataHex = "9901a2044d432f89110400cd581334f0d7a1e1bdc8b9d6d8c0baf68793632735d2bb0903224cbaa1dfbf35a60ee7a13b92643421e1eb41aa8d79bea19a115a677f6b8ba3c7818ce53a6c2a24a1608bd8b8d6e55c5090cbde09dd26e356267465ae25e69ec8bdd57c7bbb2623e4d73336f73a0a9098f7f16da2e25252130fd694c0e8070c55a812a423ae7f00a0ebf50e70c2f19c3520a551bd4b08d30f23530d3d03ff7d0bf4a53a64a09dc5e6e6e35854b7d70c882b0c60293401958b1bd9e40abec3ea05ba87cf64899299d4bd6aa7f459c201d3fbbd6c82004bdc5e8a9eb8082d12054cc90fa9d4ec251a843236a588bf49552441817436c4f43326966fe85447d4e6d0acf8fa1ef0f014730770603ad7634c3088dc52501c237328417c31c89ed70400b2f1a98b0bf42f11fefc430704bebbaa41d9f355600c3facee1e490f64208e0e094ea55e3a598a219a58500bf78ac677b670a14f4e47e9cf8eab4f368cc1ddcaa18cc59309d4cc62dd4f680e73e6cc3e1ce87a84d0925efbcb26c575c093fc42eecf45135fabf6403a25c2016e1774c0484e440a18319072c617cc97ac0a3bb0" const ecdsaFingerprintHex = "9892270b38b8980b05c8d56d43fe956c542ca00b" const ecdsaPkDataHex = "9893045071c29413052b8104002304230401f4867769cedfa52c325018896245443968e52e51d0c2df8d939949cb5b330f2921711fbee1c9b9dddb95d15cb0255e99badeddda7cc23d9ddcaacbc290969b9f24019375d61c2e4e3b36953a28d8b2bc95f78c3f1d592fb24499be348656a7b17e3963187b4361afe497bc5f9f81213f04069f8e1fb9e6a6290ae295ca1a92b894396cb4" // Source: https://sites.google.com/site/brainhub/pgpecckeys#TOC-ECC-NIST-P-384-key const ecc384PubHex = `99006f044d53059213052b81040022030304f6b8c5aced5b84ef9f4a209db2e4a9dfb70d28cb8c10ecd57674a9fa5a67389942b62d5e51367df4c7bfd3f8e500feecf07ed265a621a8ebbbe53e947ec78c677eba143bd1533c2b350e1c29f82313e1e1108eba063be1e64b10e6950e799c2db42465635f6473615f64685f333834203c6f70656e70677040627261696e6875622e6f72673e8900cb04101309005305024d530592301480000000002000077072656665727265642d656d61696c2d656e636f64696e67407067702e636f6d7067706d696d65040b090807021901051b03000000021602051e010000000415090a08000a0910098033880f54719fca2b0180aa37350968bd5f115afd8ce7bc7b103822152dbff06d0afcda835329510905b98cb469ba208faab87c7412b799e7b633017f58364ea480e8a1a3f253a0c5f22c446e8be9a9fce6210136ee30811abbd49139de28b5bdf8dc36d06ae748579e9ff503b90073044d53059212052b810400220303042faa84024a20b6735c4897efa5bfb41bf85b7eefeab5ca0cb9ffc8ea04a46acb25534a577694f9e25340a4ab5223a9dd1eda530c8aa2e6718db10d7e672558c7736fe09369ea5739a2a3554bf16d41faa50562f11c6d39bbd5dffb6b9a9ec9180301090989008404181309000c05024d530592051b0c000000000a0910098033880f54719f80970180eee7a6d8fcee41ee4f9289df17f9bcf9d955dca25c583b94336f3a2b2d4986dc5cf417b8d2dc86f741a9e1a6d236c0e3017d1c76575458a0cfb93ae8a2b274fcc65ceecd7a91eec83656ba13219969f06945b48c56bd04152c3a0553c5f2f4bd1267` ����������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/public_key.go��������������������������������0000644�0610621�0607500�00000051240�13172163317�026450� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto" "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" "crypto/rsa" "crypto/sha1" _ "crypto/sha256" _ "crypto/sha512" "encoding/binary" "fmt" "hash" "io" "math/big" "strconv" "time" "golang.org/x/crypto/openpgp/elgamal" "golang.org/x/crypto/openpgp/errors" ) var ( // NIST curve P-256 oidCurveP256 []byte = []byte{0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07} // NIST curve P-384 oidCurveP384 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x22} // NIST curve P-521 oidCurveP521 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x23} ) const maxOIDLength = 8 // ecdsaKey stores the algorithm-specific fields for ECDSA keys. // as defined in RFC 6637, Section 9. type ecdsaKey struct { // oid contains the OID byte sequence identifying the elliptic curve used oid []byte // p contains the elliptic curve point that represents the public key p parsedMPI } // parseOID reads the OID for the curve as defined in RFC 6637, Section 9. func parseOID(r io.Reader) (oid []byte, err error) { buf := make([]byte, maxOIDLength) if _, err = readFull(r, buf[:1]); err != nil { return } oidLen := buf[0] if int(oidLen) > len(buf) { err = errors.UnsupportedError("invalid oid length: " + strconv.Itoa(int(oidLen))) return } oid = buf[:oidLen] _, err = readFull(r, oid) return } func (f *ecdsaKey) parse(r io.Reader) (err error) { if f.oid, err = parseOID(r); err != nil { return err } f.p.bytes, f.p.bitLength, err = readMPI(r) return } func (f *ecdsaKey) serialize(w io.Writer) (err error) { buf := make([]byte, maxOIDLength+1) buf[0] = byte(len(f.oid)) copy(buf[1:], f.oid) if _, err = w.Write(buf[:len(f.oid)+1]); err != nil { return } return writeMPIs(w, f.p) } func (f *ecdsaKey) newECDSA() (*ecdsa.PublicKey, error) { var c elliptic.Curve if bytes.Equal(f.oid, oidCurveP256) { c = elliptic.P256() } else if bytes.Equal(f.oid, oidCurveP384) { c = elliptic.P384() } else if bytes.Equal(f.oid, oidCurveP521) { c = elliptic.P521() } else { return nil, errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", f.oid)) } x, y := elliptic.Unmarshal(c, f.p.bytes) if x == nil { return nil, errors.UnsupportedError("failed to parse EC point") } return &ecdsa.PublicKey{Curve: c, X: x, Y: y}, nil } func (f *ecdsaKey) byteLen() int { return 1 + len(f.oid) + 2 + len(f.p.bytes) } type kdfHashFunction byte type kdfAlgorithm byte // ecdhKdf stores key derivation function parameters // used for ECDH encryption. See RFC 6637, Section 9. type ecdhKdf struct { KdfHash kdfHashFunction KdfAlgo kdfAlgorithm } func (f *ecdhKdf) parse(r io.Reader) (err error) { buf := make([]byte, 1) if _, err = readFull(r, buf); err != nil { return } kdfLen := int(buf[0]) if kdfLen < 3 { return errors.UnsupportedError("Unsupported ECDH KDF length: " + strconv.Itoa(kdfLen)) } buf = make([]byte, kdfLen) if _, err = readFull(r, buf); err != nil { return } reserved := int(buf[0]) f.KdfHash = kdfHashFunction(buf[1]) f.KdfAlgo = kdfAlgorithm(buf[2]) if reserved != 0x01 { return errors.UnsupportedError("Unsupported KDF reserved field: " + strconv.Itoa(reserved)) } return } func (f *ecdhKdf) serialize(w io.Writer) (err error) { buf := make([]byte, 4) // See RFC 6637, Section 9, Algorithm-Specific Fields for ECDH keys. buf[0] = byte(0x03) // Length of the following fields buf[1] = byte(0x01) // Reserved for future extensions, must be 1 for now buf[2] = byte(f.KdfHash) buf[3] = byte(f.KdfAlgo) _, err = w.Write(buf[:]) return } func (f *ecdhKdf) byteLen() int { return 4 } // PublicKey represents an OpenPGP public key. See RFC 4880, section 5.5.2. type PublicKey struct { CreationTime time.Time PubKeyAlgo PublicKeyAlgorithm PublicKey interface{} // *rsa.PublicKey, *dsa.PublicKey or *ecdsa.PublicKey Fingerprint [20]byte KeyId uint64 IsSubkey bool n, e, p, q, g, y parsedMPI // RFC 6637 fields ec *ecdsaKey ecdh *ecdhKdf } // signingKey provides a convenient abstraction over signature verification // for v3 and v4 public keys. type signingKey interface { SerializeSignaturePrefix(io.Writer) serializeWithoutHeaders(io.Writer) error } func fromBig(n *big.Int) parsedMPI { return parsedMPI{ bytes: n.Bytes(), bitLength: uint16(n.BitLen()), } } // NewRSAPublicKey returns a PublicKey that wraps the given rsa.PublicKey. func NewRSAPublicKey(creationTime time.Time, pub *rsa.PublicKey) *PublicKey { pk := &PublicKey{ CreationTime: creationTime, PubKeyAlgo: PubKeyAlgoRSA, PublicKey: pub, n: fromBig(pub.N), e: fromBig(big.NewInt(int64(pub.E))), } pk.setFingerPrintAndKeyId() return pk } // NewDSAPublicKey returns a PublicKey that wraps the given dsa.PublicKey. func NewDSAPublicKey(creationTime time.Time, pub *dsa.PublicKey) *PublicKey { pk := &PublicKey{ CreationTime: creationTime, PubKeyAlgo: PubKeyAlgoDSA, PublicKey: pub, p: fromBig(pub.P), q: fromBig(pub.Q), g: fromBig(pub.G), y: fromBig(pub.Y), } pk.setFingerPrintAndKeyId() return pk } // NewElGamalPublicKey returns a PublicKey that wraps the given elgamal.PublicKey. func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *PublicKey { pk := &PublicKey{ CreationTime: creationTime, PubKeyAlgo: PubKeyAlgoElGamal, PublicKey: pub, p: fromBig(pub.P), g: fromBig(pub.G), y: fromBig(pub.Y), } pk.setFingerPrintAndKeyId() return pk } func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey { pk := &PublicKey{ CreationTime: creationTime, PubKeyAlgo: PubKeyAlgoECDSA, PublicKey: pub, ec: new(ecdsaKey), } switch pub.Curve { case elliptic.P256(): pk.ec.oid = oidCurveP256 case elliptic.P384(): pk.ec.oid = oidCurveP384 case elliptic.P521(): pk.ec.oid = oidCurveP521 default: panic("unknown elliptic curve") } pk.ec.p.bytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) pk.ec.p.bitLength = uint16(8 * len(pk.ec.p.bytes)) pk.setFingerPrintAndKeyId() return pk } func (pk *PublicKey) parse(r io.Reader) (err error) { // RFC 4880, section 5.5.2 var buf [6]byte _, err = readFull(r, buf[:]) if err != nil { return } if buf[0] != 4 { return errors.UnsupportedError("public key version") } pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0) pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5]) switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: err = pk.parseRSA(r) case PubKeyAlgoDSA: err = pk.parseDSA(r) case PubKeyAlgoElGamal: err = pk.parseElGamal(r) case PubKeyAlgoECDSA: pk.ec = new(ecdsaKey) if err = pk.ec.parse(r); err != nil { return err } pk.PublicKey, err = pk.ec.newECDSA() case PubKeyAlgoECDH: pk.ec = new(ecdsaKey) if err = pk.ec.parse(r); err != nil { return } pk.ecdh = new(ecdhKdf) if err = pk.ecdh.parse(r); err != nil { return } // The ECDH key is stored in an ecdsa.PublicKey for convenience. pk.PublicKey, err = pk.ec.newECDSA() default: err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) } if err != nil { return } pk.setFingerPrintAndKeyId() return } func (pk *PublicKey) setFingerPrintAndKeyId() { // RFC 4880, section 12.2 fingerPrint := sha1.New() pk.SerializeSignaturePrefix(fingerPrint) pk.serializeWithoutHeaders(fingerPrint) copy(pk.Fingerprint[:], fingerPrint.Sum(nil)) pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[12:20]) } // parseRSA parses RSA public key material from the given Reader. See RFC 4880, // section 5.5.2. func (pk *PublicKey) parseRSA(r io.Reader) (err error) { pk.n.bytes, pk.n.bitLength, err = readMPI(r) if err != nil { return } pk.e.bytes, pk.e.bitLength, err = readMPI(r) if err != nil { return } if len(pk.e.bytes) > 3 { err = errors.UnsupportedError("large public exponent") return } rsa := &rsa.PublicKey{ N: new(big.Int).SetBytes(pk.n.bytes), E: 0, } for i := 0; i < len(pk.e.bytes); i++ { rsa.E <<= 8 rsa.E |= int(pk.e.bytes[i]) } pk.PublicKey = rsa return } // parseDSA parses DSA public key material from the given Reader. See RFC 4880, // section 5.5.2. func (pk *PublicKey) parseDSA(r io.Reader) (err error) { pk.p.bytes, pk.p.bitLength, err = readMPI(r) if err != nil { return } pk.q.bytes, pk.q.bitLength, err = readMPI(r) if err != nil { return } pk.g.bytes, pk.g.bitLength, err = readMPI(r) if err != nil { return } pk.y.bytes, pk.y.bitLength, err = readMPI(r) if err != nil { return } dsa := new(dsa.PublicKey) dsa.P = new(big.Int).SetBytes(pk.p.bytes) dsa.Q = new(big.Int).SetBytes(pk.q.bytes) dsa.G = new(big.Int).SetBytes(pk.g.bytes) dsa.Y = new(big.Int).SetBytes(pk.y.bytes) pk.PublicKey = dsa return } // parseElGamal parses ElGamal public key material from the given Reader. See // RFC 4880, section 5.5.2. func (pk *PublicKey) parseElGamal(r io.Reader) (err error) { pk.p.bytes, pk.p.bitLength, err = readMPI(r) if err != nil { return } pk.g.bytes, pk.g.bitLength, err = readMPI(r) if err != nil { return } pk.y.bytes, pk.y.bitLength, err = readMPI(r) if err != nil { return } elgamal := new(elgamal.PublicKey) elgamal.P = new(big.Int).SetBytes(pk.p.bytes) elgamal.G = new(big.Int).SetBytes(pk.g.bytes) elgamal.Y = new(big.Int).SetBytes(pk.y.bytes) pk.PublicKey = elgamal return } // SerializeSignaturePrefix writes the prefix for this public key to the given Writer. // The prefix is used when calculating a signature over this public key. See // RFC 4880, section 5.2.4. func (pk *PublicKey) SerializeSignaturePrefix(h io.Writer) { var pLength uint16 switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: pLength += 2 + uint16(len(pk.n.bytes)) pLength += 2 + uint16(len(pk.e.bytes)) case PubKeyAlgoDSA: pLength += 2 + uint16(len(pk.p.bytes)) pLength += 2 + uint16(len(pk.q.bytes)) pLength += 2 + uint16(len(pk.g.bytes)) pLength += 2 + uint16(len(pk.y.bytes)) case PubKeyAlgoElGamal: pLength += 2 + uint16(len(pk.p.bytes)) pLength += 2 + uint16(len(pk.g.bytes)) pLength += 2 + uint16(len(pk.y.bytes)) case PubKeyAlgoECDSA: pLength += uint16(pk.ec.byteLen()) case PubKeyAlgoECDH: pLength += uint16(pk.ec.byteLen()) pLength += uint16(pk.ecdh.byteLen()) default: panic("unknown public key algorithm") } pLength += 6 h.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) return } func (pk *PublicKey) Serialize(w io.Writer) (err error) { length := 6 // 6 byte header switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: length += 2 + len(pk.n.bytes) length += 2 + len(pk.e.bytes) case PubKeyAlgoDSA: length += 2 + len(pk.p.bytes) length += 2 + len(pk.q.bytes) length += 2 + len(pk.g.bytes) length += 2 + len(pk.y.bytes) case PubKeyAlgoElGamal: length += 2 + len(pk.p.bytes) length += 2 + len(pk.g.bytes) length += 2 + len(pk.y.bytes) case PubKeyAlgoECDSA: length += pk.ec.byteLen() case PubKeyAlgoECDH: length += pk.ec.byteLen() length += pk.ecdh.byteLen() default: panic("unknown public key algorithm") } packetType := packetTypePublicKey if pk.IsSubkey { packetType = packetTypePublicSubkey } err = serializeHeader(w, packetType, length) if err != nil { return } return pk.serializeWithoutHeaders(w) } // serializeWithoutHeaders marshals the PublicKey to w in the form of an // OpenPGP public key packet, not including the packet header. func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) { var buf [6]byte buf[0] = 4 t := uint32(pk.CreationTime.Unix()) buf[1] = byte(t >> 24) buf[2] = byte(t >> 16) buf[3] = byte(t >> 8) buf[4] = byte(t) buf[5] = byte(pk.PubKeyAlgo) _, err = w.Write(buf[:]) if err != nil { return } switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: return writeMPIs(w, pk.n, pk.e) case PubKeyAlgoDSA: return writeMPIs(w, pk.p, pk.q, pk.g, pk.y) case PubKeyAlgoElGamal: return writeMPIs(w, pk.p, pk.g, pk.y) case PubKeyAlgoECDSA: return pk.ec.serialize(w) case PubKeyAlgoECDH: if err = pk.ec.serialize(w); err != nil { return } return pk.ecdh.serialize(w) } return errors.InvalidArgumentError("bad public-key algorithm") } // CanSign returns true iff this public key can generate signatures func (pk *PublicKey) CanSign() bool { return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly && pk.PubKeyAlgo != PubKeyAlgoElGamal } // VerifySignature returns nil iff sig is a valid signature, made by this // public key, of the data hashed into signed. signed is mutated by this call. func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) { if !pk.CanSign() { return errors.InvalidArgumentError("public key cannot generate signatures") } signed.Write(sig.HashSuffix) hashBytes := signed.Sum(nil) if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { return errors.SignatureError("hash tag doesn't match") } if pk.PubKeyAlgo != sig.PubKeyAlgo { return errors.InvalidArgumentError("public key and signature use different algorithms") } switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey) err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes) if err != nil { return errors.SignatureError("RSA verification failure") } return nil case PubKeyAlgoDSA: dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey) // Need to truncate hashBytes to match FIPS 186-3 section 4.6. subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8 if len(hashBytes) > subgroupSize { hashBytes = hashBytes[:subgroupSize] } if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) { return errors.SignatureError("DSA verification failure") } return nil case PubKeyAlgoECDSA: ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey) if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) { return errors.SignatureError("ECDSA verification failure") } return nil default: return errors.SignatureError("Unsupported public key algorithm used in signature") } } // VerifySignatureV3 returns nil iff sig is a valid signature, made by this // public key, of the data hashed into signed. signed is mutated by this call. func (pk *PublicKey) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) { if !pk.CanSign() { return errors.InvalidArgumentError("public key cannot generate signatures") } suffix := make([]byte, 5) suffix[0] = byte(sig.SigType) binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix())) signed.Write(suffix) hashBytes := signed.Sum(nil) if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { return errors.SignatureError("hash tag doesn't match") } if pk.PubKeyAlgo != sig.PubKeyAlgo { return errors.InvalidArgumentError("public key and signature use different algorithms") } switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: rsaPublicKey := pk.PublicKey.(*rsa.PublicKey) if err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil { return errors.SignatureError("RSA verification failure") } return case PubKeyAlgoDSA: dsaPublicKey := pk.PublicKey.(*dsa.PublicKey) // Need to truncate hashBytes to match FIPS 186-3 section 4.6. subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8 if len(hashBytes) > subgroupSize { hashBytes = hashBytes[:subgroupSize] } if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) { return errors.SignatureError("DSA verification failure") } return nil default: panic("shouldn't happen") } } // keySignatureHash returns a Hash of the message that needs to be signed for // pk to assert a subkey relationship to signed. func keySignatureHash(pk, signed signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) { if !hashFunc.Available() { return nil, errors.UnsupportedError("hash function") } h = hashFunc.New() // RFC 4880, section 5.2.4 pk.SerializeSignaturePrefix(h) pk.serializeWithoutHeaders(h) signed.SerializeSignaturePrefix(h) signed.serializeWithoutHeaders(h) return } // VerifyKeySignature returns nil iff sig is a valid signature, made by this // public key, of signed. func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error { h, err := keySignatureHash(pk, signed, sig.Hash) if err != nil { return err } if err = pk.VerifySignature(h, sig); err != nil { return err } if sig.FlagSign { // Signing subkeys must be cross-signed. See // https://www.gnupg.org/faq/subkey-cross-certify.html. if sig.EmbeddedSignature == nil { return errors.StructuralError("signing subkey is missing cross-signature") } // Verify the cross-signature. This is calculated over the same // data as the main signature, so we cannot just recursively // call signed.VerifyKeySignature(...) if h, err = keySignatureHash(pk, signed, sig.EmbeddedSignature.Hash); err != nil { return errors.StructuralError("error while hashing for cross-signature: " + err.Error()) } if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil { return errors.StructuralError("error while verifying cross-signature: " + err.Error()) } } return nil } func keyRevocationHash(pk signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) { if !hashFunc.Available() { return nil, errors.UnsupportedError("hash function") } h = hashFunc.New() // RFC 4880, section 5.2.4 pk.SerializeSignaturePrefix(h) pk.serializeWithoutHeaders(h) return } // VerifyRevocationSignature returns nil iff sig is a valid signature, made by this // public key. func (pk *PublicKey) VerifyRevocationSignature(sig *Signature) (err error) { h, err := keyRevocationHash(pk, sig.Hash) if err != nil { return err } return pk.VerifySignature(h, sig) } // userIdSignatureHash returns a Hash of the message that needs to be signed // to assert that pk is a valid key for id. func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) { if !hashFunc.Available() { return nil, errors.UnsupportedError("hash function") } h = hashFunc.New() // RFC 4880, section 5.2.4 pk.SerializeSignaturePrefix(h) pk.serializeWithoutHeaders(h) var buf [5]byte buf[0] = 0xb4 buf[1] = byte(len(id) >> 24) buf[2] = byte(len(id) >> 16) buf[3] = byte(len(id) >> 8) buf[4] = byte(len(id)) h.Write(buf[:]) h.Write([]byte(id)) return } // VerifyUserIdSignature returns nil iff sig is a valid signature, made by this // public key, that id is the identity of pub. func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) { h, err := userIdSignatureHash(id, pub, sig.Hash) if err != nil { return err } return pk.VerifySignature(h, sig) } // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this // public key, that id is the identity of pub. func (pk *PublicKey) VerifyUserIdSignatureV3(id string, pub *PublicKey, sig *SignatureV3) (err error) { h, err := userIdSignatureV3Hash(id, pub, sig.Hash) if err != nil { return err } return pk.VerifySignatureV3(h, sig) } // KeyIdString returns the public key's fingerprint in capital hex // (e.g. "6C7EE1B8621CC013"). func (pk *PublicKey) KeyIdString() string { return fmt.Sprintf("%X", pk.Fingerprint[12:20]) } // KeyIdShortString returns the short form of public key's fingerprint // in capital hex, as shown by gpg --list-keys (e.g. "621CC013"). func (pk *PublicKey) KeyIdShortString() string { return fmt.Sprintf("%X", pk.Fingerprint[16:20]) } // A parsedMPI is used to store the contents of a big integer, along with the // bit length that was specified in the original input. This allows the MPI to // be reserialized exactly. type parsedMPI struct { bytes []byte bitLength uint16 } // writeMPIs is a utility function for serializing several big integers to the // given Writer. func writeMPIs(w io.Writer, mpis ...parsedMPI) (err error) { for _, mpi := range mpis { err = writeMPI(w, mpi.bitLength, mpi.bytes) if err != nil { return } } return } // BitLength returns the bit length for the given public key. func (pk *PublicKey) BitLength() (bitLength uint16, err error) { switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: bitLength = pk.n.bitLength case PubKeyAlgoDSA: bitLength = pk.p.bitLength case PubKeyAlgoElGamal: bitLength = pk.p.bitLength default: err = errors.InvalidArgumentError("bad public-key algorithm") } return } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/private_key_test.go��������������������������0000644�0610621�0607500�00000021014�13172163317�027677� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/hex" "hash" "io" "testing" "time" ) var privateKeyTests = []struct { privateKeyHex string creationTime time.Time }{ { privKeyRSAHex, time.Unix(0x4cc349a8, 0), }, { privKeyElGamalHex, time.Unix(0x4df9ee1a, 0), }, } func TestPrivateKeyRead(t *testing.T) { for i, test := range privateKeyTests { packet, err := Read(readerFromHex(test.privateKeyHex)) if err != nil { t.Errorf("#%d: failed to parse: %s", i, err) continue } privKey := packet.(*PrivateKey) if !privKey.Encrypted { t.Errorf("#%d: private key isn't encrypted", i) continue } err = privKey.Decrypt([]byte("wrong password")) if err == nil { t.Errorf("#%d: decrypted with incorrect key", i) continue } err = privKey.Decrypt([]byte("testing")) if err != nil { t.Errorf("#%d: failed to decrypt: %s", i, err) continue } if !privKey.CreationTime.Equal(test.creationTime) || privKey.Encrypted { t.Errorf("#%d: bad result, got: %#v", i, privKey) } } } func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) { h := hashFunc.New() if _, err := h.Write(msg); err != nil { return nil, err } return h, nil } func TestRSAPrivateKey(t *testing.T) { privKeyDER, _ := hex.DecodeString(pkcs1PrivKeyHex) rsaPriv, err := x509.ParsePKCS1PrivateKey(privKeyDER) if err != nil { t.Fatal(err) } var buf bytes.Buffer if err := NewRSAPrivateKey(time.Now(), rsaPriv).Serialize(&buf); err != nil { t.Fatal(err) } p, err := Read(&buf) if err != nil { t.Fatal(err) } priv, ok := p.(*PrivateKey) if !ok { t.Fatal("didn't parse private key") } sig := &Signature{ PubKeyAlgo: PubKeyAlgoRSA, Hash: crypto.SHA256, } msg := []byte("Hello World!") h, err := populateHash(sig.Hash, msg) if err != nil { t.Fatal(err) } if err := sig.Sign(h, priv, nil); err != nil { t.Fatal(err) } if h, err = populateHash(sig.Hash, msg); err != nil { t.Fatal(err) } if err := priv.VerifySignature(h, sig); err != nil { t.Fatal(err) } } func TestECDSAPrivateKey(t *testing.T) { ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } var buf bytes.Buffer if err := NewECDSAPrivateKey(time.Now(), ecdsaPriv).Serialize(&buf); err != nil { t.Fatal(err) } p, err := Read(&buf) if err != nil { t.Fatal(err) } priv, ok := p.(*PrivateKey) if !ok { t.Fatal("didn't parse private key") } sig := &Signature{ PubKeyAlgo: PubKeyAlgoECDSA, Hash: crypto.SHA256, } msg := []byte("Hello World!") h, err := populateHash(sig.Hash, msg) if err != nil { t.Fatal(err) } if err := sig.Sign(h, priv, nil); err != nil { t.Fatal(err) } if h, err = populateHash(sig.Hash, msg); err != nil { t.Fatal(err) } if err := priv.VerifySignature(h, sig); err != nil { t.Fatal(err) } } type rsaSigner struct { priv *rsa.PrivateKey } func (s *rsaSigner) Public() crypto.PublicKey { return s.priv.PublicKey } func (s *rsaSigner) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { return s.priv.Sign(rand, msg, opts) } func TestRSASignerPrivateKey(t *testing.T) { rsaPriv, err := rsa.GenerateKey(rand.Reader, 1024) if err != nil { t.Fatal(err) } priv := NewSignerPrivateKey(time.Now(), &rsaSigner{rsaPriv}) if priv.PubKeyAlgo != PubKeyAlgoRSASignOnly { t.Fatal("NewSignerPrivateKey should have made a sign-only RSA private key") } sig := &Signature{ PubKeyAlgo: PubKeyAlgoRSASignOnly, Hash: crypto.SHA256, } msg := []byte("Hello World!") h, err := populateHash(sig.Hash, msg) if err != nil { t.Fatal(err) } if err := sig.Sign(h, priv, nil); err != nil { t.Fatal(err) } if h, err = populateHash(sig.Hash, msg); err != nil { t.Fatal(err) } if err := priv.VerifySignature(h, sig); err != nil { t.Fatal(err) } } type ecdsaSigner struct { priv *ecdsa.PrivateKey } func (s *ecdsaSigner) Public() crypto.PublicKey { return s.priv.PublicKey } func (s *ecdsaSigner) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { return s.priv.Sign(rand, msg, opts) } func TestECDSASignerPrivateKey(t *testing.T) { ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } priv := NewSignerPrivateKey(time.Now(), &ecdsaSigner{ecdsaPriv}) if priv.PubKeyAlgo != PubKeyAlgoECDSA { t.Fatal("NewSignerPrivateKey should have made an ECSDA private key") } sig := &Signature{ PubKeyAlgo: PubKeyAlgoECDSA, Hash: crypto.SHA256, } msg := []byte("Hello World!") h, err := populateHash(sig.Hash, msg) if err != nil { t.Fatal(err) } if err := sig.Sign(h, priv, nil); err != nil { t.Fatal(err) } if h, err = populateHash(sig.Hash, msg); err != nil { t.Fatal(err) } if err := priv.VerifySignature(h, sig); err != nil { t.Fatal(err) } } func TestIssue11505(t *testing.T) { // parsing a rsa private key with p or q == 1 used to panic due to a divide by zero _, _ = Read(readerFromHex("9c3004303030300100000011303030000000000000010130303030303030303030303030303030303030303030303030303030303030303030303030303030303030")) } // Generated with `gpg --export-secret-keys "Test Key 2"` const privKeyRSAHex = "9501fe044cc349a8010400b70ca0010e98c090008d45d1ee8f9113bd5861fd57b88bacb7c68658747663f1e1a3b5a98f32fda6472373c024b97359cd2efc88ff60f77751adfbf6af5e615e6a1408cfad8bf0cea30b0d5f53aa27ad59089ba9b15b7ebc2777a25d7b436144027e3bcd203909f147d0e332b240cf63d3395f5dfe0df0a6c04e8655af7eacdf0011010001fe0303024a252e7d475fd445607de39a265472aa74a9320ba2dac395faa687e9e0336aeb7e9a7397e511b5afd9dc84557c80ac0f3d4d7bfec5ae16f20d41c8c84a04552a33870b930420e230e179564f6d19bb153145e76c33ae993886c388832b0fa042ddda7f133924f3854481533e0ede31d51278c0519b29abc3bf53da673e13e3e1214b52413d179d7f66deee35cac8eacb060f78379d70ef4af8607e68131ff529439668fc39c9ce6dfef8a5ac234d234802cbfb749a26107db26406213ae5c06d4673253a3cbee1fcbae58d6ab77e38d6e2c0e7c6317c48e054edadb5a40d0d48acb44643d998139a8a66bb820be1f3f80185bc777d14b5954b60effe2448a036d565c6bc0b915fcea518acdd20ab07bc1529f561c58cd044f723109b93f6fd99f876ff891d64306b5d08f48bab59f38695e9109c4dec34013ba3153488ce070268381ba923ee1eb77125b36afcb4347ec3478c8f2735b06ef17351d872e577fa95d0c397c88c71b59629a36aec" // Generated by `gpg --export-secret-keys` followed by a manual extraction of // the ElGamal subkey from the packets. const privKeyElGamalHex = "9d0157044df9ee1a100400eb8e136a58ec39b582629cdadf830bc64e0a94ed8103ca8bb247b27b11b46d1d25297ef4bcc3071785ba0c0bedfe89eabc5287fcc0edf81ab5896c1c8e4b20d27d79813c7aede75320b33eaeeaa586edc00fd1036c10133e6ba0ff277245d0d59d04b2b3421b7244aca5f4a8d870c6f1c1fbff9e1c26699a860b9504f35ca1d700030503fd1ededd3b840795be6d9ccbe3c51ee42e2f39233c432b831ddd9c4e72b7025a819317e47bf94f9ee316d7273b05d5fcf2999c3a681f519b1234bbfa6d359b4752bd9c3f77d6b6456cde152464763414ca130f4e91d91041432f90620fec0e6d6b5116076c2985d5aeaae13be492b9b329efcaf7ee25120159a0a30cd976b42d7afe030302dae7eb80db744d4960c4df930d57e87fe81412eaace9f900e6c839817a614ddb75ba6603b9417c33ea7b6c93967dfa2bcff3fa3c74a5ce2c962db65b03aece14c96cbd0038fc" // pkcs1PrivKeyHex is a PKCS#1, RSA private key. // Generated by `openssl genrsa 1024 | openssl rsa -outform DER | xxd -p` const pkcs1PrivKeyHex = "3082025d02010002818100e98edfa1c3b35884a54d0b36a6a603b0290fa85e49e30fa23fc94fef9c6790bc4849928607aa48d809da326fb42a969d06ad756b98b9c1a90f5d4a2b6d0ac05953c97f4da3120164a21a679793ce181c906dc01d235cc085ddcdf6ea06c389b6ab8885dfd685959e693138856a68a7e5db263337ff82a088d583a897cf2d59e9020301000102818100b6d5c9eb70b02d5369b3ee5b520a14490b5bde8a317d36f7e4c74b7460141311d1e5067735f8f01d6f5908b2b96fbd881f7a1ab9a84d82753e39e19e2d36856be960d05ac9ef8e8782ea1b6d65aee28fdfe1d61451e8cff0adfe84322f12cf455028b581cf60eb9e0e140ba5d21aeba6c2634d7c65318b9a665fc01c3191ca21024100fa5e818da3705b0fa33278bb28d4b6f6050388af2d4b75ec9375dd91ccf2e7d7068086a8b82a8f6282e4fbbdb8a7f2622eb97295249d87acea7f5f816f54d347024100eecf9406d7dc49cdfb95ab1eff4064de84c7a30f64b2798936a0d2018ba9eb52e4b636f82e96c49cc63b80b675e91e40d1b2e4017d4b9adaf33ab3d9cf1c214f024100c173704ace742c082323066226a4655226819a85304c542b9dacbeacbf5d1881ee863485fcf6f59f3a604f9b42289282067447f2b13dfeed3eab7851fc81e0550240741fc41f3fc002b382eed8730e33c5d8de40256e4accee846667f536832f711ab1d4590e7db91a8a116ac5bff3be13d3f9243ff2e976662aa9b395d907f8e9c9024046a5696c9ef882363e06c9fa4e2f5b580906452befba03f4a99d0f873697ef1f851d2226ca7934b30b7c3e80cb634a67172bbbf4781735fe3e09263e2dd723e7" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/private_key.go�������������������������������0000644�0610621�0607500�00000021202�13172163317�026637� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto" "crypto/cipher" "crypto/dsa" "crypto/ecdsa" "crypto/rsa" "crypto/sha1" "io" "io/ioutil" "math/big" "strconv" "time" "golang.org/x/crypto/openpgp/elgamal" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/s2k" ) // PrivateKey represents a possibly encrypted private key. See RFC 4880, // section 5.5.3. type PrivateKey struct { PublicKey Encrypted bool // if true then the private key is unavailable until Decrypt has been called. encryptedData []byte cipher CipherFunction s2k func(out, in []byte) PrivateKey interface{} // An *{rsa|dsa|ecdsa}.PrivateKey or a crypto.Signer. sha1Checksum bool iv []byte } func NewRSAPrivateKey(currentTime time.Time, priv *rsa.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewRSAPublicKey(currentTime, &priv.PublicKey) pk.PrivateKey = priv return pk } func NewDSAPrivateKey(currentTime time.Time, priv *dsa.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewDSAPublicKey(currentTime, &priv.PublicKey) pk.PrivateKey = priv return pk } func NewElGamalPrivateKey(currentTime time.Time, priv *elgamal.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewElGamalPublicKey(currentTime, &priv.PublicKey) pk.PrivateKey = priv return pk } func NewECDSAPrivateKey(currentTime time.Time, priv *ecdsa.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewECDSAPublicKey(currentTime, &priv.PublicKey) pk.PrivateKey = priv return pk } // NewSignerPrivateKey creates a sign-only PrivateKey from a crypto.Signer that // implements RSA or ECDSA. func NewSignerPrivateKey(currentTime time.Time, signer crypto.Signer) *PrivateKey { pk := new(PrivateKey) switch pubkey := signer.Public().(type) { case rsa.PublicKey: pk.PublicKey = *NewRSAPublicKey(currentTime, &pubkey) pk.PubKeyAlgo = PubKeyAlgoRSASignOnly case ecdsa.PublicKey: pk.PublicKey = *NewECDSAPublicKey(currentTime, &pubkey) default: panic("openpgp: unknown crypto.Signer type in NewSignerPrivateKey") } pk.PrivateKey = signer return pk } func (pk *PrivateKey) parse(r io.Reader) (err error) { err = (&pk.PublicKey).parse(r) if err != nil { return } var buf [1]byte _, err = readFull(r, buf[:]) if err != nil { return } s2kType := buf[0] switch s2kType { case 0: pk.s2k = nil pk.Encrypted = false case 254, 255: _, err = readFull(r, buf[:]) if err != nil { return } pk.cipher = CipherFunction(buf[0]) pk.Encrypted = true pk.s2k, err = s2k.Parse(r) if err != nil { return } if s2kType == 254 { pk.sha1Checksum = true } default: return errors.UnsupportedError("deprecated s2k function in private key") } if pk.Encrypted { blockSize := pk.cipher.blockSize() if blockSize == 0 { return errors.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher))) } pk.iv = make([]byte, blockSize) _, err = readFull(r, pk.iv) if err != nil { return } } pk.encryptedData, err = ioutil.ReadAll(r) if err != nil { return } if !pk.Encrypted { return pk.parsePrivateKey(pk.encryptedData) } return } func mod64kHash(d []byte) uint16 { var h uint16 for _, b := range d { h += uint16(b) } return h } func (pk *PrivateKey) Serialize(w io.Writer) (err error) { // TODO(agl): support encrypted private keys buf := bytes.NewBuffer(nil) err = pk.PublicKey.serializeWithoutHeaders(buf) if err != nil { return } buf.WriteByte(0 /* no encryption */) privateKeyBuf := bytes.NewBuffer(nil) switch priv := pk.PrivateKey.(type) { case *rsa.PrivateKey: err = serializeRSAPrivateKey(privateKeyBuf, priv) case *dsa.PrivateKey: err = serializeDSAPrivateKey(privateKeyBuf, priv) case *elgamal.PrivateKey: err = serializeElGamalPrivateKey(privateKeyBuf, priv) case *ecdsa.PrivateKey: err = serializeECDSAPrivateKey(privateKeyBuf, priv) default: err = errors.InvalidArgumentError("unknown private key type") } if err != nil { return } ptype := packetTypePrivateKey contents := buf.Bytes() privateKeyBytes := privateKeyBuf.Bytes() if pk.IsSubkey { ptype = packetTypePrivateSubkey } err = serializeHeader(w, ptype, len(contents)+len(privateKeyBytes)+2) if err != nil { return } _, err = w.Write(contents) if err != nil { return } _, err = w.Write(privateKeyBytes) if err != nil { return } checksum := mod64kHash(privateKeyBytes) var checksumBytes [2]byte checksumBytes[0] = byte(checksum >> 8) checksumBytes[1] = byte(checksum) _, err = w.Write(checksumBytes[:]) return } func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error { err := writeBig(w, priv.D) if err != nil { return err } err = writeBig(w, priv.Primes[1]) if err != nil { return err } err = writeBig(w, priv.Primes[0]) if err != nil { return err } return writeBig(w, priv.Precomputed.Qinv) } func serializeDSAPrivateKey(w io.Writer, priv *dsa.PrivateKey) error { return writeBig(w, priv.X) } func serializeElGamalPrivateKey(w io.Writer, priv *elgamal.PrivateKey) error { return writeBig(w, priv.X) } func serializeECDSAPrivateKey(w io.Writer, priv *ecdsa.PrivateKey) error { return writeBig(w, priv.D) } // Decrypt decrypts an encrypted private key using a passphrase. func (pk *PrivateKey) Decrypt(passphrase []byte) error { if !pk.Encrypted { return nil } key := make([]byte, pk.cipher.KeySize()) pk.s2k(key, passphrase) block := pk.cipher.new(key) cfb := cipher.NewCFBDecrypter(block, pk.iv) data := make([]byte, len(pk.encryptedData)) cfb.XORKeyStream(data, pk.encryptedData) if pk.sha1Checksum { if len(data) < sha1.Size { return errors.StructuralError("truncated private key data") } h := sha1.New() h.Write(data[:len(data)-sha1.Size]) sum := h.Sum(nil) if !bytes.Equal(sum, data[len(data)-sha1.Size:]) { return errors.StructuralError("private key checksum failure") } data = data[:len(data)-sha1.Size] } else { if len(data) < 2 { return errors.StructuralError("truncated private key data") } var sum uint16 for i := 0; i < len(data)-2; i++ { sum += uint16(data[i]) } if data[len(data)-2] != uint8(sum>>8) || data[len(data)-1] != uint8(sum) { return errors.StructuralError("private key checksum failure") } data = data[:len(data)-2] } return pk.parsePrivateKey(data) } func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) { switch pk.PublicKey.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly: return pk.parseRSAPrivateKey(data) case PubKeyAlgoDSA: return pk.parseDSAPrivateKey(data) case PubKeyAlgoElGamal: return pk.parseElGamalPrivateKey(data) case PubKeyAlgoECDSA: return pk.parseECDSAPrivateKey(data) } panic("impossible") } func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) { rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey) rsaPriv := new(rsa.PrivateKey) rsaPriv.PublicKey = *rsaPub buf := bytes.NewBuffer(data) d, _, err := readMPI(buf) if err != nil { return } p, _, err := readMPI(buf) if err != nil { return } q, _, err := readMPI(buf) if err != nil { return } rsaPriv.D = new(big.Int).SetBytes(d) rsaPriv.Primes = make([]*big.Int, 2) rsaPriv.Primes[0] = new(big.Int).SetBytes(p) rsaPriv.Primes[1] = new(big.Int).SetBytes(q) if err := rsaPriv.Validate(); err != nil { return err } rsaPriv.Precompute() pk.PrivateKey = rsaPriv pk.Encrypted = false pk.encryptedData = nil return nil } func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) { dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey) dsaPriv := new(dsa.PrivateKey) dsaPriv.PublicKey = *dsaPub buf := bytes.NewBuffer(data) x, _, err := readMPI(buf) if err != nil { return } dsaPriv.X = new(big.Int).SetBytes(x) pk.PrivateKey = dsaPriv pk.Encrypted = false pk.encryptedData = nil return nil } func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) { pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey) priv := new(elgamal.PrivateKey) priv.PublicKey = *pub buf := bytes.NewBuffer(data) x, _, err := readMPI(buf) if err != nil { return } priv.X = new(big.Int).SetBytes(x) pk.PrivateKey = priv pk.Encrypted = false pk.encryptedData = nil return nil } func (pk *PrivateKey) parseECDSAPrivateKey(data []byte) (err error) { ecdsaPub := pk.PublicKey.PublicKey.(*ecdsa.PublicKey) buf := bytes.NewBuffer(data) d, _, err := readMPI(buf) if err != nil { return } pk.PrivateKey = &ecdsa.PrivateKey{ PublicKey: *ecdsaPub, D: new(big.Int).SetBytes(d), } pk.Encrypted = false pk.encryptedData = nil return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/packet_test.go�������������������������������0000644�0610621�0607500�00000014306�13172163317�026632� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/hex" "fmt" "golang.org/x/crypto/openpgp/errors" "io" "io/ioutil" "testing" ) func TestReadFull(t *testing.T) { var out [4]byte b := bytes.NewBufferString("foo") n, err := readFull(b, out[:3]) if n != 3 || err != nil { t.Errorf("full read failed n:%d err:%s", n, err) } b = bytes.NewBufferString("foo") n, err = readFull(b, out[:4]) if n != 3 || err != io.ErrUnexpectedEOF { t.Errorf("partial read failed n:%d err:%s", n, err) } b = bytes.NewBuffer(nil) n, err = readFull(b, out[:3]) if n != 0 || err != io.ErrUnexpectedEOF { t.Errorf("empty read failed n:%d err:%s", n, err) } } func readerFromHex(s string) io.Reader { data, err := hex.DecodeString(s) if err != nil { panic("readerFromHex: bad input") } return bytes.NewBuffer(data) } var readLengthTests = []struct { hexInput string length int64 isPartial bool err error }{ {"", 0, false, io.ErrUnexpectedEOF}, {"1f", 31, false, nil}, {"c0", 0, false, io.ErrUnexpectedEOF}, {"c101", 256 + 1 + 192, false, nil}, {"e0", 1, true, nil}, {"e1", 2, true, nil}, {"e2", 4, true, nil}, {"ff", 0, false, io.ErrUnexpectedEOF}, {"ff00", 0, false, io.ErrUnexpectedEOF}, {"ff0000", 0, false, io.ErrUnexpectedEOF}, {"ff000000", 0, false, io.ErrUnexpectedEOF}, {"ff00000000", 0, false, nil}, {"ff01020304", 16909060, false, nil}, } func TestReadLength(t *testing.T) { for i, test := range readLengthTests { length, isPartial, err := readLength(readerFromHex(test.hexInput)) if test.err != nil { if err != test.err { t.Errorf("%d: expected different error got:%s want:%s", i, err, test.err) } continue } if err != nil { t.Errorf("%d: unexpected error: %s", i, err) continue } if length != test.length || isPartial != test.isPartial { t.Errorf("%d: bad result got:(%d,%t) want:(%d,%t)", i, length, isPartial, test.length, test.isPartial) } } } var partialLengthReaderTests = []struct { hexInput string err error hexOutput string }{ {"e0", io.ErrUnexpectedEOF, ""}, {"e001", io.ErrUnexpectedEOF, ""}, {"e0010102", nil, "0102"}, {"ff00000000", nil, ""}, {"e10102e1030400", nil, "01020304"}, {"e101", io.ErrUnexpectedEOF, ""}, } func TestPartialLengthReader(t *testing.T) { for i, test := range partialLengthReaderTests { r := &partialLengthReader{readerFromHex(test.hexInput), 0, true} out, err := ioutil.ReadAll(r) if test.err != nil { if err != test.err { t.Errorf("%d: expected different error got:%s want:%s", i, err, test.err) } continue } if err != nil { t.Errorf("%d: unexpected error: %s", i, err) continue } got := fmt.Sprintf("%x", out) if got != test.hexOutput { t.Errorf("%d: got:%s want:%s", i, test.hexOutput, got) } } } var readHeaderTests = []struct { hexInput string structuralError bool unexpectedEOF bool tag int length int64 hexOutput string }{ {"", false, false, 0, 0, ""}, {"7f", true, false, 0, 0, ""}, // Old format headers {"80", false, true, 0, 0, ""}, {"8001", false, true, 0, 1, ""}, {"800102", false, false, 0, 1, "02"}, {"81000102", false, false, 0, 1, "02"}, {"820000000102", false, false, 0, 1, "02"}, {"860000000102", false, false, 1, 1, "02"}, {"83010203", false, false, 0, -1, "010203"}, // New format headers {"c0", false, true, 0, 0, ""}, {"c000", false, false, 0, 0, ""}, {"c00102", false, false, 0, 1, "02"}, {"c0020203", false, false, 0, 2, "0203"}, {"c00202", false, true, 0, 2, ""}, {"c3020203", false, false, 3, 2, "0203"}, } func TestReadHeader(t *testing.T) { for i, test := range readHeaderTests { tag, length, contents, err := readHeader(readerFromHex(test.hexInput)) if test.structuralError { if _, ok := err.(errors.StructuralError); ok { continue } t.Errorf("%d: expected StructuralError, got:%s", i, err) continue } if err != nil { if len(test.hexInput) == 0 && err == io.EOF { continue } if !test.unexpectedEOF || err != io.ErrUnexpectedEOF { t.Errorf("%d: unexpected error from readHeader: %s", i, err) } continue } if int(tag) != test.tag || length != test.length { t.Errorf("%d: got:(%d,%d) want:(%d,%d)", i, int(tag), length, test.tag, test.length) continue } body, err := ioutil.ReadAll(contents) if err != nil { if !test.unexpectedEOF || err != io.ErrUnexpectedEOF { t.Errorf("%d: unexpected error from contents: %s", i, err) } continue } if test.unexpectedEOF { t.Errorf("%d: expected ErrUnexpectedEOF from contents but got no error", i) continue } got := fmt.Sprintf("%x", body) if got != test.hexOutput { t.Errorf("%d: got:%s want:%s", i, got, test.hexOutput) } } } func TestSerializeHeader(t *testing.T) { tag := packetTypePublicKey lengths := []int{0, 1, 2, 64, 192, 193, 8000, 8384, 8385, 10000} for _, length := range lengths { buf := bytes.NewBuffer(nil) serializeHeader(buf, tag, length) tag2, length2, _, err := readHeader(buf) if err != nil { t.Errorf("length %d, err: %s", length, err) } if tag2 != tag { t.Errorf("length %d, tag incorrect (got %d, want %d)", length, tag2, tag) } if int(length2) != length { t.Errorf("length %d, length incorrect (got %d)", length, length2) } } } func TestPartialLengths(t *testing.T) { buf := bytes.NewBuffer(nil) w := new(partialLengthWriter) w.w = noOpCloser{buf} const maxChunkSize = 64 var b [maxChunkSize]byte var n uint8 for l := 1; l <= maxChunkSize; l++ { for i := 0; i < l; i++ { b[i] = n n++ } m, err := w.Write(b[:l]) if m != l { t.Errorf("short write got: %d want: %d", m, l) } if err != nil { t.Errorf("error from write: %s", err) } } w.Close() want := (maxChunkSize * (maxChunkSize + 1)) / 2 copyBuf := bytes.NewBuffer(nil) r := &partialLengthReader{buf, 0, true} m, err := io.Copy(copyBuf, r) if m != int64(want) { t.Errorf("short copy got: %d want: %d", m, want) } if err != nil { t.Errorf("error from copy: %s", err) } copyBytes := copyBuf.Bytes() for i := 0; i < want; i++ { if copyBytes[i] != uint8(i) { t.Errorf("bad pattern in copy at %d", i) break } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/packet.go������������������������������������0000644�0610621�0607500�00000032442�13172163317�025574� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package packet implements parsing and serialization of OpenPGP packets, as // specified in RFC 4880. package packet // import "golang.org/x/crypto/openpgp/packet" import ( "bufio" "crypto/aes" "crypto/cipher" "crypto/des" "golang.org/x/crypto/cast5" "golang.org/x/crypto/openpgp/errors" "io" "math/big" ) // readFull is the same as io.ReadFull except that reading zero bytes returns // ErrUnexpectedEOF rather than EOF. func readFull(r io.Reader, buf []byte) (n int, err error) { n, err = io.ReadFull(r, buf) if err == io.EOF { err = io.ErrUnexpectedEOF } return } // readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2. func readLength(r io.Reader) (length int64, isPartial bool, err error) { var buf [4]byte _, err = readFull(r, buf[:1]) if err != nil { return } switch { case buf[0] < 192: length = int64(buf[0]) case buf[0] < 224: length = int64(buf[0]-192) << 8 _, err = readFull(r, buf[0:1]) if err != nil { return } length += int64(buf[0]) + 192 case buf[0] < 255: length = int64(1) << (buf[0] & 0x1f) isPartial = true default: _, err = readFull(r, buf[0:4]) if err != nil { return } length = int64(buf[0])<<24 | int64(buf[1])<<16 | int64(buf[2])<<8 | int64(buf[3]) } return } // partialLengthReader wraps an io.Reader and handles OpenPGP partial lengths. // The continuation lengths are parsed and removed from the stream and EOF is // returned at the end of the packet. See RFC 4880, section 4.2.2.4. type partialLengthReader struct { r io.Reader remaining int64 isPartial bool } func (r *partialLengthReader) Read(p []byte) (n int, err error) { for r.remaining == 0 { if !r.isPartial { return 0, io.EOF } r.remaining, r.isPartial, err = readLength(r.r) if err != nil { return 0, err } } toRead := int64(len(p)) if toRead > r.remaining { toRead = r.remaining } n, err = r.r.Read(p[:int(toRead)]) r.remaining -= int64(n) if n < int(toRead) && err == io.EOF { err = io.ErrUnexpectedEOF } return } // partialLengthWriter writes a stream of data using OpenPGP partial lengths. // See RFC 4880, section 4.2.2.4. type partialLengthWriter struct { w io.WriteCloser lengthByte [1]byte } func (w *partialLengthWriter) Write(p []byte) (n int, err error) { for len(p) > 0 { for power := uint(14); power < 32; power-- { l := 1 << power if len(p) >= l { w.lengthByte[0] = 224 + uint8(power) _, err = w.w.Write(w.lengthByte[:]) if err != nil { return } var m int m, err = w.w.Write(p[:l]) n += m if err != nil { return } p = p[l:] break } } } return } func (w *partialLengthWriter) Close() error { w.lengthByte[0] = 0 _, err := w.w.Write(w.lengthByte[:]) if err != nil { return err } return w.w.Close() } // A spanReader is an io.LimitReader, but it returns ErrUnexpectedEOF if the // underlying Reader returns EOF before the limit has been reached. type spanReader struct { r io.Reader n int64 } func (l *spanReader) Read(p []byte) (n int, err error) { if l.n <= 0 { return 0, io.EOF } if int64(len(p)) > l.n { p = p[0:l.n] } n, err = l.r.Read(p) l.n -= int64(n) if l.n > 0 && err == io.EOF { err = io.ErrUnexpectedEOF } return } // readHeader parses a packet header and returns an io.Reader which will return // the contents of the packet. See RFC 4880, section 4.2. func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) { var buf [4]byte _, err = io.ReadFull(r, buf[:1]) if err != nil { return } if buf[0]&0x80 == 0 { err = errors.StructuralError("tag byte does not have MSB set") return } if buf[0]&0x40 == 0 { // Old format packet tag = packetType((buf[0] & 0x3f) >> 2) lengthType := buf[0] & 3 if lengthType == 3 { length = -1 contents = r return } lengthBytes := 1 << lengthType _, err = readFull(r, buf[0:lengthBytes]) if err != nil { return } for i := 0; i < lengthBytes; i++ { length <<= 8 length |= int64(buf[i]) } contents = &spanReader{r, length} return } // New format packet tag = packetType(buf[0] & 0x3f) length, isPartial, err := readLength(r) if err != nil { return } if isPartial { contents = &partialLengthReader{ remaining: length, isPartial: true, r: r, } length = -1 } else { contents = &spanReader{r, length} } return } // serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section // 4.2. func serializeHeader(w io.Writer, ptype packetType, length int) (err error) { var buf [6]byte var n int buf[0] = 0x80 | 0x40 | byte(ptype) if length < 192 { buf[1] = byte(length) n = 2 } else if length < 8384 { length -= 192 buf[1] = 192 + byte(length>>8) buf[2] = byte(length) n = 3 } else { buf[1] = 255 buf[2] = byte(length >> 24) buf[3] = byte(length >> 16) buf[4] = byte(length >> 8) buf[5] = byte(length) n = 6 } _, err = w.Write(buf[:n]) return } // serializeStreamHeader writes an OpenPGP packet header to w where the // length of the packet is unknown. It returns a io.WriteCloser which can be // used to write the contents of the packet. See RFC 4880, section 4.2. func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) { var buf [1]byte buf[0] = 0x80 | 0x40 | byte(ptype) _, err = w.Write(buf[:]) if err != nil { return } out = &partialLengthWriter{w: w} return } // Packet represents an OpenPGP packet. Users are expected to try casting // instances of this interface to specific packet types. type Packet interface { parse(io.Reader) error } // consumeAll reads from the given Reader until error, returning the number of // bytes read. func consumeAll(r io.Reader) (n int64, err error) { var m int var buf [1024]byte for { m, err = r.Read(buf[:]) n += int64(m) if err == io.EOF { err = nil return } if err != nil { return } } } // packetType represents the numeric ids of the different OpenPGP packet types. See // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-2 type packetType uint8 const ( packetTypeEncryptedKey packetType = 1 packetTypeSignature packetType = 2 packetTypeSymmetricKeyEncrypted packetType = 3 packetTypeOnePassSignature packetType = 4 packetTypePrivateKey packetType = 5 packetTypePublicKey packetType = 6 packetTypePrivateSubkey packetType = 7 packetTypeCompressed packetType = 8 packetTypeSymmetricallyEncrypted packetType = 9 packetTypeLiteralData packetType = 11 packetTypeUserId packetType = 13 packetTypePublicSubkey packetType = 14 packetTypeUserAttribute packetType = 17 packetTypeSymmetricallyEncryptedMDC packetType = 18 ) // peekVersion detects the version of a public key packet about to // be read. A bufio.Reader at the original position of the io.Reader // is returned. func peekVersion(r io.Reader) (bufr *bufio.Reader, ver byte, err error) { bufr = bufio.NewReader(r) var verBuf []byte if verBuf, err = bufr.Peek(1); err != nil { return } ver = verBuf[0] return } // Read reads a single OpenPGP packet from the given io.Reader. If there is an // error parsing a packet, the whole packet is consumed from the input. func Read(r io.Reader) (p Packet, err error) { tag, _, contents, err := readHeader(r) if err != nil { return } switch tag { case packetTypeEncryptedKey: p = new(EncryptedKey) case packetTypeSignature: var version byte // Detect signature version if contents, version, err = peekVersion(contents); err != nil { return } if version < 4 { p = new(SignatureV3) } else { p = new(Signature) } case packetTypeSymmetricKeyEncrypted: p = new(SymmetricKeyEncrypted) case packetTypeOnePassSignature: p = new(OnePassSignature) case packetTypePrivateKey, packetTypePrivateSubkey: pk := new(PrivateKey) if tag == packetTypePrivateSubkey { pk.IsSubkey = true } p = pk case packetTypePublicKey, packetTypePublicSubkey: var version byte if contents, version, err = peekVersion(contents); err != nil { return } isSubkey := tag == packetTypePublicSubkey if version < 4 { p = &PublicKeyV3{IsSubkey: isSubkey} } else { p = &PublicKey{IsSubkey: isSubkey} } case packetTypeCompressed: p = new(Compressed) case packetTypeSymmetricallyEncrypted: p = new(SymmetricallyEncrypted) case packetTypeLiteralData: p = new(LiteralData) case packetTypeUserId: p = new(UserId) case packetTypeUserAttribute: p = new(UserAttribute) case packetTypeSymmetricallyEncryptedMDC: se := new(SymmetricallyEncrypted) se.MDC = true p = se default: err = errors.UnknownPacketTypeError(tag) } if p != nil { err = p.parse(contents) } if err != nil { consumeAll(contents) } return } // SignatureType represents the different semantic meanings of an OpenPGP // signature. See RFC 4880, section 5.2.1. type SignatureType uint8 const ( SigTypeBinary SignatureType = 0 SigTypeText = 1 SigTypeGenericCert = 0x10 SigTypePersonaCert = 0x11 SigTypeCasualCert = 0x12 SigTypePositiveCert = 0x13 SigTypeSubkeyBinding = 0x18 SigTypePrimaryKeyBinding = 0x19 SigTypeDirectSignature = 0x1F SigTypeKeyRevocation = 0x20 SigTypeSubkeyRevocation = 0x28 ) // PublicKeyAlgorithm represents the different public key system specified for // OpenPGP. See // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-12 type PublicKeyAlgorithm uint8 const ( PubKeyAlgoRSA PublicKeyAlgorithm = 1 PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2 PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3 PubKeyAlgoElGamal PublicKeyAlgorithm = 16 PubKeyAlgoDSA PublicKeyAlgorithm = 17 // RFC 6637, Section 5. PubKeyAlgoECDH PublicKeyAlgorithm = 18 PubKeyAlgoECDSA PublicKeyAlgorithm = 19 ) // CanEncrypt returns true if it's possible to encrypt a message to a public // key of the given type. func (pka PublicKeyAlgorithm) CanEncrypt() bool { switch pka { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal: return true } return false } // CanSign returns true if it's possible for a public key of the given type to // sign a message. func (pka PublicKeyAlgorithm) CanSign() bool { switch pka { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA: return true } return false } // CipherFunction represents the different block ciphers specified for OpenPGP. See // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13 type CipherFunction uint8 const ( Cipher3DES CipherFunction = 2 CipherCAST5 CipherFunction = 3 CipherAES128 CipherFunction = 7 CipherAES192 CipherFunction = 8 CipherAES256 CipherFunction = 9 ) // KeySize returns the key size, in bytes, of cipher. func (cipher CipherFunction) KeySize() int { switch cipher { case Cipher3DES: return 24 case CipherCAST5: return cast5.KeySize case CipherAES128: return 16 case CipherAES192: return 24 case CipherAES256: return 32 } return 0 } // blockSize returns the block size, in bytes, of cipher. func (cipher CipherFunction) blockSize() int { switch cipher { case Cipher3DES: return des.BlockSize case CipherCAST5: return 8 case CipherAES128, CipherAES192, CipherAES256: return 16 } return 0 } // new returns a fresh instance of the given cipher. func (cipher CipherFunction) new(key []byte) (block cipher.Block) { switch cipher { case Cipher3DES: block, _ = des.NewTripleDESCipher(key) case CipherCAST5: block, _ = cast5.NewCipher(key) case CipherAES128, CipherAES192, CipherAES256: block, _ = aes.NewCipher(key) } return } // readMPI reads a big integer from r. The bit length returned is the bit // length that was specified in r. This is preserved so that the integer can be // reserialized exactly. func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) { var buf [2]byte _, err = readFull(r, buf[0:]) if err != nil { return } bitLength = uint16(buf[0])<<8 | uint16(buf[1]) numBytes := (int(bitLength) + 7) / 8 mpi = make([]byte, numBytes) _, err = readFull(r, mpi) return } // mpiLength returns the length of the given *big.Int when serialized as an // MPI. func mpiLength(n *big.Int) (mpiLengthInBytes int) { mpiLengthInBytes = 2 /* MPI length */ mpiLengthInBytes += (n.BitLen() + 7) / 8 return } // writeMPI serializes a big integer to w. func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) { _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)}) if err == nil { _, err = w.Write(mpiBytes) } return } // writeBig serializes a *big.Int to w. func writeBig(w io.Writer, i *big.Int) error { return writeMPI(w, uint16(i.BitLen()), i.Bytes()) } // CompressionAlgo Represents the different compression algorithms // supported by OpenPGP (except for BZIP2, which is not currently // supported). See Section 9.3 of RFC 4880. type CompressionAlgo uint8 const ( CompressionNone CompressionAlgo = 0 CompressionZIP CompressionAlgo = 1 CompressionZLIB CompressionAlgo = 2 ) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/opaque_test.go�������������������������������0000644�0610621�0607500�00000004705�13172163317�026657� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/hex" "io" "testing" ) // Test packet.Read error handling in OpaquePacket.Parse, // which attempts to re-read an OpaquePacket as a supported // Packet type. func TestOpaqueParseReason(t *testing.T) { buf, err := hex.DecodeString(UnsupportedKeyHex) if err != nil { t.Fatal(err) } or := NewOpaqueReader(bytes.NewBuffer(buf)) count := 0 badPackets := 0 var uid *UserId for { op, err := or.Next() if err == io.EOF { break } else if err != nil { t.Errorf("#%d: opaque read error: %v", count, err) break } // try to parse opaque packet p, err := op.Parse() switch pkt := p.(type) { case *UserId: uid = pkt case *OpaquePacket: // If an OpaquePacket can't re-parse, packet.Read // certainly had its reasons. if pkt.Reason == nil { t.Errorf("#%d: opaque packet, no reason", count) } else { badPackets++ } } count++ } const expectedBad = 3 // Test post-conditions, make sure we actually parsed packets as expected. if badPackets != expectedBad { t.Errorf("unexpected # unparseable packets: %d (want %d)", badPackets, expectedBad) } if uid == nil { t.Errorf("failed to find expected UID in unsupported keyring") } else if uid.Id != "Armin M. Warda <warda@nephilim.ruhr.de>" { t.Errorf("unexpected UID: %v", uid.Id) } } // This key material has public key and signature packet versions modified to // an unsupported value (1), so that trying to parse the OpaquePacket to // a typed packet will get an error. It also contains a GnuPG trust packet. // (Created with: od -An -t x1 pubring.gpg | xargs | sed 's/ //g') const UnsupportedKeyHex = `988d012e7a18a20000010400d6ac00d92b89c1f4396c243abb9b76d2e9673ad63483291fed88e22b82e255e441c078c6abbbf7d2d195e50b62eeaa915b85b0ec20c225ce2c64c167cacb6e711daf2e45da4a8356a059b8160e3b3628ac0dd8437b31f06d53d6e8ea4214d4a26406a6b63e1001406ef23e0bb3069fac9a99a91f77dfafd5de0f188a5da5e3c9000511b42741726d696e204d2e205761726461203c7761726461406e657068696c696d2e727568722e64653e8900950105102e8936c705d1eb399e58489901013f0e03ff5a0c4f421e34fcfa388129166420c08cd76987bcdec6f01bd0271459a85cc22048820dd4e44ac2c7d23908d540f54facf1b36b0d9c20488781ce9dca856531e76e2e846826e9951338020a03a09b57aa5faa82e9267458bd76105399885ac35af7dc1cbb6aaed7c39e1039f3b5beda2c0e916bd38560509bab81235d1a0ead83b0020000` �����������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/opaque.go������������������������������������0000644�0610621�0607500�00000010016�13172163317�025610� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "io" "io/ioutil" "golang.org/x/crypto/openpgp/errors" ) // OpaquePacket represents an OpenPGP packet as raw, unparsed data. This is // useful for splitting and storing the original packet contents separately, // handling unsupported packet types or accessing parts of the packet not yet // implemented by this package. type OpaquePacket struct { // Packet type Tag uint8 // Reason why the packet was parsed opaquely Reason error // Binary contents of the packet data Contents []byte } func (op *OpaquePacket) parse(r io.Reader) (err error) { op.Contents, err = ioutil.ReadAll(r) return } // Serialize marshals the packet to a writer in its original form, including // the packet header. func (op *OpaquePacket) Serialize(w io.Writer) (err error) { err = serializeHeader(w, packetType(op.Tag), len(op.Contents)) if err == nil { _, err = w.Write(op.Contents) } return } // Parse attempts to parse the opaque contents into a structure supported by // this package. If the packet is not known then the result will be another // OpaquePacket. func (op *OpaquePacket) Parse() (p Packet, err error) { hdr := bytes.NewBuffer(nil) err = serializeHeader(hdr, packetType(op.Tag), len(op.Contents)) if err != nil { op.Reason = err return op, err } p, err = Read(io.MultiReader(hdr, bytes.NewBuffer(op.Contents))) if err != nil { op.Reason = err p = op } return } // OpaqueReader reads OpaquePackets from an io.Reader. type OpaqueReader struct { r io.Reader } func NewOpaqueReader(r io.Reader) *OpaqueReader { return &OpaqueReader{r: r} } // Read the next OpaquePacket. func (or *OpaqueReader) Next() (op *OpaquePacket, err error) { tag, _, contents, err := readHeader(or.r) if err != nil { return } op = &OpaquePacket{Tag: uint8(tag), Reason: err} err = op.parse(contents) if err != nil { consumeAll(contents) } return } // OpaqueSubpacket represents an unparsed OpenPGP subpacket, // as found in signature and user attribute packets. type OpaqueSubpacket struct { SubType uint8 Contents []byte } // OpaqueSubpackets extracts opaque, unparsed OpenPGP subpackets from // their byte representation. func OpaqueSubpackets(contents []byte) (result []*OpaqueSubpacket, err error) { var ( subHeaderLen int subPacket *OpaqueSubpacket ) for len(contents) > 0 { subHeaderLen, subPacket, err = nextSubpacket(contents) if err != nil { break } result = append(result, subPacket) contents = contents[subHeaderLen+len(subPacket.Contents):] } return } func nextSubpacket(contents []byte) (subHeaderLen int, subPacket *OpaqueSubpacket, err error) { // RFC 4880, section 5.2.3.1 var subLen uint32 if len(contents) < 1 { goto Truncated } subPacket = &OpaqueSubpacket{} switch { case contents[0] < 192: subHeaderLen = 2 // 1 length byte, 1 subtype byte if len(contents) < subHeaderLen { goto Truncated } subLen = uint32(contents[0]) contents = contents[1:] case contents[0] < 255: subHeaderLen = 3 // 2 length bytes, 1 subtype if len(contents) < subHeaderLen { goto Truncated } subLen = uint32(contents[0]-192)<<8 + uint32(contents[1]) + 192 contents = contents[2:] default: subHeaderLen = 6 // 5 length bytes, 1 subtype if len(contents) < subHeaderLen { goto Truncated } subLen = uint32(contents[1])<<24 | uint32(contents[2])<<16 | uint32(contents[3])<<8 | uint32(contents[4]) contents = contents[5:] } if subLen > uint32(len(contents)) || subLen == 0 { goto Truncated } subPacket.SubType = contents[0] subPacket.Contents = contents[1:subLen] return Truncated: err = errors.StructuralError("subpacket truncated") return } func (osp *OpaqueSubpacket) Serialize(w io.Writer) (err error) { buf := make([]byte, 6) n := serializeSubpacketLength(buf, len(osp.Contents)+1) buf[n] = osp.SubType if _, err = w.Write(buf[:n+1]); err != nil { return } _, err = w.Write(osp.Contents) return } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/one_pass_signature.go������������������������0000644�0610621�0607500�00000003362�13172163317�030214� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "crypto" "encoding/binary" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/s2k" "io" "strconv" ) // OnePassSignature represents a one-pass signature packet. See RFC 4880, // section 5.4. type OnePassSignature struct { SigType SignatureType Hash crypto.Hash PubKeyAlgo PublicKeyAlgorithm KeyId uint64 IsLast bool } const onePassSignatureVersion = 3 func (ops *OnePassSignature) parse(r io.Reader) (err error) { var buf [13]byte _, err = readFull(r, buf[:]) if err != nil { return } if buf[0] != onePassSignatureVersion { err = errors.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0]))) } var ok bool ops.Hash, ok = s2k.HashIdToHash(buf[2]) if !ok { return errors.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2]))) } ops.SigType = SignatureType(buf[1]) ops.PubKeyAlgo = PublicKeyAlgorithm(buf[3]) ops.KeyId = binary.BigEndian.Uint64(buf[4:12]) ops.IsLast = buf[12] != 0 return } // Serialize marshals the given OnePassSignature to w. func (ops *OnePassSignature) Serialize(w io.Writer) error { var buf [13]byte buf[0] = onePassSignatureVersion buf[1] = uint8(ops.SigType) var ok bool buf[2], ok = s2k.HashToHashId(ops.Hash) if !ok { return errors.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash))) } buf[3] = uint8(ops.PubKeyAlgo) binary.BigEndian.PutUint64(buf[4:12], ops.KeyId) if ops.IsLast { buf[12] = 1 } if err := serializeHeader(w, packetTypeOnePassSignature, len(buf)); err != nil { return err } _, err := w.Write(buf[:]) return err } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/ocfb_test.go���������������������������������0000644�0610621�0607500�00000002365�13172163317�026276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto/aes" "crypto/rand" "testing" ) var commonKey128 = []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c} func testOCFB(t *testing.T, resync OCFBResyncOption) { block, err := aes.NewCipher(commonKey128) if err != nil { t.Error(err) return } plaintext := []byte("this is the plaintext, which is long enough to span several blocks.") randData := make([]byte, block.BlockSize()) rand.Reader.Read(randData) ocfb, prefix := NewOCFBEncrypter(block, randData, resync) ciphertext := make([]byte, len(plaintext)) ocfb.XORKeyStream(ciphertext, plaintext) ocfbdec := NewOCFBDecrypter(block, prefix, resync) if ocfbdec == nil { t.Errorf("NewOCFBDecrypter failed (resync: %t)", resync) return } plaintextCopy := make([]byte, len(plaintext)) ocfbdec.XORKeyStream(plaintextCopy, ciphertext) if !bytes.Equal(plaintextCopy, plaintext) { t.Errorf("got: %x, want: %x (resync: %t)", plaintextCopy, plaintext, resync) } } func TestOCFB(t *testing.T) { testOCFB(t, OCFBNoResync) testOCFB(t, OCFBResync) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/ocfb.go��������������������������������������0000644�0610621�0607500�00000007173�13172163317�025241� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // OpenPGP CFB Mode. http://tools.ietf.org/html/rfc4880#section-13.9 package packet import ( "crypto/cipher" ) type ocfbEncrypter struct { b cipher.Block fre []byte outUsed int } // An OCFBResyncOption determines if the "resynchronization step" of OCFB is // performed. type OCFBResyncOption bool const ( OCFBResync OCFBResyncOption = true OCFBNoResync OCFBResyncOption = false ) // NewOCFBEncrypter returns a cipher.Stream which encrypts data with OpenPGP's // cipher feedback mode using the given cipher.Block, and an initial amount of // ciphertext. randData must be random bytes and be the same length as the // cipher.Block's block size. Resync determines if the "resynchronization step" // from RFC 4880, 13.9 step 7 is performed. Different parts of OpenPGP vary on // this point. func NewOCFBEncrypter(block cipher.Block, randData []byte, resync OCFBResyncOption) (cipher.Stream, []byte) { blockSize := block.BlockSize() if len(randData) != blockSize { return nil, nil } x := &ocfbEncrypter{ b: block, fre: make([]byte, blockSize), outUsed: 0, } prefix := make([]byte, blockSize+2) block.Encrypt(x.fre, x.fre) for i := 0; i < blockSize; i++ { prefix[i] = randData[i] ^ x.fre[i] } block.Encrypt(x.fre, prefix[:blockSize]) prefix[blockSize] = x.fre[0] ^ randData[blockSize-2] prefix[blockSize+1] = x.fre[1] ^ randData[blockSize-1] if resync { block.Encrypt(x.fre, prefix[2:]) } else { x.fre[0] = prefix[blockSize] x.fre[1] = prefix[blockSize+1] x.outUsed = 2 } return x, prefix } func (x *ocfbEncrypter) XORKeyStream(dst, src []byte) { for i := 0; i < len(src); i++ { if x.outUsed == len(x.fre) { x.b.Encrypt(x.fre, x.fre) x.outUsed = 0 } x.fre[x.outUsed] ^= src[i] dst[i] = x.fre[x.outUsed] x.outUsed++ } } type ocfbDecrypter struct { b cipher.Block fre []byte outUsed int } // NewOCFBDecrypter returns a cipher.Stream which decrypts data with OpenPGP's // cipher feedback mode using the given cipher.Block. Prefix must be the first // blockSize + 2 bytes of the ciphertext, where blockSize is the cipher.Block's // block size. If an incorrect key is detected then nil is returned. On // successful exit, blockSize+2 bytes of decrypted data are written into // prefix. Resync determines if the "resynchronization step" from RFC 4880, // 13.9 step 7 is performed. Different parts of OpenPGP vary on this point. func NewOCFBDecrypter(block cipher.Block, prefix []byte, resync OCFBResyncOption) cipher.Stream { blockSize := block.BlockSize() if len(prefix) != blockSize+2 { return nil } x := &ocfbDecrypter{ b: block, fre: make([]byte, blockSize), outUsed: 0, } prefixCopy := make([]byte, len(prefix)) copy(prefixCopy, prefix) block.Encrypt(x.fre, x.fre) for i := 0; i < blockSize; i++ { prefixCopy[i] ^= x.fre[i] } block.Encrypt(x.fre, prefix[:blockSize]) prefixCopy[blockSize] ^= x.fre[0] prefixCopy[blockSize+1] ^= x.fre[1] if prefixCopy[blockSize-2] != prefixCopy[blockSize] || prefixCopy[blockSize-1] != prefixCopy[blockSize+1] { return nil } if resync { block.Encrypt(x.fre, prefix[2:]) } else { x.fre[0] = prefix[blockSize] x.fre[1] = prefix[blockSize+1] x.outUsed = 2 } copy(prefix, prefixCopy) return x } func (x *ocfbDecrypter) XORKeyStream(dst, src []byte) { for i := 0; i < len(src); i++ { if x.outUsed == len(x.fre) { x.b.Encrypt(x.fre, x.fre) x.outUsed = 0 } c := src[i] dst[i] = x.fre[x.outUsed] ^ src[i] x.fre[x.outUsed] = c x.outUsed++ } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/literal.go�����������������������������������0000644�0610621�0607500�00000003604�13172163317�025757� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "encoding/binary" "io" ) // LiteralData represents an encrypted file. See RFC 4880, section 5.9. type LiteralData struct { IsBinary bool FileName string Time uint32 // Unix epoch time. Either creation time or modification time. 0 means undefined. Body io.Reader } // ForEyesOnly returns whether the contents of the LiteralData have been marked // as especially sensitive. func (l *LiteralData) ForEyesOnly() bool { return l.FileName == "_CONSOLE" } func (l *LiteralData) parse(r io.Reader) (err error) { var buf [256]byte _, err = readFull(r, buf[:2]) if err != nil { return } l.IsBinary = buf[0] == 'b' fileNameLen := int(buf[1]) _, err = readFull(r, buf[:fileNameLen]) if err != nil { return } l.FileName = string(buf[:fileNameLen]) _, err = readFull(r, buf[:4]) if err != nil { return } l.Time = binary.BigEndian.Uint32(buf[:4]) l.Body = r return } // SerializeLiteral serializes a literal data packet to w and returns a // WriteCloser to which the data itself can be written and which MUST be closed // on completion. The fileName is truncated to 255 bytes. func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err error) { var buf [4]byte buf[0] = 't' if isBinary { buf[0] = 'b' } if len(fileName) > 255 { fileName = fileName[:255] } buf[1] = byte(len(fileName)) inner, err := serializeStreamHeader(w, packetTypeLiteralData) if err != nil { return } _, err = inner.Write(buf[:2]) if err != nil { return } _, err = inner.Write([]byte(fileName)) if err != nil { return } binary.BigEndian.PutUint32(buf[:], time) _, err = inner.Write(buf[:]) if err != nil { return } plaintext = inner return } ����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/encrypted_key_test.go������������������������0000644�0610621�0607500�00000010465�13172163317�030232� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "crypto/rsa" "encoding/hex" "fmt" "math/big" "testing" ) func bigFromBase10(s string) *big.Int { b, ok := new(big.Int).SetString(s, 10) if !ok { panic("bigFromBase10 failed") } return b } var encryptedKeyPub = rsa.PublicKey{ E: 65537, N: bigFromBase10("115804063926007623305902631768113868327816898845124614648849934718568541074358183759250136204762053879858102352159854352727097033322663029387610959884180306668628526686121021235757016368038585212410610742029286439607686208110250133174279811431933746643015923132833417396844716207301518956640020862630546868823"), } var encryptedKeyRSAPriv = &rsa.PrivateKey{ PublicKey: encryptedKeyPub, D: bigFromBase10("32355588668219869544751561565313228297765464314098552250409557267371233892496951383426602439009993875125222579159850054973310859166139474359774543943714622292329487391199285040721944491839695981199720170366763547754915493640685849961780092241140181198779299712578774460837139360803883139311171713302987058393"), } var encryptedKeyPriv = &PrivateKey{ PublicKey: PublicKey{ PubKeyAlgo: PubKeyAlgoRSA, }, PrivateKey: encryptedKeyRSAPriv, } func TestDecryptingEncryptedKey(t *testing.T) { const encryptedKeyHex = "c18c032a67d68660df41c70104005789d0de26b6a50c985a02a13131ca829c413a35d0e6fa8d6842599252162808ac7439c72151c8c6183e76923fe3299301414d0c25a2f06a2257db3839e7df0ec964773f6e4c4ac7ff3b48c444237166dd46ba8ff443a5410dc670cb486672fdbe7c9dfafb75b4fea83af3a204fe2a7dfa86bd20122b4f3d2646cbeecb8f7be8" const expectedKeyHex = "d930363f7e0308c333b9618617ea728963d8df993665ae7be1092d4926fd864b" p, err := Read(readerFromHex(encryptedKeyHex)) if err != nil { t.Errorf("error from Read: %s", err) return } ek, ok := p.(*EncryptedKey) if !ok { t.Errorf("didn't parse an EncryptedKey, got %#v", p) return } if ek.KeyId != 0x2a67d68660df41c7 || ek.Algo != PubKeyAlgoRSA { t.Errorf("unexpected EncryptedKey contents: %#v", ek) return } err = ek.Decrypt(encryptedKeyPriv, nil) if err != nil { t.Errorf("error from Decrypt: %s", err) return } if ek.CipherFunc != CipherAES256 { t.Errorf("unexpected EncryptedKey contents: %#v", ek) return } keyHex := fmt.Sprintf("%x", ek.Key) if keyHex != expectedKeyHex { t.Errorf("bad key, got %s want %x", keyHex, expectedKeyHex) } } func TestEncryptingEncryptedKey(t *testing.T) { key := []byte{1, 2, 3, 4} const expectedKeyHex = "01020304" const keyId = 42 pub := &PublicKey{ PublicKey: &encryptedKeyPub, KeyId: keyId, PubKeyAlgo: PubKeyAlgoRSAEncryptOnly, } buf := new(bytes.Buffer) err := SerializeEncryptedKey(buf, pub, CipherAES128, key, nil) if err != nil { t.Errorf("error writing encrypted key packet: %s", err) } p, err := Read(buf) if err != nil { t.Errorf("error from Read: %s", err) return } ek, ok := p.(*EncryptedKey) if !ok { t.Errorf("didn't parse an EncryptedKey, got %#v", p) return } if ek.KeyId != keyId || ek.Algo != PubKeyAlgoRSAEncryptOnly { t.Errorf("unexpected EncryptedKey contents: %#v", ek) return } err = ek.Decrypt(encryptedKeyPriv, nil) if err != nil { t.Errorf("error from Decrypt: %s", err) return } if ek.CipherFunc != CipherAES128 { t.Errorf("unexpected EncryptedKey contents: %#v", ek) return } keyHex := fmt.Sprintf("%x", ek.Key) if keyHex != expectedKeyHex { t.Errorf("bad key, got %s want %x", keyHex, expectedKeyHex) } } func TestSerializingEncryptedKey(t *testing.T) { const encryptedKeyHex = "c18c032a67d68660df41c70104005789d0de26b6a50c985a02a13131ca829c413a35d0e6fa8d6842599252162808ac7439c72151c8c6183e76923fe3299301414d0c25a2f06a2257db3839e7df0ec964773f6e4c4ac7ff3b48c444237166dd46ba8ff443a5410dc670cb486672fdbe7c9dfafb75b4fea83af3a204fe2a7dfa86bd20122b4f3d2646cbeecb8f7be8" p, err := Read(readerFromHex(encryptedKeyHex)) if err != nil { t.Fatalf("error from Read: %s", err) } ek, ok := p.(*EncryptedKey) if !ok { t.Fatalf("didn't parse an EncryptedKey, got %#v", p) } var buf bytes.Buffer ek.Serialize(&buf) if bufHex := hex.EncodeToString(buf.Bytes()); bufHex != encryptedKeyHex { t.Fatalf("serialization of encrypted key differed from original. Original was %s, but reserialized as %s", encryptedKeyHex, bufHex) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/encrypted_key.go�����������������������������0000644�0610621�0607500�00000014042�13172163317�027166� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "crypto/rsa" "encoding/binary" "io" "math/big" "strconv" "golang.org/x/crypto/openpgp/elgamal" "golang.org/x/crypto/openpgp/errors" ) const encryptedKeyVersion = 3 // EncryptedKey represents a public-key encrypted session key. See RFC 4880, // section 5.1. type EncryptedKey struct { KeyId uint64 Algo PublicKeyAlgorithm CipherFunc CipherFunction // only valid after a successful Decrypt Key []byte // only valid after a successful Decrypt encryptedMPI1, encryptedMPI2 parsedMPI } func (e *EncryptedKey) parse(r io.Reader) (err error) { var buf [10]byte _, err = readFull(r, buf[:]) if err != nil { return } if buf[0] != encryptedKeyVersion { return errors.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0]))) } e.KeyId = binary.BigEndian.Uint64(buf[1:9]) e.Algo = PublicKeyAlgorithm(buf[9]) switch e.Algo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) case PubKeyAlgoElGamal: e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) if err != nil { return } e.encryptedMPI2.bytes, e.encryptedMPI2.bitLength, err = readMPI(r) } _, err = consumeAll(r) return } func checksumKeyMaterial(key []byte) uint16 { var checksum uint16 for _, v := range key { checksum += uint16(v) } return checksum } // Decrypt decrypts an encrypted session key with the given private key. The // private key must have been decrypted first. // If config is nil, sensible defaults will be used. func (e *EncryptedKey) Decrypt(priv *PrivateKey, config *Config) error { var err error var b []byte // TODO(agl): use session key decryption routines here to avoid // padding oracle attacks. switch priv.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: b, err = rsa.DecryptPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), e.encryptedMPI1.bytes) case PubKeyAlgoElGamal: c1 := new(big.Int).SetBytes(e.encryptedMPI1.bytes) c2 := new(big.Int).SetBytes(e.encryptedMPI2.bytes) b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2) default: err = errors.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo))) } if err != nil { return err } e.CipherFunc = CipherFunction(b[0]) e.Key = b[1 : len(b)-2] expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1]) checksum := checksumKeyMaterial(e.Key) if checksum != expectedChecksum { return errors.StructuralError("EncryptedKey checksum incorrect") } return nil } // Serialize writes the encrypted key packet, e, to w. func (e *EncryptedKey) Serialize(w io.Writer) error { var mpiLen int switch e.Algo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: mpiLen = 2 + len(e.encryptedMPI1.bytes) case PubKeyAlgoElGamal: mpiLen = 2 + len(e.encryptedMPI1.bytes) + 2 + len(e.encryptedMPI2.bytes) default: return errors.InvalidArgumentError("don't know how to serialize encrypted key type " + strconv.Itoa(int(e.Algo))) } serializeHeader(w, packetTypeEncryptedKey, 1 /* version */ +8 /* key id */ +1 /* algo */ +mpiLen) w.Write([]byte{encryptedKeyVersion}) binary.Write(w, binary.BigEndian, e.KeyId) w.Write([]byte{byte(e.Algo)}) switch e.Algo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: writeMPIs(w, e.encryptedMPI1) case PubKeyAlgoElGamal: writeMPIs(w, e.encryptedMPI1, e.encryptedMPI2) default: panic("internal error") } return nil } // SerializeEncryptedKey serializes an encrypted key packet to w that contains // key, encrypted to pub. // If config is nil, sensible defaults will be used. func SerializeEncryptedKey(w io.Writer, pub *PublicKey, cipherFunc CipherFunction, key []byte, config *Config) error { var buf [10]byte buf[0] = encryptedKeyVersion binary.BigEndian.PutUint64(buf[1:9], pub.KeyId) buf[9] = byte(pub.PubKeyAlgo) keyBlock := make([]byte, 1 /* cipher type */ +len(key)+2 /* checksum */) keyBlock[0] = byte(cipherFunc) copy(keyBlock[1:], key) checksum := checksumKeyMaterial(key) keyBlock[1+len(key)] = byte(checksum >> 8) keyBlock[1+len(key)+1] = byte(checksum) switch pub.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: return serializeEncryptedKeyRSA(w, config.Random(), buf, pub.PublicKey.(*rsa.PublicKey), keyBlock) case PubKeyAlgoElGamal: return serializeEncryptedKeyElGamal(w, config.Random(), buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock) case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly: return errors.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) } return errors.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) } func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error { cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock) if err != nil { return errors.InvalidArgumentError("RSA encryption failed: " + err.Error()) } packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText) err = serializeHeader(w, packetTypeEncryptedKey, packetLen) if err != nil { return err } _, err = w.Write(header[:]) if err != nil { return err } return writeMPI(w, 8*uint16(len(cipherText)), cipherText) } func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error { c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock) if err != nil { return errors.InvalidArgumentError("ElGamal encryption failed: " + err.Error()) } packetLen := 10 /* header length */ packetLen += 2 /* mpi size */ + (c1.BitLen()+7)/8 packetLen += 2 /* mpi size */ + (c2.BitLen()+7)/8 err = serializeHeader(w, packetTypeEncryptedKey, packetLen) if err != nil { return err } _, err = w.Write(header[:]) if err != nil { return err } err = writeBig(w, c1) if err != nil { return err } return writeBig(w, c2) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/config.go������������������������������������0000644�0610621�0607500�00000005011�13172163317�025562� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "crypto" "crypto/rand" "io" "time" ) // Config collects a number of parameters along with sensible defaults. // A nil *Config is valid and results in all default values. type Config struct { // Rand provides the source of entropy. // If nil, the crypto/rand Reader is used. Rand io.Reader // DefaultHash is the default hash function to be used. // If zero, SHA-256 is used. DefaultHash crypto.Hash // DefaultCipher is the cipher to be used. // If zero, AES-128 is used. DefaultCipher CipherFunction // Time returns the current time as the number of seconds since the // epoch. If Time is nil, time.Now is used. Time func() time.Time // DefaultCompressionAlgo is the compression algorithm to be // applied to the plaintext before encryption. If zero, no // compression is done. DefaultCompressionAlgo CompressionAlgo // CompressionConfig configures the compression settings. CompressionConfig *CompressionConfig // S2KCount is only used for symmetric encryption. It // determines the strength of the passphrase stretching when // the said passphrase is hashed to produce a key. S2KCount // should be between 1024 and 65011712, inclusive. If Config // is nil or S2KCount is 0, the value 65536 used. Not all // values in the above range can be represented. S2KCount will // be rounded up to the next representable value if it cannot // be encoded exactly. When set, it is strongly encrouraged to // use a value that is at least 65536. See RFC 4880 Section // 3.7.1.3. S2KCount int // RSABits is the number of bits in new RSA keys made with NewEntity. // If zero, then 2048 bit keys are created. RSABits int } func (c *Config) Random() io.Reader { if c == nil || c.Rand == nil { return rand.Reader } return c.Rand } func (c *Config) Hash() crypto.Hash { if c == nil || uint(c.DefaultHash) == 0 { return crypto.SHA256 } return c.DefaultHash } func (c *Config) Cipher() CipherFunction { if c == nil || uint8(c.DefaultCipher) == 0 { return CipherAES128 } return c.DefaultCipher } func (c *Config) Now() time.Time { if c == nil || c.Time == nil { return time.Now() } return c.Time() } func (c *Config) Compression() CompressionAlgo { if c == nil { return CompressionNone } return c.DefaultCompressionAlgo } func (c *Config) PasswordHashIterations() int { if c == nil || c.S2KCount == 0 { return 0 } return c.S2KCount } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/compressed_test.go���������������������������0000644�0610621�0607500�00000001601�13172163317�027521� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/hex" "io" "io/ioutil" "testing" ) func TestCompressed(t *testing.T) { packet, err := Read(readerFromHex(compressedHex)) if err != nil { t.Errorf("failed to read Compressed: %s", err) return } c, ok := packet.(*Compressed) if !ok { t.Error("didn't find Compressed packet") return } contents, err := ioutil.ReadAll(c.Body) if err != nil && err != io.EOF { t.Error(err) return } expected, _ := hex.DecodeString(compressedExpectedHex) if !bytes.Equal(expected, contents) { t.Errorf("got:%x want:%x", contents, expected) } } const compressedHex = "a3013b2d90c4e02b72e25f727e5e496a5e49b11e1700" const compressedExpectedHex = "cb1062004d14c8fe636f6e74656e74732e0a" �������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/packet/compressed.go��������������������������������0000644�0610621�0607500�00000006331�13172163317�026467� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "compress/bzip2" "compress/flate" "compress/zlib" "golang.org/x/crypto/openpgp/errors" "io" "strconv" ) // Compressed represents a compressed OpenPGP packet. The decompressed contents // will contain more OpenPGP packets. See RFC 4880, section 5.6. type Compressed struct { Body io.Reader } const ( NoCompression = flate.NoCompression BestSpeed = flate.BestSpeed BestCompression = flate.BestCompression DefaultCompression = flate.DefaultCompression ) // CompressionConfig contains compressor configuration settings. type CompressionConfig struct { // Level is the compression level to use. It must be set to // between -1 and 9, with -1 causing the compressor to use the // default compression level, 0 causing the compressor to use // no compression and 1 to 9 representing increasing (better, // slower) compression levels. If Level is less than -1 or // more then 9, a non-nil error will be returned during // encryption. See the constants above for convenient common // settings for Level. Level int } func (c *Compressed) parse(r io.Reader) error { var buf [1]byte _, err := readFull(r, buf[:]) if err != nil { return err } switch buf[0] { case 1: c.Body = flate.NewReader(r) case 2: c.Body, err = zlib.NewReader(r) case 3: c.Body = bzip2.NewReader(r) default: err = errors.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0]))) } return err } // compressedWriterCloser represents the serialized compression stream // header and the compressor. Its Close() method ensures that both the // compressor and serialized stream header are closed. Its Write() // method writes to the compressor. type compressedWriteCloser struct { sh io.Closer // Stream Header c io.WriteCloser // Compressor } func (cwc compressedWriteCloser) Write(p []byte) (int, error) { return cwc.c.Write(p) } func (cwc compressedWriteCloser) Close() (err error) { err = cwc.c.Close() if err != nil { return err } return cwc.sh.Close() } // SerializeCompressed serializes a compressed data packet to w and // returns a WriteCloser to which the literal data packets themselves // can be written and which MUST be closed on completion. If cc is // nil, sensible defaults will be used to configure the compression // algorithm. func SerializeCompressed(w io.WriteCloser, algo CompressionAlgo, cc *CompressionConfig) (literaldata io.WriteCloser, err error) { compressed, err := serializeStreamHeader(w, packetTypeCompressed) if err != nil { return } _, err = compressed.Write([]byte{uint8(algo)}) if err != nil { return } level := DefaultCompression if cc != nil { level = cc.Level } var compressor io.WriteCloser switch algo { case CompressionZIP: compressor, err = flate.NewWriter(compressed, level) case CompressionZLIB: compressor, err = zlib.NewWriterLevel(compressed, level) default: s := strconv.Itoa(int(algo)) err = errors.UnsupportedError("Unsupported compression algorithm: " + s) } if err != nil { return } literaldata = compressedWriteCloser{compressed, compressor} return } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/keys_test.go����������������������������������������0000644�0610621�0607500�00000070507�13172163317�025074� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package openpgp import ( "bytes" "crypto" "strings" "testing" "time" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/packet" ) func TestKeyExpiry(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(expiringKeyHex)) if err != nil { t.Fatal(err) } entity := kring[0] const timeFormat = "2006-01-02" time1, _ := time.Parse(timeFormat, "2013-07-01") // The expiringKeyHex key is structured as: // // pub 1024R/5E237D8C created: 2013-07-01 expires: 2013-07-31 usage: SC // sub 1024R/1ABB25A0 created: 2013-07-01 23:11:07 +0200 CEST expires: 2013-07-08 usage: E // sub 1024R/96A672F5 created: 2013-07-01 23:11:23 +0200 CEST expires: 2013-07-31 usage: E // // So this should select the newest, non-expired encryption key. key, _ := entity.encryptionKey(time1) if id := key.PublicKey.KeyIdShortString(); id != "96A672F5" { t.Errorf("Expected key 1ABB25A0 at time %s, but got key %s", time1.Format(timeFormat), id) } // Once the first encryption subkey has expired, the second should be // selected. time2, _ := time.Parse(timeFormat, "2013-07-09") key, _ = entity.encryptionKey(time2) if id := key.PublicKey.KeyIdShortString(); id != "96A672F5" { t.Errorf("Expected key 96A672F5 at time %s, but got key %s", time2.Format(timeFormat), id) } // Once all the keys have expired, nothing should be returned. time3, _ := time.Parse(timeFormat, "2013-08-01") if key, ok := entity.encryptionKey(time3); ok { t.Errorf("Expected no key at time %s, but got key %s", time3.Format(timeFormat), key.PublicKey.KeyIdShortString()) } } func TestMissingCrossSignature(t *testing.T) { // This public key has a signing subkey, but the subkey does not // contain a cross-signature. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(missingCrossSignatureKey)) if len(keys) != 0 { t.Errorf("Accepted key with missing cross signature") } if err == nil { t.Fatal("Failed to detect error in keyring with missing cross signature") } structural, ok := err.(errors.StructuralError) if !ok { t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err) } const expectedMsg = "signing subkey is missing cross-signature" if !strings.Contains(string(structural), expectedMsg) { t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg) } } func TestInvalidCrossSignature(t *testing.T) { // This public key has a signing subkey, and the subkey has an // embedded cross-signature. However, the cross-signature does // not correctly validate over the primary and subkey. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(invalidCrossSignatureKey)) if len(keys) != 0 { t.Errorf("Accepted key with invalid cross signature") } if err == nil { t.Fatal("Failed to detect error in keyring with an invalid cross signature") } structural, ok := err.(errors.StructuralError) if !ok { t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err) } const expectedMsg = "subkey signature invalid" if !strings.Contains(string(structural), expectedMsg) { t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg) } } func TestGoodCrossSignature(t *testing.T) { // This public key has a signing subkey, and the subkey has an // embedded cross-signature which correctly validates over the // primary and subkey. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(goodCrossSignatureKey)) if err != nil { t.Fatal(err) } if len(keys) != 1 { t.Errorf("Failed to accept key with good cross signature, %d", len(keys)) } if len(keys[0].Subkeys) != 1 { t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys)) } } // TestExternallyRevokableKey attempts to load and parse a key with a third party revocation permission. func TestExternallyRevocableKey(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex)) if err != nil { t.Fatal(err) } // The 0xA42704B92866382A key can be revoked by 0xBE3893CB843D0FE70C // according to this signature that appears within the key: // :signature packet: algo 1, keyid A42704B92866382A // version 4, created 1396409682, md5len 0, sigclass 0x1f // digest algo 2, begin of digest a9 84 // hashed subpkt 2 len 4 (sig created 2014-04-02) // hashed subpkt 12 len 22 (revocation key: c=80 a=1 f=CE094AA433F7040BB2DDF0BE3893CB843D0FE70C) // hashed subpkt 7 len 1 (not revocable) // subpkt 16 len 8 (issuer key ID A42704B92866382A) // data: [1024 bits] id := uint64(0xA42704B92866382A) keys := kring.KeysById(id) if len(keys) != 1 { t.Errorf("Expected to find key id %X, but got %d matches", id, len(keys)) } } func TestKeyRevocation(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(revokedKeyHex)) if err != nil { t.Fatal(err) } // revokedKeyHex contains these keys: // pub 1024R/9A34F7C0 2014-03-25 [revoked: 2014-03-25] // sub 1024R/1BA3CD60 2014-03-25 [revoked: 2014-03-25] ids := []uint64{0xA401D9F09A34F7C0, 0x5CD3BE0A1BA3CD60} for _, id := range ids { keys := kring.KeysById(id) if len(keys) != 1 { t.Errorf("Expected KeysById to find revoked key %X, but got %d matches", id, len(keys)) } keys = kring.KeysByIdUsage(id, 0) if len(keys) != 0 { t.Errorf("Expected KeysByIdUsage to filter out revoked key %X, but got %d matches", id, len(keys)) } } } func TestSubkeyRevocation(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(revokedSubkeyHex)) if err != nil { t.Fatal(err) } // revokedSubkeyHex contains these keys: // pub 1024R/4EF7E4BECCDE97F0 2014-03-25 // sub 1024R/D63636E2B96AE423 2014-03-25 // sub 1024D/DBCE4EE19529437F 2014-03-25 // sub 1024R/677815E371C2FD23 2014-03-25 [revoked: 2014-03-25] validKeys := []uint64{0x4EF7E4BECCDE97F0, 0xD63636E2B96AE423, 0xDBCE4EE19529437F} revokedKey := uint64(0x677815E371C2FD23) for _, id := range validKeys { keys := kring.KeysById(id) if len(keys) != 1 { t.Errorf("Expected KeysById to find key %X, but got %d matches", id, len(keys)) } keys = kring.KeysByIdUsage(id, 0) if len(keys) != 1 { t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", id, len(keys)) } } keys := kring.KeysById(revokedKey) if len(keys) != 1 { t.Errorf("Expected KeysById to find key %X, but got %d matches", revokedKey, len(keys)) } keys = kring.KeysByIdUsage(revokedKey, 0) if len(keys) != 0 { t.Errorf("Expected KeysByIdUsage to filter out revoked key %X, but got %d matches", revokedKey, len(keys)) } } func TestKeyUsage(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex)) if err != nil { t.Fatal(err) } // subkeyUsageHex contains these keys: // pub 1024R/2866382A created: 2014-04-01 expires: never usage: SC // sub 1024R/936C9153 created: 2014-04-01 expires: never usage: E // sub 1024R/64D5F5BB created: 2014-04-02 expires: never usage: E // sub 1024D/BC0BA992 created: 2014-04-02 expires: never usage: S certifiers := []uint64{0xA42704B92866382A} signers := []uint64{0xA42704B92866382A, 0x42CE2C64BC0BA992} encrypters := []uint64{0x09C0C7D9936C9153, 0xC104E98664D5F5BB} for _, id := range certifiers { keys := kring.KeysByIdUsage(id, packet.KeyFlagCertify) if len(keys) == 1 { if keys[0].PublicKey.KeyId != id { t.Errorf("Expected to find certifier key id %X, but got %X", id, keys[0].PublicKey.KeyId) } } else { t.Errorf("Expected one match for certifier key id %X, but got %d matches", id, len(keys)) } } for _, id := range signers { keys := kring.KeysByIdUsage(id, packet.KeyFlagSign) if len(keys) == 1 { if keys[0].PublicKey.KeyId != id { t.Errorf("Expected to find signing key id %X, but got %X", id, keys[0].PublicKey.KeyId) } } else { t.Errorf("Expected one match for signing key id %X, but got %d matches", id, len(keys)) } // This keyring contains no encryption keys that are also good for signing. keys = kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications) if len(keys) != 0 { t.Errorf("Unexpected match for encryption key id %X", id) } } for _, id := range encrypters { keys := kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications) if len(keys) == 1 { if keys[0].PublicKey.KeyId != id { t.Errorf("Expected to find encryption key id %X, but got %X", id, keys[0].PublicKey.KeyId) } } else { t.Errorf("Expected one match for encryption key id %X, but got %d matches", id, len(keys)) } // This keyring contains no encryption keys that are also good for signing. keys = kring.KeysByIdUsage(id, packet.KeyFlagSign) if len(keys) != 0 { t.Errorf("Unexpected match for signing key id %X", id) } } } func TestIdVerification(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) if err != nil { t.Fatal(err) } if err := kring[1].PrivateKey.Decrypt([]byte("passphrase")); err != nil { t.Fatal(err) } const identity = "Test Key 1 (RSA)" if err := kring[0].SignIdentity(identity, kring[1], nil); err != nil { t.Fatal(err) } ident, ok := kring[0].Identities[identity] if !ok { t.Fatal("identity missing from key after signing") } checked := false for _, sig := range ident.Signatures { if sig.IssuerKeyId == nil || *sig.IssuerKeyId != kring[1].PrimaryKey.KeyId { continue } if err := kring[1].PrimaryKey.VerifyUserIdSignature(identity, kring[0].PrimaryKey, sig); err != nil { t.Fatalf("error verifying new identity signature: %s", err) } checked = true break } if !checked { t.Fatal("didn't find identity signature in Entity") } } func TestNewEntityWithPreferredHash(t *testing.T) { c := &packet.Config{ DefaultHash: crypto.SHA256, } entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", c) if err != nil { t.Fatal(err) } for _, identity := range entity.Identities { if len(identity.SelfSignature.PreferredHash) == 0 { t.Fatal("didn't find a preferred hash in self signature") } ph := hashToHashId(c.DefaultHash) if identity.SelfSignature.PreferredHash[0] != ph { t.Fatalf("Expected preferred hash to be %d, got %d", ph, identity.SelfSignature.PreferredHash[0]) } } } func TestNewEntityWithoutPreferredHash(t *testing.T) { entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil) if err != nil { t.Fatal(err) } for _, identity := range entity.Identities { if len(identity.SelfSignature.PreferredHash) != 0 { t.Fatalf("Expected preferred hash to be empty but got length %d", len(identity.SelfSignature.PreferredHash)) } } } const expiringKeyHex = "988d0451d1ec5d010400ba3385721f2dc3f4ab096b2ee867ab77213f0a27a8538441c35d2fa225b08798a1439a66a5150e6bdc3f40f5d28d588c712394c632b6299f77db8c0d48d37903fb72ebd794d61be6aa774688839e5fdecfe06b2684cc115d240c98c66cb1ef22ae84e3aa0c2b0c28665c1e7d4d044e7f270706193f5223c8d44e0d70b7b8da830011010001b40f4578706972792074657374206b657988be041301020028050251d1ec5d021b03050900278d00060b090807030206150802090a0b0416020301021e01021780000a091072589ad75e237d8c033503fd10506d72837834eb7f994117740723adc39227104b0d326a1161871c0b415d25b4aedef946ca77ea4c05af9c22b32cf98be86ab890111fced1ee3f75e87b7cc3c00dc63bbc85dfab91c0dc2ad9de2c4d13a34659333a85c6acc1a669c5e1d6cecb0cf1e56c10e72d855ae177ddc9e766f9b2dda57ccbb75f57156438bbdb4e42b88d0451d1ec5d0104009c64906559866c5cb61578f5846a94fcee142a489c9b41e67b12bb54cfe86eb9bc8566460f9a720cb00d6526fbccfd4f552071a8e3f7744b1882d01036d811ee5a3fb91a1c568055758f43ba5d2c6a9676b012f3a1a89e47bbf624f1ad571b208f3cc6224eb378f1645dd3d47584463f9eadeacfd1ce6f813064fbfdcc4b5a53001101000188a504180102000f021b0c050251d1f06b050900093e89000a091072589ad75e237d8c20e00400ab8310a41461425b37889c4da28129b5fae6084fafbc0a47dd1adc74a264c6e9c9cc125f40462ee1433072a58384daef88c961c390ed06426a81b464a53194c4e291ddd7e2e2ba3efced01537d713bd111f48437bde2363446200995e8e0d4e528dda377fd1e8f8ede9c8e2198b393bd86852ce7457a7e3daf74d510461a5b77b88d0451d1ece8010400b3a519f83ab0010307e83bca895170acce8964a044190a2b368892f7a244758d9fc193482648acb1fb9780d28cc22d171931f38bb40279389fc9bf2110876d4f3db4fcfb13f22f7083877fe56592b3b65251312c36f83ffcb6d313c6a17f197dd471f0712aad15a8537b435a92471ba2e5b0c72a6c72536c3b567c558d7b6051001101000188a504180102000f021b0c050251d1f07b050900279091000a091072589ad75e237d8ce69e03fe286026afacf7c97ee20673864d4459a2240b5655219950643c7dba0ac384b1d4359c67805b21d98211f7b09c2a0ccf6410c8c04d4ff4a51293725d8d6570d9d8bb0e10c07d22357caeb49626df99c180be02d77d1fe8ed25e7a54481237646083a9f89a11566cd20b9e995b1487c5f9e02aeb434f3a1897cd416dd0a87861838da3e9e" const subkeyUsageHex = "988d04533a52bc010400d26af43085558f65b9e7dbc90cb9238015259aed5e954637adcfa2181548b2d0b60c65f1f42ec5081cbf1bc0a8aa4900acfb77070837c58f26012fbce297d70afe96e759ad63531f0037538e70dbf8e384569b9720d99d8eb39d8d0a2947233ed242436cb6ac7dfe74123354b3d0119b5c235d3dd9c9d6c004f8ffaf67ad8583001101000188b7041f010200210502533b8552170c8001ce094aa433f7040bb2ddf0be3893cb843d0fe70c020700000a0910a42704b92866382aa98404009d63d916a27543da4221c60087c33f1c44bec9998c5438018ed370cca4962876c748e94b73eb39c58eb698063f3fd6346d58dd2a11c0247934c4a9d71f24754f7468f96fb24c3e791dd2392b62f626148ad724189498cbf993db2df7c0cdc2d677c35da0f16cb16c9ce7c33b4de65a4a91b1d21a130ae9cc26067718910ef8e2b417556d627261203c756d627261407379642e65642e61753e88b80413010200220502533a52bc021b03060b090807030206150802090a0b0416020301021e01021780000a0910a42704b92866382a47840400c0c2bd04f5fca586de408b395b3c280a278259c93eaaa8b79a53b97003f8ed502a8a00446dd9947fb462677e4fcac0dac2f0701847d15130aadb6cd9e0705ea0cf5f92f129136c7be21a718d46c8e641eb7f044f2adae573e11ae423a0a9ca51324f03a8a2f34b91fa40c3cc764bee4dccadedb54c768ba0469b683ea53f1c29b88d04533a52bc01040099c92a5d6f8b744224da27bc2369127c35269b58bec179de6bbc038f749344222f85a31933224f26b70243c4e4b2d242f0c4777eaef7b5502f9dad6d8bf3aaeb471210674b74de2d7078af497d55f5cdad97c7bedfbc1b41e8065a97c9c3d344b21fc81d27723af8e374bc595da26ea242dccb6ae497be26eea57e563ed517e90011010001889f0418010200090502533a52bc021b0c000a0910a42704b92866382afa1403ff70284c2de8a043ff51d8d29772602fa98009b7861c540535f874f2c230af8caf5638151a636b21f8255003997ccd29747fdd06777bb24f9593bd7d98a3e887689bf902f999915fcc94625ae487e5d13e6616f89090ebc4fdc7eb5cad8943e4056995bb61c6af37f8043016876a958ec7ebf39c43d20d53b7f546cfa83e8d2604b88d04533b8283010400c0b529316dbdf58b4c54461e7e669dc11c09eb7f73819f178ccd4177b9182b91d138605fcf1e463262fabefa73f94a52b5e15d1904635541c7ea540f07050ce0fb51b73e6f88644cec86e91107c957a114f69554548a85295d2b70bd0b203992f76eb5d493d86d9eabcaa7ef3fc7db7e458438db3fcdb0ca1cc97c638439a9170011010001889f0418010200090502533b8283021b0c000a0910a42704b92866382adc6d0400cfff6258485a21675adb7a811c3e19ebca18851533f75a7ba317950b9997fda8d1a4c8c76505c08c04b6c2cc31dc704d33da36a21273f2b388a1a706f7c3378b66d887197a525936ed9a69acb57fe7f718133da85ec742001c5d1864e9c6c8ea1b94f1c3759cebfd93b18606066c063a63be86085b7e37bdbc65f9a915bf084bb901a204533b85cd110400aed3d2c52af2b38b5b67904b0ef73d6dd7aef86adb770e2b153cd22489654dcc91730892087bb9856ae2d9f7ed1eb48f214243fe86bfe87b349ebd7c30e630e49c07b21fdabf78b7a95c8b7f969e97e3d33f2e074c63552ba64a2ded7badc05ce0ea2be6d53485f6900c7860c7aa76560376ce963d7271b9b54638a4028b573f00a0d8854bfcdb04986141568046202192263b9b67350400aaa1049dbc7943141ef590a70dcb028d730371d92ea4863de715f7f0f16d168bd3dc266c2450457d46dcbbf0b071547e5fbee7700a820c3750b236335d8d5848adb3c0da010e998908dfd93d961480084f3aea20b247034f8988eccb5546efaa35a92d0451df3aaf1aee5aa36a4c4d462c760ecd9cebcabfbe1412b1f21450f203fd126687cd486496e971a87fd9e1a8a765fe654baa219a6871ab97768596ab05c26c1aeea8f1a2c72395a58dbc12ef9640d2b95784e974a4d2d5a9b17c25fedacfe551bda52602de8f6d2e48443f5dd1a2a2a8e6a5e70ecdb88cd6e766ad9745c7ee91d78cc55c3d06536b49c3fee6c3d0b6ff0fb2bf13a314f57c953b8f4d93bf88e70418010200090502533b85cd021b0200520910a42704b92866382a47200419110200060502533b85cd000a091042ce2c64bc0ba99214b2009e26b26852c8b13b10c35768e40e78fbbb48bd084100a0c79d9ea0844fa5853dd3c85ff3ecae6f2c9dd6c557aa04008bbbc964cd65b9b8299d4ebf31f41cc7264b8cf33a00e82c5af022331fac79efc9563a822497ba012953cefe2629f1242fcdcb911dbb2315985bab060bfd58261ace3c654bdbbe2e8ed27a46e836490145c86dc7bae15c011f7e1ffc33730109b9338cd9f483e7cef3d2f396aab5bd80efb6646d7e778270ee99d934d187dd98" const revokedKeyHex = "988d045331ce82010400c4fdf7b40a5477f206e6ee278eaef888ca73bf9128a9eef9f2f1ddb8b7b71a4c07cfa241f028a04edb405e4d916c61d6beabc333813dc7b484d2b3c52ee233c6a79b1eea4e9cc51596ba9cd5ac5aeb9df62d86ea051055b79d03f8a4fa9f38386f5bd17529138f3325d46801514ea9047977e0829ed728e68636802796801be10011010001889f04200102000905025331d0e3021d03000a0910a401d9f09a34f7c042aa040086631196405b7e6af71026b88e98012eab44aa9849f6ef3fa930c7c9f23deaedba9db1538830f8652fb7648ec3fcade8dbcbf9eaf428e83c6cbcc272201bfe2fbb90d41963397a7c0637a1a9d9448ce695d9790db2dc95433ad7be19eb3de72dacf1d6db82c3644c13eae2a3d072b99bb341debba012c5ce4006a7d34a1f4b94b444526567205265766f6b657220283c52656727732022424d204261726973746122204b657920262530305c303e5c29203c72656740626d626172697374612e636f2e61753e88b704130102002205025331ce82021b03060b090807030206150802090a0b0416020301021e01021780000a0910a401d9f09a34f7c0019c03f75edfbeb6a73e7225ad3cc52724e2872e04260d7daf0d693c170d8c4b243b8767bc7785763533febc62ec2600c30603c433c095453ede59ff2fcabeb84ce32e0ed9d5cf15ffcbc816202b64370d4d77c1e9077d74e94a16fb4fa2e5bec23a56d7a73cf275f91691ae1801a976fcde09e981a2f6327ac27ea1fecf3185df0d56889c04100102000605025331cfb5000a0910fe9645554e8266b64b4303fc084075396674fb6f778d302ac07cef6bc0b5d07b66b2004c44aef711cbac79617ef06d836b4957522d8772dd94bf41a2f4ac8b1ee6d70c57503f837445a74765a076d07b829b8111fc2a918423ddb817ead7ca2a613ef0bfb9c6b3562aec6c3cf3c75ef3031d81d95f6563e4cdcc9960bcb386c5d757b104fcca5fe11fc709df884604101102000605025331cfe7000a09107b15a67f0b3ddc0317f6009e360beea58f29c1d963a22b962b80788c3fa6c84e009d148cfde6b351469b8eae91187eff07ad9d08fcaab88d045331ce820104009f25e20a42b904f3fa555530fe5c46737cf7bd076c35a2a0d22b11f7e0b61a69320b768f4a80fe13980ce380d1cfc4a0cd8fbe2d2e2ef85416668b77208baa65bf973fe8e500e78cc310d7c8705cdb34328bf80e24f0385fce5845c33bc7943cf6b11b02348a23da0bf6428e57c05135f2dc6bd7c1ce325d666d5a5fd2fd5e410011010001889f04180102000905025331ce82021b0c000a0910a401d9f09a34f7c0418003fe34feafcbeaef348a800a0d908a7a6809cc7304017d820f70f0474d5e23cb17e38b67dc6dca282c6ca00961f4ec9edf2738d0f087b1d81e4871ef08e1798010863afb4eac4c44a376cb343be929c5be66a78cfd4456ae9ec6a99d97f4e1c3ff3583351db2147a65c0acef5c003fb544ab3a2e2dc4d43646f58b811a6c3a369d1f" const revokedSubkeyHex = "988d04533121f6010400aefc803a3e4bb1a61c86e8a86d2726c6a43e0079e9f2713f1fa017e9854c83877f4aced8e331d675c67ea83ddab80aacbfa0b9040bb12d96f5a3d6be09455e2a76546cbd21677537db941cab710216b6d24ec277ee0bd65b910f416737ed120f6b93a9d3b306245c8cfd8394606fdb462e5cf43c551438d2864506c63367fc890011010001b41d416c696365203c616c69636540626d626172697374612e636f2e61753e88bb041301020025021b03060b090807030206150802090a0b0416020301021e01021780050253312798021901000a09104ef7e4beccde97f015a803ff5448437780f63263b0df8442a995e7f76c221351a51edd06f2063d8166cf3157aada4923dfc44aa0f2a6a4da5cf83b7fe722ba8ab416c976e77c6b5682e7f1069026673bd0de56ba06fd5d7a9f177607f277d9b55ff940a638c3e68525c67517e2b3d976899b93ca267f705b3e5efad7d61220e96b618a4497eab8d04403d23f8846041011020006050253312910000a09107b15a67f0b3ddc03d96e009f50b6365d86c4be5d5e9d0ea42d5e56f5794c617700a0ab274e19c2827780016d23417ce89e0a2c0d987d889c04100102000605025331cf7a000a0910a401d9f09a34f7c0ee970400aca292f213041c9f3b3fc49148cbda9d84afee6183c8dd6c5ff2600b29482db5fecd4303797be1ee6d544a20a858080fec43412061c9a71fae4039fd58013b4ae341273e6c66ad4c7cdd9e68245bedb260562e7b166f2461a1032f2b38c0e0e5715fb3d1656979e052b55ca827a76f872b78a9fdae64bc298170bfcebedc1271b41a416c696365203c616c696365407379646973702e6f722e61753e88b804130102002205025331278b021b03060b090807030206150802090a0b0416020301021e01021780000a09104ef7e4beccde97f06a7003fa03c3af68d272ebc1fa08aa72a03b02189c26496a2833d90450801c4e42c5b5f51ad96ce2d2c9cef4b7c02a6a2fcf1412d6a2d486098eb762f5010a201819c17fd2888aec8eda20c65a3b75744de7ee5cc8ac7bfc470cbe3cb982720405a27a3c6a8c229cfe36905f881b02ed5680f6a8f05866efb9d6c5844897e631deb949ca8846041011020006050253312910000a09107b15a67f0b3ddc0347bc009f7fa35db59147469eb6f2c5aaf6428accb138b22800a0caa2f5f0874bacc5909c652a57a31beda65eddd5889c04100102000605025331cf7a000a0910a401d9f09a34f7c0316403ff46f2a5c101256627f16384d34a38fb47a6c88ba60506843e532d91614339fccae5f884a5741e7582ffaf292ba38ee10a270a05f139bde3814b6a077e8cd2db0f105ebea2a83af70d385f13b507fac2ad93ff79d84950328bb86f3074745a8b7f9b64990fb142e2a12976e27e8d09a28dc5621f957ac49091116da410ac3cbde1b88d04533121f6010400cbd785b56905e4192e2fb62a720727d43c4fa487821203cf72138b884b78b701093243e1d8c92a0248a6c0203a5a88693da34af357499abacaf4b3309c640797d03093870a323b4b6f37865f6eaa2838148a67df4735d43a90ca87942554cdf1c4a751b1e75f9fd4ce4e97e278d6c1c7ed59d33441df7d084f3f02beb68896c70011010001889f0418010200090502533121f6021b0c000a09104ef7e4beccde97f0b98b03fc0a5ccf6a372995835a2f5da33b282a7d612c0ab2a97f59cf9fff73e9110981aac2858c41399afa29624a7fd8a0add11654e3d882c0fd199e161bdad65e5e2548f7b68a437ea64293db1246e3011cbb94dc1bcdeaf0f2539bd88ff16d95547144d97cead6a8c5927660a91e6db0d16eb36b7b49a3525b54d1644e65599b032b7eb901a204533127a0110400bd3edaa09eff9809c4edc2c2a0ebe52e53c50a19c1e49ab78e6167bf61473bb08f2050d78a5cbbc6ed66aff7b42cd503f16b4a0b99fa1609681fca9b7ce2bbb1a5b3864d6cdda4d7ef7849d156d534dea30fb0efb9e4cf8959a2b2ce623905882d5430b995a15c3b9fe92906086788b891002924f94abe139b42cbbfaaabe42f00a0b65dc1a1ad27d798adbcb5b5ad02d2688c89477b03ff4eebb6f7b15a73b96a96bed201c0e5e4ea27e4c6e2dd1005b94d4b90137a5b1cf5e01c6226c070c4cc999938101578877ee76d296b9aab8246d57049caacf489e80a3f40589cade790a020b1ac146d6f7a6241184b8c7fcde680eae3188f5dcbe846d7f7bdad34f6fcfca08413e19c1d5df83fc7c7c627d493492e009c2f52a80400a2fe82de87136fd2e8845888c4431b032ba29d9a29a804277e31002a8201fb8591a3e55c7a0d0881496caf8b9fb07544a5a4879291d0dc026a0ea9e5bd88eb4aa4947bbd694b25012e208a250d65ddc6f1eea59d3aed3b4ec15fcab85e2afaa23a40ab1ef9ce3e11e1bc1c34a0e758e7aa64deb8739276df0af7d4121f834a9b88e70418010200090502533127a0021b02005209104ef7e4beccde97f047200419110200060502533127a0000a0910dbce4ee19529437fe045009c0b32f5ead48ee8a7e98fac0dea3d3e6c0e2c552500a0ad71fadc5007cfaf842d9b7db3335a8cdad15d3d1a6404009b08e2c68fe8f3b45c1bb72a4b3278cdf3012aa0f229883ad74aa1f6000bb90b18301b2f85372ca5d6b9bf478d235b733b1b197d19ccca48e9daf8e890cb64546b4ce1b178faccfff07003c172a2d4f5ebaba9f57153955f3f61a9b80a4f5cb959908f8b211b03b7026a8a82fc612bfedd3794969bcf458c4ce92be215a1176ab88d045331d144010400a5063000c5aaf34953c1aa3bfc95045b3aab9882b9a8027fecfe2142dc6b47ba8aca667399990244d513dd0504716908c17d92c65e74219e004f7b83fc125e575dd58efec3ab6dd22e3580106998523dea42ec75bf9aa111734c82df54630bebdff20fe981cfc36c76f865eb1c2fb62c9e85bc3a6e5015a361a2eb1c8431578d0011010001889f04280102000905025331d433021d03000a09104ef7e4beccde97f02e5503ff5e0630d1b65291f4882b6d40a29da4616bb5088717d469fbcc3648b8276de04a04988b1f1b9f3e18f52265c1f8b6c85861691c1a6b8a3a25a1809a0b32ad330aec5667cb4262f4450649184e8113849b05e5ad06a316ea80c001e8e71838190339a6e48bbde30647bcf245134b9a97fa875c1d83a9862cae87ffd7e2c4ce3a1b89013d04180102000905025331d144021b0200a809104ef7e4beccde97f09d2004190102000605025331d144000a0910677815e371c2fd23522203fe22ab62b8e7a151383cea3edd3a12995693911426f8ccf125e1f6426388c0010f88d9ca7da2224aee8d1c12135998640c5e1813d55a93df472faae75bef858457248db41b4505827590aeccf6f9eb646da7f980655dd3050c6897feddddaca90676dee856d66db8923477d251712bb9b3186b4d0114daf7d6b59272b53218dd1da94a03ff64006fcbe71211e5daecd9961fba66cdb6de3f914882c58ba5beddeba7dcb950c1156d7fba18c19ea880dccc800eae335deec34e3b84ac75ffa24864f782f87815cda1c0f634b3dd2fa67cea30811d21723d21d9551fa12ccbcfa62b6d3a15d01307b99925707992556d50065505b090aadb8579083a20fe65bd2a270da9b011" const missingCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- Charset: UTF-8 mQENBFMYynYBCACVOZ3/e8Bm2b9KH9QyIlHGo/i1bnkpqsgXj8tpJ2MIUOnXMMAY ztW7kKFLCmgVdLIC0vSoLA4yhaLcMojznh/2CcUglZeb6Ao8Gtelr//Rd5DRfPpG zqcfUo+m+eO1co2Orabw0tZDfGpg5p3AYl0hmxhUyYSc/xUq93xL1UJzBFgYXY54 QsM8dgeQgFseSk/YvdP5SMx1ev+eraUyiiUtWzWrWC1TdyRa5p4UZg6Rkoppf+WJ QrW6BWrhAtqATHc8ozV7uJjeONjUEq24roRc/OFZdmQQGK6yrzKnnbA6MdHhqpdo 9kWDcXYb7pSE63Lc+OBa5X2GUVvXJLS/3nrtABEBAAG0F2ludmFsaWQtc2lnbmlu Zy1zdWJrZXlziQEoBBMBAgASBQJTnKB5AhsBAgsHAhUIAh4BAAoJEO3UDQUIHpI/ dN4H/idX4FQ1LIZCnpHS/oxoWQWfpRgdKAEM0qCqjMgiipJeEwSQbqjTCynuh5/R JlODDz85ABR06aoF4l5ebGLQWFCYifPnJZ/Yf5OYcMGtb7dIbqxWVFL9iLMO/oDL ioI3dotjPui5e+2hI9pVH1UHB/bZ/GvMGo6Zg0XxLPolKQODMVjpjLAQ0YJ3spew RAmOGre6tIvbDsMBnm8qREt7a07cBJ6XK7xjxYaZHQBiHVxyEWDa6gyANONx8duW /fhQ/zDTnyVM/ik6VO0Ty9BhPpcEYLFwh5c1ilFari1ta3e6qKo6ZGa9YMk/REhu yBHd9nTkI+0CiQUmbckUiVjDKKe5AQ0EUxjKdgEIAJcXQeP+NmuciE99YcJoffxv 2gVLU4ZXBNHEaP0mgaJ1+tmMD089vUQAcyGRvw8jfsNsVZQIOAuRxY94aHQhIRHR bUzBN28ofo/AJJtfx62C15xt6fDKRV6HXYqAiygrHIpEoRLyiN69iScUsjIJeyFL C8wa72e8pSL6dkHoaV1N9ZH/xmrJ+k0vsgkQaAh9CzYufncDxcwkoP+aOlGtX1gP WwWoIbz0JwLEMPHBWvDDXQcQPQTYQyj+LGC9U6f9VZHN25E94subM1MjuT9OhN9Y MLfWaaIc5WyhLFyQKW2Upofn9wSFi8ubyBnv640Dfd0rVmaWv7LNTZpoZ/GbJAMA EQEAAYkBHwQYAQIACQUCU5ygeQIbAgAKCRDt1A0FCB6SP0zCB/sEzaVR38vpx+OQ MMynCBJrakiqDmUZv9xtplY7zsHSQjpd6xGflbU2n+iX99Q+nav0ETQZifNUEd4N 1ljDGQejcTyKD6Pkg6wBL3x9/RJye7Zszazm4+toJXZ8xJ3800+BtaPoI39akYJm +ijzbskvN0v/j5GOFJwQO0pPRAFtdHqRs9Kf4YanxhedB4dIUblzlIJuKsxFit6N lgGRblagG3Vv2eBszbxzPbJjHCgVLR3RmrVezKOsZjr/2i7X+xLWIR0uD3IN1qOW CXQxLBizEEmSNVNxsp7KPGTLnqO3bPtqFirxS9PJLIMPTPLNBY7ZYuPNTMqVIUWF 4artDmrG =7FfJ -----END PGP PUBLIC KEY BLOCK-----` const invalidCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFMYynYBCACVOZ3/e8Bm2b9KH9QyIlHGo/i1bnkpqsgXj8tpJ2MIUOnXMMAY ztW7kKFLCmgVdLIC0vSoLA4yhaLcMojznh/2CcUglZeb6Ao8Gtelr//Rd5DRfPpG zqcfUo+m+eO1co2Orabw0tZDfGpg5p3AYl0hmxhUyYSc/xUq93xL1UJzBFgYXY54 QsM8dgeQgFseSk/YvdP5SMx1ev+eraUyiiUtWzWrWC1TdyRa5p4UZg6Rkoppf+WJ QrW6BWrhAtqATHc8ozV7uJjeONjUEq24roRc/OFZdmQQGK6yrzKnnbA6MdHhqpdo 9kWDcXYb7pSE63Lc+OBa5X2GUVvXJLS/3nrtABEBAAG0F2ludmFsaWQtc2lnbmlu Zy1zdWJrZXlziQEoBBMBAgASBQJTnKB5AhsBAgsHAhUIAh4BAAoJEO3UDQUIHpI/ dN4H/idX4FQ1LIZCnpHS/oxoWQWfpRgdKAEM0qCqjMgiipJeEwSQbqjTCynuh5/R JlODDz85ABR06aoF4l5ebGLQWFCYifPnJZ/Yf5OYcMGtb7dIbqxWVFL9iLMO/oDL ioI3dotjPui5e+2hI9pVH1UHB/bZ/GvMGo6Zg0XxLPolKQODMVjpjLAQ0YJ3spew RAmOGre6tIvbDsMBnm8qREt7a07cBJ6XK7xjxYaZHQBiHVxyEWDa6gyANONx8duW /fhQ/zDTnyVM/ik6VO0Ty9BhPpcEYLFwh5c1ilFari1ta3e6qKo6ZGa9YMk/REhu yBHd9nTkI+0CiQUmbckUiVjDKKe5AQ0EUxjKdgEIAIINDqlj7X6jYKc6DjwrOkjQ UIRWbQQar0LwmNilehmt70g5DCL1SYm9q4LcgJJ2Nhxj0/5qqsYib50OSWMcKeEe iRXpXzv1ObpcQtI5ithp0gR53YPXBib80t3bUzomQ5UyZqAAHzMp3BKC54/vUrSK FeRaxDzNLrCeyI00+LHNUtwghAqHvdNcsIf8VRumK8oTm3RmDh0TyjASWYbrt9c8 R1Um3zuoACOVy+mEIgIzsfHq0u7dwYwJB5+KeM7ZLx+HGIYdUYzHuUE1sLwVoELh +SHIGHI1HDicOjzqgajShuIjj5hZTyQySVprrsLKiXS6NEwHAP20+XjayJ/R3tEA EQEAAYkCPgQYAQIBKAUCU5ygeQIbAsBdIAQZAQIABgUCU5ygeQAKCRCpVlnFZmhO 52RJB/9uD1MSa0wjY6tHOIgquZcP3bHBvHmrHNMw9HR2wRCMO91ZkhrpdS3ZHtgb u3/55etj0FdvDo1tb8P8FGSVtO5Vcwf5APM8sbbqoi8L951Q3i7qt847lfhu6sMl w0LWFvPTOLHrliZHItPRjOltS1WAWfr2jUYhsU9ytaDAJmvf9DujxEOsN5G1YJep 54JCKVCkM/y585Zcnn+yxk/XwqoNQ0/iJUT9qRrZWvoeasxhl1PQcwihCwss44A+ YXaAt3hbk+6LEQuZoYS73yR3WHj+42tfm7YxRGeubXfgCEz/brETEWXMh4pe0vCL bfWrmfSPq2rDegYcAybxRQz0lF8PAAoJEO3UDQUIHpI/exkH/0vQfdHA8g/N4T6E i6b1CUVBAkvtdJpCATZjWPhXmShOw62gkDw306vHPilL4SCvEEi4KzG72zkp6VsB DSRcpxCwT4mHue+duiy53/aRMtSJ+vDfiV1Vhq+3sWAck/yUtfDU9/u4eFaiNok1 8/Gd7reyuZt5CiJnpdPpjCwelK21l2w7sHAnJF55ITXdOxI8oG3BRKufz0z5lyDY s2tXYmhhQIggdgelN8LbcMhWs/PBbtUr6uZlNJG2lW1yscD4aI529VjwJlCeo745 U7pO4eF05VViUJ2mmfoivL3tkhoTUWhx8xs8xCUcCg8DoEoSIhxtOmoTPR22Z9BL 6LCg2mg= =Dhm4 -----END PGP PUBLIC KEY BLOCK-----` const goodCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1 mI0EVUqeVwEEAMufHRrMPWK3gyvi0O0tABCs/oON9zV9KDZlr1a1M91ShCSFwCPo 7r80PxdWVWcj0V5h50/CJYtpN3eE/mUIgW2z1uDYQF1OzrQ8ubrksfsJvpAhENom lTQEppv9mV8qhcM278teb7TX0pgrUHLYF5CfPdp1L957JLLXoQR/lwLVABEBAAG0 E2dvb2Qtc2lnbmluZy1zdWJrZXmIuAQTAQIAIgUCVUqeVwIbAwYLCQgHAwIGFQgC CQoLBBYCAwECHgECF4AACgkQNRjL95IRWP69XQQAlH6+eyXJN4DZTLX78KGjHrsw 6FCvxxClEPtPUjcJy/1KCRQmtLAt9PbbA78dvgzjDeZMZqRAwdjyJhjyg/fkU2OH 7wq4ktjUu+dLcOBb+BFMEY+YjKZhf6EJuVfxoTVr5f82XNPbYHfTho9/OABKH6kv X70PaKZhbwnwij8Nts65AaIEVUqftREEAJ3WxZfqAX0bTDbQPf2CMT2IVMGDfhK7 GyubOZgDFFjwUJQvHNvsrbeGLZ0xOBumLINyPO1amIfTgJNm1iiWFWfmnHReGcDl y5mpYG60Mb79Whdcer7CMm3AqYh/dW4g6IB02NwZMKoUHo3PXmFLxMKXnWyJ0clw R0LI/Qn509yXAKDh1SO20rqrBM+EAP2c5bfI98kyNwQAi3buu94qo3RR1ZbvfxgW CKXDVm6N99jdZGNK7FbRifXqzJJDLcXZKLnstnC4Sd3uyfyf1uFhmDLIQRryn5m+ LBYHfDBPN3kdm7bsZDDq9GbTHiFZUfm/tChVKXWxkhpAmHhU/tH6GGzNSMXuIWSO aOz3Rqq0ED4NXyNKjdF9MiwD/i83S0ZBc0LmJYt4Z10jtH2B6tYdqnAK29uQaadx yZCX2scE09UIm32/w7pV77CKr1Cp/4OzAXS1tmFzQ+bX7DR+Gl8t4wxr57VeEMvl BGw4Vjh3X8//m3xynxycQU18Q1zJ6PkiMyPw2owZ/nss3hpSRKFJsxMLhW3fKmKr Ey2KiOcEGAECAAkFAlVKn7UCGwIAUgkQNRjL95IRWP5HIAQZEQIABgUCVUqftQAK CRD98VjDN10SqkWrAKDTpEY8D8HC02E/KVC5YUI01B30wgCgurpILm20kXEDCeHp C5pygfXw1DJrhAP+NyPJ4um/bU1I+rXaHHJYroYJs8YSweiNcwiHDQn0Engh/mVZ SqLHvbKh2dL/RXymC3+rjPvQf5cup9bPxNMa6WagdYBNAfzWGtkVISeaQW+cTEp/ MtgVijRGXR/lGLGETPg2X3Afwn9N9bLMBkBprKgbBqU7lpaoPupxT61bL70= =vtbN -----END PGP PUBLIC KEY BLOCK-----` �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/keys.go���������������������������������������������0000644�0610621�0607500�00000043540�13172163317�024032� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package openpgp import ( "crypto/rsa" "io" "time" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/packet" ) // PublicKeyType is the armor type for a PGP public key. var PublicKeyType = "PGP PUBLIC KEY BLOCK" // PrivateKeyType is the armor type for a PGP private key. var PrivateKeyType = "PGP PRIVATE KEY BLOCK" // An Entity represents the components of an OpenPGP key: a primary public key // (which must be a signing key), one or more identities claimed by that key, // and zero or more subkeys, which may be encryption keys. type Entity struct { PrimaryKey *packet.PublicKey PrivateKey *packet.PrivateKey Identities map[string]*Identity // indexed by Identity.Name Revocations []*packet.Signature Subkeys []Subkey } // An Identity represents an identity claimed by an Entity and zero or more // assertions by other entities about that claim. type Identity struct { Name string // by convention, has the form "Full Name (comment) <email@example.com>" UserId *packet.UserId SelfSignature *packet.Signature Signatures []*packet.Signature } // A Subkey is an additional public key in an Entity. Subkeys can be used for // encryption. type Subkey struct { PublicKey *packet.PublicKey PrivateKey *packet.PrivateKey Sig *packet.Signature } // A Key identifies a specific public key in an Entity. This is either the // Entity's primary key or a subkey. type Key struct { Entity *Entity PublicKey *packet.PublicKey PrivateKey *packet.PrivateKey SelfSignature *packet.Signature } // A KeyRing provides access to public and private keys. type KeyRing interface { // KeysById returns the set of keys that have the given key id. KeysById(id uint64) []Key // KeysByIdAndUsage returns the set of keys with the given id // that also meet the key usage given by requiredUsage. // The requiredUsage is expressed as the bitwise-OR of // packet.KeyFlag* values. KeysByIdUsage(id uint64, requiredUsage byte) []Key // DecryptionKeys returns all private keys that are valid for // decryption. DecryptionKeys() []Key } // primaryIdentity returns the Identity marked as primary or the first identity // if none are so marked. func (e *Entity) primaryIdentity() *Identity { var firstIdentity *Identity for _, ident := range e.Identities { if firstIdentity == nil { firstIdentity = ident } if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { return ident } } return firstIdentity } // encryptionKey returns the best candidate Key for encrypting a message to the // given Entity. func (e *Entity) encryptionKey(now time.Time) (Key, bool) { candidateSubkey := -1 // Iterate the keys to find the newest key var maxTime time.Time for i, subkey := range e.Subkeys { if subkey.Sig.FlagsValid && subkey.Sig.FlagEncryptCommunications && subkey.PublicKey.PubKeyAlgo.CanEncrypt() && !subkey.Sig.KeyExpired(now) && (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) { candidateSubkey = i maxTime = subkey.Sig.CreationTime } } if candidateSubkey != -1 { subkey := e.Subkeys[candidateSubkey] return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig}, true } // If we don't have any candidate subkeys for encryption and // the primary key doesn't have any usage metadata then we // assume that the primary key is ok. Or, if the primary key is // marked as ok to encrypt to, then we can obviously use it. i := e.primaryIdentity() if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications && e.PrimaryKey.PubKeyAlgo.CanEncrypt() && !i.SelfSignature.KeyExpired(now) { return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature}, true } // This Entity appears to be signing only. return Key{}, false } // signingKey return the best candidate Key for signing a message with this // Entity. func (e *Entity) signingKey(now time.Time) (Key, bool) { candidateSubkey := -1 for i, subkey := range e.Subkeys { if subkey.Sig.FlagsValid && subkey.Sig.FlagSign && subkey.PublicKey.PubKeyAlgo.CanSign() && !subkey.Sig.KeyExpired(now) { candidateSubkey = i break } } if candidateSubkey != -1 { subkey := e.Subkeys[candidateSubkey] return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig}, true } // If we have no candidate subkey then we assume that it's ok to sign // with the primary key. i := e.primaryIdentity() if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagSign && !i.SelfSignature.KeyExpired(now) { return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature}, true } return Key{}, false } // An EntityList contains one or more Entities. type EntityList []*Entity // KeysById returns the set of keys that have the given key id. func (el EntityList) KeysById(id uint64) (keys []Key) { for _, e := range el { if e.PrimaryKey.KeyId == id { var selfSig *packet.Signature for _, ident := range e.Identities { if selfSig == nil { selfSig = ident.SelfSignature } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { selfSig = ident.SelfSignature break } } keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig}) } for _, subKey := range e.Subkeys { if subKey.PublicKey.KeyId == id { keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig}) } } } return } // KeysByIdAndUsage returns the set of keys with the given id that also meet // the key usage given by requiredUsage. The requiredUsage is expressed as // the bitwise-OR of packet.KeyFlag* values. func (el EntityList) KeysByIdUsage(id uint64, requiredUsage byte) (keys []Key) { for _, key := range el.KeysById(id) { if len(key.Entity.Revocations) > 0 { continue } if key.SelfSignature.RevocationReason != nil { continue } if key.SelfSignature.FlagsValid && requiredUsage != 0 { var usage byte if key.SelfSignature.FlagCertify { usage |= packet.KeyFlagCertify } if key.SelfSignature.FlagSign { usage |= packet.KeyFlagSign } if key.SelfSignature.FlagEncryptCommunications { usage |= packet.KeyFlagEncryptCommunications } if key.SelfSignature.FlagEncryptStorage { usage |= packet.KeyFlagEncryptStorage } if usage&requiredUsage != requiredUsage { continue } } keys = append(keys, key) } return } // DecryptionKeys returns all private keys that are valid for decryption. func (el EntityList) DecryptionKeys() (keys []Key) { for _, e := range el { for _, subKey := range e.Subkeys { if subKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) { keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig}) } } } return } // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. func ReadArmoredKeyRing(r io.Reader) (EntityList, error) { block, err := armor.Decode(r) if err == io.EOF { return nil, errors.InvalidArgumentError("no armored data found") } if err != nil { return nil, err } if block.Type != PublicKeyType && block.Type != PrivateKeyType { return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type) } return ReadKeyRing(block.Body) } // ReadKeyRing reads one or more public/private keys. Unsupported keys are // ignored as long as at least a single valid key is found. func ReadKeyRing(r io.Reader) (el EntityList, err error) { packets := packet.NewReader(r) var lastUnsupportedError error for { var e *Entity e, err = ReadEntity(packets) if err != nil { // TODO: warn about skipped unsupported/unreadable keys if _, ok := err.(errors.UnsupportedError); ok { lastUnsupportedError = err err = readToNextPublicKey(packets) } else if _, ok := err.(errors.StructuralError); ok { // Skip unreadable, badly-formatted keys lastUnsupportedError = err err = readToNextPublicKey(packets) } if err == io.EOF { err = nil break } if err != nil { el = nil break } } else { el = append(el, e) } } if len(el) == 0 && err == nil { err = lastUnsupportedError } return } // readToNextPublicKey reads packets until the start of the entity and leaves // the first packet of the new entity in the Reader. func readToNextPublicKey(packets *packet.Reader) (err error) { var p packet.Packet for { p, err = packets.Next() if err == io.EOF { return } else if err != nil { if _, ok := err.(errors.UnsupportedError); ok { err = nil continue } return } if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey { packets.Unread(p) return } } } // ReadEntity reads an entity (public key, identities, subkeys etc) from the // given Reader. func ReadEntity(packets *packet.Reader) (*Entity, error) { e := new(Entity) e.Identities = make(map[string]*Identity) p, err := packets.Next() if err != nil { return nil, err } var ok bool if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok { if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { packets.Unread(p) return nil, errors.StructuralError("first packet was not a public/private key") } else { e.PrimaryKey = &e.PrivateKey.PublicKey } } if !e.PrimaryKey.PubKeyAlgo.CanSign() { return nil, errors.StructuralError("primary key cannot be used for signatures") } var current *Identity var revocations []*packet.Signature EachPacket: for { p, err := packets.Next() if err == io.EOF { break } else if err != nil { return nil, err } switch pkt := p.(type) { case *packet.UserId: current = new(Identity) current.Name = pkt.Id current.UserId = pkt e.Identities[pkt.Id] = current for { p, err = packets.Next() if err == io.EOF { return nil, io.ErrUnexpectedEOF } else if err != nil { return nil, err } sig, ok := p.(*packet.Signature) if !ok { return nil, errors.StructuralError("user ID packet not followed by self-signature") } if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId { if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, e.PrimaryKey, sig); err != nil { return nil, errors.StructuralError("user ID self-signature invalid: " + err.Error()) } current.SelfSignature = sig break } current.Signatures = append(current.Signatures, sig) } case *packet.Signature: if pkt.SigType == packet.SigTypeKeyRevocation { revocations = append(revocations, pkt) } else if pkt.SigType == packet.SigTypeDirectSignature { // TODO: RFC4880 5.2.1 permits signatures // directly on keys (eg. to bind additional // revocation keys). } else if current == nil { return nil, errors.StructuralError("signature packet found before user id packet") } else { current.Signatures = append(current.Signatures, pkt) } case *packet.PrivateKey: if pkt.IsSubkey == false { packets.Unread(p) break EachPacket } err = addSubkey(e, packets, &pkt.PublicKey, pkt) if err != nil { return nil, err } case *packet.PublicKey: if pkt.IsSubkey == false { packets.Unread(p) break EachPacket } err = addSubkey(e, packets, pkt, nil) if err != nil { return nil, err } default: // we ignore unknown packets } } if len(e.Identities) == 0 { return nil, errors.StructuralError("entity without any identities") } for _, revocation := range revocations { err = e.PrimaryKey.VerifyRevocationSignature(revocation) if err == nil { e.Revocations = append(e.Revocations, revocation) } else { // TODO: RFC 4880 5.2.3.15 defines revocation keys. return nil, errors.StructuralError("revocation signature signed by alternate key") } } return e, nil } func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error { var subKey Subkey subKey.PublicKey = pub subKey.PrivateKey = priv p, err := packets.Next() if err == io.EOF { return io.ErrUnexpectedEOF } if err != nil { return errors.StructuralError("subkey signature invalid: " + err.Error()) } var ok bool subKey.Sig, ok = p.(*packet.Signature) if !ok { return errors.StructuralError("subkey packet not followed by signature") } if subKey.Sig.SigType != packet.SigTypeSubkeyBinding && subKey.Sig.SigType != packet.SigTypeSubkeyRevocation { return errors.StructuralError("subkey signature with wrong type") } err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig) if err != nil { return errors.StructuralError("subkey signature invalid: " + err.Error()) } e.Subkeys = append(e.Subkeys, subKey) return nil } const defaultRSAKeyBits = 2048 // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a // single identity composed of the given full name, comment and email, any of // which may be empty but must not contain any of "()<>\x00". // If config is nil, sensible defaults will be used. func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) { currentTime := config.Now() bits := defaultRSAKeyBits if config != nil && config.RSABits != 0 { bits = config.RSABits } uid := packet.NewUserId(name, comment, email) if uid == nil { return nil, errors.InvalidArgumentError("user id field contained invalid characters") } signingPriv, err := rsa.GenerateKey(config.Random(), bits) if err != nil { return nil, err } encryptingPriv, err := rsa.GenerateKey(config.Random(), bits) if err != nil { return nil, err } e := &Entity{ PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey), PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv), Identities: make(map[string]*Identity), } isPrimaryId := true e.Identities[uid.Id] = &Identity{ Name: uid.Name, UserId: uid, SelfSignature: &packet.Signature{ CreationTime: currentTime, SigType: packet.SigTypePositiveCert, PubKeyAlgo: packet.PubKeyAlgoRSA, Hash: config.Hash(), IsPrimaryId: &isPrimaryId, FlagsValid: true, FlagSign: true, FlagCertify: true, IssuerKeyId: &e.PrimaryKey.KeyId, }, } // If the user passes in a DefaultHash via packet.Config, // set the PreferredHash for the SelfSignature. if config != nil && config.DefaultHash != 0 { e.Identities[uid.Id].SelfSignature.PreferredHash = []uint8{hashToHashId(config.DefaultHash)} } e.Subkeys = make([]Subkey, 1) e.Subkeys[0] = Subkey{ PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey), PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv), Sig: &packet.Signature{ CreationTime: currentTime, SigType: packet.SigTypeSubkeyBinding, PubKeyAlgo: packet.PubKeyAlgoRSA, Hash: config.Hash(), FlagsValid: true, FlagEncryptStorage: true, FlagEncryptCommunications: true, IssuerKeyId: &e.PrimaryKey.KeyId, }, } e.Subkeys[0].PublicKey.IsSubkey = true e.Subkeys[0].PrivateKey.IsSubkey = true return e, nil } // SerializePrivate serializes an Entity, including private key material, to // the given Writer. For now, it must only be used on an Entity returned from // NewEntity. // If config is nil, sensible defaults will be used. func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) { err = e.PrivateKey.Serialize(w) if err != nil { return } for _, ident := range e.Identities { err = ident.UserId.Serialize(w) if err != nil { return } err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config) if err != nil { return } err = ident.SelfSignature.Serialize(w) if err != nil { return } } for _, subkey := range e.Subkeys { err = subkey.PrivateKey.Serialize(w) if err != nil { return } err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config) if err != nil { return } err = subkey.Sig.Serialize(w) if err != nil { return } } return nil } // Serialize writes the public part of the given Entity to w. (No private // key material will be output). func (e *Entity) Serialize(w io.Writer) error { err := e.PrimaryKey.Serialize(w) if err != nil { return err } for _, ident := range e.Identities { err = ident.UserId.Serialize(w) if err != nil { return err } err = ident.SelfSignature.Serialize(w) if err != nil { return err } for _, sig := range ident.Signatures { err = sig.Serialize(w) if err != nil { return err } } } for _, subkey := range e.Subkeys { err = subkey.PublicKey.Serialize(w) if err != nil { return err } err = subkey.Sig.Serialize(w) if err != nil { return err } } return nil } // SignIdentity adds a signature to e, from signer, attesting that identity is // associated with e. The provided identity must already be an element of // e.Identities and the private key of signer must have been decrypted if // necessary. // If config is nil, sensible defaults will be used. func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error { if signer.PrivateKey == nil { return errors.InvalidArgumentError("signing Entity must have a private key") } if signer.PrivateKey.Encrypted { return errors.InvalidArgumentError("signing Entity's private key must be decrypted") } ident, ok := e.Identities[identity] if !ok { return errors.InvalidArgumentError("given identity string not found in Entity") } sig := &packet.Signature{ SigType: packet.SigTypeGenericCert, PubKeyAlgo: signer.PrivateKey.PubKeyAlgo, Hash: config.Hash(), CreationTime: config.Now(), IssuerKeyId: &signer.PrivateKey.KeyId, } if err := sig.SignUserId(identity, e.PrimaryKey, signer.PrivateKey, config); err != nil { return err } ident.Signatures = append(ident.Signatures, sig) return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/errors/���������������������������������������������0000755�0610621�0607500�00000000000�13172163317�024036� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/errors/errors.go������������������������������������0000644�0610621�0607500�00000003533�13172163317�025705� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package errors contains common error types for the OpenPGP packages. package errors // import "golang.org/x/crypto/openpgp/errors" import ( "strconv" ) // A StructuralError is returned when OpenPGP data is found to be syntactically // invalid. type StructuralError string func (s StructuralError) Error() string { return "openpgp: invalid data: " + string(s) } // UnsupportedError indicates that, although the OpenPGP data is valid, it // makes use of currently unimplemented features. type UnsupportedError string func (s UnsupportedError) Error() string { return "openpgp: unsupported feature: " + string(s) } // InvalidArgumentError indicates that the caller is in error and passed an // incorrect value. type InvalidArgumentError string func (i InvalidArgumentError) Error() string { return "openpgp: invalid argument: " + string(i) } // SignatureError indicates that a syntactically valid signature failed to // validate. type SignatureError string func (b SignatureError) Error() string { return "openpgp: invalid signature: " + string(b) } type keyIncorrectError int func (ki keyIncorrectError) Error() string { return "openpgp: incorrect key" } var ErrKeyIncorrect error = keyIncorrectError(0) type unknownIssuerError int func (unknownIssuerError) Error() string { return "openpgp: signature made by unknown entity" } var ErrUnknownIssuer error = unknownIssuerError(0) type keyRevokedError int func (keyRevokedError) Error() string { return "openpgp: signature made by revoked key" } var ErrKeyRevoked error = keyRevokedError(0) type UnknownPacketTypeError uint8 func (upte UnknownPacketTypeError) Error() string { return "openpgp: unknown packet type: " + strconv.Itoa(int(upte)) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/elgamal/��������������������������������������������0000755�0610621�0607500�00000000000�13172163317�024124� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/elgamal/elgamal_test.go�����������������������������0000644�0610621�0607500�00000003065�13172163317�027120� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package elgamal import ( "bytes" "crypto/rand" "math/big" "testing" ) // This is the 1024-bit MODP group from RFC 5114, section 2.1: const primeHex = "B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C69A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C013ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD7098488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708DF1FB2BC2E4A4371" const generatorHex = "A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507FD6406CFF14266D31266FEA1E5C41564B777E690F5504F213160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28AD662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24855E6EEB22B3B2E5" func fromHex(hex string) *big.Int { n, ok := new(big.Int).SetString(hex, 16) if !ok { panic("failed to parse hex number") } return n } func TestEncryptDecrypt(t *testing.T) { priv := &PrivateKey{ PublicKey: PublicKey{ G: fromHex(generatorHex), P: fromHex(primeHex), }, X: fromHex("42"), } priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P) message := []byte("hello world") c1, c2, err := Encrypt(rand.Reader, &priv.PublicKey, message) if err != nil { t.Errorf("error encrypting: %s", err) } message2, err := Decrypt(priv, c1, c2) if err != nil { t.Errorf("error decrypting: %s", err) } if !bytes.Equal(message2, message) { t.Errorf("decryption failed, got: %x, want: %x", message2, message) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/elgamal/elgamal.go����������������������������������0000644�0610621�0607500�00000006727�13172163317�026071� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package elgamal implements ElGamal encryption, suitable for OpenPGP, // as specified in "A Public-Key Cryptosystem and a Signature Scheme Based on // Discrete Logarithms," IEEE Transactions on Information Theory, v. IT-31, // n. 4, 1985, pp. 469-472. // // This form of ElGamal embeds PKCS#1 v1.5 padding, which may make it // unsuitable for other protocols. RSA should be used in preference in any // case. package elgamal // import "golang.org/x/crypto/openpgp/elgamal" import ( "crypto/rand" "crypto/subtle" "errors" "io" "math/big" ) // PublicKey represents an ElGamal public key. type PublicKey struct { G, P, Y *big.Int } // PrivateKey represents an ElGamal private key. type PrivateKey struct { PublicKey X *big.Int } // Encrypt encrypts the given message to the given public key. The result is a // pair of integers. Errors can result from reading random, or because msg is // too large to be encrypted to the public key. func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) { pLen := (pub.P.BitLen() + 7) / 8 if len(msg) > pLen-11 { err = errors.New("elgamal: message too long") return } // EM = 0x02 || PS || 0x00 || M em := make([]byte, pLen-1) em[0] = 2 ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):] err = nonZeroRandomBytes(ps, random) if err != nil { return } em[len(em)-len(msg)-1] = 0 copy(mm, msg) m := new(big.Int).SetBytes(em) k, err := rand.Int(random, pub.P) if err != nil { return } c1 = new(big.Int).Exp(pub.G, k, pub.P) s := new(big.Int).Exp(pub.Y, k, pub.P) c2 = s.Mul(s, m) c2.Mod(c2, pub.P) return } // Decrypt takes two integers, resulting from an ElGamal encryption, and // returns the plaintext of the message. An error can result only if the // ciphertext is invalid. Users should keep in mind that this is a padding // oracle and thus, if exposed to an adaptive chosen ciphertext attack, can // be used to break the cryptosystem. See ``Chosen Ciphertext Attacks // Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel // Bleichenbacher, Advances in Cryptology (Crypto '98), func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) { s := new(big.Int).Exp(c1, priv.X, priv.P) s.ModInverse(s, priv.P) s.Mul(s, c2) s.Mod(s, priv.P) em := s.Bytes() firstByteIsTwo := subtle.ConstantTimeByteEq(em[0], 2) // The remainder of the plaintext must be a string of non-zero random // octets, followed by a 0, followed by the message. // lookingForIndex: 1 iff we are still looking for the zero. // index: the offset of the first zero byte. var lookingForIndex, index int lookingForIndex = 1 for i := 1; i < len(em); i++ { equals0 := subtle.ConstantTimeByteEq(em[i], 0) index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index) lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex) } if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 { return nil, errors.New("elgamal: decryption error") } return em[index+1:], nil } // nonZeroRandomBytes fills the given slice with non-zero random octets. func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) { _, err = io.ReadFull(rand, s) if err != nil { return } for i := 0; i < len(s); i++ { for s[i] == 0 { _, err = io.ReadFull(rand, s[i:i+1]) if err != nil { return } } } return } �����������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/clearsign/������������������������������������������0000755�0610621�0607500�00000000000�13172163317�024471� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/clearsign/clearsign_test.go�������������������������0000644�0610621�0607500�00000015030�13172163317�030025� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package clearsign import ( "bytes" "golang.org/x/crypto/openpgp" "testing" ) func testParse(t *testing.T, input []byte, expected, expectedPlaintext string) { b, rest := Decode(input) if b == nil { t.Fatal("failed to decode clearsign message") } if !bytes.Equal(rest, []byte("trailing")) { t.Errorf("unexpected remaining bytes returned: %s", string(rest)) } if b.ArmoredSignature.Type != "PGP SIGNATURE" { t.Errorf("bad armor type, got:%s, want:PGP SIGNATURE", b.ArmoredSignature.Type) } if !bytes.Equal(b.Bytes, []byte(expected)) { t.Errorf("bad body, got:%x want:%x", b.Bytes, expected) } if !bytes.Equal(b.Plaintext, []byte(expectedPlaintext)) { t.Errorf("bad plaintext, got:%x want:%x", b.Plaintext, expectedPlaintext) } keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(signingKey)) if err != nil { t.Errorf("failed to parse public key: %s", err) } if _, err := openpgp.CheckDetachedSignature(keyring, bytes.NewBuffer(b.Bytes), b.ArmoredSignature.Body); err != nil { t.Errorf("failed to check signature: %s", err) } } func TestParse(t *testing.T) { testParse(t, clearsignInput, "Hello world\r\nline 2", "Hello world\nline 2\n") testParse(t, clearsignInput2, "\r\n\r\n(This message has a couple of blank lines at the start and end.)\r\n\r\n", "\n\n(This message has a couple of blank lines at the start and end.)\n\n\n") } func TestParseInvalid(t *testing.T) { if b, _ := Decode(clearsignInput3); b != nil { t.Fatal("decoded a bad clearsigned message without any error") } } func TestParseWithNoNewlineAtEnd(t *testing.T) { input := clearsignInput input = input[:len(input)-len("trailing")-1] b, rest := Decode(input) if b == nil { t.Fatal("failed to decode clearsign message") } if len(rest) > 0 { t.Errorf("unexpected remaining bytes returned: %s", string(rest)) } } var signingTests = []struct { in, signed, plaintext string }{ {"", "", ""}, {"a", "a", "a\n"}, {"a\n", "a", "a\n"}, {"-a\n", "-a", "-a\n"}, {"--a\nb", "--a\r\nb", "--a\nb\n"}, // leading whitespace {" a\n", " a", " a\n"}, {" a\n", " a", " a\n"}, // trailing whitespace (should be stripped) {"a \n", "a", "a\n"}, {"a ", "a", "a\n"}, // whitespace-only lines (should be stripped) {" \n", "", "\n"}, {" ", "", "\n"}, {"a\n \n \nb\n", "a\r\n\r\n\r\nb", "a\n\n\nb\n"}, } func TestSigning(t *testing.T) { keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(signingKey)) if err != nil { t.Errorf("failed to parse public key: %s", err) } for i, test := range signingTests { var buf bytes.Buffer plaintext, err := Encode(&buf, keyring[0].PrivateKey, nil) if err != nil { t.Errorf("#%d: error from Encode: %s", i, err) continue } if _, err := plaintext.Write([]byte(test.in)); err != nil { t.Errorf("#%d: error from Write: %s", i, err) continue } if err := plaintext.Close(); err != nil { t.Fatalf("#%d: error from Close: %s", i, err) continue } b, _ := Decode(buf.Bytes()) if b == nil { t.Errorf("#%d: failed to decode clearsign message", i) continue } if !bytes.Equal(b.Bytes, []byte(test.signed)) { t.Errorf("#%d: bad result, got:%x, want:%x", i, b.Bytes, test.signed) continue } if !bytes.Equal(b.Plaintext, []byte(test.plaintext)) { t.Errorf("#%d: bad result, got:%x, want:%x", i, b.Plaintext, test.plaintext) continue } if _, err := openpgp.CheckDetachedSignature(keyring, bytes.NewBuffer(b.Bytes), b.ArmoredSignature.Body); err != nil { t.Errorf("#%d: failed to check signature: %s", i, err) } } } var clearsignInput = []byte(` ;lasjlkfdsa -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello world line 2 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) iJwEAQECAAYFAk8kMuEACgkQO9o98PRieSpMsAQAhmY/vwmNpflrPgmfWsYhk5O8 pjnBUzZwqTDoDeINjZEoPDSpQAHGhjFjgaDx/Gj4fAl0dM4D0wuUEBb6QOrwflog 2A2k9kfSOMOtk0IH/H5VuFN1Mie9L/erYXjTQIptv9t9J7NoRBMU0QOOaFU0JaO9 MyTpno24AjIAGb+mH1U= =hIJ6 -----END PGP SIGNATURE----- trailing`) var clearsignInput2 = []byte(` asdlfkjasdlkfjsadf -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 (This message has a couple of blank lines at the start and end.) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (GNU/Linux) iJwEAQEIAAYFAlPpSREACgkQO9o98PRieSpZTAP+M8QUoCt/7Rf3YbXPcdzIL32v pt1I+cMNeopzfLy0u4ioEFi8s5VkwpL1AFmirvgViCwlf82inoRxzZRiW05JQ5LI ESEzeCoy2LIdRCQ2hcrG8pIUPzUO4TqO5D/dMbdHwNH4h5nNmGJUAEG6FpURlPm+ qZg6BaTvOxepqOxnhVU= =e+C6 -----END PGP SIGNATURE----- trailing`) var clearsignInput3 = []byte(` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 (This message was truncated.) `) var signingKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1.4.10 (GNU/Linux) lQHYBE2rFNoBBADFwqWQIW/DSqcB4yCQqnAFTJ27qS5AnB46ccAdw3u4Greeu3Bp idpoHdjULy7zSKlwR1EA873dO/k/e11Ml3dlAFUinWeejWaK2ugFP6JjiieSsrKn vWNicdCS4HTWn0X4sjl0ZiAygw6GNhqEQ3cpLeL0g8E9hnYzJKQ0LWJa0QARAQAB AAP/TB81EIo2VYNmTq0pK1ZXwUpxCrvAAIG3hwKjEzHcbQznsjNvPUihZ+NZQ6+X 0HCfPAdPkGDCLCb6NavcSW+iNnLTrdDnSI6+3BbIONqWWdRDYJhqZCkqmG6zqSfL IdkJgCw94taUg5BWP/AAeQrhzjChvpMQTVKQL5mnuZbUCeMCAN5qrYMP2S9iKdnk VANIFj7656ARKt/nf4CBzxcpHTyB8+d2CtPDKCmlJP6vL8t58Jmih+kHJMvC0dzn gr5f5+sCAOOe5gt9e0am7AvQWhdbHVfJU0TQJx+m2OiCJAqGTB1nvtBLHdJnfdC9 TnXXQ6ZXibqLyBies/xeY2sCKL5qtTMCAKnX9+9d/5yQxRyrQUHt1NYhaXZnJbHx q4ytu0eWz+5i68IYUSK69jJ1NWPM0T6SkqpB3KCAIv68VFm9PxqG1KmhSrQIVGVz dCBLZXmIuAQTAQIAIgUCTasU2gIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AA CgkQO9o98PRieSoLhgQAkLEZex02Qt7vGhZzMwuN0R22w3VwyYyjBx+fM3JFETy1 ut4xcLJoJfIaF5ZS38UplgakHG0FQ+b49i8dMij0aZmDqGxrew1m4kBfjXw9B/v+ eIqpODryb6cOSwyQFH0lQkXC040pjq9YqDsO5w0WYNXYKDnzRV0p4H1pweo2VDid AdgETasU2gEEAN46UPeWRqKHvA99arOxee38fBt2CI08iiWyI8T3J6ivtFGixSqV bRcPxYO/qLpVe5l84Nb3X71GfVXlc9hyv7CD6tcowL59hg1E/DC5ydI8K8iEpUmK /UnHdIY5h8/kqgGxkY/T/hgp5fRQgW1ZoZxLajVlMRZ8W4tFtT0DeA+JABEBAAEA A/0bE1jaaZKj6ndqcw86jd+QtD1SF+Cf21CWRNeLKnUds4FRRvclzTyUMuWPkUeX TaNNsUOFqBsf6QQ2oHUBBK4VCHffHCW4ZEX2cd6umz7mpHW6XzN4DECEzOVksXtc lUC1j4UB91DC/RNQqwX1IV2QLSwssVotPMPqhOi0ZLNY7wIA3n7DWKInxYZZ4K+6 rQ+POsz6brEoRHwr8x6XlHenq1Oki855pSa1yXIARoTrSJkBtn5oI+f8AzrnN0BN oyeQAwIA/7E++3HDi5aweWrViiul9cd3rcsS0dEnksPhvS0ozCJiHsq/6GFmy7J8 QSHZPteedBnZyNp5jR+H7cIfVN3KgwH/Skq4PsuPhDq5TKK6i8Pc1WW8MA6DXTdU nLkX7RGmMwjC0DBf7KWAlPjFaONAX3a8ndnz//fy1q7u2l9AZwrj1qa1iJ8EGAEC AAkFAk2rFNoCGwwACgkQO9o98PRieSo2/QP/WTzr4ioINVsvN1akKuekmEMI3LAp BfHwatufxxP1U+3Si/6YIk7kuPB9Hs+pRqCXzbvPRrI8NHZBmc8qIGthishdCYad AHcVnXjtxrULkQFGbGvhKURLvS9WnzD/m1K2zzwxzkPTzT9/Yf06O6Mal5AdugPL VrM0m72/jnpKo04= =zNCn -----END PGP PRIVATE KEY BLOCK----- ` ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/clearsign/clearsign.go������������������������������0000644�0610621�0607500�00000022673�13172163317�027001� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package clearsign generates and processes OpenPGP, clear-signed data. See // RFC 4880, section 7. // // Clearsigned messages are cryptographically signed, but the contents of the // message are kept in plaintext so that it can be read without special tools. package clearsign // import "golang.org/x/crypto/openpgp/clearsign" import ( "bufio" "bytes" "crypto" "hash" "io" "net/textproto" "strconv" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/packet" ) // A Block represents a clearsigned message. A signature on a Block can // be checked by passing Bytes into openpgp.CheckDetachedSignature. type Block struct { Headers textproto.MIMEHeader // Optional message headers Plaintext []byte // The original message text Bytes []byte // The signed message ArmoredSignature *armor.Block // The signature block } // start is the marker which denotes the beginning of a clearsigned message. var start = []byte("\n-----BEGIN PGP SIGNED MESSAGE-----") // dashEscape is prefixed to any lines that begin with a hyphen so that they // can't be confused with endText. var dashEscape = []byte("- ") // endText is a marker which denotes the end of the message and the start of // an armored signature. var endText = []byte("-----BEGIN PGP SIGNATURE-----") // end is a marker which denotes the end of the armored signature. var end = []byte("\n-----END PGP SIGNATURE-----") var crlf = []byte("\r\n") var lf = byte('\n') // getLine returns the first \r\n or \n delineated line from the given byte // array. The line does not include the \r\n or \n. The remainder of the byte // array (also not including the new line bytes) is also returned and this will // always be smaller than the original argument. func getLine(data []byte) (line, rest []byte) { i := bytes.Index(data, []byte{'\n'}) var j int if i < 0 { i = len(data) j = i } else { j = i + 1 if i > 0 && data[i-1] == '\r' { i-- } } return data[0:i], data[j:] } // Decode finds the first clearsigned message in data and returns it, as well // as the suffix of data which remains after the message. func Decode(data []byte) (b *Block, rest []byte) { // start begins with a newline. However, at the very beginning of // the byte array, we'll accept the start string without it. rest = data if bytes.HasPrefix(data, start[1:]) { rest = rest[len(start)-1:] } else if i := bytes.Index(data, start); i >= 0 { rest = rest[i+len(start):] } else { return nil, data } // Consume the start line. _, rest = getLine(rest) var line []byte b = &Block{ Headers: make(textproto.MIMEHeader), } // Next come a series of header lines. for { // This loop terminates because getLine's second result is // always smaller than its argument. if len(rest) == 0 { return nil, data } // An empty line marks the end of the headers. if line, rest = getLine(rest); len(line) == 0 { break } i := bytes.Index(line, []byte{':'}) if i == -1 { return nil, data } key, val := line[0:i], line[i+1:] key = bytes.TrimSpace(key) val = bytes.TrimSpace(val) b.Headers.Add(string(key), string(val)) } firstLine := true for { start := rest line, rest = getLine(rest) if len(line) == 0 && len(rest) == 0 { // No armored data was found, so this isn't a complete message. return nil, data } if bytes.Equal(line, endText) { // Back up to the start of the line because armor expects to see the // header line. rest = start break } // The final CRLF isn't included in the hash so we don't write it until // we've seen the next line. if firstLine { firstLine = false } else { b.Bytes = append(b.Bytes, crlf...) } if bytes.HasPrefix(line, dashEscape) { line = line[2:] } line = bytes.TrimRight(line, " \t") b.Bytes = append(b.Bytes, line...) b.Plaintext = append(b.Plaintext, line...) b.Plaintext = append(b.Plaintext, lf) } // We want to find the extent of the armored data (including any newlines at // the end). i := bytes.Index(rest, end) if i == -1 { return nil, data } i += len(end) for i < len(rest) && (rest[i] == '\r' || rest[i] == '\n') { i++ } armored := rest[:i] rest = rest[i:] var err error b.ArmoredSignature, err = armor.Decode(bytes.NewBuffer(armored)) if err != nil { return nil, data } return b, rest } // A dashEscaper is an io.WriteCloser which processes the body of a clear-signed // message. The clear-signed message is written to buffered and a hash, suitable // for signing, is maintained in h. // // When closed, an armored signature is created and written to complete the // message. type dashEscaper struct { buffered *bufio.Writer h hash.Hash hashType crypto.Hash atBeginningOfLine bool isFirstLine bool whitespace []byte byteBuf []byte // a one byte buffer to save allocations privateKey *packet.PrivateKey config *packet.Config } func (d *dashEscaper) Write(data []byte) (n int, err error) { for _, b := range data { d.byteBuf[0] = b if d.atBeginningOfLine { // The final CRLF isn't included in the hash so we have to wait // until this point (the start of the next line) before writing it. if !d.isFirstLine { d.h.Write(crlf) } d.isFirstLine = false } // Any whitespace at the end of the line has to be removed so we // buffer it until we find out whether there's more on this line. if b == ' ' || b == '\t' || b == '\r' { d.whitespace = append(d.whitespace, b) d.atBeginningOfLine = false continue } if d.atBeginningOfLine { // At the beginning of a line, hyphens have to be escaped. if b == '-' { // The signature isn't calculated over the dash-escaped text so // the escape is only written to buffered. if _, err = d.buffered.Write(dashEscape); err != nil { return } d.h.Write(d.byteBuf) d.atBeginningOfLine = false } else if b == '\n' { // Nothing to do because we delay writing CRLF to the hash. } else { d.h.Write(d.byteBuf) d.atBeginningOfLine = false } if err = d.buffered.WriteByte(b); err != nil { return } } else { if b == '\n' { // We got a raw \n. Drop any trailing whitespace and write a // CRLF. d.whitespace = d.whitespace[:0] // We delay writing CRLF to the hash until the start of the // next line. if err = d.buffered.WriteByte(b); err != nil { return } d.atBeginningOfLine = true } else { // Any buffered whitespace wasn't at the end of the line so // we need to write it out. if len(d.whitespace) > 0 { d.h.Write(d.whitespace) if _, err = d.buffered.Write(d.whitespace); err != nil { return } d.whitespace = d.whitespace[:0] } d.h.Write(d.byteBuf) if err = d.buffered.WriteByte(b); err != nil { return } } } } n = len(data) return } func (d *dashEscaper) Close() (err error) { if !d.atBeginningOfLine { if err = d.buffered.WriteByte(lf); err != nil { return } } sig := new(packet.Signature) sig.SigType = packet.SigTypeText sig.PubKeyAlgo = d.privateKey.PubKeyAlgo sig.Hash = d.hashType sig.CreationTime = d.config.Now() sig.IssuerKeyId = &d.privateKey.KeyId if err = sig.Sign(d.h, d.privateKey, d.config); err != nil { return } out, err := armor.Encode(d.buffered, "PGP SIGNATURE", nil) if err != nil { return } if err = sig.Serialize(out); err != nil { return } if err = out.Close(); err != nil { return } if err = d.buffered.Flush(); err != nil { return } return } // Encode returns a WriteCloser which will clear-sign a message with privateKey // and write it to w. If config is nil, sensible defaults are used. func Encode(w io.Writer, privateKey *packet.PrivateKey, config *packet.Config) (plaintext io.WriteCloser, err error) { if privateKey.Encrypted { return nil, errors.InvalidArgumentError("signing key is encrypted") } hashType := config.Hash() name := nameOfHash(hashType) if len(name) == 0 { return nil, errors.UnsupportedError("unknown hash type: " + strconv.Itoa(int(hashType))) } if !hashType.Available() { return nil, errors.UnsupportedError("unsupported hash type: " + strconv.Itoa(int(hashType))) } h := hashType.New() buffered := bufio.NewWriter(w) // start has a \n at the beginning that we don't want here. if _, err = buffered.Write(start[1:]); err != nil { return } if err = buffered.WriteByte(lf); err != nil { return } if _, err = buffered.WriteString("Hash: "); err != nil { return } if _, err = buffered.WriteString(name); err != nil { return } if err = buffered.WriteByte(lf); err != nil { return } if err = buffered.WriteByte(lf); err != nil { return } plaintext = &dashEscaper{ buffered: buffered, h: h, hashType: hashType, atBeginningOfLine: true, isFirstLine: true, byteBuf: make([]byte, 1), privateKey: privateKey, config: config, } return } // nameOfHash returns the OpenPGP name for the given hash, or the empty string // if the name isn't known. See RFC 4880, section 9.4. func nameOfHash(h crypto.Hash) string { switch h { case crypto.MD5: return "MD5" case crypto.SHA1: return "SHA1" case crypto.RIPEMD160: return "RIPEMD160" case crypto.SHA224: return "SHA224" case crypto.SHA256: return "SHA256" case crypto.SHA384: return "SHA384" case crypto.SHA512: return "SHA512" } return "" } ���������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/canonical_text_test.go������������������������������0000644�0610621�0607500�00000002262�13172163317�027105� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package openpgp import ( "bytes" "testing" ) type recordingHash struct { buf *bytes.Buffer } func (r recordingHash) Write(b []byte) (n int, err error) { return r.buf.Write(b) } func (r recordingHash) Sum(in []byte) []byte { return append(in, r.buf.Bytes()...) } func (r recordingHash) Reset() { panic("shouldn't be called") } func (r recordingHash) Size() int { panic("shouldn't be called") } func (r recordingHash) BlockSize() int { panic("shouldn't be called") } func testCanonicalText(t *testing.T, input, expected string) { r := recordingHash{bytes.NewBuffer(nil)} c := NewCanonicalTextHash(r) c.Write([]byte(input)) result := c.Sum(nil) if expected != string(result) { t.Errorf("input: %x got: %x want: %x", input, result, expected) } } func TestCanonicalText(t *testing.T) { testCanonicalText(t, "foo\n", "foo\r\n") testCanonicalText(t, "foo", "foo") testCanonicalText(t, "foo\r\n", "foo\r\n") testCanonicalText(t, "foo\r\nbar", "foo\r\nbar") testCanonicalText(t, "foo\r\nbar\n\n", "foo\r\nbar\r\n\r\n") } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/canonical_text.go�����������������������������������0000644�0610621�0607500�00000002167�13172163317�026052� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package openpgp import "hash" // NewCanonicalTextHash reformats text written to it into the canonical // form and then applies the hash h. See RFC 4880, section 5.2.1. func NewCanonicalTextHash(h hash.Hash) hash.Hash { return &canonicalTextHash{h, 0} } type canonicalTextHash struct { h hash.Hash s int } var newline = []byte{'\r', '\n'} func (cth *canonicalTextHash) Write(buf []byte) (int, error) { start := 0 for i, c := range buf { switch cth.s { case 0: if c == '\r' { cth.s = 1 } else if c == '\n' { cth.h.Write(buf[start:i]) cth.h.Write(newline) start = i + 1 } case 1: cth.s = 0 } } cth.h.Write(buf[start:]) return len(buf), nil } func (cth *canonicalTextHash) Sum(in []byte) []byte { return cth.h.Sum(in) } func (cth *canonicalTextHash) Reset() { cth.h.Reset() cth.s = 0 } func (cth *canonicalTextHash) Size() int { return cth.h.Size() } func (cth *canonicalTextHash) BlockSize() int { return cth.h.BlockSize() } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/armor/����������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023642� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/armor/encode.go�������������������������������������0000644�0610621�0607500�00000006500�13172163317�025427� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package armor import ( "encoding/base64" "io" ) var armorHeaderSep = []byte(": ") var blockEnd = []byte("\n=") var newline = []byte("\n") var armorEndOfLineOut = []byte("-----\n") // writeSlices writes its arguments to the given Writer. func writeSlices(out io.Writer, slices ...[]byte) (err error) { for _, s := range slices { _, err = out.Write(s) if err != nil { return err } } return } // lineBreaker breaks data across several lines, all of the same byte length // (except possibly the last). Lines are broken with a single '\n'. type lineBreaker struct { lineLength int line []byte used int out io.Writer haveWritten bool } func newLineBreaker(out io.Writer, lineLength int) *lineBreaker { return &lineBreaker{ lineLength: lineLength, line: make([]byte, lineLength), used: 0, out: out, } } func (l *lineBreaker) Write(b []byte) (n int, err error) { n = len(b) if n == 0 { return } if l.used == 0 && l.haveWritten { _, err = l.out.Write([]byte{'\n'}) if err != nil { return } } if l.used+len(b) < l.lineLength { l.used += copy(l.line[l.used:], b) return } l.haveWritten = true _, err = l.out.Write(l.line[0:l.used]) if err != nil { return } excess := l.lineLength - l.used l.used = 0 _, err = l.out.Write(b[0:excess]) if err != nil { return } _, err = l.Write(b[excess:]) return } func (l *lineBreaker) Close() (err error) { if l.used > 0 { _, err = l.out.Write(l.line[0:l.used]) if err != nil { return } } return } // encoding keeps track of a running CRC24 over the data which has been written // to it and outputs a OpenPGP checksum when closed, followed by an armor // trailer. // // It's built into a stack of io.Writers: // encoding -> base64 encoder -> lineBreaker -> out type encoding struct { out io.Writer breaker *lineBreaker b64 io.WriteCloser crc uint32 blockType []byte } func (e *encoding) Write(data []byte) (n int, err error) { e.crc = crc24(e.crc, data) return e.b64.Write(data) } func (e *encoding) Close() (err error) { err = e.b64.Close() if err != nil { return } e.breaker.Close() var checksumBytes [3]byte checksumBytes[0] = byte(e.crc >> 16) checksumBytes[1] = byte(e.crc >> 8) checksumBytes[2] = byte(e.crc) var b64ChecksumBytes [4]byte base64.StdEncoding.Encode(b64ChecksumBytes[:], checksumBytes[:]) return writeSlices(e.out, blockEnd, b64ChecksumBytes[:], newline, armorEnd, e.blockType, armorEndOfLine) } // Encode returns a WriteCloser which will encode the data written to it in // OpenPGP armor. func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err error) { bType := []byte(blockType) err = writeSlices(out, armorStart, bType, armorEndOfLineOut) if err != nil { return } for k, v := range headers { err = writeSlices(out, []byte(k), armorHeaderSep, []byte(v), newline) if err != nil { return } } _, err = out.Write(newline) if err != nil { return } e := &encoding{ out: out, breaker: newLineBreaker(out, 64), crc: crc24Init, blockType: bType, } e.b64 = base64.NewEncoder(base64.StdEncoding, e.breaker) return e, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/armor/armor_test.go���������������������������������0000644�0610621�0607500�00000006036�13172163317�026355� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package armor import ( "bytes" "hash/adler32" "io/ioutil" "testing" ) func TestDecodeEncode(t *testing.T) { buf := bytes.NewBuffer([]byte(armorExample1)) result, err := Decode(buf) if err != nil { t.Error(err) } expectedType := "PGP SIGNATURE" if result.Type != expectedType { t.Errorf("result.Type: got:%s want:%s", result.Type, expectedType) } if len(result.Header) != 1 { t.Errorf("len(result.Header): got:%d want:1", len(result.Header)) } v, ok := result.Header["Version"] if !ok || v != "GnuPG v1.4.10 (GNU/Linux)" { t.Errorf("result.Header: got:%#v", result.Header) } contents, err := ioutil.ReadAll(result.Body) if err != nil { t.Error(err) } if adler32.Checksum(contents) != 0x27b144be { t.Errorf("contents: got: %x", contents) } buf = bytes.NewBuffer(nil) w, err := Encode(buf, result.Type, result.Header) if err != nil { t.Error(err) } _, err = w.Write(contents) if err != nil { t.Error(err) } w.Close() if !bytes.Equal(buf.Bytes(), []byte(armorExample1)) { t.Errorf("got: %s\nwant: %s", string(buf.Bytes()), armorExample1) } } func TestLongHeader(t *testing.T) { buf := bytes.NewBuffer([]byte(armorLongLine)) result, err := Decode(buf) if err != nil { t.Error(err) return } value, ok := result.Header["Version"] if !ok { t.Errorf("missing Version header") } if value != longValueExpected { t.Errorf("got: %s want: %s", value, longValueExpected) } } const armorExample1 = `-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) iJwEAAECAAYFAk1Fv/0ACgkQo01+GMIMMbsYTwQAiAw+QAaNfY6WBdplZ/uMAccm 4g+81QPmTSGHnetSb6WBiY13kVzK4HQiZH8JSkmmroMLuGeJwsRTEL4wbjRyUKEt p1xwUZDECs234F1xiG5enc5SGlRtP7foLBz9lOsjx+LEcA4sTl5/2eZR9zyFZqWW TxRjs+fJCIFuo71xb1g= =/teI -----END PGP SIGNATURE-----` const armorLongLine = `-----BEGIN PGP SIGNATURE----- Version: 0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz iQEcBAABAgAGBQJMtFESAAoJEKsQXJGvOPsVj40H/1WW6jaMXv4BW+1ueDSMDwM8 kx1fLOXbVM5/Kn5LStZNt1jWWnpxdz7eq3uiqeCQjmqUoRde3YbB2EMnnwRbAhpp cacnAvy9ZQ78OTxUdNW1mhX5bS6q1MTEJnl+DcyigD70HG/yNNQD7sOPMdYQw0TA byQBwmLwmTsuZsrYqB68QyLHI+DUugn+kX6Hd2WDB62DKa2suoIUIHQQCd/ofwB3 WfCYInXQKKOSxu2YOg2Eb4kLNhSMc1i9uKUWAH+sdgJh7NBgdoE4MaNtBFkHXRvv okWuf3+xA9ksp1npSY/mDvgHijmjvtpRDe6iUeqfCn8N9u9CBg8geANgaG8+QA4= =wfQG -----END PGP SIGNATURE-----` const longValueExpected = "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/openpgp/armor/armor.go��������������������������������������0000644�0610621�0607500�00000011642�13172163317�025315� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package armor implements OpenPGP ASCII Armor, see RFC 4880. OpenPGP Armor is // very similar to PEM except that it has an additional CRC checksum. package armor // import "golang.org/x/crypto/openpgp/armor" import ( "bufio" "bytes" "encoding/base64" "golang.org/x/crypto/openpgp/errors" "io" ) // A Block represents an OpenPGP armored structure. // // The encoded form is: // -----BEGIN Type----- // Headers // // base64-encoded Bytes // '=' base64 encoded checksum // -----END Type----- // where Headers is a possibly empty sequence of Key: Value lines. // // Since the armored data can be very large, this package presents a streaming // interface. type Block struct { Type string // The type, taken from the preamble (i.e. "PGP SIGNATURE"). Header map[string]string // Optional headers. Body io.Reader // A Reader from which the contents can be read lReader lineReader oReader openpgpReader } var ArmorCorrupt error = errors.StructuralError("armor invalid") const crc24Init = 0xb704ce const crc24Poly = 0x1864cfb const crc24Mask = 0xffffff // crc24 calculates the OpenPGP checksum as specified in RFC 4880, section 6.1 func crc24(crc uint32, d []byte) uint32 { for _, b := range d { crc ^= uint32(b) << 16 for i := 0; i < 8; i++ { crc <<= 1 if crc&0x1000000 != 0 { crc ^= crc24Poly } } } return crc } var armorStart = []byte("-----BEGIN ") var armorEnd = []byte("-----END ") var armorEndOfLine = []byte("-----") // lineReader wraps a line based reader. It watches for the end of an armor // block and records the expected CRC value. type lineReader struct { in *bufio.Reader buf []byte eof bool crc uint32 } func (l *lineReader) Read(p []byte) (n int, err error) { if l.eof { return 0, io.EOF } if len(l.buf) > 0 { n = copy(p, l.buf) l.buf = l.buf[n:] return } line, isPrefix, err := l.in.ReadLine() if err != nil { return } if isPrefix { return 0, ArmorCorrupt } if len(line) == 5 && line[0] == '=' { // This is the checksum line var expectedBytes [3]byte var m int m, err = base64.StdEncoding.Decode(expectedBytes[0:], line[1:]) if m != 3 || err != nil { return } l.crc = uint32(expectedBytes[0])<<16 | uint32(expectedBytes[1])<<8 | uint32(expectedBytes[2]) line, _, err = l.in.ReadLine() if err != nil && err != io.EOF { return } if !bytes.HasPrefix(line, armorEnd) { return 0, ArmorCorrupt } l.eof = true return 0, io.EOF } if len(line) > 96 { return 0, ArmorCorrupt } n = copy(p, line) bytesToSave := len(line) - n if bytesToSave > 0 { if cap(l.buf) < bytesToSave { l.buf = make([]byte, 0, bytesToSave) } l.buf = l.buf[0:bytesToSave] copy(l.buf, line[n:]) } return } // openpgpReader passes Read calls to the underlying base64 decoder, but keeps // a running CRC of the resulting data and checks the CRC against the value // found by the lineReader at EOF. type openpgpReader struct { lReader *lineReader b64Reader io.Reader currentCRC uint32 } func (r *openpgpReader) Read(p []byte) (n int, err error) { n, err = r.b64Reader.Read(p) r.currentCRC = crc24(r.currentCRC, p[:n]) if err == io.EOF { if r.lReader.crc != uint32(r.currentCRC&crc24Mask) { return 0, ArmorCorrupt } } return } // Decode reads a PGP armored block from the given Reader. It will ignore // leading garbage. If it doesn't find a block, it will return nil, io.EOF. The // given Reader is not usable after calling this function: an arbitrary amount // of data may have been read past the end of the block. func Decode(in io.Reader) (p *Block, err error) { r := bufio.NewReaderSize(in, 100) var line []byte ignoreNext := false TryNextBlock: p = nil // Skip leading garbage for { ignoreThis := ignoreNext line, ignoreNext, err = r.ReadLine() if err != nil { return } if ignoreNext || ignoreThis { continue } line = bytes.TrimSpace(line) if len(line) > len(armorStart)+len(armorEndOfLine) && bytes.HasPrefix(line, armorStart) { break } } p = new(Block) p.Type = string(line[len(armorStart) : len(line)-len(armorEndOfLine)]) p.Header = make(map[string]string) nextIsContinuation := false var lastKey string // Read headers for { isContinuation := nextIsContinuation line, nextIsContinuation, err = r.ReadLine() if err != nil { p = nil return } if isContinuation { p.Header[lastKey] += string(line) continue } line = bytes.TrimSpace(line) if len(line) == 0 { break } i := bytes.Index(line, []byte(": ")) if i == -1 { goto TryNextBlock } lastKey = string(line[:i]) p.Header[lastKey] = string(line[i+2:]) } p.lReader.in = r p.oReader.currentCRC = crc24Init p.oReader.lReader = &p.lReader p.oReader.b64Reader = base64.NewDecoder(base64.StdEncoding, &p.lReader) p.Body = &p.oReader return } ����������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ocsp/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022016� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ocsp/ocsp_test.go�������������������������������������������0000644�0610621�0607500�00000137132�13172163317�024357� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package ocsp import ( "bytes" "crypto" "crypto/sha1" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/hex" "math/big" "reflect" "testing" "time" ) func TestOCSPDecode(t *testing.T) { responseBytes, _ := hex.DecodeString(ocspResponseHex) resp, err := ParseResponse(responseBytes, nil) if err != nil { t.Fatal(err) } responderCert, _ := hex.DecodeString(startComResponderCertHex) responder, err := x509.ParseCertificate(responderCert) if err != nil { t.Fatal(err) } expected := Response{ Status: Good, SerialNumber: big.NewInt(0x1d0fa), RevocationReason: Unspecified, ThisUpdate: time.Date(2010, 7, 7, 15, 1, 5, 0, time.UTC), NextUpdate: time.Date(2010, 7, 7, 18, 35, 17, 0, time.UTC), RawResponderName: responder.RawSubject, } if !reflect.DeepEqual(resp.ThisUpdate, expected.ThisUpdate) { t.Errorf("resp.ThisUpdate: got %d, want %d", resp.ThisUpdate, expected.ThisUpdate) } if !reflect.DeepEqual(resp.NextUpdate, expected.NextUpdate) { t.Errorf("resp.NextUpdate: got %d, want %d", resp.NextUpdate, expected.NextUpdate) } if resp.Status != expected.Status { t.Errorf("resp.Status: got %d, want %d", resp.Status, expected.Status) } if resp.SerialNumber.Cmp(expected.SerialNumber) != 0 { t.Errorf("resp.SerialNumber: got %x, want %x", resp.SerialNumber, expected.SerialNumber) } if resp.RevocationReason != expected.RevocationReason { t.Errorf("resp.RevocationReason: got %d, want %d", resp.RevocationReason, expected.RevocationReason) } if !bytes.Equal(resp.RawResponderName, expected.RawResponderName) { t.Errorf("resp.RawResponderName: got %x, want %x", resp.RawResponderName, expected.RawResponderName) } if !bytes.Equal(resp.ResponderKeyHash, expected.ResponderKeyHash) { t.Errorf("resp.ResponderKeyHash: got %x, want %x", resp.ResponderKeyHash, expected.ResponderKeyHash) } } func TestOCSPDecodeWithoutCert(t *testing.T) { responseBytes, _ := hex.DecodeString(ocspResponseWithoutCertHex) _, err := ParseResponse(responseBytes, nil) if err != nil { t.Error(err) } } func TestOCSPDecodeWithExtensions(t *testing.T) { responseBytes, _ := hex.DecodeString(ocspResponseWithCriticalExtensionHex) _, err := ParseResponse(responseBytes, nil) if err == nil { t.Error(err) } responseBytes, _ = hex.DecodeString(ocspResponseWithExtensionHex) response, err := ParseResponse(responseBytes, nil) if err != nil { t.Fatal(err) } if len(response.Extensions) != 1 { t.Errorf("len(response.Extensions): got %v, want %v", len(response.Extensions), 1) } extensionBytes := response.Extensions[0].Value expectedBytes, _ := hex.DecodeString(ocspExtensionValueHex) if !bytes.Equal(extensionBytes, expectedBytes) { t.Errorf("response.Extensions[0]: got %x, want %x", extensionBytes, expectedBytes) } } func TestOCSPSignature(t *testing.T) { issuerCert, _ := hex.DecodeString(startComHex) issuer, err := x509.ParseCertificate(issuerCert) if err != nil { t.Fatal(err) } response, _ := hex.DecodeString(ocspResponseHex) if _, err := ParseResponse(response, issuer); err != nil { t.Error(err) } } func TestOCSPRequest(t *testing.T) { leafCert, _ := hex.DecodeString(leafCertHex) cert, err := x509.ParseCertificate(leafCert) if err != nil { t.Fatal(err) } issuerCert, _ := hex.DecodeString(issuerCertHex) issuer, err := x509.ParseCertificate(issuerCert) if err != nil { t.Fatal(err) } request, err := CreateRequest(cert, issuer, nil) if err != nil { t.Fatal(err) } expectedBytes, _ := hex.DecodeString(ocspRequestHex) if !bytes.Equal(request, expectedBytes) { t.Errorf("request: got %x, wanted %x", request, expectedBytes) } decodedRequest, err := ParseRequest(expectedBytes) if err != nil { t.Fatal(err) } if decodedRequest.HashAlgorithm != crypto.SHA1 { t.Errorf("request.HashAlgorithm: got %v, want %v", decodedRequest.HashAlgorithm, crypto.SHA1) } var publicKeyInfo struct { Algorithm pkix.AlgorithmIdentifier PublicKey asn1.BitString } _, err = asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo) if err != nil { t.Fatal(err) } h := sha1.New() h.Write(publicKeyInfo.PublicKey.RightAlign()) issuerKeyHash := h.Sum(nil) h.Reset() h.Write(issuer.RawSubject) issuerNameHash := h.Sum(nil) if got := decodedRequest.IssuerKeyHash; !bytes.Equal(got, issuerKeyHash) { t.Errorf("request.IssuerKeyHash: got %x, want %x", got, issuerKeyHash) } if got := decodedRequest.IssuerNameHash; !bytes.Equal(got, issuerNameHash) { t.Errorf("request.IssuerKeyHash: got %x, want %x", got, issuerNameHash) } if got := decodedRequest.SerialNumber; got.Cmp(cert.SerialNumber) != 0 { t.Errorf("request.SerialNumber: got %x, want %x", got, cert.SerialNumber) } marshaledRequest, err := decodedRequest.Marshal() if err != nil { t.Fatal(err) } if bytes.Compare(expectedBytes, marshaledRequest) != 0 { t.Errorf( "Marshaled request doesn't match expected: wanted %x, got %x", expectedBytes, marshaledRequest, ) } } func TestOCSPResponse(t *testing.T) { leafCert, _ := hex.DecodeString(leafCertHex) leaf, err := x509.ParseCertificate(leafCert) if err != nil { t.Fatal(err) } issuerCert, _ := hex.DecodeString(issuerCertHex) issuer, err := x509.ParseCertificate(issuerCert) if err != nil { t.Fatal(err) } responderCert, _ := hex.DecodeString(responderCertHex) responder, err := x509.ParseCertificate(responderCert) if err != nil { t.Fatal(err) } responderPrivateKeyDER, _ := hex.DecodeString(responderPrivateKeyHex) responderPrivateKey, err := x509.ParsePKCS1PrivateKey(responderPrivateKeyDER) if err != nil { t.Fatal(err) } extensionBytes, _ := hex.DecodeString(ocspExtensionValueHex) extensions := []pkix.Extension{ pkix.Extension{ Id: ocspExtensionOID, Critical: false, Value: extensionBytes, }, } thisUpdate := time.Date(2010, 7, 7, 15, 1, 5, 0, time.UTC) nextUpdate := time.Date(2010, 7, 7, 18, 35, 17, 0, time.UTC) template := Response{ Status: Revoked, SerialNumber: leaf.SerialNumber, ThisUpdate: thisUpdate, NextUpdate: nextUpdate, RevokedAt: thisUpdate, RevocationReason: KeyCompromise, Certificate: responder, ExtraExtensions: extensions, } template.IssuerHash = crypto.MD5 _, err = CreateResponse(issuer, responder, template, responderPrivateKey) if err == nil { t.Fatal("CreateResponse didn't fail with non-valid template.IssuerHash value crypto.MD5") } testCases := []struct { name string issuerHash crypto.Hash }{ {"Zero value", 0}, {"crypto.SHA1", crypto.SHA1}, {"crypto.SHA256", crypto.SHA256}, {"crypto.SHA384", crypto.SHA384}, {"crypto.SHA512", crypto.SHA512}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { template.IssuerHash = tc.issuerHash responseBytes, err := CreateResponse(issuer, responder, template, responderPrivateKey) if err != nil { t.Fatalf("CreateResponse failed: %s", err) } resp, err := ParseResponse(responseBytes, nil) if err != nil { t.Fatalf("ParseResponse failed: %s", err) } if !reflect.DeepEqual(resp.ThisUpdate, template.ThisUpdate) { t.Errorf("resp.ThisUpdate: got %d, want %d", resp.ThisUpdate, template.ThisUpdate) } if !reflect.DeepEqual(resp.NextUpdate, template.NextUpdate) { t.Errorf("resp.NextUpdate: got %d, want %d", resp.NextUpdate, template.NextUpdate) } if !reflect.DeepEqual(resp.RevokedAt, template.RevokedAt) { t.Errorf("resp.RevokedAt: got %d, want %d", resp.RevokedAt, template.RevokedAt) } if !reflect.DeepEqual(resp.Extensions, template.ExtraExtensions) { t.Errorf("resp.Extensions: got %v, want %v", resp.Extensions, template.ExtraExtensions) } delay := time.Since(resp.ProducedAt) if delay < -time.Hour || delay > time.Hour { t.Errorf("resp.ProducedAt: got %s, want close to current time (%s)", resp.ProducedAt, time.Now()) } if resp.Status != template.Status { t.Errorf("resp.Status: got %d, want %d", resp.Status, template.Status) } if resp.SerialNumber.Cmp(template.SerialNumber) != 0 { t.Errorf("resp.SerialNumber: got %x, want %x", resp.SerialNumber, template.SerialNumber) } if resp.RevocationReason != template.RevocationReason { t.Errorf("resp.RevocationReason: got %d, want %d", resp.RevocationReason, template.RevocationReason) } expectedHash := tc.issuerHash if tc.issuerHash == 0 { expectedHash = crypto.SHA1 } if resp.IssuerHash != expectedHash { t.Errorf("resp.IssuerHash: got %d, want %d", resp.IssuerHash, expectedHash) } }) } } func TestErrorResponse(t *testing.T) { responseBytes, _ := hex.DecodeString(errorResponseHex) _, err := ParseResponse(responseBytes, nil) respErr, ok := err.(ResponseError) if !ok { t.Fatalf("expected ResponseError from ParseResponse but got %#v", err) } if respErr.Status != Malformed { t.Fatalf("expected Malformed status from ParseResponse but got %d", respErr.Status) } } func TestOCSPDecodeMultiResponse(t *testing.T) { inclCert, _ := hex.DecodeString(ocspMultiResponseCertHex) cert, err := x509.ParseCertificate(inclCert) if err != nil { t.Fatal(err) } responseBytes, _ := hex.DecodeString(ocspMultiResponseHex) resp, err := ParseResponseForCert(responseBytes, cert, nil) if err != nil { t.Fatal(err) } if resp.SerialNumber.Cmp(cert.SerialNumber) != 0 { t.Errorf("resp.SerialNumber: got %x, want %x", resp.SerialNumber, cert.SerialNumber) } } func TestOCSPDecodeMultiResponseWithoutMatchingCert(t *testing.T) { wrongCert, _ := hex.DecodeString(startComHex) cert, err := x509.ParseCertificate(wrongCert) if err != nil { t.Fatal(err) } responseBytes, _ := hex.DecodeString(ocspMultiResponseHex) _, err = ParseResponseForCert(responseBytes, cert, nil) want := ParseError("no response matching the supplied certificate") if err != want { t.Errorf("err: got %q, want %q", err, want) } } // This OCSP response was taken from Thawte's public OCSP responder. // To recreate: // $ openssl s_client -tls1 -showcerts -servername www.google.com -connect www.google.com:443 // Copy and paste the first certificate into /tmp/cert.crt and the second into // /tmp/intermediate.crt // $ openssl ocsp -issuer /tmp/intermediate.crt -cert /tmp/cert.crt -url http://ocsp.thawte.com -resp_text -respout /tmp/ocsp.der // Then hex encode the result: // $ python -c 'print file("/tmp/ocsp.der", "r").read().encode("hex")' const ocspResponseHex = "308206bc0a0100a08206b5308206b106092b0601050507300101048206a23082069e3081" + "c9a14e304c310b300906035504061302494c31163014060355040a130d5374617274436f" + "6d204c74642e312530230603550403131c5374617274436f6d20436c6173732031204f43" + "5350205369676e6572180f32303130303730373137333531375a30663064303c30090605" + "2b0e03021a050004146568874f40750f016a3475625e1f5c93e5a26d580414eb4234d098" + "b0ab9ff41b6b08f7cc642eef0e2c45020301d0fa8000180f323031303037303731353031" + "30355aa011180f32303130303730373138333531375a300d06092a864886f70d01010505" + "000382010100ab557ff070d1d7cebbb5f0ec91a15c3fed22eb2e1b8244f1b84545f013a4" + "fb46214c5e3fbfbebb8a56acc2b9db19f68fd3c3201046b3824d5ba689f99864328710cb" + "467195eb37d84f539e49f859316b32964dc3e47e36814ce94d6c56dd02733b1d0802f7ff" + "4eebdbbd2927dcf580f16cbc290f91e81b53cb365e7223f1d6e20a88ea064104875e0145" + "672b20fc14829d51ca122f5f5d77d3ad6c83889c55c7dc43680ba2fe3cef8b05dbcabdc0" + "d3e09aaf9725597f8c858c2fa38c0d6aed2e6318194420dd1a1137445d13e1c97ab47896" + "17a4e08925f46f867b72e3a4dc1f08cb870b2b0717f7207faa0ac512e628a029aba7457a" + "e63dcf3281e2162d9349a08204ba308204b6308204b23082039aa003020102020101300d" + "06092a864886f70d010105050030818c310b300906035504061302494c31163014060355" + "040a130d5374617274436f6d204c74642e312b3029060355040b13225365637572652044" + "69676974616c204365727469666963617465205369676e696e6731383036060355040313" + "2f5374617274436f6d20436c6173732031205072696d61727920496e7465726d65646961" + "746520536572766572204341301e170d3037313032353030323330365a170d3132313032" + "333030323330365a304c310b300906035504061302494c31163014060355040a130d5374" + "617274436f6d204c74642e312530230603550403131c5374617274436f6d20436c617373" + "2031204f435350205369676e657230820122300d06092a864886f70d0101010500038201" + "0f003082010a0282010100b9561b4c45318717178084e96e178df2255e18ed8d8ecc7c2b" + "7b51a6c1c2e6bf0aa3603066f132fe10ae97b50e99fa24b83fc53dd2777496387d14e1c3" + "a9b6a4933e2ac12413d085570a95b8147414a0bc007c7bcf222446ef7f1a156d7ea1c577" + "fc5f0facdfd42eb0f5974990cb2f5cefebceef4d1bdc7ae5c1075c5a99a93171f2b0845b" + "4ff0864e973fcfe32f9d7511ff87a3e943410c90a4493a306b6944359340a9ca96f02b66" + "ce67f028df2980a6aaee8d5d5d452b8b0eb93f923cc1e23fcccbdbe7ffcb114d08fa7a6a" + "3c404f825d1a0e715935cf623a8c7b59670014ed0622f6089a9447a7a19010f7fe58f841" + "29a2765ea367824d1c3bb2fda308530203010001a382015c30820158300c0603551d1301" + "01ff04023000300b0603551d0f0404030203a8301e0603551d250417301506082b060105" + "0507030906092b0601050507300105301d0603551d0e0416041445e0a36695414c5dd449" + "bc00e33cdcdbd2343e173081a80603551d230481a030819d8014eb4234d098b0ab9ff41b" + "6b08f7cc642eef0e2c45a18181a47f307d310b300906035504061302494c311630140603" + "55040a130d5374617274436f6d204c74642e312b3029060355040b132253656375726520" + "4469676974616c204365727469666963617465205369676e696e67312930270603550403" + "13205374617274436f6d2043657274696669636174696f6e20417574686f726974798201" + "0a30230603551d12041c301a8618687474703a2f2f7777772e737461727473736c2e636f" + "6d2f302c06096086480186f842010d041f161d5374617274436f6d205265766f63617469" + "6f6e20417574686f72697479300d06092a864886f70d01010505000382010100182d2215" + "8f0fc0291324fa8574c49bb8ff2835085adcbf7b7fc4191c397ab6951328253fffe1e5ec" + "2a7da0d50fca1a404e6968481366939e666c0a6209073eca57973e2fefa9ed1718e8176f" + "1d85527ff522c08db702e3b2b180f1cbff05d98128252cf0f450f7dd2772f4188047f19d" + "c85317366f94bc52d60f453a550af58e308aaab00ced33040b62bf37f5b1ab2a4f7f0f80" + "f763bf4d707bc8841d7ad9385ee2a4244469260b6f2bf085977af9074796048ecc2f9d48" + "a1d24ce16e41a9941568fec5b42771e118f16c106a54ccc339a4b02166445a167902e75e" + "6d8620b0825dcd18a069b90fd851d10fa8effd409deec02860d26d8d833f304b10669b42" const startComResponderCertHex = "308204b23082039aa003020102020101300d06092a864886f70d010105050030818c310b" + "300906035504061302494c31163014060355040a130d5374617274436f6d204c74642e31" + "2b3029060355040b1322536563757265204469676974616c204365727469666963617465" + "205369676e696e67313830360603550403132f5374617274436f6d20436c617373203120" + "5072696d61727920496e7465726d65646961746520536572766572204341301e170d3037" + "313032353030323330365a170d3132313032333030323330365a304c310b300906035504" + "061302494c31163014060355040a130d5374617274436f6d204c74642e31253023060355" + "0403131c5374617274436f6d20436c6173732031204f435350205369676e657230820122" + "300d06092a864886f70d01010105000382010f003082010a0282010100b9561b4c453187" + "17178084e96e178df2255e18ed8d8ecc7c2b7b51a6c1c2e6bf0aa3603066f132fe10ae97" + "b50e99fa24b83fc53dd2777496387d14e1c3a9b6a4933e2ac12413d085570a95b8147414" + "a0bc007c7bcf222446ef7f1a156d7ea1c577fc5f0facdfd42eb0f5974990cb2f5cefebce" + "ef4d1bdc7ae5c1075c5a99a93171f2b0845b4ff0864e973fcfe32f9d7511ff87a3e94341" + "0c90a4493a306b6944359340a9ca96f02b66ce67f028df2980a6aaee8d5d5d452b8b0eb9" + "3f923cc1e23fcccbdbe7ffcb114d08fa7a6a3c404f825d1a0e715935cf623a8c7b596700" + "14ed0622f6089a9447a7a19010f7fe58f84129a2765ea367824d1c3bb2fda30853020301" + "0001a382015c30820158300c0603551d130101ff04023000300b0603551d0f0404030203" + "a8301e0603551d250417301506082b0601050507030906092b0601050507300105301d06" + "03551d0e0416041445e0a36695414c5dd449bc00e33cdcdbd2343e173081a80603551d23" + "0481a030819d8014eb4234d098b0ab9ff41b6b08f7cc642eef0e2c45a18181a47f307d31" + "0b300906035504061302494c31163014060355040a130d5374617274436f6d204c74642e" + "312b3029060355040b1322536563757265204469676974616c2043657274696669636174" + "65205369676e696e6731293027060355040313205374617274436f6d2043657274696669" + "636174696f6e20417574686f7269747982010a30230603551d12041c301a861868747470" + "3a2f2f7777772e737461727473736c2e636f6d2f302c06096086480186f842010d041f16" + "1d5374617274436f6d205265766f636174696f6e20417574686f72697479300d06092a86" + "4886f70d01010505000382010100182d22158f0fc0291324fa8574c49bb8ff2835085adc" + "bf7b7fc4191c397ab6951328253fffe1e5ec2a7da0d50fca1a404e6968481366939e666c" + "0a6209073eca57973e2fefa9ed1718e8176f1d85527ff522c08db702e3b2b180f1cbff05" + "d98128252cf0f450f7dd2772f4188047f19dc85317366f94bc52d60f453a550af58e308a" + "aab00ced33040b62bf37f5b1ab2a4f7f0f80f763bf4d707bc8841d7ad9385ee2a4244469" + "260b6f2bf085977af9074796048ecc2f9d48a1d24ce16e41a9941568fec5b42771e118f1" + "6c106a54ccc339a4b02166445a167902e75e6d8620b0825dcd18a069b90fd851d10fa8ef" + "fd409deec02860d26d8d833f304b10669b42" const startComHex = "308206343082041ca003020102020118300d06092a864886f70d0101050500307d310b30" + "0906035504061302494c31163014060355040a130d5374617274436f6d204c74642e312b" + "3029060355040b1322536563757265204469676974616c20436572746966696361746520" + "5369676e696e6731293027060355040313205374617274436f6d20436572746966696361" + "74696f6e20417574686f72697479301e170d3037313032343230353431375a170d313731" + "3032343230353431375a30818c310b300906035504061302494c31163014060355040a13" + "0d5374617274436f6d204c74642e312b3029060355040b13225365637572652044696769" + "74616c204365727469666963617465205369676e696e67313830360603550403132f5374" + "617274436f6d20436c6173732031205072696d61727920496e7465726d65646961746520" + "53657276657220434130820122300d06092a864886f70d01010105000382010f00308201" + "0a0282010100b689c6acef09527807ac9263d0f44418188480561f91aee187fa3250b4d3" + "4706f0e6075f700e10f71dc0ce103634855a0f92ac83c6ac58523fba38e8fce7a724e240" + "a60876c0926e9e2a6d4d3f6e61200adb59ded27d63b33e46fefa215118d7cd30a6ed076e" + "3b7087b4f9faebee823c056f92f7a4dc0a301e9373fe07cad75f809d225852ae06da8b87" + "2369b0e42ad8ea83d2bdf371db705a280faf5a387045123f304dcd3baf17e50fcba0a95d" + "48aab16150cb34cd3c5cc30be810c08c9bf0030362feb26c3e720eee1c432ac9480e5739" + "c43121c810c12c87fe5495521f523c31129b7fe7c0a0a559d5e28f3ef0d5a8e1d77031a9" + "c4b3cfaf6d532f06f4a70203010001a38201ad308201a9300f0603551d130101ff040530" + "030101ff300e0603551d0f0101ff040403020106301d0603551d0e04160414eb4234d098" + "b0ab9ff41b6b08f7cc642eef0e2c45301f0603551d230418301680144e0bef1aa4405ba5" + "17698730ca346843d041aef2306606082b06010505070101045a3058302706082b060105" + "05073001861b687474703a2f2f6f6373702e737461727473736c2e636f6d2f6361302d06" + "082b060105050730028621687474703a2f2f7777772e737461727473736c2e636f6d2f73" + "667363612e637274305b0603551d1f045430523027a025a0238621687474703a2f2f7777" + "772e737461727473736c2e636f6d2f73667363612e63726c3027a025a023862168747470" + "3a2f2f63726c2e737461727473736c2e636f6d2f73667363612e63726c3081800603551d" + "20047930773075060b2b0601040181b5370102013066302e06082b060105050702011622" + "687474703a2f2f7777772e737461727473736c2e636f6d2f706f6c6963792e7064663034" + "06082b060105050702011628687474703a2f2f7777772e737461727473736c2e636f6d2f" + "696e7465726d6564696174652e706466300d06092a864886f70d01010505000382020100" + "2109493ea5886ee00b8b48da314d8ff75657a2e1d36257e9b556f38545753be5501f048b" + "e6a05a3ee700ae85d0fbff200364cbad02e1c69172f8a34dd6dee8cc3fa18aa2e37c37a7" + "c64f8f35d6f4d66e067bdd21d9cf56ffcb302249fe8904f385e5aaf1e71fe875904dddf9" + "46f74234f745580c110d84b0c6da5d3ef9019ee7e1da5595be741c7bfc4d144fac7e5547" + "7d7bf4a50d491e95e8f712c1ccff76a62547d0f37535be97b75816ebaa5c786fec5330af" + "ea044dcca902e3f0b60412f630b1113d904e5664d7dc3c435f7339ef4baf87ebf6fe6888" + "4472ead207c669b0c1a18bef1749d761b145485f3b2021e95bb2ccf4d7e931f50b15613b" + "7a94e3ebd9bc7f94ae6ae3626296a8647cb887f399327e92a252bebbf865cfc9f230fc8b" + "c1c2a696d75f89e15c3480f58f47072fb491bfb1a27e5f4b5ad05b9f248605515a690365" + "434971c5e06f94346bf61bd8a9b04c7e53eb8f48dfca33b548fa364a1a53a6330cd089cd" + "4915cd89313c90c072d7654b52358a461144b93d8e2865a63e799e5c084429adb035112e" + "214eb8d2e7103e5d8483b3c3c2e4d2c6fd094b7409ddf1b3d3193e800da20b19f038e7c5" + "c2afe223db61e29d5c6e2089492e236ab262c145b49faf8ba7f1223bf87de290d07a19fb" + "4a4ce3d27d5f4a8303ed27d6239e6b8db459a2d9ef6c8229dd75193c3f4c108defbb7527" + "d2ae83a7a8ce5ba7" const ocspResponseWithoutCertHex = "308201d40a0100a08201cd308201c906092b0601050507300101048201ba3082" + "01b630819fa2160414884451ff502a695e2d88f421bad90cf2cecbea7c180f3230313330" + "3631383037323434335a30743072304a300906052b0e03021a0500041448b60d38238df8" + "456e4ee5843ea394111802979f0414884451ff502a695e2d88f421bad90cf2cecbea7c02" + "1100f78b13b946fc9635d8ab49de9d2148218000180f3230313330363138303732343433" + "5aa011180f32303133303632323037323434335a300d06092a864886f70d010105050003" + "82010100103e18b3d297a5e7a6c07a4fc52ac46a15c0eba96f3be17f0ffe84de5b8c8e05" + "5a8f577586a849dc4abd6440eb6fedde4622451e2823c1cbf3558b4e8184959c9fe96eff" + "8bc5f95866c58c6d087519faabfdae37e11d9874f1bc0db292208f645dd848185e4dd38b" + "6a8547dfa7b74d514a8470015719064d35476b95bebb03d4d2845c5ca15202d2784878f2" + "0f904c24f09736f044609e9c271381713400e563023d212db422236440c6f377bbf24b2b" + "9e7dec8698e36a8df68b7592ad3489fb2937afb90eb85d2aa96b81c94c25057dbd4759d9" + "20a1a65c7f0b6427a224b3c98edd96b9b61f706099951188b0289555ad30a216fb774651" + "5a35fca2e054dfa8" // PKIX nonce extension var ocspExtensionOID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1, 2} var ocspExtensionValueHex = "0403000000" const ocspResponseWithCriticalExtensionHex = "308204fe0a0100a08204f7308204f306092b0601050507300101048204e4308204e03081" + "dba003020100a11b3019311730150603550403130e4f43535020526573706f6e64657218" + "0f32303136303130343137303130305a3081a53081a23049300906052b0e03021a050004" + "14c0fe0278fc99188891b3f212e9c7e1b21ab7bfc004140dfc1df0a9e0f01ce7f2b21317" + "7e6f8d157cd4f60210017f77deb3bcbb235d44ccc7dba62e72a116180f32303130303730" + "373135303130355aa0030a0101180f32303130303730373135303130355aa011180f3230" + "3130303730373138333531375aa1193017301506092b06010505073001020101ff040504" + "03000000300d06092a864886f70d01010b0500038201010031c730ca60a7a0d92d8e4010" + "911b469de95b4d27e89de6537552436237967694f76f701cf6b45c932bd308bca4a8d092" + "5c604ba94796903091d9e6c000178e72c1f0a24a277dd262835af5d17d3f9d7869606c9f" + "e7c8e708a41645699895beee38bfa63bb46296683761c5d1d65439b8ab868dc3017c9eeb" + "b70b82dbf3a31c55b457d48bb9e82b335ed49f445042eaf606b06a3e0639824924c89c63" + "eccddfe85e6694314138b2536f5e15e07085d0f6e26d4b2f8244bab0d70de07283ac6384" + "a0501fc3dea7cf0adfd4c7f34871080900e252ddc403e3f0265f2a704af905d3727504ed" + "28f3214a219d898a022463c78439799ca81c8cbafdbcec34ea937cd6a08202ea308202e6" + "308202e2308201caa003020102020101300d06092a864886f70d01010b05003019311730" + "150603550403130e4f43535020526573706f6e646572301e170d31353031333031353530" + "33335a170d3136303133303135353033335a3019311730150603550403130e4f43535020" + "526573706f6e64657230820122300d06092a864886f70d01010105000382010f00308201" + "0a0282010100e8155f2d3e6f2e8d14c62a788bd462f9f844e7a6977c83ef1099f0f6616e" + "c5265b56f356e62c5400f0b06a2e7945a82752c636df32a895152d6074df1701dc6ccfbc" + "bec75a70bd2b55ae2be7e6cad3b5fd4cd5b7790ab401a436d3f5f346074ffde8a99d5b72" + "3350f0a112076614b12ef79c78991b119453445acf2416ab0046b540db14c9fc0f27b898" + "9ad0f63aa4b8aefc91aa8a72160c36307c60fec78a93d3fddf4259902aa77e7332971c7d" + "285b6a04f648993c6922a3e9da9adf5f81508c3228791843e5d49f24db2f1290bafd97e6" + "55b1049a199f652cd603c4fafa330c390b0da78fbbc67e8fa021cbd74eb96222b12ace31" + "a77dcf920334dc94581b0203010001a3353033300e0603551d0f0101ff04040302078030" + "130603551d25040c300a06082b06010505070309300c0603551d130101ff04023000300d" + "06092a864886f70d01010b05000382010100718012761b5063e18f0dc44644d8e6ab8612" + "31c15fd5357805425d82aec1de85bf6d3e30fce205e3e3b8b795bbe52e40a439286d2288" + "9064f4aeeb150359b9425f1da51b3a5c939018555d13ac42c565a0603786a919328f3267" + "09dce52c22ad958ecb7873b9771d1148b1c4be2efe80ba868919fc9f68b6090c2f33c156" + "d67156e42766a50b5d51e79637b7e58af74c2a951b1e642fa7741fec982cc937de37eff5" + "9e2005d5939bfc031589ca143e6e8ab83f40ee08cc20a6b4a95a318352c28d18528dcaf9" + "66705de17afa19d6e8ae91ddf33179d16ebb6ac2c69cae8373d408ebf8c55308be6c04d9" + "3a25439a94299a65a709756c7a3e568be049d5c38839" const ocspResponseWithExtensionHex = "308204fb0a0100a08204f4308204f006092b0601050507300101048204e1308204dd3081" + "d8a003020100a11b3019311730150603550403130e4f43535020526573706f6e64657218" + "0f32303136303130343136353930305a3081a230819f3049300906052b0e03021a050004" + "14c0fe0278fc99188891b3f212e9c7e1b21ab7bfc004140dfc1df0a9e0f01ce7f2b21317" + "7e6f8d157cd4f60210017f77deb3bcbb235d44ccc7dba62e72a116180f32303130303730" + "373135303130355aa0030a0101180f32303130303730373135303130355aa011180f3230" + "3130303730373138333531375aa1163014301206092b0601050507300102040504030000" + "00300d06092a864886f70d01010b05000382010100c09a33e0b2324c852421bb83f85ac9" + "9113f5426012bd2d2279a8166e9241d18a33c870894250622ffc7ed0c4601b16d624f90b" + "779265442cdb6868cf40ab304ab4b66e7315ed02cf663b1601d1d4751772b31bc299db23" + "9aebac78ed6797c06ed815a7a8d18d63cfbb609cafb47ec2e89e37db255216eb09307848" + "d01be0a3e943653c78212b96ff524b74c9ec456b17cdfb950cc97645c577b2e09ff41dde" + "b03afb3adaa381cc0f7c1d95663ef22a0f72f2c45613ae8e2b2d1efc96e8463c7d1d8a1d" + "7e3b35df8fe73a301fc3f804b942b2b3afa337ff105fc1462b7b1c1d75eb4566c8665e59" + "f80393b0adbf8004ff6c3327ed34f007cb4a3348a7d55e06e3a08202ea308202e6308202" + "e2308201caa003020102020101300d06092a864886f70d01010b05003019311730150603" + "550403130e4f43535020526573706f6e646572301e170d3135303133303135353033335a" + "170d3136303133303135353033335a3019311730150603550403130e4f43535020526573" + "706f6e64657230820122300d06092a864886f70d01010105000382010f003082010a0282" + "010100e8155f2d3e6f2e8d14c62a788bd462f9f844e7a6977c83ef1099f0f6616ec5265b" + "56f356e62c5400f0b06a2e7945a82752c636df32a895152d6074df1701dc6ccfbcbec75a" + "70bd2b55ae2be7e6cad3b5fd4cd5b7790ab401a436d3f5f346074ffde8a99d5b723350f0" + "a112076614b12ef79c78991b119453445acf2416ab0046b540db14c9fc0f27b8989ad0f6" + "3aa4b8aefc91aa8a72160c36307c60fec78a93d3fddf4259902aa77e7332971c7d285b6a" + "04f648993c6922a3e9da9adf5f81508c3228791843e5d49f24db2f1290bafd97e655b104" + "9a199f652cd603c4fafa330c390b0da78fbbc67e8fa021cbd74eb96222b12ace31a77dcf" + "920334dc94581b0203010001a3353033300e0603551d0f0101ff04040302078030130603" + "551d25040c300a06082b06010505070309300c0603551d130101ff04023000300d06092a" + "864886f70d01010b05000382010100718012761b5063e18f0dc44644d8e6ab861231c15f" + "d5357805425d82aec1de85bf6d3e30fce205e3e3b8b795bbe52e40a439286d22889064f4" + "aeeb150359b9425f1da51b3a5c939018555d13ac42c565a0603786a919328f326709dce5" + "2c22ad958ecb7873b9771d1148b1c4be2efe80ba868919fc9f68b6090c2f33c156d67156" + "e42766a50b5d51e79637b7e58af74c2a951b1e642fa7741fec982cc937de37eff59e2005" + "d5939bfc031589ca143e6e8ab83f40ee08cc20a6b4a95a318352c28d18528dcaf966705d" + "e17afa19d6e8ae91ddf33179d16ebb6ac2c69cae8373d408ebf8c55308be6c04d93a2543" + "9a94299a65a709756c7a3e568be049d5c38839" const ocspMultiResponseHex = "30820ee60a0100a0820edf30820edb06092b060105050730010104820ecc30820ec83082" + "0839a216041445ac2ecd75f53f1cf6e4c51d3de0047ad0aa7465180f3230313530363032" + "3130303033305a3082080c3065303d300906052b0e03021a05000414f7452a0080601527" + "72e4a135e76e9e52fde0f1580414edd8f2ee977252853a330b297a18f5c993853b3f0204" + "5456656a8000180f32303135303630323039303230375aa011180f323031353036303331" + "30303033305a3065303d300906052b0e03021a05000414f7452a008060152772e4a135e7" + "6e9e52fde0f1580414edd8f2ee977252853a330b297a18f5c993853b3f02045456656b80" + "00180f32303135303630323039303230375aa011180f3230313530363033313030303330" + "5a3065303d300906052b0e03021a05000414f7452a008060152772e4a135e76e9e52fde0" + "f1580414edd8f2ee977252853a330b297a18f5c993853b3f02045456656c8000180f3230" + "3135303630323039303230375aa011180f32303135303630333130303033305a3065303d" + "300906052b0e03021a05000414f7452a008060152772e4a135e76e9e52fde0f1580414ed" + "d8f2ee977252853a330b297a18f5c993853b3f02045456656d8000180f32303135303630" + "323039303230375aa011180f32303135303630333130303033305a3065303d300906052b" + "0e03021a05000414f7452a008060152772e4a135e76e9e52fde0f1580414edd8f2ee9772" + "52853a330b297a18f5c993853b3f02045456656e8000180f323031353036303230393032" + "30375aa011180f32303135303630333130303033305a3065303d300906052b0e03021a05" + "000414f7452a008060152772e4a135e76e9e52fde0f1580414edd8f2ee977252853a330b" + "297a18f5c993853b3f02045456656f8000180f32303135303630323039303230375aa011" + "180f32303135303630333130303033305a3065303d300906052b0e03021a05000414f745" + "2a008060152772e4a135e76e9e52fde0f1580414edd8f2ee977252853a330b297a18f5c9" + "93853b3f0204545665708000180f32303135303630323039303230375aa011180f323031" + "35303630333130303033305a3065303d300906052b0e03021a05000414f7452a00806015" + "2772e4a135e76e9e52fde0f1580414edd8f2ee977252853a330b297a18f5c993853b3f02" + "04545665718000180f32303135303630323039303230375aa011180f3230313530363033" + "3130303033305a3065303d300906052b0e03021a05000414f7452a008060152772e4a135" + "e76e9e52fde0f1580414edd8f2ee977252853a330b297a18f5c993853b3f020454566572" + "8000180f32303135303630323039303230375aa011180f32303135303630333130303033" + "305a3065303d300906052b0e03021a05000414f7452a008060152772e4a135e76e9e52fd" + "e0f1580414edd8f2ee977252853a330b297a18f5c993853b3f0204545665738000180f32" + "303135303630323039303230375aa011180f32303135303630333130303033305a306530" + "3d300906052b0e03021a05000414f7452a008060152772e4a135e76e9e52fde0f1580414" + "edd8f2ee977252853a330b297a18f5c993853b3f0204545665748000180f323031353036" + "30323039303230375aa011180f32303135303630333130303033305a3065303d30090605" + "2b0e03021a05000414f7452a008060152772e4a135e76e9e52fde0f1580414edd8f2ee97" + "7252853a330b297a18f5c993853b3f0204545665758000180f3230313530363032303930" + "3230375aa011180f32303135303630333130303033305a3065303d300906052b0e03021a" + "05000414f7452a008060152772e4a135e76e9e52fde0f1580414edd8f2ee977252853a33" + "0b297a18f5c993853b3f0204545665768000180f32303135303630323039303230375aa0" + "11180f32303135303630333130303033305a3065303d300906052b0e03021a05000414f7" + "452a008060152772e4a135e76e9e52fde0f1580414edd8f2ee977252853a330b297a18f5" + "c993853b3f0204545665778000180f32303135303630323039303230375aa011180f3230" + "3135303630333130303033305a3065303d300906052b0e03021a05000414f7452a008060" + "152772e4a135e76e9e52fde0f1580414edd8f2ee977252853a330b297a18f5c993853b3f" + "0204545665788000180f32303135303630323039303230375aa011180f32303135303630" + "333130303033305a3065303d300906052b0e03021a05000414f7452a008060152772e4a1" + "35e76e9e52fde0f1580414edd8f2ee977252853a330b297a18f5c993853b3f0204545665" + "798000180f32303135303630323039303230375aa011180f323031353036303331303030" + "33305a3065303d300906052b0e03021a05000414f7452a008060152772e4a135e76e9e52" + "fde0f1580414edd8f2ee977252853a330b297a18f5c993853b3f02045456657a8000180f" + "32303135303630323039303230375aa011180f32303135303630333130303033305a3065" + "303d300906052b0e03021a05000414f7452a008060152772e4a135e76e9e52fde0f15804" + "14edd8f2ee977252853a330b297a18f5c993853b3f02045456657b8000180f3230313530" + "3630323039303230375aa011180f32303135303630333130303033305a3065303d300906" + "052b0e03021a05000414f7452a008060152772e4a135e76e9e52fde0f1580414edd8f2ee" + "977252853a330b297a18f5c993853b3f02045456657c8000180f32303135303630323039" + "303230375aa011180f32303135303630333130303033305a3065303d300906052b0e0302" + "1a05000414f7452a008060152772e4a135e76e9e52fde0f1580414edd8f2ee977252853a" + "330b297a18f5c993853b3f02045456657d8000180f32303135303630323039303230375a" + "a011180f32303135303630333130303033305a300d06092a864886f70d01010505000382" + "01010016b73b92859979f27d15eb018cf069eed39c3d280213565f3026de11ba15bdb94d" + "764cf2d0fdd204ef926c588d7b183483c8a2b1995079c7ed04dcefcc650c1965be4b6832" + "a8839e832f7f60f638425eccdf9bc3a81fbe700fda426ddf4f06c29bee431bbbe81effda" + "a60b7da5b378f199af2f3c8380be7ba6c21c8e27124f8a4d8989926aea19055700848d33" + "799e833512945fd75364edbd2dd18b783c1e96e332266b17979a0b88c35b43f47c87c493" + "19155056ad8dbbae5ff2afad3c0e1c69ed111206ffda49875e8e4efc0926264823bc4423" + "c8a002f34288c4bc22516f98f54fc609943721f590ddd8d24f989457526b599b0eb75cb5" + "a80da1ad93a621a08205733082056f3082056b30820453a0030201020204545638c4300d" + "06092a864886f70d01010b0500308182310b300906035504061302555331183016060355" + "040a130f552e532e20476f7665726e6d656e7431233021060355040b131a446570617274" + "6d656e74206f662074686520547265617375727931223020060355040b13194365727469" + "6669636174696f6e20417574686f7269746965733110300e060355040b13074f43494f20" + "4341301e170d3135303332303131353531335a170d3135303633303034303030305a3081" + "98310b300906035504061302555331183016060355040a130f552e532e20476f7665726e" + "6d656e7431233021060355040b131a4465706172746d656e74206f662074686520547265" + "617375727931223020060355040b131943657274696669636174696f6e20417574686f72" + "69746965733110300e060355040b13074f43494f204341311430120603550403130b4f43" + "5350205369676e657230820122300d06092a864886f70d01010105000382010f00308201" + "0a0282010100c1b6fe1ba1ad50bb98c855811acbd67fe68057f48b8e08d3800e7f2c51b7" + "9e20551934971fd92b9c9e6c49453097927cba83a94c0b2fea7124ba5ac442b38e37dba6" + "7303d4962dd7d92b22a04b0e0e182e9ea67620b1c6ce09ee607c19e0e6e3adae81151db1" + "2bb7f706149349a292e21c1eb28565b6839df055e1a838a772ff34b5a1452618e2c26042" + "705d53f0af4b57aae6163f58216af12f3887813fe44b0321827b3a0c52b0e47d0aab94a2" + "f768ab0ba3901d22f8bb263823090b0e37a7f8856db4b0d165c42f3aa7e94f5f6ce1855e" + "98dc57adea0ae98ad39f67ecdec00b88685566e9e8d69f6cefb6ddced53015d0d3b862bc" + "be21f3d72251eefcec730203010001a38201cf308201cb300e0603551d0f0101ff040403" + "020780306b0603551d2004643062300c060a60864801650302010502300c060a60864801" + "650302010503300c060a60864801650302010504300c060a60864801650302010507300c" + "060a60864801650302010508300c060a6086480165030201030d300c060a608648016503" + "020103113081e506082b060105050701010481d83081d5303006082b0601050507300286" + "24687474703a2f2f706b692e74726561732e676f762f746f63615f65655f6169612e7037" + "633081a006082b060105050730028681936c6461703a2f2f6c6461702e74726561732e67" + "6f762f6f753d4f43494f25323043412c6f753d43657274696669636174696f6e25323041" + "7574686f7269746965732c6f753d4465706172746d656e742532306f6625323074686525" + "323054726561737572792c6f3d552e532e253230476f7665726e6d656e742c633d55533f" + "634143657274696669636174653b62696e61727930130603551d25040c300a06082b0601" + "0505070309300f06092b060105050730010504020500301f0603551d23041830168014a2" + "13a8e5c607546c243d4eb72b27a2a7711ab5af301d0603551d0e0416041451f98046818a" + "e46d953ac90c210ccfaa1a06980c300d06092a864886f70d01010b050003820101003a37" + "0b301d14ffdeb370883639bec5ae6f572dcbddadd672af16ee2a8303316b14e1fbdca8c2" + "8f4bad9c7b1410250e149c14e9830ca6f17370a8d13151205d956e28c141cc0500379596" + "c5b9239fcfa3d2de8f1d4f1a2b1bf2d1851bed1c86012ee8135bdc395cd4496ce69fadd0" + "3b682b90350ca7b4f458190b7a0ab5c33a04cf1347a77d541877a380a4c94988c5658908" + "44fdc22637a72b9fa410333e2caf969477f9fe07f50e3681c204fb3bf073b9da01cd8d91" + "8044c40b1159955af12a3263ab1d34119d7f59bfa6cae88ed058addc4e08250263f8f836" + "2f5bdffd45636fea7474c60a55c535954477b2f286e1b2535f0dd12c162f1b353c370e08" + "be67" const ocspMultiResponseCertHex = "308207943082067ca003020102020454566573300d06092a864886f70d01010b05003081" + "82310b300906035504061302555331183016060355040a130f552e532e20476f7665726e" + "6d656e7431233021060355040b131a4465706172746d656e74206f662074686520547265" + "617375727931223020060355040b131943657274696669636174696f6e20417574686f72" + "69746965733110300e060355040b13074f43494f204341301e170d313530343130313535" + "3733385a170d3138303431303136323733385a30819d310b300906035504061302555331" + "183016060355040a130f552e532e20476f7665726e6d656e7431233021060355040b131a" + "4465706172746d656e74206f662074686520547265617375727931253023060355040b13" + "1c427572656175206f66207468652046697363616c20536572766963653110300e060355" + "040b130744657669636573311630140603550403130d706b692e74726561732e676f7630" + "820122300d06092a864886f70d01010105000382010f003082010a0282010100c7273623" + "8c49c48bf501515a2490ef6e5ae0c06e0ad2aa9a6bb77f3d0370d846b2571581ebf38fd3" + "1948daad3dec7a4da095f1dcbe9654e65bcf7acdfd4ee802421dad9b90536c721d2bca58" + "8413e6bfd739a72470560bb7d64f9a09284f90ff8af1d5a3c5c84d0f95a00f9c6d988dd0" + "d87f1d0d3344580901c955139f54d09de0acdbd3322b758cb0c58881bf04913243401f44" + "013fd9f6d8348044cc8bb0a71978ad93366b2a4687a5274b2ee07d0fb40225453eb244ed" + "b20152251ac77c59455260ff07eeceb3cb3c60fb8121cf92afd3daa2a4650e1942ccb555" + "de10b3d481feb299838ef05d0fd1810b146753472ae80da65dd34da25ca1f89971f10039" + "0203010001a38203f3308203ef300e0603551d0f0101ff0404030205a030170603551d20" + "0410300e300c060a60864801650302010503301106096086480186f84201010404030206" + "4030130603551d25040c300a06082b060105050703013082010806082b06010505070101" + "0481fb3081f8303006082b060105050730028624687474703a2f2f706b692e7472656173" + "2e676f762f746f63615f65655f6169612e7037633081a006082b06010505073002868193" + "6c6461703a2f2f6c6461702e74726561732e676f762f6f753d4f43494f25323043412c6f" + "753d43657274696669636174696f6e253230417574686f7269746965732c6f753d446570" + "6172746d656e742532306f6625323074686525323054726561737572792c6f3d552e532e" + "253230476f7665726e6d656e742c633d55533f634143657274696669636174653b62696e" + "617279302106082b060105050730018615687474703a2f2f6f6373702e74726561732e67" + "6f76307b0603551d1104743072811c6373612d7465616d4066697363616c2e7472656173" + "7572792e676f768210706b692e74726561737572792e676f768210706b692e64696d632e" + "6468732e676f76820d706b692e74726561732e676f76811f6563622d686f7374696e6740" + "66697363616c2e74726561737572792e676f76308201890603551d1f048201803082017c" + "3027a025a0238621687474703a2f2f706b692e74726561732e676f762f4f43494f5f4341" + "332e63726c3082014fa082014ba0820147a48197308194310b3009060355040613025553" + "31183016060355040a130f552e532e20476f7665726e6d656e7431233021060355040b13" + "1a4465706172746d656e74206f662074686520547265617375727931223020060355040b" + "131943657274696669636174696f6e20417574686f7269746965733110300e060355040b" + "13074f43494f2043413110300e0603550403130743524c313430398681aa6c6461703a2f" + "2f6c6461702e74726561732e676f762f636e3d43524c313430392c6f753d4f43494f2532" + "3043412c6f753d43657274696669636174696f6e253230417574686f7269746965732c6f" + "753d4465706172746d656e742532306f6625323074686525323054726561737572792c6f" + "3d552e532e253230476f7665726e6d656e742c633d55533f636572746966696361746552" + "65766f636174696f6e4c6973743b62696e617279302b0603551d1004243022800f323031" + "35303431303135353733385a810f32303138303431303136323733385a301f0603551d23" + "041830168014a213a8e5c607546c243d4eb72b27a2a7711ab5af301d0603551d0e041604" + "14b0869c12c293914cd460e33ed43e6c5a26e0d68f301906092a864886f67d074100040c" + "300a1b0456382e31030203a8300d06092a864886f70d01010b050003820101004968d182" + "8f9efdc147e747bb5dda15536a42a079b32d3d7f87e619b483aeee70b7e26bda393c6028" + "7c733ecb468fe8b8b11bf809ff76add6b90eb25ad8d3a1052e43ee281e48a3a1ebe7efb5" + "9e2c4a48765dedeb23f5346242145786cc988c762d230d28dd33bf4c2405d80cbb2cb1d6" + "4c8f10ba130d50cb174f6ffb9cfc12808297a2cefba385f4fad170f39b51ebd87c12abf9" + "3c51fc000af90d8aaba78f48923908804a5eb35f617ccf71d201e3708a559e6d16f9f13e" + "074361eb9007e28d86bb4e0bfa13aad0e9ddd9124e84519de60e2fc6040b18d9fd602b02" + "684b4c071c3019fc842197d00c120c41654bcbfbc4a096a1c637b79112b81ce1fa3899f9" const ocspRequestHex = "3051304f304d304b3049300906052b0e03021a05000414c0fe0278fc99188891b3f212e9" + "c7e1b21ab7bfc004140dfc1df0a9e0f01ce7f2b213177e6f8d157cd4f60210017f77deb3" + "bcbb235d44ccc7dba62e72" const leafCertHex = "308203c830820331a0030201020210017f77deb3bcbb235d44ccc7dba62e72300d06092a" + "864886f70d01010505003081ba311f301d060355040a1316566572695369676e20547275" + "7374204e6574776f726b31173015060355040b130e566572695369676e2c20496e632e31" + "333031060355040b132a566572695369676e20496e7465726e6174696f6e616c20536572" + "766572204341202d20436c617373203331493047060355040b13407777772e7665726973" + "69676e2e636f6d2f43505320496e636f72702e6279205265662e204c494142494c495459" + "204c54442e286329393720566572695369676e301e170d3132303632313030303030305a" + "170d3133313233313233353935395a3068310b3009060355040613025553311330110603" + "550408130a43616c69666f726e6961311230100603550407130950616c6f20416c746f31" + "173015060355040a130e46616365626f6f6b2c20496e632e311730150603550403140e2a" + "2e66616365626f6f6b2e636f6d30819f300d06092a864886f70d010101050003818d0030" + "818902818100ae94b171e2deccc1693e051063240102e0689ae83c39b6b3e74b97d48d7b" + "23689100b0b496ee62f0e6d356bcf4aa0f50643402f5d1766aa972835a7564723f39bbef" + "5290ded9bcdbf9d3d55dfad23aa03dc604c54d29cf1d4b3bdbd1a809cfae47b44c7eae17" + "c5109bee24a9cf4a8d911bb0fd0415ae4c3f430aa12a557e2ae10203010001a382011e30" + "82011a30090603551d130402300030440603551d20043d303b3039060b6086480186f845" + "01071703302a302806082b06010505070201161c68747470733a2f2f7777772e76657269" + "7369676e2e636f6d2f727061303c0603551d1f043530333031a02fa02d862b687474703a" + "2f2f535652496e746c2d63726c2e766572697369676e2e636f6d2f535652496e746c2e63" + "726c301d0603551d250416301406082b0601050507030106082b06010505070302300b06" + "03551d0f0404030205a0303406082b0601050507010104283026302406082b0601050507" + "30018618687474703a2f2f6f6373702e766572697369676e2e636f6d30270603551d1104" + "20301e820e2a2e66616365626f6f6b2e636f6d820c66616365626f6f6b2e636f6d300d06" + "092a864886f70d0101050500038181005b6c2b75f8ed30aa51aad36aba595e555141951f" + "81a53b447910ac1f76ff78fc2781616b58f3122afc1c87010425e9ed43df1a7ba6498060" + "67e2688af03db58c7df4ee03309a6afc247ccb134dc33e54c6bc1d5133a532a73273b1d7" + "9cadc08e7e1a83116d34523340b0305427a21742827c98916698ee7eaf8c3bdd71700817" const issuerCertHex = "30820383308202eca003020102021046fcebbab4d02f0f926098233f93078f300d06092a" + "864886f70d0101050500305f310b300906035504061302555331173015060355040a130e" + "566572695369676e2c20496e632e31373035060355040b132e436c617373203320507562" + "6c6963205072696d6172792043657274696669636174696f6e20417574686f7269747930" + "1e170d3937303431373030303030305a170d3136313032343233353935395a3081ba311f" + "301d060355040a1316566572695369676e205472757374204e6574776f726b3117301506" + "0355040b130e566572695369676e2c20496e632e31333031060355040b132a5665726953" + "69676e20496e7465726e6174696f6e616c20536572766572204341202d20436c61737320" + "3331493047060355040b13407777772e766572697369676e2e636f6d2f43505320496e63" + "6f72702e6279205265662e204c494142494c495459204c54442e28632939372056657269" + "5369676e30819f300d06092a864886f70d010101050003818d0030818902818100d88280" + "e8d619027d1f85183925a2652be1bfd405d3bce6363baaf04c6c5bb6e7aa3c734555b2f1" + "bdea9742ed9a340a15d4a95cf54025ddd907c132b2756cc4cabba3fe56277143aa63f530" + "3e9328e5faf1093bf3b74d4e39f75c495ab8c11dd3b28afe70309542cbfe2b518b5a3c3a" + "f9224f90b202a7539c4f34e7ab04b27b6f0203010001a381e33081e0300f0603551d1304" + "0830060101ff02010030440603551d20043d303b3039060b6086480186f8450107010130" + "2a302806082b06010505070201161c68747470733a2f2f7777772e766572697369676e2e" + "636f6d2f43505330340603551d25042d302b06082b0601050507030106082b0601050507" + "030206096086480186f8420401060a6086480186f845010801300b0603551d0f04040302" + "0106301106096086480186f842010104040302010630310603551d1f042a30283026a024" + "a0228620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c" + "300d06092a864886f70d010105050003818100408e4997968a73dd8e4def3e61b7caa062" + "adf40e0abb753de26ed82cc7bff4b98c369bcaa2d09c724639f6a682036511c4bcbf2da6" + "f5d93b0ab598fab378b91ef22b4c62d5fdb27a1ddf33fd73f9a5d82d8c2aead1fcb028b6" + "e94948134b838a1b487b24f738de6f4154b8ab576b06dfc7a2d4a9f6f136628088f28b75" + "d68071" // Key and certificate for the OCSP responder were not taken from the Thawte // responder, since CreateResponse requires that we have the private key. // Instead, they were generated randomly. const responderPrivateKeyHex = "308204a40201000282010100e8155f2d3e6f2e8d14c62a788bd462f9f844e7a6977c83ef" + "1099f0f6616ec5265b56f356e62c5400f0b06a2e7945a82752c636df32a895152d6074df" + "1701dc6ccfbcbec75a70bd2b55ae2be7e6cad3b5fd4cd5b7790ab401a436d3f5f346074f" + "fde8a99d5b723350f0a112076614b12ef79c78991b119453445acf2416ab0046b540db14" + "c9fc0f27b8989ad0f63aa4b8aefc91aa8a72160c36307c60fec78a93d3fddf4259902aa7" + "7e7332971c7d285b6a04f648993c6922a3e9da9adf5f81508c3228791843e5d49f24db2f" + "1290bafd97e655b1049a199f652cd603c4fafa330c390b0da78fbbc67e8fa021cbd74eb9" + "6222b12ace31a77dcf920334dc94581b02030100010282010100bcf0b93d7238bda329a8" + "72e7149f61bcb37c154330ccb3f42a85c9002c2e2bdea039d77d8581cd19bed94078794e" + "56293d601547fc4bf6a2f9002fe5772b92b21b254403b403585e3130cc99ccf08f0ef81a" + "575b38f597ba4660448b54f44bfbb97072b5a2bf043bfeca828cf7741d13698e3f38162b" + "679faa646b82abd9a72c5c7d722c5fc577a76d2c2daac588accad18516d1bbad10b0dfa2" + "05cfe246b59e28608a43942e1b71b0c80498075121de5b900d727c31c42c78cf1db5c0aa" + "5b491e10ea4ed5c0962aaf2ae025dd81fa4ce490d9d6b4a4465411d8e542fc88617e5695" + "1aa4fc8ea166f2b4d0eb89ef17f2b206bd5f1014bf8fe0e71fe62f2cccf102818100f2dc" + "ddf878d553286daad68bac4070a82ffec3dc4666a2750f47879eec913f91836f1d976b60" + "daf9356e078446dafab5bd2e489e5d64f8572ba24a4ba4f3729b5e106c4dd831cc2497a7" + "e6c7507df05cb64aeb1bbc81c1e340d58b5964cf39cff84ea30c29ec5d3f005ee1362698" + "07395037955955655292c3e85f6187fa1f9502818100f4a33c102630840705f8c778a47b" + "87e8da31e68809af981ac5e5999cf1551685d761cdf0d6520361b99aebd5777a940fa64d" + "327c09fa63746fbb3247ec73a86edf115f1fe5c83598db803881ade71c33c6e956118345" + "497b98b5e07bb5be75971465ec78f2f9467e1b74956ca9d4c7c3e314e742a72d8b33889c" + "6c093a466cef0281801d3df0d02124766dd0be98349b19eb36a508c4e679e793ba0a8bef" + "4d786888c1e9947078b1ea28938716677b4ad8c5052af12eb73ac194915264a913709a0b" + "7b9f98d4a18edd781a13d49899f91c20dbd8eb2e61d991ba19b5cdc08893f5cb9d39e5a6" + "0629ea16d426244673b1b3ee72bd30e41fac8395acac40077403de5efd028180050731dd" + "d71b1a2b96c8d538ba90bb6b62c8b1c74c03aae9a9f59d21a7a82b0d572ef06fa9c807bf" + "c373d6b30d809c7871df96510c577421d9860c7383fda0919ece19996b3ca13562159193" + "c0c246471e287f975e8e57034e5136aaf44254e2650def3d51292474c515b1588969112e" + "0a85cc77073e9d64d2c2fc497844284b02818100d71d63eabf416cf677401ebf965f8314" + "120b568a57dd3bd9116c629c40dc0c6948bab3a13cc544c31c7da40e76132ef5dd3f7534" + "45a635930c74326ae3df0edd1bfb1523e3aa259873ac7cf1ac31151ec8f37b528c275622" + "48f99b8bed59fd4da2576aa6ee20d93a684900bf907e80c66d6e2261ae15e55284b4ed9d" + "6bdaa059" const responderCertHex = "308202e2308201caa003020102020101300d06092a864886f70d01010b05003019311730" + "150603550403130e4f43535020526573706f6e646572301e170d31353031333031353530" + "33335a170d3136303133303135353033335a3019311730150603550403130e4f43535020" + "526573706f6e64657230820122300d06092a864886f70d01010105000382010f00308201" + "0a0282010100e8155f2d3e6f2e8d14c62a788bd462f9f844e7a6977c83ef1099f0f6616e" + "c5265b56f356e62c5400f0b06a2e7945a82752c636df32a895152d6074df1701dc6ccfbc" + "bec75a70bd2b55ae2be7e6cad3b5fd4cd5b7790ab401a436d3f5f346074ffde8a99d5b72" + "3350f0a112076614b12ef79c78991b119453445acf2416ab0046b540db14c9fc0f27b898" + "9ad0f63aa4b8aefc91aa8a72160c36307c60fec78a93d3fddf4259902aa77e7332971c7d" + "285b6a04f648993c6922a3e9da9adf5f81508c3228791843e5d49f24db2f1290bafd97e6" + "55b1049a199f652cd603c4fafa330c390b0da78fbbc67e8fa021cbd74eb96222b12ace31" + "a77dcf920334dc94581b0203010001a3353033300e0603551d0f0101ff04040302078030" + "130603551d25040c300a06082b06010505070309300c0603551d130101ff04023000300d" + "06092a864886f70d01010b05000382010100718012761b5063e18f0dc44644d8e6ab8612" + "31c15fd5357805425d82aec1de85bf6d3e30fce205e3e3b8b795bbe52e40a439286d2288" + "9064f4aeeb150359b9425f1da51b3a5c939018555d13ac42c565a0603786a919328f3267" + "09dce52c22ad958ecb7873b9771d1148b1c4be2efe80ba868919fc9f68b6090c2f33c156" + "d67156e42766a50b5d51e79637b7e58af74c2a951b1e642fa7741fec982cc937de37eff5" + "9e2005d5939bfc031589ca143e6e8ab83f40ee08cc20a6b4a95a318352c28d18528dcaf9" + "66705de17afa19d6e8ae91ddf33179d16ebb6ac2c69cae8373d408ebf8c55308be6c04d9" + "3a25439a94299a65a709756c7a3e568be049d5c38839" const errorResponseHex = "30030a0101" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ocsp/ocsp.go������������������������������������������������0000644�0610621�0607500�00000060372�13172163317�023321� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ocsp parses OCSP responses as specified in RFC 2560. OCSP responses // are signed messages attesting to the validity of a certificate for a small // period of time. This is used to manage revocation for X.509 certificates. package ocsp // import "golang.org/x/crypto/ocsp" import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" _ "crypto/sha1" _ "crypto/sha256" _ "crypto/sha512" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "errors" "fmt" "math/big" "strconv" "time" ) var idPKIXOCSPBasic = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 5, 5, 7, 48, 1, 1}) // ResponseStatus contains the result of an OCSP request. See // https://tools.ietf.org/html/rfc6960#section-2.3 type ResponseStatus int const ( Success ResponseStatus = 0 Malformed ResponseStatus = 1 InternalError ResponseStatus = 2 TryLater ResponseStatus = 3 // Status code four is unused in OCSP. See // https://tools.ietf.org/html/rfc6960#section-4.2.1 SignatureRequired ResponseStatus = 5 Unauthorized ResponseStatus = 6 ) func (r ResponseStatus) String() string { switch r { case Success: return "success" case Malformed: return "malformed" case InternalError: return "internal error" case TryLater: return "try later" case SignatureRequired: return "signature required" case Unauthorized: return "unauthorized" default: return "unknown OCSP status: " + strconv.Itoa(int(r)) } } // ResponseError is an error that may be returned by ParseResponse to indicate // that the response itself is an error, not just that its indicating that a // certificate is revoked, unknown, etc. type ResponseError struct { Status ResponseStatus } func (r ResponseError) Error() string { return "ocsp: error from server: " + r.Status.String() } // These are internal structures that reflect the ASN.1 structure of an OCSP // response. See RFC 2560, section 4.2. type certID struct { HashAlgorithm pkix.AlgorithmIdentifier NameHash []byte IssuerKeyHash []byte SerialNumber *big.Int } // https://tools.ietf.org/html/rfc2560#section-4.1.1 type ocspRequest struct { TBSRequest tbsRequest } type tbsRequest struct { Version int `asn1:"explicit,tag:0,default:0,optional"` RequestorName pkix.RDNSequence `asn1:"explicit,tag:1,optional"` RequestList []request } type request struct { Cert certID } type responseASN1 struct { Status asn1.Enumerated Response responseBytes `asn1:"explicit,tag:0,optional"` } type responseBytes struct { ResponseType asn1.ObjectIdentifier Response []byte } type basicResponse struct { TBSResponseData responseData SignatureAlgorithm pkix.AlgorithmIdentifier Signature asn1.BitString Certificates []asn1.RawValue `asn1:"explicit,tag:0,optional"` } type responseData struct { Raw asn1.RawContent Version int `asn1:"optional,default:0,explicit,tag:0"` RawResponderID asn1.RawValue ProducedAt time.Time `asn1:"generalized"` Responses []singleResponse } type singleResponse struct { CertID certID Good asn1.Flag `asn1:"tag:0,optional"` Revoked revokedInfo `asn1:"tag:1,optional"` Unknown asn1.Flag `asn1:"tag:2,optional"` ThisUpdate time.Time `asn1:"generalized"` NextUpdate time.Time `asn1:"generalized,explicit,tag:0,optional"` SingleExtensions []pkix.Extension `asn1:"explicit,tag:1,optional"` } type revokedInfo struct { RevocationTime time.Time `asn1:"generalized"` Reason asn1.Enumerated `asn1:"explicit,tag:0,optional"` } var ( oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2} oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3} oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2} oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1} oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} ) var hashOIDs = map[crypto.Hash]asn1.ObjectIdentifier{ crypto.SHA1: asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}), crypto.SHA256: asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 1}), crypto.SHA384: asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 2}), crypto.SHA512: asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 3}), } // TODO(rlb): This is also from crypto/x509, so same comment as AGL's below var signatureAlgorithmDetails = []struct { algo x509.SignatureAlgorithm oid asn1.ObjectIdentifier pubKeyAlgo x509.PublicKeyAlgorithm hash crypto.Hash }{ {x509.MD2WithRSA, oidSignatureMD2WithRSA, x509.RSA, crypto.Hash(0) /* no value for MD2 */}, {x509.MD5WithRSA, oidSignatureMD5WithRSA, x509.RSA, crypto.MD5}, {x509.SHA1WithRSA, oidSignatureSHA1WithRSA, x509.RSA, crypto.SHA1}, {x509.SHA256WithRSA, oidSignatureSHA256WithRSA, x509.RSA, crypto.SHA256}, {x509.SHA384WithRSA, oidSignatureSHA384WithRSA, x509.RSA, crypto.SHA384}, {x509.SHA512WithRSA, oidSignatureSHA512WithRSA, x509.RSA, crypto.SHA512}, {x509.DSAWithSHA1, oidSignatureDSAWithSHA1, x509.DSA, crypto.SHA1}, {x509.DSAWithSHA256, oidSignatureDSAWithSHA256, x509.DSA, crypto.SHA256}, {x509.ECDSAWithSHA1, oidSignatureECDSAWithSHA1, x509.ECDSA, crypto.SHA1}, {x509.ECDSAWithSHA256, oidSignatureECDSAWithSHA256, x509.ECDSA, crypto.SHA256}, {x509.ECDSAWithSHA384, oidSignatureECDSAWithSHA384, x509.ECDSA, crypto.SHA384}, {x509.ECDSAWithSHA512, oidSignatureECDSAWithSHA512, x509.ECDSA, crypto.SHA512}, } // TODO(rlb): This is also from crypto/x509, so same comment as AGL's below func signingParamsForPublicKey(pub interface{}, requestedSigAlgo x509.SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { var pubType x509.PublicKeyAlgorithm switch pub := pub.(type) { case *rsa.PublicKey: pubType = x509.RSA hashFunc = crypto.SHA256 sigAlgo.Algorithm = oidSignatureSHA256WithRSA sigAlgo.Parameters = asn1.RawValue{ Tag: 5, } case *ecdsa.PublicKey: pubType = x509.ECDSA switch pub.Curve { case elliptic.P224(), elliptic.P256(): hashFunc = crypto.SHA256 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 case elliptic.P384(): hashFunc = crypto.SHA384 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 case elliptic.P521(): hashFunc = crypto.SHA512 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 default: err = errors.New("x509: unknown elliptic curve") } default: err = errors.New("x509: only RSA and ECDSA keys supported") } if err != nil { return } if requestedSigAlgo == 0 { return } found := false for _, details := range signatureAlgorithmDetails { if details.algo == requestedSigAlgo { if details.pubKeyAlgo != pubType { err = errors.New("x509: requested SignatureAlgorithm does not match private key type") return } sigAlgo.Algorithm, hashFunc = details.oid, details.hash if hashFunc == 0 { err = errors.New("x509: cannot sign with hash function requested") return } found = true break } } if !found { err = errors.New("x509: unknown SignatureAlgorithm") } return } // TODO(agl): this is taken from crypto/x509 and so should probably be exported // from crypto/x509 or crypto/x509/pkix. func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) x509.SignatureAlgorithm { for _, details := range signatureAlgorithmDetails { if oid.Equal(details.oid) { return details.algo } } return x509.UnknownSignatureAlgorithm } // TODO(rlb): This is not taken from crypto/x509, but it's of the same general form. func getHashAlgorithmFromOID(target asn1.ObjectIdentifier) crypto.Hash { for hash, oid := range hashOIDs { if oid.Equal(target) { return hash } } return crypto.Hash(0) } func getOIDFromHashAlgorithm(target crypto.Hash) asn1.ObjectIdentifier { for hash, oid := range hashOIDs { if hash == target { return oid } } return nil } // This is the exposed reflection of the internal OCSP structures. // The status values that can be expressed in OCSP. See RFC 6960. const ( // Good means that the certificate is valid. Good = iota // Revoked means that the certificate has been deliberately revoked. Revoked // Unknown means that the OCSP responder doesn't know about the certificate. Unknown // ServerFailed is unused and was never used (see // https://go-review.googlesource.com/#/c/18944). ParseResponse will // return a ResponseError when an error response is parsed. ServerFailed ) // The enumerated reasons for revoking a certificate. See RFC 5280. const ( Unspecified = iota KeyCompromise = iota CACompromise = iota AffiliationChanged = iota Superseded = iota CessationOfOperation = iota CertificateHold = iota _ = iota RemoveFromCRL = iota PrivilegeWithdrawn = iota AACompromise = iota ) // Request represents an OCSP request. See RFC 6960. type Request struct { HashAlgorithm crypto.Hash IssuerNameHash []byte IssuerKeyHash []byte SerialNumber *big.Int } // Marshal marshals the OCSP request to ASN.1 DER encoded form. func (req *Request) Marshal() ([]byte, error) { hashAlg := getOIDFromHashAlgorithm(req.HashAlgorithm) if hashAlg == nil { return nil, errors.New("Unknown hash algorithm") } return asn1.Marshal(ocspRequest{ tbsRequest{ Version: 0, RequestList: []request{ { Cert: certID{ pkix.AlgorithmIdentifier{ Algorithm: hashAlg, Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */}, }, req.IssuerNameHash, req.IssuerKeyHash, req.SerialNumber, }, }, }, }, }) } // Response represents an OCSP response containing a single SingleResponse. See // RFC 6960. type Response struct { // Status is one of {Good, Revoked, Unknown} Status int SerialNumber *big.Int ProducedAt, ThisUpdate, NextUpdate, RevokedAt time.Time RevocationReason int Certificate *x509.Certificate // TBSResponseData contains the raw bytes of the signed response. If // Certificate is nil then this can be used to verify Signature. TBSResponseData []byte Signature []byte SignatureAlgorithm x509.SignatureAlgorithm // IssuerHash is the hash used to compute the IssuerNameHash and IssuerKeyHash. // Valid values are crypto.SHA1, crypto.SHA256, crypto.SHA384, and crypto.SHA512. // If zero, the default is crypto.SHA1. IssuerHash crypto.Hash // RawResponderName optionally contains the DER-encoded subject of the // responder certificate. Exactly one of RawResponderName and // ResponderKeyHash is set. RawResponderName []byte // ResponderKeyHash optionally contains the SHA-1 hash of the // responder's public key. Exactly one of RawResponderName and // ResponderKeyHash is set. ResponderKeyHash []byte // Extensions contains raw X.509 extensions from the singleExtensions field // of the OCSP response. When parsing certificates, this can be used to // extract non-critical extensions that are not parsed by this package. When // marshaling OCSP responses, the Extensions field is ignored, see // ExtraExtensions. Extensions []pkix.Extension // ExtraExtensions contains extensions to be copied, raw, into any marshaled // OCSP response (in the singleExtensions field). Values override any // extensions that would otherwise be produced based on the other fields. The // ExtraExtensions field is not populated when parsing certificates, see // Extensions. ExtraExtensions []pkix.Extension } // These are pre-serialized error responses for the various non-success codes // defined by OCSP. The Unauthorized code in particular can be used by an OCSP // responder that supports only pre-signed responses as a response to requests // for certificates with unknown status. See RFC 5019. var ( MalformedRequestErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x01} InternalErrorErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x02} TryLaterErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x03} SigRequredErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x05} UnauthorizedErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x06} ) // CheckSignatureFrom checks that the signature in resp is a valid signature // from issuer. This should only be used if resp.Certificate is nil. Otherwise, // the OCSP response contained an intermediate certificate that created the // signature. That signature is checked by ParseResponse and only // resp.Certificate remains to be validated. func (resp *Response) CheckSignatureFrom(issuer *x509.Certificate) error { return issuer.CheckSignature(resp.SignatureAlgorithm, resp.TBSResponseData, resp.Signature) } // ParseError results from an invalid OCSP response. type ParseError string func (p ParseError) Error() string { return string(p) } // ParseRequest parses an OCSP request in DER form. It only supports // requests for a single certificate. Signed requests are not supported. // If a request includes a signature, it will result in a ParseError. func ParseRequest(bytes []byte) (*Request, error) { var req ocspRequest rest, err := asn1.Unmarshal(bytes, &req) if err != nil { return nil, err } if len(rest) > 0 { return nil, ParseError("trailing data in OCSP request") } if len(req.TBSRequest.RequestList) == 0 { return nil, ParseError("OCSP request contains no request body") } innerRequest := req.TBSRequest.RequestList[0] hashFunc := getHashAlgorithmFromOID(innerRequest.Cert.HashAlgorithm.Algorithm) if hashFunc == crypto.Hash(0) { return nil, ParseError("OCSP request uses unknown hash function") } return &Request{ HashAlgorithm: hashFunc, IssuerNameHash: innerRequest.Cert.NameHash, IssuerKeyHash: innerRequest.Cert.IssuerKeyHash, SerialNumber: innerRequest.Cert.SerialNumber, }, nil } // ParseResponse parses an OCSP response in DER form. It only supports // responses for a single certificate. If the response contains a certificate // then the signature over the response is checked. If issuer is not nil then // it will be used to validate the signature or embedded certificate. // // Invalid responses and parse failures will result in a ParseError. // Error responses will result in a ResponseError. func ParseResponse(bytes []byte, issuer *x509.Certificate) (*Response, error) { return ParseResponseForCert(bytes, nil, issuer) } // ParseResponseForCert parses an OCSP response in DER form and searches for a // Response relating to cert. If such a Response is found and the OCSP response // contains a certificate then the signature over the response is checked. If // issuer is not nil then it will be used to validate the signature or embedded // certificate. // // Invalid responses and parse failures will result in a ParseError. // Error responses will result in a ResponseError. func ParseResponseForCert(bytes []byte, cert, issuer *x509.Certificate) (*Response, error) { var resp responseASN1 rest, err := asn1.Unmarshal(bytes, &resp) if err != nil { return nil, err } if len(rest) > 0 { return nil, ParseError("trailing data in OCSP response") } if status := ResponseStatus(resp.Status); status != Success { return nil, ResponseError{status} } if !resp.Response.ResponseType.Equal(idPKIXOCSPBasic) { return nil, ParseError("bad OCSP response type") } var basicResp basicResponse rest, err = asn1.Unmarshal(resp.Response.Response, &basicResp) if err != nil { return nil, err } if len(basicResp.Certificates) > 1 { return nil, ParseError("OCSP response contains bad number of certificates") } if n := len(basicResp.TBSResponseData.Responses); n == 0 || cert == nil && n > 1 { return nil, ParseError("OCSP response contains bad number of responses") } var singleResp singleResponse if cert == nil { singleResp = basicResp.TBSResponseData.Responses[0] } else { match := false for _, resp := range basicResp.TBSResponseData.Responses { if cert.SerialNumber.Cmp(resp.CertID.SerialNumber) == 0 { singleResp = resp match = true break } } if !match { return nil, ParseError("no response matching the supplied certificate") } } ret := &Response{ TBSResponseData: basicResp.TBSResponseData.Raw, Signature: basicResp.Signature.RightAlign(), SignatureAlgorithm: getSignatureAlgorithmFromOID(basicResp.SignatureAlgorithm.Algorithm), Extensions: singleResp.SingleExtensions, SerialNumber: singleResp.CertID.SerialNumber, ProducedAt: basicResp.TBSResponseData.ProducedAt, ThisUpdate: singleResp.ThisUpdate, NextUpdate: singleResp.NextUpdate, } // Handle the ResponderID CHOICE tag. ResponderID can be flattened into // TBSResponseData once https://go-review.googlesource.com/34503 has been // released. rawResponderID := basicResp.TBSResponseData.RawResponderID switch rawResponderID.Tag { case 1: // Name var rdn pkix.RDNSequence if rest, err := asn1.Unmarshal(rawResponderID.Bytes, &rdn); err != nil || len(rest) != 0 { return nil, ParseError("invalid responder name") } ret.RawResponderName = rawResponderID.Bytes case 2: // KeyHash if rest, err := asn1.Unmarshal(rawResponderID.Bytes, &ret.ResponderKeyHash); err != nil || len(rest) != 0 { return nil, ParseError("invalid responder key hash") } default: return nil, ParseError("invalid responder id tag") } if len(basicResp.Certificates) > 0 { ret.Certificate, err = x509.ParseCertificate(basicResp.Certificates[0].FullBytes) if err != nil { return nil, err } if err := ret.CheckSignatureFrom(ret.Certificate); err != nil { return nil, ParseError("bad signature on embedded certificate: " + err.Error()) } if issuer != nil { if err := issuer.CheckSignature(ret.Certificate.SignatureAlgorithm, ret.Certificate.RawTBSCertificate, ret.Certificate.Signature); err != nil { return nil, ParseError("bad OCSP signature: " + err.Error()) } } } else if issuer != nil { if err := ret.CheckSignatureFrom(issuer); err != nil { return nil, ParseError("bad OCSP signature: " + err.Error()) } } for _, ext := range singleResp.SingleExtensions { if ext.Critical { return nil, ParseError("unsupported critical extension") } } for h, oid := range hashOIDs { if singleResp.CertID.HashAlgorithm.Algorithm.Equal(oid) { ret.IssuerHash = h break } } if ret.IssuerHash == 0 { return nil, ParseError("unsupported issuer hash algorithm") } switch { case bool(singleResp.Good): ret.Status = Good case bool(singleResp.Unknown): ret.Status = Unknown default: ret.Status = Revoked ret.RevokedAt = singleResp.Revoked.RevocationTime ret.RevocationReason = int(singleResp.Revoked.Reason) } return ret, nil } // RequestOptions contains options for constructing OCSP requests. type RequestOptions struct { // Hash contains the hash function that should be used when // constructing the OCSP request. If zero, SHA-1 will be used. Hash crypto.Hash } func (opts *RequestOptions) hash() crypto.Hash { if opts == nil || opts.Hash == 0 { // SHA-1 is nearly universally used in OCSP. return crypto.SHA1 } return opts.Hash } // CreateRequest returns a DER-encoded, OCSP request for the status of cert. If // opts is nil then sensible defaults are used. func CreateRequest(cert, issuer *x509.Certificate, opts *RequestOptions) ([]byte, error) { hashFunc := opts.hash() // OCSP seems to be the only place where these raw hash identifiers are // used. I took the following from // http://msdn.microsoft.com/en-us/library/ff635603.aspx _, ok := hashOIDs[hashFunc] if !ok { return nil, x509.ErrUnsupportedAlgorithm } if !hashFunc.Available() { return nil, x509.ErrUnsupportedAlgorithm } h := opts.hash().New() var publicKeyInfo struct { Algorithm pkix.AlgorithmIdentifier PublicKey asn1.BitString } if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil { return nil, err } h.Write(publicKeyInfo.PublicKey.RightAlign()) issuerKeyHash := h.Sum(nil) h.Reset() h.Write(issuer.RawSubject) issuerNameHash := h.Sum(nil) req := &Request{ HashAlgorithm: hashFunc, IssuerNameHash: issuerNameHash, IssuerKeyHash: issuerKeyHash, SerialNumber: cert.SerialNumber, } return req.Marshal() } // CreateResponse returns a DER-encoded OCSP response with the specified contents. // The fields in the response are populated as follows: // // The responder cert is used to populate the responder's name field, and the // certificate itself is provided alongside the OCSP response signature. // // The issuer cert is used to puplate the IssuerNameHash and IssuerKeyHash fields. // // The template is used to populate the SerialNumber, RevocationStatus, RevokedAt, // RevocationReason, ThisUpdate, and NextUpdate fields. // // If template.IssuerHash is not set, SHA1 will be used. // // The ProducedAt date is automatically set to the current date, to the nearest minute. func CreateResponse(issuer, responderCert *x509.Certificate, template Response, priv crypto.Signer) ([]byte, error) { var publicKeyInfo struct { Algorithm pkix.AlgorithmIdentifier PublicKey asn1.BitString } if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil { return nil, err } if template.IssuerHash == 0 { template.IssuerHash = crypto.SHA1 } hashOID := getOIDFromHashAlgorithm(template.IssuerHash) if hashOID == nil { return nil, errors.New("unsupported issuer hash algorithm") } if !template.IssuerHash.Available() { return nil, fmt.Errorf("issuer hash algorithm %v not linked into binary", template.IssuerHash) } h := template.IssuerHash.New() h.Write(publicKeyInfo.PublicKey.RightAlign()) issuerKeyHash := h.Sum(nil) h.Reset() h.Write(issuer.RawSubject) issuerNameHash := h.Sum(nil) innerResponse := singleResponse{ CertID: certID{ HashAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: hashOID, Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */}, }, NameHash: issuerNameHash, IssuerKeyHash: issuerKeyHash, SerialNumber: template.SerialNumber, }, ThisUpdate: template.ThisUpdate.UTC(), NextUpdate: template.NextUpdate.UTC(), SingleExtensions: template.ExtraExtensions, } switch template.Status { case Good: innerResponse.Good = true case Unknown: innerResponse.Unknown = true case Revoked: innerResponse.Revoked = revokedInfo{ RevocationTime: template.RevokedAt.UTC(), Reason: asn1.Enumerated(template.RevocationReason), } } rawResponderID := asn1.RawValue{ Class: 2, // context-specific Tag: 1, // Name (explicit tag) IsCompound: true, Bytes: responderCert.RawSubject, } tbsResponseData := responseData{ Version: 0, RawResponderID: rawResponderID, ProducedAt: time.Now().Truncate(time.Minute).UTC(), Responses: []singleResponse{innerResponse}, } tbsResponseDataDER, err := asn1.Marshal(tbsResponseData) if err != nil { return nil, err } hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm) if err != nil { return nil, err } responseHash := hashFunc.New() responseHash.Write(tbsResponseDataDER) signature, err := priv.Sign(rand.Reader, responseHash.Sum(nil), hashFunc) if err != nil { return nil, err } response := basicResponse{ TBSResponseData: tbsResponseData, SignatureAlgorithm: signatureAlgorithm, Signature: asn1.BitString{ Bytes: signature, BitLength: 8 * len(signature), }, } if template.Certificate != nil { response.Certificates = []asn1.RawValue{ asn1.RawValue{FullBytes: template.Certificate.Raw}, } } responseDER, err := asn1.Marshal(response) if err != nil { return nil, err } return asn1.Marshal(responseASN1{ Status: asn1.Enumerated(Success), Response: responseBytes{ ResponseType: idPKIXOCSPBasic, Response: responseDER, }, }) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021767� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/secretbox/���������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023765� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/secretbox/secretbox_test.go����������������������������0000644�0610621�0607500�00000006250�13172163317�027354� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package secretbox import ( "bytes" "crypto/rand" "encoding/hex" "testing" ) func TestSealOpen(t *testing.T) { var key [32]byte var nonce [24]byte rand.Reader.Read(key[:]) rand.Reader.Read(nonce[:]) var box, opened []byte for msgLen := 0; msgLen < 128; msgLen += 17 { message := make([]byte, msgLen) rand.Reader.Read(message) box = Seal(box[:0], message, &nonce, &key) var ok bool opened, ok = Open(opened[:0], box, &nonce, &key) if !ok { t.Errorf("%d: failed to open box", msgLen) continue } if !bytes.Equal(opened, message) { t.Errorf("%d: got %x, expected %x", msgLen, opened, message) continue } } for i := range box { box[i] ^= 0x20 _, ok := Open(opened[:0], box, &nonce, &key) if ok { t.Errorf("box was opened after corrupting byte %d", i) } box[i] ^= 0x20 } } func TestSecretBox(t *testing.T) { var key [32]byte var nonce [24]byte var message [64]byte for i := range key[:] { key[i] = 1 } for i := range nonce[:] { nonce[i] = 2 } for i := range message[:] { message[i] = 3 } box := Seal(nil, message[:], &nonce, &key) // expected was generated using the C implementation of NaCl. expected, _ := hex.DecodeString("8442bc313f4626f1359e3b50122b6ce6fe66ddfe7d39d14e637eb4fd5b45beadab55198df6ab5368439792a23c87db70acb6156dc5ef957ac04f6276cf6093b84be77ff0849cc33e34b7254d5a8f65ad") if !bytes.Equal(box, expected) { t.Fatalf("box didn't match, got\n%x\n, expected\n%x", box, expected) } } func TestAppend(t *testing.T) { var key [32]byte var nonce [24]byte var message [8]byte out := make([]byte, 4) box := Seal(out, message[:], &nonce, &key) if !bytes.Equal(box[:4], out[:4]) { t.Fatalf("Seal didn't correctly append") } out = make([]byte, 4, 100) box = Seal(out, message[:], &nonce, &key) if !bytes.Equal(box[:4], out[:4]) { t.Fatalf("Seal didn't correctly append with sufficient capacity.") } } func benchmarkSealSize(b *testing.B, size int) { message := make([]byte, size) out := make([]byte, size+Overhead) var nonce [24]byte var key [32]byte b.SetBytes(int64(size)) b.ResetTimer() for i := 0; i < b.N; i++ { out = Seal(out[:0], message, &nonce, &key) } } func BenchmarkSeal8Bytes(b *testing.B) { benchmarkSealSize(b, 8) } func BenchmarkSeal100Bytes(b *testing.B) { benchmarkSealSize(b, 100) } func BenchmarkSeal1K(b *testing.B) { benchmarkSealSize(b, 1024) } func BenchmarkSeal8K(b *testing.B) { benchmarkSealSize(b, 8192) } func benchmarkOpenSize(b *testing.B, size int) { msg := make([]byte, size) result := make([]byte, size) var nonce [24]byte var key [32]byte box := Seal(nil, msg, &nonce, &key) b.SetBytes(int64(size)) b.ResetTimer() for i := 0; i < b.N; i++ { if _, ok := Open(result[:0], box, &nonce, &key); !ok { panic("Open failed") } } } func BenchmarkOpen8Bytes(b *testing.B) { benchmarkOpenSize(b, 8) } func BenchmarkOpen100Bytes(b *testing.B) { benchmarkOpenSize(b, 100) } func BenchmarkOpen1K(b *testing.B) { benchmarkOpenSize(b, 1024) } func BenchmarkOpen8K(b *testing.B) { benchmarkOpenSize(b, 8192) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/secretbox/secretbox.go���������������������������������0000644�0610621�0607500�00000012535�13172163317�026320� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package secretbox encrypts and authenticates small messages. Secretbox uses XSalsa20 and Poly1305 to encrypt and authenticate messages with secret-key cryptography. The length of messages is not hidden. It is the caller's responsibility to ensure the uniqueness of nonces—for example, by using nonce 1 for the first message, nonce 2 for the second message, etc. Nonces are long enough that randomly generated nonces have negligible risk of collision. Messages should be small because: 1. The whole message needs to be held in memory to be processed. 2. Using large messages pressures implementations on small machines to decrypt and process plaintext before authenticating it. This is very dangerous, and this API does not allow it, but a protocol that uses excessive message sizes might present some implementations with no other choice. 3. Fixed overheads will be sufficiently amortised by messages as small as 8KB. 4. Performance may be improved by working with messages that fit into data caches. Thus large amounts of data should be chunked so that each message is small. (Each message still needs a unique nonce.) If in doubt, 16KB is a reasonable chunk size. This package is interoperable with NaCl: https://nacl.cr.yp.to/secretbox.html. */ package secretbox // import "golang.org/x/crypto/nacl/secretbox" import ( "golang.org/x/crypto/poly1305" "golang.org/x/crypto/salsa20/salsa" ) // Overhead is the number of bytes of overhead when boxing a message. const Overhead = poly1305.TagSize // setup produces a sub-key and Salsa20 counter given a nonce and key. func setup(subKey *[32]byte, counter *[16]byte, nonce *[24]byte, key *[32]byte) { // We use XSalsa20 for encryption so first we need to generate a // key and nonce with HSalsa20. var hNonce [16]byte copy(hNonce[:], nonce[:]) salsa.HSalsa20(subKey, &hNonce, key, &salsa.Sigma) // The final 8 bytes of the original nonce form the new nonce. copy(counter[:], nonce[16:]) } // sliceForAppend takes a slice and a requested number of bytes. It returns a // slice with the contents of the given slice followed by that many bytes and a // second slice that aliases into it and contains only the extra bytes. If the // original slice has sufficient capacity then no allocation is performed. func sliceForAppend(in []byte, n int) (head, tail []byte) { if total := len(in) + n; cap(in) >= total { head = in[:total] } else { head = make([]byte, total) copy(head, in) } tail = head[len(in):] return } // Seal appends an encrypted and authenticated copy of message to out, which // must not overlap message. The key and nonce pair must be unique for each // distinct message and the output will be Overhead bytes longer than message. func Seal(out, message []byte, nonce *[24]byte, key *[32]byte) []byte { var subKey [32]byte var counter [16]byte setup(&subKey, &counter, nonce, key) // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since // Salsa20 works with 64-byte blocks, we also generate 32 bytes of // keystream as a side effect. var firstBlock [64]byte salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey) var poly1305Key [32]byte copy(poly1305Key[:], firstBlock[:]) ret, out := sliceForAppend(out, len(message)+poly1305.TagSize) // We XOR up to 32 bytes of message with the keystream generated from // the first block. firstMessageBlock := message if len(firstMessageBlock) > 32 { firstMessageBlock = firstMessageBlock[:32] } tagOut := out out = out[poly1305.TagSize:] for i, x := range firstMessageBlock { out[i] = firstBlock[32+i] ^ x } message = message[len(firstMessageBlock):] ciphertext := out out = out[len(firstMessageBlock):] // Now encrypt the rest. counter[8] = 1 salsa.XORKeyStream(out, message, &counter, &subKey) var tag [poly1305.TagSize]byte poly1305.Sum(&tag, ciphertext, &poly1305Key) copy(tagOut, tag[:]) return ret } // Open authenticates and decrypts a box produced by Seal and appends the // message to out, which must not overlap box. The output will be Overhead // bytes smaller than box. func Open(out []byte, box []byte, nonce *[24]byte, key *[32]byte) ([]byte, bool) { if len(box) < Overhead { return nil, false } var subKey [32]byte var counter [16]byte setup(&subKey, &counter, nonce, key) // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since // Salsa20 works with 64-byte blocks, we also generate 32 bytes of // keystream as a side effect. var firstBlock [64]byte salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey) var poly1305Key [32]byte copy(poly1305Key[:], firstBlock[:]) var tag [poly1305.TagSize]byte copy(tag[:], box) if !poly1305.Verify(&tag, box[poly1305.TagSize:], &poly1305Key) { return nil, false } ret, out := sliceForAppend(out, len(box)-Overhead) // We XOR up to 32 bytes of box with the keystream generated from // the first block. box = box[Overhead:] firstMessageBlock := box if len(firstMessageBlock) > 32 { firstMessageBlock = firstMessageBlock[:32] } for i, x := range firstMessageBlock { out[i] = firstBlock[32+i] ^ x } box = box[len(firstMessageBlock):] out = out[len(firstMessageBlock):] // Now decrypt the rest. counter[8] = 1 salsa.XORKeyStream(out, box, &counter, &subKey) return ret, true } �������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/secretbox/example_test.go������������������������������0000644�0610621�0607500�00000003242�13172163317�027007� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package secretbox_test import ( "crypto/rand" "encoding/hex" "fmt" "io" "golang.org/x/crypto/nacl/secretbox" ) func Example() { // Load your secret key from a safe place and reuse it across multiple // Seal calls. (Obviously don't use this example key for anything // real.) If you want to convert a passphrase to a key, use a suitable // package like bcrypt or scrypt. secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574") if err != nil { panic(err) } var secretKey [32]byte copy(secretKey[:], secretKeyBytes) // You must use a different nonce for each message you encrypt with the // same key. Since the nonce here is 192 bits long, a random value // provides a sufficiently small probability of repeats. var nonce [24]byte if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil { panic(err) } // This encrypts "hello world" and appends the result to the nonce. encrypted := secretbox.Seal(nonce[:], []byte("hello world"), &nonce, &secretKey) // When you decrypt, you must use the same nonce and key you used to // encrypt the message. One way to achieve this is to store the nonce // alongside the encrypted message. Above, we stored the nonce in the first // 24 bytes of the encrypted text. var decryptNonce [24]byte copy(decryptNonce[:], encrypted[:24]) decrypted, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &secretKey) if !ok { panic("decryption error") } fmt.Println(string(decrypted)) // Output: hello world } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/box/���������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022557� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/box/example_test.go������������������������������������0000644�0610621�0607500�00000006432�13172163317�025605� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package box_test import ( crypto_rand "crypto/rand" // Custom so it's clear which rand we're using. "fmt" "io" "golang.org/x/crypto/nacl/box" ) func Example() { senderPublicKey, senderPrivateKey, err := box.GenerateKey(crypto_rand.Reader) if err != nil { panic(err) } recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(crypto_rand.Reader) if err != nil { panic(err) } // You must use a different nonce for each message you encrypt with the // same key. Since the nonce here is 192 bits long, a random value // provides a sufficiently small probability of repeats. var nonce [24]byte if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil { panic(err) } msg := []byte("Alas, poor Yorick! I knew him, Horatio") // This encrypts msg and appends the result to the nonce. encrypted := box.Seal(nonce[:], msg, &nonce, recipientPublicKey, senderPrivateKey) // The recipient can decrypt the message using their private key and the // sender's public key. When you decrypt, you must use the same nonce you // used to encrypt the message. One way to achieve this is to store the // nonce alongside the encrypted message. Above, we stored the nonce in the // first 24 bytes of the encrypted text. var decryptNonce [24]byte copy(decryptNonce[:], encrypted[:24]) decrypted, ok := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey) if !ok { panic("decryption error") } fmt.Println(string(decrypted)) // Output: Alas, poor Yorick! I knew him, Horatio } func Example_precompute() { senderPublicKey, senderPrivateKey, err := box.GenerateKey(crypto_rand.Reader) if err != nil { panic(err) } recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(crypto_rand.Reader) if err != nil { panic(err) } // The shared key can be used to speed up processing when using the same // pair of keys repeatedly. sharedEncryptKey := new([32]byte) box.Precompute(sharedEncryptKey, recipientPublicKey, senderPrivateKey) // You must use a different nonce for each message you encrypt with the // same key. Since the nonce here is 192 bits long, a random value // provides a sufficiently small probability of repeats. var nonce [24]byte if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil { panic(err) } msg := []byte("A fellow of infinite jest, of most excellent fancy") // This encrypts msg and appends the result to the nonce. encrypted := box.SealAfterPrecomputation(nonce[:], msg, &nonce, sharedEncryptKey) // The shared key can be used to speed up processing when using the same // pair of keys repeatedly. var sharedDecryptKey [32]byte box.Precompute(&sharedDecryptKey, senderPublicKey, recipientPrivateKey) // The recipient can decrypt the message using the shared key. When you // decrypt, you must use the same nonce you used to encrypt the message. // One way to achieve this is to store the nonce alongside the encrypted // message. Above, we stored the nonce in the first 24 bytes of the // encrypted text. var decryptNonce [24]byte copy(decryptNonce[:], encrypted[:24]) decrypted, ok := box.OpenAfterPrecomputation(nil, encrypted[24:], &decryptNonce, &sharedDecryptKey) if !ok { panic("decryption error") } fmt.Println(string(decrypted)) // Output: A fellow of infinite jest, of most excellent fancy } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/box/box_test.go����������������������������������������0000644�0610621�0607500�00000003560�13172163317�024741� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package box import ( "bytes" "crypto/rand" "encoding/hex" "testing" "golang.org/x/crypto/curve25519" ) func TestSealOpen(t *testing.T) { publicKey1, privateKey1, _ := GenerateKey(rand.Reader) publicKey2, privateKey2, _ := GenerateKey(rand.Reader) if *privateKey1 == *privateKey2 { t.Fatalf("private keys are equal!") } if *publicKey1 == *publicKey2 { t.Fatalf("public keys are equal!") } message := []byte("test message") var nonce [24]byte box := Seal(nil, message, &nonce, publicKey1, privateKey2) opened, ok := Open(nil, box, &nonce, publicKey2, privateKey1) if !ok { t.Fatalf("failed to open box") } if !bytes.Equal(opened, message) { t.Fatalf("got %x, want %x", opened, message) } for i := range box { box[i] ^= 0x40 _, ok := Open(nil, box, &nonce, publicKey2, privateKey1) if ok { t.Fatalf("opened box with byte %d corrupted", i) } box[i] ^= 0x40 } } func TestBox(t *testing.T) { var privateKey1, privateKey2 [32]byte for i := range privateKey1[:] { privateKey1[i] = 1 } for i := range privateKey2[:] { privateKey2[i] = 2 } var publicKey1 [32]byte curve25519.ScalarBaseMult(&publicKey1, &privateKey1) var message [64]byte for i := range message[:] { message[i] = 3 } var nonce [24]byte for i := range nonce[:] { nonce[i] = 4 } box := Seal(nil, message[:], &nonce, &publicKey1, &privateKey2) // expected was generated using the C implementation of NaCl. expected, _ := hex.DecodeString("78ea30b19d2341ebbdba54180f821eec265cf86312549bea8a37652a8bb94f07b78a73ed1708085e6ddd0e943bbdeb8755079a37eb31d86163ce241164a47629c0539f330b4914cd135b3855bc2a2dfc") if !bytes.Equal(box, expected) { t.Fatalf("box didn't match, got\n%x\n, expected\n%x", box, expected) } } ������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/box/box.go���������������������������������������������0000644�0610621�0607500�00000007634�13172163317�023710� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package box authenticates and encrypts small messages using public-key cryptography. Box uses Curve25519, XSalsa20 and Poly1305 to encrypt and authenticate messages. The length of messages is not hidden. It is the caller's responsibility to ensure the uniqueness of nonces—for example, by using nonce 1 for the first message, nonce 2 for the second message, etc. Nonces are long enough that randomly generated nonces have negligible risk of collision. Messages should be small because: 1. The whole message needs to be held in memory to be processed. 2. Using large messages pressures implementations on small machines to decrypt and process plaintext before authenticating it. This is very dangerous, and this API does not allow it, but a protocol that uses excessive message sizes might present some implementations with no other choice. 3. Fixed overheads will be sufficiently amortised by messages as small as 8KB. 4. Performance may be improved by working with messages that fit into data caches. Thus large amounts of data should be chunked so that each message is small. (Each message still needs a unique nonce.) If in doubt, 16KB is a reasonable chunk size. This package is interoperable with NaCl: https://nacl.cr.yp.to/box.html. */ package box // import "golang.org/x/crypto/nacl/box" import ( "io" "golang.org/x/crypto/curve25519" "golang.org/x/crypto/nacl/secretbox" "golang.org/x/crypto/salsa20/salsa" ) // Overhead is the number of bytes of overhead when boxing a message. const Overhead = secretbox.Overhead // GenerateKey generates a new public/private key pair suitable for use with // Seal and Open. func GenerateKey(rand io.Reader) (publicKey, privateKey *[32]byte, err error) { publicKey = new([32]byte) privateKey = new([32]byte) _, err = io.ReadFull(rand, privateKey[:]) if err != nil { publicKey = nil privateKey = nil return } curve25519.ScalarBaseMult(publicKey, privateKey) return } var zeros [16]byte // Precompute calculates the shared key between peersPublicKey and privateKey // and writes it to sharedKey. The shared key can be used with // OpenAfterPrecomputation and SealAfterPrecomputation to speed up processing // when using the same pair of keys repeatedly. func Precompute(sharedKey, peersPublicKey, privateKey *[32]byte) { curve25519.ScalarMult(sharedKey, privateKey, peersPublicKey) salsa.HSalsa20(sharedKey, &zeros, sharedKey, &salsa.Sigma) } // Seal appends an encrypted and authenticated copy of message to out, which // will be Overhead bytes longer than the original and must not overlap it. The // nonce must be unique for each distinct message for a given pair of keys. func Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte { var sharedKey [32]byte Precompute(&sharedKey, peersPublicKey, privateKey) return secretbox.Seal(out, message, nonce, &sharedKey) } // SealAfterPrecomputation performs the same actions as Seal, but takes a // shared key as generated by Precompute. func SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte { return secretbox.Seal(out, message, nonce, sharedKey) } // Open authenticates and decrypts a box produced by Seal and appends the // message to out, which must not overlap box. The output will be Overhead // bytes smaller than box. func Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) ([]byte, bool) { var sharedKey [32]byte Precompute(&sharedKey, peersPublicKey, privateKey) return secretbox.Open(out, box, nonce, &sharedKey) } // OpenAfterPrecomputation performs the same actions as Open, but takes a // shared key as generated by Precompute. func OpenAfterPrecomputation(out, box []byte, nonce *[24]byte, sharedKey *[32]byte) ([]byte, bool) { return secretbox.Open(out, box, nonce, sharedKey) } ����������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/auth/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022730� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/auth/example_test.go�����������������������������������0000644�0610621�0607500�00000002064�13172163317�025753� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package auth_test import ( "encoding/hex" "fmt" "golang.org/x/crypto/nacl/auth" ) func Example() { // Load your secret key from a safe place and reuse it across multiple // Sum calls. (Obviously don't use this example key for anything // real.) If you want to convert a passphrase to a key, use a suitable // package like bcrypt or scrypt. secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574") if err != nil { panic(err) } var secretKey [32]byte copy(secretKey[:], secretKeyBytes) mac := auth.Sum([]byte("hello world"), &secretKey) fmt.Printf("%x\n", *mac) result := auth.Verify(mac[:], []byte("hello world"), &secretKey) fmt.Println(result) badResult := auth.Verify(mac[:], []byte("different message"), &secretKey) fmt.Println(badResult) // Output: eca5a521f3d77b63f567fb0cb6f5f2d200641bc8dada42f60c5f881260c30317 // true // false } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/auth/auth_test.go��������������������������������������0000644�0610621�0607500�00000011100�13172163317�025250� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package auth import ( "bytes" rand "crypto/rand" mrand "math/rand" "testing" ) // Test cases are from RFC 4231, and match those present in the tests directory // of the download here: https://nacl.cr.yp.to/install.html var testCases = []struct { key [32]byte msg []byte out [32]byte }{ { key: [32]byte{ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, }, msg: []byte("Hi There"), out: [32]byte{ 0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0, 0xb4, 0x24, 0x1a, 0x1d, 0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2, 0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0, 0xb3, 0x05, 0x45, 0xe1, 0x7c, 0xde, }, }, { key: [32]byte{'J', 'e', 'f', 'e'}, msg: []byte("what do ya want for nothing?"), out: [32]byte{ 0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b, 0x56, 0xe0, 0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27, 0x0c, 0xd7, 0xea, 0x25, 0x05, 0x54, }, }, { key: [32]byte{ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, }, msg: []byte{ // 50 bytes of 0xdd 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, }, out: [32]byte{ 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c, 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8, 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, }, }, { key: [32]byte{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, }, msg: []byte{ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, }, out: [32]byte{ 0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6, 0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f, 0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, }, }, } func TestSum(t *testing.T) { for i, test := range testCases { tag := Sum(test.msg, &test.key) if !bytes.Equal(tag[:], test.out[:]) { t.Errorf("#%d: Sum: got\n%x\nwant\n%x", i, tag, test.out) } } } func TestVerify(t *testing.T) { wrongMsg := []byte("unknown msg") for i, test := range testCases { if !Verify(test.out[:], test.msg, &test.key) { t.Errorf("#%d: Verify(%x, %q, %x) failed", i, test.out, test.msg, test.key) } if Verify(test.out[:], wrongMsg, &test.key) { t.Errorf("#%d: Verify(%x, %q, %x) unexpectedly passed", i, test.out, wrongMsg, test.key) } } } func TestStress(t *testing.T) { if testing.Short() { t.Skip("exhaustiveness test") } var key [32]byte msg := make([]byte, 10000) prng := mrand.New(mrand.NewSource(0)) // copied from tests/auth5.c in nacl for i := 0; i < 10000; i++ { if _, err := rand.Read(key[:]); err != nil { t.Fatal(err) } if _, err := rand.Read(msg[:i]); err != nil { t.Fatal(err) } tag := Sum(msg[:i], &key) if !Verify(tag[:], msg[:i], &key) { t.Errorf("#%d: unexpected failure from Verify", i) } if i > 0 { msgIndex := prng.Intn(i) oldMsgByte := msg[msgIndex] msg[msgIndex] += byte(1 + prng.Intn(255)) if Verify(tag[:], msg[:i], &key) { t.Errorf("#%d: unexpected success from Verify after corrupting message", i) } msg[msgIndex] = oldMsgByte tag[prng.Intn(len(tag))] += byte(1 + prng.Intn(255)) if Verify(tag[:], msg[:i], &key) { t.Errorf("#%d: unexpected success from Verify after corrupting authenticator", i) } } } } func BenchmarkAuth(b *testing.B) { var key [32]byte if _, err := rand.Read(key[:]); err != nil { b.Fatal(err) } buf := make([]byte, 1024) if _, err := rand.Read(buf[:]); err != nil { b.Fatal(err) } b.SetBytes(int64(len(buf))) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { tag := Sum(buf, &key) if Verify(tag[:], buf, &key) == false { b.Fatal("unexpected failure from Verify") } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/nacl/auth/auth.go�������������������������������������������0000644�0610621�0607500�00000003764�13172163317�024232� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package auth authenticates a message using a secret key. The Sum function, viewed as a function of the message for a uniform random key, is designed to meet the standard notion of unforgeability. This means that an attacker cannot find authenticators for any messages not authenticated by the sender, even if the attacker has adaptively influenced the messages authenticated by the sender. For a formal definition see, e.g., Section 2.4 of Bellare, Kilian, and Rogaway, "The security of the cipher block chaining message authentication code," Journal of Computer and System Sciences 61 (2000), 362–399; http://www-cse.ucsd.edu/~mihir/papers/cbc.html. auth does not make any promises regarding "strong" unforgeability; perhaps one valid authenticator can be converted into another valid authenticator for the same message. NaCl also does not make any promises regarding "truncated unforgeability." This package is interoperable with NaCl: https://nacl.cr.yp.to/auth.html. */ package auth import ( "crypto/hmac" "crypto/sha512" ) const ( // Size is the size, in bytes, of an authenticated digest. Size = 32 // KeySize is the size, in bytes, of an authentication key. KeySize = 32 ) // Sum generates an authenticator for m using a secret key and returns the // 32-byte digest. func Sum(m []byte, key *[KeySize]byte) *[Size]byte { mac := hmac.New(sha512.New, key[:]) mac.Write(m) out := new([KeySize]byte) copy(out[:], mac.Sum(nil)[:Size]) return out } // Verify checks that digest is a valid authenticator of message m under the // given secret key. Verify does not leak timing information. func Verify(digest []byte, m []byte, key *[32]byte) bool { if len(digest) != Size { return false } mac := hmac.New(sha512.New, key[:]) mac.Write(m) expectedMAC := mac.Sum(nil) // first 256 bits of 512-bit sum return hmac.Equal(digest, expectedMAC[:Size]) } ������������lxd-2.0.11/dist/src/golang.org/x/crypto/md4/��������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021536� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/md4/md4block.go���������������������������������������������0000644�0610621�0607500�00000003764�13172163317�023576� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // MD4 block step. // In its own file so that a faster assembly or C version // can be substituted easily. package md4 var shift1 = []uint{3, 7, 11, 19} var shift2 = []uint{3, 5, 9, 13} var shift3 = []uint{3, 9, 11, 15} var xIndex2 = []uint{0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15} var xIndex3 = []uint{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15} func _Block(dig *digest, p []byte) int { a := dig.s[0] b := dig.s[1] c := dig.s[2] d := dig.s[3] n := 0 var X [16]uint32 for len(p) >= _Chunk { aa, bb, cc, dd := a, b, c, d j := 0 for i := 0; i < 16; i++ { X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24 j += 4 } // If this needs to be made faster in the future, // the usual trick is to unroll each of these // loops by a factor of 4; that lets you replace // the shift[] lookups with constants and, // with suitable variable renaming in each // unrolled body, delete the a, b, c, d = d, a, b, c // (or you can let the optimizer do the renaming). // // The index variables are uint so that % by a power // of two can be optimized easily by a compiler. // Round 1. for i := uint(0); i < 16; i++ { x := i s := shift1[i%4] f := ((c ^ d) & b) ^ d a += f + X[x] a = a<<s | a>>(32-s) a, b, c, d = d, a, b, c } // Round 2. for i := uint(0); i < 16; i++ { x := xIndex2[i] s := shift2[i%4] g := (b & c) | (b & d) | (c & d) a += g + X[x] + 0x5a827999 a = a<<s | a>>(32-s) a, b, c, d = d, a, b, c } // Round 3. for i := uint(0); i < 16; i++ { x := xIndex3[i] s := shift3[i%4] h := b ^ c ^ d a += h + X[x] + 0x6ed9eba1 a = a<<s | a>>(32-s) a, b, c, d = d, a, b, c } a += aa b += bb c += cc d += dd p = p[_Chunk:] n += _Chunk } dig.s[0] = a dig.s[1] = b dig.s[2] = c dig.s[3] = d return n } ������������lxd-2.0.11/dist/src/golang.org/x/crypto/md4/md4_test.go���������������������������������������������0000644�0610621�0607500�00000006353�13172163317�023617� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package md4 import ( "fmt" "io" "testing" ) type md4Test struct { out string in string } var golden = []md4Test{ {"31d6cfe0d16ae931b73c59d7e0c089c0", ""}, {"bde52cb31de33e46245e05fbdbd6fb24", "a"}, {"ec388dd78999dfc7cf4632465693b6bf", "ab"}, {"a448017aaf21d8525fc10ae87aa6729d", "abc"}, {"41decd8f579255c5200f86a4bb3ba740", "abcd"}, {"9803f4a34e8eb14f96adba49064a0c41", "abcde"}, {"804e7f1c2586e50b49ac65db5b645131", "abcdef"}, {"752f4adfe53d1da0241b5bc216d098fc", "abcdefg"}, {"ad9daf8d49d81988590a6f0e745d15dd", "abcdefgh"}, {"1e4e28b05464316b56402b3815ed2dfd", "abcdefghi"}, {"dc959c6f5d6f9e04e4380777cc964b3d", "abcdefghij"}, {"1b5701e265778898ef7de5623bbe7cc0", "Discard medicine more than two years old."}, {"d7f087e090fe7ad4a01cb59dacc9a572", "He who has a shady past knows that nice guys finish last."}, {"a6f8fd6df617c72837592fc3570595c9", "I wouldn't marry him with a ten foot pole."}, {"c92a84a9526da8abc240c05d6b1a1ce0", "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, {"f6013160c4dcb00847069fee3bb09803", "The days of the digital watch are numbered. -Tom Stoppard"}, {"2c3bb64f50b9107ed57640fe94bec09f", "Nepal premier won't resign."}, {"45b7d8a32c7806f2f7f897332774d6e4", "For every action there is an equal and opposite government program."}, {"b5b4f9026b175c62d7654bdc3a1cd438", "His money is twice tainted: 'taint yours and 'taint mine."}, {"caf44e80f2c20ce19b5ba1cab766e7bd", "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"}, {"191fae6707f496aa54a6bce9f2ecf74d", "It's a tiny change to the code and not completely disgusting. - Bob Manchek"}, {"9ddc753e7a4ccee6081cd1b45b23a834", "size: a.out: bad magic"}, {"8d050f55b1cadb9323474564be08a521", "The major problem is with sendmail. -Mark Horton"}, {"ad6e2587f74c3e3cc19146f6127fa2e3", "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, {"1d616d60a5fabe85589c3f1566ca7fca", "If the enemy is within range, then so are you."}, {"aec3326a4f496a2ced65a1963f84577f", "It's well we cannot hear the screams/That we create in others' dreams."}, {"77b4fd762d6b9245e61c50bf6ebf118b", "You remind me of a TV show, but that's all right: I watch it anyway."}, {"e8f48c726bae5e516f6ddb1a4fe62438", "C is as portable as Stonehedge!!"}, {"a3a84366e7219e887423b01f9be7166e", "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"}, {"a6b7aa35157e984ef5d9b7f32e5fbb52", "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, {"75661f0545955f8f9abeeb17845f3fd6", "How can you write a big system without C++? -Paul Glick"}, } func TestGolden(t *testing.T) { for i := 0; i < len(golden); i++ { g := golden[i] c := New() for j := 0; j < 3; j++ { if j < 2 { io.WriteString(c, g.in) } else { io.WriteString(c, g.in[0:len(g.in)/2]) c.Sum(nil) io.WriteString(c, g.in[len(g.in)/2:]) } s := fmt.Sprintf("%x", c.Sum(nil)) if s != g.out { t.Fatalf("md4[%d](%s) = %s want %s", j, g.in, s, g.out) } c.Reset() } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/md4/md4.go��������������������������������������������������0000644�0610621�0607500�00000004114�13172163317�022551� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package md4 implements the MD4 hash algorithm as defined in RFC 1320. package md4 // import "golang.org/x/crypto/md4" import ( "crypto" "hash" ) func init() { crypto.RegisterHash(crypto.MD4, New) } // The size of an MD4 checksum in bytes. const Size = 16 // The blocksize of MD4 in bytes. const BlockSize = 64 const ( _Chunk = 64 _Init0 = 0x67452301 _Init1 = 0xEFCDAB89 _Init2 = 0x98BADCFE _Init3 = 0x10325476 ) // digest represents the partial evaluation of a checksum. type digest struct { s [4]uint32 x [_Chunk]byte nx int len uint64 } func (d *digest) Reset() { d.s[0] = _Init0 d.s[1] = _Init1 d.s[2] = _Init2 d.s[3] = _Init3 d.nx = 0 d.len = 0 } // New returns a new hash.Hash computing the MD4 checksum. func New() hash.Hash { d := new(digest) d.Reset() return d } func (d *digest) Size() int { return Size } func (d *digest) BlockSize() int { return BlockSize } func (d *digest) Write(p []byte) (nn int, err error) { nn = len(p) d.len += uint64(nn) if d.nx > 0 { n := len(p) if n > _Chunk-d.nx { n = _Chunk - d.nx } for i := 0; i < n; i++ { d.x[d.nx+i] = p[i] } d.nx += n if d.nx == _Chunk { _Block(d, d.x[0:]) d.nx = 0 } p = p[n:] } n := _Block(d, p) p = p[n:] if len(p) > 0 { d.nx = copy(d.x[:], p) } return } func (d0 *digest) Sum(in []byte) []byte { // Make a copy of d0, so that caller can keep writing and summing. d := new(digest) *d = *d0 // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64. len := d.len var tmp [64]byte tmp[0] = 0x80 if len%64 < 56 { d.Write(tmp[0 : 56-len%64]) } else { d.Write(tmp[0 : 64+56-len%64]) } // Length in bits. len <<= 3 for i := uint(0); i < 8; i++ { tmp[i] = byte(len >> (8 * i)) } d.Write(tmp[0:8]) if d.nx != 0 { panic("d.nx != 0") } for _, s := range d.s { in = append(in, byte(s>>0)) in = append(in, byte(s>>8)) in = append(in, byte(s>>16)) in = append(in, byte(s>>24)) } return in } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/md4/example_test.go�����������������������������������������0000644�0610621�0607500�00000000642�13172163317�024561� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package md4_test import ( "fmt" "io" "golang.org/x/crypto/md4" ) func ExampleNew() { h := md4.New() data := "These pretzels are making me thirsty." io.WriteString(h, data) fmt.Printf("%x", h.Sum(nil)) // Output: 48c4e365090b30a32f084c4888deceaa } ����������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/hkdf/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021766� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/hkdf/hkdf_test.go�������������������������������������������0000644�0610621�0607500�00000025167�13172163317�024303� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hkdf import ( "bytes" "crypto/md5" "crypto/sha1" "crypto/sha256" "crypto/sha512" "hash" "io" "testing" ) type hkdfTest struct { hash func() hash.Hash master []byte salt []byte info []byte out []byte } var hkdfTests = []hkdfTest{ // Tests from RFC 5869 { sha256.New, []byte{ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, }, []byte{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, }, []byte{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, }, []byte{ 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65, }, }, { sha256.New, []byte{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, }, []byte{ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, }, []byte{ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, }, []byte{ 0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a, 0x49, 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf, 0xa9, 0x7c, 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x5e, 0x59, 0x0e, 0x09, 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x36, 0x77, 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, 0x3e, 0x87, 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87, }, }, { sha256.New, []byte{ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, }, []byte{}, []byte{}, []byte{ 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 0x80, 0x2a, 0x06, 0x3c, 0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73, 0x8d, 0x2d, 0x9d, 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8, }, }, { sha1.New, []byte{ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, }, []byte{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, }, []byte{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, }, []byte{ 0x08, 0x5a, 0x01, 0xea, 0x1b, 0x10, 0xf3, 0x69, 0x33, 0x06, 0x8b, 0x56, 0xef, 0xa5, 0xad, 0x81, 0xa4, 0xf1, 0x4b, 0x82, 0x2f, 0x5b, 0x09, 0x15, 0x68, 0xa9, 0xcd, 0xd4, 0xf1, 0x55, 0xfd, 0xa2, 0xc2, 0x2e, 0x42, 0x24, 0x78, 0xd3, 0x05, 0xf3, 0xf8, 0x96, }, }, { sha1.New, []byte{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, }, []byte{ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, }, []byte{ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, }, []byte{ 0x0b, 0xd7, 0x70, 0xa7, 0x4d, 0x11, 0x60, 0xf7, 0xc9, 0xf1, 0x2c, 0xd5, 0x91, 0x2a, 0x06, 0xeb, 0xff, 0x6a, 0xdc, 0xae, 0x89, 0x9d, 0x92, 0x19, 0x1f, 0xe4, 0x30, 0x56, 0x73, 0xba, 0x2f, 0xfe, 0x8f, 0xa3, 0xf1, 0xa4, 0xe5, 0xad, 0x79, 0xf3, 0xf3, 0x34, 0xb3, 0xb2, 0x02, 0xb2, 0x17, 0x3c, 0x48, 0x6e, 0xa3, 0x7c, 0xe3, 0xd3, 0x97, 0xed, 0x03, 0x4c, 0x7f, 0x9d, 0xfe, 0xb1, 0x5c, 0x5e, 0x92, 0x73, 0x36, 0xd0, 0x44, 0x1f, 0x4c, 0x43, 0x00, 0xe2, 0xcf, 0xf0, 0xd0, 0x90, 0x0b, 0x52, 0xd3, 0xb4, }, }, { sha1.New, []byte{ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, }, []byte{}, []byte{}, []byte{ 0x0a, 0xc1, 0xaf, 0x70, 0x02, 0xb3, 0xd7, 0x61, 0xd1, 0xe5, 0x52, 0x98, 0xda, 0x9d, 0x05, 0x06, 0xb9, 0xae, 0x52, 0x05, 0x72, 0x20, 0xa3, 0x06, 0xe0, 0x7b, 0x6b, 0x87, 0xe8, 0xdf, 0x21, 0xd0, 0xea, 0x00, 0x03, 0x3d, 0xe0, 0x39, 0x84, 0xd3, 0x49, 0x18, }, }, { sha1.New, []byte{ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, }, nil, []byte{}, []byte{ 0x2c, 0x91, 0x11, 0x72, 0x04, 0xd7, 0x45, 0xf3, 0x50, 0x0d, 0x63, 0x6a, 0x62, 0xf6, 0x4f, 0x0a, 0xb3, 0xba, 0xe5, 0x48, 0xaa, 0x53, 0xd4, 0x23, 0xb0, 0xd1, 0xf2, 0x7e, 0xbb, 0xa6, 0xf5, 0xe5, 0x67, 0x3a, 0x08, 0x1d, 0x70, 0xcc, 0xe7, 0xac, 0xfc, 0x48, }, }, } func TestHKDF(t *testing.T) { for i, tt := range hkdfTests { hkdf := New(tt.hash, tt.master, tt.salt, tt.info) out := make([]byte, len(tt.out)) n, err := io.ReadFull(hkdf, out) if n != len(tt.out) || err != nil { t.Errorf("test %d: not enough output bytes: %d.", i, n) } if !bytes.Equal(out, tt.out) { t.Errorf("test %d: incorrect output: have %v, need %v.", i, out, tt.out) } } } func TestHKDFMultiRead(t *testing.T) { for i, tt := range hkdfTests { hkdf := New(tt.hash, tt.master, tt.salt, tt.info) out := make([]byte, len(tt.out)) for b := 0; b < len(tt.out); b++ { n, err := io.ReadFull(hkdf, out[b:b+1]) if n != 1 || err != nil { t.Errorf("test %d.%d: not enough output bytes: have %d, need %d .", i, b, n, len(tt.out)) } } if !bytes.Equal(out, tt.out) { t.Errorf("test %d: incorrect output: have %v, need %v.", i, out, tt.out) } } } func TestHKDFLimit(t *testing.T) { hash := sha1.New master := []byte{0x00, 0x01, 0x02, 0x03} info := []byte{} hkdf := New(hash, master, nil, info) limit := hash().Size() * 255 out := make([]byte, limit) // The maximum output bytes should be extractable n, err := io.ReadFull(hkdf, out) if n != limit || err != nil { t.Errorf("not enough output bytes: %d, %v.", n, err) } // Reading one more should fail n, err = io.ReadFull(hkdf, make([]byte, 1)) if n > 0 || err == nil { t.Errorf("key expansion overflowed: n = %d, err = %v", n, err) } } func Benchmark16ByteMD5Single(b *testing.B) { benchmarkHKDFSingle(md5.New, 16, b) } func Benchmark20ByteSHA1Single(b *testing.B) { benchmarkHKDFSingle(sha1.New, 20, b) } func Benchmark32ByteSHA256Single(b *testing.B) { benchmarkHKDFSingle(sha256.New, 32, b) } func Benchmark64ByteSHA512Single(b *testing.B) { benchmarkHKDFSingle(sha512.New, 64, b) } func Benchmark8ByteMD5Stream(b *testing.B) { benchmarkHKDFStream(md5.New, 8, b) } func Benchmark16ByteMD5Stream(b *testing.B) { benchmarkHKDFStream(md5.New, 16, b) } func Benchmark8ByteSHA1Stream(b *testing.B) { benchmarkHKDFStream(sha1.New, 8, b) } func Benchmark20ByteSHA1Stream(b *testing.B) { benchmarkHKDFStream(sha1.New, 20, b) } func Benchmark8ByteSHA256Stream(b *testing.B) { benchmarkHKDFStream(sha256.New, 8, b) } func Benchmark32ByteSHA256Stream(b *testing.B) { benchmarkHKDFStream(sha256.New, 32, b) } func Benchmark8ByteSHA512Stream(b *testing.B) { benchmarkHKDFStream(sha512.New, 8, b) } func Benchmark64ByteSHA512Stream(b *testing.B) { benchmarkHKDFStream(sha512.New, 64, b) } func benchmarkHKDFSingle(hasher func() hash.Hash, block int, b *testing.B) { master := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07} salt := []byte{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17} info := []byte{0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27} out := make([]byte, block) b.SetBytes(int64(block)) b.ResetTimer() for i := 0; i < b.N; i++ { hkdf := New(hasher, master, salt, info) io.ReadFull(hkdf, out) } } func benchmarkHKDFStream(hasher func() hash.Hash, block int, b *testing.B) { master := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07} salt := []byte{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17} info := []byte{0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27} out := make([]byte, block) b.SetBytes(int64(block)) b.ResetTimer() hkdf := New(hasher, master, salt, info) for i := 0; i < b.N; i++ { _, err := io.ReadFull(hkdf, out) if err != nil { hkdf = New(hasher, master, salt, info) i-- } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/hkdf/hkdf.go������������������������������������������������0000644�0610621�0607500�00000003455�13172163317�023240� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package hkdf implements the HMAC-based Extract-and-Expand Key Derivation // Function (HKDF) as defined in RFC 5869. // // HKDF is a cryptographic key derivation function (KDF) with the goal of // expanding limited input keying material into one or more cryptographically // strong secret keys. // // RFC 5869: https://tools.ietf.org/html/rfc5869 package hkdf // import "golang.org/x/crypto/hkdf" import ( "crypto/hmac" "errors" "hash" "io" ) type hkdf struct { expander hash.Hash size int info []byte counter byte prev []byte cache []byte } func (f *hkdf) Read(p []byte) (int, error) { // Check whether enough data can be generated need := len(p) remains := len(f.cache) + int(255-f.counter+1)*f.size if remains < need { return 0, errors.New("hkdf: entropy limit reached") } // Read from the cache, if enough data is present n := copy(p, f.cache) p = p[n:] // Fill the buffer for len(p) > 0 { f.expander.Reset() f.expander.Write(f.prev) f.expander.Write(f.info) f.expander.Write([]byte{f.counter}) f.prev = f.expander.Sum(f.prev[:0]) f.counter++ // Copy the new batch into p f.cache = f.prev n = copy(p, f.cache) p = p[n:] } // Save leftovers for next run f.cache = f.cache[n:] return need, nil } // New returns a new HKDF using the given hash, the secret keying material to expand // and optional salt and info fields. func New(hash func() hash.Hash, secret, salt, info []byte) io.Reader { if salt == nil { salt = make([]byte, hash().Size()) } extractor := hmac.New(hash, salt) extractor.Write(secret) prk := extractor.Sum(nil) return &hkdf{hmac.New(hash, prk), extractor.Size(), info, 1, nil, nil} } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/hkdf/example_test.go����������������������������������������0000644�0610621�0607500�00000002732�13172163317�025013� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package hkdf_test import ( "bytes" "crypto/rand" "crypto/sha256" "fmt" "golang.org/x/crypto/hkdf" "io" ) // Usage example that expands one master key into three other cryptographically // secure keys. func Example_usage() { // Underlying hash function to use hash := sha256.New // Cryptographically secure master key. master := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this. // Non secret salt, optional (can be nil) // Recommended: hash-length sized random salt := make([]byte, hash().Size()) n, err := io.ReadFull(rand.Reader, salt) if n != len(salt) || err != nil { fmt.Println("error:", err) return } // Non secret context specific info, optional (can be nil). // Note, independent from the master key. info := []byte{0x03, 0x14, 0x15, 0x92, 0x65} // Create the key derivation function hkdf := hkdf.New(hash, master, salt, info) // Generate the required keys keys := make([][]byte, 3) for i := 0; i < len(keys); i++ { keys[i] = make([]byte, 24) n, err := io.ReadFull(hkdf, keys[i]) if n != len(keys[i]) || err != nil { fmt.Println("error:", err) return } } // Keys should contain 192 bit random keys for i := 1; i <= len(keys); i++ { fmt.Printf("Key #%d: %v\n", i, !bytes.Equal(keys[i-1], make([]byte, 24))) } // Output: // Key #1: true // Key #2: true // Key #3: true } ��������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022050� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/testdata/�������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023661� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/testdata/sign.input.gz������������������������������0000644�0610621�0607500�00000142232�13172163317�026325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������‹,©pP�sign.input�ìýk’ =’eþÕ�†·ï†Çþ—0çØ×22C!gšíÕUYÉ(6«2#ÂÍÍ�}\Tï»Æ7Ž}îÝeÖðΞó¼y<g=keþg¬RG{ÓSG-¤w®âš§Ýv+sôûóÆ0ß¶K~ïÙišCK3œÛsÓž³>é)ó†'ÎÚo ­Ä8~ý€ŸSJÍ)„•j˜«=#ôzx÷êéOçƒzk7ž·Ÿ²GË»·tB-Ï“Gˆ¥”ûöþÄ2ÂL~ܪñ$>4®;Þ\ßý”÷–Ê(ï{ž\K‰9æÔO›1„÷çO^k‡>Þ§ß;êžc¿u¥\ÏŠ1ŸpËÛgŠã¦2_¾"ïÙ×­gg~ó¬÷M;‡ØV:§Öãy[˜“Wo;ïkt>è²'yÔ¾VX›×ŽUkX?¿~@{~Æ3CsܰóšooO`ùÂ[nÍOÉa>ïÓÞ’c-!ÝÎ[·ú<O:/_;ö ½ÌON‡¥õäÒoª1ípcÜ}¥ÞÞçÌó²WÏ<ç a?#Öø¼oX!ð V™³ï›Ó·§öžý¶œÙý¸×ÛÞXëN½¤Z½aä·—uÒ|Nx³¿®ÝUâÚýÔ'ögê{ævvO l`=²ì‘]N)¤¹Ê>äŽÑ„§üüúóöç§ò]»–¶N”ÓûÓN+Í÷žÖá'æÓsËiòê'ÕŽ+í—%ä©Q;z ¿=Ö‹=ÏSÛm5Œž÷ªeäÙV,g4_æé{væ¬sfdƒÙx_âû8Cyq¢òÌ’S=±‡T°Oxî )—Ë¢½±´§´ÒÚszåà%ýŒS㌽¼ë܇}œu56a´šÖ¹ìô>üïV±ñ½sïÂKž½âœ¥…Ò~~ý€õ®ÖÞŸ=zí»<ëy±åSnº³Ì6ún c½¬ ^K¨À¶øÿ±9‹ÿ¦‰Û÷pȾF+½<k!¬¤øâöüìÌåiqÕ>æ5†3Ÿº^VºþÇkü©ûŽ”ÃŠ<‰=ê¸ÆÉ¹æóΙ4¾'ÔùàXø~ÊħÓòw…|ð¥÷]a³·áY¹¤ Re¯œ¢vð¤’ΜøRo ÁCˆW!Ä;ž=0¿4Yß> Ü¼:ëöŸ|ë]õ ›Ö3 6N‹ï.)ÔJˆì¸aÇÏö­„ÿ}öÅ8 ˜{"œ§b÷oœ3ÔÊvÌ,ÌûàÅ _Ÿå9ç<yÜwž2{!8àìíÿý"Þ†Qv":fw;ÿíVlãôA·‘#ɆŸ&$ÕXûK˜r*˜Q™ÏÀ’ž’È ­âA„:^>žHwÔ‚åÞë˽·$އÍnÞ>Æ{Ù¿~ý�>¸ò²a´Ÿ÷¹+×¹s3°æÜúŠcœÈ‡XÇï©éiüüÀ ù#axsp/_WqØø>DåË’ w!šGœ;¾Bâࡼé÷eá&É2—:'á?ŒÿWùÓúćï=„t<D }Èø[Å‘jãS6ûp òoø"R&-­ûÞ™CawÛÅ÷À„½K¯U2v(O ü'œ÷Á>ñ=áYäãýóëScؽ”An ÒVïŠ{ðù‡Oèvkª�—t {d÷5â¼{$ÂÌ~rdËn#``)\Ñïƒ7W¢òKèÁĶv“£æD,ÈXjÈ›€Bꬉµï=ñ$ÐÅÿ×Ëü u¬ã®þsó[Zæ©ûä(a°[Xêíµ%ÒBÊ|QÅ V¼ÊmcôIПÄäÚ0­‰/OÈiiŸ8÷¨é´FNOoÂwYÅ×ÀÝ_^‚}­éç×xó$?÷xZ�ǰ¼aÞç‚¥æI­Íú¶ÙÒÀ¾o& îôD@Óû–ó€IV½Çç´Cz=br)á‚dI¦* “½²3[DîÇ®‰:ø Á”�°YúõÀ?Üþ¯ó‡ÜPKü°Ñêý¼±Çwà�é’&Èü¯ú²Úü]~—ÞF¸;ûÎ!åÝqOú”»Hh¼A¼üd »¯.†Ÿ‘Eúx€5$É› éç×ÈDåù‚'Þ·6a ?VÀ¥+6BM#ˆ‚¤ŸÞ ›?™,̉1¼ö&žÀ_ìóðKgY=upΓ^ìw&ûÍ5ž[ˆ[§`IM K# ž6Ñëö€äÿ/ô‡à\I¹/[x�,‚y‰æä�0 žÀž±:xŸ’�Ë‚sùø825ÕAÅ#ïx° þ áŒR i¸úy°Œº+áí9x¼Qf�»ÏÝ?¿~�ò‹kÙÄn>-ןgµ:5Ì“F\‘<ÜŸ“pȹÈ)?Ôe ªØ4¡„ $Ð/°ù…ÅaÁc­‘C^9n Õ#ÆŠ &<-{­lå Q}eX‘^È’!d°Zü?y¥?ù´ý`O ;&Ò´(èëTl É ÌY‰‰dÊï ü8!#ÞõîÅ[“íÉ 0ÓÉF·Í7î+TiÆQêAsÎÛãÀ9¸WçkŒyßûóû¤M@è˜ðËÇ—,œ¯ŒÎ:5°QÀFº³Ø/1•g’ ¡b?@| Äi/¦€.0‹ÈzNÖlÝ)Ò°¦ ŽP’•A\«Y“ÌÞòh¼r•@~äÿì¥þXN²‚ð*rLª"òaGHÏxEއAECš�ž%ìþîçÙÄH…GÚ&œ“ƒxã·”\4µdtÄ€:Å$ §o}(`/+X±”Ä/÷ç×`“ê­ÂXD å)øÞOkXì8VW)l¡(Pú6B¼˜5S¿=r¦ð…Õ²²üÏêç¹T@Ö1. yct`/5ÇSÀc”ÌX8[V "2Ê—ŠÙQëÍOa‹Cø¿x­? ¤Y)oÁ% hb= ¬‚öž£€ßÄ›z˜7¹²7K²É¤ ôBÅ|OgË©)#ÿ“âÊ  ô@5Í6×—Ù?~€ž••vŒ•´Ÿ_?�dºÝ%ÊYv®b ÐËO0&6’±ÿ!ŠÖ3u0;ÑÌVu€4kûh¦™Ý<­sï F9KmLJ R!@n+äÙ–½o‹æSK°½w>¼Ô~e‚ìÃù¿|±?øðç–nrÊÒ|`¸DЦÁ³Ø¸e­ ˜T¢üS UUóK`/²)`–¢•üà¨ì ôNîõKQ“HîüËÒ¨žµ:`•"mÿüú*ØsLàƒËJ‘PÈ߯¨ëÇà&áÀ¬ŽI½—ÈŸÄÛ+– $×[Ì—Â÷æã¿|ùR6€ NI` ø{�4 ©€ÐtÆ5±ñ®ë’mq|pù"?z´{ò5ÁÃÿׯögÌ…I”áO>¢ldµ ¯k‹8Cø|+ðnÂËû„ŸÜìI¬Ê"ežz&àˆÔH›8FV%Ë6‡ôÔ÷ÄÇ¿|ñØ'¶3øË„?¸_?€•HJ‰J¾e…Ù¬‡ÇIš0m¾�dþ‚;>!à?¤À�é"<Gx�Y„™œP ܵΗ$‰E³èq€ »ô7áÀ³&ÏæBI–È @ ¢ƒïxq�»õÿçËýêJôøˆŒCÈ' �Ø™ÞÎ{žQcÅ-I;€Ðë¡Àâ/¸ €ýÆ! ð'‚©' )bÞèôKf‡æ ‰Ù�‘Ïtáfýà¥Eùùõø/`VòàÁ’„Ä ¶©oÙ„æâ+¸zþ­Èx óâ 1obk'Ì�?<”r¤‹UlªÜD0¶`¡ê¨÷ÚÙkÏùÆsØN̺Ö²zFîÛ7$ª”L�‹D@úK²øÿýzÂä'¨Ä=_ \ Ø,ž”-“ö&]˜œ Žp^Ɖ+žT€¨ iþüRSË©á¹~ –_²8oDLQË l³F‘[]ä2´”÷ç×0_viUl{ n%-Pe`ÛàíñóÌ´ŸføÝÆÖ§ b ÷b¼oby¨9ùoÑÀE•-¢1è΃?Œü’Œ)PÛRöbÐãu2cIã¹$“ö!ÝO ÀÍ,^[ó€ø=núÿ÷‚¨M„q§l Ï¡X÷¯;ŧEï¼Ù¥ú•ß)vݬLÅoJ½±³'kµ °§t È¥˜ b–4¦2KV³¯×¿€²€1‰ú÷×h¬c{(hX à}ósxžLM~š§ü? ü±ÖKˆ%¸RÂvk+jÑ™²då³2€‰Š w?t‘Ö!FUBÓÊ»à‚ä¢ ‚ygã7O@�©è½XnÔgYÑüxêú6Àg߀Öô¾pìðþO¼âŸÖ.%eF>÷zîOåAÍÊÁ8 xóRÝ‚¸²A8‚juò³ÙWv«eÀŒ   Ží•Úx(m Ãø'+@±C4[üÌ8²Ë øõxžúþüú/‹@§>Â$Aië½Ù£ä—O� Z:Åß³=¬‰@<�›­d ™=Ôh”<�à%î?ÙŸuÃÙžB^žÿ‚„ùÉÄÖeÍ !r0`äigZqšÆÂ43(&Ãr“ƒçÿÔKþ!îRÚœCõçÝ¿ûTíT>sC ÿm'a¦Â¾vÏãÉRý½¼WyG¥Þ"èöV^`)%h9€óIƽƒZ޲‡`㺨Ïé…¯fUçÃ6¬Ÿ_? G� ê1M£R¤LkmxÖú¼=r>Îó²ƒXí) )ùXЭ3É·ø ž^,·±üv %ðoñj”|ømù L0ÎñÀb`Œå%¥£Ù°eBà5H`¯§3ëò&aÍà)ãÿäkþé;&’N[VV/ñ‘|·–Í_÷ûPDÀ²˜°†K³–¦Þìf­ôl×¥ë˜0« ß|Ré9àR½Ý"-ø—WH͆®xÇûóëôwVêS�Õ 69°ä{*|s`…p¢Üß<~f¯9<ÿ§ü$oÖÖ0èz{F*"ÊÌné¬9À!7Yò=,cz<,c1€q�¬yXÊ<kɺÐ¥Æyý™b¥C¼ ù©VËû˜ò?ý¢0‰Z¶—{-PL$L1Nà95{÷™øLÍFZ¥  ”—|ïÚ4hý/õx˜·[{¾šÖïñ¡?Ÿž‹æªN·> A µx`öŸ_? Üëwü˳»{tÿŠDÀ9ÇSªÀ¨?TѲdò¡óe™ˆ¿,I‚x¯ÔØl"9ÆìU0Uå­À%à^À¨ŸJÙ½‹�ìÅÂÅ öîñÍ‘$·òFKÞÍx%Ü<ì8Ý,ó?ýª6Ø‚èT7!|aüc­n=A½i: Œž¬æaãyÉi™àöÆ m èÄnƒŒHÄ¿,”¦/‹ö‚šxôyÎµÌ %³¶ïž„_ì¾üüú‘�â‘(Qcb-Yµ=kïÅÛfW µÞuÀ&ùç%TRªá—›:ÐÈã')¼<ÍÝU“µŒ!x–ÿ‚u7È—:°™é�V™'“”¼k]f6�%öù‰¾<ŽòS¼=—¢dXÃõ9xrÿ·^ö¥6àñ„Û%ôð¾+4Êޤׇu"P„÷ê˜Â®8NFb¦È'¼‰Ò(e–Š5Ä([XÊT€¹Ô/I—$Vƒù 'UíÁ“)`ãϯP°}*,Ì;XÂPM“EI´ß ú©_p¡²äýcýiç‚©)jØk¢RÏß]"9'cÀ@ ’ê\tY&Õqžª£mÐì88¥?€U¡Œq½­­µdR³‡²ÿ‰sÃL•‡ œJú×µð¹ÿ{¯û'BîãìÙÛ/â/¾Øã5–’°½ì÷ñ†/S"4BÃ!7…¼+9,}m(zû^5'–·&JÙ>ÒKaC8ñ^J 8�ˆm�áýüúàÓJôö*—«˜ ›YÞ’‰ ‰¤’fîüCP4êÜòÃ6O¶²À+÷IhnTg©÷—…>vìxœM0µy7Yï'ÛÞw²ñÔÂßD!ñJ4ùøµáá)%W_¸Eæ> ”#C›ÿ·_ø6Áîíi³ ›$T^ ?®S€ŨbHò×-D`;I“×nĮ̈u†Ø­²¦ÍAÅ&ž-Ôb¡q ’:¯»0L qõB…|÷˜CêϯP'oO1Y^*»M…K|ܳ©ŠÀ6$¶I=Ô.EõO¤4%=cÖ½ õxL2Ó€o·å/Ðkˆ7ÆÚ=ûÔwP[ o� µgjzqÉ [Z`c¢òþUÀåfãì9±“ìò`y!x$Ôÿ^ùOÓhB­‚!”βÚ&4ó.Xõº(›¨S=n“§–ïÖqm;ÅðX|Õâ w%:x¶~=,9k÷/ß¶“mT,{Ž߉ñ½¶¤Ÿ_? ?ë¥~¤œ^‚R[Æx‚ «zªø¶ïrç¤bz:ø›XQ<ª"<%ö[«'-ðä€='±¦-^XÉ”¾m¬Ù®Ì ¿ò{ Yñl™…Ù‡ö鉰�ò{ËíØS¥úòfDHý‚ð<v¼ÿK/ýÁ;¿$Ì‚ÑÆkõžá\\zÛ™Åßrœï»÷ž“7$N�·¨D€FƒÚm²ñd€ÿk<«Ñ‹§ªÄ ªµuìø¸^%ƒn*ÏÀòYåç×àåø�’1a“Ê#Ÿ`A_¾”Rvïzywö»*7,—Úò ?i.b.á”`BñÀ2>c´ç¡Ò,Á›4ÁSÔ�·³Øø<�†:iä6 ùñ6 k}Ažnm{jÊ“ I;5O±MZ;¯gM—DV©]×ÿâkÿ©8× ÜaUx[J+J¨½ÎHDÁö�P‰–› å=ƒh²õðŒú]ò,ï“zžTÂÃ{z*;—TÀUÞǯ3ƺ¼^k‡úÍVáAö^Rûç×(˜Ûe1Å‹tæY˜=™ïס–™º—h´&æÞS(3ÞÑI…¶›`ðlÕ·½™÷úq„1bÕIž‹ØÓ2•?M:äñXÀR ñ}ˆqä5’ØnàÑŽkÝ."A}ƒåßDó¼ÛûóÉ/‘8ÿ¿úâ†ÝU½äÝ0bö°Èf½#ßeC¤W‹Ä„ê*E åÚÁû=ÇH"‹zŸÜFá{Ú¼U$Oå,™Ï0`-™âœwx݌ȇ‡€®û€„Ã=m â%›h‘¨rl^tÜ}9wN,pSrˆ]7vûj~6¿/ÚÛ5S ºµ©uÚS0ùŸÈD™ s¥N¸yN½×¦¢'È>QÄdâÛãÕ±9¼` j? †sxáÉ èŒ †#°óKc$PÔà=5y¤ý¿þêø!ªkªYH±ej·——ÀùÉs? ðJ%,–—n ‚Èf¿ö…ñ®Oz¿C£RpS3Ž*( µHžÄqŠSRiii?×ëÀäÆx³ÕåýùõÞ—ú”Ï/¸aÀ36 @‰‰Éá¨O*äqÌ´@2§¸'W±ªà®ùCV¹s{%hÃ)òÅÿ™«•…’(ê×v :ÑõDÂf祩È^aÛül‡í/q»yB3Þ¯ýîí¼‡+™Óôëa|á7S¥€>Ÿ_½üŸhÓ^™ìu3˜b!™÷%)¶þ¸þ|.ˆó>£Ï qkØãÅŸP‡q⇔W ª¾ö?Ÿø 8Îùõ»†âÍ©]Íd̘HmçϯÐ<}».öž‹„a{Ùµò=D–*p×IøìÓ°u)€t/OÖb~ÞÓ¼ ÀéH”žvø\à;û®ÇÍÛӯɲ»²(oy {”må*µƒWÃ1ãæžXN’î ,Ä$)‘€I™íÚ†ðlg=‚Ððã—¯ÿ‡j–쯻DM”Ø<BIÄÞmé–d”÷Gt“Û%ßà{O#O<ñ o7M;Z‰Ã”wv‰Q`¤À¶žJß`¬ý½¹e|+–x*uá?¿~Àl8Æ“0vŠ}R$°ìn/]6|]Œ^´¿“2ÊÌéñ;;… ½—Ïêª×¯¯¥/yß{ŠÌï`CÈxľEö!V³Ž„¥Q´3Z03SxíVô·íª]Š�/¯ÄY¿–äð¡¿J¬ÂSeåY v&5¯~û.°&}m#Ô“…R:cxdïåÏ�*÷"Ç›AÀ'²aåVòV±S”J}~NLŽ’t?pµ©®LÃ)UêbÊÌÐA]à°|íëùùõÊÌÀþ²½ TÇêöM­dW$àÕüߢ]\»±�·t#ad€BìígÚÜm]K1â‰)õí¤BòƒèÝ'¨|©ºØ_‡ð¦“ñ §LF¤úÚDÈþÜ BôÀ¬[“þ™ðŠ ÔX͘okžÿy“ø?…ªÄSÈ_Ÿ.&R\�z_>ⲟnžfmLñi‰ñI *@L­ÙÆX°dO;:b.ƒÛ~‹LvÆ�Ag[“Îs @,ÞÉðRÙõyKš”±Âϯà¹-•9•Ñ)”X༛l|@v·êêå‚Kl^3_(^±±}нOJáüÀ dÉ@Û=yYh 0°ïYΈ�^"+¸²„/º¯@9hÇxXÿ5X[<„ h9ö¾nö$Ùªz© ï‰ãiÞŠRüó%žSâÿG|„Eº7•ÌÛi“BÆË Q©u‰÷Þ¼Lž“’½Æ´@T¬ÀŸ\o@‚k3¾€Ý`Ãixñ[YqpþSÖCÁ_ÆÛ[‰V´ì…cº?¿~€M¬×m,-¶`b° :¬|xº­¦`ˆBàî•Èç:cï ªù;vÌó‡ÄRH‚ì œ«×%Ħô˜£z’~7@’4¹ˆv@½çÚÈf–üx­‹ÛÞ»S ,X¿C| ´JVYBü úå¶ÿ § ñ?è3þ¬ùÔF=NfHl*eЉRÇã™?!ð«­Îäy¡]™aïð—è7óÖ ?¾F?J%ÊcM°·ô» ²'HŒ·CŒ`êÔ].ïS~ý�lá‚Wl£Ÿd–E¼Yöü¿Î†MÛï1]’+ˆ=OïG�™ü–mbà<úœ�ìŽ? ßHJÅXŸmßÖÕH—ü8€d>že†§Òç×]DH)¶BQ=ƒ`ylå5‰mö]ÀnÊ#z!ûR%M<· «:_Mæ¢ôO¸¨—ö'¬ÿ°ù“0¢¯ÄÍß5 ©j; õ<@i¯?ìÏ�>á':‘·¨+ÉâÉ+vÒêË‚€()Z‚Í!+”M:èA@l¯¶UúöЊrP?ì™N@ƒ÷ç×X¢É”ëï¥0*Ïâ1lü"d5 cŸH¤D77{çè¼›7¡É°šðªÃçìz\yÇ$‰ìÔÉCyò6I†ª®~ƒEÔ¸o$FQ íÔwÔà çÉ“$a€[~jb@Ú‰ñC©Í àMªª9)'Fö×ÿø)ÆôŠ£áºß­Ëù®`_÷5,ËäÅ&v‡˜°Þûò*‰œR,.PoìÙ¶m›ÅÚ«éo„ª"/ñjüH¼÷ï�‹Qû7ïƒÕ¥ðóëtoŠ(§�„‰×ôœ ¶fß×pžsòŽ›�Úx *a[{íÎ •îíÅH»·= æb3%åÇ*Ù?@çIÀñ<¾‰…à ø8Í9_vôH]\XݵÁ§~ƒ¢Ï×´é<&Iˆt(·ÈÑ~Îp<övcÖ‰º¡ü‡~̰ØK1Ão˜e‡ú…cY'žóTÜÓ3xKó^t ¢ë ^è –ˆŒ”_çÍ»€Â/ßÎ{ ä,Æ6-€ÐØ«R*(–sâ“(ÿÒë†~~ý�zùæÁê×Êʱ&`ÃÔ�0°½ÛƒfWý¡ÖÆÎ1ÐKû,ë†r‡¹4›wâÎ@kJ§w�‰Ü³yÂ&‰òÅÏ[½Ü> qlÝi k t€å#{Ðøx¿^Ú΄í’ܹ'ôgÝ>ÖÏ«ã'äºM!È‹ ÏBýþœ?€-³“Ü; <-—çänJPRUïïé„ÈÓ d|¿WZ9j[@ò—˜ñxÇ 8ÆÆ�;˜5õÀ”=˜ � ê’‰t³y8Å¿¬ùí?¿~�>MZ"'âXÜÄïÆR*¬·š›‡I-Ñ—J—ÿHƒµïfgÙ%ç’Ÿ1üáv~�NØ8±‘€6ì…¦<´£‰Ý£"(Ø_cîµ$ `§ º)Pz ÅPèàÑ`NëJ—K%‚±<ÕöÒxÒV¸–˜å;fk­›™YíŽçâý?üƒþ\Òx%@?¨…‚§(œ®QŽ·¶©9‹Àú2°%、°tjpœ×HìÖvÎÝ£ûçe)âwÖåÂëÝÌô²5[íÀp Ñܨ|~ý€år°Æ¼Î¢F'Á,lãâ([ˆ¥Ë馨ÙXB2ØÉÀW½äkl]nö ÕDJŠ÷¬…±ýì2Ž'ŽT$Z#´]¿ƒ°¼ð4üRÞ®û™{j vÏ×Qüî5i§„hXŠWĉ ›sÀ#N#mV[-’¯=Ûvr<8! Ÿ: òcÏ vuªê?þ“þ”³<`Çð亥SÕV?¦‡ÑüW‡´�|•7$}[ƒG®�ˆNЙ|ÓËd‡•@ºÔd”ZÔßTô`‰<_¢Y¤`çf%<v™¿l³ ÿùõìË%nQÅñ,#RîbðXCï{õóa6>v(ƒTqX;@3­n·é«á—®A;Ô?ÑÎ6âתf§NŠ~º¬ìp¼Åî� c‹^båèý·3º4Xxž“ÿ°m‡Æ±…-9¤DJ¼¬(9vrÅ• A /6Ï™ àGyÈÿ[>êl!`�[Eçó\B´i1fÛ½n¨ïøÎõ6韬Ÿù"b‰÷ÿmÈGq< ¡Zt¦¸QÀQ¦â†Ñó·ûê÷|nÛhLŒ“\LU¹?¿~ÀlrtS’mp€©-&ùÔNÊ=(£èu¬íxxPE´ã{öhÞù& ³ˆÓ⇺㈋ ¦Õ.€ Ö݇Z÷|u¯Xs¥!•ܯ]mS¯ð§ç¡¸´µ$޶=*ùuÌ.ð«ÁŽ+¥J݃Ë˸‘œža«¼Þv|ï±T åÓgýP Úï13ÕYµ“3kÝ‹![8ÌÏo¸€ŠiëVÞp?‹d3úáeë|Þý1‰¼5>ÞôÚ™z(¾pÔ²Ûñ÷öÛâôžßÔ0%ìHíçר¤Óðd¼y>‰A9ÃiÖ$¿þ@%AeY"žˆ·/ÛäTØ-ðƒ {";¡c$\]qï^?üâÞ Qxéêy7³ÛωüRrç3âÙ™=xØ`YöpĪö¹ŽÙz:bÅjùù'Åǵïg²áyx¥6#ì¿äþ“Ѧb‘ãÛ‡ý {/B¹~úöRÜ£ žpTßÛ-`BRç%ÏËo°a5Ÿä\.˜ì¶×Kíw ü´­ƒ¯ã{ËÑkWËeq–Ôó˜iÿ†Ed³›ñ×pqmÏÜüÔMßÍö~ÏkÇëÆ[ñƒŠ %©{XÎY1ÿ×QºC]nÏ0ñÚ&Itˆ¥Ï®Î-ÄçÇüF.Djûàž¯3�tu0ö@VÃ!ÁJÉza‡a=Oþk×hÛáA^l‘²íñìÈ7ìA{˜/x.Æ&q² ¶Œ4üzŽá{“ÃÓÿÆOûÓe a ÊRÈôV/wç eÐèÇ{@êòŒ“åÂôœBYCX%—7�–"„|Ÿ¹Öá%ÉbI§Ç¶!Ð`¾ŽH™ª'äž²RÁôôüüúÙ»çÊÌí ofÙŹX Ù“°ÆŸ, ¶VµŽ’tA2¸l_xMŒöðánøÆ³»•Й^Ë6–êçYu�Mq§‰ž°ñœkò.Å�¶´· ľÑ5zØ: IzßJAüu Rq…DZd·¨¾>:"*HÔJ�ò×{YÂÙ�ÀÎ>}üÿÖûCÄ\<Ÿt¾mºº¯îLFÞXíÝ¿æzç¹Þ±ùò˜R‰, šW.d–DŒN(/ª7›ª—ãÕ†iVäö*K‹ C FN”1~ý€¼¨AøôÃ_5_•tDmãèÙ¶‰çÙ¶:7©µH¼üþ›˜¾®ö<kcmmSÖSÜØH7-Ö äêœØ©¾z”Ç ÝÖ&‘êz+GjÍi°‹LP”ˆ8Ih®äø¦ŒÍŽí•ü؉Žn>c–Žéñ%¿¶V) øÙ0ÇÆg³¯z­Íýoþ¼?‹rnv¯!AÅž&„îáv‹eY©œ®Zï¥òÍ%qŠÃ«ï׋¿ýŒqZןúb&dêžö»¨éì¼ÂM¥ÏÇéœ:êÒQ-°ðϯÐz!YÑQïÙÓï\IɤÒÖŽäò$3 ñóg ·d&6“‡CíˆðN¯îä®qÍÂsI‹•*âÞ^áPºäGè½+ª• ùER~çãÀƒT/‘{:Űƒ<”Ÿøç©|aÞSŠÎ8i;¾+ɨƒŽS^ù/ø1ÙÀ‰Ñy¹ôþÈöÿ»?ðÏkO–ÉlÑ®´u­ÌÅt1ÚSbq¨tÙ¯¾1jý{í²!Y‰ÉtÍ_;›bnhµ zƘ>åNß ïñ¬:÷ϯà´\£Šåy™:)Ù57,hk¶;£'” ²üØ8özðÉOG@uÚÔÀb}kîD~ïØ5½½â“ä°½ïX^8¸Ý16l\ ; Ûþ«æ±ù­ˆh²; ªèêY)šùÇ|$ Óš.æ•ã”o¼åR�bú†=â 9†Ro³†öŸð‰>j jö8†3<|Ç’M¡gP«Ü9ð¬o~ší9ã¼}nJ¸¢÷dGw÷xn§8OÎ’†^û£ô¢˜9Ál°Ê‰^JŸ_?à&Ãi¬Ño~ì§ŸÒž}üAò!y8_$=|I©/9½Jqîõû:¤=øØDݹ<x†÷jLdeŸôSí9Ì™Z¸O¹ è•—Ìän½Ÿ?!—N´„ÌL&]}|U˜n¼‡ÊéÅ«IÔ·ÄDmÖb‘ ÄËÆCœ~©ÂO[§53«÷$%„ÿ”ücÜÝ™×Á¼¨ùA0Dˆ!¼r_]ÌáÍD‘0Jû耺º‰ã¢Xå$©$iG¯/%&.Dh3à+wÅMÙ\›D=wæM›­¹ÜŸ_? Ê�GP«Ø“S©ãÊóé•\ŽåÝŸÇ©0Ju—‘ Ú¼«Œs%*8ÉÌ@æÇ«;Êûå8ž—„ÀÕ(9‹ðRNÿ,;Ž£vÐîF°Î€êKœúª;‹g0/Á÷ãçÁÎθÅ×ÉPü5ÊùÚHóäðh=Ô]ïÂ~@x•tüÎmcí—%z§ÊûÏùÌ?X䚯¬[lA’y,ó §ê|p”-ÔiýæQô$8¦·ÙeO8R—�-y×Gú"1™W˜ù¼ž%„^Ý‘nlAæ9¡Ë*<$Öÿüú¸«EÄÌ‘É_à¬ã¼¬ÌSt ~~«÷Ö•ŒÜmÄ”Ïàw*ß�h·›Ó9éËÇGªŽ‘ûíNñäúÏÓ€éiÚY{.±8y|+ï.š^Ò¦xÑ/U©=Öv6‰6š¨‘œîø {PÅ»“å­Öô9˜,pVžë^¢÷‰KÀ¿¼àûÿÓ>ôÏ1Ò<ÄAçñÏëp¸ ‰Gƒš!ÙÚ(/Þáÿ‡l)Þx5B üý�æ}ܦB^¢€ƒ]Rfoð ?ƒ.Ï^ª[¢¬lUï¦)¾ÖÏï�BËïÒyÍsg�ß*)1\#‹WôÓŸ·Tü9JþZcñ*ÛøM"‚Ý×�¦{{ô›”×€ê$eóÕ|¨ô§”òŒQ÷{É”ysu31¬G K$N-T¨Ú%=£JØI*ôÌ—­9™*M*Š6Ât<ökÌä<kÜÃ~Ðpt/ySçsÈø?ïSÿ¼¶Nê¡tµÒ&ø~'‰ÎŸvÛj@ã5òåÈÿð<Þ‡ÔBÒáý¤Èä1Y–):–Á7Ù#€°Ô`Ìõ²áÏ‹Íj>çç×�^Hàôòšv-EY7�Ñ¡ðÅ•*0ùɯ×ÛMP‹]¶K±L5dq‡ìâGG"{+YAòbi­ä0góA?!š¯Åóog?ží}Ÿ<‹äôfá5b*â½ÖJz†‡Æ<1Hß[´î8)A‡Þ¸<Ñ.ÇÆÄ‚×óHª\¨íسp¯£gW|DOÞÿ©ûç¥ö‘Î/È}ôx\¦jÖhÛÆ;(ekƤ.^;ÀP!@ÚyÔìçÄH›sq}=5b—#ŠgÅP›ƒ»«çñÝŠ×ûªäÙEÕøÛPÍíÙæXÄZख;‡½«Û¾æ Õ2;“õÁ'lGñÜúÅuƒ‡8NÚ•ªšÏLr/M/$'ÿl$ñ݉Ëþ G­Âz~pòg œü>•ʱ–¬yäË’²~Ïc“j÷Ѐ’ĉºG"৺eãZ7°Ø²Â±ù,sÄÜs–:‡Ã#;uKòÖ0ÙûÈl„«6ªÉB[ˆÿÉŸû§ÊEõ>Gêb™àz`=‘÷¤êĘ|xõÔàŒÌ+#U-ëâôIfê¤B½°ö¾6–Q¼<RµaÐ|Æð¸›jÜaÎ%AŸO=9AH¬ñÛx7oé)£C½´#ä9ÿt=¤sÄššúÊ(\åÇH&yÆ� ¡�'ÙŠ„.Cïî#àôOˆ^„u¬ÓfZ2ŽX.òù?Î\-›ú=¿±±§�›½<€¯áx›œåY4Š£Oun•¹©\A_'\|Ø­86y‰Åà¶uÄ)·•äÈví4yIÑ]Þ+»ÀßÿôþCá ®Þ²QÛQßšÿL‘jN'IŠ4)´ ÐYϹd^±{r-ßÊCá¾äÆámÏ&ù4@x“Ð@V+âÎT{¢î õkQ¾ ÕCo:?¿~€M Ͻ2¥ ÊÛfãœyÚ ì�2k„ã`_äÌUòŽ’KëÓ:¾ïpO“…«•ñ>ÙçìÝÓP)¾‡"Âæ<¸´4~�Aëhó:·Ê€;«´eo+Ò×ñöÛãÌ*-!+…$1¿^y Öò>ÃY£ëèOÅ"r;Òò7â‘°œ_G$% LK<G6áÿüOþcÙ ¡EÀ@±E€A§:ßvÁ¼öÕ poÄb0y€Ïµ³PŠfçšä¡0by\v;¼ó›ç\ÀsÉdmŠcÂ#i8“=ýÇ/º|Y5>?¿~@÷zN2q,('¹Ÿ¸@¼z·õý¹™ˆéð?õÐÈ6ÈÚ°Ln 8°B¶±›Í@yä·uɶÄjy}×M� 7ÙᇿâÈ8³l^ì7¼ÝfirNØl¡œß¸©-gGª€zÀƒ}"Õ/û«‘œ¨LøÆÜ‚Œ’ãªîµjuÏùälf¦èÝsþ/ùè?25Øx{QIqT=DD¯¥¢c»©¼’°Iâk«Mo‚/•Þ¤Ì÷T \ÁЉ°[vL'X¾yJû*Áž¼´#¥öÌ%ùÚ×ð|±ÕŸ_?`V ,OµaPJÖ u,ˆß¢Óœp"'E ˆÐsw¯}M×8µE£>ñ¬'Ì\¢£K­ƒ/q)—šåõm‚tÞh®ð“ž H yóP^1:C_ª›çé²í“‘†d¸iÖú²¿Óò\i”H /Rnº²_v'xÀžqØÓz£Sàëb é-rú0•ªÁ¹‘xÂø/úì?y€‘©“7ÐvÚF`Íáî©»ÛqHÙÒ=¥ZN¾>Ÿ|×C"(0à8væÍY:>Ñ8ñ‚TòM`êAÆÍîÁïykñê'¢æ.^¢ýö˜w*ã ߨÒI¸Ãó:·È­ïVªHg*SE.á5¾0 9¸“5¶dÈUI ÑänØòyàpYÉM8³5T9ŒdýÙÏ¥ò§Nv<ˆýºÔÄŽÊbI”jGVÌÌŽGà… 0¸1Õ« ¡xFR½Èð ‰Ã&Ñ ñkÅ(J^E\äªö^þœà•u–¸Æâõ¿ìÃÿ›V¥þφÓÿq~ŽÊÝmÛþˆ±&ç狃Ö[x¯Ê¦Å¦à±Uö–(Ó­ €¸º¬Òg2†QK…"…(öd/­3;2~ý€ÇS§PføšˆÖê‘ Û%25³ñÞ;ñ¥:ŸÞx_5•‡¨…ÞGæˆê%ƒwSƒÝ›Ôä’�¼¥8²’mJ®sžc2vúyæâ’Bs®¦ D}(VV0Œ|:RRSâ·›×u/X~Ñ_v!_) »êIfÛì‰\w¨ßÊ_JfJ"Ê ~‚X»ï²ý¶?eŽªàÂÙ§ÿ¡P~Ø`ʹðD–âÚF@:ÜžWÃi ³yÃ�<{ß´ù2ïGGy(b#› bçËÊåÑ¡·ƒYv"ª¾á”|Ä(ˆ| ï0¿;bVâ~ý€ò¹Îd™I±�óâ›zÁòÐ]_‡ÌÖ=9W»SÖwî,㔄7’º~½o¦T35Ž–Ù?ê‡!ϕǕ}º A^Ý7ÙÝZ~¼!Ø–M“Iv@9£(òÀ6Ky‚A-0¼Ï•ÓòLØI;W(¢¢ñt`öwJÊ󤦤O$ÏTùålp~âkSNòºeOJ©XÃû_úñ¨”l¤«2ansäa72¶M#%8ì|«_YöÌþ…ç¿d¬ŒÄ×~"";ߤNûXù¨ñ‚\üI™›ÄÏÎ-W†r'…Þóóû(a³9i/u¦:)߸½eÙHùqŠ#j y;øýo²¼«£þ^N¯êƒ‡ÔEîÞ~mÔ±³j[ÞKäÖ#|íÇ.ö)uer^@nùc7W([ÓQ�jH…³¨q¨Fßye ¬À/w¬ ÜIPоÉ¡ø¸3+«[4�Š‹ý± BÖõ§ðväçs%1•)™e¸ž½¿Ó®=–ÐÏxNün‰£Œª1{!ŸúÝ•U'*åLŠ×ûe¥µ¬?Ó®ù»IÍïÚüŒ³n^Avë‡Ðä4^�|¹=6·Léç€.Ã#Lœ…èÁ>'GœÙú<¥´¥y¶@‹#žŽ+µ€¤­z¡5¥U*tð6Ä Õ@@'ö1«ã5@LäÒÈ—ËâΉ]|õ}Þ%‘+!z´K·Ø@µê†§?§ðíuާ;ÊØ¤Í·Þ¥ÐäiV\¶Ú:T!!u"‰¡*ÑÁ_/'Å™´±CTPlÁ-’`†ÔAØyò‡äIœ€*îÖ»'‘^%9ç‡=H±æ¡rd+ñÚ< ¶×·¬©Bf+W-&·>Îûþ5Ïc›TVâ ŧ NyK"…ëšòY“Q€-¬ˆä¯ùÿ5ÿÿ:óÿSË>¢ ÏgNçÅ©°ß¡üž¬f]Pe€ò¯Üì @åûÁ¯€rž—ÌG5ž‚kÚ%+!äGˆBÒ"Åâµ×tò[Á4 çÊËa² AÁϯ“7#’‹QñoKÕ¼yµÃ?Çä›”¼.¸’O nÅ‘½›ÌÛ&¦]XùbÛÇØ_ÿk§äò¨Hí!¯]¾#Ê;d_–°ŠÜÅ®®n5 )7ðÛ´¥ Jð’ø¦ž,µÖYäƒ;ÊéóZ2\…Nó8¼ ¬ïGù¤0 ï B$á‡jͰj™½Úö~#¼ Äâ½×mÞÒüÓ¡O™õ6;0iYžÚTËM2Kl§Ø×òàÀŒü‘vaf�~e–ä:•G\;ÕŒ[Ô OU…l6$YNòD=¨ð—­ÕVX‡Ò½¨'‡Gé«Ô‹*…›²³ݬ¯|á‡˜éø±··Þ!L yÛc¨‘eô{Õk tSè+QïwGf@–5‡#r3RºYù=AÉj²‰µÅÇzôf‘‡±„­D$¸øýXúdàé*ñQ>ë/}O†d¼ˆjØnÚlçs_b…Ä1¼ÊB~,­²l;eý)èzäýŽòHe¥Ðžýy!Ï,m“—íéýáŸJ[Oe·XÅIe8®‹–ž¯Ñj`_|õ°E'KêÓ(ìh§ÊPUz©›Üøcþó4į²óŠvFrÆ'M÷òÇß�A°=€Ÿ!…üu€¿ð_é�‚£Š-ñ?ξÊ'Ù}nuä1;57ø÷må)£È–4†„›e=îû%~Rîk~<X²±Ÿùóø\ù#G<ý û£'åc.ün ¼ úùõTÏSÞÇÞX•ÿ(ö(c<ït*zPÁðHlÚìcYæ·f¸¬nÄŽ–åÕâ ûóé‰E. “¢ŸßMÎýZˆOûøÁÀD”hÔu$~VXNXJ2í¥¼-qààXk¾€šåÐØÌåÂ�Ša%œàæGuØøAÖ=Æ„H\b]í$ð íÄH&/·—öXòÞ÷àe—Ü ’”«6+Fáá9J.}40ÒîLàѪͱ<~ 1Z ï×(A}×ù¼*Qà—ÞE~áSÀÌxè1M6Êçý<Ý›á#v‰WœVíEBjìî¡&ô~úRm÷d`“ߨ_³ ÆŠ}Úƺ÷îßì¸H8SêK³ o0i«²Ê6GÚ‚ VEå”9›ôvŽèJ½ó‚©Kœû–ƒh5~ò¢²öÅ7óI¬U¨`==ñŸ(ý«×ØbP‚¤ÈÏ»Ø'ÌðâÌñ„Õ›ýŸQ¿TÚR³Ì»úWbŽZ”$p_õ±O˜Èv¼üN•›¤cm /9²Ô ŽöÚ°ÁZÚ!^ÀQjŸk©ü:sŸävô¼,ˆé‡½s´ˆaU•ž’EÂ#%LçbG›Gmm?€Ê®vƒšS]௠ü—ºÀ—*Lvã:?!#Õ2Gè•ÝŸçuÀ¶×a5àm‚B*+î\ljfmU×y$${èÝgqºò»B:¤/2sÎsÇLÍ$ƒ˜­ê䞟_?`½åý޶ø )d©’´ˆœÉ²ì÷u`³c¾ïýzò]k)÷Ž£¸R ØÖml­˜<#Ixj¹M$  ~lÍg»Â§C„™½5È—ëV«ó„Qß]¦´05ÕQÀuµç”¤Æ þ%ï± kc™ÿ0€§áäáòb¤¼zÇSÔ[½G=¤7ûAK"R¯r0¡ëÐ1F«¢tõ:jæcóü$Ÿ4gT1§*§å =Â'ðî¥ÐN—}t }œÓÄ0©^8Á曤͋ʱ„ÀxêêR^>Ôh Á0H5örs:[ÙäŠIDœ¨Þî§pÕTŸŽ&Ì ¦ ±Ò=_/[ÂÙ9£¢ BÌõÖáÉËÓ¼³Y’˱¼e“xI¥Àió‰ŠË`îêùí[¾Ú¯¹#ñùÓfq8ðQo. ƒÚú‡ë|wâIjí)ª¿ü¸Ó¡,FŒ¾c¯vŽõ�äßYòVÈ! À_/Š#É)y¶Œ¡kù„Û·S~ÔŸ½¨ú=Ÿaÿ;A°w‰ÆSdËÛ^J ÙsñÒ-7`»Çc>0ÕÒdJ)¾³Æ«¾é«�ûê·ñú /Ëõ]ï#­yÉ&~;1ë¯üu‚ÿr'øCñfSÁ»«2˜i:r'P‘ÖL2ÁælöJÇ¥¡ä-r€`¬8½zâÅ/ñ¾<�C­i»O¤À£F¹«Z˜^*29¹æaËþùõ$ë“_-ü#Óm{'a¡˜¬Ür×ç8Y®N+µí#Å 3Køß.á­2R8·†õ–ê<Û~SÑ-b“ÉÚ+–H©Â®Ð²,h‹ìúHÅ0¢Œß]®X �ϳŸŠm°?Ðéx€Ï{<_É»x×plI¯A4T„؃„^€®¾pu¨Š´ŠÙ.AžÀKÌšÊ)â@2jWàlÞ)½+£~fUz•N€ØRU�W_çBÆ“_ÐIßÄ‘sˆ YN OB'ÿ£Ñøa=YÂhoἪtêuvƒ¢qožåD¥8÷î:dí(ž?gÉp“QѯéjÇoXBJÇK±,uFc{¯ZR”ÆÎên.Õ­mqéóܨX° D &ÏÃq¢â,àÁ)À|ç«÷ŸðQ†´q[”Ìv¤.pHêOÚéüŽ ÁwÊ¢v¿±@‚h¥&oñù¥„=¡ÒÅ©Ìn' ì]…¢_#ÚþŒ…ˇhV{… °þX©"ˆüõÙl<J;l¢ÈuìÉ<ªæôÚxq yá“ö²é{Û+I°S:µ�³'È`Âìïd±/†äÔ•ÀGû˜ùJ0619Ø<H$ß¶ýuƒ¿nð/à02i…ío%¾Œ#kŒ3à2}Ö¡ ç |PМ¨~±QR% æ²²ÔªB/ivÍϴ7{Iz$iÜû`ª¯â‡Öb ËRìS~Àðóëx{G-i»Uˆ²[ã}~Œ¢EAɤl_Nl’fw¶‹óDòH’k�,Å6—GƒEéÊzªÅ2ùZåQÛÑ Õ’?ÖÙ‚¹(,/­f×+óã­Š[ƒ’rϹO0J[W ˆÍÑ“äàp•ܵÉI^yÉ—>Yújc¡'« #-Ñ¥â‰ÍÌ Ïôx8¦Ígãõ©''²Ï‘B«zÀ Vèyu„Å¿+̧ŸB4éªE»¼Y­ ÿ–Šë7ÈŒXvëX÷lSîTŸZ)Ñ@&-ílöÙ:†?]ÀPKd¾þ‹•kܬ\UO:|m_'Š¢ö 4vÆpªc5ÔÎ,$ÐvzÈBeo‰+áû!?ÏNô…õ›ð ª~°§Dã 0gÓòkI®RœD7§ª5;¼8ry·ìÆÄÆF¨ŠKØB”KìHÚœf/2H"êaðˆb=§ºYqzX‘Q¿`:âÁlú/Ïó»Ø^pösêl?`·Þš.¨.Ûë=r¥~&0âEÀ8êYg+ÆåŽ}/› :«¶½Ay(lä HÞd”Sé²ÛÄû™éhÁ”2>[Étµ]†¼†SI¶¿Žð×þ%áO°uœ|ÿ‡aâÅ?†d>ÃÖ-{§ßÞ4ÚùR]=Êu+¡ž$H„WÁ̦QÆWǵ©ã¥[yjÇD=RãÍã'ן_?€BœbÅ;¿ýq­Ê0@F®[á¡™·ÎäÀ89ÃT^ û„aW§ JdÆw>ÛªþY‡ÅÕjå°óád'V)N§f«hÅþ>{ž �-õBO�]½TÛvC�F7¿õ}k~ ¡ö=ãø¿Í$ª5*AµJMxqÀ )3eÐèÖù|ÁÎëå*Èß_ lÙš3ôvKð/h¶ËË¢àn}›Þ­#!.5·÷pì‘Ä|D!µžf ¦Î›˜ëU¡‰u?¼zjGFÿµÜÿUšÇ»ÃGþòµFG lÓ`ú’&Saw%ób’”\Ýââ#Ë+¹'±O¶qqz'¥):w‚1ê*ÉÞ’ ‰M• ø¾|Ìõ±;ÉÙ×KcÛ»DíñHO†Ër´û^úÉåäé`µ=õ¿A®!p(–´€q[SY1OøÐ’jIái„O|<)„ÛíñU™¸¦„0e½Šs‰ûlù ý:ø*¡ ±nfåc³‘ütP¿[ùç¦ÔÊàE ¡ Òu!ß‹kÆ"avâ¡;/BT¤pP•ÁTÈÍw¨QH,vTRÍ0ba²ßA®Çùµ,q"¯÷œ«^ä_Wøë ÿ"®ð')pÌ )Ó5 •ÞIÃ$›Fi ¸Zç‘æ¦?OUú Ï™6½ï“Êד¥¨©}ŽÎ v>ÇHÉ‹Êí<Í!H‰1ªI¿jš'„úóëعa¡ª?’Ga@í^3•ÚzÐP“Òùy²ôl¶•Œ@ÁŒ¢†d;ð"Å˯½'­Ú+Ž¥ô gÁõR°©ûã'ä£Î«�;è$˜¹}¢ÄîÛ Û ÖØÏu”ý?ûôÚÀDOùší²¡*e~±?lU>j_¼t;(Ù•f§>¾»DO*œŸÇºY§Ag €4¿Œ Ç‚?x5ñ ¾sŒäýnôNí,*^, _Ú3>ÑnC1UŸÕQ; ð—¥œØ&3W¢fΊ9ç§,Ç“"øïz½¹uÞ=³„;Þ/F9ôÀ-çñUe΂ó{ÉÎǦ«=c¶ÆŽ¬¯Ë¹ÉÖn¾g€éjë#'Øë(9¼µ,ž2RtNÙ&Zéa A/˜ñy$ʵx~ Ṫ]çŸ?¶¥I-û“ÖK¡•ïêà$ü0N¹#*ølåâ踃͛ró?Ÿ€—;Ñ­Eðöç½*$ƒðFZÒï½ÅƦWw惴ÕÕ<_ NØ$ù|EŠÂ~]ÍTOC–T’ù»ŒW!E­x‹ e‘[ô†"¥øÁµm…hkZ"WñmŸPþ:Ã_gø—q†?òs³d¼[ú''O¼œt‡Öy×%±¸*%dÅû�]ÍÞ5)úŸvFp-ËyÕ·CÇÇ®{J®µ‹zµ†~©Þ¹(ª•"±Ï쌟_?�$FºÊòºa`ÊǶ¶¦àE±ôÍ¢(ì{²õJŸboÂNT}ª6°JHTÍl{WtÑÔ¶= -‹-ú{«½ÿßÿrªøâ è©Ê#¢†<Gê-,$ሣݯ�v3’2_7÷î'ž`ªŠª‡WêX~ƒ,Ï,„§ùÊRåÍŽþq¿¼2VN[ß@‹ý¼<Ü1ê¡bÓÒHwÅlòùíq€updP&ap$3=èoÄî„!¶ÕY:Ò#ã3¼S¢Újo{à [þSå¶s¢òßÜÄè™:TèHµw™‡¹RqJi´íO?æcù`:5O)ˆímORk2ó†7‹RÖ"Je¦§ˆhSÅP„¸DdƑǞ¶ºÍe3^¤NȽ‡¥;þJÌÓª¢æ¢äÔJ³h±r{ËU­ˆÞóô˜÷óM³JÕg«ÓõBb:y‹‡G¼úFÙ½®EG¨‚áð\pœ_ÿÔâjØ¢# Ä¦ã”YÀD°q¾?}u函imÍ>Kit2A® úÁüÆ:¿–°å­7ȵ4Œ¢àYŠÙË}Ç+ñ9³o"lͱ\_/Ë•ËÉöWé¾®‰ s8 óÉÍú×þºÃ¿Ž;üai³,ù¬FíÔ,Ã˸ó²óÔðlë•ÞXI¦ìrì'*)nMn\[ƒ¯6‹Tç~’Hoögþ3‰zÞÕHPZ'E ?sÊϯàáÛ�iìðÑðòe  Ž|ØåÍÔøø°{‚ÍùoÉâýƬ2+«NõIB.ó +†û5é¼xÔÜ0Žý žÍzÄ%¯ú²‡= ‰;^  ôy«# Ó×Þö*/¥ùU �¾é¦&/Ô¡†•ŒÞÑÔÐ5Æa‹ ¶ÝÕx¿oí]>gþ“x«{ÆàÂ-Es6é½²BMG»ºÉÎÌêÕë¶çÆos$¶wÎŒ)o¢Å‰%Û¨DÛàcAa¼šZBd¤^¶ ´©IC•;Hûcz“—l§Äzçq&ȳÀ×-W/@í\RðìÙ¡ªnº’›ÀL»)íOi ›A§ÊO‚×ò¢Ä\<]}¬H´ˆ=ªcä÷•4‰ª|G#èÂ6ÎHˆb+¯Ÿ†WÊXöó-u�|Ýy¶ír:/Aœ|Ôn#c:ï�És&¤Ë,ñN‡‰Á‰BÛ^µ†ÊM¸ÆKd—hëʦ_ðxKýžC‰j{K©ŸqÄÆW®Ÿ×» �^'—ê&Þ¼ Χ~õ"ãIù¯²=¹%±]ü•÷ÔLT §œÊÔÈi ¿øÛ{ÕÕmm ‰HF‘áe+±óȶÖU—á¯Cüuˆ)‡ø“ñLÎAªÓ²Í-å‘´tbµU\|Î[("ä„oˆÝÎ-tŠ~à…rn«\Îägf3¥È¬åk[Ar‚ “Jz<‹Ò3b(Ômõç×è ‡¥½ñõJo,‘"ÎVŽZøåQ1 ¯éHS6Å죇ú‰š¶v0ð*«×(·•Ìç¤}µ¶d¤ §†)sQçÏ€~�·àS"%ä£^Žçžw]R_ê¾f¡æ«‹xŽw“‘¸bÖ”ußmV°rËq£¢HãÓ³yl¨�–�=ÞfoáÓ)4åÒxyGê> ßzÕ¨Mž �“¡KžàÙ¯© /îÞ©Èoí²’W_Ç´Øî*g |mÌ @RL-nÙ"H쯃qv"Þϳß~™¬«l6ŽW8}.ûä @*õL™ÂóqËsmå×ÔÇ^¸iQ>ÄOÞО%5Èqbg³³ù ~—ê§žœì™AI‘¨*Ë™ílµîù5*À(Hñ6•75leèËbéÇä¾�ªüÆ ø×W–ŧ©Ýì3¤côu±¸í¨?I^ÉÛçöâüUÕ")„ D!À0JžÔ½X—ýHëž’z’W­Äð<æõ*Ì^<Dö(9§ô|,çijȮ«•ÄÁ#YçØé…)ÅÉ’¿ ;³iHʧeµ )P&ïAC8êžôÞÆ�"ª(±¾i80¥=c]â¯Kü‹¹ÄŸF”'[¸Ë\¿ü—7‡(ƒûû5~_5GÔŠ4‡Ç(…³×‘¥ú³^Míwy'¶ó'›úTýI'ˆ¨xæLŸÈÐ#™SO/ �ëãeCòÒ_>€ÿŒ'6Õ 9®Ò]Uª£f UK¶ºH#qW”X( Wý˜7Ç£ÚÓä.NÅš·€6ZÄS±5åÊXi!ÔëØ,FP×Ç«ÊÍÛ¦œ7ð×Ò;âA?«ƒS-d¦>±áãœGÖ•ÕµÃÚ1ˆ„û &~nÇ‹ZÌð¹¸_GoàMÓ<› ªæHž†Å£ZõiÜSü"ªP1tqœL–uj~)Ù‚DaÎè±éÛ8àqÇ‘€f‰Òžxç0¶Ábó/øøW6EžÕÒõ!†¥ ¬-5 ;N¾^i‰œÔÛÃ÷ Ya@V Àø¹xßuðÎâ™Izs '¦å<þ1•UpŸý¬ˆ«¾XR¾ý:ž0ñP5ùâǘæ:%ûäM Œ,ª³J|�œÁ¸Îù ž,Ïw:A21°£J)jµžÍ~¦éÙk.ò‚zŸ7øuUäò ŠË´HP}^Ë bƒŠ>Ø êçË)”Ì[Hþ$©ÒMÉBLÎëi-ÎÞñ’Û¤ê§!™»ªÎ Ú6§a~ù[ƒ>6xOâ­J\]>ꄽ€À.`–"#÷’$³l�÷áÝ(.1 BÑvU,_' NéÚ¡ÿ¯SüuŠ9§øS6Ô€A€Äá“GM~J…„Qúh¨¦äiŸÔ™wYóR.³n˜2o£&eŽ ¬ÿe±5ˬh3_*JJ•Ìaml*©­*xÉŸýüþ¶Ùõ¥P:HnII¢½v ïlUê<ÔðzW?KXI5)Ul8ÙTá=‚¬º3GÔ´à‘+W¾mÃZ_^Ö[¾=ä»ï’˜ Ͻò0ÇÈ:ÿð‰^»5ûó|ë¾õ4ûÆñ]Ǩ¶å†¤TãNÊô÷ žÝûÂýâ…¬þnlvÄ¿€ŸÐoÙÌÛQJÄØ*QáË©W¾ü8—ç­!z„/UòuÖ›¸ä½,)@6×ûôA%]ß ÆÜë,­rì–“ÜGòÐ4²V‘2:%ÖØjuÇW Òž‘^eßïôw핲f¥ïBËl<{ s&­§J¦EÏÉŽE[|d©ÓI|ÓÆ,P¤CˆŒ^+ÛDÅ{ÉÞ7hÓêã9|’í†Ro ùŸ XUI‚’Gqx®còÃHÛŸüœ-G«2¤†õUšP•€%ÜôNÛ€9£G—øD9ð0Ó+OÞXQøxÖÙ“š6õ˰¯–øY݉wðüNåµ±ýØÙs~ò‘ÎÉAãa½rÄöè|Y´®S yÿCoU£6ÕõÓ»Àëa. íëá¼è óã.ÓÉê«Â6UN<WŠÒþ>ªÉOéÜÿëÝâ_Ï-þØé¼ÒƒÉhsl)ptgd)ŒG^)itÿó#s©uŒnóùºçS¥cãJH9÷8sÚ7ù,Z¤ÇLuÿ¥àµ/X¥kÔñüüú^ªeyèÊÔ[¡)òöV ^´O‡Z´f•,ù»ö¤^£ˆt¾€BžJõJ$¸ù³pIà·zba3jRÙòÖãªz|+ýõì&öï6,]C¶&>¹%)jZ›ñké“釟q~ízm˜,¼ë”G‰¡JVŽGvõyMl+%>Òë¹·‚Ög°‰Òõ7œ,ìTKTAj'±¤Òv.Ù‰4�V Ýg{£(Á,y<?Iê~5qlè´4Ih¢½Š™ß_»Hcò݃qa!Å*¬ìÔš<#äx,õqô‹8”ÿJ`ÇH´Qzvû§’½™áŽd+eo|Ò§]Š&Õ)Ч£ä‰ÝÈ.É)«x‚!ÞÇV(°Zî}¾MR5º‹ Ê}õ®;$’§·ˆÐž¦f%•€d¿IIÞä{<ôQÍ}}ä"l.n‚ÅÈv²Ü_Ï£°bÞòÕS²ïJTšK CÍmðÿ0ˆ'È䓵¥}^ù£\TÞñë<j:a©©û3ë :ý4ÅÀ»ÌŽ`Tâjq¶^Òááݯע ‡_Ž{þ¡>ð|‚¼—Gàê›AÓeM ™ø}üÍUy£>ÊÄ¥tU4A€›135©ßýÚW<nã¯cüK:ÆÖ¬~£J¤ç^/)ËNfþ[m‹ý6McSÔƒo9 !þw:$Ù$M¨·”¾Vþi*WU퟊Hì&éQ¯Q.6ìÛ^«uDI¤NVýùõš“US¸Eëc|Øù?.»%&ߪCµÜ NíÉ$9e)kãQå̈M</éT{ðÌ Ò.«=‚ÕQßJ­Ù0E¦Â3>«#^¡±Ôjñ¡êU½Ð;aj‹²«Wºû‡ó®C! k^+æ|0>t‘Ú#ÉÞ“Íä40vÁÆJù„³ã:ãxêAîêÙWùà²Ú÷Ÿ‰ˆmyŸù'ÑVT°#àã¹Á‡oy} ¨.жôÕâ\Àæ¬mÊTXq›Jºïn=/*}pE^ XÀ¡G­�Œ·†?¼[P ×Äz㵞3·Ž#Ïœj/? Þgµ°ó­úzÂỼ€Ì|Êñ•o P~ÀÒd±ˆ`xþƒ|Ù˜f‘ûó"Pﻀm/ñ.ÊÙÑ5ïÕv—ÓD¹˜{¤ÐÊAJ"¾Âë÷³p>¯Oc{/v›êr@š£ÎÜËÒbTÁFeá´uÿÁœ/ÉY"ú•O|¤ãó 9äïGÎ?YéœäQx:ßE…ZX@Ì.ëqP=+þq:fq ¶yÇñ¤ÌFçïÈ\Äã‰^T<d‚lC¼E;(XeuáÁò3Æ“0­lj'¯3]ã¯kü‹ºÆŸ¥ÜݧûDªWòóX¿Œ¸I‘œHëöq¦`c?{»sË<ê½_^Ň²|µ¢«Ô#%uÏ zzž«îÝ‹Á¿Rø-5x †'ÈA <#—Ÿ_?`åš¼¨j``Çéõº•» •;¦Ù{tz7¼ŽK_jvÔ‰ŠíÜ·�2Õg¾]=¹¸ ‡ÌÆ!ð­Çý³Æo™ªó;‹ç]ŽòÖš]‘S\AB-}Â<A­’”¼Ã#Ì‘X²,Kö„öõ@*>e u6àP‚é çè<ƶ± »–¼÷»úÖȧQ°‹4¥ú}wa—š©<^¢æ0+¶Ü}#ŸqHîÙo /ùE¦x=øU`ôt;J%,{ËÈü.åÔµ PÐ<@söâH£(l•¦#(ôñÂ4Á _~í½G…Øî=ƒ¤ôÄ jüªNŒ|RÁ0AÜT}8^9M½Ú.àð‹ó9 Ògr ½|6¶M"áÅ.‚•_Ì,?IÀøv_0‡±± K`Ü’ã.Urò#ßH«„p©NÆä1ìL)OŒrZFø/m]~[­Ê„.™�Û–G¯^fò|¾¬¶Ý³ï|<fØrCæãlu _ªŸb£Þ„?¾!PûØK%É ~4.ÿLù?ÌÚ7+˜^Þ¼W&=ÈJ™dUãJñ[pìL¨i5öÂjÞ#I”â+.9ŸžçñcЫ>SJ­¿Îñ×9þEã ¤á•T.2£:øS=RëW½<ÛHö§%ñJg Ïfe¾6uêÊw4¯£°WìH޵‹Ú—ßö<_@fω…7ͶÃ×±ÙªŸ_?€íýéäþ‡<qN¢Úç?2«³cqé>K¤$÷Å!ù‚£Ô·Îz ùu–ßìC’J~¸‰S׊¿¬ ’`vèø÷¸×ÁÏÊS‚*’š*tSpÞIÕØŽTr¬ÓÜC}®3©¦¾”Rˆƒ:»¿ÉË»÷z§‹í÷·~Í€TâJ»$DÒEH¶Zäqöm\ødÊ  úOȱ’Úo?‡x^®F/u¿çMI£o|šÍ@põ[IãC Øîy¬Ê;.}žpÖ<'uÝU†£&Û;O¶Œ·R>U"žãÕlø�³…O·óÙ™Åbïzº²Ffœ´ªÇá\ÀKœ�|J¢WÙ̈ƒa‹Õ‘i‘\ùvù*Àë'˴džãòpß‹iåòŽ´L”&±Ê´u+:õF f Wmç¬Oš JV>¼Ò>`Ó,ÿk8o¦|˜¼ê;¶dì›Ý9Ia'~|HTâÀד0*Ê»Ž}O·.^ßkeõýŽD€˜R~dlä·§OÑ=/µ£"×<5‡ËR‚¶§;.¯*®â X;ÿF½æ›Ôá>ð¸À`=;$0‚z2ßxz´ HÈADì¡F¹‡|6¥I5^el9ØÇô×=þºÇ¿®{üYÒV-ÞƒéXí[WeH:‡)ók¡|Üq¬øª4-û�Ɉ"ô1Q¥×M3ÙO;çl�´íR–ƒNrƒKØ=sóèÎokE4õÅÜϯ çVñ'® nyºkˆ=åñÉc¼Ôs`IÛÛ±e¼ˆ@-Hu©lšcZï7€cp¡ö îɯr¼ÔÏר¦äžxØf¨ñ(;mR䯓ìõuGÈw•ØlŒ¨ÖV%0z�JÈ Nf?>÷HlŽ1J#d}-¹A‹ÉÓÕô6 pXLñœ½«ó{À<)”^YÞP+ÖüQ¼Q‚yÿ™J Ôé„ o~×+ÓTEN}¿öø^œ‰ÆöAT3¿ÑÙë6•7Êv$Y!C‚[&þ�ÆñT¬ªÓSñ”eN‡•£Ìº"z¬‡úÿ™j^»%ÁЕ`&å9h¯„=:^WYÃЧý¢¸¾]¹�7ùË›JG@“¶–eÕY{¡d�Xg[jw¦ˆxùG­è¥½ú‘§‰¬üΦT^–¯e³ÓÄDòÇ+*ñ†bzØ/1lßïD«Ý0UˆJ3*[–gÍ€ÚÕ»pëÏï’0\)ô%4ÇûyÙ¤öÄG(hعçkÃñ†Ú{Q¸±¨[ÎÒë‚PZ, ¹åª¤L©žƒ—ÎOáÓ­cCÍ’þDç;EÿÍki;=YbË«T• dx_¼ä ±Õv-ÌCMDE/ ½Ú䯃ü ;ÈŸgïýV^fÖmݽ ÎHÅNÝ|[Âõ*,Ò"µâÜÊÑ¥l]ÜCŠ;7»K°²qHLJMÃtøç@#ÐÔeÁùT;&¡šjÕ6pÚ/ðëHT QP¹¿.Û÷P‰&П4= sfñí%T…ú€B‡U•ø ŒÉÊg©ZYiå­Cá­çt¼S-—â?•~ôÉßÿmøŸØ“š'ÄU¥úþÔô 5T銂d¯¼QŽTù(0ɽڦ §¿Ò¼ÜB#§ÆŠs¬!—Šw¥x™7éLÂ*û]’qøœdI \)Saè<2EÙ£ÉÿÂéÂõêÚCíYj“uW‰Õ6”$O°kÑ.ç³[.Ã3¯´Ê=Û,¹žÔ>cЇ@å81 ò�Q0îÀÚ>IwêŽNïê``Žm÷O3Où©Ã7Çi_ëÄ4£ÍÅä)³" ºÊÊÀR0r�ÝÚòþu‚Rµ O lv·²q*T{b³¨ë{× »‡8‡kF|–©E––i{ÓÕie¦eDVÇë†ìeƒEŸ DÖºËvÞ缓ˆßm¬Q&(p+jžˆ¼”]Â¥EZ¨ÄYà †‘Ar^Šà `^+�ÃeÁ?ô³pûƒ‹Ô[Î!å0 ÈcçQ,»aBQOJéÁõkàâÌÚlùqu¢h– €÷wÇïJm²6rò§­hìò_ùë"ÿâ.òÇF ÊÙ€¥‚Ðø1éÆeÛ …€MIK ¢h„„cÀ—¼¤$+ D)þ·Sªå æÊ’%gRî’JQM¶}[¦üNfXÓã=Òºíþüú”å±±i¸ówk·0Þ>ª´ämŽÌ:ðG‚ÙWt(3´]ß%Ÿl±AY¡Ûk3#ö ^Ü$Þ­zE3ð°©ÔqÕ>µ~ð öy“½­òV\(Íæºv†},íóy¢ ªv¨;ØÜÏ’8üiNÚéÙb7¶÷Š-:Ð7}ºWŠõH‘å(‘ ž…ptü»Ý|ë³Åë¸=Ø9O¡ÊÇ»c¥Ëý·YBX$"íÛ15¢8?êiºm)¶: å—ǻͨYb¨tjk"t¤«B¯*¿«•á¥c׎úŠ:*ÑÞéMmø([’-–_DÁ¯b³çJY‰Á­0¿ÞK6ЄH`éô¥tçø5Ž%ܤ.Vìl–¤×gó*S $Úf;Ù%@àSÛ¹bt»—ùPµäáEœ>90‰§~°Àk[†rxï«kŸ%ÛÛ‹™_ ÀÍÔ`b¢åÇsv’:,¢‚|&9eRTôlDø'€gL#xù’ו,ß¿ó[»€&ñ‡†íZåÀ”Bÿu.'­¥Ý¶/?ó•x&V0{³ÏX™õ#k±ÕÀ;Ÿ·÷ÊÏyx°¾áÊ–Òó›UºYDÖ'ywÛˆe7„¿Nò×IþåäæÝäÇ#ïL^Ô 5j—’-æä” …26†ï„Y^¤õúû5Rª¶ÜÞ‡˜£HGÛÒdížOlöyמb¼+QSVE<y¹fy~ý€ý>e ‡‘Qƒ:GëH•ôš¯^ñØdÿ,O£ËβO—êRòZ÷ƒcº^ÊÄ>yJ™>%õ&Š€`ÕÐGÂV“„ti%KIŒòæüaeû7ùÅóäï¨2ßñäö¾ícl1üßtDŽ·Ï0Õ·íeŠøèQ1îõDßcÈîýq°§è‚6ªl€”‰jÈR[Ï55Ե䃒åÄËào"½[ZÇ SÌü¾’.92œw”Î<èœ÷v¼Ž°M æÈ!_ŒAÉä.ãxõöÒ.þ…ŠL’c`k¢5bà°I©y«þ4g僇젠a×,ñÇ+"XèüGYî½öu½ o”]BŽ×è¹cs�Fwâké¾68<uŒÛᦺï¶<rê„=/8³IÞóãg¬r!Öõ!ØÞ“´&R¯vžlï•_Ëð°—É  »Á‘d^?ù«¶ªNŒ¢ºUÅEþóO{?9G5a²}ªà¼Sž/0`²ãªÊä±X %Ç g¨7–ä•?ù;šK–ó]XI οXÕÁï•UÆK±«c+ïºv*")H�Ñ¢%N”Ñ[›Ž6Αäg¹÷*àxûÆæL)M¹*{±ó_7ùë&ÿ Üä¥,hbß!?,Uê”D¡TpRúÔIÂ8–Ý›’¥a5iâ²Ñ1ØlɇyNÙ¨Úš»¾à nêø’G—åÛ©/É«C£®Æ@øÔS¨o~ý€Hiî8•ÜvÖ™îjcE£ÄCq‘æ¯ò8ìËÓNuí#?Q_VH:Fmd9]ùÙÉží˜{Q $hŸ$¤GŠ_r3+®æxE-�™Lˆ%gåuUà`Ë<‰ãƒQÔÊù{^g¢·z€…uµÍä½”WWìjº±ÔªU9Ó@z<g‘iR±Ù¨){á£ÞÖ¼,ÔUƒ"“²ñ µ[³¼J¬FZŽ~ó¶·Zšã²øÀ\[UaJÍ'ÆÊb]y—P5Êž<u`ÎëTï×>RøÆ”¤#-‡ÏÕ„Ä,S¹ç¹__Ó}? ùwÅ—5*l½ßÜ<ß÷ì'Êj ­Êʼ¥”ûlò ¯˜ûQæÐÑ å¢W)5>Š¥v†ƒÏaªËA wäEm•žìû–ö«ÊçX=ÏxqžX\ÃpR?wÉH)ð¾l:ˆÁ÷Ý<§Jü h$áo6cñ½µce„îx+žfÙKtÂQŸÊ t] uN잯ê]¸Ú. m1^K8vàÏ .]¹%ÎÒð`Øl<TY/ÑäëieÑ>’…{'ÿpù$ (€¼YÛ¼uºJ£¿ËÁ¸¦K3‰½H ®”˜?{.‚ß³I3¢ Qï믣üu”ÿŽòGɺIÒ­=raÔZ”?h ~³÷$ƒSÏÂ?s�éˆ ,™V0K7 ¨0dòð@õZißç£Ö­*ÁeÞG^ŠÎU·-(­o^[VI¿}À—7¯)xpüNl”½isX¬0ù$ʼ û‡s6ÏŸ(Ã#åûCEä[¶õª¾–ÊLü~ûYÙ“Iª^µCÂk€]£üà+ ®Ã¨ FOWc*Isþì< /99Î5Ó·‹8¥Ež#ðüä¶ѽc�p8ì) Ï)ñ. J˜µ†!²�PQî Xùêãdq/«—Þz÷Tö ß!³7µ3žœ Oêò§Å†]óAß9sá�®‡ñücùÀq�èÇ$¢‰­–Áé»ÖëÉ ÿÛw?I“ €RüÖA èûòÃÄ•€€ÔmhU «NþH‹ŸØ½o  5—Ç\«ç¨Â’s‚²ÉÔ¨£|W¹ü¦†?²HzyÁU–y€/XzE5”Ùôˆ¢�i} ‹y‹W ½gcÞ9Õ p¯Šl²|SbÄ)Ñæx Ü|~•WwnÐ Õ‘'U©Õƒ-«Ú”8Ø5Ⲭm©±í6{Ð~Õ‘K˜¥ÿ¥Ï~®çOq§ÎÊ/â*T+ç§�­¼s}÷õ¢Üø@äÀX„¸Uî•SnË“lö(•y¢ýÛ±K¶… v{ßÚ¥¹ÜS5ìѫݯk€M”Y%ó3¯ÇKRùäW~E’Ã_Wùë*ÿM\åµR�»lJBO1‹ %ÆúL@Íy©&GlÖá×Ö½•x¨2µ™ÍzIQR/ÛN?½#L’y;ËðÝnG$Áâ"»S€®XXQ,}¯Ÿ_?`ZSj' æ"euôøW…RÐYoaDP䉪]ãǬlᛳ‘VÃÀ¹!o¸ä·WÁ@JÔ¨jåÿ‚$™ÈøËi±­ø 4ÀOÞX[Ž3‰&??帉å+æ¹/…÷¸Jo+˜ñD^Á€j�Œñ#`cy•*ûSp!�Pñ×åBlü Þ.L(RŠ}5F|u²â³:1>Öx[ìØ}'ˆ`SžV;nøK ÔVvTXgJ¥Hfƒ-I%uœìãëÖâÓØÁŒÏQ‚=v¼ R0\ï%ˆÍß+£ h•Ù)”ËâD0m”Khªì£þŒ?¼rœ»x7,waøšwö` ¥oÙi;‚Ô1-ªèUf¼ÙÜoöúÔy”eûpà`;˜/‰ÙÉŸÌ-Õ‡ôÂïY¨­½æˆa/‡±Ð˜Ò.àÔqzP`±GHÝN\%ý“.è•“³Ùe“@ÕÞ‚\{­Õ8JE0ðV %‰åêŽÎˆ ‘êxsˆX*ã<zDe£j –»æ¶¦)¼*Í’·ãVüHÕÁTX”ˆ‘(wÛ釖ê]4h÷Þ[מ>Úü%8·É’i¯l”Û‰ …½f®m|LšøhsYCxŸð×Yþ:ËgùC2ß¶l÷>-ÄHMoÁñŠö‰ÀóG6èÍðiáY‰Í'nï1#G÷J ×8¶AàŠØuv€Ò]b„v)+Ç”žÔßøuS¾Ø”ã"·üöÛ®{ÀŸ>‰:¾X0åÖÈšG/ÝåQ¸±û—ŽŠ”`XÉwÞãhw–Y#±Ì�%)©@c{%?\žJ¼ò¢0 Öx,¼¬¯j½x(%8ÛèÂT©Cy…ŒËóTq˜n×ëœÞ‹ lh9¾qU‚íb­ÁÖt¬¥î¥p.ñç©ÊÀÄe±«øE#ø avýxÄ­qb_¿3”ôxã‰?a€:ç5© øVl‘ëk—T@ec—‡ŽAÐ�’¥ýª«‰»µ\Õ?sf-؆¬S”W]> ¬á_)ËdkOc_ÔÔr~XŸ;u•í¤ÇSîQyÞë‰dç.ïïUêÃïà‰:ïóÚúEرñŒZ݉y™~Áz^&óY~§°ºƒÞ-{²ñ�+þ2xù-IňãrT‡':-NDT;g>ËBÛªÈÖ†­7Öî¹6]BÛ+•b”hs»³Ë4ìL•³Wüóë½¶}°Aê¸2òù®£©‚&€;9ò f^Ý&SBžî˜•êíóÇAÃeAqù­î1±+³Ø-ŒýírÔI(Oäÿ à]¢oÂ~CŸžª$ Z]*j<ùí®¥Í”»ÅC§iø¶Qˆ‡P[˜í$øë.Ýå¿»ü±ëœÔCíûüÂÀdûõ-RMQ2÷P=…è«IÇãÄ8ÅÙÉße¦A&Ù×µµ¸F´&,¥G)¡ö×¹“=*vÙ#¾Âõ¤_jKüüúê}ÖVó˜Äê¶ê®[ aå»dUdî)Ù%,XRoI¡Š¥é¹Jc€HY Ýqߢ‚Џæ>—Ç;’€vE…êY*ø§9Ï%“~?ü“CÉýIvhº¬~{Ù"jïup²¨¼Уv)–'¤Ü6,‡2¥úÜSD÷Îè(rVOÙrT«+)—8$Œ8Çø€fFÆmH逼6°‰tí ´ É6þdr{|}NT<CY…ƒ;å0Éï’Þ « ÞÛ{Š,Yø¤ìA!€²ÀSA2zéÐÏË‹×Àú¨‹µí#Ï ¦Óù­6ÜÚmeK3öï©MäI¥)¨|°2¹Š—Ó-ÖŽ¥}¬²{LÓ=˜'+'•«jˆªƒ6pî4´)=]€þir3Ñ<²TÅúù®$X/ub"%Jø‡4³PY°ŒÞ@ òì… d´€={;¢Jp<‡ºæxÿo7/y?¦ÇþѼ±A€>Ì1`_ Ž^šÈ? m‡êUÛrNÅN!,ݱoΟò$¢d¸^…Káó¼ü @|²yRD¶Æ'vï(ãÕ¢à+ª˜¥§}ÔüÇž'¢'÷òõð¡ 8›Ïêk«÷ðx`® ¶< ЬM…Mû_‡ùë0ÿ­æ-9ª¡“H†î‹RõÅ:Ùƒty 0ñ>=×EƸ•Ô¼ìTä·`Ulï7wpR+x�º"àˆWd�"}|Dw ±¼U¤dy(è_ª¨_? ÛÆGAªÈöÈó»žx%K°¥øà¥Ù!‹–n$k^•ée0tÉýÕd_=ÝnŒ¦à@í8œÅ’˜Ûw^áøHÞlUÀ[üfäxédÙoôæ<€ÝÔ Gu±fo¶õ´(j­¼NÜ<w¥·M+p:o%ÁnÝ™G¼Ò«<¶²l@Õ™KÀ[Ç#óõ ø~ÚöÏÆÐ€d@ÂÃ?®Õ£öÎ’…¨o­¡8}j•ï¥{ aŸ�öIÉÉoÙ¦ŒWä+E­œ;ƒ�â] x;![p¼ŸÏ.aË®vw Õ¤ò¿Ä=ÂKuíÊžT µ”ŸŸNè+¶¦ž^êû‹û�¡>1Ð ŽÐª7Ñk&7ç:A†,öHrÃÈÂÈÊ´í§ö²…¿å)|…xúRýF.ém Ê�Ë7ðÚög+Þuñ¬3ËwVŸ„ýƒ Ã,¡cý-Û‹_ÜŽB]ÝéGòJí DõnbhgMï¸Õ‰_Ëþé ­Ù>ZõGóÝ‹¢ƒ £~±Íkö¬üsÔ<.X€Ó—ü“ÈèÛÓ—E·Âª¯“BÔG9`ä¶€§ƒð½häU˜ùAôø$™äøQ>+K]ðz îf¼å]d´ø×eþºÌ3—ùC6<v¢¬ó|Ì"Í–U^?ZÎSuÙÜj»Â)÷âØÀ=¤aU&–?pŠK^È;OiEá¾r÷Õžxð„Sáü FC-'æ·)ÉîÆ§ÓøùõSïõ ðs¾$Ì š“ž]6,çòPdÛøÙ=…UÚük“IM¢R,¥4 =ˆ £(é"ÆÃìä3² “ü²Tã yg�‰ Ïr“Ú·<šž“ÞSgh˜™ëe{ï#3¥RägÊuÈ×SàUæFÕw_ÌM›$Šàô…Dõ…ýz,ÃÆS ü‡øÎD–9³;8J>˜@øvïboÊ�cñ «‡© 'ßüIÅÝvª7 |Sõ®øÞ!ÏJªÌüñ×­£Ðr¡w æ6ü´—h ï Ä:ð´g7ÛÙ<b@Ù!´dÑTÖÛÈh²e–¿9ªðؘU&žµ8s’# ¶”½´�€åæ°OǨ/R½J �Œev|¤äT”åæÜ¬ÿ «}¨ýe’––¨ü àÔι—(€¿HdÅ·ÅKè¸ʃ9ËGçøPÍ@1¶Bääå/®[AíB~Eé(>Ä´oÈ)Æð®sæ—b„ùpÊñ«¥XôO–Þ4'jKh�^®«ýE§%è27àu«T¢¯ò"£JXy=Âã*+.»DÞD›ó¢ž^’g=ËÁýÑjÖ—¶ÉO.âF^óÐMÙíºHð’pÆxø¤¿Nó×iþÛ9ÍÇž“÷¨"³Cžî…}ýiª“̃¯¼ÄGw€åü�çÑm¢IÎgg¼Œ:ÈAòñf„Ãù„"ly•˜Â)•Q(œVþùõÊX,À˜WCku»¤ÄµÅ,#—¼é˜â_¨€£üXÇúÔ�A|ý'¨Nî—s¯µg¨|]CäpÊvþ;Øöz›ía¤ÊK9°jžÆ¼Î ´É7n¥C¼+˜ÞôUç½}ž)?¡rfubNõCqÊqÚ$’¾qöðN hŠ©©A?Á>낎Á6ÎdØX?‰[O”O`x*Luk#±$Âïã㊨ ,£PÀß¡xð@Bpü>NÙ�‘-™[Yü"§™ŸETßè¶³&Oö2A~ƒŸ*Ñ“õH«6‡Á¯|W ¤{¦†íD?À°B1Û+鉯ŸsJz½Òû¯¦¾£7Í*Ê쬹ÄÔ߸&8SWšº–2÷#ûp�ʯšâ>;S)èkýFÀ÷w..wtéCîPÀ%±�,_$è›±,�Ê·ÏHPHv<ï¯õëË—’ d6Åß{k„ù{vPñDá¹bO©ÝÓ‰ •¤Çz©Xmö¸vK${V#*4ÇäËRA2o‰¡ PlâªupÓþgä£ÿ�BD ðñœ¥ØÚ¿‰­à!ÍÈÿ´ÙìŽÛ|± A“oy±ÐHäÌÊjƒ!ÓKÕÁï·!ƒï‰mªËVæð´ÊÃö"8ê¾e“ÈÇpVþºÍ_·ùoè6T¼—*%gÓÞˆ™Îö¯nùªÓjG½†ÝxÏ.§fJiÊ#šìZ¶Ò?´³B`0Y'ïûŒüRä)\7Uõò~·û®ÜØ`ྑðýóë(akt²›ì``•»~zo}åD¤.gMóŒvéàÙüó*´iÈ›?åDÂWÅ{éŒcüŽ]ôÌ&e»ˆ؈M ,ÆX5�*0x?Qåfa <|I‚˜‚ù¼Èˆ^Üc}ª698樦×ê_?*–˜´Ì$9£3ðÀ±~’óò‹—¬1‚üºÒà3`Dì«—Åî:S‚äQUö«ÜvnŒÿ:ð©…*žñçlìâo½jÅen´µSÒ¨UòÒbc·÷©¯ ÎÛ¾[TÛÃ^/�þ·Ô| Š"³`ð‡Á€uX|à”8 LÕ»-\Žû…$âyRdea”£Wa_‡Ï‰±‹ºÙ›j€‰©ƒ$ên* *% TÇRù`© JËöVÉå‰áÐÛ=­Ï€Hygì”ã6"ÝÆõvÙh›jë+A©{=þ,O½[-\:EÁÓjÕ º<q‰Ù_2ŘF4…ÔTÂÛŸìföt‘#àþð!µOÀ–·1·gÇ|0A*Œ¬½v;ø#¥"ì°J’™FÀ´Üb?‰@ñÍ…�LSc'¶Ó¥€S²Í»›ì0Z¬/¨k†Ï˜CyÙÙ0š¥ÔÝ+'féö�Héê9ß!Ìa*×FuCšômw»,T¸³'ø¯ãüuœÿ–Žó‡ê&£5n`ÅŽ’]ç°ÔàŸ%É*èOY%‰‡]ÐC!öxmkÊóè?‘S;· ±ñ» ´SÏp_} ~Muñ‰ÃØ[ù²æ¬Þϯ` ¶OÍãI¾W¹÷QzØfÔ½^›=õ•¦q ¼Ó\ÙYÓíòËb£ä|�ËÄ„€~)ú›÷þFxz°£ãØé¬C“ÅDéf ›Öaö˜²*ïYNòh› “‡«í›.Y?o~s•¶ó‘¬7bMN¼D³0°aðk«Z› ±¥})“`Uü*¢ƒÿÝGñ•¯Yz•á’¬˜‡ ¤ÀûrGï‘x†—>]V¦â¸æVKÚI4ªÙ,þIŸv¤ hãáë±€ÿZÒ:q0:0†Ͳéx¢>W¼ñ `ãÛíWÅ&Ÿ-wŽR_1í4A×#™Ný @sŽð©­°7Ö¹<UP�§Jè"·�/4±uB›æ€Â.Ã:âI™·ãMãLi$€ ë_%ÌðÕ/¼: ÿÄ©ú(ÙÀ;{±i‡.ïÎ~T|s¾™Oå5IÁ¦ÿv`Gç]žÔÛé²®á(¡ÝÙŽ½^ÅÛÛöȼö°fC2¶S“[ü:Þ³<kQÖGµ%p´}ž$P *Ò-%¬ïÒÅØì·’Ö2€{2E<ÅÓ&{«2ç£þÆ0ùo'ÿGyÑÆö„—¬w™Êa6_M'ÜêðRº¯5x¯à<¼J*ßð;Öî¾’zJ„Á!EKóò&¨9K€Ë©Ä”ù›¿®ó×uþ›ºÎŸæE¢º îæBq¾÷‘7‰ß]©(•m‡Â^Lêʈ…/ RGTf«}„‚jG*?Y¯Éy:Ñ=Å­/Ylã"ëH’\_VÿC¾¾?¿~�è;˜/î #·ÍôD\L$5²ä3$ÿ€el@p¤é-_©íüx´™Ånݹ(ÉÓV·ßW,<Ó”¼«4RÿèÌœ8N¹ªq6=t)$V9K€"" *Ÿ¦øó©ßTÝmüŸ�…?½ì¥JÒŽ¼Nȧ ä*5=�£ìÚ?À`0í’OùØ$Ó?²¨'Æ@¦æ×áJüå‡t ’“pª¡åyª¬É¯²ä+×u\êq]b©áæ+u¶%øØ–Dy}$ëœO”Å&`Þ¦Ù$•¼6EúaûNwÛb<ëYÁ\QXÁ¼9ÉN±qÂ�õà|z´…(²¼¯Štž,ÉøÃ·¨`ÖÛKA¯.x4€C;¾=±+�leW°‡c'ÊÎ5ƒs-­•H}»ÌúùÚˆ§>DdJ÷]|°ñöŽæ\k’äùÕº<ª8$aà8“´Ù4?«òº6ôÞ�i“ßrÝ¡“_ÕX?N¦ò=WR{ßA°€üq$V%x–ýni=—ë pœÛ©ÇžôÇ™Áˆ¡ööð»ìK-¤ó3³ó÷£ßÅGOOc.ËÊ?”k3}"ã­Œî�ðK©‘–¢{ϳ¼ómF—ø }ºGzjGjìÀ«**±%Á"Û‹'V^Ó¾^"Ö$0ö¿Îó×yþÛ:ÏÏUÖÌ#©¥;kêDœœß|ET4* +©ÅÁvm RXÁ']€ÒÇÊáq鯤œد“7N<Þ(K6Ö8MÕ%y?Rš³§Òýüú£Å€çoîøFÛc'«w›QÒÏBºôö&æ¼®SùÍ™RÓ¼ÆÏÔ‰¾à1åƒgŸR¿3– ÚÀ—%¼lE"”¨HÛ˪=(¨äQÖ¼áÑ ÀO%@¯ ‰AYNŸÂZrü¤HŽœ>Ö‘(ûõ!<HÈÿ51͆\]þbÅ’µ¼7’ˆDíx®|±Èà Eðx.Èó}'è+×V¦—»SíÏ+•qd“ÿaÀP‹§TËÑóŠ·:eG˜RÉ̳_G3ÔY¨1;¡|8Õóq¶¦+x}7¸ëh‹@ÑâH6Ü…§,²ü0Ø›=­žàËnÅBŸ0‰[ÄJ/x»b‡ké…RÂN–Ô9{0»ý]¬fº<I!x¨KÐÀ‹›ÒeÆ­ Ø~{¬ë¼¹ÉIzŽÐ*^ÏKéž�ú„íLTTW@Zõ9öÃMüÓ±¢A{Ÿ¡^yù¸š­lO¢&_E|v– † ß;Ô.gÁ&¸±ö{_Y7;»Ã*­È©T¤»sކ_·løŽÁÙ° /Ó©Ê‹îŸø‰Q÷ð4•ð'ÞÉÎÀZ`+ Ûã¡ÔUî/òøëˆO% ŸRÕº )c•%)¿¡xÍ32«²‰ª¤#ê¨4V‹Ö€ª2Òê˜aã¯ûüuŸÿ¾îóG¹x’Óç"”ã®åQõG^€lTòüW^RÎã¼_ÅGj©ËU–B,Ž21Ú’³ºêˆ�PÕ~ä TþÉëO?Z‘Ľ~6vy\¼?¿~ÀÚm*dÕî2ëO,‚í(=p'4–P±Oé?²‡á·*W)–°Ó ,jbPà ËÎ.ûô”ÄÌ<Á³lŸM‚ÿ÷ídÿ·¾žY|’ÎZì†Ja¡©ÆÌâPÕX–ãì>عV<Pˆ`]½påÉ}6‰ßœßóbµÙüäž&ézù-•‡<ª.¬ bþÆ;~Öõw*8VdÛ¥³˜sTœ7àÃÏTÊ*lVÖE äª+už}:ó]/ ÂR~õÑ7rÞò/b$‚ÚQÙÂ%–Þ gX|&Ю»DJhÃ5äå€Îúò°›µQ¹G9ŸÂÿ+^9<©K÷ãMˆ´Ûµ+ì­^õó,V'‚F·ÔYÈö1Ѭžp¹MÈ©Õ ç¶G*Á¼ã¬L|ì»E5üšü×+¿~ã¥ôu_FæùçvÈ«g§d«ˆ³ÛcÌ rì#°s4qPp€FÕ r¨þ•‘AN<̾Sdë¦/@Ujj>Óþâå`Ô쪱ñײdEI¯µ5a¶Ûó'ãÓDÒÀoÜð§â²H}�ßÔROl[i;Þ\£¤µo×]6“,6‹ò…m{+À9ÌÉû`ÒñLáÕNŠÁÑ½ËæÝFOÏ’l‚¿ãf¢ðûÿÿ:Ð_úoí@ö•²¾vDb{r.®HE´þǤw|¹›Þ n;“¼‰ܲ^'à÷(]LÖ¡pÇÚy÷Öã-ªâZïô|sS²b–á;%Î$ë€}®4~ý�’à°BÜ]xD¾Wš„ v«ã|Þò4;�?Ài)9âOîYp§ôr!|=ø1È¢ì¥ubÕ�¢ϼ­ìD6=Á®VU# BÙûM6­cP>§ ”<“áÃälôػS<¤~_^…Úqy¨Îÿê¢’Š€À(*¥*ÅQ_G“—¯Sý°—7ÐQíåjô{J¡†XW2ûßn£©?–|X¸"˜ä©@0öÔ3±Ìú¾o‡<i¾Øj®3½qIK9l÷<7ÞK.lÀ=8åP)„gbðINÊ——Pn‡t¦Ó R~²ãñ0´’²JòqëòW’î˜ÁÅxÒ«ß“²|¶ä¸ñq½·_5Lmbbð^äVõ̧À§0e“2 (꽕_“_lÁLpA씿ï\Ö½&ð ™yÔª¦U<Û@ñ€šyËÄjSö7@íõ2J Ò¤$é› xò%yïùL'†‚äY •¡Á[9ñ@ÐÏÂKOuÇyå,%Å,e,úê¶¢ó1#àF¬öÚñ÷믆—Ó/«=ݘ†×Õ¯’TÕÔÉR‚ pµ�E…Qi[…IëiÙ…»|dÆ;¼áÜ5Þòà%0>+ËN€–‡§1]è¯ ý÷v¡?T\䦾ZUR^ùH—*Tžõñ–zx޽ߴˆ\Ñ›½›i’^Õ}súp;뎷ôü…lÕè)±Ì ƒBPíáæêÖê`Æ”ìÚ¬8àϯ@æ{)ÅW‹¾8(«Sig›˜¼Ñï `EK;›Œˆ‚ 3U£¸=6|Ê*‚eZÂûü?¡ev^¨Ç¼À¼Ã*X•±¤DØè1j²:oªŸÖK9{¼·¶¯v±¹© KÞþ©¬àÐCÊûùHpÀC%:ÛNšaÈÎóžÐK~…qYR3àÐ,3EЇ²5NÌdxS ì_cÑǶ?F·I(àøÞÞ½�ëȆý:ÿ#(R“Lj¯Ö­påjf×±#ì#ˆÅfejp Pš›ˆ8øc;ÔpíÕXo}dÊV?ñ;¾O} ©Áb•GAZÕñMß(†—²´8 YÛtœJB"êlÂv}ïQ@¤7§QŒÃÂÀônæûÕäÚà`uwÌû �#<bÓfSº§È€‡Õ'W-o¹—Ƕ%2ƒW)¶âß;Ðp6¢¸/ͺ­ô ‰ ”×ÄIž¼¸™`^iK×ëï©$öv†GîëDþPŠ((OG’ ô}»òAüýãÁß”—ÕµH1¶~fÂÎþ «)ÛßýÊ2¹ 7mQù!¹Ú¦Ù­”à8¦+m±’†Î8½Ì÷¤Ê¢ËîÖ¾Ó©òzÚDΩol Óæ½Ù¡@!+>ñ¯ýu¢ÿöNôx¶mï« ‘—„ˆ­+tó´£j…Ï9’CvÒsV YÞ.µ3µe¼Ôó/ÅlÑþ[ñຩ¬*²Ç`rÇrS•.e¯©W¢¯89+²??¿~€zX˜Kͪ[¦³ Þ$JÊ([˜D ÍVÞõ”Ý£]8ÞŒÎEÝÿx?Kήu>diÎ.ÐÌ‹æÆÂÕ |Ï|¾ê|Ê í?Y {¨ïŸ Næa¥ÍTŸ¯Z §!«]Mdþì¬%á`ÖØí§r<´ôÝ»¤ ïQ.œ“YØÎç{ZÑ+žoQL-;^¨£èö /õ³cbÄ8àÌmwõpeÇý¾{àï.–ú„È81¢ís‡ØÄÍlXó�`$9rQ“wøžXñJ– ÐÁ“–™_ùJ?ÙšÓ$_91yÂÜõ¾¹ÙÁ6OÂÈ#uhØ©9ü*´TÁ“‰Ä‘¨ªò ÁY}¤˜e%Éõ:ÓuüI…ÐIP’; yzŸ}d8ç/åÁÉ@7uI->gA°W+OÎ|à*xÛC1¿Ç7‰%c}÷ymÂÊy}-Á8hrMS/°âþ_þ¢Ÿù(1u^;~“"¹ÏNŽ;ñ|= òMè·âCNØs“äÛ«jJ+œüÙþÍb%0‚�º`8¹CIRkÊŸÆÙ„EXéßÕý“ÔiÏÛ2ÿyuù÷ŒÂ‰ 1üN‡Ð@<ÎËãÿî9T@`uñꊡhð‹ßßH)”ä PÍj²2%KYÇõ×þºÑ¿ýauSv–ïYörw“’˜å‘y^ÛŽŽçôÔH”‡�ÛÅck>M<pexfißU¯t(øPq˜eÔÂ&q°I±¯7Y;Ôºô”!Ο_?�¯¢öäż}äÈ€5Ir6Ÿååžµ¤q@…”ð+Þ.29¬†g“a)�3¦i[*;D¢­ü¶‚n ÕËÏ�'¥íÇóUñžq>lлU=~8GW>Ÿ~(=ô ìÄú‚ ¦âÔßÔÏMR˜Þ”“È!I˜ã;†Éÿ­�Ò‹É ku­ìý­ó"Y ÏPm)#òHüÕ»âÕ»\ûpø5À÷>>õDZ|o]þg@þnƒÑ†,bs¹ã’?Ô]ˆIï`ù,ÅX2FKƒâ¼»+Ó‡”tkIWàùI޼‚3«¢ì•gÊkâTU¸èù&Œ�)éDË &ͬR;»ÁO£T*ï"Ý{ZÂÏœ´©ÀI[» YÀE-Š'Ñy‡‚cÀ`ýKVxbH@Ñ»2·NÉ„´žt>ð;íz �Ê$­ž/ÜqÒþaÂ'ŽØxÔzùÄû{ʆéí»˜ý­2¾^¥`8xЉ&[†²@rT³€¡vÞåc®Þ㨇žZçcÙ#p-É XO©Çzþ¢m9>?ÏUh‚ÿòOÏóÉ׎뗨þ¾l-áp‚þæ?*1]"y¡ :C¥Çs Q%Ì,¦¿Ç1Ë¥óÄ¡þT"ÜéÚĵôéÌ·Eô°§ò]mà"ý¯#ýu¤ Gú3I¥N¨›äÙL�’2ÁM¹-VÔE¥D¯…WÀY–€·ŽáéDvF0œï!ÃPÐF);‡r™‹Êq/E‘ƒyÑ>PàæZ[U€ó:¬ÑâûóëÔçJÖå©í Ö!µ¿u-Y €nûª… n`g1—›§w›ŒD3Ø”㫼QÒï~R‰givz΃ç;6Z=î\»¢5¿úEcÎ.@% >|ì÷<’3z”­+>„³–£LDÿ„51Jy͈ð’úÖ—GÄL¬}ç¹µ~Ô1Iikžµok§ÔÎÑ¿é‡Ç3ìZœ,òøAžÌŸ}:×ÙW)³‡6¶½>!Ô+ÝüŸÖ ¥Œ˜÷w }F™!lœ(]à §YË•ïºÈ9ó @w{¾ˆÃˆŠçK‹ ±_É>m.êZž5¹àÆsg³ßÛæì’ËT–à&ŒêÁ‡Ú&_2̸C¹ZÆà mûø�½W§U‘»·ü&�pÊX ”¢ÚÀt”Ãta¾ue‰¦îQ¿Ž�9o r·_ãi‘\ d >…’+¥l÷ «~Øï–°îø}©ˆíh¨×'X’rí!ñ?­œÇn¸I ¥<•€Q’Z«ö¢X«Ã2Ún«Äuü˜â˜-fR`€ií<.Êìõ‡Ý¡¶iZþÅÔ âRö°)²1Ý[Š“Uå«Ë"[F($tÄæð.H3Õß-Ç<;²óÄ“OcUl÷RäŸ9®Ò`^ÿð£?'V„òוþºÒ¿‰+ý‰žB·,•⧨3„Žn /®„?2œŒä‘EÂ0©äÕAóFÙ$ d95'5Uû}bXö÷Á»:kðõÿ¦[òÛ++é ýëµöϯ)°A¤kºm-NžãøÑ•B˜õT�TØž£‚±fú€8:¥¿ÇÔ¶ªæÎÿÿ€ŸQåScqÙ.‚ºq¶øUZ5âÄà%á\³)é÷؆<ÔÑó|?ð-[ó’°¸É'ð6©‚+3%DfÍ“âYÚõ²g’«ÛcÃV“Q¹¿˜Œ÷(ìHòî�>_ïJ€¹p¤ß6Zrþd¼€I¼ñÒSְ﮼nÞ�SeQ—­Ža¼“ðY¥?8JyxŠgñË—“M^RÈb&5F}¤•%}T nïàX®:AÚ£¾ƒgO€ðÆ2ŽUÙhާ¬üÍ< œ%*Ú{µ?÷èæ^+\®]Ùêözvá¨ÍV£»·O¢C¥o¥?­S@Üxx²TÛ¯ŒÔÀ=–¼¨ï£Ð>ÃÊw�.iáUý¬àx^ÖÄöó—U§Œˆ›zÿà¬o`#.QÒC'Â[Nä -©QÿPð„H5$ÄCz(R™n `?‹Õ·­B–<ˆ/bïVlâ 9xï³TQ’P]^½é¡¾š'@Ôª.××ñ ÅïÃÈi‚_Ù‰fÞØ^gx(„{vO#i¿ñÄ´¤ò]v‘Ü÷;Â!õYP÷ÍÆ(5€ "ÆW‡nï!cZÕ£%K§h›ú"9¾Ò5u\ÿ:Ó_gúwq¦?7´!»ñyvúXàNî±h¯Ü, -«² Ú‘È&ïÈòÙclŒHVÏ–½È»ö~7ƪµ< ¡Å÷³´xMZ$©8ÙA²&73ÿòç×hrgÙïBÚC¦æª>ÙV=4}S‹WãêïðÌðl ÝBØÎ}O;íüÂý*½Üù%& à2d9Ø€F…­'Ùò‡ž‚‹ªõ×=þ÷j>ŸE†dUt¥î‘´ÓCÌ_+2qcÉTïÞ¼ O›]—#ý^¹Vú ý©/ §;ùi;2n*²Ñ,,¿'9¼û9ãòx=;ËÚpçj[º ]f`¹`¹ JVËì–’¾R<QËé˜H!ÚùZñåÛåëíø"kf¾'SJGÉöð·—˜@”º®Ö t%:L`<ÁHœü& ìi› 4ÈŽ ¶Rej?D¦m÷·|.êß=¯ÇFûM¼ÔÚ"Û&}šü ïzã'ˆ`CuX/€Ì9') ÒV–!½/(¹*O L<„ÍNØúäæ_Ò•_~°x|¥sW©yPõD°©Ï³ijs§òô8) ’„wñÑûN²c°åqg@—¾ÛDWåNlV¼úv‘vÇyÌSÞ,2Å^jN,o©ì`Æ™,ØDÄÒ)‰lˆÂRôÈн8«*•‡ñ<ÅK */E¢z¢z9ÊS^ô»>ÿ8DLœ”€pUyû0h%½v Rı&Þª{Ÿ„¥ýÓôQYd ŽÚä¯;ýu§#wú“ùÔ}›s`øÅ®ÏëÛTËÔš³ðV³Šÿ&ºxª’ÕéýΨ¯‚|· Çå-—'EzkdãÅ>{9�<Ä6c²PsJÆ™üˆõ™Ò~~ý€øÍرùx@廄Ê/ñÖÓÖ~.K‘žf‡ª7AÕ�;? Õœ]•øxXÍ^–L6Kâè-V%±yg’nåMN×c'Ê.pZ+¼¹>Dqš:¯Š›à¥FòÖ�¼ãóøHÜq¤Ý®Áe·èµã%yK&ZºhàÜ­ì`‰ÃI“¤@ ïŽc7�Ò:(ìÝöâü @*€¨ì*•=&XˆL£©<þx¼ý(纄nMí¤·Õ¨ (%gÅb«ê쪌ú¬ ˜ôr¹>sñפè�xB¦êG~Ù�I3ÕDPÿ§(¸ÍøwÃ"�†i­-ûŸC2ÿ4vDšv¶úŽýMDò #òCñ‘µöݧ/Üö:ô29¢]ùÃ냶m÷¬¦)þÃâ%‰®R…j~ÉùÙ¤_i³È„܉Ç>{JßVTH êÌŽ.Á· $õnÛòÓTK0êïx·Â×pÞÉ,Oª‘_‘›ªEäáy„Il»§dÀ/(r°ždíÒbé7`ÚFTµÃÞc±°BнŒª€\¬ëV�¿z~VMJu …esohóÈT^GŠÇPW ¿òÙ%8òe)÷Ç”]×S×iµyXö²á·ðšízõ”dí®î$«\Â3æzNÔÞ|³¿õסþêµÿ-¨Qª˜ kF®’ÎË0{µ©´0œeÝÅ¢šä)ƒv ׳°ÔL-ž”Ýî ›W^_úÇÊAV­(±NÕgª­È±EPÃϯ0]Ê9ÙSyC;[Cfgí¼?|^Y‰=ÈVà‚a_ e}ƒ=SB‘¦Óª,~Œð/(ЬqzïÁÃÈ®ubXó›ªÃ¦¢’®$ÞN&ÆÚg•ú´+ϸŒßí}yqPÀàTw½©É÷Ø5Ôã#°ƒOÿš›Þ,’Óüýpp8¨îê¨M_r—R—× 4•¶,›¯ì{8š¿q1 âj¯@åwÈ"†©µ@|žiƒ}â¥>H! a” QñÊyb^Óü®3I'¶û~Üßûò[…ÙÛ©Ô-½¯"OÂR~»¸Ô©'µ·3> œçµÚc¿¯ò?ë€óoP˜$ÅŽwœ ¬ãã+;6ÿµ½"E‡¯Ø:/f”õn »&¢§lR{?žœ]5S_©Âç•Ü.EZ#[Ñq,,–­[b(ü6çî- |ñçr=­çÁKË>ºg${ÊS8ûFñ«@x’xé󓢂@Ú9°¥>(âÅ�®RÀlÛ{ms¨,Ìçµ<{¹ÛÖÖ/]ÆDVß«¥À*ƒ‘ïWÔŒÏÏ+ý~+zoFHÙ’o(<\® �w¥‰}bi6ØÛ·–0p?MNýÇ[ëOì ‘­¯&J³Cß×X§ýeê$±«R c}¥•ýëR]êßÌ¥þ¿UTk[ú}eѾCmЧîð½b×tîˆb{É´U1‚Ë®ðÛ,IYL¼âVÛ°‚ÉUJÁü¼öJYÞ{DBÔóºx çEms()¶ýüúj€“ôŬ¥Ë:"¦-h›œ.×´f1L{¡²sÒÁ`$v¬`ß§¿¶ uL[:€G†Ò,Q‘E%™1”¼T_¹”¥Ú¶·Ð#êm9r€ÇÛW%æ8/X¤S[;³ßílV v ñ”|Ñ=îøž² Ú|6ªr«nÁiPÅ٧ݺ!÷~€“j9©:•¤C ¤(N‰k¼xyö†7Ý7,åçZ0;/01È3„±” K‡ë,©w½÷åO†÷ÝÓ¬ž6RømÀAÖqÍÄŠ(ˆØ”úºéÞÛmºOð×6!Fü9³yù8=UÁÎÄÔì˜éY¬´Â,×'ÓÁËl±sL¤2ç”ãåW„ønÖ’ÈóUÅ£+<B€*\))ØûÆo–úÁ[ÚØ”Jaïmp¿ x|Æ™[Eèùír Í—‹Écàݱ EË?™Xñ ª9-CR¥UìžÍãÆRtT sÂ^õc©)l÷;­È½:;¥†Æêøç )�=íAlÊ´¬¬`á[zÀ٥ʯ禫P"™ãÓ¬PekyG©2ï‰ëbž?[Ú‹ìpmµ]^2vÞ©¼Õð0AÉüÀÒQ}‡õ;òdç+ˆ}sXXÂl_ûq³§g)üøyÜmÛç@A“ò‘bh)V«òqèê¯SýÛ9Õ¥nìýßGQVçÅ oÓ¾¨å1ÈÊßPO‚øù¶Öë¹²t¦_ÆÎb”׾LJwÜEŸ@ŠXØCt¡Šïý׃m ËMÀAåaÖϯ0WÃlªŽjQÏ IÚɳš75{–@‘Êâe‹J:z¢“°ÜAiU¸•ˆbÔRx[xÜÜ.˜Ø›t=ôÞi6½©Æã´ç–ÏF™ù_Þy*UäpS⃺´ R4/^ E RÏdyÐ6¨L› Ò¾ù“7:ØÞ¶¯x¾jÛÊØKðº¿}\iña£Î *ÏVeu¾žÝZ¤Ž]®Opzd#—”cíõøü ;ËXÃÆÄÓ‚‡Áƒ€çªõ ñ“ XíÞ´VàzE¥-®×¯A’¡¡È7ÎR|}†mͪóF¢“&€^û“¤½Ã¼¼Šx ¥ùQ *ÝW¼¦€—'¬½yznó^’¼Ú@,gZŒ kn²ÿn�ÀO%®FÔæÕyš‡#;¼£ H%X”Š{>™¡—âcu(VÁîƒ_?ñ.žÎ}¬KÜMIøj±”˜r®K˜ÀK¥k³…Oh©Üß+ˆ´eÚù ÐúÆKdVw!¶oBדªb•ò¥ÆÃÈ«Tb?5�…s*¾VVU63'¿8epĦðe\»¾ÄðdXuv½ÉV#óù|åUXZaGð>¨¾䯰)ŽUŒž)»L{DÓùz”%ˆ¸ £KÆ s™ê_/ª¾ «EþüëVÝêßЭþ(˜ÞU¤ŒÂ<âdé7Å ‡@)ñ®§–”ª\y·ú{NÇûödkyÌøOƒŒ|¥L[àÐG•>à‚û¼Žä•ätI ²£|„„™“oÄ(~~ý�çØ'Jy>9½I¦ì¡¨°AZ1R8ö©vh‰9‡°Ù¡a/û!8_øuu5Jõ ý[x‚×û½ TàH¥{Ê­ÛeÿÄB3XT൶Äp7 ‰ßÚ·Do ÉΞXÅ«Þÿfö£¾RÍ| ®àdN™N²<Û`"Î*(fÞ%OÀi°^,«*È]x¦€§m â1θ­ó=F›°¤¢Æa¿=³£[ª§.ŸõæÂ*¶ ˜1ñî\IëÀ-e‚š>–uÜ-_ë‰%uç÷bé)* æbxx¯å8ðw u«Œ6žXŒ)ÍQ±›ýÃWr˜Êc'»Dì·ó£øD¨¶`«hDTJç^zìNà~–ú¢HCêv llêÜKy–eÚòëÇC–£p¯›ß˜Šó®xr ó}ŽÄíü´2µ²tÌ7¾|[Yþ6ôô¡òVÉÖ^½×K 8=å—œž½zû–nS&¡‹ß¼ÅOf¡§Kµ”Z M"ó† Õ:¥sÂÇ‹XeFâ…ç`åä«^»ù§?¬–ƒIgNâ_‚‡/ÕÜqxL†¦²ûó4~Gì m–àÞR¥:=W¢r2š†$ù*ßuA?M%èG–÷1b¦ ô¡<jÐÔêmÉû×±þ:Ö¿¥cýiϧëM5€Ì#]ŠuÙ3ßC®¹þšJâv¾ŸäÛ¥U³QÈõ¦à# †wTWñbCí‰ÇzŸq«ý=)Ê6êi,Ð-솱Ÿ_?€ý:üg÷ yžm Yÿ½ Ùdœ}?¥ó¼|“"@QÕø©'ž·Ã’¬CξØ5aâQ÷ï­X°Ú¾·+Wú ?:ö-«J`l9|xû(ÝÚPþCÃý\E<£u LuáJ6‰ƒš 8»®0…³áî€CŸP_†é bÅûk?5ðPßÂ'o¯€Ó¯a,"‡”5ëfN¦Âöa8 &ðÕ ÄdÇ~øIìuŸªZD dÀSRióžÄ¨%G êÅñûPÂsp¸ LÂT¹w_Ø>É›ÐÃkÁ¿lß–ëaÖ¯“ª½+lÞ²Î:åØKjøtÒ’PB’vâŠ|Kìxl&¯oˆ™ÿ“JR2àÍ­… üÀÉ øŸ æ®ü2ÛßÁdÑlðj_ º2¾o‚Þ ‹’º@¢B^Ϻ1×r @ñR%¹g^ÛÎä~ lh\.³tyDw°V¢F˜äþòÂM¼aHÎø—ÆOîr§›ÂpPFØÕíŠákÙBA–HIÓÚìŒý¹I哉LÊËNñ¦ˆá[“„|ûg9×;K³Î"\DG‚ÁÓZ`ý#²}§Î� íPÓ¡Âc–dÀªŽ}ðÊnŸûŠZ”QxKÌø>™ ň­v¥YxG:Y6ÿu­¿®õoêZʵ¥f�è(øvjy-ç&VøÔÏpïR±\Ÿœê4Ùd”–B³óS䈥°?8Ø»±Ï½¤áNÕ9 JÄ L;°YÀ9½?À ëΛ~ý�Þ—²¶'Ð�¥9Œ5.<F%(v‘Ͻ'–ãÀpô€)§(Oß[™õÎ={Ô­¸ùìu„qßÕ[ØUnV*sàæNˆ7Uù bmâ“*€v ‡çí*ׯãXž6—{”ŸÉ’†Û|´ïøšr" ¾œÜÆJëRæ&÷wªP+ÎX`i B(—0|H_É[KGû”{Qš°´ç®‡U,sp&)Ö½—ÁoàŽÝÚãvK–Dm—lEÛå–ºa¯ÎΖ¤ #/ç˜R‰iájR¬L•Ûþd4ø´»ù¨;¯ì-4°$¼×«zàà×¾9Ž¥\îMÕˆG·nWË]Âüî5®h_¶)¤FʬJ•\)wÕƒ˜ìƒ¿ÖåêâwïQŸüPxº´O{í©÷noãy‘÷#¯û†n÷Gìy¼XT—ßMa׉\½ô³ŠCª¼$LOÝ82…× ƒe_ä"öq8ÆÅbývmK:‡E‘móö$$é‰�°üµÊ\q*IÜ6Y›d‰+È»º}qþÓ8?(ÚçcÒXLXô& Èäż �AŠÍ6MvîŸ[{ÉO% ý]%jÛ £=ÊçÞ¨K,bâW‡òt9‰ýyQ~þå_êDÂç¯sýu®[çús–÷†ž68e aK®þ`VÃÀU’˜Óã~’e¶©k`6ÁL§úŽ Ç¬•Œw°å!_ÞL,¥7^ æJ¶ogšte|¿Û.þüú6 Ë-6 QBÊoRã9’ºWx©Í¦ÔÕ8œ7%[Æ!»CÛ•T#•¶' ¥ ɆîºðGI¹fÝ@>=€kŸØë[¶`سœî\KfÓgÊ‘PftRˆ…TÉJ½p/hc©¯ç7Jì¦ìQ·BïTåÉ3™m—¬#ÃÉï§‚U^ÂCmßâ¿=o)¡¯o&fkûú³y¾ëöàtËa]ÀØÝr+”KÑïØHÐfl¶£ªJÁcƒ Œ†óÅÓ«Ò xváE>Ù¢Ì.§çSm¦’)Á— öó³ÄC]hËô}W&Õî7¾”ªŒ½ž“y‰ÿˆ½_Æo°µVçi© 9ÇG±žšÚgØ*mxU®7ãp8Ï“_»¹Ïˆ%ÄìùŸiLöò*Ž5dÅÚì€<¹ŠÎ¢:³DÔE!!–Ýømí;«ã ŽnÉcŸ^@R܃հÑûs4J‰þ±*lÏõºR‚²†Ø*‘¾K´ì( ÎbY/\×°Ldu€Ç¦êÓ*KD*;öá'\jÛ¯Þ¬¾Ú&q£c¸«©~zfƒw©t¢jcý_Üï^–ä„(öÊáÖröMþ¡j¿Gê#v™PFië æÿ¡4f‡Q$; UÒw×Gê5õƒá<|ˆÝë¯{ý»× ê©Ã¶-yŠnnÕoÇo� #‘¹ûJN·13ë`,A n0¤³ŽX&RIÏùŽS>•Ö™?º§6ì¼!ë¦hY»ËXo‹³¼á�j¶ûóëLïô+(»+=ˆl'˜D®k>Ê!W%XjlJLÉê~Y€Ù7Uo+í›läW³-@’p¥ZMR"U%+lU;ˆkG૪©�Ü ~ç¥Þ€%‚aíG«¶JËÒØáàhˆD`b›’›?Á€ ýæ_—ë ÔŽÅFoVH’Ãú�¾ò‹Rà²>O‹9INÏçÍY®}°ãD‚ ¸5BŽá 6+Û³°ÓwO¾Oï’êu›!Žõÿ*âãéÕű°‚=o`^Vʉ­¿¼ÛùºÒë§ÿáLË G=¯$¸·Aa¾ÞTàÜjI%F’º¿«Shðß]é$~>ÞüãâR-(åKx�[ÌÚUª§\(Ô!¶ò.Bqí 4ÏJ%¢Z³G`b{±B›“V-å4?:¹Ïý#ptö†×‡ ~%T 8Q#÷~§³WÛ‹´+¶;¶£?[WÞŽÊìή-ö¥܉îJc7b˜?’&ß®¿R¡~ÛC„õj€!X5'ÉMj[QšIL˜]u¬Š-Dõ#¿›–g~cÁÓê=Cv¸ŠCøcÇ~/ß®§‘eñÈßû±5�¸eÚsä0LVOX©B¾‹4û¡²CÈß°/NË‹V›‰S ø×òŒ1­Qõ¢"‘q«ñlÅ‚§×œÃû×Áþ:Ø¿µƒýqö†r;ðÓŽä´�'±·ÂòŸüjp=ÞѺ~ÀGUí©gCz³qèeÊÓý öˆò6$X&?z£.Ôo˜Gdðl å=êϯ�¸(6Ã(‰K«… .Pmzb,‹€gÙ1HÙéÈ·X‡g†ëyFg’èç8zÕ¿XâSxðÇæé«·µóæªl ç1²ÆJ8y ˆ:G†$…äs§†'5ì‹� _”¼=~Â[Cp¨){^êyÛ)€Ç,ƒ…º!¹¨ªˆÊ+øàø•…Ò&´=^I!0KÄ=ŸæL«ƒšs÷Íò Osd§´¦è¥–(¨ `<Ø7ø|ƒÍOŸa€¦àXç"ñLƒJɧcû rV�H—›€”OWù#¬WÁ)u€y| ðroã‰IìÓk?¢W ÄÛgÍZ²ÒY¶aQ#à1‘P•úóž{¤kxyµA˜–é ‹~ã‘–Å~�¬Ã] úÚª!%-áâ@y­ò(5Td鉥Ç«}ëzrÓb‰ m ¹lx¬ê V½ùfÏ=1·‡·” ù)­Þ�Ä­ªDE©—ÈZ†Ðç"º¯ôí^iý£+o¶®±ôÇQ»õd iÈÚª]ê°›_ŒUY¥>äÙŠòkð¢Ïý¡è±“½r~Ø“¢Á3ì+l¾yå“©pˆVGªæhå ·?}òáÝûgåõ~cSr·¸°«LÜ£>ˆ¼DÙ_Wç§¢üÍÖl}üëb]ìßÚÅþ\çÇÙ¨yT_ð’ôÝ.“”nüaíD‡ªÿP@Ï) ëk_³ÈA&•vµ{0½ÑŒÒÄY8R¡Õœ–YßFJ kª¢áÿ&Üöþüúo9Ý.eªpÇIRä8ðÞÓúþP{sP’°8_K.W9èñêß ÉÄí5ap ^)œfÜà3*åôÃŽ þص@Åý’Œ9H³qNP:"uú,QYu‰ÙïůÉÚy±öšˆEÛíxˆíÙž[œ-[yP7 ³Q½ogA哤7ŠË‡9¢—sˆ¦/ïã¸Gd­,2÷\‚Äy`59‹@ÄiFÀ 8îQ°1ö{ë¿É 1ˆhƒx–TÉf¿Sq:ó‹øØ“e–XxiØÞM· €³DÉ:ÎYBQX®8ói’9D´\§‚ˆ {ŸÂJ?wà[Aæ=cQ;‘ ýñ¶¶a¿^ñt¯ª‰t28tœb¾ÄâŒü“MýŸ·ý×°O%S‚JqKº^žg篿C(>±ç}W~HW#à½qI™þ²€„á½Xã󨘢^È”Iðô‚1ÊÖëõÅBäúFeíÅf!¦<Zókä›b¶·ûo‘ü ¼X1: k–Dwd„Zò,) ¶Ê¤ »¦Èx{dföÃÊÉIf\SÒfbûwøÙÏâ&-À5åB­rËÿ3JPl,\±«›h3¥ÇÝ+éc?]nÉñ,<˜18 þÚ¦G w*²RC�‘¼SYÖk/Ý €“+õ"ÖXÊ_'ûëdÿîNöçBˆºžÈ×>ņѥN pëžñå~£X|pr’`a}ñÝDP!Oéhºjº^’â]Ÿ>`˜ÓéøÝAŠˆ9úfÍÊ8½?7þüþÞ˜Z»–*'ÅUP)ãoð´HÞ“™>Ý7?}dèÕ³3³K–ÃíQØðæîz¥~ÁÑÑê| lW­¶'ßè�‰<’Œ;Ñ’±Ý˜KÇQ•Ÿß“?~¥ùöWÞ‡ÕÁLìt #”˜úar…:ã0zD\xhþ‚ÃQeÇMðs¯aÆÑQ{>G㵩†#:¨®‰Ë_çΘ4pocÎ’$^ÚTO¥W�§µ;5´Â Ô;ÚµÖNóN)¥0eé‰8¢G>„j ½k´³÷µ9@ ¨F²EI¥´U½¬¨GUí™hSWq&ìª'Ô±‰€Ë ætL3�ÚoÝ“ˆ×²gfa{¿Ñß[²°U¾ï‹ñ&Зýl¿S7 Ú‹íÂ@Dåy½ ô¼Tÿ„«>]3MúÜI æ⧃I¸¶ÌÊ–N¯×âÓL0“ éåSlÆÄ¢Z•ˆ^ò*aW›šÄуp>‘ƒÑÏ!„ {^¿ÇáÕ¾ÌÄ â½¤ûDBùþ± éÞÛŽäjÃk ¯äÏñùDÁ7ˆ¿Ñ[ÒDej´å Jìß ûý9uò6Ò}9ìØT@Ô TySp}Ö;œs®täƒX|Œ¢åü5ÆÁÎï³!r¦|¼'R8ÅN76e`vRƒÅ êI¾¦Ndž ºþu³¿nöÿ�7ûc=;/õë+áX¦«Fr¤8ŒK™WŠê"{P8r” êã?*Ýõq´ô&Çø4JÓãP_2UUþdÔ8ÈÇó,ê~‹pa¼~™Êðç×xe"ºl\}^°Êr,²n©‘"À§ßƒÍÇ:Šê^à!«ðfå.Kªê²[ÑGaƒ‡¬K>’Ã5{¢Ô¨Ÿ 0Æìå䇦œè‘d [>åF\(1®ììò XÑ•v¸áßKb±UÖÀªq_”žs?ïõK1ö…韬£dc•W¸áûàù·0öÞöÛIí7î*Úã„©lâ/{Øæ/ðý“e‰ýÏfÏÕQ¢ŸÊÑÎ_&“¼¯–‘µY¢DX€¢£r×p°ÕšçþrÝ]Lû›`Á»•¬ò#g¾Ê-­ØUà…Ž’Ö'åH„é—š¤xúáݼ¢9]^¹¦¬kœ,æ*ËPùï¼R’ÄþíHæù·ÓëRP�ÈRÔ—’1ï⥎”|uð‘§ó6£HÃ̧×O T_Ý[ Ì‘Àý}´èùQ+$Šg¥Eܱl:OUGÀ#Æ?EhUŽ_oç'uÌ×Â\ dxEçïã`=ÑÄ+ˆ–>›"/°zÕF¸"Õ!›¦´÷G³9;®»½]?µO¸ùq6>„Chû¬Ô[M!Qô<ýçUx&•&a˜~Ñj爀õ黺!ìá社øñr’¾¨»X†LüÌï]MÚÎÝïŽö#Huÿþ£!°Xã60£“f~‰¥ÓfšOòçñƒ’Ç‘í¯£ý?ÂÑþÌ’÷Çí¡§2;NÒG» §bŒ¼Bnž»`jÀ’WÕ±úm+J_JAþjÍ™mJ)š°“ý ¯ þÉá™ÞbQLpÛ¬$_ºwÛùç×ÀÀvÃ)*<¾�¬âùÄUÀAÛ{ŠZŒKVî8‚#Â,N|Ffsð§ÉÊP6¦P].ô“x˜¿ ×ûŒ…3+Û™0KY~RdOŸQ_Eë—S¿vÈ8ðØ/0$"¼@v¤È²”5ÝR_ÇbÕ ñÙcÙ¸ä_´á«••aѶëmýÈN,c|â{Þg‡©þ‘8dM»°F Ä9…Fìê WbÕØ8¨Ó^ ý¡ÐUw¾h¼Qj‰BÌp+‰´Mž9¹@S &’«7�H—pn|gX„YBidöTÊž.ôOû¹üîtUVŒ=ÂX÷¦TI ÁŒ'yöïã;W&ª˜}:Š*œ½/`͈—Pwœ;ÃçÄšû;8(ŽˆÛg¬tJ`ˆ#[$¢ *Ã6;o5¶t˜¯Wræ«ÕK¯¿Â²_p|ò4&É/kÁ}Œø¸0 š}Ÿ¯1ƒÇʲ ÚØÒŽºåöŽDCPÜÊÔ™$BüŒ¦ê-ÙF4²ÄbãúX�›rUÀt.ùôú†Ý"QÉ–åP–ä¦4©tfThKS&ö�±€‰ý8UDù¢¾´ e2“Ò¢û:wPóQ•º‘ ¿Óá?}”½•K]>Ù0•@›êæ`­8¸$°ýU‰W÷B,Ç^ÚV”wýæÎ¼ntÿuµ¿®öÿ Wû³³“ñ^¿«sñ*nåÐ0ÚANüÛüªô@6Í Å,y°)Þ{—¨•èŠbÎgÝãÄ¿ð$OÕ%ävOäZ’<ØÿŠïë‘ ûãUv¾ýç×è ”Í[y§mC׹ỠœŽ.õÎ7yë)¼¯#ËIÁSå^ç¿àhUþ\8æÙý´ªÚ.©Õµ³n+Õ‘FèZëËq¾ôº®ß²ðKŠ1¿.ñž@?TáDˆ8Ór"i¨Ñ¥Üܰ µ‚›7 ‡û¢¨š4€h(ꑾ÷:HY÷‡¨f1=5'šþ¹¬àn÷z¢ggy±K”�í^¾à­†I•“m¬=~gχID×ÍÇ¿Á½]s'áç¼&ƒeÕ§Ñ&¾ ­‰Öœ_kÂ70‘ Œ ~^â—×-_ øÿ„—'x^V¨še~‘¥$¦‡qc\¯xI"c–÷¤¼¾·¨xÕmä· )xŠÍÎØÃ  ;…›°ÿ�ÙwýäÑ|ã^·)±!KÔGâ‹?žh]‹°ªÚÌQÒÈ ‹.BÂV òÛÇ+¸yØ¢óÎû {æ3TeE”œßÄgˆÂ±§˜3_€(AŸŠ½Ù /×°¦w8È{»œ³Ãõí– ÜCÀ†@‰â4÷9ѰÎÇã9/Kë¨Þ|ž~œµ•(ÿ¤|¶£ßj´ŒâpÄqë!5’Ü´ |¨‹ÖÊ£l oTw”‰Ô¸:|÷†VN´J$«VàÝ I v_û8b²‰‚ùëlíÿ1Îöç.PW9Æâ`žl?o'®s]t&�«Ö8AKIêÏ j™ï�de‹vçç€aÍ9£f§p˜âµñXŸÞy‘,xúø”qV{e³TÏϯ OÁÁïYlPÇ fŠÂœ Ðü m›‡yòž"YE¢•¢¼_°²OÎDMÜä±G.zÄ/cO ÒBÉ߸ña¢CÇ…bV»ÓÛ ˜„Ÿ,Ykùú¹ž!^v½ê ¶¾½ùÏZ›¯äü7CíG�AˆV½,pž”ûycAûщ#êšÜöÿjïLìÆa zw4wv6\óaÞÓ„à£û4»[ÿ‹ÀTEá:’0„ŽW9ø{g¸j]¦¤ûÓ±\ú<Â!Ñ-ûQçWsª—W‹ÄrÃ×EŽÙ€­^þx­ý(#ÁÖ%‡hàóor¹ ÷‘~Véη³8ÊGö‘Ä6·ç×>6¡1YÙúâk€¾?±”¬c±}ÒÑÏÄ/l/íjÄ‹ Æ~÷+«nðµòÍêÍ\R³üêH.žÉÚ)méf½%oÛä0H¾³­×ÁžBñ£ÞÖ~^·âg•{lP‹$!WÕï«åªö½¼†y$˺ª¸fSøŠ½ß:/oz“¨9°á Ôii‹w#k!à€9ø¹ät²…åÇŒÞ\).ß[TuàkïZTï˜ÙfÙ•¼‘FÅ[”â °ðÍí0ù©AUsöÆq‡g¨4pyÐÒ+²¾^%M‹!¦K^èØ&%æ±4bŠ•|ÊD¼øÍ´(3ž¯¥‚L WÂýÜÊ>Üü€ä%å„Ò_wûu·ÇÝþÈÀCê½Ú]K†ŸêÔÎô'Ÿ/¤rñ`™l ˜sI[g?gøéäø IµU$ z¥Uý´PHßß‹m­‘òGˆè0ìHjÊUï‡Q“”;ïÏ_?€½–zag Î\Cá'6ëã'� ”m ¹äîjÈäùµ†?êùþÏr ¢|–œ ËòÍÊ-'š%…•/P“v1)TZž$Ô’ê"øcÈ…ámÊÁ'Î7Y^cwØÄ²eÄ2¼¶@z¬OV¦“ºÅ’Ýe|”zÃÁØ×ÁX:ìš…UÐæ…;@j6l¿r‡HÅ€fFŽ_;UOîr68¯›¢Ò“¯‰ñéE£áå8ú‘Ê]z+»Úô/n®Ø±è‡¿¬—3E¥o3•k"–Md JÉð‰JêIÆ°É °j5èùË=o”;òÈ#LÈÃ)EeB‚TV VSh–øâÎä@DMœ(á¥ÊûH·ò>^«I¿®ô¹Übù¸u¨ ç�«<í§™ïœöM½).¶Õ2Oð¾Í ±ðÄw°–Þ=Bö†+T sÿª`]… uVY™Ó&>âìDÈgïù!5ŒXGöYW—½‚¡m ˆ€w“ð¥'s´Ü;Ž6†dTãÆö]t([Î ˆâw*‚­­wÛêfžÎrÒâQ$)Ý&â'D~7 ¯¡Î44 ZMo ~¥-vU]4šD‚h´Ô•…ÑVîW ò蘱*oÚci¦^óÊ£ÿ5€,«„d"¬ ÇÖÕD«”˜#¹’[|k¶KF7ò€ûëp¿÷O9ÜŸÚ]ž©3çåeŦºº‰£>“5ƒÝ¤&ZìP‹¡£%ëP ˜±·ª. /ÙæÎ˜Eh×^ª$™kBL´qØâ<©Õ,n"ÃÆ>wÿùëHñÉ“ì�v¾Ï&`4\aF=ŽÐÀŠÀ‚¼Aæí@”Ó z[x¥ �ÄXÿÌÇ(ú§VÇuE5C=”˜0æYò„D§N½á}Ôt `?Å«ZòŽ%åçˆß€ÊÄ–ú±×²ÈäàåLû°x4¦p¢C®kØDþZ(ÏåÄO÷í|<PYÆd�œœ®A°žy„òY›×G;ƒõZ2zWZ*ƒb}cçZù +–FˆG(¹lí À=V°[X a¦/[ÞÝìZíÚò:©âKçÁƒm/\îÅÃêÂk¹¡Ê¡å›…eëŠêpOoV¡vhoUÀšÐ¥j³‘)¯µHr“|2½Ee“õÅz&˜çíÞ…yuï§#ºi6EßÖöþlü%ਠH”†Ë±kâÂÚàÆ�ûÎIêJ+Df“‚ –…õÏaãìýàÁÝ]½Ûg•Ó9«:äO{8 ‚cj¤[ê½¾X¦O9$áô”dÇo²[üåô! ™çãä$b<ÇkÆŠ!+Nvr2N ¦&‘!%N’x5{j"¸ßò'Å{»7[§ÈÎI¶Âçvý.RŽ¥­SãÛ“ÍJÌVæO•;ãHƒÉ '5Ð{ä, Áœƒ¯$G ÁÉ|râ±Ï”å̱'Íä¬àY*!?{ žÀ|»%†¹ xéjemؽrö~ólò“]î×åþ)—û3å Wáű¨sÏîï鱞¥…'ëàÔ­âÕ%‡ë=m<DáŽð"e@ˆòCñŒ|ø¶ÁŸºœìg´O—Ù» ÕÃp¡ô¤9ßðó×È9OÌ|ùûØä²"¡ŒØCÆü±j!HÇðï´)ît9 ø±"Mmàç‚+v T I¥Óu¨°”;xõ<{ªm²”Ë·íéÁ›×œÿ�¡�V€_62Ÿâîû•ŠT´ÃŽbåLj(lZöq]Æ]€/ptíK"„ɸõ ðÚ–s˶e=)nA‘ºéÛ¯dóMc‰ð`_ó€xqÎÖ„«Ü-…ýißEü­oéø3&[§·ì —Áª¶s1ÀкJëσð#*Á4 °Û‘xì¹¶¥ ŒXªãàŽÁáɪž´å ·‚œïC€J…ˆÉ³–px.ƒÔÏbZs/2‰…ÓviµpH:º=ÖöWÞG%ú^qmr—LŒ·,QoqrJ*È8I0Âóc ì-Dƒð‚íð9Є·ëÜaøýÔfÂ!”扭Wóqø\M¤M+ùÕõ‰ÒHœd*6Y".Ú[y»Ä[¶ÖÊù êt¶b¢x®×’|¤—Y íçÈR=›œ©~DƒG¢~¼ïí}¦LZ‘§üfûݯ‘[%“Œ6à<h\x–öX*Ô8®ðœäOÕ¹žÂ” ÄYåå\¿o©Wz»Ÿ"¹$#™dëe·f¬\Þó?鱚u¶'æRÀÐIMÀLÆŠÕœVN'© •¥b.ƒ·%Bæ_§ûuºÎéþ€2‡-qOØdÁ£ÜƒT}O»£G—Ü¿r*JƒTÈ)e­¹ V±â¸·‡t:ÖÌ}'y§C²Jm¾Ë5/ SõRûÊ—´¾aq$Œed¾Á_? Ho§’šÄÒl”1IÖ», `£tápöãùø)Ùóiõ‰,EÊk®°®XÚÃbã‹@ì>T¾ÎŒáØÓ¦´‹¥¬™>MQÐï|Ácý>CfÊ7‚Nµyºõð‚¥šÈªÐ-©·Å€‹aú&~\à¶ãlOmçxF=MéÉþ?Æk„°'�S¢ååi�º'T G „œž €#'+ße™†¿6r?A|þµè÷íå:•žHˆ¨*°Ê4öf»AV.âÈ×eá,·}¥$ÃéÞ8ÇùóGÁ¯2ï-¦@êÿL–ú%IJè2°*ŽŒ†¨Ú¼…I¼ßäí—$ Qbç· œÛíqoªzæuðƒkÊú,øÏg0ïd A®¸ƒd›ÕÀª³xñ ßÌoYëÙ5wêk:Û¯·[ö½¿iªÃ¶¬G\ï­B¨Í)pvàµÆW!x•ä=FrœûnuAõ´n¶‡ «¶ÍàÄP¦eÈ’U϶.Bâ/œ°¾ü$~8•9ž|ÉüñJž‘UcË_Ã_YÕo|2¿Ù®S�éÓ>‡žìüµÅCBFœŸPAŸ?Êûð…Ù´‹å®6•ý>GETòÅ[|VÅ# )»$I&‹ËSщÍÚÓã¼¾ Á.NÛ\I-»ä8æ¦#W«½˜&ë¸=—Ã&½zžõëv¿n÷ºÝ0Ø‘ƒã¹<W5gæëŒZßÅG|ÇT'åJJuÀ?dÇGáä*Ã!JÉœró,—É6r%0§Mp¬5žó%¾ïõŽäÂW…‰ÇÏ_? ÊUů4é~’ŠÑé-ƒ\üѾŠÒ¥ÓšŽ7 HØkU³Ã¤wŸ à’Šo9EV÷âj`Œ—sëþ`íJ8Õ;*‰{sp¹©Unà›+— …Wƒò<¾Çs…=xôWÒI–ýƒ)ýáUYŸÅª5z“Ì’+}j Á\'Ÿ¤Äõgz›ÝuÀ¾€ÝùÖ€mO! L »Év1„) {ÈÄ”ùã½Mú@ ³ÚSopQHÀâìs‰6²©ã ÷öË®('fªÊ€ŸQ$áfýÍŽ´}Ž|§s5ó0ÀÙõAr¼H?Û™GYKwv�~쩞w9àÕU›µ±HßiƒUÙô݈9Aú‘A\‰¬{p>oÄkwšd Þö|üöüG”>SÎ&5q€UÔ­x ®;¦5Y:¯í"„zƒXwäab¹rNµcŒ3‘ÏŠ…¿xøÙ>1µ jýÛ?F ¨K²æCȆuòNæg$&Ä÷µ ž¯«Ó[Ê´%·)•Cáµ´~kH€Ú‡õ½€ný|*ù¹[R*NÝSøµØÙŒ±ÙàXH¹Ë£‚Áçùähö͘ÃåÌšÖ§%.Áfûû'5zÙ¾ *;q‘:(gÇaˆJ£Ö»›÷vÂ<¯ÌÏ9û¼$Ý8ÞЀÙdY¶L`ƒ7Ë~é]Ž]­«Ö*·$<ϯãý:Þ?éxŠlQ:_°H!÷yŠ]¹&‹¯‡ì#ש+ûX°"Wçzô<_6Ö:X#–xŽ[öG7€ûÜ(ÿߨjk±V€PÛ°¢,záþüõâ\{©=>½Žé�z—ýÔrWyæn«§ßת¹4‚7סæÉNí h$f¤§ÿ˨TlPàÓ€äjˆ+~Ã?eùÑ¥0ˆMÉé–¾<¼¦¥`Üûvé;¿µG9a;g=%?h’Dd‰+ãÀ‰2©\àFÞ¼°ù€½3"3P}«õÀój¼qm`2¥Ú”¨_Ÿ_ùþRE{m¡ß~i5y�Œó“]9™·Ä,Óc[W”‡˜øW^²²ÄmØJÛ¬&íb°\á<ÿ¢ˆ hòÍõ«øìï;�ü†4ÿ¤²?‚ç_i5਴è´-;ÄGr$¹G�ùhL¦“UuµÛ0lû€ÕIʃx}ò®C{›]a¿xwùLš}×¼8X°cäa?l®J~ã¨P£ÞŽ¢®÷&ØM %½J0�Õ{j‘ÛUØ:©nµ´%i)áТbdï%LÚ0Æac~N"{M{Æóù<¸8ßGÊ4»¾Ö‚™Ý碄7• ä⻄/[áÇŽÄÀ‘wW(©ž<Éqji|YÁ¦}ëHKŒ»d'Ž16uUg– 3>`ìC‚Äç(xœ ‹$ø åy~ö~8刘¡©Éd™)—NˆmTËÚé«W¢Â`M«viA%\)›³Šd-Ø E¥ÁûU[êÖÉ)=Œ‘oXw¯oë°[ýJºÖ”ià×õ~]ïu½?äžNõ´ÞTlÛ¶M]ñKkÔ€ýëFþQ9œe÷ÀÊõ+gmý·KÕÀ¹ú‚}²Ù;Û�úÄLn"ÅñB^»Œ}œ¹ Ÿ¸X,S&Uÿùë°‘äÎ9Ä&9ýœ"ÁÆØ?w²‚?g+˜µÕ|ivç}7ÛÏ‘ I’j©ŒY``·JY5Öc£l`Ÿ$ûT°ˆs·ó|d¼[ámNy€Ì\^®oðÊ”É~Jp‡`›Ë“6W¼>{ µ`”KXülž÷}Žœø`'ܼVK4Üd#t³^Pð#9=ÚyøgÜtÿ ¹JÿßÞîh´\ˆN'©Ï¸ž`rÌÅaØXôþL€¡Ð^¶R>ÖŸµD¹Ñ[w™4×-X¾žÇºØ¦x f=îÖ$-y!l¦Ãµâuncaõ½û…¡}‰­`©ö 4g•#@´/"ÑU,Þi@VbZÒÂX§LÄó±g>#WTT)ØB,}Ô#”ä8¸¡ÈÑ¢Ãå³fåiŽâÕ(Ëçù¦;æ“þïé ØÈòq²¸‚Ý¥´.NU¾¶,='Ë„‘[YðV<¦’ à‹¤êýZ7q-' ÚW) n|ÃøØàºw%/ûke^1Š“;û-£g*²Lƒ­Ëw¾ÍùŸ£ºŽyŸ}ËKäÐXp RÁè8ƃáî|L÷ž19òý‰Mýb~¢d æø®¡¬Gf°¬* Ž 8ßßœö!€Ý>•ëX„J%*+ü©*ÈåFJA åÀå8æ»Û T7~ÄѤ©«,ИΨ,üë|¿Î÷Ï:ߟ\Aœ×¡Kü|±ìNPeïyPõŒ W©·äECQ!^€ÕIµ¦ê*6cÚ%©W5$\"çõÍqâ|À[9 wp$e”\/à ~þú� ©k…²<«º§žë Ú¶$ì$P�fàU¸×Ñh…RR‘�6ÞÀÏyg¥ðZîìfö*" М—WÞ‹;.0Ö—õ ”[‡Zc†· ä”íô­ñh0»"ëSºÈZ¥ÜÄ}Ü:Áx|'˜}Àõ-ë&™ô[RŽ�p \UUM;l~ÅÈÈ#ö” hé{Zý' ‰_ƒ {I?‰> <™s'"æ!oË ¶tŸHD!Ñç…«ˆÐ³*n´Þì•ш”Íž=#eâ¬Òi ï¶°,ØcûÛéË®{` ./Nøã|OVó„þg?ö:ØölÜtKº–6ùŒ 2Ú¡ øÊ‘¾œÁQr¼}UÞS_>ZÐ EŽ/…Ëë>>Åqü9+FÚÔXØY‘¢ðõßµÝó%¹ÞÜpC"òÝú;mBÌ yÖT“«bŽBÄüÀþ¦%u ;Œ½—a[™ÏL$o0K²]Ÿ2e\Oê=‡iÇ}Aƒó„‘þ1X ²Ä¡§«cØ¥µ&óªõ1~ä Ç8WVê‰Pr¥ré_å‰xˆV¬üü8¶ þ¢ªo­‰ƒN¨‹1/6FtÔqéyESÖy‹½$DC©—¹ŸiêâœãÕÙôõÆi›Éô¾Œ‡Üéa±¤u•¯ëžGºV2Ã\9Ôˆ+#È’½Ÿ|äϙÄ„´Oƒ‰œ!̪ԖãÊM÷v7ë58bg™"ÞɲMÕ¨<�O¾_u5ÛTÁ î7}|Dâ>Έ‡…à6’±vÖQ«”´ì•ù&‰ìúFÒ°¿¥™Ó�Ï3TQ>ëcɹœ§Óûb>f(Çë&{íK—¯´Êں㢼í#)kÆ&ŽJ„ª.ŒŠU¶ÍÐU &q›3)Dû˜Û›Èt»$Æ=EþQv¸©X¦!ž.{APúÒÓ’_&Õ^rѵyX{vz˜bëEáË$¬„‚•>¦ºãm(!„£&þ(¹”¬?«óGõí$³&¯†UQ˜Þë…¾"áM!MyÎíV _ΣÙ"AAi‡dƤ¸i¨Ú‚ë̯L†ûò3Å„5ü†ßßðû~Ãï?~ÿüf¼¯€)�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/internal/�������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023664� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/internal/edwards25519/������������������������������0000755�0610621�0607500�00000000000�13172163317�025723� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go���������������0000644�0610621�0607500�00000122362�13172163317�030317� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package edwards25519 // This code is a port of the public domain, “ref10†implementation of ed25519 // from SUPERCOP. // FieldElement represents an element of the field GF(2^255 - 19). An element // t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 // t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on // context. type FieldElement [10]int32 var zero FieldElement func FeZero(fe *FieldElement) { copy(fe[:], zero[:]) } func FeOne(fe *FieldElement) { FeZero(fe) fe[0] = 1 } func FeAdd(dst, a, b *FieldElement) { dst[0] = a[0] + b[0] dst[1] = a[1] + b[1] dst[2] = a[2] + b[2] dst[3] = a[3] + b[3] dst[4] = a[4] + b[4] dst[5] = a[5] + b[5] dst[6] = a[6] + b[6] dst[7] = a[7] + b[7] dst[8] = a[8] + b[8] dst[9] = a[9] + b[9] } func FeSub(dst, a, b *FieldElement) { dst[0] = a[0] - b[0] dst[1] = a[1] - b[1] dst[2] = a[2] - b[2] dst[3] = a[3] - b[3] dst[4] = a[4] - b[4] dst[5] = a[5] - b[5] dst[6] = a[6] - b[6] dst[7] = a[7] - b[7] dst[8] = a[8] - b[8] dst[9] = a[9] - b[9] } func FeCopy(dst, src *FieldElement) { copy(dst[:], src[:]) } // Replace (f,g) with (g,g) if b == 1; // replace (f,g) with (f,g) if b == 0. // // Preconditions: b in {0,1}. func FeCMove(f, g *FieldElement, b int32) { b = -b f[0] ^= b & (f[0] ^ g[0]) f[1] ^= b & (f[1] ^ g[1]) f[2] ^= b & (f[2] ^ g[2]) f[3] ^= b & (f[3] ^ g[3]) f[4] ^= b & (f[4] ^ g[4]) f[5] ^= b & (f[5] ^ g[5]) f[6] ^= b & (f[6] ^ g[6]) f[7] ^= b & (f[7] ^ g[7]) f[8] ^= b & (f[8] ^ g[8]) f[9] ^= b & (f[9] ^ g[9]) } func load3(in []byte) int64 { var r int64 r = int64(in[0]) r |= int64(in[1]) << 8 r |= int64(in[2]) << 16 return r } func load4(in []byte) int64 { var r int64 r = int64(in[0]) r |= int64(in[1]) << 8 r |= int64(in[2]) << 16 r |= int64(in[3]) << 24 return r } func FeFromBytes(dst *FieldElement, src *[32]byte) { h0 := load4(src[:]) h1 := load3(src[4:]) << 6 h2 := load3(src[7:]) << 5 h3 := load3(src[10:]) << 3 h4 := load3(src[13:]) << 2 h5 := load4(src[16:]) h6 := load3(src[20:]) << 7 h7 := load3(src[23:]) << 5 h8 := load3(src[26:]) << 4 h9 := (load3(src[29:]) & 8388607) << 2 FeCombine(dst, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) } // FeToBytes marshals h to s. // Preconditions: // |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. // // Write p=2^255-19; q=floor(h/p). // Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). // // Proof: // Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. // Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. // // Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). // Then 0<y<1. // // Write r=h-pq. // Have 0<=r<=p-1=2^255-20. // Thus 0<=r+19(2^-255)r<r+19(2^-255)2^255<=2^255-1. // // Write x=r+19(2^-255)r+y. // Then 0<x<2^255 so floor(2^(-255)x) = 0 so floor(q+2^(-255)x) = q. // // Have q+2^(-255)x = 2^(-255)(h + 19 2^(-25) h9 + 2^(-1)) // so floor(2^(-255)(h + 19 2^(-25) h9 + 2^(-1))) = q. func FeToBytes(s *[32]byte, h *FieldElement) { var carry [10]int32 q := (19*h[9] + (1 << 24)) >> 25 q = (h[0] + q) >> 26 q = (h[1] + q) >> 25 q = (h[2] + q) >> 26 q = (h[3] + q) >> 25 q = (h[4] + q) >> 26 q = (h[5] + q) >> 25 q = (h[6] + q) >> 26 q = (h[7] + q) >> 25 q = (h[8] + q) >> 26 q = (h[9] + q) >> 25 // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. h[0] += 19 * q // Goal: Output h-2^255 q, which is between 0 and 2^255-20. carry[0] = h[0] >> 26 h[1] += carry[0] h[0] -= carry[0] << 26 carry[1] = h[1] >> 25 h[2] += carry[1] h[1] -= carry[1] << 25 carry[2] = h[2] >> 26 h[3] += carry[2] h[2] -= carry[2] << 26 carry[3] = h[3] >> 25 h[4] += carry[3] h[3] -= carry[3] << 25 carry[4] = h[4] >> 26 h[5] += carry[4] h[4] -= carry[4] << 26 carry[5] = h[5] >> 25 h[6] += carry[5] h[5] -= carry[5] << 25 carry[6] = h[6] >> 26 h[7] += carry[6] h[6] -= carry[6] << 26 carry[7] = h[7] >> 25 h[8] += carry[7] h[7] -= carry[7] << 25 carry[8] = h[8] >> 26 h[9] += carry[8] h[8] -= carry[8] << 26 carry[9] = h[9] >> 25 h[9] -= carry[9] << 25 // h10 = carry9 // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; // evidently 2^255 h10-2^255 q = 0. // Goal: Output h[0]+...+2^230 h[9]. s[0] = byte(h[0] >> 0) s[1] = byte(h[0] >> 8) s[2] = byte(h[0] >> 16) s[3] = byte((h[0] >> 24) | (h[1] << 2)) s[4] = byte(h[1] >> 6) s[5] = byte(h[1] >> 14) s[6] = byte((h[1] >> 22) | (h[2] << 3)) s[7] = byte(h[2] >> 5) s[8] = byte(h[2] >> 13) s[9] = byte((h[2] >> 21) | (h[3] << 5)) s[10] = byte(h[3] >> 3) s[11] = byte(h[3] >> 11) s[12] = byte((h[3] >> 19) | (h[4] << 6)) s[13] = byte(h[4] >> 2) s[14] = byte(h[4] >> 10) s[15] = byte(h[4] >> 18) s[16] = byte(h[5] >> 0) s[17] = byte(h[5] >> 8) s[18] = byte(h[5] >> 16) s[19] = byte((h[5] >> 24) | (h[6] << 1)) s[20] = byte(h[6] >> 7) s[21] = byte(h[6] >> 15) s[22] = byte((h[6] >> 23) | (h[7] << 3)) s[23] = byte(h[7] >> 5) s[24] = byte(h[7] >> 13) s[25] = byte((h[7] >> 21) | (h[8] << 4)) s[26] = byte(h[8] >> 4) s[27] = byte(h[8] >> 12) s[28] = byte((h[8] >> 20) | (h[9] << 6)) s[29] = byte(h[9] >> 2) s[30] = byte(h[9] >> 10) s[31] = byte(h[9] >> 18) } func FeIsNegative(f *FieldElement) byte { var s [32]byte FeToBytes(&s, f) return s[0] & 1 } func FeIsNonZero(f *FieldElement) int32 { var s [32]byte FeToBytes(&s, f) var x uint8 for _, b := range s { x |= b } x |= x >> 4 x |= x >> 2 x |= x >> 1 return int32(x & 1) } // FeNeg sets h = -f // // Preconditions: // |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. // // Postconditions: // |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. func FeNeg(h, f *FieldElement) { h[0] = -f[0] h[1] = -f[1] h[2] = -f[2] h[3] = -f[3] h[4] = -f[4] h[5] = -f[5] h[6] = -f[6] h[7] = -f[7] h[8] = -f[8] h[9] = -f[9] } func FeCombine(h *FieldElement, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { var c0, c1, c2, c3, c4, c5, c6, c7, c8, c9 int64 /* |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 */ c0 = (h0 + (1 << 25)) >> 26 h1 += c0 h0 -= c0 << 26 c4 = (h4 + (1 << 25)) >> 26 h5 += c4 h4 -= c4 << 26 /* |h0| <= 2^25 */ /* |h4| <= 2^25 */ /* |h1| <= 1.51*2^58 */ /* |h5| <= 1.51*2^58 */ c1 = (h1 + (1 << 24)) >> 25 h2 += c1 h1 -= c1 << 25 c5 = (h5 + (1 << 24)) >> 25 h6 += c5 h5 -= c5 << 25 /* |h1| <= 2^24; from now on fits into int32 */ /* |h5| <= 2^24; from now on fits into int32 */ /* |h2| <= 1.21*2^59 */ /* |h6| <= 1.21*2^59 */ c2 = (h2 + (1 << 25)) >> 26 h3 += c2 h2 -= c2 << 26 c6 = (h6 + (1 << 25)) >> 26 h7 += c6 h6 -= c6 << 26 /* |h2| <= 2^25; from now on fits into int32 unchanged */ /* |h6| <= 2^25; from now on fits into int32 unchanged */ /* |h3| <= 1.51*2^58 */ /* |h7| <= 1.51*2^58 */ c3 = (h3 + (1 << 24)) >> 25 h4 += c3 h3 -= c3 << 25 c7 = (h7 + (1 << 24)) >> 25 h8 += c7 h7 -= c7 << 25 /* |h3| <= 2^24; from now on fits into int32 unchanged */ /* |h7| <= 2^24; from now on fits into int32 unchanged */ /* |h4| <= 1.52*2^33 */ /* |h8| <= 1.52*2^33 */ c4 = (h4 + (1 << 25)) >> 26 h5 += c4 h4 -= c4 << 26 c8 = (h8 + (1 << 25)) >> 26 h9 += c8 h8 -= c8 << 26 /* |h4| <= 2^25; from now on fits into int32 unchanged */ /* |h8| <= 2^25; from now on fits into int32 unchanged */ /* |h5| <= 1.01*2^24 */ /* |h9| <= 1.51*2^58 */ c9 = (h9 + (1 << 24)) >> 25 h0 += c9 * 19 h9 -= c9 << 25 /* |h9| <= 2^24; from now on fits into int32 unchanged */ /* |h0| <= 1.8*2^37 */ c0 = (h0 + (1 << 25)) >> 26 h1 += c0 h0 -= c0 << 26 /* |h0| <= 2^25; from now on fits into int32 unchanged */ /* |h1| <= 1.01*2^24 */ h[0] = int32(h0) h[1] = int32(h1) h[2] = int32(h2) h[3] = int32(h3) h[4] = int32(h4) h[5] = int32(h5) h[6] = int32(h6) h[7] = int32(h7) h[8] = int32(h8) h[9] = int32(h9) } // FeMul calculates h = f * g // Can overlap h with f or g. // // Preconditions: // |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. // |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. // // Postconditions: // |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. // // Notes on implementation strategy: // // Using schoolbook multiplication. // Karatsuba would save a little in some cost models. // // Most multiplications by 2 and 19 are 32-bit precomputations; // cheaper than 64-bit postcomputations. // // There is one remaining multiplication by 19 in the carry chain; // one *19 precomputation can be merged into this, // but the resulting data flow is considerably less clean. // // There are 12 carries below. // 10 of them are 2-way parallelizable and vectorizable. // Can get away with 11 carries, but then data flow is much deeper. // // With tighter constraints on inputs, can squeeze carries into int32. func FeMul(h, f, g *FieldElement) { f0 := int64(f[0]) f1 := int64(f[1]) f2 := int64(f[2]) f3 := int64(f[3]) f4 := int64(f[4]) f5 := int64(f[5]) f6 := int64(f[6]) f7 := int64(f[7]) f8 := int64(f[8]) f9 := int64(f[9]) f1_2 := int64(2 * f[1]) f3_2 := int64(2 * f[3]) f5_2 := int64(2 * f[5]) f7_2 := int64(2 * f[7]) f9_2 := int64(2 * f[9]) g0 := int64(g[0]) g1 := int64(g[1]) g2 := int64(g[2]) g3 := int64(g[3]) g4 := int64(g[4]) g5 := int64(g[5]) g6 := int64(g[6]) g7 := int64(g[7]) g8 := int64(g[8]) g9 := int64(g[9]) g1_19 := int64(19 * g[1]) /* 1.4*2^29 */ g2_19 := int64(19 * g[2]) /* 1.4*2^30; still ok */ g3_19 := int64(19 * g[3]) g4_19 := int64(19 * g[4]) g5_19 := int64(19 * g[5]) g6_19 := int64(19 * g[6]) g7_19 := int64(19 * g[7]) g8_19 := int64(19 * g[8]) g9_19 := int64(19 * g[9]) h0 := f0*g0 + f1_2*g9_19 + f2*g8_19 + f3_2*g7_19 + f4*g6_19 + f5_2*g5_19 + f6*g4_19 + f7_2*g3_19 + f8*g2_19 + f9_2*g1_19 h1 := f0*g1 + f1*g0 + f2*g9_19 + f3*g8_19 + f4*g7_19 + f5*g6_19 + f6*g5_19 + f7*g4_19 + f8*g3_19 + f9*g2_19 h2 := f0*g2 + f1_2*g1 + f2*g0 + f3_2*g9_19 + f4*g8_19 + f5_2*g7_19 + f6*g6_19 + f7_2*g5_19 + f8*g4_19 + f9_2*g3_19 h3 := f0*g3 + f1*g2 + f2*g1 + f3*g0 + f4*g9_19 + f5*g8_19 + f6*g7_19 + f7*g6_19 + f8*g5_19 + f9*g4_19 h4 := f0*g4 + f1_2*g3 + f2*g2 + f3_2*g1 + f4*g0 + f5_2*g9_19 + f6*g8_19 + f7_2*g7_19 + f8*g6_19 + f9_2*g5_19 h5 := f0*g5 + f1*g4 + f2*g3 + f3*g2 + f4*g1 + f5*g0 + f6*g9_19 + f7*g8_19 + f8*g7_19 + f9*g6_19 h6 := f0*g6 + f1_2*g5 + f2*g4 + f3_2*g3 + f4*g2 + f5_2*g1 + f6*g0 + f7_2*g9_19 + f8*g8_19 + f9_2*g7_19 h7 := f0*g7 + f1*g6 + f2*g5 + f3*g4 + f4*g3 + f5*g2 + f6*g1 + f7*g0 + f8*g9_19 + f9*g8_19 h8 := f0*g8 + f1_2*g7 + f2*g6 + f3_2*g5 + f4*g4 + f5_2*g3 + f6*g2 + f7_2*g1 + f8*g0 + f9_2*g9_19 h9 := f0*g9 + f1*g8 + f2*g7 + f3*g6 + f4*g5 + f5*g4 + f6*g3 + f7*g2 + f8*g1 + f9*g0 FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) } func feSquare(f *FieldElement) (h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 int64) { f0 := int64(f[0]) f1 := int64(f[1]) f2 := int64(f[2]) f3 := int64(f[3]) f4 := int64(f[4]) f5 := int64(f[5]) f6 := int64(f[6]) f7 := int64(f[7]) f8 := int64(f[8]) f9 := int64(f[9]) f0_2 := int64(2 * f[0]) f1_2 := int64(2 * f[1]) f2_2 := int64(2 * f[2]) f3_2 := int64(2 * f[3]) f4_2 := int64(2 * f[4]) f5_2 := int64(2 * f[5]) f6_2 := int64(2 * f[6]) f7_2 := int64(2 * f[7]) f5_38 := 38 * f5 // 1.31*2^30 f6_19 := 19 * f6 // 1.31*2^30 f7_38 := 38 * f7 // 1.31*2^30 f8_19 := 19 * f8 // 1.31*2^30 f9_38 := 38 * f9 // 1.31*2^30 h0 = f0*f0 + f1_2*f9_38 + f2_2*f8_19 + f3_2*f7_38 + f4_2*f6_19 + f5*f5_38 h1 = f0_2*f1 + f2*f9_38 + f3_2*f8_19 + f4*f7_38 + f5_2*f6_19 h2 = f0_2*f2 + f1_2*f1 + f3_2*f9_38 + f4_2*f8_19 + f5_2*f7_38 + f6*f6_19 h3 = f0_2*f3 + f1_2*f2 + f4*f9_38 + f5_2*f8_19 + f6*f7_38 h4 = f0_2*f4 + f1_2*f3_2 + f2*f2 + f5_2*f9_38 + f6_2*f8_19 + f7*f7_38 h5 = f0_2*f5 + f1_2*f4 + f2_2*f3 + f6*f9_38 + f7_2*f8_19 h6 = f0_2*f6 + f1_2*f5_2 + f2_2*f4 + f3_2*f3 + f7_2*f9_38 + f8*f8_19 h7 = f0_2*f7 + f1_2*f6 + f2_2*f5 + f3_2*f4 + f8*f9_38 h8 = f0_2*f8 + f1_2*f7_2 + f2_2*f6 + f3_2*f5_2 + f4*f4 + f9*f9_38 h9 = f0_2*f9 + f1_2*f8 + f2_2*f7 + f3_2*f6 + f4_2*f5 return } // FeSquare calculates h = f*f. Can overlap h with f. // // Preconditions: // |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. // // Postconditions: // |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. func FeSquare(h, f *FieldElement) { h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 := feSquare(f) FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) } // FeSquare2 sets h = 2 * f * f // // Can overlap h with f. // // Preconditions: // |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. // // Postconditions: // |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. // See fe_mul.c for discussion of implementation strategy. func FeSquare2(h, f *FieldElement) { h0, h1, h2, h3, h4, h5, h6, h7, h8, h9 := feSquare(f) h0 += h0 h1 += h1 h2 += h2 h3 += h3 h4 += h4 h5 += h5 h6 += h6 h7 += h7 h8 += h8 h9 += h9 FeCombine(h, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9) } func FeInvert(out, z *FieldElement) { var t0, t1, t2, t3 FieldElement var i int FeSquare(&t0, z) // 2^1 FeSquare(&t1, &t0) // 2^2 for i = 1; i < 2; i++ { // 2^3 FeSquare(&t1, &t1) } FeMul(&t1, z, &t1) // 2^3 + 2^0 FeMul(&t0, &t0, &t1) // 2^3 + 2^1 + 2^0 FeSquare(&t2, &t0) // 2^4 + 2^2 + 2^1 FeMul(&t1, &t1, &t2) // 2^4 + 2^3 + 2^2 + 2^1 + 2^0 FeSquare(&t2, &t1) // 5,4,3,2,1 for i = 1; i < 5; i++ { // 9,8,7,6,5 FeSquare(&t2, &t2) } FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 FeSquare(&t2, &t1) // 10..1 for i = 1; i < 10; i++ { // 19..10 FeSquare(&t2, &t2) } FeMul(&t2, &t2, &t1) // 19..0 FeSquare(&t3, &t2) // 20..1 for i = 1; i < 20; i++ { // 39..20 FeSquare(&t3, &t3) } FeMul(&t2, &t3, &t2) // 39..0 FeSquare(&t2, &t2) // 40..1 for i = 1; i < 10; i++ { // 49..10 FeSquare(&t2, &t2) } FeMul(&t1, &t2, &t1) // 49..0 FeSquare(&t2, &t1) // 50..1 for i = 1; i < 50; i++ { // 99..50 FeSquare(&t2, &t2) } FeMul(&t2, &t2, &t1) // 99..0 FeSquare(&t3, &t2) // 100..1 for i = 1; i < 100; i++ { // 199..100 FeSquare(&t3, &t3) } FeMul(&t2, &t3, &t2) // 199..0 FeSquare(&t2, &t2) // 200..1 for i = 1; i < 50; i++ { // 249..50 FeSquare(&t2, &t2) } FeMul(&t1, &t2, &t1) // 249..0 FeSquare(&t1, &t1) // 250..1 for i = 1; i < 5; i++ { // 254..5 FeSquare(&t1, &t1) } FeMul(out, &t1, &t0) // 254..5,3,1,0 } func fePow22523(out, z *FieldElement) { var t0, t1, t2 FieldElement var i int FeSquare(&t0, z) for i = 1; i < 1; i++ { FeSquare(&t0, &t0) } FeSquare(&t1, &t0) for i = 1; i < 2; i++ { FeSquare(&t1, &t1) } FeMul(&t1, z, &t1) FeMul(&t0, &t0, &t1) FeSquare(&t0, &t0) for i = 1; i < 1; i++ { FeSquare(&t0, &t0) } FeMul(&t0, &t1, &t0) FeSquare(&t1, &t0) for i = 1; i < 5; i++ { FeSquare(&t1, &t1) } FeMul(&t0, &t1, &t0) FeSquare(&t1, &t0) for i = 1; i < 10; i++ { FeSquare(&t1, &t1) } FeMul(&t1, &t1, &t0) FeSquare(&t2, &t1) for i = 1; i < 20; i++ { FeSquare(&t2, &t2) } FeMul(&t1, &t2, &t1) FeSquare(&t1, &t1) for i = 1; i < 10; i++ { FeSquare(&t1, &t1) } FeMul(&t0, &t1, &t0) FeSquare(&t1, &t0) for i = 1; i < 50; i++ { FeSquare(&t1, &t1) } FeMul(&t1, &t1, &t0) FeSquare(&t2, &t1) for i = 1; i < 100; i++ { FeSquare(&t2, &t2) } FeMul(&t1, &t2, &t1) FeSquare(&t1, &t1) for i = 1; i < 50; i++ { FeSquare(&t1, &t1) } FeMul(&t0, &t1, &t0) FeSquare(&t0, &t0) for i = 1; i < 2; i++ { FeSquare(&t0, &t0) } FeMul(out, &t0, z) } // Group elements are members of the elliptic curve -x^2 + y^2 = 1 + d * x^2 * // y^2 where d = -121665/121666. // // Several representations are used: // ProjectiveGroupElement: (X:Y:Z) satisfying x=X/Z, y=Y/Z // ExtendedGroupElement: (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT // CompletedGroupElement: ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T // PreComputedGroupElement: (y+x,y-x,2dxy) type ProjectiveGroupElement struct { X, Y, Z FieldElement } type ExtendedGroupElement struct { X, Y, Z, T FieldElement } type CompletedGroupElement struct { X, Y, Z, T FieldElement } type PreComputedGroupElement struct { yPlusX, yMinusX, xy2d FieldElement } type CachedGroupElement struct { yPlusX, yMinusX, Z, T2d FieldElement } func (p *ProjectiveGroupElement) Zero() { FeZero(&p.X) FeOne(&p.Y) FeOne(&p.Z) } func (p *ProjectiveGroupElement) Double(r *CompletedGroupElement) { var t0 FieldElement FeSquare(&r.X, &p.X) FeSquare(&r.Z, &p.Y) FeSquare2(&r.T, &p.Z) FeAdd(&r.Y, &p.X, &p.Y) FeSquare(&t0, &r.Y) FeAdd(&r.Y, &r.Z, &r.X) FeSub(&r.Z, &r.Z, &r.X) FeSub(&r.X, &t0, &r.Y) FeSub(&r.T, &r.T, &r.Z) } func (p *ProjectiveGroupElement) ToBytes(s *[32]byte) { var recip, x, y FieldElement FeInvert(&recip, &p.Z) FeMul(&x, &p.X, &recip) FeMul(&y, &p.Y, &recip) FeToBytes(s, &y) s[31] ^= FeIsNegative(&x) << 7 } func (p *ExtendedGroupElement) Zero() { FeZero(&p.X) FeOne(&p.Y) FeOne(&p.Z) FeZero(&p.T) } func (p *ExtendedGroupElement) Double(r *CompletedGroupElement) { var q ProjectiveGroupElement p.ToProjective(&q) q.Double(r) } func (p *ExtendedGroupElement) ToCached(r *CachedGroupElement) { FeAdd(&r.yPlusX, &p.Y, &p.X) FeSub(&r.yMinusX, &p.Y, &p.X) FeCopy(&r.Z, &p.Z) FeMul(&r.T2d, &p.T, &d2) } func (p *ExtendedGroupElement) ToProjective(r *ProjectiveGroupElement) { FeCopy(&r.X, &p.X) FeCopy(&r.Y, &p.Y) FeCopy(&r.Z, &p.Z) } func (p *ExtendedGroupElement) ToBytes(s *[32]byte) { var recip, x, y FieldElement FeInvert(&recip, &p.Z) FeMul(&x, &p.X, &recip) FeMul(&y, &p.Y, &recip) FeToBytes(s, &y) s[31] ^= FeIsNegative(&x) << 7 } func (p *ExtendedGroupElement) FromBytes(s *[32]byte) bool { var u, v, v3, vxx, check FieldElement FeFromBytes(&p.Y, s) FeOne(&p.Z) FeSquare(&u, &p.Y) FeMul(&v, &u, &d) FeSub(&u, &u, &p.Z) // y = y^2-1 FeAdd(&v, &v, &p.Z) // v = dy^2+1 FeSquare(&v3, &v) FeMul(&v3, &v3, &v) // v3 = v^3 FeSquare(&p.X, &v3) FeMul(&p.X, &p.X, &v) FeMul(&p.X, &p.X, &u) // x = uv^7 fePow22523(&p.X, &p.X) // x = (uv^7)^((q-5)/8) FeMul(&p.X, &p.X, &v3) FeMul(&p.X, &p.X, &u) // x = uv^3(uv^7)^((q-5)/8) var tmpX, tmp2 [32]byte FeSquare(&vxx, &p.X) FeMul(&vxx, &vxx, &v) FeSub(&check, &vxx, &u) // vx^2-u if FeIsNonZero(&check) == 1 { FeAdd(&check, &vxx, &u) // vx^2+u if FeIsNonZero(&check) == 1 { return false } FeMul(&p.X, &p.X, &SqrtM1) FeToBytes(&tmpX, &p.X) for i, v := range tmpX { tmp2[31-i] = v } } if FeIsNegative(&p.X) != (s[31] >> 7) { FeNeg(&p.X, &p.X) } FeMul(&p.T, &p.X, &p.Y) return true } func (p *CompletedGroupElement) ToProjective(r *ProjectiveGroupElement) { FeMul(&r.X, &p.X, &p.T) FeMul(&r.Y, &p.Y, &p.Z) FeMul(&r.Z, &p.Z, &p.T) } func (p *CompletedGroupElement) ToExtended(r *ExtendedGroupElement) { FeMul(&r.X, &p.X, &p.T) FeMul(&r.Y, &p.Y, &p.Z) FeMul(&r.Z, &p.Z, &p.T) FeMul(&r.T, &p.X, &p.Y) } func (p *PreComputedGroupElement) Zero() { FeOne(&p.yPlusX) FeOne(&p.yMinusX) FeZero(&p.xy2d) } func geAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { var t0 FieldElement FeAdd(&r.X, &p.Y, &p.X) FeSub(&r.Y, &p.Y, &p.X) FeMul(&r.Z, &r.X, &q.yPlusX) FeMul(&r.Y, &r.Y, &q.yMinusX) FeMul(&r.T, &q.T2d, &p.T) FeMul(&r.X, &p.Z, &q.Z) FeAdd(&t0, &r.X, &r.X) FeSub(&r.X, &r.Z, &r.Y) FeAdd(&r.Y, &r.Z, &r.Y) FeAdd(&r.Z, &t0, &r.T) FeSub(&r.T, &t0, &r.T) } func geSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { var t0 FieldElement FeAdd(&r.X, &p.Y, &p.X) FeSub(&r.Y, &p.Y, &p.X) FeMul(&r.Z, &r.X, &q.yMinusX) FeMul(&r.Y, &r.Y, &q.yPlusX) FeMul(&r.T, &q.T2d, &p.T) FeMul(&r.X, &p.Z, &q.Z) FeAdd(&t0, &r.X, &r.X) FeSub(&r.X, &r.Z, &r.Y) FeAdd(&r.Y, &r.Z, &r.Y) FeSub(&r.Z, &t0, &r.T) FeAdd(&r.T, &t0, &r.T) } func geMixedAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { var t0 FieldElement FeAdd(&r.X, &p.Y, &p.X) FeSub(&r.Y, &p.Y, &p.X) FeMul(&r.Z, &r.X, &q.yPlusX) FeMul(&r.Y, &r.Y, &q.yMinusX) FeMul(&r.T, &q.xy2d, &p.T) FeAdd(&t0, &p.Z, &p.Z) FeSub(&r.X, &r.Z, &r.Y) FeAdd(&r.Y, &r.Z, &r.Y) FeAdd(&r.Z, &t0, &r.T) FeSub(&r.T, &t0, &r.T) } func geMixedSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { var t0 FieldElement FeAdd(&r.X, &p.Y, &p.X) FeSub(&r.Y, &p.Y, &p.X) FeMul(&r.Z, &r.X, &q.yMinusX) FeMul(&r.Y, &r.Y, &q.yPlusX) FeMul(&r.T, &q.xy2d, &p.T) FeAdd(&t0, &p.Z, &p.Z) FeSub(&r.X, &r.Z, &r.Y) FeAdd(&r.Y, &r.Z, &r.Y) FeSub(&r.Z, &t0, &r.T) FeAdd(&r.T, &t0, &r.T) } func slide(r *[256]int8, a *[32]byte) { for i := range r { r[i] = int8(1 & (a[i>>3] >> uint(i&7))) } for i := range r { if r[i] != 0 { for b := 1; b <= 6 && i+b < 256; b++ { if r[i+b] != 0 { if r[i]+(r[i+b]<<uint(b)) <= 15 { r[i] += r[i+b] << uint(b) r[i+b] = 0 } else if r[i]-(r[i+b]<<uint(b)) >= -15 { r[i] -= r[i+b] << uint(b) for k := i + b; k < 256; k++ { if r[k] == 0 { r[k] = 1 break } r[k] = 0 } } else { break } } } } } } // GeDoubleScalarMultVartime sets r = a*A + b*B // where a = a[0]+256*a[1]+...+256^31 a[31]. // and b = b[0]+256*b[1]+...+256^31 b[31]. // B is the Ed25519 base point (x,4/5) with x positive. func GeDoubleScalarMultVartime(r *ProjectiveGroupElement, a *[32]byte, A *ExtendedGroupElement, b *[32]byte) { var aSlide, bSlide [256]int8 var Ai [8]CachedGroupElement // A,3A,5A,7A,9A,11A,13A,15A var t CompletedGroupElement var u, A2 ExtendedGroupElement var i int slide(&aSlide, a) slide(&bSlide, b) A.ToCached(&Ai[0]) A.Double(&t) t.ToExtended(&A2) for i := 0; i < 7; i++ { geAdd(&t, &A2, &Ai[i]) t.ToExtended(&u) u.ToCached(&Ai[i+1]) } r.Zero() for i = 255; i >= 0; i-- { if aSlide[i] != 0 || bSlide[i] != 0 { break } } for ; i >= 0; i-- { r.Double(&t) if aSlide[i] > 0 { t.ToExtended(&u) geAdd(&t, &u, &Ai[aSlide[i]/2]) } else if aSlide[i] < 0 { t.ToExtended(&u) geSub(&t, &u, &Ai[(-aSlide[i])/2]) } if bSlide[i] > 0 { t.ToExtended(&u) geMixedAdd(&t, &u, &bi[bSlide[i]/2]) } else if bSlide[i] < 0 { t.ToExtended(&u) geMixedSub(&t, &u, &bi[(-bSlide[i])/2]) } t.ToProjective(r) } } // equal returns 1 if b == c and 0 otherwise, assuming that b and c are // non-negative. func equal(b, c int32) int32 { x := uint32(b ^ c) x-- return int32(x >> 31) } // negative returns 1 if b < 0 and 0 otherwise. func negative(b int32) int32 { return (b >> 31) & 1 } func PreComputedGroupElementCMove(t, u *PreComputedGroupElement, b int32) { FeCMove(&t.yPlusX, &u.yPlusX, b) FeCMove(&t.yMinusX, &u.yMinusX, b) FeCMove(&t.xy2d, &u.xy2d, b) } func selectPoint(t *PreComputedGroupElement, pos int32, b int32) { var minusT PreComputedGroupElement bNegative := negative(b) bAbs := b - (((-bNegative) & b) << 1) t.Zero() for i := int32(0); i < 8; i++ { PreComputedGroupElementCMove(t, &base[pos][i], equal(bAbs, i+1)) } FeCopy(&minusT.yPlusX, &t.yMinusX) FeCopy(&minusT.yMinusX, &t.yPlusX) FeNeg(&minusT.xy2d, &t.xy2d) PreComputedGroupElementCMove(t, &minusT, bNegative) } // GeScalarMultBase computes h = a*B, where // a = a[0]+256*a[1]+...+256^31 a[31] // B is the Ed25519 base point (x,4/5) with x positive. // // Preconditions: // a[31] <= 127 func GeScalarMultBase(h *ExtendedGroupElement, a *[32]byte) { var e [64]int8 for i, v := range a { e[2*i] = int8(v & 15) e[2*i+1] = int8((v >> 4) & 15) } // each e[i] is between 0 and 15 and e[63] is between 0 and 7. carry := int8(0) for i := 0; i < 63; i++ { e[i] += carry carry = (e[i] + 8) >> 4 e[i] -= carry << 4 } e[63] += carry // each e[i] is between -8 and 8. h.Zero() var t PreComputedGroupElement var r CompletedGroupElement for i := int32(1); i < 64; i += 2 { selectPoint(&t, i/2, int32(e[i])) geMixedAdd(&r, h, &t) r.ToExtended(h) } var s ProjectiveGroupElement h.Double(&r) r.ToProjective(&s) s.Double(&r) r.ToProjective(&s) s.Double(&r) r.ToProjective(&s) s.Double(&r) r.ToExtended(h) for i := int32(0); i < 64; i += 2 { selectPoint(&t, i/2, int32(e[i])) geMixedAdd(&r, h, &t) r.ToExtended(h) } } // The scalars are GF(2^252 + 27742317777372353535851937790883648493). // Input: // a[0]+256*a[1]+...+256^31*a[31] = a // b[0]+256*b[1]+...+256^31*b[31] = b // c[0]+256*c[1]+...+256^31*c[31] = c // // Output: // s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l // where l = 2^252 + 27742317777372353535851937790883648493. func ScMulAdd(s, a, b, c *[32]byte) { a0 := 2097151 & load3(a[:]) a1 := 2097151 & (load4(a[2:]) >> 5) a2 := 2097151 & (load3(a[5:]) >> 2) a3 := 2097151 & (load4(a[7:]) >> 7) a4 := 2097151 & (load4(a[10:]) >> 4) a5 := 2097151 & (load3(a[13:]) >> 1) a6 := 2097151 & (load4(a[15:]) >> 6) a7 := 2097151 & (load3(a[18:]) >> 3) a8 := 2097151 & load3(a[21:]) a9 := 2097151 & (load4(a[23:]) >> 5) a10 := 2097151 & (load3(a[26:]) >> 2) a11 := (load4(a[28:]) >> 7) b0 := 2097151 & load3(b[:]) b1 := 2097151 & (load4(b[2:]) >> 5) b2 := 2097151 & (load3(b[5:]) >> 2) b3 := 2097151 & (load4(b[7:]) >> 7) b4 := 2097151 & (load4(b[10:]) >> 4) b5 := 2097151 & (load3(b[13:]) >> 1) b6 := 2097151 & (load4(b[15:]) >> 6) b7 := 2097151 & (load3(b[18:]) >> 3) b8 := 2097151 & load3(b[21:]) b9 := 2097151 & (load4(b[23:]) >> 5) b10 := 2097151 & (load3(b[26:]) >> 2) b11 := (load4(b[28:]) >> 7) c0 := 2097151 & load3(c[:]) c1 := 2097151 & (load4(c[2:]) >> 5) c2 := 2097151 & (load3(c[5:]) >> 2) c3 := 2097151 & (load4(c[7:]) >> 7) c4 := 2097151 & (load4(c[10:]) >> 4) c5 := 2097151 & (load3(c[13:]) >> 1) c6 := 2097151 & (load4(c[15:]) >> 6) c7 := 2097151 & (load3(c[18:]) >> 3) c8 := 2097151 & load3(c[21:]) c9 := 2097151 & (load4(c[23:]) >> 5) c10 := 2097151 & (load3(c[26:]) >> 2) c11 := (load4(c[28:]) >> 7) var carry [23]int64 s0 := c0 + a0*b0 s1 := c1 + a0*b1 + a1*b0 s2 := c2 + a0*b2 + a1*b1 + a2*b0 s3 := c3 + a0*b3 + a1*b2 + a2*b1 + a3*b0 s4 := c4 + a0*b4 + a1*b3 + a2*b2 + a3*b1 + a4*b0 s5 := c5 + a0*b5 + a1*b4 + a2*b3 + a3*b2 + a4*b1 + a5*b0 s6 := c6 + a0*b6 + a1*b5 + a2*b4 + a3*b3 + a4*b2 + a5*b1 + a6*b0 s7 := c7 + a0*b7 + a1*b6 + a2*b5 + a3*b4 + a4*b3 + a5*b2 + a6*b1 + a7*b0 s8 := c8 + a0*b8 + a1*b7 + a2*b6 + a3*b5 + a4*b4 + a5*b3 + a6*b2 + a7*b1 + a8*b0 s9 := c9 + a0*b9 + a1*b8 + a2*b7 + a3*b6 + a4*b5 + a5*b4 + a6*b3 + a7*b2 + a8*b1 + a9*b0 s10 := c10 + a0*b10 + a1*b9 + a2*b8 + a3*b7 + a4*b6 + a5*b5 + a6*b4 + a7*b3 + a8*b2 + a9*b1 + a10*b0 s11 := c11 + a0*b11 + a1*b10 + a2*b9 + a3*b8 + a4*b7 + a5*b6 + a6*b5 + a7*b4 + a8*b3 + a9*b2 + a10*b1 + a11*b0 s12 := a1*b11 + a2*b10 + a3*b9 + a4*b8 + a5*b7 + a6*b6 + a7*b5 + a8*b4 + a9*b3 + a10*b2 + a11*b1 s13 := a2*b11 + a3*b10 + a4*b9 + a5*b8 + a6*b7 + a7*b6 + a8*b5 + a9*b4 + a10*b3 + a11*b2 s14 := a3*b11 + a4*b10 + a5*b9 + a6*b8 + a7*b7 + a8*b6 + a9*b5 + a10*b4 + a11*b3 s15 := a4*b11 + a5*b10 + a6*b9 + a7*b8 + a8*b7 + a9*b6 + a10*b5 + a11*b4 s16 := a5*b11 + a6*b10 + a7*b9 + a8*b8 + a9*b7 + a10*b6 + a11*b5 s17 := a6*b11 + a7*b10 + a8*b9 + a9*b8 + a10*b7 + a11*b6 s18 := a7*b11 + a8*b10 + a9*b9 + a10*b8 + a11*b7 s19 := a8*b11 + a9*b10 + a10*b9 + a11*b8 s20 := a9*b11 + a10*b10 + a11*b9 s21 := a10*b11 + a11*b10 s22 := a11 * b11 s23 := int64(0) carry[0] = (s0 + (1 << 20)) >> 21 s1 += carry[0] s0 -= carry[0] << 21 carry[2] = (s2 + (1 << 20)) >> 21 s3 += carry[2] s2 -= carry[2] << 21 carry[4] = (s4 + (1 << 20)) >> 21 s5 += carry[4] s4 -= carry[4] << 21 carry[6] = (s6 + (1 << 20)) >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[8] = (s8 + (1 << 20)) >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[10] = (s10 + (1 << 20)) >> 21 s11 += carry[10] s10 -= carry[10] << 21 carry[12] = (s12 + (1 << 20)) >> 21 s13 += carry[12] s12 -= carry[12] << 21 carry[14] = (s14 + (1 << 20)) >> 21 s15 += carry[14] s14 -= carry[14] << 21 carry[16] = (s16 + (1 << 20)) >> 21 s17 += carry[16] s16 -= carry[16] << 21 carry[18] = (s18 + (1 << 20)) >> 21 s19 += carry[18] s18 -= carry[18] << 21 carry[20] = (s20 + (1 << 20)) >> 21 s21 += carry[20] s20 -= carry[20] << 21 carry[22] = (s22 + (1 << 20)) >> 21 s23 += carry[22] s22 -= carry[22] << 21 carry[1] = (s1 + (1 << 20)) >> 21 s2 += carry[1] s1 -= carry[1] << 21 carry[3] = (s3 + (1 << 20)) >> 21 s4 += carry[3] s3 -= carry[3] << 21 carry[5] = (s5 + (1 << 20)) >> 21 s6 += carry[5] s5 -= carry[5] << 21 carry[7] = (s7 + (1 << 20)) >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[9] = (s9 + (1 << 20)) >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[11] = (s11 + (1 << 20)) >> 21 s12 += carry[11] s11 -= carry[11] << 21 carry[13] = (s13 + (1 << 20)) >> 21 s14 += carry[13] s13 -= carry[13] << 21 carry[15] = (s15 + (1 << 20)) >> 21 s16 += carry[15] s15 -= carry[15] << 21 carry[17] = (s17 + (1 << 20)) >> 21 s18 += carry[17] s17 -= carry[17] << 21 carry[19] = (s19 + (1 << 20)) >> 21 s20 += carry[19] s19 -= carry[19] << 21 carry[21] = (s21 + (1 << 20)) >> 21 s22 += carry[21] s21 -= carry[21] << 21 s11 += s23 * 666643 s12 += s23 * 470296 s13 += s23 * 654183 s14 -= s23 * 997805 s15 += s23 * 136657 s16 -= s23 * 683901 s23 = 0 s10 += s22 * 666643 s11 += s22 * 470296 s12 += s22 * 654183 s13 -= s22 * 997805 s14 += s22 * 136657 s15 -= s22 * 683901 s22 = 0 s9 += s21 * 666643 s10 += s21 * 470296 s11 += s21 * 654183 s12 -= s21 * 997805 s13 += s21 * 136657 s14 -= s21 * 683901 s21 = 0 s8 += s20 * 666643 s9 += s20 * 470296 s10 += s20 * 654183 s11 -= s20 * 997805 s12 += s20 * 136657 s13 -= s20 * 683901 s20 = 0 s7 += s19 * 666643 s8 += s19 * 470296 s9 += s19 * 654183 s10 -= s19 * 997805 s11 += s19 * 136657 s12 -= s19 * 683901 s19 = 0 s6 += s18 * 666643 s7 += s18 * 470296 s8 += s18 * 654183 s9 -= s18 * 997805 s10 += s18 * 136657 s11 -= s18 * 683901 s18 = 0 carry[6] = (s6 + (1 << 20)) >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[8] = (s8 + (1 << 20)) >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[10] = (s10 + (1 << 20)) >> 21 s11 += carry[10] s10 -= carry[10] << 21 carry[12] = (s12 + (1 << 20)) >> 21 s13 += carry[12] s12 -= carry[12] << 21 carry[14] = (s14 + (1 << 20)) >> 21 s15 += carry[14] s14 -= carry[14] << 21 carry[16] = (s16 + (1 << 20)) >> 21 s17 += carry[16] s16 -= carry[16] << 21 carry[7] = (s7 + (1 << 20)) >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[9] = (s9 + (1 << 20)) >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[11] = (s11 + (1 << 20)) >> 21 s12 += carry[11] s11 -= carry[11] << 21 carry[13] = (s13 + (1 << 20)) >> 21 s14 += carry[13] s13 -= carry[13] << 21 carry[15] = (s15 + (1 << 20)) >> 21 s16 += carry[15] s15 -= carry[15] << 21 s5 += s17 * 666643 s6 += s17 * 470296 s7 += s17 * 654183 s8 -= s17 * 997805 s9 += s17 * 136657 s10 -= s17 * 683901 s17 = 0 s4 += s16 * 666643 s5 += s16 * 470296 s6 += s16 * 654183 s7 -= s16 * 997805 s8 += s16 * 136657 s9 -= s16 * 683901 s16 = 0 s3 += s15 * 666643 s4 += s15 * 470296 s5 += s15 * 654183 s6 -= s15 * 997805 s7 += s15 * 136657 s8 -= s15 * 683901 s15 = 0 s2 += s14 * 666643 s3 += s14 * 470296 s4 += s14 * 654183 s5 -= s14 * 997805 s6 += s14 * 136657 s7 -= s14 * 683901 s14 = 0 s1 += s13 * 666643 s2 += s13 * 470296 s3 += s13 * 654183 s4 -= s13 * 997805 s5 += s13 * 136657 s6 -= s13 * 683901 s13 = 0 s0 += s12 * 666643 s1 += s12 * 470296 s2 += s12 * 654183 s3 -= s12 * 997805 s4 += s12 * 136657 s5 -= s12 * 683901 s12 = 0 carry[0] = (s0 + (1 << 20)) >> 21 s1 += carry[0] s0 -= carry[0] << 21 carry[2] = (s2 + (1 << 20)) >> 21 s3 += carry[2] s2 -= carry[2] << 21 carry[4] = (s4 + (1 << 20)) >> 21 s5 += carry[4] s4 -= carry[4] << 21 carry[6] = (s6 + (1 << 20)) >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[8] = (s8 + (1 << 20)) >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[10] = (s10 + (1 << 20)) >> 21 s11 += carry[10] s10 -= carry[10] << 21 carry[1] = (s1 + (1 << 20)) >> 21 s2 += carry[1] s1 -= carry[1] << 21 carry[3] = (s3 + (1 << 20)) >> 21 s4 += carry[3] s3 -= carry[3] << 21 carry[5] = (s5 + (1 << 20)) >> 21 s6 += carry[5] s5 -= carry[5] << 21 carry[7] = (s7 + (1 << 20)) >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[9] = (s9 + (1 << 20)) >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[11] = (s11 + (1 << 20)) >> 21 s12 += carry[11] s11 -= carry[11] << 21 s0 += s12 * 666643 s1 += s12 * 470296 s2 += s12 * 654183 s3 -= s12 * 997805 s4 += s12 * 136657 s5 -= s12 * 683901 s12 = 0 carry[0] = s0 >> 21 s1 += carry[0] s0 -= carry[0] << 21 carry[1] = s1 >> 21 s2 += carry[1] s1 -= carry[1] << 21 carry[2] = s2 >> 21 s3 += carry[2] s2 -= carry[2] << 21 carry[3] = s3 >> 21 s4 += carry[3] s3 -= carry[3] << 21 carry[4] = s4 >> 21 s5 += carry[4] s4 -= carry[4] << 21 carry[5] = s5 >> 21 s6 += carry[5] s5 -= carry[5] << 21 carry[6] = s6 >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[7] = s7 >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[8] = s8 >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[9] = s9 >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[10] = s10 >> 21 s11 += carry[10] s10 -= carry[10] << 21 carry[11] = s11 >> 21 s12 += carry[11] s11 -= carry[11] << 21 s0 += s12 * 666643 s1 += s12 * 470296 s2 += s12 * 654183 s3 -= s12 * 997805 s4 += s12 * 136657 s5 -= s12 * 683901 s12 = 0 carry[0] = s0 >> 21 s1 += carry[0] s0 -= carry[0] << 21 carry[1] = s1 >> 21 s2 += carry[1] s1 -= carry[1] << 21 carry[2] = s2 >> 21 s3 += carry[2] s2 -= carry[2] << 21 carry[3] = s3 >> 21 s4 += carry[3] s3 -= carry[3] << 21 carry[4] = s4 >> 21 s5 += carry[4] s4 -= carry[4] << 21 carry[5] = s5 >> 21 s6 += carry[5] s5 -= carry[5] << 21 carry[6] = s6 >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[7] = s7 >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[8] = s8 >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[9] = s9 >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[10] = s10 >> 21 s11 += carry[10] s10 -= carry[10] << 21 s[0] = byte(s0 >> 0) s[1] = byte(s0 >> 8) s[2] = byte((s0 >> 16) | (s1 << 5)) s[3] = byte(s1 >> 3) s[4] = byte(s1 >> 11) s[5] = byte((s1 >> 19) | (s2 << 2)) s[6] = byte(s2 >> 6) s[7] = byte((s2 >> 14) | (s3 << 7)) s[8] = byte(s3 >> 1) s[9] = byte(s3 >> 9) s[10] = byte((s3 >> 17) | (s4 << 4)) s[11] = byte(s4 >> 4) s[12] = byte(s4 >> 12) s[13] = byte((s4 >> 20) | (s5 << 1)) s[14] = byte(s5 >> 7) s[15] = byte((s5 >> 15) | (s6 << 6)) s[16] = byte(s6 >> 2) s[17] = byte(s6 >> 10) s[18] = byte((s6 >> 18) | (s7 << 3)) s[19] = byte(s7 >> 5) s[20] = byte(s7 >> 13) s[21] = byte(s8 >> 0) s[22] = byte(s8 >> 8) s[23] = byte((s8 >> 16) | (s9 << 5)) s[24] = byte(s9 >> 3) s[25] = byte(s9 >> 11) s[26] = byte((s9 >> 19) | (s10 << 2)) s[27] = byte(s10 >> 6) s[28] = byte((s10 >> 14) | (s11 << 7)) s[29] = byte(s11 >> 1) s[30] = byte(s11 >> 9) s[31] = byte(s11 >> 17) } // Input: // s[0]+256*s[1]+...+256^63*s[63] = s // // Output: // s[0]+256*s[1]+...+256^31*s[31] = s mod l // where l = 2^252 + 27742317777372353535851937790883648493. func ScReduce(out *[32]byte, s *[64]byte) { s0 := 2097151 & load3(s[:]) s1 := 2097151 & (load4(s[2:]) >> 5) s2 := 2097151 & (load3(s[5:]) >> 2) s3 := 2097151 & (load4(s[7:]) >> 7) s4 := 2097151 & (load4(s[10:]) >> 4) s5 := 2097151 & (load3(s[13:]) >> 1) s6 := 2097151 & (load4(s[15:]) >> 6) s7 := 2097151 & (load3(s[18:]) >> 3) s8 := 2097151 & load3(s[21:]) s9 := 2097151 & (load4(s[23:]) >> 5) s10 := 2097151 & (load3(s[26:]) >> 2) s11 := 2097151 & (load4(s[28:]) >> 7) s12 := 2097151 & (load4(s[31:]) >> 4) s13 := 2097151 & (load3(s[34:]) >> 1) s14 := 2097151 & (load4(s[36:]) >> 6) s15 := 2097151 & (load3(s[39:]) >> 3) s16 := 2097151 & load3(s[42:]) s17 := 2097151 & (load4(s[44:]) >> 5) s18 := 2097151 & (load3(s[47:]) >> 2) s19 := 2097151 & (load4(s[49:]) >> 7) s20 := 2097151 & (load4(s[52:]) >> 4) s21 := 2097151 & (load3(s[55:]) >> 1) s22 := 2097151 & (load4(s[57:]) >> 6) s23 := (load4(s[60:]) >> 3) s11 += s23 * 666643 s12 += s23 * 470296 s13 += s23 * 654183 s14 -= s23 * 997805 s15 += s23 * 136657 s16 -= s23 * 683901 s23 = 0 s10 += s22 * 666643 s11 += s22 * 470296 s12 += s22 * 654183 s13 -= s22 * 997805 s14 += s22 * 136657 s15 -= s22 * 683901 s22 = 0 s9 += s21 * 666643 s10 += s21 * 470296 s11 += s21 * 654183 s12 -= s21 * 997805 s13 += s21 * 136657 s14 -= s21 * 683901 s21 = 0 s8 += s20 * 666643 s9 += s20 * 470296 s10 += s20 * 654183 s11 -= s20 * 997805 s12 += s20 * 136657 s13 -= s20 * 683901 s20 = 0 s7 += s19 * 666643 s8 += s19 * 470296 s9 += s19 * 654183 s10 -= s19 * 997805 s11 += s19 * 136657 s12 -= s19 * 683901 s19 = 0 s6 += s18 * 666643 s7 += s18 * 470296 s8 += s18 * 654183 s9 -= s18 * 997805 s10 += s18 * 136657 s11 -= s18 * 683901 s18 = 0 var carry [17]int64 carry[6] = (s6 + (1 << 20)) >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[8] = (s8 + (1 << 20)) >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[10] = (s10 + (1 << 20)) >> 21 s11 += carry[10] s10 -= carry[10] << 21 carry[12] = (s12 + (1 << 20)) >> 21 s13 += carry[12] s12 -= carry[12] << 21 carry[14] = (s14 + (1 << 20)) >> 21 s15 += carry[14] s14 -= carry[14] << 21 carry[16] = (s16 + (1 << 20)) >> 21 s17 += carry[16] s16 -= carry[16] << 21 carry[7] = (s7 + (1 << 20)) >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[9] = (s9 + (1 << 20)) >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[11] = (s11 + (1 << 20)) >> 21 s12 += carry[11] s11 -= carry[11] << 21 carry[13] = (s13 + (1 << 20)) >> 21 s14 += carry[13] s13 -= carry[13] << 21 carry[15] = (s15 + (1 << 20)) >> 21 s16 += carry[15] s15 -= carry[15] << 21 s5 += s17 * 666643 s6 += s17 * 470296 s7 += s17 * 654183 s8 -= s17 * 997805 s9 += s17 * 136657 s10 -= s17 * 683901 s17 = 0 s4 += s16 * 666643 s5 += s16 * 470296 s6 += s16 * 654183 s7 -= s16 * 997805 s8 += s16 * 136657 s9 -= s16 * 683901 s16 = 0 s3 += s15 * 666643 s4 += s15 * 470296 s5 += s15 * 654183 s6 -= s15 * 997805 s7 += s15 * 136657 s8 -= s15 * 683901 s15 = 0 s2 += s14 * 666643 s3 += s14 * 470296 s4 += s14 * 654183 s5 -= s14 * 997805 s6 += s14 * 136657 s7 -= s14 * 683901 s14 = 0 s1 += s13 * 666643 s2 += s13 * 470296 s3 += s13 * 654183 s4 -= s13 * 997805 s5 += s13 * 136657 s6 -= s13 * 683901 s13 = 0 s0 += s12 * 666643 s1 += s12 * 470296 s2 += s12 * 654183 s3 -= s12 * 997805 s4 += s12 * 136657 s5 -= s12 * 683901 s12 = 0 carry[0] = (s0 + (1 << 20)) >> 21 s1 += carry[0] s0 -= carry[0] << 21 carry[2] = (s2 + (1 << 20)) >> 21 s3 += carry[2] s2 -= carry[2] << 21 carry[4] = (s4 + (1 << 20)) >> 21 s5 += carry[4] s4 -= carry[4] << 21 carry[6] = (s6 + (1 << 20)) >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[8] = (s8 + (1 << 20)) >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[10] = (s10 + (1 << 20)) >> 21 s11 += carry[10] s10 -= carry[10] << 21 carry[1] = (s1 + (1 << 20)) >> 21 s2 += carry[1] s1 -= carry[1] << 21 carry[3] = (s3 + (1 << 20)) >> 21 s4 += carry[3] s3 -= carry[3] << 21 carry[5] = (s5 + (1 << 20)) >> 21 s6 += carry[5] s5 -= carry[5] << 21 carry[7] = (s7 + (1 << 20)) >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[9] = (s9 + (1 << 20)) >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[11] = (s11 + (1 << 20)) >> 21 s12 += carry[11] s11 -= carry[11] << 21 s0 += s12 * 666643 s1 += s12 * 470296 s2 += s12 * 654183 s3 -= s12 * 997805 s4 += s12 * 136657 s5 -= s12 * 683901 s12 = 0 carry[0] = s0 >> 21 s1 += carry[0] s0 -= carry[0] << 21 carry[1] = s1 >> 21 s2 += carry[1] s1 -= carry[1] << 21 carry[2] = s2 >> 21 s3 += carry[2] s2 -= carry[2] << 21 carry[3] = s3 >> 21 s4 += carry[3] s3 -= carry[3] << 21 carry[4] = s4 >> 21 s5 += carry[4] s4 -= carry[4] << 21 carry[5] = s5 >> 21 s6 += carry[5] s5 -= carry[5] << 21 carry[6] = s6 >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[7] = s7 >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[8] = s8 >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[9] = s9 >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[10] = s10 >> 21 s11 += carry[10] s10 -= carry[10] << 21 carry[11] = s11 >> 21 s12 += carry[11] s11 -= carry[11] << 21 s0 += s12 * 666643 s1 += s12 * 470296 s2 += s12 * 654183 s3 -= s12 * 997805 s4 += s12 * 136657 s5 -= s12 * 683901 s12 = 0 carry[0] = s0 >> 21 s1 += carry[0] s0 -= carry[0] << 21 carry[1] = s1 >> 21 s2 += carry[1] s1 -= carry[1] << 21 carry[2] = s2 >> 21 s3 += carry[2] s2 -= carry[2] << 21 carry[3] = s3 >> 21 s4 += carry[3] s3 -= carry[3] << 21 carry[4] = s4 >> 21 s5 += carry[4] s4 -= carry[4] << 21 carry[5] = s5 >> 21 s6 += carry[5] s5 -= carry[5] << 21 carry[6] = s6 >> 21 s7 += carry[6] s6 -= carry[6] << 21 carry[7] = s7 >> 21 s8 += carry[7] s7 -= carry[7] << 21 carry[8] = s8 >> 21 s9 += carry[8] s8 -= carry[8] << 21 carry[9] = s9 >> 21 s10 += carry[9] s9 -= carry[9] << 21 carry[10] = s10 >> 21 s11 += carry[10] s10 -= carry[10] << 21 out[0] = byte(s0 >> 0) out[1] = byte(s0 >> 8) out[2] = byte((s0 >> 16) | (s1 << 5)) out[3] = byte(s1 >> 3) out[4] = byte(s1 >> 11) out[5] = byte((s1 >> 19) | (s2 << 2)) out[6] = byte(s2 >> 6) out[7] = byte((s2 >> 14) | (s3 << 7)) out[8] = byte(s3 >> 1) out[9] = byte(s3 >> 9) out[10] = byte((s3 >> 17) | (s4 << 4)) out[11] = byte(s4 >> 4) out[12] = byte(s4 >> 12) out[13] = byte((s4 >> 20) | (s5 << 1)) out[14] = byte(s5 >> 7) out[15] = byte((s5 >> 15) | (s6 << 6)) out[16] = byte(s6 >> 2) out[17] = byte(s6 >> 10) out[18] = byte((s6 >> 18) | (s7 << 3)) out[19] = byte(s7 >> 5) out[20] = byte(s7 >> 13) out[21] = byte(s8 >> 0) out[22] = byte(s8 >> 8) out[23] = byte((s8 >> 16) | (s9 << 5)) out[24] = byte(s9 >> 3) out[25] = byte(s9 >> 11) out[26] = byte((s9 >> 19) | (s10 << 2)) out[27] = byte(s10 >> 6) out[28] = byte((s10 >> 14) | (s11 << 7)) out[29] = byte(s11 >> 1) out[30] = byte(s11 >> 9) out[31] = byte(s11 >> 17) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/internal/edwards25519/const.go����������������������0000644�0610621�0607500�00000274342�13172163317�027414� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package edwards25519 // These values are from the public domain, “ref10†implementation of ed25519 // from SUPERCOP. // d is a constant in the Edwards curve equation. var d = FieldElement{ -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116, } // d2 is 2*d. var d2 = FieldElement{ -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199, } // SqrtM1 is the square-root of -1 in the field. var SqrtM1 = FieldElement{ -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482, } // A is a constant in the Montgomery-form of curve25519. var A = FieldElement{ 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0, } // bi contains precomputed multiples of the base-point. See the Ed25519 paper // for a discussion about how these values are used. var bi = [8]PreComputedGroupElement{ { FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, FieldElement{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, FieldElement{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, }, { FieldElement{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, FieldElement{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, FieldElement{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, }, { FieldElement{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, FieldElement{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, FieldElement{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, }, { FieldElement{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, FieldElement{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, FieldElement{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, }, { FieldElement{-22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, -1361450, -13062696, 13821877}, FieldElement{-6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, -7212327, 18853322, -14220951}, FieldElement{4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, -10431137, 2207753, -3209784}, }, { FieldElement{-25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, -663000, -31111463, -16132436}, FieldElement{25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, 15725684, 171356, 6466918}, FieldElement{23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, -14088058, -30714912, 16193877}, }, { FieldElement{-33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, 4729455, -18074513, 9256800}, FieldElement{-25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, 9761698, -19827198, 630305}, FieldElement{-13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, -15960994, -2449256, -14291300}, }, { FieldElement{-3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, 15033784, 25105118, -7894876}, FieldElement{-24326370, 15950226, -31801215, -14592823, -11662737, -5090925, 1573892, -2625887, 2198790, -15804619}, FieldElement{-3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, -16236442, -32461234, -12290683}, }, } // base contains precomputed multiples of the base-point. See the Ed25519 paper // for a discussion about how these values are used. var base = [32][8]PreComputedGroupElement{ { { FieldElement{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, FieldElement{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, FieldElement{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, }, { FieldElement{-12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903, -3814571, -358445, -10211303}, FieldElement{-21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268, -26829678, -5319081}, FieldElement{26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118, -15472047, -4166697}, }, { FieldElement{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, FieldElement{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, FieldElement{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, }, { FieldElement{-17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023, 3284568, -6276540}, FieldElement{23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445, 13059162, 10374397}, FieldElement{7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045, -641708, -101325}, }, { FieldElement{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, FieldElement{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, FieldElement{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, }, { FieldElement{-15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819, -9818940, -12085777}, FieldElement{-8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887, 1762328, 14866737}, FieldElement{-18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421, 27914454, 4383652}, }, { FieldElement{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, FieldElement{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, FieldElement{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, }, { FieldElement{14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454, -33154098, 2381726}, FieldElement{-7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005, -32300832, 15351955}, FieldElement{27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515, 29551813, 10109425}, }, }, { { FieldElement{-13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556, 10092783, -4764171}, FieldElement{27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538, -17810127, 12803510}, FieldElement{17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194, 18016357, 4397660}, }, { FieldElement{-10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525, -17477504, 982639}, FieldElement{29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128, -21047696, 9934963}, FieldElement{5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895, -30123922, -10897950}, }, { FieldElement{-27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697, -13338309, 5500568}, FieldElement{12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343, 10874051, 13524335}, FieldElement{25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568, -22528059, 5376628}, }, { FieldElement{-26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443, 4535768, 1569007}, FieldElement{-2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290, 31848280, 12543772}, FieldElement{-22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731, 7718482, 14474653}, }, { FieldElement{2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665, 24316168, -5253567}, FieldElement{13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532, -20729456, 8321686}, FieldElement{21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838, -9984458, 608372}, }, { FieldElement{-13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577, 27229399, 23887}, FieldElement{-23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308, -1633405, 16678954}, FieldElement{-29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045, -17169265, 4904953}, }, { FieldElement{24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880, 2128236, -4326833}, FieldElement{-16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033, -6882542, -2986532}, FieldElement{-22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829, 15736322, 4143876}, }, { FieldElement{2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663, 23527084, -16458268}, FieldElement{33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881, -15188911, -14416214}, FieldElement{1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868, -4774191, -16323038}, }, }, { { FieldElement{6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732, 7390890, 2759800}, FieldElement{4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057, 1244380, -12919645}, FieldElement{-4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236, 15886429, 16489664}, }, { FieldElement{1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369, -30606455, -712933}, FieldElement{-25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947, -30836462, 5113182}, FieldElement{-17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386, 13847711, 5387222}, }, { FieldElement{-18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786, -19600662, 10370991}, FieldElement{20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092, 32232924, 16763880}, FieldElement{9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506, 3140038, -16510092}, }, { FieldElement{-16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613, -28774454, 366295}, FieldElement{19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113, 719605, 11671788}, FieldElement{8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516, 27000813, -10195553}, }, { FieldElement{-15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097, 6750977, -14521026}, FieldElement{11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122, 8169720, 16220347}, FieldElement{-18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664, -5990708, -14166033}, }, { FieldElement{-23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284, 2655861, 1738395}, FieldElement{-27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336, -19087449, -11005278}, FieldElement{1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890}, }, { FieldElement{32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473, 17789017, -3395995}, FieldElement{-30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233, 30460520, 1052596}, FieldElement{-11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359, 3179268, -9478891}, }, { FieldElement{31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777, -16411740, 19072640, -9511060}, FieldElement{11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017, 473099, 5040608}, FieldElement{-20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092, -19558642, -3131606}, }, }, { { FieldElement{7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149, -27868496, 11538389}, FieldElement{-19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702, -5676054, 5797016}, FieldElement{-11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574, -2369172, -5877341}, }, { FieldElement{-22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199, 15123619, 10811505}, FieldElement{14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356, -28886779, -11974553}, FieldElement{-28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855, 4714547, -9600655}, }, { FieldElement{15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832, -11745876, 12340220}, FieldElement{12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152, 15370987, 9608631}, FieldElement{-4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074, -28210621, -8814099}, }, { FieldElement{26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697, 20571223, 8420556}, FieldElement{14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406, -21574435, -12476749}, FieldElement{236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136, 15069930}, }, { FieldElement{1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229, -30663140, -2331391}, FieldElement{5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378, -33069337, 9234253}, FieldElement{20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587, 18979186, 13396066}, }, { FieldElement{24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782, 33514650, 7021958}, FieldElement{-11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677, -21480480, 12868082}, FieldElement{-28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500, -12455797, -8089383}, }, { FieldElement{-30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937, -15233648, 5540521}, FieldElement{-11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984, -16128528, -14962807}, FieldElement{23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185, -11513277, -15205948}, }, { FieldElement{9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127, -19179614, 5867134}, FieldElement{-32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263, -29749703, -16108455}, FieldElement{27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073, -19526700, 7734629}, }, }, { { FieldElement{-8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626, 18549497, 15302069}, FieldElement{-32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461, -8872242, 8424746}, FieldElement{24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917, -11284482, -828919}, }, { FieldElement{11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461, -5066034, 16498837}, FieldElement{8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238, 6536641, 10543906}, FieldElement{-28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574, -27235709, 8876771}, }, { FieldElement{-25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474, -604426, -9039817}, FieldElement{10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394, 3084098}, FieldElement{10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151, -30233575, 15272409}, }, { FieldElement{-12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138, -25014757, 1950504}, FieldElement{-26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532, 15341279, 8373727}, FieldElement{28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602, -2878207, 15190420}, }, { FieldElement{-32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393, -26033313, -6875003}, FieldElement{-1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594, -16247779, -12154742, 6048605}, FieldElement{-30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384}, }, { FieldElement{-26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150, 20470157, -16398701}, FieldElement{-23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608, 14042978, 5230683}, FieldElement{29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042, -5933891, -12449708}, }, { FieldElement{-3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513, -28539189, 15326563}, FieldElement{-19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988, -20514118, 9168260}, FieldElement{-5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605, 33087103, -9011387}, }, { FieldElement{-19443170, -15512900, -20797467, -12445323, -29824447, 10229461, -27444329, -15000531, -5996870, 15664672}, FieldElement{23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356, 18151676, 13417686}, FieldElement{-24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441, 15271676, -15452665}, }, }, { { FieldElement{11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544, -6921301, -13440182}, FieldElement{-31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997, 12215110, 12028277}, FieldElement{14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780, -16900089, -655628}, }, { FieldElement{-4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009, 23973261, -12684474}, FieldElement{-26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951, 32013174, -10103539}, FieldElement{-25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752, 4425632, -837822}, }, { FieldElement{-10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462, 4725005, 14044970}, FieldElement{19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784, -19522291, -16109756}, FieldElement{-24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106, 9282262, 10282508}, }, { FieldElement{-26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215, 5542595, -10702683}, FieldElement{-10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761, -18093885, 10114655}, FieldElement{-20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146, 25953725, -106158}, }, { FieldElement{-4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296, -3315279, 12831125}, FieldElement{-15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196, 7381791, -2421839}, FieldElement{-20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724, -15362489, 12339664}, }, { FieldElement{27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922, 25091167, 14856294}, FieldElement{-18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493, -22182473, -9012899}, FieldElement{-11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390, 30146206, 9142070}, }, { FieldElement{3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384, -8237858, 4171294}, FieldElement{-15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949, 345228, -5462949}, FieldElement{-21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231, -16253183, -13582083}, }, { FieldElement{31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657, 28012650, -16405420}, FieldElement{-5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057, -8867157, 3507940}, FieldElement{29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267, -9164929, 6580396}, }, }, { { FieldElement{-12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846, -2095802, 9304567}, FieldElement{20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617, 5289421, -477127}, FieldElement{-16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094, 26939669, -3752294}, }, { FieldElement{-12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559, -3698806, 117887}, FieldElement{22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056, -23319780, 541964}, FieldElement{16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829, -13337066, -13552195}, }, { FieldElement{9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351, 690426, 14876244}, FieldElement{24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348, -22380984, 6618999}, FieldElement{-1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328, 32239829, -5652762}, }, { FieldElement{-18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059, 32779359, 5095274}, FieldElement{-33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724, 21639561, -2630236}, FieldElement{-16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535, 17874574, 558605}, }, { FieldElement{-13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151, 2085892, 5119761}, FieldElement{-22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614, -31999993, -5759884}, FieldElement{-6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145, -22351378, 12961482}, }, { FieldElement{-24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996, -30194652, -5159638}, FieldElement{-11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275, 7589640, 8945490}, FieldElement{-32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180, 24099109, -14456170}, }, { FieldElement{5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025, -6231896, -10280736}, FieldElement{10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898, -3363451, -6441124}, FieldElement{-17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168, -13866408, 7421392}, }, { FieldElement{8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252, 28826358, -4123029}, FieldElement{6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124, 13746021, -1742048}, FieldElement{28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524, 4771362, -8419958}, }, }, { { FieldElement{24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695, 3569627, 11342593}, FieldElement{26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608, 7325975, -14801071}, FieldElement{-11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390, -17646694, -8186692}, }, { FieldElement{11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664, 9280358, -3973687}, FieldElement{-160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901, -11181622, -15545091, 4387441}, FieldElement{-20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137, 20617071, -7482001}, }, { FieldElement{-938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822, 24345683, 10325460}, FieldElement{-19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689, 4766743, 3552007}, FieldElement{-21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909, 10988822, -3994762}, }, { FieldElement{15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343, -8295852, 13296005}, FieldElement{-9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054, -30000824, 12074674}, FieldElement{4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716, 29832613, -16391035}, }, { FieldElement{7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297, -27122660, 13101590}, FieldElement{-2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593, -30356070, -4190957}, FieldElement{-30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896, 19568978, 9628812}, }, { FieldElement{33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839, -6291786, 3437740}, FieldElement{-18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104, 7463304, 4176122}, FieldElement{-27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751, 24216882, 5944158}, }, { FieldElement{8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796, 11632993, 5847885}, FieldElement{26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194, -9727230, 4782140}, FieldElement{19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911, 6358847, -1873857}, }, { FieldElement{801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480, -13538503, 1387155}, FieldElement{19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355, -21866831, 11835260}, FieldElement{19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, -26560550, 5052483}, }, }, { { FieldElement{-3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185, 12228557, -7003677}, FieldElement{32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564, -6114803, 8653815}, FieldElement{22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875, 28483275, 2841751}, }, { FieldElement{-16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658, 19932058, -12739203}, FieldElement{-11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134, -4777469, -13910208}, FieldElement{1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705, -14013818, 3093230}, }, { FieldElement{16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225, -24049421, -6691850}, FieldElement{-21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618, -21652117, -16739389}, FieldElement{-9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968}, }, { FieldElement{-11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601, -25578460, -16240689}, FieldElement{14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, -6443880}, FieldElement{5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128, -5652273, -3050304}, }, { FieldElement{30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496, -27999779, 1803632}, FieldElement{-3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514, -21405489, 7047412}, FieldElement{20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601, -32343828, -10257566}, }, { FieldElement{-20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640, -21679658, 2288038}, FieldElement{-26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692, -24819617, 12570232}, FieldElement{-1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680, -11974704, 4724943}, }, { FieldElement{17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932, -29576300, 1903856}, FieldElement{23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296, 26955097, 14109738}, FieldElement{15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562, 31960942, 11934971}, }, { FieldElement{-27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028, 10491392, 1379718}, FieldElement{-13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658, 21432314, 12180697}, FieldElement{-11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540, -10301319, -13872883}, }, }, { { FieldElement{5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231, 26128231, 6032912}, FieldElement{-26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894, -25875034, -10437358}, FieldElement{3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164, 12376617, 3188849}, }, { FieldElement{29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113, -16109234, -9852307}, FieldElement{-14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669, 18640741, -960977}, FieldElement{-6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430, 10530747, 1053335}, }, { FieldElement{-29265967, -14186805, -13538216, -12117373, -19457059, -10655384, -31462369, -2948985, 24018831, 15026644}, FieldElement{-22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497, -2314791, -15145616}, FieldElement{-27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899, -23166419, -2531735}, }, { FieldElement{-21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922, -5070217, 726099}, FieldElement{29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461, 30007388, -15823341}, FieldElement{-936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848, 4555336}, }, { FieldElement{-23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696, -11985298, 12422646}, FieldElement{31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706, 29120153, 13924425}, FieldElement{-17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700, 7240931, -237388}, }, { FieldElement{-31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483, 3293637, -15551743}, FieldElement{-16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547, 12796905, -6335822}, FieldElement{-8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836, 3222231, -11160462}, }, { FieldElement{18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234, -7550776, 2484985}, FieldElement{9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812, -19802075, -3034702}, FieldElement{-22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966, -30097688, -10618797}, }, { FieldElement{21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497, -7360503, -4109293}, FieldElement{27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276, -23659143, -8132100}, FieldElement{19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329, 13243957, 8709688}, }, }, { { FieldElement{12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734, 5150968, 7274186}, FieldElement{2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058, 31021603, -9793610}, FieldElement{-2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465, 15067285, -14147707}, }, { FieldElement{7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586, -19379462, -12403220}, FieldElement{915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997, -7220461, 16527025}, FieldElement{32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992, 23834301, 6588044}, }, { FieldElement{32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107, -20314580, -1305992}, FieldElement{-4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281, 1976123, -7249027}, FieldElement{21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252, 12331345, -8237197}, }, { FieldElement{8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970, 10008136, -4667901}, FieldElement{31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089, 8684155, -10532952}, FieldElement{19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921, 31316348, 14219878}, }, { FieldElement{-28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390}, FieldElement{32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782, -7957600, -14435730}, FieldElement{2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130, 28346258, 1994730}, }, { FieldElement{-19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894, 22628102, 8115180}, FieldElement{-30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160, -9943017, 930272}, FieldElement{-15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970, -22765376, -10650715}, }, { FieldElement{-22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018, -16554220, -1867018, 8398970}, FieldElement{-31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273, 18009408, -15772772}, FieldElement{-17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419, 19288549, 1325865}, }, { FieldElement{15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146, 33166107, -8042750}, FieldElement{20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715, 2213263, -13878373}, FieldElement{32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134, -5766928, 8371348}, }, }, { { FieldElement{9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132, -26442943, 10486144}, FieldElement{-22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596, -23921530, -11455195}, FieldElement{5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541, 19985175, -3436086}, }, { FieldElement{-13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297, 65030, 8370684}, FieldElement{-8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164, 12743482, -9800518}, FieldElement{-2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569, 18800704, 255233}, }, { FieldElement{-5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, -14753793}, FieldElement{-2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390, -1524053, 2055794}, FieldElement{580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389, -30021019, 7394435}, }, { FieldElement{23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205, -4821741, 14799921}, FieldElement{13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856, -9056018, 7402518}, FieldElement{2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352, 8205061, 1607563}, }, { FieldElement{14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958, 30019587, -9029278}, FieldElement{-27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093, 9944378, 8024}, FieldElement{4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085, -8142388, 5640030}, }, { FieldElement{10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564, 15219798, -14327783}, FieldElement{27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195, -18342183, 9742717}, FieldElement{6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155, 1994844}, }, { FieldElement{14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803, 24319929, -6446333}, FieldElement{16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049, -30102368, -4739048}, FieldElement{22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366, 21880021, -12250760}, }, { FieldElement{-4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729, 8840445, 4957760}, FieldElement{-15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072, -14796503, 5005757}, FieldElement{-2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326, -16395286, -2176112}, }, }, { { FieldElement{-19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104, 22208662, 2000468}, FieldElement{3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527, -3691214, -7414184}, FieldElement{10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332, -3132688, 16400289}, }, { FieldElement{15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580, 26894937, 9132066}, FieldElement{24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452, -6817084, -2692882}, FieldElement{13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511, -4688006, 2364226}, }, { FieldElement{16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457, 15445875, -7798101}, FieldElement{29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540, -278050, -15759279}, FieldElement{-6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290, -29828287, -10815811}, }, { FieldElement{27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179, 17293797, 960709}, FieldElement{20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122, -19384511, 7639714}, FieldElement{-2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750, 29994677, -15808121}, }, { FieldElement{9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782, -31184575, 709464}, FieldElement{12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874, 16102007, 13205847}, FieldElement{13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972, 10151379, 10394400}, }, { FieldElement{4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039, -33302334, 8934414}, FieldElement{-15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094, -11536886, 11721158}, FieldElement{17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153, -9205489, -1280045}, }, { FieldElement{-461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429, 6108462, -6183415}, FieldElement{-5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331, -26898490, -7867459}, FieldElement{-31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095, 7592688, -14992079}, }, { FieldElement{21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833, -28256052, 4298412}, FieldElement{-20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194, 13717174, 10805743}, FieldElement{-14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609, -26938930, -5863836}, }, }, { { FieldElement{12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704, -4381056, 9882022}, FieldElement{18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879, -23967430, -3299429}, FieldElement{-6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110, -2403099, 5276065}, }, { FieldElement{30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982, 1449224, 13082861}, FieldElement{10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, -21016438, -8202000}, FieldElement{-33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814, -10300080, -11060101}, }, { FieldElement{32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008, -22664288, 6904815}, FieldElement{29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096, -29003639, -6657642}, FieldElement{10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370, -25584551, 5181966}, }, { FieldElement{25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922, -2322852, -12388574}, FieldElement{-21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087, 20603771, -6561742}, FieldElement{-18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390, 4662781, 7820689}, }, { FieldElement{12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924, 16136752, 15264020}, FieldElement{-10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822, 19012087, 3772772}, FieldElement{3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884, 20527771, 12988982}, }, { FieldElement{-14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943, 3299665, -12424953}, FieldElement{-16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331, -25583147, 8991218}, FieldElement{-17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950, -30242287, 1507265}, }, { FieldElement{29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391, 14606362, -10647073}, FieldElement{-3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487, 4170404, -2085325}, FieldElement{-11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000, -14276837, -8400798}, }, { FieldElement{-4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092, 13240845, 10965870}, FieldElement{-7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411, 29514390, 4302863}, FieldElement{-13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373, 17846988, -13971927}, }, }, { { FieldElement{-2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789, -5222701, 12650267}, FieldElement{-9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293, -19134326, 10958663}, FieldElement{22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455, -25083830, 4271862}, }, { FieldElement{-25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529, -32526221, 8469673}, FieldElement{15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372, 24154791, -9460943}, FieldElement{15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104, 24913809, 9815020}, }, { FieldElement{-4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769, 18735128, 9466238}, FieldElement{11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103, -22728655, 16199064}, FieldElement{14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699, 30801119, 2164795}, }, { FieldElement{15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269, -13492807, 1268052}, FieldElement{-10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221, -17055369, 3565904}, FieldElement{29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713, -27162222, -14030531}, }, { FieldElement{-13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423, 2244111, -14001979}, FieldElement{-5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800, 13491506, 4641841}, FieldElement{10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242, 14476989, -12767431}, }, { FieldElement{10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259, -27912810, 12651324}, FieldElement{-31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, -3148940}, FieldElement{10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694, 13216206, 14842320}, }, { FieldElement{-15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824, -27434397, 9900184}, FieldElement{14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406, -7051866, -8040114}, FieldElement{30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635, 9524356, -7018878}, }, { FieldElement{12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483, 15663516, 4035784}, FieldElement{-2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334, -22258478, 4659091}, FieldElement{-16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997, -2178256, -13455585}, }, }, { { FieldElement{-8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095, 23440562, -290208}, FieldElement{10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483, -16571960, -7442864}, FieldElement{17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594, -3646624, 3898661}, }, { FieldElement{7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530, 21831162, 1245233}, FieldElement{26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035, -30402091, -16716212}, FieldElement{-12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, -22338025, 13987525}, }, { FieldElement{-24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639, -7469781, -2858068}, FieldElement{9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245, -14581012, 4091397}, FieldElement{-8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163, 29077877, -14741988}, }, { FieldElement{5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881, -20017847, 2357889}, FieldElement{32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908, 5727338, 189038}, FieldElement{14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115, -25888931, -14884697}, }, { FieldElement{20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781, 13913677, -5137875}, FieldElement{-25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180, 12878652, 8511905}, FieldElement{-25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974, 5568676, -3127656}, }, { FieldElement{11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373, -14395196, 8070818}, FieldElement{27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306, -11552749, -1028714}, FieldElement{10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853, -27493162, 15431203}, }, { FieldElement{20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142, -15056790, -7935931}, FieldElement{-30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766, -3356550, 9594024}, FieldElement{-23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290, 13352335, -10977084}, }, { FieldElement{-1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482, -13215537, -319204}, FieldElement{20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870, -22750759, 14523817}, FieldElement{27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494, -30172742, -4805667}, }, }, { { FieldElement{11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740, -27727044, 11358504}, FieldElement{-12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336, -26123651, 4985768}, FieldElement{-19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114, -19414307, -15621255}, }, { FieldElement{6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005, -1691065, -9004790}, FieldElement{1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723, -16796596, -5031438}, FieldElement{-22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978, -99853, -10237333}, }, { FieldElement{17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976, -29260363, -5511971}, FieldElement{31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247, 4882242, -10626905}, FieldElement{29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828, -5190932, -4162409}, }, { FieldElement{12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697, 330070, -3659409}, FieldElement{6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892, -271295, 12071499}, FieldElement{-8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675, -5159697, 3829363}, }, { FieldElement{28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787, 26333140, 14267664}, FieldElement{-11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488, -21761224, 8930324}, FieldElement{-21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911, -26491501, -16408940}, }, { FieldElement{13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254, -15943699, 13814990}, FieldElement{-17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833, -1956526, -1776914}, FieldElement{-25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135, -18685978, 4578290}, }, { FieldElement{24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919, 21964432, 8235257}, FieldElement{-6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206, 13006806, 2355433}, FieldElement{-16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366, 1141648, -12796236}, }, { FieldElement{-12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972, 32674895, 13715045}, FieldElement{11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212, -28740881, -15642093}, FieldElement{-1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794, -27245943, 4383347}, }, }, { { FieldElement{-28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449, 27193557, 6245191}, FieldElement{-15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507}, FieldElement{-12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092, -29571492, -3635906}, }, { FieldElement{3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320, 5611860, 8164018}, FieldElement{-16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289, 5773085, -8422109}, FieldElement{-23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320, 31632953, 190926}, }, { FieldElement{-24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564, -25341555, -3627528}, FieldElement{8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005, -1672488, 827625}, FieldElement{-32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036, -24878478, 1541286}, }, { FieldElement{2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481, 20456845, -1885033}, FieldElement{27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058, 29439641, 15138866}, FieldElement{21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163, 7779328, 109896}, }, { FieldElement{30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118, 23177719, -554075}, FieldElement{26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492, 4439158, -13279347}, FieldElement{-22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527, -17717757, -5461437}, }, { FieldElement{-5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225, 8550082, -15114165}, FieldElement{-18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739, -23260460, -8428588}, FieldElement{-32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482, -21902570, 1494193}, }, { FieldElement{-19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112, 8742704, 12967017}, FieldElement{-28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896, -29903758, 15553883}, FieldElement{21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274, 19375923, -12647961}, }, { FieldElement{8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716, 2862653, 9455043}, FieldElement{29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080, 15511449, 4789663}, FieldElement{-20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893, 23513200, 16652362}, }, }, { { FieldElement{-33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300, -18319198, 10212860}, FieldElement{2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940, -9988298, -12506466}, FieldElement{-24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440, -2499677, -16710063}, }, { FieldElement{-26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300, 2719757, 4940997}, FieldElement{-1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463, 26699843, 5276295}, FieldElement{-13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635, -15452774, 7159369}, }, { FieldElement{9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176, 22477218, -8403385}, FieldElement{18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995, -22548173, 9334109}, FieldElement{2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545, -22587149, 536906}, }, { FieldElement{4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, -15420424}, FieldElement{-19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950, 6378260, 699185}, FieldElement{7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155, -5045064, -13373962}, }, { FieldElement{-7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840, -3918636, -9669325}, FieldElement{10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568, -21786507, 5427593}, FieldElement{696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720, 19236243, 12477404}, }, { FieldElement{-11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504, -23169516, 7733644}, FieldElement{17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171, 10322027, 15313801}, FieldElement{26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982, -24449242, 10890804}, }, { FieldElement{-31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931, 25180797, -5334884}, FieldElement{-586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883, 316878, 13820577}, FieldElement{-9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054, 30696930, -3712849}, }, { FieldElement{32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397, -32349517, 7392473}, FieldElement{-8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995, 25112947, -2926644}, FieldElement{-2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194, 5537438, -13914319}, }, }, { { FieldElement{-11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667, 31234590, 6090599}, FieldElement{-9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753, -6970405, -9034768}, FieldElement{-27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646, 20650474, 1804084}, }, { FieldElement{-27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713, 27842616, -202328}, FieldElement{-15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, -11375082, 12714369}, FieldElement{20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546, -19733229, 12796920}, }, { FieldElement{12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495, -12899438, 3480665, -15182815}, FieldElement{-32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875, -33374054, 2771025}, FieldElement{-21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226, -24552282, 15673397}, }, { FieldElement{-20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254, 3727144, -12934448}, FieldElement{6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683, 31123697, -10958981}, FieldElement{30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260, -16432438, 9648165}, }, { FieldElement{32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604, -26008332, -11377501}, FieldElement{17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639, 2662509, -16297073}, FieldElement{-1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777, 32247248, -14389861}, }, { FieldElement{14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817, -16027623, -13378845}, FieldElement{-1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137, 17597934, 2346211}, FieldElement{18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352, 3059833, -11782870}, }, { FieldElement{10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586, -33502212, 3592096}, FieldElement{33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897, -982665, -6837803}, FieldElement{-32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704, 26353178, 693168}, }, { FieldElement{30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668, 31375464, 14369965}, FieldElement{-14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839, 17901441, 16011505}, FieldElement{18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240, -16046376, 8764035, 12309598}, }, }, { { FieldElement{5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319, 17544096, -10593782}, FieldElement{5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127, -5565381, 12348900}, FieldElement{-31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295, -10632534, -585479}, }, { FieldElement{-12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050, 30944593, 1130208}, FieldElement{8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540, 23550156, -271232}, FieldElement{17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146, -408818, -137719}, }, { FieldElement{16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936, 3260525, -7166271}, FieldElement{-4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905, -12748722, 2701326}, FieldElement{-8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971, 11329923, 1862132}, }, { FieldElement{14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231, -9037963, -940300}, FieldElement{8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717, -15438168, 11595570}, FieldElement{15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794, -13489462, -4363670}, }, { FieldElement{-2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635, 977108, 699994}, FieldElement{-12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841, -30534533, -14337913}, FieldElement{31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775, 12493932, -5409317}, }, { FieldElement{-25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121, 29375955, 6024730}, FieldElement{842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184, -9940361, 2854096}, FieldElement{-4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770, 12121869, 16648078}, }, { FieldElement{-15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064, 20237806, 2838411}, FieldElement{-19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457, 1068881, -12499905}, FieldElement{-9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053, 12521378, 4845654}, }, { FieldElement{-28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400, -6482306, -12885870}, FieldElement{-23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216, -3113227, 13974498}, FieldElement{12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737, 18895762, 12629579}, }, }, { { FieldElement{14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443, 32195181, 3895677}, FieldElement{10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119, -8982069, 4429647}, FieldElement{-2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895, 18047436, -15281743}, }, { FieldElement{-25173001, -11307165, 29759956, 11776784, -22262383, -15820455, 10993114, -12850837, -17620701, -9408468}, FieldElement{21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431, -29958985, 8773375}, FieldElement{-25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935, -7874389, -13920155}, }, { FieldElement{6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042, -1721788, -2776725}, FieldElement{-12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698, 28408820, 6816612}, FieldElement{-10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702, -10339570, 5067943}, }, { FieldElement{-30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132, 5331210, -10105944}, FieldElement{30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394, 27679908, -1648928}, FieldElement{9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565, 22611444, -12715406}, }, { FieldElement{22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942, 4854859, 6622139}, FieldElement{-8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227, 26404409, 13001963}, FieldElement{-31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720, -15405155, 11020693}, }, { FieldElement{1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163, 28761762, 1406734}, FieldElement{-448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088, 25577411, -13378680}, FieldElement{-24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936, -9368926, 4745410}, }, { FieldElement{-9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852, 10931924, -11931931}, FieldElement{-16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641, -20470770, 13434654}, FieldElement{22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326, 28445307, -5364710}, }, { FieldElement{29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675, 9074234, 1167180}, FieldElement{-26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498, 3843903, 9367684}, FieldElement{-10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684, -139197, 4242895}, }, }, { { FieldElement{22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660, -27417366, 16625501}, FieldElement{-11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725, -27351616, 14247413}, FieldElement{6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061, 27108877, -1180880}, }, { FieldElement{-8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889, -27148451, 981874}, FieldElement{22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780, -10479804, -16197962}, FieldElement{-7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969, -15933690, 3797899}, }, { FieldElement{21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232, 20491983, -8042152}, FieldElement{9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587, 30997318, -6703063}, FieldElement{7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576, 17649998, -250080}, }, { FieldElement{-9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724, -2233253, 7662146}, FieldElement{-17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199, -3174674, 3440183}, FieldElement{-19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835, 4862400, 1133}, }, { FieldElement{-32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861, -30594991, -7379421}, FieldElement{-3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622}, FieldElement{-4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523, -21875062, 13626197}, }, { FieldElement{2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792, 13340839, 15928663}, FieldElement{31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826, -23452306, 5964753}, FieldElement{4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144, 2538215, -7570755}, }, { FieldElement{-9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421, -629256, -15958862}, FieldElement{-26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288, 11659922, -11115118}, FieldElement{26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080, 33100372, -1306171}, }, { FieldElement{15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675, -5931810, -14466380}, FieldElement{16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968, -10735770, -10039824}, FieldElement{28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599, 18036436, 5803270}, }, }, { { FieldElement{-817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332, -6159431, -14117438}, FieldElement{-31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292, -20095739, 11763584}, FieldElement{-594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632, -19773211, -10713562}, }, { FieldElement{30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773, -17020157, 992471}, FieldElement{18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033, -11574335, -10601610}, FieldElement{19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234, 26224780, 16452269}, }, { FieldElement{-30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186, -20533829, 3698650}, FieldElement{14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444, 27394301, 12015369}, FieldElement{19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777, -13259127, -3402461}, }, { FieldElement{30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312, -8550524, -10393462}, FieldElement{-5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654, -4976164, 12651793}, FieldElement{-2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902, 9768698, -2533218}, }, { FieldElement{-24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450, 4940095, 10678226}, FieldElement{18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024, -24372348, 16582019}, FieldElement{-15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560, -11003761, 7989037}, }, { FieldElement{31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206, -19686113, -14800171}, FieldElement{-17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713, 28550068, -6857132}, FieldElement{-28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038, 1155602, 5988841}, }, { FieldElement{21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481, 24618407, 8283181}, FieldElement{-33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928, 1466169, 10740210}, FieldElement{-1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719, -32164649, -15327040}, }, { FieldElement{3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507, -3260321, -573935}, FieldElement{24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372, -7380369, -6144105}, FieldElement{-28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463, -14453128, -1625486, -6494814}, }, }, { { FieldElement{793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251, -9906200, -621852}, FieldElement{5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826, -6171428, -15186581}, FieldElement{-4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238, -1558923, -9863646}, }, { FieldElement{10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338, -30581476, -15757844}, FieldElement{10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496, 24003793, 14264025}, FieldElement{27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525, 13958495, -5732453}, }, { FieldElement{-23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781, 7340521, -15410068}, FieldElement{4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061, -15066784, -10375192}, FieldElement{-17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888, -8843694, 3849921}, }, { FieldElement{-9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955, 5002294, -15550259}, FieldElement{-12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448, -25845716, 12741426}, FieldElement{-5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464, 28834118, -7646072}, }, { FieldElement{-17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841, 20461858, 5491305}, FieldElement{13669248, -16095482, -12481974, -10203039, -14569770, -11893198, -24995986, 11293807, -28588204, -9421832}, FieldElement{28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166, 29867745, -8795943}, }, { FieldElement{-16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392, 22853429, -4012011}, FieldElement{24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887, 12876623, -2112447}, FieldElement{17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397, 16031844, 3723494}, }, { FieldElement{-28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890, 23896954, -4314245}, FieldElement{-20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064, -9919646, -8826859}, FieldElement{28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325, -18051778, -2082915}, }, { FieldElement{16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268, -19715240, 7847707}, FieldElement{10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018, -10020567, 3852848}, FieldElement{-11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110, 29330899, -15076224}, }, }, { { FieldElement{-25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490, -27548796, 12314391}, FieldElement{15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866, 16103996, -3731215}, FieldElement{-23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699, -29815713, -9841101}, }, { FieldElement{23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517, -25205859, 2739713}, FieldElement{21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907, 4931255, 11987849}, FieldElement{-7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388, -30076310, 10117930}, }, { FieldElement{-29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079, 12890019, 15728940}, FieldElement{-21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139, 12885167, 8311031}, FieldElement{-17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730, 1888765, -5435404}, }, { FieldElement{-25817338, -3107312, -13494599, -3182506, 30896459, -13921729, -32251644, -12707869, -19464434, -3340243}, FieldElement{-23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197, 17151279, -9854116}, FieldElement{-24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279, -16866484, 16176525}, }, { FieldElement{-23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426, -28746253, -10197509}, FieldElement{-10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610, 32808310, 1099883}, FieldElement{15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350, 2051441, -15225865}, }, { FieldElement{-3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188, -22686354, 16633660}, FieldElement{4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549, 8402478, -9864273}, FieldElement{-28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072, 17983010, 9967138}, }, { FieldElement{-25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337, 17507396, 3651560}, FieldElement{-10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557, -18553322, -11357135}, FieldElement{2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447, -5605463, -7621941}, }, { FieldElement{-4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066, 17258084, -7977739}, FieldElement{18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008, 26908270, 12150756}, FieldElement{-30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701, -32302074, 16215819}, }, }, { { FieldElement{-6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905, -7503072, -8675347}, FieldElement{-27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080, 21676107, -1943028}, FieldElement{21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466, -3556191, -7913075}, }, { FieldElement{16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336, -18907032, -9662799}, FieldElement{-2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659, 25459437, -4564609}, FieldElement{-25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602, -6432418, -1644817}, }, { FieldElement{-23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658, 6335692, 7249989}, FieldElement{-30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242, 25993170, -12478523}, FieldElement{4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955, 31820368, 15075278}, }, { FieldElement{31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886, -17970238, 12833045}, FieldElement{19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449, -9413939, 14905377}, FieldElement{24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129, 27628530, -7555480}, }, { FieldElement{17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582, -14110875, 15297016}, FieldElement{510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220, 8683221, 2921426}, FieldElement{18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924, 4674690, 13890525}, }, { FieldElement{13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105, 4389687, 288396}, FieldElement{9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628, 23388070, 16052080}, FieldElement{12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979, -14754271, -10812892}, }, { FieldElement{15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844, -28822128, 929275}, FieldElement{11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533, -9371869, -21393143, 2465074}, FieldElement{20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066, 2463391, -4622140}, }, { FieldElement{-16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107, 4003896, 12673717}, FieldElement{-1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726, 7903886, 2348101}, FieldElement{24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159, -28377538, 10048127}, }, }, { { FieldElement{-12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090, -32297756, 15221632}, FieldElement{-26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755, 29769758, 6593415}, FieldElement{-31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678, 30958054, 8292160}, }, { FieldElement{31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186, 26143136, -3148876}, FieldElement{22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433, -3758243, -2304625}, FieldElement{-15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569, -16664475, 8194478}, }, { FieldElement{27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376, 28572286, 3005164}, FieldElement{26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479, -26094821, -13079595}, FieldElement{-7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627, 32208683, -1198248}, }, { FieldElement{-16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842, -27672585, -11539858}, FieldElement{15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429, 15397331, -4130193}, FieldElement{8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021, -27505566, 15087184}, }, { FieldElement{-18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896, 16788528, -5868942}, FieldElement{-1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320, 31322514, -11615635}, FieldElement{21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414, 13040862, -12112948}, }, { FieldElement{11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103, 1613711, 4896935}, FieldElement{-25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045, -23971776, -11267415}, FieldElement{-15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433, -23753030, -8436416}, }, { FieldElement{-7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030, 23097949, -566018}, FieldElement{4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221, -18512313, 2424778}, FieldElement{366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109, -3642553, 12412659}, }, { FieldElement{-24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504, -3141501, 11179385}, FieldElement{18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897, -18684645, -11443503}, FieldElement{476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813, 11052904, 5219329}, }, }, { { FieldElement{20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730, 9014762, -8579056}, FieldElement{-13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280, 8473550, -3256838}, FieldElement{24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821, -24568481, 11788948}, }, { FieldElement{-3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733, -24568470, -1458691}, FieldElement{-15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194, -18513325, 8464118}, FieldElement{-23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612, 33313881, -8370517}, }, { FieldElement{-20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854, -8940735, -5818269}, FieldElement{-6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188, 28358192, -4253904}, FieldElement{-23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016, -5351664, 5596589}, }, { FieldElement{-28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193}, FieldElement{-7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991, -24660491, 3442910}, FieldElement{-30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455, -18585478, 13365930}, }, { FieldElement{-7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186, -9689599, -3031667}, FieldElement{25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784, 15723479, -15163481}, FieldElement{-9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171, 519526, -1235876}, }, { FieldElement{22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967, 16648397, 7605640}, FieldElement{-8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555, -9468848, 4763278}, FieldElement{-21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523, -11356529, 728112}, }, { FieldElement{26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558, -29365436, -5498272}, FieldElement{17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945, 10750447, 10014012}, FieldElement{-10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732, 3424691, 7540221}, }, { FieldElement{30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219, -9244265, 15258046}, FieldElement{13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395, 1062915, -5136345}, FieldElement{-19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497, 32960380, 1459310}, }, }, { { FieldElement{19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885, 18638003, -11174937}, FieldElement{31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354, -6643087, -5442636}, FieldElement{-9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543, -32294889, -6456008}, }, { FieldElement{-2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692, -7852844, -8138429}, FieldElement{-15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588, -9431476, 5203576}, FieldElement{31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524, 31809243, 7347066}, }, { FieldElement{-9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255, 15192876, -2087490}, FieldElement{-12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420, 33473243, -13382104}, FieldElement{33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903, -6135662, 14480053}, }, { FieldElement{31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227, 27595050, 8737275}, FieldElement{-20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604, 26498114, 66511}, FieldElement{22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747, -13327787, -7515095}, }, { FieldElement{-28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437, -17127465, 15115439}, FieldElement{23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096, 8236921, 16492939}, FieldElement{-23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562, 6708380, -6222424}, }, { FieldElement{2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700, 29955601, -11678310}, FieldElement{3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595, -9917575, 6216608}, FieldElement{-32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567, -26767480, 7525079}, }, { FieldElement{-23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495, -19386633, 11994101}, FieldElement{21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258, -7477437, 13381418}, FieldElement{18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247, 28535282, 15779576}, }, { FieldElement{30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730, 9955285, -16303356}, FieldElement{9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399, 20194861, 13380996}, FieldElement{-26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771, 26342023, 10146099}, }, }, { { FieldElement{-26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040, 21612326, -545728}, FieldElement{-13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797, -20856566, 11649658}, FieldElement{-10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064, 33514190, 2333242}, }, { FieldElement{-21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638, 24350578, -13450001}, FieldElement{-4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836, 8317860, 12352766}, FieldElement{18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550, 20712163, 6719373}, }, { FieldElement{26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210, 26224235, -3297458}, FieldElement{-17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610, 18620611, -16428628}, FieldElement{-13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556, -30701573, -16479657}, }, { FieldElement{-23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639, 13735342, 1934062}, FieldElement{25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346, -21277997, 5473616}, FieldElement{31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656, 29111212, -5451014}, }, { FieldElement{24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839, -10295587, 452383}, FieldElement{-25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248, 15766062, 8407814}, FieldElement{-20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953, -8067909, 2276718}, }, { FieldElement{30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219, 22740376, -7303417}, FieldElement{2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383, -15637599, 13295222}, FieldElement{33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972, -4451357, -14669444}, }, { FieldElement{-20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880, 7770569, 9620597}, FieldElement{23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323, -33502340, -14767970}, FieldElement{1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118, 30494170, -11440799}, }, { FieldElement{-5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050, -1684339, -13333647}, FieldElement{13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865, 3353509, 4033511}, FieldElement{-29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127, 27485041, 7356032}, }, }, { { FieldElement{9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015, 28431036, -16771834}, FieldElement{-23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565, 15970762, 4099461}, FieldElement{29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143, 11465739, 8317062}, }, { FieldElement{-25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455, 20969334, -5157516}, FieldElement{-20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888, 11177095, 14989547}, FieldElement{-24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286, -28487508, 9930240}, }, { FieldElement{-17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767, -13403753, 16291481, -5314038}, FieldElement{-33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617, 4368891, 9788741}, FieldElement{16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148, 16250552, -11111103}, }, { FieldElement{-19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807, -30190403, 4782747}, FieldElement{-1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045, 22546403, 437323}, FieldElement{31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016}, }, { FieldElement{-14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284671, -6114373}, FieldElement{15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498, -29380133, 11754228}, FieldElement{-2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556, 22761615, -10134141}, }, { FieldElement{16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393, 32851222, 11717399}, FieldElement{11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633, -1193175, -4030831}, FieldElement{-185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660, -19985279, -3948376}, }, { FieldElement{-32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048, -30772034, -15486313}, FieldElement{-18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879, 10928917, 3011958}, FieldElement{-6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180, 18008031, 10258577}, }, { FieldElement{-22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120, 25127874, 6671743}, FieldElement{29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292, 25838796, 4642684}, FieldElement{-20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640, 18423289, 4177476}, }, }, } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/ed25519_test.go�������������������������������������0000644�0610621�0607500�00000010011�13172163317�024425� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ed25519 import ( "bufio" "bytes" "compress/gzip" "crypto" "crypto/rand" "encoding/hex" "os" "strings" "testing" "golang.org/x/crypto/ed25519/internal/edwards25519" ) type zeroReader struct{} func (zeroReader) Read(buf []byte) (int, error) { for i := range buf { buf[i] = 0 } return len(buf), nil } func TestUnmarshalMarshal(t *testing.T) { pub, _, _ := GenerateKey(rand.Reader) var A edwards25519.ExtendedGroupElement var pubBytes [32]byte copy(pubBytes[:], pub) if !A.FromBytes(&pubBytes) { t.Fatalf("ExtendedGroupElement.FromBytes failed") } var pub2 [32]byte A.ToBytes(&pub2) if pubBytes != pub2 { t.Errorf("FromBytes(%v)->ToBytes does not round-trip, got %x\n", pubBytes, pub2) } } func TestSignVerify(t *testing.T) { var zero zeroReader public, private, _ := GenerateKey(zero) message := []byte("test message") sig := Sign(private, message) if !Verify(public, message, sig) { t.Errorf("valid signature rejected") } wrongMessage := []byte("wrong message") if Verify(public, wrongMessage, sig) { t.Errorf("signature of different message accepted") } } func TestCryptoSigner(t *testing.T) { var zero zeroReader public, private, _ := GenerateKey(zero) signer := crypto.Signer(private) publicInterface := signer.Public() public2, ok := publicInterface.(PublicKey) if !ok { t.Fatalf("expected PublicKey from Public() but got %T", publicInterface) } if !bytes.Equal(public, public2) { t.Errorf("public keys do not match: original:%x vs Public():%x", public, public2) } message := []byte("message") var noHash crypto.Hash signature, err := signer.Sign(zero, message, noHash) if err != nil { t.Fatalf("error from Sign(): %s", err) } if !Verify(public, message, signature) { t.Errorf("Verify failed on signature from Sign()") } } func TestGolden(t *testing.T) { // sign.input.gz is a selection of test cases from // https://ed25519.cr.yp.to/python/sign.input testDataZ, err := os.Open("testdata/sign.input.gz") if err != nil { t.Fatal(err) } defer testDataZ.Close() testData, err := gzip.NewReader(testDataZ) if err != nil { t.Fatal(err) } defer testData.Close() scanner := bufio.NewScanner(testData) lineNo := 0 for scanner.Scan() { lineNo++ line := scanner.Text() parts := strings.Split(line, ":") if len(parts) != 5 { t.Fatalf("bad number of parts on line %d", lineNo) } privBytes, _ := hex.DecodeString(parts[0]) pubKey, _ := hex.DecodeString(parts[1]) msg, _ := hex.DecodeString(parts[2]) sig, _ := hex.DecodeString(parts[3]) // The signatures in the test vectors also include the message // at the end, but we just want R and S. sig = sig[:SignatureSize] if l := len(pubKey); l != PublicKeySize { t.Fatalf("bad public key length on line %d: got %d bytes", lineNo, l) } var priv [PrivateKeySize]byte copy(priv[:], privBytes) copy(priv[32:], pubKey) sig2 := Sign(priv[:], msg) if !bytes.Equal(sig, sig2[:]) { t.Errorf("different signature result on line %d: %x vs %x", lineNo, sig, sig2) } if !Verify(pubKey, msg, sig2) { t.Errorf("signature failed to verify on line %d", lineNo) } } if err := scanner.Err(); err != nil { t.Fatalf("error reading test data: %s", err) } } func BenchmarkKeyGeneration(b *testing.B) { var zero zeroReader for i := 0; i < b.N; i++ { if _, _, err := GenerateKey(zero); err != nil { b.Fatal(err) } } } func BenchmarkSigning(b *testing.B) { var zero zeroReader _, priv, err := GenerateKey(zero) if err != nil { b.Fatal(err) } message := []byte("Hello, world!") b.ResetTimer() for i := 0; i < b.N; i++ { Sign(priv, message) } } func BenchmarkVerification(b *testing.B) { var zero zeroReader pub, priv, err := GenerateKey(zero) if err != nil { b.Fatal(err) } message := []byte("Hello, world!") signature := Sign(priv, message) b.ResetTimer() for i := 0; i < b.N; i++ { Verify(pub, message, signature) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/ed25519/ed25519.go������������������������������������������0000644�0610621�0607500�00000012026�13172163317�023376� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ed25519 implements the Ed25519 signature algorithm. See // https://ed25519.cr.yp.to/. // // These functions are also compatible with the “Ed25519†function defined in // https://tools.ietf.org/html/draft-irtf-cfrg-eddsa-05. package ed25519 // This code is a port of the public domain, “ref10†implementation of ed25519 // from SUPERCOP. import ( "bytes" "crypto" cryptorand "crypto/rand" "crypto/sha512" "errors" "io" "strconv" "golang.org/x/crypto/ed25519/internal/edwards25519" ) const ( // PublicKeySize is the size, in bytes, of public keys as used in this package. PublicKeySize = 32 // PrivateKeySize is the size, in bytes, of private keys as used in this package. PrivateKeySize = 64 // SignatureSize is the size, in bytes, of signatures generated and verified by this package. SignatureSize = 64 ) // PublicKey is the type of Ed25519 public keys. type PublicKey []byte // PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. type PrivateKey []byte // Public returns the PublicKey corresponding to priv. func (priv PrivateKey) Public() crypto.PublicKey { publicKey := make([]byte, PublicKeySize) copy(publicKey, priv[32:]) return PublicKey(publicKey) } // Sign signs the given message with priv. // Ed25519 performs two passes over messages to be signed and therefore cannot // handle pre-hashed messages. Thus opts.HashFunc() must return zero to // indicate the message hasn't been hashed. This can be achieved by passing // crypto.Hash(0) as the value for opts. func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) { if opts.HashFunc() != crypto.Hash(0) { return nil, errors.New("ed25519: cannot sign hashed message") } return Sign(priv, message), nil } // GenerateKey generates a public/private key pair using entropy from rand. // If rand is nil, crypto/rand.Reader will be used. func GenerateKey(rand io.Reader) (publicKey PublicKey, privateKey PrivateKey, err error) { if rand == nil { rand = cryptorand.Reader } privateKey = make([]byte, PrivateKeySize) publicKey = make([]byte, PublicKeySize) _, err = io.ReadFull(rand, privateKey[:32]) if err != nil { return nil, nil, err } digest := sha512.Sum512(privateKey[:32]) digest[0] &= 248 digest[31] &= 127 digest[31] |= 64 var A edwards25519.ExtendedGroupElement var hBytes [32]byte copy(hBytes[:], digest[:]) edwards25519.GeScalarMultBase(&A, &hBytes) var publicKeyBytes [32]byte A.ToBytes(&publicKeyBytes) copy(privateKey[32:], publicKeyBytes[:]) copy(publicKey, publicKeyBytes[:]) return publicKey, privateKey, nil } // Sign signs the message with privateKey and returns a signature. It will // panic if len(privateKey) is not PrivateKeySize. func Sign(privateKey PrivateKey, message []byte) []byte { if l := len(privateKey); l != PrivateKeySize { panic("ed25519: bad private key length: " + strconv.Itoa(l)) } h := sha512.New() h.Write(privateKey[:32]) var digest1, messageDigest, hramDigest [64]byte var expandedSecretKey [32]byte h.Sum(digest1[:0]) copy(expandedSecretKey[:], digest1[:]) expandedSecretKey[0] &= 248 expandedSecretKey[31] &= 63 expandedSecretKey[31] |= 64 h.Reset() h.Write(digest1[32:]) h.Write(message) h.Sum(messageDigest[:0]) var messageDigestReduced [32]byte edwards25519.ScReduce(&messageDigestReduced, &messageDigest) var R edwards25519.ExtendedGroupElement edwards25519.GeScalarMultBase(&R, &messageDigestReduced) var encodedR [32]byte R.ToBytes(&encodedR) h.Reset() h.Write(encodedR[:]) h.Write(privateKey[32:]) h.Write(message) h.Sum(hramDigest[:0]) var hramDigestReduced [32]byte edwards25519.ScReduce(&hramDigestReduced, &hramDigest) var s [32]byte edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced) signature := make([]byte, SignatureSize) copy(signature[:], encodedR[:]) copy(signature[32:], s[:]) return signature } // Verify reports whether sig is a valid signature of message by publicKey. It // will panic if len(publicKey) is not PublicKeySize. func Verify(publicKey PublicKey, message, sig []byte) bool { if l := len(publicKey); l != PublicKeySize { panic("ed25519: bad public key length: " + strconv.Itoa(l)) } if len(sig) != SignatureSize || sig[63]&224 != 0 { return false } var A edwards25519.ExtendedGroupElement var publicKeyBytes [32]byte copy(publicKeyBytes[:], publicKey) if !A.FromBytes(&publicKeyBytes) { return false } edwards25519.FeNeg(&A.X, &A.X) edwards25519.FeNeg(&A.T, &A.T) h := sha512.New() h.Write(sig[:32]) h.Write(publicKey[:]) h.Write(message) var digest [64]byte h.Sum(digest[:0]) var hReduced [32]byte edwards25519.ScReduce(&hReduced, &digest) var R edwards25519.ProjectiveGroupElement var b [32]byte copy(b[:], sig[32:]) edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b) var checkR [32]byte R.ToBytes(&checkR) return bytes.Equal(sig[:32], checkR[:]) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/�������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022604� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/square_amd64.s�����������������������������������0000644�0610621�0607500�00000004004�13172163317�025261� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine #include "const_amd64.h" // func square(out, in *[5]uint64) TEXT ·square(SB),7,$0-16 MOVQ out+0(FP), DI MOVQ in+8(FP), SI MOVQ 0(SI),AX MULQ 0(SI) MOVQ AX,CX MOVQ DX,R8 MOVQ 0(SI),AX SHLQ $1,AX MULQ 8(SI) MOVQ AX,R9 MOVQ DX,R10 MOVQ 0(SI),AX SHLQ $1,AX MULQ 16(SI) MOVQ AX,R11 MOVQ DX,R12 MOVQ 0(SI),AX SHLQ $1,AX MULQ 24(SI) MOVQ AX,R13 MOVQ DX,R14 MOVQ 0(SI),AX SHLQ $1,AX MULQ 32(SI) MOVQ AX,R15 MOVQ DX,BX MOVQ 8(SI),AX MULQ 8(SI) ADDQ AX,R11 ADCQ DX,R12 MOVQ 8(SI),AX SHLQ $1,AX MULQ 16(SI) ADDQ AX,R13 ADCQ DX,R14 MOVQ 8(SI),AX SHLQ $1,AX MULQ 24(SI) ADDQ AX,R15 ADCQ DX,BX MOVQ 8(SI),DX IMUL3Q $38,DX,AX MULQ 32(SI) ADDQ AX,CX ADCQ DX,R8 MOVQ 16(SI),AX MULQ 16(SI) ADDQ AX,R15 ADCQ DX,BX MOVQ 16(SI),DX IMUL3Q $38,DX,AX MULQ 24(SI) ADDQ AX,CX ADCQ DX,R8 MOVQ 16(SI),DX IMUL3Q $38,DX,AX MULQ 32(SI) ADDQ AX,R9 ADCQ DX,R10 MOVQ 24(SI),DX IMUL3Q $19,DX,AX MULQ 24(SI) ADDQ AX,R9 ADCQ DX,R10 MOVQ 24(SI),DX IMUL3Q $38,DX,AX MULQ 32(SI) ADDQ AX,R11 ADCQ DX,R12 MOVQ 32(SI),DX IMUL3Q $19,DX,AX MULQ 32(SI) ADDQ AX,R13 ADCQ DX,R14 MOVQ $REDMASK51,SI SHLQ $13,R8:CX ANDQ SI,CX SHLQ $13,R10:R9 ANDQ SI,R9 ADDQ R8,R9 SHLQ $13,R12:R11 ANDQ SI,R11 ADDQ R10,R11 SHLQ $13,R14:R13 ANDQ SI,R13 ADDQ R12,R13 SHLQ $13,BX:R15 ANDQ SI,R15 ADDQ R14,R15 IMUL3Q $19,BX,DX ADDQ DX,CX MOVQ CX,DX SHRQ $51,DX ADDQ R9,DX ANDQ SI,CX MOVQ DX,R8 SHRQ $51,DX ADDQ R11,DX ANDQ SI,R8 MOVQ DX,R9 SHRQ $51,DX ADDQ R13,DX ANDQ SI,R9 MOVQ DX,AX SHRQ $51,DX ADDQ R15,DX ANDQ SI,AX MOVQ DX,R10 SHRQ $51,DX IMUL3Q $19,DX,DX ADDQ DX,CX ANDQ SI,R10 MOVQ CX,0(DI) MOVQ R8,8(DI) MOVQ R9,16(DI) MOVQ AX,24(DI) MOVQ R10,32(DI) RET ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/mul_amd64.s��������������������������������������0000644�0610621�0607500�00000004766�13172163317�024575� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine #include "const_amd64.h" // func mul(dest, a, b *[5]uint64) TEXT ·mul(SB),0,$16-24 MOVQ dest+0(FP), DI MOVQ a+8(FP), SI MOVQ b+16(FP), DX MOVQ DX,CX MOVQ 24(SI),DX IMUL3Q $19,DX,AX MOVQ AX,0(SP) MULQ 16(CX) MOVQ AX,R8 MOVQ DX,R9 MOVQ 32(SI),DX IMUL3Q $19,DX,AX MOVQ AX,8(SP) MULQ 8(CX) ADDQ AX,R8 ADCQ DX,R9 MOVQ 0(SI),AX MULQ 0(CX) ADDQ AX,R8 ADCQ DX,R9 MOVQ 0(SI),AX MULQ 8(CX) MOVQ AX,R10 MOVQ DX,R11 MOVQ 0(SI),AX MULQ 16(CX) MOVQ AX,R12 MOVQ DX,R13 MOVQ 0(SI),AX MULQ 24(CX) MOVQ AX,R14 MOVQ DX,R15 MOVQ 0(SI),AX MULQ 32(CX) MOVQ AX,BX MOVQ DX,BP MOVQ 8(SI),AX MULQ 0(CX) ADDQ AX,R10 ADCQ DX,R11 MOVQ 8(SI),AX MULQ 8(CX) ADDQ AX,R12 ADCQ DX,R13 MOVQ 8(SI),AX MULQ 16(CX) ADDQ AX,R14 ADCQ DX,R15 MOVQ 8(SI),AX MULQ 24(CX) ADDQ AX,BX ADCQ DX,BP MOVQ 8(SI),DX IMUL3Q $19,DX,AX MULQ 32(CX) ADDQ AX,R8 ADCQ DX,R9 MOVQ 16(SI),AX MULQ 0(CX) ADDQ AX,R12 ADCQ DX,R13 MOVQ 16(SI),AX MULQ 8(CX) ADDQ AX,R14 ADCQ DX,R15 MOVQ 16(SI),AX MULQ 16(CX) ADDQ AX,BX ADCQ DX,BP MOVQ 16(SI),DX IMUL3Q $19,DX,AX MULQ 24(CX) ADDQ AX,R8 ADCQ DX,R9 MOVQ 16(SI),DX IMUL3Q $19,DX,AX MULQ 32(CX) ADDQ AX,R10 ADCQ DX,R11 MOVQ 24(SI),AX MULQ 0(CX) ADDQ AX,R14 ADCQ DX,R15 MOVQ 24(SI),AX MULQ 8(CX) ADDQ AX,BX ADCQ DX,BP MOVQ 0(SP),AX MULQ 24(CX) ADDQ AX,R10 ADCQ DX,R11 MOVQ 0(SP),AX MULQ 32(CX) ADDQ AX,R12 ADCQ DX,R13 MOVQ 32(SI),AX MULQ 0(CX) ADDQ AX,BX ADCQ DX,BP MOVQ 8(SP),AX MULQ 16(CX) ADDQ AX,R10 ADCQ DX,R11 MOVQ 8(SP),AX MULQ 24(CX) ADDQ AX,R12 ADCQ DX,R13 MOVQ 8(SP),AX MULQ 32(CX) ADDQ AX,R14 ADCQ DX,R15 MOVQ $REDMASK51,SI SHLQ $13,R9:R8 ANDQ SI,R8 SHLQ $13,R11:R10 ANDQ SI,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ SI,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ SI,R14 ADDQ R13,R14 SHLQ $13,BP:BX ANDQ SI,BX ADDQ R15,BX IMUL3Q $19,BP,DX ADDQ DX,R8 MOVQ R8,DX SHRQ $51,DX ADDQ R10,DX MOVQ DX,CX SHRQ $51,DX ANDQ SI,R8 ADDQ R12,DX MOVQ DX,R9 SHRQ $51,DX ANDQ SI,CX ADDQ R14,DX MOVQ DX,AX SHRQ $51,DX ANDQ SI,R9 ADDQ BX,DX MOVQ DX,R10 SHRQ $51,DX ANDQ SI,AX IMUL3Q $19,DX,DX ADDQ DX,R8 ANDQ SI,R10 MOVQ R8,0(DI) MOVQ CX,8(DI) MOVQ R9,16(DI) MOVQ AX,24(DI) MOVQ R10,32(DI) RET ����������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/mont25519_amd64.go�������������������������������0000644�0610621�0607500�00000012231�13172163317�025510� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!gccgo,!appengine package curve25519 // These functions are implemented in the .s files. The names of the functions // in the rest of the file are also taken from the SUPERCOP sources to help // people following along. //go:noescape func cswap(inout *[5]uint64, v uint64) //go:noescape func ladderstep(inout *[5][5]uint64) //go:noescape func freeze(inout *[5]uint64) //go:noescape func mul(dest, a, b *[5]uint64) //go:noescape func square(out, in *[5]uint64) // mladder uses a Montgomery ladder to calculate (xr/zr) *= s. func mladder(xr, zr *[5]uint64, s *[32]byte) { var work [5][5]uint64 work[0] = *xr setint(&work[1], 1) setint(&work[2], 0) work[3] = *xr setint(&work[4], 1) j := uint(6) var prevbit byte for i := 31; i >= 0; i-- { for j < 8 { bit := ((*s)[i] >> j) & 1 swap := bit ^ prevbit prevbit = bit cswap(&work[1], uint64(swap)) ladderstep(&work) j-- } j = 7 } *xr = work[1] *zr = work[2] } func scalarMult(out, in, base *[32]byte) { var e [32]byte copy(e[:], (*in)[:]) e[0] &= 248 e[31] &= 127 e[31] |= 64 var t, z [5]uint64 unpack(&t, base) mladder(&t, &z, &e) invert(&z, &z) mul(&t, &t, &z) pack(out, &t) } func setint(r *[5]uint64, v uint64) { r[0] = v r[1] = 0 r[2] = 0 r[3] = 0 r[4] = 0 } // unpack sets r = x where r consists of 5, 51-bit limbs in little-endian // order. func unpack(r *[5]uint64, x *[32]byte) { r[0] = uint64(x[0]) | uint64(x[1])<<8 | uint64(x[2])<<16 | uint64(x[3])<<24 | uint64(x[4])<<32 | uint64(x[5])<<40 | uint64(x[6]&7)<<48 r[1] = uint64(x[6])>>3 | uint64(x[7])<<5 | uint64(x[8])<<13 | uint64(x[9])<<21 | uint64(x[10])<<29 | uint64(x[11])<<37 | uint64(x[12]&63)<<45 r[2] = uint64(x[12])>>6 | uint64(x[13])<<2 | uint64(x[14])<<10 | uint64(x[15])<<18 | uint64(x[16])<<26 | uint64(x[17])<<34 | uint64(x[18])<<42 | uint64(x[19]&1)<<50 r[3] = uint64(x[19])>>1 | uint64(x[20])<<7 | uint64(x[21])<<15 | uint64(x[22])<<23 | uint64(x[23])<<31 | uint64(x[24])<<39 | uint64(x[25]&15)<<47 r[4] = uint64(x[25])>>4 | uint64(x[26])<<4 | uint64(x[27])<<12 | uint64(x[28])<<20 | uint64(x[29])<<28 | uint64(x[30])<<36 | uint64(x[31]&127)<<44 } // pack sets out = x where out is the usual, little-endian form of the 5, // 51-bit limbs in x. func pack(out *[32]byte, x *[5]uint64) { t := *x freeze(&t) out[0] = byte(t[0]) out[1] = byte(t[0] >> 8) out[2] = byte(t[0] >> 16) out[3] = byte(t[0] >> 24) out[4] = byte(t[0] >> 32) out[5] = byte(t[0] >> 40) out[6] = byte(t[0] >> 48) out[6] ^= byte(t[1]<<3) & 0xf8 out[7] = byte(t[1] >> 5) out[8] = byte(t[1] >> 13) out[9] = byte(t[1] >> 21) out[10] = byte(t[1] >> 29) out[11] = byte(t[1] >> 37) out[12] = byte(t[1] >> 45) out[12] ^= byte(t[2]<<6) & 0xc0 out[13] = byte(t[2] >> 2) out[14] = byte(t[2] >> 10) out[15] = byte(t[2] >> 18) out[16] = byte(t[2] >> 26) out[17] = byte(t[2] >> 34) out[18] = byte(t[2] >> 42) out[19] = byte(t[2] >> 50) out[19] ^= byte(t[3]<<1) & 0xfe out[20] = byte(t[3] >> 7) out[21] = byte(t[3] >> 15) out[22] = byte(t[3] >> 23) out[23] = byte(t[3] >> 31) out[24] = byte(t[3] >> 39) out[25] = byte(t[3] >> 47) out[25] ^= byte(t[4]<<4) & 0xf0 out[26] = byte(t[4] >> 4) out[27] = byte(t[4] >> 12) out[28] = byte(t[4] >> 20) out[29] = byte(t[4] >> 28) out[30] = byte(t[4] >> 36) out[31] = byte(t[4] >> 44) } // invert calculates r = x^-1 mod p using Fermat's little theorem. func invert(r *[5]uint64, x *[5]uint64) { var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t [5]uint64 square(&z2, x) /* 2 */ square(&t, &z2) /* 4 */ square(&t, &t) /* 8 */ mul(&z9, &t, x) /* 9 */ mul(&z11, &z9, &z2) /* 11 */ square(&t, &z11) /* 22 */ mul(&z2_5_0, &t, &z9) /* 2^5 - 2^0 = 31 */ square(&t, &z2_5_0) /* 2^6 - 2^1 */ for i := 1; i < 5; i++ { /* 2^20 - 2^10 */ square(&t, &t) } mul(&z2_10_0, &t, &z2_5_0) /* 2^10 - 2^0 */ square(&t, &z2_10_0) /* 2^11 - 2^1 */ for i := 1; i < 10; i++ { /* 2^20 - 2^10 */ square(&t, &t) } mul(&z2_20_0, &t, &z2_10_0) /* 2^20 - 2^0 */ square(&t, &z2_20_0) /* 2^21 - 2^1 */ for i := 1; i < 20; i++ { /* 2^40 - 2^20 */ square(&t, &t) } mul(&t, &t, &z2_20_0) /* 2^40 - 2^0 */ square(&t, &t) /* 2^41 - 2^1 */ for i := 1; i < 10; i++ { /* 2^50 - 2^10 */ square(&t, &t) } mul(&z2_50_0, &t, &z2_10_0) /* 2^50 - 2^0 */ square(&t, &z2_50_0) /* 2^51 - 2^1 */ for i := 1; i < 50; i++ { /* 2^100 - 2^50 */ square(&t, &t) } mul(&z2_100_0, &t, &z2_50_0) /* 2^100 - 2^0 */ square(&t, &z2_100_0) /* 2^101 - 2^1 */ for i := 1; i < 100; i++ { /* 2^200 - 2^100 */ square(&t, &t) } mul(&t, &t, &z2_100_0) /* 2^200 - 2^0 */ square(&t, &t) /* 2^201 - 2^1 */ for i := 1; i < 50; i++ { /* 2^250 - 2^50 */ square(&t, &t) } mul(&t, &t, &z2_50_0) /* 2^250 - 2^0 */ square(&t, &t) /* 2^251 - 2^1 */ square(&t, &t) /* 2^252 - 2^2 */ square(&t, &t) /* 2^253 - 2^3 */ square(&t, &t) /* 2^254 - 2^4 */ square(&t, &t) /* 2^255 - 2^5 */ mul(r, &t, &z11) /* 2^255 - 21 */ } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/ladderstep_amd64.s�������������������������������0000644�0610621�0607500�00000046766�13172163317�026135� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine #include "const_amd64.h" // func ladderstep(inout *[5][5]uint64) TEXT ·ladderstep(SB),0,$296-8 MOVQ inout+0(FP),DI MOVQ 40(DI),SI MOVQ 48(DI),DX MOVQ 56(DI),CX MOVQ 64(DI),R8 MOVQ 72(DI),R9 MOVQ SI,AX MOVQ DX,R10 MOVQ CX,R11 MOVQ R8,R12 MOVQ R9,R13 ADDQ ·_2P0(SB),AX ADDQ ·_2P1234(SB),R10 ADDQ ·_2P1234(SB),R11 ADDQ ·_2P1234(SB),R12 ADDQ ·_2P1234(SB),R13 ADDQ 80(DI),SI ADDQ 88(DI),DX ADDQ 96(DI),CX ADDQ 104(DI),R8 ADDQ 112(DI),R9 SUBQ 80(DI),AX SUBQ 88(DI),R10 SUBQ 96(DI),R11 SUBQ 104(DI),R12 SUBQ 112(DI),R13 MOVQ SI,0(SP) MOVQ DX,8(SP) MOVQ CX,16(SP) MOVQ R8,24(SP) MOVQ R9,32(SP) MOVQ AX,40(SP) MOVQ R10,48(SP) MOVQ R11,56(SP) MOVQ R12,64(SP) MOVQ R13,72(SP) MOVQ 40(SP),AX MULQ 40(SP) MOVQ AX,SI MOVQ DX,CX MOVQ 40(SP),AX SHLQ $1,AX MULQ 48(SP) MOVQ AX,R8 MOVQ DX,R9 MOVQ 40(SP),AX SHLQ $1,AX MULQ 56(SP) MOVQ AX,R10 MOVQ DX,R11 MOVQ 40(SP),AX SHLQ $1,AX MULQ 64(SP) MOVQ AX,R12 MOVQ DX,R13 MOVQ 40(SP),AX SHLQ $1,AX MULQ 72(SP) MOVQ AX,R14 MOVQ DX,R15 MOVQ 48(SP),AX MULQ 48(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 48(SP),AX SHLQ $1,AX MULQ 56(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 48(SP),AX SHLQ $1,AX MULQ 64(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 48(SP),DX IMUL3Q $38,DX,AX MULQ 72(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 56(SP),AX MULQ 56(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 56(SP),DX IMUL3Q $38,DX,AX MULQ 64(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 56(SP),DX IMUL3Q $38,DX,AX MULQ 72(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 64(SP),DX IMUL3Q $19,DX,AX MULQ 64(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 64(SP),DX IMUL3Q $38,DX,AX MULQ 72(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 72(SP),DX IMUL3Q $19,DX,AX MULQ 72(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX ANDQ DX,SI MOVQ CX,R8 SHRQ $51,CX ADDQ R10,CX ANDQ DX,R8 MOVQ CX,R9 SHRQ $51,CX ADDQ R12,CX ANDQ DX,R9 MOVQ CX,AX SHRQ $51,CX ADDQ R14,CX ANDQ DX,AX MOVQ CX,R10 SHRQ $51,CX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,80(SP) MOVQ R8,88(SP) MOVQ R9,96(SP) MOVQ AX,104(SP) MOVQ R10,112(SP) MOVQ 0(SP),AX MULQ 0(SP) MOVQ AX,SI MOVQ DX,CX MOVQ 0(SP),AX SHLQ $1,AX MULQ 8(SP) MOVQ AX,R8 MOVQ DX,R9 MOVQ 0(SP),AX SHLQ $1,AX MULQ 16(SP) MOVQ AX,R10 MOVQ DX,R11 MOVQ 0(SP),AX SHLQ $1,AX MULQ 24(SP) MOVQ AX,R12 MOVQ DX,R13 MOVQ 0(SP),AX SHLQ $1,AX MULQ 32(SP) MOVQ AX,R14 MOVQ DX,R15 MOVQ 8(SP),AX MULQ 8(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 8(SP),AX SHLQ $1,AX MULQ 16(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 8(SP),AX SHLQ $1,AX MULQ 24(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 8(SP),DX IMUL3Q $38,DX,AX MULQ 32(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 16(SP),AX MULQ 16(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 16(SP),DX IMUL3Q $38,DX,AX MULQ 24(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 16(SP),DX IMUL3Q $38,DX,AX MULQ 32(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 24(SP),DX IMUL3Q $19,DX,AX MULQ 24(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 24(SP),DX IMUL3Q $38,DX,AX MULQ 32(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 32(SP),DX IMUL3Q $19,DX,AX MULQ 32(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX ANDQ DX,SI MOVQ CX,R8 SHRQ $51,CX ADDQ R10,CX ANDQ DX,R8 MOVQ CX,R9 SHRQ $51,CX ADDQ R12,CX ANDQ DX,R9 MOVQ CX,AX SHRQ $51,CX ADDQ R14,CX ANDQ DX,AX MOVQ CX,R10 SHRQ $51,CX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,120(SP) MOVQ R8,128(SP) MOVQ R9,136(SP) MOVQ AX,144(SP) MOVQ R10,152(SP) MOVQ SI,SI MOVQ R8,DX MOVQ R9,CX MOVQ AX,R8 MOVQ R10,R9 ADDQ ·_2P0(SB),SI ADDQ ·_2P1234(SB),DX ADDQ ·_2P1234(SB),CX ADDQ ·_2P1234(SB),R8 ADDQ ·_2P1234(SB),R9 SUBQ 80(SP),SI SUBQ 88(SP),DX SUBQ 96(SP),CX SUBQ 104(SP),R8 SUBQ 112(SP),R9 MOVQ SI,160(SP) MOVQ DX,168(SP) MOVQ CX,176(SP) MOVQ R8,184(SP) MOVQ R9,192(SP) MOVQ 120(DI),SI MOVQ 128(DI),DX MOVQ 136(DI),CX MOVQ 144(DI),R8 MOVQ 152(DI),R9 MOVQ SI,AX MOVQ DX,R10 MOVQ CX,R11 MOVQ R8,R12 MOVQ R9,R13 ADDQ ·_2P0(SB),AX ADDQ ·_2P1234(SB),R10 ADDQ ·_2P1234(SB),R11 ADDQ ·_2P1234(SB),R12 ADDQ ·_2P1234(SB),R13 ADDQ 160(DI),SI ADDQ 168(DI),DX ADDQ 176(DI),CX ADDQ 184(DI),R8 ADDQ 192(DI),R9 SUBQ 160(DI),AX SUBQ 168(DI),R10 SUBQ 176(DI),R11 SUBQ 184(DI),R12 SUBQ 192(DI),R13 MOVQ SI,200(SP) MOVQ DX,208(SP) MOVQ CX,216(SP) MOVQ R8,224(SP) MOVQ R9,232(SP) MOVQ AX,240(SP) MOVQ R10,248(SP) MOVQ R11,256(SP) MOVQ R12,264(SP) MOVQ R13,272(SP) MOVQ 224(SP),SI IMUL3Q $19,SI,AX MOVQ AX,280(SP) MULQ 56(SP) MOVQ AX,SI MOVQ DX,CX MOVQ 232(SP),DX IMUL3Q $19,DX,AX MOVQ AX,288(SP) MULQ 48(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 200(SP),AX MULQ 40(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 200(SP),AX MULQ 48(SP) MOVQ AX,R8 MOVQ DX,R9 MOVQ 200(SP),AX MULQ 56(SP) MOVQ AX,R10 MOVQ DX,R11 MOVQ 200(SP),AX MULQ 64(SP) MOVQ AX,R12 MOVQ DX,R13 MOVQ 200(SP),AX MULQ 72(SP) MOVQ AX,R14 MOVQ DX,R15 MOVQ 208(SP),AX MULQ 40(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 208(SP),AX MULQ 48(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 208(SP),AX MULQ 56(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 208(SP),AX MULQ 64(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 208(SP),DX IMUL3Q $19,DX,AX MULQ 72(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 216(SP),AX MULQ 40(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 216(SP),AX MULQ 48(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 216(SP),AX MULQ 56(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 216(SP),DX IMUL3Q $19,DX,AX MULQ 64(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 216(SP),DX IMUL3Q $19,DX,AX MULQ 72(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 224(SP),AX MULQ 40(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 224(SP),AX MULQ 48(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 280(SP),AX MULQ 64(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 280(SP),AX MULQ 72(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 232(SP),AX MULQ 40(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 288(SP),AX MULQ 56(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 288(SP),AX MULQ 64(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 288(SP),AX MULQ 72(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX MOVQ CX,R8 SHRQ $51,CX ANDQ DX,SI ADDQ R10,CX MOVQ CX,R9 SHRQ $51,CX ANDQ DX,R8 ADDQ R12,CX MOVQ CX,AX SHRQ $51,CX ANDQ DX,R9 ADDQ R14,CX MOVQ CX,R10 SHRQ $51,CX ANDQ DX,AX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,40(SP) MOVQ R8,48(SP) MOVQ R9,56(SP) MOVQ AX,64(SP) MOVQ R10,72(SP) MOVQ 264(SP),SI IMUL3Q $19,SI,AX MOVQ AX,200(SP) MULQ 16(SP) MOVQ AX,SI MOVQ DX,CX MOVQ 272(SP),DX IMUL3Q $19,DX,AX MOVQ AX,208(SP) MULQ 8(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 240(SP),AX MULQ 0(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 240(SP),AX MULQ 8(SP) MOVQ AX,R8 MOVQ DX,R9 MOVQ 240(SP),AX MULQ 16(SP) MOVQ AX,R10 MOVQ DX,R11 MOVQ 240(SP),AX MULQ 24(SP) MOVQ AX,R12 MOVQ DX,R13 MOVQ 240(SP),AX MULQ 32(SP) MOVQ AX,R14 MOVQ DX,R15 MOVQ 248(SP),AX MULQ 0(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 248(SP),AX MULQ 8(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 248(SP),AX MULQ 16(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 248(SP),AX MULQ 24(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 248(SP),DX IMUL3Q $19,DX,AX MULQ 32(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 256(SP),AX MULQ 0(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 256(SP),AX MULQ 8(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 256(SP),AX MULQ 16(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 256(SP),DX IMUL3Q $19,DX,AX MULQ 24(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 256(SP),DX IMUL3Q $19,DX,AX MULQ 32(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 264(SP),AX MULQ 0(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 264(SP),AX MULQ 8(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 200(SP),AX MULQ 24(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 200(SP),AX MULQ 32(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 272(SP),AX MULQ 0(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 208(SP),AX MULQ 16(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 208(SP),AX MULQ 24(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 208(SP),AX MULQ 32(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX MOVQ CX,R8 SHRQ $51,CX ANDQ DX,SI ADDQ R10,CX MOVQ CX,R9 SHRQ $51,CX ANDQ DX,R8 ADDQ R12,CX MOVQ CX,AX SHRQ $51,CX ANDQ DX,R9 ADDQ R14,CX MOVQ CX,R10 SHRQ $51,CX ANDQ DX,AX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,DX MOVQ R8,CX MOVQ R9,R11 MOVQ AX,R12 MOVQ R10,R13 ADDQ ·_2P0(SB),DX ADDQ ·_2P1234(SB),CX ADDQ ·_2P1234(SB),R11 ADDQ ·_2P1234(SB),R12 ADDQ ·_2P1234(SB),R13 ADDQ 40(SP),SI ADDQ 48(SP),R8 ADDQ 56(SP),R9 ADDQ 64(SP),AX ADDQ 72(SP),R10 SUBQ 40(SP),DX SUBQ 48(SP),CX SUBQ 56(SP),R11 SUBQ 64(SP),R12 SUBQ 72(SP),R13 MOVQ SI,120(DI) MOVQ R8,128(DI) MOVQ R9,136(DI) MOVQ AX,144(DI) MOVQ R10,152(DI) MOVQ DX,160(DI) MOVQ CX,168(DI) MOVQ R11,176(DI) MOVQ R12,184(DI) MOVQ R13,192(DI) MOVQ 120(DI),AX MULQ 120(DI) MOVQ AX,SI MOVQ DX,CX MOVQ 120(DI),AX SHLQ $1,AX MULQ 128(DI) MOVQ AX,R8 MOVQ DX,R9 MOVQ 120(DI),AX SHLQ $1,AX MULQ 136(DI) MOVQ AX,R10 MOVQ DX,R11 MOVQ 120(DI),AX SHLQ $1,AX MULQ 144(DI) MOVQ AX,R12 MOVQ DX,R13 MOVQ 120(DI),AX SHLQ $1,AX MULQ 152(DI) MOVQ AX,R14 MOVQ DX,R15 MOVQ 128(DI),AX MULQ 128(DI) ADDQ AX,R10 ADCQ DX,R11 MOVQ 128(DI),AX SHLQ $1,AX MULQ 136(DI) ADDQ AX,R12 ADCQ DX,R13 MOVQ 128(DI),AX SHLQ $1,AX MULQ 144(DI) ADDQ AX,R14 ADCQ DX,R15 MOVQ 128(DI),DX IMUL3Q $38,DX,AX MULQ 152(DI) ADDQ AX,SI ADCQ DX,CX MOVQ 136(DI),AX MULQ 136(DI) ADDQ AX,R14 ADCQ DX,R15 MOVQ 136(DI),DX IMUL3Q $38,DX,AX MULQ 144(DI) ADDQ AX,SI ADCQ DX,CX MOVQ 136(DI),DX IMUL3Q $38,DX,AX MULQ 152(DI) ADDQ AX,R8 ADCQ DX,R9 MOVQ 144(DI),DX IMUL3Q $19,DX,AX MULQ 144(DI) ADDQ AX,R8 ADCQ DX,R9 MOVQ 144(DI),DX IMUL3Q $38,DX,AX MULQ 152(DI) ADDQ AX,R10 ADCQ DX,R11 MOVQ 152(DI),DX IMUL3Q $19,DX,AX MULQ 152(DI) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX ANDQ DX,SI MOVQ CX,R8 SHRQ $51,CX ADDQ R10,CX ANDQ DX,R8 MOVQ CX,R9 SHRQ $51,CX ADDQ R12,CX ANDQ DX,R9 MOVQ CX,AX SHRQ $51,CX ADDQ R14,CX ANDQ DX,AX MOVQ CX,R10 SHRQ $51,CX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,120(DI) MOVQ R8,128(DI) MOVQ R9,136(DI) MOVQ AX,144(DI) MOVQ R10,152(DI) MOVQ 160(DI),AX MULQ 160(DI) MOVQ AX,SI MOVQ DX,CX MOVQ 160(DI),AX SHLQ $1,AX MULQ 168(DI) MOVQ AX,R8 MOVQ DX,R9 MOVQ 160(DI),AX SHLQ $1,AX MULQ 176(DI) MOVQ AX,R10 MOVQ DX,R11 MOVQ 160(DI),AX SHLQ $1,AX MULQ 184(DI) MOVQ AX,R12 MOVQ DX,R13 MOVQ 160(DI),AX SHLQ $1,AX MULQ 192(DI) MOVQ AX,R14 MOVQ DX,R15 MOVQ 168(DI),AX MULQ 168(DI) ADDQ AX,R10 ADCQ DX,R11 MOVQ 168(DI),AX SHLQ $1,AX MULQ 176(DI) ADDQ AX,R12 ADCQ DX,R13 MOVQ 168(DI),AX SHLQ $1,AX MULQ 184(DI) ADDQ AX,R14 ADCQ DX,R15 MOVQ 168(DI),DX IMUL3Q $38,DX,AX MULQ 192(DI) ADDQ AX,SI ADCQ DX,CX MOVQ 176(DI),AX MULQ 176(DI) ADDQ AX,R14 ADCQ DX,R15 MOVQ 176(DI),DX IMUL3Q $38,DX,AX MULQ 184(DI) ADDQ AX,SI ADCQ DX,CX MOVQ 176(DI),DX IMUL3Q $38,DX,AX MULQ 192(DI) ADDQ AX,R8 ADCQ DX,R9 MOVQ 184(DI),DX IMUL3Q $19,DX,AX MULQ 184(DI) ADDQ AX,R8 ADCQ DX,R9 MOVQ 184(DI),DX IMUL3Q $38,DX,AX MULQ 192(DI) ADDQ AX,R10 ADCQ DX,R11 MOVQ 192(DI),DX IMUL3Q $19,DX,AX MULQ 192(DI) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX ANDQ DX,SI MOVQ CX,R8 SHRQ $51,CX ADDQ R10,CX ANDQ DX,R8 MOVQ CX,R9 SHRQ $51,CX ADDQ R12,CX ANDQ DX,R9 MOVQ CX,AX SHRQ $51,CX ADDQ R14,CX ANDQ DX,AX MOVQ CX,R10 SHRQ $51,CX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,160(DI) MOVQ R8,168(DI) MOVQ R9,176(DI) MOVQ AX,184(DI) MOVQ R10,192(DI) MOVQ 184(DI),SI IMUL3Q $19,SI,AX MOVQ AX,0(SP) MULQ 16(DI) MOVQ AX,SI MOVQ DX,CX MOVQ 192(DI),DX IMUL3Q $19,DX,AX MOVQ AX,8(SP) MULQ 8(DI) ADDQ AX,SI ADCQ DX,CX MOVQ 160(DI),AX MULQ 0(DI) ADDQ AX,SI ADCQ DX,CX MOVQ 160(DI),AX MULQ 8(DI) MOVQ AX,R8 MOVQ DX,R9 MOVQ 160(DI),AX MULQ 16(DI) MOVQ AX,R10 MOVQ DX,R11 MOVQ 160(DI),AX MULQ 24(DI) MOVQ AX,R12 MOVQ DX,R13 MOVQ 160(DI),AX MULQ 32(DI) MOVQ AX,R14 MOVQ DX,R15 MOVQ 168(DI),AX MULQ 0(DI) ADDQ AX,R8 ADCQ DX,R9 MOVQ 168(DI),AX MULQ 8(DI) ADDQ AX,R10 ADCQ DX,R11 MOVQ 168(DI),AX MULQ 16(DI) ADDQ AX,R12 ADCQ DX,R13 MOVQ 168(DI),AX MULQ 24(DI) ADDQ AX,R14 ADCQ DX,R15 MOVQ 168(DI),DX IMUL3Q $19,DX,AX MULQ 32(DI) ADDQ AX,SI ADCQ DX,CX MOVQ 176(DI),AX MULQ 0(DI) ADDQ AX,R10 ADCQ DX,R11 MOVQ 176(DI),AX MULQ 8(DI) ADDQ AX,R12 ADCQ DX,R13 MOVQ 176(DI),AX MULQ 16(DI) ADDQ AX,R14 ADCQ DX,R15 MOVQ 176(DI),DX IMUL3Q $19,DX,AX MULQ 24(DI) ADDQ AX,SI ADCQ DX,CX MOVQ 176(DI),DX IMUL3Q $19,DX,AX MULQ 32(DI) ADDQ AX,R8 ADCQ DX,R9 MOVQ 184(DI),AX MULQ 0(DI) ADDQ AX,R12 ADCQ DX,R13 MOVQ 184(DI),AX MULQ 8(DI) ADDQ AX,R14 ADCQ DX,R15 MOVQ 0(SP),AX MULQ 24(DI) ADDQ AX,R8 ADCQ DX,R9 MOVQ 0(SP),AX MULQ 32(DI) ADDQ AX,R10 ADCQ DX,R11 MOVQ 192(DI),AX MULQ 0(DI) ADDQ AX,R14 ADCQ DX,R15 MOVQ 8(SP),AX MULQ 16(DI) ADDQ AX,R8 ADCQ DX,R9 MOVQ 8(SP),AX MULQ 24(DI) ADDQ AX,R10 ADCQ DX,R11 MOVQ 8(SP),AX MULQ 32(DI) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX MOVQ CX,R8 SHRQ $51,CX ANDQ DX,SI ADDQ R10,CX MOVQ CX,R9 SHRQ $51,CX ANDQ DX,R8 ADDQ R12,CX MOVQ CX,AX SHRQ $51,CX ANDQ DX,R9 ADDQ R14,CX MOVQ CX,R10 SHRQ $51,CX ANDQ DX,AX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,160(DI) MOVQ R8,168(DI) MOVQ R9,176(DI) MOVQ AX,184(DI) MOVQ R10,192(DI) MOVQ 144(SP),SI IMUL3Q $19,SI,AX MOVQ AX,0(SP) MULQ 96(SP) MOVQ AX,SI MOVQ DX,CX MOVQ 152(SP),DX IMUL3Q $19,DX,AX MOVQ AX,8(SP) MULQ 88(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 120(SP),AX MULQ 80(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 120(SP),AX MULQ 88(SP) MOVQ AX,R8 MOVQ DX,R9 MOVQ 120(SP),AX MULQ 96(SP) MOVQ AX,R10 MOVQ DX,R11 MOVQ 120(SP),AX MULQ 104(SP) MOVQ AX,R12 MOVQ DX,R13 MOVQ 120(SP),AX MULQ 112(SP) MOVQ AX,R14 MOVQ DX,R15 MOVQ 128(SP),AX MULQ 80(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 128(SP),AX MULQ 88(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 128(SP),AX MULQ 96(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 128(SP),AX MULQ 104(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 128(SP),DX IMUL3Q $19,DX,AX MULQ 112(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 136(SP),AX MULQ 80(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 136(SP),AX MULQ 88(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 136(SP),AX MULQ 96(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 136(SP),DX IMUL3Q $19,DX,AX MULQ 104(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 136(SP),DX IMUL3Q $19,DX,AX MULQ 112(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 144(SP),AX MULQ 80(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 144(SP),AX MULQ 88(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 0(SP),AX MULQ 104(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 0(SP),AX MULQ 112(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 152(SP),AX MULQ 80(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 8(SP),AX MULQ 96(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 8(SP),AX MULQ 104(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 8(SP),AX MULQ 112(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX MOVQ CX,R8 SHRQ $51,CX ANDQ DX,SI ADDQ R10,CX MOVQ CX,R9 SHRQ $51,CX ANDQ DX,R8 ADDQ R12,CX MOVQ CX,AX SHRQ $51,CX ANDQ DX,R9 ADDQ R14,CX MOVQ CX,R10 SHRQ $51,CX ANDQ DX,AX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,40(DI) MOVQ R8,48(DI) MOVQ R9,56(DI) MOVQ AX,64(DI) MOVQ R10,72(DI) MOVQ 160(SP),AX MULQ ·_121666_213(SB) SHRQ $13,AX MOVQ AX,SI MOVQ DX,CX MOVQ 168(SP),AX MULQ ·_121666_213(SB) SHRQ $13,AX ADDQ AX,CX MOVQ DX,R8 MOVQ 176(SP),AX MULQ ·_121666_213(SB) SHRQ $13,AX ADDQ AX,R8 MOVQ DX,R9 MOVQ 184(SP),AX MULQ ·_121666_213(SB) SHRQ $13,AX ADDQ AX,R9 MOVQ DX,R10 MOVQ 192(SP),AX MULQ ·_121666_213(SB) SHRQ $13,AX ADDQ AX,R10 IMUL3Q $19,DX,DX ADDQ DX,SI ADDQ 80(SP),SI ADDQ 88(SP),CX ADDQ 96(SP),R8 ADDQ 104(SP),R9 ADDQ 112(SP),R10 MOVQ SI,80(DI) MOVQ CX,88(DI) MOVQ R8,96(DI) MOVQ R9,104(DI) MOVQ R10,112(DI) MOVQ 104(DI),SI IMUL3Q $19,SI,AX MOVQ AX,0(SP) MULQ 176(SP) MOVQ AX,SI MOVQ DX,CX MOVQ 112(DI),DX IMUL3Q $19,DX,AX MOVQ AX,8(SP) MULQ 168(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 80(DI),AX MULQ 160(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 80(DI),AX MULQ 168(SP) MOVQ AX,R8 MOVQ DX,R9 MOVQ 80(DI),AX MULQ 176(SP) MOVQ AX,R10 MOVQ DX,R11 MOVQ 80(DI),AX MULQ 184(SP) MOVQ AX,R12 MOVQ DX,R13 MOVQ 80(DI),AX MULQ 192(SP) MOVQ AX,R14 MOVQ DX,R15 MOVQ 88(DI),AX MULQ 160(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 88(DI),AX MULQ 168(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 88(DI),AX MULQ 176(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 88(DI),AX MULQ 184(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 88(DI),DX IMUL3Q $19,DX,AX MULQ 192(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 96(DI),AX MULQ 160(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 96(DI),AX MULQ 168(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 96(DI),AX MULQ 176(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 96(DI),DX IMUL3Q $19,DX,AX MULQ 184(SP) ADDQ AX,SI ADCQ DX,CX MOVQ 96(DI),DX IMUL3Q $19,DX,AX MULQ 192(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 104(DI),AX MULQ 160(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ 104(DI),AX MULQ 168(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 0(SP),AX MULQ 184(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 0(SP),AX MULQ 192(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 112(DI),AX MULQ 160(SP) ADDQ AX,R14 ADCQ DX,R15 MOVQ 8(SP),AX MULQ 176(SP) ADDQ AX,R8 ADCQ DX,R9 MOVQ 8(SP),AX MULQ 184(SP) ADDQ AX,R10 ADCQ DX,R11 MOVQ 8(SP),AX MULQ 192(SP) ADDQ AX,R12 ADCQ DX,R13 MOVQ $REDMASK51,DX SHLQ $13,CX:SI ANDQ DX,SI SHLQ $13,R9:R8 ANDQ DX,R8 ADDQ CX,R8 SHLQ $13,R11:R10 ANDQ DX,R10 ADDQ R9,R10 SHLQ $13,R13:R12 ANDQ DX,R12 ADDQ R11,R12 SHLQ $13,R15:R14 ANDQ DX,R14 ADDQ R13,R14 IMUL3Q $19,R15,CX ADDQ CX,SI MOVQ SI,CX SHRQ $51,CX ADDQ R8,CX MOVQ CX,R8 SHRQ $51,CX ANDQ DX,SI ADDQ R10,CX MOVQ CX,R9 SHRQ $51,CX ANDQ DX,R8 ADDQ R12,CX MOVQ CX,AX SHRQ $51,CX ANDQ DX,R9 ADDQ R14,CX MOVQ CX,R10 SHRQ $51,CX ANDQ DX,AX IMUL3Q $19,CX,CX ADDQ CX,SI ANDQ DX,R10 MOVQ SI,80(DI) MOVQ R8,88(DI) MOVQ R9,96(DI) MOVQ AX,104(DI) MOVQ R10,112(DI) RET ����������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/freeze_amd64.s�����������������������������������0000644�0610621�0607500�00000002334�13172163317�025245� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine #include "const_amd64.h" // func freeze(inout *[5]uint64) TEXT ·freeze(SB),7,$0-8 MOVQ inout+0(FP), DI MOVQ 0(DI),SI MOVQ 8(DI),DX MOVQ 16(DI),CX MOVQ 24(DI),R8 MOVQ 32(DI),R9 MOVQ $REDMASK51,AX MOVQ AX,R10 SUBQ $18,R10 MOVQ $3,R11 REDUCELOOP: MOVQ SI,R12 SHRQ $51,R12 ANDQ AX,SI ADDQ R12,DX MOVQ DX,R12 SHRQ $51,R12 ANDQ AX,DX ADDQ R12,CX MOVQ CX,R12 SHRQ $51,R12 ANDQ AX,CX ADDQ R12,R8 MOVQ R8,R12 SHRQ $51,R12 ANDQ AX,R8 ADDQ R12,R9 MOVQ R9,R12 SHRQ $51,R12 ANDQ AX,R9 IMUL3Q $19,R12,R12 ADDQ R12,SI SUBQ $1,R11 JA REDUCELOOP MOVQ $1,R12 CMPQ R10,SI CMOVQLT R11,R12 CMPQ AX,DX CMOVQNE R11,R12 CMPQ AX,CX CMOVQNE R11,R12 CMPQ AX,R8 CMOVQNE R11,R12 CMPQ AX,R9 CMOVQNE R11,R12 NEGQ R12 ANDQ R12,AX ANDQ R12,R10 SUBQ R10,SI SUBQ AX,DX SUBQ AX,CX SUBQ AX,R8 SUBQ AX,R9 MOVQ SI,0(DI) MOVQ DX,8(DI) MOVQ CX,16(DI) MOVQ R8,24(DI) MOVQ R9,32(DI) RET ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/doc.go�������������������������������������������0000644�0610621�0607500�00000002024�13172163317�023676� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package curve25519 provides an implementation of scalar multiplication on // the elliptic curve known as curve25519. See https://cr.yp.to/ecdh.html package curve25519 // import "golang.org/x/crypto/curve25519" // basePoint is the x coordinate of the generator of the curve. var basePoint = [32]byte{9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // ScalarMult sets dst to the product in*base where dst and base are the x // coordinates of group points and all values are in little-endian form. func ScalarMult(dst, in, base *[32]byte) { scalarMult(dst, in, base) } // ScalarBaseMult sets dst to the product in*base where dst and base are the x // coordinates of group points, base is the standard generator and all values // are in little-endian form. func ScalarBaseMult(dst, in *[32]byte) { ScalarMult(dst, in, &basePoint) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/curve25519_test.go�������������������������������0000644�0610621�0607500�00000001372�13172163317�025727� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package curve25519 import ( "fmt" "testing" ) const expectedHex = "89161fde887b2b53de549af483940106ecc114d6982daa98256de23bdf77661a" func TestBaseScalarMult(t *testing.T) { var a, b [32]byte in := &a out := &b a[0] = 1 for i := 0; i < 200; i++ { ScalarBaseMult(out, in) in, out = out, in } result := fmt.Sprintf("%x", in[:]) if result != expectedHex { t.Errorf("incorrect result: got %s, want %s", result, expectedHex) } } func BenchmarkScalarBaseMult(b *testing.B) { var in, out [32]byte in[0] = 1 b.SetBytes(32) for i := 0; i < b.N; i++ { ScalarBaseMult(&out, &in) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/curve25519.go������������������������������������0000644�0610621�0607500�00000052652�13172163317�024677� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // We have an implementation in amd64 assembly so this code is only run on // non-amd64 platforms. The amd64 assembly does not support gccgo. // +build !amd64 gccgo appengine package curve25519 import ( "encoding/binary" ) // This code is a port of the public domain, "ref10" implementation of // curve25519 from SUPERCOP 20130419 by D. J. Bernstein. // fieldElement represents an element of the field GF(2^255 - 19). An element // t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 // t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on // context. type fieldElement [10]int32 func feZero(fe *fieldElement) { for i := range fe { fe[i] = 0 } } func feOne(fe *fieldElement) { feZero(fe) fe[0] = 1 } func feAdd(dst, a, b *fieldElement) { for i := range dst { dst[i] = a[i] + b[i] } } func feSub(dst, a, b *fieldElement) { for i := range dst { dst[i] = a[i] - b[i] } } func feCopy(dst, src *fieldElement) { for i := range dst { dst[i] = src[i] } } // feCSwap replaces (f,g) with (g,f) if b == 1; replaces (f,g) with (f,g) if b == 0. // // Preconditions: b in {0,1}. func feCSwap(f, g *fieldElement, b int32) { b = -b for i := range f { t := b & (f[i] ^ g[i]) f[i] ^= t g[i] ^= t } } // load3 reads a 24-bit, little-endian value from in. func load3(in []byte) int64 { var r int64 r = int64(in[0]) r |= int64(in[1]) << 8 r |= int64(in[2]) << 16 return r } // load4 reads a 32-bit, little-endian value from in. func load4(in []byte) int64 { return int64(binary.LittleEndian.Uint32(in)) } func feFromBytes(dst *fieldElement, src *[32]byte) { h0 := load4(src[:]) h1 := load3(src[4:]) << 6 h2 := load3(src[7:]) << 5 h3 := load3(src[10:]) << 3 h4 := load3(src[13:]) << 2 h5 := load4(src[16:]) h6 := load3(src[20:]) << 7 h7 := load3(src[23:]) << 5 h8 := load3(src[26:]) << 4 h9 := load3(src[29:]) << 2 var carry [10]int64 carry[9] = (h9 + 1<<24) >> 25 h0 += carry[9] * 19 h9 -= carry[9] << 25 carry[1] = (h1 + 1<<24) >> 25 h2 += carry[1] h1 -= carry[1] << 25 carry[3] = (h3 + 1<<24) >> 25 h4 += carry[3] h3 -= carry[3] << 25 carry[5] = (h5 + 1<<24) >> 25 h6 += carry[5] h5 -= carry[5] << 25 carry[7] = (h7 + 1<<24) >> 25 h8 += carry[7] h7 -= carry[7] << 25 carry[0] = (h0 + 1<<25) >> 26 h1 += carry[0] h0 -= carry[0] << 26 carry[2] = (h2 + 1<<25) >> 26 h3 += carry[2] h2 -= carry[2] << 26 carry[4] = (h4 + 1<<25) >> 26 h5 += carry[4] h4 -= carry[4] << 26 carry[6] = (h6 + 1<<25) >> 26 h7 += carry[6] h6 -= carry[6] << 26 carry[8] = (h8 + 1<<25) >> 26 h9 += carry[8] h8 -= carry[8] << 26 dst[0] = int32(h0) dst[1] = int32(h1) dst[2] = int32(h2) dst[3] = int32(h3) dst[4] = int32(h4) dst[5] = int32(h5) dst[6] = int32(h6) dst[7] = int32(h7) dst[8] = int32(h8) dst[9] = int32(h9) } // feToBytes marshals h to s. // Preconditions: // |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. // // Write p=2^255-19; q=floor(h/p). // Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). // // Proof: // Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. // Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. // // Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). // Then 0<y<1. // // Write r=h-pq. // Have 0<=r<=p-1=2^255-20. // Thus 0<=r+19(2^-255)r<r+19(2^-255)2^255<=2^255-1. // // Write x=r+19(2^-255)r+y. // Then 0<x<2^255 so floor(2^(-255)x) = 0 so floor(q+2^(-255)x) = q. // // Have q+2^(-255)x = 2^(-255)(h + 19 2^(-25) h9 + 2^(-1)) // so floor(2^(-255)(h + 19 2^(-25) h9 + 2^(-1))) = q. func feToBytes(s *[32]byte, h *fieldElement) { var carry [10]int32 q := (19*h[9] + (1 << 24)) >> 25 q = (h[0] + q) >> 26 q = (h[1] + q) >> 25 q = (h[2] + q) >> 26 q = (h[3] + q) >> 25 q = (h[4] + q) >> 26 q = (h[5] + q) >> 25 q = (h[6] + q) >> 26 q = (h[7] + q) >> 25 q = (h[8] + q) >> 26 q = (h[9] + q) >> 25 // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. h[0] += 19 * q // Goal: Output h-2^255 q, which is between 0 and 2^255-20. carry[0] = h[0] >> 26 h[1] += carry[0] h[0] -= carry[0] << 26 carry[1] = h[1] >> 25 h[2] += carry[1] h[1] -= carry[1] << 25 carry[2] = h[2] >> 26 h[3] += carry[2] h[2] -= carry[2] << 26 carry[3] = h[3] >> 25 h[4] += carry[3] h[3] -= carry[3] << 25 carry[4] = h[4] >> 26 h[5] += carry[4] h[4] -= carry[4] << 26 carry[5] = h[5] >> 25 h[6] += carry[5] h[5] -= carry[5] << 25 carry[6] = h[6] >> 26 h[7] += carry[6] h[6] -= carry[6] << 26 carry[7] = h[7] >> 25 h[8] += carry[7] h[7] -= carry[7] << 25 carry[8] = h[8] >> 26 h[9] += carry[8] h[8] -= carry[8] << 26 carry[9] = h[9] >> 25 h[9] -= carry[9] << 25 // h10 = carry9 // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; // evidently 2^255 h10-2^255 q = 0. // Goal: Output h[0]+...+2^230 h[9]. s[0] = byte(h[0] >> 0) s[1] = byte(h[0] >> 8) s[2] = byte(h[0] >> 16) s[3] = byte((h[0] >> 24) | (h[1] << 2)) s[4] = byte(h[1] >> 6) s[5] = byte(h[1] >> 14) s[6] = byte((h[1] >> 22) | (h[2] << 3)) s[7] = byte(h[2] >> 5) s[8] = byte(h[2] >> 13) s[9] = byte((h[2] >> 21) | (h[3] << 5)) s[10] = byte(h[3] >> 3) s[11] = byte(h[3] >> 11) s[12] = byte((h[3] >> 19) | (h[4] << 6)) s[13] = byte(h[4] >> 2) s[14] = byte(h[4] >> 10) s[15] = byte(h[4] >> 18) s[16] = byte(h[5] >> 0) s[17] = byte(h[5] >> 8) s[18] = byte(h[5] >> 16) s[19] = byte((h[5] >> 24) | (h[6] << 1)) s[20] = byte(h[6] >> 7) s[21] = byte(h[6] >> 15) s[22] = byte((h[6] >> 23) | (h[7] << 3)) s[23] = byte(h[7] >> 5) s[24] = byte(h[7] >> 13) s[25] = byte((h[7] >> 21) | (h[8] << 4)) s[26] = byte(h[8] >> 4) s[27] = byte(h[8] >> 12) s[28] = byte((h[8] >> 20) | (h[9] << 6)) s[29] = byte(h[9] >> 2) s[30] = byte(h[9] >> 10) s[31] = byte(h[9] >> 18) } // feMul calculates h = f * g // Can overlap h with f or g. // // Preconditions: // |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. // |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. // // Postconditions: // |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. // // Notes on implementation strategy: // // Using schoolbook multiplication. // Karatsuba would save a little in some cost models. // // Most multiplications by 2 and 19 are 32-bit precomputations; // cheaper than 64-bit postcomputations. // // There is one remaining multiplication by 19 in the carry chain; // one *19 precomputation can be merged into this, // but the resulting data flow is considerably less clean. // // There are 12 carries below. // 10 of them are 2-way parallelizable and vectorizable. // Can get away with 11 carries, but then data flow is much deeper. // // With tighter constraints on inputs can squeeze carries into int32. func feMul(h, f, g *fieldElement) { f0 := f[0] f1 := f[1] f2 := f[2] f3 := f[3] f4 := f[4] f5 := f[5] f6 := f[6] f7 := f[7] f8 := f[8] f9 := f[9] g0 := g[0] g1 := g[1] g2 := g[2] g3 := g[3] g4 := g[4] g5 := g[5] g6 := g[6] g7 := g[7] g8 := g[8] g9 := g[9] g1_19 := 19 * g1 // 1.4*2^29 g2_19 := 19 * g2 // 1.4*2^30; still ok g3_19 := 19 * g3 g4_19 := 19 * g4 g5_19 := 19 * g5 g6_19 := 19 * g6 g7_19 := 19 * g7 g8_19 := 19 * g8 g9_19 := 19 * g9 f1_2 := 2 * f1 f3_2 := 2 * f3 f5_2 := 2 * f5 f7_2 := 2 * f7 f9_2 := 2 * f9 f0g0 := int64(f0) * int64(g0) f0g1 := int64(f0) * int64(g1) f0g2 := int64(f0) * int64(g2) f0g3 := int64(f0) * int64(g3) f0g4 := int64(f0) * int64(g4) f0g5 := int64(f0) * int64(g5) f0g6 := int64(f0) * int64(g6) f0g7 := int64(f0) * int64(g7) f0g8 := int64(f0) * int64(g8) f0g9 := int64(f0) * int64(g9) f1g0 := int64(f1) * int64(g0) f1g1_2 := int64(f1_2) * int64(g1) f1g2 := int64(f1) * int64(g2) f1g3_2 := int64(f1_2) * int64(g3) f1g4 := int64(f1) * int64(g4) f1g5_2 := int64(f1_2) * int64(g5) f1g6 := int64(f1) * int64(g6) f1g7_2 := int64(f1_2) * int64(g7) f1g8 := int64(f1) * int64(g8) f1g9_38 := int64(f1_2) * int64(g9_19) f2g0 := int64(f2) * int64(g0) f2g1 := int64(f2) * int64(g1) f2g2 := int64(f2) * int64(g2) f2g3 := int64(f2) * int64(g3) f2g4 := int64(f2) * int64(g4) f2g5 := int64(f2) * int64(g5) f2g6 := int64(f2) * int64(g6) f2g7 := int64(f2) * int64(g7) f2g8_19 := int64(f2) * int64(g8_19) f2g9_19 := int64(f2) * int64(g9_19) f3g0 := int64(f3) * int64(g0) f3g1_2 := int64(f3_2) * int64(g1) f3g2 := int64(f3) * int64(g2) f3g3_2 := int64(f3_2) * int64(g3) f3g4 := int64(f3) * int64(g4) f3g5_2 := int64(f3_2) * int64(g5) f3g6 := int64(f3) * int64(g6) f3g7_38 := int64(f3_2) * int64(g7_19) f3g8_19 := int64(f3) * int64(g8_19) f3g9_38 := int64(f3_2) * int64(g9_19) f4g0 := int64(f4) * int64(g0) f4g1 := int64(f4) * int64(g1) f4g2 := int64(f4) * int64(g2) f4g3 := int64(f4) * int64(g3) f4g4 := int64(f4) * int64(g4) f4g5 := int64(f4) * int64(g5) f4g6_19 := int64(f4) * int64(g6_19) f4g7_19 := int64(f4) * int64(g7_19) f4g8_19 := int64(f4) * int64(g8_19) f4g9_19 := int64(f4) * int64(g9_19) f5g0 := int64(f5) * int64(g0) f5g1_2 := int64(f5_2) * int64(g1) f5g2 := int64(f5) * int64(g2) f5g3_2 := int64(f5_2) * int64(g3) f5g4 := int64(f5) * int64(g4) f5g5_38 := int64(f5_2) * int64(g5_19) f5g6_19 := int64(f5) * int64(g6_19) f5g7_38 := int64(f5_2) * int64(g7_19) f5g8_19 := int64(f5) * int64(g8_19) f5g9_38 := int64(f5_2) * int64(g9_19) f6g0 := int64(f6) * int64(g0) f6g1 := int64(f6) * int64(g1) f6g2 := int64(f6) * int64(g2) f6g3 := int64(f6) * int64(g3) f6g4_19 := int64(f6) * int64(g4_19) f6g5_19 := int64(f6) * int64(g5_19) f6g6_19 := int64(f6) * int64(g6_19) f6g7_19 := int64(f6) * int64(g7_19) f6g8_19 := int64(f6) * int64(g8_19) f6g9_19 := int64(f6) * int64(g9_19) f7g0 := int64(f7) * int64(g0) f7g1_2 := int64(f7_2) * int64(g1) f7g2 := int64(f7) * int64(g2) f7g3_38 := int64(f7_2) * int64(g3_19) f7g4_19 := int64(f7) * int64(g4_19) f7g5_38 := int64(f7_2) * int64(g5_19) f7g6_19 := int64(f7) * int64(g6_19) f7g7_38 := int64(f7_2) * int64(g7_19) f7g8_19 := int64(f7) * int64(g8_19) f7g9_38 := int64(f7_2) * int64(g9_19) f8g0 := int64(f8) * int64(g0) f8g1 := int64(f8) * int64(g1) f8g2_19 := int64(f8) * int64(g2_19) f8g3_19 := int64(f8) * int64(g3_19) f8g4_19 := int64(f8) * int64(g4_19) f8g5_19 := int64(f8) * int64(g5_19) f8g6_19 := int64(f8) * int64(g6_19) f8g7_19 := int64(f8) * int64(g7_19) f8g8_19 := int64(f8) * int64(g8_19) f8g9_19 := int64(f8) * int64(g9_19) f9g0 := int64(f9) * int64(g0) f9g1_38 := int64(f9_2) * int64(g1_19) f9g2_19 := int64(f9) * int64(g2_19) f9g3_38 := int64(f9_2) * int64(g3_19) f9g4_19 := int64(f9) * int64(g4_19) f9g5_38 := int64(f9_2) * int64(g5_19) f9g6_19 := int64(f9) * int64(g6_19) f9g7_38 := int64(f9_2) * int64(g7_19) f9g8_19 := int64(f9) * int64(g8_19) f9g9_38 := int64(f9_2) * int64(g9_19) h0 := f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38 h1 := f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + f7g4_19 + f8g3_19 + f9g2_19 h2 := f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + f7g5_38 + f8g4_19 + f9g3_38 h3 := f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + f7g6_19 + f8g5_19 + f9g4_19 h4 := f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + f7g7_38 + f8g6_19 + f9g5_38 h5 := f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + f8g7_19 + f9g6_19 h6 := f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + f7g9_38 + f8g8_19 + f9g7_38 h7 := f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + f8g9_19 + f9g8_19 h8 := f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + f8g0 + f9g9_38 h9 := f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 var carry [10]int64 // |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) // i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 // |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) // i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 carry[0] = (h0 + (1 << 25)) >> 26 h1 += carry[0] h0 -= carry[0] << 26 carry[4] = (h4 + (1 << 25)) >> 26 h5 += carry[4] h4 -= carry[4] << 26 // |h0| <= 2^25 // |h4| <= 2^25 // |h1| <= 1.51*2^58 // |h5| <= 1.51*2^58 carry[1] = (h1 + (1 << 24)) >> 25 h2 += carry[1] h1 -= carry[1] << 25 carry[5] = (h5 + (1 << 24)) >> 25 h6 += carry[5] h5 -= carry[5] << 25 // |h1| <= 2^24; from now on fits into int32 // |h5| <= 2^24; from now on fits into int32 // |h2| <= 1.21*2^59 // |h6| <= 1.21*2^59 carry[2] = (h2 + (1 << 25)) >> 26 h3 += carry[2] h2 -= carry[2] << 26 carry[6] = (h6 + (1 << 25)) >> 26 h7 += carry[6] h6 -= carry[6] << 26 // |h2| <= 2^25; from now on fits into int32 unchanged // |h6| <= 2^25; from now on fits into int32 unchanged // |h3| <= 1.51*2^58 // |h7| <= 1.51*2^58 carry[3] = (h3 + (1 << 24)) >> 25 h4 += carry[3] h3 -= carry[3] << 25 carry[7] = (h7 + (1 << 24)) >> 25 h8 += carry[7] h7 -= carry[7] << 25 // |h3| <= 2^24; from now on fits into int32 unchanged // |h7| <= 2^24; from now on fits into int32 unchanged // |h4| <= 1.52*2^33 // |h8| <= 1.52*2^33 carry[4] = (h4 + (1 << 25)) >> 26 h5 += carry[4] h4 -= carry[4] << 26 carry[8] = (h8 + (1 << 25)) >> 26 h9 += carry[8] h8 -= carry[8] << 26 // |h4| <= 2^25; from now on fits into int32 unchanged // |h8| <= 2^25; from now on fits into int32 unchanged // |h5| <= 1.01*2^24 // |h9| <= 1.51*2^58 carry[9] = (h9 + (1 << 24)) >> 25 h0 += carry[9] * 19 h9 -= carry[9] << 25 // |h9| <= 2^24; from now on fits into int32 unchanged // |h0| <= 1.8*2^37 carry[0] = (h0 + (1 << 25)) >> 26 h1 += carry[0] h0 -= carry[0] << 26 // |h0| <= 2^25; from now on fits into int32 unchanged // |h1| <= 1.01*2^24 h[0] = int32(h0) h[1] = int32(h1) h[2] = int32(h2) h[3] = int32(h3) h[4] = int32(h4) h[5] = int32(h5) h[6] = int32(h6) h[7] = int32(h7) h[8] = int32(h8) h[9] = int32(h9) } // feSquare calculates h = f*f. Can overlap h with f. // // Preconditions: // |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. // // Postconditions: // |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. func feSquare(h, f *fieldElement) { f0 := f[0] f1 := f[1] f2 := f[2] f3 := f[3] f4 := f[4] f5 := f[5] f6 := f[6] f7 := f[7] f8 := f[8] f9 := f[9] f0_2 := 2 * f0 f1_2 := 2 * f1 f2_2 := 2 * f2 f3_2 := 2 * f3 f4_2 := 2 * f4 f5_2 := 2 * f5 f6_2 := 2 * f6 f7_2 := 2 * f7 f5_38 := 38 * f5 // 1.31*2^30 f6_19 := 19 * f6 // 1.31*2^30 f7_38 := 38 * f7 // 1.31*2^30 f8_19 := 19 * f8 // 1.31*2^30 f9_38 := 38 * f9 // 1.31*2^30 f0f0 := int64(f0) * int64(f0) f0f1_2 := int64(f0_2) * int64(f1) f0f2_2 := int64(f0_2) * int64(f2) f0f3_2 := int64(f0_2) * int64(f3) f0f4_2 := int64(f0_2) * int64(f4) f0f5_2 := int64(f0_2) * int64(f5) f0f6_2 := int64(f0_2) * int64(f6) f0f7_2 := int64(f0_2) * int64(f7) f0f8_2 := int64(f0_2) * int64(f8) f0f9_2 := int64(f0_2) * int64(f9) f1f1_2 := int64(f1_2) * int64(f1) f1f2_2 := int64(f1_2) * int64(f2) f1f3_4 := int64(f1_2) * int64(f3_2) f1f4_2 := int64(f1_2) * int64(f4) f1f5_4 := int64(f1_2) * int64(f5_2) f1f6_2 := int64(f1_2) * int64(f6) f1f7_4 := int64(f1_2) * int64(f7_2) f1f8_2 := int64(f1_2) * int64(f8) f1f9_76 := int64(f1_2) * int64(f9_38) f2f2 := int64(f2) * int64(f2) f2f3_2 := int64(f2_2) * int64(f3) f2f4_2 := int64(f2_2) * int64(f4) f2f5_2 := int64(f2_2) * int64(f5) f2f6_2 := int64(f2_2) * int64(f6) f2f7_2 := int64(f2_2) * int64(f7) f2f8_38 := int64(f2_2) * int64(f8_19) f2f9_38 := int64(f2) * int64(f9_38) f3f3_2 := int64(f3_2) * int64(f3) f3f4_2 := int64(f3_2) * int64(f4) f3f5_4 := int64(f3_2) * int64(f5_2) f3f6_2 := int64(f3_2) * int64(f6) f3f7_76 := int64(f3_2) * int64(f7_38) f3f8_38 := int64(f3_2) * int64(f8_19) f3f9_76 := int64(f3_2) * int64(f9_38) f4f4 := int64(f4) * int64(f4) f4f5_2 := int64(f4_2) * int64(f5) f4f6_38 := int64(f4_2) * int64(f6_19) f4f7_38 := int64(f4) * int64(f7_38) f4f8_38 := int64(f4_2) * int64(f8_19) f4f9_38 := int64(f4) * int64(f9_38) f5f5_38 := int64(f5) * int64(f5_38) f5f6_38 := int64(f5_2) * int64(f6_19) f5f7_76 := int64(f5_2) * int64(f7_38) f5f8_38 := int64(f5_2) * int64(f8_19) f5f9_76 := int64(f5_2) * int64(f9_38) f6f6_19 := int64(f6) * int64(f6_19) f6f7_38 := int64(f6) * int64(f7_38) f6f8_38 := int64(f6_2) * int64(f8_19) f6f9_38 := int64(f6) * int64(f9_38) f7f7_38 := int64(f7) * int64(f7_38) f7f8_38 := int64(f7_2) * int64(f8_19) f7f9_76 := int64(f7_2) * int64(f9_38) f8f8_19 := int64(f8) * int64(f8_19) f8f9_38 := int64(f8) * int64(f9_38) f9f9_38 := int64(f9) * int64(f9_38) h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 var carry [10]int64 carry[0] = (h0 + (1 << 25)) >> 26 h1 += carry[0] h0 -= carry[0] << 26 carry[4] = (h4 + (1 << 25)) >> 26 h5 += carry[4] h4 -= carry[4] << 26 carry[1] = (h1 + (1 << 24)) >> 25 h2 += carry[1] h1 -= carry[1] << 25 carry[5] = (h5 + (1 << 24)) >> 25 h6 += carry[5] h5 -= carry[5] << 25 carry[2] = (h2 + (1 << 25)) >> 26 h3 += carry[2] h2 -= carry[2] << 26 carry[6] = (h6 + (1 << 25)) >> 26 h7 += carry[6] h6 -= carry[6] << 26 carry[3] = (h3 + (1 << 24)) >> 25 h4 += carry[3] h3 -= carry[3] << 25 carry[7] = (h7 + (1 << 24)) >> 25 h8 += carry[7] h7 -= carry[7] << 25 carry[4] = (h4 + (1 << 25)) >> 26 h5 += carry[4] h4 -= carry[4] << 26 carry[8] = (h8 + (1 << 25)) >> 26 h9 += carry[8] h8 -= carry[8] << 26 carry[9] = (h9 + (1 << 24)) >> 25 h0 += carry[9] * 19 h9 -= carry[9] << 25 carry[0] = (h0 + (1 << 25)) >> 26 h1 += carry[0] h0 -= carry[0] << 26 h[0] = int32(h0) h[1] = int32(h1) h[2] = int32(h2) h[3] = int32(h3) h[4] = int32(h4) h[5] = int32(h5) h[6] = int32(h6) h[7] = int32(h7) h[8] = int32(h8) h[9] = int32(h9) } // feMul121666 calculates h = f * 121666. Can overlap h with f. // // Preconditions: // |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. // // Postconditions: // |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. func feMul121666(h, f *fieldElement) { h0 := int64(f[0]) * 121666 h1 := int64(f[1]) * 121666 h2 := int64(f[2]) * 121666 h3 := int64(f[3]) * 121666 h4 := int64(f[4]) * 121666 h5 := int64(f[5]) * 121666 h6 := int64(f[6]) * 121666 h7 := int64(f[7]) * 121666 h8 := int64(f[8]) * 121666 h9 := int64(f[9]) * 121666 var carry [10]int64 carry[9] = (h9 + (1 << 24)) >> 25 h0 += carry[9] * 19 h9 -= carry[9] << 25 carry[1] = (h1 + (1 << 24)) >> 25 h2 += carry[1] h1 -= carry[1] << 25 carry[3] = (h3 + (1 << 24)) >> 25 h4 += carry[3] h3 -= carry[3] << 25 carry[5] = (h5 + (1 << 24)) >> 25 h6 += carry[5] h5 -= carry[5] << 25 carry[7] = (h7 + (1 << 24)) >> 25 h8 += carry[7] h7 -= carry[7] << 25 carry[0] = (h0 + (1 << 25)) >> 26 h1 += carry[0] h0 -= carry[0] << 26 carry[2] = (h2 + (1 << 25)) >> 26 h3 += carry[2] h2 -= carry[2] << 26 carry[4] = (h4 + (1 << 25)) >> 26 h5 += carry[4] h4 -= carry[4] << 26 carry[6] = (h6 + (1 << 25)) >> 26 h7 += carry[6] h6 -= carry[6] << 26 carry[8] = (h8 + (1 << 25)) >> 26 h9 += carry[8] h8 -= carry[8] << 26 h[0] = int32(h0) h[1] = int32(h1) h[2] = int32(h2) h[3] = int32(h3) h[4] = int32(h4) h[5] = int32(h5) h[6] = int32(h6) h[7] = int32(h7) h[8] = int32(h8) h[9] = int32(h9) } // feInvert sets out = z^-1. func feInvert(out, z *fieldElement) { var t0, t1, t2, t3 fieldElement var i int feSquare(&t0, z) for i = 1; i < 1; i++ { feSquare(&t0, &t0) } feSquare(&t1, &t0) for i = 1; i < 2; i++ { feSquare(&t1, &t1) } feMul(&t1, z, &t1) feMul(&t0, &t0, &t1) feSquare(&t2, &t0) for i = 1; i < 1; i++ { feSquare(&t2, &t2) } feMul(&t1, &t1, &t2) feSquare(&t2, &t1) for i = 1; i < 5; i++ { feSquare(&t2, &t2) } feMul(&t1, &t2, &t1) feSquare(&t2, &t1) for i = 1; i < 10; i++ { feSquare(&t2, &t2) } feMul(&t2, &t2, &t1) feSquare(&t3, &t2) for i = 1; i < 20; i++ { feSquare(&t3, &t3) } feMul(&t2, &t3, &t2) feSquare(&t2, &t2) for i = 1; i < 10; i++ { feSquare(&t2, &t2) } feMul(&t1, &t2, &t1) feSquare(&t2, &t1) for i = 1; i < 50; i++ { feSquare(&t2, &t2) } feMul(&t2, &t2, &t1) feSquare(&t3, &t2) for i = 1; i < 100; i++ { feSquare(&t3, &t3) } feMul(&t2, &t3, &t2) feSquare(&t2, &t2) for i = 1; i < 50; i++ { feSquare(&t2, &t2) } feMul(&t1, &t2, &t1) feSquare(&t1, &t1) for i = 1; i < 5; i++ { feSquare(&t1, &t1) } feMul(out, &t1, &t0) } func scalarMult(out, in, base *[32]byte) { var e [32]byte copy(e[:], in[:]) e[0] &= 248 e[31] &= 127 e[31] |= 64 var x1, x2, z2, x3, z3, tmp0, tmp1 fieldElement feFromBytes(&x1, base) feOne(&x2) feCopy(&x3, &x1) feOne(&z3) swap := int32(0) for pos := 254; pos >= 0; pos-- { b := e[pos/8] >> uint(pos&7) b &= 1 swap ^= int32(b) feCSwap(&x2, &x3, swap) feCSwap(&z2, &z3, swap) swap = int32(b) feSub(&tmp0, &x3, &z3) feSub(&tmp1, &x2, &z2) feAdd(&x2, &x2, &z2) feAdd(&z2, &x3, &z3) feMul(&z3, &tmp0, &x2) feMul(&z2, &z2, &tmp1) feSquare(&tmp0, &tmp1) feSquare(&tmp1, &x2) feAdd(&x3, &z3, &z2) feSub(&z2, &z3, &z2) feMul(&x2, &tmp1, &tmp0) feSub(&tmp1, &tmp1, &tmp0) feSquare(&z2, &z2) feMul121666(&z3, &tmp1) feSquare(&x3, &x3) feAdd(&tmp0, &tmp0, &z3) feMul(&z3, &x1, &z2) feMul(&z2, &tmp1, &tmp0) } feCSwap(&x2, &x3, swap) feCSwap(&z2, &z3, swap) feInvert(&z2, &z2) feMul(&x2, &x2, &z2) feToBytes(out, &x2) } ��������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/cswap_amd64.s������������������������������������0000644�0610621�0607500�00000002101�13172163317�025072� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!gccgo,!appengine // func cswap(inout *[4][5]uint64, v uint64) TEXT ·cswap(SB),7,$0 MOVQ inout+0(FP),DI MOVQ v+8(FP),SI SUBQ $1, SI NOTQ SI MOVQ SI, X15 PSHUFD $0x44, X15, X15 MOVOU 0(DI), X0 MOVOU 16(DI), X2 MOVOU 32(DI), X4 MOVOU 48(DI), X6 MOVOU 64(DI), X8 MOVOU 80(DI), X1 MOVOU 96(DI), X3 MOVOU 112(DI), X5 MOVOU 128(DI), X7 MOVOU 144(DI), X9 MOVO X1, X10 MOVO X3, X11 MOVO X5, X12 MOVO X7, X13 MOVO X9, X14 PXOR X0, X10 PXOR X2, X11 PXOR X4, X12 PXOR X6, X13 PXOR X8, X14 PAND X15, X10 PAND X15, X11 PAND X15, X12 PAND X15, X13 PAND X15, X14 PXOR X10, X0 PXOR X10, X1 PXOR X11, X2 PXOR X11, X3 PXOR X12, X4 PXOR X12, X5 PXOR X13, X6 PXOR X13, X7 PXOR X14, X8 PXOR X14, X9 MOVOU X0, 0(DI) MOVOU X2, 16(DI) MOVOU X4, 32(DI) MOVOU X6, 48(DI) MOVOU X8, 64(DI) MOVOU X1, 80(DI) MOVOU X3, 96(DI) MOVOU X5, 112(DI) MOVOU X7, 128(DI) MOVOU X9, 144(DI) RET ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/const_amd64.s������������������������������������0000644�0610621�0607500�00000001205�13172163317�025107� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine // These constants cannot be encoded in non-MOVQ immediates. // We access them directly from memory instead. DATA ·_121666_213(SB)/8, $996687872 GLOBL ·_121666_213(SB), 8, $8 DATA ·_2P0(SB)/8, $0xFFFFFFFFFFFDA GLOBL ·_2P0(SB), 8, $8 DATA ·_2P1234(SB)/8, $0xFFFFFFFFFFFFE GLOBL ·_2P1234(SB), 8, $8 �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/curve25519/const_amd64.h������������������������������������0000644�0610621�0607500�00000000531�13172163317�025075� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html #define REDMASK51 0x0007FFFFFFFFFFFF �����������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/�������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023256� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/string.go����������������������������������������0000644�0610621�0607500�00000011154�13172163317�025115� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package cryptobyte contains types that help with parsing and constructing // length-prefixed, binary messages, including ASN.1 DER. (The asn1 subpackage // contains useful ASN.1 constants.) // // The String type is for parsing. It wraps a []byte slice and provides helper // functions for consuming structures, value by value. // // The Builder type is for constructing messages. It providers helper functions // for appending values and also for appending length-prefixed submessages – // without having to worry about calculating the length prefix ahead of time. // // See the documentation and examples for the Builder and String types to get // started. package cryptobyte // import "golang.org/x/crypto/cryptobyte" // String represents a string of bytes. It provides methods for parsing // fixed-length and length-prefixed values from it. type String []byte // read advances a String by n bytes and returns them. If less than n bytes // remain, it returns nil. func (s *String) read(n int) []byte { if len(*s) < n { return nil } v := (*s)[:n] *s = (*s)[n:] return v } // Skip advances the String by n byte and reports whether it was successful. func (s *String) Skip(n int) bool { return s.read(n) != nil } // ReadUint8 decodes an 8-bit value into out and advances over it. It // returns true on success and false on error. func (s *String) ReadUint8(out *uint8) bool { v := s.read(1) if v == nil { return false } *out = uint8(v[0]) return true } // ReadUint16 decodes a big-endian, 16-bit value into out and advances over it. // It returns true on success and false on error. func (s *String) ReadUint16(out *uint16) bool { v := s.read(2) if v == nil { return false } *out = uint16(v[0])<<8 | uint16(v[1]) return true } // ReadUint24 decodes a big-endian, 24-bit value into out and advances over it. // It returns true on success and false on error. func (s *String) ReadUint24(out *uint32) bool { v := s.read(3) if v == nil { return false } *out = uint32(v[0])<<16 | uint32(v[1])<<8 | uint32(v[2]) return true } // ReadUint32 decodes a big-endian, 32-bit value into out and advances over it. // It returns true on success and false on error. func (s *String) ReadUint32(out *uint32) bool { v := s.read(4) if v == nil { return false } *out = uint32(v[0])<<24 | uint32(v[1])<<16 | uint32(v[2])<<8 | uint32(v[3]) return true } func (s *String) readUnsigned(out *uint32, length int) bool { v := s.read(length) if v == nil { return false } var result uint32 for i := 0; i < length; i++ { result <<= 8 result |= uint32(v[i]) } *out = result return true } func (s *String) readLengthPrefixed(lenLen int, outChild *String) bool { lenBytes := s.read(lenLen) if lenBytes == nil { return false } var length uint32 for _, b := range lenBytes { length = length << 8 length = length | uint32(b) } if int(length) < 0 { // This currently cannot overflow because we read uint24 at most, but check // anyway in case that changes in the future. return false } v := s.read(int(length)) if v == nil { return false } *outChild = v return true } // ReadUint8LengthPrefixed reads the content of an 8-bit length-prefixed value // into out and advances over it. It returns true on success and false on // error. func (s *String) ReadUint8LengthPrefixed(out *String) bool { return s.readLengthPrefixed(1, out) } // ReadUint16LengthPrefixed reads the content of a big-endian, 16-bit // length-prefixed value into out and advances over it. It returns true on // success and false on error. func (s *String) ReadUint16LengthPrefixed(out *String) bool { return s.readLengthPrefixed(2, out) } // ReadUint24LengthPrefixed reads the content of a big-endian, 24-bit // length-prefixed value into out and advances over it. It returns true on // success and false on error. func (s *String) ReadUint24LengthPrefixed(out *String) bool { return s.readLengthPrefixed(3, out) } // ReadBytes reads n bytes into out and advances over them. It returns true on // success and false and error. func (s *String) ReadBytes(out *[]byte, n int) bool { v := s.read(n) if v == nil { return false } *out = v return true } // CopyBytes copies len(out) bytes into out and advances over them. It returns // true on success and false on error. func (s *String) CopyBytes(out []byte) bool { n := len(out) v := s.read(n) if v == nil { return false } return copy(out, v) == n } // Empty reports whether the string does not contain any bytes. func (s String) Empty() bool { return len(s) == 0 } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/example_test.go����������������������������������0000644�0610621�0607500�00000007714�13172163317�026310� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cryptobyte_test import ( "errors" "fmt" "golang.org/x/crypto/cryptobyte" "golang.org/x/crypto/cryptobyte/asn1" ) func ExampleString_lengthPrefixed() { // This is an example of parsing length-prefixed data (as found in, for // example, TLS). Imagine a 16-bit prefixed series of 8-bit prefixed // strings. input := cryptobyte.String([]byte{0, 12, 5, 'h', 'e', 'l', 'l', 'o', 5, 'w', 'o', 'r', 'l', 'd'}) var result []string var values cryptobyte.String if !input.ReadUint16LengthPrefixed(&values) || !input.Empty() { panic("bad format") } for !values.Empty() { var value cryptobyte.String if !values.ReadUint8LengthPrefixed(&value) { panic("bad format") } result = append(result, string(value)) } // Output: []string{"hello", "world"} fmt.Printf("%#v\n", result) } func ExampleString_aSN1() { // This is an example of parsing ASN.1 data that looks like: // Foo ::= SEQUENCE { // version [6] INTEGER DEFAULT 0 // data OCTET STRING // } input := cryptobyte.String([]byte{0x30, 12, 0xa6, 3, 2, 1, 2, 4, 5, 'h', 'e', 'l', 'l', 'o'}) var ( version int64 data, inner, versionBytes cryptobyte.String haveVersion bool ) if !input.ReadASN1(&inner, asn1.SEQUENCE) || !input.Empty() || !inner.ReadOptionalASN1(&versionBytes, &haveVersion, asn1.Tag(6).Constructed().ContextSpecific()) || (haveVersion && !versionBytes.ReadASN1Integer(&version)) || (haveVersion && !versionBytes.Empty()) || !inner.ReadASN1(&data, asn1.OCTET_STRING) || !inner.Empty() { panic("bad format") } // Output: haveVersion: true, version: 2, data: hello fmt.Printf("haveVersion: %t, version: %d, data: %s\n", haveVersion, version, string(data)) } func ExampleBuilder_aSN1() { // This is an example of building ASN.1 data that looks like: // Foo ::= SEQUENCE { // version [6] INTEGER DEFAULT 0 // data OCTET STRING // } version := int64(2) data := []byte("hello") const defaultVersion = 0 var b cryptobyte.Builder b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) { if version != defaultVersion { b.AddASN1(asn1.Tag(6).Constructed().ContextSpecific(), func(b *cryptobyte.Builder) { b.AddASN1Int64(version) }) } b.AddASN1OctetString(data) }) result, err := b.Bytes() if err != nil { panic(err) } // Output: 300ca603020102040568656c6c6f fmt.Printf("%x\n", result) } func ExampleBuilder_lengthPrefixed() { // This is an example of building length-prefixed data (as found in, // for example, TLS). Imagine a 16-bit prefixed series of 8-bit // prefixed strings. input := []string{"hello", "world"} var b cryptobyte.Builder b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { for _, value := range input { b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { b.AddBytes([]byte(value)) }) } }) result, err := b.Bytes() if err != nil { panic(err) } // Output: 000c0568656c6c6f05776f726c64 fmt.Printf("%x\n", result) } func ExampleBuilder_lengthPrefixOverflow() { // Writing more data that can be expressed by the length prefix results // in an error from Bytes(). tooLarge := make([]byte, 256) var b cryptobyte.Builder b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { b.AddBytes(tooLarge) }) result, err := b.Bytes() fmt.Printf("len=%d err=%s\n", len(result), err) // Output: len=0 err=cryptobyte: pending child length 256 exceeds 1-byte length prefix } func ExampleBuilderContinuation_errorHandling() { var b cryptobyte.Builder // Continuations that panic with a BuildError will cause Bytes to // return the inner error. b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { b.AddUint32(0) panic(cryptobyte.BuildError{Err: errors.New("example error")}) }) result, err := b.Bytes() fmt.Printf("len=%d err=%s\n", len(result), err) // Output: len=0 err=example error } ����������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/cryptobyte_test.go�������������������������������0000644�0610621�0607500�00000022745�13172163317�027062� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cryptobyte import ( "bytes" "errors" "fmt" "testing" ) func builderBytesEq(b *Builder, want ...byte) error { got := b.BytesOrPanic() if !bytes.Equal(got, want) { return fmt.Errorf("Bytes() = %v, want %v", got, want) } return nil } func TestContinuationError(t *testing.T) { const errorStr = "TestContinuationError" var b Builder b.AddUint8LengthPrefixed(func(b *Builder) { b.AddUint8(1) panic(BuildError{Err: errors.New(errorStr)}) }) ret, err := b.Bytes() if ret != nil { t.Error("expected nil result") } if err == nil { t.Fatal("unexpected nil error") } if s := err.Error(); s != errorStr { t.Errorf("expected error %q, got %v", errorStr, s) } } func TestContinuationNonError(t *testing.T) { defer func() { recover() }() var b Builder b.AddUint8LengthPrefixed(func(b *Builder) { b.AddUint8(1) panic(1) }) t.Error("Builder did not panic") } func TestGeneratedPanic(t *testing.T) { defer func() { recover() }() var b Builder b.AddUint8LengthPrefixed(func(b *Builder) { var p *byte *p = 0 }) t.Error("Builder did not panic") } func TestBytes(t *testing.T) { var b Builder v := []byte("foobarbaz") b.AddBytes(v[0:3]) b.AddBytes(v[3:4]) b.AddBytes(v[4:9]) if err := builderBytesEq(&b, v...); err != nil { t.Error(err) } s := String(b.BytesOrPanic()) for _, w := range []string{"foo", "bar", "baz"} { var got []byte if !s.ReadBytes(&got, 3) { t.Errorf("ReadBytes() = false, want true (w = %v)", w) } want := []byte(w) if !bytes.Equal(got, want) { t.Errorf("ReadBytes(): got = %v, want %v", got, want) } } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } } func TestUint8(t *testing.T) { var b Builder b.AddUint8(42) if err := builderBytesEq(&b, 42); err != nil { t.Error(err) } var s String = b.BytesOrPanic() var v uint8 if !s.ReadUint8(&v) { t.Error("ReadUint8() = false, want true") } if v != 42 { t.Errorf("v = %d, want 42", v) } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } } func TestUint16(t *testing.T) { var b Builder b.AddUint16(65534) if err := builderBytesEq(&b, 255, 254); err != nil { t.Error(err) } var s String = b.BytesOrPanic() var v uint16 if !s.ReadUint16(&v) { t.Error("ReadUint16() == false, want true") } if v != 65534 { t.Errorf("v = %d, want 65534", v) } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } } func TestUint24(t *testing.T) { var b Builder b.AddUint24(0xfffefd) if err := builderBytesEq(&b, 255, 254, 253); err != nil { t.Error(err) } var s String = b.BytesOrPanic() var v uint32 if !s.ReadUint24(&v) { t.Error("ReadUint8() = false, want true") } if v != 0xfffefd { t.Errorf("v = %d, want fffefd", v) } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } } func TestUint24Truncation(t *testing.T) { var b Builder b.AddUint24(0x10111213) if err := builderBytesEq(&b, 0x11, 0x12, 0x13); err != nil { t.Error(err) } } func TestUint32(t *testing.T) { var b Builder b.AddUint32(0xfffefdfc) if err := builderBytesEq(&b, 255, 254, 253, 252); err != nil { t.Error(err) } var s String = b.BytesOrPanic() var v uint32 if !s.ReadUint32(&v) { t.Error("ReadUint8() = false, want true") } if v != 0xfffefdfc { t.Errorf("v = %x, want fffefdfc", v) } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } } func TestUMultiple(t *testing.T) { var b Builder b.AddUint8(23) b.AddUint32(0xfffefdfc) b.AddUint16(42) if err := builderBytesEq(&b, 23, 255, 254, 253, 252, 0, 42); err != nil { t.Error(err) } var s String = b.BytesOrPanic() var ( x uint8 y uint32 z uint16 ) if !s.ReadUint8(&x) || !s.ReadUint32(&y) || !s.ReadUint16(&z) { t.Error("ReadUint8() = false, want true") } if x != 23 || y != 0xfffefdfc || z != 42 { t.Errorf("x, y, z = %d, %d, %d; want 23, 4294901244, 5", x, y, z) } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } } func TestUint8LengthPrefixedSimple(t *testing.T) { var b Builder b.AddUint8LengthPrefixed(func(c *Builder) { c.AddUint8(23) c.AddUint8(42) }) if err := builderBytesEq(&b, 2, 23, 42); err != nil { t.Error(err) } var base, child String = b.BytesOrPanic(), nil var x, y uint8 if !base.ReadUint8LengthPrefixed(&child) || !child.ReadUint8(&x) || !child.ReadUint8(&y) { t.Error("parsing failed") } if x != 23 || y != 42 { t.Errorf("want x, y == 23, 42; got %d, %d", x, y) } if len(base) != 0 { t.Errorf("len(base) = %d, want 0", len(base)) } if len(child) != 0 { t.Errorf("len(child) = %d, want 0", len(child)) } } func TestUint8LengthPrefixedMulti(t *testing.T) { var b Builder b.AddUint8LengthPrefixed(func(c *Builder) { c.AddUint8(23) c.AddUint8(42) }) b.AddUint8(5) b.AddUint8LengthPrefixed(func(c *Builder) { c.AddUint8(123) c.AddUint8(234) }) if err := builderBytesEq(&b, 2, 23, 42, 5, 2, 123, 234); err != nil { t.Error(err) } var s, child String = b.BytesOrPanic(), nil var u, v, w, x, y uint8 if !s.ReadUint8LengthPrefixed(&child) || !child.ReadUint8(&u) || !child.ReadUint8(&v) || !s.ReadUint8(&w) || !s.ReadUint8LengthPrefixed(&child) || !child.ReadUint8(&x) || !child.ReadUint8(&y) { t.Error("parsing failed") } if u != 23 || v != 42 || w != 5 || x != 123 || y != 234 { t.Errorf("u, v, w, x, y = %d, %d, %d, %d, %d; want 23, 42, 5, 123, 234", u, v, w, x, y) } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } if len(child) != 0 { t.Errorf("len(child) = %d, want 0", len(child)) } } func TestUint8LengthPrefixedNested(t *testing.T) { var b Builder b.AddUint8LengthPrefixed(func(c *Builder) { c.AddUint8(5) c.AddUint8LengthPrefixed(func(d *Builder) { d.AddUint8(23) d.AddUint8(42) }) c.AddUint8(123) }) if err := builderBytesEq(&b, 5, 5, 2, 23, 42, 123); err != nil { t.Error(err) } var base, child1, child2 String = b.BytesOrPanic(), nil, nil var u, v, w, x uint8 if !base.ReadUint8LengthPrefixed(&child1) { t.Error("parsing base failed") } if !child1.ReadUint8(&u) || !child1.ReadUint8LengthPrefixed(&child2) || !child1.ReadUint8(&x) { t.Error("parsing child1 failed") } if !child2.ReadUint8(&v) || !child2.ReadUint8(&w) { t.Error("parsing child2 failed") } if u != 5 || v != 23 || w != 42 || x != 123 { t.Errorf("u, v, w, x = %d, %d, %d, %d, want 5, 23, 42, 123", u, v, w, x) } if len(base) != 0 { t.Errorf("len(base) = %d, want 0", len(base)) } if len(child1) != 0 { t.Errorf("len(child1) = %d, want 0", len(child1)) } if len(base) != 0 { t.Errorf("len(child2) = %d, want 0", len(child2)) } } func TestPreallocatedBuffer(t *testing.T) { var buf [5]byte b := NewBuilder(buf[0:0]) b.AddUint8(1) b.AddUint8LengthPrefixed(func(c *Builder) { c.AddUint8(3) c.AddUint8(4) }) b.AddUint16(1286) // Outgrow buf by one byte. want := []byte{1, 2, 3, 4, 0} if !bytes.Equal(buf[:], want) { t.Errorf("buf = %v want %v", buf, want) } if err := builderBytesEq(b, 1, 2, 3, 4, 5, 6); err != nil { t.Error(err) } } func TestWriteWithPendingChild(t *testing.T) { var b Builder b.AddUint8LengthPrefixed(func(c *Builder) { c.AddUint8LengthPrefixed(func(d *Builder) { defer func() { if recover() == nil { t.Errorf("recover() = nil, want error; c.AddUint8() did not panic") } }() c.AddUint8(2) // panics defer func() { if recover() == nil { t.Errorf("recover() = nil, want error; b.AddUint8() did not panic") } }() b.AddUint8(2) // panics }) defer func() { if recover() == nil { t.Errorf("recover() = nil, want error; b.AddUint8() did not panic") } }() b.AddUint8(2) // panics }) } // ASN.1 func TestASN1Int64(t *testing.T) { tests := []struct { in int64 want []byte }{ {-0x800000, []byte{2, 3, 128, 0, 0}}, {-256, []byte{2, 2, 255, 0}}, {-129, []byte{2, 2, 255, 127}}, {-128, []byte{2, 1, 128}}, {-1, []byte{2, 1, 255}}, {0, []byte{2, 1, 0}}, {1, []byte{2, 1, 1}}, {2, []byte{2, 1, 2}}, {127, []byte{2, 1, 127}}, {128, []byte{2, 2, 0, 128}}, {256, []byte{2, 2, 1, 0}}, {0x800000, []byte{2, 4, 0, 128, 0, 0}}, } for i, tt := range tests { var b Builder b.AddASN1Int64(tt.in) if err := builderBytesEq(&b, tt.want...); err != nil { t.Errorf("%v, (i = %d; in = %v)", err, i, tt.in) } var n int64 s := String(b.BytesOrPanic()) ok := s.ReadASN1Integer(&n) if !ok || n != tt.in { t.Errorf("s.ReadASN1Integer(&n) = %v, n = %d; want true, n = %d (i = %d)", ok, n, tt.in, i) } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } } } func TestASN1Uint64(t *testing.T) { tests := []struct { in uint64 want []byte }{ {0, []byte{2, 1, 0}}, {1, []byte{2, 1, 1}}, {2, []byte{2, 1, 2}}, {127, []byte{2, 1, 127}}, {128, []byte{2, 2, 0, 128}}, {256, []byte{2, 2, 1, 0}}, {0x800000, []byte{2, 4, 0, 128, 0, 0}}, {0x7fffffffffffffff, []byte{2, 8, 127, 255, 255, 255, 255, 255, 255, 255}}, {0x8000000000000000, []byte{2, 9, 0, 128, 0, 0, 0, 0, 0, 0, 0}}, {0xffffffffffffffff, []byte{2, 9, 0, 255, 255, 255, 255, 255, 255, 255, 255}}, } for i, tt := range tests { var b Builder b.AddASN1Uint64(tt.in) if err := builderBytesEq(&b, tt.want...); err != nil { t.Errorf("%v, (i = %d; in = %v)", err, i, tt.in) } var n uint64 s := String(b.BytesOrPanic()) ok := s.ReadASN1Integer(&n) if !ok || n != tt.in { t.Errorf("s.ReadASN1Integer(&n) = %v, n = %d; want true, n = %d (i = %d)", ok, n, tt.in, i) } if len(s) != 0 { t.Errorf("len(s) = %d, want 0", len(s)) } } } ���������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/builder.go���������������������������������������0000644�0610621�0607500�00000021115�13172163317�025233� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cryptobyte import ( "errors" "fmt" ) // A Builder builds byte strings from fixed-length and length-prefixed values. // Builders either allocate space as needed, or are ‘fixed’, which means that // they write into a given buffer and produce an error if it's exhausted. // // The zero value is a usable Builder that allocates space as needed. // // Simple values are marshaled and appended to a Builder using methods on the // Builder. Length-prefixed values are marshaled by providing a // BuilderContinuation, which is a function that writes the inner contents of // the value to a given Builder. See the documentation for BuilderContinuation // for details. type Builder struct { err error result []byte fixedSize bool child *Builder offset int pendingLenLen int pendingIsASN1 bool inContinuation *bool } // NewBuilder creates a Builder that appends its output to the given buffer. // Like append(), the slice will be reallocated if its capacity is exceeded. // Use Bytes to get the final buffer. func NewBuilder(buffer []byte) *Builder { return &Builder{ result: buffer, } } // NewFixedBuilder creates a Builder that appends its output into the given // buffer. This builder does not reallocate the output buffer. Writes that // would exceed the buffer's capacity are treated as an error. func NewFixedBuilder(buffer []byte) *Builder { return &Builder{ result: buffer, fixedSize: true, } } // Bytes returns the bytes written by the builder or an error if one has // occurred during during building. func (b *Builder) Bytes() ([]byte, error) { if b.err != nil { return nil, b.err } return b.result[b.offset:], nil } // BytesOrPanic returns the bytes written by the builder or panics if an error // has occurred during building. func (b *Builder) BytesOrPanic() []byte { if b.err != nil { panic(b.err) } return b.result[b.offset:] } // AddUint8 appends an 8-bit value to the byte string. func (b *Builder) AddUint8(v uint8) { b.add(byte(v)) } // AddUint16 appends a big-endian, 16-bit value to the byte string. func (b *Builder) AddUint16(v uint16) { b.add(byte(v>>8), byte(v)) } // AddUint24 appends a big-endian, 24-bit value to the byte string. The highest // byte of the 32-bit input value is silently truncated. func (b *Builder) AddUint24(v uint32) { b.add(byte(v>>16), byte(v>>8), byte(v)) } // AddUint32 appends a big-endian, 32-bit value to the byte string. func (b *Builder) AddUint32(v uint32) { b.add(byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) } // AddBytes appends a sequence of bytes to the byte string. func (b *Builder) AddBytes(v []byte) { b.add(v...) } // BuilderContinuation is continuation-passing interface for building // length-prefixed byte sequences. Builder methods for length-prefixed // sequences (AddUint8LengthPrefixed etc) will invoke the BuilderContinuation // supplied to them. The child builder passed to the continuation can be used // to build the content of the length-prefixed sequence. For example: // // parent := cryptobyte.NewBuilder() // parent.AddUint8LengthPrefixed(func (child *Builder) { // child.AddUint8(42) // child.AddUint8LengthPrefixed(func (grandchild *Builder) { // grandchild.AddUint8(5) // }) // }) // // It is an error to write more bytes to the child than allowed by the reserved // length prefix. After the continuation returns, the child must be considered // invalid, i.e. users must not store any copies or references of the child // that outlive the continuation. // // If the continuation panics with a value of type BuildError then the inner // error will be returned as the error from Bytes. If the child panics // otherwise then Bytes will repanic with the same value. type BuilderContinuation func(child *Builder) // BuildError wraps an error. If a BuilderContinuation panics with this value, // the panic will be recovered and the inner error will be returned from // Builder.Bytes. type BuildError struct { Err error } // AddUint8LengthPrefixed adds a 8-bit length-prefixed byte sequence. func (b *Builder) AddUint8LengthPrefixed(f BuilderContinuation) { b.addLengthPrefixed(1, false, f) } // AddUint16LengthPrefixed adds a big-endian, 16-bit length-prefixed byte sequence. func (b *Builder) AddUint16LengthPrefixed(f BuilderContinuation) { b.addLengthPrefixed(2, false, f) } // AddUint24LengthPrefixed adds a big-endian, 24-bit length-prefixed byte sequence. func (b *Builder) AddUint24LengthPrefixed(f BuilderContinuation) { b.addLengthPrefixed(3, false, f) } // AddUint32LengthPrefixed adds a big-endian, 32-bit length-prefixed byte sequence. func (b *Builder) AddUint32LengthPrefixed(f BuilderContinuation) { b.addLengthPrefixed(4, false, f) } func (b *Builder) callContinuation(f BuilderContinuation, arg *Builder) { if !*b.inContinuation { *b.inContinuation = true defer func() { *b.inContinuation = false r := recover() if r == nil { return } if buildError, ok := r.(BuildError); ok { b.err = buildError.Err } else { panic(r) } }() } f(arg) } func (b *Builder) addLengthPrefixed(lenLen int, isASN1 bool, f BuilderContinuation) { // Subsequent writes can be ignored if the builder has encountered an error. if b.err != nil { return } offset := len(b.result) b.add(make([]byte, lenLen)...) if b.inContinuation == nil { b.inContinuation = new(bool) } b.child = &Builder{ result: b.result, fixedSize: b.fixedSize, offset: offset, pendingLenLen: lenLen, pendingIsASN1: isASN1, inContinuation: b.inContinuation, } b.callContinuation(f, b.child) b.flushChild() if b.child != nil { panic("cryptobyte: internal error") } } func (b *Builder) flushChild() { if b.child == nil { return } b.child.flushChild() child := b.child b.child = nil if child.err != nil { b.err = child.err return } length := len(child.result) - child.pendingLenLen - child.offset if length < 0 { panic("cryptobyte: internal error") // result unexpectedly shrunk } if child.pendingIsASN1 { // For ASN.1, we reserved a single byte for the length. If that turned out // to be incorrect, we have to move the contents along in order to make // space. if child.pendingLenLen != 1 { panic("cryptobyte: internal error") } var lenLen, lenByte uint8 if int64(length) > 0xfffffffe { b.err = errors.New("pending ASN.1 child too long") return } else if length > 0xffffff { lenLen = 5 lenByte = 0x80 | 4 } else if length > 0xffff { lenLen = 4 lenByte = 0x80 | 3 } else if length > 0xff { lenLen = 3 lenByte = 0x80 | 2 } else if length > 0x7f { lenLen = 2 lenByte = 0x80 | 1 } else { lenLen = 1 lenByte = uint8(length) length = 0 } // Insert the initial length byte, make space for successive length bytes, // and adjust the offset. child.result[child.offset] = lenByte extraBytes := int(lenLen - 1) if extraBytes != 0 { child.add(make([]byte, extraBytes)...) childStart := child.offset + child.pendingLenLen copy(child.result[childStart+extraBytes:], child.result[childStart:]) } child.offset++ child.pendingLenLen = extraBytes } l := length for i := child.pendingLenLen - 1; i >= 0; i-- { child.result[child.offset+i] = uint8(l) l >>= 8 } if l != 0 { b.err = fmt.Errorf("cryptobyte: pending child length %d exceeds %d-byte length prefix", length, child.pendingLenLen) return } if !b.fixedSize { b.result = child.result // In case child reallocated result. } } func (b *Builder) add(bytes ...byte) { if b.err != nil { return } if b.child != nil { panic("attempted write while child is pending") } if len(b.result)+len(bytes) < len(bytes) { b.err = errors.New("cryptobyte: length overflow") } if b.fixedSize && len(b.result)+len(bytes) > cap(b.result) { b.err = errors.New("cryptobyte: Builder is exceeding its fixed-size buffer") return } b.result = append(b.result, bytes...) } // A MarshalingValue marshals itself into a Builder. type MarshalingValue interface { // Marshal is called by Builder.AddValue. It receives a pointer to a builder // to marshal itself into. It may return an error that occurred during // marshaling, such as unset or invalid values. Marshal(b *Builder) error } // AddValue calls Marshal on v, passing a pointer to the builder to append to. // If Marshal returns an error, it is set on the Builder so that subsequent // appends don't have an effect. func (b *Builder) AddValue(v MarshalingValue) { err := v.Marshal(b) if err != nil { b.err = err } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/asn1_test.go�������������������������������������0000644�0610621�0607500�00000023164�13172163317�025514� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cryptobyte import ( "bytes" encoding_asn1 "encoding/asn1" "math/big" "reflect" "testing" "time" "golang.org/x/crypto/cryptobyte/asn1" ) type readASN1Test struct { name string in []byte tag asn1.Tag ok bool out interface{} } var readASN1TestData = []readASN1Test{ {"valid", []byte{0x30, 2, 1, 2}, 0x30, true, []byte{1, 2}}, {"truncated", []byte{0x30, 3, 1, 2}, 0x30, false, nil}, {"zero length of length", []byte{0x30, 0x80}, 0x30, false, nil}, {"invalid long form length", []byte{0x30, 0x81, 1, 1}, 0x30, false, nil}, {"non-minimal length", append([]byte{0x30, 0x82, 0, 0x80}, make([]byte, 0x80)...), 0x30, false, nil}, {"invalid tag", []byte{0xa1, 3, 0x4, 1, 1}, 31, false, nil}, {"high tag", []byte{0x1f, 0x81, 0x80, 0x01, 2, 1, 2}, 0xff /* actually 0x4001, but tag is uint8 */, false, nil}, } func TestReadASN1(t *testing.T) { for _, test := range readASN1TestData { t.Run(test.name, func(t *testing.T) { var in, out String = test.in, nil ok := in.ReadASN1(&out, test.tag) if ok != test.ok || ok && !bytes.Equal(out, test.out.([]byte)) { t.Errorf("in.ReadASN1() = %v, want %v; out = %v, want %v", ok, test.ok, out, test.out) } }) } } func TestReadASN1Optional(t *testing.T) { var empty String var present bool ok := empty.ReadOptionalASN1(nil, &present, 0xa0) if !ok || present { t.Errorf("empty.ReadOptionalASN1() = %v, want true; present = %v want false", ok, present) } var in, out String = []byte{0xa1, 3, 0x4, 1, 1}, nil ok = in.ReadOptionalASN1(&out, &present, 0xa0) if !ok || present { t.Errorf("in.ReadOptionalASN1() = %v, want true, present = %v, want false", ok, present) } ok = in.ReadOptionalASN1(&out, &present, 0xa1) wantBytes := []byte{4, 1, 1} if !ok || !present || !bytes.Equal(out, wantBytes) { t.Errorf("in.ReadOptionalASN1() = %v, want true; present = %v, want true; out = %v, want = %v", ok, present, out, wantBytes) } } var optionalOctetStringTestData = []struct { readASN1Test present bool }{ {readASN1Test{"empty", []byte{}, 0xa0, true, []byte{}}, false}, {readASN1Test{"invalid", []byte{0xa1, 3, 0x4, 2, 1}, 0xa1, false, []byte{}}, true}, {readASN1Test{"missing", []byte{0xa1, 3, 0x4, 1, 1}, 0xa0, true, []byte{}}, false}, {readASN1Test{"present", []byte{0xa1, 3, 0x4, 1, 1}, 0xa1, true, []byte{1}}, true}, } func TestReadASN1OptionalOctetString(t *testing.T) { for _, test := range optionalOctetStringTestData { t.Run(test.name, func(t *testing.T) { in := String(test.in) var out []byte var present bool ok := in.ReadOptionalASN1OctetString(&out, &present, test.tag) if ok != test.ok || present != test.present || !bytes.Equal(out, test.out.([]byte)) { t.Errorf("in.ReadOptionalASN1OctetString() = %v, want %v; present = %v want %v; out = %v, want %v", ok, test.ok, present, test.present, out, test.out) } }) } } const defaultInt = -1 var optionalIntTestData = []readASN1Test{ {"empty", []byte{}, 0xa0, true, defaultInt}, {"invalid", []byte{0xa1, 3, 0x2, 2, 127}, 0xa1, false, 0}, {"missing", []byte{0xa1, 3, 0x2, 1, 127}, 0xa0, true, defaultInt}, {"present", []byte{0xa1, 3, 0x2, 1, 42}, 0xa1, true, 42}, } func TestReadASN1OptionalInteger(t *testing.T) { for _, test := range optionalIntTestData { t.Run(test.name, func(t *testing.T) { in := String(test.in) var out int ok := in.ReadOptionalASN1Integer(&out, test.tag, defaultInt) if ok != test.ok || ok && out != test.out.(int) { t.Errorf("in.ReadOptionalASN1Integer() = %v, want %v; out = %v, want %v", ok, test.ok, out, test.out) } }) } } func TestReadASN1IntegerSigned(t *testing.T) { testData64 := []struct { in []byte out int64 }{ {[]byte{2, 3, 128, 0, 0}, -0x800000}, {[]byte{2, 2, 255, 0}, -256}, {[]byte{2, 2, 255, 127}, -129}, {[]byte{2, 1, 128}, -128}, {[]byte{2, 1, 255}, -1}, {[]byte{2, 1, 0}, 0}, {[]byte{2, 1, 1}, 1}, {[]byte{2, 1, 2}, 2}, {[]byte{2, 1, 127}, 127}, {[]byte{2, 2, 0, 128}, 128}, {[]byte{2, 2, 1, 0}, 256}, {[]byte{2, 4, 0, 128, 0, 0}, 0x800000}, } for i, test := range testData64 { in := String(test.in) var out int64 ok := in.ReadASN1Integer(&out) if !ok || out != test.out { t.Errorf("#%d: in.ReadASN1Integer() = %v, want true; out = %d, want %d", i, ok, out, test.out) } } // Repeat the same cases, reading into a big.Int. t.Run("big.Int", func(t *testing.T) { for i, test := range testData64 { in := String(test.in) var out big.Int ok := in.ReadASN1Integer(&out) if !ok || out.Int64() != test.out { t.Errorf("#%d: in.ReadASN1Integer() = %v, want true; out = %d, want %d", i, ok, out.Int64(), test.out) } } }) } func TestReadASN1IntegerUnsigned(t *testing.T) { testData := []struct { in []byte out uint64 }{ {[]byte{2, 1, 0}, 0}, {[]byte{2, 1, 1}, 1}, {[]byte{2, 1, 2}, 2}, {[]byte{2, 1, 127}, 127}, {[]byte{2, 2, 0, 128}, 128}, {[]byte{2, 2, 1, 0}, 256}, {[]byte{2, 4, 0, 128, 0, 0}, 0x800000}, {[]byte{2, 8, 127, 255, 255, 255, 255, 255, 255, 255}, 0x7fffffffffffffff}, {[]byte{2, 9, 0, 128, 0, 0, 0, 0, 0, 0, 0}, 0x8000000000000000}, {[]byte{2, 9, 0, 255, 255, 255, 255, 255, 255, 255, 255}, 0xffffffffffffffff}, } for i, test := range testData { in := String(test.in) var out uint64 ok := in.ReadASN1Integer(&out) if !ok || out != test.out { t.Errorf("#%d: in.ReadASN1Integer() = %v, want true; out = %d, want %d", i, ok, out, test.out) } } } func TestReadASN1IntegerInvalid(t *testing.T) { testData := []String{ []byte{3, 1, 0}, // invalid tag // truncated []byte{2, 1}, []byte{2, 2, 0}, // not minimally encoded []byte{2, 2, 0, 1}, []byte{2, 2, 0xff, 0xff}, } for i, test := range testData { var out int64 if test.ReadASN1Integer(&out) { t.Errorf("#%d: in.ReadASN1Integer() = true, want false (out = %d)", i, out) } } } func TestASN1ObjectIdentifier(t *testing.T) { testData := []struct { in []byte ok bool out []int }{ {[]byte{}, false, []int{}}, {[]byte{6, 0}, false, []int{}}, {[]byte{5, 1, 85}, false, []int{2, 5}}, {[]byte{6, 1, 85}, true, []int{2, 5}}, {[]byte{6, 2, 85, 0x02}, true, []int{2, 5, 2}}, {[]byte{6, 4, 85, 0x02, 0xc0, 0x00}, true, []int{2, 5, 2, 0x2000}}, {[]byte{6, 3, 0x81, 0x34, 0x03}, true, []int{2, 100, 3}}, {[]byte{6, 7, 85, 0x02, 0xc0, 0x80, 0x80, 0x80, 0x80}, false, []int{}}, } for i, test := range testData { in := String(test.in) var out encoding_asn1.ObjectIdentifier ok := in.ReadASN1ObjectIdentifier(&out) if ok != test.ok || ok && !out.Equal(test.out) { t.Errorf("#%d: in.ReadASN1ObjectIdentifier() = %v, want %v; out = %v, want %v", i, ok, test.ok, out, test.out) continue } var b Builder b.AddASN1ObjectIdentifier(out) result, err := b.Bytes() if builderOk := err == nil; test.ok != builderOk { t.Errorf("#%d: error from Builder.Bytes: %s", i, err) continue } if test.ok && !bytes.Equal(result, test.in) { t.Errorf("#%d: reserialisation didn't match, got %x, want %x", i, result, test.in) continue } } } func TestReadASN1GeneralizedTime(t *testing.T) { testData := []struct { in string ok bool out time.Time }{ {"20100102030405Z", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.UTC)}, {"20100102030405", false, time.Time{}}, {"20100102030405+0607", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.FixedZone("", 6*60*60+7*60))}, {"20100102030405-0607", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.FixedZone("", -6*60*60-7*60))}, /* These are invalid times. However, the time package normalises times * and they were accepted in some versions. See #11134. */ {"00000100000000Z", false, time.Time{}}, {"20101302030405Z", false, time.Time{}}, {"20100002030405Z", false, time.Time{}}, {"20100100030405Z", false, time.Time{}}, {"20100132030405Z", false, time.Time{}}, {"20100231030405Z", false, time.Time{}}, {"20100102240405Z", false, time.Time{}}, {"20100102036005Z", false, time.Time{}}, {"20100102030460Z", false, time.Time{}}, {"-20100102030410Z", false, time.Time{}}, {"2010-0102030410Z", false, time.Time{}}, {"2010-0002030410Z", false, time.Time{}}, {"201001-02030410Z", false, time.Time{}}, {"20100102-030410Z", false, time.Time{}}, {"2010010203-0410Z", false, time.Time{}}, {"201001020304-10Z", false, time.Time{}}, } for i, test := range testData { in := String(append([]byte{byte(asn1.GeneralizedTime), byte(len(test.in))}, test.in...)) var out time.Time ok := in.ReadASN1GeneralizedTime(&out) if ok != test.ok || ok && !reflect.DeepEqual(out, test.out) { t.Errorf("#%d: in.ReadASN1GeneralizedTime() = %v, want %v; out = %q, want %q", i, ok, test.ok, out, test.out) } } } func TestReadASN1BitString(t *testing.T) { testData := []struct { in []byte ok bool out encoding_asn1.BitString }{ {[]byte{}, false, encoding_asn1.BitString{}}, {[]byte{0x00}, true, encoding_asn1.BitString{}}, {[]byte{0x07, 0x00}, true, encoding_asn1.BitString{Bytes: []byte{0}, BitLength: 1}}, {[]byte{0x07, 0x01}, false, encoding_asn1.BitString{}}, {[]byte{0x07, 0x40}, false, encoding_asn1.BitString{}}, {[]byte{0x08, 0x00}, false, encoding_asn1.BitString{}}, {[]byte{0xff}, false, encoding_asn1.BitString{}}, {[]byte{0xfe, 0x00}, false, encoding_asn1.BitString{}}, } for i, test := range testData { in := String(append([]byte{3, byte(len(test.in))}, test.in...)) var out encoding_asn1.BitString ok := in.ReadASN1BitString(&out) if ok != test.ok || ok && (!bytes.Equal(out.Bytes, test.out.Bytes) || out.BitLength != test.out.BitLength) { t.Errorf("#%d: in.ReadASN1BitString() = %v, want %v; out = %v, want %v", i, ok, test.ok, out, test.out) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/asn1/��������������������������������������������0000755�0610621�0607500�00000000000�13172163317�024120� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/asn1/asn1.go�������������������������������������0000644�0610621�0607500�00000003073�13172163317�025314� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package asn1 contains supporting types for parsing and building ASN.1 // messages with the cryptobyte package. package asn1 // import "golang.org/x/crypto/cryptobyte/asn1" // Tag represents an ASN.1 identifier octet, consisting of a tag number // (indicating a type) and class (such as context-specific or constructed). // // Methods in the cryptobyte package only support the low-tag-number form, i.e. // a single identifier octet with bits 7-8 encoding the class and bits 1-6 // encoding the tag number. type Tag uint8 const ( classConstructed = 0x20 classContextSpecific = 0x80 ) // Constructed returns t with the constructed class bit set. func (t Tag) Constructed() Tag { return t | classConstructed } // ContextSpecific returns t with the context-specific class bit set. func (t Tag) ContextSpecific() Tag { return t | classContextSpecific } // The following is a list of standard tag and class combinations. const ( BOOLEAN = Tag(1) INTEGER = Tag(2) BIT_STRING = Tag(3) OCTET_STRING = Tag(4) NULL = Tag(5) OBJECT_IDENTIFIER = Tag(6) ENUM = Tag(10) UTF8String = Tag(12) SEQUENCE = Tag(16 | classConstructed) SET = Tag(17 | classConstructed) PrintableString = Tag(19) T61String = Tag(20) IA5String = Tag(22) UTCTime = Tag(23) GeneralizedTime = Tag(24) GeneralString = Tag(27) ) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cryptobyte/asn1.go������������������������������������������0000644�0610621�0607500�00000045513�13172163317�024457� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cryptobyte import ( encoding_asn1 "encoding/asn1" "fmt" "math/big" "reflect" "time" "golang.org/x/crypto/cryptobyte/asn1" ) // This file contains ASN.1-related methods for String and Builder. // Builder // AddASN1Int64 appends a DER-encoded ASN.1 INTEGER. func (b *Builder) AddASN1Int64(v int64) { b.addASN1Signed(asn1.INTEGER, v) } // AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION. func (b *Builder) AddASN1Enum(v int64) { b.addASN1Signed(asn1.ENUM, v) } func (b *Builder) addASN1Signed(tag asn1.Tag, v int64) { b.AddASN1(tag, func(c *Builder) { length := 1 for i := v; i >= 0x80 || i < -0x80; i >>= 8 { length++ } for ; length > 0; length-- { i := v >> uint((length-1)*8) & 0xff c.AddUint8(uint8(i)) } }) } // AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER. func (b *Builder) AddASN1Uint64(v uint64) { b.AddASN1(asn1.INTEGER, func(c *Builder) { length := 1 for i := v; i >= 0x80; i >>= 8 { length++ } for ; length > 0; length-- { i := v >> uint((length-1)*8) & 0xff c.AddUint8(uint8(i)) } }) } // AddASN1BigInt appends a DER-encoded ASN.1 INTEGER. func (b *Builder) AddASN1BigInt(n *big.Int) { if b.err != nil { return } b.AddASN1(asn1.INTEGER, func(c *Builder) { if n.Sign() < 0 { // A negative number has to be converted to two's-complement form. So we // invert and subtract 1. If the most-significant-bit isn't set then // we'll need to pad the beginning with 0xff in order to keep the number // negative. nMinus1 := new(big.Int).Neg(n) nMinus1.Sub(nMinus1, bigOne) bytes := nMinus1.Bytes() for i := range bytes { bytes[i] ^= 0xff } if bytes[0]&0x80 == 0 { c.add(0xff) } c.add(bytes...) } else if n.Sign() == 0 { c.add(0) } else { bytes := n.Bytes() if bytes[0]&0x80 != 0 { c.add(0) } c.add(bytes...) } }) } // AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING. func (b *Builder) AddASN1OctetString(bytes []byte) { b.AddASN1(asn1.OCTET_STRING, func(c *Builder) { c.AddBytes(bytes) }) } const generalizedTimeFormatStr = "20060102150405Z0700" // AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME. func (b *Builder) AddASN1GeneralizedTime(t time.Time) { if t.Year() < 0 || t.Year() > 9999 { b.err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", t) return } b.AddASN1(asn1.GeneralizedTime, func(c *Builder) { c.AddBytes([]byte(t.Format(generalizedTimeFormatStr))) }) } // AddASN1BitString appends a DER-encoded ASN.1 BIT STRING. This does not // support BIT STRINGs that are not a whole number of bytes. func (b *Builder) AddASN1BitString(data []byte) { b.AddASN1(asn1.BIT_STRING, func(b *Builder) { b.AddUint8(0) b.AddBytes(data) }) } func (b *Builder) addBase128Int(n int64) { var length int if n == 0 { length = 1 } else { for i := n; i > 0; i >>= 7 { length++ } } for i := length - 1; i >= 0; i-- { o := byte(n >> uint(i*7)) o &= 0x7f if i != 0 { o |= 0x80 } b.add(o) } } func isValidOID(oid encoding_asn1.ObjectIdentifier) bool { if len(oid) < 2 { return false } if oid[0] > 2 || (oid[0] <= 1 && oid[1] >= 40) { return false } for _, v := range oid { if v < 0 { return false } } return true } func (b *Builder) AddASN1ObjectIdentifier(oid encoding_asn1.ObjectIdentifier) { b.AddASN1(asn1.OBJECT_IDENTIFIER, func(b *Builder) { if !isValidOID(oid) { b.err = fmt.Errorf("cryptobyte: invalid OID: %v", oid) return } b.addBase128Int(int64(oid[0])*40 + int64(oid[1])) for _, v := range oid[2:] { b.addBase128Int(int64(v)) } }) } func (b *Builder) AddASN1Boolean(v bool) { b.AddASN1(asn1.BOOLEAN, func(b *Builder) { if v { b.AddUint8(0xff) } else { b.AddUint8(0) } }) } func (b *Builder) AddASN1NULL() { b.add(uint8(asn1.NULL), 0) } // MarshalASN1 calls encoding_asn1.Marshal on its input and appends the result if // successful or records an error if one occurred. func (b *Builder) MarshalASN1(v interface{}) { // NOTE(martinkr): This is somewhat of a hack to allow propagation of // encoding_asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a // value embedded into a struct, its tag information is lost. if b.err != nil { return } bytes, err := encoding_asn1.Marshal(v) if err != nil { b.err = err return } b.AddBytes(bytes) } // AddASN1 appends an ASN.1 object. The object is prefixed with the given tag. // Tags greater than 30 are not supported and result in an error (i.e. // low-tag-number form only). The child builder passed to the // BuilderContinuation can be used to build the content of the ASN.1 object. func (b *Builder) AddASN1(tag asn1.Tag, f BuilderContinuation) { if b.err != nil { return } // Identifiers with the low five bits set indicate high-tag-number format // (two or more octets), which we don't support. if tag&0x1f == 0x1f { b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag) return } b.AddUint8(uint8(tag)) b.addLengthPrefixed(1, true, f) } // String func (s *String) ReadASN1Boolean(out *bool) bool { var bytes String if !s.ReadASN1(&bytes, asn1.INTEGER) || len(bytes) != 1 { return false } switch bytes[0] { case 0: *out = false case 0xff: *out = true default: return false } return true } var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem() // ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does // not point to an integer or to a big.Int, it panics. It returns true on // success and false on error. func (s *String) ReadASN1Integer(out interface{}) bool { if reflect.TypeOf(out).Kind() != reflect.Ptr { panic("out is not a pointer") } switch reflect.ValueOf(out).Elem().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: var i int64 if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) { return false } reflect.ValueOf(out).Elem().SetInt(i) return true case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: var u uint64 if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) { return false } reflect.ValueOf(out).Elem().SetUint(u) return true case reflect.Struct: if reflect.TypeOf(out).Elem() == bigIntType { return s.readASN1BigInt(out.(*big.Int)) } } panic("out does not point to an integer type") } func checkASN1Integer(bytes []byte) bool { if len(bytes) == 0 { // An INTEGER is encoded with at least one octet. return false } if len(bytes) == 1 { return true } if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 { // Value is not minimally encoded. return false } return true } var bigOne = big.NewInt(1) func (s *String) readASN1BigInt(out *big.Int) bool { var bytes String if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) { return false } if bytes[0]&0x80 == 0x80 { // Negative number. neg := make([]byte, len(bytes)) for i, b := range bytes { neg[i] = ^b } out.SetBytes(neg) out.Add(out, bigOne) out.Neg(out) } else { out.SetBytes(bytes) } return true } func (s *String) readASN1Int64(out *int64) bool { var bytes String if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) { return false } return true } func asn1Signed(out *int64, n []byte) bool { length := len(n) if length > 8 { return false } for i := 0; i < length; i++ { *out <<= 8 *out |= int64(n[i]) } // Shift up and down in order to sign extend the result. *out <<= 64 - uint8(length)*8 *out >>= 64 - uint8(length)*8 return true } func (s *String) readASN1Uint64(out *uint64) bool { var bytes String if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) { return false } return true } func asn1Unsigned(out *uint64, n []byte) bool { length := len(n) if length > 9 || length == 9 && n[0] != 0 { // Too large for uint64. return false } if n[0]&0x80 != 0 { // Negative number. return false } for i := 0; i < length; i++ { *out <<= 8 *out |= uint64(n[i]) } return true } // ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It returns // true on success and false on error. func (s *String) ReadASN1Enum(out *int) bool { var bytes String var i int64 if !s.ReadASN1(&bytes, asn1.ENUM) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) { return false } if int64(int(i)) != i { return false } *out = int(i) return true } func (s *String) readBase128Int(out *int) bool { ret := 0 for i := 0; len(*s) > 0; i++ { if i == 4 { return false } ret <<= 7 b := s.read(1)[0] ret |= int(b & 0x7f) if b&0x80 == 0 { *out = ret return true } } return false // truncated } // ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and // advances. It returns true on success and false on error. func (s *String) ReadASN1ObjectIdentifier(out *encoding_asn1.ObjectIdentifier) bool { var bytes String if !s.ReadASN1(&bytes, asn1.OBJECT_IDENTIFIER) || len(bytes) == 0 { return false } // In the worst case, we get two elements from the first byte (which is // encoded differently) and then every varint is a single byte long. components := make([]int, len(bytes)+1) // The first varint is 40*value1 + value2: // According to this packing, value1 can take the values 0, 1 and 2 only. // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2, // then there are no restrictions on value2. var v int if !bytes.readBase128Int(&v) { return false } if v < 80 { components[0] = v / 40 components[1] = v % 40 } else { components[0] = 2 components[1] = v - 80 } i := 2 for ; len(bytes) > 0; i++ { if !bytes.readBase128Int(&v) { return false } components[i] = v } *out = components[:i] return true } // ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and // advances. It returns true on success and false on error. func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool { var bytes String if !s.ReadASN1(&bytes, asn1.GeneralizedTime) { return false } t := string(bytes) res, err := time.Parse(generalizedTimeFormatStr, t) if err != nil { return false } if serialized := res.Format(generalizedTimeFormatStr); serialized != t { return false } *out = res return true } // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It // returns true on success and false on error. func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool { var bytes String if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 { return false } paddingBits := uint8(bytes[0]) bytes = bytes[1:] if paddingBits > 7 || len(bytes) == 0 && paddingBits != 0 || len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 { return false } out.BitLength = len(bytes)*8 - int(paddingBits) out.Bytes = bytes return true } // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It is // an error if the BIT STRING is not a whole number of bytes. This function // returns true on success and false on error. func (s *String) ReadASN1BitStringAsBytes(out *[]byte) bool { var bytes String if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 { return false } paddingBits := uint8(bytes[0]) if paddingBits != 0 { return false } *out = bytes[1:] return true } // ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including // tag and length bytes) into out, and advances. The element must match the // given tag. It returns true on success and false on error. func (s *String) ReadASN1Bytes(out *[]byte, tag asn1.Tag) bool { return s.ReadASN1((*String)(out), tag) } // ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including // tag and length bytes) into out, and advances. The element must match the // given tag. It returns true on success and false on error. // // Tags greater than 30 are not supported (i.e. low-tag-number format only). func (s *String) ReadASN1(out *String, tag asn1.Tag) bool { var t asn1.Tag if !s.ReadAnyASN1(out, &t) || t != tag { return false } return true } // ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including // tag and length bytes) into out, and advances. The element must match the // given tag. It returns true on success and false on error. // // Tags greater than 30 are not supported (i.e. low-tag-number format only). func (s *String) ReadASN1Element(out *String, tag asn1.Tag) bool { var t asn1.Tag if !s.ReadAnyASN1Element(out, &t) || t != tag { return false } return true } // ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including // tag and length bytes) into out, sets outTag to its tag, and advances. It // returns true on success and false on error. // // Tags greater than 30 are not supported (i.e. low-tag-number format only). func (s *String) ReadAnyASN1(out *String, outTag *asn1.Tag) bool { return s.readASN1(out, outTag, true /* skip header */) } // ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element // (including tag and length bytes) into out, sets outTag to is tag, and // advances. It returns true on success and false on error. // // Tags greater than 30 are not supported (i.e. low-tag-number format only). func (s *String) ReadAnyASN1Element(out *String, outTag *asn1.Tag) bool { return s.readASN1(out, outTag, false /* include header */) } // PeekASN1Tag returns true if the next ASN.1 value on the string starts with // the given tag. func (s String) PeekASN1Tag(tag asn1.Tag) bool { if len(s) == 0 { return false } return asn1.Tag(s[0]) == tag } // SkipASN1 reads and discards an ASN.1 element with the given tag. func (s *String) SkipASN1(tag asn1.Tag) bool { var unused String return s.ReadASN1(&unused, tag) } // ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.1 // element (not including tag and length bytes) tagged with the given tag into // out. It stores whether an element with the tag was found in outPresent, // unless outPresent is nil. It returns true on success and false on error. func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag asn1.Tag) bool { present := s.PeekASN1Tag(tag) if outPresent != nil { *outPresent = present } if present && !s.ReadASN1(out, tag) { return false } return true } // SkipOptionalASN1 advances s over an ASN.1 element with the given tag, or // else leaves s unchanged. func (s *String) SkipOptionalASN1(tag asn1.Tag) bool { if !s.PeekASN1Tag(tag) { return true } var unused String return s.ReadASN1(&unused, tag) } // ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER // explicitly tagged with tag into out and advances. If no element with a // matching tag is present, it writes defaultValue into out instead. If out // does not point to an integer or to a big.Int, it panics. It returns true on // success and false on error. func (s *String) ReadOptionalASN1Integer(out interface{}, tag asn1.Tag, defaultValue interface{}) bool { if reflect.TypeOf(out).Kind() != reflect.Ptr { panic("out is not a pointer") } var present bool var i String if !s.ReadOptionalASN1(&i, &present, tag) { return false } if !present { switch reflect.ValueOf(out).Elem().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue)) case reflect.Struct: if reflect.TypeOf(out).Elem() != bigIntType { panic("invalid integer type") } if reflect.TypeOf(defaultValue).Kind() != reflect.Ptr || reflect.TypeOf(defaultValue).Elem() != bigIntType { panic("out points to big.Int, but defaultValue does not") } out.(*big.Int).Set(defaultValue.(*big.Int)) default: panic("invalid integer type") } return true } if !i.ReadASN1Integer(out) || !i.Empty() { return false } return true } // ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING // explicitly tagged with tag into out and advances. If no element with a // matching tag is present, it writes defaultValue into out instead. It returns // true on success and false on error. func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag asn1.Tag) bool { var present bool var child String if !s.ReadOptionalASN1(&child, &present, tag) { return false } if outPresent != nil { *outPresent = present } if present { var oct String if !child.ReadASN1(&oct, asn1.OCTET_STRING) || !child.Empty() { return false } *out = oct } else { *out = nil } return true } // ReadOptionalASN1Boolean sets *out to the value of the next ASN.1 BOOLEAN or, // if the next bytes are not an ASN.1 BOOLEAN, to the value of defaultValue. func (s *String) ReadOptionalASN1Boolean(out *bool, defaultValue bool) bool { var present bool var child String if !s.ReadOptionalASN1(&child, &present, asn1.BOOLEAN) { return false } if !present { *out = defaultValue return true } return s.ReadASN1Boolean(out) } func (s *String) readASN1(out *String, outTag *asn1.Tag, skipHeader bool) bool { if len(*s) < 2 { return false } tag, lenByte := (*s)[0], (*s)[1] if tag&0x1f == 0x1f { // ITU-T X.690 section 8.1.2 // // An identifier octet with a tag part of 0x1f indicates a high-tag-number // form identifier with two or more octets. We only support tags less than // 31 (i.e. low-tag-number form, single octet identifier). return false } if outTag != nil { *outTag = asn1.Tag(tag) } // ITU-T X.690 section 8.1.3 // // Bit 8 of the first length byte indicates whether the length is short- or // long-form. var length, headerLen uint32 // length includes headerLen if lenByte&0x80 == 0 { // Short-form length (section 8.1.3.4), encoded in bits 1-7. length = uint32(lenByte) + 2 headerLen = 2 } else { // Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets // used to encode the length. lenLen := lenByte & 0x7f var len32 uint32 if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) { return false } lenBytes := String((*s)[2 : 2+lenLen]) if !lenBytes.readUnsigned(&len32, int(lenLen)) { return false } // ITU-T X.690 section 10.1 (DER length forms) requires encoding the length // with the minimum number of octets. if len32 < 128 { // Length should have used short-form encoding. return false } if len32>>((lenLen-1)*8) == 0 { // Leading octet is 0. Length should have been at least one byte shorter. return false } headerLen = 2 + uint32(lenLen) if headerLen+len32 < len32 { // Overflow. return false } length = headerLen + len32 } if uint32(int(length)) != length || !s.ReadBytes((*[]byte)(out), int(length)) { return false } if skipHeader && !out.Skip(int(headerLen)) { panic("cryptobyte: internal error") } return true } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/codereview.cfg����������������������������������������������0000644�0610621�0607500�00000000025�13172163317�023664� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������issuerepo: golang/go �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/�������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023640� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/internal/����������������������������������0000755�0610621�0607500�00000000000�13172163317�025454� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/internal/chacha20/�������������������������0000755�0610621�0607500�00000000000�13172163317�027025� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/internal/chacha20/chacha_test.go�����������0000644�0610621�0607500�00000001615�13172163317�031625� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package chacha20 import ( "encoding/hex" "testing" ) func TestCore(t *testing.T) { // This is just a smoke test that checks the example from // https://tools.ietf.org/html/rfc7539#section-2.3.2. The // chacha20poly1305 package contains much more extensive tests of this // code. var key [32]byte for i := range key { key[i] = byte(i) } var input [16]byte input[0] = 1 input[7] = 9 input[11] = 0x4a var out [64]byte XORKeyStream(out[:], out[:], &input, &key) const expected = "10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4ed2826446079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e" if result := hex.EncodeToString(out[:]); result != expected { t.Errorf("wanted %x but got %x", expected, result) } } �������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/internal/chacha20/chacha_generic.go��������0000644�0610621�0607500�00000011330�13172163317�032255� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ChaCha20 implements the core ChaCha20 function as specified in https://tools.ietf.org/html/rfc7539#section-2.3. package chacha20 import "encoding/binary" const rounds = 20 // core applies the ChaCha20 core function to 16-byte input in, 32-byte key k, // and 16-byte constant c, and puts the result into 64-byte array out. func core(out *[64]byte, in *[16]byte, k *[32]byte) { j0 := uint32(0x61707865) j1 := uint32(0x3320646e) j2 := uint32(0x79622d32) j3 := uint32(0x6b206574) j4 := binary.LittleEndian.Uint32(k[0:4]) j5 := binary.LittleEndian.Uint32(k[4:8]) j6 := binary.LittleEndian.Uint32(k[8:12]) j7 := binary.LittleEndian.Uint32(k[12:16]) j8 := binary.LittleEndian.Uint32(k[16:20]) j9 := binary.LittleEndian.Uint32(k[20:24]) j10 := binary.LittleEndian.Uint32(k[24:28]) j11 := binary.LittleEndian.Uint32(k[28:32]) j12 := binary.LittleEndian.Uint32(in[0:4]) j13 := binary.LittleEndian.Uint32(in[4:8]) j14 := binary.LittleEndian.Uint32(in[8:12]) j15 := binary.LittleEndian.Uint32(in[12:16]) x0, x1, x2, x3, x4, x5, x6, x7 := j0, j1, j2, j3, j4, j5, j6, j7 x8, x9, x10, x11, x12, x13, x14, x15 := j8, j9, j10, j11, j12, j13, j14, j15 for i := 0; i < rounds; i += 2 { x0 += x4 x12 ^= x0 x12 = (x12 << 16) | (x12 >> (16)) x8 += x12 x4 ^= x8 x4 = (x4 << 12) | (x4 >> (20)) x0 += x4 x12 ^= x0 x12 = (x12 << 8) | (x12 >> (24)) x8 += x12 x4 ^= x8 x4 = (x4 << 7) | (x4 >> (25)) x1 += x5 x13 ^= x1 x13 = (x13 << 16) | (x13 >> 16) x9 += x13 x5 ^= x9 x5 = (x5 << 12) | (x5 >> 20) x1 += x5 x13 ^= x1 x13 = (x13 << 8) | (x13 >> 24) x9 += x13 x5 ^= x9 x5 = (x5 << 7) | (x5 >> 25) x2 += x6 x14 ^= x2 x14 = (x14 << 16) | (x14 >> 16) x10 += x14 x6 ^= x10 x6 = (x6 << 12) | (x6 >> 20) x2 += x6 x14 ^= x2 x14 = (x14 << 8) | (x14 >> 24) x10 += x14 x6 ^= x10 x6 = (x6 << 7) | (x6 >> 25) x3 += x7 x15 ^= x3 x15 = (x15 << 16) | (x15 >> 16) x11 += x15 x7 ^= x11 x7 = (x7 << 12) | (x7 >> 20) x3 += x7 x15 ^= x3 x15 = (x15 << 8) | (x15 >> 24) x11 += x15 x7 ^= x11 x7 = (x7 << 7) | (x7 >> 25) x0 += x5 x15 ^= x0 x15 = (x15 << 16) | (x15 >> 16) x10 += x15 x5 ^= x10 x5 = (x5 << 12) | (x5 >> 20) x0 += x5 x15 ^= x0 x15 = (x15 << 8) | (x15 >> 24) x10 += x15 x5 ^= x10 x5 = (x5 << 7) | (x5 >> 25) x1 += x6 x12 ^= x1 x12 = (x12 << 16) | (x12 >> 16) x11 += x12 x6 ^= x11 x6 = (x6 << 12) | (x6 >> 20) x1 += x6 x12 ^= x1 x12 = (x12 << 8) | (x12 >> 24) x11 += x12 x6 ^= x11 x6 = (x6 << 7) | (x6 >> 25) x2 += x7 x13 ^= x2 x13 = (x13 << 16) | (x13 >> 16) x8 += x13 x7 ^= x8 x7 = (x7 << 12) | (x7 >> 20) x2 += x7 x13 ^= x2 x13 = (x13 << 8) | (x13 >> 24) x8 += x13 x7 ^= x8 x7 = (x7 << 7) | (x7 >> 25) x3 += x4 x14 ^= x3 x14 = (x14 << 16) | (x14 >> 16) x9 += x14 x4 ^= x9 x4 = (x4 << 12) | (x4 >> 20) x3 += x4 x14 ^= x3 x14 = (x14 << 8) | (x14 >> 24) x9 += x14 x4 ^= x9 x4 = (x4 << 7) | (x4 >> 25) } x0 += j0 x1 += j1 x2 += j2 x3 += j3 x4 += j4 x5 += j5 x6 += j6 x7 += j7 x8 += j8 x9 += j9 x10 += j10 x11 += j11 x12 += j12 x13 += j13 x14 += j14 x15 += j15 binary.LittleEndian.PutUint32(out[0:4], x0) binary.LittleEndian.PutUint32(out[4:8], x1) binary.LittleEndian.PutUint32(out[8:12], x2) binary.LittleEndian.PutUint32(out[12:16], x3) binary.LittleEndian.PutUint32(out[16:20], x4) binary.LittleEndian.PutUint32(out[20:24], x5) binary.LittleEndian.PutUint32(out[24:28], x6) binary.LittleEndian.PutUint32(out[28:32], x7) binary.LittleEndian.PutUint32(out[32:36], x8) binary.LittleEndian.PutUint32(out[36:40], x9) binary.LittleEndian.PutUint32(out[40:44], x10) binary.LittleEndian.PutUint32(out[44:48], x11) binary.LittleEndian.PutUint32(out[48:52], x12) binary.LittleEndian.PutUint32(out[52:56], x13) binary.LittleEndian.PutUint32(out[56:60], x14) binary.LittleEndian.PutUint32(out[60:64], x15) } // XORKeyStream crypts bytes from in to out using the given key and counters. // In and out must overlap entirely or not at all. Counter contains the raw // ChaCha20 counter bytes (i.e. block counter followed by nonce). func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { var block [64]byte var counterCopy [16]byte copy(counterCopy[:], counter[:]) for len(in) >= 64 { core(&block, &counterCopy, key) for i, x := range block { out[i] = in[i] ^ x } u := uint32(1) for i := 0; i < 4; i++ { u += uint32(counterCopy[i]) counterCopy[i] = byte(u) u >>= 8 } in = in[64:] out = out[64:] } if len(in) > 0 { core(&block, &counterCopy, key) for i, v := range in { out[i] = v ^ block[i] } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_vectors_test.go�����������0000644�0610621�0607500�00001115720�13172163317�031570� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package chacha20poly1305 var chacha20Poly1305Tests = []struct { plaintext, aad, key, nonce, out string }{ { "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73637265656e20776f756c642062652069742e", "50515253c0c1c2c3c4c5c6c7", "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f", "070000004041424344454647", "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd0600691", }, { "1400000cebccee3bf561b292340fec60", "00000000000000001603030010", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "2b487a2941bc07f3cc76d1a531662588ee7c2598e59778c24d5b27559a80d163", }, { "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "00000000000000000000000000", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "3f487a25aa70e9c8391763370569c9e83b7650dd1921c8b78869f241f25d2096c910b180930c5b8747fd90959fe8ca2dcadb4fa50fa1439f916b2301e1cc0810d6725775d3ab86721700f96e22709b0a7a8bef32627dd929b2dd3ba15772b669062bb558bc92e6c241a1d60d9f0035e80c335f854815fe1138ab8af653eab3e122135feeec7dfaba1cc24af82a2b7acccdd824899a7e03cc29c25be8a4f56a66673845b93bae1556f09dafc89a0d22af207718e2a6bb022e9d917597295992ea3b750cc0e7a7c3d33b23c5a8aeab45f5bb542f6c9e6c1747ae5a344aff483ba38577ad534b33b3abc7d284776ea33ed488c2a2475648a4fcda561745ea7787ed60f2368deb27c75adce6ff9b6cc6de1f5e72a741e2d59f64751b3ae482d714e0c90e83c671ff98ed611823afb39e6e5019a6ba548a2a72e829c7b7b4a101ac9deb90a25d3e0c50d22e1fc26c7c02296fa13c6d9c14767f68aaf46450a8d0fd5feb60d9d73c6e68623425b4984a79d619dd6bf896459aa77a681ec9c1a97f645e121f47779b051f8948a817f84d1f55da170d5bbbaf2f64e18b97ed3fd822db2819f523314f1e5ac72e8f69bbe6c87c22daddb0e1ac6790f8534071de2f258064b99789bfb165b065b8fe96f9127cd7dca9f7cb0368420f1e802faa3ca23792f2a5b93773dd405e71c320b211b54f7a26626b03c060e1ab87f32ac588abfa056ce090bd7c69913a700c80f325bfe824fa", }, { "0967de57eefe1aaa999b9b746d88a1a248000d8734e0e938c6aa87", "e4f0a3a4f90a8250f8806aa319053e8d73c62f150e2f239563037e9cc92823ad18c65111d0d462c954cc6c6ed2aafb45702a5a7e597d13bd8091594ab97cf7d1", "f2db28620582e05f00f31c808475ca3df1c20e340bf14828352499466d79295f", "4349e2131d44dc711148dfe3", "bd06cc144fdc0d8b735fa4452eabbf78fd4ad2966ea41a84f68da40ca2da439777bc2ba6c4ec2de0d003eb", }, { "c4c920fb52a56fe66eaa8aa3fa187c543e3db8e5c8094c4313dc4ed35dfc5821c5791d171e8cfe8d37883031a0ad", "85deea3dc4", "05ff881d1e151bab4ca3db7d44880222733fe62686f71ce1e4610f2ea19599a7", "b34710f65aed442e4a40866b", "b154452fb7e85d175dd0b0db08591565c5587a725cf22386922f5d27a01015aba778975510b38754b2182e24352f019b7ad493e1ed255906715644aec6e0", }, { "c4b337df5e83823900c6c202e93541cf5bc8c677a9aad8b8d87a4d7221e294e595cbc4f34e462d4e0def50f62491c57f598cf60236cfba0f4908816aea154f80e013732e59a07c668fcc5cb35d2232b7ae29b9e4f874f3417c74ab6689fae6690d5a9766fa13cd8adf293d3d4b70f4f999adde9121d1d29d467d04cf77ea398444d0ea3fe4b7c9c3e106002c76f4260fa204a0c3d5", "72611bef65eb664f24ea94f4d5d3d88c9c9c6da29c9a1991c02833c4c9f6993b57b5", "dd0f2d4bb1c9e5ca5aa5f38d69bc8402f7dbb7229857b4a41b3044d481b7655e", "2bbca0910cc47ca0b8517391", "83aa28d6d98901e2981d21d3758ae4db8cce07fe08d82ca6f036a68daa88a7dda56eeb38040c942bdda0fd2d369eec44bd070e2c9314992f68dc16989a6ac0c3912c378cf3254f4bae74a66b075e828df6f855c0d8a827ffed3c03582c12a9112eeb7be43dfe8bd78beb2d1e56678b99a0372531727cb7f2b98d2f917ec10de93fe86267100c20356e80528c5066688c8b7acba76e591449952343f663993d5b642e59eb0f", }, { "a9775b8e42b63335439cf1c79fe8a3560b3baebfdfc9ef239d70da02cea0947817f00659a63a8ee9d67fb1756854cc738f7a326e432191e1916be35f0b78d72268de7c0e180af7ee8aa864f2fc30658baa97f9edb88ace49f5b2a8002a8023925e9fa076a997643340c8253cf88ac8a221c190d94c5e224110cb423a4b65cca9046c1fad0483e1444c0680449148e7b20a778c56d5ae97e679d920c43eed6d42598cf05d10d1a15cd722a0686a871b74fea7cad45562bacf3bda937ac701bc218dac7e9d7d20f955429abdac21d821207febf4d54daea4898837035038bf71c66cef63e90f5d3e51f7fcfe18d41f38540a2c2958dacde16304e4b33da324030f1366f923c337", "74ba3372d308910b5c9c3885f41252d57556", "9cf77bd06a4ed8fb59349791b98ba40b6019611942f5768e8be2ee88477149e3", "b928935c4c966c60fd6583c0", "ec7fd64fd75b254961a2b7fc942470d8620f439258b871d0d00f58028b5e0bee5e139e8108ac439391465d6658f559b1df57aa21cf826ede1a28bc11af885e13eebfc009870928fae8abfdd943a60c54fca93f0502dc23d29c2fd5340f9bc0e6ef2a18b66ef627af95f796d5bbca50de22c8ec802da9397089b25c6ba5262468e3977b45dc112e51896c70731b0a52d7efec7c93b41995823436bf4b0c477ae79684407c9831b487928b2b8303caca752b3edf1f0598e15831155462706f94ef3fa3a9e5f937f37085afa9b4bbf939d275796a61b78f70597acfd25cd87f967021cd99328fc371b5eb5739869520657b30e4a5b0db7c8715cbe275dee78e719b357d3a9731f9eaba95986479bb2004a77822fc115a3d", }, { "b3d3128bce6bbf66fd78f1a18352bae56bfcdae18b65c379ee0aeb37ee54fba1270d2df578ec5b75654d16e89fd1cd0acda7ec580dafd2fbbabd32a8112d49383a762db2638928c8d63eb0750f7e7fdd256b35321b072dd5c45f7dd58cc60dc63d3b79a0c4a1689adf180fef968eccbcfa01ee15091ceacd7b67a3082db0ce6aeb470aafe87249c88b58b721e783dde184ccf68de8e05b6347fe6b74ae3adf9a81e9496a5c9332e7ebe908d26ce6b3f0b2a97e9a89d9fdd0d7694585a3241f240d698e69fcc050e7a959ba153f6d06f117848ba05d887134f1b6b994dad9b9e74247513e08a125b1fadfc7394dcd2a6451b504ae3e75e22f2b9bc405747dedb6c43ef4ccdf1a7edaf9451346123eaa63f3af113124f361508e255503a242b96680ae3360c8b13ac1f64d08088bb26b7f617cb0866f11d6fd362b00d86eba3fee68724e302388f119d6f92161ac8ce00d08919377a26974d99575b1032ff0f1976240c785c8b89e9eb2bf005e4be06b5371ffca14683fedfdb49e00e38ff27af1324177faf91599abd5990920797574eb743effdc7decda318ada1419cc8e0bfecf82f9c99792746c2b", "7e8da4f3018f673f8e43bd7a1dee05f8031ec49129c361abbc2a434e9eaf791c3c1d0f3dad767d3bba3ab6d728bbcf2bd994bd03571eae1348f161e6a1da03ddf7121ba4", "7ee32dd501dce849cd492f6e23324c1a4567bfceff9f11d1352bcb8615f1b093", "8998e043d2961afa51ea262a", "ba85e72af18cb5ba85a4a0d6c28b4ac1e5509a3a2fdb0e3255cbc559df5e6a661fc560c756a0264dd99b72c61c51a4b7ad56ca4c8ccb7e8edfc48ff3cceac5d1e8ac5fc87096adc4d0e9a27492857b17604c3a694cfe0e70b22df106c8f3c61f840bcd634964cdb571840e125e381e7dd3a0d97972e965f16f775fa4ce555124318290bf508beb7bd77e633042deb0e863631478fc3dc9122862b3c31264471bcce54e0b74040c8bafd481cf798f332e8940f1134d3027d6f28e771d15e154fc89c6c25fe18a5d312807cc2e623bb1bbb4f0b6ec71d009407eb54bb0759f03682f65d0da8812f84d8e97483f6a8d76a8417efcd9526444abba24288647609791578887ef49780b0b89f51b072cae81c5b5014463da3633dda105b82add0f9c2f065dca46eedd2928be2570493c79a996fa78ea6aec0996497fe2dc444432ade4eaa662ee2255f0f4b92d593288a8e3ffe7a15a10e9d33b0203af23f4c9fd2cfcb6160db63b52810869ff1e65423dbe2c4415884b9f8dec3c968e14cd74f323c89053a96111bc9ce59ec483832c49c53a648e5f0f797f53642ac60170c94b473f1f2e7d8a38e46460b81219b52081263027f74cbf63a75af3a7", }, { "68d5ba501e87994ef6bc8042d7c5a99693a835a4796ad044f0e536a0790a7ee1e03832fec0cb4cb688cdf85f92a1f526492acac2949a0684803c24f947a3da27db0c259bd87251603f49bfd1eab4f733dec2f5725cfcf6dc381ad57fbdb0a699bccc34943e86f47dcfb34eba6746ed4508e3b764dfad4117c8169785c63d1e8309531747d90cc4a8bf13622759506c613324c512d10629991dc01fe3fe3d6607907e4f698a1312492674707fc4dde0f701a609d2ac336cc9f38badf1c813f9599148c21b5bd4658249d5010db2e205b3880e863441f2fe357dab2645be1f9e5067616bc335d0457ea6468c5828910cb09f92e5e184e316018e3c464c5ce59cc34608867bd8cbfa7e1286d73a17e3ebb675d097f9b3adfa41ea408d46252a096b3290e70a5be1896d6760a87e439334b863ccb11679ab5763ebe4a9110eb37c4043634b9e44d40cab34b42977475e2faa2ae0c0a38b170776fbb0870a63044aa6679545ac6951579d0581144cdf43f60923b6acaecdb325c864acd2c7b01d6e18b2b3c41c041bb9099cce557b114b84350131e3cee4089648b5691065867e7d38314154355d0e3ef9dc9375eddef922df2a06ad0f0e4357c3ac672932e5a66b16e8bf4b45cd893ea91cb397faadb9d9d7bf86e6ceca3e9176a5baa98b6114a149d3ed8ea176cc4a9380e18d2d9b67045aedeb28b729ba2ece74d759d5ebfb1ebee8ac5f5e79aaf1f98b7f2626e62a81d315a98b3e", "63b90dd89066ad7b61cc39497899a8f14399eace1810f5fe3b76d2501f5d8f83169c5ba602082164d45aad4df3553e36ef29050739fa067470d8c58f3554124bf06df1f27612564a6c04976059d69648ff9b50389556ad052e729563c6a7", "7d5c4314a542aff57a454b274a7999dfdc5f878a159c29be27dabdfcf7c06975", "aeb6159fa88bb1ffd51d036d", "7597f7f44191e815a409754db7fea688e0105c987fa065e621823ea6dea617aed613092ad566c487cfa1a93f556615d2a575fb30ac34b11e19cd908d74545906f929dc9e59f6f1e1e6eaaabe182748ef87057ef7820ffcf254c40237d3ea9ff004472db783ed54b5a294a46cf90519bf89367b04fc01ce544c5bcdd3197eb1237923ce2c0c99921ca959c53b54176d292e97f6d9696ded6054711721aebda543e3e077c90e6f216cdc275b86d45603521c5aab24f08fd06833b0743c388382f941e19e0283ac7c4ef22383e1b9b08572882769c1382bab9ad127e7f3e09b5330b82d3e0c7d6f0df46edc93265999eef8e7afa0cb1db77df7accf5bff8631a320d146a5c751a637a80f627b0c9a41b44f09212f38c154226de02f4906ef34139bbeacc3f06739c8540e37334392d38ba1cbf4bc7debe77c09b35d2200216db15ed4389f43bfd8ae9bf76fd8243c3d869546e16b8e44a6cd1edbd2c58ef890b5a84cda889131e5cd9402ca4d8271052c6b4fe3f2dff54fb77bcb575c315b9109f90b14bc8e109919808a581c1809e2a188d29fd34ce639088a6683f641925f5b4b3529baa34e080bb47fb7ad9b43d0d67c9e6ae7cacb50527fa74e56d0c8b20149f5d332d686d48ebbe634c2b5d35fc84c69a5bcc93b93dedcf9fdf19a1fb9b75f6df9692d16f6c3490377a06294499e4b8ebeaa0cfd840bfa05fde21c0b5e94d13063b3f5da7b537caefe89069cfa9de9eb8f06e4d30125de64716f821bcc8279c0c7ea2e", }, { "89c1ee38b6697d0190c87a2aa756892ee09fca095df1e31aeedbda5750f604d9b8f2116e5b8f70ec57ea16fe419f2d213ef72b9be90eb5d7e98f2e398632123e2524ac80b31c6c0a07820848223569602d94fc16a3b1ed8c411bc6c74ed80573fcb1f3afce60b9d5e2c21d04f78665241b613abe12274a5343101a91e91f04e5d1f7959f574e743a10913e0817a32c320467f0178e3b6ad14b856234a4661a755eaf14b5fd88ef0e192e1631d14263d6a954ed388f5709dadc6c0f81d229f630d80be6d593d5e3ad03f9ded53c41abe595981d24ef27ffcc930e4d653743960f4e7ce4e251c88f55c16d2afdaed5e3446d00685c276728ba757520acb9b6bb0732a0e9836878d829e5022794d70ad8440a40a132a8c9ec1d3f0ccaf8c285fff425e9788d6150b74753dedb2ae8b36ff2f310249bd911b9181d8310e00810d42ef94cbb5a9d72a1f0507c1a382f892b23994fbe7360778b7efa9c5e03ac3231a57fecff1c5fa10caf1d26e84db0137049622ebcc3a64841a0e49fa390d1d43550c1346c20d578cff39fb7404fcab0982dde55f0849d312581d0c811a19d46f25e7a5e7e50d74d43760583c5cf335dfc11b2ec964f1dbbd0ed83e18f2027817ea2dffcf2b64a352c4fb8f11eeb4f1bfc01079251254d2112d103a1f12a2270cc026cbeb8b6f3e505abd62496253f93274625786b73997e449c1f35c742a593441252fcc845e1cef1b8f287dd311a0477407ce3b31661f7b2802c79c2d20d06e45f03aca4e47a959c6c1d7a9d377e1577fbf82a115921c3d94e3d9c204aa204a9a5b04d8a2be3269700a035371f4aaf1a42d92b9bfbee74492b106975b36d1e581d6ce2484f09e04fa91586c85f35e2a10f0d3c0afcb05327c1bc9d7429bbcc4627af8f76b86fc561844c2ae3810c84901ac09a1670ed3d31a9daa5d296", "7219bd21a834d917f93a9b45647ec77102578bc2f2a132dfde6489b9095b4f7b740c9c1c4075333ab0ce7f14", "a7f849b054982cc8a4c8e5e53e181feee79e0233e58882839892134ad582da7c", "4c46854e9e101090b1436f90", "ab2e189baf60886bed88eb751bf3560a8bd3cdb6ee621d8c18b5fb3aa418f350048ecf359a7d542daf7090ec8688c3b0fe85914aa49d83be4ae3396f7bdc48051afae6a97fca7b42c0bf612a42d3c79ef6aadceb57f5cfe8d67f89d49add0ea1ffd423da058297239e72a85fa6cd1d82e243a503b1b0e12d7510a9ee98d7921dae2754d7581e52acb8ab9e7f9df3c73410789115cef6ce7c937a5441ad4edf2b7a8c0c6d152d5a5909c4ce839d59594a6163364038c4c71a1507389717f61e2bda1ea66a83ef477762e7834ebcfaa8f2ee61ced1605ba1380108236e1763bf40af5259da07dd3e3d0fb2801868c2e7c839e318678687cbe33384e2ef5750a0a0e2d2e19e869a4277e32a315ed4de79357f6a12a8a25d5b18291316d9bf40dad2d05d1b523ade76650669c700a1c2965f4e51337aa5d45ec7b4981072779401d6d30ed69034053334bccb18425ac68460becf2aeccc75aacd3d6709f07ee10366ed848c8a54904af4ea71fc2117de133f01e1cc031f2a4d0779b997b82682433ee615202d5dfffba6c916f11a00551d56ffde8c36b303263e14adaf45b6eab0bedf344e5214ce52f071d2f40154d788c6870020791a03d2fd4ec5879d9026241954ed45cfddef4937ea3d0d45647f252be31411237983a1be340fc65ebab9a5620abb0e8d475af4e89e842e895eda0cbd283bb5d0bf20236c62d956de733d60ebceb42fc0c9adbf9b69f8d66551b0aca0e260625ad41cad75d752a234af7caf7902c2c5b62f04b6a8e019a6179d44feeb2ad5859ef1c45371e66f1af1fe0de63997266c290e27f0dd62185c53f81e0a50c296a51ace7c90d9cf0dda8b2d7e72a347f64c44262e2a544d1acc7bb05734dc1783bbc1903279092fe7fe434610aa95fc2ce5fc5ee45858f5e8337d8fcb0a468464becb1cef6b7e5ea48ba383ad8a406df9c581f1cac057d8711fcb", }, { "2dcfbb59975f217c445f95634d7c0250afe7d8316a70c47dba99ff94167ab74349729ce1d2bd5d161df27a6a6e7cba1e63924fcd03134abdad4952c3c409060d7ca2ee4e5f4c647c3edee7ad5aa1cbbd341a8a372ed4f4db1e469ee250a4efcc46de1aa52a7e22685d0915b7aae075defbff1529d40a04f250a2d4a046c36c8ca18631cb055334625c4919072a8ee5258efb4e6205525455f428f63aeb62c68de9f758ee4b8c50a7d669ae00f89425868f73e894c53ce9b964dff34f42b9dc2bb03519fbc169a397d25197cae5bc50742f3808f474f2add8d1a0281359043e0a395705fbc0a89293fa2a5ddfe6ae5416e65c0a5b4eb83320585b33b26072bc99c9c1948a6a271d64517a433728974d0ff4586a42109d6268f9961a5908d6f2d198875b02ae7866fff3a9361b41842a35dc9477ec32da542b706f8478457649ddfda5dfab1d45aa10efe12c3065566541ebdc2d1db6814826f0cc9e3642e813408df3ebaa3896bb2777e757dc3dbc1d28994a454fcb8d76bc5914f29cfc05dc89f8c734315def58d4d6b0b0136ccd3c05178155e30fcb9f68df9104dc96e0658fa899c0058818da5ec88a723558ae3a6f2f8f523e5af1a73a82ab16198c7ba8341568399d8013fc499e6e7ef61cb8654b48b88aa2a931dc2cdcf245686eed9c8355d620d5e91c1e878a9c7da655e3f29d9b7c3f44ad1c70890eb5f27ca28efff76420cd4e3cebd5c788536ddd365f7ad1dbb91588d58612e43b0460de9260d5f780a245bc8e1a83166df1f3a3506d742c268ab4fc10c6e04bca40295da0ff5420a199dd2fb36045215138c4a2a539ceccc382c8d349a81e13e848708947c4a9e85d861811e75d323896f6da3b2fa807f22bcfc57477e487602cf8e973bc925b1a19732b00d15d38675313a283bbaa75e6793b5af11fe2514bda3abe96cc19b0e58ddbe55e381ec58c31670fec1184d38bbf2d7cde0fcd29e907e780d30130b98e0c9eec44bcb1d0ed18dfda2a64adb523da3102eafe2bd3051353d8148491a290308ed4ec3fa5da5784b481e861360c3b670e256539f96a4c4c4360d0d40260049035f1cfdacb275e7fa847e0df531b466141ac9a3a16e7865947572e4ab732daec23aac6eed1256d796c4d58bf699f20aa4bbae461a16abbe9c1e9", "33791b0d653fb72c2d88519b02bde85a7c51f99cfb4456dfa6f84a61e10b4a14846521", "a0a7b73ca2fc9282a28acc036bd74d7f5cb2a146577a5c29dbc3963fe7ebfd87", "eaa4d916d261676d632455be", "c9a631de470fd04dcbf8ea9f4d8ac37c3988878b6381707ac2c91d3720edbb31576ba90731f433a5e13582aca2b3c76ae75ca8881a463ecfa789910d3a776a9ad4800521c6baa120b2f1afd10f32ef8da63f5b69f5e5fd88ee84bf66b0666b15d05c4050f5358a050b9d5cf1503719f56cd48ceba78f29efe2ae8092e37f5134df526831532f86ccb9339637e2c9e9b9036f83cc058fda23e826a188456e7fd3f4ee20f4e4a3221883fe3232b49db607b90a8956133ab95051c9ec33a908ea7e81a1bfa7bd06c09f0143d07bb23a3feeac7f0d7720269c93e2df19d03605828c8713b84d183c9a50954c12fe3b047511ad15ef03a63355520cbd224d06a34de67a671368e6a8f9feeefe48fc273764a8c69c00314e5d693f159cb5270544f3c4e1760b0529e3303ab308e9a6d03835a3a42aef2df5f7643696f707a574d1dcc676aeecdd9947ebe8c13bcf15d30b2d10d2cd95445a307c1d22d39450615ad38f9302c6eb9dc05764b0503d6a7eaff9feb94834853b47bc25660207be3e7c0e27cb3127b5402cb016396e5ff07ddc3df29861dd68a17f53bf660b23352b739d6da72381b8d19a9fc95da7efb79330a2b360dce4309860af429e3fd10cab235c4acc1d80d9e20d67019375bd161ab65648400f308815afe63cfc717f7d0eea150e687caac25b6603287d44dca4a7cc2f67c3bdd54450bd3170340253b03ba054ec003070eddf9c14fb9dc595e228e4968524900cb5d85af6d1e658a42d744e0e7eb6995023823a8dc33528c6715b2e1aa607782c8e1ddddad72026d657bf122ece8685f6e92236e809139325e4a3c069facf94c10b7896995bba01eb22c7b3a87ea2114a7649d7ed3e83d223e5e785c66a75119beab0968d3eaf0cbcc2d7ede95d024041e6db39a880ce3e19efea32fb89a40a2aae22f407e5fd615e51e48dbd50a8b4ec27ce95e2ba1928bf699d0418705482ed0ed7acc858dfbd690403c74667a88dd5221bb79940c6c4a268379c10343aaefb635982c14f33ad83d47ced9682961540bd4f75804d3d48ba8aa67fb2e3a1db83fbcbe57fec9e4ffb1b575e947f8bd8263c680357960e3a39382974774b5a013f2f8514b3c63c21dbfd314fd5d927d82ba616d76629ac018879f54ff84b5808e94af4fcfe1cf8845b65208ca5510b5b593ce6c109611652cd", }, { "c335b055b752e083554b5aa2cbb6556cfcace658d5c11b6b000256fd89e9b24c1e62a2d5b582580acdb2ad9869020465aeeabe83acd9eeacdc44aa652d5cb24bbe542073d6787ea32b2b3c942d40f9db2bb75ed7914c836d902dd2be89840948d82abbaea23952cd648e6191ce5b6cf912cad0a3165410a781e3650b676e5340980eee3b484008acce6a3e9dc5aa96d775677b8bbb8b323c6e9747d6069a169ea904d9f145e29d134cdbb0118647e8fbae638669efb9a55d50ed33568749f5304ece2193b0bfa6fc9a570d209ef61b4c59a2b5485b5aa6ab47d902cf23f7ff71c5210476e0aa727a01809b9f76b6ebcf58a018b3fbbe5f42976111ba58112b1d322f9312da068cdb86277bfcde66cb3607e3ea02a1494439aa56f302671f1f994eb3ab28b937043f5f7f3b3de50673ecea5dee8ba633c45089b852f0d772892525344ede6b521dcad15807b65e7ba348d891d47fc498cf4d50223d2794c64db9fa9b9766edb430be0c38746ab317b38ba9870a6d1fdabb70fcf89790bfe449b97fe01f6c94502aa0889f0a3bb6bdc65f44d1cd64ab88d4a7806b373f5080f9cf60183cf4686694f0059e2bbc5cf21ba0c3e8046e70d815f1444c3094cc29632c429f20aa06b49b0b52c6c7aeb8e34f7bcb53e93c2cfe2d704a5d0416876742c90762730d160e1869d5e0178dc366098ebaf2cae6f1f7563b555a52dcc194a5c8f718d50d27ee76fcce8e8991f4921fae85ea9476e1eab1364403120698b7ce8fd0a49cf79213f360a17cf1950f104494fad80adcc3bb1207bf250d57dcdce6ac8082a312959672361363cc227310b66ee8c04aab7b5cb33a81c0915e9c770a1cfaae2e8f44a0c65703927977a22fe58aef2f366b8be9a50da9376b46ae7562a82391386831febf359039ac326891bc58c0f2c34bdb6858859fc3cb4e392df65cbe2ec4f02c8425bcbdd1ee2562ab7d229d406d79a9c6fe4889c996c2f68d1fb5bbe3a5e867caa4249b934afd3ec71fdb088c54b15252f9dc1b909e121dbdc7d8a16cc00836652dd1f877ce363eed11467966f7ccb8f1a8d48146e69e04ad76a51937ad4f9cda209451eeca90dbdbd65441ce20fabfc8ce400fb4de136154b87a8b65c92740e9bb91d78521b261f806a2c6279c85ef6ac5fe1ea3117ff7c9f9832fc2aa6fab660082eb22344c1a3befe0628b6551f62a5014cd6194c42b8d475a50f2c9fb58c97e43ebb29005ed7fe54f0a4aa10074f1154152a9067d364dd7863fa082976a00db55b26b5ba0ea40eff48b90", "f5ff810a41d4b34751e9942970d4c9f26b33f24689a4b1e4449b243490afc485af468ff01a42376b2bcb949b9f5e8d0b917f511a", "a74271c184a82cb074c14b131fd91eb05870cb7c73c9e511ec8140bfe2f34089", "2403fe689e239c2ed261b381", "af9be893d5fd23aab42e6a2e59a8e7cb13d4f543db02af87cb0802bc1af7c717cd0093cc8244994cf21189146922b69927ffd5745e57118bea07a6afe7c21d952c13ab636b3c2e461dc9ffb3ae701175360156338be94b1fa7115799831019455cfaf5114010fe45f8fb9c77ec50fe06f2c5a32423edccb3b2210ee1200a78e1a3130c567542377827586ca8cf0c14c19fa1449a2cce9c039bb441b04e9c0a3f9a743b31c828032174fcdb7c894349aa68f5adf97dfe9294d24e6b5fed95eb994397883f58487bf5c57b0aea5268be7cee9efeab370f89805ebe5373ab2e93658fc078955ccf68b554dd5605005751ee8531c35ca5336a5d0ce273370c0dc9307779b86e96d2d1daf2620d67d43e1fb7800ccf250ca3c02eb74047c1d2a2bc7f29fff8320301694b80d0fd975f834337d00d5f0e4215044d52aa4ca21e6a9d7e03f186d7cdd5c48e3765dc926fb0a46bb0f05c50d9f69c9c507527a60366b7dc251aae1d6bb0d9c73735dcfab959f6fd4382fe2a1f6ad07affb0601bb9040f81b55a48f6a6c5f8ac4a2acc2b0c9a6c439198f7926460695fa11e0b0b017e39de5cf0d5d5f84d972b5eee7b5d1e0343b5485cd84b92ad892e5b23f3e803f5b363f2398c11c15be9f13e59922b0d49902dc8483fb142850b4226da2fb84e9b434a34f6bb67f575a9e57fde3354bc3077a876e260311bb2481bb139aa9af55df5074749fe532d7b8a554218a90cc7e7ac69db280bae5d55a174dfc8d325b9909a8da1016d4e162fe5ba70cf8726cdf291f5e47083d9929cd5e32021cbfd982fd0975f6f9baf4322b553cb3174b11c007559879f308419ff9e4e18eee8d3640cec8aea082b90f69cf3c7676c28af0265c24c91cd58a06513198892ce6ce1ab3ee9ac0a2e937b973a9cac06a039a54f8d994c13d42c59187f677352e5feb32a417aebec4d852b2595e7e67450e06dbd183279e3b63022a3813b37257b085bf8454d6890875a2950d20210a8df4f9da746722f62687e92f0e9efc3e5d526d65ccfbcc042fcac7964dbe147932c73924bdcdf62f9eae58d29e8567ffed90048bcf0566b952e986efeae4c477944af18bd243c3eccf8d88c06d07279adad037450cb8547a8aa0a74223f4851747c803cb21a2dd027e7080aed75038cdcecbc4639d87763cdd41829a1b72cedf0d722b180d0d492a5740ea7607b95f3201df352fb1ab28149124d2df5d5ec106867897b537302c3431402348f94d28eebc701ae1b49d10adedea38f1654fbc48885e59e6e6dfd413c6b5a97d8c35dfb07a6cdefe317bf61cf91", }, { "4aba5a776ace38b6e2578f0007e770d264e39c49f588ca3547ad2888365e3a811994f8836330394587c8458eb0b6611499fd5d8e8527c3cdd4ec550b4a8f8c632384e786b420cb3be911c999c72aad60270aefad31b27a069ecf11e95e9d4c81213308d554d3103de4d9d6ab04830c2b8dfbd8bead52c44c21d5357f72810193b5096809dc7846c1521c6c569f78812c735aea21acaf6dce84a24df7234e8ad857f3e1346b27f5bd436113e2da950e4deff96e9ba8db692c7db723a105ae795da15b910c8286cac6e7dda8c172b70f61b07dfd58596684d61da8772356f180f74c1103ce97cd947eab3d401df44f7fa4cc7cfc25e280fc002873237e64a375b0b4797f4b4613c9f150090f44588ee8250ae44aec6546ec8dba0f0c1eb281cf66fa4eb141617b32b28441f6ddcfdf02d9c34cc62893b2b64dc2c26b74433adb3e888c7fea07b19c8cf39269c2716b9c35b7625d4a141397d6d5034b193d2657c6b2d6b0ba874c467adeaf3d501ad985d13be21c4ff6b326cbb671e4f4973bba49116a0399b6491394f850e4122969e4644c00b442b3da0d6a4bf25ee22d182b3f822fd83878ebcc713cb183651a67ca66677ea81b58b685a3a8e385d5fbb0147ddfecb558d881c914324c794db443b31bc15c361912bbbcba9e418f99f2a416d190cb29684df27c7f3ff6ccf339800efbdc4514ee00d1a89f12373804db4fd66c1affd467f251e73147b3248033327b0f7790fd7861a51773dd4f78b89e4e24b94df9203f4a077091bb9411eec78dfe3e1dfbb67ea1cdf17e1d6936bbb75b74055495449e9cb52f5749404610cd444fea3f0568e0d35a5ef0c395ab7bf0208044b5c4e2517911a9c351efd31f33220972287253fbccb1eb8f46960a36b68a7a6b4f5cbdc86d668bbf555fde8881e7faa9594da425ff8fb54526bf7cdc4af64899530561c06bed7fc04c5d48cd4542779e901bc48fab79d4d13850ad8247f51b9afa7d5a656ada25b6376d837cb0fa1b4016dfcfc158a39290f43f133b352ed52fab2f951509bacb41284fbdd849d8185fb7e7200f8ab2a07ef2b3b927e18e568dbeeba2c7a66e08cebdc6a6069ebe6656a586652f3905ae2bb867529af6a827b494c97b3a378408f44aaefbe86c613e11e7a44020a9ee4b62569dfc4c462300daec7b1424ff1c1849ca1332367470475c14877cbe76c820cc651c18ab3f18852b93994f93b568dc7f7b0eb5f07ffc4c9384c851fa9071c6f68ddea1ccf627f889c0471c76aff9f52b07ab1b86a7671a2b2f6b25c0ddebb66ac95737bf7e2f493f7665b5265eaa5166556cecfdd3062802724ec24f3978b903d0f0c24e1f0b8d967142bccfed0d354279223f4c28684e9ab611e9ef89a3f25993b5a8b3c0354931780501651236a78b58e7d7814f251b053605f4c0a8e7193b9cc1ee5cf7378e6f3c8fd44ec57bd91e62b09fb1d6bab60cbfabcc6792e6a32ea7918a9ec9180d05a7e1546d5d2d8bbfde2a71b4e427c0a4d28d0b6473ae", "921a401db90935c60edda8624a0590d5c46eff3522e35de2872f6f9394e24126fd8143b68a797c995624fba0298b75eef974", "6a4d35ae03bf277f587da4541dcddf92bbd906dff45d5ff23c0f60ae53b062be", "231b5780fedfb06d724450b3", "ba40968282d98849b19d867f8b564ea5a81d657516099362926bca4cb6e9ae02719d10c8061f53008c727a0eeea5e1e36c9e55c117e9434e213316c96840231a1e356b254a9981d4a6ca3c66cfc61018bcaade1a4486506559e6aa3a86bac980d391d835fd5ded98d10f1394d84bf1bbf2cd3397890d704154802f7864ecc753db782fd3d19213ae65ace4770e1bacf32d61c6730aa5adcab4d7e2e437888c11c29abba4890a17a00f67a53b660becd94092df0598df5ac57326f6860593a519e28bd4a39f6481e1a4748881fd5f0456a3cd9f28d1d1e78dc64030cbd8fdb2c5abdab3f13d6ccccd187e71e989f8c486929efcdbf2a763effa95af62db5cef95e9081b818275c69267022fda4b7fdb8c650b491a785b03d4d0186625962b6326ec3f4e176373da4dc1f83a14815adf82c6bffa7c6967d77528d0249754bb4d17656bc4a89449b16152a4a1aea7eb0054a8892f271138971507d2f3b237ba5b620f444544e4a8c2b1ab4f9168762c27478c9f776c47ee2e9ff05bfa35ed127f0cabe7cc053640bb8aa01f8359b74bf89ef43ca94c48fcd201eae39d1835957eeccd6b3a852f4e1bbfef9a469f42c764481ff8408fe5871afeeae7676b58f4202199aad50a596626dff97c8e60d750cc59da9f595ce12ce9afdce14481cb1e39994de8fe4cce07845110d6703dc59d34734e93e9e57e1c52d61f44143a2d290220a4bad5098d098ee65ea4b6757d8a9bf5485aa3d697a7826d4a285186f5da10eff707566c23c6a15033365bcb498c44487c72d96402d1834753fdbf86770239761f03e0dc8963766441da99c0813e4f1df5a1d018c8799861a396562eb24ce305ca15f4022d83ea3c56b68d9a7ceac4742ec0ce50f4d36273df26005ec2b051fa071b319be2d8a5ed26eb75bc1ea83761b8454db234d15d84d6706cd178981c1f156e6d28f774aee3e9a4fade022e71b52b50aa532b8bc7fe464f22d6eb169c69671875d614e987658820c2f584a4fea3008afdcbb646dba3d69020fbf503f121be3480344db23efdda0d255aa058c3ff66abd3a5fe35db977521608bba7eddae72ae801f4fbb12a1de4133039e046ceb8db87e465e5ede1d79a08c857d59076d7ff858942c31e15cbbdae6fc15c3f9545a0825d6ff8583c0aba8a7d143d27b93f6caefb98c0d83bd8715abcab2a49087f55a9daf9090eacdf45be08ad80b5df5070e1719f68c4cc8f8711083f0f7823a09ec092f22df95fe9e95114fdf82a3f6eed0bfc9c0aa65222609442776154a474dbc9e662cd5dce66846572e52417ee5d7eb59287d07ef60a9537fe1f85c7fa74fe84dea0da235ac7574335e6649b54a6bd33397df4bf4a7976c4ab868aa702766d2bc8d2c82c2d1c2653fc8428b8d1e61852ac185a3a0b416dbcf8eb54c44967ff43c44f2b32c6d4a9dbf2c2f3a587b430aef50f0375cdb4c1b319ac9aca486d9bb321141b065f52f7b6decaf1985531ca7bbc3772a561eb1efb8a6297075920bc432131a5b211bf25e35fa31e12833bc77a9de14c7", }, { "6c0056937faf1023032df1e2bfacbbc58bb022eba25ffa020d4eb26f0caf0678af5d0b2f0c1b520f4843f107f0adcc7b5dee66ff4d61025bafb4cabb64d133132e3e423a599549a1d83aa8c8e774444462aa44b00b460bbafad5755ea6a872d4e6b40e3f4957e0229288ea79fc2ebe5fd9020fe4481a9f42ef14a196bd136aa3c779e311d0c333624c1ddc484c9aa7259cb609e4d0a826c0bdc7567adac01da23900b30ac4e66c100348584fe200747eb67e6287268947e3509d5d2b5d7bcd977b80a13f660d4f6956a8b938a82db75eab19e5d2a22cb5f3c9131e278eebbe096b5f49d16c983ac240f3fbe821b247cccb2c9e6e59546122677f49f56a07fed56647a6d3e0e09520d49009f54250c10e7c607cd5b4ddf81b5c4110c6490e9baf56418236211856f5a85feaebafacf92c0c7501c052f9dbae3beb7484f90f334f50b68571cedc67763b5161ebfd5a1709cf18c92112a4cf4d8f43d1895204d8a2ba5e14883a7bff75cc6060cabb77d38a909daca2417befd1bfc05a11c432b47f90c807ca4306400f67a0d92218adaca84a584a8bd4395c93f9b6a4bde9583c79204444634a8473b1244cd33cf980e443d82ecfac672b3f60e2e41ecb3c5a445d9e88c0e90c339a31806e6d79ee52bdc6808c73e8b7b24899966664d3c1a9305f31f0483e24e36fa451dc1d3f2eda05af6678971e2bdfb7c1461c9407c5c466f6b5af34d992a37de3809a22ae75275ddba0f4f9cbd4b18c1acd212192e587889a36bd73c860f0abe08bcd8f00f5ecdb95e1d560b586eccf530df0e5f3776d8dae2a01768bf1226b7ceffa7ce4e75879c82dd97db3c64c06d33cebc6b35854618355d80e46fa79c3e9743fce5b974723c421a077e7ec7dba286881dbc1d53d442a1552700fcb33f83f73c69a0a0ebdcf2f5d461649c4d0712c514ded268a31509f83c1ae4ff4a68e676d29727be641aa4487c08d4b90ff78e24c6508d69759751a1a23690ec9f8763621e8b107295b4bb01bd9fcacd8748e24d996fa70ef6f8b0992f4185bec8e920d7643159f9f604fba394b6611bff435998b2f097a9e948430899c8c752a1e83a061983f00f88ebb32da214399167932a1a83c1b47d09f77593b03cf6521520583ea4483e2d33e14ad60584676d1791779b532c085d238df0d3bae735d0078e0eabd63cc90a2e13d023983780afc8f83b1c14437937c16a1b7c41414c48cf4ae49587ad9fa5b16fc949a749e96032248c4667f58e295f999590dae1d99a2cbe3fa45bcf4a1d3f0356d64d40367f64b2c5cca843e5f7dd7b88a85d52328a00622e6c317879607bc036c9006d38652ffe21c83207c00f8348a7d0aaea5aab4c89077df170de6d41052641726eb6925cd85a9ee01a9e636346340e209ea96d17b0eb0921b96662ce9cb430fb6ac348331dd7133875769bbbba99dc49333950e4145a15ddb0789c4d2ccd38878080ca9e57ddc6cd5452790eec45482f8e990392e319609391fce0beba19463a9a00d8f1de9fbf22f23821de7d69fdfbf3019ed61aff79acfc5a6ba663a1e10da2b9ff7149aea43bd6c61a543008402309df0924de72c1cacd2d6120cf422e61fc1de345cc8771934d8be77d9437a09e06a9b2d51c849fd9a200fa714328d34f36b684f33df6968b827df916a599a4bc3367814fec21198e2213ff653cd2a463892966c72ffd42a26b3bb91", "0d55dcd08b54e58916f622f81761ef6a2e19b167ac47d3", "e42e1d6d44138f3d2bf12c951f454686f18d590fd30057405b5a3dc2b317fa97", "1e46a7486c5a03fd6758d938", "fd3c1fac10cc82e49235fd57f5aea0ee7a7bd6d539b138d4b3fb623aee591615c1a61228ef9673113a3a90a3687a12d4c6367d5f7bc67d422fdc4106455084d79c2c42c5e86368dd164bcbce7925bfffe7d96c13a2f49aac8e9d1ada3554e3fdc21aab00455a0f33b0c1fdea91b3588e7ad301bfccf9940027332fbdf966463491f7a33c093e0a13831ea9d2183294f89f414cf7b5876af04fa68d594430194429df74fa5915394427259e832bc545c13400aef6cf16620d48280798a6e49773c9316d79fa1dc758e54cde2e2cdb856092d83f4e9b698385cb976fd6cc2538abe055273a5b34a784182ea5e7d3ac9019a05de5e5afe4308a7ed2d363cd50ed6a52df1c616e4a82f607ced768445d13ae4884f2ae1f9fd8313924e8a1a8a23905c92eb231f638dfa6f4cb27bbb9844e05afbbe2ca4d1a3b3a5b371bf33c9ab6f82a7387d61cf8bf662097624145a983839b0cb9f4bd07556800b4054fb3d0bac94f44bcc9b4ac49c39f5571fac4e02ff09f08b3ed5add4bf8bba934e9feb773c0590b45c45fa036382f3fe9782ad19107d4630321e414b7b442b64f18fdd5219039e5740f34b3ce8925d1afe8a39e35ce8db086060bab63b9720700499f82db19a62897c6d845389461260303f9cf2bc7235a898b4620c2191ef05604a5c8c783d58009533a86b27c12b0772635d34ac53993ccf174c9087073e5e69b26c0c3d9f768507ac4d4e2af847b65e3a6e1b7a6dafb0aefc190871cdae6c60f0b1d6137c351d4cb211870791cf4cb8af2ea446f6401eb9ec8a5bcebccce898d1dfb13454df6b35b81ed6d7637e6e261e004080c60944f3a08e8e5fc7e2e4939e7c2607c8cf07d1d10883ba3ad43e2611826f245df571857ae0a7a867df9659f2082c19f94ce400132e48c7f8de2b102c7f83ba5cd1e785597a0ba0d73bb81bba0c00300d4bcd6ec25fb73105a46122873bfa729c0979d8d314ab7ea52391aabab513dbfd1cf01c2990c0a3612f4511c2bcf0f5a07e659a881a7f99c3f1fc4a46e66904427fe26a4a80a904c047d090c861a075c0ae4e29bfbc18b9620aaa42237f4c6fa76ee7491ee638ab5f1cf0b440759828e1ec519679efc776eb1468999a00f667e87199ad6891e98b95fb682e02517b024a6bb803ed23c944010cb7bad0733eccc12d6ab6030c6e88d510ce92e2f98fdcfaa1e37e41fbfb4e99589c0e8efbefd40473db42b3a73b57b22a2f8c9bdaab16831f1b117dd83a77dd01ee8d0c2e92203adb670f4fd65e618823ad196220d70e014c1aafd8863797c61c16382c2600062683ed3a180c70891717c52da15191b02f25d1715ebf33a5e6037092421989c942082f4b836423cc3e976c9bcda185de36f06265dfc250a27d2de0bc48c73b3bff704f3b386f962522f572108458bdb283c6ab3fd33b3ac13a406268fd5d97e17db9c0f780b4b2a8f761d15a4d8b3a0cd73357ecf4d26a6492ee069f19325823ef50bcb2f73326719a57b67eeef506fe8915a1b1ba1a637592268257b91e9c7c5d33cdd947967efc1952005d82ccef9a3ad7ef8ffbb6b658983d64c51242ba53f8f8963245b87a25aa9324c527e53f8c11d55f30aab598401589acd13f090541b3b057b162190f27910718b02a6b8ddbb8ca6cf40bf0d2848f4b76341bd5e78f476862bcdbe2d1bac84c0566fb45b21388221ecd8483d99fe603646b1a9f38a49230cf4dbe5d7883d73eece01bf", }, { "04892b94c65685f2eba438322b29bf8439938590d3e0eb10a29e279d356cb439f6dfcdbc3552af21f7e753221012a649a52bda780bc589ae63b04b981dffd113df9fcf14f17e35e865880a769bb1bf40dc99b9e85e4296c1f2e1590fe02b22bfcaf2d4bb7009a4d692ae4c2d5f0b6d3ca526240368bac55b9b1e6a7b498d3b137f0fcfef1873c5aa2111d7811d45bdc26be1c5d49b8a2f36a999b1f226ec06a5fbd59514485abe696c96ea89dba74b4688101a239b495944e30b3609f73caff3114407599ec5c30a5bad933655de7dddef97018ae15acec46504cd5d417c5052c057ac5f1c6f69781cfdae71db2b4fcac35054a4aa22681027356d68b2bdba721466d130d53ba8f23857631382b2de450232e9ad5551bd7c872ae439e79eabfb057d2bdab8d4ccf02b3003ade2e1f3e514dc92692e4fe5b579c9ee6067995b6c168647ce5a13be8543c23326a3260bb7029d2030ec05e565ced3c5366d20a283a6e95201fd108640d2b96676df712de20e4e12fa53f85f22cb24583844fabcebe40eece11e7221f12c88670bf994ed08e2000236f86258c386b0fccbaab8b68ec6a26fe41491d540193c4c12d1391ab3391de9317f41f505f1f1d09ca9862a6f289a533d2b297d4465c956360371ea3c8ed36e0d1563120654e3a2fd69cd6c9267bfcf92e84cd64e162c84199d6e552b42c33857264b5d7a2e007797cde32934a3f8c68b459cd95bc85e7466ccc9910e8dca65b315c32e43c3a5da908904c42cfc8ab74126919ceeef1054bbdae6ca67b02f1ac5f24808b5eee24577e609a3e3935a24b9ebc1a8dad1fc96abe26012928f2d5782755f3763427dda28867d0b1ad830d3c3f17b9ec278346e5a9480ed23ad44a523a4dd86e65a610ee0de1afab64ace7a3b4918fdc14c6b1ce0ec0903994da9bcf18643d7e0a4e6c08200bb394a89b385d2cb829417eeb0f7dab9fa7306a330f82973cf0917b5ca99b585d2ff0e8584e050077467f5245ecfdd5942e4fc72dc26e5ab2ffc61f996167e68168cee9a6d3ea1e1a696060465e35da8c75a1aa380004faffcb0a992c627fbdcb4e97721271802cdaf08d214ec2fbcb389d75709d7a6b9d35662661c8961f93d4a705e7188613f3769114c55400809cadf60d3b6068c8a5ceef078785171b59be1140c6a754ba1de5ced349df63d67d59d3a8ca3c716ffb506772d57e9e3f2caf7fe346c4ad64aa6c37e43b9bbaa8f58e51bfbac31fa6137728f8e5b728025697e5ad5c8301f6ff39eb2ad595d3cb24257adee88a84fbf1ade4d7550cd9ab94bf48e1424ae83184c35c5a5920157d45805c2e0ad129fc7f0ec3c41b9d6fa04cb8918ef379b0783d1cc2863cd80382585fa05320ca4f9fd90353e490b384ed6c166c6f802cd7bd39aa43667246e8da96992db7537d472c709b01114e95febaac5b1a3c77e1e9a18c2d180e63f0d8fa89f6a1ed63e909e4741af5c2a0e47d4d3f8779b7696358f58060f3f461cceeebb390c92779d30bfdedf1b08ed62dcc05a545bd0ea915f42976e81dd8a50cc4689d8d8007508bf53e7da5bd43c3894968cf0677681c6b818353af6bf8ac205139add1310e5d363ccadbfa0eaf735808325e7f9a6aeb1bee3ebb4a27576a88811859c216b6f84371c43d8063a0d87bd326eb6d81c6896ff534ba2c9c14a51d2cfedf33a5c787279bb4a7ff65706b389756a6191d2f791254233ee047d40d64c2dca878a42f903fd4382f39a89a723fe11848fe37b2008be53f7c2d037981d6462a4eea49df1a2e074957afd3c9dfb4d218a309cab395afe301ccf", "67b5eccb1790babc2dab5e0d1ff3871c3024177d45a2ae", "259603e1c3af3fd0ce3257eb627b02e0c0a48ea2f175de3d8c36570a445e5369", "e14de73c4b17581a7e0d0649", "33522e67ef932da5fa8abe628b51f3abd5049951dbc982ea95b7769652d4830c588fa45e3fcff094c8602b9008d7b2f9bf6c1c4a8cfb515401c7c44a7ec42ccb967722a710199e121a41160b1ec581507e9bd2e2e506b10c4b5a8d6977435aa08e27504957cd49e756e1574c4ccbbdde937de35128b7ee3455d2e665c596c2e97c253c94e405f85eb5de84874c099b4a97eb8f492d28f2e4bc64b228dd5984e76ca08376d7f1355ba8e0fa60fca96635075417d8b436278e0fb91e3bfc7d61ca8c7407086933c061b2d318f46f352099e1d317d6c44098539d1d2c1b7894db668e7a82ff991864fae236570cc420a4229883f1e2242d05aa07e175bc6abe11cc643cf1786a4456a2de8c066fb1a70fe387f149ffbe8cca7b110e256fd0c09b1d3bd7381cfa82fa700c8db1e79809ccf75ea52d0b349264557046e8703a191ddaace00ccfc513db5e78810eaac0a99d7bb1a5725e722d4e595216a0e12f3a7aab2e623ea9e1dad06169914bcd51b643016fea7dc3f2743b1e65877f1fd5581bee5ef206d86494a587ec8462a170746fcedb2c9f99090674ee687382711b4610ddac599732453dc063518aa36f5b4129098fb9fddc02eb8f8cfc2fdf0d904ef4d6d06014f977b29d0e9aab4044ce9c662a18b1a8db1ceea97854e90704430fe9b1046b221b27ac79054fcc68c3abd6fab7da66e255ff0cbd0506c852e961e619615c944cd9a05c25abb63742f5da7bd9939feb0f2f2208c8ce82f551a9d4d70e935dad018e3e4e6998e39670221601c3e34716ba75eb4e2fdf53c4d471c444330514986de45cf44d77f793c17e36a271fc65e6bf08943aef4c66547dc310c7a430e3fe7a54898de48f69f282f52bbdc4daabdb325cec7ab66fce1aea4e2fd932dc1a316c821f5220ea437447feae2fa478adade7cd515a27d8c132d0299b3ca1bc8516c9d9e7c65c38c238c69f03e104eb42a29cacc8d79b808ea6fb233a5056201e3697f81a2d49ccd8b8efd1ab0fd407c16a210767d1d3ca798ee53a4bbf1ce5090d321b1a64fc2c5f013c23829f5b0d2737936ca71595a1d02711c8a7b0e74654e5d76376ae26977dd49c68e3c0a7b36e047d44be42d732c31f681bd7b1b4b339f004ecd847960377acd005debfab13d0fb88355025877630aff753a7cfddf6851e8bcc8ec37b8f9149830f47e6b601098b2ba19a4c0808e31e8927b2525cb82bfddc9b4bcba2b46bbe768ee278fb89010243d16f9679f5ba4f13cfe76b5beb16c7b28daf99b0873098115c2233ee3402ac0f6c899a2cfcc83b2ccc06676999ad48017c4ace507080a26501993327ebdcbd1e2eaaaa99f4998b716cd9e36eb26b4573a03fd1d18047198fdf675ef4f979864ac85d230a011c69d8b6c45e9efbdc2a03f195c9731b4cefa60208ba845c0978e73d082bf6d6a513b93dc805a4f5973f4158f60a200167ca88704a15ac5ab1f38ed455a426f7c6a96b6bfea2ebc1ae1247cfe5ff29ee81bdbcb53b03b89568bae9a6f311d2b20e31c2d91bd18fd93a37be266d0de8015d52e325f78356dea0b77cc76f28e0f06e4ec705d1328340013a77b0b6196f44b7712fff4ae0ac7f6afab9456a95012b7c6d387285487476d189977e28f6c9d1a3f736320d61302c2d627d5a7ac8cde4988056b55eeba27efe7e640f94c115762ad5849423ae138c76f15b47bd2a2bde2c492489b7980aaf1c4e32a155f858d7be4fcd0f8a18e7b5d97c5a08d7885d6d56222ef49542c7f80498a14a8eed1c092543aac3439966d5b5d0cb9e602f4fd795c09d652b64f9ab67e38f48c88d18e30a9774f37e9c77b7a94cc7310d", }, { "4ab8068988d4bbe0bf1e5bc2fe1c668cbe58019c958dd2ec97164aea7f3f41c9f747527f1c0e5fdb2cbb9d2ad704b6955cb731f14403dddb1a28c5996707635e4eb5dd6ac33d46eff8e319cfe7cf6443869534ca9812a5b23a6b4ca172afffc064dc2b28197117115431e03c00447f87d9b45172c6f724006270a1d41fa094847cbfac9630c3a785f488c1f5cc407ca6f4cd18bac43cba26ad5bfaccfb8f50784efc0e7fc0b504b43dc5a90a0525b0faf3c8b4b7046fdeb1cad87ec667ce3eb6cb4c358b01393f3ffee949030ef9fd01c1b2b9c5219777eb6ff5b1d7c3ef8d8e3bc2193dfb597cf942c5fc50befa527fac0b44cda2bbb811b06ae87459750295371cd232754e2bb7132807d1225950ce64949b0650531800bd0074177677acad937ee008cc0bbfdf33c6b0552000238494be8be412a3e5cfa359e619d092c76310a76bdcb22abbe6f16b3b116b5f95001d20e42fc3c9ff6723e580f378475788eec265a1ed2087de8cc2eff72184f73fa5dc6e68a56dcfc85350bccb97135386d5b827c2d9aea065708f5c921454d1b9303f21d5adf19e00415acbd86d1e5e42d78505b033a515a435713649c50702f54623cbf31469f355c3be2e30dd8c72b4127764451d79e952ea1f9bb0269da56dc07060d5d9542a9c1258ccefe53fa3f7b6073cd38026256b45c01b6c5dc0d91e3139f30a8d1da7a076738f5bb23352693a8e3cbbb46226fa22416680013f9e3278913d06aee4a62457357f0a68d173a360af5e1411840e34c574b4c6b352f92ce33632911ad8b6710d357b7607ee19679e777baffb8ae3c0fe9786b2e97fdeccb5105ecfe81441f549bc6b50ab84b749fb33f8f6bddcb6bb733d6d5dbc4b29725b8741439b8239e53fa435ea29ed3324202b1bdd07d1987b0e06d8cb51013dad897ef02401290940ce3f2af72c5d1b4c8836299008c10b16c7e3e119e41ec66d9db6929ee09bdeaeda08a50665c052edf77b7dff3d8815046bf71d5015e3bdb29a4f507aeb2e28c536cdcc9b8d1e89849a0683d78f99dbfa90f94aa5dc08587657a8f042d718080de5d4a973f232f78c387b63c7143fc2a4380c491414a18b6c4a7bae2194b62e798ad7ec7d09e409425f6d0973accb17e4d860f8ec0283584cff076d93bd9b0c4873f9c57cddcebe3c3bc8afe793c6cb6b26c4582847b07446b7e1d9757de6bdf0df826cbc502bf88cf3a773866d3ff293034abc4afa3091b2126a278f50e47f2f66ebebb616e342098ab690f7f5828bf8cc4742c677d378893e9f188e8397bee983a9a0998de2a31798330f8db59a8581e1c847589bc0e2d95ffa68e39226cc15cf6cae5c4f5174e7848375391dfabafec202565ec2383721339f04c5c5d1da953d88f18cda65745ee8e99805e35203a6545a0416923b38c5db3c8aa00d64354bed27d7c78c4b257534bd7a18107ebe64d8c27b6afdb330d8efba79fd1fae480cd51fd3626bf8d79fb651b7c6cf752aa737a5123558420d48fc86451b358d270aacfa6c17f343b7a9956e6f64e4990c1b3f1e5097605edf5ce4247819b19f245e9a90758dd42c36699ba5cd7f3ed99a7df7eb155749f4b42d192c47cacb6b2865fb9ef2cfca283865cd06e40cdf7f89d76a9e2eb393e2e0ac0e2776da929f3f8e3d325d075a966d289c51347bd0bd523a5c81edef63ce9b72f5114c88b08b16edbd73f518096240a5b37421843173be8df4ac7c587a17ca6f2916f7d9a10dc75f81bc778a1eb730d12b51555cc414eab9c066113a7edba9a7f1a18092ae47f12f0368ba211feaf34a3b48a7ff5c91b81cf7c95675a4001c95a19d284fe4197fe8823909a123fcec5e45935da12416be1bdf14918414ad19b54a41052f5b8417ddbd207ee01d6a3e62fd9b0321b1c13d91d6ce15ea7b2ea0c670a5f5cb290ca8e62c26c6499104ab8e9fafb05170ede246bbf7313625d1fc9576f1609ffd08852a2f4b73c04f1f4eeecefe3f3eeb2185a618b6dd3e87d9d3fdcb349cc83c21f26b6c662bbb857aa95378e991640a160a23cce76153c134508c68ec54a5", "0d471079ad3c3432b6de852ec71692d12d9df4f984554d458a9dd1f28a2697976da8111ae4454c9a23d1c8eae75bbc14f8b00e7c065bc290f8938282b91a1a26c22b40a6708c40945d087e45633a595beb67d8f1c29a81", "f3dac58738ce057d3140d68d2b3e651c00ff9dbb2ca0f913be50219dd36f23c6", "bb2d033de71d570ddf824e85", "238c4e6be84bfb151557327095c88f6dc2889bce2d6f0329e0c42a5cd7554ab16c8b5a4db26eab30f519c24766b1085e11d40823053ca77adfe2af387b4dcde12bc38502229510606ff086265f45b1087375dc4a022eb0b641101c74ad566ab6f230133b7aa61861aa8202b67beddc30dda506691a42032357010d45adc7ee633b536a2fefb3b2143837bb46db04f66a6e2bc628d6041b3d306ff78e96205ab66847036efa1fb6e6a387cf8d5a105738be7163df9da0db48e3d8fd6a786f0f887968e180ad6888e110fb3d7919c42a7f8c92491d795c813f30ea645fafcddf877f5035f133f864fd0ba1415b3d698f2349ebe03d9e76610355e7fc23221c5c72b1b2628a40b14badf93288fc4abeaff5306d274f21938650ab236a39496d3f8a6e9086eac058e365d4335b51eafac813f9175bb7bebb75605909ec3fde6515694e119f7b6e96aa1d6d6454c3a7dddeacc83bf0c1f5f6c2a9dd2f460f3e5b074a33b8d7904e6988ae43a22a87f0933f812e45c4c518bf83e606bad4c3c55422ab2207e9d3cfcbc5819049f55e35b9663273d9d3a6f8a897fa38b0dca77eb6c344290cc007b68d913187f2cd480a40262623a4e95d90d5701ac2b9d858d70a27f0672f919c2ded1fb89134ac9a8ba6ac62931c832372abb70e811dc50cce264ece65e87338231f18ac007c5f68f3b1c5904ffbb2e1dc361d53914917770d66afe28c547d8cd5896d892cbdadc34cd6af348c93bdb8b072f38b085361e62ded7a38b4368824c759ec7d2cf4caddb9191e5deedc8b8388bc4ba2c0672321bcda3a7343c9ea71ef03750912f35624d81da5fa8a6ee676c4efd99d0c7258b844ded7b35d8c8233a316b508d79c7c0b3edabad5db9543615179b1c111bfd78b79327ac5b4155336d670baa592d441c810cb1b7c07f3d35473a45b57e780b7d997782aeecfc0363976fb608d6967844ed00b63ba75996054d090aeb605c195b1ff86f9d9ab5892d27632cbb59c06b3ccd69d33ed5dea9398f00b7c6404fcfe2fcb5924e4cb75cbcae0a1b084ea8b15eaa5847431e9ab70e4afe15b4c82239f6165e243e3b76d6c91d23b16edecad8bcb16898641f8e323671452034a8ec9b42b29cec0db210bad0444f1c5bf3505cc41d514d5a270d556f0a34333bd06cd6509ba253a6ba7a6db8f1a60c99f0c3d566a038a72f1271a178cc3ff890b0df1e7438c0c1a12d9873643e2d7bfeb92379545de50834abe2a345faf7ca49beeab87ee516dd8598b71196b8cdb15e7200cb5bd814338babd74c565faaf33d9a8ed4209b417345a1ae611880ea22ab2e894d5d14a28fe3835d3b2718125f0e6daabd85327455646290ceab89e579ed5e1d72a0172e4a6d8da70290b5022c941f3866f96cc4218de5d2622d13af6dab15760a1ec5d10918267f9585284058aba611ba07b1d5711cef505869831699bedc2b190fe1d578814065c91d87a8c8dc9b0d4dae0c80cd241f0bda3a6d5e714c894b7a48b1e5eed4555f103eb03c9db30efcb855df422d7451a6d70f28174c7ebff536dd2cd2891f6c3f264d632ca924c4e0d84b37cf8e06e6f2e29efac6cf008cc27f062441278dbc9f09cf44987e0e9ca088a48437b0b89efb9cf00d3d0c5fb449fd4b64e21dc48cf300c2d80a502cb583219f1881e78e647783d91dd2f3b389a1594eefd8ea07d4786f983d13e33cf7a34e4c9a0ec4b791f1666a4eef4e63bde7a241f49b5cf615888bd8130743bc8a6d502bfc73ab64d1184ead9a611832b7e24483a1a0fc475d9ff6166b86a18a3dc96910ff182cf326456c4461ce8acb3467f801890eaf1ce0b24791da9c650876e718c0bf43c475174f9712dd4a228695e8f8b2b23fc4a06358b4a6a8e1afa87a0280c3e098f218f7a6d6bd716f8c105a7eb799ba0220837fa5a96c8a22a826a6f7ea9d7216a24acbc7b0133210cc17c8190507badb421bc54997ff9340cdc1ee415126ac46a4fec9fee12d40f06300f7e397b228250f36d6f0d2ddad5fe1898ea690e4c7cc3a116a70bfaf6d2dc996753fffae40ba5280b8356b7ab4ffbc914ec74eaa070581fdd1d9e5aa2", }, { "4d81b652fee892d575bd13dad913d976cf0517c819d5183a72eba995b1f27efe743451721ce34791a15a6b7a6e44f13d4a080563dd1d9d4f0946e5ba3863b9ac970a1fb4ed66458ec1b1092ff5fa6c3f0271a2df8e3f2e97851352be760b6a0e1589c202f00791b1b89ae0ae944ced96bd90754bcfa3e355b735132d407d3b5507fd57f705e8a8bd82886b16d459ac91e921dcb8c5bf0d7cf420a9349ee589a5e2e19ce7c944a54ccc1062a0690f3152300d0bf5cd1871c1391bf6d7007f7ce26018ca2a5c6f76287fd8c8e9e7f93b1806460dd35f7f95989a8b6f9a0aeb7c6b0346955fb50b8735e34f1ecb4859e34ea0f022ff6fb797094206a34cf120b7f4664c531c57da513b296f0671c8e9bf68d9e1674998fe52da04f627f516dee97c2b3c988216e9bd3f58c3b021ac70898651f1cfeaef21c4f417ebe92dcad3aaf50f4277262c356584f816a5a5862f2bd720fac10f1b86033371ed603bc00a30cf4da8f579dd5bfdd571a37af7d2a5cef29f9001bb1605ee87f24ec3b259f381a69b771f78d21c4e43bfc83a916e08830d9885c8ae8ab6367c05f92e5eecaf0488262300f83f4e3bff177590857e149216995bc52311fb9f16f4cd74e07c7868a39b699bdbb7d7dace4c6a53ca7ee6e11741a63a52a1d96995a6dd752356dec6f14761ccfe38a6cd8511204f8f0630a747d6e19a77bb030c61e0828436604a28a7acf4a5e49b7269ac93b93b99e9e2e1c0c47b377f7e44e05ec6659526afbdcd5bb172404ce5a9f8786234114c16f20cda6d4359eb873a4a4d9fdf734e9c40aa4db3ea9a98939210f6c62142dd144eb78191116d194bb766ea96da38321ae27fcdcc196560ac75567297984fabe6072c771899906350f74de6d18518eb6898b934b11e945d94ead02b821fd6682602e03e9c70a1ec67eed33874eb24dc83dd1035fba5928f8f62ba1282907aa8935ae72fcb881b3277ee6bebda8fc75d6cd792677c25f70c87b11e094298b2d5f39904be211ff0980e5b83e8ea4a455622d8be9efdb5aa8466c88ea861407d54d98112faa10293af5e16974861dc9f83b45d21b112cc367894c421f5049e49dd205bd7c15e6a70bc810704e2e3a3659800864912527f8be743acdc474a26246a81fc2bdf669b9be7a2a0c986432e1e44b5675607e7e1ee2a8dcb72d8f1964272926e52f909ede0ac8daa32d1d850158db76b959e4d83c9da4e3bb23fd1f5b26463045d6cf13d187fe74a50c09a654d52d0e2f01d66b9f8b4f4aaf4c69fa62a02aa876f9bc4871aacd26a6c6ccfb9bea09cafbd0268b5b65d60aa23ff504d02fad4719698f8b044ca1bb037ea6af58a06a448080dfdbe6a5d698d5db9da5fb4aed04a46c8fa8b93153bca00a5bf8aab64d2b371d072db2ddb688a9442e948f0b99236828dc115a2fddfa2a29e2d4e02ff0173cf734efd4eb687e3f8712be82abe1fac4be0c1eddda090803fbdce41bccfb58c43038991ba1074b281a09bac5eba58a99a1a9678ba26f8f9e3c63ba095f02cd8f3b56aadc5de60477efbf3dcb54b854f651cc72042bf19268554c61b44f2f338a75de56c3c45b3ba40a697f5f21c4557380c777bcc91a151e5676c2a59606200bd476cf98d20b4cdc64bc3b8670810a014871be018bc32fe239e287cfe8a7cbcd1e8b55e08692ccfb4ef871cf797bc0b1fd7ec37931e35b6bc5d32bbe7ae77b9962c179f96436e4a32f566298d2235acf921e38c3f1942fb7674b65e222d17b95a2e58f072c63aa4bba1ce48c303f4bd24d84963f18c5e670015c52342dcdc9c0b348c7dfac721b568effe2bf2f2e816ca3279bbbed823beede8e12fc5bdccd0f1584deb1f6ea1875e9fb350919b675ccde0178bb83a4aa5232bd5e8e9a1b8daf905c6197367a0d106532297ef89f3bc690b48224592c768bd9c50a63d0881370d475081aef052b444744b33fd3fef674a37898fc950f887ed482d2a51ae615ef5b1dfa3a23257e6a6a319a4e2080b2c4094bb09e4b390d1fcbefc4d6c5dab620f8b05b1bd5d976300b007e2b8120ef8a6c9028b7d925c795058c6bdb6711fc5fc2476b9810d1d81bd24637537716edd3b7068b802c531531df710d3682f9865530e1ed51b3b56d860ba4e972bbc74662cdd1e2ea24f81bf469193afc02b14143a32e9556e3f2ecef97c65", "2538d98b64b6aa9258f9141840a5abef66d6037a10356366a3a294719c10d6c148b04cac66f63ebff052d730f8821f5e5822d869573bcffbdd636c7973433abbf38767597da5186df8ef9df071bc4ecade2633366102313e659db8d8e0f293d379fa2df79f456497", "a5049b0aa153e282457555bf6f82b60fc81aa6fd1c2ea3db031478ffb74b5b5d", "350287a6bed5709dfba3d35c", "849670914f5fe318eb01e8849e536374ec11e813acdbbe6a5e82a506f6aef4f916a3a7fb2e41db3adf990175e21f2386d1805af9bbc32a6ac156b13b1a9505958f68599019c4b7297314229c467114754277b10e9f49a4d12837ef24184629c8902ebe2a23f740dc826b01f8963d47100bf617b314835e436104eb207fa9a1079b8feba06d9369b9aa8222d38d87096b73678bc5db9a1add59394530e678b6ec93a80efc6e8320f2909e3e891306d69b016ade0d30cde64c2c903b401f9d01a29b5cb8619dc68ad6c21900b365a6b657f7d9ca4c145fe598a94eeea741e20a9329996b17aba5d7115c93623f2f5d6927068d0f190b49eb885429d771bbbb3980e9293e4d664a71c3cb629d869dc97e58fc3d328331b11df19a38d61e1705ec4c3d779168abe049e9d675337ff658e00d2d610c8f227d1341d1c41f1c01d8b5d83c4b1b30ae4318da9822f46402ee8cd5cfe9f3f22d90a5ec2d0aaa0baa85e10f5295cc6005c5a0887287b0c867a23da1a4c2196f91fe0bd4f0db1ab324c26fe6088d7583f3cd052b7f6fca38e8b21f98fd07fe78b7657da1f586f1fbd3d2b4079e20f21dccc0d269d53a29deb7c7fb63cc291d1d2c50ff163e08ce612310d3bd622f2416e193078ce4e1463f8a3490578af96ca98e665468281f1af9117a2ed23367df19b570885de9d6594f09aaba4090bdd1079720b08d54311793c97bbe14433b031c865b059cb4f75db74779b82c4f83eb4bd829c62eab995027b548063d7cab7d1a6f9642da6cf7181c0ac71594b97fc2c84b1768f81eb287091f63c76623c61e7ba90c922c74d46b9ae5d8094d9752bc1e8020a82601c356a201e0473d540053c707a88f4baad37826152dd245c4cee6b0019583c61e4327fdf6bdcae53584cdba8a503b835bfb5df9d649705fcc1f09376eec96c3da1e105accc1cbc21d90f527041a9beb85f8cbb1ee8db798838bb45374b741618f83b5d0801a3af2f640abdbe74ec3dc15d6711b4c1480aa8d6084defba82ed221ba359c9744705c4feee0955c27ef468cbb816694516f73fb541e0ad4ccf99ec8b67ef090505d1f7c4c3a8ed7e291c820261f12d92bbc6609da6c275349819848c9112826674f243acb9a29ab73f17c8f8af12c7437c11972c824f00db7ad284e51b9b508a925f0664bb259b4443d56463bffc9e5d845c9b9f79b24c1f457088fadd281f48238866e0b92d6253638eb188bbaa8bf6a81d2b1087904974752697cffb00b4ba05e5b7b842a3d2c0a743e4bd691625788fbe9df14600643b1d161bb2916176b6ee40aee38dbb594ec2735d41369ed3a0c6dd9073f1eb51d1b77eb9a967b53670a8ed755f3b2b73a6cb50a9e1ea7549346646dbe4b801c8aa642779d8761b6c2d2e1a9995e758ab92f07c4eb4a23c042171a4b354f434ced5f6d9ccd26cd6c2506e5023dc076ced15566fdabc7364f4a8594cd6ec404e1a9470f52a83052390e4f7789ade9179b069d9f84ca2c7ac9eea51035db817845aded7405bee90cbe92364c8c7cf8a366cbebd7a972438f2a9881395a8610a2cd0c06c46b60cdae5b1f473f4fd6ec48479cf35101656f05485198a470cd36af22838e7ba3e28863cd8ba7bbba7e3c2625c1106a6be44c9e3d9b9938679b26f0713c62c3757a2dc8b2d9eed5e652220a7711cd220bc91a9afd7c940dd8be71616ebb8b2cb0686dfa161c6ef56994a3cafaec5e79bd0a2531fd1c1a42771acb101a38988bcba51ad85bffcd8c67aebec5b37d526b29f7b9d31388e1e7ad7154f8e65516f0d80a30b88c2b868be2541d19ea1d2bcbadd30e2fbb1b4678bfef7f200e0f8309ac0701000c52ebbcd6fa00cb85c8d3ea9c5aceeb3adcf3773cfb3bfc9ac764d031d7c63ab888e9b03eb9fa74554dab4719d426d0875a508c8c86b22cabfeeb70b0f1461db4e5f639d2a2d28a089dbcc48e3f34394ff1acb887b89f75d3236c8143bb9b06273c3878744340ea1858a9f383f8bbdc259250e23a3c3992bf8b7ca7e1a66913547710402bb538a8866772d11cf4214060ed091d403e1c9ca3af75859259f88656a1cfecfdb49d57c193e60a2223627c681a2fbc7390140aeddc19df035a5207adde4f5736bc542bfdc943ae8b094f4a8701618688fadc2284fb423f602c41ad8ee11e5d9fdfa67fb7dc7d4dce7847d4875b3af667168ebb6082f6911c95", }, { "67f0494a728fbfc84e2f4a043e121ee40f3b12b31616c78e157ed970db28674318b08d8b3f4c538d7b9d91b9b0b09ebfebb07201c6398fdbb8684c9390b3d6a8636333a3b086302b24c2e5d47283935d33065efa3fedd5f755218be5d4618d38c5c1db75470ba06bcd853f3f08d39c3cd9fa3618e70b103c2d9b2101fcaf39c1701436b720d723ed5c622d6535c9a10ec4d727abe237e80fd20911ceb84a90285fc6e07f9d036cfa65995f9b6300a927d7d0d2b907bac9d9c4daa87c2438a583fe85029c886f96ed08f5886bf53292cc0265850a1f4ee3e3288b604dc305d0c28ad35e1242f4ff4ae988b6deba48aabcad2fc6cd7eaab0a63510f3f915c4bb9f9719b1d90db123f639d9d4f3227eafcfad769c2b204dd2555dc54e738909122022c4f92f751d25aef6f9a1187750e825c68450e6d1223c2fe88aa27194b492b6788be6eda80b9b9f053cb77c8d9fa15324f23af5147624fc00c66e947b004bf38b31e1343c7cd341b98abe462a5f994e51d343664968624a2ed0dea9d0299d5c5a7e9097fa63d8b3ed96f917f693654766a9adb01110fa3fe0d8e9b102860d5c049df3fe00ccb2ed62ab05583e6aa0a5134d55245d4f643e274def29d3fc86d79979d599458786a8338b0071f6a01609ee6b2e4bba9289e2df780bb27491890d0b5ea650e62df819b8f98aae99a1b8870ce6d3c7785ca957d5b4094946925751f0fda1d62a9aefe3937a912c1b49b4272f87eea7e397feb84c0702929959e38a568460811e5064b1caf5dee53f920c6e19fb16fc9214b5de1cb770b510533f66d8a0e7f6f04ba8ba41869f8018abee31a6042d3919e217359988eaa9db2a10b3caf7aaba43527484d81304f0bef22165f74e9e1031b545ca3d2f74195984cc237b76ddbec85142a06446902339b1883000264031db85fb19b46f320ef3fe316f750f2d3d6070dec5b66ee8ef20701f20965f5171e44c8a99bcbca7afbbd81e30e74c6d48bc4b0d72baf562da6581fafbe14b6cc597f75e53b305036ede219ec56d0c0d29571a9c110ffeeb747fe56f6030dc26c8d3841b868a1ef56840932dad9f3bd7f75573086571f4d9f0d949510a2577d2f8fbed7e850c73ed4c071bf9a656d09dab43a610b49aeaa57333f67d586d4f50683dceee4942db9549f68eef4c5f8df8a2330857cdf2fc4025f2be7d5f0dcdc74a9cb593de91282787b716d416a3ccb8d6d40fa3c70be4ecfda26a5caf3724fad3d98db16ab6d8f26defc68392923b69664b0c2d56f01a549284b042bbd43c8faec940187f190aec08d06f9a62ab03c9f610f64c0010a0939451d5502511dfd3da1fec5a38f64640c7b6db2961def257eee9a3eff944828e9557deba68bd8e42dc7a9c1570e35537993061fa0f5351fd3cf4ec36386ec4cdc5a2882d5f16703b900c5000efa63888d69982e5ecd3e329c8cf5f003e23ce03c55631246ca15ffcadb0fc9d5634252ccda812ba7bf5e343c44244026512062a68374ed4d8add0855dcc22b30148e0cef0f2886be76bafabadf3ae1205b43c6deb8a41c338114895dd6b49deb329ada31b350e02a1bdad4eb05b61b50f9d22fa2863bd607406f552713e302467ddc78213d584b4933202438d63f99d011b97297f5589f35b7e45ccbd76f02453b7a7668c2b1a1f5d1d63eb805c8881771faaf67433eacfb22f9b6fa58b93f9423a5fcf667aeec39751ae17ad36992556431bca77059a29353598dac12bd3036633d2ccadc18f44123e5bc074f4e5ca380095af062fd83b647015259be929011cfbcdc9bc5d0dcf9b688f0f5d74da95746f447a9e1cb5028ccb2827b45129d04cf6990953a6d8ee0e67fe6bdbd8004f4744cae5607fe7ec4a0f14fe603dcead3367b6870d8e751cf57387d04b881f92cce9772d695f19b36e2db2cf6a807c9ee83225f5c09a11b50e99855921a4eced8e631af7c234aa31615c00ccdd7c6ac5ae8fba6e29cc233765a891864c7d73dae08ed1a3c27cd423d8d4efb550597afee8356c12018f496637daec83575f5e38ed2fdbafabafd38483c239d31cb4d104e93d16eacc6050033a3c86929be4ca8914a538bf540b43d7ce7daaea317bee1ab80504846554879f900d312bf2fbb406a0edc5f4f809cbc68675b0b7f09fd1a8a4d52c0929b3a8b9c1dae4b3d599b976867e6a7e8736450dabf5c49c949544386a71419324ea4ce5c4319899ca510f50d07ace57b013655b0929f79dbf3cd629ad17bdd10109b7c53a4f5f04a16e5471e823c898362df43f57ebdd1627b33fd4cafca6cc065d9140acf0454d5f99be47bc87e0f3b4d4320bbf0f21e7c261bb8d5d615963beeaa46bdbe9b83a8277813ffe6132b23564bef5", "74dfdc364097c39ef91c01b707a522e28edb1c11529d5050ff820234e6c0295aa00591e09d547e9671804d7825705ab44b76c59d1315ed1297ef477db070d85076693013bdafa92e2ff6a654660008b176cd4e8ae23b9c792be3f7db54cf2bca385bddf50a8624397cca8ee3cb96944164e3cb461e68", "b3b5ccd7ef49a27d2c6d13c0ae77a37abec2e27e0b2d3530cdbb7f36792a7d2c", "c0494bb7249f864f69beab46", "ed8d6e964bcde1df68e7f362243073941fd68ac77929c8e480c89f519f748b3dc337b1af6231632c975167a8425b174b42c2c60dfc0ec85a0a212bf5c9aada818a83f9664c8712d96de1036b5e5d8c8298786b753638de3a8da958549f16eb9c723355cdf7b999aac464ec39df7d6c1607e81b88b63043d1c847dab618f1b19336911b4b0145c2a694e61db71e021282006d48e37f10f3b6314dd012a07618228532c28ca84a936e0eff83723d117b2f2db857d14af5bbd5948a0e53018b31e57cc2a81f36aa013a844990753ccb347fe98fab294cbd252a8b8f7246276275d2780511fd3cb7baa2fd1548184f968c422230f7ad73ae9dde91295f79f6b799e7d234dfd6573fee6d6ae748b0a8cd7ed4862ebd957390826f276c2afb01fbb4b64b61a1bfc138508efd630e77580867bdc1e96a48a694cf0db6c2a11f05dd0bc8769e7200bb0749f5798b6f3559de55d0c281eb5df22b731fbbc109da9c68f209b888e61240c4c0ca006d105c0a7f43144021547d3316e5a99f6c429f9ea2f17d77dc68bc9d5125b6260f79bc8b3b8061972e6757d87b6544f21645c0b4debe5224f7c48142c09f35b8e144c0c1e6521f04c170519ff744d61abd59a56d25a26c5ed5972191b25e78e2140f3ce68fe17be9e59a79f6c69619a79b83614c670c7736d19c27fd22515fb5b896a6418cc0b4850e85c07b38b995cffafd9f69763cbbcfa9d1bbea6868244a66a5cc82e815fae09f5775d28437634926d571c2b0d200855e09cbdc67d10f85bd4cc334ded4c83aeea57f8e373a950f135997666b653e8de47a3bc0059525720045996bff500a47baeec97808fe971d7693dfde339e8beca3598fbc053121536c30d0af10f8f5d8e5eeaaaa9586d7abb563fd69e88351f93bcc46520f6d97c1a49ba9f8f6a25cdcfc11b2a722910aabe7435ac8f0dcda9f824fdde80850f21a2d4bcbfd2e9fcbd14dec05c117a9796db49e2f0dc55e74c7f0f615bd049fa7d0bfcf197dcda3ef3de90762e6f6f9f8a8936bd04fcf2a97cf18ecc8f2f118ffbf02b67f252097e4289d02f264161f6f90f79e1e1ef8414b01a9e1a77b88c039ad6eda6df1e28fcfe9370f0d574aa9e857dcebb19eb7ce8af9b19b4481c9fb3e1f0db3b02af483f737ce3ea824b2165e7c0fca8585383d4b0a16eab2c7e3ee5c038f939a97bc8e1c093cc5372ee45d81836c988f3ab3e6ee0e5f9549e4b7bc381a2afac2074cf75ed56b0e757e7966cb253d549fb0902da98294c6dd4de3c2e166b7e45098d2729b1393deb68471d4d3218dea3dfd0183b654ae4092a79357945eea4b28cfd06b40d30d1b4b8f19827895f6f908f0fe511f74ec84cbab2483ca4bdfc6ef50178eabad79b18b58529c9328c13c52c2869858cc20ec36ef7717e1c743d13f9607bbdb0b701d9df6aca7366814e883d23e51ee5b0f20ef70e2c4134ab037d213315fddc89009260981329a1872e541767adbd5ee9501e7df4ef0cdfae9769961f8716ee7dfbab0ec89b3f62e987387d5842e124a69b07245d359052ada50cfd67472d27ce2c4eacb5421b62dd7331da54ebf0989803797f4c8c781d0e2e6477b421c7d5cefc8146aacc0012af3f1f7cd71ce2b1045d86bf48c9a13fe469a1865294e160b4975023d0eb24ed26837afefc250a914f86f8b1f5d67d65e9737e841519148d4dd5dbf2b5a8b073861288ec9793d4b113d71c01727f67d791852fc3946dc912d60fc66bffccf4c45d859eed9f0bfc7f89086df5d5cd830ac919aa7cdb4504018052d67f6a3ca012ed69187cd5fbe91875cfade381bff1e804ba59cd59f0f75cb46dcfba234ab9832c3fb9aa8dde19fc1fb30677ac1793a38d94aefd9ffcd4e777e9e4f6d49e0cdac6c16a36bc2f3ed8e23b80350e3be6d866aaafbc8cbf7c69fe44c2aa80651164803150c23ebe262aa669c77ca94d215895d2ee9c3e325a0bf2c61e419a41e0f7b1ba8ee0508307d49301abccd5b74c054b6c7bd1aa67cffeafee033761d8226d9dbd7214b130a867764062cf4da685deefa23693b8549d5ef5e53df85c19bfb3c43c6bd073e7a836f849587a4747e1a9a3c7194f6d5472d2e3e4c81784a3061fc9bd3b94862c4784974d859134369486f2651f1db94f511c6f59f41da0d75307191602730b88e4e6101fc8d392c87687f3be454dd92fb8ec380715bcd88aadb63717cbce4db91a36821a572c363759d8d0a2ab007e5981b78731dfdea20d900b14f0c5ee6a4a9b532ed2134e6edb4dc267f001cb88dbe43aac4aad453b839d035697df7de98ca7a9ee7601228a79004b89796e9ab971aeb8e62c789bb21f38b77b492c57db402bf6a42ad0cee169e9251d865ea3e5f79b1801ef1e53797aa6c7060d6f9486081", }, { "04cf92a64cbe135f7fc1d7223b95e41d13f04b482018039f4e7ccacba8aa15ac79a752c5666524e527fb076290ec80a3dccbebfce3ee9b316a65fd130f12bf88b9124d1f7772049e6d0c01fef881a1d44c8dd02f7b6b60e6d15df9e06fb86929cab64842284de09659e19451623525aec2f5dd3e603e24319b1d120bd57b34a0317ce25ac9c2f022a4847306b998b57c8d92baeed0de1f6cfb3177d0acab70de275238f1152813b9ac87bf651f74e1ad079b9bd779ba4374ecba459865b5768d08ae7e1dd691d6821895e8380ac9e5116580e8de3a2c5326e698bf4c4d35d955e45772bae8483d01de2539e8ee1ef9539ee132d80d85fff41dbe406af319c0d7703292587bcf5959f49241e2b03a364e1b682729ed261d0ae45d74d77634afe667413ee210983b042a7ce6dbb61c29d18450fa7176177b5a74f032ea24e1d08b220f6d32a7a836d1241cacda39d6acbd26a62f9dbeaaf7329a291dbf0aed4a2cfcb85ea360947585b1215feaf70ba71eb2d6bb7081b2a21bdcbfdae6ad2513a9dd714d3d06c2c2b7e322a1db2d48f9df1fb44fa066f2bb42b196295ebb3c0898ad55d5b317986afaba0bd5e754cec773821613e908ce2bba6454181f9020b73e758df18c255c87df675cc6bb2b8d2eada44196ac10c26674167f94a79f4be515d8d6a1fd3228dc9a85a355b030845dd4c5f481d5b6e74acc66de730629581b022fbcff61e5dcfb6a7f511aafd577849a6b057021ecbaee53986159c1ba74c3e930c34a159f467f1e9799cd6c1151067c56769e43308c96c8edef8aa7634d909310dba9af2128cdb8c29b24d3ec2a4f43a1ed86d1791c9a670b240e6e719f01827aaa319bd3ff53959a776886a1b7c942a54f141e6bae8576d294e44333e6c5ad90f74863f69bf890126016b318e0f6bd2f0adb9bb861118af5f6cd28dc93d56c8a1dd080b8c810ca29267d410673fe367dd9d1353ae2bf2fd88d57b4202c21aa49f12a01b93acbe260492367bc219d3afb6e6f35502f6529bcbcdddce9fe8632efb034a9eaff8b4a48afb105d04e3fcbbcae010ddd6636992213750b12fb3e01ab72aa957136e0bae591bfb5e0fe819cac82a98ae8df230af399160594540640c6b1d537e7b5f1cc47b08127ae02c35b846de56c4c08773fa18d4436e14b76a7fc4bdee301d0af4880306f2f33328ab79f6f24ec779b2b1928704f09bbc5b0b7108e9a115e4959df79c80eacfb98649a0788867e23b2974b22e654ddab0494bc922ecdf17727d0f0efde9dea7601857d890bfbacbd93f7df794bbc254f50e1e17eaed2f5d5a2e6c58083aff68434730d406fb9fd02b0dd7bfb99a04aea812b6830fe5e05a044ca21c77a174bae8b58eefa11ecfcc1c977bc6218064c9931b5c92f13cfd05799f11e130869c293c1b08dd29c899365014fc8195514b286c97cb6dc4b8633e47751f87fbaba137b6aa04d072ae06c2b2f34448449f60b1272c1efbd4722a2be749a3d2e5450aabef1f7c51bd8324607668a8caf8097c2f358b1b09fd3525d47ec9a7640eb20ffdc17c4f7eff63df75dc7830c471ace3a727feb11533d6e9a2a08106af33069cf482ec63724032e81cab18e12cb5c4c3ddc374e2f75bcc99fc5da09b80a738852a14e8ac552b8471c6ad52e35317b730db2c13c277e06c643e0d0fbea43833de4d2c7a9247ff040e9c56f1ff7ea92049c5341c4d1478a14275a10119d934e8165152b89951bca7ee1399dd8232fdcbf831d8354640e698b68799d060ceb877201b2fb96cec514affeb28721e163e1648164b9e5722271db9b0ee1a7f96819fa1b1590e9daa598d9571ffa3882db9d034056e9b2785a8d13686eba61d7d45cf2e9ecdbc391739ce89297211472be18b21401658c5bf29fc3615924382d802a166d05dafe7876e70a0d081e80c63632da379766928a0555eb5e7a238cfa4da267527c66caf34dd40055f2801b29b3f5604a5bf3d46048bfbec2e24abd2fed2481698a4b5cd71f5d2c12dd473b903c9bdb978eaff7d76fb69951005681ed7b0257054eb3dd6d10097fee51ba7e8d565925e4091cbb78d255c9d3ab4ac0264d172c9bcb0908db1288c9634248f198a1167daa323822058decd83936985f83b08b1e7b942756a7af200af168fb8a091107b4443fd649cdc22106f9b9657c69f19be485c23b2c715b3762c332eccc44f380883357d10019f20612ab6b8f155c2af9e2ec340e5d8f45bf5278ac1fbc9f9f44d2f615d21007d822b244b1c7a0dbc182c7f5912485d6e4d74e90f60a2f964e028c63d49c6aadbf1df170e4914ca514139ba538207b1cf7caaceed4db8423dd1086b2adf15f6c0e50dcf2e12898f53c339a745316904ae03c38b417bcd7f5cd5ea77a4f06e65d56c24f37ebe72d271ac79b6ddd2bb8bd67f0727ead49737aa71af4f620da53769ca3ae878adbaea5a249128074ca3ddbbbaf5a68f9cde2a0e8d69708b0ea7f4c8d2dd4180882bdaacccf2a409a681c551776bd10439fb12b7548342532b371c0e045d8e8c895929464bdd4fe25f0533c66104daaaffed52446094978bcbb389c", "001084c8a5175c0ad43108f9215c35886c82321c800740c6118a3fcd45776a4588ee0e2d056a37d99b40d2bd9c0845088a77240b7e65d18fef105d3488c77910b5873dbbf275948db5", "d614d2e671066e387f7eee07bca9f9313d86e6a4d1371360900d670e11ecf1e7", "674a516f8f59f9067e0485e3", "1ee376e9e3c89b2147bcf75480ff0dec1d0e8cd45ba812f34c84124871d484b4ca87bfc8cf99f85ad452c482933801426e2737a97468809fa36caebebe8eed07a626b3bc3614ef1ceb54f9221ecb16f413f0bd9ed4b3010c40632f05223484af7bf5948c2fb8a3d2ce04c53e3f2682494f3969a0f8eb738cf93c0141799c9e6b68924433f0326991e19626bb19e6fbb5dd46baf39f92e830f9b1ff465a007f031891fb1f1799cc122d3ae7a55624356b5297bd5d948d9ff2e414cd8adf00a53524df43f398938d33c93b2c06bcde2679566c0a7b0177b4a873f35874739d550712d5cfe3d25c19292ba97c01d84224738bb25546e5c252fe5e5f260ca881aaf176a271a6fca2edbb2cf23ae6d4c56c20daadadb8205c2e33881867cd67ae6e59132edccc3601f014b744ff8eb6aef5e09b358607695d3af42ab8fa30e9fdf99ce54427ba9da3699de19f7a8f9be368df47ff0607601a91e7a5fa6e72be50bb32b825427cdeda3972a18a23af290986cde14f5fb9cbddad336f5efcd2d7a0cf3d5b23e54b702352fd5ee52d7e3479441497d56e17d5868574c56cfc421ee47bb00e9c75b84262a1b9e2cbfcccfed9c4c386ef0d2c1be9a7b7556909b5d72a38b7258acdd624de2396c75386e077c34f005f92a2203c82d1072c8998f03b1df22de832ac733977705453b1d72336b8d371cf1ed3923f462ecd22075de5df68c83ab1e6648ede7fd5ee5794a744abcb32af73bcb182cf97d36f37c15535c4107b7c8f2321f9fe0e2b6ccbe74204df3d748c05bc1e0e2c55ae1aee2d4aa4a52e98ca7229d6d06576196ac8e4b14a9ce807075cdc876aaf904c9962741efa8c6caf41e6b87b2ecd6636e2e58f3ecf576e5d8b895162545e618960ff6e336ff17eacd5a1eb335001633fa78c41ed05466d904ef9b81b643a043298c0e291a085e4e67da72e329adfccc407f800709865147db49cbdf4232073b7bc7ad89b3dd901d927ee08ae6497e0f2f9d052ca8d7444d2e2ae2197f930a7b1c8af38d8739ad298464169823684612cb628c484f710cf9c552551b6837b575a43275100bf800b7a3d777adc44d07f67cee5000422b9049dcfbedfccded0f2aa4d189621579b01e3fdaedc4d772dcc593316ca85e7aa248d219dac21c561d318a4936ac0d3bd5c75311486c174e0e2182affdf69bdd6a086534e4a602efba2b9363beeb5346539b45336cbaf479da6b15b226a9ac026482216dedb84ae3443b306820d9f05f78dca7090d727c7481d82c6e5df80e189e24e46f5758e453e542bd91a58eb51a89e07c50afb543c6b998704432e863dc4c0d0236e0672835a7b0b64e14f5ced2904e54da4287597f920bb4d542c35d3b0271cf0eec055656d523d7d2cbd667445d3e8634854f8616b7d7a7f3e14fd32651e9df40e1daedfdff1371f16d5549ed5646adf2d417e4b3a4d145bbe0974ab388c2716861a08296b862e4fd035163281457877eff89dadb160eb2b780414435784804bf4fd36602699d8c2f6a8cbcb509198c38e2df2edaae7bd7c93313ca98a9c2d24419a12ce35b0b3d68c18840e3ff8739d70969927c7db9a6569787bdedf5c99948a9e79b2302a83a71159f4c789b3b3f05f1e574f8a24c899ae3457f8e73f9bd86976fbddd83b1af337eb8da4c0dbac3792921597e18a2fd3a0ac89a270794529d370d36bb6dc7452e754e903781cbf57c8646b92d5d02842e7df229b3d721f9b981f9d61a48f00e53948a5dbc4f739849609d94aba3e3f5f8163d40321576cb8eb8e89953b608a01184d41aafc13f40c47b12240e3ad49413473c26b6843f4514be221c2af632d1a54cba230457f23f00b2608485c381ae03b389ad0a1671fb416de4659cc7f7a9c4b6d9807789c307d061fcf613b96a2d79e5e3e20b863c8b1b75f35c982b40ac8dcb7d2712ef7df94901facef783e8015a9a48574aa6f0cfb0bf6c1a3409028f8d62137c347f5a35ad6a3cd60d71aeb29bae56bb4590f69226fb4e08fab7a9f41e58f4d5784540a70e7a97720c549c8440b089eabd0eb3e4d37a2e54b1160572ce568f4256dd244decec31fec555017ebf488e878945383750eff26a8a1cca73e7d6f52d8cb229d5603360a3bffec23029ee34145c4aade82d486758e0aea9e1b7bf0b4bfbd4fcc96aab66a27fb463b48c6a6c5c5a60253e2fbc5716ef55629277a5f3b89c300e21bf1226241ce0d587fe3f5b11e47f35614169dcfaa375ee1aa589be33a4363765368f5666d155cf72e851d426fa67b982aac4dbbc29356d71deb0715b34e00b9fd8876bbb09ca0701b15615f05cc45e128b3864b26003e6ffe801c4e27402f37b8997e0c29ebc273dc03358cd22fdb68d9cd3b56ff8248a727c2d4ac65acda4d0e0f511bc07ab06cefcf444f1002c151b953d7f7b19695668a86683497c2a2d2e69f19a4997148d2e8d158da859c8f44437d9ce9db92f84a88e89cbffc74c0ef4295088e2543a4f7c6ae9c908bd987bcfd7a074f83ffaf3888bd7f430dc5a5bb70d223c21b1bcd8bff2103408460df864dcc168486f6a66d67ded366c6e10f50bcddada93627cda711764a57ec36035ebc", }, { "ce72c93caa49bb9850774149a87fcf8e23a0c53701554468645554553d54190bc6e247712b02097b794bc421ca94afed34742435ca689d2ebef183fb469c060c7f4d7daa508726c9d2eaeb9c7e9a89b30faee8d9168607d4778acfbd27d5caa623475073ce763ca061273cdfc2c692d1747baa8a01b15f783b2e36620400082747599a16cfd6b630fef310c0b9a2912d1d3bb71eec16972745cd8a49cd927014eb0a2abbe0e1ebded4fb9e8d9e2fbabb6a71da5688717ecd3e08160b9a861f86904a41702b2c4fff28ed8cc61d468187b75bde3fcc5c0c0a642215fea83584387fc5a9aaf2f8a91ae535e0027b618a32bd687289c47e9428a1a92649deab825d702b076223b07c08e55c0b60be95937bfd0504c18398e924420f6e20baf07e2b1b858d3e360a461b66517c24e60f9fe314a4a4973c8dbc7e9d2a9f571a1d8235a21073d81ab9f4800b70a5f17f44d593e8792a2507e6a3a41042fb2a5f7e5f028ed2daa88cce28973ecd88bd125d50fad77b1fde61c38272057d9c65fbfc6789ce41315a105af14e277a0c39d75c34aed7538c39160eab1c8c47818743e8111229426c399c5e88c4d894fdaff0315ec885ea019bf9acb785f3380c37201d494a60b583fc130bc0eb9fbe9b90eff95874e35910dc05c761f8006e2f208b786aeb2eeee841f9a82d9966c82956c181caa4dada81dfa2e2d7a25007c2dc7f2dc7ad1bafef14581cadbee4d614a557df4931b9ca105bade8fdfdefc0d96eeda11c08500b1ca827ca670ba07bb0f85af92914c43a6f71226d6e112d487f1ae99b2239a63ee2cd0849d8a9c488a11f82ca334604a2b7260f25373c6db75656527890f9b772c6bfbb9f687f27099ea9d4d1efd874a6ff83cc36c039ed1690408f20394692ff054d9e6eccc6776b6f4b3c5f24b0052334d159f40b470a9b8799bbc0df4dbfe59a5e536624cad193160ef23abef85df2c9b6e6d4fdf16f848a2a446a77044f1162a278866c491982570cbc16041908cdd0efa2cde011526a3c96d4b39a23c5fcc53d8232869cb4dea871f4ac8afc795aeb1b28cb2d7a3669100a1cab2ee1a7f31e2a25a5c6da836e4b771ad57393305faf582adcd26045e26b618d9943358c615fb206258c8993d700adac7440dcd3ef34fdcb065e10e9c9727662b5abee160aa01d2f2ca6c203a76fb01bb08cee9fc1eb6bc7497bb012ed2774a2d263b9dd03d60c307ccf33233ee33eee702c8e3118f9f86174a97462d0e804a24bbd7f4f938c7f105bb23399967288069e1637b60f2f1883d88ce5a874ea4bc0a7ca0f3b568e4bb1407e4bd6f0d3dc8fe91345f8435d7b1be961c45e4b0f1ef2d92d2d30bb78e1fbf72cd2e7ffae76e8c2bce005195c2003bde46108f37ffacdac28fd67a0de62970b347f0ae3f5f3a5b1d3aacb2fcaceecaf2ff4a2aeef6f5a176cc1b74b234f5658ce603bc353e075278a4056540e43033d37a6eb2615453d8206f5cd294423811283bcd5d79c4afe268a547b98977ed5cf24c0f53a0533bc0b2889356cacb67e2f7353060f9e04362859b1c1f02f96bf5457b58e5ce84a6810d39d7c7f53faaec64db5d6ebb90c1412bdd503ec6bc240c277ce1f5f18876feb24eb6a77e5193e33ce141e8720329add079dc9735f0a35d7d85436f1dba6dcff9147777760b5aa2ec9c8b5e9fb4fc602ec8f754c99ab2372ff5963dbff3fda91865108e606b214cf7acab875197e78060eed52a798751998ce7c73cebc4d5f429f6729a5193d7593072d0921ac8127ba6e796107ee7b9fbcf7128ab35fe9f6fe501fa4695c19fd64460685f287acacf5250efc13899bcf80ad5a340d432a0b9449affda5c8fa090f008e01873aae7d5fbc7972451542c5c29cf9cfdf23db736c8a7112536b1b626caa63f3e4117044cdeab612fff8d8c194d19174f56ce761f6587349c48fab30390f231d209461ee7e18007d10d83ea5aacf199f3b00003259747b1d03274d3c3670595604bb4482d345ffe31d3e88c70da16649a2677bfbdbf618de1d651a53d573aada2eee5c01335ce5519a6d18a70f7ff0b1e66bacc162c49f7f29b9d3fe2c7dd85b6b355c9f9141f02baf08d2be87c36f6d2e1b2e90dfcd100886e306b360df0ecb146a6aa5ac5ad05b63a219ea65885894a386248254348ada17908d776f9b438306ad28b208f80d6b9b265500aead945134b9d388ed5d6205edf07c5d8bbfe0916d0943750150e09c76359d24e3317517ea489fd8a501dd93f159f07d19d00e86d952fbdba2db771910143df346b30a30fba908a1abe5349c3f241958f428dece7ad9a91cb42035c43573b87b26c2ab216cb4c21799f6b3d81acd300ff50edd6fe7868b9ba6c160db3418565ada027b46b63e5d4f3411284fde585ed3673b424ec1cdea678e4a43c262991c3c9b988351d6e0a10af1c959cf21b7a288f2e4d7b3b2c11b400b5e036df71fa993b72ce48d0d8598fe4ef1ce70a970f89b55cf4f07906a479bc84a08bf6ab25221de37afebbc47ea0b38b87be128737d7d43cc84d336cc6ffe1677bd802910a2084751f30398dd0ed09589b2befd2f3b40fbc013318c822fa2faec2323fcc52b43161f47aefc557e92df3050dc5f8b1c5a4b2f8bd7b2ba7aaca79dcfa362fbe7781a2e261683a4a862d5f83e34845a8fcf8a1aa73cd521e87cbeb71f20b20698cc34bee3b8628b1a3784596c", "08b3fbd73d157e79ea9f61665d19867dcb8c1598c1d37b793606936d8aecd992a0d46addeae857d488b83be5d1c1639d4d78350e4cb08782b61bef4107c9d3a79d3d85", "a56f38b4bbe83b3d9e562cdf5ef5b30593f08a1a166676c4fb0d5861654e640b", "8726dc5cae9497936658f603", "88420357d1ad70e7c7bfd55b3cfd4bf06cd4e9b4ed5cba681045199a06985956d35fe86b28b9a4599964930d05d230a23c55a6a152f67082a453fc31f68489df05c553f9ae5cdb3f611445db384d79af865e52440a876fc4153d896b7a2318dbc2a4495ecdbb2e9dc68022326d35289e82aa55197aedc266dd91ba3018c7b474ba22b4e773773f3e9890ea84bc16a6b235e4bb69e785c40c1adc15b0e0ef03aa147b0d14e62341e27398b84a53f72c9199cc1c94cbcad2bd31aa69c96b06d01775b8c0f80278a43f526664bdd430164863c9c9140ad87798a5b8f38dfe90d37f54d1137709d5311136b728e6c799da244294daa4c8b44bfb0acc603a16c088a081129a0d2cff55ce1c4ccb486fa0ecc3098ef2196f47c49f9d253112bd5746fd99df5d2be577617dc2519c0ad04ee49ee1d7be3d50492017108fffc9a414ea227af39fe49fb2c895fcf00d927bf4a2d78c466fd44df4768e6775d39fa5c834b60979ca27ee9f00faf37a090838f56275a894ddadd265a8d2de74265e4d8d286639ce8f01eccd4f551cf6b4429eae3f08902b6ce6ef422cf91ce8946d9403fe8064784895b62a7f5df76ea294132c59da6b9f53d4195c1e9000bec499c14cf8bad460aebb024a76ac50616f0dcda71c0f56dd3239b11764f3ed6ed06c049b2ad673e4beea391dbb854fde1f01b1900858b9809259f3906b34f95a1c6ce8d24fdf0cf7c2ab7bde2202a7f1482baa6e51caaccef9f541c377da620bfbc63955cae0e6644ec8ed6878f704f1dea30d6b50d4291892bad19b0234582d50c6cc0b4165322cff24a9dc2ce1be35be0fdb3bb7abb777ff0b2f4cf16277388af5a89220d59f1f45ee9cc2a0fd7af9aa8e9e8d548fd65be4e47e7f8ef58f7701f93a42e7ff78f70e807fb63513157fcba96ad9731b2e8f80da85ef407d5c368ad16f0657620bfc122ba1b10d7ac2bf46d8133a9c6fec1fe04882f3d5765da8f825e1984a4313f72b67d806ed45c000dd3ddedd524d474b9b5788547d0712e8edb4c6c586d0cdf8f2384f1e093a7f6dffea6e79df9cb9398f5d0b9a7cbd63d489430fbfa397a0d03ef916b7702f33a54ebab84a7055b7ec6179b0ab7722f03e126ed343b1cdf2af3763df7e3a070162535514b01ad86c6cb051859aba1cc4766b12c8cd57b73fdd3c65af6961c45395aa7b885dd59e115db885f644e1c94bfa26b3804f767601c86e2c7dcecd4daa59955e6a40991a4b4701e63fc82b46dc0ccf59af40a8583171375551c868436ede535705f2e6380c5899cddfcaf9e94314794bab98846cd5ba9e9afbdbe1ea7fec5e22e7b2aae59fa598f4d6c0cc6f936a616e11bf01a2acc891cbfa2bc53c511a8a3a3da2e3aa5907d123ab2a4a3c0009fdb5235a3c33718fe4c504e1539abac6370e06150c402b5fc2f8c32608db4ce2eca9d1e4b96371ee195f6cd632f5b972385f9d5d357b87c78cb4e2c27aa9851534de14de923543f5fd9d55e34d6e8b7e1f3f2735df80046de01f79d0321066f9bbd76299c7386d285f7bf4ac15e033e89a040710c90f87aacc09fb8159f93c8b4860247eef079e32d05707e88aac734a2eadaa853f528d9986e0af3435b5c5f44ddfdab9b0c9ab3eea97676e920f80d1794740067f9b229fb018c804e595aa997533a5e967cb79ee58eea18995a90ac08333f1c69600b17ef4f454f540dbfa8b502457761bc4daa876d9053ae1f55001b6916ce559dc6268d01841255990e56614e6f4ee4ce04472dff0657360d75da4e83a71c852a2585110e53137e91bd89d64d99b5614ab2a5691c876f15d9931b092fc6729c0732db5cc40f966fe440ff99d7d05b24a872f552c27fb0cf2af443340b153214b407fb9ca3750d9c157aa75763b0b7600959663889d00f392d6ebc12835bd2f03ad802a21d0228f1d2e9731d0f0051eb2d5369ab790d1134c38e28d2bc2d5d57d6d897244742c176559961a1e40c84ee5c8225c8d72b92352a011e3785c262aac115cafccc2fe1b5e81a677a0220f207ebadd786b93f58e40eb6ade68ddda5b66c5f0f6b4b95cdb8241156110ba3303beb79acbd54423315768bb43b4fe8c4a465e50c4e63bce272c4d731ea4c797e14b2de31ce4264e2479179b906f67af4a23c56e817abafedc2c7a65aa45f0c89fcd0baba60561a8d013e2d5e0bdf9fbcc1346d3edb20e6e9f9c410982e1ac43039ad8fd0ebd453a6788376951fc20374b59946a6803498929d9fdf2e0f5e58c441329a79d1232e957b3a9ed17231c663b4819dcb6b4e33d205edaeb7d7ec466930bd84a064b40aa67fd76f6ca005408062b45b5aed6f8161836c7160a8c8313dc9aa1c6d42c2c16972a1065e41aea9c58db7916e1670cb42a8b54d85498561b4401761506860b19b446655f8988101fb4c45067e30edc3f00df8d88ee34111dd6626d605d993ff207be09704fd8dc242ce514bae77cecd20f10d4a38435a3f5e545882fdc224586a04ca6a162e118d23716240fa67892b78faf98a17916471f7f121fb9f85497a0b34bf5aaa4ee1ed8a4681bec55d1b4973d4368600115bea70f20a37c9e942b87f6cd1e2ab70fd401e703e3c8334c75fc338508e06d6370779578fbe737a75954b4701bfd92028ec32d3d7ae606caaf9f049d9774f70efa707c1c1174d9fcb5b0a0ae2a961c6f58e48ba82c2db14ebbbdc24288e42879f547b855c86dea9a3b9877e4b105515bd78cc43465", }, { "bf7884fab52251e202afd7b5b46aa53f85bca5fb80a009d8016e276579e401385d853312a884f4aa33cc5fe7360426bbc0ccb7416cc0196e2e40d3a825d5e0825a1394029789acca550bb28b10d847d0a4fe1111be2b7fec6b5294902775128288a784203031ea853c9c104c75571d19552e2a1359a900c5fc9455230968a5920f2ab23f5b9cc49739d4e4ae2c01c7812ff295899b954e9729a3bb330b60c51a8a7759e5131d7d4cf261fa1e62c29f91b4341a4fc968e7f30ca2261702eb328d628b7275a9efc29b50bcb9b27e5844328d5e8256c76949d30b6fea0d5a1c9abca80d3251fcf4ec4db0a5ff2ffd43618aa2e3e1694c2a3c579a2665f443ffb1eb0ce33c09d7285687cd55b6ca9918553bfb36a44860e09ffa0604ef4904a034108370195a986fe165c598305eb08599abbb3df31b1d93162397056d9ba5a1ac2812c582aa356310fafb4058abc5f157802e4a9b4bddb16e75b6db105b7dbc838f820539b76949b1648909104efa67ce28b16a738f1be104d2bd142d3ad1b1c953b6020a1f4cbb84d5c49424befbf2e6ac5c593b783a3f4af75477312528fa78dffd82fe493d821e011642bf1135a5be91fef909383953308dcb61b2f35c2ad259acd1a2e953c0ea6a03a97b384e39c94c33d3846c26b4f9f116abe572d5b7cb81886d6adc2d544630fdc1684bfb32972e051b9a2bd0931de63e025813b923944290fe1ebd5264ee4f25569a2088314e8d4ce8b91c7bd602b9d85acc917d60d30d5ef1cbb055b9ff7b0f999b98caea2517d2de334eb436078c90d41e0e34f11b93e3e643389f43b3afdc4f47a7396cbe0b4bf159ff27618cb835aac6699be1fc7ec840b767836a165fb95d06f2cac4fe15b65714ddb8a095ed4a5b57e63d536405931b6c168683763fe07c32aa4130bff787d4d440746a2dbfc584a502d809076b257482abf7f8ead7741c82b54c41acd41581148aeb4149b0c6eeb39ef7ba091c2e8bc72583b2fdf8ce7fad1bc05aefd6db0360c644a9760a9729a88ee4b2ab123d7238c12435b9f3b4660e74c0fd4a9b00aa614453d84fea01f779e5a924f8e79630a8bb6561ae19c7bc8d88b9d823b98285fdd65d4cc05e443944ed5d3cd4f46c7cafd1dd5deaa519772dd24f508bd2d588a832d5689119a2d506ff11dbf37d57a24e35ff38da18af07eaff5775d12dfe795fd3e1f0ec83c5f283d6cd76532519a15a18d93431893b1b88929159bf8fd21f62b30f4e37d540baab0e30ff3349a08d627ac19303fcae8b8e3fe44eceb66d30697c7ea051bf5afdcd8bfc00d49c8d36164ec9194a78a4d8b78826863e93b6a810354861f4a35ec12e5ac102f74e390d9c0227e67acbbe3254e5b892786e3a88a383ea9726485854a319569a678fa70392cee90c9aa83eee8df6800565bb8e083e78a064c0f8b863120efd799ea57d3073663c0d0e7bfb9b717ca1d6372fdf75a77fd9677791cb899fc8033d6d806de1e6aaeef525ea909666316d9d604c1207cbeb6f427c3acc1b02cf59704fc65135703f2a9529bb2c8fec992c4de53e54b029c3f2a5fdbec1008d1a70dce0c11251003ce62af712b9e4abe631902485404e4933f346f1b4467fceb65baf776d0078aae6a2a1f95b85a441b635663c75b485a8a7cb9a5c12192ac874d940e2d9b88cc05a2db9b5b35df769925da508112ab0b8f64a1408633fd0d81810baf2c846b222736bd826c8cf905b2c35633d6013f5565e0a5ec1492e99613f53530799052a0d70023339d1c394fdf9f73a590a2faf68390d2a823bc3e47a173782b03dacbdadaef1e67fb47a7cad71b6067ce5b5e41fc20ea1fed28578e9bdfa99faa657a754488ed3fc084faa7a05b0f6eb66da0a28e9ab26bb319fa4ee993de840948f94dc1d68d926b783a0bd3396a89970b2c2595de8148e87b87c21f664618af4f567115d403715c3d7d2f66d7a90de2c5237893a4c18c20494e3faf94485ed39ecfe972c36acef0d7ee57bf8755924c790ad02dcc5c4e15aa7db53eb6040244c3ebb7874676782e54dfdddc256018ae6af8cc37450a4cef77f21e2e061062ca0c2a514290c960f5993ec1ce9eea6d09d3293118237e079b6015b966361c3032368174d74ae5cce4148ea2b3690fbd3c28ee544c5c5bd7bc618122979d52c9d3d44eab1f2467f338e695ec5f95998bbe77dffac42bc2809d43a324e0f5feb4ca3d5fd951b7dc8a9e6276ee080079b68849b14c7573cd02c76027a856165d1043acf99554c62fe32896d120974ae71f84986bfa0c28fcc399246bef3ab90f8e55f913aabf339dd7ca6f0861a9ef712e77dd28740615479f39a37e746c7df2b267066d1649fafe0459f665f3d5e7124db43ab1ba5ff94989acc7fe0935e0bbacf718b33103a1355d97ab416d8263ab369e6cf0ee563a77f2f265fc3856b7d54dc0887ed439a421c14f733ec1d6da086536f9539d23cb8026218c5e783423b5f4ac24c8d5d8faa7186dd5ea34afe299e6dbed73ffa8f415da706442a48808a9342d6209f65ca11eba76f8ef26db890da76671971f65bce9e6112c8aa92523dd5295d748e28857acff408c161c0513b37b855a8afb0764d118815bb1b68f8f09156641f7eea994ddea20f4062607b9919d041c880b71592402a4d5b92464b239caf431a99dc67787e76b8e1d7337af004bcb88473cd16b3f7640e8aaa59ad4609f060a2cdc71a4b3ed22c1506a7050a63bd8ed68aa58a8109980bb3f2b9f9fba9599d7620b8c25e8aee739095789af83529cfbfce5941d7f14c8ae30583deafdc7c25fc34e75bbed6ce4f6b47e9647c12333ce08c7db77dc94161cfc43f7ea0bba39def8bf8ae61c6fdcc0de6308af963c6d9ef43916d0cd2cedb970d5937c9fdd4b888cc66e99363b5a04ae62a4349f01c3933ada64080741b1781754e4a722303faef69e382cd9823177e4d5ac83e76017124a7b1a41bcdbb9c4209e7b42c", "eaae1c53919e2029c137a80f91704d0871be2c1870d0333d8bcf7f94", "4c434cddb399e52457113cc7e16f046c3f8301f5b6c296979f8a091a9ea557ea", "b633c1a0e1ddf4727b149b3d", "f1de487001a580cee6edadb1ef6b700c861a70c6ef16274447b8c61bb10d2d1efbf104d5f7d7172c6a5cf9c06d886165a2919ee9418e2e8f803d47832dae5ef232ee300d1f973a6298c22d777a1b16264353cc731a7a683cfe31e0abc704460788c555c0c24f281b81d7761235a955c736f17f213a896b40a034609ca8456ec3cf5906d01121b7580ce19d89347b6a59c81add318df487b2442a7a8b5e30df78467abbf46bcd5ee5b994a39ca5bd8846caba6f02f4f1335b73d4e20be0b6ad85966f86d1bb857713ebf947ae936782f1f4929498bbd66bdd5ad6fa252364a5a6b46180e93b54cc321b3cf63cf23d55392475c6b8c8c9dc707924b55544151c7c55ae0bf391f793e52bed70829fcd32b2926600f65be0943d6a9a96547675426b0dca9cc7b0f5dbc9d5439d0281014c6c159d055d6bd89d67828ba7fd2a0570ba82996037f7dcce297fe6518331270f6fd5ee63d406cc5081472bc5f2298a9208dba9398ccf807ce9af982885897715b3c5742456f756d79c70434a9baf7b4b6664c9d9f5696c5256b74099e593f97a2d4a469cb3430d0c3eb06083398cabd58af598945a85c9235a3fdd9ba7686e54d0de9afb594b1bb030be8e6bb839f6b45699dbcd2f771db64b0c62bbf6c8672fb412d60c00b3d87f82ffff6512e8308877573323c5a2d6a216ce3e2ce07c9763835ae59d44d7958fd873e3995b62b1b347e489ce86e023ae27a6cb03ddec27a38fb233499a714acd89232a91d38abce30299f38f437f7a46df647f2be862c1e7bcc1e4263c2147b13ee5b345b7fcb973f3ac71db8bc12309f67ddb62659bd73fbd20664eadcd23a79233386aeec1a6fcc8c592053954ee53826cb9b6bba22400648887311cdfa5414c96d5956fe193a3729be1434d923a3f9849f6c419f77ea05fb72f3c4f75ccec03b7f7aef8c8e55c8c5480ee505ae1a7594e6a911dfbc39dbb0ae8656f5972eb644c64203a920fe0078f3d050cc5666ed9747c23df7853d6913005d0156e741a5ead3bb1b22e5bd802c303a73a961f0b60d0fa698041c22577b44eba5d6071de4b545d9f5de24944c151de6a189bfdc223e0507c74ff929f06a2e7497e8c63073294b4aba110a006a6e9510a9617405d9ee711831e085940006761822672549d1d1c70e50002c2227f6f304b9a7f11dc05751be2dfd297087044d2e20ecfa0c091478d62c1bf5f0aacd25bb0384853762a51144b77d30418b633c4c10a6eda7b2eac46905641da0b685f85349749a91cdbaa4027fc50eb97a7dea9e8cbb5b5f386ace0363803ba579cd16ef80dc40ba1044b4ecd0e81e382635d7855e2341b18e0ca705ff46990282fe25093a248ca04a1fff64ebee25065350ea4b9e5990da4dd2e28688ab08b6d6fcb54d70f6d74fd7e5e05d21c12f5b140839aa966aea9ee094a923ee5ec704b5b709ff009c20ed89a75468c48b505d07c7a5ba1ad54ed610886c9d84468eaa598c71b017578404c909dbca431703e0cb1cfb975a696a1677bc015a75db007eccdcb21b9e5e119c48f148c2cffcf29e245e52156ba5ba0a8b0031570e4cbe7b3ac4646353594f0c4a9424c9d97845c5e1a4b4016df9be8df3013e5269484cf32258849afbdd733189ea11783f0f64d3aba9b4f48818011e868cc03ecaa44ff0ab83ed12981a6df445294ff672f3a16d6e0d19b90007d4646e967e0fb1763b3c879f548e1103a75c94f3a7f72be78555eafc086c1c58d1761aac60b843704f234c55b951a1303a12705f2120f784c2bc1494432a94c835d908f0edd5cbb169afd2d38087ca5bc5e5df9c3bd970dd2da4fb2a00933538148ebf669a20b5beef0402e53dbfc3a0f289b33b41ca27eb2f036a22f0d02e0617bd01e8c74be264515c9b46b9ab6fc67403a35837844580794088a9d3c14ad9309435daa0396f48017be524856ab6c191350529962ead64bab33171a01bb3c144b23bed406cb05102c693ce5df36eb541c47e871acf56f2b47de687eb9b3511ae83d06b1f69fbcef3225c3469c304741437fcd0ff4ae3484c117f51d24b6ae1363beb7d85d9b61e01e3dee901b90f2d3272eedb384ddb4d3b9594b9c0926595e500f8ce2e5cd407bd7a4e2c8e6f4315bf693e8c961ba5b8a6c7f5030c68a6b995e9d3f9eaee9eebc9d679eaf72a5f1cb6b2fc66edc7dffa2370dd778ea7ff446121999afba7bb35ceabf626c6269bc466d65f7f812c663bcb2fd87d3e09ab7d71e727f66d20ec48a5d2bf0aaf0aca05d1546d6e974f90df85c1393e3d45731f71ec7b5cb6cfb4e5c29976ead6944a99df2045056e198b19905362d4e9b765adb65eb089233a8b3777352665489c9456cceed593c6590d9f3cc4024d0bb92e1a0dc619bf8ae65be77456c18f8171e4d2d846073cf5c57ba93adbc0db9799e3d98934aa6899372acfa4d7d2ea32e20164b79c71d7bd33c94f9a781a25cbcafe563462eeacaec0e8d9d6c0199de85558a3a05d1ee3483351915d8a4e65ca0ab129a2386a9e26aff9b912c588babbcf25f8c467145061b9b8fbbff19d8c6ded8527d457be7c926c8f490bbcd627b3002044b7729a52e94147f95772591616f6074047e758597f410b3100f9efafaa4137dedfd0edfa85b0927804f0b4fcea1a174622116222004d42b36c2c73d04781f2f49d080f351e57154a3980005bcfb0ea34288e2fafec5bfd01e1f7901b3efc71ae58bf8df4cd7c045856103b77bd78073f0174aaaef4a3c0e8b5b46dc92db55478f012dc1b7d513e215e735573257f105d2390b5366f49b61809033c13ed4e1ebe19ab89313c947f2585f0788a0c5de90b41ad0dbbfc604a0d414d0e5390a0f3c9616cfce4097e38e05888b8bc6e55e40368bacdba7e5b76f4bd8fe619746155c30b38807a1ad325b00ecc3dbcf23014e79f1c39af7cdd0dc7ea58ce733e6611b7eae069deb047aeadfc21960e614db19d2e7e0905a9873268b9a24f856c28059321a742cd6cb3d1527", }, { "c89c3cadc094bffd5ba06c600dabe30ea19ad037316fc13b895fe0e14ac8841264c1bf25557e22b01f8e102c3af43adb8e0a12bf79d3fa0232dae37ca3688e07294e2c7ecc4e2eebdd3f17173351f2c15b0480d4d77bd70955ba86f82214004b622cc92f7bf81a5837326f6a83612bdf65abb33c268a457c45cb7467e074b342a17c711c748c74abbee31541444020a9ecd4e5125e2a8ea3f6030bd677be18183a8a34af16a85ad48b7015cfb036789c0a5daf68883d0c7e401754b8d56cd00ff605be0cad19e03989f608392c81d636de859e66c2aae403c138bb96a58ba69b9064a83e7d8877067e7f40aa0016e0df9b7f455d292a60eb621b8107a727a3378c4b7509d3ec10526c50fc6c66dd4b015c915e85bbbf701ddaf2258119c8b9a5132eafe61bbf38870f35f375123f766ed0d4f38b9364a86e56cdef6f95a815a8d7c48ff283c77992fc6c070eab7d7c7b517006e5d4af532a7c429912ebaebac27249b4f5112d870d998e1c450b98c05d08c742dc769506f2d7a004c24ebf84c10838b619653e27ffcc4344d8db0435e4cb77c0410cc734e36738a6b5f72a7600632d19c86b40c737830b0f5f104443dbbb031dc7ca51ab318951e7817b5d81de8a9aa7f5db6e2d5e7a3cbd8a8100653c048204ced3af005d00e7de7b445f5acff901c4d46ff133e92ef073aff1d9ebf55befc32f9ec38c9eaa6a1aefc974bec2758297e474cacea2ba4151ab1a3ca0762c64a5ca273169d29b83c164f77f266c01bd5075871e17426068ed7aa58ef0d1f2959b19c604eb6187acc57e2becea2da93ba23159ba73b9226034c7ee2498e0ba34fa8038e5e2c092a73ebd9329ea3d648d6ebd47e1776941ab3130cfc91089fd0a0a36f0ecf68293343f275d2a64c1b7d27ffeb3f667f4a19824706235fa5f3f04952ff08bb183c0f1aa1d1b0edfd2e05ed093543788f5d0ac6532e15f912163275053b202d772f381900e906fe070cdb00421e78c16b7387be91adb7b3b3ea28b92548d69c780ea578e7ac66eeb931eefb4067bcabdb345a7cd2022085fc494f118215adfa2443630bffc9faa8fbd9943c3140d81c7532895734a9dd20e31c326531d06f5623c252139c4cbc882640c457819c63f6ceed4e03872b246a3766df69373ebf5af1116e8d5e1b15745bd9dbdd663fd4352d1238a43d5d1e74b3edddfb1c9d460daeb49afccfa0712b7a4cf8d07ccd0599ef3e4e1c9b5c814f3a6f3a46fc80449b34df87f47ff91fea3618cab2d5c04cb50e8ad199d752d901b21348ae939d39c86cc1bcecbadcc6f0e581a3bb51e070507b41ea4294b35456c69cf55a2a3f1296f0df73abac3a9c81cc303d1e20ad6e9bef48de83fc22dac2cfc01ce9ff3f70e00ee49bab2f282ceb6859f989075814e690e36a8d16354fd6056cbff49c30e49b1570363498531ff0ad0979a4518e9ae271f57f883abf5e301c0e24a83f09335479698911bca90269a28c0e040a98e67c9e55f4c91542f921511dd980270cd490766da22306b48ca9309aad3b2393b7b1e9ac7afeff64204081f9c0a8f6a5396d02eb9009901ca2c0a75ffbdae3a38ccd5007cc4f6bec8fedd64086cce5c039e8abc9e23bd694fc8de4e858c89bd585ebdd422b492eab26f4ebbdc1d17dfbba19b5ac458c31320a161a52dea638548205a6ad4ec54875ca34238c059177bfab2d5be0a98d12b3932d0661d33ec655446d0283224af8ec7f1c6874add03448fd8029a71d3c5aa06951123c9fd881d435845757df50444e6cacc31a8cf7537a778d1184b96c3512cd474f5d1fd1214555789d24c8d173358e36400b2d937595109729d9f35eecb0963c0da60d2eeb52a778876059fa95d820d5d34e7948d389dffd53d34c4083d27c917879b053cc57dc43c8263e5dfe5f33c19dad0a7126ea6e8abdbacb318d37c305a183596ddb25b1934beff13a4f24fbdcc2064de8e0bc639e672ecfe45692e9f8164365e1691784b4f775ef369aeb135ce15135c20da95064c810592ea33316b9767caaef842f948b9573b2205ec57d3026a2f2244c42991462e233061549cf9bc66a7b4a8a0fc61f73883fd24dad02644004989c4721a0aa03d3b0191d7fa4d3da102e541fe463936c9365ba30681e706ca70cb3c8ad5dcc710de59e7d8a6247aa809bba74ff4dd182a38bb31baa337841302c19ed89d65e87bbed05465f4ce0dfe89b44d7e9266a8ca21d984c41109d813ca76eb67dbd4e39aa437ff98050c968ec1e40c534ab51d6b8ea2309fab08b3757e9edc5972bff316f6f2affbff458ac0299613734b30dfdad20f797d172cf295cbcfee3d8ee25485d40380d3480a9372a1a6e5ecd7c4c6a9d34027ea6c197f37e86e757750c9fc24cc7cf814878b8628326c140930dbb2041bd9ee87f36ebfdbdc34522cfd4e50c9cb48dd52d4647a06d08e0f0069c104849bf30c8e61cb693dffbc69fc0ab9c5d502a227d606a1dcd630ebd799acdb1e47ce2ad52ff53f6cf4fbd5f0058fb5db915702675ea44334d42e0b6ddae78b22b5b5f7e5aa36519e31278e37b64312479b14aef9b8f12d8c1f39faf920851bd53b13bae5490c847b3312b2e956c430f1d8deea91cf171dee5017e7709d0346d81600bd5f0c41da3f548c28aa50589b293685ba059cd7f3edefdb5d8cdea364f4a42153b0632ef0b7ba18610b71fc34a781eead1dc5a00ab47b6840590ba44dafc6a16029cf50e089684194d93dc881beb62edb7ccee6304a4e71a35915f109db92690461b9e4ea21257ffb62477c20feaafc7a78e2aac2301b66893157920ce9fb114ab4f534d61bb3d17dfb4d9ef9f79a736f7c1d32ac3998356aefc876d8c38722787d564e980a1f15056cb3fe634d71d2c98e0475c79cab318b73a863362f85aeacdcfc44e61b5aeb870de9ea5b5abd24e8c19ab05e45e1e9b8894deeb9d29d65ae99aa94b5047f3c1168276cc2e491aba52b5b03703ced28c63a167f0cb3e4bb4d8e4f0292cf3ea4376510fa49a1a5efcc00f23c3cdf6402197b81262e66e17bf4307d87ffbc2b37213b316bddd65aa9d64ce6122c4a1545c5966bf4fc4c6ff17ded787ca9a3b3cadee435bbba8f6590dc4ba30895b84d5b4eb94f4b05be3c", "82abb4ff5457b21f359754f151e456e2c0a185c8363d15918bcee0d6d49f12564ac655", "b63b577e719494032062e3f63682098dcdcfe26cedea2a40893c847a331e4ce9", "9f1d08be539f1244f0f69ad2", "88dcdb0309f8c4a96ad5560f8210eda1f5afb31b85b7a8b15525777748967d4ed77c063f65d64ef19b31044f2adc690f5e457faa1abe2e127b38c626eaa94053c9ae1b6b4d0db1f02c8404b50f58210cc9fcc6fa4ecc615631da631031cd6253b4a13a3e88295ffdc775fd4bdf29655d9780dbe02b0a82aad4c4088e90b51f170909c0f98ff93ca3926067ec94be05841603db4f913b7025a9ee34b8d8bc629ed827a2a9857e0814d36b83cba21e670f8f94ceb4be5757e0b8782895b5d8605868e4f584b5bb6a5f3a94edd9b23fc2b6fa06914aec970c260fc370aa245ca68888c90c43eecb68474c9e45c53a7da055f5bfe39b56769fa56264dc8bf4c1616e30262bd501ff9fc5cd78f73ad89e093feba0393a11c6b2cbca765ba025c40dd0417dfa644fce96db5a0362235ad37a317145e7b5f3c7213c7fb3c393be57a1cb55035f06da1f0bf665653c5fe8a0f3ca67dbcbfc59852694d34819d0978cd09b508d103017168f6848258493be737cc24c2112f2afeabf41038bea1f74bc8656d9910b77d33cc691a0d9b12f7c518ecef93423cb4871949a518d2f06e5427823324275b97110f8f88b0d14788741e617f4b194e679a1627da50376a08d4f23b005c0446b46d4f534ed85e4692e7946ec818437089425ee30e47de995e8774b61003801de67939d9fed7bf0cdaf625798d0d0d04a61a2482217b890168e36f20cf1d6b81f9daf1a49a781567c4363ac2f3ebf0252d5adfbed17f98cc264ed2765aa279b7437410ee8b4cf42932e5055f4884deefd2a979ab1328f97cb750b3b7e4615b9c1c61659c90a5ff6d1c736e785587ec85040fb2c6decf789c2707974bfcbd0c7f699627b31e0762321d55bcc6acf1aabbd44abd7766d397bfbb68c424b311611d9eeb6598ca3126f569f688455da8d5ab86eb01f9c96186858c4b5e447aa2b9ca11aa5453f731beed4e09f95bb7376e200212e2f03551b8b09a19d6910f25898d692bc20bf6ed3ac9a0276db560de5c9e264f4db8fec6577042fbbd4510bb7070086508ac451a1fda26582c259412fbf1bd60cd5e921160c2604fde559b5ed4df52b805010b225f999450adadc6e108b70f169a3d8da6efbe1cce1c4908b004e928e3cdfdd0b4c5f742fd72a11c9585aa3517486201b6d9a98739b77970a88072750d29d005a291546f13b576b4249d71f04a9abf8f653ca206d98f738af2a1203bf0975f0a40138df054ee834ab73a3b1d7036567369a7ae15f808904e08adfc84b34a0e1356009d8a82e51c3e8f2170908179bfe47be8ad819cb12e85b6b76bba7c9b9398dfc00f550e32c171b4d5f2d9676063efee0b0b49660c10260ce052dd00addc3359e35c25dc33066d4b05bec7d93f71e0ad7d5ab83d844c7f33137894327f464260688ea4ce9847046e7dd0bfa48d4e15277a9586b4742daf0c5ecc59aceea6867068b03c20aad38d04a814472287d809a9285cd4dcdbf68f3f4ffb794701f4c265b2dff4aee55c9815938689162e08309df150538e60dccc03d495adcc560fb831444b922a6375845cef5dec56eff2910b5bde5f25f0e550ab5a13205de91d20896fe04a8ecc2c83d1371cf381424f8c43d2a5ced374878405f52bb92f4fa3c15d29ec151508488f9b4e42527921e245a8ee4b5d6ee95797f6ec4374d79acd7b467454a1d7eda05a8ae104534b23c46b27581abed6afc3ca555202dda94fc2b93501fe78867730a84f6f726dfd7364bc240b65d6c3022a04e09c89e36a809fbf244cc5522315110e9e33c8a4e1f1396e3e51fcdd53d9ae94fe7bf6c6ccef0ce02048a11441de3c25aa9787c577501977e486f8dfaa4c81e3183e648311148ce5cf3de56878847a9d14c0645777022c158670377dd9553eb63eb17e19ebb06202be8fd9bc2b24878cc86f9938e5996751ad9ca04b636497199f7f27dfa0f5ba2a01c3a491bec6dc5113d127f6aae38fa07ce7539a0c1817f7f0de0da538f4d85ffa394784a42eb50994e28530e3997e3345db28bafbb836fa463d34146d9f46d8d2b28b3954b9bc7f84046828e9b55e2fd663e562aa95caa97873f48f0a003d2251fb3ddbce0b6072fc17e0d3f99b655b8f41e8e6986ef7526544222e2d402489eabed4c219540605b9f5dd321ad902708601e85bc874c11efedd072aab7e10272c87b08b9457223de9fbc3abc2d1346656a524e9c67d79d4053c4257e886d6b430f5b7f57b2e5e92ae69273c1705a3074d5066def69fadea1af8fa9b3bf4890f9cda4b1833e5ed27f22bc4fe4cf452880c7b53320bc7cb748c0af6e7550ffa84e4714ec18d208131ae9e3edc6cd6fa2c60ab8ebc1ee56eafc01fbfba061e55014b9711eb58fdd01f8936d29dd081565de0b175b02989c5ff374e6f58c3383e9bc00d8a93903e6a221c7475e15aaef77594849af877f3807a76e03bdd54ff0b192bf34385d24d858d6f454810ee48141d73e3acf1aa3d19cd4c723a634cd8e25b4fb604c744e408dfd82961e46e8444f001d0991af24b3b6ec57ba41fb45122afc73ec6b25f501f1abd46181247945729337bf5083e5821968502a5a696043ee696c290095feac000957f968ac61ccb572ab2f37008830ab9a81d02456190af99873450b52df1888c3d8b6b13df65a9bb36a4b6d0538a0f179daebca2bed6f94b4670560fc5471c3770f2d004b6a138b8243068d754fd246e9881242638c6675f1611f237146f6e0f72ff2fba96f479fe0a662a81f40928f5400a0bbfb5ed07a87f457d5febdbdd6f323e2a59f749e6fc8a51d08b023734c762a91cc517401be57ffdf6a52b9174ea153abf2190ae2642955c3c02b4a15d72456c9d2f323de6fabbf56dfa3b566f1aa688c86b662bd34cf2511cc4a30621b6f1f1ac382bc1c4fa4c0d4d5a30ae90a5e54a9fb4afc1475e7c612eeb7f0e09e894c2004cd04126df9359d525d7f090e4b531916207c38c3512341c84218c86fc50061043ba1b89ddfb21cd756b391cb53e8c1cd55352be05efe562669e3986c022e30c79a97bdf087889a392e6da0d72cc7ea208aaf23408df23f3a9ea9bf9a935e49c9994a37a5dd0faf1267d5f7db47cf64ae1d3ec166466b2f882eb21698aa375cb50146c0e660e9bbb38d7bbc1c1c6d8333f7031d6a", }, { "68ca38fccd585eb14f953358220027046c14ef965478d3d8f206f63fef4fe3571a1b53e774b298c347cc1b69cc426d39575ccfabd5a284c7a87a0698cae9efe40543cb79f5643c3c3057a5fc991235f06f059c44a7200b509a12e864fbd748001a14790f78b54ba80cf0a4a603da9672df32b68652c1d6edd3be51cf969acfb0ae49c026fe0bce0bfc72b1ff4c47712b7a27b2cce888b9bc470b8bdda55a8d53a34d79a25947ad55b95e5406a5c5311fece3ecd46ca590b3b01b9055761da8196b21bbc468681922c66d286c32598b1e3d77f2a91d835ccd9eec231409cb2e74ede9385552517718be9f84f0f9100e368701dfa4843b7222279537306065a54d4edda3a02f1ab9edba3ddeb34dece9d5edc8797103eb942a80cb5ae130ff2e7eddd11f0cecd8f9a615d75963c44238b10ab1230d9db7371d8291feb2912d306efe4f7aea2773903d4be9a00f2bd8c03589e342269a79441c0b42ce9c6fff0a6e4e845876f7e9b342d25351fe2b1233b4f576db90ef1facfa617b96d17aa03fc824973e1c80f15e5344b0516fc28424b7faff47ea1ef4e47f6f7b50e91b8fb14027f05ca7e1bafa266a4b952cd0b9e4cab82bb4d61f99568e14a6772f36296f5d19cb04fa86ff20f04ab61d1a6f01e5282c99fe4c3254da46fb5276317be58e94b1928e3791af27dc6544f6d445dbfc7275fbbea74f98ee4aea647b654909f9fa9c88312d3759099c9d0070e3db6d55506813f8b7abe602964a7dfb9387f58e237dbf50b4185a50b65ac099352dee8695017e4dac644f42aecc3e415333cf76b08fc764a721b45d7b74f6b0a2e43637e5b4849218d3d4c6a01208f345d76af56631590e520d6bcd82627d2446b45b2c68e0be81b3924753a54f47ea27b1e08de2399b34470701c9697eedaf3248db9b28991cdc2c632fd1b376bbda279b6709d5033d1c0a3ee573bdd222ef1afe8a4397a61fc30a4e94bdc55097ecebfef6c00133dc0b72c17e2f93a11eae9fa9f1364f10fa595e8e1623dead10caac068aad3967b9ab2837dabcd8f96a77a25baef16ba84bc93661ed150ffddfbb0369683cd021e8f959c2b531bb1fa95d7a574fe5ff9aae35fb9b4a0a9829c59b932ed8634fc05ca88211da3e30839baadaea8fd9843e0e80d9598a7282500d157ee579cda5d57628e7506617d301c2adec5186708f94f069ed7bdb70cbe88549cefe1673d48c9bbbdc01d2af03945cefe6e25f757750de64cbb9d496a25adf7058f5e32c827fe75e80ba0e834e6a72344dd2aac4228828ed42fd83e4576254af5737dcd9b6c338377d46baccb02d00fdffaac12133ea0e75e791593ef3aded4ae4c9249b8d5cd20aa28cd652b9d750b88111d9b4fbe729e27882206b2f0eb614d7daaf6436816fd80d452ac71c7a7f9e8c595287407c6ab9fe8a242e98da4270b4f1d4ea7243c27f89ed46a567c643f31f967b5f12e518106f3d3e08178078cc714cb6e39079631966a9becd6f02c18e983ceeaa2106ba9043f9985b791027eb5dddceed563106bcdbc48a4ac64bd95e87c708a8cdc33811bcd16c35e193203e70ef2bc7203183fbf60d46bc581f1bdfe62387b3e6c0c4a29130d872c3f8b134e7dcfb080e7e03048c49c0e468dbc44eff4b02e50bc6889cf7600fba58c0ee409ce948aa684baef4956fd8fd4a9c4c49e84e2ff314b7900b179fc66f5fb4affb9ef7a6064354fad8c3d2d50e6f2157576f864a843dda8f547955c4d80a73d4a86b7aaeaecea886927a5ba0e97df740ec7e8b70bb650010df55d4b75f478b07b205b560d45de666d84206c1bffd02ab7b8d1c37f21c47d1711b89d16214d8151a8e75eeeb5c54c39e5a855d578708d314240a064051d8b26c6183ce755be38fe9597dd5b5d198532b1db083a4b856b8dd60bf1db197cf1df852eb6daecffd97287a6cdd4c05307722e0fac798507f75b03e9361d5627ecdb56a3b633938fa61b2673efe6c6e768e4e7055e6c1d55c7113efd3e95151b606bbf169f4296455dccb93da370150c54fc11b3682f092f30381c6ecd218a3d9d39442c8bea61d9a71b174a8b2c56e028689380879cafb7c4bc2691dda0cf6ada039755edf93f851446df9f63267f8b8f030c069fabbe6457d4f63575b5905fb927a5a720d52c351bfbc48f12440a91471697e6b2564b1a2b314fa0e6dff090079637287b635d875f120671561102ad27aa83d9f0cee41bf023bcd703ad670b43ae23bf01713650834cc1e95dd486757f0a4f6fc9337bb95738805ad5e756198579c886eb0ee77e4ba957997dde0eecd84e4c9171c84ad8f0cb23c6a289e037f3a8beeea7965ce34fa47cbd727baa4ac9e6dc3baf17049fd2386674b246aca5ef6b8496f1d17a3175f6fee86299232c7fff682f066cbed895155d475bf9fd4b5571d257534c88c93377b1a600d4c280d42aafda975eb32c740073cffa610b5fd2dda7262a2fff5da7a0f3a875c62949e0c9247827d7a49bd8185bc27967124c34b9725ee961bc8102a029786652c2571be6cf33be63cf867c2b48e5826b31b714a415fe05c27f0862a870d8fb33200719ef4ac8530a4ecf2597b4a7f2e66f078a7505803774889a1cf963083c831f46725a1ec5545d8489e53921d81f80ef99f5e51a2d5992c7769c2a7ec8bd8e0f2fd81de53c7b69b650a2d838b269185c5efd668c470943bd956e3c5e1bba5d3b927b10cee68a75372d4d6fdfa6782c05659281bc9bc56a2123967f4f50cc7ae3379ba21e1617553354b5030b3d3f0092c1824f5d47b97e6b4fedaa90aa2573e1b115ffc72d44fa8209fd8d372c8dc9ee00193b47c2a9a302875da331731713243d02eb5a57d5dc51c35988ffd742ddd75c191f1eb2c2214a1fc47b82db8ea708818262d9583f2b1b98a40b6ff6e94742f25661a51882ef28475aab12d9422b6ac48e341cbd6f38460333b5fa1cfd4d0f43aeb46c21938468fe3f7bc771972246156652d2c58b18c8cecec2dbbc0feb0fae9f6bc022e029111f94e8913c0ad741612a1426b53cff73fbb24fb7b22ab750ba1310ecf339fe12ced6a3fae17b4c429550794a8d68be891b0e30cd28e81de2fb2ecfee58bdf11794951276005eb8a5af21e03c8aaeb595ace652c5ce60a8b98f6897d82698ffbb2e02213e50d9d3f00bb42c8652d22bffb87ec576ef6e206ed6c846fd5136a87f38c9ad899371799f35a6258878418830b04da79fabd80e7290456fe17c0850a4c20e2e657f97f4a53e1a3db65bb5e71bf38eab9f56aa11e6ef71c85b8a28f04c271", "ea196b6a64be4b0799b1c2f72281300c3a2577db44e5d3606b8b02fa8fc46c7aded7e442", "7c86a2c06b7520d60023d18fe73d09c514ed07a91d50d8fd5bff00e7550faed1", "952f492fe00b26028c560fc6", "b3f3294815ce461c8843172efe93f73a8254e58a0e71953e35c15aa89a7bd9dfee967853dcbfba73d3b87fa60449cbcabf13b1206d0cb27d2c3fedcfa695b6d41efda37bb6db35449bd470a23787619ee48f981d3f0b1c8e121725b2289b6d67858a4f9ab41683bdaec8a913ca2cc292a9640efe50fb85a1d1f7b286f45d4448f85b3242f45ab44e3281d759db24dfabbae4259f127d6546ecb914d7e93e2c19230c67fba8a6cba6069023ff7ea3d8a170289c2b4391bb97a7b899228d032b36186dfbb29ae8f0e6c06d753f4c6b21982d49ee682bef50a5c2c8434510c5fa2b9c0349592f33f8d7ad6f7243d42b292aee6d210c61e3f898875b91a17a89148275031b74cb34e628d7b701775dbfcf87c79ab279a73dad14d8eed365eb9f29a007b7d2ccc07ceb8cdcdaece67fa0166e135c9a4b939426882eeca98ab887ed2e4888bbebd5afc9f2da3e9162527262b0fa85903246bc8b80df3060c890ebaa516781a2b2a138b98001287e12a9c68471912dd297bc0beadccdc31a27b7c726baf31510cd355a28e4ef786b30084af66ef135909795aa73814cbbc6552270d5e11d46e9497ba30d6d8cecf343d16e7e3357bc9bbfbc7c1dcaa5fafd8a9b07056129da02e6228886463474c5af1d670bc14cf2868b816cc71578ad807a37477341c8192bfc2e8b1f7bfd58827e041f70384f92bb4c6acc415dde5099a1c2b27b709f9e53d1dab07c87a042ca4af7a2a6ee57b37bf2bb42259d372ecfeaf1dc55ac3a9f211f16fef3b2d5f11dc19fd1f425c14779580b2501ec6e0a84220e7e12baf9e0fee3e8cf499a7fba6721a746f598f04ee8ab4df31fb8fa5ce2d2419d5551155c009f2780cdd225ec2c19f94fb9c8b785ad4574b4da766eabfa696a1994e64a2518d1bcade6390cc683a6e80cf8b163c3e58cfa1134ee743079347f08a89c81478668df32ce9cdd7b853db5cf7af13436f3bbb11bcfa8f6b6d727a1df84f99fb3a5c248b8fd5baf669b68fd9af45298030f3251bf0351fa9b58b0b9fba53ecfd838300790ebd689744c1b7b333fbed76c8fb96fc669ecc6695ff5bf8379dd2a3c270af858cc60894be8922d69fb9707bd2a7825f2eec4a5056e5e91714f4dcfa86974259fcbfd5f20d55923a0a9936fb20e5ae9670e2019336e15f530c0be449fe355a7a02c0938d60720d5b8f4f59d2e4213ad5251c6058312b43d47c44ffc8946a98797f5ace279d3e126da63633c0eff1c412febdd47817aaee466c639e43637c1e179f606780ab490d3f0b3c2d79709f1262305fc87c02f68da2dc32f8c544e7b358c3a5d2c27986a19d13fe736c60a3524e94caa55e853eedeece985d16bfa6c487bed6583436cf82077fcdcf90a05f49db50588f46550f7a0c3a1cfca902d66d25dba8d2c53bb5557cc1d87c8a407898b3c30c4f0852df92d839859c191228d0a47324ea9ec2e0ae84513cbe4ff4aff85e77b8587f1044bcb9775099ebc2f28fbcd1cad58a8ce1f072f2228f559fbfdd8405d86f8262c27c3d95e01016b343c6a4e59dec81b59bb6e3c6109a4cffffa85e9752ed2149b5624417c0dfd1a27bd2630bf59814f15820c43bfa317be59ef6f433c95e8be154a8ae94765bcedadebb717f0d8c24e01e1952bd104ba9620f067554ae0faeb78f13c622c45d97b2b5774a3e30cb07f2cf0e8b19d1266d8a8861f3772305e24ec5c9cb714806c7d705a3bed6385f8be4e12562e17ec3df01afb4ef6f7427c48a1bc0e64fc65eb1c3d3ff2d6687e4c275a019f5ab5c63bbe47e3680fb1802d5835c4d494f0f394de1ae47f81eef005127d0971c4589c456ae6a69855f35635c28b590c1b93f155fabcab59b6c7cd8ea1c4ed1f67093aa782c54329cdcf9bf84a40400de707b894587d6e08cf7fd72fa45b6709a26e97ff5ec1269b8042358f872a79e8c2db1c7ebffac014d6b6f71b0c1c1945ddedaf5b6911668059b61b55eea4737aa307c829309c9ea548fba2bede023849bd61b5a467cd1ab1c61205ce64301e2531e5d58d03c74ecdafe1f5b74627be8716cad0d0a0be60984c9f9dfeae24a6c4949170ce2f589326e0a76c447a578ea3a5e4bd9f18884f18843eb1a78aa2fae06a7569a97551b227c34d429c8e1c8c5417ced93c30dcc607cb32a365d87328aaecb4ce57ab8e74f0d9099e267cfb747a3bca9f76b5f6dfb543bc4b5c06c3646062ec14f511058eb2939601913f8a0f1785249cb72b0bb1c12a9508b23caf490537eec53f614f3e06592eb61f75c1cecfa514cf7b500b0375095d5db74556220131390b77d0db72711c0c7229a5769b1d2b3f5105f3a4370beb1cacbd93ce32f89f1fc833c7949211dd204616c013a3399a22f5325f1a00008f4c8ee7dc5bd7476848721fef843123a6213cb0c0b6ae84233ed01a77a115d06e08990b8e60cfa4f41dbc9505cfae76463278b6c6b5ac7c3b83284caaba4a6a1d739c392528ff5b06bc3b82e98060e3001279a44aabaacc661fb14e7581d1235940cbe067c6b386da09454e0467c785ed0b65d41ff4cf36ba5f63d3ff2b45c11c6c22d3ea8ebbf1d52d770e0ebf2ba0c67c7d3641c145cab474a88119335990137fa82a340c2cc8c453752a3aa801127a47aeefe66d1af1a26ee1cd0e6d935bd548f6ce33a9c204be02ba08f9fa03c685665375db7c0c656ddf3e441ddd96b0d2018beff5086cc63339f26bc8332a5e6a1422bfedb69187a3443c23b630a28b02f8075faf3ff2fbeef6cdf02ba4af47a765003de2254b69f487bb5d038759a33ce6885611198b81b0b6fc5d7a531a7a90dbc3556aa758db1657698cb3698b8207b1c1b589efe5d52790667ac483dde9543953c6392d5eb8afdafa205d325e314f810e9c7722cbf5bb76fd6502733149bf21c60717ff5bc366b85ee9f206bb1f330ea72f61a9766090eabde747b1eb9c046cc8713d5a4f8d4b7dcd7c61f2496c5b467608cd9260382b8f11b04c318a5ebb6411a4c7fa060e08c295c6062ac644bd3d10bcbfcfe2e3748eba66f65d904ff21147faa8475f508f21238d42f62b697249b9fceb905127f7684c8130cb8663f09cd25ea038078e1980237389337d1446c3a77bce41b37b50b9c3a020526e7b7b3bef370cd7af71b225700627060eb65693899d277ed130ec5ed9eee75d4886f31aa93bbf302e0c69c9c4499396b43dceb67c02fafaff8b56698308393a03f60babde883f00de2c66831f024fafaf98b2fcf37a9ce01d4f34e95c9408395716dcf83fe86c7a0f5e3e6741c3b63b6ebe9964f1d5005eeb732ce66402007beb3e6a087053", }, { "9100c5b2d7c5d5a854bce55e82f94b89a268da7b66357a661dcf75cba10a1b320ae0e4e1a5b989f9766e57f867a3810a0b5b857191ffd7aece4c796f5694a2617486421940cc12b63a6aaea20d2fac188b318a1c3061cafeae436e04d710654b96a864d674768caee03a50ed6afc06f52d90115df1db5c9f1ecaa4f5da094070b1a447251ad3d4fb0e24e87821ee6d4e7e7eac7059080f77d2b36cacbdac1c6e5063946a376865458c4ebdad3c2afcbba8a82b01b03a7882eee42eab904a19e0aead4ae515b02aa2fee74f3a114bf5b9f320baa35b3225491653f4a69e0d864cbbd031d0805b727e42c2b9530dae0c01cfc6a42af8ca730e1d67b4bb743a072f0a38008b937209d534c2284271344340fae76af2b1dd00cf44b48ab8ee92e8f9cae8845e5a8d338f505cd1c19014018bfb6b7dad487e7c8c32064421982c1a63149ec16f2bf4fe7b50cf3ce1e33d6cdea8e98bf067077c9a0ec1bba6edd5090273ca719ebf6f1a0f3e56f021945cff3c468b2dad92a947a06a024758d7505a4a1bcbe9da3a03e97859da99ed36982a7c23572ab60071566b749dc34bee1d9609e87fe32282cc9adba633c9ddcbf359ef4a83a54af5fbb5699978b487954a907dc9739f4b3f3927e66cf0c338e31c272da0cc7795c72dfe60a5b2e73bfd77b8c6ea58122a913910fe29d3360cef5d398f29b024f0dd225183d538bed2b076989aceaac460e3d45e0ca7941897f151261a024b0adf6d5b62429420144497adde6557a3c53b7723471fb760b6a8b1dcc2b327cd939528f5d7bc16ec00ad99df12f082d82bf9fb7318b3d3ce5b84ab1e38d2ebcb6713c03fd0d62bd083c4af96b4316ee02b6953431c261278aabd96e28f81adf7946e3664446135c825e45ed916ccb941350c84523296cadd5360bfe3e16dda75db10da1f710fe796f3456f0911294a4735cf9968656345b9c3049ca47176194c86f36cf702538df699fcffaa254af15b198ac37eed0837b00cd3547e496ecacf6136c6648a535a235059cd75a3bfd0bc49933b379b72e7a8463c268faaf05f0b27256fb179c9d4c923a13ec6600f83aaa2bee13e30c8e676040c06aefc65ba238a29d403f3a8cc164a0bdcaa1a5f54bc1d35fa4efee0c402eccab1e92f6b0cba94e1bd87898a9dd3957a7eafd9d26bf70866450646090833d4b91c032428bdb9097b409305de669a58e44931b7b428bf1a6dc56177cd944b87b04eabd80c64e287a5758c83db26dbc06f0c772335363ea2fb9f19c833644fe3b3fbbbbf5f9d460412d287eef862ae676f258aa45bc8465667601e9ac46e7d77693936c8d67ccde94e54d746b785ad26aa38ca0500105b6870790235e780ac50b9e3198f5fe678ae3a4ff4f1d4a2177edae183daf2de42625845973fc544907e27a90d868f8634c9d529bbaacbd228a5b4ac7fa68ac208e207a022cce4b24a0b5b5791eaddc6b3b3ef6e5dba41855ff531de9bbca0a39ea743c0732772bd32cd15c4b7f28a6ba579d902331a88920fb970aa75114e14b891d42cb947e9eb14feafccf1393796b21099e52b21773adae8e550f93364b1c438dd7d7fc76994c51860b652974d04a7e6ead207610de149f231422595f4e9ced1674d98d0e15ee841143ad8613f804729524e8a5f30d451611676f70a60c5dcc7127497f4d27f35e7ba0e48f98e9022e0deac400e809170970867a1682c7d2f3ef2c632c44568abff76f4f804841ae462c7247147b6e1debe48802674fd55b2ef1be5b4604d5f60c35358c7d773ab3a3ad0ab81868c6044d4e06a48ddbffacddadf813a2ce09aef34f3b60b666245a032f021b87c81fc506166983f25930cff728d399f6dd48ea1c745ad2da7f2cdd9e3ee915f708db0d1f3481018db1c174ea950ed17247bb8ebc065186758e5403bd4d19a445e4a15519326696e4280bcecd1a903f525bbe1e521f94d79df8db4b35f4ef7bd990c0f2c32789a75f95761ca0064bf251fa00b409a58b979e56d2c44bc2302552f118162891bd78272384c739c0c98bbaca3fc46fbb5bfe123eb25df0e27343e38b5a0c2d0774443af91b64b9d4e0649f20290edb84fcedb3bf4ba491bee8754a32716739e5ab64deb6c9888bb9fd2ada1629a59b16934ec5dee3678dcbdcc7fe5e2f3833da9d1281669b1d108837eaae5180396813883de26b957037623825b0675df431fb06b35191c06229f84cc849ccf1b1e079efc2e575331cd77b3297d2908c048b82b7dd14883f3e707bf6ca38f87c19625bec47c11f54988a97205d27ac51a32f19704391af72021b78cc4461386dc3844a1b45596fede3f70e311eba92b1d9ac221d3dc19f3fdd080c2169348f2cc8c9380e12a7ebf69efa37bda4ca6f7e66919b94532ac43022c0518c04d0a8cd99e0cbac88b7a317a1dac5469534b4fbc64080196b44498e149b0a196bb2d6f59392a21c4a4523ec1ff922a52de790e42810fd9355471169d22b734dde4a3361ecd57e271a92132a8b35cfa91d508d45618ad8c6c1ea209405a3d1d3ee1535caeaa3f20546052fc13aff7a584ff79db1726678344098d8563caa2a2abf6fe5aa03d7af49dccf1b17be85600e7cfdbfff54282394b0fbeafda615185574fdff78d59ec2a26dddba1c531a1ac007cabf5be2e2f0a3dedb9174e0a9da5597c9de6d68911fc66ec9d2b1e3fd71ebb83147ab14384ee303d067f47a324a01fc187f54a98f1b0848fdba2ceb3c18936d503e71887d548c4dbc70b7eecac9ead3393f8cb85a84f1484f2e237b36b6d886f54a0f629e8bb05b0c6839c722149a5b541703aeac04e6eb230a5659b12ed0a668d018f75bc94258218c1f5390b9aee4c0b2836cb76a47da649e2425bcf4cc15c4d51d109e5f78cfdb88137c31b2510264e46f1c4eb6e6b3450ad901ff9517b47a24d508844dc85fc5dbcc079e2d09f301691f401ff5f36500cc66f0617eb4dba389d427c7ac778d78438506608f0961f818a2080ea56d0f61c40fc342b49ee63e730df61f757387b9089e1987977b7fa02d87aec2e4be24b8bdf7fb6286d190f9df870944fa910df32f178ab692fa56b071f57366a3981f51800ab416dc4500abcc19e0c6aaeeb9ca063470993ec749a0bcbd07604516b1d51175ebedbaec8986f67a4d9158f75b5f3bcbe86a83220b4fdf12a0242951f94ac7d52882b1b209b82c4749753ea4d46a60bcc4f3eed033bde2d3d20c25cb46fd907f7052217a0a4db143b2efe8875a59441f4d22ef70d0c244b2de6a7e15581e84c860a6326ae3e3aea6d3972e2de0623d2d852c9e65eed318bd3d86d29595575df60d9050e1740f884796b6657718a294adcf2303adf61c6b23933db93885172e82a78f741b8efc6315a2c88ccb6b11692a346cd82a79334e0c610734e61e6378b5e2ecc161d924778bfcf4475805a0823a0d5a54768d9272ee99b7c4a81b3d5dfe1a2f5ff34", "3c77f30bbb698b1571aeb54653fcae2c23dc16be58603f0c361eedd813ec0c4f63005a1e69e533da93e820e6e4ce1308aa29c60289060ebf24fc9738e8a4874ca4e26a0dc79ee75b8607416bd554737f", "0223c0a6052bb3cdc99a284fa169ba76be2df53b677642a606090a9267a60769", "7d3981073f90c6648c5e9c74", "61ec5230306b70113f67b340575b77ef76d521ff75b754d551e4177591a02351ad382b2a4067f2b3af7e8e15431c7133e98be9d8293d17ef40161dbad9a4f1a4f30cdd557bb9a8b03b5f1b277c850e23ecfa0fc2ab1102e4b1d5e836a606883c3d43527fc3aa26955964b144a9a56cafa7b174d72a0635b80e7b4f871ead3838a955a14c4b8c5c3c66fd86a5e4ff10dfaa92105378bbc5f76ad29727e5bc4779ba3e6dc19bf45020f6ce4dfb3400df05cac51577d58eec21b22839b8f055226b204e641783bb3305b4461172f1c1d48eec56fe6f82aae564ac6688d7b0994747d9b23a24418e69f8a4fc548f854f86baacbdec78b7597b138c453349034c8cad2ff272781e0e6799ef2f8addaf18528736aef21ef8c2d213161e36b2c7815fcfc40747626e0165684e46a9a2275c533d548e52a9952a556168195d602ead86f6bd699e97ca59f4cb2050ff148f5bdfec358dc4542ff2f700db9861dfe5ba377ec7fdc0fcb2501e72fe6873c7cc76b95b4f300857f76e6e6e370119f403b556115b19fee7009f4f6675ad2d174f44002e35ddc360f309f20a3a1dbf39d90d7e5fa2106c53afb0bf445e4cede59cb50b8a7a2c0961d00b2c251f2d815309f74a46a424838ee87f1229273ff3b66dfb79e3b1ce11bd60e061e60e3f37bd7ac896b618cd78388590f44b1a276b965a4b95f2e3a7a175b30fb45dc7a71d4b3a1a33e98af30dbb46a217c50046ac21b8bbe9537c02f05a5780c8a5d796bd6424fd9e9f3ed5932069bc050bf4a1898a0ef0ca756aa2e2269b709cc92e0c5192ab49d692143388ede2bde4923c85eae8f59db5c7711dabeb33743c692be6dfebd815456958b5e1384a109f891f433e7b4a1031d4f30478b05766dd97eb964a28f2f7b55aa6c27c7f4ebf4d47ee8709bf99915426b3896412a855798e392e111789213af537cff7a976b4509e0eb6ffbb8e886a3596a242d16d95109b0ff562c624e06636a3611f804f9b2e252afe8a4e5e868b48e9e734f688f2da2012d7fdfe2d3aca75fd74730a85aae90353417fd52b92d28a5098b6af358a096b859859916bcd5a8f779676c6e04ea461fe62872050af92d08cdf1124bde1e889ace3c923457ecfe0a635ec757907a131ad7c2ca3f60e1317880f843c5e63f4ba59ab2882a492dd1e070b070af6f60e18cca29541206a7b267c3f75a5327fd9b8ffc9b36b57b73b36e586541d15c85253e17a2581e8f8a1518f275cc79afcf2b5c88a16e9bf553e757df089b5db90a9dcdc1867b788fe75abb5161dd7ee1cf37d3f0faa793ddb1bbf1eca13f4220ea63af8ef7c0e7144d999ba1c5a983e74d48cef708c1d28d3c0a168ab87d0ef70f381693f0d438ce013ffa2cba65a8cf6b498a7120209564535b7372690329cdbd74eaa76765962720f06aae58338a10064ad80f5a67395db2c31d36b1f5eb777306395f192599d2f737327afdcd9f14b3f24155a3f974915d3302427494fad756703b13afcd1764ef9735e7dbff920f1253cb668e9f40632aea1e0b4620db162138e4a97e6f0729b14be4a7c3256250d5e7423ba1238c704503c51cfc9cb68db7001b2f597a15e77138beea02e11e0bb98a72f2a77b7260e9172fe7e60483114ddd836addd966b69570db5eb26a0cfc4f8a8b80d26357ed51a70165bc0dd11ad7467688025bdb532e7222ea12f23c44d08d111b0ad4acb2f5b3d6b45c387d541ffc84466ed57acacefb1436ef00bcb5b6211dfd0650113ac369b9f3e4891acb2693c377467b1e9c949cc0ea6c4a72ef9292964275ed397cd2b1ed25fe1aa8f47e90cde362392da5e53893eef6e4f61decae1a75e3b726f0596f09c3cba62aa08bea89984b484d5768296a5afa8b0759dceba530a169d22b81979212b3343db35ce4e4766dd251ea6a47f5033cc090d6577efbed441bb4f8944937e812f12ef17ede76df621bd4cfa31567ade18b74583a2b783279150d584ca13c0d4784b70156afdf9be8ae96666b82def888465cd3df349de427d5f5b3572e4f963d33f968e6780e381ca196bc04a6664fe93fdc8558b21b84130dfa2a646950eb2e927885925af46d7a28d1507bcc3c02ba98318bfebe5b9eea1bd47935ad869eb701cbc35a9aef5efad88ff54eb350a34ccef2e159de8e16135b81105bf799fbd86aa11653b5ef93a1ab1c367231d61b42b8bdb4f04d8d05396d53247d51890be9b56c51cb19eec0fd1e6b8cdc98376b6c6b30963ac7ab02656ff94dec0e3a0eb3f3ffb8bebd99d5889df98e6c77093c370373dd5f17871fb334c7eb12c6ca22deb75bdac9eaf24281c965dffe03da9c940e13fb382fb6be332797813710a7cd2e7720f5b9e53fc0d98fcceeea4a8e9f787e670d60bfc4a849f34571e5d09b9e9c28cdf2b2d888eca9bb31ea8b9239bd19dca86880ad3e12b1583acc3a6d1f0a438ce3b5a337487279dc4ead1b214272d455e6a2c8cce4ae3bb29abfdbe77a67ababeaff5dd9c96b17f589cd4615c0209eba5e4b1c7167b4b739ca4b9957185961529d1082226f85068890c94aa1f1c244259ef7b120e40114926a49c4412b67b4caef1ff3ce6f3aea3c6107b830cd34df9f4d73d7d978b6b9d5c481e9d76e83d649e742b098334838fe50d80975fb567642d3b72c461ef3072ebb1d03c0099e97575bae6a12cd2352d9d296351df6965d736d7568c2911394a73d199743526ba54dd62c56c598f4e78495c0172739274c0b8c96755e489765723a24a8704093a94544f6c8764dcd1ce6b4bf2917cfad27d85e4442b4e5bd577ea1a88c2b79d61cc1be01ee9028235b36444483b4e45da1087bf6d45ca540620de5aacc644a0d5c4b807b582c7b058e140eebca539947502bf73c9abc81a0e3a618b39d3a38c4ff7f94767fd7e6b9eb61e629806bc3d183bdade7e369d180dd2f57fef677e22ce41be7224f11723a85a3f1d14d7b72dc98ccb2816b77e625ce3db3e2c5753af8b079e0d63939079a01910ee4699cb405d4d9c60e4ac86a7fda3a4c9c290662afbdb7678c3a84c87ff83470fa8a416511a06d3216a1445699d7ad7e6980491fd596d39762d576b08fcbf0825243c1fc01ec8300780857c429c607113160a8354f6699b368a87983464472a5754fd58943fca6f6779764fbe6cbb510d5280292df02c4a7ed9acec8c95ad67ebcda71d0f519ac18db9b43b28244cd34fe02c5d694df57410eb54c5e1ca0f8501e7776a811d7ee81eb9d8c80b2ca50a012b5eecd5428af965b217e7fdac80be88a01f76d473105b027eb557a523f13c55e1670ff34627667649573e0f19dda41c525a8c96c2866a88bd73e66c786767e1657960f6676d8a22be1c6024158a0f0e4ec761148b5a3d8ea481d8fed94855be82479ba23213190054f937838f0e35e00aa74c89b294c29ea25ad7e96b4b6fa952ea8f1cbe5397b7c86d0b74ccc25e22c88736b045fe86110bffa0679f28a1f27162b51410498cb7", }, { "0fcff2c29cbb5cc40bfd2ec573ecf368275ade6a00e5730b77dab17e437b46524b3814e7f470acff6ddac4e0c6b748ed112657120bca1d83a4ce01e74a473995804d7c74bd28732a02370ac8ef52b600790d1284d82f077cfe096448509dddd0eb5944a882b7d384efdd4dde3003dea910f12de82035651e3ec9668e66435f519da3fa1f5bcda34aaaf028daf3068304f7b1ec18e65136241a9db281e011d27db5cc9c1099405a4430821e2488a228805314983966ce5d806b0f014c21d4c9d6a066e63aa6407ed6c29cfa4a3e22ca913762ca9d31271d9c371fe858f3b22e931814cdbe544b9416e88f6026b12bb8e88d8285beaaa35be1c24339b5f567480d7b16cbcf6160e549ef4570a0702889feaa0ebc54b11735735b6e2850d5715e5087291fe8890432784aa219bacaa2b874b075c9628cfed5e76dfe38426f9693f6bfb2de49b710c101b2dabb7c7c74f12de9ba8f75b8645d25629568d12bfbc7eaada63364b6f56569cf21e54c95d6797e9008f3496c506ecfe5d6a010d168fb7f0e2ee3c423492df36a133fffe9b87d7ac070c32cc131fba6089cb7d904b25812e03cd6048504f7ef1736ee00ee6b7aaedb3dda9c6fd6437772fa5076aca9888ce55e906a62875979bd477aabb2f4598d32342aa10a6d187c6768f213117a9ff6d830603bb7b9b475002e20b2237a4055ae6af6b8d70e343e76265188a0f07e7820dfb3d898684d99966d4bb9e78b0e95f5044dcc12810a89a75b11474c8fc06c6e734407db91a072ffeb2be6773a7c6c3ec939514b43daf29feb3aeb7afa57e96d9cf0492d90bb2c7be613f2208f5f5f5898b0a3db8a967a75d065efcabdd83759c88086583bb3d422c6c6425525a1adbd515199dbe71350b77940813618b88fe139153974c80d968ed4d9e3f97a91b7cce250a7c963f880dc38011250b9a131f2b76b677f78fd0e4cd6f1465182fd1d644dc42db0bcad8df4ae9f456841765af8e1c1775abf85a69577ece6f9e9035e36c88be784397479e713be4f5434aa4c166bc4702a4916c0c003a6baecaa182372a30af6dc7e6fc4912d13e662bd327829f6e85340fe130001babaee64d211d6761bcc52993c162a692a10cbe7434310392b64792a777a2b31341995072a6b7d4538cfde74e609dd1019a9f75cec0896186c0f42e3896d15be87aac5b11642f74e11d5c2f7de9f07f848ff543507ea4d73fa8f5683fc6b41831606352c482c7a5a013c51e0db59d824582c595f17a6d2113528943194d6b5aadcead62516507f178cd0f76729cf8b81fce4e0138ab224bfdbb8f16f8ea6196b90ef90a63f0fbdcbdfb5320984be8a80a26b932d1db7ecf870dd67fe838069136ff9b9ae087779e82cacf1b06a7b310ce6c439047c26fcec0364ea87e4549a544d540256cb7c3ef7282fa792aad89e919dd89519fe910501f5ef88da43232e917730e742ac2539d454e066feb9058f56dd246fdbb674dcab636585a788b338ffe41f4190447a65985acb9613d02669ad4ad888004c65acb0ca315752e58f51c9ae9259f20cbe8a668a207a5a46e30891bc909108f53db8bf6f0f11549e621d4cf4763e0035c867bfe9e1192fc421c080b25289a78f4167fe517852efdb6f3ccfe67ad01b4337da2c18f35bdc151c5dc76ee66efd27d5fc784e4e6829bea4f8a41ec8bf61ff998d178ce9f4a10551687337d7705eac6cd7fabb3f2379e31c1d01e4dc63e475f0fb01d9efa3de400b5177e2c2d68f2ead89e9ecad62cfc97fd0ad5b3391d0248dd2fd7c75dcbd802d3463ef0af21eb77b07a3286a72f1e9439f457630159abde7983a5c74f7dda12b40913632afedadb691d62003c70a46664fbd976457544cef8ea863858505b1c596e7f745d4a5fb657b1c694226afa9756c40d9c49425b323ce17a8531c5919b24010f715b5f27a300ee37334931ca9ff5c83c3f0a87713768ebccaaa15e35c56f3536ba945e5d954c94c885c68325bc4b51fb55d96c8d424849ece9a812af0747d5b1dc240f71609439f65acd1c17086e025e376eeb79a7255680cd692fc4b0f5768d1985fe8a1a387074f58c8bfdea8e5c11ed379b845ce2052a5b24ef0c1a658923eb87adf5b01e6aa59ae6937564ef97421722c67404cb9e5fe07d5bfad2e52ebe6cccb41ceb1eb2760545fb6a3582bc4ca572b0aa4e4f0a2ecc56299f3b485d980501a4e010576615ad518fd2d43c1f79aed013ed1f1e1bdb74357aaf7dc84772c9ec62da43c8ffe11a7fb3eeabc3584a936c37b28a438dfe78f89de6b0d5597ac1bc55057544e68fb49a6e505db69af122c2a3ad06219b7f2a2955db0ebf55c06baac5e0efac609436dee484857f75a8421945484ad0c7650a1d3008cc85c938208f19002b7994524878d6ddf85c763a65cb72a09c3a059657459f13cb584bfbd754fbf2de904517092be4f1786b2bde26ae8eb2d884592fc9e84395408f8117e47d1ab30d5fca167bbf07e41a33c230d240e3aac53cda9f251e24659da57d721288252fe7ff3653ae3e47b86209e9344accef0009b99f2ec7b3845558f1d77b89fc9b61ebc1b589fffd3261f71b9631e87541e22ed100e694854bed771358f10fe452fba61875a605b8080cc39e3eac13708e32518f28e60464c38b782c7c7800df63b6e7e95ced9154ea54e32900f6998f38eb1e51c112b6949e2eb11a96b1ea0a68c1e3b5af750a99c9fdb2cae44c5a1d37686ef87b158d19343e23daf00dd558cfb91e6f2e18f8e806abb2faf80d082f657717d08ca4e9c0d30d9bc30b612bcb1a3a3a3843231059dec344c6c04ce625b3fe064092e00175fd9d38f8fe54c4088efe30d211412be01460a6d4ad8d0a618b00a21de0a383de30ccd72f119b27a08958729a999e8aadff21829cbe8cfe398d90476e33db4c64981383a9aeab4a27f3bcb29d4b3d3b3a6ebdd71d3ac546b8658e269959630de176819b153cd53d2091efbddd2cf9178ba6ee98e1a3df9a095db0a2b713a0988a22239f5f08cc8f9abc3d67d9267f54dd5dedbf01bd490b0b09adb21d4e5aa7707e36cf77034f01bf8c7988a2e8dd7046bb2f486878436371f1258f3f7026afee6d7f6560be67103ad098edc9665e00118d4879f58bdd677cf2e6bc631d5c517acbb6db8a1debb4fe7492b7daf0b7ec7df056637c23caf926a1a589bef1db29cd81f547afd0fc9e459f46108ffdfcfdee43515a771c439dbde9177ceaf296a8749be0146cdca2b26be8c2ebd6cfd9b5032b1f7a375307f54c2f622711f8cf8684afaaf17c4da3e83666c40d26adc239c8d1a40024bbf560db5787ed404763d4e70ec6635c6a4b82c10f8ff7ad42217613c57648716ba94cb33129f3789dc86f9c8ec2e8e90e6bba0dfba1bb3dc3215188979a09f33346a6647099ed0e624c9ae10f83da0def840bdb25b718e8d86a616ff46b5327b1f99c22937920f5b5bbd6b53fa0b32f24befa4a7603234e6d94be51f00189a20b15c49e8ee58434a15ae9d10b9cf0204bfa7ab1fd9e006b22bebd22b036c4bb4c9949cb7ecdf01028d9f12466e144b2dbbf64d95d65347013e192d428678f64f0d9306f97208fb00a70d4615229143dd8890725ee3ba6021d38d6359055aa812edaf", "0c5fb7075f5e15a6733737b614bf46871e29417e4b140bae6e10081623f5c52f557c36b4da4b5a4e82920497514b1e6f745fedbf73f86ee10976f82c6cbd5bc13a917514ddd062", "e70954c812cac03e367e99f7b82a6dcc073d2f679f965d524872756ee58654cc", "5f6267f6b3b21423267310e6", "c53868c0fdc14e891ae1bc257fbb13be210a5d9cdbd9d18fe1b474f9a1929dbba3f25222d8fe8c1be3eef22352100064b922fd9642ad128a202b6382ae0a67c8affb0c5bfa1a80e55c1084cc372485243df872d677a80a3ef1ca3589908bca621f6f50133eb762cb9c05775d13db7dd3eb65ffd3eef96e8dd42928facc68390f6bbc50b17e1ef5ea6310d8756dd177be2cceb63a97bcceaa046794915589ca022d90756b02c22e8634c0ed44192abc3b8b1e2814c855ab27aaae3bdd801a73e6209fdd559ceb59a94fd98a66d12a31a643ca2f4b07ed910bc390f77ab89395d5cd1d783d8940dad4447f0452991b209cfcd998b0c814cebd08f9ff15052818bab0bf51c3b72ac1020d3b0974fbdf4ff941b1ab9c01f284fe82f2fd89c0aeb4b9fbb0a74ece08b3debc7b65e7263e2922fd4aba15ae3cba7885d04127c8e06a67f244e7aa4556f8694a5db6653f6e48d6de54f9e4024d25d3236d4f933205b6a358aa1506f832ef7d556c6a1bfe4aabfce51f3b5ac64bf6ab1e665bddb12fe13db9f07a55db3da3886df36ddb89f3a4939b1e9e5b701301570e3d01c0b947f498dcc6af438cc15e6038cb78a78986da0316cab67bca3e28c95e6b7e6b36cae9202cf4a77a0e15d3c3291d267aeee172dd587a944719b9fbe077603b4d39d4302b9a6415aa07af309a5e1cf7a9379552becdb4bc6a0b5c85d2e63bb141c405afc58a8b2b4188b3883a24eedf98dd50fc54725c440ccdb03514a6f37cab49296b6826b6bc7d7ad8cac0a3425eeb6866d94119acdad468cefe162a29e8831c77aa83321e8ae3e20e968cfe51dbf2b63f4e26c61536e6be4f63d61bbd06af38023b15f4fccb8ae0356d924dbf646bff69d1ac0d6e1c7f40b12d6d16e52d1c15958add5708bd38c514e47fe623a67c9ec211cd625b398fa7fd67a23e6e9f65d42dda2bae94524372fbc1a7e0ab3f1c451c126135536e73c573749aa60177dfb68843752b010e2cb9c1afaf51c94a48cf8ac7aab3fb200aaebcedefc6cccb581848da0121af92d9f4be002f0c2beffdfa65c36bec80e7f62d7009b1eb719d24b96e97059e6b50a52662c2c833738849f342391514349305228b29bfa9c7cf2a931558ca8e704c600148a28bd871465b23af499c11784aa45acd051f276d82789c58b14f12619372be4bc3a285f6cee21d65648d18e61752d6e7957736d3385f8ad36702c451c61ed475997d6d9f11c8be5257d8febce329aa701028aa2b5644b8515a95b5e866780e32754ac2e6f2e31b2c04a4ad35cbcbc25b23e9bf49cb1a5d877ca30880741757c29303af8676546760016f1538991b37cf0cd24ad3b1d877e5e1bd083e4b990af6ff5c0b28e530db3f463d21e76c928c8e1ffaa6c045937ea171a9071827a173e231f50e95430ae4895932c88ce048058ce6d0a50ca5c1842506158e98bb2912a61c7991a2256c97cb9050a4bb3ca32594622756291340561e9e584dd2e096263b6ff8eb898ae86f5f24500320d2d0ebb30d84cb4ef876a877dad23a611b39bf0cba5e22f2850e11c298fa23fed40691b83acc87136f8fa540b1dc40d1b0d0bd489ee9dad785c121955a094a2c6bd3353e142c04f7b88b2eb3305fd00d5eddb391b73fa2b16a6357aaa2abf2059ec979bd3ce06d5fff1c325bbe5c833a101615750613047d8155ac0c3a0734cc6aaeae7cb65d7501cb95f9d6d1161d09c961c0681547faf7983ed2efaf4e0fbb87a06169ecff1d0ee540a9223a73f75584441d4669cac09c2dbdb8aa2aed74eb9a2870f2021eb16e5f5c3e79a24d7110af4bece22a1086d27642550cadfa4f0e03f2c032a2745e1c9277a4f67fa4dc74ba056110fed3a63f643567d079c9430b8d5b3bf57a9b3f02d486d870229fee5462043b6bda8d265c745ddc1b8952bf91828d6db2edcfca7051e74df9dd456dca5e04ba469b9ff6a8130aab3903c05659b8f31cf4ba4c22511493a36541ff9d88c708dfb714d52a3c0356543e6efad37530b598bb63c3724772907abe4cad39c896c62daf5b30cd7d37eb36a7be2494353028c76e8d148b018c7bb755c45d2a33f61944071bae8316881e9aa37e4ec2374aac4f8436ed3c7db2092326538f07fc6644e0239899e3335f73c1e3c4602b12d19d7b639d4968974b6b2703ec1add8cd930cbafff4158f68f06aaac83bb4a2e31466e2ddc247ad71c5f4c49af7defd1394e21819cc24c78380caefb2ce87c0d1050680313037def12ca21cf67bb6692d6e4a9e90a9c9a0b7118ac300c6c6f636337aa25bc59cf1d9749dc183803cc0ccd1ff53210352795c6edb49ff1e5e8ebaee7b3eda6e3c0c340fa60594115e37fab60133b8a3b39d2e63db0bc6a03973e236fca801553912f93feafd8b96766049dd2066f3c5ac9222121ee9d36cbcd8f713adc8779949941f8a8dcc92ade62e46e9f1b292d5f7eced14c3bff50a811cb762ced1f103652773ef946e18569eb5892626627e085d4ffb3102c1586ddf88acbaeed903b22d3e7ccd8b8ddcdfddb872403240bc8e0e46a068f55bbddaf90fffb9a914187aac2ceedf21fefa1fe32fc7bdbb9fd76dcda1fca7b39107d308d11a118e47499dc4092ef0cd28d0d9af84440f095b4feb7adcba198894cd89a324c60ed0b996c520d4b33391bbbef1997256af7ba7ec1069244359066af81543ca23105742fee3480f890373d3205236bed566cd22a62bf69f8c0f27b714f84a203bca1605865e2cc2f9211389e0df7a4b3aab9d10826639357efe1f5fe64a1bd6d06d0b5605658c4d2d12e1bec77e70ea393b0a09043dd7d6684bd53f4c883f2f6928d99ba91873d063d43600f9105d503b11d8dc2b05e34b4fcf18e78b2b6c97d3b2c9249a2f6566ddab2a8a67fed6c9f8af2f4ef98dd579f2d4fb572e178489c503df5d5f03bee9920db347a6e734ed72ec7233387f1579c13725599a33a90915ddf03725dce20fd3806abc1029a20732380596057830ed63b6edcaa4d4418871bbfd58de1d1f2800588ed207f2016e11abd1baf1895f6096e2c75cc5916836a9ddc09cab4c28e53fadbd7d3080088131cc270095315b61011b0cea5b4d64b647bbcea54d20be1eec0992c72fc9c9771cae19191cf6a6f1840acec1deff605626d0a0d79ea8fe0af63ea75e80f8141fa8d7ca6f4c99dc7e78aeacc67762ed0134f1a0b053debfb9ccb145800b9818c2deb46f7124e8655f37c3291af107ed75384afcedb44518ca14cdea341c9657ec638531011cb957ed6b3434b736ae8c8199684cc58862638c5f6c07e1cbe8ae68c5582b1697ca9dbdd01e97023138a9173d6b1294cd99514a28102e6912b1c87ef22cdc611133bcc111e95c355a26b20a3d6f0ead66e932c5e1229b0fc17a7d6f78134c69beb362ca75017b1bf1105ac8970fad48acb8313cb3ff10e9d72c4ff11f95c2dab59575525c98653a9c7d31585a3742267c062d6ffc7a4303a3e81a45bf39e1ce2097623bba70f216aa612c64ba06ed6d596ad6abbdde69d56ab45e25ebcd4e485824449550232be26f987c14008f67c9db9d0f709f567fa44502b9e0839457e5f0aadec0395bf5c38ed8de7529708e58c0a895198fc8b2570fb6e68547630ca7f313526d392ac4776be973205f971854c300454d5", }, { "95a17355dfa9d378a18ba20e58aa4b8711ea1d6e3c65e0b2d3c6382892c7d02768437d47ed50bf8edc619c340be7bb1cd1d88b0d3d6bbf1031f738c4be09eb264c686d39b92cc7958e63c9994a84b61b5c412999ace8a9dee0e2a29eeb8dc537f63271af5f3844ed9c0d86e6913c02ed7d2b862a132f08f311aa92fc3757342d89a5dce8dd20d5792d5c60be9862ab168d3140a061489472f2266f297da357064833ef2554c49f8120ff40b961ebcfee1d0f8e7e5722f049485f72c502c9cc4afdbb70517f0fd2a00e12596ffe285d1b37eb998e0e89d756e9491ceb13e83610a3a66122b533c2c3461b3244438f5f7a7af8088881dfdf6a29fb563ce38c4c8632ada8e7e06baa2686dc6aca6bc944e5c14d6e432c4dad554803912b8fddb1c18a59a86bc452914b2efc1599c5597f87a6edcad33a7728827bbaad0a975ecc22b7748d7cc71ec7f51adc8fe0350e67dcfb31af35a8d7b72391642e29c2fa4b796ed8f535f6bc2b1198baf1cec858aac38959f83130af55c21383ebd57d364eeb0e442104004c1599060667ce5e1191e76a89199a386e5c4bf147206e7d6e598bb27a90b3c6a54cccacb39a0ac42bf22eb40bc8ec7925376a6c57d8eac6317578ac052b72ab773f572ad961ee05531cb95ee5a6d70add4176351960fb4bd673f7db9f698616a8dd41823f2f87924c40f131e6c83bc40ab1f92312f46ee86765c306cf4a1d77275ef9668d80f9d9c1ea0aa7b2456bbcf764e009584ef1c0b4b4c683fee3fa2641f48ccf7485a8356fb3dd22f848deefadbef8050de9c5c19e8c449c6f3ec2b1324f80a7d428dc44dbb966d40244c3af03bcb410a57ad1430615e07553a22686f1a62dc6cf090aaac3707ec5b44274b7fe28c7a3a298e7a8adc71e016944875bebb421babd2b64809be3454f25b90723e2cec68467ad2d14744b15de8f9c397a505a340e85998e207cd46fa18d76c46f458af4ac3821c0ac6cd68afb72c376c31daad1a2435fc2bf333260c1a82430edaf2499e7455a93b1301eada2e12365ffcd36a1119664d0c996318a3e55bb2c04dfc5eb251f7fd64f9d83f27ea6577d748e1f85248355ed19867857dc3383e01249cc37684b0eb8e891aa663801e4ac8f0331b38686a19f0d19f6e94c7ac95ec395962be0a4e3c8358d2f6d8f13191e164ad29cd1733bde8c31c7d8ab90366e26cc9a06707dcfa60bfe139a112db827778ac348fdfe26892fed61db7e9849a464e3aad561797b6c778e0688bbbeaf3349727b4670a2d0a08f317b0dc9c4b12ea85c0309d57e754d0c7bd5c83985fb82f776c968189908a8ca83b5944767c2efc3c5f898436de54fe8bb17224012a437896d9fa106a749d12aff657266276129ec5ac12fc7a77eb06296d2a2a876d931e479d3ea201cbb4b1b20bd81471eaa33786c624013e1f07577c2171f38f0511c6924078a40c2d55ce392dd2ab0885e29f4c06907a1597c181b933853838970edad7777ed394c491cde27478eafa5b7a36520aa0779261f94b957e83ce058298dcfa07b08ecc425caeb6c599a11103d7631e77daa0d9d3fc6f42703d57f2c624ecddd56b9a27b848de7dd28f8ed656f1e4decc95a8908217e2f2453ae50b5fc1d9352d735ce5bc2b538eaae25501d449d090df793151811443c64f28d19eeaaac4081e10edca4c4148e723ade8f7e7b988b732ba08b3ce4c8a0d655bac4ff66048148135decd7727a49ac59d82ad470b5479c55d3d8399b790ff033d3ef99d770e1eacecdc140480aeca1e2167553cbbdef2090c7592b40681b733b0a0d127beefd49bcbe8904c975a5ab8b1afe56d7ed7667b5cf92f537ad6972b876843364817c20400524097ac9b405e4b35bbba0d12355a0b54bd763b4491b2acd4e8e4fcaaf8fcfd398499d4c4e81ffa93ca07a5ff51a1540f178f43a931e07e1ad56ab5ce57a2f7dc3ccca114dc9ba8a6934e95f4efe9f3f76947909b280ea5fd795bbbc0feb3ad2b704e305cd9d8f37d178961f77355eedc9d7f77c58e1db2f7797eb8682255939293c3ef7dacd2eab46c4cbbdf929aac301a13f59831a88fab173803399d96dc216abb9f079e79bbfab667ca590266891c8a7ea4bc1724573e5c5a67e9f1341b5bffaa538e240f78da7733237999ac86141b2ac0324f17609b71c885630c90befc3b027a5f01e33979165ce2a00968c414838446c2aba76e1d7fe3707c742f68af21d30e23b637accc848f6c8df820a27bb4e94e5090ac6e008fde7cf3fdd5931fa891335ec8d01b5d6f77db57a87dc35d6701adf7ae0bf82dda6511c83ab4d7d3460b221eeb3d6c4aa537924db5559b1c6739040534fc330f5144c78bf99f5f4faa715e85aebac043e2529197a82ca40f65a8149a9447a9e58c61618600b0c5ab221420c0cee114a133a648dbc2eceb2894ffc329376d1eb3ce7039cf30ff6a53038b23c26c38739fdebc7b919956ca2e468d577dea6621a8d66b78075ad26a6e6d8e20c9b694698540d516ea2bd108625e5fd038b5f1e19c5d5993b82bfe16897c375322dbbca81c81cef6ad900f0ffe5ed02714c208a12f5234d78e32ee07af155ad1e1077a0d8938f426d8f326c751f6ee66c8f707e8493cbfc76f9ddf1ea329e094315a91ba9385e16c890823db0f0231c7f939a042665009d5edd8e48102c515341fa6eea33cc00fb5d82380d735b29f2eec3f61428f7b186d43fcee46b2037ad1aa6974d729848cf1a80dc8ddb0580c9c876def06d8f7642cf45263a655ee77f047fcd76171546319622bf71283f3bf0b519e123a85765779c8bb201e99981ed184e642f63aa61f9cc206bf45fa6e514bfc637671d9cdfba2891bb112a3cff438a6372ee0dd3e7d9f352ce52f8b367b7799e1f963bfe50638f0c74b94873fcd3d66fc1e342a8bd36fb8b88f33eefabb78eca4dc9c89e2c57aaa010f2140dc5ea7c86cebe2f8bf42a167d1d546cc80bfa9258c35af6efb1a090c293a4cf588e4bdf5c090ee7fe38fd7b5551e71e5ce2b0b5a50bab95bc4c257edfc94d37579816b4a2249ba05c991bb2ea02d047e480fc8a8ba71f48f344c6d20d140a64ac20184e45b4eea14d0953370c237ef0a47a7a2f22997715dd3ee8ea52f24ffe12674d571b3bf968454ca051701e411499bc43bb55bbd033f9b81d4baa6c49bdd49614efd20d58175af868ca16a9deaf65216abbdc3beed5f30b209e786a5b4c006f3bd27d93e9d78b51a1a2fb7f5160a0bc1b7df70952ea1573888ddde3d9dd5314b0d0a899a733eb48d5e6c7274667e362e4da6b37c480aa4d0d8730e66483fb1453a3aefad69942ac7f09d3c571b6275590938c541336a121bdd20722550236a9a5e4a37c7de628fceffbc260b1e9b6417c4295907937b13609b8585ebb8f076073abdcf19104ed80ffafe1b09997f115d987a552be5689c70fe125ca702d2ae4d807d5690bc2e90b72cabb0b61ad203b34c68df21c16b92bf8def5680b204ce327214c32e4363d5600f96162a6819dda472acc6441858f396385a16fa5ee52cc0f9ffef3d53c49d535aa37db2cd4b573ff81d74006677969ec1ad891082b5d18ca5b0b9f975574ccffaca72b805c9f7fdd76bfe3dd384dc953255a5b50b7731a137fb9aad42e77d3da1eff5a7b9eda5814993cf2d289bb25ae1680ffcdf419e073d38b4701021adb2019359bb70ff4cca930be7bb979a0678f20665d14803d8753c8ce54cae92feb026486ba747a861daa449863bd38cb4d5831aa6db1e7f404b0c3587aac8765aeecec686066ee7d11321574f04d3f3da571e71222ce07277eca7ff97607", "5e24f34a8d53b17bd0c2aee5369e3276dbd7e7c2ea0990f1300fbbb00831b76655aab1e2fd625ecd", "c1d796f1e651a1ee825855d80206baff6818cc8c247ee6ce62b7531e6e9ac32f", "240cb25aaae4d085bbb747a5", "319e968ad291ea5d4a057c38f7afa4ddb9c9565962fa1a7b231e397a268ad8e0c5030a2df09dc4f99402ddf2e0d06e753bf55e1b318b3e5ff0108de2328d3b8d53e23e08bf7d84d59fededd60d47bbb52736b0491f82c616eb5f779c496abd6499555035e4513c8613e7204e6bff8d06dfecd9ce38c6b83efd8d0e41f84f7cfc9ae07113237987a4b2eaa87f7e0a310155e282e57858244e9071712fa026cb781e5a4bfe6fa1bc480e534096394459a3d1354e2d9a54aac6926a60b388410fd0b53f7a3a9116292f37406369c22ea674418c4deeead171e00f74f5cabae5d24a0686a4bcd8ba99aea613a23edd0a019a319daa3779c212fbdca9d772fc3fe612cf178c2aca2aeaf6bce2433494027a474eff699bba95fc7dcf79ca1d77b1e097439a9050a5cc78e0b78bf2e7f50f959ea2986a59be3880519cd84d0a673acb0432feb1945c603e70748445c74600ccfec60efcf9e4d02a7df5f967de4b473f63b0b0499ff4ba350ec1182f3a0ac17ef9ae28945fc9bc714c49909a7c1e2f311aa6ad7652e22e1f48bb51cf53814a2125152813752d86c7f9468a991d0ac84b1a2f3969b8081c228b7f5760718036e26a10e211ff04ea323acdaaddf9b06a08c92ed663d0fdf13fa601cda45c416c2d3803dd9b5ca29cba57e59cf4ad93176c65c64507b1995d638541c90b381ff758833a2ad67b0de44c280fdfd82b3c6d4353ae30b33768863cd3169a2032f26e37ddd57e7da1673cfc7375bf6e6792495a2b434155d684f2a6f2b919f944469d47be5aa7da74eed69d871e6f65c3ae08904a9ad042ba39905188f0b9158fd14094bd6a408fba6ef57566d69eccda86bb54cd3ca7381f51bffeaf8bcc1ae8df91d22c359888e21b70f640d6f3726a34e6100ee269124747f0ca05110f63deee07e3628bd6aacf926036ccec02c0b6bd7259db52ea8b7a686b36ba1d0296c85e43e25d72ce46c66a1e646301dafd2f4c502281e6f949011cea69459c026c65bd130d6ef06be17b23a9c9a84746e39d017b144135025ac527c1e653f233770cd68e9f232c3b623ceda836843b3e9ea313cc6a57d28ce71ccfb7265ce73b06bce1447220645e6f66caeb06b55129b97c8dd8db54c94d771504d24cedc86a8ec706a9f7dcbbcd7fc7cf38005b2913b1cfb77370bd23183ac7b5ca5135a2738cc91d05b2b22640469e3daeb6a7b0f14fc6652563663520f7754aba624a35e5d24529a6ee9f5ef0d019d83c04f5a93a38b68cbce0cecd42a11aae305475806326aebb4f673791f50c9f90894add51a0fd7c02807efd8c1bd21fa717a860e224bc9fa3f40975fd8d558e4844a09f8920256528450d77e546604e2ce2d38efadaf39a0ea3ea12156174aa8a20481e6c1190e448564675f9ca60bcef37cacec5aa218122e7bd25b571ff10f54979d62018b779a2a3d5d7d6cd56ae31efef2c844ba50ff9da88eba7a8e0d9fc5388a805ba4ad35eaa4798e395d2fe112083cce2f11cc850d25ca5c6e60a9996cee4789ca99d519daedb62f4fb1e535b742a35d71d7390117e93821ff18948a78c1fcdcb90a5f1211327d7ee0663ef16ff446e0e22d8cb7b2d3d05469b1c02864f4a87e2d9715f60c9e7be841e308d0a5f6c50161a4a0464aebafb88e0d2df8cefcead93c9623106d5518a9852f320235594be10c45bc0cf06c9daa007100ff97959357f9be8e49c870d0a11c884213e266c35e9131439fb3654fd5f1abd1e778ccb02b8c262753a22653a09272a0c33b6b2683c9045e8f967af756b98dc1797ff605c64ac5bda8252e9ebfe0e4d8d7ca754fcca5e3de3c4b63678da095281d76d60fa12ff4ca818825f346b9c4e426cee16db5818d78a527a901cd088bc2983f9b83430b50683018996996717a1738439680b68e3f61cbdcd0f0e1a6b436af8fa05d3ce2228054e319bad1dc6ac970c75313c552fc1136fabc302fcd1d09ef1b9138d18133a772cbd9cb197ff58c6e898f9e83e4e27206f3b15b6bf2778aaf9fb38e0d50152f8dbf5763816132a04b4b2e9639584b3dc8ea6d95ade024f9497944200ab0aeab206ef099859b9240aaa15f737c1e0fe6d015d04f47261ade4928e3c2ca21d1f5ab4a3f571f2ed92ebeeebf2493e6e39f0063ba931e165384ee1b5081f5f8d26ec24716757037f5158d35effbe67009080ad7b0381292a513f312eb28328cf5ff47a6599e36c14277c3eb5053c5aca530ff5954c21c03fb3fd5fc0facdac36dd819b0495fde421411e0440991da0cc4a20d294446115c0b79045037fbfacfeac574da3bf192fec4bf38c27cef71d03787430223b6069ba6d9273ec8679736a832277c657862ca791b559a5054ee8c7c07618083f75480c8aa01cb086c7317315911802e6cefb15bbe20494b14d97e3a885806db775c216dc15949e3b724f7cbb30bd2c46bd5a2fd6132352c2b21cc2b47891dd9794975f70a6fa7a0791ee761ccf4c263f27f64790826c1aa656c39483e029baef0855935e7e6c133a4035a3699925fbde131ca62948879373346af35bd7fa52b8d6c3338f213bbd9c79977c0d710028d1d386df614c5faf4a1f8fe5506a9af7059370893ff6d07d91383baba67a617b5d829e0e2eb20e541ed5c34be7ef0eaf6c6f6f52d7ca01933a2a4e8de46e422dc95161ba8ad354f6bc7c8e4cf8ab5e08607530147fcd7c9481afc621c5a3230a05e2c4db79db9e1e73f43556a8e8f0dff7ffe420282212f23d4c5f6f8d2febe129b9fe5ba7ddf27f72ae898a4eba270b5d2bb3b6b06e38c546ba80a9b2bc46097d0b47db5ae72485ef2c6419e856c33c2d66a861b9d474699e730eb8a8992e3ea9c1ed74316687d5d9fc611189eba2aa31af5ba8e81179866dc016bda977c59c595e40001c8ab3a4a44cec00ff84c6dbd9ad4be30bcc080e69b9398089d6ea464a70f536ace3b447693301c94850606d0de1299770b5f45e6d28f8ab83e3ffe52178522eb91fdaa9e4a696674ba0f52ee18e960b04415782f018d67479081b1bf9b4c9b90de026cbb66bf7d9d12cddccdd9b2c8ee2f010892571c6f0c0feac9555c71bf61f9cd69553cf7fc2be8d058e0c3430e134adb1ba28985fdc4f0cf71bd3cd09f5f82f303cded0de62f98404477bdd0a846c6c51e3e82ebf72f475afc8e6388aec57206018ba2528ede194345cc1ee95cb2023793f692f708aac3c9e8a682af36b078f5d6c7a3ed07475e9fe73b95d1eee048ab898edfee3fac4beda45f03eeb64b2128f6df9453ed77c6010e13c0270c068f704f49e62fb7410be90ffee47584ca2efc5287dae1f63bcc1819e7548eb9f0d8a3182f9ed00da3817255a2ff735876b75cd21cb25e86aa4b2893f9e5089dfac76194563f9a14335dd37ef06a501c89623caaf6feb4afb792092dfed515ba7518e278c341834a9dd17b50a0fc860b62ec621b69408cb3fbf7d4ab88a3e367fda84c82357376fa9b1161b739361c313b99dcbf4122f3870c8175093298cf432174217398928983ab6cea4759f18e7a21d71fe1b0f3cda05d241e12db0818b8763bd23d958d6e52981ce8d84cd6d82640d2000874a53c0bd14949ec99e48ce6c954ef0d08e6e319de5ebf7e142f25c0f50ff13f6acecde6a270c8d8de05ef4c310ce9e92f40f6f2b77d6e7aa3f056d4a20f7faa7cd0b93d82e3972343a50a26ff462caada10621bc953b73913944246d2a4da25fa52cc6ee1293c436ab9031ee2dc79cce39f139f44d473c236731257c6f65ca4d383e39cf8d33923afea3c80244021d36e0ed43230c44e7d1a1297d35464861f9149d869f26cc51879027169803e43c898d1b4a2a2480197500", }, { "2158abc2472e1b9c061da2c01d0ad9e996fd687cccca331fe8a2baacd12c06f284b1b5cbdfd067e5ed09a60a137ff4a97c5c26482659680ffb22bbcd4ec1bfd272749e52440537320fdd3c225c30ccd98cf221b34b89c247ab7d14f93ed3ccb0486a028c6f3abe7e17fba1742b6d4db85f6e6baaf82df1a3aa059de8d9699821d39bad42d56cc1ec67626092cfad4a2e1cb5d814e2cab78ccf5474a8bd0dc990a877d37de394694af6cadcc57727f393dccba7bf955f4b65b3c00d71cdd701754ed4f231685b7b5e2557239d7e16305be2d81a773765dcea25ea5bf2c15d670f3159409ab5bbf8da121c779132a8ec1480068cb76b68a19152fd83135aeb228b446225f91d1ed4303a4bc16cf3ad8173b30d2a1e75ccafc8c933db231efeae6260d45c7ef230ae2c7b6f986f1c19e2cf260ded9cd99d64a2d03fc5ee3d73509e47ac1c39dcca655839fec75517a9243eb611da8fae3e317e7df66cbb6abd59b16975eb463f509e784e65cd660ef1a4c5027e54b1bc862f397c9cf4e6594d98c2c2830801d3a679220b46881a372cdf3aaa33eb66b91a9f36b6941c0fe1b4d2a437daa50b811f2d8c65b5a69de185d78bb9c2f172dc90a89324c5a2067974aab14f4fbcd06ee95cd49e03717f88480a410afbb4e68b5c79b0211cb69b90604cdfaf08af1ef10cf28f0f630e97ab18d9b5138d9b9ee9154e0b3104a6c164f2a114fa5032eb5c247a6b87880332a0dce7b36982515297a05dc8a4038a09f52b1def7b4fdad8735443fadc462c7c22132f8b9581de2d213bf5c53f7fce34aaeb24263afefead5341a72f88d3acaae6db367c5c14a97d4f9e438e1e11c3c8fde7ee37e5ece5382e8c68b660146046ef96c24caa6bc9fa0a0c88281e4bf01b32df5218cb3750f9c4b8af24cc106abca62d085198d14ba2ded3cafc1fbb17519a696965a1ba5f65720e893f1ef3fbc5200316b9d4615bb23426ae53e1c5a57b2f0ee0d0c83f353b4ebe7a6cb17531d278478b4ca8e6ffdd0cad30ed73d568a2e44972ac88a7e7d665614316d674e84ebc739b645a9a4166477254ba47bc5c2b05ced88e75bf64da21a7f1f71cd946d84de13ca77b7e0dc2f0617d371ed96323a83bb11dfa16f81bbde913d9c259b10f3aeeb6b56cc4775c25f49343cef667763118932c2e8b47ec745ac537b37746ed65fda2d1c11a2de60ec02adcb79152e8a9e614d8715cc4e6b6891d6a0063576560fa3621146308222432ffdbc351c36c37d844a934088fea92ac54920facf870a62e91ba9299dcb6cbdb918e2d54fb642c3f0d60489c4bda489f6c584b64c8f19359ab25f388dbbe636c4d90c048f5ed87024dcf9f98a9e738163f837a07750d61203254a80d120c795f9c3aa791272f9474fe330da81a45be5ac838613d46c25e781606862912ff88af393040605fd4d55d07e2052227c37ceffcdd2d42a08bbab69140dfa4406853799893daf768af546f915a91b81d0da719ebd45b8b5f1641f15621959689e810217bea18e3996c532ac6e4e2e4f289fddd5e5968bd6fa9aec5ca435c532b6c74a7568c8aeff9dd19bfc2fba3b484a191e2faf9a069a24e2e6d928ac0bdf635644cc1ef3bbacc547a8e4f1d42d4bed3b6b8cc56216fa550dc37da9cf4d1d1591d9348594d14adc7a3fde5e5d1a3b9875c85de7df483cdd0baa86dae793e0796d14fef1f649de6079acbec6b6fa5f2cb2bd0481f5316f00dbe5dbc379bc3cd6d13bd8c775a727ef43e6a5fad1051783b22c05a75d64a8394a73fcb430299b015563c8cb0ae0aa4ec750399855411c076d21aeca8656f3d0cae084fb0a1ffc6f73b52a7ea5d4bd6d24e7057a3811719533105fc967439a32241f2d3e3f299da2deb821748cdee1a1c5e71bfdf88d833bade2f505268f375a9e6488cd8e16705cce91d15b60b2fd269a19148296a7be348aa349a12270fbc0d5748e538afeb0598081a4f1349217ceab3c4141d40f765ea2bfffd530fb9606601469fb131a44939be984c07bac8f26d8c068accfdefb729eeb47cfd6ddc646e22031f53a7698c6501d86cbba05e282d64b2f962a1b08b9064078dd1e3f14006f45f599bc8e600cabe6d855fcbae8c3060859202361d929a241f6c0711ac0d050b67a1d44da19e0b0e236adad1f60a327c9c34b2b9c64cdde5b8e4f664f2fc70599d44a63ee2b14d051c27d71231098ecd3d4086038d63e84547dfaa39db1a92785e38b640ea0345062a1c185b25a72862e7ae6574114eba592d6492087e2580dc5d361c473a614d647e66c0a30de806f4976b69a8b92301e68794ee05b96ee116a5fd5edf5eab43dc1103801eec861383f17c2bab9f2d9126c1802b7aee0c909309ee72679ab644abb9c4caa54add283b5954e6f881781e42f849bce6554c7a5e3becc5d5a209805ccd4a0117272a53807e3978ffb19641a9dffd9034490a9284f658599961daf52f24f6464c2099cc9ed3459d84dbde2ebbdbbeef25c882a9beda03573bdd4c6a0143b14d634a1a021d5f9fa23a7ed0f5598ee57e56672814412b6c7c08b8e709fb98575fe2716100d000a20a7e7200d800e556564c7e6a8da9d609b18ff0bb8a8812e96b834a6b534b0d5dc97f5da17f42f8d58e763f1b201625d1a5158c2f9e9e190921637474ae81d278002f197f7211540088931ca8a941794e56067ef4a497fdc6fa713aa9f20c21f23c3a71ae4cc5aed459ca7c020bf55162fbcf56a066546660c5a009b8ad2aaae9651c97b1e145853a10013d1bf68e7df25dd492c328f823ed982da54557502ebc6cc56d4d0bf2881bf3c536ea53b4dcb0886e73b066969dfec343441b9372d7ff38454c4337d45e2b999415ec48f19cd05f0f80c5a61ec369610784f47a5cf3b2a13ff5d8145303ade7189a300936006846812dec9ff15500f8daf47236e724d72619af3a6cb3e854cb8284d5b8843dfe056beaa45c40a4541a98c7507feb27a605d6e07189c8c5554a492a03ce6701d3d2ec782e2c1c8346b54a963435bdda3a93bbac1d837172cebb9cd18903d25cd6bed404eaf18730a6d1c6da0783b5411770ed34f35fa6c11a4292a34565ff1b23d4200ec5a73e6b7905458088fac19f6aafd35e0e791f28bbb2cb0117ca1c3a9e3c4863e487ce5d8c14dd140e9eb4794d87d75b01f683bca84ebdbf19dafab716421bfac9e95755fd346a0cd31e8520a55c7ca652ff63fb4e20ba67fab41e11f7390bc02363162097802c6a9eb18b430d07ea60064d5b546d15bb68cada79c113848136e797577f1783e9b53574f9427be3a28230fdd69d139205dd6c7e9e7f031fb6eab70d69ce905384c5c77d084360aac590a89b2dbb2d339899b13619b455cf9f0cdc08db6c5b5f3223dc3a663ce42bcc8cc6f947f42cdf8dde15a6926b753177513a52be95b1f0b88d2a1ec90e49959b108fe204bbc29199d7382c42ad5dbaff970cbd2dbeade54bd70415e54daa805d396361f525f38efc2bba3fd818f9d7af0594dcc341c20f18c624fe13ce7e7108e1d2fd06c58b03f04642c95e3ba00d4035ea0476ac138f72378d85050bf60dedc90af38e96f67fdc38483a73e847b41d31b894ddcb234f02b0d507bbcb15a8941f9c23b592a291cbeacb3ed213f2f044aa842275a7717757467f121294bba6b357c969e96bfab455c6f328d9e5181d909c3f0543b17d9af7fcac099067b043be79aca8e5a75c3a6d4f6246357a63c516a3ca595447f34b43a055d3070517c67ec36e636aca9ed71a001d4f7b81149124deeb7826dec3697e183d861d544c9c17baff82849d599e9e77ed19f801aa1ce095940674576ff270ac788d00c429187e299a03c6f3a1646a8f7d6290287e70bd1276316ae624da929c67936191abdfba45e2803884e5a3136205a38a841448968a7900709dda033a42969bd3417a8d865d0dbee1f261f4556797dfebab278136a182a63e5ca9789e3f1371808efe06eb0cc5ccfe26c0538d573378035afa39fb7cdf3ad889b277c8c6e84954e74f3ff3140bf13bcb45c822784125d23b5eceb73e", "088fc7ba068f80efd8d4d62813c93c1eba77e9ff400c7781314abc901873ce200295da09245bf8fd2fce254397616151d94b511957c89a881256182ac9e64acb7b25d4a080cc9daf9ac2f231235483fc9fd415f69caf7eaf0597", "78d5f86b071bbf8a185e5e2d54faddd2a9e26983b1e7a74be0f0b979b9f4af31", "d9ce7d249af9496e99c93b36", "ad542824b49fc520f0b7ff8ce2bff8b3d47baacb4a1c95ed56a306483aac551fffba48e8a8f5e4cc536e9266182f6811d070fb9282f5c542cefb4993ccc7044b42cfd6fc71793dc8dd2de23c630f9ceaeddba45efed9d7fca25fcb07d193c000822478b19c2ee9fb31760cfe01475ba8a003db469d1130318a79345a29d054a9f9412dca1edf6d8f1498af5bb6fdbbd3d5f9a244ff176f62742c53779291ef6294df6540d841f4ee8c7c58fc8497ba74d9cf7947add5373427d81ae928305b93dd26cfc65e63b0ed0812ce759511bfbb10aca98f2abdbc9055c4e5ab82637f6a965bb74f592bdf11118b8eb79d50331e76cb4d10c6b4428cd4ec2ef4cb727bdba2b5375f5184d77772d0f9fd3a3c579a4a548b9c2dadc22c805ae959617af49a514b43f47af834313ed2e4d1fcec2c4b9ea87f328fa3d23129a36e6c54bcd08f7e30645de86e98ebb11bcaf99543503eb1e024bc9fd51fe6bd5e6d749033f2452cdf28b3d0f8a304111bdd26dbde641c02fcb15dc21b1a9baac5e86d35b4126ed1cc8a2c3c2a5b94c99fb9b2008daf1a0c090633bf9e31326428c75a50e821b1e72a6504c9d7bcfcaabecd929163d365832e8971f5efebff99ee3f5b95f957e8904d05b410936d8a81c60b4947f8605c58e5b727d491995c76fbe06e556c8ab5cc661a0c09ebc98d61010050f68b31fbe1f9de8f6481b2704204b0164d8433ba4dc1076908c782826e9b555e8d608463581099a466f92bfd6ac9796eacc0ab771a3f11d03806b0f33ec04c69cef6b87d58c11acb5d1374450ce61ba159456b915043c5c17cb03f0ba66d027105bb6fff41e6422f13e2a466f073358bf68149a3b577cfba7ea08b42f83fbc5a2aff17c5ee7dbdac3ff97389f5b8d1f3750e5c9be651209eeb9574127ea81bd7619da16d1cfab85754883543f6474c8c0cc9d5b80e34bf8262d2b4798f9917bcab4b880339397907a5bafe7d149247fd735523df3cbb17ae5e298846ad3bfb7d4f902aa549b7667d3ea945b002e7b209bc83842a7b120d6d27ce80631404371f31d1f61efc5423e1822032a1cbf4fa1a6b6fe79934a202d5add8c6e3595e49be3dd9553a569521c50e9653bc684ef2b73c3526ff7a0843fcac9cc9ecf46e63df5b9328a54c576bd299a366bbdc0f83a9de67b03f1da16244bd6d52e7e4b52c4ed693827735554b05b3a260cd01a41d7c944d0b7b58ae4b0eb052da34bc22b779d7ad46f90f3d4049c097e0adeaf71bbb30ed24b32ff5c7a65177db77492c2571e9cd99f15e613797e319ea7377038d53b28a4cd66a697e5e8f84cf16bd0f0430b34826114b4e1d1ebaaf2939dff7f9f4ce7c0861e51701c42d9cc9e871018b447ccaf4e402e3d63be164dcdf6799314a389ada8bf5e51a35148acf627e51481b9b0e4bec09c9e6d59229721b151fa9adf8323001fcf33afbc9a949643172f39b0d10ef57b37973683fdd9b9eb46e63054fd05ffbef889ff8fc8f251b0ab41fb00757ec1964ef373fceb8f6d148a7f7c89944b3cfc240d091601b23046188ba70a7cdf7b6f96eb93dcd3d24d4aebdc4a29a749bfe3cf5f6e1a025b62982ce188e6b57245d829c9fc1dcaaa5309a8b9557b8824a78eceef6e977721de4065b474ae008642b974001a5565ef5fe4250194e8b861cc45a8691c461817f10b646fb526bf0fe7790bb0db29d1356e8c7a197ec78df8310431d632a032b5490c2a458eb8d4327a9679d7e8ef8739797b0e820e2c567ce3562592e862a1dfcecd50bf77fcfcd00518db65ee0effb9eb3655d5d401a4a47808faa596d17b316f828cbbc14a7e018a0593da9320140a752f3824b5fcb66aa4c3cb94366ee8b821b09e7bea2c04ece15e8a7be1f58463b525e8cfcfc3fdd395ec5b0575094313557e632d0a65e3099e3c653111a5fb4f0eb2aa710229fc055a2bfd8a7147cbecc10823f1244fbb6894af1408ff9047d6483ef83573b5421b9798ee387dc38f166b11de6c33e9785e9b3d9d28bc24c37890e4f8f8ff24cca298b44d6fb1c6aad28cc634a67dd427205285521a172c2a4884ac5b038e261e38faf0086a02aa29195713cea335c47d03d67fa0dec7a8cb21db741519f5f0ba0143f14d71e33d82c75d6a19b3f7a42e6c16d762354daa2670ffa55bd400637de9cddf9e7964a03b4c8956f36bf54d89cf16de23e8c52957b52eb4572a11d1398be72bdb129e2c1abb58c65cc291bb7b0d2dc326c6125a441863a6c92de0f47a355222d58bf10af0d297a86a98b4e933a8f844fc7f1bbc8ba77919dfc50c41219e3db309b92ba056349faa758daf360b8ac05e43fc2069cd46e63fec399cd7764b111467fc65407ac06f5f84a3179930f6215ac5ec906146c19e0d3e162e77a2bca3582128284282b251cdcac03ecc204266ac3a9cfe8d8854008baf89c0ea0096a400d6a0d2f7c681c99462cf0105f7a3dde690ece0438fbb820b9c73c6cdf6208c336831101b904526cf8ac331d879d71615d8b1f750ac7f0ec692d97a5e21e17e194a98c10172b5c4bc1049a8743188ae7c4d70384a7e68c1353aab7882bb91aa383821046ed0ebabb4b2dd126ccb935f48646b299095cdb71ecd5cc402e4635a3f7a3c8a6f54f4076ba028dedb402bcc92f5668dec3d91dda7319f58382017e306237e42480ee2c1f5930564cf16fdf37a3434585336b8e4535bba87311cd47722b9da727250560624a5dde48a2090ee44592d2fc06edda634b600fad9f843c6b2eaa0697b42858afee8191dd2a31e5685bd104188e2ccb057dd0a8d4d1205d7c846f5b8ec0f06bff61c7f47ac4da30e1bc80a4e95af79b14a83e9af2e0f195cb92d14f752a5f12ff90a05765be453075d799694848fcddb07859336ec101c8052bdc273d4abc313cfb351b543fa340dcd01bf32fea59881ddb8f33c6023ccea70532814ce4a2d0c66c846347b86c29dfc34f6fa4db298911d4367c59939020a3d078194e6a3a3c5126c24ed182398468e77fd61a5b1271f5cb2a97868876954c3f7179d6a045f4bd770f681cd82216cd2b1ceeb4e724b3fddeb74481e662fbd7f5dd45bed6d4f89d21b8dd9c1009ad2b0b16954e97993ab8f3fdd9d61f8db102a945591b4552f419971a9e46a792dd8392c8d9502767c82d9b4f69e66071eb579859e9ca070cad5fe3b7fcb77b8474926ea991ce7ad201421f8a79c051b762a066027ab2b9595a1c97ad57f3149f5872ed4d8e99195d47bd3c03bbee590a50a99d8048e912aaeed797977b52f0240a6cf2c865b108456881adbfda60cf701454da17bae879cf098df808f34e50bccaada2d3edeb1aa73cfe3c512d814eb33897b6ff9d67d3d682517cc333c3c2552adc99860b1f0d1076390de9f84fcc9e802581f77e14f5254da01831c70cb8581630dadb44209377d90447a1a21cc8a2d6d897db62d8420afbcc6ed85ce42f3281255bd43e0afd3e86b27d3b957104ef54959282b0e1b381a26f16057246704c7888126055af5a1f494540f01897e8781e1a5c0193b7bef4b5588d0e9b9c8de74dcdb63f03f7b15cf48fbb71c7c3bbe9329e3d326988bad7d0cb85537c1e0b3cd88f37a3c7765f548f99e495ddc29daed8c7f15dadf2e5b79def91dbbea277c51a5da250e66c305604bcce4789ca2df9a10614d72824ba8e4f179f35ccae7119fd962cce13b282f0f970ca6c4776374c4bc438f0de98aa04fb3cf23d2c6800a4a666c15bd20c486e88e688ff9e5fce906b4ae96ec7c3388d7567ce6c8bc61f6d2373b93f9ddbb02b384084b3f28f54c9ddda232d3084daa5fac5ca356ac0059f2fd3fde5d6a9516d0954653b699aa986f70733538e19721daa41329abb95058450e602eb5726ad5a8b81aa474650659c6f7f6f53f8a6e635bf35f4b1191e0dbefad3be756c6141c7d55f007f4fd131e5d5eaa120ba31cc32b8d4c69d4fa784fe0af7dc272898789c774e7995cb252eb6c8e8053c9e7adb59c27f675952d161dba78bdfb15859fdfe4fe4a44c01efd394bf51d43c600aa9a527d9c490971e188e28b980e77a9c6ea0a4ef6bd38d11b47f5745ecdb", }, { "9cd1c25b5bdab9b9080db3e5e05dc749e0783087c310777d89307138613bdffe0ca259677c13208420d4690031314a11a97a986d8b0fea143f5b4da0972c9ea3cef80b4b0b2bcf2bff392c306a764113f0d9807be86a9027c6ddc85d096600d85e0b236937f295362bc1679537a8a9278229a36a9433925a105ab719c0b7f11fc31488fa071d3032de97c81540713dc29ae02c2e13be8823183f3cd9f72ef8ba4280b4499ee47c7c7c4492bcb5cf7e4fafaa7ec26906e58146215a3d4f52f792d3abdb718f57ed0b9b7fc7504e45a0fdf01ebf5924a4da6ac635a715879ea75a4983cbd9dab9e47638acc687f16684e184443aa9e81513ae4abbc4d1596b2ca3eef77cc9b0603fe90c0570fe6cf4dff0381a99212fadcf7968934ac1ff7664ed6ee0b61e41f5074dfb774b676c2b57a445f1c5749e95ed062837c727ae2c151c0ccb3a4dc1429bbcb9e62325117aca566b8fca0924b70f4defd7749d0389b90f55f35d1635f8d2efdef514f06fde46db6e11e492c8f4dfb7cb5454cedd0ddd32013a4836321a25110f3a017f18475a86583e192132f8d8fd4c2dcb2a3aa95c3be3a57216bf9727cfd1284eea6fa870c8e689e91982c116ceeee2f8298b55646efad684b96eab883fd3d629437e9a0b6523f47ea5b59474a4766ccd01c13170bb08f47576a0fdb573d4dfb65279c1b79cb535426bcab60f4022dc42e40db29f15a6148b461241bae62070389932f035e7257752ef2d6130503d72344b24d360cae8ec11fa2dcbe04d3b18e66d081b552e93a71dc0094d1046bf4491e318f2ae00debffa0b8ada58c5f23e33fb598829ec2f46ad3894bd7f530210371a02e51ae0a414eb2eee43f3e08126dbdbae04c7de4b7416df32953234a6694ea84e6889f27c74206ab8144a393a2614e92adcc77550dd54827387b619f004c13f6c4a31e8bf525277669db0a0c3c589eda15063f12eb774a13e2aba2f2f7b6e9bc69f8485f1d6fc5773acf83671812412d28704003e78a17da25bacd1d61a6d9cb9f121abc71d023bcafa713b7c954e4e1c524e5bcaefd86c4a843e209eabbd579cde0263fc059ec6ff10017ba54fc9c2a1171d6b06f5d85079167117c12e6e5d0c71c008765fce756fd0f1141fbad6c1d2f32cd8e80429611a9a78dbc8e738d458f9ddce58ab43c77b34db9befb25cc1a588998e8dc2efa75c6883244fbbf9a7b4d6750c81b8d3fdedaf98dc61f49d067c369409f984b155ec347a3bef73e2a44957b0ca0f84c7fc335fd89453759ad0ac2fd9a5b38afa9fbe74daaee7bc52301302fb2286c21fb922f74d756de84519171fbecaa9b869682d431614ff6845126a4034f10253aa244bf89ab8e0dfd1f7fe8fc1a8472a10746d26896c8ece7ef80eb2e910069435518ccf096caeda63ad692455b04e6525bb8bae27197ca5118a57fb9a5d8fcfae1b9eb7874d91eafafa0e4fab5cb4d0173f7e3e58fae369843a641e98f3ee460e8cfe95d98f7fd38a8d2235e9d6050015833e6d7d21d7015c3b1ff42f0d3a3d9a38d373c8524752e06987c9408cca550f08c38c2a9a8d86d5ac7a04bab44254ed15c7b5670e0747788e11b81adb0d29e3d0b50d6a429340ee0d44a8c286fcaf9bc46403d26b4a4af95b021336103c1ae0f1274b33bb8b21c8cfca8a56c639f18a9df45d083fa7019aaa14d1ba50eb9a4112e574cd70969640602096265a87b1f77c0e00bbb501555f1626196611b4a824991cf10ab2874a12a8e0390267eaf9e3f8f99eadfbf40d111a26772cda1f50743c417eeec9c80171a83a730f246cf31c6691c96185d672a0fde9ccd7091c4b455dc93326913497396e0a4992773caeddcd783e534eb0f34b99bf23a2db6ee738381b5fc94ff603be014c507888ff55557793a8c5439b11dc5a347f35a2666eda81cda4d1c3a78fc4f3df3c7bde91d05524791b67142c446f60c3a4022912ddabdf817ca3280b671beaa496c935661e5adf39c1f4650563c5c807c8f21aa59df926199c4e2404690ea8ffd7dd65f637452ff93995fe9c5ac7a322b9bdc756b7ed6f533b9357a4a1ffa379dd096f144e9e0d87330c238ed3c6b08c8478e23b65518ea1e4e64585e5e9fec2f26dd7400ce4c73ff0eacdc3b07e4f34f6316f5b82fefc66e442ecc92bea8c1d58635d644724a3380e71fbbeef4bf3e57c6240ff603d65447f510eaa3c9ac794fd24f844489b7c560c7814fbc307e03f6a213eca5ea40fddf51d8731b74ec5b472bdf8ba59751065ed2461b02c41ef96622e60c0d26f9dc78c24f94372bef7e47cf09ed565ae3a52d39b02ffddf1953f1ff500f1659db9f1c2b23534702c19ec1cb7c18166fcd33997d53874c7cdb4e6c2b4d82751911913434e48b37a61a0971861187e5decb7f5c1ef6988bc1d6f7fd147a623d8bf361b0d7ece88df6e1ff8d037762d232e22e51d8c6ddaa9dc597b23ff9efbbfd416cc53e5543253732a23aba151cecf73b3ecff21c6a9fd1f24211fc21cde9633aae918ff1c6b72468f1de7e0ecb6539fa353c069fcbe8920dfa8e2fb86782e3062462f7eb2a2c441bfac21ab62744b05c70b6fc3c9f8e3a8a0c5a4263ed256a019861ecb28e20ce78e2d93f1a1def669e9652cb35d105bfdd5ff2313d27ab3eb00d1b628b4c20f42efa23390802af96a8f261ded3678ea0b780e1f4a88d23588a4ebb058adbf9a9c62ce2ce2f8264c874c697482e25f8d5a6daca4f57fd97d23c42d7b71ec150d4ee33931db5f7d63abe7d72dc936bb23a367c798e6a01509644284d52f9ae27d7d1bae597b2cbc26139354dcca0fff6d76c6065d661b66ca5eeb9f8d85810a029cb95b17e5173ef8ab92d475a1d3e21799e874ff04dbc962c668ef4be9f94d85b2a99d97c0db8f6b6d63e00e36c325cfab9aceaf7597113bff0086e8fad36eac7c0b443de6d3a8533789616d4c863df7200ba795a3b8d0a2b9568bb32af95fa604a3e3ea778c3dae159e1b612458584564ffda07b8aba9710134242b2d83d23127b51b9e41584c56f667b71bc01060240f3a2bc7e5d438e7095c1236e0e468079a83a5dbdcf132d258e9ed18f94d3c098867d06d3c09544565677b454be34ce567f1c143e2f3153bdc0353d65090dfd8f7af4633b89a781e01f4634dd7b0323ea1f38184e697bfc39a1299eaa278c39a2709cde0a346fea53a61f211112450b318d137fe68f6c102085aedabd2b045fab912da5c58d8019239f3a44b18f4fe30c5352e2e2bf030334a1dde1dcd23178636f1e38ec9e42102d8c54df0b94b207e804eacab3edddf89fabda6c8e1bd4e17ae31a57716c679ee8bc7de4412fec3934c6f3e8b4c1d1447dbba0fbc775dd3258f789ca53f1593cadc710fef6fd282bb41c0468ede5ad5b914e4758b4148b0d0c04c75ff6208ca3e79d92de8abafa4ec70ea7a4e454f0759337ce575c4954584e2bb8444c34e823d27b025d25fc9becfb4391df9882452bca0373164cd76e9af316df3f5bb7532e22557b485217254d5ab72ce349620f03758219b259784d4c9f1c7beac3cf08e624742e768b53b3d60ad0b94442c847b84a516a93d9b7d068c44c43980b4c7e2fb0ac964bf05a11fb2adb4f6d938715dde88061b238321afc7e5e84799b02a94baf3f879f89a98ab474ca12085137d639b837ebe069f6dcd8456141d063eb1c032aa392a44d1d58b1e77aba38a280625ab84e3b123507ea7a692c4acd1756c031fa52d637703ee957a993804c13e296cc20c1de55c9b8c032e50afffc51c02e5c12f48383237cdacd005b09243d9fe05e51cea42b77645e5c6f4e48c10e671d216b90a48f0d8f5c1dda553217f5126646d11a62587eb0a4ee0efdaf0d54bc2eb04cd34f5a529b682ce09a34d5acab2c8db58ed6244f7b024e68a14bcd5d7a7daa4dbcf490485cbd38e6f20e839d2b0142b9d766f9527937bb1a737877edf6122ba306bbfb5379243a6b22bdf85dcf3b079691f0e90b28a4259c1c9d8a02afa5b5a661a0f9dac52435e7d22e3591593d37eb2e10f646b51be2d1a96cd4490289ef642ad93eeffd64d7cf830d60dc4a98c768a9bdbf6ec9923062ff04abf19e8b65b95494a9420971018c7e6268b8fb2021a4ddd103976333fa52389643c711a980664e29a8479aa9c4091c2cc2074ce3ac1ab4afa217d39c6a1", "c22add33457539a957d32dd07ec9110f8cdd2f00ab6ac256b4bc7732f63dd3b867b0ecac262555", "e71f9a3dd457b4064df1d9055889f105af175a2d10dd7b8729da0d0116c2d9fd", "7df9824e774c5f86d83cb5d8", "689683c9e7aa9c48b9fda0cfffea0458ea0c3dedccd21efeb06126f1194780917c9f4f2f44b1daceec3f6b1f75506f4169bdacf12c1f65958784851056fe0b4b42a22aeb043ab35ca73747346ac58c550324c4b849a404c94b8860967b6fc58aff25dad0556f1952c045b91f56ec8eebf6f552c18b2a0641c037e6c6538b289601e1fd5a7bbe7b6e0b224124fec341bf77615183abafb52b3e30082a0abfc2cf224324338c132426011d9f800b382e6b834896ea48a8247f149d92ded7e69c7800096076cd2a729a1fe41c70dafb1f855ffa2ffc27b93e2f5f6827ade7118af60730033675d84de9cde6c260d3d615a945dfe0ed25f33b6cbd2c0e204ee919219d85c7536f4700f06fa61937f8dbbe9bda88db1f4ba8a8d195cd385eec62edd9ce673880800be9aa4430e5c10a5908f6dd349af70f32b32d8db38a7d73821af47b993b622bf168565082d07e88fc48231a440469adeca59263302438ece96d89de11cf8057454d1bfe8e4e36965a4d82618834a0847af39dd8776866d9558a5cff79a1cc9d1e3c22e050677e54ead68b3cf0094daa01330d41bb66708a8bbb8a196fae5c77dc6774629d38905e81d97c5b16d755182f687a8046e55d148419cf9c12139fee50c0533b0f04a805723ce1ea5595fca5b668e58f6b3b396f438308372489b640317cfa3a79392cf6d1afdd8c3359557a83790021a4eb418fa189ad15ba9be0f74182ac76076f102ec171117a3d16ca20b4d200e03e54f1f0ee6308e463a148c0c85aac3ccbe5781cf45b53a313f7c9975a45d1853ed9104a860c08634a8211b87500b5ffa3d8d9d56f22256d485b9b45b24d3873159adb8ae25966cc40f164f342519e88d1ead1e711e1b2bbd4be64c7e83f056f797c2d3a5cf7c5025f92be5637fa7738a1bbba55f761dcd1451ce4b1e85a6628b629a2f7917a86363b01516472c0f8614abe2ad1c9d5501b2a44a68e3eeeb34a64541125bf49138bcd15b7c82dfd40708414b85107d8b982c4f99783a03c707a37787a91a7198063f0e8a2d52dca61755105faaa09c063c7a0849570cba1aa7ddb3600eeba602c7e7c9b90ed00ec731d4d1d8e4bb42f9e9db21616c4aca48dc27b939428834404331288f03c2b5e887103c51748d0257519c3988f6492eb70cabbc2dd8a8a910d737a678d0970ec48bef3b81673bd10b687b37e11d49e7cf90c03c54826ecd833bfd9dbb8174274dd45b139d08371d5d248ee33298193194734c5863adf4bca92bc282bae2f47da5201fc240dd0710a22a8d922faf92c2071a7eede7ee17232d3b6ee5f3ebb1a8b230600b243c860968ab427a5f540912e5e7bfa0271201f288727f2bd5173539d5318e5c1c0a71cba4d9501b91c3bffa7bb61b3713f1751efe94a66e17d2b42da51d13c3df40f4db988dace42a6a1b9d138c4f590b7227990711afbf8f56fa63f2800cc019bbd4a7b3a0983c9b9e5f77562dcad6de96e3b2eb85cd99d28a021a10d6734400a91369236b48ed68528afc68f247d45c79318fc5d634ecb0f3ef8536d8ec2e877adc3308be906c5b96777d0e05970023e5c5dffed12310cc97249e4b95e32451c9acca8394fde699deda57e938bed7167e62e2cb62357f82fbe821ee73b4e09c6e2f512515412c2f27805762a8493e74a3d30bb409e499002a97354381318af28311ce484bdf7c39db53f08f73ca5793945e13fc8c66d503fa95506b37ce134ce2945d75b424ca6367ef4ed47b9cb8ba7de80e773279bf23ac888eb105385ea958b1b49b27c8db6b1e14a5c8ed5d28808a7d0b6bff1a58f24f9c57fd8b8f477a9d1365f89c698b8ba923896181299d474b93e05d3c915b10a69e61910761a6d8644933c593661b0828afeca590ca18e702322d9140d98fcf836c2f7a4f72b59eb529823a52ab05d919c3eee4db2cae1067213c5070450a160fd52fa44bc9bacc5c136701cd7adb1faf484da376477da08f6a4dcaa37af47c7b026c2da9d5fd0b30741357104cb2bc0d3cebd132b5fc7c873ebeceec5492aecab95ab393f35b93b923d2ca071e6bd8522c3ad8598a05e96646504f1620c045aa5734d665acbdda0ef73612be4ca4d95ba069041e042497f7b10445869989ce30f55206a1feb4e64890b7d1f7e9df2e88a352674a52ae4267c06592d425ed1d88101cf94588135892218ac11f3976ab2b47a27f02eb887696c94b13d48b4370eb11222274b5513a0fef905c66d0c1893832ffdb9b333178b65338fd8b81094d8f86f2e4e96a47e72032cd6fd47af87eec295c6e980f595b57f79abeb4654c4039fa03ade732b1e579551898b801ecd6e0fb1c5fd198335834b51673d074a8222640d2a969998f5b878bf897fdcf3426c4e24a7c599e5567643fa79ea5d20e7de581a873ee0181e3632a4e304f9dae09a81f882d4061ec17e588793b160c93a926874d5a8b78727f88de9bc125589a9562db5bb1c01012bbea1b2eeab68877871ce83455db43cc48455effbc71c436aebe362af22c6a319d134f65681c4d0d51f9aa42fb20f48ae3f7065664aeff5d8349624a5d79eb0bef3cbb2a1244ee445f560a6bf7a796b2c950a37dfb85ed5be11e8e305e835c9e077e676aa5ce23edb1f74806278548e3fa35059abc2f032289f9bd76043c8dd1352b6131cf34f66bcd0e7f1d13081f5b08ed0c69136f3b7ad8e05e9fe99a9b73624095f96740c1f40074e5d92ffeccdc0f15502082fdfcfc97a800be511c22b875f2832b2b891cb1aad2a17c7bd0be4427a4549404172f7c14d5e425e14498237c26a7813cd8612d048703cb180f1a6194f688b4644304950b078692faec7a2a5c5bbc482f3a7e8ef2825c4c19032a7a79a2908ca9774c6403e6b15625c485f2dd078902aff769dfee2dca9373704bf63ad981b51f61253910fd48c49ef10e3938f35ca8dd491a8e569baef675df30367b093f1088ebe8f876191dc32055481d074e5e47a4bd728efaea9fee3e83d8556255ffb2fa08194bdc66897d97d1557186d5f873169461494a83368ed8065b9a033fa4c2f07f7c60f945b60479e3c89233d58f674c0c6fa5918150bae0c6de2b65a09ccd490e2ad8571745bc37e70982411af667f3e8e9b9f7f75d863e5fef05c1f0d2acc7c86585a83ee32e0a64a9e67e75b80def5bfeb7cffe6e6822efa7a9cf049689b58336b081c039696e0fd3b2a2a6b0d177c9b3f8fe5cbb1c69ea93c1235b2c5b6934f603127eeafc4ed0728161612acdb2ba894a5ac376c4ef1fa8d49b4722379e5cb39752837395c413dd29a2a88c03849b6fb2221fd85ba6d5a50ba7ee9c09ecc5e6dc66afdaa1b021282cadc68f19529eadab809341187d57cfdfe01d0798ab8a94277b9b868612e575bd98f70de80ebe5f57637c511800373262eb5ac3836b03808ca5d5f732f286a5f18a7b7fb8cd8f60e4debe54731c9c524b84694c5469975443964ed28ccff2f4e8e0cf4c60c1c8a092e986cf12fa90a994e4f26ac89fabe8a0d1e27fdc00f1d3d3fdb73bb76809f93ea113e336cb0a5438147e454e262fbb7d656aa1be1288839bc342b48ba7d0e72c85a2e24be1a97dfb2db85b5d850481e62f3b11a28c6407686e73d550b9f1d0f010602e82af26813d2484a8db2da0814782c8404b2865abfbe3c98a07ffb37eea6de7992cad73a9b81ae96a9acb13ba213eb4111d868cc73b0432d2b6c2d7e0e0ca7ccbdce86d01576e1136871a07c76498eae53fb7ebf2e85fb8561d10dfba740400ef4495ece7eb33ce3bce26344eddd88cf1ed8028ec5fe8e71edda54dbdae08f50f8df6295f6d7ef1163f62262a200456a7777d0565d7f5832fcc7ac144b5c3e0ce3e5c9b7f880a54ed5e80662e96b356ff58f2e372b1dc0d73cb8b96c72caa9e5dd312841a8be23f838bc706d893e1a8a48b2c069874c293c41d00226f73f987aec8686046ac4c0c972c991c38b98cabce30e7255dbf16039b95dc7d103fde630b03441b15bd2c214763fece9d6778d1c6354d2c9478c226175c02cb006006715fffc879a6a2b4111f6234ee330d6c84d453c9ffac08efda1f380110a8ef8c2fe44e2ed644cc3e0146b4d02f76586fbb6d69b827be38b9add444e2bac4d7165007cdbf2ea8c4b967fc1bb70c68b229f19bc3f79cb13ee6265264885f04c09a96583f331ed46de3e5dcaf08313ba6053f3d0c1916a0f", }, { "3ab6cbeebc18df951d371e0f3cce2697fb367476bd9d50ca9e668c77636eeb9d24b68be0ce6a75eca194fbde6221755d57e9d3148623de24896a9becd98789fd3d14de0c7e53f81fe7f3fd491472a66b5b797fe19c5d0525c7a111a0289a9e65ae7c712ccf694cb75c490070bca7db17205af9bdb7fee27f9ff41fc78ebd2d3d399e690908b5c064ffc0d5bb67b0d2880bcb45c2ca2741691b6131aa1e5ee758fc50610406216905e13ec049ee92d1f95e16bc283dfd91595ec2037d20ead51d3a362140578a4538c80581b79852b0f6686c1ea66aafffc872024592ec1aaf2650d167a75bace024b261db4ab48b401cf85ec2620dc12a7fc37012af8ac1d6db923d82eee962129bc4ede578782594708357d29118fd10dc6d228bf7e461d2769e556488b776237b6309f3dc2e884cb2df1f43f71c53d389765f805ac053d05fa835e75fab0adb0f13ceeb425637f43556372d728a00fb005f7c5a20cf2b7f776066d60b70b11a848005c6d63dba0c93f139067b39017c997dd6b94c0138c3619e9a6d0e4b8792cb8d58a2ca12ae5d03e7637f2065fbb9e2d1722fd3aaf234488ca157d829e9a3b642458054f3dd58da41d7fba6d2b488a327b776d1aaab1a364c710e755ab22b9cf7abf1eb8949c5ca20c070f275f8959cb00c6d5ab7879003f89f795351a4ef4850e033d929f9a349b9133b2e0bd1cabbdd381594bfa697b845100b96b5fade05db12de040b814ec49489f39f5abd5b37f570cbb516636d5b7378f12872d02d4de20b52ed8ca0b12029a4c084621bbb578b870ca2ea79fd5df1ef8664bfb3b1a1bf038e4ba33f6ccde42c5146470c9dd293aa747d2372db1561617920142ac1d32e4f1fd18e8b9e72b7efb8fefc56d08f00450d23b7e8381849b1385ddcf9310a4850dbd6db7a4992690190655760f557a5027b5ceab3743365ac9041a5c14bed1126c4eca00d7e0a0e0e6f666f64bd1466387150ece5835192149237d5dd25e703e9d3a4f652ae04601d6acf8228e4e86055394c3abc9dccd02f04a60c298d101260b408b2620c137f77e2019fc6eaff1b234c56dfe922b0192656254fe3356143e969f64b7609cbedebcc8cb2b68bcdd9d723b9c14669da6cbfffbca2351de51e87db6afde435ead0017682b8014f91d9734a9ab9b374257273e114a8fffac786d53183ba666d8a67e30c1fe45bb1bdcefb5787afcbad213f8e36e78d30ae1305df96bf450349ade655cccbb17d887f79e00728abb449ea427fd2d0af80e3b5607a74a57dbe5264131f2fc49cb74415974b3d43ff872d4106ff11b680f56be06fdf85ec9dd850b1f77f759337b9a9ce04e611036d3f45743e562abe4b959eba7424a712fcf7c3f3773886aef22f7cf6168efa83cd3ff70b9521cae1b6689b2b8c423d883a007bb138025f2a31db2147691bcb365ac242efe40cd09a746cc501ae0289e80205993b07f86538d486803da14b74fb0db6ebf1c2bb8c36275137d654c1be56c65891cd50f705247d85621fd0d61ade8c05cf4ec15b84e8adbcbe017d7d5743d5e91025e0154a5d9bac7c6b8297490e9c195c5d74e046219c042219817a5c56636c7c4382c6a01d721d88f4b4d20250eb5eae5f3ef481dbf8a3f47a1d51d080bd4cc33f12645c8481e57835b77a85a2d83301172782f22026e69a43376ac4f5b78734c9eb914e6c76c6a12d4127cf195ad030825322a279093cbc40a680355d086a27f3fb7560713b019e7c286d96833dc60590e9a709f2e3c632894668e74ed20e42cd83a23ebea3dc3bcc49d14f8697541780fb2072dee6a5672d0d4e7bdf5cbdacdf5fea9e03c6d9cf0faa1e954172acc26dcd344bb3d9b2e0e6015cc55d19713d795bdb7c21b44b305e69c69fdb7261483f9693f36f45d356462f1ba4498de1c2e8bc3e0a70893acef2006dcd73cf15b265a8a5d4ed792a34a846d8f1d3b9b3bb75f1c5e57a00b36c00203973ef4e2654f6cb29e4445318ed99f0de6ca992281e83ed03feedb66aeed6a461c6f2871ae95343cd9797e58430d5639d7ef5c59c78b29f76a055e18e2b85eff177770c60ca4f2d61e612e617e749b4653e7901b62ba02dcbf50e59219349120ac01e6b8a6e98eb54abd16b921a1ff85898f90fc49a3c8f8f4ae9b0dd32c3e7f2e1527c4feb67a496390f28532f20acc71abb8bb4f71b434104f41e36b705289858a4e8430b8cd9449b0198ca2244923cff1df0f63833373c275572de5a9a77b23e5ff54aebce8e86d02651f26ae32e69001e5f3951967579ebe8574682cef8c12dee0b18bc999f8cc0f07e2ad3ac94d3caf30c1c8a8295756aecbbecbbb4ade8a2b8015e52a0eb1290693c6316d036e0c443fc4ec591c32f7e7f1b3933c921d5812233d3c21ee5528822b59ef2ec7eb62f7b04f40cc8238a473ec37a07e54f8907825ccaa1421c2964d2c756be450dedc011e1cdd9045720421b9a4a00e9d3076c2fd10d71ee36d5c0fd2c7e42396b034a4cd0245027449242dfdc42c8af4a34df1b4150097726c9745247b78bb2bad5fe8af94eb13ee1f41dbd36e56d801a4c9c5b9ca5d3c26f4714b6fe9f69b87567426eb6f4ac97e8c9541eafc19fc90d3b24aae0f76c4f3f81063d206ff695d638048c2cb023147a78332939d2f2470d16f1ed0e5d3d4dde438affb2809488b99815e54938fac3b02deceaffde310cf422f9027f364f5e79da5d2b5af1b4138ac9f9d301f396b220829c1f60cd2b54ef24576e5ba6ccd4802900db1bb4eea57de7787eda0e30fa90cc19f099444488699bf7c442c398c2ed989d084c8cadc97325484e337848c34562b3dea6f7670f935ed3d5216c970e04351651c1c31a34e862821bdbcbde202d91fed38965e31cc3b6f1e52288f327bd0a787ecd92b3b6f535d1d000b0f02d41ee01ca54e4e6179ad7fcbd60f0e41dfa5c9cc7ee4f7de3844fb385ffa3b24092b30be697f1fd32c9faef29ead346e42fe2ab1d312901b678b43b7758edb7eaa1c2d038b4cd6a7dc759a6b12cec955bcf4179006a7ab6e22ef15986df107080d340b8870e2304d57caa87a9961c04655d7d66c7f71ca9260e02aced131d6de65d256d6b487141c51bc86eb1e4721742f07d09e799b30da7b5ba94c8d701ae34271ba06f8ce134a7a9a2598d1570cf05edd9ec868cfa2e41b4c20a8bc4b8bfebd45f5a60408f08e931617746d1464bbe1f3844ab3272ede635f771f9af30e483903ee4d0cdecbaff4d31451e7791dc97c92042fb932fe1c82652c1d682a55912e33de3b1299db076cef594458670dc4f911f4a244e2bec757dad4b0052a41235e2f5e60b929682608c16a61287826218a1ac3cf0d8286555d5b0552754685c365d4342f0d9c45065daf6786179da791a86b50a5edd6fb4b21f09d9747136aacf79ecbf52b00fb88b0630ec7f0a6699901ba4eff913a3ab33ac85a71ebb51ed343eac86eebb3e79c16e664078ccda09e77ef8e0919b8cc447116b65ccbd5200fbfe86e9bac5637b33c9bcac9596b57c14ad5da548e96a8ffad5f5c69247c68d464c770011da7b45a337f138cda6b4e15311879bfaf12af4c61fba596780e6adcd5dadde372823da6014122dbac70f0dd896a8d387d3c74df282a659028d06cfeab3ae22dcd1fc3ce60f69a0d678aeae0e5681952949e31ccb8975cd167c9d012f4b230b1c1f47022eb1a3042951b338a734cdd17db0ed483a621650deb3510efe74191a94611dc212c0c73b117a73b8ae41892cf176742bd98a7cb73dcdc53b42df56d640739852335f8d44d901fc884286b433fc285fd5b3db8df0a8522cea3182c071f559c328b8516c9252681a94eecec7ebf626c0a9014d9aaaa0c694d14855433dae06656657d1f8a939123d28e00513d72bd3802d211ad7c1e06b9228c0d5656edccad5339bcdddd5e01afdc01f10974be3187804324fc513ba583b7b2da1e9096bbe3d078c1adc6c34d92c54e9c49fccdc17d10e66962120ee5d9b1cfe852569436270cf7c4c3bb12568050e2ca4db08bbac16214238413195dd4d936272fca5d56d7551b9b002df1807ed44abc84c66746387b79bc9e830a635c308a7bfad7c2c22cee6d3d0c5ebd8b230837b7ceaefdf71a67a3a8eaae0c36de86b2d96e759b8b53f8b8604775eb7a7e13223cb21033dc87d775628581a954085c2d66c1c8f225b1aa86091061738e7495cb36a5ff032dc678904bfa39a00285cd6947865b6d4805e3411644b4a4c94a6fffe05ef31e156bae6165d801685dcec195552d029d22e5de393a82ddf3cd3de3ad8cd6bba2325a03982204f07fc3c21518ef17a601fd743b27f7191bb446ff61d3c61d7608777990997e911932532e5b3235f13423756f5b6c786720cf6682932c90092", "50772c5a0e156ba13a9d86edc0e600021d56f7d31e7e452a74ad53a6775339c7ca6521d87a8c79b42900a1e9e6a1ec03f7e3d615611c3fd5c9927c40e5b508af1a298794b60148df01e9c9e78ab5ea8198c097fadcd6cfa6694be64e00eefe1a1885aece86f6ad87df766e692b58ebc41982bef5", "93a2561a9904a1787a10e2a668cd6a814f2877a7b512698e94796805875c8d1a", "588d9bc1d98210d9700ef488", "165d8c9eabcd5e93e6eff7be122c8c242e1a7f284790c93324f924efabcec4a4ce48262011b7360c2833143d645ff295453853c92f0c48c6dfc2af7ec58d9bec0d13239c7e5593cdb39d49376c6341263df80c0ed2ed79fe9899d0c07de93f6ea95a5dfd307e49bdb5672b158a4df623ee86d54cd1a0fa9a60ce39d1f5f4b6b0ce9daf2a61a907cff3bdd3f29156ac439638e0910d728843ae17ea7368814ad7734732e7c023d4954e1cd5fd19fc9b76e9bb84b61dd4371478917757b14b366b4bfab4eab0d9de746088ad43d8742e2b9e58faff15c2eff084df5f4316111d5dd7d23cc0b1ee1000253f26cd260aa636f03f64a8342e531ca1515b3beecc3ee07a29184988325322d5c09754c278231f92c0d980adc919d4fccf4a1da1d37f1ddb58ca997d6d700946199fa007c43853b6caf5f8049233584087fb23c3952414ac487e452f0c3898486d04e5b008b843122501f9c8a294da9159a04119ad5c8e9f5c211411e34559d3a7bcf2ac10e0174f94f3f2968c80ebdf4498de172884dbdad0acc3a887f9bfe896a6004d54cc424567d53f1198ba33c56aa460edc6af0e437b34322c1144854bafb2434f00703c1992dbad0ceaa0616aec60a380676ca11558cece57a936959d6c2ffe0647eeffd37524fbafa9691f31499701b202d9dc9980e79ea517089eced779aa45b522c9ad193e63ea8b64e8a942f630d44370f23b7e9acfedac51dd9f139f8806b09a8fbbabc76fec3c3721fad5087a6d41f93973af8d787d8bc74a3122d99ea14e2f30a3c90be4b695c8b269784eefafa52d6a79e785eb47a23d72f037ca572b7029d2f37baabce57658119fb02c5b659e3aadfe0052f1cc3c0afc6fe4624533d9700388713945c20c1d175da53738fc73f48fe57fef8305e796b474b6f8d3fc5040042373a13384237d95bb045ce0c20934a964a8372acedfd6e559aa84180a86311a3996cc17bf7f73e5d85d4db2529989e5836edad490aaa5f56d17326825aa20608fd209903335de4b36b79f68b6a52194f6ea8ce42570533df650e65b50c367f69b9f08c32b3ce3e75318106b8b2c6b6d09369c781fbf2aaa35053af215b621f833814ec4778ac683de0dc22c418b077a917a6e405ccbde9f72ed523aa696be1a6f247b096b9235217bcf19b88d43178cce5a7d82335fccb4c079e00280bfd272b9f16ffefa7fea38d09dfb2e4874553b135052595812aed3fa15096abf1eebf9abd598289e0d156974de4c2654c60825d42b662ca7439816d9d3a0255f40a4965504f643f029da535d4b109e8658ec570e99859382ca0ede0b0495d508c63c7f1eff3f648c60e9b773590cc663a751178ba7603a11985ff519056661b9460c1aabc30e83bb0073a927682a06d1b8050c345f7920c1a37546d79587fae2a92c803a986248f90547f0b6c0ad0552d8260d2a0dc3cc76d092ab76b8c12f05dcf141167a6ea300bc23227933396ef6fe9d51a1ba5a754485950f06cfa6964db2d0fd1d4393cc36f0592fca25ac1a6aacda2a32f548ed20287e3d291661848a62d41504e4fcb1cd1785617fa5786712b3005f1a1041733df6cf838ea3ea0b93685889bc6b2857d80a9bc0e7a66f7fb3d805770402f049889311fc112dccc72a25bd127777fd87bf5ab56d39bfe6be2b45a8301c2f324dcc50b27540200d522c24941701f7293b8877ac84cf35638507c7d912a3a94e4384b68c507412df65d0c4ca8ec2da704bd4483eb2e0d13b68c0c2b68c106a55b9710ad0a1436d655a3cf3c419d5e6f027ddf5dcfc896a5b316a7dae9290a7bf81aed539a647c8c98e24e7ed6a4f7f00a11134ca715e5826625c250500f8f16b40de048b095b5dd08268407f58a91c86c36ca5a2bf4f8fc682adf1bf601da24414c74956e1a8fd2888b5260e980c32f6678a4dc4ff73220c22593d23144b84c2ff56920342248876d15ea54fc100c09a81b802dd15f030bda9aa08727ea49e34f0ca8693e0a06d0af06ea7ceddbf0584adfdebeb20510bbac683451d9f84cf0f4e85c34d979e550e07e7f414d6f1011cb3dc28d0df6d4aac113f2d5b04e4486ee2cdcd4157dafcbbd55e8330a7176d1b231d9f47a63da9ee30fec6cc2c5aba3a8c6154f79997af89d972743255355647235ee939f4f305ec655271e0cd562ff6f401b86dd5826c769298445108ad0d9e13c504551f74c507436911331db60ef0ea99dc259b13cfcb0596fa9b3c95cd7fc3b1611e3b012b6719afbcee7548939676dffc372276aecd08e6a14251407cf995266545427d49ae5ab245cd5d534c52542fc71b3973f0b766f3d234c8baaec8b74eaa8ba90abe160b4504769d02e08d7af4e7ecc167780c619cefa58865169b674b2b1e10d82f6560ba0be41a781f4afa46bd722566d941a8e6f87e4a5c03d89685a22a3470354f2922e2915f9d46288a5e8896ed13617dce694a595e379f25fe621dde8ba73d865976950954e5bd07db147a0fb74f87cb06aba49b073942b82fab33a878651df73df2721ef800b658bdc6c359d396f684598e93f38e79639b8736b02dfcc124fb9fc199c35f2fa1d0dc39939c57286e58a7deed7b6c76e02b99a14d9bbf11f65d8eb7fa096fe4baf0f78cb34736499a0ca550f10d7edc8909dc34b039e3abdf1aa67a51d37a2eaf4c07022897d4d8355d3325bcf392d91d02d462488ead90b366e9645b956c3802e4249d34b5b2b2484a1dec15a9477821df6bef5e1626ec5ee9832fc3bd0b63a3c4100d32fac3e9085f0b5ba43123f54beaa7ccbe6ba68231649f35a28acfcbbf97dea2d6cfd96025032b3950ec8437108d0f07baf1bc89e3afbc2cdbb5031d3cd9e20b19018adda466382059229e4c8c54b455eda4280bde43b36afa96e146e408c7104523d5f565d22ef86d4c7cbf9c6e0d0b30e37b37feb9332939c642eacfe19d0dae1259d3267635051ea5f9b518dd74786e45fb8bdf72cbe3753bd50bea2a961b49cc0e2d589e77fd25ebd962463fc728b1d288c38a79a182b124d345872afbcfe792d259e7e5334311244edc75d05f9a12eadb61fd3ff79fe8c097eb01a4ac1f0c339d3be74be3d96b0b6a15e8868d043a0f2007ee8aa51756d78b7a78ad90fd9a26afbcb51fdc20ed7a3947f715c833e363bb87504d8efc9f8b93a993e2e26430f79f3cce203b09093c9b456b1967212eb0db4f7688d4dccd4a523866f75c9d9e7ce07825ae34399c5607a60b771866a647b6d5e1e20795ca906e451f367d8c40ffe79a2cecfe7aa47a402f8d49be9084661c96ebb11f1b48e7e8abd2978ee626f962e98f99db4eb3c6a52aa2bb2e62194120ce1e773b9db784e8c9b5adcfb70e3bd5717293eebf014e9872c5c1bdf3fb296cb88eab5e97a5ac320092033b49f37d840dac23021c19ab2a89190f3c8dde927f6e6b41874bf71ba7747a616682bd5b3f17a1dad40f4993a1b186ce4f44afb4e36af7715450bac62cb1527eb8db1d87bbc4d9c99415d16660e48efd911e02f5777a77e72733af3c3f5315dd0c785d5212b79c46c3bccd74582c57cfac0d50fc0c85370476913f9d8e8e10d0f6602f2271994972de49ab1a91728713c3cfcedb0e61c270b5fb331a980965bcfe10b41251a0f7915d5943f49fb139626f1c424524f2fba3a407e77dd7513669894fd09fff4185fbb997b4e4677f6ea0b52892f013f1691bdb38eee9307a565e396bab484d91cea9268f49aed29e319b0add900b6a75f7461db5486aaf5366f98df05674361308931de753c70777de73337a996f6d4b0e06d63a69849ba7533bb0e446f062edbd6250e61a49f4120f84efc1cf74c1bd30cc61a2d719fa76991dab119fc814a7c56f48bd584c7935679c53bb0ac78905b5d961fcd89a4b567d17a5182651cb07146aa9a94972ce613e8ff9c878a8433c0244052f09980a52d800e97ba65e8ac186862def58c72b9feec91266e26aa5075b3337c7bb8716b3acafe666ffe2df32b78f9995661d3ba28f8a8780436aae1da2a3e6a0a16dc562b8d5df6f68391aab73a10508e0f55208f974a0505f0fc0d8a55049a7b631fc94fab91459ae1f199527362695b41972e50faee34c5cca9e35e8682099f5e9652f88cfe9fa990ff2154c89c1c2a4ed6bb8a889fecfdf048ee0aae7798c55d6cdfd062cbca97ca289578c832d658ceaf26faba54c9c3ee9eb5bac80698c1441b9cba287f749a5e30d5cc715a01c89353ceab0974ae77fecc1d2dfb31a5101783cbc002c73cd155dfd14685c2f9acc170dc437c649b6b4720b676848a7f9b56cc4787eabe72f6e3f2aed776f9bb1432fba93a63bfa44fbcfcb6eaa9ef4b79b32bdbd68cddbb9897cf5a02c6f99fc765790092edf0d5bca7c55cf232a03fbb6f3eae09b12e09a9b49a538e0589394700d16ebd3", }, { "3497e8d61062e6f2084ebf72d00e9a47b550591edeee9746f31ea28039a1646d384c4348af293ab778f92a4807c48fbd14e8dbf3d67339c991dc4aca7dae38b5fb7bfeaaa538611d328b653950f4f664dcd257b345917cd66dc6a1ea75d99f70549d1af9d67b1608077b41576f38bb4c0a13ff4fa47b251142c6fbb79f9a27f43841ed0ebc0416c37f571aef8fd63b99e93ae88db50e9ef7d499ae7433d5686b165579d3598f96d9e7b1c876870310703df8fdf2069beadb34984f676eb7d3840c4c5766dcee3fc39f0739260a499647429339482e232362bc72c92a299cae36e9069cc5f4db8893e2c1b9ec0b4f334de26c951090b9724c2b3b7655d8248bc12a27861e020eb1e4cf6ad0dab903279b6fbdabff761d4ba159c1f631e681f210a8782faa86e08e554b5e30046157a0d1144bd08a691c2cc2dd22f3c3a4e5d44c5d03f7e3e385382ee4683345c0d316d41ee75f87038b49e0ad3ca45121789e7e7b95615e1a9a8dfe02c044c2935a97b141f639448182252ebfc980e0411e5fbcb3c01acd5aa7cc5d67101ffa6ab6acacace5f02d67155c26dedc071ffa66dbad26f67a819d46de0556fdffc1b4ab6d60905d8ef873ea1e51c62571c08b4c6db242e733e02e11e5840ee445c290b2232010b118839b37d4615c4521e8928e9ad475cdb4a3de9928ec7e6daf0e20d22e308347b31e7e877fdacda0c25f2e5c33a329e84707816ff4ffdca30dfc753c2cf883df16016795db34359e9363fac60624ae4d2b30bc1f2f99c23d953779c22ffca145fd08dad83c0f76cf727196799544c6c07483e0a41ca2e1b1da5a730956154f531d292b5a39a229ab13bf24a804eb68786e481c8aebfd3bc557afceadc41d00e1472c3b80ce652be1245089283bf1a1a93abd3325bb6eea121db8c0e1d6c0c31decfe9dba63c89b881824b0531651fc500f2f75ca9e5fdcbb179c9ded5d600a495ea704c2709f4a88c4fadcda4cd82a5b089f25a6fe0161159efe03fb5e0d44bdb5487f25e8c9adacc389860f62b06a6a4f8f104d9171622f70652ace736e8b28b70a4d9fd3fa4b9784d1a6e6811150d0a0601d31d17f6041e58a1058f99b80b0a6cd4f79c79a104b6bb731ecc881bc68e1d99ab358faf43d8504957ea0152e46e27dbfaa17d0f58287276e4fa82ab78a03513d5b4c3199d1362e4fd6447d1c26fadbd011abc69332ed0181952b391f2e8a5c89d68e22a7c451f69a9573b6bb6d918c7e3d52116f3f12f1d43d2af46bb450f58bde1732a268293cfd9cf2b90a844588c1979a30d6ac21aaea4b9e5500ef4a8bcd62bd70cae6acc8839f818d23c615e45daf14335c36dd46817c9b816be60c3848caa812b055da33f45bc01721d6fb7e850fb1e1458f27c70bc34876a955aef11f5703cfacde03a039c3b75b99b2d91fc18b00071a28ce25eb169b946b49858aa0885a4c665deca020a3fbba55d4d9175fd91e7901ec9eec0239806e8305f8238e5270f4af5c94d0008f8a5564636cc33c8a3d3e76db2a7915abe798b0dfbb3e322b33e188c7b188573bddbb9e4a7edbd4bb194b9743c4aceeab449f8affddbc2b109eb3d84f3b2f8b18ea2962680437241d82bb6146674ff1abee7baacc38d5dcd688b425c3e3b0dccdda3e36de755afcf7155d3d7cac2e279baad167e2a743b82ff8ddf3db8ecfa9680ddf468339427a4e9fb8ca4ce6f1e790c24e7269912a9989088c65965b0efe68ed44eb26876674261e3e72042f5995f1a7075b3932f4c23a8027d0db35ce4322122f489995bcc0b3fa32b7298c4c1b3354766c866a2fc0ea5690c58c5e08ae7037f70accb3ca7faefc37d78883f2bcd768285dd2571dbcaead813a0b8ae87cc1df868e93500d414c4418d5c80b919f73b9fd46111a02bfc884f9d30ee14fcfc1d55d54256b9572afad4777b8d8172c911472a22e7461f6f85aca063c19d6fdef3351149ee6864e93cdc54ca5dc7837f0ead91f5e3b155795df5dd1f933cee8671ffc05058353995019e5f6f55d2de6470605a5411afcd7fa5aa8f38d77dbf496d7fa9c5a4d35ab661aa15c77ce42bed44763166160ed5bba954e470c293ca301363f5b837406ea8ea746057588c34acf266030864d8c40e2da88ef04c49205fad1607d456767d30eadd884359bce04c12e35487bc1885d9b104c9fd4dea4ceaf054cf46cb3c77a619ffe963acc9bfcfad0447591ccd32cdd1fccb1fe7080ad75cca2e17f695ce0095a774327123f21e2839773506a9f2d896bde87dc5e35512ad733aa408f8a49e9018d1013cc32f550c968a03308cdbc73ab444f0a79a13450d4de906369da4c6a675d7e338f738358dc238be4f047579c8ba7a60448da541cb9e57f22bfcb8c26280a59b77edd0f5a009a3ef1e2958d6d3c3372840dc6a0c6ab1fe86aeb7590137feacbfdc7da57c77595b8572b45c4677836ec86fd8c4ca8ac351397aaa3aa298d752754507e1cc514d41c3f1ae0a692179218141f65bccb9acf6244730c6d00829455d21371972745b3665f930cf2aa9f0abebe6f7b89094aeb4dbdf7bbbe794f134b6284e289c995ef2929fc1bd39b259259950de29e57cdec15c4a7d33ef6e689596a6ce23301d25c2ace77fe699d90c2329da4d0f471bc093563dc735ac2fdb32c6995606a67bc953534939ed1236003c004d3b47590beabf39a1e4d5d1b00898496e9effda68433da17d1ab3a32aefa3681aeac116c5705077552649153ed15e9d704e67d8819579feb02d91db0d3533182ff43ee5648f5cc9a595ded4772d61e77bd9bffd6f29fc1f478dea44c32d5ce3118bc8860b254fb0bb1e85223bf709a7c0b9a52fd3914f1b1f295fd246bcb568388dee43a32df45e3c798068608a102143b5511746903255b98238003eed68776b46bb0e64af6c9118ecf9896709aaaabefbc1f58bf45b45768345b560ae2cdbe4d7da497736da8013c4098addb4258cafe7823bdbdd715250b707b155248d39fc6773639e4de3b201fd3cdfa1526c4149ee7d15bbee680c956fbdea844b1470a287d430c5c7e2d7b51fa756720397bbe214c19df3399a989958732d93979e361f7266e53a59bcef695435db67cd8749d258e7d582726e1bcad1395e68d7848849fb6d74451a53ae6e8989c64701102959f7fedc6a5cf8352e218396f9181f33037ca74886fae6e57460bbcb71cbe4cbb3d3a81e2090434eb1d6d5baeee4ede251952ad88001ce047279cfe435a4afe97847f798d84ad79a11bd44f09222d2f3b7fdcc47ff8a4c61f40c4629a0f603193e0aa2164579a05726e547c9081abcc0087907f8034469f740a020e19623fad42e9cea64068abb3d6ff2f6680da328061c200e1f646816a5083786ae5b71728a0e5cee14d7a942379c389fa9dbc7afe7e7ae075c061df11e4587bc90f92f1b077c091c43a25e7b3e870ad852c2883aba2632063c4ff74a857ef7267816317f823a8bc5dcda311b513be3a40e6bdeb89210bece50a608e624f00c9d063e0c8878884e45527f50a3ab4447a9a01652322700f087b6f96ddbe96a68ef98656800eda6563015a6d3c0eb1b6a9b21cccd58cdcdd074b73e40a098a980210ef831ec9e881cb42ee07519fbdfa52d9c62766a2046dee7752f880dc9082ed7f050b49ed8d14307b1b811bd87b6db2419418e49885d20fd7ca8fb45a11a1da17ac2304393734b552b5d02a303ddc72d1f456697a287851f207054c18a6262f5349348c806841d21e11fd4e4ed9c01fce1688483e009930079f7d2045a34f98ed83256dec66400a783d58c61619e6e42f6e2c6e6fc69e76651b96aabfe643ac69681955ce595f4696b80dadd1f3910061be6ed0840d47e928dd93e7c3d6932d3ead820d06e2539d9a604a6b53db6bb599da851de7cc060faa9af76d708a9aaf371dbc3eff0fdb99702504c3006f789a49feb730cabe40745837e2c8c17c77f999333798431231b337357637a5efd1eeed891fb7475f2c9f960e67578adf50241287bc5599ee08d0237f08c86ed9b75b62d612a9353e48cb4cb022d78f73fba1fab7f794a5ff64c97e6c91ec464847a81e5a5253989a1ee54a41bcd9b4b77bae6e72421471a7ddf0136edc59b72402d57e542916ee47fb3988b7123c6e8debddff2df171d4ce61e83c3d41f36143c9df97f2f68639f1bfc2a9d1fe175fe9f45e17e5cfebb330d3f06e15e3cf58acaff09ea576d896359a3f06985765824bc499319384e4c458d4326db801c564b0b503552bdbec60752b670d82cc8fce9028ff24ade3e805b81a72701b37d4ccedd72118b20d792739e035bbacc4893ded88619a6c499f246311947e48684a35406c4ef279c71ab2a74f6e5313f7900080f19aec3a39109d4aa41c930c66c84cd2163f4cdd59fe84a86cd8bb6468bce45a56d09490e032da844e6d90b436dd874c1cd32a75d1ae1d3e86d8a2ef948649eb56dd7b360f55ba5dc34a12f9279945436c6fb83d1ed57ba4ae1d9342a3dc2df9baa82fc9fee927c13439ba5bd2ff9f3e6f577b8d2df731db14c51db8a14bb15bf3e125f1ca4cb2fe856c5a576cf995db5010687d0799581c5e76d400c1855bb46680a631cc582f51c589a831", "823d0cd34e7450550da9716c1f456ce0cbc79431483a6214939266581b0e899e4c95719a09c1ef166a618289a6ee6971b6fea3fe380512cb977823b387ac51d341c26d4a835c61eebde37764d2e1d588df7886177e98e3151106c898b3196bf4dbd83f5f", "a4639c22fc7f370d8500a53819102df5e86c541c0ca10e8f6564e50b90c28f34", "34a04df283c45655a52bdd84", "cd8d1b2e5f65ddb3c0da8f12096134da22ad4d541444964077610aafc1f77f8da5ffc75bee807541cb6eb0526e78d57fd88fa9d9608914cf391ae7ccb8eedb0aa711889f9b6192601163b271c90df5d69fef487b6c05a24fc667469cf16cbd5afd58fc830119fc9f61b26dd50a96ed84c96825a615a3aee84ea4c950152323b20884346b25c9e2a6be3a93505ba059fbb114c224bed8f05f54eab76b2c9c23a0fd942eef9696ff67484b542c8347f1b1fd7df7242872b3528c9e45030447b2bc85eaf191963291e4223b75778335e5f1256618ff87bbd68b5a9e5cbd2ca1dc8aff4625c834edf8fb0d879b1f75ba9b85895a6bb4d7569a41bb3be6cdd020065bcc69b44a8fa335d9418ea2d090d8061e042e8e1a6ac03a6d5525079f14274079734ed42c5c9ab9986f0fee6bc9ee6c485e233e9b4d6de70664902529a135a5675ae129353eb2c00b73f226e84fe8c594272d6eceaca28b6da30492c92074250ec80beddb7208f9b5418944305b0864009b3bbb3dfbfb4cc2bba3313f8f7c6c19860f1dc0f5d7aa06e3b551adfc63dddac980a79d72bd2225d54a87a93717291c7b78bdfc5521f7f3239d5564fe9c9559dfefe76b77efc2e75991f31a0134529a6611ab9ef076491f2d2d81ffc5774ba8f8009dd7e5881e09ddf5116fcb5a44e576aef6cea91ebf52c56c742049639392cfb8b280dc2229252e04d8d394ffafa539290acdd8118656e7e1a4f7bfc0bb689448379e8cedff7590a09a3f5a29bf819fd87297b96ca07431a29a07ae126eb9d65e21824c16707db89868e127f17614a536de6ed268b1600a8b02aac2bca54a09b7cccf8e184448df334f95b9f0221187d56da7bd422f09b4d94228098b563df53414a5a86728962a2ea63023d8c3f03847b36db7cd189ccfef3e623b14842b8cccb18b4f80f01b32a4cec48f3009b98ffa25dbad76089c8700e90848da74aeca81d01f4dab2b7e844a3e48bef21f33c92734b821ab382bdf6d0b1048a9866e676b78ac9398678ff626d5c173a15a0a7514b2544405dd54eccaa2791605c87d7117bc9f8c0ad84623a9d3a2b1733304b492d4dec38f7981db9361b03a2837a95fe937976c7f4341a802dbf583366fbe368a3af3f92618046bb55696cf7af1f465a5a57ec5908621f431ffc762f35abe892f772a60a3f75ad8401321f67981e90083fdd1cce40903ce56a629120d6e13c8871523c4d848664331966298c8b31a5bc8174a8c14f61cbe98ae7ee3e90bc832b04318864d19a9b8b6d49a260f42bb120cef9afbe704faecf0f428d917ead9f020f5e9d772bc8f29600f8a7623d8971c1e3c5f1a3b094191e497bd70f85de124137cc4b9fe0617cb73cd44b89aada072625e25976e7aaa5a8fe9d9e3f32db47d1565aaef0e84d256bfce6aedfa1a2dce5a94976a2bb9a0da95941fb7ed444990b0e0e87627e35f3235a998019650a5e5cae804ecab8cf729a5c712f1e7d17486082dd50cbeb2ee1b0be6a7bf08a66ab3cf1fe9f49c7083f5b8ad183f32fb35fb8a41230e4041bcf0e5ef54bc3d21ecc1fceb08d95d745a997e8f2fc3c0f6b1b6c1c02e03ff02ae0d879d13eedd42d9f9949ca7ebb785764162ceb6c6f9944dcb3927b2f4eab23ab566b2b2bcc0c7d77b82579e88203602264064ce98b5b1ed992c1bb13edce579ae7f5e11697b493749f308b33e47512533350df5c07c3dadff656197884f359cdfcb736d29231aea1524b56e06c92f5a98ea663543f67e44003f5b41907a951dd792468c84c5e0e1b46149a5c9751295e153990b78c0cc712889a21b299b0315150dc50aa3b4f7fb0079ddd39d263a754b1dcc595c76ea9fea6c120384afb38d4bd40491c4689b1afc9dd096dd0327c84802bda6bb6b7a8830bc6c06b308ae9665a8666a5551ec954eb72adb827ef38f036c51698a28c92dc1c9e25c267532da2c04c1bf27f5b683ac750c3ef53a8460dc186331549bf82868f9327422c09afe1cd15e161bc41a70cab2f973efcfc8f01a380b86a432e1ae540e09d404d93d22a20dd5f685a52f0acb863dadea236288b1714700f23d1c19e40e219e8ed21f6a393e541abba850ffbbd4030e5f6567b7202fb66d86cc2a0beabd495814f6a50690e8d74cb8b093e4d43261fff80e7a67ca06dfe808899cbef84c09ece01414baac740cbe4c656b17991868e2a136f4785a0de311aeb18cc95ed33fbece22aaed8cc1e47f58cf6c09a6f92c96f37d2d2485b369093506f5e9f8534f8569655277d0399ddd3d33861bd40c71ac53a44d1981cd744d79202322d47a0228356c0e27efa2ff1009cf2a416fb6e8844eb76b8077a4a3961ff193e1c95b222e72688ba48be82ec5da498e58861ea613782ed1ab50a95b5cc236834af98e61528ab18453c20ff978551b81e1bcc0ff4b7092bdd9ab0b946b7324b7361ef05e1f7d7f6a336281b4bb2c671a95a6ab84be6bef1b9c8c3d2536edb8d79b40637e16d7281ec5243016232d7c9fc07ed9dfcf555055d8ae65f12ad150da81f62f2e1e82b3adacf6d623ee4759ad61a09038905bcf1dbbab671dd28fc1d10a0b7eaaef73a5862ab449bd84c8698d061e79fbe52a86739ba945a01353e0f3916667bd7b4356cc65451c7003927f2aa738d98245760550156dda529be741ce3ae1afdea0de35ada26ac241fcb5d518e6ee7f9930baf88bacf8bdaccbecfdb920f3b26285439912a8902ae029b07f28c1dbcfde780cd2bee6c6e5f4520c5c7ff3ab5448ec86cfb270c39586f80041f3764b5dc77dc5ced0695c89671cf90ed34c4067b4bd938b1493c7902dd94be824810a00bbde4915d138fcc7584790bb0b6682fc0799cd415441ac90c1caa008c7fde3ab4a3aae478c64991ebe07e6c4587d3046c9ebb8e125e795f0be9266bcee5a4e4355a2830c5b34e583b0355b34b89c08011db6f6b8371de003074704e8cdda37ce42c7e395b6a37bae3dfbe67bcfd1f125c9a262d56883ddc028773988270aa30c6dd326cbffee589f38286533e1d5c9486011170be591beab5e0ce98837cf91f0a58d69d872e364aa88daf9cfa71bad167129420282d99ed5884a1276dfffb2c4100c74a8b863b063c07937f2e9c12523deac4ea16178863d975e3a5be5efb5ffbea994d07f7ddc5326bed1f5c9415c1d4ee1667e3a581499bb573595158636ad94d84f7c6e4b8efc2b141f2bfab7932a050fd88a8c7b21877cddd488543db5b11138cc808e1248b6e2ef492faa8a32f9d93e3c060b5cec10f03794248f9662ed8c283a8e0eb493824e2750ec75b3b1292d80ce002083a3c64cc487afc31b20f84a778f386b012ef7bef46e638d0f1cd75487ea46e05621d608482637b3e642a9a2c5371bead4386eff968b3e007fc263086d8a930dc76a8431a4e6907ae35c7b3291075d1c723f02e4895714803c0e97d65b04c0f27d01d5d68001bdb3bbd44dfee1eff1754fe8c182cd9bc6ee273beb2a444ca1766f747d86f36cd8cef6eb1dafe0c38b9327a8cac6e83e076099188f02721cc4de3d940c3ef19d9b067be07b890c798a79ee8c44d96c5e05ee5d5202d941a674378386233a83bc85134dc8c46a7531b2b952fb277d8089cfb13e882bcf7545f0605271fe38bf4754f98dfa13fe6b635a62bcf962553882a8f28a9a5fc0b3f85509b702d4a7555d40c4f7d10fbe80d48b4826995fda7d15f14aa9b95fc6526101cf09c97fd74baca6bd26b4fce8a57b0726e0f68118969ec067e9ca39b2ba59fb0d78eb5cec5b872613b1b76763b3217d859bd6d991bbb5448bd4e49dd6597ddec9e46afb3f71d254aba828c91de51904139ab19138e36e6996a207da80323d96077c97a3e8994296376d4dcb602f1e77371efe8b020b7b6f6f7bd2bd733ad9c06c45b77a2893d73b4a8a57707969af74ba06b2fe7d4079bcad1cfeb3689ab95c8b1215fe0a855eb431f67df4ea589dadbf055086924e42cb142c9031e25b81e8e1167a54008ba1ad7fec6794f203b27f3092dd72bb766c9653a72b2e25c965f53487cf3baf74eb7742702380303af8c0a61cca3eec78d4b709e35e2cc5bd586263d9f56fc12454547bc6165e3f070ce7b2bcace5c8cbf52f987568dd90237cf190dabd4ee7a80494692a5379b013611f4eebeef8e1ab9a9c5ba61926095545e19c3dd61b7b404230729aff7d82b6bbbed6b4a926f6e49189e3bccb578fcb3537951fe9c78ac842350ddd80133275ac0bce3a669183776fee8288f874d29190b452d65bb7d8edfedc6fa0ae147102b92041af6dd8a566932e016763b60a5b9b1e3667f228cab075f966d1c525ac19d12046c6409345799adfd7154b6d8b51eeb1eab3a132ac6a2e08acd1a34bbbbdd019195af9f8a93c6ed5463765173e669cb0d42b6cffee1a4b45987853d43c02f920819f45a4fe0905d8c65aca182b4bf56fa0dc51cb53c642fef003d92c13ef4bc1bac571cbe2ba3673a49694f6311b7dfc17a4069759177930b179748d4403c7259e10a5d221cd0a6b745966e598f894e607b779dd5289fbdae0b4348141ad373a62c76aa454b35b39a7be875598bb30007fc300606ee2537cfcd7c22b6149880fb3cd8eb53054d698a0d20f26a5c3ce468255737a68706784", }, { "5622aa8d2f308dd468a7e4959ccc01f0e80d91f79df65b8201eb44911f6abc758c6703bb97908fff377395d33f96c328a4541f414b7ac34c6607dd85729afbfe01feba988e4997c6bd2c99fcc35d2467b143a8fcbe6b49247226a9e4c0a4e3c1a29d5931e6f1f7a31d90a0e0edc4479f08ef9bc65ae4eacd0b93b1cb38948dda31e60b18d702bbf5935bd580201d1f280cbbee679fd834aa6be576a37a037eabe989c3c18c7fb61fda8b9ffaa8bf22b57a101c19e850c454353af7af3d755b26ff1ee78b9d9daa78294972d108958682a5a29c8ef260e2289ad9d7d74f32fd4e51e5d9ee828366abccd97dd56e035713a6f3a1985383c0ed5d98c4accac2fa1ba7d30a295670d5224952f7b7554fcbfb426c9496f054834dec48f9b70af3d2b1c6dcda1c4daf3e9601364e57851952c785e65d753be1c22729bbde33aeb1e4748dbe90da6ecf716f05bfc68ad819515dffafd33a909562b95140ecfff1d0747f8e0459fcd3ca6cd8893262614bb4bf4b639285f327e7ac782898781968ec98f6f0f2f3c4bc5f9c4691ffa7ddb3662816f8ad092095b598bd4d10d6b5fc6fabed619eb11dfd4d638f4c0b6cff7194156a411e8ad6d3229320336ad52fd9811c3a1fcd571d1bbbac67c6186737ac7ca1ed9b2bc46e4e578f81c164b09ae5cdd4059a2c22b5e7ce1dade684e49200867f9bb1430aff9b99805cfd31f7e3fecbe898f70a4eded86b8bbeef7050eff6cf8ba71395a7ae2e270a2b58010e56cdf6efc4003da3d8a82e96979ee68694b6113cc9a6e377d40a810063830eb95005a81405e5b7de8de67424845bab1911bc55da6338513742d237a555465fa54b07ba50ed712e7a57a39fdcfe4af50f064ae969823aa1c40cd86a621ec90769d0c1babd33e8388a8bd76689215b9827a5819127bb32ecc80a562a291f3192eff34cad2635e5b0c0bc174add72e2041864953f1fc72be7d28111fba0438d9036da3d5c0f220ccfde2319bb96fcbfae6055ed7f1c1967ee9a78e93bbb77cbf151084d602a5a2f087d49c3134582c1a5d7af24f4c88be26204cc9dbf4368b19470fef49a5823a2d66c65e9b1e8ab56bf5a7bb3220696840a6222caa58a7b39fb792d95d25038a8bd9d916e853cc5459640f8b8468e3d51f05f1b95e996cee40ffb7ae14cb289094f1b77d5573c1aee7c12a6c3a1e31491422f272cc5f510d4f18ab63d3c3f468c5abd61b2fa7ba0768d46392e2a4dc06c7ce79841dca916cd33cc0a700b50fc660e5d1808d8b87e65feb89428055495823b2dc317d6d9e50aa5ef7ab14076174ed32f56abe7d410e58ca40e92f8a31433d0d74ba7b130b1561f2b075fa11ead744d031f34d82f1a64d428f6cccb0a009be24b42937bf3e99a1ef1fabf0fa7335dab52918382abe756d3de229ee8223aca6d7c5de87047838e387d4e472481a4cfd4365256e13aacb518ce5300f18dcb5e0a28477a6fca08a74756ef6bd8933bacc98d02abc7ae60df7cb3e06d41abcc4bd313c543ddcdea2424d98ffc6dcaa83658aae11f5841ffd4f5df42368a0e815d2146a0fe138b223764b133d17cdb08d485e9f3dd2bf2b220d1f4565b02d7b9231d592130e4436849f49b1a70772244fc0c38da372a8c57fc80ad57828410a5a16ac6d14e093997fdd5b26e4cd4b248e0ea221715ae6e112e1b68b09f795540e31b1231244bc922207b906c4f42b5302dd7474286b653b4d1bb657134bab117d6c349fa0f121c2f8dac9cdcef510c1c28545eae0ab163db6cc84ca182feb858c10153d0136f00a01c9c7d0bed892715dd85c4e73627c3a2ef0f43710dfccacffd1d9f118c9fb1a83b2eb328b8da3e955f027d95294038184f7b895d77532c7570cb86fd6b37a5a66659cf1e330db3930f302838706050c0dcd91d532d49c89d144e9a7f864026ec99f50acc02bd5f11ee88495ee8991ec4723b189f84e03d992fd718b5173ea1b033ab7d3568dc4656648fb54d28d3119b0f293a930a772c394f45ee66838f17b73a94eca27033f9d5c2ae22eb813386905dc024673850a087958eed191d04d05798bcf909eff2deb2a0009d223323b290e3d6f71b2797a2bc2590d54294a5992d629336518514032614a04847c3fad8a7d1cfc2f86765b48cf58acf892f68b691fbece38100e6a71487ef5c4ae934f1ba03b4b26a1967f70ef1c697202e4eb22a3a95ab3b7b524f0241ab4d2adf3ee5e3f2974d0bfe4419ef0ab11039ffc26339570e74d260c4d5a16f22cb4f60b03253487f5e46c47836ce29460728086a615f78d631d89a06790928455889f58adc3d0a3a84ceb2ba9cdb00a403080e6567873b985fd59fd9dec71e375013c12c51cb67d599198f36f58fdaf897e85dfe6f9896cf6d35a84cfdc6834dd9447a2a10e1ffa9fa8edfef1db9e8b4a245b211de49e04b7e88977b4e1ac9285f43526f2452181ee0f80efeb1f6b2533b656519ae45652ccefca81c17714476b497e5d8e9fdf6c9f504c7a7fa7afa36df5f4f8da5b4b973b1618fc8d2d43e866b235e5420551d1659e5bd545fb78a3e17d9cbbc8e842f3fe6be07b892453ffd689d5188f26f9e4c545ba0b3132af12a03bce6914015d026d3d7df661c1e6384bbb50dae24abfa78079a2b1ac41c44c7d82a59183f293f12011e781d3cdca2f791afa5b55a9f2d6139587bfd74bfc54ce91e642847a33b48c1b366fd8f08f520b79ad5113a0273735aee71ceae361a97547fc09b22fbe4e4ae4ae13e52d65e0971341aab368d1e917c8f5f2ac57ac119f981b51b7c99ff2be3e16935b7c73e28fb58d332e6f2c36281228c479c4d6095cf15b14baeb0769191dfc649a70471a25d45d4433797a5b8ba31ff567e60ec4d759d99244d0fb5dfef7c2896809938ddde0d2015a4c5ce5ef6cdb5752da1c2a33e5bc78b6b7c6a5af892f0792c28560a357720da3cee3833bbeda8e98e6a8cccc6535831cfc28bc8557b4181a3978bd90eabb34b99eb7e55d9263e6790ca34561d8c87ec4e12b4a38df524318db00a9b5bbde6f5a8644a818a88e91b521d716fa9f95bf70b109b9905bfca926fd42ecb9114c039790abb0392a41ee4c190536a89ae6194befc2dc4bcf7562bcb84f65c99b69612c0511552f53436b6c489204d3881e1f67e0fba3a061165d2955c2e2e12c440d31556250a8a5cc04ee5e09b1d627c14e08bce1a92df7f6475db92a3ee57e4c16c3ae677c44237122818ad457a29595ab528744707f3ab7ccf3d20bd94047e013e647802a7af14cfc7c11441ea6e9b9f960fe69d03911ad2cf3a8f633e0d647c71dc7e188c92e75353fc953d6a30dd0040c39d4355b71524f1a4872fb1ecab22c8293b54bb22a80e1e3d4c886d2988adec26f041dd0565cfa9edfe5ad9aa7da1d3b8f68fda9e9df9dbe98148120af6ff30e6400deca6dc9593dbf06c856d0d582503e7ffa185f87c6e7ac58184bb80b4a1c0c18d669e23f9791365fe807356a5763ea418c39d94311759b29b14324fb6f3104359ae66532779b825f92b7c9ea2ba43ba7de04eaef7a86192bc93e17286f1b6e0a01c33c796ebed8f17692eb9237173a051c14e4869afda2643bb98c9ac4ea94c6bdc1401c80190df6abe988d2f0b2d80cc7bc8362ba25c6e5df4370a43e156aebd6aaf856b3f64d5fefc622d078faed40b760a361966a4765adb809dbcd74b7a41faffad3a64823860e5656874133c7f8a46b5a3ac591906359aa4f171ef6bb2ea6b5f24cfe25c2fc7c1973bd5d3bb5f197002c5ca1bccffb570f0265f5cd949c7386d961ac9c5e18b5d1d6030d8bf4a48c10f12dcdb11924b02b8ab5e91f425ca62bbe42b80c6b6dde3160ebbd55803966716734327058e29bd39874f2eac199067fdbbe8c372c5a688d3615e2b65f4937b67d6a26c64cc2a9e5379cc00925c678f174f538915f912e85b7014c064a73bcc7ddd38e1a9627ffddb4bfd6da764fdbfb45048c9495ab1a4cac5642f6c9ffbe97d33cb26964a23719620df3d85dcfc392c4502759fb31a6a797e99e51e94cf9bc79ac15de4e5cf7a05aeb88a8ab4c3b6f9c52b99794503f2c49cd7e230a67df7403e552523249f29d257b35c0c7712053c3d9eb583a1a7473d7f296d25a66566e4ba8b08de2a31b082e40c8e5b1e93985b324dded3f52511744e7e99f4e3ffd99d8ae17bb5122b37f637c5525558eab18a378f5e2cb56fa003ed3af8d139d16ec4b2ea79c415b0ba4d750ca2cdf653582ee3b65a9825fb9b123593e36e645232163cabda515b959ed0a1419e9894f6c677ac200fd11babe3503ec7bfa319f1b9559d94a6f82945c9ca8667621a5d28920949a1da644cbdb58b84742e9d65e7f2027b99fba4dec46f642bd17e88fa109143b26ba7fe285c89add0b74a369f3d381ad633bfb4f72e1822ff96aaf9a73b3c59a6e457cf40e17c1198c64737037f52d9b3118daa3fa5cd3e3c7738e3b3743c595893289974a4aa0d6bf1446e70964823a7d5cee67b9b25b7125d9ac5d1d61f2a6947c3deec6deb575e2fc5cec60df26de3c0545e5b79156dd6af33a78552d1ee9994cc8501b7dc5fe7a22eadaf201a92e06ef03be705a8bdb4db65392d3628c7cbf44cccac292c93cb5a407a7a5a0d5ac9fd95b0033d6eb719d3f14609190dd40d5aa1b983cd4c4e278cc8a1e7d5fbb0d39060d6cdce8de6a17e2dab973a7fa594205e17edab6514372eb51e03b0ced6402fac0efd3af49fb8214a505cc9f5f0ea5308d7fe6dec369ba154", "9f522375925222a04f5c95ee14b6386412025903ecad0bc3ab78afe1145136b3a3592835ab4ad6faa66be9", "d1ba82b3ced3e9817642aaacedf482e79bedd0560ef2754215ee792514bbf8e6", "bb21211f342379370f2642d3", "1a6683805d3f478ca1c1512b9846468378f83be27393db63956e151ec408368b47334afe610249182f54c4d0a01b704db2aa90a9755b8feb67ef9301f0715d7d6bdfa5cc4497cef1142a43eeb42f7c413e8f489af30d742a706d05a40a0c4a5991f9e2cc5d9fbca6ad3767682e20c146ac35aef38dfb2a77388b738fa022158d5c802e5f0761096bb45b50815ebf09172759521b5c5d459703ebe9ff669ee4d14a86e5d0650b597f4a082ba0aef366a924ea378b91c3262d99f48189eea19c76c0f644079f8415c11033cf24d30d6c149ab13ca5c29deafdc816e457257361c1af4b915da312d2e6c7fc712faa27be3e67c893f9005a0e2c28369991c1dab22d38961d1abd6d94c4d549cf491aa1f8d522be3ffa6d214825a5fde3c94c4e35c29b8d05b2627eb12c9d94f450a85eec6bc963a279a37c2344ca36eb604c4bd11c2bf2ecc0dc16c2c365bbbcad3541bd54f8d0bdbb3ca4a087b62fc19fcc1c13984eab807d2a6a1386643d90d412d027bcd0a638765498cdbb1f4cc1b91b69bd241eab3645f225ece85a56e5008d6094041f8cca6b9a0ae3b15585de6fe0695d79d348f8619431ece40e736957a7627224fe92bbe30df5124f476d97e36b5b08b3787e8e00f0c10013068eb156f82f3494a35d6edd5f7048d1e91954f1013ede22eca8b4ba41699ee08decedde87139180a567c6d169b672af0f12aa09ce20e9cac4e78b8067d31ba4f63606c00d1d787b868cf7643fbb170f8074667c9f7584d36af80b4e6557724013618c28d0dd40bfe9d4b25761b3c99558af528c2d290d04b09821bd7f992c044dd61dde9395bd0c9ddec6d0bf6e044ddf0b4b2d6753f5acf2e9c904caa4e9f310578527b85e6738803758da646919989f735b09c9a5744e63fed2c3982e59fd29d2baeb9771316bf8d29213a4956b66c78d5654436ffdd82d0d572530fd09507b988d13fd743f35333237681f8abbb301a8ea870159f802a57760659094d0e4902036c5a62c563f1fc86c4238e1ce89f5176ecaea194ca112fbdeefbef4fa7c203678cafd34486fe58b2af04f84a1cb620c6e123bfd96301e0a5e5e5abcc95d28b852d0cee2f51faa73e42f22fc335f50de4c3812ee14038633a195083f3944284c1086c34995832c3cceb7d385b4ce86af10685c16005495121105272d1d739c584a07ec7801c3667bb280987a8aa41f9537e9d1812a5dba5b385a0b71d2e9573c6f3e9ebf0bf7267528946a6aa6f43efce908d32525cdc3b825bb11c7239f1de412704d24c17455b9382fd6a873180f0d5d44dc449320973d5cd0d4e67e83946b6ef47e5fc3dabadd80751f1421404e56b1bce748b7bde63c6975ca81f3eaf52586a55242c9745dee3f7c796d4508e818eaa4fa50490c1a79624561b98d2e1139a328806414c905372356a22393ea0da51c83957029edd8c2dfcf46d9564264d74c1c0497034ec018b1dd4c14acebc34b6d2c1a616937c37b8b4a0ee5dcdf787a0de1173798ab929b72e0fa83a6c9b9a99d8024328d9c236a8f57550a4f83e8071eac76adb55939f85f5b5f514174b670a3e8dc2b54656f6201940a81fe4953d2680ae4ec58635ba74d15efab3e06dca6ac269711ef2d4dd49f731e24a92a3b935ebbb3fe8d001cd4062669ae4baa62c2947033afcfaca227d88a11769f87456d5cd1bb6606891e71d63aff9cd5a7d23263a78768ac2ac54ece1441fd37d096cd27e916e68891137fc3cca427febd1947cfb4d7ccfad75b2ec5e809c132111eadf25a73043d68333139bd2435de9941bbc61c5c509897cfc19a21645019eaaccb6d06371e3d0570c09c7556e41a727e44d9bd672fccd1f89cc7d58761c16df8fb75fb8a1dde2caaf088f02dad91b6489114398740e6798f3ea8c7b0cfd974e160a0106d703d9589ab09aae79108e3212f19cb950ea9c0798a1532bc2a065d5900a12054395c0545b0878ac0b1d461f553dccfc2a22bf254ced88dcb538e3889549960b77ba6237ab1458e158f4f46606372e797ec9d9ecc6534acaa1218e7540eef11030bb9c3e5a7816f3b33a590d970619bdd2dc04d5c6f4ec38b7cb4d525234b836eab57f65dd045e02367eede9049e219b8712b8d6fe178080c5f77b821f1a475259ae571a5578eb3b48863162d45486f71a28ecbcedb35b320e5b6401f9e7870aa5418449bf47502626e1f42abf481b48d5a6819c640bfdb64f873d583fc4e40187940a6c3373ea7b47195270a8657898f55568985018abcea9bce1c155d95b426f91a734b2a14ec2c7ca2011a4d30019fd9b3ef63a804e9c30c3de2651c4213e90285a4ba100b31ee402e8a7f23cf9d4dba003bbf982526bc63be5af102dca34e7d362d6fbf6f56046160d7af33b364f2a86074d1c0fdd54aae89b19480efde2a9caef9de7c0f9491e1cf43a48752cef405a0ff16b0fc67bbe433a3c1b9661406c3726092efdc076febd60c436476f24dab1b0b8f8893986d951ed72282990e8b1526f4dcf539b22c01c6a7eb5577cd540a16a81296ebeeb7ddda72e60fcf2840c5b42c5cba30eaea5402f267d1d04bc80da5ef0dd2bf3c7a2be986507617c9bdbc96c6273a0c9e586a0c48c98b4552113149c6f79557fc8ace0b1a512fec3aa09ef191f95c2163113ac5cdd940f0c2120509bc53c3ea493c54703effb902ef752c830c61e85636ca95429bf16937bf6786b3eae1b277bf08dcd69f521a0078d633beb33c9aa0cb33b238e1021ca67df122a403a3698452740bdcac81d22ccfe4ab5f835d1961708d1faf6d40f115f16c6094ea37a7ff15e0534f62c19a6f4ded0967be337cdbdd2a7c58ba16ba2e4c3686e9d075c6fa7d29b2a0335ab4940d2a95c4500295f4db84ae65e46c54b7300909cc5411c725a31fd962d239aa0e2007c285586b4c778e2ac7afec42cd8409a63d7cd9c677031f43f4aaf04258dcf1270c02a4764177aa66db2d8f860eeb1fd06d0b27587537410bcb641f90aaa7bfc6f12bd143f66e7c933a0f3ce6b5048913e1b2d79eaa6c19e7255d5eabd24d5f12426339541a22d600cdfd1781a1a3894740887840aa82e5a461fc324285b0223ac9b95c3eb88160353f168b3d4ae8a2e87b7715b5fd2671f66e6eaaf9365b3d9e3acd9a749faefba6009783771177aa4dc91f72fed7a5bf6b1b7738b84ac0a07b4a5a3f0a9134a39e1e7e3e2f9a92d5644295f31c5a356092bf07c709b4c34305ebf50e857a4f593dd1cce0439d3fd125c1ede1a48f583bbbe0eec7058345129ef78868a96f8a76ba7fbfd1c5eebf75f3e0eeeb9db87474b96f321b87fffc02433513fb467fb74e2fc8feb498d51530c753e9a173e95e0edc5ba9802641a45db281b2e2d87d409057b4fb1925e834e90fa5619ae3a9237d5b104e7ac67c2bdc31001eedb4ec7064b2f72e0379bf8780f67ec4b195db014a2d130e77b1778efe3dc703f1310a566a6d3b5c9b12b1d4e25815493ed1510a516a31ced3b64ca49a783ad63ea71a57290727fa31386d2fbfe41f12d36a618c6c28d8f10405eb3e0a33e8ac2e4133ba75c688c8c9a2bb33c8fa032eaf3ea0d2c27bf89269c4aec55f8232b292e7fa9fc24527184f19187d9d8a3f52335e2feb5dc6d997b9b773a79a31db832b752e5738963ee5d61a1b426414975693f986e165e52d46cb059fdd4f48f008e96d4c1a48306b7c002fd0c861721656074cf11173ca65cbdb694c79f58a3f3365e872b24670b691682c10261eb1ffb2b65da031d070e31542f49704b77970a78bcfb4c4ca517b4c966a4e8e27664704f633e90cb7d7917dc1d3a8b8b7fcf59ea3a8a81305761923cb182cebdd59255803a14ca8a75fd007670d79a25eacda1138d67a0fd1da981529dbf182fc4d7a700ba498e4476a1d415381c9e2ffa3bd46201cf2e454c4aaedbbe3893bb4121a6de02cbecc1f319155eb8c99d1030103bb6194bee51e74fa01f28dbe16092955b9599d5c1f1c3f356e26d48fcad7c4cdf0eef25c25273dd62171785c9d2c5a01b1f3da9b4786b1b399d890e2049b73c12de2fb7177f2bc3d9c645398111ebcfd83b73119897bb994f998f4a6fae1b3d6361e171059dba0bf9de9af7a5a1b21641790baf82a36278945d649cf5d310f3792fdefe8c58986a48118fd94647b786e47733ae703701e18992bc1b143b1da6110a98030bb9895c14d7b8eae1a155a550e219a5b6301b6d26d7956ecfe4c7023eec1ff62538b3606ebc7906a1243bf8357f593b6cfff32e3fc6b51f6a0ffaecb658d526f7a5e9faa6294e4808b779f4832318cc184e49e8957b72bea0d67366e040cf76a85889fc6b04e84afab0d02947d0d83e0de19f12966fa8372f6e82ff402bd7a69195eb1a7864a3375aa9e23736fa4d4b0224647e416474c01f72b7d4af240d7f43395b5b04c8fdef1165ce1d56ee8ba0e350e6ada893e0594facbfb5f0d8829ae203929525951584c21371b86deb0f76ef5daad5e847135a6488b35ea33e3a165fea502975d6421d4567a229bf3ce94605885453610eb9c82f9ea743bee9e14776bc3076a29af268cc72d9092a492d9ff08c345dc2eb2f8003b561d9912ae1198c58107f8b37a08b35075af9863110e6770425e9d59c2dfff9d9942c8bc3bf7904c2a952bcd573706caf1ee14420564ffc433c0f5871c4bda916f2530ac75819ade49fa1de21edacbbf6b7075dba21a84989411c566b7c356b81803c7215ab0f326a6b8910dbc62c1bee3af51f105fcdebc0dbc56a50b22cf81eda563bf8c2eff98b476e8", }, { "99444e82c6c4c47070b164f298ffdf6955ee5bcb3070b9aa95ce658db4db084d2056cfe61a93568b44ba7ddcba5d450f4ba0da7b119425a6628b3416663c638692326cacc5c237097db5e537122b465dcb21d8dcb5fe831789b72deff3907685c2e23187a56990221e755930a09f8d6cc065487563cb8cec82b9dc754952fa0b342c92d99522fbb39854e338f470a4b4d5ed2a39b8b6253b7001b0b953abc588d757616c7a5d1f12b1024aa572ef5a47dc8480943aa6cfaaa78064fb2b29830280e46efa418d0cf38f57980146f2482276c9b6b16f865b1606bf1131e894336979a163ba2e70adbdc746be0d38062fafcfe5603e6bbb55717b66a263fbd5cc7476302ea4a0dc6167221f745a26a309f5886934f4258965a0ef0803eaddd05e54008df8a0695a078b797be59f1eef95a658c99a7d52001d4108212ce5f18a39f1173291808c980b0513f1a531e03ad7380372b65572d3967af4c25fe54d99d664cb67e557fff05c12e10143c13b1bfa3e8db093ff832a7978ecd85d3971349e3c9b83939b73f0ad55f1f1162d0c106b99c0ff98442911bc15e9194f5b4ded97e9702b84e31b31380c224f392e5fa5c720a45f64cd7020e25a3931b5871e4c708e77f4729225aa9f48f9d876597d3e79219dddee0efdd16836021dbd21692dafe121217347cc128fc5eb051e6843978ae17478ef714957a84c74656ddd931cbeb43e32fb0a448acf2f90ee98d38522b4fa9aa36be4fa13306e799d4c0cb90ac0f73cbc018146d1b0d6bf48aa446a5e3e0502aae9fcbd196b36b6b7426fc10367febf687f05392fdcf878863de2e47be7e625d0e3e3e94e199f055c0fc65f76c41ede43231873ff10eb854dcd6ac9b550ee8533d16f81eb0e86471d4da69311c47255e78ac8e79ab36ce880d6b135279fbb5a712adc5c3862a356af49e9c10d5b16f4e5dedb80914868111e194745b802a0292c7c8564de28ba8e71a44f7eff6573e5434e65d496cde5b5e62cfa9e2e9ac85a164dbff5767983e71dd2661d37d9027a27674ebe3433731a606db88e0880e91ecea8134421962b3f68915c9f6a5e1992c56750f99bc313fb30cb89384c72571a1a6a5e3c01897b691bd70985352217fa8a67f3252a06205bd1a9931d1cea3736559572561fedbf3ac4c8bff9ebd7f3753ee69a69ecbac4be6357db7f4213b697a828edc716ac01da75c1d46098c7d5d6ae6f3f9a2903588c5b340c9d47c234efea21b700cdb8db4279afa2117677e824e627bf0f2b179c864ba823926a57825478395545f130886bdf2a7c55a2647a888c3998b750343d9cdc602e46b7b09a2fe9ef74db1ffc46fe27c254c927ce51b307e96a571da7f3f907223fbed2daedbcc96197e95edde7859f3b4ec6099f791089e368a68a5ba0917ddf4f50b93c0c839ea36cfc8053811f8fcfe6986e5fa9f743119ecd6c3e5fea1dae3ad7eb465a89e9c68569190688a8d56e4143ceea3b11fbd9de67173d5134ec8b0bd7d16560ba2be52345ebacedc01a2e03e8183ef91317d87b2e15cc6301586ed829d438e4ff1d074408b332c8ce60ccb6790ab08c228807509dd4b39f2c227755f6b039f5cd413ad6f46c9ec2cc6a79457529d297b1d9e74ead9bedd9bd652fb31568a8e2a9e2b89e4e57601bc1d960360232cdb30cb502b950ef930d54c2c0692a684cd44b0472995bd2b41dac1553ae47216253d6640d2653a033a862f3118c5b5d60a662d240bda5f4da51092eff514f61a425c5b14b19517ec1b371d240cc30a0739273b34f18a72a69b1586802a7caa6cc8f5817a8a995695d063c9dd26c3d45feb0f84dc8a0773151cf9a537664f942f351599cfbee0558f441f5c7ad320cabe305f9aba570ddf6407749b6db42f9ce94526a8f4170e735b1dcfc5f0e090af10e039db3747aa9b4f1f26acc34639ac8b60557f7753e2c261a29852932901a4093b7f307319cbb228e26eec289898b3f8ee236032163293b8caf64be3f7ffed236f1da688d958a1bbb79dd45026884904bbb936c1ebca7aa6b0c68aa8b667dc1575729e4ecb4ffa82ddced2f4571bf902c52fc4a0ea3f47aaf5c243ac2a1fc19f825fde5d9fc8d06d97a351eebf4ae1846aa62554d57cffdb3f3377695338f8d598d723289ff3962796e8065632e7da9d8dffe2636cd23eac15a60568eefe3e77c561906555268cfc1e9342417b1cdf090cc16c79939b15a9311b0210094087dea22833f74eb0e35d44259ecf327dc84f3f24b8c2bfce7be0d97e00d2be88a150a0d557ff963b4cda60eb99935951d288768b4b2649b717133517f5e3909744417c9c3102c77ddd285976cba2c89e2b4f297665632d7c8652847c4625038a6670169772de0550066ec6c2018f503cce79a333ecc0a0632334df6959d2e3b052fa47c5c84d15ceabdc80bd6be0ea2a5a8d5e374e0e9a613369ca8d4cae3d9f98755560b27b2f6e47b01ba390f5ddeb732c22b12abd225e26ecdb639b08f3237e488430b3b39f0b63aaaef4907cd003a8f2b4c3bfd721d6c3fd3a5f062d72746606a529ba34251ddec4026f40d262e9d527ad84fecf5bb2cc8601c2a38437098aec2335104842ff1c455e5d17c136ece8d461d7a3bd9a60339c22d71059e09b3603c0565c0345684893b56054ec4d3db0bf15546cafb4a03bd7775c3157e7676bb7bdb7baf3100396c563eba1a12952503eb6ccde6b6d0a42d456743c4ddb97f5994fa08c5fa41315080eb6b928090956bfc6252b232f6e0785d233c3adcbb9370b59c35b0dd66005d516befd1fc843df8e68fab19858b91e2aecd1c8a88b0fa3d4c2fed2995ee87e65976b755fbf44ee183f9fa08848bea325807bce0b7b61e03e50b2c7af9b360532a17a8250cf6068fef0198738c82a5e58961c54017e343fcef7076e823d63b4deee472fada7989ca7a213d06a4e3eb2d44b16e5c94b1588321cf6c45a5a792938b058d667e1730f8386dfedc50ea0a959b78f12f2949b34b181f90bec622515227dfb8a5f6e89d2e559c0ba686153b218d2c50b67503018e22914ce9b49d3bdb7cf38172db1ea130baacd640c111614e3db204b3b50641d8978dc14b2afc27a7efa819cac6bafa8166d1c127e2237520d57ad38a80146217a12363cb1f8a720e328cd8f846d379ada43bd4865e4aa633c479bd448d205b2e43befa63486c717af84a733f1dececc127c047850aeeb8ce677612f5966e23d92c1d3c758aaeef82f862c1154fadd6766e1dfc780bb447732a5968c0c78b9af4a9d669338458b57cbb77910a24678092857c0b903152035bab6b1c73f7b667a08cd0d31128888de3ff1fed24866eb60beac19c1b139f77bf0b9332024999a2d56975e691fd7475fd93622119d0d725bb99c1d6ac604d6b6be09d6d29360fff9f84e5318259a67fec08a006d9772b9410ec6abd4cb828b898c625c2fc35c19cb9a6cd3b0073baec7b5af254d21de8e209539f560bc80ea38e33658a68262622cdf35dcd6618b9e272ac3644c91f27d372c6297d8e37201c6a86a7d3accdf579c15246276a0009ddac4021755f4848d10f714e9da86eba13f461e6a12edb1aef2d6117986120750d609682bfdfcb90ee3cde8be54d45f841a6dee2d5b9fdc4e65edb7ebffcf3cc5c8a4e1c6919ac57568be23bd8283319ce11fca3caf968b057432f163f22e29cac30b8154a646ca0ef4fdbc7770ee1451fdde9e9d651992d94c843d4eb2570975528ad9f8c193f7c681a43df28242547010e30d75fca04f39247c77d6c3715c25fc261ecdba16844bbab23e4d0482bd1565ca9b526ada9b8f5703661a84b23070d85f3e8265b2ce10750c5d798f1a8ef4d51a473ff4d2bf4be615566ac796db9fe61a224bcce05c31ecb9ab7bc43a609944a7c9398a7875609ddbcb556296f548a117847df7d0afe48a5b504e85b0d7ca589103d3197933a744fefca795e1e036f964a4f14554d5cfa0261e25d6e5e02f86e402906d3637a2352459cb1639f20faea6f0e3fbc6a39becb1b1b3a791e32e85e5bee31be685410adf0c11190e20b7a5119b90e83f2cc4f0de8898606bb6e64165c95d4c5eae472daa6836a888ee4d9a79de72b8fb47a9c9c0323a2be9106d4ee9ba8b3858c256032a9caba37af94df4c7b0adc2f8478cb879b6d452d73191b0fc1ce944df3f4809cbf3ad46eceb3ba4abd9679410f45c8aab20dd72626f235e7c0c934b4beb4507def24ebbdd7a507943c81d54bc69df578aacd9ed0bfd3b7809dec345ba084d88fa9c34d80685415a4d5eaef9b88e51432b2b2037186baf123a6257e47aa56d6531923d38178e8264dd315e95bfafd8dacaf901e354b0f58f135d638df2c0f32453205c7aaeeedf8c102e11cfddea9a98d3ac7c385d71b760cf2afeb1ebe1d64f0222b9b101893d11a74ed175297c1dfd188a2565fbecc6bb07b56ce3973322a965dc5a675587890cc65a71efc68fdcdf1a023505ef0bc0e6b12dca5860fcf1c6c94c2e2ec3a72b8a019d69c82d36a73738dc3d17d7fdfe992bc8e18cb5d3437f1f619dd318b95d1a56b6d273ed79ab2655d83e2dd63cb6f1f5987eab6bb21a7b13b84e2c619b36b842192c3f82c755d8af840675b0bd67a655d641b1886c3c9c147ac87615ff3e58085a879b21dd63c1616a3712279ec87d650a2eed665b797ad631f0ec312f343979cbc49b99385cfa92841cba12d52777df565545a1deb07800a15431c0987b4a543fd5ed6832e80ab6f4b4d9c9ec419932a6ded4759f5c7630a0b80139234b8d53117acb4452c60b477ad50157169a89bd796e2308baa9395b513a94747611c7978c82dbdf48d716c3ac181ac2b2a4702c02a324bd4c5e089d989d020ebec9963b5c721a95492158f54973b7fc1828181acb3cc8078ac095136d97221c60b847bd2a52427383ab68cd1f10b92738c13203fdfa0b78baa09c1837be2498667c459", "0ce980442336d0f427db869a6799baa6785b5e030567c588e2a7d2680e96c11b7f415fa27730969e0b1c3973b5f3192d4e773153def6dcc09dae29ac44eac7c42c2666a356fd4262197bd5cf6eeefcbd662d104423ec05c19a2e6ddf1834a3445a09e8b1062a1320a5e8ef13d6ebd03c19e1813ccd86fd68b46a", "1ac8a509db7bf4acb80d8d394a5abf47c273b2093f50f35049e749f3e16cb0fb", "47cc9eea11f9f3f9aafa23bd", "088888333340b3a057b05491fb2402301c8654948aa6d5ee1ec75eb045858c22056fef0873d6675f897126052923a47a30675b266ffb6181cbd29ce2da3720e36a227e4c6e53328d789913c0d9cd149a6e49293996b1be7d6c513b24d876445a950e723ade3efc36907c840b9b8cfdb1503811b4044d931a0009b381fd60a5bf1e73d16348cb57eea672709875fb9d56908dbc729d5d7d322a17a41d0f62c9af9a013ab1e19fb7b6c6e7fa0c0b18bec5e3d3e92546c77e3753193389e5fcdb6a6a1896cba461343e71ef7a156b136b27ae6f45be9368301cfade203e9b53824d70f07de9abfea1968b8ff8489b9804422ba05ac3c3adf23ba0848817fa51febab5e9b5500100310479e710b663f064c1ef101c9a5320367cd8bc6e52081a32f070e7d3fd6f4210cdffdb9fcab1de4af5b06a7c6d191dcc12b25b3053e58952bfd1f723afbf570796946c1df9579ad14ea9c8c30389c1de4d1e845c764fec5eb8faaf4c558c5eb5113018c6a21ef653ac7d7f5b6c7e1a8fd48c6f423e9913436202da176a86731287db7331db055508acc94168888040ee37b3c119c8a0d88360241d68745825fe480324a944d56e7cd0375d4d33a5fe7a3863c2aaa899b2d24f65b70bd804039116fe959c32442c9f0b5470463523eb4336985b71125fe5235cbca0c88a6f92416d038e144de5ff8ef6ca749a9e239f02db505bff8e16fad1cba8b1500445f067a674142b6413e9dc0f432242d8301879bfc11fa86d1ac9992ab12319fea8b703e10a13bfd4b017496222be26b56af3ef67610f904f0ca8a3e7cc249ca8122735a542b289f13922904ff23dd197f8883c7ac77150d7331316ef94e0cf13b6ad95070420513599100b0a6d117640b781c622ed7ef7ead29476b3c835bd9dbda2203930bcee7ac01c3b9c89da405ee436ee652ddcc3e96c7f1a94e200eec9a4a226f3cf7ae5725068916e73b61149497d11dd85157f895669f51978d1bea8fd2afabb18d082365daba2682ef623109988b7d0e27ae57bc14d86603f93b5ac040ae52d8db404ee27e6c34cd4246f40eccf9d3f8637a4615a4006918b01d34709bcbebd02ea72958d54db3e87d69e6d783de2f1841029d6975eb11f9b076c247108797d5368c656f888092b82aa81aa26e164e038b359bd68801c22fc107e4083a9d85fc254b002ece9d4545310b0cb22ec1af04a7ee31d210ede4b605dbdbcb70e4301989422ef46edf63f9c96de9cb3f70638b51df5c0abe79b7af8cd97148f2b7bf394bea0f7bbbf6925f83b901b87a6079f2c3b38a98fe1a86dc7f48bf97553701834f557451df4b41e7db984a34432823585380b45c1b84813d6aa21107cae252923fb4673cf660a541e65610ac0127d238285f53bf329b62169f3e42d5efe268dea62578e97da59a58a1314a1bd46cf7a7cae772814130b51411082e30062fdbda1c9e14d6b2bfff89d0379d32461f3b8e833b105f6a89532ae748b5fb43f283fc86450404e8befb8442b65e338aa0408303a70e9c27a1d923d9f2a06e7c6159c50bf2e3ba5b035420ecbd9d0b5fae478eb1ab72fa714f99d00188bb10e60380fa3a3a318c2d359ea3805c2fa0dde17ee52a504f70d6b466bd38d1dd4196be336a9ab4a9e573d1bc6404018a119f688c1dc2a8ed1433e8a8ebf455ce3808c245f0220f0c12d28c771757763bd111ab829294e2429a6f7a59858dfa1fe0b806e986d40aaff934589fefd75ab91097a979f26bc9352267efb2d82c4738e4e6c451b0d5adc398f546c646b9e6b8fc84e91651a1252d5b805a857c7798d102d1e6f90749252bc53588348ecec0897c79f514442fe3b27608c95d0cba999a7e0fbd7f601689b4dc63ecb9ff553ff12eca3e9b26e3eccbde28770bb6aff7c864ad6be77fc09f81f90df6efd0c4025d0916ab5197ab846dfe6121c462761d9cc87112ebbca197b0a222fd34a15b824b7eda06a56a6ffda760fae5f0b527e2798f01e205a3f47947a4bd190f6abfb1dab2e3a53131af95d593bb57e4f4af506440cf20636d9fccc449d9565bf43dec8b6877337ca5a43900c1dc600c877b290342914e909aad8c5f0755bc25652781535c057ed5ab2ff8ad4322a8edf3fc1b5311dae6361a7395919725f4cd87ce0ccba37c64eb3618f9c5a53644ada569b90cd07184fc048f1b589eb29852909e75e7116ef96a268ea85c2bd257cefdde9222d7eda875a2a3abcd3a02a1fb470ba967b20beb54914b8b0c6ed464ba978088d7f8b30d098966b0bde82a8f1210f5d0c3405c9bc73f703134d0b6ee13326f65fa0b8154f4e30808997d4afbd060285942ca1dededc3410a099881492b5730ab7bdc2a4cfd0068f67766d60b5d4945f121459d2083334ac878d067bef644b9ee427bbbd6c9351d7b019bfc051c05ac301ff3792a1c687546dbf6a07a0cf56717374bfa1191c22b7753f6ae02392f8aac9207d1ad0fcd57c5c8b35817574b7dd90a00cab75f508f8a234eabce6618305f94746cb6a8573389d336bb67e1b0d2b6e9bd3959ef344e1eb245b522c35222813b8c6e82df48987436b5592025e9786ca63b6d1a064223bfacf59ada713c2a3116611393aa8446ea79b3cb21e96d13b659ada2d6524686fd46ec66c1b4d8f5ae7831840c9e3db64d528f83a1cef1e0a586a783f8306cb261ed9c2905493e74d35883fcb39cfc5745c282104cc3ce804999231d13e1bc6f2c022f05999fb57575bbdaf00d7a990e17dd2f8b9dfe66a637b42f58ee49ba60f2dd9718d09d7025b6061b2087bc35f0a8c884f5b67a5e18c2b4e857d3b48b79dc7cab6b72f572d22987566238a7153ed6264578424f1ce091fd05b7f14563fe12c76104d3373367af3ed3aca694a21127b5912c0b7eb1ddf9d4a9f03f660d49f7a7f0fb42797fd112414c3eba2b75a04282dcb9645191fd3dbe376e7f60ab40bb7ca1e991053a1912854a68d7dcf854201d1f2c26c6cfaea32e29d80847e6288274713d2ca973b91dab97884326b280c6f06c65b8fd25d314be29139961051a1d8699467d02b67991baabc9b05629660c243ca3b0477362d5e6bf9eaa33beeb52cf399846c77fcae11a89cbfdb2058e443ddd44fe202a3ba5c2efce937d78b9639781b8b2b99077b433189cf3b0733ed73b59bb194c9a98c5aa0cba6e71d1c5522f193defb9e31fd2cd60f22bedaf7008c2fb0b55a8dd52731dfa2bc69b40f835ae95db040cda6a4a1588a5ba4769edfeb7369c1e9a3b1cda293255b4942881d94d771b7b82460004875e71be64c582f2830c5e80dd6de421a311c5852f4912bea1451b0328d01c7029867cf9af99284cdfc1e1f0aa0d8c19ba9bc035dc270b45724247137da5d3fc4daa09e7014fe1439889968eb23fe124f067825d5f7b304f17a983580e009e0e51630ea0006dbc74a30b512cd9eb4d0b315a0ffdbfb581609ea9661b0007cd234ce43c17c92269a7519bfe99c2ca94b5cd3e7654946e67b37d4270a369266db6804336a446022677a024d44cc02cb04108292dc12f790578a0d61cb6fada738902eed3afdf1850bafcb279f18b5798d7466752c6368a594533baff5dbd17974638ecc41753b184845206c79bbab84dfef148eb7f1390f8cb7346a14c88caf540c241cad11ce8869be3bec85d029ef490fc5edacf94fa962be39a33c8efefcbb6b43960d5bc35f8fb72038af3801466aed141b50e9ac7dcf1921f7a6abaf320ff02ac34bbfac265e05e27495e6e027e673a48a874e6f0c33827a050fa21c2efa789c1e3df2ecda95fc52ca7be35dbf17ff6c73f37cb236e5131542e002913d177ffb21ac450e2542e24b894650007c36c52d90f83731009a7c3239ccf11829cf0fb6510d9924e927f14d6a06f8dc772fc9b028a8bbd2d3388985f3e2609abbd08434c46642b97240c9380a831bbafdc5db77be63a1400cc9a4f7362a689b07a77162022c6ba7a1bb9f0446a0b6b460ebdd9111132694fa5f1b29da39be66c5179849ae9720b2da0a012d4bdfd1b18b8fbef0d5c32b92c351dcf2c599f069c3b53f622fc8e904f27584b2d97d43f779abcde6dc1413c0a677dd187b28cfbcf7fa6316f0967b53977432d45944ce8ebd2e265c0bf6b2870c75ae808fed52aa35421ef55667ecd6f9d279c9b91c9314bd9411bce267d6ad52b1d910b3e65147c3eb6021a0af98707408e66bb11ca5abf5e34b2bc85b144fd06ea56f5d7f8939fe0cfa4862e7f306de069cf85f4aa7aa97c6848594f5a6dbcc718d2af77497f4b9d5ffa217fc301127071e9bc9c2c9222ba90e286506e384f321e622f05d81c114953d0f7e9626b74f4a6bea8cfb86ceb4575e5cf4fb84e9efac8291d1f4153ad3cd9a34ce0ffcfbe30b6829c0f986a4f85d63b602ab99ff3934b1e0c46e55d56eb479b79ca0729beb59aed783e9a3ccd55db8d884733dbd93f9fd7a7209fb92fcc49826b2d4356ca676f01b0981637897b3d2f90f37bfd73b214a398a8e4e2f9e5abec01d8192ca690191255dd8304a2d95a69331288bce00385f462e942f4d694dc3560a263c8ac2b5cd1d2c63b90ec67c32eaf5bd947bd8ac730da9c09ebc6888b0b4f3bead157aa9d31c2802df8ff0e4d69b7abfed6f184bf35a16ffb5677ddfc4682322128932d57fe4c32f21e190e1147d8e673ae407b1dbbca31331310b299e9f3db08ebfd2dad3158562c2e47addcbcc831cef0194ac8ba9778d0103c2955c886d439967bf788eae688f2a7459b0ef3bd16808e8d768b8962a24588d918ceb2cd1cd611b504019f65216beca212f44600cb7fac77216b7645c49f18064a3acdc01399315084dc9ea151ee28534fb31628d190bc540ac6b6aba572ba51aee89544015e6fbca2b3c2330f2ac1f68849e99e1a1f7f523599eaee22720392ea52259e26f1101614d4edae481b3783af4e99082d75dcca549049290731bbadd1ec0a93789ad5c9afe8bae44e35b3e59e562362964", }, { "0410d1f8bc890649c250a3819766f4496f339a6384e34acdd72b3a87266edd2a7eae223a372883f978277a108d6e59fca1f35f25d7a9f3aed42d35fa9b12241ac04754f76fd8f0e8ff6af88cd851887a45e89f1c9192ca66bfff605b128575d2ccc9ca3ba1ba23a0251b2cfd6db577b29d17ce2ea998946997f5c4a97a397c46024681a400a54425c071232d269adfc3b1adf15b4586c4dd7b8886f5c1023bc348bc674961ac6e221d914f432c2f06dddcf738227dfcfff88485ed45882809d0e57019461c88683919b87c45e78223c37a5be5f758e4f0dc6add22f2062bc2eb9bdc31b8649af17d526ec339f0e6fc6a41e26299c65276302f982235c3e5205ec1521625ec08a23e766577664b73d18d5533261c859c4cb4346feaf7540a56155c6c3a4874dc86ea42fd518d71221ac65541e2dadd2f8e129e7809f2835f07dfcc4128401dae2b5fac7ced1d9e07e3f348c6cd26f55b3893d4418557a18c366dcd5eadea0dd84ab95437d6f23eb9e5877fb2ad740ee507e2268c39c7186f34e5cee2d0dbba1a940f516a018f23e716a399c317a7a81f89cfabc296c432cba900ad79db67936f76e4d97874fc5f8a9ff84eb7a0f6d629c581ec5c451e27ef1ed468f93bfc68b2e0412a543d89dfdd812d9421236a4be9eb374531556c207340886c7b84d42d651557b952e0982f62c5c383e92dced21905174a5a836acdc3f2393e770d6cdc22c39575a42ea406f36889dc9558aeae5dc5f8b84862850b55bf4accccb6a8ef793d641d6b08235f70ad3b0605eab462afad1af80fa003645f4d302b03d81a7d167e9a8187bee0f76b1cfd7006b2d2b55fedad6e8db1d3ecfe031702dc327ff2b0197337d7542f42702cb276de852b3d72d9acff8a7feb8882028a5e340950e523c41cfa184b3d8878effe56742994e60240e58cbfd01541d39fa007a9f0ecccb409c6cc540354ccf35223677cb74e7ef7330bb60420f7d7bf97de6888cb343cd4fb0928fe5df5f1b018592ccfa7aac6dab57cded573b5950b94fd935f32cf332dd85b2b36501de6687612371dbcfdf77279d647ed8bdcf81fda8b7e0c5ab139330d64695d814fc6f761fd141dfb0c8f74e2d7616db3598d8de40b993fbdd272ca37db27b82aedb08bebc4a8e6d0385ab20fbc20c215ad50fab8e93975bcab3ff38667abb0545b3b3f20e325f01b80a32a3cc3ed51703d4b2826849ee22fddd5b544816599dca0d8fc84feed9f7e90caba53b70bc3f457eb1adb89fd0b67d2c0ab53264430c61d2c4a1b19ea99a9b453fc6b5ebf5fb5ab799134769c9b495c479c828bcc49a8f993c3127d5cbc31afb89c0e78fbc323755457ebf0f3344d3ad1cfc59d186e96ac31a9298e655b3d1df74b95f30fb868631053540388a13d597002f689708d35a2365e309bb96db8b1b94ea4c8060c2b165f7f19e72056409159371ac9c44f6bfaad9b9567094d18c29bbc8aa2c8b5b82735d20f55284fe68186004b4a4fb644fd52d9645b277c1dc238a764005c1d2791ef36e71786cd990ccee4571d9a9b1aec757e479cfa645e320bc33268e05af9cf90e0e616ae7f237c637a99fe15b4ea8a3232262d96855fa248920a28ec03f77ce4dd93925db60ec030a7be455ba9d08edbf6bb717b1a13c3ac1deb9821e21505c0a8971d5ea5dd8e4c9cd3a845a336209af191150ba5d9b8c2c450e3a765e8670d7f846b2461f971fdcd1942704f620a40f4204b99f9035bbd543f64b927cbc7a74f32cbb12c3caef955f169a45374e4479430e08d333c4a877baf41a27a0849ca3a157b6651295fa71ac94b6e3d30b5d160965e93d2a81b4d575cefd264399c9e4e17059f4064465b2d92c96ac27e3b221499b5e642d033992c236b905c072faa1e34495f9890bac6228330e4016c061605bbfc478c30e1b8534c49af54785972aca2d144328b0a540e3b3810a73e26acfa22f48652d53ea521875475ffade8ab50b9f08245fad753350f63dc4e898948ac7dcefe520ca47394f8e993a6d13ff68a2f78cf294f235f5f863bad10c4f5bc41c3ba93cf5e076357f0f7fdc136f34b656b1b8ebb3eed1ac429c7d4edbc902f7f4bc24ea9c9b200b9a9fd7adff0c6445ce1d2171fc031e3e9f8b8d6b448053393c8813d91333d4bdc3bc5bb2b8bff876cd29e8b92cf6f7bc727517b6f57ae031f3040b0637dfb40b8c1fbe44cfb6bb9cd0a445fd9b3daa1da2b1c4a82cb4da1fb8d525e0a4d9ec30e9aa75b951214621c58c1f60c9b97e6c6b330497e7dea790a3cd8158a76d898107ff3a5910707ae60c8a46c633b522aee83736d005de60b9abe202435f8bc4577b0eb08b7f2b617bb5a831e95d6488459bbf15919d764b39684d7cb7c9310f343fbfcfbeeb212a90d96c7a26c1026c5cb171ee4ef839785076e5084026077455c73404a2653f333e9bad555cafc1a9613387a02bb1287c380d7478238bec8943208de585bd18b448b6099565cb3ec70ec6672a778fa6af9d1b17b0970439da24c7bfaa74c85ecd8e5852e42391ab2258024ccf91e37f2f0e86df958b197fafd12f4a45f7990375f1665a14f7f5374ff7740f89677ea8660587fb80916b30629a7aa88213bbf80512421a0a37414a2eb549b81cc85072cdd87e4e69d97ecc63f974e60d20de0233101c3d475d777602b12e2f797e9237570085b0e9f48d4dedf233eb1301ed4621f9736946eadf599bfd79157c0b4cc31bc273f5c6f133a4e3679ff6797d3c9b76aff4bd8ad40726c1703c3d8b78f0974b748d0265b0a75928374f91b48c2d2b2c11d8b6e5efddb75009e4db72e562be59efb0bfa06808c89f585a43d4776ef08947a77f277526777f0b52f1e0b5a03aa560fa45c8f30e584b58ac1fc00b104942b7b86a3cdee1abea349dcaea4e058faeffc567e2c3b03e1c5c4ddc675e25aa15de1442bcf5ee972a8c5204ca5794694759c13a2d716839dda61635043bdf1a09e35cb6d93b4df3b7a00871f79cdb4ee69c79041dd14deb7754107b8fef8589d2d240ac1d8eafc52ea847263512651bbede2fccaf6da816b1b892319817bb6af9fc17078ab6cca95f03cf8426249fd4f2bf91921d39b8cee24af07a52bbe54ca7fc4422a310dbf2149b763ac0060fb2c59154d2cb0da1ad4892279b4e0ce7f5f92c189c3ce48e518ff48c4ffa9bf2b02d4792f84534958dc6bd2914ba010aa32d133f6a07bdbb87a237c7acc3ba5cf101efe947147ed4eb3bfdffe5fefa991c0dc8760586218d286944c52d0f221e0101f74826761d01a20af187f9ec1115e9e98bff6fbd7c8816c15d33c07f51c171490997bf269951218ae92b66fa3150d3bd40336abccb717e18b53e8806fff94009910f202a5041b5396d1c339e6d075bad4ab66a0637d81eed1696e4068024001123204b8371f0bcdf0ce07d79f7c917327f7138a75947846fde68665e9c767fbf96bb3308abffe7a8d05512c81e39fa8dab2334f46ab9543921ca97be31076dc7b2a0d05e90b7f7610d1a391b442398ef56cde3b18737faa8f282572389b4fb3c55cb8ae6737257708c808bc0a414bffae293bc69cba702ce2959e1a30edcdf64985a4b0bcc927c5912f819c71cc9b1ff5d6e5929055be72ea5c8c1a4a591093deb5449b7e6b60109be1ac0cae472ba31e1035ae65f3214f50ad699a077a2de52f7180addde0bd78c2698470b1af13cfbf497d243c9e738c4cdc265356543885c5b933a299f01a5b5a9ecb0b4ddfda0c28573064f6a3f142801795d66bcd5c31868fd3207fee7bd98c47e4da26bee64e1617b20cbaa34e3abbe31126b06d5737fc2b577b19d255a519397f3ff8668d0e7d401a37e368729e4b83c5fbf01c32ec478967605cbc0675f685b5eeeb42fc688216a0667e1204c995c9c485e6f7712d80d88edc9594528b1907790549756dcc8b0d32091f36d2b4009639e68daa130e83a1ea18353ca34f431c548d91c1591ccf8b25eec1f7a3c18ddca71b87bb290a5c13229250c5e193e1352072f6798ec504b3b4c6aa578737332f52baea7bc4468fe6d8dfabb9728cee93fee50c8caa113f5ed7e9b55e21e98d73a377ef68be7e4e965dfa50cf863e6285236f11ce80512c573ae2b55bcb43cf6ebabed6783c250f991f5f68a59dcb2ac13a3c8fba8dbb11c79dc6236809f2d7c4b0ad3cecd24b85f1aaed9748b8c109f2fd98ac8a53bd52f18475598d67305117de8e03b0d988a2847539cc2efad520f86dcd82c08ad4b10e490b9cb03bedc7197bcaca55526cd9c8a5a5f69f7a1697e7e31aa76eee597c386418e89f06b0b9817a83d6cdefaf9594548b33cea1cbb585e55df3d3b66f0b1a88f4b98ea4720f1ef5e6ebe4958078ea0bacb8ad776e325ccb252f81943b9b1c2f54aad3c7baf1bca0dda1355d191f69c5d8163c464898116dc89201032d1e3281c8054882f60522d3a65831bf779a854fb0c195f85aa66522386625658457e74d5c2fcf5234f226da4a579ac1f11f11a1e0a6993a4dfe5c856481ebe9d8d2363401058736f7ad104104aa03f5c91496aaba2fe4072d418d91c2787a9b4ab0cf4bb65681ad0392ef073cf2fc060692b0c0c194c8eed5558098cdfa3317ab02626159e40e5c76fd64b2ef60b8f5f368b6b4fd7ea3d2d3236aa01d9db7c8a01929f9fd38557335b926251ade1a0d47d0c1444e6416218781c1a51e786dbe9297b78fcf0d0304c62929e00744ed4e14af926313a9849b2a464048bead075044bee013cbe318920c4172138560629a0ff4fd229d81bdc7c7fd1086ab17d6efd5b603a1991b33a55ca5b9e2051b7c140f7937adfaf474c2f284489d9b1e8c71d58f126eaa451407eacde9f0e86504f7de3ba4d830199a229de2bf39014baad6dbbc448501588ceb2575db0ddae005b81ba9914bc22b6d600e2c990f7843e553ff29d8008265eba7dac7b5b5a7ba6dc263fe0e262a7b8638a81f4720622c7361554b61d7b04c7f8b133440baeead7d51ac8b77d606fd0eae1c55ce7e8141dfd68d40ae3d8d2dc8a061085b4fb6d8a06263183869154618329be6b01c2890f2b5d0a0f25dcdbbfe2ec3597d79311edb943613fd4b59157df4fc2e1024be03d98ea3cbec7186ea9f4a431dc3743b9f0871b205bc0c1b3a001768", "113b261414b4b7dfa028668ac8b0cde5734120124991c54f4dd16a87d181efe2bc15f6d0caaeaf6ad615f59ec5c2833904a34b4d34109c82e10609b387f995430e8c13d83ac34310d838af9efa32d7fed6224c0a33", "cd762390b93369f1e207eb15deeaeb0036f5331e82480d180f84a76c3e44550b", "e88c14ef96c7768f5dba9de9", "8d6aaa27892a76fb05a2e96cef9a9b4b7ae0670a12cff95f7b076372456889fbd3b9b4fb5fd98b3bd85b247f15009be2f4e7a0329dd118b6872199b314e159618ede0381dd97db28743461ace1a694c0383d8458150a501d6c45f4b50d5b1bd47e61a51f9ed4929bf2e564f201ed0e6825170027d93e482c1ce268459d2f81cab41f0e7ff281430c16b34a29b5c76630dba72ab9e751bae41122b26121d91f2af271a23e818263f46e05fdd52f319d58330bcabf66637a368c0a8aeeb20cad1916d966e5e0b0de74cc67ebe57e3d1fe01e9743d42a931cb4b98bb762ea43ab937d1e5c42eb08fd56e70e911bdcc1ca4ca0604a329c5364b262ce2de282b4732ea657b89300cc7b7127ba4a2d08c13f581f024fd093ac09c2bc245be60c80e102405597fa8082f4d28cc954a93217edffaba3d2a397bb59ee89c8cc0f33eded78f21183bd1acdce64a923dd609a0620d2911f61e81fb2c8ccad8ad9d81157223253a121ea2bc60d6a3670c563fe06bd75688572b3be83cd31dfeac6b17cf8455267b481219c42034b2252977f32b8e6588fb05166498fa37d17c2b002a655b5711bbc21175348225fdcca041b1f97fae48fb1e222c5bb46b5202191c00666b7e1b2d84aca3edbee7a97dc0f6d1330e929226f8a76c155e973c1ab62c867e1f87be37788754e51825ba31af9f4722b5782ef782fbb70c391a664f252d14e49a805e94790135ff6bd881a687f98b42da96fd34bf240eae4914488af739ec15f13f048a7eb5fa94af14e8b6ac5fae714cbef6268b114813ca2a3920a7a9d5eb506a2ca211758de292047eefdb5a97e18530dcd8410495fc42abed91b1204d9b8ba9d6aed11d2d0fa0d931d46f93f2c1a560ef9f5f7cee1497be770d3cb07c534215cec12c1458bb57aab4d95cf4a15a5e3a3bf8e650206d5cac4af3193d169f1a57638d9a50f6b7c6985d42f7138b9226451670d7359351c2affbca65680557693d03458341198b8e13d0ea6abb7496edea3cd4dee2eb93695e668c7c0901c6809b8ef434e88b85a8b22cab6508b9560fae62900056b7c5c29a8c899bed45a2b5159a1d4929476ef350101317f77f02d48a039cf4cf01c56319cbba16fe908c49ed6f3face88867c0ad3703452baa7b86fe58a00ab8f740b4e8055164b0385dd3fa44502ffbb99cdd843bc3287ea468aafe4cc298a3fc180f284dbf78aa09e0a2f7d8593356eab016ad8dc505420edd376b66598a3d0aaa848fd68c4e07419b8b50e40febe2b6b17ad07726fae1f87e86abd01490a0ce24fb57b533c765504ee0a9ca154187bcf5e6828e3addc7597532643cfd992558d63b1acd00e7aa41b9765094217480c08c43f4f0b3f0127120699b7f2a5ac07c655b6143e467777cdad4bc21d4b57da4d8f9b9a7e4523d8c6fba3614b7f7281e80ff0f9004577adcff1b79fe443c80ca9655ecc102d5df6aab2ff6c3401f344b77666c59ac7d5b92bf4f1e2322f74b75e6ef2bf43ad9e018f164ae76a91451e5221bdf5b65a4fbbaa8dc31e6063b451edbbf4965307f8e65bfae87b15f2453083bea8484017228a9cdc6edab1a28834eed8ce07430f776b916b3bdd2340798955ce9ffcf114c3f6a88bcc4c7b6f2e3842426488c340d00f2c4d2d6fd3b6263dcf7a57f5cea6c77efba7013297bd3320accf033acc0833aaa8e8f95cecba469704214f54a1ed581349878a591f9993371f1daf92e55b2a4faf8f952cf785c687a59b3c258daef1b6d7bf9f904123c7384a859933c3ac31e33edf648a1be4d6264ffade860915bd118f0b9aaec2eb8e16b2015fc25e68caac77a3accea53b9b178f6cf48d15029fac12963b4277df037b7a494cb29b1d9e6d2148531a1f7360519cba5657c080254f130a1cc3ccaadb4298d7ea0223897e63d798b4f4909577cf9b491a82de0275a246bb1211bc4144574c8ef176b382262c0e087975cbef33cc616d32e0131a9efdbe8ad3d9cb5f935d3f4f409852acca22ae2a6e7450e9a426ec3b9183f93b4b7f89d850e1c7053c661936e0cde23e831a261b319b430da45772f0fc0113679d06f025983bbf37ecfba35eeca28de5ff4815a490570491266e92faaf8d0ad4ac8df106faff8fe3c8d050ae9dfc03a01ad177c21d7b653509a80369a668a97eaa532dc9867c32aebaf89ed36586e1ebbe1045347766a354a86ec1e8b2f30c8fdfbb6c5d549e7a84db81b73fb828499c5c4be0d4b2b7ffb197133a0ee18abb5a4e371be0ec0a6535507029316f8decde30833ca47493ffcab781d028edfb91c138609baf1054ad52a5d8ccb98b3ca5b138f253d99bd556afd80f71b39f36e0d96fba4e0cbdb18926894968aa825392f12d98b6497ff85a0e4a91c97f37ba1dcad30fe688b54008b925805104a61dc22b712685202ecdb073fad9b10b5b9ee2ff781f23fd41ecdec87f85b369a304b85bd2af126d08f79d8a9e2bff0b18607a95c4efe35941c5493c94e3f2f3902e79f4cfe84c138b83c7f32d7c5a125b28c6107921e8ac92f1af7da015b46a2f9169369cede770292eee8a5f40d080ea1c267c33cb7d4187093d486dc3911bb2d6cae036cb508e81ca783ab5e95cec751e39f3038003081a252eefa7cd913baf136d4e27076251da9cbf0c7d2586fe02b62ec786790ef08fb3ff3d79bd06868eb1abd9875920e14fccf6dc144e898f578b7295fb5f4e84cbf683722ce3597aafe3195e194736fc317ed03ebbb00d956ce89f7a41a334020e1a88da355d3b47d5bd3965a290f6fbf5dfdc8c8e6347b4eb85151e53a960311582235f3b546ca80a670dcb628fef572dfae0c101bc08c80f78d5630a793bdfe402592c316227f2333b386839a67e6ee8d9396fabc9648ea656a407670efaf80966034958f4a70fe7b920c79dea3d5a0ff05f3ed0516537d51a686efcb258520936fdd415345251c9ac1143a41be295cf12da5d4319e78e1c57ce20507490e5213ca7be92afca8ec8b6a07b33571afe6940daa2afb0dd4dcc1c329474ff8e13d740488e5ced552074fff695a04fc1b70755245895a1e9c387fd9514261dbb0f600ae03f4896e795d1e72f421d8572543243d662f6811eb9402b6a3b8dbb0f32de95bb1ac01b1287663d3b6a3f52339a4f6b27789e15519b2b59f2f4fc8fd33ad1a6e4d02cf0ddf8499f45746da424ee78e72847e3cd3833551b6e6fd6b1aa98c688252b57a1d97660ff006ea1b970a0b8fc7d2e313ffd0b0b85299ded47b60cd2fe9bdd7ebace4b0c1072cdf67231a475045990b35ec761e1dc1dfbd0c402296566eb4b9462979d33c9d652a9295ae70943f38adb212b48bd8ebe82722b1712ab6a3be6060297e2aa54e7d0158e4aba6975237e7c7a1e22b29560b8d262125ff2a6e5c1332acd0f6b5ba15b4a82d3631891a01530321830aa8f2e8ab6b41bc5b5356957a4d0c3bc3eab04df7700305a95d0f9cd18d486c675c963876b25b1a0f78e245deb40dedd14dafdaa9d614fb06eb2538c5411e13be116c76fbd3377ff212eb07c5c035612e4cd7a1de2ceafe95832eff88a9bdb3595cc19287fa40b8d244afe9bd24dca40db49893602a59640d7a1b8e7475825b09cb0cee111864deba9d3d1beac03664279910accb9fac534ef099e398d7f6e3235cef7685fd1ae46e47da093135741894273c0c3486197c26057044b10faa57244721328b47e611633d16d3e4776d90309d68ce4a60d3ecda26c9f39c1c6da67ff79fde4977efc5653d79ad86c3b53090003bb72e78aeedcf4c8107185d9aa65221df4e2104640a1a083845c01000370371fea2a6bc8ae43fbe290949da4e559d3867c16df16b143fdc807616f51ebce8d05bb03c2b0bd587b95e3f6a15d907aa9a5b11622ddf4c81ff9fda4bb49d3e9577551bae649cf64ac0cfd646b02f6f16cdefde09a55e77afd16c74e8a3d777d80b7cc42c51f618a3c467968631119f11ca4385f0f5713e37ab1133b692de475db1d44fbfe9d274b9a09e673dac88aea74ba88cde8db3c831e9b5a0f1e40261281e5aea9d4dfd48c5d9e173f4d9cd56fe7fd610909c838bcbe1d6c729e151ecb4caef511a36a14b03cca7ec5d0feacb4647ea5212a11d18cbcbedf78443127680ac0b1bb65120b4197570288226830e2a92b380e32387bbcd3be2c77d6c7722054d849be9de459cc1832ec3ac8e7f60fba9c81cf5fbad37d228eba137a23227d56cd24970340f2b7599aada9d2424cdba8b50c2b97244dc83f7391e2ceba5bc0a11ba547c142126c791265b33a3db6238321a5f3273ffb01e42adee17b898153e41818b91413ec4f6386ab3dd48db875afe659db9eac94d16f850ac179d087d93784d607349e8711f5f96fd514e8d096de8b4a74122ba914520e93a11fa4adf006700e122e2531e1f39340cccbab4862708d69c117d3efbebabc14a0231916ae1ee8285727c9fc980051360346d53dfc76aa5a11fb1fc8f36f95f741e913bd2cd1031e508b320abd2d3a62baa400dc439969eb44e6abf8223b29d4025c3d1ca08d2dbdbbf9927c625270543e8c0cb5ac5bb5d504d224e66a1895719e4f975d819a95e54cecfa59ec8e385aaacbb023772fdddbe093afaf5a75e63a62d51926254e5b47da1e9b05851196644b9180734d05810dcf3502747c4ece652b67674c02aae74f20d07de2ad5993b3a68d10207eab6be5be34e52ada655aa96c1d82df9b24c2acec35e8f0bec9131c20d0ad8936880af87215611b80d07d7a741a12d8145bd05066c6ac171afd8684b92f72237bb0e4ca4aec1ec280e39f36928852d5d8d02fe463acbad8ecefc103083fd4298f399bb254e7bfa166638460b760ccf2b0f5fec0e3875206bdc8ce096274643824acfad71ba06441c74788356caebdd2208f6f077b056fa9d85aa4357e93bf064a776f5f3b0f288d0afdc51558c8f25cbee17247364c2bb24637dd69017f92bbb43024d9c773439626a02bd0cd44136a642c9c5ae593f32eada790c31a6704030f2e07f1173cbc0dabc410bf9864214c298a6283b3631acbf94b8371681ba81eed1aa81ccf258252d7f90fe733ac770b9744d0170cb554b39e6c72e05919cc237f8f4d7f3545f4d2732f4c9473c77401dcba04c0fd33efc73219f31c08dfab26abee9a7cd4ad3584730768fae899fc", }, { "9c73ac05648e0c50a3ea3a8eea70841e8e06669c1e7520c5e25e093769c4b005375c0a9cea16ec8e00261ceb96a00924a66fc0c4e4e089c63e93fea857aead8e0ab82af4ce1682cf3c9fbad23fc3f7e632b7aa169834ddd6c7db7e1e892cac93e4d787b2ed0a812aa93bfce8fef3ce30ab794743ad241974ff989288c43e1ba815a25a03acdc2d5517293e161d0c46c8858d0b32b124a6b0bc3838807753288cf6838fa25fbcf876e6368c0342d3cbc860d6fa12faa1c2b7d9fb37504e60dd44e36ce74229dfb80f1545125718dd1f78b31a8aadbb4d6494489ce596fcc2dbdf2ec22157a1d966b61e780d36552daf084739b602861a96ceb67b65b23d40916c02b2c3a38c2a59aaa266e1f8939000dac9b6dc50d1731e87ee833a2cc3cb98c57e5b680a85c1b428289520bb252096efd7723fa8e55d2fd4e16900a435986ab3f3d2bd799471a1bc07c1772ce10d1bb8805a6065b8903999f9393d2ed1a7e1c57a9e3e0e10dfca17a04143814f5f3acfb99a34712a6e0a24a7485279ef343e69d27c77e25b41f9fb833d7cd29cb6a15551d5c77b43d19feb19f2640926a272f81eeadb792bd474ae11f080ada72103f8f7ca733a9b1325b50589be2b2b3023491afec246d336f4e4277592ce9695c68d5f39c8fa4cedaf51776d7ca29ea0ecb89eaefe71e5f3560c68e8dafe7da08cdcd954d626418677b8f3f45b9194474a32f548a4da3bfae6a3e2c0a25f602e3b3a821160c397d77c8bcbd71c5f1e669213af36eeea30d48e12953071f55eac2fe0bd8fa355671fe032f6fc9214632428125a16fc8aea8a9c7fba0d7518b9a4f876349ccb9bbbabcdb2a85fc60b83ee1ddd041967efa4036e5e10e377c9886f40bc0b0b57c7b724795f843f6a072e87e532a04c21445090a360731a2afb896ab795750e5c2c33d58bb714f5be427ca3751df09661402604a09a1eca95a8344d3daa5b99d68e6e6245825704c5d4a73af197d052d7f75778917542261d77735a21cff3f75d6159a3e4b1a7a9854ee376e6b3c8bdaa1f353b957862b2efd50d10a40007026261a546124cef979ad20d8085d53e30f5736b8aebcd3cdaa349ea474af249ac53eef2653ae1fcd5b3095538de9368d307d45df2a19acd44e3b78c2da9d5d9fcc4cb61feac5dd35f66299845bc0018c3d476b6761083baf33a4621e41cfae0e0c642de729fb2d206db6a4b976a635b3fd911b5e9946fddceb6feb2d2f893b2bed590317442037a1d6dc5b5d72910160221cbecb53bc983f1c736c3bfc9757e9e05af1248b28d651f521af67b2a0d7e4bd86a0013338404fabac7b9833c372142e6338a98c0efb7130aae8e34bb0c80937680a7a904aba3be735d41af9462f17b967b13566bcb697579f8a9340429c77baa6e24ae1ac86d8d25ae3cb9112e34a7a948fd141367898c5f33c0635c87de06f603b510cb229df0d0d9a9e107de88b12686c539ed4fc54c8285afde0c8ee502919a125cbcaf4c8c89f56e90d3f641f97c07326956f7b5d87c65b689f39b8b84359ee0f14d2c7ed621ec67f5e2a8ee5faf21c805187edd95e3941ed62fa95a65473a569566d46b87c0d27ca37b6b022a8cca30a4480d392ba15701d1015b3648958cddfb614983211bffc4966ac6c1f691f19bd9fed405a02c06712d62a775f73353f3949c76b6b7757a4ee0410fd6d20071abfe46b09e72b70f9f19b61410ea67037e037934bbefaf09cff018a5c218176d165d1eb5cfd5c46eee7b82fe65ea02e3ed7b18a86ac7b139b7c9df79e1f6e6f85304ad22d97190c7ec12c651fcc835ea434d92ae1444e7cb0dc644efbc2ae70f2f94310805c1d0f2d49643d05e78baa1c54d4fd99137a49efde88dba1374c94208fb4a0ebc1a0090b043610ebc1bb08168ff5bf936ff9834e825eefb9ab73da2b287b06fa2b0ff52f46061b07c1131e4108cde478c767b749b696f3520acd8d3338842d53941282da289dd1e9a0e02aa9be0f127566c9bf2d50a27f6b6ffc9e9880bbfc14ce7eeee70cb0c0ad90fb474efa69b46123638e8405fdef65fa7e0e7b29fa8fe8696edf661f9003a08b4aff85a4a3e6d817655c1d533b834da981b8c37c38abd5977b3ba71b3f57967a471c2eeaf2f6f258431fbb7e92f91814b1db80ea775681f282290db170942bb7b04aa2a331950b74a4b6e337affb4c51c6cd4c4e13ce3095e73e4767c2731f72bdb225ff572163fbd8573378427fda194d165750d487f6bbb63e1378a132fb6ee5115e3c32b2380b096b735bdb4d651853bc7928346fe3ea9df7534f2a4eae1f5ffc4b82ae738db7df0103ba4e68c2a2153bca499bae2439a57778cfc616df16032aa8a19e26597d275d2775b5ea17cb25d204b18028eb25a053e5666ac47c6def151f7d4b68ea62c601d87bfbe04711c24bc34274be6815024d7b7d01e7dae10cea6e485348ab195a83854663cc5826181b688cc9c091dc1e0d491fe51400e20e6f2a51a7d56af258e038bcbc80e2c4ac4b41661bd33229d07b39b59f3aa79d99c1ef41974a33e02a7cacd6fd8f9b99cadd0fd6a031f070bd3a364c64ddda0e9fb94036f374171de0b3f4ee3380780e6d77d50db9d58e670fb4a364827d631226a3491a27602808141ce657ad6e560ad62b088ff086e6f03b8a64bdf7c7d01e7b19289279509a9d6d80e50aef3b05b5561e4556952c46d0b6ab8eae735eccee77e570e1360b7ea38c53ae6b8eb420e4c2663b57827228392db6e79105a47f7d89e06ecfebdd63783101d3bfb5f494785acfdfed41f8166faefdf0b49260222c4080ec2c6e4f949f41784f076ce37fc7a34fa4e547bb44e6b9359b4b95cd67d64e4402ac83973bd50f8adc7c6e4c34019bd8f6d3843bba3d7155890712e0ed5134e00db877398d86b459f312a6272431f01b057446bfb1b8053acf181bac79408c7708f3a0867a64e06d7786849bb874a6bdf8fd6daaa572d5648ae100f4318d6b3a811bb0fb709168e817ed83c0622a7e5b17ebf5cd5ecb21d9ac32ddddb039083144c93cb55a95ad72732132d54bb120639d1620ebd142b58d75835b35cc6367012c93c6772963e9ac852c71c0dda2246ab845469997fc170d8f62334bc5aa4ce23e036967674303ec6f75bd3d17d197d026de69beda70bc59d2ff95a899d28ac7e5e42f4d37233996a8e6d3b0b86b80df49ea8e145b4a6e3e39f3d6c3c6518bac45baf97cde23037709d737b242b8918ca31f90fe59ff2c83e2f347a954d3559a8e4f075c620ad36be20b1e24b3afa156cf3255192171ad0474e4adc9b7f35436325b92945665f038611e5d14bdfe7b7d20c09642323346a717f460dfe7b5062a0098be66febe9f5fccfc747aeaeff81ba08e5dd2b1a489c998ea9970afaf9aa03859073707a686c492fb3f7ddb27897ba5e75e578bd82114b2ba85525a2002927909c970a04035334b64b1169c3a923211e0999db8baa26b6537cdcf57c051c0ca1b317a5b66ad96cb5ebd57994f99ab202348d8ddeb343312f1f26ab2442b8c5f5cf6bab394418ef2fed68c3e60275e836027515b6b946e5d86d91fdaf49c2a5182d5051726840a156a8653cabda25e1dd9af693533d782caa09295952ebfe6a194fbc8bb7fc2c0da5914a506c6f31490928dc5d6554890f5eb268b09d671bb6b6d7416dd36e7b78ffc5c86b34fab43d22909a87e5239643d5fef373650e291be56b89b9d90431d8c9fa44fdf4f83a1689d59d6ef833b1ce31a44197b36ab298d53b51ae3f8387087dcb0571c340874c1524ba0d576bdb88101c1fc387d25b5c0dad0b4d309255ad5d5b1e209ba56db0c927bd209399a8a3b5c8663c9ac199a76ea4f49e364a4b93a569b3400e20f0d748adf7db46a07efc68e43802a5d1a914759eb2abe8fe3e8d67f2cd7612bd4d5a6a4535b1e5b3ad4d97e54f3db7f8512c9603d87e01160b6908d8df1b952c750071abb1565e5ea3f643f233faeb84278187ff0089150bf21ee4d13979fdae796f592ac5b88869aecc5be1c64665edc8ececc87502d36720b73859313607aaa561d56a195dd3c7292fa8f0750ddd3df9ca056fccd9d6ec900f45c1454c6ceaad4154c69e288dc85735b8cc42950a3c5f0fab2be8811779905c3ad5a9a6bf56e7141d863caa4e93e0065f229b695efb790926618b3eda1b9a15f143bbb09aa3c4b72900617793417df364185cc213d5cc3a375778117212266356e214f085d8a7aed908256c4aa25faebabc70ce913c08c89380da06920069e8e27dd867567f152f883a9bd2dcfb8097b7f065482d6d11c0edebc67feb3068cead403503c04b324885ce1a62c99af9808a5ec8b7cbd978b8c43e37b06e9f7e1ce0b31fa0fe52e8842002e6e99cdf69263d31de080b56c0cf94f77f0397fd1f77b13e17af90ff33b00119999df802c33534a13d3ff7fd0e8cf58e8f8c8bae033cec1aec7d191f2d1a39c7b731c97a67fd1ca43c13a24b9f97d92e2364dc26a1c9408d4659ac7373e53a2a1704a47e01c0223ed4c489735b62a27ec67ea46747e4f48d3da101b0863bda9d3f7f1b413f3e7f130208875e6a29dc30a78198ef658c7ca32d7d53b4b92e51f8ad6d39ecabb800adc0870b2ab0e85b5769f346ce7fc371ad40c561f9f3b2f2a01f2b8ccae48c78a41383cfc36b2a1bd41d61a39c24144965d9aa5ecc5d506c7c7cf9476085bf049942d35caefd77821ad925b7fd3a006213abc1e008114c848d45cbedcb8af264cdc5c07bc338fddd1123940e5d95717040325048439dccd1e298bead22b011ef76d26a390a68161b8bab29e8409a5880cca9c8104694e1282c9fd64f50e73ec6b9a9ffc31115de9cc0088400a2dc806f85487fcbdd60f409ffca584fb197156b40142e512a0dedea1571ebb74d6b26d3b4a59e9105929a055cf3540e8a6a79ca7ea71ba8b40893c9797e81c6e9a7999d4d382e52cac95727bcac354616ae1094552b3d0a33d0d3ac4e547237fc0cd54944039b0eccf335889f6aceb518de496e0986783c564be8a4a05bdc9c67b1e5abb480b98173ef091259d8c772b611e0c09758fceea3e59243406edfa71fc452d4450b55b8fa5ecb543692c6eda3a6ad3bfea929a18ebbe5ce2ac4754989c71dced37286cdd1512107e4e7f4878da1c28b4beb2dd9a712a8d1d61d1a5fe5382db8aab4857b05a783e98e77711c1933a7641fd43dc6e6e597bd03b11ce8e94aa094fe250f03cc92ed5b0a5e7723911e87b0f3c476d9aa0d96adbfb395a8fd353cfb5a4cfe27deeb82e849f90bdb17928b0a5702e4010f7aaece2d43772a78b325d2ff24f9de0f7bc65974d2348c64", "bf96bbc17abcd1f56a9f22ad164d25ca72f8c996f1a7a66d6effe140336da4f20460b47e1c8573872496343be35a055552ceec437692b0e4919224c4ffc8b603286a8245eff5cc148b004f6e5a54c4ac22b0f09842a07cd332a09732694d3591b8b7d6a7ada2bb38a30aa7fd5e6baa811b9a195d3a96306d", "aa2f714d3a184a9883f4199e8e33fbc9c92b36fff2d59f07a9d0d335d7476e81", "36c79f9f14d431cc8c077439", "873d0617c986dc9d83e9cdfc50b1f916626a9d9e1c595dc7ccd99d1e993d25d89b04a893c89e205952eef8f1733054bbb55fa5e1b07135787d4fcfae226737b50cafa2c11276e8708451be9b4d7f662e98ef6b705c5c4fc64588728eab1dfee22a0a92bae61828a7394977b0ae8a3b6d0126a23583fec025becf0a72a28891391ac1495732a7a4a1d43a63ed8eb37b280b6d886096fbc4f77aadbc5e441e996334d0e10cd7f3dbba9bb7efb147297986509a07735385c681e0543186dc166291edc3b4664f5c8ffb0965c85bc30ff5e7769a69609c69ebb68f35d104bafe3dbd3e2a40e13865f19bca3612e48592aa930eaee29440b4ebc1c0a59f1c54519857c929709b086bfddd6d4a30940b592be48e0067976099efe71f45f956182dbb300e8076e1207baa32d59c1afef7f34171bd66099d2d7f07b39d16d0f8b085185bf2554c6ad66bcd656f07979e8f19575a116f5c4fb9700ec3b46a3254f28afa1ed51348c1af6dba26fd398098a76d7bfa2ff195eebab41330ef290bf75205a2ee570a2fa46bbaa74aa6ba68a0e63e2731dc1974eb44794f3c89ba58cf96f7a070fcca678185711d97cd9d7d8202351ed589e0b05a7a190e60ae4aa109254a7bcf7013f8addd07a64145e21226795ff7c7b1c225f40ed7c3552da8eb18b9bc9bc70c2e7ecb10c8b20c54f04b6e27b5044a7a67b558407eb330f2083444375c022565c45fe817dc00c7d24c23db320d15949b0b64fbbaedd310e73e423fcebe6e1e98a5cd232d97e6466642e5e3b23f06525ac1cdf8688650cd366b1b7ba2a9033e62d836b14bb73717757b76b9673671bd3d3b2a56628f5a309f3b86ad32abac0590c50f7c5a22e0a920d88dc9fbcb3add08b900a2a2fae4178aa100a0e645ab428e0e79bd90baf4af2755e48262b64838a6fbc21226e323c0a1ba5703e30738fc7b5a7df9eabec6199df5ff6ad58f9df5a734ccd6509e53ecb3de1c881732e26e52ab848a0335b04b25f2254aaf8c130c78b0c9a40b60d402673ac7ec7311d0b00c45bd176bc73ad81c2478611804f59e3c145110aacce922e473ef346f8acaabdbb9f313dd3f8d0a937d0c048e5af789e2e09a816146f9ea28170909caf2572a2f6e2d0d511242909de2815e9ec586b2d12183ddbeb7dd70f32424097e2ec28b4ba62cf78f547e2057a4c050cccdf6b582172343742ec8c85e2847efb1595bccf89ece3b3ebba824d2f097b1987ec26c6e5710544739d54a714060fa91b7995cff0161415eaf55758078772c0271d9d282354e47a25b673eb11497a6ed8db82267d65ad47412300ed525af96f943c5336b1de88676dc346e7339230032463d305b0442f934018bdf0242768511d20474c6ecc82fd752c0c0ca5cee1f3e06e679fa5835540f97870d47ccc6bab233290be7a3bbd4a73f1dc7682049bf7b3cbfb6687479c18d246e3c07161df5c889ee95d39cccd989625a8c9e80f951f8b1832f6378e05daa8566477d7fe547e49ae6e822a68de4df9fc4d6500d5219c3d3bd8887bd7f695151ba378da17c2e750399f7482973510a386721c59683a86003edb9f0ce1ea89bd7bb8a25c222df7ebedcc1b56c8ce18f367b2cae720e0591b477f6ffb498c3d7ce59cabb1b01d7cba84d7180b4b2a165d4b889a6ac361720e768f2913aa50b0b5c88e55c35bb4df4fbc4460338809605f1fd445a2bcd97ec1d2f269b5e779a18c8f215bbc5555c745424484ee5436119eb8754f5e9e91f51fe715353596baa1fbb0a690e99691636e6027cbd4b7be752bc278661e2677070ddc12dccc262d3dd47160345de51359ee8dcf2f61044f95dfdaf323881b2bbff68af6572348f786f6e52d1309cff871ad58148307d7eaedc93ef037922b6092ac62171433adc4934884efdee3052ebd60ee115f76f9dbd0eab7c4c0a77b4ce8078209d23d81d957335f331965b556ebd54732327b5aacc899f9ed0edacad9eb98cb845867f249efb0e1a5fa2483227f78decbf7f1f32d060ab0c01eb985d83920b2cc24b5f9a0d5d869e980129d3b78277fb87e5cda61e340a729d86b6617b8828dffc7c37d4c38080ef3515c2784935973dd184e0a8160f84bb78bcd8a5e691760be4a4d41ed6512ee436ce24650c0e17e7d74b5e01cc39b21e21514a84db262d673f24a82cfd5dfe2a162976171c538b24af16429bf8ed5fa8e37f89ec6e7d63ea1d83ac1087cf89e8f43161f225108889e922493d973e36b510074533cb1cb22174d21c4076959e4191a5df880a8b868b95a9cb5151a7ad47375fcd87725660cc0b59c88ceb86984941268493c49b8aa2baa8c531ecf497853ffc3d26b926a379e72188e246d42073041fbca453bd558f328881c8f8d9e099e898a912530c4be499f2b32229c359ea10e0befe6d94cba5ddafe51d164898166e890b22fd1eebd5724451511dce1f8f7431d712a3f1e50fa5f609da686253311af255b84b2106b09b803e94b51729cfa0826869945d46b9606547e7e33fd9961cf15b400d0f5e01d8fd4d92a83ae526934059d4514b9e0005317a70466aa0b6086d5fcfed201d958a0de55fd23f0919ea29b8aa02440031a9fc206b9feef362a73430a4204869354ec81b6fff92eca97e7f1bb12d25228eae466b8137b4806895ce34b57dc14bdcd107fe160776b0e5daab150ba06976eb884eaa574da393af4de355381c7caa4f611a2ee70a0c78df93a4276f55e6281997b4aeb36888a6d9638cc95444047e5202f41f8bdd787f1ff44a648cc7d39f05e49e5d6989fedb194c526780709763da81a780db0d1534a466cce57e11dd3a4c0e273d9873af1040d52a90e20101e1f80ef296d45769d204cd5417a84e022b6b336675d36d9cbdb16b0cbb08f5e240012967c8067c92f97f981cd19d449084400d76adfb7c610abb73bf21e161db04debe6665fca79d71c8cc50adc3ecf0e52d07773478ca97b8e9821a5704dc58acc647a5bc618d2b681f17942c46c266c73ec211ca403a7d47e42e12c775b370cd500d70a4aac7124f5f6d2d4ca78e1c17a96426c326bb60379ceb0c84a86200f3b450e5e9aaa11f45440f5260eee7675a8b9c47fbc58cf18a651a1dc7b39a911442504f12c103054bb50f15381e512dc6e3af7b414b3db26fe767d83a2a53d7181fec8f6b196c7874befd6628b31797ee3c9260c7b7853b137893e36696e2a47277add98462ea9a0edeb7d2d3c0f2805fd7db64c2c7eff353ff2b36f4de862a42779ffd4dbe77b6a79bc9f4ea3e909474ead915fa3fa990bc82b83a670b163e79300b627fb91c4502e96bb9dde00f716ae6ad14dac647c9f7c2e5b2e505708b5fee996b8e9113a8f4f2caaf414061ee72e76b8bf47ec4f781bd7c589adebc2c267448247e30d659998d8037783494a1fdadcc819d7ad7ea2674f75e10639c3d3055046a00814ddda0e463185454a4455d60b9780250183d591c3db6f27373cd2ce4f02f206ae10a8c32d71226e7cb8d5b05909445977164983c0073434d6c0f2bb62bda66a16792d6e53a49ccb5ac3e285a6baba935f30e9d1ddb812a018ce04f29e2009ad678ba72b6a7112d6e7cfcd3ee7b058ec954a6fd7fd01018a6eba6209687c3130de58147b07bcfa02ec1caf30b59daf87db4618b4a5fad34cbc8014a7529b9458e05eccb9a77ef1621aa95513c6fa4003b0877ffa6d48805e7867dcf53447caf348228ce926233f65d553146584d6ff3dc3ed3296db9bfe69dec6a07add13037b3aade118b2ac3c52350b9691a6cb32356ad93377059fb8ceab68de38d96876d6d383db01f3cf620e47cbfd471bf6dd1f601210482f7c3bdd4c3bd37dd0a7507e1f0fe515151634813dd4ecefe97b52eda28e7a7129993b0af311abd3a07bc463f3cbbcb4fb0eb265a5835663fdbab0d8b8b5a73837ac98ced6582348fdeb41ac8ea9e36f9818ab9c0a41bac1389a6b518ea17df043dd50550f32471645791bf59855ed695b84919aa5cb688e569122786660f06e3a919ef9cf18c355bb397b86710c367362cddb0239aa1d32d489328e4bf92b3abdc3d0dacd76ef1a1efa28fdb848e708aed6780e2d8efb19a2e26fea56b4440dc3eafd796896d73fd150bbd967871f5e6ee5db58995f2f85cc2a15077d7d472bec2e30430af6891193ef03dfc7761e2b3b3b54a72d4f1084a8fc541526fdeb0633dcba14e9485b43065aee8750397ea88d9ff13417149e0fa145be666e6f4afdabe7ad8e4864e777c20ee7a2842db44dedee22f3ce2f97d72919b9ff6059352083be816a7515c48c5140a99af8e81b9e18b10074dc73dab55fae66261421629c8e323d8134f08beefbda555660a51e4b55a9ba4573bdf0396cc413145a941c4175aa672586f7676027f9fe211db87fe07a23962f5b1ad8f566f0d5b13c5146457276f307a02e1e13d00c5032a06d225248215e4bc4be1b672f1eaff16ca95da42513fc4315c7a6663f9101aba80224acbf0c87fd3a2ee9dedd1808c1247c5bebf3cb8d77377a508ddb484ed91203a438ef5ed3ca14e087102bc5f3828d8c3437ecf5c92eeec0331ed93ae33520740abae9b7bfc45f097da70adbb9b9b879e46a7d655dbf75d89773f737b66fd8a8c13506cff7b44bd85dee279ea7053f3ed8447fe79c400cf23726fae800449d27af5e342ecf776378e2eb449a3af27a40fe4a9806487b81c942bfe1a4b0fc146c971a13f83669e0189e337cc9fa2024864436189a9165ade6b864698ecb797ea05fed0d60f0ab4b92cbae36c72ccb5aa45337cc02dd086afed9e5522ecdb75ccf389fcd63c5a4abbf60908e39cb3268c76a08687588be67a856a841eeaaee8ed016f6640ef0f5acce12ab8bb58dda380696e3fb22d0bae0788c4fb79d00cfa5ae3e479dcf7d08b45f4592c2d2a7f8081d5a9398659613ba4932ebfd7382d516b2648ec4ff4477648069b9b2e4decc89547c16ab82a0ad9cf293fee5adb17cea4c95ab7b8e386dcae6acac63ad0d1d13656dfd97d5623dbe45230de597751321bbe5a03c879c303fd7a0d837d48141decb6df4f0865717628c85dbfda29df9a8a69b2c956c75fc66e45c08960c23bbbc706e48395057f989dfe675305067b3ed8d046db339e504d5b2bc978ab4dc261d8afb325c5e794ec79d63d8db53f9dd24b623fbcc202679fae8f7d39f7f7e0667b142c714b6a723996e5254ad2ebafd63c3577f8909981ce6b3eb1a6ad67a4e93c45ac3b34587d153ec5ab67a2697a9741610d5a176cb9b5856bdccb98f69421061c84811dd6660495d9f30548efaa69e36ead246d997c95bad0ca3fdc1a08b4be31b12daf211d3e29d585cdac48af8f2268ec304bb35d", }, { "ceb1f819497c0d631a9c9616655f419b5e3470fd3b19cd0e4fa556bd26cd9df57e960ec7121b2a2cb7c0421c1f84b77eb8277bf341490190ee574d1424eb09a281176a933394bfea5502077486bef23ee66e3127b732b7a58a04b9aeefc35170dabb030d4fc3f8a4c5ff194bbd0b89a379baca30ec81d576868f25755276e62c31e93a80ac322571313ebcee494592c3ff5cf3ecdec962645887d9aafdbfd62ea910af5542d4c7731283625bc9f41ec85012b42edb1792339e6cdd9c2bb3cad4c4792a064df17a5f74dcbb3dd0d90620ebba4fc6d1e1f9704dd60c798ad64d4e5077549d68cefdddaab81a7a91209b7ddbea43accb3d1c191328929dffdfeb4f5740ecbf0ee99cb9a1b73333d7ceb0b2b8f35f84307b9d44a42fe1a30ecdf2650dde251bc8c1d46978089c50d64c028f40611370ddb0b481df9624ed63165370f4788bbc396026b268c2023e0f04cd4f66e0bf439074c46f0ae85d6dfeb0ddf22868af61c8d5133097156fa61a3cf5801db5c3ad29871d336f7aa06d2a7d5f52e50eb3aee3c7de7bdc4d21f68a1776a7cc3954f5c071282febc89c1545fc672a0a1bd8eee2b769be048ab58ea12b356d658a6225fb8a55e752f1fc97ed64c2f87f9ae661514f1f56d9d4e47b001ae865a44b8a9fd5df8628d183bfbee781b6661c9cc76debe6c3c5bba840bbc228206673aa05498a8c715b0f3019f6b2d05cce6c233b5809ff1dc4a75d7f69859fcff94ad442d460b32f6fe348659518c16385e49fddee9efab2455732aedcd17dd51b5117efb2ca1e21ae6787437f48a7042d46e11be4dbcd2932ffd70fd154e4eca5fcdc57c6fa79746100b8e1485fe575a5c79089a25eb2d55d89e42eddc81b82c4f7da8bf153ff5353b7349b161911bbe0a14483fff6585d7f3c8b5c04a6dfc99db9548f0c53e25f0b16fa212f0bdd10ad2193ac18eb09972795f42b3bd3f4d98c4868989c4af7a760f1c88ffda59faac73256df1d607644f56a70303d6409c9ad716149bb58f01b4ab8ab475e4af1257d47049aa77adf9ce54fcd22b3d6ec60484da903a6991ff052ca37b01428d5916fd92c17530bb3385a805b0d57476e9f9417a23ab1c12a038b61b3a0898831f9615d10b468c3edc24448d09b8f3e3a2355dc5e069e880929eabcc97344fb6ca5587c5ac1404783848f531f1e915941e7359fedd328f7fd12b3c685f8c1f29d1a6ef7dbae3e5e32cdb251eb43aa2d2ae0cc18b3f40fb006c2778cba387e5852ec4f2d9b8e8ccd5b3e1f4781c974aca940c45d35d30d3b9584c750bd45a80f32f73dcd85c99ae107b92888839c342cdcf88911cb974d611b14b1d85a59e88c502559d6eef3b7f5addf7d307bb25c57aae669767db6d798ca887124e159b0317e09076cfdbe61aa9ddeda189036703b1cd9b1998f88325910a37ef1fc2e227a382ae635e847df8625b99eb6ef0ef10ce7a2a5762ad7d03a7a4e2b767c4df0b477d6e9601dc8e6438184f97193ea7d7a8c22f1b6fac1f0740f1beb8b68db40e0b22940cff2261273aa0be43df561b88184a9377e6a27f27942dd04abb9448b6b6ecb3a60f14dd39b58b8d94e1991cf9d3a071ba42e0e1d71eb211ca466a70fd4724a34639707feefbfd73dd9680d76a214924642a063b38b85cf30eb763fbfe889f34b20fa4a10ba214d938a5a092c6e9b73b13bd664c75b34f746aa360593c0f8dee0f328f0ad4a3e40d498490007e573b8204a1ce7a550deecfb15f18ed5ea6cb5dd95a68adfe4cab37c13b383f8273b1971580016a8df02a3f4f431c9de9e7ebb33244512080fc5852278081b9f4434109c3427441329e8071d19d0fbb74fb6ea73fbfc7c0ac1012d3a0948d94d7ceae9b0112ec43a16cb582f9c53e7eb0ad15e05ceda108fdb3dc9e585a332018d1cb19e4a75d86041308fdd8476c88e4826931601a3a5dce06fc16512f4669f10183d5a8d15bace4649abcac07358089aeb1e9b8fc3776f3239d5442d3be33d532097e13651af7c9a5b465ace9e626889800318447b8876b45dbbe1989e1eecbfb5cdf5067c71a0d7b7fba6555d0edede12f7228d7f9841dc532274f24060b1f52da6fbaa179b81ce962723f43601d248f8f4d5778c1653e038c8d27828836d562968004003810e9aa9318edf3260272b54fca2e012f6c04abe92c2e6152f3c3e973c7e9abe8c3467bdc246f0226d1b7669bd577bb317c571aa8758bfb694fe4dd17ce78f091cf6c6de3cb601a9d177128fce8d42e652b490d90c4f8fa04ddc71cac300d3dff699be3250bfdb2136edb0057af3ebcca77ba5b3ca34531810c5e2d4c5b5b3bc4e71ee9e30cac067b7706c326357fe0ad2a4bd9cd811b4e9d696bd9b4b70579ae246381210f879c769e5f9cc3cf8d70e9c94ab74a55f5d7bf61a17418b6edb6db4147fc40cf98c75de85421b7d192919add48e5334ebce2a06e56b915447fe085b7dcd677659dd55de1f705c389975e56e0338a2ef07ccf5ec3786407e8449d9011641786f1ecd4d3d3da975d61f5a442293e6119ab20686ea8cc7681010421226838a95a157e2de948c536aabadafcd4095dfda48e5613272289a8238dc945e5f1ef30075d5de096131740cdf23da1fb8b9fa009e5b321083cd93bba9271909460c09bbe1e8c54319394ff85c291814e21215816d4791f01424abbe4cc4c792d0d04db1b812f4d24b44caa76de2bc50f4d1d1611862512d87fcebd3c0b2659082b2423bc5360d107ad7b8e8ba7438ae4509105d6b618af25e75c51e272aafaaddf1e5a227f2b2a2c96a8a83dec23223cb428136a30b290181ee20a819cf52f6c03798e7294a89f3b5137693d5a8b7a0ea38d78e43008fc4eeaf6d077ebffd3ef7952620e0af1395c38a289832df391d1710ab5b103a1ffeea8c06684c03a74399cd63797c770e3f0136d8331611502d21fb883136a82f2034358880392fc3d2fc274b799e59b89f8f90d2a5a123d3c21e5bf3540323743858fdb8912c7c6329a3aea241075ae097ebb23c8cd50f4ff46b42486e65bda6beba5f4fe6dbb30f7e61b1bf690c9f00f7513c83274cd21bb71563257a20cc38da2b88c1063bd0849c8243058ee205853342085a8edb7545f0d96a6af936a3d4612b95676665eb02e72e0875100dfa444f039eddde1422ceed8d38e6c3dbba25064f8c6cb5786f9ca67712b7840cfbd40f99b1edadd4bb9a61f48124cf3b49d68bd642404eb1dcf428eeabadfba6810a4032f8ed06b38867a7098c7744d54dcfab8f0ff941ecee69da9916d54097e080cad86dd08bf53833fec4aa4399f7124586223ec70e2c31e8c647be06df9e86a976f37901e9b134e775de2a0fd53d545c5f92236dbf5455859c138b7bb1112427049d29ed4f5dd5c43cffd3113c276d9bba910879e55efe817189fc239a204a9ebe738c0dd161d10d60a51e9dcc8c38861d41ff029ffd841086803320a17ebf5ff14b6cc2ac3dcf0ce2eea9af7ae23597233599c2321dd2b99e06d93f84989e75e30a388f47079c2af545d96f270e064a43a00c76bddf2f5be5089a69a138de844216148a1eb0b413f58d831d9b8967df297455e7538442388cdda12d157fb25896c6e2b47696c76b234a88bed4f09dfd64f2e4b77627ef03049030190fe271a5a853591ee9218a0c6b12cb3f02683d665b211dd1480cd44c9c0566ace7d751902babae14cc3821374bec774d54b4b4afd5d1811ede556a7a5ad02642a878d2d32380e7efb9082604f49d51495105f827d77945b5cfaf2f2980566b28ce3dfbf1bee2e077eb067bdfa4cc28f5d2211ca99a615e69118d9391e3feb9b13cb4a2fa9682718189ec612db889228aaa3f3345a091aeb11f41420240fbb47caf567646d9e7c762d3288f8bb2b1165cf049a191db5042fa9185fcd180b04d3007c376e0aa3d427d66d10918821f74736816044366463df7cb3ac94cea167cf1daf2d1842f130295e40bad672a22da9238ded69e241395f04d5e3c3875b8294faafbd3d90ed56ff3e01c5a0a3e349d761273143686aa26d408620c7d1a35ccc430a09e3f750d3256298c6068c0fdded270f308f79d2fcba591d723ac0cef703d8f0e7c051bae5b453abbadfab98bcc297ed4201b03ebc195c2e441cfd3b10c63c08868db36c320707ecd6a37593661d70a81f30e6db4a32f98e4fe6b950ace55923631c8f95138781fa2af78d8104fe39242f1fff6942e8e782dfa0d37c863caff9492f8e5cb70046d207c4630cc29c20e1ac105aef093261d8d335456961e552ab14d107cbe14e9de912f0e5d58d16b729270208204469f917af4e710123c3bc38a4b3f485f2926f058344db105b9239829441a2d8ababf04aea615c0e350846d9bc3b5faecdbeb450f38f615f119ad1b5dc748e88107ec2fae01f0915174feec37b3e7248ed2699d0a5fb2fc785f17d6275fbea867aad815acc8a6fd3ca4ea7357d197e5a30082ad5f35a9d894c0aebb206c6487163c9cc20442c040e6aab33d7b4b221e4ba4cbabd975836e353129559d8ddcb3c97876cdba360da0e0c1dd5b0cff7957a444027db985ebefb6154453a221076c997d3954b347f49308d2ee14d1676b75ab6ef365f3de54aaf398fd96b9040253813ba734829bc78a6db59e3f1c0ab4c878a72d6b8681157919130fd3171126994dcdcdcf68955ad64af8156702c92f7a715ce6f7ddfb70f60e80c92691efbfdebc8cae252108fb6c0010d303d9027d4a5e63413b5fb2316d32fb93c3ea52a2a7df50cc0058c76c58d73f5bb041d9fb9f3c3cda9bee0c0920079ce4f1ef8698ced664ce2e2b3b86027ae2b3bcbbae5bf7ea3693d9429cf94938dd3a2763d3f53937c46763ffee6579d018358bc69182b1c7158a09b18352ea618c11c45f07fe97cb65faca535f43237879ae3e0a31efd14679daf8fd2ce25eb8f32218fa20afc586a98fd908d3fd804cabbf56dcae272328011b252dfd83e5f0a5fdebc6acb04c5540255e1322de5fce9db5aa4cdccd74dde8990ae51cefd6c1edc1879971d3efb1f94dc41b2b23e9c9d89415b46189914a229b2f3e8b05ff78c68711385a00e9534dae6f79d15842aaec575e4ee0f098028bc74016cd3f8e93c6a0cb21a0b574ee63e367343ca9de28003d76e02d0ee2b8d622cfa3615d3628fd02499eb7bd8c1aa1f34edd9c2d059c6a7c7c978a5e4f60801e03e17c3a09793c5217f310a30db1965b8e328893cef20f4a899aa8d9fa28f7fe0a733813ed7466046776a874273ecfb57158483f4a588ad4f232adec5ba4ea651822780596de09fd54b1717bf04130619979a0e3d12ab7c35d64afb8099a1d21bc952653742f50c8e1c244d10374329cedd27fbefd37815a9b3112a4cb2fc587c4ebda381b2b01fced45cdf0b9ff8ca7d10b65ce42e728de183a82e369486a2e3345664e70674a5dac174d6616d90de8e472b62759df057119875483cfbfb103041751747f9cd12bb31e91caf79eb2db1168026a4707dc618f30", "e45eef9561f3acb3672b4f38570256e8cc4d877e2998e72b022e33de8fc20f7320fe0882f2b53559e084923786e8205336a7d15f3fb88a41e7bd20767f2feaa02df2221fa7577988db0bbf61f3dfb429868688c53e130725d0279c505686f083", "475a44cde0cc931edf9a44b0c1e0001766f09ade023dfe6b59a6af800e549b55", "7812a320691ca8442767a51a", "eaa577bd67fe79ce4586f43355c94528e306c1678946e4f7a907d2a8ee7f4281270502522119a8b09b6f05d864921cb515fddf6a1000fc2f67b52d0627998591e2acf5b6faf71c278e5754b2703662ce670dd049da8d6e280c2b84d6a9b29ce28980563c40e03381a49c54608b72faec9b272ef05cfa41957d9eaf3e944b22610c725d8efea90aaac6e782848d368ffc08784d7fe37ea1effbbbb34952def29fc511fb10a1282bb0b6334328e4d00529a44de3259b522553a07d524dc75f431cc9670127c15670c0df419826617cfb5ebdd8788d5f528a9eb1e61324eac5c1746f339aae2e2e2fae598642a389da671482128acf2d69814258d83de98f186468136868b729aa5f0874fef2ff2575a1f87439d64e049e4d0637e9c99ecb7275417af654541306615f30b75a6caaa563e4790dfb28fe9f0e7881ea2d885eefdba99efa7f878925ce7d33e86d888154a1b03189429fe20af8fa3a68d65ced9b690a709031121425cfcd7e1890ed9614f9dc3ecbd0e38c6c84e453e3204978ddc1ef8d7fc6cae28c61a472d8e089e23209f0c36e80c994af771e6505e72ba90e5543f6bad6dcd31fdd468b13533a0254e44797825764ac1f63747d8d6ca019ff16fa732068ee94be382c46b168050ba725379df31a98ab81ec8eb266a3c3f2e1cd95e5f12b3bc79b8b435e4d94098c6184631cec57e9d8913458889223a2a4541f34d2f9df380f34c3e541fc587f0a6cf08c82e99476060eb84709a292f4c7a8551bda3a9eb6735787dbb9d7f1e83937c2e0e49f2cf6e0ab0ad84c40fbafc3c7e61886a8629bea816972fa0afd0f617b6340b1af19e341875e97565c8eb0b25fcf68696ee674d2abdc29396bfd0f282543d2b72a239c6470f76d3b5bff6d1d064e6e2d06f9deef2aae8a259c034373efc820f9a2fdbce36cc27f35dd6386de3b49509d0c305757257f8674d958c580a09e768c0f6ef237416fd53c31511badb2e7cdfee636508482f01899e72052b46b5d844799cf94708520178cfec2b61c8980fa7dfaad8915b0b75ce6eb57ed4a01edcb4a35c1dfcdf8d60f3191bbcdfd522a0e321ea41c2cd87a303522d0f98b82dcbe53232ecbf0e2528de7e1be75569584bf2ec574687fde67ffe9827ebbe78f2e5bc4fb368f3c9b0f588c97f7a139bd82fe86eb605b8e29cee75d07b510da1b24fd62cd2fb366f1621e7dbf268b15937f7f7ea4acf6e615775a32c90733769996dd2c5aebe08ecba73e0bc4781d33971992b2764c1b08aa972859cb61b003406479423254a01ea85a348ef249d408157cc0962d1e24cd9c426e6e6a3784dec6fe935be1f6730b01e8683d97e21d8774b2e2655f85db7149e930a44524d4f86004cd687d8a528b6ceadd890707458cab62809110ee28f61a7277ed79dc41e573fd4a59fabf15393ed4c21bf4d5138ac843e80bbf5e1c39ac2d7f2147f35996eb51a9e835db63faaa196b8aef1823ad72523fbfcb35b5560582a48a25ab770e7528e4b3ef291e6f62f5fac916e2162b3b56304287e46839858daf322b0de083d1691d6bda44d66d085ef0d0ad364eebacdd0a43a4456035e58910d0b2dacce45b1c0beabc784f3620a3e4390c345df6117b86d4fc386523b7ceeaecc21233a2865ec6b63bffba6689fb3323402119db8f0665a4730b2e26ca6411db04f1bcc78ce6272159ed2665a286f1ad7758d6d90090a6fd320e697dafbdfef575077e282b825bd64a4dbcf92d1fc0c6f795154e8466ee4b318f2d44b6f81c52523ab68ff8367e01090c2623e00b4008e784049df873a35c29e0abcfae7acbf27236adba0b913d19a15b4af4996669aba4c656c317084347ca962ac8df15cd2f849f522016eb92de4de62944b917d88200ef9aa2def0d13e5f4ae09d2eb4a2d0800af1d704cb01975f6d59768a2b50e39e78116147fd6dcdfbc08354c1b4033bf6772fa127856a4072556a9f07bd7516d01ef41bcb519005c0a3b2a04400427ec033f1b52fe5fdc1aed8e2521fd0fff663e203defc39d7546281a98a502b8a470af16cc62a6581c9985d7ca516864b799fcc55a803ce80711484f6b81591d2402bb1499c95dfb1dee9846679c22853be87c84b4547138dc4fd46b4e79ad12773a5392540a595954112f0cb1d9be4d4eb3aaa4286b6c01520558d58587d9d7f0df3a0282011ce01c9c17111d10ad61b3675b1826c1ad37fc562bdde951b43f890555d6f74ac4fbdb9abbe8bc1e80bb6d52c13de8960a3ff8f65201265e82981dbe39e0d65cf3f1fb6c56e11f9786210383d0150a5e0cbbdb52ca8b2bc45c12fb572657380df369082685b3de9847d5014beaeef815d63e203cc911061eb53d89a312d187f9f02760bfa71083fb643f5d8c324c410070b7ebde250a185e7359837899bb1568a43fa3418f39c12feb03b148b924bfb98b99352b1fbad3f07ac8e4302f85d1fe9ee4bf7507972670ff8beca105cdeb037f1cc4f944d6ca869d0281653de5ee93a7362420fdba8b01a375ff08fe27873655953ec1c00f53613c6ab8b244e2fc1b6babdca5311428d06f57aa4882dc870165deff75ba877dd2a04d1799f26ebfac97a1be53a83ab77dbc2cd4aa45bd779f61b1283eae1a1866ec8a9c150dd0a4deceb2ddea1bc0f4206cd435600a8f190b999b952337d9eb2bdeb3aba2cb2e7000319056629dc1f00901f0880278509417223a3ea0919fcdcf12bff0771c7cc725bdca292068478ccb2e1f35ae8964e0601789a73e7e7c1769ba53f865910fc3d0085c922d7f7849d27b6e7503d521371351f9d7dfd5afc5df0effdf6ac49617fa228501ad72154a73e07781dc4b07765dbfa721d95cf1dc41e161cbd34fc7883a25e3ba6b03e504b2c3b98c8b12ff629b965c2aefc26d74faff7f784baf09c3fc38c487a9d1f5818261162f97e9dff70cf42eb5dbcd7bebb66d68f26d917ddf2a3efc0db1e3372b170b4cd18da507e44c467943f73648dba74db1053b53f989e481c3054bac22c6342fca2c26d30a859a1312e9c353bf921f68136de2b1589747bc765153927c31ebe749dcdff98b5da84c4b66085451b4c87fe1ba2142f98636bcb268c33f7b8c2b96a6525298814578377aa189dd73d5bb27ec5cd2110d8751c18a3110273df2595d4c3a00809bdeda70d86c4a8169b7010c9cdeabfbc3dd3266518226d0ade9bcc4825f18198c854de329fb8fe456dd3bf35d89bd9d2384f3f3282f6872351a18a2f852bf173ea4426de6d01b3ef4b4685aa82df7dc45b99617a8b8c8a0c65a2237b3eaae8267e1f6c453f485432529d973924a080f6a1cc2cc18f804f53209383ce3601ad9361afc331707be1c88b4370404cb7fe0bc538df04adc5c8d9ced94b4c474b19619a53dca3fddb434cac09ce10c0293fea04e8e1b19fd3ff3d174baa988d91cb604fadc59ac0b61f4f87bfd07eee20f7f3ffd96766dd6f3555cd48da7ecd71d2fef34ab082678bfc4dd007669b3fc7a937a5a46269baa7e4e4e43eff1b2b847ea70b6c6c23905d6fb2fbccd944251087ac00c35c2eedba30641797d36ef9d3cb1afc0e3e8930f5b605a847ee77106995bd44047294d04350194369c5a7bf246d1108e1d18d9a638be0c051f695ce86579db613cd8922e86c683c91800b9a34fe6339e0dd79472daa662f78f04f0151a3acd18f11faa4e1216222843b521fb998c8490ab8bab27fde36395b456501307d07b484b453b189fa339282a634af30fea99c9af8f877e61871fe743238b2cee6cb69dbd17d574b5106ebe4b0fde4ef42fab469a5ba7d62c23b67d857f1af6ac981c320db70cdbb6be41bbca60bb7a159ee1c85cb82e0a220064359c06c660b75de6b49839eea68c80283b75d9d627aa4500c0c0f21edafe4a2cf7ee079d5310479da06ba58b142614fe69cb236c51447d63db31cdff91485b46325c26d40dc6d608d46a5e2fb01df06064a022ddf6d5cce0147d5b2a5aba5f9fadc5e778010a924e00a13e21daeea2cd330f45536ef4f42c2e77be00bb53b3f9a93d3eb327dbf30baccee5d26849cfad654ff3ef2b035b78dd3ef42de3302e5514551a968a205b823dffb040ac9452ae3efb43219b02436d0761ca11470405510e534d56caeaacc40eaf9c47a39475adad266f5ddc813e71223800dd46fa7c02b078353f870049806ed7ba57b40b7c3c6272296667500c4b97dd2d7026698b6bc4985bc01be99e0097013a2632c71740888ffaf902a02bf644b38cf9a42528880d9dd142de967cc2ad3e1f1737f0cb8dc5c59c252496e8cfe4e53c82f4a28d9ba2bfa62b6415ba3e5e09040d7f3e3abfeba53e46575e8817ac5eca806ec8a84c7cf77c9fa86c9dd2940f5b96b25a92d4a8f894d4717c8f80a62a35a51d8511f1e822fd79e6fc27cc3f3097d9e3272447de6f223971657ded9e660ee4f8836359742ce7616fd0ca2de6656c71b212b34b8edc71ff36bc84ac4af58eb1adcba4b2c0cb31468dbd2c2b7ee6752981ee1d152c4e4a9b25b2ce87796820def34b662381806d2e4fc77f0b69d7a87de43d94d62a6a6526a7f8c588392890e96f9c51bb58b4f438eb5d197477ce9b160d1c898c89ab408b3c1d648be93b531a5bb4988592c5a8999ae3acbe586d947fe6dd507cddb92dff4974ae17ab99aad5aec9d07b96bd29489876f51afa67570e86b69321d9e565d86001514638403f86666dbf93f18e0a62bf65db333bb85a3ae12d8411aa3c2a423a29bacbbfeebb8a5bafd90436bfded16f992232360211086a3084d9fd1980dd96631820a2cf25c3ac5c19d164cf5ab9a852399491962100ca4fd640146b7ea5460b4fb9e46bf8d23d508a4eeb8a3e9fad8249ece3648c2ec7705a7414eb8e8d602549204cb437f589161fe40de1447d14efa4d738b775d0333526c845cef5ffcbaf5c957df1d8022176b56eeb198e7ad2dfc3d7ea46b125ed432cd04c77efc011a2dad8573345080d7c3cdf5cc160fbc86c4ee1959ee1b8258056b0f3d9343c22dbb2f7858c5f162f08cffdca1acc866aa68e5f1c00b74f66544e8a61e429335adf6f73e32fa87e48e1adf15bb6c7aeacc93713dbc31cdccc9b0e52f922842679494039c395cc1d95eb97ae4df3bb8aba9a2584d97a236f87cb22f00c0a078b045044a5c456e22b2b94a76a559de2672c880660f9785b76bcc2aaed780e05212415c6e73880ca110654ed155a1004af45d5f15ae8e5bfd4817440c5d3d5589eea2c6c344ca0d85d91460638b37f877ea4cbbed35ea75678ef2335a5922cc8541987cc256c8f58045028d33a1c4899cc32265c619ac782ff998a478996be6a0c5b102a664831b395a884f18e77885d860d6b236c52a8066d2ced25432bce79a31b23117f405ef4ebdf3517de98d288f8c3baf04b63b6817c46c14b646308e9f97170b7dbbf9d1a36480338d8eb7466df56feb6baef42cba75512954fd7e33961d247b7393726e46c6e94e156d5776a89ad3e288554470ca0bc4cf4d2d2b0c01ae4fcafcb65ccd6ead03df1d4d6577bb", }, { "228eabb5ad8b4ff13b10d13b27372bc2152dff149859ba47d9c89b741d4a5340d8fff5858a4576c55547007d7e2b3f94583ea8f0976237712bd2e5481c3988f5387e7ac2c3f18718388795b7b2d44b0a13f3faaa55311b800301c9203a511572cf8f349280bbabb9424070f415bbfe28aef8d20329ee842cef4d4c299e619b6ef1cf00718aab2accec9ac00155be2903b6fb07dfe98b0bd8d8580176b99ce4aa6be51cf59046c17ce1817d363fa63af5a241d48bcce064a438651af102ff9c6de4b86374fe24f1dfa66e16e51550dbb791af425d8fa601c70c1bb90e1a557bfe0dde730b0364eba9d2018ee751699ee219e13fa8874070935b29a1767e1d748bfbe796fe4b81a71e823605d39fa4b5b885f4610c34d1a090fa4106785e7a035a629958ad1b00cb9d36d171d575268efa1bef064fc0a6dfbae8e532466035a0c2cef96fe9f93b872f0cf804811e927b39818189412868fb104e2d56ae62f77031f0df1ae91aa11826991ca7b8af22f130a47a72cce36ddc319b32dffd294f2e192e490249ea1a6f8437173ce6392d16dda888a98bf685bc91b89b8ee1eabdfb1806fd61f018d1744fe8b03521de4bff86d4a811ca2ecd5be668e9c752a6c26aacc0cc9dd89d112785c25ca6a0a7a5267b4e37457c04a0626c8a29be30ec28ddacf47a84918bab164d07bdedae62132ab04a6f2c4e108eba9ab878caa4a1a7509521d427ad7f3dfa86fae8345dfb5e0d46ce3a94dec84f7880c7422468ea74fe0b4825b8c762b34d5d9b82ba96e0c7dcae01718ccac0044a87476ff031e3ee3c2c13f5f375a841d243c38cd9a354b6525527de1fe7e36a6e2ad95e5bbc4c97e85f8cdcd5341da777e03451838807d5dd2eb4fd15976783c140e21cfc2eb3e58e40c16374de0aecbe3e3d41c64417a472cba18762080a2348ec3f441bf229a932ea0ca7c816938655d0c81b14dfbf86aa600d0c68172fb0046ef51f601ec89309d43ad1eacd583f9d205bb1ff1a37a97b44b5e35be4945f52897eb2a74645b01a7f82054cda44e9fa9f9af9bad1a235155718713bacd08d354f3fdd95858db0040fb551e9f93ae399d5dc53a67e88bcd5a02d104dfd9d824cdd5fe262ed9266fc47b7e640f2c9d9c7a62c6d24b429fa55560aa254a824a0858482e771144d6d5b05539cf71d75bec3a22be75655e1ababec4dff9472a019f6220067374dd49252282e4945a407084633ef9c88d14833bd95335107d36afdf56a642cb739bf0a61ed53a6915baed78e9d74166ebc492b517c7c594fe6564550bb7108f43012551e65fbafc0a9874e46fb64b5b7aee0082a5d617a43b8bf9473309c6761aebc7f13b72ed460b522a6b0875b67353c705f99d1d9dc899870fcc90c632aba1fa9ced6d7a2368dc4dd3d4b38a5807415e00de6b9ea70525a6c1b67d04521efeeefc6c591fc5256d990a1123522864a029430bb7ea00dd80d283fdd6d61cc5b509221e28f73386803d97a38fb0182fd95b3b91353c6eb60ef2b3d5c8c0ab8dc9cd9be2b4cf69450d00e88cb0f0bc9a4be82b71148a37237ceaf945ab94c365625f58171eb15c1bb244a87335550d813d28f241a3296520046e65aff3291555786d7c871ec8a2d10d4b44429041c3cd6ab60f0def742de3d28393c5aca92b150697ac15504ee66d8a2aa01a6c63d7c719d6d4f94af2ed1d8670e3231a0e481095e425e6231c43ad36e3b7a3478f6a61563f5aa13237beb8a891dbb29013c325f7f91c1b055fb83c436fdf8aef49ec457946e6ab7e955427373fd9c743acfd4b9609569b591ec79c7ea7276de103a35a4a8a05c91f59e04689ba1ddd570b18ed046f785d7e4ff9fce7115ac814fe126f781828877208ddfbb2ebc919e6d1f6eb417f38bfbf22ac9633f75e58e560b85d88d0e4fad9b2e68c9ebf9675819d50c30c8982bbbc2f41e02690390bf0e16979b24e648bf15b18800aaef58c3c465f38cfd1e47bf1266c17b69523b7868d2138cb95c4bce0dd3ceb7c2267b868b6e12888d5a489fc0091b295b56a1c328b54fe1119aaf1e6d7dd52fa450b52fbfc8b84c2200ebe209060b655cad288562786673121691809366af37b76567762d1fc24f1fad3128b43c8d10e9b6954b2efcbe40124fc0a5b670dd6dd544e30263a551825282aa06be3817a8eeacf31ca8b25cba011d60b78d3d2462810764e4acb566ff371005f5481c9d36c991527143af2c44cc8cfc59c920bb4a281f2ed4d494d30ba4d900edf59e23be2f763072255cb6f1e8b24ab1d305fbfb2429cff8bda303617c034e71a17230d0e860420dbcf9fea4ab48557e4d50797179496936ec6c97686fe6d9115809e14069244d251d4bc9c8931e47e06ec051e709ba1df526b55d959b37a6f3408833aaac80cfc9cb99915eb7d83e26998f0da2492b986fe0f5047b2cab6e6d33a117df21e6a8ec7f394a3712885dab176a4d6095e5cf75dbd3f0077e5e74b1ff8b902072380cf172562884de852ff5f07c55856224fb3df8eb44764ab9284944b86ab6f176a863cdd0e7ab5616a14692f6cbf41bc63113b27689fc2fb145736aaf2a5b26d2bef3a2a59ef8bb3f3e4d360a4251d0736482e9ed7e189fc48c0973b6649988228c2ac72b23826a61cfa06b11f13c8555be6e433d87e20113eb74c94f0e51719a7b38c59eba300089d06b9bc2a72017668e5aa3153ca4282718f1762642e7c1be1f865cd9b65c6387c8fe496f1e60d5acbb78c2f71cea1f35dc955b1e7d1cdc9ca339765995d9e05dd729cdf58aa2a1451b633c374e5b6c2af1c8486ee4250a875e80e1f359c15130eb1e2575c0c7badb2af61378527fa24347ebb12c10bbb36e3c94619556b2c641d0ebb691b2706cdd667f55b8fff8fb46e3ac72f3682661a4bac2391075ff5145eb07d69d77437adec2d096c1c89208ab3e7a9ea6a0ff4a5bc1846b3683bd7c6ec4520c3c95861a5856b0191e4221c9819c67273c66729728f6035e79c0dae8842df4c0c27ada1ad18b34efcd55b94ef120762e87e8c5afdec80d5788e83f0d1533cdd7aea8f27f33266e007b274f6d48c59bcfad607e8b298be2b17322be88558c60033452826778f167f318b660607bfb2f285cadb385399636acb8f5350d819511b5e7931c5f8483529d3ab3fdb5ae2dde0ada918f1327c6c0dfbbf5ed3c8afef171910dd0169022b3cad5b08084dd5e8eb8ef1ecb17e48bf69f80e3db0ae1cc7b73d94b89696e3c3443ecb4c7ca12568201744d1858d90ff759f2d264d49edf47772bd0e0990c14dcf8c8a4c2dafa44dc6e92f4c66b03bdc4f68f28ca2d0811a433e184cced99a8e5614ca83c46ec18b47e0c7ae91037ae06c6d6d0f3dee19711c21cddafb5869416d23c5219296acda7774891877f3f8d46155d39f43ed10500ede3afa26943b83b800b54a9752250ec6ae173e920002f365d692a9b3a2f9b27124ac97b8e81b70e8c0bb7022d07ee97e962810962b03fc019695b5399f77aab414327cfc5dedd51e99453179c42ae85a42f8e06e0cec6f937224dd019c77c5a0ba32ad08107216a9c758138b730bd5b5f4b613f192839514a8621634d9dbd5840e728c1ef4a2c8bbfadc376dd80d13dcb327ce55ab536a43b570789f5c5e135ac0af79b54232613d0e989ae695aeb358c671ae71d508b58a793e19c58c3d204cdc9a021ecc634bcb0bd6a1917554ea3bd688adab8163260a914fc01d7ce05a497a5c5836cf9401cb6aa35cd008470bdecfb97a511c905badd01bbb4d0c05867661debd2162beeccd52399d5a70a929405293916f33ed0d03f8b850f4bdd77b1fb6283118d71de629577383c81cad086f4099ce7476cb787f73c96431a0df4156f7826fce9045f7e7c97bbfd618b845595203cdc8df4638430fac74a07bc5f773486731d8ad29c06695704cbe2882077a85d543551b7ba81b181ccb93d2b3071b1a38f3c762b42df8246aa64cecbdc772830ac79e766fa99e8c65225f28297a32526df9b51227bd368253737f013ae18435a912bc18cc4a95216ce449865e8bd8bc759dce9d4af52f9e789eafa37023e91946952202dfb7243cab7db2f9f98bb66f19750c547a2bf2e2ba92862ab66f33fcf465ffc41d23f0b891a3b28b3f68ea48dde6ad4802902abd22b0d7d9101bd61471c5d88ee9d9477b7cf9f6ac52e0f520c79278da22938745446f1e647ae478ecba416b941aa31f979d0633efe72910bebb8988de1d0013616f31c5da163eb6c07022649ac57422627a5642618f53103adc9918f9992c5b085e10d2744f9934bfbb994a710d6cd387c325e94278f97d5582864f1bb29a1400aaf674ea8fb99a3b42e4ac50418fd804a5b1471eaac4642d4aa338fd3d5d0dd84372b2c32c5cfe7f319acf731a9787b048cedee3833300dde639cb1386c8fbca4bae8d67fb7bd72d1696a0212e27e166e6b04a79e34b47c98502ed0bdbd8d61777537f72df569fe5ed30071b57e8724e98ccb88c07f0458cf32298cefb6ed672b255e581ac756789b57e950d57174bffd3f47bdbe4b168e7e3f1a6df508d4202d327947facfbf9526a9e5fc1a5abb179902d4584deae6cb2900391e080d3f3540b87c3a873ccfaee5b4aaff0e6516a867ea00b4d5e680fee6b91defc65c240614a1409bdd0f49c2c4f3c1d258d77abfc17a749660f49547adb236730e5a7a22fbbabdd8ca079a8efa5b605332db12f455868ab67a1ffd27d1339bdf8d150189cfbf6199c6fc27c05788138a63267eb8ac086e27286b4ef99ee9d92cfedab5ce9916675f128f206a1733f47a597232067aa12da20c7b9cab6575d7634f8c31e9a29948b528681f3f9c13b9f585ebfbff8c28a299a43e4409b31b6c02a79eeb493734fe5f9c1d9e3830572eb54229b5cf525768f695acff48c76b4a6e0936b7406ab69f06d33d3f04946db9d7966ea6e8c50ede5abadda28149edef5223a6938d5c32933070d234043feddbd65c81be218f9d7c497a1ecac30bb9162e60a9bbbcdb4fec4b212050610e2b376aadf58b3c9207860d2650d0310ae6606a8f1b266b6a13b68c3306ed413224abdf19371bac3ea1b964f28996fc70f666ff118c6a7c9f2108d327f5145919c03832f754de35f5979ae72130e39126499037d6fbb3751cbb4843b05d9dc91dd5fc1429da491f72e3069313ea243933b47109af247fcbe0c70f9024ac5a41815655ab309fcaa282d03596ba59cfee0e40f7bd657689453e98d562442fa4c585f970b6983a581b0b8eb1c5e780b3f5c1abb326213c6b5fd440c2187066ddf55f4eabf88804139392c45979440c6f05b7222bd95e963832d7fa4a4760273cc075e8b8feeccb917e8feaf7d3f766d9ae880487e69bc01872ba62b91b8af5dbffdd93fdc95e8f47ed793fc070a5991f2e9ea61439662dab218f643c1959171937aa160008a548f51f87b58f2c4fae5aed556f26bb9cd1dc2b3518458e2f5ec5d974c6e11a0ed639958cc8c1db771cc8cc8bee8727bf6452f47c9782acf548856a0e67841c3dbdb1c98572a4fc8e6cc8195a504019b4930d302a90dc20d8628ae6c90e0206cbb3d05025744db4e115cd3b650e5519a1624acbf226ebca8875b05183b2584e65289f8b9cec3f7d010cb9671a0e80bb70ca8763f1722d79e8decb6b9023baf64b5981e745c06546cc1e", "ade72c2ea29cf829ffe99c2d63840b2eef9b51a9919c02128347d2e88e9f063b86326928cf6252ce4beefbae7206dc61a22d0b33c90d464d551835e3b73c1e3d6e88663deab80c35a607e4180ec079b0ee84e3b7922904e7423acaf976e837", "43348cf32211d7daa300de8a4218543c8e3c7373ad10950765c39760f80b733c", "e4709d225a552e90fb357413", "562050bfb40451f27b1181c389508550a0f46b53d14ca73143da9dae3d3d2b466e9618db39e3219675d2b6eadded7dd9c741d7c9bf3c5619a521189607acbcf6b3964d469d966fa134444aa06d80749c873f0f976e0c5efc5be8d00a2729f03eda6a7b8630575df8b3a19388ff88daf0d00bb3e7c35a525ded90a4511ce815fe6c8904406cf72d7bfa14ca533566f7b54268835285c5402e22a63f98b5d90c86dae0a76d65eacc1ba85b3f5a1499d5f3432dd5455fab9e8bfbd266e99283c2bddf9b556410956b2f061603d1fc91194766f90da841699ba7da3d53ed5abdd8e98034f8fe734446d92b458a731aa4c578552ec1ac5d1baaccc4153a67b48a290602d5f955d61a08436b27cfb0786a80afef76e1266310a42d90feeb3bcc40ae5c4506432dcc92f7e5758ceaf277255401f5c5f4b10df93a249e38edd9effe7bacdf7fecc451d3b2cea77c9bab0403450c41929775b8c0ace46f6928f4d9cf3adf86832d298ea32b236d3201464e2ff506ef01da0e1e389e26e2b3ddc553b369b48d1aa5dd43edd5cab065e276aeff72a4c43206063fc7eea3bcc783ba2221f5b615a7a43a75cecda6bca5aa159e9208bf66af61e2e465c2daee630c4c62077ea6ef0e8b4b4e272d4e93a5f5284f9da463e1a60f815a8a31698ecdc09dff2b62f00e37aea5fd4b07a110cef27e12466c1814d3b10017cb9b8e12f2f38f10cbe31296de2570d5662b16639fcdc05db81e0d48178d055ef873501148d00903ec771400fa4873c5579dc3265028f531538f6dab1e5607a15c8b90cbfa4835107cba6f453bbdc71d08c7e423f58b44be38a9c8a610469f2551ee6177edf639cde35fe8e02f76b7ed106d691a876a4fda3b42d8ace3e0d3d4e026206c5d7d4d56fdda9dcd30fd7b74217fab3c617903f1aeffb8363443ed128af94c391810e327704d6f655e57dece97658d41e074029823850ddf7c5937af41c64465046d8544bba65c691ac69121bd272107f7eef8cfdb6a25da5da16d1033cede09129d51f6abfe63905a6fba9a64d7832fa35825447150595a60163af848eea878fb31a5fb97b1859efbfcc8586eebce8cfe64386461a9b88aa5efc1db43c64dfd5d4a45aa74803fd178f9e16a3f59acfb6e13a564d645cedd73890d0a82fb6dffeef527694a7cf2a89aed9750c3675a67505bff77de8d046087bd39a85c90aedb085e99baf04c7e3bf92e350b332da1b8af85550a00d68904ca426da61add864496d6ff442bb0b848e9aa463bb0c2085cff1a83a47d6f702bd184cfb5c139752754c8978d27b58d364bd88722b9097ee3a6ae28eabb14ca7c31e40461101e92448dbbc63b55cfe56efd078d0058c5e6146c73bcd949c4b3ec9f881b9a5f7b41ca83301261e0c674f2d35d96761baa00ce0675c082bf73dc52dc726a3e605067569a372d2bb47fc8fe1e74f00078ce6f352a6d9d97fd2834670ba3a45aa6751eafc7ed6694e1e07542860c8ea516f296ee901a3ee16b00b40419c74bf6db12c7230325e85a918f412bc2f6469c1a13a5aa77f028e327749efd05b91053f49d9f1edf49aa552c58c68257233a168db60ac55b4086ddaea275b078869cda7b69493c4b371b4e9c8361357a7ac7d3d3bbb464c960addfa8df2b208b21b090d540c440241598212d33273203d484e0930e22469c2a8e866579a4a2b3db8f8344dbf8baa1b97be0c4d976f6aaf14cc09ec52630139b894b2b6f4dad3a205a7b286253f1522b1d6e43bfa37beaf06f831c6f0945cefb2593b9b298da13b0d910582086c5d7e256ed4067bfb476dbe01bcddb437d46ba716d6ace2ff9912c8e460ad33ab3d8f97b7b08dd4ba9e01968d1949ff85b4b9d5b8da291fc0f90ab1eab1d246f67d76092b7a37528ceb388dd76f8a8f0aabb7490f02a2c8bc6498cb26350d859c466dd611bf0ceb81a8b7899c67742c22697ccee21c4963acb003d15c1a2078112bab05595917584e417db3872a0ff0a29138bbca7314449b19827525340370d7e48fdf9f7c6b4a280e78d00775a291081a5e78e7a00ff915015dd5af5f0a45690baba8b1b503bf85f326c23136f4424be4a559aed03fbc81400ac27a33dadb2155d1704950d98043dcd86df1eee78f3f266c4d14deb8126708f74b59aa15e8b497c6a52924a473f999aaf0abd3d148fee8503a1568efec7bfb0bd463402f563e4019cc9c9e1eb498aa54dcb659f43b86df0a34de4e51ec558bbbade3d69511d3fea2baf44f67e85ada7398d7f72ecadcd9e981f82b0743ed74bd33088ba4cbc85b0c99dc5382c599706dd2d51aa9f470c25a98e7e8248dec216a155495630662bf6ba0b7a4baa2cdad30e9ce3e1a65e3c23d69d5f946606ee8504dd70830aa5a8ddd84f10e064695469727d2efeb46186c9d3b7a170057636f05b9ec4c2de7d935fba504a1e7eddf7a5a95226b253b0b9eccec976ca3c57599850db40c27a51ae755c1f30d392467cb74e5c8235861d11d0f8461b0e1d84f5718d64ea92da62f4de184a6499dba473e82b3d197305de0e494f118a263237c7b4c0652327977edb427ccded35552c00a5804b9557ccf2bca2484d9da2c33f6c1bbf2c666ea10b4644a21e3905e5c4eb417ac3572e783428d23dd7222e75c356b99e8183d033034e29e618c90e66ec2f1e9fca47d82c1cffda8ad14c96045159d9437e91ecef41d24cff89009ff57e18c1a422860aa9cd31dd2a85b07422c72a5decc614a9742e62a4988f394421b6918e51c2412d749bb53b1e8fed7b2ef0873ffe14fa77bc366bbd5fa1432be465f5e25266c6c12b55df1f19b1a491acfc5c9019f122c422243d751d8eaa8ff721397915171556e999b34425f7d3ad6f6c3323b8133b4618c65ac16cb5941edc979472734bdccafc73c08939c0b1e306ae3015faa9cfa09ed6560269a1dc54c2c046a12a178144f4381f7b6fd3fd2d28f778d444d9f7a0dae00ea96c6969b78ef326a962d23275f1518f0e6a2469440612f3710b53538fe99a6179471be8c5b2d682ab3e9a5126e41ed6de000cd9e92fec3974e0f4cb2d2245d03d6ee80d6a793b16efa829d75c796f34d4e918250f457703559bb48ff78f0896be1bda403b7f1fd6a319d68478ff70d88238f2b8afc7d20e51757bb9db3bffb35a8040fc0db913c4f03d48619af7fd24cb8986b3e139058be3cc253b3de9b3bb3f8dab7b8818638279b2e6a0c29cfe16fa7250d3c74362ffa07e2977cf562140fe28afba8f61d81f7c73bdd4a2faddb00752bb049d0a57d05c6475c7387e6716ee31974169930c9fd830cef138659cf56f2212de185186c3d683fc6b7fd36e7821f69d0de041a569765066dc4a1934870a7b80f174e8f9e484942e62404a42b21658467873865ef94fc262c231527f39e82dfec91215947b99567daf75c6a28073ee4e67d4307e4b35b46f85433abd9812f35438b34598ff3b6dbd60b60747ad64565391df45ac80b272d0141702ab807fa27c6a6ba2f42c3facfae0c773940cb2943bb1353b41298258bc0d07542b69483e17ab9ce709e4160b80a0968dae9af8fc7c0324c753ca4a11a6df32dfa79a87b445c988154bb3c503e6884cf6d8f5e062a16b4ff230fbda109a6127d35e3bf2b29bfd3b18ba275af773b1981d603300035e046ef023d51874aa105d136bfcc9c7323bd0513a6b2b397ffea71afb7a8d4695411d86164917099eef504f6cff3c5cefb88f23f56c4ae3e2b09a3f353fa55630f45f06c29e8912e8c3c4f493f25eda781680585580595bba43dca9cfd400d9eaf5081d2c6697da59e012dfd0b875336b88fe16609c2e9876737b9afb868ed52417ed0c6b359d582d585ff82d98edd4e63c6b65cf43d4f69eee2af4819157b8a433966953862d1ff2c6d0cba382644a1b0033ddb7be3d1fa9a204042d7b821b293bd659dca980c108ad1db740800b9bd2fc1a163f9b4066f7604f160a7910bd947cb48ce6c81e680fc6571ff0cd12a3ded9c8cd560970ca5cb480a70a8322d5072edcd257604eba8dcf55f9ec97ea2b14fdcc72fbf615131836fb14e42b8d7171d0a06d2fb3caec2e0759e86b0d8f21e312d9211ed7fe0b48669934ffb892baf1db9aa457c07820723e5446420334bf6479f2099e01ef8adf273adfdd9ed0b741931284515d69c211cc2efead8339e450b13be71b35c36c1f00c2b8ed0cfa9792e422912e14b5b1455ef6abdbbec0035480c6cb69d21321d12ee19d528dd48f43b142cf0502eae5304ce52b7fb827552db9ab885b93e83d56a33346135aef11b7e48efca7cd52e2499a7edab0bd0562862187ff4599b2446bff11c37181092fbb05d0e05220ca6bc37f529d6599e8c29acb9f25616c27df291d4fb07430188e6470df7002f73cfe5fe6907dab0b4f90bb58130fe90241c29c6063a22c9f45d032b282eb92c93736692bd5cbde2a17552e942b595b08e6ba0c91a03b9079e9117fbba8f26ce6c5d0500c69bb6e22e3562a50baece49109c2d42b6714250665afd0f0a7e951182012f21aef4b917cd434d9ca22661437608e32666497516be34652500def6c28ef8f56f2273de5416142ce9606faf7df92ab779ed6aa74cb99bb1bfe758ffd344e1d31f479807326d1a7b98f6811e275545d69198707b0fbf027dc6a5e4815d62ef191535569a452c27c4e25ecf139df949d70dd5935bddc04f33b2f0bcf5073c51fc51c15067963a20569b5659f0e7413b347d6d5ee38a92b7e6e656c199149f07ebafe5281db6b1b2ecd9e0384b6f5a8e27ecea9a0249c61b16564964054f5f9621471a98de132e102f518c1419829e2ae2c8c5fffd1270f0a0b33a383437b0034783d50bce8bd7420c059d16364eecbd55b6ac8df8a70382734d8127f4f5895cc9e508b13c000ea053ab59b87ee639745418ffc566ceebad37a17b842d24d3423ac3f086142c622eceaadc4106f8c90c5dae1f52f407fa0bf1e6bf9385cbcbf3b61006ea3b1e66b693ce704577ca9598587f41e05d36d1de424e0e51290a5f2e2f99f1960c0253a046a49b19eef249ca2dda2af1e8dd78411088eff1e9c23c31bd20abd4fc9e7eab19500827d202f76270fe9f90e95309516343e0fca48e5a12182e91c78ebf2cdd4644629afdc90bbccb77546cd765135910ba1cd8a3e3c00fa77e585865e898bfecd06c01a0a4d7be483801099c61941c4967154af5620b171b426cf229df59d2944ba50754140c3f305c16956953be376fe6e7cf31a2e9c276bb09cc24c4b86b2b26f039b0d8511853adcb7feb8502e7641a34e3242bf2c538006bb1983345ec3cacbf219ef10efc1681d52e6e1b1c60bb556b6b8a63d1d1f6869077841d1b816f3165a35833e33d39a8c6e62a2f7c482c395768fc6a0e3cbfc7a1a6d64da53adad66c8016f76eaa73df1b8ef83012ecbe75c92a8e39b48169433f951a539b28a034d5fdd00639a5e3e17ef14dafe869064d130c90c68be4d5ceddabed1bc94e97e2cdf7313f780cd6e175a9e3eba3eaed896fe464073fcf07ae7b5bd41d58c3160f66ac95a76fdaa7a8cbaebb304fe3c8f03cef927a1182ac2281c3b32378813b24bb99e42cb0774331ad78b74d46b8ce48bbf4ef8431a82d4240edfd61b910c38570ba0bfbd4a41665117e6d5f5a97908462e62d0b76160d06aa56cc6e17aaf4607ba8263648f2a0077e306c25486f5f39a75", }, { "2f6210063cb3071b3d49339185c2cef8357b08ca826d8d1acd852540c16540f1c850f70404fe1f414853d3cd15a1c64a1cce149e3ca1b80926de4ae8438ad90bdad010decf2f201782f3e49794aae1b079f54eb59607bebde508a528927e346d4e444b1d736b34f65e198df2c36fa23c64f1f1fbf8b0b8ddb85d054bdb39b8297d0347f16f7be7cd9474c058e36294485386434b36fb28ee582e393367f15ce5f5a3d6641fbd31b331f10b1554a05da726a0f35c9b1b4af3498426b17582966a266cce452900f85af1046f45a4ccedca6ce02607fb70fa45f420f66aa38cd4c9f8a30e21a3067b940aebdaaeb7c77824a79e2ba20f26e70346dd6de96942b261e5c08288c7fe1cd1e9f680a0bdf8c46497f007a616eea95ccc17463559f8973eb919c68017e25100d9d1a196ca65fb615502076bf0b0c8bcc70ef22006895ebfa2243fba0791bae0625b762cc1718d1673948264454a200c58122d5e9b8b1e3eb05df8b7eeb297510e0d7dcf7f0be5f29f6756e4b177f109891e6825a9866359e35b10d20da7231bb5a0ea34abd0264b377d2fe9f420f27d3e5aa2e8e00541c46052966ef9b989ae5974e2054409507b867f647aa057f7deb19ac6929f0856005aec6e53a5f702fe6be403afed532b73d38fed73e6e551987f182a1e20801e7a6c8ccd1184cf0fefb4139fa166ca15395902ac40e7fed8661602853682a3b0ee307dffb44d0ea3012142a2880cb7c166ba6ea6a16c7e0882808db8023068f060e5ef1432fdb8331ffad6a7078d686d47d613e94291f1c4117e7c13aee4030fcaf223fcefdb300ed606b5dd931e4adbf45dc437eeb5fbff337812e15c15f026071423f6ef5305c559baa2ecd8ecc7cd498b043740ff3673774855d45d45fa64591d5b4970600ec91ab1b6f39d7dc0e709c41e49c355bd3b9d120ffb57095fb127bafa971a086135b917285794e83e9dac5ce76fb1a4aa4fb6b94a0dc3a9beea64b8817ec1e2b37af9dbd18ec30f2b6f6c12df1db6896c6c43b67a066038f0c4f17142b254f62c4dd1fedb950d07047919e397d06d033cb0bab6b61aefa6dee01720926b16beb9e8bc947dca9b8143b565da85d2dec182987838b267de9047f5b0d961c7971aaf54ae2c1e4aad61ff123c84e41a4566b2bd9e64247cf46b72a444d36bdced1a309b464ee5f4afe406eb68eb05ae51b76bf01b906c0ffbdeb440b11f1c9e3a4c3a809a1f7449047b356c663a1ab7f286a70d16141d11f2d151a4f06d422ab97cab539c1f9da09ad20c000c27b8fead5f0cc37329d466fa260aea934c154dc9c0a065df3d057a0f117a1c38321ae59226a8054f7d6b49a3753436c249838b0924f0e861f5627106dd8d3f0fa724a1cecda71d4a1267ed889b234ae4a7d5edcbc5d52cba389dc0152aff24d224c6a0f16dbd3b7f242807bf4b51a3f22690bdeb66eaa59e8766b3b265d784899d247a0ae1b58a06dd91c529e3691b09f9d9f55fc39afd4a00b0fc668880ef25a46a30861fba8cfd4b51262eba4138b41a2d13ddc71128c8c1242e49a51d6f49879fcfa7595ba4a4adcad3670b0b1b26382f03ff402bc70150f54bf513ba3e9a590e41b269e55616af297ebb3499e16cc8e46c0810330a602955553c0f93d668a1181a0bfd7021ad9a9f68ce39493b012da70a3dda149d0369f23f788616e0272efa322b6a54d804f340d32c890e2eb7b538f48f4c9293b584d22d0ae80d321607644271b81a76ac5b49d8e457069b0c3e909b8a222e3fa6016cb1e979e300804742f2005c68acb7b1849c088b3714c9c7af54e9de9390df0041c87924c8fa6b0aec6b6754171e059cba0d27f221f0b9d044a3aed8338dd8745651981e4b0329376f908b86ae9022699d495bbe3a148f7eb73d56eacb2e5e2180f63fcbfa680369f88eefa71f1210bc5b6b7b957f0a1437476a2112998033197673e470dbe7d9d476c97b95db8b5136f6cccc75d6e0ac1e4ace30e34e64fcc4d7e135b2c80e863ed701d3b28c25e982f1b5f8c895a4e6df7216c3c07abf8551a0ba0469c88aa7a08c7b5218a03b9b91f0935985373f65aa56286ad0e7ef2288a926f172b098123c136455b3a0f04590839e16bade7b6434a3cf048abe2612684c03dafd9cec39af508e63f07ea881014697bc24122058b5ef5d3fae835216d055f0cdf1dc06a12c95041d13ac9e15f235d11747f16ffce1cc3b8f508da520e395edd471f3759d8879ba9c2558b1188d822fd4739ed0546b0ce3bb9988db7c1dc8518ebbc62c4440e6e0653f917dcc13aca1864b71dbb67dbe7117474c936414e4f3cfab1f13eb05f3504484ce11977ab21ec523f97ba1b7ecb8fe384b634c30561cdb752fc67a2316bfa7e4d03f5f825d24a556a0460d8cfe0cc54a6f117ac52d553a5d1bb48031732716436675c5c3996b1939b127c6b0338bfaa29c7467cac9a127e455a715c9ce2b0c35a0d2f83a3d1273ee39399e6cc4980e610c752bd51652b96bf9cf34c7fa41fc9b13f5d55007483e4082ddac4675baa7822fd257452411b01de0e5e5da26e17539d64a89dd93c71d15a4c95b1a83039cb2d5f3f7fa04a817e48dfcbfb3de34ecb47f7592123caf27e17982fbfc8597af5b8aa6558f4e6c73db69328e47677afbe6ef8df82c3d1f0db6a108b2279f61822908d7b856432c32ac5ec0f3c53befab2a7ca356b9c2636f646b228b0a830d348be4ece2271814d477d4c73c0fb6e83a338b90ec4ef45cb25f7e3d6a014a9e8d2e8a6f55a383291a57f15667a73ea1daca31c7182523ca85a107efa2518d2f7f179ed4ba21fed479ef2be09669817133b2384bd85b155dfc1c4c9e6dd9ceecf06cc1ab8ebf7f07aeaae7441468b5471aed93f248a84f44c59be33274b11f651de010ab9f8fb24d3a99914e0147951c34280e7dd15ec196f9a4c86e55e7d373c7e31e6672d1b3ac6a45fa6c8c9088c0b8963d89f4ff1feea3e85cf9cf2f6c97128afd845bb131c6f62b3282bbba42745080fd457f1d3322058f1bd4be876bd01269546d1a853310b165926c1fd4e07054deb5d3fbe8f6007711d435994005aba95918c3df4cd390b165fcd139dd418ebbf661b6de57b655698a8a02ca8fad73e8c536c7110957c36e5494a831d536eccb97a2a9ef58fe58e2885aad170720ffcc57c7de601ea1cf723577a30aad8fd544317e33897c8b6c04e5191bec391ab990e197f10038c0726d371677e4a54c28d7ca5c6046e7cc4acde565b91f7f72af6109a0614160d3ae97e9257b8f71a4663b00c681e793cbb478306e97b0e04711eae7722b4845dadf2fff5bbe71ff24acffea2ee67df99bf62a098ddae9d4ebd3bc5dff04a2d9e3d1d83e8f493db3f63c9e24231b1dbe1147c79f21b0730c842f6983330c5c17dd34556d7e932074cfbe98f2dab5b0ebfd778a1e28fe2bac2d942f61a08b787ebfcdeb3d600bb130ca4922a4ffd38ffc4a1a1a7218451e45da4da67ad81ef898ece3d54cef877cb9d09f5dcf72eccbbc06e62f1e2b4d64059b0a807329780b155ce1614b68de04387d6108ef4dd3ab54b9da72e528d6eac3e16a360ae3421f3f23808a8b5e8ec3dbefcbca3c9f76905850033d78d9283bba9272c475b4e3b4d7643e62c2cc259ebbf168f890de88e82f8b26a7654ee31fe055e45609c70ae02b4942ee15678cd158f4c9e8d351d102ddf7a942458c6125e1457bea0d86ca38cf0c26e474b2b5cca77eb57ad0867cad7d25efc2b250e79396637ea3e948dbb855029cc9b452955bd04ad5a0d0514d4d773c0f298df7bc235a3ac64383a1fbd8a397a158e936b3ba81895a51daa89f51e4ae7a71a53794ff715a42f4fc3dcc9fd56df7bea4ab782534d3760e7b15605fc4dad16911656983c0ab77bce9445bbeb1537c55fef57a32c8f1404306a0a2ca7b73348cd99d0f9948875531cbb0ef7c036cd201614c33293d746c44140e0e8f82421c5bdf2bf428b249597df949fafdb5ccfe1618323f56a6ab9abab9a84a3beb6696ca918af244d34cc1cd95bbca4a87c860a0fa9ff6a04a905b0338a53f230bd5ee9c60e0e0332ca200c15dca0be5936b858d0a7b2e540b8958432e9767396c55d5cc35b60062580023b5cb2f9a5e9a1feba59a19f9a5a251e9d0e8500955a5df21da95213ced2260a2ed8f3d4b295c36cef750c89cf21985c302d5cc577aab7855409a912dbcf1d0a9800df4aa692a78607a40fd6d5a82305c58fcb3d2a82b27e8c5b91681aae62a2bf31ed55c494dbdc38eba30e83c6044945df76705228eede8470369f2e9941ddcb2f239fb3ff6bfcdb0efb5ec50f981adf0e8b213769ffbbea364b08cf8cd69abbfa2a6fe9865cc48558134a57bb5526b9d047e14a379d246de82d3d64f3c810ede280c768dd8bee25af287d5a8d94045ddbf5981382bc716ad9aedfcd66e0ab496172a24efe80649db8e1e83675fc8451e22c6564d8d6dfb285af7fec802b35f19dd8308c68952a11770247fcfecc4ed0e8a445c17b1573f0b4e3ed350f13269ceb572943fc435563459d5044699f1542335b03be6077af156b8c5a6a9f71078ad820cec4642427a9b187ee1b17036d5a5e6108cee8a7d444342eaec3afa64e77c71d3c2b3153d4e2dbb30df2b66b4d14cc45d3a4eda7e911d697e5763e23ee05311a20626df55549b8533c6ebe79737abf472f9cff08bec590943bdeb819d3f923f45b81f9a0cba1f3f800a261842d10cb4cbdba456c7fe5f0abb4a8b58891d97cfd6b669e2708922f1934809d51a1589e5f12e3bb82c9ac3e7e44e3f6e6cd63d428da624fd2f46eec38ff798a90d228efe50c9b67c63796347c8a2b53478f27605999a03c8e1f18b70e92419f646a7f49670aa12d324751aec17d0208fc296955b3098241189af8172d39a6819415cafb107c1842b369f174d6f37dd31cd728dfd0ab10f93609006342b6e4d6ccbfd1ed2bea2fdf5411442b04b1fe218916f159b20242f80b535b4e0a3024c6eff6a40bd0d3db24e51f5ff9c14e1b4a650ca4170ee70f0a3a5a58349a7d0b7a63af86347351696870b95231f76d8c5c6a20736907726341dcbb76672871d18c2157c094b929fd29d34f5bcaacd82706f89a60000cd341d98eb830b73a12335b69f3e0131ded3ce12c98bbd960d2d0696d40696a13ab43925374498d868cd8f070c9039ea6407fc2d92b9c39fe7c935bbcfcc5c0980952fb7dac79042951f49a1af828b138a87401c4104bc28cdf1e39dbd3fa63dd4d5f5ae9d85f032a43ad353bc5e6746e5a76326ab1f4e79103116ce70bc0b459200f32f85e461291e347dda92e421778b849e37a3ecb0b31ec6818e828dd3148dc74313aba43cc9d8b9a36a9dc4e229488060eb6c109f8ad6201958adec6d3bb3b04e5e558a272d44cb98e18f7a0ad8fa6ac3667a62f150830aa930f6166baac6b9081b44304988fbe1698a5b746255de26bb5988aca90bb6523cad68a7572f615f4aa58f932d8a749615cf0a7724e99de042268ceb31433e6df0a61547d576a6201b36b348c028ded5f7e94d1cd2eafc141088ff42cb3dafbbe4c402b93aa9d955df8d9d9fb57c75ac65c2c837acc44bbd4d4aff1888aed46c73d625ad7fff035e8ca0fe411c73ed8135b6b8e17a039ec74e9de0d64cb442bf8a676c0a666f68f21066332cd921ae0ed766f0516a8e19b82cf98e78add0373737a3419e13aa902310c44feae5fdf8bc64e80dce772686a31f141bcce452041bf545b908ef4a2b000e7beaf378e2afdccbbcaa42e330e5024400cf2852d3444718", "fd5008477b0855f6f2486fd4f74b9fb4f6e19726c6996bc66893183bd76054d5b05c1c2b64722256ba912ab2dcca66d2abfdf972966438fff7513acfb18ea461eac08c4e32aea4ed3fcf9f1c9905ee4402e7b6984bef974340d212f160b6524b76de99a98d3e96cc0d35e8a63ad7ea3cbea1d40a906c4dd03e5fc19e1513e9", "390a5e75c9ff4ad38fb6205ff47f209294337c1f25ff54a3c01eee8e1e220257", "8bf183347ec1ca4bceff3374", "19fa2641519e21293094e9d767ee1237f9e0715dc57172794867c3bbe2cb647f9b28a8d3f85c0ff557b91bad66f5ea16e0107757b0277fdd3ca05bf47c19bcb92a958a57e8c142a51af29bddb20af84377b6db65f77494e0dc4d2634a776b3a5d777319873bc0dacbbd4b9ebccfae849fa7e9769cdf54660ecca0d5cf4fa5190713726d54d02b3a3f21857125b8a808c0ca2f99d11dc430ed5113ee49ff8f00bcc08f0370dd510e8100e1285659a7b2c7457a6049f2af7786c4db1471ce5bd164e11c7a2165e83e03a135ae2b3429f82f677de044a067e99e0bda2d65a7270d629c00e1d528212d3aeb2896e58ee5145a93ed06a9c00705ad5c5988d3a192304c1d17661d45257c5d16799ef70771964435b12e3b2ee9d5b467c3b1992f45b7a59871b40d8daa1c280747ecb3d170257b91df1f549ce6d66455b5b6f60b7c6e95c92a67e20cffe8599ceb183de53f1dedfe19bae836447af8e053ba419660e0912cad064d6125b9e978e8d0d5f28f8a4e43ca3cdf2d4c0e9a11221d8184e9eb6c90761b0beac82d0d22793279aedb1c7db3632adbee323bc3bbde4801152694831abf5676979af26af7dcbadfba1cad1306b635840cbca76c558b37db0803b4c12befa27d16f21506b07ade4a838d6beba1816eb29ed5e3c4f132a752fc747bd9ba879156e87e6c1584e911da9f796e1fa4a055e427272559e4bd6d0f54b8257100f8a55d84c27b702bb1fe2f995425c85fd48b0a0610db5b39f7a5031407a12dae9f508b21b1378f14952d1beb2dea81d016b2d9b7f1a67b814569b69c0e619adea02a8683242d63a11d3317d060e5b4d85df5ad73127541ba5314715d187990735aa81f438f8b94070ec506ba536274d98b766c1694e54367891a602b99e370425b47a70b819277a249fa429c5bbd0530267f987e6022f25030c30f3baeedc0d13c95f3d5e4b2b87465d179a3a23b9f9e76a42ceea55226ce072f9488392f40621289124d786109d2498e74fb37e2ef466fe8bf3016d96e34204c32978775765aa80461cac48518157f86d59f6187bad4ee62fba1ddbe166b29452f4a59af1e057300c353440644a8e40ae8171ea028be2fa315804abf518847c7945e8228b7766cfdb08d3a3116b59aab8e94b6d8c8c9ef442c2dc7f923bc2cd3e5c663baca7dded976bf191fe36da16948c89c385fe71434f4aa5dd15fe0e925d2459e3b068b9d82a9cc8b8f9786bd9f5fef9baaaf2d67027d9bfd58bb2c58ec7c746b747ab62f9242e4b53ed14d6fc75f5280eca0de23717c97a2293826e19cc8eb47f946421516c349dc4ba49225b91e4e868874bdebd373700df1f3792aaa140597e58b88f90e163397dbad3941705b53d754e3e0c9003df836a7fb8d23f40362fcb5f3947a4281b24240be4ee89aa8e917b194f94345eeca224df0adc15f22a617b6427f29410bc48ea3f92216163785723efc36301d23ed52780c6fd7924bcfaa03269b13582b7c7ea9c0e4a451f38a469fbdb585dcb7c81452da77945ebe27eb26ff6e8c7b2decea289aac5af74746dc257c9bea44a0847f02c4f586e1d76f39d5bf952355a0875f177a666d1d354ad86ce5ec0aba2c2b20cab050eaffd31095395132f5af80a2d2d53b77bda49f948bbb37bdf31c8a690476488e14e542ff6841e7fbfc2eb84795696562d079dc1612274b6dff362567084f793f0bc2dd8de23392d05aeeeeac6991c9f74387153a4b7da94790375e336a00c8293bad0fcef2dd1880e7094e2e53f738247c860780ebe308410ca02ae409ae720e841f48c9677acc6e7d4ccd18c219c400f8b7e1257f692e09eaef96802b17a1cb7d93eb81d3bfcbc7af4cdf05b98e22556b3d1a8b56d6d83bb5f5724696f8f329839dbe477483ec3c09fa2e0628faeba1bf285c224bea3f6cdc7bbd768133c6ef1da14f248cc3b819b196588811b073a7291817bd1e89c65760435d8d17cbf9423744a92143e0f956e2977b39c54fdead5a57f3a04a0facca01bbf44d3b1fb9c4fa83ae1046985e3f26aa0a437999004dd8adc04c5111759849f919b93558dbc559173a23b069b59f800096d9fcf077c7640f59170bb9a6fffe64778bac272365d27ea62aa956559e90edd3f6393cc8775597bcf7d91990ab9511973d948324a27261059e93f4b5dd2f70caf12e1a08e0493cb05588618764391f355379578cf94dd33e616136eea997ec11c0d4ff064ff51a767e5558433a2e3a9a74c232d8e187f47b8cca010709eb9fea0dac8f1ea53bf18822e154ecd929c83b0eac366e30fffbd5ba6a46d734f58d26e7f5df538e18b3d827884aa857a680823131bcf30a76f1a555bcabb17b02b53aefad96fe76f7312da69719434c580d3ff1bcdcd594e6375935003d5d732cc577e11ea2abb1d04259f50aed4c3af9866e8c4a52a09809046ee330f05c4403acbc297a9416c5208fadb31ed4eb7a3b01b87bf08c75cf44c2b0df84df30872d021d6567ea649859268e5e1b5b6405e1b41e350a32c1af13722959c17c01b52c42241313b26b25995a1c89a53e248488724d280647226195746901929501df36d1e94815d7fe6c4ca2731f3181293217f71b9d7f59c2474856972013924ae4796db4cbd22d8905a6043c959941ca6b556c53d1688c439036c715d33a47a7dfc2fe40e53424c5093020d2e85e4b04aa4c704ea5bfe5a2384878da38319c59d41d66b6add2a443d9ea11edd8d18fa41004251653857733b388b453943eb33df93dcd5d549757fa2967ef0f9a5105836c48826c47fcccb2d9bc349032b286962136b848632bdcf186a08cbeaa52d195efcfc3a440bac154971d11ff4994f293b14fb8c3214ebe7ab8b3d0f2fe0b03ed7b145fafd7730a173e3cc1847f0cdf2cf629f5ea81a07bef716b1a67dd9e3b7a52fea1aaa7a393f53b5bdb5988df78a57a9dad19a8253316835acab8a6b9a9fb42d97bf29b2443322f46de386fd82bd3453ed68e2370c6eac4497b1bde7b42d569c452f377bd38bd50fa5a6792ef5c9ec6c647001149b86fedb3e2f18d4271e9cc4801aa16ecddb31b6a795fecabc613bfbc8e4f5636d71e74595c841fd11b6a6bc7f169317c1added56b82a71fc36d774bb4d661685363e9da5fd2e1f357006dc5b5bbf8b42ee3f869e75a541586fba558a8f490d641b78c27368b9b4c2db046354e9358ae9140e91cd95ebeffc6c0d2676a3ff4ab10d463bf32bed97023a80a79df191ab9858c43537a03072a17c30b1bd99efbd361590ed6b7d5b0ec4e2326fa35904ab9a48596f44491cbbc0112890f9386ed04dec30126be359a05e99b2b77fa2c8f6b7460a6cd590d71c73b2a1b23312ff89306b6e41c76ddc0a099bfa79498e36ae5cf0c560b8854dff32d2b690ce0ac4aabfa723ac6f2e97ad1083235196b464ad67fdd649aec01695d55c8b4bb198f30630ca635aa5a1915f3718341bcfd8b522f764015fa5479004d28eceea7fe67df7ee24a97a9708d528b89589f1899f13242a0d00f7464c3cdfce213699340e754533b934f4a8410224e111f31cf8e54d7b5e90cd8c68bf96edbc8d183894deefdf4fcc1a83162a3f6341dcd9a9aecf171c0df28257a68b1af1b67c54c43c3cff27fed89cc64bc46e23a49ec74a9efbab7981d9f0a018247441e4f0f5b5f68ba9325582f92de4cca4a5f878a0c5c387581e64324e3246d8f3205c838a29f1abeea24446e496421f0e742d411adb55f70272ae4a992e825a3d327e44b8b3762b25aa451d07eb4eac0322b431fa676462632daba2aba7bdeee1b438f051d21d4b1897e2ac2f95ee7c23f9996a805de8fffb3b30b855cd6c5b84c011accf4bf94d304d944079f04b5cadf8fcd6751c22a0f9165ab98998b2d89e6514641f1f3b91b8c0bf057d69c3d893fc4e041e06a2229e2ee58082ffb58cb920972ede58483287d0ace94c1becef26a410b93e4ff402e61dcc574b790d49679f18f4e2004f8b7cc357faba34a80e56821bb5b883d1a8b49c6605002152f270bbc36bc79095644e29ab08cc988deda765d67e4fff12b726d5de135ff9d0cbd9d5f9d440e548836633b93a38330d638468b59a32642da3375cdf70b062d14b46a78569c24a706e179baa2058dcae5c61fb6cadd9e015b017f26e9dbe3e6366cf5f1ec839aa3bbb21dd6c9b8e910245fa95b09b7d6cbf08a4c6c84bef257a70389be962dad14d97a893c128b73bf6580689e540d004f21edf8403f36b1ad7c9a2e83ffceb141af59700c316c8c1e3347187f24819c2ff0c9f9a2360dce354f3374374eab1643d2d8831310a8e3ca6768200ea7759822b82f7027cd450479fcc7f6d04802b15735a137ad489f1e1ee78434a253a9dd16684ad58fc91960cde6754f82e8b38edd5e798fdbbbf8fc2e2380a4e21dd94f8c1c063b18f29d8cd8d89f65deac5640799d4ca2caa29c1e72ad8bc417490d11e4051d94956fbc74289857e5f8e9e87b9a2d83074a994de0b10bc7782f6650cfbdb8c835c81cd88bdce5f04ca939b3c5cd010d4dc5d51224fcacbca9851694b8bf55b22dead859d023eee5a7ad3436a912c3fc0284456d5d72ea5f1afa8545c856676ac2dd9a057028bd3ca0f50e7070fa74152f13997c95c1834c3e67504f1a4165d2b49a96919b88f72caed60f56ca7ab5a3204fb12ad3592c725fdebb048732fc189c7dfed185c6c184a626e07d7356860d00389862d5b9701eaa4e5f7889e6db0f54633369b8d26805c08471de8fc3f8fa1fb0b0711d9e015add5373f7f8b64abaddbac3399c756244b1b07c579d33e4967e5e0cf16de29cb8a7efad07ff9039ca305772a6e45c76bd9b77e24949556766a8b8425c5e595efb431bde4ee222f9eb3fc2d002a1e2d14db2b23135266c942eea33bffd30eb0218405373240e0cd3040436ca895093bf056fd001c00ba59d90502042e6e6c0167105051628895c8164c9ab959400898309cabafdef12be53604fa57df44e0a90a81bd63c331291a93bffefe809e80db0679568f6e94e0d8e2edec0087c35bcb3c4f4725e6013bcf197156cd9d90612423348123383e45c14d27d8833f56ddb04083c069fd6e282fe69c940840f5f747dfb72ad72fd8cf9f3ded15c9e2f4727fd60b4f40e95dbe77a89b47dde7d5326942600554905d9dade9d145ab6da802643f2081678392609c2fdd1b79dd8caec137cbed315374c6f05c0758070f3bb17e23d81ccc39c6aa89913897e487fde889c5aacd422278f8571641cc4f0a93d9768aef9e45d6bd187d1ba637ce0fbd3c573d6778cf7bf5188c00dcdf13be3fd599143952b376220283e34e014e83b214bd5f64eb0ecb098ae8bef883949907cc36e22ece60b893b963cfa73d120513e285aaf70ce5add34edbdac60b3aa7b385b90e339058fb9b3cf984b06f79788016035c5ce490f2de7995b98a8c1c9c80f29603ae2b7fc41886663163e604275cb085f8453b27f4d795b9bad19ade2f98a1c99b43a7581bd991e5d0e5e1a6e713acc522ba9fe8302658a9782558e35436e714ac6bc85ad1d3cd008f24106901fa954f5fefb61210d6f8dc9ff35c480f1d14e59c0e501917a31ee9d00c6bdb06a00af5a8b08c3928cc5f37476248223627cb77eaf0e96213cb0a13e97d3fe9b9814d462690e8d68d02655a32fc271ee73db4f88a33386ea88a5857e15a28d9b3e3a96f00c7cd85aa53f9282ab8c8ca6d6a8afed43aa87fe7fc1ad59b0f0db2dd25c20af96e8c282c19fc883ef01a4060398926a1c82f07bcd3bc314580d7636b623b7bad8ddba05850291a6344df0f346fa4a321a85ee3e9c", }, { "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b", "0942e506c433afcda3847f2dad", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "588e1356fb8fa32410dad99cf7922aae47b4042502c92f3afe33dc22c1c2e90caf22bc37a254f8dd62a09582c70194f9616982639415178e9fe95740c0f1d497a69b69d4924a7a15290187f9c8acf09cf5b3b3188ecde2d2807207f5bb6a6d3504314b1b47684cf8ba8807eb9a3c497c79ebe1e4c1eca2aa90328563e201425227fca8ee05dcc05fd6c98128626c1e71d2fb3a21860567093db1012dfabe13055c48219d2a301c8a5a49033a811d8d9413bafbb2eefc177226fe578e93c2ef1f309416dc98843bfac387debb1b610b1d2366178ce7212a7312057a3d058357a629f18c78e129e60979a2310455a76207be5611e8b4b840629564020c17f5c9446882e23f610e931246ec434e62de765bf22954cfae02b2ff4b4086fbbd1b6cec23e45481eac5a25d", }, { "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b0942e506c433afcda3847f2dadd47647de321cec4ac430f62023856cfbb20704f4ec0bb920ba86c33e05f1ecd96733b79950a3e314", "d3d934f75ea0f210a8f6059401", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "588e1356fb8fa32410dad99cf7922aae47b4042502c92f3afe33dc22c1c2e90caf22bc37a254f8dd62a09582c70194f9616982639415178e9fe95740c0f1d497a69b69d4924a7a15290187f9c8acf09cf5b3b3188ecde2d2807207f5bb6a6d3504314b1b47684cf8ba8807eb9a3c497c79ebe1e4c1eca2aa90328563e201425227fca8ee05dcc05fd6c98128626c1e71d2fb3a21860567093db1012dfabe13055c48219d2a301c8a5a49033a811d8d9413bafbb2eefc177226fe578e93c2ef1f309416dc98843bfac387debb1b610b1d2366178ce7212a7312057a3d058357a629f18c78e129e60979a2310455a76207be5611e8b4b840629564020c17f5c9446882e23f610e931246ec434e62de765bf22954cfae02b2ff7c59dfe246e4bb2d6a8afcebdc2beeaabf2a3f43f95a5ea639853f38719875ecdd2bbc0d81bb2a5ed59553b1e76b6365b74f618f685eb7731024bbf6794c3f4c7c5a1cf925", }, { "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b0942e506c433afcda3847f2dadd47647de321cec4ac430f62023856cfbb20704f4ec0bb920ba86c33e05f1ecd96733b79950a3e314", "d3d934f75ea0f210a8f6059401beb4bc4478fa4969e623d01ada696a7e4c7e5125b34884533a94fb319990325744ee9bbce9e525cf08f5e9e25e5360aad2b2d085fa54d835e8d466826498d9a8877565705a8a3f62802944de7ca5894e5759d351adac869580ec17e485f18c0c66f17cc07cbb", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "588e1356fb8fa32410dad99cf7922aae47b4042502c92f3afe33dc22c1c2e90caf22bc37a254f8dd62a09582c70194f9616982639415178e9fe95740c0f1d497a69b69d4924a7a15290187f9c8acf09cf5b3b3188ecde2d2807207f5bb6a6d3504314b1b47684cf8ba8807eb9a3c497c79ebe1e4c1eca2aa90328563e201425227fca8ee05dcc05fd6c98128626c1e71d2fb3a21860567093db1012dfabe13055c48219d2a301c8a5a49033a811d8d9413bafbb2eefc177226fe578e93c2ef1f309416dc98843bfac387debb1b610b1d2366178ce7212a7312057a3d058357a629f18c78e129e60979a2310455a76207be5611e8b4b840629564020c17f5c9446882e23f610e931246ec434e62de765bf22954cfae02b2ff7c59dfe246e4bb2d6a8afcebdc2beeaabf2a3f43f95a5ea639853f38719875ecdd2bbc0d81bb2a5ed59553b1e76b6365b74f618f68a12d0f1cc99e132db9014100d9668c91", }, { "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b0942e506c433afcda3847f2dadd47647de321cec4ac430f62023856cfbb20704f4ec0bb920ba86c33e05f1ecd96733b79950a3e314d3d934f75ea0f210a8f6059401beb4bc4478fa4969e623d01ada696a7e4c7e5125b34884533a94fb319990325744ee9b", "bc", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "588e1356fb8fa32410dad99cf7922aae47b4042502c92f3afe33dc22c1c2e90caf22bc37a254f8dd62a09582c70194f9616982639415178e9fe95740c0f1d497a69b69d4924a7a15290187f9c8acf09cf5b3b3188ecde2d2807207f5bb6a6d3504314b1b47684cf8ba8807eb9a3c497c79ebe1e4c1eca2aa90328563e201425227fca8ee05dcc05fd6c98128626c1e71d2fb3a21860567093db1012dfabe13055c48219d2a301c8a5a49033a811d8d9413bafbb2eefc177226fe578e93c2ef1f309416dc98843bfac387debb1b610b1d2366178ce7212a7312057a3d058357a629f18c78e129e60979a2310455a76207be5611e8b4b840629564020c17f5c9446882e23f610e931246ec434e62de765bf22954cfae02b2ff7c59dfe246e4bb2d6a8afcebdc2beeaabf2a3f43f95a5ea639853f38719875ecdd2bbc0d81bb2a5ed59553b1e76b6365b74f618f68d1f05b5662cd6e04de896d3ef5dae4149485a5a2093ff4ec74b20b5e5bf8e61b5c65515938c202beab3eea5a498d2f32d4d00a24b826b6efb16013ef54cbe170", }, { "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b0942e506c433afcda3847f2dadd47647de321cec4ac430f62023856cfbb20704f4ec0bb920ba86c33e05f1ecd96733b79950a3e314d3d934f75ea0f210a8f6059401beb4bc4478fa4969e623d01ada696a7e4c7e5125b34884533a94fb319990325744ee9bbce9e525cf08f5e9e25e5360aad2b2d085fa54d835e8d466826498d9a8877565705a8a3f62802944de7ca5894e5759d351adac869580ec17e485f18c0c66f17cc0", "7cbb22fce466da610b63af62bc83b4692f3affaf271693ac071fb86d11342d", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "588e1356fb8fa32410dad99cf7922aae47b4042502c92f3afe33dc22c1c2e90caf22bc37a254f8dd62a09582c70194f9616982639415178e9fe95740c0f1d497a69b69d4924a7a15290187f9c8acf09cf5b3b3188ecde2d2807207f5bb6a6d3504314b1b47684cf8ba8807eb9a3c497c79ebe1e4c1eca2aa90328563e201425227fca8ee05dcc05fd6c98128626c1e71d2fb3a21860567093db1012dfabe13055c48219d2a301c8a5a49033a811d8d9413bafbb2eefc177226fe578e93c2ef1f309416dc98843bfac387debb1b610b1d2366178ce7212a7312057a3d058357a629f18c78e129e60979a2310455a76207be5611e8b4b840629564020c17f5c9446882e23f610e931246ec434e62de765bf22954cfae02b2ff7c59dfe246e4bb2d6a8afcebdc2beeaabf2a3f43f95a5ea639853f38719875ecdd2bbc0d81bb2a5ed59553b1e76b6365b74f618f68d1f05b5662cd6e04de896d3ef5dae4149485a5a2093ff4ec74b20b5e5bf8e61b5c65515938c202beab3eea5a498d2f32c38dbb37d04f8272e741da2802c54a9d9aaf8ecf38b36fc9ad0079523f6a4abd5281a22697a3180bc02662a7c13ee23599d18e5c48300dbb831509df4c172f53e524b3c15124a87ac73e5028cde6c94d8d", }, { "67c6697351ff4aec29cdbaabf2fbe3467cc254f81be8e78d765a2e63339fc99a66320db73158a35a255d051758e95ed4abb2cdc69bb454110e827441213ddc8770e93ea141e1fc673e017e97eadc6b968f385c2aecb03bfb32af3c54ec18db5c021afe43fbfaaa3afb29d1e6053c7c9475d8be6189f95cbba8990f95b1ebf1b305eff700e9a13ae5ca0bcbd0484764bd1f231ea81c7b64c514735ac55e4b79633b706424119e09dcaad4acf21b10af3b33cde3504847155cbb6f2219ba9b7df50be11a1c7f23f829f8a41b13b5ca4ee8983238e0794d3d34bc5f4e77facb6c05ac86212baa1a55a2be70b5733b045cd33694b3afe2f0e49e4f321549fd824ea90870d4b28a2954489a0abcd50e18a844ac5bf38e4cd72d9b0942e506c433afcda3847f2dadd47647de321cec4ac430f62023856cfbb20704f4ec0bb920ba86c33e05f1ecd96733b79950a3e314d3d934f75ea0f210a8f6059401beb4bc4478fa4969e623d01ada696a7e4c7e5125b34884533a94fb319990325744ee9bbce9e525", "", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "588e1356fb8fa32410dad99cf7922aae47b4042502c92f3afe33dc22c1c2e90caf22bc37a254f8dd62a09582c70194f9616982639415178e9fe95740c0f1d497a69b69d4924a7a15290187f9c8acf09cf5b3b3188ecde2d2807207f5bb6a6d3504314b1b47684cf8ba8807eb9a3c497c79ebe1e4c1eca2aa90328563e201425227fca8ee05dcc05fd6c98128626c1e71d2fb3a21860567093db1012dfabe13055c48219d2a301c8a5a49033a811d8d9413bafbb2eefc177226fe578e93c2ef1f309416dc98843bfac387debb1b610b1d2366178ce7212a7312057a3d058357a629f18c78e129e60979a2310455a76207be5611e8b4b840629564020c17f5c9446882e23f610e931246ec434e62de765bf22954cfae02b2ff7c59dfe246e4bb2d6a8afcebdc2beeaabf2a3f43f95a5ea639853f38719875ecdd2bbc0d81bb2a5ed59553b1e76b6365b74f618f68d1f05b5662cd6e04de896d3ef5dae4149485a5a2093ff4ec74b20b5e5bf8e61b5c65515938c202beab3eea5a498d2f32c38dbb370a9bbc3187cc260ddac991f94ce4f0d5", }, { "0fb826ddb2eb5e708de203d0438be12cf708d635ebdbae56278be09077009586b9bc646ba7c2db35a5de05e86ae71461efea96dac64430edcf117d461113cccacf303576f310ab98efb180599894ba877e50614494923163a3afa9b4c2757f91a6b40799c5b331b464b10dfc45c783c317e408ab76390e19e8b7ceaa2c4d3bd201436bc6f69c7a5a4d8756924ed95665bd5e1034971e4d80d51b2a", "026866d46aa940309fdcabf92a324fbc", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "30f05cf8189bb7b8b4f560e746e228c4cc7e86e8f2fa66e1afe212d1855db51070acd5eb34ce80b2e223957df50fde4c2531d97fc9e573725e7a5e47f0dfc4da1942620320bb2deaf8b17937bae4218d04db8e76f6efe84a117292159507c9f8a09fb2c17921d7762510dbf1dac7b62b1bd7572e3e2cf008d01c445c7fa78833235034281ae180e051451c6a64f22ca9708634bd0d604e4cfcd971b13742efa5b6363e662a875daccb2b00", }, { "c7d4f8790e4c47d4daecbddf5939973521ddbf3b832e564afc66f03b5583c41c58bd956609dc3ae3c8f7c2213059575236168dba44e3044049f47c9e7840bbd0fd5036062d70e9f567ac1797056ee93c8476f6c959fa09a3ee854166c6fc36c34d6cca7adcb36f435f86db65f4c4a1793b974294914b377fd179e697751c5ac289243c65d8aca93732849c27483da083d4e218652d4fe5fec8cb953ee7f00070143dd6ece97f241b03c0424bfee2cfd2c4e738f2361df0ffe8863dcf763d408a7a167763959b7f985bc1e359a4b22c6899645ad0814bcf69d10c38474978d1c48e482723e3a6bb3f689f980c51c474eb28cfbba91a8a12eb964b32dfc303a3524ccb752f71316ed9d007e521cb5a0cf429c79d4351b02ee7fb60c7be636a10af3586dfa7b74d80875466a820c0b514e97cb12cce615ab55cba7c1b1de72bcd1cb1acc368f944ef4eaa986e6a4d8253c9337f9795d94df193c90cb0b0387dcde929905223d441717ed9dfe826613bf094ba872993d41b269e27d74e5f541b497eac9ba180dc12ffb6f1e7dc5223cce6dd541071282b97c6526e15b2c330fb41dc96e25d72f45c28e543053766d11d44252db54e584c14abbb295d7e5a58bf36eea1936095ef897a338eb1995fcedd85fc92d354dfe7ff9a115c186bb4d7a1a27835030d248c87571a38f17906cefe0261d15740b9", "56", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "f89c825ca43cae1ce3fbdee85c505edd1aabefe69a0f9efd740f027aa7dee48a91ad24e69ad061648f0a52b4afb19d7ffccdc21f4b4247dfd89f5f9f998cb3c02b226173fedb6f8770aceef9271e7236fefd19fb3b87d08a5c587ac7918e80aa4b477f22602189811e270d686bc4949137a41d11d95ec96ee9d26c6126f6e923ab37638b34d1538d2e46d6df6216da4f193a3cecb731e632e109ced643056a1673059355d2d1314df35ded8364efed7de490201090a6f2d1751748585f64d26041637ba3723cbc4b60e226f10a19699d223075bc1f27d82e7f560c0db630ea670b3f8a70a8950894af4d1c7b3f674a3fa00d19ee4cc2b6174c1d259a297424bf2c3943a29a16a9830ce11abaa79cd2eb77b53a02b365b1838e7bfd5ae1bd044ffc885c61c6b2186a357e8b8f732b7ab96517969aeb70c7b493bbaca9462a61815a3c6135c748bf9c8487ac0631807aa69243fa09cd3b8efb63f8d4e090ad30b6c2f08bf4e82f191cedfa5cbe2b42268d67ecd105918181e44fc9879efd642d20be84e6f74717e03fb94fcbaa6ed3b307431d2a9384b8a2b3e5825ffce8d99af48f177e43bb4272226d8a5edd37d53807f768feb9e0733b437a1d0f84779ab68a1804e92a5eecca56364f0fa6dca152203b249fdc8fbd950fdc37c1887596308a90ba3a5751c7096bfbd1cb177bb17847b33c4379b43938a67674459cd9a06e3017ccac5b", }, { "135a28170fe89066da7bcff3a9ccc1b27dfe942a6f47b23835ef746aaea63dc10066d90f4e697528e5451b8e11dd408fdbd4b94a1c6c82515bf7bc099df9cb9d5fa4acad0d22d5f267f18078cec107a995c1f3b12d7603886dbf910ab85ca7180053c50e759b00dc8c81555a425c03d71df6894a6c8cd2d94b64e303c08a1bc1dee1cf537ccf300850856292e1656aff5bf349c87f1ca1ca8085cd400fe901edcad04146a0714ef0f6b083d715edd670e020385f3cda29bc5ff6fc6edffe5ca9ce9def6e0e3d5f04ede2db02cfb2", "73afd2ab0e0e8537cae42dc6530dc4afb6934ca6", "a5117e70953568bf750862df9e6f92af81677c3a188e847917a4a915bda7792e", "129039b5572e8a7a8131f76a", "2c125232a59879aee36cacc4aca5085a4688c4f776667a8fbd86862b5cfb1d57c976688fdd652eafa2b88b1b8e358aa2110ff6ef13cdc1ceca9c9f087c35c38d89d6fbd8de89538070f17916ecb19ca3ef4a1c834f0bdaa1df62aaabef2e117106787056c909e61ecd208357dd5c363f11c5d6cf24992cc873cf69f59360a820fcf290bd90b2cab24c47286acb4e1033962b6d41e562a206a94796a8ab1c6b8bade804ff9bdf5ba6062d2c1f8fe0f4dfc05720bd9a612b92c26789f9f6a7ce43f5e8e3aee99a9cd7d6c11eaa611983c36935b0dda57d898a60a0ab7c4b54", }, } ������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_test.go�������������������0000644�0610621�0607500�00000010650�13172163317�030016� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package chacha20poly1305 import ( "bytes" cr "crypto/rand" "encoding/hex" mr "math/rand" "testing" ) func TestVectors(t *testing.T) { for i, test := range chacha20Poly1305Tests { key, _ := hex.DecodeString(test.key) nonce, _ := hex.DecodeString(test.nonce) ad, _ := hex.DecodeString(test.aad) plaintext, _ := hex.DecodeString(test.plaintext) aead, err := New(key) if err != nil { t.Fatal(err) } ct := aead.Seal(nil, nonce, plaintext, ad) if ctHex := hex.EncodeToString(ct); ctHex != test.out { t.Errorf("#%d: got %s, want %s", i, ctHex, test.out) continue } plaintext2, err := aead.Open(nil, nonce, ct, ad) if err != nil { t.Errorf("#%d: Open failed", i) continue } if !bytes.Equal(plaintext, plaintext2) { t.Errorf("#%d: plaintext's don't match: got %x vs %x", i, plaintext2, plaintext) continue } if len(ad) > 0 { alterAdIdx := mr.Intn(len(ad)) ad[alterAdIdx] ^= 0x80 if _, err := aead.Open(nil, nonce, ct, ad); err == nil { t.Errorf("#%d: Open was successful after altering additional data", i) } ad[alterAdIdx] ^= 0x80 } alterNonceIdx := mr.Intn(aead.NonceSize()) nonce[alterNonceIdx] ^= 0x80 if _, err := aead.Open(nil, nonce, ct, ad); err == nil { t.Errorf("#%d: Open was successful after altering nonce", i) } nonce[alterNonceIdx] ^= 0x80 alterCtIdx := mr.Intn(len(ct)) ct[alterCtIdx] ^= 0x80 if _, err := aead.Open(nil, nonce, ct, ad); err == nil { t.Errorf("#%d: Open was successful after altering ciphertext", i) } ct[alterCtIdx] ^= 0x80 } } func TestRandom(t *testing.T) { // Some random tests to verify Open(Seal) == Plaintext for i := 0; i < 256; i++ { var nonce [12]byte var key [32]byte al := mr.Intn(128) pl := mr.Intn(16384) ad := make([]byte, al) plaintext := make([]byte, pl) cr.Read(key[:]) cr.Read(nonce[:]) cr.Read(ad) cr.Read(plaintext) aead, err := New(key[:]) if err != nil { t.Fatal(err) } ct := aead.Seal(nil, nonce[:], plaintext, ad) plaintext2, err := aead.Open(nil, nonce[:], ct, ad) if err != nil { t.Errorf("Random #%d: Open failed", i) continue } if !bytes.Equal(plaintext, plaintext2) { t.Errorf("Random #%d: plaintext's don't match: got %x vs %x", i, plaintext2, plaintext) continue } if len(ad) > 0 { alterAdIdx := mr.Intn(len(ad)) ad[alterAdIdx] ^= 0x80 if _, err := aead.Open(nil, nonce[:], ct, ad); err == nil { t.Errorf("Random #%d: Open was successful after altering additional data", i) } ad[alterAdIdx] ^= 0x80 } alterNonceIdx := mr.Intn(aead.NonceSize()) nonce[alterNonceIdx] ^= 0x80 if _, err := aead.Open(nil, nonce[:], ct, ad); err == nil { t.Errorf("Random #%d: Open was successful after altering nonce", i) } nonce[alterNonceIdx] ^= 0x80 alterCtIdx := mr.Intn(len(ct)) ct[alterCtIdx] ^= 0x80 if _, err := aead.Open(nil, nonce[:], ct, ad); err == nil { t.Errorf("Random #%d: Open was successful after altering ciphertext", i) } ct[alterCtIdx] ^= 0x80 } } func benchamarkChaCha20Poly1305Seal(b *testing.B, buf []byte) { b.SetBytes(int64(len(buf))) var key [32]byte var nonce [12]byte var ad [13]byte var out []byte aead, _ := New(key[:]) b.ResetTimer() for i := 0; i < b.N; i++ { out = aead.Seal(out[:0], nonce[:], buf[:], ad[:]) } } func benchamarkChaCha20Poly1305Open(b *testing.B, buf []byte) { b.SetBytes(int64(len(buf))) var key [32]byte var nonce [12]byte var ad [13]byte var ct []byte var out []byte aead, _ := New(key[:]) ct = aead.Seal(ct[:0], nonce[:], buf[:], ad[:]) b.ResetTimer() for i := 0; i < b.N; i++ { out, _ = aead.Open(out[:0], nonce[:], ct[:], ad[:]) } } func BenchmarkChacha20Poly1305Open_64(b *testing.B) { benchamarkChaCha20Poly1305Open(b, make([]byte, 64)) } func BenchmarkChacha20Poly1305Seal_64(b *testing.B) { benchamarkChaCha20Poly1305Seal(b, make([]byte, 64)) } func BenchmarkChacha20Poly1305Open_1350(b *testing.B) { benchamarkChaCha20Poly1305Open(b, make([]byte, 1350)) } func BenchmarkChacha20Poly1305Seal_1350(b *testing.B) { benchamarkChaCha20Poly1305Seal(b, make([]byte, 1350)) } func BenchmarkChacha20Poly1305Open_8K(b *testing.B) { benchamarkChaCha20Poly1305Open(b, make([]byte, 8*1024)) } func BenchmarkChacha20Poly1305Seal_8K(b *testing.B) { benchamarkChaCha20Poly1305Seal(b, make([]byte, 8*1024)) } ����������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_noasm.go������������������0000644�0610621�0607500�00000001033�13172163317�030147� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !amd64 !go1.7 gccgo appengine package chacha20poly1305 func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []byte { return c.sealGeneric(dst, nonce, plaintext, additionalData) } func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { return c.openGeneric(dst, nonce, ciphertext, additionalData) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_generic.go����������������0000644�0610621�0607500�00000004261�13172163317�030454� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package chacha20poly1305 import ( "encoding/binary" "golang.org/x/crypto/chacha20poly1305/internal/chacha20" "golang.org/x/crypto/poly1305" ) func roundTo16(n int) int { return 16 * ((n + 15) / 16) } func (c *chacha20poly1305) sealGeneric(dst, nonce, plaintext, additionalData []byte) []byte { var counter [16]byte copy(counter[4:], nonce) var polyKey [32]byte chacha20.XORKeyStream(polyKey[:], polyKey[:], &counter, &c.key) ret, out := sliceForAppend(dst, len(plaintext)+poly1305.TagSize) counter[0] = 1 chacha20.XORKeyStream(out, plaintext, &counter, &c.key) polyInput := make([]byte, roundTo16(len(additionalData))+roundTo16(len(plaintext))+8+8) copy(polyInput, additionalData) copy(polyInput[roundTo16(len(additionalData)):], out[:len(plaintext)]) binary.LittleEndian.PutUint64(polyInput[len(polyInput)-16:], uint64(len(additionalData))) binary.LittleEndian.PutUint64(polyInput[len(polyInput)-8:], uint64(len(plaintext))) var tag [poly1305.TagSize]byte poly1305.Sum(&tag, polyInput, &polyKey) copy(out[len(plaintext):], tag[:]) return ret } func (c *chacha20poly1305) openGeneric(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { var tag [poly1305.TagSize]byte copy(tag[:], ciphertext[len(ciphertext)-16:]) ciphertext = ciphertext[:len(ciphertext)-16] var counter [16]byte copy(counter[4:], nonce) var polyKey [32]byte chacha20.XORKeyStream(polyKey[:], polyKey[:], &counter, &c.key) polyInput := make([]byte, roundTo16(len(additionalData))+roundTo16(len(ciphertext))+8+8) copy(polyInput, additionalData) copy(polyInput[roundTo16(len(additionalData)):], ciphertext) binary.LittleEndian.PutUint64(polyInput[len(polyInput)-16:], uint64(len(additionalData))) binary.LittleEndian.PutUint64(polyInput[len(polyInput)-8:], uint64(len(ciphertext))) ret, out := sliceForAppend(dst, len(ciphertext)) if !poly1305.Verify(&tag, polyInput, &polyKey) { for i := range out { out[i] = 0 } return nil, errOpen } counter[0] = 1 chacha20.XORKeyStream(out, ciphertext, &counter, &c.key) return ret, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_amd64.s�������������������0000644�0610621�0607500�00000323056�13172163317�027616� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file was originally from https://golang.org/cl/24717 by Vlad Krasnov of CloudFlare. // +build go1.7,amd64,!gccgo,!appengine #include "textflag.h" // General register allocation #define oup DI #define inp SI #define inl BX #define adp CX // free to reuse, after we hash the additional data #define keyp R8 // free to reuse, when we copy the key to stack #define itr2 R9 // general iterator #define itr1 CX // general iterator #define acc0 R10 #define acc1 R11 #define acc2 R12 #define t0 R13 #define t1 R14 #define t2 R15 #define t3 R8 // Register and stack allocation for the SSE code #define rStore (0*16)(BP) #define sStore (1*16)(BP) #define state1Store (2*16)(BP) #define state2Store (3*16)(BP) #define tmpStore (4*16)(BP) #define ctr0Store (5*16)(BP) #define ctr1Store (6*16)(BP) #define ctr2Store (7*16)(BP) #define ctr3Store (8*16)(BP) #define A0 X0 #define A1 X1 #define A2 X2 #define B0 X3 #define B1 X4 #define B2 X5 #define C0 X6 #define C1 X7 #define C2 X8 #define D0 X9 #define D1 X10 #define D2 X11 #define T0 X12 #define T1 X13 #define T2 X14 #define T3 X15 #define A3 T0 #define B3 T1 #define C3 T2 #define D3 T3 // Register and stack allocation for the AVX2 code #define rsStoreAVX2 (0*32)(BP) #define state1StoreAVX2 (1*32)(BP) #define state2StoreAVX2 (2*32)(BP) #define ctr0StoreAVX2 (3*32)(BP) #define ctr1StoreAVX2 (4*32)(BP) #define ctr2StoreAVX2 (5*32)(BP) #define ctr3StoreAVX2 (6*32)(BP) #define tmpStoreAVX2 (7*32)(BP) // 256 bytes on stack #define AA0 Y0 #define AA1 Y5 #define AA2 Y6 #define AA3 Y7 #define BB0 Y14 #define BB1 Y9 #define BB2 Y10 #define BB3 Y11 #define CC0 Y12 #define CC1 Y13 #define CC2 Y8 #define CC3 Y15 #define DD0 Y4 #define DD1 Y1 #define DD2 Y2 #define DD3 Y3 #define TT0 DD3 #define TT1 AA3 #define TT2 BB3 #define TT3 CC3 // ChaCha20 constants DATA ·chacha20Constants<>+0x00(SB)/4, $0x61707865 DATA ·chacha20Constants<>+0x04(SB)/4, $0x3320646e DATA ·chacha20Constants<>+0x08(SB)/4, $0x79622d32 DATA ·chacha20Constants<>+0x0c(SB)/4, $0x6b206574 DATA ·chacha20Constants<>+0x10(SB)/4, $0x61707865 DATA ·chacha20Constants<>+0x14(SB)/4, $0x3320646e DATA ·chacha20Constants<>+0x18(SB)/4, $0x79622d32 DATA ·chacha20Constants<>+0x1c(SB)/4, $0x6b206574 // <<< 16 with PSHUFB DATA ·rol16<>+0x00(SB)/8, $0x0504070601000302 DATA ·rol16<>+0x08(SB)/8, $0x0D0C0F0E09080B0A DATA ·rol16<>+0x10(SB)/8, $0x0504070601000302 DATA ·rol16<>+0x18(SB)/8, $0x0D0C0F0E09080B0A // <<< 8 with PSHUFB DATA ·rol8<>+0x00(SB)/8, $0x0605040702010003 DATA ·rol8<>+0x08(SB)/8, $0x0E0D0C0F0A09080B DATA ·rol8<>+0x10(SB)/8, $0x0605040702010003 DATA ·rol8<>+0x18(SB)/8, $0x0E0D0C0F0A09080B DATA ·avx2InitMask<>+0x00(SB)/8, $0x0 DATA ·avx2InitMask<>+0x08(SB)/8, $0x0 DATA ·avx2InitMask<>+0x10(SB)/8, $0x1 DATA ·avx2InitMask<>+0x18(SB)/8, $0x0 DATA ·avx2IncMask<>+0x00(SB)/8, $0x2 DATA ·avx2IncMask<>+0x08(SB)/8, $0x0 DATA ·avx2IncMask<>+0x10(SB)/8, $0x2 DATA ·avx2IncMask<>+0x18(SB)/8, $0x0 // Poly1305 key clamp DATA ·polyClampMask<>+0x00(SB)/8, $0x0FFFFFFC0FFFFFFF DATA ·polyClampMask<>+0x08(SB)/8, $0x0FFFFFFC0FFFFFFC DATA ·polyClampMask<>+0x10(SB)/8, $0xFFFFFFFFFFFFFFFF DATA ·polyClampMask<>+0x18(SB)/8, $0xFFFFFFFFFFFFFFFF DATA ·sseIncMask<>+0x00(SB)/8, $0x1 DATA ·sseIncMask<>+0x08(SB)/8, $0x0 // To load/store the last < 16 bytes in a buffer DATA ·andMask<>+0x00(SB)/8, $0x00000000000000ff DATA ·andMask<>+0x08(SB)/8, $0x0000000000000000 DATA ·andMask<>+0x10(SB)/8, $0x000000000000ffff DATA ·andMask<>+0x18(SB)/8, $0x0000000000000000 DATA ·andMask<>+0x20(SB)/8, $0x0000000000ffffff DATA ·andMask<>+0x28(SB)/8, $0x0000000000000000 DATA ·andMask<>+0x30(SB)/8, $0x00000000ffffffff DATA ·andMask<>+0x38(SB)/8, $0x0000000000000000 DATA ·andMask<>+0x40(SB)/8, $0x000000ffffffffff DATA ·andMask<>+0x48(SB)/8, $0x0000000000000000 DATA ·andMask<>+0x50(SB)/8, $0x0000ffffffffffff DATA ·andMask<>+0x58(SB)/8, $0x0000000000000000 DATA ·andMask<>+0x60(SB)/8, $0x00ffffffffffffff DATA ·andMask<>+0x68(SB)/8, $0x0000000000000000 DATA ·andMask<>+0x70(SB)/8, $0xffffffffffffffff DATA ·andMask<>+0x78(SB)/8, $0x0000000000000000 DATA ·andMask<>+0x80(SB)/8, $0xffffffffffffffff DATA ·andMask<>+0x88(SB)/8, $0x00000000000000ff DATA ·andMask<>+0x90(SB)/8, $0xffffffffffffffff DATA ·andMask<>+0x98(SB)/8, $0x000000000000ffff DATA ·andMask<>+0xa0(SB)/8, $0xffffffffffffffff DATA ·andMask<>+0xa8(SB)/8, $0x0000000000ffffff DATA ·andMask<>+0xb0(SB)/8, $0xffffffffffffffff DATA ·andMask<>+0xb8(SB)/8, $0x00000000ffffffff DATA ·andMask<>+0xc0(SB)/8, $0xffffffffffffffff DATA ·andMask<>+0xc8(SB)/8, $0x000000ffffffffff DATA ·andMask<>+0xd0(SB)/8, $0xffffffffffffffff DATA ·andMask<>+0xd8(SB)/8, $0x0000ffffffffffff DATA ·andMask<>+0xe0(SB)/8, $0xffffffffffffffff DATA ·andMask<>+0xe8(SB)/8, $0x00ffffffffffffff GLOBL ·chacha20Constants<>(SB), (NOPTR+RODATA), $32 GLOBL ·rol16<>(SB), (NOPTR+RODATA), $32 GLOBL ·rol8<>(SB), (NOPTR+RODATA), $32 GLOBL ·sseIncMask<>(SB), (NOPTR+RODATA), $16 GLOBL ·avx2IncMask<>(SB), (NOPTR+RODATA), $32 GLOBL ·avx2InitMask<>(SB), (NOPTR+RODATA), $32 GLOBL ·polyClampMask<>(SB), (NOPTR+RODATA), $32 GLOBL ·andMask<>(SB), (NOPTR+RODATA), $240 // No PALIGNR in Go ASM yet (but VPALIGNR is present). #define shiftB0Left BYTE $0x66; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xdb; BYTE $0x04 // PALIGNR $4, X3, X3 #define shiftB1Left BYTE $0x66; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xe4; BYTE $0x04 // PALIGNR $4, X4, X4 #define shiftB2Left BYTE $0x66; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xed; BYTE $0x04 // PALIGNR $4, X5, X5 #define shiftB3Left BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xed; BYTE $0x04 // PALIGNR $4, X13, X13 #define shiftC0Left BYTE $0x66; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xf6; BYTE $0x08 // PALIGNR $8, X6, X6 #define shiftC1Left BYTE $0x66; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xff; BYTE $0x08 // PALIGNR $8, X7, X7 #define shiftC2Left BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xc0; BYTE $0x08 // PALIGNR $8, X8, X8 #define shiftC3Left BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xf6; BYTE $0x08 // PALIGNR $8, X14, X14 #define shiftD0Left BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xc9; BYTE $0x0c // PALIGNR $12, X9, X9 #define shiftD1Left BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xd2; BYTE $0x0c // PALIGNR $12, X10, X10 #define shiftD2Left BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xdb; BYTE $0x0c // PALIGNR $12, X11, X11 #define shiftD3Left BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xff; BYTE $0x0c // PALIGNR $12, X15, X15 #define shiftB0Right BYTE $0x66; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xdb; BYTE $0x0c // PALIGNR $12, X3, X3 #define shiftB1Right BYTE $0x66; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xe4; BYTE $0x0c // PALIGNR $12, X4, X4 #define shiftB2Right BYTE $0x66; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xed; BYTE $0x0c // PALIGNR $12, X5, X5 #define shiftB3Right BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xed; BYTE $0x0c // PALIGNR $12, X13, X13 #define shiftC0Right shiftC0Left #define shiftC1Right shiftC1Left #define shiftC2Right shiftC2Left #define shiftC3Right shiftC3Left #define shiftD0Right BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xc9; BYTE $0x04 // PALIGNR $4, X9, X9 #define shiftD1Right BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xd2; BYTE $0x04 // PALIGNR $4, X10, X10 #define shiftD2Right BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xdb; BYTE $0x04 // PALIGNR $4, X11, X11 #define shiftD3Right BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xff; BYTE $0x04 // PALIGNR $4, X15, X15 // Some macros #define chachaQR(A, B, C, D, T) \ PADDD B, A; PXOR A, D; PSHUFB ·rol16<>(SB), D \ PADDD D, C; PXOR C, B; MOVO B, T; PSLLL $12, T; PSRLL $20, B; PXOR T, B \ PADDD B, A; PXOR A, D; PSHUFB ·rol8<>(SB), D \ PADDD D, C; PXOR C, B; MOVO B, T; PSLLL $7, T; PSRLL $25, B; PXOR T, B #define chachaQR_AVX2(A, B, C, D, T) \ VPADDD B, A, A; VPXOR A, D, D; VPSHUFB ·rol16<>(SB), D, D \ VPADDD D, C, C; VPXOR C, B, B; VPSLLD $12, B, T; VPSRLD $20, B, B; VPXOR T, B, B \ VPADDD B, A, A; VPXOR A, D, D; VPSHUFB ·rol8<>(SB), D, D \ VPADDD D, C, C; VPXOR C, B, B; VPSLLD $7, B, T; VPSRLD $25, B, B; VPXOR T, B, B #define polyAdd(S) ADDQ S, acc0; ADCQ 8+S, acc1; ADCQ $1, acc2 #define polyMulStage1 MOVQ (0*8)(BP), AX; MOVQ AX, t2; MULQ acc0; MOVQ AX, t0; MOVQ DX, t1; MOVQ (0*8)(BP), AX; MULQ acc1; IMULQ acc2, t2; ADDQ AX, t1; ADCQ DX, t2 #define polyMulStage2 MOVQ (1*8)(BP), AX; MOVQ AX, t3; MULQ acc0; ADDQ AX, t1; ADCQ $0, DX; MOVQ DX, acc0; MOVQ (1*8)(BP), AX; MULQ acc1; ADDQ AX, t2; ADCQ $0, DX #define polyMulStage3 IMULQ acc2, t3; ADDQ acc0, t2; ADCQ DX, t3 #define polyMulReduceStage MOVQ t0, acc0; MOVQ t1, acc1; MOVQ t2, acc2; ANDQ $3, acc2; MOVQ t2, t0; ANDQ $-4, t0; MOVQ t3, t1; SHRQ $2, t2:t3; SHRQ $2, t3; ADDQ t0, acc0; ADCQ t1, acc1; ADCQ $0, acc2; ADDQ t2, acc0; ADCQ t3, acc1; ADCQ $0, acc2 #define polyMulStage1_AVX2 MOVQ (0*8)(BP), DX; MOVQ DX, t2; MULXQ acc0, t0, t1; IMULQ acc2, t2; MULXQ acc1, AX, DX; ADDQ AX, t1; ADCQ DX, t2 #define polyMulStage2_AVX2 MOVQ (1*8)(BP), DX; MULXQ acc0, acc0, AX; ADDQ acc0, t1; MULXQ acc1, acc1, t3; ADCQ acc1, t2; ADCQ $0, t3 #define polyMulStage3_AVX2 IMULQ acc2, DX; ADDQ AX, t2; ADCQ DX, t3 #define polyMul polyMulStage1; polyMulStage2; polyMulStage3; polyMulReduceStage #define polyMulAVX2 polyMulStage1_AVX2; polyMulStage2_AVX2; polyMulStage3_AVX2; polyMulReduceStage // ---------------------------------------------------------------------------- TEXT polyHashADInternal<>(SB), NOSPLIT, $0 // adp points to beginning of additional data // itr2 holds ad length XORQ acc0, acc0 XORQ acc1, acc1 XORQ acc2, acc2 CMPQ itr2, $13 JNE hashADLoop openFastTLSAD: // Special treatment for the TLS case of 13 bytes MOVQ (adp), acc0 MOVQ 5(adp), acc1 SHRQ $24, acc1 MOVQ $1, acc2 polyMul RET hashADLoop: // Hash in 16 byte chunks CMPQ itr2, $16 JB hashADTail polyAdd(0(adp)) LEAQ (1*16)(adp), adp SUBQ $16, itr2 polyMul JMP hashADLoop hashADTail: CMPQ itr2, $0 JE hashADDone // Hash last < 16 byte tail XORQ t0, t0 XORQ t1, t1 XORQ t2, t2 ADDQ itr2, adp hashADTailLoop: SHLQ $8, t1:t0 SHLQ $8, t0 MOVB -1(adp), t2 XORQ t2, t0 DECQ adp DECQ itr2 JNE hashADTailLoop hashADTailFinish: ADDQ t0, acc0; ADCQ t1, acc1; ADCQ $1, acc2 polyMul // Finished AD hashADDone: RET // ---------------------------------------------------------------------------- // func chacha20Poly1305Open(dst, key, src, ad []byte) bool TEXT ·chacha20Poly1305Open(SB), 0, $288-97 // For aligned stack access MOVQ SP, BP ADDQ $32, BP ANDQ $-32, BP MOVQ dst+0(FP), oup MOVQ key+24(FP), keyp MOVQ src+48(FP), inp MOVQ src_len+56(FP), inl MOVQ ad+72(FP), adp // Check for AVX2 support CMPB ·useAVX2(SB), $1 JE chacha20Poly1305Open_AVX2 // Special optimization, for very short buffers CMPQ inl, $128 JBE openSSE128 // About 16% faster // For long buffers, prepare the poly key first MOVOU ·chacha20Constants<>(SB), A0 MOVOU (1*16)(keyp), B0 MOVOU (2*16)(keyp), C0 MOVOU (3*16)(keyp), D0 MOVO D0, T1 // Store state on stack for future use MOVO B0, state1Store MOVO C0, state2Store MOVO D0, ctr3Store MOVQ $10, itr2 openSSEPreparePolyKey: chachaQR(A0, B0, C0, D0, T0) shiftB0Left; shiftC0Left; shiftD0Left chachaQR(A0, B0, C0, D0, T0) shiftB0Right; shiftC0Right; shiftD0Right DECQ itr2 JNE openSSEPreparePolyKey // A0|B0 hold the Poly1305 32-byte key, C0,D0 can be discarded PADDL ·chacha20Constants<>(SB), A0; PADDL state1Store, B0 // Clamp and store the key PAND ·polyClampMask<>(SB), A0 MOVO A0, rStore; MOVO B0, sStore // Hash AAD MOVQ ad_len+80(FP), itr2 CALL polyHashADInternal<>(SB) openSSEMainLoop: CMPQ inl, $256 JB openSSEMainLoopDone // Load state, increment counter blocks MOVO ·chacha20Constants<>(SB), A0; MOVO state1Store, B0; MOVO state2Store, C0; MOVO ctr3Store, D0; PADDL ·sseIncMask<>(SB), D0 MOVO A0, A1; MOVO B0, B1; MOVO C0, C1; MOVO D0, D1; PADDL ·sseIncMask<>(SB), D1 MOVO A1, A2; MOVO B1, B2; MOVO C1, C2; MOVO D1, D2; PADDL ·sseIncMask<>(SB), D2 MOVO A2, A3; MOVO B2, B3; MOVO C2, C3; MOVO D2, D3; PADDL ·sseIncMask<>(SB), D3 // Store counters MOVO D0, ctr0Store; MOVO D1, ctr1Store; MOVO D2, ctr2Store; MOVO D3, ctr3Store // There are 10 ChaCha20 iterations of 2QR each, so for 6 iterations we hash 2 blocks, and for the remaining 4 only 1 block - for a total of 16 MOVQ $4, itr1 MOVQ inp, itr2 openSSEInternalLoop: MOVO C3, tmpStore chachaQR(A0, B0, C0, D0, C3); chachaQR(A1, B1, C1, D1, C3); chachaQR(A2, B2, C2, D2, C3) MOVO tmpStore, C3 MOVO C1, tmpStore chachaQR(A3, B3, C3, D3, C1) MOVO tmpStore, C1 polyAdd(0(itr2)) shiftB0Left; shiftB1Left; shiftB2Left; shiftB3Left shiftC0Left; shiftC1Left; shiftC2Left; shiftC3Left shiftD0Left; shiftD1Left; shiftD2Left; shiftD3Left polyMulStage1 polyMulStage2 LEAQ (2*8)(itr2), itr2 MOVO C3, tmpStore chachaQR(A0, B0, C0, D0, C3); chachaQR(A1, B1, C1, D1, C3); chachaQR(A2, B2, C2, D2, C3) MOVO tmpStore, C3 MOVO C1, tmpStore polyMulStage3 chachaQR(A3, B3, C3, D3, C1) MOVO tmpStore, C1 polyMulReduceStage shiftB0Right; shiftB1Right; shiftB2Right; shiftB3Right shiftC0Right; shiftC1Right; shiftC2Right; shiftC3Right shiftD0Right; shiftD1Right; shiftD2Right; shiftD3Right DECQ itr1 JGE openSSEInternalLoop polyAdd(0(itr2)) polyMul LEAQ (2*8)(itr2), itr2 CMPQ itr1, $-6 JG openSSEInternalLoop // Add in the state PADDD ·chacha20Constants<>(SB), A0; PADDD ·chacha20Constants<>(SB), A1; PADDD ·chacha20Constants<>(SB), A2; PADDD ·chacha20Constants<>(SB), A3 PADDD state1Store, B0; PADDD state1Store, B1; PADDD state1Store, B2; PADDD state1Store, B3 PADDD state2Store, C0; PADDD state2Store, C1; PADDD state2Store, C2; PADDD state2Store, C3 PADDD ctr0Store, D0; PADDD ctr1Store, D1; PADDD ctr2Store, D2; PADDD ctr3Store, D3 // Load - xor - store MOVO D3, tmpStore MOVOU (0*16)(inp), D3; PXOR D3, A0; MOVOU A0, (0*16)(oup) MOVOU (1*16)(inp), D3; PXOR D3, B0; MOVOU B0, (1*16)(oup) MOVOU (2*16)(inp), D3; PXOR D3, C0; MOVOU C0, (2*16)(oup) MOVOU (3*16)(inp), D3; PXOR D3, D0; MOVOU D0, (3*16)(oup) MOVOU (4*16)(inp), D0; PXOR D0, A1; MOVOU A1, (4*16)(oup) MOVOU (5*16)(inp), D0; PXOR D0, B1; MOVOU B1, (5*16)(oup) MOVOU (6*16)(inp), D0; PXOR D0, C1; MOVOU C1, (6*16)(oup) MOVOU (7*16)(inp), D0; PXOR D0, D1; MOVOU D1, (7*16)(oup) MOVOU (8*16)(inp), D0; PXOR D0, A2; MOVOU A2, (8*16)(oup) MOVOU (9*16)(inp), D0; PXOR D0, B2; MOVOU B2, (9*16)(oup) MOVOU (10*16)(inp), D0; PXOR D0, C2; MOVOU C2, (10*16)(oup) MOVOU (11*16)(inp), D0; PXOR D0, D2; MOVOU D2, (11*16)(oup) MOVOU (12*16)(inp), D0; PXOR D0, A3; MOVOU A3, (12*16)(oup) MOVOU (13*16)(inp), D0; PXOR D0, B3; MOVOU B3, (13*16)(oup) MOVOU (14*16)(inp), D0; PXOR D0, C3; MOVOU C3, (14*16)(oup) MOVOU (15*16)(inp), D0; PXOR tmpStore, D0; MOVOU D0, (15*16)(oup) LEAQ 256(inp), inp LEAQ 256(oup), oup SUBQ $256, inl JMP openSSEMainLoop openSSEMainLoopDone: // Handle the various tail sizes efficiently TESTQ inl, inl JE openSSEFinalize CMPQ inl, $64 JBE openSSETail64 CMPQ inl, $128 JBE openSSETail128 CMPQ inl, $192 JBE openSSETail192 JMP openSSETail256 openSSEFinalize: // Hash in the PT, AAD lengths ADDQ ad_len+80(FP), acc0; ADCQ src_len+56(FP), acc1; ADCQ $1, acc2 polyMul // Final reduce MOVQ acc0, t0 MOVQ acc1, t1 MOVQ acc2, t2 SUBQ $-5, acc0 SBBQ $-1, acc1 SBBQ $3, acc2 CMOVQCS t0, acc0 CMOVQCS t1, acc1 CMOVQCS t2, acc2 // Add in the "s" part of the key ADDQ 0+sStore, acc0 ADCQ 8+sStore, acc1 // Finally, constant time compare to the tag at the end of the message XORQ AX, AX MOVQ $1, DX XORQ (0*8)(inp), acc0 XORQ (1*8)(inp), acc1 ORQ acc1, acc0 CMOVQEQ DX, AX // Return true iff tags are equal MOVB AX, ret+96(FP) RET // ---------------------------------------------------------------------------- // Special optimization for buffers smaller than 129 bytes openSSE128: // For up to 128 bytes of ciphertext and 64 bytes for the poly key, we require to process three blocks MOVOU ·chacha20Constants<>(SB), A0; MOVOU (1*16)(keyp), B0; MOVOU (2*16)(keyp), C0; MOVOU (3*16)(keyp), D0 MOVO A0, A1; MOVO B0, B1; MOVO C0, C1; MOVO D0, D1; PADDL ·sseIncMask<>(SB), D1 MOVO A1, A2; MOVO B1, B2; MOVO C1, C2; MOVO D1, D2; PADDL ·sseIncMask<>(SB), D2 MOVO B0, T1; MOVO C0, T2; MOVO D1, T3 MOVQ $10, itr2 openSSE128InnerCipherLoop: chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0); chachaQR(A2, B2, C2, D2, T0) shiftB0Left; shiftB1Left; shiftB2Left shiftC0Left; shiftC1Left; shiftC2Left shiftD0Left; shiftD1Left; shiftD2Left chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0); chachaQR(A2, B2, C2, D2, T0) shiftB0Right; shiftB1Right; shiftB2Right shiftC0Right; shiftC1Right; shiftC2Right shiftD0Right; shiftD1Right; shiftD2Right DECQ itr2 JNE openSSE128InnerCipherLoop // A0|B0 hold the Poly1305 32-byte key, C0,D0 can be discarded PADDL ·chacha20Constants<>(SB), A0; PADDL ·chacha20Constants<>(SB), A1; PADDL ·chacha20Constants<>(SB), A2 PADDL T1, B0; PADDL T1, B1; PADDL T1, B2 PADDL T2, C1; PADDL T2, C2 PADDL T3, D1; PADDL ·sseIncMask<>(SB), T3; PADDL T3, D2 // Clamp and store the key PAND ·polyClampMask<>(SB), A0 MOVOU A0, rStore; MOVOU B0, sStore // Hash MOVQ ad_len+80(FP), itr2 CALL polyHashADInternal<>(SB) openSSE128Open: CMPQ inl, $16 JB openSSETail16 SUBQ $16, inl // Load for hashing polyAdd(0(inp)) // Load for decryption MOVOU (inp), T0; PXOR T0, A1; MOVOU A1, (oup) LEAQ (1*16)(inp), inp LEAQ (1*16)(oup), oup polyMul // Shift the stream "left" MOVO B1, A1 MOVO C1, B1 MOVO D1, C1 MOVO A2, D1 MOVO B2, A2 MOVO C2, B2 MOVO D2, C2 JMP openSSE128Open openSSETail16: TESTQ inl, inl JE openSSEFinalize // We can safely load the CT from the end, because it is padded with the MAC MOVQ inl, itr2 SHLQ $4, itr2 LEAQ ·andMask<>(SB), t0 MOVOU (inp), T0 ADDQ inl, inp PAND -16(t0)(itr2*1), T0 MOVO T0, 0+tmpStore MOVQ T0, t0 MOVQ 8+tmpStore, t1 PXOR A1, T0 // We can only store one byte at a time, since plaintext can be shorter than 16 bytes openSSETail16Store: MOVQ T0, t3 MOVB t3, (oup) PSRLDQ $1, T0 INCQ oup DECQ inl JNE openSSETail16Store ADDQ t0, acc0; ADCQ t1, acc1; ADCQ $1, acc2 polyMul JMP openSSEFinalize // ---------------------------------------------------------------------------- // Special optimization for the last 64 bytes of ciphertext openSSETail64: // Need to decrypt up to 64 bytes - prepare single block MOVO ·chacha20Constants<>(SB), A0; MOVO state1Store, B0; MOVO state2Store, C0; MOVO ctr3Store, D0; PADDL ·sseIncMask<>(SB), D0; MOVO D0, ctr0Store XORQ itr2, itr2 MOVQ inl, itr1 CMPQ itr1, $16 JB openSSETail64LoopB openSSETail64LoopA: // Perform ChaCha rounds, while hashing the remaining input polyAdd(0(inp)(itr2*1)) polyMul SUBQ $16, itr1 openSSETail64LoopB: ADDQ $16, itr2 chachaQR(A0, B0, C0, D0, T0) shiftB0Left; shiftC0Left; shiftD0Left chachaQR(A0, B0, C0, D0, T0) shiftB0Right; shiftC0Right; shiftD0Right CMPQ itr1, $16 JAE openSSETail64LoopA CMPQ itr2, $160 JNE openSSETail64LoopB PADDL ·chacha20Constants<>(SB), A0; PADDL state1Store, B0; PADDL state2Store, C0; PADDL ctr0Store, D0 openSSETail64DecLoop: CMPQ inl, $16 JB openSSETail64DecLoopDone SUBQ $16, inl MOVOU (inp), T0 PXOR T0, A0 MOVOU A0, (oup) LEAQ 16(inp), inp LEAQ 16(oup), oup MOVO B0, A0 MOVO C0, B0 MOVO D0, C0 JMP openSSETail64DecLoop openSSETail64DecLoopDone: MOVO A0, A1 JMP openSSETail16 // ---------------------------------------------------------------------------- // Special optimization for the last 128 bytes of ciphertext openSSETail128: // Need to decrypt up to 128 bytes - prepare two blocks MOVO ·chacha20Constants<>(SB), A1; MOVO state1Store, B1; MOVO state2Store, C1; MOVO ctr3Store, D1; PADDL ·sseIncMask<>(SB), D1; MOVO D1, ctr0Store MOVO A1, A0; MOVO B1, B0; MOVO C1, C0; MOVO D1, D0; PADDL ·sseIncMask<>(SB), D0; MOVO D0, ctr1Store XORQ itr2, itr2 MOVQ inl, itr1 ANDQ $-16, itr1 openSSETail128LoopA: // Perform ChaCha rounds, while hashing the remaining input polyAdd(0(inp)(itr2*1)) polyMul openSSETail128LoopB: ADDQ $16, itr2 chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0) shiftB0Left; shiftC0Left; shiftD0Left shiftB1Left; shiftC1Left; shiftD1Left chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0) shiftB0Right; shiftC0Right; shiftD0Right shiftB1Right; shiftC1Right; shiftD1Right CMPQ itr2, itr1 JB openSSETail128LoopA CMPQ itr2, $160 JNE openSSETail128LoopB PADDL ·chacha20Constants<>(SB), A0; PADDL ·chacha20Constants<>(SB), A1 PADDL state1Store, B0; PADDL state1Store, B1 PADDL state2Store, C0; PADDL state2Store, C1 PADDL ctr1Store, D0; PADDL ctr0Store, D1 MOVOU (0*16)(inp), T0; MOVOU (1*16)(inp), T1; MOVOU (2*16)(inp), T2; MOVOU (3*16)(inp), T3 PXOR T0, A1; PXOR T1, B1; PXOR T2, C1; PXOR T3, D1 MOVOU A1, (0*16)(oup); MOVOU B1, (1*16)(oup); MOVOU C1, (2*16)(oup); MOVOU D1, (3*16)(oup) SUBQ $64, inl LEAQ 64(inp), inp LEAQ 64(oup), oup JMP openSSETail64DecLoop // ---------------------------------------------------------------------------- // Special optimization for the last 192 bytes of ciphertext openSSETail192: // Need to decrypt up to 192 bytes - prepare three blocks MOVO ·chacha20Constants<>(SB), A2; MOVO state1Store, B2; MOVO state2Store, C2; MOVO ctr3Store, D2; PADDL ·sseIncMask<>(SB), D2; MOVO D2, ctr0Store MOVO A2, A1; MOVO B2, B1; MOVO C2, C1; MOVO D2, D1; PADDL ·sseIncMask<>(SB), D1; MOVO D1, ctr1Store MOVO A1, A0; MOVO B1, B0; MOVO C1, C0; MOVO D1, D0; PADDL ·sseIncMask<>(SB), D0; MOVO D0, ctr2Store MOVQ inl, itr1 MOVQ $160, itr2 CMPQ itr1, $160 CMOVQGT itr2, itr1 ANDQ $-16, itr1 XORQ itr2, itr2 openSSLTail192LoopA: // Perform ChaCha rounds, while hashing the remaining input polyAdd(0(inp)(itr2*1)) polyMul openSSLTail192LoopB: ADDQ $16, itr2 chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0); chachaQR(A2, B2, C2, D2, T0) shiftB0Left; shiftC0Left; shiftD0Left shiftB1Left; shiftC1Left; shiftD1Left shiftB2Left; shiftC2Left; shiftD2Left chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0); chachaQR(A2, B2, C2, D2, T0) shiftB0Right; shiftC0Right; shiftD0Right shiftB1Right; shiftC1Right; shiftD1Right shiftB2Right; shiftC2Right; shiftD2Right CMPQ itr2, itr1 JB openSSLTail192LoopA CMPQ itr2, $160 JNE openSSLTail192LoopB CMPQ inl, $176 JB openSSLTail192Store polyAdd(160(inp)) polyMul CMPQ inl, $192 JB openSSLTail192Store polyAdd(176(inp)) polyMul openSSLTail192Store: PADDL ·chacha20Constants<>(SB), A0; PADDL ·chacha20Constants<>(SB), A1; PADDL ·chacha20Constants<>(SB), A2 PADDL state1Store, B0; PADDL state1Store, B1; PADDL state1Store, B2 PADDL state2Store, C0; PADDL state2Store, C1; PADDL state2Store, C2 PADDL ctr2Store, D0; PADDL ctr1Store, D1; PADDL ctr0Store, D2 MOVOU (0*16)(inp), T0; MOVOU (1*16)(inp), T1; MOVOU (2*16)(inp), T2; MOVOU (3*16)(inp), T3 PXOR T0, A2; PXOR T1, B2; PXOR T2, C2; PXOR T3, D2 MOVOU A2, (0*16)(oup); MOVOU B2, (1*16)(oup); MOVOU C2, (2*16)(oup); MOVOU D2, (3*16)(oup) MOVOU (4*16)(inp), T0; MOVOU (5*16)(inp), T1; MOVOU (6*16)(inp), T2; MOVOU (7*16)(inp), T3 PXOR T0, A1; PXOR T1, B1; PXOR T2, C1; PXOR T3, D1 MOVOU A1, (4*16)(oup); MOVOU B1, (5*16)(oup); MOVOU C1, (6*16)(oup); MOVOU D1, (7*16)(oup) SUBQ $128, inl LEAQ 128(inp), inp LEAQ 128(oup), oup JMP openSSETail64DecLoop // ---------------------------------------------------------------------------- // Special optimization for the last 256 bytes of ciphertext openSSETail256: // Need to decrypt up to 256 bytes - prepare four blocks MOVO ·chacha20Constants<>(SB), A0; MOVO state1Store, B0; MOVO state2Store, C0; MOVO ctr3Store, D0; PADDL ·sseIncMask<>(SB), D0 MOVO A0, A1; MOVO B0, B1; MOVO C0, C1; MOVO D0, D1; PADDL ·sseIncMask<>(SB), D1 MOVO A1, A2; MOVO B1, B2; MOVO C1, C2; MOVO D1, D2; PADDL ·sseIncMask<>(SB), D2 MOVO A2, A3; MOVO B2, B3; MOVO C2, C3; MOVO D2, D3; PADDL ·sseIncMask<>(SB), D3 // Store counters MOVO D0, ctr0Store; MOVO D1, ctr1Store; MOVO D2, ctr2Store; MOVO D3, ctr3Store XORQ itr2, itr2 openSSETail256Loop: // This loop inteleaves 8 ChaCha quarter rounds with 1 poly multiplication polyAdd(0(inp)(itr2*1)) MOVO C3, tmpStore chachaQR(A0, B0, C0, D0, C3); chachaQR(A1, B1, C1, D1, C3); chachaQR(A2, B2, C2, D2, C3) MOVO tmpStore, C3 MOVO C1, tmpStore chachaQR(A3, B3, C3, D3, C1) MOVO tmpStore, C1 shiftB0Left; shiftB1Left; shiftB2Left; shiftB3Left shiftC0Left; shiftC1Left; shiftC2Left; shiftC3Left shiftD0Left; shiftD1Left; shiftD2Left; shiftD3Left polyMulStage1 polyMulStage2 MOVO C3, tmpStore chachaQR(A0, B0, C0, D0, C3); chachaQR(A1, B1, C1, D1, C3); chachaQR(A2, B2, C2, D2, C3) MOVO tmpStore, C3 MOVO C1, tmpStore chachaQR(A3, B3, C3, D3, C1) MOVO tmpStore, C1 polyMulStage3 polyMulReduceStage shiftB0Right; shiftB1Right; shiftB2Right; shiftB3Right shiftC0Right; shiftC1Right; shiftC2Right; shiftC3Right shiftD0Right; shiftD1Right; shiftD2Right; shiftD3Right ADDQ $2*8, itr2 CMPQ itr2, $160 JB openSSETail256Loop MOVQ inl, itr1 ANDQ $-16, itr1 openSSETail256HashLoop: polyAdd(0(inp)(itr2*1)) polyMul ADDQ $2*8, itr2 CMPQ itr2, itr1 JB openSSETail256HashLoop // Add in the state PADDD ·chacha20Constants<>(SB), A0; PADDD ·chacha20Constants<>(SB), A1; PADDD ·chacha20Constants<>(SB), A2; PADDD ·chacha20Constants<>(SB), A3 PADDD state1Store, B0; PADDD state1Store, B1; PADDD state1Store, B2; PADDD state1Store, B3 PADDD state2Store, C0; PADDD state2Store, C1; PADDD state2Store, C2; PADDD state2Store, C3 PADDD ctr0Store, D0; PADDD ctr1Store, D1; PADDD ctr2Store, D2; PADDD ctr3Store, D3 MOVO D3, tmpStore // Load - xor - store MOVOU (0*16)(inp), D3; PXOR D3, A0 MOVOU (1*16)(inp), D3; PXOR D3, B0 MOVOU (2*16)(inp), D3; PXOR D3, C0 MOVOU (3*16)(inp), D3; PXOR D3, D0 MOVOU A0, (0*16)(oup) MOVOU B0, (1*16)(oup) MOVOU C0, (2*16)(oup) MOVOU D0, (3*16)(oup) MOVOU (4*16)(inp), A0; MOVOU (5*16)(inp), B0; MOVOU (6*16)(inp), C0; MOVOU (7*16)(inp), D0 PXOR A0, A1; PXOR B0, B1; PXOR C0, C1; PXOR D0, D1 MOVOU A1, (4*16)(oup); MOVOU B1, (5*16)(oup); MOVOU C1, (6*16)(oup); MOVOU D1, (7*16)(oup) MOVOU (8*16)(inp), A0; MOVOU (9*16)(inp), B0; MOVOU (10*16)(inp), C0; MOVOU (11*16)(inp), D0 PXOR A0, A2; PXOR B0, B2; PXOR C0, C2; PXOR D0, D2 MOVOU A2, (8*16)(oup); MOVOU B2, (9*16)(oup); MOVOU C2, (10*16)(oup); MOVOU D2, (11*16)(oup) LEAQ 192(inp), inp LEAQ 192(oup), oup SUBQ $192, inl MOVO A3, A0 MOVO B3, B0 MOVO C3, C0 MOVO tmpStore, D0 JMP openSSETail64DecLoop // ---------------------------------------------------------------------------- // ------------------------- AVX2 Code ---------------------------------------- chacha20Poly1305Open_AVX2: VZEROUPPER VMOVDQU ·chacha20Constants<>(SB), AA0 BYTE $0xc4; BYTE $0x42; BYTE $0x7d; BYTE $0x5a; BYTE $0x70; BYTE $0x10 // broadcasti128 16(r8), ymm14 BYTE $0xc4; BYTE $0x42; BYTE $0x7d; BYTE $0x5a; BYTE $0x60; BYTE $0x20 // broadcasti128 32(r8), ymm12 BYTE $0xc4; BYTE $0xc2; BYTE $0x7d; BYTE $0x5a; BYTE $0x60; BYTE $0x30 // broadcasti128 48(r8), ymm4 VPADDD ·avx2InitMask<>(SB), DD0, DD0 // Special optimization, for very short buffers CMPQ inl, $192 JBE openAVX2192 CMPQ inl, $320 JBE openAVX2320 // For the general key prepare the key first - as a byproduct we have 64 bytes of cipher stream VMOVDQA BB0, state1StoreAVX2 VMOVDQA CC0, state2StoreAVX2 VMOVDQA DD0, ctr3StoreAVX2 MOVQ $10, itr2 openAVX2PreparePolyKey: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0) VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $12, DD0, DD0, DD0 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0) VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $4, DD0, DD0, DD0 DECQ itr2 JNE openAVX2PreparePolyKey VPADDD ·chacha20Constants<>(SB), AA0, AA0 VPADDD state1StoreAVX2, BB0, BB0 VPADDD state2StoreAVX2, CC0, CC0 VPADDD ctr3StoreAVX2, DD0, DD0 VPERM2I128 $0x02, AA0, BB0, TT0 // Clamp and store poly key VPAND ·polyClampMask<>(SB), TT0, TT0 VMOVDQA TT0, rsStoreAVX2 // Stream for the first 64 bytes VPERM2I128 $0x13, AA0, BB0, AA0 VPERM2I128 $0x13, CC0, DD0, BB0 // Hash AD + first 64 bytes MOVQ ad_len+80(FP), itr2 CALL polyHashADInternal<>(SB) XORQ itr1, itr1 openAVX2InitialHash64: polyAdd(0(inp)(itr1*1)) polyMulAVX2 ADDQ $16, itr1 CMPQ itr1, $64 JNE openAVX2InitialHash64 // Decrypt the first 64 bytes VPXOR (0*32)(inp), AA0, AA0 VPXOR (1*32)(inp), BB0, BB0 VMOVDQU AA0, (0*32)(oup) VMOVDQU BB0, (1*32)(oup) LEAQ (2*32)(inp), inp LEAQ (2*32)(oup), oup SUBQ $64, inl openAVX2MainLoop: CMPQ inl, $512 JB openAVX2MainLoopDone // Load state, increment counter blocks, store the incremented counters VMOVDQU ·chacha20Constants<>(SB), AA0; VMOVDQA AA0, AA1; VMOVDQA AA0, AA2; VMOVDQA AA0, AA3 VMOVDQA state1StoreAVX2, BB0; VMOVDQA BB0, BB1; VMOVDQA BB0, BB2; VMOVDQA BB0, BB3 VMOVDQA state2StoreAVX2, CC0; VMOVDQA CC0, CC1; VMOVDQA CC0, CC2; VMOVDQA CC0, CC3 VMOVDQA ctr3StoreAVX2, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD1; VPADDD ·avx2IncMask<>(SB), DD1, DD2; VPADDD ·avx2IncMask<>(SB), DD2, DD3 VMOVDQA DD0, ctr0StoreAVX2; VMOVDQA DD1, ctr1StoreAVX2; VMOVDQA DD2, ctr2StoreAVX2; VMOVDQA DD3, ctr3StoreAVX2 XORQ itr1, itr1 openAVX2InternalLoop: // Lets just say this spaghetti loop interleaves 2 quarter rounds with 3 poly multiplications // Effectively per 512 bytes of stream we hash 480 bytes of ciphertext polyAdd(0*8(inp)(itr1*1)) VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 polyMulStage1_AVX2 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 polyMulStage2_AVX2 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 polyMulStage3_AVX2 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyMulReduceStage VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol8<>(SB), DD0, DD0; VPSHUFB ·rol8<>(SB), DD1, DD1; VPSHUFB ·rol8<>(SB), DD2, DD2; VPSHUFB ·rol8<>(SB), DD3, DD3 polyAdd(2*8(inp)(itr1*1)) VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 polyMulStage1_AVX2 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $7, BB0, CC3; VPSRLD $25, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $7, BB1, CC3; VPSRLD $25, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $7, BB2, CC3; VPSRLD $25, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $7, BB3, CC3; VPSRLD $25, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyMulStage2_AVX2 VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $4, BB2, BB2, BB2; VPALIGNR $4, BB3, BB3, BB3 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $8, CC3, CC3, CC3 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1; VPALIGNR $12, DD2, DD2, DD2; VPALIGNR $12, DD3, DD3, DD3 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 polyMulStage3_AVX2 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 polyMulReduceStage VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 polyAdd(4*8(inp)(itr1*1)) LEAQ (6*8)(itr1), itr1 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyMulStage1_AVX2 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 polyMulStage2_AVX2 VPSHUFB ·rol8<>(SB), DD0, DD0; VPSHUFB ·rol8<>(SB), DD1, DD1; VPSHUFB ·rol8<>(SB), DD2, DD2; VPSHUFB ·rol8<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 polyMulStage3_AVX2 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $7, BB0, CC3; VPSRLD $25, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $7, BB1, CC3; VPSRLD $25, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $7, BB2, CC3; VPSRLD $25, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $7, BB3, CC3; VPSRLD $25, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyMulReduceStage VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $12, BB2, BB2, BB2; VPALIGNR $12, BB3, BB3, BB3 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $8, CC3, CC3, CC3 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1; VPALIGNR $4, DD2, DD2, DD2; VPALIGNR $4, DD3, DD3, DD3 CMPQ itr1, $480 JNE openAVX2InternalLoop VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1; VPADDD ·chacha20Constants<>(SB), AA2, AA2; VPADDD ·chacha20Constants<>(SB), AA3, AA3 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1; VPADDD state1StoreAVX2, BB2, BB2; VPADDD state1StoreAVX2, BB3, BB3 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1; VPADDD state2StoreAVX2, CC2, CC2; VPADDD state2StoreAVX2, CC3, CC3 VPADDD ctr0StoreAVX2, DD0, DD0; VPADDD ctr1StoreAVX2, DD1, DD1; VPADDD ctr2StoreAVX2, DD2, DD2; VPADDD ctr3StoreAVX2, DD3, DD3 VMOVDQA CC3, tmpStoreAVX2 // We only hashed 480 of the 512 bytes available - hash the remaining 32 here polyAdd(480(inp)) polyMulAVX2 VPERM2I128 $0x02, AA0, BB0, CC3; VPERM2I128 $0x13, AA0, BB0, BB0; VPERM2I128 $0x02, CC0, DD0, AA0; VPERM2I128 $0x13, CC0, DD0, CC0 VPXOR (0*32)(inp), CC3, CC3; VPXOR (1*32)(inp), AA0, AA0; VPXOR (2*32)(inp), BB0, BB0; VPXOR (3*32)(inp), CC0, CC0 VMOVDQU CC3, (0*32)(oup); VMOVDQU AA0, (1*32)(oup); VMOVDQU BB0, (2*32)(oup); VMOVDQU CC0, (3*32)(oup) VPERM2I128 $0x02, AA1, BB1, AA0; VPERM2I128 $0x02, CC1, DD1, BB0; VPERM2I128 $0x13, AA1, BB1, CC0; VPERM2I128 $0x13, CC1, DD1, DD0 VPXOR (4*32)(inp), AA0, AA0; VPXOR (5*32)(inp), BB0, BB0; VPXOR (6*32)(inp), CC0, CC0; VPXOR (7*32)(inp), DD0, DD0 VMOVDQU AA0, (4*32)(oup); VMOVDQU BB0, (5*32)(oup); VMOVDQU CC0, (6*32)(oup); VMOVDQU DD0, (7*32)(oup) // and here polyAdd(496(inp)) polyMulAVX2 VPERM2I128 $0x02, AA2, BB2, AA0; VPERM2I128 $0x02, CC2, DD2, BB0; VPERM2I128 $0x13, AA2, BB2, CC0; VPERM2I128 $0x13, CC2, DD2, DD0 VPXOR (8*32)(inp), AA0, AA0; VPXOR (9*32)(inp), BB0, BB0; VPXOR (10*32)(inp), CC0, CC0; VPXOR (11*32)(inp), DD0, DD0 VMOVDQU AA0, (8*32)(oup); VMOVDQU BB0, (9*32)(oup); VMOVDQU CC0, (10*32)(oup); VMOVDQU DD0, (11*32)(oup) VPERM2I128 $0x02, AA3, BB3, AA0; VPERM2I128 $0x02, tmpStoreAVX2, DD3, BB0; VPERM2I128 $0x13, AA3, BB3, CC0; VPERM2I128 $0x13, tmpStoreAVX2, DD3, DD0 VPXOR (12*32)(inp), AA0, AA0; VPXOR (13*32)(inp), BB0, BB0; VPXOR (14*32)(inp), CC0, CC0; VPXOR (15*32)(inp), DD0, DD0 VMOVDQU AA0, (12*32)(oup); VMOVDQU BB0, (13*32)(oup); VMOVDQU CC0, (14*32)(oup); VMOVDQU DD0, (15*32)(oup) LEAQ (32*16)(inp), inp LEAQ (32*16)(oup), oup SUBQ $(32*16), inl JMP openAVX2MainLoop openAVX2MainLoopDone: // Handle the various tail sizes efficiently TESTQ inl, inl JE openSSEFinalize CMPQ inl, $128 JBE openAVX2Tail128 CMPQ inl, $256 JBE openAVX2Tail256 CMPQ inl, $384 JBE openAVX2Tail384 JMP openAVX2Tail512 // ---------------------------------------------------------------------------- // Special optimization for buffers smaller than 193 bytes openAVX2192: // For up to 192 bytes of ciphertext and 64 bytes for the poly key, we process four blocks VMOVDQA AA0, AA1 VMOVDQA BB0, BB1 VMOVDQA CC0, CC1 VPADDD ·avx2IncMask<>(SB), DD0, DD1 VMOVDQA AA0, AA2 VMOVDQA BB0, BB2 VMOVDQA CC0, CC2 VMOVDQA DD0, DD2 VMOVDQA DD1, TT3 MOVQ $10, itr2 openAVX2192InnerCipherLoop: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1 DECQ itr2 JNE openAVX2192InnerCipherLoop VPADDD AA2, AA0, AA0; VPADDD AA2, AA1, AA1 VPADDD BB2, BB0, BB0; VPADDD BB2, BB1, BB1 VPADDD CC2, CC0, CC0; VPADDD CC2, CC1, CC1 VPADDD DD2, DD0, DD0; VPADDD TT3, DD1, DD1 VPERM2I128 $0x02, AA0, BB0, TT0 // Clamp and store poly key VPAND ·polyClampMask<>(SB), TT0, TT0 VMOVDQA TT0, rsStoreAVX2 // Stream for up to 192 bytes VPERM2I128 $0x13, AA0, BB0, AA0 VPERM2I128 $0x13, CC0, DD0, BB0 VPERM2I128 $0x02, AA1, BB1, CC0 VPERM2I128 $0x02, CC1, DD1, DD0 VPERM2I128 $0x13, AA1, BB1, AA1 VPERM2I128 $0x13, CC1, DD1, BB1 openAVX2ShortOpen: // Hash MOVQ ad_len+80(FP), itr2 CALL polyHashADInternal<>(SB) openAVX2ShortOpenLoop: CMPQ inl, $32 JB openAVX2ShortTail32 SUBQ $32, inl // Load for hashing polyAdd(0*8(inp)) polyMulAVX2 polyAdd(2*8(inp)) polyMulAVX2 // Load for decryption VPXOR (inp), AA0, AA0 VMOVDQU AA0, (oup) LEAQ (1*32)(inp), inp LEAQ (1*32)(oup), oup // Shift stream left VMOVDQA BB0, AA0 VMOVDQA CC0, BB0 VMOVDQA DD0, CC0 VMOVDQA AA1, DD0 VMOVDQA BB1, AA1 VMOVDQA CC1, BB1 VMOVDQA DD1, CC1 VMOVDQA AA2, DD1 VMOVDQA BB2, AA2 JMP openAVX2ShortOpenLoop openAVX2ShortTail32: CMPQ inl, $16 VMOVDQA A0, A1 JB openAVX2ShortDone SUBQ $16, inl // Load for hashing polyAdd(0*8(inp)) polyMulAVX2 // Load for decryption VPXOR (inp), A0, T0 VMOVDQU T0, (oup) LEAQ (1*16)(inp), inp LEAQ (1*16)(oup), oup VPERM2I128 $0x11, AA0, AA0, AA0 VMOVDQA A0, A1 openAVX2ShortDone: VZEROUPPER JMP openSSETail16 // ---------------------------------------------------------------------------- // Special optimization for buffers smaller than 321 bytes openAVX2320: // For up to 320 bytes of ciphertext and 64 bytes for the poly key, we process six blocks VMOVDQA AA0, AA1; VMOVDQA BB0, BB1; VMOVDQA CC0, CC1; VPADDD ·avx2IncMask<>(SB), DD0, DD1 VMOVDQA AA0, AA2; VMOVDQA BB0, BB2; VMOVDQA CC0, CC2; VPADDD ·avx2IncMask<>(SB), DD1, DD2 VMOVDQA BB0, TT1; VMOVDQA CC0, TT2; VMOVDQA DD0, TT3 MOVQ $10, itr2 openAVX2320InnerCipherLoop: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0); chachaQR_AVX2(AA2, BB2, CC2, DD2, TT0) VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $4, BB2, BB2, BB2 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1; VPALIGNR $12, DD2, DD2, DD2 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0); chachaQR_AVX2(AA2, BB2, CC2, DD2, TT0) VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $12, BB2, BB2, BB2 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1; VPALIGNR $4, DD2, DD2, DD2 DECQ itr2 JNE openAVX2320InnerCipherLoop VMOVDQA ·chacha20Constants<>(SB), TT0 VPADDD TT0, AA0, AA0; VPADDD TT0, AA1, AA1; VPADDD TT0, AA2, AA2 VPADDD TT1, BB0, BB0; VPADDD TT1, BB1, BB1; VPADDD TT1, BB2, BB2 VPADDD TT2, CC0, CC0; VPADDD TT2, CC1, CC1; VPADDD TT2, CC2, CC2 VMOVDQA ·avx2IncMask<>(SB), TT0 VPADDD TT3, DD0, DD0; VPADDD TT0, TT3, TT3 VPADDD TT3, DD1, DD1; VPADDD TT0, TT3, TT3 VPADDD TT3, DD2, DD2 // Clamp and store poly key VPERM2I128 $0x02, AA0, BB0, TT0 VPAND ·polyClampMask<>(SB), TT0, TT0 VMOVDQA TT0, rsStoreAVX2 // Stream for up to 320 bytes VPERM2I128 $0x13, AA0, BB0, AA0 VPERM2I128 $0x13, CC0, DD0, BB0 VPERM2I128 $0x02, AA1, BB1, CC0 VPERM2I128 $0x02, CC1, DD1, DD0 VPERM2I128 $0x13, AA1, BB1, AA1 VPERM2I128 $0x13, CC1, DD1, BB1 VPERM2I128 $0x02, AA2, BB2, CC1 VPERM2I128 $0x02, CC2, DD2, DD1 VPERM2I128 $0x13, AA2, BB2, AA2 VPERM2I128 $0x13, CC2, DD2, BB2 JMP openAVX2ShortOpen // ---------------------------------------------------------------------------- // Special optimization for the last 128 bytes of ciphertext openAVX2Tail128: // Need to decrypt up to 128 bytes - prepare two blocks VMOVDQA ·chacha20Constants<>(SB), AA1 VMOVDQA state1StoreAVX2, BB1 VMOVDQA state2StoreAVX2, CC1 VMOVDQA ctr3StoreAVX2, DD1 VPADDD ·avx2IncMask<>(SB), DD1, DD1 VMOVDQA DD1, DD0 XORQ itr2, itr2 MOVQ inl, itr1 ANDQ $-16, itr1 TESTQ itr1, itr1 JE openAVX2Tail128LoopB openAVX2Tail128LoopA: // Perform ChaCha rounds, while hashing the remaining input polyAdd(0(inp)(itr2*1)) polyMulAVX2 openAVX2Tail128LoopB: ADDQ $16, itr2 chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) VPALIGNR $4, BB1, BB1, BB1 VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $12, DD1, DD1, DD1 chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) VPALIGNR $12, BB1, BB1, BB1 VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $4, DD1, DD1, DD1 CMPQ itr2, itr1 JB openAVX2Tail128LoopA CMPQ itr2, $160 JNE openAVX2Tail128LoopB VPADDD ·chacha20Constants<>(SB), AA1, AA1 VPADDD state1StoreAVX2, BB1, BB1 VPADDD state2StoreAVX2, CC1, CC1 VPADDD DD0, DD1, DD1 VPERM2I128 $0x02, AA1, BB1, AA0; VPERM2I128 $0x02, CC1, DD1, BB0; VPERM2I128 $0x13, AA1, BB1, CC0; VPERM2I128 $0x13, CC1, DD1, DD0 openAVX2TailLoop: CMPQ inl, $32 JB openAVX2Tail SUBQ $32, inl // Load for decryption VPXOR (inp), AA0, AA0 VMOVDQU AA0, (oup) LEAQ (1*32)(inp), inp LEAQ (1*32)(oup), oup VMOVDQA BB0, AA0 VMOVDQA CC0, BB0 VMOVDQA DD0, CC0 JMP openAVX2TailLoop openAVX2Tail: CMPQ inl, $16 VMOVDQA A0, A1 JB openAVX2TailDone SUBQ $16, inl // Load for decryption VPXOR (inp), A0, T0 VMOVDQU T0, (oup) LEAQ (1*16)(inp), inp LEAQ (1*16)(oup), oup VPERM2I128 $0x11, AA0, AA0, AA0 VMOVDQA A0, A1 openAVX2TailDone: VZEROUPPER JMP openSSETail16 // ---------------------------------------------------------------------------- // Special optimization for the last 256 bytes of ciphertext openAVX2Tail256: // Need to decrypt up to 256 bytes - prepare four blocks VMOVDQA ·chacha20Constants<>(SB), AA0; VMOVDQA AA0, AA1 VMOVDQA state1StoreAVX2, BB0; VMOVDQA BB0, BB1 VMOVDQA state2StoreAVX2, CC0; VMOVDQA CC0, CC1 VMOVDQA ctr3StoreAVX2, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD1 VMOVDQA DD0, TT1 VMOVDQA DD1, TT2 // Compute the number of iterations that will hash data MOVQ inl, tmpStoreAVX2 MOVQ inl, itr1 SUBQ $128, itr1 SHRQ $4, itr1 MOVQ $10, itr2 CMPQ itr1, $10 CMOVQGT itr2, itr1 MOVQ inp, inl XORQ itr2, itr2 openAVX2Tail256LoopA: polyAdd(0(inl)) polyMulAVX2 LEAQ 16(inl), inl // Perform ChaCha rounds, while hashing the remaining input openAVX2Tail256LoopB: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1 INCQ itr2 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1 CMPQ itr2, itr1 JB openAVX2Tail256LoopA CMPQ itr2, $10 JNE openAVX2Tail256LoopB MOVQ inl, itr2 SUBQ inp, inl MOVQ inl, itr1 MOVQ tmpStoreAVX2, inl // Hash the remainder of data (if any) openAVX2Tail256Hash: ADDQ $16, itr1 CMPQ itr1, inl JGT openAVX2Tail256HashEnd polyAdd (0(itr2)) polyMulAVX2 LEAQ 16(itr2), itr2 JMP openAVX2Tail256Hash // Store 128 bytes safely, then go to store loop openAVX2Tail256HashEnd: VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1 VPADDD TT1, DD0, DD0; VPADDD TT2, DD1, DD1 VPERM2I128 $0x02, AA0, BB0, AA2; VPERM2I128 $0x02, CC0, DD0, BB2; VPERM2I128 $0x13, AA0, BB0, CC2; VPERM2I128 $0x13, CC0, DD0, DD2 VPERM2I128 $0x02, AA1, BB1, AA0; VPERM2I128 $0x02, CC1, DD1, BB0; VPERM2I128 $0x13, AA1, BB1, CC0; VPERM2I128 $0x13, CC1, DD1, DD0 VPXOR (0*32)(inp), AA2, AA2; VPXOR (1*32)(inp), BB2, BB2; VPXOR (2*32)(inp), CC2, CC2; VPXOR (3*32)(inp), DD2, DD2 VMOVDQU AA2, (0*32)(oup); VMOVDQU BB2, (1*32)(oup); VMOVDQU CC2, (2*32)(oup); VMOVDQU DD2, (3*32)(oup) LEAQ (4*32)(inp), inp LEAQ (4*32)(oup), oup SUBQ $4*32, inl JMP openAVX2TailLoop // ---------------------------------------------------------------------------- // Special optimization for the last 384 bytes of ciphertext openAVX2Tail384: // Need to decrypt up to 384 bytes - prepare six blocks VMOVDQA ·chacha20Constants<>(SB), AA0; VMOVDQA AA0, AA1; VMOVDQA AA0, AA2 VMOVDQA state1StoreAVX2, BB0; VMOVDQA BB0, BB1; VMOVDQA BB0, BB2 VMOVDQA state2StoreAVX2, CC0; VMOVDQA CC0, CC1; VMOVDQA CC0, CC2 VMOVDQA ctr3StoreAVX2, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD1 VPADDD ·avx2IncMask<>(SB), DD1, DD2 VMOVDQA DD0, ctr0StoreAVX2 VMOVDQA DD1, ctr1StoreAVX2 VMOVDQA DD2, ctr2StoreAVX2 // Compute the number of iterations that will hash two blocks of data MOVQ inl, tmpStoreAVX2 MOVQ inl, itr1 SUBQ $256, itr1 SHRQ $4, itr1 ADDQ $6, itr1 MOVQ $10, itr2 CMPQ itr1, $10 CMOVQGT itr2, itr1 MOVQ inp, inl XORQ itr2, itr2 // Perform ChaCha rounds, while hashing the remaining input openAVX2Tail384LoopB: polyAdd(0(inl)) polyMulAVX2 LEAQ 16(inl), inl openAVX2Tail384LoopA: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0); chachaQR_AVX2(AA2, BB2, CC2, DD2, TT0) VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $4, BB2, BB2, BB2 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1; VPALIGNR $12, DD2, DD2, DD2 polyAdd(0(inl)) polyMulAVX2 LEAQ 16(inl), inl INCQ itr2 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0); chachaQR_AVX2(AA2, BB2, CC2, DD2, TT0) VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $12, BB2, BB2, BB2 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1; VPALIGNR $4, DD2, DD2, DD2 CMPQ itr2, itr1 JB openAVX2Tail384LoopB CMPQ itr2, $10 JNE openAVX2Tail384LoopA MOVQ inl, itr2 SUBQ inp, inl MOVQ inl, itr1 MOVQ tmpStoreAVX2, inl openAVX2Tail384Hash: ADDQ $16, itr1 CMPQ itr1, inl JGT openAVX2Tail384HashEnd polyAdd(0(itr2)) polyMulAVX2 LEAQ 16(itr2), itr2 JMP openAVX2Tail384Hash // Store 256 bytes safely, then go to store loop openAVX2Tail384HashEnd: VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1; VPADDD ·chacha20Constants<>(SB), AA2, AA2 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1; VPADDD state1StoreAVX2, BB2, BB2 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1; VPADDD state2StoreAVX2, CC2, CC2 VPADDD ctr0StoreAVX2, DD0, DD0; VPADDD ctr1StoreAVX2, DD1, DD1; VPADDD ctr2StoreAVX2, DD2, DD2 VPERM2I128 $0x02, AA0, BB0, TT0; VPERM2I128 $0x02, CC0, DD0, TT1; VPERM2I128 $0x13, AA0, BB0, TT2; VPERM2I128 $0x13, CC0, DD0, TT3 VPXOR (0*32)(inp), TT0, TT0; VPXOR (1*32)(inp), TT1, TT1; VPXOR (2*32)(inp), TT2, TT2; VPXOR (3*32)(inp), TT3, TT3 VMOVDQU TT0, (0*32)(oup); VMOVDQU TT1, (1*32)(oup); VMOVDQU TT2, (2*32)(oup); VMOVDQU TT3, (3*32)(oup) VPERM2I128 $0x02, AA1, BB1, TT0; VPERM2I128 $0x02, CC1, DD1, TT1; VPERM2I128 $0x13, AA1, BB1, TT2; VPERM2I128 $0x13, CC1, DD1, TT3 VPXOR (4*32)(inp), TT0, TT0; VPXOR (5*32)(inp), TT1, TT1; VPXOR (6*32)(inp), TT2, TT2; VPXOR (7*32)(inp), TT3, TT3 VMOVDQU TT0, (4*32)(oup); VMOVDQU TT1, (5*32)(oup); VMOVDQU TT2, (6*32)(oup); VMOVDQU TT3, (7*32)(oup) VPERM2I128 $0x02, AA2, BB2, AA0; VPERM2I128 $0x02, CC2, DD2, BB0; VPERM2I128 $0x13, AA2, BB2, CC0; VPERM2I128 $0x13, CC2, DD2, DD0 LEAQ (8*32)(inp), inp LEAQ (8*32)(oup), oup SUBQ $8*32, inl JMP openAVX2TailLoop // ---------------------------------------------------------------------------- // Special optimization for the last 512 bytes of ciphertext openAVX2Tail512: VMOVDQU ·chacha20Constants<>(SB), AA0; VMOVDQA AA0, AA1; VMOVDQA AA0, AA2; VMOVDQA AA0, AA3 VMOVDQA state1StoreAVX2, BB0; VMOVDQA BB0, BB1; VMOVDQA BB0, BB2; VMOVDQA BB0, BB3 VMOVDQA state2StoreAVX2, CC0; VMOVDQA CC0, CC1; VMOVDQA CC0, CC2; VMOVDQA CC0, CC3 VMOVDQA ctr3StoreAVX2, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD1; VPADDD ·avx2IncMask<>(SB), DD1, DD2; VPADDD ·avx2IncMask<>(SB), DD2, DD3 VMOVDQA DD0, ctr0StoreAVX2; VMOVDQA DD1, ctr1StoreAVX2; VMOVDQA DD2, ctr2StoreAVX2; VMOVDQA DD3, ctr3StoreAVX2 XORQ itr1, itr1 MOVQ inp, itr2 openAVX2Tail512LoopB: polyAdd(0(itr2)) polyMulAVX2 LEAQ (2*8)(itr2), itr2 openAVX2Tail512LoopA: VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyAdd(0*8(itr2)) polyMulAVX2 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol8<>(SB), DD0, DD0; VPSHUFB ·rol8<>(SB), DD1, DD1; VPSHUFB ·rol8<>(SB), DD2, DD2; VPSHUFB ·rol8<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $7, BB0, CC3; VPSRLD $25, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $7, BB1, CC3; VPSRLD $25, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $7, BB2, CC3; VPSRLD $25, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $7, BB3, CC3; VPSRLD $25, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $4, BB2, BB2, BB2; VPALIGNR $4, BB3, BB3, BB3 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $8, CC3, CC3, CC3 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1; VPALIGNR $12, DD2, DD2, DD2; VPALIGNR $12, DD3, DD3, DD3 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 polyAdd(2*8(itr2)) polyMulAVX2 LEAQ (4*8)(itr2), itr2 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol8<>(SB), DD0, DD0; VPSHUFB ·rol8<>(SB), DD1, DD1; VPSHUFB ·rol8<>(SB), DD2, DD2; VPSHUFB ·rol8<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $7, BB0, CC3; VPSRLD $25, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $7, BB1, CC3; VPSRLD $25, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $7, BB2, CC3; VPSRLD $25, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $7, BB3, CC3; VPSRLD $25, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $12, BB2, BB2, BB2; VPALIGNR $12, BB3, BB3, BB3 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $8, CC3, CC3, CC3 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1; VPALIGNR $4, DD2, DD2, DD2; VPALIGNR $4, DD3, DD3, DD3 INCQ itr1 CMPQ itr1, $4 JLT openAVX2Tail512LoopB CMPQ itr1, $10 JNE openAVX2Tail512LoopA MOVQ inl, itr1 SUBQ $384, itr1 ANDQ $-16, itr1 openAVX2Tail512HashLoop: TESTQ itr1, itr1 JE openAVX2Tail512HashEnd polyAdd(0(itr2)) polyMulAVX2 LEAQ 16(itr2), itr2 SUBQ $16, itr1 JMP openAVX2Tail512HashLoop openAVX2Tail512HashEnd: VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1; VPADDD ·chacha20Constants<>(SB), AA2, AA2; VPADDD ·chacha20Constants<>(SB), AA3, AA3 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1; VPADDD state1StoreAVX2, BB2, BB2; VPADDD state1StoreAVX2, BB3, BB3 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1; VPADDD state2StoreAVX2, CC2, CC2; VPADDD state2StoreAVX2, CC3, CC3 VPADDD ctr0StoreAVX2, DD0, DD0; VPADDD ctr1StoreAVX2, DD1, DD1; VPADDD ctr2StoreAVX2, DD2, DD2; VPADDD ctr3StoreAVX2, DD3, DD3 VMOVDQA CC3, tmpStoreAVX2 VPERM2I128 $0x02, AA0, BB0, CC3; VPERM2I128 $0x13, AA0, BB0, BB0; VPERM2I128 $0x02, CC0, DD0, AA0; VPERM2I128 $0x13, CC0, DD0, CC0 VPXOR (0*32)(inp), CC3, CC3; VPXOR (1*32)(inp), AA0, AA0; VPXOR (2*32)(inp), BB0, BB0; VPXOR (3*32)(inp), CC0, CC0 VMOVDQU CC3, (0*32)(oup); VMOVDQU AA0, (1*32)(oup); VMOVDQU BB0, (2*32)(oup); VMOVDQU CC0, (3*32)(oup) VPERM2I128 $0x02, AA1, BB1, AA0; VPERM2I128 $0x02, CC1, DD1, BB0; VPERM2I128 $0x13, AA1, BB1, CC0; VPERM2I128 $0x13, CC1, DD1, DD0 VPXOR (4*32)(inp), AA0, AA0; VPXOR (5*32)(inp), BB0, BB0; VPXOR (6*32)(inp), CC0, CC0; VPXOR (7*32)(inp), DD0, DD0 VMOVDQU AA0, (4*32)(oup); VMOVDQU BB0, (5*32)(oup); VMOVDQU CC0, (6*32)(oup); VMOVDQU DD0, (7*32)(oup) VPERM2I128 $0x02, AA2, BB2, AA0; VPERM2I128 $0x02, CC2, DD2, BB0; VPERM2I128 $0x13, AA2, BB2, CC0; VPERM2I128 $0x13, CC2, DD2, DD0 VPXOR (8*32)(inp), AA0, AA0; VPXOR (9*32)(inp), BB0, BB0; VPXOR (10*32)(inp), CC0, CC0; VPXOR (11*32)(inp), DD0, DD0 VMOVDQU AA0, (8*32)(oup); VMOVDQU BB0, (9*32)(oup); VMOVDQU CC0, (10*32)(oup); VMOVDQU DD0, (11*32)(oup) VPERM2I128 $0x02, AA3, BB3, AA0; VPERM2I128 $0x02, tmpStoreAVX2, DD3, BB0; VPERM2I128 $0x13, AA3, BB3, CC0; VPERM2I128 $0x13, tmpStoreAVX2, DD3, DD0 LEAQ (12*32)(inp), inp LEAQ (12*32)(oup), oup SUBQ $12*32, inl JMP openAVX2TailLoop // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // func chacha20Poly1305Seal(dst, key, src, ad []byte) TEXT ·chacha20Poly1305Seal(SB), 0, $288-96 // For aligned stack access MOVQ SP, BP ADDQ $32, BP ANDQ $-32, BP MOVQ dst+0(FP), oup MOVQ key+24(FP), keyp MOVQ src+48(FP), inp MOVQ src_len+56(FP), inl MOVQ ad+72(FP), adp CMPB ·useAVX2(SB), $1 JE chacha20Poly1305Seal_AVX2 // Special optimization, for very short buffers CMPQ inl, $128 JBE sealSSE128 // About 15% faster // In the seal case - prepare the poly key + 3 blocks of stream in the first iteration MOVOU ·chacha20Constants<>(SB), A0 MOVOU (1*16)(keyp), B0 MOVOU (2*16)(keyp), C0 MOVOU (3*16)(keyp), D0 // Store state on stack for future use MOVO B0, state1Store MOVO C0, state2Store // Load state, increment counter blocks MOVO A0, A1; MOVO B0, B1; MOVO C0, C1; MOVO D0, D1; PADDL ·sseIncMask<>(SB), D1 MOVO A1, A2; MOVO B1, B2; MOVO C1, C2; MOVO D1, D2; PADDL ·sseIncMask<>(SB), D2 MOVO A2, A3; MOVO B2, B3; MOVO C2, C3; MOVO D2, D3; PADDL ·sseIncMask<>(SB), D3 // Store counters MOVO D0, ctr0Store; MOVO D1, ctr1Store; MOVO D2, ctr2Store; MOVO D3, ctr3Store MOVQ $10, itr2 sealSSEIntroLoop: MOVO C3, tmpStore chachaQR(A0, B0, C0, D0, C3); chachaQR(A1, B1, C1, D1, C3); chachaQR(A2, B2, C2, D2, C3) MOVO tmpStore, C3 MOVO C1, tmpStore chachaQR(A3, B3, C3, D3, C1) MOVO tmpStore, C1 shiftB0Left; shiftB1Left; shiftB2Left; shiftB3Left shiftC0Left; shiftC1Left; shiftC2Left; shiftC3Left shiftD0Left; shiftD1Left; shiftD2Left; shiftD3Left MOVO C3, tmpStore chachaQR(A0, B0, C0, D0, C3); chachaQR(A1, B1, C1, D1, C3); chachaQR(A2, B2, C2, D2, C3) MOVO tmpStore, C3 MOVO C1, tmpStore chachaQR(A3, B3, C3, D3, C1) MOVO tmpStore, C1 shiftB0Right; shiftB1Right; shiftB2Right; shiftB3Right shiftC0Right; shiftC1Right; shiftC2Right; shiftC3Right shiftD0Right; shiftD1Right; shiftD2Right; shiftD3Right DECQ itr2 JNE sealSSEIntroLoop // Add in the state PADDD ·chacha20Constants<>(SB), A0; PADDD ·chacha20Constants<>(SB), A1; PADDD ·chacha20Constants<>(SB), A2; PADDD ·chacha20Constants<>(SB), A3 PADDD state1Store, B0; PADDD state1Store, B1; PADDD state1Store, B2; PADDD state1Store, B3 PADDD state2Store, C1; PADDD state2Store, C2; PADDD state2Store, C3 PADDD ctr1Store, D1; PADDD ctr2Store, D2; PADDD ctr3Store, D3 // Clamp and store the key PAND ·polyClampMask<>(SB), A0 MOVO A0, rStore MOVO B0, sStore // Hash AAD MOVQ ad_len+80(FP), itr2 CALL polyHashADInternal<>(SB) MOVOU (0*16)(inp), A0; MOVOU (1*16)(inp), B0; MOVOU (2*16)(inp), C0; MOVOU (3*16)(inp), D0 PXOR A0, A1; PXOR B0, B1; PXOR C0, C1; PXOR D0, D1 MOVOU A1, (0*16)(oup); MOVOU B1, (1*16)(oup); MOVOU C1, (2*16)(oup); MOVOU D1, (3*16)(oup) MOVOU (4*16)(inp), A0; MOVOU (5*16)(inp), B0; MOVOU (6*16)(inp), C0; MOVOU (7*16)(inp), D0 PXOR A0, A2; PXOR B0, B2; PXOR C0, C2; PXOR D0, D2 MOVOU A2, (4*16)(oup); MOVOU B2, (5*16)(oup); MOVOU C2, (6*16)(oup); MOVOU D2, (7*16)(oup) MOVQ $128, itr1 SUBQ $128, inl LEAQ 128(inp), inp MOVO A3, A1; MOVO B3, B1; MOVO C3, C1; MOVO D3, D1 CMPQ inl, $64 JBE sealSSE128SealHash MOVOU (0*16)(inp), A0; MOVOU (1*16)(inp), B0; MOVOU (2*16)(inp), C0; MOVOU (3*16)(inp), D0 PXOR A0, A3; PXOR B0, B3; PXOR C0, C3; PXOR D0, D3 MOVOU A3, (8*16)(oup); MOVOU B3, (9*16)(oup); MOVOU C3, (10*16)(oup); MOVOU D3, (11*16)(oup) ADDQ $64, itr1 SUBQ $64, inl LEAQ 64(inp), inp MOVQ $2, itr1 MOVQ $8, itr2 CMPQ inl, $64 JBE sealSSETail64 CMPQ inl, $128 JBE sealSSETail128 CMPQ inl, $192 JBE sealSSETail192 sealSSEMainLoop: // Load state, increment counter blocks MOVO ·chacha20Constants<>(SB), A0; MOVO state1Store, B0; MOVO state2Store, C0; MOVO ctr3Store, D0; PADDL ·sseIncMask<>(SB), D0 MOVO A0, A1; MOVO B0, B1; MOVO C0, C1; MOVO D0, D1; PADDL ·sseIncMask<>(SB), D1 MOVO A1, A2; MOVO B1, B2; MOVO C1, C2; MOVO D1, D2; PADDL ·sseIncMask<>(SB), D2 MOVO A2, A3; MOVO B2, B3; MOVO C2, C3; MOVO D2, D3; PADDL ·sseIncMask<>(SB), D3 // Store counters MOVO D0, ctr0Store; MOVO D1, ctr1Store; MOVO D2, ctr2Store; MOVO D3, ctr3Store sealSSEInnerLoop: MOVO C3, tmpStore chachaQR(A0, B0, C0, D0, C3); chachaQR(A1, B1, C1, D1, C3); chachaQR(A2, B2, C2, D2, C3) MOVO tmpStore, C3 MOVO C1, tmpStore chachaQR(A3, B3, C3, D3, C1) MOVO tmpStore, C1 polyAdd(0(oup)) shiftB0Left; shiftB1Left; shiftB2Left; shiftB3Left shiftC0Left; shiftC1Left; shiftC2Left; shiftC3Left shiftD0Left; shiftD1Left; shiftD2Left; shiftD3Left polyMulStage1 polyMulStage2 LEAQ (2*8)(oup), oup MOVO C3, tmpStore chachaQR(A0, B0, C0, D0, C3); chachaQR(A1, B1, C1, D1, C3); chachaQR(A2, B2, C2, D2, C3) MOVO tmpStore, C3 MOVO C1, tmpStore polyMulStage3 chachaQR(A3, B3, C3, D3, C1) MOVO tmpStore, C1 polyMulReduceStage shiftB0Right; shiftB1Right; shiftB2Right; shiftB3Right shiftC0Right; shiftC1Right; shiftC2Right; shiftC3Right shiftD0Right; shiftD1Right; shiftD2Right; shiftD3Right DECQ itr2 JGE sealSSEInnerLoop polyAdd(0(oup)) polyMul LEAQ (2*8)(oup), oup DECQ itr1 JG sealSSEInnerLoop // Add in the state PADDD ·chacha20Constants<>(SB), A0; PADDD ·chacha20Constants<>(SB), A1; PADDD ·chacha20Constants<>(SB), A2; PADDD ·chacha20Constants<>(SB), A3 PADDD state1Store, B0; PADDD state1Store, B1; PADDD state1Store, B2; PADDD state1Store, B3 PADDD state2Store, C0; PADDD state2Store, C1; PADDD state2Store, C2; PADDD state2Store, C3 PADDD ctr0Store, D0; PADDD ctr1Store, D1; PADDD ctr2Store, D2; PADDD ctr3Store, D3 MOVO D3, tmpStore // Load - xor - store MOVOU (0*16)(inp), D3; PXOR D3, A0 MOVOU (1*16)(inp), D3; PXOR D3, B0 MOVOU (2*16)(inp), D3; PXOR D3, C0 MOVOU (3*16)(inp), D3; PXOR D3, D0 MOVOU A0, (0*16)(oup) MOVOU B0, (1*16)(oup) MOVOU C0, (2*16)(oup) MOVOU D0, (3*16)(oup) MOVO tmpStore, D3 MOVOU (4*16)(inp), A0; MOVOU (5*16)(inp), B0; MOVOU (6*16)(inp), C0; MOVOU (7*16)(inp), D0 PXOR A0, A1; PXOR B0, B1; PXOR C0, C1; PXOR D0, D1 MOVOU A1, (4*16)(oup); MOVOU B1, (5*16)(oup); MOVOU C1, (6*16)(oup); MOVOU D1, (7*16)(oup) MOVOU (8*16)(inp), A0; MOVOU (9*16)(inp), B0; MOVOU (10*16)(inp), C0; MOVOU (11*16)(inp), D0 PXOR A0, A2; PXOR B0, B2; PXOR C0, C2; PXOR D0, D2 MOVOU A2, (8*16)(oup); MOVOU B2, (9*16)(oup); MOVOU C2, (10*16)(oup); MOVOU D2, (11*16)(oup) ADDQ $192, inp MOVQ $192, itr1 SUBQ $192, inl MOVO A3, A1 MOVO B3, B1 MOVO C3, C1 MOVO D3, D1 CMPQ inl, $64 JBE sealSSE128SealHash MOVOU (0*16)(inp), A0; MOVOU (1*16)(inp), B0; MOVOU (2*16)(inp), C0; MOVOU (3*16)(inp), D0 PXOR A0, A3; PXOR B0, B3; PXOR C0, C3; PXOR D0, D3 MOVOU A3, (12*16)(oup); MOVOU B3, (13*16)(oup); MOVOU C3, (14*16)(oup); MOVOU D3, (15*16)(oup) LEAQ 64(inp), inp SUBQ $64, inl MOVQ $6, itr1 MOVQ $4, itr2 CMPQ inl, $192 JG sealSSEMainLoop MOVQ inl, itr1 TESTQ inl, inl JE sealSSE128SealHash MOVQ $6, itr1 CMPQ inl, $64 JBE sealSSETail64 CMPQ inl, $128 JBE sealSSETail128 JMP sealSSETail192 // ---------------------------------------------------------------------------- // Special optimization for the last 64 bytes of plaintext sealSSETail64: // Need to encrypt up to 64 bytes - prepare single block, hash 192 or 256 bytes MOVO ·chacha20Constants<>(SB), A1 MOVO state1Store, B1 MOVO state2Store, C1 MOVO ctr3Store, D1 PADDL ·sseIncMask<>(SB), D1 MOVO D1, ctr0Store sealSSETail64LoopA: // Perform ChaCha rounds, while hashing the previously encrypted ciphertext polyAdd(0(oup)) polyMul LEAQ 16(oup), oup sealSSETail64LoopB: chachaQR(A1, B1, C1, D1, T1) shiftB1Left; shiftC1Left; shiftD1Left chachaQR(A1, B1, C1, D1, T1) shiftB1Right; shiftC1Right; shiftD1Right polyAdd(0(oup)) polyMul LEAQ 16(oup), oup DECQ itr1 JG sealSSETail64LoopA DECQ itr2 JGE sealSSETail64LoopB PADDL ·chacha20Constants<>(SB), A1 PADDL state1Store, B1 PADDL state2Store, C1 PADDL ctr0Store, D1 JMP sealSSE128Seal // ---------------------------------------------------------------------------- // Special optimization for the last 128 bytes of plaintext sealSSETail128: // Need to encrypt up to 128 bytes - prepare two blocks, hash 192 or 256 bytes MOVO ·chacha20Constants<>(SB), A0; MOVO state1Store, B0; MOVO state2Store, C0; MOVO ctr3Store, D0; PADDL ·sseIncMask<>(SB), D0; MOVO D0, ctr0Store MOVO A0, A1; MOVO B0, B1; MOVO C0, C1; MOVO D0, D1; PADDL ·sseIncMask<>(SB), D1; MOVO D1, ctr1Store sealSSETail128LoopA: // Perform ChaCha rounds, while hashing the previously encrypted ciphertext polyAdd(0(oup)) polyMul LEAQ 16(oup), oup sealSSETail128LoopB: chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0) shiftB0Left; shiftC0Left; shiftD0Left shiftB1Left; shiftC1Left; shiftD1Left polyAdd(0(oup)) polyMul LEAQ 16(oup), oup chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0) shiftB0Right; shiftC0Right; shiftD0Right shiftB1Right; shiftC1Right; shiftD1Right DECQ itr1 JG sealSSETail128LoopA DECQ itr2 JGE sealSSETail128LoopB PADDL ·chacha20Constants<>(SB), A0; PADDL ·chacha20Constants<>(SB), A1 PADDL state1Store, B0; PADDL state1Store, B1 PADDL state2Store, C0; PADDL state2Store, C1 PADDL ctr0Store, D0; PADDL ctr1Store, D1 MOVOU (0*16)(inp), T0; MOVOU (1*16)(inp), T1; MOVOU (2*16)(inp), T2; MOVOU (3*16)(inp), T3 PXOR T0, A0; PXOR T1, B0; PXOR T2, C0; PXOR T3, D0 MOVOU A0, (0*16)(oup); MOVOU B0, (1*16)(oup); MOVOU C0, (2*16)(oup); MOVOU D0, (3*16)(oup) MOVQ $64, itr1 LEAQ 64(inp), inp SUBQ $64, inl JMP sealSSE128SealHash // ---------------------------------------------------------------------------- // Special optimization for the last 192 bytes of plaintext sealSSETail192: // Need to encrypt up to 192 bytes - prepare three blocks, hash 192 or 256 bytes MOVO ·chacha20Constants<>(SB), A0; MOVO state1Store, B0; MOVO state2Store, C0; MOVO ctr3Store, D0; PADDL ·sseIncMask<>(SB), D0; MOVO D0, ctr0Store MOVO A0, A1; MOVO B0, B1; MOVO C0, C1; MOVO D0, D1; PADDL ·sseIncMask<>(SB), D1; MOVO D1, ctr1Store MOVO A1, A2; MOVO B1, B2; MOVO C1, C2; MOVO D1, D2; PADDL ·sseIncMask<>(SB), D2; MOVO D2, ctr2Store sealSSETail192LoopA: // Perform ChaCha rounds, while hashing the previously encrypted ciphertext polyAdd(0(oup)) polyMul LEAQ 16(oup), oup sealSSETail192LoopB: chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0); chachaQR(A2, B2, C2, D2, T0) shiftB0Left; shiftC0Left; shiftD0Left shiftB1Left; shiftC1Left; shiftD1Left shiftB2Left; shiftC2Left; shiftD2Left polyAdd(0(oup)) polyMul LEAQ 16(oup), oup chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0); chachaQR(A2, B2, C2, D2, T0) shiftB0Right; shiftC0Right; shiftD0Right shiftB1Right; shiftC1Right; shiftD1Right shiftB2Right; shiftC2Right; shiftD2Right DECQ itr1 JG sealSSETail192LoopA DECQ itr2 JGE sealSSETail192LoopB PADDL ·chacha20Constants<>(SB), A0; PADDL ·chacha20Constants<>(SB), A1; PADDL ·chacha20Constants<>(SB), A2 PADDL state1Store, B0; PADDL state1Store, B1; PADDL state1Store, B2 PADDL state2Store, C0; PADDL state2Store, C1; PADDL state2Store, C2 PADDL ctr0Store, D0; PADDL ctr1Store, D1; PADDL ctr2Store, D2 MOVOU (0*16)(inp), T0; MOVOU (1*16)(inp), T1; MOVOU (2*16)(inp), T2; MOVOU (3*16)(inp), T3 PXOR T0, A0; PXOR T1, B0; PXOR T2, C0; PXOR T3, D0 MOVOU A0, (0*16)(oup); MOVOU B0, (1*16)(oup); MOVOU C0, (2*16)(oup); MOVOU D0, (3*16)(oup) MOVOU (4*16)(inp), T0; MOVOU (5*16)(inp), T1; MOVOU (6*16)(inp), T2; MOVOU (7*16)(inp), T3 PXOR T0, A1; PXOR T1, B1; PXOR T2, C1; PXOR T3, D1 MOVOU A1, (4*16)(oup); MOVOU B1, (5*16)(oup); MOVOU C1, (6*16)(oup); MOVOU D1, (7*16)(oup) MOVO A2, A1 MOVO B2, B1 MOVO C2, C1 MOVO D2, D1 MOVQ $128, itr1 LEAQ 128(inp), inp SUBQ $128, inl JMP sealSSE128SealHash // ---------------------------------------------------------------------------- // Special seal optimization for buffers smaller than 129 bytes sealSSE128: // For up to 128 bytes of ciphertext and 64 bytes for the poly key, we require to process three blocks MOVOU ·chacha20Constants<>(SB), A0; MOVOU (1*16)(keyp), B0; MOVOU (2*16)(keyp), C0; MOVOU (3*16)(keyp), D0 MOVO A0, A1; MOVO B0, B1; MOVO C0, C1; MOVO D0, D1; PADDL ·sseIncMask<>(SB), D1 MOVO A1, A2; MOVO B1, B2; MOVO C1, C2; MOVO D1, D2; PADDL ·sseIncMask<>(SB), D2 MOVO B0, T1; MOVO C0, T2; MOVO D1, T3 MOVQ $10, itr2 sealSSE128InnerCipherLoop: chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0); chachaQR(A2, B2, C2, D2, T0) shiftB0Left; shiftB1Left; shiftB2Left shiftC0Left; shiftC1Left; shiftC2Left shiftD0Left; shiftD1Left; shiftD2Left chachaQR(A0, B0, C0, D0, T0); chachaQR(A1, B1, C1, D1, T0); chachaQR(A2, B2, C2, D2, T0) shiftB0Right; shiftB1Right; shiftB2Right shiftC0Right; shiftC1Right; shiftC2Right shiftD0Right; shiftD1Right; shiftD2Right DECQ itr2 JNE sealSSE128InnerCipherLoop // A0|B0 hold the Poly1305 32-byte key, C0,D0 can be discarded PADDL ·chacha20Constants<>(SB), A0; PADDL ·chacha20Constants<>(SB), A1; PADDL ·chacha20Constants<>(SB), A2 PADDL T1, B0; PADDL T1, B1; PADDL T1, B2 PADDL T2, C1; PADDL T2, C2 PADDL T3, D1; PADDL ·sseIncMask<>(SB), T3; PADDL T3, D2 PAND ·polyClampMask<>(SB), A0 MOVOU A0, rStore MOVOU B0, sStore // Hash MOVQ ad_len+80(FP), itr2 CALL polyHashADInternal<>(SB) XORQ itr1, itr1 sealSSE128SealHash: // itr1 holds the number of bytes encrypted but not yet hashed CMPQ itr1, $16 JB sealSSE128Seal polyAdd(0(oup)) polyMul SUBQ $16, itr1 ADDQ $16, oup JMP sealSSE128SealHash sealSSE128Seal: CMPQ inl, $16 JB sealSSETail SUBQ $16, inl // Load for decryption MOVOU (inp), T0 PXOR T0, A1 MOVOU A1, (oup) LEAQ (1*16)(inp), inp LEAQ (1*16)(oup), oup // Extract for hashing MOVQ A1, t0 PSRLDQ $8, A1 MOVQ A1, t1 ADDQ t0, acc0; ADCQ t1, acc1; ADCQ $1, acc2 polyMul // Shift the stream "left" MOVO B1, A1 MOVO C1, B1 MOVO D1, C1 MOVO A2, D1 MOVO B2, A2 MOVO C2, B2 MOVO D2, C2 JMP sealSSE128Seal sealSSETail: TESTQ inl, inl JE sealSSEFinalize // We can only load the PT one byte at a time to avoid read after end of buffer MOVQ inl, itr2 SHLQ $4, itr2 LEAQ ·andMask<>(SB), t0 MOVQ inl, itr1 LEAQ -1(inp)(inl*1), inp XORQ t2, t2 XORQ t3, t3 XORQ AX, AX sealSSETailLoadLoop: SHLQ $8, t2, t3 SHLQ $8, t2 MOVB (inp), AX XORQ AX, t2 LEAQ -1(inp), inp DECQ itr1 JNE sealSSETailLoadLoop MOVQ t2, 0+tmpStore MOVQ t3, 8+tmpStore PXOR 0+tmpStore, A1 MOVOU A1, (oup) MOVOU -16(t0)(itr2*1), T0 PAND T0, A1 MOVQ A1, t0 PSRLDQ $8, A1 MOVQ A1, t1 ADDQ t0, acc0; ADCQ t1, acc1; ADCQ $1, acc2 polyMul ADDQ inl, oup sealSSEFinalize: // Hash in the buffer lengths ADDQ ad_len+80(FP), acc0 ADCQ src_len+56(FP), acc1 ADCQ $1, acc2 polyMul // Final reduce MOVQ acc0, t0 MOVQ acc1, t1 MOVQ acc2, t2 SUBQ $-5, acc0 SBBQ $-1, acc1 SBBQ $3, acc2 CMOVQCS t0, acc0 CMOVQCS t1, acc1 CMOVQCS t2, acc2 // Add in the "s" part of the key ADDQ 0+sStore, acc0 ADCQ 8+sStore, acc1 // Finally store the tag at the end of the message MOVQ acc0, (0*8)(oup) MOVQ acc1, (1*8)(oup) RET // ---------------------------------------------------------------------------- // ------------------------- AVX2 Code ---------------------------------------- chacha20Poly1305Seal_AVX2: VZEROUPPER VMOVDQU ·chacha20Constants<>(SB), AA0 BYTE $0xc4; BYTE $0x42; BYTE $0x7d; BYTE $0x5a; BYTE $0x70; BYTE $0x10 // broadcasti128 16(r8), ymm14 BYTE $0xc4; BYTE $0x42; BYTE $0x7d; BYTE $0x5a; BYTE $0x60; BYTE $0x20 // broadcasti128 32(r8), ymm12 BYTE $0xc4; BYTE $0xc2; BYTE $0x7d; BYTE $0x5a; BYTE $0x60; BYTE $0x30 // broadcasti128 48(r8), ymm4 VPADDD ·avx2InitMask<>(SB), DD0, DD0 // Special optimizations, for very short buffers CMPQ inl, $192 JBE seal192AVX2 // 33% faster CMPQ inl, $320 JBE seal320AVX2 // 17% faster // For the general key prepare the key first - as a byproduct we have 64 bytes of cipher stream VMOVDQA AA0, AA1; VMOVDQA AA0, AA2; VMOVDQA AA0, AA3 VMOVDQA BB0, BB1; VMOVDQA BB0, BB2; VMOVDQA BB0, BB3; VMOVDQA BB0, state1StoreAVX2 VMOVDQA CC0, CC1; VMOVDQA CC0, CC2; VMOVDQA CC0, CC3; VMOVDQA CC0, state2StoreAVX2 VPADDD ·avx2IncMask<>(SB), DD0, DD1; VMOVDQA DD0, ctr0StoreAVX2 VPADDD ·avx2IncMask<>(SB), DD1, DD2; VMOVDQA DD1, ctr1StoreAVX2 VPADDD ·avx2IncMask<>(SB), DD2, DD3; VMOVDQA DD2, ctr2StoreAVX2 VMOVDQA DD3, ctr3StoreAVX2 MOVQ $10, itr2 sealAVX2IntroLoop: VMOVDQA CC3, tmpStoreAVX2 chachaQR_AVX2(AA0, BB0, CC0, DD0, CC3); chachaQR_AVX2(AA1, BB1, CC1, DD1, CC3); chachaQR_AVX2(AA2, BB2, CC2, DD2, CC3) VMOVDQA tmpStoreAVX2, CC3 VMOVDQA CC1, tmpStoreAVX2 chachaQR_AVX2(AA3, BB3, CC3, DD3, CC1) VMOVDQA tmpStoreAVX2, CC1 VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $12, DD0, DD0, DD0 VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $12, DD1, DD1, DD1 VPALIGNR $4, BB2, BB2, BB2; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $12, DD2, DD2, DD2 VPALIGNR $4, BB3, BB3, BB3; VPALIGNR $8, CC3, CC3, CC3; VPALIGNR $12, DD3, DD3, DD3 VMOVDQA CC3, tmpStoreAVX2 chachaQR_AVX2(AA0, BB0, CC0, DD0, CC3); chachaQR_AVX2(AA1, BB1, CC1, DD1, CC3); chachaQR_AVX2(AA2, BB2, CC2, DD2, CC3) VMOVDQA tmpStoreAVX2, CC3 VMOVDQA CC1, tmpStoreAVX2 chachaQR_AVX2(AA3, BB3, CC3, DD3, CC1) VMOVDQA tmpStoreAVX2, CC1 VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $4, DD0, DD0, DD0 VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $4, DD1, DD1, DD1 VPALIGNR $12, BB2, BB2, BB2; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $4, DD2, DD2, DD2 VPALIGNR $12, BB3, BB3, BB3; VPALIGNR $8, CC3, CC3, CC3; VPALIGNR $4, DD3, DD3, DD3 DECQ itr2 JNE sealAVX2IntroLoop VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1; VPADDD ·chacha20Constants<>(SB), AA2, AA2; VPADDD ·chacha20Constants<>(SB), AA3, AA3 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1; VPADDD state1StoreAVX2, BB2, BB2; VPADDD state1StoreAVX2, BB3, BB3 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1; VPADDD state2StoreAVX2, CC2, CC2; VPADDD state2StoreAVX2, CC3, CC3 VPADDD ctr0StoreAVX2, DD0, DD0; VPADDD ctr1StoreAVX2, DD1, DD1; VPADDD ctr2StoreAVX2, DD2, DD2; VPADDD ctr3StoreAVX2, DD3, DD3 VPERM2I128 $0x13, CC0, DD0, CC0 // Stream bytes 96 - 127 VPERM2I128 $0x02, AA0, BB0, DD0 // The Poly1305 key VPERM2I128 $0x13, AA0, BB0, AA0 // Stream bytes 64 - 95 // Clamp and store poly key VPAND ·polyClampMask<>(SB), DD0, DD0 VMOVDQA DD0, rsStoreAVX2 // Hash AD MOVQ ad_len+80(FP), itr2 CALL polyHashADInternal<>(SB) // Can store at least 320 bytes VPXOR (0*32)(inp), AA0, AA0 VPXOR (1*32)(inp), CC0, CC0 VMOVDQU AA0, (0*32)(oup) VMOVDQU CC0, (1*32)(oup) VPERM2I128 $0x02, AA1, BB1, AA0; VPERM2I128 $0x02, CC1, DD1, BB0; VPERM2I128 $0x13, AA1, BB1, CC0; VPERM2I128 $0x13, CC1, DD1, DD0 VPXOR (2*32)(inp), AA0, AA0; VPXOR (3*32)(inp), BB0, BB0; VPXOR (4*32)(inp), CC0, CC0; VPXOR (5*32)(inp), DD0, DD0 VMOVDQU AA0, (2*32)(oup); VMOVDQU BB0, (3*32)(oup); VMOVDQU CC0, (4*32)(oup); VMOVDQU DD0, (5*32)(oup) VPERM2I128 $0x02, AA2, BB2, AA0; VPERM2I128 $0x02, CC2, DD2, BB0; VPERM2I128 $0x13, AA2, BB2, CC0; VPERM2I128 $0x13, CC2, DD2, DD0 VPXOR (6*32)(inp), AA0, AA0; VPXOR (7*32)(inp), BB0, BB0; VPXOR (8*32)(inp), CC0, CC0; VPXOR (9*32)(inp), DD0, DD0 VMOVDQU AA0, (6*32)(oup); VMOVDQU BB0, (7*32)(oup); VMOVDQU CC0, (8*32)(oup); VMOVDQU DD0, (9*32)(oup) MOVQ $320, itr1 SUBQ $320, inl LEAQ 320(inp), inp VPERM2I128 $0x02, AA3, BB3, AA0; VPERM2I128 $0x02, CC3, DD3, BB0; VPERM2I128 $0x13, AA3, BB3, CC0; VPERM2I128 $0x13, CC3, DD3, DD0 CMPQ inl, $128 JBE sealAVX2SealHash VPXOR (0*32)(inp), AA0, AA0; VPXOR (1*32)(inp), BB0, BB0; VPXOR (2*32)(inp), CC0, CC0; VPXOR (3*32)(inp), DD0, DD0 VMOVDQU AA0, (10*32)(oup); VMOVDQU BB0, (11*32)(oup); VMOVDQU CC0, (12*32)(oup); VMOVDQU DD0, (13*32)(oup) SUBQ $128, inl LEAQ 128(inp), inp MOVQ $8, itr1 MOVQ $2, itr2 CMPQ inl, $128 JBE sealAVX2Tail128 CMPQ inl, $256 JBE sealAVX2Tail256 CMPQ inl, $384 JBE sealAVX2Tail384 CMPQ inl, $512 JBE sealAVX2Tail512 // We have 448 bytes to hash, but main loop hashes 512 bytes at a time - perform some rounds, before the main loop VMOVDQA ·chacha20Constants<>(SB), AA0; VMOVDQA AA0, AA1; VMOVDQA AA0, AA2; VMOVDQA AA0, AA3 VMOVDQA state1StoreAVX2, BB0; VMOVDQA BB0, BB1; VMOVDQA BB0, BB2; VMOVDQA BB0, BB3 VMOVDQA state2StoreAVX2, CC0; VMOVDQA CC0, CC1; VMOVDQA CC0, CC2; VMOVDQA CC0, CC3 VMOVDQA ctr3StoreAVX2, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD1; VPADDD ·avx2IncMask<>(SB), DD1, DD2; VPADDD ·avx2IncMask<>(SB), DD2, DD3 VMOVDQA DD0, ctr0StoreAVX2; VMOVDQA DD1, ctr1StoreAVX2; VMOVDQA DD2, ctr2StoreAVX2; VMOVDQA DD3, ctr3StoreAVX2 VMOVDQA CC3, tmpStoreAVX2 chachaQR_AVX2(AA0, BB0, CC0, DD0, CC3); chachaQR_AVX2(AA1, BB1, CC1, DD1, CC3); chachaQR_AVX2(AA2, BB2, CC2, DD2, CC3) VMOVDQA tmpStoreAVX2, CC3 VMOVDQA CC1, tmpStoreAVX2 chachaQR_AVX2(AA3, BB3, CC3, DD3, CC1) VMOVDQA tmpStoreAVX2, CC1 VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $12, DD0, DD0, DD0 VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $12, DD1, DD1, DD1 VPALIGNR $4, BB2, BB2, BB2; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $12, DD2, DD2, DD2 VPALIGNR $4, BB3, BB3, BB3; VPALIGNR $8, CC3, CC3, CC3; VPALIGNR $12, DD3, DD3, DD3 VMOVDQA CC3, tmpStoreAVX2 chachaQR_AVX2(AA0, BB0, CC0, DD0, CC3); chachaQR_AVX2(AA1, BB1, CC1, DD1, CC3); chachaQR_AVX2(AA2, BB2, CC2, DD2, CC3) VMOVDQA tmpStoreAVX2, CC3 VMOVDQA CC1, tmpStoreAVX2 chachaQR_AVX2(AA3, BB3, CC3, DD3, CC1) VMOVDQA tmpStoreAVX2, CC1 VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $4, DD0, DD0, DD0 VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $4, DD1, DD1, DD1 VPALIGNR $12, BB2, BB2, BB2; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $4, DD2, DD2, DD2 VPALIGNR $12, BB3, BB3, BB3; VPALIGNR $8, CC3, CC3, CC3; VPALIGNR $4, DD3, DD3, DD3 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 SUBQ $16, oup // Adjust the pointer MOVQ $9, itr1 JMP sealAVX2InternalLoopStart sealAVX2MainLoop: // Load state, increment counter blocks, store the incremented counters VMOVDQU ·chacha20Constants<>(SB), AA0; VMOVDQA AA0, AA1; VMOVDQA AA0, AA2; VMOVDQA AA0, AA3 VMOVDQA state1StoreAVX2, BB0; VMOVDQA BB0, BB1; VMOVDQA BB0, BB2; VMOVDQA BB0, BB3 VMOVDQA state2StoreAVX2, CC0; VMOVDQA CC0, CC1; VMOVDQA CC0, CC2; VMOVDQA CC0, CC3 VMOVDQA ctr3StoreAVX2, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD1; VPADDD ·avx2IncMask<>(SB), DD1, DD2; VPADDD ·avx2IncMask<>(SB), DD2, DD3 VMOVDQA DD0, ctr0StoreAVX2; VMOVDQA DD1, ctr1StoreAVX2; VMOVDQA DD2, ctr2StoreAVX2; VMOVDQA DD3, ctr3StoreAVX2 MOVQ $10, itr1 sealAVX2InternalLoop: polyAdd(0*8(oup)) VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 polyMulStage1_AVX2 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 polyMulStage2_AVX2 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 polyMulStage3_AVX2 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyMulReduceStage sealAVX2InternalLoopStart: VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol8<>(SB), DD0, DD0; VPSHUFB ·rol8<>(SB), DD1, DD1; VPSHUFB ·rol8<>(SB), DD2, DD2; VPSHUFB ·rol8<>(SB), DD3, DD3 polyAdd(2*8(oup)) VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 polyMulStage1_AVX2 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $7, BB0, CC3; VPSRLD $25, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $7, BB1, CC3; VPSRLD $25, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $7, BB2, CC3; VPSRLD $25, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $7, BB3, CC3; VPSRLD $25, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyMulStage2_AVX2 VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $4, BB2, BB2, BB2; VPALIGNR $4, BB3, BB3, BB3 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $8, CC3, CC3, CC3 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1; VPALIGNR $12, DD2, DD2, DD2; VPALIGNR $12, DD3, DD3, DD3 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 polyMulStage3_AVX2 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 polyMulReduceStage VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 polyAdd(4*8(oup)) LEAQ (6*8)(oup), oup VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyMulStage1_AVX2 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 polyMulStage2_AVX2 VPSHUFB ·rol8<>(SB), DD0, DD0; VPSHUFB ·rol8<>(SB), DD1, DD1; VPSHUFB ·rol8<>(SB), DD2, DD2; VPSHUFB ·rol8<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 polyMulStage3_AVX2 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $7, BB0, CC3; VPSRLD $25, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $7, BB1, CC3; VPSRLD $25, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $7, BB2, CC3; VPSRLD $25, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $7, BB3, CC3; VPSRLD $25, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyMulReduceStage VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $12, BB2, BB2, BB2; VPALIGNR $12, BB3, BB3, BB3 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $8, CC3, CC3, CC3 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1; VPALIGNR $4, DD2, DD2, DD2; VPALIGNR $4, DD3, DD3, DD3 DECQ itr1 JNE sealAVX2InternalLoop VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1; VPADDD ·chacha20Constants<>(SB), AA2, AA2; VPADDD ·chacha20Constants<>(SB), AA3, AA3 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1; VPADDD state1StoreAVX2, BB2, BB2; VPADDD state1StoreAVX2, BB3, BB3 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1; VPADDD state2StoreAVX2, CC2, CC2; VPADDD state2StoreAVX2, CC3, CC3 VPADDD ctr0StoreAVX2, DD0, DD0; VPADDD ctr1StoreAVX2, DD1, DD1; VPADDD ctr2StoreAVX2, DD2, DD2; VPADDD ctr3StoreAVX2, DD3, DD3 VMOVDQA CC3, tmpStoreAVX2 // We only hashed 480 of the 512 bytes available - hash the remaining 32 here polyAdd(0*8(oup)) polyMulAVX2 LEAQ (4*8)(oup), oup VPERM2I128 $0x02, AA0, BB0, CC3; VPERM2I128 $0x13, AA0, BB0, BB0; VPERM2I128 $0x02, CC0, DD0, AA0; VPERM2I128 $0x13, CC0, DD0, CC0 VPXOR (0*32)(inp), CC3, CC3; VPXOR (1*32)(inp), AA0, AA0; VPXOR (2*32)(inp), BB0, BB0; VPXOR (3*32)(inp), CC0, CC0 VMOVDQU CC3, (0*32)(oup); VMOVDQU AA0, (1*32)(oup); VMOVDQU BB0, (2*32)(oup); VMOVDQU CC0, (3*32)(oup) VPERM2I128 $0x02, AA1, BB1, AA0; VPERM2I128 $0x02, CC1, DD1, BB0; VPERM2I128 $0x13, AA1, BB1, CC0; VPERM2I128 $0x13, CC1, DD1, DD0 VPXOR (4*32)(inp), AA0, AA0; VPXOR (5*32)(inp), BB0, BB0; VPXOR (6*32)(inp), CC0, CC0; VPXOR (7*32)(inp), DD0, DD0 VMOVDQU AA0, (4*32)(oup); VMOVDQU BB0, (5*32)(oup); VMOVDQU CC0, (6*32)(oup); VMOVDQU DD0, (7*32)(oup) // and here polyAdd(-2*8(oup)) polyMulAVX2 VPERM2I128 $0x02, AA2, BB2, AA0; VPERM2I128 $0x02, CC2, DD2, BB0; VPERM2I128 $0x13, AA2, BB2, CC0; VPERM2I128 $0x13, CC2, DD2, DD0 VPXOR (8*32)(inp), AA0, AA0; VPXOR (9*32)(inp), BB0, BB0; VPXOR (10*32)(inp), CC0, CC0; VPXOR (11*32)(inp), DD0, DD0 VMOVDQU AA0, (8*32)(oup); VMOVDQU BB0, (9*32)(oup); VMOVDQU CC0, (10*32)(oup); VMOVDQU DD0, (11*32)(oup) VPERM2I128 $0x02, AA3, BB3, AA0; VPERM2I128 $0x02, tmpStoreAVX2, DD3, BB0; VPERM2I128 $0x13, AA3, BB3, CC0; VPERM2I128 $0x13, tmpStoreAVX2, DD3, DD0 VPXOR (12*32)(inp), AA0, AA0; VPXOR (13*32)(inp), BB0, BB0; VPXOR (14*32)(inp), CC0, CC0; VPXOR (15*32)(inp), DD0, DD0 VMOVDQU AA0, (12*32)(oup); VMOVDQU BB0, (13*32)(oup); VMOVDQU CC0, (14*32)(oup); VMOVDQU DD0, (15*32)(oup) LEAQ (32*16)(inp), inp SUBQ $(32*16), inl CMPQ inl, $512 JG sealAVX2MainLoop // Tail can only hash 480 bytes polyAdd(0*8(oup)) polyMulAVX2 polyAdd(2*8(oup)) polyMulAVX2 LEAQ 32(oup), oup MOVQ $10, itr1 MOVQ $0, itr2 CMPQ inl, $128 JBE sealAVX2Tail128 CMPQ inl, $256 JBE sealAVX2Tail256 CMPQ inl, $384 JBE sealAVX2Tail384 JMP sealAVX2Tail512 // ---------------------------------------------------------------------------- // Special optimization for buffers smaller than 193 bytes seal192AVX2: // For up to 192 bytes of ciphertext and 64 bytes for the poly key, we process four blocks VMOVDQA AA0, AA1 VMOVDQA BB0, BB1 VMOVDQA CC0, CC1 VPADDD ·avx2IncMask<>(SB), DD0, DD1 VMOVDQA AA0, AA2 VMOVDQA BB0, BB2 VMOVDQA CC0, CC2 VMOVDQA DD0, DD2 VMOVDQA DD1, TT3 MOVQ $10, itr2 sealAVX2192InnerCipherLoop: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1 DECQ itr2 JNE sealAVX2192InnerCipherLoop VPADDD AA2, AA0, AA0; VPADDD AA2, AA1, AA1 VPADDD BB2, BB0, BB0; VPADDD BB2, BB1, BB1 VPADDD CC2, CC0, CC0; VPADDD CC2, CC1, CC1 VPADDD DD2, DD0, DD0; VPADDD TT3, DD1, DD1 VPERM2I128 $0x02, AA0, BB0, TT0 // Clamp and store poly key VPAND ·polyClampMask<>(SB), TT0, TT0 VMOVDQA TT0, rsStoreAVX2 // Stream for up to 192 bytes VPERM2I128 $0x13, AA0, BB0, AA0 VPERM2I128 $0x13, CC0, DD0, BB0 VPERM2I128 $0x02, AA1, BB1, CC0 VPERM2I128 $0x02, CC1, DD1, DD0 VPERM2I128 $0x13, AA1, BB1, AA1 VPERM2I128 $0x13, CC1, DD1, BB1 sealAVX2ShortSeal: // Hash aad MOVQ ad_len+80(FP), itr2 CALL polyHashADInternal<>(SB) XORQ itr1, itr1 sealAVX2SealHash: // itr1 holds the number of bytes encrypted but not yet hashed CMPQ itr1, $16 JB sealAVX2ShortSealLoop polyAdd(0(oup)) polyMul SUBQ $16, itr1 ADDQ $16, oup JMP sealAVX2SealHash sealAVX2ShortSealLoop: CMPQ inl, $32 JB sealAVX2ShortTail32 SUBQ $32, inl // Load for encryption VPXOR (inp), AA0, AA0 VMOVDQU AA0, (oup) LEAQ (1*32)(inp), inp // Now can hash polyAdd(0*8(oup)) polyMulAVX2 polyAdd(2*8(oup)) polyMulAVX2 LEAQ (1*32)(oup), oup // Shift stream left VMOVDQA BB0, AA0 VMOVDQA CC0, BB0 VMOVDQA DD0, CC0 VMOVDQA AA1, DD0 VMOVDQA BB1, AA1 VMOVDQA CC1, BB1 VMOVDQA DD1, CC1 VMOVDQA AA2, DD1 VMOVDQA BB2, AA2 JMP sealAVX2ShortSealLoop sealAVX2ShortTail32: CMPQ inl, $16 VMOVDQA A0, A1 JB sealAVX2ShortDone SUBQ $16, inl // Load for encryption VPXOR (inp), A0, T0 VMOVDQU T0, (oup) LEAQ (1*16)(inp), inp // Hash polyAdd(0*8(oup)) polyMulAVX2 LEAQ (1*16)(oup), oup VPERM2I128 $0x11, AA0, AA0, AA0 VMOVDQA A0, A1 sealAVX2ShortDone: VZEROUPPER JMP sealSSETail // ---------------------------------------------------------------------------- // Special optimization for buffers smaller than 321 bytes seal320AVX2: // For up to 320 bytes of ciphertext and 64 bytes for the poly key, we process six blocks VMOVDQA AA0, AA1; VMOVDQA BB0, BB1; VMOVDQA CC0, CC1; VPADDD ·avx2IncMask<>(SB), DD0, DD1 VMOVDQA AA0, AA2; VMOVDQA BB0, BB2; VMOVDQA CC0, CC2; VPADDD ·avx2IncMask<>(SB), DD1, DD2 VMOVDQA BB0, TT1; VMOVDQA CC0, TT2; VMOVDQA DD0, TT3 MOVQ $10, itr2 sealAVX2320InnerCipherLoop: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0); chachaQR_AVX2(AA2, BB2, CC2, DD2, TT0) VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $4, BB2, BB2, BB2 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1; VPALIGNR $12, DD2, DD2, DD2 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0); chachaQR_AVX2(AA2, BB2, CC2, DD2, TT0) VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $12, BB2, BB2, BB2 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1; VPALIGNR $4, DD2, DD2, DD2 DECQ itr2 JNE sealAVX2320InnerCipherLoop VMOVDQA ·chacha20Constants<>(SB), TT0 VPADDD TT0, AA0, AA0; VPADDD TT0, AA1, AA1; VPADDD TT0, AA2, AA2 VPADDD TT1, BB0, BB0; VPADDD TT1, BB1, BB1; VPADDD TT1, BB2, BB2 VPADDD TT2, CC0, CC0; VPADDD TT2, CC1, CC1; VPADDD TT2, CC2, CC2 VMOVDQA ·avx2IncMask<>(SB), TT0 VPADDD TT3, DD0, DD0; VPADDD TT0, TT3, TT3 VPADDD TT3, DD1, DD1; VPADDD TT0, TT3, TT3 VPADDD TT3, DD2, DD2 // Clamp and store poly key VPERM2I128 $0x02, AA0, BB0, TT0 VPAND ·polyClampMask<>(SB), TT0, TT0 VMOVDQA TT0, rsStoreAVX2 // Stream for up to 320 bytes VPERM2I128 $0x13, AA0, BB0, AA0 VPERM2I128 $0x13, CC0, DD0, BB0 VPERM2I128 $0x02, AA1, BB1, CC0 VPERM2I128 $0x02, CC1, DD1, DD0 VPERM2I128 $0x13, AA1, BB1, AA1 VPERM2I128 $0x13, CC1, DD1, BB1 VPERM2I128 $0x02, AA2, BB2, CC1 VPERM2I128 $0x02, CC2, DD2, DD1 VPERM2I128 $0x13, AA2, BB2, AA2 VPERM2I128 $0x13, CC2, DD2, BB2 JMP sealAVX2ShortSeal // ---------------------------------------------------------------------------- // Special optimization for the last 128 bytes of ciphertext sealAVX2Tail128: // Need to decrypt up to 128 bytes - prepare two blocks // If we got here after the main loop - there are 512 encrypted bytes waiting to be hashed // If we got here before the main loop - there are 448 encrpyred bytes waiting to be hashed VMOVDQA ·chacha20Constants<>(SB), AA0 VMOVDQA state1StoreAVX2, BB0 VMOVDQA state2StoreAVX2, CC0 VMOVDQA ctr3StoreAVX2, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD0 VMOVDQA DD0, DD1 sealAVX2Tail128LoopA: polyAdd(0(oup)) polyMul LEAQ 16(oup), oup sealAVX2Tail128LoopB: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0) polyAdd(0(oup)) polyMul VPALIGNR $4, BB0, BB0, BB0 VPALIGNR $8, CC0, CC0, CC0 VPALIGNR $12, DD0, DD0, DD0 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0) polyAdd(16(oup)) polyMul LEAQ 32(oup), oup VPALIGNR $12, BB0, BB0, BB0 VPALIGNR $8, CC0, CC0, CC0 VPALIGNR $4, DD0, DD0, DD0 DECQ itr1 JG sealAVX2Tail128LoopA DECQ itr2 JGE sealAVX2Tail128LoopB VPADDD ·chacha20Constants<>(SB), AA0, AA1 VPADDD state1StoreAVX2, BB0, BB1 VPADDD state2StoreAVX2, CC0, CC1 VPADDD DD1, DD0, DD1 VPERM2I128 $0x02, AA1, BB1, AA0 VPERM2I128 $0x02, CC1, DD1, BB0 VPERM2I128 $0x13, AA1, BB1, CC0 VPERM2I128 $0x13, CC1, DD1, DD0 JMP sealAVX2ShortSealLoop // ---------------------------------------------------------------------------- // Special optimization for the last 256 bytes of ciphertext sealAVX2Tail256: // Need to decrypt up to 256 bytes - prepare two blocks // If we got here after the main loop - there are 512 encrypted bytes waiting to be hashed // If we got here before the main loop - there are 448 encrpyred bytes waiting to be hashed VMOVDQA ·chacha20Constants<>(SB), AA0; VMOVDQA ·chacha20Constants<>(SB), AA1 VMOVDQA state1StoreAVX2, BB0; VMOVDQA state1StoreAVX2, BB1 VMOVDQA state2StoreAVX2, CC0; VMOVDQA state2StoreAVX2, CC1 VMOVDQA ctr3StoreAVX2, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD1 VMOVDQA DD0, TT1 VMOVDQA DD1, TT2 sealAVX2Tail256LoopA: polyAdd(0(oup)) polyMul LEAQ 16(oup), oup sealAVX2Tail256LoopB: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) polyAdd(0(oup)) polyMul VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0) polyAdd(16(oup)) polyMul LEAQ 32(oup), oup VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1 DECQ itr1 JG sealAVX2Tail256LoopA DECQ itr2 JGE sealAVX2Tail256LoopB VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1 VPADDD TT1, DD0, DD0; VPADDD TT2, DD1, DD1 VPERM2I128 $0x02, AA0, BB0, TT0 VPERM2I128 $0x02, CC0, DD0, TT1 VPERM2I128 $0x13, AA0, BB0, TT2 VPERM2I128 $0x13, CC0, DD0, TT3 VPXOR (0*32)(inp), TT0, TT0; VPXOR (1*32)(inp), TT1, TT1; VPXOR (2*32)(inp), TT2, TT2; VPXOR (3*32)(inp), TT3, TT3 VMOVDQU TT0, (0*32)(oup); VMOVDQU TT1, (1*32)(oup); VMOVDQU TT2, (2*32)(oup); VMOVDQU TT3, (3*32)(oup) MOVQ $128, itr1 LEAQ 128(inp), inp SUBQ $128, inl VPERM2I128 $0x02, AA1, BB1, AA0 VPERM2I128 $0x02, CC1, DD1, BB0 VPERM2I128 $0x13, AA1, BB1, CC0 VPERM2I128 $0x13, CC1, DD1, DD0 JMP sealAVX2SealHash // ---------------------------------------------------------------------------- // Special optimization for the last 384 bytes of ciphertext sealAVX2Tail384: // Need to decrypt up to 384 bytes - prepare two blocks // If we got here after the main loop - there are 512 encrypted bytes waiting to be hashed // If we got here before the main loop - there are 448 encrpyred bytes waiting to be hashed VMOVDQA ·chacha20Constants<>(SB), AA0; VMOVDQA AA0, AA1; VMOVDQA AA0, AA2 VMOVDQA state1StoreAVX2, BB0; VMOVDQA BB0, BB1; VMOVDQA BB0, BB2 VMOVDQA state2StoreAVX2, CC0; VMOVDQA CC0, CC1; VMOVDQA CC0, CC2 VMOVDQA ctr3StoreAVX2, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD1; VPADDD ·avx2IncMask<>(SB), DD1, DD2 VMOVDQA DD0, TT1; VMOVDQA DD1, TT2; VMOVDQA DD2, TT3 sealAVX2Tail384LoopA: polyAdd(0(oup)) polyMul LEAQ 16(oup), oup sealAVX2Tail384LoopB: chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0); chachaQR_AVX2(AA2, BB2, CC2, DD2, TT0) polyAdd(0(oup)) polyMul VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $4, BB2, BB2, BB2 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1; VPALIGNR $12, DD2, DD2, DD2 chachaQR_AVX2(AA0, BB0, CC0, DD0, TT0); chachaQR_AVX2(AA1, BB1, CC1, DD1, TT0); chachaQR_AVX2(AA2, BB2, CC2, DD2, TT0) polyAdd(16(oup)) polyMul LEAQ 32(oup), oup VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $12, BB2, BB2, BB2 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1; VPALIGNR $4, DD2, DD2, DD2 DECQ itr1 JG sealAVX2Tail384LoopA DECQ itr2 JGE sealAVX2Tail384LoopB VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1; VPADDD ·chacha20Constants<>(SB), AA2, AA2 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1; VPADDD state1StoreAVX2, BB2, BB2 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1; VPADDD state2StoreAVX2, CC2, CC2 VPADDD TT1, DD0, DD0; VPADDD TT2, DD1, DD1; VPADDD TT3, DD2, DD2 VPERM2I128 $0x02, AA0, BB0, TT0 VPERM2I128 $0x02, CC0, DD0, TT1 VPERM2I128 $0x13, AA0, BB0, TT2 VPERM2I128 $0x13, CC0, DD0, TT3 VPXOR (0*32)(inp), TT0, TT0; VPXOR (1*32)(inp), TT1, TT1; VPXOR (2*32)(inp), TT2, TT2; VPXOR (3*32)(inp), TT3, TT3 VMOVDQU TT0, (0*32)(oup); VMOVDQU TT1, (1*32)(oup); VMOVDQU TT2, (2*32)(oup); VMOVDQU TT3, (3*32)(oup) VPERM2I128 $0x02, AA1, BB1, TT0 VPERM2I128 $0x02, CC1, DD1, TT1 VPERM2I128 $0x13, AA1, BB1, TT2 VPERM2I128 $0x13, CC1, DD1, TT3 VPXOR (4*32)(inp), TT0, TT0; VPXOR (5*32)(inp), TT1, TT1; VPXOR (6*32)(inp), TT2, TT2; VPXOR (7*32)(inp), TT3, TT3 VMOVDQU TT0, (4*32)(oup); VMOVDQU TT1, (5*32)(oup); VMOVDQU TT2, (6*32)(oup); VMOVDQU TT3, (7*32)(oup) MOVQ $256, itr1 LEAQ 256(inp), inp SUBQ $256, inl VPERM2I128 $0x02, AA2, BB2, AA0 VPERM2I128 $0x02, CC2, DD2, BB0 VPERM2I128 $0x13, AA2, BB2, CC0 VPERM2I128 $0x13, CC2, DD2, DD0 JMP sealAVX2SealHash // ---------------------------------------------------------------------------- // Special optimization for the last 512 bytes of ciphertext sealAVX2Tail512: // Need to decrypt up to 512 bytes - prepare two blocks // If we got here after the main loop - there are 512 encrypted bytes waiting to be hashed // If we got here before the main loop - there are 448 encrpyred bytes waiting to be hashed VMOVDQA ·chacha20Constants<>(SB), AA0; VMOVDQA AA0, AA1; VMOVDQA AA0, AA2; VMOVDQA AA0, AA3 VMOVDQA state1StoreAVX2, BB0; VMOVDQA BB0, BB1; VMOVDQA BB0, BB2; VMOVDQA BB0, BB3 VMOVDQA state2StoreAVX2, CC0; VMOVDQA CC0, CC1; VMOVDQA CC0, CC2; VMOVDQA CC0, CC3 VMOVDQA ctr3StoreAVX2, DD0 VPADDD ·avx2IncMask<>(SB), DD0, DD0; VPADDD ·avx2IncMask<>(SB), DD0, DD1; VPADDD ·avx2IncMask<>(SB), DD1, DD2; VPADDD ·avx2IncMask<>(SB), DD2, DD3 VMOVDQA DD0, ctr0StoreAVX2; VMOVDQA DD1, ctr1StoreAVX2; VMOVDQA DD2, ctr2StoreAVX2; VMOVDQA DD3, ctr3StoreAVX2 sealAVX2Tail512LoopA: polyAdd(0(oup)) polyMul LEAQ 16(oup), oup sealAVX2Tail512LoopB: VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 polyAdd(0*8(oup)) polyMulAVX2 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol8<>(SB), DD0, DD0; VPSHUFB ·rol8<>(SB), DD1, DD1; VPSHUFB ·rol8<>(SB), DD2, DD2; VPSHUFB ·rol8<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $7, BB0, CC3; VPSRLD $25, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $7, BB1, CC3; VPSRLD $25, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $7, BB2, CC3; VPSRLD $25, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $7, BB3, CC3; VPSRLD $25, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 VPALIGNR $4, BB0, BB0, BB0; VPALIGNR $4, BB1, BB1, BB1; VPALIGNR $4, BB2, BB2, BB2; VPALIGNR $4, BB3, BB3, BB3 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $8, CC3, CC3, CC3 VPALIGNR $12, DD0, DD0, DD0; VPALIGNR $12, DD1, DD1, DD1; VPALIGNR $12, DD2, DD2, DD2; VPALIGNR $12, DD3, DD3, DD3 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol16<>(SB), DD0, DD0; VPSHUFB ·rol16<>(SB), DD1, DD1; VPSHUFB ·rol16<>(SB), DD2, DD2; VPSHUFB ·rol16<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 polyAdd(2*8(oup)) polyMulAVX2 LEAQ (4*8)(oup), oup VMOVDQA CC3, tmpStoreAVX2 VPSLLD $12, BB0, CC3; VPSRLD $20, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $12, BB1, CC3; VPSRLD $20, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $12, BB2, CC3; VPSRLD $20, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $12, BB3, CC3; VPSRLD $20, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 VPADDD BB0, AA0, AA0; VPADDD BB1, AA1, AA1; VPADDD BB2, AA2, AA2; VPADDD BB3, AA3, AA3 VPXOR AA0, DD0, DD0; VPXOR AA1, DD1, DD1; VPXOR AA2, DD2, DD2; VPXOR AA3, DD3, DD3 VPSHUFB ·rol8<>(SB), DD0, DD0; VPSHUFB ·rol8<>(SB), DD1, DD1; VPSHUFB ·rol8<>(SB), DD2, DD2; VPSHUFB ·rol8<>(SB), DD3, DD3 VPADDD DD0, CC0, CC0; VPADDD DD1, CC1, CC1; VPADDD DD2, CC2, CC2; VPADDD DD3, CC3, CC3 VPXOR CC0, BB0, BB0; VPXOR CC1, BB1, BB1; VPXOR CC2, BB2, BB2; VPXOR CC3, BB3, BB3 VMOVDQA CC3, tmpStoreAVX2 VPSLLD $7, BB0, CC3; VPSRLD $25, BB0, BB0; VPXOR CC3, BB0, BB0 VPSLLD $7, BB1, CC3; VPSRLD $25, BB1, BB1; VPXOR CC3, BB1, BB1 VPSLLD $7, BB2, CC3; VPSRLD $25, BB2, BB2; VPXOR CC3, BB2, BB2 VPSLLD $7, BB3, CC3; VPSRLD $25, BB3, BB3; VPXOR CC3, BB3, BB3 VMOVDQA tmpStoreAVX2, CC3 VPALIGNR $12, BB0, BB0, BB0; VPALIGNR $12, BB1, BB1, BB1; VPALIGNR $12, BB2, BB2, BB2; VPALIGNR $12, BB3, BB3, BB3 VPALIGNR $8, CC0, CC0, CC0; VPALIGNR $8, CC1, CC1, CC1; VPALIGNR $8, CC2, CC2, CC2; VPALIGNR $8, CC3, CC3, CC3 VPALIGNR $4, DD0, DD0, DD0; VPALIGNR $4, DD1, DD1, DD1; VPALIGNR $4, DD2, DD2, DD2; VPALIGNR $4, DD3, DD3, DD3 DECQ itr1 JG sealAVX2Tail512LoopA DECQ itr2 JGE sealAVX2Tail512LoopB VPADDD ·chacha20Constants<>(SB), AA0, AA0; VPADDD ·chacha20Constants<>(SB), AA1, AA1; VPADDD ·chacha20Constants<>(SB), AA2, AA2; VPADDD ·chacha20Constants<>(SB), AA3, AA3 VPADDD state1StoreAVX2, BB0, BB0; VPADDD state1StoreAVX2, BB1, BB1; VPADDD state1StoreAVX2, BB2, BB2; VPADDD state1StoreAVX2, BB3, BB3 VPADDD state2StoreAVX2, CC0, CC0; VPADDD state2StoreAVX2, CC1, CC1; VPADDD state2StoreAVX2, CC2, CC2; VPADDD state2StoreAVX2, CC3, CC3 VPADDD ctr0StoreAVX2, DD0, DD0; VPADDD ctr1StoreAVX2, DD1, DD1; VPADDD ctr2StoreAVX2, DD2, DD2; VPADDD ctr3StoreAVX2, DD3, DD3 VMOVDQA CC3, tmpStoreAVX2 VPERM2I128 $0x02, AA0, BB0, CC3 VPXOR (0*32)(inp), CC3, CC3 VMOVDQU CC3, (0*32)(oup) VPERM2I128 $0x02, CC0, DD0, CC3 VPXOR (1*32)(inp), CC3, CC3 VMOVDQU CC3, (1*32)(oup) VPERM2I128 $0x13, AA0, BB0, CC3 VPXOR (2*32)(inp), CC3, CC3 VMOVDQU CC3, (2*32)(oup) VPERM2I128 $0x13, CC0, DD0, CC3 VPXOR (3*32)(inp), CC3, CC3 VMOVDQU CC3, (3*32)(oup) VPERM2I128 $0x02, AA1, BB1, AA0 VPERM2I128 $0x02, CC1, DD1, BB0 VPERM2I128 $0x13, AA1, BB1, CC0 VPERM2I128 $0x13, CC1, DD1, DD0 VPXOR (4*32)(inp), AA0, AA0; VPXOR (5*32)(inp), BB0, BB0; VPXOR (6*32)(inp), CC0, CC0; VPXOR (7*32)(inp), DD0, DD0 VMOVDQU AA0, (4*32)(oup); VMOVDQU BB0, (5*32)(oup); VMOVDQU CC0, (6*32)(oup); VMOVDQU DD0, (7*32)(oup) VPERM2I128 $0x02, AA2, BB2, AA0 VPERM2I128 $0x02, CC2, DD2, BB0 VPERM2I128 $0x13, AA2, BB2, CC0 VPERM2I128 $0x13, CC2, DD2, DD0 VPXOR (8*32)(inp), AA0, AA0; VPXOR (9*32)(inp), BB0, BB0; VPXOR (10*32)(inp), CC0, CC0; VPXOR (11*32)(inp), DD0, DD0 VMOVDQU AA0, (8*32)(oup); VMOVDQU BB0, (9*32)(oup); VMOVDQU CC0, (10*32)(oup); VMOVDQU DD0, (11*32)(oup) MOVQ $384, itr1 LEAQ 384(inp), inp SUBQ $384, inl VPERM2I128 $0x02, AA3, BB3, AA0 VPERM2I128 $0x02, tmpStoreAVX2, DD3, BB0 VPERM2I128 $0x13, AA3, BB3, CC0 VPERM2I128 $0x13, tmpStoreAVX2, DD3, DD0 JMP sealAVX2SealHash // func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) TEXT ·cpuid(SB), NOSPLIT, $0-24 MOVL eaxArg+0(FP), AX MOVL ecxArg+4(FP), CX CPUID MOVL AX, eax+8(FP) MOVL BX, ebx+12(FP) MOVL CX, ecx+16(FP) MOVL DX, edx+20(FP) RET // func xgetbv() (eax, edx uint32) TEXT ·xgetbv(SB),NOSPLIT,$0-8 MOVL $0, CX XGETBV MOVL AX, eax+0(FP) MOVL DX, edx+4(FP) RET ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_amd64.go������������������0000644�0610621�0607500�00000006401�13172163317�027751� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7,amd64,!gccgo,!appengine package chacha20poly1305 import "encoding/binary" //go:noescape func chacha20Poly1305Open(dst []byte, key []uint32, src, ad []byte) bool //go:noescape func chacha20Poly1305Seal(dst []byte, key []uint32, src, ad []byte) // cpuid is implemented in chacha20poly1305_amd64.s. func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) // xgetbv with ecx = 0 is implemented in chacha20poly1305_amd64.s. func xgetbv() (eax, edx uint32) var ( useASM bool useAVX2 bool ) func init() { detectCPUFeatures() } // detectCPUFeatures is used to detect if cpu instructions // used by the functions implemented in assembler in // chacha20poly1305_amd64.s are supported. func detectCPUFeatures() { maxID, _, _, _ := cpuid(0, 0) if maxID < 1 { return } _, _, ecx1, _ := cpuid(1, 0) haveSSSE3 := isSet(9, ecx1) useASM = haveSSSE3 haveOSXSAVE := isSet(27, ecx1) osSupportsAVX := false // For XGETBV, OSXSAVE bit is required and sufficient. if haveOSXSAVE { eax, _ := xgetbv() // Check if XMM and YMM registers have OS support. osSupportsAVX = isSet(1, eax) && isSet(2, eax) } haveAVX := isSet(28, ecx1) && osSupportsAVX if maxID < 7 { return } _, ebx7, _, _ := cpuid(7, 0) haveAVX2 := isSet(5, ebx7) && haveAVX haveBMI2 := isSet(8, ebx7) useAVX2 = haveAVX2 && haveBMI2 } // isSet checks if bit at bitpos is set in value. func isSet(bitpos uint, value uint32) bool { return value&(1<<bitpos) != 0 } // setupState writes a ChaCha20 input matrix to state. See // https://tools.ietf.org/html/rfc7539#section-2.3. func setupState(state *[16]uint32, key *[32]byte, nonce []byte) { state[0] = 0x61707865 state[1] = 0x3320646e state[2] = 0x79622d32 state[3] = 0x6b206574 state[4] = binary.LittleEndian.Uint32(key[:4]) state[5] = binary.LittleEndian.Uint32(key[4:8]) state[6] = binary.LittleEndian.Uint32(key[8:12]) state[7] = binary.LittleEndian.Uint32(key[12:16]) state[8] = binary.LittleEndian.Uint32(key[16:20]) state[9] = binary.LittleEndian.Uint32(key[20:24]) state[10] = binary.LittleEndian.Uint32(key[24:28]) state[11] = binary.LittleEndian.Uint32(key[28:32]) state[12] = 0 state[13] = binary.LittleEndian.Uint32(nonce[:4]) state[14] = binary.LittleEndian.Uint32(nonce[4:8]) state[15] = binary.LittleEndian.Uint32(nonce[8:12]) } func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []byte { if !useASM { return c.sealGeneric(dst, nonce, plaintext, additionalData) } var state [16]uint32 setupState(&state, &c.key, nonce) ret, out := sliceForAppend(dst, len(plaintext)+16) chacha20Poly1305Seal(out[:], state[:], plaintext, additionalData) return ret } func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { if !useASM { return c.openGeneric(dst, nonce, ciphertext, additionalData) } var state [16]uint32 setupState(&state, &c.key, nonce) ciphertext = ciphertext[:len(ciphertext)-16] ret, out := sliceForAppend(dst, len(ciphertext)) if !chacha20Poly1305Open(out, state[:], ciphertext, additionalData) { for i := range out { out[i] = 0 } return nil, errOpen } return ret, nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305.go������������������������0000644�0610621�0607500�00000004434�13172163317�026762� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package chacha20poly1305 implements the ChaCha20-Poly1305 AEAD as specified in RFC 7539. package chacha20poly1305 // import "golang.org/x/crypto/chacha20poly1305" import ( "crypto/cipher" "errors" ) const ( // KeySize is the size of the key used by this AEAD, in bytes. KeySize = 32 // NonceSize is the size of the nonce used with this AEAD, in bytes. NonceSize = 12 ) type chacha20poly1305 struct { key [32]byte } // New returns a ChaCha20-Poly1305 AEAD that uses the given, 256-bit key. func New(key []byte) (cipher.AEAD, error) { if len(key) != KeySize { return nil, errors.New("chacha20poly1305: bad key length") } ret := new(chacha20poly1305) copy(ret.key[:], key) return ret, nil } func (c *chacha20poly1305) NonceSize() int { return NonceSize } func (c *chacha20poly1305) Overhead() int { return 16 } func (c *chacha20poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte { if len(nonce) != NonceSize { panic("chacha20poly1305: bad nonce length passed to Seal") } if uint64(len(plaintext)) > (1<<38)-64 { panic("chacha20poly1305: plaintext too large") } return c.seal(dst, nonce, plaintext, additionalData) } var errOpen = errors.New("chacha20poly1305: message authentication failed") func (c *chacha20poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { if len(nonce) != NonceSize { panic("chacha20poly1305: bad nonce length passed to Open") } if len(ciphertext) < 16 { return nil, errOpen } if uint64(len(ciphertext)) > (1<<38)-48 { panic("chacha20poly1305: ciphertext too large") } return c.open(dst, nonce, ciphertext, additionalData) } // sliceForAppend takes a slice and a requested number of bytes. It returns a // slice with the contents of the given slice followed by that many bytes and a // second slice that aliases into it and contains only the extra bytes. If the // original slice has sufficient capacity then no allocation is performed. func sliceForAppend(in []byte, n int) (head, tail []byte) { if total := len(in) + n; cap(in) >= total { head = in[:total] } else { head = make([]byte, total) copy(head, in) } tail = head[len(in):] return } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cast5/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022071� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cast5/cast5_test.go�����������������������������������������0000644�0610621�0607500�00000005100�13172163317�024472� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cast5 import ( "bytes" "encoding/hex" "testing" ) // This test vector is taken from RFC 2144, App B.1. // Since the other two test vectors are for reduced-round variants, we can't // use them. var basicTests = []struct { key, plainText, cipherText string }{ { "0123456712345678234567893456789a", "0123456789abcdef", "238b4fe5847e44b2", }, } func TestBasic(t *testing.T) { for i, test := range basicTests { key, _ := hex.DecodeString(test.key) plainText, _ := hex.DecodeString(test.plainText) expected, _ := hex.DecodeString(test.cipherText) c, err := NewCipher(key) if err != nil { t.Errorf("#%d: failed to create Cipher: %s", i, err) continue } var cipherText [BlockSize]byte c.Encrypt(cipherText[:], plainText) if !bytes.Equal(cipherText[:], expected) { t.Errorf("#%d: got:%x want:%x", i, cipherText, expected) } var plainTextAgain [BlockSize]byte c.Decrypt(plainTextAgain[:], cipherText[:]) if !bytes.Equal(plainTextAgain[:], plainText) { t.Errorf("#%d: got:%x want:%x", i, plainTextAgain, plainText) } } } // TestFull performs the test specified in RFC 2144, App B.2. // However, due to the length of time taken, it's disabled here and a more // limited version is included, below. func TestFull(t *testing.T) { if testing.Short() { // This is too slow for normal testing return } a, b := iterate(1000000) const expectedA = "eea9d0a249fd3ba6b3436fb89d6dca92" const expectedB = "b2c95eb00c31ad7180ac05b8e83d696e" if hex.EncodeToString(a) != expectedA { t.Errorf("a: got:%x want:%s", a, expectedA) } if hex.EncodeToString(b) != expectedB { t.Errorf("b: got:%x want:%s", b, expectedB) } } func iterate(iterations int) ([]byte, []byte) { const initValueHex = "0123456712345678234567893456789a" initValue, _ := hex.DecodeString(initValueHex) var a, b [16]byte copy(a[:], initValue) copy(b[:], initValue) for i := 0; i < iterations; i++ { c, _ := NewCipher(b[:]) c.Encrypt(a[:8], a[:8]) c.Encrypt(a[8:], a[8:]) c, _ = NewCipher(a[:]) c.Encrypt(b[:8], b[:8]) c.Encrypt(b[8:], b[8:]) } return a[:], b[:] } func TestLimited(t *testing.T) { a, b := iterate(1000) const expectedA = "23f73b14b02a2ad7dfb9f2c35644798d" const expectedB = "e5bf37eff14c456a40b21ce369370a9f" if hex.EncodeToString(a) != expectedA { t.Errorf("a: got:%x want:%s", a, expectedA) } if hex.EncodeToString(b) != expectedB { t.Errorf("b: got:%x want:%s", b, expectedB) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/cast5/cast5.go����������������������������������������������0000644�0610621�0607500�00000077435�13172163317�023457� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package cast5 implements CAST5, as defined in RFC 2144. CAST5 is a common // OpenPGP cipher. package cast5 // import "golang.org/x/crypto/cast5" import "errors" const BlockSize = 8 const KeySize = 16 type Cipher struct { masking [16]uint32 rotate [16]uint8 } func NewCipher(key []byte) (c *Cipher, err error) { if len(key) != KeySize { return nil, errors.New("CAST5: keys must be 16 bytes") } c = new(Cipher) c.keySchedule(key) return } func (c *Cipher) BlockSize() int { return BlockSize } func (c *Cipher) Encrypt(dst, src []byte) { l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) l, r = r, l^f1(r, c.masking[0], c.rotate[0]) l, r = r, l^f2(r, c.masking[1], c.rotate[1]) l, r = r, l^f3(r, c.masking[2], c.rotate[2]) l, r = r, l^f1(r, c.masking[3], c.rotate[3]) l, r = r, l^f2(r, c.masking[4], c.rotate[4]) l, r = r, l^f3(r, c.masking[5], c.rotate[5]) l, r = r, l^f1(r, c.masking[6], c.rotate[6]) l, r = r, l^f2(r, c.masking[7], c.rotate[7]) l, r = r, l^f3(r, c.masking[8], c.rotate[8]) l, r = r, l^f1(r, c.masking[9], c.rotate[9]) l, r = r, l^f2(r, c.masking[10], c.rotate[10]) l, r = r, l^f3(r, c.masking[11], c.rotate[11]) l, r = r, l^f1(r, c.masking[12], c.rotate[12]) l, r = r, l^f2(r, c.masking[13], c.rotate[13]) l, r = r, l^f3(r, c.masking[14], c.rotate[14]) l, r = r, l^f1(r, c.masking[15], c.rotate[15]) dst[0] = uint8(r >> 24) dst[1] = uint8(r >> 16) dst[2] = uint8(r >> 8) dst[3] = uint8(r) dst[4] = uint8(l >> 24) dst[5] = uint8(l >> 16) dst[6] = uint8(l >> 8) dst[7] = uint8(l) } func (c *Cipher) Decrypt(dst, src []byte) { l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) l, r = r, l^f1(r, c.masking[15], c.rotate[15]) l, r = r, l^f3(r, c.masking[14], c.rotate[14]) l, r = r, l^f2(r, c.masking[13], c.rotate[13]) l, r = r, l^f1(r, c.masking[12], c.rotate[12]) l, r = r, l^f3(r, c.masking[11], c.rotate[11]) l, r = r, l^f2(r, c.masking[10], c.rotate[10]) l, r = r, l^f1(r, c.masking[9], c.rotate[9]) l, r = r, l^f3(r, c.masking[8], c.rotate[8]) l, r = r, l^f2(r, c.masking[7], c.rotate[7]) l, r = r, l^f1(r, c.masking[6], c.rotate[6]) l, r = r, l^f3(r, c.masking[5], c.rotate[5]) l, r = r, l^f2(r, c.masking[4], c.rotate[4]) l, r = r, l^f1(r, c.masking[3], c.rotate[3]) l, r = r, l^f3(r, c.masking[2], c.rotate[2]) l, r = r, l^f2(r, c.masking[1], c.rotate[1]) l, r = r, l^f1(r, c.masking[0], c.rotate[0]) dst[0] = uint8(r >> 24) dst[1] = uint8(r >> 16) dst[2] = uint8(r >> 8) dst[3] = uint8(r) dst[4] = uint8(l >> 24) dst[5] = uint8(l >> 16) dst[6] = uint8(l >> 8) dst[7] = uint8(l) } type keyScheduleA [4][7]uint8 type keyScheduleB [4][5]uint8 // keyScheduleRound contains the magic values for a round of the key schedule. // The keyScheduleA deals with the lines like: // z0z1z2z3 = x0x1x2x3 ^ S5[xD] ^ S6[xF] ^ S7[xC] ^ S8[xE] ^ S7[x8] // Conceptually, both x and z are in the same array, x first. The first // element describes which word of this array gets written to and the // second, which word gets read. So, for the line above, it's "4, 0", because // it's writing to the first word of z, which, being after x, is word 4, and // reading from the first word of x: word 0. // // Next are the indexes into the S-boxes. Now the array is treated as bytes. So // "xD" is 0xd. The first byte of z is written as "16 + 0", just to be clear // that it's z that we're indexing. // // keyScheduleB deals with lines like: // K1 = S5[z8] ^ S6[z9] ^ S7[z7] ^ S8[z6] ^ S5[z2] // "K1" is ignored because key words are always written in order. So the five // elements are the S-box indexes. They use the same form as in keyScheduleA, // above. type keyScheduleRound struct{} type keySchedule []keyScheduleRound var schedule = []struct { a keyScheduleA b keyScheduleB }{ { keyScheduleA{ {4, 0, 0xd, 0xf, 0xc, 0xe, 0x8}, {5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa}, {6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9}, {7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb}, }, keyScheduleB{ {16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2}, {16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6}, {16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9}, {16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc}, }, }, { keyScheduleA{ {0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0}, {1, 4, 0, 2, 1, 3, 16 + 2}, {2, 5, 7, 6, 5, 4, 16 + 1}, {3, 7, 0xa, 9, 0xb, 8, 16 + 3}, }, keyScheduleB{ {3, 2, 0xc, 0xd, 8}, {1, 0, 0xe, 0xf, 0xd}, {7, 6, 8, 9, 3}, {5, 4, 0xa, 0xb, 7}, }, }, { keyScheduleA{ {4, 0, 0xd, 0xf, 0xc, 0xe, 8}, {5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa}, {6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9}, {7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb}, }, keyScheduleB{ {16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9}, {16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc}, {16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2}, {16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6}, }, }, { keyScheduleA{ {0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0}, {1, 4, 0, 2, 1, 3, 16 + 2}, {2, 5, 7, 6, 5, 4, 16 + 1}, {3, 7, 0xa, 9, 0xb, 8, 16 + 3}, }, keyScheduleB{ {8, 9, 7, 6, 3}, {0xa, 0xb, 5, 4, 7}, {0xc, 0xd, 3, 2, 8}, {0xe, 0xf, 1, 0, 0xd}, }, }, } func (c *Cipher) keySchedule(in []byte) { var t [8]uint32 var k [32]uint32 for i := 0; i < 4; i++ { j := i * 4 t[i] = uint32(in[j])<<24 | uint32(in[j+1])<<16 | uint32(in[j+2])<<8 | uint32(in[j+3]) } x := []byte{6, 7, 4, 5} ki := 0 for half := 0; half < 2; half++ { for _, round := range schedule { for j := 0; j < 4; j++ { var a [7]uint8 copy(a[:], round.a[j][:]) w := t[a[1]] w ^= sBox[4][(t[a[2]>>2]>>(24-8*(a[2]&3)))&0xff] w ^= sBox[5][(t[a[3]>>2]>>(24-8*(a[3]&3)))&0xff] w ^= sBox[6][(t[a[4]>>2]>>(24-8*(a[4]&3)))&0xff] w ^= sBox[7][(t[a[5]>>2]>>(24-8*(a[5]&3)))&0xff] w ^= sBox[x[j]][(t[a[6]>>2]>>(24-8*(a[6]&3)))&0xff] t[a[0]] = w } for j := 0; j < 4; j++ { var b [5]uint8 copy(b[:], round.b[j][:]) w := sBox[4][(t[b[0]>>2]>>(24-8*(b[0]&3)))&0xff] w ^= sBox[5][(t[b[1]>>2]>>(24-8*(b[1]&3)))&0xff] w ^= sBox[6][(t[b[2]>>2]>>(24-8*(b[2]&3)))&0xff] w ^= sBox[7][(t[b[3]>>2]>>(24-8*(b[3]&3)))&0xff] w ^= sBox[4+j][(t[b[4]>>2]>>(24-8*(b[4]&3)))&0xff] k[ki] = w ki++ } } } for i := 0; i < 16; i++ { c.masking[i] = k[i] c.rotate[i] = uint8(k[16+i] & 0x1f) } } // These are the three 'f' functions. See RFC 2144, section 2.2. func f1(d, m uint32, r uint8) uint32 { t := m + d I := (t << r) | (t >> (32 - r)) return ((sBox[0][I>>24] ^ sBox[1][(I>>16)&0xff]) - sBox[2][(I>>8)&0xff]) + sBox[3][I&0xff] } func f2(d, m uint32, r uint8) uint32 { t := m ^ d I := (t << r) | (t >> (32 - r)) return ((sBox[0][I>>24] - sBox[1][(I>>16)&0xff]) + sBox[2][(I>>8)&0xff]) ^ sBox[3][I&0xff] } func f3(d, m uint32, r uint8) uint32 { t := m - d I := (t << r) | (t >> (32 - r)) return ((sBox[0][I>>24] + sBox[1][(I>>16)&0xff]) ^ sBox[2][(I>>8)&0xff]) - sBox[3][I&0xff] } var sBox = [8][256]uint32{ { 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf, }, { 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1, }, { 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783, }, { 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2, }, { 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4, }, { 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f, }, { 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3, }, { 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e, }, } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021706� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/twist.go����������������������������������������������0000644�0610621�0607500�00000012272�13172163317�023413� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 import ( "math/big" ) // twistPoint implements the elliptic curve y²=x³+3/ξ over GF(p²). Points are // kept in Jacobian form and t=z² when valid. The group Gâ‚‚ is the set of // n-torsion points of this curve over GF(p²) (where n = Order) type twistPoint struct { x, y, z, t *gfP2 } var twistB = &gfP2{ bigFromBase10("6500054969564660373279643874235990574282535810762300357187714502686418407178"), bigFromBase10("45500384786952622612957507119651934019977750675336102500314001518804928850249"), } // twistGen is the generator of group Gâ‚‚. var twistGen = &twistPoint{ &gfP2{ bigFromBase10("21167961636542580255011770066570541300993051739349375019639421053990175267184"), bigFromBase10("64746500191241794695844075326670126197795977525365406531717464316923369116492"), }, &gfP2{ bigFromBase10("20666913350058776956210519119118544732556678129809273996262322366050359951122"), bigFromBase10("17778617556404439934652658462602675281523610326338642107814333856843981424549"), }, &gfP2{ bigFromBase10("0"), bigFromBase10("1"), }, &gfP2{ bigFromBase10("0"), bigFromBase10("1"), }, } func newTwistPoint(pool *bnPool) *twistPoint { return &twistPoint{ newGFp2(pool), newGFp2(pool), newGFp2(pool), newGFp2(pool), } } func (c *twistPoint) String() string { return "(" + c.x.String() + ", " + c.y.String() + ", " + c.z.String() + ")" } func (c *twistPoint) Put(pool *bnPool) { c.x.Put(pool) c.y.Put(pool) c.z.Put(pool) c.t.Put(pool) } func (c *twistPoint) Set(a *twistPoint) { c.x.Set(a.x) c.y.Set(a.y) c.z.Set(a.z) c.t.Set(a.t) } // IsOnCurve returns true iff c is on the curve where c must be in affine form. func (c *twistPoint) IsOnCurve() bool { pool := new(bnPool) yy := newGFp2(pool).Square(c.y, pool) xxx := newGFp2(pool).Square(c.x, pool) xxx.Mul(xxx, c.x, pool) yy.Sub(yy, xxx) yy.Sub(yy, twistB) yy.Minimal() return yy.x.Sign() == 0 && yy.y.Sign() == 0 } func (c *twistPoint) SetInfinity() { c.z.SetZero() } func (c *twistPoint) IsInfinity() bool { return c.z.IsZero() } func (c *twistPoint) Add(a, b *twistPoint, pool *bnPool) { // For additional comments, see the same function in curve.go. if a.IsInfinity() { c.Set(b) return } if b.IsInfinity() { c.Set(a) return } // See http://hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2007-bl.op3 z1z1 := newGFp2(pool).Square(a.z, pool) z2z2 := newGFp2(pool).Square(b.z, pool) u1 := newGFp2(pool).Mul(a.x, z2z2, pool) u2 := newGFp2(pool).Mul(b.x, z1z1, pool) t := newGFp2(pool).Mul(b.z, z2z2, pool) s1 := newGFp2(pool).Mul(a.y, t, pool) t.Mul(a.z, z1z1, pool) s2 := newGFp2(pool).Mul(b.y, t, pool) h := newGFp2(pool).Sub(u2, u1) xEqual := h.IsZero() t.Add(h, h) i := newGFp2(pool).Square(t, pool) j := newGFp2(pool).Mul(h, i, pool) t.Sub(s2, s1) yEqual := t.IsZero() if xEqual && yEqual { c.Double(a, pool) return } r := newGFp2(pool).Add(t, t) v := newGFp2(pool).Mul(u1, i, pool) t4 := newGFp2(pool).Square(r, pool) t.Add(v, v) t6 := newGFp2(pool).Sub(t4, j) c.x.Sub(t6, t) t.Sub(v, c.x) // t7 t4.Mul(s1, j, pool) // t8 t6.Add(t4, t4) // t9 t4.Mul(r, t, pool) // t10 c.y.Sub(t4, t6) t.Add(a.z, b.z) // t11 t4.Square(t, pool) // t12 t.Sub(t4, z1z1) // t13 t4.Sub(t, z2z2) // t14 c.z.Mul(t4, h, pool) z1z1.Put(pool) z2z2.Put(pool) u1.Put(pool) u2.Put(pool) t.Put(pool) s1.Put(pool) s2.Put(pool) h.Put(pool) i.Put(pool) j.Put(pool) r.Put(pool) v.Put(pool) t4.Put(pool) t6.Put(pool) } func (c *twistPoint) Double(a *twistPoint, pool *bnPool) { // See http://hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/doubling/dbl-2009-l.op3 A := newGFp2(pool).Square(a.x, pool) B := newGFp2(pool).Square(a.y, pool) C := newGFp2(pool).Square(B, pool) t := newGFp2(pool).Add(a.x, B) t2 := newGFp2(pool).Square(t, pool) t.Sub(t2, A) t2.Sub(t, C) d := newGFp2(pool).Add(t2, t2) t.Add(A, A) e := newGFp2(pool).Add(t, A) f := newGFp2(pool).Square(e, pool) t.Add(d, d) c.x.Sub(f, t) t.Add(C, C) t2.Add(t, t) t.Add(t2, t2) c.y.Sub(d, c.x) t2.Mul(e, c.y, pool) c.y.Sub(t2, t) t.Mul(a.y, a.z, pool) c.z.Add(t, t) A.Put(pool) B.Put(pool) C.Put(pool) t.Put(pool) t2.Put(pool) d.Put(pool) e.Put(pool) f.Put(pool) } func (c *twistPoint) Mul(a *twistPoint, scalar *big.Int, pool *bnPool) *twistPoint { sum := newTwistPoint(pool) sum.SetInfinity() t := newTwistPoint(pool) for i := scalar.BitLen(); i >= 0; i-- { t.Double(sum, pool) if scalar.Bit(i) != 0 { sum.Add(t, a, pool) } else { sum.Set(t) } } c.Set(sum) sum.Put(pool) t.Put(pool) return c } func (c *twistPoint) MakeAffine(pool *bnPool) *twistPoint { if c.z.IsOne() { return c } zInv := newGFp2(pool).Invert(c.z, pool) t := newGFp2(pool).Mul(c.y, zInv, pool) zInv2 := newGFp2(pool).Square(zInv, pool) c.y.Mul(t, zInv2, pool) t.Mul(c.x, zInv2, pool) c.x.Set(t) c.z.SetOne() c.t.SetOne() zInv.Put(pool) t.Put(pool) zInv2.Put(pool) return c } func (c *twistPoint) Negative(a *twistPoint, pool *bnPool) { c.x.Set(a.x) c.y.SetZero() c.y.Sub(c.y, a.y) c.z.Set(a.z) c.t.SetZero() } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/optate.go���������������������������������������������0000644�0610621�0607500�00000020733�13172163317�023536� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 func lineFunctionAdd(r, p *twistPoint, q *curvePoint, r2 *gfP2, pool *bnPool) (a, b, c *gfP2, rOut *twistPoint) { // See the mixed addition algorithm from "Faster Computation of the // Tate Pairing", http://arxiv.org/pdf/0904.0854v3.pdf B := newGFp2(pool).Mul(p.x, r.t, pool) D := newGFp2(pool).Add(p.y, r.z) D.Square(D, pool) D.Sub(D, r2) D.Sub(D, r.t) D.Mul(D, r.t, pool) H := newGFp2(pool).Sub(B, r.x) I := newGFp2(pool).Square(H, pool) E := newGFp2(pool).Add(I, I) E.Add(E, E) J := newGFp2(pool).Mul(H, E, pool) L1 := newGFp2(pool).Sub(D, r.y) L1.Sub(L1, r.y) V := newGFp2(pool).Mul(r.x, E, pool) rOut = newTwistPoint(pool) rOut.x.Square(L1, pool) rOut.x.Sub(rOut.x, J) rOut.x.Sub(rOut.x, V) rOut.x.Sub(rOut.x, V) rOut.z.Add(r.z, H) rOut.z.Square(rOut.z, pool) rOut.z.Sub(rOut.z, r.t) rOut.z.Sub(rOut.z, I) t := newGFp2(pool).Sub(V, rOut.x) t.Mul(t, L1, pool) t2 := newGFp2(pool).Mul(r.y, J, pool) t2.Add(t2, t2) rOut.y.Sub(t, t2) rOut.t.Square(rOut.z, pool) t.Add(p.y, rOut.z) t.Square(t, pool) t.Sub(t, r2) t.Sub(t, rOut.t) t2.Mul(L1, p.x, pool) t2.Add(t2, t2) a = newGFp2(pool) a.Sub(t2, t) c = newGFp2(pool) c.MulScalar(rOut.z, q.y) c.Add(c, c) b = newGFp2(pool) b.SetZero() b.Sub(b, L1) b.MulScalar(b, q.x) b.Add(b, b) B.Put(pool) D.Put(pool) H.Put(pool) I.Put(pool) E.Put(pool) J.Put(pool) L1.Put(pool) V.Put(pool) t.Put(pool) t2.Put(pool) return } func lineFunctionDouble(r *twistPoint, q *curvePoint, pool *bnPool) (a, b, c *gfP2, rOut *twistPoint) { // See the doubling algorithm for a=0 from "Faster Computation of the // Tate Pairing", http://arxiv.org/pdf/0904.0854v3.pdf A := newGFp2(pool).Square(r.x, pool) B := newGFp2(pool).Square(r.y, pool) C := newGFp2(pool).Square(B, pool) D := newGFp2(pool).Add(r.x, B) D.Square(D, pool) D.Sub(D, A) D.Sub(D, C) D.Add(D, D) E := newGFp2(pool).Add(A, A) E.Add(E, A) G := newGFp2(pool).Square(E, pool) rOut = newTwistPoint(pool) rOut.x.Sub(G, D) rOut.x.Sub(rOut.x, D) rOut.z.Add(r.y, r.z) rOut.z.Square(rOut.z, pool) rOut.z.Sub(rOut.z, B) rOut.z.Sub(rOut.z, r.t) rOut.y.Sub(D, rOut.x) rOut.y.Mul(rOut.y, E, pool) t := newGFp2(pool).Add(C, C) t.Add(t, t) t.Add(t, t) rOut.y.Sub(rOut.y, t) rOut.t.Square(rOut.z, pool) t.Mul(E, r.t, pool) t.Add(t, t) b = newGFp2(pool) b.SetZero() b.Sub(b, t) b.MulScalar(b, q.x) a = newGFp2(pool) a.Add(r.x, E) a.Square(a, pool) a.Sub(a, A) a.Sub(a, G) t.Add(B, B) t.Add(t, t) a.Sub(a, t) c = newGFp2(pool) c.Mul(rOut.z, r.t, pool) c.Add(c, c) c.MulScalar(c, q.y) A.Put(pool) B.Put(pool) C.Put(pool) D.Put(pool) E.Put(pool) G.Put(pool) t.Put(pool) return } func mulLine(ret *gfP12, a, b, c *gfP2, pool *bnPool) { a2 := newGFp6(pool) a2.x.SetZero() a2.y.Set(a) a2.z.Set(b) a2.Mul(a2, ret.x, pool) t3 := newGFp6(pool).MulScalar(ret.y, c, pool) t := newGFp2(pool) t.Add(b, c) t2 := newGFp6(pool) t2.x.SetZero() t2.y.Set(a) t2.z.Set(t) ret.x.Add(ret.x, ret.y) ret.y.Set(t3) ret.x.Mul(ret.x, t2, pool) ret.x.Sub(ret.x, a2) ret.x.Sub(ret.x, ret.y) a2.MulTau(a2, pool) ret.y.Add(ret.y, a2) a2.Put(pool) t3.Put(pool) t2.Put(pool) t.Put(pool) } // sixuPlus2NAF is 6u+2 in non-adjacent form. var sixuPlus2NAF = []int8{0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 1} // miller implements the Miller loop for calculating the Optimal Ate pairing. // See algorithm 1 from http://cryptojedi.org/papers/dclxvi-20100714.pdf func miller(q *twistPoint, p *curvePoint, pool *bnPool) *gfP12 { ret := newGFp12(pool) ret.SetOne() aAffine := newTwistPoint(pool) aAffine.Set(q) aAffine.MakeAffine(pool) bAffine := newCurvePoint(pool) bAffine.Set(p) bAffine.MakeAffine(pool) minusA := newTwistPoint(pool) minusA.Negative(aAffine, pool) r := newTwistPoint(pool) r.Set(aAffine) r2 := newGFp2(pool) r2.Square(aAffine.y, pool) for i := len(sixuPlus2NAF) - 1; i > 0; i-- { a, b, c, newR := lineFunctionDouble(r, bAffine, pool) if i != len(sixuPlus2NAF)-1 { ret.Square(ret, pool) } mulLine(ret, a, b, c, pool) a.Put(pool) b.Put(pool) c.Put(pool) r.Put(pool) r = newR switch sixuPlus2NAF[i-1] { case 1: a, b, c, newR = lineFunctionAdd(r, aAffine, bAffine, r2, pool) case -1: a, b, c, newR = lineFunctionAdd(r, minusA, bAffine, r2, pool) default: continue } mulLine(ret, a, b, c, pool) a.Put(pool) b.Put(pool) c.Put(pool) r.Put(pool) r = newR } // In order to calculate Q1 we have to convert q from the sextic twist // to the full GF(p^12) group, apply the Frobenius there, and convert // back. // // The twist isomorphism is (x', y') -> (xω², yω³). If we consider just // x for a moment, then after applying the Frobenius, we have x̄ω^(2p) // where xÌ„ is the conjugate of x. If we are going to apply the inverse // isomorphism we need a value with a single coefficient of ω² so we // rewrite this as x̄ω^(2p-2)ω². ξⶠ= ω and, due to the construction of // p, 2p-2 is a multiple of six. Therefore we can rewrite as // x̄ξ^((p-1)/3)ω² and applying the inverse isomorphism eliminates the // ω². // // A similar argument can be made for the y value. q1 := newTwistPoint(pool) q1.x.Conjugate(aAffine.x) q1.x.Mul(q1.x, xiToPMinus1Over3, pool) q1.y.Conjugate(aAffine.y) q1.y.Mul(q1.y, xiToPMinus1Over2, pool) q1.z.SetOne() q1.t.SetOne() // For Q2 we are applying the p² Frobenius. The two conjugations cancel // out and we are left only with the factors from the isomorphism. In // the case of x, we end up with a pure number which is why // xiToPSquaredMinus1Over3 is ∈ GF(p). With y we get a factor of -1. We // ignore this to end up with -Q2. minusQ2 := newTwistPoint(pool) minusQ2.x.MulScalar(aAffine.x, xiToPSquaredMinus1Over3) minusQ2.y.Set(aAffine.y) minusQ2.z.SetOne() minusQ2.t.SetOne() r2.Square(q1.y, pool) a, b, c, newR := lineFunctionAdd(r, q1, bAffine, r2, pool) mulLine(ret, a, b, c, pool) a.Put(pool) b.Put(pool) c.Put(pool) r.Put(pool) r = newR r2.Square(minusQ2.y, pool) a, b, c, newR = lineFunctionAdd(r, minusQ2, bAffine, r2, pool) mulLine(ret, a, b, c, pool) a.Put(pool) b.Put(pool) c.Put(pool) r.Put(pool) r = newR aAffine.Put(pool) bAffine.Put(pool) minusA.Put(pool) r.Put(pool) r2.Put(pool) return ret } // finalExponentiation computes the (p¹²-1)/Order-th power of an element of // GF(p¹²) to obtain an element of GT (steps 13-15 of algorithm 1 from // http://cryptojedi.org/papers/dclxvi-20100714.pdf) func finalExponentiation(in *gfP12, pool *bnPool) *gfP12 { t1 := newGFp12(pool) // This is the p^6-Frobenius t1.x.Negative(in.x) t1.y.Set(in.y) inv := newGFp12(pool) inv.Invert(in, pool) t1.Mul(t1, inv, pool) t2 := newGFp12(pool).FrobeniusP2(t1, pool) t1.Mul(t1, t2, pool) fp := newGFp12(pool).Frobenius(t1, pool) fp2 := newGFp12(pool).FrobeniusP2(t1, pool) fp3 := newGFp12(pool).Frobenius(fp2, pool) fu, fu2, fu3 := newGFp12(pool), newGFp12(pool), newGFp12(pool) fu.Exp(t1, u, pool) fu2.Exp(fu, u, pool) fu3.Exp(fu2, u, pool) y3 := newGFp12(pool).Frobenius(fu, pool) fu2p := newGFp12(pool).Frobenius(fu2, pool) fu3p := newGFp12(pool).Frobenius(fu3, pool) y2 := newGFp12(pool).FrobeniusP2(fu2, pool) y0 := newGFp12(pool) y0.Mul(fp, fp2, pool) y0.Mul(y0, fp3, pool) y1, y4, y5 := newGFp12(pool), newGFp12(pool), newGFp12(pool) y1.Conjugate(t1) y5.Conjugate(fu2) y3.Conjugate(y3) y4.Mul(fu, fu2p, pool) y4.Conjugate(y4) y6 := newGFp12(pool) y6.Mul(fu3, fu3p, pool) y6.Conjugate(y6) t0 := newGFp12(pool) t0.Square(y6, pool) t0.Mul(t0, y4, pool) t0.Mul(t0, y5, pool) t1.Mul(y3, y5, pool) t1.Mul(t1, t0, pool) t0.Mul(t0, y2, pool) t1.Square(t1, pool) t1.Mul(t1, t0, pool) t1.Square(t1, pool) t0.Mul(t1, y1, pool) t1.Mul(t1, y0, pool) t0.Square(t0, pool) t0.Mul(t0, t1, pool) inv.Put(pool) t1.Put(pool) t2.Put(pool) fp.Put(pool) fp2.Put(pool) fp3.Put(pool) fu.Put(pool) fu2.Put(pool) fu3.Put(pool) fu2p.Put(pool) fu3p.Put(pool) y0.Put(pool) y1.Put(pool) y2.Put(pool) y3.Put(pool) y4.Put(pool) y5.Put(pool) y6.Put(pool) return t0 } func optimalAte(a *twistPoint, b *curvePoint, pool *bnPool) *gfP12 { e := miller(a, b, pool) ret := finalExponentiation(e, pool) e.Put(pool) if a.IsInfinity() || b.IsInfinity() { ret.SetOne() } return ret } �������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/gfp6.go�����������������������������������������������0000644�0610621�0607500�00000013221�13172163317�023076� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 // For details of the algorithms used, see "Multiplication and Squaring on // Pairing-Friendly Fields, Devegili et al. // http://eprint.iacr.org/2006/471.pdf. import ( "math/big" ) // gfP6 implements the field of size pâ¶ as a cubic extension of gfP2 where τ³=ξ // and ξ=i+3. type gfP6 struct { x, y, z *gfP2 // value is xτ² + yÏ„ + z } func newGFp6(pool *bnPool) *gfP6 { return &gfP6{newGFp2(pool), newGFp2(pool), newGFp2(pool)} } func (e *gfP6) String() string { return "(" + e.x.String() + "," + e.y.String() + "," + e.z.String() + ")" } func (e *gfP6) Put(pool *bnPool) { e.x.Put(pool) e.y.Put(pool) e.z.Put(pool) } func (e *gfP6) Set(a *gfP6) *gfP6 { e.x.Set(a.x) e.y.Set(a.y) e.z.Set(a.z) return e } func (e *gfP6) SetZero() *gfP6 { e.x.SetZero() e.y.SetZero() e.z.SetZero() return e } func (e *gfP6) SetOne() *gfP6 { e.x.SetZero() e.y.SetZero() e.z.SetOne() return e } func (e *gfP6) Minimal() { e.x.Minimal() e.y.Minimal() e.z.Minimal() } func (e *gfP6) IsZero() bool { return e.x.IsZero() && e.y.IsZero() && e.z.IsZero() } func (e *gfP6) IsOne() bool { return e.x.IsZero() && e.y.IsZero() && e.z.IsOne() } func (e *gfP6) Negative(a *gfP6) *gfP6 { e.x.Negative(a.x) e.y.Negative(a.y) e.z.Negative(a.z) return e } func (e *gfP6) Frobenius(a *gfP6, pool *bnPool) *gfP6 { e.x.Conjugate(a.x) e.y.Conjugate(a.y) e.z.Conjugate(a.z) e.x.Mul(e.x, xiTo2PMinus2Over3, pool) e.y.Mul(e.y, xiToPMinus1Over3, pool) return e } // FrobeniusP2 computes (xτ²+yÏ„+z)^(p²) = xÏ„^(2p²) + yÏ„^(p²) + z func (e *gfP6) FrobeniusP2(a *gfP6) *gfP6 { // Ï„^(2p²) = τ²τ^(2p²-2) = τ²ξ^((2p²-2)/3) e.x.MulScalar(a.x, xiTo2PSquaredMinus2Over3) // Ï„^(p²) = ττ^(p²-1) = τξ^((p²-1)/3) e.y.MulScalar(a.y, xiToPSquaredMinus1Over3) e.z.Set(a.z) return e } func (e *gfP6) Add(a, b *gfP6) *gfP6 { e.x.Add(a.x, b.x) e.y.Add(a.y, b.y) e.z.Add(a.z, b.z) return e } func (e *gfP6) Sub(a, b *gfP6) *gfP6 { e.x.Sub(a.x, b.x) e.y.Sub(a.y, b.y) e.z.Sub(a.z, b.z) return e } func (e *gfP6) Double(a *gfP6) *gfP6 { e.x.Double(a.x) e.y.Double(a.y) e.z.Double(a.z) return e } func (e *gfP6) Mul(a, b *gfP6, pool *bnPool) *gfP6 { // "Multiplication and Squaring on Pairing-Friendly Fields" // Section 4, Karatsuba method. // http://eprint.iacr.org/2006/471.pdf v0 := newGFp2(pool) v0.Mul(a.z, b.z, pool) v1 := newGFp2(pool) v1.Mul(a.y, b.y, pool) v2 := newGFp2(pool) v2.Mul(a.x, b.x, pool) t0 := newGFp2(pool) t0.Add(a.x, a.y) t1 := newGFp2(pool) t1.Add(b.x, b.y) tz := newGFp2(pool) tz.Mul(t0, t1, pool) tz.Sub(tz, v1) tz.Sub(tz, v2) tz.MulXi(tz, pool) tz.Add(tz, v0) t0.Add(a.y, a.z) t1.Add(b.y, b.z) ty := newGFp2(pool) ty.Mul(t0, t1, pool) ty.Sub(ty, v0) ty.Sub(ty, v1) t0.MulXi(v2, pool) ty.Add(ty, t0) t0.Add(a.x, a.z) t1.Add(b.x, b.z) tx := newGFp2(pool) tx.Mul(t0, t1, pool) tx.Sub(tx, v0) tx.Add(tx, v1) tx.Sub(tx, v2) e.x.Set(tx) e.y.Set(ty) e.z.Set(tz) t0.Put(pool) t1.Put(pool) tx.Put(pool) ty.Put(pool) tz.Put(pool) v0.Put(pool) v1.Put(pool) v2.Put(pool) return e } func (e *gfP6) MulScalar(a *gfP6, b *gfP2, pool *bnPool) *gfP6 { e.x.Mul(a.x, b, pool) e.y.Mul(a.y, b, pool) e.z.Mul(a.z, b, pool) return e } func (e *gfP6) MulGFP(a *gfP6, b *big.Int) *gfP6 { e.x.MulScalar(a.x, b) e.y.MulScalar(a.y, b) e.z.MulScalar(a.z, b) return e } // MulTau computes τ·(aτ²+bÏ„+c) = bτ²+cÏ„+aξ func (e *gfP6) MulTau(a *gfP6, pool *bnPool) { tz := newGFp2(pool) tz.MulXi(a.x, pool) ty := newGFp2(pool) ty.Set(a.y) e.y.Set(a.z) e.x.Set(ty) e.z.Set(tz) tz.Put(pool) ty.Put(pool) } func (e *gfP6) Square(a *gfP6, pool *bnPool) *gfP6 { v0 := newGFp2(pool).Square(a.z, pool) v1 := newGFp2(pool).Square(a.y, pool) v2 := newGFp2(pool).Square(a.x, pool) c0 := newGFp2(pool).Add(a.x, a.y) c0.Square(c0, pool) c0.Sub(c0, v1) c0.Sub(c0, v2) c0.MulXi(c0, pool) c0.Add(c0, v0) c1 := newGFp2(pool).Add(a.y, a.z) c1.Square(c1, pool) c1.Sub(c1, v0) c1.Sub(c1, v1) xiV2 := newGFp2(pool).MulXi(v2, pool) c1.Add(c1, xiV2) c2 := newGFp2(pool).Add(a.x, a.z) c2.Square(c2, pool) c2.Sub(c2, v0) c2.Add(c2, v1) c2.Sub(c2, v2) e.x.Set(c2) e.y.Set(c1) e.z.Set(c0) v0.Put(pool) v1.Put(pool) v2.Put(pool) c0.Put(pool) c1.Put(pool) c2.Put(pool) xiV2.Put(pool) return e } func (e *gfP6) Invert(a *gfP6, pool *bnPool) *gfP6 { // See "Implementing cryptographic pairings", M. Scott, section 3.2. // ftp://136.206.11.249/pub/crypto/pairings.pdf // Here we can give a short explanation of how it works: let j be a cubic root of // unity in GF(p²) so that 1+j+j²=0. // Then (xτ² + yÏ„ + z)(xj²τ² + yjÏ„ + z)(xjτ² + yj²τ + z) // = (xτ² + yÏ„ + z)(Cτ²+BÏ„+A) // = (x³ξ²+y³ξ+z³-3ξxyz) = F is an element of the base field (the norm). // // On the other hand (xj²τ² + yjÏ„ + z)(xjτ² + yj²τ + z) // = τ²(y²-ξxz) + Ï„(ξx²-yz) + (z²-ξxy) // // So that's why A = (z²-ξxy), B = (ξx²-yz), C = (y²-ξxz) t1 := newGFp2(pool) A := newGFp2(pool) A.Square(a.z, pool) t1.Mul(a.x, a.y, pool) t1.MulXi(t1, pool) A.Sub(A, t1) B := newGFp2(pool) B.Square(a.x, pool) B.MulXi(B, pool) t1.Mul(a.y, a.z, pool) B.Sub(B, t1) C := newGFp2(pool) C.Square(a.y, pool) t1.Mul(a.x, a.z, pool) C.Sub(C, t1) F := newGFp2(pool) F.Mul(C, a.y, pool) F.MulXi(F, pool) t1.Mul(A, a.z, pool) F.Add(F, t1) t1.Mul(B, a.x, pool) t1.MulXi(t1, pool) F.Add(F, t1) F.Invert(F, pool) e.x.Mul(C, F, pool) e.y.Mul(B, F, pool) e.z.Mul(A, F, pool) t1.Put(pool) A.Put(pool) B.Put(pool) C.Put(pool) F.Put(pool) return e } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/gfp2.go�����������������������������������������������0000644�0610621�0607500�00000007320�13172163317�023075� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 // For details of the algorithms used, see "Multiplication and Squaring on // Pairing-Friendly Fields, Devegili et al. // http://eprint.iacr.org/2006/471.pdf. import ( "math/big" ) // gfP2 implements a field of size p² as a quadratic extension of the base // field where i²=-1. type gfP2 struct { x, y *big.Int // value is xi+y. } func newGFp2(pool *bnPool) *gfP2 { return &gfP2{pool.Get(), pool.Get()} } func (e *gfP2) String() string { x := new(big.Int).Mod(e.x, p) y := new(big.Int).Mod(e.y, p) return "(" + x.String() + "," + y.String() + ")" } func (e *gfP2) Put(pool *bnPool) { pool.Put(e.x) pool.Put(e.y) } func (e *gfP2) Set(a *gfP2) *gfP2 { e.x.Set(a.x) e.y.Set(a.y) return e } func (e *gfP2) SetZero() *gfP2 { e.x.SetInt64(0) e.y.SetInt64(0) return e } func (e *gfP2) SetOne() *gfP2 { e.x.SetInt64(0) e.y.SetInt64(1) return e } func (e *gfP2) Minimal() { if e.x.Sign() < 0 || e.x.Cmp(p) >= 0 { e.x.Mod(e.x, p) } if e.y.Sign() < 0 || e.y.Cmp(p) >= 0 { e.y.Mod(e.y, p) } } func (e *gfP2) IsZero() bool { return e.x.Sign() == 0 && e.y.Sign() == 0 } func (e *gfP2) IsOne() bool { if e.x.Sign() != 0 { return false } words := e.y.Bits() return len(words) == 1 && words[0] == 1 } func (e *gfP2) Conjugate(a *gfP2) *gfP2 { e.y.Set(a.y) e.x.Neg(a.x) return e } func (e *gfP2) Negative(a *gfP2) *gfP2 { e.x.Neg(a.x) e.y.Neg(a.y) return e } func (e *gfP2) Add(a, b *gfP2) *gfP2 { e.x.Add(a.x, b.x) e.y.Add(a.y, b.y) return e } func (e *gfP2) Sub(a, b *gfP2) *gfP2 { e.x.Sub(a.x, b.x) e.y.Sub(a.y, b.y) return e } func (e *gfP2) Double(a *gfP2) *gfP2 { e.x.Lsh(a.x, 1) e.y.Lsh(a.y, 1) return e } func (c *gfP2) Exp(a *gfP2, power *big.Int, pool *bnPool) *gfP2 { sum := newGFp2(pool) sum.SetOne() t := newGFp2(pool) for i := power.BitLen() - 1; i >= 0; i-- { t.Square(sum, pool) if power.Bit(i) != 0 { sum.Mul(t, a, pool) } else { sum.Set(t) } } c.Set(sum) sum.Put(pool) t.Put(pool) return c } // See "Multiplication and Squaring in Pairing-Friendly Fields", // http://eprint.iacr.org/2006/471.pdf func (e *gfP2) Mul(a, b *gfP2, pool *bnPool) *gfP2 { tx := pool.Get().Mul(a.x, b.y) t := pool.Get().Mul(b.x, a.y) tx.Add(tx, t) tx.Mod(tx, p) ty := pool.Get().Mul(a.y, b.y) t.Mul(a.x, b.x) ty.Sub(ty, t) e.y.Mod(ty, p) e.x.Set(tx) pool.Put(tx) pool.Put(ty) pool.Put(t) return e } func (e *gfP2) MulScalar(a *gfP2, b *big.Int) *gfP2 { e.x.Mul(a.x, b) e.y.Mul(a.y, b) return e } // MulXi sets e=ξa where ξ=i+3 and then returns e. func (e *gfP2) MulXi(a *gfP2, pool *bnPool) *gfP2 { // (xi+y)(i+3) = (3x+y)i+(3y-x) tx := pool.Get().Lsh(a.x, 1) tx.Add(tx, a.x) tx.Add(tx, a.y) ty := pool.Get().Lsh(a.y, 1) ty.Add(ty, a.y) ty.Sub(ty, a.x) e.x.Set(tx) e.y.Set(ty) pool.Put(tx) pool.Put(ty) return e } func (e *gfP2) Square(a *gfP2, pool *bnPool) *gfP2 { // Complex squaring algorithm: // (xi+b)² = (x+y)(y-x) + 2*i*x*y t1 := pool.Get().Sub(a.y, a.x) t2 := pool.Get().Add(a.x, a.y) ty := pool.Get().Mul(t1, t2) ty.Mod(ty, p) t1.Mul(a.x, a.y) t1.Lsh(t1, 1) e.x.Mod(t1, p) e.y.Set(ty) pool.Put(t1) pool.Put(t2) pool.Put(ty) return e } func (e *gfP2) Invert(a *gfP2, pool *bnPool) *gfP2 { // See "Implementing cryptographic pairings", M. Scott, section 3.2. // ftp://136.206.11.249/pub/crypto/pairings.pdf t := pool.Get() t.Mul(a.y, a.y) t2 := pool.Get() t2.Mul(a.x, a.x) t.Add(t, t2) inv := pool.Get() inv.ModInverse(t, p) e.x.Neg(a.x) e.x.Mul(e.x, inv) e.x.Mod(e.x, p) e.y.Mul(a.y, inv) e.y.Mod(e.y, p) pool.Put(t) pool.Put(t2) pool.Put(inv) return e } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/gfp12.go����������������������������������������������0000644�0610621�0607500�00000007075�13172163317�023165� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 // For details of the algorithms used, see "Multiplication and Squaring on // Pairing-Friendly Fields, Devegili et al. // http://eprint.iacr.org/2006/471.pdf. import ( "math/big" ) // gfP12 implements the field of size p¹² as a quadratic extension of gfP6 // where ω²=Ï„. type gfP12 struct { x, y *gfP6 // value is xω + y } func newGFp12(pool *bnPool) *gfP12 { return &gfP12{newGFp6(pool), newGFp6(pool)} } func (e *gfP12) String() string { return "(" + e.x.String() + "," + e.y.String() + ")" } func (e *gfP12) Put(pool *bnPool) { e.x.Put(pool) e.y.Put(pool) } func (e *gfP12) Set(a *gfP12) *gfP12 { e.x.Set(a.x) e.y.Set(a.y) return e } func (e *gfP12) SetZero() *gfP12 { e.x.SetZero() e.y.SetZero() return e } func (e *gfP12) SetOne() *gfP12 { e.x.SetZero() e.y.SetOne() return e } func (e *gfP12) Minimal() { e.x.Minimal() e.y.Minimal() } func (e *gfP12) IsZero() bool { e.Minimal() return e.x.IsZero() && e.y.IsZero() } func (e *gfP12) IsOne() bool { e.Minimal() return e.x.IsZero() && e.y.IsOne() } func (e *gfP12) Conjugate(a *gfP12) *gfP12 { e.x.Negative(a.x) e.y.Set(a.y) return a } func (e *gfP12) Negative(a *gfP12) *gfP12 { e.x.Negative(a.x) e.y.Negative(a.y) return e } // Frobenius computes (xω+y)^p = x^p ω·ξ^((p-1)/6) + y^p func (e *gfP12) Frobenius(a *gfP12, pool *bnPool) *gfP12 { e.x.Frobenius(a.x, pool) e.y.Frobenius(a.y, pool) e.x.MulScalar(e.x, xiToPMinus1Over6, pool) return e } // FrobeniusP2 computes (xω+y)^p² = x^p² ω·ξ^((p²-1)/6) + y^p² func (e *gfP12) FrobeniusP2(a *gfP12, pool *bnPool) *gfP12 { e.x.FrobeniusP2(a.x) e.x.MulGFP(e.x, xiToPSquaredMinus1Over6) e.y.FrobeniusP2(a.y) return e } func (e *gfP12) Add(a, b *gfP12) *gfP12 { e.x.Add(a.x, b.x) e.y.Add(a.y, b.y) return e } func (e *gfP12) Sub(a, b *gfP12) *gfP12 { e.x.Sub(a.x, b.x) e.y.Sub(a.y, b.y) return e } func (e *gfP12) Mul(a, b *gfP12, pool *bnPool) *gfP12 { tx := newGFp6(pool) tx.Mul(a.x, b.y, pool) t := newGFp6(pool) t.Mul(b.x, a.y, pool) tx.Add(tx, t) ty := newGFp6(pool) ty.Mul(a.y, b.y, pool) t.Mul(a.x, b.x, pool) t.MulTau(t, pool) e.y.Add(ty, t) e.x.Set(tx) tx.Put(pool) ty.Put(pool) t.Put(pool) return e } func (e *gfP12) MulScalar(a *gfP12, b *gfP6, pool *bnPool) *gfP12 { e.x.Mul(e.x, b, pool) e.y.Mul(e.y, b, pool) return e } func (c *gfP12) Exp(a *gfP12, power *big.Int, pool *bnPool) *gfP12 { sum := newGFp12(pool) sum.SetOne() t := newGFp12(pool) for i := power.BitLen() - 1; i >= 0; i-- { t.Square(sum, pool) if power.Bit(i) != 0 { sum.Mul(t, a, pool) } else { sum.Set(t) } } c.Set(sum) sum.Put(pool) t.Put(pool) return c } func (e *gfP12) Square(a *gfP12, pool *bnPool) *gfP12 { // Complex squaring algorithm v0 := newGFp6(pool) v0.Mul(a.x, a.y, pool) t := newGFp6(pool) t.MulTau(a.x, pool) t.Add(a.y, t) ty := newGFp6(pool) ty.Add(a.x, a.y) ty.Mul(ty, t, pool) ty.Sub(ty, v0) t.MulTau(v0, pool) ty.Sub(ty, t) e.y.Set(ty) e.x.Double(v0) v0.Put(pool) t.Put(pool) ty.Put(pool) return e } func (e *gfP12) Invert(a *gfP12, pool *bnPool) *gfP12 { // See "Implementing cryptographic pairings", M. Scott, section 3.2. // ftp://136.206.11.249/pub/crypto/pairings.pdf t1 := newGFp6(pool) t2 := newGFp6(pool) t1.Square(a.x, pool) t2.Square(a.y, pool) t1.MulTau(t1, pool) t1.Sub(t2, t1) t2.Invert(t1, pool) e.x.Negative(a.x) e.y.Set(a.y) e.MulScalar(e, t2, pool) t1.Put(pool) t2.Put(pool) return e } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/example_test.go���������������������������������������0000644�0610621�0607500�00000002213�13172163317�024725� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 import ( "crypto/rand" ) func ExamplePair() { // This implements the tripartite Diffie-Hellman algorithm from "A One // Round Protocol for Tripartite Diffie-Hellman", A. Joux. // http://www.springerlink.com/content/cddc57yyva0hburb/fulltext.pdf // Each of three parties, a, b and c, generate a private value. a, _ := rand.Int(rand.Reader, Order) b, _ := rand.Int(rand.Reader, Order) c, _ := rand.Int(rand.Reader, Order) // Then each party calculates gâ‚ and gâ‚‚ times their private value. pa := new(G1).ScalarBaseMult(a) qa := new(G2).ScalarBaseMult(a) pb := new(G1).ScalarBaseMult(b) qb := new(G2).ScalarBaseMult(b) pc := new(G1).ScalarBaseMult(c) qc := new(G2).ScalarBaseMult(c) // Now each party exchanges its public values with the other two and // all parties can calculate the shared key. k1 := Pair(pb, qc) k1.ScalarMult(k1, a) k2 := Pair(pc, qa) k2.ScalarMult(k2, b) k3 := Pair(pa, qb) k3.ScalarMult(k3, c) // k1, k2 and k3 will all be equal. } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/curve.go����������������������������������������������0000644�0610621�0607500�00000012545�13172163317�023370� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 import ( "math/big" ) // curvePoint implements the elliptic curve y²=x³+3. Points are kept in // Jacobian form and t=z² when valid. Gâ‚ is the set of points of this curve on // GF(p). type curvePoint struct { x, y, z, t *big.Int } var curveB = new(big.Int).SetInt64(3) // curveGen is the generator of Gâ‚. var curveGen = &curvePoint{ new(big.Int).SetInt64(1), new(big.Int).SetInt64(-2), new(big.Int).SetInt64(1), new(big.Int).SetInt64(1), } func newCurvePoint(pool *bnPool) *curvePoint { return &curvePoint{ pool.Get(), pool.Get(), pool.Get(), pool.Get(), } } func (c *curvePoint) String() string { c.MakeAffine(new(bnPool)) return "(" + c.x.String() + ", " + c.y.String() + ")" } func (c *curvePoint) Put(pool *bnPool) { pool.Put(c.x) pool.Put(c.y) pool.Put(c.z) pool.Put(c.t) } func (c *curvePoint) Set(a *curvePoint) { c.x.Set(a.x) c.y.Set(a.y) c.z.Set(a.z) c.t.Set(a.t) } // IsOnCurve returns true iff c is on the curve where c must be in affine form. func (c *curvePoint) IsOnCurve() bool { yy := new(big.Int).Mul(c.y, c.y) xxx := new(big.Int).Mul(c.x, c.x) xxx.Mul(xxx, c.x) yy.Sub(yy, xxx) yy.Sub(yy, curveB) if yy.Sign() < 0 || yy.Cmp(p) >= 0 { yy.Mod(yy, p) } return yy.Sign() == 0 } func (c *curvePoint) SetInfinity() { c.z.SetInt64(0) } func (c *curvePoint) IsInfinity() bool { return c.z.Sign() == 0 } func (c *curvePoint) Add(a, b *curvePoint, pool *bnPool) { if a.IsInfinity() { c.Set(b) return } if b.IsInfinity() { c.Set(a) return } // See http://hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2007-bl.op3 // Normalize the points by replacing a = [x1:y1:z1] and b = [x2:y2:z2] // by [u1:s1:z1·z2] and [u2:s2:z1·z2] // where u1 = x1·z2², s1 = y1·z2³ and u1 = x2·z1², s2 = y2·z1³ z1z1 := pool.Get().Mul(a.z, a.z) z1z1.Mod(z1z1, p) z2z2 := pool.Get().Mul(b.z, b.z) z2z2.Mod(z2z2, p) u1 := pool.Get().Mul(a.x, z2z2) u1.Mod(u1, p) u2 := pool.Get().Mul(b.x, z1z1) u2.Mod(u2, p) t := pool.Get().Mul(b.z, z2z2) t.Mod(t, p) s1 := pool.Get().Mul(a.y, t) s1.Mod(s1, p) t.Mul(a.z, z1z1) t.Mod(t, p) s2 := pool.Get().Mul(b.y, t) s2.Mod(s2, p) // Compute x = (2h)²(s²-u1-u2) // where s = (s2-s1)/(u2-u1) is the slope of the line through // (u1,s1) and (u2,s2). The extra factor 2h = 2(u2-u1) comes from the value of z below. // This is also: // 4(s2-s1)² - 4h²(u1+u2) = 4(s2-s1)² - 4h³ - 4h²(2u1) // = r² - j - 2v // with the notations below. h := pool.Get().Sub(u2, u1) xEqual := h.Sign() == 0 t.Add(h, h) // i = 4h² i := pool.Get().Mul(t, t) i.Mod(i, p) // j = 4h³ j := pool.Get().Mul(h, i) j.Mod(j, p) t.Sub(s2, s1) yEqual := t.Sign() == 0 if xEqual && yEqual { c.Double(a, pool) return } r := pool.Get().Add(t, t) v := pool.Get().Mul(u1, i) v.Mod(v, p) // t4 = 4(s2-s1)² t4 := pool.Get().Mul(r, r) t4.Mod(t4, p) t.Add(v, v) t6 := pool.Get().Sub(t4, j) c.x.Sub(t6, t) // Set y = -(2h)³(s1 + s*(x/4h²-u1)) // This is also // y = - 2·s1·j - (s2-s1)(2x - 2i·u1) = r(v-x) - 2·s1·j t.Sub(v, c.x) // t7 t4.Mul(s1, j) // t8 t4.Mod(t4, p) t6.Add(t4, t4) // t9 t4.Mul(r, t) // t10 t4.Mod(t4, p) c.y.Sub(t4, t6) // Set z = 2(u2-u1)·z1·z2 = 2h·z1·z2 t.Add(a.z, b.z) // t11 t4.Mul(t, t) // t12 t4.Mod(t4, p) t.Sub(t4, z1z1) // t13 t4.Sub(t, z2z2) // t14 c.z.Mul(t4, h) c.z.Mod(c.z, p) pool.Put(z1z1) pool.Put(z2z2) pool.Put(u1) pool.Put(u2) pool.Put(t) pool.Put(s1) pool.Put(s2) pool.Put(h) pool.Put(i) pool.Put(j) pool.Put(r) pool.Put(v) pool.Put(t4) pool.Put(t6) } func (c *curvePoint) Double(a *curvePoint, pool *bnPool) { // See http://hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/doubling/dbl-2009-l.op3 A := pool.Get().Mul(a.x, a.x) A.Mod(A, p) B := pool.Get().Mul(a.y, a.y) B.Mod(B, p) C := pool.Get().Mul(B, B) C.Mod(C, p) t := pool.Get().Add(a.x, B) t2 := pool.Get().Mul(t, t) t2.Mod(t2, p) t.Sub(t2, A) t2.Sub(t, C) d := pool.Get().Add(t2, t2) t.Add(A, A) e := pool.Get().Add(t, A) f := pool.Get().Mul(e, e) f.Mod(f, p) t.Add(d, d) c.x.Sub(f, t) t.Add(C, C) t2.Add(t, t) t.Add(t2, t2) c.y.Sub(d, c.x) t2.Mul(e, c.y) t2.Mod(t2, p) c.y.Sub(t2, t) t.Mul(a.y, a.z) t.Mod(t, p) c.z.Add(t, t) pool.Put(A) pool.Put(B) pool.Put(C) pool.Put(t) pool.Put(t2) pool.Put(d) pool.Put(e) pool.Put(f) } func (c *curvePoint) Mul(a *curvePoint, scalar *big.Int, pool *bnPool) *curvePoint { sum := newCurvePoint(pool) sum.SetInfinity() t := newCurvePoint(pool) for i := scalar.BitLen(); i >= 0; i-- { t.Double(sum, pool) if scalar.Bit(i) != 0 { sum.Add(t, a, pool) } else { sum.Set(t) } } c.Set(sum) sum.Put(pool) t.Put(pool) return c } func (c *curvePoint) MakeAffine(pool *bnPool) *curvePoint { if words := c.z.Bits(); len(words) == 1 && words[0] == 1 { return c } zInv := pool.Get().ModInverse(c.z, p) t := pool.Get().Mul(c.y, zInv) t.Mod(t, p) zInv2 := pool.Get().Mul(zInv, zInv) zInv2.Mod(zInv2, p) c.y.Mul(t, zInv2) c.y.Mod(c.y, p) t.Mul(c.x, zInv2) t.Mod(t, p) c.x.Set(t) c.z.SetInt64(1) c.t.SetInt64(1) pool.Put(zInv) pool.Put(t) pool.Put(zInv2) return c } func (c *curvePoint) Negative(a *curvePoint) { c.x.Set(a.x) c.y.Neg(a.y) c.z.Set(a.z) c.t.SetInt64(0) } �����������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/constants.go������������������������������������������0000644�0610621�0607500�00000004650�13172163317�024256� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 import ( "math/big" ) func bigFromBase10(s string) *big.Int { n, _ := new(big.Int).SetString(s, 10) return n } // u is the BN parameter that determines the prime: 1868033³. var u = bigFromBase10("6518589491078791937") // p is a prime over which we form a basic field: 36uâ´+36u³+24u²+6u+1. var p = bigFromBase10("65000549695646603732796438742359905742825358107623003571877145026864184071783") // Order is the number of elements in both Gâ‚ and Gâ‚‚: 36uâ´+36u³+18u²+6u+1. var Order = bigFromBase10("65000549695646603732796438742359905742570406053903786389881062969044166799969") // xiToPMinus1Over6 is ξ^((p-1)/6) where ξ = i+3. var xiToPMinus1Over6 = &gfP2{bigFromBase10("8669379979083712429711189836753509758585994370025260553045152614783263110636"), bigFromBase10("19998038925833620163537568958541907098007303196759855091367510456613536016040")} // xiToPMinus1Over3 is ξ^((p-1)/3) where ξ = i+3. var xiToPMinus1Over3 = &gfP2{bigFromBase10("26098034838977895781559542626833399156321265654106457577426020397262786167059"), bigFromBase10("15931493369629630809226283458085260090334794394361662678240713231519278691715")} // xiToPMinus1Over2 is ξ^((p-1)/2) where ξ = i+3. var xiToPMinus1Over2 = &gfP2{bigFromBase10("50997318142241922852281555961173165965672272825141804376761836765206060036244"), bigFromBase10("38665955945962842195025998234511023902832543644254935982879660597356748036009")} // xiToPSquaredMinus1Over3 is ξ^((p²-1)/3) where ξ = i+3. var xiToPSquaredMinus1Over3 = bigFromBase10("65000549695646603727810655408050771481677621702948236658134783353303381437752") // xiTo2PSquaredMinus2Over3 is ξ^((2p²-2)/3) where ξ = i+3 (a cubic root of unity, mod p). var xiTo2PSquaredMinus2Over3 = bigFromBase10("4985783334309134261147736404674766913742361673560802634030") // xiToPSquaredMinus1Over6 is ξ^((1p²-1)/6) where ξ = i+3 (a cubic root of -1, mod p). var xiToPSquaredMinus1Over6 = bigFromBase10("65000549695646603727810655408050771481677621702948236658134783353303381437753") // xiTo2PMinus2Over3 is ξ^((2p-2)/3) where ξ = i+3. var xiTo2PMinus2Over3 = &gfP2{bigFromBase10("19885131339612776214803633203834694332692106372356013117629940868870585019582"), bigFromBase10("21645619881471562101905880913352894726728173167203616652430647841922248593627")} ����������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/bn256_test.go�����������������������������������������0000644�0610621�0607500�00000015050�13172163317�024131� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bn256 import ( "bytes" "crypto/rand" "math/big" "testing" ) func TestGFp2Invert(t *testing.T) { pool := new(bnPool) a := newGFp2(pool) a.x.SetString("23423492374", 10) a.y.SetString("12934872398472394827398470", 10) inv := newGFp2(pool) inv.Invert(a, pool) b := newGFp2(pool).Mul(inv, a, pool) if b.x.Int64() != 0 || b.y.Int64() != 1 { t.Fatalf("bad result for a^-1*a: %s %s", b.x, b.y) } a.Put(pool) b.Put(pool) inv.Put(pool) if c := pool.Count(); c > 0 { t.Errorf("Pool count non-zero: %d\n", c) } } func isZero(n *big.Int) bool { return new(big.Int).Mod(n, p).Int64() == 0 } func isOne(n *big.Int) bool { return new(big.Int).Mod(n, p).Int64() == 1 } func TestGFp6Invert(t *testing.T) { pool := new(bnPool) a := newGFp6(pool) a.x.x.SetString("239487238491", 10) a.x.y.SetString("2356249827341", 10) a.y.x.SetString("082659782", 10) a.y.y.SetString("182703523765", 10) a.z.x.SetString("978236549263", 10) a.z.y.SetString("64893242", 10) inv := newGFp6(pool) inv.Invert(a, pool) b := newGFp6(pool).Mul(inv, a, pool) if !isZero(b.x.x) || !isZero(b.x.y) || !isZero(b.y.x) || !isZero(b.y.y) || !isZero(b.z.x) || !isOne(b.z.y) { t.Fatalf("bad result for a^-1*a: %s", b) } a.Put(pool) b.Put(pool) inv.Put(pool) if c := pool.Count(); c > 0 { t.Errorf("Pool count non-zero: %d\n", c) } } func TestGFp12Invert(t *testing.T) { pool := new(bnPool) a := newGFp12(pool) a.x.x.x.SetString("239846234862342323958623", 10) a.x.x.y.SetString("2359862352529835623", 10) a.x.y.x.SetString("928836523", 10) a.x.y.y.SetString("9856234", 10) a.x.z.x.SetString("235635286", 10) a.x.z.y.SetString("5628392833", 10) a.y.x.x.SetString("252936598265329856238956532167968", 10) a.y.x.y.SetString("23596239865236954178968", 10) a.y.y.x.SetString("95421692834", 10) a.y.y.y.SetString("236548", 10) a.y.z.x.SetString("924523", 10) a.y.z.y.SetString("12954623", 10) inv := newGFp12(pool) inv.Invert(a, pool) b := newGFp12(pool).Mul(inv, a, pool) if !isZero(b.x.x.x) || !isZero(b.x.x.y) || !isZero(b.x.y.x) || !isZero(b.x.y.y) || !isZero(b.x.z.x) || !isZero(b.x.z.y) || !isZero(b.y.x.x) || !isZero(b.y.x.y) || !isZero(b.y.y.x) || !isZero(b.y.y.y) || !isZero(b.y.z.x) || !isOne(b.y.z.y) { t.Fatalf("bad result for a^-1*a: %s", b) } a.Put(pool) b.Put(pool) inv.Put(pool) if c := pool.Count(); c > 0 { t.Errorf("Pool count non-zero: %d\n", c) } } func TestCurveImpl(t *testing.T) { pool := new(bnPool) g := &curvePoint{ pool.Get().SetInt64(1), pool.Get().SetInt64(-2), pool.Get().SetInt64(1), pool.Get().SetInt64(0), } x := pool.Get().SetInt64(32498273234) X := newCurvePoint(pool).Mul(g, x, pool) y := pool.Get().SetInt64(98732423523) Y := newCurvePoint(pool).Mul(g, y, pool) s1 := newCurvePoint(pool).Mul(X, y, pool).MakeAffine(pool) s2 := newCurvePoint(pool).Mul(Y, x, pool).MakeAffine(pool) if s1.x.Cmp(s2.x) != 0 || s2.x.Cmp(s1.x) != 0 { t.Errorf("DH points don't match: (%s, %s) (%s, %s)", s1.x, s1.y, s2.x, s2.y) } pool.Put(x) X.Put(pool) pool.Put(y) Y.Put(pool) s1.Put(pool) s2.Put(pool) g.Put(pool) if c := pool.Count(); c > 0 { t.Errorf("Pool count non-zero: %d\n", c) } } func TestOrderG1(t *testing.T) { g := new(G1).ScalarBaseMult(Order) if !g.p.IsInfinity() { t.Error("G1 has incorrect order") } one := new(G1).ScalarBaseMult(new(big.Int).SetInt64(1)) g.Add(g, one) g.p.MakeAffine(nil) if g.p.x.Cmp(one.p.x) != 0 || g.p.y.Cmp(one.p.y) != 0 { t.Errorf("1+0 != 1 in G1") } } func TestOrderG2(t *testing.T) { g := new(G2).ScalarBaseMult(Order) if !g.p.IsInfinity() { t.Error("G2 has incorrect order") } one := new(G2).ScalarBaseMult(new(big.Int).SetInt64(1)) g.Add(g, one) g.p.MakeAffine(nil) if g.p.x.x.Cmp(one.p.x.x) != 0 || g.p.x.y.Cmp(one.p.x.y) != 0 || g.p.y.x.Cmp(one.p.y.x) != 0 || g.p.y.y.Cmp(one.p.y.y) != 0 { t.Errorf("1+0 != 1 in G2") } } func TestOrderGT(t *testing.T) { gt := Pair(&G1{curveGen}, &G2{twistGen}) g := new(GT).ScalarMult(gt, Order) if !g.p.IsOne() { t.Error("GT has incorrect order") } } func TestBilinearity(t *testing.T) { for i := 0; i < 2; i++ { a, p1, _ := RandomG1(rand.Reader) b, p2, _ := RandomG2(rand.Reader) e1 := Pair(p1, p2) e2 := Pair(&G1{curveGen}, &G2{twistGen}) e2.ScalarMult(e2, a) e2.ScalarMult(e2, b) minusE2 := new(GT).Neg(e2) e1.Add(e1, minusE2) if !e1.p.IsOne() { t.Fatalf("bad pairing result: %s", e1) } } } func TestG1Marshal(t *testing.T) { g := new(G1).ScalarBaseMult(new(big.Int).SetInt64(1)) form := g.Marshal() _, ok := new(G1).Unmarshal(form) if !ok { t.Fatalf("failed to unmarshal") } g.ScalarBaseMult(Order) form = g.Marshal() g2, ok := new(G1).Unmarshal(form) if !ok { t.Fatalf("failed to unmarshal ∞") } if !g2.p.IsInfinity() { t.Fatalf("∞ unmarshaled incorrectly") } } func TestG2Marshal(t *testing.T) { g := new(G2).ScalarBaseMult(new(big.Int).SetInt64(1)) form := g.Marshal() _, ok := new(G2).Unmarshal(form) if !ok { t.Fatalf("failed to unmarshal") } g.ScalarBaseMult(Order) form = g.Marshal() g2, ok := new(G2).Unmarshal(form) if !ok { t.Fatalf("failed to unmarshal ∞") } if !g2.p.IsInfinity() { t.Fatalf("∞ unmarshaled incorrectly") } } func TestG1Identity(t *testing.T) { g := new(G1).ScalarBaseMult(new(big.Int).SetInt64(0)) if !g.p.IsInfinity() { t.Error("failure") } } func TestG2Identity(t *testing.T) { g := new(G2).ScalarBaseMult(new(big.Int).SetInt64(0)) if !g.p.IsInfinity() { t.Error("failure") } } func TestTripartiteDiffieHellman(t *testing.T) { a, _ := rand.Int(rand.Reader, Order) b, _ := rand.Int(rand.Reader, Order) c, _ := rand.Int(rand.Reader, Order) pa, _ := new(G1).Unmarshal(new(G1).ScalarBaseMult(a).Marshal()) qa, _ := new(G2).Unmarshal(new(G2).ScalarBaseMult(a).Marshal()) pb, _ := new(G1).Unmarshal(new(G1).ScalarBaseMult(b).Marshal()) qb, _ := new(G2).Unmarshal(new(G2).ScalarBaseMult(b).Marshal()) pc, _ := new(G1).Unmarshal(new(G1).ScalarBaseMult(c).Marshal()) qc, _ := new(G2).Unmarshal(new(G2).ScalarBaseMult(c).Marshal()) k1 := Pair(pb, qc) k1.ScalarMult(k1, a) k1Bytes := k1.Marshal() k2 := Pair(pc, qa) k2.ScalarMult(k2, b) k2Bytes := k2.Marshal() k3 := Pair(pa, qb) k3.ScalarMult(k3, c) k3Bytes := k3.Marshal() if !bytes.Equal(k1Bytes, k2Bytes) || !bytes.Equal(k2Bytes, k3Bytes) { t.Errorf("keys didn't agree") } } func BenchmarkPairing(b *testing.B) { for i := 0; i < b.N; i++ { Pair(&G1{curveGen}, &G2{twistGen}) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bn256/bn256.go����������������������������������������������0000644�0610621�0607500�00000022625�13172163317�023100� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package bn256 implements a particular bilinear group at the 128-bit security level. // // Bilinear groups are the basis of many of the new cryptographic protocols // that have been proposed over the past decade. They consist of a triplet of // groups (Gâ‚, Gâ‚‚ and GT) such that there exists a function e(gâ‚Ë£,g₂ʸ)=gTˣʸ // (where gâ‚“ is a generator of the respective group). That function is called // a pairing function. // // This package specifically implements the Optimal Ate pairing over a 256-bit // Barreto-Naehrig curve as described in // http://cryptojedi.org/papers/dclxvi-20100714.pdf. Its output is compatible // with the implementation described in that paper. package bn256 // import "golang.org/x/crypto/bn256" import ( "crypto/rand" "io" "math/big" ) // BUG(agl): this implementation is not constant time. // TODO(agl): keep GF(p²) elements in Mongomery form. // G1 is an abstract cyclic group. The zero value is suitable for use as the // output of an operation, but cannot be used as an input. type G1 struct { p *curvePoint } // RandomG1 returns x and gâ‚Ë£ where x is a random, non-zero number read from r. func RandomG1(r io.Reader) (*big.Int, *G1, error) { var k *big.Int var err error for { k, err = rand.Int(r, Order) if err != nil { return nil, nil, err } if k.Sign() > 0 { break } } return k, new(G1).ScalarBaseMult(k), nil } func (g *G1) String() string { return "bn256.G1" + g.p.String() } // ScalarBaseMult sets e to g*k where g is the generator of the group and // then returns e. func (e *G1) ScalarBaseMult(k *big.Int) *G1 { if e.p == nil { e.p = newCurvePoint(nil) } e.p.Mul(curveGen, k, new(bnPool)) return e } // ScalarMult sets e to a*k and then returns e. func (e *G1) ScalarMult(a *G1, k *big.Int) *G1 { if e.p == nil { e.p = newCurvePoint(nil) } e.p.Mul(a.p, k, new(bnPool)) return e } // Add sets e to a+b and then returns e. // BUG(agl): this function is not complete: a==b fails. func (e *G1) Add(a, b *G1) *G1 { if e.p == nil { e.p = newCurvePoint(nil) } e.p.Add(a.p, b.p, new(bnPool)) return e } // Neg sets e to -a and then returns e. func (e *G1) Neg(a *G1) *G1 { if e.p == nil { e.p = newCurvePoint(nil) } e.p.Negative(a.p) return e } // Marshal converts n to a byte slice. func (n *G1) Marshal() []byte { n.p.MakeAffine(nil) xBytes := new(big.Int).Mod(n.p.x, p).Bytes() yBytes := new(big.Int).Mod(n.p.y, p).Bytes() // Each value is a 256-bit number. const numBytes = 256 / 8 ret := make([]byte, numBytes*2) copy(ret[1*numBytes-len(xBytes):], xBytes) copy(ret[2*numBytes-len(yBytes):], yBytes) return ret } // Unmarshal sets e to the result of converting the output of Marshal back into // a group element and then returns e. func (e *G1) Unmarshal(m []byte) (*G1, bool) { // Each value is a 256-bit number. const numBytes = 256 / 8 if len(m) != 2*numBytes { return nil, false } if e.p == nil { e.p = newCurvePoint(nil) } e.p.x.SetBytes(m[0*numBytes : 1*numBytes]) e.p.y.SetBytes(m[1*numBytes : 2*numBytes]) if e.p.x.Sign() == 0 && e.p.y.Sign() == 0 { // This is the point at infinity. e.p.y.SetInt64(1) e.p.z.SetInt64(0) e.p.t.SetInt64(0) } else { e.p.z.SetInt64(1) e.p.t.SetInt64(1) if !e.p.IsOnCurve() { return nil, false } } return e, true } // G2 is an abstract cyclic group. The zero value is suitable for use as the // output of an operation, but cannot be used as an input. type G2 struct { p *twistPoint } // RandomG1 returns x and gâ‚‚Ë£ where x is a random, non-zero number read from r. func RandomG2(r io.Reader) (*big.Int, *G2, error) { var k *big.Int var err error for { k, err = rand.Int(r, Order) if err != nil { return nil, nil, err } if k.Sign() > 0 { break } } return k, new(G2).ScalarBaseMult(k), nil } func (g *G2) String() string { return "bn256.G2" + g.p.String() } // ScalarBaseMult sets e to g*k where g is the generator of the group and // then returns out. func (e *G2) ScalarBaseMult(k *big.Int) *G2 { if e.p == nil { e.p = newTwistPoint(nil) } e.p.Mul(twistGen, k, new(bnPool)) return e } // ScalarMult sets e to a*k and then returns e. func (e *G2) ScalarMult(a *G2, k *big.Int) *G2 { if e.p == nil { e.p = newTwistPoint(nil) } e.p.Mul(a.p, k, new(bnPool)) return e } // Add sets e to a+b and then returns e. // BUG(agl): this function is not complete: a==b fails. func (e *G2) Add(a, b *G2) *G2 { if e.p == nil { e.p = newTwistPoint(nil) } e.p.Add(a.p, b.p, new(bnPool)) return e } // Marshal converts n into a byte slice. func (n *G2) Marshal() []byte { n.p.MakeAffine(nil) xxBytes := new(big.Int).Mod(n.p.x.x, p).Bytes() xyBytes := new(big.Int).Mod(n.p.x.y, p).Bytes() yxBytes := new(big.Int).Mod(n.p.y.x, p).Bytes() yyBytes := new(big.Int).Mod(n.p.y.y, p).Bytes() // Each value is a 256-bit number. const numBytes = 256 / 8 ret := make([]byte, numBytes*4) copy(ret[1*numBytes-len(xxBytes):], xxBytes) copy(ret[2*numBytes-len(xyBytes):], xyBytes) copy(ret[3*numBytes-len(yxBytes):], yxBytes) copy(ret[4*numBytes-len(yyBytes):], yyBytes) return ret } // Unmarshal sets e to the result of converting the output of Marshal back into // a group element and then returns e. func (e *G2) Unmarshal(m []byte) (*G2, bool) { // Each value is a 256-bit number. const numBytes = 256 / 8 if len(m) != 4*numBytes { return nil, false } if e.p == nil { e.p = newTwistPoint(nil) } e.p.x.x.SetBytes(m[0*numBytes : 1*numBytes]) e.p.x.y.SetBytes(m[1*numBytes : 2*numBytes]) e.p.y.x.SetBytes(m[2*numBytes : 3*numBytes]) e.p.y.y.SetBytes(m[3*numBytes : 4*numBytes]) if e.p.x.x.Sign() == 0 && e.p.x.y.Sign() == 0 && e.p.y.x.Sign() == 0 && e.p.y.y.Sign() == 0 { // This is the point at infinity. e.p.y.SetOne() e.p.z.SetZero() e.p.t.SetZero() } else { e.p.z.SetOne() e.p.t.SetOne() if !e.p.IsOnCurve() { return nil, false } } return e, true } // GT is an abstract cyclic group. The zero value is suitable for use as the // output of an operation, but cannot be used as an input. type GT struct { p *gfP12 } func (g *GT) String() string { return "bn256.GT" + g.p.String() } // ScalarMult sets e to a*k and then returns e. func (e *GT) ScalarMult(a *GT, k *big.Int) *GT { if e.p == nil { e.p = newGFp12(nil) } e.p.Exp(a.p, k, new(bnPool)) return e } // Add sets e to a+b and then returns e. func (e *GT) Add(a, b *GT) *GT { if e.p == nil { e.p = newGFp12(nil) } e.p.Mul(a.p, b.p, new(bnPool)) return e } // Neg sets e to -a and then returns e. func (e *GT) Neg(a *GT) *GT { if e.p == nil { e.p = newGFp12(nil) } e.p.Invert(a.p, new(bnPool)) return e } // Marshal converts n into a byte slice. func (n *GT) Marshal() []byte { n.p.Minimal() xxxBytes := n.p.x.x.x.Bytes() xxyBytes := n.p.x.x.y.Bytes() xyxBytes := n.p.x.y.x.Bytes() xyyBytes := n.p.x.y.y.Bytes() xzxBytes := n.p.x.z.x.Bytes() xzyBytes := n.p.x.z.y.Bytes() yxxBytes := n.p.y.x.x.Bytes() yxyBytes := n.p.y.x.y.Bytes() yyxBytes := n.p.y.y.x.Bytes() yyyBytes := n.p.y.y.y.Bytes() yzxBytes := n.p.y.z.x.Bytes() yzyBytes := n.p.y.z.y.Bytes() // Each value is a 256-bit number. const numBytes = 256 / 8 ret := make([]byte, numBytes*12) copy(ret[1*numBytes-len(xxxBytes):], xxxBytes) copy(ret[2*numBytes-len(xxyBytes):], xxyBytes) copy(ret[3*numBytes-len(xyxBytes):], xyxBytes) copy(ret[4*numBytes-len(xyyBytes):], xyyBytes) copy(ret[5*numBytes-len(xzxBytes):], xzxBytes) copy(ret[6*numBytes-len(xzyBytes):], xzyBytes) copy(ret[7*numBytes-len(yxxBytes):], yxxBytes) copy(ret[8*numBytes-len(yxyBytes):], yxyBytes) copy(ret[9*numBytes-len(yyxBytes):], yyxBytes) copy(ret[10*numBytes-len(yyyBytes):], yyyBytes) copy(ret[11*numBytes-len(yzxBytes):], yzxBytes) copy(ret[12*numBytes-len(yzyBytes):], yzyBytes) return ret } // Unmarshal sets e to the result of converting the output of Marshal back into // a group element and then returns e. func (e *GT) Unmarshal(m []byte) (*GT, bool) { // Each value is a 256-bit number. const numBytes = 256 / 8 if len(m) != 12*numBytes { return nil, false } if e.p == nil { e.p = newGFp12(nil) } e.p.x.x.x.SetBytes(m[0*numBytes : 1*numBytes]) e.p.x.x.y.SetBytes(m[1*numBytes : 2*numBytes]) e.p.x.y.x.SetBytes(m[2*numBytes : 3*numBytes]) e.p.x.y.y.SetBytes(m[3*numBytes : 4*numBytes]) e.p.x.z.x.SetBytes(m[4*numBytes : 5*numBytes]) e.p.x.z.y.SetBytes(m[5*numBytes : 6*numBytes]) e.p.y.x.x.SetBytes(m[6*numBytes : 7*numBytes]) e.p.y.x.y.SetBytes(m[7*numBytes : 8*numBytes]) e.p.y.y.x.SetBytes(m[8*numBytes : 9*numBytes]) e.p.y.y.y.SetBytes(m[9*numBytes : 10*numBytes]) e.p.y.z.x.SetBytes(m[10*numBytes : 11*numBytes]) e.p.y.z.y.SetBytes(m[11*numBytes : 12*numBytes]) return e, true } // Pair calculates an Optimal Ate pairing. func Pair(g1 *G1, g2 *G2) *GT { return &GT{optimalAte(g2.p, g1.p, new(bnPool))} } // bnPool implements a tiny cache of *big.Int objects that's used to reduce the // number of allocations made during processing. type bnPool struct { bns []*big.Int count int } func (pool *bnPool) Get() *big.Int { if pool == nil { return new(big.Int) } pool.count++ l := len(pool.bns) if l == 0 { return new(big.Int) } bn := pool.bns[l-1] pool.bns = pool.bns[:l-1] return bn } func (pool *bnPool) Put(bn *big.Int) { if pool == nil { return } pool.bns = append(pool.bns, bn) pool.count-- } func (pool *bnPool) Count() int { return pool.count } �����������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blowfish/���������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022667� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blowfish/const.go�������������������������������������������0000644�0610621�0607500�00000031514�13172163317�024350� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The startup permutation array and substitution boxes. // They are the hexadecimal digits of PI; see: // https://www.schneier.com/code/constants.txt. package blowfish var s0 = [256]uint32{ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, } var s1 = [256]uint32{ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, } var s2 = [256]uint32{ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, } var s3 = [256]uint32{ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6, } var p = [18]uint32{ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b, } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blowfish/cipher.go������������������������������������������0000644�0610621�0607500�00000006047�13172163317�024477� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package blowfish implements Bruce Schneier's Blowfish encryption algorithm. package blowfish // import "golang.org/x/crypto/blowfish" // The code is a port of Bruce Schneier's C implementation. // See https://www.schneier.com/blowfish.html. import "strconv" // The Blowfish block size in bytes. const BlockSize = 8 // A Cipher is an instance of Blowfish encryption using a particular key. type Cipher struct { p [18]uint32 s0, s1, s2, s3 [256]uint32 } type KeySizeError int func (k KeySizeError) Error() string { return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k)) } // NewCipher creates and returns a Cipher. // The key argument should be the Blowfish key, from 1 to 56 bytes. func NewCipher(key []byte) (*Cipher, error) { var result Cipher if k := len(key); k < 1 || k > 56 { return nil, KeySizeError(k) } initCipher(&result) ExpandKey(key, &result) return &result, nil } // NewSaltedCipher creates a returns a Cipher that folds a salt into its key // schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is // sufficient and desirable. For bcrypt compatibility, the key can be over 56 // bytes. func NewSaltedCipher(key, salt []byte) (*Cipher, error) { if len(salt) == 0 { return NewCipher(key) } var result Cipher if k := len(key); k < 1 { return nil, KeySizeError(k) } initCipher(&result) expandKeyWithSalt(key, salt, &result) return &result, nil } // BlockSize returns the Blowfish block size, 8 bytes. // It is necessary to satisfy the Block interface in the // package "crypto/cipher". func (c *Cipher) BlockSize() int { return BlockSize } // Encrypt encrypts the 8-byte buffer src using the key k // and stores the result in dst. // Note that for amounts of data larger than a block, // it is not safe to just call Encrypt on successive blocks; // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). func (c *Cipher) Encrypt(dst, src []byte) { l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) l, r = encryptBlock(l, r, c) dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) } // Decrypt decrypts the 8-byte buffer src using the key k // and stores the result in dst. func (c *Cipher) Decrypt(dst, src []byte) { l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) l, r = decryptBlock(l, r, c) dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) } func initCipher(c *Cipher) { copy(c.p[0:], p[0:]) copy(c.s0[0:], s0[0:]) copy(c.s1[0:], s1[0:]) copy(c.s2[0:], s2[0:]) copy(c.s3[0:], s3[0:]) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blowfish/blowfish_test.go�����������������������������������0000644�0610621�0607500�00000023726�13172163317�026104� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package blowfish import "testing" type CryptTest struct { key []byte in []byte out []byte } // Test vector values are from https://www.schneier.com/code/vectors.txt. var encryptTests = []CryptTest{ { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78}}, { []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, []byte{0x51, 0x86, 0x6F, 0xD5, 0xB8, 0x5E, 0xCB, 0x8A}}, { []byte{0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, []byte{0x7D, 0x85, 0x6F, 0x9A, 0x61, 0x30, 0x63, 0xF2}}, { []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, []byte{0x24, 0x66, 0xDD, 0x87, 0x8B, 0x96, 0x3C, 0x9D}}, { []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, []byte{0x61, 0xF9, 0xC3, 0x80, 0x22, 0x81, 0xB0, 0x96}}, { []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, []byte{0x7D, 0x0C, 0xC6, 0x30, 0xAF, 0xDA, 0x1E, 0xC7}}, { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78}}, { []byte{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}, []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, []byte{0x0A, 0xCE, 0xAB, 0x0F, 0xC6, 0xA0, 0xA2, 0x8D}}, { []byte{0x7C, 0xA1, 0x10, 0x45, 0x4A, 0x1A, 0x6E, 0x57}, []byte{0x01, 0xA1, 0xD6, 0xD0, 0x39, 0x77, 0x67, 0x42}, []byte{0x59, 0xC6, 0x82, 0x45, 0xEB, 0x05, 0x28, 0x2B}}, { []byte{0x01, 0x31, 0xD9, 0x61, 0x9D, 0xC1, 0x37, 0x6E}, []byte{0x5C, 0xD5, 0x4C, 0xA8, 0x3D, 0xEF, 0x57, 0xDA}, []byte{0xB1, 0xB8, 0xCC, 0x0B, 0x25, 0x0F, 0x09, 0xA0}}, { []byte{0x07, 0xA1, 0x13, 0x3E, 0x4A, 0x0B, 0x26, 0x86}, []byte{0x02, 0x48, 0xD4, 0x38, 0x06, 0xF6, 0x71, 0x72}, []byte{0x17, 0x30, 0xE5, 0x77, 0x8B, 0xEA, 0x1D, 0xA4}}, { []byte{0x38, 0x49, 0x67, 0x4C, 0x26, 0x02, 0x31, 0x9E}, []byte{0x51, 0x45, 0x4B, 0x58, 0x2D, 0xDF, 0x44, 0x0A}, []byte{0xA2, 0x5E, 0x78, 0x56, 0xCF, 0x26, 0x51, 0xEB}}, { []byte{0x04, 0xB9, 0x15, 0xBA, 0x43, 0xFE, 0xB5, 0xB6}, []byte{0x42, 0xFD, 0x44, 0x30, 0x59, 0x57, 0x7F, 0xA2}, []byte{0x35, 0x38, 0x82, 0xB1, 0x09, 0xCE, 0x8F, 0x1A}}, { []byte{0x01, 0x13, 0xB9, 0x70, 0xFD, 0x34, 0xF2, 0xCE}, []byte{0x05, 0x9B, 0x5E, 0x08, 0x51, 0xCF, 0x14, 0x3A}, []byte{0x48, 0xF4, 0xD0, 0x88, 0x4C, 0x37, 0x99, 0x18}}, { []byte{0x01, 0x70, 0xF1, 0x75, 0x46, 0x8F, 0xB5, 0xE6}, []byte{0x07, 0x56, 0xD8, 0xE0, 0x77, 0x47, 0x61, 0xD2}, []byte{0x43, 0x21, 0x93, 0xB7, 0x89, 0x51, 0xFC, 0x98}}, { []byte{0x43, 0x29, 0x7F, 0xAD, 0x38, 0xE3, 0x73, 0xFE}, []byte{0x76, 0x25, 0x14, 0xB8, 0x29, 0xBF, 0x48, 0x6A}, []byte{0x13, 0xF0, 0x41, 0x54, 0xD6, 0x9D, 0x1A, 0xE5}}, { []byte{0x07, 0xA7, 0x13, 0x70, 0x45, 0xDA, 0x2A, 0x16}, []byte{0x3B, 0xDD, 0x11, 0x90, 0x49, 0x37, 0x28, 0x02}, []byte{0x2E, 0xED, 0xDA, 0x93, 0xFF, 0xD3, 0x9C, 0x79}}, { []byte{0x04, 0x68, 0x91, 0x04, 0xC2, 0xFD, 0x3B, 0x2F}, []byte{0x26, 0x95, 0x5F, 0x68, 0x35, 0xAF, 0x60, 0x9A}, []byte{0xD8, 0x87, 0xE0, 0x39, 0x3C, 0x2D, 0xA6, 0xE3}}, { []byte{0x37, 0xD0, 0x6B, 0xB5, 0x16, 0xCB, 0x75, 0x46}, []byte{0x16, 0x4D, 0x5E, 0x40, 0x4F, 0x27, 0x52, 0x32}, []byte{0x5F, 0x99, 0xD0, 0x4F, 0x5B, 0x16, 0x39, 0x69}}, { []byte{0x1F, 0x08, 0x26, 0x0D, 0x1A, 0xC2, 0x46, 0x5E}, []byte{0x6B, 0x05, 0x6E, 0x18, 0x75, 0x9F, 0x5C, 0xCA}, []byte{0x4A, 0x05, 0x7A, 0x3B, 0x24, 0xD3, 0x97, 0x7B}}, { []byte{0x58, 0x40, 0x23, 0x64, 0x1A, 0xBA, 0x61, 0x76}, []byte{0x00, 0x4B, 0xD6, 0xEF, 0x09, 0x17, 0x60, 0x62}, []byte{0x45, 0x20, 0x31, 0xC1, 0xE4, 0xFA, 0xDA, 0x8E}}, { []byte{0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xB0, 0x07}, []byte{0x48, 0x0D, 0x39, 0x00, 0x6E, 0xE7, 0x62, 0xF2}, []byte{0x75, 0x55, 0xAE, 0x39, 0xF5, 0x9B, 0x87, 0xBD}}, { []byte{0x49, 0x79, 0x3E, 0xBC, 0x79, 0xB3, 0x25, 0x8F}, []byte{0x43, 0x75, 0x40, 0xC8, 0x69, 0x8F, 0x3C, 0xFA}, []byte{0x53, 0xC5, 0x5F, 0x9C, 0xB4, 0x9F, 0xC0, 0x19}}, { []byte{0x4F, 0xB0, 0x5E, 0x15, 0x15, 0xAB, 0x73, 0xA7}, []byte{0x07, 0x2D, 0x43, 0xA0, 0x77, 0x07, 0x52, 0x92}, []byte{0x7A, 0x8E, 0x7B, 0xFA, 0x93, 0x7E, 0x89, 0xA3}}, { []byte{0x49, 0xE9, 0x5D, 0x6D, 0x4C, 0xA2, 0x29, 0xBF}, []byte{0x02, 0xFE, 0x55, 0x77, 0x81, 0x17, 0xF1, 0x2A}, []byte{0xCF, 0x9C, 0x5D, 0x7A, 0x49, 0x86, 0xAD, 0xB5}}, { []byte{0x01, 0x83, 0x10, 0xDC, 0x40, 0x9B, 0x26, 0xD6}, []byte{0x1D, 0x9D, 0x5C, 0x50, 0x18, 0xF7, 0x28, 0xC2}, []byte{0xD1, 0xAB, 0xB2, 0x90, 0x65, 0x8B, 0xC7, 0x78}}, { []byte{0x1C, 0x58, 0x7F, 0x1C, 0x13, 0x92, 0x4F, 0xEF}, []byte{0x30, 0x55, 0x32, 0x28, 0x6D, 0x6F, 0x29, 0x5A}, []byte{0x55, 0xCB, 0x37, 0x74, 0xD1, 0x3E, 0xF2, 0x01}}, { []byte{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, []byte{0xFA, 0x34, 0xEC, 0x48, 0x47, 0xB2, 0x68, 0xB2}}, { []byte{0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E}, []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, []byte{0xA7, 0x90, 0x79, 0x51, 0x08, 0xEA, 0x3C, 0xAE}}, { []byte{0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE}, []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, []byte{0xC3, 0x9E, 0x07, 0x2D, 0x9F, 0xAC, 0x63, 0x1D}}, { []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, []byte{0x01, 0x49, 0x33, 0xE0, 0xCD, 0xAF, 0xF6, 0xE4}}, { []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0xF2, 0x1E, 0x9A, 0x77, 0xB7, 0x1C, 0x49, 0xBC}}, { []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x24, 0x59, 0x46, 0x88, 0x57, 0x54, 0x36, 0x9A}}, { []byte{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}, []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, []byte{0x6B, 0x5C, 0x5A, 0x9C, 0x5D, 0x9E, 0x0A, 0x5A}}, } func TestCipherEncrypt(t *testing.T) { for i, tt := range encryptTests { c, err := NewCipher(tt.key) if err != nil { t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err) continue } ct := make([]byte, len(tt.out)) c.Encrypt(ct, tt.in) for j, v := range ct { if v != tt.out[j] { t.Errorf("Cipher.Encrypt, test vector #%d: cipher-text[%d] = %#x, expected %#x", i, j, v, tt.out[j]) break } } } } func TestCipherDecrypt(t *testing.T) { for i, tt := range encryptTests { c, err := NewCipher(tt.key) if err != nil { t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err) continue } pt := make([]byte, len(tt.in)) c.Decrypt(pt, tt.out) for j, v := range pt { if v != tt.in[j] { t.Errorf("Cipher.Decrypt, test vector #%d: plain-text[%d] = %#x, expected %#x", i, j, v, tt.in[j]) break } } } } func TestSaltedCipherKeyLength(t *testing.T) { if _, err := NewSaltedCipher(nil, []byte{'a'}); err != KeySizeError(0) { t.Errorf("NewSaltedCipher with short key, gave error %#v, expected %#v", err, KeySizeError(0)) } // A 57-byte key. One over the typical blowfish restriction. key := []byte("012345678901234567890123456789012345678901234567890123456") if _, err := NewSaltedCipher(key, []byte{'a'}); err != nil { t.Errorf("NewSaltedCipher with long key, gave error %#v", err) } } // Test vectors generated with Blowfish from OpenSSH. var saltedVectors = [][8]byte{ {0x0c, 0x82, 0x3b, 0x7b, 0x8d, 0x01, 0x4b, 0x7e}, {0xd1, 0xe1, 0x93, 0xf0, 0x70, 0xa6, 0xdb, 0x12}, {0xfc, 0x5e, 0xba, 0xde, 0xcb, 0xf8, 0x59, 0xad}, {0x8a, 0x0c, 0x76, 0xe7, 0xdd, 0x2c, 0xd3, 0xa8}, {0x2c, 0xcb, 0x7b, 0xee, 0xac, 0x7b, 0x7f, 0xf8}, {0xbb, 0xf6, 0x30, 0x6f, 0xe1, 0x5d, 0x62, 0xbf}, {0x97, 0x1e, 0xc1, 0x3d, 0x3d, 0xe0, 0x11, 0xe9}, {0x06, 0xd7, 0x4d, 0xb1, 0x80, 0xa3, 0xb1, 0x38}, {0x67, 0xa1, 0xa9, 0x75, 0x0e, 0x5b, 0xc6, 0xb4}, {0x51, 0x0f, 0x33, 0x0e, 0x4f, 0x67, 0xd2, 0x0c}, {0xf1, 0x73, 0x7e, 0xd8, 0x44, 0xea, 0xdb, 0xe5}, {0x14, 0x0e, 0x16, 0xce, 0x7f, 0x4a, 0x9c, 0x7b}, {0x4b, 0xfe, 0x43, 0xfd, 0xbf, 0x36, 0x04, 0x47}, {0xb1, 0xeb, 0x3e, 0x15, 0x36, 0xa7, 0xbb, 0xe2}, {0x6d, 0x0b, 0x41, 0xdd, 0x00, 0x98, 0x0b, 0x19}, {0xd3, 0xce, 0x45, 0xce, 0x1d, 0x56, 0xb7, 0xfc}, {0xd9, 0xf0, 0xfd, 0xda, 0xc0, 0x23, 0xb7, 0x93}, {0x4c, 0x6f, 0xa1, 0xe4, 0x0c, 0xa8, 0xca, 0x57}, {0xe6, 0x2f, 0x28, 0xa7, 0x0c, 0x94, 0x0d, 0x08}, {0x8f, 0xe3, 0xf0, 0xb6, 0x29, 0xe3, 0x44, 0x03}, {0xff, 0x98, 0xdd, 0x04, 0x45, 0xb4, 0x6d, 0x1f}, {0x9e, 0x45, 0x4d, 0x18, 0x40, 0x53, 0xdb, 0xef}, {0xb7, 0x3b, 0xef, 0x29, 0xbe, 0xa8, 0x13, 0x71}, {0x02, 0x54, 0x55, 0x41, 0x8e, 0x04, 0xfc, 0xad}, {0x6a, 0x0a, 0xee, 0x7c, 0x10, 0xd9, 0x19, 0xfe}, {0x0a, 0x22, 0xd9, 0x41, 0xcc, 0x23, 0x87, 0x13}, {0x6e, 0xff, 0x1f, 0xff, 0x36, 0x17, 0x9c, 0xbe}, {0x79, 0xad, 0xb7, 0x40, 0xf4, 0x9f, 0x51, 0xa6}, {0x97, 0x81, 0x99, 0xa4, 0xde, 0x9e, 0x9f, 0xb6}, {0x12, 0x19, 0x7a, 0x28, 0xd0, 0xdc, 0xcc, 0x92}, {0x81, 0xda, 0x60, 0x1e, 0x0e, 0xdd, 0x65, 0x56}, {0x7d, 0x76, 0x20, 0xb2, 0x73, 0xc9, 0x9e, 0xee}, } func TestSaltedCipher(t *testing.T) { var key, salt [32]byte for i := range key { key[i] = byte(i) salt[i] = byte(i + 32) } for i, v := range saltedVectors { c, err := NewSaltedCipher(key[:], salt[:i]) if err != nil { t.Fatal(err) } var buf [8]byte c.Encrypt(buf[:], buf[:]) if v != buf { t.Errorf("%d: expected %x, got %x", i, v, buf) } } } func BenchmarkExpandKeyWithSalt(b *testing.B) { key := make([]byte, 32) salt := make([]byte, 16) c, _ := NewCipher(key) for i := 0; i < b.N; i++ { expandKeyWithSalt(key, salt, c) } } func BenchmarkExpandKey(b *testing.B) { key := make([]byte, 32) c, _ := NewCipher(key) for i := 0; i < b.N; i++ { ExpandKey(key, c) } } ������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blowfish/block.go�������������������������������������������0000644�0610621�0607500�00000014021�13172163317�024306� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package blowfish // getNextWord returns the next big-endian uint32 value from the byte slice // at the given position in a circular manner, updating the position. func getNextWord(b []byte, pos *int) uint32 { var w uint32 j := *pos for i := 0; i < 4; i++ { w = w<<8 | uint32(b[j]) j++ if j >= len(b) { j = 0 } } *pos = j return w } // ExpandKey performs a key expansion on the given *Cipher. Specifically, it // performs the Blowfish algorithm's key schedule which sets up the *Cipher's // pi and substitution tables for calls to Encrypt. This is used, primarily, // by the bcrypt package to reuse the Blowfish key schedule during its // set up. It's unlikely that you need to use this directly. func ExpandKey(key []byte, c *Cipher) { j := 0 for i := 0; i < 18; i++ { // Using inlined getNextWord for performance. var d uint32 for k := 0; k < 4; k++ { d = d<<8 | uint32(key[j]) j++ if j >= len(key) { j = 0 } } c.p[i] ^= d } var l, r uint32 for i := 0; i < 18; i += 2 { l, r = encryptBlock(l, r, c) c.p[i], c.p[i+1] = l, r } for i := 0; i < 256; i += 2 { l, r = encryptBlock(l, r, c) c.s0[i], c.s0[i+1] = l, r } for i := 0; i < 256; i += 2 { l, r = encryptBlock(l, r, c) c.s1[i], c.s1[i+1] = l, r } for i := 0; i < 256; i += 2 { l, r = encryptBlock(l, r, c) c.s2[i], c.s2[i+1] = l, r } for i := 0; i < 256; i += 2 { l, r = encryptBlock(l, r, c) c.s3[i], c.s3[i+1] = l, r } } // This is similar to ExpandKey, but folds the salt during the key // schedule. While ExpandKey is essentially expandKeyWithSalt with an all-zero // salt passed in, reusing ExpandKey turns out to be a place of inefficiency // and specializing it here is useful. func expandKeyWithSalt(key []byte, salt []byte, c *Cipher) { j := 0 for i := 0; i < 18; i++ { c.p[i] ^= getNextWord(key, &j) } j = 0 var l, r uint32 for i := 0; i < 18; i += 2 { l ^= getNextWord(salt, &j) r ^= getNextWord(salt, &j) l, r = encryptBlock(l, r, c) c.p[i], c.p[i+1] = l, r } for i := 0; i < 256; i += 2 { l ^= getNextWord(salt, &j) r ^= getNextWord(salt, &j) l, r = encryptBlock(l, r, c) c.s0[i], c.s0[i+1] = l, r } for i := 0; i < 256; i += 2 { l ^= getNextWord(salt, &j) r ^= getNextWord(salt, &j) l, r = encryptBlock(l, r, c) c.s1[i], c.s1[i+1] = l, r } for i := 0; i < 256; i += 2 { l ^= getNextWord(salt, &j) r ^= getNextWord(salt, &j) l, r = encryptBlock(l, r, c) c.s2[i], c.s2[i+1] = l, r } for i := 0; i < 256; i += 2 { l ^= getNextWord(salt, &j) r ^= getNextWord(salt, &j) l, r = encryptBlock(l, r, c) c.s3[i], c.s3[i+1] = l, r } } func encryptBlock(l, r uint32, c *Cipher) (uint32, uint32) { xl, xr := l, r xl ^= c.p[0] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[1] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[2] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[3] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[4] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[5] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[6] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[7] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[8] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[9] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[10] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[11] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[12] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[13] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[14] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[15] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[16] xr ^= c.p[17] return xr, xl } func decryptBlock(l, r uint32, c *Cipher) (uint32, uint32) { xl, xr := l, r xl ^= c.p[17] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[16] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[15] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[14] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[13] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[12] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[11] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[10] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[9] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[8] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[7] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[6] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[5] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[4] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[3] xr ^= ((c.s0[byte(xl>>24)] + c.s1[byte(xl>>16)]) ^ c.s2[byte(xl>>8)]) + c.s3[byte(xl)] ^ c.p[2] xl ^= ((c.s0[byte(xr>>24)] + c.s1[byte(xr>>16)]) ^ c.s2[byte(xr>>8)]) + c.s3[byte(xr)] ^ c.p[1] xr ^= c.p[0] return xr, xl } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022375� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/register.go�����������������������������������������0000644�0610621�0607500�00000000554�13172163317�024554� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package blake2s import ( "crypto" "hash" ) func init() { newHash256 := func() hash.Hash { h, _ := New256(nil) return h } crypto.RegisterHash(crypto.BLAKE2s_256, newHash256) } ����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2x.go������������������������������������������0000644�0610621�0607500�00000010034�13172163317�024252� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package blake2s import ( "encoding/binary" "errors" "io" ) // XOF defines the interface to hash functions that // support arbitrary-length output. type XOF interface { // Write absorbs more data into the hash's state. It panics if called // after Read. io.Writer // Read reads more output from the hash. It returns io.EOF if the limit // has been reached. io.Reader // Clone returns a copy of the XOF in its current state. Clone() XOF // Reset resets the XOF to its initial state. Reset() } // OutputLengthUnknown can be used as the size argument to NewXOF to indicate // the the length of the output is not known in advance. const OutputLengthUnknown = 0 // magicUnknownOutputLength is a magic value for the output size that indicates // an unknown number of output bytes. const magicUnknownOutputLength = 65535 // maxOutputLength is the absolute maximum number of bytes to produce when the // number of output bytes is unknown. const maxOutputLength = (1 << 32) * 32 // NewXOF creates a new variable-output-length hash. The hash either produce a // known number of bytes (1 <= size < 65535), or an unknown number of bytes // (size == OutputLengthUnknown). In the latter case, an absolute limit of // 128GiB applies. // // A non-nil key turns the hash into a MAC. The key must between // zero and 32 bytes long. func NewXOF(size uint16, key []byte) (XOF, error) { if len(key) > Size { return nil, errKeySize } if size == magicUnknownOutputLength { // 2^16-1 indicates an unknown number of bytes and thus isn't a // valid length. return nil, errors.New("blake2s: XOF length too large") } if size == OutputLengthUnknown { size = magicUnknownOutputLength } x := &xof{ d: digest{ size: Size, keyLen: len(key), }, length: size, } copy(x.d.key[:], key) x.Reset() return x, nil } type xof struct { d digest length uint16 remaining uint64 cfg, root, block [Size]byte offset int nodeOffset uint32 readMode bool } func (x *xof) Write(p []byte) (n int, err error) { if x.readMode { panic("blake2s: write to XOF after read") } return x.d.Write(p) } func (x *xof) Clone() XOF { clone := *x return &clone } func (x *xof) Reset() { x.cfg[0] = byte(Size) binary.LittleEndian.PutUint32(x.cfg[4:], uint32(Size)) // leaf length binary.LittleEndian.PutUint16(x.cfg[12:], x.length) // XOF length x.cfg[15] = byte(Size) // inner hash size x.d.Reset() x.d.h[3] ^= uint32(x.length) x.remaining = uint64(x.length) if x.remaining == magicUnknownOutputLength { x.remaining = maxOutputLength } x.offset, x.nodeOffset = 0, 0 x.readMode = false } func (x *xof) Read(p []byte) (n int, err error) { if !x.readMode { x.d.finalize(&x.root) x.readMode = true } if x.remaining == 0 { return 0, io.EOF } n = len(p) if uint64(n) > x.remaining { n = int(x.remaining) p = p[:n] } if x.offset > 0 { blockRemaining := Size - x.offset if n < blockRemaining { x.offset += copy(p, x.block[x.offset:]) x.remaining -= uint64(n) return } copy(p, x.block[x.offset:]) p = p[blockRemaining:] x.offset = 0 x.remaining -= uint64(blockRemaining) } for len(p) >= Size { binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) x.nodeOffset++ x.d.initConfig(&x.cfg) x.d.Write(x.root[:]) x.d.finalize(&x.block) copy(p, x.block[:]) p = p[Size:] x.remaining -= uint64(Size) } if todo := len(p); todo > 0 { if x.remaining < uint64(Size) { x.cfg[0] = byte(x.remaining) } binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) x.nodeOffset++ x.d.initConfig(&x.cfg) x.d.Write(x.root[:]) x.d.finalize(&x.block) x.offset = copy(p, x.block[:todo]) x.remaining -= uint64(todo) } return } func (d *digest) initConfig(cfg *[Size]byte) { d.offset, d.c[0], d.c[1] = 0, 0, 0 for i := range d.h { d.h[i] = iv[i] ^ binary.LittleEndian.Uint32(cfg[i*4:]) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2s_test.go�������������������������������������0000644�0610621�0607500�00000302605�13172163317�025314� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package blake2s import ( "encoding/hex" "fmt" "testing" ) func TestHashes(t *testing.T) { defer func(sse2, ssse3, sse4 bool) { useSSE2, useSSSE3, useSSE4 = sse2, ssse3, sse4 }(useSSE2, useSSSE3, useSSE4) if useSSE4 { t.Log("SSE4 version") testHashes(t) testHashes128(t) useSSE4 = false } if useSSSE3 { t.Log("SSSE3 version") testHashes(t) testHashes128(t) useSSSE3 = false } if useSSE2 { t.Log("SSE2 version") testHashes(t) testHashes128(t) useSSE2 = false } t.Log("generic version") testHashes(t) testHashes128(t) } func TestHashes2X(t *testing.T) { defer func(sse2, ssse3, sse4 bool) { useSSE2, useSSSE3, useSSE4 = sse2, ssse3, sse4 }(useSSE2, useSSSE3, useSSE4) if useSSE4 { t.Log("SSE4 version") testHashes2X(t) useSSE4 = false } if useSSSE3 { t.Log("SSSE3 version") testHashes2X(t) useSSSE3 = false } if useSSE2 { t.Log("SSE2 version") testHashes2X(t) useSSE2 = false } t.Log("generic version") testHashes2X(t) } func testHashes(t *testing.T) { key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f") input := make([]byte, 255) for i := range input { input[i] = byte(i) } for i, expectedHex := range hashes { h, err := New256(key) if err != nil { t.Fatalf("#%d: error from New256: %v", i, err) } h.Write(input[:i]) sum := h.Sum(nil) if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (single write): got %s, wanted %s", i, gotHex, expectedHex) } h.Reset() for j := 0; j < i; j++ { h.Write(input[j : j+1]) } sum = h.Sum(sum[:0]) if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (byte-by-byte): got %s, wanted %s", i, gotHex, expectedHex) } } } func testHashes128(t *testing.T) { key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f") input := make([]byte, 255) for i := range input { input[i] = byte(i) } for i, expectedHex := range hashes128 { h, err := New128(key) if err != nil { t.Fatalf("#%d: error from New128: %v", i, err) } h.Write(input[:i]) sum := h.Sum(nil) if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (single write): got %s, wanted %s", i, gotHex, expectedHex) } h.Reset() for j := 0; j < i; j++ { h.Write(input[j : j+1]) } sum = h.Sum(sum[:0]) if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (byte-by-byte): got %s, wanted %s", i, gotHex, expectedHex) } } } func testHashes2X(t *testing.T) { key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f") input := make([]byte, 256) for i := range input { input[i] = byte(i) } for i, expectedHex := range hashes2X { length := uint16(len(expectedHex) / 2) sum := make([]byte, int(length)) h, err := NewXOF(length, key) if err != nil { t.Fatalf("#%d: error from NewXOF: %v", i, err) } if _, err := h.Write(input); err != nil { t.Fatalf("#%d (single write): error from Write: %v", i, err) } if _, err := h.Read(sum); err != nil { t.Fatalf("#%d (single write): error from Read: %v", i, err) } if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (single write): got %s, wanted %s", i, gotHex, expectedHex) } h.Reset() for j := 0; j < len(input); j++ { h.Write(input[j : j+1]) } for j := 0; j < len(sum); j++ { h = h.Clone() if _, err := h.Read(sum[j : j+1]); err != nil { t.Fatalf("#%d (byte-by-byte) - Read %d: error from Read: %v", i, j, err) } } if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (byte-by-byte): got %s, wanted %s", i, gotHex, expectedHex) } } h, err := NewXOF(OutputLengthUnknown, key) if err != nil { t.Fatalf("#unknown length: error from NewXOF: %v", err) } if _, err := h.Write(input); err != nil { t.Fatalf("#unknown length: error from Write: %v", err) } var result [64]byte if n, err := h.Read(result[:]); err != nil { t.Fatalf("#unknown length: error from Read: %v", err) } else if n != len(result) { t.Fatalf("#unknown length: Read returned %d bytes, want %d: %v", n, len(result)) } const expected = "2a9a6977d915a2c4dd07dbcafe1918bf1682e56d9c8e567ecd19bfd7cd93528833c764d12b34a5e2a219c9fd463dab45e972c5574d73f45de5b2e23af72530d8" if fmt.Sprintf("%x", result) != expected { t.Fatalf("#unknown length: bad result %x, wanted %s", result, expected) } } // Benchmarks func benchmarkSum(b *testing.B, size int) { data := make([]byte, size) b.SetBytes(int64(size)) b.ResetTimer() for i := 0; i < b.N; i++ { Sum256(data) } } func benchmarkWrite(b *testing.B, size int) { data := make([]byte, size) h, _ := New256(nil) b.SetBytes(int64(size)) b.ResetTimer() for i := 0; i < b.N; i++ { h.Write(data) } } func BenchmarkWrite64(b *testing.B) { benchmarkWrite(b, 64) } func BenchmarkWrite1K(b *testing.B) { benchmarkWrite(b, 1024) } func BenchmarkSum64(b *testing.B) { benchmarkSum(b, 64) } func BenchmarkSum1K(b *testing.B) { benchmarkSum(b, 1024) } // hashes is taken from https://blake2.net/blake2s-test.txt var hashes = []string{ "48a8997da407876b3d79c0d92325ad3b89cbb754d86ab71aee047ad345fd2c49", "40d15fee7c328830166ac3f918650f807e7e01e177258cdc0a39b11f598066f1", "6bb71300644cd3991b26ccd4d274acd1adeab8b1d7914546c1198bbe9fc9d803", "1d220dbe2ee134661fdf6d9e74b41704710556f2f6e5a091b227697445dbea6b", "f6c3fbadb4cc687a0064a5be6e791bec63b868ad62fba61b3757ef9ca52e05b2", "49c1f21188dfd769aea0e911dd6b41f14dab109d2b85977aa3088b5c707e8598", "fdd8993dcd43f696d44f3cea0ff35345234ec8ee083eb3cada017c7f78c17143", "e6c8125637438d0905b749f46560ac89fd471cf8692e28fab982f73f019b83a9", "19fc8ca6979d60e6edd3b4541e2f967ced740df6ec1eaebbfe813832e96b2974", "a6ad777ce881b52bb5a4421ab6cdd2dfba13e963652d4d6d122aee46548c14a7", "f5c4b2ba1a00781b13aba0425242c69cb1552f3f71a9a3bb22b4a6b4277b46dd", "e33c4c9bd0cc7e45c80e65c77fa5997fec7002738541509e68a9423891e822a3", "fba16169b2c3ee105be6e1e650e5cbf40746b6753d036ab55179014ad7ef6651", "f5c4bec6d62fc608bf41cc115f16d61c7efd3ff6c65692bbe0afffb1fede7475", "a4862e76db847f05ba17ede5da4e7f91b5925cf1ad4ba12732c3995742a5cd6e", "65f4b860cd15b38ef814a1a804314a55be953caa65fd758ad989ff34a41c1eea", "19ba234f0a4f38637d1839f9d9f76ad91c8522307143c97d5f93f69274cec9a7", "1a67186ca4a5cb8e65fca0e2ecbc5ddc14ae381bb8bffeb9e0a103449e3ef03c", "afbea317b5a2e89c0bd90ccf5d7fd0ed57fe585e4be3271b0a6bf0f5786b0f26", "f1b01558ce541262f5ec34299d6fb4090009e3434be2f49105cf46af4d2d4124", "13a0a0c86335635eaa74ca2d5d488c797bbb4f47dc07105015ed6a1f3309efce", "1580afeebebb346f94d59fe62da0b79237ead7b1491f5667a90e45edf6ca8b03", "20be1a875b38c573dd7faaa0de489d655c11efb6a552698e07a2d331b5f655c3", "be1fe3c4c04018c54c4a0f6b9a2ed3c53abe3a9f76b4d26de56fc9ae95059a99", "e3e3ace537eb3edd8463d9ad3582e13cf86533ffde43d668dd2e93bbdbd7195a", "110c50c0bf2c6e7aeb7e435d92d132ab6655168e78a2decdec3330777684d9c1", "e9ba8f505c9c80c08666a701f3367e6cc665f34b22e73c3c0417eb1c2206082f", "26cd66fca02379c76df12317052bcafd6cd8c3a7b890d805f36c49989782433a", "213f3596d6e3a5d0e9932cd2159146015e2abc949f4729ee2632fe1edb78d337", "1015d70108e03be1c702fe97253607d14aee591f2413ea6787427b6459ff219a", "3ca989de10cfe609909472c8d35610805b2f977734cf652cc64b3bfc882d5d89", "b6156f72d380ee9ea6acd190464f2307a5c179ef01fd71f99f2d0f7a57360aea", "c03bc642b20959cbe133a0303e0c1abff3e31ec8e1a328ec8565c36decff5265", "2c3e08176f760c6264c3a2cd66fec6c3d78de43fc192457b2a4a660a1e0eb22b", "f738c02f3c1b190c512b1a32deabf353728e0e9ab034490e3c3409946a97aeec", "8b1880df301cc963418811088964839287ff7fe31c49ea6ebd9e48bdeee497c5", "1e75cb21c60989020375f1a7a242839f0b0b68973a4c2a05cf7555ed5aaec4c1", "62bf8a9c32a5bccf290b6c474d75b2a2a4093f1a9e27139433a8f2b3bce7b8d7", "166c8350d3173b5e702b783dfd33c66ee0432742e9b92b997fd23c60dc6756ca", "044a14d822a90cacf2f5a101428adc8f4109386ccb158bf905c8618b8ee24ec3", "387d397ea43a994be84d2d544afbe481a2000f55252696bba2c50c8ebd101347", "56f8ccf1f86409b46ce36166ae9165138441577589db08cbc5f66ca29743b9fd", "9706c092b04d91f53dff91fa37b7493d28b576b5d710469df79401662236fc03", "877968686c068ce2f7e2adcff68bf8748edf3cf862cfb4d3947a3106958054e3", "8817e5719879acf7024787eccdb271035566cfa333e049407c0178ccc57a5b9f", "8938249e4b50cadaccdf5b18621326cbb15253e33a20f5636e995d72478de472", "f164abba4963a44d107257e3232d90aca5e66a1408248c51741e991db5227756", "d05563e2b1cba0c4a2a1e8bde3a1a0d9f5b40c85a070d6f5fb21066ead5d0601", "03fbb16384f0a3866f4c3117877666efbf124597564b293d4aab0d269fabddfa", "5fa8486ac0e52964d1881bbe338eb54be2f719549224892057b4da04ba8b3475", "cdfabcee46911111236a31708b2539d71fc211d9b09c0d8530a11e1dbf6eed01", "4f82de03b9504793b82a07a0bdcdff314d759e7b62d26b784946b0d36f916f52", "259ec7f173bcc76a0994c967b4f5f024c56057fb79c965c4fae41875f06a0e4c", "193cc8e7c3e08bb30f5437aa27ade1f142369b246a675b2383e6da9b49a9809e", "5c10896f0e2856b2a2eee0fe4a2c1633565d18f0e93e1fab26c373e8f829654d", "f16012d93f28851a1eb989f5d0b43f3f39ca73c9a62d5181bff237536bd348c3", "2966b3cfae1e44ea996dc5d686cf25fa053fb6f67201b9e46eade85d0ad6b806", "ddb8782485e900bc60bcf4c33a6fd585680cc683d516efa03eb9985fad8715fb", "4c4d6e71aea05786413148fc7a786b0ecaf582cff1209f5a809fba8504ce662c", "fb4c5e86d7b2229b99b8ba6d94c247ef964aa3a2bae8edc77569f28dbbff2d4e", "e94f526de9019633ecd54ac6120f23958d7718f1e7717bf329211a4faeed4e6d", "cbd6660a10db3f23f7a03d4b9d4044c7932b2801ac89d60bc9eb92d65a46c2a0", "8818bbd3db4dc123b25cbba5f54c2bc4b3fcf9bf7d7a7709f4ae588b267c4ece", "c65382513f07460da39833cb666c5ed82e61b9e998f4b0c4287cee56c3cc9bcd", "8975b0577fd35566d750b362b0897a26c399136df07bababbde6203ff2954ed4", "21fe0ceb0052be7fb0f004187cacd7de67fa6eb0938d927677f2398c132317a8", "2ef73f3c26f12d93889f3c78b6a66c1d52b649dc9e856e2c172ea7c58ac2b5e3", "388a3cd56d73867abb5f8401492b6e2681eb69851e767fd84210a56076fb3dd3", "af533e022fc9439e4e3cb838ecd18692232adf6fe9839526d3c3dd1b71910b1a", "751c09d41a9343882a81cd13ee40818d12eb44c6c7f40df16e4aea8fab91972a", "5b73ddb68d9d2b0aa265a07988d6b88ae9aac582af83032f8a9b21a2e1b7bf18", "3da29126c7c5d7f43e64242a79feaa4ef3459cdeccc898ed59a97f6ec93b9dab", "566dc920293da5cb4fe0aa8abda8bbf56f552313bff19046641e3615c1e3ed3f", "4115bea02f73f97f629e5c5590720c01e7e449ae2a6697d4d2783321303692f9", "4ce08f4762468a7670012164878d68340c52a35e66c1884d5c864889abc96677", "81ea0b7804124e0c22ea5fc71104a2afcb52a1fa816f3ecb7dcb5d9dea1786d0", "fe362733b05f6bedaf9379d7f7936ede209b1f8323c3922549d9e73681b5db7b", "eff37d30dfd20359be4e73fdf40d27734b3df90a97a55ed745297294ca85d09f", "172ffc67153d12e0ca76a8b6cd5d4731885b39ce0cac93a8972a18006c8b8baf", "c47957f1cc88e83ef9445839709a480a036bed5f88ac0fcc8e1e703ffaac132c", "30f3548370cfdceda5c37b569b6175e799eef1a62aaa943245ae7669c227a7b5", "c95dcb3cf1f27d0eef2f25d2413870904a877c4a56c2de1e83e2bc2ae2e46821", "d5d0b5d705434cd46b185749f66bfb5836dcdf6ee549a2b7a4aee7f58007caaf", "bbc124a712f15d07c300e05b668389a439c91777f721f8320c1c9078066d2c7e", "a451b48c35a6c7854cfaae60262e76990816382ac0667e5a5c9e1b46c4342ddf", "b0d150fb55e778d01147f0b5d89d99ecb20ff07e5e6760d6b645eb5b654c622b", "34f737c0ab219951eee89a9f8dac299c9d4c38f33fa494c5c6eefc92b6db08bc", "1a62cc3a00800dcbd99891080c1e098458193a8cc9f970ea99fbeff00318c289", "cfce55ebafc840d7ae48281c7fd57ec8b482d4b704437495495ac414cf4a374b", "6746facf71146d999dabd05d093ae586648d1ee28e72617b99d0f0086e1e45bf", "571ced283b3f23b4e750bf12a2caf1781847bd890e43603cdc5976102b7bb11b", "cfcb765b048e35022c5d089d26e85a36b005a2b80493d03a144e09f409b6afd1", "4050c7a27705bb27f42089b299f3cbe5054ead68727e8ef9318ce6f25cd6f31d", "184070bd5d265fbdc142cd1c5cd0d7e414e70369a266d627c8fba84fa5e84c34", "9edda9a4443902a9588c0d0ccc62b930218479a6841e6fe7d43003f04b1fd643", "e412feef7908324a6da1841629f35d3d358642019310ec57c614836b63d30763", "1a2b8edff3f9acc1554fcbae3cf1d6298c6462e22e5eb0259684f835012bd13f", "288c4ad9b9409762ea07c24a41f04f69a7d74bee2d95435374bde946d7241c7b", "805691bb286748cfb591d3aebe7e6f4e4dc6e2808c65143cc004e4eb6fd09d43", "d4ac8d3a0afc6cfa7b460ae3001baeb36dadb37da07d2e8ac91822df348aed3d", "c376617014d20158bced3d3ba552b6eccf84e62aa3eb650e90029c84d13eea69", "c41f09f43cecae7293d6007ca0a357087d5ae59be500c1cd5b289ee810c7b082", "03d1ced1fba5c39155c44b7765cb760c78708dcfc80b0bd8ade3a56da8830b29", "09bde6f152218dc92c41d7f45387e63e5869d807ec70b821405dbd884b7fcf4b", "71c9036e18179b90b37d39e9f05eb89cc5fc341fd7c477d0d7493285faca08a4", "5916833ebb05cd919ca7fe83b692d3205bef72392b2cf6bb0a6d43f994f95f11", "f63aab3ec641b3b024964c2b437c04f6043c4c7e0279239995401958f86bbe54", "f172b180bfb09740493120b6326cbdc561e477def9bbcfd28cc8c1c5e3379a31", "cb9b89cc18381dd9141ade588654d4e6a231d5bf49d4d59ac27d869cbe100cf3", "7bd8815046fdd810a923e1984aaebdcdf84d87c8992d68b5eeb460f93eb3c8d7", "607be66862fd08ee5b19facac09dfdbcd40c312101d66e6ebd2b841f1b9a9325", "9fe03bbe69ab1834f5219b0da88a08b30a66c5913f0151963c360560db0387b3", "90a83585717b75f0e9b725e055eeeeb9e7a028ea7e6cbc07b20917ec0363e38c", "336ea0530f4a7469126e0218587ebbde3358a0b31c29d200f7dc7eb15c6aadd8", "a79e76dc0abca4396f0747cd7b748df913007626b1d659da0c1f78b9303d01a3", "44e78a773756e0951519504d7038d28d0213a37e0ce375371757bc996311e3b8", "77ac012a3f754dcfeab5eb996be9cd2d1f96111b6e49f3994df181f28569d825", "ce5a10db6fccdaf140aaa4ded6250a9c06e9222bc9f9f3658a4aff935f2b9f3a", "ecc203a7fe2be4abd55bb53e6e673572e0078da8cd375ef430cc97f9f80083af", "14a5186de9d7a18b0412b8563e51cc5433840b4a129a8ff963b33a3c4afe8ebb", "13f8ef95cb86e6a638931c8e107673eb76ba10d7c2cd70b9d9920bbeed929409", "0b338f4ee12f2dfcb78713377941e0b0632152581d1332516e4a2cab1942cca4", "eaab0ec37b3b8ab796e9f57238de14a264a076f3887d86e29bb5906db5a00e02", "23cb68b8c0e6dc26dc27766ddc0a13a99438fd55617aa4095d8f969720c872df", "091d8ee30d6f2968d46b687dd65292665742de0bb83dcc0004c72ce10007a549", "7f507abc6d19ba00c065a876ec5657868882d18a221bc46c7a6912541f5bc7ba", "a0607c24e14e8c223db0d70b4d30ee88014d603f437e9e02aa7dafa3cdfbad94", "ddbfea75cc467882eb3483ce5e2e756a4f4701b76b445519e89f22d60fa86e06", "0c311f38c35a4fb90d651c289d486856cd1413df9b0677f53ece2cd9e477c60a", "46a73a8dd3e70f59d3942c01df599def783c9da82fd83222cd662b53dce7dbdf", "ad038ff9b14de84a801e4e621ce5df029dd93520d0c2fa38bff176a8b1d1698c", "ab70c5dfbd1ea817fed0cd067293abf319e5d7901c2141d5d99b23f03a38e748", "1fffda67932b73c8ecaf009a3491a026953babfe1f663b0697c3c4ae8b2e7dcb", "b0d2cc19472dd57f2b17efc03c8d58c2283dbb19da572f7755855aa9794317a0", "a0d19a6ee33979c325510e276622df41f71583d07501b87071129a0ad94732a5", "724642a7032d1062b89e52bea34b75df7d8fe772d9fe3c93ddf3c4545ab5a99b", "ade5eaa7e61f672d587ea03dae7d7b55229c01d06bc0a5701436cbd18366a626", "013b31ebd228fcdda51fabb03bb02d60ac20ca215aafa83bdd855e3755a35f0b", "332ed40bb10dde3c954a75d7b8999d4b26a1c063c1dc6e32c1d91bab7bbb7d16", "c7a197b3a05b566bcc9facd20e441d6f6c2860ac9651cd51d6b9d2cdeeea0390", "bd9cf64ea8953c037108e6f654914f3958b68e29c16700dc184d94a21708ff60", "8835b0ac021151df716474ce27ce4d3c15f0b2dab48003cf3f3efd0945106b9a", "3bfefa3301aa55c080190cffda8eae51d9af488b4c1f24c3d9a75242fd8ea01d", "08284d14993cd47d53ebaecf0df0478cc182c89c00e1859c84851686ddf2c1b7", "1ed7ef9f04c2ac8db6a864db131087f27065098e69c3fe78718d9b947f4a39d0", "c161f2dcd57e9c1439b31a9dd43d8f3d7dd8f0eb7cfac6fb25a0f28e306f0661", "c01969ad34c52caf3dc4d80d19735c29731ac6e7a92085ab9250c48dea48a3fc", "1720b3655619d2a52b3521ae0e49e345cb3389ebd6208acaf9f13fdacca8be49", "756288361c83e24c617cf95c905b22d017cdc86f0bf1d658f4756c7379873b7f", "e7d0eda3452693b752abcda1b55e276f82698f5f1605403eff830bea0071a394", "2c82ecaa6b84803e044af63118afe544687cb6e6c7df49ed762dfd7c8693a1bc", "6136cbf4b441056fa1e2722498125d6ded45e17b52143959c7f4d4e395218ac2", "721d3245aafef27f6a624f47954b6c255079526ffa25e9ff77e5dcff473b1597", "9dd2fbd8cef16c353c0ac21191d509eb28dd9e3e0d8cea5d26ca839393851c3a", "b2394ceacdebf21bf9df2ced98e58f1c3a4bbbff660dd900f62202d6785cc46e", "57089f222749ad7871765f062b114f43ba20ec56422a8b1e3f87192c0ea718c6", "e49a9459961cd33cdf4aae1b1078a5dea7c040e0fea340c93a724872fc4af806", "ede67f720effd2ca9c88994152d0201dee6b0a2d2c077aca6dae29f73f8b6309", "e0f434bf22e3088039c21f719ffc67f0f2cb5e98a7a0194c76e96bf4e8e17e61", "277c04e2853484a4eba910ad336d01b477b67cc200c59f3c8d77eef8494f29cd", "156d5747d0c99c7f27097d7b7e002b2e185cb72d8dd7eb424a0321528161219f", "20ddd1ed9b1ca803946d64a83ae4659da67fba7a1a3eddb1e103c0f5e03e3a2c", "f0af604d3dabbf9a0f2a7d3dda6bd38bba72c6d09be494fcef713ff10189b6e6", "9802bb87def4cc10c4a5fd49aa58dfe2f3fddb46b4708814ead81d23ba95139b", "4f8ce1e51d2fe7f24043a904d898ebfc91975418753413aa099b795ecb35cedb", "bddc6514d7ee6ace0a4ac1d0e068112288cbcf560454642705630177cba608bd", "d635994f6291517b0281ffdd496afa862712e5b3c4e52e4cd5fdae8c0e72fb08", "878d9ca600cf87e769cc305c1b35255186615a73a0da613b5f1c98dbf81283ea", "a64ebe5dc185de9fdde7607b6998702eb23456184957307d2fa72e87a47702d6", "ce50eab7b5eb52bdc9ad8e5a480ab780ca9320e44360b1fe37e03f2f7ad7de01", "eeddb7c0db6e30abe66d79e327511e61fcebbc29f159b40a86b046ecf0513823", "787fc93440c1ec96b5ad01c16cf77916a1405f9426356ec921d8dff3ea63b7e0", "7f0d5eab47eefda696c0bf0fbf86ab216fce461e9303aba6ac374120e890e8df", "b68004b42f14ad029f4c2e03b1d5eb76d57160e26476d21131bef20ada7d27f4", "b0c4eb18ae250b51a41382ead92d0dc7455f9379fc9884428e4770608db0faec", "f92b7a870c059f4d46464c824ec96355140bdce681322cc3a992ff103e3fea52", "5364312614813398cc525d4c4e146edeb371265fba19133a2c3d2159298a1742", "f6620e68d37fb2af5000fc28e23b832297ecd8bce99e8be4d04e85309e3d3374", "5316a27969d7fe04ff27b283961bffc3bf5dfb32fb6a89d101c6c3b1937c2871", "81d1664fdf3cb33c24eebac0bd64244b77c4abea90bbe8b5ee0b2aafcf2d6a53", "345782f295b0880352e924a0467b5fbc3e8f3bfbc3c7e48b67091fb5e80a9442", "794111ea6cd65e311f74ee41d476cb632ce1e4b051dc1d9e9d061a19e1d0bb49", "2a85daf6138816b99bf8d08ba2114b7ab07975a78420c1a3b06a777c22dd8bcb", "89b0d5f289ec16401a069a960d0b093e625da3cf41ee29b59b930c5820145455", "d0fdcb543943fc27d20864f52181471b942cc77ca675bcb30df31d358ef7b1eb", "b17ea8d77063c709d4dc6b879413c343e3790e9e62ca85b7900b086f6b75c672", "e71a3e2c274db842d92114f217e2c0eac8b45093fdfd9df4ca7162394862d501", "c0476759ab7aa333234f6b44f5fd858390ec23694c622cb986e769c78edd733e", "9ab8eabb1416434d85391341d56993c55458167d4418b19a0f2ad8b79a83a75b", "7992d0bbb15e23826f443e00505d68d3ed7372995a5c3e498654102fbcd0964e", "c021b30085151435df33b007ccecc69df1269f39ba25092bed59d932ac0fdc28", "91a25ec0ec0d9a567f89c4bfe1a65a0e432d07064b4190e27dfb81901fd3139b", "5950d39a23e1545f301270aa1a12f2e6c453776e4d6355de425cc153f9818867", "d79f14720c610af179a3765d4b7c0968f977962dbf655b521272b6f1e194488e", "e9531bfc8b02995aeaa75ba27031fadbcbf4a0dab8961d9296cd7e84d25d6006", "34e9c26a01d7f16181b454a9d1623c233cb99d31c694656e9413aca3e918692f", "d9d7422f437bd439ddd4d883dae2a08350173414be78155133fff1964c3d7972", "4aee0c7aaf075414ff1793ead7eaca601775c615dbd60b640b0a9f0ce505d435", "6bfdd15459c83b99f096bfb49ee87b063d69c1974c6928acfcfb4099f8c4ef67", "9fd1c408fd75c336193a2a14d94f6af5adf050b80387b4b010fb29f4cc72707c", "13c88480a5d00d6c8c7ad2110d76a82d9b70f4fa6696d4e5dd42a066dcaf9920", "820e725ee25fe8fd3a8d5abe4c46c3ba889de6fa9191aa22ba67d5705421542b", "32d93a0eb02f42fbbcaf2bad0085b282e46046a4df7ad10657c9d6476375b93e", "adc5187905b1669cd8ec9c721e1953786b9d89a9bae30780f1e1eab24a00523c", "e90756ff7f9ad810b239a10ced2cf9b2284354c1f8c7e0accc2461dc796d6e89", "1251f76e56978481875359801db589a0b22f86d8d634dc04506f322ed78f17e8", "3afa899fd980e73ecb7f4d8b8f291dc9af796bc65d27f974c6f193c9191a09fd", "aa305be26e5deddc3c1010cbc213f95f051c785c5b431e6a7cd048f161787528", "8ea1884ff32e9d10f039b407d0d44e7e670abd884aeee0fb757ae94eaa97373d", "d482b2155d4dec6b4736a1f1617b53aaa37310277d3fef0c37ad41768fc235b4", "4d413971387e7a8898a8dc2a27500778539ea214a2dfe9b3d7e8ebdce5cf3db3", "696e5d46e6c57e8796e4735d08916e0b7929b3cf298c296d22e9d3019653371c", "1f5647c1d3b088228885865c8940908bf40d1a8272821973b160008e7a3ce2eb", "b6e76c330f021a5bda65875010b0edf09126c0f510ea849048192003aef4c61c", "3cd952a0beada41abb424ce47f94b42be64e1ffb0fd0782276807946d0d0bc55", "98d92677439b41b7bb513312afb92bcc8ee968b2e3b238cecb9b0f34c9bb63d0", "ecbca2cf08ae57d517ad16158a32bfa7dc0382eaeda128e91886734c24a0b29d", "942cc7c0b52e2b16a4b89fa4fc7e0bf609e29a08c1a8543452b77c7bfd11bb28", "8a065d8b61a0dffb170d5627735a76b0e9506037808cba16c345007c9f79cf8f", "1b9fa19714659c78ff413871849215361029ac802b1cbcd54e408bd87287f81f", "8dab071bcd6c7292a9ef727b4ae0d86713301da8618d9a48adce55f303a869a1", "8253e3e7c7b684b9cb2beb014ce330ff3d99d17abbdbabe4f4d674ded53ffc6b", "f195f321e9e3d6bd7d074504dd2ab0e6241f92e784b1aa271ff648b1cab6d7f6", "27e4cc72090f241266476a7c09495f2db153d5bcbd761903ef79275ec56b2ed8", "899c2405788e25b99a1846355e646d77cf400083415f7dc5afe69d6e17c00023", "a59b78c4905744076bfee894de707d4f120b5c6893ea0400297d0bb834727632", "59dc78b105649707a2bb4419c48f005400d3973de3736610230435b10424b24f", "c0149d1d7e7a6353a6d906efe728f2f329fe14a4149a3ea77609bc42b975ddfa", "a32f241474a6c16932e9243be0cf09bcdc7e0ca0e7a6a1b9b1a0f01e41502377", "b239b2e4f81841361c1339f68e2c359f929af9ad9f34e01aab4631ad6d5500b0", "85fb419c7002a3e0b4b6ea093b4c1ac6936645b65dac5ac15a8528b7b94c1754", "9619720625f190b93a3fad186ab314189633c0d3a01e6f9bc8c4a8f82f383dbf", "7d620d90fe69fa469a6538388970a1aa09bb48a2d59b347b97e8ce71f48c7f46", "294383568596fb37c75bbacd979c5ff6f20a556bf8879cc72924855df9b8240e", "16b18ab314359c2b833c1c6986d48c55a9fc97cde9a3c1f10a3177140f73f738", "8cbbdd14bc33f04cf45813e4a153a273d36adad5ce71f499eeb87fb8ac63b729", "69c9a498db174ecaefcc5a3ac9fdedf0f813a5bec727f1e775babdec7718816e", "b462c3be40448f1d4f80626254e535b08bc9cdcff599a768578d4b2881a8e3f0", "553e9d9c5f360ac0b74a7d44e5a391dad4ced03e0c24183b7e8ecabdf1715a64", "7a7c55a56fa9ae51e655e01975d8a6ff4ae9e4b486fcbe4eac044588f245ebea", "2afdf3c82abc4867f5de111286c2b3be7d6e48657ba923cfbf101a6dfcf9db9a", "41037d2edcdce0c49b7fb4a6aa0999ca66976c7483afe631d4eda283144f6dfc", "c4466f8497ca2eeb4583a0b08e9d9ac74395709fda109d24f2e4462196779c5d", "75f609338aa67d969a2ae2a2362b2da9d77c695dfd1df7224a6901db932c3364", "68606ceb989d5488fc7cf649f3d7c272ef055da1a93faecd55fe06f6967098ca", "44346bdeb7e052f6255048f0d9b42c425bab9c3dd24168212c3ecf1ebf34e6ae", "8e9cf6e1f366471f2ac7d2ee9b5e6266fda71f8f2e4109f2237ed5f8813fc718", "84bbeb8406d250951f8c1b3e86a7c010082921833dfd9555a2f909b1086eb4b8", "ee666f3eef0f7e2a9c222958c97eaf35f51ced393d714485ab09a069340fdf88", "c153d34a65c47b4a62c5cacf24010975d0356b2f32c8f5da530d338816ad5de6", "9fc5450109e1b779f6c7ae79d56c27635c8dd426c5a9d54e2578db989b8c3b4e", "d12bf3732ef4af5c22fa90356af8fc50fcb40f8f2ea5c8594737a3b3d5abdbd7", "11030b9289bba5af65260672ab6fee88b87420acef4a1789a2073b7ec2f2a09e", "69cb192b8444005c8c0ceb12c846860768188cda0aec27a9c8a55cdee2123632", "db444c15597b5f1a03d1f9edd16e4a9f43a667cc275175dfa2b704e3bb1a9b83", "3fb735061abc519dfe979e54c1ee5bfad0a9d858b3315bad34bde999efd724dd", } var hashes128 = []string{ "9536f9b267655743dee97b8a670f9f53", "13bacfb85b48a1223c595f8c1e7e82cb", "d47a9b1645e2feae501cd5fe44ce6333", "1e2a79436a7796a3e9826bfedf07659f", "7640360ed3c4f3054dba79a21dda66b7", "d1207ac2bf5ac84fc9ef016da5a46a86", "3123987871e59305ece3125abfc0099a", "cf9e072ad522f2cda2d825218086731c", "95d22870392efe2846b12b6e8e84efbb", "7d63c30e2d51333f245601b038c0b93b", "ed608b98e13976bdf4bedc63fa35e443", "ed704b5cd1abf8e0dd67a6ac667a3fa5", "77dc70109827dc74c70fd26cba379ae5", "d2bf34508b07825ee934f33958f4560e", "a340baa7b8a93a6e658adef42e78eeb7", "b85c5ceaecbe9a251eac76f6932ba395", "246519722001f6e8e97a2183f5985e53", "5bce5aa0b7c6cac2ecf6406183cd779a", "13408f1647c02f6efd0047ad8344f695", "a63970f196760aa36cb965ab62f0e0fa", "bc26f48421dd99fd45e15e736d3e7dac", "4c6f70f9e3237cde918afb52d26f1823", "45ed610cfbc37db80c4bf0eef14ae8d6", "87c4c150705ea5078209ec008200539c", "54de21f5e0e6f2afe04daeb822b6931e", "9732a04e505064e19de3d542e7e71631", "d2bd27e95531d6957eef511c4ba64ad4", "7a36c9f70dcc7c3063b547101a5f6c35", "322007d1a44c4257bc7903b183305529", "dbcc9a09f412290ca2e0d53dfd142ddb", "df12ed43b8e53a56db20e0f83764002c", "d114cc11e7d5b33a360c45f18d4c7c6e", "c43b5e836af88620a8a71b1652cb8640", "9491c653e8867ed73c1b4ac6b5a9bb4d", "06d0e988df94ada6c6f9f36f588ab7c5", "561efad2480e93262c8eeaa3677615c4", "ba8ffc702e5adc93503045eca8702312", "5782be6ccdc78c8425285e85de8ccdc6", "aa1c4393e4c07b53ea6e2b5b1e970771", "42a229dc50e52271c51e8666023ebc1e", "53706110e919f84de7f8d6c7f0e7b831", "fc5ac8ee39cc1dd1424391323e2901bd", "bed27b62ff66cac2fbb68193c727106a", "cd5e689b96d0b9ea7e08dac36f7b211e", "0b4c7f604eba058d18e322c6e1baf173", "eb838227fdfad09a27f0f8413120675d", "3149cf9d19a7fd529e6154a8b4c3b3ad", "ca1e20126df930fd5fb7afe4422191e5", "b23398f910599f3c09b6549fa81bcb46", "27fb17c11b34fa5d8b5afe5ee3321ead", "0f665f5f04cf2d46b7fead1a1f328158", "8f068be73b3681f99f3b282e3c02bba5", "ba189bbd13808dcf4e002a4dd21660d5", "2732dcd1b16668ae6ab6a61595d0d62a", "d410ccdd059f0e02b472ec9ec54bdd3c", "b2eaa07b055b3a03a399971327f7e8c2", "2e8a225655e9f99b69c60dc8b4d8e566", "4eb55416c853f2152e67f8a224133cec", "49552403790d8de0505a8e317a443687", "7f2747cd41f56942752e868212c7d5ac", "02a28f10e193b430df7112d2d98cf759", "d4213404a9f1cf759017747cf5958270", "faa34884344f9c65e944882db8476d34", "ece382a8bd5018f1de5da44b72cea75b", "f1efa90d2547036841ecd3627fafbc36", "811ff8686d23a435ecbd0bdafcd27b1b", "b21beea9c7385f657a76558530438721", "9cb969da4f1b4fc5b13bf78fe366f0c4", "8850d16d7b614d3268ccfa009d33c7fc", "aa98a2b6176ea86415b9aff3268c6f6d", "ec3e1efa5ed195eff667e16b1af1e39e", "e40787dca57411d2630db2de699beb08", "554835890735babd06318de23d31e78a", "493957feecddc302ee2bb2086b6ebfd3", "f6069709ad5b0139163717e9ce1114ab", "ba5ed386098da284484b211555505a01", "9244c8dfad8cbb68c118fa51465b3ae4", "51e309a5008eb1f5185e5cc007cfb36f", "6ce9ff712121b4f6087955f4911eafd4", "59b51d8dcda031218ccdd7c760828155", "0012878767a3d4f1c8194458cf1f8832", "82900708afd5b6582dc16f008c655edd", "21302c7e39b5a4cdf1d6f86b4f00c9b4", "e894c7431591eab8d1ce0fe2aa1f01df", "b67e1c40ee9d988226d605621854d955", "6237bdafa34137cbbec6be43ea9bd22c", "4172a8e19b0dcb09b978bb9eff7af52b", "5714abb55bd4448a5a6ad09fbd872fdf", "7ce1700bef423e1f958a94a77a94d44a", "3742ec50cded528527775833453e0b26", "5d41b135724c7c9c689495324b162f18", "85c523333c6442c202e9e6e0f1185f93", "5c71f5222d40ff5d90e7570e71ab2d30", "6e18912e83d012efb4c66250ced6f0d9", "4add4448c2e35e0b138a0bac7b4b1775", "c0376c6bc5e7b8b9d2108ec25d2aab53", "f72261d5ed156765c977751c8a13fcc1", "cff4156c48614b6ceed3dd6b9058f17e", "36bfb513f76c15f514bcb593419835aa", "166bf48c6bffaf8291e6fdf63854bef4", "0b67d33f8b859c3157fbabd9e6e47ed0", "e4da659ca76c88e73a9f9f10f3d51789", "33c1ae2a86b3f51c0642e6ed5b5aa1f1", "27469b56aca2334449c1cf4970dcd969", "b7117b2e363378aa0901b0d6a9f6ddc0", "a9578233b09e5cd5231943fdb12cd90d", "486d7d75253598b716a068243c1c3e89", "66f6b02d682b78ffdc85e9ec86852489", "38a07b9a4b228fbcc305476e4d2e05d2", "aedb61c7970e7d05bf9002dae3c6858c", "c03ef441f7dd30fdb61ad2d4d8e4c7da", "7f45cc1eea9a00cb6aeb2dd748361190", "a59538b358459132e55160899e47bd65", "137010fef72364411820c3fbed15c8df", "d8362b93fc504500dbd33ac74e1b4d70", "a7e49f12c8f47e3b29cf8c0889b0a9c8", "072e94ffbfc684bd8ab2a1b9dade2fd5", "5ab438584bd2229e452052e002631a5f", "f233d14221097baef57d3ec205c9e086", "3a95db000c4a8ff98dc5c89631a7f162", "0544f18c2994ab4ddf1728f66041ff16", "0bc02116c60a3cc331928d6c9d3ba37e", "b189dca6cb5b813c74200834fba97f29", "ac8aaab075b4a5bc24419da239212650", "1e9f19323dc71c29ae99c479dc7e8df9", "12d944c3fa7caa1b3d62adfc492274dd", "b4c68f1fffe8f0030e9b18aad8c9dc96", "25887fab1422700d7fa3edc0b20206e2", "8c09f698d03eaf88abf69f8147865ef6", "5c363ae42a5bec26fbc5e996428d9bd7", "7fdfc2e854fbb3928150d5e3abcf56d6", "f0c944023f714df115f9e4f25bcdb89b", "6d19534b4c332741c8ddd79a9644de2d", "32595eb23764fbfc2ee7822649f74a12", "5a51391aab33c8d575019b6e76ae052a", "98b861ce2c620f10f913af5d704a5afd", "b7fe2fc8b77fb1ce434f8465c7ddf793", "0e8406e0cf8e9cc840668ece2a0fc64e", "b89922db99c58f6a128ccffe19b6ce60", "e1be9af665f0932b77d7f5631a511db7", "74b96f20f58de8dc9ff5e31f91828523", "36a4cfef5a2a7d8548db6710e50b3009", "007e95e8d3b91948a1dedb91f75de76b", "a87a702ce08f5745edf765bfcd5fbe0d", "847e69a388a749a9c507354d0dddfe09", "07176eefbc107a78f058f3d424ca6a54", "ad7e80682333b68296f6cb2b4a8e446d", "53c4aba43896ae422e5de5b9edbd46bf", "33bd6c20ca2a7ab916d6e98003c6c5f8", "060d088ea94aa093f9981a79df1dfcc8", "5617b214b9df08d4f11e58f5e76d9a56", "ca3a60ee85bd971e1daf9f7db059d909", "cd2b7754505d8c884eddf736f1ec613e", "f496163b252f1439e7e113ba2ecabd8e", "5719c7dcf9d9f756d6213354acb7d5cf", "6f7dd40b245c54411e7a9be83ae5701c", "c8994dd9fdeb077a45ea04a30358b637", "4b1184f1e35458c1c747817d527a252f", "fc7df674afeac7a3fd994183f4c67a74", "4f68e05ce4dcc533acf9c7c01d95711e", "d4ebc59e918400720035dfc88e0c486a", "d3105dd6fa123e543b0b3a6e0eeaea9e", "874196128ed443f5bdb2800ca048fcad", "01645f134978dc8f9cf0abc93b53780e", "5b8b64caa257873a0ffd47c981ef6c3f", "4ee208fc50ba0a6e65c5b58cec44c923", "53f409a52427b3b7ffabb057ca088428", "c1d6cd616f5341a93d921e356e5887a9", "e85c20fea67fa7320dc23379181183c8", "7912b6409489df001b7372bc94aebde7", "e559f761ec866a87f1f331767fafc60f", "20a6f5a36bc37043d977ed7708465ef8", "6a72f526965ab120826640dd784c6cc4", "bf486d92ad68e87c613689dd370d001b", "d339fd0eb35edf3abd6419c8d857acaf", "9521cd7f32306d969ddabc4e6a617f52", "a1cd9f3e81520842f3cf6cc301cb0021", "18e879b6f154492d593edd3f4554e237", "66e2329c1f5137589e051592587e521e", "e899566dd6c3e82cbc83958e69feb590", "8a4b41d7c47e4e80659d77b4e4bfc9ae", "f1944f6fcfc17803405a1101998c57dd", "f6bcec07567b4f72851b307139656b18", "22e7bb256918fe9924dce9093e2d8a27", "dd25b925815fe7b50b7079f5f65a3970", "0457f10f299acf0c230dd4007612e58f", "ecb420c19efd93814fae2964d69b54af", "14eb47b06dff685d88751c6e32789db4", "e8f072dbb50d1ab6654aa162604a892d", "69cff9c62092332f03a166c7b0034469", "d3619f98970b798ca32c6c14cd25af91", "2246d423774ee9d51a551e89c0539d9e", "75e5d1a1e374a04a699247dad827b6cf", "6d087dd1d4cd15bf47db07c7a96b1db8", "967e4c055ac51b4b2a3e506cebd5826f", "7417aa79247e473401bfa92a25b62e2a", "24f3f4956da34b5c533d9a551ccd7b16", "0c40382de693a5304e2331eb951cc962", "9436f949d51b347db5c8e6258dafaaac", "d2084297fe84c4ba6e04e4fb73d734fe", "42a6f8ff590af21b512e9e088257aa34", "c484ad06b1cdb3a54f3f6464a7a2a6fd", "1b8ac860f5ceb4365400a201ed2917aa", "c43eadabbe7b7473f3f837fc52650f54", "0e5d3205406126b1f838875deb150d6a", "6bf4946f8ec8a9c417f50cd1e67565be", "42f09a2522314799c95b3fc121a0e3e8", "06b8f1487f691a3f7c3f74e133d55870", "1a70a65fb4f314dcf6a31451a9d2704f", "7d4acdd0823279fd28a1e48b49a04669", "09545cc8822a5dfc93bbab708fd69174", "efc063db625013a83c9a426d39a9bddb", "213bbf89b3f5be0ffdb14854bbcb2588", "b69624d89fe2774df9a6f43695d755d4", "c0f9ff9ded82bd73c512e365a894774d", "d1b68507ed89c17ead6f69012982db71", "14cf16db04648978e35c44850855d1b0", "9f254d4eccab74cd91d694df863650a8", "8f8946e2967baa4a814d36ff01d20813", "6b9dc4d24ecba166cb2915d7a6cba43b", "eb35a80418a0042b850e294db7898d4d", "f55f925d280c637d54055c9df088ef5f", "f48427a04f67e33f3ba0a17f7c9704a7", "4a9f5bfcc0321aea2eced896cee65894", "8723a67d1a1df90f1cef96e6fe81e702", "c166c343ee25998f80bad4067960d3fd", "dab67288d16702e676a040fd42344d73", "c8e9e0d80841eb2c116dd14c180e006c", "92294f546bacf0dea9042c93ecba8b34", "013705b1502b37369ad22fe8237d444e", "9b97f8837d5f2ebab0768fc9a6446b93", "7e7e5236b05ec35f89edf8bf655498e7", "7be8f2362c174c776fb9432fe93bf259", "2422e80420276d2df5702c6470879b01", "df645795db778bcce23bbe819a76ba48", "3f97a4ac87dfc58761cda1782d749074", "50e3f45df21ebfa1b706b9c0a1c245a8", "7879541c7ff612c7ddf17cb8f7260183", "67f6542b903b7ba1945eba1a85ee6b1c", "b34b73d36ab6234b8d3f5494d251138e", "0aea139641fdba59ab1103479a96e05f", "02776815a87b8ba878453666d42afe3c", "5929ab0a90459ebac5a16e2fb37c847e", "c244def5b20ce0468f2b5012d04ac7fd", "12116add6fefce36ed8a0aeccce9b6d3", "3cd743841e9d8b878f34d91b793b4fad", "45e87510cf5705262185f46905fae35f", "276047016b0bfb501b2d4fc748165793", "ddd245df5a799417d350bd7f4e0b0b7e", "d34d917a54a2983f3fdbc4b14caae382", "7730fbc09d0c1fb1939a8fc436f6b995", "eb4899ef257a1711cc9270a19702e5b5", "8a30932014bce35bba620895d374df7a", "1924aabf9c50aa00bee5e1f95b5d9e12", "1758d6f8b982aec9fbe50f20e3082b46", "cd075928ab7e6883e697fe7fd3ac43ee", } // hashes2X is taken from // https://github.com/BLAKE2/BLAKE2/blob/master/testvectors/blake2-kat.json var hashes2X = []string{ "0e", "5196", "ad6bad", "d8e4b32f", "8eb89056f3", "410497c2ed72", "f0de771b375c90", "8662db8685033611", "9ef9f1eed88a3f52ca", "08225082df0d2b0a815e", "0f6e84a17439f1bc97c299", "895ec39c78d3556cefdbfabc", "2b396b3fa90ab556079a79b44d", "abae26501c4c1d6123c0f2289111", "bca098df9099b3f785a37ba40fce5f", "19b827f054b67a120f11efb0d690be70", "b88d32a338fd60b58570fda228a121113b", "3f30143af1cad33f9b794576e078cc79062e", "ffddb58d9aa8d38086fcdae07e6653e8f31dfc", "abb99c2e74a74556919040ca0cd857c95ec985e9", "71f13f89af55ba936f8a7188ee93d2e8fb0cf2a720", "99734fdf0eef4838a7515426f4c59b800854e2fcdc1c", "579b1652aa1f5779d2b0e61868af856855020bdd44d7a7", "1383d4ab4a6d8672b4075d421a159f69380ff47e4bb518d5", "d3fa1412712dbbab71d4c6265dc1585c8dcc73380cf807f76a", "1d57868a71e7245667780455d9aaa9e0683baf08fbaf946091c2", "ef80418fe7049c6251ed7960a6b0e9def0da2749781994b24593a0", "ef91cb81e4bfb50231e89475e251e2ef2fde59357551cd227588b63f", "d7f398a5d21c3139cff0562a84f154b6953c7bc18a5f4b60491c196b6d", "0a2abc6d38f30aef253579a4088c5b9aec64391f37d576eb06a300c193a5", "02dd758fa23113a14fd94830e50e0f6b86faec4e551e808b0ca8d00fef2a15", "a4fe2bd0f96a215fa7164ae1a405f4030a586c12b0c29806a099d7d7fdd8dd72", "7dce710a20f42ab687ec6ea83b53faaa418229ce0d5a2ff2a5e66defb0b65c03c9", "0320c40b5eea641d0bc25420b7545ac1d796b61563728a4dc451207f1addeedcf860", "460539415f2baeb626fad748dee0eb3e9f27221661160e13edf39d1b5d476ee0672400", "02de8ffa5b9c748164f99ed9d678b02e53f4ae88fb26c6d94a8cefc328725a692eae78c2", "348a61a0136436136910262ad67ef20644b32c15456d5fad6b1679386d0bea87cc1a2e2b5e", "24c32966c803434d48d2283482ee8f404f598cf7a17961748125d2ed1da987039b1ce00f2ba7", "bd07cb16121d3b47adf03b96c41c947beadc01e40548e0d0773e61780d48d33a0e2a675ca681a6", "a35844e34c20b4b9371b6c52fac412afe5d80a4c1e40aa3a0e5a729dc3d41c2c3719d096f616f0ba", "6df1efbb4567747fe98d218935612f8835852dde2ce3dec767792d7f1d876cdae0056fef085245449d", "48d6094af78bd38d8f4b39c54279b80ef617bc6ad21def0b2c62113b656c5d6a55aea2e3fde94a254b92", "cd6e684759d2f19083164712c2aca0038442efb5b646594396b1fccdbd21203290f44cfdecca0373b3801b", "155dfbf26103c8354362663677fa27d0e1ce3487a821a2a7171014c1bd5dd071f4974df272b1374765b8f2e1", "15b11067f311efa4ee813dbca48d690dc92780656bc4d4c56510523190a240180867c829a8b8b9844175a8aa23", "9bc27953a17fb84d5eabe95b4ea6bc03ea450274abccfb6f3938ded8560fb59662459a11a86b0e0f32fbea6bb1f8", "03b78fb0b34fb8662accdf350a6be75ace9789653ee4375d351e871f6a98ac5e782ca4b4a717665d25e49a5ae25d81", "687e9a6fda6e2ce0e40e4d30fef38c31e3513d2892bbe85c991fc3715947e42bc49bcd079a40ed061c2c3665efe555ab", "f3886027d2049a8909e26545bd202d6a6fa2a6f815d31c7d520f705a81fa606dd695369c37aee4fa77dc645e9b05813ceb", "e4a412ccd20b97797d91ccc286904fcd17c5afe8bed0618f1af333c052c473cd327637d951c32e4af047106036a3bc8c1c45", "92f4b8c240a28b6238bc2eabadaf2ff3c4bfe0e6c61268ace6aebdeb0691450caea4287db8b329bde96af8cdb8a0fe2f57ef2d", "e506834b3445e1a9a9b7bae844e91e0834512a06c0dc75fa4604e3b903c4e23616f2e0c78b5cc496660b4a13064bb1138edef4ff", "27031955a40d8dbd1591f26e3c26e367a3c68f8204a396c6a4ba34b89672896d11276966a42bd516716f35ed63e442e116dbcf35da", "646b1635c68d2328dddd5ac26eb9877c24c28390a45753a65044c3136ae2fe4fb40d09bf555271646d3dceb1ab1b7c8d8e421f553f94", "f6171f8d833743bdee7cc8f8b29c38614e1d2d8d6a5fff68bec2c0f4dd463d7941ff5c368e2683d8f1dc97119bde2b73ca412718bc8cb1", "45db1c478b040aa2e23fb4427017079810775c62abe737e82ec0ef8dcd0fc51f521f29fe6412fff7eac9beb7bcf75f483f3f8b971e42454b", "500dab14687db3ca3dde9304af5f54194b37bdf475628af46b07bfbf6bc2b64ecef284b17f9d1d9be41794699bc0e76c2878b3a55730f7142d", "31bba2efc7b3f415c3f031d4c06bb590ae40085ad157370af30238e03e25a359c9e133212ed34b7a006f839173b577e7015a87fdff2270fafddb", "0600b3fb4b5e1ed0c8b2698ac1d9905e67e027390764821f963ad8d2b33cbc378b9c25c3ee422992d22b760222ed5697be0576d73938ae9d634ed7", "4c0ca4f177d132594a4c613bad68da24c564efa3b4da0d0a903f26534a2e09f8d799d10e78f48ccdb0203954a36c5cf1bf24c076632c2b022b041200", "97aacf2e1b013677b2e14084f097cb1e64d7b3fa36f097e189d86dc4a263bcc46817cd1ee6ff0c7ccd9acef63201cdc0e36254e19204a7388643bb571f", "71fd6846ce7adb0843d6063546a16b79b54ad6c0f018a479a45817624fa221f63525084860559d1a0679c8d89a80701c62743ec2da8419d503f8f0cd7946", "f73dfb046def3362d6de36077dae2cee2587fe95fe0800548bb7d99737897096ba59052e0dadcc1fb0ccb5535391875328637a0376a43a4d89366758dfe3e2", "ec470d0aa932c78c5bcf86203ec0014314114765fa679c3daef214f883a17e1b4ca12f44433772a6e4ef685c904b2fc35586c6bd88f325b965968b06d808d73f", "cf601753ffa09fe48a8a84c37769991e96290e200bbaf1910c57760f989bd0c72e6128e294528ee861ad7eee70d589de3cf4a0c35f7197e1925a64d0133628d87d", "f15413f7d6fc54bb55829f698da92ee42fcf58dde1aa1bd07d438ecdc32ad6bf2bcdbecc99f18ed43e81b33065af5a4ca29960ae50553e610c0bbf4153d580e73dbb", "84b1738adb9757fb9402ef7113581291136184d7ae35fe0b6a738da6acb0889d4d5bac7a957024e3709fa80c77d3859871ed1aa25cf488e438a2d24cfadce6008761dd", "e02814bb81f250c1835a05108396b74c7878e737654bb83155e241774d04e639bbc571b413cd9349092f926c8a149a53cd33e9b63f370b6d460e504199d2e7d849db6cbe", "aeee4a789956ec0913592c30ce4f9c544894da77ba447c84df3be2c869100e4df8f7e316445d844b31c3209abcc912f647735fd4a7136c2f35c6fda5b2e6708f5ca951b2b0", "8cfd11ca385de3c843de84c830d59278fe79b70fb5ddbfbfc1ddefeb22c329ef2f607d1d1abbd1cd0d0cc7c5d3ed922add76aadca0d2f57b66cb16c582b6f18f60aee2f7509b", "852e5ce2047d8d8b42b4c7e4987b95d23e8026a202d4567951bbbd23111e389fe33a736318546a914d2bddedfbf53846036ad9e35f29318b1f96e33eba08f071d6dc665149feb6", "f225c23164979d0d13874a90ee291627e4f61a672a5578506fd3d65a12cb48a182f78350dc24c637b2f3950dc4882a5c1d5d5bad551c6f3e0093aa87e962bea51566af3791d52d65", "5f33864d882455f8ef046aed64e2d1691e5c1555e333b0852750592e6f00d3b5ec941d0c00e99629612795d5870cf93c984b45e4464ba072a34903b400a42824ac13da28c7c1cb1959", "7baaee7c3eb68c18c5ae1d45ba381803de34e36a52e2d7ccc9d48a297273c4d8644b473195bc23005f7a4f5ca790b1fa11f6a96e585e635513f11745dd97a69c1222204ab28d3c7735df", "d0a2a3fc450ef9af7ae982041feb2842901026467d87839c33b4a9e081ea63d5be60ae99ca6e42393ded45255b8f42886f87ba0310572d9f0d8b5a07ff4b6bae1f30559a844983cc568560", "3aa4164462b3e7044c35b08b047b924790f6d5c520b1df4305b5d41f4717e81f0cd4bccb9a5a6594773832b8707443adde4047caaed2293f92234df257df54ed275a9658fab483d0576d33a9", "c8b4239fd7f1b893d978268f77f6505b5775d89090374322d40083b0f4c437423f670ca213f7fe05c61069725da2561646eefaea597ac48e293fbad44c2872046857e56d04a426a84008cefd71", "f94839a7024c0a16971271b6727c081770110c957b1f2e03be03d2200b565cf8240f2873b0426042aaea996a1784fadb2b27f23bc1a521b4f7320dfbed86cd38d75141365ba9b443defc0a3b4078", "8af934fdc8b3376ca09bdd89f9057ed38b656bff96a8f8a3038d456a265689ca32036670cb01469cc6e958cc4a46f1e80d700ae56659828a65c0456b8e55f28f255bc86ce48e44377bf1f9970b617d", "ada572989e42f0e38c1f7c22b46bb52a84df8f7b3b773c9f17a5823e59a9725248d703efb4cb011abc9474e8e711666ed3cfa60db48480a8160615dfabad761bc0eb843d2e46299c59b61a15b4422fdf", "b11f1ea52a7e4bd2a5cf1e234b7c9eb909fb45860080f0a6bdb5517a37b5b7cd90f3a9e2297f995e96c293189b807a7bf6e7633bebbc36674544db5f18dd33020aeaf50ee832efe4d3d053873fd31ce3b9", "e54b006cd96c43d19787c1ab1e08ea0f8922bdb7142e748212e7912a1f2c0a4fad1b9f5209c30960b8b83ef4960e929b155a8a48c8fb7ce4326915950cede6b98a96b6f1ecb12715b713985dacd1c1180413", "ee2c2f31a414ccd8f6a790f55e09155fd50aac2a878f9014f6c6035cae9186f90cdef0b7adf3e207c3d24ddfba8cd321b2e9228b02a1182b6973da6698071fce8cc0a23a7bf0d5aefd21ab1b8dc7818549bba3", "6d6810793bad6c7efe8fd56cac04a0fb8717a44c09cbfaebce196a80ac318c79ca5c2db54fee8191ee2d305b690a92bd9e2c947a3c29342a93ac05796484638787a184e4525e82aeb9afa2f9480caebb91014c51", "91e4694366cff84854872667fd168d2d42eca9070cdc92fca9936e8361e7266931f418450d098a42686241d08024dd72f0024d22ba644bd414245e78608942321ff61860ba1245f83c88592dc7995c49c0c53aa8a9", "608aa620a5cf145f4477694407ccd8faa3182465b29ae98d96a42f7409434c21e4671bcae079f6871a09d8f2965e4926a9b08277d32f9dd6a474e3a9fb232f27fc4235df9c02abf67f7e540ca9ddc270ee91b23a5b57", "c14f75e92f75f4356ab01c8792af13383e7fef2ffb3064de55e8da0a50511fea364ccd8140134872adccad197228319260a7b77b67a39677a0dcdcadfb750333ac8e032121e278bdcdbed5e452dae0416011186d9ebf29", "03fcb9f6e1f058091b11351e775184ff2cd1f31ee846c6ea8efd49dd344f4af473f92eb44eba8a019776f77bb24e294aa9f962b39feecf7c59d46f1a606f89b1e81c2715ac9aa252e9ce941d091ffb99bb52404961794cf8", "11e189b1d90fcfe8111c79c5351d826f5ec15a602af3b71d50bc7ed813f36c9a682520984ae911669d3c3036223a53176794c7e17929efab2b1c5b500f24f8c83d3db5d1029c5714c6fd34eb800a913985c218071677b9885c", "69f8f5db3ab0321a708ab2f4234645dade6bfda495851dbe7257f2b72e3e8378b9fa8120bc836b737a675271e519b4712d2b56b359e0f2234ba7552dd4828b939e0542e729878ac1f81b6ce14cb573e76af3a6aa227f95b2350e", "be734d78fae92cacb009cc400e023086bc3a3a10e8ca7cb4d553ea85314f51383660b8508e8477af60baf7e07c04cc9e094690ae12c73e5f089763201b4b48d664b94b4f5820bd1540f4a84100fdf8fce7f6466aa5d5c34fcbab45", "d61b77032403f9b6ea5ad2b760eb0157545e37f1712ec44d7926ccf130e8fc0fe8e9b15570a6214c3899a074811486182b250dc97ebdd3b61403614d935cd0a61c0899f31b0e49b81c8a9a4fe8409822c470aacfde229d965dd62f51", "c31bd548e36d5fae95ed8fa6e807642711c897f0fcc3b0d00bd317ed2bca73412064618c6a84a61c71bce3e963333b0266a5656571dcc4ba8a8c9d84af4bdb445c34a7aef445b15d77698e0b13c436c928cc7fa7acd5f68867e8132993", "9903b8adab803d085b634bfae2e109dd247a7d6249f203403216d9f7410c36142df8fa56fb4d6f78136eef5817bad5ea3608439bb19336628c37d42db16ab2df8018b773baedafb77278a50926370b48bd81710203c7abc7b4043f9a1751", "4dadaf0d6a96022c8ce40d48f460526d9956da33260e1770315ead420da75b122c762762aa3ddc1aef9070ff2298b2304cf90443318b17183b60778f3859b141053e5827decfff27ff106a48cfdb0371d0ef614fc7400e860b676df3176d1a", "314dda800f2f494ca9c9678f178940d2284cb29c51cb01ca2019a9bede0cdc50f8ecf2a77e238b884867e78e691461a66100b38f374c4ccac80309641533a3217eca7e6b9a9af01c026201f0afaec5a61629a59eb530c3cb81934b0cb5b45eae", "4658b7500951f75c84e4509d74047ca621009835c0152f03c9f96ca73beb29608c44390ba4473323e621284be872bdb72175628780113e470036265d11dfcb284ac04604e667f1e4c1d357a411d3100d4d9f84a14a6fabd1e3f4de0ac81af50179", "491f877592837e7912f16b73ee1fb06f4633d854a5723e156978f48ec48fbd8b5e863c24d838ff95fa865155d07e5513df42c8bb7706f8e3806b705866475c0ac04bbe5aa4b91b7dc373e82153483b1b03304a1a791b058926c1becd069509cbf46e", "231034720c719ab31f7c146a702a971f5943b70086b80a2a3eb928fa9380b7a1ad8773bfd0739142d2ad6e19819765ca54f92db5f16c1df5fa4b445c266215a92527bd4ef50ed277b9a21aee3fb7a8128c14ce084f53eac878a7a660b7c011eb1a33c5", "3366860c77804fe0b4f368b02bb5b0d150821d957e3ba37842da9fc8d336e9d702c8446ecafbd19d79b868702f32405853bc17695873a7306e0ce4573cd9ac0b7fc7dd35534d7635198d152a1802f7d8d6a4bb07600fcdaacfaa1c3f40a09bc02e974c99", "ccbbbe621f910a95835f5f8d74b21e13f8a4b03f72f91f37b5c7e995aa3cd5539508d5e234e77a4668a42c239b2d13ef0e55ecf85142055e3f8a7e46320e21324a6b88e6c823ac04b485125c2aa59b61476481208f92ea4dd330cb18777c1cf0df7cd07893", "87faf0e49e7e5ab66ee3147921f8817867fe637d4ab694c33ee8009c759e7d707f44c69c1b9754e2b4f8f47b25f51cd01de7273f548f4952e8efc4d9044c6ea72d1d5857e0ffeb3f44b0c88cb67683401cfb2f1d17f0ca5696641bef28d7579f68d9d066d968", "38c876a007ec727c92e2503990c4d9407cea2271026aee88cd7b16c4396f00cc4b760576adf2d683713a3f6063cc13ecd7e4f3b6148ad914ca89f34d1375aa4c8e2033f1315153189507bfd116b07fc4bc14f751bbbb0e752f621153ae8df4d68491a22430b309", "87d636a33dbd9ad81ecd6f3569e418bf8a972f97c5644787b99c361195231a72455a121dd7b3254d6ff80101a0a1e2b1eb1ca4866bd23063fe007310c88c4a2ab3b49f14755cd0ee0e5ffa2fd0d2c0ea41d89e67a27a8f6c94b134ba8d361491b3c20bacac3d226b", "b021af793badbb857f9a353e320450c44c1030fce3885e6b271bcc02e6af65fdc5be4dc483ff44bd5d539ed1e7eb7efe3001252e92a87df8227ace601047e101c871d29302b3cb6c6f4639078afc81c4c0f4c2e04688612ecf3f7be1d58ea92894a5dab49b949f2089", "c5c1f2fbf2c8504a686b615278fc6221858d401b7fe790b75fb6bca6885cdd128e9142bf925471ee126f9e62d984de1c30c9c677eff5fdbd5eb0fa4ef3bff6a831056cea20fd61cf44d56ffc5bda0e8472ecdc67946d63c40db4ba882bc4dfa16d8ddac600570b9b6bf3", "88f8cc0daeaeaea7ab0520a311dff91b1fd9a7a3ec778c333422c9f3eb0bc183acc80dfefb17a5ac5f95c490693c45666ec69234919b83244003191bad837aa2a237daeb427e07b9e7aa6ca94b1db03d54ee8f4fe8d0802cb14a6599005eb6326eefe5008d9098d40aa851", "2eb6b1a58e7fe39ff915ac84c2f21a22432c4f0d260380a3f993310af048b11647f95d23adf8a746500833ee4e467fb52ea9f1039519fa58bcb0f1d0151558147b3c92b83730aba0e20eeeea2b75f3ff3ad79f2f8a46cbbadb114a52e32f018342aeeaf827e03ad6d583bbce", "3ba7dcd16a98be1df6b904457709b906cbf8d39516ef107006c0bf363db79f91aaae033466624d30858e61c2c368599963e49f22446e4473aa0df06e9c734e183a941510d540536377072334910e9cef56bc66c12df310ecd4b9dc14207439c1da0ac08bdd9be9f2c840df207e", "a34a7926324ea96867dac6f0dba51d753268e497b1c4f272918c7eb0e34120be65b7b5ba044d583141ec3ea16fcedae6197116b16562fb0706a89dc8efd3ba173ccd0fd7d84d480e0a3dda3b580c326aa1caca623879b0fb91e7d173998889da704eda6495023b5ad4c9ad406298", "5ef97d80b90d5c716322d9ba645a0e1b7a403968258a7d43d310320f60f96235f50e9f22cac0ad239636521fa0607d2f471051b505b371d88778c46fe6787d47a91a5bec4e3900fe6ed22918226fc9fbb3f70ee733c369420612b76b5f55988d757c891d7005d17ee55783fe506202", "140d2c08dae0553f6a49585fd5c217796279152b2e100ebde6812d6e5f6b862b2a3a484aed4d6226197e511be2d7f05f55a916e32534ddcb81bdcf499c3f44f526eb515cc3b6fa4c4039ad251253241f541558bba7413ca29318a414179048a054104e433c674ca2d4b3a4c181878727", "29fdfc1e859b001ee104d107216b5299a792d26b2418e823e0381fa390380d654e4a0a0720ba5ff59b2ff22d8c4e013284f980911dcfec7f0dca2f89867f311ced1ac8a14d669ef1114504a5b7626f67b22ecd86469800f1575543b72ab1d4c5c10ee08f06159a4a3e1ae09937f12aa173", "52dfb643832a598a10786a430fc484d6370a05356ee61c80a101dbbcfac75847fba78e27e537cc4eb918eb5ab40b968d0fb23506fee2ad37e12fb7534fb55a9e50902b69ceb78d51db449cbe2d1fc0a8c0022d8a82e2182b0a059035e5f6c4f4cc90278518e178becfbea814f317f9e7c051", "d32f69c6a8ee00ca83b82eaf82e312fbb00d9b2f6202412a1ffc6890b4509bbbeda4c4a90e8f7bca37e7fd82bd23307e2342d27aa10039a83da55e84ce273822740510e4ec239d73c52b0cbc245ad523af961994f19db225212bf4cc160f68a84760233952a8e09f2c963be9bb1d71ca4bb265", "d1e603a46aa49ee1a9ded63918f80feca5fc22fb45f659fd837ff79be5ad7faf0bbd9c4ba91628ee293b478a7e6a7bd433fa265c20e5941b9ea7edc906055ce9799cbb06d0b33ae7ed7f4b918cc082c3d4a1ac317a4acec175a73cc3eeb7cb97d96d24133a29c19375c57f3a4105519846dd14d4", "b45ac88fac2e8d8f5a4a90930cd7523730733369af9e39bf1ffb833c01108952198301f4619f04b9c399fef04c214bad3358999967c474b67a7c06457a1d61f9466489ed5c0c64c6cdc83027386d6263491d18e81ae8d68ca4e396a71207adaaa60997d0dca867065e68852e6dba9669b62dc7672b", "d5f2893edd67f8a4b5245a616039ffe459d50e3d103ad4675102028f2c497ea69bf52fa62cd9e84f30ae2ea40449302932bbb0a5e426a054f166fdbe92c744314cc0a0aa58bbc3a8739f7e099961219ec208a8d01c1ae8a2a2b06534bf822aaa00ca96218e430f0389c69c7f3fd195e128c38d484ff6", "37279a76e79f33f8b52f29358841db9ec2e03cc86d09a335f5a35c0a31a1db3e9c4eb7b1d1b978332f47f8c3e5409d4e443e1d15342a316f442e3bfa151f6a0d216df2443d80cbcf12c101c51f2946d81161583218584640f4f9c10de3bb3f4772bd3a0f4a365f444777456b913592719818afb26472b6", "a46d252a0addf504ad2541e7d992cbed58a22ea5679980fb0df072d37540a77dd0a1448bdb7f172da7da19d6e4180a29356ecb2a8b5199b59a24e7028bb4521f3281313d2c00da9e1d284972ab6527066e9d508d68094c6aa03537226ef19c28d47f91dddebfcc796ec4221642ddf9de5b80b3b90c22d9e7", "060c18d8b57b5e6572dee194c69e265c2743a48d4185a802eaa8d4dbd4c66c9ff725c93667f1fb816418f18c5f9be55e38b7718a9250bc06284bd834c7bd6dfcd11a97c14779ac539629bcd6e15b5fca3466d14fe60d8671af0fb8b080218703bc1c21563b8f640fde0304a3f4aeb9ec0482f880b5be0daa74", "8f2f42bc01acca20d36054ec81272da60580a9a5414697e0bdb4e44a4ab18b8e690c8056d32f6eaaf9ee08f3448f1f23b9844cf33fb4a93cba5e8157b00b2179d18b6aa7215ae4e9dc9ad52484ad4bfb3688fc80565ddb246dd6db8f0937e01b0d2f2e2a64ad87e03c2a4ad74af5ab97976379445b96404f1d71", "ccb9e524051cca0578aa1cb437116a01c400338f371f9e57525214ad5143b9c3416897eae8e584ce79347297071f67041f921cbc381c2be0b310b8004d039c7cc08cb8ff30ef83c3db413f3fb9c799e31cd930f64da1592ec980cc19830b2a448594cb12a61fc7a229e9c59fe1d66179772865894afd068f0942e5", "3eb5dc42172022ab7d0bc465a3c725b2d82ee8d9844b396913ceb8a885323dbbbf9ef4ed549724cc96d451ea1d1d44a8175a75f2a7d44bb8bfc2c2dffed00db0328cfde52bf9171f4025770abbe59b3aefd8151c480bafa09f613955fd571e5d8c0d4936c670d182cf119c068d420ded12af694d63cd5aef2f4f6f71", "20ea77e58e41337ad63f149ed962a8210b6efa3747fe9bea317c4b48f9641f7145b7906ed020a7ae7d2ee59435392edc32aee7eff978a661375af723fbd440dd84e4a152f2e6ef66f4ab1046b22c77ac52717de721dfe39aa8ba8cd5da27baca00cc1fffe12c52382f0ee83ad1418f4c6a122effaf7471e1e125d7e7ba", "95c662b835171fa23f948c3c3ed27bab9b3c367bbfe267fe65f8037a35b50cd7fc6030bfce4000425ef646c34793f0762635ae70487a0216ef7428da622be895d1b6040423246511c2370d6876a5c5d2df8bbd48fb14f787b632ad2c1f5a927fdf36bc493c1c8606accfa52de33258669f7d2d73c9c81119591c8ea2b0ef", "f708a230675d83299cc43167a771602d52fa37cbc068ef9128ef60d186e5d98efb8c98798da619d2011bf4673214f4a4c82e4b11156f6292f6e676d5b84dc1b81e7cc811b0d37310ac58da1bfcb339f6ba689d80dd876b82d131e03f450c6c9f15c3a3b3d4db43c273c94ed1d1bd6d369c4d30256ff80ea626bda56a6b94ea", "f8417766ce86b275f2b7fec49da832ab9bf9cb6fdfe1b916979ae5b69176d7e0293f8d34cb55cf2b4264a8d671370cb595c419c1a3ce5b8afa642208481333522005fbe48cdc700e47b29254b79f685e1e91e7e34121784f53bd6a7d9fb6369571bba992c54316a54e309bbc2d488e9f4233d51d72a0dd8845772377f2c0feb9", "3479e04efa2318afc441931a7d0134abc2f04227239fa5a6ae40f25189da1f1f313732026631969d3761aea0c478528b129808955be429136eeff003779dd0b8757e3b802bdff0f5f957e19278eabad72764aa74d469231e935f4c80040462ab56094e4a69a82346b3aeb075e73a8e30318e46fdaec0a42f17ccf5b592fb800613", "03df0e061fa2ae63b42f94a1ba387661760deaab3ec8ffabcaff20eeed8d0717d8d09a0eafd9bde04e97b9501ac0c6f4255331f787d16054873f0673a3b42ce23b75a3b38c1ebcc04306d086c57a79d6095d8ce78e082a66c9efca7c2650c1046c6e0bbce0b2cba27c3824333e50e046e2a7703d3328ab3b82c9d6a51bc99b9516ff", "76b488b801932932beefffdd8c19cf5b4632306e69e37e6a837e9a20c8e073bcadd5640549faa4972ebd7ee55cb2425b74cb041a52dd401b1a531beb6dfb23c4cfe74bc84f034156c8f55050ca93236eb73c4e2595d9fbf93dc49e1ec9a31705359732dda73f737ec4274e5c82626dc4ec929e5e2c7a2f5f5fb666181922bd8be575e3", "ff17f6ef13abc0426b03d309dc6e8eeb822300f7b87eff4f9c44140a424098fd2aef860e5646066d22f5e8ed1e82a459c9b9ad7b9d5978c29718e17bff4eeefd1a80ba48108b551e62cd8be919e29edea8fbd5a96dfc97d01058d226105cfcdec0fba5d70769039c77be10bd182bd67f431e4b48b3345f534f08a4beb49628515d3e0b67", "95b9d7b5b88431445ec80df511d4d106db2da75a2ba201484f90699157e5954d31a19f34d8f11524c1dabd88b9c3adcdba0520b2bdc8485def670409d1cd3707ff5f3e9dffe1bca56a23f254bf24770e2e636755f215814c8e897a062fd84c9f3f3fd62d16c6672a2578db26f65851b2c9f50e0f42685733a12dd9828cee198eb7c835b066", "010e2192db21f3d49f96ba542b9977588025d823fc941c1c02d982eae87fb58c200b70b88d41bbe8ab0b0e8d6e0f14f7da03fde25e10148887d698289d2f686fa1408501422e1250af6b63e8bb30aac23dcdec4bba9c517361dff6dff5e6c6d9adcf42e1606e451b0004de10d90f0aed30dd853a7143e9e3f9256a1e638793713013ebee79d5", "02aaf6b569e8e5b703ff5f28ccb6b89bf879b7311ea7f1a25edd372db62de8e000219afc1ad67e7909cc2f7c714c6fc63ba341062cebf24780980899950afc35cef38086ee88991e3002ae17c07fd8a16a49a8a90fc5540be0956dff95390c3d37629949de99920d93096eb35cf0427f75a6561cf68326e129dbeffb8772bfdce245d320f922ae", "70752b3f18713e2f533246a2a46e38a83cc36dfccec07c1030b5204cba4432700735a8cee538b078d281a2d0262110381c5815a112bb84404f55af91652bd17502dd75e4910e062943d8a736ae3eecdfdd8e3f83e0a5e2ddeeff0ccbdadaddc95391310fc657a59724f7e6560c37dc1d5bb5db40170190f04a274c864ade9687c0f6a2a48283177a", "01f3c1333b44077c518cc594d0fb90c37651fb7b2442e71fc0a5611097f1cf7bcfaf11c8e0ac1b1cab54afba15bb9332df6bc64d8032368e3f686c8324b0114e0979dad78a5ccd3fff88bbe89eef89c4be586ca092addef552ed33224e85d8c2f4fba85ac7735f34b6aa5ae5299154f861a9fb83046b0e8fca4db32c1343e02676f283975f43c086cf", "509283ebc99ff8d87902fa00e2d2a6fa239e335fb840dbd0fdbab6ed2d95e8275402523f7ce9a2fabd4b6c9b533288fbe914bde84365a204711d0977a7d698f4614385984dd4c137e4820035dd6737da364edff1bb62283e87a8c7ae8637314fe9b5777ec4ec21276dafedb2ad5ee1aa0ac99e34a6c01c055c8a239fd28681607f65143082cd4553c529", "c17e417e876db4e123c631f7136b8a85bfd6ce66a69180d0cd5ecfd6f037bb1c7bd7908d51f2c485bf9e92c0e1799ee5f6ab834ee481f5eb1a8020205adb4d0f90126d4e7c2c859c5a5f644bdfa9c649ff4f168e834de6f9769429732099d46d0af506ab86c6fd92175159bbc05c75db8e1fa867e6030d64250008d64c857c47caec3dc8b2ffb384d0193e", "950988fbe9d62a66f5f2c492bc8dc944a78eb3796ec37ba94b6a81a9d402ccad03cd8497fff74c5f4a03081c5fecec48574fecb21c1de261332c23108195d3f6a96ff8e433a1a30eda53dd5bb414973334f8cde5510ff759f7c17046cbb5acd8e8c4a6eecf2a9121ec3fc4b22c4daa72678194ce809024cd45c4ebb9ccdb6f854205cdb624f0787480d8034d", "552a212c403b473741da8e9c7b916d5e5e9bcc9949021ae1ca1ed46b7d4a98addbb604d9fff56175b7e0367db26c9635fa7813653dc8d610befdd09ec41e99b192a716106f4299eec8b940863e5a59cf26cdc2cd0c3017f9b4f215812bed15f69e77edf672178e13c55580982f01fcc2fa131ec3d736a55d56504c545f4be50fee83f1263e4d3f3c877cc6242c", "b00c4283dd3d9cd26e44bd97cede6c771cb14f2571b51cfdaae4309560ffd165da025a1bbd31096c3aa8286e2d6dcc3e681b8d01f2c5064ea26dfd0b5156b7a7f5d1e046c5bd1628f8fdae24b03bdf7cf7366900cc013a8cbed9d7f5937c914b08f8c27683b956e1279812d04288515333fc6aba3684dde2292951f0610649d90fe61606630fc6a4cd383649252c", "f6e79457bb6d0884dd223be2cf5ae412a1ed425f1e4012f75951b096aea3b9f3581f9013bcae1aff2d3fc1e5c7e06f24af6d53c2c5c238b71c71cc670b05a7ee5204400026a5c4e5ddec3ad96771e49fae4b0f75ec58049ad9d972e5749a32d90f847f1ed2a1bab83db181e541cf5c8adb6b29ecc64dc25add491d408d3eb3ddcb013de7f5ffb6de9dd7ff300a5fc6", "fe1d71e1d5efa3f712d23216ee8ee9139e66bd648b83efc02cdb4d45a28cf36759ff190a84d14d9471477abefb5aea4111110336143dd80cf81e02f268120cc07d746538f968e9876bff8358d390f5b8e7eafa61ecd236cedaf276bd61865fdd3424988201dcdeda2e3e0c33c9e3b3670125dd1049106cc6df5695fb2dca443233ff440f265bbff055483bac1e859b83", "4c80163562872a965dedd8725652906156ada6e9d999027d96f49289edb92f9ef043e9d7c3377e091b27f85275499454af32317535997fb4aaeaf93565ad481ff7d45d2abddd4df4b60f71a6923ec30496c6ae534dc5427107ab4c5e656a322c7ab058d4c13ec0ebafa76576560697ac98f84aa4a554f98ec87134c0d7dca9184cf70412a324aac91823c0aca02537d197", "fdd58c5ffe88665beb7073c8f4c22472f4bc9390cdd27a42622ca55978b000ab7579f795d4de0dfcaf521b8268980ef1d20277b07567985c0fd5030784ad6c32541ac24e99ab706105a2255fc32935c0fce6fdad9bb224d94ae4eae2a3ff08836618a3adf193630647bce1952b69da4de360f59da303519278bfd39b733cf66820a5e9e971b702f45998b69a0889f4bec8ec", "ff38b15aba3794e2c81d88003e045ac6cbfc9f4833cdf896cefd8ac0c88674727ad9a9fcb9ef36574deea480e6f6e8691c8390ad73b8ea0eb3665c914b0d886546948e67d7987eea248b5feb52346ffdd965d5c835144c3bc63daf325e74b11267e32e58a914ae4521a668839d9445fececa49c5fba41f9e171698bbc7c6c97fa163a377a96456958d6e1d74f91ada56a30df8", "f048c19328d60b4e59ed76940415b2c84c23883198bba5699efb0a1774ad5da6d15390c7b55d77d66f37448fe08107f42a5336408d5322f4b630e3275865fc66dccab39f6e13fabc133e5a441fe352d81c7cd9a25f145a6e2e2417d3b0bbc79eafcd7ad688c02011fd268dd44ac3f4f87b37a84a46fd9e9975962fba92c9a3486deb0c45f6a2e044df4bb79f0feeea432c5008b0", "1b3e5fe6f113cce28a6f8d6f7809d3cec398cabffe9ff2ff10a7fec29a4ee4b54186063fd5307a2be393c9ecd75a37620bdb94c9c18da69b658579676ec90351d10dc33a7cb3b75798b1234f9f684d4a73a0fab2df3d5d6fdb1c1b1514d0935c1f2dd21486f91c2595b2f8f8a500ff443b9305270fb6f3da7961d9316d4ed6a135a31c4a3611d40e6585bbb34f498cd5b9a5d92676", "740db337baa12b16897f17a85fa5685acc85e48338867f8ac9c0198dd650f5dfa7c17725c1262c72207e365c8aa45ffaab6470a0e5afefbfc3bb702a9766064f28cc8b796878dfdd3ca9d0216c14941438fc541fb5be0a13d29a996c5c985db4f630df067a5626db5dcd8df3a2bff17dc446e46e4079b8815da4318cb228c7722684e2a795a0ca56f500ea51951a6a385385d886f678", "1465f2d578d167faa017fe8f763ce3cc8dc1e8371d774ed2a8803f12585296ee71a1f2253dd16b717a81f91f0f3641018a0111182b4e65d884b0a3d0292631ad807cdccc88bdeecb476e76f72b5246a630aff6e2401fa9570f85acb73ccb4e19ef04a932a03d7b7985dbe1e5bb410df517fe362321469e6f8b0e0cef6c31d7aa8ec06aa220620d66cc0e133fdee963589b12320fc9678e", "80c051952fa6f3ef6af0f1759ec3e83c8eb91abee1de360bfa09e74b05af2475a0dbf8f9135aa25892919bbe0515898cfb6f88abc9e1891f2b2180bb97370f578973d55c13c35edb22ed80647c2a7e2884d1ccb2dc2f92d7b6ec5843ade13a608a31190ce965bde97161c4d4af1d91ca9962053f9aa51865bdf04fc23fa35a6fc3c8e888941263a26ed66c2dd0b29b2325dfbd1227c5091c", "9c1e2a1aed6406052eed12b4495365f2f80e9c9645473f3549b607f20910bcd16dc3a4b173ac8d128129cdb7c76ebbc8e9a2a1ba0d822c66b367e790a69ac71f0a60ed4bff0e979148e3f3ee6607c76dbc572ee5ff17c27e4b52adebb4bedddff517f591a1977299c7cb01106f1453b098d29848ba3751c816215bb0d090c50f9e445b41b2c49d4eec83b92ce6c269ce835fd279e7cbbb5e47", "466abda8944d0329d2975c0f2e2afc901f117887af301881f63b714f49a2f692fa63a8871fc0b301fe8573dc9b2689880cd8969e5072c57671e0633b041481dab25e65c9de404af033a11a8070c8ab70ca6d465318501afdd9940c7efbe1bb6d49581c222fad251dba4ee0a98efe22a3c4f74da05844523b30bbad6b080ac8df70a02da80bc9d477dfb869adb211e209a316d5dd1fd89a6b8f8e", "0e89a873e07799ba9372fc95d483193bd91a1ee6cc186374b51c8e4d1f40dd3d30e08f7feecfffbea5395d480ee588a294b96304b04f1ee7bbf6200cc8876395d1db3ac813e1019bb68d27204e514fe4a61ad2cbd1782dca0e38b5538c5390bca626c5895b745cfca5dac636fd4f37fed9014ab46ae1156c7789bbcbb956ff7ee5ce9effa560731d26783dc6ae8bddd53a5d28133614d0ddeddd9c", "fdde2b80bc7a577ef0a6c03e59512bd5b62c265d860b75416ef0ce374d544cbb4e3a5dbd31e3b43e82975090c28bc77d1bdec907aeceb5d1c8b71375b6d631b84a46153f5f1d195bfcb2af6f597a9cdc83782c5bbbb58c5188a87ebf375eee5212fa52523820a83106e8ecd52bedd60d95cd646159774389c07e1adcaa6b6f649408f33399ec6e507d61659696b3dd249996892d5986b654d94ff337", "f5d7d66929afcdff04de30e83f248e69e89604daea782e1d82d8032e91a95c1d6fb2f5578f79b51be4397e4cd7cbc608ce143fdddbc6fb6c43ffdd394a7df0124353b919aeeac025f3eb11ff246c3b9657c1a947fc534ce48e18feffada8797037c6bc7e2d9a9e2e019fe65627b3feb28e446473e3bd413047a2587f0be6a103403cb3c33fdc212dca14d8e386aa511c22308e632f5f9528dbabaf2deb", "332990a8dba55f977bc814436cf386ebbf10cb487a5f6ce83e13741bac670c6810284fbbe4e303547ef411e964fae82854e8c13cf56979b89ecfedd337aad78260060122d13dfbbf8497acb2066ed89e30a1d5c11008bd4d145b5ec353956310536304d8b8bba0793baec6d8f3ff49718a56e6694f8122078265cf5731d9ba61292c1219a1affb3679576d4998290aba3684a205c3469d40761a5c4e96b2", "efbdff285027610f03182009c89b953f19721cfcdb8accd74bab6ec4bdf3f555ab902cb0dd91284269d140638aaabd211748aa4da3b18cddc653b57e461b9ad8491807c535c08fe97d89eb587c6af19ca152e72479626ab764e8b62da89fefc8354c75a44851f985746d78715a5a92798dac1a4222be27897b3f0aa63d596aa7378545f49b259aa8518c3def8a2ec8f7aa956c43668c8717052035a7c36b47", "0eea9bb83bdc324fd21b03669aa922fbebc448e7d25e210294c07862cfa6e061731dfb67b4810633f4dbe2130d90fa1c65843af436e74219d213c4458dcac1c48ec4541fc6e3b7918ab2bc621aedda53658050900c3865ca57cd5dfa1d28576827401956d2dd8b861fa90ab11bb0b544ded9bd3d62e3278ed484e17db8f2d5dc5ea4d19a0e15134ba6986714c2b22c59c2f0e517b74eb92ce40d2f5b89e6d79f", "25da9f90d2d3f81b420ea5b03be69df8ccf05f91cc46d9ace62c7f56ead9de4af576fbeee747b906aad69e59104523fe03e1a0a4d5d902352df18d18dc8225855c46fefeec9bd09c508c916995ed4161ee633f6e6291cb16e8cac7edcce213417d34a2c1edea84a0e613278b1e853e25fb4d66ff4c7ee4584e7f9b681c319c874d43502534e8c16a57b1ae7cc0723783807738a55b661e617ee285bdb8b845607f", "a76b6f81372df09322098868d469fb3fb9beafc5edb32c674974ca7032966aaca5b5c9bffef87bfe626bd8e33d1c5f054f7d5acd3b91ff95324d1ae39eb905b9f2694fe5cb03486cee86d2f661a751b0e6c716a61d1d405494c2d4e32bf803803dc02dba2c06eecf6f97fb1f6c5fd10cfc4215c06d627c46b6a16da0854e4c7c873d50aa1bd396b35961b5fa31ac962575230c07c369f8fbc1ff2256b47383a3df2a", "f9db613812f2259972d91b1598ffb166031b339913925ee385f03b3b35dc4b2f1ae78a3c3d99c6ff6a07be129ce1f4b8d994d24988d7fbd31f20535d36ab6bd0592cfb4f8c1ed9244c7fa8a3c46e91272a1a40c6cfcf261c5658476c59793bf1a3775086e41a0492f88a31e2d9d1ce75cf1c6b4b928b3545d838d1de6b61b735d921bcf72e4e0615e9ff969ef76b4b947026cb016e2660ba39b0c4c953369a52c210de", "e601c7e75f80b10a2d15b06c521618ddc1836fe9b024458385c53cbfcedd79f3b4239598cd7b9f72c42dec0b29dda9d4fa842173558ed16c2c0969f7117157317b57266990855b9acbf510e76310ebe4b96c0de47d7f6b00bb88d06fad2c2f01610b9a686079f3ed84613ba477922502bc2305681cd8dd465e70e357534503b7cbc68070ad16d9c51de96ccf0aae1599299331c5655b801fd1dd48dddf6902d0e9579f0c", "ee5ff4ca16d1bde59ffaf2d064eac9141c1d8f120ea2bda942b7956ba3effc5f1e725a3b40b0b9223a14d7a50df1681d14ca0e0eda7bb09c428fa3b2701f83a7a3e139485a118f6287d266dbc7fe68c87b35becabc7782537c79cb8165bdc40cc103d7b6d4b627fafa0e4113f92341ab90ceab594bfae20dadbfafd401684584598941f1ffb8e23dc8a04ecd15376cda6d849fe0dfd177538c62413622d172d9d46e05c450", "1daca80db6ed9cb162ae24aae07c02f4126f07cd09ecee8e798fa1bc25c26c644333b63731b4ebc3f287f2318a820c32a3a55fc976576bc936f7384e2553d2891e3771ff24dd4c7f0256906460a8f12d30ed2b23583a0259cb00a9065a757d654d6e4603e7c7eb4a8426b527ae8a849d9350e9094b890367df3e8b23ad2df4d7dcce416bd8ea3badd037f53f7b07c02e5926515f196d62aeb9b8b14c863f067fc12c5dfc90db", "27ff4e58a34ff1fcd66855d014ea17889a3cf0021a9fea3fabfd5b270ae770f40b5439e00c0d26bd9766f6fb0b4f23c5fcc195edf6d04bf708e5b0bced4f5c256e5ae47cc5651e51cd9fe9dc5d101439b9bc5cc24f76a8e8847c72686e2af1ce7098ad7bc104dad00c096a6d48b6453322e9cd6773fb91fb1eabd05dc5185a9aea07a2f64c6fea9897681b4428aaffe1fe5fd3e8ceb890b12169ec9d51eaabf0ca3d5ba415770d", "75e2fb56327983b04f640717be8cba6fef3655b4d8e5539587d6478356ec397efaed818b8425d052778eb30ef0dee656c52c2aeab079ed496ae4441a365f2130432c87ba757e25b4511656ad15e2eff84d342331fd2814d1f1d11af65d98a424c115ba183437c0d0aa55f5c44b8685028a47d89d0d36a0f20aed510c366ab338f074a941b404fb349caaec821e0850a627777cc8f5abce6b509290027a2a28ff1db62a5ed2f95fc6", "c6ae8b6a060917cd498aa7874ad44baff73efc89a023d9f3e9d12c03d0b7f5bcb5e24e1bc2ab2f2c67b9a9d36ff8beb51b5affd4a3510361001c80642955b22ea4bf28b81a5affe5ecdbabd8d17960a6af3825a4522fe76b3d720b5d06e66bff5379d7a8de1f5cc3e7bb75163a854d77d9b3949bf904b6c4e568682f0dab7f217f80da7303cfdc9a53c17b6b51d8ddff0ce49541e0c7d7b2eed82a9d6be4aec73274c30895f5f0f5fa", "606c9a15a89cd66a00f26122e33ab0a08c4f73f073d843e0f6a4c1618271cfd64e52a055327deaaea8841bdd5b778ebbbd46fbc5f43362326208fdb0d0f93153c57072e2e84cecfe3b45accae7cf9dd1b3eaf9d8250d8174b3dade2256ecc8c3acc77f79d1bf9795a53c46c0f04196d8b492608a9f2a0f0b80294e2abe012dc01e60af94323c467f44c536bf375cddbb068c78432843703dd00544f4fff3eaa1a5a1467afaae7815f80d", "88b383cb266937c4259fc65b9005a8c190ee6cc4b7d3575900e6f3f091d0a2cefa26e601259ffb3fd03083270eb63db1ffb8b4515ec454d12f0944f8f9f6869eedc2c5f1689766a748d74e79ad83ff6a1639aefdec6109342dead31e9cead50bcc00c5b2206e8aaa47fdd01397b141880490174141a1e6e19268378c1b54a84aba60ca711fd72f7df88e120dfea2caa140085a0cf73342f3c588b7edfb5b5e5ccabd68a32364746d92d536", "dc0b293f1ba02a326743509f41efdfeeac1efc45137ac03e397a3273a1f586a0190cfb4ea96d6c13ca692a4de6de905c8338c3e29a04cbae76272f568b9d795cea5d758106b9d9cff6f80ef650d6b7c428ea3946c3acc594907fe4227ed68faf31f2f6775f1be5139dc0b4d73ed6308fa226b9077561c9e4c7a4df68cc6b819b0f463a11b9a09682ba99752c4db7aea9beac1d9279f2c2675d42b551d27aa2c1c34125e32f2f6f45c35bca45", "5d801a7413311e1d1b19b3c321542b22e2a4ccbe340545d272abede9223741d9835a0fc80cc9da97a13f8bb4110eb4ad71093efba165b1edad0da01da89d86726e0d8e42ae003b4b50297d233c87da08406f0e7fc58ba6da5ee5ba3d2d7142cbe6632734eb2e7b7863c15cc82198ee8f9a0ae0b7f93bdbda1ed269b3824d5d3c8e78513815b17a4c0cc8c9706b9c77423a309ae3fd98e1e05cdbe9e2577834fd71f964301b10b66c316a2d8f2c", "2fd32a2bc15a9e96a100624404fd0a4e54ba9f8c0543d8ccf7c5c2e35f5e8c3c11dfd497320aa903900a4ca55a2b323b3ac4a7cfcd01bf0b448db8829072bee6b77c3d7bec2e1d8b414d907288d4a804d2379546ef2e2dc628269589164b13fceb32dba6fd5d48a956ce0b5c3eb28d894a95af58bf52f0d6d6cbe51317152744b4ccfc918ed17fa6856478d580b389016b772e1d02e57d2217a204e25361d91d4845a3fa20fefe2c5004f1f89ff7", "f537b437662759bef8bd64368536b9c64fffbddc5e2cbdad465c3966b7f2c4bc5b96767ef40a1c144a4f1cd49edc4cc5b57e7eb30d9b90108f6fd3c0dc8a8808b9e0bd13aa3d661c4863637c5e4ba286553694a60bef18801299ae349df53a355051dcc46a7d003c4aa613808f430e9db8ca7dfe0b3f0a4c5ab6eb306aeb53e11a01f910064fbe6ca78b2a94fac34a2602f73de3f275953e13ff5c6bb5c39b82321ead17ec0f8ecc479e6afbc926e1", "1dd9fb7d5b5d5074971e69300720014deba6fbdb942bd29704cdfcd40fa5281d2a1b9f5b776183e03ff99c29587f10e8d325cb49c5c93e94f5132741b92c4086eec1374dea5c1e772cbb230c7b31f3e962eb572be810076bdb926b63732522cdf815c3ab99bbc164a1036aab103cac7b823dd21a911aec9bc794028f07b7f839bae0e68211286441f1c8d3a35b281fd321312577bbda04f643ecb2a74ec4527bb5148dbccbeba749f5ea19b6072366ba", "5bd63737449de2d20ca63943953338ecf4cdd6cd0a726241adb04376385a809cc6ba0f3482a310746fbc2cd5eb214f03a14cdc548777fb0d048d659cd75a962e490c4fe47affc2430a34b10275e4c76752a115aae3a24d4fb4fad89ce4d79d65de10292f3490bfdaeabfae08ed51bda6ec8230e66cb07ddbeec26e3ef68dd71c852900659fcf0c963f4574ffe4626a33db9abf0873dde68b21138498b81e8cc44d354be4073615889a7ddff633b5447d38", "a683ec8250506571f9c640fb1837e1ebb06f123e745f95e521e4ea7a0b2b08a514bbe5bdfd316903d1d6a05f5a143d94dab61d8a3a146ab40b2d6b72df2f0e945875a8aa7051ed115975f6f1567cfcbf04c5e11e3a7027b8e179ba00739181ba10b028e3df7259d0712f4a6cef96469ff737865b85fee2c2db02a6423e32505381e18a1e0b4ce3c7998b8d6b1b5e09c3a280b85486d0984c9e193b0ad2043c2bc4ad04f5b00a73956715937eebf6b3e27afc", "4df9d160b8e81c42930c48956fcb46b20b6656ee30e5a51dd6317876dc33e0160d31280fc185e58479f994991d575a917073b4439919c9ac49b6a7c3f985211d084c82c9d5c5b9a2d29c5699a22e79de3958d7b0e856b9aa97493cd4563aaa04fa3977a9bb89e0bc06a82296bdc76d20c8d393770176d648712454305fdfcf4e117d05acb5a5b006a9f8d0dc66dca708c4e4103ca825d2331750685c44ce3d9b3e753455580f4d6ac4533edeeb02cebec7cc84", "67bb59c3ef5ee8bc79b89a673e331e581215076cc36b68f517ca0a74f74efafe9dcc240e6d8ca4b21019c27d6c9289f4419b4f218eeb39eb741c5ebebfe0ed2f6faeec5e8c477acf71907990e8e288f4d4049111779b0635c7bbec16b76493f1c22f645745fdac2b383679fee573e4f47af45ee08d84f63a5ace4ee1c06fa41e2e6e14b7bc392e38426813087a3a461efc62ed1941dc8f1728a2bdc04fde72a0b786558783c84abd4bd100e4926979a0a5e707b1", "d341147169d2937ff2373bd0a9aefa77968ec8f0d993c6f9881eb174a1911e05cdc45993cb86d149a754bbe321ae38363f9518c50dd3faf087ffeeeb6a058b226ccab7858c00ba6de0e8f4d034b1d27508da5cc473f3a413189ee6fd912d7750486912944d4dc34405ce5ccc3885fb0aabcb922bcfa9081d0ab84c288022bd501235a835eb2e1124ed1d48fd4f8682da8e7919321031326502273375625c4e3a7282b9f53452195e53c6b4b57cd5c66f621bed1814", "27e7872a54dfff359ea7f0fca256983f7600236e716e111be15a1fe72eb66923ea60038ca2953b0286447dfe4fe853ca13c4d1ddc7a578f1fc5fc8598b05809ad0c64a4363c0228f8d15e28280837a16a5c4dadab681e28968ae17934639fbc124bc59212138e494eecad48f6546c38366f1b7b2a0f56f579f41fb3aef75dc5a0958b25deaa50cb7fd1c69816aa9a51874a98e57911a33daf773c6e6166cecfeec7a0cf54df01ab4b931984f54424e92e08cd92d5e43", "13dcc9c2783b3fbf6711d02505b924e72ec6736131159017b966dda90986b97522bf52fd15fc0560ecb91e2175322334aaaa0097e1f3777c0be6d5d3de18ed6fa3444133486068a777443a8d0fa212ca46994944555c87ad1fb3a367db711c7ebd8f7a7a6dbb3a0207de85851d1b0ad2f4149bdd5a5ba0e1a81ff742df95edee850c0de20e90dd01753137cb8f2c64e5e4638ceb893a3879ae2c049aa5bce44d56bf3f325b6c5029b2b8e1b2da8de7d4e48ca7d8f6fbdc", "9ca875115b109eab538d4ec7023600ad953cacdb49b5abe263e68b48eafac89a15e803e838d048d9625972f271cc8f36344bed7bab69abf0bf05979a4cfff273b82f9961626509765fcb4b4e7fa48212bcb3ab2b1f2dd5e2af768cba6300a813514dd13e4d269e3d36548af0cacdb18bb2439ec9459f6d847d39f5598304ec46a26d75de1f9f0c2a88db915bd26e45e1f1e68c5b5b50d1890e97a3803c36755f026863d14176b8b57f42e91d3ff37787f9b38e333e9f0433", "ec006ac11e6d62b6d9b32ebe2e18c002353a9ffd5dfbc5161ab887770ddd9b8c0e19e5321e5bc105add22e473050b71f0399327c7eba1ef809f8667c1f4e2c7172e10e753705e9a083f5bce88d77521225ecd9e89f1e1caed367fb0275dc28f620fbd67e6b176c9ae5d2659e6ec662116c9f2bbca3a93043233a4861e0688db6dc1800f752c5d58aa5033c250c891d9126e534ed921a9026eb333333fa8292059b8b446f336ca6a0cb4c7946b6aea3831653122f154a4ea1d7", "23deadc94481ce28188f3a0ca3e85431964cb31b60fabf381e6bd45ef0332bd4dde774b0281d317dc2e7d0c298fcf8625fa734126968df8b68ef8a35c325d84ba4fc53936ff3ffdd8838d2a8cabf8a9cac54aa444ed9875944e55994a22f7fa8538b1e983b57d9215fac5c0052029644044e790ce2f5044655608c1d7ad3bb862203ba3aba3b526606f273d342ed5721648e3f600942d3f7546f679161436389d879dd8094e1bd1b1e12cde15cd3cda4c30a40835665e4e5cf94", "94701e06340114f9cf715a1fb659988d33db59e87bc4844b1500448960af757b5282f6d52967a6ae11aa4ecfc6818c962b084c811a57724f5d401191567f24ce917e4f8c3963474fdc9d2c8613c16f62446448b6da6eeae54d672825ed7606a90e4611d0e318ff00566862c955b636b5e81fec3362e8672ad2a6d222a515cf410482836deba092a51a4d464dfbbab35c50a33437ac16a88256e9e23ddd3c827cc58d3e5000ee90b12e4c5175c5733662d4848ae0d406c2f0a4f498", "735b0758d5a331b2304f01081172eb95ae4115de651b1a6693c5b9543de33df25d9f421dbaeca033fc8bff57313b482778005aa9fdcbca65c643da2f3320e34197868eec3848ff3c70d7ac7d910fc332e9a359f892ae01641be253013b554a0d3f249b3586b1857e5a0f9482ebd91432a852b221f4287a6e81ed24e8064645d5b28ab9a13b26cc1420ce73dbc47b31acf8a871601022ce23bc443b1222ce9a037a2fe5226295feb4efd4fd671338f459ae146032697cf82fc55c8fbf", "c48d94f14549352790079fee69e3e72ebaa380510e3581a0824066413e7044a36ad08affbf9b52b21963d2f8e092ff0ac1c973c423ade3ece5d3bca852b894675e8173290529226939c24109f50b8b0d5c9f762ff10388833d99bea99c5ef3ebb2a9d19d2231e67ca6c9056d8834730605897426cd069cbeb6a46b9f5332be73ab45c03fcc35c2d91f22bf3861b2b2549f9ec8798aeff83ceaf707325c77e7389b388de8dab7c7c63a4110ec156c5145e42203c4a8e3d071a7cb83b4cd", "553e9e0de274167ecdd7b5fc85f9c0e665be7c22c93ddc6ec840ce171cf5d1d1a476743eb7ea0c9492eac5a4c9837c62a91dd1a6ea9e6fff1f1470b22cc62359474a6ba0b0334b2739528454470f4e14b9c4eeb6fd2cdd7e7c6f97668eebd1000bef4388015630a8332de7b17c2004060ecb11e58029b3f9575040a5dd4e294e7c78e4fc99e4390c56534a4e933d9a45460f62ffaaba25da293f7765cd7a4ce78c28a85013b893a0099c1c128b01ee66a76f051dc1409bf4176e5afec90e", "dea8f97c66a3e375d0a3412105ed4f0784f3973ec8c57b4f553d3da40fd4cfd39761de563ec96a9178804641f7ebbee48caf9dec17a14bc8246618b22e683c0090259e3db19dc5b6175710df80cdc735a92a990a3cfb166461ae713adda7d9fa3c4cf9f409b1467f3cf85d2141ef3f119d1c53f23c0380b1ebd728d7e932c535965bca41a414b6ea5bf0f9a381e098d282a554a25ce41980d7c7be75ff5ce4b1e54cc61e683f1dd817b8e2c1a430d7f895e5e7af13912cc110f0bbb95372fb", "9dfda2e2f732867e60ed2b5fa99ab88eb82dc7a54334d02031258beef75fa4bd6962a1083b9c29e4eeb3e5ab8065f3e2fc732675b8d7705c16cfb4ef7305eb58120f1af5ddc55872a2cbde3a48661a0598f48f63e2e9aadc603545e2b6001748e3af9e86e1830af7b84ffd3e8f16679213d37cac91f07af0af02b37f5ed946ef5c955b60d488acc6ae736b10459ca7dabeacd7dabcfd656511ac913174f6d99327be59befe3e463a49afbb5235f0ce2840588c6edfbaaba00a4211c0764dd638", "ddcd23e8b9dc8889b8599c721e7f8ecc2cbdca03e5a8fd5105f7f2941daec4e2906c654210bdd478374ddee43ee749a920ee91872e057a1157d384dcd111266221b3c79774476b4862fe450704ff2c5353e9a936cac87c96515c28ed4c830335a55d084cb5873c5fd2dd907f3266d8eb7bf13b6dd7cd4966982a0949efd8e428dae13daee549e01cc3c226211d6307823f742c5ef2155601a4644c46eddd603d4abd959c6d242e427768df3b1e22d87971df58a1564b38311a897c85b497a72556", "39016647acfbc63fe55a74598bc1956eaf4e0cb49d532c5d8323fc6a3f15a0231597f06eafd74ad245e672bf6b21e4da503cb5bf9d15e9038ef354b38807564d91f38b4258378ccd9b9420a1562d7136196822a1291c913d83c4cd99fd8d420990c72cdc47607124de21da8d9c7f472fdcc780379f186a04da93cd87628abf323c8dadcd7fb8fbade37d7d2b5c9f9fc524ff77494c98f42f2158a6f68c906105ca9e8bb2df463863cfc1e9008d8344f55c4e3203dde6699b59812d49ce1279fa1c86", "02cff7567067cbca5911664c6bd7daaf484181edd2a771d0b64566c3ab08d382e83932cdd7b4dbf86c9cdd1a4c353a511e68afb6746a507a9cd385c198246f4543d606c6149a5384e4ff54c1b90d663dc7a4b91aeac3cf716db7ca6f9a1914e3a33efe82e7ccc4215999c0b012782402db4726db1d7d1c73571d45739aa6fcb5a20eeb54a84d5f99902a8d356cbf95f34c9c28c8f2badfbc08c69233514493c0c04963268c88bc54039ab2999c7b06cba405936dfc43b48cb53f62e18e7ff8ff3f6eb9", "5764812ae6ab9491d8d295a0299228ec7146148ff373241a510faee7db7080706a8dada87938bf726c754e416c8c63c0ac617266a0a4863c2582412bf0f53b827e9a3465949a03dc2db3cb10b8c75e45cb9bf65410a0f6e6410b7f71f3a7e229e647cbbd5a54904bb96f8358adea1aaa0e845ac2838f6dd16936baa15a7c755af8029ef50aed3066d375d3265eaaa38822d11b173f4a1de39461d17d1629c8df7334d8da1b6401daaf7f34b2b48d6556ae99cd29ed1073926bcda867421832a4c36c7095", "4df3043cf0f90462b37d9106e67366d112e4938c4f06abae97869531af89e9feebce0812dffe71a226de5dc36be652e26ef6a4be47d9b2db5cdd43809a565e4fc0988bfe82037c505dd276b757b785203249fd083fb474a25acccc9f38dc5164ff9097e05989aa6e280739a755231f93670e7226e22046914c155bf33d135b3f736ccca84cc47ae643215a054b54b7e13ffcd7ad73cced9279dc3210b80700fcc757acfb64c68e0bc4da05aac2b6a99d5582e79b303c88a7ac4dd8ed4289516bba0e243527", "bf041a11622715426c3a755c637d5f478dd7da949e50f05377bf333f1c62c671ebdbf9467d37b780c25f7af9d453fc67fafb2f065a3f9f15d4c3561eeaa73fa6c813bf96dcf02430a2e6b65da8d174d2558110dc1208bdcb7898e2670894c0b9e2c894da3b130f57a90ec8ea1bffd27a37b4da4645c546b2b141db4e2c919154dac00e78dd3eb6e4445974e3bb07905982da35e4069ee8f8c5acd0efcfa5c981b4fd5d42da83c633e3e35ebdc959bd14c8bacb52212b4334f94aa64d2ee183861db35d2d8a94", "a170ceda0613adc9c3a1e427f07beacf3b16ed69fb42b6bc09a38d803f632ad2929dba215b85683b74e2feb1d18fe17d0ea0db84d1be4e2e73476917a2a4cff51d6eca7c5e82232afde00dd2286a4c20eb09800b4d5d80e7ea35b6965b9792d99e399abda8cf32174ae2b7414b9bdb9d63e148f7357635a7310b130c939593cd3479164724011966c4232142df9966f09422f34f20b30af4b640a2c6d3dd985fe0ba3dfa9083cbb9b8dfe540ff9f6c608d18481213040768ef33300d773f9890c724ead320a1e7", "929477e9c2d0bbad3429a0e0de776695255013108261dc6404cb09828770e274d8bb650a50e490dfe917fc2047b0f8ee72e105927d9fa70523c727778cbf6ae876d641ad562938c870d12f2e047bb78920739dba0c3f8ce1fb77589623a5f1625f5d6ab81940c7dfc3dc3a641d82b2813629bab8282999317d6b93842334f123fb4693a9c2c9d8ba9bfc746642dfbd045cd2021b272eab7358aa954d453da53fc5392dfa7eb881f6f53809b692d27f3366595ff403289efcc691e118b4744a1147071d8909bef1e8", "3e98bb14fff5bdf7db38a3960dc55ca7d02333daed8712cca13dd5bffd114636559279db72554cc0a0ee1f7e15557d77cab0f2f1131f94fe698db81be38300a856a5eca85e5cf915fb7b6f38ccd2f27350e62cc30ce10ffe835118be3d435d2342ed3d06199b7e20c8e34d68902f0ab8745bd8b7d5b863d525c1f5906d2dca598db8a0f1e67736182cac15677579c58b8c670cae1be3e3c882153b2aa2988933e579ec2d6dbb00c671da64443dfc027dee6dfc3233c99758304570a982bf9b2eb59ccd70d0b54c4b54", "aa12c7fa50ffdc2811c1872e4bee15f43e6909212385c872eb489f7e06dc1787043f56126f8373bdfa4b3f61405c73dd4dfd3f40aa5cd207e8520849c26f67716a46c0989a99efff42f24e0736e327af8e607c401a1bac77341e9a78c91e35d55b2457bdd5317a405a1fcf7a2a23de68ef92b65819e8aa3807c545361dfc9fe89125123492da958dc313cb5d03cb4b192c54ac6b27fcbc498652f5ed36b587bb74942b3ad453a8d79e5ddc06ebf806dad5046b73251064582ef5777dc530f8701701761884783fdf197f", "83e615cf6e17a29e63945710b548a6d9935850eec69830841e26cb6071e908bf72c87cf079ffb34c5eb1a390def72d004a9488224a18e189aa1092a0f1135712834d257a53dc1d0e2c6417d8f472ff13b181910f4c93a307420d44beec8875d5219a3160b8e921434ddf3f71d68db1c1d5c39d68edb7a604792f8b4e31ecda7895c99fc7031a5b98a22009c1da005ac8fd2da0b5d742743f5712d12fd76d11a18e487776ce21ca0d6e5ab9ca6d8c394c321b91c14e291399a642721361811a73b7392e8603a3004e7060bf", "ae1a8f7bfe4b1a0fa94708921dadb2c20b938239d7b9a2c7c598528f20f49764d322ebe85a5b2ea15563cf2f2304baf55d6607c52e2e1160859dcb7af6d7856899eada0e9128a180d3de6fed9334ba52b80c5c362d5591a0ec30f86d37a399927eb1c53076a12d26775522c511c83eb5b7abc2a00bd2dfd5627a8febba53d85f9b74c4b7f0c862ddb0d9298899b646b774d6cc23e4e23ab47174fccd34499253996d5e0917210e2f6daa1685f89f2f1fdfd5509ebc38191d539ecfb54ff0f5bbe6ef36ea35d425af6462f518", "1d033e06be253ab800c8176d3a9650ab2a5bcaa03e11ea95fb9ab3834b41eb0d1b2bcecfe219364c3104ef65a8d692bd77c798548b7d9a8faf7f5172db24ec7c93006d6e9839368291b8277a82c034a3731f1b2e298d6e0282ec8a7902e4f844d132f1d261d171375c646065e201849f2df73e3748d853a3122c2206aac92fea448500c5418ecfb3d80e0e6c0d51f85831ce74f6c659cc291f5348a1ef8b949f1b2a753633e382f40c1bd1b2f44748ea61127b6f568255ae25e1da9f52c8c53cd62cd482788ae430388a92694c", "104bc838b16a641749dcf73c57b207ea3bcc84381170e4ca362065a3d492e892b426a1f4fd82f69461d1ce1f3aaf8fc291ea30d6667e7e1aea4c44f7d52a5fa6d34709e6658483260ff5da76bfb74e7d194ad40dcac00daf0e45e74db4bc2248100a8b256b257278c3c98f1f2e3a80cdb812352aaf4155b3a4033999fb9fe7f506994fcf3a8db31e9e5ca8ef8c2e9c6326ca5b0803724ba641950eca877fe6ed6afc2e014651c56d0e6a61eaff7c5ed0b861d4bebe42904c0a568c26aa8abb2e97da2bfb40f14eafb6bf16cd208f", "5b92e4a175437d0a53eb10de2c56401720b11715a034459ebf506c3fd6534b5e817a0f09deac4bcfd353301d8d031b1331582ac09189b48e6ccea444655866c4bbd123d45ebabb774f877cf12d33b84cfca4a6a94f3f98869fcf2bbb6cc1b964c2438c2f348bcdf9001dce60a4706d20c169a040baa61cbeb0b8e58d505e6e3739ab03e110ae7efdf91347474033defbd1e86af322ec6456d3394699ca7ca6a29a70d9b10a38fe666eab2858bfe12dacb31568549c826c15af5b6fddf779954351be1872f04e53db7b3b5fbf61fd18", "401cc7bd9f8227efaed70dad83fc8db3bd38efc166f0f11ab142c565c68ba9db680423a3d698b6f3476ef440051fd20b93f6a2ed045825567df5a65e3f62e4442ec396ad260a16a13a1dee46c7e8d88bdd7edf223ab76a9a787c1f4fe9925c051a4ca0e77a0e78baa29f36d193c862fd3a60653f544ea9e3f75f2f553891be8c1fb882f6a6aad118f576f3c2793efc67221b37a45ab6137434f6228cb002fc137b91fb8572c757f00736879453d64a8a868c131810ffdad9e9d028d132157ecb1da675d54047d19b27d3258c9b1bca0a", "c20cf0354982ca6a19d9a4dbf78f810934db2373941a12c263adefa61a5f385c859bc47028829c531dc25ccc0004c7510e707175a102ec3c4b4c933e3f52033e67476ff5f864c446c042a21e6037f7798363d20267891b965879fde80af6b59d77862e3a229af01b7ac78b578e94bd9f9b073c38a627c1864df0083aabb17024bdab6c3c0f0f73d31d59480523a2f23b78baa0385c15f290114305d7f98786b7dbc17a8c2aad97448e8ea389e68ef71091a6a9735ac12ca5497b9171da11a93c28d3273f58b74e2e46279d3ce9d0b20d19", "e2365c2754073b511f16a1881ff8a537541ca7362ae7b84223d3c7d1d49d03a37d6d05dd2b819af9705c015dacc9dda83474eb14b7d5fce6e8a8f8c58e870149338d320e5ae476da6749af45e65ffed550d225a39dc74ffd93ba7da476985d6f44e90fc8e82454496260458431804d802fe804d825f611772f9710667377adfb1a11e4275bcecb42175c515f6a9439a359824f82cc9d480954364e6693099a821ace362e6c7ecbe68be8823bb5b49b4f23ad81b64139e3b63d9d4d298a842f013ef0d91ce7915ee8f816c70ba2aa3994216f", "9c43944676fe859327096f82049cf69e48b98715878400fdf2805e0d5ee642e6cc9c43739f418b701348a033c5cb96bf8702fcd2fac9be58262a843c1e4155ed8a1724b6ebf7cce659d88a95a0c54deb2d7d9574a45219b6419ee173d1d8fad3ace47c962b349abe1048565df85bbd0eb9b11698258c23598023a00fdd26573e41951452027125c6e894a97736ecd63fd15b29a55d8dd9dab7e2e18f541a2e341890a61b7c896e7dc67aa82f3479dacd4a8ec7558d40c34d9ae4060e13718d676c2450258d83de8a86e012813693098c165b4e", "1c707c29582d98a0e99639211102f3f041660ca03ad0939fe3855b8c1b22d6a9b8673c93e3eabc0ab231509b2b0d73c76a290a363943d12d2ff0ea30c6dd54eda753767effe04cabb4c3966388fa4c83a1906a0f48519a5fba9aeb585e0f8c45d6123a75ebe98fd1d0272f733a3925119481a321fe7509346c05128302851ba17a137f956f184e057a305e79a148727a5926de6854eb0314d5492fd735fa773d99ea34c95ca7546bd3a3aa8e66bcc6d860cec3d35d0e2165d5fbe8be99b6e7967df6693e5a6243e94c9c4a2528ae6305cbeca209", "8f1e88103ffa378f062cade0ec509bec99a5c73fb273e79dbef24abf718ac26ac23dfd2b8932038ed3cb9637b71643c161142019f45b25b4fa4c52356737a27027e805ec635154327a66bfe64efc6285cca98c34edc7fb6c0766970a545342cf840aec0a5ba1dd3c6949be4fe97b0f8c8186de07536fd9074db34d09b2f08af9dcf9424d6edbf9cd044102c0e5dc35aff78c36d079dbd2c500e19c8c985ae2abaf6b2a20716bb719754a8840ce97632116c4d0b0e3c83ccca27f11c4204b76b5d6cfe6348a9615d8e4af53500dc4c2cabf12ec8c76", "b9a0c28f1a6156992c103a84655fc6e654fa6e45e45819513afa797024717c00cc195994512fd53ecd1e12dac4d2448e0c40308382312084d2111f7db147b2e6589ce6d977f6115f629508167df8f45bac98abd49f6b272bcc4fd874dd5e29fb6daceb2d727a2a892194cfb9269eda00626ac89b4e74bd29b21e9f6ef18cb69889a02d4f0a06a2e5718899c1dc3b051c2cfa29653e782f87fefa478e6465bf5ff27f8b6abdb500077aac97100bd955ec535a587d66f23354be51cd8170289344bac9451f74e8aee3639f7c09981f4885e018912324d7", "456844a34ae1074246f8f71eeef2010ec8733265bed7c1cc60043d770edfa320cbd4284a94be2574337e16d27f125074ebd7e99031f7abb4547b9540a7b0b5148ef501b550dd929f3dfe39ac65519f563e9254424aaafa05b1d37c16c771882e9e25d4906ac58603da749adf686932cd73d81e2658134fe69294c7a521d257eaf2110c667fc9d6f09b52d24b93910e532184eeb96eae9d9c9750ac3c39e79367431ac1af7011172d0a8be46a31010219a0310a733068c589bfc4748f3626aa4ff8d355cc893d05111c287c9992e95ad47481a6c42d6eca", "c5c4b9900b9727bdc24baa544cad5faf8340be6b3759361f53889f71f5f4b224aa0090d875a00ea7116772117dbefc3a81c6950ca7ceeae71e4ba975c50d61fec82e6d9448d3a0dfd10bb087bdf0673e3e19fa2aaa7e97eebf71f11b86034fcf5a61240c71444ac3da15ef09b27b3523d37d309e8722380f835c1aee4a767bb027ec0674040853e5b53d6a31657f51acff6d2487860becd5ce695696cfe5937f4a0217b69e01cc6facc24dfe5f5230b8692a0b718e3b3c789d682db36101795a9a5f8bbb838c3679be72f7941a1db180135347d0a884ab7c", "1781df2fedd2c39137854737d054cd3ed16b0ade411e41d97888ac900fdb46d9ae26b3d2dd07e118fd57eabd0dfd03a55793c76420666444865371adffc9b2f35068a0d70f9cfda1ac27ccb4beff4ffa5b8bb8bddac843386675c38a181fd0d935d6d51b25d78e7ff4ecef27a9853c0f0d2879c395ed1c4883987d123890d04f851c3e042e1164c68c0d503de16816f4b0e554236e5f4c339ea11d01ce652f6208f78f457a2417a97c0a6a240f443262def4b6763abf53e597bf1a28f907dc7cbdc751a234ea7d75710ad5ab0c37e8e9805102a375abd44011", "8963552ad1e729ead07750df599d734157aaa4bcdcac17e8eb19b4f99cdb162686ff433137aa4e8a0cc8df0053999196262115aec326cf37567d9ba4760e0ad21d5763977f1ab9b35c0fc667890fa87fc946ceb776a811b5adc69446bfb8f5d9908029dc5aa38db816e4a4e8f98e5a48cf0a01627031c5bd1ced8bc1940dcafe4ae2f1199b186468eafc07e96a89d95dc18ef0fed3eda5b58ce58f221a47ba5311313cc680367eeb058fafc7bcadce5f520b6371489d9e529278ae6ee2650a85aed82896879038bbd9aa8d685fc9528943ccf2235cdf69a86464", "23ceae3008085134433f5de4b47bafe0f443d443491e6cd47b216dd2dcc3da65239515a6e6b9beb9a939ae9f1f1f5e11f88326475e0962f319d9bf75ddfb4a46e7cc3f799d7547f3c0b2e089018b75787b82ea1a7295e7411f4852f94c94170e98bb0647923b8eb7d184038e56560da46085540cbfef82b6b577c445d038f6c93fbfdfc96ab3a0191d20a57b8610efb4cc45cd95198198e6f80ac46b0601511885f650eb00992605be903bcb46cd53c360c6f86e476c4c9ca4ad052eb572bbf26eb81dd9c73bcbec137aea6ee27aa97dadf7bef733fa1555019dab", "c0fd31e82c996d7edef095cccfcf669accb85a483ea9c59f368cc980f73da7202a95c5156c34192ae4ebf773c1a683c079b17ac9d08b4265b4054fcddaf6666ca50f38f1a2ef2497459a68c06837363a526e850ecfbd223f55dba67db017eadb7a9139abb5bf3854834478b838aafa16c5ee90ea52fb2f7b8db2bcefb85b06fc455c2b6c27d0af9a49dbf2f313bf2599370637393e7972b31d8bf6759f3e6115c618e672831f84d76ba1879c754144e1df4d56b1e264b1797dcb8ab165040c8d20b931071081d7f74fbff590bdc8e888e71acc6a720270da8db7c821", "936fdab91fba396e4a8754a97a04ba333daadc29885c9d0c8fea3387165278f4974e468fea57f2bfd8428c4d0f010833283db73735d39de0c0cb5898d0c06c0ecd05f61098935cb6130a8da60d1a6c2ecfe420f972263fff5a631b09e81c837183c5528bb1c740b36fc39cb082f3383c2b4afb25d04ad1d1f4af63dcf26a0bf5a647cd2e35a51cc119c4dc5031f5715b3bfa1f2b92de06bdac0d670fdd30980f32c51f3936b51e5db6b95a8d36279da5faa4c4e454f2b7e54e9f488071011c7f6f9b63da260a2e46d796d36c9a9dcae88085806a10a77bbb670d475778", "a55fe162b287bd6eebd6cf7e7aeea8672322d924ae42c7404ff89aedb98943f3755d2889bca488cc7000e6e9b8e7a0ef289273cd29c44cc600e330d1775e3cb767f12150e1615dca8c3f67466463a3ca993a1b788cf67a7a35b95dfff954206eb5ea1e1bf7fb06482a551625b5c9fd9a86e8414c8cf79d3a14104a153cbe04aac5172aa4c4a89349f5856c4262dd1d7317a7544c9afbbed449e7dcc2b58d9df6c9c9ed3883e42e80f5c2433550f30e73c7bce0fccdd880adc19282a392dae26a0108e7faf168cfc15937aeb046d60712603286b8ddfb27916b79242d56f1", "2bd6976592408cdbc4e41dcd3ecfbb786775ddedef914d9058e6753f839fdfe15b17d549dbc084aa6cdf3befa0158aa84c5d58c5876144fd7e6c41ab7d42419d0dd353732e0e6d3fafc4f5626c07433390a4fd467197e85b5de7e2cf1c26cc575356adedcc0740008523b503df12ff571387726c5ccb280376d19cbacb1d7ce7aab8b13292c6a8b8881e949cbf6d4610d16ebba1d46cdb8d0459596e0aa683d0307bd926e14de19b9bfeaefa29d91b82248604673a455520cbb64eef3f38cfad8e126a3b1cfa1aaba53a784c8ae0c50279c0ecdab54095d36f67ace9b8ebbb", "71913ae2b1c8729ed6da003c24a1d4f96e28d7faf55ca14ee0b2865282b9b61103ce6ee0b00b00aacf2081adedea5616f9dfd22c6d6d4f5907bcc02eb33edf92de0bd479794f51246d9b612b4543f6ff633c4fc83bfa6144c9d26721cdc690a3d5a8db54d8bc7873bfd32924eeb502810732b5ac2f1852bb021c401d26c39aa3b7eb09083093a9e89bf889b53383b5af61110aca1b9fdf38908c7d5a184fc5f46b3423a66a2749feb8de2c541c563987278dbd0513d99b732411012b5b75e385510de5f6839c3797dc094c9501d5f0504b06b43efb6e746f2129ca189c1da424", "9d048a83294de08d3063d2ee4b4f3106641d9b340a3785c076233686dd3382d9064a349c9eaa78028d35652078b583e3f708e036eb2ced3f7f0e936c0fd98f5d0f8aa91b8d9badef298bd0c06843831279e7c0c67ca7e572f552cfdd984c12e924c08c13aeec6f7e13d161785546ebfd794b5d6a92a4744e52c4cab1d0df93b9468be6e264e8cfcc488f9c3c1817cbe501f4b9cc5999483b7433aea777226b25273a6ef2331b5f3b6db8091591e8e276015da3ef78bb2ee0526ffe23def2d8d193cbe594e8ced1f3d216fcedae2a1eb288da82e34cf98aebc28def658ee0849ae7", "3251c96cbf82ee2e5264528c0b6cdfc23d20e1eb2d6441b5d62f0fd24c692a0d45a8bc8aac32884b7141ac0f4f113ec9fc7f6b4db3d696374177f9a42d602ca471275b928f639105a55b846da9ac7274cc37de8c38541f6895f94d72a81e117844b46601c201f7189b935a96e42505f2098ac985d92dfe86349a706ef6325b3c2e4060ced3c453e68ed09e043bcc75846b80118dc53530248da250fb57922d0afa53a7b2c89161aa4fa372a46b2a8e1307741cecedf585d2f998a9d496763800b6965c38a5d8aa566c709f13699c8185ab4fd8fdc8b824f4dd6d1c255b4788f50574", "2de31dbc8a012254586f3229d3524fc529554e98850d30acdfc11406bba6a142029126ac165ee90b2de7509fc3571a8ee12e16b05054eb8baea879d135b39627f0d8331be3e66bc720c2096ce74e437daebf3bc53d8f2ccc228c3256d3edb6e9ae7c354a0c9350e6d663a9a30630bf9da3d96b96608a2a171ae28105714058b6c4b38a36c56561c4612c32aad25c65b7fb6faa4e4ecd44ebf9b2fad42ff9a807cda2581614fd30d41a7436069399b8d4f062a37a5bd4066a93d541fa5797a7d3e7dc9c4c40f0bbf5256f71613240f9ef128b3423eacaf428ada06b6a531f835281e4f3", "07dadee629a08223dcd7ec441287b4c5e26347451d9c003e3a8496b4ea313b51126283a6720d7851e24423d9c9c818b4601247178f38a61f45fd4c8596d79529d416834226666a2c8552bbc901cc5cc3406a18fc88077fea52e1b620748553052ab7788c0d025b095b736fbe714cb3a968ec16b5917652eba2d7cf32ef3140d6c27b25d053e9786d24cd09a5306a0ef55e46201faa6196a91084267d7a7b5ca57c2efdeb2cb97d682d2a191b915553c8933f1d1b7faf0b4a1d83ef611f1e44438bc1c3d860fbfd12b5f26e5a6889a31ce26ae6a55c7a563b5816d113423ef3f25fa9befc", "1d94166bb387526d519c4ce150221954da8930f66765fe6a5504e30a69962d595cfdd07a82c003843598864261f053bdb6f5086d516c261e089caa89990f0967605768ae9200bdfe4dcd7b77a93265cb33d9851a2a1036113c732bf3f37534530641300f0620de5c16101e16f4baf39d9fcbfcb01c52afce0992c329d8dbb438c314eee995c5020611d6f889e06b8a032785cba9a415580dbf752b5e510523c89f478cc6f047bd926f51e4a965c9749d1e76379c0e7e5b56803893bafaa4d2892b4c52f143b2fa777cd1035ea418684b8019df084f9a3f1f768753096621f342895c510d01", "fc0073f199ed8a1d6edc8e7bdf182670003108d82b283aba82326e856f8de378987a03d0fe8d2041440fd29d51c63796aab44090d2b14ee00859b3a08cbe88f724badcd3c401226c5db8b307b8deea5be305412b080e9f99cf79d6d08d3646f347a7afebb62912e3e246e2e726f9aec5c101d916e47f984507b1d65d313697256c77da7eca3bc5811c87bee02a2826cefff0d92bae989609aaf95d70561b40d98474c37277c884aed887a1606d206b11e8a8a71d1f1d19319557b57351228ff0404be700a6cc56c0a30f3d4b7a0a046463fdaf19e7d5f59e155f378e35baa33db1e881f2207f", "f42a6a91278d6a076feba985b1cf4ce0af1fa9d6d039c136e8971e665ff088a10b6b9a379a6f5526fc5957773a0ccb8972a4a19be0745ac13937030a54b18dee4f4c5df47a58a33a7516b90e646e5da999166ab0e52f457f7c9b7e391836a687eaae37b377e59a4c995ab0c57162c307ab951a9ba6590f429cd27250e7010eb794ec1b1ec35f8aad189b2fd3e8aff24d93601d91a4884e6f84b02757ce7620a02901519fccfda52f68ad6df709d112a9c25d66bcbb9622806427ca8b8d346b6db05874bde800cde9cf17df4b05baab0f133febd1ebbb053b49c109a7f5b1f864a304d10288e2f0", "bbcefaf4a0739509f8a2f831c954071aac52e60cfa882a867b8b910dcf7edf92e1c0692bb027bc378c460a01cb6ecc8f2a012dd84ee5a678cd497b1457b6d393421fbee98ff544fc7eba24cbc3aae506254d9a2d74dde74437ce4c8a69010718506bf4c5943342a942e5e2d3406a3016280b6e37954c5d5e763346251afb0b746cad68cac757f9df765e092518729cfb9a5e76300c124e708ca33591a369767ffb63933cb72fba67beb2223d98984d0b75eb5d1a38615913747b520b3d613c715c0c77d2987bb88f3c419bcc5d38573cf4a8a4f550b2d876f05ca252d88c70a561d869a5018b32f7", "dc2437010cb05d9cab2af5c275e1d2acd627ce19fb86355df91fb8d059e60d591663c8eb077d48388c9a321057a98136f49f0098348d9f29d808936f98bb1787c7ac75fb14f6076dfd2de5b59b1fa4848cabaa9a99a091dc24b561911c392ecdbe53f4adae82b852d830adea3a10490c908e337ce0a6d12354ce05a37ad3a06696b66820af8a1f67e6287533fd6f38a5f6ad1c6b078c08baf2c37d2683af01e6a5b33796c8ae48935a888f9bd265f4f11a4e27c433b8b1c9afd140bcd21a07e24378ad6badde8e47c57e3340f49e2406e8d49afadd65eaaa4c3d078c27d7e42118cb86cd248100a356", "6c290db326dd3152e6fa9b9c0cd7d49e50a0221b96e32f5f34a8cb7d0c2edd3e937a7d025d6999b7b468add4d6894d8f7aceaabc18f4d9c171f1fe95ea1ae8570382a8450fbc595d95b1f51d24e1abc2970b0e1d20ca40aa21bdfb3656adf2f19882eda606f5ef1c03174e1d94c8d12f0fee8dce6852f42a364eeafa27a7971d4379405db8e46baac4d685b969238e5df06292a6c790bf1994a051b038e1d8db91e1bc4804f32443781c34a552ed2e8100cea374e77af56ba0e11c45990d3ba68df9087b1f4968cbcbb1c42f99b7267c76af926ff3134e093df28fab039cad420c6b70f2d9b5e678c155", "ac724a22ebabaedbbb052953e3c264a4b6440f313bad501cdc1484b64f33402a2230898776db5c818c28035ffae6ea24abd04b7159e42159833903a0c23a7c564f7645e49ddedb748fd9e51bd6cbf2eced98caaa35226970f003ce1fd260ac5795e096f1c04aebf8fd36e5e2adeea929b5e963a3cb71d6b55c85bb7d3a2b03a7e74b4416de8fa68950168d7c3ae8ed2e29bad1e8a182a7c5418e5d564373163778cd3c34e9d320eb1a60480a8f98b12e0026cbd7752e6079812e3767d9f55f3f10b8c214a6eceb2a58954091a06b33862af171a9b60bf2c6a44e8766e6c56e98092c56f2a8510f6d05c103", "8c70114f7cffb375c2b9a06e27297a5c32418b2daf68af5bbedcc7106edbc070e764bf40c1f8eb15079e2ab77f898afff3490108ed9afb7ea9cb05df41d263be0e42d2321d3d2656622d7bd232bf68d37375fe7314b09cba66f19c8b59424198ee69e7a9f3de0ecce0685127807ce336fa479ccaf7aa1ebc4e406271ce6c4923ec36093516498cc227f9218869346c80ba5ae83e023aca0ae2bc86b5bf5d115a4616b6587cb869d92f8c780ab70d5766de07a204af5e1c8dbba622516d2e911b36c82e4687e4d258ea616c07f76ff0baa376c8d5975cffac0b25817f779ae3ce88b72eb47e378484ce999bf0", "0733d59f041036398233fd47a84b93f6778ae5259ef5d62aa3b9faedec34c7edb570c18b2a5d2c4c55cf656d98a1ae396d45a3b746b7ad6f07312c3d05d1a50ffa90bcdcdba105e25b7b0c52664223f8c2476925d46dc6ea2406ded7d0b0b292f6656cebcc7616cfa4b82aec68b35d1da67f6ed2bf0171849d6bb65128d8a140ea5cf97f1003f8d7093bee077be78def4f7bd2caccbf0644f26b26285225142c40038484c3bb9ba9597744f4389e76dca3eb695c33ccc621cab1fb603cb3535a0ad318d220385d5e94f8674f3d55e97e097f8d5c049e911946afbfce783819951d65d6bff4567dc951390d1aaa", "398ddbba3dcb5642c102efa841c1fcdaf067062e7eef8e2ee0cd73d7f77e57372d6ee1a9b7b6f86ad12d575001ae71f593449cb5a476c6bfeddaa2af0f9239c1d7effdedf66ceaf413707b5ab9661a7cc0ef8cfe4d1651579c4f0f64e2d12a52653c54f2dd60864e769eab8a627c89c56ee93365d031f0d2523cb95664b1575d51b122f33c9e94de75432a690658c977b68aa5b721a393f9b9b3b612c10e920a7d510c6d8460b35f8614c42f5d2c241a01b28105aa7c1b521ac63ebbedafac6d5a38c898e8590f918a1927bc53aecc2b1c8b18d7df9107c6997d9b3fa4b0bdb1c603da619d9e75670b97a5b40f06", "ef07bbc7c4150dd47f8c69a7989948fe831dc798b0424dcd6551bfa8e88216095a7e5d720909bf3d23526b9ba464b66ff6b63a7337c31451ab9a15f04ead809a62bb52206237de77597a730106d02d227dd6099ea9ee2a92cdc446ac3b9d024e32255adb3e9b56b561c431e0b5a721f0336f19568a5335d0ebc6c73ed8ff2c15e219477d9e4b67f2928e251f8a61a2848857e037d010806c718ab062967fd8e85f3722252957923f5f9005aae47b4b1b3fa464e3ba9df573a56055f17e903126fbbcb6cb96de92fe617c97f84ef3ba0d8f2651dc4aa80c157f372ae1bc02e5067ad076f3fe48bb72c0f3c99273f82b", "c7076986d2333f3a6752adf11f1a9e5c6bc4755f341073cc86a9c7519c8db029d5ae833fdf3fee826ff4692c57880c5074620ea97c00f1dde1e8a0f18501627984ded4d1b5c4af35be5cc1bcc868060a49a968dc0547acde490b4c68d79924a93a986aa0ad060c7de706e8a99ce8f84a4f8707b52a8ee122b763ba580d6b1f35f6af25094c69f49247da96c836991851ad36f60bf577863d7471608a012afa7a56656abeee7cd9b4f1f4d9d13a8526c0f33cd251caf7486639e787250390e7e488e9ec311fc3d847a7266cc59bcc2bc34192554aa57cf25db10ce04bdabef3fde6db85f55195ecc2ff892b2e268ebea6", "01789f40d42d8d3e4a416fd9ae7de78c3a30507809eda200e1afaaf8d7020cd1fad18eba62d821946f220506cf105ff0e2069a771a2c233714afa6b2f695497e4b95c9693dbb93ec4c9a14720676aa87ee31dd34e4e081756477032b4a57b328285f2cdec1b269754c474936927e93acc26012aff1bb36f30c2402aca0a9b9ce9568f5000e2c934263933b436c94f8d6589c89db7edabc5d03a8fe795fe50c5166beab64ed7c22662b984ae2c66dbe4c090b0df603b27c759278f8d66859afea3f6a8f02c2c2a2202b9fc29132256f164b5050a803b43688dc4c9ba86374a3522afba5d1a19bb3820b883aebc267627095", "2c61944bd6a50da00ebb951d2b67d79fc6b6fb5aca83b1de3dbd7690ab756bb1e1a21051ccf1e24136ac8ccb42a2ee10be94d2cb9289d5f52b6f90e9d07a3478f36a1eb7d08c3dec52ca154fd1427ba92a4ecbe73a71bceafbd26e9a39d50821e2876d3a0c0e6e373b9795dbf72ea29cc439ff42706be798c90d4617b39c90ec84bf9fb699dc8a9a34e25d81759d6c57df45efb1d0d68aa51278564b99633ed5dc464bb7d53c5c21f798f33bcd868657ecfe75a1ed8149d394b398969ef624831b30f1458465bfd2fdf3f284f2ffc54bf2817b5fab2e02056e864f78bb6fd870c64f3609dab218f25da8060f756e45121e79", "942fa0c68cc72f69518a3a7aac0cde45bab0e928b5cb2bd24d049fc313f74b6afa87c4e34150484f3b5200163f8a6472d04777928ecc49319539fc17d71a38090f55a74f757fe45781a3c09f08dcd3dd4c73c8533a5e00cf8a86ebe77fe45be2848574f7c5d25e9a0632a60d2dd41febdbf987d2a0487e4a4ce6ed5f49f2d741a88ecac232b1498253fa4ee8147bbd0f600abdf295e81f7570015aac5fe6ca7bb4a99bb3fc54287106d7fc1132a574af49db82a7b9a5f33e193cde527ca2176c52cdab672165e0fe5720f71ada57ee90060aa069ae2a0bfe67c1b71b17c601c3c2224bf9891bc11ba216e3ebcb51fd95b8d7cb", "0d68cfe9c087ec116fe7572042385159cc705960f842aabad1ed1387ec1697f4413a23c6090041328fedd4b626c6eeaac5b5a71acc1fd1bb8fbd228857ac5bd045c364be7a5a26338ff04c99c4c473cf445a891db6422d1bdef4533442df171643fc36a092fabb464298e4194c9e2950884de13d113ee24160a416404c16ddc5d2476cb3fb80da543e6ed9105f6003977acb34e1fdd2cbdf7a00d5ff84350b74ac231418c0d88269d02d824802791ff42a51cc835deb9869a6023f867f82ef6dc0bfb03e6dfa835646bb18a4074773486e308aa39e532aaea4e6fb35dcada7e060f8282c371ed26d22302323d4fd142a85534671", "45e24b167a0bbef1bd8f79dd047763d0754f36a7b623f298059d177e8ac994945c37d2c4af06f01318960301595941124592f2995af1459d854339998d3ae17534df2d9793d6e203857d02c98a0cd88991e641b3e640090ba303f87b907dca8ca462fac19ad079b2c82ea5b521ab891b10138b083b3d9fa214a8fe60d1cb3599c5d199c61a2cfb7ee2f39e5a5abad5ac4998b707545f73e92128d21803420526d2598a53bb314adf29a0ef56b94bd2221601eb53ecb8540e8fffd38fba7bd827ef255e4ef55491475c0f383a241f81c72af4e1dbf2a65cd4d18a497615aa0de2791a3511a7977a8d4d41492bfa4085f2fd4e8f751d", "1c1bb695ae90e6e33fc1e8b2a62ab98bf835ac7193440f2351c8cdd830472b637d2fd9c9013cb83caef506abc1c4f7567706db6046b1d184579c7a9223ab1b35e32898c70a3c27628123ffcfa518612f080a2c4a9f8e0a927a47dc98307d2b48de9d5dddcb5c82f0b0e4e610d44f1baa9bbbf7f5a727134680bb7d1327b73b52d8e5e36dbb53971e99e699d79f75a3fc01316bd7012947d119d6aeb7f75b8fbf0479c03002148553fa0da450fd59d4f1bebc252caa11ed9bec5b6ef54279b5f8382b61cffc67ec03f4baa7ea476c31364b86aa8ccad9fd0818717f0ced2dd49477874b4341c602d7a1beab860eb476c7e3ce597e6926", "7a3cd9bb2277e2c7f1134fe7233f0f7883c2db9fba80aa5742b03041de0fe589d9e5ea84470dabf41bb66816f3e33ebf19a0ca5aba1004cf971249b258ff26a98dbd0c37ec6cd574854109433357720040bafed4531e0079186b1e853e0ced35d08d27f6d732ed6e2c6651b51cc15c420a24f2dc36c16ef4b3896df1bb03b3963f9aaeb02a48eac5772abd5948c2fd0db2bb74e3351e5eabd681c4f413655bd94dec96b1544c1d5d2d1df4bdc26020d25fe81d5238de824687a5505e1fbe08d11b3924b3ccc070fd225bf01eb79e3d21f7b62a836cd3bcc11c931669c37613470e356143df87c48848a829f5e018973a5db88eb6c60203", "3f158afd0733fcc5dfe1efc2dd4eada732f942af734ee664955bb1ba613eafd0f349e7554a14d68200c62d8f2dca2ec8b81c8350735eaf437041f78b452598825b6899560963ade66a0fc74ad01f8343d1d19c7bb327a8dc14ffdb1c42fa72b2970d9155e2da6a2e6419d4117842d826ff38ffab9617307a0283d3ea28c8104ad9a6e087bb750ed1d10fd8f7100b1663682e979d80e43968c33d9eff66f4d1344e583ee521e78d0a2193c0577516b978339c143bfc689bc744bbc4a9163063de82c9706384b6b385e54666c86b34f23c1e25be293af06092ca31d857e11e5b2caf0d19dd3afbe85380878eda76d718b4bb869c67e044e242", "a177af4387b9bfa3d59e97ee7b0ff5f4ae4a326fd9204c8d28831a67fcc385ee6c4828247b16d11aea9bb8cd9e6c4d2876c6b2fa6d5041ad39e1b04039071e29c4d86417e7eac4fc7d3823958a021823e2c880a757dfbcd0c8196371db5bbfac15e4d1a0596508b6d26f8c4a664924c95082d173f817995b44c4285d625d9b2f56c86632fe1295c5a8a7a3760028072bcb07bc245a705e7174d06b9d5c0c8ca495b9ac218f1921fa63f2db3fd148f07545366d008fb5aead7497d902b91fbaa39669929d4ae9d07df8557f1f0aed7b51252f10c6606e5ff3ede1327530ca356b4896ecf14bf7322d77fddfbe28d52f6de7f66eeb81704c87e2", "01a15b9018e35cc342c926b01d03ad9db4993a6bf92e0555969fee90033f28f3ec234c1268b11b040dfa0770d4ceb39edfeb8ee6a589f4eebcc08d2d1b0a1a52953aa26eb44fdf4a2743c3dacb212a0c0f325572f645f53027b6f3c0c55abaeb1b0918c89bedcb5028f094d743ea354f8ff553c45f111a8fd5a14a4e5c835164747d302472e19a67da04b4c8e39756a9d248ce14d1ed43de75aca86850f2455eccd4639b2af035bb3f504cc9065d091c1c47e036083cb3fc50bf39292b11737c7ce0b49673ba93981de304dc65a671775b6ff927e3ff93850b214fffb5792105a4bdc81354d5b09e84afbdd1792b8fb4e9d0ae3dad2492b03282", "24f07ae31279ceed18ec6d35990f21200934ad6b132c6c62e82fe92a40a0e60a5bed10720eff5a1f728971888682772b2d9060d4fee88f37d0824e7384dddcc549475f0e1a44eda4804778b62febe46e04657a20577ee70acb3425e334881eebd8ddf714ae8c527ea747e3367de384e595a43b299b6bb3f6b0a4716cf90038e0f75a47d5057d7fcc3c8a8f9224992c67f8ae0d3251ea09a24aed9ce57ab637f6b3cbb7083df62b6287f64d0877984c4249d113bdb2b07865082aa24cd7ec07061b17de320f51f29f25b82d7073d369cf2dbf96310c0c311997911b2cc02f606f9cd99663c57e78499192a2a78f9c9fa67013e0f9817287faa69b22", "4aeb32bf9d050f10bea18d9f71b4afea7bd08550e574e7d50df234c7413668b297b6721d7a0f0bdcdcceb2f55adddea28cd59bd44be0c5ec067039e428706caae11f565d961ad6e7f4c51b0aed6d05cc5b8d826c4b9c39daefb6c7da46dce619a359dc9ce215a215218fa8d54ee0b4f301b6c201c7c2c5f7cb1c6e0cb76ba6c6e8f63ef7a5213d550b0d0857fa0ff9e3e38e497161617413ac066e2fa539520233193a5cb7baa0c2cb20b45e56bfed2c40a9544d1f230dd0cd6d4976e7cf51da8a13200c3957c0154c8237b2931ce19b824963ac576ea49b548cc6aa85c47796b470fb2c6308d88f390bb13607e294c84a838b2713b14ca6a5e8bcee", "77e607478be5502432230c913d9ec82f967d87c0ee169a74076f989648853eca693277287f8a5b306bc94dfdbf64ca5cb5dfc0bc498589d51a691b8d57d4b0a9ee247d038fe1b5571183be3e75c37045bf1235863ff1b84b208c10e7f1a5ba54ff36af5b2870129867164d013e0a6d2cc067a3509bba2f46390302c80b651cf590ef69aad8effd94cab28a9b44be6a38b58cfc47c9c725d6fa467894163383b6873d10d263b1cbbad932ded59ab503920267ac026726f794a335a88f6ef564f8968c6fa6f5d3ea161eb6062ca349b9a0e4038273399cfa297a6b07ceda1ebaa99c9de2d935ee230a08c5a488ad46f3393243371d40916b8063cac9da63", "50957c407519951bd32e45d21129d6b83436e520b0801ec8292d79a828106a41583a0d607f853dc4410e0a1427f7e873455a75df065cfc6eef970f7e49d123b346976460aadd91cf513c140c356442a84656904a8b1d708dc6089db371c36f4fe059c62302eaab3c06c0cb3b429961f899dcf99798464b8571a440cac7a52b495f32417af6bc8f58adc63647531f804b4e96273b29b42434c1236bde80ba3744fef7b1d11c2f9db332b35bc25123338ac9a0796aac213c9709b3c514ea7ecd80e22d3d8a74f28c8194418a6e1ff30714d0f5a61c068b73b2ba6cad14e05569b4a5a100da3f91429d6e3ffee10ceea057845ec6fc47a6c5125b22e598b2dc", "f2273ec31e03cf42d9ca953f8b87e78c291cb538098e0f2436194b308ce30583f553fccb21ae6c2d58f3a5a2ca6037c1b8b7afb291009e4310a0c518e75314c5bb1e813bf521f56d0a4891d0772ad84f09a00634815029a3f9ad4e41eafb4a745e409ef3d4f0b1cf6232b70a5ce262b9432f096e834201a0992db5d09ffa5cbc5471460519a4bc7cdc33ae6dfe6ffc1e80ea5d29813136406499c3514186ced71854a340701519ef33b6c82ca67049ab58578ff49c4c4fbf7d97bfec2ecd8fbefec1b6d6467503fea9d26e134e8c35739a422647aaf4db29c9a32e3df36e5845791fdd75a70903e0ce808313a3327431b7772567f779bbaee2e134c109a387", "5784e614d538f7f26c803191deb464a884817002988c36448dcbecfad1997fe51ab0b3853c51ed49ce9f4e477522fb3f32cc50515b753c18fb89a8d965afcf1ed5e099b22c4225732baeb986f5c5bc88e4582d27915e2a19126d3d4555fab4f6516a6a156dbfeed9e982fc589e33ce2b9e1ba2b416e11852ddeab93025974267ac82c84f071c3d07f215f47e3565fd1d962c76e0d635892ea71488273765887d31f250a26c4ddc377ed89b17326e259f6cc1de0e63158e83aebb7f5a7c08c63c767876c8203639958a407acca096d1f606c04b4f4b3fd771781a5901b1c3cee7c04c3b6870226eee309b74f51edbf70a3817cc8da87875301e04d0416a65dc5d", } ���������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2s_ref.go��������������������������������������0000644�0610621�0607500�00000000612�13172163317�025102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !amd64,!386 gccgo appengine package blake2s var ( useSSE4 = false useSSSE3 = false useSSE2 = false ) func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { hashBlocksGeneric(h, c, flag, blocks) } ����������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2s_generic.go����������������������������������0000644�0610621�0607500�00000007277�13172163317�025760� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package blake2s // the precomputed values for BLAKE2s // there are 10 16-byte arrays - one for each round // the entries are calculated from the sigma constants. var precomputed = [10][16]byte{ {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, {11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4}, {7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8}, {9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13}, {2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9}, {12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11}, {13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10}, {6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5}, {10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0}, } func hashBlocksGeneric(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { var m [16]uint32 c0, c1 := c[0], c[1] for i := 0; i < len(blocks); { c0 += BlockSize if c0 < BlockSize { c1++ } v0, v1, v2, v3, v4, v5, v6, v7 := h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7] v8, v9, v10, v11, v12, v13, v14, v15 := iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7] v12 ^= c0 v13 ^= c1 v14 ^= flag for j := range m { m[j] = uint32(blocks[i]) | uint32(blocks[i+1])<<8 | uint32(blocks[i+2])<<16 | uint32(blocks[i+3])<<24 i += 4 } for k := range precomputed { s := &(precomputed[k]) v0 += m[s[0]] v0 += v4 v12 ^= v0 v12 = v12<<(32-16) | v12>>16 v8 += v12 v4 ^= v8 v4 = v4<<(32-12) | v4>>12 v1 += m[s[1]] v1 += v5 v13 ^= v1 v13 = v13<<(32-16) | v13>>16 v9 += v13 v5 ^= v9 v5 = v5<<(32-12) | v5>>12 v2 += m[s[2]] v2 += v6 v14 ^= v2 v14 = v14<<(32-16) | v14>>16 v10 += v14 v6 ^= v10 v6 = v6<<(32-12) | v6>>12 v3 += m[s[3]] v3 += v7 v15 ^= v3 v15 = v15<<(32-16) | v15>>16 v11 += v15 v7 ^= v11 v7 = v7<<(32-12) | v7>>12 v0 += m[s[4]] v0 += v4 v12 ^= v0 v12 = v12<<(32-8) | v12>>8 v8 += v12 v4 ^= v8 v4 = v4<<(32-7) | v4>>7 v1 += m[s[5]] v1 += v5 v13 ^= v1 v13 = v13<<(32-8) | v13>>8 v9 += v13 v5 ^= v9 v5 = v5<<(32-7) | v5>>7 v2 += m[s[6]] v2 += v6 v14 ^= v2 v14 = v14<<(32-8) | v14>>8 v10 += v14 v6 ^= v10 v6 = v6<<(32-7) | v6>>7 v3 += m[s[7]] v3 += v7 v15 ^= v3 v15 = v15<<(32-8) | v15>>8 v11 += v15 v7 ^= v11 v7 = v7<<(32-7) | v7>>7 v0 += m[s[8]] v0 += v5 v15 ^= v0 v15 = v15<<(32-16) | v15>>16 v10 += v15 v5 ^= v10 v5 = v5<<(32-12) | v5>>12 v1 += m[s[9]] v1 += v6 v12 ^= v1 v12 = v12<<(32-16) | v12>>16 v11 += v12 v6 ^= v11 v6 = v6<<(32-12) | v6>>12 v2 += m[s[10]] v2 += v7 v13 ^= v2 v13 = v13<<(32-16) | v13>>16 v8 += v13 v7 ^= v8 v7 = v7<<(32-12) | v7>>12 v3 += m[s[11]] v3 += v4 v14 ^= v3 v14 = v14<<(32-16) | v14>>16 v9 += v14 v4 ^= v9 v4 = v4<<(32-12) | v4>>12 v0 += m[s[12]] v0 += v5 v15 ^= v0 v15 = v15<<(32-8) | v15>>8 v10 += v15 v5 ^= v10 v5 = v5<<(32-7) | v5>>7 v1 += m[s[13]] v1 += v6 v12 ^= v1 v12 = v12<<(32-8) | v12>>8 v11 += v12 v6 ^= v11 v6 = v6<<(32-7) | v6>>7 v2 += m[s[14]] v2 += v7 v13 ^= v2 v13 = v13<<(32-8) | v13>>8 v8 += v13 v7 ^= v8 v7 = v7<<(32-7) | v7>>7 v3 += m[s[15]] v3 += v4 v14 ^= v3 v14 = v14<<(32-8) | v14>>8 v9 += v14 v4 ^= v9 v4 = v4<<(32-7) | v4>>7 } h[0] ^= v0 ^ v8 h[1] ^= v1 ^ v9 h[2] ^= v2 ^ v10 h[3] ^= v3 ^ v11 h[4] ^= v4 ^ v12 h[5] ^= v5 ^ v13 h[6] ^= v6 ^ v14 h[7] ^= v7 ^ v15 } c[0], c[1] = c0, c1 } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2s_amd64.s�������������������������������������0000644�0610621�0607500�00000040171�13172163317�025102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!gccgo,!appengine #include "textflag.h" DATA iv0<>+0x00(SB)/4, $0x6a09e667 DATA iv0<>+0x04(SB)/4, $0xbb67ae85 DATA iv0<>+0x08(SB)/4, $0x3c6ef372 DATA iv0<>+0x0c(SB)/4, $0xa54ff53a GLOBL iv0<>(SB), (NOPTR+RODATA), $16 DATA iv1<>+0x00(SB)/4, $0x510e527f DATA iv1<>+0x04(SB)/4, $0x9b05688c DATA iv1<>+0x08(SB)/4, $0x1f83d9ab DATA iv1<>+0x0c(SB)/4, $0x5be0cd19 GLOBL iv1<>(SB), (NOPTR+RODATA), $16 DATA rol16<>+0x00(SB)/8, $0x0504070601000302 DATA rol16<>+0x08(SB)/8, $0x0D0C0F0E09080B0A GLOBL rol16<>(SB), (NOPTR+RODATA), $16 DATA rol8<>+0x00(SB)/8, $0x0407060500030201 DATA rol8<>+0x08(SB)/8, $0x0C0F0E0D080B0A09 GLOBL rol8<>(SB), (NOPTR+RODATA), $16 DATA counter<>+0x00(SB)/8, $0x40 DATA counter<>+0x08(SB)/8, $0x0 GLOBL counter<>(SB), (NOPTR+RODATA), $16 #define ROTL_SSE2(n, t, v) \ MOVO v, t; \ PSLLL $n, t; \ PSRLL $(32-n), v; \ PXOR t, v #define ROTL_SSSE3(c, v) \ PSHUFB c, v #define ROUND_SSE2(v0, v1, v2, v3, m0, m1, m2, m3, t) \ PADDL m0, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSE2(16, t, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(20, t, v1); \ PADDL m1, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSE2(24, t, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(25, t, v1); \ PSHUFL $0x39, v1, v1; \ PSHUFL $0x4E, v2, v2; \ PSHUFL $0x93, v3, v3; \ PADDL m2, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSE2(16, t, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(20, t, v1); \ PADDL m3, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSE2(24, t, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(25, t, v1); \ PSHUFL $0x39, v3, v3; \ PSHUFL $0x4E, v2, v2; \ PSHUFL $0x93, v1, v1 #define ROUND_SSSE3(v0, v1, v2, v3, m0, m1, m2, m3, t, c16, c8) \ PADDL m0, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSSE3(c16, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(20, t, v1); \ PADDL m1, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSSE3(c8, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(25, t, v1); \ PSHUFL $0x39, v1, v1; \ PSHUFL $0x4E, v2, v2; \ PSHUFL $0x93, v3, v3; \ PADDL m2, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSSE3(c16, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(20, t, v1); \ PADDL m3, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSSE3(c8, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(25, t, v1); \ PSHUFL $0x39, v3, v3; \ PSHUFL $0x4E, v2, v2; \ PSHUFL $0x93, v1, v1 #define LOAD_MSG_SSE4(m0, m1, m2, m3, src, i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15) \ MOVL i0*4(src), m0; \ PINSRD $1, i1*4(src), m0; \ PINSRD $2, i2*4(src), m0; \ PINSRD $3, i3*4(src), m0; \ MOVL i4*4(src), m1; \ PINSRD $1, i5*4(src), m1; \ PINSRD $2, i6*4(src), m1; \ PINSRD $3, i7*4(src), m1; \ MOVL i8*4(src), m2; \ PINSRD $1, i9*4(src), m2; \ PINSRD $2, i10*4(src), m2; \ PINSRD $3, i11*4(src), m2; \ MOVL i12*4(src), m3; \ PINSRD $1, i13*4(src), m3; \ PINSRD $2, i14*4(src), m3; \ PINSRD $3, i15*4(src), m3 #define PRECOMPUTE_MSG(dst, off, src, R8, R9, R10, R11, R12, R13, R14, R15) \ MOVQ 0*4(src), R8; \ MOVQ 2*4(src), R9; \ MOVQ 4*4(src), R10; \ MOVQ 6*4(src), R11; \ MOVQ 8*4(src), R12; \ MOVQ 10*4(src), R13; \ MOVQ 12*4(src), R14; \ MOVQ 14*4(src), R15; \ \ MOVL R8, 0*4+off+0(dst); \ MOVL R8, 9*4+off+64(dst); \ MOVL R8, 5*4+off+128(dst); \ MOVL R8, 14*4+off+192(dst); \ MOVL R8, 4*4+off+256(dst); \ MOVL R8, 2*4+off+320(dst); \ MOVL R8, 8*4+off+384(dst); \ MOVL R8, 12*4+off+448(dst); \ MOVL R8, 3*4+off+512(dst); \ MOVL R8, 15*4+off+576(dst); \ SHRQ $32, R8; \ MOVL R8, 4*4+off+0(dst); \ MOVL R8, 8*4+off+64(dst); \ MOVL R8, 14*4+off+128(dst); \ MOVL R8, 5*4+off+192(dst); \ MOVL R8, 12*4+off+256(dst); \ MOVL R8, 11*4+off+320(dst); \ MOVL R8, 1*4+off+384(dst); \ MOVL R8, 6*4+off+448(dst); \ MOVL R8, 10*4+off+512(dst); \ MOVL R8, 3*4+off+576(dst); \ \ MOVL R9, 1*4+off+0(dst); \ MOVL R9, 13*4+off+64(dst); \ MOVL R9, 6*4+off+128(dst); \ MOVL R9, 8*4+off+192(dst); \ MOVL R9, 2*4+off+256(dst); \ MOVL R9, 0*4+off+320(dst); \ MOVL R9, 14*4+off+384(dst); \ MOVL R9, 11*4+off+448(dst); \ MOVL R9, 12*4+off+512(dst); \ MOVL R9, 4*4+off+576(dst); \ SHRQ $32, R9; \ MOVL R9, 5*4+off+0(dst); \ MOVL R9, 15*4+off+64(dst); \ MOVL R9, 9*4+off+128(dst); \ MOVL R9, 1*4+off+192(dst); \ MOVL R9, 11*4+off+256(dst); \ MOVL R9, 7*4+off+320(dst); \ MOVL R9, 13*4+off+384(dst); \ MOVL R9, 3*4+off+448(dst); \ MOVL R9, 6*4+off+512(dst); \ MOVL R9, 10*4+off+576(dst); \ \ MOVL R10, 2*4+off+0(dst); \ MOVL R10, 1*4+off+64(dst); \ MOVL R10, 15*4+off+128(dst); \ MOVL R10, 10*4+off+192(dst); \ MOVL R10, 6*4+off+256(dst); \ MOVL R10, 8*4+off+320(dst); \ MOVL R10, 3*4+off+384(dst); \ MOVL R10, 13*4+off+448(dst); \ MOVL R10, 14*4+off+512(dst); \ MOVL R10, 5*4+off+576(dst); \ SHRQ $32, R10; \ MOVL R10, 6*4+off+0(dst); \ MOVL R10, 11*4+off+64(dst); \ MOVL R10, 2*4+off+128(dst); \ MOVL R10, 9*4+off+192(dst); \ MOVL R10, 1*4+off+256(dst); \ MOVL R10, 13*4+off+320(dst); \ MOVL R10, 4*4+off+384(dst); \ MOVL R10, 8*4+off+448(dst); \ MOVL R10, 15*4+off+512(dst); \ MOVL R10, 7*4+off+576(dst); \ \ MOVL R11, 3*4+off+0(dst); \ MOVL R11, 7*4+off+64(dst); \ MOVL R11, 13*4+off+128(dst); \ MOVL R11, 12*4+off+192(dst); \ MOVL R11, 10*4+off+256(dst); \ MOVL R11, 1*4+off+320(dst); \ MOVL R11, 9*4+off+384(dst); \ MOVL R11, 14*4+off+448(dst); \ MOVL R11, 0*4+off+512(dst); \ MOVL R11, 6*4+off+576(dst); \ SHRQ $32, R11; \ MOVL R11, 7*4+off+0(dst); \ MOVL R11, 14*4+off+64(dst); \ MOVL R11, 10*4+off+128(dst); \ MOVL R11, 0*4+off+192(dst); \ MOVL R11, 5*4+off+256(dst); \ MOVL R11, 9*4+off+320(dst); \ MOVL R11, 12*4+off+384(dst); \ MOVL R11, 1*4+off+448(dst); \ MOVL R11, 13*4+off+512(dst); \ MOVL R11, 2*4+off+576(dst); \ \ MOVL R12, 8*4+off+0(dst); \ MOVL R12, 5*4+off+64(dst); \ MOVL R12, 4*4+off+128(dst); \ MOVL R12, 15*4+off+192(dst); \ MOVL R12, 14*4+off+256(dst); \ MOVL R12, 3*4+off+320(dst); \ MOVL R12, 11*4+off+384(dst); \ MOVL R12, 10*4+off+448(dst); \ MOVL R12, 7*4+off+512(dst); \ MOVL R12, 1*4+off+576(dst); \ SHRQ $32, R12; \ MOVL R12, 12*4+off+0(dst); \ MOVL R12, 2*4+off+64(dst); \ MOVL R12, 11*4+off+128(dst); \ MOVL R12, 4*4+off+192(dst); \ MOVL R12, 0*4+off+256(dst); \ MOVL R12, 15*4+off+320(dst); \ MOVL R12, 10*4+off+384(dst); \ MOVL R12, 7*4+off+448(dst); \ MOVL R12, 5*4+off+512(dst); \ MOVL R12, 9*4+off+576(dst); \ \ MOVL R13, 9*4+off+0(dst); \ MOVL R13, 4*4+off+64(dst); \ MOVL R13, 8*4+off+128(dst); \ MOVL R13, 13*4+off+192(dst); \ MOVL R13, 3*4+off+256(dst); \ MOVL R13, 5*4+off+320(dst); \ MOVL R13, 7*4+off+384(dst); \ MOVL R13, 15*4+off+448(dst); \ MOVL R13, 11*4+off+512(dst); \ MOVL R13, 0*4+off+576(dst); \ SHRQ $32, R13; \ MOVL R13, 13*4+off+0(dst); \ MOVL R13, 10*4+off+64(dst); \ MOVL R13, 0*4+off+128(dst); \ MOVL R13, 3*4+off+192(dst); \ MOVL R13, 9*4+off+256(dst); \ MOVL R13, 6*4+off+320(dst); \ MOVL R13, 15*4+off+384(dst); \ MOVL R13, 4*4+off+448(dst); \ MOVL R13, 2*4+off+512(dst); \ MOVL R13, 12*4+off+576(dst); \ \ MOVL R14, 10*4+off+0(dst); \ MOVL R14, 12*4+off+64(dst); \ MOVL R14, 1*4+off+128(dst); \ MOVL R14, 6*4+off+192(dst); \ MOVL R14, 13*4+off+256(dst); \ MOVL R14, 4*4+off+320(dst); \ MOVL R14, 0*4+off+384(dst); \ MOVL R14, 2*4+off+448(dst); \ MOVL R14, 8*4+off+512(dst); \ MOVL R14, 14*4+off+576(dst); \ SHRQ $32, R14; \ MOVL R14, 14*4+off+0(dst); \ MOVL R14, 3*4+off+64(dst); \ MOVL R14, 7*4+off+128(dst); \ MOVL R14, 2*4+off+192(dst); \ MOVL R14, 15*4+off+256(dst); \ MOVL R14, 12*4+off+320(dst); \ MOVL R14, 6*4+off+384(dst); \ MOVL R14, 0*4+off+448(dst); \ MOVL R14, 9*4+off+512(dst); \ MOVL R14, 11*4+off+576(dst); \ \ MOVL R15, 11*4+off+0(dst); \ MOVL R15, 0*4+off+64(dst); \ MOVL R15, 12*4+off+128(dst); \ MOVL R15, 7*4+off+192(dst); \ MOVL R15, 8*4+off+256(dst); \ MOVL R15, 14*4+off+320(dst); \ MOVL R15, 2*4+off+384(dst); \ MOVL R15, 5*4+off+448(dst); \ MOVL R15, 1*4+off+512(dst); \ MOVL R15, 13*4+off+576(dst); \ SHRQ $32, R15; \ MOVL R15, 15*4+off+0(dst); \ MOVL R15, 6*4+off+64(dst); \ MOVL R15, 3*4+off+128(dst); \ MOVL R15, 11*4+off+192(dst); \ MOVL R15, 7*4+off+256(dst); \ MOVL R15, 10*4+off+320(dst); \ MOVL R15, 5*4+off+384(dst); \ MOVL R15, 9*4+off+448(dst); \ MOVL R15, 4*4+off+512(dst); \ MOVL R15, 8*4+off+576(dst) #define BLAKE2s_SSE2() \ PRECOMPUTE_MSG(SP, 16, SI, R8, R9, R10, R11, R12, R13, R14, R15); \ ROUND_SSE2(X4, X5, X6, X7, 16(SP), 32(SP), 48(SP), 64(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+64(SP), 32+64(SP), 48+64(SP), 64+64(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+128(SP), 32+128(SP), 48+128(SP), 64+128(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+192(SP), 32+192(SP), 48+192(SP), 64+192(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+256(SP), 32+256(SP), 48+256(SP), 64+256(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+320(SP), 32+320(SP), 48+320(SP), 64+320(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+384(SP), 32+384(SP), 48+384(SP), 64+384(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+448(SP), 32+448(SP), 48+448(SP), 64+448(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+512(SP), 32+512(SP), 48+512(SP), 64+512(SP), X8); \ ROUND_SSE2(X4, X5, X6, X7, 16+576(SP), 32+576(SP), 48+576(SP), 64+576(SP), X8) #define BLAKE2s_SSSE3() \ PRECOMPUTE_MSG(SP, 16, SI, R8, R9, R10, R11, R12, R13, R14, R15); \ ROUND_SSSE3(X4, X5, X6, X7, 16(SP), 32(SP), 48(SP), 64(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+64(SP), 32+64(SP), 48+64(SP), 64+64(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+128(SP), 32+128(SP), 48+128(SP), 64+128(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+192(SP), 32+192(SP), 48+192(SP), 64+192(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+256(SP), 32+256(SP), 48+256(SP), 64+256(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+320(SP), 32+320(SP), 48+320(SP), 64+320(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+384(SP), 32+384(SP), 48+384(SP), 64+384(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+448(SP), 32+448(SP), 48+448(SP), 64+448(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+512(SP), 32+512(SP), 48+512(SP), 64+512(SP), X8, X13, X14); \ ROUND_SSSE3(X4, X5, X6, X7, 16+576(SP), 32+576(SP), 48+576(SP), 64+576(SP), X8, X13, X14) #define BLAKE2s_SSE4() \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14); \ LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0); \ ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14) #define HASH_BLOCKS(h, c, flag, blocks_base, blocks_len, BLAKE2s_FUNC) \ MOVQ h, AX; \ MOVQ c, BX; \ MOVL flag, CX; \ MOVQ blocks_base, SI; \ MOVQ blocks_len, DX; \ \ MOVQ SP, BP; \ MOVQ SP, R9; \ ADDQ $15, R9; \ ANDQ $~15, R9; \ MOVQ R9, SP; \ \ MOVQ 0(BX), R9; \ MOVQ R9, 0(SP); \ XORQ R9, R9; \ MOVQ R9, 8(SP); \ MOVL CX, 8(SP); \ \ MOVOU 0(AX), X0; \ MOVOU 16(AX), X1; \ MOVOU iv0<>(SB), X2; \ MOVOU iv1<>(SB), X3 \ \ MOVOU counter<>(SB), X12; \ MOVOU rol16<>(SB), X13; \ MOVOU rol8<>(SB), X14; \ MOVO 0(SP), X15; \ \ loop: \ MOVO X0, X4; \ MOVO X1, X5; \ MOVO X2, X6; \ MOVO X3, X7; \ \ PADDQ X12, X15; \ PXOR X15, X7; \ \ BLAKE2s_FUNC(); \ \ PXOR X4, X0; \ PXOR X5, X1; \ PXOR X6, X0; \ PXOR X7, X1; \ \ LEAQ 64(SI), SI; \ SUBQ $64, DX; \ JNE loop; \ \ MOVO X15, 0(SP); \ MOVQ 0(SP), R9; \ MOVQ R9, 0(BX); \ \ MOVOU X0, 0(AX); \ MOVOU X1, 16(AX); \ \ MOVQ BP, SP // func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) TEXT ·hashBlocksSSE2(SB), 0, $672-48 // frame = 656 + 16 byte alignment HASH_BLOCKS(h+0(FP), c+8(FP), flag+16(FP), blocks_base+24(FP), blocks_len+32(FP), BLAKE2s_SSE2) RET // func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) TEXT ·hashBlocksSSSE3(SB), 0, $672-48 // frame = 656 + 16 byte alignment HASH_BLOCKS(h+0(FP), c+8(FP), flag+16(FP), blocks_base+24(FP), blocks_len+32(FP), BLAKE2s_SSSE3) RET // func hashBlocksSSE4(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) TEXT ·hashBlocksSSE4(SB), 0, $32-48 // frame = 16 + 16 byte alignment HASH_BLOCKS(h+0(FP), c+8(FP), flag+16(FP), blocks_base+24(FP), blocks_len+32(FP), BLAKE2s_SSE4) RET // func supportSSE4() bool TEXT ·supportSSE4(SB), 4, $0-1 MOVL $1, AX CPUID SHRL $19, CX // Bit 19 indicates SSE4.1. ANDL $1, CX MOVB CX, ret+0(FP) RET // func supportSSSE3() bool TEXT ·supportSSSE3(SB), 4, $0-1 MOVL $1, AX CPUID MOVL CX, BX ANDL $0x1, BX // Bit zero indicates SSE3 support. JZ FALSE ANDL $0x200, CX // Bit nine indicates SSSE3 support. JZ FALSE MOVB $1, ret+0(FP) RET FALSE: MOVB $0, ret+0(FP) RET �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2s_amd64.go������������������������������������0000644�0610621�0607500�00000001713�13172163317�025244� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!gccgo,!appengine package blake2s var ( useSSE4 = supportSSE4() useSSSE3 = supportSSSE3() useSSE2 = true // Always available on amd64 ) //go:noescape func supportSSSE3() bool //go:noescape func supportSSE4() bool //go:noescape func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) //go:noescape func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) //go:noescape func hashBlocksSSE4(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { if useSSE4 { hashBlocksSSE4(h, c, flag, blocks) } else if useSSSE3 { hashBlocksSSSE3(h, c, flag, blocks) } else if useSSE2 { hashBlocksSSE2(h, c, flag, blocks) } else { hashBlocksGeneric(h, c, flag, blocks) } } �����������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2s_386.s���������������������������������������0000644�0610621�0607500�00000027637�13172163317�024523� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build 386,!gccgo,!appengine #include "textflag.h" DATA iv0<>+0x00(SB)/4, $0x6a09e667 DATA iv0<>+0x04(SB)/4, $0xbb67ae85 DATA iv0<>+0x08(SB)/4, $0x3c6ef372 DATA iv0<>+0x0c(SB)/4, $0xa54ff53a GLOBL iv0<>(SB), (NOPTR+RODATA), $16 DATA iv1<>+0x00(SB)/4, $0x510e527f DATA iv1<>+0x04(SB)/4, $0x9b05688c DATA iv1<>+0x08(SB)/4, $0x1f83d9ab DATA iv1<>+0x0c(SB)/4, $0x5be0cd19 GLOBL iv1<>(SB), (NOPTR+RODATA), $16 DATA rol16<>+0x00(SB)/8, $0x0504070601000302 DATA rol16<>+0x08(SB)/8, $0x0D0C0F0E09080B0A GLOBL rol16<>(SB), (NOPTR+RODATA), $16 DATA rol8<>+0x00(SB)/8, $0x0407060500030201 DATA rol8<>+0x08(SB)/8, $0x0C0F0E0D080B0A09 GLOBL rol8<>(SB), (NOPTR+RODATA), $16 DATA counter<>+0x00(SB)/8, $0x40 DATA counter<>+0x08(SB)/8, $0x0 GLOBL counter<>(SB), (NOPTR+RODATA), $16 #define ROTL_SSE2(n, t, v) \ MOVO v, t; \ PSLLL $n, t; \ PSRLL $(32-n), v; \ PXOR t, v #define ROTL_SSSE3(c, v) \ PSHUFB c, v #define ROUND_SSE2(v0, v1, v2, v3, m0, m1, m2, m3, t) \ PADDL m0, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSE2(16, t, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(20, t, v1); \ PADDL m1, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSE2(24, t, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(25, t, v1); \ PSHUFL $0x39, v1, v1; \ PSHUFL $0x4E, v2, v2; \ PSHUFL $0x93, v3, v3; \ PADDL m2, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSE2(16, t, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(20, t, v1); \ PADDL m3, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSE2(24, t, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(25, t, v1); \ PSHUFL $0x39, v3, v3; \ PSHUFL $0x4E, v2, v2; \ PSHUFL $0x93, v1, v1 #define ROUND_SSSE3(v0, v1, v2, v3, m0, m1, m2, m3, t, c16, c8) \ PADDL m0, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSSE3(c16, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(20, t, v1); \ PADDL m1, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSSE3(c8, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(25, t, v1); \ PSHUFL $0x39, v1, v1; \ PSHUFL $0x4E, v2, v2; \ PSHUFL $0x93, v3, v3; \ PADDL m2, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSSE3(c16, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(20, t, v1); \ PADDL m3, v0; \ PADDL v1, v0; \ PXOR v0, v3; \ ROTL_SSSE3(c8, v3); \ PADDL v3, v2; \ PXOR v2, v1; \ ROTL_SSE2(25, t, v1); \ PSHUFL $0x39, v3, v3; \ PSHUFL $0x4E, v2, v2; \ PSHUFL $0x93, v1, v1 #define PRECOMPUTE(dst, off, src, t) \ MOVL 0*4(src), t; \ MOVL t, 0*4+off+0(dst); \ MOVL t, 9*4+off+64(dst); \ MOVL t, 5*4+off+128(dst); \ MOVL t, 14*4+off+192(dst); \ MOVL t, 4*4+off+256(dst); \ MOVL t, 2*4+off+320(dst); \ MOVL t, 8*4+off+384(dst); \ MOVL t, 12*4+off+448(dst); \ MOVL t, 3*4+off+512(dst); \ MOVL t, 15*4+off+576(dst); \ MOVL 1*4(src), t; \ MOVL t, 4*4+off+0(dst); \ MOVL t, 8*4+off+64(dst); \ MOVL t, 14*4+off+128(dst); \ MOVL t, 5*4+off+192(dst); \ MOVL t, 12*4+off+256(dst); \ MOVL t, 11*4+off+320(dst); \ MOVL t, 1*4+off+384(dst); \ MOVL t, 6*4+off+448(dst); \ MOVL t, 10*4+off+512(dst); \ MOVL t, 3*4+off+576(dst); \ MOVL 2*4(src), t; \ MOVL t, 1*4+off+0(dst); \ MOVL t, 13*4+off+64(dst); \ MOVL t, 6*4+off+128(dst); \ MOVL t, 8*4+off+192(dst); \ MOVL t, 2*4+off+256(dst); \ MOVL t, 0*4+off+320(dst); \ MOVL t, 14*4+off+384(dst); \ MOVL t, 11*4+off+448(dst); \ MOVL t, 12*4+off+512(dst); \ MOVL t, 4*4+off+576(dst); \ MOVL 3*4(src), t; \ MOVL t, 5*4+off+0(dst); \ MOVL t, 15*4+off+64(dst); \ MOVL t, 9*4+off+128(dst); \ MOVL t, 1*4+off+192(dst); \ MOVL t, 11*4+off+256(dst); \ MOVL t, 7*4+off+320(dst); \ MOVL t, 13*4+off+384(dst); \ MOVL t, 3*4+off+448(dst); \ MOVL t, 6*4+off+512(dst); \ MOVL t, 10*4+off+576(dst); \ MOVL 4*4(src), t; \ MOVL t, 2*4+off+0(dst); \ MOVL t, 1*4+off+64(dst); \ MOVL t, 15*4+off+128(dst); \ MOVL t, 10*4+off+192(dst); \ MOVL t, 6*4+off+256(dst); \ MOVL t, 8*4+off+320(dst); \ MOVL t, 3*4+off+384(dst); \ MOVL t, 13*4+off+448(dst); \ MOVL t, 14*4+off+512(dst); \ MOVL t, 5*4+off+576(dst); \ MOVL 5*4(src), t; \ MOVL t, 6*4+off+0(dst); \ MOVL t, 11*4+off+64(dst); \ MOVL t, 2*4+off+128(dst); \ MOVL t, 9*4+off+192(dst); \ MOVL t, 1*4+off+256(dst); \ MOVL t, 13*4+off+320(dst); \ MOVL t, 4*4+off+384(dst); \ MOVL t, 8*4+off+448(dst); \ MOVL t, 15*4+off+512(dst); \ MOVL t, 7*4+off+576(dst); \ MOVL 6*4(src), t; \ MOVL t, 3*4+off+0(dst); \ MOVL t, 7*4+off+64(dst); \ MOVL t, 13*4+off+128(dst); \ MOVL t, 12*4+off+192(dst); \ MOVL t, 10*4+off+256(dst); \ MOVL t, 1*4+off+320(dst); \ MOVL t, 9*4+off+384(dst); \ MOVL t, 14*4+off+448(dst); \ MOVL t, 0*4+off+512(dst); \ MOVL t, 6*4+off+576(dst); \ MOVL 7*4(src), t; \ MOVL t, 7*4+off+0(dst); \ MOVL t, 14*4+off+64(dst); \ MOVL t, 10*4+off+128(dst); \ MOVL t, 0*4+off+192(dst); \ MOVL t, 5*4+off+256(dst); \ MOVL t, 9*4+off+320(dst); \ MOVL t, 12*4+off+384(dst); \ MOVL t, 1*4+off+448(dst); \ MOVL t, 13*4+off+512(dst); \ MOVL t, 2*4+off+576(dst); \ MOVL 8*4(src), t; \ MOVL t, 8*4+off+0(dst); \ MOVL t, 5*4+off+64(dst); \ MOVL t, 4*4+off+128(dst); \ MOVL t, 15*4+off+192(dst); \ MOVL t, 14*4+off+256(dst); \ MOVL t, 3*4+off+320(dst); \ MOVL t, 11*4+off+384(dst); \ MOVL t, 10*4+off+448(dst); \ MOVL t, 7*4+off+512(dst); \ MOVL t, 1*4+off+576(dst); \ MOVL 9*4(src), t; \ MOVL t, 12*4+off+0(dst); \ MOVL t, 2*4+off+64(dst); \ MOVL t, 11*4+off+128(dst); \ MOVL t, 4*4+off+192(dst); \ MOVL t, 0*4+off+256(dst); \ MOVL t, 15*4+off+320(dst); \ MOVL t, 10*4+off+384(dst); \ MOVL t, 7*4+off+448(dst); \ MOVL t, 5*4+off+512(dst); \ MOVL t, 9*4+off+576(dst); \ MOVL 10*4(src), t; \ MOVL t, 9*4+off+0(dst); \ MOVL t, 4*4+off+64(dst); \ MOVL t, 8*4+off+128(dst); \ MOVL t, 13*4+off+192(dst); \ MOVL t, 3*4+off+256(dst); \ MOVL t, 5*4+off+320(dst); \ MOVL t, 7*4+off+384(dst); \ MOVL t, 15*4+off+448(dst); \ MOVL t, 11*4+off+512(dst); \ MOVL t, 0*4+off+576(dst); \ MOVL 11*4(src), t; \ MOVL t, 13*4+off+0(dst); \ MOVL t, 10*4+off+64(dst); \ MOVL t, 0*4+off+128(dst); \ MOVL t, 3*4+off+192(dst); \ MOVL t, 9*4+off+256(dst); \ MOVL t, 6*4+off+320(dst); \ MOVL t, 15*4+off+384(dst); \ MOVL t, 4*4+off+448(dst); \ MOVL t, 2*4+off+512(dst); \ MOVL t, 12*4+off+576(dst); \ MOVL 12*4(src), t; \ MOVL t, 10*4+off+0(dst); \ MOVL t, 12*4+off+64(dst); \ MOVL t, 1*4+off+128(dst); \ MOVL t, 6*4+off+192(dst); \ MOVL t, 13*4+off+256(dst); \ MOVL t, 4*4+off+320(dst); \ MOVL t, 0*4+off+384(dst); \ MOVL t, 2*4+off+448(dst); \ MOVL t, 8*4+off+512(dst); \ MOVL t, 14*4+off+576(dst); \ MOVL 13*4(src), t; \ MOVL t, 14*4+off+0(dst); \ MOVL t, 3*4+off+64(dst); \ MOVL t, 7*4+off+128(dst); \ MOVL t, 2*4+off+192(dst); \ MOVL t, 15*4+off+256(dst); \ MOVL t, 12*4+off+320(dst); \ MOVL t, 6*4+off+384(dst); \ MOVL t, 0*4+off+448(dst); \ MOVL t, 9*4+off+512(dst); \ MOVL t, 11*4+off+576(dst); \ MOVL 14*4(src), t; \ MOVL t, 11*4+off+0(dst); \ MOVL t, 0*4+off+64(dst); \ MOVL t, 12*4+off+128(dst); \ MOVL t, 7*4+off+192(dst); \ MOVL t, 8*4+off+256(dst); \ MOVL t, 14*4+off+320(dst); \ MOVL t, 2*4+off+384(dst); \ MOVL t, 5*4+off+448(dst); \ MOVL t, 1*4+off+512(dst); \ MOVL t, 13*4+off+576(dst); \ MOVL 15*4(src), t; \ MOVL t, 15*4+off+0(dst); \ MOVL t, 6*4+off+64(dst); \ MOVL t, 3*4+off+128(dst); \ MOVL t, 11*4+off+192(dst); \ MOVL t, 7*4+off+256(dst); \ MOVL t, 10*4+off+320(dst); \ MOVL t, 5*4+off+384(dst); \ MOVL t, 9*4+off+448(dst); \ MOVL t, 4*4+off+512(dst); \ MOVL t, 8*4+off+576(dst) // func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) TEXT ·hashBlocksSSE2(SB), 0, $672-24 // frame = 656 + 16 byte alignment MOVL h+0(FP), AX MOVL c+4(FP), BX MOVL flag+8(FP), CX MOVL blocks_base+12(FP), SI MOVL blocks_len+16(FP), DX MOVL SP, BP MOVL SP, DI ADDL $15, DI ANDL $~15, DI MOVL DI, SP MOVL CX, 8(SP) MOVL 0(BX), CX MOVL CX, 0(SP) MOVL 4(BX), CX MOVL CX, 4(SP) XORL CX, CX MOVL CX, 12(SP) MOVOU 0(AX), X0 MOVOU 16(AX), X1 MOVOU counter<>(SB), X2 loop: MOVO X0, X4 MOVO X1, X5 MOVOU iv0<>(SB), X6 MOVOU iv1<>(SB), X7 MOVO 0(SP), X3 PADDQ X2, X3 PXOR X3, X7 MOVO X3, 0(SP) PRECOMPUTE(SP, 16, SI, CX) ROUND_SSE2(X4, X5, X6, X7, 16(SP), 32(SP), 48(SP), 64(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+64(SP), 32+64(SP), 48+64(SP), 64+64(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+128(SP), 32+128(SP), 48+128(SP), 64+128(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+192(SP), 32+192(SP), 48+192(SP), 64+192(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+256(SP), 32+256(SP), 48+256(SP), 64+256(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+320(SP), 32+320(SP), 48+320(SP), 64+320(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+384(SP), 32+384(SP), 48+384(SP), 64+384(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+448(SP), 32+448(SP), 48+448(SP), 64+448(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+512(SP), 32+512(SP), 48+512(SP), 64+512(SP), X3) ROUND_SSE2(X4, X5, X6, X7, 16+576(SP), 32+576(SP), 48+576(SP), 64+576(SP), X3) PXOR X4, X0 PXOR X5, X1 PXOR X6, X0 PXOR X7, X1 LEAL 64(SI), SI SUBL $64, DX JNE loop MOVL 0(SP), CX MOVL CX, 0(BX) MOVL 4(SP), CX MOVL CX, 4(BX) MOVOU X0, 0(AX) MOVOU X1, 16(AX) MOVL BP, SP RET // func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) TEXT ·hashBlocksSSSE3(SB), 0, $704-24 // frame = 688 + 16 byte alignment MOVL h+0(FP), AX MOVL c+4(FP), BX MOVL flag+8(FP), CX MOVL blocks_base+12(FP), SI MOVL blocks_len+16(FP), DX MOVL SP, BP MOVL SP, DI ADDL $15, DI ANDL $~15, DI MOVL DI, SP MOVL CX, 8(SP) MOVL 0(BX), CX MOVL CX, 0(SP) MOVL 4(BX), CX MOVL CX, 4(SP) XORL CX, CX MOVL CX, 12(SP) MOVOU 0(AX), X0 MOVOU 16(AX), X1 MOVOU counter<>(SB), X2 loop: MOVO X0, 656(SP) MOVO X1, 672(SP) MOVO X0, X4 MOVO X1, X5 MOVOU iv0<>(SB), X6 MOVOU iv1<>(SB), X7 MOVO 0(SP), X3 PADDQ X2, X3 PXOR X3, X7 MOVO X3, 0(SP) MOVOU rol16<>(SB), X0 MOVOU rol8<>(SB), X1 PRECOMPUTE(SP, 16, SI, CX) ROUND_SSSE3(X4, X5, X6, X7, 16(SP), 32(SP), 48(SP), 64(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+64(SP), 32+64(SP), 48+64(SP), 64+64(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+128(SP), 32+128(SP), 48+128(SP), 64+128(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+192(SP), 32+192(SP), 48+192(SP), 64+192(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+256(SP), 32+256(SP), 48+256(SP), 64+256(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+320(SP), 32+320(SP), 48+320(SP), 64+320(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+384(SP), 32+384(SP), 48+384(SP), 64+384(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+448(SP), 32+448(SP), 48+448(SP), 64+448(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+512(SP), 32+512(SP), 48+512(SP), 64+512(SP), X3, X0, X1) ROUND_SSSE3(X4, X5, X6, X7, 16+576(SP), 32+576(SP), 48+576(SP), 64+576(SP), X3, X0, X1) MOVO 656(SP), X0 MOVO 672(SP), X1 PXOR X4, X0 PXOR X5, X1 PXOR X6, X0 PXOR X7, X1 LEAL 64(SI), SI SUBL $64, DX JNE loop MOVL 0(SP), CX MOVL CX, 0(BX) MOVL 4(SP), CX MOVL CX, 4(BX) MOVOU X0, 0(AX) MOVOU X1, 16(AX) MOVL BP, SP RET // func supportSSSE3() bool TEXT ·supportSSSE3(SB), 4, $0-1 MOVL $1, AX CPUID MOVL CX, BX ANDL $0x1, BX // supports SSE3 JZ FALSE ANDL $0x200, CX // supports SSSE3 JZ FALSE MOVB $1, ret+0(FP) RET FALSE: MOVB $0, ret+0(FP) RET // func supportSSE2() bool TEXT ·supportSSE2(SB), 4, $0-1 MOVL $1, AX CPUID SHRL $26, DX ANDL $1, DX // DX != 0 if support SSE2 MOVB DX, ret+0(FP) RET �������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2s_386.go��������������������������������������0000644�0610621�0607500�00000001430�13172163317�024645� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build 386,!gccgo,!appengine package blake2s var ( useSSE4 = false useSSSE3 = supportSSSE3() useSSE2 = supportSSE2() ) //go:noescape func supportSSE2() bool //go:noescape func supportSSSE3() bool //go:noescape func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) //go:noescape func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { if useSSSE3 { hashBlocksSSSE3(h, c, flag, blocks) } else if useSSE2 { hashBlocksSSE2(h, c, flag, blocks) } else { hashBlocksGeneric(h, c, flag, blocks) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2s/blake2s.go������������������������������������������0000644�0610621�0607500�00000010353�13172163317�024251� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package blake2s implements the BLAKE2s hash algorithm defined by RFC 7693 // and the extendable output function (XOF) BLAKE2Xs. // // For a detailed specification of BLAKE2s see https://blake2.net/blake2.pdf // and for BLAKE2Xs see https://blake2.net/blake2x.pdf // // If you aren't sure which function you need, use BLAKE2s (Sum256 or New256). // If you need a secret-key MAC (message authentication code), use the New256 // function with a non-nil key. // // BLAKE2X is a construction to compute hash values larger than 32 bytes. It // can produce hash values between 0 and 65535 bytes. package blake2s // import "golang.org/x/crypto/blake2s" import ( "encoding/binary" "errors" "hash" ) const ( // The blocksize of BLAKE2s in bytes. BlockSize = 64 // The hash size of BLAKE2s-256 in bytes. Size = 32 // The hash size of BLAKE2s-128 in bytes. Size128 = 16 ) var errKeySize = errors.New("blake2s: invalid key size") var iv = [8]uint32{ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, } // Sum256 returns the BLAKE2s-256 checksum of the data. func Sum256(data []byte) [Size]byte { var sum [Size]byte checkSum(&sum, Size, data) return sum } // New256 returns a new hash.Hash computing the BLAKE2s-256 checksum. A non-nil // key turns the hash into a MAC. The key must between zero and 32 bytes long. func New256(key []byte) (hash.Hash, error) { return newDigest(Size, key) } // New128 returns a new hash.Hash computing the BLAKE2s-128 checksum given a // non-empty key. Note that a 128-bit digest is too small to be secure as a // cryptographic hash and should only be used as a MAC, thus the key argument // is not optional. func New128(key []byte) (hash.Hash, error) { if len(key) == 0 { return nil, errors.New("blake2s: a key is required for a 128-bit hash") } return newDigest(Size128, key) } func newDigest(hashSize int, key []byte) (*digest, error) { if len(key) > Size { return nil, errKeySize } d := &digest{ size: hashSize, keyLen: len(key), } copy(d.key[:], key) d.Reset() return d, nil } func checkSum(sum *[Size]byte, hashSize int, data []byte) { var ( h [8]uint32 c [2]uint32 ) h = iv h[0] ^= uint32(hashSize) | (1 << 16) | (1 << 24) if length := len(data); length > BlockSize { n := length &^ (BlockSize - 1) if length == n { n -= BlockSize } hashBlocks(&h, &c, 0, data[:n]) data = data[n:] } var block [BlockSize]byte offset := copy(block[:], data) remaining := uint32(BlockSize - offset) if c[0] < remaining { c[1]-- } c[0] -= remaining hashBlocks(&h, &c, 0xFFFFFFFF, block[:]) for i, v := range h { binary.LittleEndian.PutUint32(sum[4*i:], v) } } type digest struct { h [8]uint32 c [2]uint32 size int block [BlockSize]byte offset int key [BlockSize]byte keyLen int } func (d *digest) BlockSize() int { return BlockSize } func (d *digest) Size() int { return d.size } func (d *digest) Reset() { d.h = iv d.h[0] ^= uint32(d.size) | (uint32(d.keyLen) << 8) | (1 << 16) | (1 << 24) d.offset, d.c[0], d.c[1] = 0, 0, 0 if d.keyLen > 0 { d.block = d.key d.offset = BlockSize } } func (d *digest) Write(p []byte) (n int, err error) { n = len(p) if d.offset > 0 { remaining := BlockSize - d.offset if n <= remaining { d.offset += copy(d.block[d.offset:], p) return } copy(d.block[d.offset:], p[:remaining]) hashBlocks(&d.h, &d.c, 0, d.block[:]) d.offset = 0 p = p[remaining:] } if length := len(p); length > BlockSize { nn := length &^ (BlockSize - 1) if length == nn { nn -= BlockSize } hashBlocks(&d.h, &d.c, 0, p[:nn]) p = p[nn:] } d.offset += copy(d.block[:], p) return } func (d *digest) Sum(sum []byte) []byte { var hash [Size]byte d.finalize(&hash) return append(sum, hash[:d.size]...) } func (d *digest) finalize(hash *[Size]byte) { var block [BlockSize]byte h := d.h c := d.c copy(block[:], d.block[:d.offset]) remaining := uint32(BlockSize - d.offset) if c[0] < remaining { c[1]-- } c[0] -= remaining hashBlocks(&h, &c, 0xFFFFFFFF, block[:]) for i, v := range h { binary.LittleEndian.PutUint32(hash[4*i:], v) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022354� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/register.go�����������������������������������������0000644�0610621�0607500�00000001143�13172163317�024526� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.9 package blake2b import ( "crypto" "hash" ) func init() { newHash256 := func() hash.Hash { h, _ := New256(nil) return h } newHash384 := func() hash.Hash { h, _ := New384(nil) return h } newHash512 := func() hash.Hash { h, _ := New512(nil) return h } crypto.RegisterHash(crypto.BLAKE2b_256, newHash256) crypto.RegisterHash(crypto.BLAKE2b_384, newHash384) crypto.RegisterHash(crypto.BLAKE2b_512, newHash512) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2x.go������������������������������������������0000644�0610621�0607500�00000010053�13172163317�024232� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package blake2b import ( "encoding/binary" "errors" "io" ) // XOF defines the interface to hash functions that // support arbitrary-length output. type XOF interface { // Write absorbs more data into the hash's state. It panics if called // after Read. io.Writer // Read reads more output from the hash. It returns io.EOF if the limit // has been reached. io.Reader // Clone returns a copy of the XOF in its current state. Clone() XOF // Reset resets the XOF to its initial state. Reset() } // OutputLengthUnknown can be used as the size argument to NewXOF to indicate // the the length of the output is not known in advance. const OutputLengthUnknown = 0 // magicUnknownOutputLength is a magic value for the output size that indicates // an unknown number of output bytes. const magicUnknownOutputLength = (1 << 32) - 1 // maxOutputLength is the absolute maximum number of bytes to produce when the // number of output bytes is unknown. const maxOutputLength = (1 << 32) * 64 // NewXOF creates a new variable-output-length hash. The hash either produce a // known number of bytes (1 <= size < 2**32-1), or an unknown number of bytes // (size == OutputLengthUnknown). In the latter case, an absolute limit of // 256GiB applies. // // A non-nil key turns the hash into a MAC. The key must between // zero and 32 bytes long. func NewXOF(size uint32, key []byte) (XOF, error) { if len(key) > Size { return nil, errKeySize } if size == magicUnknownOutputLength { // 2^32-1 indicates an unknown number of bytes and thus isn't a // valid length. return nil, errors.New("blake2b: XOF length too large") } if size == OutputLengthUnknown { size = magicUnknownOutputLength } x := &xof{ d: digest{ size: Size, keyLen: len(key), }, length: size, } copy(x.d.key[:], key) x.Reset() return x, nil } type xof struct { d digest length uint32 remaining uint64 cfg, root, block [Size]byte offset int nodeOffset uint32 readMode bool } func (x *xof) Write(p []byte) (n int, err error) { if x.readMode { panic("blake2b: write to XOF after read") } return x.d.Write(p) } func (x *xof) Clone() XOF { clone := *x return &clone } func (x *xof) Reset() { x.cfg[0] = byte(Size) binary.LittleEndian.PutUint32(x.cfg[4:], uint32(Size)) // leaf length binary.LittleEndian.PutUint32(x.cfg[12:], x.length) // XOF length x.cfg[17] = byte(Size) // inner hash size x.d.Reset() x.d.h[1] ^= uint64(x.length) << 32 x.remaining = uint64(x.length) if x.remaining == magicUnknownOutputLength { x.remaining = maxOutputLength } x.offset, x.nodeOffset = 0, 0 x.readMode = false } func (x *xof) Read(p []byte) (n int, err error) { if !x.readMode { x.d.finalize(&x.root) x.readMode = true } if x.remaining == 0 { return 0, io.EOF } n = len(p) if uint64(n) > x.remaining { n = int(x.remaining) p = p[:n] } if x.offset > 0 { blockRemaining := Size - x.offset if n < blockRemaining { x.offset += copy(p, x.block[x.offset:]) x.remaining -= uint64(n) return } copy(p, x.block[x.offset:]) p = p[blockRemaining:] x.offset = 0 x.remaining -= uint64(blockRemaining) } for len(p) >= Size { binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) x.nodeOffset++ x.d.initConfig(&x.cfg) x.d.Write(x.root[:]) x.d.finalize(&x.block) copy(p, x.block[:]) p = p[Size:] x.remaining -= uint64(Size) } if todo := len(p); todo > 0 { if x.remaining < uint64(Size) { x.cfg[0] = byte(x.remaining) } binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) x.nodeOffset++ x.d.initConfig(&x.cfg) x.d.Write(x.root[:]) x.d.finalize(&x.block) x.offset = copy(p, x.block[:todo]) x.remaining -= uint64(todo) } return } func (d *digest) initConfig(cfg *[Size]byte) { d.offset, d.c[0], d.c[1] = 0, 0, 0 for i := range d.h { d.h[i] = iv[i] ^ binary.LittleEndian.Uint64(cfg[i*8:]) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2b_test.go�������������������������������������0000644�0610621�0607500�00000322477�13172163317�025263� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package blake2b import ( "bytes" "encoding/hex" "fmt" "hash" "io" "testing" ) func fromHex(s string) []byte { b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } func TestHashes(t *testing.T) { defer func(sse4, avx, avx2 bool) { useSSE4, useAVX, useAVX2 = sse4, avx, avx2 }(useSSE4, useAVX, useAVX2) if useAVX2 { t.Log("AVX2 version") testHashes(t) useAVX2 = false } if useAVX { t.Log("AVX version") testHashes(t) useAVX = false } if useSSE4 { t.Log("SSE4 version") testHashes(t) useSSE4 = false } t.Log("generic version") testHashes(t) } func TestHashes2X(t *testing.T) { defer func(sse4, avx, avx2 bool) { useSSE4, useAVX, useAVX2 = sse4, avx, avx2 }(useSSE4, useAVX, useAVX2) if useAVX2 { t.Log("AVX2 version") testHashes2X(t) useAVX2 = false } if useAVX { t.Log("AVX version") testHashes2X(t) useAVX = false } if useSSE4 { t.Log("SSE4 version") testHashes2X(t) useSSE4 = false } t.Log("generic version") testHashes2X(t) } func testHashes(t *testing.T) { key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f") input := make([]byte, 255) for i := range input { input[i] = byte(i) } for i, expectedHex := range hashes { h, err := New512(key) if err != nil { t.Fatalf("#%d: error from New512: %v", i, err) } h.Write(input[:i]) sum := h.Sum(nil) if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (single write): got %s, wanted %s", i, gotHex, expectedHex) } h.Reset() for j := 0; j < i; j++ { h.Write(input[j : j+1]) } sum = h.Sum(sum[:0]) if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (byte-by-byte): got %s, wanted %s", i, gotHex, expectedHex) } } } func testHashes2X(t *testing.T) { key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f") input := make([]byte, 256) for i := range input { input[i] = byte(i) } for i, expectedHex := range hashes2X { length := uint32(len(expectedHex) / 2) sum := make([]byte, int(length)) h, err := NewXOF(length, key) if err != nil { t.Fatalf("#%d: error from NewXOF: %v", i, err) } if _, err := h.Write(input); err != nil { t.Fatalf("#%d (single write): error from Write: %v", i, err) } if _, err := h.Read(sum); err != nil { t.Fatalf("#%d (single write): error from Read: %v", i, err) } if n, err := h.Read(sum); n != 0 || err != io.EOF { t.Fatalf("#%d (single write): Read did not return (0, io.EOF) after exhaustion, got (%v, %v)", i, n, err) } if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (single write): got %s, wanted %s", i, gotHex, expectedHex) } h.Reset() for j := 0; j < len(input); j++ { h.Write(input[j : j+1]) } for j := 0; j < len(sum); j++ { h = h.Clone() if _, err := h.Read(sum[j : j+1]); err != nil { t.Fatalf("#%d (byte-by-byte) - Read %d: error from Read: %v", i, j, err) } } if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex { t.Fatalf("#%d (byte-by-byte): got %s, wanted %s", i, gotHex, expectedHex) } } h, err := NewXOF(OutputLengthUnknown, key) if err != nil { t.Fatalf("#unknown length: error from NewXOF: %v", err) } if _, err := h.Write(input); err != nil { t.Fatalf("#unknown length: error from Write: %v", err) } var result [64]byte if n, err := h.Read(result[:]); err != nil { t.Fatalf("#unknown length: error from Read: %v", err) } else if n != len(result) { t.Fatalf("#unknown length: Read returned %d bytes, want %d", n, len(result)) } const expected = "3dbba8516da76bf7330055c66ea36cf1005e92714262b24d9710f51d9e126406e1bcd6497059f9331f1091c3634b695428d475ed432f987040575520a1c29f5e" if fmt.Sprintf("%x", result) != expected { t.Fatalf("#unknown length: bad result %x, wanted %s", result, expected) } } func generateSequence(out []byte, seed uint32) { a := 0xDEAD4BAD * seed // prime b := uint32(1) for i := range out { // fill the buf a, b = b, a+b out[i] = byte(b >> 24) } } func computeMAC(msg []byte, hashSize int, key []byte) (sum []byte) { var h hash.Hash switch hashSize { case Size: h, _ = New512(key) case Size384: h, _ = New384(key) case Size256: h, _ = New256(key) case 20: h, _ = newDigest(20, key) default: panic("unexpected hashSize") } h.Write(msg) return h.Sum(sum) } func computeHash(msg []byte, hashSize int) (sum []byte) { switch hashSize { case Size: hash := Sum512(msg) return hash[:] case Size384: hash := Sum384(msg) return hash[:] case Size256: hash := Sum256(msg) return hash[:] case 20: var hash [64]byte checkSum(&hash, 20, msg) return hash[:20] default: panic("unexpected hashSize") } } // Test function from RFC 7693. func TestSelfTest(t *testing.T) { hashLens := [4]int{20, 32, 48, 64} msgLens := [6]int{0, 3, 128, 129, 255, 1024} msg := make([]byte, 1024) key := make([]byte, 64) h, _ := New256(nil) for _, hashSize := range hashLens { for _, msgLength := range msgLens { generateSequence(msg[:msgLength], uint32(msgLength)) // unkeyed hash md := computeHash(msg[:msgLength], hashSize) h.Write(md) generateSequence(key[:], uint32(hashSize)) // keyed hash md = computeMAC(msg[:msgLength], hashSize, key[:hashSize]) h.Write(md) } } sum := h.Sum(nil) expected := [32]byte{ 0xc2, 0x3a, 0x78, 0x00, 0xd9, 0x81, 0x23, 0xbd, 0x10, 0xf5, 0x06, 0xc6, 0x1e, 0x29, 0xda, 0x56, 0x03, 0xd7, 0x63, 0xb8, 0xbb, 0xad, 0x2e, 0x73, 0x7f, 0x5e, 0x76, 0x5a, 0x7b, 0xcc, 0xd4, 0x75, } if !bytes.Equal(sum, expected[:]) { t.Fatalf("got %x, wanted %x", sum, expected) } } // Benchmarks func benchmarkSum(b *testing.B, size int) { data := make([]byte, size) b.SetBytes(int64(size)) b.ResetTimer() for i := 0; i < b.N; i++ { Sum512(data) } } func benchmarkWrite(b *testing.B, size int) { data := make([]byte, size) h, _ := New512(nil) b.SetBytes(int64(size)) b.ResetTimer() for i := 0; i < b.N; i++ { h.Write(data) } } func BenchmarkWrite128(b *testing.B) { benchmarkWrite(b, 128) } func BenchmarkWrite1K(b *testing.B) { benchmarkWrite(b, 1024) } func BenchmarkSum128(b *testing.B) { benchmarkSum(b, 128) } func BenchmarkSum1K(b *testing.B) { benchmarkSum(b, 1024) } // These values were taken from https://blake2.net/blake2b-test.txt. var hashes = []string{ "10ebb67700b1868efb4417987acf4690ae9d972fb7a590c2f02871799aaa4786b5e996e8f0f4eb981fc214b005f42d2ff4233499391653df7aefcbc13fc51568", "961f6dd1e4dd30f63901690c512e78e4b45e4742ed197c3c5e45c549fd25f2e4187b0bc9fe30492b16b0d0bc4ef9b0f34c7003fac09a5ef1532e69430234cebd", "da2cfbe2d8409a0f38026113884f84b50156371ae304c4430173d08a99d9fb1b983164a3770706d537f49e0c916d9f32b95cc37a95b99d857436f0232c88a965", "33d0825dddf7ada99b0e7e307104ad07ca9cfd9692214f1561356315e784f3e5a17e364ae9dbb14cb2036df932b77f4b292761365fb328de7afdc6d8998f5fc1", "beaa5a3d08f3807143cf621d95cd690514d0b49efff9c91d24b59241ec0eefa5f60196d407048bba8d2146828ebcb0488d8842fd56bb4f6df8e19c4b4daab8ac", "098084b51fd13deae5f4320de94a688ee07baea2800486689a8636117b46c1f4c1f6af7f74ae7c857600456a58a3af251dc4723a64cc7c0a5ab6d9cac91c20bb", "6044540d560853eb1c57df0077dd381094781cdb9073e5b1b3d3f6c7829e12066bbaca96d989a690de72ca3133a83652ba284a6d62942b271ffa2620c9e75b1f", "7a8cfe9b90f75f7ecb3acc053aaed6193112b6f6a4aeeb3f65d3de541942deb9e2228152a3c4bbbe72fc3b12629528cfbb09fe630f0474339f54abf453e2ed52", "380beaf6ea7cc9365e270ef0e6f3a64fb902acae51dd5512f84259ad2c91f4bc4108db73192a5bbfb0cbcf71e46c3e21aee1c5e860dc96e8eb0b7b8426e6abe9", "60fe3c4535e1b59d9a61ea8500bfac41a69dffb1ceadd9aca323e9a625b64da5763bad7226da02b9c8c4f1a5de140ac5a6c1124e4f718ce0b28ea47393aa6637", "4fe181f54ad63a2983feaaf77d1e7235c2beb17fa328b6d9505bda327df19fc37f02c4b6f0368ce23147313a8e5738b5fa2a95b29de1c7f8264eb77b69f585cd", "f228773ce3f3a42b5f144d63237a72d99693adb8837d0e112a8a0f8ffff2c362857ac49c11ec740d1500749dac9b1f4548108bf3155794dcc9e4082849e2b85b", "962452a8455cc56c8511317e3b1f3b2c37df75f588e94325fdd77070359cf63a9ae6e930936fdf8e1e08ffca440cfb72c28f06d89a2151d1c46cd5b268ef8563", "43d44bfa18768c59896bf7ed1765cb2d14af8c260266039099b25a603e4ddc5039d6ef3a91847d1088d401c0c7e847781a8a590d33a3c6cb4df0fab1c2f22355", "dcffa9d58c2a4ca2cdbb0c7aa4c4c1d45165190089f4e983bb1c2cab4aaeff1fa2b5ee516fecd780540240bf37e56c8bcca7fab980e1e61c9400d8a9a5b14ac6", "6fbf31b45ab0c0b8dad1c0f5f4061379912dde5aa922099a030b725c73346c524291adef89d2f6fd8dfcda6d07dad811a9314536c2915ed45da34947e83de34e", "a0c65bddde8adef57282b04b11e7bc8aab105b99231b750c021f4a735cb1bcfab87553bba3abb0c3e64a0b6955285185a0bd35fb8cfde557329bebb1f629ee93", "f99d815550558e81eca2f96718aed10d86f3f1cfb675cce06b0eff02f617c5a42c5aa760270f2679da2677c5aeb94f1142277f21c7f79f3c4f0cce4ed8ee62b1", "95391da8fc7b917a2044b3d6f5374e1ca072b41454d572c7356c05fd4bc1e0f40b8bb8b4a9f6bce9be2c4623c399b0dca0dab05cb7281b71a21b0ebcd9e55670", "04b9cd3d20d221c09ac86913d3dc63041989a9a1e694f1e639a3ba7e451840f750c2fc191d56ad61f2e7936bc0ac8e094b60caeed878c18799045402d61ceaf9", "ec0e0ef707e4ed6c0c66f9e089e4954b058030d2dd86398fe84059631f9ee591d9d77375355149178c0cf8f8e7c49ed2a5e4f95488a2247067c208510fadc44c", "9a37cce273b79c09913677510eaf7688e89b3314d3532fd2764c39de022a2945b5710d13517af8ddc0316624e73bec1ce67df15228302036f330ab0cb4d218dd", "4cf9bb8fb3d4de8b38b2f262d3c40f46dfe747e8fc0a414c193d9fcf753106ce47a18f172f12e8a2f1c26726545358e5ee28c9e2213a8787aafbc516d2343152", "64e0c63af9c808fd893137129867fd91939d53f2af04be4fa268006100069b2d69daa5c5d8ed7fddcb2a70eeecdf2b105dd46a1e3b7311728f639ab489326bc9", "5e9c93158d659b2def06b0c3c7565045542662d6eee8a96a89b78ade09fe8b3dcc096d4fe48815d88d8f82620156602af541955e1f6ca30dce14e254c326b88f", "7775dff889458dd11aef417276853e21335eb88e4dec9cfb4e9edb49820088551a2ca60339f12066101169f0dfe84b098fddb148d9da6b3d613df263889ad64b", "f0d2805afbb91f743951351a6d024f9353a23c7ce1fc2b051b3a8b968c233f46f50f806ecb1568ffaa0b60661e334b21dde04f8fa155ac740eeb42e20b60d764", "86a2af316e7d7754201b942e275364ac12ea8962ab5bd8d7fb276dc5fbffc8f9a28cae4e4867df6780d9b72524160927c855da5b6078e0b554aa91e31cb9ca1d", "10bdf0caa0802705e706369baf8a3f79d72c0a03a80675a7bbb00be3a45e516424d1ee88efb56f6d5777545ae6e27765c3a8f5e493fc308915638933a1dfee55", "b01781092b1748459e2e4ec178696627bf4ebafebba774ecf018b79a68aeb84917bf0b84bb79d17b743151144cd66b7b33a4b9e52c76c4e112050ff5385b7f0b", "c6dbc61dec6eaeac81e3d5f755203c8e220551534a0b2fd105a91889945a638550204f44093dd998c076205dffad703a0e5cd3c7f438a7e634cd59fededb539e", "eba51acffb4cea31db4b8d87e9bf7dd48fe97b0253ae67aa580f9ac4a9d941f2bea518ee286818cc9f633f2a3b9fb68e594b48cdd6d515bf1d52ba6c85a203a7", "86221f3ada52037b72224f105d7999231c5e5534d03da9d9c0a12acb68460cd375daf8e24386286f9668f72326dbf99ba094392437d398e95bb8161d717f8991", "5595e05c13a7ec4dc8f41fb70cb50a71bce17c024ff6de7af618d0cc4e9c32d9570d6d3ea45b86525491030c0d8f2b1836d5778c1ce735c17707df364d054347", "ce0f4f6aca89590a37fe034dd74dd5fa65eb1cbd0a41508aaddc09351a3cea6d18cb2189c54b700c009f4cbf0521c7ea01be61c5ae09cb54f27bc1b44d658c82", "7ee80b06a215a3bca970c77cda8761822bc103d44fa4b33f4d07dcb997e36d55298bceae12241b3fa07fa63be5576068da387b8d5859aeab701369848b176d42", "940a84b6a84d109aab208c024c6ce9647676ba0aaa11f86dbb7018f9fd2220a6d901a9027f9abcf935372727cbf09ebd61a2a2eeb87653e8ecad1bab85dc8327", "2020b78264a82d9f4151141adba8d44bf20c5ec062eee9b595a11f9e84901bf148f298e0c9f8777dcdbc7cc4670aac356cc2ad8ccb1629f16f6a76bcefbee760", "d1b897b0e075ba68ab572adf9d9c436663e43eb3d8e62d92fc49c9be214e6f27873fe215a65170e6bea902408a25b49506f47babd07cecf7113ec10c5dd31252", "b14d0c62abfa469a357177e594c10c194243ed2025ab8aa5ad2fa41ad318e0ff48cd5e60bec07b13634a711d2326e488a985f31e31153399e73088efc86a5c55", "4169c5cc808d2697dc2a82430dc23e3cd356dc70a94566810502b8d655b39abf9e7f902fe717e0389219859e1945df1af6ada42e4ccda55a197b7100a30c30a1", "258a4edb113d66c839c8b1c91f15f35ade609f11cd7f8681a4045b9fef7b0b24c82cda06a5f2067b368825e3914e53d6948ede92efd6e8387fa2e537239b5bee", "79d2d8696d30f30fb34657761171a11e6c3f1e64cbe7bebee159cb95bfaf812b4f411e2f26d9c421dc2c284a3342d823ec293849e42d1e46b0a4ac1e3c86abaa", "8b9436010dc5dee992ae38aea97f2cd63b946d94fedd2ec9671dcde3bd4ce9564d555c66c15bb2b900df72edb6b891ebcadfeff63c9ea4036a998be7973981e7", "c8f68e696ed28242bf997f5b3b34959508e42d613810f1e2a435c96ed2ff560c7022f361a9234b9837feee90bf47922ee0fd5f8ddf823718d86d1e16c6090071", "b02d3eee4860d5868b2c39ce39bfe81011290564dd678c85e8783f29302dfc1399ba95b6b53cd9ebbf400cca1db0ab67e19a325f2d115812d25d00978ad1bca4", "7693ea73af3ac4dad21ca0d8da85b3118a7d1c6024cfaf557699868217bc0c2f44a199bc6c0edd519798ba05bd5b1b4484346a47c2cadf6bf30b785cc88b2baf", "a0e5c1c0031c02e48b7f09a5e896ee9aef2f17fc9e18e997d7f6cac7ae316422c2b1e77984e5f3a73cb45deed5d3f84600105e6ee38f2d090c7d0442ea34c46d", "41daa6adcfdb69f1440c37b596440165c15ada596813e2e22f060fcd551f24dee8e04ba6890387886ceec4a7a0d7fc6b44506392ec3822c0d8c1acfc7d5aebe8", "14d4d40d5984d84c5cf7523b7798b254e275a3a8cc0a1bd06ebc0bee726856acc3cbf516ff667cda2058ad5c3412254460a82c92187041363cc77a4dc215e487", "d0e7a1e2b9a447fee83e2277e9ff8010c2f375ae12fa7aaa8ca5a6317868a26a367a0b69fbc1cf32a55d34eb370663016f3d2110230eba754028a56f54acf57c", "e771aa8db5a3e043e8178f39a0857ba04a3f18e4aa05743cf8d222b0b095825350ba422f63382a23d92e4149074e816a36c1cd28284d146267940b31f8818ea2", "feb4fd6f9e87a56bef398b3284d2bda5b5b0e166583a66b61e538457ff0584872c21a32962b9928ffab58de4af2edd4e15d8b35570523207ff4e2a5aa7754caa", "462f17bf005fb1c1b9e671779f665209ec2873e3e411f98dabf240a1d5ec3f95ce6796b6fc23fe171903b502023467dec7273ff74879b92967a2a43a5a183d33", "d3338193b64553dbd38d144bea71c5915bb110e2d88180dbc5db364fd6171df317fc7268831b5aef75e4342b2fad8797ba39eddcef80e6ec08159350b1ad696d", "e1590d585a3d39f7cb599abd479070966409a6846d4377acf4471d065d5db94129cc9be92573b05ed226be1e9b7cb0cabe87918589f80dadd4ef5ef25a93d28e", "f8f3726ac5a26cc80132493a6fedcb0e60760c09cfc84cad178175986819665e76842d7b9fedf76dddebf5d3f56faaad4477587af21606d396ae570d8e719af2", "30186055c07949948183c850e9a756cc09937e247d9d928e869e20bafc3cd9721719d34e04a0899b92c736084550186886efba2e790d8be6ebf040b209c439a4", "f3c4276cb863637712c241c444c5cc1e3554e0fddb174d035819dd83eb700b4ce88df3ab3841ba02085e1a99b4e17310c5341075c0458ba376c95a6818fbb3e2", "0aa007c4dd9d5832393040a1583c930bca7dc5e77ea53add7e2b3f7c8e231368043520d4a3ef53c969b6bbfd025946f632bd7f765d53c21003b8f983f75e2a6a", "08e9464720533b23a04ec24f7ae8c103145f765387d738777d3d343477fd1c58db052142cab754ea674378e18766c53542f71970171cc4f81694246b717d7564", "d37ff7ad297993e7ec21e0f1b4b5ae719cdc83c5db687527f27516cbffa822888a6810ee5c1ca7bfe3321119be1ab7bfa0a502671c8329494df7ad6f522d440f", "dd9042f6e464dcf86b1262f6accfafbd8cfd902ed3ed89abf78ffa482dbdeeb6969842394c9a1168ae3d481a017842f660002d42447c6b22f7b72f21aae021c9", "bd965bf31e87d70327536f2a341cebc4768eca275fa05ef98f7f1b71a0351298de006fba73fe6733ed01d75801b4a928e54231b38e38c562b2e33ea1284992fa", "65676d800617972fbd87e4b9514e1c67402b7a331096d3bfac22f1abb95374abc942f16e9ab0ead33b87c91968a6e509e119ff07787b3ef483e1dcdccf6e3022", "939fa189699c5d2c81ddd1ffc1fa207c970b6a3685bb29ce1d3e99d42f2f7442da53e95a72907314f4588399a3ff5b0a92beb3f6be2694f9f86ecf2952d5b41c", "c516541701863f91005f314108ceece3c643e04fc8c42fd2ff556220e616aaa6a48aeb97a84bad74782e8dff96a1a2fa949339d722edcaa32b57067041df88cc", "987fd6e0d6857c553eaebb3d34970a2c2f6e89a3548f492521722b80a1c21a153892346d2cba6444212d56da9a26e324dccbc0dcde85d4d2ee4399eec5a64e8f", "ae56deb1c2328d9c4017706bce6e99d41349053ba9d336d677c4c27d9fd50ae6aee17e853154e1f4fe7672346da2eaa31eea53fcf24a22804f11d03da6abfc2b", "49d6a608c9bde4491870498572ac31aac3fa40938b38a7818f72383eb040ad39532bc06571e13d767e6945ab77c0bdc3b0284253343f9f6c1244ebf2ff0df866", "da582ad8c5370b4469af862aa6467a2293b2b28bd80ae0e91f425ad3d47249fdf98825cc86f14028c3308c9804c78bfeeeee461444ce243687e1a50522456a1d", "d5266aa3331194aef852eed86d7b5b2633a0af1c735906f2e13279f14931a9fc3b0eac5ce9245273bd1aa92905abe16278ef7efd47694789a7283b77da3c70f8", "2962734c28252186a9a1111c732ad4de4506d4b4480916303eb7991d659ccda07a9911914bc75c418ab7a4541757ad054796e26797feaf36e9f6ad43f14b35a4", "e8b79ec5d06e111bdfafd71e9f5760f00ac8ac5d8bf768f9ff6f08b8f026096b1cc3a4c973333019f1e3553e77da3f98cb9f542e0a90e5f8a940cc58e59844b3", "dfb320c44f9d41d1efdcc015f08dd5539e526e39c87d509ae6812a969e5431bf4fa7d91ffd03b981e0d544cf72d7b1c0374f8801482e6dea2ef903877eba675e", "d88675118fdb55a5fb365ac2af1d217bf526ce1ee9c94b2f0090b2c58a06ca58187d7fe57c7bed9d26fca067b4110eefcd9a0a345de872abe20de368001b0745", "b893f2fc41f7b0dd6e2f6aa2e0370c0cff7df09e3acfcc0e920b6e6fad0ef747c40668417d342b80d2351e8c175f20897a062e9765e6c67b539b6ba8b9170545", "6c67ec5697accd235c59b486d7b70baeedcbd4aa64ebd4eef3c7eac189561a726250aec4d48cadcafbbe2ce3c16ce2d691a8cce06e8879556d4483ed7165c063", "f1aa2b044f8f0c638a3f362e677b5d891d6fd2ab0765f6ee1e4987de057ead357883d9b405b9d609eea1b869d97fb16d9b51017c553f3b93c0a1e0f1296fedcd", "cbaa259572d4aebfc1917acddc582b9f8dfaa928a198ca7acd0f2aa76a134a90252e6298a65b08186a350d5b7626699f8cb721a3ea5921b753ae3a2dce24ba3a", "fa1549c9796cd4d303dcf452c1fbd5744fd9b9b47003d920b92de34839d07ef2a29ded68f6fc9e6c45e071a2e48bd50c5084e96b657dd0404045a1ddefe282ed", "5cf2ac897ab444dcb5c8d87c495dbdb34e1838b6b629427caa51702ad0f9688525f13bec503a3c3a2c80a65e0b5715e8afab00ffa56ec455a49a1ad30aa24fcd", "9aaf80207bace17bb7ab145757d5696bde32406ef22b44292ef65d4519c3bb2ad41a59b62cc3e94b6fa96d32a7faadae28af7d35097219aa3fd8cda31e40c275", "af88b163402c86745cb650c2988fb95211b94b03ef290eed9662034241fd51cf398f8073e369354c43eae1052f9b63b08191caa138aa54fea889cc7024236897", "48fa7d64e1ceee27b9864db5ada4b53d00c9bc7626555813d3cd6730ab3cc06ff342d727905e33171bde6e8476e77fb1720861e94b73a2c538d254746285f430", "0e6fd97a85e904f87bfe85bbeb34f69e1f18105cf4ed4f87aec36c6e8b5f68bd2a6f3dc8a9ecb2b61db4eedb6b2ea10bf9cb0251fb0f8b344abf7f366b6de5ab", "06622da5787176287fdc8fed440bad187d830099c94e6d04c8e9c954cda70c8bb9e1fc4a6d0baa831b9b78ef6648681a4867a11da93ee36e5e6a37d87fc63f6f", "1da6772b58fabf9c61f68d412c82f182c0236d7d575ef0b58dd22458d643cd1dfc93b03871c316d8430d312995d4197f0874c99172ba004a01ee295abac24e46", "3cd2d9320b7b1d5fb9aab951a76023fa667be14a9124e394513918a3f44096ae4904ba0ffc150b63bc7ab1eeb9a6e257e5c8f000a70394a5afd842715de15f29", "04cdc14f7434e0b4be70cb41db4c779a88eaef6accebcb41f2d42fffe7f32a8e281b5c103a27021d0d08362250753cdf70292195a53a48728ceb5844c2d98bab", "9071b7a8a075d0095b8fb3ae5113785735ab98e2b52faf91d5b89e44aac5b5d4ebbf91223b0ff4c71905da55342e64655d6ef8c89a4768c3f93a6dc0366b5bc8", "ebb30240dd96c7bc8d0abe49aa4edcbb4afdc51ff9aaf720d3f9e7fbb0f9c6d6571350501769fc4ebd0b2141247ff400d4fd4be414edf37757bb90a32ac5c65a", "8532c58bf3c8015d9d1cbe00eef1f5082f8f3632fbe9f1ed4f9dfb1fa79e8283066d77c44c4af943d76b300364aecbd0648c8a8939bd204123f4b56260422dec", "fe9846d64f7c7708696f840e2d76cb4408b6595c2f81ec6a28a7f2f20cb88cfe6ac0b9e9b8244f08bd7095c350c1d0842f64fb01bb7f532dfcd47371b0aeeb79", "28f17ea6fb6c42092dc264257e29746321fb5bdaea9873c2a7fa9d8f53818e899e161bc77dfe8090afd82bf2266c5c1bc930a8d1547624439e662ef695f26f24", "ec6b7d7f030d4850acae3cb615c21dd25206d63e84d1db8d957370737ba0e98467ea0ce274c66199901eaec18a08525715f53bfdb0aacb613d342ebdceeddc3b", "b403d3691c03b0d3418df327d5860d34bbfcc4519bfbce36bf33b208385fadb9186bc78a76c489d89fd57e7dc75412d23bcd1dae8470ce9274754bb8585b13c5", "31fc79738b8772b3f55cd8178813b3b52d0db5a419d30ba9495c4b9da0219fac6df8e7c23a811551a62b827f256ecdb8124ac8a6792ccfecc3b3012722e94463", "bb2039ec287091bcc9642fc90049e73732e02e577e2862b32216ae9bedcd730c4c284ef3968c368b7d37584f97bd4b4dc6ef6127acfe2e6ae2509124e66c8af4", "f53d68d13f45edfcb9bd415e2831e938350d5380d3432278fc1c0c381fcb7c65c82dafe051d8c8b0d44e0974a0e59ec7bf7ed0459f86e96f329fc79752510fd3", "8d568c7984f0ecdf7640fbc483b5d8c9f86634f6f43291841b309a350ab9c1137d24066b09da9944bac54d5bb6580d836047aac74ab724b887ebf93d4b32eca9", "c0b65ce5a96ff774c456cac3b5f2c4cd359b4ff53ef93a3da0778be4900d1e8da1601e769e8f1b02d2a2f8c5b9fa10b44f1c186985468feeb008730283a6657d", "4900bba6f5fb103ece8ec96ada13a5c3c85488e05551da6b6b33d988e611ec0fe2e3c2aa48ea6ae8986a3a231b223c5d27cec2eadde91ce07981ee652862d1e4", "c7f5c37c7285f927f76443414d4357ff789647d7a005a5a787e03c346b57f49f21b64fa9cf4b7e45573e23049017567121a9c3d4b2b73ec5e9413577525db45a", "ec7096330736fdb2d64b5653e7475da746c23a4613a82687a28062d3236364284ac01720ffb406cfe265c0df626a188c9e5963ace5d3d5bb363e32c38c2190a6", "82e744c75f4649ec52b80771a77d475a3bc091989556960e276a5f9ead92a03f718742cdcfeaee5cb85c44af198adc43a4a428f5f0c2ddb0be36059f06d7df73", "2834b7a7170f1f5b68559ab78c1050ec21c919740b784a9072f6e5d69f828d70c919c5039fb148e39e2c8a52118378b064ca8d5001cd10a5478387b966715ed6", "16b4ada883f72f853bb7ef253efcab0c3e2161687ad61543a0d2824f91c1f81347d86be709b16996e17f2dd486927b0288ad38d13063c4a9672c39397d3789b6", "78d048f3a69d8b54ae0ed63a573ae350d89f7c6cf1f3688930de899afa037697629b314e5cd303aa62feea72a25bf42b304b6c6bcb27fae21c16d925e1fbdac3", "0f746a48749287ada77a82961f05a4da4abdb7d77b1220f836d09ec814359c0ec0239b8c7b9ff9e02f569d1b301ef67c4612d1de4f730f81c12c40cc063c5caa", "f0fc859d3bd195fbdc2d591e4cdac15179ec0f1dc821c11df1f0c1d26e6260aaa65b79fafacafd7d3ad61e600f250905f5878c87452897647a35b995bcadc3a3", "2620f687e8625f6a412460b42e2cef67634208ce10a0cbd4dff7044a41b7880077e9f8dc3b8d1216d3376a21e015b58fb279b521d83f9388c7382c8505590b9b", "227e3aed8d2cb10b918fcb04f9de3e6d0a57e08476d93759cd7b2ed54a1cbf0239c528fb04bbf288253e601d3bc38b21794afef90b17094a182cac557745e75f", "1a929901b09c25f27d6b35be7b2f1c4745131fdebca7f3e2451926720434e0db6e74fd693ad29b777dc3355c592a361c4873b01133a57c2e3b7075cbdb86f4fc", "5fd7968bc2fe34f220b5e3dc5af9571742d73b7d60819f2888b629072b96a9d8ab2d91b82d0a9aaba61bbd39958132fcc4257023d1eca591b3054e2dc81c8200", "dfcce8cf32870cc6a503eadafc87fd6f78918b9b4d0737db6810be996b5497e7e5cc80e312f61e71ff3e9624436073156403f735f56b0b01845c18f6caf772e6", "02f7ef3a9ce0fff960f67032b296efca3061f4934d690749f2d01c35c81c14f39a67fa350bc8a0359bf1724bffc3bca6d7c7bba4791fd522a3ad353c02ec5aa8", "64be5c6aba65d594844ae78bb022e5bebe127fd6b6ffa5a13703855ab63b624dcd1a363f99203f632ec386f3ea767fc992e8ed9686586aa27555a8599d5b808f", "f78585505c4eaa54a8b5be70a61e735e0ff97af944ddb3001e35d86c4e2199d976104b6ae31750a36a726ed285064f5981b503889fef822fcdc2898dddb7889a", "e4b5566033869572edfd87479a5bb73c80e8759b91232879d96b1dda36c012076ee5a2ed7ae2de63ef8406a06aea82c188031b560beafb583fb3de9e57952a7e", "e1b3e7ed867f6c9484a2a97f7715f25e25294e992e41f6a7c161ffc2adc6daaeb7113102d5e6090287fe6ad94ce5d6b739c6ca240b05c76fb73f25dd024bf935", "85fd085fdc12a080983df07bd7012b0d402a0f4043fcb2775adf0bad174f9b08d1676e476985785c0a5dcc41dbff6d95ef4d66a3fbdc4a74b82ba52da0512b74", "aed8fa764b0fbff821e05233d2f7b0900ec44d826f95e93c343c1bc3ba5a24374b1d616e7e7aba453a0ada5e4fab5382409e0d42ce9c2bc7fb39a99c340c20f0", "7ba3b2e297233522eeb343bd3ebcfd835a04007735e87f0ca300cbee6d416565162171581e4020ff4cf176450f1291ea2285cb9ebffe4c56660627685145051c", "de748bcf89ec88084721e16b85f30adb1a6134d664b5843569babc5bbd1a15ca9b61803c901a4fef32965a1749c9f3a4e243e173939dc5a8dc495c671ab52145", "aaf4d2bdf200a919706d9842dce16c98140d34bc433df320aba9bd429e549aa7a3397652a4d768277786cf993cde2338673ed2e6b66c961fefb82cd20c93338f", "c408218968b788bf864f0997e6bc4c3dba68b276e2125a4843296052ff93bf5767b8cdce7131f0876430c1165fec6c4f47adaa4fd8bcfacef463b5d3d0fa61a0", "76d2d819c92bce55fa8e092ab1bf9b9eab237a25267986cacf2b8ee14d214d730dc9a5aa2d7b596e86a1fd8fa0804c77402d2fcd45083688b218b1cdfa0dcbcb", "72065ee4dd91c2d8509fa1fc28a37c7fc9fa7d5b3f8ad3d0d7a25626b57b1b44788d4caf806290425f9890a3a2a35a905ab4b37acfd0da6e4517b2525c9651e4", "64475dfe7600d7171bea0b394e27c9b00d8e74dd1e416a79473682ad3dfdbb706631558055cfc8a40e07bd015a4540dcdea15883cbbf31412df1de1cd4152b91", "12cd1674a4488a5d7c2b3160d2e2c4b58371bedad793418d6f19c6ee385d70b3e06739369d4df910edb0b0a54cbff43d54544cd37ab3a06cfa0a3ddac8b66c89", "60756966479dedc6dd4bcff8ea7d1d4ce4d4af2e7b097e32e3763518441147cc12b3c0ee6d2ecabf1198cec92e86a3616fba4f4e872f5825330adbb4c1dee444", "a7803bcb71bc1d0f4383dde1e0612e04f872b715ad30815c2249cf34abb8b024915cb2fc9f4e7cc4c8cfd45be2d5a91eab0941c7d270e2da4ca4a9f7ac68663a", "b84ef6a7229a34a750d9a98ee2529871816b87fbe3bc45b45fa5ae82d5141540211165c3c5d7a7476ba5a4aa06d66476f0d9dc49a3f1ee72c3acabd498967414", "fae4b6d8efc3f8c8e64d001dabec3a21f544e82714745251b2b4b393f2f43e0da3d403c64db95a2cb6e23ebb7b9e94cdd5ddac54f07c4a61bd3cb10aa6f93b49", "34f7286605a122369540141ded79b8957255da2d4155abbf5a8dbb89c8eb7ede8eeef1daa46dc29d751d045dc3b1d658bb64b80ff8589eddb3824b13da235a6b", "3b3b48434be27b9eababba43bf6b35f14b30f6a88dc2e750c358470d6b3aa3c18e47db4017fa55106d8252f016371a00f5f8b070b74ba5f23cffc5511c9f09f0", "ba289ebd6562c48c3e10a8ad6ce02e73433d1e93d7c9279d4d60a7e879ee11f441a000f48ed9f7c4ed87a45136d7dccdca482109c78a51062b3ba4044ada2469", "022939e2386c5a37049856c850a2bb10a13dfea4212b4c732a8840a9ffa5faf54875c5448816b2785a007da8a8d2bc7d71a54e4e6571f10b600cbdb25d13ede3", "e6fec19d89ce8717b1a087024670fe026f6c7cbda11caef959bb2d351bf856f8055d1c0ebdaaa9d1b17886fc2c562b5e99642fc064710c0d3488a02b5ed7f6fd", "94c96f02a8f576aca32ba61c2b206f907285d9299b83ac175c209a8d43d53bfe683dd1d83e7549cb906c28f59ab7c46f8751366a28c39dd5fe2693c9019666c8", "31a0cd215ebd2cb61de5b9edc91e6195e31c59a5648d5c9f737e125b2605708f2e325ab3381c8dce1a3e958886f1ecdc60318f882cfe20a24191352e617b0f21", "91ab504a522dce78779f4c6c6ba2e6b6db5565c76d3e7e7c920caf7f757ef9db7c8fcf10e57f03379ea9bf75eb59895d96e149800b6aae01db778bb90afbc989", "d85cabc6bd5b1a01a5afd8c6734740da9fd1c1acc6db29bfc8a2e5b668b028b6b3154bfb8703fa3180251d589ad38040ceb707c4bad1b5343cb426b61eaa49c1", "d62efbec2ca9c1f8bd66ce8b3f6a898cb3f7566ba6568c618ad1feb2b65b76c3ce1dd20f7395372faf28427f61c9278049cf0140df434f5633048c86b81e0399", "7c8fdc6175439e2c3db15bafa7fb06143a6a23bc90f449e79deef73c3d492a671715c193b6fea9f036050b946069856b897e08c00768f5ee5ddcf70b7cd6d0e0", "58602ee7468e6bc9df21bd51b23c005f72d6cb013f0a1b48cbec5eca299299f97f09f54a9a01483eaeb315a6478bad37ba47ca1347c7c8fc9e6695592c91d723", "27f5b79ed256b050993d793496edf4807c1d85a7b0a67c9c4fa99860750b0ae66989670a8ffd7856d7ce411599e58c4d77b232a62bef64d15275be46a68235ff", "3957a976b9f1887bf004a8dca942c92d2b37ea52600f25e0c9bc5707d0279c00c6e85a839b0d2d8eb59c51d94788ebe62474a791cadf52cccf20f5070b6573fc", "eaa2376d55380bf772ecca9cb0aa4668c95c707162fa86d518c8ce0ca9bf7362b9f2a0adc3ff59922df921b94567e81e452f6c1a07fc817cebe99604b3505d38", "c1e2c78b6b2734e2480ec550434cb5d613111adcc21d475545c3b1b7e6ff12444476e5c055132e2229dc0f807044bb919b1a5662dd38a9ee65e243a3911aed1a", "8ab48713389dd0fcf9f965d3ce66b1e559a1f8c58741d67683cd971354f452e62d0207a65e436c5d5d8f8ee71c6abfe50e669004c302b31a7ea8311d4a916051", "24ce0addaa4c65038bd1b1c0f1452a0b128777aabc94a29df2fd6c7e2f85f8ab9ac7eff516b0e0a825c84a24cfe492eaad0a6308e46dd42fe8333ab971bb30ca", "5154f929ee03045b6b0c0004fa778edee1d139893267cc84825ad7b36c63de32798e4a166d24686561354f63b00709a1364b3c241de3febf0754045897467cd4", "e74e907920fd87bd5ad636dd11085e50ee70459c443e1ce5809af2bc2eba39f9e6d7128e0e3712c316da06f4705d78a4838e28121d4344a2c79c5e0db307a677", "bf91a22334bac20f3fd80663b3cd06c4e8802f30e6b59f90d3035cc9798a217ed5a31abbda7fa6842827bdf2a7a1c21f6fcfccbb54c6c52926f32da816269be1", "d9d5c74be5121b0bd742f26bffb8c89f89171f3f934913492b0903c271bbe2b3395ef259669bef43b57f7fcc3027db01823f6baee66e4f9fead4d6726c741fce", "50c8b8cf34cd879f80e2faab3230b0c0e1cc3e9dcadeb1b9d97ab923415dd9a1fe38addd5c11756c67990b256e95ad6d8f9fedce10bf1c90679cde0ecf1be347", "0a386e7cd5dd9b77a035e09fe6fee2c8ce61b5383c87ea43205059c5e4cd4f4408319bb0a82360f6a58e6c9ce3f487c446063bf813bc6ba535e17fc1826cfc91", "1f1459cb6b61cbac5f0efe8fc487538f42548987fcd56221cfa7beb22504769e792c45adfb1d6b3d60d7b749c8a75b0bdf14e8ea721b95dca538ca6e25711209", "e58b3836b7d8fedbb50ca5725c6571e74c0785e97821dab8b6298c10e4c079d4a6cdf22f0fedb55032925c16748115f01a105e77e00cee3d07924dc0d8f90659", "b929cc6505f020158672deda56d0db081a2ee34c00c1100029bdf8ea98034fa4bf3e8655ec697fe36f40553c5bb46801644a627d3342f4fc92b61f03290fb381", "72d353994b49d3e03153929a1e4d4f188ee58ab9e72ee8e512f29bc773913819ce057ddd7002c0433ee0a16114e3d156dd2c4a7e80ee53378b8670f23e33ef56", "c70ef9bfd775d408176737a0736d68517ce1aaad7e81a93c8c1ed967ea214f56c8a377b1763e676615b60f3988241eae6eab9685a5124929d28188f29eab06f7", "c230f0802679cb33822ef8b3b21bf7a9a28942092901d7dac3760300831026cf354c9232df3e084d9903130c601f63c1f4a4a4b8106e468cd443bbe5a734f45f", "6f43094cafb5ebf1f7a4937ec50f56a4c9da303cbb55ac1f27f1f1976cd96beda9464f0e7b9c54620b8a9fba983164b8be3578425a024f5fe199c36356b88972", "3745273f4c38225db2337381871a0c6aafd3af9b018c88aa02025850a5dc3a42a1a3e03e56cbf1b0876d63a441f1d2856a39b8801eb5af325201c415d65e97fe", "c50c44cca3ec3edaae779a7e179450ebdda2f97067c690aa6c5a4ac7c30139bb27c0df4db3220e63cb110d64f37ffe078db72653e2daacf93ae3f0a2d1a7eb2e", "8aef263e385cbc61e19b28914243262af5afe8726af3ce39a79c27028cf3ecd3f8d2dfd9cfc9ad91b58f6f20778fd5f02894a3d91c7d57d1e4b866a7f364b6be", "28696141de6e2d9bcb3235578a66166c1448d3e905a1b482d423be4bc5369bc8c74dae0acc9cc123e1d8ddce9f97917e8c019c552da32d39d2219b9abf0fa8c8", "2fb9eb2085830181903a9dafe3db428ee15be7662224efd643371fb25646aee716e531eca69b2bdc8233f1a8081fa43da1500302975a77f42fa592136710e9dc", "66f9a7143f7a3314a669bf2e24bbb35014261d639f495b6c9c1f104fe8e320aca60d4550d69d52edbd5a3cdeb4014ae65b1d87aa770b69ae5c15f4330b0b0ad8", "f4c4dd1d594c3565e3e25ca43dad82f62abea4835ed4cd811bcd975e46279828d44d4c62c3679f1b7f7b9dd4571d7b49557347b8c5460cbdc1bef690fb2a08c0", "8f1dc9649c3a84551f8f6e91cac68242a43b1f8f328ee92280257387fa7559aa6db12e4aeadc2d26099178749c6864b357f3f83b2fb3efa8d2a8db056bed6bcc", "3139c1a7f97afd1675d460ebbc07f2728aa150df849624511ee04b743ba0a833092f18c12dc91b4dd243f333402f59fe28abdbbbae301e7b659c7a26d5c0f979", "06f94a2996158a819fe34c40de3cf0379fd9fb85b3e363ba3926a0e7d960e3f4c2e0c70c7ce0ccb2a64fc29869f6e7ab12bd4d3f14fce943279027e785fb5c29", "c29c399ef3eee8961e87565c1ce263925fc3d0ce267d13e48dd9e732ee67b0f69fad56401b0f10fcaac119201046cca28c5b14abdea3212ae65562f7f138db3d", "4cec4c9df52eef05c3f6faaa9791bc7445937183224ecc37a1e58d0132d35617531d7e795f52af7b1eb9d147de1292d345fe341823f8e6bc1e5badca5c656108", "898bfbae93b3e18d00697eab7d9704fa36ec339d076131cefdf30edbe8d9cc81c3a80b129659b163a323bab9793d4feed92d54dae966c77529764a09be88db45", "ee9bd0469d3aaf4f14035be48a2c3b84d9b4b1fff1d945e1f1c1d38980a951be197b25fe22c731f20aeacc930ba9c4a1f4762227617ad350fdabb4e80273a0f4", "3d4d3113300581cd96acbf091c3d0f3c310138cd6979e6026cde623e2dd1b24d4a8638bed1073344783ad0649cc6305ccec04beb49f31c633088a99b65130267", "95c0591ad91f921ac7be6d9ce37e0663ed8011c1cfd6d0162a5572e94368bac02024485e6a39854aa46fe38e97d6c6b1947cd272d86b06bb5b2f78b9b68d559d", "227b79ded368153bf46c0a3ca978bfdbef31f3024a5665842468490b0ff748ae04e7832ed4c9f49de9b1706709d623e5c8c15e3caecae8d5e433430ff72f20eb", "5d34f3952f0105eef88ae8b64c6ce95ebfade0e02c69b08762a8712d2e4911ad3f941fc4034dc9b2e479fdbcd279b902faf5d838bb2e0c6495d372b5b7029813", "7f939bf8353abce49e77f14f3750af20b7b03902e1a1e7fb6aaf76d0259cd401a83190f15640e74f3e6c5a90e839c7821f6474757f75c7bf9002084ddc7a62dc", "062b61a2f9a33a71d7d0a06119644c70b0716a504de7e5e1be49bd7b86e7ed6817714f9f0fc313d06129597e9a2235ec8521de36f7290a90ccfc1ffa6d0aee29", "f29e01eeae64311eb7f1c6422f946bf7bea36379523e7b2bbaba7d1d34a22d5ea5f1c5a09d5ce1fe682cced9a4798d1a05b46cd72dff5c1b355440b2a2d476bc", "ec38cd3bbab3ef35d7cb6d5c914298351d8a9dc97fcee051a8a02f58e3ed6184d0b7810a5615411ab1b95209c3c810114fdeb22452084e77f3f847c6dbaafe16", "c2aef5e0ca43e82641565b8cb943aa8ba53550caef793b6532fafad94b816082f0113a3ea2f63608ab40437ecc0f0229cb8fa224dcf1c478a67d9b64162b92d1", "15f534efff7105cd1c254d074e27d5898b89313b7d366dc2d7d87113fa7d53aae13f6dba487ad8103d5e854c91fdb6e1e74b2ef6d1431769c30767dde067a35c", "89acbca0b169897a0a2714c2df8c95b5b79cb69390142b7d6018bb3e3076b099b79a964152a9d912b1b86412b7e372e9cecad7f25d4cbab8a317be36492a67d7", "e3c0739190ed849c9c962fd9dbb55e207e624fcac1eb417691515499eea8d8267b7e8f1287a63633af5011fde8c4ddf55bfdf722edf88831414f2cfaed59cb9a", "8d6cf87c08380d2d1506eee46fd4222d21d8c04e585fbfd08269c98f702833a156326a0724656400ee09351d57b440175e2a5de93cc5f80db6daf83576cf75fa", "da24bede383666d563eeed37f6319baf20d5c75d1635a6ba5ef4cfa1ac95487e96f8c08af600aab87c986ebad49fc70a58b4890b9c876e091016daf49e1d322e", "f9d1d1b1e87ea7ae753a029750cc1cf3d0157d41805e245c5617bb934e732f0ae3180b78e05bfe76c7c3051e3e3ac78b9b50c05142657e1e03215d6ec7bfd0fc", "11b7bc1668032048aa43343de476395e814bbbc223678db951a1b03a021efac948cfbe215f97fe9a72a2f6bc039e3956bfa417c1a9f10d6d7ba5d3d32ff323e5", "b8d9000e4fc2b066edb91afee8e7eb0f24e3a201db8b6793c0608581e628ed0bcc4e5aa6787992a4bcc44e288093e63ee83abd0bc3ec6d0934a674a4da13838a", "ce325e294f9b6719d6b61278276ae06a2564c03bb0b783fafe785bdf89c7d5acd83e78756d301b445699024eaeb77b54d477336ec2a4f332f2b3f88765ddb0c3", "29acc30e9603ae2fccf90bf97e6cc463ebe28c1b2f9b4b765e70537c25c702a29dcbfbf14c99c54345ba2b51f17b77b5f15db92bbad8fa95c471f5d070a137cc", "3379cbaae562a87b4c0425550ffdd6bfe1203f0d666cc7ea095be407a5dfe61ee91441cd5154b3e53b4f5fb31ad4c7a9ad5c7af4ae679aa51a54003a54ca6b2d", "3095a349d245708c7cf550118703d7302c27b60af5d4e67fc978f8a4e60953c7a04f92fcf41aee64321ccb707a895851552b1e37b00bc5e6b72fa5bcef9e3fff", "07262d738b09321f4dbccec4bb26f48cb0f0ed246ce0b31b9a6e7bc683049f1f3e5545f28ce932dd985c5ab0f43bd6de0770560af329065ed2e49d34624c2cbb", "b6405eca8ee3316c87061cc6ec18dba53e6c250c63ba1f3bae9e55dd3498036af08cd272aa24d713c6020d77ab2f3919af1a32f307420618ab97e73953994fb4", "7ee682f63148ee45f6e5315da81e5c6e557c2c34641fc509c7a5701088c38a74756168e2cd8d351e88fd1a451f360a01f5b2580f9b5a2e8cfc138f3dd59a3ffc", "1d263c179d6b268f6fa016f3a4f29e943891125ed8593c81256059f5a7b44af2dcb2030d175c00e62ecaf7ee96682aa07ab20a611024a28532b1c25b86657902", "106d132cbdb4cd2597812846e2bc1bf732fec5f0a5f65dbb39ec4e6dc64ab2ce6d24630d0f15a805c3540025d84afa98e36703c3dbee713e72dde8465bc1be7e", "0e79968226650667a8d862ea8da4891af56a4e3a8b6d1750e394f0dea76d640d85077bcec2cc86886e506751b4f6a5838f7f0b5fef765d9dc90dcdcbaf079f08", "521156a82ab0c4e566e5844d5e31ad9aaf144bbd5a464fdca34dbd5717e8ff711d3ffebbfa085d67fe996a34f6d3e4e60b1396bf4b1610c263bdbb834d560816", "1aba88befc55bc25efbce02db8b9933e46f57661baeabeb21cc2574d2a518a3cba5dc5a38e49713440b25f9c744e75f6b85c9d8f4681f676160f6105357b8406", "5a9949fcb2c473cda968ac1b5d08566dc2d816d960f57e63b898fa701cf8ebd3f59b124d95bfbbedc5f1cf0e17d5eaed0c02c50b69d8a402cabcca4433b51fd4", "b0cead09807c672af2eb2b0f06dde46cf5370e15a4096b1a7d7cbb36ec31c205fbefca00b7a4162fa89fb4fb3eb78d79770c23f44e7206664ce3cd931c291e5d", "bb6664931ec97044e45b2ae420ae1c551a8874bc937d08e969399c3964ebdba8346cdd5d09caafe4c28ba7ec788191ceca65ddd6f95f18583e040d0f30d0364d", "65bc770a5faa3792369803683e844b0be7ee96f29f6d6a35568006bd5590f9a4ef639b7a8061c7b0424b66b60ac34af3119905f33a9d8c3ae18382ca9b689900", "ea9b4dca333336aaf839a45c6eaa48b8cb4c7ddabffea4f643d6357ea6628a480a5b45f2b052c1b07d1fedca918b6f1139d80f74c24510dcbaa4be70eacc1b06", "e6342fb4a780ad975d0e24bce149989b91d360557e87994f6b457b895575cc02d0c15bad3ce7577f4c63927ff13f3e381ff7e72bdbe745324844a9d27e3f1c01", "3e209c9b33e8e461178ab46b1c64b49a07fb745f1c8bc95fbfb94c6b87c69516651b264ef980937fad41238b91ddc011a5dd777c7efd4494b4b6ecd3a9c22ac0", "fd6a3d5b1875d80486d6e69694a56dbb04a99a4d051f15db2689776ba1c4882e6d462a603b7015dc9f4b7450f05394303b8652cfb404a266962c41bae6e18a94", "951e27517e6bad9e4195fc8671dee3e7e9be69cee1422cb9fecfce0dba875f7b310b93ee3a3d558f941f635f668ff832d2c1d033c5e2f0997e4c66f147344e02", "8eba2f874f1ae84041903c7c4253c82292530fc8509550bfdc34c95c7e2889d5650b0ad8cb988e5c4894cb87fbfbb19612ea93ccc4c5cad17158b9763464b492", "16f712eaa1b7c6354719a8e7dbdfaf55e4063a4d277d947550019b38dfb564830911057d50506136e2394c3b28945cc964967d54e3000c2181626cfb9b73efd2", "c39639e7d5c7fb8cdd0fd3e6a52096039437122f21c78f1679cea9d78a734c56ecbeb28654b4f18e342c331f6f7229ec4b4bc281b2d80a6eb50043f31796c88c", "72d081af99f8a173dcc9a0ac4eb3557405639a29084b54a40172912a2f8a395129d5536f0918e902f9e8fa6000995f4168ddc5f893011be6a0dbc9b8a1a3f5bb", "c11aa81e5efd24d5fc27ee586cfd8847fbb0e27601ccece5ecca0198e3c7765393bb74457c7e7a27eb9170350e1fb53857177506be3e762cc0f14d8c3afe9077", "c28f2150b452e6c0c424bcde6f8d72007f9310fed7f2f87de0dbb64f4479d6c1441ba66f44b2accee61609177ed340128b407ecec7c64bbe50d63d22d8627727", "f63d88122877ec30b8c8b00d22e89000a966426112bd44166e2f525b769ccbe9b286d437a0129130dde1a86c43e04bedb594e671d98283afe64ce331de9828fd", "348b0532880b88a6614a8d7408c3f913357fbb60e995c60205be9139e74998aede7f4581e42f6b52698f7fa1219708c14498067fd1e09502de83a77dd281150c", "5133dc8bef725359dff59792d85eaf75b7e1dcd1978b01c35b1b85fcebc63388ad99a17b6346a217dc1a9622ebd122ecf6913c4d31a6b52a695b86af00d741a0", "2753c4c0e98ecad806e88780ec27fccd0f5c1ab547f9e4bf1659d192c23aa2cc971b58b6802580baef8adc3b776ef7086b2545c2987f348ee3719cdef258c403", "b1663573ce4b9d8caefc865012f3e39714b9898a5da6ce17c25a6a47931a9ddb9bbe98adaa553beed436e89578455416c2a52a525cf2862b8d1d49a2531b7391", "64f58bd6bfc856f5e873b2a2956ea0eda0d6db0da39c8c7fc67c9f9feefcff3072cdf9e6ea37f69a44f0c61aa0da3693c2db5b54960c0281a088151db42b11e8", "0764c7be28125d9065c4b98a69d60aede703547c66a12e17e1c618994132f5ef82482c1e3fe3146cc65376cc109f0138ed9a80e49f1f3c7d610d2f2432f20605", "f748784398a2ff03ebeb07e155e66116a839741a336e32da71ec696001f0ad1b25cd48c69cfca7265eca1dd71904a0ce748ac4124f3571076dfa7116a9cf00e9", "3f0dbc0186bceb6b785ba78d2a2a013c910be157bdaffae81bb6663b1a73722f7f1228795f3ecada87cf6ef0078474af73f31eca0cc200ed975b6893f761cb6d", "d4762cd4599876ca75b2b8fe249944dbd27ace741fdab93616cbc6e425460feb51d4e7adcc38180e7fc47c89024a7f56191adb878dfde4ead62223f5a2610efe", "cd36b3d5b4c91b90fcbba79513cfee1907d8645a162afd0cd4cf4192d4a5f4c892183a8eacdb2b6b6a9d9aa8c11ac1b261b380dbee24ca468f1bfd043c58eefe", "98593452281661a53c48a9d8cd790826c1a1ce567738053d0bee4a91a3d5bd92eefdbabebe3204f2031ca5f781bda99ef5d8ae56e5b04a9e1ecd21b0eb05d3e1", "771f57dd2775ccdab55921d3e8e30ccf484d61fe1c1b9c2ae819d0fb2a12fab9be70c4a7a138da84e8280435daade5bbe66af0836a154f817fb17f3397e725a3", "c60897c6f828e21f16fbb5f15b323f87b6c8955eabf1d38061f707f608abdd993fac3070633e286cf8339ce295dd352df4b4b40b2f29da1dd50b3a05d079e6bb", "8210cd2c2d3b135c2cf07fa0d1433cd771f325d075c6469d9c7f1ba0943cd4ab09808cabf4acb9ce5bb88b498929b4b847f681ad2c490d042db2aec94214b06b", "1d4edfffd8fd80f7e4107840fa3aa31e32598491e4af7013c197a65b7f36dd3ac4b478456111cd4309d9243510782fa31b7c4c95fa951520d020eb7e5c36e4ef", "af8e6e91fab46ce4873e1a50a8ef448cc29121f7f74deef34a71ef89cc00d9274bc6c2454bbb3230d8b2ec94c62b1dec85f3593bfa30ea6f7a44d7c09465a253", "29fd384ed4906f2d13aa9fe7af905990938bed807f1832454a372ab412eea1f5625a1fcc9ac8343b7c67c5aba6e0b1cc4644654913692c6b39eb9187ceacd3ec", "a268c7885d9874a51c44dffed8ea53e94f78456e0b2ed99ff5a3924760813826d960a15edbedbb5de5226ba4b074e71b05c55b9756bb79e55c02754c2c7b6c8a", "0cf8545488d56a86817cd7ecb10f7116b7ea530a45b6ea497b6c72c997e09e3d0da8698f46bb006fc977c2cd3d1177463ac9057fdd1662c85d0c126443c10473", "b39614268fdd8781515e2cfebf89b4d5402bab10c226e6344e6b9ae000fb0d6c79cb2f3ec80e80eaeb1980d2f8698916bd2e9f747236655116649cd3ca23a837", "74bef092fc6f1e5dba3663a3fb003b2a5ba257496536d99f62b9d73f8f9eb3ce9ff3eec709eb883655ec9eb896b9128f2afc89cf7d1ab58a72f4a3bf034d2b4a", "3a988d38d75611f3ef38b8774980b33e573b6c57bee0469ba5eed9b44f29945e7347967fba2c162e1c3be7f310f2f75ee2381e7bfd6b3f0baea8d95dfb1dafb1", "58aedfce6f67ddc85a28c992f1c0bd0969f041e66f1ee88020a125cbfcfebcd61709c9c4eba192c15e69f020d462486019fa8dea0cd7a42921a19d2fe546d43d", "9347bd291473e6b4e368437b8e561e065f649a6d8ada479ad09b1999a8f26b91cf6120fd3bfe014e83f23acfa4c0ad7b3712b2c3c0733270663112ccd9285cd9", "b32163e7c5dbb5f51fdc11d2eac875efbbcb7e7699090a7e7ff8a8d50795af5d74d9ff98543ef8cdf89ac13d0485278756e0ef00c817745661e1d59fe38e7537", "1085d78307b1c4b008c57a2e7e5b234658a0a82e4ff1e4aaac72b312fda0fe27d233bc5b10e9cc17fdc7697b540c7d95eb215a19a1a0e20e1abfa126efd568c7", "4e5c734c7dde011d83eac2b7347b373594f92d7091b9ca34cb9c6f39bdf5a8d2f134379e16d822f6522170ccf2ddd55c84b9e6c64fc927ac4cf8dfb2a17701f2", "695d83bd990a1117b3d0ce06cc888027d12a054c2677fd82f0d4fbfc93575523e7991a5e35a3752e9b70ce62992e268a877744cdd435f5f130869c9a2074b338", "a6213743568e3b3158b9184301f3690847554c68457cb40fc9a4b8cfd8d4a118c301a07737aeda0f929c68913c5f51c80394f53bff1c3e83b2e40ca97eba9e15", "d444bfa2362a96df213d070e33fa841f51334e4e76866b8139e8af3bb3398be2dfaddcbc56b9146de9f68118dc5829e74b0c28d7711907b121f9161cb92b69a9", "142709d62e28fcccd0af97fad0f8465b971e82201dc51070faa0372aa43e92484be1c1e73ba10906d5d1853db6a4106e0a7bf9800d373d6dee2d46d62ef2a461", } var hashes2X = []string{ "64", "f457", "e8c045", "a74c6d0d", "eb02ae482a", "be65b981275e", "8540ccd083a455", "074a02fa58d7c7c0", "da6da05e10db3022b6", "542a5aae2f28f2c3b68c", "ca3af2afc4afe891da78b1", "e0f66b8dcebf4edc85f12c85", "744224d383733b3fa2c53bfcf5", "b09b653e85b72ef5cdf8fcfa95f3", "dd51877f31f1cf7b9f68bbb09064a3", "f5ebf68e7ebed6ad445ffc0c47e82650", "ebdcfe03bcb7e21a9091202c5938c0a1bb", "860fa5a72ff92efafc48a89df1632a4e2809", "0d6d49daa26ae2818041108df3ce0a4db48c8d", "e5d7e1bc5715f5ae991e4043e39533af5d53e47f", "5232028a43b9d4dfa7f37439b49495926481ab8a29", "c118803c922f9ae2397fb676a2ab7603dd9c29c21fe4", "2af924f48b9bd7076bfd68794bba6402e2a7ae048de3ea", "61255ac38231087c79ea1a0fa14538c26be1c851b6f318c0", "f9712b8e42f0532162822f142cb946c40369f2f0e77b6b186e", "76da0b89558df66f9b1e66a61d1e795b178ce77a359087793ff2", "9036fd1eb32061bdecebc4a32aa524b343b8098a16768ee774d93c", "f4ce5a05934e125d159678bea521f585574bcf9572629f155f63efcc", "5e1c0d9fae56393445d3024d6b82692d1339f7b5936f68b062c691d3bf", "538e35f3e11111d7c4bab69f83b30ade4f67addf1f45cdd2ac74bf299509", "17572c4dcbb17faf8785f3bba9f6903895394352eae79b01ebd758377694cc", "29f6bb55de7f8868e053176c878c9fe6c2055c4c5413b51ab0386c277fdbac75", "bad026c8b2bd3d294907f2280a7145253ec2117d76e3800357be6d431b16366e41", "386b7cb6e0fd4b27783125cbe80065af8eb9981fafc3ed18d8120863d972fa7427d9", "06e8e6e26e756fff0b83b226dce974c21f970e44fb5b3e5bbada6e4b12f81cca666f48", "2f9bd300244f5bc093ba6dcdb4a89fa29da22b1de9d2c9762af919b5fedf6998fbda305b", "cf6bdcc46d788074511f9e8f0a4b86704365b2d3f98340b8db53920c385b959a38c8869ae7", "1171e603e5cdeb4cda8fd7890222dd8390ede87b6f3284cac0f0d832d8250c9200715af7913d", "bda7b2ad5d02bd35ffb009bdd72b7d7bc9c28b3a32f32b0ba31d6cbd3ee87c60b7b98c03404621", "2001455324e748503aa08eff2fb2e52ae0170e81a6e9368ada054a36ca340fb779393fb045ac72b3", "45f0761aefafbf87a68f9f1f801148d9bba52616ad5ee8e8ac9207e9846a782f487d5cca8b20355a18", "3a7e05708be62f087f17b41ac9f20e4ef8115c5ab6d08e84d46af8c273fb46d3ce1aabebae5eea14e018", "ea318da9d042ca337ccdfb2bee3e96ecb8f907876c8d143e8e44569178353c2e593e4a82c265931ba1dd79", "e0f7c08f5bd712f87094b04528fadb283d83c9ceb82a3e39ec31c19a42a1a1c3bee5613b5640abe069b0d690", "d35e63fb1f3f52ab8f7c6cd7c8247e9799042e53922fbaea808ab979fa0c096588cfea3009181d2f93002dfc11", "b8b0ab69e3ae55a8699eb481dd665b6a2424c89bc6b7cca02d15fdf1b9854139cab49d34de498b50b2c7e8b910cf", "fb65e3222a2950eae1701d4cdd4736266f65bf2c0d2e77968996eadb60ef74fb786f6234973a2524bdfe32d100aa0e", "f28b4bb3a2e2c4d5c01a23ff134558559a2d3d704b75402983ee4e0f71d273ae056842c4153b18ee5c47e2bfa54313d4", "7bb78794e58a53c3e4b1aeb161e756af051583d14e0a5a3205e094b7c9a8cf62d098fa9ea1db12f330a51ab9852c17f983", "a879a8ebae4d0987789bcc58ec3448e35ba1fa1ee58c668d8295aba4eaeaf2762b053a677e25404f635a53037996974d418a", "695865b353ec701ecc1cb38f3154489eed0d39829fc192bb68db286d20fa0a64235cde5639137819f7e99f86bd89afcef84a0f", "a6ec25f369f71176952fb9b33305dc768589a6070463ee4c35996e1ced4964a865a5c3dc8f0d809eab71366450de702318e4834d", "604749f7bfadb069a036409ffac5ba291fa05be8cba2f141554132f56d9bcb88d1ce12f2004cd3ade1aa66a26e6ef64e327514096d", "daf9fa7dc2464a899533594e7916fc9bc585bd29dd60c930f3bfa78bc47f6c8439448043a45119fc9228c15bce5fd24f46baf9de736b", "943ea5647a8666763084da6a6f15dcf0e8dc24f27fd0d9194805d25180fe3a6d98f4b2b5e0d6a04e9b41869817030f16ae975dd41fc35c", "af4f73cbfc093760dfeb52d57ef45207bbd1a515f5523404e5d95a73c237d97ae65bd195b472de6d514c2c448b12fafc282166da132258e9", "605f4ed72ed7f5046a342fe4cf6808100d4632e610d59f7ebb016e367d0ff0a95cf45b02c727ba71f147e95212f52046804d376c918cadd260", "3750d8ab0a6b13f78e51d321dfd1aa801680e958de45b7b977d05732ee39f856b27cb2bcce8fbf3db6666d35e21244c2881fdcc27fbfea6b1672", "8f1b929e80ab752b58abe9731b7b34eb61369536995abef1c0980d93903c1880da3637d367456895f0cb4769d6de3a979e38ed6f5f6ac4d48e9b32", "d8469b7aa538b36cdc711a591d60dafecca22bd421973a70e2deef72f69d8014a6f0064eabfbebf5383cbb90f452c6e113d2110e4b1092c54a38b857", "7d1f1ad2029f4880e1898af8289c23bc933a40863cc4ab697fead79c58b6b8e25b68cf5324579b0fe879fe7a12e6d03907f0140dfe7b29d33d6109ecf1", "87a77aca6d551642288a0dff66078225ae39d288801607429d6725ca949eed7a6f199dd8a65523b4ee7cfa4187400e96597bfffc3e38ade0ae0ab88536a9", "e101f43179d8e8546e5ce6a96d7556b7e6b9d4a7d00e7aade5579d085d527ce34a9329551ebcaf6ba946949bbe38e30a62ae344c1950b4bde55306b3bac432", "4324561d76c370ef35ac36a4adf8f3773a50d86504bd284f71f7ce9e2bc4c1f1d34a7fb2d67561d101955d448b67577eb30dfee96a95c7f921ef53e20be8bc44", "78f0ed6e220b3da3cc9381563b2f72c8dc830cb0f39a48c6ae479a6a78dcfa94002631dec467e9e9b47cc8f0887eb680e340aec3ec009d4a33d241533c76c8ca8c", "9f6589c31a472e0a736f4eb22b6c70a9d332cc15304ccb66a6b97cd051b6ed82f8990e1d9bee2e4bb1c3c45e550ae0e7b96e93ae23f2fb8f63b309131e72b36cba6a", "c138077ee4ed3d7ffa85ba851dfdf6e9843fc1dc00889d117237bfaad9aa757192f73556b959f98e6d24886ce48869f2a01a48c371785f12b6484eb2078f08c22066e1", "f83e7c9e0954a500576ea1fc90a3db2cbd7994eaef647dab5b34e88ab9dc0b47addbc807b21c8e6dd3d0bd357f008471d4f3e0abb18450e1d4919e03a34545b9643f870e", "3277a11f2628544fc66f50428f1ad56bcba6ee36ba2ca6ecdf7e255effc0c30235c039d13e01f04cf1efe95b5c2033ab72adda30994b62f2851d17c9920eadca9a251752dc", "c2a834281a06fe7b730d3a03f90761daf02714c066e33fc07e1f59ac801ec2f4433486b5a2da8faa51a0cf3c34e29b2960cd0013378938dbd47c3a3d12d70db01d7d06c3e91e", "47680182924a51cabe142a6175c9253e8ba7ea579ece8d9bcb78b1e9ca00db844fa08abcf41702bd758ee2c608d9612fed50e85854469cb4ef3038acf1e35b6ba4390561d8ae82", "cec45830cd71869e83b109a99a3cd7d935f83a95de7c582f3adbd34e4938fa2f3f922f52f14f169c38cc6618d3f306a8a4d607b345b8a9c48017136fbf825aecf7b620e85f837fae", "46fb53c70ab105079d5d78dc60eaa30d938f26e4d0b9df122e21ec85deda94744c1daf8038b8a6652d1ff3e7e15376f5abd30e564784a999f665078340d66b0e939e0c2ef03f9c08bb", "7b0dcb52791a170cc52f2e8b95d8956f325c3751d3ef3b2b83b41d82d4496b46228a750d02b71a96012e56b0720949ca77dc68be9b1ef1ad6d6a5ceb86bf565cb972279039e209dddcdc", "7153fd43e6b05f5e1a4401e0fef954a737ed142ec2f60bc4daeef9ce73ea1b40a0fcaf1a1e03a3513f930dd5335723632f59f7297fe3a98b68e125eadf478eb045ed9fc4ee566d13f537f5", "c7f569c79c801dab50e9d9ca6542f25774b3841e49c83efe0b89109f569509ce7887bc0d2b57b50320eb81fab9017f16c4c870e59edb6c26620d93748500231d70a36f48a7c60747ca2d5986", "0a81e0c547648595adca65623ce783411aac7f7d30c3ad269efafab288e7186f6895261972f5137877669c550f34f5128850ebb50e1884814ea1055ee29a866afd04b2087abed02d9592573428", "6a7b6769e1f1c95314b0c7fe77013567891bd23416374f23e4f43e27bc4c55cfada13b53b1581948e07fb96a50676baa2756db0988077b0f27d36ac088e0ff0fe72eda1e8eb4b8facff3218d9af0", "a399474595cb1ccab6107f18e80f03b1707745c7bf769fc9f260094dc9f8bc6fe09271cb0b131ebb2acd073de4a6521c8368e664278be86be216d1622393f23435fae4fbc6a2e7c961282a777c2d75", "4f0fc590b2755a515ae6b46e9628092369d9c8e589e3239320639aa8f7aa44f8111c7c4b3fdbe6e55e036fbf5ebc9c0aa87a4e66851c11e86f6cbf0bd9eb1c98a378c7a7d3af900f55ee108b59bc9e5c", "ed96a046f08dd675107331d267379c6fce3c352a9f8d7b243008a74cb4e9410836afaabe871dab6038ca94ce5f6d41fa922ce08aba58169f94cfc86d9f688f396abd24c11a6a9b0830572105a477c33e92", "379955f539abf0eb2972ee99ed9546c4bbee363403991833005dc27904c271ef22a799bc32cb39f08d2e4ba6717d55153feb692d7c5efae70890bf29d96df02333c7b05ccc314e4835b018fec9141a82c745", "e16cc8d41b96547ede0d0cf4d908c5fa393399daa4a9696e76a4c1f6a2a9fef70f17fb53551a8145ed88f18db8fe780a079d94732437023f7c1d1849ef69ad536a76204239e8ba5d97e507c36c7d042f87fe0e", "a81de50750ece3f84536728f227208bf01ec5b7721579d007de72c88ee20663318332efe5bc7c09ad1fa8342be51f0609046ccf760a7957a7d8dc88941adb93666a4521ebe76618e5ddc2dd3261493d400b50073", "b72c5fb7c7f60d243928fa41a2d711157b96aef290185c64b4de3dcfa3d644da67a8f37c2ac55caad79ec695a473e8b481f658c497edb8a191526592b11a412282d2a4010c90ef4647bd6ce745ebc9244a71d4876b", "9550703877079c90e200e830f277b605624954c549e729c359ee01ee2b07741ecc4255cb37f96682dafcdbaade1063e2c5ccbd1918fb669926a67744101fb6de3ac016be4c74165a1e5a696b704ba2ebf4a953d44b95", "a17eb44d4de502dc04a80d5a5e9507d17f27c96467f24c79b06bc98a4c410741d4ac2db98ec02c2a976d788531f1a4451b6c6204cef6dae1b6ebbcd0bde23e6fffb02754043c8fd3c783d90a670b16879ce68b5554fe1c", "41d3ea1eaba5be4a206732dbb5b70b79b66a6e5908795ad4fb7cf9e67efb13f06fef8f90acb080ce082aadec6a1b543af759ab63fa6f1d3941186482b0c2b312f1151ea8386253a13ed3708093279b8eb04185636488b226", "5e7cdd8373dc42a243c96013cd29df9283b5f28bb50453a903c85e2ce57f35861bf93f03029072b70dac0804e7d51fd0c578c8d9fa619f1e9ce3d8044f65d55634dba611280c1d5cfb59c836a595c803124f696b07ddfac718", "26a14c4aa168907cb5de0d12a82e1373a128fb21f2ed11feba108b1bebce934ad63ed89f4ed7ea5e0bc8846e4fc10142f82de0bebd39d68f7874f615c3a9c896bab34190e85df05aaa316e14820b5e478d838fa89dfc94a7fc1e", "0211dfc3c35881adc170e4ba6daab1b702dff88933db9a6829a76b8f4a7c2a6d658117132a974f0a0b3a38ceea1efc2488da21905345909e1d859921dc2b5054f09bce8eeb91fa2fc6d048ce00b9cd655e6aafbdaa3a2f19270a16", "ddf015b01b68c4f5f72c3145d54049867d99ee6bef24282abf0eecdb506e295bacf8f23ffa65a4cd891f76a046b9dd82cae43a8d01e18a8dff3b50aeb92672be69d7c087ec1fa2d3b2a39196ea5b49b7baede37a586fea71aded587f", "6ee721f71ca4dd5c9ce7873c5c04c6ce76a2c824b984251c15535afc96adc9a4d48ca314bfeb6b8ee65092f14cf2a7ca9614e1dcf24c2a7f0f0c11207d3d8aed4af92873b56e8b9ba2fbd659c3f4ca90fa24f113f74a37181bf0fdf758", "689bd150e65ac123612524f720f54def78c095eaab8a87b8bcc72b443408e3227f5c8e2bd5af9bcac684d497bc3e41b7a022c28fb5458b95e8dfa2e8caccde0492936ff1902476bb7b4ef2125b19aca2cd3384d922d9f36dddbcd96ae0d6", "3a3c0ef066fa4390ec76ad6be1dc9c31ddf45fef43fbfa1f49b439caa2eb9f3042253a9853e96a9cf86b4f873785a5d2c5d3b05f6501bc876e09031188e05f48937bf3c9b667d14800db62437590b84ce96aa70bb5141ee2ea41b55a6fd944", "741ce384e5e0edaebb136701ce38b3d33215415197758ae81235307a4115777d4dab23891db530c6d28f63a957428391421f742789a0e04c99c828373d9903b64dd57f26b3a38b67df829ae243feef731ead0abfca049924667fdec49d40f665", "a513f450d66cd5a48a115aee862c65b26e836f35a5eb6894a80519e2cd96cc4cad8ed7eb922b4fc9bbc55c973089d627b1da9c3a95f6c019ef1d47143cc545b15e4244424be28199c51a5efc7234dcd94e72d229897c392af85f523c2633427825", "71f1554d2d49bb7bd9e62e71fa049fb54a2c097032f61ebda669b3e1d4593962e47fc62a0ab5d85706aebd6a2f9a192c88aa1ee2f6a46710cf4af6d3c25b7e68ad5c3db23ac009c8f13625ff85dc8e50a9a1b2682d3329330b973ec8cbb7bb73b2bd", "167cc1067bc08a8d2c1a0c10041ebe1fc327b37043f6bd8f1c63569e9d36ded58519e66b162f34b6d8f1107ef1e3de199d97b36b44141a1fc4f49b883f40507ff11f909a017869dc8a2357fc7336ae68703d25f75710b0ff5f9765321c0fa53a51675c", "cb859b35dc70e264efaad2a809fea1e71cd4a3f924be3b5a13f8687a1166b538c40b2ad51d5c3e47b0de482497382673140f547068ff0b3b0fb7501209e1bf36082509ae85f60bb98fd02ac50d883a1a8daa704952d83c1f6da60c9624bc7c99912930bf", "afb1f0c6b7125b04fa2578dd40f60cb411b35ebc7026c702e25b3f0ae3d4695d44cfdf37cb755691dd9c365edadf21ee44245620e6a24d4c2497135b37cd7ac67e3bd0aaee9f63f107746f9b88859ea902bc7d6895406aa2161f480cad56327d0a5bba2836", "13e9c0522587460d90c7cb354604de8f1bf850e75b4b176bda92862d35ec810861f7d5e7ff6ba9302f2c2c8642ff8b7776a2f53665790f570fcef3cac069a90d50db42227331c4affb33d6c040d75b9aeafc9086eb83ced38bb02c759e95ba08c92b17031288", "0549812d62d3ed497307673a4806a21060987a4dbbf43d352b9b170a29240954cf04bc3e1e250476e6800b79e843a8bd8253b7d743de01ab336e978d4bea384eaff700ce020691647411b10a60acacb6f8837fb08ad666b8dcc9eaa87ccb42aef6914a3f3bc30a", "3a263efbe1f2d463f20526e1d0fd735035fd3f808925f058b32c4d8788aeeab9b8ce233b3c34894731cd73361f465bd350395aebcabd2fb63010298ca025d849c1fa3cd573309b74d7f824bbfe383f09db24bcc565f636b877333206a6ad70815c3bef5574c5fc1c", "3c6a7d8a84ef7e3eaa812fc1eb8e85105467230d2c9e4562edbfd808f4d1ac15d16b786cc6a02959c2bc17149c2ce74c6f85ee5ef22a8a96b9be1f197cffd214c1ab02a06a9227f37cd432579f8c28ff2b5ac91cca8ffe6240932739d56788c354e92c591e1dd76499", "b571859294b02af17541a0b5e899a5f67d6f5e36d38255bc417486e69240db56b09cf2607fbf4f95d085a779358a8a8b41f36503438c1860c8f361ce0f2783a08b21bd7232b50ca6d35428335272a5c05b436b2631d8d5c84d60e8040083768ce56a250727fb0579dd5c", "98ee1b7269d2a0dd490ca38d447279870ea55326571a1b430adbb2cf65c492131136f504145df3ab113a13abfb72c33663266b8bc9c458db4bf5d7ef03e1d3b8a99d5de0c024be8fabc8dc4f5dac82a0342d8ed65c329e7018d6997e69e29a01350516c86beaf153da65ac", "41c5c95f088df320d35269e5bf86d10248f17aec6776f0fe653f1c356aae409788c938befeb67c86d1c8870e8099ca0ce61a80fbb5a6654c44529368f70fc9b9c2f912f5092047d0ffc339577d24142300e34948e086f62e23ecaca410d24f8a36b5c8c5a80e0926bc8aa16a", "9f93c41f533b2a82a4df893c78faaaa793c1506974ba2a604cd33101713ca4adfd30819ffd8403402b8d40aff78106f3357f3e2c24312c0d3603a17184d7b999fc9908d14d50192aebabd90d05073da7af4be37dd3d81c90acc80e8333df546f17ab6874f1ec204392d1c0571e", "3da5207245ac270a915fc91cdb314e5a2577c4f8e269c4e701f0d7493ba716de79935918b917a2bd5db98050dbd1eb3894b65fac5abf13e075abebc011e651c03cafb6127147771a5c8418223e1548137a89206635c26ca9c235ccc108dc25cf846e4732444bd0c2782b197b262b", "96011af3965bb941dc8f749932ea484eccb9ba94e34b39f24c1e80410f96ce1d4f6e0aa5be606def4f54301e930493d4b55d484d93ab9dd4dc2c9cfb79345363af31ad42f4bd1aa6c77b8afc9f0d551bef7570b13b927afe3e7ac4de7603a0876d5edb1ad9be05e9ee8b53941e8f59", "51dbbf2a7ca224e524e3454fe82ddc901fafd2120fa8603bc343f129484e9600f688586e040566de0351d1693829045232d04ff31aa6b80125c763faab2a9b233313d931903dcfaba490538b06e4688a35886dc24cdd32a13875e6acf45454a8eb8a315ab95e608ad8b6a49aef0e299a", "5a6a422529e22104681e8b18d64bc0463a45df19ae2633751c7aae412c250f8fb2cd5e1270d3d0cf009c8aa69688ccd4e2b6536f5747a5bc479b20c135bf4e89d33a26118705a614c6be7ecfe766932471ad4ba01c4f045b1abb5070f90ec78439a27a1788db9327d1c32f939e5fb1d5ba", "5d26c983642093cb12ff0afabd87b7c56e211d01844ad6da3f623b9f20a0c968034299f2a65e6673530c5980a532beb831c7d0697d12760445986681076dfb6fae5f3a4d8f17a0db5008ce8619f566d2cfe4cf2a6d6f9c3664e3a48564a351c0b3c945c5ee24587521e4112c57e318be1b6a", "52641dbc6e36be4d905d8d60311e303e8e859cc47901ce30d6f67f152343e3c4030e3a33463793c19effd81fb7c4d631a9479a7505a983a052b1e948ce093b30efa595fab3a00f4cef9a2f664ceeb07ec61719212d58966bca9f00a7d7a8cb4024cf6476bab7fbccee5fd4e7c3f5e2b2975aa2", "a34ce135b37bf3db1c4aaa4878b4499bd2ee17b85578fcaf605d41e1826b45fdaa1b083d8235dc642787f11469a5493e36806504fe2a2063905e821475e2d5ee217057950370492f5024995e77b82aa51b4f5bd8ea24dc71e0a8a640b0592c0d80c24a726169cf0a10b40944747113d03b52708c", "46b3cdf4946e15a5334fc3244d6680f5fc132afa67bf43bfade23d0c9e0ec64e7dab76faaeca1870c05f96b7d019411d8b0873d9fed04fa5057c039d5949a4d592827f619471359d6171691cfa8a5d7cb07ef2804f6ccad4821c56d4988bea7765f660f09ef87405f0a80bcf8559efa111f2a0b419", "8b9fc21691477f11252fca050b121c5334eb4280aa11659e267297de1fec2b2294c7ccee9b59a149b9930b08bd320d3943130930a7d931b71d2f10234f4480c67f1de883d9894ada5ed5071660e221d78ae402f1f05af47761e13fec979f2671e3c63fb0ae7aa1327cf9b8313adab90794a52686bbc4", "cd6598924ce847de7ff45b20ac940aa6292a8a99b56a74eddc24f2cfb45797188614a21d4e8867e23ff75afd7cd324248d58fcf1ddc73fbd115dfa8c09e62022fab540a59f87c989c12a86ded05130939f00cd2f3b512963dfe0289f0e54acad881c1027d2a0292138fdee902d67d9669c0ca1034a9456", "594e1cd7337248704e691854af0fdb021067ddf7832b049ba7b684438c32b029eded2df2c89a6ff5f2f2c311522ae2dc6db5a815afc60637b15ec24ef9541f1550409db2a006da3affffe548a1eaee7bd114e9b805d0756c8e90c4dc33cb05226bc2b393b18d953f8730d4c7ae693159cdba758ad28964e2", "1f0d292453f04406ada8be4c161b82e3cdd69099a8637659e0ee40b8f6da46005cfc6085db9804852decfbe9f7b4dda019a7112612895a144ed430a960c8b2f5458d3d56b7f427cee6358915aee7146278aed2a0296cdd929e4d21ef95a3adf8b7a6beba673cdccdbdcfb2474711732d972ad054b2dc64f38d", "b65a72d4e1f9f9f75911cc46ad0806b9b18c87d105332a3fe183f45f063a746c892dc6c4b9181b1485b3e3a2cc3b453eba2d4c39d6905a774ed3fb755468beb190925ecd8e57ecb0d985125741650c6b6a1b2a3a50e93e3892c21d47ed5884eed83aa94e1602288f2f49fe286624de9d01fcb54433a0dc4ad70b", "705ce0ffa469250782aff725248fc88fe98eb76659e8407edc1c4842c9867d61fe64fb86f74e980598b92bc213d06f337bd5654fc28643c7ba769a4c31563427543c00808b627a19c90d86c322f33566ce020121cc322229c3337943d46f68ef939d613dcef0077269f88151d6398b6b009abb763410b154ad76a3", "7fa881ce87498440ab6af13854f0d851a7e0404de33896999a9b3292a5d2f5b3ad033530c558168fe5d2fdb9b89a2354c46cf32a0e612afc6c6485d789511bfef26800c74bf1a4cfbe30bda310d5f6029c3dccdedb6149e4971274e276dccfabd63bc4b9955e8303feb57f8a688db55ecb4b33d1f9fe1b3a8ba7ac32", "23a98f71c01c0408ae16843dc03be7db0aeaf055f951709d4e0dfdf64fffbffaf900ee592ee10929648e56f6c1e9f5be5793f7df66453eb56502c7c56c0f0c88da77abc8fa371e434104627ef7c663c49f40998dbad63fa6c7aa4fac17ae138d8bbe081f9bd168cd33c1fbc92fa35ed687679f48a64b87db1fe5bae675", "7b8970b6a33237e5a7bcb39272703edb92285c55842b30b9a48834b1b507cc02a6764739f2f7ee6ae02a7b715a1c455e59e8c77a1ae98abb10161853f1234d20da99016588cd8602d6b7ec7e177d4011edfa61e6b3766a3c6f8d6e9eac893c568903eb6e6aba9c4725774f6b4343b7acaa6c031593a36eef6c72806ff309", "f7f4d328ba108b7b1de4443e889a985ed52f485f3ca4e0c246aa5526590cbed344e9f4fe53e4eea0e761c82324649206ca8c2b45152157d4115e68c818644b03b65bb47ad79f94d37cb03c1d953b74c2b8adfa0e1c418bda9c518ddcd7050e0f149044740a2b16479413b63fc13c36144f80c73687513dca761ba8642a8ae0", "2d7dc80c19a1d12d5fe3963569547a5d1d3e821e6f06c5d5e2c09401f946c9f7e13cd019f2f9a878b62dd850453b6294b99ccaa068e542993524b0f63832d48e865be31e8ec1ee103c718340c904b32efb69170b67f038d50a3252794b1b4076c0620621ab3d91215d55ffea99f23d54e161a90d8d4902fda5931d9f6a27146a", "77dff4c7ad30c954338c4b23639dae4b275086cbe654d401a2343528065e4c9f1f2eca22aa025d49ca823e76fdbb35df78b1e5075ff2c82b680bca385c6d57f7ea7d1030bb392527b25dd73e9eeff97bea397cf3b9dda0c817a9c870ed12c006cc054968c64000e0da874e9b7d7d621b0679866912243ea096c7b38a1344e98f74", "83bed0d556798f2b419f7056e6d3ffada06e939b95a688d0ec8c6ac5ea45ab73a4cf01043e0a170766e21395f27ab4b78c435f5f0dfe6e93ab80df38610e41158429ddf20296f53a06a017723359fe22dc08b5da33f0800a4fe50118e8d7eab2f83a85cd764bf8a166903bd0e9dcfeeceba44ff4ca4439846458d31ea2bb564645d1", "ea12cf5a113543e39504123036f15a5bafa9c555562469f99cd29996a4dfaaab2a34b00557ccf15f37fc0cc1b3be427e725f2cd952e50af7970dda9200cd5ce252b1f29c40067fea3027ed686190803b59d834179d1b8f5b55abe55ad174b2a1188f7753ec0ae2fc01316e7d498b68ee3598a0e9baaaa664a60f7fb4f90edbed494ad7", "55266358332d8d9e68bd13432088beadf95833aab67a0eb3b10650414255f299e2670c3e1a5b2976159a46c72a7ce57d59b7be14c15798e09ed50fa312a431b0264d7a1396aa6168bde897e208ece53d2cfc83786113b1e6eac5e9bb98984abb6c8d64eebb991903254abc650c999bb9958a5d7937434b869bc940e21b9dc1cc8982f2ba", "4d6104ded730aefe02873f4c741232c8234a6d66d85393aff57fbf56ba6347666988dfc4d58f3cc895a0da598822edeee4533d24ec0ee292fd5e1ad04898ffbc1ff4bef14dec220babcb0f28fffe32a6e2c28aaaac16442bf4feb02917d18bb3a415d84fa9358d5a9852688d846c92271911f934181c30f82434d915f93f155a1ffbf0b125", "eb5f579a4c476af554aac11e5719d378549497e613b35a929d6f36bb8831d7a466aa76de9be24ebb55543f1c13924f64cfd648a5b3fa90387315c16174dbf1e9a183c196d9bb8f84af65f1f8212429aadc11ef2426d07d4716062b85c8d5d2dff8e21b9e62b7fa7dbd57d72633054b464fb28583a56ca13ccc5ddc74dae942492f31731e7046", "ebddec3dcaf18063e45a76ebeac39af85a1adc2818881ccce48c106288f5988365cca2b4b1d7f037322da46840f42bebdcbc7193838d426e101087d8cea03aaff743d573eb4f4e9a71a2c884390769a6503874125d194bee8d46a3a0d5e4fcf28ff8465887d8e9df771d70157e75df3642b331d2778ceb32ceba868640171ab7a5d22eede1ee44", "26d87ec70b57691e3bb359633d3ddba17f029d62cdfe977f5fd42274d79b444a32494d1c01e9f72d03cce78c806df96e93ea78da3a054209924ed765edc4d570f66168dc25ee3114e4017e387440349c8f0a94804761c3055f88e4fda2a49b860b1486a9609095f6250f268b6a4d1aecc03a505632ebf0b9dc22d0755a736faf7ad7000858b5864b", "3880f5cc2d08fa70ef44b1f263fcf534d062a298c1bd5ee2eee8c3265806c4ce50b004f3a1fc1fa5b024aaac7f528c023c8181f67c6e1c357425dc4d573bd46b93a542afa3a19bdb140a2ce666e1a01f5c4d2dcd681fa9f5839b797813c394738d5ee4971386c12c7c117d17c7bec324b760aa30cda9ab2aa850284ba6fa97946f710f02449d1883c6", "3317d2f452105dd3f4a96f9257af8285a80be58066b50f6f54bd633749b49f6ab9d57d45652d2ae852a2f6940cd5ec3159dd7f333358b12f502325df38843508faf7e246352d201280babd90b14fbf7722641c3601d0e458474439973c611bb5502fd0eb3078f87124ca7e1a016fcb6cfeff65f6a565985aca7122cfa8c5a11da0cb47797c5132333179", "f2c5c955d0224e784a46b9125f8fef8a5e1271e145eb08bbbd07ca8e1cfc848cef14fa3b36221ac62006403dbb7f7d77958ccc54a8566c837858b809f3e310ace8ca682515bc655d2a397cab238a663b464d511f02dc5d033dad4cb5e0e519e94a54b62a3896e460ec70e5716b5921bf8396aa86a60123e6287e34570bb01bdc602e113670bf498af2ff10", "180e275205691a83630cf4b0c7b80e6df8fad6ef1c23ba8013d2f09aef7abade1827f23af230de90676240b4b3b0673f8afdea0327330055041741f65560d90348de696d34ca80dfe8afae582fe4879d4594b80e9408fb53e800e01ca58552b905c365e7f1416e51c080f517d6bbd30e64ae1535d59decdc76c6624d737868f49f2f719da39ba1344d59eab9", "c517a84e4631a7f65ace170d1e5c2fdb259841535d88da323e68c0883e6af7b041cfe05908815a5a9d1b14fa712c2c16fadcf1ca54d3aa954d411240df331b2aebdfb65aced84d0b8aace56ec0aa7c13ec7d75ca883b6bcf6db74c9e98463c484a8262684f29910373430651f90ecffe18b072170e61ee58de20e2a6ff67b3ab00fccbb80af943f20b56b98107", "d1a56a5ee990e02b84b5862fde62f69ec07567be2d7ccb769a461c4989d11fdda6c945d942fb8b2da795ed97e43a5b7dbdde7f8fd2ff7154544336d5c50fb7380341e660d4898c7fbc39b2b782f28defac6873523c7c1de8e52c65e4395c686ba483c35a220b0416d46357a063fa4c33fa9c52d5c207a1304ae141c791e62ba6a7374ed922b8dd94079b72b69302", "4720b88d6bfb1ab43958e26827730d852d9ec30173ebd0fe0d273edcece2e788558984cd9306fe5978086a5cb6d37975755d2a3daeb16f99a8a11544b8247a8b7ed5587afc5bea1daf85dcea5703c5905cf56ae7cc76408ccabb8fcc25cacc5ff456db3f62fa559c45b9c71505eb5073df1f10fc4c9060843f0cd68bbb4e8edfb48d0fd81d9c21e53b28a2aae4f7ba", "f4639b511db9e092823d47d2947efacbaae0e5b912dec3b284d2350b9262f3a51796a0cd9f8bc5a65879d6578ec24a060e293100c2e12ad82d5b2a0e9d22965858030e7cdf2ab3562bfa8ac084c6e8237aa22f54b94c4e92d69f22169ced6c85a293f5e16bfc326153bf629cdd6393675c6627cd949cd367eef02e0f54779f4d5210197698e4754a5fe490a3a7521c1c", "3d9e7a860a718565e3670c29079ce80e381969fea91017cfd5952e0d8a4a79bb08e2cd1e26161f30ee03a24891d1bfa8c212861b51618d07429fb48000ff87ef09c6fca526567777e9c076d58a642d5c521b1caa5fb0fb3a4b8982dc14a444732b72b239b8f01fc8ba8ee86b3013b5d3e98a92b2aeaecd4879fca5d5e9e0bd880dbfffa6f96f94f3998812aac6a714f331", "4d9bf551d7fd531e7482e2ec875c0651b0bcc6caa738f7497befd11e67ae0e036c9d7ae4301cc3c7906f0d0e1ed4738753f414f9b3cd9b8a71176e325c4c74ce020680ecbfb146889597f5b40487e93f974cd866817fb9fb24c7c7c16177e6e120bfe349e83aa82ba40e59e917565788658a2b254f25cf99bc65070b3794cea2259eb10e42bb54852cba3110baa773dcd70c", "b91f65ab5bc059bfa5b43b6ebae243b1c46826f3da061338b5af02b2da76bb5ebad2b426de3c3134a633499c7c36a120369727cb48a0c6cbab0acecdda137057159aa117a5d687c4286868f561a272e0c18966b2fec3e55d75abea818ce2d339e26adc005c2658493fe06271ad0cc33fcb25065e6a2a286af45a518aee5e2532f81ec9256f93ff2d0d41c9b9a2efdb1a2af899", "736f6e387acb9acbee026a6080f8a9eb8dbb5d7c54ac7053ce75dd184b2cb7b942e22a3497419ddb3a04cf9e4eb9340a1a6f9474c06ee1dcfc8513979fee1fc4768087617fd424f4d65f54782c787a1d2de6efc81534343e855f20b3f3589027a5436201eee747d45b9b8375e4294d72ab6a52e04dfbb2914db92ee58f134b026527ed52d4f794459e02a43a17b0d51ea69bd7f3", "9242d3eb31d26d923b99d66954cfade94f25a18912e6356810b63b971ae74bb53bc58b3c01424208ea1e0b1499936daea27e63d904f9ed65fdf69de40780a3027b2e89d94bdf214f585472613ce328f628f4f0d56217dfb53db5f7a07f54c8d71db16e27de7cdb8d23988837b49b65c12f1771d979e8b192c9f4a16b8d9fba917bcf74ce5a82aac2075608ba6c2d485fa59864b9de", "5da68704f4b592d41f08aca08f62d85e2e2466e5f3be010315d11d113db674c4b98764a509a2f5aacc7ae72c9deff2bcc42810b47f64d429b35745b9efff0b18c58653461e968aaa3c2c7fc455bc5771a8f10cd184be831040df767201ab8d32cb9a58c89afbebecb524502c9b940c1b838f8361bbcde90d272715017f67609ea39b20fac985332d82daaa023999e3f8bfa5f3758bb8", "71ea2af9c8ac2e5ae44a176662882e01027ca3cdb41ec2c6785606a07d7231cd4a2bded7155c2feef3d44d8fd42afa73265cef826f6e03aa761c5c51d5b1f129ddc27503ff50d9c2d748322df4b13dd5cdc7d46381528ab22b79b0049011e4d2e57fe2735e0d58d8d56e92c75dbeac8c76c4239d7f3f24fb56697593b3e4afa6671d5bbc96c079a1c154fe20212ade67b05d49ceaa7a84", "1d133170582fa4bff59a21953ebbc01bc202d43cd79c083d1f5c02fa15a43a0f519e36acb710bdabac880f04bc003800641c2487930de9c03c0e0deb347fa815efca0a38c6c5de694db698743bc955581f6a945deec4ae988ef7cdf40498b77796ddea3fae0ea844891ab751c7ee20917c5a4af53cd4ebd82170078f41ada2795e6eea17593fa90cbf5290a1095e299fc7f507f360f187cd", "5ec4ac45d48fc15c72471d795066bdf8e99a483d5fdd599511b9cdc408de7c0616491b73924d0266da34a495331a935c4b8884f57d7ad8cce4cbe586875aa52482215ed39d7626cce55d50349c7767981c8bd6890f132a196184247343566fc972b86fe3c5369d6a6519e9f07942f0522b77ad01c751dcf7defe31e471a0ec00963765dd8518144a3b8c3c978ad108056516a25dbe3092e73c", "0d5e74b78290c689f2b3cfea45fc9b6a84c822639cd438a7f05c07c374adced42cdc12d2a9233a4ffe80307efc1ac13cb04300e165f8d90dd01c0ea955e7657332c6e86ad6b43e78ba4c13c675aed83192d8427866fb6484e6a3071b2369a46fba9005f31232da7ffec7952f831aaaddf63e225263531c2cf387f8cc14fa856c8795137142c3a52ffa69b8e30ebc88ce3bbc227597bcc8dddd89", "a0fe36f983259921dc2fa7d89002b3066241d63bfc2448caf7e10522a35562be0bfedc3dce49cfce2e614a04d4c64cfc0ab898873a7fc26928dc1927c009d12f6f9b7a278205d3d0057604f4ac746f8b9287c3bc6b929832bf253b6586192ac43fdd29ba585dbd9059aab9c6ff6000a7867c67fec1457b733f6b620881166b8fed92bc8d84f0426002e7be7fcd6ee0abf3755e2babfe5636ca0b37", "1d29b6d8eca793bb801becf90b7d7de215b17618ec32340da4bac707cdbb58b951d5036ec02e105d83b5960e2a72002d19b7fa8e1128cc7c5049ed1f76b82a59eac6ed09e56eb73d9ade38a6739f0e07155afa6ec0d9f5cf13c4b30f5f9a465b162a9c3ba04b5a0b3363c2a63f13f2a3b57c590ec6aa7f64f4dcf7f1582d0ca157eb3b3e53b20e306b1f24e9bda87397d413f01b453ceffeca1fb1e7", "6a2860c110cd0fc5a19bcaafcd30762ee10242d34739638e716bd89fd537ea4dc630e6f85d1bd88a25ad3892ca554c232c9830bd56980c9f08d378d28f7fa6fa7df4fcbf6ad98b1adfff3ec1f63310e50f920c99a5200b8e64c2c2ca249399a149942261f737d5d72da949e914c024d57c4b639cb89990fed2b38a37e5bcd24d17ca12dfcd36ce04691fd03c32f6ed5de2a2191ed7c826375ba81f78d0", "7132aa291ddc9210c60dbe7eb3c19f9053f2dd74742cf57fdc5df98312adbf4710a73245de4a0c3b24e21ab8b466a77ae29d15500d5142555ef3088cbccbe685ed9119a10755148f0b9f0dbcf02b2b9bcadc8517c88346ea4e78285e9cbab122f824cc18faf53b742a87c008bb6aa47eed8e1c8709b8c2b9adb4cc4f07fb423e5830a8e503ab4f7945a2a02ab0a019b65d4fd71dc364d07bdc6e637990e3", "3e664da330f2c6007bff0d5101d88288aaacd3c07913c09e871cce16e55a39fde1ce4db6b8379977c46cce08983ca686778afe0a77a41baf447854b9aa286c398c2b83c95a127b053101b6799c1638e5efd67273b2618df6ec0b96d8d040e8c1ee01a99b9b5c8fe63fea2f749e6c90d31f6fae4e1469ac09884c4fe1a8539acb313f42c941224a0e79c059e18affc2bcb6724975c436f7bf949ebdd8aef51c", "7a6ea63a271eb49470f5ce77519ed61ae9b2f1be07a96855726bc3df1d0723af3a703fdfc2e739c9d31d25814daf661a23558b50982e66ee37ad880f5c8f11c8130fac8a5d0250583700d5a324894fae6d61993f6bf9327214f8674649f355b23fd634940b2c467973a839e659169c773119919f5b81ee171edb2e5f6940d7551f9e5a70625d9ea88711ad0ed8ab2da720ad358bef954456cb2d5636425717c2", "c5106bbda114168c449172e49590c7eeb827fa4e1a2a7a87a3c1f721a9047d0c0a50fbf244731be1b7eb1a2ef30f5ae846a9f38f0df44f32af61b68dbdcd0226e741dfb6ef81a2503691af5e4b3171f48c59ba4ef91eba344b5b697f261df7bbbb734ca6e6daebaa4a179feb17002823281b8534d55a6531c59305f6e3fd3fa63b747bcf0deb654c392a02fe687a269effb1238f38bcaea6b208b221c45fe7fbe7", "597716a5ebeebc4bf524c15518816f0b5dcda39cc833c3d66b6368ce39f3fd02ceba8d12072bfe6137c68d3acd50c849873150928b320b4fbc31c1456679ea1d0acaeeabf666d1f1bad3e6b9312c5cbdecf9b799d3e30b0316bed5f41245107b693366accc8b2bcef2a6be54209ffabc0bb6f93377abdcd57d1b25a89e046f16d8fd00f99d1c0cd247aafa72234386ae484510c084ee609f08aad32a005a0a5710cb", "0771ffe789f4135704b6970b617bae41666bc9a6939d47bd04282e140d5a861c44cf05e0aa57190f5b02e298f1431265a365d29e3127d6fccd86ec0df600e26bcdda2d8f487d2e4b38fbb20f1667591f9b5730930788f2691b9ee1564829d1ada15fffc53e785e0c5e5dd11705a5a71e390ca66f4a592785be188fefe89b4bd085b2024b22a210cb7f4a71c2ad215f082ec63746c7367c22aedb5601f513d9f1ffc1f3", "be6556c94313739c115895a7bad2b620c0708e24f0390daa55521c31d2c6782acf41156271238885c367a57c72b4fe999c160e804ad58d8e565edbce14a2dd90e443eb80626b3eab9d7ab75d6f8a062d7ca89b7af8eb292c98eaf87ad1dfd0db103d1bb6188bd7e7a63502153cf3ce23d43b60c5782602bac8ad92fb2324f5a79453898c5de18415639ecc5c7974d3077f76fc1df5b956723bb19a624d7ea3ec13ba3d86", "4bc33729f14cd2f1dc2ff459abee8f6860dda1062845e4adab78b53c835d106bdfa35dd9e77219eaef403d4e80488ca6bd1c93dd76ef9d543fbb7c8904dccc5f71509a6214f73d0f4e467c3e038ea639b29e7fc442ee29f57117740576188ada15a739827c647a46b0271817ab235c023c30c90f2115e5c90cd8501e7b286962fc66ffc3fe7e8978746168314908a41998bd83a1eeffda9d714b864f4d490fdeb9c7a6edfa", "ab12faea205b3d3a803cf6cb32b9698c32301a1e7f7c6c23a20174c95e98b7c3cfe93fffb3c970face8f5751312a261741141b948d777b8a2ea286fe69fc8ac84d34116a4674bb09a1a0b6af90a748e511749de4697908f4acb22be08e96ebc58ab1690acf73914286c198a2b57f1dd70ea8a52325d3045b8bdfe9a09792521526b7564a2a5fcd01e291f1f8894017ce7d3e8a5dba15332fb410fcfc8d62195a48a9e7c86fc4", "7d421e59a567af70594757a49809a9c22e07fe14061090b9a041875bb77933deae36c823a9b47044fa0599187c75426b6b5ed94982ab1af7882d9e952eca399ee80a8903c4bc8ebe7a0fb035b6b26a2a013536e57fa9c94b16f8c2753c9dd79fb568f638966b06da81ce87cd77ac0793b7a36c45b8687c995bf4414d28289dbee977e77bf05d931b4feaa359a397ca41be529910077c8d498e0e8fb06e8e660cc6ebf07b77a02f", "0c18ab727725d62fd3a2714b7185c09faca130438eff1675b38beca7f93a6962d7b98cb300ea33067a2035cdd694348784aa2eda2f16c731eca119a050d3b3ce7d5c0fd6c234354a1da98c0642451922f670984d035f8c6f35031d6188bbeb31a95e99e21b26f6eb5e2af3c7f8eea426357b3b5f83e0029f4c4732bca366c9aa625748297f039327c276cd8d9c9bf692a47af098aa50ca97b99961bef8bc2a7a802e0b8cfdb84319", "92d5909d18a8b2b9971cd1627b461e98a74ba377186a6a9df5bd133635250b300abccb2254cacb775df6d99f7c7d0952653c28e6909b9f9a45adce691f7adc1afffcd9b06e49f775364cc2c62825b9c1a86089080e26b57e732aac98d80d009bfe50df01b95205aa07ed8ec5c873da3b92d00d53af825aa64b3c634c5ece40bff152c331222d3453fd92e0ca17cef19ecb96a6eed4961b627aca48b12fecd091754f770d52ba861546", "802f22e4a388e874927fef24c797408254e03910bab5bf372320207f8067f2b1ea543917d4a27df89f5bf936ba12e04302bde23119533d0976beca9e20cc16b4dbf17a2ddc44b66aba76c61ad59d5e90de02a88327ead0a8b75463a1a68e307a6e2e53ecc1986274b9ee80bc9f3140671d5285bc5fb57b281042a8978a1175900c6073fd7bd740122956602c1aa773dd2896674d0a6beab24454b107f7c847acb31a0d332b4dfc5e3f2f", "3844fe65db11c92fb90bf15e2e0cd216b5b5be91604baf3b84a0ca480e41ecfaca3709b32f8c6e8761406a635b88eec91e075c48799a16ca08f295d9766d74475c47f3f2a274eae8a6ee1d191a7f37ee413a4bf42cad52acd5564a651715ae42ac2cddd52f819c692ecdef52ecb763270322cdca7bd5aef71428fa73e844568b96b43c89bf1ed42a0abf209ffad0eeec286c6f141e8af073ba4adfbbdeda253752ae36c9957dfc905b4c49", "329377f7bf3c8d74991a7d61b0cf39baff5d485d79751b0d5ad017d23bec570fb19810105bab79ab5acb102ab972165224d4ec888ec7de5148077fa9c1bb6820e0d91ae4e2591a21fec2f820606ce4bafc1e377f8dc3a5bd1a9e2772a57abccd0b757164d768872c91d02789545ab5b203f688d71dd08522a3fd2f5bcd7df507aebf1ca27ddff0a82afb7aa9c180008f49d1325adf97d047e77238fc75f56356de4e87d8c961575c9f6362c9", "f7f269929b0d71ea8eef7120e55ccba691c582dd534692abef35c0fe9dec7dae973cd9702e5ad420d278fe0e653fdcb22fdcb63148109ec7e94f2d0750b28157dd1764376ae10fdb0a4aef3b304bd82793e0595f941226a2d72abbc929f53134dc495b0d65ced409914f94c2523f3dfbbdeeac84ae247ab5d1b9ea33dce1a808885a55be1f3683b46f4be73d9b62eec2585f690056858dfc427aabf591cd276724885bcd4c00b93bb51fb7484d", "ac022309aa2c4d7fb628255b8b7fb4c3e3ae64b1cb65e0de711a6def1653d95d8088871cb8905fe8ae76423604988a8f77589f3f776dc1e4b30dbe9dd262b2187db02518a132d219bd1a06ebac13132b5164b6c420b37dd2ccee7d69b3b7fa12e54f0a53b853d490a68379ea1fa2d79762830ffb71bf86aab506b51f85c4b6a41b69325c7d0c7aa85b93b7144489d213e8f33dbb879fce22849865337b620b155cb2d2d36a68832889e30194d36d", "d009c2b78a8f02e5e5dbb586ef71fc324b375092e15913ca1a5bfd22d516baadb96867bee3562e77c4a4852344a1a76c30728be5e22400b4cc41711f66754c246a520498d8c24f0205b9c873748dbeb67fe1ad099ad04cf89f4b517f0aa481136d9f6de2d727df01c6aa4099da59d4382b51e25fd47c33d9842c32b62331e50794bfe8b61b3ba9de1b8b704779c6d65edff3af00f121ab4a7ea384edabe47c6d0098a48991f387ca4444135ec59d46", "c00bab36cce69899817d1425016d222d7303197ed3e3fdcac744705e7f178a1ac745968900f69299163e19b3161f3e0a4cc55aa2e4e71e0ee6ac427d1f4d14e063f68d303ddfbb18118335cfa7a6a90d99c38319ee76f7a884846a9e0b68030bf28e78bfbd56359b9368842814da42b04cb0e307d5d846dc22f049147bae31b9a956d17676a8cc348dafa3cabc2007a30e730e3894dddf9999fb8819086311f0703e141613ed6dcd7af8510e2dc435b0", "c9789152a9fc29698d49ed95f09bd11b75f18a8c5615a73dbe54ae5e550027fd0ae6a8b60667040c1b12de3d1ee3f6bf061c78c951a3210effc912e19f482dd4de152063c588c44903bc11761706fd935afa040df085b08144d83d0dde32b46ab52f4fae98ac116c7ff11d7f553450c2e37b9c5f0b1dd9e0b8640a24cba6f2a5246c41f197f46e3dc8a29131c79bef3351c6e277a0a34442274d546ccd058891277473d668420f121750d19cd684267405", "06a15a0731ce52557e368bcbaa11ef3399299e36fb9f2eda6e5726907c1d29c5c6fc581405ba48c7e2e522206a8f128d7c1c939d1132a00bd7d6366aa82724e968964eb2e373563f607dfa649590dcf5589114df69da5547fef8d1604cc4c6de1ed5783c8746918a4dd31168d6bc8784cd0c769206bd803d6ca8557b66748770402b075ef44b38157d4c0da7c6281725a2065d087b1f7b23455fa673bdeeba45b983311c44eabe9ef4b7bde3420ae9881863", "d08aacef2d7a41aec09473bd8a44f628e15addb7b9e5b77a1e09c8ab4942f379a0bfcb324d580b774666f18ae78dd36710824ff12393f059068fe4b559c53662c2b0e6c69e23785c8f32554e837ec1714bee902e60737b639dd933af4f68cb9d7de77e1f3b28e5b122891afce62b79acd5b1ab4ba411662cc77d806449e69c5a45a143b742d98ac84a0826d68433b9b700ace6cd472ba2d58a90847f42ce9c43f38ffc017db4bf40450b2eee1f4594dc740c0f", "6a6058b0a498b7ea76a93c646eb9b8629f0cba4a0c726420c5f67ba9b0412cade356abdf0a4fb94384bad32ce0d5dd9e23dcaae1d6f28ff8683616b30f1392890c67b3a2c04b360893b801f127e527e4da82e239f4c878da13f4a4f1c76db07190e77ec123995168102fb274434a2d1e12913b9b5cbab4aacaad2bd89d88b3ca2b8e60dacf7c22c9379097ff60880f552e320ca3b571994f52534470feee2b39e0dadb5cd88257a3e459a4cc6f12f17b8d54e1bb", "adeced01fc5671531cbb45679f5ddd42b3a95151677b6125aaf6f5e8f82fbabaa5ecf7c3552c2458587224f0042870f178f5fca5465250e75d71352e652eeed23cdb7f915f5ebb44099b6db116ca1be45530ac8ed32b7f161d60ed4397ad3d7d649ae6bf75ca5bec891d8e595605be9764f3a03965e1fe0eaffbf212e3df4f0fa35e08ff9d0091e6d4ac4748edfe43b611085a6ffec163014655fdd839fd9e81b63b1fa8cae4ec335ec343289758e389a79ceedfae", "d014592f3a83ba40af366f137c674724916c3cdd3f6cf9d4c5c7c8d6d51ebf26e315e2c12b3546be56fb52382904046ecbd2f5b883aa4ff473de6f0c26ab862c3fa34bf3d880cc1911ce39a4088c6617c179dc5faf68a2c488bbde12d67b50f73abcfab0e3b062e68c95363e11f5f1de8ec36ed01ea21442518089045df67d346135283ad5b3fff80cf57f20876849f6db9fa139728358415a90610f69ec720fc92d8234e3e122551e9df2c644c4a2c4e3734d07de8e", "c0d0c37838873ba8757d6e41b409605043bc1635edcd731219587676d94217e9f0ab44b71de25000661ce7303b7015f45e6eaa7b7ebef92b8f4a34c902c908d2172185505fa33aca5a41be83079316cdfdd430fc2c45f505f85d867e6d516f7e1bf19c001d9f43018968aab65ec031b3801399231c83ec9e622dab5629922a6b424cab938c135ff7310501c2c02971bfd2f577e25904d1a618baf0859f77f4e8b1d0cde9544e95ec52ff710c0672fdb3d891feeea2b017", "7022e7f00902219ba97baa0e940e8ac7727f58955aa068c29680fac4a16bcd812c03eeb5adbcfe867a7f7c6b5d89f4641adb9173b76a1a8438866f9b4f640ce2aedf5f1080c890bcf515b4be4e3e512352f1e5323c62ec46cb73f3d71be8235fee55a154763f7c3f9aeb61ffd28f4cd93d3310f608e2133586bf1ab3f102de96f64c68a4668de8acb2a76a7ce0cddddc8fa3df5e9d230823da16ed9ebb402d36e38e6e018795e5a71517ecab5f9ca472b9ced8ff69d2d195", "acaf4baf3681ab865ab9abfae41697141ead9d5e98523c2e0e1eeb6373dd15405242a3393611e19b693cabaa4e45ac866cc66663a6e898dc73095a4132d43fb78ff7166724f06562fc6c546c78f2d5087467fcfb780478ec871ac38d9516c2f62bdb66c00218747e959b24f1f1795fafe39ee4109a1f84e3f82e96436a3f8e2c74ef1a665b0daaa459c7a80757b52c905e2fb4e30c4a3f882e87bce35d70e2925a1671205c28c89886a49e045e31434abaab4a7aed077ff22c", "84cb6ec8a2da4f6c3b15edf77f9af9e44e13d67acc17b24bd4c7a33980f37050c0301ba3aa15ad92efe842cd3ebd3636cf945bb1f199fe0682037b9dacf86f162dadabfa625239c37f8b8db9901df0e618ff56fa62a57499f7ba83baebc085eaf3dda850835520344a67e09419368d81012168e5de5ea45158397af9a5c6a1657b26f319b66f816cd2c28996547d697e8df2bb163ccb9dda4d6691dffd102a13667ab9cde60ffbfb872187d9c425a7f67c1d9fffff9276ed0aeb", "6a52c9bbbba454c14540b2be58230d78ecbeb391646a0c6fcce2f789086a78364b81ae85d5396d7cfa8b46bda41e3083ec5cf7b4c47dc601c8a697df52f557defca248506dbebab25657f5a561d09625b7f4b2f0119a12beeac087efc9d350a735c35d2431c1da7dda99befb17f41a3dc4da0f00bb95366be128538ce27763d81f832fe3c1d4efc07b5b08ad8dc9e65fb5e48546664e18cb2d3bb3fe1f56fa7aae718c5e3bbdeaf70e15023f6a25b72a2d177fcfd04211d40664fe", "c3c4d3b31f1f5f9538923df3478c84fffaef411520a542da9a220ee4132eabb9d718b5076fb2f985485e8ba058330aed27ddfd3afa3db34aa60301088caec3d0053828c0c2bc87e2e61db5ea5a29f62fdad9c8b5fc5063ec4ee865e5b2e35fac0c7a835d5f57a1b1079833c25fc38fcb14311c54f8a3bd251bca19342d69e5785f9c2e43cf189d421c76c8e8db925d70fa0fae5ee3a28c4047c23a2b8a167ce53f35ced33bec822b88b06f41558c47d4fed1bfa3e21eb060df4d8ba1", "8d55e92136992ba23856c1aea109766fc44772477efc932b3194af2265e433ed77d63b44d2a1cff2e8680eff120a430fe012f0f09c6201d546e13ad46fc4ce910eab27bb1569879abed2d9c37fae9f1267c2216ec5debcb20d4de58461a621e6ce8946899de81c0add44d35e27b7982a97f2a5e6314901caebe41dbba35f48bc9244ca6dca2bdde7306435892f287036df088633a070c2e385815ab3e2bfc1a47c05a5b9fe0e80dd6e38e4713a70c8f82bd32475eea8400c7bc67f59cf", "5016284e20362610fa05ca9d789cad25f6d43263787e7e085476764ce4a8908ce99b262b375e9d106170b1bec1f473d5e777e0c1896533040e39c8c1465e07907ef5860e14e4d8310013e35f12090e0bfc687474b1f15f3dd2033a0edac5246102da4deec7e188c3517d84d9c2a0a4497a4c5f82a30f1ba009e45ee6eb3ab4368c720ea6feee428ffd2c4cc52debb8d634a64176572c72368f94a66689f23f8a01218f532117af5a8060d140e7ca435a92882fcb5630ebe14a4805f1dc83", "05456ec59b8d41bbd736727976b96b38c43827f9e16169be673ff37870c2ecd5f0d1ea1a136be4cc7b047a02a4421d484fd2a12ece418e42ee391a13a0b1df5a0162b29ab70d3fe3e04ba6ab26b37d62b7cf05a5e2f033611bf970b8e1f30e198e483e740fa9618c1e8677e07b61296b94a9787a68fba622d7653b5568f4a8628025939b0f74389ea8fced6098c065bf2a869fd8e07d705eadb53006be2abb716a3114ceb0236d7e916f037cb954cf977720855d12be76d900ca124a2a66bb", "eb6f60b83fcee77060ff346aaf6ec34d82a8af469947d3b5074cde8eb26566eb1fa039bcc707738df1e95869bd827c246e88436f0614d9834ead5392ef376105c4a9f370071cdeaaff6ca0f18b74c3a48d19a717253c49bd9009ccbfdd5728a08b7d112a2ed8dbafbbb46d7a75dc9a05e09bfde1a0a92d74a51887f9d123d7896e9f9d0057b660ed7d55454c069d3c5260411db4cdc67e7b74f680d7ac4b9dcc2f8baf72e15e6b3cafebcdf449a6436ed2c398b675f79c644747c57553bf7ea2", "187a88e88514f6c4157c1ba40b442baae1ae563a6c989277443b12a219aa484cb9fa8adbb9a29d429f50155321b15664926317477079c7060dfdaa84c1d74bba78892c34e6f21ad35208d2ae622012401696bff5cd57b6485944b3db7b9071fa5f57fbfb1085d91bb9cff5808d662cdc6c8157249478262c44b7fbc397ed42a4977b202e817717bfccc9f0467294062313f7705251ed09573f16d23429361fada259dfb300369c4198f07341b38e84d02cdb74af5de6aab1fc2026208ea7c418c0", "be31bc96606d0fab007e5caeded2f1c9f747c759777e9b6eef962bed49e45a1d4fc993e279d024915e600865ecb087b960584be18c41114d3c43f92169b9e0e1f85a0ebcd4e196376ccdc920e66103cd3b1c58407d0aafd0e003c4e341a1daddb9f4faba974362a32f35db83384b05ae8e3322d728893861afd8b1c940de5a17f691e763ce4969b6d94f67fb4a0235d100225bd8602f291388f0ca4a568748ad0d6040f1262eac2aede6cd27419bb78a394c1ffad72c262be8c3f9d9619d633e51d0", "4d83d85ca838b4518588f2a90228a4dd18f14dd5b4c012d26298a97d848abbd825d221d02cceb6e8c701b4ad00e1dee4889b5c533e4bb60f1f41a4a61ee5478be2c1b1016c30345afd7a5253668260515e70751f22c8b4022d7fe4877d7bbce90b46531507dd3e89549e7fd58ea28f4cb23d33662bd003c1345ba94cc4b06867f778957901a8c441bee0f3b12e16463a51f7e50690356971dd73a686a49fda1eae46c9d54fba262811d698025d0ee053f1c58591c3bb3cbde69de0b31549ef5b69cf10", "cdeb07d36dc5f9a1cd717a9e9cca37a2ce93caa298eee63571f7d6c5fde2a11c666cf53cf2dcb41ca2ea2319e7230ca68e38c647905928713a13982bf47fe33d7095ebd50b2df976208920a43eb2e29b942f32467403c45cea18bf44e0f6aeb155b48a8e5c471fec972a9d62f7ae093d2758f0aaec7ca50cb4725bfa219f1a3a46ad6bde7361f445f86b94d66b8ece080e56c510250693a5d0ea0ae87b4421860b853bcf0381eae4f1bf7c5c0472a93ad18407bc88475ab8560d344a921d3e86a02da397", "a598fad52852c5d51ae3b10528fc1f722e21d44fbd42ae5acdf20e85a28532e646a223d27fd907bfd38eb8bb75175636892f8242877aab89e8c0824d368f3339ce7a82aa4e5af6db1f3b588a4d667a00f67bee37cfd2724dde06d2909fb9e58d892f4cfd2c4ca85acdf8256f5458b030a6bda151154ff2e6d7a8da90b54a2884c8a99fab5a4ac211ff23dc0975f4f592fd1b6b9dc7783bdcd2d4ca4e68d2902f2013e122cb62e2bff6b0a98ec55ba25837e21f1cfe67739b568d43e6413dab2bd1dc471e5a", "17b68c74c9fe4926e8102070916a4e381b9fe25f5973c9bd4b04ce25749fc18931f37a65a356d3f5e5a1ef125d546f4f0ea797c15fb2efea6fbfcc5739c564693d47adeb12dcb3d98a2830719b13247792cb2491dca159a28138c6cff925aca42f4fdb02e73fbd508ec49b25c60703a7595a3e8f44b155b371d525e48e7e5dc84ac7b17c52bf5e526a67e7187234a2f19f57c548c70fc0b27183df73ffa53fa58b658034c896fa791ae9a7fd2620f5e46ce84c842a6e60e9324ae4db224ffc87d9617cb85ca2", "b9e4267ea39e1de1fed0579f93bb351007c9f8fcdd811053fae33f09e2753d7428f04e1a9efcd45ea701a5d87a35b3afb2e6b65365dee6ead0bbb611b7797b212ac688653f542e604a39df277f12514ddfee3b4e27b98395c2cd97a203f1f1153c50327965770802ec2c9783edc428271762b275471e7ac65ac36523df28b0d7e6e6ccc7674268a132a63411fc82c0738dbb68af003b769a0bf9e6587b36476cb465350fee13f88ea355d47ffac7b0f964f4139db11b7642cb8d75fe1bc74d859b6d9e884f75ac", "8ca704fe7208fe5f9c23110c0b3b4eee0ef632cae82bda68d8db2436ad409aa05cf159223586e1e6d8bdae9f316ea786809fbe7fe81ec61c61552d3a83cd6beaf652d1263862664df6aae321d0323440430f400f291c3efbe5d5c690b0cc6b0bf871b3933befb40bc870e2ee1ebb68025a2dcc11b68daadef6be29b5f21e440374301bde1e80dcfade4c9d681480e65ec494a6af48df232c3d51447b9d06be714949249c44c43cf73ed13ef0d533e770284e51369d94ae241a5fb2f163893071b2b4c118aeaf9eae", "4fd8dd01012bb4df82bf42e0683f998e6f52dd9c5617bae33f867d6c0b69798cead8179346d70acc941abbbdd26e3229d5651361d2252c72ff22db2938d06ff6fc29a42fdf800ae967d06479bc7bbb8e71f40b1190a4b7189ffc9a7096cdb76d40aec424e1388e1eb7ef4ac3b34f3f089da8fda7d1927f5d775c0b2801d22dd1265c973158f640cec93edfed06dc80b20ef8c496b98289d54d46ccd205951cbb0f4e7daeb866b60bacb483411e4382b6f04d472843186bd0e31fbaa93e5c901ec028efafeb45fc551a", "e9ee1b22b04b321a5fdd8301627011f583887d77560fb0f35552e207561f81e38ac58a0d0aeaf832d1ee72d913720d01f75574e9a321864fe95f4d0d8f0b8db97649a53e71e940aede5c40b4b9105daa42a6fb2811b61209247534cbaf830b07abe338d75d2f5f4eb1c3cf151e9edabe2c8d5f6fff08fac1495ef48160b100d30dcb0676700bcceb28723a29980ab0766a93abb8cb3d1963007db8458ed99b689d2a7c28c788743c80e8c1239b20982c81dadd0eed6740c65fbc4ef15c7b5569cb9fc997c6550a34b3b2", "ec01e3a60964360f7f23ab0b22e021815765ad706f242265ebc19a2bb9e4eac94393952dcf61aae47682671a10f9165f0b20adf83a6706bfbdcf04c6faba6114653a35584267267873291c6fe7ff5f7695243143421509502c8875aafa9e9afe5be5ef2c851c7f35d69be5d3896000ccdbbfab5c238bb34d607cfe2d55d748880545b4aa7ca61137992925189025c62654b1f20d49c3ccd75aa73ce99cd7258dabedd6480a9f5185531fc0118beb68cc0a9cd182f6973287cf9252e12be5b619f15c25b65c71b7a316ebfd", "db51a2f84704b78414093aa93708ec5e78573595c6e3a16c9e15744fa0f98ec78a1b3ed1e16f9717c01f6cab1bff0d56367ffc516c2e33261074935e0735ccf0d018744b4d28450f9a4db0dcf7ff504d3183aa967f76a507357948da9018fc38f150db53e2df6cea14466f03792f8bc11bdb5266dd6d508cde9e12ff04305c0295de29de19d491ad86e766774bb517e7e65befb1c5e2c267f013e235d8483e177214f89978b4cdc81aa7eff8b39f2825ad3a1b6ac1424e30edd49b067d770f16e74dd7a9c3af2ad74289a676", "00e40f30ae3746edad0f5dd03d0e640933cf3d1694804c1e1ed6399ac36611d405196ee48f129344a8512feda16a354517871322bd5d9c6a1b592933eab531923efb393ffb23d9109cbe1075cebfa5fb917b40df028a621460ff6783c798792cb1d9635b5a6f84ec13918fa302924649b5c7fcb1f7007f0d2f06e9cfd7c27491e565a96c68a0c3644f92cd8f38857258c33801c5d537a83dfe583cba59d7eec7e394199c0a2660a62fabe3ed2099d57f315a6cd8de1a4ade29d977f15d65759cff433e5ac0c182aef3761163e1", "3c5ea24d0d9b618294a263f062b2414a722be4eb10dfc346a6ec3b821d7396eba61cd6ef33618b04cd087a811f299d4606820227f16000d7c839062b96d3e3f59cd1a082448d13fc8f56b3fa7fb5f66d0350aa3b72dd7c165d590282f7da2e12cfe9e60e1796122bb8c2d40fdc2997af634b9c6b127a893dfb3467909378300db3da911be1d7b616bb8e0572433e65527e15d936500a2c60e9f9909dcf22ab5e4b6700f0238c205b4a813626fac3d945bab2637fb08203044a73d20c9a3fcf7c3fc4eb7807c3276dd5f73ce89597", "9271aeeebfac46f4de85df78f1bfd36136aa8905e15835c9e1941176f71e3aa5b1b131843d40479735e23e182a2bd71f66f6149dccb7ed8c16469079dc8590bbf165374951785f4531f7e7361de62f936cfb23a2b5bdf186632e7042a0dd451fdc9b7208f923f3a5f250ae590ec348c63a16c3aacaf7379f53b5dd4152dcd40d23e683e2156e64c592ffc07e2cd6bbeebef4dd590b2f6b2bcbf08fcd111c079f5c4033adb6c17574f8756ecd87be27eff1d7c8e8d0324438d59ae171d5a17128fbcb5533d921bd044a2038a5046b33", "4e3e533d5bcb15793d1b9d0468aaee801f32fdb486b11027183553a09ddbee8213924296f2815dc61577297459e834bf1c7a53f87d43782209e589b8295219ba7073a8fff18ad647fdb474fa39e1faa69911bf83438d5f64fe52f38ce6a991f25812c8f548de7bf2fdea7e9b4782beb4011d3567184c817521a2ba0ebad75b892f7f8e35d68b099827a1b08a84ec5e8125651d6f260295684d0ab1011a9209d2bdeb75128bf5364774d7df91e0746b7b08bda9185035f4f226e7d0a1946fcaa9c607a66b185d8546aac2800e85b74e67", "b5d89fa2d94531093365d1259cc6fe8827fea48e6374c8b9a8c4d2209c280fa5c44958a1847222a692a59e6aa2696e6cdc8a543dd89b0ce03bc293b4e78d6ef48e1839694ccd5c65661143095c705b07e3ced84a0f5959114dd89deb956ab3fac8130eb4a878278205b801ae41a29e34146192308c4e759b374757b0c3b00319bce92a1b95a4d2ee179fd6714ff96155d26f693a5bc973f84ac8b3b91e3926276297532d98b46992a3f104c08100bf1671c43134bac280c617da711e90a0100137525375ebb12802a428885ae7fce6514a", "40e3d8048fc10650cb8a7fc2e7113e26dec34f9ca2d5129cd10a8e8e44d113d61ee48c7d003e19fd307fc6debd70feb30243f298c510ccc4418355ce143066f067ad7c6de7288c3080e7ad46a23c8d34deb55a43e652fe90444ad3c57d3ec1e1c489d63ef915a24bc74a7925a0a7b1e1523f21ca8fee78df24e3d0a68d0013423db97c280799a0618229c0f2c167289a891e5c8d6661ab21285951c31710e3b5fe55f6347fe16d9b40507948a59252efeb616df83e5c098b07d0a7247cd371daff0e50491c582503fd89f79ba94d6af9ed76", "1fa444de01dd3901e2b4684e3d7a799ffa02d85afd35fb30fe4c9d672837bee6dd8a3b8608b4bb5e589220ad5a854f46b46e41c6d57ad124a46beab4169ff69fee7e3838a6165e19dad8eb5d7bf53d4edd3cd2769daf219510a02fdd2afe0c0e1da3cd30fcd1aa88b68965586f07a25a1720fbd90a096ea30fc8e945e3637d7857c8a9c0ab4154ffb2000e57b5f9adfa4e4eaf8065bc3c2b2e75f495963325588785a6ce417dcddffd299873b15dcccca128d63cd4eeeadb64cda28099a9ad7c80d34844901f26b88b00b9aafeb2f90286d29d", "fde0a0d9d813983bd1f55cf778a003a2023b34a555322ab280584537bc6bdd844d22a7d6066c18da83ec09f3d8d5a1aab4be0d5ce19b436052f6e259a4b49017a1f47f1fe2bf115d5bc8599fb216351c60dd6b1bedb2e6f4dcadf424b833501b6f099cbfad9e2290680fb69c25032b42a6274f7cb9b5c5950401354838a45f7cb77b95bf54718e2f3d3d9fb91eb2311903980277396398d9736d8e92fd838594ac8a537c6c529db5a8a4f89290e6ba6f20ac0e5ed6fef40901d0e0e8e3e502990811f9acaae555dd54eb1bcd96b513e2fe751bec", "9f8e0caec87858599f5ab29bff86da78a841a918a023a111098687ecdf2747612d3f3809d9ca400b878bd4f92c43a1004f1c17c7f19a3cd1ce449bd2b23aff551623c37dd8c0be56bf3fd857b500c2b9f9ccea62481944090a3cf3b6ee81d9af8eeb60f65ef150f9fa4d3ed6ce4762d3d4f174ee8ccd460c25cafac0ea5ec8a6a4b2f9e8c0520cb7061155e532cb65f188b01e4b9086db951f504b060c296b326b3fc1c590498ecce594f828f4a10ea416675720ae505295d38a791bd0e93f428448a8f4c1fc0af53604a9e8255384d29ae5c334e2", "33d1e683a4c97ee6bbaa5f9df1a88cb53b7f3c157b6045d70a56fda0ccbd3a1fa1f049cd564da072b53f415bf5fb843771c1d2551fd075d33377362b2f7c0645f9723123d11975991db8a2b518f02e2c7c30342a044754290bae2c77496d755e5981f12e6b0a0174280b958bf11ed628a9062775993ced04bf752ea8d165e3ac2177d7cd1b9371c44efa98f0b3e68602a839d384eec007979f46429dafb138cbc231ad928a9f65f7d66fac77416395e8f1debaaf76ec2e4e03e8674102cd26f614739f3ec9f949033df1fb97e87c2326d65aef94ed5f", "180048f09d0b480887af7fd548a85abf605440c1ddde6afe4c30c30670233f7bf928f43b4681f59279ebbda5e8f8f2a1abefdee129e18ac60f9224e90b38b0aabd01308e0a27f41b6fb2ee07ee176ec9048c5fe33c3f7c791469c81f30e28170585b9f3e7e3c8c2e9d74370cb4518f13bf2dee048cbd98ffa32d85e43bcc64a626b40efb51ce712925fdd6fee006dc68b88004a81549d2121986dd1966084cd654a7c6686b3bae32afbd9625e09344e85cf9611ea08dfce835a2e5b3726e69ae8a76a97db60fcc539944ba4b1e8449e4d9802ae99fae86", "13c0bc2f5eb887cd90eae426143764cf82b3545998c386007cca871890912217aa143ac4ed4ddb5a7495b704aa4de18419b8664b15bc26cfc6596a4d2ae408f98b47a566476d5802d594ba84c2f538def9d016661f6404bb2337a3932a24f6e30073a6c9c274b940c62c727242e24466084a3ea336365d71ea8fa6499c0ea8d59eea505f1126b99c795023c4963aa0d99323d0391e8701110edf551b2d3799e1063ca443f1add162156e445502ca1a052fe70c289838593b58839fc63de128a03e2bbf389e22ae0cf957fd03315ee407b096cc1cfd92dee6", "6f1eb607d679efef065df08987a1174aab41bdac8aece7726dfa65805d6fff5b3d17a672d96b770dc32165f144f0f7324822a5c87563b7cd9e37a742ae83ef245d09006d91576f435a03476f509ea2936636232f66aa7f6cdf1ac187bbd1fcb8e20f8791866e60ed96c73374c12ac16795e999b891c64507d2dbd97e5fc29fac750ad27f2937cbcd29fdafccf27ab22453834d475f6186eaf975a36fad5c8bd61c21da554e1ded46c4c39765dcf5c8f5ccfb49b6a4dc562c919d0c7d8940ec536ab2448ec3c9a9c8b0e8fd4870cad9de2577c7b0c38563f355", "dcdd993c94d3acbc555f464871a32c5da6f13b3d5bbc3e34429705e8ad2e76393fdd96a69a94acb652f5dc3c120d41187e9aa919669f727c4868013b0cb6acc165c1b7706c52248e15c3bf81eb6c147619467945c7c48fa14a73e7c3d5bec91706c567145342a026c9d97eff97ec672c5debb9df1a998083b0b0081d65c517b3e5634c95e347e781aa30ca1c8af815e2e494d844e847fdcb41622894a518dc36571123a40bfdbe8c4f4cff44d83c61dd9dcd24c464c53b395edb31efee9f3aa080e87cdc3d22d613ae84a53c9249c32c96f9a3bc4629bb126a70", "49971f9823e63c3a72574d977953329e813b22a8387cd13f56d8ea77a5d1a8a20012632d1d8732bbcb9f756b9675aab5db927beacab7ca263e5718b8dfa7b2eed9a91bf5ed163b16139d45f7b8cc7e3f7bdda6202106f67dfb23b7c315ee3e17a09d466b1e6b13e7c7428184a979f5358667b4fa8bd40bcc8ea46058db44587a85377ac46bf155136c09ac58cb6c27f28e17028c91e7e8f74d5b500e56293b316974f02b9d9ea205d9b6ac4cfb74eb8eb0c944577fd2f41316368307beab3e327bf7dbaa0a4428836ec4e895dea635234abeaf113ceeadac33c7a3", "c57a9cc958cee983599b04fe694f15fb470fcbc53e4bfcc00a27351b12d5d2434444253ad4184e87b81b738922ffd7ff1dc1e54f39c5518b49fb8fe50d63e3935f99e4bd125e8dc0ba8a17fd62de709339a43fabe15cf86d96a54010112170c340cfac4132182eed7301402bc7c8276089dec38488af145cb6222525894658f03501204b7a66aba0be1b557b28a2f652d66f7313ed825ecc4d8596c1be7420d4425b86a1a90a5b7f30d0f24e0d1aae0eb619ca457a71699e44be612a4011c597ee80b94d5507e429d7fc6af22579cd6ad642723b05ef169fade526fb", "0568a672cd1ecbaa947045b712e2ac27995392fbef8f9488f79803cbee561c212287f080eca95adb5ba42739d78e3ba667f06045d87850d3a0499358649caa257ad29f1a9c511e7054db20554d15cbb55ff854afa45cae475c729cea72ede953522031865bc02b95589ed4d9841c552a8cc94904a93ed09ed77222f6c178195056be59bc4e96a815adf534e6b466fb47e262ff79c803c157a21b6e2269c2e0abeb494113cd868d8466e82d4b2f6a28b73645853d96bc9242515d803e33294848d3fe42fdff68da53c03491636beede47ff1399dd3d54a5e914d55d7adf", "3f19f61a4cd085796731ac9f85a75a8bce77031932c31762d87d8b8d07b8bd19ff78d6b7d1bd1e87f3a4f41aad03b6c4d17a6cbc86be55f7c8b88ada047bb04f8d49f1c34bcf81cc0f3389ad01a758fc7eeb0072aa9ad1481992bfdde82e438e75590a4423832dfbe3756e2229ea873bc3606e6d72174cb2163bf40b5d49c81009dab85ecc03e311351bbf96e32c030a2b276a7698cb25bc2c967acb3213161a1fdde7d912cd6a804490f8056c47da1333f6e35c41e749c2c23919cb9af5eec5652e6e072b034fb1682e9aaa194a9c0bd456ea0b008d14dbce37967a7a8e", "705f98f632d99d3651793825c38dc4deda56c59eac539da6a0159c83131cf8ab6f2ee0c3b74111fde351f7aa1a8c500a0cecab17c212d2c58ca09eae608c8eefc922b9902ef8d6832f799ba48c3c28aa702b3242107edeba01daafe424406a3822965056cfe8783455a671e93b1e2eae2321364f1871471c82124df33bc09e1b52882bd7e1c4c7d0b2f3dd4a28c2a002a43246768af0700f9659de99d62167be93177aabf19d678e79e9c726ac510d94e74873eda99620a3961930cd91937c88a06d8153d64fd60da7ca38cf26d1d4f04a0df273f52127c53fdc593f0f8df9", "ea6f8e977c954657b45f25480ff42c36c7a10c77caa26eb1c907062e24fbca5aebc65cacca0de10abea8c78322f08672e13d8ac16996eca1aa17402eaea4c1cc6c800b22dc18cb8d620192d74bac02c07b5cfa61e513c7f28b7e29b9700e0e442720bf4c669d4995da19d19f841d9eb68cc74153592591e3bf059ef616b95305aa453b32fe99a91afb35bd482cf2b7aa42702837a53be3c38883d2963020e347556f841254ec6b85854485fe8c520b05f2ea67a9bf3981555c20991e2bacd4db5b418228b6002d8d41c025cb472bf5443aaa885974a408ea7f2e3f932c600deb", "408190134ed06556811b1af808ab2d986aff152a28de2c41a2207c0ccc18125ac20f48384de89ea7c80cda1da14e60cc1599943646b4c0082bbcda2d9fa55a13e9df2934edf15eb4fd41f25fa3dd706ab6de522ed351b106321e494e7a27d5f7caf44ec6fadf1122d227eefc0f57aefc140d2c63d07dcbfd65790b1099745ed042cfd1548242076b98e616b76ff0d53db5179df8dd62c06a36a8b9e95a671e2a9b9dd3fb187a31ae5828d218ec5851913e0b52e2532bd4bf9e7b349f32de2b6d5d3cdf9f372d49617b6220c93c05962327e99a0480488443349f0fd54c1860f7c8", "5f9e5c6f38573a85010a9d84d33f29c057003b2645e3ea6f72cbc7af95d197ce6a06b13fea81722853e6991791b8b15091cd066f5ed913592ed3d3af5370d39ba22beeb2a582a414b16824b77e194a094c2afdcc09aa73ce36f4943cca5ae32c5017dc398801dd92a47382d9327c9f6cffd38ca4167cd836f7855fc5ff048d8efba378cdde224905a0425e6b1de061fc951c5e624a5153b008ad41160a710b3ff2081748d5e02deb9f841f4fc6cf4a15153dd4fe874fd447482696283e79ee0e6bc8c1c0409baa5ab02c5209c319e3169b2476149c0c6e541c6197ca46e004eef533", "218c6b3508aec69574f2b5039b30b942b72a8349d05f48ff945bbbe5c8957d5a6199492a6bf54bab821c9377e2edfa4c908384664d2c80112d5e805d66e0a551b941021be17dd20bd825bea9a3b6afb1b8c605805b3bda58750f03ea5c953a698494b425d8980c69f34d1c3f6b5866e8717031152a127215c256e08873c21b0f5cc85875d0f7c94601659150c04cd5fe5d381ba29983a2d94fcd3a65a94c53c7279cd000dddd4253d8cff8d7f6ace10247fe3bc30d63ba4bb54f557b3d22a3924369430d71ab37b701e9500bda70b5a643704858beed4726a889b6c9c91584194c68f1", "dac26aa7273fc25d6e044c79fc2bfa46e59892a42bbca59a86826c91e76ab03e4bd9f7c0b5f08d1931d88b36ea77d94f7ba67cd4f1d3086e529427201119096ae066ae6f170940830ed7900de7bb9d66e09788287403a4ecc93c6da975d2fb08e918840a236c15f5d3a8f7375c2eeebbf6f01a6e7f29ca2b8d42df158414c320777433663c59fdcd1f39ca68e3473db721be7ce8c6dba5fddc024f94fedb286b0477581d451313ca8c737484daf60d67f9b2d56d4bcc271f7e9ae958c7f258efbc74d25753e0516f28282461941bf2dcc7dd8c7df6173b89760cefcac07190243ff863fb", "c46e6512e6797cc7a54254a1b26b2de29aa83d6c4b1ea5a2786fbcec388270625b12635eae39e1fba013f8a65219421bca8b52a8ddfd431cda60299bdf160734d5a7450ec79620058522702174ae451b9bfa7c4a455fbbee3e1d048c7d4bac5131018228f137c8e130440c7059b4f15eaa34ce872a851a16ce86f982df78a00be4d564da2003a450ddee9ab43ea876b8b4b65c84f0b39265fd5456417afb5bc54997c986e66fc222f2123ba5e719c4d6b9a177b188277df384f1125821cf19d5248cef0be183ccdc84ac194506f740ed2188b2689ea4c9236a9e9e3a2fff85b6af4e9b49a3", "1ccd4d278d67b65cf2564ecd4de1b55fe07adc80e1f735fe2f08ea53fd3977323689122c29c798957abaff6aba09bdcbf661d77f4dc8913ab1fe2bef38846166e3834785e7105d746484eff8c656af5d8c7854abc1c62b7fadb65521dc6f793d978bda9838eb3800417d32e8a24d8c8cb1d18a5de6ca79d9e1b0ff9aa25e6218fe944cf18666fecc1e31334b390260dbe0997539e1b02f6366b2aea4f4a21efe04f4b97568fcb39e59919d5ebac6543d5d0f48fc66b923c34aac377dc95c20329b837b6ed5e8d9a3d2089cd0d8f025658006ff41cbdaccca618822ca590ab155253f8bc1c7f5", "9875209588395ee3c9fdd793fd48717cc84c8c3ea622b2ccc4a1be4448e6034b7810569855255031f10be5ffd714b05f9ce01972d712d40abf03d4d0ce175813a7a668f761324996093fc2aa5912f7fc2abdadd8775d2b4d9ad492216293381460ed8f6db3d641d1525f4242c348bbfe504c704f215dc461de51b5c75c1aae967936963848f16c673eca5e78dfd47eb19001d52d1bcf96c98956dad5ddf594a5da757e7ca35f2f69803b784e66ac5a58b75c228b8266ec592505e5d1ca87d81225738855f15bc0914677e81593fd409e77d159f8a908f67788de9eb06c5561547aada96c47c535", "40c90e375e366f3756d89091eb3eed9fe0fbfc5638700af4617d358812bac53124a2205dd6756456787d49cd6a35e302479a0992288f47532e4ea7ab62fc5ad5adc690a5d9a446f7e035ad4641bd8dae83946aee3338ec984ccb5cc633e1409f2531eeffe05532a8b0062ba99454c9aeabf8ecb94db195af7032bfebc22912f49d39330add47ff8fa5720612d697f0b602738930e060a1bb214efc5e292224cf34e29deaea6b1b1ff847e94ecc997325ac38df61db45d82bf0e74a664d2fe085c20b04c39e90d6a170b68d2f1d373f00c731c524456ada73d659aaac9df3191a7a3865083343fc13", "e8800d82e072210ca6d7fa2472028974780b76aad4bcb9ad362422dd05ae3232668251d164daa375a43b26a38cce28dbeb3dee1a4a579f70d0fe7febb29b5ece8aa836e050fb3d188c63aa9c3c0da6c717d86458a6096b5effceb964efdec7035960c09ccd10dea3c5f1c7f9f478d5887ebbe2e15c5ff85dbacbc444bb951c4eec7abecb89ed80187e409e2972ffe1a5f01562af109f2cf09471cf72cf83a3bb8f4e2ef38ed0e326b698296394e5b2718a5000c01425708e8ad0461e62462d8819c2377f13ab1be2c7c9f33dc06fe23cad27b87569f2ce2e56e4b2c60c7b1b3d370841d89ebdc1f192", "796d6d1447d5b7e8c55cd8b2f8b7010db39f27565f907e3fc0e464ea2d4bb52b37f10e7c6dcfc59231b9cdee12c32aeb4adbc42b86e86eb6defb5b69e6ca75e1f4d0dae3e124e5a1b8b6697f7e10b0403f1f0a5ff848eef3752837a9ba17780f16a9a709188a8d5b89a2fa74adb2e651163b1c2b3d261e225c9158dcd9eb7ac3d6704cee290cdff6bcb3cb90cee030aa0d19d4693655c3c30ac6fc06d2ae37787c47126d57ed9a6bef5f8a6c56859aefc08755739a95aac57a4dd916a92ba9f3afbf969df8085949615033365c751a9a3e1a18cee98a69d22e64009bebf8307169b6c61de0617ecfafdf", "4f9057183566153cf337b07c3f5556006de54c56b2a1e5326c07aaeabd1886ec6f1641358925db232b2f0dbf75229c796a7395b2f934c1f99090bec1123f3c841b1cb3c5b1ec42ed5408f2940f0c48a9470b852c46d6557853d459cecd2c32bbcd8ee21fa11e385eef0857cba4d8545a61b52a484cdd779db4739fbc7aa9860dcabe0488b98fa0b60c3f7d6153db279000a52ffb573dab37d2ab1896a90e5deb7ac6bbe56239085c325d83a917dc6e8a448425b718c2356b9f3066163555ec444f372e184e02c8c4c69b1c1c2ae2b51e45b98f73d933d18750968945ca85d6bbb22014b4c4015262e3c40d", "79dcca7d8b81a61359e4aece21f3df7b99518ce70bd2f57a18bab5e7114af2add0a0cea7f319d69f231f060e0a539d9a23fb3e95451ce8c6340cfb09edf931df84203a39226dd9eb278f11b691ef612585b973daab373e65d11325898badf6732100371fd759960fa8fec373268421d28bffdb9b12a430b92fe4b07566ca0c89e616e49f8fc75ccd9cdc66db820d7c02e109aa5ed86b89770262918a518f90a2292f6b68d68ae03992e4259a17a23c84ec2a417f082b5abf3a26e44d2278ecb8ba9456965303a75f25394d1aaf5544590e74b14d8a4cc4050be2b0ebcfe4d2db6b12a02c68a3bcdda70301f3", "848755dc31e25e9a42f9ec12d847d19f292c14c162c9aba49e972cb123b58b8e57bb263a923929833373858594ff52dbc298dbbc078599194e4c07b0e5fc1e10808bbacdb6e93c72b333685cf961f28eb0d5a395c63266b01f130d25db384b356e5da6d01042fc2359581b89c63b3bb2d1ce897fbc9e83fe85d9666cb60e6a8c657f70caad5387b8a045bf91095606802c8424ea8ac52ef29386dc46183378a5fcb2cb927428b8c070f1c42aafd3bc70ca25437807696a46873cfeb7b80ba2ebc3c4272443d445e46343a1465253a9eebd532a0d1d2c18264b91ff45159f245404ae9335f2af55c802772426b4", "ecaa6e999ef355a0768730edb835db411829a3764f79d764bb5682af6d00f51b313e017b83fffe2e332cd4a3de0a81d6a52084d5748346a1f81eb9b183ff6d93d05edc00e938d001c90872dfe234e8dd085f639af168af4a07e18f1c56ca6c7c1addffc4a70eb4660666dda0321636c3f83479ad3b64e23d749620413a2ecdcc52ad4e6e63f2b817ce99c15b5d2da3792721d7158297cce65e0c04fe810d7e2434b969e4c7892b3840623e153576356e9a696fd9e7a801c25de621a7849da3f99158d3d09bf039f43c510c8ffb00fa3e9a3c12d2c8062dd25b8dabe53d8581e30427e81c3dfc2d455352487e1255", "23a3fe80e3636313fdf922a1359514d9f31775e1adf24285e8001c04dbce866df055edf25b506e18953492a173ba5aa0c1ec758123406a97025ba9b6b7a97eb14734424d1a7841ec0eaeba0051d6e9734263bea1af9895a3b8c83d8c854da2ae7832bdd7c285b73f8113c3821cced38b3656b4e6369a9f8327cd368f04128f1d78b6b4260f55995277feffa15e34532cd0306c1f47354667c17018ee012a791af2dbbc7afc92c388008c601740cccbbe66f1eb06ea657e9d478066c2bd2093ab62cd94abadc002722f50968e8acf361658fc64f50685a5b1b004888b3b4f64a4ddb67bec7e4ac64c9ee8deeda896b9", "758f3567cd992228386a1c01930f7c52a9dcce28fdc1aaa54b0fed97d9a54f1df805f31bac12d559e90a2063cd7df8311a148f6904f78c5440f75e49877c0c0855d59c7f7ee52837e6ef3e54a568a7b38a0d5b896e298c8e46a56d24d8cabda8aeff85a622a3e7c87483ba921f34156defd185f608e2241224286e38121a162c2ba7604f68484717196f6628861a948180e8f06c6cc1ec66d032cf8d16da039cd74277cde31e535bc1692a44046e16881c954af3cd91dc49b443a3680e4bc42a954a46ebd1368b1398edd7580f935514b15c7fbfa9b40048a35122283af731f5e460aa85b66e65f49a9d158699bd2870", "fe511e86971cea2b6af91b2afa898d9b067fa71780790bb409189f5debe719f405e16acf7c4306a6e6ac5cd535290efe088943b9e6c5d25bfc508023c1b105d20d57252fee8cdbddb4d34a6ec2f72e8d55be55afcafd2e922ab8c31888bec4e816d04f0b2cd23df6e04720969c5152b3563c6da37e4608554cc7b8715bc10aba6a2e3b6fbcd35408df0dd73a9076bfad32b741fcdb0edfb563b3f753508b9b26f0a91673255f9bcda2b9a120f6bfa0632b6551ca517d846a747b66ebda1b2170891ece94c19ce8bf682cc94afdf0053fba4e4f0530935c07cdd6f879c999a8c4328ef6d3e0a37974a230ada83910604337", "a6024f5b959698c0de45f4f29e1803f99dc8112989c536e5a1337e281bc856ff721e986de183d7b0ea9eb61166830ae5d6d6bc857dc833ff189b52889b8e2bd3f35b4937624d9b36dc5f19db44f0772508029784c7dac9568d28609058bc437e2f79f95b12307d8a8fb042d7fd6ee910a9e8df609ede3283f958ba918a9925a0b1d0f9f9f232062315f28a52cbd60e71c09d83e0f6600f508f0ae8ad7642c080ffc618fcd2314e26f67f1529342569f6df37017f7e3b2dac32ad88d56d175ab22205ee7e3ee94720d76933a21132e110fefbb0689a3adbaa4c685f43652136d09b3a359b5c671e38f11915cb5612db2ae294", "af6de0e227bd78494acb559ddf34d8a7d55a03912384831be21c38376f39cda8a864aff7a48aed758f6bdf777779a669068a75ce82a06f6b3325c855ed83daf5513a078a61f7dc6c1622a633367e5f3a33e765c8ec5d8d54f48494006fdbf8922063e5340013e312871b7f8f8e5ea439c0d4cb78e2f19dd11f010729b692c65dd0d347f0ce53de9d849224666ea2f6487f1c6f953e8f9dbfd3d6de291c3e9d045e633cfd83c89d2f2327d0b2f31f72ac1604a3db1febc5f22cad08153278047210cc2894582c251a014c652e3951593e70e52a5d7451be8924b64f85c8247dab6268d24710b39fc1c07b4ac829fbda34ed79b5", "d7314e8b1ff82100b8f5870da62b61c31ab37ace9e6a7b6f7d294571523783c1fdedcbc00dd487dd6f848c34aab493507d07071b5eb59d1a2346068c7f356755fbde3d2cab67514f8c3a12d6ff9f96a977a9ac9263491bd33122a904da5386b943d35a6ba383932df07f259b6b45f69e9b27b4ca124fb3ae143d709853eed86690bc2754d5f8865c355a44b5279d8eb31cdc00f7407fb5f5b34edc57fc7ace943565da2222dc80632ccf42f2f125ceb19714ea964c2e50603c9f8960c3f27c2ed0e18a559931c4352bd7422109a28c5e145003f55c9b7c664fdc985168868950396eaf6fefc7b73d815c1aca721d7c67da632925", "2928b55c0e4d0f5cb4b60af59e9a702e3d616a8cf427c8bb03981fb8c29026d8f7d89161f36c11654f9a5e8ccb703595a58d671ecdc22c6a784abe363158682be4643002a7da5c9d268a30ea9a8d4cc24f562ab59f55c2b43af7dbcecc7e5ebe7494e82d74145a1e7d442125eb0431c5ea0939b27afa47f8ca97849f341f707660c7fbe49b7a0712fbcb6f7562ae2961425f27c7779c7534ecdeb8047ff3cb89a25159f3e1cefe42f9ef16426241f2c4d62c11d7ac43c4500dfcd184436bb4ef33260366f875230f26d81613c334dbda4736ba9d1d2966502914ec01bbe72d885606ec11da7a2cb01b29d35eebedbb0ecc73ed6c35", "fd993f50e8a68c7b2c7f87511ce65b93c0aa94dcbdf2c9cca93816f0f3b2ab34c62c586fc507b4900a34cf9d0517e0fe10a89d154c5419c1f5e38de00e8834fe3dc1032abdeb10729a81655a69a12856a78ca6e12110580de879b086fd6608726541cfa9616326bdd36064bc0d1e5f9c93b41278bff6a13b2494b81e238c0c45aea1b07d855e8f3fe1478e373bd9d3957cf8a5e5b9003386793d994c7c575cff2322e2428cbbaa4f47560316ae3354a7478842ff7cc5dcbacb6e871e72b36f06d63a9aaeb9044cfb7974afdc238a5816f537dcf33ee40b4e1a5eb3cff2402b46d548264e133008d284f11b7e4e450bc3c5ff9f79b9c4", "8df21892f5fc303b0de4adef1970186db6fe71bb3ea3094922e13afcfabf1d0be009f36d6f6310c5f9fda51f1a946507a055b645c296370440e5e83d8e906a2fb51f2b42de8856a81a4f28a73a8825c68ea08e5e366730bce8047011cb7d6d9be8c6f4211308fad21856284d5bc47d199988e0abf5badf8693ceeed0a2d98e8ae94b7775a42925edb1f697ffbd8e806af23145054a85e071819cca4cd48875290ca65e5ee72a9a54ff9f19c10ef4adaf8d04c9a9afcc73853fc128bbebc61f78702787c966ca6e1b1a0e4dab646acdfcd3c6bf3e5cfbec5ebe3e06c8abaa1de56e48421d87c46b5c78030afcafd91f27e7d7c85eb4872b", "48ec6ec520f8e593d7b3f653eb15553de246723b81a6d0c3221aaa42a37420fba98a23796338dff5f845dce6d5a449be5ecc1887356619270461087e08d05fb60433a83d7bd00c002b09ea210b428965124b9b27d9105a71c826c1a2491cfd60e4cfa86c2da0c7100a8dc1c3f2f94b280d54e01e043acf0e966200d9fa8a41daf3b9382820786c75cadbb8841a1b2be5b6cbeb64878e4a231ae063a99b4e2308960ef0c8e2a16bb3545cc43bdf171493fb89a84f47e7973dc60cf75aeeca71e0a7ebe17d161d4fb9fe009941cc438f16a5bae6c99fcad08cac486eb2a48060b023d8730bf1d82fe60a2f036e6f52a5bff95f43bbe088933f", "f4d84ed3e564c102600a795eaa9b1eaf4ad12f1a4deca1d042a0a2750ddf6201db03073d8bf553cb9dde48a1b0083827a609f7242b86584cc180964ae794b12ce55661e00e36a6ba4dbc389e6a5a85f1b45df9af7ead1b0a54db56e68639b9d438a91504e82c35d40c7bc7e048a53ac0b04accd0dadf4ac9884b0ca0e3cb5ba4336e3581be4c4760a553823ffa283a1120d4e145af56a59f2533903650f0b9e9ad9fe2e8a3c3c3dd03a1fcb709032c8835324839c735b0c051d0cbd8b5d867617c11023432e4bd275d3d0eb98a0b6cf58071a5b712922f2bc751ac7c2588c447444cde2f37a8ea5ec126425bf517e0d17c9e2999f52fee14b3", "2ccea21bac9c2b70d3923309cbf2d7cb7abd1fcc8b8b002688870a80029c62397350c3c898194e5deea360bb963d26d485cb7963f8167586976ec0556950b2e86135f4a2800991ce8473bfd44a3c5e937a48b5e355ba5141bccf2131a83988d9d2a9e8e7635a956105b3512c05ef708139ced51d7a4e204c12d8a49a21e8dc6de2629a2fd092326885d9f218745fe09f6d91fb6afce250a30a63689534b6be1f26899ffa3767d835cf586aa47776700f94241bc999b1e3deefe188f37ff734f5f16ee6a00914323dc7b8a143c9137cdcc5cd08ae9566f04bb2941532674c97dff6ffa5ce3405ef8e5d27ec403114253dd6394c0167d72a0044c5", "2b681c6398aee63bf862770341648bbcd31d7de7903c5903fe3d9469311320bb24d914f2af0cdca199c97214c7c679dc32a2800ba484a03c010ea6be3bb9f2c87e30a98b606050b8a3f297f12b8f92caaeceb3e844652115934874e0a1ab093a73d759b53f6a6c3096940dd22c2bb96ce6820a7b9c6d71a208de9892aa6a7209b0fff56a0cafea52b952cdd6f5752cff3309d448800b4e4c878aa595595b56b12b83fcd6ca89520c7da664e449d7b4438fc455888aad5de0fad9a06eed14afd3513b5ebbffe01775549b701181bd26370764f56eba52fdb24286ad1ac0f5418a7c429f7dfc7f3168437fa8eed7a2ed7c723a485e4c3ed14dea2e07", "aadfd505a89f4aade2c3018258a7e039401b1fc6a7f3d87910dddbb880d372ec8a13c70d92245de5b8e5f9a285c33b99dc82fa2b22decee72b93a72211656ad7a52696c8e570f78be28c0e427a371dafde856e8d5ed24f83b0660b51e7fac05d93a8666dfde6def59af863f80f3e5f6801182c87422203df390dcb736b8f830052a8832eeeb0b4e27e732aaf793d166b5a3ec7745aeef3766937c2b75a276bddd145f6010c29d035e343e267cb2d828436876ec3a7ebe3b6347d4172f7a99d6821ce152e039e53deb33340b324c7f068ffb94b3cde35a8eaa12d15c3806a7ad0acec3e8c7078c1d32a28fd3eec9f32cb86e4c22166ff69e83785e851", "1605b8cce529a9d6262fd4390d9e4ae5e14e0adc0ec89b028ef68dd0f373ea259aaa96f2967091dd0874c0105385e9e6da9ca68297c31afa44ef834535fb302ce5b4e49edacbbdf359fe1228a8172495b3e57014c27edd58b685110980056c50c398a64f4923f2d720b4df16d75cb36b4233660694182099c35028a972519c24764fc94e18e582b24deb3491535fc06b83837c7958522800e822201d694af0bd0aa3834e17d4b1ba36f470905ae5f8bbeeb6c4c8604d8af02baa347b07086d6989867ddd5e8e8ed7740c3469bfa2810519c55c6add1332c4c54ee9097961d6741cb12a09713a0d07645f784f42f5ad94b48b836b34263130b0483f15e3", "ff9c6125b2f60bfd6c2427b279df070e430075096647599bdc68c531152c58e13858b82385d78c856092d6c74106e87ccf51ac7e673936332d9b223444eaa0e762ee258d8a733d3a515ec68ed73285e5ca183ae3278b4820b0ab2797feb1e7d8cc864df585dfb5ebe02a993325a9ad5e2d7d49d3132cf66013898351d044e0fe908ccdfeeebf651983601e3673a1f92d36510c0cc19b2e75856db8e4a41f92a51efa66d6cc22e414944c2c34a5a89ccde0be76f51410824e330d8e7c613194338c93732e8aea651fca18bcf1ac1824340c5553aff1e58d4ab8d7c8842b4712021e517cd6c140f6743c69c7bee05b10a8f24050a8caa4f96d1664909c5a06", "6e85c2f8e1fdc3aaeb969da1258cb504bbf0070cd03d23b3fb5ee08feea5ee2e0ee1c71a5d0f4f701b351f4e4b4d74cb1e2ae6184814f77b62d2f08134b7236ebf6b67d8a6c9f01b4248b30667c555f5d8646dbfe291151b23c9c9857e33a4d5c847be29a5ee7b402e03bac02d1a4319acc0dd8f25e9c7a266f5e5c896cc11b5b238df96a0963ae806cb277abc515c298a3e61a3036b177acf87a56ca4478c4c6d0d468913de602ec891318bbaf52c97a77c35c5b7d164816cf24e4c4b0b5f45853882f716d61eb947a45ce2efa78f1c70a918512af1ad536cbe6148083385b34e207f5f690d7a954021e4b5f4258a385fd8a87809a481f34202af4caccb82", "1e9b2c454e9de3a2d723d850331037dbf54133dbe27488ff757dd255833a27d8eb8a128ad12d0978b6884e25737086a704fb289aaaccf930d5b582ab4df1f55f0c429b6875edec3fe45464fa74164be056a55e243c4222c586bec5b18f39036aa903d98180f24f83d09a454dfa1e03a60e6a3ba4613e99c35f874d790174ee48a557f4f021ade4d1b278d7997ef094569b37b3db0505951e9ee8400adaea275c6db51b325ee730c69df97745b556ae41cd98741e28aa3a49544541eeb3da1b1e8fa4e8e9100d66dd0c7f5e2c271b1ecc077de79c462b9fe4c273543ecd82a5bea63c5acc01eca5fb780c7d7c8c9fe208ae8bd50cad1769693d92c6c8649d20d8", } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2b_ref.go��������������������������������������0000644�0610621�0607500�00000000506�13172163317�025042� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !amd64 appengine gccgo package blake2b func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { hashBlocksGeneric(h, c, flag, blocks) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2b_generic.go����������������������������������0000644�0610621�0607500�00000007541�13172163317�025710� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package blake2b import "encoding/binary" // the precomputed values for BLAKE2b // there are 12 16-byte arrays - one for each round // the entries are calculated from the sigma constants. var precomputed = [12][16]byte{ {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, {11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4}, {7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8}, {9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13}, {2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9}, {12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11}, {13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10}, {6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5}, {10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0}, {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, // equal to the first {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, // equal to the second } func hashBlocksGeneric(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { var m [16]uint64 c0, c1 := c[0], c[1] for i := 0; i < len(blocks); { c0 += BlockSize if c0 < BlockSize { c1++ } v0, v1, v2, v3, v4, v5, v6, v7 := h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7] v8, v9, v10, v11, v12, v13, v14, v15 := iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7] v12 ^= c0 v13 ^= c1 v14 ^= flag for j := range m { m[j] = binary.LittleEndian.Uint64(blocks[i:]) i += 8 } for j := range precomputed { s := &(precomputed[j]) v0 += m[s[0]] v0 += v4 v12 ^= v0 v12 = v12<<(64-32) | v12>>32 v8 += v12 v4 ^= v8 v4 = v4<<(64-24) | v4>>24 v1 += m[s[1]] v1 += v5 v13 ^= v1 v13 = v13<<(64-32) | v13>>32 v9 += v13 v5 ^= v9 v5 = v5<<(64-24) | v5>>24 v2 += m[s[2]] v2 += v6 v14 ^= v2 v14 = v14<<(64-32) | v14>>32 v10 += v14 v6 ^= v10 v6 = v6<<(64-24) | v6>>24 v3 += m[s[3]] v3 += v7 v15 ^= v3 v15 = v15<<(64-32) | v15>>32 v11 += v15 v7 ^= v11 v7 = v7<<(64-24) | v7>>24 v0 += m[s[4]] v0 += v4 v12 ^= v0 v12 = v12<<(64-16) | v12>>16 v8 += v12 v4 ^= v8 v4 = v4<<(64-63) | v4>>63 v1 += m[s[5]] v1 += v5 v13 ^= v1 v13 = v13<<(64-16) | v13>>16 v9 += v13 v5 ^= v9 v5 = v5<<(64-63) | v5>>63 v2 += m[s[6]] v2 += v6 v14 ^= v2 v14 = v14<<(64-16) | v14>>16 v10 += v14 v6 ^= v10 v6 = v6<<(64-63) | v6>>63 v3 += m[s[7]] v3 += v7 v15 ^= v3 v15 = v15<<(64-16) | v15>>16 v11 += v15 v7 ^= v11 v7 = v7<<(64-63) | v7>>63 v0 += m[s[8]] v0 += v5 v15 ^= v0 v15 = v15<<(64-32) | v15>>32 v10 += v15 v5 ^= v10 v5 = v5<<(64-24) | v5>>24 v1 += m[s[9]] v1 += v6 v12 ^= v1 v12 = v12<<(64-32) | v12>>32 v11 += v12 v6 ^= v11 v6 = v6<<(64-24) | v6>>24 v2 += m[s[10]] v2 += v7 v13 ^= v2 v13 = v13<<(64-32) | v13>>32 v8 += v13 v7 ^= v8 v7 = v7<<(64-24) | v7>>24 v3 += m[s[11]] v3 += v4 v14 ^= v3 v14 = v14<<(64-32) | v14>>32 v9 += v14 v4 ^= v9 v4 = v4<<(64-24) | v4>>24 v0 += m[s[12]] v0 += v5 v15 ^= v0 v15 = v15<<(64-16) | v15>>16 v10 += v15 v5 ^= v10 v5 = v5<<(64-63) | v5>>63 v1 += m[s[13]] v1 += v6 v12 ^= v1 v12 = v12<<(64-16) | v12>>16 v11 += v12 v6 ^= v11 v6 = v6<<(64-63) | v6>>63 v2 += m[s[14]] v2 += v7 v13 ^= v2 v13 = v13<<(64-16) | v13>>16 v8 += v13 v7 ^= v8 v7 = v7<<(64-63) | v7>>63 v3 += m[s[15]] v3 += v4 v14 ^= v3 v14 = v14<<(64-16) | v14>>16 v9 += v14 v4 ^= v9 v4 = v4<<(64-63) | v4>>63 } h[0] ^= v0 ^ v8 h[1] ^= v1 ^ v9 h[2] ^= v2 ^ v10 h[3] ^= v3 ^ v11 h[4] ^= v4 ^ v12 h[5] ^= v5 ^ v13 h[6] ^= v6 ^ v14 h[7] ^= v7 ^ v15 } c[0], c[1] = c0, c1 } ���������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2b_amd64.s�������������������������������������0000644�0610621�0607500�00000021062�13172163317�025036� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,!gccgo,!appengine #include "textflag.h" DATA ·iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 DATA ·iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b GLOBL ·iv0<>(SB), (NOPTR+RODATA), $16 DATA ·iv1<>+0x00(SB)/8, $0x3c6ef372fe94f82b DATA ·iv1<>+0x08(SB)/8, $0xa54ff53a5f1d36f1 GLOBL ·iv1<>(SB), (NOPTR+RODATA), $16 DATA ·iv2<>+0x00(SB)/8, $0x510e527fade682d1 DATA ·iv2<>+0x08(SB)/8, $0x9b05688c2b3e6c1f GLOBL ·iv2<>(SB), (NOPTR+RODATA), $16 DATA ·iv3<>+0x00(SB)/8, $0x1f83d9abfb41bd6b DATA ·iv3<>+0x08(SB)/8, $0x5be0cd19137e2179 GLOBL ·iv3<>(SB), (NOPTR+RODATA), $16 DATA ·c40<>+0x00(SB)/8, $0x0201000706050403 DATA ·c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b GLOBL ·c40<>(SB), (NOPTR+RODATA), $16 DATA ·c48<>+0x00(SB)/8, $0x0100070605040302 DATA ·c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a GLOBL ·c48<>(SB), (NOPTR+RODATA), $16 #define SHUFFLE(v2, v3, v4, v5, v6, v7, t1, t2) \ MOVO v4, t1; \ MOVO v5, v4; \ MOVO t1, v5; \ MOVO v6, t1; \ PUNPCKLQDQ v6, t2; \ PUNPCKHQDQ v7, v6; \ PUNPCKHQDQ t2, v6; \ PUNPCKLQDQ v7, t2; \ MOVO t1, v7; \ MOVO v2, t1; \ PUNPCKHQDQ t2, v7; \ PUNPCKLQDQ v3, t2; \ PUNPCKHQDQ t2, v2; \ PUNPCKLQDQ t1, t2; \ PUNPCKHQDQ t2, v3 #define SHUFFLE_INV(v2, v3, v4, v5, v6, v7, t1, t2) \ MOVO v4, t1; \ MOVO v5, v4; \ MOVO t1, v5; \ MOVO v2, t1; \ PUNPCKLQDQ v2, t2; \ PUNPCKHQDQ v3, v2; \ PUNPCKHQDQ t2, v2; \ PUNPCKLQDQ v3, t2; \ MOVO t1, v3; \ MOVO v6, t1; \ PUNPCKHQDQ t2, v3; \ PUNPCKLQDQ v7, t2; \ PUNPCKHQDQ t2, v6; \ PUNPCKLQDQ t1, t2; \ PUNPCKHQDQ t2, v7 #define HALF_ROUND(v0, v1, v2, v3, v4, v5, v6, v7, m0, m1, m2, m3, t0, c40, c48) \ PADDQ m0, v0; \ PADDQ m1, v1; \ PADDQ v2, v0; \ PADDQ v3, v1; \ PXOR v0, v6; \ PXOR v1, v7; \ PSHUFD $0xB1, v6, v6; \ PSHUFD $0xB1, v7, v7; \ PADDQ v6, v4; \ PADDQ v7, v5; \ PXOR v4, v2; \ PXOR v5, v3; \ PSHUFB c40, v2; \ PSHUFB c40, v3; \ PADDQ m2, v0; \ PADDQ m3, v1; \ PADDQ v2, v0; \ PADDQ v3, v1; \ PXOR v0, v6; \ PXOR v1, v7; \ PSHUFB c48, v6; \ PSHUFB c48, v7; \ PADDQ v6, v4; \ PADDQ v7, v5; \ PXOR v4, v2; \ PXOR v5, v3; \ MOVOU v2, t0; \ PADDQ v2, t0; \ PSRLQ $63, v2; \ PXOR t0, v2; \ MOVOU v3, t0; \ PADDQ v3, t0; \ PSRLQ $63, v3; \ PXOR t0, v3 #define LOAD_MSG(m0, m1, m2, m3, src, i0, i1, i2, i3, i4, i5, i6, i7) \ MOVQ i0*8(src), m0; \ PINSRQ $1, i1*8(src), m0; \ MOVQ i2*8(src), m1; \ PINSRQ $1, i3*8(src), m1; \ MOVQ i4*8(src), m2; \ PINSRQ $1, i5*8(src), m2; \ MOVQ i6*8(src), m3; \ PINSRQ $1, i7*8(src), m3 // func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) TEXT ·hashBlocksSSE4(SB), 4, $288-48 // frame size = 272 + 16 byte alignment MOVQ h+0(FP), AX MOVQ c+8(FP), BX MOVQ flag+16(FP), CX MOVQ blocks_base+24(FP), SI MOVQ blocks_len+32(FP), DI MOVQ SP, BP MOVQ SP, R9 ADDQ $15, R9 ANDQ $~15, R9 MOVQ R9, SP MOVOU ·iv3<>(SB), X0 MOVO X0, 0(SP) XORQ CX, 0(SP) // 0(SP) = ·iv3 ^ (CX || 0) MOVOU ·c40<>(SB), X13 MOVOU ·c48<>(SB), X14 MOVOU 0(AX), X12 MOVOU 16(AX), X15 MOVQ 0(BX), R8 MOVQ 8(BX), R9 loop: ADDQ $128, R8 CMPQ R8, $128 JGE noinc INCQ R9 noinc: MOVQ R8, X8 PINSRQ $1, R9, X8 MOVO X12, X0 MOVO X15, X1 MOVOU 32(AX), X2 MOVOU 48(AX), X3 MOVOU ·iv0<>(SB), X4 MOVOU ·iv1<>(SB), X5 MOVOU ·iv2<>(SB), X6 PXOR X8, X6 MOVO 0(SP), X7 LOAD_MSG(X8, X9, X10, X11, SI, 0, 2, 4, 6, 1, 3, 5, 7) MOVO X8, 16(SP) MOVO X9, 32(SP) MOVO X10, 48(SP) MOVO X11, 64(SP) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 8, 10, 12, 14, 9, 11, 13, 15) MOVO X8, 80(SP) MOVO X9, 96(SP) MOVO X10, 112(SP) MOVO X11, 128(SP) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 14, 4, 9, 13, 10, 8, 15, 6) MOVO X8, 144(SP) MOVO X9, 160(SP) MOVO X10, 176(SP) MOVO X11, 192(SP) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 1, 0, 11, 5, 12, 2, 7, 3) MOVO X8, 208(SP) MOVO X9, 224(SP) MOVO X10, 240(SP) MOVO X11, 256(SP) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 11, 12, 5, 15, 8, 0, 2, 13) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 10, 3, 7, 9, 14, 6, 1, 4) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 7, 3, 13, 11, 9, 1, 12, 14) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 2, 5, 4, 15, 6, 10, 0, 8) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 9, 5, 2, 10, 0, 7, 4, 15) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 14, 11, 6, 3, 1, 12, 8, 13) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 2, 6, 0, 8, 12, 10, 11, 3) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 4, 7, 15, 1, 13, 5, 14, 9) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 12, 1, 14, 4, 5, 15, 13, 10) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 0, 6, 9, 8, 7, 3, 2, 11) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 13, 7, 12, 3, 11, 14, 1, 9) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 5, 15, 8, 2, 0, 4, 6, 10) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 6, 14, 11, 0, 15, 9, 3, 8) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 12, 13, 1, 10, 2, 7, 4, 5) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 10, 8, 7, 1, 2, 4, 6, 5) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) LOAD_MSG(X8, X9, X10, X11, SI, 15, 9, 3, 13, 11, 14, 12, 0) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 16(SP), 32(SP), 48(SP), 64(SP), X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 80(SP), 96(SP), 112(SP), 128(SP), X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 144(SP), 160(SP), 176(SP), 192(SP), X11, X13, X14) SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 208(SP), 224(SP), 240(SP), 256(SP), X11, X13, X14) SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) MOVOU 32(AX), X10 MOVOU 48(AX), X11 PXOR X0, X12 PXOR X1, X15 PXOR X2, X10 PXOR X3, X11 PXOR X4, X12 PXOR X5, X15 PXOR X6, X10 PXOR X7, X11 MOVOU X10, 32(AX) MOVOU X11, 48(AX) LEAQ 128(SI), SI SUBQ $128, DI JNE loop MOVOU X12, 0(AX) MOVOU X15, 16(AX) MOVQ R8, 0(BX) MOVQ R9, 8(BX) MOVQ BP, SP RET // func supportsSSE4() bool TEXT ·supportsSSE4(SB), 4, $0-1 MOVL $1, AX CPUID SHRL $19, CX // Bit 19 indicates SSE4 support ANDL $1, CX // CX != 0 if support SSE4 MOVB CX, ret+0(FP) RET ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2b_amd64.go������������������������������������0000644�0610621�0607500�00000001075�13172163317�025203� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7,amd64,!gccgo,!appengine package blake2b func init() { useSSE4 = supportsSSE4() } //go:noescape func supportsSSE4() bool //go:noescape func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { if useSSE4 { hashBlocksSSE4(h, c, flag, blocks) } else { hashBlocksGeneric(h, c, flag, blocks) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s���������������������������������0000644�0610621�0607500�00000057715�13172163317�025515� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7,amd64,!gccgo,!appengine #include "textflag.h" DATA ·AVX2_iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 DATA ·AVX2_iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b DATA ·AVX2_iv0<>+0x10(SB)/8, $0x3c6ef372fe94f82b DATA ·AVX2_iv0<>+0x18(SB)/8, $0xa54ff53a5f1d36f1 GLOBL ·AVX2_iv0<>(SB), (NOPTR+RODATA), $32 DATA ·AVX2_iv1<>+0x00(SB)/8, $0x510e527fade682d1 DATA ·AVX2_iv1<>+0x08(SB)/8, $0x9b05688c2b3e6c1f DATA ·AVX2_iv1<>+0x10(SB)/8, $0x1f83d9abfb41bd6b DATA ·AVX2_iv1<>+0x18(SB)/8, $0x5be0cd19137e2179 GLOBL ·AVX2_iv1<>(SB), (NOPTR+RODATA), $32 DATA ·AVX2_c40<>+0x00(SB)/8, $0x0201000706050403 DATA ·AVX2_c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b DATA ·AVX2_c40<>+0x10(SB)/8, $0x0201000706050403 DATA ·AVX2_c40<>+0x18(SB)/8, $0x0a09080f0e0d0c0b GLOBL ·AVX2_c40<>(SB), (NOPTR+RODATA), $32 DATA ·AVX2_c48<>+0x00(SB)/8, $0x0100070605040302 DATA ·AVX2_c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a DATA ·AVX2_c48<>+0x10(SB)/8, $0x0100070605040302 DATA ·AVX2_c48<>+0x18(SB)/8, $0x09080f0e0d0c0b0a GLOBL ·AVX2_c48<>(SB), (NOPTR+RODATA), $32 DATA ·AVX_iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 DATA ·AVX_iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b GLOBL ·AVX_iv0<>(SB), (NOPTR+RODATA), $16 DATA ·AVX_iv1<>+0x00(SB)/8, $0x3c6ef372fe94f82b DATA ·AVX_iv1<>+0x08(SB)/8, $0xa54ff53a5f1d36f1 GLOBL ·AVX_iv1<>(SB), (NOPTR+RODATA), $16 DATA ·AVX_iv2<>+0x00(SB)/8, $0x510e527fade682d1 DATA ·AVX_iv2<>+0x08(SB)/8, $0x9b05688c2b3e6c1f GLOBL ·AVX_iv2<>(SB), (NOPTR+RODATA), $16 DATA ·AVX_iv3<>+0x00(SB)/8, $0x1f83d9abfb41bd6b DATA ·AVX_iv3<>+0x08(SB)/8, $0x5be0cd19137e2179 GLOBL ·AVX_iv3<>(SB), (NOPTR+RODATA), $16 DATA ·AVX_c40<>+0x00(SB)/8, $0x0201000706050403 DATA ·AVX_c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b GLOBL ·AVX_c40<>(SB), (NOPTR+RODATA), $16 DATA ·AVX_c48<>+0x00(SB)/8, $0x0100070605040302 DATA ·AVX_c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a GLOBL ·AVX_c48<>(SB), (NOPTR+RODATA), $16 #define VPERMQ_0x39_Y1_Y1 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xc9; BYTE $0x39 #define VPERMQ_0x93_Y1_Y1 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xc9; BYTE $0x93 #define VPERMQ_0x4E_Y2_Y2 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xd2; BYTE $0x4e #define VPERMQ_0x93_Y3_Y3 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xdb; BYTE $0x93 #define VPERMQ_0x39_Y3_Y3 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xdb; BYTE $0x39 #define ROUND_AVX2(m0, m1, m2, m3, t, c40, c48) \ VPADDQ m0, Y0, Y0; \ VPADDQ Y1, Y0, Y0; \ VPXOR Y0, Y3, Y3; \ VPSHUFD $-79, Y3, Y3; \ VPADDQ Y3, Y2, Y2; \ VPXOR Y2, Y1, Y1; \ VPSHUFB c40, Y1, Y1; \ VPADDQ m1, Y0, Y0; \ VPADDQ Y1, Y0, Y0; \ VPXOR Y0, Y3, Y3; \ VPSHUFB c48, Y3, Y3; \ VPADDQ Y3, Y2, Y2; \ VPXOR Y2, Y1, Y1; \ VPADDQ Y1, Y1, t; \ VPSRLQ $63, Y1, Y1; \ VPXOR t, Y1, Y1; \ VPERMQ_0x39_Y1_Y1; \ VPERMQ_0x4E_Y2_Y2; \ VPERMQ_0x93_Y3_Y3; \ VPADDQ m2, Y0, Y0; \ VPADDQ Y1, Y0, Y0; \ VPXOR Y0, Y3, Y3; \ VPSHUFD $-79, Y3, Y3; \ VPADDQ Y3, Y2, Y2; \ VPXOR Y2, Y1, Y1; \ VPSHUFB c40, Y1, Y1; \ VPADDQ m3, Y0, Y0; \ VPADDQ Y1, Y0, Y0; \ VPXOR Y0, Y3, Y3; \ VPSHUFB c48, Y3, Y3; \ VPADDQ Y3, Y2, Y2; \ VPXOR Y2, Y1, Y1; \ VPADDQ Y1, Y1, t; \ VPSRLQ $63, Y1, Y1; \ VPXOR t, Y1, Y1; \ VPERMQ_0x39_Y3_Y3; \ VPERMQ_0x4E_Y2_Y2; \ VPERMQ_0x93_Y1_Y1 #define VMOVQ_SI_X11_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x1E #define VMOVQ_SI_X12_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x26 #define VMOVQ_SI_X13_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x2E #define VMOVQ_SI_X14_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x36 #define VMOVQ_SI_X15_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x3E #define VMOVQ_SI_X11(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x5E; BYTE $n #define VMOVQ_SI_X12(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x66; BYTE $n #define VMOVQ_SI_X13(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x6E; BYTE $n #define VMOVQ_SI_X14(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x76; BYTE $n #define VMOVQ_SI_X15(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x7E; BYTE $n #define VPINSRQ_1_SI_X11_0 BYTE $0xC4; BYTE $0x63; BYTE $0xA1; BYTE $0x22; BYTE $0x1E; BYTE $0x01 #define VPINSRQ_1_SI_X12_0 BYTE $0xC4; BYTE $0x63; BYTE $0x99; BYTE $0x22; BYTE $0x26; BYTE $0x01 #define VPINSRQ_1_SI_X13_0 BYTE $0xC4; BYTE $0x63; BYTE $0x91; BYTE $0x22; BYTE $0x2E; BYTE $0x01 #define VPINSRQ_1_SI_X14_0 BYTE $0xC4; BYTE $0x63; BYTE $0x89; BYTE $0x22; BYTE $0x36; BYTE $0x01 #define VPINSRQ_1_SI_X15_0 BYTE $0xC4; BYTE $0x63; BYTE $0x81; BYTE $0x22; BYTE $0x3E; BYTE $0x01 #define VPINSRQ_1_SI_X11(n) BYTE $0xC4; BYTE $0x63; BYTE $0xA1; BYTE $0x22; BYTE $0x5E; BYTE $n; BYTE $0x01 #define VPINSRQ_1_SI_X12(n) BYTE $0xC4; BYTE $0x63; BYTE $0x99; BYTE $0x22; BYTE $0x66; BYTE $n; BYTE $0x01 #define VPINSRQ_1_SI_X13(n) BYTE $0xC4; BYTE $0x63; BYTE $0x91; BYTE $0x22; BYTE $0x6E; BYTE $n; BYTE $0x01 #define VPINSRQ_1_SI_X14(n) BYTE $0xC4; BYTE $0x63; BYTE $0x89; BYTE $0x22; BYTE $0x76; BYTE $n; BYTE $0x01 #define VPINSRQ_1_SI_X15(n) BYTE $0xC4; BYTE $0x63; BYTE $0x81; BYTE $0x22; BYTE $0x7E; BYTE $n; BYTE $0x01 #define VMOVQ_R8_X15 BYTE $0xC4; BYTE $0x41; BYTE $0xF9; BYTE $0x6E; BYTE $0xF8 #define VPINSRQ_1_R9_X15 BYTE $0xC4; BYTE $0x43; BYTE $0x81; BYTE $0x22; BYTE $0xF9; BYTE $0x01 // load msg: Y12 = (i0, i1, i2, i3) // i0, i1, i2, i3 must not be 0 #define LOAD_MSG_AVX2_Y12(i0, i1, i2, i3) \ VMOVQ_SI_X12(i0*8); \ VMOVQ_SI_X11(i2*8); \ VPINSRQ_1_SI_X12(i1*8); \ VPINSRQ_1_SI_X11(i3*8); \ VINSERTI128 $1, X11, Y12, Y12 // load msg: Y13 = (i0, i1, i2, i3) // i0, i1, i2, i3 must not be 0 #define LOAD_MSG_AVX2_Y13(i0, i1, i2, i3) \ VMOVQ_SI_X13(i0*8); \ VMOVQ_SI_X11(i2*8); \ VPINSRQ_1_SI_X13(i1*8); \ VPINSRQ_1_SI_X11(i3*8); \ VINSERTI128 $1, X11, Y13, Y13 // load msg: Y14 = (i0, i1, i2, i3) // i0, i1, i2, i3 must not be 0 #define LOAD_MSG_AVX2_Y14(i0, i1, i2, i3) \ VMOVQ_SI_X14(i0*8); \ VMOVQ_SI_X11(i2*8); \ VPINSRQ_1_SI_X14(i1*8); \ VPINSRQ_1_SI_X11(i3*8); \ VINSERTI128 $1, X11, Y14, Y14 // load msg: Y15 = (i0, i1, i2, i3) // i0, i1, i2, i3 must not be 0 #define LOAD_MSG_AVX2_Y15(i0, i1, i2, i3) \ VMOVQ_SI_X15(i0*8); \ VMOVQ_SI_X11(i2*8); \ VPINSRQ_1_SI_X15(i1*8); \ VPINSRQ_1_SI_X11(i3*8); \ VINSERTI128 $1, X11, Y15, Y15 #define LOAD_MSG_AVX2_0_2_4_6_1_3_5_7_8_10_12_14_9_11_13_15() \ VMOVQ_SI_X12_0; \ VMOVQ_SI_X11(4*8); \ VPINSRQ_1_SI_X12(2*8); \ VPINSRQ_1_SI_X11(6*8); \ VINSERTI128 $1, X11, Y12, Y12; \ LOAD_MSG_AVX2_Y13(1, 3, 5, 7); \ LOAD_MSG_AVX2_Y14(8, 10, 12, 14); \ LOAD_MSG_AVX2_Y15(9, 11, 13, 15) #define LOAD_MSG_AVX2_14_4_9_13_10_8_15_6_1_0_11_5_12_2_7_3() \ LOAD_MSG_AVX2_Y12(14, 4, 9, 13); \ LOAD_MSG_AVX2_Y13(10, 8, 15, 6); \ VMOVQ_SI_X11(11*8); \ VPSHUFD $0x4E, 0*8(SI), X14; \ VPINSRQ_1_SI_X11(5*8); \ VINSERTI128 $1, X11, Y14, Y14; \ LOAD_MSG_AVX2_Y15(12, 2, 7, 3) #define LOAD_MSG_AVX2_11_12_5_15_8_0_2_13_10_3_7_9_14_6_1_4() \ VMOVQ_SI_X11(5*8); \ VMOVDQU 11*8(SI), X12; \ VPINSRQ_1_SI_X11(15*8); \ VINSERTI128 $1, X11, Y12, Y12; \ VMOVQ_SI_X13(8*8); \ VMOVQ_SI_X11(2*8); \ VPINSRQ_1_SI_X13_0; \ VPINSRQ_1_SI_X11(13*8); \ VINSERTI128 $1, X11, Y13, Y13; \ LOAD_MSG_AVX2_Y14(10, 3, 7, 9); \ LOAD_MSG_AVX2_Y15(14, 6, 1, 4) #define LOAD_MSG_AVX2_7_3_13_11_9_1_12_14_2_5_4_15_6_10_0_8() \ LOAD_MSG_AVX2_Y12(7, 3, 13, 11); \ LOAD_MSG_AVX2_Y13(9, 1, 12, 14); \ LOAD_MSG_AVX2_Y14(2, 5, 4, 15); \ VMOVQ_SI_X15(6*8); \ VMOVQ_SI_X11_0; \ VPINSRQ_1_SI_X15(10*8); \ VPINSRQ_1_SI_X11(8*8); \ VINSERTI128 $1, X11, Y15, Y15 #define LOAD_MSG_AVX2_9_5_2_10_0_7_4_15_14_11_6_3_1_12_8_13() \ LOAD_MSG_AVX2_Y12(9, 5, 2, 10); \ VMOVQ_SI_X13_0; \ VMOVQ_SI_X11(4*8); \ VPINSRQ_1_SI_X13(7*8); \ VPINSRQ_1_SI_X11(15*8); \ VINSERTI128 $1, X11, Y13, Y13; \ LOAD_MSG_AVX2_Y14(14, 11, 6, 3); \ LOAD_MSG_AVX2_Y15(1, 12, 8, 13) #define LOAD_MSG_AVX2_2_6_0_8_12_10_11_3_4_7_15_1_13_5_14_9() \ VMOVQ_SI_X12(2*8); \ VMOVQ_SI_X11_0; \ VPINSRQ_1_SI_X12(6*8); \ VPINSRQ_1_SI_X11(8*8); \ VINSERTI128 $1, X11, Y12, Y12; \ LOAD_MSG_AVX2_Y13(12, 10, 11, 3); \ LOAD_MSG_AVX2_Y14(4, 7, 15, 1); \ LOAD_MSG_AVX2_Y15(13, 5, 14, 9) #define LOAD_MSG_AVX2_12_1_14_4_5_15_13_10_0_6_9_8_7_3_2_11() \ LOAD_MSG_AVX2_Y12(12, 1, 14, 4); \ LOAD_MSG_AVX2_Y13(5, 15, 13, 10); \ VMOVQ_SI_X14_0; \ VPSHUFD $0x4E, 8*8(SI), X11; \ VPINSRQ_1_SI_X14(6*8); \ VINSERTI128 $1, X11, Y14, Y14; \ LOAD_MSG_AVX2_Y15(7, 3, 2, 11) #define LOAD_MSG_AVX2_13_7_12_3_11_14_1_9_5_15_8_2_0_4_6_10() \ LOAD_MSG_AVX2_Y12(13, 7, 12, 3); \ LOAD_MSG_AVX2_Y13(11, 14, 1, 9); \ LOAD_MSG_AVX2_Y14(5, 15, 8, 2); \ VMOVQ_SI_X15_0; \ VMOVQ_SI_X11(6*8); \ VPINSRQ_1_SI_X15(4*8); \ VPINSRQ_1_SI_X11(10*8); \ VINSERTI128 $1, X11, Y15, Y15 #define LOAD_MSG_AVX2_6_14_11_0_15_9_3_8_12_13_1_10_2_7_4_5() \ VMOVQ_SI_X12(6*8); \ VMOVQ_SI_X11(11*8); \ VPINSRQ_1_SI_X12(14*8); \ VPINSRQ_1_SI_X11_0; \ VINSERTI128 $1, X11, Y12, Y12; \ LOAD_MSG_AVX2_Y13(15, 9, 3, 8); \ VMOVQ_SI_X11(1*8); \ VMOVDQU 12*8(SI), X14; \ VPINSRQ_1_SI_X11(10*8); \ VINSERTI128 $1, X11, Y14, Y14; \ VMOVQ_SI_X15(2*8); \ VMOVDQU 4*8(SI), X11; \ VPINSRQ_1_SI_X15(7*8); \ VINSERTI128 $1, X11, Y15, Y15 #define LOAD_MSG_AVX2_10_8_7_1_2_4_6_5_15_9_3_13_11_14_12_0() \ LOAD_MSG_AVX2_Y12(10, 8, 7, 1); \ VMOVQ_SI_X13(2*8); \ VPSHUFD $0x4E, 5*8(SI), X11; \ VPINSRQ_1_SI_X13(4*8); \ VINSERTI128 $1, X11, Y13, Y13; \ LOAD_MSG_AVX2_Y14(15, 9, 3, 13); \ VMOVQ_SI_X15(11*8); \ VMOVQ_SI_X11(12*8); \ VPINSRQ_1_SI_X15(14*8); \ VPINSRQ_1_SI_X11_0; \ VINSERTI128 $1, X11, Y15, Y15 // func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) TEXT ·hashBlocksAVX2(SB), 4, $320-48 // frame size = 288 + 32 byte alignment MOVQ h+0(FP), AX MOVQ c+8(FP), BX MOVQ flag+16(FP), CX MOVQ blocks_base+24(FP), SI MOVQ blocks_len+32(FP), DI MOVQ SP, DX MOVQ SP, R9 ADDQ $31, R9 ANDQ $~31, R9 MOVQ R9, SP MOVQ CX, 16(SP) XORQ CX, CX MOVQ CX, 24(SP) VMOVDQU ·AVX2_c40<>(SB), Y4 VMOVDQU ·AVX2_c48<>(SB), Y5 VMOVDQU 0(AX), Y8 VMOVDQU 32(AX), Y9 VMOVDQU ·AVX2_iv0<>(SB), Y6 VMOVDQU ·AVX2_iv1<>(SB), Y7 MOVQ 0(BX), R8 MOVQ 8(BX), R9 MOVQ R9, 8(SP) loop: ADDQ $128, R8 MOVQ R8, 0(SP) CMPQ R8, $128 JGE noinc INCQ R9 MOVQ R9, 8(SP) noinc: VMOVDQA Y8, Y0 VMOVDQA Y9, Y1 VMOVDQA Y6, Y2 VPXOR 0(SP), Y7, Y3 LOAD_MSG_AVX2_0_2_4_6_1_3_5_7_8_10_12_14_9_11_13_15() VMOVDQA Y12, 32(SP) VMOVDQA Y13, 64(SP) VMOVDQA Y14, 96(SP) VMOVDQA Y15, 128(SP) ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_14_4_9_13_10_8_15_6_1_0_11_5_12_2_7_3() VMOVDQA Y12, 160(SP) VMOVDQA Y13, 192(SP) VMOVDQA Y14, 224(SP) VMOVDQA Y15, 256(SP) ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_11_12_5_15_8_0_2_13_10_3_7_9_14_6_1_4() ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_7_3_13_11_9_1_12_14_2_5_4_15_6_10_0_8() ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_9_5_2_10_0_7_4_15_14_11_6_3_1_12_8_13() ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_2_6_0_8_12_10_11_3_4_7_15_1_13_5_14_9() ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_12_1_14_4_5_15_13_10_0_6_9_8_7_3_2_11() ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_13_7_12_3_11_14_1_9_5_15_8_2_0_4_6_10() ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_6_14_11_0_15_9_3_8_12_13_1_10_2_7_4_5() ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) LOAD_MSG_AVX2_10_8_7_1_2_4_6_5_15_9_3_13_11_14_12_0() ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) ROUND_AVX2(32(SP), 64(SP), 96(SP), 128(SP), Y10, Y4, Y5) ROUND_AVX2(160(SP), 192(SP), 224(SP), 256(SP), Y10, Y4, Y5) VPXOR Y0, Y8, Y8 VPXOR Y1, Y9, Y9 VPXOR Y2, Y8, Y8 VPXOR Y3, Y9, Y9 LEAQ 128(SI), SI SUBQ $128, DI JNE loop MOVQ R8, 0(BX) MOVQ R9, 8(BX) VMOVDQU Y8, 0(AX) VMOVDQU Y9, 32(AX) VZEROUPPER MOVQ DX, SP RET #define VPUNPCKLQDQ_X2_X2_X15 BYTE $0xC5; BYTE $0x69; BYTE $0x6C; BYTE $0xFA #define VPUNPCKLQDQ_X3_X3_X15 BYTE $0xC5; BYTE $0x61; BYTE $0x6C; BYTE $0xFB #define VPUNPCKLQDQ_X7_X7_X15 BYTE $0xC5; BYTE $0x41; BYTE $0x6C; BYTE $0xFF #define VPUNPCKLQDQ_X13_X13_X15 BYTE $0xC4; BYTE $0x41; BYTE $0x11; BYTE $0x6C; BYTE $0xFD #define VPUNPCKLQDQ_X14_X14_X15 BYTE $0xC4; BYTE $0x41; BYTE $0x09; BYTE $0x6C; BYTE $0xFE #define VPUNPCKHQDQ_X15_X2_X2 BYTE $0xC4; BYTE $0xC1; BYTE $0x69; BYTE $0x6D; BYTE $0xD7 #define VPUNPCKHQDQ_X15_X3_X3 BYTE $0xC4; BYTE $0xC1; BYTE $0x61; BYTE $0x6D; BYTE $0xDF #define VPUNPCKHQDQ_X15_X6_X6 BYTE $0xC4; BYTE $0xC1; BYTE $0x49; BYTE $0x6D; BYTE $0xF7 #define VPUNPCKHQDQ_X15_X7_X7 BYTE $0xC4; BYTE $0xC1; BYTE $0x41; BYTE $0x6D; BYTE $0xFF #define VPUNPCKHQDQ_X15_X3_X2 BYTE $0xC4; BYTE $0xC1; BYTE $0x61; BYTE $0x6D; BYTE $0xD7 #define VPUNPCKHQDQ_X15_X7_X6 BYTE $0xC4; BYTE $0xC1; BYTE $0x41; BYTE $0x6D; BYTE $0xF7 #define VPUNPCKHQDQ_X15_X13_X3 BYTE $0xC4; BYTE $0xC1; BYTE $0x11; BYTE $0x6D; BYTE $0xDF #define VPUNPCKHQDQ_X15_X13_X7 BYTE $0xC4; BYTE $0xC1; BYTE $0x11; BYTE $0x6D; BYTE $0xFF #define SHUFFLE_AVX() \ VMOVDQA X6, X13; \ VMOVDQA X2, X14; \ VMOVDQA X4, X6; \ VPUNPCKLQDQ_X13_X13_X15; \ VMOVDQA X5, X4; \ VMOVDQA X6, X5; \ VPUNPCKHQDQ_X15_X7_X6; \ VPUNPCKLQDQ_X7_X7_X15; \ VPUNPCKHQDQ_X15_X13_X7; \ VPUNPCKLQDQ_X3_X3_X15; \ VPUNPCKHQDQ_X15_X2_X2; \ VPUNPCKLQDQ_X14_X14_X15; \ VPUNPCKHQDQ_X15_X3_X3; \ #define SHUFFLE_AVX_INV() \ VMOVDQA X2, X13; \ VMOVDQA X4, X14; \ VPUNPCKLQDQ_X2_X2_X15; \ VMOVDQA X5, X4; \ VPUNPCKHQDQ_X15_X3_X2; \ VMOVDQA X14, X5; \ VPUNPCKLQDQ_X3_X3_X15; \ VMOVDQA X6, X14; \ VPUNPCKHQDQ_X15_X13_X3; \ VPUNPCKLQDQ_X7_X7_X15; \ VPUNPCKHQDQ_X15_X6_X6; \ VPUNPCKLQDQ_X14_X14_X15; \ VPUNPCKHQDQ_X15_X7_X7; \ #define HALF_ROUND_AVX(v0, v1, v2, v3, v4, v5, v6, v7, m0, m1, m2, m3, t0, c40, c48) \ VPADDQ m0, v0, v0; \ VPADDQ v2, v0, v0; \ VPADDQ m1, v1, v1; \ VPADDQ v3, v1, v1; \ VPXOR v0, v6, v6; \ VPXOR v1, v7, v7; \ VPSHUFD $-79, v6, v6; \ VPSHUFD $-79, v7, v7; \ VPADDQ v6, v4, v4; \ VPADDQ v7, v5, v5; \ VPXOR v4, v2, v2; \ VPXOR v5, v3, v3; \ VPSHUFB c40, v2, v2; \ VPSHUFB c40, v3, v3; \ VPADDQ m2, v0, v0; \ VPADDQ v2, v0, v0; \ VPADDQ m3, v1, v1; \ VPADDQ v3, v1, v1; \ VPXOR v0, v6, v6; \ VPXOR v1, v7, v7; \ VPSHUFB c48, v6, v6; \ VPSHUFB c48, v7, v7; \ VPADDQ v6, v4, v4; \ VPADDQ v7, v5, v5; \ VPXOR v4, v2, v2; \ VPXOR v5, v3, v3; \ VPADDQ v2, v2, t0; \ VPSRLQ $63, v2, v2; \ VPXOR t0, v2, v2; \ VPADDQ v3, v3, t0; \ VPSRLQ $63, v3, v3; \ VPXOR t0, v3, v3 // load msg: X12 = (i0, i1), X13 = (i2, i3), X14 = (i4, i5), X15 = (i6, i7) // i0, i1, i2, i3, i4, i5, i6, i7 must not be 0 #define LOAD_MSG_AVX(i0, i1, i2, i3, i4, i5, i6, i7) \ VMOVQ_SI_X12(i0*8); \ VMOVQ_SI_X13(i2*8); \ VMOVQ_SI_X14(i4*8); \ VMOVQ_SI_X15(i6*8); \ VPINSRQ_1_SI_X12(i1*8); \ VPINSRQ_1_SI_X13(i3*8); \ VPINSRQ_1_SI_X14(i5*8); \ VPINSRQ_1_SI_X15(i7*8) // load msg: X12 = (0, 2), X13 = (4, 6), X14 = (1, 3), X15 = (5, 7) #define LOAD_MSG_AVX_0_2_4_6_1_3_5_7() \ VMOVQ_SI_X12_0; \ VMOVQ_SI_X13(4*8); \ VMOVQ_SI_X14(1*8); \ VMOVQ_SI_X15(5*8); \ VPINSRQ_1_SI_X12(2*8); \ VPINSRQ_1_SI_X13(6*8); \ VPINSRQ_1_SI_X14(3*8); \ VPINSRQ_1_SI_X15(7*8) // load msg: X12 = (1, 0), X13 = (11, 5), X14 = (12, 2), X15 = (7, 3) #define LOAD_MSG_AVX_1_0_11_5_12_2_7_3() \ VPSHUFD $0x4E, 0*8(SI), X12; \ VMOVQ_SI_X13(11*8); \ VMOVQ_SI_X14(12*8); \ VMOVQ_SI_X15(7*8); \ VPINSRQ_1_SI_X13(5*8); \ VPINSRQ_1_SI_X14(2*8); \ VPINSRQ_1_SI_X15(3*8) // load msg: X12 = (11, 12), X13 = (5, 15), X14 = (8, 0), X15 = (2, 13) #define LOAD_MSG_AVX_11_12_5_15_8_0_2_13() \ VMOVDQU 11*8(SI), X12; \ VMOVQ_SI_X13(5*8); \ VMOVQ_SI_X14(8*8); \ VMOVQ_SI_X15(2*8); \ VPINSRQ_1_SI_X13(15*8); \ VPINSRQ_1_SI_X14_0; \ VPINSRQ_1_SI_X15(13*8) // load msg: X12 = (2, 5), X13 = (4, 15), X14 = (6, 10), X15 = (0, 8) #define LOAD_MSG_AVX_2_5_4_15_6_10_0_8() \ VMOVQ_SI_X12(2*8); \ VMOVQ_SI_X13(4*8); \ VMOVQ_SI_X14(6*8); \ VMOVQ_SI_X15_0; \ VPINSRQ_1_SI_X12(5*8); \ VPINSRQ_1_SI_X13(15*8); \ VPINSRQ_1_SI_X14(10*8); \ VPINSRQ_1_SI_X15(8*8) // load msg: X12 = (9, 5), X13 = (2, 10), X14 = (0, 7), X15 = (4, 15) #define LOAD_MSG_AVX_9_5_2_10_0_7_4_15() \ VMOVQ_SI_X12(9*8); \ VMOVQ_SI_X13(2*8); \ VMOVQ_SI_X14_0; \ VMOVQ_SI_X15(4*8); \ VPINSRQ_1_SI_X12(5*8); \ VPINSRQ_1_SI_X13(10*8); \ VPINSRQ_1_SI_X14(7*8); \ VPINSRQ_1_SI_X15(15*8) // load msg: X12 = (2, 6), X13 = (0, 8), X14 = (12, 10), X15 = (11, 3) #define LOAD_MSG_AVX_2_6_0_8_12_10_11_3() \ VMOVQ_SI_X12(2*8); \ VMOVQ_SI_X13_0; \ VMOVQ_SI_X14(12*8); \ VMOVQ_SI_X15(11*8); \ VPINSRQ_1_SI_X12(6*8); \ VPINSRQ_1_SI_X13(8*8); \ VPINSRQ_1_SI_X14(10*8); \ VPINSRQ_1_SI_X15(3*8) // load msg: X12 = (0, 6), X13 = (9, 8), X14 = (7, 3), X15 = (2, 11) #define LOAD_MSG_AVX_0_6_9_8_7_3_2_11() \ MOVQ 0*8(SI), X12; \ VPSHUFD $0x4E, 8*8(SI), X13; \ MOVQ 7*8(SI), X14; \ MOVQ 2*8(SI), X15; \ VPINSRQ_1_SI_X12(6*8); \ VPINSRQ_1_SI_X14(3*8); \ VPINSRQ_1_SI_X15(11*8) // load msg: X12 = (6, 14), X13 = (11, 0), X14 = (15, 9), X15 = (3, 8) #define LOAD_MSG_AVX_6_14_11_0_15_9_3_8() \ MOVQ 6*8(SI), X12; \ MOVQ 11*8(SI), X13; \ MOVQ 15*8(SI), X14; \ MOVQ 3*8(SI), X15; \ VPINSRQ_1_SI_X12(14*8); \ VPINSRQ_1_SI_X13_0; \ VPINSRQ_1_SI_X14(9*8); \ VPINSRQ_1_SI_X15(8*8) // load msg: X12 = (5, 15), X13 = (8, 2), X14 = (0, 4), X15 = (6, 10) #define LOAD_MSG_AVX_5_15_8_2_0_4_6_10() \ MOVQ 5*8(SI), X12; \ MOVQ 8*8(SI), X13; \ MOVQ 0*8(SI), X14; \ MOVQ 6*8(SI), X15; \ VPINSRQ_1_SI_X12(15*8); \ VPINSRQ_1_SI_X13(2*8); \ VPINSRQ_1_SI_X14(4*8); \ VPINSRQ_1_SI_X15(10*8) // load msg: X12 = (12, 13), X13 = (1, 10), X14 = (2, 7), X15 = (4, 5) #define LOAD_MSG_AVX_12_13_1_10_2_7_4_5() \ VMOVDQU 12*8(SI), X12; \ MOVQ 1*8(SI), X13; \ MOVQ 2*8(SI), X14; \ VPINSRQ_1_SI_X13(10*8); \ VPINSRQ_1_SI_X14(7*8); \ VMOVDQU 4*8(SI), X15 // load msg: X12 = (15, 9), X13 = (3, 13), X14 = (11, 14), X15 = (12, 0) #define LOAD_MSG_AVX_15_9_3_13_11_14_12_0() \ MOVQ 15*8(SI), X12; \ MOVQ 3*8(SI), X13; \ MOVQ 11*8(SI), X14; \ MOVQ 12*8(SI), X15; \ VPINSRQ_1_SI_X12(9*8); \ VPINSRQ_1_SI_X13(13*8); \ VPINSRQ_1_SI_X14(14*8); \ VPINSRQ_1_SI_X15_0 // func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) TEXT ·hashBlocksAVX(SB), 4, $288-48 // frame size = 272 + 16 byte alignment MOVQ h+0(FP), AX MOVQ c+8(FP), BX MOVQ flag+16(FP), CX MOVQ blocks_base+24(FP), SI MOVQ blocks_len+32(FP), DI MOVQ SP, BP MOVQ SP, R9 ADDQ $15, R9 ANDQ $~15, R9 MOVQ R9, SP VMOVDQU ·AVX_c40<>(SB), X0 VMOVDQU ·AVX_c48<>(SB), X1 VMOVDQA X0, X8 VMOVDQA X1, X9 VMOVDQU ·AVX_iv3<>(SB), X0 VMOVDQA X0, 0(SP) XORQ CX, 0(SP) // 0(SP) = ·AVX_iv3 ^ (CX || 0) VMOVDQU 0(AX), X10 VMOVDQU 16(AX), X11 VMOVDQU 32(AX), X2 VMOVDQU 48(AX), X3 MOVQ 0(BX), R8 MOVQ 8(BX), R9 loop: ADDQ $128, R8 CMPQ R8, $128 JGE noinc INCQ R9 noinc: VMOVQ_R8_X15 VPINSRQ_1_R9_X15 VMOVDQA X10, X0 VMOVDQA X11, X1 VMOVDQU ·AVX_iv0<>(SB), X4 VMOVDQU ·AVX_iv1<>(SB), X5 VMOVDQU ·AVX_iv2<>(SB), X6 VPXOR X15, X6, X6 VMOVDQA 0(SP), X7 LOAD_MSG_AVX_0_2_4_6_1_3_5_7() VMOVDQA X12, 16(SP) VMOVDQA X13, 32(SP) VMOVDQA X14, 48(SP) VMOVDQA X15, 64(SP) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX(8, 10, 12, 14, 9, 11, 13, 15) VMOVDQA X12, 80(SP) VMOVDQA X13, 96(SP) VMOVDQA X14, 112(SP) VMOVDQA X15, 128(SP) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX(14, 4, 9, 13, 10, 8, 15, 6) VMOVDQA X12, 144(SP) VMOVDQA X13, 160(SP) VMOVDQA X14, 176(SP) VMOVDQA X15, 192(SP) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX_1_0_11_5_12_2_7_3() VMOVDQA X12, 208(SP) VMOVDQA X13, 224(SP) VMOVDQA X14, 240(SP) VMOVDQA X15, 256(SP) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX_11_12_5_15_8_0_2_13() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX(10, 3, 7, 9, 14, 6, 1, 4) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX(7, 3, 13, 11, 9, 1, 12, 14) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX_2_5_4_15_6_10_0_8() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX_9_5_2_10_0_7_4_15() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX(14, 11, 6, 3, 1, 12, 8, 13) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX_2_6_0_8_12_10_11_3() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX(4, 7, 15, 1, 13, 5, 14, 9) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX(12, 1, 14, 4, 5, 15, 13, 10) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX_0_6_9_8_7_3_2_11() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX(13, 7, 12, 3, 11, 14, 1, 9) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX_5_15_8_2_0_4_6_10() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX_6_14_11_0_15_9_3_8() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX_12_13_1_10_2_7_4_5() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() LOAD_MSG_AVX(10, 8, 7, 1, 2, 4, 6, 5) HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX() LOAD_MSG_AVX_15_9_3_13_11_14_12_0() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) SHUFFLE_AVX_INV() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 16(SP), 32(SP), 48(SP), 64(SP), X15, X8, X9) SHUFFLE_AVX() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 80(SP), 96(SP), 112(SP), 128(SP), X15, X8, X9) SHUFFLE_AVX_INV() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 144(SP), 160(SP), 176(SP), 192(SP), X15, X8, X9) SHUFFLE_AVX() HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 208(SP), 224(SP), 240(SP), 256(SP), X15, X8, X9) SHUFFLE_AVX_INV() VMOVDQU 32(AX), X14 VMOVDQU 48(AX), X15 VPXOR X0, X10, X10 VPXOR X1, X11, X11 VPXOR X2, X14, X14 VPXOR X3, X15, X15 VPXOR X4, X10, X10 VPXOR X5, X11, X11 VPXOR X6, X14, X2 VPXOR X7, X15, X3 VMOVDQU X2, 32(AX) VMOVDQU X3, 48(AX) LEAQ 128(SI), SI SUBQ $128, DI JNE loop VMOVDQU X10, 0(AX) VMOVDQU X11, 16(AX) MOVQ R8, 0(BX) MOVQ R9, 8(BX) VZEROUPPER MOVQ BP, SP RET // func supportsAVX2() bool TEXT ·supportsAVX2(SB), 4, $0-1 MOVQ runtime·support_avx2(SB), AX MOVB AX, ret+0(FP) RET // func supportsAVX() bool TEXT ·supportsAVX(SB), 4, $0-1 MOVQ runtime·support_avx(SB), AX MOVB AX, ret+0(FP) RET ���������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go��������������������������������0000644�0610621�0607500�00000001744�13172163317�025647� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7,amd64,!gccgo,!appengine package blake2b func init() { useAVX2 = supportsAVX2() useAVX = supportsAVX() useSSE4 = supportsSSE4() } //go:noescape func supportsSSE4() bool //go:noescape func supportsAVX() bool //go:noescape func supportsAVX2() bool //go:noescape func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) //go:noescape func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) //go:noescape func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { if useAVX2 { hashBlocksAVX2(h, c, flag, blocks) } else if useAVX { hashBlocksAVX(h, c, flag, blocks) } else if useSSE4 { hashBlocksSSE4(h, c, flag, blocks) } else { hashBlocksGeneric(h, c, flag, blocks) } } ����������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/blake2b/blake2b.go������������������������������������������0000644�0610621�0607500�00000011572�13172163317�024213� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package blake2b implements the BLAKE2b hash algorithm defined by RFC 7693 // and the extendable output function (XOF) BLAKE2Xb. // // For a detailed specification of BLAKE2b see https://blake2.net/blake2.pdf // and for BLAKE2Xb see https://blake2.net/blake2x.pdf // // If you aren't sure which function you need, use BLAKE2b (Sum512 or New512). // If you need a secret-key MAC (message authentication code), use the New512 // function with a non-nil key. // // BLAKE2X is a construction to compute hash values larger than 64 bytes. It // can produce hash values between 0 and 4 GiB. package blake2b import ( "encoding/binary" "errors" "hash" ) const ( // The blocksize of BLAKE2b in bytes. BlockSize = 128 // The hash size of BLAKE2b-512 in bytes. Size = 64 // The hash size of BLAKE2b-384 in bytes. Size384 = 48 // The hash size of BLAKE2b-256 in bytes. Size256 = 32 ) var ( useAVX2 bool useAVX bool useSSE4 bool ) var errKeySize = errors.New("blake2b: invalid key size") var iv = [8]uint64{ 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, } // Sum512 returns the BLAKE2b-512 checksum of the data. func Sum512(data []byte) [Size]byte { var sum [Size]byte checkSum(&sum, Size, data) return sum } // Sum384 returns the BLAKE2b-384 checksum of the data. func Sum384(data []byte) [Size384]byte { var sum [Size]byte var sum384 [Size384]byte checkSum(&sum, Size384, data) copy(sum384[:], sum[:Size384]) return sum384 } // Sum256 returns the BLAKE2b-256 checksum of the data. func Sum256(data []byte) [Size256]byte { var sum [Size]byte var sum256 [Size256]byte checkSum(&sum, Size256, data) copy(sum256[:], sum[:Size256]) return sum256 } // New512 returns a new hash.Hash computing the BLAKE2b-512 checksum. A non-nil // key turns the hash into a MAC. The key must between zero and 64 bytes long. func New512(key []byte) (hash.Hash, error) { return newDigest(Size, key) } // New384 returns a new hash.Hash computing the BLAKE2b-384 checksum. A non-nil // key turns the hash into a MAC. The key must between zero and 64 bytes long. func New384(key []byte) (hash.Hash, error) { return newDigest(Size384, key) } // New256 returns a new hash.Hash computing the BLAKE2b-256 checksum. A non-nil // key turns the hash into a MAC. The key must between zero and 64 bytes long. func New256(key []byte) (hash.Hash, error) { return newDigest(Size256, key) } func newDigest(hashSize int, key []byte) (*digest, error) { if len(key) > Size { return nil, errKeySize } d := &digest{ size: hashSize, keyLen: len(key), } copy(d.key[:], key) d.Reset() return d, nil } func checkSum(sum *[Size]byte, hashSize int, data []byte) { h := iv h[0] ^= uint64(hashSize) | (1 << 16) | (1 << 24) var c [2]uint64 if length := len(data); length > BlockSize { n := length &^ (BlockSize - 1) if length == n { n -= BlockSize } hashBlocks(&h, &c, 0, data[:n]) data = data[n:] } var block [BlockSize]byte offset := copy(block[:], data) remaining := uint64(BlockSize - offset) if c[0] < remaining { c[1]-- } c[0] -= remaining hashBlocks(&h, &c, 0xFFFFFFFFFFFFFFFF, block[:]) for i, v := range h[:(hashSize+7)/8] { binary.LittleEndian.PutUint64(sum[8*i:], v) } } type digest struct { h [8]uint64 c [2]uint64 size int block [BlockSize]byte offset int key [BlockSize]byte keyLen int } func (d *digest) BlockSize() int { return BlockSize } func (d *digest) Size() int { return d.size } func (d *digest) Reset() { d.h = iv d.h[0] ^= uint64(d.size) | (uint64(d.keyLen) << 8) | (1 << 16) | (1 << 24) d.offset, d.c[0], d.c[1] = 0, 0, 0 if d.keyLen > 0 { d.block = d.key d.offset = BlockSize } } func (d *digest) Write(p []byte) (n int, err error) { n = len(p) if d.offset > 0 { remaining := BlockSize - d.offset if n <= remaining { d.offset += copy(d.block[d.offset:], p) return } copy(d.block[d.offset:], p[:remaining]) hashBlocks(&d.h, &d.c, 0, d.block[:]) d.offset = 0 p = p[remaining:] } if length := len(p); length > BlockSize { nn := length &^ (BlockSize - 1) if length == nn { nn -= BlockSize } hashBlocks(&d.h, &d.c, 0, p[:nn]) p = p[nn:] } if len(p) > 0 { d.offset += copy(d.block[:], p) } return } func (d *digest) Sum(sum []byte) []byte { var hash [Size]byte d.finalize(&hash) return append(sum, hash[:d.size]...) } func (d *digest) finalize(hash *[Size]byte) { var block [BlockSize]byte copy(block[:], d.block[:d.offset]) remaining := uint64(BlockSize - d.offset) c := d.c if c[0] < remaining { c[1]-- } c[0] -= remaining h := d.h hashBlocks(&h, &c, 0xFFFFFFFFFFFFFFFF, block[:]) for i, v := range h { binary.LittleEndian.PutUint64(hash[8*i:], v) } } ��������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bcrypt/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�022355� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bcrypt/bcrypt_test.go���������������������������������������0000644�0610621�0607500�00000015372�13172163317�025256� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bcrypt import ( "bytes" "fmt" "testing" ) func TestBcryptingIsEasy(t *testing.T) { pass := []byte("mypassword") hp, err := GenerateFromPassword(pass, 0) if err != nil { t.Fatalf("GenerateFromPassword error: %s", err) } if CompareHashAndPassword(hp, pass) != nil { t.Errorf("%v should hash %s correctly", hp, pass) } notPass := "notthepass" err = CompareHashAndPassword(hp, []byte(notPass)) if err != ErrMismatchedHashAndPassword { t.Errorf("%v and %s should be mismatched", hp, notPass) } } func TestBcryptingIsCorrect(t *testing.T) { pass := []byte("allmine") salt := []byte("XajjQvNhvvRt5GSeFk1xFe") expectedHash := []byte("$2a$10$XajjQvNhvvRt5GSeFk1xFeyqRrsxkhBkUiQeg0dt.wU1qD4aFDcga") hash, err := bcrypt(pass, 10, salt) if err != nil { t.Fatalf("bcrypt blew up: %v", err) } if !bytes.HasSuffix(expectedHash, hash) { t.Errorf("%v should be the suffix of %v", hash, expectedHash) } h, err := newFromHash(expectedHash) if err != nil { t.Errorf("Unable to parse %s: %v", string(expectedHash), err) } // This is not the safe way to compare these hashes. We do this only for // testing clarity. Use bcrypt.CompareHashAndPassword() if err == nil && !bytes.Equal(expectedHash, h.Hash()) { t.Errorf("Parsed hash %v should equal %v", h.Hash(), expectedHash) } } func TestVeryShortPasswords(t *testing.T) { key := []byte("k") salt := []byte("XajjQvNhvvRt5GSeFk1xFe") _, err := bcrypt(key, 10, salt) if err != nil { t.Errorf("One byte key resulted in error: %s", err) } } func TestTooLongPasswordsWork(t *testing.T) { salt := []byte("XajjQvNhvvRt5GSeFk1xFe") // One byte over the usual 56 byte limit that blowfish has tooLongPass := []byte("012345678901234567890123456789012345678901234567890123456") tooLongExpected := []byte("$2a$10$XajjQvNhvvRt5GSeFk1xFe5l47dONXg781AmZtd869sO8zfsHuw7C") hash, err := bcrypt(tooLongPass, 10, salt) if err != nil { t.Fatalf("bcrypt blew up on long password: %v", err) } if !bytes.HasSuffix(tooLongExpected, hash) { t.Errorf("%v should be the suffix of %v", hash, tooLongExpected) } } type InvalidHashTest struct { err error hash []byte } var invalidTests = []InvalidHashTest{ {ErrHashTooShort, []byte("$2a$10$fooo")}, {ErrHashTooShort, []byte("$2a")}, {HashVersionTooNewError('3'), []byte("$3a$10$sssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")}, {InvalidHashPrefixError('%'), []byte("%2a$10$sssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")}, {InvalidCostError(32), []byte("$2a$32$sssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")}, } func TestInvalidHashErrors(t *testing.T) { check := func(name string, expected, err error) { if err == nil { t.Errorf("%s: Should have returned an error", name) } if err != nil && err != expected { t.Errorf("%s gave err %v but should have given %v", name, err, expected) } } for _, iht := range invalidTests { _, err := newFromHash(iht.hash) check("newFromHash", iht.err, err) err = CompareHashAndPassword(iht.hash, []byte("anything")) check("CompareHashAndPassword", iht.err, err) } } func TestUnpaddedBase64Encoding(t *testing.T) { original := []byte{101, 201, 101, 75, 19, 227, 199, 20, 239, 236, 133, 32, 30, 109, 243, 30} encodedOriginal := []byte("XajjQvNhvvRt5GSeFk1xFe") encoded := base64Encode(original) if !bytes.Equal(encodedOriginal, encoded) { t.Errorf("Encoded %v should have equaled %v", encoded, encodedOriginal) } decoded, err := base64Decode(encodedOriginal) if err != nil { t.Fatalf("base64Decode blew up: %s", err) } if !bytes.Equal(decoded, original) { t.Errorf("Decoded %v should have equaled %v", decoded, original) } } func TestCost(t *testing.T) { suffix := "XajjQvNhvvRt5GSeFk1xFe5l47dONXg781AmZtd869sO8zfsHuw7C" for _, vers := range []string{"2a", "2"} { for _, cost := range []int{4, 10} { s := fmt.Sprintf("$%s$%02d$%s", vers, cost, suffix) h := []byte(s) actual, err := Cost(h) if err != nil { t.Errorf("Cost, error: %s", err) continue } if actual != cost { t.Errorf("Cost, expected: %d, actual: %d", cost, actual) } } } _, err := Cost([]byte("$a$a$" + suffix)) if err == nil { t.Errorf("Cost, malformed but no error returned") } } func TestCostValidationInHash(t *testing.T) { if testing.Short() { return } pass := []byte("mypassword") for c := 0; c < MinCost; c++ { p, _ := newFromPassword(pass, c) if p.cost != DefaultCost { t.Errorf("newFromPassword should default costs below %d to %d, but was %d", MinCost, DefaultCost, p.cost) } } p, _ := newFromPassword(pass, 14) if p.cost != 14 { t.Errorf("newFromPassword should default cost to 14, but was %d", p.cost) } hp, _ := newFromHash(p.Hash()) if p.cost != hp.cost { t.Errorf("newFromHash should maintain the cost at %d, but was %d", p.cost, hp.cost) } _, err := newFromPassword(pass, 32) if err == nil { t.Fatalf("newFromPassword: should return a cost error") } if err != InvalidCostError(32) { t.Errorf("newFromPassword: should return cost error, got %#v", err) } } func TestCostReturnsWithLeadingZeroes(t *testing.T) { hp, _ := newFromPassword([]byte("abcdefgh"), 7) cost := hp.Hash()[4:7] expected := []byte("07$") if !bytes.Equal(expected, cost) { t.Errorf("single digit costs in hash should have leading zeros: was %v instead of %v", cost, expected) } } func TestMinorNotRequired(t *testing.T) { noMinorHash := []byte("$2$10$XajjQvNhvvRt5GSeFk1xFeyqRrsxkhBkUiQeg0dt.wU1qD4aFDcga") h, err := newFromHash(noMinorHash) if err != nil { t.Fatalf("No minor hash blew up: %s", err) } if h.minor != 0 { t.Errorf("Should leave minor version at 0, but was %d", h.minor) } if !bytes.Equal(noMinorHash, h.Hash()) { t.Errorf("Should generate hash %v, but created %v", noMinorHash, h.Hash()) } } func BenchmarkEqual(b *testing.B) { b.StopTimer() passwd := []byte("somepasswordyoulike") hash, _ := GenerateFromPassword(passwd, 10) b.StartTimer() for i := 0; i < b.N; i++ { CompareHashAndPassword(hash, passwd) } } func BenchmarkGeneration(b *testing.B) { b.StopTimer() passwd := []byte("mylongpassword1234") b.StartTimer() for i := 0; i < b.N; i++ { GenerateFromPassword(passwd, 10) } } // See Issue https://github.com/golang/go/issues/20425. func TestNoSideEffectsFromCompare(t *testing.T) { source := []byte("passw0rd123456") password := source[:len(source)-6] token := source[len(source)-6:] want := make([]byte, len(source)) copy(want, source) wantHash := []byte("$2a$10$LK9XRuhNxHHCvjX3tdkRKei1QiCDUKrJRhZv7WWZPuQGRUM92rOUa") _ = CompareHashAndPassword(wantHash, password) got := bytes.Join([][]byte{password, token}, []byte("")) if !bytes.Equal(got, want) { t.Errorf("got=%q want=%q", got, want) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bcrypt/bcrypt.go��������������������������������������������0000644�0610621�0607500�00000017432�13172163317�024216� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing // algorithm. See http://www.usenix.org/event/usenix99/provos/provos.pdf package bcrypt // import "golang.org/x/crypto/bcrypt" // The code is a port of Provos and Mazières's C implementation. import ( "crypto/rand" "crypto/subtle" "errors" "fmt" "io" "strconv" "golang.org/x/crypto/blowfish" ) const ( MinCost int = 4 // the minimum allowable cost as passed in to GenerateFromPassword MaxCost int = 31 // the maximum allowable cost as passed in to GenerateFromPassword DefaultCost int = 10 // the cost that will actually be set if a cost below MinCost is passed into GenerateFromPassword ) // The error returned from CompareHashAndPassword when a password and hash do // not match. var ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password") // The error returned from CompareHashAndPassword when a hash is too short to // be a bcrypt hash. var ErrHashTooShort = errors.New("crypto/bcrypt: hashedSecret too short to be a bcrypted password") // The error returned from CompareHashAndPassword when a hash was created with // a bcrypt algorithm newer than this implementation. type HashVersionTooNewError byte func (hv HashVersionTooNewError) Error() string { return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion) } // The error returned from CompareHashAndPassword when a hash starts with something other than '$' type InvalidHashPrefixError byte func (ih InvalidHashPrefixError) Error() string { return fmt.Sprintf("crypto/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'", byte(ih)) } type InvalidCostError int func (ic InvalidCostError) Error() string { return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost)) } const ( majorVersion = '2' minorVersion = 'a' maxSaltSize = 16 maxCryptedHashSize = 23 encodedSaltSize = 22 encodedHashSize = 31 minHashSize = 59 ) // magicCipherData is an IV for the 64 Blowfish encryption calls in // bcrypt(). It's the string "OrpheanBeholderScryDoubt" in big-endian bytes. var magicCipherData = []byte{ 0x4f, 0x72, 0x70, 0x68, 0x65, 0x61, 0x6e, 0x42, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x53, 0x63, 0x72, 0x79, 0x44, 0x6f, 0x75, 0x62, 0x74, } type hashed struct { hash []byte salt []byte cost int // allowed range is MinCost to MaxCost major byte minor byte } // GenerateFromPassword returns the bcrypt hash of the password at the given // cost. If the cost given is less than MinCost, the cost will be set to // DefaultCost, instead. Use CompareHashAndPassword, as defined in this package, // to compare the returned hashed password with its cleartext version. func GenerateFromPassword(password []byte, cost int) ([]byte, error) { p, err := newFromPassword(password, cost) if err != nil { return nil, err } return p.Hash(), nil } // CompareHashAndPassword compares a bcrypt hashed password with its possible // plaintext equivalent. Returns nil on success, or an error on failure. func CompareHashAndPassword(hashedPassword, password []byte) error { p, err := newFromHash(hashedPassword) if err != nil { return err } otherHash, err := bcrypt(password, p.cost, p.salt) if err != nil { return err } otherP := &hashed{otherHash, p.salt, p.cost, p.major, p.minor} if subtle.ConstantTimeCompare(p.Hash(), otherP.Hash()) == 1 { return nil } return ErrMismatchedHashAndPassword } // Cost returns the hashing cost used to create the given hashed // password. When, in the future, the hashing cost of a password system needs // to be increased in order to adjust for greater computational power, this // function allows one to establish which passwords need to be updated. func Cost(hashedPassword []byte) (int, error) { p, err := newFromHash(hashedPassword) if err != nil { return 0, err } return p.cost, nil } func newFromPassword(password []byte, cost int) (*hashed, error) { if cost < MinCost { cost = DefaultCost } p := new(hashed) p.major = majorVersion p.minor = minorVersion err := checkCost(cost) if err != nil { return nil, err } p.cost = cost unencodedSalt := make([]byte, maxSaltSize) _, err = io.ReadFull(rand.Reader, unencodedSalt) if err != nil { return nil, err } p.salt = base64Encode(unencodedSalt) hash, err := bcrypt(password, p.cost, p.salt) if err != nil { return nil, err } p.hash = hash return p, err } func newFromHash(hashedSecret []byte) (*hashed, error) { if len(hashedSecret) < minHashSize { return nil, ErrHashTooShort } p := new(hashed) n, err := p.decodeVersion(hashedSecret) if err != nil { return nil, err } hashedSecret = hashedSecret[n:] n, err = p.decodeCost(hashedSecret) if err != nil { return nil, err } hashedSecret = hashedSecret[n:] // The "+2" is here because we'll have to append at most 2 '=' to the salt // when base64 decoding it in expensiveBlowfishSetup(). p.salt = make([]byte, encodedSaltSize, encodedSaltSize+2) copy(p.salt, hashedSecret[:encodedSaltSize]) hashedSecret = hashedSecret[encodedSaltSize:] p.hash = make([]byte, len(hashedSecret)) copy(p.hash, hashedSecret) return p, nil } func bcrypt(password []byte, cost int, salt []byte) ([]byte, error) { cipherData := make([]byte, len(magicCipherData)) copy(cipherData, magicCipherData) c, err := expensiveBlowfishSetup(password, uint32(cost), salt) if err != nil { return nil, err } for i := 0; i < 24; i += 8 { for j := 0; j < 64; j++ { c.Encrypt(cipherData[i:i+8], cipherData[i:i+8]) } } // Bug compatibility with C bcrypt implementations. We only encode 23 of // the 24 bytes encrypted. hsh := base64Encode(cipherData[:maxCryptedHashSize]) return hsh, nil } func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) { csalt, err := base64Decode(salt) if err != nil { return nil, err } // Bug compatibility with C bcrypt implementations. They use the trailing // NULL in the key string during expansion. // We copy the key to prevent changing the underlying array. ckey := append(key[:len(key):len(key)], 0) c, err := blowfish.NewSaltedCipher(ckey, csalt) if err != nil { return nil, err } var i, rounds uint64 rounds = 1 << cost for i = 0; i < rounds; i++ { blowfish.ExpandKey(ckey, c) blowfish.ExpandKey(csalt, c) } return c, nil } func (p *hashed) Hash() []byte { arr := make([]byte, 60) arr[0] = '$' arr[1] = p.major n := 2 if p.minor != 0 { arr[2] = p.minor n = 3 } arr[n] = '$' n += 1 copy(arr[n:], []byte(fmt.Sprintf("%02d", p.cost))) n += 2 arr[n] = '$' n += 1 copy(arr[n:], p.salt) n += encodedSaltSize copy(arr[n:], p.hash) n += encodedHashSize return arr[:n] } func (p *hashed) decodeVersion(sbytes []byte) (int, error) { if sbytes[0] != '$' { return -1, InvalidHashPrefixError(sbytes[0]) } if sbytes[1] > majorVersion { return -1, HashVersionTooNewError(sbytes[1]) } p.major = sbytes[1] n := 3 if sbytes[2] != '$' { p.minor = sbytes[2] n++ } return n, nil } // sbytes should begin where decodeVersion left off. func (p *hashed) decodeCost(sbytes []byte) (int, error) { cost, err := strconv.Atoi(string(sbytes[0:2])) if err != nil { return -1, err } err = checkCost(cost) if err != nil { return -1, err } p.cost = cost return 3, nil } func (p *hashed) String() string { return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor) } func checkCost(cost int) error { if cost < MinCost || cost > MaxCost { return InvalidCostError(cost) } return nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/bcrypt/base64.go��������������������������������������������0000644�0610621�0607500�00000001461�13172163317�023772� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bcrypt import "encoding/base64" const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" var bcEncoding = base64.NewEncoding(alphabet) func base64Encode(src []byte) []byte { n := bcEncoding.EncodedLen(len(src)) dst := make([]byte, n) bcEncoding.Encode(dst, src) for dst[n-1] == '=' { n-- } return dst[:n] } func base64Decode(src []byte) ([]byte, error) { numOfEquals := 4 - (len(src) % 4) for i := 0; i < numOfEquals; i++ { src = append(src, '=') } dst := make([]byte, bcEncoding.DecodedLen(len(src))) n, err := bcEncoding.Decode(dst, src) if err != nil { return nil, err } return dst[:n], nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163317�021757� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/types_test.go������������������������������������������0000644�0610621�0607500�00000002630�13172163317�024512� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package acme import ( "errors" "net/http" "testing" "time" ) func TestRateLimit(t *testing.T) { now := time.Date(2017, 04, 27, 10, 0, 0, 0, time.UTC) f := timeNow defer func() { timeNow = f }() timeNow = func() time.Time { return now } h120, hTime := http.Header{}, http.Header{} h120.Set("Retry-After", "120") hTime.Set("Retry-After", "Tue Apr 27 11:00:00 2017") err1 := &Error{ ProblemType: "urn:ietf:params:acme:error:nolimit", Header: h120, } err2 := &Error{ ProblemType: "urn:ietf:params:acme:error:rateLimited", Header: h120, } err3 := &Error{ ProblemType: "urn:ietf:params:acme:error:rateLimited", Header: nil, } err4 := &Error{ ProblemType: "urn:ietf:params:acme:error:rateLimited", Header: hTime, } tt := []struct { err error res time.Duration ok bool }{ {nil, 0, false}, {errors.New("dummy"), 0, false}, {err1, 0, false}, {err2, 2 * time.Minute, true}, {err3, 0, true}, {err4, time.Hour, true}, } for i, test := range tt { res, ok := RateLimit(test.err) if ok != test.ok { t.Errorf("%d: RateLimit(%+v): ok = %v; want %v", i, test.err, ok, test.ok) continue } if res != test.res { t.Errorf("%d: RateLimit(%+v) = %v; want %v", i, test.err, res, test.res) } } } ��������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/types.go�����������������������������������������������0000644�0610621�0607500�00000022467�13172163317�023465� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package acme import ( "crypto" "crypto/x509" "errors" "fmt" "net/http" "strings" "time" ) // ACME server response statuses used to describe Authorization and Challenge states. const ( StatusUnknown = "unknown" StatusPending = "pending" StatusProcessing = "processing" StatusValid = "valid" StatusInvalid = "invalid" StatusRevoked = "revoked" ) // CRLReasonCode identifies the reason for a certificate revocation. type CRLReasonCode int // CRL reason codes as defined in RFC 5280. const ( CRLReasonUnspecified CRLReasonCode = 0 CRLReasonKeyCompromise CRLReasonCode = 1 CRLReasonCACompromise CRLReasonCode = 2 CRLReasonAffiliationChanged CRLReasonCode = 3 CRLReasonSuperseded CRLReasonCode = 4 CRLReasonCessationOfOperation CRLReasonCode = 5 CRLReasonCertificateHold CRLReasonCode = 6 CRLReasonRemoveFromCRL CRLReasonCode = 8 CRLReasonPrivilegeWithdrawn CRLReasonCode = 9 CRLReasonAACompromise CRLReasonCode = 10 ) // ErrUnsupportedKey is returned when an unsupported key type is encountered. var ErrUnsupportedKey = errors.New("acme: unknown key type; only RSA and ECDSA are supported") // Error is an ACME error, defined in Problem Details for HTTP APIs doc // http://tools.ietf.org/html/draft-ietf-appsawg-http-problem. type Error struct { // StatusCode is The HTTP status code generated by the origin server. StatusCode int // ProblemType is a URI reference that identifies the problem type, // typically in a "urn:acme:error:xxx" form. ProblemType string // Detail is a human-readable explanation specific to this occurrence of the problem. Detail string // Header is the original server error response headers. // It may be nil. Header http.Header } func (e *Error) Error() string { return fmt.Sprintf("%d %s: %s", e.StatusCode, e.ProblemType, e.Detail) } // AuthorizationError indicates that an authorization for an identifier // did not succeed. // It contains all errors from Challenge items of the failed Authorization. type AuthorizationError struct { // URI uniquely identifies the failed Authorization. URI string // Identifier is an AuthzID.Value of the failed Authorization. Identifier string // Errors is a collection of non-nil error values of Challenge items // of the failed Authorization. Errors []error } func (a *AuthorizationError) Error() string { e := make([]string, len(a.Errors)) for i, err := range a.Errors { e[i] = err.Error() } return fmt.Sprintf("acme: authorization error for %s: %s", a.Identifier, strings.Join(e, "; ")) } // RateLimit reports whether err represents a rate limit error and // any Retry-After duration returned by the server. // // See the following for more details on rate limiting: // https://tools.ietf.org/html/draft-ietf-acme-acme-05#section-5.6 func RateLimit(err error) (time.Duration, bool) { e, ok := err.(*Error) if !ok { return 0, false } // Some CA implementations may return incorrect values. // Use case-insensitive comparison. if !strings.HasSuffix(strings.ToLower(e.ProblemType), ":ratelimited") { return 0, false } if e.Header == nil { return 0, true } return retryAfter(e.Header.Get("Retry-After"), 0), true } // Account is a user account. It is associated with a private key. type Account struct { // URI is the account unique ID, which is also a URL used to retrieve // account data from the CA. URI string // Contact is a slice of contact info used during registration. Contact []string // The terms user has agreed to. // A value not matching CurrentTerms indicates that the user hasn't agreed // to the actual Terms of Service of the CA. AgreedTerms string // Actual terms of a CA. CurrentTerms string // Authz is the authorization URL used to initiate a new authz flow. Authz string // Authorizations is a URI from which a list of authorizations // granted to this account can be fetched via a GET request. Authorizations string // Certificates is a URI from which a list of certificates // issued for this account can be fetched via a GET request. Certificates string } // Directory is ACME server discovery data. type Directory struct { // RegURL is an account endpoint URL, allowing for creating new // and modifying existing accounts. RegURL string // AuthzURL is used to initiate Identifier Authorization flow. AuthzURL string // CertURL is a new certificate issuance endpoint URL. CertURL string // RevokeURL is used to initiate a certificate revocation flow. RevokeURL string // Term is a URI identifying the current terms of service. Terms string // Website is an HTTP or HTTPS URL locating a website // providing more information about the ACME server. Website string // CAA consists of lowercase hostname elements, which the ACME server // recognises as referring to itself for the purposes of CAA record validation // as defined in RFC6844. CAA []string } // Challenge encodes a returned CA challenge. // Its Error field may be non-nil if the challenge is part of an Authorization // with StatusInvalid. type Challenge struct { // Type is the challenge type, e.g. "http-01", "tls-sni-02", "dns-01". Type string // URI is where a challenge response can be posted to. URI string // Token is a random value that uniquely identifies the challenge. Token string // Status identifies the status of this challenge. Status string // Error indicates the reason for an authorization failure // when this challenge was used. // The type of a non-nil value is *Error. Error error } // Authorization encodes an authorization response. type Authorization struct { // URI uniquely identifies a authorization. URI string // Status identifies the status of an authorization. Status string // Identifier is what the account is authorized to represent. Identifier AuthzID // Challenges that the client needs to fulfill in order to prove possession // of the identifier (for pending authorizations). // For final authorizations, the challenges that were used. Challenges []*Challenge // A collection of sets of challenges, each of which would be sufficient // to prove possession of the identifier. // Clients must complete a set of challenges that covers at least one set. // Challenges are identified by their indices in the challenges array. // If this field is empty, the client needs to complete all challenges. Combinations [][]int } // AuthzID is an identifier that an account is authorized to represent. type AuthzID struct { Type string // The type of identifier, e.g. "dns". Value string // The identifier itself, e.g. "example.org". } // wireAuthz is ACME JSON representation of Authorization objects. type wireAuthz struct { Status string Challenges []wireChallenge Combinations [][]int Identifier struct { Type string Value string } } func (z *wireAuthz) authorization(uri string) *Authorization { a := &Authorization{ URI: uri, Status: z.Status, Identifier: AuthzID{Type: z.Identifier.Type, Value: z.Identifier.Value}, Combinations: z.Combinations, // shallow copy Challenges: make([]*Challenge, len(z.Challenges)), } for i, v := range z.Challenges { a.Challenges[i] = v.challenge() } return a } func (z *wireAuthz) error(uri string) *AuthorizationError { err := &AuthorizationError{ URI: uri, Identifier: z.Identifier.Value, } for _, raw := range z.Challenges { if raw.Error != nil { err.Errors = append(err.Errors, raw.Error.error(nil)) } } return err } // wireChallenge is ACME JSON challenge representation. type wireChallenge struct { URI string `json:"uri"` Type string Token string Status string Error *wireError } func (c *wireChallenge) challenge() *Challenge { v := &Challenge{ URI: c.URI, Type: c.Type, Token: c.Token, Status: c.Status, } if v.Status == "" { v.Status = StatusPending } if c.Error != nil { v.Error = c.Error.error(nil) } return v } // wireError is a subset of fields of the Problem Details object // as described in https://tools.ietf.org/html/rfc7807#section-3.1. type wireError struct { Status int Type string Detail string } func (e *wireError) error(h http.Header) *Error { return &Error{ StatusCode: e.Status, ProblemType: e.Type, Detail: e.Detail, Header: h, } } // CertOption is an optional argument type for the TLSSNIxChallengeCert methods for // customizing a temporary certificate for TLS-SNI challenges. type CertOption interface { privateCertOpt() } // WithKey creates an option holding a private/public key pair. // The private part signs a certificate, and the public part represents the signee. func WithKey(key crypto.Signer) CertOption { return &certOptKey{key} } type certOptKey struct { key crypto.Signer } func (*certOptKey) privateCertOpt() {} // WithTemplate creates an option for specifying a certificate template. // See x509.CreateCertificate for template usage details. // // In TLSSNIxChallengeCert methods, the template is also used as parent, // resulting in a self-signed certificate. // The DNSNames field of t is always overwritten for tls-sni challenge certs. func WithTemplate(t *x509.Certificate) CertOption { return (*certOptTemplate)(t) } type certOptTemplate x509.Certificate func (*certOptTemplate) privateCertOpt() {} ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/jws_test.go��������������������������������������������0000644�0610621�0607500�00000025405�13172163317�024156� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package acme import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/json" "encoding/pem" "fmt" "math/big" "testing" ) const ( testKeyPEM = ` -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA4xgZ3eRPkwoRvy7qeRUbmMDe0V+xH9eWLdu0iheeLlrmD2mq WXfP9IeSKApbn34g8TuAS9g5zhq8ELQ3kmjr+KV86GAMgI6VAcGlq3QrzpTCf/30 Ab7+zawrfRaFONa1HwEzPY1KHnGVkxJc85gNkwYI9SY2RHXtvln3zs5wITNrdosq EXeaIkVYBEhbhNu54pp3kxo6TuWLi9e6pXeWetEwmlBwtWZlPoib2j3TxLBksKZf oyFyek380mHgJAumQ/I2fjj98/97mk3ihOY4AgVdCDj1z/GCoZkG5Rq7nbCGyosy KWyDX00Zs+nNqVhoLeIvXC4nnWdJMZ6rogxyQQIDAQABAoIBACIEZTOI1Kao9nmV 9IeIsuaR1Y61b9neOF/MLmIVIZu+AAJFCMB4Iw11FV6sFodwpEyeZhx2WkpWVN+H r19eGiLX3zsL0DOdqBJoSIHDWCCMxgnYJ6nvS0nRxX3qVrBp8R2g12Ub+gNPbmFm ecf/eeERIVxfifd9VsyRu34eDEvcmKFuLYbElFcPh62xE3x12UZvV/sN7gXbawpP G+w255vbE5MoaKdnnO83cTFlcHvhn24M/78qP7Te5OAeelr1R89kYxQLpuGe4fbS zc6E3ym5Td6urDetGGrSY1Eu10/8sMusX+KNWkm+RsBRbkyKq72ks/qKpOxOa+c6 9gm+Y8ECgYEA/iNUyg1ubRdH11p82l8KHtFC1DPE0V1gSZsX29TpM5jS4qv46K+s 8Ym1zmrORM8x+cynfPx1VQZQ34EYeCMIX212ryJ+zDATl4NE0I4muMvSiH9vx6Xc 7FmhNnaYzPsBL5Tm9nmtQuP09YEn8poiOJFiDs/4olnD5ogA5O4THGkCgYEA5MIL qWYBUuqbEWLRtMruUtpASclrBqNNsJEsMGbeqBJmoMxdHeSZckbLOrqm7GlMyNRJ Ne/5uWRGSzaMYuGmwsPpERzqEvYFnSrpjW5YtXZ+JtxFXNVfm9Z1gLLgvGpOUCIU RbpoDckDe1vgUuk3y5+DjZihs+rqIJ45XzXTzBkCgYBWuf3segruJZy5rEKhTv+o JqeUvRn0jNYYKFpLBeyTVBrbie6GkbUGNIWbrK05pC+c3K9nosvzuRUOQQL1tJbd 4gA3oiD9U4bMFNr+BRTHyZ7OQBcIXdz3t1qhuHVKtnngIAN1p25uPlbRFUNpshnt jgeVoHlsBhApcs5DUc+pyQKBgDzeHPg/+g4z+nrPznjKnktRY1W+0El93kgi+J0Q YiJacxBKEGTJ1MKBb8X6sDurcRDm22wMpGfd9I5Cv2v4GsUsF7HD/cx5xdih+G73 c4clNj/k0Ff5Nm1izPUno4C+0IOl7br39IPmfpSuR6wH/h6iHQDqIeybjxyKvT1G N0rRAoGBAKGD+4ZI/E1MoJ5CXB8cDDMHagbE3cq/DtmYzE2v1DFpQYu5I4PCm5c7 EQeIP6dZtv8IMgtGIb91QX9pXvP0aznzQKwYIA8nZgoENCPfiMTPiEDT9e/0lObO 9XWsXpbSTsRPj0sv1rB+UzBJ0PgjK4q2zOF0sNo7b1+6nlM3BWPx -----END RSA PRIVATE KEY----- ` // This thumbprint is for the testKey defined above. testKeyThumbprint = "6nicxzh6WETQlrvdchkz-U3e3DOQZ4heJKU63rfqMqQ" // openssl ecparam -name secp256k1 -genkey -noout testKeyECPEM = ` -----BEGIN EC PRIVATE KEY----- MHcCAQEEIK07hGLr0RwyUdYJ8wbIiBS55CjnkMD23DWr+ccnypWLoAoGCCqGSM49 AwEHoUQDQgAE5lhEug5xK4xBDZ2nAbaxLtaLiv85bxJ7ePd1dkO23HThqIrvawF5 QAaS/RNouybCiRhRjI3EaxLkQwgrCw0gqQ== -----END EC PRIVATE KEY----- ` // openssl ecparam -name secp384r1 -genkey -noout testKeyEC384PEM = ` -----BEGIN EC PRIVATE KEY----- MIGkAgEBBDAQ4lNtXRORWr1bgKR1CGysr9AJ9SyEk4jiVnlUWWUChmSNL+i9SLSD Oe/naPqXJ6CgBwYFK4EEACKhZANiAAQzKtj+Ms0vHoTX5dzv3/L5YMXOWuI5UKRj JigpahYCqXD2BA1j0E/2xt5vlPf+gm0PL+UHSQsCokGnIGuaHCsJAp3ry0gHQEke WYXapUUFdvaK1R2/2hn5O+eiQM8YzCg= -----END EC PRIVATE KEY----- ` // openssl ecparam -name secp521r1 -genkey -noout testKeyEC512PEM = ` -----BEGIN EC PRIVATE KEY----- MIHcAgEBBEIBSNZKFcWzXzB/aJClAb305ibalKgtDA7+70eEkdPt28/3LZMM935Z KqYHh/COcxuu3Kt8azRAUz3gyr4zZKhlKUSgBwYFK4EEACOhgYkDgYYABAHUNKbx 7JwC7H6pa2sV0tERWhHhB3JmW+OP6SUgMWryvIKajlx73eS24dy4QPGrWO9/ABsD FqcRSkNVTXnIv6+0mAF25knqIBIg5Q8M9BnOu9GGAchcwt3O7RDHmqewnJJDrbjd GGnm6rb+NnWR9DIopM0nKNkToWoF/hzopxu4Ae/GsQ== -----END EC PRIVATE KEY----- ` // 1. openssl ec -in key.pem -noout -text // 2. remove first byte, 04 (the header); the rest is X and Y // 3. convert each with: echo <val> | xxd -r -p | base64 -w 100 | tr -d '=' | tr '/+' '_-' testKeyECPubX = "5lhEug5xK4xBDZ2nAbaxLtaLiv85bxJ7ePd1dkO23HQ" testKeyECPubY = "4aiK72sBeUAGkv0TaLsmwokYUYyNxGsS5EMIKwsNIKk" testKeyEC384PubX = "MyrY_jLNLx6E1-Xc79_y-WDFzlriOVCkYyYoKWoWAqlw9gQNY9BP9sbeb5T3_oJt" testKeyEC384PubY = "Dy_lB0kLAqJBpyBrmhwrCQKd68tIB0BJHlmF2qVFBXb2itUdv9oZ-TvnokDPGMwo" testKeyEC512PubX = "AdQ0pvHsnALsfqlraxXS0RFaEeEHcmZb44_pJSAxavK8gpqOXHvd5Lbh3LhA8atY738AGwMWpxFKQ1VNeci_r7SY" testKeyEC512PubY = "AXbmSeogEiDlDwz0Gc670YYByFzC3c7tEMeap7CckkOtuN0Yaebqtv42dZH0MiikzSco2ROhagX-HOinG7gB78ax" // echo -n '{"crv":"P-256","kty":"EC","x":"<testKeyECPubX>","y":"<testKeyECPubY>"}' | \ // openssl dgst -binary -sha256 | base64 | tr -d '=' | tr '/+' '_-' testKeyECThumbprint = "zedj-Bd1Zshp8KLePv2MB-lJ_Hagp7wAwdkA0NUTniU" ) var ( testKey *rsa.PrivateKey testKeyEC *ecdsa.PrivateKey testKeyEC384 *ecdsa.PrivateKey testKeyEC512 *ecdsa.PrivateKey ) func init() { testKey = parseRSA(testKeyPEM, "testKeyPEM") testKeyEC = parseEC(testKeyECPEM, "testKeyECPEM") testKeyEC384 = parseEC(testKeyEC384PEM, "testKeyEC384PEM") testKeyEC512 = parseEC(testKeyEC512PEM, "testKeyEC512PEM") } func decodePEM(s, name string) []byte { d, _ := pem.Decode([]byte(s)) if d == nil { panic("no block found in " + name) } return d.Bytes } func parseRSA(s, name string) *rsa.PrivateKey { b := decodePEM(s, name) k, err := x509.ParsePKCS1PrivateKey(b) if err != nil { panic(fmt.Sprintf("%s: %v", name, err)) } return k } func parseEC(s, name string) *ecdsa.PrivateKey { b := decodePEM(s, name) k, err := x509.ParseECPrivateKey(b) if err != nil { panic(fmt.Sprintf("%s: %v", name, err)) } return k } func TestJWSEncodeJSON(t *testing.T) { claims := struct{ Msg string }{"Hello JWS"} // JWS signed with testKey and "nonce" as the nonce value // JSON-serialized JWS fields are split for easier testing const ( // {"alg":"RS256","jwk":{"e":"AQAB","kty":"RSA","n":"..."},"nonce":"nonce"} protected = "eyJhbGciOiJSUzI1NiIsImp3ayI6eyJlIjoiQVFBQiIsImt0eSI6" + "IlJTQSIsIm4iOiI0eGdaM2VSUGt3b1J2eTdxZVJVYm1NRGUwVi14" + "SDllV0xkdTBpaGVlTGxybUQybXFXWGZQOUllU0tBcGJuMzRnOFR1" + "QVM5ZzV6aHE4RUxRM2ttanItS1Y4NkdBTWdJNlZBY0dscTNRcnpw" + "VENmXzMwQWI3LXphd3JmUmFGT05hMUh3RXpQWTFLSG5HVmt4SmM4" + "NWdOa3dZSTlTWTJSSFh0dmxuM3pzNXdJVE5yZG9zcUVYZWFJa1ZZ" + "QkVoYmhOdTU0cHAza3hvNlR1V0xpOWU2cFhlV2V0RXdtbEJ3dFda" + "bFBvaWIyajNUeExCa3NLWmZveUZ5ZWszODBtSGdKQXVtUV9JMmZq" + "ajk4Xzk3bWszaWhPWTRBZ1ZkQ0RqMXpfR0NvWmtHNVJxN25iQ0d5" + "b3N5S1d5RFgwMFpzLW5OcVZob0xlSXZYQzRubldkSk1aNnJvZ3h5" + "UVEifSwibm9uY2UiOiJub25jZSJ9" // {"Msg":"Hello JWS"} payload = "eyJNc2ciOiJIZWxsbyBKV1MifQ" signature = "eAGUikStX_UxyiFhxSLMyuyBcIB80GeBkFROCpap2sW3EmkU_ggF" + "knaQzxrTfItICSAXsCLIquZ5BbrSWA_4vdEYrwWtdUj7NqFKjHRa" + "zpLHcoR7r1rEHvkoP1xj49lS5fc3Wjjq8JUhffkhGbWZ8ZVkgPdC" + "4tMBWiQDoth-x8jELP_3LYOB_ScUXi2mETBawLgOT2K8rA0Vbbmx" + "hWNlOWuUf-8hL5YX4IOEwsS8JK_TrTq5Zc9My0zHJmaieqDV0UlP" + "k0onFjPFkGm7MrPSgd0MqRG-4vSAg2O4hDo7rKv4n8POjjXlNQvM" + "9IPLr8qZ7usYBKhEGwX3yq_eicAwBw" ) b, err := jwsEncodeJSON(claims, testKey, "nonce") if err != nil { t.Fatal(err) } var jws struct{ Protected, Payload, Signature string } if err := json.Unmarshal(b, &jws); err != nil { t.Fatal(err) } if jws.Protected != protected { t.Errorf("protected:\n%s\nwant:\n%s", jws.Protected, protected) } if jws.Payload != payload { t.Errorf("payload:\n%s\nwant:\n%s", jws.Payload, payload) } if jws.Signature != signature { t.Errorf("signature:\n%s\nwant:\n%s", jws.Signature, signature) } } func TestJWSEncodeJSONEC(t *testing.T) { tt := []struct { key *ecdsa.PrivateKey x, y string alg, crv string }{ {testKeyEC, testKeyECPubX, testKeyECPubY, "ES256", "P-256"}, {testKeyEC384, testKeyEC384PubX, testKeyEC384PubY, "ES384", "P-384"}, {testKeyEC512, testKeyEC512PubX, testKeyEC512PubY, "ES512", "P-521"}, } for i, test := range tt { claims := struct{ Msg string }{"Hello JWS"} b, err := jwsEncodeJSON(claims, test.key, "nonce") if err != nil { t.Errorf("%d: %v", i, err) continue } var jws struct{ Protected, Payload, Signature string } if err := json.Unmarshal(b, &jws); err != nil { t.Errorf("%d: %v", i, err) continue } b, err = base64.RawURLEncoding.DecodeString(jws.Protected) if err != nil { t.Errorf("%d: jws.Protected: %v", i, err) } var head struct { Alg string Nonce string JWK struct { Crv string Kty string X string Y string } `json:"jwk"` } if err := json.Unmarshal(b, &head); err != nil { t.Errorf("%d: jws.Protected: %v", i, err) } if head.Alg != test.alg { t.Errorf("%d: head.Alg = %q; want %q", i, head.Alg, test.alg) } if head.Nonce != "nonce" { t.Errorf("%d: head.Nonce = %q; want nonce", i, head.Nonce) } if head.JWK.Crv != test.crv { t.Errorf("%d: head.JWK.Crv = %q; want %q", i, head.JWK.Crv, test.crv) } if head.JWK.Kty != "EC" { t.Errorf("%d: head.JWK.Kty = %q; want EC", i, head.JWK.Kty) } if head.JWK.X != test.x { t.Errorf("%d: head.JWK.X = %q; want %q", i, head.JWK.X, test.x) } if head.JWK.Y != test.y { t.Errorf("%d: head.JWK.Y = %q; want %q", i, head.JWK.Y, test.y) } } } func TestJWKThumbprintRSA(t *testing.T) { // Key example from RFC 7638 const base64N = "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAt" + "VT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn6" + "4tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FD" + "W2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n9" + "1CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINH" + "aQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw" const base64E = "AQAB" const expected = "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs" b, err := base64.RawURLEncoding.DecodeString(base64N) if err != nil { t.Fatalf("Error parsing example key N: %v", err) } n := new(big.Int).SetBytes(b) b, err = base64.RawURLEncoding.DecodeString(base64E) if err != nil { t.Fatalf("Error parsing example key E: %v", err) } e := new(big.Int).SetBytes(b) pub := &rsa.PublicKey{N: n, E: int(e.Uint64())} th, err := JWKThumbprint(pub) if err != nil { t.Error(err) } if th != expected { t.Errorf("thumbprint = %q; want %q", th, expected) } } func TestJWKThumbprintEC(t *testing.T) { // Key example from RFC 7520 // expected was computed with // echo -n '{"crv":"P-521","kty":"EC","x":"<base64X>","y":"<base64Y>"}' | \ // openssl dgst -binary -sha256 | \ // base64 | \ // tr -d '=' | tr '/+' '_-' const ( base64X = "AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9A5RkT" + "KqjqvjyekWF-7ytDyRXYgCF5cj0Kt" base64Y = "AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVySsUda" + "QkAgDPrwQrJmbnX9cwlGfP-HqHZR1" expected = "dHri3SADZkrush5HU_50AoRhcKFryN-PI6jPBtPL55M" ) b, err := base64.RawURLEncoding.DecodeString(base64X) if err != nil { t.Fatalf("Error parsing example key X: %v", err) } x := new(big.Int).SetBytes(b) b, err = base64.RawURLEncoding.DecodeString(base64Y) if err != nil { t.Fatalf("Error parsing example key Y: %v", err) } y := new(big.Int).SetBytes(b) pub := &ecdsa.PublicKey{Curve: elliptic.P521(), X: x, Y: y} th, err := JWKThumbprint(pub) if err != nil { t.Error(err) } if th != expected { t.Errorf("thumbprint = %q; want %q", th, expected) } } func TestJWKThumbprintErrUnsupportedKey(t *testing.T) { _, err := JWKThumbprint(struct{}{}) if err != ErrUnsupportedKey { t.Errorf("err = %q; want %q", err, ErrUnsupportedKey) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/jws.go�������������������������������������������������0000644�0610621�0607500�00000010315�13172163317�023111� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package acme import ( "crypto" "crypto/ecdsa" "crypto/rand" "crypto/rsa" "crypto/sha256" _ "crypto/sha512" // need for EC keys "encoding/base64" "encoding/json" "fmt" "math/big" ) // jwsEncodeJSON signs claimset using provided key and a nonce. // The result is serialized in JSON format. // See https://tools.ietf.org/html/rfc7515#section-7. func jwsEncodeJSON(claimset interface{}, key crypto.Signer, nonce string) ([]byte, error) { jwk, err := jwkEncode(key.Public()) if err != nil { return nil, err } alg, sha := jwsHasher(key) if alg == "" || !sha.Available() { return nil, ErrUnsupportedKey } phead := fmt.Sprintf(`{"alg":%q,"jwk":%s,"nonce":%q}`, alg, jwk, nonce) phead = base64.RawURLEncoding.EncodeToString([]byte(phead)) cs, err := json.Marshal(claimset) if err != nil { return nil, err } payload := base64.RawURLEncoding.EncodeToString(cs) hash := sha.New() hash.Write([]byte(phead + "." + payload)) sig, err := jwsSign(key, sha, hash.Sum(nil)) if err != nil { return nil, err } enc := struct { Protected string `json:"protected"` Payload string `json:"payload"` Sig string `json:"signature"` }{ Protected: phead, Payload: payload, Sig: base64.RawURLEncoding.EncodeToString(sig), } return json.Marshal(&enc) } // jwkEncode encodes public part of an RSA or ECDSA key into a JWK. // The result is also suitable for creating a JWK thumbprint. // https://tools.ietf.org/html/rfc7517 func jwkEncode(pub crypto.PublicKey) (string, error) { switch pub := pub.(type) { case *rsa.PublicKey: // https://tools.ietf.org/html/rfc7518#section-6.3.1 n := pub.N e := big.NewInt(int64(pub.E)) // Field order is important. // See https://tools.ietf.org/html/rfc7638#section-3.3 for details. return fmt.Sprintf(`{"e":"%s","kty":"RSA","n":"%s"}`, base64.RawURLEncoding.EncodeToString(e.Bytes()), base64.RawURLEncoding.EncodeToString(n.Bytes()), ), nil case *ecdsa.PublicKey: // https://tools.ietf.org/html/rfc7518#section-6.2.1 p := pub.Curve.Params() n := p.BitSize / 8 if p.BitSize%8 != 0 { n++ } x := pub.X.Bytes() if n > len(x) { x = append(make([]byte, n-len(x)), x...) } y := pub.Y.Bytes() if n > len(y) { y = append(make([]byte, n-len(y)), y...) } // Field order is important. // See https://tools.ietf.org/html/rfc7638#section-3.3 for details. return fmt.Sprintf(`{"crv":"%s","kty":"EC","x":"%s","y":"%s"}`, p.Name, base64.RawURLEncoding.EncodeToString(x), base64.RawURLEncoding.EncodeToString(y), ), nil } return "", ErrUnsupportedKey } // jwsSign signs the digest using the given key. // It returns ErrUnsupportedKey if the key type is unknown. // The hash is used only for RSA keys. func jwsSign(key crypto.Signer, hash crypto.Hash, digest []byte) ([]byte, error) { switch key := key.(type) { case *rsa.PrivateKey: return key.Sign(rand.Reader, digest, hash) case *ecdsa.PrivateKey: r, s, err := ecdsa.Sign(rand.Reader, key, digest) if err != nil { return nil, err } rb, sb := r.Bytes(), s.Bytes() size := key.Params().BitSize / 8 if size%8 > 0 { size++ } sig := make([]byte, size*2) copy(sig[size-len(rb):], rb) copy(sig[size*2-len(sb):], sb) return sig, nil } return nil, ErrUnsupportedKey } // jwsHasher indicates suitable JWS algorithm name and a hash function // to use for signing a digest with the provided key. // It returns ("", 0) if the key is not supported. func jwsHasher(key crypto.Signer) (string, crypto.Hash) { switch key := key.(type) { case *rsa.PrivateKey: return "RS256", crypto.SHA256 case *ecdsa.PrivateKey: switch key.Params().Name { case "P-256": return "ES256", crypto.SHA256 case "P-384": return "ES384", crypto.SHA384 case "P-521": return "ES512", crypto.SHA512 } } return "", 0 } // JWKThumbprint creates a JWK thumbprint out of pub // as specified in https://tools.ietf.org/html/rfc7638. func JWKThumbprint(pub crypto.PublicKey) (string, error) { jwk, err := jwkEncode(pub) if err != nil { return "", err } b := sha256.Sum256([]byte(jwk)) return base64.RawURLEncoding.EncodeToString(b[:]), nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/����������������������������������������������0000755�0610621�0607500�00000000000�13172163317�023605� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/renewal_test.go�������������������������������0000644�0610621�0607500�00000011313�13172163317�026627� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package autocert import ( "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/tls" "crypto/x509" "encoding/base64" "fmt" "net/http" "net/http/httptest" "testing" "time" "golang.org/x/crypto/acme" ) func TestRenewalNext(t *testing.T) { now := time.Now() timeNow = func() time.Time { return now } defer func() { timeNow = time.Now }() man := &Manager{RenewBefore: 7 * 24 * time.Hour} defer man.stopRenew() tt := []struct { expiry time.Time min, max time.Duration }{ {now.Add(90 * 24 * time.Hour), 83*24*time.Hour - renewJitter, 83 * 24 * time.Hour}, {now.Add(time.Hour), 0, 1}, {now, 0, 1}, {now.Add(-time.Hour), 0, 1}, } dr := &domainRenewal{m: man} for i, test := range tt { next := dr.next(test.expiry) if next < test.min || test.max < next { t.Errorf("%d: next = %v; want between %v and %v", i, next, test.min, test.max) } } } func TestRenewFromCache(t *testing.T) { const domain = "example.org" // ACME CA server stub var ca *httptest.Server ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Replay-Nonce", "nonce") if r.Method == "HEAD" { // a nonce request return } switch r.URL.Path { // discovery case "/": if err := discoTmpl.Execute(w, ca.URL); err != nil { t.Fatalf("discoTmpl: %v", err) } // client key registration case "/new-reg": w.Write([]byte("{}")) // domain authorization case "/new-authz": w.Header().Set("Location", ca.URL+"/authz/1") w.WriteHeader(http.StatusCreated) w.Write([]byte(`{"status": "valid"}`)) // cert request case "/new-cert": var req struct { CSR string `json:"csr"` } decodePayload(&req, r.Body) b, _ := base64.RawURLEncoding.DecodeString(req.CSR) csr, err := x509.ParseCertificateRequest(b) if err != nil { t.Fatalf("new-cert: CSR: %v", err) } der, err := dummyCert(csr.PublicKey, domain) if err != nil { t.Fatalf("new-cert: dummyCert: %v", err) } chainUp := fmt.Sprintf("<%s/ca-cert>; rel=up", ca.URL) w.Header().Set("Link", chainUp) w.WriteHeader(http.StatusCreated) w.Write(der) // CA chain cert case "/ca-cert": der, err := dummyCert(nil, "ca") if err != nil { t.Fatalf("ca-cert: dummyCert: %v", err) } w.Write(der) default: t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path) } })) defer ca.Close() // use EC key to run faster on 386 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } man := &Manager{ Prompt: AcceptTOS, Cache: newMemCache(), RenewBefore: 24 * time.Hour, Client: &acme.Client{ Key: key, DirectoryURL: ca.URL, }, } defer man.stopRenew() // cache an almost expired cert now := time.Now() cert, err := dateDummyCert(key.Public(), now.Add(-2*time.Hour), now.Add(time.Minute), domain) if err != nil { t.Fatal(err) } tlscert := &tls.Certificate{PrivateKey: key, Certificate: [][]byte{cert}} if err := man.cachePut(context.Background(), domain, tlscert); err != nil { t.Fatal(err) } // veriy the renewal happened defer func() { testDidRenewLoop = func(next time.Duration, err error) {} }() done := make(chan struct{}) testDidRenewLoop = func(next time.Duration, err error) { defer close(done) if err != nil { t.Errorf("testDidRenewLoop: %v", err) } // Next should be about 90 days: // dummyCert creates 90days expiry + account for man.RenewBefore. // Previous expiration was within 1 min. future := 88 * 24 * time.Hour if next < future { t.Errorf("testDidRenewLoop: next = %v; want >= %v", next, future) } // ensure the new cert is cached after := time.Now().Add(future) tlscert, err := man.cacheGet(context.Background(), domain) if err != nil { t.Fatalf("man.cacheGet: %v", err) } if !tlscert.Leaf.NotAfter.After(after) { t.Errorf("cache leaf.NotAfter = %v; want > %v", tlscert.Leaf.NotAfter, after) } // verify the old cert is also replaced in memory man.stateMu.Lock() defer man.stateMu.Unlock() s := man.state[domain] if s == nil { t.Fatalf("m.state[%q] is nil", domain) } tlscert, err = s.tlscert() if err != nil { t.Fatalf("s.tlscert: %v", err) } if !tlscert.Leaf.NotAfter.After(after) { t.Errorf("state leaf.NotAfter = %v; want > %v", tlscert.Leaf.NotAfter, after) } } // trigger renew hello := &tls.ClientHelloInfo{ServerName: domain} if _, err := man.GetCertificate(hello); err != nil { t.Fatal(err) } // wait for renew loop select { case <-time.After(10 * time.Second): t.Fatal("renew took too long to occur") case <-done: } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/renewal.go������������������������������������0000644�0610621�0607500�00000006255�13172163317�025601� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package autocert import ( "context" "crypto" "sync" "time" ) // renewJitter is the maximum deviation from Manager.RenewBefore. const renewJitter = time.Hour // domainRenewal tracks the state used by the periodic timers // renewing a single domain's cert. type domainRenewal struct { m *Manager domain string key crypto.Signer timerMu sync.Mutex timer *time.Timer } // start starts a cert renewal timer at the time // defined by the certificate expiration time exp. // // If the timer is already started, calling start is a noop. func (dr *domainRenewal) start(exp time.Time) { dr.timerMu.Lock() defer dr.timerMu.Unlock() if dr.timer != nil { return } dr.timer = time.AfterFunc(dr.next(exp), dr.renew) } // stop stops the cert renewal timer. // If the timer is already stopped, calling stop is a noop. func (dr *domainRenewal) stop() { dr.timerMu.Lock() defer dr.timerMu.Unlock() if dr.timer == nil { return } dr.timer.Stop() dr.timer = nil } // renew is called periodically by a timer. // The first renew call is kicked off by dr.start. func (dr *domainRenewal) renew() { dr.timerMu.Lock() defer dr.timerMu.Unlock() if dr.timer == nil { return } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() // TODO: rotate dr.key at some point? next, err := dr.do(ctx) if err != nil { next = renewJitter / 2 next += time.Duration(pseudoRand.int63n(int64(next))) } dr.timer = time.AfterFunc(next, dr.renew) testDidRenewLoop(next, err) } // do is similar to Manager.createCert but it doesn't lock a Manager.state item. // Instead, it requests a new certificate independently and, upon success, // replaces dr.m.state item with a new one and updates cache for the given domain. // // It may return immediately if the expiration date of the currently cached cert // is far enough in the future. // // The returned value is a time interval after which the renewal should occur again. func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) { // a race is likely unavoidable in a distributed environment // but we try nonetheless if tlscert, err := dr.m.cacheGet(ctx, dr.domain); err == nil { next := dr.next(tlscert.Leaf.NotAfter) if next > dr.m.renewBefore()+renewJitter { return next, nil } } der, leaf, err := dr.m.authorizedCert(ctx, dr.key, dr.domain) if err != nil { return 0, err } state := &certState{ key: dr.key, cert: der, leaf: leaf, } tlscert, err := state.tlscert() if err != nil { return 0, err } dr.m.cachePut(ctx, dr.domain, tlscert) dr.m.stateMu.Lock() defer dr.m.stateMu.Unlock() // m.state is guaranteed to be non-nil at this point dr.m.state[dr.domain] = state return dr.next(leaf.NotAfter), nil } func (dr *domainRenewal) next(expiry time.Time) time.Duration { d := expiry.Sub(timeNow()) - dr.m.renewBefore() // add a bit of randomness to renew deadline n := pseudoRand.int63n(int64(renewJitter)) d -= time.Duration(n) if d < 0 { return 0 } return d } var testDidRenewLoop = func(next time.Duration, err error) {} ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/listener.go�����������������������������������0000644�0610621�0607500�00000011125�13172163317�025761� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package autocert import ( "crypto/tls" "log" "net" "os" "path/filepath" "runtime" "time" ) // NewListener returns a net.Listener that listens on the standard TLS // port (443) on all interfaces and returns *tls.Conn connections with // LetsEncrypt certificates for the provided domain or domains. // // It enables one-line HTTPS servers: // // log.Fatal(http.Serve(autocert.NewListener("example.com"), handler)) // // NewListener is a convenience function for a common configuration. // More complex or custom configurations can use the autocert.Manager // type instead. // // Use of this function implies acceptance of the LetsEncrypt Terms of // Service. If domains is not empty, the provided domains are passed // to HostWhitelist. If domains is empty, the listener will do // LetsEncrypt challenges for any requested domain, which is not // recommended. // // Certificates are cached in a "golang-autocert" directory under an // operating system-specific cache or temp directory. This may not // be suitable for servers spanning multiple machines. // // The returned listener uses a *tls.Config that enables HTTP/2, and // should only be used with servers that support HTTP/2. // // The returned Listener also enables TCP keep-alives on the accepted // connections. The returned *tls.Conn are returned before their TLS // handshake has completed. func NewListener(domains ...string) net.Listener { m := &Manager{ Prompt: AcceptTOS, } if len(domains) > 0 { m.HostPolicy = HostWhitelist(domains...) } dir := cacheDir() if err := os.MkdirAll(dir, 0700); err != nil { log.Printf("warning: autocert.NewListener not using a cache: %v", err) } else { m.Cache = DirCache(dir) } return m.Listener() } // Listener listens on the standard TLS port (443) on all interfaces // and returns a net.Listener returning *tls.Conn connections. // // The returned listener uses a *tls.Config that enables HTTP/2, and // should only be used with servers that support HTTP/2. // // The returned Listener also enables TCP keep-alives on the accepted // connections. The returned *tls.Conn are returned before their TLS // handshake has completed. // // Unlike NewListener, it is the caller's responsibility to initialize // the Manager m's Prompt, Cache, HostPolicy, and other desired options. func (m *Manager) Listener() net.Listener { ln := &listener{ m: m, conf: &tls.Config{ GetCertificate: m.GetCertificate, // bonus: panic on nil m NextProtos: []string{"h2", "http/1.1"}, // Enable HTTP/2 }, } ln.tcpListener, ln.tcpListenErr = net.Listen("tcp", ":443") return ln } type listener struct { m *Manager conf *tls.Config tcpListener net.Listener tcpListenErr error } func (ln *listener) Accept() (net.Conn, error) { if ln.tcpListenErr != nil { return nil, ln.tcpListenErr } conn, err := ln.tcpListener.Accept() if err != nil { return nil, err } tcpConn := conn.(*net.TCPConn) // Because Listener is a convenience function, help out with // this too. This is not possible for the caller to set once // we return a *tcp.Conn wrapping an inaccessible net.Conn. // If callers don't want this, they can do things the manual // way and tweak as needed. But this is what net/http does // itself, so copy that. If net/http changes, we can change // here too. tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(3 * time.Minute) return tls.Server(tcpConn, ln.conf), nil } func (ln *listener) Addr() net.Addr { if ln.tcpListener != nil { return ln.tcpListener.Addr() } // net.Listen failed. Return something non-nil in case callers // call Addr before Accept: return &net.TCPAddr{IP: net.IP{0, 0, 0, 0}, Port: 443} } func (ln *listener) Close() error { if ln.tcpListenErr != nil { return ln.tcpListenErr } return ln.tcpListener.Close() } func homeDir() string { if runtime.GOOS == "windows" { return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") } if h := os.Getenv("HOME"); h != "" { return h } return "/" } func cacheDir() string { const base = "golang-autocert" switch runtime.GOOS { case "darwin": return filepath.Join(homeDir(), "Library", "Caches", base) case "windows": for _, ev := range []string{"APPDATA", "CSIDL_APPDATA", "TEMP", "TMP"} { if v := os.Getenv(ev); v != "" { return filepath.Join(v, base) } } // Worst case: return filepath.Join(homeDir(), base) } if xdg := os.Getenv("XDG_CACHE_HOME"); xdg != "" { return filepath.Join(xdg, base) } return filepath.Join(homeDir(), ".cache", base) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/example_test.go�������������������������������0000644�0610621�0607500�00000001523�13172163317�026627� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package autocert_test import ( "crypto/tls" "fmt" "log" "net/http" "golang.org/x/crypto/acme/autocert" ) func ExampleNewListener() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, TLS user! Your config: %+v", r.TLS) }) log.Fatal(http.Serve(autocert.NewListener("example.com"), mux)) } func ExampleManager() { m := autocert.Manager{ Cache: autocert.DirCache("secret-dir"), Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("example.org"), } s := &http.Server{ Addr: ":https", TLSConfig: &tls.Config{GetCertificate: m.GetCertificate}, } s.ListenAndServeTLS("", "") } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/cache_test.go���������������������������������0000644�0610621�0607500�00000002433�13172163317�026240� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package autocert import ( "context" "io/ioutil" "os" "path/filepath" "reflect" "testing" ) // make sure DirCache satisfies Cache interface var _ Cache = DirCache("/") func TestDirCache(t *testing.T) { dir, err := ioutil.TempDir("", "autocert") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) dir = filepath.Join(dir, "certs") // a nonexistent dir cache := DirCache(dir) ctx := context.Background() // test cache miss if _, err := cache.Get(ctx, "nonexistent"); err != ErrCacheMiss { t.Errorf("get: %v; want ErrCacheMiss", err) } // test put/get b1 := []byte{1} if err := cache.Put(ctx, "dummy", b1); err != nil { t.Fatalf("put: %v", err) } b2, err := cache.Get(ctx, "dummy") if err != nil { t.Fatalf("get: %v", err) } if !reflect.DeepEqual(b1, b2) { t.Errorf("b1 = %v; want %v", b1, b2) } name := filepath.Join(dir, "dummy") if _, err := os.Stat(name); err != nil { t.Error(err) } // test delete if err := cache.Delete(ctx, "dummy"); err != nil { t.Fatalf("delete: %v", err) } if _, err := cache.Get(ctx, "dummy"); err != ErrCacheMiss { t.Errorf("get: %v; want ErrCacheMiss", err) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/cache.go��������������������������������������0000644�0610621�0607500�00000006466�13172163317�025213� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package autocert import ( "context" "errors" "io/ioutil" "os" "path/filepath" ) // ErrCacheMiss is returned when a certificate is not found in cache. var ErrCacheMiss = errors.New("acme/autocert: certificate cache miss") // Cache is used by Manager to store and retrieve previously obtained certificates // as opaque data. // // The key argument of the methods refers to a domain name but need not be an FQDN. // Cache implementations should not rely on the key naming pattern. type Cache interface { // Get returns a certificate data for the specified key. // If there's no such key, Get returns ErrCacheMiss. Get(ctx context.Context, key string) ([]byte, error) // Put stores the data in the cache under the specified key. // Underlying implementations may use any data storage format, // as long as the reverse operation, Get, results in the original data. Put(ctx context.Context, key string, data []byte) error // Delete removes a certificate data from the cache under the specified key. // If there's no such key in the cache, Delete returns nil. Delete(ctx context.Context, key string) error } // DirCache implements Cache using a directory on the local filesystem. // If the directory does not exist, it will be created with 0700 permissions. type DirCache string // Get reads a certificate data from the specified file name. func (d DirCache) Get(ctx context.Context, name string) ([]byte, error) { name = filepath.Join(string(d), name) var ( data []byte err error done = make(chan struct{}) ) go func() { data, err = ioutil.ReadFile(name) close(done) }() select { case <-ctx.Done(): return nil, ctx.Err() case <-done: } if os.IsNotExist(err) { return nil, ErrCacheMiss } return data, err } // Put writes the certificate data to the specified file name. // The file will be created with 0600 permissions. func (d DirCache) Put(ctx context.Context, name string, data []byte) error { if err := os.MkdirAll(string(d), 0700); err != nil { return err } done := make(chan struct{}) var err error go func() { defer close(done) var tmp string if tmp, err = d.writeTempFile(name, data); err != nil { return } select { case <-ctx.Done(): // Don't overwrite the file if the context was canceled. default: newName := filepath.Join(string(d), name) err = os.Rename(tmp, newName) } }() select { case <-ctx.Done(): return ctx.Err() case <-done: } return err } // Delete removes the specified file name. func (d DirCache) Delete(ctx context.Context, name string) error { name = filepath.Join(string(d), name) var ( err error done = make(chan struct{}) ) go func() { err = os.Remove(name) close(done) }() select { case <-ctx.Done(): return ctx.Err() case <-done: } if err != nil && !os.IsNotExist(err) { return err } return nil } // writeTempFile writes b to a temporary file, closes the file and returns its path. func (d DirCache) writeTempFile(prefix string, b []byte) (string, error) { // TempFile uses 0600 permissions f, err := ioutil.TempFile(string(d), prefix) if err != nil { return "", err } if _, err := f.Write(b); err != nil { f.Close() return "", err } return f.Name(), f.Close() } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/autocert_test.go������������������������������0000644�0610621�0607500�00000036612�13172163317�027031� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package autocert import ( "context" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/base64" "encoding/json" "fmt" "html/template" "io" "math/big" "net/http" "net/http/httptest" "reflect" "sync" "testing" "time" "golang.org/x/crypto/acme" ) var discoTmpl = template.Must(template.New("disco").Parse(`{ "new-reg": "{{.}}/new-reg", "new-authz": "{{.}}/new-authz", "new-cert": "{{.}}/new-cert" }`)) var authzTmpl = template.Must(template.New("authz").Parse(`{ "status": "pending", "challenges": [ { "uri": "{{.}}/challenge/1", "type": "tls-sni-01", "token": "token-01" }, { "uri": "{{.}}/challenge/2", "type": "tls-sni-02", "token": "token-02" } ] }`)) type memCache struct { mu sync.Mutex keyData map[string][]byte } func (m *memCache) Get(ctx context.Context, key string) ([]byte, error) { m.mu.Lock() defer m.mu.Unlock() v, ok := m.keyData[key] if !ok { return nil, ErrCacheMiss } return v, nil } func (m *memCache) Put(ctx context.Context, key string, data []byte) error { m.mu.Lock() defer m.mu.Unlock() m.keyData[key] = data return nil } func (m *memCache) Delete(ctx context.Context, key string) error { m.mu.Lock() defer m.mu.Unlock() delete(m.keyData, key) return nil } func newMemCache() *memCache { return &memCache{ keyData: make(map[string][]byte), } } func dummyCert(pub interface{}, san ...string) ([]byte, error) { return dateDummyCert(pub, time.Now(), time.Now().Add(90*24*time.Hour), san...) } func dateDummyCert(pub interface{}, start, end time.Time, san ...string) ([]byte, error) { // use EC key to run faster on 386 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return nil, err } t := &x509.Certificate{ SerialNumber: big.NewInt(1), NotBefore: start, NotAfter: end, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageKeyEncipherment, DNSNames: san, } if pub == nil { pub = &key.PublicKey } return x509.CreateCertificate(rand.Reader, t, t, pub, key) } func decodePayload(v interface{}, r io.Reader) error { var req struct{ Payload string } if err := json.NewDecoder(r).Decode(&req); err != nil { return err } payload, err := base64.RawURLEncoding.DecodeString(req.Payload) if err != nil { return err } return json.Unmarshal(payload, v) } func TestGetCertificate(t *testing.T) { man := &Manager{Prompt: AcceptTOS} defer man.stopRenew() hello := &tls.ClientHelloInfo{ServerName: "example.org"} testGetCertificate(t, man, "example.org", hello) } func TestGetCertificate_trailingDot(t *testing.T) { man := &Manager{Prompt: AcceptTOS} defer man.stopRenew() hello := &tls.ClientHelloInfo{ServerName: "example.org."} testGetCertificate(t, man, "example.org", hello) } func TestGetCertificate_ForceRSA(t *testing.T) { man := &Manager{ Prompt: AcceptTOS, Cache: newMemCache(), ForceRSA: true, } defer man.stopRenew() hello := &tls.ClientHelloInfo{ServerName: "example.org"} testGetCertificate(t, man, "example.org", hello) cert, err := man.cacheGet(context.Background(), "example.org") if err != nil { t.Fatalf("man.cacheGet: %v", err) } if _, ok := cert.PrivateKey.(*rsa.PrivateKey); !ok { t.Errorf("cert.PrivateKey is %T; want *rsa.PrivateKey", cert.PrivateKey) } } func TestGetCertificate_nilPrompt(t *testing.T) { man := &Manager{} defer man.stopRenew() url, finish := startACMEServerStub(t, man, "example.org") defer finish() key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } man.Client = &acme.Client{ Key: key, DirectoryURL: url, } hello := &tls.ClientHelloInfo{ServerName: "example.org"} if _, err := man.GetCertificate(hello); err == nil { t.Error("got certificate for example.org; wanted error") } } func TestGetCertificate_expiredCache(t *testing.T) { // Make an expired cert and cache it. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } tmpl := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "example.org"}, NotAfter: time.Now(), } pub, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &pk.PublicKey, pk) if err != nil { t.Fatal(err) } tlscert := &tls.Certificate{ Certificate: [][]byte{pub}, PrivateKey: pk, } man := &Manager{Prompt: AcceptTOS, Cache: newMemCache()} defer man.stopRenew() if err := man.cachePut(context.Background(), "example.org", tlscert); err != nil { t.Fatalf("man.cachePut: %v", err) } // The expired cached cert should trigger a new cert issuance // and return without an error. hello := &tls.ClientHelloInfo{ServerName: "example.org"} testGetCertificate(t, man, "example.org", hello) } func TestGetCertificate_failedAttempt(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) })) defer ts.Close() const example = "example.org" d := createCertRetryAfter f := testDidRemoveState defer func() { createCertRetryAfter = d testDidRemoveState = f }() createCertRetryAfter = 0 done := make(chan struct{}) testDidRemoveState = func(domain string) { if domain != example { t.Errorf("testDidRemoveState: domain = %q; want %q", domain, example) } close(done) } key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } man := &Manager{ Prompt: AcceptTOS, Client: &acme.Client{ Key: key, DirectoryURL: ts.URL, }, } defer man.stopRenew() hello := &tls.ClientHelloInfo{ServerName: example} if _, err := man.GetCertificate(hello); err == nil { t.Error("GetCertificate: err is nil") } select { case <-time.After(5 * time.Second): t.Errorf("took too long to remove the %q state", example) case <-done: man.stateMu.Lock() defer man.stateMu.Unlock() if v, exist := man.state[example]; exist { t.Errorf("state exists for %q: %+v", example, v) } } } // startACMEServerStub runs an ACME server // The domain argument is the expected domain name of a certificate request. func startACMEServerStub(t *testing.T, man *Manager, domain string) (url string, finish func()) { // echo token-02 | shasum -a 256 // then divide result in 2 parts separated by dot tokenCertName := "4e8eb87631187e9ff2153b56b13a4dec.13a35d002e485d60ff37354b32f665d9.token.acme.invalid" verifyTokenCert := func() { hello := &tls.ClientHelloInfo{ServerName: tokenCertName} _, err := man.GetCertificate(hello) if err != nil { t.Errorf("verifyTokenCert: GetCertificate(%q): %v", tokenCertName, err) return } } // ACME CA server stub var ca *httptest.Server ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Replay-Nonce", "nonce") if r.Method == "HEAD" { // a nonce request return } switch r.URL.Path { // discovery case "/": if err := discoTmpl.Execute(w, ca.URL); err != nil { t.Errorf("discoTmpl: %v", err) } // client key registration case "/new-reg": w.Write([]byte("{}")) // domain authorization case "/new-authz": w.Header().Set("Location", ca.URL+"/authz/1") w.WriteHeader(http.StatusCreated) if err := authzTmpl.Execute(w, ca.URL); err != nil { t.Errorf("authzTmpl: %v", err) } // accept tls-sni-02 challenge case "/challenge/2": verifyTokenCert() w.Write([]byte("{}")) // authorization status case "/authz/1": w.Write([]byte(`{"status": "valid"}`)) // cert request case "/new-cert": var req struct { CSR string `json:"csr"` } decodePayload(&req, r.Body) b, _ := base64.RawURLEncoding.DecodeString(req.CSR) csr, err := x509.ParseCertificateRequest(b) if err != nil { t.Errorf("new-cert: CSR: %v", err) } if csr.Subject.CommonName != domain { t.Errorf("CommonName in CSR = %q; want %q", csr.Subject.CommonName, domain) } der, err := dummyCert(csr.PublicKey, domain) if err != nil { t.Errorf("new-cert: dummyCert: %v", err) } chainUp := fmt.Sprintf("<%s/ca-cert>; rel=up", ca.URL) w.Header().Set("Link", chainUp) w.WriteHeader(http.StatusCreated) w.Write(der) // CA chain cert case "/ca-cert": der, err := dummyCert(nil, "ca") if err != nil { t.Errorf("ca-cert: dummyCert: %v", err) } w.Write(der) default: t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path) } })) finish = func() { ca.Close() // make sure token cert was removed cancel := make(chan struct{}) done := make(chan struct{}) go func() { defer close(done) tick := time.NewTicker(100 * time.Millisecond) defer tick.Stop() for { hello := &tls.ClientHelloInfo{ServerName: tokenCertName} if _, err := man.GetCertificate(hello); err != nil { return } select { case <-tick.C: case <-cancel: return } } }() select { case <-done: case <-time.After(5 * time.Second): close(cancel) t.Error("token cert was not removed") <-done } } return ca.URL, finish } // tests man.GetCertificate flow using the provided hello argument. // The domain argument is the expected domain name of a certificate request. func testGetCertificate(t *testing.T, man *Manager, domain string, hello *tls.ClientHelloInfo) { url, finish := startACMEServerStub(t, man, domain) defer finish() // use EC key to run faster on 386 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } man.Client = &acme.Client{ Key: key, DirectoryURL: url, } // simulate tls.Config.GetCertificate var tlscert *tls.Certificate done := make(chan struct{}) go func() { tlscert, err = man.GetCertificate(hello) close(done) }() select { case <-time.After(time.Minute): t.Fatal("man.GetCertificate took too long to return") case <-done: } if err != nil { t.Fatalf("man.GetCertificate: %v", err) } // verify the tlscert is the same we responded with from the CA stub if len(tlscert.Certificate) == 0 { t.Fatal("len(tlscert.Certificate) is 0") } cert, err := x509.ParseCertificate(tlscert.Certificate[0]) if err != nil { t.Fatalf("x509.ParseCertificate: %v", err) } if len(cert.DNSNames) == 0 || cert.DNSNames[0] != domain { t.Errorf("cert.DNSNames = %v; want %q", cert.DNSNames, domain) } } func TestAccountKeyCache(t *testing.T) { m := Manager{Cache: newMemCache()} ctx := context.Background() k1, err := m.accountKey(ctx) if err != nil { t.Fatal(err) } k2, err := m.accountKey(ctx) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(k1, k2) { t.Errorf("account keys don't match: k1 = %#v; k2 = %#v", k1, k2) } } func TestCache(t *testing.T) { privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } tmpl := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "example.org"}, NotAfter: time.Now().Add(time.Hour), } pub, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &privKey.PublicKey, privKey) if err != nil { t.Fatal(err) } tlscert := &tls.Certificate{ Certificate: [][]byte{pub}, PrivateKey: privKey, } man := &Manager{Cache: newMemCache()} defer man.stopRenew() ctx := context.Background() if err := man.cachePut(ctx, "example.org", tlscert); err != nil { t.Fatalf("man.cachePut: %v", err) } res, err := man.cacheGet(ctx, "example.org") if err != nil { t.Fatalf("man.cacheGet: %v", err) } if res == nil { t.Fatal("res is nil") } } func TestHostWhitelist(t *testing.T) { policy := HostWhitelist("example.com", "example.org", "*.example.net") tt := []struct { host string allow bool }{ {"example.com", true}, {"example.org", true}, {"one.example.com", false}, {"two.example.org", false}, {"three.example.net", false}, {"dummy", false}, } for i, test := range tt { err := policy(nil, test.host) if err != nil && test.allow { t.Errorf("%d: policy(%q): %v; want nil", i, test.host, err) } if err == nil && !test.allow { t.Errorf("%d: policy(%q): nil; want an error", i, test.host) } } } func TestValidCert(t *testing.T) { key1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } key2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { t.Fatal(err) } key3, err := rsa.GenerateKey(rand.Reader, 512) if err != nil { t.Fatal(err) } cert1, err := dummyCert(key1.Public(), "example.org") if err != nil { t.Fatal(err) } cert2, err := dummyCert(key2.Public(), "example.org") if err != nil { t.Fatal(err) } cert3, err := dummyCert(key3.Public(), "example.org") if err != nil { t.Fatal(err) } now := time.Now() early, err := dateDummyCert(key1.Public(), now.Add(time.Hour), now.Add(2*time.Hour), "example.org") if err != nil { t.Fatal(err) } expired, err := dateDummyCert(key1.Public(), now.Add(-2*time.Hour), now.Add(-time.Hour), "example.org") if err != nil { t.Fatal(err) } tt := []struct { domain string key crypto.Signer cert [][]byte ok bool }{ {"example.org", key1, [][]byte{cert1}, true}, {"example.org", key3, [][]byte{cert3}, true}, {"example.org", key1, [][]byte{cert1, cert2, cert3}, true}, {"example.org", key1, [][]byte{cert1, {1}}, false}, {"example.org", key1, [][]byte{{1}}, false}, {"example.org", key1, [][]byte{cert2}, false}, {"example.org", key2, [][]byte{cert1}, false}, {"example.org", key1, [][]byte{cert3}, false}, {"example.org", key3, [][]byte{cert1}, false}, {"example.net", key1, [][]byte{cert1}, false}, {"example.org", key1, [][]byte{early}, false}, {"example.org", key1, [][]byte{expired}, false}, } for i, test := range tt { leaf, err := validCert(test.domain, test.cert, test.key) if err != nil && test.ok { t.Errorf("%d: err = %v", i, err) } if err == nil && !test.ok { t.Errorf("%d: err is nil", i) } if err == nil && test.ok && leaf == nil { t.Errorf("%d: leaf is nil", i) } } } type cacheGetFunc func(ctx context.Context, key string) ([]byte, error) func (f cacheGetFunc) Get(ctx context.Context, key string) ([]byte, error) { return f(ctx, key) } func (f cacheGetFunc) Put(ctx context.Context, key string, data []byte) error { return fmt.Errorf("unsupported Put of %q = %q", key, data) } func (f cacheGetFunc) Delete(ctx context.Context, key string) error { return fmt.Errorf("unsupported Delete of %q", key) } func TestManagerGetCertificateBogusSNI(t *testing.T) { m := Manager{ Prompt: AcceptTOS, Cache: cacheGetFunc(func(ctx context.Context, key string) ([]byte, error) { return nil, fmt.Errorf("cache.Get of %s", key) }), } tests := []struct { name string wantErr string }{ {"foo.com", "cache.Get of foo.com"}, {"foo.com.", "cache.Get of foo.com"}, {`a\b.com`, "acme/autocert: server name contains invalid character"}, {`a/b.com`, "acme/autocert: server name contains invalid character"}, {"", "acme/autocert: missing server name"}, {"foo", "acme/autocert: server name component count invalid"}, {".foo", "acme/autocert: server name component count invalid"}, {"foo.", "acme/autocert: server name component count invalid"}, {"fo.o", "cache.Get of fo.o"}, } for _, tt := range tests { _, err := m.GetCertificate(&tls.ClientHelloInfo{ServerName: tt.name}) got := fmt.Sprint(err) if got != tt.wantErr { t.Errorf("GetCertificate(SNI = %q) = %q; want %q", tt.name, got, tt.wantErr) } } } ����������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/autocert/autocert.go�����������������������������������0000644�0610621�0607500�00000056120�13172163317�025766� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package autocert provides automatic access to certificates from Let's Encrypt // and any other ACME-based CA. // // This package is a work in progress and makes no API stability promises. package autocert import ( "bytes" "context" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "errors" "fmt" "io" mathrand "math/rand" "net/http" "strconv" "strings" "sync" "time" "golang.org/x/crypto/acme" ) // createCertRetryAfter is how much time to wait before removing a failed state // entry due to an unsuccessful createCert call. // This is a variable instead of a const for testing. // TODO: Consider making it configurable or an exp backoff? var createCertRetryAfter = time.Minute // pseudoRand is safe for concurrent use. var pseudoRand *lockedMathRand func init() { src := mathrand.NewSource(timeNow().UnixNano()) pseudoRand = &lockedMathRand{rnd: mathrand.New(src)} } // AcceptTOS is a Manager.Prompt function that always returns true to // indicate acceptance of the CA's Terms of Service during account // registration. func AcceptTOS(tosURL string) bool { return true } // HostPolicy specifies which host names the Manager is allowed to respond to. // It returns a non-nil error if the host should be rejected. // The returned error is accessible via tls.Conn.Handshake and its callers. // See Manager's HostPolicy field and GetCertificate method docs for more details. type HostPolicy func(ctx context.Context, host string) error // HostWhitelist returns a policy where only the specified host names are allowed. // Only exact matches are currently supported. Subdomains, regexp or wildcard // will not match. func HostWhitelist(hosts ...string) HostPolicy { whitelist := make(map[string]bool, len(hosts)) for _, h := range hosts { whitelist[h] = true } return func(_ context.Context, host string) error { if !whitelist[host] { return errors.New("acme/autocert: host not configured") } return nil } } // defaultHostPolicy is used when Manager.HostPolicy is not set. func defaultHostPolicy(context.Context, string) error { return nil } // Manager is a stateful certificate manager built on top of acme.Client. // It obtains and refreshes certificates automatically, // as well as providing them to a TLS server via tls.Config. // // You must specify a cache implementation, such as DirCache, // to reuse obtained certificates across program restarts. // Otherwise your server is very likely to exceed the certificate // issuer's request rate limits. type Manager struct { // Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS). // The registration may require the caller to agree to the CA's TOS. // If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report // whether the caller agrees to the terms. // // To always accept the terms, the callers can use AcceptTOS. Prompt func(tosURL string) bool // Cache optionally stores and retrieves previously-obtained certificates. // If nil, certs will only be cached for the lifetime of the Manager. // // Manager passes the Cache certificates data encoded in PEM, with private/public // parts combined in a single Cache.Put call, private key first. Cache Cache // HostPolicy controls which domains the Manager will attempt // to retrieve new certificates for. It does not affect cached certs. // // If non-nil, HostPolicy is called before requesting a new cert. // If nil, all hosts are currently allowed. This is not recommended, // as it opens a potential attack where clients connect to a server // by IP address and pretend to be asking for an incorrect host name. // Manager will attempt to obtain a certificate for that host, incorrectly, // eventually reaching the CA's rate limit for certificate requests // and making it impossible to obtain actual certificates. // // See GetCertificate for more details. HostPolicy HostPolicy // RenewBefore optionally specifies how early certificates should // be renewed before they expire. // // If zero, they're renewed 30 days before expiration. RenewBefore time.Duration // Client is used to perform low-level operations, such as account registration // and requesting new certificates. // If Client is nil, a zero-value acme.Client is used with acme.LetsEncryptURL // directory endpoint and a newly-generated ECDSA P-256 key. // // Mutating the field after the first call of GetCertificate method will have no effect. Client *acme.Client // Email optionally specifies a contact email address. // This is used by CAs, such as Let's Encrypt, to notify about problems // with issued certificates. // // If the Client's account key is already registered, Email is not used. Email string // ForceRSA makes the Manager generate certificates with 2048-bit RSA keys. // // If false, a default is used. Currently the default // is EC-based keys using the P-256 curve. ForceRSA bool clientMu sync.Mutex client *acme.Client // initialized by acmeClient method stateMu sync.Mutex state map[string]*certState // keyed by domain name // tokenCert is keyed by token domain name, which matches server name // of ClientHello. Keys always have ".acme.invalid" suffix. tokenCertMu sync.RWMutex tokenCert map[string]*tls.Certificate // renewal tracks the set of domains currently running renewal timers. // It is keyed by domain name. renewalMu sync.Mutex renewal map[string]*domainRenewal } // GetCertificate implements the tls.Config.GetCertificate hook. // It provides a TLS certificate for hello.ServerName host, including answering // *.acme.invalid (TLS-SNI) challenges. All other fields of hello are ignored. // // If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting // a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation. // The error is propagated back to the caller of GetCertificate and is user-visible. // This does not affect cached certs. See HostPolicy field description for more details. func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { if m.Prompt == nil { return nil, errors.New("acme/autocert: Manager.Prompt not set") } name := hello.ServerName if name == "" { return nil, errors.New("acme/autocert: missing server name") } if !strings.Contains(strings.Trim(name, "."), ".") { return nil, errors.New("acme/autocert: server name component count invalid") } if strings.ContainsAny(name, `/\`) { return nil, errors.New("acme/autocert: server name contains invalid character") } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() // check whether this is a token cert requested for TLS-SNI challenge if strings.HasSuffix(name, ".acme.invalid") { m.tokenCertMu.RLock() defer m.tokenCertMu.RUnlock() if cert := m.tokenCert[name]; cert != nil { return cert, nil } if cert, err := m.cacheGet(ctx, name); err == nil { return cert, nil } // TODO: cache error results? return nil, fmt.Errorf("acme/autocert: no token cert for %q", name) } // regular domain name = strings.TrimSuffix(name, ".") // golang.org/issue/18114 cert, err := m.cert(ctx, name) if err == nil { return cert, nil } if err != ErrCacheMiss { return nil, err } // first-time if err := m.hostPolicy()(ctx, name); err != nil { return nil, err } cert, err = m.createCert(ctx, name) if err != nil { return nil, err } m.cachePut(ctx, name, cert) return cert, nil } // cert returns an existing certificate either from m.state or cache. // If a certificate is found in cache but not in m.state, the latter will be filled // with the cached value. func (m *Manager) cert(ctx context.Context, name string) (*tls.Certificate, error) { m.stateMu.Lock() if s, ok := m.state[name]; ok { m.stateMu.Unlock() s.RLock() defer s.RUnlock() return s.tlscert() } defer m.stateMu.Unlock() cert, err := m.cacheGet(ctx, name) if err != nil { return nil, err } signer, ok := cert.PrivateKey.(crypto.Signer) if !ok { return nil, errors.New("acme/autocert: private key cannot sign") } if m.state == nil { m.state = make(map[string]*certState) } s := &certState{ key: signer, cert: cert.Certificate, leaf: cert.Leaf, } m.state[name] = s go m.renew(name, s.key, s.leaf.NotAfter) return cert, nil } // cacheGet always returns a valid certificate, or an error otherwise. // If a cached certficate exists but is not valid, ErrCacheMiss is returned. func (m *Manager) cacheGet(ctx context.Context, domain string) (*tls.Certificate, error) { if m.Cache == nil { return nil, ErrCacheMiss } data, err := m.Cache.Get(ctx, domain) if err != nil { return nil, err } // private priv, pub := pem.Decode(data) if priv == nil || !strings.Contains(priv.Type, "PRIVATE") { return nil, ErrCacheMiss } privKey, err := parsePrivateKey(priv.Bytes) if err != nil { return nil, err } // public var pubDER [][]byte for len(pub) > 0 { var b *pem.Block b, pub = pem.Decode(pub) if b == nil { break } pubDER = append(pubDER, b.Bytes) } if len(pub) > 0 { // Leftover content not consumed by pem.Decode. Corrupt. Ignore. return nil, ErrCacheMiss } // verify and create TLS cert leaf, err := validCert(domain, pubDER, privKey) if err != nil { return nil, ErrCacheMiss } tlscert := &tls.Certificate{ Certificate: pubDER, PrivateKey: privKey, Leaf: leaf, } return tlscert, nil } func (m *Manager) cachePut(ctx context.Context, domain string, tlscert *tls.Certificate) error { if m.Cache == nil { return nil } // contains PEM-encoded data var buf bytes.Buffer // private switch key := tlscert.PrivateKey.(type) { case *ecdsa.PrivateKey: if err := encodeECDSAKey(&buf, key); err != nil { return err } case *rsa.PrivateKey: b := x509.MarshalPKCS1PrivateKey(key) pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b} if err := pem.Encode(&buf, pb); err != nil { return err } default: return errors.New("acme/autocert: unknown private key type") } // public for _, b := range tlscert.Certificate { pb := &pem.Block{Type: "CERTIFICATE", Bytes: b} if err := pem.Encode(&buf, pb); err != nil { return err } } return m.Cache.Put(ctx, domain, buf.Bytes()) } func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error { b, err := x509.MarshalECPrivateKey(key) if err != nil { return err } pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} return pem.Encode(w, pb) } // createCert starts the domain ownership verification and returns a certificate // for that domain upon success. // // If the domain is already being verified, it waits for the existing verification to complete. // Either way, createCert blocks for the duration of the whole process. func (m *Manager) createCert(ctx context.Context, domain string) (*tls.Certificate, error) { // TODO: maybe rewrite this whole piece using sync.Once state, err := m.certState(domain) if err != nil { return nil, err } // state may exist if another goroutine is already working on it // in which case just wait for it to finish if !state.locked { state.RLock() defer state.RUnlock() return state.tlscert() } // We are the first; state is locked. // Unblock the readers when domain ownership is verified // and we got the cert or the process failed. defer state.Unlock() state.locked = false der, leaf, err := m.authorizedCert(ctx, state.key, domain) if err != nil { // Remove the failed state after some time, // making the manager call createCert again on the following TLS hello. time.AfterFunc(createCertRetryAfter, func() { defer testDidRemoveState(domain) m.stateMu.Lock() defer m.stateMu.Unlock() // Verify the state hasn't changed and it's still invalid // before deleting. s, ok := m.state[domain] if !ok { return } if _, err := validCert(domain, s.cert, s.key); err == nil { return } delete(m.state, domain) }) return nil, err } state.cert = der state.leaf = leaf go m.renew(domain, state.key, state.leaf.NotAfter) return state.tlscert() } // certState returns a new or existing certState. // If a new certState is returned, state.exist is false and the state is locked. // The returned error is non-nil only in the case where a new state could not be created. func (m *Manager) certState(domain string) (*certState, error) { m.stateMu.Lock() defer m.stateMu.Unlock() if m.state == nil { m.state = make(map[string]*certState) } // existing state if state, ok := m.state[domain]; ok { return state, nil } // new locked state var ( err error key crypto.Signer ) if m.ForceRSA { key, err = rsa.GenerateKey(rand.Reader, 2048) } else { key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) } if err != nil { return nil, err } state := &certState{ key: key, locked: true, } state.Lock() // will be unlocked by m.certState caller m.state[domain] = state return state, nil } // authorizedCert starts the domain ownership verification process and requests a new cert upon success. // The key argument is the certificate private key. func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, domain string) (der [][]byte, leaf *x509.Certificate, err error) { if err := m.verify(ctx, domain); err != nil { return nil, nil, err } client, err := m.acmeClient(ctx) if err != nil { return nil, nil, err } csr, err := certRequest(key, domain) if err != nil { return nil, nil, err } der, _, err = client.CreateCert(ctx, csr, 0, true) if err != nil { return nil, nil, err } leaf, err = validCert(domain, der, key) if err != nil { return nil, nil, err } return der, leaf, nil } // verify starts a new identifier (domain) authorization flow. // It prepares a challenge response and then blocks until the authorization // is marked as "completed" by the CA (either succeeded or failed). // // verify returns nil iff the verification was successful. func (m *Manager) verify(ctx context.Context, domain string) error { client, err := m.acmeClient(ctx) if err != nil { return err } // start domain authorization and get the challenge authz, err := client.Authorize(ctx, domain) if err != nil { return err } // maybe don't need to at all if authz.Status == acme.StatusValid { return nil } // pick a challenge: prefer tls-sni-02 over tls-sni-01 // TODO: consider authz.Combinations var chal *acme.Challenge for _, c := range authz.Challenges { if c.Type == "tls-sni-02" { chal = c break } if c.Type == "tls-sni-01" { chal = c } } if chal == nil { return errors.New("acme/autocert: no supported challenge type found") } // create a token cert for the challenge response var ( cert tls.Certificate name string ) switch chal.Type { case "tls-sni-01": cert, name, err = client.TLSSNI01ChallengeCert(chal.Token) case "tls-sni-02": cert, name, err = client.TLSSNI02ChallengeCert(chal.Token) default: err = fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type) } if err != nil { return err } m.putTokenCert(ctx, name, &cert) defer func() { // verification has ended at this point // don't need token cert anymore go m.deleteTokenCert(name) }() // ready to fulfill the challenge if _, err := client.Accept(ctx, chal); err != nil { return err } // wait for the CA to validate _, err = client.WaitAuthorization(ctx, authz.URI) return err } // putTokenCert stores the cert under the named key in both m.tokenCert map // and m.Cache. func (m *Manager) putTokenCert(ctx context.Context, name string, cert *tls.Certificate) { m.tokenCertMu.Lock() defer m.tokenCertMu.Unlock() if m.tokenCert == nil { m.tokenCert = make(map[string]*tls.Certificate) } m.tokenCert[name] = cert m.cachePut(ctx, name, cert) } // deleteTokenCert removes the token certificate for the specified domain name // from both m.tokenCert map and m.Cache. func (m *Manager) deleteTokenCert(name string) { m.tokenCertMu.Lock() defer m.tokenCertMu.Unlock() delete(m.tokenCert, name) if m.Cache != nil { m.Cache.Delete(context.Background(), name) } } // renew starts a cert renewal timer loop, one per domain. // // The loop is scheduled in two cases: // - a cert was fetched from cache for the first time (wasn't in m.state) // - a new cert was created by m.createCert // // The key argument is a certificate private key. // The exp argument is the cert expiration time (NotAfter). func (m *Manager) renew(domain string, key crypto.Signer, exp time.Time) { m.renewalMu.Lock() defer m.renewalMu.Unlock() if m.renewal[domain] != nil { // another goroutine is already on it return } if m.renewal == nil { m.renewal = make(map[string]*domainRenewal) } dr := &domainRenewal{m: m, domain: domain, key: key} m.renewal[domain] = dr dr.start(exp) } // stopRenew stops all currently running cert renewal timers. // The timers are not restarted during the lifetime of the Manager. func (m *Manager) stopRenew() { m.renewalMu.Lock() defer m.renewalMu.Unlock() for name, dr := range m.renewal { delete(m.renewal, name) dr.stop() } } func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) { const keyName = "acme_account.key" genKey := func() (*ecdsa.PrivateKey, error) { return ecdsa.GenerateKey(elliptic.P256(), rand.Reader) } if m.Cache == nil { return genKey() } data, err := m.Cache.Get(ctx, keyName) if err == ErrCacheMiss { key, err := genKey() if err != nil { return nil, err } var buf bytes.Buffer if err := encodeECDSAKey(&buf, key); err != nil { return nil, err } if err := m.Cache.Put(ctx, keyName, buf.Bytes()); err != nil { return nil, err } return key, nil } if err != nil { return nil, err } priv, _ := pem.Decode(data) if priv == nil || !strings.Contains(priv.Type, "PRIVATE") { return nil, errors.New("acme/autocert: invalid account key found in cache") } return parsePrivateKey(priv.Bytes) } func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) { m.clientMu.Lock() defer m.clientMu.Unlock() if m.client != nil { return m.client, nil } client := m.Client if client == nil { client = &acme.Client{DirectoryURL: acme.LetsEncryptURL} } if client.Key == nil { var err error client.Key, err = m.accountKey(ctx) if err != nil { return nil, err } } var contact []string if m.Email != "" { contact = []string{"mailto:" + m.Email} } a := &acme.Account{Contact: contact} _, err := client.Register(ctx, a, m.Prompt) if ae, ok := err.(*acme.Error); err == nil || ok && ae.StatusCode == http.StatusConflict { // conflict indicates the key is already registered m.client = client err = nil } return m.client, err } func (m *Manager) hostPolicy() HostPolicy { if m.HostPolicy != nil { return m.HostPolicy } return defaultHostPolicy } func (m *Manager) renewBefore() time.Duration { if m.RenewBefore > renewJitter { return m.RenewBefore } return 720 * time.Hour // 30 days } // certState is ready when its mutex is unlocked for reading. type certState struct { sync.RWMutex locked bool // locked for read/write key crypto.Signer // private key for cert cert [][]byte // DER encoding leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil } // tlscert creates a tls.Certificate from s.key and s.cert. // Callers should wrap it in s.RLock() and s.RUnlock(). func (s *certState) tlscert() (*tls.Certificate, error) { if s.key == nil { return nil, errors.New("acme/autocert: missing signer") } if len(s.cert) == 0 { return nil, errors.New("acme/autocert: missing certificate") } return &tls.Certificate{ PrivateKey: s.key, Certificate: s.cert, Leaf: s.leaf, }, nil } // certRequest creates a certificate request for the given common name cn // and optional SANs. func certRequest(key crypto.Signer, cn string, san ...string) ([]byte, error) { req := &x509.CertificateRequest{ Subject: pkix.Name{CommonName: cn}, DNSNames: san, } return x509.CreateCertificateRequest(rand.Reader, req, key) } // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. // // Inspired by parsePrivateKey in crypto/tls/tls.go. func parsePrivateKey(der []byte) (crypto.Signer, error) { if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { return key, nil } if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { switch key := key.(type) { case *rsa.PrivateKey: return key, nil case *ecdsa.PrivateKey: return key, nil default: return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping") } } if key, err := x509.ParseECPrivateKey(der); err == nil { return key, nil } return nil, errors.New("acme/autocert: failed to parse private key") } // validCert parses a cert chain provided as der argument and verifies the leaf, der[0], // corresponds to the private key, as well as the domain match and expiration dates. // It doesn't do any revocation checking. // // The returned value is the verified leaf cert. func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certificate, err error) { // parse public part(s) var n int for _, b := range der { n += len(b) } pub := make([]byte, n) n = 0 for _, b := range der { n += copy(pub[n:], b) } x509Cert, err := x509.ParseCertificates(pub) if len(x509Cert) == 0 { return nil, errors.New("acme/autocert: no public key found") } // verify the leaf is not expired and matches the domain name leaf = x509Cert[0] now := timeNow() if now.Before(leaf.NotBefore) { return nil, errors.New("acme/autocert: certificate is not valid yet") } if now.After(leaf.NotAfter) { return nil, errors.New("acme/autocert: expired certificate") } if err := leaf.VerifyHostname(domain); err != nil { return nil, err } // ensure the leaf corresponds to the private key switch pub := leaf.PublicKey.(type) { case *rsa.PublicKey: prv, ok := key.(*rsa.PrivateKey) if !ok { return nil, errors.New("acme/autocert: private key type does not match public key type") } if pub.N.Cmp(prv.N) != 0 { return nil, errors.New("acme/autocert: private key does not match public key") } case *ecdsa.PublicKey: prv, ok := key.(*ecdsa.PrivateKey) if !ok { return nil, errors.New("acme/autocert: private key type does not match public key type") } if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 { return nil, errors.New("acme/autocert: private key does not match public key") } default: return nil, errors.New("acme/autocert: unknown public key algorithm") } return leaf, nil } func retryAfter(v string) time.Duration { if i, err := strconv.Atoi(v); err == nil { return time.Duration(i) * time.Second } if t, err := http.ParseTime(v); err == nil { return t.Sub(timeNow()) } return time.Second } type lockedMathRand struct { sync.Mutex rnd *mathrand.Rand } func (r *lockedMathRand) int63n(max int64) int64 { r.Lock() n := r.rnd.Int63n(max) r.Unlock() return n } // For easier testing. var ( timeNow = time.Now // Called when a state is removed. testDidRemoveState = func(domain string) {} ) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/acme_test.go�������������������������������������������0000644�0610621�0607500�00000110220�13172163317�024246� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package acme import ( "bytes" "context" "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "math/big" "net/http" "net/http/httptest" "reflect" "sort" "strings" "testing" "time" ) // Decodes a JWS-encoded request and unmarshals the decoded JSON into a provided // interface. func decodeJWSRequest(t *testing.T, v interface{}, r *http.Request) { // Decode request var req struct{ Payload string } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { t.Fatal(err) } payload, err := base64.RawURLEncoding.DecodeString(req.Payload) if err != nil { t.Fatal(err) } err = json.Unmarshal(payload, v) if err != nil { t.Fatal(err) } } type jwsHead struct { Alg string Nonce string JWK map[string]string `json:"jwk"` } func decodeJWSHead(r *http.Request) (*jwsHead, error) { var req struct{ Protected string } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return nil, err } b, err := base64.RawURLEncoding.DecodeString(req.Protected) if err != nil { return nil, err } var head jwsHead if err := json.Unmarshal(b, &head); err != nil { return nil, err } return &head, nil } func TestDiscover(t *testing.T) { const ( reg = "https://example.com/acme/new-reg" authz = "https://example.com/acme/new-authz" cert = "https://example.com/acme/new-cert" revoke = "https://example.com/acme/revoke-cert" ) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `{ "new-reg": %q, "new-authz": %q, "new-cert": %q, "revoke-cert": %q }`, reg, authz, cert, revoke) })) defer ts.Close() c := Client{DirectoryURL: ts.URL} dir, err := c.Discover(context.Background()) if err != nil { t.Fatal(err) } if dir.RegURL != reg { t.Errorf("dir.RegURL = %q; want %q", dir.RegURL, reg) } if dir.AuthzURL != authz { t.Errorf("dir.AuthzURL = %q; want %q", dir.AuthzURL, authz) } if dir.CertURL != cert { t.Errorf("dir.CertURL = %q; want %q", dir.CertURL, cert) } if dir.RevokeURL != revoke { t.Errorf("dir.RevokeURL = %q; want %q", dir.RevokeURL, revoke) } } func TestRegister(t *testing.T) { contacts := []string{"mailto:admin@example.com"} ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "test-nonce") return } if r.Method != "POST" { t.Errorf("r.Method = %q; want POST", r.Method) } var j struct { Resource string Contact []string Agreement string } decodeJWSRequest(t, &j, r) // Test request if j.Resource != "new-reg" { t.Errorf("j.Resource = %q; want new-reg", j.Resource) } if !reflect.DeepEqual(j.Contact, contacts) { t.Errorf("j.Contact = %v; want %v", j.Contact, contacts) } w.Header().Set("Location", "https://ca.tld/acme/reg/1") w.Header().Set("Link", `<https://ca.tld/acme/new-authz>;rel="next"`) w.Header().Add("Link", `<https://ca.tld/acme/recover-reg>;rel="recover"`) w.Header().Add("Link", `<https://ca.tld/acme/terms>;rel="terms-of-service"`) w.WriteHeader(http.StatusCreated) b, _ := json.Marshal(contacts) fmt.Fprintf(w, `{"contact": %s}`, b) })) defer ts.Close() prompt := func(url string) bool { const terms = "https://ca.tld/acme/terms" if url != terms { t.Errorf("prompt url = %q; want %q", url, terms) } return false } c := Client{Key: testKeyEC, dir: &Directory{RegURL: ts.URL}} a := &Account{Contact: contacts} var err error if a, err = c.Register(context.Background(), a, prompt); err != nil { t.Fatal(err) } if a.URI != "https://ca.tld/acme/reg/1" { t.Errorf("a.URI = %q; want https://ca.tld/acme/reg/1", a.URI) } if a.Authz != "https://ca.tld/acme/new-authz" { t.Errorf("a.Authz = %q; want https://ca.tld/acme/new-authz", a.Authz) } if a.CurrentTerms != "https://ca.tld/acme/terms" { t.Errorf("a.CurrentTerms = %q; want https://ca.tld/acme/terms", a.CurrentTerms) } if !reflect.DeepEqual(a.Contact, contacts) { t.Errorf("a.Contact = %v; want %v", a.Contact, contacts) } } func TestUpdateReg(t *testing.T) { const terms = "https://ca.tld/acme/terms" contacts := []string{"mailto:admin@example.com"} ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "test-nonce") return } if r.Method != "POST" { t.Errorf("r.Method = %q; want POST", r.Method) } var j struct { Resource string Contact []string Agreement string } decodeJWSRequest(t, &j, r) // Test request if j.Resource != "reg" { t.Errorf("j.Resource = %q; want reg", j.Resource) } if j.Agreement != terms { t.Errorf("j.Agreement = %q; want %q", j.Agreement, terms) } if !reflect.DeepEqual(j.Contact, contacts) { t.Errorf("j.Contact = %v; want %v", j.Contact, contacts) } w.Header().Set("Link", `<https://ca.tld/acme/new-authz>;rel="next"`) w.Header().Add("Link", `<https://ca.tld/acme/recover-reg>;rel="recover"`) w.Header().Add("Link", fmt.Sprintf(`<%s>;rel="terms-of-service"`, terms)) w.WriteHeader(http.StatusOK) b, _ := json.Marshal(contacts) fmt.Fprintf(w, `{"contact":%s, "agreement":%q}`, b, terms) })) defer ts.Close() c := Client{Key: testKeyEC} a := &Account{URI: ts.URL, Contact: contacts, AgreedTerms: terms} var err error if a, err = c.UpdateReg(context.Background(), a); err != nil { t.Fatal(err) } if a.Authz != "https://ca.tld/acme/new-authz" { t.Errorf("a.Authz = %q; want https://ca.tld/acme/new-authz", a.Authz) } if a.AgreedTerms != terms { t.Errorf("a.AgreedTerms = %q; want %q", a.AgreedTerms, terms) } if a.CurrentTerms != terms { t.Errorf("a.CurrentTerms = %q; want %q", a.CurrentTerms, terms) } if a.URI != ts.URL { t.Errorf("a.URI = %q; want %q", a.URI, ts.URL) } } func TestGetReg(t *testing.T) { const terms = "https://ca.tld/acme/terms" const newTerms = "https://ca.tld/acme/new-terms" contacts := []string{"mailto:admin@example.com"} ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "test-nonce") return } if r.Method != "POST" { t.Errorf("r.Method = %q; want POST", r.Method) } var j struct { Resource string Contact []string Agreement string } decodeJWSRequest(t, &j, r) // Test request if j.Resource != "reg" { t.Errorf("j.Resource = %q; want reg", j.Resource) } if len(j.Contact) != 0 { t.Errorf("j.Contact = %v", j.Contact) } if j.Agreement != "" { t.Errorf("j.Agreement = %q", j.Agreement) } w.Header().Set("Link", `<https://ca.tld/acme/new-authz>;rel="next"`) w.Header().Add("Link", `<https://ca.tld/acme/recover-reg>;rel="recover"`) w.Header().Add("Link", fmt.Sprintf(`<%s>;rel="terms-of-service"`, newTerms)) w.WriteHeader(http.StatusOK) b, _ := json.Marshal(contacts) fmt.Fprintf(w, `{"contact":%s, "agreement":%q}`, b, terms) })) defer ts.Close() c := Client{Key: testKeyEC} a, err := c.GetReg(context.Background(), ts.URL) if err != nil { t.Fatal(err) } if a.Authz != "https://ca.tld/acme/new-authz" { t.Errorf("a.AuthzURL = %q; want https://ca.tld/acme/new-authz", a.Authz) } if a.AgreedTerms != terms { t.Errorf("a.AgreedTerms = %q; want %q", a.AgreedTerms, terms) } if a.CurrentTerms != newTerms { t.Errorf("a.CurrentTerms = %q; want %q", a.CurrentTerms, newTerms) } if a.URI != ts.URL { t.Errorf("a.URI = %q; want %q", a.URI, ts.URL) } } func TestAuthorize(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "test-nonce") return } if r.Method != "POST" { t.Errorf("r.Method = %q; want POST", r.Method) } var j struct { Resource string Identifier struct { Type string Value string } } decodeJWSRequest(t, &j, r) // Test request if j.Resource != "new-authz" { t.Errorf("j.Resource = %q; want new-authz", j.Resource) } if j.Identifier.Type != "dns" { t.Errorf("j.Identifier.Type = %q; want dns", j.Identifier.Type) } if j.Identifier.Value != "example.com" { t.Errorf("j.Identifier.Value = %q; want example.com", j.Identifier.Value) } w.Header().Set("Location", "https://ca.tld/acme/auth/1") w.WriteHeader(http.StatusCreated) fmt.Fprintf(w, `{ "identifier": {"type":"dns","value":"example.com"}, "status":"pending", "challenges":[ { "type":"http-01", "status":"pending", "uri":"https://ca.tld/acme/challenge/publickey/id1", "token":"token1" }, { "type":"tls-sni-01", "status":"pending", "uri":"https://ca.tld/acme/challenge/publickey/id2", "token":"token2" } ], "combinations":[[0],[1]]}`) })) defer ts.Close() cl := Client{Key: testKeyEC, dir: &Directory{AuthzURL: ts.URL}} auth, err := cl.Authorize(context.Background(), "example.com") if err != nil { t.Fatal(err) } if auth.URI != "https://ca.tld/acme/auth/1" { t.Errorf("URI = %q; want https://ca.tld/acme/auth/1", auth.URI) } if auth.Status != "pending" { t.Errorf("Status = %q; want pending", auth.Status) } if auth.Identifier.Type != "dns" { t.Errorf("Identifier.Type = %q; want dns", auth.Identifier.Type) } if auth.Identifier.Value != "example.com" { t.Errorf("Identifier.Value = %q; want example.com", auth.Identifier.Value) } if n := len(auth.Challenges); n != 2 { t.Fatalf("len(auth.Challenges) = %d; want 2", n) } c := auth.Challenges[0] if c.Type != "http-01" { t.Errorf("c.Type = %q; want http-01", c.Type) } if c.URI != "https://ca.tld/acme/challenge/publickey/id1" { t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", c.URI) } if c.Token != "token1" { t.Errorf("c.Token = %q; want token1", c.Token) } c = auth.Challenges[1] if c.Type != "tls-sni-01" { t.Errorf("c.Type = %q; want tls-sni-01", c.Type) } if c.URI != "https://ca.tld/acme/challenge/publickey/id2" { t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id2", c.URI) } if c.Token != "token2" { t.Errorf("c.Token = %q; want token2", c.Token) } combs := [][]int{{0}, {1}} if !reflect.DeepEqual(auth.Combinations, combs) { t.Errorf("auth.Combinations: %+v\nwant: %+v\n", auth.Combinations, combs) } } func TestAuthorizeValid(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "nonce") return } w.WriteHeader(http.StatusCreated) w.Write([]byte(`{"status":"valid"}`)) })) defer ts.Close() client := Client{Key: testKey, dir: &Directory{AuthzURL: ts.URL}} _, err := client.Authorize(context.Background(), "example.com") if err != nil { t.Errorf("err = %v", err) } } func TestGetAuthorization(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { t.Errorf("r.Method = %q; want GET", r.Method) } w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{ "identifier": {"type":"dns","value":"example.com"}, "status":"pending", "challenges":[ { "type":"http-01", "status":"pending", "uri":"https://ca.tld/acme/challenge/publickey/id1", "token":"token1" }, { "type":"tls-sni-01", "status":"pending", "uri":"https://ca.tld/acme/challenge/publickey/id2", "token":"token2" } ], "combinations":[[0],[1]]}`) })) defer ts.Close() cl := Client{Key: testKeyEC} auth, err := cl.GetAuthorization(context.Background(), ts.URL) if err != nil { t.Fatal(err) } if auth.Status != "pending" { t.Errorf("Status = %q; want pending", auth.Status) } if auth.Identifier.Type != "dns" { t.Errorf("Identifier.Type = %q; want dns", auth.Identifier.Type) } if auth.Identifier.Value != "example.com" { t.Errorf("Identifier.Value = %q; want example.com", auth.Identifier.Value) } if n := len(auth.Challenges); n != 2 { t.Fatalf("len(set.Challenges) = %d; want 2", n) } c := auth.Challenges[0] if c.Type != "http-01" { t.Errorf("c.Type = %q; want http-01", c.Type) } if c.URI != "https://ca.tld/acme/challenge/publickey/id1" { t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", c.URI) } if c.Token != "token1" { t.Errorf("c.Token = %q; want token1", c.Token) } c = auth.Challenges[1] if c.Type != "tls-sni-01" { t.Errorf("c.Type = %q; want tls-sni-01", c.Type) } if c.URI != "https://ca.tld/acme/challenge/publickey/id2" { t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id2", c.URI) } if c.Token != "token2" { t.Errorf("c.Token = %q; want token2", c.Token) } combs := [][]int{{0}, {1}} if !reflect.DeepEqual(auth.Combinations, combs) { t.Errorf("auth.Combinations: %+v\nwant: %+v\n", auth.Combinations, combs) } } func TestWaitAuthorization(t *testing.T) { var count int ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { count++ w.Header().Set("Retry-After", "0") if count > 1 { fmt.Fprintf(w, `{"status":"valid"}`) return } fmt.Fprintf(w, `{"status":"pending"}`) })) defer ts.Close() type res struct { authz *Authorization err error } done := make(chan res) defer close(done) go func() { var client Client a, err := client.WaitAuthorization(context.Background(), ts.URL) done <- res{a, err} }() select { case <-time.After(5 * time.Second): t.Fatal("WaitAuthz took too long to return") case res := <-done: if res.err != nil { t.Fatalf("res.err = %v", res.err) } if res.authz == nil { t.Fatal("res.authz is nil") } } } func TestWaitAuthorizationInvalid(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `{"status":"invalid"}`) })) defer ts.Close() res := make(chan error) defer close(res) go func() { var client Client _, err := client.WaitAuthorization(context.Background(), ts.URL) res <- err }() select { case <-time.After(3 * time.Second): t.Fatal("WaitAuthz took too long to return") case err := <-res: if err == nil { t.Error("err is nil") } if _, ok := err.(*AuthorizationError); !ok { t.Errorf("err is %T; want *AuthorizationError", err) } } } func TestWaitAuthorizationCancel(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Retry-After", "60") fmt.Fprintf(w, `{"status":"pending"}`) })) defer ts.Close() res := make(chan error) defer close(res) go func() { var client Client ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() _, err := client.WaitAuthorization(ctx, ts.URL) res <- err }() select { case <-time.After(time.Second): t.Fatal("WaitAuthz took too long to return") case err := <-res: if err == nil { t.Error("err is nil") } } } func TestRevokeAuthorization(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "nonce") return } switch r.URL.Path { case "/1": var req struct { Resource string Status string Delete bool } decodeJWSRequest(t, &req, r) if req.Resource != "authz" { t.Errorf("req.Resource = %q; want authz", req.Resource) } if req.Status != "deactivated" { t.Errorf("req.Status = %q; want deactivated", req.Status) } if !req.Delete { t.Errorf("req.Delete is false") } case "/2": w.WriteHeader(http.StatusInternalServerError) } })) defer ts.Close() client := &Client{Key: testKey} ctx := context.Background() if err := client.RevokeAuthorization(ctx, ts.URL+"/1"); err != nil { t.Errorf("err = %v", err) } if client.RevokeAuthorization(ctx, ts.URL+"/2") == nil { t.Error("nil error") } } func TestPollChallenge(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { t.Errorf("r.Method = %q; want GET", r.Method) } w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{ "type":"http-01", "status":"pending", "uri":"https://ca.tld/acme/challenge/publickey/id1", "token":"token1"}`) })) defer ts.Close() cl := Client{Key: testKeyEC} chall, err := cl.GetChallenge(context.Background(), ts.URL) if err != nil { t.Fatal(err) } if chall.Status != "pending" { t.Errorf("Status = %q; want pending", chall.Status) } if chall.Type != "http-01" { t.Errorf("c.Type = %q; want http-01", chall.Type) } if chall.URI != "https://ca.tld/acme/challenge/publickey/id1" { t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", chall.URI) } if chall.Token != "token1" { t.Errorf("c.Token = %q; want token1", chall.Token) } } func TestAcceptChallenge(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "test-nonce") return } if r.Method != "POST" { t.Errorf("r.Method = %q; want POST", r.Method) } var j struct { Resource string Type string Auth string `json:"keyAuthorization"` } decodeJWSRequest(t, &j, r) // Test request if j.Resource != "challenge" { t.Errorf(`resource = %q; want "challenge"`, j.Resource) } if j.Type != "http-01" { t.Errorf(`type = %q; want "http-01"`, j.Type) } keyAuth := "token1." + testKeyECThumbprint if j.Auth != keyAuth { t.Errorf(`keyAuthorization = %q; want %q`, j.Auth, keyAuth) } // Respond to request w.WriteHeader(http.StatusAccepted) fmt.Fprintf(w, `{ "type":"http-01", "status":"pending", "uri":"https://ca.tld/acme/challenge/publickey/id1", "token":"token1", "keyAuthorization":%q }`, keyAuth) })) defer ts.Close() cl := Client{Key: testKeyEC} c, err := cl.Accept(context.Background(), &Challenge{ URI: ts.URL, Token: "token1", Type: "http-01", }) if err != nil { t.Fatal(err) } if c.Type != "http-01" { t.Errorf("c.Type = %q; want http-01", c.Type) } if c.URI != "https://ca.tld/acme/challenge/publickey/id1" { t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", c.URI) } if c.Token != "token1" { t.Errorf("c.Token = %q; want token1", c.Token) } } func TestNewCert(t *testing.T) { notBefore := time.Now() notAfter := notBefore.AddDate(0, 2, 0) timeNow = func() time.Time { return notBefore } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "test-nonce") return } if r.Method != "POST" { t.Errorf("r.Method = %q; want POST", r.Method) } var j struct { Resource string `json:"resource"` CSR string `json:"csr"` NotBefore string `json:"notBefore,omitempty"` NotAfter string `json:"notAfter,omitempty"` } decodeJWSRequest(t, &j, r) // Test request if j.Resource != "new-cert" { t.Errorf(`resource = %q; want "new-cert"`, j.Resource) } if j.NotBefore != notBefore.Format(time.RFC3339) { t.Errorf(`notBefore = %q; wanted %q`, j.NotBefore, notBefore.Format(time.RFC3339)) } if j.NotAfter != notAfter.Format(time.RFC3339) { t.Errorf(`notAfter = %q; wanted %q`, j.NotAfter, notAfter.Format(time.RFC3339)) } // Respond to request template := x509.Certificate{ SerialNumber: big.NewInt(int64(1)), Subject: pkix.Name{ Organization: []string{"goacme"}, }, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, } sampleCert, err := x509.CreateCertificate(rand.Reader, &template, &template, &testKeyEC.PublicKey, testKeyEC) if err != nil { t.Fatalf("Error creating certificate: %v", err) } w.Header().Set("Location", "https://ca.tld/acme/cert/1") w.WriteHeader(http.StatusCreated) w.Write(sampleCert) })) defer ts.Close() csr := x509.CertificateRequest{ Version: 0, Subject: pkix.Name{ CommonName: "example.com", Organization: []string{"goacme"}, }, } csrb, err := x509.CreateCertificateRequest(rand.Reader, &csr, testKeyEC) if err != nil { t.Fatal(err) } c := Client{Key: testKeyEC, dir: &Directory{CertURL: ts.URL}} cert, certURL, err := c.CreateCert(context.Background(), csrb, notAfter.Sub(notBefore), false) if err != nil { t.Fatal(err) } if cert == nil { t.Errorf("cert is nil") } if certURL != "https://ca.tld/acme/cert/1" { t.Errorf("certURL = %q; want https://ca.tld/acme/cert/1", certURL) } } func TestFetchCert(t *testing.T) { var count byte var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { count++ if count < 3 { up := fmt.Sprintf("<%s>;rel=up", ts.URL) w.Header().Set("Link", up) } w.Write([]byte{count}) })) defer ts.Close() res, err := (&Client{}).FetchCert(context.Background(), ts.URL, true) if err != nil { t.Fatalf("FetchCert: %v", err) } cert := [][]byte{{1}, {2}, {3}} if !reflect.DeepEqual(res, cert) { t.Errorf("res = %v; want %v", res, cert) } } func TestFetchCertRetry(t *testing.T) { var count int ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if count < 1 { w.Header().Set("Retry-After", "0") w.WriteHeader(http.StatusAccepted) count++ return } w.Write([]byte{1}) })) defer ts.Close() res, err := (&Client{}).FetchCert(context.Background(), ts.URL, false) if err != nil { t.Fatalf("FetchCert: %v", err) } cert := [][]byte{{1}} if !reflect.DeepEqual(res, cert) { t.Errorf("res = %v; want %v", res, cert) } } func TestFetchCertCancel(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Retry-After", "0") w.WriteHeader(http.StatusAccepted) })) defer ts.Close() ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) var err error go func() { _, err = (&Client{}).FetchCert(ctx, ts.URL, false) close(done) }() cancel() <-done if err != context.Canceled { t.Errorf("err = %v; want %v", err, context.Canceled) } } func TestFetchCertDepth(t *testing.T) { var count byte var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { count++ if count > maxChainLen+1 { t.Errorf("count = %d; want at most %d", count, maxChainLen+1) w.WriteHeader(http.StatusInternalServerError) } w.Header().Set("Link", fmt.Sprintf("<%s>;rel=up", ts.URL)) w.Write([]byte{count}) })) defer ts.Close() _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true) if err == nil { t.Errorf("err is nil") } } func TestFetchCertBreadth(t *testing.T) { var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for i := 0; i < maxChainLen+1; i++ { w.Header().Add("Link", fmt.Sprintf("<%s>;rel=up", ts.URL)) } w.Write([]byte{1}) })) defer ts.Close() _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true) if err == nil { t.Errorf("err is nil") } } func TestFetchCertSize(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b := bytes.Repeat([]byte{1}, maxCertSize+1) w.Write(b) })) defer ts.Close() _, err := (&Client{}).FetchCert(context.Background(), ts.URL, false) if err == nil { t.Errorf("err is nil") } } func TestRevokeCert(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Replay-Nonce", "nonce") return } var req struct { Resource string Certificate string Reason int } decodeJWSRequest(t, &req, r) if req.Resource != "revoke-cert" { t.Errorf("req.Resource = %q; want revoke-cert", req.Resource) } if req.Reason != 1 { t.Errorf("req.Reason = %d; want 1", req.Reason) } // echo -n cert | base64 | tr -d '=' | tr '/+' '_-' cert := "Y2VydA" if req.Certificate != cert { t.Errorf("req.Certificate = %q; want %q", req.Certificate, cert) } })) defer ts.Close() client := &Client{ Key: testKeyEC, dir: &Directory{RevokeURL: ts.URL}, } ctx := context.Background() if err := client.RevokeCert(ctx, nil, []byte("cert"), CRLReasonKeyCompromise); err != nil { t.Fatal(err) } } func TestNonce_add(t *testing.T) { var c Client c.addNonce(http.Header{"Replay-Nonce": {"nonce"}}) c.addNonce(http.Header{"Replay-Nonce": {}}) c.addNonce(http.Header{"Replay-Nonce": {"nonce"}}) nonces := map[string]struct{}{"nonce": struct{}{}} if !reflect.DeepEqual(c.nonces, nonces) { t.Errorf("c.nonces = %q; want %q", c.nonces, nonces) } } func TestNonce_addMax(t *testing.T) { c := &Client{nonces: make(map[string]struct{})} for i := 0; i < maxNonces; i++ { c.nonces[fmt.Sprintf("%d", i)] = struct{}{} } c.addNonce(http.Header{"Replay-Nonce": {"nonce"}}) if n := len(c.nonces); n != maxNonces { t.Errorf("len(c.nonces) = %d; want %d", n, maxNonces) } } func TestNonce_fetch(t *testing.T) { tests := []struct { code int nonce string }{ {http.StatusOK, "nonce1"}, {http.StatusBadRequest, "nonce2"}, {http.StatusOK, ""}, } var i int ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "HEAD" { t.Errorf("%d: r.Method = %q; want HEAD", i, r.Method) } w.Header().Set("Replay-Nonce", tests[i].nonce) w.WriteHeader(tests[i].code) })) defer ts.Close() for ; i < len(tests); i++ { test := tests[i] c := &Client{} n, err := c.fetchNonce(context.Background(), ts.URL) if n != test.nonce { t.Errorf("%d: n=%q; want %q", i, n, test.nonce) } switch { case err == nil && test.nonce == "": t.Errorf("%d: n=%q, err=%v; want non-nil error", i, n, err) case err != nil && test.nonce != "": t.Errorf("%d: n=%q, err=%v; want %q", i, n, err, test.nonce) } } } func TestNonce_fetchError(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTooManyRequests) })) defer ts.Close() c := &Client{} _, err := c.fetchNonce(context.Background(), ts.URL) e, ok := err.(*Error) if !ok { t.Fatalf("err is %T; want *Error", err) } if e.StatusCode != http.StatusTooManyRequests { t.Errorf("e.StatusCode = %d; want %d", e.StatusCode, http.StatusTooManyRequests) } } func TestNonce_postJWS(t *testing.T) { var count int seen := make(map[string]bool) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { count++ w.Header().Set("Replay-Nonce", fmt.Sprintf("nonce%d", count)) if r.Method == "HEAD" { // We expect the client do a HEAD request // but only to fetch the first nonce. return } // Make client.Authorize happy; we're not testing its result. defer func() { w.WriteHeader(http.StatusCreated) w.Write([]byte(`{"status":"valid"}`)) }() head, err := decodeJWSHead(r) if err != nil { t.Errorf("decodeJWSHead: %v", err) return } if head.Nonce == "" { t.Error("head.Nonce is empty") return } if seen[head.Nonce] { t.Errorf("nonce is already used: %q", head.Nonce) } seen[head.Nonce] = true })) defer ts.Close() client := Client{Key: testKey, dir: &Directory{AuthzURL: ts.URL}} if _, err := client.Authorize(context.Background(), "example.com"); err != nil { t.Errorf("client.Authorize 1: %v", err) } // The second call should not generate another extra HEAD request. if _, err := client.Authorize(context.Background(), "example.com"); err != nil { t.Errorf("client.Authorize 2: %v", err) } if count != 3 { t.Errorf("total requests count: %d; want 3", count) } if n := len(client.nonces); n != 1 { t.Errorf("len(client.nonces) = %d; want 1", n) } for k := range seen { if _, exist := client.nonces[k]; exist { t.Errorf("used nonce %q in client.nonces", k) } } } func TestRetryPostJWS(t *testing.T) { var count int ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { count++ w.Header().Set("Replay-Nonce", fmt.Sprintf("nonce%d", count)) if r.Method == "HEAD" { // We expect the client to do 2 head requests to fetch // nonces, one to start and another after getting badNonce return } head, err := decodeJWSHead(r) if err != nil { t.Errorf("decodeJWSHead: %v", err) } else if head.Nonce == "" { t.Error("head.Nonce is empty") } else if head.Nonce == "nonce1" { // return a badNonce error to force the call to retry w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"type":"urn:ietf:params:acme:error:badNonce"}`)) return } // Make client.Authorize happy; we're not testing its result. w.WriteHeader(http.StatusCreated) w.Write([]byte(`{"status":"valid"}`)) })) defer ts.Close() client := Client{Key: testKey, dir: &Directory{AuthzURL: ts.URL}} // This call will fail with badNonce, causing a retry if _, err := client.Authorize(context.Background(), "example.com"); err != nil { t.Errorf("client.Authorize 1: %v", err) } if count != 4 { t.Errorf("total requests count: %d; want 4", count) } } func TestLinkHeader(t *testing.T) { h := http.Header{"Link": { `<https://example.com/acme/new-authz>;rel="next"`, `<https://example.com/acme/recover-reg>; rel=recover`, `<https://example.com/acme/terms>; foo=bar; rel="terms-of-service"`, `<dup>;rel="next"`, }} tests := []struct { rel string out []string }{ {"next", []string{"https://example.com/acme/new-authz", "dup"}}, {"recover", []string{"https://example.com/acme/recover-reg"}}, {"terms-of-service", []string{"https://example.com/acme/terms"}}, {"empty", nil}, } for i, test := range tests { if v := linkHeader(h, test.rel); !reflect.DeepEqual(v, test.out) { t.Errorf("%d: linkHeader(%q): %v; want %v", i, test.rel, v, test.out) } } } func TestErrorResponse(t *testing.T) { s := `{ "status": 400, "type": "urn:acme:error:xxx", "detail": "text" }` res := &http.Response{ StatusCode: 400, Status: "400 Bad Request", Body: ioutil.NopCloser(strings.NewReader(s)), Header: http.Header{"X-Foo": {"bar"}}, } err := responseError(res) v, ok := err.(*Error) if !ok { t.Fatalf("err = %+v (%T); want *Error type", err, err) } if v.StatusCode != 400 { t.Errorf("v.StatusCode = %v; want 400", v.StatusCode) } if v.ProblemType != "urn:acme:error:xxx" { t.Errorf("v.ProblemType = %q; want urn:acme:error:xxx", v.ProblemType) } if v.Detail != "text" { t.Errorf("v.Detail = %q; want text", v.Detail) } if !reflect.DeepEqual(v.Header, res.Header) { t.Errorf("v.Header = %+v; want %+v", v.Header, res.Header) } } func TestTLSSNI01ChallengeCert(t *testing.T) { const ( token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA" // echo -n <token.testKeyECThumbprint> | shasum -a 256 san = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.acme.invalid" ) client := &Client{Key: testKeyEC} tlscert, name, err := client.TLSSNI01ChallengeCert(token) if err != nil { t.Fatal(err) } if n := len(tlscert.Certificate); n != 1 { t.Fatalf("len(tlscert.Certificate) = %d; want 1", n) } cert, err := x509.ParseCertificate(tlscert.Certificate[0]) if err != nil { t.Fatal(err) } if len(cert.DNSNames) != 1 || cert.DNSNames[0] != san { t.Fatalf("cert.DNSNames = %v; want %q", cert.DNSNames, san) } if cert.DNSNames[0] != name { t.Errorf("cert.DNSNames[0] != name: %q vs %q", cert.DNSNames[0], name) } if cn := cert.Subject.CommonName; cn != san { t.Errorf("cert.Subject.CommonName = %q; want %q", cn, san) } } func TestTLSSNI02ChallengeCert(t *testing.T) { const ( token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA" // echo -n evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA | shasum -a 256 sanA = "7ea0aaa69214e71e02cebb18bb867736.09b730209baabf60e43d4999979ff139.token.acme.invalid" // echo -n <token.testKeyECThumbprint> | shasum -a 256 sanB = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.ka.acme.invalid" ) client := &Client{Key: testKeyEC} tlscert, name, err := client.TLSSNI02ChallengeCert(token) if err != nil { t.Fatal(err) } if n := len(tlscert.Certificate); n != 1 { t.Fatalf("len(tlscert.Certificate) = %d; want 1", n) } cert, err := x509.ParseCertificate(tlscert.Certificate[0]) if err != nil { t.Fatal(err) } names := []string{sanA, sanB} if !reflect.DeepEqual(cert.DNSNames, names) { t.Fatalf("cert.DNSNames = %v;\nwant %v", cert.DNSNames, names) } sort.Strings(cert.DNSNames) i := sort.SearchStrings(cert.DNSNames, name) if i >= len(cert.DNSNames) || cert.DNSNames[i] != name { t.Errorf("%v doesn't have %q", cert.DNSNames, name) } if cn := cert.Subject.CommonName; cn != sanA { t.Errorf("CommonName = %q; want %q", cn, sanA) } } func TestTLSChallengeCertOpt(t *testing.T) { key, err := rsa.GenerateKey(rand.Reader, 512) if err != nil { t.Fatal(err) } tmpl := &x509.Certificate{ SerialNumber: big.NewInt(2), Subject: pkix.Name{Organization: []string{"Test"}}, DNSNames: []string{"should-be-overwritten"}, } opts := []CertOption{WithKey(key), WithTemplate(tmpl)} client := &Client{Key: testKeyEC} cert1, _, err := client.TLSSNI01ChallengeCert("token", opts...) if err != nil { t.Fatal(err) } cert2, _, err := client.TLSSNI02ChallengeCert("token", opts...) if err != nil { t.Fatal(err) } for i, tlscert := range []tls.Certificate{cert1, cert2} { // verify generated cert private key tlskey, ok := tlscert.PrivateKey.(*rsa.PrivateKey) if !ok { t.Errorf("%d: tlscert.PrivateKey is %T; want *rsa.PrivateKey", i, tlscert.PrivateKey) continue } if tlskey.D.Cmp(key.D) != 0 { t.Errorf("%d: tlskey.D = %v; want %v", i, tlskey.D, key.D) } // verify generated cert public key x509Cert, err := x509.ParseCertificate(tlscert.Certificate[0]) if err != nil { t.Errorf("%d: %v", i, err) continue } tlspub, ok := x509Cert.PublicKey.(*rsa.PublicKey) if !ok { t.Errorf("%d: x509Cert.PublicKey is %T; want *rsa.PublicKey", i, x509Cert.PublicKey) continue } if tlspub.N.Cmp(key.N) != 0 { t.Errorf("%d: tlspub.N = %v; want %v", i, tlspub.N, key.N) } // verify template option sn := big.NewInt(2) if x509Cert.SerialNumber.Cmp(sn) != 0 { t.Errorf("%d: SerialNumber = %v; want %v", i, x509Cert.SerialNumber, sn) } org := []string{"Test"} if !reflect.DeepEqual(x509Cert.Subject.Organization, org) { t.Errorf("%d: Subject.Organization = %+v; want %+v", i, x509Cert.Subject.Organization, org) } for _, v := range x509Cert.DNSNames { if !strings.HasSuffix(v, ".acme.invalid") { t.Errorf("%d: invalid DNSNames element: %q", i, v) } } } } func TestHTTP01Challenge(t *testing.T) { const ( token = "xxx" // thumbprint is precomputed for testKeyEC in jws_test.go value = token + "." + testKeyECThumbprint urlpath = "/.well-known/acme-challenge/" + token ) client := &Client{Key: testKeyEC} val, err := client.HTTP01ChallengeResponse(token) if err != nil { t.Fatal(err) } if val != value { t.Errorf("val = %q; want %q", val, value) } if path := client.HTTP01ChallengePath(token); path != urlpath { t.Errorf("path = %q; want %q", path, urlpath) } } func TestDNS01ChallengeRecord(t *testing.T) { // echo -n xxx.<testKeyECThumbprint> | \ // openssl dgst -binary -sha256 | \ // base64 | tr -d '=' | tr '/+' '_-' const value = "8DERMexQ5VcdJ_prpPiA0mVdp7imgbCgjsG4SqqNMIo" client := &Client{Key: testKeyEC} val, err := client.DNS01ChallengeRecord("xxx") if err != nil { t.Fatal(err) } if val != value { t.Errorf("val = %q; want %q", val, value) } } func TestBackoff(t *testing.T) { tt := []struct{ min, max time.Duration }{ {time.Second, 2 * time.Second}, {2 * time.Second, 3 * time.Second}, {4 * time.Second, 5 * time.Second}, {8 * time.Second, 9 * time.Second}, } for i, test := range tt { d := backoff(i, time.Minute) if d < test.min || test.max < d { t.Errorf("%d: d = %v; want between %v and %v", i, d, test.min, test.max) } } min, max := time.Second, 2*time.Second if d := backoff(-1, time.Minute); d < min || max < d { t.Errorf("d = %v; want between %v and %v", d, min, max) } bound := 10 * time.Second if d := backoff(100, bound); d != bound { t.Errorf("d = %v; want %v", d, bound) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/acme/acme.go������������������������������������������������0000644�0610621�0607500�00000077166�13172163317�023234� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package acme provides an implementation of the // Automatic Certificate Management Environment (ACME) spec. // See https://tools.ietf.org/html/draft-ietf-acme-acme-02 for details. // // Most common scenarios will want to use autocert subdirectory instead, // which provides automatic access to certificates from Let's Encrypt // and any other ACME-based CA. // // This package is a work in progress and makes no API stability promises. package acme import ( "bytes" "context" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/hex" "encoding/json" "encoding/pem" "errors" "fmt" "io" "io/ioutil" "math/big" "net/http" "strconv" "strings" "sync" "time" ) // LetsEncryptURL is the Directory endpoint of Let's Encrypt CA. const LetsEncryptURL = "https://acme-v01.api.letsencrypt.org/directory" const ( maxChainLen = 5 // max depth and breadth of a certificate chain maxCertSize = 1 << 20 // max size of a certificate, in bytes // Max number of collected nonces kept in memory. // Expect usual peak of 1 or 2. maxNonces = 100 ) // Client is an ACME client. // The only required field is Key. An example of creating a client with a new key // is as follows: // // key, err := rsa.GenerateKey(rand.Reader, 2048) // if err != nil { // log.Fatal(err) // } // client := &Client{Key: key} // type Client struct { // Key is the account key used to register with a CA and sign requests. // Key.Public() must return a *rsa.PublicKey or *ecdsa.PublicKey. Key crypto.Signer // HTTPClient optionally specifies an HTTP client to use // instead of http.DefaultClient. HTTPClient *http.Client // DirectoryURL points to the CA directory endpoint. // If empty, LetsEncryptURL is used. // Mutating this value after a successful call of Client's Discover method // will have no effect. DirectoryURL string dirMu sync.Mutex // guards writes to dir dir *Directory // cached result of Client's Discover method noncesMu sync.Mutex nonces map[string]struct{} // nonces collected from previous responses } // Discover performs ACME server discovery using c.DirectoryURL. // // It caches successful result. So, subsequent calls will not result in // a network round-trip. This also means mutating c.DirectoryURL after successful call // of this method will have no effect. func (c *Client) Discover(ctx context.Context) (Directory, error) { c.dirMu.Lock() defer c.dirMu.Unlock() if c.dir != nil { return *c.dir, nil } dirURL := c.DirectoryURL if dirURL == "" { dirURL = LetsEncryptURL } res, err := c.get(ctx, dirURL) if err != nil { return Directory{}, err } defer res.Body.Close() c.addNonce(res.Header) if res.StatusCode != http.StatusOK { return Directory{}, responseError(res) } var v struct { Reg string `json:"new-reg"` Authz string `json:"new-authz"` Cert string `json:"new-cert"` Revoke string `json:"revoke-cert"` Meta struct { Terms string `json:"terms-of-service"` Website string `json:"website"` CAA []string `json:"caa-identities"` } } if err := json.NewDecoder(res.Body).Decode(&v); err != nil { return Directory{}, err } c.dir = &Directory{ RegURL: v.Reg, AuthzURL: v.Authz, CertURL: v.Cert, RevokeURL: v.Revoke, Terms: v.Meta.Terms, Website: v.Meta.Website, CAA: v.Meta.CAA, } return *c.dir, nil } // CreateCert requests a new certificate using the Certificate Signing Request csr encoded in DER format. // The exp argument indicates the desired certificate validity duration. CA may issue a certificate // with a different duration. // If the bundle argument is true, the returned value will also contain the CA (issuer) certificate chain. // // In the case where CA server does not provide the issued certificate in the response, // CreateCert will poll certURL using c.FetchCert, which will result in additional round-trips. // In such a scenario, the caller can cancel the polling with ctx. // // CreateCert returns an error if the CA's response or chain was unreasonably large. // Callers are encouraged to parse the returned value to ensure the certificate is valid and has the expected features. func (c *Client) CreateCert(ctx context.Context, csr []byte, exp time.Duration, bundle bool) (der [][]byte, certURL string, err error) { if _, err := c.Discover(ctx); err != nil { return nil, "", err } req := struct { Resource string `json:"resource"` CSR string `json:"csr"` NotBefore string `json:"notBefore,omitempty"` NotAfter string `json:"notAfter,omitempty"` }{ Resource: "new-cert", CSR: base64.RawURLEncoding.EncodeToString(csr), } now := timeNow() req.NotBefore = now.Format(time.RFC3339) if exp > 0 { req.NotAfter = now.Add(exp).Format(time.RFC3339) } res, err := c.retryPostJWS(ctx, c.Key, c.dir.CertURL, req) if err != nil { return nil, "", err } defer res.Body.Close() if res.StatusCode != http.StatusCreated { return nil, "", responseError(res) } curl := res.Header.Get("Location") // cert permanent URL if res.ContentLength == 0 { // no cert in the body; poll until we get it cert, err := c.FetchCert(ctx, curl, bundle) return cert, curl, err } // slurp issued cert and CA chain, if requested cert, err := c.responseCert(ctx, res, bundle) return cert, curl, err } // FetchCert retrieves already issued certificate from the given url, in DER format. // It retries the request until the certificate is successfully retrieved, // context is cancelled by the caller or an error response is received. // // The returned value will also contain the CA (issuer) certificate if the bundle argument is true. // // FetchCert returns an error if the CA's response or chain was unreasonably large. // Callers are encouraged to parse the returned value to ensure the certificate is valid // and has expected features. func (c *Client) FetchCert(ctx context.Context, url string, bundle bool) ([][]byte, error) { for { res, err := c.get(ctx, url) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode == http.StatusOK { return c.responseCert(ctx, res, bundle) } if res.StatusCode > 299 { return nil, responseError(res) } d := retryAfter(res.Header.Get("Retry-After"), 3*time.Second) select { case <-time.After(d): // retry case <-ctx.Done(): return nil, ctx.Err() } } } // RevokeCert revokes a previously issued certificate cert, provided in DER format. // // The key argument, used to sign the request, must be authorized // to revoke the certificate. It's up to the CA to decide which keys are authorized. // For instance, the key pair of the certificate may be authorized. // If the key is nil, c.Key is used instead. func (c *Client) RevokeCert(ctx context.Context, key crypto.Signer, cert []byte, reason CRLReasonCode) error { if _, err := c.Discover(ctx); err != nil { return err } body := &struct { Resource string `json:"resource"` Cert string `json:"certificate"` Reason int `json:"reason"` }{ Resource: "revoke-cert", Cert: base64.RawURLEncoding.EncodeToString(cert), Reason: int(reason), } if key == nil { key = c.Key } res, err := c.retryPostJWS(ctx, key, c.dir.RevokeURL, body) if err != nil { return err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return responseError(res) } return nil } // AcceptTOS always returns true to indicate the acceptance of a CA's Terms of Service // during account registration. See Register method of Client for more details. func AcceptTOS(tosURL string) bool { return true } // Register creates a new account registration by following the "new-reg" flow. // It returns the registered account. The account is not modified. // // The registration may require the caller to agree to the CA's Terms of Service (TOS). // If so, and the account has not indicated the acceptance of the terms (see Account for details), // Register calls prompt with a TOS URL provided by the CA. Prompt should report // whether the caller agrees to the terms. To always accept the terms, the caller can use AcceptTOS. func (c *Client) Register(ctx context.Context, a *Account, prompt func(tosURL string) bool) (*Account, error) { if _, err := c.Discover(ctx); err != nil { return nil, err } var err error if a, err = c.doReg(ctx, c.dir.RegURL, "new-reg", a); err != nil { return nil, err } var accept bool if a.CurrentTerms != "" && a.CurrentTerms != a.AgreedTerms { accept = prompt(a.CurrentTerms) } if accept { a.AgreedTerms = a.CurrentTerms a, err = c.UpdateReg(ctx, a) } return a, err } // GetReg retrieves an existing registration. // The url argument is an Account URI. func (c *Client) GetReg(ctx context.Context, url string) (*Account, error) { a, err := c.doReg(ctx, url, "reg", nil) if err != nil { return nil, err } a.URI = url return a, nil } // UpdateReg updates an existing registration. // It returns an updated account copy. The provided account is not modified. func (c *Client) UpdateReg(ctx context.Context, a *Account) (*Account, error) { uri := a.URI a, err := c.doReg(ctx, uri, "reg", a) if err != nil { return nil, err } a.URI = uri return a, nil } // Authorize performs the initial step in an authorization flow. // The caller will then need to choose from and perform a set of returned // challenges using c.Accept in order to successfully complete authorization. // // If an authorization has been previously granted, the CA may return // a valid authorization (Authorization.Status is StatusValid). If so, the caller // need not fulfill any challenge and can proceed to requesting a certificate. func (c *Client) Authorize(ctx context.Context, domain string) (*Authorization, error) { if _, err := c.Discover(ctx); err != nil { return nil, err } type authzID struct { Type string `json:"type"` Value string `json:"value"` } req := struct { Resource string `json:"resource"` Identifier authzID `json:"identifier"` }{ Resource: "new-authz", Identifier: authzID{Type: "dns", Value: domain}, } res, err := c.retryPostJWS(ctx, c.Key, c.dir.AuthzURL, req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusCreated { return nil, responseError(res) } var v wireAuthz if err := json.NewDecoder(res.Body).Decode(&v); err != nil { return nil, fmt.Errorf("acme: invalid response: %v", err) } if v.Status != StatusPending && v.Status != StatusValid { return nil, fmt.Errorf("acme: unexpected status: %s", v.Status) } return v.authorization(res.Header.Get("Location")), nil } // GetAuthorization retrieves an authorization identified by the given URL. // // If a caller needs to poll an authorization until its status is final, // see the WaitAuthorization method. func (c *Client) GetAuthorization(ctx context.Context, url string) (*Authorization, error) { res, err := c.get(ctx, url) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted { return nil, responseError(res) } var v wireAuthz if err := json.NewDecoder(res.Body).Decode(&v); err != nil { return nil, fmt.Errorf("acme: invalid response: %v", err) } return v.authorization(url), nil } // RevokeAuthorization relinquishes an existing authorization identified // by the given URL. // The url argument is an Authorization.URI value. // // If successful, the caller will be required to obtain a new authorization // using the Authorize method before being able to request a new certificate // for the domain associated with the authorization. // // It does not revoke existing certificates. func (c *Client) RevokeAuthorization(ctx context.Context, url string) error { req := struct { Resource string `json:"resource"` Status string `json:"status"` Delete bool `json:"delete"` }{ Resource: "authz", Status: "deactivated", Delete: true, } res, err := c.retryPostJWS(ctx, c.Key, url, req) if err != nil { return err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return responseError(res) } return nil } // WaitAuthorization polls an authorization at the given URL // until it is in one of the final states, StatusValid or StatusInvalid, // or the context is done. // // It returns a non-nil Authorization only if its Status is StatusValid. // In all other cases WaitAuthorization returns an error. // If the Status is StatusInvalid, the returned error is of type *AuthorizationError. func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorization, error) { sleep := sleeper(ctx) for { res, err := c.get(ctx, url) if err != nil { return nil, err } retry := res.Header.Get("Retry-After") if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted { res.Body.Close() if err := sleep(retry, 1); err != nil { return nil, err } continue } var raw wireAuthz err = json.NewDecoder(res.Body).Decode(&raw) res.Body.Close() if err != nil { if err := sleep(retry, 0); err != nil { return nil, err } continue } if raw.Status == StatusValid { return raw.authorization(url), nil } if raw.Status == StatusInvalid { return nil, raw.error(url) } if err := sleep(retry, 0); err != nil { return nil, err } } } // GetChallenge retrieves the current status of an challenge. // // A client typically polls a challenge status using this method. func (c *Client) GetChallenge(ctx context.Context, url string) (*Challenge, error) { res, err := c.get(ctx, url) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted { return nil, responseError(res) } v := wireChallenge{URI: url} if err := json.NewDecoder(res.Body).Decode(&v); err != nil { return nil, fmt.Errorf("acme: invalid response: %v", err) } return v.challenge(), nil } // Accept informs the server that the client accepts one of its challenges // previously obtained with c.Authorize. // // The server will then perform the validation asynchronously. func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error) { auth, err := keyAuth(c.Key.Public(), chal.Token) if err != nil { return nil, err } req := struct { Resource string `json:"resource"` Type string `json:"type"` Auth string `json:"keyAuthorization"` }{ Resource: "challenge", Type: chal.Type, Auth: auth, } res, err := c.retryPostJWS(ctx, c.Key, chal.URI, req) if err != nil { return nil, err } defer res.Body.Close() // Note: the protocol specifies 200 as the expected response code, but // letsencrypt seems to be returning 202. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted { return nil, responseError(res) } var v wireChallenge if err := json.NewDecoder(res.Body).Decode(&v); err != nil { return nil, fmt.Errorf("acme: invalid response: %v", err) } return v.challenge(), nil } // DNS01ChallengeRecord returns a DNS record value for a dns-01 challenge response. // A TXT record containing the returned value must be provisioned under // "_acme-challenge" name of the domain being validated. // // The token argument is a Challenge.Token value. func (c *Client) DNS01ChallengeRecord(token string) (string, error) { ka, err := keyAuth(c.Key.Public(), token) if err != nil { return "", err } b := sha256.Sum256([]byte(ka)) return base64.RawURLEncoding.EncodeToString(b[:]), nil } // HTTP01ChallengeResponse returns the response for an http-01 challenge. // Servers should respond with the value to HTTP requests at the URL path // provided by HTTP01ChallengePath to validate the challenge and prove control // over a domain name. // // The token argument is a Challenge.Token value. func (c *Client) HTTP01ChallengeResponse(token string) (string, error) { return keyAuth(c.Key.Public(), token) } // HTTP01ChallengePath returns the URL path at which the response for an http-01 challenge // should be provided by the servers. // The response value can be obtained with HTTP01ChallengeResponse. // // The token argument is a Challenge.Token value. func (c *Client) HTTP01ChallengePath(token string) string { return "/.well-known/acme-challenge/" + token } // TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response. // Servers can present the certificate to validate the challenge and prove control // over a domain name. // // The implementation is incomplete in that the returned value is a single certificate, // computed only for Z0 of the key authorization. ACME CAs are expected to update // their implementations to use the newer version, TLS-SNI-02. // For more details on TLS-SNI-01 see https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-7.3. // // The token argument is a Challenge.Token value. // If a WithKey option is provided, its private part signs the returned cert, // and the public part is used to specify the signee. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve. // // The returned certificate is valid for the next 24 hours and must be presented only when // the server name of the client hello matches exactly the returned name value. func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) { ka, err := keyAuth(c.Key.Public(), token) if err != nil { return tls.Certificate{}, "", err } b := sha256.Sum256([]byte(ka)) h := hex.EncodeToString(b[:]) name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:]) cert, err = tlsChallengeCert([]string{name}, opt) if err != nil { return tls.Certificate{}, "", err } return cert, name, nil } // TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response. // Servers can present the certificate to validate the challenge and prove control // over a domain name. For more details on TLS-SNI-02 see // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-7.3. // // The token argument is a Challenge.Token value. // If a WithKey option is provided, its private part signs the returned cert, // and the public part is used to specify the signee. // If no WithKey option is provided, a new ECDSA key is generated using P-256 curve. // // The returned certificate is valid for the next 24 hours and must be presented only when // the server name in the client hello matches exactly the returned name value. func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) { b := sha256.Sum256([]byte(token)) h := hex.EncodeToString(b[:]) sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:]) ka, err := keyAuth(c.Key.Public(), token) if err != nil { return tls.Certificate{}, "", err } b = sha256.Sum256([]byte(ka)) h = hex.EncodeToString(b[:]) sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:]) cert, err = tlsChallengeCert([]string{sanA, sanB}, opt) if err != nil { return tls.Certificate{}, "", err } return cert, sanA, nil } // doReg sends all types of registration requests. // The type of request is identified by typ argument, which is a "resource" // in the ACME spec terms. // // A non-nil acct argument indicates whether the intention is to mutate data // of the Account. Only Contact and Agreement of its fields are used // in such cases. func (c *Client) doReg(ctx context.Context, url string, typ string, acct *Account) (*Account, error) { req := struct { Resource string `json:"resource"` Contact []string `json:"contact,omitempty"` Agreement string `json:"agreement,omitempty"` }{ Resource: typ, } if acct != nil { req.Contact = acct.Contact req.Agreement = acct.AgreedTerms } res, err := c.retryPostJWS(ctx, c.Key, url, req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode < 200 || res.StatusCode > 299 { return nil, responseError(res) } var v struct { Contact []string Agreement string Authorizations string Certificates string } if err := json.NewDecoder(res.Body).Decode(&v); err != nil { return nil, fmt.Errorf("acme: invalid response: %v", err) } var tos string if v := linkHeader(res.Header, "terms-of-service"); len(v) > 0 { tos = v[0] } var authz string if v := linkHeader(res.Header, "next"); len(v) > 0 { authz = v[0] } return &Account{ URI: res.Header.Get("Location"), Contact: v.Contact, AgreedTerms: v.Agreement, CurrentTerms: tos, Authz: authz, Authorizations: v.Authorizations, Certificates: v.Certificates, }, nil } // retryPostJWS will retry calls to postJWS if there is a badNonce error, // clearing the stored nonces after each error. // If the response was 4XX-5XX, then responseError is called on the body, // the body is closed, and the error returned. func (c *Client) retryPostJWS(ctx context.Context, key crypto.Signer, url string, body interface{}) (*http.Response, error) { sleep := sleeper(ctx) for { res, err := c.postJWS(ctx, key, url, body) if err != nil { return nil, err } // handle errors 4XX-5XX with responseError if res.StatusCode >= 400 && res.StatusCode <= 599 { err := responseError(res) res.Body.Close() // according to spec badNonce is urn:ietf:params:acme:error:badNonce // however, acme servers in the wild return their version of the error // https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-5.4 if ae, ok := err.(*Error); ok && strings.HasSuffix(strings.ToLower(ae.ProblemType), ":badnonce") { // clear any nonces that we might've stored that might now be // considered bad c.clearNonces() retry := res.Header.Get("Retry-After") if err := sleep(retry, 1); err != nil { return nil, err } continue } return nil, err } return res, nil } } // postJWS signs the body with the given key and POSTs it to the provided url. // The body argument must be JSON-serializable. func (c *Client) postJWS(ctx context.Context, key crypto.Signer, url string, body interface{}) (*http.Response, error) { nonce, err := c.popNonce(ctx, url) if err != nil { return nil, err } b, err := jwsEncodeJSON(body, key, nonce) if err != nil { return nil, err } res, err := c.post(ctx, url, "application/jose+json", bytes.NewReader(b)) if err != nil { return nil, err } c.addNonce(res.Header) return res, nil } // popNonce returns a nonce value previously stored with c.addNonce // or fetches a fresh one from the given URL. func (c *Client) popNonce(ctx context.Context, url string) (string, error) { c.noncesMu.Lock() defer c.noncesMu.Unlock() if len(c.nonces) == 0 { return c.fetchNonce(ctx, url) } var nonce string for nonce = range c.nonces { delete(c.nonces, nonce) break } return nonce, nil } // clearNonces clears any stored nonces func (c *Client) clearNonces() { c.noncesMu.Lock() defer c.noncesMu.Unlock() c.nonces = make(map[string]struct{}) } // addNonce stores a nonce value found in h (if any) for future use. func (c *Client) addNonce(h http.Header) { v := nonceFromHeader(h) if v == "" { return } c.noncesMu.Lock() defer c.noncesMu.Unlock() if len(c.nonces) >= maxNonces { return } if c.nonces == nil { c.nonces = make(map[string]struct{}) } c.nonces[v] = struct{}{} } func (c *Client) httpClient() *http.Client { if c.HTTPClient != nil { return c.HTTPClient } return http.DefaultClient } func (c *Client) get(ctx context.Context, urlStr string) (*http.Response, error) { req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return nil, err } return c.do(ctx, req) } func (c *Client) head(ctx context.Context, urlStr string) (*http.Response, error) { req, err := http.NewRequest("HEAD", urlStr, nil) if err != nil { return nil, err } return c.do(ctx, req) } func (c *Client) post(ctx context.Context, urlStr, contentType string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest("POST", urlStr, body) if err != nil { return nil, err } req.Header.Set("Content-Type", contentType) return c.do(ctx, req) } func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, error) { res, err := c.httpClient().Do(req.WithContext(ctx)) if err != nil { select { case <-ctx.Done(): // Prefer the unadorned context error. // (The acme package had tests assuming this, previously from ctxhttp's // behavior, predating net/http supporting contexts natively) // TODO(bradfitz): reconsider this in the future. But for now this // requires no test updates. return nil, ctx.Err() default: return nil, err } } return res, nil } func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) { resp, err := c.head(ctx, url) if err != nil { return "", err } defer resp.Body.Close() nonce := nonceFromHeader(resp.Header) if nonce == "" { if resp.StatusCode > 299 { return "", responseError(resp) } return "", errors.New("acme: nonce not found") } return nonce, nil } func nonceFromHeader(h http.Header) string { return h.Get("Replay-Nonce") } func (c *Client) responseCert(ctx context.Context, res *http.Response, bundle bool) ([][]byte, error) { b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1)) if err != nil { return nil, fmt.Errorf("acme: response stream: %v", err) } if len(b) > maxCertSize { return nil, errors.New("acme: certificate is too big") } cert := [][]byte{b} if !bundle { return cert, nil } // Append CA chain cert(s). // At least one is required according to the spec: // https://tools.ietf.org/html/draft-ietf-acme-acme-03#section-6.3.1 up := linkHeader(res.Header, "up") if len(up) == 0 { return nil, errors.New("acme: rel=up link not found") } if len(up) > maxChainLen { return nil, errors.New("acme: rel=up link is too large") } for _, url := range up { cc, err := c.chainCert(ctx, url, 0) if err != nil { return nil, err } cert = append(cert, cc...) } return cert, nil } // responseError creates an error of Error type from resp. func responseError(resp *http.Response) error { // don't care if ReadAll returns an error: // json.Unmarshal will fail in that case anyway b, _ := ioutil.ReadAll(resp.Body) e := &wireError{Status: resp.StatusCode} if err := json.Unmarshal(b, e); err != nil { // this is not a regular error response: // populate detail with anything we received, // e.Status will already contain HTTP response code value e.Detail = string(b) if e.Detail == "" { e.Detail = resp.Status } } return e.error(resp.Header) } // chainCert fetches CA certificate chain recursively by following "up" links. // Each recursive call increments the depth by 1, resulting in an error // if the recursion level reaches maxChainLen. // // First chainCert call starts with depth of 0. func (c *Client) chainCert(ctx context.Context, url string, depth int) ([][]byte, error) { if depth >= maxChainLen { return nil, errors.New("acme: certificate chain is too deep") } res, err := c.get(ctx, url) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, responseError(res) } b, err := ioutil.ReadAll(io.LimitReader(res.Body, maxCertSize+1)) if err != nil { return nil, err } if len(b) > maxCertSize { return nil, errors.New("acme: certificate is too big") } chain := [][]byte{b} uplink := linkHeader(res.Header, "up") if len(uplink) > maxChainLen { return nil, errors.New("acme: certificate chain is too large") } for _, up := range uplink { cc, err := c.chainCert(ctx, up, depth+1) if err != nil { return nil, err } chain = append(chain, cc...) } return chain, nil } // linkHeader returns URI-Reference values of all Link headers // with relation-type rel. // See https://tools.ietf.org/html/rfc5988#section-5 for details. func linkHeader(h http.Header, rel string) []string { var links []string for _, v := range h["Link"] { parts := strings.Split(v, ";") for _, p := range parts { p = strings.TrimSpace(p) if !strings.HasPrefix(p, "rel=") { continue } if v := strings.Trim(p[4:], `"`); v == rel { links = append(links, strings.Trim(parts[0], "<>")) } } } return links } // sleeper returns a function that accepts the Retry-After HTTP header value // and an increment that's used with backoff to increasingly sleep on // consecutive calls until the context is done. If the Retry-After header // cannot be parsed, then backoff is used with a maximum sleep time of 10 // seconds. func sleeper(ctx context.Context) func(ra string, inc int) error { var count int return func(ra string, inc int) error { count += inc d := backoff(count, 10*time.Second) d = retryAfter(ra, d) wakeup := time.NewTimer(d) defer wakeup.Stop() select { case <-ctx.Done(): return ctx.Err() case <-wakeup.C: return nil } } } // retryAfter parses a Retry-After HTTP header value, // trying to convert v into an int (seconds) or use http.ParseTime otherwise. // It returns d if v cannot be parsed. func retryAfter(v string, d time.Duration) time.Duration { if i, err := strconv.Atoi(v); err == nil { return time.Duration(i) * time.Second } t, err := http.ParseTime(v) if err != nil { return d } return t.Sub(timeNow()) } // backoff computes a duration after which an n+1 retry iteration should occur // using truncated exponential backoff algorithm. // // The n argument is always bounded between 0 and 30. // The max argument defines upper bound for the returned value. func backoff(n int, max time.Duration) time.Duration { if n < 0 { n = 0 } if n > 30 { n = 30 } var d time.Duration if x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil { d = time.Duration(x.Int64()) * time.Millisecond } d += time.Duration(1<<uint(n)) * time.Second if d > max { return max } return d } // keyAuth generates a key authorization string for a given token. func keyAuth(pub crypto.PublicKey, token string) (string, error) { th, err := JWKThumbprint(pub) if err != nil { return "", err } return fmt.Sprintf("%s.%s", token, th), nil } // tlsChallengeCert creates a temporary certificate for TLS-SNI challenges // with the given SANs and auto-generated public/private key pair. // The Subject Common Name is set to the first SAN to aid debugging. // To create a cert with a custom key pair, specify WithKey option. func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) { var ( key crypto.Signer tmpl *x509.Certificate ) for _, o := range opt { switch o := o.(type) { case *certOptKey: if key != nil { return tls.Certificate{}, errors.New("acme: duplicate key option") } key = o.key case *certOptTemplate: var t = *(*x509.Certificate)(o) // shallow copy is ok tmpl = &t default: // package's fault, if we let this happen: panic(fmt.Sprintf("unsupported option type %T", o)) } } if key == nil { var err error if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil { return tls.Certificate{}, err } } if tmpl == nil { tmpl = &x509.Certificate{ SerialNumber: big.NewInt(1), NotBefore: time.Now(), NotAfter: time.Now().Add(24 * time.Hour), BasicConstraintsValid: true, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, } } tmpl.DNSNames = san if len(san) > 0 { tmpl.Subject.CommonName = san[0] } der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key) if err != nil { return tls.Certificate{}, err } return tls.Certificate{ Certificate: [][]byte{der}, PrivateKey: key, }, nil } // encodePEM returns b encoded as PEM with block of type typ. func encodePEM(typ string, b []byte) []byte { pb := &pem.Block{Type: typ, Bytes: b} return pem.EncodeToMemory(pb) } // timeNow is useful for testing for fixed current time. var timeNow = time.Now ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/README.md���������������������������������������������������0000644�0610621�0607500�00000001423�13172163317�022331� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go Cryptography This repository holds supplementary Go cryptography libraries. ## Download/Install The easiest way to install is to run `go get -u golang.org/x/crypto/...`. You can also manually git clone the repository to `$GOPATH/src/golang.org/x/crypto`. ## Report Issues / Send Patches This repository uses Gerrit for code changes. To learn how to submit changes to this repository, see https://golang.org/doc/contribute.html. The main issue tracker for the crypto repository is located at https://github.com/golang/go/issues. Prefix your issue with "x/crypto:" in the subject line, so it is easy to find. Note that contributions to the cryptography package receive additional scrutiny due to their sensitive nature. Patches may take longer than normal to receive feedback. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/PATENTS�����������������������������������������������������0000644�0610621�0607500�00000002427�13172163317�022120� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Additional IP Rights Grant (Patents) "This implementation" means the copyrightable works distributed by Google as part of the Go project. Google hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer and otherwise run, modify and propagate the contents of this implementation of Go, where such license applies only to those patent claims, both currently owned or controlled by Google and acquired in the future, licensable by Google that are necessarily infringed by this implementation of Go. This grant does not include claims that would be infringed only as a consequence of further modification of this implementation. If you or your agent or exclusive licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that this implementation of Go or any code incorporated within this implementation of Go constitutes direct or contributory patent infringement, or inducement of patent infringement, then any patent rights granted to you under this License for this implementation of Go shall terminate as of the date such litigation is filed. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/LICENSE�����������������������������������������������������0000644�0610621�0607500�00000002707�13172163317�022065� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ���������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/CONTRIBUTORS������������������������������������������������0000644�0610621�0607500�00000000253�13172163317�022732� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at https://tip.golang.org/CONTRIBUTORS. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/CONTRIBUTING.md���������������������������������������������0000644�0610621�0607500�00000002007�13172163317�023302� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Contributing to Go Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! ## Filing issues When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: 1. What version of Go are you using (`go version`)? 2. What operating system and processor architecture are you using? 3. What did you do? 4. What did you expect to see? 5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. ## Contributing code Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. **We do not accept GitHub pull requests** (we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/golang.org/x/crypto/AUTHORS�����������������������������������������������������0000644�0610621�0607500�00000000256�13172163317�022125� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This source code refers to The Go Authors for copyright purposes. # The master list of authors is in the main Go distribution, # visible at https://tip.golang.org/AUTHORS. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/�����������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163433�016741� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/���������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163434�020231� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/tomb_test.go���������������������������������������������������0000644�0610621�0607500�00000007535�13172163434�022572� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package tomb_test import ( "errors" "gopkg.in/tomb.v2" "reflect" "testing" ) func nothing() error { return nil } func TestNewTomb(t *testing.T) { tb := &tomb.Tomb{} checkState(t, tb, false, false, tomb.ErrStillAlive) } func TestGo(t *testing.T) { tb := &tomb.Tomb{} alive := make(chan bool) tb.Go(func() error { alive <- true tb.Go(func() error { alive <- true <-tb.Dying() return nil }) <-tb.Dying() return nil }) <-alive <-alive checkState(t, tb, false, false, tomb.ErrStillAlive) tb.Kill(nil) tb.Wait() checkState(t, tb, true, true, nil) } func TestGoErr(t *testing.T) { first := errors.New("first error") second := errors.New("first error") tb := &tomb.Tomb{} alive := make(chan bool) tb.Go(func() error { alive <- true tb.Go(func() error { alive <- true return first }) <-tb.Dying() return second }) <-alive <-alive tb.Wait() checkState(t, tb, true, true, first) } func TestGoPanic(t *testing.T) { // ErrDying being used properly, after a clean death. tb := &tomb.Tomb{} tb.Go(nothing) tb.Wait() defer func() { err := recover() if err != "tomb.Go called after all goroutines terminated" { t.Fatalf("Wrong panic on post-death tomb.Go call: %v", err) } checkState(t, tb, true, true, nil) }() tb.Go(nothing) } func TestKill(t *testing.T) { // a nil reason flags the goroutine as dying tb := &tomb.Tomb{} tb.Kill(nil) checkState(t, tb, true, false, nil) // a non-nil reason now will override Kill err := errors.New("some error") tb.Kill(err) checkState(t, tb, true, false, err) // another non-nil reason won't replace the first one tb.Kill(errors.New("ignore me")) checkState(t, tb, true, false, err) tb.Go(nothing) tb.Wait() checkState(t, tb, true, true, err) } func TestKillf(t *testing.T) { tb := &tomb.Tomb{} err := tb.Killf("BO%s", "OM") if s := err.Error(); s != "BOOM" { t.Fatalf(`Killf("BO%s", "OM"): want "BOOM", got %q`, s) } checkState(t, tb, true, false, err) // another non-nil reason won't replace the first one tb.Killf("ignore me") checkState(t, tb, true, false, err) tb.Go(nothing) tb.Wait() checkState(t, tb, true, true, err) } func TestErrDying(t *testing.T) { // ErrDying being used properly, after a clean death. tb := &tomb.Tomb{} tb.Kill(nil) tb.Kill(tomb.ErrDying) checkState(t, tb, true, false, nil) // ErrDying being used properly, after an errorful death. err := errors.New("some error") tb.Kill(err) tb.Kill(tomb.ErrDying) checkState(t, tb, true, false, err) // ErrDying being used badly, with an alive tomb. tb = &tomb.Tomb{} defer func() { err := recover() if err != "tomb: Kill with ErrDying while still alive" { t.Fatalf("Wrong panic on Kill(ErrDying): %v", err) } checkState(t, tb, false, false, tomb.ErrStillAlive) }() tb.Kill(tomb.ErrDying) } func TestKillErrStillAlivePanic(t *testing.T) { tb := &tomb.Tomb{} defer func() { err := recover() if err != "tomb: Kill with ErrStillAlive" { t.Fatalf("Wrong panic on Kill(ErrStillAlive): %v", err) } checkState(t, tb, false, false, tomb.ErrStillAlive) }() tb.Kill(tomb.ErrStillAlive) } func checkState(t *testing.T, tb *tomb.Tomb, wantDying, wantDead bool, wantErr error) { select { case <-tb.Dying(): if !wantDying { t.Error("<-Dying: should block") } default: if wantDying { t.Error("<-Dying: should not block") } } seemsDead := false select { case <-tb.Dead(): if !wantDead { t.Error("<-Dead: should block") } seemsDead = true default: if wantDead { t.Error("<-Dead: should not block") } } if err := tb.Err(); err != wantErr { t.Errorf("Err: want %#v, got %#v", wantErr, err) } if wantDead && seemsDead { waitErr := tb.Wait() switch { case waitErr == tomb.ErrStillAlive: t.Errorf("Wait should not return ErrStillAlive") case !reflect.DeepEqual(waitErr, wantErr): t.Errorf("Wait: want %#v, got %#v", wantErr, waitErr) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/tomb.go��������������������������������������������������������0000644�0610621�0607500�00000016062�13172163434�021526� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2011 - Gustavo Niemeyer <gustavo@niemeyer.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The tomb package handles clean goroutine tracking and termination. // // The zero value of a Tomb is ready to handle the creation of a tracked // goroutine via its Go method, and then any tracked goroutine may call // the Go method again to create additional tracked goroutines at // any point. // // If any of the tracked goroutines returns a non-nil error, or the // Kill or Killf method is called by any goroutine in the system (tracked // or not), the tomb Err is set, Alive is set to false, and the Dying // channel is closed to flag that all tracked goroutines are supposed // to willingly terminate as soon as possible. // // Once all tracked goroutines terminate, the Dead channel is closed, // and Wait unblocks and returns the first non-nil error presented // to the tomb via a result or an explicit Kill or Killf method call, // or nil if there were no errors. // // It is okay to create further goroutines via the Go method while // the tomb is in a dying state. The final dead state is only reached // once all tracked goroutines terminate, at which point calling // the Go method again will cause a runtime panic. // // Tracked functions and methods that are still running while the tomb // is in dying state may choose to return ErrDying as their error value. // This preserves the well established non-nil error convention, but is // understood by the tomb as a clean termination. The Err and Wait // methods will still return nil if all observed errors were either // nil or ErrDying. // // For background and a detailed example, see the following blog post: // // http://blog.labix.org/2011/10/09/death-of-goroutines-under-control // package tomb import ( "errors" "fmt" "sync" ) // A Tomb tracks the lifecycle of one or more goroutines as alive, // dying or dead, and the reason for their death. // // See the package documentation for details. type Tomb struct { m sync.Mutex alive int dying chan struct{} dead chan struct{} reason error // context.Context is available in Go 1.7+. parent interface{} child map[interface{}]childContext } type childContext struct { context interface{} cancel func() done <-chan struct{} } var ( ErrStillAlive = errors.New("tomb: still alive") ErrDying = errors.New("tomb: dying") ) func (t *Tomb) init() { t.m.Lock() if t.dead == nil { t.dead = make(chan struct{}) t.dying = make(chan struct{}) t.reason = ErrStillAlive } t.m.Unlock() } // Dead returns the channel that can be used to wait until // all goroutines have finished running. func (t *Tomb) Dead() <-chan struct{} { t.init() return t.dead } // Dying returns the channel that can be used to wait until // t.Kill is called. func (t *Tomb) Dying() <-chan struct{} { t.init() return t.dying } // Wait blocks until all goroutines have finished running, and // then returns the reason for their death. func (t *Tomb) Wait() error { t.init() <-t.dead t.m.Lock() reason := t.reason t.m.Unlock() return reason } // Go runs f in a new goroutine and tracks its termination. // // If f returns a non-nil error, t.Kill is called with that // error as the death reason parameter. // // It is f's responsibility to monitor the tomb and return // appropriately once it is in a dying state. // // It is safe for the f function to call the Go method again // to create additional tracked goroutines. Once all tracked // goroutines return, the Dead channel is closed and the // Wait method unblocks and returns the death reason. // // Calling the Go method after all tracked goroutines return // causes a runtime panic. For that reason, calling the Go // method a second time out of a tracked goroutine is unsafe. func (t *Tomb) Go(f func() error) { t.init() t.m.Lock() defer t.m.Unlock() select { case <-t.dead: panic("tomb.Go called after all goroutines terminated") default: } t.alive++ go t.run(f) } func (t *Tomb) run(f func() error) { err := f() t.m.Lock() defer t.m.Unlock() t.alive-- if t.alive == 0 || err != nil { t.kill(err) if t.alive == 0 { close(t.dead) } } } // Kill puts the tomb in a dying state for the given reason, // closes the Dying channel, and sets Alive to false. // // Althoguh Kill may be called multiple times, only the first // non-nil error is recorded as the death reason. // // If reason is ErrDying, the previous reason isn't replaced // even if nil. It's a runtime error to call Kill with ErrDying // if t is not in a dying state. func (t *Tomb) Kill(reason error) { t.init() t.m.Lock() defer t.m.Unlock() t.kill(reason) } func (t *Tomb) kill(reason error) { if reason == ErrStillAlive { panic("tomb: Kill with ErrStillAlive") } if reason == ErrDying { if t.reason == ErrStillAlive { panic("tomb: Kill with ErrDying while still alive") } return } if t.reason == ErrStillAlive { t.reason = reason close(t.dying) for _, child := range t.child { child.cancel() } t.child = nil return } if t.reason == nil { t.reason = reason return } } // Killf calls the Kill method with an error built providing the received // parameters to fmt.Errorf. The generated error is also returned. func (t *Tomb) Killf(f string, a ...interface{}) error { err := fmt.Errorf(f, a...) t.Kill(err) return err } // Err returns the death reason, or ErrStillAlive if the tomb // is not in a dying or dead state. func (t *Tomb) Err() (reason error) { t.init() t.m.Lock() reason = t.reason t.m.Unlock() return } // Alive returns true if the tomb is not in a dying or dead state. func (t *Tomb) Alive() bool { return t.Err() == ErrStillAlive } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/context_test.go������������������������������������������������0000644�0610621�0607500�00000007644�13172163434�023316� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.7 package tomb_test import ( "context" "testing" "time" "gopkg.in/tomb.v2" ) func TestWithContext(t *testing.T) { parent1, cancel1 := context.WithCancel(context.Background()) tb, child1 := tomb.WithContext(parent1) if !tb.Alive() { t.Fatalf("WithContext returned dead tomb") } if tb.Context(parent1) != child1 { t.Fatalf("Context returned different context for same parent") } if tb.Context(nil) != child1 { t.Fatalf("Context returned different context for nil parent") } select { case <-child1.Done(): t.Fatalf("Tomb's child context was born dead") default: } parent2, cancel2 := context.WithCancel(context.WithValue(context.Background(), "parent", "parent2")) child2 := tb.Context(parent2) if tb.Context(parent2) != child2 { t.Fatalf("Context returned different context for same parent") } if child2.Value("parent") != "parent2" { t.Fatalf("Child context didn't inherit its parent's properties") } select { case <-child2.Done(): t.Fatalf("Tomb's child context was born dead") default: } cancel2() select { case <-child2.Done(): default: t.Fatalf("Tomb's child context didn't die after parent was canceled") } if !tb.Alive() { t.Fatalf("Canceling unrelated parent context killed tomb") } parent3 := context.WithValue(context.Background(), "parent", "parent3") child3 := tb.Context(parent3) if child3.Value("parent") != "parent3" { t.Fatalf("Child context didn't inherit its parent's properties") } select { case <-child3.Done(): t.Fatalf("Tomb's child context was born dead") default: } cancel1() select { case <-tb.Dying(): case <-time.After(5 * time.Second): t.Fatalf("Canceling parent context did not kill tomb") } if tb.Err() != context.Canceled { t.Fatalf("tomb should be %v, got %v", context.Canceled, tb.Err()) } if tb.Context(parent1) == child1 || tb.Context(parent3) == child3 { t.Fatalf("Tomb is dead and shouldn't be tracking children anymore") } select { case <-child3.Done(): default: t.Fatalf("Child context didn't die after tomb's death") } parent4 := context.WithValue(context.Background(), "parent", "parent4") child4 := tb.Context(parent4) select { case <-child4.Done(): default: t.Fatalf("Child context should be born canceled") } childnil := tb.Context(nil) select { case <-childnil.Done(): default: t.Fatalf("Child context should be born canceled") } } func TestContextNoParent(t *testing.T) { var tb tomb.Tomb parent2, cancel2 := context.WithCancel(context.WithValue(context.Background(), "parent", "parent2")) child2 := tb.Context(parent2) if tb.Context(parent2) != child2 { t.Fatalf("Context returned different context for same parent") } if child2.Value("parent") != "parent2" { t.Fatalf("Child context didn't inherit its parent's properties") } select { case <-child2.Done(): t.Fatalf("Tomb's child context was born dead") default: } cancel2() select { case <-child2.Done(): default: t.Fatalf("Tomb's child context didn't die after parent was canceled") } if !tb.Alive() { t.Fatalf("Canceling unrelated parent context killed tomb") } parent3 := context.WithValue(context.Background(), "parent", "parent3") child3 := tb.Context(parent3) if child3.Value("parent") != "parent3" { t.Fatalf("Child context didn't inherit its parent's properties") } select { case <-child3.Done(): t.Fatalf("Tomb's child context was born dead") default: } tb.Kill(nil) if tb.Context(parent3) == child3 { t.Fatalf("Tomb is dead and shouldn't be tracking children anymore") } select { case <-child3.Done(): default: t.Fatalf("Child context didn't die after tomb's death") } parent4 := context.WithValue(context.Background(), "parent", "parent4") child4 := tb.Context(parent4) select { case <-child4.Done(): default: t.Fatalf("Child context should be born canceled") } childnil := tb.Context(nil) select { case <-childnil.Done(): default: t.Fatalf("Child context should be born canceled") } } ��������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/context16_test.go����������������������������������������������0000644�0610621�0607500�00000010010�13172163434�023442� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.7 package tomb_test import ( "testing" "time" "golang.org/x/net/context" "gopkg.in/tomb.v2" ) func TestWithContext(t *testing.T) { parent1, cancel1 := context.WithCancel(context.Background()) tb, child1 := tomb.WithContext(parent1) if !tb.Alive() { t.Fatalf("WithContext returned dead tomb") } if tb.Context(parent1) != child1 { t.Fatalf("Context returned different context for same parent") } if tb.Context(nil) != child1 { t.Fatalf("Context returned different context for nil parent") } select { case <-child1.Done(): t.Fatalf("Tomb's child context was born dead") default: } parent2, cancel2 := context.WithCancel(context.WithValue(context.Background(), "parent", "parent2")) child2 := tb.Context(parent2) if tb.Context(parent2) != child2 { t.Fatalf("Context returned different context for same parent") } if child2.Value("parent") != "parent2" { t.Fatalf("Child context didn't inherit its parent's properties") } select { case <-child2.Done(): t.Fatalf("Tomb's child context was born dead") default: } cancel2() select { case <-child2.Done(): case <-time.After(5 * time.Second): t.Fatalf("Tomb's child context didn't die after parent was canceled") } if !tb.Alive() { t.Fatalf("Canceling unrelated parent context killed tomb") } parent3 := context.WithValue(context.Background(), "parent", "parent3") child3 := tb.Context(parent3) if child3.Value("parent") != "parent3" { t.Fatalf("Child context didn't inherit its parent's properties") } select { case <-child3.Done(): t.Fatalf("Tomb's child context was born dead") default: } cancel1() select { case <-tb.Dying(): case <-time.After(5 * time.Second): t.Fatalf("Canceling parent context did not kill tomb") } if tb.Err() != context.Canceled { t.Fatalf("tomb should be %v, got %v", context.Canceled, tb.Err()) } if tb.Context(parent1) == child1 || tb.Context(parent3) == child3 { t.Fatalf("Tomb is dead and shouldn't be tracking children anymore") } select { case <-child3.Done(): case <-time.After(5 * time.Second): t.Fatalf("Child context didn't die after tomb's death") } parent4 := context.WithValue(context.Background(), "parent", "parent4") child4 := tb.Context(parent4) select { case <-child4.Done(): case <-time.After(5 * time.Second): t.Fatalf("Child context should be born canceled") } childnil := tb.Context(nil) select { case <-childnil.Done(): default: t.Fatalf("Child context should be born canceled") } } func TestContextNoParent(t *testing.T) { var tb tomb.Tomb parent2, cancel2 := context.WithCancel(context.WithValue(context.Background(), "parent", "parent2")) child2 := tb.Context(parent2) if tb.Context(parent2) != child2 { t.Fatalf("Context returned different context for same parent") } if child2.Value("parent") != "parent2" { t.Fatalf("Child context didn't inherit its parent's properties") } select { case <-child2.Done(): t.Fatalf("Tomb's child context was born dead") default: } cancel2() select { case <-child2.Done(): default: t.Fatalf("Tomb's child context didn't die after parent was canceled") } if !tb.Alive() { t.Fatalf("Canceling unrelated parent context killed tomb") } parent3 := context.WithValue(context.Background(), "parent", "parent3") child3 := tb.Context(parent3) if child3.Value("parent") != "parent3" { t.Fatalf("Child context didn't inherit its parent's properties") } select { case <-child3.Done(): t.Fatalf("Tomb's child context was born dead") default: } tb.Kill(nil) if tb.Context(parent3) == child3 { t.Fatalf("Tomb is dead and shouldn't be tracking children anymore") } select { case <-child3.Done(): default: t.Fatalf("Child context didn't die after tomb's death") } parent4 := context.WithValue(context.Background(), "parent", "parent4") child4 := tb.Context(parent4) select { case <-child4.Done(): default: t.Fatalf("Child context should be born canceled") } childnil := tb.Context(nil) select { case <-childnil.Done(): default: t.Fatalf("Child context should be born canceled") } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/context16.go���������������������������������������������������0000644�0610621�0607500�00000003504�13172163434�022415� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.7 package tomb import ( "golang.org/x/net/context" ) // WithContext returns a new tomb that is killed when the provided parent // context is canceled, and a copy of parent with a replaced Done channel // that is closed when either the tomb is dying or the parent is canceled. // The returned context may also be obtained via the tomb's Context method. func WithContext(parent context.Context) (*Tomb, context.Context) { var t Tomb t.init() if parent.Done() != nil { go func() { select { case <-t.Dying(): case <-parent.Done(): t.Kill(parent.Err()) } }() } t.parent = parent child, cancel := context.WithCancel(parent) t.addChild(parent, child, cancel) return &t, child } // Context returns a context that is a copy of the provided parent context with // a replaced Done channel that is closed when either the tomb is dying or the // parent is cancelled. // // If parent is nil, it defaults to the parent provided via WithContext, or an // empty background parent if the tomb wasn't created via WithContext. func (t *Tomb) Context(parent context.Context) context.Context { t.init() t.m.Lock() defer t.m.Unlock() if parent == nil { if t.parent == nil { t.parent = context.Background() } parent = t.parent.(context.Context) } if child, ok := t.child[parent]; ok { return child.context.(context.Context) } child, cancel := context.WithCancel(parent) t.addChild(parent, child, cancel) return child } func (t *Tomb) addChild(parent context.Context, child context.Context, cancel func()) { if t.reason != ErrStillAlive { cancel() return } if t.child == nil { t.child = make(map[interface{}]childContext) } t.child[parent] = childContext{child, cancel, child.Done()} for parent, child := range t.child { select { case <-child.done: delete(t.child, parent) default: } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/context.go�����������������������������������������������������0000644�0610621�0607500�00000003462�13172163434�022251� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.7 package tomb import ( "context" ) // WithContext returns a new tomb that is killed when the provided parent // context is canceled, and a copy of parent with a replaced Done channel // that is closed when either the tomb is dying or the parent is canceled. // The returned context may also be obtained via the tomb's Context method. func WithContext(parent context.Context) (*Tomb, context.Context) { var t Tomb t.init() if parent.Done() != nil { go func() { select { case <-t.Dying(): case <-parent.Done(): t.Kill(parent.Err()) } }() } t.parent = parent child, cancel := context.WithCancel(parent) t.addChild(parent, child, cancel) return &t, child } // Context returns a context that is a copy of the provided parent context with // a replaced Done channel that is closed when either the tomb is dying or the // parent is cancelled. // // If parent is nil, it defaults to the parent provided via WithContext, or an // empty background parent if the tomb wasn't created via WithContext. func (t *Tomb) Context(parent context.Context) context.Context { t.init() t.m.Lock() defer t.m.Unlock() if parent == nil { if t.parent == nil { t.parent = context.Background() } parent = t.parent.(context.Context) } if child, ok := t.child[parent]; ok { return child.context.(context.Context) } child, cancel := context.WithCancel(parent) t.addChild(parent, child, cancel) return child } func (t *Tomb) addChild(parent context.Context, child context.Context, cancel func()) { if t.reason != ErrStillAlive { cancel() return } if t.child == nil { t.child = make(map[interface{}]childContext) } t.child[parent] = childContext{child, cancel, child.Done()} for parent, child := range t.child { select { case <-child.done: delete(t.child, parent) default: } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/README.md������������������������������������������������������0000644�0610621�0607500�00000000205�13172163434�021505� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Installation and usage ---------------------- See [gopkg.in/tomb.v2](https://gopkg.in/tomb.v2) for documentation and usage details. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/tomb.v2/LICENSE��������������������������������������������������������0000644�0610621�0607500�00000003110�13172163434�021231� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������tomb - support for clean goroutine termination in Go. Copyright (c) 2010-2011 - Gustavo Niemeyer <gustavo@niemeyer.net> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/�������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163432�017526� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/���������������������������������������������������������0000755�0610621�0607500�00000000000�13172163433�021246� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/util.go��������������������������������������������������0000644�0610621�0607500�00000004173�13172163433�022557� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc /* #include <stdlib.h> #include <lxc/lxccontainer.h> static char** makeCharArray(size_t size) { // caller checks return value return calloc(sizeof(char*), size); } static void setArrayString(char **array, char *string, size_t n) { array[n] = string; } static void freeCharArray(char **array, size_t size) { size_t i; for (i = 0; i < size; i++) { free(array[i]); } free(array); } static void freeSnapshotArray(struct lxc_snapshot *s, size_t size) { size_t i; for (i = 0; i < size; i++) { s[i].free(&s[i]); } free(s); } static size_t getArrayLength(char **array) { char **p; size_t size = 0; for (p = (char **)array; *p; p++) { size++; } return size; } */ import "C" import ( "reflect" "unsafe" ) func makeNullTerminatedArgs(args []string) **C.char { cparams := C.makeCharArray(C.size_t(len(args) + 1)) if cparams == nil { return nil } for i := 0; i < len(args); i++ { C.setArrayString(cparams, C.CString(args[i]), C.size_t(i)) } C.setArrayString(cparams, nil, C.size_t(len(args))) return cparams } func freeNullTerminatedArgs(cArgs **C.char, length int) { C.freeCharArray(cArgs, C.size_t(length+1)) } func convertArgs(cArgs **C.char) []string { if cArgs == nil { return nil } return convertNArgs(cArgs, int(C.getArrayLength(cArgs))) } func convertNArgs(cArgs **C.char, size int) []string { if cArgs == nil || size <= 0 { return nil } var A []*C.char hdr := reflect.SliceHeader{ Data: uintptr(unsafe.Pointer(cArgs)), Len: size, Cap: size, } cArgsInterface := reflect.NewAt(reflect.TypeOf(A), unsafe.Pointer(&hdr)).Elem().Interface() result := make([]string, size) for i := 0; i < size; i++ { result[i] = C.GoString(cArgsInterface.([]*C.char)[i]) } C.freeCharArray(cArgs, C.size_t(size)) return result } func freeSnapshots(snapshots *C.struct_lxc_snapshot, size int) { C.freeSnapshotArray(snapshots, C.size_t(size)) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/type.go��������������������������������������������������0000644�0610621�0607500�00000011166�13172163433�022563� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc // #include <lxc/lxccontainer.h> import "C" import "fmt" // Verbosity type type Verbosity int const ( // Quiet makes some API calls not to write anything to stdout Quiet Verbosity = 1 << iota // Verbose makes some API calls write to stdout Verbose ) // BackendStore type specifies possible backend types. type BackendStore int const ( // Btrfs backendstore type Btrfs BackendStore = iota + 1 // Directory backendstore type Directory // LVM backendstore type LVM // ZFS backendstore type ZFS // Aufs backendstore type Aufs // Overlayfs backendstore type Overlayfs // Loopback backendstore type Loopback // Best backendstore type Best ) // BackendStore as string func (t BackendStore) String() string { switch t { case Directory: return "dir" case ZFS: return "zfs" case Btrfs: return "btrfs" case LVM: return "lvm" case Aufs: return "aufs" case Overlayfs: return "overlayfs" case Loopback: return "loopback" case Best: return "best" } return "" } var backendStoreMap = map[string]BackendStore{ "dir": Directory, "zfs": ZFS, "btrfs": Btrfs, "lvm": LVM, "aufs": Aufs, "overlayfs": Overlayfs, "loopback": Loopback, "best": Best, } // Set is the method to set the flag value, part of the flag.Value interface. func (t *BackendStore) Set(value string) error { backend, ok := backendStoreMap[value] if ok { *t = backend return nil } return ErrUnknownBackendStore } // State type specifies possible container states. type State int const ( // STOPPED means container is not running STOPPED State = iota + 1 // STARTING means container is starting STARTING // RUNNING means container is running RUNNING // STOPPING means container is stopping STOPPING // ABORTING means container is aborting ABORTING // FREEZING means container is freezing FREEZING // FROZEN means containe is frozen FROZEN // THAWED means container is thawed THAWED ) // StateMap provides the mapping betweens the state names and states var StateMap = map[string]State{ "STOPPED": STOPPED, "STARTING": STARTING, "RUNNING": RUNNING, "STOPPING": STOPPING, "ABORTING": ABORTING, "FREEZING": FREEZING, "FROZEN": FROZEN, "THAWED": THAWED, } // State as string func (t State) String() string { switch t { case STOPPED: return "STOPPED" case STARTING: return "STARTING" case RUNNING: return "RUNNING" case STOPPING: return "STOPPING" case ABORTING: return "ABORTING" case FREEZING: return "FREEZING" case FROZEN: return "FROZEN" case THAWED: return "THAWED" } return "" } // Taken from http://golang.org/doc/effective_go.html#constants // ByteSize type type ByteSize float64 const ( _ = iota // KB - kilobyte KB ByteSize = 1 << (10 * iota) // MB - megabyte MB // GB - gigabyte GB // TB - terabyte TB // PB - petabyte PB // EB - exabyte EB // ZB - zettabyte ZB // YB - yottabyte YB ) func (b ByteSize) String() string { switch { case b >= YB: return fmt.Sprintf("%.2fYB", b/YB) case b >= ZB: return fmt.Sprintf("%.2fZB", b/ZB) case b >= EB: return fmt.Sprintf("%.2fEB", b/EB) case b >= PB: return fmt.Sprintf("%.2fPB", b/PB) case b >= TB: return fmt.Sprintf("%.2fTB", b/TB) case b >= GB: return fmt.Sprintf("%.2fGB", b/GB) case b >= MB: return fmt.Sprintf("%.2fMB", b/MB) case b >= KB: return fmt.Sprintf("%.2fKB", b/KB) } return fmt.Sprintf("%.2fB", b) } // LogLevel type specifies possible log levels. type LogLevel int const ( // TRACE priority TRACE LogLevel = iota // DEBUG priority DEBUG // INFO priority INFO // NOTICE priority NOTICE // WARN priority WARN // ERROR priority ERROR // CRIT priority CRIT // ALERT priority ALERT // FATAL priority FATAL ) var logLevelMap = map[string]LogLevel{ "TRACE": TRACE, "DEBUG": DEBUG, "INFO": INFO, "NOTICE": NOTICE, "WARN": WARN, "ERROR": ERROR, "CRIT": CRIT, "ALERT": ALERT, "FATAL": FATAL, } func (l LogLevel) String() string { switch l { case TRACE: return "TRACE" case DEBUG: return "DEBUG" case INFO: return "INFO" case NOTICE: return "NOTICE" case WARN: return "WARN" case ERROR: return "ERROR" case CRIT: return "CRIT" case ALERT: return "ALERT" case FATAL: return "FATAL" } return "NOTSET" } // Personality allows to set the architecture for the container. type Personality int64 const ( X86 Personality = 0x0008 X86_64 = 0x0000 ) const ( MIGRATE_PRE_DUMP = 0 MIGRATE_DUMP = 1 MIGRATE_RESTORE = 2 ) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/options.go�����������������������������������������������0000644�0610621�0607500�00000011726�13172163433�023277� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc import ( "os" ) // AttachOptions type is used for defining various attach options. type AttachOptions struct { // Specify the namespaces to attach to, as OR'ed list of clone flags (syscall.CLONE_NEWNS | syscall.CLONE_NEWUTS ...). Namespaces int // Specify the architecture which the kernel should appear to be running as to the command executed. Arch Personality // Cwd specifies the working directory of the command. Cwd string // UID specifies the user id to run as. UID int // GID specifies the group id to run as. GID int // If ClearEnv is true the environment is cleared before running the command. ClearEnv bool // Env specifies the environment of the process. Env []string // EnvToKeep specifies the environment of the process when ClearEnv is true. EnvToKeep []string // StdinFd specifies the fd to read input from. StdinFd uintptr // StdoutFd specifies the fd to write output to. StdoutFd uintptr // StderrFd specifies the fd to write error output to. StderrFd uintptr } // DefaultAttachOptions is a convenient set of options to be used. var DefaultAttachOptions = AttachOptions{ Namespaces: -1, Arch: -1, Cwd: "/", UID: -1, GID: -1, ClearEnv: false, Env: nil, EnvToKeep: nil, StdinFd: os.Stdin.Fd(), StdoutFd: os.Stdout.Fd(), StderrFd: os.Stderr.Fd(), } // TemplateOptions type is used for defining various template options. type TemplateOptions struct { // Template specifies the name of the template. Template string // Backend specifies the type of the backend. Backend BackendStore // Distro specifies the name of the distribution. Distro string // Release specifies the name/version of the distribution. Release string // Arch specified the architecture of the container. Arch string // Variant specifies the variant of the image (default: "default"). Variant string // Image server (default: "images.linuxcontainers.org"). Server string // GPG keyid (default: 0x...). KeyID string // GPG keyserver to use. KeyServer string // Disable GPG validation (not recommended). DisableGPGValidation bool // Flush the local copy (if present). FlushCache bool // Force the use of the local copy even if expired. ForceCache bool // ExtraArgs provides a way to specify template specific args. ExtraArgs []string } // DownloadTemplateOptions is a convenient set of options for "download" template. var DownloadTemplateOptions = TemplateOptions{ Template: "download", Distro: "ubuntu", Release: "trusty", Arch: "amd64", } // BusyboxTemplateOptions is a convenient set of options for "busybox" template. var BusyboxTemplateOptions = TemplateOptions{ Template: "busybox", } // UbuntuTemplateOptions is a convenient set of options for "ubuntu" template. var UbuntuTemplateOptions = TemplateOptions{ Template: "ubuntu", } // ConsoleOptions type is used for defining various console options. type ConsoleOptions struct { // Tty number to attempt to allocate, -1 to allocate the first available tty, or 0 to allocate the console. Tty int // StdinFd specifies the fd to read input from. StdinFd uintptr // StdoutFd specifies the fd to write output to. StdoutFd uintptr // StderrFd specifies the fd to write error output to. StderrFd uintptr // EscapeCharacter (a means <Ctrl a>, b maens <Ctrl b>). EscapeCharacter rune } // DefaultConsoleOptions is a convenient set of options to be used. var DefaultConsoleOptions = ConsoleOptions{ Tty: -1, StdinFd: os.Stdin.Fd(), StdoutFd: os.Stdout.Fd(), StderrFd: os.Stderr.Fd(), EscapeCharacter: 'a', } // CloneOptions type is used for defining various clone options. type CloneOptions struct { // Backend specifies the type of the backend. Backend BackendStore // lxcpath in which to create the new container. If not set the original container's lxcpath will be used. ConfigPath string // Do not change the hostname of the container (in the root filesystem). KeepName bool // Use the same MAC address as the original container, rather than generating a new random one. KeepMAC bool // Create a snapshot rather than copy. Snapshot bool } // DefaultCloneOptions is a convenient set of options to be used. var DefaultCloneOptions = CloneOptions{ Backend: Directory, } // CheckpointOptions type is used for defining checkpoint options for CRIU. type CheckpointOptions struct { Directory string Stop bool Verbose bool } // RestoreOptions type is used for defining restore options for CRIU. type RestoreOptions struct { Directory string Verbose bool } // MigrateOptions type is used for defining migrate options. type MigrateOptions struct { Directory string PredumpDir string ActionScript string Verbose bool Stop bool PreservesInodes bool GhostLimit uint64 } ������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/lxc_test.go����������������������������������������������0000644�0610621�0607500�00000067305�13172163433�023435� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc import ( "fmt" "math/rand" "os" "runtime" "strconv" "strings" "sync" "syscall" "testing" "time" ) const ( ContainerName = "lorem" SnapshotName = "snap0" ContainerRestoreName = "ipsum" ContainerCloneName = "consectetur" ContainerCloneOverlayName = "adipiscing" ContainerCloneAufsName = "pellentesque" ) func PathExists(name string) bool { _, err := os.Lstat(name) if err != nil && os.IsNotExist(err) { return false } return true } func unprivileged() bool { return os.Geteuid() != 0 } func supported(moduleName string) bool { if _, err := os.Stat("/sys/module/" + moduleName); err != nil { return false } return true } func TestVersion(t *testing.T) { t.Logf("LXC version: %s", Version()) } func TestDefaultConfigPath(t *testing.T) { if DefaultConfigPath() == "" { t.Errorf("DefaultConfigPath failed...") } } func TestSetConfigPath(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } currentPath := c.ConfigPath() if err := c.SetConfigPath("/tmp"); err != nil { t.Errorf(err.Error()) } newPath := c.ConfigPath() if currentPath == newPath { t.Errorf("SetConfigPath failed...") } } func TestAcquire(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } Acquire(c) Release(c) } func TestConcurrentDefined_Negative(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) var wg sync.WaitGroup for i := 0; i <= 100; i++ { wg.Add(1) go func() { c, err := NewContainer(strconv.Itoa(rand.Intn(10))) if err != nil { t.Errorf(err.Error()) } // sleep for a while to simulate some dummy work time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) if c.Defined() { t.Errorf("Defined_Negative failed...") } wg.Done() }() } wg.Wait() } func TestDefined_Negative(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.Defined() { t.Errorf("Defined_Negative failed...") } } func TestExecute(t *testing.T) { if unprivileged() { t.Skip("skipping test in unprivileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.Execute("/bin/true"); err != nil { t.Errorf(err.Error()) } } func TestSetVerbosity(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } c.SetVerbosity(Quiet) } func TestCreate(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Create(BusyboxTemplateOptions); err != nil { t.Errorf(err.Error()) } } func TestClone(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err = c.Clone(ContainerCloneName, DefaultCloneOptions); err != nil { t.Errorf(err.Error()) } } func TestCloneUsingOverlayfs(t *testing.T) { if !supported("overlayfs") { t.Skip("skipping test as overlayfs support is missing.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } err = c.Clone(ContainerCloneOverlayName, CloneOptions{ Backend: Overlayfs, KeepName: true, KeepMAC: true, Snapshot: true, }) if err != nil { t.Errorf(err.Error()) } } func TestCloneUsingAufs(t *testing.T) { if unprivileged() { t.Skip("skipping test in unprivileged mode.") } if !supported("aufs") { t.Skip("skipping test as aufs support is missing.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } err = c.Clone(ContainerCloneAufsName, CloneOptions{ Backend: Aufs, KeepName: true, KeepMAC: true, Snapshot: true, }) if err != nil { t.Errorf(err.Error()) } } func TestCreateSnapshot(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.CreateSnapshot(); err != nil { t.Errorf(err.Error()) } } func TestCreateSnapshots(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } for i := 0; i < 3; i++ { if _, err := c.CreateSnapshot(); err != nil { t.Errorf(err.Error()) } } } func TestRestoreSnapshot(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } snapshot := Snapshot{Name: SnapshotName} if err := c.RestoreSnapshot(snapshot, ContainerRestoreName); err != nil { t.Errorf(err.Error()) } } func TestConcurrentCreate(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup options := BusyboxTemplateOptions for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { c, err := NewContainer(strconv.Itoa(i)) if err != nil { t.Errorf(err.Error()) } // sleep for a while to simulate some dummy work time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) if err := c.Create(options); err != nil { t.Errorf(err.Error()) } wg.Done() }(i) } wg.Wait() } func TestSnapshots(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.Snapshots(); err != nil { t.Errorf(err.Error()) } } func TestConcurrentStart(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { c, err := NewContainer(strconv.Itoa(i)) if err != nil { t.Errorf(err.Error()) } if err := c.Start(); err != nil { t.Errorf(err.Error()) } c.Wait(RUNNING, 30*time.Second) if !c.Running() { t.Errorf("Starting the container failed...") } wg.Done() }(i) } wg.Wait() } func TestConfigFileName(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.ConfigFileName() == "" { t.Errorf("ConfigFileName failed...") } } func TestDefined_Positive(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if !c.Defined() { t.Errorf("Defined_Positive failed...") } } func TestConcurrentDefined_Positive(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup for i := 0; i <= 100; i++ { wg.Add(1) go func() { c, err := NewContainer(strconv.Itoa(rand.Intn(10))) if err != nil { t.Errorf(err.Error()) } // sleep for a while to simulate some dummy work time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) if !c.Defined() { t.Errorf("Defined_Positive failed...") } wg.Done() }() } wg.Wait() } func TestInitPid_Negative(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.InitPid() != -1 { t.Errorf("InitPid failed...") } } func TestStart(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Start(); err != nil { t.Errorf(err.Error()) } c.Wait(RUNNING, 30*time.Second) if !c.Running() { t.Errorf("Starting the container failed...") } } func TestWaitIPAddresses(t *testing.T) { if !unprivileged() { t.Skip("skipping test in privileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.WaitIPAddresses(30 * time.Second); err != nil { t.Errorf(err.Error()) } } func TestControllable(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if !c.Controllable() { t.Errorf("Controling the container failed...") } } func TestContainerNames(t *testing.T) { if ContainerNames() == nil { t.Errorf("ContainerNames failed...") } } func TestDefinedContainerNames(t *testing.T) { if DefinedContainerNames() == nil { t.Errorf("DefinedContainerNames failed...") } } func TestActiveContainerNames(t *testing.T) { if ActiveContainerNames() == nil { t.Errorf("ActiveContainerNames failed...") } } func TestContainers(t *testing.T) { if Containers() == nil { t.Errorf("Containers failed...") } } func TestDefinedContainers(t *testing.T) { if DefinedContainers() == nil { t.Errorf("DefinedContainers failed...") } } func TestActiveContainers(t *testing.T) { if ActiveContainers() == nil { t.Errorf("ActiveContainers failed...") } } func TestRunning(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if !c.Running() { t.Errorf("Checking the container failed...") } } func TestWantDaemonize(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.WantDaemonize(false); err != nil || c.Daemonize() { t.Errorf("WantDaemonize failed...") } } func TestWantCloseAllFds(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.WantCloseAllFds(true); err != nil { t.Errorf("WantCloseAllFds failed...") } } func TestSetLogLevel(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.SetLogLevel(WARN); err != nil || c.LogLevel() != WARN { t.Errorf("SetLogLevel( failed...") } } func TestSetLogFile(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.SetLogFile("/tmp/" + ContainerName); err != nil || c.LogFile() != "/tmp/"+ContainerName { t.Errorf("SetLogFile failed...") } } func TestInitPid_Positive(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.InitPid() == -1 { t.Errorf("InitPid failed...") } } func TestName(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.Name() != ContainerName { t.Errorf("Name failed...") } } func TestFreeze(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Freeze(); err != nil { t.Errorf(err.Error()) } c.Wait(FROZEN, 30*time.Second) if c.State() != FROZEN { t.Errorf("Freezing the container failed...") } } func TestUnfreeze(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Unfreeze(); err != nil { t.Errorf(err.Error()) } c.Wait(RUNNING, 30*time.Second) if !c.Running() { t.Errorf("Unfreezing the container failed...") } } func TestLoadConfigFile(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.LoadConfigFile(c.ConfigFileName()); err != nil { t.Errorf(err.Error()) } } func TestSaveConfigFile(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.SaveConfigFile(c.ConfigFileName()); err != nil { t.Errorf(err.Error()) } } func TestConfigItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.ConfigItem("lxc.utsname")[0] != ContainerName { t.Errorf("ConfigItem failed...") } } func TestSetConfigItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.SetConfigItem("lxc.utsname", ContainerName); err != nil { t.Errorf(err.Error()) } if c.ConfigItem("lxc.utsname")[0] != ContainerName { t.Errorf("ConfigItem failed...") } } func TestRunningConfigItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.RunningConfigItem("lxc.network.0.type") == nil { t.Errorf("RunningConfigItem failed...") } } func TestSetCgroupItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } maxMem := c.CgroupItem("memory.max_usage_in_bytes")[0] currentMem := c.CgroupItem("memory.limit_in_bytes")[0] if err := c.SetCgroupItem("memory.limit_in_bytes", maxMem); err != nil { t.Errorf(err.Error()) } newMem := c.CgroupItem("memory.limit_in_bytes")[0] if newMem == currentMem { t.Errorf("SetCgroupItem failed...") } } func TestClearConfigItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.ClearConfigItem("lxc.cap.drop"); err != nil { t.Errorf(err.Error()) } if c.ConfigItem("lxc.cap.drop")[0] != "" { t.Errorf("ClearConfigItem failed...") } } func TestConfigKeys(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } keys := "" if VersionAtLeast(2, 1, 0) { keys = strings.Join(c.ConfigKeys("lxc.net.0"), " ") } else { keys = strings.Join(c.ConfigKeys("lxc.network.0"), " ") } if !strings.Contains(keys, "mtu") { t.Errorf("Keys failed...") } } func TestInterfaces(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.Interfaces(); err != nil { t.Errorf(err.Error()) } } func TestMemoryUsage(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.MemoryUsage(); err != nil { t.Errorf(err.Error()) } } func TestKernelMemoryUsage(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.KernelMemoryUsage(); err != nil { t.Errorf(err.Error()) } } func TestMemorySwapUsage(t *testing.T) { if !PathExists("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") { t.Skip("skipping the test as it requires memory.memsw.limit_in_bytes to be set") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.MemorySwapUsage(); err != nil { t.Errorf(err.Error()) } } func TestBlkioUsage(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.BlkioUsage(); err != nil { t.Errorf(err.Error()) } } func TestMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.MemoryLimit(); err != nil { t.Errorf(err.Error()) } } func TestSoftMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.SoftMemoryLimit(); err != nil { t.Errorf(err.Error()) } } func TestKernelMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.KernelMemoryLimit(); err != nil { t.Errorf(err.Error()) } } func TestMemorySwapLimit(t *testing.T) { if !PathExists("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") { t.Skip("skipping the test as it requires memory.memsw.limit_in_bytes to be set") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.MemorySwapLimit(); err != nil { t.Errorf(err.Error()) } } func TestSetMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } oldMemLimit, err := c.MemoryLimit() if err != nil { t.Errorf(err.Error()) } if err := c.SetMemoryLimit(oldMemLimit * 4); err != nil { t.Errorf(err.Error()) } newMemLimit, err := c.MemoryLimit() if err != nil { t.Errorf(err.Error()) } if newMemLimit != oldMemLimit*4 { t.Errorf("SetMemoryLimit failed") } } func TestSetSoftMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } oldMemLimit, err := c.MemoryLimit() if err != nil { t.Errorf(err.Error()) } if err := c.SetSoftMemoryLimit(oldMemLimit * 4); err != nil { t.Errorf(err.Error()) } newMemLimit, err := c.SoftMemoryLimit() if err != nil { t.Errorf(err.Error()) } if newMemLimit != oldMemLimit*4 { t.Errorf("SetSoftMemoryLimit failed") } } func TestSetKernelMemoryLimit(t *testing.T) { t.Skip("skipping the test as it requires memory.kmem.limit_in_bytes to be set") c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } oldMemLimit, err := c.KernelMemoryLimit() if err != nil { t.Errorf(err.Error()) } if err := c.SetKernelMemoryLimit(oldMemLimit * 4); err != nil { t.Errorf(err.Error()) } newMemLimit, err := c.KernelMemoryLimit() if err != nil { t.Errorf(err.Error()) } // Floats aren't exactly exact, check that we did get something smaller if newMemLimit < oldMemLimit*3 { t.Errorf("SetKernelMemoryLimit failed") } } func TestSetMemorySwapLimit(t *testing.T) { if !PathExists("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") { t.Skip("skipping the test as it requires memory.memsw.limit_in_bytes to be set") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } oldMemorySwapLimit, err := c.MemorySwapLimit() if err != nil { t.Errorf(err.Error()) } if err := c.SetMemorySwapLimit(oldMemorySwapLimit / 4); err != nil { t.Errorf(err.Error()) } newMemorySwapLimit, err := c.MemorySwapLimit() if err != nil { t.Errorf(err.Error()) } // Floats aren't exactly exact, check that we did get something smaller if newMemorySwapLimit > oldMemorySwapLimit/3 { t.Errorf("SetSwapLimit failed") } } func TestCPUTime(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.CPUTime(); err != nil { t.Errorf(err.Error()) } } func TestCPUTimePerCPU(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.CPUTimePerCPU(); err != nil { t.Errorf(err.Error()) } } func TestCPUStats(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.CPUStats(); err != nil { t.Errorf(err.Error()) } } func TestRunCommandNoWait(t *testing.T) { c, err := NewContainer("TestRunCommandNoWait") if err != nil { t.Errorf(err.Error()) t.FailNow() } if err := c.Create(BusyboxTemplateOptions); err != nil { t.Errorf(err.Error()) t.FailNow() } defer c.Destroy() err = c.Start() if err != nil { t.Errorf(err.Error()) t.FailNow() } defer c.Stop() argsThree := []string{"/bin/sh", "-c", "exit 0"} pid, err := c.RunCommandNoWait(argsThree, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) t.FailNow() } proc, err := os.FindProcess(pid) if err != nil { t.Errorf(err.Error()) t.FailNow() } procState, err := proc.Wait() if err != nil { t.Errorf(err.Error()) t.FailNow() } if !procState.Success() { t.Errorf("Expected success") t.FailNow() } argsThree = []string{"/bin/sh", "-c", "exit 1"} pid, err = c.RunCommandNoWait(argsThree, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) t.FailNow() } proc, err = os.FindProcess(pid) if err != nil { t.Errorf(err.Error()) t.FailNow() } procState, err = proc.Wait() if err != nil { t.Errorf(err.Error()) t.FailNow() } if procState.Success() { t.Errorf("Expected failure") t.FailNow() } } func TestRunCommand(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } argsThree := []string{"/bin/sh", "-c", "exit 0"} ok, err := c.RunCommand(argsThree, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } argsThree = []string{"/bin/sh", "-c", "exit 1"} ok, err = c.RunCommand(argsThree, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) } if ok { t.Errorf("Expected failure") } } func TestCommandWithEnv(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.Env = []string{"FOO=BAR"} options.ClearEnv = true args := []string{"/bin/sh", "-c", "test $FOO = 'BAR'"} ok, err := c.RunCommand(args, options) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestCommandWithEnvToKeep(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.ClearEnv = true options.EnvToKeep = []string{"TERM"} args := []string{"/bin/sh", "-c", fmt.Sprintf("test $TERM = '%s'", os.Getenv("TERM"))} ok, err := c.RunCommand(args, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestCommandWithCwd(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.Cwd = "/tmp" args := []string{"/bin/sh", "-c", "test `pwd` = /tmp"} ok, err := c.RunCommand(args, options) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestCommandWithUIDGID(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.UID = 1000 options.GID = 1000 args := []string{"/bin/sh", "-c", "test `id -u` = 1000 && test `id -g` = 1000"} ok, err := c.RunCommand(args, options) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestCommandWithArch(t *testing.T) { uname := syscall.Utsname{} if err := syscall.Uname(&uname); err != nil { t.Errorf(err.Error()) } arch := "" for _, c := range uname.Machine { if c == 0 { break } arch += string(byte(c)) } if arch != "x86_64" && arch != "i686" { t.Skip("skipping architecture test, not on x86") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.Arch = X86 args := []string{"/bin/sh", "-c", "test `uname -m` = i686"} ok, err := c.RunCommand(args, options) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestConsoleFd(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.ConsoleFd(0); err != nil { t.Errorf(err.Error()) } } func TestIPAddress(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if unprivileged() { time.Sleep(3 * time.Second) } if _, err := c.IPAddress("lo"); err != nil { t.Errorf(err.Error()) } } func TestIPv4Address(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if unprivileged() { time.Sleep(3 * time.Second) } if _, err := c.IPv4Address("lo"); err != nil { t.Errorf(err.Error()) } } func TestIPv46ddress(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if unprivileged() { time.Sleep(3 * time.Second) } if _, err := c.IPv6Address("lo"); err != nil { t.Errorf(err.Error()) } } func TestAddDeviceNode(t *testing.T) { if unprivileged() { t.Skip("skipping test in unprivileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.AddDeviceNode("/dev/network_latency"); err != nil { t.Errorf(err.Error()) } } func TestRemoveDeviceNode(t *testing.T) { if unprivileged() { t.Skip("skipping test in unprivileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.RemoveDeviceNode("/dev/network_latency"); err != nil { t.Errorf(err.Error()) } } func TestIPv4Addresses(t *testing.T) { if !unprivileged() { t.Skip("skipping test in privileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.IPv4Addresses(); err != nil { t.Errorf(err.Error()) } } func TestIPv6Addresses(t *testing.T) { if !unprivileged() { t.Skip("skipping test in privileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.IPv6Addresses(); err != nil { t.Errorf(err.Error()) } } func TestReboot(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Reboot(); err != nil { t.Errorf("Rebooting the container failed...") } c.Wait(RUNNING, 30*time.Second) } func TestConcurrentShutdown(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { c, err := NewContainer(strconv.Itoa(i)) if err != nil { t.Errorf(err.Error()) } if err := c.Shutdown(30 * time.Second); err != nil { t.Errorf(err.Error()) } c.Wait(STOPPED, 30*time.Second) if c.Running() { t.Errorf("Shutting down the container failed...") } wg.Done() }(i) } wg.Wait() } func TestShutdown(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Shutdown(30 * time.Second); err != nil { t.Errorf(err.Error()) } c.Wait(STOPPED, 30*time.Second) if c.Running() { t.Errorf("Shutting down the container failed...") } } func TestStop(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Start(); err != nil { t.Errorf(err.Error()) } if err := c.Stop(); err != nil { t.Errorf(err.Error()) } c.Wait(STOPPED, 30*time.Second) if c.Running() { t.Errorf("Stopping the container failed...") } } func TestDestroySnapshot(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } snapshot := Snapshot{Name: SnapshotName} if err := c.DestroySnapshot(snapshot); err != nil { t.Errorf(err.Error()) } } func TestDestroyAllSnapshots(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.DestroyAllSnapshots(); err != nil { if err == ErrNotSupported { t.Skip("skipping due to lxc version.") } t.Errorf(err.Error()) } } func TestDestroy(t *testing.T) { if supported("overlayfs") { c, err := NewContainer(ContainerCloneOverlayName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } if !unprivileged() && supported("aufs") { c, err := NewContainer(ContainerCloneAufsName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } c, err := NewContainer(ContainerCloneName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } c, err = NewContainer(ContainerRestoreName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } c, err = NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } func TestConcurrentDestroy(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { c, err := NewContainer(strconv.Itoa(i)) if err != nil { t.Errorf(err.Error()) } // sleep for a while to simulate some dummy work time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } wg.Done() }(i) } wg.Wait() } func TestBackendStore(t *testing.T) { var X struct { store BackendStore } if X.store.String() != "" { t.Error("zero value of BackendStore should be invalid") } } func TestState(t *testing.T) { var X struct { state State } if X.state.String() != "" { t.Error("zero value of State should be invalid") } } func TestSupportedConfigItems(t *testing.T) { if VersionAtLeast(2, 1, 0) { if !IsSupportedConfigItem("lxc.arch") { t.Errorf("IsSupportedConfigItem failed to detect \"lxc.arch\" as supported config item...") } if IsSupportedConfigItem("lxc.nonsense") { t.Errorf("IsSupportedConfigItem failed to detect \"lxc.nonsense\" as unsupported config item...") } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/lxc-binding.h��������������������������������������������0000644�0610621�0607500�00000013073�13172163433�023621� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. extern bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path); extern void go_lxc_clear_config(struct lxc_container *c); extern bool go_lxc_clear_config_item(struct lxc_container *c, const char *key); extern bool go_lxc_clone(struct lxc_container *c, const char *newname, const char *lxcpath, int flags, const char *bdevtype); extern bool go_lxc_console(struct lxc_container *c, int ttynum, int stdinfd, int stdoutfd, int stderrfd, int escape); extern bool go_lxc_create(struct lxc_container *c, const char *t, const char *bdevtype, int flags, char * const argv[]); extern bool go_lxc_defined(struct lxc_container *c); extern bool go_lxc_destroy(struct lxc_container *c); extern bool go_lxc_destroy_with_snapshots(struct lxc_container *c); extern bool go_lxc_freeze(struct lxc_container *c); extern bool go_lxc_load_config(struct lxc_container *c, const char *alt_file); extern bool go_lxc_may_control(struct lxc_container *c); extern bool go_lxc_reboot(struct lxc_container *c); extern bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path); extern bool go_lxc_rename(struct lxc_container *c, const char *newname); extern bool go_lxc_running(struct lxc_container *c); extern bool go_lxc_save_config(struct lxc_container *c, const char *alt_file); extern bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value); extern bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value); extern bool go_lxc_set_config_path(struct lxc_container *c, const char *path); extern bool go_lxc_shutdown(struct lxc_container *c, int timeout); extern bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname); extern bool go_lxc_snapshot_destroy_all(struct lxc_container *c); extern bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname); extern bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]); extern bool go_lxc_stop(struct lxc_container *c); extern bool go_lxc_unfreeze(struct lxc_container *c); extern bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout); extern bool go_lxc_want_close_all_fds(struct lxc_container *c, bool state); extern bool go_lxc_want_daemonize(struct lxc_container *c, bool state); extern char* go_lxc_config_file_name(struct lxc_container *c); extern char* go_lxc_get_cgroup_item(struct lxc_container *c, const char *key); extern char* go_lxc_get_config_item(struct lxc_container *c, const char *key); extern char** go_lxc_get_interfaces(struct lxc_container *c); extern char** go_lxc_get_ips(struct lxc_container *c, const char *interface, const char *family, int scope); extern char* go_lxc_get_keys(struct lxc_container *c, const char *key); extern char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key); extern const char* go_lxc_get_config_path(struct lxc_container *c); extern const char* go_lxc_state(struct lxc_container *c); extern int go_lxc_attach_run_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[]); extern int go_lxc_attach(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env); extern int go_lxc_attach_no_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[], pid_t *attached_pid); extern int go_lxc_console_getfd(struct lxc_container *c, int ttynum); extern int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret); extern int go_lxc_snapshot(struct lxc_container *c); extern pid_t go_lxc_init_pid(struct lxc_container *c); extern bool go_lxc_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose); extern bool go_lxc_restore(struct lxc_container *c, char *directory, bool verbose); extern bool go_lxc_config_item_is_supported(const char *key); extern bool go_lxc_set_running_config_item(struct lxc_container *c, const char *key, const char *value); /* n.b. that we're just adding the fields here to shorten the definition * of go_lxc_migrate; in the case where we don't have the ->migrate API call, * we don't want to have to pass all the arguments in to let conditional * compilation handle things, but the call will still fail */ #if LXC_VERSION_MAJOR != 2 struct migrate_opts { char *directory; bool verbose; bool stop; char *predump_dir; }; #endif /* This is a struct that we can add "extra" (i.e. options added after 2.0.0) * migrate options to, so that we don't have to have a massive function * signature when the list of options grows. */ struct extra_migrate_opts { bool preserves_inodes; char *action_script; uint64_t ghost_limit; }; int go_lxc_migrate(struct lxc_container *c, unsigned int cmd, struct migrate_opts *opts, struct extra_migrate_opts *extras); extern bool go_lxc_attach_interface(struct lxc_container *c, const char *dev, const char *dst_dev); extern bool go_lxc_detach_interface(struct lxc_container *c, const char *dev, const char *dst_dev); ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/lxc-binding.go�������������������������������������������0000644�0610621�0607500�00000014012�13172163433�023771� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc // #cgo pkg-config: lxc // #cgo LDFLAGS: -llxc -lutil // #include <lxc/lxccontainer.h> // #include <lxc/version.h> // #include "lxc-binding.h" // #ifndef LXC_DEVEL // #define LXC_DEVEL 0 // #endif import "C" import ( "fmt" "runtime" "strings" "unsafe" ) // NewContainer returns a new container struct. func NewContainer(name string, lxcpath ...string) (*Container, error) { var container *C.struct_lxc_container cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) if lxcpath != nil && len(lxcpath) == 1 { clxcpath := C.CString(lxcpath[0]) defer C.free(unsafe.Pointer(clxcpath)) container = C.lxc_container_new(cname, clxcpath) } else { container = C.lxc_container_new(cname, nil) } if container == nil { return nil, ErrNewFailed } c := &Container{container: container, verbosity: Quiet} // http://golang.org/pkg/runtime/#SetFinalizer runtime.SetFinalizer(c, Release) return c, nil } // Acquire increments the reference counter of the container object. func Acquire(c *Container) bool { return C.lxc_container_get(c.container) == 1 } // Release decrements the reference counter of the container object. func Release(c *Container) bool { // http://golang.org/pkg/runtime/#SetFinalizer runtime.SetFinalizer(c, nil) return C.lxc_container_put(c.container) == 1 } // Version returns the LXC version. func Version() string { version := C.GoString(C.lxc_get_version()) // New liblxc versions append "-devel" when LXC_DEVEL is set. if strings.HasSuffix(version, "-devel") { return fmt.Sprintf("%s (devel)", version[:(len(version)-len("-devel"))]) } else if C.LXC_DEVEL == 1 { version = fmt.Sprintf("%s (devel)", version) } return version } // GlobalConfigItem returns the value of the given global config key. func GlobalConfigItem(name string) string { cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) return C.GoString(C.lxc_get_global_config_item(cname)) } // DefaultConfigPath returns default config path. func DefaultConfigPath() string { return GlobalConfigItem("lxc.lxcpath") } // DefaultLvmVg returns the name of the default LVM volume group. func DefaultLvmVg() string { return GlobalConfigItem("lxc.bdev.lvm.vg") } // DefaultZfsRoot returns the name of the default ZFS root. func DefaultZfsRoot() string { return GlobalConfigItem("lxc.bdev.zfs.root") } // ContainerNames returns the names of defined and active containers on the system. func ContainerNames(lxcpath ...string) []string { var size int var cnames **C.char if lxcpath != nil && len(lxcpath) == 1 { clxcpath := C.CString(lxcpath[0]) defer C.free(unsafe.Pointer(clxcpath)) size = int(C.list_all_containers(clxcpath, &cnames, nil)) } else { size = int(C.list_all_containers(nil, &cnames, nil)) } if size < 1 { return nil } return convertNArgs(cnames, size) } // Containers returns the defined and active containers on the system. Only // containers that could retrieved successfully are returned. func Containers(lxcpath ...string) []*Container { var containers []*Container for _, v := range ContainerNames(lxcpath...) { if container, err := NewContainer(v, lxcpath...); err == nil { containers = append(containers, container) } } return containers } // DefinedContainerNames returns the names of the defined containers on the system. func DefinedContainerNames(lxcpath ...string) []string { var size int var cnames **C.char if lxcpath != nil && len(lxcpath) == 1 { clxcpath := C.CString(lxcpath[0]) defer C.free(unsafe.Pointer(clxcpath)) size = int(C.list_defined_containers(clxcpath, &cnames, nil)) } else { size = int(C.list_defined_containers(nil, &cnames, nil)) } if size < 1 { return nil } return convertNArgs(cnames, size) } // DefinedContainers returns the defined containers on the system. Only // containers that could retrieved successfully are returned. func DefinedContainers(lxcpath ...string) []*Container { var containers []*Container for _, v := range DefinedContainerNames(lxcpath...) { if container, err := NewContainer(v, lxcpath...); err == nil { containers = append(containers, container) } } return containers } // ActiveContainerNames returns the names of the active containers on the system. func ActiveContainerNames(lxcpath ...string) []string { var size int var cnames **C.char if lxcpath != nil && len(lxcpath) == 1 { clxcpath := C.CString(lxcpath[0]) defer C.free(unsafe.Pointer(clxcpath)) size = int(C.list_active_containers(clxcpath, &cnames, nil)) } else { size = int(C.list_active_containers(nil, &cnames, nil)) } if size < 1 { return nil } return convertNArgs(cnames, size) } // ActiveContainers returns the active containers on the system. Only // containers that could retrieved successfully are returned. func ActiveContainers(lxcpath ...string) []*Container { var containers []*Container for _, v := range ActiveContainerNames(lxcpath...) { if container, err := NewContainer(v, lxcpath...); err == nil { containers = append(containers, container) } } return containers } // VersionNumber returns the LXC version. func VersionNumber() (major int, minor int) { major = C.LXC_VERSION_MAJOR minor = C.LXC_VERSION_MINOR return } // VersionAtLeast returns true when the tested version >= current version. func VersionAtLeast(major int, minor int, micro int) bool { if C.LXC_DEVEL == 1 { return true } if major > C.LXC_VERSION_MAJOR { return false } if major == C.LXC_VERSION_MAJOR && minor > C.LXC_VERSION_MINOR { return false } if major == C.LXC_VERSION_MAJOR && minor == C.LXC_VERSION_MINOR && micro > C.LXC_VERSION_MICRO { return false } return true } // IsSupportedConfigItem returns true if the key belongs to a supported config item. func IsSupportedConfigItem(key string) bool { configItem := C.CString(key) defer C.free(unsafe.Pointer(configItem)) return bool(C.go_lxc_config_item_is_supported(configItem)) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/lxc-binding.c��������������������������������������������0000644�0610621�0607500�00000027442�13172163433�023621� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo #include <stdbool.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <lxc/lxccontainer.h> #include <lxc/attach_options.h> #include <lxc/version.h> #include "lxc-binding.h" #ifndef LXC_DEVEL #define LXC_DEVEL 0 #endif #define VERSION_AT_LEAST(major, minor, micro) \ ((LXC_DEVEL == 1) || (!(major > LXC_VERSION_MAJOR || \ major == LXC_VERSION_MAJOR && minor > LXC_VERSION_MINOR || \ major == LXC_VERSION_MAJOR && minor == LXC_VERSION_MINOR && micro > LXC_VERSION_MICRO))) bool go_lxc_defined(struct lxc_container *c) { return c->is_defined(c); } const char* go_lxc_state(struct lxc_container *c) { return c->state(c); } bool go_lxc_running(struct lxc_container *c) { return c->is_running(c); } bool go_lxc_freeze(struct lxc_container *c) { return c->freeze(c); } bool go_lxc_unfreeze(struct lxc_container *c) { return c->unfreeze(c); } pid_t go_lxc_init_pid(struct lxc_container *c) { return c->init_pid(c); } bool go_lxc_want_daemonize(struct lxc_container *c, bool state) { return c->want_daemonize(c, state); } bool go_lxc_want_close_all_fds(struct lxc_container *c, bool state) { return c->want_close_all_fds(c, state); } bool go_lxc_create(struct lxc_container *c, const char *t, const char *bdevtype, int flags, char * const argv[]) { return c->create(c, t, bdevtype, NULL, !!(flags & LXC_CREATE_QUIET), argv); } bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]) { return c->start(c, useinit, argv); } bool go_lxc_stop(struct lxc_container *c) { return c->stop(c); } bool go_lxc_reboot(struct lxc_container *c) { return c->reboot(c); } bool go_lxc_shutdown(struct lxc_container *c, int timeout) { return c->shutdown(c, timeout); } char* go_lxc_config_file_name(struct lxc_container *c) { return c->config_file_name(c); } bool go_lxc_destroy(struct lxc_container *c) { return c->destroy(c); } bool go_lxc_destroy_with_snapshots(struct lxc_container *c) { #if VERSION_AT_LEAST(1, 1, 0) return c->destroy_with_snapshots(c); #else return false; #endif } bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout) { return c->wait(c, state, timeout); } char* go_lxc_get_config_item(struct lxc_container *c, const char *key) { int len = c->get_config_item(c, key, NULL, 0); if (len <= 0) { return NULL; } char* value = (char*)malloc(sizeof(char)*len + 1); if (c->get_config_item(c, key, value, len + 1) != len) { return NULL; } return value; } bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value) { return c->set_config_item(c, key, value); } void go_lxc_clear_config(struct lxc_container *c) { c->clear_config(c); } bool go_lxc_clear_config_item(struct lxc_container *c, const char *key) { return c->clear_config_item(c, key); } char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key) { return c->get_running_config_item(c, key); } char* go_lxc_get_keys(struct lxc_container *c, const char *key) { int len = c->get_keys(c, key, NULL, 0); if (len <= 0) { return NULL; } char* value = (char*)malloc(sizeof(char)*len + 1); if (c->get_keys(c, key, value, len + 1) != len) { return NULL; } return value; } char* go_lxc_get_cgroup_item(struct lxc_container *c, const char *key) { int len = c->get_cgroup_item(c, key, NULL, 0); if (len <= 0) { return NULL; } char* value = (char*)malloc(sizeof(char)*len + 1); if (c->get_cgroup_item(c, key, value, len + 1) != len) { return NULL; } return value; } bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value) { return c->set_cgroup_item(c, key, value); } const char* go_lxc_get_config_path(struct lxc_container *c) { return c->get_config_path(c); } bool go_lxc_set_config_path(struct lxc_container *c, const char *path) { return c->set_config_path(c, path); } bool go_lxc_load_config(struct lxc_container *c, const char *alt_file) { return c->load_config(c, alt_file); } bool go_lxc_save_config(struct lxc_container *c, const char *alt_file) { return c->save_config(c, alt_file); } bool go_lxc_clone(struct lxc_container *c, const char *newname, const char *lxcpath, int flags, const char *bdevtype) { return c->clone(c, newname, lxcpath, flags, bdevtype, NULL, 0, NULL) != NULL; } int go_lxc_console_getfd(struct lxc_container *c, int ttynum) { int masterfd; if (c->console_getfd(c, &ttynum, &masterfd) < 0) { return -1; } return masterfd; } bool go_lxc_console(struct lxc_container *c, int ttynum, int stdinfd, int stdoutfd, int stderrfd, int escape) { if (c->console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape) == 0) { return true; } return false; } char** go_lxc_get_interfaces(struct lxc_container *c) { return c->get_interfaces(c); } char** go_lxc_get_ips(struct lxc_container *c, const char *interface, const char *family, int scope) { return c->get_ips(c, interface, family, scope); } int wait_for_pid_status(pid_t pid) { int status, ret; again: ret = waitpid(pid, &status, 0); if (ret == -1) { if (errno == EINTR) goto again; return -1; } if (ret != pid) goto again; return status; } int go_lxc_attach_no_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[], pid_t *attached_pid) { int ret; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; lxc_attach_command_t command = (lxc_attach_command_t){.program = NULL}; attach_options.env_policy = LXC_ATTACH_KEEP_ENV; if (clear_env) { attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; } attach_options.namespaces = namespaces; attach_options.personality = personality; attach_options.uid = uid; attach_options.gid = gid; attach_options.stdin_fd = stdinfd; attach_options.stdout_fd = stdoutfd; attach_options.stderr_fd = stderrfd; attach_options.initial_cwd = initial_cwd; attach_options.extra_env_vars = extra_env_vars; attach_options.extra_keep_env = extra_keep_env; command.program = (char *)argv[0]; command.argv = (char **)argv; ret = c->attach(c, lxc_attach_run_command, &command, &attach_options, attached_pid); if (ret < 0) return -1; return 0; } int go_lxc_attach(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env) { int ret; pid_t pid; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; attach_options.env_policy = LXC_ATTACH_KEEP_ENV; if (clear_env) { attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; } attach_options.namespaces = namespaces; attach_options.personality = personality; attach_options.uid = uid; attach_options.gid = gid; attach_options.stdin_fd = stdinfd; attach_options.stdout_fd = stdoutfd; attach_options.stderr_fd = stderrfd; attach_options.initial_cwd = initial_cwd; attach_options.extra_env_vars = extra_env_vars; attach_options.extra_keep_env = extra_keep_env; /* remount_sys_proc When using -s and the mount namespace is not included, this flag will cause lxc-attach to remount /proc and /sys to reflect the current other namespace contexts. default_options.attach_flags |= LXC_ATTACH_REMOUNT_PROC_SYS; elevated_privileges Do not drop privileges when running command inside the container. If this option is specified, the new process will not be added to the container's cgroup(s) and it will not drop its capabilities before executing. default_options.attach_flags &= ~(LXC_ATTACH_MOVE_TO_CGROUP | LXC_ATTACH_DROP_CAPABILITIES | LXC_ATTACH_APPARMOR); */ ret = c->attach(c, lxc_attach_run_shell, NULL, &attach_options, &pid); if (ret < 0) return -1; ret = wait_for_pid_status(pid); if (ret < 0) return -1; if (WIFEXITED(ret)) return WEXITSTATUS(ret); return -1; } int go_lxc_attach_run_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[]) { int ret; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; attach_options.env_policy = LXC_ATTACH_KEEP_ENV; if (clear_env) { attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; } attach_options.namespaces = namespaces; attach_options.personality = personality; attach_options.uid = uid; attach_options.gid = gid; attach_options.stdin_fd = stdinfd; attach_options.stdout_fd = stdoutfd; attach_options.stderr_fd = stderrfd; attach_options.initial_cwd = initial_cwd; attach_options.extra_env_vars = extra_env_vars; attach_options.extra_keep_env = extra_keep_env; ret = c->attach_run_wait(c, &attach_options, argv[0], argv); if (WIFEXITED(ret) && WEXITSTATUS(ret) == 255) return -1; return ret; } bool go_lxc_may_control(struct lxc_container *c) { return c->may_control(c); } int go_lxc_snapshot(struct lxc_container *c) { return c->snapshot(c, NULL); } int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret) { return c->snapshot_list(c, ret); } bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname) { return c->snapshot_restore(c, snapname, newname); } bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname) { return c->snapshot_destroy(c, snapname); } bool go_lxc_snapshot_destroy_all(struct lxc_container *c) { #if VERSION_AT_LEAST(1, 1, 0) return c->snapshot_destroy_all(c); #else return false; #endif } bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { return c->add_device_node(c, src_path, dest_path); } bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { return c->remove_device_node(c, src_path, dest_path); } bool go_lxc_rename(struct lxc_container *c, const char *newname) { return c->rename(c, newname); } bool go_lxc_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose) { #if VERSION_AT_LEAST(1, 1, 0) return c->checkpoint(c, directory, stop, verbose); #else return false; #endif } bool go_lxc_restore(struct lxc_container *c, char *directory, bool verbose) { #if VERSION_AT_LEAST(1, 1, 0) return c->restore(c, directory, verbose); #else return false; #endif } int go_lxc_migrate(struct lxc_container *c, unsigned int cmd, struct migrate_opts *opts, struct extra_migrate_opts *extras) { #if VERSION_AT_LEAST(2, 0, 4) opts->action_script = extras->action_script; opts->ghost_limit = extras->ghost_limit; #endif #if VERSION_AT_LEAST(2, 0, 1) opts->preserves_inodes = extras->preserves_inodes; #endif #if VERSION_AT_LEAST(2, 0, 0) return c->migrate(c, cmd, opts, sizeof(*opts)); #else return -EINVAL; #endif } bool go_lxc_attach_interface(struct lxc_container *c, const char *dev, const char *dst_dev) { #if VERSION_AT_LEAST(1, 1, 0) return c->attach_interface(c, dev, dst_dev); #else return false; #endif } bool go_lxc_detach_interface(struct lxc_container *c, const char *dev, const char *dst_dev) { #if VERSION_AT_LEAST(1, 1, 0) return c->detach_interface(c, dev, dst_dev); #else return false; #endif } bool go_lxc_config_item_is_supported(const char *key) { #if VERSION_AT_LEAST(2, 1, 0) return lxc_config_item_is_supported(key); #else return false; #endif } bool go_lxc_set_running_config_item(struct lxc_container *c, const char *key, const char *value) { #if VERSION_AT_LEAST(3, 0, 0) return c->set_running_config_item(c, key, value); #else return false; #endif } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/������������������������������������������������0000755�0610621�0607500�00000000000�13172163433�023064� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/unfreeze.go�������������������������������������0000644�0610621�0607500�00000001422�13172163433�025235� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Unfreezing the container...\n") if err := c.Unfreeze(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.Wait(lxc.RUNNING, 10*time.Second) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/stop.go�����������������������������������������0000644�0610621�0607500�00000001441�13172163433�024400� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.SetLogFile("/tmp/" + name + ".log") c.SetLogLevel(lxc.TRACE) log.Printf("Stopping the container...\n") if err := c.Stop(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/stats.go����������������������������������������0000644�0610621�0607500�00000004436�13172163433�024560� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } // mem memUsed, err := c.MemoryUsage() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("MemoryUsage: %s\n", memUsed) } memLimit, err := c.MemoryLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("MemoryLimit: %s\n", memLimit) } // kmem kmemUsed, err := c.KernelMemoryUsage() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("KernelMemoryUsage: %s\n", kmemUsed) } kmemLimit, err := c.KernelMemoryLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("KernelMemoryLimit: %s\n", kmemLimit) } // swap swapUsed, err := c.MemorySwapUsage() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("MemorySwapUsage: %s\n", swapUsed) } swapLimit, err := c.MemorySwapLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("MemorySwapLimit: %s\n", swapLimit) } // blkio blkioUsage, err := c.BlkioUsage() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("BlkioUsage: %s\n", blkioUsage) } cpuTime, err := c.CPUTime() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("cpuacct.usage: %s\n", cpuTime) cpuTimePerCPU, err := c.CPUTimePerCPU() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("cpuacct.usageerrpercpu: %v\n", cpuTimePerCPU) cpuStats, err := c.CPUStats() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("cpuacct.stat: %v\n", cpuStats) interfaceStats, err := c.InterfaceStats() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("InterfaceStats: %v\n", interfaceStats) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/start.go����������������������������������������0000644�0610621�0607500�00000001722�13172163433�024552� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.SetLogFile("/tmp/" + name + ".log") c.SetLogLevel(lxc.TRACE) log.Printf("Starting the container...\n") if err := c.Start(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Waiting container to startup networking...\n") if _, err := c.WaitIPAddresses(5 * time.Second); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } ����������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/shutdown.go�������������������������������������0000644�0610621�0607500�00000001447�13172163433�025274� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Shutting down the container...\n") if err := c.Shutdown(30 * time.Second); err != nil { if err = c.Stop(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/restore_snapshot.go�����������������������������0000644�0610621�0607500�00000001456�13172163433�027023� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Restoring the container...\n") snapshot := lxc.Snapshot{Name: "snap0"} if err := c.RestoreSnapshot(snapshot, "rubik-restore"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/rename.go���������������������������������������0000644�0610621�0607500�00000001516�13172163433�024665� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string newname string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&newname, "newname", "kibur", "New name of the container") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Renaming container to %s...\n", newname) if err := c.Rename(newname); err != nil { log.Printf("ERROR: %s\n", err.Error()) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/reboot.go���������������������������������������0000644�0610621�0607500�00000001342�13172163433�024705� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Rebooting the container...\n") if err := c.Reboot(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/list_snapshots.go�������������������������������0000644�0610621�0607500�00000001226�13172163433�026471� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "log" "gopkg.in/lxc/go-lxc.v2" ) func main() { c := lxc.Containers() for i := range c { log.Printf("%s\n", c[i].Name()) l, err := c[i].Snapshots() if err != nil { log.Printf("ERROR: %s\n", err.Error()) } for _, s := range l { log.Printf("Name: %s\n", s.Name) log.Printf("Comment path: %s\n", s.CommentPath) log.Printf("Timestamp: %s\n", s.Timestamp) log.Printf("LXC path: %s\n", s.Path) log.Println() } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/list_keys.go������������������������������������0000644�0610621�0607500�00000001272�13172163433�025423� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } for _, k := range c.ConfigKeys() { log.Printf("%s -> %s", k, c.ConfigItem(k)) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/list.go�����������������������������������������0000644�0610621�0607500�00000001626�13172163433�024373� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.Parse() } func main() { log.Printf("Defined containers:\n") c := lxc.DefinedContainers(lxcpath) for i := range c { log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) } log.Println() log.Printf("Active containers:\n") c = lxc.ActiveContainers(lxcpath) for i := range c { log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) } log.Println() log.Printf("Active and Defined containers:\n") c = lxc.ActiveContainers(lxcpath) for i := range c { log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) } } ����������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/limit.go����������������������������������������0000644�0610621�0607500�00000002003�13172163433�024524� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } memLimit, err := c.MemoryLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } memorySwapLimit, err := c.MemorySwapLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err := c.SetMemoryLimit(memLimit / 4); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err := c.SetMemorySwapLimit(memorySwapLimit / 4); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/ipaddress.go������������������������������������0000644�0610621�0607500�00000002664�13172163433�025401� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("IPAddress(\"lo\")\n") if addresses, err := c.IPAddress("lo"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range addresses { log.Printf("%d) %s\n", i, v) } } log.Printf("IPAddresses()\n") if addresses, err := c.IPAddresses(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range addresses { log.Printf("%d) %s\n", i, v) } } log.Printf("IPv4Addresses()\n") if addresses, err := c.IPv4Addresses(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range addresses { log.Printf("%d) %s\n", i, v) } } log.Printf("IPv6Addresses()\n") if addresses, err := c.IPv6Addresses(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range addresses { log.Printf("%d) %s\n", i, v) } } } ����������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/interfaces.go�����������������������������������0000644�0610621�0607500�00000001472�13172163433�025542� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Interfaces\n") if interfaces, err := c.Interfaces(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range interfaces { log.Printf("%d) %s\n", i, v) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/freeze.go���������������������������������������0000644�0610621�0607500�00000001415�13172163433�024674� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Freezing the container...\n") if err := c.Freeze(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.Wait(lxc.FROZEN, 10*time.Second) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/execute.go��������������������������������������0000644�0610621�0607500�00000001434�13172163433�025057� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.LoadConfigFile(lxc.DefaultConfigPath()) if output, err := c.Execute("uname", "-a"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("%s", output) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/device_add_remove.go����������������������������0000644�0610621�0607500�00000001563�13172163433�027044� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err := c.AddDeviceNode("/dev/network_latency"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } time.Sleep(10000 * time.Millisecond) if err := c.RemoveDeviceNode("/dev/network_latency"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } ���������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/destroy_snapshots.go����������������������������0000644�0610621�0607500�00000001155�13172163433�027210� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "log" "gopkg.in/lxc/go-lxc.v2" ) func main() { c := lxc.Containers() for i := range c { log.Printf("%s\n", c[i].Name()) l, err := c[i].Snapshots() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } for _, s := range l { log.Printf("Destroying Snaphot: %s\n", s.Name) if err := c[i].DestroySnapshot(s); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/destroy.go��������������������������������������0000644�0610621�0607500�00000001340�13172163433�025102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Destroying container...\n") if err := c.Destroy(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/create_snapshot.go������������������������������0000644�0610621�0607500�00000001357�13172163433�026603� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Snapshoting the container...\n") if _, err := c.CreateSnapshot(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/create.go���������������������������������������0000644�0610621�0607500�00000003074�13172163433�024662� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string template string distro string release string arch string name string verbose bool flush bool validation bool ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&template, "template", "download", "Template to use") flag.StringVar(&distro, "distro", "ubuntu", "Template to use") flag.StringVar(&release, "release", "trusty", "Template to use") flag.StringVar(&arch, "arch", "amd64", "Template to use") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.BoolVar(&verbose, "verbose", false, "Verbose output") flag.BoolVar(&flush, "flush", false, "Flush the cache") flag.BoolVar(&validation, "validation", false, "GPG validation") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Creating container...\n") if verbose { c.SetVerbosity(lxc.Verbose) } options := lxc.TemplateOptions{ Template: template, Distro: distro, Release: release, Arch: arch, FlushCache: flush, DisableGPGValidation: validation, } if err := c.Create(options); err != nil { log.Printf("ERROR: %s\n", err.Error()) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/console.go��������������������������������������0000644�0610621�0607500�00000001405�13172163433�025055� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Attaching to container's console...\n") if err := c.Console(lxc.DefaultConsoleOptions); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/config.go���������������������������������������0000644�0610621�0607500�00000001673�13172163433�024667� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string hostname string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.StringVar(&hostname, "hostname", "rubik-host1", "Hostname of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } //setting hostname err = c.SetConfigItem("lxc.utsname", hostname) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } // fetching rootfs location rootfs := c.ConfigItem("lxc.rootfs")[0] log.Printf("Root FS: %s\n", rootfs) } ���������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/concurrent_stress.go����������������������������0000644�0610621�0607500�00000005103�13172163433�027177� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "io/ioutil" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string iteration int threads int template string quiet bool startstop bool createdestroy bool ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&template, "template", "busybox", "Template to use") flag.IntVar(&threads, "threads", 10, "Number of operations to run concurrently") flag.IntVar(&iteration, "iteration", 1, "Number times to run the test") flag.BoolVar(&quiet, "quiet", false, "Don't produce any output") flag.BoolVar(&startstop, "startstop", false, "Flag to execute Start and Stop") flag.BoolVar(&createdestroy, "createdestroy", false, "Flag to execute Create and Destroy") flag.Parse() } func main() { if quiet { log.SetOutput(ioutil.Discard) } log.Printf("Using %d GOMAXPROCS\n", runtime.NumCPU()) var wg sync.WaitGroup options := lxc.BusyboxTemplateOptions options.Template = template for i := 0; i < iteration; i++ { log.Printf("-- ITERATION %d --\n", i+1) for _, mode := range []string{"CREATE", "START", "STOP", "DESTROY"} { log.Printf("\t-- %s --\n", mode) for j := 0; j < threads; j++ { wg.Add(1) go func(i int, mode string) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if mode == "CREATE" && startstop == false { log.Printf("\t\tCreating the container (%d)...\n", i) if err := c.Create(options); err != nil { log.Fatalf("\t\t\tERROR: %s\n", err.Error()) } } else if mode == "START" && createdestroy == false { log.Printf("\t\tStarting the container (%d)...\n", i) if err := c.Start(); err != nil { log.Fatalf("\t\t\tERROR: %s\n", err.Error()) } } else if mode == "STOP" && createdestroy == false { log.Printf("\t\tStoping the container (%d)...\n", i) if err := c.Stop(); err != nil { log.Fatalf("\t\t\tERROR: %s\n", err.Error()) } } else if mode == "DESTROY" && startstop == false { log.Printf("\t\tDestroying the container (%d)...\n", i) if err := c.Destroy(); err != nil { log.Fatalf("\t\t\tERROR: %s\n", err.Error()) } } wg.Done() }(j, mode) } wg.Wait() } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/concurrent_stop.go������������������������������0000644�0610621�0607500�00000001662�13172163433�026647� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Stoping the container (%d)...\n", i) if err := c.Stop(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Done() }(i) } wg.Wait() } ������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/concurrent_start.go�����������������������������0000644�0610621�0607500�00000001664�13172163433�027021� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Starting the container (%d)...\n", i) if err := c.Start(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Done() }(i) } wg.Wait() } ����������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/concurrent_shutdown.go��������������������������0000644�0610621�0607500�00000001777�13172163433�027544� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Shutting down the container (%d)...\n", i) if err := c.Shutdown(30 * time.Second); err != nil { if err = c.Stop(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } wg.Done() }(i) } wg.Wait() } �lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/concurrent_destroy.go���������������������������0000644�0610621�0607500�00000001670�13172163433�027352� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Destroying the container (%d)...\n", i) if err := c.Destroy(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Done() }(i) } wg.Wait() } ������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/concurrent_create.go����������������������������0000644�0610621�0607500�00000001743�13172163433�027125� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup options := lxc.BusyboxTemplateOptions for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Creating the container (%d)...\n", i) if err := c.Create(options); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Done() }(i) } wg.Wait() } �����������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/clone.go����������������������������������������0000644�0610621�0607500�00000002060�13172163433�024511� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string backend lxc.BackendStore ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.Var(&backend, "backend", "Backend type to use, possible values are [dir, zfs, btrfs, lvm, aufs, overlayfs, loopback, best]") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if backend == 0 { log.Fatalf("ERROR: %s\n", lxc.ErrUnknownBackendStore) } log.Printf("Cloning the container using %s backend...\n", backend) err = c.Clone(name+"_"+backend.String(), lxc.CloneOptions{ Backend: backend, }) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/checkpoint.go�����������������������������������0000644�0610621�0607500�00000002170�13172163433�025542� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string directory string name string stop bool verbose bool ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.StringVar(&directory, "directory", "/tmp/rubik", "directory to save the checkpoint in") flag.BoolVar(&verbose, "verbose", false, "Verbose output") flag.BoolVar(&stop, "stop", false, "Stop the container after checkpointing.") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if verbose { c.SetVerbosity(lxc.Verbose) } options := lxc.CheckpointOptions{ Directory: directory, Verbose: verbose, Stop: stop, } if err := c.Checkpoint(options); err != nil { log.Printf("ERROR: %s\n", err.Error()) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/attach_with_pipes.go����������������������������0000644�0610621�0607500�00000004251�13172163433�027114� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "io" "log" "os" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string clear bool x86 bool regular bool wg sync.WaitGroup ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.BoolVar(&clear, "clear", false, "Attach with clear environment") flag.BoolVar(&x86, "x86", false, "Attach using x86 personality") flag.BoolVar(&regular, "regular", false, "Attach using a regular user") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } stdoutReader, stdoutWriter, err := os.Pipe() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } stderrReader, stderrWriter, err := os.Pipe() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Add(1) go func() { defer wg.Done() _, err = io.Copy(os.Stdout, stdoutReader) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } }() wg.Add(1) go func() { defer wg.Done() _, err = io.Copy(os.Stderr, stderrReader) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } }() options := lxc.DefaultAttachOptions options.StdinFd = os.Stdin.Fd() options.StdoutFd = stdoutWriter.Fd() options.StderrFd = stderrWriter.Fd() options.ClearEnv = false if clear { options.ClearEnv = true } if x86 { options.Arch = lxc.X86 } if regular { options.UID = 1000 options.GID = 1000 } log.Printf("AttachShell\n") if err := c.AttachShell(options); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("RunCommand\n") _, err = c.RunCommand([]string{"uname", "-a"}, options) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err = stdoutWriter.Close(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err = stderrWriter.Close(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Wait() } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/attach.go���������������������������������������0000644�0610621�0607500�00000002466�13172163433�024667� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string clear bool x86 bool regular bool ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.BoolVar(&clear, "clear", false, "Attach with clear environment") flag.BoolVar(&x86, "x86", false, "Attach using x86 personality") flag.BoolVar(&regular, "regular", false, "Attach using a regular user") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } options := lxc.DefaultAttachOptions options.ClearEnv = false if clear { options.ClearEnv = true } if x86 { options.Arch = lxc.X86 } if regular { options.UID = 1000 options.GID = 1000 } log.Printf("AttachShell\n") err = c.AttachShell(options) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("RunCommand\n") _, err = c.RunCommand([]string{"id"}, options) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/examples/Makefile����������������������������������������0000644�0610621�0607500�00000001243�13172163433�024524� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������NO_COLOR=\033[0m OK_COLOR=\033[0;32m ALL_GO_FILES = $(wildcard *.go) ALL_FILES = $(patsubst %.go,%,$(ALL_GO_FILES)) all: $(ALL_FILES) define PROGRAM_template $(1): format vet lint @echo "$(OK_COLOR)==> Building $(1) $(NO_COLOR)" @go build $(1).go endef $(foreach prog,$(ALL_FILES),$(eval $(call PROGRAM_template,$(prog)))) clean: @$(foreach file,$(ALL_FILES),rm -f $(file);) format: @echo "$(OK_COLOR)==> Formatting the code $(NO_COLOR)" @gofmt -s -w *.go @goimports -w *.go vet: @echo "$(OK_COLOR)==> Running go vet $(NO_COLOR)" @`which go` vet . lint: @echo "$(OK_COLOR)==> Running golint $(NO_COLOR)" @`which golint` . .PHONY: all clean format vet lint �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/error.go�������������������������������������������������0000644�0610621�0607500�00000013220�13172163433�022724� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc var ( ErrAddDeviceNodeFailed = NewError("adding device to container failed") ErrAllocationFailed = NewError("allocating memory failed") ErrAlreadyDefined = NewError("container already defined") ErrAlreadyFrozen = NewError("container is already frozen") ErrAlreadyRunning = NewError("container is already running") ErrAttachFailed = NewError("attaching to the container failed") ErrAttachInterfaceFailed = NewError("attaching specified netdev to the container failed") ErrBlkioUsage = NewError("BlkioUsage for the container failed") ErrCheckpointFailed = NewError("checkpoint failed") ErrClearingConfigItemFailed = NewError("clearing config item for the container failed") ErrClearingCgroupItemFailed = NewError("clearing cgroup item for the container failed") ErrCloneFailed = NewError("cloning the container failed") ErrCloseAllFdsFailed = NewError("setting close_all_fds flag for container failed") ErrCreateFailed = NewError("creating the container failed") ErrCreateSnapshotFailed = NewError("snapshotting the container failed") ErrDaemonizeFailed = NewError("setting daemonize flag for container failed") ErrDestroyAllSnapshotsFailed = NewError("destroying all snapshots failed") ErrDestroyFailed = NewError("destroying the container failed") ErrDestroySnapshotFailed = NewError("destroying the snapshot failed") ErrDestroyWithAllSnapshotsFailed = NewError("destroying the container with all snapshots failed") ErrDetachInterfaceFailed = NewError("detaching specified netdev to the container failed") ErrExecuteFailed = NewError("executing the command in a temporary container failed") ErrFreezeFailed = NewError("freezing the container failed") ErrInsufficientNumberOfArguments = NewError("insufficient number of arguments were supplied") ErrInterfaces = NewError("getting interface names for the container failed") ErrIPAddresses = NewError("getting IP addresses of the container failed") ErrIPAddress = NewError("getting IP address on the interface of the container failed") ErrIPv4Addresses = NewError("getting IPv4 addresses of the container failed") ErrIPv6Addresses = NewError("getting IPv6 addresses of the container failed") ErrKMemLimit = NewError("your kernel does not support cgroup kernel memory controller") ErrLoadConfigFailed = NewError("loading config file for the container failed") ErrMemLimit = NewError("your kernel does not support cgroup memory controller") ErrMemorySwapLimit = NewError("your kernel does not support cgroup swap controller") ErrMethodNotAllowed = NewError("the requested method is not currently supported with unprivileged containers") ErrNewFailed = NewError("allocating the container failed") ErrNoSnapshot = NewError("container has no snapshot") ErrNotDefined = NewError("container is not defined") ErrNotFrozen = NewError("container is not frozen") ErrNotRunning = NewError("container is not running") ErrNotSupported = NewError("method is not supported by this LXC version") ErrRebootFailed = NewError("rebooting the container failed") ErrRemoveDeviceNodeFailed = NewError("removing device from container failed") ErrRenameFailed = NewError("renaming the container failed") ErrRestoreFailed = NewError("restore failed") ErrRestoreSnapshotFailed = NewError("restoring the container failed") ErrSaveConfigFailed = NewError("saving config file for the container failed") ErrSettingCgroupItemFailed = NewError("setting cgroup item for the container failed") ErrSettingConfigItemFailed = NewError("setting config item for the container failed") ErrSettingConfigPathFailed = NewError("setting config file for the container failed") ErrSettingKMemoryLimitFailed = NewError("setting kernel memory limit for the container failed") ErrSettingMemoryLimitFailed = NewError("setting memory limit for the container failed") ErrSettingMemorySwapLimitFailed = NewError("setting memory+swap limit for the container failed") ErrSettingSoftMemoryLimitFailed = NewError("setting soft memory limit for the container failed") ErrShutdownFailed = NewError("shutting down the container failed") ErrSoftMemLimit = NewError("your kernel does not support cgroup memory controller") ErrStartFailed = NewError("starting the container failed") ErrStopFailed = NewError("stopping the container failed") ErrTemplateNotAllowed = NewError("unprivileged users only allowed to use \"download\" template") ErrUnfreezeFailed = NewError("unfreezing the container failed") ErrUnknownBackendStore = NewError("unknown backend type") ) // Error represents a basic error that implies the error interface. type Error struct { Message string } // NewError creates a new error with the given msg argument. func NewError(msg string) error { return &Error{ Message: msg, } } func (e *Error) Error() string { return e.Message } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/doc.go���������������������������������������������������0000644�0610621�0607500�00000000526�13172163433�022345� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Package lxc provides Go Bindings for LXC (Linux Containers) C API. LXC (LinuX Containers) is an operating system–level virtualization method for running multiple isolated Linux systems (containers) on a single control host. LXC combines cgroups and namespace support to provide an isolated environment for applications. */ package lxc ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/container.go���������������������������������������������0000644�0610621�0607500�00000122350�13172163433�023562� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc // #include <lxc/lxccontainer.h> // #include <lxc/version.h> // #include "lxc-binding.h" import "C" import ( "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "reflect" "strconv" "strings" "sync" "time" "unsafe" ) // Container struct type Container struct { mu sync.RWMutex container *C.struct_lxc_container verbosity Verbosity } // Snapshot struct type Snapshot struct { Name string CommentPath string Timestamp string Path string } const ( isDefined = 1 << iota isNotDefined isRunning isNotRunning isPrivileged isUnprivileged isGreaterEqualThanLXC11 isGreaterEqualThanLXC20 ) func (c *Container) makeSure(flags int) error { if flags&isDefined != 0 && !c.Defined() { return ErrNotDefined } if flags&isNotDefined != 0 && c.Defined() { return ErrAlreadyDefined } if flags&isRunning != 0 && !c.Running() { return ErrNotRunning } if flags&isNotRunning != 0 && c.Running() { return ErrAlreadyRunning } if flags&isPrivileged != 0 && os.Geteuid() != 0 { return ErrMethodNotAllowed } if flags&isGreaterEqualThanLXC11 != 0 && !VersionAtLeast(1, 1, 0) { return ErrNotSupported } if flags&isGreaterEqualThanLXC20 != 0 && !VersionAtLeast(2, 0, 0) { return ErrNotSupported } return nil } func (c *Container) cgroupItemAsByteSize(filename string, missing error) (ByteSize, error) { size, err := strconv.ParseFloat(c.CgroupItem(filename)[0], 64) if err != nil { return -1, missing } return ByteSize(size), nil } func (c *Container) setCgroupItemWithByteSize(filename string, limit ByteSize, missing error) error { if err := c.SetCgroupItem(filename, fmt.Sprintf("%.f", limit)); err != nil { return missing } return nil } // Name returns the name of the container. func (c *Container) Name() string { c.mu.RLock() defer c.mu.RUnlock() return C.GoString(c.container.name) } // Defined returns true if the container is already defined. func (c *Container) Defined() bool { c.mu.RLock() defer c.mu.RUnlock() return bool(C.go_lxc_defined(c.container)) } // Running returns true if the container is already running. func (c *Container) Running() bool { c.mu.RLock() defer c.mu.RUnlock() return bool(C.go_lxc_running(c.container)) } // Controllable returns true if the caller can control the container. func (c *Container) Controllable() bool { c.mu.RLock() defer c.mu.RUnlock() return bool(C.go_lxc_may_control(c.container)) } // CreateSnapshot creates a new snapshot. func (c *Container) CreateSnapshot() (*Snapshot, error) { if err := c.makeSure(isDefined | isNotRunning); err != nil { return nil, err } c.mu.Lock() defer c.mu.Unlock() ret := int(C.go_lxc_snapshot(c.container)) if ret < 0 { return nil, ErrCreateSnapshotFailed } return &Snapshot{Name: fmt.Sprintf("snap%d", ret)}, nil } // RestoreSnapshot creates a new container based on a snapshot. func (c *Container) RestoreSnapshot(snapshot Snapshot, name string) error { if err := c.makeSure(isDefined); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) csnapname := C.CString(snapshot.Name) defer C.free(unsafe.Pointer(csnapname)) if !bool(C.go_lxc_snapshot_restore(c.container, csnapname, cname)) { return ErrRestoreSnapshotFailed } return nil } // DestroySnapshot destroys the specified snapshot. func (c *Container) DestroySnapshot(snapshot Snapshot) error { if err := c.makeSure(isDefined); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() csnapname := C.CString(snapshot.Name) defer C.free(unsafe.Pointer(csnapname)) if !bool(C.go_lxc_snapshot_destroy(c.container, csnapname)) { return ErrDestroySnapshotFailed } return nil } // DestroyAllSnapshots destroys all the snapshot. func (c *Container) DestroyAllSnapshots() error { if err := c.makeSure(isDefined | isGreaterEqualThanLXC11); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_snapshot_destroy_all(c.container)) { return ErrDestroyAllSnapshotsFailed } return nil } // Snapshots returns the list of container snapshots. func (c *Container) Snapshots() ([]Snapshot, error) { if err := c.makeSure(isDefined); err != nil { return nil, err } c.mu.Lock() defer c.mu.Unlock() var csnapshots *C.struct_lxc_snapshot size := int(C.go_lxc_snapshot_list(c.container, &csnapshots)) defer freeSnapshots(csnapshots, size) if size < 1 { return nil, ErrNoSnapshot } hdr := reflect.SliceHeader{ Data: uintptr(unsafe.Pointer(csnapshots)), Len: size, Cap: size, } gosnapshots := *(*[]C.struct_lxc_snapshot)(unsafe.Pointer(&hdr)) snapshots := make([]Snapshot, size, size) for i := 0; i < size; i++ { snapshots[i] = Snapshot{ Name: C.GoString(gosnapshots[i].name), Timestamp: C.GoString(gosnapshots[i].timestamp), CommentPath: C.GoString(gosnapshots[i].comment_pathname), Path: C.GoString(gosnapshots[i].lxcpath), } } return snapshots, nil } // State returns the state of the container. func (c *Container) State() State { c.mu.RLock() defer c.mu.RUnlock() return StateMap[C.GoString(C.go_lxc_state(c.container))] } // InitPid returns the process ID of the container's init process // seen from outside the container. func (c *Container) InitPid() int { c.mu.RLock() defer c.mu.RUnlock() return int(C.go_lxc_init_pid(c.container)) } // Daemonize returns true if the container wished to be daemonized. func (c *Container) Daemonize() bool { c.mu.RLock() defer c.mu.RUnlock() return bool(c.container.daemonize) } // WantDaemonize determines if the container wants to run daemonized. func (c *Container) WantDaemonize(state bool) error { c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_want_daemonize(c.container, C.bool(state))) { return ErrDaemonizeFailed } return nil } // WantCloseAllFds determines whether container wishes all file descriptors // to be closed on startup. func (c *Container) WantCloseAllFds(state bool) error { c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_want_close_all_fds(c.container, C.bool(state))) { return ErrCloseAllFdsFailed } return nil } // SetVerbosity sets the verbosity level of some API calls func (c *Container) SetVerbosity(verbosity Verbosity) { c.mu.Lock() defer c.mu.Unlock() c.verbosity = verbosity } // Freeze freezes the running container. func (c *Container) Freeze() error { if err := c.makeSure(isRunning); err != nil { return err } if c.State() == FROZEN { return ErrAlreadyFrozen } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_freeze(c.container)) { return ErrFreezeFailed } return nil } // Unfreeze thaws the frozen container. func (c *Container) Unfreeze() error { if err := c.makeSure(isRunning); err != nil { return err } if c.State() != FROZEN { return ErrNotFrozen } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_unfreeze(c.container)) { return ErrUnfreezeFailed } return nil } // Create creates the container using given TemplateOptions func (c *Container) Create(options TemplateOptions) error { // FIXME: Support bdev_specs // // bdev_specs: // zfs requires zfsroot // lvm requires lvname/vgname/thinpool as well as fstype and fssize // btrfs requires nothing // dir requires nothing if err := c.makeSure(isNotDefined); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() // use download template if not set if options.Template == "" { options.Template = "download" } // use Directory backend if not set if options.Backend == 0 { options.Backend = Directory } var args []string if options.Template == "download" { // required parameters if options.Distro == "" || options.Release == "" || options.Arch == "" { return ErrInsufficientNumberOfArguments } args = append(args, "--dist", options.Distro, "--release", options.Release, "--arch", options.Arch) // optional arguments if options.Variant != "" { args = append(args, "--variant", options.Variant) } if options.Server != "" { args = append(args, "--server", options.Server) } if options.KeyID != "" { args = append(args, "--keyid", options.KeyID) } if options.KeyServer != "" { args = append(args, "--keyserver", options.KeyServer) } if options.DisableGPGValidation { args = append(args, "--no-validate") } if options.FlushCache { args = append(args, "--flush-cache") } if options.ForceCache { args = append(args, "--force-cache") } } else { // optional arguments if options.Release != "" { args = append(args, "--release", options.Release) } if options.Arch != "" { args = append(args, "--arch", options.Arch) } if options.FlushCache { args = append(args, "--flush-cache") } } if options.ExtraArgs != nil { args = append(args, options.ExtraArgs...) } ctemplate := C.CString(options.Template) defer C.free(unsafe.Pointer(ctemplate)) cbackend := C.CString(options.Backend.String()) defer C.free(unsafe.Pointer(cbackend)) ret := false if args != nil { cargs := makeNullTerminatedArgs(args) if cargs == nil { return ErrAllocationFailed } defer freeNullTerminatedArgs(cargs, len(args)) ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), cargs)) } else { ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), nil)) } if !ret { return ErrCreateFailed } return nil } // Start starts the container. func (c *Container) Start() error { if err := c.makeSure(isNotRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_start(c.container, 0, nil)) { return ErrStartFailed } return nil } // StartWithArgs starts the container using given arguments. func (c *Container) StartWithArgs(args []string) error { if err := c.makeSure(isNotRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_start(c.container, 0, makeNullTerminatedArgs(args))) { return ErrStartFailed } return nil } // Execute executes the given command in a temporary container. func (c *Container) Execute(args ...string) ([]byte, error) { if err := c.makeSure(isNotDefined); err != nil { return nil, err } // Deal with LXC 2.1's need of a defined container if VersionAtLeast(2, 1, 0) { os.MkdirAll(filepath.Join(c.ConfigPath(), c.Name()), 0700) c.SaveConfigFile(filepath.Join(c.ConfigPath(), c.Name(), "config")) defer os.RemoveAll(filepath.Join(c.ConfigPath(), c.Name())) } cargs := []string{"lxc-execute", "-n", c.Name(), "-P", c.ConfigPath(), "--"} cargs = append(cargs, args...) c.mu.Lock() defer c.mu.Unlock() // FIXME: Go runtime and src/lxc/start.c signal_handler are not playing nice together so use lxc-execute for now // go-nuts thread: https://groups.google.com/forum/#!msg/golang-nuts/h9GbvfYv83w/5Ly_jvOr86wJ output, err := exec.Command(cargs[0], cargs[1:]...).CombinedOutput() if err != nil { return nil, ErrExecuteFailed } return output, nil /* cargs := makeNullTerminatedArgs(args) if cargs == nil { return ErrAllocationFailed } defer freeNullTerminatedArgs(cargs, len(args)) if !bool(C.go_lxc_start(c.container, 1, cargs)) { return ErrExecuteFailed } return nil */ } // Stop stops the container. func (c *Container) Stop() error { if err := c.makeSure(isRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_stop(c.container)) { return ErrStopFailed } return nil } // Reboot reboots the container. func (c *Container) Reboot() error { if err := c.makeSure(isRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_reboot(c.container)) { return ErrRebootFailed } return nil } // Shutdown shuts down the container. func (c *Container) Shutdown(timeout time.Duration) error { if err := c.makeSure(isRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_shutdown(c.container, C.int(timeout.Seconds()))) { return ErrShutdownFailed } return nil } // Destroy destroys the container. func (c *Container) Destroy() error { if err := c.makeSure(isDefined | isNotRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_destroy(c.container)) { return ErrDestroyFailed } return nil } // DestroyWithAllSnapshots destroys the container and its snapshots func (c *Container) DestroyWithAllSnapshots() error { if err := c.makeSure(isDefined | isNotRunning | isGreaterEqualThanLXC11); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_destroy_with_snapshots(c.container)) { return ErrDestroyWithAllSnapshotsFailed } return nil } // Clone clones the container using given arguments with specified backend. func (c *Container) Clone(name string, options CloneOptions) error { // FIXME: bdevdata, newsize and hookargs // // bdevdata: // zfs requires zfsroot // lvm requires lvname/vgname/thinpool as well as fstype and fssize // btrfs requires nothing // dir requires nothing // // newsize: for blockdev-backed backingstores // // hookargs: additional arguments to pass to the clone hook script if err := c.makeSure(isDefined | isNotRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() // use Directory backend if not set if options.Backend == 0 { options.Backend = Directory } var flags int if options.KeepName { flags |= C.LXC_CLONE_KEEPNAME } if options.KeepMAC { flags |= C.LXC_CLONE_KEEPMACADDR } if options.Snapshot { flags |= C.LXC_CLONE_SNAPSHOT } cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) cbackend := C.CString(options.Backend.String()) defer C.free(unsafe.Pointer(cbackend)) if options.ConfigPath != "" { clxcpath := C.CString(options.ConfigPath) defer C.free(unsafe.Pointer(clxcpath)) if !bool(C.go_lxc_clone(c.container, cname, clxcpath, C.int(flags), cbackend)) { return ErrCloneFailed } } else { if !bool(C.go_lxc_clone(c.container, cname, nil, C.int(flags), cbackend)) { return ErrCloneFailed } } return nil } // Rename renames the container. func (c *Container) Rename(name string) error { if err := c.makeSure(isDefined | isNotRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) if !bool(C.go_lxc_rename(c.container, cname)) { return ErrRenameFailed } return nil } // Wait waits for container to reach a particular state. func (c *Container) Wait(state State, timeout time.Duration) bool { c.mu.Lock() defer c.mu.Unlock() cstate := C.CString(state.String()) defer C.free(unsafe.Pointer(cstate)) return bool(C.go_lxc_wait(c.container, cstate, C.int(timeout.Seconds()))) } // ConfigFileName returns the container's configuration file's name. func (c *Container) ConfigFileName() string { c.mu.RLock() defer c.mu.RUnlock() // allocated in lxc.c configFileName := C.go_lxc_config_file_name(c.container) defer C.free(unsafe.Pointer(configFileName)) return C.GoString(configFileName) } // ConfigItem returns the value of the given config item. func (c *Container) ConfigItem(key string) []string { c.mu.RLock() defer c.mu.RUnlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) // allocated in lxc.c configItem := C.go_lxc_get_config_item(c.container, ckey) defer C.free(unsafe.Pointer(configItem)) ret := strings.TrimSpace(C.GoString(configItem)) return strings.Split(ret, "\n") } // SetConfigItem sets the value of the given config item. func (c *Container) SetConfigItem(key string, value string) error { c.mu.Lock() defer c.mu.Unlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) cvalue := C.CString(value) defer C.free(unsafe.Pointer(cvalue)) if !bool(C.go_lxc_set_config_item(c.container, ckey, cvalue)) { return ErrSettingConfigItemFailed } return nil } // RunningConfigItem returns the value of the given config item. func (c *Container) RunningConfigItem(key string) []string { c.mu.RLock() defer c.mu.RUnlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) // allocated in lxc.c configItem := C.go_lxc_get_running_config_item(c.container, ckey) defer C.free(unsafe.Pointer(configItem)) ret := strings.TrimSpace(C.GoString(configItem)) return strings.Split(ret, "\n") } // CgroupItem returns the value of the given cgroup subsystem value. func (c *Container) CgroupItem(key string) []string { c.mu.RLock() defer c.mu.RUnlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) // allocated in lxc.c cgroupItem := C.go_lxc_get_cgroup_item(c.container, ckey) defer C.free(unsafe.Pointer(cgroupItem)) ret := strings.TrimSpace(C.GoString(cgroupItem)) return strings.Split(ret, "\n") } // SetCgroupItem sets the value of given cgroup subsystem value. func (c *Container) SetCgroupItem(key string, value string) error { c.mu.Lock() defer c.mu.Unlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) cvalue := C.CString(value) defer C.free(unsafe.Pointer(cvalue)) if !bool(C.go_lxc_set_cgroup_item(c.container, ckey, cvalue)) { return ErrSettingCgroupItemFailed } return nil } // ClearConfig completely clears the containers in-memory configuration. func (c *Container) ClearConfig() { c.mu.Lock() defer c.mu.Unlock() C.go_lxc_clear_config(c.container) } // ClearConfigItem clears the value of given config item. func (c *Container) ClearConfigItem(key string) error { c.mu.Lock() defer c.mu.Unlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) if !bool(C.go_lxc_clear_config_item(c.container, ckey)) { return ErrClearingConfigItemFailed } return nil } // ConfigKeys returns the names of the config items. func (c *Container) ConfigKeys(key ...string) []string { c.mu.RLock() defer c.mu.RUnlock() var keys *_Ctype_char if key != nil && len(key) == 1 { ckey := C.CString(key[0]) defer C.free(unsafe.Pointer(ckey)) // allocated in lxc.c keys = C.go_lxc_get_keys(c.container, ckey) defer C.free(unsafe.Pointer(keys)) } else { // allocated in lxc.c keys = C.go_lxc_get_keys(c.container, nil) defer C.free(unsafe.Pointer(keys)) } ret := strings.TrimSpace(C.GoString(keys)) return strings.Split(ret, "\n") } // LoadConfigFile loads the configuration file from given path. func (c *Container) LoadConfigFile(path string) error { c.mu.Lock() defer c.mu.Unlock() cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) if !bool(C.go_lxc_load_config(c.container, cpath)) { return ErrLoadConfigFailed } return nil } // SaveConfigFile saves the configuration file to given path. func (c *Container) SaveConfigFile(path string) error { c.mu.Lock() defer c.mu.Unlock() cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) if !bool(C.go_lxc_save_config(c.container, cpath)) { return ErrSaveConfigFailed } return nil } // ConfigPath returns the configuration file's path. func (c *Container) ConfigPath() string { c.mu.RLock() defer c.mu.RUnlock() return C.GoString(C.go_lxc_get_config_path(c.container)) } // SetConfigPath sets the configuration file's path. func (c *Container) SetConfigPath(path string) error { c.mu.Lock() defer c.mu.Unlock() cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) if !bool(C.go_lxc_set_config_path(c.container, cpath)) { return ErrSettingConfigPathFailed } return nil } // MemoryUsage returns memory usage of the container in bytes. func (c *Container) MemoryUsage() (ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.usage_in_bytes", ErrMemLimit) } // MemoryLimit returns memory limit of the container in bytes. func (c *Container) MemoryLimit() (ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.limit_in_bytes", ErrMemLimit) } // SetMemoryLimit sets memory limit of the container in bytes. func (c *Container) SetMemoryLimit(limit ByteSize) error { if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.limit_in_bytes", limit, ErrSettingMemoryLimitFailed) } // SoftMemoryLimit returns soft memory limit of the container in bytes. func (c *Container) SoftMemoryLimit() (ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.soft_limit_in_bytes", ErrSoftMemLimit) } // SetSoftMemoryLimit sets soft memory limit of the container in bytes. func (c *Container) SetSoftMemoryLimit(limit ByteSize) error { if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.soft_limit_in_bytes", limit, ErrSettingSoftMemoryLimitFailed) } // KernelMemoryUsage returns current kernel memory allocation of the container in bytes. func (c *Container) KernelMemoryUsage() (ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit) } // KernelMemoryLimit returns kernel memory limit of the container in bytes. func (c *Container) KernelMemoryLimit() (ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit) } // SetKernelMemoryLimit sets kernel memory limit of the container in bytes. func (c *Container) SetKernelMemoryLimit(limit ByteSize) error { if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.kmem.limit_in_bytes", limit, ErrSettingKMemoryLimitFailed) } // MemorySwapUsage returns memory+swap usage of the container in bytes. func (c *Container) MemorySwapUsage() (ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.memsw.usage_in_bytes", ErrMemorySwapLimit) } // MemorySwapLimit returns the memory+swap limit of the container in bytes. func (c *Container) MemorySwapLimit() (ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.memsw.limit_in_bytes", ErrMemorySwapLimit) } // SetMemorySwapLimit sets memory+swap limit of the container in bytes. func (c *Container) SetMemorySwapLimit(limit ByteSize) error { if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.memsw.limit_in_bytes", limit, ErrSettingMemorySwapLimitFailed) } // BlkioUsage returns number of bytes transferred to/from the disk by the container. func (c *Container) BlkioUsage() (ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } c.mu.RLock() defer c.mu.RUnlock() for _, v := range c.CgroupItem("blkio.throttle.io_service_bytes") { b := strings.Split(v, " ") if b[0] == "Total" { blkioUsed, err := strconv.ParseFloat(b[1], 64) if err != nil { return -1, err } return ByteSize(blkioUsed), nil } } return -1, ErrBlkioUsage } // CPUTime returns the total CPU time (in nanoseconds) consumed by all tasks // in this cgroup (including tasks lower in the hierarchy). func (c *Container) CPUTime() (time.Duration, error) { if err := c.makeSure(isRunning); err != nil { return -1, err } c.mu.RLock() defer c.mu.RUnlock() cpuUsage, err := strconv.ParseInt(c.CgroupItem("cpuacct.usage")[0], 10, 64) if err != nil { return -1, err } return time.Duration(cpuUsage), nil } // CPUTimePerCPU returns the CPU time (in nanoseconds) consumed on each CPU by // all tasks in this cgroup (including tasks lower in the hierarchy). func (c *Container) CPUTimePerCPU() (map[int]time.Duration, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() cpuTimes := make(map[int]time.Duration) for i, v := range strings.Split(c.CgroupItem("cpuacct.usage_percpu")[0], " ") { cpuUsage, err := strconv.ParseInt(v, 10, 64) if err != nil { return nil, err } cpuTimes[i] = time.Duration(cpuUsage) } return cpuTimes, nil } // CPUStats returns the number of CPU cycles (in the units defined by USER_HZ on the system) // consumed by tasks in this cgroup and its children in both user mode and system (kernel) mode. func (c *Container) CPUStats() (map[string]int64, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() cpuStat := c.CgroupItem("cpuacct.stat") user, err := strconv.ParseInt(strings.Split(cpuStat[0], "user ")[1], 10, 64) if err != nil { return nil, err } system, err := strconv.ParseInt(strings.Split(cpuStat[1], "system ")[1], 10, 64) if err != nil { return nil, err } return map[string]int64{"user": user, "system": system}, nil } // ConsoleFd allocates a console tty from container // ttynum: tty number to attempt to allocate or -1 to allocate the first available tty // // Returns "ttyfd" on success, -1 on failure. The returned "ttyfd" is // used to keep the tty allocated. The caller should close "ttyfd" to // indicate that it is done with the allocated console so that it can // be allocated by another caller. func (c *Container) ConsoleFd(ttynum int) (int, error) { // FIXME: Make idiomatic if err := c.makeSure(isRunning); err != nil { return -1, err } c.mu.Lock() defer c.mu.Unlock() ret := int(C.go_lxc_console_getfd(c.container, C.int(ttynum))) if ret < 0 { return -1, ErrAttachFailed } return ret, nil } // Console allocates and runs a console tty from container // // This function will not return until the console has been exited by the user. func (c *Container) Console(options ConsoleOptions) error { if err := c.makeSure(isRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() ret := bool(C.go_lxc_console(c.container, C.int(options.Tty), C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), C.int(options.EscapeCharacter))) if !ret { return ErrAttachFailed } return nil } // AttachShell attaches a shell to the container. // It clears all environment variables before attaching. func (c *Container) AttachShell(options AttachOptions) error { if err := c.makeSure(isRunning); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() cenv := makeNullTerminatedArgs(options.Env) if cenv == nil { return ErrAllocationFailed } defer freeNullTerminatedArgs(cenv, len(options.Env)) cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) if cenvToKeep == nil { return ErrAllocationFailed } defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) cwd := C.CString(options.Cwd) defer C.free(unsafe.Pointer(cwd)) ret := int(C.go_lxc_attach(c.container, C.bool(options.ClearEnv), C.int(options.Namespaces), C.long(options.Arch), C.uid_t(options.UID), C.gid_t(options.GID), C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, )) if ret < 0 { return ErrAttachFailed } return nil } // RunCommandStatus attachs a shell and runs the command within the container. // The process will wait for the command to finish and return the result of // waitpid(), i.e. the process' exit status. An error is returned only when // invocation of the command completely fails. func (c *Container) RunCommandStatus(args []string, options AttachOptions) (int, error) { if len(args) == 0 { return -1, ErrInsufficientNumberOfArguments } if err := c.makeSure(isRunning); err != nil { return -1, err } c.mu.Lock() defer c.mu.Unlock() cargs := makeNullTerminatedArgs(args) if cargs == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cargs, len(args)) cenv := makeNullTerminatedArgs(options.Env) if cenv == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenv, len(options.Env)) cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) if cenvToKeep == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) cwd := C.CString(options.Cwd) defer C.free(unsafe.Pointer(cwd)) ret := int(C.go_lxc_attach_run_wait( c.container, C.bool(options.ClearEnv), C.int(options.Namespaces), C.long(options.Arch), C.uid_t(options.UID), C.gid_t(options.GID), C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, cargs, )) return ret, nil } // RunCommandNoWait runs the given command and returns without waiting it to finish. func (c *Container) RunCommandNoWait(args []string, options AttachOptions) (int, error) { if len(args) == 0 { return -1, ErrInsufficientNumberOfArguments } if err := c.makeSure(isRunning); err != nil { return -1, err } c.mu.Lock() defer c.mu.Unlock() cargs := makeNullTerminatedArgs(args) if cargs == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cargs, len(args)) cenv := makeNullTerminatedArgs(options.Env) if cenv == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenv, len(options.Env)) cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) if cenvToKeep == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) cwd := C.CString(options.Cwd) defer C.free(unsafe.Pointer(cwd)) var attachedPid C.pid_t ret := int(C.go_lxc_attach_no_wait( c.container, C.bool(options.ClearEnv), C.int(options.Namespaces), C.long(options.Arch), C.uid_t(options.UID), C.gid_t(options.GID), C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, cargs, &attachedPid, )) if ret < 0 { return -1, ErrAttachFailed } return int(attachedPid), nil } // RunCommand attachs a shell and runs the command within the container. // The process will wait for the command to finish and return a success status. An error // is returned only when invocation of the command completely fails. func (c *Container) RunCommand(args []string, options AttachOptions) (bool, error) { ret, err := c.RunCommandStatus(args, options) if err != nil { return false, err } if ret < 0 { return false, ErrAttachFailed } return ret == 0, nil } // Interfaces returns the names of the network interfaces. func (c *Container) Interfaces() ([]string, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() result := C.go_lxc_get_interfaces(c.container) if result == nil { return nil, ErrInterfaces } return convertArgs(result), nil } // InterfaceStats returns the stats about container's network interfaces func (c *Container) InterfaceStats() (map[string]map[string]ByteSize, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() var interfaceName string statistics := make(map[string]map[string]ByteSize) netPrefix := "lxc.net" if !VersionAtLeast(2, 1, 0) { netPrefix = "lxc.network" } for i := 0; i < len(c.ConfigItem(netPrefix)); i++ { interfaceType := c.RunningConfigItem(fmt.Sprintf("%s.%d.type", netPrefix, i)) if interfaceType == nil { continue } if interfaceType[0] == "veth" { interfaceName = c.RunningConfigItem(fmt.Sprintf("%s.%d.veth.pair", netPrefix, i))[0] } else { interfaceName = c.RunningConfigItem(fmt.Sprintf("%s.%d.link", netPrefix, i))[0] } for _, v := range []string{"rx", "tx"} { /* tx and rx are reversed from the host vs container */ content, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/net/%s/statistics/%s_bytes", interfaceName, v)) if err != nil { return nil, err } bytes, err := strconv.ParseInt(strings.Split(string(content), "\n")[0], 10, 64) if err != nil { return nil, err } if statistics[interfaceName] == nil { statistics[interfaceName] = make(map[string]ByteSize) } statistics[interfaceName][v] = ByteSize(bytes) } } return statistics, nil } // IPAddress returns the IP address of the given network interface. func (c *Container) IPAddress(interfaceName string) ([]string, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() cinterface := C.CString(interfaceName) defer C.free(unsafe.Pointer(cinterface)) result := C.go_lxc_get_ips(c.container, cinterface, nil, 0) if result == nil { return nil, ErrIPAddress } return convertArgs(result), nil } // IPv4Address returns the IPv4 address of the given network interface. func (c *Container) IPv4Address(interfaceName string) ([]string, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() cinterface := C.CString(interfaceName) defer C.free(unsafe.Pointer(cinterface)) cfamily := C.CString("inet") defer C.free(unsafe.Pointer(cfamily)) result := C.go_lxc_get_ips(c.container, cinterface, cfamily, 0) if result == nil { return nil, ErrIPv4Addresses } return convertArgs(result), nil } // IPv6Address returns the IPv6 address of the given network interface. func (c *Container) IPv6Address(interfaceName string) ([]string, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() cinterface := C.CString(interfaceName) defer C.free(unsafe.Pointer(cinterface)) cfamily := C.CString("inet6") defer C.free(unsafe.Pointer(cfamily)) result := C.go_lxc_get_ips(c.container, cinterface, cfamily, 0) if result == nil { return nil, ErrIPv6Addresses } return convertArgs(result), nil } // WaitIPAddresses waits until IPAddresses call returns something or time outs func (c *Container) WaitIPAddresses(timeout time.Duration) ([]string, error) { now := time.Now() for { if result, err := c.IPAddresses(); err == nil && len(result) > 0 { return result, nil } // Python API sleeps 1 second as well time.Sleep(1 * time.Second) if time.Since(now) >= timeout { return nil, ErrIPAddresses } } } // IPAddresses returns all IP addresses. func (c *Container) IPAddresses() ([]string, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() result := C.go_lxc_get_ips(c.container, nil, nil, 0) if result == nil { return nil, ErrIPAddresses } return convertArgs(result), nil } // IPv4Addresses returns all IPv4 addresses. func (c *Container) IPv4Addresses() ([]string, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() cfamily := C.CString("inet") defer C.free(unsafe.Pointer(cfamily)) result := C.go_lxc_get_ips(c.container, nil, cfamily, 0) if result == nil { return nil, ErrIPv4Addresses } return convertArgs(result), nil } // IPv6Addresses returns all IPv6 addresses. func (c *Container) IPv6Addresses() ([]string, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } c.mu.RLock() defer c.mu.RUnlock() cfamily := C.CString("inet6") defer C.free(unsafe.Pointer(cfamily)) result := C.go_lxc_get_ips(c.container, nil, cfamily, 0) if result == nil { return nil, ErrIPv6Addresses } return convertArgs(result), nil } // LogFile returns the name of the logfile. func (c *Container) LogFile() string { if VersionAtLeast(2, 1, 0) { return c.ConfigItem("lxc.log.file")[0] } return c.ConfigItem("lxc.logfile")[0] } // SetLogFile sets the name of the logfile. func (c *Container) SetLogFile(filename string) error { var err error if VersionAtLeast(2, 1, 0) { err = c.SetConfigItem("lxc.log.file", filename) } else { err = c.SetConfigItem("lxc.logfile", filename) } if err != nil { return err } return nil } // LogLevel returns the level of the logfile. func (c *Container) LogLevel() LogLevel { if VersionAtLeast(2, 1, 0) { return logLevelMap[c.ConfigItem("lxc.log.level")[0]] } return logLevelMap[c.ConfigItem("lxc.loglevel")[0]] } // SetLogLevel sets the level of the logfile. func (c *Container) SetLogLevel(level LogLevel) error { var err error if VersionAtLeast(2, 1, 0) { err = c.SetConfigItem("lxc.log.level", level.String()) } else { err = c.SetConfigItem("lxc.loglevel", level.String()) } if err != nil { return err } return nil } // AddDeviceNode adds specified device to the container. func (c *Container) AddDeviceNode(source string, destination ...string) error { if err := c.makeSure(isRunning | isPrivileged); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) if destination != nil && len(destination) == 1 { cdestination := C.CString(destination[0]) defer C.free(unsafe.Pointer(cdestination)) if !bool(C.go_lxc_add_device_node(c.container, csource, cdestination)) { return ErrAddDeviceNodeFailed } return nil } if !bool(C.go_lxc_add_device_node(c.container, csource, nil)) { return ErrAddDeviceNodeFailed } return nil } // RemoveDeviceNode removes the specified device from the container. func (c *Container) RemoveDeviceNode(source string, destination ...string) error { if err := c.makeSure(isRunning | isPrivileged); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) if destination != nil && len(destination) == 1 { cdestination := C.CString(destination[0]) defer C.free(unsafe.Pointer(cdestination)) if !bool(C.go_lxc_remove_device_node(c.container, csource, cdestination)) { return ErrRemoveDeviceNodeFailed } return nil } if !bool(C.go_lxc_remove_device_node(c.container, csource, nil)) { return ErrRemoveDeviceNodeFailed } return nil } // Checkpoint checkpoints the container. func (c *Container) Checkpoint(opts CheckpointOptions) error { if err := c.makeSure(isRunning | isGreaterEqualThanLXC11); err != nil { return err } cdirectory := C.CString(opts.Directory) defer C.free(unsafe.Pointer(cdirectory)) cstop := C.bool(opts.Stop) cverbose := C.bool(opts.Verbose) if !C.go_lxc_checkpoint(c.container, cdirectory, cstop, cverbose) { return ErrCheckpointFailed } return nil } // Restore restores the container from a checkpoint. func (c *Container) Restore(opts RestoreOptions) error { if err := c.makeSure(isGreaterEqualThanLXC11); err != nil { return err } cdirectory := C.CString(opts.Directory) defer C.free(unsafe.Pointer(cdirectory)) cverbose := C.bool(opts.Verbose) if !C.bool(C.go_lxc_restore(c.container, cdirectory, cverbose)) { return ErrRestoreFailed } return nil } // Migrate migrates the container. func (c *Container) Migrate(cmd uint, opts MigrateOptions) error { if err := c.makeSure(isNotDefined | isGreaterEqualThanLXC20); err != nil { return err } if cmd != MIGRATE_RESTORE { if err := c.makeSure(isRunning); err != nil { return err } } cdirectory := C.CString(opts.Directory) defer C.free(unsafe.Pointer(cdirectory)) var cpredumpdir *C.char if opts.PredumpDir != "" { cpredumpdir = C.CString(opts.PredumpDir) defer C.free(unsafe.Pointer(cpredumpdir)) } /* Since we can't do conditional compilation here, we allocate the * "extras" struct and then merge them in the C code. */ copts := C.struct_migrate_opts{ directory: cdirectory, verbose: C.bool(opts.Verbose), stop: C.bool(opts.Stop), predump_dir: cpredumpdir, } var cActionScript *C.char if opts.ActionScript != "" { cActionScript = C.CString(opts.ActionScript) defer C.free(unsafe.Pointer(cActionScript)) } extras := C.struct_extra_migrate_opts{ preserves_inodes: C.bool(opts.PreservesInodes), action_script: cActionScript, ghost_limit: C.uint64_t(opts.GhostLimit), } ret := C.int(C.go_lxc_migrate(c.container, C.uint(cmd), &copts, &extras)) if ret != 0 { return fmt.Errorf("migration failed %d", ret) } return nil } // AttachInterface attaches specifed netdev to the container. func (c *Container) AttachInterface(source, destination string) error { if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) cdestination := C.CString(destination) defer C.free(unsafe.Pointer(cdestination)) if !bool(C.go_lxc_attach_interface(c.container, csource, cdestination)) { return ErrAttachInterfaceFailed } return nil } // DetachInterface detaches specifed netdev from the container. func (c *Container) DetachInterface(source string) error { if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) if !bool(C.go_lxc_detach_interface(c.container, csource, nil)) { return ErrDetachInterfaceFailed } return nil } // DetachInterfaceRename detaches specifed netdev from the container and renames it. func (c *Container) DetachInterfaceRename(source, target string) error { if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { return err } c.mu.Lock() defer c.mu.Unlock() csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) ctarget := C.CString(target) defer C.free(unsafe.Pointer(ctarget)) if !bool(C.go_lxc_detach_interface(c.container, csource, ctarget)) { return ErrDetachInterfaceFailed } return nil } // SetRunningConfigItem sets the value of the given config item in the // container's in-memory config. func (c *Container) SetRunningConfigItem(key string, value string) error { c.mu.Lock() defer c.mu.Unlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) cvalue := C.CString(value) defer C.free(unsafe.Pointer(cvalue)) if !bool(C.go_lxc_set_running_config_item(c.container, ckey, cvalue)) { return ErrSettingConfigItemFailed } return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/README.md������������������������������������������������0000644�0610621�0607500�00000002346�13172163433�022532� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go Bindings for LXC (Linux Containers) This package implements [Go](http://golang.org) bindings for the [LXC](http://linuxcontainers.org/) C API (liblxc). ## Requirements This package requires [LXC 1.x](https://github.com/lxc/lxc/releases) and its development package to be installed. Works with [Go 1.x](http://golang.org/dl). Following command should install required dependencies on Ubuntu: apt-get install -y pkg-config lxc-dev ## Installing To install it, run: go get gopkg.in/lxc/go-lxc.v2 ## Documentation Documentation can be found at [GoDoc](http://godoc.org/gopkg.in/lxc/go-lxc.v2). ## Stability The package API will remain stable as described in [gopkg.in](https://gopkg.in). ## Examples See the [examples](https://github.com/lxc/go-lxc/tree/v2/examples) directory for some. ## Contributing We'd love to see go-lxc improve. To contribute to go-lxc; * **Fork** the repository * **Modify** your fork * Ensure your fork **passes all tests** * **Send** a pull request * Bonus points if the pull request includes *what* you changed, *why* you changed it, and *tests* attached. * For the love of all that is holy, please use `go fmt` *before* you send the pull request. We'll review it and merge it in if it's appropriate. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/Makefile�������������������������������������������������0000644�0610621�0607500�00000002462�13172163433�022712� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������NO_COLOR=\033[0m OK_COLOR=\033[0;32m all: format vet lint format: @echo "$(OK_COLOR)==> Formatting the code $(NO_COLOR)" @gofmt -s -w *.go @goimports -w *.go || true test: @echo "$(OK_COLOR)==> Running go test $(NO_COLOR)" @sudo `which go` test -v test-race: @echo "$(OK_COLOR)==> Running go test $(NO_COLOR)" @sudo `which go` test -race -v test-unprivileged: @echo "$(OK_COLOR)==> Running go test for unprivileged user$(NO_COLOR)" @`which go` test -v test-unprivileged-race: @echo "$(OK_COLOR)==> Running go test for unprivileged user$(NO_COLOR)" @`which go` test -race -v cover: @sudo `which go` test -v -coverprofile=coverage.out @`which go` tool cover -func=coverage.out doc: @`which godoc` gopkg.in/lxc/go-lxc.v2 | less vet: @echo "$(OK_COLOR)==> Running go vet $(NO_COLOR)" @`which go` vet . lint: @echo "$(OK_COLOR)==> Running golint $(NO_COLOR)" @`which golint` . || true escape-analysis: @go build -gcflags -m ctags: @ctags -R --languages=c,go setup-test-cgroup: for d in /sys/fs/cgroup/*; do \ [ -f $$d/cgroup.clone_children ] && echo 1 | sudo tee $$d/cgroup.clone_children; \ [ -f $$d/cgroup.use_hierarchy ] && echo 1 | sudo tee $$d/cgroup.use_hierarchy; \ sudo mkdir -p $$d/lxc; \ sudo chown -R $$USER: $$d/lxc; \ done .PHONY: all format test doc vet lint ctags ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/LICENSE��������������������������������������������������0000644�0610621�0607500�00000065715�13172163433�022271� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������This software is licensed under the LGPLv2.1, included below. As a special exception to the GNU Lesser General Public License version 2.1 ("LGPL2.1"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code or providing the installation information, provided that you comply with the other provisions of LGPL2.1 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL2.1 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the library's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. <signature of Ty Coon>, 1 April 1990 Ty Coon, President of Vice That's all there is to it! ���������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/AUTHORS��������������������������������������������������0000644�0610621�0607500�00000001032�13172163433�022312� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This is the official list of Go-LXC authors for copyright purposes. # Names should be added to this file as #Name or Organization <email address> # The email address is not required for organizations. # Please keep the list sorted. David Cramer <cramer@dropbox.com> Fatih Arslan <fatih@koding.com> Kelsey Hightower <kelsey.hightower@gmail.com> S.Çağlar Onur <caglar@10ur.org> Serge Hallyn <serge.hallyn@ubuntu.com> Stéphane Graber <stgraber@ubuntu.com> Syed <syed1.mushtaq@gmail.com> Tycho Andersen <tycho.andersen@canonical.com> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/lxc/go-lxc.v2/.travis.yml����������������������������������������������0000644�0610621�0607500�00000002057�13172163433�023363� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go os: - linux go: - 1.6 - 1.7 - 1.8 - 1.9 - tip matrix: fast_finish: true allow_failures: - go: tip before_install: - sudo add-apt-repository ppa:ubuntu-lxc/daily -y - sudo apt-get update - sudo apt-get install -qq lxc lxc-dev uidmap - echo "${USER}:100000:65536" | sudo tee /etc/subuid - echo "${USER}:100000:65536" | sudo tee /etc/subgid - echo "${USER} veth lxcbr0 10" | sudo tee -a /etc/lxc/lxc-usernet - mkdir -p ~/.config/lxc/ - cp /etc/lxc/default.conf ~/.config/lxc/default.conf - echo "lxc.idmap = u 0 100000 65536" | sudo tee -a ~/.config/lxc/default.conf - echo "lxc.idmap = g 0 100000 65536" | sudo tee -a ~/.config/lxc/default.conf - "make setup-test-cgroup" - mkdir -p ~/.local/share - chmod +x ~/.local/share - chmod +x ~/.local/ - chmod +x ${HOME} install: - go get gopkg.in/lxc/go-lxc.v2 script: - "make all" - "make test" - "make test-race" - "make test-unprivileged" - "make test-unprivileged-race" - "make cover" notifications: webhooks: https://linuxcontainers.org/webhook-lxcbot/ ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/����������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163430�020214� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163432�021751� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/variable.go�������������������������������������������0000644�0610621�0607500�00000040426�13172163432�024073� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" "reflect" "strconv" "strings" ) const ( varTypeInt = iota varTypeIdent ) type variablePart struct { typ int s string i int is_function_call bool calling_args []functionCallArgument // needed for a function call, represents all argument nodes (INode supports nested function calls) } type functionCallArgument interface { Evaluate(*ExecutionContext) (*Value, *Error) } // TODO: Add location tokens type stringResolver struct { location_token *Token val string } type intResolver struct { location_token *Token val int } type floatResolver struct { location_token *Token val float64 } type boolResolver struct { location_token *Token val bool } type variableResolver struct { location_token *Token parts []*variablePart } type nodeFilteredVariable struct { location_token *Token resolver IEvaluator filterChain []*filterCall } type nodeVariable struct { location_token *Token expr IEvaluator } func (expr *nodeFilteredVariable) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *variableResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *stringResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *intResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *floatResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *boolResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (v *nodeFilteredVariable) GetPositionToken() *Token { return v.location_token } func (v *variableResolver) GetPositionToken() *Token { return v.location_token } func (v *stringResolver) GetPositionToken() *Token { return v.location_token } func (v *intResolver) GetPositionToken() *Token { return v.location_token } func (v *floatResolver) GetPositionToken() *Token { return v.location_token } func (v *boolResolver) GetPositionToken() *Token { return v.location_token } func (s *stringResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) { return AsValue(s.val), nil } func (i *intResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) { return AsValue(i.val), nil } func (f *floatResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) { return AsValue(f.val), nil } func (b *boolResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) { return AsValue(b.val), nil } func (s *stringResolver) FilterApplied(name string) bool { return false } func (i *intResolver) FilterApplied(name string) bool { return false } func (f *floatResolver) FilterApplied(name string) bool { return false } func (b *boolResolver) FilterApplied(name string) bool { return false } func (nv *nodeVariable) FilterApplied(name string) bool { return nv.expr.FilterApplied(name) } func (nv *nodeVariable) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := nv.expr.Evaluate(ctx) if err != nil { return err } if !nv.expr.FilterApplied("safe") && !value.safe && value.IsString() && ctx.Autoescape { // apply escape filter value, err = filters["escape"](value, nil) if err != nil { return err } } buffer.WriteString(value.String()) return nil } func (vr *variableResolver) FilterApplied(name string) bool { return false } func (vr *variableResolver) String() string { parts := make([]string, 0, len(vr.parts)) for _, p := range vr.parts { switch p.typ { case varTypeInt: parts = append(parts, strconv.Itoa(p.i)) case varTypeIdent: parts = append(parts, p.s) default: panic("unimplemented") } } return strings.Join(parts, ".") } func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) { var current reflect.Value var is_safe bool for idx, part := range vr.parts { if idx == 0 { // We're looking up the first part of the variable. // First we're having a look in our private // context (e. g. information provided by tags, like the forloop) val, in_private := ctx.Private[vr.parts[0].s] if !in_private { // Nothing found? Then have a final lookup in the public context val = ctx.Public[vr.parts[0].s] } current = reflect.ValueOf(val) // Get the initial value } else { // Next parts, resolve it from current // Before resolving the pointer, let's see if we have a method to call // Problem with resolving the pointer is we're changing the receiver is_func := false if part.typ == varTypeIdent { func_value := current.MethodByName(part.s) if func_value.IsValid() { current = func_value is_func = true } } if !is_func { // If current a pointer, resolve it if current.Kind() == reflect.Ptr { current = current.Elem() if !current.IsValid() { // Value is not valid (anymore) return AsValue(nil), nil } } // Look up which part must be called now switch part.typ { case varTypeInt: // Calling an index is only possible for: // * slices/arrays/strings switch current.Kind() { case reflect.String, reflect.Array, reflect.Slice: current = current.Index(part.i) default: return nil, fmt.Errorf("Can't access an index on type %s (variable %s)", current.Kind().String(), vr.String()) } case varTypeIdent: // debugging: // fmt.Printf("now = %s (kind: %s)\n", part.s, current.Kind().String()) // Calling a field or key switch current.Kind() { case reflect.Struct: current = current.FieldByName(part.s) case reflect.Map: current = current.MapIndex(reflect.ValueOf(part.s)) default: return nil, fmt.Errorf("Can't access a field by name on type %s (variable %s)", current.Kind().String(), vr.String()) } default: panic("unimplemented") } } } if !current.IsValid() { // Value is not valid (anymore) return AsValue(nil), nil } // If current is a reflect.ValueOf(pongo2.Value), then unpack it // Happens in function calls (as a return value) or by injecting // into the execution context (e.g. in a for-loop) if current.Type() == reflect.TypeOf(&Value{}) { tmp_value := current.Interface().(*Value) current = tmp_value.val is_safe = tmp_value.safe } // Check whether this is an interface and resolve it where required if current.Kind() == reflect.Interface { current = reflect.ValueOf(current.Interface()) } // Check if the part is a function call if part.is_function_call || current.Kind() == reflect.Func { // Check for callable if current.Kind() != reflect.Func { return nil, fmt.Errorf("'%s' is not a function (it is %s).", vr.String(), current.Kind().String()) } // Check for correct function syntax and types // func(*Value, ...) *Value t := current.Type() // Input arguments if len(part.calling_args) != t.NumIn() && !(len(part.calling_args) >= t.NumIn()-1 && t.IsVariadic()) { return nil, fmt.Errorf("Function input argument count (%d) of '%s' must be equal to the calling argument count (%d).", t.NumIn(), vr.String(), len(part.calling_args)) } // Output arguments if t.NumOut() != 1 { return nil, fmt.Errorf("'%s' must have exactly 1 output argument.", vr.String()) } // Evaluate all parameters parameters := make([]reflect.Value, 0) num_args := t.NumIn() is_variadic := t.IsVariadic() var fn_arg reflect.Type for idx, arg := range part.calling_args { pv, err := arg.Evaluate(ctx) if err != nil { return nil, err } if is_variadic { if idx >= t.NumIn()-1 { fn_arg = t.In(num_args - 1).Elem() } else { fn_arg = t.In(idx) } } else { fn_arg = t.In(idx) } if fn_arg != reflect.TypeOf(new(Value)) { // Function's argument is not a *pongo2.Value, then we have to check whether input argument is of the same type as the function's argument if !is_variadic { if fn_arg != reflect.TypeOf(pv.Interface()) && fn_arg.Kind() != reflect.Interface { return nil, fmt.Errorf("Function input argument %d of '%s' must be of type %s or *pongo2.Value (not %T).", idx, vr.String(), fn_arg.String(), pv.Interface()) } else { // Function's argument has another type, using the interface-value parameters = append(parameters, reflect.ValueOf(pv.Interface())) } } else { if fn_arg != reflect.TypeOf(pv.Interface()) && fn_arg.Kind() != reflect.Interface { return nil, fmt.Errorf("Function variadic input argument of '%s' must be of type %s or *pongo2.Value (not %T).", vr.String(), fn_arg.String(), pv.Interface()) } else { // Function's argument has another type, using the interface-value parameters = append(parameters, reflect.ValueOf(pv.Interface())) } } } else { // Function's argument is a *pongo2.Value parameters = append(parameters, reflect.ValueOf(pv)) } } // Call it and get first return parameter back rv := current.Call(parameters)[0] if rv.Type() != reflect.TypeOf(new(Value)) { current = reflect.ValueOf(rv.Interface()) } else { // Return the function call value current = rv.Interface().(*Value).val is_safe = rv.Interface().(*Value).safe } } } if !current.IsValid() { // Value is not valid (e. g. NIL value) return AsValue(nil), nil } return &Value{val: current, safe: is_safe}, nil } func (vr *variableResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) { value, err := vr.resolve(ctx) if err != nil { return AsValue(nil), ctx.Error(err.Error(), vr.location_token) } return value, nil } func (v *nodeFilteredVariable) FilterApplied(name string) bool { for _, filter := range v.filterChain { if filter.name == name { return true } } return false } func (v *nodeFilteredVariable) Evaluate(ctx *ExecutionContext) (*Value, *Error) { value, err := v.resolver.Evaluate(ctx) if err != nil { return nil, err } for _, filter := range v.filterChain { value, err = filter.Execute(value, ctx) if err != nil { return nil, err } } return value, nil } // IDENT | IDENT.(IDENT|NUMBER)... func (p *Parser) parseVariableOrLiteral() (IEvaluator, *Error) { t := p.Current() if t == nil { return nil, p.Error("Unexpected EOF, expected a number, string, keyword or identifier.", p.last_token) } // Is first part a number or a string, there's nothing to resolve (because there's only to return the value then) switch t.Typ { case TokenNumber: p.Consume() // One exception to the rule that we don't have float64 literals is at the beginning // of an expression (or a variable name). Since we know we started with an integer // which can't obviously be a variable name, we can check whether the first number // is followed by dot (and then a number again). If so we're converting it to a float64. if p.Match(TokenSymbol, ".") != nil { // float64 t2 := p.MatchType(TokenNumber) if t2 == nil { return nil, p.Error("Expected a number after the '.'.", nil) } f, err := strconv.ParseFloat(fmt.Sprintf("%s.%s", t.Val, t2.Val), 64) if err != nil { return nil, p.Error(err.Error(), t) } fr := &floatResolver{ location_token: t, val: f, } return fr, nil } else { i, err := strconv.Atoi(t.Val) if err != nil { return nil, p.Error(err.Error(), t) } nr := &intResolver{ location_token: t, val: i, } return nr, nil } case TokenString: p.Consume() sr := &stringResolver{ location_token: t, val: t.Val, } return sr, nil case TokenKeyword: p.Consume() switch t.Val { case "true": br := &boolResolver{ location_token: t, val: true, } return br, nil case "false": br := &boolResolver{ location_token: t, val: false, } return br, nil default: return nil, p.Error("This keyword is not allowed here.", nil) } } resolver := &variableResolver{ location_token: t, } // First part of a variable MUST be an identifier if t.Typ != TokenIdentifier { return nil, p.Error("Expected either a number, string, keyword or identifier.", t) } resolver.parts = append(resolver.parts, &variablePart{ typ: varTypeIdent, s: t.Val, }) p.Consume() // we consumed the first identifier of the variable name variableLoop: for p.Remaining() > 0 { t = p.Current() if p.Match(TokenSymbol, ".") != nil { // Next variable part (can be either NUMBER or IDENT) t2 := p.Current() if t2 != nil { switch t2.Typ { case TokenIdentifier: resolver.parts = append(resolver.parts, &variablePart{ typ: varTypeIdent, s: t2.Val, }) p.Consume() // consume: IDENT continue variableLoop case TokenNumber: i, err := strconv.Atoi(t2.Val) if err != nil { return nil, p.Error(err.Error(), t2) } resolver.parts = append(resolver.parts, &variablePart{ typ: varTypeInt, i: i, }) p.Consume() // consume: NUMBER continue variableLoop default: return nil, p.Error("This token is not allowed within a variable name.", t2) } } else { // EOF return nil, p.Error("Unexpected EOF, expected either IDENTIFIER or NUMBER after DOT.", p.last_token) } } else if p.Match(TokenSymbol, "(") != nil { // Function call // FunctionName '(' Comma-separated list of expressions ')' part := resolver.parts[len(resolver.parts)-1] part.is_function_call = true argumentLoop: for { if p.Remaining() == 0 { return nil, p.Error("Unexpected EOF, expected function call argument list.", p.last_token) } if p.Peek(TokenSymbol, ")") == nil { // No closing bracket, so we're parsing an expression expr_arg, err := p.ParseExpression() if err != nil { return nil, err } part.calling_args = append(part.calling_args, expr_arg) if p.Match(TokenSymbol, ")") != nil { // If there's a closing bracket after an expression, we will stop parsing the arguments break argumentLoop } else { // If there's NO closing bracket, there MUST be an comma if p.Match(TokenSymbol, ",") == nil { return nil, p.Error("Missing comma or closing bracket after argument.", nil) } } } else { // We got a closing bracket, so stop parsing arguments p.Consume() break argumentLoop } } // We're done parsing the function call, next variable part continue variableLoop } // No dot or function call? Then we're done with the variable parsing break } return resolver, nil } func (p *Parser) parseVariableOrLiteralWithFilter() (*nodeFilteredVariable, *Error) { v := &nodeFilteredVariable{ location_token: p.Current(), } // Parse the variable name resolver, err := p.parseVariableOrLiteral() if err != nil { return nil, err } v.resolver = resolver // Parse all the filters filterLoop: for p.Match(TokenSymbol, "|") != nil { // Parse one single filter filter, err := p.parseFilter() if err != nil { return nil, err } // Check sandbox filter restriction if _, is_banned := p.template.set.bannedFilters[filter.name]; is_banned { return nil, p.Error(fmt.Sprintf("Usage of filter '%s' is not allowed (sandbox restriction active).", filter.name), nil) } v.filterChain = append(v.filterChain, filter) continue filterLoop return nil, p.Error("This token is not allowed within a variable.", nil) } return v, nil } func (p *Parser) parseVariableElement() (INode, *Error) { node := &nodeVariable{ location_token: p.Current(), } p.Consume() // consume '{{' expr, err := p.ParseExpression() if err != nil { return nil, err } node.expr = expr if p.Match(TokenSymbol, "}}") == nil { return nil, p.Error("'}}' expected", nil) } return node, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/value.go����������������������������������������������0000644�0610621�0607500�00000032515�13172163432�023422� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "fmt" "reflect" "strconv" "strings" ) type Value struct { val reflect.Value safe bool // used to indicate whether a Value needs explicit escaping in the template } // Converts any given value to a pongo2.Value // Usually being used within own functions passed to a template // through a Context or within filter functions. // // Example: // AsValue("my string") func AsValue(i interface{}) *Value { return &Value{ val: reflect.ValueOf(i), } } // Like AsValue, but does not apply the 'escape' filter. func AsSafeValue(i interface{}) *Value { return &Value{ val: reflect.ValueOf(i), safe: true, } } func (v *Value) getResolvedValue() reflect.Value { if v.val.IsValid() && v.val.Kind() == reflect.Ptr { return v.val.Elem() } return v.val } // Checks whether the underlying value is a string func (v *Value) IsString() bool { return v.getResolvedValue().Kind() == reflect.String } // Checks whether the underlying value is a bool func (v *Value) IsBool() bool { return v.getResolvedValue().Kind() == reflect.Bool } // Checks whether the underlying value is a float func (v *Value) IsFloat() bool { return v.getResolvedValue().Kind() == reflect.Float32 || v.getResolvedValue().Kind() == reflect.Float64 } // Checks whether the underlying value is an integer func (v *Value) IsInteger() bool { return v.getResolvedValue().Kind() == reflect.Int || v.getResolvedValue().Kind() == reflect.Int8 || v.getResolvedValue().Kind() == reflect.Int16 || v.getResolvedValue().Kind() == reflect.Int32 || v.getResolvedValue().Kind() == reflect.Int64 || v.getResolvedValue().Kind() == reflect.Uint || v.getResolvedValue().Kind() == reflect.Uint8 || v.getResolvedValue().Kind() == reflect.Uint16 || v.getResolvedValue().Kind() == reflect.Uint32 || v.getResolvedValue().Kind() == reflect.Uint64 } // Checks whether the underlying value is either an integer // or a float. func (v *Value) IsNumber() bool { return v.IsInteger() || v.IsFloat() } // Checks whether the underlying value is NIL func (v *Value) IsNil() bool { //fmt.Printf("%+v\n", v.getResolvedValue().Type().String()) return !v.getResolvedValue().IsValid() } // Returns a string for the underlying value. If this value is not // of type string, pongo2 tries to convert it. Currently the following // types for underlying values are supported: // // 1. string // 2. int/uint (any size) // 3. float (any precision) // 4. bool // 5. time.Time // 6. String() will be called on the underlying value if provided // // NIL values will lead to an empty string. Unsupported types are leading // to their respective type name. func (v *Value) String() string { if v.IsNil() { return "" } switch v.getResolvedValue().Kind() { case reflect.String: return v.getResolvedValue().String() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return strconv.FormatInt(v.getResolvedValue().Int(), 10) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return strconv.FormatUint(v.getResolvedValue().Uint(), 10) case reflect.Float32, reflect.Float64: return fmt.Sprintf("%f", v.getResolvedValue().Float()) case reflect.Bool: if v.Bool() { return "True" } else { return "False" } case reflect.Struct: if t, ok := v.Interface().(fmt.Stringer); ok { return t.String() } } logf("Value.String() not implemented for type: %s\n", v.getResolvedValue().Kind().String()) return v.getResolvedValue().String() } // Returns the underlying value as an integer (converts the underlying // value, if necessary). If it's not possible to convert the underlying value, // it will return 0. func (v *Value) Integer() int { switch v.getResolvedValue().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return int(v.getResolvedValue().Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return int(v.getResolvedValue().Uint()) case reflect.Float32, reflect.Float64: return int(v.getResolvedValue().Float()) case reflect.String: // Try to convert from string to int (base 10) f, err := strconv.ParseFloat(v.getResolvedValue().String(), 64) if err != nil { return 0 } return int(f) default: logf("Value.Integer() not available for type: %s\n", v.getResolvedValue().Kind().String()) return 0 } } // Returns the underlying value as a float (converts the underlying // value, if necessary). If it's not possible to convert the underlying value, // it will return 0.0. func (v *Value) Float() float64 { switch v.getResolvedValue().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return float64(v.getResolvedValue().Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return float64(v.getResolvedValue().Uint()) case reflect.Float32, reflect.Float64: return v.getResolvedValue().Float() case reflect.String: // Try to convert from string to float64 (base 10) f, err := strconv.ParseFloat(v.getResolvedValue().String(), 64) if err != nil { return 0.0 } return f default: logf("Value.Float() not available for type: %s\n", v.getResolvedValue().Kind().String()) return 0.0 } } // Returns the underlying value as bool. If the value is not bool, false // will always be returned. If you're looking for true/false-evaluation of the // underlying value, have a look on the IsTrue()-function. func (v *Value) Bool() bool { switch v.getResolvedValue().Kind() { case reflect.Bool: return v.getResolvedValue().Bool() default: logf("Value.Bool() not available for type: %s\n", v.getResolvedValue().Kind().String()) return false } } // Tries to evaluate the underlying value the Pythonic-way: // // Returns TRUE in one the following cases: // // * int != 0 // * uint != 0 // * float != 0.0 // * len(array/chan/map/slice/string) > 0 // * bool == true // * underlying value is a struct // // Otherwise returns always FALSE. func (v *Value) IsTrue() bool { switch v.getResolvedValue().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.getResolvedValue().Int() != 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.getResolvedValue().Uint() != 0 case reflect.Float32, reflect.Float64: return v.getResolvedValue().Float() != 0 case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: return v.getResolvedValue().Len() > 0 case reflect.Bool: return v.getResolvedValue().Bool() case reflect.Struct: return true // struct instance is always true default: logf("Value.IsTrue() not available for type: %s\n", v.getResolvedValue().Kind().String()) return false } } // Tries to negate the underlying value. It's mainly used for // the NOT-operator and in conjunction with a call to // return_value.IsTrue() afterwards. // // Example: // AsValue(1).Negate().IsTrue() == false func (v *Value) Negate() *Value { switch v.getResolvedValue().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: if v.Integer() != 0 { return AsValue(0) } else { return AsValue(1) } case reflect.Float32, reflect.Float64: if v.Float() != 0.0 { return AsValue(float64(0.0)) } else { return AsValue(float64(1.1)) } case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: return AsValue(v.getResolvedValue().Len() == 0) case reflect.Bool: return AsValue(!v.getResolvedValue().Bool()) default: logf("Value.IsTrue() not available for type: %s\n", v.getResolvedValue().Kind().String()) return AsValue(true) } } // Returns the length for an array, chan, map, slice or string. // Otherwise it will return 0. func (v *Value) Len() int { switch v.getResolvedValue().Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: return v.getResolvedValue().Len() case reflect.String: runes := []rune(v.getResolvedValue().String()) return len(runes) default: logf("Value.Len() not available for type: %s\n", v.getResolvedValue().Kind().String()) return 0 } } // Slices an array, slice or string. Otherwise it will // return an empty []int. func (v *Value) Slice(i, j int) *Value { switch v.getResolvedValue().Kind() { case reflect.Array, reflect.Slice: return AsValue(v.getResolvedValue().Slice(i, j).Interface()) case reflect.String: runes := []rune(v.getResolvedValue().String()) return AsValue(string(runes[i:j])) default: logf("Value.Slice() not available for type: %s\n", v.getResolvedValue().Kind().String()) return AsValue([]int{}) } } // Get the i-th item of an array, slice or string. Otherwise // it will return NIL. func (v *Value) Index(i int) *Value { switch v.getResolvedValue().Kind() { case reflect.Array, reflect.Slice: if i >= v.Len() { return AsValue(nil) } return AsValue(v.getResolvedValue().Index(i).Interface()) case reflect.String: //return AsValue(v.getResolvedValue().Slice(i, i+1).Interface()) s := v.getResolvedValue().String() runes := []rune(s) if i < len(runes) { return AsValue(string(runes[i])) } return AsValue("") default: logf("Value.Slice() not available for type: %s\n", v.getResolvedValue().Kind().String()) return AsValue([]int{}) } } // Checks whether the underlying value (which must be of type struct, map, // string, array or slice) contains of another Value (e. g. used to check // whether a struct contains of a specific field or a map contains a specific key). // // Example: // AsValue("Hello, World!").Contains(AsValue("World")) == true func (v *Value) Contains(other *Value) bool { switch v.getResolvedValue().Kind() { case reflect.Struct: field_value := v.getResolvedValue().FieldByName(other.String()) return field_value.IsValid() case reflect.Map: var map_value reflect.Value switch other.Interface().(type) { case int: map_value = v.getResolvedValue().MapIndex(other.getResolvedValue()) case string: map_value = v.getResolvedValue().MapIndex(other.getResolvedValue()) default: logf("Value.Contains() does not support lookup type '%s'\n", other.getResolvedValue().Kind().String()) return false } return map_value.IsValid() case reflect.String: return strings.Contains(v.getResolvedValue().String(), other.String()) // TODO: reflect.Array, reflect.Slice default: logf("Value.Contains() not available for type: %s\n", v.getResolvedValue().Kind().String()) return false } } // Checks whether the underlying value is of type array, slice or string. // You normally would use CanSlice() before using the Slice() operation. func (v *Value) CanSlice() bool { switch v.getResolvedValue().Kind() { case reflect.Array, reflect.Slice, reflect.String: return true } return false } // Iterates over a map, array, slice or a string. It calls the // function's first argument for every value with the following arguments: // // idx current 0-index // count total amount of items // key *Value for the key or item // value *Value (only for maps, the respective value for a specific key) // // If the underlying value has no items or is not one of the types above, // the empty function (function's second argument) will be called. func (v *Value) Iterate(fn func(idx, count int, key, value *Value) bool, empty func()) { v.IterateOrder(fn, empty, false) } // Like Value.Iterate, but can iterate through an array/slice/string in reverse. Does // not affect the iteration through a map because maps don't have any particular order. func (v *Value) IterateOrder(fn func(idx, count int, key, value *Value) bool, empty func(), reverse bool) { switch v.getResolvedValue().Kind() { case reflect.Map: // Reverse not needed for maps, since they are not ordered keys := v.getResolvedValue().MapKeys() keyLen := len(keys) for idx, key := range keys { value := v.getResolvedValue().MapIndex(key) if !fn(idx, keyLen, &Value{val: key}, &Value{val: value}) { return } } if keyLen == 0 { empty() } return // done case reflect.Array, reflect.Slice: itemCount := v.getResolvedValue().Len() if itemCount > 0 { if reverse { for i := itemCount - 1; i >= 0; i-- { if !fn(i, itemCount, &Value{val: v.getResolvedValue().Index(i)}, nil) { return } } } else { for i := 0; i < itemCount; i++ { if !fn(i, itemCount, &Value{val: v.getResolvedValue().Index(i)}, nil) { return } } } } else { empty() } return // done case reflect.String: // TODO: Not utf8-compatible (utf8-decoding neccessary) charCount := v.getResolvedValue().Len() if charCount > 0 { if reverse { for i := charCount - 1; i >= 0; i-- { if !fn(i, charCount, &Value{val: v.getResolvedValue().Slice(i, i+1)}, nil) { return } } } else { for i := 0; i < charCount; i++ { if !fn(i, charCount, &Value{val: v.getResolvedValue().Slice(i, i+1)}, nil) { return } } } } else { empty() } return // done default: logf("Value.Iterate() not available for type: %s\n", v.getResolvedValue().Kind().String()) } empty() } // Gives you access to the underlying value. func (v *Value) Interface() interface{} { if v.val.IsValid() { return v.val.Interface() } return nil } // Checks whether two values are containing the same value or object. func (v *Value) EqualValueTo(other *Value) bool { return v.Interface() == other.Interface() } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/���������������������������������������0000755�0610621�0607500�00000000000�13172163432�025006� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/with.tpl.out���������������������������0000644�0610621�0607500�00000000733�13172163432�027313� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������new style Start 'I'm john doe' End Start 'I'm john doe11' End Start 'I'm guest7' End Start 'Hi number 10! Will not be overridden inside the block. I'm john doe, 50 years old.I have 10 children.' End old style - still supported by Django Start 'I'm john doe' End Start 'I'm john doe11' End Start 'I'm guest7' End Start 'Hi number 10! Will not be overridden inside the block. I'm john doe, 50 years old.I have 10 children.' End more with tests <pongo2.user Value> user1 user3�������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/with.tpl�������������������������������0000644�0610621�0607500�00000001731�13172163432�026504� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������new style Start '{% with what_am_i=simple.name %}I'm {{what_am_i}}{% endwith %}' End Start '{% with what_am_i=simple.name %}I'm {{what_am_i}}11{% endwith %}' End Start '{% with number=7 what_am_i="guest" %}I'm {{what_am_i}}{{number}}{% endwith %}' End Start '{% include "with.helper" with what_am_i=simple.name number=10 %}' End old style - still supported by Django Start '{% with simple.name as what_am_i %}I'm {{what_am_i}}{% endwith %}' End Start '{% with simple.name as what_am_i %}I'm {{what_am_i}}11{% endwith %}' End Start '{% with 7 as number "guest" as what_am_i %}I'm {{what_am_i}}{{number}}{% endwith %}' End Start '{% include "with.helper" with what_am_i=simple.name number=10 %}' End more with tests {% with first_comment=complex.comments|first %}{{ first_comment.Author }}{% endwith %} {% with first_comment=complex.comments|first %}{{ first_comment.Author.Name }}{% endwith %} {% with first_comment=complex.comments|last %}{{ first_comment.Author.Name }}{% endwith %}���������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/with.helper����������������������������0000644�0610621�0607500�00000000247�13172163432�027165� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Hi number {{number}}! Will not be overridden inside the block. {% with number=50 %}I'm {{ what_am_i }}, {{ number }} years old{% endwith %}.I have {{number}} children.���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/widthratio.tpl.out���������������������0000644�0610621�0607500�00000000007�13172163432�030510� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� 88 88�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/widthratio.tpl�������������������������0000644�0610621�0607500�00000000303�13172163432�027701� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{# Tip: In pongo2 you can easily use arithmetic expressions like value/100.0, but widthratio is supported as well #} {% widthratio 175 200 100 %} {% widthratio 175 200 100 as width %} {{ width }}�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/verbatim.tpl.out�����������������������0000644�0610621�0607500�00000000110�13172163432�030136� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.42 <style>@media{#foobar... {{ test }} {% test %} 42. .42{{ test }}42.��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/verbatim.tpl���������������������������0000644�0610621�0607500�00000000312�13172163432�027334� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.{{ simple.number }}{% verbatim %} <style>@media{#foobar... {{ test }} {% test %} {% endverbatim %}{{ simple.number }}. .{{ simple.number }}{% verbatim %}{{ test }}{% endverbatim %}{{ simple.number }}.����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/variables.tpl.out����������������������0000644�0610621�0607500�00000000067�13172163432�030310� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������1 -5 hallo True False 8 string False True 8 8 8.000000�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/variables.tpl��������������������������0000644�0610621�0607500�00000000334�13172163432�027477� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ 1 }} {{ -5 }} {{ "hallo" }} {{ true }} {{ false }} {{ simple.uint }} {{ simple.nil }} {{ simple.str }} {{ simple.bool_false }} {{ simple.bool_true }} {{ simple.uint }} {{ simple.uint|integer }} {{ simple.uint|float }}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/templatetag.tpl.out��������������������0000644�0610621�0607500�00000000043�13172163432�030641� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% url 'entry_list' %} {{}} {} {##}���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/templatetag.tpl������������������������0000644�0610621�0607500�00000000373�13172163432�030041� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% templatetag openblock %} url 'entry_list' {% templatetag closeblock %} {% templatetag openvariable %}{% templatetag closevariable %} {% templatetag openbrace %}{% templatetag closebrace %} {% templatetag opencomment %}{% templatetag closecomment %}���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/template_sets.tpl.out������������������0000644�0610621�0607500�00000000035�13172163432�031204� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Globals this is a global text���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/template_sets.tpl����������������������0000644�0610621�0607500�00000000047�13172163432�030401� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Globals {{ this_is_a_global_variable }}�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/tags-compilation.err.out���������������0000644�0610621�0607500�00000000534�13172163432�031602� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.*Unexpected EOF, expected tag elif or else or endif. .*If-condition is malformed. .*Block named 'test' already defined.* .*Name for 'endblock' must equal to 'block'\-tag's name \('test' != 'test2'\). .*Name for 'endblock' must equal to 'block'-tag's name \('test2' != 'xy'\). .*Either no or only one argument \(identifier\) allowed for 'endblock'.��������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/tags-compilation.err�������������������0000644�0610621�0607500�00000000474�13172163432�030777� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% if true %} {% if (1) . %}{% endif %} {% block test %}{% block test %}{% endblock %}{% endblock %} {% block test %}{% block test %}{% endblock %}{% endblock test2 %} {% block test %}{% block test2 %}{% endblock xy %}{% endblock test %} {% block test %}{% block test2 %}{% endblock test2 test3 %}{% endblock test %}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/tag_filter.tpl.out���������������������0000644�0610621�0607500�00000000163�13172163432�030455� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������this is a nice test; let's see whether it works. foobar. &lt;script&gt;alert(&quot;uh oh&quot;);&lt;/script&gt; 10�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/tag_filter.tpl�������������������������0000644�0610621�0607500�00000000361�13172163432�027647� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% filter lower %}This is a nice test; let's see whether it works. Foobar. {{ simple.xss }}{% endfilter %} {% filter truncatechars:10|lower|length %}This is a nice test; let's see whether it works. Foobar. {{ simple.number }}{% endfilter %}�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/ssi.tpl.out����������������������������0000644�0610621�0607500�00000000043�13172163432�027130� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ number }} {{ "hello" }} 11 hello���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/ssi.tpl��������������������������������0000644�0610621�0607500�00000000064�13172163432�026325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% ssi "ssi.helper" %} {% ssi "ssi.helper" parsed %}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/ssi.helper�����������������������������0000644�0610621�0607500�00000000032�13172163432�027000� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ number }} {{ "hello" }}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/spaceless.tpl.out����������������������0000644�0610621�0607500�00000000307�13172163432�030317� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� <div id="content"><p> This is a test! Mail me at <a href="mailto:mail@example.tld"> mail@example.tld </a></p><p> Yep! </p></div> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/spaceless.tpl��������������������������0000644�0610621�0607500�00000000372�13172163432�027513� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% spaceless %} <div id="content"> <p> This is a test! Mail me at <a href="mailto:mail@example.tld"> mail@example.tld </a> </p> <p> Yep! </p> </div> {% endspaceless %}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/set.tpl.out����������������������������0000644�0610621�0607500�00000000056�13172163432�027131� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������hello world world Hello 99 3.140000 good world����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/set.tpl��������������������������������0000644�0610621�0607500�00000000342�13172163432�026321� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% set new_var = "hello" %}{{ new_var }} {% block content %}{% set new_var = "world" %}{{ new_var }}{% endblock %} {{ new_var }}{% for item in simple.misc_list %} {% set new_var = item %}{{ new_var }}{% endfor %} {{ new_var }}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/sandbox.tpl.out������������������������0000644�0610621�0607500�00000000035�13172163432�027771� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������hello hello Hello from pongo2���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/sandbox.tpl����������������������������0000644�0610621�0607500�00000000110�13172163432�027155� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ "hello"|unbanned_filter }} {% unbanned_tag %} {% include temp_file %}��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/sandbox-compilation.err.out������������0000644�0610621�0607500�00000000411�13172163432�032274� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.*Usage of filter 'banned_filter' is not allowed \(sandbox restriction active\). .*Usage of tag 'banned_tag' is not allowed \(sandbox restriction active\). \[Error \(where: fromfile\) | Line 1 Col 12 near '../../test_not_existent'\] open : no such file or directory�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/sandbox-compilation.err����������������0000644�0610621�0607500�00000000124�13172163432�031467� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ "hello"|banned_filter }} {% banned_tag %} {% include "../../test_not_existent" %}��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/pongo2ctx.tpl.out����������������������0000644�0610621�0607500�00000000002�13172163432�030250� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������v3������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/pongo2ctx.tpl��������������������������0000644�0610621�0607500�00000000024�13172163432�027446� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ pongo2.version }}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/now.tpl.out����������������������������0000644�0610621�0607500�00000000042�13172163432�027134� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� Wed Feb 5 18:31:45 +0000 UTC 2014����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/now.tpl��������������������������������0000644�0610621�0607500�00000000251�13172163432�026330� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{# The 'fake' argument exists to have tests for the now-tag; it will set the time to a specific date instead of now #} {% now "Mon Jan 2 15:04:05 -0700 MST 2006" fake %}�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/macro2.helper��������������������������0000644�0610621�0607500�00000000272�13172163432�027373� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% macro greeter_macro() export %} {% import "macro.helper" imported_macro, imported_macro_void %} One greeting: {{ imported_macro("Dirk") }} - {{ imported_macro_void() }} {% endmacro %}��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/macro.tpl.out��������������������������0000644�0610621�0607500�00000001310�13172163432�027431� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Begin Greetings to from john doe. Howdy, anonymous guest! Greetings to 10 from john doe. Howdy, anonymous guest! Greetings to john from john doe. Howdy, anonymous guest! Greetings to john from michelle. Howdy, anonymous guest! Greetings to john from michelle. Howdy, johann! [Error (where: execution) in template_tests/macro.tpl | Line 2 Col 4 near 'macro'] Macro 'greetings' called with too many arguments (4 instead of 3). map[0] = Hello map[1] = 99 map[2] = 3.140000 map[3] = good issue #39 (deactivate auto-escape of macros) <p>Hello Max.</p> Importing macros <p>Hey User1!</p> <p>Hey User2!</p> <p>Hey Max!</p> Chaining macros One greeting: <p>Hey Dirk!</p> - <p>Hello mate!</p> End������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/macro.tpl������������������������������0000644�0610621�0607500�00000001730�13172163432�026631� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Begin {% macro greetings(to, from=simple.name, name2="guest") %} Greetings to {{ to }} from {{ from }}. Howdy, {% if name2 == "guest" %}anonymous guest{% else %}{{ name2 }}{% endif %}! {% endmacro %} {{ greetings() }} {{ greetings(10) }} {{ greetings("john") }} {{ greetings("john", "michelle") }} {{ greetings("john", "michelle", "johann") }} {{ greetings("john", "michelle", "johann", "foobar") }} {% macro test2(loop, value) %}map[{{ loop.Counter0 }}] = {{ value }}{% endmacro %} {% for item in simple.misc_list %} {{ test2(forloop, item) }}{% endfor %} issue #39 (deactivate auto-escape of macros) {% macro html_test(name) %} <p>Hello {{ name }}.</p> {% endmacro %} {{ html_test("Max") }} Importing macros {% import "macro.helper" imported_macro, imported_macro as renamed_macro, imported_macro as html_test %} {{ imported_macro("User1") }} {{ renamed_macro("User2") }} {{ html_test("Max") }} Chaining macros{% import "macro2.helper" greeter_macro %} {{ greeter_macro() }} End����������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/macro.helper���������������������������0000644�0610621�0607500�00000000222�13172163432�027304� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% macro imported_macro(foo) export %}<p>Hey {{ foo }}!</p>{% endmacro %} {% macro imported_macro_void() export %}<p>Hello mate!</p>{% endmacro %}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/macro-execution.err.out����������������0000644�0610621�0607500�00000000070�13172163432�031425� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.*Context key name 'number' clashes with macro 'number'.������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/macro-execution.err��������������������0000644�0610621�0607500�00000000106�13172163432�030617� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% macro number() export %}No number here.{% endmacro %}{{ number() }}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/macro-compilation.err.out��������������0000644�0610621�0607500�00000000073�13172163432�031743� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.*Another macro with name 'test_override' already exported.���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/macro-compilation.err������������������0000644�0610621�0607500�00000000140�13172163432�031130� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% macro test_override() export %}{% endmacro %}{% macro test_override() export %}{% endmacro %}��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/lorem.tpl.out��������������������������0000644�0610621�0607500�00000015714�13172163432�027463� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������----- Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ----- Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. ----- <p>Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> <p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> ----- Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum -----����������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/lorem.tpl������������������������������0000644�0610621�0607500�00000000132�13172163432�026641� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������----- {% lorem %} ----- {% lorem 10 %} ----- {% lorem 3 p %} ----- {% lorem 100 w %} -----��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/issues.tpl.out�������������������������0000644�0610621�0607500�00000000000�13172163432�027636� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/issues.tpl�����������������������������0000644�0610621�0607500�00000000000�13172163432�027030� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/inheritance/���������������������������0000755�0610621�0607500�00000000000�13172163432�027277� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/inheritance/inheritance2/��������������0000755�0610621�0607500�00000000000�13172163432�031652� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/inheritance/inheritance2/skeleton.tpl��0000644�0610621�0607500�00000000064�13172163432�034217� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Start#{% block body %}Default body{% endblock %}#End����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/inheritance/cycle_include.tpl����������0000644�0610621�0607500�00000000033�13172163432�032616� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Included '{{ cycleitem }}'.�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/inheritance/base2.tpl������������������0000644�0610621�0607500�00000000041�13172163432�031007� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% include "doesnotexist.tpl" %} �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/inheritance/base.tpl�������������������0000644�0610621�0607500�00000000214�13172163432�030727� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% extends "inheritance2/skeleton.tpl" %} {% block body %}This is base's body{% block content %}Default content{% endblock %}{% endblock %}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/includes.tpl.out�����������������������0000644�0610621�0607500�00000000135�13172163432�030142� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Start 'I'm 11' End Start 'I'm john doe' End Start 'I'm john doe11' End Start 'I'm guest7' End�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/includes.tpl���������������������������0000644�0610621�0607500�00000000423�13172163432�027334� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Start '{% include "includes.helper" %}' End Start '{% include "includes.helper" with what_am_i=simple.name only %}' End Start '{% include "includes.helper" with what_am_i=simple.name %}' End Start '{% include simple.included_file|lower with number=7 what_am_i="guest" %}' End���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/includes.helper������������������������0000644�0610621�0607500�00000000037�13172163432�030015� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������I'm {{ what_am_i }}{{ number }}�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/ifchanged.tpl.out����������������������0000644�0610621�0607500�00000000535�13172163432�030250� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� New comment from another user user1 Validated changed to True Comment's author name or date changed Validated value not changed Comment's author name or date changed New comment from another user user3 Validated changed to False Comment's author name or date changed �������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/ifchanged.tpl��������������������������0000644�0610621�0607500�00000000657�13172163432�027447� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% for comment in complex.comments2 %} {% ifchanged %}New comment from another user {{ comment.Author.Name }}{% endifchanged %} {% ifchanged comment.Author.Validated %} Validated changed to {{ comment.Author.Validated }} {% else %} Validated value not changed {% endifchanged %} {% ifchanged comment.Author.Name comment.Date %}Comment's author name or date changed{% endifchanged %} {% endfor %}���������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/if.tpl.out�����������������������������0000644�0610621�0607500�00000000263�13172163432�026734� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������true simple != nil uint != 0 float != 0.0 !simple !simple.uint !simple.float text field in complex.post 5 in simple.intmap !0.0 !0 42 yes yes true simple.float Elseif with no else���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/if.tpl���������������������������������0000644�0610621�0607500�00000002043�13172163432�026124� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% if nothing %}false{% else %}true{% endif %} {% if simple %}simple != nil{% endif %} {% if simple.uint %}uint != 0{% endif %} {% if simple.float %}float != 0.0{% endif %} {% if !simple %}false{% else %}!simple{% endif %} {% if !simple.uint %}false{% else %}!simple.uint{% endif %} {% if !simple.float %}false{% else %}!simple.float{% endif %} {% if "Text" in complex.post %}text field in complex.post{% endif %} {% if 5 in simple.intmap %}5 in simple.intmap{% endif %} {% if !0.0 %}!0.0{% endif %} {% if !0 %}!0{% endif %} {% if simple.number == 43 %}no{% else %}42{% endif %} {% if simple.number < 42 %}false{% elif simple.number > 42 %}no{% elif simple.number >= 42 %}yes{% else %}no{% endif %} {% if simple.number < 42 %}false{% elif simple.number > 42 %}no{% elif simple.number != 42 %}no{% else %}yes{% endif %} {% if 0 %}!0{% elif nothing %}nothing{% else %}true{% endif %} {% if 0 %}!0{% elif simple.float %}simple.float{% else %}false{% endif %} {% if 0 %}!0{% elif !simple.float %}false{% elif "Text" in complex.post%}Elseif with no else{% endif %}���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/function_calls_wrapper.tpl.out���������0000644�0610621�0607500�00000000070�13172163432�033075� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������79 79 hello hello, john doe 5 + 42 is 49 0 1 205 0 2 108������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/function_calls_wrapper.tpl�������������0000644�0610621�0607500�00000001046�13172163432�032273� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ simple.func_add(simple.func_add(5, 15), simple.number) + 17 }} {{ simple.func_add_iface(simple.func_add_iface(5, 15), simple.number) + 17 }} {{ simple.func_variadic("hello") }} {{ simple.func_variadic("hello, %s", simple.name) }} {{ simple.func_variadic("%d + %d %s %d", 5, simple.number, "is", 49) }} {{ simple.func_variadic_sum_int() }} {{ simple.func_variadic_sum_int(1) }} {{ simple.func_variadic_sum_int(1, 19, 185) }} {{ simple.func_variadic_sum_int2() }} {{ simple.func_variadic_sum_int2(2) }} {{ simple.func_variadic_sum_int2(1, 7, 100) }}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/for.tpl.out����������������������������0000644�0610621�0607500�00000001261�13172163432�027123� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������[1 0 True False 3 2] user1 0.0:" 0.1:p 0.2:o 0.3:n 0.4:g 0.5:o 0.6:2 0.7: 0.8:i 0.9:s 0.10: 0.11:n 0.12:i 0.13:c 0.14:e 0.15:! 0.16:" [2 1 False False 2 1] user2 1.0:c 1.1:o 1.2:m 1.3:m 1.4:e 1.5:n 1.6:t 1.7:2 1.8: 1.9:w 1.10:i 1.11:t 1.12:h 1.13: 1.14:< 1.15:s 1.16:c 1.17:r 1.18:i 1.19:p 1.20:t 1.21:> 1.22:u 1.23:n 1.24:s 1.25:a 1.26:f 1.27:e 1.28:< 1.29:/ 1.30:s 1.31:c 1.32:r 1.33:i 1.34:p 1.35:t 1.36:> 1.37: 1.38:t 1.39:a 1.40:g 1.41:s 1.42: 1.43:i 1.44:n 1.45: 1.46:i 1.47:t [3 2 False True 1 0] user3 2.0:< 2.1:b 2.2:> 2.3:h 2.4:e 2.5:l 2.6:l 2.7:o 2.8:! 2.9:< 2.10:/ 2.11:b 2.12:> 2.13: 2.14:t 2.15:h 2.16:e 2.17:r 2.18:e reversed '55 34 21 13 8 5 3 2 1 1 '�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/for.tpl��������������������������������0000644�0610621�0607500�00000000660�13172163432�026317� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% for comment in complex.comments %}[{{ forloop.Counter }} {{ forloop.Counter0 }} {{ forloop.First }} {{ forloop.Last }} {{ forloop.Revcounter }} {{ forloop.Revcounter0 }}] {{ comment.Author.Name }} {# nested loop #} {% for char in comment.Text %}{{forloop.Parentloop.Counter0}}.{{forloop.Counter0}}:{{ char|safe }} {% endfor %} {% endfor %} reversed '{% for item in simple.multiple_item_list reversed %}{{ item }} {% endfor %}'��������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/firstof.tpl.out������������������������0000644�0610621�0607500�00000000141�13172163432�030005� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������42 &lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt; <script>alert('xss');</script> 8 test test�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/firstof.tpl����������������������������0000644�0610621�0607500�00000000442�13172163432�027203� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% firstof doesnotexist 42 %} {% firstof doesnotexist "<script>alert('xss');</script>" %} {% firstof doesnotexist "<script>alert('xss');</script>"|safe %} {% firstof doesnotexist simple.uint 42 %} {% firstof doesnotexist "test" simple.number 42 %} {% firstof %} {% firstof "test" "test2" %}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/filters.tpl.out������������������������0000644�0610621�0607500�00000024334�13172163432�030013� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������add 7 47 5 5test hello john doe hello john doe addslashes plain text This is \\a Test. \"Yep\". \'Yep\'. capfirst H Hello there! 你好世界 cut 1 Helloworld default n/a 42 42 5 default_if_none n/a n/a get_digit 1234567890 1234567890 9 7 1 1234567890 safe &lt;script&gt; <script> escape &lt;script&gt; title H Hello There! Hello There! Hello There! 你好世界 truncatechars Joel i... Joel is a ... Joel is a slug 你 你好 divisibleby True True True False False True striptags Hello! removetags <strong>Hello!</strong> yesno yes no maybe maybe ja nein maybe pluralize customers customer customers cherries cherry cherries walruses walrus walruses random 5 h 99 first T <pongo2.comment Value> 你 last t <pongo2.comment Value> 界 urlencode http%3A%2F%2Fwww.example.org%2Ffoo%3Fa%3Db%26c%3Dd linebreaksbr this is a text&lt;br /&gt;with a new line in it hallo length_is True False True False False True False False integer 0 0 5 5 5 6 -100 float 0.000000 0.000000 5.500000 5.000000 5.000000 -100.000000 5.5 is 5.500000 5.5 is not 5.500001 floatformat 34.2 34 34.3 34.2 34 34.3 34.232 34.000 34.260 34 34 40 34.232 34 34.260 join Hello, 99, 3.140000, good stringformat 3.14 Test: 8 Chinese: 你好世界 make_list j, o, h, n, , d, o, e john doe center 'test' ' test ' ' test ' 20 ' test2 ' ' test2 ' 20 ' 你好世界 ' ljust 'test' 'test ' 20 '你好世界 ' rjust 'test' ' test' 20 ' 你好世界' wordcount 0 25 wordwrap Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation iriencode ?foo=123&amp;bar=yes linebreaks <p>this is a text<br />with a new line in it</p> <p>This is a simple text.</p><p>This too, as a paragraph.<br />Right?</p><p>Yep!</p> <p>john doe</p> linenumbers 1. Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 2. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. 3. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. 4. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. 5. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. 6. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat. 7. Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. 8. Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 9. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. 10. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. phone2numeric 999-766462 truncatewords Lorem ipsum dolor sit amet, consectetur adipisici elit, sed ... 10 你好世界 你好世界 urlize <a href="http://www.florian-schlachter.de" rel="nofollow">http://www.florian-schlachter.de</a> <a href="http://www.florian-schlachter.de" rel="nofollow">www.florian-schlachter.de</a> <a href="http://florian-schlachter.de" rel="nofollow">florian-schlachter.de</a> Please mail me at <a href="mailto:demo@example.com">demo@example.com</a> or visit mit on: - lorem ipsum <a href="http://github.com/flosch/pongo2" rel="nofollow">github.com/flosch/pongo2</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de" rel="nofollow">http://www.florian-schlachter.de</a> lorem ipsum - lorem ipsum <a href="https://www.florian-schlachter.de" rel="nofollow">https://www.florian-schlachter.de</a> lorem ipsum - lorem ipsum <a href="https://www.florian-schlachter.de" rel="nofollow">https://www.florian-schlachter.de</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de" rel="nofollow">www.florian-schlachter.de</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de/test=%22test%22" rel="nofollow">www.florian-schlachter.de/test=&quot;test&quot;</a> lorem ipsum -- Please mail me at <a href="mailto:demo@example.com">demo@example.com</a> or visit mit on: - lorem ipsum <a href="http://github.com/flosch/pongo2" rel="nofollow">github.com/flosch/pongo2</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de" rel="nofollow">http://www.florian-schlachter.de</a> lorem ipsum - lorem ipsum <a href="https://www.florian-schlachter.de" rel="nofollow">https://www.florian-schlachter.de</a> lorem ipsum - lorem ipsum <a href="https://www.florian-schlachter.de" rel="nofollow">https://www.florian-schlachter.de</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de" rel="nofollow">www.florian-schlachter.de</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de/test=%22test%22" rel="nofollow">www.florian-schlachter.de/test="test"</a> lorem ipsum urlizetrunc Please mail me at <a href="mailto:demo@example.com">demo@example...</a> or visit mit on: - lorem ipsum <a href="http://github.com/flosch/pongo2" rel="nofollow">github.com/f...</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de" rel="nofollow">http://www.f...</a> lorem ipsum - lorem ipsum <a href="https://www.florian-schlachter.de" rel="nofollow">https://www....</a> lorem ipsum - lorem ipsum <a href="https://www.florian-schlachter.de" rel="nofollow">https://www....</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de" rel="nofollow">www.florian-...</a> lorem ipsum - lorem ipsum <a href="http://www.florian-schlachter.de/test=%22test%22" rel="nofollow">www.florian-...</a> lorem ipsum escapejs escape sequences \u000D\u000A\u005C\u0027\u005C\u0022 special chars \u0022\u003F\u0021\u003D\u0024\u003C\u003E slice 1,1,2,3,5,8,13,21,34,55 1,1,2 3,5 2,3,5,8,13,21,34,55 2 2,3,5,8,13,21,34,55 es 好世 truncatechars_html This is a long test wh... <div class="foo"><ul class="foo"><li class="foo"><p class="foo">This is a long test wh...</p></li></ul></div> <p class='test' id='foo'>This is a long test wh...</p> <a name='link'><p>This </a>is a long test wh...</p> <p>This </a>is a long test wh...</p> <p>This...</p> truncatewords_html This is a long test which will be cutted after some words. <div class="foo"><ul class="foo"><li class="foo"><p class="foo">This is a long test ...</p></li></ul></div> <p>This. is. a. long test. Test test, test....</p> <a name='link' href="https://...."><p class="foo">This </a>is a long test,...</p> <p>This </a>is a long test,...</p> <p>This is ...</p> ...����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/filters.tpl����������������������������0000644�0610621�0607500�00000021513�13172163432�027201� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������add {{ 5|add:2 }} {{ 5|add:simple.number }} {{ 5|add:nothing }} {{ 5|add:"test" }} {{ "hello "|add:"john doe" }} {{ "hello "|add:simple.name }} addslashes {{ "plain text"|addslashes|safe }} {{ simple.escape_text|addslashes|safe }} capfirst {{ ""|capfirst }} {{ 5|capfirst }} {{ "h"|capfirst }} {{ "hello there!"|capfirst }} {{ simple.chinese_hello_world|capfirst }} cut {{ 15|cut:"5" }} {{ "Hello world"|cut: " " }} default {{ simple.nothing|default:"n/a" }} {{ nothing|default:simple.number }} {{ simple.number|default:"n/a" }} {{ 5|default:"n/a" }} default_if_none {{ simple.nothing|default_if_none:"n/a" }} {{ ""|default_if_none:"n/a" }} {{ nil|default_if_none:"n/a" }} get_digit {{ 1234567890|get_digit:0 }} {{ 1234567890|get_digit }} {{ 1234567890|get_digit:2 }} {{ 1234567890|get_digit:"4" }} {{ 1234567890|get_digit:10 }} {{ 1234567890|get_digit:15 }} safe {{ "<script>" }} {{ "<script>"|safe }} escape {{ "<script>"|safe|escape }} title {{ ""|title }} {{ 5|title }} {{ "h"|title }} {{ "hello there!"|title }} {{ "HELLO THERE!"|title }} {{ "hELLO tHERE!"|title }} {{ simple.chinese_hello_world|title }} truncatechars {{ "Joel is a slug"|truncatechars:9 }} {{ "Joel is a slug"|truncatechars:13 }} {{ "Joel is a slug"|truncatechars:14 }} {{ simple.chinese_hello_world|truncatechars:1 }} {{ simple.chinese_hello_world|truncatechars:2 }} divisibleby {{ 21|divisibleby:3 }} {{ 21|divisibleby:"3" }} {{ 21|float|divisibleby:"3" }} {{ 22|divisibleby:"3" }} {{ 85|divisibleby:simple.number }} {{ 84|divisibleby:simple.number }} striptags {{ "<strong><i>Hello!</i></strong>"|striptags|safe }} removetags {{ "<strong><i>Hello!</i></strong>"|removetags:"i"|safe }} yesno {{ simple.bool_true|yesno }} {{ simple.bool_false|yesno }} {{ simple.nil|yesno }} {{ simple.nothing|yesno }} {{ simple.bool_true|yesno:"ja,nein,vielleicht" }} {{ simple.bool_false|yesno:"ja,nein,vielleicht" }} {{ simple.nothing|yesno:"ja,nein" }} pluralize customer{{ 0|pluralize }} customer{{ 1|pluralize }} customer{{ 2|pluralize }} cherr{{ 0|pluralize:"y,ies" }} cherr{{ 1|pluralize:"y,ies" }} cherr{{ 2|pluralize:"y,ies" }} walrus{{ 0|pluralize:"es" }} walrus{{ 1|pluralize:"es" }} walrus{{ simple.number|pluralize:"es" }} random {{ 5|random }} {{ ""|random }} {{ "h"|random }} {{ simple.one_item_list|random }} first {{ "Test"|first }} {{ complex.comments|first }} {{ 5|first }} {{ true|first }} {{ nothing|first }} {{ simple.chinese_hello_world|first }} last {{ "Test"|last }} {{ complex.comments|last }} {{ 5|last }} {{ true|last }} {{ nothing|last }} {{ simple.chinese_hello_world|last }} urlencode {{ "http://www.example.org/foo?a=b&c=d"|urlencode }} linebreaksbr {{ simple.newline_text|linebreaksbr }} {{ ""|linebreaksbr }} {{ "hallo"|linebreaksbr }} length_is {{ simple.name|length_is:8 }} {{ simple.name|length_is:10 }} {{ simple.name|length_is:"8" }} {{ simple.name|length_is:"10" }} {{ 5|length_is:1 }} {{ simple.chinese_hello_world|length_is:4 }} {{ simple.chinese_hello_world|length_is:3 }} {{ simple.chinese_hello_world|length_is:5 }} integer {{ "foobar"|integer }} {{ nothing|integer }} {{ "5.4"|float|integer }} {{ "5.5"|float|integer }} {{ "5.6"|float|integer }} {{ 6|float|integer }} {{ -100|integer }} float {{ "foobar"|float }} {{ nil|float }} {{ "5.5"|float }} {{ 5|float }} {{ "5.6"|integer|float }} {{ -100|float }} {% if 5.5 == 5.500000 %}5.5 is 5.500000{% endif %} {% if 5.5 != 5.500001 %}5.5 is not 5.500001{% endif %} floatformat {{ 34.23234|floatformat }} {{ 34.00000|floatformat }} {{ 34.26000|floatformat }} {{ "34.23234"|floatformat }} {{ "34.00000"|floatformat }} {{ "34.26000"|floatformat }} {{ 34.23234|floatformat:3 }} {{ 34.00000|floatformat:3 }} {{ 34.26000|floatformat:3 }} {{ 34.23234|floatformat:"0" }} {{ 34.00000|floatformat:"0" }} {{ 39.56000|floatformat:"0" }} {{ 34.23234|floatformat:"-3" }} {{ 34.00000|floatformat:"-3" }} {{ 34.26000|floatformat:"-3" }} join {{ simple.misc_list|join:", " }} stringformat {{ simple.float|stringformat:"%.2f" }} {{ simple.uint|stringformat:"Test: %d" }} {{ simple.chinese_hello_world|stringformat:"Chinese: %s" }} make_list {{ simple.name|make_list|join:", " }} {% for char in simple.name|make_list %}{{ char }}{% endfor %} center '{{ "test"|center:3 }}' '{{ "test"|center:19 }}' '{{ "test"|center:20 }}' {{ "test"|center:20|length }} '{{ "test2"|center:19 }}' '{{ "test2"|center:20 }}' {{ "test2"|center:20|length }} '{{ simple.chinese_hello_world|center:20 }}' ljust '{{ "test"|ljust:"2" }}' '{{ "test"|ljust:"20" }}' {{ "test"|ljust:"20"|length }} '{{ simple.chinese_hello_world|ljust:10 }}' rjust '{{ "test"|rjust:"2" }}' '{{ "test"|rjust:"20" }}' {{ "test"|rjust:"20"|length }} '{{ simple.chinese_hello_world|rjust:10 }}' wordcount {{ ""|wordcount }} {% filter wordcount %}{% lorem 25 w %}{% endfilter %} wordwrap {{ ""|wordwrap:2 }} {% filter wordwrap:5 %}{% lorem 26 w %}{% endfilter %} iriencode {{ "?foo=123&bar=yes"|iriencode }} linebreaks {{ ""|linebreaks|safe }} {{ simple.newline_text|linebreaks|safe }} {{ simple.long_text|linebreaks|safe }} {{ simple.name|linebreaks|safe }} linenumbers {% filter linenumbers %}{% lorem 10 %}{% endfilter %} phone2numeric {{ "999-PONGO2"|phone2numeric }} truncatewords {% filter truncatewords:9 %}{% lorem 25 w %}{% endfilter %} {% filter wordcount %}{% filter truncatewords:9 %}{% lorem 25 w %}{% endfilter %}{% endfilter %} {{ simple.chinese_hello_world|truncatewords:0 }} {{ simple.chinese_hello_world|truncatewords:1 }} {{ simple.chinese_hello_world|truncatewords:2 }} urlize {{ "http://www.florian-schlachter.de"|urlize|safe }} {{ "www.florian-schlachter.de"|urlize|safe }} {{ "florian-schlachter.de"|urlize|safe }} {% filter urlize:true|safe %} Please mail me at demo@example.com or visit mit on: - lorem ipsum github.com/flosch/pongo2 lorem ipsum - lorem ipsum http://www.florian-schlachter.de lorem ipsum - lorem ipsum https://www.florian-schlachter.de lorem ipsum - lorem ipsum https://www.florian-schlachter.de lorem ipsum - lorem ipsum www.florian-schlachter.de lorem ipsum - lorem ipsum www.florian-schlachter.de/test="test" lorem ipsum {% endfilter %} -- {% filter urlize:false|safe %} Please mail me at demo@example.com or visit mit on: - lorem ipsum github.com/flosch/pongo2 lorem ipsum - lorem ipsum http://www.florian-schlachter.de lorem ipsum - lorem ipsum https://www.florian-schlachter.de lorem ipsum - lorem ipsum https://www.florian-schlachter.de lorem ipsum - lorem ipsum www.florian-schlachter.de lorem ipsum - lorem ipsum www.florian-schlachter.de/test="test" lorem ipsum {% endfilter %} urlizetrunc {% filter urlizetrunc:15|safe %} Please mail me at demo@example.com or visit mit on: - lorem ipsum github.com/flosch/pongo2 lorem ipsum - lorem ipsum http://www.florian-schlachter.de lorem ipsum - lorem ipsum https://www.florian-schlachter.de lorem ipsum - lorem ipsum https://www.florian-schlachter.de lorem ipsum - lorem ipsum www.florian-schlachter.de lorem ipsum - lorem ipsum www.florian-schlachter.de/test="test" lorem ipsum {% endfilter %} escapejs {{ simple.escape_js_test|escapejs|safe }} slice {{ simple.multiple_item_list|slice:":99"|join:"," }} {{ simple.multiple_item_list|slice:"99:"|join:"," }} {{ simple.multiple_item_list|slice:":3"|join:"," }} {{ simple.multiple_item_list|slice:"3:5"|join:"," }} {{ simple.multiple_item_list|slice:"2:"|join:"," }} {{ simple.multiple_item_list|slice:"2:3"|join:"," }} {{ simple.multiple_item_list|slice:"2:1"|join:"," }} {{ "Test"|slice:"1:3" }} {{ simple.chinese_hello_world|slice:"1:3" }} truncatechars_html {{ "This is a long test which will be cutted after some chars."|truncatechars_html:25 }} {{ "<div class=\"foo\"><ul class=\"foo\"><li class=\"foo\"><p class=\"foo\">This is a long test which will be cutted after some chars.</p></li></ul></div>"|truncatechars_html:25 }} {{ "<p class='test' id='foo'>This is a long test which will be cutted after some chars.</p>"|truncatechars_html:25 }} {{ "<a name='link'><p>This </a>is a long test which will be cutted after some chars.</p>"|truncatechars_html:25 }} {{ "<p>This </a>is a long test which will be cutted after some chars.</p>"|truncatechars_html:25 }} {{ "<p>This is a long test which will be cutted after some chars.</p>"|truncatechars_html:7 }} truncatewords_html {{ "This is a long test which will be cutted after some words."|truncatewords_html:25|safe }} {{ "<div class=\"foo\"><ul class=\"foo\"><li class=\"foo\"><p class=\"foo\">This is a long test which will be cutted after some chars.</p></li></ul></div>"|truncatewords_html:5 }} {{ "<p>This. is. a. long test. Test test, test.</p>"|truncatewords_html:8 }} {{ "<a name='link' href=\"https://....\"><p class=\"foo\">This </a>is a long test, which will be cutted after some words.</p>"|truncatewords_html:5 }} {{ "<p>This </a>is a long test, which will be cutted after some words.</p>"|truncatewords_html:5 }} {{ "<p>This is a long test which will be cutted after some words.</p>"|truncatewords_html:2 }} {{ "<p>This is a long test which will be cutted after some words.</p>"|truncatewords_html:0 }}�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/filters-execution.err.out��������������0000644�0610621�0607500�00000000437�13172163432�032003� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.*where: execution.*Negative sign on a non\-number expression .*Function input argument 0 of 'simple.func_add' must be of type int or \*pongo2.Value \(not string\). .*Function variadic input argument of 'simple.func_variadic_sum_int' must be of type int or \*pongo2.Value \(not string\).���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/filters-execution.err������������������0000644�0610621�0607500�00000000141�13172163432�031165� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ -(true || false) }} {{ simple.func_add("test", 5) }} {{ simple.func_variadic_sum_int("foo") }}�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/filters-compilation.err.out������������0000644�0610621�0607500�00000000345�13172163432�032314� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.*Expected either a number, string, keyword or identifier\. .*Closing bracket expected after expression .*Filter parameter required after ':'.* .*Filter 'non_existent_filter' does not exist\. .*Filter name must be an identifier\.�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/filters-compilation.err����������������0000644�0610621�0607500�00000000126�13172163432�031503� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ }} {{ (1 - 1 }} {{ 1|float: }} {{ "test"|non_existent_filter }} {{ "test"|"test" }}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/extends.tpl.out������������������������0000644�0610621�0607500�00000000055�13172163432�030007� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Start#This is base's bodyExtends' content#End�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/extends.tpl����������������������������0000644�0610621�0607500�00000000127�13172163432�027201� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% extends "inheritance/base.tpl" %} {% block content %}Extends' content{% endblock %}�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/expressions.tpl.out��������������������0000644�0610621�0607500�00000000567�13172163432�030727� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������integers and complex expressions -90 90 -90 90 531440999967.000000 floats 5.500000 5.172841 False True mul/div 10 10.000000 0 13.250000 0 0.500000 1000000.000000 logic expressions False False True True False False True float comparison True False False True remainders 0 True 1 in/not in True True False False True issue #48 (associativity for infix operators) 33 12 0�����������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/expressions.tpl������������������������0000644�0610621�0607500�00000001701�13172163432�030110� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������integers and complex expressions {{ 10-100 }} {{ -(10-100) }} {{ -(-(10-100)) }} {{ -1 * (-(-(10-100))) }} {{ -1 * (-(-(10-100)) ^ 2) ^ 3 + 3 * (5 - 17) + 1 + 2 }} floats {{ 5.5 }} {{ 5.172841 }} {{ 5.5 - 1.5 == 4 }} {{ 5.5 - 1.5 == 4.0 }} mul/div {{ 2 * 5 }} {{ 2 * 5.0 }} {{ 2 * 0 }} {{ 2.5 * 5.3 }} {{ 1/2 }} {{ 1/2.0 }} {{ 1/0.000001 }} logic expressions {{ !true }} {{ !(true || false) }} {{ true || false }} {{ true or false }} {{ false or false }} {{ false || false }} {{ true && (true && (true && (true && (1 == 1 || false)))) }} float comparison {{ 5.5 <= 5.5 }} {{ 5.5 < 5.5 }} {{ 5.5 > 5.5 }} {{ 5.5 >= 5.5 }} remainders {{ (simple.number+7)%7 }} {{ (simple.number+7)%7 == 0 }} {{ (simple.number+7)%6 }} in/not in {{ 5 in simple.intmap }} {{ 2 in simple.intmap }} {{ 7 in simple.intmap }} {{ !(5 in simple.intmap) }} {{ not(7 in simple.intmap) }} issue #48 (associativity for infix operators) {{ 34/3*3 }} {{ 10 + 24 / 6 / 2 }} {{ 6 - 4 - 2 }}���������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/empty.tpl.out��������������������������0000644�0610621�0607500�00000000000�13172163432�027461� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/empty.tpl������������������������������0000644�0610621�0607500�00000000000�13172163432�026653� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/cycle.tpl.out��������������������������0000644�0610621�0607500�00000003727�13172163432�027445� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� 'item1' 'john doe' '42' 'item1' 'john doe' '42' 'item1' 'john doe' '42' 'item1' 'item1' May I present the cycle item again: 'item1' 'john doe' May I present the cycle item again: 'john doe' '42' May I present the cycle item again: '42' 'item1' May I present the cycle item again: 'item1' 'john doe' May I present the cycle item again: 'john doe' '42' May I present the cycle item again: '42' 'item1' May I present the cycle item again: 'item1' 'john doe' May I present the cycle item again: 'john doe' '42' May I present the cycle item again: '42' 'item1' May I present the cycle item again: 'item1' '' May I present the cycle item: 'item1' '' May I present the cycle item: 'john doe' '' May I present the cycle item: '42' '' May I present the cycle item: 'item1' '' May I present the cycle item: 'john doe' '' May I present the cycle item: '42' '' May I present the cycle item: 'item1' '' May I present the cycle item: 'john doe' '' May I present the cycle item: '42' '' May I present the cycle item: 'item1' '' May I present the cycle item: 'item1' Included 'item1'. '' May I present the cycle item: 'john doe' Included 'john doe'. '' May I present the cycle item: '42' Included '42'. '' May I present the cycle item: 'item1' Included 'item1'. '' May I present the cycle item: 'john doe' Included 'john doe'. '' May I present the cycle item: '42' Included '42'. '' May I present the cycle item: 'item1' Included 'item1'. '' May I present the cycle item: 'john doe' Included 'john doe'. '' May I present the cycle item: '42' Included '42'. '' May I present the cycle item: 'item1' Included 'item1'. 'item1' 'john doe' '' 'item1' '' 'john doe'�����������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/cycle.tpl������������������������������0000644�0610621�0607500�00000001621�13172163432�026626� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% for item in simple.multiple_item_list %} '{% cycle "item1" simple.name simple.number %}' {% endfor %} {% for item in simple.multiple_item_list %} '{% cycle "item1" simple.name simple.number as cycleitem %}' May I present the cycle item again: '{{ cycleitem }}' {% endfor %} {% for item in simple.multiple_item_list %} '{% cycle "item1" simple.name simple.number as cycleitem silent %}' May I present the cycle item: '{{ cycleitem }}' {% endfor %} {% for item in simple.multiple_item_list %} '{% cycle "item1" simple.name simple.number as cycleitem silent %}' May I present the cycle item: '{{ cycleitem }}' {% include "inheritance/cycle_include.tpl" %} {% endfor %} '{% cycle "item1" simple.name simple.number as cycleitem %}' '{% cycle cycleitem %}' '{% cycle "item1" simple.name simple.number as cycleitem silent %}' '{{ cycleitem }}' '{% cycle cycleitem %}' '{{ cycleitem }}'���������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/complex.tpl.out������������������������0000644�0610621�0607500�00000001603�13172163432�030004� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� <!DOCTYPE html> <html> <head> <title>My blog page</title> </head> <body> <h1>Blogpost</h1> <div id="content"> <h2>Hello!</h2><p>Welcome to my new blog page. I'm using pongo2 which supports {{ variables }} and {% tags %}.</p> </div> <h1>Comments</h1> <h2>1. Comment (3 comments left)</h2> <p>From: user1 (validated)</p> <p>This user is not admin!</p> <p>Written 2014-06-10 15:30:15 +0000 UTC</p> <p>&quot;pongo2 is nice!&quot;</p> <h2>2. Comment (2 comments left)</h2> <p>From: user2 (validated)</p> <p>This user is an admin (verify: True)!</p> <p>Written 2011-03-21 08:37:56.000000012 +0000 UTC</p> <p>comment2 with unsafe tags in it</p> <h2>3. Comment (1 comment left)</h2> <p>From: user3 (not validated)</p> <p>This user is not admin!</p> <p>Written 2014-06-10 15:30:15 +0000 UTC</p> <p>hello! there</p> </body> </html>�����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/complex.tpl����������������������������0000644�0610621�0607500�00000001473�13172163432�027203� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{# A more complex template using pongo2 (fully django-compatible template) #} <!DOCTYPE html> <html> <head> <title>My blog page</title> </head> <body> <h1>Blogpost</h1> <div id="content"> {{ complex.post.Text|safe }} </div> <h1>Comments</h1> {% for comment in complex.comments %} <h2>{{ forloop.Counter }}. Comment ({{ forloop.Revcounter}} comment{{ forloop.Revcounter|pluralize:"s" }} left)</h2> <p>From: {{ comment.Author.Name }} ({{ comment.Author.Validated|yesno:"validated,not validated,unknown validation status" }})</p> {% if complex.is_admin(comment.Author) %} <p>This user is an admin (verify: {{ comment.Author.Is_admin }})!</p> {% else %} <p>This user is not admin!</p> {% endif %} <p>Written {{ comment.Date }}</p> <p>{{ comment.Text|striptags }}</p> {% endfor %} </body> </html>�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/base_dir_test/�������������������������0000755�0610621�0607500�00000000000�13172163432�027615� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/base_dir_test/subdir/������������������0000755�0610621�0607500�00000000000�13172163432�031105� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/base_dir_test/subdir/ssi.html����������0000644�0610621�0607500�00000000034�13172163432�032566� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% ssi "base.html" parsed %}����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/base_dir_test/subdir/index.html��������0000644�0610621�0607500�00000000032�13172163432�033075� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% extends "base.html" %} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/base_dir_test/subdir/include.html������0000644�0610621�0607500�00000000031�13172163432�033410� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% include "base.html" %}�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/base_dir_test/base.html����������������0000644�0610621�0607500�00000000037�13172163432�031415� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Hello from {{ base_directory }}�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/autoescape.tpl.out���������������������0000644�0610621�0607500�00000000275�13172163432�030472� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������&lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt; <script>alert('xss');</script> &lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt; &lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt; �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_tests/autoescape.tpl�������������������������0000644�0610621�0607500�00000000434�13172163432�027661� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{ "<script>alert('xss');</script>" }} {% autoescape off %} {{ "<script>alert('xss');</script>" }} {% endautoescape %} {% autoescape on %} {{ "<script>alert('xss');</script>" }} {% endautoescape %} {% autoescape off %} {{ "<script>alert('xss');</script>"|escape }} {% endautoescape %}������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template_sets.go��������������������������������������0000644�0610621�0607500�00000022322�13172163432�025152� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "fmt" "io/ioutil" "log" "os" "path/filepath" "sync" ) // A template set allows you to create your own group of templates with their own global context (which is shared // among all members of the set), their own configuration (like a specific base directory) and their own sandbox. // It's useful for a separation of different kind of templates (e. g. web templates vs. mail templates). type TemplateSet struct { name string // Globals will be provided to all templates created within this template set Globals Context // If debug is true (default false), ExecutionContext.Logf() will work and output to STDOUT. Furthermore, // FromCache() won't cache the templates. Make sure to synchronize the access to it in case you're changing this // variable during program execution (and template compilation/execution). Debug bool // Base directory: If you set the base directory (string is non-empty), all filename lookups in tags/filters are // relative to this directory. If it's empty, all lookups are relative to the current filename which is importing. baseDirectory string // Sandbox features // - Limit access to directories (using SandboxDirectories) // - Disallow access to specific tags and/or filters (using BanTag() and BanFilter()) // // You can limit file accesses (for all tags/filters which are using pongo2's file resolver technique) // to these sandbox directories. All default pongo2 filters/tags are respecting these restrictions. // For example, if you only have your base directory in the list, a {% ssi "/etc/passwd" %} will not work. // No items in SandboxDirectories means no restrictions at all. // // For efficiency reasons you can ban tags/filters only *before* you have added your first // template to the set (restrictions are statically checked). After you added one, it's not possible anymore // (for your personal security). // // SandboxDirectories can be changed at runtime. Please synchronize the access to it if you need to change it // after you've added your first template to the set. You *must* use this match pattern for your directories: // http://golang.org/pkg/path/filepath/#Match SandboxDirectories []string firstTemplateCreated bool bannedTags map[string]bool bannedFilters map[string]bool // Template cache (for FromCache()) templateCache map[string]*Template templateCacheMutex sync.Mutex } // Create your own template sets to separate different kind of templates (e. g. web from mail templates) with // different globals or other configurations (like base directories). func NewSet(name string) *TemplateSet { return &TemplateSet{ name: name, Globals: make(Context), bannedTags: make(map[string]bool), bannedFilters: make(map[string]bool), templateCache: make(map[string]*Template), } } // Use this function to set your template set's base directory. This directory will be used for any relative // path in filters, tags and From*-functions to determine your template. func (set *TemplateSet) SetBaseDirectory(name string) error { // Make the path absolute if !filepath.IsAbs(name) { abs, err := filepath.Abs(name) if err != nil { return err } name = abs } // Check for existence fi, err := os.Stat(name) if err != nil { return err } if !fi.IsDir() { return fmt.Errorf("The given path '%s' is not a directory.") } set.baseDirectory = name return nil } func (set *TemplateSet) BaseDirectory() string { return set.baseDirectory } // Ban a specific tag for this template set. See more in the documentation for TemplateSet. func (set *TemplateSet) BanTag(name string) { _, has := tags[name] if !has { panic(fmt.Sprintf("Tag '%s' not found.", name)) } if set.firstTemplateCreated { panic("You cannot ban any tags after you've added your first template to your template set.") } _, has = set.bannedTags[name] if has { panic(fmt.Sprintf("Tag '%s' is already banned.", name)) } set.bannedTags[name] = true } // Ban a specific filter for this template set. See more in the documentation for TemplateSet. func (set *TemplateSet) BanFilter(name string) { _, has := filters[name] if !has { panic(fmt.Sprintf("Filter '%s' not found.", name)) } if set.firstTemplateCreated { panic("You cannot ban any filters after you've added your first template to your template set.") } _, has = set.bannedFilters[name] if has { panic(fmt.Sprintf("Filter '%s' is already banned.", name)) } set.bannedFilters[name] = true } // FromCache() is a convenient method to cache templates. It is thread-safe // and will only compile the template associated with a filename once. // If TemplateSet.Debug is true (for example during development phase), // FromCache() will not cache the template and instead recompile it on any // call (to make changes to a template live instantaneously). // Like FromFile(), FromCache() takes a relative path to a set base directory. // Sandbox restrictions apply (if given). func (set *TemplateSet) FromCache(filename string) (*Template, error) { if set.Debug { // Recompile on any request return set.FromFile(filename) } else { // Cache the template cleaned_filename := set.resolveFilename(nil, filename) set.templateCacheMutex.Lock() defer set.templateCacheMutex.Unlock() tpl, has := set.templateCache[cleaned_filename] // Cache miss if !has { tpl, err := set.FromFile(cleaned_filename) if err != nil { return nil, err } set.templateCache[cleaned_filename] = tpl return tpl, nil } // Cache hit return tpl, nil } } // Loads a template from string and returns a Template instance. func (set *TemplateSet) FromString(tpl string) (*Template, error) { set.firstTemplateCreated = true return newTemplateString(set, tpl) } // Loads a template from a filename and returns a Template instance. // If a base directory is set, the filename must be either relative to it // or be an absolute path. Sandbox restrictions (SandboxDirectories) apply // if given. func (set *TemplateSet) FromFile(filename string) (*Template, error) { set.firstTemplateCreated = true buf, err := ioutil.ReadFile(set.resolveFilename(nil, filename)) if err != nil { return nil, &Error{ Filename: filename, Sender: "fromfile", ErrorMsg: err.Error(), } } return newTemplate(set, filename, false, string(buf)) } // Shortcut; renders a template string directly. Panics when providing a // malformed template or an error occurs during execution. func (set *TemplateSet) RenderTemplateString(s string, ctx Context) string { set.firstTemplateCreated = true tpl := Must(set.FromString(s)) result, err := tpl.Execute(ctx) if err != nil { panic(err) } return result } // Shortcut; renders a template file directly. Panics when providing a // malformed template or an error occurs during execution. func (set *TemplateSet) RenderTemplateFile(fn string, ctx Context) string { set.firstTemplateCreated = true tpl := Must(set.FromFile(fn)) result, err := tpl.Execute(ctx) if err != nil { panic(err) } return result } func (set *TemplateSet) logf(format string, args ...interface{}) { if set.Debug { logger.Printf(fmt.Sprintf("[template set: %s] %s", set.name, format), args...) } } // Resolves a filename relative to the base directory. Absolute paths are allowed. // If sandbox restrictions are given (SandboxDirectories), they will be respected and checked. // On sandbox restriction violation, resolveFilename() panics. func (set *TemplateSet) resolveFilename(tpl *Template, filename string) (resolved_path string) { if len(set.SandboxDirectories) > 0 { defer func() { // Remove any ".." or other crap resolved_path = filepath.Clean(resolved_path) // Make the path absolute abs_path, err := filepath.Abs(resolved_path) if err != nil { panic(err) } resolved_path = abs_path // Check against the sandbox directories (once one pattern matches, we're done and can allow it) for _, pattern := range set.SandboxDirectories { matched, err := filepath.Match(pattern, resolved_path) if err != nil { panic("Wrong sandbox directory match pattern (see http://golang.org/pkg/path/filepath/#Match).") } if matched { // OK! return } } // No pattern matched, we have to log+deny the request set.logf("Access attempt outside of the sandbox directories (blocked): '%s'", resolved_path) resolved_path = "" }() } if filepath.IsAbs(filename) { return filename } if set.baseDirectory == "" { if tpl != nil { if tpl.is_tpl_string { return filename } base := filepath.Dir(tpl.name) return filepath.Join(base, filename) } return filename } else { return filepath.Join(set.baseDirectory, filename) } } // Logging function (internally used) func logf(format string, items ...interface{}) { if debug { logger.Printf(format, items...) } } var ( debug bool // internal debugging logger = log.New(os.Stdout, "[pongo2] ", log.LstdFlags) // Creating a default set DefaultSet = NewSet("default") // Methods on the default set FromString = DefaultSet.FromString FromFile = DefaultSet.FromFile FromCache = DefaultSet.FromCache RenderTemplateString = DefaultSet.RenderTemplateString RenderTemplateFile = DefaultSet.RenderTemplateFile // Globals for the default set Globals = DefaultSet.Globals ) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/template.go�������������������������������������������0000644�0610621�0607500�00000007146�13172163432�024123� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" "io" ) type Template struct { set *TemplateSet // Input is_tpl_string bool name string tpl string size int // Calculation tokens []*Token parser *Parser // first come, first serve (it's important to not override existing entries in here) level int parent *Template child *Template blocks map[string]*NodeWrapper exported_macros map[string]*tagMacroNode // Output root *nodeDocument } func newTemplateString(set *TemplateSet, tpl string) (*Template, error) { return newTemplate(set, "<string>", true, tpl) } func newTemplate(set *TemplateSet, name string, is_tpl_string bool, tpl string) (*Template, error) { // Create the template t := &Template{ set: set, is_tpl_string: is_tpl_string, name: name, tpl: tpl, size: len(tpl), blocks: make(map[string]*NodeWrapper), exported_macros: make(map[string]*tagMacroNode), } // Tokenize it tokens, err := lex(name, tpl) if err != nil { return nil, err } t.tokens = tokens // For debugging purposes, show all tokens: /*for i, t := range tokens { fmt.Printf("%3d. %s\n", i, t) }*/ // Parse it err = t.parse() if err != nil { return nil, err } return t, nil } func (tpl *Template) execute(context Context) (*bytes.Buffer, error) { // Create output buffer // We assume that the rendered template will be 30% larger buffer := bytes.NewBuffer(make([]byte, 0, int(float64(tpl.size)*1.3))) // Determine the parent to be executed (for template inheritance) parent := tpl for parent.parent != nil { parent = parent.parent } // Create context if none is given newContext := make(Context) newContext.Update(tpl.set.Globals) if context != nil { newContext.Update(context) if len(newContext) > 0 { // Check for context name syntax err := newContext.checkForValidIdentifiers() if err != nil { return nil, err } // Check for clashes with macro names for k, _ := range newContext { _, has := tpl.exported_macros[k] if has { return nil, &Error{ Filename: tpl.name, Sender: "execution", ErrorMsg: fmt.Sprintf("Context key name '%s' clashes with macro '%s'.", k, k), } } } } } // Create operational context ctx := newExecutionContext(parent, newContext) // Run the selected document err := parent.root.Execute(ctx, buffer) if err != nil { return nil, err } return buffer, nil } // Executes the template with the given context and writes to writer (io.Writer) // on success. Context can be nil. Nothing is written on error; instead the error // is being returned. func (tpl *Template) ExecuteWriter(context Context, writer io.Writer) error { buffer, err := tpl.execute(context) if err != nil { return err } l := buffer.Len() n, werr := buffer.WriteTo(writer) if int(n) != l { panic(fmt.Sprintf("error on writing template: n(%d) != buffer.Len(%d)", n, l)) } if werr != nil { return &Error{ Filename: tpl.name, Sender: "execution", ErrorMsg: werr.Error(), } } return nil } // Executes the template and returns the rendered template as a []byte func (tpl *Template) ExecuteBytes(context Context) ([]byte, error) { // Execute template buffer, err := tpl.execute(context) if err != nil { return nil, err } return buffer.Bytes(), nil } // Executes the template and returns the rendered template as a string func (tpl *Template) Execute(context Context) (string, error) { // Execute template buffer, err := tpl.execute(context) if err != nil { return "", err } return buffer.String(), nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_with.go������������������������������������������0000644�0610621�0607500�00000004443�13172163432�024276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagWithNode struct { with_pairs map[string]IEvaluator wrapper *NodeWrapper } func (node *tagWithNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { //new context for block withctx := NewChildExecutionContext(ctx) // Put all custom with-pairs into the context for key, value := range node.with_pairs { val, err := value.Evaluate(ctx) if err != nil { return err } withctx.Private[key] = val } return node.wrapper.Execute(withctx, buffer) } func tagWithParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { with_node := &tagWithNode{ with_pairs: make(map[string]IEvaluator), } if arguments.Count() == 0 { return nil, arguments.Error("Tag 'with' requires at least one argument.", nil) } wrapper, endargs, err := doc.WrapUntilTag("endwith") if err != nil { return nil, err } with_node.wrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } // Scan through all arguments to see which style the user uses (old or new style). // If we find any "as" keyword we will enforce old style; otherwise we will use new style. old_style := false // by default we're using the new_style for i := 0; i < arguments.Count(); i++ { if arguments.PeekN(i, TokenKeyword, "as") != nil { old_style = true break } } for arguments.Remaining() > 0 { if old_style { value_expr, err := arguments.ParseExpression() if err != nil { return nil, err } if arguments.Match(TokenKeyword, "as") == nil { return nil, arguments.Error("Expected 'as' keyword.", nil) } key_token := arguments.MatchType(TokenIdentifier) if key_token == nil { return nil, arguments.Error("Expected an identifier", nil) } with_node.with_pairs[key_token.Val] = value_expr } else { key_token := arguments.MatchType(TokenIdentifier) if key_token == nil { return nil, arguments.Error("Expected an identifier", nil) } if arguments.Match(TokenSymbol, "=") == nil { return nil, arguments.Error("Expected '='.", nil) } value_expr, err := arguments.ParseExpression() if err != nil { return nil, err } with_node.with_pairs[key_token.Val] = value_expr } } return with_node, nil } func init() { RegisterTag("with", tagWithParser) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_widthratio.go������������������������������������0000644�0610621�0607500�00000003213�13172163432�025473� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" "math" ) type tagWidthratioNode struct { position *Token current, max IEvaluator width IEvaluator ctx_name string } func (node *tagWidthratioNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { current, err := node.current.Evaluate(ctx) if err != nil { return err } max, err := node.max.Evaluate(ctx) if err != nil { return err } width, err := node.width.Evaluate(ctx) if err != nil { return err } value := int(math.Ceil(current.Float()/max.Float()*width.Float() + 0.5)) if node.ctx_name == "" { buffer.WriteString(fmt.Sprintf("%d", value)) } else { ctx.Private[node.ctx_name] = value } return nil } func tagWidthratioParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { widthratio_node := &tagWidthratioNode{ position: start, } current, err := arguments.ParseExpression() if err != nil { return nil, err } widthratio_node.current = current max, err := arguments.ParseExpression() if err != nil { return nil, err } widthratio_node.max = max width, err := arguments.ParseExpression() if err != nil { return nil, err } widthratio_node.width = width if arguments.MatchOne(TokenKeyword, "as") != nil { // Name follows name_token := arguments.MatchType(TokenIdentifier) if name_token == nil { return nil, arguments.Error("Expected name (identifier).", nil) } widthratio_node.ctx_name = name_token.Val } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed widthratio-tag arguments.", nil) } return widthratio_node, nil } func init() { RegisterTag("widthratio", tagWidthratioParser) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_templatetag.go�����������������������������������0000644�0610621�0607500�00000002122�13172163432�025622� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagTemplateTagNode struct { content string } var templateTagMapping = map[string]string{ "openblock": "{%", "closeblock": "%}", "openvariable": "{{", "closevariable": "}}", "openbrace": "{", "closebrace": "}", "opencomment": "{#", "closecomment": "#}", } func (node *tagTemplateTagNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { buffer.WriteString(node.content) return nil } func tagTemplateTagParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { tt_node := &tagTemplateTagNode{} if arg_token := arguments.MatchType(TokenIdentifier); arg_token != nil { output, found := templateTagMapping[arg_token.Val] if !found { return nil, arguments.Error("Argument not found", arg_token) } tt_node.content = output } else { return nil, arguments.Error("Identifier expected.", nil) } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed templatetag-tag argument.", nil) } return tt_node, nil } func init() { RegisterTag("templatetag", tagTemplateTagParser) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_ssi.go�������������������������������������������0000644�0610621�0607500�00000003271�13172163432�024117� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "io/ioutil" ) type tagSSINode struct { filename string content string template *Template } func (node *tagSSINode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { if node.template != nil { // Execute the template within the current context includeCtx := make(Context) includeCtx.Update(ctx.Public) includeCtx.Update(ctx.Private) err := node.template.ExecuteWriter(includeCtx, buffer) if err != nil { return err.(*Error) } } else { // Just print out the content buffer.WriteString(node.content) } return nil } func tagSSIParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { ssi_node := &tagSSINode{} if file_token := arguments.MatchType(TokenString); file_token != nil { ssi_node.filename = file_token.Val if arguments.Match(TokenIdentifier, "parsed") != nil { // parsed temporary_tpl, err := doc.template.set.FromFile(doc.template.set.resolveFilename(doc.template, file_token.Val)) if err != nil { return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, file_token) } ssi_node.template = temporary_tpl } else { // plaintext buf, err := ioutil.ReadFile(doc.template.set.resolveFilename(doc.template, file_token.Val)) if err != nil { return nil, (&Error{ Sender: "tag:ssi", ErrorMsg: err.Error(), }).updateFromTokenIfNeeded(doc.template, file_token) } ssi_node.content = string(buf) } } else { return nil, arguments.Error("First argument must be a string.", nil) } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed SSI-tag argument.", nil) } return ssi_node, nil } func init() { RegisterTag("ssi", tagSSIParser) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_spaceless.go�������������������������������������0000644�0610621�0607500�00000002057�13172163432�025304� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "regexp" ) type tagSpacelessNode struct { wrapper *NodeWrapper } var tagSpacelessRegexp = regexp.MustCompile(`(?U:(<.*>))([\t\n\v\f\r ]+)(?U:(<.*>))`) func (node *tagSpacelessNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { b := bytes.NewBuffer(make([]byte, 0, 1024)) // 1 KiB err := node.wrapper.Execute(ctx, b) if err != nil { return err } s := b.String() // Repeat this recursively changed := true for changed { s2 := tagSpacelessRegexp.ReplaceAllString(s, "$1$3") changed = s != s2 s = s2 } buffer.WriteString(s) return nil } func tagSpacelessParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { spaceless_node := &tagSpacelessNode{} wrapper, _, err := doc.WrapUntilTag("endspaceless") if err != nil { return nil, err } spaceless_node.wrapper = wrapper if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed spaceless-tag arguments.", nil) } return spaceless_node, nil } func init() { RegisterTag("spaceless", tagSpacelessParser) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_set.go�������������������������������������������0000644�0610621�0607500�00000002100�13172163432�024102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import "bytes" type tagSetNode struct { name string expression IEvaluator } func (node *tagSetNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { // Evaluate expression value, err := node.expression.Evaluate(ctx) if err != nil { return err } ctx.Private[node.name] = value return nil } func tagSetParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { node := &tagSetNode{} // Parse variable name typeToken := arguments.MatchType(TokenIdentifier) if typeToken == nil { return nil, arguments.Error("Expected an identifier.", nil) } node.name = typeToken.Val if arguments.Match(TokenSymbol, "=") == nil { return nil, arguments.Error("Expected '='.", nil) } // Variable expression keyExpression, err := arguments.ParseExpression() if err != nil { return nil, err } node.expression = keyExpression // Remaining arguments if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed 'set'-tag arguments.", nil) } return node, nil } func init() { RegisterTag("set", tagSetParser) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_now.go�������������������������������������������0000644�0610621�0607500�00000001716�13172163432�024126� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "time" ) type tagNowNode struct { position *Token format string fake bool } func (node *tagNowNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { var t time.Time if node.fake { t = time.Date(2014, time.February, 05, 18, 31, 45, 00, time.UTC) } else { t = time.Now() } buffer.WriteString(t.Format(node.format)) return nil } func tagNowParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { now_node := &tagNowNode{ position: start, } format_token := arguments.MatchType(TokenString) if format_token == nil { return nil, arguments.Error("Expected a format string.", nil) } now_node.format = format_token.Val if arguments.MatchOne(TokenIdentifier, "fake") != nil { now_node.fake = true } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed now-tag arguments.", nil) } return now_node, nil } func init() { RegisterTag("now", tagNowParser) } ��������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_macro.go�����������������������������������������0000644�0610621�0607500�00000007477�13172163432�024436� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" ) type tagMacroNode struct { position *Token name string args_order []string args map[string]IEvaluator exported bool wrapper *NodeWrapper } func (node *tagMacroNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { ctx.Private[node.name] = func(args ...*Value) *Value { return node.call(ctx, args...) } return nil } func (node *tagMacroNode) call(ctx *ExecutionContext, args ...*Value) *Value { args_ctx := make(Context) for k, v := range node.args { if v == nil { // User did not provided a default value args_ctx[k] = nil } else { // Evaluate the default value value_expr, err := v.Evaluate(ctx) if err != nil { ctx.Logf(err.Error()) return AsSafeValue(err.Error()) } args_ctx[k] = value_expr } } if len(args) > len(node.args_order) { // Too many arguments, we're ignoring them and just logging into debug mode. err := ctx.Error(fmt.Sprintf("Macro '%s' called with too many arguments (%d instead of %d).", node.name, len(args), len(node.args_order)), nil).updateFromTokenIfNeeded(ctx.template, node.position) ctx.Logf(err.Error()) // TODO: This is a workaround, because the error is not returned yet to the Execution()-methods return AsSafeValue(err.Error()) } // Make a context for the macro execution macroCtx := NewChildExecutionContext(ctx) // Register all arguments in the private context macroCtx.Private.Update(args_ctx) for idx, arg_value := range args { macroCtx.Private[node.args_order[idx]] = arg_value.Interface() } var b bytes.Buffer err := node.wrapper.Execute(macroCtx, &b) if err != nil { return AsSafeValue(err.updateFromTokenIfNeeded(ctx.template, node.position).Error()) } return AsSafeValue(b.String()) } func tagMacroParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { macro_node := &tagMacroNode{ position: start, args: make(map[string]IEvaluator), } name_token := arguments.MatchType(TokenIdentifier) if name_token == nil { return nil, arguments.Error("Macro-tag needs at least an identifier as name.", nil) } macro_node.name = name_token.Val if arguments.MatchOne(TokenSymbol, "(") == nil { return nil, arguments.Error("Expected '('.", nil) } for arguments.Match(TokenSymbol, ")") == nil { arg_name_token := arguments.MatchType(TokenIdentifier) if arg_name_token == nil { return nil, arguments.Error("Expected argument name as identifier.", nil) } macro_node.args_order = append(macro_node.args_order, arg_name_token.Val) if arguments.Match(TokenSymbol, "=") != nil { // Default expression follows arg_default_expr, err := arguments.ParseExpression() if err != nil { return nil, err } macro_node.args[arg_name_token.Val] = arg_default_expr } else { // No default expression macro_node.args[arg_name_token.Val] = nil } if arguments.Match(TokenSymbol, ")") != nil { break } if arguments.Match(TokenSymbol, ",") == nil { return nil, arguments.Error("Expected ',' or ')'.", nil) } } if arguments.Match(TokenKeyword, "export") != nil { macro_node.exported = true } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed macro-tag.", nil) } // Body wrapping wrapper, endargs, err := doc.WrapUntilTag("endmacro") if err != nil { return nil, err } macro_node.wrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } if macro_node.exported { // Now register the macro if it wants to be exported _, has := doc.template.exported_macros[macro_node.name] if has { return nil, doc.Error(fmt.Sprintf("Another macro with name '%s' already exported.", macro_node.name), start) } doc.template.exported_macros[macro_node.name] = macro_node } return macro_node, nil } func init() { RegisterTag("macro", tagMacroParser) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_lorem.go�����������������������������������������0000644�0610621�0607500�00000014362�13172163432�024442� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "math/rand" "strings" "time" ) var ( tagLoremParagraphs = strings.Split(tagLoremText, "\n") tagLoremWords = strings.Fields(tagLoremText) ) type tagLoremNode struct { position *Token count int // number of paragraphs method string // w = words, p = HTML paragraphs, b = plain-text (default is b) random bool // does not use the default paragraph "Lorem ipsum dolor sit amet, ..." } func (node *tagLoremNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { switch node.method { case "b": if node.random { for i := 0; i < node.count; i++ { if i > 0 { buffer.WriteString("\n") } par := tagLoremParagraphs[rand.Intn(len(tagLoremParagraphs))] buffer.WriteString(par) } } else { for i := 0; i < node.count; i++ { if i > 0 { buffer.WriteString("\n") } par := tagLoremParagraphs[i%len(tagLoremParagraphs)] buffer.WriteString(par) } } case "w": if node.random { for i := 0; i < node.count; i++ { if i > 0 { buffer.WriteString(" ") } word := tagLoremWords[rand.Intn(len(tagLoremWords))] buffer.WriteString(word) } } else { for i := 0; i < node.count; i++ { if i > 0 { buffer.WriteString(" ") } word := tagLoremWords[i%len(tagLoremWords)] buffer.WriteString(word) } } case "p": if node.random { for i := 0; i < node.count; i++ { if i > 0 { buffer.WriteString("\n") } buffer.WriteString("<p>") par := tagLoremParagraphs[rand.Intn(len(tagLoremParagraphs))] buffer.WriteString(par) buffer.WriteString("</p>") } } else { for i := 0; i < node.count; i++ { if i > 0 { buffer.WriteString("\n") } buffer.WriteString("<p>") par := tagLoremParagraphs[i%len(tagLoremParagraphs)] buffer.WriteString(par) buffer.WriteString("</p>") } } default: panic("unsupported method") } return nil } func tagLoremParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { lorem_node := &tagLoremNode{ position: start, count: 1, method: "b", } if count_token := arguments.MatchType(TokenNumber); count_token != nil { lorem_node.count = AsValue(count_token.Val).Integer() } if method_token := arguments.MatchType(TokenIdentifier); method_token != nil { if method_token.Val != "w" && method_token.Val != "p" && method_token.Val != "b" { return nil, arguments.Error("lorem-method must be either 'w', 'p' or 'b'.", nil) } lorem_node.method = method_token.Val } if arguments.MatchOne(TokenIdentifier, "random") != nil { lorem_node.random = true } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed lorem-tag arguments.", nil) } return lorem_node, nil } func init() { rand.Seed(time.Now().Unix()) RegisterTag("lorem", tagLoremParser) } const tagLoremText = `Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat. Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.` ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_include.go���������������������������������������0000644�0610621�0607500�00000007035�13172163432�024746� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagIncludeNode struct { tpl *Template filename_evaluator IEvaluator lazy bool only bool filename string with_pairs map[string]IEvaluator } func (node *tagIncludeNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { // Building the context for the template include_ctx := make(Context) // Fill the context with all data from the parent if !node.only { include_ctx.Update(ctx.Public) include_ctx.Update(ctx.Private) } // Put all custom with-pairs into the context for key, value := range node.with_pairs { val, err := value.Evaluate(ctx) if err != nil { return err } include_ctx[key] = val } // Execute the template if node.lazy { // Evaluate the filename filename, err := node.filename_evaluator.Evaluate(ctx) if err != nil { return err } if filename.String() == "" { return ctx.Error("Filename for 'include'-tag evaluated to an empty string.", nil) } // Get include-filename included_filename := ctx.template.set.resolveFilename(ctx.template, filename.String()) included_tpl, err2 := ctx.template.set.FromFile(included_filename) if err2 != nil { return err2.(*Error) } err2 = included_tpl.ExecuteWriter(include_ctx, buffer) if err2 != nil { return err2.(*Error) } return nil } else { // Template is already parsed with static filename err := node.tpl.ExecuteWriter(include_ctx, buffer) if err != nil { return err.(*Error) } return nil } } func tagIncludeParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { include_node := &tagIncludeNode{ with_pairs: make(map[string]IEvaluator), } if filename_token := arguments.MatchType(TokenString); filename_token != nil { // prepared, static template // Get include-filename included_filename := doc.template.set.resolveFilename(doc.template, filename_token.Val) // Parse the parent include_node.filename = included_filename included_tpl, err := doc.template.set.FromFile(included_filename) if err != nil { return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, filename_token) } include_node.tpl = included_tpl } else { // No String, then the user wants to use lazy-evaluation (slower, but possible) filename_evaluator, err := arguments.ParseExpression() if err != nil { return nil, err.updateFromTokenIfNeeded(doc.template, filename_token) } include_node.filename_evaluator = filename_evaluator include_node.lazy = true } // After having parsed the filename we're gonna parse the with+only options if arguments.Match(TokenIdentifier, "with") != nil { for arguments.Remaining() > 0 { // We have at least one key=expr pair (because of starting "with") key_token := arguments.MatchType(TokenIdentifier) if key_token == nil { return nil, arguments.Error("Expected an identifier", nil) } if arguments.Match(TokenSymbol, "=") == nil { return nil, arguments.Error("Expected '='.", nil) } value_expr, err := arguments.ParseExpression() if err != nil { return nil, err.updateFromTokenIfNeeded(doc.template, key_token) } include_node.with_pairs[key_token.Val] = value_expr // Only? if arguments.Match(TokenIdentifier, "only") != nil { include_node.only = true break // stop parsing arguments because it's the last option } } } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed 'include'-tag arguments.", nil) } return include_node, nil } func init() { RegisterTag("include", tagIncludeParser) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_import.go����������������������������������������0000644�0610621�0607500�00000004330�13172163432�024630� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" ) type tagImportNode struct { position *Token filename string template *Template macros map[string]*tagMacroNode // alias/name -> macro instance } func (node *tagImportNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { for name, macro := range node.macros { func(name string, macro *tagMacroNode) { ctx.Private[name] = func(args ...*Value) *Value { return macro.call(ctx, args...) } }(name, macro) } return nil } func tagImportParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { import_node := &tagImportNode{ position: start, macros: make(map[string]*tagMacroNode), } filename_token := arguments.MatchType(TokenString) if filename_token == nil { return nil, arguments.Error("Import-tag needs a filename as string.", nil) } import_node.filename = doc.template.set.resolveFilename(doc.template, filename_token.Val) if arguments.Remaining() == 0 { return nil, arguments.Error("You must at least specify one macro to import.", nil) } // Compile the given template tpl, err := doc.template.set.FromFile(import_node.filename) if err != nil { return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, start) } for arguments.Remaining() > 0 { macro_name_token := arguments.MatchType(TokenIdentifier) if macro_name_token == nil { return nil, arguments.Error("Expected macro name (identifier).", nil) } as_name := macro_name_token.Val if arguments.Match(TokenKeyword, "as") != nil { alias_token := arguments.MatchType(TokenIdentifier) if alias_token == nil { return nil, arguments.Error("Expected macro alias name (identifier).", nil) } as_name = alias_token.Val } macro_instance, has := tpl.exported_macros[macro_name_token.Val] if !has { return nil, arguments.Error(fmt.Sprintf("Macro '%s' not found (or not exported) in '%s'.", macro_name_token.Val, import_node.filename), macro_name_token) } import_node.macros[as_name] = macro_instance if arguments.Remaining() == 0 { break } if arguments.Match(TokenSymbol, ",") == nil { return nil, arguments.Error("Expected ','.", nil) } } return import_node, nil } func init() { RegisterTag("import", tagImportParser) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_ifnotequal.go������������������������������������0000644�0610621�0607500�00000003356�13172163432�025474� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagIfNotEqualNode struct { var1, var2 IEvaluator thenWrapper *NodeWrapper elseWrapper *NodeWrapper } func (node *tagIfNotEqualNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { r1, err := node.var1.Evaluate(ctx) if err != nil { return err } r2, err := node.var2.Evaluate(ctx) if err != nil { return err } result := !r1.EqualValueTo(r2) if result { return node.thenWrapper.Execute(ctx, buffer) } else { if node.elseWrapper != nil { return node.elseWrapper.Execute(ctx, buffer) } } return nil } func tagIfNotEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { ifnotequal_node := &tagIfNotEqualNode{} // Parse two expressions var1, err := arguments.ParseExpression() if err != nil { return nil, err } var2, err := arguments.ParseExpression() if err != nil { return nil, err } ifnotequal_node.var1 = var1 ifnotequal_node.var2 = var2 if arguments.Remaining() > 0 { return nil, arguments.Error("ifequal only takes 2 arguments.", nil) } // Wrap then/else-blocks wrapper, endargs, err := doc.WrapUntilTag("else", "endifequal") if err != nil { return nil, err } ifnotequal_node.thenWrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } if wrapper.Endtag == "else" { // if there's an else in the if-statement, we need the else-Block as well wrapper, endargs, err = doc.WrapUntilTag("endifequal") if err != nil { return nil, err } ifnotequal_node.elseWrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } } return ifnotequal_node, nil } func init() { RegisterTag("ifnotequal", tagIfNotEqualParser) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_ifequal.go���������������������������������������0000644�0610621�0607500�00000003311�13172163432�024742� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagIfEqualNode struct { var1, var2 IEvaluator thenWrapper *NodeWrapper elseWrapper *NodeWrapper } func (node *tagIfEqualNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { r1, err := node.var1.Evaluate(ctx) if err != nil { return err } r2, err := node.var2.Evaluate(ctx) if err != nil { return err } result := r1.EqualValueTo(r2) if result { return node.thenWrapper.Execute(ctx, buffer) } else { if node.elseWrapper != nil { return node.elseWrapper.Execute(ctx, buffer) } } return nil } func tagIfEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { ifequal_node := &tagIfEqualNode{} // Parse two expressions var1, err := arguments.ParseExpression() if err != nil { return nil, err } var2, err := arguments.ParseExpression() if err != nil { return nil, err } ifequal_node.var1 = var1 ifequal_node.var2 = var2 if arguments.Remaining() > 0 { return nil, arguments.Error("ifequal only takes 2 arguments.", nil) } // Wrap then/else-blocks wrapper, endargs, err := doc.WrapUntilTag("else", "endifequal") if err != nil { return nil, err } ifequal_node.thenWrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } if wrapper.Endtag == "else" { // if there's an else in the if-statement, we need the else-Block as well wrapper, endargs, err = doc.WrapUntilTag("endifequal") if err != nil { return nil, err } ifequal_node.elseWrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } } return ifequal_node, nil } func init() { RegisterTag("ifequal", tagIfEqualParser) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_ifchanged.go�������������������������������������0000644�0610621�0607500�00000005110�13172163432�025223� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagIfchangedNode struct { watched_expr []IEvaluator last_values []*Value last_content []byte thenWrapper *NodeWrapper elseWrapper *NodeWrapper } func (node *tagIfchangedNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { if len(node.watched_expr) == 0 { // Check against own rendered body buf := bytes.NewBuffer(make([]byte, 0, 1024)) // 1 KiB err := node.thenWrapper.Execute(ctx, buf) if err != nil { return err } buf_bytes := buf.Bytes() if !bytes.Equal(node.last_content, buf_bytes) { // Rendered content changed, output it buffer.Write(buf_bytes) node.last_content = buf_bytes } } else { now_values := make([]*Value, 0, len(node.watched_expr)) for _, expr := range node.watched_expr { val, err := expr.Evaluate(ctx) if err != nil { return err } now_values = append(now_values, val) } // Compare old to new values now changed := len(node.last_values) == 0 for idx, old_val := range node.last_values { if !old_val.EqualValueTo(now_values[idx]) { changed = true break // we can stop here because ONE value changed } } node.last_values = now_values if changed { // Render thenWrapper err := node.thenWrapper.Execute(ctx, buffer) if err != nil { return err } } else { // Render elseWrapper err := node.elseWrapper.Execute(ctx, buffer) if err != nil { return err } } } return nil } func tagIfchangedParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { ifchanged_node := &tagIfchangedNode{} for arguments.Remaining() > 0 { // Parse condition expr, err := arguments.ParseExpression() if err != nil { return nil, err } ifchanged_node.watched_expr = append(ifchanged_node.watched_expr, expr) } if arguments.Remaining() > 0 { return nil, arguments.Error("Ifchanged-arguments are malformed.", nil) } // Wrap then/else-blocks wrapper, endargs, err := doc.WrapUntilTag("else", "endifchanged") if err != nil { return nil, err } ifchanged_node.thenWrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } if wrapper.Endtag == "else" { // if there's an else in the if-statement, we need the else-Block as well wrapper, endargs, err = doc.WrapUntilTag("endifchanged") if err != nil { return nil, err } ifchanged_node.elseWrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } } return ifchanged_node, nil } func init() { RegisterTag("ifchanged", tagIfchangedParser) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_if.go��������������������������������������������0000644�0610621�0607500�00000003346�13172163432�023722� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagIfNode struct { conditions []IEvaluator wrappers []*NodeWrapper } func (node *tagIfNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { for i, condition := range node.conditions { result, err := condition.Evaluate(ctx) if err != nil { return err } if result.IsTrue() { return node.wrappers[i].Execute(ctx, buffer) } else { // Last condition? if len(node.conditions) == i+1 && len(node.wrappers) > i+1 { return node.wrappers[i+1].Execute(ctx, buffer) } } } return nil } func tagIfParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { if_node := &tagIfNode{} // Parse first and main IF condition condition, err := arguments.ParseExpression() if err != nil { return nil, err } if_node.conditions = append(if_node.conditions, condition) if arguments.Remaining() > 0 { return nil, arguments.Error("If-condition is malformed.", nil) } // Check the rest for { wrapper, tag_args, err := doc.WrapUntilTag("elif", "else", "endif") if err != nil { return nil, err } if_node.wrappers = append(if_node.wrappers, wrapper) if wrapper.Endtag == "elif" { // elif can take a condition condition, err := tag_args.ParseExpression() if err != nil { return nil, err } if_node.conditions = append(if_node.conditions, condition) if tag_args.Remaining() > 0 { return nil, tag_args.Error("Elif-condition is malformed.", nil) } } else { if tag_args.Count() > 0 { // else/endif can't take any conditions return nil, tag_args.Error("Arguments not allowed here.", nil) } } if wrapper.Endtag == "endif" { break } } return if_node, nil } func init() { RegisterTag("if", tagIfParser) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_for.go�������������������������������������������0000644�0610621�0607500�00000007401�13172163432�024106� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagForNode struct { key string value string // only for maps: for key, value in map object_evaluator IEvaluator reversed bool bodyWrapper *NodeWrapper emptyWrapper *NodeWrapper } type tagForLoopInformation struct { Counter int Counter0 int Revcounter int Revcounter0 int First bool Last bool Parentloop *tagForLoopInformation } func (node *tagForNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) (forError *Error) { // Backup forloop (as parentloop in public context), key-name and value-name forCtx := NewChildExecutionContext(ctx) parentloop := forCtx.Private["forloop"] // Create loop struct loopInfo := &tagForLoopInformation{ First: true, } // Is it a loop in a loop? if parentloop != nil { loopInfo.Parentloop = parentloop.(*tagForLoopInformation) } // Register loopInfo in public context forCtx.Private["forloop"] = loopInfo obj, err := node.object_evaluator.Evaluate(forCtx) if err != nil { return err } obj.IterateOrder(func(idx, count int, key, value *Value) bool { // There's something to iterate over (correct type and at least 1 item) // Update loop infos and public context forCtx.Private[node.key] = key if value != nil { forCtx.Private[node.value] = value } loopInfo.Counter = idx + 1 loopInfo.Counter0 = idx if idx == 1 { loopInfo.First = false } if idx+1 == count { loopInfo.Last = true } loopInfo.Revcounter = count - idx // TODO: Not sure about this, have to look it up loopInfo.Revcounter0 = count - (idx + 1) // TODO: Not sure about this, have to look it up // Render elements with updated context err := node.bodyWrapper.Execute(forCtx, buffer) if err != nil { forError = err return false } return true }, func() { // Nothing to iterate over (maybe wrong type or no items) if node.emptyWrapper != nil { err := node.emptyWrapper.Execute(forCtx, buffer) if err != nil { forError = err } } }, node.reversed) return nil } func tagForParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { for_node := &tagForNode{} // Arguments parsing var value_token *Token key_token := arguments.MatchType(TokenIdentifier) if key_token == nil { return nil, arguments.Error("Expected an key identifier as first argument for 'for'-tag", nil) } if arguments.Match(TokenSymbol, ",") != nil { // Value name is provided value_token = arguments.MatchType(TokenIdentifier) if value_token == nil { return nil, arguments.Error("Value name must be an identifier.", nil) } } if arguments.Match(TokenKeyword, "in") == nil { return nil, arguments.Error("Expected keyword 'in'.", nil) } object_evaluator, err := arguments.ParseExpression() if err != nil { return nil, err } for_node.object_evaluator = object_evaluator for_node.key = key_token.Val if value_token != nil { for_node.value = value_token.Val } if arguments.MatchOne(TokenIdentifier, "reversed") != nil { for_node.reversed = true } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed for-loop arguments.", nil) } // Body wrapping wrapper, endargs, err := doc.WrapUntilTag("empty", "endfor") if err != nil { return nil, err } for_node.bodyWrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } if wrapper.Endtag == "empty" { // if there's an else in the if-statement, we need the else-Block as well wrapper, endargs, err = doc.WrapUntilTag("endfor") if err != nil { return nil, err } for_node.emptyWrapper = wrapper if endargs.Count() > 0 { return nil, endargs.Error("Arguments not allowed here.", nil) } } return for_node, nil } func init() { RegisterTag("for", tagForParser) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_firstof.go���������������������������������������0000644�0610621�0607500�00000001666�13172163432�025003� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagFirstofNode struct { position *Token args []IEvaluator } func (node *tagFirstofNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { for _, arg := range node.args { val, err := arg.Evaluate(ctx) if err != nil { return err } if val.IsTrue() { if ctx.Autoescape && !arg.FilterApplied("safe") { val, err = ApplyFilter("escape", val, nil) if err != nil { return err } } buffer.WriteString(val.String()) return nil } } return nil } func tagFirstofParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { firstof_node := &tagFirstofNode{ position: start, } for arguments.Remaining() > 0 { node, err := arguments.ParseExpression() if err != nil { return nil, err } firstof_node.args = append(firstof_node.args, node) } return firstof_node, nil } func init() { RegisterTag("firstof", tagFirstofParser) } ��������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_filter.go����������������������������������������0000644�0610621�0607500�00000004023�13172163432�024602� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type nodeFilterCall struct { name string param_expr IEvaluator } type tagFilterNode struct { position *Token bodyWrapper *NodeWrapper filterChain []*nodeFilterCall } func (node *tagFilterNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { temp := bytes.NewBuffer(make([]byte, 0, 1024)) // 1 KiB size err := node.bodyWrapper.Execute(ctx, temp) if err != nil { return err } value := AsValue(temp.String()) for _, call := range node.filterChain { var param *Value if call.param_expr != nil { param, err = call.param_expr.Evaluate(ctx) if err != nil { return err } } else { param = AsValue(nil) } value, err = ApplyFilter(call.name, value, param) if err != nil { return ctx.Error(err.Error(), node.position) } } buffer.WriteString(value.String()) return nil } func tagFilterParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { filter_node := &tagFilterNode{ position: start, } wrapper, _, err := doc.WrapUntilTag("endfilter") if err != nil { return nil, err } filter_node.bodyWrapper = wrapper for arguments.Remaining() > 0 { filterCall := &nodeFilterCall{} name_token := arguments.MatchType(TokenIdentifier) if name_token == nil { return nil, arguments.Error("Expected a filter name (identifier).", nil) } filterCall.name = name_token.Val if arguments.MatchOne(TokenSymbol, ":") != nil { // Filter parameter // NOTICE: we can't use ParseExpression() here, because it would parse the next filter "|..." as well in the argument list expr, err := arguments.parseVariableOrLiteral() if err != nil { return nil, err } filterCall.param_expr = expr } filter_node.filterChain = append(filter_node.filterChain, filterCall) if arguments.MatchOne(TokenSymbol, "|") == nil { break } } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed filter-tag arguments.", nil) } return filter_node, nil } func init() { RegisterTag("filter", tagFilterParser) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_extends.go���������������������������������������0000644�0610621�0607500�00000002573�13172163432�024777� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagExtendsNode struct { filename string } func (node *tagExtendsNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { return nil } func tagExtendsParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { extends_node := &tagExtendsNode{} if doc.template.level > 1 { return nil, arguments.Error("The 'extends' tag can only defined on root level.", start) } if doc.template.parent != nil { // Already one parent return nil, arguments.Error("This template has already one parent.", start) } if filename_token := arguments.MatchType(TokenString); filename_token != nil { // prepared, static template // Get parent's filename parent_filename := doc.template.set.resolveFilename(doc.template, filename_token.Val) // Parse the parent parent_template, err := doc.template.set.FromFile(parent_filename) if err != nil { return nil, err.(*Error) } // Keep track of things parent_template.child = doc.template doc.template.parent = parent_template extends_node.filename = parent_filename } else { return nil, arguments.Error("Tag 'extends' requires a template filename as string.", nil) } if arguments.Remaining() > 0 { return nil, arguments.Error("Tag 'extends' does only take 1 argument.", nil) } return extends_node, nil } func init() { RegisterTag("extends", tagExtendsParser) } �������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_cycle.go�����������������������������������������0000644�0610621�0607500�00000004063�13172163432�024420� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagCycleValue struct { node *tagCycleNode value *Value } type tagCycleNode struct { position *Token args []IEvaluator idx int as_name string silent bool } func (cv *tagCycleValue) String() string { return cv.value.String() } func (node *tagCycleNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { item := node.args[node.idx%len(node.args)] node.idx++ val, err := item.Evaluate(ctx) if err != nil { return err } if t, ok := val.Interface().(*tagCycleValue); ok { // {% cycle "test1" "test2" // {% cycle cycleitem %} // Update the cycle value with next value item := t.node.args[t.node.idx%len(t.node.args)] t.node.idx++ val, err := item.Evaluate(ctx) if err != nil { return err } t.value = val if !t.node.silent { buffer.WriteString(val.String()) } } else { // Regular call cycle_value := &tagCycleValue{ node: node, value: val, } if node.as_name != "" { ctx.Private[node.as_name] = cycle_value } if !node.silent { buffer.WriteString(val.String()) } } return nil } // HINT: We're not supporting the old comma-seperated list of expresions argument-style func tagCycleParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { cycle_node := &tagCycleNode{ position: start, } for arguments.Remaining() > 0 { node, err := arguments.ParseExpression() if err != nil { return nil, err } cycle_node.args = append(cycle_node.args, node) if arguments.MatchOne(TokenKeyword, "as") != nil { // as name_token := arguments.MatchType(TokenIdentifier) if name_token == nil { return nil, arguments.Error("Name (identifier) expected after 'as'.", nil) } cycle_node.as_name = name_token.Val if arguments.MatchOne(TokenIdentifier, "silent") != nil { cycle_node.silent = true } // Now we're finished break } } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed cycle-tag.", nil) } return cycle_node, nil } func init() { RegisterTag("cycle", tagCycleParser) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_comment.go���������������������������������������0000644�0610621�0607500�00000001227�13172163432�024762� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagCommentNode struct{} func (node *tagCommentNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { return nil } func tagCommentParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { comment_node := &tagCommentNode{} // TODO: Process the endtag's arguments (see django 'comment'-tag documentation) _, _, err := doc.WrapUntilTag("endcomment") if err != nil { return nil, err } if arguments.Count() != 0 { return nil, arguments.Error("Tag 'comment' does not take any argument.", nil) } return comment_node, nil } func init() { RegisterTag("comment", tagCommentParser) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_block.go�����������������������������������������0000644�0610621�0607500�00000004660�13172163432�024416� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" ) type tagBlockNode struct { name string } func (node *tagBlockNode) getBlockWrapperByName(tpl *Template) *NodeWrapper { var t *NodeWrapper if tpl.child != nil { // First ask the child for the block t = node.getBlockWrapperByName(tpl.child) } if t == nil { // Child has no block, lets look up here at parent t = tpl.blocks[node.name] } return t } func (node *tagBlockNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { tpl := ctx.template if tpl == nil { panic("internal error: tpl == nil") } // Determine the block to execute block_wrapper := node.getBlockWrapperByName(tpl) if block_wrapper == nil { // fmt.Printf("could not find: %s\n", node.name) return ctx.Error("internal error: block_wrapper == nil in tagBlockNode.Execute()", nil) } err := block_wrapper.Execute(ctx, buffer) if err != nil { return err } // TODO: Add support for {{ block.super }} return nil } func tagBlockParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { if arguments.Count() == 0 { return nil, arguments.Error("Tag 'block' requires an identifier.", nil) } name_token := arguments.MatchType(TokenIdentifier) if name_token == nil { return nil, arguments.Error("First argument for tag 'block' must be an identifier.", nil) } if arguments.Remaining() != 0 { return nil, arguments.Error("Tag 'block' takes exactly 1 argument (an identifier).", nil) } wrapper, endtagargs, err := doc.WrapUntilTag("endblock") if err != nil { return nil, err } if endtagargs.Remaining() > 0 { endtagname_token := endtagargs.MatchType(TokenIdentifier) if endtagname_token != nil { if endtagname_token.Val != name_token.Val { return nil, endtagargs.Error(fmt.Sprintf("Name for 'endblock' must equal to 'block'-tag's name ('%s' != '%s').", name_token.Val, endtagname_token.Val), nil) } } if endtagname_token == nil || endtagargs.Remaining() > 0 { return nil, endtagargs.Error("Either no or only one argument (identifier) allowed for 'endblock'.", nil) } } tpl := doc.template if tpl == nil { panic("internal error: tpl == nil") } _, has_block := tpl.blocks[name_token.Val] if !has_block { tpl.blocks[name_token.Val] = wrapper } else { return nil, arguments.Error(fmt.Sprintf("Block named '%s' already defined", name_token.Val), nil) } return &tagBlockNode{name: name_token.Val}, nil } func init() { RegisterTag("block", tagBlockParser) } ��������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags_autoescape.go������������������������������������0000644�0610621�0607500�00000002335�13172163432�025452� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type tagAutoescapeNode struct { wrapper *NodeWrapper autoescape bool } func (node *tagAutoescapeNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { old := ctx.Autoescape ctx.Autoescape = node.autoescape err := node.wrapper.Execute(ctx, buffer) if err != nil { return err } ctx.Autoescape = old return nil } func tagAutoescapeParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { autoescape_node := &tagAutoescapeNode{} wrapper, _, err := doc.WrapUntilTag("endautoescape") if err != nil { return nil, err } autoescape_node.wrapper = wrapper mode_token := arguments.MatchType(TokenIdentifier) if mode_token == nil { return nil, arguments.Error("A mode is required for autoescape-tag.", nil) } if mode_token.Val == "on" { autoescape_node.autoescape = true } else if mode_token.Val == "off" { autoescape_node.autoescape = false } else { return nil, arguments.Error("Only 'on' or 'off' is valid as an autoescape-mode.", nil) } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed autoescape-tag arguments.", nil) } return autoescape_node, nil } func init() { RegisterTag("autoescape", tagAutoescapeParser) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/tags.go�����������������������������������������������0000644�0610621�0607500�00000007117�13172163432�023244� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 /* Incomplete: ----------- verbatim (only the "name" argument is missing for verbatim) Reconsideration: ---------------- debug (reason: not sure what to output yet) regroup / Grouping on other properties (reason: maybe too python-specific; not sure how useful this would be in Go) Following built-in tags wont be added: -------------------------------------- csrf_token (reason: web-framework specific) load (reason: python-specific) url (reason: web-framework specific) */ import ( "fmt" ) type INodeTag interface { INode } // This is the function signature of the tag's parser you will have // to implement in order to create a new tag. // // 'doc' is providing access to the whole document while 'arguments' // is providing access to the user's arguments to the tag: // // {% your_tag_name some "arguments" 123 %} // // start_token will be the *Token with the tag's name in it (here: your_tag_name). // // Please see the Parser documentation on how to use the parser. // See RegisterTag()'s documentation for more information about // writing a tag as well. type TagParser func(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) type tag struct { name string parser TagParser } var tags map[string]*tag func init() { tags = make(map[string]*tag) } // Registers a new tag. If there's already a tag with the same // name, RegisterTag will panic. You usually want to call this // function in the tag's init() function: // http://golang.org/doc/effective_go.html#init // // See http://www.florian-schlachter.de/post/pongo2/ for more about // writing filters and tags. func RegisterTag(name string, parserFn TagParser) { _, existing := tags[name] if existing { panic(fmt.Sprintf("Tag with name '%s' is already registered.", name)) } tags[name] = &tag{ name: name, parser: parserFn, } } // Replaces an already registered tag with a new implementation. Use this // function with caution since it allows you to change existing tag behaviour. func ReplaceTag(name string, parserFn TagParser) { _, existing := tags[name] if !existing { panic(fmt.Sprintf("Tag with name '%s' does not exist (therefore cannot be overridden).", name)) } tags[name] = &tag{ name: name, parser: parserFn, } } // Tag = "{%" IDENT ARGS "%}" func (p *Parser) parseTagElement() (INodeTag, *Error) { p.Consume() // consume "{%" token_name := p.MatchType(TokenIdentifier) // Check for identifier if token_name == nil { return nil, p.Error("Tag name must be an identifier.", nil) } // Check for the existing tag tag, exists := tags[token_name.Val] if !exists { // Does not exists return nil, p.Error(fmt.Sprintf("Tag '%s' not found (or beginning tag not provided)", token_name.Val), token_name) } // Check sandbox tag restriction if _, is_banned := p.template.set.bannedTags[token_name.Val]; is_banned { return nil, p.Error(fmt.Sprintf("Usage of tag '%s' is not allowed (sandbox restriction active).", token_name.Val), token_name) } args_token := make([]*Token, 0) for p.Peek(TokenSymbol, "%}") == nil && p.Remaining() > 0 { // Add token to args args_token = append(args_token, p.Current()) p.Consume() // next token } // EOF? if p.Remaining() == 0 { return nil, p.Error("Unexpectedly reached EOF, no tag end found.", p.last_token) } p.Match(TokenSymbol, "%}") arg_parser := newParser(p.name, args_token, p.template) if len(args_token) == 0 { // This is done to have nice EOF error messages arg_parser.last_token = token_name } p.template.level++ defer func() { p.template.level-- }() return tag.parser(p, token_name, arg_parser) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/pongo2_test.go����������������������������������������0000644�0610621�0607500�00000003151�13172163432�024543� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "testing" . "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { TestingT(t) } type TestSuite struct { tpl *Template } var ( _ = Suite(&TestSuite{}) test_suite2 = NewSet("test suite 2") ) func parseTemplate(s string, c Context) string { t, err := test_suite2.FromString(s) if err != nil { panic(err) } out, err := t.Execute(c) if err != nil { panic(err) } return out } func parseTemplateFn(s string, c Context) func() { return func() { parseTemplate(s, c) } } func (s *TestSuite) TestMisc(c *C) { // Must // TODO: Add better error message (see issue #18) c.Check(func() { Must(test_suite2.FromFile("template_tests/inheritance/base2.tpl")) }, PanicMatches, `\[Error \(where: fromfile\) in template_tests/inheritance/doesnotexist.tpl | Line 1 Col 12 near 'doesnotexist.tpl'\] open template_tests/inheritance/doesnotexist.tpl: no such file or directory`) // Context c.Check(parseTemplateFn("", Context{"'illegal": nil}), PanicMatches, ".*not a valid identifier.*") // Registers c.Check(func() { RegisterFilter("escape", nil) }, PanicMatches, ".*is already registered.*") c.Check(func() { RegisterTag("for", nil) }, PanicMatches, ".*is already registered.*") // ApplyFilter v, err := ApplyFilter("title", AsValue("this is a title"), nil) if err != nil { c.Fatal(err) } c.Check(v.String(), Equals, "This Is A Title") c.Check(func() { _, err := ApplyFilter("doesnotexist", nil, nil) if err != nil { panic(err) } }, PanicMatches, `\[Error \(where: applyfilter\)\] Filter with name 'doesnotexist' not found.`) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/pongo2_template_test.go�������������������������������0000644�0610621�0607500�00000030502�13172163432�026436� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" "io/ioutil" "path/filepath" "regexp" "strings" "testing" "time" ) var admin_list = []string{"user2"} var time1 = time.Date(2014, 06, 10, 15, 30, 15, 0, time.UTC) var time2 = time.Date(2011, 03, 21, 8, 37, 56, 12, time.UTC) type post struct { Text string Created time.Time } type user struct { Name string Validated bool } type comment struct { Author *user Date time.Time Text string } func is_admin(u *user) bool { for _, a := range admin_list { if a == u.Name { return true } } return false } func (u *user) Is_admin() *Value { return AsValue(is_admin(u)) } func (u *user) Is_admin2() bool { return is_admin(u) } func (p *post) String() string { return ":-)" } /* * Start setup sandbox */ type tagSandboxDemoTag struct { } func (node *tagSandboxDemoTag) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { buffer.WriteString("hello") return nil } func tagSandboxDemoTagParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { return &tagSandboxDemoTag{}, nil } func BannedFilterFn(in *Value, params *Value) (*Value, *Error) { return in, nil } func init() { DefaultSet.Debug = true RegisterFilter("banned_filter", BannedFilterFn) RegisterFilter("unbanned_filter", BannedFilterFn) RegisterTag("banned_tag", tagSandboxDemoTagParser) RegisterTag("unbanned_tag", tagSandboxDemoTagParser) DefaultSet.BanFilter("banned_filter") DefaultSet.BanTag("banned_tag") // Allow different kind of levels inside template_tests/ abs_path, err := filepath.Abs("./template_tests/*") if err != nil { panic(err) } DefaultSet.SandboxDirectories = append(DefaultSet.SandboxDirectories, abs_path) abs_path, err = filepath.Abs("./template_tests/*/*") if err != nil { panic(err) } DefaultSet.SandboxDirectories = append(DefaultSet.SandboxDirectories, abs_path) abs_path, err = filepath.Abs("./template_tests/*/*/*") if err != nil { panic(err) } DefaultSet.SandboxDirectories = append(DefaultSet.SandboxDirectories, abs_path) // Allow pongo2 temp files DefaultSet.SandboxDirectories = append(DefaultSet.SandboxDirectories, "/tmp/pongo2_*") f, err := ioutil.TempFile("/tmp/", "pongo2_") if err != nil { panic("cannot write to /tmp/") } f.Write([]byte("Hello from pongo2")) DefaultSet.Globals["temp_file"] = f.Name() } /* * End setup sandbox */ var tplContext = Context{ "number": 11, "simple": map[string]interface{}{ "number": 42, "name": "john doe", "included_file": "INCLUDES.helper", "nil": nil, "uint": uint(8), "float": float64(3.1415), "str": "string", "chinese_hello_world": "你好世界", "bool_true": true, "bool_false": false, "newline_text": `this is a text with a new line in it`, "long_text": `This is a simple text. This too, as a paragraph. Right? Yep!`, "escape_js_test": `escape sequences \r\n\'\" special chars "?!=$<>`, "one_item_list": []int{99}, "multiple_item_list": []int{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}, "misc_list": []interface{}{"Hello", 99, 3.14, "good"}, "escape_text": "This is \\a Test. \"Yep\". 'Yep'.", "xss": "<script>alert(\"uh oh\");</script>", "intmap": map[int]string{ 1: "one", 2: "two", 5: "five", }, "func_add": func(a, b int) int { return a + b }, "func_add_iface": func(a, b interface{}) interface{} { return a.(int) + b.(int) }, "func_variadic": func(msg string, args ...interface{}) string { return fmt.Sprintf(msg, args...) }, "func_variadic_sum_int": func(args ...int) int { // Create a sum s := 0 for _, i := range args { s += i } return s }, "func_variadic_sum_int2": func(args ...*Value) *Value { // Create a sum s := 0 for _, i := range args { s += i.Integer() } return AsValue(s) }, }, "complex": map[string]interface{}{ "is_admin": is_admin, "post": post{ Text: "<h2>Hello!</h2><p>Welcome to my new blog page. I'm using pongo2 which supports {{ variables }} and {% tags %}.</p>", Created: time2, }, "comments": []*comment{ &comment{ Author: &user{ Name: "user1", Validated: true, }, Date: time1, Text: "\"pongo2 is nice!\"", }, &comment{ Author: &user{ Name: "user2", Validated: true, }, Date: time2, Text: "comment2 with <script>unsafe</script> tags in it", }, &comment{ Author: &user{ Name: "user3", Validated: false, }, Date: time1, Text: "<b>hello!</b> there", }, }, "comments2": []*comment{ &comment{ Author: &user{ Name: "user1", Validated: true, }, Date: time2, Text: "\"pongo2 is nice!\"", }, &comment{ Author: &user{ Name: "user1", Validated: true, }, Date: time1, Text: "comment2 with <script>unsafe</script> tags in it", }, &comment{ Author: &user{ Name: "user3", Validated: false, }, Date: time1, Text: "<b>hello!</b> there", }, }, }, } func TestTemplates(t *testing.T) { debug = true // Add a global to the default set Globals["this_is_a_global_variable"] = "this is a global text" matches, err := filepath.Glob("./template_tests/*.tpl") if err != nil { t.Fatal(err) } for idx, match := range matches { t.Logf("[Template %3d] Testing '%s'", idx+1, match) tpl, err := FromFile(match) if err != nil { t.Fatalf("Error on FromFile('%s'): %s", match, err.Error()) } test_filename := fmt.Sprintf("%s.out", match) test_out, rerr := ioutil.ReadFile(test_filename) if rerr != nil { t.Fatalf("Error on ReadFile('%s'): %s", test_filename, rerr.Error()) } tpl_out, err := tpl.ExecuteBytes(tplContext) if err != nil { t.Fatalf("Error on Execute('%s'): %s", match, err.Error()) } if bytes.Compare(test_out, tpl_out) != 0 { t.Logf("Template (rendered) '%s': '%s'", match, tpl_out) err_filename := filepath.Base(fmt.Sprintf("%s.error", match)) err := ioutil.WriteFile(err_filename, []byte(tpl_out), 0600) if err != nil { t.Fatalf(err.Error()) } t.Logf("get a complete diff with command: 'diff -ya %s %s'", test_filename, err_filename) t.Errorf("Failed: test_out != tpl_out for %s", match) } } } func TestExecutionErrors(t *testing.T) { debug = true matches, err := filepath.Glob("./template_tests/*-execution.err") if err != nil { t.Fatal(err) } for idx, match := range matches { t.Logf("[Errors %3d] Testing '%s'", idx+1, match) test_data, err := ioutil.ReadFile(match) tests := strings.Split(string(test_data), "\n") check_filename := fmt.Sprintf("%s.out", match) check_data, err := ioutil.ReadFile(check_filename) if err != nil { t.Fatalf("Error on ReadFile('%s'): %s", check_filename, err.Error()) } checks := strings.Split(string(check_data), "\n") if len(checks) != len(tests) { t.Fatal("Template lines != Checks lines") } for idx, test := range tests { if strings.TrimSpace(test) == "" { continue } if strings.TrimSpace(checks[idx]) == "" { t.Fatalf("[%s Line %d] Check is empty (must contain an regular expression).", match, idx+1) } tpl, err := FromString(test) if err != nil { t.Fatalf("Error on FromString('%s'): %s", test, err.Error()) } _, err = tpl.ExecuteBytes(tplContext) if err == nil { t.Fatalf("[%s Line %d] Expected error for (got none): %s", match, idx+1, tests[idx]) } re := regexp.MustCompile(fmt.Sprintf("^%s$", checks[idx])) if !re.MatchString(err.Error()) { t.Fatalf("[%s Line %d] Error for '%s' (err = '%s') does not match the (regexp-)check: %s", match, idx+1, test, err.Error(), checks[idx]) } } } } func TestCompilationErrors(t *testing.T) { debug = true matches, err := filepath.Glob("./template_tests/*-compilation.err") if err != nil { t.Fatal(err) } for idx, match := range matches { t.Logf("[Errors %3d] Testing '%s'", idx+1, match) test_data, err := ioutil.ReadFile(match) tests := strings.Split(string(test_data), "\n") check_filename := fmt.Sprintf("%s.out", match) check_data, err := ioutil.ReadFile(check_filename) if err != nil { t.Fatalf("Error on ReadFile('%s'): %s", check_filename, err.Error()) } checks := strings.Split(string(check_data), "\n") if len(checks) != len(tests) { t.Fatal("Template lines != Checks lines") } for idx, test := range tests { if strings.TrimSpace(test) == "" { continue } if strings.TrimSpace(checks[idx]) == "" { t.Fatalf("[%s Line %d] Check is empty (must contain an regular expression).", match, idx+1) } _, err = FromString(test) if err == nil { t.Fatalf("[%s | Line %d] Expected error for (got none): %s", match, idx+1, tests[idx]) } re := regexp.MustCompile(fmt.Sprintf("^%s$", checks[idx])) if !re.MatchString(err.Error()) { t.Fatalf("[%s | Line %d] Error for '%s' (err = '%s') does not match the (regexp-)check: %s", match, idx+1, test, err.Error(), checks[idx]) } } } } func TestBaseDirectory(t *testing.T) { mustStr := "Hello from template_tests/base_dir_test/" s := NewSet("test set with base directory") s.Globals["base_directory"] = "template_tests/base_dir_test/" if err := s.SetBaseDirectory(s.Globals["base_directory"].(string)); err != nil { t.Fatal(err) } matches, err := filepath.Glob("./template_tests/base_dir_test/subdir/*") if err != nil { t.Fatal(err) } for _, match := range matches { match = strings.Replace(match, "template_tests/base_dir_test/", "", -1) tpl, err := s.FromFile(match) if err != nil { t.Fatal(err) } out, err := tpl.Execute(nil) if err != nil { t.Fatal(err) } if out != mustStr { t.Errorf("%s: out ('%s') != mustStr ('%s')", match, out, mustStr) } } } func BenchmarkCache(b *testing.B) { cache_set := NewSet("cache set") for i := 0; i < b.N; i++ { tpl, err := cache_set.FromCache("template_tests/complex.tpl") if err != nil { b.Fatal(err) } _, err = tpl.ExecuteBytes(tplContext) if err != nil { b.Fatal(err) } } } func BenchmarkCacheDebugOn(b *testing.B) { cache_debug_set := NewSet("cache set") cache_debug_set.Debug = true for i := 0; i < b.N; i++ { tpl, err := cache_debug_set.FromFile("template_tests/complex.tpl") if err != nil { b.Fatal(err) } _, err = tpl.ExecuteBytes(tplContext) if err != nil { b.Fatal(err) } } } func BenchmarkExecuteComplexWithSandboxActive(b *testing.B) { tpl, err := FromFile("template_tests/complex.tpl") if err != nil { b.Fatal(err) } b.ResetTimer() for i := 0; i < b.N; i++ { _, err = tpl.ExecuteBytes(tplContext) if err != nil { b.Fatal(err) } } } func BenchmarkCompileAndExecuteComplexWithSandboxActive(b *testing.B) { buf, err := ioutil.ReadFile("template_tests/complex.tpl") if err != nil { b.Fatal(err) } preloadedTpl := string(buf) b.ResetTimer() for i := 0; i < b.N; i++ { tpl, err := FromString(preloadedTpl) if err != nil { b.Fatal(err) } _, err = tpl.ExecuteBytes(tplContext) if err != nil { b.Fatal(err) } } } func BenchmarkParallelExecuteComplexWithSandboxActive(b *testing.B) { tpl, err := FromFile("template_tests/complex.tpl") if err != nil { b.Fatal(err) } b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _, err := tpl.ExecuteBytes(tplContext) if err != nil { b.Fatal(err) } } }) } func BenchmarkExecuteComplexWithoutSandbox(b *testing.B) { s := NewSet("set without sandbox") tpl, err := s.FromFile("template_tests/complex.tpl") if err != nil { b.Fatal(err) } b.ResetTimer() for i := 0; i < b.N; i++ { _, err = tpl.ExecuteBytes(tplContext) if err != nil { b.Fatal(err) } } } func BenchmarkCompileAndExecuteComplexWithoutSandbox(b *testing.B) { buf, err := ioutil.ReadFile("template_tests/complex.tpl") if err != nil { b.Fatal(err) } preloadedTpl := string(buf) s := NewSet("set without sandbox") b.ResetTimer() for i := 0; i < b.N; i++ { tpl, err := s.FromString(preloadedTpl) if err != nil { b.Fatal(err) } _, err = tpl.ExecuteBytes(tplContext) if err != nil { b.Fatal(err) } } } func BenchmarkParallelExecuteComplexWithoutSandbox(b *testing.B) { s := NewSet("set without sandbox") tpl, err := s.FromFile("template_tests/complex.tpl") if err != nil { b.Fatal(err) } b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _, err := tpl.ExecuteBytes(tplContext) if err != nil { b.Fatal(err) } } }) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/pongo2_issues_test.go���������������������������������0000644�0610621�0607500�00000000474�13172163432�026143� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "testing" . "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func TestIssues(t *testing.T) { TestingT(t) } type IssueTestSuite struct{} var _ = Suite(&IssueTestSuite{}) func (s *TestSuite) TestIssues(c *C) { // Add a test for any issue c.Check(42, Equals, 42) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/pongo2.go���������������������������������������������0000644�0610621�0607500�00000000523�13172163432�023504� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 // Version string const Version = "v3" // Helper function which panics, if a Template couldn't // successfully parsed. This is how you would use it: // var baseTemplate = pongo2.Must(pongo2.FromFile("templates/base.html")) func Must(tpl *Template, err error) *Template { if err != nil { panic(err) } return tpl } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/parser_expression.go����������������������������������0000644�0610621�0607500�00000025110�13172163432�026052� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" "math" ) type Expression struct { // TODO: Add location token? expr1 IEvaluator expr2 IEvaluator op_token *Token } type relationalExpression struct { // TODO: Add location token? expr1 IEvaluator expr2 IEvaluator op_token *Token } type simpleExpression struct { negate bool negative_sign bool term1 IEvaluator term2 IEvaluator op_token *Token } type term struct { // TODO: Add location token? factor1 IEvaluator factor2 IEvaluator op_token *Token } type power struct { // TODO: Add location token? power1 IEvaluator power2 IEvaluator } func (expr *Expression) FilterApplied(name string) bool { return expr.expr1.FilterApplied(name) && (expr.expr2 == nil || (expr.expr2 != nil && expr.expr2.FilterApplied(name))) } func (expr *relationalExpression) FilterApplied(name string) bool { return expr.expr1.FilterApplied(name) && (expr.expr2 == nil || (expr.expr2 != nil && expr.expr2.FilterApplied(name))) } func (expr *simpleExpression) FilterApplied(name string) bool { return expr.term1.FilterApplied(name) && (expr.term2 == nil || (expr.term2 != nil && expr.term2.FilterApplied(name))) } func (t *term) FilterApplied(name string) bool { return t.factor1.FilterApplied(name) && (t.factor2 == nil || (t.factor2 != nil && t.factor2.FilterApplied(name))) } func (p *power) FilterApplied(name string) bool { return p.power1.FilterApplied(name) && (p.power2 == nil || (p.power2 != nil && p.power2.FilterApplied(name))) } func (expr *Expression) GetPositionToken() *Token { return expr.expr1.GetPositionToken() } func (expr *relationalExpression) GetPositionToken() *Token { return expr.expr1.GetPositionToken() } func (expr *simpleExpression) GetPositionToken() *Token { return expr.term1.GetPositionToken() } func (expr *term) GetPositionToken() *Token { return expr.factor1.GetPositionToken() } func (expr *power) GetPositionToken() *Token { return expr.power1.GetPositionToken() } func (expr *Expression) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *relationalExpression) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *simpleExpression) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *term) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *power) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { value, err := expr.Evaluate(ctx) if err != nil { return err } buffer.WriteString(value.String()) return nil } func (expr *Expression) Evaluate(ctx *ExecutionContext) (*Value, *Error) { v1, err := expr.expr1.Evaluate(ctx) if err != nil { return nil, err } if expr.expr2 != nil { v2, err := expr.expr2.Evaluate(ctx) if err != nil { return nil, err } switch expr.op_token.Val { case "and", "&&": return AsValue(v1.IsTrue() && v2.IsTrue()), nil case "or", "||": return AsValue(v1.IsTrue() || v2.IsTrue()), nil default: panic(fmt.Sprintf("unimplemented: %s", expr.op_token.Val)) } } else { return v1, nil } } func (expr *relationalExpression) Evaluate(ctx *ExecutionContext) (*Value, *Error) { v1, err := expr.expr1.Evaluate(ctx) if err != nil { return nil, err } if expr.expr2 != nil { v2, err := expr.expr2.Evaluate(ctx) if err != nil { return nil, err } switch expr.op_token.Val { case "<=": if v1.IsFloat() || v2.IsFloat() { return AsValue(v1.Float() <= v2.Float()), nil } else { return AsValue(v1.Integer() <= v2.Integer()), nil } case ">=": if v1.IsFloat() || v2.IsFloat() { return AsValue(v1.Float() >= v2.Float()), nil } else { return AsValue(v1.Integer() >= v2.Integer()), nil } case "==": return AsValue(v1.EqualValueTo(v2)), nil case ">": if v1.IsFloat() || v2.IsFloat() { return AsValue(v1.Float() > v2.Float()), nil } else { return AsValue(v1.Integer() > v2.Integer()), nil } case "<": if v1.IsFloat() || v2.IsFloat() { return AsValue(v1.Float() < v2.Float()), nil } else { return AsValue(v1.Integer() < v2.Integer()), nil } case "!=", "<>": return AsValue(!v1.EqualValueTo(v2)), nil case "in": return AsValue(v2.Contains(v1)), nil default: panic(fmt.Sprintf("unimplemented: %s", expr.op_token.Val)) } } else { return v1, nil } } func (expr *simpleExpression) Evaluate(ctx *ExecutionContext) (*Value, *Error) { t1, err := expr.term1.Evaluate(ctx) if err != nil { return nil, err } result := t1 if expr.negate { result = result.Negate() } if expr.negative_sign { if result.IsNumber() { switch { case result.IsFloat(): result = AsValue(-1 * result.Float()) case result.IsInteger(): result = AsValue(-1 * result.Integer()) default: panic("not possible") } } else { return nil, ctx.Error("Negative sign on a non-number expression", expr.GetPositionToken()) } } if expr.term2 != nil { t2, err := expr.term2.Evaluate(ctx) if err != nil { return nil, err } switch expr.op_token.Val { case "+": if result.IsFloat() || t2.IsFloat() { // Result will be a float return AsValue(result.Float() + t2.Float()), nil } else { // Result will be an integer return AsValue(result.Integer() + t2.Integer()), nil } case "-": if result.IsFloat() || t2.IsFloat() { // Result will be a float return AsValue(result.Float() - t2.Float()), nil } else { // Result will be an integer return AsValue(result.Integer() - t2.Integer()), nil } default: panic("unimplemented") } } return result, nil } func (t *term) Evaluate(ctx *ExecutionContext) (*Value, *Error) { f1, err := t.factor1.Evaluate(ctx) if err != nil { return nil, err } if t.factor2 != nil { f2, err := t.factor2.Evaluate(ctx) if err != nil { return nil, err } switch t.op_token.Val { case "*": if f1.IsFloat() || f2.IsFloat() { // Result will be float return AsValue(f1.Float() * f2.Float()), nil } // Result will be int return AsValue(f1.Integer() * f2.Integer()), nil case "/": if f1.IsFloat() || f2.IsFloat() { // Result will be float return AsValue(f1.Float() / f2.Float()), nil } // Result will be int return AsValue(f1.Integer() / f2.Integer()), nil case "%": // Result will be int return AsValue(f1.Integer() % f2.Integer()), nil default: panic("unimplemented") } } else { return f1, nil } } func (pw *power) Evaluate(ctx *ExecutionContext) (*Value, *Error) { p1, err := pw.power1.Evaluate(ctx) if err != nil { return nil, err } if pw.power2 != nil { p2, err := pw.power2.Evaluate(ctx) if err != nil { return nil, err } return AsValue(math.Pow(p1.Float(), p2.Float())), nil } else { return p1, nil } } func (p *Parser) parseFactor() (IEvaluator, *Error) { if p.Match(TokenSymbol, "(") != nil { expr, err := p.ParseExpression() if err != nil { return nil, err } if p.Match(TokenSymbol, ")") == nil { return nil, p.Error("Closing bracket expected after expression", nil) } return expr, nil } return p.parseVariableOrLiteralWithFilter() } func (p *Parser) parsePower() (IEvaluator, *Error) { pw := new(power) power1, err := p.parseFactor() if err != nil { return nil, err } pw.power1 = power1 if p.Match(TokenSymbol, "^") != nil { power2, err := p.parsePower() if err != nil { return nil, err } pw.power2 = power2 } if pw.power2 == nil { // Shortcut for faster evaluation return pw.power1, nil } return pw, nil } func (p *Parser) parseTerm() (IEvaluator, *Error) { return_term := new(term) factor1, err := p.parsePower() if err != nil { return nil, err } return_term.factor1 = factor1 for p.PeekOne(TokenSymbol, "*", "/", "%") != nil { if return_term.op_token != nil { // Create new sub-term return_term = &term{ factor1: return_term, } } op := p.Current() p.Consume() factor2, err := p.parsePower() if err != nil { return nil, err } return_term.op_token = op return_term.factor2 = factor2 } if return_term.op_token == nil { // Shortcut for faster evaluation return return_term.factor1, nil } return return_term, nil } func (p *Parser) parseSimpleExpression() (IEvaluator, *Error) { expr := new(simpleExpression) if sign := p.MatchOne(TokenSymbol, "+", "-"); sign != nil { if sign.Val == "-" { expr.negative_sign = true } } if p.Match(TokenSymbol, "!") != nil || p.Match(TokenKeyword, "not") != nil { expr.negate = true } term1, err := p.parseTerm() if err != nil { return nil, err } expr.term1 = term1 for p.PeekOne(TokenSymbol, "+", "-") != nil { if expr.op_token != nil { // New sub expr expr = &simpleExpression{ term1: expr, } } op := p.Current() p.Consume() term2, err := p.parseTerm() if err != nil { return nil, err } expr.term2 = term2 expr.op_token = op } if expr.negate == false && expr.negative_sign == false && expr.term2 == nil { // Shortcut for faster evaluation return expr.term1, nil } return expr, nil } func (p *Parser) parseRelationalExpression() (IEvaluator, *Error) { expr1, err := p.parseSimpleExpression() if err != nil { return nil, err } expr := &relationalExpression{ expr1: expr1, } if t := p.MatchOne(TokenSymbol, "==", "<=", ">=", "!=", "<>", ">", "<"); t != nil { expr2, err := p.parseRelationalExpression() if err != nil { return nil, err } expr.op_token = t expr.expr2 = expr2 } else if t := p.MatchOne(TokenKeyword, "in"); t != nil { expr2, err := p.parseSimpleExpression() if err != nil { return nil, err } expr.op_token = t expr.expr2 = expr2 } if expr.expr2 == nil { // Shortcut for faster evaluation return expr.expr1, nil } return expr, nil } func (p *Parser) ParseExpression() (IEvaluator, *Error) { rexpr1, err := p.parseRelationalExpression() if err != nil { return nil, err } exp := &Expression{ expr1: rexpr1, } if p.PeekOne(TokenSymbol, "&&", "||") != nil || p.PeekOne(TokenKeyword, "and", "or") != nil { op := p.Current() p.Consume() expr2, err := p.ParseExpression() if err != nil { return nil, err } exp.expr2 = expr2 exp.op_token = op } if exp.expr2 == nil { // Shortcut for faster evaluation return exp.expr1, nil } return exp, nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/parser_document.go������������������������������������0000644�0610621�0607500�00000002067�13172163432�025477� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 // Doc = { ( Filter | Tag | HTML ) } func (p *Parser) parseDocElement() (INode, *Error) { t := p.Current() switch t.Typ { case TokenHTML: p.Consume() // consume HTML element return &nodeHTML{token: t}, nil case TokenSymbol: switch t.Val { case "{{": // parse variable variable, err := p.parseVariableElement() if err != nil { return nil, err } return variable, nil case "{%": // parse tag tag, err := p.parseTagElement() if err != nil { return nil, err } return tag, nil } } return nil, p.Error("Unexpected token (only HTML/tags/filters in templates allowed)", t) } func (tpl *Template) parse() *Error { tpl.parser = newParser(tpl.name, tpl.tokens, tpl) doc, err := tpl.parser.parseDocument() if err != nil { return err } tpl.root = doc return nil } func (p *Parser) parseDocument() (*nodeDocument, *Error) { doc := &nodeDocument{} for p.Remaining() > 0 { node, err := p.parseDocElement() if err != nil { return nil, err } doc.Nodes = append(doc.Nodes, node) } return doc, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/parser.go���������������������������������������������0000644�0610621�0607500�00000014425�13172163432�023602� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" "fmt" "strings" ) type INode interface { Execute(*ExecutionContext, *bytes.Buffer) *Error } type IEvaluator interface { INode GetPositionToken() *Token Evaluate(*ExecutionContext) (*Value, *Error) FilterApplied(name string) bool } // The parser provides you a comprehensive and easy tool to // work with the template document and arguments provided by // the user for your custom tag. // // The parser works on a token list which will be provided by pongo2. // A token is a unit you can work with. Tokens are either of type identifier, // string, number, keyword, HTML or symbol. // // (See Token's documentation for more about tokens) type Parser struct { name string idx int tokens []*Token last_token *Token // if the parser parses a template document, here will be // a reference to it (needed to access the template through Tags) template *Template } // Creates a new parser to parse tokens. // Used inside pongo2 to parse documents and to provide an easy-to-use // parser for tag authors func newParser(name string, tokens []*Token, template *Template) *Parser { p := &Parser{ name: name, tokens: tokens, template: template, } if len(tokens) > 0 { p.last_token = tokens[len(tokens)-1] } return p } // Consume one token. It will be gone forever. func (p *Parser) Consume() { p.ConsumeN(1) } // Consume N tokens. They will be gone forever. func (p *Parser) ConsumeN(count int) { p.idx += count } // Returns the current token. func (p *Parser) Current() *Token { return p.Get(p.idx) } // Returns the CURRENT token if the given type matches. // Consumes this token on success. func (p *Parser) MatchType(typ TokenType) *Token { if t := p.PeekType(typ); t != nil { p.Consume() return t } return nil } // Returns the CURRENT token if the given type AND value matches. // Consumes this token on success. func (p *Parser) Match(typ TokenType, val string) *Token { if t := p.Peek(typ, val); t != nil { p.Consume() return t } return nil } // Returns the CURRENT token if the given type AND *one* of // the given values matches. // Consumes this token on success. func (p *Parser) MatchOne(typ TokenType, vals ...string) *Token { for _, val := range vals { if t := p.Peek(typ, val); t != nil { p.Consume() return t } } return nil } // Returns the CURRENT token if the given type matches. // It DOES NOT consume the token. func (p *Parser) PeekType(typ TokenType) *Token { return p.PeekTypeN(0, typ) } // Returns the CURRENT token if the given type AND value matches. // It DOES NOT consume the token. func (p *Parser) Peek(typ TokenType, val string) *Token { return p.PeekN(0, typ, val) } // Returns the CURRENT token if the given type AND *one* of // the given values matches. // It DOES NOT consume the token. func (p *Parser) PeekOne(typ TokenType, vals ...string) *Token { for _, v := range vals { t := p.PeekN(0, typ, v) if t != nil { return t } } return nil } // Returns the tokens[current position + shift] token if the // given type AND value matches for that token. // DOES NOT consume the token. func (p *Parser) PeekN(shift int, typ TokenType, val string) *Token { t := p.Get(p.idx + shift) if t != nil { if t.Typ == typ && t.Val == val { return t } } return nil } // Returns the tokens[current position + shift] token if the given type matches. // DOES NOT consume the token for that token. func (p *Parser) PeekTypeN(shift int, typ TokenType) *Token { t := p.Get(p.idx + shift) if t != nil { if t.Typ == typ { return t } } return nil } // Returns the UNCONSUMED token count. func (p *Parser) Remaining() int { return len(p.tokens) - p.idx } // Returns the total token count. func (p *Parser) Count() int { return len(p.tokens) } // Returns tokens[i] or NIL (if i >= len(tokens)) func (p *Parser) Get(i int) *Token { if i < len(p.tokens) { return p.tokens[i] } return nil } // Returns tokens[current-position + shift] or NIL // (if (current-position + i) >= len(tokens)) func (p *Parser) GetR(shift int) *Token { i := p.idx + shift return p.Get(i) } // Produces a nice error message and returns an error-object. // The 'token'-argument is optional. If provided, it will take // the token's position information. If not provided, it will // automatically use the CURRENT token's position information. func (p *Parser) Error(msg string, token *Token) *Error { if token == nil { // Set current token token = p.Current() if token == nil { // Set to last token if len(p.tokens) > 0 { token = p.tokens[len(p.tokens)-1] } } } var line, col int if token != nil { line = token.Line col = token.Col } return &Error{ Template: p.template, Filename: p.name, Sender: "parser", Line: line, Column: col, Token: token, ErrorMsg: msg, } } // Wraps all nodes between starting tag and "{% endtag %}" and provides // one simple interface to execute the wrapped nodes. // It returns a parser to process provided arguments to the tag. func (p *Parser) WrapUntilTag(names ...string) (*NodeWrapper, *Parser, *Error) { wrapper := &NodeWrapper{} tagArgs := make([]*Token, 0) for p.Remaining() > 0 { // New tag, check whether we have to stop wrapping here if p.Peek(TokenSymbol, "{%") != nil { tag_ident := p.PeekTypeN(1, TokenIdentifier) if tag_ident != nil { // We've found a (!) end-tag found := false for _, n := range names { if tag_ident.Val == n { found = true break } } // We only process the tag if we've found an end tag if found { // Okay, endtag found. p.ConsumeN(2) // '{%' tagname for { if p.Match(TokenSymbol, "%}") != nil { // Okay, end the wrapping here wrapper.Endtag = tag_ident.Val return wrapper, newParser(p.template.name, tagArgs, p.template), nil } else { t := p.Current() p.Consume() if t == nil { return nil, nil, p.Error("Unexpected EOF.", p.last_token) } tagArgs = append(tagArgs, t) } } } } } // Otherwise process next element to be wrapped node, err := p.parseDocElement() if err != nil { return nil, nil, err } wrapper.nodes = append(wrapper.nodes, node) } return nil, nil, p.Error(fmt.Sprintf("Unexpected EOF, expected tag %s.", strings.Join(names, " or ")), p.last_token) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/nodes_wrapper.go��������������������������������������0000644�0610621�0607500�00000000463�13172163432�025153� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type NodeWrapper struct { Endtag string nodes []INode } func (wrapper *NodeWrapper) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { for _, n := range wrapper.nodes { err := n.Execute(ctx, buffer) if err != nil { return err } } return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/nodes_html.go�����������������������������������������0000644�0610621�0607500�00000000315�13172163432�024433� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) type nodeHTML struct { token *Token } func (n *nodeHTML) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { buffer.WriteString(n.token.Val) return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/nodes.go����������������������������������������������0000644�0610621�0607500�00000000462�13172163432�023412� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bytes" ) // The root document type nodeDocument struct { Nodes []INode } func (doc *nodeDocument) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error { for _, n := range doc.Nodes { err := n.Execute(ctx, buffer) if err != nil { return err } } return nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/lexer.go����������������������������������������������0000644�0610621�0607500�00000017625�13172163432�023432� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "fmt" "strings" "unicode/utf8" ) const ( TokenError = iota EOF TokenHTML TokenKeyword TokenIdentifier TokenString TokenNumber TokenSymbol ) var ( tokenSpaceChars = " \n\r\t" tokenIdentifierChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_" tokenIdentifierCharsWithDigits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789" tokenDigits = "0123456789" // Available symbols in pongo2 (within filters/tag) TokenSymbols = []string{ // 3-Char symbols // 2-Char symbols "==", ">=", "<=", "&&", "||", "{{", "}}", "{%", "%}", "!=", "<>", // 1-Char symbol "(", ")", "+", "-", "*", "<", ">", "/", "^", ",", ".", "!", "|", ":", "=", "%", } // Available keywords in pongo2 TokenKeywords = []string{"in", "and", "or", "not", "true", "false", "as", "export"} ) type TokenType int type Token struct { Filename string Typ TokenType Val string Line int Col int } type lexerStateFn func() lexerStateFn type lexer struct { name string input string start int // start pos of the item pos int // current pos width int // width of last rune tokens []*Token errored bool startline int startcol int line int col int in_verbatim bool verbatim_name string } func (t *Token) String() string { val := t.Val if len(val) > 1000 { val = fmt.Sprintf("%s...%s", val[:10], val[len(val)-5:len(val)]) } typ := "" switch t.Typ { case TokenHTML: typ = "HTML" case TokenError: typ = "Error" case TokenIdentifier: typ = "Identifier" case TokenKeyword: typ = "Keyword" case TokenNumber: typ = "Number" case TokenString: typ = "String" case TokenSymbol: typ = "Symbol" default: typ = "Unknown" } return fmt.Sprintf("<Token Typ=%s (%d) Val='%s' Line=%d Col=%d>", typ, t.Typ, val, t.Line, t.Col) } func lex(name string, input string) ([]*Token, *Error) { l := &lexer{ name: name, input: input, tokens: make([]*Token, 0, 100), line: 1, col: 1, startline: 1, startcol: 1, } l.run() if l.errored { errtoken := l.tokens[len(l.tokens)-1] return nil, &Error{ Filename: name, Line: errtoken.Line, Column: errtoken.Col, Sender: "lexer", ErrorMsg: errtoken.Val, } } return l.tokens, nil } func (l *lexer) value() string { return l.input[l.start:l.pos] } func (l *lexer) length() int { return l.pos - l.start } func (l *lexer) emit(t TokenType) { tok := &Token{ Filename: l.name, Typ: t, Val: l.value(), Line: l.startline, Col: l.startcol, } if t == TokenString { // Escape sequence \" in strings tok.Val = strings.Replace(tok.Val, `\"`, `"`, -1) tok.Val = strings.Replace(tok.Val, `\\`, `\`, -1) } l.tokens = append(l.tokens, tok) l.start = l.pos l.startline = l.line l.startcol = l.col } func (l *lexer) next() rune { if l.pos >= len(l.input) { l.width = 0 return EOF } r, w := utf8.DecodeRuneInString(l.input[l.pos:]) l.width = w l.pos += l.width l.col += l.width return r } func (l *lexer) backup() { l.pos -= l.width l.col -= l.width } func (l *lexer) peek() rune { r := l.next() l.backup() return r } func (l *lexer) ignore() { l.start = l.pos l.startline = l.line l.startcol = l.col } func (l *lexer) accept(what string) bool { if strings.IndexRune(what, l.next()) >= 0 { return true } l.backup() return false } func (l *lexer) acceptRun(what string) { for strings.IndexRune(what, l.next()) >= 0 { } l.backup() } func (l *lexer) errorf(format string, args ...interface{}) lexerStateFn { t := &Token{ Filename: l.name, Typ: TokenError, Val: fmt.Sprintf(format, args...), Line: l.startline, Col: l.startcol, } l.tokens = append(l.tokens, t) l.errored = true l.startline = l.line l.startcol = l.col return nil } func (l *lexer) eof() bool { return l.start >= len(l.input)-1 } func (l *lexer) run() { for { // TODO: Support verbatim tag names // https://docs.djangoproject.com/en/dev/ref/templates/builtins/#verbatim if l.in_verbatim { name := l.verbatim_name if name != "" { name += " " } if strings.HasPrefix(l.input[l.pos:], fmt.Sprintf("{%% endverbatim %s%%}", name)) { // end verbatim if l.pos > l.start { l.emit(TokenHTML) } w := len("{% endverbatim %}") l.pos += w l.col += w l.ignore() l.in_verbatim = false } } else if strings.HasPrefix(l.input[l.pos:], "{% verbatim %}") { // tag if l.pos > l.start { l.emit(TokenHTML) } l.in_verbatim = true w := len("{% verbatim %}") l.pos += w l.col += w l.ignore() } if !l.in_verbatim { // Ignore single-line comments {# ... #} if strings.HasPrefix(l.input[l.pos:], "{#") { if l.pos > l.start { l.emit(TokenHTML) } l.pos += 2 // pass '{#' l.col += 2 for { switch l.peek() { case EOF: l.errorf("Single-line comment not closed.") return case '\n': l.errorf("Newline not permitted in a single-line comment.") return } if strings.HasPrefix(l.input[l.pos:], "#}") { l.pos += 2 // pass '#}' l.col += 2 break } l.next() } l.ignore() // ignore whole comment // Comment skipped continue // next token } if strings.HasPrefix(l.input[l.pos:], "{{") || // variable strings.HasPrefix(l.input[l.pos:], "{%") { // tag if l.pos > l.start { l.emit(TokenHTML) } l.tokenize() if l.errored { return } continue } } switch l.peek() { case '\n': l.line++ l.col = 0 } if l.next() == EOF { break } } if l.pos > l.start { l.emit(TokenHTML) } if l.in_verbatim { l.errorf("verbatim-tag not closed, got EOF.") } } func (l *lexer) tokenize() { for state := l.stateCode; state != nil; { state = state() } } func (l *lexer) stateCode() lexerStateFn { outer_loop: for { switch { case l.accept(tokenSpaceChars): if l.value() == "\n" { return l.errorf("Newline not allowed within tag/variable.") } l.ignore() continue case l.accept(tokenIdentifierChars): return l.stateIdentifier case l.accept(tokenDigits): return l.stateNumber case l.accept(`"`): return l.stateString } // Check for symbol for _, sym := range TokenSymbols { if strings.HasPrefix(l.input[l.start:], sym) { l.pos += len(sym) l.col += l.length() l.emit(TokenSymbol) if sym == "%}" || sym == "}}" { // Tag/variable end, return after emit return nil } continue outer_loop } } if l.pos < len(l.input) { return l.errorf("Unknown character: %q (%d)", l.peek(), l.peek()) } break } // Normal shut down return nil } func (l *lexer) stateIdentifier() lexerStateFn { l.acceptRun(tokenIdentifierChars) l.acceptRun(tokenIdentifierCharsWithDigits) for _, kw := range TokenKeywords { if kw == l.value() { l.emit(TokenKeyword) return l.stateCode } } l.emit(TokenIdentifier) return l.stateCode } func (l *lexer) stateNumber() lexerStateFn { l.acceptRun(tokenDigits) /* Maybe context-sensitive number lexing? * comments.0.Text // first comment * usercomments.1.0 // second user, first comment * if (score >= 8.5) // 8.5 as a number if l.peek() == '.' { l.accept(".") if !l.accept(tokenDigits) { return l.errorf("Malformed number.") } l.acceptRun(tokenDigits) } */ l.emit(TokenNumber) return l.stateCode } func (l *lexer) stateString() lexerStateFn { l.ignore() l.startcol -= 1 // we're starting the position at the first " for !l.accept(`"`) { switch l.next() { case '\\': // escape sequence switch l.peek() { case '"', '\\': l.next() default: return l.errorf("Unknown escape sequence: \\%c", l.peek()) } case EOF: return l.errorf("Unexpected EOF, string not closed.") case '\n': return l.errorf("Newline in string is not allowed.") } } l.backup() l.emit(TokenString) l.next() l.ignore() return l.stateCode } �����������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/helpers.go��������������������������������������������0000644�0610621�0607500�00000000217�13172163432�023742� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 func max(a, b int) int { if a > b { return a } return b } func min(a, b int) int { if a < b { return a } return b } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/filters_builtin.go������������������������������������0000644�0610621�0607500�00000053243�13172163432�025505� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 /* Filters that are provided through github.com/flosch/pongo2-addons: ------------------------------------------------------------------ filesizeformat slugify timesince timeuntil Filters that won't be added: ---------------------------- get_static_prefix (reason: web-framework specific) pprint (reason: python-specific) static (reason: web-framework specific) Reconsideration (not implemented yet): -------------------------------------- force_escape (reason: not yet needed since this is the behaviour of pongo2's escape filter) safeseq (reason: same reason as `force_escape`) unordered_list (python-specific; not sure whether needed or not) dictsort (python-specific; maybe one could add a filter to sort a list of structs by a specific field name) dictsortreversed (see dictsort) */ import ( "bytes" "fmt" "math/rand" "net/url" "regexp" "strconv" "strings" "time" "unicode/utf8" ) func init() { rand.Seed(time.Now().Unix()) RegisterFilter("escape", filterEscape) RegisterFilter("safe", filterSafe) RegisterFilter("escapejs", filterEscapejs) RegisterFilter("add", filterAdd) RegisterFilter("addslashes", filterAddslashes) RegisterFilter("capfirst", filterCapfirst) RegisterFilter("center", filterCenter) RegisterFilter("cut", filterCut) RegisterFilter("date", filterDate) RegisterFilter("default", filterDefault) RegisterFilter("default_if_none", filterDefaultIfNone) RegisterFilter("divisibleby", filterDivisibleby) RegisterFilter("first", filterFirst) RegisterFilter("floatformat", filterFloatformat) RegisterFilter("get_digit", filterGetdigit) RegisterFilter("iriencode", filterIriencode) RegisterFilter("join", filterJoin) RegisterFilter("last", filterLast) RegisterFilter("length", filterLength) RegisterFilter("length_is", filterLengthis) RegisterFilter("linebreaks", filterLinebreaks) RegisterFilter("linebreaksbr", filterLinebreaksbr) RegisterFilter("linenumbers", filterLinenumbers) RegisterFilter("ljust", filterLjust) RegisterFilter("lower", filterLower) RegisterFilter("make_list", filterMakelist) RegisterFilter("phone2numeric", filterPhone2numeric) RegisterFilter("pluralize", filterPluralize) RegisterFilter("random", filterRandom) RegisterFilter("removetags", filterRemovetags) RegisterFilter("rjust", filterRjust) RegisterFilter("slice", filterSlice) RegisterFilter("stringformat", filterStringformat) RegisterFilter("striptags", filterStriptags) RegisterFilter("time", filterDate) // time uses filterDate (same golang-format) RegisterFilter("title", filterTitle) RegisterFilter("truncatechars", filterTruncatechars) RegisterFilter("truncatechars_html", filterTruncatecharsHtml) RegisterFilter("truncatewords", filterTruncatewords) RegisterFilter("truncatewords_html", filterTruncatewordsHtml) RegisterFilter("upper", filterUpper) RegisterFilter("urlencode", filterUrlencode) RegisterFilter("urlize", filterUrlize) RegisterFilter("urlizetrunc", filterUrlizetrunc) RegisterFilter("wordcount", filterWordcount) RegisterFilter("wordwrap", filterWordwrap) RegisterFilter("yesno", filterYesno) RegisterFilter("float", filterFloat) // pongo-specific RegisterFilter("integer", filterInteger) // pongo-specific } func filterTruncatecharsHelper(s string, newLen int) string { runes := []rune(s) if newLen < len(runes) { if newLen >= 3 { return fmt.Sprintf("%s...", string(runes[:newLen-3])) } // Not enough space for the ellipsis return string(runes[:newLen]) } return string(runes) } func filterTruncateHtmlHelper(value string, new_output *bytes.Buffer, cond func() bool, fn func(c rune, s int, idx int) int, finalize func()) { vLen := len(value) tag_stack := make([]string, 0) idx := 0 for idx < vLen && !cond() { c, s := utf8.DecodeRuneInString(value[idx:]) if c == utf8.RuneError { idx += s continue } if c == '<' { new_output.WriteRune(c) idx += s // consume "<" if idx+1 < vLen { if value[idx] == '/' { // Close tag new_output.WriteString("/") tag := "" idx += 1 // consume "/" for idx < vLen { c2, size2 := utf8.DecodeRuneInString(value[idx:]) if c2 == utf8.RuneError { idx += size2 continue } // End of tag found if c2 == '>' { idx++ // consume ">" break } tag += string(c2) idx += size2 } if len(tag_stack) > 0 { // Ideally, the close tag is TOP of tag stack // In malformed HTML, it must not be, so iterate through the stack and remove the tag for i := len(tag_stack) - 1; i >= 0; i-- { if tag_stack[i] == tag { // Found the tag tag_stack[i] = tag_stack[len(tag_stack)-1] tag_stack = tag_stack[:len(tag_stack)-1] break } } } new_output.WriteString(tag) new_output.WriteString(">") } else { // Open tag tag := "" params := false for idx < vLen { c2, size2 := utf8.DecodeRuneInString(value[idx:]) if c2 == utf8.RuneError { idx += size2 continue } new_output.WriteRune(c2) // End of tag found if c2 == '>' { idx++ // consume ">" break } if !params { if c2 == ' ' { params = true } else { tag += string(c2) } } idx += size2 } // Add tag to stack tag_stack = append(tag_stack, tag) } } } else { idx = fn(c, s, idx) } } finalize() for i := len(tag_stack) - 1; i >= 0; i-- { tag := tag_stack[i] // Close everything from the regular tag stack new_output.WriteString(fmt.Sprintf("</%s>", tag)) } } func filterTruncatechars(in *Value, param *Value) (*Value, *Error) { s := in.String() newLen := param.Integer() return AsValue(filterTruncatecharsHelper(s, newLen)), nil } func filterTruncatecharsHtml(in *Value, param *Value) (*Value, *Error) { value := in.String() newLen := max(param.Integer()-3, 0) new_output := bytes.NewBuffer(nil) textcounter := 0 filterTruncateHtmlHelper(value, new_output, func() bool { return textcounter >= newLen }, func(c rune, s int, idx int) int { textcounter++ new_output.WriteRune(c) return idx + s }, func() { if textcounter >= newLen && textcounter < len(value) { new_output.WriteString("...") } }) return AsSafeValue(new_output.String()), nil } func filterTruncatewords(in *Value, param *Value) (*Value, *Error) { words := strings.Fields(in.String()) n := param.Integer() if n <= 0 { return AsValue(""), nil } nlen := min(len(words), n) out := make([]string, 0, nlen) for i := 0; i < nlen; i++ { out = append(out, words[i]) } if n < len(words) { out = append(out, "...") } return AsValue(strings.Join(out, " ")), nil } func filterTruncatewordsHtml(in *Value, param *Value) (*Value, *Error) { value := in.String() newLen := max(param.Integer(), 0) new_output := bytes.NewBuffer(nil) wordcounter := 0 filterTruncateHtmlHelper(value, new_output, func() bool { return wordcounter >= newLen }, func(_ rune, _ int, idx int) int { // Get next word word_found := false for idx < len(value) { c2, size2 := utf8.DecodeRuneInString(value[idx:]) if c2 == utf8.RuneError { idx += size2 continue } if c2 == '<' { // HTML tag start, don't consume it return idx } new_output.WriteRune(c2) idx += size2 if c2 == ' ' || c2 == '.' || c2 == ',' || c2 == ';' { // Word ends here, stop capturing it now break } else { word_found = true } } if word_found { wordcounter++ } return idx }, func() { if wordcounter >= newLen { new_output.WriteString("...") } }) return AsSafeValue(new_output.String()), nil } func filterEscape(in *Value, param *Value) (*Value, *Error) { output := strings.Replace(in.String(), "&", "&amp;", -1) output = strings.Replace(output, ">", "&gt;", -1) output = strings.Replace(output, "<", "&lt;", -1) output = strings.Replace(output, "\"", "&quot;", -1) output = strings.Replace(output, "'", "&#39;", -1) return AsValue(output), nil } func filterSafe(in *Value, param *Value) (*Value, *Error) { return in, nil // nothing to do here, just to keep track of the safe application } func filterEscapejs(in *Value, param *Value) (*Value, *Error) { sin := in.String() var b bytes.Buffer idx := 0 for idx < len(sin) { c, size := utf8.DecodeRuneInString(sin[idx:]) if c == utf8.RuneError { idx += size continue } if c == '\\' { // Escape seq? if idx+1 < len(sin) { switch sin[idx+1] { case 'r': b.WriteString(fmt.Sprintf(`\u%04X`, '\r')) idx += 2 continue case 'n': b.WriteString(fmt.Sprintf(`\u%04X`, '\n')) idx += 2 continue /*case '\'': b.WriteString(fmt.Sprintf(`\u%04X`, '\'')) idx += 2 continue case '"': b.WriteString(fmt.Sprintf(`\u%04X`, '"')) idx += 2 continue*/ } } } if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == ' ' || c == '/' { b.WriteRune(c) } else { b.WriteString(fmt.Sprintf(`\u%04X`, c)) } idx += size } return AsValue(b.String()), nil } func filterAdd(in *Value, param *Value) (*Value, *Error) { if in.IsNumber() && param.IsNumber() { if in.IsFloat() || param.IsFloat() { return AsValue(in.Float() + param.Float()), nil } else { return AsValue(in.Integer() + param.Integer()), nil } } // If in/param is not a number, we're relying on the // Value's String() convertion and just add them both together return AsValue(in.String() + param.String()), nil } func filterAddslashes(in *Value, param *Value) (*Value, *Error) { output := strings.Replace(in.String(), "\\", "\\\\", -1) output = strings.Replace(output, "\"", "\\\"", -1) output = strings.Replace(output, "'", "\\'", -1) return AsValue(output), nil } func filterCut(in *Value, param *Value) (*Value, *Error) { return AsValue(strings.Replace(in.String(), param.String(), "", -1)), nil } func filterLength(in *Value, param *Value) (*Value, *Error) { return AsValue(in.Len()), nil } func filterLengthis(in *Value, param *Value) (*Value, *Error) { return AsValue(in.Len() == param.Integer()), nil } func filterDefault(in *Value, param *Value) (*Value, *Error) { if !in.IsTrue() { return param, nil } return in, nil } func filterDefaultIfNone(in *Value, param *Value) (*Value, *Error) { if in.IsNil() { return param, nil } return in, nil } func filterDivisibleby(in *Value, param *Value) (*Value, *Error) { if param.Integer() == 0 { return AsValue(false), nil } return AsValue(in.Integer()%param.Integer() == 0), nil } func filterFirst(in *Value, param *Value) (*Value, *Error) { if in.CanSlice() && in.Len() > 0 { return in.Index(0), nil } return AsValue(""), nil } func filterFloatformat(in *Value, param *Value) (*Value, *Error) { val := in.Float() decimals := -1 if !param.IsNil() { // Any argument provided? decimals = param.Integer() } // if the argument is not a number (e. g. empty), the default // behaviour is trim the result trim := !param.IsNumber() if decimals <= 0 { // argument is negative or zero, so we // want the output being trimmed decimals = -decimals trim = true } if trim { // Remove zeroes if float64(int(val)) == val { return AsValue(in.Integer()), nil } } return AsValue(strconv.FormatFloat(val, 'f', decimals, 64)), nil } func filterGetdigit(in *Value, param *Value) (*Value, *Error) { i := param.Integer() l := len(in.String()) // do NOT use in.Len() here! if i <= 0 || i > l { return in, nil } return AsValue(in.String()[l-i] - 48), nil } const filterIRIChars = "/#%[]=:;$&()+,!?*@'~" func filterIriencode(in *Value, param *Value) (*Value, *Error) { var b bytes.Buffer sin := in.String() for _, r := range sin { if strings.IndexRune(filterIRIChars, r) >= 0 { b.WriteRune(r) } else { b.WriteString(url.QueryEscape(string(r))) } } return AsValue(b.String()), nil } func filterJoin(in *Value, param *Value) (*Value, *Error) { if !in.CanSlice() { return in, nil } sep := param.String() sl := make([]string, 0, in.Len()) for i := 0; i < in.Len(); i++ { sl = append(sl, in.Index(i).String()) } return AsValue(strings.Join(sl, sep)), nil } func filterLast(in *Value, param *Value) (*Value, *Error) { if in.CanSlice() && in.Len() > 0 { return in.Index(in.Len() - 1), nil } return AsValue(""), nil } func filterUpper(in *Value, param *Value) (*Value, *Error) { return AsValue(strings.ToUpper(in.String())), nil } func filterLower(in *Value, param *Value) (*Value, *Error) { return AsValue(strings.ToLower(in.String())), nil } func filterMakelist(in *Value, param *Value) (*Value, *Error) { s := in.String() result := make([]string, 0, len(s)) for _, c := range s { result = append(result, string(c)) } return AsValue(result), nil } func filterCapfirst(in *Value, param *Value) (*Value, *Error) { if in.Len() <= 0 { return AsValue(""), nil } t := in.String() r, size := utf8.DecodeRuneInString(t) return AsValue(strings.ToUpper(string(r)) + t[size:]), nil } func filterCenter(in *Value, param *Value) (*Value, *Error) { width := param.Integer() slen := in.Len() if width <= slen { return in, nil } spaces := width - slen left := spaces/2 + spaces%2 right := spaces / 2 return AsValue(fmt.Sprintf("%s%s%s", strings.Repeat(" ", left), in.String(), strings.Repeat(" ", right))), nil } func filterDate(in *Value, param *Value) (*Value, *Error) { t, is_time := in.Interface().(time.Time) if !is_time { return nil, &Error{ Sender: "filter:date", ErrorMsg: "Filter input argument must be of type 'time.Time'.", } } return AsValue(t.Format(param.String())), nil } func filterFloat(in *Value, param *Value) (*Value, *Error) { return AsValue(in.Float()), nil } func filterInteger(in *Value, param *Value) (*Value, *Error) { return AsValue(in.Integer()), nil } func filterLinebreaks(in *Value, param *Value) (*Value, *Error) { if in.Len() == 0 { return in, nil } var b bytes.Buffer // Newline = <br /> // Double newline = <p>...</p> lines := strings.Split(in.String(), "\n") lenlines := len(lines) opened := false for idx, line := range lines { if !opened { b.WriteString("<p>") opened = true } b.WriteString(line) if idx < lenlines-1 && strings.TrimSpace(lines[idx]) != "" { // We've not reached the end if strings.TrimSpace(lines[idx+1]) == "" { // Next line is empty if opened { b.WriteString("</p>") opened = false } } else { b.WriteString("<br />") } } } if opened { b.WriteString("</p>") } return AsValue(b.String()), nil } func filterLinebreaksbr(in *Value, param *Value) (*Value, *Error) { return AsValue(strings.Replace(in.String(), "\n", "<br />", -1)), nil } func filterLinenumbers(in *Value, param *Value) (*Value, *Error) { lines := strings.Split(in.String(), "\n") output := make([]string, 0, len(lines)) for idx, line := range lines { output = append(output, fmt.Sprintf("%d. %s", idx+1, line)) } return AsValue(strings.Join(output, "\n")), nil } func filterLjust(in *Value, param *Value) (*Value, *Error) { times := param.Integer() - in.Len() if times < 0 { times = 0 } return AsValue(fmt.Sprintf("%s%s", in.String(), strings.Repeat(" ", times))), nil } func filterUrlencode(in *Value, param *Value) (*Value, *Error) { return AsValue(url.QueryEscape(in.String())), nil } // TODO: This regexp could do some work var filterUrlizeURLRegexp = regexp.MustCompile(`((((http|https)://)|www\.|((^|[ ])[0-9A-Za-z_\-]+(\.com|\.net|\.org|\.info|\.biz|\.de))))(?U:.*)([ ]+|$)`) var filterUrlizeEmailRegexp = regexp.MustCompile(`(\w+@\w+\.\w{2,4})`) func filterUrlizeHelper(input string, autoescape bool, trunc int) string { sout := filterUrlizeURLRegexp.ReplaceAllStringFunc(input, func(raw_url string) string { var prefix string var suffix string if strings.HasPrefix(raw_url, " ") { prefix = " " } if strings.HasSuffix(raw_url, " ") { suffix = " " } raw_url = strings.TrimSpace(raw_url) t, err := ApplyFilter("iriencode", AsValue(raw_url), nil) if err != nil { panic(err) } url := t.String() if !strings.HasPrefix(url, "http") { url = fmt.Sprintf("http://%s", url) } title := raw_url if trunc > 3 && len(title) > trunc { title = fmt.Sprintf("%s...", title[:trunc-3]) } if autoescape { t, err := ApplyFilter("escape", AsValue(title), nil) if err != nil { panic(err) } title = t.String() } return fmt.Sprintf(`%s<a href="%s" rel="nofollow">%s</a>%s`, prefix, url, title, suffix) }) sout = filterUrlizeEmailRegexp.ReplaceAllStringFunc(sout, func(mail string) string { title := mail if trunc > 3 && len(title) > trunc { title = fmt.Sprintf("%s...", title[:trunc-3]) } return fmt.Sprintf(`<a href="mailto:%s">%s</a>`, mail, title) }) return sout } func filterUrlize(in *Value, param *Value) (*Value, *Error) { autoescape := true if param.IsBool() { autoescape = param.Bool() } return AsValue(filterUrlizeHelper(in.String(), autoescape, -1)), nil } func filterUrlizetrunc(in *Value, param *Value) (*Value, *Error) { return AsValue(filterUrlizeHelper(in.String(), true, param.Integer())), nil } func filterStringformat(in *Value, param *Value) (*Value, *Error) { return AsValue(fmt.Sprintf(param.String(), in.Interface())), nil } var re_striptags = regexp.MustCompile("<[^>]*?>") func filterStriptags(in *Value, param *Value) (*Value, *Error) { s := in.String() // Strip all tags s = re_striptags.ReplaceAllString(s, "") return AsValue(strings.TrimSpace(s)), nil } // https://en.wikipedia.org/wiki/Phoneword var filterPhone2numericMap = map[string]string{ "a": "2", "b": "2", "c": "2", "d": "3", "e": "3", "f": "3", "g": "4", "h": "4", "i": "4", "j": "5", "k": "5", "l": "5", "m": "6", "n": "6", "o": "6", "p": "7", "q": "7", "r": "7", "s": "7", "t": "8", "u": "8", "v": "8", "w": "9", "x": "9", "y": "9", "z": "9", } func filterPhone2numeric(in *Value, param *Value) (*Value, *Error) { sin := in.String() for k, v := range filterPhone2numericMap { sin = strings.Replace(sin, k, v, -1) sin = strings.Replace(sin, strings.ToUpper(k), v, -1) } return AsValue(sin), nil } func filterPluralize(in *Value, param *Value) (*Value, *Error) { if in.IsNumber() { // Works only on numbers if param.Len() > 0 { endings := strings.Split(param.String(), ",") if len(endings) > 2 { return nil, &Error{ Sender: "filter:pluralize", ErrorMsg: "You cannot pass more than 2 arguments to filter 'pluralize'.", } } if len(endings) == 1 { // 1 argument if in.Integer() != 1 { return AsValue(endings[0]), nil } } else { if in.Integer() != 1 { // 2 arguments return AsValue(endings[1]), nil } return AsValue(endings[0]), nil } } else { if in.Integer() != 1 { // return default 's' return AsValue("s"), nil } } return AsValue(""), nil } else { return nil, &Error{ Sender: "filter:pluralize", ErrorMsg: "Filter 'pluralize' does only work on numbers.", } } } func filterRandom(in *Value, param *Value) (*Value, *Error) { if !in.CanSlice() || in.Len() <= 0 { return in, nil } i := rand.Intn(in.Len()) return in.Index(i), nil } func filterRemovetags(in *Value, param *Value) (*Value, *Error) { s := in.String() tags := strings.Split(param.String(), ",") // Strip only specific tags for _, tag := range tags { re := regexp.MustCompile(fmt.Sprintf("</?%s/?>", tag)) s = re.ReplaceAllString(s, "") } return AsValue(strings.TrimSpace(s)), nil } func filterRjust(in *Value, param *Value) (*Value, *Error) { return AsValue(fmt.Sprintf(fmt.Sprintf("%%%ds", param.Integer()), in.String())), nil } func filterSlice(in *Value, param *Value) (*Value, *Error) { comp := strings.Split(param.String(), ":") if len(comp) != 2 { return nil, &Error{ Sender: "filter:slice", ErrorMsg: "Slice string must have the format 'from:to' [from/to can be omitted, but the ':' is required]", } } if !in.CanSlice() { return in, nil } from := AsValue(comp[0]).Integer() to := in.Len() if from > to { from = to } vto := AsValue(comp[1]).Integer() if vto >= from && vto <= in.Len() { to = vto } return in.Slice(from, to), nil } func filterTitle(in *Value, param *Value) (*Value, *Error) { if !in.IsString() { return AsValue(""), nil } return AsValue(strings.Title(strings.ToLower(in.String()))), nil } func filterWordcount(in *Value, param *Value) (*Value, *Error) { return AsValue(len(strings.Fields(in.String()))), nil } func filterWordwrap(in *Value, param *Value) (*Value, *Error) { words := strings.Fields(in.String()) words_len := len(words) wrap_at := param.Integer() if wrap_at <= 0 { return in, nil } linecount := words_len/wrap_at + words_len%wrap_at lines := make([]string, 0, linecount) for i := 0; i < linecount; i++ { lines = append(lines, strings.Join(words[wrap_at*i:min(wrap_at*(i+1), words_len)], " ")) } return AsValue(strings.Join(lines, "\n")), nil } func filterYesno(in *Value, param *Value) (*Value, *Error) { choices := map[int]string{ 0: "yes", 1: "no", 2: "maybe", } param_string := param.String() custom_choices := strings.Split(param_string, ",") if len(param_string) > 0 { if len(custom_choices) > 3 { return nil, &Error{ Sender: "filter:yesno", ErrorMsg: fmt.Sprintf("You cannot pass more than 3 options to the 'yesno'-filter (got: '%s').", param_string), } } if len(custom_choices) < 2 { return nil, &Error{ Sender: "filter:yesno", ErrorMsg: fmt.Sprintf("You must pass either no or at least 2 arguments to the 'yesno'-filter (got: '%s').", param_string), } } // Map to the options now choices[0] = custom_choices[0] choices[1] = custom_choices[1] if len(custom_choices) == 3 { choices[2] = custom_choices[2] } } // maybe if in.IsNil() { return AsValue(choices[2]), nil } // yes if in.IsTrue() { return AsValue(choices[0]), nil } // no return AsValue(choices[1]), nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/filters.go��������������������������������������������0000644�0610621�0607500�00000006342�13172163432�023755� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "fmt" ) type FilterFunction func(in *Value, param *Value) (out *Value, err *Error) var filters map[string]FilterFunction func init() { filters = make(map[string]FilterFunction) } // Registers a new filter. If there's already a filter with the same // name, RegisterFilter will panic. You usually want to call this // function in the filter's init() function: // http://golang.org/doc/effective_go.html#init // // See http://www.florian-schlachter.de/post/pongo2/ for more about // writing filters and tags. func RegisterFilter(name string, fn FilterFunction) { _, existing := filters[name] if existing { panic(fmt.Sprintf("Filter with name '%s' is already registered.", name)) } filters[name] = fn } // Replaces an already registered filter with a new implementation. Use this // function with caution since it allows you to change existing filter behaviour. func ReplaceFilter(name string, fn FilterFunction) { _, existing := filters[name] if !existing { panic(fmt.Sprintf("Filter with name '%s' does not exist (therefore cannot be overridden).", name)) } filters[name] = fn } // Like ApplyFilter, but panics on an error func MustApplyFilter(name string, value *Value, param *Value) *Value { val, err := ApplyFilter(name, value, param) if err != nil { panic(err) } return val } // Applies a filter to a given value using the given parameters. Returns a *pongo2.Value or an error. func ApplyFilter(name string, value *Value, param *Value) (*Value, *Error) { fn, existing := filters[name] if !existing { return nil, &Error{ Sender: "applyfilter", ErrorMsg: fmt.Sprintf("Filter with name '%s' not found.", name), } } // Make sure param is a *Value if param == nil { param = AsValue(nil) } return fn(value, param) } type filterCall struct { token *Token name string parameter IEvaluator filterFunc FilterFunction } func (fc *filterCall) Execute(v *Value, ctx *ExecutionContext) (*Value, *Error) { var param *Value var err *Error if fc.parameter != nil { param, err = fc.parameter.Evaluate(ctx) if err != nil { return nil, err } } else { param = AsValue(nil) } filtered_value, err := fc.filterFunc(v, param) if err != nil { return nil, err.updateFromTokenIfNeeded(ctx.template, fc.token) } return filtered_value, nil } // Filter = IDENT | IDENT ":" FilterArg | IDENT "|" Filter func (p *Parser) parseFilter() (*filterCall, *Error) { ident_token := p.MatchType(TokenIdentifier) // Check filter ident if ident_token == nil { return nil, p.Error("Filter name must be an identifier.", nil) } filter := &filterCall{ token: ident_token, name: ident_token.Val, } // Get the appropriate filter function and bind it filterFn, exists := filters[ident_token.Val] if !exists { return nil, p.Error(fmt.Sprintf("Filter '%s' does not exist.", ident_token.Val), ident_token) } filter.filterFunc = filterFn // Check for filter-argument (2 tokens needed: ':' ARG) if p.Match(TokenSymbol, ":") != nil { if p.Peek(TokenSymbol, "}}") != nil { return nil, p.Error("Filter parameter required after ':'.", nil) } // Get filter argument expression v, err := p.parseVariableOrLiteral() if err != nil { return nil, err } filter.parameter = v } return filter, nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/error.go����������������������������������������������0000644�0610621�0607500�00000003502�13172163432�023431� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "bufio" "fmt" "os" ) // This Error type is being used to address an error during lexing, parsing or // execution. If you want to return an error object (for example in your own // tag or filter) fill this object with as much information as you have. // Make sure "Sender" is always given (if you're returning an error within // a filter, make Sender equals 'filter:yourfilter'; same goes for tags: 'tag:mytag'). // It's okay if you only fill in ErrorMsg if you don't have any other details at hand. type Error struct { Template *Template Filename string Line int Column int Token *Token Sender string ErrorMsg string } func (e *Error) updateFromTokenIfNeeded(template *Template, t *Token) *Error { if e.Template == nil { e.Template = template } if e.Token == nil { e.Token = t if e.Line <= 0 { e.Line = t.Line e.Column = t.Col } } return e } // Returns a nice formatted error string. func (e *Error) Error() string { s := "[Error" if e.Sender != "" { s += " (where: " + e.Sender + ")" } if e.Filename != "" { s += " in " + e.Filename } if e.Line > 0 { s += fmt.Sprintf(" | Line %d Col %d", e.Line, e.Column) if e.Token != nil { s += fmt.Sprintf(" near '%s'", e.Token.Val) } } s += "] " s += e.ErrorMsg return s } // Returns the affected line from the original template, if available. func (e *Error) RawLine() (line string, available bool) { if e.Line <= 0 || e.Filename == "<string>" { return "", false } filename := e.Filename if e.Template != nil { filename = e.Template.set.resolveFilename(e.Template, e.Filename) } file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) l := 0 for scanner.Scan() { l++ if l == e.Line { return scanner.Text(), true } } return "", false } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/�������������������������������������������������0000755�0610621�0607500�00000000000�13172163432�022701� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/write_tags.md������������������������������������0000644�0610621�0607500�00000000000�13172163432�025361� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/write_filters.md���������������������������������0000644�0610621�0607500�00000000000�13172163432�026073� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/template_sets.md���������������������������������0000644�0610621�0607500�00000000013�13172163432�026066� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������(Stub, TBA)���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/tags.md������������������������������������������0000644�0610621�0607500�00000000546�13172163432�024166� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������TODO: * What are tags? * List+explain all existing tags (pongo2 + pongo2-addons) Implemented tags so far which needs documentation: * autoescape * block * comment * cycle * extends * filter * firstof * for * if * ifchanged * ifequal * ifnotequal * import * include * lorem * macro * now * set * spaceless * ssi * templatetag * verbatim * widthratio * with����������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/macros.md����������������������������������������0000644�0610621�0607500�00000000014�13172163432�024502� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������(Stub, TBA) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/index.md�����������������������������������������0000644�0610621�0607500�00000000013�13172163432�024324� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������(Stub, TBA)���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/filters.md���������������������������������������0000644�0610621�0607500�00000001655�13172163432�024702� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������TODO: * What are filters? * List+explain all existing filters (pongo2 + pongo2-addons) Implemented filters so far which needs documentation: * escape * safe * escapejs * add * addslashes * capfirst * center * cut * date * default * default_if_none * divisibleby * first * floatformat * get_digit * iriencode * join * last * length * length_is * linebreaks * linebreaksbr * linenumbers * ljust * lower * make_list * phone2numeric * pluralize * random * removetags * rjust * slice * stringformat * striptags * time * title * truncatechars * truncatechars_html * truncatewords * truncatewords_html * upper * urlencode * urlize * urlizetrunc * wordcount * wordwrap * yesno * filesizeformat* * slugify* * truncatesentences* * truncatesentences_html* * markdown* * intcomma* * ordinal* * naturalday* * timesince* * timeuntil* * naturaltime* Filters marked with * are available through [pongo2-addons](https://github.com/flosch/pongo2-addons).�����������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/docs/examples.md��������������������������������������0000644�0610621�0607500�00000000013�13172163432�025033� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������(Stub, TBA)���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/doc.go������������������������������������������������0000644�0610621�0607500�00000002013�13172163432�023041� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// A Django-syntax like template-engine // // Blog posts about pongo2 (including introduction and migration): // https://www.florian-schlachter.de/?tag=pongo2 // // Complete documentation on the template language: // https://docs.djangoproject.com/en/dev/topics/templates/ // // Try out pongo2 live in the pongo2 playground: // https://www.florian-schlachter.de/pongo2/ // // Make sure to read README.md in the repository as well. // // A tiny example with template strings: // // (Snippet on playground: https://www.florian-schlachter.de/pongo2/?id=1206546277) // // // Compile the template first (i. e. creating the AST) // tpl, err := pongo2.FromString("Hello {{ name|capfirst }}!") // if err != nil { // panic(err) // } // // Now you can render the template with the given // // pongo2.Context how often you want to. // out, err := tpl.Execute(pongo2.Context{"name": "fred"}) // if err != nil { // panic(err) // } // fmt.Println(out) // Output: Hello Fred! // package pongo2 ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/context.go��������������������������������������������0000644�0610621�0607500�00000006051�13172163432�023766� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package pongo2 import ( "fmt" "regexp" ) var reIdentifiers = regexp.MustCompile("^[a-zA-Z0-9_]+$") // Use this Context type to provide constants, variables, instances or functions to your template. // // pongo2 automatically provides meta-information or functions through the "pongo2"-key. // Currently, context["pongo2"] contains the following keys: // 1. version: returns the version string // // Template examples for accessing items from your context: // {{ myconstant }} // {{ myfunc("test", 42) }} // {{ user.name }} // {{ pongo2.version }} type Context map[string]interface{} func (c Context) checkForValidIdentifiers() *Error { for k, v := range c { if !reIdentifiers.MatchString(k) { return &Error{ Sender: "checkForValidIdentifiers", ErrorMsg: fmt.Sprintf("Context-key '%s' (value: '%+v') is not a valid identifier.", k, v), } } } return nil } func (c Context) Update(other Context) Context { for k, v := range other { c[k] = v } return c } // If you're writing a custom tag, your tag's Execute()-function will // have access to the ExecutionContext. This struct stores anything // about the current rendering process's Context including // the Context provided by the user (field Public). // You can safely use the Private context to provide data to the user's // template (like a 'forloop'-information). The Shared-context is used // to share data between tags. All ExecutionContexts share this context. // // Please be careful when accessing the Public data. // PLEASE DO NOT MODIFY THE PUBLIC CONTEXT (read-only). // // To create your own execution context within tags, use the // NewChildExecutionContext(parent) function. type ExecutionContext struct { template *Template Autoescape bool Public Context Private Context Shared Context } var pongo2MetaContext = Context{ "version": Version, } func newExecutionContext(tpl *Template, ctx Context) *ExecutionContext { privateCtx := make(Context) // Make the pongo2-related funcs/vars available to the context privateCtx["pongo2"] = pongo2MetaContext return &ExecutionContext{ template: tpl, Public: ctx, Private: privateCtx, Autoescape: true, } } func NewChildExecutionContext(parent *ExecutionContext) *ExecutionContext { newctx := &ExecutionContext{ template: parent.template, Public: parent.Public, Private: make(Context), Autoescape: parent.Autoescape, } newctx.Shared = parent.Shared // Copy all existing private items newctx.Private.Update(parent.Private) return newctx } func (ctx *ExecutionContext) Error(msg string, token *Token) *Error { filename := ctx.template.name var line, col int if token != nil { // No tokens available // TODO: Add location (from where?) filename = token.Filename line = token.Line col = token.Col } return &Error{ Template: ctx.template, Filename: filename, Line: line, Column: col, Token: token, Sender: "execution", ErrorMsg: msg, } } func (ctx *ExecutionContext) Logf(format string, args ...interface{}) { ctx.template.set.logf(format, args...) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/README.md���������������������������������������������0000644�0610621�0607500�00000032714�13172163432�023237� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# [pongo](https://en.wikipedia.org/wiki/Pongo_%28genus%29)2 [![GoDoc](https://godoc.org/github.com/flosch/pongo2?status.png)](https://godoc.org/github.com/flosch/pongo2) [![Build Status](https://travis-ci.org/flosch/pongo2.svg?branch=master)](https://travis-ci.org/flosch/pongo2) [![Coverage Status](https://coveralls.io/repos/flosch/pongo2/badge.png?branch=master)](https://coveralls.io/r/flosch/pongo2?branch=master) [![gratipay](http://img.shields.io/badge/gratipay-support%20pongo-brightgreen.svg)](https://gratipay.com/flosch/) [![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=3654947)](https://www.bountysource.com/trackers/3654947-pongo2?utm_source=3654947&utm_medium=shield&utm_campaign=TRACKER_BADGE) pongo2 is the successor of [pongo](https://github.com/flosch/pongo), a Django-syntax like templating-language. Install/update using `go get` (no dependencies required by pongo2): ``` go get -u github.com/flosch/pongo2 ``` Please use the [issue tracker](https://github.com/flosch/pongo2/issues) if you're encountering any problems with pongo2 or if you need help with implementing tags or filters ([create a ticket!](https://github.com/flosch/pongo2/issues/new)). If possible, please use [playground](https://www.florian-schlachter.de/pongo2/) to create a short test case on what's wrong and include the link to the snippet in your issue. **New**: [Try pongo2 out in the pongo2 playground.](https://www.florian-schlachter.de/pongo2/) ## First impression of a template ```HTML+Django <html><head><title>Our admins and users</title></head> {# This is a short example to give you a quick overview of pongo2's syntax. #} {% macro user_details(user, is_admin=false) %} <div class="user_item"> <!-- Let's indicate a user's good karma --> <h2 {% if (user.karma >= 40) || (user.karma > calc_avg_karma(userlist)+5) %} class="karma-good"{% endif %}> <!-- This will call user.String() automatically if available: --> {{ user }} </h2> <!-- Will print a human-readable time duration like "3 weeks ago" --> <p>This user registered {{ user.register_date|naturaltime }}.</p> <!-- Let's allow the users to write down their biography using markdown; we will only show the first 15 words as a preview --> <p>The user's biography:</p> <p>{{ user.biography|markdown|truncatewords_html:15 }} <a href="/user/{{ user.id }}/">read more</a></p> {% if is_admin %}<p>This user is an admin!</p>{% endif %} </div> {% endmacro %} <body> <!-- Make use of the macro defined above to avoid repetitive HTML code since we want to use the same code for admins AND members --> <h1>Our admins</h1> {% for admin in adminlist %} {{ user_details(admin, true) }} {% endfor %} <h1>Our members</h1> {% for user in userlist %} {{ user_details(user) }} {% endfor %} </body> </html> ``` ## Development status **Latest stable release**: v3.0 (`go get -u gopkg.in/flosch/pongo2.v3` / [`v3`](https://github.com/flosch/pongo2/tree/v3)-branch) [[read the announcement](https://www.florian-schlachter.de/post/pongo2-v3/)] **Current development**: v4 (`master`-branch) *Note*: With the release of pongo v4 the branch v2 will be deprecated. **Deprecated versions** (not supported anymore): v1 | Topic | Status | | ------------------------------------ | -------------------------------------------------------------------------------------- | | Django version compatibility: | [1.7](https://docs.djangoproject.com/en/1.7/ref/templates/builtins/) | | *Missing* (planned) **filters**: | none ([hints](https://github.com/flosch/pongo2/blob/master/filters_builtin.go#L3)) | | *Missing* (planned) **tags**: | none ([hints](https://github.com/flosch/pongo2/blob/master/tags.go#L3)) | Please also have a look on the [caveats](https://github.com/flosch/pongo2#caveats) and on the [official add-ons](https://github.com/flosch/pongo2#official). ## Features (and new in pongo2) * Entirely rewritten from the ground-up. * [Advanced C-like expressions](https://github.com/flosch/pongo2/blob/master/template_tests/expressions.tpl). * [Complex function calls within expressions](https://github.com/flosch/pongo2/blob/master/template_tests/function_calls_wrapper.tpl). * [Easy API to create new filters and tags](http://godoc.org/github.com/flosch/pongo2#RegisterFilter) ([including parsing arguments](http://godoc.org/github.com/flosch/pongo2#Parser)) * Additional features: * Macros including importing macros from other files (see [template_tests/macro.tpl](https://github.com/flosch/pongo2/blob/master/template_tests/macro.tpl)) * [Template sandboxing](https://godoc.org/github.com/flosch/pongo2#TemplateSet) ([directory patterns](http://golang.org/pkg/path/filepath/#Match), banned tags/filters) ## Recent API changes within pongo2 If you're using the `master`-branch of pongo2, you might be interested in this section. Since pongo2 is still in development (even though there is a first stable release!), there could be (backwards-incompatible) API changes over time. To keep track of these and therefore make it painless for you to adapt your codebase, I'll list them here. * Function signature for tag and filter parsing/execution changed (`error` return type changed to `*Error`). * `INodeEvaluator` has been removed and got replaced by `IEvaluator`. You can change your existing tags/filters by simply replacing the interface. * Two new helper functions: [`RenderTemplateFile()`](https://godoc.org/github.com/flosch/pongo2#RenderTemplateFile) and [`RenderTemplateString()`](https://godoc.org/github.com/flosch/pongo2#RenderTemplateString). * `Template.ExecuteRW()` is now [`Template.ExecuteWriter()`](https://godoc.org/github.com/flosch/pongo2#Template.ExecuteWriter) * `Template.Execute*()` functions do now take a `pongo2.Context` directly (no pointer anymore). ## How you can help * Write [filters](https://github.com/flosch/pongo2/blob/master/filters_builtin.go#L3) / [tags](https://github.com/flosch/pongo2/blob/master/tags.go#L4) (see [tutorial](https://www.florian-schlachter.de/post/pongo2/)) by forking pongo2 and sending pull requests * Write/improve code tests (use the following command to see what tests are missing: `go test -v -cover -covermode=count -coverprofile=cover.out && go tool cover -html=cover.out`) * Write/improve template tests (see the `template_tests/` directory) * Write middleware, libraries and websites using pongo2. :-) # Documentation For a documentation on how the templating language works you can [head over to the Django documentation](https://docs.djangoproject.com/en/dev/topics/templates/). pongo2 aims to be compatible with it. You can access pongo2's API documentation on [godoc](https://godoc.org/github.com/flosch/pongo2). ## Blog post series * [pongo2 v2 released](https://www.florian-schlachter.de/post/pongo2-v2/) * [pongo2 1.0 released](https://www.florian-schlachter.de/post/pongo2-10/) [August 8th 2014] * [pongo2 playground](https://www.florian-schlachter.de/post/pongo2-playground/) [August 1st 2014] * [Release of pongo2 1.0-rc1 + pongo2-addons](https://www.florian-schlachter.de/post/pongo2-10-rc1/) [July 30th 2014] * [Introduction to pongo2 + migration- and "how to write tags/filters"-tutorial.](https://www.florian-schlachter.de/post/pongo2/) [June 29th 2014] ## Caveats ### Filters * **date** / **time**: The `date` and `time` filter are taking the Golang specific time- and date-format (not Django's one) currently. [Take a look on the format here](http://golang.org/pkg/time/#Time.Format). * **stringformat**: `stringformat` does **not** take Python's string format syntax as a parameter, instead it takes Go's. Essentially `{{ 3.14|stringformat:"pi is %.2f" }}` is `fmt.Sprintf("pi is %.2f", 3.14)`. * **escape** / **force_escape**: Unlike Django's behaviour, the `escape`-filter is applied immediately. Therefore there is no need for a `force_escape`-filter yet. ### Tags * **for**: All the `forloop` fields (like `forloop.counter`) are written with a capital letter at the beginning. For example, the `counter` can be accessed by `forloop.Counter` and the parentloop by `forloop.Parentloop`. * **now**: takes Go's time format (see **date** and **time**-filter). ### Misc * **not in-operator**: You can check whether a map/struct/string contains a key/field/substring by using the in-operator (or the negation of it): `{% if key in map %}Key is in map{% else %}Key not in map{% endif %}` or `{% if !(key in map) %}Key is NOT in map{% else %}Key is in map{% endif %}`. # Add-ons, libraries and helpers ## Official * [ponginae](https://github.com/flosch/ponginae) - A web-framework for Go (using pongo2). * [pongo2-tools](https://github.com/flosch/pongo2-tools) - Official tools and helpers for pongo2 * [pongo2-addons](https://github.com/flosch/pongo2-addons) - Official additional filters/tags for pongo2 (for example a **markdown**-filter). They are in their own repository because they're relying on 3rd-party-libraries. ## 3rd-party * [beego-pongo2](https://github.com/oal/beego-pongo2) - A tiny little helper for using Pongo2 with [Beego](https://github.com/astaxie/beego). * [beego-pongo2.v2](https://github.com/ipfans/beego-pongo2.v2) - Same as `beego-pongo2`, but for pongo2 v2. * [macaron-pongo2](https://github.com/macaron-contrib/pongo2) - pongo2 support for [Macaron](https://github.com/Unknwon/macaron), a modular web framework. * [ginpongo2](https://github.com/ngerakines/ginpongo2) - middleware for [gin](github.com/gin-gonic/gin) to use pongo2 templates * [pongo2-trans](https://github.com/fromYukki/pongo2trans) - `trans`-tag implementation for internationalization Please add your project to this list and send me a pull request when you've developed something nice for pongo2. # API-usage examples Please see the documentation for a full list of provided API methods. ## A tiny example (template string) ```Go // Compile the template first (i. e. creating the AST) tpl, err := pongo2.FromString("Hello {{ name|capfirst }}!") if err != nil { panic(err) } // Now you can render the template with the given // pongo2.Context how often you want to. out, err := tpl.Execute(pongo2.Context{"name": "florian"}) if err != nil { panic(err) } fmt.Println(out) // Output: Hello Florian! ``` ## Example server-usage (template file) ```Go package main import ( "github.com/flosch/pongo2" "net/http" ) // Pre-compiling the templates at application startup using the // little Must()-helper function (Must() will panic if FromFile() // or FromString() will return with an error - that's it). // It's faster to pre-compile it anywhere at startup and only // execute the template later. var tplExample = pongo2.Must(pongo2.FromFile("example.html")) func examplePage(w http.ResponseWriter, r *http.Request) { // Execute the template per HTTP request err := tplExample.ExecuteWriter(pongo2.Context{"query": r.FormValue("query")}, w) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func main() { http.HandleFunc("/", examplePage) http.ListenAndServe(":8080", nil) } ``` # Benchmark The benchmarks have been run on the my machine (`Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz`) using the command: go test -bench . -cpu 1,2,4,8 All benchmarks are compiling (depends on the benchmark) and executing the `template_tests/complex.tpl` template. The results are: BenchmarkExecuteComplexWithSandboxActive 50000 60450 ns/op BenchmarkExecuteComplexWithSandboxActive-2 50000 56998 ns/op BenchmarkExecuteComplexWithSandboxActive-4 50000 60343 ns/op BenchmarkExecuteComplexWithSandboxActive-8 50000 64229 ns/op BenchmarkCompileAndExecuteComplexWithSandboxActive 10000 164410 ns/op BenchmarkCompileAndExecuteComplexWithSandboxActive-2 10000 156682 ns/op BenchmarkCompileAndExecuteComplexWithSandboxActive-4 10000 164821 ns/op BenchmarkCompileAndExecuteComplexWithSandboxActive-8 10000 171806 ns/op BenchmarkParallelExecuteComplexWithSandboxActive 50000 60428 ns/op BenchmarkParallelExecuteComplexWithSandboxActive-2 50000 31887 ns/op BenchmarkParallelExecuteComplexWithSandboxActive-4 100000 22810 ns/op BenchmarkParallelExecuteComplexWithSandboxActive-8 100000 18820 ns/op BenchmarkExecuteComplexWithoutSandbox 50000 56942 ns/op BenchmarkExecuteComplexWithoutSandbox-2 50000 56168 ns/op BenchmarkExecuteComplexWithoutSandbox-4 50000 57838 ns/op BenchmarkExecuteComplexWithoutSandbox-8 50000 60539 ns/op BenchmarkCompileAndExecuteComplexWithoutSandbox 10000 162086 ns/op BenchmarkCompileAndExecuteComplexWithoutSandbox-2 10000 159771 ns/op BenchmarkCompileAndExecuteComplexWithoutSandbox-4 10000 163826 ns/op BenchmarkCompileAndExecuteComplexWithoutSandbox-8 10000 169062 ns/op BenchmarkParallelExecuteComplexWithoutSandbox 50000 57152 ns/op BenchmarkParallelExecuteComplexWithoutSandbox-2 50000 30276 ns/op BenchmarkParallelExecuteComplexWithoutSandbox-4 100000 22065 ns/op BenchmarkParallelExecuteComplexWithoutSandbox-8 100000 18034 ns/op Benchmarked on October 2nd 2014. ����������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/LICENSE�����������������������������������������������0000644�0610621�0607500�00000002102�13172163432�022751� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The MIT License (MIT) Copyright (c) 2013-2014 Florian Schlachter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/AUTHORS�����������������������������������������������0000644�0610621�0607500�00000000363�13172163432�023023� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Main author and maintainer of pongo2: * Florian Schlachter <flori@n-schlachter.de> Contributors (in no specific order): * @romanoaugusto88 * @vitalbh Feel free to add yourself to the list or to modify your entry if you did a contribution. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/flosch/pongo2.v3/.travis.yml�������������������������������������������0000644�0610621�0607500�00000000620�13172163432�024060� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go: - 1.3 - tip install: - go get code.google.com/p/go.tools/cmd/cover - go get github.com/mattn/goveralls - go get gopkg.in/check.v1 script: - go test -v -covermode=count -coverprofile=coverage.out -bench . -cpu 1,4 - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN || true' ����������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163414�022107� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/����������������������������������������������0000755�0610621�0607500�00000000000�13172163415�023365� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/�����������������������������������������0000755�0610621�0607500�00000000000�13172163415�024334� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_windows.go����������������������0000644�0610621�0607500�00000001132�13172163415�030245� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package term import ( "syscall" "unsafe" ) var kernel32 = syscall.NewLazyDLL("kernel32.dll") var ( procGetConsoleMode = kernel32.NewProc("GetConsoleMode") ) // IsTty returns true if the given file descriptor is a terminal. func IsTty(fd uintptr) bool { var st uint32 r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) return r != 0 && e == 0 } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_solaris.go����������������������0000644�0610621�0607500�00000000331�13172163415�030227� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package term import "golang.org/x/sys/unix" // IsTty returns true if the given file descriptor is a terminal. func IsTty(fd uintptr) bool { _, err := unix.IoctlGetTermios(int(fd), unix.TCGETA) return err == nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_openbsd.go����������������������0000644�0610621�0607500�00000000150�13172163415�030204� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package term import "syscall" const ioctlReadTermios = syscall.TIOCGETA type Termios syscall.Termios ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_notwindows.go�������������������0000644�0610621�0607500�00000001037�13172163415�030772� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux,!appengine darwin freebsd openbsd netbsd package term import ( "syscall" "unsafe" ) // IsTty returns true if the given file descriptor is a terminal. func IsTty(fd uintptr) bool { var termios Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_netbsd.go�����������������������0000644�0610621�0607500�00000000150�13172163415�030031� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package term import "syscall" const ioctlReadTermios = syscall.TIOCGETA type Termios syscall.Termios ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_linux.go������������������������0000644�0610621�0607500�00000000466�13172163415�027723� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !appengine package term import "syscall" const ioctlReadTermios = syscall.TCGETS type Termios syscall.Termios ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_freebsd.go����������������������0000644�0610621�0607500�00000000516�13172163415�030172� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package term import ( "syscall" ) const ioctlReadTermios = syscall.TIOCGETA // Go 1.2 doesn't include Termios for FreeBSD. This should be added in 1.3 and this could be merged with terminal_darwin. type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_darwin.go�����������������������0000644�0610621�0607500�00000000467�13172163415�030051� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !appengine package term import "syscall" const ioctlReadTermios = syscall.TIOCGETA type Termios syscall.Termios ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/terminal_appengine.go��������������������0000644�0610621�0607500�00000000467�13172163415�030533� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build appengine package term // IsTty always returns false on AppEngine. func IsTty(fd uintptr) bool { return false } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/term/LICENSE����������������������������������0000644�0610621�0607500�00000002072�13172163415�025342� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The MIT License (MIT) Copyright (c) 2014 Simon Eskildsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/syslog.go�������������������������������������0000644�0610621�0607500�00000003010�13172163415�025226� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows,!plan9 package log15 import ( "log/syslog" "strings" ) // SyslogHandler opens a connection to the system syslog daemon by calling // syslog.New and writes all records to it. func SyslogHandler(priority syslog.Priority, tag string, fmtr Format) (Handler, error) { wr, err := syslog.New(priority, tag) return sharedSyslog(fmtr, wr, err) } // SyslogNetHandler opens a connection to a log daemon over the network and writes // all log records to it. func SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) (Handler, error) { wr, err := syslog.Dial(net, addr, priority, tag) return sharedSyslog(fmtr, wr, err) } func sharedSyslog(fmtr Format, sysWr *syslog.Writer, err error) (Handler, error) { if err != nil { return nil, err } h := FuncHandler(func(r *Record) error { var syslogFn = sysWr.Info switch r.Lvl { case LvlCrit: syslogFn = sysWr.Crit case LvlError: syslogFn = sysWr.Err case LvlWarn: syslogFn = sysWr.Warning case LvlInfo: syslogFn = sysWr.Info case LvlDebug: syslogFn = sysWr.Debug } s := strings.TrimSpace(string(fmtr.Format(r))) return syslogFn(s) }) return LazyHandler(&closingHandler{sysWr, h}), nil } func (m muster) SyslogHandler(priority syslog.Priority, tag string, fmtr Format) Handler { return must(SyslogHandler(priority, tag, fmtr)) } func (m muster) SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) Handler { return must(SyslogNetHandler(net, addr, priority, tag, fmtr)) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/root.go���������������������������������������0000644�0610621�0607500�00000003210�13172163415�024673� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "os" "github.com/inconshreveable/log15/term" "github.com/mattn/go-colorable" ) var ( root *logger StdoutHandler = StreamHandler(os.Stdout, LogfmtFormat()) StderrHandler = StreamHandler(os.Stderr, LogfmtFormat()) ) func init() { if term.IsTty(os.Stdout.Fd()) { StdoutHandler = StreamHandler(colorable.NewColorableStdout(), TerminalFormat()) } if term.IsTty(os.Stderr.Fd()) { StderrHandler = StreamHandler(colorable.NewColorableStderr(), TerminalFormat()) } root = &logger{[]interface{}{}, new(swapHandler)} root.SetHandler(StdoutHandler) } // New returns a new logger with the given context. // New is a convenient alias for Root().New func New(ctx ...interface{}) Logger { return root.New(ctx...) } // Root returns the root logger func Root() Logger { return root } // The following functions bypass the exported logger methods (logger.Debug, // etc.) to keep the call depth the same for all paths to logger.write so // runtime.Caller(2) always refers to the call site in client code. // Debug is a convenient alias for Root().Debug func Debug(msg string, ctx ...interface{}) { root.write(msg, LvlDebug, ctx) } // Info is a convenient alias for Root().Info func Info(msg string, ctx ...interface{}) { root.write(msg, LvlInfo, ctx) } // Warn is a convenient alias for Root().Warn func Warn(msg string, ctx ...interface{}) { root.write(msg, LvlWarn, ctx) } // Error is a convenient alias for Root().Error func Error(msg string, ctx ...interface{}) { root.write(msg, LvlError, ctx) } // Crit is a convenient alias for Root().Crit func Crit(msg string, ctx ...interface{}) { root.write(msg, LvlCrit, ctx) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/logger.go�������������������������������������0000644�0610621�0607500�00000011070�13172163415�025172� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "fmt" "time" "github.com/go-stack/stack" ) const timeKey = "t" const lvlKey = "lvl" const msgKey = "msg" const errorKey = "LOG15_ERROR" type Lvl int const ( LvlCrit Lvl = iota LvlError LvlWarn LvlInfo LvlDebug ) // Returns the name of a Lvl func (l Lvl) String() string { switch l { case LvlDebug: return "dbug" case LvlInfo: return "info" case LvlWarn: return "warn" case LvlError: return "eror" case LvlCrit: return "crit" default: panic("bad level") } } // Returns the appropriate Lvl from a string name. // Useful for parsing command line args and configuration files. func LvlFromString(lvlString string) (Lvl, error) { switch lvlString { case "debug", "dbug": return LvlDebug, nil case "info": return LvlInfo, nil case "warn": return LvlWarn, nil case "error", "eror": return LvlError, nil case "crit": return LvlCrit, nil default: return LvlDebug, fmt.Errorf("Unknown level: %v", lvlString) } } // A Record is what a Logger asks its handler to write type Record struct { Time time.Time Lvl Lvl Msg string Ctx []interface{} Call stack.Call KeyNames RecordKeyNames } type RecordKeyNames struct { Time string Msg string Lvl string } // A Logger writes key/value pairs to a Handler type Logger interface { // New returns a new Logger that has this logger's context plus the given context New(ctx ...interface{}) Logger // GetHandler gets the handler associated with the logger. GetHandler() Handler // SetHandler updates the logger to write records to the specified handler. SetHandler(h Handler) // Log a message at the given level with context key/value pairs Debug(msg string, ctx ...interface{}) Info(msg string, ctx ...interface{}) Warn(msg string, ctx ...interface{}) Error(msg string, ctx ...interface{}) Crit(msg string, ctx ...interface{}) } type logger struct { ctx []interface{} h *swapHandler } func (l *logger) write(msg string, lvl Lvl, ctx []interface{}) { l.h.Log(&Record{ Time: time.Now(), Lvl: lvl, Msg: msg, Ctx: newContext(l.ctx, ctx), Call: stack.Caller(2), KeyNames: RecordKeyNames{ Time: timeKey, Msg: msgKey, Lvl: lvlKey, }, }) } func (l *logger) New(ctx ...interface{}) Logger { child := &logger{newContext(l.ctx, ctx), new(swapHandler)} child.SetHandler(l.h) return child } func newContext(prefix []interface{}, suffix []interface{}) []interface{} { normalizedSuffix := normalize(suffix) newCtx := make([]interface{}, len(prefix)+len(normalizedSuffix)) n := copy(newCtx, prefix) copy(newCtx[n:], normalizedSuffix) return newCtx } func (l *logger) Debug(msg string, ctx ...interface{}) { l.write(msg, LvlDebug, ctx) } func (l *logger) Info(msg string, ctx ...interface{}) { l.write(msg, LvlInfo, ctx) } func (l *logger) Warn(msg string, ctx ...interface{}) { l.write(msg, LvlWarn, ctx) } func (l *logger) Error(msg string, ctx ...interface{}) { l.write(msg, LvlError, ctx) } func (l *logger) Crit(msg string, ctx ...interface{}) { l.write(msg, LvlCrit, ctx) } func (l *logger) GetHandler() Handler { return l.h.Get() } func (l *logger) SetHandler(h Handler) { l.h.Swap(h) } func normalize(ctx []interface{}) []interface{} { // if the caller passed a Ctx object, then expand it if len(ctx) == 1 { if ctxMap, ok := ctx[0].(Ctx); ok { ctx = ctxMap.toArray() } } // ctx needs to be even because it's a series of key/value pairs // no one wants to check for errors on logging functions, // so instead of erroring on bad input, we'll just make sure // that things are the right length and users can fix bugs // when they see the output looks wrong if len(ctx)%2 != 0 { ctx = append(ctx, nil, errorKey, "Normalized odd number of arguments by adding nil") } return ctx } // Lazy allows you to defer calculation of a logged value that is expensive // to compute until it is certain that it must be evaluated with the given filters. // // Lazy may also be used in conjunction with a Logger's New() function // to generate a child logger which always reports the current value of changing // state. // // You may wrap any function which takes no arguments to Lazy. It may return any // number of values of any type. type Lazy struct { Fn interface{} } // Ctx is a map of key/value pairs to pass as context to a log function // Use this only if you really need greater safety around the arguments you pass // to the logging functions. type Ctx map[string]interface{} func (c Ctx) toArray() []interface{} { arr := make([]interface{}, len(c)*2) i := 0 for k, v := range c { arr[i] = k arr[i+1] = v i += 2 } return arr } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/log15_test.go���������������������������������0000644�0610621�0607500�00000027551�13172163415�025714� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "net" "regexp" "runtime" "sync" "testing" "time" ) func testHandler() (Handler, *Record) { rec := new(Record) return FuncHandler(func(r *Record) error { *rec = *r return nil }), rec } func testLogger() (Logger, Handler, *Record) { l := New() h, r := testHandler() l.SetHandler(LazyHandler(h)) return l, h, r } func TestLazy(t *testing.T) { t.Parallel() x := 1 lazy := func() int { return x } l, _, r := testLogger() l.Info("", "x", Lazy{lazy}) if r.Ctx[1] != 1 { t.Fatalf("Lazy function not evaluated, got %v, expected %d", r.Ctx[1], 1) } x = 2 l.Info("", "x", Lazy{lazy}) if r.Ctx[1] != 2 { t.Fatalf("Lazy function not evaluated, got %v, expected %d", r.Ctx[1], 1) } } func TestInvalidLazy(t *testing.T) { t.Parallel() l, _, r := testLogger() validate := func() { if len(r.Ctx) < 4 { t.Fatalf("Invalid lazy, got %d args, expecting at least 4", len(r.Ctx)) } if r.Ctx[2] != errorKey { t.Fatalf("Invalid lazy, got key %s expecting %s", r.Ctx[2], errorKey) } } l.Info("", "x", Lazy{1}) validate() l.Info("", "x", Lazy{func(x int) int { return x }}) validate() l.Info("", "x", Lazy{func() {}}) validate() } func TestCtx(t *testing.T) { t.Parallel() l, _, r := testLogger() l.Info("", Ctx{"x": 1, "y": "foo", "tester": t}) if len(r.Ctx) != 6 { t.Fatalf("Expecting Ctx tansformed into %d ctx args, got %d: %v", 6, len(r.Ctx), r.Ctx) } } func testFormatter(f Format) (Logger, *bytes.Buffer) { l := New() var buf bytes.Buffer l.SetHandler(StreamHandler(&buf, f)) return l, &buf } func TestJson(t *testing.T) { t.Parallel() l, buf := testFormatter(JsonFormat()) l.Error("some message", "x", 1, "y", 3.2) var v map[string]interface{} decoder := json.NewDecoder(buf) if err := decoder.Decode(&v); err != nil { t.Fatalf("Error decoding JSON: %v", v) } validate := func(key string, expected interface{}) { if v[key] != expected { t.Fatalf("Got %v expected %v for %v", v[key], expected, key) } } validate("msg", "some message") validate("x", float64(1)) // all numbers are floats in JSON land validate("y", 3.2) validate("lvl", "eror") } type testtype struct { name string } func (tt testtype) String() string { return tt.name } func TestLogfmt(t *testing.T) { t.Parallel() var nilVal *testtype l, buf := testFormatter(LogfmtFormat()) l.Error("some message", "x", 1, "y", 3.2, "equals", "=", "quote", "\"", "nil", nilVal, "carriage_return", "bang"+string('\r')+"foo", "tab", "bar baz", "newline", "foo\nbar") // skip timestamp in comparison got := buf.Bytes()[27:buf.Len()] expected := []byte(`lvl=eror msg="some message" x=1 y=3.200 equals="=" quote="\"" nil=nil carriage_return="bang\rfoo" tab="bar\tbaz" newline="foo\nbar"` + "\n") if !bytes.Equal(got, expected) { t.Fatalf("Got %s, expected %s", got, expected) } } func TestMultiHandler(t *testing.T) { t.Parallel() h1, r1 := testHandler() h2, r2 := testHandler() l := New() l.SetHandler(MultiHandler(h1, h2)) l.Debug("clone") if r1.Msg != "clone" { t.Fatalf("wrong value for h1.Msg. Got %s expected %s", r1.Msg, "clone") } if r2.Msg != "clone" { t.Fatalf("wrong value for h2.Msg. Got %s expected %s", r2.Msg, "clone") } } type waitHandler struct { ch chan Record } func (h *waitHandler) Log(r *Record) error { h.ch <- *r return nil } func TestBufferedHandler(t *testing.T) { t.Parallel() ch := make(chan Record) l := New() l.SetHandler(BufferedHandler(0, &waitHandler{ch})) l.Debug("buffer") if r := <-ch; r.Msg != "buffer" { t.Fatalf("wrong value for r.Msg. Got %s expected %s", r.Msg, "") } } func TestLogContext(t *testing.T) { t.Parallel() l, _, r := testLogger() l = l.New("foo", "bar") l.Crit("baz") if len(r.Ctx) != 2 { t.Fatalf("Expected logger context in record context. Got length %d, expected %d", len(r.Ctx), 2) } if r.Ctx[0] != "foo" { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], "foo") } if r.Ctx[1] != "bar" { t.Fatalf("Wrong context value, got %s expected %s", r.Ctx[1], "bar") } } func TestMapCtx(t *testing.T) { t.Parallel() l, _, r := testLogger() l.Crit("test", Ctx{"foo": "bar"}) if len(r.Ctx) != 2 { t.Fatalf("Wrong context length, got %d, expected %d", len(r.Ctx), 2) } if r.Ctx[0] != "foo" { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], "foo") } if r.Ctx[1] != "bar" { t.Fatalf("Wrong context value, got %s expected %s", r.Ctx[1], "bar") } } func TestLvlFilterHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() l.SetHandler(LvlFilterHandler(LvlWarn, h)) l.Info("info'd") if r.Msg != "" { t.Fatalf("Expected zero record, but got record with msg: %v", r.Msg) } l.Warn("warned") if r.Msg != "warned" { t.Fatalf("Got record msg %s expected %s", r.Msg, "warned") } l.Warn("error'd") if r.Msg != "error'd" { t.Fatalf("Got record msg %s expected %s", r.Msg, "error'd") } } func TestNetHandler(t *testing.T) { t.Parallel() l, err := net.Listen("tcp", "localhost:0") if err != nil { t.Fatalf("Failed to listen: %v", l) } errs := make(chan error) go func() { c, err := l.Accept() if err != nil { errs <- fmt.Errorf("Failed to accept connection: %v", err) return } rd := bufio.NewReader(c) s, err := rd.ReadString('\n') if err != nil { errs <- fmt.Errorf("Failed to read string: %v", err) return } got := s[27:] expected := "lvl=info msg=test x=1\n" if got != expected { t.Errorf("Got log line %s, expected %s", got, expected) } errs <- nil }() lg := New() h, err := NetHandler("tcp", l.Addr().String(), LogfmtFormat()) if err != nil { t.Fatal(err) } lg.SetHandler(h) lg.Info("test", "x", 1) select { case <-time.After(time.Second): t.Fatalf("Test timed out!") case err := <-errs: if err != nil { t.Fatal(err) } } } func TestMatchFilterHandler(t *testing.T) { t.Parallel() l, h, r := testLogger() l.SetHandler(MatchFilterHandler("err", nil, h)) l.Crit("test", "foo", "bar") if r.Msg != "" { t.Fatalf("expected filter handler to discard msg") } l.Crit("test2", "err", "bad fd") if r.Msg != "" { t.Fatalf("expected filter handler to discard msg") } l.Crit("test3", "err", nil) if r.Msg != "test3" { t.Fatalf("expected filter handler to allow msg") } } func TestMatchFilterBuiltin(t *testing.T) { t.Parallel() l, h, r := testLogger() l.SetHandler(MatchFilterHandler("lvl", LvlError, h)) l.Info("does not pass") if r.Msg != "" { t.Fatalf("got info level record that should not have matched") } l.Error("error!") if r.Msg != "error!" { t.Fatalf("did not get error level record that should have matched") } r.Msg = "" l.SetHandler(MatchFilterHandler("msg", "matching message", h)) l.Info("doesn't match") if r.Msg != "" { t.Fatalf("got record with wrong message matched") } l.Debug("matching message") if r.Msg != "matching message" { t.Fatalf("did not get record which matches") } } type failingWriter struct { fail bool } func (w *failingWriter) Write(buf []byte) (int, error) { if w.fail { return 0, errors.New("fail") } else { return len(buf), nil } } func TestFailoverHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() w := &failingWriter{false} l.SetHandler(FailoverHandler( StreamHandler(w, JsonFormat()), h)) l.Debug("test ok") if r.Msg != "" { t.Fatalf("expected no failover") } w.fail = true l.Debug("test failover", "x", 1) if r.Msg != "test failover" { t.Fatalf("expected failover") } if len(r.Ctx) != 4 { t.Fatalf("expected additional failover ctx") } got := r.Ctx[2] expected := "failover_err_0" if got != expected { t.Fatalf("expected failover ctx. got: %s, expected %s", got, expected) } } // https://github.com/inconshreveable/log15/issues/16 func TestIndependentSetHandler(t *testing.T) { t.Parallel() parent, _, r := testLogger() child := parent.New() child.SetHandler(DiscardHandler()) parent.Info("test") if r.Msg != "test" { t.Fatalf("parent handler affected by child") } } // https://github.com/inconshreveable/log15/issues/16 func TestInheritHandler(t *testing.T) { t.Parallel() parent, _, r := testLogger() child := parent.New() parent.SetHandler(DiscardHandler()) child.Info("test") if r.Msg == "test" { t.Fatalf("child handler affected not affected by parent") } } func TestCallerFileHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() l.SetHandler(CallerFileHandler(h)) l.Info("baz") _, _, line, _ := runtime.Caller(0) if len(r.Ctx) != 2 { t.Fatalf("Expected caller in record context. Got length %d, expected %d", len(r.Ctx), 2) } const key = "caller" if r.Ctx[0] != key { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], key) } s, ok := r.Ctx[1].(string) if !ok { t.Fatalf("Wrong context value type, got %T expected string", r.Ctx[1]) } exp := fmt.Sprint("log15_test.go:", line-1) if s != exp { t.Fatalf("Wrong context value, got %s expected string matching %s", s, exp) } } func TestCallerFuncHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() l.SetHandler(CallerFuncHandler(h)) l.Info("baz") if len(r.Ctx) != 2 { t.Fatalf("Expected caller in record context. Got length %d, expected %d", len(r.Ctx), 2) } const key = "fn" if r.Ctx[0] != key { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], key) } const regex = ".*\\.TestCallerFuncHandler" s, ok := r.Ctx[1].(string) if !ok { t.Fatalf("Wrong context value type, got %T expected string", r.Ctx[1]) } match, err := regexp.MatchString(regex, s) if err != nil { t.Fatalf("Error matching %s to regex %s: %v", s, regex, err) } if !match { t.Fatalf("Wrong context value, got %s expected string matching %s", s, regex) } } // https://github.com/inconshreveable/log15/issues/27 func TestCallerStackHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() l.SetHandler(CallerStackHandler("%#v", h)) lines := []int{} func() { l.Info("baz") _, _, line, _ := runtime.Caller(0) lines = append(lines, line-1) }() _, file, line, _ := runtime.Caller(0) lines = append(lines, line-1) if len(r.Ctx) != 2 { t.Fatalf("Expected stack in record context. Got length %d, expected %d", len(r.Ctx), 2) } const key = "stack" if r.Ctx[0] != key { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], key) } s, ok := r.Ctx[1].(string) if !ok { t.Fatalf("Wrong context value type, got %T expected string", r.Ctx[1]) } exp := "[" for i, line := range lines { if i > 0 { exp += " " } exp += fmt.Sprint(file, ":", line) } exp += "]" if s != exp { t.Fatalf("Wrong context value, got %s expected string matching %s", s, exp) } } // tests that when logging concurrently to the same logger // from multiple goroutines that the calls are handled independently // this test tries to trigger a previous bug where concurrent calls could // corrupt each other's context values // // this test runs N concurrent goroutines each logging a fixed number of // records and a handler that buckets them based on the index passed in the context. // if the logger is not concurrent-safe then the values in the buckets will not all be the same // // https://github.com/inconshreveable/log15/pull/30 func TestConcurrent(t *testing.T) { root := New() // this was the first value that triggered // go to allocate extra capacity in the logger's context slice which // was necessary to trigger the bug const ctxLen = 34 l := root.New(make([]interface{}, ctxLen)...) const goroutines = 8 var res [goroutines]int l.SetHandler(SyncHandler(FuncHandler(func(r *Record) error { res[r.Ctx[ctxLen+1].(int)]++ return nil }))) var wg sync.WaitGroup wg.Add(goroutines) for i := 0; i < goroutines; i++ { go func(idx int) { defer wg.Done() for j := 0; j < 10000; j++ { l.Info("test message", "goroutine_idx", idx) } }(i) } wg.Wait() for _, val := range res[:] { if val != 10000 { t.Fatalf("Wrong number of messages for context: %+v", res) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/handler_go14.go�������������������������������0000644�0610621�0607500�00000000727�13172163415�026171� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.4 package log15 import "sync/atomic" // swapHandler wraps another handler that may be swapped out // dynamically at runtime in a thread-safe fashion. type swapHandler struct { handler atomic.Value } func (h *swapHandler) Log(r *Record) error { return (*h.handler.Load().(*Handler)).Log(r) } func (h *swapHandler) Swap(newHandler Handler) { h.handler.Store(&newHandler) } func (h *swapHandler) Get() Handler { return *h.handler.Load().(*Handler) } �����������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/handler_go13.go�������������������������������0000644�0610621�0607500�00000001001�13172163415�026152� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.4 package log15 import ( "sync/atomic" "unsafe" ) // swapHandler wraps another handler that may be swapped out // dynamically at runtime in a thread-safe fashion. type swapHandler struct { handler unsafe.Pointer } func (h *swapHandler) Log(r *Record) error { return h.Get().Log(r) } func (h *swapHandler) Get() Handler { return *(*Handler)(atomic.LoadPointer(&h.handler)) } func (h *swapHandler) Swap(newHandler Handler) { atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler)) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/handler.go������������������������������������0000644�0610621�0607500�00000024052�13172163415�025334� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "fmt" "io" "net" "os" "reflect" "sync" "github.com/go-stack/stack" ) // A Logger prints its log records by writing to a Handler. // The Handler interface defines where and how log records are written. // Handlers are composable, providing you great flexibility in combining // them to achieve the logging structure that suits your applications. type Handler interface { Log(r *Record) error } // FuncHandler returns a Handler that logs records with the given // function. func FuncHandler(fn func(r *Record) error) Handler { return funcHandler(fn) } type funcHandler func(r *Record) error func (h funcHandler) Log(r *Record) error { return h(r) } // StreamHandler writes log records to an io.Writer // with the given format. StreamHandler can be used // to easily begin writing log records to other // outputs. // // StreamHandler wraps itself with LazyHandler and SyncHandler // to evaluate Lazy objects and perform safe concurrent writes. func StreamHandler(wr io.Writer, fmtr Format) Handler { h := FuncHandler(func(r *Record) error { _, err := wr.Write(fmtr.Format(r)) return err }) return LazyHandler(SyncHandler(h)) } // SyncHandler can be wrapped around a handler to guarantee that // only a single Log operation can proceed at a time. It's necessary // for thread-safe concurrent writes. func SyncHandler(h Handler) Handler { var mu sync.Mutex return FuncHandler(func(r *Record) error { defer mu.Unlock() mu.Lock() return h.Log(r) }) } // FileHandler returns a handler which writes log records to the give file // using the given format. If the path // already exists, FileHandler will append to the given file. If it does not, // FileHandler will create the file with mode 0644. func FileHandler(path string, fmtr Format) (Handler, error) { f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { return nil, err } return closingHandler{f, StreamHandler(f, fmtr)}, nil } // NetHandler opens a socket to the given address and writes records // over the connection. func NetHandler(network, addr string, fmtr Format) (Handler, error) { conn, err := net.Dial(network, addr) if err != nil { return nil, err } return closingHandler{conn, StreamHandler(conn, fmtr)}, nil } // XXX: closingHandler is essentially unused at the moment // it's meant for a future time when the Handler interface supports // a possible Close() operation type closingHandler struct { io.WriteCloser Handler } func (h *closingHandler) Close() error { return h.WriteCloser.Close() } // CallerFileHandler returns a Handler that adds the line number and file of // the calling function to the context with key "caller". func CallerFileHandler(h Handler) Handler { return FuncHandler(func(r *Record) error { r.Ctx = append(r.Ctx, "caller", fmt.Sprint(r.Call)) return h.Log(r) }) } // CallerFuncHandler returns a Handler that adds the calling function name to // the context with key "fn". func CallerFuncHandler(h Handler) Handler { return FuncHandler(func(r *Record) error { r.Ctx = append(r.Ctx, "fn", fmt.Sprintf("%+n", r.Call)) return h.Log(r) }) } // CallerStackHandler returns a Handler that adds a stack trace to the context // with key "stack". The stack trace is formated as a space separated list of // call sites inside matching []'s. The most recent call site is listed first. // Each call site is formatted according to format. See the documentation of // package github.com/go-stack/stack for the list of supported formats. func CallerStackHandler(format string, h Handler) Handler { return FuncHandler(func(r *Record) error { s := stack.Trace().TrimBelow(r.Call).TrimRuntime() if len(s) > 0 { r.Ctx = append(r.Ctx, "stack", fmt.Sprintf(format, s)) } return h.Log(r) }) } // FilterHandler returns a Handler that only writes records to the // wrapped Handler if the given function evaluates true. For example, // to only log records where the 'err' key is not nil: // // logger.SetHandler(FilterHandler(func(r *Record) bool { // for i := 0; i < len(r.Ctx); i += 2 { // if r.Ctx[i] == "err" { // return r.Ctx[i+1] != nil // } // } // return false // }, h)) // func FilterHandler(fn func(r *Record) bool, h Handler) Handler { return FuncHandler(func(r *Record) error { if fn(r) { return h.Log(r) } return nil }) } // MatchFilterHandler returns a Handler that only writes records // to the wrapped Handler if the given key in the logged // context matches the value. For example, to only log records // from your ui package: // // log.MatchFilterHandler("pkg", "app/ui", log.StdoutHandler) // func MatchFilterHandler(key string, value interface{}, h Handler) Handler { return FilterHandler(func(r *Record) (pass bool) { switch key { case r.KeyNames.Lvl: return r.Lvl == value case r.KeyNames.Time: return r.Time == value case r.KeyNames.Msg: return r.Msg == value } for i := 0; i < len(r.Ctx); i += 2 { if r.Ctx[i] == key { return r.Ctx[i+1] == value } } return false }, h) } // LvlFilterHandler returns a Handler that only writes // records which are less than the given verbosity // level to the wrapped Handler. For example, to only // log Error/Crit records: // // log.LvlFilterHandler(log.LvlError, log.StdoutHandler) // func LvlFilterHandler(maxLvl Lvl, h Handler) Handler { return FilterHandler(func(r *Record) (pass bool) { return r.Lvl <= maxLvl }, h) } // A MultiHandler dispatches any write to each of its handlers. // This is useful for writing different types of log information // to different locations. For example, to log to a file and // standard error: // // log.MultiHandler( // log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()), // log.StderrHandler) // func MultiHandler(hs ...Handler) Handler { return FuncHandler(func(r *Record) error { for _, h := range hs { // what to do about failures? h.Log(r) } return nil }) } // A FailoverHandler writes all log records to the first handler // specified, but will failover and write to the second handler if // the first handler has failed, and so on for all handlers specified. // For example you might want to log to a network socket, but failover // to writing to a file if the network fails, and then to // standard out if the file write fails: // // log.FailoverHandler( // log.Must.NetHandler("tcp", ":9090", log.JsonFormat()), // log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()), // log.StdoutHandler) // // All writes that do not go to the first handler will add context with keys of // the form "failover_err_{idx}" which explain the error encountered while // trying to write to the handlers before them in the list. func FailoverHandler(hs ...Handler) Handler { return FuncHandler(func(r *Record) error { var err error for i, h := range hs { err = h.Log(r) if err == nil { return nil } else { r.Ctx = append(r.Ctx, fmt.Sprintf("failover_err_%d", i), err) } } return err }) } // ChannelHandler writes all records to the given channel. // It blocks if the channel is full. Useful for async processing // of log messages, it's used by BufferedHandler. func ChannelHandler(recs chan<- *Record) Handler { return FuncHandler(func(r *Record) error { recs <- r return nil }) } // BufferedHandler writes all records to a buffered // channel of the given size which flushes into the wrapped // handler whenever it is available for writing. Since these // writes happen asynchronously, all writes to a BufferedHandler // never return an error and any errors from the wrapped handler are ignored. func BufferedHandler(bufSize int, h Handler) Handler { recs := make(chan *Record, bufSize) go func() { for m := range recs { _ = h.Log(m) } }() return ChannelHandler(recs) } // LazyHandler writes all values to the wrapped handler after evaluating // any lazy functions in the record's context. It is already wrapped // around StreamHandler and SyslogHandler in this library, you'll only need // it if you write your own Handler. func LazyHandler(h Handler) Handler { return FuncHandler(func(r *Record) error { // go through the values (odd indices) and reassign // the values of any lazy fn to the result of its execution hadErr := false for i := 1; i < len(r.Ctx); i += 2 { lz, ok := r.Ctx[i].(Lazy) if ok { v, err := evaluateLazy(lz) if err != nil { hadErr = true r.Ctx[i] = err } else { if cs, ok := v.(stack.CallStack); ok { v = cs.TrimBelow(r.Call).TrimRuntime() } r.Ctx[i] = v } } } if hadErr { r.Ctx = append(r.Ctx, errorKey, "bad lazy") } return h.Log(r) }) } func evaluateLazy(lz Lazy) (interface{}, error) { t := reflect.TypeOf(lz.Fn) if t.Kind() != reflect.Func { return nil, fmt.Errorf("INVALID_LAZY, not func: %+v", lz.Fn) } if t.NumIn() > 0 { return nil, fmt.Errorf("INVALID_LAZY, func takes args: %+v", lz.Fn) } if t.NumOut() == 0 { return nil, fmt.Errorf("INVALID_LAZY, no func return val: %+v", lz.Fn) } value := reflect.ValueOf(lz.Fn) results := value.Call([]reflect.Value{}) if len(results) == 1 { return results[0].Interface(), nil } else { values := make([]interface{}, len(results)) for i, v := range results { values[i] = v.Interface() } return values, nil } } // DiscardHandler reports success for all writes but does nothing. // It is useful for dynamically disabling logging at runtime via // a Logger's SetHandler method. func DiscardHandler() Handler { return FuncHandler(func(r *Record) error { return nil }) } // The Must object provides the following Handler creation functions // which instead of returning an error parameter only return a Handler // and panic on failure: FileHandler, NetHandler, SyslogHandler, SyslogNetHandler var Must muster func must(h Handler, err error) Handler { if err != nil { panic(err) } return h } type muster struct{} func (m muster) FileHandler(path string, fmtr Format) Handler { return must(FileHandler(path, fmtr)) } func (m muster) NetHandler(network, addr string, fmtr Format) Handler { return must(NetHandler(network, addr, fmtr)) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/format.go�������������������������������������0000644�0610621�0607500�00000014312�13172163415�025205� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "bytes" "encoding/json" "fmt" "reflect" "strconv" "strings" "sync" "time" ) const ( timeFormat = "2006-01-02T15:04:05-0700" termTimeFormat = "01-02|15:04:05" floatFormat = 'f' termMsgJust = 40 ) type Format interface { Format(r *Record) []byte } // FormatFunc returns a new Format object which uses // the given function to perform record formatting. func FormatFunc(f func(*Record) []byte) Format { return formatFunc(f) } type formatFunc func(*Record) []byte func (f formatFunc) Format(r *Record) []byte { return f(r) } // TerminalFormat formats log records optimized for human readability on // a terminal with color-coded level output and terser human friendly timestamp. // This format should only be used for interactive programs or while developing. // // [TIME] [LEVEL] MESAGE key=value key=value ... // // Example: // // [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002 // func TerminalFormat() Format { return FormatFunc(func(r *Record) []byte { var color = 0 switch r.Lvl { case LvlCrit: color = 35 case LvlError: color = 31 case LvlWarn: color = 33 case LvlInfo: color = 32 case LvlDebug: color = 36 } b := &bytes.Buffer{} lvl := strings.ToUpper(r.Lvl.String()) if color > 0 { fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %s ", color, lvl, r.Time.Format(termTimeFormat), r.Msg) } else { fmt.Fprintf(b, "[%s] [%s] %s ", lvl, r.Time.Format(termTimeFormat), r.Msg) } // try to justify the log output for short messages if len(r.Ctx) > 0 && len(r.Msg) < termMsgJust { b.Write(bytes.Repeat([]byte{' '}, termMsgJust-len(r.Msg))) } // print the keys logfmt style logfmt(b, r.Ctx, color) return b.Bytes() }) } // LogfmtFormat prints records in logfmt format, an easy machine-parseable but human-readable // format for key/value pairs. // // For more details see: http://godoc.org/github.com/kr/logfmt // func LogfmtFormat() Format { return FormatFunc(func(r *Record) []byte { common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg} buf := &bytes.Buffer{} logfmt(buf, append(common, r.Ctx...), 0) return buf.Bytes() }) } func logfmt(buf *bytes.Buffer, ctx []interface{}, color int) { for i := 0; i < len(ctx); i += 2 { if i != 0 { buf.WriteByte(' ') } k, ok := ctx[i].(string) v := formatLogfmtValue(ctx[i+1]) if !ok { k, v = errorKey, formatLogfmtValue(k) } // XXX: we should probably check that all of your key bytes aren't invalid if color > 0 { fmt.Fprintf(buf, "\x1b[%dm%s\x1b[0m=%s", color, k, v) } else { buf.WriteString(k) buf.WriteByte('=') buf.WriteString(v) } } buf.WriteByte('\n') } // JsonFormat formats log records as JSON objects separated by newlines. // It is the equivalent of JsonFormatEx(false, true). func JsonFormat() Format { return JsonFormatEx(false, true) } // JsonFormatEx formats log records as JSON objects. If pretty is true, // records will be pretty-printed. If lineSeparated is true, records // will be logged with a new line between each record. func JsonFormatEx(pretty, lineSeparated bool) Format { jsonMarshal := json.Marshal if pretty { jsonMarshal = func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") } } return FormatFunc(func(r *Record) []byte { props := make(map[string]interface{}) props[r.KeyNames.Time] = r.Time props[r.KeyNames.Lvl] = r.Lvl.String() props[r.KeyNames.Msg] = r.Msg for i := 0; i < len(r.Ctx); i += 2 { k, ok := r.Ctx[i].(string) if !ok { props[errorKey] = fmt.Sprintf("%+v is not a string key", r.Ctx[i]) } props[k] = formatJsonValue(r.Ctx[i+1]) } b, err := jsonMarshal(props) if err != nil { b, _ = jsonMarshal(map[string]string{ errorKey: err.Error(), }) return b } if lineSeparated { b = append(b, '\n') } return b }) } func formatShared(value interface{}) (result interface{}) { defer func() { if err := recover(); err != nil { if v := reflect.ValueOf(value); v.Kind() == reflect.Ptr && v.IsNil() { result = "nil" } else { panic(err) } } }() switch v := value.(type) { case time.Time: return v.Format(timeFormat) case error: return v.Error() case fmt.Stringer: return v.String() default: return v } } func formatJsonValue(value interface{}) interface{} { value = formatShared(value) switch value.(type) { case int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64, string: return value default: return fmt.Sprintf("%+v", value) } } // formatValue formats a value for serialization func formatLogfmtValue(value interface{}) string { if value == nil { return "nil" } if t, ok := value.(time.Time); ok { // Performance optimization: No need for escaping since the provided // timeFormat doesn't have any escape characters, and escaping is // expensive. return t.Format(timeFormat) } value = formatShared(value) switch v := value.(type) { case bool: return strconv.FormatBool(v) case float32: return strconv.FormatFloat(float64(v), floatFormat, 3, 64) case float64: return strconv.FormatFloat(v, floatFormat, 3, 64) case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: return fmt.Sprintf("%d", value) case string: return escapeString(v) default: return escapeString(fmt.Sprintf("%+v", value)) } } var stringBufPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, } func escapeString(s string) string { needsQuotes := false needsEscape := false for _, r := range s { if r <= ' ' || r == '=' || r == '"' { needsQuotes = true } if r == '\\' || r == '"' || r == '\n' || r == '\r' || r == '\t' { needsEscape = true } } if needsEscape == false && needsQuotes == false { return s } e := stringBufPool.Get().(*bytes.Buffer) e.WriteByte('"') for _, r := range s { switch r { case '\\', '"': e.WriteByte('\\') e.WriteByte(byte(r)) case '\n': e.WriteString("\\n") case '\r': e.WriteString("\\r") case '\t': e.WriteString("\\t") default: e.WriteRune(r) } } e.WriteByte('"') var ret string if needsQuotes { ret = e.String() } else { ret = string(e.Bytes()[1 : e.Len()-1]) } e.Reset() stringBufPool.Put(e) return ret } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/ext/������������������������������������������0000755�0610621�0607500�00000000000�13172163415�024165� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/ext/id.go�������������������������������������0000644�0610621�0607500�00000001765�13172163415�025121� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ext import ( "fmt" "math/rand" "sync" "time" ) var r = rand.New(&lockedSource{src: rand.NewSource(time.Now().Unix())}) // RandId creates a random identifier of the requested length. // Useful for assigning mostly-unique identifiers for logging // and identification that are unlikely to collide because of // short lifespan or low set cardinality func RandId(idlen int) string { b := make([]byte, idlen) var randVal uint32 for i := 0; i < idlen; i++ { byteIdx := i % 4 if byteIdx == 0 { randVal = r.Uint32() } b[i] = byte((randVal >> (8 * uint(byteIdx))) & 0xFF) } return fmt.Sprintf("%x", b) } // lockedSource is a wrapper to allow a rand.Source to be used // concurrently (same type as the one used internally in math/rand). type lockedSource struct { lk sync.Mutex src rand.Source } func (r *lockedSource) Int63() (n int64) { r.lk.Lock() n = r.src.Int63() r.lk.Unlock() return } func (r *lockedSource) Seed(seed int64) { r.lk.Lock() r.src.Seed(seed) r.lk.Unlock() } �����������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/ext/handler.go��������������������������������0000644�0610621�0607500�00000006473�13172163415�026143� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ext import ( "os" "sync" "sync/atomic" "unsafe" log "github.com/inconshreveable/log15" ) // EscalateErrHandler wraps another handler and passes all records through // unchanged except if the logged context contains a non-nil error // value in its context. In that case, the record's level is raised // to LvlError unless it was already more serious (LvlCrit). // // This allows you to log the result of all functions for debugging // and still capture error conditions when in production with a single // log line. As an example, the following the log record will be written // out only if there was an error writing a value to redis: // // logger := logext.EscalateErrHandler( // log.LvlFilterHandler(log.LvlInfo, log.StdoutHandler)) // // reply, err := redisConn.Do("SET", "foo", "bar") // logger.Debug("Wrote value to redis", "reply", reply, "err", err) // if err != nil { // return err // } // func EscalateErrHandler(h log.Handler) log.Handler { return log.FuncHandler(func(r *log.Record) error { if r.Lvl > log.LvlError { for i := 1; i < len(r.Ctx); i++ { if v, ok := r.Ctx[i].(error); ok && v != nil { r.Lvl = log.LvlError break } } } return h.Log(r) }) } // SpeculativeHandler is a handler for speculative logging. It // keeps a ring buffer of the given size full of the last events // logged into it. When Flush is called, all buffered log records // are written to the wrapped handler. This is extremely for // continuosly capturing debug level output, but only flushing those // log records if an exceptional condition is encountered. func SpeculativeHandler(size int, h log.Handler) *Speculative { return &Speculative{ handler: h, recs: make([]*log.Record, size), } } type Speculative struct { mu sync.Mutex idx int recs []*log.Record handler log.Handler full bool } func (h *Speculative) Log(r *log.Record) error { h.mu.Lock() defer h.mu.Unlock() h.recs[h.idx] = r h.idx = (h.idx + 1) % len(h.recs) h.full = h.full || h.idx == 0 return nil } func (h *Speculative) Flush() { recs := make([]*log.Record, 0) func() { h.mu.Lock() defer h.mu.Unlock() if h.full { recs = append(recs, h.recs[h.idx:]...) } recs = append(recs, h.recs[:h.idx]...) // reset state h.full = false h.idx = 0 }() // don't hold the lock while we flush to the wrapped handler for _, r := range recs { h.handler.Log(r) } } // HotSwapHandler wraps another handler that may swapped out // dynamically at runtime in a thread-safe fashion. // HotSwapHandler is the same functionality // used to implement the SetHandler method for the default // implementation of Logger. func HotSwapHandler(h log.Handler) *HotSwap { hs := new(HotSwap) hs.Swap(h) return hs } type HotSwap struct { handler unsafe.Pointer } func (h *HotSwap) Log(r *log.Record) error { return (*(*log.Handler)(atomic.LoadPointer(&h.handler))).Log(r) } func (h *HotSwap) Swap(newHandler log.Handler) { atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler)) } // FatalHandler makes critical errors exit the program // immediately, much like the log.Fatal* methods from the // standard log package func FatalHandler(h log.Handler) log.Handler { return log.FuncHandler(func(r *log.Record) error { err := h.Log(r) if r.Lvl == log.LvlCrit { os.Exit(1) } return err }) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/ext/ext_test.go�������������������������������0000644�0610621�0607500�00000004333�13172163415�026356� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ext import ( "errors" log "github.com/inconshreveable/log15" "math" "testing" ) func testHandler() (log.Handler, *log.Record) { rec := new(log.Record) return log.FuncHandler(func(r *log.Record) error { *rec = *r return nil }), rec } func TestHotSwapHandler(t *testing.T) { t.Parallel() h1, r1 := testHandler() l := log.New() h := HotSwapHandler(h1) l.SetHandler(h) l.Info("to h1") if r1.Msg != "to h1" { t.Fatalf("didn't get expected message to h1") } h2, r2 := testHandler() h.Swap(h2) l.Info("to h2") if r2.Msg != "to h2" { t.Fatalf("didn't get expected message to h2") } } func TestSpeculativeHandler(t *testing.T) { t.Parallel() // test with an even multiple of the buffer size, less than full buffer size // and not a multiple of the buffer size for _, count := range []int{10000, 50, 432} { recs := make(chan *log.Record) done := make(chan int) spec := SpeculativeHandler(100, log.ChannelHandler(recs)) go func() { defer close(done) expectedCount := int(math.Min(float64(count), float64(100))) expectedIdx := count - expectedCount for r := range recs { if r.Ctx[1] != expectedIdx { t.Errorf("Bad ctx 'i', got %d expected %d", r.Ctx[1], expectedIdx) return } expectedIdx++ expectedCount-- if expectedCount == 0 { // got everything we expected break } } select { case <-recs: t.Errorf("got an extra record we shouldn't have!") default: } }() lg := log.New() lg.SetHandler(spec) for i := 0; i < count; i++ { lg.Debug("test speculative", "i", i) } go spec.Flush() // wait for the go routine to finish <-done } } func TestErrorHandler(t *testing.T) { t.Parallel() h, r := testHandler() lg := log.New() lg.SetHandler(EscalateErrHandler( log.LvlFilterHandler(log.LvlError, h))) lg.Debug("some function result", "err", nil) if r.Msg != "" { t.Fatalf("Expected debug level message to be filtered") } lg.Debug("some function result", "err", errors.New("failed operation")) if r.Msg != "some function result" { t.Fatalf("Expected debug level message to be escalated and pass lvlfilter") } if r.Lvl != log.LvlError { t.Fatalf("Expected debug level message to be escalated to LvlError") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/doc.go����������������������������������������0000644�0610621�0607500�00000027735�13172163415�024477� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Package log15 provides an opinionated, simple toolkit for best-practice logging that is both human and machine readable. It is modeled after the standard library's io and net/http packages. This package enforces you to only log key/value pairs. Keys must be strings. Values may be any type that you like. The default output format is logfmt, but you may also choose to use JSON instead if that suits you. Here's how you log: log.Info("page accessed", "path", r.URL.Path, "user_id", user.id) This will output a line that looks like: lvl=info t=2014-05-02T16:07:23-0700 msg="page accessed" path=/org/71/profile user_id=9 Getting Started To get started, you'll want to import the library: import log "github.com/inconshreveable/log15" Now you're ready to start logging: func main() { log.Info("Program starting", "args", os.Args()) } Convention Because recording a human-meaningful message is common and good practice, the first argument to every logging method is the value to the *implicit* key 'msg'. Additionally, the level you choose for a message will be automatically added with the key 'lvl', and so will the current timestamp with key 't'. You may supply any additional context as a set of key/value pairs to the logging function. log15 allows you to favor terseness, ordering, and speed over safety. This is a reasonable tradeoff for logging functions. You don't need to explicitly state keys/values, log15 understands that they alternate in the variadic argument list: log.Warn("size out of bounds", "low", lowBound, "high", highBound, "val", val) If you really do favor your type-safety, you may choose to pass a log.Ctx instead: log.Warn("size out of bounds", log.Ctx{"low": lowBound, "high": highBound, "val": val}) Context loggers Frequently, you want to add context to a logger so that you can track actions associated with it. An http request is a good example. You can easily create new loggers that have context that is automatically included with each log line: requestlogger := log.New("path", r.URL.Path) // later requestlogger.Debug("db txn commit", "duration", txnTimer.Finish()) This will output a log line that includes the path context that is attached to the logger: lvl=dbug t=2014-05-02T16:07:23-0700 path=/repo/12/add_hook msg="db txn commit" duration=0.12 Handlers The Handler interface defines where log lines are printed to and how they are formated. Handler is a single interface that is inspired by net/http's handler interface: type Handler interface { Log(r *Record) error } Handlers can filter records, format them, or dispatch to multiple other Handlers. This package implements a number of Handlers for common logging patterns that are easily composed to create flexible, custom logging structures. Here's an example handler that prints logfmt output to Stdout: handler := log.StreamHandler(os.Stdout, log.LogfmtFormat()) Here's an example handler that defers to two other handlers. One handler only prints records from the rpc package in logfmt to standard out. The other prints records at Error level or above in JSON formatted output to the file /var/log/service.json handler := log.MultiHandler( log.LvlFilterHandler(log.LvlError, log.Must.FileHandler("/var/log/service.json", log.JsonFormat())), log.MatchFilterHandler("pkg", "app/rpc" log.StdoutHandler()) ) Logging File Names and Line Numbers This package implements three Handlers that add debugging information to the context, CallerFileHandler, CallerFuncHandler and CallerStackHandler. Here's an example that adds the source file and line number of each logging call to the context. h := log.CallerFileHandler(log.StdoutHandler) log.Root().SetHandler(h) ... log.Error("open file", "err", err) This will output a line that looks like: lvl=eror t=2014-05-02T16:07:23-0700 msg="open file" err="file not found" caller=data.go:42 Here's an example that logs the call stack rather than just the call site. h := log.CallerStackHandler("%+v", log.StdoutHandler) log.Root().SetHandler(h) ... log.Error("open file", "err", err) This will output a line that looks like: lvl=eror t=2014-05-02T16:07:23-0700 msg="open file" err="file not found" stack="[pkg/data.go:42 pkg/cmd/main.go]" The "%+v" format instructs the handler to include the path of the source file relative to the compile time GOPATH. The github.com/go-stack/stack package documents the full list of formatting verbs and modifiers available. Custom Handlers The Handler interface is so simple that it's also trivial to write your own. Let's create an example handler which tries to write to one handler, but if that fails it falls back to writing to another handler and includes the error that it encountered when trying to write to the primary. This might be useful when trying to log over a network socket, but if that fails you want to log those records to a file on disk. type BackupHandler struct { Primary Handler Secondary Handler } func (h *BackupHandler) Log (r *Record) error { err := h.Primary.Log(r) if err != nil { r.Ctx = append(ctx, "primary_err", err) return h.Secondary.Log(r) } return nil } This pattern is so useful that a generic version that handles an arbitrary number of Handlers is included as part of this library called FailoverHandler. Logging Expensive Operations Sometimes, you want to log values that are extremely expensive to compute, but you don't want to pay the price of computing them if you haven't turned up your logging level to a high level of detail. This package provides a simple type to annotate a logging operation that you want to be evaluated lazily, just when it is about to be logged, so that it would not be evaluated if an upstream Handler filters it out. Just wrap any function which takes no arguments with the log.Lazy type. For example: func factorRSAKey() (factors []int) { // return the factors of a very large number } log.Debug("factors", log.Lazy{factorRSAKey}) If this message is not logged for any reason (like logging at the Error level), then factorRSAKey is never evaluated. Dynamic context values The same log.Lazy mechanism can be used to attach context to a logger which you want to be evaluated when the message is logged, but not when the logger is created. For example, let's imagine a game where you have Player objects: type Player struct { name string alive bool log.Logger } You always want to log a player's name and whether they're alive or dead, so when you create the player object, you might do: p := &Player{name: name, alive: true} p.Logger = log.New("name", p.name, "alive", p.alive) Only now, even after a player has died, the logger will still report they are alive because the logging context is evaluated when the logger was created. By using the Lazy wrapper, we can defer the evaluation of whether the player is alive or not to each log message, so that the log records will reflect the player's current state no matter when the log message is written: p := &Player{name: name, alive: true} isAlive := func() bool { return p.alive } player.Logger = log.New("name", p.name, "alive", log.Lazy{isAlive}) Terminal Format If log15 detects that stdout is a terminal, it will configure the default handler for it (which is log.StdoutHandler) to use TerminalFormat. This format logs records nicely for your terminal, including color-coded output based on log level. Error Handling Becasuse log15 allows you to step around the type system, there are a few ways you can specify invalid arguments to the logging functions. You could, for example, wrap something that is not a zero-argument function with log.Lazy or pass a context key that is not a string. Since logging libraries are typically the mechanism by which errors are reported, it would be onerous for the logging functions to return errors. Instead, log15 handles errors by making these guarantees to you: - Any log record containing an error will still be printed with the error explained to you as part of the log record. - Any log record containing an error will include the context key LOG15_ERROR, enabling you to easily (and if you like, automatically) detect if any of your logging calls are passing bad values. Understanding this, you might wonder why the Handler interface can return an error value in its Log method. Handlers are encouraged to return errors only if they fail to write their log records out to an external source like if the syslog daemon is not responding. This allows the construction of useful handlers which cope with those failures like the FailoverHandler. Library Use log15 is intended to be useful for library authors as a way to provide configurable logging to users of their library. Best practice for use in a library is to always disable all output for your logger by default and to provide a public Logger instance that consumers of your library can configure. Like so: package yourlib import "github.com/inconshreveable/log15" var Log = log.New() func init() { Log.SetHandler(log.DiscardHandler()) } Users of your library may then enable it if they like: import "github.com/inconshreveable/log15" import "example.com/yourlib" func main() { handler := // custom handler setup yourlib.Log.SetHandler(handler) } Best practices attaching logger context The ability to attach context to a logger is a powerful one. Where should you do it and why? I favor embedding a Logger directly into any persistent object in my application and adding unique, tracing context keys to it. For instance, imagine I am writing a web browser: type Tab struct { url string render *RenderingContext // ... Logger } func NewTab(url string) *Tab { return &Tab { // ... url: url, Logger: log.New("url", url), } } When a new tab is created, I assign a logger to it with the url of the tab as context so it can easily be traced through the logs. Now, whenever we perform any operation with the tab, we'll log with its embedded logger and it will include the tab title automatically: tab.Debug("moved position", "idx", tab.idx) There's only one problem. What if the tab url changes? We could use log.Lazy to make sure the current url is always written, but that would mean that we couldn't trace a tab's full lifetime through our logs after the user navigate to a new URL. Instead, think about what values to attach to your loggers the same way you think about what to use as a key in a SQL database schema. If it's possible to use a natural key that is unique for the lifetime of the object, do so. But otherwise, log15's ext package has a handy RandId function to let you generate what you might call "surrogate keys" They're just random hex identifiers to use for tracing. Back to our Tab example, we would prefer to set up our Logger like so: import logext "github.com/inconshreveable/log15/ext" t := &Tab { // ... url: url, } t.Logger = log.New("id", logext.RandId(8), "url", log.Lazy{t.getUrl}) return t Now we'll have a unique traceable identifier even across loading new urls, but we'll still be able to see the tab's current url in the log messages. Must For all Handler functions which can return an error, there is a version of that function which will return no error but panics on failure. They are all available on the Must object. For example: log.Must.FileHandler("/path", log.JsonFormat) log.Must.NetHandler("tcp", ":1234", log.JsonFormat) Inspiration and Credit All of the following excellent projects inspired the design of this library: code.google.com/p/log4go github.com/op/go-logging github.com/technoweenie/grohl github.com/Sirupsen/logrus github.com/kr/logfmt github.com/spacemonkeygo/spacelog golang's stdlib, notably io and net/http The Name https://xkcd.com/927/ */ package log15 �����������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/bench_test.go���������������������������������0000644�0610621�0607500�00000007377�13172163415�026050� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.3 package log15 import ( "bytes" "errors" "io/ioutil" "testing" "time" ) func BenchmarkStreamNoCtx(b *testing.B) { lg := New() buf := bytes.Buffer{} lg.SetHandler(StreamHandler(&buf, LogfmtFormat())) for i := 0; i < b.N; i++ { lg.Info("test message") buf.Reset() } } func BenchmarkDiscard(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkCallerFileHandler(b *testing.B) { lg := New() lg.SetHandler(CallerFileHandler(DiscardHandler())) for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkCallerFuncHandler(b *testing.B) { lg := New() lg.SetHandler(CallerFuncHandler(DiscardHandler())) for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkLogfmtNoCtx(b *testing.B) { r := Record{ Time: time.Now(), Lvl: LvlInfo, Msg: "test message", Ctx: []interface{}{}, } logfmt := LogfmtFormat() for i := 0; i < b.N; i++ { logfmt.Format(&r) } } func BenchmarkJsonNoCtx(b *testing.B) { r := Record{ Time: time.Now(), Lvl: LvlInfo, Msg: "test message", Ctx: []interface{}{}, } jsonfmt := JsonFormat() for i := 0; i < b.N; i++ { jsonfmt.Format(&r) } } func BenchmarkMultiLevelFilter(b *testing.B) { handler := MultiHandler( LvlFilterHandler(LvlDebug, DiscardHandler()), LvlFilterHandler(LvlError, DiscardHandler()), ) lg := New() lg.SetHandler(handler) for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkDescendant1(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) lg = lg.New() for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkDescendant2(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) for i := 0; i < 2; i++ { lg = lg.New() } for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkDescendant4(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) for i := 0; i < 4; i++ { lg = lg.New() } for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkDescendant8(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) for i := 0; i < 8; i++ { lg = lg.New() } for i := 0; i < b.N; i++ { lg.Info("test message") } } // Copied from https://github.com/uber-go/zap/blob/master/benchmarks/log15_bench_test.go // (MIT License) func newLog15() Logger { logger := New() logger.SetHandler(StreamHandler(ioutil.Discard, JsonFormat())) return logger } var errExample = errors.New("fail") type user struct { Name string `json:"name"` Email string `json:"email"` CreatedAt time.Time `json:"created_at"` } var _jane = user{ Name: "Jane Doe", Email: "jane@test.com", CreatedAt: time.Date(1980, 1, 1, 12, 0, 0, 0, time.UTC), } func BenchmarkLog15AddingFields(b *testing.B) { logger := newLog15() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { logger.Info("Go fast.", "int", 1, "int64", int64(1), "float", 3.0, "string", "four!", "bool", true, "time", time.Unix(0, 0), "error", errExample.Error(), "duration", time.Second, "user-defined type", _jane, "another string", "done!", ) } }) } func BenchmarkLog15WithAccumulatedContext(b *testing.B) { logger := newLog15().New( "int", 1, "int64", int64(1), "float", 3.0, "string", "four!", "bool", true, "time", time.Unix(0, 0), "error", errExample.Error(), "duration", time.Second, "user-defined type", _jane, "another string", "done!", ) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { logger.Info("Go really fast.") } }) } func BenchmarkLog15WithoutFields(b *testing.B) { logger := newLog15() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { logger.Info("Go fast.") } }) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/README.md�������������������������������������0000644�0610621�0607500�00000006307�13172163415�024652� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������![obligatory xkcd](http://imgs.xkcd.com/comics/standards.png) # log15 [![godoc reference](https://godoc.org/github.com/inconshreveable/log15?status.png)](https://godoc.org/github.com/inconshreveable/log15) [![Build Status](https://travis-ci.org/inconshreveable/log15.svg?branch=master)](https://travis-ci.org/inconshreveable/log15) Package log15 provides an opinionated, simple toolkit for best-practice logging in Go (golang) that is both human and machine readable. It is modeled after the Go standard library's [`io`](http://golang.org/pkg/io/) and [`net/http`](http://golang.org/pkg/net/http/) packages and is an alternative to the standard library's [`log`](http://golang.org/pkg/log/) package. ## Features - A simple, easy-to-understand API - Promotes structured logging by encouraging use of key/value pairs - Child loggers which inherit and add their own private context - Lazy evaluation of expensive operations - Simple Handler interface allowing for construction of flexible, custom logging configurations with a tiny API. - Color terminal support - Built-in support for logging to files, streams, syslog, and the network - Support for forking records to multiple handlers, buffering records for output, failing over from failed handler writes, + more ## Versioning The API of the master branch of log15 should always be considered unstable. If you want to rely on a stable API, you must vendor the library. ## Importing ```go import log "github.com/inconshreveable/log15" ``` ## Examples ```go // all loggers can have key/value context srvlog := log.New("module", "app/server") // all log messages can have key/value context srvlog.Warn("abnormal conn rate", "rate", curRate, "low", lowRate, "high", highRate) // child loggers with inherited context connlog := srvlog.New("raddr", c.RemoteAddr()) connlog.Info("connection open") // lazy evaluation connlog.Debug("ping remote", "latency", log.Lazy{pingRemote}) // flexible configuration srvlog.SetHandler(log.MultiHandler( log.StreamHandler(os.Stderr, log.LogfmtFormat()), log.LvlFilterHandler( log.LvlError, log.Must.FileHandler("errors.json", log.JsonFormat())))) ``` Will result in output that looks like this: ``` WARN[06-17|21:58:10] abnormal conn rate module=app/server rate=0.500 low=0.100 high=0.800 INFO[06-17|21:58:10] connection open module=app/server raddr=10.0.0.1 ``` ## Breaking API Changes The following commits broke API stability. This reference is intended to help you understand the consequences of updating to a newer version of log15. - 57a084d014d4150152b19e4e531399a7145d1540 - Added a `Get()` method to the `Logger` interface to retrieve the current handler - 93404652ee366648fa622b64d1e2b67d75a3094a - `Record` field `Call` changed to `stack.Call` with switch to `github.com/go-stack/stack` - a5e7613673c73281f58e15a87d2cf0cf111e8152 - Restored `syslog.Priority` argument to the `SyslogXxx` handler constructors ## FAQ ### The varargs style is brittle and error prone! Can I have type safety please? Yes. Use `log.Ctx`: ```go srvlog := log.New(log.Ctx{"module": "app/server"}) srvlog.Warn("abnormal conn rate", log.Ctx{"rate": curRate, "low": lowRate, "high": highRate}) ``` ## License Apache �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/LICENSE���������������������������������������0000644�0610621�0607500�00000001047�13172163415�024374� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright 2014 Alan Shreve Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/CONTRIBUTORS����������������������������������0000644�0610621�0607500�00000000255�13172163415�025247� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Contributors to log15: - Aaron L - Alan Shreve - Chris Hines - Ciaran Downey - Dmitry Chestnykh - Evan Shaw - Péter Szilágyi - Trevor Gattis - Vincent Vanackere ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/inconshreveable/log15.v2/.travis.yml�����������������������������������0000644�0610621�0607500�00000000217�13172163415�025476� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go_import_path: github.com/inconshreveable/log15 sudo: false go: - 1.3 - 1.4 - 1.5 - 1.6 - 1.7 - 1.8 - 1.9 - tip ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/��������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163413�020431� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/strategy.go���������������������������������������������������0000644�0610621�0607500�00000002522�13172163413�022623� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package retry // import "gopkg.in/retry.v1" import ( "time" ) type strategyFunc func(now time.Time) Timer // NewTimer implements Strategy.NewTimer. func (f strategyFunc) NewTimer(now time.Time) Timer { return f(now) } // LimitCount limits the number of attempts that the given // strategy will perform to n. Note that all strategies // will allow at least one attempt. func LimitCount(n int, strategy Strategy) Strategy { return strategyFunc(func(now time.Time) Timer { return &countLimitTimer{ timer: strategy.NewTimer(now), remain: n, } }) } type countLimitTimer struct { timer Timer remain int } func (t *countLimitTimer) NextSleep(now time.Time) (time.Duration, bool) { if t.remain--; t.remain <= 0 { return 0, false } return t.timer.NextSleep(now) } // LimitTime limits the given strategy such that no attempt will // made after the given duration has elapsed. func LimitTime(limit time.Duration, strategy Strategy) Strategy { return strategyFunc(func(now time.Time) Timer { return &timeLimitTimer{ timer: strategy.NewTimer(now), end: now.Add(limit), } }) } type timeLimitTimer struct { timer Timer end time.Time } func (t *timeLimitTimer) NextSleep(now time.Time) (time.Duration, bool) { sleep, ok := t.timer.NextSleep(now) if ok && now.Add(sleep).After(t.end) { return 0, false } return sleep, ok } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/retry_test.go�������������������������������������������������0000644�0610621�0607500�00000020011�13172163413�023156� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011, 2012, 2013 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package retry_test // import "gopkg.in/retry.v1" import ( "time" "github.com/juju/testing" gc "gopkg.in/check.v1" "github.com/juju/utils/clock" "gopkg.in/retry.v1" ) type retrySuite struct{} var _ = gc.Suite(&retrySuite{}) func (*retrySuite) TestAttemptTiming(c *gc.C) { testAttempt := retry.Regular{ Total: 0.25e9, Delay: 0.1e9, } want := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9} got := make([]time.Duration, 0, len(want)) // avoid allocation when testing timing t0 := time.Now() a := testAttempt.Start(nil) for a.Next() { got = append(got, time.Now().Sub(t0)) } got = append(got, time.Now().Sub(t0)) c.Assert(a.Stopped(), gc.Equals, false) c.Assert(got, gc.HasLen, len(want)) const margin = 0.01e9 for i, got := range want { lo := want[i] - margin hi := want[i] + margin if got < lo || got > hi { c.Errorf("attempt %d want %g got %g", i, want[i].Seconds(), got.Seconds()) } } } func (*retrySuite) TestAttemptNextMore(c *gc.C) { a := retry.Regular{}.Start(nil) c.Assert(a.Next(), gc.Equals, true) c.Assert(a.Next(), gc.Equals, false) a = retry.Regular{}.Start(nil) c.Assert(a.Next(), gc.Equals, true) c.Assert(a.More(), gc.Equals, false) c.Assert(a.Next(), gc.Equals, false) a = retry.Regular{Total: 2e8}.Start(nil) c.Assert(a.Next(), gc.Equals, true) c.Assert(a.More(), gc.Equals, true) time.Sleep(2e8) c.Assert(a.More(), gc.Equals, true) c.Assert(a.Next(), gc.Equals, true) c.Assert(a.Next(), gc.Equals, false) a = retry.Regular{Total: 1e8, Min: 2}.Start(nil) time.Sleep(1e8) c.Assert(a.Next(), gc.Equals, true) c.Assert(a.More(), gc.Equals, true) c.Assert(a.Next(), gc.Equals, true) c.Assert(a.More(), gc.Equals, false) c.Assert(a.Next(), gc.Equals, false) } func (*retrySuite) TestAttemptWithStop(c *gc.C) { stop := make(chan struct{}) close(stop) done := make(chan struct{}) go func() { strategy := retry.Regular{ Delay: 5 * time.Second, Total: 30 * time.Second, } a := retry.StartWithCancel(strategy, nil, stop) for a.Next() { c.Errorf("unexpected attempt") } c.Check(a.Stopped(), gc.Equals, true) close(done) }() assertReceive(c, done, "attempt loop abort") } func (*retrySuite) TestAttemptWithLaterStop(c *gc.C) { clock := testing.NewClock(time.Now()) stop := make(chan struct{}) done := make(chan struct{}) progress := make(chan struct{}, 10) go func() { strategy := retry.Regular{ Delay: 5 * time.Second, Total: 30 * time.Second, } a := retry.StartWithCancel(strategy, clock, stop) for a.Next() { progress <- struct{}{} } c.Check(a.Stopped(), gc.Equals, true) close(done) }() assertReceive(c, progress, "progress") clock.Advance(5 * time.Second) assertReceive(c, progress, "progress") clock.Advance(2 * time.Second) close(stop) assertReceive(c, done, "attempt loop abort") select { case <-progress: c.Fatalf("unxpected loop iteration after stop") default: } } func (*retrySuite) TestAttemptWithMockClock(c *gc.C) { clock := testing.NewClock(time.Now()) strategy := retry.Regular{ Delay: 5 * time.Second, Total: 30 * time.Second, } progress := make(chan struct{}) done := make(chan struct{}) go func() { for a := strategy.Start(clock); a.Next(); { progress <- struct{}{} } close(done) }() assertReceive(c, progress, "progress first time") clock.Advance(5 * time.Second) assertReceive(c, progress, "progress second time") clock.Advance(5 * time.Second) assertReceive(c, progress, "progress third time") clock.Advance(30 * time.Second) assertReceive(c, progress, "progress fourth time") assertReceive(c, done, "loop finish") } type strategyTest struct { about string strategy retry.Strategy calls []nextCall terminates bool } type nextCall struct { // t holds the time since the timer was started that // the Next call will be made. t time.Duration // delay holds the length of time that a call made at // time t is expected to sleep for. sleep time.Duration } var strategyTests = []strategyTest{{ about: "regular retry (same params as TestAttemptTiming)", strategy: retry.Regular{ Total: 0.25e9, Delay: 0.1e9, }, calls: []nextCall{ {0, 0}, {0, 0.1e9}, {0.1e9, 0.1e9}, {0.2e9, 0}, }, terminates: true, }, { about: "regular retry with calls at different times", strategy: retry.Regular{ Total: 2.5e9, Delay: 1e9, }, calls: []nextCall{ {0.5e9, 0}, {0.5e9, 0.5e9}, {1.1e9, 0.9e9}, {2.2e9, 0}, }, terminates: true, }, { about: "regular retry with call after next deadline", strategy: retry.Regular{ Total: 3.5e9, Delay: 1e9, }, calls: []nextCall{ {0.5e9, 0}, // We call Next at well beyond the deadline, // so we get a zero delay, but subsequent events // resume pace. {2e9, 0}, {2.1e9, 0.9e9}, {3e9, 0}, }, terminates: true, }, { about: "exponential retry", strategy: retry.Exponential{ Initial: 1e9, Factor: 2, }, calls: []nextCall{ {0, 0}, {0.1e9, 0.9e9}, {1e9, 2e9}, {3e9, 4e9}, {7e9, 8e9}, }, }, { about: "time-limited exponential retry", strategy: retry.LimitTime(5e9, retry.Exponential{ Initial: 1e9, Factor: 2, }), calls: []nextCall{ {0, 0}, {0.1e9, 0.9e9}, {1e9, 2e9}, {3e9, 0}, }, terminates: true, }, { about: "count-limited exponential retry", strategy: retry.LimitCount(2, retry.Exponential{ Initial: 1e9, Factor: 2, }), calls: []nextCall{ {0, 0}, {0.1e9, 0.9e9}, {1e9, 0}, }, terminates: true, }} func (*retrySuite) TestStrategies(c *gc.C) { for i, test := range strategyTests { c.Logf("test %d: %s", i, test.about) testStrategy(c, test) } } func testStrategy(c *gc.C, test strategyTest) { t0 := time.Now() clk := &mockClock{ now: t0, } a := retry.Start(test.strategy, clk) for i, call := range test.calls { c.Logf("call %d - %v", i, call.t) clk.now = t0.Add(call.t) ok := a.Next() expectTerminate := test.terminates && i == len(test.calls)-1 c.Assert(ok, gc.Equals, !expectTerminate) if got, want := clk.now.Sub(t0), call.t+call.sleep; !closeTo(got, want) { c.Fatalf("incorrect time after Next; got %v want %v", got, want) } if ok { c.Assert(a.Count(), gc.Equals, i+1) } } } func (*retrySuite) TestGapBetweenMoreAndNext(c *gc.C) { t0 := time.Now().UTC() clk := &mockClock{ now: t0, } a := (&retry.Regular{ Min: 3, Delay: time.Second, }).Start(clk) c.Assert(a.Next(), gc.Equals, true) c.Assert(clk.now, gc.Equals, t0) clk.now = clk.now.Add(500 * time.Millisecond) // Sanity check that the first iteration sleeps for half a second. c.Assert(a.More(), gc.Equals, true) c.Assert(a.Next(), gc.Equals, true) c.Assert(clk.now.Sub(t0), gc.Equals, t0.Add(time.Second).Sub(t0)) clk.now = clk.now.Add(500 * time.Millisecond) c.Assert(a.More(), gc.Equals, true) // Add a delay between calling More and Next. // Next should wait until the correct time anyway. clk.now = clk.now.Add(250 * time.Millisecond) c.Assert(a.More(), gc.Equals, true) c.Assert(a.Next(), gc.Equals, true) c.Assert(clk.now.Sub(t0), gc.Equals, t0.Add(2*time.Second).Sub(t0)) } func (*retrySuite) TestOnlyOneHitOnZeroTotal(c *gc.C) { t0 := time.Now().UTC() clk := &mockClock{ now: t0, } a := (&retry.Regular{ Total: 0, Delay: 0, Min: 0, }).Start(clk) // Even if the clock didn't advanced we want to have only one hit c.Check(a.Next(), gc.Equals, true) c.Check(a.More(), gc.Equals, false) } // closeTo reports whether d0 and d1 are close enough // to one another to cater for inaccuracies of floating point arithmetic. func closeTo(d0, d1 time.Duration) bool { const margin = 20 * time.Nanosecond diff := d1 - d0 if diff < 0 { diff = -diff } return diff < margin } type mockClock struct { clock.Clock now time.Time sleep func(d time.Duration) } func (c *mockClock) After(d time.Duration) <-chan time.Time { c.now = c.now.Add(d) ch := make(chan time.Time) close(ch) return ch } func (c *mockClock) Now() time.Time { return c.now } func assertReceive(c *gc.C, ch <-chan struct{}, what string) { select { case <-ch: case <-time.After(time.Second): c.Fatalf("timed out waiting for %s", what) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/retry.go������������������������������������������������������0000644�0610621�0607500�00000010555�13172163413�022133� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. // Package retry provides a framework for retrying actions. // It does not itself invoke the action to be retried, but // is intended to be used in a retry loop. // // The basic usage is as follows: // // for a := someStrategy.Start(); a.Next(); { // try() // } // // See examples for details of suggested usage. package retry // import "gopkg.in/retry.v1" import ( "time" ) // Strategy is implemented by types that represent a retry strategy. // // Note: You probably won't need to implement a new strategy - the existing types // and functions are intended to be sufficient for most purposes. type Strategy interface { // NewTimer is called when the strategy is started - it is // called with the time that the strategy is started and returns // an object that is used to find out how long to sleep before // each retry attempt. NewTimer(now time.Time) Timer } // Timer represents a source of timing events for a retry strategy. type Timer interface { // NextSleep is called with the time that Next or More has been // called and returns the length of time to sleep before the // next retry. If no more attempts should be made it should // return false, and the returned duration will be ignored. // // Note that NextSleep is called once after each iteration has // completed, assuming the retry loop is continuing. NextSleep(now time.Time) (time.Duration, bool) } // Attempt represents a running retry attempt. type Attempt struct { clock Clock stop <-chan struct{} timer Timer // next holds when the next attempt should start. // It is valid only when known is true. next time.Time // count holds the iteration count. count int // known holds whether next and running are known. known bool // running holds whether the attempt is still going. running bool // stopped holds whether the attempt has been stopped. stopped bool } // Start begins a new sequence of attempts for the given strategy using // the given Clock implementation for time keeping. If clk is // nil, the time package will be used to keep time. func Start(strategy Strategy, clk Clock) *Attempt { return StartWithCancel(strategy, clk, nil) } // StartWithCancel is like Start except that if a value // is received on stop while waiting, the attempt will be aborted. func StartWithCancel(strategy Strategy, clk Clock, stop <-chan struct{}) *Attempt { if clk == nil { clk = wallClock{} } now := clk.Now() return &Attempt{ clock: clk, stop: stop, timer: strategy.NewTimer(now), known: true, running: true, next: now, } } // Next reports whether another attempt should be made, waiting as // necessary until it's time for the attempt. It always returns true the // first time it is called unless a value is received on the stop // channel - we are guaranteed to make at least one attempt unless // stopped. func (a *Attempt) Next() bool { if !a.More() { return false } sleep := a.next.Sub(a.clock.Now()) if sleep <= 0 { // We're not going to sleep for any length of time, // so guarantee that we respect the stop channel. This // ensures that we make no attempts if Next is called // with a value available on the stop channel. select { case <-a.stop: a.stopped = true a.running = false return false default: a.known = false a.count++ return true } } select { case <-a.clock.After(sleep): a.known = false a.count++ case <-a.stop: a.running = false a.stopped = true } return a.running } // More reports whether there are more retry attempts to be made. It // does not sleep. // // If More returns false, Next will return false. If More returns true, // Next will return true except when the attempt has been explicitly // stopped via the stop channel. func (a *Attempt) More() bool { if !a.known { now := a.clock.Now() sleepDuration, running := a.timer.NextSleep(now) a.next, a.running, a.known = now.Add(sleepDuration), running, true } return a.running } // Stopped reports whether the attempt has terminated because // a value was received on the stop channel. func (a *Attempt) Stopped() bool { return a.stopped } // Count returns the current attempt count number, starting at 1. // It returns 0 if called before Next is called. // When the loop has terminated, it holds the total number // of retries made. func (a *Attempt) Count() int { return a.count } ���������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/regular.go����������������������������������������������������0000644�0610621�0607500�00000003073�13172163413�022424� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package retry // import "gopkg.in/retry.v1" import ( "time" ) // Regular represents a strategy that repeats at regular intervals. type Regular struct { // Total specifies the total duration of the attempt. Total time.Duration // Delay specifies the interval between the start of each try // in the burst. If an try takes longer than Delay, the // next try will happen immediately. Delay time.Duration // Min holds the minimum number of retries. It overrides Total. // To limit the maximum number of retries, use LimitCount. Min int } // regularTimer holds a running instantiation of the Regular timer. type regularTimer struct { strategy Regular count int // start holds when the current try started. start time.Time end time.Time } // Start is short for Start(r, clk, nil) func (r Regular) Start(clk Clock) *Attempt { return Start(r, clk) } // NewTimer implements Strategy.NewTimer. func (r Regular) NewTimer(now time.Time) Timer { return &regularTimer{ strategy: r, start: now, end: now.Add(r.Total), } } // NextSleep implements Timer.NextSleep. func (a *regularTimer) NextSleep(now time.Time) (time.Duration, bool) { sleep := a.strategy.Delay - now.Sub(a.start) if sleep <= 0 { sleep = 0 } a.count++ // Set the start of the next try. a.start = now.Add(sleep) if a.count < a.strategy.Min { return sleep, true } // The next try is not before the end - no more attempts. if !a.start.Before(a.end) { return 0, false } return sleep, true } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/package_test.go�����������������������������������������������0000644�0610621�0607500�00000000363�13172163413�023414� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package retry_test // import "gopkg.in/retry.v1" import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/exp.go��������������������������������������������������������0000644�0610621�0607500�00000002434�13172163413�021557� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package retry // import "gopkg.in/retry.v1" import ( "time" ) // Exponential represents an exponential backoff retry strategy. // To limit the number of attempts or their overall duration, wrap // this in LimitCount or LimitDuration. type Exponential struct { // Initial holds the initial delay. Initial time.Duration // Factor holds the factor that the delay time will be multiplied // by on each iteration. Factor float64 // MaxDelay holds the maximum delay between the start // of attempts. If this is zero, there is no maximum delay. MaxDelay time.Duration } type exponentialTimer struct { strategy Exponential start time.Time end time.Time delay time.Duration } // NewTimer implements Strategy.NewTimer. func (r Exponential) NewTimer(now time.Time) Timer { return &exponentialTimer{ strategy: r, start: now, delay: r.Initial, } } // NextSleep implements Timer.NextSleep. func (a *exponentialTimer) NextSleep(now time.Time) (time.Duration, bool) { sleep := a.delay - now.Sub(a.start) if sleep <= 0 { sleep = 0 } // Set the start of the next try. a.start = now.Add(sleep) a.delay = time.Duration(float64(a.delay) * a.strategy.Factor) if a.strategy.MaxDelay > 0 && a.delay > a.strategy.MaxDelay { a.delay = a.strategy.MaxDelay } return sleep, true } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/example_test.go�����������������������������������������������0000644�0610621�0607500�00000002365�13172163413�023460� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package retry_test // import "gopkg.in/retry.v1" import ( "net/http" "time" "gopkg.in/retry.v1" ) func doSomething() (int, error) { return 0, nil } func shouldRetry(error) bool { return false } func doSomethingWith(int) {} func ExampleAttempt_More() { // This example shows how Attempt.More can be used to help // structure an attempt loop. If the godoc example code allowed // us to make the example return an error, we would uncomment // the commented return statements. attempts := retry.Regular{ Total: 1 * time.Second, Delay: 250 * time.Millisecond, } for attempt := attempts.Start(nil); attempt.Next(); { x, err := doSomething() if shouldRetry(err) && attempt.More() { continue } if err != nil { // return err return } doSomethingWith(x) } // return ErrTimedOut return } func ExampleExponential() { // This example shows a retry loop that will retry an // HTTP POST request with an exponential backoff // for up to 30s. strategy := retry.LimitTime(30*time.Second, retry.Exponential{ Initial: 10 * time.Millisecond, Factor: 1.5, }, ) for a := retry.Start(strategy, nil); a.Next(); { if reply, err := http.Post("http://example.com/form", "", nil); err == nil { reply.Body.Close() break } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/clock.go������������������������������������������������������0000644�0610621�0607500�00000001002�13172163413�022044� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package retry // import "gopkg.in/retry.v1" import "time" // Clock represents a virtual clock interface that // can be replaced for testing. type Clock interface { Now() time.Time After(time.Duration) <-chan time.Time } // WallClock exposes wall-clock time as returned by time.Now. type wallClock struct{} // Now implements Clock.Now. func (wallClock) Now() time.Time { return time.Now() } // After implements Clock.After. func (wallClock) After(d time.Duration) <-chan time.Time { return time.After(d) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/retry.v1/README.md�����������������������������������������������������0000644�0610621�0607500�00000011775�13172163413�021723� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# retry -- import "gopkg.in/retry.v1" Package retry provides a framework for retrying actions. It does not itself invoke the action to be retried, but is intended to be used in a retry loop. The basic usage is as follows: for a := someStrategy.Start(); a.Next(); { try() } See examples for details of suggested usage. ## Usage #### type Attempt ```go type Attempt struct { } ``` Attempt represents a running retry attempt. #### func Start ```go func Start(strategy Strategy, clk Clock) *Attempt ``` Start begins a new sequence of attempts for the given strategy using the given Clock implementation for time keeping. If clk is nil, the time package will be used to keep time. #### func StartWithCancel ```go func StartWithCancel(strategy Strategy, clk Clock, stop <-chan struct{}) *Attempt ``` StartWithCancel is like Start except that if a value is received on stop while waiting, the attempt will be aborted. #### func (*Attempt) Count ```go func (a *Attempt) Count() int ``` Count returns the current attempt count number, starting at 1. It returns 0 if called before Next is called. When the loop has terminated, it holds the total number of retries made. #### func (*Attempt) More ```go func (a *Attempt) More() bool ``` More reports whether there are more retry attempts to be made. It does not sleep. If More returns false, Next will return false. If More returns true, Next will return true except when the attempt has been explicitly stopped via the stop channel. #### func (*Attempt) Next ```go func (a *Attempt) Next() bool ``` Next reports whether another attempt should be made, waiting as necessary until it's time for the attempt. It always returns true the first time it is called unless a value is received on the stop channel - we are guaranteed to make at least one attempt unless stopped. #### func (*Attempt) Stopped ```go func (a *Attempt) Stopped() bool ``` Stopped reports whether the attempt has terminated because a value was received on the stop channel. #### type Clock ```go type Clock interface { Now() time.Time After(time.Duration) <-chan time.Time } ``` Clock represents a virtual clock interface that can be replaced for testing. #### type Exponential ```go type Exponential struct { // Initial holds the initial delay. Initial time.Duration // Factor holds the factor that the delay time will be multiplied // by on each iteration. Factor float64 // MaxDelay holds the maximum delay between the start // of attempts. If this is zero, there is no maximum delay. MaxDelay time.Duration } ``` Exponential represents an exponential backoff retry strategy. To limit the number of attempts or their overall duration, wrap this in LimitCount or LimitDuration. #### func (Exponential) NewTimer ```go func (r Exponential) NewTimer(now time.Time) Timer ``` NewTimer implements Strategy.NewTimer. #### type Regular ```go type Regular struct { // Total specifies the total duration of the attempt. Total time.Duration // Delay specifies the interval between the start of each try // in the burst. If an try takes longer than Delay, the // next try will happen immediately. Delay time.Duration // Min holds the minimum number of retries. It overrides Total. // To limit the maximum number of retries, use LimitCount. Min int } ``` Regular represents a strategy that repeats at regular intervals. #### func (Regular) NewTimer ```go func (r Regular) NewTimer(now time.Time) Timer ``` NewTimer implements Strategy.NewTimer. #### func (Regular) Start ```go func (r Regular) Start(clk Clock) *Attempt ``` Start is short for Start(r, clk, nil) #### type Strategy ```go type Strategy interface { // NewTimer is called when the strategy is started - it is // called with the time that the strategy is started and returns // an object that is used to find out how long to sleep before // each retry attempt. NewTimer(now time.Time) Timer } ``` Strategy is implemented by types that represent a retry strategy. Note: You probably won't need to implement a new strategy - the existing types and functions are intended to be sufficient for most purposes. #### func LimitCount ```go func LimitCount(n int, strategy Strategy) Strategy ``` LimitCount limits the number of attempts that the given strategy will perform to n. Note that all strategies will allow at least one attempt. #### func LimitTime ```go func LimitTime(limit time.Duration, strategy Strategy) Strategy ``` LimitTime limits the given strategy such that no attempt will made after the given duration has elapsed. #### type Timer ```go type Timer interface { // NextSleep is called with the time that Next or More has been // called and returns the length of time to sleep before the // next retry. If no more attempts should be made it should // return false, and the returned duration will be ignored. // // Note that NextSleep is called once after each iteration has // completed, assuming the retry loop is continuing. NextSleep(now time.Time) (time.Duration, bool) } ``` Timer represents a source of timing events for a retry strategy. ���lxd-2.0.11/dist/src/gopkg.in/retry.v1/LICENSE�������������������������������������������������������0000644�0610621�0607500�00000021122�13172163413�021434� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (C) 2011-2015 Canonical Ltd. This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163405�022700� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/trace.go������������������������������������������0000644�0610621�0607500�00000005163�13172163405�024332� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "fmt" ) // Trace holds all toperations involved in verifying a macaroon, // and the root key used as the initial verification key. // This can be useful for debugging macaroon implementations. type Trace struct { RootKey []byte Ops []TraceOp } // Results returns the output from all operations in the Trace. // The result from ts.Ops[i] will be in the i'th element of the // returned slice. // When a trace has resulted in a failure, the // last element will be nil. func (t Trace) Results() [][]byte { r := make([][]byte, len(t.Ops)) input := t.RootKey for i, op := range t.Ops { input = op.Result(input) r[i] = input } return r } // TraceOp holds one possible operation when verifying a macaroon. type TraceOp struct { Kind TraceOpKind `json:"kind"` Data1 []byte `json:"data1,omitempty"` Data2 []byte `json:"data2,omitempty"` } // Result returns the result of computing the given // operation with the given input data. // If op is TraceFail, it returns nil. func (op TraceOp) Result(input []byte) []byte { switch op.Kind { case TraceMakeKey: return makeKey(input)[:] case TraceHash: if len(op.Data2) == 0 { return keyedHash(bytesToKey(input), op.Data1)[:] } return keyedHash2(bytesToKey(input), op.Data1, op.Data2)[:] case TraceBind: return bindForRequest(op.Data1, bytesToKey(input))[:] case TraceFail: return nil default: panic(fmt.Errorf("unknown trace operation kind %d", op.Kind)) } } func bytesToKey(data []byte) *[keyLen]byte { var key [keyLen]byte if len(data) != keyLen { panic(fmt.Errorf("unexpected input key length; got %d want %d", len(data), keyLen)) } copy(key[:], data) return &key } // TraceOpKind represents the kind of a macaroon verification operation. type TraceOpKind int const ( TraceInvalid = TraceOpKind(iota) // TraceMakeKey represents the operation of calculating a // fixed length root key from the variable length input key. TraceMakeKey // TraceHash represents a keyed hash operation with one // or two values. If there is only one value, it will be in Data1. TraceHash // TraceBind represents the operation of binding a discharge macaroon // to its primary macaroon. Data1 holds the signature of the primary // macaroon. TraceBind // TraceFail represents a verification failure. If present, this will always // be the last operation in a trace. TraceFail ) var traceOps = []string{ TraceInvalid: "invalid", TraceMakeKey: "makekey", TraceHash: "hash", TraceBind: "bind", TraceFail: "fail", } // String returns a string representation of the operation. func (k TraceOpKind) String() string { return traceOps[k] } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/packet-v2_test.go���������������������������������0000644�0610621�0607500�00000005753�13172163405�026074� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" ) type packetV2Suite struct{} var _ = gc.Suite(&packetV2Suite{}) var parsePacketV2Tests = []struct { about string data string expectPacket packetV2 expectData string expectError string }{{ about: "EOS packet", data: "\x00", expectPacket: packetV2{ fieldType: fieldEOS, }, }, { about: "simple field", data: "\x02\x03xyz", expectPacket: packetV2{ fieldType: 2, data: []byte("xyz"), }, }, { about: "empty buffer", data: "", expectError: "varint value extends past end of buffer", }, { about: "varint out of range", data: "\xff\xff\xff\xff\xff\xff\x7f", expectError: "varint value out of range", }, { about: "varint way out of range", data: "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x7f", expectError: "varint value out of range", }, { about: "unterminated varint", data: "\x80", expectError: "varint value extends past end of buffer", }, { about: "field data too long", data: "\x01\x02a", expectError: "field data extends past end of buffer", }, { about: "bad data length varint", data: "\x01\xff", expectError: "varint value extends past end of buffer", }} func (*packetV2Suite) TestParsePacketV2(c *gc.C) { for i, test := range parsePacketV2Tests { c.Logf("test %d: %v", i, test.about) data, p, err := parsePacketV2([]byte(test.data)) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) c.Assert(data, gc.IsNil) c.Assert(p, gc.DeepEquals, packetV2{}) } else { c.Assert(err, gc.IsNil) c.Assert(p, jc.DeepEquals, test.expectPacket) } } } var parseSectionV2Tests = []struct { about string data string expectData string expectPackets []packetV2 expectError string }{{ about: "no packets", data: "\x00", }, { about: "one packet", data: "\x02\x03xyz\x00", expectPackets: []packetV2{{ fieldType: 2, data: []byte("xyz"), }}, }, { about: "two packets", data: "\x02\x03xyz\x07\x05abcde\x00", expectPackets: []packetV2{{ fieldType: 2, data: []byte("xyz"), }, { fieldType: 7, data: []byte("abcde"), }}, }, { about: "unterminated section", data: "\x02\x03xyz\x07\x05abcde", expectError: "section extends past end of buffer", }, { about: "out of order fields", data: "\x07\x05abcde\x02\x03xyz\x00", expectError: "fields out of order", }, { about: "bad packet", data: "\x07\x05abcde\xff", expectError: "varint value extends past end of buffer", }} func (*packetV2Suite) TestParseSectionV2(c *gc.C) { for i, test := range parseSectionV2Tests { c.Logf("test %d: %v", i, test.about) data, ps, err := parseSectionV2([]byte(test.data)) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) c.Assert(data, gc.IsNil) c.Assert(ps, gc.IsNil) } else { c.Assert(err, gc.IsNil) c.Assert(ps, jc.DeepEquals, test.expectPackets) } } } ���������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/packet-v2.go��������������������������������������0000644�0610621�0607500�00000005462�13172163405�025032� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "encoding/binary" "fmt" ) type fieldType int // Field constants as used in the binary encoding. const ( fieldEOS fieldType = 0 fieldLocation fieldType = 1 fieldIdentifier fieldType = 2 fieldVerificationId fieldType = 4 fieldSignature fieldType = 6 ) type packetV2 struct { // fieldType holds the type of the field. fieldType fieldType // data holds the packet's data. data []byte } // parseSectionV2 parses a sequence of packets // in data. The sequence is terminated by a packet // with a field type of fieldEOS. func parseSectionV2(data []byte) ([]byte, []packetV2, error) { prevFieldType := fieldType(-1) var packets []packetV2 for { if len(data) == 0 { return nil, nil, fmt.Errorf("section extends past end of buffer") } rest, p, err := parsePacketV2(data) if err != nil { return nil, nil, err } if p.fieldType == fieldEOS { return rest, packets, nil } if p.fieldType <= prevFieldType { return nil, nil, fmt.Errorf("fields out of order") } packets = append(packets, p) prevFieldType = p.fieldType data = rest } } // parsePacketV2 parses a V2 data package at the start // of the given data. // The format of a packet is as follows: // // fieldType(varint) payloadLen(varint) data[payloadLen bytes] // // apart from fieldEOS which has no payloadLen or data (it's // a single zero byte). func parsePacketV2(data []byte) ([]byte, packetV2, error) { data, ft, err := parseVarint(data) if err != nil { return nil, packetV2{}, err } p := packetV2{ fieldType: fieldType(ft), } if p.fieldType == fieldEOS { return data, p, nil } data, payloadLen, err := parseVarint(data) if err != nil { return nil, packetV2{}, err } if payloadLen > len(data) { return nil, packetV2{}, fmt.Errorf("field data extends past end of buffer") } p.data = data[0:payloadLen] return data[payloadLen:], p, nil } // parseVarint parses the variable-length integer // at the start of the given data and returns rest // of the buffer and the number. func parseVarint(data []byte) ([]byte, int, error) { val, n := binary.Uvarint(data) if n > 0 { if val > 0x7fffffff { return nil, 0, fmt.Errorf("varint value out of range") } return data[n:], int(val), nil } if n == 0 { return nil, 0, fmt.Errorf("varint value extends past end of buffer") } return nil, 0, fmt.Errorf("varint value out of range") } func appendPacketV2(data []byte, p packetV2) []byte { data = appendVarint(data, int(p.fieldType)) if p.fieldType != fieldEOS { data = appendVarint(data, len(p.data)) data = append(data, p.data...) } return data } func appendEOSV2(data []byte) []byte { return append(data, 0) } func appendVarint(data []byte, x int) []byte { var buf [binary.MaxVarintLen32]byte n := binary.PutUvarint(buf[:], uint64(x)) return append(data, buf[:n]...) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/packet-v1_test.go���������������������������������0000644�0610621�0607500�00000004566�13172163405�026074� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "strconv" "strings" "unicode" gc "gopkg.in/check.v1" ) type packetV1Suite struct{} var _ = gc.Suite(&packetV1Suite{}) func (*packetV1Suite) TestAppendPacket(c *gc.C) { data, ok := appendPacketV1(nil, "field", []byte("some data")) c.Assert(ok, gc.Equals, true) c.Assert(string(data), gc.Equals, "0014field some data\n") data, ok = appendPacketV1(data, "otherfield", []byte("more and more data")) c.Assert(ok, gc.Equals, true) c.Assert(string(data), gc.Equals, "0014field some data\n0022otherfield more and more data\n") } func (*packetV1Suite) TestAppendPacketTooBig(c *gc.C) { data, ok := appendPacketV1(nil, "field", make([]byte, 65532)) c.Assert(ok, gc.Equals, false) c.Assert(data, gc.IsNil) } var parsePacketV1Tests = []struct { data string expect packetV1 expectErr string }{{ expectErr: "packet too short", }, { data: "0014field some data\n", expect: packetV1{ fieldName: []byte("field"), data: []byte("some data"), totalLen: 20, }, }, { data: "0015field some data\n", expectErr: "packet size too big", }, { data: "0003a\n", expectErr: "packet size too small", }, { data: "0014fieldwithoutanyspaceordata\n", expectErr: "cannot parse field name", }, { data: "fedcsomefield " + strings.Repeat("x", 0xfedc-len("0000somefield \n")) + "\n", expect: packetV1{ fieldName: []byte("somefield"), data: []byte(strings.Repeat("x", 0xfedc-len("0000somefield \n"))), totalLen: 0xfedc, }, }, { data: "zzzzbadpacketsizenomacaroon", expectErr: "cannot parse size", }} func (*packetV1Suite) TestParsePacketV1(c *gc.C) { for i, test := range parsePacketV1Tests { c.Logf("test %d: %q", i, truncate(test.data)) p, err := parsePacketV1([]byte(test.data)) if test.expectErr != "" { c.Assert(err, gc.ErrorMatches, test.expectErr) c.Assert(p, gc.DeepEquals, packetV1{}) continue } c.Assert(err, gc.IsNil) c.Assert(p, gc.DeepEquals, test.expect) } } func truncate(d string) string { if len(d) > 50 { return d[0:50] + "..." } return d } func (*packetV1Suite) TestAsciiHex(c *gc.C) { for b := 0; b < 256; b++ { n, err := strconv.ParseInt(string(b), 16, 8) value, ok := asciiHex(byte(b)) if err != nil || unicode.IsUpper(rune(b)) { c.Assert(ok, gc.Equals, false) c.Assert(value, gc.Equals, 0) } else { c.Assert(ok, gc.Equals, true) c.Assert(value, gc.Equals, int(n)) } } } ������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/packet-v1.go��������������������������������������0000644�0610621�0607500�00000006265�13172163405�025033� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "bytes" "fmt" ) // field names, as defined in libmacaroons const ( fieldNameLocation = "location" fieldNameIdentifier = "identifier" fieldNameSignature = "signature" fieldNameCaveatId = "cid" fieldNameVerificationId = "vid" fieldNameCaveatLocation = "cl" ) // maxPacketV1Len is the maximum allowed length of a packet in the v1 macaroon // serialization format. const maxPacketV1Len = 0xffff // The original macaroon binary encoding is made from a sequence // of "packets", each of which has a field name and some data. // The encoding is: // // - four ascii hex digits holding the entire packet size (including // the digits themselves). // // - the field name, followed by an ascii space. // // - the raw data // // - a newline (\n) character // // The packet struct below holds a reference into Macaroon.data. type packetV1 struct { // ftype holds the field name of the packet. fieldName []byte // data holds the packet's data. data []byte // len holds the total length in bytes // of the packet, including any header. totalLen int } // parsePacket parses the packet at the start of the // given data. func parsePacketV1(data []byte) (packetV1, error) { if len(data) < 6 { return packetV1{}, fmt.Errorf("packet too short") } plen, ok := parseSizeV1(data) if !ok { return packetV1{}, fmt.Errorf("cannot parse size") } if plen > len(data) { return packetV1{}, fmt.Errorf("packet size too big") } if plen < 4 { return packetV1{}, fmt.Errorf("packet size too small") } data = data[4:plen] i := bytes.IndexByte(data, ' ') if i <= 0 { return packetV1{}, fmt.Errorf("cannot parse field name") } fieldName := data[0:i] if data[len(data)-1] != '\n' { return packetV1{}, fmt.Errorf("no terminating newline found") } return packetV1{ fieldName: fieldName, data: data[i+1 : len(data)-1], totalLen: plen, }, nil } // appendPacketV1 appends a packet with the given field name // and data to the given buffer. If the field and data were // too long to be encoded, it returns nil, false; otherwise // it returns the appended buffer. func appendPacketV1(buf []byte, field string, data []byte) ([]byte, bool) { plen := packetV1Size(field, data) if plen > maxPacketV1Len { return nil, false } buf = appendSizeV1(buf, plen) buf = append(buf, field...) buf = append(buf, ' ') buf = append(buf, data...) buf = append(buf, '\n') return buf, true } func packetV1Size(field string, data []byte) int { return 4 + len(field) + 1 + len(data) + 1 } var hexDigits = []byte("0123456789abcdef") func appendSizeV1(data []byte, size int) []byte { return append(data, hexDigits[size>>12], hexDigits[(size>>8)&0xf], hexDigits[(size>>4)&0xf], hexDigits[size&0xf], ) } func parseSizeV1(data []byte) (int, bool) { d0, ok0 := asciiHex(data[0]) d1, ok1 := asciiHex(data[1]) d2, ok2 := asciiHex(data[2]) d3, ok3 := asciiHex(data[3]) return d0<<12 + d1<<8 + d2<<4 + d3, ok0 && ok1 && ok2 && ok3 } func asciiHex(b byte) (int, bool) { switch { case b >= '0' && b <= '9': return int(b) - '0', true case b >= 'a' && b <= 'f': return int(b) - 'a' + 0xa, true } return 0, false } func isASCIIHex(b byte) bool { _, ok := asciiHex(b) return ok } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/marshal_test.go�����������������������������������0000644�0610621�0607500�00000013723�13172163405�025723� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon_test import ( jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/macaroon.v2-unstable" ) type marshalSuite struct{} var _ = gc.Suite(&marshalSuite{}) func (s *marshalSuite) TestMarshalUnmarshalMacaroonV1(c *gc.C) { s.testMarshalUnmarshalWithVersion(c, macaroon.V1) } func (s *marshalSuite) TestMarshalUnmarshalMacaroonV2(c *gc.C) { s.testMarshalUnmarshalWithVersion(c, macaroon.V2) } func (*marshalSuite) testMarshalUnmarshalWithVersion(c *gc.C, vers macaroon.Version) { rootKey := []byte("secret") m := MustNew(rootKey, []byte("some id"), "a location", vers) // Adding the third party caveat before the first party caveat // tests a former bug where the caveat wasn't zeroed // before moving to the next caveat. err := m.AddThirdPartyCaveat([]byte("shared root key"), []byte("3rd party caveat"), "remote.com") c.Assert(err, gc.IsNil) err = m.AddFirstPartyCaveat("a caveat") c.Assert(err, gc.IsNil) b, err := m.MarshalBinary() c.Assert(err, gc.IsNil) var um macaroon.Macaroon err = um.UnmarshalBinary(b) c.Assert(err, gc.IsNil) c.Assert(um.Location(), gc.Equals, m.Location()) c.Assert(string(um.Id()), gc.Equals, string(m.Id())) c.Assert(um.Signature(), jc.DeepEquals, m.Signature()) c.Assert(um.Caveats(), jc.DeepEquals, m.Caveats()) c.Assert(um.Version(), gc.Equals, vers) um.SetVersion(m.Version()) c.Assert(m, jc.DeepEquals, &um) } func (s *marshalSuite) TestMarshalBinaryRoundTrip(c *gc.C) { // This data holds the V2 binary encoding of data := []byte( "\x02" + "\x01\x0ehttp://mybank/" + "\x02\x1cwe used our other secret key" + "\x00" + "\x02\x14account = 3735928559" + "\x00" + "\x01\x13http://auth.mybank/" + "\x02'this was how we remind auth of key/pred" + "\x04\x48\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd3\x6e\xc5\x02\xe0\x58\x86\xd1\xf0\x27\x9f\x05\x5f\xa5\x25\x54\xd1\x6d\x16\xc1\xb1\x40\x74\xbb\xb8\x3f\xf0\xfd\xd7\x9d\xc2\xfe\x09\x8f\x0e\xd4\xa2\xb0\x91\x13\x0e\x6b\x5d\xb4\x6a\x20\xa8\x6b" + "\x00" + "\x00" + "\x06\x20\xd2\x7d\xb2\xfd\x1f\x22\x76\x0e\x4c\x3d\xae\x81\x37\xe2\xd8\xfc\x1d\xf6\xc0\x74\x1c\x18\xae\xd4\xb9\x72\x56\xbf\x78\xd1\xf5\x5c", ) var m macaroon.Macaroon err := m.UnmarshalBinary(data) c.Assert(err, gc.Equals, nil) assertLibMacaroonsMacaroon(c, &m) c.Assert(m.Version(), gc.Equals, macaroon.V2) data1, err := m.MarshalBinary() c.Assert(err, gc.Equals, nil) c.Assert(data1, jc.DeepEquals, data) } func (s *marshalSuite) TestMarshalUnmarshalSliceV1(c *gc.C) { s.testMarshalUnmarshalSliceWithVersion(c, macaroon.V1) } func (s *marshalSuite) TestMarshalUnmarshalSliceV2(c *gc.C) { s.testMarshalUnmarshalSliceWithVersion(c, macaroon.V2) } func (*marshalSuite) testMarshalUnmarshalSliceWithVersion(c *gc.C, vers macaroon.Version) { rootKey := []byte("secret") m1 := MustNew(rootKey, []byte("some id"), "a location", vers) m2 := MustNew(rootKey, []byte("some other id"), "another location", vers) err := m1.AddFirstPartyCaveat("a caveat") c.Assert(err, gc.IsNil) err = m2.AddFirstPartyCaveat("another caveat") c.Assert(err, gc.IsNil) macaroons := macaroon.Slice{m1, m2} b, err := macaroons.MarshalBinary() c.Assert(err, gc.IsNil) var unmarshaledMacs macaroon.Slice err = unmarshaledMacs.UnmarshalBinary(b) c.Assert(err, gc.IsNil) c.Assert(unmarshaledMacs, gc.HasLen, len(macaroons)) for i, m := range macaroons { um := unmarshaledMacs[i] c.Assert(um.Location(), gc.Equals, m.Location()) c.Assert(string(um.Id()), gc.Equals, string(m.Id())) c.Assert(um.Signature(), jc.DeepEquals, m.Signature()) c.Assert(um.Caveats(), jc.DeepEquals, m.Caveats()) c.Assert(um.Version(), gc.Equals, vers) um.SetVersion(m.Version()) } c.Assert(macaroons, jc.DeepEquals, unmarshaledMacs) // Check that appending a caveat to the first does not // affect the second. for i := 0; i < 10; i++ { err = unmarshaledMacs[0].AddFirstPartyCaveat("caveat") c.Assert(err, gc.IsNil) } unmarshaledMacs[1].SetVersion(macaroons[1].Version()) c.Assert(unmarshaledMacs[1], jc.DeepEquals, macaroons[1]) c.Assert(err, gc.IsNil) } func (s *marshalSuite) TestSliceRoundTripV1(c *gc.C) { s.testSliceRoundTripWithVersion(c, macaroon.V1) } func (s *marshalSuite) TestSliceRoundTripV2(c *gc.C) { s.testSliceRoundTripWithVersion(c, macaroon.V2) } func (*marshalSuite) testSliceRoundTripWithVersion(c *gc.C, vers macaroon.Version) { rootKey := []byte("secret") m1 := MustNew(rootKey, []byte("some id"), "a location", vers) m2 := MustNew(rootKey, []byte("some other id"), "another location", vers) err := m1.AddFirstPartyCaveat("a caveat") c.Assert(err, gc.IsNil) err = m2.AddFirstPartyCaveat("another caveat") c.Assert(err, gc.IsNil) macaroons := macaroon.Slice{m1, m2} b, err := macaroons.MarshalBinary() c.Assert(err, gc.IsNil) var unmarshaledMacs macaroon.Slice err = unmarshaledMacs.UnmarshalBinary(b) c.Assert(err, gc.IsNil) marshaledMacs, err := unmarshaledMacs.MarshalBinary() c.Assert(err, gc.IsNil) c.Assert(b, jc.DeepEquals, marshaledMacs) } var base64DecodeTests = []struct { about string input string expect string expectError string }{{ about: "empty string", input: "", expect: "", }, { about: "standard encoding, padded", input: "Z29+IQ==", expect: "go~!", }, { about: "URL encoding, padded", input: "Z29-IQ==", expect: "go~!", }, { about: "standard encoding, not padded", input: "Z29+IQ", expect: "go~!", }, { about: "URL encoding, not padded", input: "Z29-IQ", expect: "go~!", }, { about: "standard encoding, too much padding", input: "Z29+IQ===", expectError: `illegal base64 data at input byte 8`, }} func (*marshalSuite) TestBase64Decode(c *gc.C) { for i, test := range base64DecodeTests { c.Logf("test %d: %s", i, test.about) out, err := macaroon.Base64Decode([]byte(test.input)) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) } else { c.Assert(err, gc.Equals, nil) c.Assert(string(out), gc.Equals, test.expect) } } } ���������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/marshal.go����������������������������������������0000644�0610621�0607500�00000014503�13172163405�024661� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "encoding/base64" "encoding/json" "fmt" ) // Version specifies the version of a macaroon. // In version 1, the macaroon id and all caveats // must be UTF-8-compatible strings, and the // size of any part of the macaroon may not exceed // approximately 64K. In version 2, // all field may be arbitrary binary blobs. type Version uint16 const ( // V1 specifies version 1 macaroons. V1 Version = 1 // V2 specifies version 2 macaroons. V2 Version = 2 // LatestVersion holds the latest supported version. LatestVersion = V2 ) // String returns a string representation of the version; // for example V1 formats as "v1". func (v Version) String() string { return fmt.Sprintf("v%d", v) } // Version returns the version of the macaroon. func (m *Macaroon) Version() Version { return m.version } // MarshalJSON implements json.Marshaler by marshaling the // macaroon in JSON format. The serialisation format is determined // by the macaroon's version. func (m *Macaroon) MarshalJSON() ([]byte, error) { switch m.version { case V1: return m.marshalJSONV1() case V2: return m.marshalJSONV2() default: return nil, fmt.Errorf("unknown version %v", m.version) } } // UnmarshalJSON implements json.Unmarshaller by unmarshaling // the given macaroon in JSON format. It accepts both V1 and V2 // forms encoded forms, and also a base64-encoded JSON string // containing the binary-marshaled macaroon. // // After unmarshaling, the macaroon's version will reflect // the version that it was unmarshaled as. func (m *Macaroon) UnmarshalJSON(data []byte) error { if data[0] == '"' { // It's a string, so it must be a base64-encoded binary form. var s string if err := json.Unmarshal(data, &s); err != nil { return err } data, err := Base64Decode([]byte(s)) if err != nil { return err } if err := m.UnmarshalBinary(data); err != nil { return err } return nil } // Not a string; try to unmarshal into both kinds of macaroon object. // This assumes that neither format has any fields in common. // For subsequent versions we may need to change this approach. type MacaroonJSONV1 macaroonJSONV1 type MacaroonJSONV2 macaroonJSONV2 var both struct { *MacaroonJSONV1 *MacaroonJSONV2 } if err := json.Unmarshal(data, &both); err != nil { return err } switch { case both.MacaroonJSONV1 != nil && both.MacaroonJSONV2 != nil: return fmt.Errorf("cannot determine macaroon encoding version") case both.MacaroonJSONV1 != nil: if err := m.initJSONV1((*macaroonJSONV1)(both.MacaroonJSONV1)); err != nil { return err } m.version = V1 case both.MacaroonJSONV2 != nil: if err := m.initJSONV2((*macaroonJSONV2)(both.MacaroonJSONV2)); err != nil { return err } m.version = V2 default: return fmt.Errorf("invalid JSON macaroon encoding") } return nil } // UnmarshalBinary implements encoding.BinaryUnmarshaler. // It accepts both V1 and V2 binary encodings. func (m *Macaroon) UnmarshalBinary(data []byte) error { // Copy the data to avoid retaining references to it // in the internal data structures. data = append([]byte(nil), data...) _, err := m.parseBinary(data) return err } // parseBinary parses the macaroon in binary format // from the given data and returns where the parsed data ends. // // It retains references to data. func (m *Macaroon) parseBinary(data []byte) ([]byte, error) { if len(data) == 0 { return nil, fmt.Errorf("empty macaroon data") } v := data[0] if v == 2 { // Version 2 binary format. data, err := m.parseBinaryV2(data) if err != nil { return nil, fmt.Errorf("unmarshal v2: %v", err) } m.version = V2 return data, nil } if isASCIIHex(v) { // It's a hex digit - version 1 binary format data, err := m.parseBinaryV1(data) if err != nil { return nil, fmt.Errorf("unmarshal v1: %v", err) } m.version = V1 return data, nil } return nil, fmt.Errorf("cannot determine data format of binary-encoded macaroon") } // MarshalBinary implements encoding.BinaryMarshaler by // formatting the macaroon according to the version specified // by MarshalAs. func (m *Macaroon) MarshalBinary() ([]byte, error) { return m.appendBinary(nil) } // appendBinary appends the binary-formatted macaroon to // the given data, formatting it according to the macaroon's // version. func (m *Macaroon) appendBinary(data []byte) ([]byte, error) { switch m.version { case V1: return m.appendBinaryV1(data) case V2: return m.appendBinaryV2(data), nil default: return nil, fmt.Errorf("bad macaroon version %v", m.version) } } // Slice defines a collection of macaroons. By convention, the // first macaroon in the slice is a primary macaroon and the rest // are discharges for its third party caveats. type Slice []*Macaroon // MarshalBinary implements encoding.BinaryMarshaler. func (s Slice) MarshalBinary() ([]byte, error) { var data []byte var err error for _, m := range s { data, err = m.appendBinary(data) if err != nil { return nil, fmt.Errorf("failed to marshal macaroon %q: %v", m.Id(), err) } } return data, nil } // UnmarshalBinary implements encoding.BinaryUnmarshaler. // It accepts all known binary encodings for the data - all the // embedded macaroons need not be encoded in the same format. func (s *Slice) UnmarshalBinary(data []byte) error { // Prevent the internal data structures from holding onto the // slice by copying it first. data = append([]byte(nil), data...) *s = (*s)[:0] for len(data) > 0 { var m Macaroon rest, err := m.parseBinary(data) if err != nil { return fmt.Errorf("cannot unmarshal macaroon: %v", err) } *s = append(*s, &m) data = rest } return nil } const ( padded = 1 << iota stdEncoding ) var codecs = [4]*base64.Encoding{ 0: base64.RawURLEncoding, padded: base64.URLEncoding, stdEncoding: base64.RawStdEncoding, stdEncoding | padded: base64.StdEncoding, } // Base64Decode base64-decodes the given data. // It accepts both standard and URL encodings, both // padded and unpadded. func Base64Decode(data []byte) ([]byte, error) { encoding := 0 if len(data) > 0 && data[len(data)-1] == '=' { encoding |= padded } for _, b := range data { if b == '/' || b == '+' { encoding |= stdEncoding break } } codec := codecs[encoding] buf := make([]byte, codec.DecodedLen(len(data))) n, err := codec.Decode(buf, data) if err == nil { return buf[0:n], nil } return nil, err } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/marshal-v2.go�������������������������������������0000644�0610621�0607500�00000015672�13172163405�025216� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "encoding/base64" "encoding/json" "fmt" "unicode/utf8" ) // macaroonJSONV2 defines the V2 JSON format for macaroons. type macaroonJSONV2 struct { Caveats []caveatJSONV2 `json:"c,omitempty"` Location string `json:"l,omitempty"` Identifier string `json:"i,omitempty"` Identifier64 string `json:"i64,omitempty"` Signature string `json:"s,omitempty"` Signature64 string `json:"s64,omitempty"` } // caveatJSONV2 defines the V2 JSON format for caveats within a macaroon. type caveatJSONV2 struct { CID string `json:"i,omitempty"` CID64 string `json:"i64,omitempty"` VID string `json:"v,omitempty"` VID64 string `json:"v64,omitempty"` Location string `json:"l,omitempty"` } func (m *Macaroon) marshalJSONV2() ([]byte, error) { mjson := macaroonJSONV2{ Location: m.location, Caveats: make([]caveatJSONV2, len(m.caveats)), } putJSONBinaryField(m.id, &mjson.Identifier, &mjson.Identifier64) putJSONBinaryField(m.sig[:], &mjson.Signature, &mjson.Signature64) for i, cav := range m.caveats { cavjson := caveatJSONV2{ Location: cav.Location, } putJSONBinaryField(cav.Id, &cavjson.CID, &cavjson.CID64) putJSONBinaryField(cav.VerificationId, &cavjson.VID, &cavjson.VID64) mjson.Caveats[i] = cavjson } data, err := json.Marshal(mjson) if err != nil { return nil, fmt.Errorf("cannot marshal json data: %v", err) } return data, nil } // initJSONV2 initializes m from the JSON-unmarshaled data // held in mjson. func (m *Macaroon) initJSONV2(mjson *macaroonJSONV2) error { id, err := jsonBinaryField(mjson.Identifier, mjson.Identifier64) if err != nil { return fmt.Errorf("invalid identifier: %v", err) } m.init(id, mjson.Location, V2) sig, err := jsonBinaryField(mjson.Signature, mjson.Signature64) if err != nil { return fmt.Errorf("invalid signature: %v", err) } if len(sig) != hashLen { return fmt.Errorf("signature has unexpected length %d", len(sig)) } copy(m.sig[:], sig) m.caveats = make([]Caveat, 0, len(mjson.Caveats)) for _, cav := range mjson.Caveats { cid, err := jsonBinaryField(cav.CID, cav.CID64) if err != nil { return fmt.Errorf("invalid cid in caveat: %v", err) } vid, err := jsonBinaryField(cav.VID, cav.VID64) if err != nil { return fmt.Errorf("invalid vid in caveat: %v", err) } m.appendCaveat(cid, vid, cav.Location) } return nil } // putJSONBinaryField puts the value of x into one // of the appropriate fields depending on its value. func putJSONBinaryField(x []byte, s, sb64 *string) { if !utf8.Valid(x) { *sb64 = base64.RawURLEncoding.EncodeToString(x) return } // We could use either string or base64 encoding; // choose the most compact of the two possibilities. b64len := base64.RawURLEncoding.EncodedLen(len(x)) sx := string(x) if jsonEnc, _ := json.Marshal(sx); len(jsonEnc)-2 <= b64len+2 { // The JSON encoding is smaller than the base 64 encoding. // NB marshaling a string can never return an error; // it always includes the two quote characters; // but using base64 also uses two extra characters for the // "64" suffix on the field name. If all is equal, prefer string // encoding because it's more readable. *s = sx return } *sb64 = base64.RawURLEncoding.EncodeToString(x) } // jsonBinaryField returns the value of a JSON field that may // be string, hex or base64-encoded. func jsonBinaryField(s, sb64 string) ([]byte, error) { switch { case s != "": if sb64 != "" { return nil, fmt.Errorf("ambiguous field encoding") } return []byte(s), nil case sb64 != "": return Base64Decode([]byte(sb64)) } return []byte{}, nil } // The v2 binary format of a macaroon is as follows. // All entries other than the version are packets as // parsed by parsePacketV2. // // version [1 byte] // location? // identifier // eos // ( // location? // identifier // verificationId? // eos // )* // eos // signature // // See also https://github.com/rescrv/libmacaroons/blob/master/doc/format.txt // parseBinaryV2 parses the given data in V2 format into the macaroon. The macaroon's // internal data structures will retain references to the data. It // returns the data after the end of the macaroon. func (m *Macaroon) parseBinaryV2(data []byte) ([]byte, error) { // The version has already been checked, so // skip it. data = data[1:] data, section, err := parseSectionV2(data) if err != nil { return nil, err } var loc string if len(section) > 0 && section[0].fieldType == fieldLocation { loc = string(section[0].data) section = section[1:] } if len(section) != 1 || section[0].fieldType != fieldIdentifier { return nil, fmt.Errorf("invalid macaroon header") } id := section[0].data m.init(id, loc, V2) for { rest, section, err := parseSectionV2(data) if err != nil { return nil, err } data = rest if len(section) == 0 { break } var cav Caveat if len(section) > 0 && section[0].fieldType == fieldLocation { cav.Location = string(section[0].data) section = section[1:] } if len(section) == 0 || section[0].fieldType != fieldIdentifier { return nil, fmt.Errorf("no identifier in caveat") } cav.Id = section[0].data section = section[1:] if len(section) == 0 { // First party caveat. if cav.Location != "" { return nil, fmt.Errorf("location not allowed in first party caveat") } m.caveats = append(m.caveats, cav) continue } if len(section) != 1 { return nil, fmt.Errorf("extra fields found in caveat") } if section[0].fieldType != fieldVerificationId { return nil, fmt.Errorf("invalid field found in caveat") } cav.VerificationId = section[0].data m.caveats = append(m.caveats, cav) } data, sig, err := parsePacketV2(data) if err != nil { return nil, err } if sig.fieldType != fieldSignature { return nil, fmt.Errorf("unexpected field found instead of signature") } if len(sig.data) != hashLen { return nil, fmt.Errorf("signature has unexpected length") } copy(m.sig[:], sig.data) return data, nil } // appendBinaryV2 appends the binary-encoded macaroon // in v2 format to data. func (m *Macaroon) appendBinaryV2(data []byte) []byte { // Version byte. data = append(data, 2) if len(m.location) > 0 { data = appendPacketV2(data, packetV2{ fieldType: fieldLocation, data: []byte(m.location), }) } data = appendPacketV2(data, packetV2{ fieldType: fieldIdentifier, data: m.id, }) data = appendEOSV2(data) for _, cav := range m.caveats { if len(cav.Location) > 0 { data = appendPacketV2(data, packetV2{ fieldType: fieldLocation, data: []byte(cav.Location), }) } data = appendPacketV2(data, packetV2{ fieldType: fieldIdentifier, data: cav.Id, }) if len(cav.VerificationId) > 0 { data = appendPacketV2(data, packetV2{ fieldType: fieldVerificationId, data: []byte(cav.VerificationId), }) } data = appendEOSV2(data) } data = appendEOSV2(data) data = appendPacketV2(data, packetV2{ fieldType: fieldSignature, data: m.sig[:], }) return data } ����������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/marshal-v1.go�������������������������������������0000644�0610621�0607500�00000012636�13172163405�025212� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "encoding/base64" "encoding/hex" "encoding/json" "fmt" "unicode/utf8" ) // macaroonJSONV1 defines the V1 JSON format for macaroons. type macaroonJSONV1 struct { Caveats []caveatJSONV1 `json:"caveats"` Location string `json:"location"` Identifier string `json:"identifier"` Signature string `json:"signature"` // hex-encoded } // caveatJSONV1 defines the V1 JSON format for caveats within a macaroon. type caveatJSONV1 struct { CID string `json:"cid"` VID string `json:"vid,omitempty"` Location string `json:"cl,omitempty"` } // marshalJSONV1 marshals the macaroon to the V1 JSON format. func (m *Macaroon) marshalJSONV1() ([]byte, error) { if !utf8.Valid(m.id) { return nil, fmt.Errorf("macaroon id is not valid UTF-8") } mjson := macaroonJSONV1{ Location: m.location, Identifier: string(m.id), Signature: hex.EncodeToString(m.sig[:]), Caveats: make([]caveatJSONV1, len(m.caveats)), } for i, cav := range m.caveats { if !utf8.Valid(cav.Id) { return nil, fmt.Errorf("caveat id is not valid UTF-8") } mjson.Caveats[i] = caveatJSONV1{ Location: cav.Location, CID: string(cav.Id), VID: base64.RawURLEncoding.EncodeToString(cav.VerificationId), } } data, err := json.Marshal(mjson) if err != nil { return nil, fmt.Errorf("cannot marshal json data: %v", err) } return data, nil } // initJSONV1 initializes m from the JSON-unmarshaled data // held in mjson. func (m *Macaroon) initJSONV1(mjson *macaroonJSONV1) error { m.init([]byte(mjson.Identifier), mjson.Location, V1) sig, err := hex.DecodeString(mjson.Signature) if err != nil { return fmt.Errorf("cannot decode macaroon signature %q: %v", m.sig, err) } if len(sig) != hashLen { return fmt.Errorf("signature has unexpected length %d", len(sig)) } copy(m.sig[:], sig) m.caveats = m.caveats[:0] for _, cav := range mjson.Caveats { vid, err := Base64Decode([]byte(cav.VID)) if err != nil { return fmt.Errorf("cannot decode verification id %q: %v", cav.VID, err) } m.appendCaveat([]byte(cav.CID), vid, cav.Location) } return nil } // The original (v1) binary format of a macaroon is as follows. // Each identifier represents a v1 packet. // // location // identifier // ( // caveatId? // verificationId? // caveatLocation? // )* // signature // parseBinaryV1 parses the given data in V1 format into the macaroon. The macaroon's // internal data structures will retain references to the data. It // returns the data after the end of the macaroon. func (m *Macaroon) parseBinaryV1(data []byte) ([]byte, error) { var err error loc, err := expectPacketV1(data, fieldNameLocation) if err != nil { return nil, err } data = data[loc.totalLen:] id, err := expectPacketV1(data, fieldNameIdentifier) if err != nil { return nil, err } data = data[id.totalLen:] m.init(id.data, string(loc.data), V1) var cav Caveat for { p, err := parsePacketV1(data) if err != nil { return nil, err } data = data[p.totalLen:] switch field := string(p.fieldName); field { case fieldNameSignature: // At the end of the caveats we find the signature. if cav.Id != nil { m.caveats = append(m.caveats, cav) } if len(p.data) != hashLen { return nil, fmt.Errorf("signature has unexpected length %d", len(p.data)) } copy(m.sig[:], p.data) return data, nil case fieldNameCaveatId: if cav.Id != nil { m.caveats = append(m.caveats, cav) cav = Caveat{} } cav.Id = p.data case fieldNameVerificationId: if cav.VerificationId != nil { return nil, fmt.Errorf("repeated field %q in caveat", fieldNameVerificationId) } cav.VerificationId = p.data case fieldNameCaveatLocation: if cav.Location != "" { return nil, fmt.Errorf("repeated field %q in caveat", fieldNameLocation) } cav.Location = string(p.data) default: return nil, fmt.Errorf("unexpected field %q", field) } } } func expectPacketV1(data []byte, kind string) (packetV1, error) { p, err := parsePacketV1(data) if err != nil { return packetV1{}, err } if field := string(p.fieldName); field != kind { return packetV1{}, fmt.Errorf("unexpected field %q; expected %s", field, kind) } return p, nil } // appendBinaryV1 appends the binary encoding of m to data. func (m *Macaroon) appendBinaryV1(data []byte) ([]byte, error) { var ok bool data, ok = appendPacketV1(data, fieldNameLocation, []byte(m.location)) if !ok { return nil, fmt.Errorf("failed to append location to macaroon, packet is too long") } data, ok = appendPacketV1(data, fieldNameIdentifier, m.id) if !ok { return nil, fmt.Errorf("failed to append identifier to macaroon, packet is too long") } for _, cav := range m.caveats { data, ok = appendPacketV1(data, fieldNameCaveatId, cav.Id) if !ok { return nil, fmt.Errorf("failed to append caveat id to macaroon, packet is too long") } if cav.VerificationId == nil { continue } data, ok = appendPacketV1(data, fieldNameVerificationId, cav.VerificationId) if !ok { return nil, fmt.Errorf("failed to append verification id to macaroon, packet is too long") } data, ok = appendPacketV1(data, fieldNameCaveatLocation, []byte(cav.Location)) if !ok { return nil, fmt.Errorf("failed to append verification id to macaroon, packet is too long") } } data, ok = appendPacketV1(data, fieldNameSignature, m.sig[:]) if !ok { return nil, fmt.Errorf("failed to append signature to macaroon, packet is too long") } return data, nil } ��������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/macaroon_test.go����������������������������������0000644�0610621�0607500�00000066425�13172163405�026102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon_test import ( "encoding/base64" "encoding/hex" "encoding/json" "fmt" "testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/macaroon.v2-unstable" ) func TestPackage(t *testing.T) { gc.TestingT(t) } type macaroonSuite struct{} var _ = gc.Suite(&macaroonSuite{}) func never(string) error { return fmt.Errorf("condition is never true") } func (*macaroonSuite) TestNoCaveats(c *gc.C) { rootKey := []byte("secret") m := MustNew(rootKey, []byte("some id"), "a location", macaroon.LatestVersion) c.Assert(m.Location(), gc.Equals, "a location") c.Assert(m.Id(), gc.DeepEquals, []byte("some id")) err := m.Verify(rootKey, never, nil) c.Assert(err, gc.IsNil) } func (*macaroonSuite) TestFirstPartyCaveat(c *gc.C) { rootKey := []byte("secret") m := MustNew(rootKey, []byte("some id"), "a location", macaroon.LatestVersion) caveats := map[string]bool{ "a caveat": true, "another caveat": true, } tested := make(map[string]bool) for cav := range caveats { m.AddFirstPartyCaveat(cav) } expectErr := fmt.Errorf("condition not met") check := func(cav string) error { tested[cav] = true if caveats[cav] { return nil } return expectErr } err := m.Verify(rootKey, check, nil) c.Assert(err, gc.IsNil) c.Assert(tested, gc.DeepEquals, caveats) m.AddFirstPartyCaveat("not met") err = m.Verify(rootKey, check, nil) c.Assert(err, gc.Equals, expectErr) c.Assert(tested["not met"], gc.Equals, true) } func (*macaroonSuite) TestThirdPartyCaveat(c *gc.C) { rootKey := []byte("secret") m := MustNew(rootKey, []byte("some id"), "a location", macaroon.LatestVersion) dischargeRootKey := []byte("shared root key") thirdPartyCaveatId := []byte("3rd party caveat") err := m.AddThirdPartyCaveat(dischargeRootKey, thirdPartyCaveatId, "remote.com") c.Assert(err, gc.IsNil) dm := MustNew(dischargeRootKey, thirdPartyCaveatId, "remote location", macaroon.LatestVersion) dm.Bind(m.Signature()) err = m.Verify(rootKey, never, []*macaroon.Macaroon{dm}) c.Assert(err, gc.IsNil) } func (*macaroonSuite) TestThirdPartyCaveatBadRandom(c *gc.C) { rootKey := []byte("secret") m := MustNew(rootKey, []byte("some id"), "a location", macaroon.LatestVersion) dischargeRootKey := []byte("shared root key") thirdPartyCaveatId := []byte("3rd party caveat") err := macaroon.AddThirdPartyCaveatWithRand(m, dischargeRootKey, thirdPartyCaveatId, "remote.com", &macaroon.ErrorReader{}) c.Assert(err, gc.ErrorMatches, "cannot generate random bytes: fail") } func (*macaroonSuite) TestSetLocation(c *gc.C) { rootKey := []byte("secret") m := MustNew(rootKey, []byte("some id"), "a location", macaroon.LatestVersion) c.Assert(m.Location(), gc.Equals, "a location") m.SetLocation("another location") c.Assert(m.Location(), gc.Equals, "another location") } type conditionTest struct { conditions map[string]bool expectErr string } var verifyTests = []struct { about string macaroons []macaroonSpec conditions []conditionTest }{{ about: "single third party caveat without discharge", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "wonderful", }, { condition: "bob-is-great", location: "bob", rootKey: "bob-caveat-root-key", }}, }}, conditions: []conditionTest{{ conditions: map[string]bool{ "wonderful": true, }, expectErr: fmt.Sprintf(`cannot find discharge macaroon for caveat %x`, "bob-is-great"), }}, }, { about: "single third party caveat with discharge", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "wonderful", }, { condition: "bob-is-great", location: "bob", rootKey: "bob-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "bob-is-great", }}, conditions: []conditionTest{{ conditions: map[string]bool{ "wonderful": true, }, }, { conditions: map[string]bool{ "wonderful": false, }, expectErr: `condition "wonderful" not met`, }}, }, { about: "single third party caveat with discharge with mismatching root key", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "wonderful", }, { condition: "bob-is-great", location: "bob", rootKey: "bob-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key-wrong", id: "bob-is-great", }}, conditions: []conditionTest{{ conditions: map[string]bool{ "wonderful": true, }, expectErr: `signature mismatch after caveat verification`, }}, }, { about: "single third party caveat with two discharges", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "wonderful", }, { condition: "bob-is-great", location: "bob", rootKey: "bob-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "bob-is-great", caveats: []caveat{{ condition: "splendid", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "bob-is-great", caveats: []caveat{{ condition: "top of the world", }}, }}, conditions: []conditionTest{{ conditions: map[string]bool{ "wonderful": true, }, expectErr: `condition "splendid" not met`, }, { conditions: map[string]bool{ "wonderful": true, "splendid": true, "top of the world": true, }, expectErr: `discharge macaroon "bob-is-great" was not used`, }, { conditions: map[string]bool{ "wonderful": true, "splendid": false, "top of the world": true, }, expectErr: `condition "splendid" not met`, }, { conditions: map[string]bool{ "wonderful": true, "splendid": true, "top of the world": false, }, expectErr: `discharge macaroon "bob-is-great" was not used`, }}, }, { about: "one discharge used for two macaroons", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "somewhere else", location: "bob", rootKey: "bob-caveat-root-key", }, { condition: "bob-is-great", location: "charlie", rootKey: "bob-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "somewhere else", caveats: []caveat{{ condition: "bob-is-great", location: "charlie", rootKey: "bob-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "bob-is-great", }}, conditions: []conditionTest{{ expectErr: `discharge macaroon "bob-is-great" was used more than once`, }}, }, { about: "recursive third party caveat", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "bob-is-great", location: "bob", rootKey: "bob-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "bob-is-great", caveats: []caveat{{ condition: "bob-is-great", location: "charlie", rootKey: "bob-caveat-root-key", }}, }}, conditions: []conditionTest{{ expectErr: `discharge macaroon "bob-is-great" was used more than once`, }}, }, { about: "two third party caveats", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "wonderful", }, { condition: "bob-is-great", location: "bob", rootKey: "bob-caveat-root-key", }, { condition: "charlie-is-great", location: "charlie", rootKey: "charlie-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "bob-is-great", caveats: []caveat{{ condition: "splendid", }}, }, { location: "charlie", rootKey: "charlie-caveat-root-key", id: "charlie-is-great", caveats: []caveat{{ condition: "top of the world", }}, }}, conditions: []conditionTest{{ conditions: map[string]bool{ "wonderful": true, "splendid": true, "top of the world": true, }, }, { conditions: map[string]bool{ "wonderful": true, "splendid": false, "top of the world": true, }, expectErr: `condition "splendid" not met`, }, { conditions: map[string]bool{ "wonderful": true, "splendid": true, "top of the world": false, }, expectErr: `condition "top of the world" not met`, }}, }, { about: "third party caveat with undischarged third party caveat", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "wonderful", }, { condition: "bob-is-great", location: "bob", rootKey: "bob-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "bob-is-great", caveats: []caveat{{ condition: "splendid", }, { condition: "barbara-is-great", location: "barbara", rootKey: "barbara-caveat-root-key", }}, }}, conditions: []conditionTest{{ conditions: map[string]bool{ "wonderful": true, "splendid": true, }, expectErr: fmt.Sprintf(`cannot find discharge macaroon for caveat %x`, "barbara-is-great"), }}, }, { about: "multilevel third party caveats", macaroons: multilevelThirdPartyCaveatMacaroons, conditions: []conditionTest{{ conditions: map[string]bool{ "wonderful": true, "splendid": true, "high-fiving": true, "spiffing": true, }, }, { conditions: map[string]bool{ "wonderful": true, "splendid": true, "high-fiving": false, "spiffing": true, }, expectErr: `condition "high-fiving" not met`, }}, }, { about: "unused discharge", macaroons: []macaroonSpec{{ rootKey: "root-key", id: "root-id", }, { rootKey: "other-key", id: "unused", }}, conditions: []conditionTest{{ expectErr: `discharge macaroon "unused" was not used`, }}, }} var multilevelThirdPartyCaveatMacaroons = []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "wonderful", }, { condition: "bob-is-great", location: "bob", rootKey: "bob-caveat-root-key", }, { condition: "charlie-is-great", location: "charlie", rootKey: "charlie-caveat-root-key", }}, }, { location: "bob", rootKey: "bob-caveat-root-key", id: "bob-is-great", caveats: []caveat{{ condition: "splendid", }, { condition: "barbara-is-great", location: "barbara", rootKey: "barbara-caveat-root-key", }}, }, { location: "charlie", rootKey: "charlie-caveat-root-key", id: "charlie-is-great", caveats: []caveat{{ condition: "splendid", }, { condition: "celine-is-great", location: "celine", rootKey: "celine-caveat-root-key", }}, }, { location: "barbara", rootKey: "barbara-caveat-root-key", id: "barbara-is-great", caveats: []caveat{{ condition: "spiffing", }, { condition: "ben-is-great", location: "ben", rootKey: "ben-caveat-root-key", }}, }, { location: "ben", rootKey: "ben-caveat-root-key", id: "ben-is-great", }, { location: "celine", rootKey: "celine-caveat-root-key", id: "celine-is-great", caveats: []caveat{{ condition: "high-fiving", }}, }} func (*macaroonSuite) TestVerify(c *gc.C) { for i, test := range verifyTests { c.Logf("test %d: %s", i, test.about) rootKey, macaroons := makeMacaroons(test.macaroons) for _, cond := range test.conditions { c.Logf("conditions %#v", cond.conditions) check := func(cav string) error { if cond.conditions[cav] { return nil } return fmt.Errorf("condition %q not met", cav) } err := macaroons[0].Verify( rootKey, check, macaroons[1:], ) if cond.expectErr != "" { c.Assert(err, gc.ErrorMatches, cond.expectErr) } else { c.Assert(err, gc.IsNil) } // Cloned macaroon should have same verify result. cloneErr := macaroons[0].Clone().Verify(rootKey, check, macaroons[1:]) c.Assert(cloneErr, gc.DeepEquals, err) } } } func (*macaroonSuite) TestTraceVerify(c *gc.C) { rootKey, macaroons := makeMacaroons(multilevelThirdPartyCaveatMacaroons) traces, err := macaroons[0].TraceVerify(rootKey, macaroons[1:]) c.Assert(err, gc.Equals, nil) c.Assert(traces, gc.HasLen, len(macaroons)) // Check that we can run through the resulting operations and // arrive at the same signature. for i, m := range macaroons { r := traces[i].Results() c.Assert(b64str(r[len(r)-1]), gc.Equals, b64str(m.Signature()), gc.Commentf("macaroon %d", i)) } } func (*macaroonSuite) TestTraceVerifyFailure(c *gc.C) { rootKey, macaroons := makeMacaroons([]macaroonSpec{{ rootKey: "xxx", id: "hello", caveats: []caveat{{ condition: "cond1", }, { condition: "cond2", }, { condition: "cond3", }}, }}) // Marshal the macaroon, corrupt a condition, then unmarshal // it and check we see the expected trace failure. data, err := json.Marshal(macaroons[0]) c.Assert(err, gc.Equals, nil) var jm macaroon.MacaroonJSONV2 err = json.Unmarshal(data, &jm) c.Assert(err, gc.Equals, nil) jm.Caveats[1].CID = "cond2 corrupted" data, err = json.Marshal(jm) c.Assert(err, gc.Equals, nil) var corruptm *macaroon.Macaroon err = json.Unmarshal(data, &corruptm) c.Assert(err, gc.Equals, nil) traces, err := corruptm.TraceVerify(rootKey, nil) c.Assert(err, gc.ErrorMatches, `signature mismatch after caveat verification`) c.Assert(traces, gc.HasLen, 1) var kinds []macaroon.TraceOpKind for _, op := range traces[0].Ops { kinds = append(kinds, op.Kind) } c.Assert(kinds, gc.DeepEquals, []macaroon.TraceOpKind{ macaroon.TraceMakeKey, macaroon.TraceHash, // id macaroon.TraceHash, // cond1 macaroon.TraceHash, // cond2 macaroon.TraceHash, // cond3 macaroon.TraceFail, // sig mismatch }) } func b64str(b []byte) string { return base64.StdEncoding.EncodeToString(b) } func (*macaroonSuite) TestVerifySignature(c *gc.C) { rootKey, macaroons := makeMacaroons([]macaroonSpec{{ rootKey: "xxx", id: "hello", caveats: []caveat{{ rootKey: "y", condition: "something", location: "somewhere", }, { condition: "cond1", }, { condition: "cond2", }}, }, { rootKey: "y", id: "something", caveats: []caveat{{ condition: "cond3", }, { condition: "cond4", }}, }}) conds, err := macaroons[0].VerifySignature(rootKey, macaroons[1:]) c.Assert(err, gc.IsNil) c.Assert(conds, jc.DeepEquals, []string{"cond3", "cond4", "cond1", "cond2"}) conds, err = macaroons[0].VerifySignature(nil, macaroons[1:]) c.Assert(err, gc.ErrorMatches, `failed to decrypt caveat 0 signature: decryption failure`) c.Assert(conds, gc.IsNil) } // TODO(rog) move the following JSON-marshal tests into marshal_test.go. // jsonTestVersions holds the various possible ways of marshaling a macaroon // to JSON. var jsonTestVersions = []macaroon.Version{ macaroon.V1, macaroon.V2, } func (s *macaroonSuite) TestMarshalJSON(c *gc.C) { for i, vers := range jsonTestVersions { c.Logf("test %d: %v", i, vers) s.testMarshalJSONWithVersion(c, vers) } } func (*macaroonSuite) testMarshalJSONWithVersion(c *gc.C, vers macaroon.Version) { rootKey := []byte("secret") m0 := MustNew(rootKey, []byte("some id"), "a location", vers) m0.AddFirstPartyCaveat("account = 3735928559") m0JSON, err := json.Marshal(m0) c.Assert(err, gc.IsNil) var m1 macaroon.Macaroon err = json.Unmarshal(m0JSON, &m1) c.Assert(err, gc.IsNil) c.Assert(m0.Location(), gc.Equals, m1.Location()) c.Assert(string(m0.Id()), gc.Equals, string(m1.Id())) c.Assert( hex.EncodeToString(m0.Signature()), gc.Equals, hex.EncodeToString(m1.Signature())) c.Assert(m1.Version(), gc.Equals, vers) } var jsonRoundTripTests = []struct { about string // data holds the marshaled data. All the data values hold // different encodings of the same macaroon - the same as produced // from the second example in libmacaroons // example README with the following libmacaroons code: // // secret = 'this is a different super-secret key; never use the same secret twice' // public = 'we used our other secret key' // location = 'http://mybank/' // M = macaroons.create(location, secret, public) // M = M.add_first_party_caveat('account = 3735928559') // caveat_key = '4; guaranteed random by a fair toss of the dice' // predicate = 'user = Alice' // identifier = 'this was how we remind auth of key/pred' // M = M.add_third_party_caveat('http://auth.mybank/', caveat_key, identifier) // m.serialize_json() data string expectExactRoundTrip bool expectVers macaroon.Version }{{ about: "exact JSON as produced by libmacaroons", data: `{"caveats":[{"cid":"account = 3735928559"},{"cid":"this was how we remind auth of key\/pred","vid":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA027FAuBYhtHwJ58FX6UlVNFtFsGxQHS7uD_w_dedwv4Jjw7UorCREw5rXbRqIKhr","cl":"http:\/\/auth.mybank\/"}],"location":"http:\/\/mybank\/","identifier":"we used our other secret key","signature":"d27db2fd1f22760e4c3dae8137e2d8fc1df6c0741c18aed4b97256bf78d1f55c"}`, expectVers: macaroon.V1, expectExactRoundTrip: true, }, { about: "V2 object with std base-64 binary values", data: `{"c":[{"i64":"YWNjb3VudCA9IDM3MzU5Mjg1NTk="},{"i64":"dGhpcyB3YXMgaG93IHdlIHJlbWluZCBhdXRoIG9mIGtleS9wcmVk","v64":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA027FAuBYhtHwJ58FX6UlVNFtFsGxQHS7uD/w/dedwv4Jjw7UorCREw5rXbRqIKhr","l":"http://auth.mybank/"}],"l":"http://mybank/","i64":"d2UgdXNlZCBvdXIgb3RoZXIgc2VjcmV0IGtleQ==","s64":"0n2y/R8idg5MPa6BN+LY/B32wHQcGK7UuXJWv3jR9Vw="}`, expectVers: macaroon.V2, }, { about: "V2 object with URL base-64 binary values", data: `{"c":[{"i64":"YWNjb3VudCA9IDM3MzU5Mjg1NTk"},{"i64":"dGhpcyB3YXMgaG93IHdlIHJlbWluZCBhdXRoIG9mIGtleS9wcmVk","v64":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA027FAuBYhtHwJ58FX6UlVNFtFsGxQHS7uD_w_dedwv4Jjw7UorCREw5rXbRqIKhr","l":"http://auth.mybank/"}],"l":"http://mybank/","i64":"d2UgdXNlZCBvdXIgb3RoZXIgc2VjcmV0IGtleQ","s64":"0n2y_R8idg5MPa6BN-LY_B32wHQcGK7UuXJWv3jR9Vw"}`, expectVers: macaroon.V2, }, { about: "V2 object with URL base-64 binary values and strings for ASCII", data: `{"c":[{"i":"account = 3735928559"},{"i":"this was how we remind auth of key/pred","v64":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA027FAuBYhtHwJ58FX6UlVNFtFsGxQHS7uD_w_dedwv4Jjw7UorCREw5rXbRqIKhr","l":"http://auth.mybank/"}],"l":"http://mybank/","i":"we used our other secret key","s64":"0n2y_R8idg5MPa6BN-LY_B32wHQcGK7UuXJWv3jR9Vw"}`, expectVers: macaroon.V2, expectExactRoundTrip: true, }, { about: "V2 base64 encoded binary", data: `"` + base64.StdEncoding.EncodeToString([]byte( "\x02"+ "\x01\x0ehttp://mybank/"+ "\x02\x1cwe used our other secret key"+ "\x00"+ "\x02\x14account = 3735928559"+ "\x00"+ "\x01\x13http://auth.mybank/"+ "\x02'this was how we remind auth of key/pred"+ "\x04\x48\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd3\x6e\xc5\x02\xe0\x58\x86\xd1\xf0\x27\x9f\x05\x5f\xa5\x25\x54\xd1\x6d\x16\xc1\xb1\x40\x74\xbb\xb8\x3f\xf0\xfd\xd7\x9d\xc2\xfe\x09\x8f\x0e\xd4\xa2\xb0\x91\x13\x0e\x6b\x5d\xb4\x6a\x20\xa8\x6b"+ "\x00"+ "\x00"+ "\x06\x20\xd2\x7d\xb2\xfd\x1f\x22\x76\x0e\x4c\x3d\xae\x81\x37\xe2\xd8\xfc\x1d\xf6\xc0\x74\x1c\x18\xae\xd4\xb9\x72\x56\xbf\x78\xd1\xf5\x5c", )) + `"`, expectVers: macaroon.V2, }} func (s *macaroonSuite) TestJSONRoundTrip(c *gc.C) { for i, test := range jsonRoundTripTests { c.Logf("test %d (%v) %s", i, test.expectVers, test.about) s.testJSONRoundTripWithVersion(c, test.data, test.expectVers, test.expectExactRoundTrip) } } func (*macaroonSuite) testJSONRoundTripWithVersion(c *gc.C, jsonData string, vers macaroon.Version, expectExactRoundTrip bool) { var m macaroon.Macaroon err := json.Unmarshal([]byte(jsonData), &m) c.Assert(err, gc.IsNil) assertLibMacaroonsMacaroon(c, &m) c.Assert(m.Version(), gc.Equals, vers) data, err := m.MarshalJSON() c.Assert(err, gc.IsNil) if expectExactRoundTrip { // The data is in canonical form, so we can check that // the round-tripped data is the same as the original // data when unmarshalled into an interface{}. var got interface{} err = json.Unmarshal(data, &got) c.Assert(err, gc.IsNil) var original interface{} err = json.Unmarshal([]byte(jsonData), &original) c.Assert(err, gc.IsNil) c.Assert(got, jc.DeepEquals, original, gc.Commentf("data: %s", data)) } // Check that we can unmarshal the marshaled data anyway // and the macaroon still looks the same. var m1 macaroon.Macaroon err = m1.UnmarshalJSON(data) c.Assert(err, gc.IsNil) assertLibMacaroonsMacaroon(c, &m1) c.Assert(m.Version(), gc.Equals, vers) } // assertLibMacaroonsMacaroon asserts that m looks like the macaroon // created in the README of the libmacaroons documentation. // In particular, the signature is the same one reported there. func assertLibMacaroonsMacaroon(c *gc.C, m *macaroon.Macaroon) { c.Assert(fmt.Sprintf("%x", m.Signature()), gc.Equals, "d27db2fd1f22760e4c3dae8137e2d8fc1df6c0741c18aed4b97256bf78d1f55c") c.Assert(m.Location(), gc.Equals, "http://mybank/") c.Assert(string(m.Id()), gc.Equals, "we used our other secret key") c.Assert(m.Caveats(), jc.DeepEquals, []macaroon.Caveat{{ Id: []byte("account = 3735928559"), }, { Id: []byte("this was how we remind auth of key/pred"), VerificationId: decodeB64("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA027FAuBYhtHwJ58FX6UlVNFtFsGxQHS7uD_w_dedwv4Jjw7UorCREw5rXbRqIKhr"), Location: "http://auth.mybank/", }}) } var jsonDecodeErrorTests = []struct { about string data string expectError string }{{ about: "ambiguous id #1", data: `{"i": "hello", "i64": "abcd", "s64": "ZDI3ZGIyZmQxZjIyNzYwZTRjM2RhZTgxMzdlMmQ4ZmMK"}`, expectError: "invalid identifier: ambiguous field encoding", }, { about: "ambiguous signature", data: `{"i": "hello", "s": "345", "s64": "543467"}`, expectError: "invalid signature: ambiguous field encoding", }, { about: "signature too short", data: `{"i": "hello", "s64": "0n2y/R8idg5MPa6BN+LY/B32wHQcGK7UuXJWv3jR9Q"}`, expectError: "signature has unexpected length 31", }, { about: "signature too long", data: `{"i": "hello", "s64": "0n2y/R8idg5MPa6BN+LY/B32wHQcGK7UuXJWv3jR9dP1"}`, expectError: "signature has unexpected length 33", }, { about: "invalid caveat id", data: `{"i": "hello", "s64": "0n2y/R8idg5MPa6BN+LY/B32wHQcGK7UuXJWv3jR9Vw", "c": [{"i": "hello", "i64": "00"}]}`, expectError: "invalid cid in caveat: ambiguous field encoding", }, { about: "invalid caveat vid", data: `{"i": "hello", "s64": "0n2y/R8idg5MPa6BN+LY/B32wHQcGK7UuXJWv3jR9Vw", "c": [{"i": "hello", "v": "hello", "v64": "00"}]}`, expectError: "invalid vid in caveat: ambiguous field encoding", }} func (*macaroonSuite) TestJSONDecodeError(c *gc.C) { for i, test := range jsonDecodeErrorTests { c.Logf("test %d: %v", i, test.about) var m macaroon.Macaroon err := json.Unmarshal([]byte(test.data), &m) c.Assert(err, gc.ErrorMatches, test.expectError) } } func (*macaroonSuite) TestInvalidMacaroonFields(c *gc.C) { rootKey := []byte("secret") badString := "foo\xff" m0 := MustNew(rootKey, []byte("some id"), "a location", macaroon.LatestVersion) err := m0.AddFirstPartyCaveat(badString) c.Assert(err, gc.ErrorMatches, `first party caveat condition is not a valid utf-8 string`) } func decodeB64(s string) []byte { data, err := base64.RawURLEncoding.DecodeString(s) if err != nil { panic(err) } return data } type caveat struct { rootKey string location string condition string } type macaroonSpec struct { rootKey string id string caveats []caveat location string } func makeMacaroons(mspecs []macaroonSpec) (rootKey []byte, macaroons macaroon.Slice) { for _, mspec := range mspecs { macaroons = append(macaroons, makeMacaroon(mspec)) } primary := macaroons[0] for _, m := range macaroons[1:] { m.Bind(primary.Signature()) } return []byte(mspecs[0].rootKey), macaroons } func makeMacaroon(mspec macaroonSpec) *macaroon.Macaroon { m := MustNew([]byte(mspec.rootKey), []byte(mspec.id), mspec.location, macaroon.LatestVersion) for _, cav := range mspec.caveats { if cav.location != "" { err := m.AddThirdPartyCaveat([]byte(cav.rootKey), []byte(cav.condition), cav.location) if err != nil { panic(err) } } else { m.AddFirstPartyCaveat(cav.condition) } } return m } func assertEqualMacaroons(c *gc.C, m0, m1 *macaroon.Macaroon) { m0json, err := m0.MarshalJSON() c.Assert(err, gc.IsNil) m1json, err := m1.MarshalJSON() var m0val, m1val interface{} err = json.Unmarshal(m0json, &m0val) c.Assert(err, gc.IsNil) err = json.Unmarshal(m1json, &m1val) c.Assert(err, gc.IsNil) c.Assert(m0val, gc.DeepEquals, m1val) } func (*macaroonSuite) TestBinaryRoundTrip(c *gc.C) { // Test the binary marshalling and unmarshalling of a macaroon with // first and third party caveats. rootKey := []byte("secret") m0 := MustNew(rootKey, []byte("some id"), "a location", macaroon.LatestVersion) err := m0.AddFirstPartyCaveat("first caveat") c.Assert(err, gc.IsNil) err = m0.AddFirstPartyCaveat("second caveat") c.Assert(err, gc.IsNil) err = m0.AddThirdPartyCaveat([]byte("shared root key"), []byte("3rd party caveat"), "remote.com") c.Assert(err, gc.IsNil) data, err := m0.MarshalBinary() c.Assert(err, gc.IsNil) var m1 macaroon.Macaroon err = m1.UnmarshalBinary(data) c.Assert(err, gc.IsNil) assertEqualMacaroons(c, m0, &m1) } func (*macaroonSuite) TestBinaryMarshalingAgainstLibmacaroon(c *gc.C) { // Test that a libmacaroon marshalled macaroon can be correctly unmarshaled data, err := base64.RawURLEncoding.DecodeString( "MDAxY2xvY2F0aW9uIGh0dHA6Ly9teWJhbmsvCjAwMmNpZGVudGlmaWVyIHdlIHVzZWQgb3VyIG90aGVyIHNlY3JldCBrZXkKMDAxZGNpZCBhY2NvdW50ID0gMzczNTkyODU1OQowMDMwY2lkIHRoaXMgd2FzIGhvdyB3ZSByZW1pbmQgYXV0aCBvZiBrZXkvcHJlZAowMDUxdmlkIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANNuxQLgWIbR8CefBV-lJVTRbRbBsUB0u7g_8P3XncL-CY8O1KKwkRMOa120aiCoawowMDFiY2wgaHR0cDovL2F1dGgubXliYW5rLwowMDJmc2lnbmF0dXJlINJ9sv0fInYOTD2ugTfi2Pwd9sB0HBiu1LlyVr940fVcCg") c.Assert(err, gc.IsNil) var m0 macaroon.Macaroon err = m0.UnmarshalBinary(data) c.Assert(err, gc.IsNil) jsonData := []byte(`{"caveats":[{"cid":"account = 3735928559"},{"cid":"this was how we remind auth of key\/pred","vid":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA027FAuBYhtHwJ58FX6UlVNFtFsGxQHS7uD_w_dedwv4Jjw7UorCREw5rXbRqIKhr","cl":"http:\/\/auth.mybank\/"}],"location":"http:\/\/mybank\/","identifier":"we used our other secret key","signature":"d27db2fd1f22760e4c3dae8137e2d8fc1df6c0741c18aed4b97256bf78d1f55c"}`) var m1 macaroon.Macaroon err = m1.UnmarshalJSON(jsonData) c.Assert(err, gc.IsNil) assertEqualMacaroons(c, &m0, &m1) } var binaryFieldBase64ChoiceTests = []struct { id string expectBase64 bool }{ {"x", false}, {"\x00", true}, {"\x03\x00", true}, {"a longer id with more stuff", false}, {"a longer id with more stuff and one invalid \xff", true}, {"a longer id with more stuff and one encoded \x00", false}, } func (*macaroonSuite) TestBinaryFieldBase64Choice(c *gc.C) { for i, test := range binaryFieldBase64ChoiceTests { c.Logf("test %d: %q", i, test.id) m := MustNew([]byte{0}, []byte(test.id), "", macaroon.LatestVersion) data, err := json.Marshal(m) c.Assert(err, gc.Equals, nil) var x struct { Id *string `json:"i"` Id64 *string `json:"i64"` } err = json.Unmarshal(data, &x) c.Assert(err, gc.Equals, nil) if test.expectBase64 { c.Assert(x.Id64, gc.NotNil) c.Assert(x.Id, gc.IsNil) idDec, err := base64.RawURLEncoding.DecodeString(*x.Id64) c.Assert(err, gc.Equals, nil) c.Assert(string(idDec), gc.Equals, test.id) } else { c.Assert(x.Id64, gc.IsNil) c.Assert(x.Id, gc.NotNil) c.Assert(*x.Id, gc.Equals, test.id) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/macaroon.go���������������������������������������0000644�0610621�0607500�00000026767�13172163405�025050� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// The macaroon package implements macaroons as described in // the paper "Macaroons: Cookies with Contextual Caveats for // Decentralized Authorization in the Cloud" // (http://theory.stanford.edu/~ataly/Papers/macaroons.pdf) // // See the macaroon bakery packages at http://godoc.org/gopkg.in/macaroon-bakery.v1 // for higher level services and operations that use macaroons. package macaroon import ( "bytes" "crypto/hmac" "crypto/rand" "fmt" "io" "unicode/utf8" ) // Macaroon holds a macaroon. // See Fig. 7 of http://theory.stanford.edu/~ataly/Papers/macaroons.pdf // for a description of the data contained within. // Macaroons are mutable objects - use Clone as appropriate // to avoid unwanted mutation. type Macaroon struct { location string id []byte caveats []Caveat sig [hashLen]byte version Version } // Caveat holds a first person or third party caveat. type Caveat struct { // Id holds the id of the caveat. For first // party caveats this holds the condition; // for third party caveats this holds the encrypted // third party caveat. Id []byte // VerificationId holds the verification id. If this is // non-empty, it's a third party caveat. VerificationId []byte // For third-party caveats, Location holds the // ocation hint. Note that this is not signature checked // as part of the caveat, so should only // be used as a hint. Location string } // isThirdParty reports whether the caveat must be satisfied // by some third party (if not, it's a first person caveat). func (cav *Caveat) isThirdParty() bool { return len(cav.VerificationId) > 0 } // New returns a new macaroon with the given root key, // identifier, location and version. func New(rootKey, id []byte, loc string, version Version) (*Macaroon, error) { var m Macaroon if version < V2 { if !utf8.Valid(id) { return nil, fmt.Errorf("invalid id for %v macaroon", id) } // TODO check id length too. } if version < V1 || version > LatestVersion { return nil, fmt.Errorf("invalid version %v", version) } m.version = version m.init(append([]byte(nil), id...), loc, version) derivedKey := makeKey(rootKey) m.sig = *keyedHash(derivedKey, m.id) return &m, nil } // init initializes the macaroon. It retains a reference to id. func (m *Macaroon) init(id []byte, loc string, vers Version) { m.location = loc m.id = append([]byte(nil), id...) m.version = vers } // SetLocation sets the location associated with the macaroon. // Note that the location is not included in the macaroon's // hash chain, so this does not change the signature. func (m *Macaroon) SetLocation(loc string) { m.location = loc } // Clone returns a copy of the receiving macaroon. func (m *Macaroon) Clone() *Macaroon { m1 := *m // Ensure that if any caveats are appended to the new // macaroon, it will copy the caveats. m1.caveats = m1.caveats[0:len(m1.caveats):len(m1.caveats)] return &m1 } // Location returns the macaroon's location hint. This is // not verified as part of the macaroon. func (m *Macaroon) Location() string { return m.location } // Id returns the id of the macaroon. This can hold // arbitrary information. func (m *Macaroon) Id() []byte { return append([]byte(nil), m.id...) } // Signature returns the macaroon's signature. func (m *Macaroon) Signature() []byte { // sig := m.sig // return sig[:] // Work around https://github.com/golang/go/issues/9537 sig := new([hashLen]byte) *sig = m.sig return sig[:] } // Caveats returns the macaroon's caveats. // This method will probably change, and it's important not to change the returned caveat. func (m *Macaroon) Caveats() []Caveat { return m.caveats[0:len(m.caveats):len(m.caveats)] } // appendCaveat appends a caveat without modifying the macaroon's signature. func (m *Macaroon) appendCaveat(caveatId, verificationId []byte, loc string) { m.caveats = append(m.caveats, Caveat{ Id: caveatId, VerificationId: verificationId, Location: loc, }) } func (m *Macaroon) addCaveat(caveatId, verificationId []byte, loc string) error { if m.version < V2 { if !utf8.Valid(caveatId) { return fmt.Errorf("invalid caveat id for %v macaroon", m.version) } // TODO check caveat length too. } m.appendCaveat(caveatId, verificationId, loc) if len(verificationId) == 0 { m.sig = *keyedHash(&m.sig, caveatId) } else { m.sig = *keyedHash2(&m.sig, verificationId, caveatId) } return nil } func keyedHash2(key *[keyLen]byte, d1, d2 []byte) *[hashLen]byte { var data [hashLen * 2]byte copy(data[0:], keyedHash(key, d1)[:]) copy(data[hashLen:], keyedHash(key, d2)[:]) return keyedHash(key, data[:]) } // Bind prepares the macaroon for being used to discharge the // macaroon with the given signature sig. This must be // used before it is used in the discharges argument to Verify. func (m *Macaroon) Bind(sig []byte) { m.sig = *bindForRequest(sig, &m.sig) } // AddFirstPartyCaveat adds a caveat that will be verified // by the target service. The caveat id must be a UTF-8 encoded // string. func (m *Macaroon) AddFirstPartyCaveat(condition string) error { if !utf8.ValidString(condition) { return fmt.Errorf("first party caveat condition is not a valid utf-8 string") } m.addCaveat([]byte(condition), nil, "") return nil } // AddThirdPartyCaveat adds a third-party caveat to the macaroon, // using the given shared root key, caveat id and location hint. // The caveat id should encode the root key in some // way, either by encrypting it with a key known to the third party // or by holding a reference to it stored in the third party's // storage. func (m *Macaroon) AddThirdPartyCaveat(rootKey, caveatId []byte, loc string) error { return m.addThirdPartyCaveatWithRand(rootKey, caveatId, loc, rand.Reader) } // addThirdPartyCaveatWithRand adds a third-party caveat to the macaroon, using // the given source of randomness for encrypting the caveat id. func (m *Macaroon) addThirdPartyCaveatWithRand(rootKey, caveatId []byte, loc string, r io.Reader) error { derivedKey := makeKey(rootKey) verificationId, err := encrypt(&m.sig, derivedKey, r) if err != nil { return err } m.addCaveat(caveatId, verificationId, loc) return nil } var zeroKey [hashLen]byte // bindForRequest binds the given macaroon // to the given signature of its parent macaroon. func bindForRequest(rootSig []byte, dischargeSig *[hashLen]byte) *[hashLen]byte { if bytes.Equal(rootSig, dischargeSig[:]) { return dischargeSig } return keyedHash2(&zeroKey, rootSig, dischargeSig[:]) } // Verify verifies that the receiving macaroon is valid. // The root key must be the same that the macaroon was originally // minted with. The check function is called to verify each // first-party caveat - it should return an error if the // condition is not met. // // The discharge macaroons should be provided in discharges. // // Verify returns nil if the verification succeeds. func (m *Macaroon) Verify(rootKey []byte, check func(caveat string) error, discharges []*Macaroon) error { var vctx verificationContext vctx.init(rootKey, m, discharges, check) return vctx.verify(m, rootKey) } // VerifySignature verifies the signature of the given macaroon with respect // to the root key, but it does not validate any first-party caveats. Instead // it returns all the applicable first party caveats on success. // // The caller is responsible for checking the returned first party caveat // conditions. func (m *Macaroon) VerifySignature(rootKey []byte, discharges []*Macaroon) ([]string, error) { n := len(m.caveats) for _, dm := range discharges { n += len(dm.caveats) } conds := make([]string, 0, n) var vctx verificationContext vctx.init(rootKey, m, discharges, func(cond string) error { conds = append(conds, cond) return nil }) err := vctx.verify(m, rootKey) if err != nil { return nil, err } return conds, nil } // TraceVerify verifies the signature of the macaroon without checking // any of the first party caveats, and returns a slice of Traces holding // the operations used when verifying the macaroons. // // Each element in the returned slice corresponds to the // operation for one of the argument macaroons, with m at index 0, // and discharges at 1 onwards. func (m *Macaroon) TraceVerify(rootKey []byte, discharges []*Macaroon) ([]Trace, error) { var vctx verificationContext vctx.init(rootKey, m, discharges, func(string) error { return nil }) vctx.traces = make([]Trace, len(discharges)+1) err := vctx.verify(m, rootKey) return vctx.traces, err } type verificationContext struct { used []bool discharges []*Macaroon rootSig *[hashLen]byte traces []Trace check func(caveat string) error } func (vctx *verificationContext) init(rootKey []byte, root *Macaroon, discharges []*Macaroon, check func(caveat string) error) { *vctx = verificationContext{ discharges: discharges, used: make([]bool, len(discharges)), rootSig: &root.sig, check: check, } } func (vctx *verificationContext) verify(root *Macaroon, rootKey []byte) error { vctx.traceRootKey(0, rootKey) vctx.trace(0, TraceMakeKey, rootKey, nil) derivedKey := makeKey(rootKey) if err := vctx.verify0(root, 0, derivedKey); err != nil { vctx.trace(0, TraceFail, nil, nil) return err } for i, wasUsed := range vctx.used { if !wasUsed { vctx.trace(i+1, TraceFail, nil, nil) return fmt.Errorf("discharge macaroon %q was not used", vctx.discharges[i].Id()) } } return nil } func (vctx *verificationContext) verify0(m *Macaroon, index int, rootKey *[hashLen]byte) error { vctx.trace(index, TraceHash, m.id, nil) caveatSig := keyedHash(rootKey, m.id) for i, cav := range m.caveats { if cav.isThirdParty() { cavKey, err := decrypt(caveatSig, cav.VerificationId) if err != nil { return fmt.Errorf("failed to decrypt caveat %d signature: %v", i, err) } dm, di, err := vctx.findDischarge(cav.Id) if err != nil { return err } vctx.traceRootKey(di+1, cavKey[:]) if err := vctx.verify0(dm, di+1, cavKey); err != nil { vctx.trace(di+1, TraceFail, nil, nil) return err } vctx.trace(index, TraceHash, cav.VerificationId, cav.Id) caveatSig = keyedHash2(caveatSig, cav.VerificationId, cav.Id) } else { vctx.trace(index, TraceHash, cav.Id, nil) caveatSig = keyedHash(caveatSig, cav.Id) if err := vctx.check(string(cav.Id)); err != nil { return err } } } if index > 0 { vctx.trace(index, TraceBind, vctx.rootSig[:], caveatSig[:]) caveatSig = bindForRequest(vctx.rootSig[:], caveatSig) } // TODO perhaps we should actually do this check before doing // all the potentially expensive caveat checks. if !hmac.Equal(caveatSig[:], m.sig[:]) { return fmt.Errorf("signature mismatch after caveat verification") } return nil } func (vctx *verificationContext) findDischarge(id []byte) (dm *Macaroon, index int, err error) { for di, dm := range vctx.discharges { if !bytes.Equal(dm.id, id) { continue } // Don't use a discharge macaroon more than once. // It's important that we do this check here rather than after // verify as it prevents potentially infinite recursion. if vctx.used[di] { return nil, 0, fmt.Errorf("discharge macaroon %q was used more than once", dm.Id()) } vctx.used[di] = true return dm, di, nil } return nil, 0, fmt.Errorf("cannot find discharge macaroon for caveat %x", id) } func (vctx *verificationContext) trace(index int, op TraceOpKind, data1, data2 []byte) { if vctx.traces != nil { vctx.traces[index].Ops = append(vctx.traces[index].Ops, TraceOp{ Kind: op, Data1: data1, Data2: data2, }) } } func (vctx *verificationContext) traceRootKey(index int, rootKey []byte) { if vctx.traces != nil { vctx.traces[index].RootKey = rootKey[:] } } ���������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/export_test.go������������������������������������0000644�0610621�0607500�00000000533�13172163405�025610� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon var ( AddThirdPartyCaveatWithRand = (*Macaroon).addThirdPartyCaveatWithRand ) type MacaroonJSONV2 macaroonJSONV2 // SetVersion sets the version field of m to v; // usually so that we can compare it for deep equality with // another differently unmarshaled macaroon. func (m *Macaroon) SetVersion(v Version) { m.version = v } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/crypto_test.go������������������������������������0000644�0610621�0607500�00000003217�13172163405�025611� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "crypto/rand" "fmt" "golang.org/x/crypto/nacl/secretbox" gc "gopkg.in/check.v1" ) type cryptoSuite struct{} var _ = gc.Suite(&cryptoSuite{}) var testCryptKey = &[hashLen]byte{'k', 'e', 'y'} var testCryptText = &[hashLen]byte{'t', 'e', 'x', 't'} func (*cryptoSuite) TestEncDec(c *gc.C) { b, err := encrypt(testCryptKey, testCryptText, rand.Reader) c.Assert(err, gc.IsNil) t, err := decrypt(testCryptKey, b) c.Assert(err, gc.IsNil) c.Assert(string(t[:]), gc.Equals, string(testCryptText[:])) } func (*cryptoSuite) TestUniqueNonces(c *gc.C) { nonces := make(map[string]struct{}) for i := 0; i < 100; i++ { nonce, err := newNonce(rand.Reader) c.Assert(err, gc.IsNil) nonces[string(nonce[:])] = struct{}{} } c.Assert(nonces, gc.HasLen, 100, gc.Commentf("duplicate nonce detected")) } type ErrorReader struct{} func (*ErrorReader) Read([]byte) (int, error) { return 0, fmt.Errorf("fail") } func (*cryptoSuite) TestBadRandom(c *gc.C) { _, err := newNonce(&ErrorReader{}) c.Assert(err, gc.ErrorMatches, "^cannot generate random bytes:.*") _, err = encrypt(testCryptKey, testCryptText, &ErrorReader{}) c.Assert(err, gc.ErrorMatches, "^cannot generate random bytes:.*") } func (*cryptoSuite) TestBadCiphertext(c *gc.C) { buf := randomBytes(nonceLen + secretbox.Overhead) for i := range buf { _, err := decrypt(testCryptKey, buf[0:i]) c.Assert(err, gc.ErrorMatches, "message too short") } _, err := decrypt(testCryptKey, buf) c.Assert(err, gc.ErrorMatches, "decryption failure") } func randomBytes(n int) []byte { buf := make([]byte, n) if _, err := rand.Reader.Read(buf); err != nil { panic(err) } return buf } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/crypto.go�����������������������������������������0000644�0610621�0607500�00000004124�13172163405�024550� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon import ( "crypto/hmac" "crypto/sha256" "fmt" "hash" "io" "golang.org/x/crypto/nacl/secretbox" ) func keyedHash(key *[hashLen]byte, text []byte) *[hashLen]byte { h := keyedHasher(key) h.Write([]byte(text)) var sum [hashLen]byte hashSum(h, &sum) return &sum } func keyedHasher(key *[hashLen]byte) hash.Hash { return hmac.New(sha256.New, key[:]) } var keyGen = []byte("macaroons-key-generator") // makeKey derives a fixed length key from a variable // length key. The keyGen constant is the same // as that used in libmacaroons. func makeKey(variableKey []byte) *[keyLen]byte { h := hmac.New(sha256.New, keyGen) h.Write(variableKey) var key [keyLen]byte hashSum(h, &key) return &key } // hashSum calls h.Sum to put the sum into // the given destination. It also sanity // checks that the result really is the expected // size. func hashSum(h hash.Hash, dest *[hashLen]byte) { r := h.Sum(dest[:0]) if len(r) != len(dest) { panic("hash size inconsistency") } } const ( keyLen = 32 nonceLen = 24 hashLen = sha256.Size ) func newNonce(r io.Reader) (*[nonceLen]byte, error) { var nonce [nonceLen]byte _, err := r.Read(nonce[:]) if err != nil { return nil, fmt.Errorf("cannot generate random bytes: %v", err) } return &nonce, nil } func encrypt(key *[keyLen]byte, text *[hashLen]byte, r io.Reader) ([]byte, error) { nonce, err := newNonce(r) if err != nil { return nil, err } out := make([]byte, 0, len(nonce)+secretbox.Overhead+len(text)) out = append(out, nonce[:]...) return secretbox.Seal(out, text[:], nonce, key), nil } func decrypt(key *[keyLen]byte, ciphertext []byte) (*[hashLen]byte, error) { if len(ciphertext) < nonceLen+secretbox.Overhead { return nil, fmt.Errorf("message too short") } var nonce [nonceLen]byte copy(nonce[:], ciphertext) ciphertext = ciphertext[nonceLen:] text, ok := secretbox.Open(nil, ciphertext, &nonce, key) if !ok { return nil, fmt.Errorf("decryption failure") } if len(text) != hashLen { return nil, fmt.Errorf("decrypted text is wrong length") } var rtext [hashLen]byte copy(rtext[:], text) return &rtext, nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/bench_test.go�������������������������������������0000644�0610621�0607500�00000005112�13172163405�025344� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package macaroon_test import ( "crypto/rand" "encoding/base64" "testing" "gopkg.in/macaroon.v2-unstable" ) func randomBytes(n int) []byte { b := make([]byte, n) _, err := rand.Read(b) if err != nil { panic(err) } return b } func BenchmarkNew(b *testing.B) { rootKey := randomBytes(24) id := []byte(base64.StdEncoding.EncodeToString(randomBytes(100))) loc := base64.StdEncoding.EncodeToString(randomBytes(40)) b.ResetTimer() for i := b.N - 1; i >= 0; i-- { MustNew(rootKey, id, loc, macaroon.LatestVersion) } } func BenchmarkAddCaveat(b *testing.B) { rootKey := randomBytes(24) id := []byte(base64.StdEncoding.EncodeToString(randomBytes(100))) loc := base64.StdEncoding.EncodeToString(randomBytes(40)) b.ResetTimer() for i := b.N - 1; i >= 0; i-- { b.StopTimer() m := MustNew(rootKey, id, loc, macaroon.LatestVersion) b.StartTimer() m.AddFirstPartyCaveat("some caveat stuff") } } func benchmarkVerify(b *testing.B, mspecs []macaroonSpec) { rootKey, macaroons := makeMacaroons(mspecs) check := func(string) error { return nil } b.ResetTimer() for i := b.N - 1; i >= 0; i-- { err := macaroons[0].Verify(rootKey, check, macaroons[1:]) if err != nil { b.Fatalf("verification failed: %v", err) } } } func BenchmarkVerifyLarge(b *testing.B) { benchmarkVerify(b, multilevelThirdPartyCaveatMacaroons) } func BenchmarkVerifySmall(b *testing.B) { benchmarkVerify(b, []macaroonSpec{{ rootKey: "root-key", id: "root-id", caveats: []caveat{{ condition: "wonderful", }}, }}) } func BenchmarkMarshalJSON(b *testing.B) { rootKey := randomBytes(24) id := []byte(base64.StdEncoding.EncodeToString(randomBytes(100))) loc := base64.StdEncoding.EncodeToString(randomBytes(40)) m := MustNew(rootKey, id, loc, macaroon.LatestVersion) b.ResetTimer() for i := b.N - 1; i >= 0; i-- { _, err := m.MarshalJSON() if err != nil { b.Fatalf("cannot marshal JSON: %v", err) } } } func MustNew(rootKey, id []byte, loc string, vers macaroon.Version) *macaroon.Macaroon { m, err := macaroon.New(rootKey, id, loc, vers) if err != nil { panic(err) } return m } func BenchmarkUnmarshalJSON(b *testing.B) { rootKey := randomBytes(24) id := []byte(base64.StdEncoding.EncodeToString(randomBytes(100))) loc := base64.StdEncoding.EncodeToString(randomBytes(40)) m := MustNew(rootKey, id, loc, macaroon.LatestVersion) data, err := m.MarshalJSON() if err != nil { b.Fatalf("cannot marshal JSON: %v", err) } for i := b.N - 1; i >= 0; i-- { var m macaroon.Macaroon err := m.UnmarshalJSON(data) if err != nil { b.Fatalf("cannot unmarshal JSON: %v", err) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/TODO����������������������������������������������0000644�0610621�0607500�00000000137�13172163405�023371� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������macaroon: - verify that all signature calculations to correspond exactly with libmacaroons. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/README.md�����������������������������������������0000644�0610621�0607500�00000007723�13172163405�024170� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# macaroon -- import "gopkg.in/macaroon.v1" The macaroon package implements macaroons as described in the paper "Macaroons: Cookies with Contextual Caveats for Decentralized Authorization in the Cloud" (http://theory.stanford.edu/~ataly/Papers/macaroons.pdf) See the macaroon bakery packages at http://godoc.org/gopkg.in/macaroon-bakery.v0 for higher level services and operations that use macaroons. ## Usage #### type Caveat ```go type Caveat struct { Id string Location string } ``` #### type Macaroon ```go type Macaroon struct { } ``` Macaroon holds a macaroon. See Fig. 7 of http://theory.stanford.edu/~ataly/Papers/macaroons.pdf for a description of the data contained within. Macaroons are mutable objects - use Clone as appropriate to avoid unwanted mutation. #### func New ```go func New(rootKey []byte, id, loc string) (*Macaroon, error) ``` New returns a new macaroon with the given root key, identifier and location. #### func (*Macaroon) AddFirstPartyCaveat ```go func (m *Macaroon) AddFirstPartyCaveat(caveatId string) error ``` AddFirstPartyCaveat adds a caveat that will be verified by the target service. #### func (*Macaroon) AddThirdPartyCaveat ```go func (m *Macaroon) AddThirdPartyCaveat(rootKey []byte, caveatId string, loc string) error ``` AddThirdPartyCaveat adds a third-party caveat to the macaroon, using the given shared root key, caveat id and location hint. The caveat id should encode the root key in some way, either by encrypting it with a key known to the third party or by holding a reference to it stored in the third party's storage. #### func (*Macaroon) Bind ```go func (m *Macaroon) Bind(sig []byte) ``` Bind prepares the macaroon for being used to discharge the macaroon with the given signature sig. This must be used before it is used in the discharges argument to Verify. #### func (*Macaroon) Caveats ```go func (m *Macaroon) Caveats() []Caveat ``` Caveats returns the macaroon's caveats. This method will probably change, and it's important not to change the returned caveat. #### func (*Macaroon) Clone ```go func (m *Macaroon) Clone() *Macaroon ``` Clone returns a copy of the receiving macaroon. #### func (*Macaroon) Id ```go func (m *Macaroon) Id() string ``` Id returns the id of the macaroon. This can hold arbitrary information. #### func (*Macaroon) Location ```go func (m *Macaroon) Location() string ``` Location returns the macaroon's location hint. This is not verified as part of the macaroon. #### func (*Macaroon) MarshalBinary ```go func (m *Macaroon) MarshalBinary() ([]byte, error) ``` MarshalBinary implements encoding.BinaryMarshaler. #### func (*Macaroon) MarshalJSON ```go func (m *Macaroon) MarshalJSON() ([]byte, error) ``` MarshalJSON implements json.Marshaler. #### func (*Macaroon) Signature ```go func (m *Macaroon) Signature() []byte ``` Signature returns the macaroon's signature. #### func (*Macaroon) UnmarshalBinary ```go func (m *Macaroon) UnmarshalBinary(data []byte) error ``` UnmarshalBinary implements encoding.BinaryUnmarshaler. #### func (*Macaroon) UnmarshalJSON ```go func (m *Macaroon) UnmarshalJSON(jsonData []byte) error ``` UnmarshalJSON implements json.Unmarshaler. #### func (*Macaroon) Verify ```go func (m *Macaroon) Verify(rootKey []byte, check func(caveat string) error, discharges []*Macaroon) error ``` Verify verifies that the receiving macaroon is valid. The root key must be the same that the macaroon was originally minted with. The check function is called to verify each first-party caveat - it should return an error if the condition is not met. The discharge macaroons should be provided in discharges. Verify returns true if the verification succeeds; if returns (false, nil) if the verification fails, and (false, err) if the verification cannot be asserted (but may not be false). TODO(rog) is there a possible DOS attack that can cause this function to infinitely recurse? #### type Verifier ```go type Verifier interface { Verify(m *Macaroon, rootKey []byte) (bool, error) } ``` ���������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon.v2-unstable/LICENSE�������������������������������������������0000644�0610621�0607500�00000002745�13172163405�023715� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright © 2014, Roger Peppe All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of this project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ���������������������������lxd-2.0.11/dist/src/gopkg.in/errgo.v1/��������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163404�020402� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/errgo.v1/export_test.go������������������������������������������������0000644�0610621�0607500�00000000142�13172163404�023306� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Roger Peppe. // See LICENCE file for details. package errgo var Match = match ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/errgo.v1/errors_test.go������������������������������������������������0000644�0610621�0607500�00000016637�13172163404�023321� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Roger Peppe. // See LICENCE file for details. package errgo_test import ( "fmt" "io/ioutil" "runtime" "strings" "testing" gc "launchpad.net/gocheck" "gopkg.in/errgo.v1" ) var ( _ errgo.Wrapper = (*errgo.Err)(nil) _ errgo.Locationer = (*errgo.Err)(nil) _ errgo.Causer = (*errgo.Err)(nil) ) func Test(t *testing.T) { gc.TestingT(t) } type errorsSuite struct{} var _ = gc.Suite(&errorsSuite{}) func (*errorsSuite) TestNew(c *gc.C) { err := errgo.New("foo") //err TestNew checkErr(c, err, nil, "foo", "[{$TestNew$: foo}]", err) } func (*errorsSuite) TestNewf(c *gc.C) { err := errgo.Newf("foo %d", 5) //err TestNewf checkErr(c, err, nil, "foo 5", "[{$TestNewf$: foo 5}]", err) } var someErr = errgo.New("some error") //err varSomeErr func annotate1() error { err := errgo.Notef(someErr, "annotate1") //err annotate1 return err } func annotate2() error { err := annotate1() err = errgo.Notef(err, "annotate2") //err annotate2 return err } func (*errorsSuite) TestNoteUsage(c *gc.C) { err0 := annotate2() err, ok := err0.(errgo.Wrapper) c.Assert(ok, gc.Equals, true) underlying := err.Underlying() checkErr( c, err0, underlying, "annotate2: annotate1: some error", "[{$annotate2$: annotate2} {$annotate1$: annotate1} {$varSomeErr$: some error}]", err0) } func (*errorsSuite) TestMask(c *gc.C) { err0 := errgo.WithCausef(nil, someErr, "foo") //err TestMask#0 err := errgo.Mask(err0) //err TestMask#1 checkErr(c, err, err0, "foo", "[{$TestMask#1$: } {$TestMask#0$: foo}]", err) err = errgo.Mask(nil) c.Assert(err, gc.IsNil) } func (*errorsSuite) TestNotef(c *gc.C) { err0 := errgo.WithCausef(nil, someErr, "foo") //err TestNotef#0 err := errgo.Notef(err0, "bar") //err TestNotef#1 checkErr(c, err, err0, "bar: foo", "[{$TestNotef#1$: bar} {$TestNotef#0$: foo}]", err) err = errgo.Notef(nil, "bar") //err TestNotef#2 checkErr(c, err, nil, "bar", "[{$TestNotef#2$: bar}]", err) } func (*errorsSuite) TestNoteMask(c *gc.C) { err0 := errgo.WithCausef(nil, someErr, "foo") //err TestNoteMask#0 err := errgo.NoteMask(err0, "bar") //err TestNoteMask#1 checkErr(c, err, err0, "bar: foo", "[{$TestNoteMask#1$: bar} {$TestNoteMask#0$: foo}]", err) err = errgo.NoteMask(err0, "bar", errgo.Is(someErr)) //err TestNoteMask#2 checkErr(c, err, err0, "bar: foo", "[{$TestNoteMask#2$: bar} {$TestNoteMask#0$: foo}]", someErr) err = errgo.NoteMask(err0, "") //err TestNoteMask#3 checkErr(c, err, err0, "foo", "[{$TestNoteMask#3$: } {$TestNoteMask#0$: foo}]", err) } func (*errorsSuite) TestMaskFunc(c *gc.C) { err0 := errgo.New("zero") err1 := errgo.New("one") allowVals := func(vals ...error) (r []func(error) bool) { for _, val := range vals { r = append(r, errgo.Is(val)) } return } tests := []struct { err error allow0 []func(error) bool allow1 []func(error) bool cause error }{{ err: err0, allow0: allowVals(err0), cause: err0, }, { err: err1, allow0: allowVals(err0), cause: nil, }, { err: err0, allow1: allowVals(err0), cause: err0, }, { err: err0, allow0: allowVals(err1), allow1: allowVals(err0), cause: err0, }, { err: err0, allow0: allowVals(err0, err1), cause: err0, }, { err: err1, allow0: allowVals(err0, err1), cause: err1, }, { err: err0, allow1: allowVals(err0, err1), cause: err0, }, { err: err1, allow1: allowVals(err0, err1), cause: err1, }} for i, test := range tests { c.Logf("test %d", i) wrap := errgo.MaskFunc(test.allow0...) err := wrap(test.err, test.allow1...) cause := errgo.Cause(err) wantCause := test.cause if wantCause == nil { wantCause = err } c.Check(cause, gc.Equals, wantCause) } } type embed struct { *errgo.Err } func (*errorsSuite) TestCause(c *gc.C) { c.Assert(errgo.Cause(someErr), gc.Equals, someErr) causeErr := errgo.New("cause error") underlyingErr := errgo.New("underlying error") //err TestCause#1 err := errgo.WithCausef(underlyingErr, causeErr, "foo %d", 99) //err TestCause#2 c.Assert(errgo.Cause(err), gc.Equals, causeErr) checkErr(c, err, underlyingErr, "foo 99: underlying error", "[{$TestCause#2$: foo 99} {$TestCause#1$: underlying error}]", causeErr) err = &embed{err.(*errgo.Err)} c.Assert(errgo.Cause(err), gc.Equals, causeErr) } func (*errorsSuite) TestWithCausefNoMessage(c *gc.C) { cause := errgo.New("cause") err := errgo.WithCausef(nil, cause, "") c.Assert(err, gc.ErrorMatches, "cause") c.Assert(errgo.Cause(err), gc.Equals, cause) } func (*errorsSuite) TestWithCausefWithUnderlyingButNoMessage(c *gc.C) { err := errgo.New("something") cause := errgo.New("cause") err = errgo.WithCausef(err, cause, "") c.Assert(err, gc.ErrorMatches, "something") c.Assert(errgo.Cause(err), gc.Equals, cause) } func (*errorsSuite) TestDetails(c *gc.C) { c.Assert(errgo.Details(nil), gc.Equals, "[]") otherErr := fmt.Errorf("other") checkErr(c, otherErr, nil, "other", "[{other}]", otherErr) err0 := &embed{errgo.New("foo").(*errgo.Err)} //err TestStack#0 checkErr(c, err0, nil, "foo", "[{$TestStack#0$: foo}]", err0) err1 := &embed{errgo.Notef(err0, "bar").(*errgo.Err)} //err TestStack#1 checkErr(c, err1, err0, "bar: foo", "[{$TestStack#1$: bar} {$TestStack#0$: foo}]", err1) err2 := errgo.Mask(err1) //err TestStack#2 checkErr(c, err2, err1, "bar: foo", "[{$TestStack#2$: } {$TestStack#1$: bar} {$TestStack#0$: foo}]", err2) } func (*errorsSuite) TestMatch(c *gc.C) { type errTest func(error) bool allow := func(ss ...string) []func(error) bool { fns := make([]func(error) bool, len(ss)) for i, s := range ss { s := s fns[i] = func(err error) bool { return err != nil && err.Error() == s } } return fns } tests := []struct { err error fns []func(error) bool ok bool }{{ err: errgo.New("foo"), fns: allow("foo"), ok: true, }, { err: errgo.New("foo"), fns: allow("bar"), ok: false, }, { err: errgo.New("foo"), fns: allow("bar", "foo"), ok: true, }, { err: errgo.New("foo"), fns: nil, ok: false, }, { err: nil, fns: nil, ok: false, }} for i, test := range tests { c.Logf("test %d", i) c.Assert(errgo.Match(test.err, test.fns...), gc.Equals, test.ok) } } func checkErr(c *gc.C, err, underlying error, msg string, details string, cause error) { c.Assert(err, gc.NotNil) c.Assert(err.Error(), gc.Equals, msg) if err, ok := err.(errgo.Wrapper); ok { c.Assert(err.Underlying(), gc.Equals, underlying) } else { c.Assert(underlying, gc.IsNil) } c.Assert(errgo.Cause(err), gc.Equals, cause) wantDetails := replaceLocations(details) c.Assert(errgo.Details(err), gc.Equals, wantDetails) } func replaceLocations(s string) string { t := "" for { i := strings.Index(s, "$") if i == -1 { break } t += s[0:i] s = s[i+1:] i = strings.Index(s, "$") if i == -1 { panic("no second $") } file, line := location(s[0:i]) t += fmt.Sprintf("%s:%d", file, line) s = s[i+1:] } t += s return t } func location(tag string) (string, int) { line, ok := tagToLine[tag] if !ok { panic(fmt.Errorf("tag %q not found", tag)) } return filename, line } var tagToLine = make(map[string]int) var filename string func init() { data, err := ioutil.ReadFile("errors_test.go") if err != nil { panic(err) } lines := strings.Split(string(data), "\n") for i, line := range lines { if j := strings.Index(line, "//err "); j >= 0 { tagToLine[line[j+len("//err "):]] = i + 1 } } _, filename, _, _ = runtime.Caller(0) } �������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/errgo.v1/errors.go�����������������������������������������������������0000644�0610621�0607500�00000025037�13172163404�022254� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Roger Peppe. // See LICENCE file for details. // The errgo package provides a way to create // and diagnose errors. It is compatible with // the usual Go error idioms but adds a way to wrap errors // so that they record source location information // while retaining a consistent way for code to // inspect errors to find out particular problems. // package errgo import ( "bytes" "fmt" "log" "runtime" ) const debug = false // Err holds a description of an error along with information about // where the error was created. // // It may be embedded in custom error types to add // extra information that this errors package can // understand. type Err struct { // Message_ holds the text of the error message. It may be empty // if Underlying is set. Message_ string // Cause_ holds the cause of the error as returned // by the Cause method. Cause_ error // Underlying holds the underlying error, if any. Underlying_ error // File and Line identify the source code location where the error was // created. File string Line int } // Location implements Locationer. func (e *Err) Location() (file string, line int) { return e.File, e.Line } // Underlying returns the underlying error if any. func (e *Err) Underlying() error { return e.Underlying_ } // Cause implements Causer. func (e *Err) Cause() error { return e.Cause_ } // Message returns the top level error message. func (e *Err) Message() string { return e.Message_ } // Error implements error.Error. func (e *Err) Error() string { switch { case e.Message_ == "" && e.Underlying_ == nil: return "<no error>" case e.Message_ == "": return e.Underlying_.Error() case e.Underlying_ == nil: return e.Message_ } return fmt.Sprintf("%s: %v", e.Message_, e.Underlying_) } // GoString returns the details of the receiving error // message, so that printing an error with %#v will // produce useful information. func (e *Err) GoString() string { return Details(e) } // Causer is the type of an error that may provide // an error cause for error diagnosis. Cause may return // nil if there is no cause (for example because the // cause has been masked). type Causer interface { Cause() error } // Wrapper is the type of an error that wraps another error. It is // exposed so that external types may implement it, but should in // general not be used otherwise. type Wrapper interface { // Message returns the top level error message, // not including the message from the underlying // error. Message() string // Underlying returns the underlying error, or nil // if there is none. Underlying() error } // Locationer can be implemented by any error type // that wants to expose the source location of an error. type Locationer interface { // Location returns the name of the file and the line // number associated with an error. Location() (file string, line int) } // Details returns information about the stack of // underlying errors wrapped by err, in the format: // // [{filename:99: error one} {otherfile:55: cause of error one}] // // The details are found by type-asserting the error to // the Locationer, Causer and Wrapper interfaces. // Details of the underlying stack are found by // recursively calling Underlying when the // underlying error implements Wrapper. func Details(err error) string { if err == nil { return "[]" } var s []byte s = append(s, '[') for { s = append(s, '{') if err, ok := err.(Locationer); ok { file, line := err.Location() if file != "" { s = append(s, fmt.Sprintf("%s:%d", file, line)...) s = append(s, ": "...) } } if cerr, ok := err.(Wrapper); ok { s = append(s, cerr.Message()...) err = cerr.Underlying() } else { s = append(s, err.Error()...) err = nil } if debug { if err, ok := err.(Causer); ok { if cause := err.Cause(); cause != nil { s = append(s, fmt.Sprintf("=%T", cause)...) s = append(s, Details(cause)...) } } } s = append(s, '}') if err == nil { break } s = append(s, ' ') } s = append(s, ']') return string(s) } // Locate records the source location of the error by setting // e.Location, at callDepth stack frames above the call. func (e *Err) SetLocation(callDepth int) { _, file, line, _ := runtime.Caller(callDepth + 1) e.File, e.Line = file, line } func setLocation(err error, callDepth int) { if e, _ := err.(*Err); e != nil { e.SetLocation(callDepth + 1) } } // New returns a new error with the given error message and no cause. It // is a drop-in replacement for errors.New from the standard library. func New(s string) error { err := &Err{Message_: s} err.SetLocation(1) return err } // Newf returns a new error with the given printf-formatted error // message and no cause. func Newf(f string, a ...interface{}) error { err := &Err{Message_: fmt.Sprintf(f, a...)} err.SetLocation(1) return err } // match returns whether any of the given // functions returns true when called with err as an // argument. func match(err error, pass ...func(error) bool) bool { for _, f := range pass { if f(err) { return true } } return false } // Is returns a function that returns whether the // an error is equal to the given error. // It is intended to be used as a "pass" argument // to Mask and friends; for example: // // return errgo.Mask(err, errgo.Is(http.ErrNoCookie)) // // would return an error with an http.ErrNoCookie cause // only if that was err's diagnosis; otherwise the diagnosis // would be itself. func Is(err error) func(error) bool { return func(err1 error) bool { return err == err1 } } // Any returns true. It can be used as an argument to Mask // to allow any diagnosis to pass through to the wrapped // error. func Any(error) bool { return true } // NoteMask returns an Err that has the given underlying error, // with the given message added as context, and allowing // the cause of the underlying error to pass through into // the result if allowed by the specific pass functions // (see Mask for an explanation of the pass parameter). func NoteMask(underlying error, msg string, pass ...func(error) bool) error { err := noteMask(underlying, msg, pass...) setLocation(err, 1) return err } // noteMask is exactly like NoteMask except it doesn't set the location // of the returned error, so that we can avoid setting it twice // when it's used in other functions. func noteMask(underlying error, msg string, pass ...func(error) bool) error { newErr := &Err{ Underlying_: underlying, Message_: msg, } if len(pass) > 0 { if cause := Cause(underlying); match(cause, pass...) { newErr.Cause_ = cause } } if debug { if newd, oldd := newErr.Cause_, Cause(underlying); newd != oldd { log.Printf("Mask cause %[1]T(%[1]v)->%[2]T(%[2]v)", oldd, newd) log.Printf("call stack: %s", callers(0, 20)) log.Printf("len(allow) == %d", len(pass)) log.Printf("old error %#v", underlying) log.Printf("new error %#v", newErr) } } newErr.SetLocation(1) return newErr } // Mask returns an Err that wraps the given underyling error. The error // message is unchanged, but the error location records the caller of // Mask. // // If err is nil, Mask returns nil. // // By default Mask conceals the cause of the wrapped error, but if // pass(Cause(err)) returns true for any of the provided pass functions, // the cause of the returned error will be Cause(err). // // For example, the following code will return an error whose cause is // the error from the os.Open call when (and only when) the file does // not exist. // // f, err := os.Open("non-existent-file") // if err != nil { // return errgo.Mask(err, os.IsNotExist) // } // // In order to add context to returned errors, it // is conventional to call Mask when returning any // error received from elsewhere. // func Mask(underlying error, pass ...func(error) bool) error { if underlying == nil { return nil } err := noteMask(underlying, "", pass...) setLocation(err, 1) return err } // Notef returns an Error that wraps the given underlying // error and adds the given formatted context message. // The returned error has no cause (use NoteMask // or WithCausef to add a message while retaining a cause). func Notef(underlying error, f string, a ...interface{}) error { err := noteMask(underlying, fmt.Sprintf(f, a...)) setLocation(err, 1) return err } // MaskFunc returns an equivalent of Mask that always allows the // specified causes in addition to any causes specified when the // returned function is called. // // It is defined for convenience, for example when all calls to Mask in // a given package wish to allow the same set of causes to be returned. func MaskFunc(allow ...func(error) bool) func(error, ...func(error) bool) error { return func(err error, allow1 ...func(error) bool) error { var allowEither []func(error) bool if len(allow1) > 0 { // This is more efficient than using a function literal, // because the compiler knows that it doesn't escape. allowEither = make([]func(error) bool, len(allow)+len(allow1)) copy(allowEither, allow) copy(allowEither[len(allow):], allow1) } else { allowEither = allow } err = Mask(err, allowEither...) setLocation(err, 1) return err } } // WithCausef returns a new Error that wraps the given // (possibly nil) underlying error and associates it with // the given cause. The given formatted message context // will also be added. If underlying is nil and f is empty and has no arguments, // the message will be the same as the cause. func WithCausef(underlying, cause error, f string, a ...interface{}) error { var msg string if underlying == nil && f == "" && len(a) == 0 && cause != nil { msg = cause.Error() } else { msg = fmt.Sprintf(f, a...) } err := &Err{ Underlying_: underlying, Cause_: cause, Message_: msg, } err.SetLocation(1) return err } // Cause returns the cause of the given error. If err does not // implement Causer or its Cause method returns nil, it returns err itself. // // Cause is the usual way to diagnose errors that may have // been wrapped by Mask or NoteMask. func Cause(err error) error { var diag error if err, ok := err.(Causer); ok { diag = err.Cause() } if diag != nil { return diag } return err } // callers returns the stack trace of the goroutine that called it, // starting n entries above the caller of callers, as a space-separated list // of filename:line-number pairs with no new lines. func callers(n, max int) []byte { var b bytes.Buffer prev := false for i := 0; i < max; i++ { _, file, line, ok := runtime.Caller(n + 1) if !ok { return b.Bytes() } if prev { fmt.Fprintf(&b, " ") } fmt.Fprintf(&b, "%s:%d", file, line) n++ prev = true } return b.Bytes() } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/errgo.v1/README.md�����������������������������������������������������0000644�0610621�0607500�00000015133�13172163404�021664� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# errgo -- import "gopkg.in/errgo.v1" The errgo package provides a way to create and diagnose errors. It is compatible with the usual Go error idioms but adds a way to wrap errors so that they record source location information while retaining a consistent way for code to inspect errors to find out particular problems. ## Usage #### func Any ```go func Any(error) bool ``` Any returns true. It can be used as an argument to Mask to allow any diagnosis to pass through to the wrapped error. #### func Cause ```go func Cause(err error) error ``` Cause returns the cause of the given error. If err does not implement Causer or its Cause method returns nil, it returns err itself. Cause is the usual way to diagnose errors that may have been wrapped by Mask or NoteMask. #### func Details ```go func Details(err error) string ``` Details returns information about the stack of underlying errors wrapped by err, in the format: [{filename:99: error one} {otherfile:55: cause of error one}] The details are found by type-asserting the error to the Locationer, Causer and Wrapper interfaces. Details of the underlying stack are found by recursively calling Underlying when the underlying error implements Wrapper. #### func Is ```go func Is(err error) func(error) bool ``` Is returns a function that returns whether the an error is equal to the given error. It is intended to be used as a "pass" argument to Mask and friends; for example: return errgo.Mask(err, errgo.Is(http.ErrNoCookie)) would return an error with an http.ErrNoCookie cause only if that was err's diagnosis; otherwise the diagnosis would be itself. #### func Mask ```go func Mask(underlying error, pass ...func(error) bool) error ``` Mask returns an Err that wraps the given underyling error. The error message is unchanged, but the error location records the caller of Mask. If err is nil, Mask returns nil. By default Mask conceals the cause of the wrapped error, but if pass(Cause(err)) returns true for any of the provided pass functions, the cause of the returned error will be Cause(err). For example, the following code will return an error whose cause is the error from the os.Open call when (and only when) the file does not exist. f, err := os.Open("non-existent-file") if err != nil { return errgo.Mask(err, os.IsNotExist) } In order to add context to returned errors, it is conventional to call Mask when returning any error received from elsewhere. #### func MaskFunc ```go func MaskFunc(allow ...func(error) bool) func(error, ...func(error) bool) error ``` MaskFunc returns an equivalent of Mask that always allows the specified causes in addition to any causes specified when the returned function is called. It is defined for convenience, for example when all calls to Mask in a given package wish to allow the same set of causes to be returned. #### func New ```go func New(s string) error ``` New returns a new error with the given error message and no cause. It is a drop-in replacement for errors.New from the standard library. #### func Newf ```go func Newf(f string, a ...interface{}) error ``` Newf returns a new error with the given printf-formatted error message and no cause. #### func NoteMask ```go func NoteMask(underlying error, msg string, pass ...func(error) bool) error ``` NoteMask returns an Err that has the given underlying error, with the given message added as context, and allowing the cause of the underlying error to pass through into the result if allowed by the specific pass functions (see Mask for an explanation of the pass parameter). #### func Notef ```go func Notef(underlying error, f string, a ...interface{}) error ``` Notef returns an Error that wraps the given underlying error and adds the given formatted context message. The returned error has no cause (use NoteMask or WithCausef to add a message while retaining a cause). #### func WithCausef ```go func WithCausef(underlying, cause error, f string, a ...interface{}) error ``` WithCausef returns a new Error that wraps the given (possibly nil) underlying error and associates it with the given cause. The given formatted message context will also be added. #### type Causer ```go type Causer interface { Cause() error } ``` Causer is the type of an error that may provide an error cause for error diagnosis. Cause may return nil if there is no cause (for example because the cause has been masked). #### type Err ```go type Err struct { // Message_ holds the text of the error message. It may be empty // if Underlying is set. Message_ string // Cause_ holds the cause of the error as returned // by the Cause method. Cause_ error // Underlying holds the underlying error, if any. Underlying_ error // File and Line identify the source code location where the error was // created. File string Line int } ``` Err holds a description of an error along with information about where the error was created. It may be embedded in custom error types to add extra information that this errors package can understand. #### func (*Err) Cause ```go func (e *Err) Cause() error ``` Cause implements Causer. #### func (*Err) Error ```go func (e *Err) Error() string ``` Error implements error.Error. #### func (*Err) GoString ```go func (e *Err) GoString() string ``` GoString returns the details of the receiving error message, so that printing an error with %#v will produce useful information. #### func (*Err) Location ```go func (e *Err) Location() (file string, line int) ``` Location implements Locationer. #### func (*Err) Message ```go func (e *Err) Message() string ``` Message returns the top level error message. #### func (*Err) SetLocation ```go func (e *Err) SetLocation(callDepth int) ``` Locate records the source location of the error by setting e.Location, at callDepth stack frames above the call. #### func (*Err) Underlying ```go func (e *Err) Underlying() error ``` Underlying returns the underlying error if any. #### type Locationer ```go type Locationer interface { // Location returns the name of the file and the line // number associated with an error. Location() (file string, line int) } ``` Locationer can be implemented by any error type that wants to expose the source location of an error. #### type Wrapper ```go type Wrapper interface { // Message returns the top level error message, // not including the message from the underlying // error. Message() string // Underlying returns the underlying error, or nil // if there is none. Underlying() error } ``` Wrapper is the type of an error that wraps another error. It is exposed so that external types may implement it, but should in general not be used otherwise. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/errgo.v1/LICENSE�������������������������������������������������������0000644�0610621�0607500�00000002745�13172163404�021417� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright © 2013, Roger Peppe All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of this project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ���������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/�������������������������������������������0000755�0610621�0607500�00000000000�13172163311�024147� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/internal/����������������������������������0000755�0610621�0607500�00000000000�13172163311�025763� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/internal/httputil/�������������������������0000755�0610621�0607500�00000000000�13172163311�027640� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/internal/httputil/relativeurl_test.go������0000644�0610621�0607500�00000005705�13172163311�033573� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. // Note: this code was copied from github.com/juju/utils. package httputil_test import ( "fmt" "net/url" "testing" qt "github.com/frankban/quicktest" "gopkg.in/macaroon-bakery.v2-unstable/internal/httputil" ) var relativeURLTests = []struct { base string target string expect string expectError string }{{ expectError: "non-absolute base URL", }, { base: "/foo", expectError: "non-absolute target URL", }, { base: "foo", expectError: "non-absolute base URL", }, { base: "/foo", target: "foo", expectError: "non-absolute target URL", }, { base: "/foo", target: "/bar", expect: "bar", }, { base: "/foo/", target: "/bar", expect: "../bar", }, { base: "/bar", target: "/foo/", expect: "foo/", }, { base: "/foo/", target: "/bar/", expect: "../bar/", }, { base: "/foo/bar", target: "/bar/", expect: "../bar/", }, { base: "/foo/bar/", target: "/bar/", expect: "../../bar/", }, { base: "/foo/bar/baz", target: "/foo/targ", expect: "../targ", }, { base: "/foo/bar/baz/frob", target: "/foo/bar/one/two/", expect: "../one/two/", }, { base: "/foo/bar/baz/", target: "/foo/targ", expect: "../../targ", }, { base: "/foo/bar/baz/frob/", target: "/foo/bar/one/two/", expect: "../../one/two/", }, { base: "/foo/bar", target: "/foot/bar", expect: "../foot/bar", }, { base: "/foo/bar/baz/frob", target: "/foo/bar", expect: "../../bar", }, { base: "/foo/bar/baz/frob/", target: "/foo/bar", expect: "../../../bar", }, { base: "/foo/bar/baz/frob/", target: "/foo/bar/", expect: "../../", }, { base: "/foo/bar/baz", target: "/foo/bar/other", expect: "other", }, { base: "/foo/bar/", target: "/foo/bar/", expect: ".", }, { base: "/foo/bar", target: "/foo/bar", expect: "bar", }, { base: "/foo/bar/", target: "/foo/bar/", expect: ".", }, { base: "/foo/bar", target: "/foo/", expect: ".", }, { base: "/foo", target: "/", expect: ".", }, { base: "/foo/", target: "/", expect: "../", }, { base: "/foo/bar", target: "/", expect: "../", }, { base: "/foo/bar/", target: "/", expect: "../../", }} func TestRelativeURL(t *testing.T) { c := qt.New(t) for i, test := range relativeURLTests { t.Logf("test %d: %q %q", i, test.base, test.target) // Sanity check the test itself. if test.expectError == "" { baseURL := &url.URL{Path: test.base} expectURL := &url.URL{Path: test.expect} targetURL := baseURL.ResolveReference(expectURL) c.Check(targetURL.Path, qt.Equals, test.target, fmt.Sprintf("resolve reference failure (%q + %q != %q)", test.base, test.expect, test.target)) } result, err := httputil.RelativeURLPath(test.base, test.target) if test.expectError != "" { c.Assert(err, qt.ErrorMatches, test.expectError) c.Assert(result, qt.Equals, "") } else { c.Assert(err, qt.IsNil) c.Check(result, qt.Equals, test.expect) } } } �����������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/internal/httputil/relativeurl.go�����������0000644�0610621�0607500�00000003761�13172163311�032534� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. // Note: this code was copied from github.com/juju/utils. // Package httputil holds utility functions related to net/http. package httputil import ( "errors" "strings" ) // RelativeURLPath returns a relative URL path that is lexically // equivalent to targpath when interpreted by url.URL.ResolveReference. // On success, the returned path will always be non-empty and relative // to basePath, even if basePath and targPath share no elements. // // It is assumed that both basePath and targPath are normalized // (have no . or .. elements). // // An error is returned if basePath or targPath are not absolute paths. func RelativeURLPath(basePath, targPath string) (string, error) { if !strings.HasPrefix(basePath, "/") { return "", errors.New("non-absolute base URL") } if !strings.HasPrefix(targPath, "/") { return "", errors.New("non-absolute target URL") } baseParts := strings.Split(basePath, "/") targParts := strings.Split(targPath, "/") // For the purposes of dotdot, the last element of // the paths are irrelevant. We save the last part // of the target path for later. lastElem := targParts[len(targParts)-1] baseParts = baseParts[0 : len(baseParts)-1] targParts = targParts[0 : len(targParts)-1] // Find the common prefix between the two paths: var i int for ; i < len(baseParts); i++ { if i >= len(targParts) || baseParts[i] != targParts[i] { break } } dotdotCount := len(baseParts) - i targOnly := targParts[i:] result := make([]string, 0, dotdotCount+len(targOnly)+1) for i := 0; i < dotdotCount; i++ { result = append(result, "..") } result = append(result, targOnly...) result = append(result, lastElem) final := strings.Join(result, "/") if final == "" { // If the final result is empty, the last element must // have been empty, so the target was slash terminated // and there were no previous elements, so "." // is appropriate. final = "." } return final, nil } ���������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/��������������������������������0000755�0610621�0607500�00000000000�13172163311�026324� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/visitor_test.go�����������������0000644�0610621�0607500�00000003753�13172163311�031421� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery_test import ( "fmt" "net/http" "net/http/httptest" "net/url" jujutesting "github.com/juju/testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) type InteractorSuite struct { jujutesting.LoggingSuite } var _ = gc.Suite(&InteractorSuite{}) func (*InteractorSuite) TestLegacyGetInteractionMethodsGetFailure(c *gc.C) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusTeapot) w.Write([]byte("failure")) })) defer srv.Close() methods := httpbakery.LegacyGetInteractionMethods(testContext, http.DefaultClient, mustParseURL(srv.URL)) // On error, it falls back to just the single default interactive method. c.Assert(methods, jc.DeepEquals, map[string]*url.URL{ "interactive": mustParseURL(srv.URL), }) } func (*InteractorSuite) TestLegacyGetInteractionMethodsSuccess(c *gc.C) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, `{"method": "http://somewhere/something"}`) })) defer srv.Close() methods := httpbakery.LegacyGetInteractionMethods(testContext, http.DefaultClient, mustParseURL(srv.URL)) c.Assert(methods, jc.DeepEquals, map[string]*url.URL{ "interactive": mustParseURL(srv.URL), "method": mustParseURL("http://somewhere/something"), }) } func (*InteractorSuite) TestLegacyGetInteractionMethodsInvalidURL(c *gc.C) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, `{"method": ":::"}`) })) defer srv.Close() methods := httpbakery.LegacyGetInteractionMethods(testContext, http.DefaultClient, mustParseURL(srv.URL)) // On error, it falls back to just the single default interactive method. c.Assert(methods, jc.DeepEquals, map[string]*url.URL{ "interactive": mustParseURL(srv.URL), }) } ���������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/visitor.go����������������������0000644�0610621�0607500�00000004154�13172163311�030356� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "net/http" "net/url" "github.com/juju/httprequest" "golang.org/x/net/context" "gopkg.in/errgo.v1" ) // TODO(rog) rename this file. // legacyGetInteractionMethods queries a URL as found in an // ErrInteractionRequired VisitURL field to find available interaction // methods. // // It does this by sending a GET request to the URL with the Accept // header set to "application/json" and parsing the resulting // response as a map[string]string. // // It uses the given Doer to execute the HTTP GET request. func legacyGetInteractionMethods(ctx context.Context, client httprequest.Doer, u *url.URL) map[string]*url.URL { methodURLs, err := legacyGetInteractionMethods1(ctx, client, u) if err != nil { // When a discharger doesn't support retrieving interaction methods, // we expect to get an error, because it's probably returning an HTML // page not JSON. logger.Debugf("ignoring error: cannot get interaction methods: %v; %s", err, errgo.Details(err)) methodURLs = make(map[string]*url.URL) } if methodURLs["interactive"] == nil { // There's no "interactive" method returned, but we know // the server does actually support it, because all dischargers // are required to, so fill it in with the original URL. methodURLs["interactive"] = u } return methodURLs } func legacyGetInteractionMethods1(ctx context.Context, client httprequest.Doer, u *url.URL) (map[string]*url.URL, error) { httpReqClient := &httprequest.Client{ Doer: client, } req, err := http.NewRequest("GET", u.String(), nil) if err != nil { return nil, errgo.Notef(err, "cannot create request") } req.Header.Set("Accept", "application/json") var methodURLStrs map[string]string if err := httpReqClient.Do(ctx, req, &methodURLStrs); err != nil { return nil, errgo.Mask(err) } // Make all the URLs relative to the request URL. methodURLs := make(map[string]*url.URL) for m, urlStr := range methodURLStrs { relURL, err := url.Parse(urlStr) if err != nil { return nil, errgo.Notef(err, "invalid URL for interaction method %q", m) } methodURLs[m] = u.ResolveReference(relURL) } return methodURLs, nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/request.go����������������������0000644�0610621�0607500�00000007215�13172163311�030350� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "io" "io/ioutil" "net/http" "reflect" "sync" "sync/atomic" errgo "gopkg.in/errgo.v1" ) // newRetrableRequest wraps an HTTP request so that it can // be retried without incurring race conditions and reports // whether the request can be retried. // // Because http.NewRequest often wraps its request bodies // with ioutil.NopCloser, which hides whether the body is // seekable, we extract the seeker from inside the nopCloser if // possible. // // We also work around Go issue 12796 by preventing concurrent // reads to the underlying reader after the request body has // been closed by Client.Do. // // The returned value should be closed after use. func newRetryableRequest(req *http.Request) (*retryableRequest, bool) { if req.Body == nil { return &retryableRequest{ ref: 1, req: req, }, true } body := seekerFromBody(req.Body) if body == nil { return nil, false } rreq := &retryableRequest{ ref: 1, req: req, origBody: req.Body, body: body, } req.Body = nil return rreq, true } type retryableRequest struct { ref int32 origBody io.ReadCloser body io.ReadSeeker req *http.Request } // try should be called just before invoking http.Client.Do. func (req *retryableRequest) try() error { if req.body == nil { return nil } if req.req.Body != nil { // Close the old readStopper. req.req.Body.Close() if _, err := req.body.Seek(0, 0); err != nil { return errgo.Notef(err, "cannot seek to start of request body") } } atomic.AddInt32(&req.ref, 1) // Replace the body with a new readStopper so that // the old request cannot interfere with the new request's reader. req.req.Body = &readStopper{ req: req, r: req.body, } return nil } // close closes the request. It closes the underlying reader // when all references have gone. func (req *retryableRequest) close() { if atomic.AddInt32(&req.ref, -1) == 0 { // We've closed it for the last time, so actually close // the original body. if req.origBody != nil { req.origBody.Close() } } } // readStopper works around an issue with the net/http // package (see http://golang.org/issue/12796). // Because the first HTTP request might not have finished // reading from its body when it returns, we need to // ensure that the second request does not race on Read, // so this type implements a Reader that prevents all Read // calls to the underlying Reader after Close has been called. type readStopper struct { req *retryableRequest mu sync.Mutex r io.ReadSeeker } func (r *readStopper) Read(buf []byte) (int, error) { r.mu.Lock() defer r.mu.Unlock() if r.r == nil { // Note: we have to use io.EOF here because otherwise // another connection can (in rare circumstances) be // polluted by the error returned here. Although this // means the file may appear truncated to the server, // that shouldn't matter because the body will only // be closed after the server has replied. return 0, io.EOF } return r.r.Read(buf) } func (r *readStopper) Close() error { r.mu.Lock() closed := r.r == nil r.r = nil r.mu.Unlock() if !closed { r.req.close() } return nil } var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil)) // seekerFromBody tries to obtain a seekable reader // from the given request body. func seekerFromBody(r io.ReadCloser) io.ReadSeeker { if r, ok := r.(io.ReadSeeker); ok { return r } rv := reflect.ValueOf(r) if rv.Type() != nopCloserType { return nil } // It's a value created by nopCloser. Extract the // underlying Reader. Note that this works // because the ioutil.nopCloser type exports // its Reader field. rs, _ := rv.Field(0).Interface().(io.ReadSeeker) return rs } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/package_test.go�����������������0000644�0610621�0607500�00000000174�13172163311�031307� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery_test import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/oven_test.go��������������������0000644�0610621�0607500�00000013261�13172163311�030664� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery_test import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "time" "github.com/juju/httprequest" jujutesting "github.com/juju/testing" jc "github.com/juju/testing/checkers" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/bakerytest" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) type OvenSuite struct { jujutesting.LoggingSuite } var _ = gc.Suite(&OvenSuite{}) func (*OvenSuite) TestOvenWithAuthnMacaroon(c *gc.C) { discharger := newTestIdentityServer() defer discharger.Close() key, err := bakery.GenerateKey() if err != nil { panic(err) } b := bakery.New(bakery.BakeryParams{ Location: "here", Locator: discharger, Key: key, Checker: httpbakery.NewChecker(), IdentityClient: discharger, }) expectedExpiry := time.Hour oven := &httpbakery.Oven{ Oven: b.Oven, AuthnExpiry: expectedExpiry, AuthzExpiry: 5 * time.Minute, } errorCalled := 0 handler := httpReqServer.HandleErrors(func(p httprequest.Params) error { if _, err := b.Checker.Auth(httpbakery.RequestMacaroons(p.Request)...).Allow(p.Context, bakery.LoginOp); err != nil { errorCalled++ return oven.Error(testContext, p.Request, err) } fmt.Fprintf(p.Response, "done") return nil }) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { handler(w, req, nil) })) defer ts.Close() req, err := http.NewRequest("GET", ts.URL, nil) c.Assert(err, gc.Equals, nil) client := httpbakery.NewClient() t0 := time.Now() resp, err := client.Do(req) c.Assert(err, gc.Equals, nil) c.Check(errorCalled, gc.Equals, 1) body, _ := ioutil.ReadAll(resp.Body) c.Assert(resp.StatusCode, gc.Equals, http.StatusOK, gc.Commentf("body: %q", body)) mss := httpbakery.MacaroonsForURL(client.Jar, mustParseURL(discharger.Location())) c.Assert(mss, gc.HasLen, 1) t, ok := checkers.MacaroonsExpiryTime(b.Checker.Namespace(), mss[0]) c.Assert(ok, gc.Equals, true) want := t0.Add(expectedExpiry) c.Assert(t, jc.TimeBetween(want, want.Add(time.Second))) } func (*OvenSuite) TestOvenWithAuthzMacaroon(c *gc.C) { discharger := newTestIdentityServer() defer discharger.Close() discharger2 := bakerytest.NewDischarger(nil) defer discharger2.Close() locator := httpbakery.NewThirdPartyLocator(nil, nil) locator.AllowInsecure() key, err := bakery.GenerateKey() if err != nil { panic(err) } b := bakery.New(bakery.BakeryParams{ Location: "here", Locator: locator, Key: key, Checker: httpbakery.NewChecker(), IdentityClient: discharger, Authorizer: bakery.AuthorizerFunc(func(ctx context.Context, id bakery.Identity, op bakery.Op) (bool, []checkers.Caveat, error) { return true, []checkers.Caveat{{ Location: discharger2.Location(), Condition: "something", }}, nil }), }) expectedAuthnExpiry := 5 * time.Minute expectedAuthzExpiry := time.Hour oven := &httpbakery.Oven{ Oven: b.Oven, AuthnExpiry: expectedAuthnExpiry, AuthzExpiry: expectedAuthzExpiry, } errorCalled := 0 handler := httpReqServer.HandleErrors(func(p httprequest.Params) error { if _, err := b.Checker.Auth(httpbakery.RequestMacaroons(p.Request)...).Allow(p.Context, bakery.Op{"something", "read"}); err != nil { errorCalled++ return oven.Error(testContext, p.Request, err) } fmt.Fprintf(p.Response, "done") return nil }) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { handler(w, req, nil) })) defer ts.Close() req, err := http.NewRequest("GET", ts.URL, nil) c.Assert(err, gc.Equals, nil) client := httpbakery.NewClient() t0 := time.Now() resp, err := client.Do(req) c.Assert(err, gc.Equals, nil) c.Check(errorCalled, gc.Equals, 2) body, _ := ioutil.ReadAll(resp.Body) c.Assert(resp.StatusCode, gc.Equals, http.StatusOK, gc.Commentf("body: %q", body)) mss := httpbakery.MacaroonsForURL(client.Jar, mustParseURL(discharger.Location())) c.Assert(mss, gc.HasLen, 2) // The cookie jar returns otherwise-similar cookies in the order // they were added, so the authn macaroon will be first. t, ok := checkers.MacaroonsExpiryTime(b.Checker.Namespace(), mss[0]) c.Assert(ok, gc.Equals, true) want := t0.Add(expectedAuthnExpiry) c.Assert(t, jc.TimeBetween(want, want.Add(time.Second))) t, ok = checkers.MacaroonsExpiryTime(b.Checker.Namespace(), mss[1]) c.Assert(ok, gc.Equals, true) want = t0.Add(expectedAuthzExpiry) c.Assert(t, jc.TimeBetween(want, want.Add(time.Second))) } type testIdentityServer struct { *bakerytest.Discharger } func newTestIdentityServer() *testIdentityServer { checker := func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if string(cav.Condition) != "is-authenticated-user" { return nil, errgo.New("unexpected caveat") } return []checkers.Caveat{ checkers.DeclaredCaveat("username", "bob"), }, nil } discharger := bakerytest.NewDischarger(nil) discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(checker) return &testIdentityServer{ Discharger: discharger, } } func (s *testIdentityServer) IdentityFromContext(ctx context.Context) (bakery.Identity, []checkers.Caveat, error) { return nil, []checkers.Caveat{{ Location: s.Location(), Condition: "is-authenticated-user", }}, nil } func (s *testIdentityServer) DeclaredIdentity(ctx context.Context, declared map[string]string) (bakery.Identity, error) { username, ok := declared["username"] if !ok { return nil, errgo.New("no username declared") } return bakery.SimpleIdentity(username), nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/oven.go�������������������������0000644�0610621�0607500�00000005354�13172163311�027631� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "net/http" "time" "golang.org/x/net/context" errgo "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) // Oven is like bakery.Oven except it provides a method for // translating errors returned by bakery.AuthChecker into // errors suitable for passing to WriteError. type Oven struct { // Oven holds the bakery Oven used to create // new macaroons to put in discharge-required errors. *bakery.Oven // AuthnExpiry holds the expiry time of macaroons that // are created for authentication. As these are generally // applicable to all endpoints in an API, this is usually // longer than AuthzExpiry. If this is zero, DefaultAuthnExpiry // will be used. AuthnExpiry time.Duration // AuthzExpiry holds the expiry time of macaroons that are // created for authorization. As these are generally applicable // to specific operations, they generally don't need // a long lifespan, so this is usually shorter than AuthnExpiry. // If this is zero, DefaultAuthzExpiry will be used. AuthzExpiry time.Duration } // Default expiry times for macaroons created by Oven.Error. const ( DefaultAuthnExpiry = 7 * 24 * time.Hour DefaultAuthzExpiry = 5 * time.Minute ) // Error processes an error as returned from bakery.AuthChecker // into an error suitable for returning as a response to req // with WriteError. // // Specifically, it translates bakery.ErrPermissionDenied into // ErrPermissionDenied and bakery.DischargeRequiredError // into an Error with an ErrDischargeRequired code, using // oven.Oven to mint the macaroon in it. func (oven *Oven) Error(ctx context.Context, req *http.Request, err error) error { cause := errgo.Cause(err) if cause == bakery.ErrPermissionDenied { return errgo.WithCausef(err, ErrPermissionDenied, "") } derr, ok := cause.(*bakery.DischargeRequiredError) if !ok { return errgo.Mask(err) } // TODO it's possible to have more than two levels here - think // about some naming scheme for the cookies that allows that. expiryDuration := oven.AuthzExpiry if expiryDuration == 0 { expiryDuration = DefaultAuthzExpiry } cookieName := "authz" if len(derr.Ops) == 1 && derr.Ops[0] == bakery.LoginOp { // Authentication macaroons are a bit different, so use // a different cookie name so both can be presented together. cookieName = "authn" expiryDuration = oven.AuthnExpiry if expiryDuration == 0 { expiryDuration = DefaultAuthnExpiry } } m, err := oven.Oven.NewMacaroon(ctx, RequestVersion(req), time.Now().Add(expiryDuration), derr.Caveats, derr.Ops...) if err != nil { return errgo.Notef(err, "cannot mint new macaroon") } return NewDischargeRequiredError(DischargeRequiredErrorParams{ Macaroon: m, CookieNameSuffix: cookieName, Request: req, }) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/keyring_test.go�����������������0000644�0610621�0607500�00000014550�13172163311�031367� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery_test import ( "fmt" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "sync" "github.com/juju/httprequest" jujutesting "github.com/juju/testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakerytest" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) type KeyringSuite struct { jujutesting.LoggingSuite } var _ = gc.Suite(&KeyringSuite{}) func (s *KeyringSuite) TestCachePrepopulated(c *gc.C) { cache := bakery.NewThirdPartyStore() key, err := bakery.GenerateKey() c.Assert(err, gc.IsNil) expectInfo := bakery.ThirdPartyInfo{ PublicKey: key.Public, Version: bakery.LatestVersion, } cache.AddInfo("https://0.1.2.3/", expectInfo) kr := httpbakery.NewThirdPartyLocator(nil, cache) info, err := kr.ThirdPartyInfo(testContext, "https://0.1.2.3/") c.Assert(err, gc.IsNil) c.Assert(info, jc.DeepEquals, expectInfo) } func (s *KeyringSuite) TestCacheMiss(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() kr := httpbakery.NewThirdPartyLocator(nil, nil) expectInfo := bakery.ThirdPartyInfo{ PublicKey: d.Key.Public, Version: bakery.LatestVersion, } location := d.Location() info, err := kr.ThirdPartyInfo(testContext, location) c.Assert(err, gc.IsNil) c.Assert(info, jc.DeepEquals, expectInfo) // Close down the service and make sure that // the key is cached. d.Close() info, err = kr.ThirdPartyInfo(testContext, location) c.Assert(err, gc.IsNil) c.Assert(info, jc.DeepEquals, expectInfo) } func (s *KeyringSuite) TestInsecureURL(c *gc.C) { // Set up a discharger with an non-HTTPS access point. d := bakerytest.NewDischarger(nil) defer d.Close() httpsDischargeURL, err := url.Parse(d.Location()) c.Assert(err, gc.IsNil) srv := httptest.NewServer(httputil.NewSingleHostReverseProxy(httpsDischargeURL)) defer srv.Close() // Check that we are refused because it's an insecure URL. kr := httpbakery.NewThirdPartyLocator(nil, nil) info, err := kr.ThirdPartyInfo(testContext, srv.URL) c.Assert(err, gc.ErrorMatches, `untrusted discharge URL "http://.*"`) c.Assert(info, jc.DeepEquals, bakery.ThirdPartyInfo{}) // Check that it does work when we've enabled AllowInsecure. kr.AllowInsecure() info, err = kr.ThirdPartyInfo(testContext, srv.URL) c.Assert(err, gc.IsNil) c.Assert(info, jc.DeepEquals, bakery.ThirdPartyInfo{ PublicKey: d.Key.Public, Version: bakery.LatestVersion, }) } func (s *KeyringSuite) TestConcurrentThirdPartyInfo(c *gc.C) { // This test is designed to fail only if run with the race detector // enabled. d := bakerytest.NewDischarger(nil) defer d.Close() kr := httpbakery.NewThirdPartyLocator(nil, nil) var wg sync.WaitGroup for i := 0; i < 2; i++ { wg.Add(1) go func() { _, err := kr.ThirdPartyInfo(testContext, d.Location()) c.Check(err, gc.IsNil) defer wg.Done() }() } wg.Wait() } func (s *KeyringSuite) TestCustomHTTPClient(c *gc.C) { client := &http.Client{ Transport: errorTransport{}, } kr := httpbakery.NewThirdPartyLocator(client, nil) info, err := kr.ThirdPartyInfo(testContext, "https://0.1.2.3/") c.Assert(err, gc.ErrorMatches, `(Get|GET) https://0.1.2.3/discharge/info: custom round trip error`) c.Assert(info, jc.DeepEquals, bakery.ThirdPartyInfo{}) } func (s *KeyringSuite) TestThirdPartyInfoForLocation(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() client := httpbakery.NewHTTPClient() info, err := httpbakery.ThirdPartyInfoForLocation(testContext, client, d.Location()) c.Assert(err, gc.IsNil) expectedInfo := bakery.ThirdPartyInfo{ PublicKey: d.Key.Public, Version: bakery.LatestVersion, } c.Assert(info, gc.DeepEquals, expectedInfo) // Check that it works with client==nil. info, err = httpbakery.ThirdPartyInfoForLocation(testContext, nil, d.Location()) c.Assert(err, gc.IsNil) c.Assert(info, gc.DeepEquals, expectedInfo) } func (s *KeyringSuite) TestThirdPartyInfoForLocationWrongURL(c *gc.C) { client := httpbakery.NewHTTPClient() _, err := httpbakery.ThirdPartyInfoForLocation(testContext, client, "http://localhost:0") c.Logf("%v", errgo.Details(err)) c.Assert(err, gc.ErrorMatches, `(Get|GET) http://localhost:0/discharge/info: dial tcp 127.0.0.1:0: .*connection refused`) } func (s *KeyringSuite) TestThirdPartyInfoForLocationReturnsInvalidJSON(c *gc.C) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "BADJSON") })) defer ts.Close() client := httpbakery.NewHTTPClient() _, err := httpbakery.ThirdPartyInfoForLocation(testContext, client, ts.URL) c.Assert(err, gc.ErrorMatches, fmt.Sprintf(`Get http://.*/discharge/info: unexpected content type text/plain; want application/json; content: BADJSON`)) } func (s *KeyringSuite) TestThirdPartyInfoForLocationReturnsStatusInternalServerError(c *gc.C) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer ts.Close() client := httpbakery.NewHTTPClient() _, err := httpbakery.ThirdPartyInfoForLocation(testContext, client, ts.URL) c.Assert(err, gc.ErrorMatches, fmt.Sprintf(`Get %s/discharge/info: cannot unmarshal error response \(status 500 Internal Server Error\): unexpected content type text/plain; want application/json; content: `, ts.URL)) } func (s *KeyringSuite) TestThirdPartyInfoForLocationFallbackToOldVersion(c *gc.C) { // Start a bakerytest discharger so we benefit from its TLS-verification-skip logic. d := bakerytest.NewDischarger(nil) defer d.Close() key, err := bakery.GenerateKey() c.Assert(err, gc.IsNil) // Start a server which serves the publickey endpoint only. mux := http.NewServeMux() server := httptest.NewTLSServer(mux) mux.HandleFunc("/publickey", func(w http.ResponseWriter, req *http.Request) { c.Check(req.Method, gc.Equals, "GET") httprequest.WriteJSON(w, http.StatusOK, &httpbakery.PublicKeyResponse{ PublicKey: &key.Public, }) }) info, err := httpbakery.ThirdPartyInfoForLocation(testContext, httpbakery.NewHTTPClient(), server.URL) c.Assert(err, gc.IsNil) expectedInfo := bakery.ThirdPartyInfo{ PublicKey: key.Public, Version: bakery.Version1, } c.Assert(info, jc.DeepEquals, expectedInfo) } type errorTransport struct{} func (errorTransport) RoundTrip(req *http.Request) (*http.Response, error) { return nil, errgo.New("custom round trip error") } ��������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/keyring.go����������������������0000644�0610621�0607500�00000006135�13172163311�030330� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "net/http" "net/url" "github.com/juju/httprequest" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) var _ bakery.ThirdPartyLocator = (*ThirdPartyLocator)(nil) // NewThirdPartyLocator returns a new third party // locator that uses the given client to find // information about third parties and // uses the given cache as a backing. // // If cache is nil, a new cache will be created. // // If client is nil, http.DefaultClient will be used. func NewThirdPartyLocator(client httprequest.Doer, cache *bakery.ThirdPartyStore) *ThirdPartyLocator { if cache == nil { cache = bakery.NewThirdPartyStore() } if client == nil { client = http.DefaultClient } return &ThirdPartyLocator{ client: client, cache: cache, } } // ThirdPartyLocator represents locator that can interrogate // third party discharge services for information. By default it refuses // to use insecure URLs. type ThirdPartyLocator struct { client httprequest.Doer allowInsecure bool cache *bakery.ThirdPartyStore } // AllowInsecure allows insecure URLs. This can be useful // for testing purposes. func (kr *ThirdPartyLocator) AllowInsecure() { kr.allowInsecure = true } // ThirdPartyLocator implements bakery.ThirdPartyLocator // by first looking in the backing cache and, if that fails, // making an HTTP request to find the information associated // with the given discharge location. func (kr *ThirdPartyLocator) ThirdPartyInfo(ctx context.Context, loc string) (bakery.ThirdPartyInfo, error) { u, err := url.Parse(loc) if err != nil { return bakery.ThirdPartyInfo{}, errgo.Notef(err, "invalid discharge URL %q", loc) } if u.Scheme != "https" && !kr.allowInsecure { return bakery.ThirdPartyInfo{}, errgo.Newf("untrusted discharge URL %q", loc) } info, err := kr.cache.ThirdPartyInfo(ctx, loc) if err == nil { return info, nil } info, err = ThirdPartyInfoForLocation(ctx, kr.client, loc) if err != nil { return bakery.ThirdPartyInfo{}, errgo.Mask(err) } kr.cache.AddInfo(loc, info) return info, nil } // ThirdPartyInfoForLocation returns information on the third party // discharge server running at the given location URL. Note that this is // insecure if an http: URL scheme is used. If client is nil, // http.DefaultClient will be used. func ThirdPartyInfoForLocation(ctx context.Context, client httprequest.Doer, url string) (bakery.ThirdPartyInfo, error) { dclient := newDischargeClient(url, client) info, err := dclient.DischargeInfo(ctx, &dischargeInfoRequest{}) if err == nil { return bakery.ThirdPartyInfo{ PublicKey: *info.PublicKey, Version: info.Version, }, nil } derr, ok := errgo.Cause(err).(*httprequest.DecodeResponseError) if !ok || derr.Response.StatusCode != http.StatusNotFound { return bakery.ThirdPartyInfo{}, errgo.Mask(err) } // The new endpoint isn't there, so try the old one. pkResp, err := dclient.PublicKey(ctx, &publicKeyRequest{}) if err != nil { return bakery.ThirdPartyInfo{}, errgo.Mask(err) } return bakery.ThirdPartyInfo{ PublicKey: *pkResp.PublicKey, Version: bakery.Version1, }, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/form/���������������������������0000755�0610621�0607500�00000000000�13172163311�027267� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/form/package_test.go������������0000644�0610621�0607500�00000000166�13172163311�032253� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package form_test import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/form/form_test.go���������������0000644�0610621�0607500�00000021446�13172163311�031627� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package form_test import ( "net/http" "time" "github.com/juju/httprequest" jujutesting "github.com/juju/testing" "github.com/juju/testing/httptesting" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/juju/environschema.v1" esform "gopkg.in/juju/environschema.v1/form" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/bakerytest" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery/form" ) type formSuite struct { jujutesting.LoggingSuite } var ages = time.Now().Add(time.Hour) var reqServer = httprequest.Server{ ErrorMapper: httpbakery.ErrorToResponse, } var _ = gc.Suite(&formSuite{}) var formLoginTests = []struct { about string filler fillerFunc expectError string noFormMethod bool getForm func() (environschema.Fields, error) postForm func(values map[string]interface{}) (*httpbakery.DischargeToken, error) }{{ about: "complete visit", getForm: func() (environschema.Fields, error) { return userPassForm, nil }, postForm: func(values map[string]interface{}) (*httpbakery.DischargeToken, error) { return &httpbakery.DischargeToken{ Kind: "form", Value: []byte("ok"), }, nil }, }, { about: "error getting schema", getForm: func() (environschema.Fields, error) { return nil, errgo.Newf("some error") }, expectError: `cannot get discharge from ".*": cannot get schema: Get https://.*/form: some error`, }, { about: "form visit method not supported", noFormMethod: true, expectError: `cannot get discharge from ".*": cannot start interactive session: no supported interaction method`, }, { about: "error submitting form", getForm: func() (environschema.Fields, error) { return userPassForm, nil }, postForm: func(values map[string]interface{}) (*httpbakery.DischargeToken, error) { return nil, errgo.Newf("some error") }, expectError: `cannot get discharge from ".*": cannot submit form.*: some error`, }, { about: "no schema", getForm: func() (environschema.Fields, error) { return nil, nil }, expectError: `cannot get discharge from ".*": invalid schema: no fields found`, }, { about: "filler error", getForm: func() (environschema.Fields, error) { return userPassForm, nil }, filler: func(esform.Form) (map[string]interface{}, error) { return nil, errgo.Newf("test error") }, expectError: `cannot get discharge from ".*": cannot handle form: test error`, }, { about: "invalid token returned from form submission", getForm: func() (environschema.Fields, error) { return userPassForm, nil }, postForm: func(values map[string]interface{}) (*httpbakery.DischargeToken, error) { return &httpbakery.DischargeToken{ Kind: "other", Value: []byte("something"), }, nil }, expectError: `cannot get discharge from ".*": Post .*: cannot discharge: invalid token .*`, }} func (s *formSuite) TestFormLogin(c *gc.C) { var ( getForm func() (environschema.Fields, error) postForm func(values map[string]interface{}) (*httpbakery.DischargeToken, error) noFormMethod bool ) discharger := bakerytest.NewDischarger(nil) defer discharger.Close() discharger.AddHTTPHandlers(FormHandlers(FormHandler{ getForm: func() (environschema.Fields, error) { return getForm() }, postForm: func(values map[string]interface{}) (*httpbakery.DischargeToken, error) { return postForm(values) }, })) discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if token != nil { if token.Kind != "form" || string(token.Value) != "ok" { return nil, errgo.Newf("invalid token %#v", token) } return nil, nil } err := httpbakery.NewInteractionRequiredError(nil, req) if noFormMethod { err.SetInteraction("notform", "value") } else { err.SetInteraction("form", form.InteractionInfo{ URL: "/form", }) } return nil, err }) b := bakery.New(bakery.BakeryParams{ Key: bakery.MustGenerateKey(), Locator: discharger, }) for i, test := range formLoginTests { c.Logf("\ntest %d: %s", i, test.about) getForm = test.getForm postForm = test.postForm noFormMethod = test.noFormMethod m, err := b.Oven.NewMacaroon(context.TODO(), bakery.LatestVersion, ages, []checkers.Caveat{{ Location: discharger.Location(), Condition: "test condition", }}, bakery.LoginOp) c.Assert(err, gc.Equals, nil) client := httpbakery.NewClient() filler := defaultFiller if test.filler != nil { filler = test.filler } client.AddInteractor(form.Interactor{ Filler: filler, }) ms, err := client.DischargeAll(context.Background(), m) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) continue } c.Assert(err, gc.IsNil) c.Assert(len(ms), gc.Equals, 2) } } var formTitleTests = []struct { host string expect string }{{ host: "xyz.com", expect: "Log in to xyz.com", }, { host: "abc.xyz.com", expect: "Log in to xyz.com", }, { host: "com", expect: "Log in to com", }} func (s *formSuite) TestFormTitle(c *gc.C) { discharger := bakerytest.NewDischarger(nil) defer discharger.Close() discharger.AddHTTPHandlers(FormHandlers(FormHandler{ getForm: func() (environschema.Fields, error) { return userPassForm, nil }, postForm: func(values map[string]interface{}) (*httpbakery.DischargeToken, error) { return &httpbakery.DischargeToken{ Kind: "form", Value: []byte("ok"), }, nil }, })) discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if token != nil { return nil, nil } err := httpbakery.NewInteractionRequiredError(nil, req) err.SetInteraction("form", form.InteractionInfo{ URL: "/form", }) return nil, err }) b := bakery.New(bakery.BakeryParams{ Key: bakery.MustGenerateKey(), Locator: testLocator{ loc: discharger.Location(), locator: discharger, }, }) for i, test := range formTitleTests { c.Logf("test %d: %s", i, test.host) m, err := b.Oven.NewMacaroon(context.TODO(), bakery.LatestVersion, ages, []checkers.Caveat{{ Location: "https://" + test.host, Condition: "test condition", }}, bakery.LoginOp) c.Assert(err, gc.Equals, nil) client := httpbakery.NewClient() c.Logf("match %v; replace with %v", test.host, discharger.Location()) client.Client.Transport = httptesting.URLRewritingTransport{ MatchPrefix: "https://" + test.host, Replace: discharger.Location(), RoundTripper: http.DefaultTransport, } var f titleTestFiller client.AddInteractor(form.Interactor{ Filler: &f, }) ms, err := client.DischargeAll(context.Background(), m) c.Assert(err, gc.IsNil) c.Assert(len(ms), gc.Equals, 2) c.Assert(f.title, gc.Equals, test.expect) } } func FormHandlers(h FormHandler) []httprequest.Handler { return reqServer.Handlers(func(p httprequest.Params) (formHandlers, context.Context, error) { return formHandlers{h}, p.Context, nil }) } type FormHandler struct { getForm func() (environschema.Fields, error) postForm func(values map[string]interface{}) (*httpbakery.DischargeToken, error) } type formHandlers struct { h FormHandler } type schemaRequest struct { httprequest.Route `httprequest:"GET /form"` } func (d formHandlers) GetForm(*schemaRequest) (*form.SchemaResponse, error) { schema, err := d.h.getForm() if err != nil { return nil, errgo.Mask(err) } return &form.SchemaResponse{schema}, nil } type loginRequest struct { httprequest.Route `httprequest:"POST /form"` form.LoginRequest } func (d formHandlers) PostForm(req *loginRequest) (*form.LoginResponse, error) { token, err := d.h.postForm(req.Body.Form) if err != nil { return nil, errgo.Mask(err) } return &form.LoginResponse{ Token: token, }, nil } type fillerFunc func(esform.Form) (map[string]interface{}, error) func (f fillerFunc) Fill(form esform.Form) (map[string]interface{}, error) { return f(form) } var defaultFiller = fillerFunc(func(esform.Form) (map[string]interface{}, error) { return map[string]interface{}{"test": 1}, nil }) type testLocator struct { loc string locator bakery.ThirdPartyLocator } func (l testLocator) ThirdPartyInfo(ctx context.Context, loc string) (bakery.ThirdPartyInfo, error) { return l.locator.ThirdPartyInfo(ctx, l.loc) } type titleTestFiller struct { title string } func (f *titleTestFiller) Fill(form esform.Form) (map[string]interface{}, error) { f.title = form.Title return map[string]interface{}{"test": 1}, nil } var userPassForm = environschema.Fields{ "username": environschema.Attr{ Type: environschema.Tstring, }, "password": environschema.Attr{ Type: environschema.Tstring, Secret: true, }, } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/form/form.go��������������������0000644�0610621�0607500�00000012450�13172163311�030563� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package form enables interactive login without using a web browser. package form import ( "net/url" "github.com/juju/httprequest" "github.com/juju/loggo" "golang.org/x/net/context" "golang.org/x/net/publicsuffix" "gopkg.in/errgo.v1" "gopkg.in/juju/environschema.v1" "gopkg.in/juju/environschema.v1/form" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) var logger = loggo.GetLogger("httpbakery.form") /* PROTOCOL A form login works as follows: Client Login Service | | | Discharge request | |----------------------------------->| | | | Interaction-required error with | | "form" entry with formURL. | |<-----------------------------------| | | | GET "form" URL | |----------------------------------->| | | | Schema definition | |<-----------------------------------| | | +-------------+ | | Client | | | Interaction | | +-------------+ | | | | POST data to "form" URL | |----------------------------------->| | | | Form login response | | with discharge token | |<-----------------------------------| | | | Discharge request with | | discharge token. | |----------------------------------->| | | | Discharge macaroon | |<-----------------------------------| The schema is provided as a environschema.Fields object. It is the client's responsibility to interpret the schema and present it to the user. */ const ( // InteractionMethod is the methodURLs key // used for a URL that can be used for form-based // interaction. InteractionMethod = "form" ) // SchemaResponse contains the message expected in response to the schema // request. type SchemaResponse struct { Schema environschema.Fields `json:"schema"` } // InteractionInfo holds the information expected in // the form interaction entry in an interaction-required // error. type InteractionInfo struct { URL string `json:"url"` } // LoginRequest is a request to perform a login using the provided form. type LoginRequest struct { httprequest.Route `httprequest:"POST"` Body LoginBody `httprequest:",body"` } // LoginBody holds the body of a form login request. type LoginBody struct { Form map[string]interface{} `json:"form"` } type LoginResponse struct { Token *httpbakery.DischargeToken `json:"token"` } // Interactor implements httpbakery.Interactor // by providing form-based interaction. type Interactor struct { // Filler holds the form filler that will be used when // form-based interaction is required. Filler form.Filler } // Kind implements httpbakery.Interactor.Kind. func (i Interactor) Kind() string { return InteractionMethod } // Interact implements httpbakery.Interactor.Interact. func (i Interactor) Interact(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { var p InteractionInfo if err := interactionRequiredErr.InteractionMethod(InteractionMethod, &p); err != nil { return nil, errgo.Mask(err) } if p.URL == "" { return nil, errgo.Newf("no URL found in form information") } schemaURL, err := relativeURL(location, p.URL) if err != nil { return nil, errgo.Notef(err, "invalid url %q", p.URL) } httpReqClient := &httprequest.Client{ Doer: client, } var s SchemaResponse if err := httpReqClient.Get(ctx, schemaURL.String(), &s); err != nil { return nil, errgo.Notef(err, "cannot get schema") } if len(s.Schema) == 0 { return nil, errgo.Newf("invalid schema: no fields found") } host, err := publicsuffix.EffectiveTLDPlusOne(schemaURL.Host) if err != nil { host = schemaURL.Host } formValues, err := i.Filler.Fill(form.Form{ Title: "Log in to " + host, Fields: s.Schema, }) if err != nil { return nil, errgo.NoteMask(err, "cannot handle form", errgo.Any) } lr := LoginRequest{ Body: LoginBody{ Form: formValues, }, } var lresp LoginResponse if err := httpReqClient.CallURL(ctx, schemaURL.String(), &lr, &lresp); err != nil { return nil, errgo.Notef(err, "cannot submit form") } if lresp.Token == nil { return nil, errgo.Newf("no token found in form response") } return lresp.Token, nil } // relativeURL returns newPath relative to an original URL. func relativeURL(base, new string) (*url.URL, error) { if new == "" { return nil, errgo.Newf("empty URL") } baseURL, err := url.Parse(base) if err != nil { return nil, errgo.Notef(err, "cannot parse URL") } newURL, err := url.Parse(new) if err != nil { return nil, errgo.Notef(err, "cannot parse URL") } return baseURL.ResolveReference(newURL), nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/export_test.go������������������0000644�0610621�0607500�00000000255�13172163311�031235� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery type PublicKeyResponse publicKeyResponse const MaxDischargeRetries = maxDischargeRetries var LegacyGetInteractionMethods = legacyGetInteractionMethods ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/error_test.go�������������������0000644�0610621�0607500�00000015263�13172163311�031052� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery_test import ( "encoding/json" "errors" "net/http" "net/http/httptest" "reflect" "github.com/juju/httprequest" jc "github.com/juju/testing/checkers" "github.com/juju/testing/httptesting" gc "gopkg.in/check.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) type ErrorSuite struct{} var _ = gc.Suite(&ErrorSuite{}) func (s *ErrorSuite) TestWriteDischargeRequiredError(c *gc.C) { m, err := bakery.NewMacaroon([]byte("secret"), []byte("id"), "a location", bakery.LatestVersion, nil) c.Assert(err, gc.IsNil) tests := []struct { about string path string requestPath string err error expectedResponse httpbakery.Error }{{ about: `write discharge required with "an error" but no path`, path: "", err: errors.New("an error"), expectedResponse: httpbakery.Error{ Code: httpbakery.ErrDischargeRequired, Message: "an error", Info: &httpbakery.ErrorInfo{ Macaroon: m, MacaroonPath: "/", }, }, }, { about: `write discharge required with "an error" but and set a path`, path: "/foo", err: errors.New("an error"), expectedResponse: httpbakery.Error{ Code: httpbakery.ErrDischargeRequired, Message: "an error", Info: &httpbakery.ErrorInfo{ Macaroon: m, MacaroonPath: "/foo", }, }, }, { about: `write discharge required with nil error but set a path`, path: "/foo", expectedResponse: httpbakery.Error{ Code: httpbakery.ErrDischargeRequired, Message: httpbakery.ErrDischargeRequired.Error(), Info: &httpbakery.ErrorInfo{ Macaroon: m, MacaroonPath: "/foo", }, }, }, { about: `empty cookie path`, requestPath: "/foo/bar/baz", expectedResponse: httpbakery.Error{ Code: httpbakery.ErrDischargeRequired, Message: httpbakery.ErrDischargeRequired.Error(), Info: &httpbakery.ErrorInfo{ Macaroon: m, MacaroonPath: "../../", }, }, }} for i, t := range tests { c.Logf("test %d: %s", i, t.about) var req *http.Request if t.requestPath != "" { req0, err := http.NewRequest("GET", t.requestPath, nil) c.Check(err, gc.Equals, nil) req = req0 } response := httptest.NewRecorder() err := httpbakery.NewDischargeRequiredError(httpbakery.DischargeRequiredErrorParams{ Macaroon: m, CookiePath: t.path, OriginalError: t.err, Request: req, }) httpbakery.WriteError(testContext, response, err) httptesting.AssertJSONResponse(c, response, http.StatusUnauthorized, t.expectedResponse) } } func (s *ErrorSuite) TestNewInteractionRequiredError(c *gc.C) { // With a request with no version header, the response // should be 407. req, err := http.NewRequest("GET", "/", nil) c.Assert(err, gc.IsNil) err = httpbakery.NewInteractionRequiredError(nil, req) code, resp := httpbakery.ErrorToResponse(testContext, err) c.Assert(code, gc.Equals, http.StatusProxyAuthRequired) data, err := json.Marshal(resp) c.Assert(err, gc.IsNil) c.Assert(string(data), jc.JSONEquals, &httpbakery.Error{ Code: httpbakery.ErrInteractionRequired, Message: httpbakery.ErrInteractionRequired.Error(), }) // With a request with a version 1 header, the response // should be 401. req.Header.Set("Bakery-Protocol-Version", "1") err = httpbakery.NewInteractionRequiredError(nil, req) code, resp = httpbakery.ErrorToResponse(testContext, err) c.Assert(code, gc.Equals, http.StatusUnauthorized) h := make(http.Header) resp.(httprequest.HeaderSetter).SetHeader(h) c.Assert(h.Get("WWW-Authenticate"), gc.Equals, "Macaroon") data, err = json.Marshal(resp) c.Assert(err, gc.IsNil) c.Assert(string(data), jc.JSONEquals, &httpbakery.Error{ Code: httpbakery.ErrInteractionRequired, Message: httpbakery.ErrInteractionRequired.Error(), }) // With a request with a later version header, the response // should be also be 401. req.Header.Set("Bakery-Protocol-Version", "2") err = httpbakery.NewInteractionRequiredError(nil, req) code, resp = httpbakery.ErrorToResponse(testContext, err) c.Assert(code, gc.Equals, http.StatusUnauthorized) h = make(http.Header) resp.(httprequest.HeaderSetter).SetHeader(h) c.Assert(h.Get("WWW-Authenticate"), gc.Equals, "Macaroon") data, err = json.Marshal(resp) c.Assert(err, gc.IsNil) c.Assert(string(data), jc.JSONEquals, &httpbakery.Error{ Code: httpbakery.ErrInteractionRequired, Message: httpbakery.ErrInteractionRequired.Error(), }) } func (*ErrorSuite) TestSetInteraction(c *gc.C) { var e httpbakery.Error e.SetInteraction("foo", 5) c.Assert(e, jc.DeepEquals, httpbakery.Error{ Info: &httpbakery.ErrorInfo{ InteractionMethods: map[string]*json.RawMessage{ "foo": jsonRawMessage("5"), }, }, }) } func jsonRawMessage(s string) *json.RawMessage { m := json.RawMessage(s) return &m } var interactionMethodTests = []struct { about string err *httpbakery.Error kind string expect interface{} expectError string }{{ about: "no info", err: &httpbakery.Error{}, expect: 0, expectError: `not an interaction-required error \(code \)`, }, { about: "not interaction-required code", err: &httpbakery.Error{ Code: "other", Info: &httpbakery.ErrorInfo{}, }, expect: 0, expectError: `not an interaction-required error \(code other\)`, }, { about: "interaction method not found", err: &httpbakery.Error{ Code: httpbakery.ErrInteractionRequired, Info: &httpbakery.ErrorInfo{ InteractionMethods: map[string]*json.RawMessage{ "foo": jsonRawMessage("0"), }, }, }, kind: "x", expect: 0, expectError: `interaction method "x" not found`, }, { about: "cannot unmarshal", err: &httpbakery.Error{ Code: httpbakery.ErrInteractionRequired, Info: &httpbakery.ErrorInfo{ InteractionMethods: map[string]*json.RawMessage{ "x": jsonRawMessage(`{"X": 45}`), }, }, }, kind: "x", expect: struct { X string }{}, expectError: `cannot unmarshal data for interaction method "x": json: cannot unmarshal number into Go struct field .X of type string`, }, { about: "success", err: &httpbakery.Error{ Code: httpbakery.ErrInteractionRequired, Info: &httpbakery.ErrorInfo{ InteractionMethods: map[string]*json.RawMessage{ "x": jsonRawMessage(`45`), }, }, }, kind: "x", expect: 45, }} func (*ErrorSuite) TestInteractionMethod(c *gc.C) { for i, test := range interactionMethodTests { c.Logf("test %d: %s", i, test.about) v := reflect.New(reflect.TypeOf(test.expect)) err := test.err.InteractionMethod(test.kind, v.Interface()) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) } else { c.Assert(err, gc.Equals, nil) c.Assert(v.Elem().Interface(), jc.DeepEquals, test.expect) } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/error.go������������������������0000644�0610621�0607500�00000026326�13172163311�030015� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "encoding/json" "fmt" "net/http" "strconv" "github.com/juju/httprequest" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/internal/httputil" ) // ErrorCode holds an error code that classifies // an error returned from a bakery HTTP handler. type ErrorCode string func (e ErrorCode) Error() string { return string(e) } func (e ErrorCode) ErrorCode() ErrorCode { return e } const ( ErrBadRequest = ErrorCode("bad request") ErrDischargeRequired = ErrorCode("macaroon discharge required") ErrInteractionRequired = ErrorCode("interaction required") ErrInteractionMethodNotFound = ErrorCode("discharger does not provide an supported interaction method") ErrPermissionDenied = ErrorCode("permission denied") ) var httpReqServer = httprequest.Server{ ErrorMapper: ErrorToResponse, } // WriteError writes the given bakery error to w. func WriteError(ctx context.Context, w http.ResponseWriter, err error) { httpReqServer.WriteError(ctx, w, err) } // Error holds the type of a response from an httpbakery HTTP request, // marshaled as JSON. // // Note: Do not construct Error values with ErrDischargeRequired or // ErrInteractionRequired codes directly - use the // NewDischargeRequiredError or NewInteractionRequiredError // functions instead. type Error struct { Code ErrorCode `json:",omitempty"` Message string `json:",omitempty"` Info *ErrorInfo `json:",omitempty"` // version holds the protocol version that was used // to create the error (see NewDischargeRequiredError). version bakery.Version } // ErrorInfo holds additional information provided // by an error. type ErrorInfo struct { // Macaroon may hold a macaroon that, when // discharged, may allow access to a service. // This field is associated with the ErrDischargeRequired // error code. Macaroon *bakery.Macaroon `json:",omitempty"` // MacaroonPath holds the URL path to be associated // with the macaroon. The macaroon is potentially // valid for all URLs under the given path. // If it is empty, the macaroon will be associated with // the original URL from which the error was returned. MacaroonPath string `json:",omitempty"` // CookieNameSuffix holds the desired cookie name suffix to be // associated with the macaroon. The actual name used will be // ("macaroon-" + CookieName). Clients may ignore this field - // older clients will always use ("macaroon-" + // macaroon.Signature() in hex). CookieNameSuffix string `json:",omitempty"` // The following fields are associated with the // ErrInteractionRequired error code. // InteractionMethods holds the set of methods that the // third party supports for completing the discharge. // See InteractionMethod for a more convenient // accessor method. InteractionMethods map[string]*json.RawMessage `json:",omitempty"` // LegacyVisitURL holds a URL that the client should visit // in a web browser to authenticate themselves. // This is deprecated - it is superceded by the InteractionMethods // field. LegacyVisitURL string `json:"VisitURL,omitempty"` // LegacyWaitURL holds a URL that the client should visit // to acquire the discharge macaroon. A GET on // this URL will block until the client has authenticated, // and then it will return the discharge macaroon. // This is deprecated - it is superceded by the InteractionMethods // field. LegacyWaitURL string `json:"WaitURL,omitempty"` } // SetInteraction sets the information for a particular // interaction kind to v. The error should be an interaction-required // error. This method will panic if v cannot be JSON-marshaled. // It is expected that interaction implementations will // implement type-safe wrappers for this method, // so you should not need to call it directly. func (e *Error) SetInteraction(kind string, v interface{}) { if e.Info == nil { e.Info = new(ErrorInfo) } if e.Info.InteractionMethods == nil { e.Info.InteractionMethods = make(map[string]*json.RawMessage) } data, err := json.Marshal(v) if err != nil { panic(err) } m := json.RawMessage(data) e.Info.InteractionMethods[kind] = &m } // InteractionMethod checks whether the error is an InteractionRequired error // that implements the method with the given name, and JSON-unmarshals the // method-specific data into x. func (e *Error) InteractionMethod(kind string, x interface{}) error { if e.Info == nil || e.Code != ErrInteractionRequired { return errgo.Newf("not an interaction-required error (code %v)", e.Code) } entry := e.Info.InteractionMethods[kind] if entry == nil { return errgo.WithCausef(nil, ErrInteractionMethodNotFound, "interaction method %q not found", kind) } if err := json.Unmarshal(*entry, x); err != nil { return errgo.Notef(err, "cannot unmarshal data for interaction method %q", kind) } return nil } func (e *Error) Error() string { return e.Message } func (e *Error) ErrorCode() ErrorCode { return e.Code } // ErrorInfo returns additional information // about the error. // TODO return interface{} here? func (e *Error) ErrorInfo() *ErrorInfo { return e.Info } // ErrorToResponse returns the HTTP status and an error body to be // marshaled as JSON for the given error. This allows a third party // package to integrate bakery errors into their error responses when // they encounter an error with a *bakery.Error cause. func ErrorToResponse(ctx context.Context, err error) (int, interface{}) { errorBody := errorResponseBody(err) var body interface{} = errorBody status := http.StatusInternalServerError switch errorBody.Code { case ErrBadRequest: status = http.StatusBadRequest case ErrPermissionDenied: status = http.StatusUnauthorized case ErrDischargeRequired, ErrInteractionRequired: switch errorBody.version { case bakery.Version0: status = http.StatusProxyAuthRequired case bakery.Version1, bakery.Version2, bakery.Version3: status = http.StatusUnauthorized body = httprequest.CustomHeader{ Body: body, SetHeaderFunc: setAuthenticateHeader, } default: panic(fmt.Sprintf("out of range version number %v", errorBody.version)) } } return status, body } func setAuthenticateHeader(h http.Header) { h.Set("WWW-Authenticate", "Macaroon") } type errorInfoer interface { ErrorInfo() *ErrorInfo } type errorCoder interface { ErrorCode() ErrorCode } // errorResponse returns an appropriate error // response for the provided error. func errorResponseBody(err error) *Error { var errResp Error cause := errgo.Cause(err) if cause, ok := cause.(*Error); ok { // It's an Error already. Preserve the wrapped // error message but copy everything else. errResp = *cause errResp.Message = err.Error() return &errResp } // It's not an error. Preserve as much info as // we can find. errResp.Message = err.Error() if coder, ok := cause.(errorCoder); ok { errResp.Code = coder.ErrorCode() } if infoer, ok := cause.(errorInfoer); ok { errResp.Info = infoer.ErrorInfo() } return &errResp } // NewInteractionRequiredError returns an error of type *Error // that requests an interaction from the client in response // to the given request. The originalErr value describes the original // error - if it is nil, a default message will be provided. // // This function should be used in preference to creating the Error value // directly, as it sets the bakery protocol version correctly in the error. // // The returned error does not support any interaction kinds. // Use kind-specific SetInteraction methods (for example // WebBrowserInteractor.SetInteraction) to add supported // interaction kinds. // // Note that WebBrowserInteractor.SetInteraction should always be called // for legacy clients to maintain backwards compatibility. func NewInteractionRequiredError(originalErr error, req *http.Request) *Error { if originalErr == nil { originalErr = ErrInteractionRequired } return &Error{ Message: originalErr.Error(), version: RequestVersion(req), Code: ErrInteractionRequired, } } type DischargeRequiredErrorParams struct { // Macaroon holds the macaroon that needs to be discharged // by the client. Macaroon *bakery.Macaroon // OriginalError holds the reason that the discharge-required // error was created. If it's nil, ErrDischargeRequired will // be used. OriginalError error // CookiePath holds the path for the client to give the cookie // holding the discharged macaroon. If it's empty, then a // relative path from the request URL path to / will be used if // Request is provided, or "/" otherwise. CookiePath string // CookieNameSuffix holds the suffix for the client // to give the cookie holding the discharged macaroon // (after the "macaroon-" prefix). // If it's empty, "auth" will be used. CookieNameSuffix string // Request holds the request that the error is in response to. // It is used to form the cookie path if CookiePath is empty. Request *http.Request } // NewDischargeRequiredErrorWithVersion returns an error of type *Error // that contains a macaroon to the client and acts as a request that the // macaroon be discharged to authorize the request. // // The client is responsible for discharging the macaroon and // storing it as a cookie (or including it as a Macaroon header) // to be used for the subsequent request. func NewDischargeRequiredError(p DischargeRequiredErrorParams) error { if p.OriginalError == nil { p.OriginalError = ErrDischargeRequired } if p.CookiePath == "" { p.CookiePath = "/" if p.Request != nil { path, err := httputil.RelativeURLPath(p.Request.URL.Path, "/") if err == nil { p.CookiePath = path } } } if p.CookieNameSuffix == "" { p.CookieNameSuffix = "auth" } return &Error{ version: p.Macaroon.Version(), Message: p.OriginalError.Error(), Code: ErrDischargeRequired, Info: &ErrorInfo{ Macaroon: p.Macaroon, MacaroonPath: p.CookiePath, }, } } // BakeryProtocolHeader is the header that HTTP clients should set // to determine the bakery protocol version. If it is 0 or missing, // a discharge-required error response will be returned with HTTP status 407; // if it is 1, the response will have status 401 with the WWW-Authenticate // header set to "Macaroon". const BakeryProtocolHeader = "Bakery-Protocol-Version" // RequestVersion determines the bakery protocol version from a client // request. If the protocol cannot be determined, or is invalid, the // original version of the protocol is used. If a later version is // found, the latest known version is used, which is OK because versions // are backwardly compatible. // // TODO as there are no known version 0 clients, default to version 1 // instead. func RequestVersion(req *http.Request) bakery.Version { vs := req.Header.Get(BakeryProtocolHeader) if vs == "" { // No header - use backward compatibility mode. return bakery.Version0 } x, err := strconv.Atoi(vs) if err != nil || x < 0 { // Badly formed header - use backward compatibility mode. return bakery.Version0 } v := bakery.Version(x) if v > bakery.LatestVersion { // Later version than we know about - use the // latest version that we can. return bakery.LatestVersion } return v } func isDischargeRequiredError(err error) bool { respErr, ok := errgo.Cause(err).(*Error) if !ok { return false } return respErr.Code == ErrDischargeRequired } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/dischargeclient_generated.go����0000644�0610621�0607500�00000001741�13172163311�034024� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// The code in this file was automatically generated by running httprequest-generate-client. // DO NOT EDIT package httpbakery import ( "github.com/juju/httprequest" "golang.org/x/net/context" ) type dischargeClient struct { Client httprequest.Client } // Discharge discharges a third party caveat. func (c *dischargeClient) Discharge(ctx context.Context, p *dischargeRequest) (*dischargeResponse, error) { var r *dischargeResponse err := c.Client.Call(ctx, p, &r) return r, err } // DischargeInfo returns information on the discharger. func (c *dischargeClient) DischargeInfo(ctx context.Context, p *dischargeInfoRequest) (dischargeInfoResponse, error) { var r dischargeInfoResponse err := c.Client.Call(ctx, p, &r) return r, err } // PublicKey returns the public key of the discharge service. func (c *dischargeClient) PublicKey(ctx context.Context, p *publicKeyRequest) (publicKeyResponse, error) { var r publicKeyResponse err := c.Client.Call(ctx, p, &r) return r, err } �������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/discharge.go��������������������0000644�0610621�0607500�00000024102�13172163311�030603� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "encoding/base64" "net/http" "path" "unicode/utf8" "github.com/juju/httprequest" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // ThirdPartyCaveatChecker is used to check third party caveats. type ThirdPartyCaveatChecker interface { // CheckThirdPartyCaveat is used to check whether a client // making the given request should be allowed a discharge for // the given caveat. On success, the caveat will be discharged, // with any returned caveats also added to the discharge // macaroon. // // The given token, if non-nil, is a token obtained from // Interactor.Interact as the result of a discharge interaction // after an interaction required error. // // Note than when used in the context of a discharge handler // created by Discharger, any returned errors will be marshaled // as documented in DischargeHandler.ErrorMapper. CheckThirdPartyCaveat(ctx context.Context, info *bakery.ThirdPartyCaveatInfo, req *http.Request, token *DischargeToken) ([]checkers.Caveat, error) } // ThirdPartyCaveatCheckerFunc implements ThirdPartyCaveatChecker // by calling a function. type ThirdPartyCaveatCheckerFunc func(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *DischargeToken) ([]checkers.Caveat, error) func (f ThirdPartyCaveatCheckerFunc) CheckThirdPartyCaveat(ctx context.Context, info *bakery.ThirdPartyCaveatInfo, req *http.Request, token *DischargeToken) ([]checkers.Caveat, error) { return f(ctx, req, info, token) } // newDischargeClient returns a discharge client that addresses the // third party discharger at the given location URL and uses // the given client to make HTTP requests. // // If client is nil, http.DefaultClient is used. func newDischargeClient(location string, client httprequest.Doer) *dischargeClient { if client == nil { client = http.DefaultClient } return &dischargeClient{ Client: httprequest.Client{ BaseURL: location, Doer: client, UnmarshalError: unmarshalError, }, } } // Discharger holds parameters for creating a new Discharger. type DischargerParams struct { // Checker is used to actually check the caveats. Checker ThirdPartyCaveatChecker // Key holds the key pair of the discharger. Key *bakery.KeyPair // Locator is used to find public keys when adding // third-party caveats on discharge macaroons. // If this is nil, no third party caveats may be added. Locator bakery.ThirdPartyLocator // ErrorToResponse is used to convert errors returned by the third // party caveat checker to the form that will be JSON-marshaled // on the wire. If zero, this defaults to ErrorToResponse. // If set, it should handle errors that it does not understand // by falling back to calling ErrorToResponse to ensure // that the standard bakery errors are marshaled in the expected way. ErrorToResponse func(ctx context.Context, err error) (int, interface{}) } // Discharger represents a third-party caveat discharger. // can discharge caveats in an HTTP server. // // The name space served by dischargers is as follows. // All parameters can be provided either as URL attributes // or form attributes. The result is always formatted as a JSON // object. // // On failure, all endpoints return an error described by // the Error type. // // POST /discharge // params: // id: all-UTF-8 third party caveat id // id64: non-padded URL-base64 encoded caveat id // macaroon-id: (optional) id to give to discharge macaroon (defaults to id) // token: (optional) value of discharge token // token64: (optional) base64-encoded value of discharge token. // token-kind: (mandatory if token or token64 provided) discharge token kind. // result on success (http.StatusOK): // { // Macaroon *macaroon.Macaroon // } // // GET /publickey // result: // public key of service // expiry time of key type Discharger struct { p DischargerParams } // NewDischarger returns a new third-party caveat discharger // using the given parameters. func NewDischarger(p DischargerParams) *Discharger { if p.ErrorToResponse == nil { p.ErrorToResponse = ErrorToResponse } if p.Locator == nil { p.Locator = emptyLocator{} } return &Discharger{ p: p, } } type emptyLocator struct{} func (emptyLocator) ThirdPartyInfo(ctx context.Context, loc string) (bakery.ThirdPartyInfo, error) { return bakery.ThirdPartyInfo{}, bakery.ErrNotFound } // AddMuxHandlers adds handlers to the given ServeMux to provide // a third-party caveat discharge service. func (d *Discharger) AddMuxHandlers(mux *http.ServeMux, rootPath string) { for _, h := range d.Handlers() { // Note: this only works because we don't have any wildcard // patterns in the discharger paths. mux.Handle(path.Join(rootPath, h.Path), mkHTTPHandler(h.Handle)) } } // Handlers returns a slice of handlers that can handle a third-party // caveat discharge service when added to an httprouter.Router. // TODO provide some way of customizing the context so that // ErrorToResponse can see a request-specific context. func (d *Discharger) Handlers() []httprequest.Handler { f := func(p httprequest.Params) (dischargeHandler, context.Context, error) { return dischargeHandler{ discharger: d, }, p.Context, nil } srv := httprequest.Server{ ErrorMapper: d.p.ErrorToResponse, } return srv.Handlers(f) } //go:generate httprequest-generate-client gopkg.in/macaroon-bakery.v2-unstable/httpbakery dischargeHandler dischargeClient // dischargeHandler is the type used to define the httprequest handler // methods for a discharger. type dischargeHandler struct { discharger *Discharger } // dischargeRequest is a request to create a macaroon that discharges the // supplied third-party caveat. Discharging caveats will normally be // handled by the bakery it would be unusual to use this type directly in // client software. type dischargeRequest struct { httprequest.Route `httprequest:"POST /discharge"` Id string `httprequest:"id,form,omitempty"` Id64 string `httprequest:"id64,form,omitempty"` Caveat string `httprequest:"caveat64,form,omitempty"` Token string `httprequest:"token,form,omitempty"` Token64 string `httprequest:"token64,form,omitempty"` TokenKind string `httprequest:"token-kind,form,omitempty"` } // dischargeResponse contains the response from a /discharge POST request. type dischargeResponse struct { Macaroon *bakery.Macaroon `json:",omitempty"` } // Discharge discharges a third party caveat. func (h dischargeHandler) Discharge(p httprequest.Params, r *dischargeRequest) (*dischargeResponse, error) { id, err := maybeBase64Decode(r.Id, r.Id64) if err != nil { return nil, errgo.Notef(err, "bad caveat id") } var caveat []byte if r.Caveat != "" { // Note that it's important that when r.Caveat is empty, // we leave DischargeParams.Caveat as nil (Base64Decode // always returns a non-nil byte slice). caveat1, err := macaroon.Base64Decode([]byte(r.Caveat)) if err != nil { return nil, errgo.Notef(err, "bad base64-encoded caveat: %v", err) } caveat = caveat1 } tokenVal, err := maybeBase64Decode(r.Token, r.Token64) if err != nil { return nil, errgo.Notef(err, "bad discharge token") } var token *DischargeToken if len(tokenVal) != 0 { if r.TokenKind == "" { return nil, errgo.Notef(err, "discharge token provided without token kind") } token = &DischargeToken{ Kind: r.TokenKind, Value: tokenVal, } } m, err := bakery.Discharge(p.Context, bakery.DischargeParams{ Id: id, Caveat: caveat, Key: h.discharger.p.Key, Checker: bakery.ThirdPartyCaveatCheckerFunc( func(ctx context.Context, cav *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { return h.discharger.p.Checker.CheckThirdPartyCaveat(ctx, cav, p.Request, token) }, ), Locator: h.discharger.p.Locator, }) if err != nil { return nil, errgo.NoteMask(err, "cannot discharge", errgo.Any) } return &dischargeResponse{m}, nil } // publicKeyRequest specifies the /publickey endpoint. type publicKeyRequest struct { httprequest.Route `httprequest:"GET /publickey"` } // publicKeyResponse is the response to a /publickey GET request. type publicKeyResponse struct { PublicKey *bakery.PublicKey } // dischargeInfoRequest specifies the /discharge/info endpoint. type dischargeInfoRequest struct { httprequest.Route `httprequest:"GET /discharge/info"` } // dischargeInfoResponse is the response to a /discharge/info GET // request. type dischargeInfoResponse struct { PublicKey *bakery.PublicKey Version bakery.Version } // PublicKey returns the public key of the discharge service. func (h dischargeHandler) PublicKey(*publicKeyRequest) (publicKeyResponse, error) { return publicKeyResponse{ PublicKey: &h.discharger.p.Key.Public, }, nil } // DischargeInfo returns information on the discharger. func (h dischargeHandler) DischargeInfo(*dischargeInfoRequest) (dischargeInfoResponse, error) { return dischargeInfoResponse{ PublicKey: &h.discharger.p.Key.Public, Version: bakery.LatestVersion, }, nil } // mkHTTPHandler converts an httprouter handler to an http.Handler, // assuming that the httprouter handler has no wildcard path // parameters. func mkHTTPHandler(h httprouter.Handle) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { h(w, req, nil) }) } // maybeBase64Encode encodes b as is if it's // OK to be passed as a URL form parameter, // or encoded as base64 otherwise. func maybeBase64Encode(b []byte) (s, s64 string) { if utf8.Valid(b) { valid := true for _, c := range b { if c < 32 || c == 127 { valid = false break } } if valid { return string(b), "" } } return "", base64.RawURLEncoding.EncodeToString(b) } // maybeBase64Decode implements the inverse of maybeBase64Encode. func maybeBase64Decode(s, s64 string) ([]byte, error) { if s64 != "" { data, err := macaroon.Base64Decode([]byte(s64)) if err != nil { return nil, errgo.Mask(err) } if len(data) == 0 { return nil, nil } return data, nil } return []byte(s), nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/context_prego17.go��������������0000644�0610621�0607500�00000000267�13172163311�031710� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.7 package httpbakery import ( "net/http" "golang.org/x/net/context" ) func contextFromRequest(req *http.Request) context.Context { return context.Background() } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/context_go17.go�����������������0000644�0610621�0607500�00000000257�13172163311�031200� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.7 package httpbakery import ( "net/http" "golang.org/x/net/context" ) func contextFromRequest(req *http.Request) context.Context { return req.Context() } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/client_test.go������������������0000644�0610621�0607500�00000125674�13172163311�031207� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery_test import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "sort" "strings" "time" "github.com/juju/httprequest" jujutesting "github.com/juju/testing" jc "github.com/juju/testing/checkers" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/bakerytest" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) type ClientSuite struct { jujutesting.LoggingSuite } var _ = gc.Suite(&ClientSuite{}) var ( testOp = bakery.Op{"test", "test"} ages = time.Now().Add(24 * time.Hour) testContext = context.Background() ) // TestSingleServiceFirstParty creates a single service // with a macaroon with one first party caveat. // It creates a request with this macaroon and checks that the service // can verify this macaroon as valid. func (s *ClientSuite) TestSingleServiceFirstParty(c *gc.C) { // Create a target service. b := newBakery("loc", nil, nil) // No discharge required, so pass "unknown" for the third party // caveat discharger location so we know that we don't try // to discharge the location. ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: "unknown", })) defer ts.Close() // Mint a macaroon for the target service. serverMacaroon, err := b.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, testOp) c.Assert(err, gc.IsNil) c.Assert(serverMacaroon.M().Location(), gc.Equals, "loc") err = b.Oven.AddCaveat(testContext, serverMacaroon, isSomethingCaveat()) c.Assert(err, gc.IsNil) // Create a client request. req, err := http.NewRequest("GET", ts.URL, nil) c.Assert(err, gc.IsNil) client := clientRequestWithCookies(c, ts.URL, macaroon.Slice{serverMacaroon.M()}) // Somehow the client has accquired the macaroon. Add it to the cookiejar in our request. // Make the request to the server. resp, err := client.Do(req) c.Assert(err, gc.IsNil) defer resp.Body.Close() assertResponse(c, resp, "done") } func (s *ClientSuite) TestSingleServiceFirstPartyWithHeader(c *gc.C) { // Create a target service. b := newBakery("loc", nil, nil) // No discharge required, so pass "unknown" for the third party // caveat discharger location so we know that we don't try // to discharge the location. ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: "unknown", })) defer ts.Close() // Mint a macaroon for the target service. serverMacaroon, err := b.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, testOp) c.Assert(err, gc.IsNil) c.Assert(serverMacaroon.M().Location(), gc.Equals, "loc") err = b.Oven.AddCaveat(testContext, serverMacaroon, isSomethingCaveat()) c.Assert(err, gc.IsNil) // Serialize the macaroon slice. data, err := json.Marshal(macaroon.Slice{serverMacaroon.M()}) c.Assert(err, gc.IsNil) value := base64.StdEncoding.EncodeToString(data) // Create a client request. req, err := http.NewRequest("GET", ts.URL, nil) c.Assert(err, gc.IsNil) req.Header.Set(httpbakery.MacaroonsHeader, value) client := httpbakery.NewHTTPClient() // Make the request to the server. resp, err := client.Do(req) c.Assert(err, gc.IsNil) defer resp.Body.Close() assertResponse(c, resp, "done") } func (s *ClientSuite) TestRepeatedRequestWithBody(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() // Create a target service. b := newBakery("loc", d, nil) ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: d.Location(), alwaysReadBody: true, })) defer ts.Close() // Try with no authorization, to make sure that httpbakery.Do // really will retry the request. bodyText := "postbody" bodyReader := &readCounter{ReadSeeker: strings.NewReader(bodyText)} req, err := http.NewRequest("POST", ts.URL, bodyReader) c.Assert(err, gc.IsNil) resp, err := httpbakery.NewClient().Do(req) c.Assert(err, gc.IsNil) defer resp.Body.Close() assertResponse(c, resp, "done postbody") // Sanity check that the body really was read twice and hence // that we are checking the logic we intend to check. c.Assert(bodyReader.byteCount, gc.Equals, len(bodyText)*2) } func (s ClientSuite) TestWithLargeBody(c *gc.C) { // This test is designed to fail when run with the race // checker enabled and when go issue #12796 // is not fixed. d := bakerytest.NewDischarger(nil) defer d.Close() // Create a target service. b := newBakery("loc", d, nil) ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: d.Location(), })) defer ts.Close() // Create a client request. req, err := http.NewRequest("POST", ts.URL+"/no-body", &largeReader{total: 3 * 1024 * 1024}) c.Assert(err, gc.IsNil) resp, err := httpbakery.NewClient().Do(req) c.Assert(err, gc.IsNil) resp.Body.Close() c.Assert(resp.StatusCode, gc.Equals, http.StatusOK) } // largeReader implements a reader that produces up to total bytes // in 1 byte reads. type largeReader struct { total int n int } func (r *largeReader) Read(buf []byte) (int, error) { if r.n >= r.total { return 0, io.EOF } r.n++ return copy(buf, []byte("a")), nil } func (r *largeReader) Seek(offset int64, whence int) (int64, error) { if offset != 0 || whence != 0 { panic("unexpected seek") } r.n = 0 return 0, nil } func (r *largeReader) Close() error { // By setting n to zero, we ensure that if there's // a concurrent read, it will also read from n // and so the race detector should pick up the // problem. r.n = 0 return nil } func (s *ClientSuite) TestDischargeServerWithBinaryCaveatId(c *gc.C) { assertDischargeServerDischargesConditionForVersion(c, "\xff\x00\x89", bakery.Version2) } func (s *ClientSuite) TestDischargeServerWithStringCaveatId(c *gc.C) { assertDischargeServerDischargesConditionForVersion(c, "foo", bakery.Version1) } func assertDischargeServerDischargesConditionForVersion(c *gc.C, cond string, version bakery.Version) { called := 0 checker := func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { called++ c.Check(string(cav.Condition), gc.Equals, cond) return nil, nil } discharger := bakerytest.NewDischarger(nil) discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(checker) bKey, err := bakery.GenerateKey() c.Assert(err, gc.IsNil) m, err := bakery.NewMacaroon([]byte("root key"), []byte("id"), "location", version, nil) c.Assert(err, gc.IsNil) err = m.AddCaveat(context.TODO(), checkers.Caveat{ Location: discharger.Location(), Condition: cond, }, bKey, discharger) c.Assert(err, gc.IsNil) client := httpbakery.NewClient() ms, err := client.DischargeAll(context.TODO(), m) c.Assert(err, gc.IsNil) c.Check(ms, gc.HasLen, 2) c.Check(called, gc.Equals, 1) } func (s *ClientSuite) TestDoClosesBody(c *gc.C) { cn := closeNotifier{ closed: make(chan struct{}), } req, err := http.NewRequest("GET", "http://0.1.2.3/", cn) c.Assert(err, gc.IsNil) _, err = httpbakery.NewClient().Do(req) c.Assert(err, gc.NotNil) select { case <-cn.closed: case <-time.After(5 * time.Second): c.Fatalf("timed out waiting for request body to be closed") } } func (s *ClientSuite) TestWithNonSeekableBody(c *gc.C) { r := bytes.NewBufferString("hello") req, err := http.NewRequest("GET", "http://0.1.2.3/", r) c.Assert(err, gc.IsNil) _, err = httpbakery.NewClient().Do(req) c.Assert(err, gc.ErrorMatches, `request body is not seekable`) } func (s *ClientSuite) TestWithNonSeekableCloserBody(c *gc.C) { req, err := http.NewRequest("GET", "http://0.1.2.3/", readCloser{}) c.Assert(err, gc.IsNil) _, err = httpbakery.NewClient().Do(req) c.Assert(err, gc.ErrorMatches, `request body is not seekable`) } type readCloser struct { } func (r readCloser) Read(buf []byte) (int, error) { return 0, io.EOF } func (r readCloser) Close() error { return nil } type closeNotifier struct { closed chan struct{} } func (r closeNotifier) Read(buf []byte) (int, error) { return 0, io.EOF } func (r closeNotifier) Seek(offset int64, whence int) (int64, error) { return 0, nil } func (r closeNotifier) Close() error { close(r.closed) return nil } func (s *ClientSuite) TestDischargeServerWithMacaraqOnDischarge(c *gc.C) { locator := bakery.NewThirdPartyStore() var called [3]int // create the services from leaf discharger to primary // service so that each one can know the location // to discharge at. db1 := newBakery("loc", locator, nil) key2, h2 := newHTTPDischarger(db1, httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { called[2]++ if string(cav.Condition) != "is-ok" { return nil, fmt.Errorf("unrecognized caveat at srv2") } return nil, nil })) srv2 := httptest.NewServer(h2) defer srv2.Close() locator.AddInfo(srv2.URL, bakery.ThirdPartyInfo{ PublicKey: key2, Version: bakery.LatestVersion, }) db2 := newBakery("loc", locator, nil) key1, h1 := newHTTPDischarger(db2, httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { called[1]++ if _, err := db2.Checker.Auth(httpbakery.RequestMacaroons(req)...).Allow(testContext, testOp); err != nil { c.Logf("returning discharge required error") return nil, newDischargeRequiredError(serverHandlerParams{ bakery: db2, authLocation: srv2.URL, }, err, req) } if string(cav.Condition) != "is-ok" { return nil, fmt.Errorf("unrecognized caveat at srv1") } return nil, nil })) srv1 := httptest.NewServer(h1) defer srv1.Close() locator.AddInfo(srv1.URL, bakery.ThirdPartyInfo{ PublicKey: key1, Version: bakery.LatestVersion, }) b0 := newBakery("loc", locator, nil) srv0 := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b0, authLocation: srv1.URL, })) defer srv0.Close() // Make a client request. client := httpbakery.NewClient() req, err := http.NewRequest("GET", srv0.URL, nil) c.Assert(err, gc.IsNil) resp, err := client.Do(req) c.Assert(err, gc.IsNil) defer resp.Body.Close() assertResponse(c, resp, "done") c.Assert(called, gc.DeepEquals, [3]int{0, 2, 1}) } func (s *ClientSuite) TestTwoDischargesRequired(c *gc.C) { // Sometimes the first discharge won't be enough and we'll // need to discharge another one to get through another // layer of security. dischargeCount := 0 checker := func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { c.Check(string(cav.Condition), gc.Equals, "is-ok") dischargeCount++ return nil, nil } discharger := bakerytest.NewDischarger(nil) discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(checker) srv := s.serverRequiringMultipleDischarges(httpbakery.MaxDischargeRetries, discharger) defer srv.Close() // Create a client request. req, err := http.NewRequest("GET", srv.URL, nil) c.Assert(err, gc.IsNil) resp, err := httpbakery.NewClient().Do(req) c.Assert(err, gc.IsNil) defer resp.Body.Close() c.Assert(resp.StatusCode, gc.Equals, http.StatusOK) data, err := ioutil.ReadAll(resp.Body) c.Assert(err, gc.IsNil) c.Assert(string(data), gc.Equals, "ok") c.Assert(dischargeCount, gc.Equals, httpbakery.MaxDischargeRetries) } func (s *ClientSuite) TestTooManyDischargesRequired(c *gc.C) { checker := func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { return nil, nil } discharger := bakerytest.NewDischarger(nil) discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(checker) srv := s.serverRequiringMultipleDischarges(httpbakery.MaxDischargeRetries+1, discharger) defer srv.Close() // Create a client request. req, err := http.NewRequest("GET", srv.URL, nil) c.Assert(err, gc.IsNil) _, err = httpbakery.NewClient().Do(req) c.Assert(err, gc.ErrorMatches, `too many \(3\) discharge requests: foo`) } // multiDischargeServer returns a server that will require multiple // discharges when accessing its endpoints. The parameter // holds the total number of discharges that will be required. func (s *ClientSuite) serverRequiringMultipleDischarges(n int, discharger *bakerytest.Discharger) *httptest.Server { b := newBakery("loc", discharger, nil) return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if _, err := b.Checker.Auth(httpbakery.RequestMacaroons(req)...).Allow(context.TODO(), testOp); err == nil { w.Write([]byte("ok")) return } caveats := []checkers.Caveat{{ Location: discharger.Location(), Condition: "is-ok", }} if n--; n > 0 { // We've got more attempts to go, so add a first party caveat that // will cause the macaroon to fail verification and so trigger // another discharge-required error. caveats = append(caveats, checkers.Caveat{ Condition: fmt.Sprintf("error %d attempts left", n), }) } m, err := b.Oven.NewMacaroon(context.TODO(), bakery.LatestVersion, ages, caveats, testOp) if err != nil { panic(fmt.Errorf("cannot make new macaroon: %v", err)) } err = httpbakery.NewDischargeRequiredError(httpbakery.DischargeRequiredErrorParams{ OriginalError: errgo.New("foo"), Macaroon: m, }) httpbakery.WriteError(testContext, w, err) })) } func (s *ClientSuite) TestVersion0Generates407Status(c *gc.C) { m, err := bakery.NewMacaroon([]byte("root key"), []byte("id"), "location", bakery.Version0, nil) c.Assert(err, gc.IsNil) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { err := httpbakery.NewDischargeRequiredError(httpbakery.DischargeRequiredErrorParams{ Macaroon: m, }) httpbakery.WriteError(testContext, w, err) })) defer srv.Close() resp, err := http.Get(srv.URL) c.Assert(err, gc.IsNil) c.Assert(resp.StatusCode, gc.Equals, http.StatusProxyAuthRequired) } func (s *ClientSuite) TestVersion1Generates401Status(c *gc.C) { m, err := bakery.NewMacaroon([]byte("root key"), []byte("id"), "location", bakery.Version1, nil) c.Assert(err, gc.IsNil) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { err := httpbakery.NewDischargeRequiredError(httpbakery.DischargeRequiredErrorParams{ Macaroon: m, }) httpbakery.WriteError(testContext, w, err) })) defer srv.Close() req, err := http.NewRequest("GET", srv.URL, nil) c.Assert(err, gc.IsNil) req.Header.Set(httpbakery.BakeryProtocolHeader, "1") resp, err := http.DefaultClient.Do(req) c.Assert(err, gc.IsNil) c.Assert(resp.StatusCode, gc.Equals, http.StatusUnauthorized) c.Assert(resp.Header.Get("WWW-Authenticate"), gc.Equals, "Macaroon") } func newHTTPDischarger(b *bakery.Bakery, checker httpbakery.ThirdPartyCaveatChecker) (bakery.PublicKey, http.Handler) { mux := http.NewServeMux() d := httpbakery.NewDischarger(httpbakery.DischargerParams{ Checker: checker, Key: b.Oven.Key(), }) d.AddMuxHandlers(mux, "/") return b.Oven.Key().Public, mux } func (s *ClientSuite) TestMacaroonCookieName(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() checked := make(map[string]bool) checker := checkers.New(nil) checker.Namespace().Register("testns", "") checker.Register("once", "testns", func(ctx context.Context, _, arg string) error { if checked[arg] { return errgo.Newf("caveat %q has already been checked once", arg) } checked[arg] = true return nil }) b := newBakery("loc", nil, checker) // We arrange things so that although we use the same client // (with the same cookie jar), the macaroon verification only // succeeds once, so the client always fetches a new macaroon. caveatSeq := 0 cookieName := "" ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, mutateError: func(e *httpbakery.Error) { e.Info.CookieNameSuffix = cookieName e.Info.MacaroonPath = "/" }, caveats: func() []checkers.Caveat { caveatSeq++ return []checkers.Caveat{{ Condition: fmt.Sprintf("once %d", caveatSeq), }} }, })) defer ts.Close() client := httpbakery.NewClient() doRequest := func() { req, err := http.NewRequest("GET", ts.URL+"/foo/bar/", nil) c.Assert(err, gc.IsNil) resp, err := client.Do(req) c.Assert(err, gc.IsNil) assertResponse(c, resp, "done") } assertCookieNames := func(names ...string) { u, err := url.Parse(ts.URL) c.Assert(err, gc.IsNil) sort.Strings(names) var gotNames []string for _, c := range client.Jar.Cookies(u) { gotNames = append(gotNames, c.Name) } sort.Strings(gotNames) c.Assert(gotNames, jc.DeepEquals, names) } cookieName = "foo" doRequest() assertCookieNames("macaroon-foo") // Another request with the same cookie name should // overwrite the old cookie. doRequest() assertCookieNames("macaroon-foo") // A subsequent request with a different cookie name // should create a new cookie, but the old one will still // be around. cookieName = "bar" doRequest() assertCookieNames("macaroon-foo", "macaroon-bar") } func (s *ClientSuite) TestMacaroonCookiePath(c *gc.C) { b := newBakery("loc", nil, nil) cookiePath := "" ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, mutateError: func(e *httpbakery.Error) { e.Info.MacaroonPath = cookiePath }, })) defer ts.Close() var client *httpbakery.Client doRequest := func() { req, err := http.NewRequest("GET", ts.URL+"/foo/bar/", nil) c.Assert(err, gc.IsNil) client = httpbakery.NewClient() resp, err := client.Do(req) c.Assert(err, gc.IsNil) assertResponse(c, resp, "done") } assertCookieCount := func(path string, n int) { u, err := url.Parse(ts.URL + path) c.Assert(err, gc.IsNil) c.Assert(client.Jar.Cookies(u), gc.HasLen, n) } cookiePath = "" c.Logf("- cookie path %q", cookiePath) doRequest() assertCookieCount("", 0) assertCookieCount("/foo", 0) assertCookieCount("/foo", 0) assertCookieCount("/foo/", 0) assertCookieCount("/foo/bar/", 1) assertCookieCount("/foo/bar/baz", 1) cookiePath = "/foo/" c.Logf("- cookie path %q", cookiePath) doRequest() assertCookieCount("", 0) assertCookieCount("/foo", 0) assertCookieCount("/foo/", 1) assertCookieCount("/foo/bar/", 1) assertCookieCount("/foo/bar/baz", 1) cookiePath = "/foo" c.Logf("- cookie path %q", cookiePath) doRequest() assertCookieCount("", 0) assertCookieCount("/bar", 0) assertCookieCount("/foo", 1) assertCookieCount("/foo/", 1) assertCookieCount("/foo/bar/", 1) assertCookieCount("/foo/bar/baz", 1) cookiePath = "../" c.Logf("- cookie path %q", cookiePath) doRequest() assertCookieCount("", 0) assertCookieCount("/bar", 0) assertCookieCount("/foo", 0) assertCookieCount("/foo/", 1) assertCookieCount("/foo/bar/", 1) assertCookieCount("/foo/bar/baz", 1) cookiePath = "../bar" c.Logf("- cookie path %q", cookiePath) doRequest() assertCookieCount("", 0) assertCookieCount("/bar", 0) assertCookieCount("/foo", 0) assertCookieCount("/foo/", 0) assertCookieCount("/foo/bar/", 1) assertCookieCount("/foo/bar/baz", 1) assertCookieCount("/foo/baz", 0) assertCookieCount("/foo/baz/", 0) assertCookieCount("/foo/baz/bar", 0) cookiePath = "/" c.Logf("- cookie path %q", cookiePath) doRequest() assertCookieCount("", 1) assertCookieCount("/bar", 1) assertCookieCount("/foo", 1) assertCookieCount("/foo/", 1) assertCookieCount("/foo/bar/", 1) assertCookieCount("/foo/bar/baz", 1) } func (s *ClientSuite) TestThirdPartyDischargeRefused(c *gc.C) { d := bakerytest.NewDischarger(nil) d.Checker = bakerytest.ConditionParser(func(cond, arg string) ([]checkers.Caveat, error) { return nil, errgo.New("boo! cond " + cond) }) defer d.Close() // Create a target service. b := newBakery("loc", d, nil) ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: d.Location(), })) defer ts.Close() // Create a client request. req, err := http.NewRequest("GET", ts.URL, nil) c.Assert(err, gc.IsNil) client := httpbakery.NewClient() // Make the request to the server. resp, err := client.Do(req) c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httpbakery.DischargeError)(nil)) c.Assert(err, gc.ErrorMatches, `cannot get discharge from ".*": third party refused discharge: cannot discharge: boo! cond is-ok`) c.Assert(resp, gc.IsNil) } func (s *ClientSuite) TestDischargeWithInteractionRequiredError(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() d.Checker = bakerytest.ConditionParser(func(cond, arg string) ([]checkers.Caveat, error) { return nil, &httpbakery.Error{ Code: httpbakery.ErrInteractionRequired, Message: "interaction required", Info: &httpbakery.ErrorInfo{ LegacyVisitURL: "http://0.1.2.3/", LegacyWaitURL: "http://0.1.2.3/", }, } }) // Create a target service. b := newBakery("loc", d, nil) ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: d.Location(), })) defer ts.Close() // Create a client request. req, err := http.NewRequest("GET", ts.URL, nil) c.Assert(err, gc.IsNil) errCannotVisit := errgo.New("cannot visit") client := httpbakery.NewClient() client.AddInteractor(legacyInteractor{ kind: httpbakery.WebBrowserInteractionKind, legacyInteract: func(ctx context.Context, client *httpbakery.Client, location string, visitURL *url.URL) error { return errCannotVisit }, }) // Make the request to the server. resp, err := client.Do(req) c.Assert(err, gc.ErrorMatches, `cannot get discharge from "https://.*": cannot start interactive session: cannot visit`) c.Assert(httpbakery.IsInteractionError(errgo.Cause(err)), gc.Equals, true) ierr, ok := errgo.Cause(err).(*httpbakery.InteractionError) c.Assert(ok, gc.Equals, true) c.Assert(errgo.Cause(ierr.Reason), gc.Equals, errCannotVisit) c.Assert(resp, gc.IsNil) } var interactionRequiredMethodsTests = []struct { about string methods map[string]interface{} interactors []httpbakery.Interactor expectInteractCalls int expectMethod string expectError string }{{ about: "single method", methods: map[string]interface{}{ "test-interactor": "interaction-data", }, interactors: []httpbakery.Interactor{ testInteractor("test-interactor"), }, expectInteractCalls: 1, expectMethod: "test-interactor", }, { about: "two methods, first one not used", methods: map[string]interface{}{ "test-interactor": "interaction-data", }, interactors: []httpbakery.Interactor{ testInteractor("other-interactor"), testInteractor("test-interactor"), }, expectInteractCalls: 1, expectMethod: "test-interactor", }, { about: "two methods, first one takes precedence", methods: map[string]interface{}{ "test-interactor": "interaction-data", "other-interactor": "other-data", }, interactors: []httpbakery.Interactor{ testInteractor("other-interactor"), testInteractor("test-interactor"), }, expectInteractCalls: 1, expectMethod: "other-interactor", }, { about: "two methods, first one takes precedence", methods: map[string]interface{}{ "test-interactor": "interaction-data", "other-interactor": "other-data", }, interactors: []httpbakery.Interactor{ testInteractor("test-interactor"), testInteractor("other-interactor"), }, expectInteractCalls: 1, expectMethod: "test-interactor", }, { about: "two methods, first one returns ErrInteractionMethodNotFound", methods: map[string]interface{}{ "test-interactor": "interaction-data", "other-interactor": "other-data", }, interactors: []httpbakery.Interactor{ interactor{ kind: "test-interactor", interact: func(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { return nil, errgo.WithCausef(nil, httpbakery.ErrInteractionMethodNotFound, "") }, }, testInteractor("other-interactor"), }, expectInteractCalls: 2, expectMethod: "other-interactor", }, { about: "interactor returns error", methods: map[string]interface{}{ "test-interactor": "interaction-data", "other-interactor": "other-data", }, interactors: []httpbakery.Interactor{ interactor{ kind: "test-interactor", interact: func(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { return nil, errgo.New("an error") }, }, testInteractor("other-interactor"), }, expectInteractCalls: 1, expectError: `cannot get discharge from "https://.*": an error`, }, { about: "no supported methods", methods: map[string]interface{}{ "a-interactor": "interaction-data", "b-interactor": "other-data", }, interactors: []httpbakery.Interactor{ testInteractor("c-interactor"), testInteractor("d-interactor"), }, expectError: `cannot get discharge from "https://.*": cannot start interactive session: no supported interaction method`, }, { about: "interactor returns nil token", methods: map[string]interface{}{ "test-interactor": "interaction-data", }, interactors: []httpbakery.Interactor{ interactor{ kind: "test-interactor", interact: func(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { return nil, nil }, }, }, expectInteractCalls: 1, expectError: `cannot get discharge from "https://.*": interaction method returned an empty token`, }, { about: "no interaction methods", methods: map[string]interface{}{ "test-interactor": "interaction-data", }, expectError: `cannot get discharge from "https://.*": cannot start interactive session: interaction required but not possible`, }} func (s *ClientSuite) TestInteractionRequiredMethods(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() checkedWithToken := 0 checkedWithoutToken := 0 interactionKind := "" var serverInteractionMethods map[string]interface{} d.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if token != nil { checkedWithToken++ if token.Kind != "test" { c.Errorf("invalid token value") return nil, errgo.Newf("unexpected token value") } interactionKind = string(token.Value) return nil, nil } checkedWithoutToken++ err := httpbakery.NewInteractionRequiredError(nil, req) for key, val := range serverInteractionMethods { err.SetInteraction(key, val) } return nil, err }) // Create a target service. b := newBakery("loc", d, nil) ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: d.Location(), })) defer ts.Close() for i, test := range interactionRequiredMethodsTests { c.Logf("\ntest %d: %s", i, test.about) interactCalls := 0 checkedWithToken = 0 checkedWithoutToken = 0 interactionKind = "" client := httpbakery.NewClient() for _, in := range test.interactors { in := in client.AddInteractor(interactor{ kind: in.Kind(), interact: func(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { interactCalls++ return in.Interact(ctx, client, location, interactionRequiredErr) }, }) c.Logf("added interactor %q", in.Kind()) } serverInteractionMethods = test.methods // Make the request to the server. req, err := http.NewRequest("GET", ts.URL, nil) c.Assert(err, gc.IsNil) resp, err := client.Do(req) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) c.Assert(resp, gc.IsNil) continue } c.Assert(err, gc.Equals, nil) assertResponse(c, resp, "done") c.Check(interactCalls, gc.Equals, test.expectInteractCalls) c.Check(checkedWithoutToken, gc.Equals, 1) c.Check(checkedWithToken, gc.Equals, 1) c.Check(interactionKind, gc.Equals, test.expectMethod) } } func testInteractor(kind string) httpbakery.Interactor { return interactor{ kind: kind, interact: func(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { return &httpbakery.DischargeToken{ Kind: "test", Value: []byte(kind), }, nil }, } } var dischargeWithVisitURLErrorTests = []struct { about string respond func(http.ResponseWriter) expectError string }{{ about: "error message", respond: func(w http.ResponseWriter) { httpReqServer.WriteError(testContext, w, fmt.Errorf("an error")) }, expectError: `cannot get discharge from ".*": failed to acquire macaroon after waiting: third party refused discharge: an error`, }, { about: "non-JSON error", respond: func(w http.ResponseWriter) { w.Write([]byte("bad response")) }, // TODO fix this unhelpful error message expectError: `cannot get discharge from ".*": cannot unmarshal wait response: unexpected content type text/plain; want application/json; content: bad response`, }} func (s *ClientSuite) TestDischargeWithVisitURLError(c *gc.C) { visitor := newVisitHandler(nil) visitSrv := httptest.NewServer(visitor) defer visitSrv.Close() d := bakerytest.NewDischarger(nil) d.Checker = bakerytest.ConditionParser(func(cond, arg string) ([]checkers.Caveat, error) { return nil, &httpbakery.Error{ Code: httpbakery.ErrInteractionRequired, Message: "interaction required", Info: &httpbakery.ErrorInfo{ LegacyVisitURL: visitSrv.URL + "/visit", LegacyWaitURL: visitSrv.URL + "/wait", }, } }) defer d.Close() // Create a target service. b := newBakery("loc", d, nil) ts := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: d.Location(), })) defer ts.Close() for i, test := range dischargeWithVisitURLErrorTests { c.Logf("test %d: %s", i, test.about) visitor.respond = test.respond client := httpbakery.NewClient() client.AddInteractor(legacyInteractor{ kind: httpbakery.WebBrowserInteractionKind, legacyInteract: func(ctx context.Context, client *httpbakery.Client, location string, visitURL *url.URL) error { resp, err := http.Get(visitURL.String()) if err != nil { return err } resp.Body.Close() return nil }, }) // Create a client request. req, err := http.NewRequest("GET", ts.URL, nil) c.Assert(err, gc.IsNil) // Make the request to the server. _, err = client.Do(req) c.Assert(err, gc.ErrorMatches, test.expectError) } } func (s *ClientSuite) TestMacaroonsForURL(c *gc.C) { // Create a target service. b := newBakery("loc", nil, nil) m1, err := b.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, testOp) c.Assert(err, gc.IsNil) m2, err := b.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, testOp) c.Assert(err, gc.IsNil) u1 := mustParseURL("http://0.1.2.3/") u2 := mustParseURL("http://0.1.2.3/x/") // Create some cookies with different cookie paths. jar, err := cookiejar.New(nil) c.Assert(err, gc.IsNil) httpbakery.SetCookie(jar, u1, nil, macaroon.Slice{m1.M()}) httpbakery.SetCookie(jar, u2, nil, macaroon.Slice{m2.M()}) jar.SetCookies(u1, []*http.Cookie{{ Name: "foo", Path: "/", Value: "ignored", }, { Name: "bar", Path: "/x/", Value: "ignored", }}) // Check that MacaroonsForURL behaves correctly // with both single and multiple cookies. mss := httpbakery.MacaroonsForURL(jar, u1) c.Assert(mss, gc.HasLen, 1) c.Assert(mss[0], gc.HasLen, 1) c.Assert(mss[0][0].Id(), jc.DeepEquals, m1.M().Id()) mss = httpbakery.MacaroonsForURL(jar, u2) checked := make(map[string]int) for _, ms := range mss { checked[string(ms[0].Id())]++ _, err := b.Checker.Auth(ms).Allow(testContext, testOp) c.Assert(err, gc.IsNil) } c.Assert(checked, jc.DeepEquals, map[string]int{ string(m1.M().Id()): 1, string(m2.M().Id()): 1, }) } func (s *ClientSuite) TestDoWithCustomError(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() // Create a target service. b := newBakery("loc", d, nil) type customError struct { CustomError *httpbakery.Error } callCount := 0 handler := func(w http.ResponseWriter, req *http.Request) { callCount++ if _, err := b.Checker.Auth(httpbakery.RequestMacaroons(req)...).Allow(testContext, testOp); err != nil { httprequest.WriteJSON(w, http.StatusTeapot, customError{ CustomError: newDischargeRequiredError(serverHandlerParams{ bakery: b, authLocation: d.Location(), }, err, req).(*httpbakery.Error), }) return } fmt.Fprintf(w, "hello there") } srv := httptest.NewServer(http.HandlerFunc(handler)) defer srv.Close() req, err := http.NewRequest("GET", srv.URL, nil) c.Assert(err, gc.IsNil) // First check that a normal request fails. resp, err := httpbakery.NewClient().Do(req) c.Assert(err, gc.IsNil) defer resp.Body.Close() c.Assert(resp.StatusCode, gc.Equals, http.StatusTeapot) c.Assert(callCount, gc.Equals, 1) callCount = 0 // Then check that a request with a custom error getter succeeds. errorGetter := func(resp *http.Response) error { if resp.StatusCode != http.StatusTeapot { return nil } data, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } var respErr customError if err := json.Unmarshal(data, &respErr); err != nil { panic(err) } return respErr.CustomError } resp, err = httpbakery.NewClient().DoWithCustomError(req, errorGetter) c.Assert(err, gc.IsNil) data, err := ioutil.ReadAll(resp.Body) c.Assert(err, gc.IsNil) c.Assert(string(data), gc.Equals, "hello there") c.Assert(callCount, gc.Equals, 2) } func (s *ClientSuite) TestHandleError(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() // Create a target service. b := newBakery("loc", d, nil) srv := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: "unknown", mutateError: nil, })) defer srv.Close() m, err := b.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, []checkers.Caveat{{ Location: d.Location(), Condition: "something", }}, testOp) c.Assert(err, gc.IsNil) u, err := url.Parse(srv.URL + "/bar") c.Assert(err, gc.IsNil) respErr := &httpbakery.Error{ Message: "an error", Code: httpbakery.ErrDischargeRequired, Info: &httpbakery.ErrorInfo{ Macaroon: m, MacaroonPath: "/foo", }, } client := httpbakery.NewClient() err = client.HandleError(testContext, u, respErr) c.Assert(err, gc.Equals, nil) // No cookies at the original location. c.Assert(client.Client.Jar.Cookies(u), gc.HasLen, 0) u.Path = "/foo" cookies := client.Client.Jar.Cookies(u) c.Assert(cookies, gc.HasLen, 1) // Check that we can actually make a request // with the newly acquired macaroon cookies. req, err := http.NewRequest("GET", srv.URL+"/foo", nil) c.Assert(err, gc.IsNil) resp, err := client.Do(req) c.Assert(err, gc.IsNil) resp.Body.Close() c.Assert(resp.StatusCode, gc.Equals, http.StatusOK) } func (s *ClientSuite) TestNewClientOldServer(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() // Create a target service. b := newBakery("loc", d, nil) srv := httptest.NewServer(serverHandler(serverHandlerParams{ bakery: b, authLocation: d.Location(), })) defer srv.Close() // Make the request to the server. client := httpbakery.NewClient() req, err := http.NewRequest("GET", srv.URL, nil) c.Assert(err, gc.IsNil) resp, err := client.Do(req) c.Assert(err, gc.IsNil) defer resp.Body.Close() assertResponse(c, resp, "done") } func (s *ClientSuite) TestHandleErrorDifferentError(c *gc.C) { berr := &httpbakery.Error{ Message: "an error", Code: "another code", } client := httpbakery.NewClient() err := client.HandleError(testContext, &url.URL{}, berr) c.Assert(err, gc.Equals, berr) } func (s *ClientSuite) TestNewCookieExpires(c *gc.C) { t := time.Now().Add(time.Minute) b := newBakery("loc", nil, nil) m, err := b.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, []checkers.Caveat{ checkers.TimeBeforeCaveat(t), }, testOp) c.Assert(err, gc.IsNil) cookie, err := httpbakery.NewCookie(nil, macaroon.Slice{m.M()}) c.Assert(err, gc.IsNil) c.Assert(cookie.Expires.Equal(t), gc.Equals, true, gc.Commentf("obtained: %s, expected: %s", cookie.Expires, t)) } func mustParseURL(s string) *url.URL { u, err := url.Parse(s) if err != nil { panic(err) } return u } type visitHandler struct { mux *http.ServeMux rendez chan struct{} respond func(w http.ResponseWriter) } func newVisitHandler(respond func(http.ResponseWriter)) *visitHandler { h := &visitHandler{ rendez: make(chan struct{}, 1), respond: respond, mux: http.NewServeMux(), } h.mux.HandleFunc("/visit", h.serveVisit) h.mux.HandleFunc("/wait", h.serveWait) return h } func (h *visitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { h.mux.ServeHTTP(w, req) } func (h *visitHandler) serveVisit(w http.ResponseWriter, req *http.Request) { h.rendez <- struct{}{} } func (h *visitHandler) serveWait(w http.ResponseWriter, req *http.Request) { <-h.rendez h.respond(w) } // assertResponse asserts that the given response is OK and contains // the expected body text. func assertResponse(c *gc.C, resp *http.Response, expectBody string) { body, err := ioutil.ReadAll(resp.Body) c.Assert(err, gc.IsNil) resp.Body.Close() c.Assert(resp.StatusCode, gc.Equals, http.StatusOK, gc.Commentf("body %q", body)) c.Assert(string(body), gc.DeepEquals, expectBody) resp.Body = ioutil.NopCloser(bytes.NewReader(body)) } type readCounter struct { io.ReadSeeker byteCount int } func (r *readCounter) Read(buf []byte) (int, error) { n, err := r.ReadSeeker.Read(buf) r.byteCount += n return n, err } func newBakery(location string, locator bakery.ThirdPartyLocator, checker bakery.FirstPartyCaveatChecker) *bakery.Bakery { if checker == nil { c := checkers.New(nil) c.Namespace().Register("testns", "") c.Register("is", "testns", checkIsSomething) checker = c } key, err := bakery.GenerateKey() if err != nil { panic(err) } return bakery.New(bakery.BakeryParams{ Location: location, Locator: locator, Key: key, Checker: checker, }) } func clientRequestWithCookies(c *gc.C, u string, macaroons macaroon.Slice) *http.Client { client := httpbakery.NewHTTPClient() url, err := url.Parse(u) c.Assert(err, gc.IsNil) err = httpbakery.SetCookie(client.Jar, url, nil, macaroons) c.Assert(err, gc.IsNil) return client } var httpReqServer = &httprequest.Server{ ErrorMapper: httpbakery.ErrorToResponse, } type serverHandlerParams struct { // bakery is used to check incoming requests // and macaroons for discharge-required errors. bakery *bakery.Bakery // authLocation holds the location of any 3rd party authorizer. // If this is non-empty, a 3rd party caveat will be added // addressed to this location. authLocation string // mutateError, if non-zero, will be called with any // discharge-required error before responding // to the client. mutateError func(*httpbakery.Error) // If caveats is non-nil, it is called to get caveats to // add to the returned macaroon. caveats func() []checkers.Caveat // alwaysReadBody specifies whether the handler should always read // the entire request body before returning. alwaysReadBody bool } // serverHandler returns an HTTP handler that checks macaroon authorization // and, if that succeeds, writes the string "done" followed by all the // data read from the request body. // It recognises the single first party caveat "is something". func serverHandler(hp serverHandlerParams) http.Handler { h := httpReqServer.HandleErrors(func(p httprequest.Params) error { if hp.alwaysReadBody { defer ioutil.ReadAll(p.Request.Body) } if _, err := hp.bakery.Checker.Auth(httpbakery.RequestMacaroons(p.Request)...).Allow(p.Context, testOp); err != nil { return newDischargeRequiredError(hp, err, p.Request) } fmt.Fprintf(p.Response, "done") // Special case: the no-body path doesn't return the body. if p.Request.URL.Path == "/no-body" { return nil } data, err := ioutil.ReadAll(p.Request.Body) if err != nil { panic(fmt.Errorf("cannot read body: %v", err)) } if len(data) > 0 { fmt.Fprintf(p.Response, " %s", data) } return nil }) return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { h(w, req, nil) }) } // newDischargeRequiredError returns a discharge-required error holding // a newly minted macaroon referencing the original check error // checkErr. If hp.authLocation is non-empty, the issued macaroon will // contain an "is-ok" third party caveat addressed to that location. func newDischargeRequiredError(hp serverHandlerParams, checkErr error, req *http.Request) error { var caveats []checkers.Caveat if hp.authLocation != "" { caveats = []checkers.Caveat{{ Location: hp.authLocation, Condition: "is-ok", }} } if hp.caveats != nil { caveats = append(caveats, hp.caveats()...) } m, err := hp.bakery.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, caveats, testOp) if err != nil { panic(fmt.Errorf("cannot make new macaroon: %v", err)) } err = httpbakery.NewDischargeRequiredError(httpbakery.DischargeRequiredErrorParams{ Macaroon: m, OriginalError: checkErr, Request: req, }) if hp.mutateError != nil { hp.mutateError(err.(*httpbakery.Error)) } return err } func isSomethingCaveat() checkers.Caveat { return checkers.Caveat{ Condition: "is something", Namespace: "testns", } } func checkIsSomething(ctx context.Context, _, arg string) error { if arg != "something" { return fmt.Errorf(`%v doesn't match "something"`, arg) } return nil } type interactor struct { kind string interact func(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) } func (i interactor) Kind() string { return i.kind } func (i interactor) Interact(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { return i.interact(ctx, client, location, interactionRequiredErr) } var ( _ httpbakery.Interactor = interactor{} _ httpbakery.Interactor = legacyInteractor{} _ httpbakery.LegacyInteractor = legacyInteractor{} ) type legacyInteractor struct { kind string interact func(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) legacyInteract func(ctx context.Context, client *httpbakery.Client, location string, visitURL *url.URL) error } func (i legacyInteractor) Kind() string { return i.kind } func (i legacyInteractor) Interact(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { if i.interact == nil { return nil, errgo.Newf("non-legacy interaction not supported") } return i.interact(ctx, client, location, interactionRequiredErr) } func (i legacyInteractor) LegacyInteract(ctx context.Context, client *httpbakery.Client, location string, visitURL *url.URL) error { if i.legacyInteract == nil { return errgo.Newf("legacy interaction not supported") } return i.legacyInteract(ctx, client, location, visitURL) } ��������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/client.go�����������������������0000644�0610621�0607500�00000056623�13172163311�030145� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "encoding/base64" "encoding/json" "fmt" "net/http" "net/http/cookiejar" "net/url" "strings" "github.com/juju/httprequest" "github.com/juju/loggo" "golang.org/x/net/context" "golang.org/x/net/context/ctxhttp" "golang.org/x/net/publicsuffix" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) var logger = loggo.GetLogger("httpbakery") var unmarshalError = httprequest.ErrorUnmarshaler(&Error{}) // maxDischargeRetries holds the maximum number of times that an HTTP // request will be retried after a third party caveat has been successfully // discharged. const maxDischargeRetries = 3 // DischargeError represents the error when a third party discharge // is refused by a server. type DischargeError struct { // Reason holds the underlying remote error that caused the // discharge to fail. Reason *Error } func (e *DischargeError) Error() string { return fmt.Sprintf("third party refused discharge: %v", e.Reason) } // IsDischargeError reports whether err is a *DischargeError. func IsDischargeError(err error) bool { _, ok := err.(*DischargeError) return ok } // InteractionError wraps an error returned by a call to visitWebPage. type InteractionError struct { // Reason holds the actual error returned from visitWebPage. Reason error } func (e *InteractionError) Error() string { return fmt.Sprintf("cannot start interactive session: %v", e.Reason) } // IsInteractionError reports whether err is an *InteractionError. func IsInteractionError(err error) bool { _, ok := err.(*InteractionError) return ok } // NewHTTPClient returns an http.Client that ensures // that headers are sent to the server even when the // server redirects a GET request. The returned client // also contains an empty in-memory cookie jar. // // See https://github.com/golang/go/issues/4677 func NewHTTPClient() *http.Client { c := *http.DefaultClient c.CheckRedirect = func(req *http.Request, via []*http.Request) error { if len(via) >= 10 { return fmt.Errorf("too many redirects") } if len(via) == 0 { return nil } for attr, val := range via[0].Header { if attr == "Cookie" { // Cookies are added automatically anyway. continue } if _, ok := req.Header[attr]; !ok { req.Header[attr] = val } } return nil } jar, err := cookiejar.New(&cookiejar.Options{ PublicSuffixList: publicsuffix.List, }) if err != nil { panic(err) } c.Jar = &cookieLogger{jar} return &c } // Client holds the context for making HTTP requests // that automatically acquire and discharge macaroons. type Client struct { // Client holds the HTTP client to use. It should have a cookie // jar configured, and when redirecting it should preserve the // headers (see NewHTTPClient). *http.Client // InteractionMethods holds a slice of supported interaction // methods, with preferred methods earlier in the slice. // On receiving an interaction-required error when discharging, // the Kind method of each Interactor in turn will be called // and, if the error indicates that the interaction kind is supported, // the Interact method will be called to complete the discharge. InteractionMethods []Interactor // Key holds the client's key. If set, the client will try to // discharge third party caveats with the special location // "local" by using this key. See bakery.DischargeAllWithKey and // bakery.LocalThirdPartyCaveat for more information Key *bakery.KeyPair } // An Interactor represents a way of persuading a discharger // that it should grant a discharge macaroon. type Interactor interface { // Kind returns the interaction method name. This corresponds to the // key in the Error.InteractionMethods type. Kind() string // Interact performs the interaction, and returns a token that can be // used to acquire the discharge macaroon. The location provides // the third party caveat location to make it possible to use // relative URLs. // // If the given interaction isn't supported by the client for // the given location, it may return an error with an // ErrInteractionMethodNotFound cause which will cause the // interactor to be ignored that time. Interact(ctx context.Context, client *Client, location string, interactionRequiredErr *Error) (*DischargeToken, error) } // DischargeToken holds a token that is intended // to persuade a discharger to discharge a third // party caveat. type DischargeToken struct { // Kind holds the kind of the token. By convention this // matches the name of the interaction method used to // obtain the token, but that's not required. Kind string `json:"kind"` // Value holds the value of the token. Value []byte `json:"value"` } // LegacyInteractor may optionally be implemented by Interactor // implementations that implement the legacy interaction-required // error protocols. type LegacyInteractor interface { // LegacyInteract implements the "visit" half of a legacy discharge // interaction. The "wait" half will be implemented by httpbakery. // The location is the location specified by the third party // caveat. LegacyInteract(ctx context.Context, client *Client, location string, visitURL *url.URL) error } // NewClient returns a new Client containing an HTTP client // created with NewHTTPClient and leaves all other fields zero. func NewClient() *Client { return &Client{ Client: NewHTTPClient(), } } // AddInteractor is a convenience method that appends the given // interactor to c.InteractionMethods. // For example, to enable web-browser interaction on // a client c, do: // // c.AddInteractor(httpbakery.WebBrowserWindowInteractor) func (c *Client) AddInteractor(i Interactor) { c.InteractionMethods = append(c.InteractionMethods, i) } // DischargeAll attempts to acquire discharge macaroons for all the // third party caveats in m, and returns a slice containing all // of them bound to m. // // If the discharge fails because a third party refuses to discharge a // caveat, the returned error will have a cause of type *DischargeError. // If the discharge fails because visitWebPage returns an error, // the returned error will have a cause of *InteractionError. // // The returned macaroon slice will not be stored in the client // cookie jar (see SetCookie if you need to do that). func (c *Client) DischargeAll(ctx context.Context, m *bakery.Macaroon) (macaroon.Slice, error) { return bakery.DischargeAllWithKey(ctx, m, c.AcquireDischarge, c.Key) } // DischargeAllUnbound is like DischargeAll except that it does not // bind the resulting macaroons. func (c *Client) DischargeAllUnbound(ctx context.Context, ms bakery.Slice) (bakery.Slice, error) { return ms.DischargeAll(ctx, c.AcquireDischarge, c.Key) } // Do is like DoWithContext, except the context is automatically derived. // If using go version 1.7 or later the context will be taken from the // given request, otherwise context.Background() will be used. func (c *Client) Do(req *http.Request) (*http.Response, error) { return c.do(contextFromRequest(req), req, nil) } // DoWithContext sends the given HTTP request and returns its response. // If the request fails with a discharge-required error, any required // discharge macaroons will be acquired, and the request will be repeated // with those attached. // // If the required discharges were refused by a third party, an error // with a *DischargeError cause will be returned. // // If interaction is required by the user, the client's InteractionMethods // will be used to perform interaction. An error // with a *InteractionError cause will be returned if this interaction // fails. See WebBrowserWindowInteractor for a possible implementation of // an Interactor for an interaction method. // // DoWithContext may add headers to req.Header. func (c *Client) DoWithContext(ctx context.Context, req *http.Request) (*http.Response, error) { return c.do(ctx, req, nil) } // DoWithCustomError is like Do except it allows a client // to specify a custom error function, getError, which is called on the // HTTP response and may return a non-nil error if the response holds an // error. If the cause of the returned error is a *Error value and its // code is ErrDischargeRequired, the macaroon in its Info field will be // discharged and the request will be repeated with the discharged // macaroon. If getError returns nil, it should leave the response body // unchanged. // // If getError is nil, DefaultGetError will be used. // // This method can be useful when dealing with APIs that // return their errors in a format incompatible with Error, but the // need for it should be avoided when creating new APIs, // as it makes the endpoints less amenable to generic tools. func (c *Client) DoWithCustomError(req *http.Request, getError func(resp *http.Response) error) (*http.Response, error) { return c.do(contextFromRequest(req), req, getError) } func (c *Client) do(ctx context.Context, req *http.Request, getError func(resp *http.Response) error) (*http.Response, error) { logger.Debugf("client do %s %s {", req.Method, req.URL) resp, err := c.do1(ctx, req, getError) logger.Debugf("} -> error %#v", err) return resp, err } func (c *Client) do1(ctx context.Context, req *http.Request, getError func(resp *http.Response) error) (*http.Response, error) { if getError == nil { getError = DefaultGetError } if c.Client.Jar == nil { return nil, errgo.New("no cookie jar supplied in HTTP client") } rreq, ok := newRetryableRequest(req) if !ok { return nil, fmt.Errorf("request body is not seekable") } defer rreq.close() req.Header.Set(BakeryProtocolHeader, fmt.Sprint(bakery.LatestVersion)) // Make several attempts to do the request, because we might have // to get through several layers of security. We only retry if // we get a DischargeRequiredError and succeed in discharging // the macaroon in it. retry := 0 for { resp, err := c.do2(ctx, rreq, getError) if err == nil || !isDischargeRequiredError(err) { return resp, errgo.Mask(err, errgo.Any) } if retry++; retry > maxDischargeRetries { return nil, errgo.NoteMask(err, fmt.Sprintf("too many (%d) discharge requests", retry-1), errgo.Any) } if err1 := c.HandleError(ctx, req.URL, err); err1 != nil { return nil, errgo.Mask(err1, errgo.Any) } logger.Debugf("discharge succeeded; retry %d", retry) } } func (c *Client) do2(ctx context.Context, req *retryableRequest, getError func(resp *http.Response) error) (*http.Response, error) { if err := req.try(); err != nil { return nil, errgo.Mask(err) } httpResp, err := ctxhttp.Do(ctx, c.Client, req.req) if err != nil { return nil, errgo.Mask(err, errgo.Any) } err = getError(httpResp) if err == nil { logger.Infof("HTTP response OK (status %v)", httpResp.Status) return httpResp, nil } httpResp.Body.Close() return nil, errgo.Mask(err, errgo.Any) } // HandleError tries to resolve the given error, which should be a // response to the given URL, by discharging any macaroon contained in // it. That is, if the error cause is an *Error and its code is // ErrDischargeRequired, then it will try to discharge // err.Info.Macaroon. If the discharge succeeds, the discharged macaroon // will be saved to the client's cookie jar and ResolveError will return // nil. // // For any other kind of error, the original error will be returned. func (c *Client) HandleError(ctx context.Context, reqURL *url.URL, err error) error { respErr, ok := errgo.Cause(err).(*Error) if !ok { return err } if respErr.Code != ErrDischargeRequired { return respErr } if respErr.Info == nil || respErr.Info.Macaroon == nil { return errgo.New("no macaroon found in discharge-required response") } mac := respErr.Info.Macaroon macaroons, err := bakery.DischargeAllWithKey(ctx, mac, c.AcquireDischarge, c.Key) if err != nil { return errgo.Mask(err, errgo.Any) } var cookiePath string if path := respErr.Info.MacaroonPath; path != "" { relURL, err := parseURLPath(path) if err != nil { logger.Warningf("ignoring invalid path in discharge-required response: %v", err) } else { cookiePath = reqURL.ResolveReference(relURL).Path } } // TODO use a namespace taken from the error response. cookie, err := NewCookie(nil, macaroons) if err != nil { return errgo.Notef(err, "cannot make cookie") } cookie.Path = cookiePath if name := respErr.Info.CookieNameSuffix; name != "" { cookie.Name = "macaroon-" + name } c.Jar.SetCookies(reqURL, []*http.Cookie{cookie}) return nil } // DefaultGetError is the default error unmarshaler used by Client.Do. func DefaultGetError(httpResp *http.Response) error { if httpResp.StatusCode != http.StatusProxyAuthRequired && httpResp.StatusCode != http.StatusUnauthorized { return nil } // Check for the new protocol discharge error. if httpResp.StatusCode == http.StatusUnauthorized && httpResp.Header.Get("WWW-Authenticate") != "Macaroon" { return nil } if httpResp.Header.Get("Content-Type") != "application/json" { return nil } var resp Error if err := json.NewDecoder(httpResp.Body).Decode(&resp); err != nil { return fmt.Errorf("cannot unmarshal error response: %v", err) } return &resp } func parseURLPath(path string) (*url.URL, error) { u, err := url.Parse(path) if err != nil { return nil, errgo.Mask(err) } if u.Scheme != "" || u.Opaque != "" || u.User != nil || u.Host != "" || u.RawQuery != "" || u.Fragment != "" { return nil, errgo.Newf("URL path %q is not clean", path) } return u, nil } // NewCookie takes a slice of macaroons and returns them // encoded as a cookie. The slice should contain a single primary // macaroon in its first element, and any discharges after that. // // The given namespace specifies the first party caveat namespace, // used for deriving the expiry time of the cookie. func NewCookie(ns *checkers.Namespace, ms macaroon.Slice) (*http.Cookie, error) { if len(ms) == 0 { return nil, errgo.New("no macaroons in cookie") } // TODO(rog) marshal cookie as binary if version allows. data, err := json.Marshal(ms) if err != nil { return nil, errgo.Notef(err, "cannot marshal macaroons") } cookie := &http.Cookie{ Name: fmt.Sprintf("macaroon-%x", ms[0].Signature()), Value: base64.StdEncoding.EncodeToString(data), } cookie.Expires, _ = checkers.MacaroonsExpiryTime(ns, ms) // TODO(rog) other fields. return cookie, nil } // SetCookie sets a cookie for the given URL on the given cookie jar // that will holds the given macaroon slice. The macaroon slice should // contain a single primary macaroon in its first element, and any // discharges after that. // // The given namespace specifies the first party caveat namespace, // used for deriving the expiry time of the cookie. func SetCookie(jar http.CookieJar, url *url.URL, ns *checkers.Namespace, ms macaroon.Slice) error { cookie, err := NewCookie(ns, ms) if err != nil { return errgo.Mask(err) } jar.SetCookies(url, []*http.Cookie{cookie}) return nil } // MacaroonsForURL returns any macaroons associated with the // given URL in the given cookie jar. func MacaroonsForURL(jar http.CookieJar, u *url.URL) []macaroon.Slice { return cookiesToMacaroons(jar.Cookies(u)) } func appendURLElem(u, elem string) string { if strings.HasSuffix(u, "/") { return u + elem } return u + "/" + elem } // AcquireDischarge implements DischargeAcquirer by requesting a discharge // macaroon from the caveat location as an HTTP URL. func (c *Client) AcquireDischarge(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { m, err := c.acquireDischarge(ctx, cav, payload, nil) if err == nil { return m, nil } cause, ok := errgo.Cause(err).(*Error) if !ok { return nil, errgo.NoteMask(err, "cannot acquire discharge", IsInteractionError) } if cause.Code != ErrInteractionRequired { return nil, &DischargeError{ Reason: cause, } } if cause.Info == nil { return nil, errgo.Notef(err, "interaction-required response with no info") } // Make sure the location has a trailing slash so that // the relative URL calculations work correctly even when // cav.Location doesn't have a trailing slash. loc := appendURLElem(cav.Location, "") token, m, err := c.interact(ctx, loc, cause, payload) if err != nil { return nil, errgo.Mask(err, IsDischargeError, IsInteractionError) } if m != nil { // We've acquired the macaroon directly via legacy interaction. return m, nil } // Try to acquire the discharge again, but this time with // the token acquired by the interaction method. m, err = c.acquireDischarge(ctx, cav, payload, token) if err != nil { return nil, errgo.Mask(err, IsDischargeError, IsInteractionError) } return m, nil } // acquireDischarge is like AcquireDischarge except that it also // takes a token acquired from an interaction method. func (c *Client) acquireDischarge( ctx context.Context, cav macaroon.Caveat, payload []byte, token *DischargeToken, ) (*bakery.Macaroon, error) { dclient := newDischargeClient(cav.Location, c) var req dischargeRequest req.Id, req.Id64 = maybeBase64Encode(cav.Id) if token != nil { req.Token, req.Token64 = maybeBase64Encode(token.Value) req.TokenKind = token.Kind } req.Caveat = base64.RawURLEncoding.EncodeToString(payload) resp, err := dclient.Discharge(ctx, &req) if err == nil { return resp.Macaroon, nil } return nil, errgo.Mask(err, errgo.Any) } // interact gathers a macaroon by directing the user to interact with a // web page. The irErr argument holds the interaction-required // error response. func (c *Client) interact(ctx context.Context, location string, irErr *Error, payload []byte) (*DischargeToken, *bakery.Macaroon, error) { if len(c.InteractionMethods) == 0 { return nil, nil, &InteractionError{ Reason: errgo.New("interaction required but not possible"), } } if irErr.Info.InteractionMethods == nil && irErr.Info.LegacyVisitURL != "" { // It's an old-style error; deal with it differently. m, err := c.legacyInteract(ctx, location, irErr) if err != nil { return nil, nil, errgo.Mask(err, IsDischargeError, IsInteractionError) } return nil, m, nil } for _, interactor := range c.InteractionMethods { logger.Infof("checking interaction method %q", interactor.Kind()) if _, ok := irErr.Info.InteractionMethods[interactor.Kind()]; ok { logger.Infof("found possible interaction method %q", interactor.Kind()) token, err := interactor.Interact(ctx, c, location, irErr) if err != nil { if errgo.Cause(err) == ErrInteractionMethodNotFound { continue } return nil, nil, errgo.Mask(err, IsDischargeError, IsInteractionError) } if token == nil { return nil, nil, errgo.New("interaction method returned an empty token") } return token, nil, nil } else { logger.Infof("interaction method %q not found in %#v", interactor.Kind(), irErr.Info.InteractionMethods) } } return nil, nil, &InteractionError{ Reason: errgo.Newf("no supported interaction method"), } } func (c *Client) legacyInteract(ctx context.Context, location string, irErr *Error) (*bakery.Macaroon, error) { visitURL, err := relativeURL(location, irErr.Info.LegacyVisitURL) if err != nil { return nil, errgo.Mask(err) } waitURL, err := relativeURL(location, irErr.Info.LegacyWaitURL) if err != nil { return nil, errgo.Mask(err) } methodURLs := map[string]*url.URL{ "interactive": visitURL, } if len(c.InteractionMethods) > 1 || c.InteractionMethods[0].Kind() != WebBrowserInteractionKind { // We have several possible methods or we only support a non-window // method, so we need to fetch the possible methods supported by the discharger. methodURLs = legacyGetInteractionMethods(ctx, c, visitURL) } for _, interactor := range c.InteractionMethods { kind := interactor.Kind() if kind == WebBrowserInteractionKind { // This is the old name for browser-window interaction. kind = "interactive" } interactor, ok := interactor.(LegacyInteractor) if !ok { // Legacy interaction mode isn't supported. continue } visitURL, ok := methodURLs[kind] if !ok { continue } visitURL, err := relativeURL(location, visitURL.String()) if err != nil { return nil, errgo.Mask(err) } if err := interactor.LegacyInteract(ctx, c, location, visitURL); err != nil { return nil, &InteractionError{ Reason: errgo.Mask(err, errgo.Any), } } return waitForMacaroon(ctx, c, waitURL) } return nil, &InteractionError{ Reason: errgo.Newf("no methods supported"), } } // waitForMacaroon returns a macaroon from a legacy wait endpoint. func waitForMacaroon(ctx context.Context, client *Client, waitURL *url.URL) (*bakery.Macaroon, error) { httpResp, err := ctxhttp.Get(ctx, client.Client, waitURL.String()) if err != nil { return nil, errgo.Notef(err, "cannot get %q", waitURL) } defer httpResp.Body.Close() if httpResp.StatusCode != http.StatusOK { err := unmarshalError(httpResp) if err1, ok := err.(*Error); ok { err = &DischargeError{ Reason: err1, } } return nil, errgo.NoteMask(err, "failed to acquire macaroon after waiting", errgo.Any) } var resp WaitResponse if err := httprequest.UnmarshalJSONResponse(httpResp, &resp); err != nil { return nil, errgo.Notef(err, "cannot unmarshal wait response") } return resp.Macaroon, nil } // relativeURL returns newPath relative to an original URL. func relativeURL(base, new string) (*url.URL, error) { if new == "" { return nil, errgo.Newf("empty URL") } baseURL, err := url.Parse(base) if err != nil { return nil, errgo.Notef(err, "cannot parse URL") } newURL, err := url.Parse(new) if err != nil { return nil, errgo.Notef(err, "cannot parse URL") } return baseURL.ResolveReference(newURL), nil } // TODO(rog) move a lot of the code below into server.go, as it's // much more about server side than client side. // MacaroonsHeader is the key of the HTTP header that can be used to provide a // macaroon for request authorization. const MacaroonsHeader = "Macaroons" // RequestMacaroons returns any collections of macaroons from the header and // cookies found in the request. By convention, each slice will contain a // primary macaroon followed by its discharges. func RequestMacaroons(req *http.Request) []macaroon.Slice { mss := cookiesToMacaroons(req.Cookies()) for _, h := range req.Header[MacaroonsHeader] { ms, err := decodeMacaroonSlice(h) if err != nil { logger.Errorf("cannot retrieve macaroons from header: %v", err) } else { mss = append(mss, ms) } } return mss } // cookiesToMacaroons returns a slice of any macaroons found // in the given slice of cookies. func cookiesToMacaroons(cookies []*http.Cookie) []macaroon.Slice { var mss []macaroon.Slice for _, cookie := range cookies { if !strings.HasPrefix(cookie.Name, "macaroon-") { continue } ms, err := decodeMacaroonSlice(cookie.Value) if err != nil { logger.Errorf("cannot retrieve macaroons from cookie: %v", err) continue } mss = append(mss, ms) } return mss } // decodeMacaroonSlice decodes a base64-JSON-encoded slice of macaroons from // the given string. func decodeMacaroonSlice(value string) (macaroon.Slice, error) { data, err := macaroon.Base64Decode([]byte(value)) if err != nil { return nil, errgo.NoteMask(err, "cannot base64-decode macaroons") } // TODO(rog) accept binary encoded macaroon cookies. var ms macaroon.Slice if err := json.Unmarshal(data, &ms); err != nil { return nil, errgo.NoteMask(err, "cannot unmarshal macaroons") } return ms, nil } type cookieLogger struct { http.CookieJar } func (j *cookieLogger) SetCookies(u *url.URL, cookies []*http.Cookie) { logger.Debugf("%p setting %d cookies for %s", j.CookieJar, len(cookies), u) for i, c := range cookies { logger.Debugf("\t%d. path %s; name %s", i, c.Path, c.Name) } j.CookieJar.SetCookies(u, cookies) } �������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/checkers_test.go����������������0000644�0610621�0607500�00000013156�13172163311�031507� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery_test import ( "net" "net/http" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) type CheckersSuite struct{} var _ = gc.Suite(&CheckersSuite{}) type checkTest struct { caveat checkers.Caveat expectError string expectCause func(err error) bool } func caveatWithCondition(cond string) checkers.Caveat { return checkers.Caveat{ Condition: cond, } } var checkerTests = []struct { about string req *http.Request checks []checkTest }{{ about: "no host name declared", req: &http.Request{}, checks: []checkTest{{ caveat: httpbakery.ClientIPAddrCaveat(net.IP{0, 0, 0, 0}), expectError: `caveat "http:client-ip-addr 0.0.0.0" not satisfied: client has no remote address`, }, { caveat: httpbakery.ClientIPAddrCaveat(net.IP{127, 0, 0, 1}), expectError: `caveat "http:client-ip-addr 127.0.0.1" not satisfied: client has no remote address`, }, { caveat: caveatWithCondition("http:client-ip-addr badip"), expectError: `caveat "http:client-ip-addr badip" not satisfied: cannot parse IP address in caveat`, }}, }, { about: "IPv4 host name declared", req: &http.Request{ RemoteAddr: "127.0.0.1:1234", }, checks: []checkTest{{ caveat: httpbakery.ClientIPAddrCaveat(net.IP{127, 0, 0, 1}), }, { caveat: httpbakery.ClientIPAddrCaveat(net.IP{127, 0, 0, 1}.To16()), }, { caveat: caveatWithCondition("http:client-ip-addr ::ffff:7f00:1"), }, { caveat: httpbakery.ClientIPAddrCaveat(net.IP{127, 0, 0, 2}), expectError: `caveat "http:client-ip-addr 127.0.0.2" not satisfied: client IP address mismatch, got 127.0.0.1`, }, { caveat: httpbakery.ClientIPAddrCaveat(net.ParseIP("2001:4860:0:2001::68")), expectError: `caveat "http:client-ip-addr 2001:4860:0:2001::68" not satisfied: client IP address mismatch, got 127.0.0.1`, }}, }, { about: "IPv6 host name declared", req: &http.Request{ RemoteAddr: "[2001:4860:0:2001::68]:1234", }, checks: []checkTest{{ caveat: httpbakery.ClientIPAddrCaveat(net.ParseIP("2001:4860:0:2001::68")), }, { caveat: caveatWithCondition("http:client-ip-addr 2001:4860:0:2001:0::68"), }, { caveat: httpbakery.ClientIPAddrCaveat(net.ParseIP("2001:4860:0:2001::69")), expectError: `caveat "http:client-ip-addr 2001:4860:0:2001::69" not satisfied: client IP address mismatch, got 2001:4860:0:2001::68`, }, { caveat: httpbakery.ClientIPAddrCaveat(net.ParseIP("127.0.0.1")), expectError: `caveat "http:client-ip-addr 127.0.0.1" not satisfied: client IP address mismatch, got 2001:4860:0:2001::68`, }}, }, { about: "same client address, ipv4 request address", req: &http.Request{ RemoteAddr: "127.0.0.1:1324", }, checks: []checkTest{{ caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{ RemoteAddr: "127.0.0.1:1234", }), }, { caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{ RemoteAddr: "[::ffff:7f00:1]:1235", }), }, { caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{ RemoteAddr: "127.0.0.2:1234", }), expectError: `caveat "http:client-ip-addr 127.0.0.2" not satisfied: client IP address mismatch, got 127.0.0.1`, }, { caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{ RemoteAddr: "[::ffff:7f00:2]:1235", }), expectError: `caveat "http:client-ip-addr 127.0.0.2" not satisfied: client IP address mismatch, got 127.0.0.1`, }, { caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{}), expectError: `caveat "error client has no remote IP address" not satisfied: bad caveat`, }, { caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{ RemoteAddr: "bad", }), expectError: `caveat "error cannot parse host port in remote address: .*" not satisfied: bad caveat`, }, { caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{ RemoteAddr: "bad:56", }), expectError: `caveat "error invalid IP address in remote address \\"bad:56\\"" not satisfied: bad caveat`, }}, }, { about: "same client address, ipv6 request address", req: &http.Request{ RemoteAddr: "[2001:4860:0:2001:0::68]:1235", }, checks: []checkTest{{ caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{ RemoteAddr: "[2001:4860:0:2001:0::68]:1234", }), }, { caveat: httpbakery.SameClientIPAddrCaveat(&http.Request{ RemoteAddr: "127.0.0.2:1234", }), expectError: `caveat "http:client-ip-addr 127.0.0.2" not satisfied: client IP address mismatch, got 2001:4860:0:2001::68`, }}, }, { about: "request with no origin", req: &http.Request{}, checks: []checkTest{{ caveat: httpbakery.ClientOriginCaveat(""), }, { caveat: httpbakery.ClientOriginCaveat("somewhere"), }}, }, { about: "request with origin", req: &http.Request{ Header: http.Header{ "Origin": {"somewhere"}, }, }, checks: []checkTest{{ caveat: httpbakery.ClientOriginCaveat(""), expectError: `caveat "http:origin" not satisfied: request has invalid Origin header; got "somewhere"`, }, { caveat: httpbakery.ClientOriginCaveat("somewhere"), }}, }} func (s *CheckersSuite) TestCheckers(c *gc.C) { checker := httpbakery.NewChecker() for i, test := range checkerTests { c.Logf("test %d: %s", i, test.about) ctx := httpbakery.ContextWithRequest(testContext, test.req) for j, check := range test.checks { c.Logf("\tcheck %d", j) err := checker.CheckFirstPartyCaveat(ctx, checker.Namespace().ResolveCaveat(check.caveat).Condition) if check.expectError != "" { c.Assert(err, gc.ErrorMatches, check.expectError) if check.expectCause == nil { check.expectCause = errgo.Any } c.Assert(check.expectCause(errgo.Cause(err)), gc.Equals, true) } else { c.Assert(err, gc.IsNil) } } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/checkers.go���������������������0000644�0610621�0607500�00000011032�13172163311�030437� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "net" "net/http" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type httpRequestKey struct{} // ContextWithRequest returns the context with information from the // given request attached as context. This is used by the httpbakery // checkers (see RegisterCheckers for details). func ContextWithRequest(ctx context.Context, req *http.Request) context.Context { return context.WithValue(ctx, httpRequestKey{}, req) } func requestFromContext(ctx context.Context) *http.Request { req, _ := ctx.Value(httpRequestKey{}).(*http.Request) return req } const ( // CondClientIPAddr holds the first party caveat condition // that checks a client's IP address. CondClientIPAddr = "client-ip-addr" // CondClientOrigin holds the first party caveat condition that // checks a client's origin header. CondClientOrigin = "origin" ) // CheckersNamespace holds the URI of the HTTP checkers schema. const CheckersNamespace = "http" var allCheckers = map[string]checkers.Func{ CondClientIPAddr: ipAddrCheck, CondClientOrigin: clientOriginCheck, } // RegisterCheckers registers all the HTTP checkers with the given checker. // Current checkers include: // // client-ip-addr <ip-address> // // The client-ip-addr caveat checks that the HTTP request has // the given remote IP address. // // origin <name> // // The origin caveat checks that the HTTP Origin header has // the given value. func RegisterCheckers(c *checkers.Checker) { c.Namespace().Register(CheckersNamespace, "http") for cond, check := range allCheckers { c.Register(cond, CheckersNamespace, check) } } // NewChecker returns a new checker with the standard // and HTTP checkers registered in it. func NewChecker() *checkers.Checker { c := checkers.New(nil) RegisterCheckers(c) return c } // ipAddrCheck implements the IP client address checker // for an HTTP request. func ipAddrCheck(ctx context.Context, cond, args string) error { req := requestFromContext(ctx) if req == nil { return errgo.Newf("no IP address found in context") } ip := net.ParseIP(args) if ip == nil { return errgo.Newf("cannot parse IP address in caveat") } if req.RemoteAddr == "" { return errgo.Newf("client has no remote address") } reqIP, err := requestIPAddr(req) if err != nil { return errgo.Mask(err) } if !reqIP.Equal(ip) { return errgo.Newf("client IP address mismatch, got %s", reqIP) } return nil } // clientOriginCheck implements the Origin header checker // for an HTTP request. func clientOriginCheck(ctx context.Context, cond, args string) error { req := requestFromContext(ctx) if req == nil { return errgo.Newf("no origin found in context") } // Note that web browsers may not provide the origin header when it's // not a cross-site request with a GET method. There's nothing we // can do about that, so just allow all requests with an empty origin. if reqOrigin := req.Header.Get("Origin"); reqOrigin != "" && reqOrigin != args { return errgo.Newf("request has invalid Origin header; got %q", reqOrigin) } return nil } // SameClientIPAddrCaveat returns a caveat that will check that // the remote IP address is the same as that in the given HTTP request. func SameClientIPAddrCaveat(req *http.Request) checkers.Caveat { if req.RemoteAddr == "" { return checkers.ErrorCaveatf("client has no remote IP address") } ip, err := requestIPAddr(req) if err != nil { return checkers.ErrorCaveatf("%v", err) } return ClientIPAddrCaveat(ip) } // ClientIPAddrCaveat returns a caveat that will check whether the // client's IP address is as provided. func ClientIPAddrCaveat(addr net.IP) checkers.Caveat { if len(addr) != net.IPv4len && len(addr) != net.IPv6len { return checkers.ErrorCaveatf("bad IP address %d", []byte(addr)) } return httpCaveat(CondClientIPAddr, addr.String()) } // ClientOriginCaveat returns a caveat that will check whether the // client's Origin header in its HTTP request is as provided. func ClientOriginCaveat(origin string) checkers.Caveat { return httpCaveat(CondClientOrigin, origin) } func httpCaveat(cond, arg string) checkers.Caveat { return checkers.Caveat{ Condition: checkers.Condition(cond, arg), Namespace: CheckersNamespace, } } func requestIPAddr(req *http.Request) (net.IP, error) { reqHost, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { return nil, errgo.Newf("cannot parse host port in remote address: %v", err) } ip := net.ParseIP(reqHost) if ip == nil { return nil, errgo.Newf("invalid IP address in remote address %q", req.RemoteAddr) } return ip, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/browser.go����������������������0000644�0610621�0607500�00000014207�13172163311�030342� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httpbakery import ( "fmt" "net/http" "net/url" "os" "github.com/juju/httprequest" "github.com/juju/webbrowser" "golang.org/x/net/context" "golang.org/x/net/context/ctxhttp" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) const WebBrowserInteractionKind = "browser-window" // WaitTokenResponse holds the response type // returned, JSON-encoded, from the waitToken // URL passed to SetBrowserInteraction. type WaitTokenResponse struct { Kind string `json:"kind"` // Token holds the token value when it's well-formed utf-8 Token string `json:"token,omitempty"` // Token64 holds the token value, base64 encoded, when it's // not well-formed utf-8. Token64 string `json:"token64,omitempty"` } // WaitResponse holds the type that should be returned // by an HTTP response made to a LegacyWaitURL // (See the ErrorInfo type). type WaitResponse struct { Macaroon *bakery.Macaroon } // WebBrowserInteractionInfo holds the information // expected in the browser-window interaction // entry in an interaction-required error. type WebBrowserInteractionInfo struct { // VisitURL holds the URL to be visited in a web browser. VisitURL string // WaitTokenURL holds a URL that will block on GET // until the browser interaction has completed. // On success, the response is expected to hold a waitTokenResponse // in its body holding the token to be returned from the // Interact method. WaitTokenURL string } var ( _ Interactor = WebBrowserInteractor{} _ LegacyInteractor = WebBrowserInteractor{} ) // OpenWebBrowser opens a web browser at the // given URL. If the OS is not recognised, the URL // is just printed to standard output. func OpenWebBrowser(url *url.URL) error { err := webbrowser.Open(url) if err == nil { fmt.Fprintf(os.Stderr, "Opening an authorization web page in your browser.\n") fmt.Fprintf(os.Stderr, "If it does not open, please open this URL:\n%s\n", url) return nil } if err == webbrowser.ErrNoBrowser { fmt.Fprintf(os.Stderr, "Please open this URL in your browser to authorize:\n%s\n", url) return nil } return err } // SetWebBrowserInteraction adds information about web-browser-based // interaction to the given error, which should be an // interaction-required error that's about to be returned from a // discharge request. // // The visitURL parameter holds a URL that should be visited by the user // in a web browser; the waitTokenURL parameter holds a URL that can be // long-polled to acquire the resulting discharge token. // // Use SetLegacyInteraction to add support for legacy clients // that don't understand the newer InteractionMethods field. func SetWebBrowserInteraction(e *Error, visitURL, waitTokenURL string) { e.SetInteraction(WebBrowserInteractionKind, WebBrowserInteractionInfo{ VisitURL: visitURL, WaitTokenURL: waitTokenURL, }) } // SetLegacyInteraction adds information about web-browser-based // interaction (or other kinds of legacy-protocol interaction) to the // given error, which should be an interaction-required error that's // about to be returned from a discharge request. // // The visitURL parameter holds a URL that should be visited by the user // in a web browser (or with an "Accept: application/json" header to // find out the set of legacy interaction methods). // // The waitURL parameter holds a URL that can be long-polled // to acquire the discharge macaroon. func SetLegacyInteraction(e *Error, visitURL, waitURL string) { if e.Info == nil { e.Info = new(ErrorInfo) } e.Info.LegacyVisitURL = visitURL e.Info.LegacyWaitURL = waitURL } // WebBrowserInteractor handls web-browser-based // interaction-required errors by opening a web // browser to allow the user to prove their // credentials interactively. // // It implements the Interactor interface, so instances // can be used with Client.AddInteractor. type WebBrowserInteractor struct { // OpenWebBrowser is used to visit a page in // the user's web browser. If it's nil, the // OpenWebBrowser function will be used. OpenWebBrowser func(*url.URL) error } // Kind implements Interactor.Kind. func (WebBrowserInteractor) Kind() string { return WebBrowserInteractionKind } // Interact implements Interactor.Interact by opening a new web page. func (wi WebBrowserInteractor) Interact(ctx context.Context, client *Client, location string, irErr *Error) (*DischargeToken, error) { var p WebBrowserInteractionInfo if err := irErr.InteractionMethod(wi.Kind(), &p); err != nil { return nil, errgo.Mask(err, errgo.Is(ErrInteractionMethodNotFound)) } visitURL, err := relativeURL(location, p.VisitURL) if err != nil { return nil, errgo.Notef(err, "cannot make relative visit URL") } waitTokenURL, err := relativeURL(location, p.WaitTokenURL) if err != nil { return nil, errgo.Notef(err, "cannot make relative wait URL") } open := wi.OpenWebBrowser if open == nil { open = OpenWebBrowser } if err := open(visitURL); err != nil { return nil, errgo.Mask(err) } return waitForToken(ctx, client, waitTokenURL) } // waitForToken returns a token from a the waitToken URL func waitForToken(ctx context.Context, client *Client, waitTokenURL *url.URL) (*DischargeToken, error) { // TODO integrate this with waitForMacaroon somehow? httpResp, err := ctxhttp.Get(ctx, client.Client, waitTokenURL.String()) if err != nil { return nil, errgo.Notef(err, "cannot get %q", waitTokenURL) } defer httpResp.Body.Close() if httpResp.StatusCode != http.StatusOK { err := unmarshalError(httpResp) return nil, errgo.NoteMask(err, "cannot acquire discharge token", errgo.Any) } var resp WaitTokenResponse if err := httprequest.UnmarshalJSONResponse(httpResp, &resp); err != nil { return nil, errgo.Notef(err, "cannot unmarshal wait response") } tokenVal, err := maybeBase64Decode(resp.Token, resp.Token64) if err != nil { return nil, errgo.Notef(err, "bad discharge token") } // TODO check that kind and value are non-empty? return &DischargeToken{ Kind: resp.Kind, Value: tokenVal, }, nil } // LegacyInteract implements LegacyInteractor by opening a web browser page. func (wi WebBrowserInteractor) LegacyInteract(ctx context.Context, client *Client, location string, visitURL *url.URL) error { return OpenWebBrowser(visitURL) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/��������������������������0000755�0610621�0607500�00000000000�13172163311�027422� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/protocol.go���������������0000644�0610621�0607500�00000004303�13172163311�031612� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package agent /* PROTOCOL The agent protocol is initiated when attempting to perform a discharge. It works as follows: A is Agent L is Login Service A->L POST /discharge L->A Interaction-required error containing an entry for "agent" with field "login-url" holding URL $loginURL. A->L GET $loginURL?username=$user&public-key=$pubkey where $user is the username to log in as and $pubkey is the public key of that username, base-64 encoded. L->A JSON response: macaroon: macaroon with "local" third-party-caveat addressed to $pubkey. A->L POST /discharge?token-kind=agent&token64=self-discharged macaroon The macaroon is binary-encoded, then base64 encoded. Note that, as with most Go HTTP handlers, the parameters may also be in the form-encoded request body. L->A discharge macaroon A local third-party caveat is a third party caveat with the location set to "local" and the caveat encrypted with the public key specified in the GET request. LEGACY PROTOCOL The legacy agent protocol is used by services that don't yet implement the new protocol. Once a discharge has failed with an interaction required error, an agent login works as follows: Agent Login Service | | | GET visitURL with agent cookie | |----------------------------------->| | | | Macaroon with local third-party | | caveat | |<-----------------------------------| | | | GET visitURL with agent cookie & | | discharged macaroon | |----------------------------------->| | | | Agent login response | |<-----------------------------------| | | The agent cookie is a cookie in the same form described in the PROTOCOL section above. On success the response is the following JSON object: { "agent_login": "true" } If an error occurs then the response should be a JSON object that unmarshals to an httpbakery.Error. */ �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/package_test.go�����������0000644�0610621�0607500�00000000167�13172163311�032407� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package agent_test import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/legacy_test.go������������0000644�0610621�0607500�00000027022�13172163311�032257� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package agent_test import ( "net/http" "time" "github.com/juju/httprequest" "github.com/juju/testing" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/bakerytest" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent" ) type legacyAgentSuite struct { testing.LoggingSuite agentBakery *bakery.Bakery serverBakery *bakery.Bakery discharger *bakerytest.Discharger } type visitFunc func(w http.ResponseWriter, req *http.Request, dischargeId string) error var _ = gc.Suite(&legacyAgentSuite{}) func (s *legacyAgentSuite) SetUpTest(c *gc.C) { s.LoggingSuite.SetUpTest(c) s.discharger = bakerytest.NewDischarger(nil) s.agentBakery = bakery.New(bakery.BakeryParams{ IdentityClient: idmClient{s.discharger.Location()}, Key: bakery.MustGenerateKey(), }) s.serverBakery = bakery.New(bakery.BakeryParams{ Locator: s.discharger, IdentityClient: idmClient{s.discharger.Location()}, Key: bakery.MustGenerateKey(), }) } func (s *legacyAgentSuite) TearDownTest(c *gc.C) { s.discharger.Close() s.LoggingSuite.TearDownTest(c) } var legacyAgentLoginErrorTests = []struct { about string visitHandler visitFunc expectError string }{{ about: "error response", visitHandler: func(w http.ResponseWriter, req *http.Request, dischargeId string) error { return errgo.Newf("test error") }, expectError: `cannot get discharge from ".*": cannot start interactive session: Get http(s)?://.*: test error`, }, { about: "unexpected response", visitHandler: func(w http.ResponseWriter, req *http.Request, dischargeId string) error { w.Write([]byte("OK")) return nil }, expectError: `cannot get discharge from ".*": cannot start interactive session: Get http(s)?://.*: unexpected content type text/plain; want application/json; content: OK`, }, { about: "unexpected error response", visitHandler: func(w http.ResponseWriter, req *http.Request, dischargeId string) error { httprequest.WriteJSON(w, http.StatusBadRequest, httpbakery.Error{}) return nil }, expectError: `cannot get discharge from ".*": cannot start interactive session: Get http(s)?://.*: no error message found`, }, { about: "login false value", visitHandler: func(w http.ResponseWriter, req *http.Request, dischargeId string) error { httprequest.WriteJSON(w, http.StatusOK, agent.LegacyAgentResponse{}) return nil }, expectError: `cannot get discharge from ".*": cannot start interactive session: agent login failed`, }} func (s *legacyAgentSuite) TestAgentLoginError(c *gc.C) { var visit visitFunc s.discharger.AddHTTPHandlers(LegacyAgentHandlers(LegacyAgentHandler{ Visit: func(p httprequest.Params, dischargeId string) error { if handleLoginMethods(p) { return nil } return visit(p.Response, p.Request, dischargeId) }, })) rendezvous := bakerytest.NewRendezvous() s.discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if token != nil { return nil, errgo.Newf("received unexpected discharge token") } dischargeId := rendezvous.NewDischarge(info) err := httpbakery.NewInteractionRequiredError(nil, req) err.Info = &httpbakery.ErrorInfo{ LegacyVisitURL: "/visit?dischargeid=" + dischargeId, LegacyWaitURL: "/wait?dischargeid=" + dischargeId, } return nil, err }) for i, test := range legacyAgentLoginErrorTests { c.Logf("%d. %s", i, test.about) visit = test.visitHandler client := httpbakery.NewClient() err := agent.SetUpAuth(client, &agent.AuthInfo{ Key: s.agentBakery.Oven.Key(), Agents: []agent.Agent{{ URL: s.discharger.Location(), Username: "test-user", }}, }) c.Assert(err, gc.IsNil) m, err := s.serverBakery.Oven.NewMacaroon( context.Background(), bakery.LatestVersion, time.Now().Add(time.Minute), identityCaveats(s.discharger.Location()), bakery.LoginOp, ) c.Assert(err, gc.IsNil) ms, err := client.DischargeAll(context.Background(), m) c.Assert(err, gc.ErrorMatches, test.expectError) c.Assert(ms, gc.IsNil) } } func (s *legacyAgentSuite) TestSetUpAuth(c *gc.C) { rendezvous := bakerytest.NewRendezvous() s.discharger.AddHTTPHandlers(LegacyAgentHandlers(LegacyAgentHandler{ Visit: func(p httprequest.Params, dischargeId string) error { if handleLoginMethods(p) { return nil } return s.visit(p, dischargeId, rendezvous) }, Wait: func(p httprequest.Params, dischargeId string) (*bakery.Macaroon, error) { caveats, err := rendezvous.Await(dischargeId, 5*time.Second) if err != nil { return nil, errgo.Mask(err) } info, _ := rendezvous.Info(dischargeId) return s.discharger.DischargeMacaroon(p.Context, info, caveats) }, })) s.discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if token != nil { return nil, errgo.Newf("received unexpected discharge token") } dischargeId := rendezvous.NewDischarge(info) err := httpbakery.NewInteractionRequiredError(nil, req) err.Info = &httpbakery.ErrorInfo{ LegacyVisitURL: "/visit?dischargeid=" + dischargeId, LegacyWaitURL: "/wait?dischargeid=" + dischargeId, } return nil, err }) client := httpbakery.NewClient() err := agent.SetUpAuth(client, &agent.AuthInfo{ Key: s.agentBakery.Oven.Key(), Agents: []agent.Agent{{ URL: s.discharger.Location(), Username: "test-user", }}, }) c.Assert(err, gc.IsNil) m, err := s.serverBakery.Oven.NewMacaroon( context.Background(), bakery.LatestVersion, time.Now().Add(time.Minute), identityCaveats(s.discharger.Location()), bakery.LoginOp, ) c.Assert(err, gc.IsNil) ms, err := client.DischargeAll(context.Background(), m) c.Assert(err, gc.IsNil) authInfo, err := s.serverBakery.Checker.Auth(ms).Allow(context.Background(), bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("test-user")) } func (s *legacyAgentSuite) TestNoMatchingSite(c *gc.C) { rendezvous := bakerytest.NewRendezvous() s.discharger.AddHTTPHandlers(LegacyAgentHandlers(LegacyAgentHandler{ Visit: func(p httprequest.Params, dischargeId string) error { if handleLoginMethods(p) { return nil } return s.visit(p, dischargeId, rendezvous) }, Wait: func(p httprequest.Params, dischargeId string) (*bakery.Macaroon, error) { _, err := rendezvous.Await(dischargeId, 5*time.Second) if err != nil { return nil, errgo.Mask(err) } return nil, errgo.Newf("rendezvous unexpectedly succeeded") }, })) s.discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if token != nil { return nil, errgo.Newf("received unexpected discharge token") } dischargeId := rendezvous.NewDischarge(info) err := httpbakery.NewInteractionRequiredError(nil, req) err.Info = &httpbakery.ErrorInfo{ LegacyVisitURL: "/visit?dischargeid=" + dischargeId, LegacyWaitURL: "/wait?dischargeid=" + dischargeId, } return nil, err }) client := httpbakery.NewClient() err := agent.SetUpAuth(client, &agent.AuthInfo{ Key: bakery.MustGenerateKey(), Agents: []agent.Agent{{ URL: "http://0.1.2.3/", Username: "test-user", }}, }) c.Assert(err, gc.IsNil) m, err := s.serverBakery.Oven.NewMacaroon( context.Background(), bakery.LatestVersion, time.Now().Add(time.Minute), identityCaveats(s.discharger.Location()), bakery.LoginOp, ) c.Assert(err, gc.IsNil) _, err = client.DischargeAll(context.Background(), m) c.Assert(err, gc.ErrorMatches, `cannot get discharge from ".*": cannot start interactive session: cannot find username for discharge location ".*"`) _, ok := errgo.Cause(err).(*httpbakery.InteractionError) c.Assert(ok, gc.Equals, true) } type idmClient struct { dischargerURL string } func (c idmClient) IdentityFromContext(ctx context.Context) (bakery.Identity, []checkers.Caveat, error) { return nil, identityCaveats(c.dischargerURL), nil } func identityCaveats(dischargerURL string) []checkers.Caveat { return []checkers.Caveat{{ Location: dischargerURL, Condition: "test condition", }} } func (c idmClient) DeclaredIdentity(ctx context.Context, declared map[string]string) (bakery.Identity, error) { return bakery.SimpleIdentity(declared["username"]), nil } var ages = time.Now().Add(time.Hour) // handleLoginMethods handles a legacy visit request // to ask for the set of login methods. // It reports whether it has handled the request. func handleLoginMethods(p httprequest.Params) bool { if p.Request.Header.Get("Accept") != "application/json" { return false } httprequest.WriteJSON(p.Response, http.StatusOK, map[string]string{ "agent": p.Request.URL.String(), }) return true } func (s *legacyAgentSuite) visit(p httprequest.Params, dischargeId string, rendezvous *bakerytest.Rendezvous) error { ctx := context.TODO() username, userPublicKey, err := agent.LoginCookie(p.Request) if err != nil { return errgo.Notef(err, "cannot read agent login") } authInfo, authErr := s.agentBakery.Checker.Auth(httpbakery.RequestMacaroons(p.Request)...).Allow(ctx, bakery.LoginOp) if authErr == nil && authInfo.Identity != nil { rendezvous.DischargeComplete(dischargeId, []checkers.Caveat{ checkers.DeclaredCaveat("username", authInfo.Identity.Id()), }) httprequest.WriteJSON(p.Response, http.StatusOK, agent.LegacyAgentResponse{true}) return nil } version := httpbakery.RequestVersion(p.Request) m, err := s.agentBakery.Oven.NewMacaroon(ctx, version, ages, []checkers.Caveat{ bakery.LocalThirdPartyCaveat(userPublicKey, version), checkers.DeclaredCaveat("username", username), }, bakery.LoginOp) if err != nil { return errgo.Notef(err, "cannot create macaroon") } return httpbakery.NewDischargeRequiredError(httpbakery.DischargeRequiredErrorParams{ Macaroon: m, Request: p.Request, }) } // LegacyAgentHandler represents a handler for legacy // agent interactions. Each member corresponds to an HTTP endpoint, type LegacyAgentHandler struct { Visit func(p httprequest.Params, dischargeId string) error Wait func(p httprequest.Params, dischargeId string) (*bakery.Macaroon, error) } var reqServer = httprequest.Server{ ErrorMapper: httpbakery.ErrorToResponse, } func LegacyAgentHandlers(h LegacyAgentHandler) []httprequest.Handler { return reqServer.Handlers(func(p httprequest.Params) (legacyAgentHandlers, context.Context, error) { return legacyAgentHandlers{h}, p.Context, nil }) } type legacyAgentHandlers struct { h LegacyAgentHandler } type visitRequest struct { httprequest.Route `httprequest:"GET /visit"` DischargeId string `httprequest:"dischargeid,form"` } func (h legacyAgentHandlers) Visit(p httprequest.Params, r *visitRequest) error { if h.h.Visit == nil { return errgo.Newf("visit not implemented") } return h.h.Visit(p, r.DischargeId) } type waitRequest struct { httprequest.Route `httprequest:"GET /wait"` DischargeId string `httprequest:"dischargeid,form"` } func (h legacyAgentHandlers) Wait(p httprequest.Params, r *waitRequest) (*httpbakery.WaitResponse, error) { if h.h.Wait == nil { return nil, errgo.Newf("wait not implemented") } m, err := h.h.Wait(p, r.DischargeId) if err != nil { return nil, errgo.Mask(err, errgo.Any) } return &httpbakery.WaitResponse{ Macaroon: m, }, nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/export_test.go������������0000644�0610621�0607500�00000000051�13172163311�032325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package agent var AddCookie = addCookie ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/example_test.go�����������0000644�0610621�0607500�00000001111�13172163311�032435� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package agent_test import ( "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent" ) func ExampleSetUpAuth() { // In practice the key would be read from persistent // storage. key, err := bakery.GenerateKey() if err != nil { // handle error } client := httpbakery.NewClient() err = agent.SetUpAuth(client, &agent.AuthInfo{ Key: key, Agents: []agent.Agent{{ URL: "http://foo.com", Username: "agent-username", }}, }) if err != nil { // handle error } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/cookie_test.go������������0000644�0610621�0607500�00000004447�13172163311�032272� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package agent_test import ( "encoding/base64" "net/http" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent" ) type cookieSuite struct{} var _ = gc.Suite(&cookieSuite{}) var loginCookieTests = []struct { about string addCookie func(*http.Request, *bakery.PublicKey) expectUser string expectError string expectCause error }{{ about: "success", addCookie: func(req *http.Request, key *bakery.PublicKey) { agent.AddCookie(req, "bob", key) }, expectUser: "bob", }, { about: "no cookie", addCookie: func(req *http.Request, key *bakery.PublicKey) {}, expectError: "no agent-login cookie found", expectCause: agent.ErrNoAgentLoginCookie, }, { about: "invalid base64 encoding", addCookie: func(req *http.Request, key *bakery.PublicKey) { req.AddCookie(&http.Cookie{ Name: "agent-login", Value: "x", }) }, expectError: "cannot decode cookie value: illegal base64 data at input byte 0", }, { about: "invalid JSON", addCookie: func(req *http.Request, key *bakery.PublicKey) { req.AddCookie(&http.Cookie{ Name: "agent-login", Value: base64.StdEncoding.EncodeToString([]byte("}")), }) }, expectError: "cannot unmarshal agent login: invalid character '}' looking for beginning of value", }, { about: "no username", addCookie: func(req *http.Request, key *bakery.PublicKey) { agent.AddCookie(req, "", key) }, expectError: "agent login has no user name", }, { about: "no public key", addCookie: func(req *http.Request, key *bakery.PublicKey) { agent.AddCookie(req, "bob", nil) }, expectError: "agent login has no public key", }} func (s *cookieSuite) TestLoginCookie(c *gc.C) { key, err := bakery.GenerateKey() c.Assert(err, gc.IsNil) for i, test := range loginCookieTests { c.Logf("test %d: %s", i, test.about) req, err := http.NewRequest("GET", "", nil) c.Assert(err, gc.IsNil) test.addCookie(req, &key.Public) gotUsername, gotKey, err := agent.LoginCookie(req) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) if test.expectCause != nil { c.Assert(errgo.Cause(err), gc.Equals, test.expectCause) } continue } c.Assert(gotUsername, gc.Equals, test.expectUser) c.Assert(gotKey, gc.DeepEquals, &key.Public) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/cookie.go�����������������0000644�0610621�0607500�00000003721�13172163311�031225� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package agent import ( "encoding/base64" "encoding/json" "net/http" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) const cookieName = "agent-login" // agentLogin defines the structure of an agent login cookie. type agentLogin struct { Username string `json:"username"` PublicKey *bakery.PublicKey `json:"public_key"` } // addCookie adds an agent-login cookie with the specified parameters to // the given request. func addCookie(req *http.Request, username string, key *bakery.PublicKey) { al := agentLogin{ Username: username, PublicKey: key, } data, err := json.Marshal(al) if err != nil { // This should be impossible as the agentLogin structure // has to be marshalable. It is certainly a bug if it // isn't. panic(errgo.Notef(err, "cannot marshal %s cookie", cookieName)) } req.AddCookie(&http.Cookie{ Name: cookieName, Value: base64.StdEncoding.EncodeToString(data), }) } // ErrNoAgentLoginCookie is the error returned when the expected // agent login cookie has not been found. var ErrNoAgentLoginCookie = errgo.New("no agent-login cookie found") // LoginCookie returns details of the agent login cookie // from the given request. If no agent-login cookie is found, // it returns an ErrNoAgentLoginCookie error. func LoginCookie(req *http.Request) (username string, key *bakery.PublicKey, err error) { c, err := req.Cookie(cookieName) if err != nil { return "", nil, ErrNoAgentLoginCookie } b, err := macaroon.Base64Decode([]byte(c.Value)) if err != nil { return "", nil, errgo.Notef(err, "cannot decode cookie value") } var al agentLogin if err := json.Unmarshal(b, &al); err != nil { return "", nil, errgo.Notef(err, "cannot unmarshal agent login") } if al.Username == "" { return "", nil, errgo.Newf("agent login has no user name") } if al.PublicKey == nil { return "", nil, errgo.Newf("agent login has no public key") } return al.Username, al.PublicKey, nil } �����������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/agent_test.go�������������0000644�0610621�0607500�00000011467�13172163311�032117� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package agent_test import ( "net/http" "time" "github.com/juju/httprequest" "github.com/juju/testing" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/bakerytest" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent" ) type agentSuite struct { testing.LoggingSuite agentBakery *bakery.Bakery serverBakery *bakery.Bakery discharger *bakerytest.Discharger } var _ = gc.Suite(&agentSuite{}) func (s *agentSuite) SetUpTest(c *gc.C) { s.LoggingSuite.SetUpTest(c) s.discharger = bakerytest.NewDischarger(nil) s.agentBakery = bakery.New(bakery.BakeryParams{ Key: bakery.MustGenerateKey(), }) s.serverBakery = bakery.New(bakery.BakeryParams{ Locator: s.discharger, Key: bakery.MustGenerateKey(), }) } func (s *agentSuite) TearDownTest(c *gc.C) { s.discharger.Close() s.LoggingSuite.TearDownTest(c) } var agentLoginOp = bakery.Op{"agent", "login"} func (s *agentSuite) TestSetUpAuth(c *gc.C) { dischargerBakery := bakery.New(bakery.BakeryParams{ Key: s.discharger.Key, }) s.discharger.AddHTTPHandlers(AgentHandlers(AgentHandler{ AgentMacaroon: func(p httprequest.Params, username string, pubKey *bakery.PublicKey) (*bakery.Macaroon, error) { if username != "test-user" || *pubKey != s.agentBakery.Oven.Key().Public { return nil, errgo.Newf("mismatched user/pubkey; want %s got %s", s.agentBakery.Oven.Key().Public, *pubKey) } version := httpbakery.RequestVersion(p.Request) return dischargerBakery.Oven.NewMacaroon( context.Background(), bakery.LatestVersion, time.Now().Add(time.Minute), []checkers.Caveat{ bakery.LocalThirdPartyCaveat(pubKey, version), }, agentLoginOp, ) }, })) s.discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if token != nil { c.Logf("with token request: %v", req.URL) if token.Kind != "agent" { return nil, errgo.Newf("unexpected discharge token kind %q", token.Kind) } var m macaroon.Slice if err := m.UnmarshalBinary(token.Value); err != nil { return nil, errgo.Notef(err, "cannot unmarshal token") } if _, err := dischargerBakery.Checker.Auth(m).Allow(ctx, agentLoginOp); err != nil { return nil, errgo.Newf("received unexpected discharge token") } return nil, nil } if string(info.Condition) != "some-third-party-caveat" { return nil, errgo.Newf("unexpected caveat condition") } err := httpbakery.NewInteractionRequiredError(nil, req) agent.SetInteraction(err, "/agent-macaroon") return nil, err }) client := httpbakery.NewClient() err := agent.SetUpAuth(client, &agent.AuthInfo{ Key: s.agentBakery.Oven.Key(), Agents: []agent.Agent{{ URL: s.discharger.Location(), Username: "test-user", }}, }) someOp := bakery.Op{ Entity: "something", Action: "doit", } c.Assert(err, gc.IsNil) m, err := s.serverBakery.Oven.NewMacaroon( context.Background(), bakery.LatestVersion, time.Now().Add(time.Minute), []checkers.Caveat{{ Location: s.discharger.Location(), Condition: "some-third-party-caveat", }}, someOp, ) c.Assert(err, gc.Equals, nil) ms, err := client.DischargeAll(context.Background(), m) c.Assert(err, gc.Equals, nil) _, err = s.serverBakery.Checker.Auth(ms).Allow(context.Background(), someOp) c.Assert(err, gc.Equals, nil) } func AgentHandlers(h AgentHandler) []httprequest.Handler { return reqServer.Handlers(func(p httprequest.Params) (agentHandlers, context.Context, error) { return agentHandlers{h}, p.Context, nil }) } // AgentHandler holds the functions that may be called by the // agent-interaction server. type AgentHandler struct { AgentMacaroon func(p httprequest.Params, username string, pubKey *bakery.PublicKey) (*bakery.Macaroon, error) } // agentHandlers is used to define the handler methods. type agentHandlers struct { h AgentHandler } // agentMacaroonRequest represents a request for the // agent macaroon - it matches agent.agentMacaroonRequest. type agentMacaroonRequest struct { httprequest.Route `httprequest:"GET /agent-macaroon"` Username string `httprequest:"username,form"` PublicKey *bakery.PublicKey `httprequest:"public-key,form"` } type agentMacaroonResponse struct { Macaroon *bakery.Macaroon `json:"macaroon"` } func (h agentHandlers) AgentMacaroon(p httprequest.Params, r *agentMacaroonRequest) (*agentMacaroonResponse, error) { m, err := h.h.AgentMacaroon(p, r.Username, r.PublicKey) if err != nil { return nil, errgo.Mask(err, errgo.Any) } return &agentMacaroonResponse{ Macaroon: m, }, nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/httpbakery/agent/agent.go������������������0000644�0610621�0607500�00000014501�13172163311�031050� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package agent enables non-interactive (agent) login using macaroons. // To enable agent authorization with a given httpbakery.Client c against // a given third party discharge server URL u: // // SetUpAuth(c, u, agentUsername) // package agent import ( "errors" "net/http" "net/url" "strings" "github.com/juju/httprequest" "github.com/juju/loggo" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) var logger = loggo.GetLogger("httpbakery.agent") // AuthInfo holds the agent information required // to set up agent authentication information. // It holds the agent's private key and information // about the username associated with each // known agent-authentication server. type AuthInfo struct { Key *bakery.KeyPair `json:"key,omitempty" yaml:"key,omitempty"` Agents []Agent `json:"agents" yaml:"agents"` } // Agent represents an agent that can be used for agent authentication. type Agent struct { // URL holds the URL associated with the agent. URL string `json:"url" yaml:"url"` // Username holds the username to use for the agent. Username string `json:"username" yaml:"username"` } // SetUpAuth sets up agent authentication on the given client. // If this is called several times on the same client, earlier // calls will take precedence over later calls when there's // a URL and username match for both. func SetUpAuth(client *httpbakery.Client, authInfo *AuthInfo) error { if authInfo.Key == nil { return errgo.Newf("no key in auth info") } if client.Key != nil { if *client.Key != *authInfo.Key { return errgo.Newf("client already has a different key set up") } } else { client.Key = authInfo.Key } client.AddInteractor(interactor{authInfo}) return nil } // InteractionInfo holds the information expected in // the agent interaction entry in an interaction-required // error. type InteractionInfo struct { // LoginURL holds the URL from which to acquire // a macaroon that can be used to complete the agent // login. To acquire the macaroon, make a POST // request to the URL with user and public-key // parameters. LoginURL string `json:"login-url"` } // SetInteraction sets agent interaction information on the // given error, which should be an interaction-required // error to be returned from a discharge request. // // The given URL (which may be relative to the discharger // location) will be the subject of a GET request by the // client to fetch the agent macaroon that, when discharged, // can act as the discharge token. func SetInteraction(e *httpbakery.Error, loginURL string) { e.SetInteraction("agent", &InteractionInfo{ LoginURL: loginURL, }) } // interactor is a httpbakery.Interactor that performs interaction using the // agent login protocol. type interactor struct { authInfo *AuthInfo } func (i interactor) Kind() string { return "agent" } // agentMacaroonRequest represents a request to get the // agent macaroon that, when discharged, becomes // the discharge token to complete the discharge. type agentMacaroonRequest struct { httprequest.Route `httprequest:"GET"` Username string `httprequest:"username,form"` PublicKey *bakery.PublicKey `httprequest:"public-key,form"` } type agentMacaroonResponse struct { Macaroon *bakery.Macaroon `json:"macaroon"` } func (i interactor) Interact(ctx context.Context, client *httpbakery.Client, location string, interactionRequiredErr *httpbakery.Error) (*httpbakery.DischargeToken, error) { var p InteractionInfo err := interactionRequiredErr.InteractionMethod("agent", &p) if err != nil { return nil, errgo.Mask(err) } if p.LoginURL == "" { return nil, errgo.Newf("no login-url field found in agent interaction method") } agent, err := i.findAgent(location) if err != nil { return nil, errgo.Mask(err) } loginURL, err := relativeURL(location, p.LoginURL) if err != nil { return nil, errgo.Mask(err) } var resp agentMacaroonResponse err = (&httprequest.Client{ Doer: client, }).CallURL(ctx, loginURL.String(), &agentMacaroonRequest{ Username: agent.Username, PublicKey: &client.Key.Public, }, &resp) if err != nil { return nil, errgo.Notef(err, "cannot acquire agent macaroon") } if resp.Macaroon == nil { return nil, errgo.Newf("no macaroon in response") } ms, err := client.DischargeAll(ctx, resp.Macaroon) if err != nil { return nil, errgo.Notef(err, "cannot discharge agent macaroon") } data, err := ms.MarshalBinary() if err != nil { return nil, errgo.Notef(err, "cannot marshal agent macaroon") } return &httpbakery.DischargeToken{ Kind: "agent", Value: data, }, nil } // findAgent finds an appropriate agent entry // for the given location. func (i interactor) findAgent(location string) (*Agent, error) { for _, a := range i.authInfo.Agents { // Don't worry about trailing slashes if strings.TrimSuffix(a.URL, "/") == strings.TrimSuffix(location, "/") { return &a, nil } } return nil, errgo.WithCausef(nil, httpbakery.ErrInteractionMethodNotFound, "cannot find username for discharge location %q", location) } // LegacyAgentResponse contains the response to a // legacy agent login attempt. type LegacyAgentResponse struct { AgentLogin bool `json:"agent-login"` } // LegacyInteract implements httpbakery.LegactInteractor.LegacyInteract by fetching a // func (i interactor) LegacyInteract(ctx context.Context, client *httpbakery.Client, location string, visitURL *url.URL) error { c := &httprequest.Client{ Doer: client, } agent, err := i.findAgent(location) if err != nil { return errgo.Mask(err) } req, err := http.NewRequest("GET", "", nil) if err != nil { return errgo.Notef(err, "cannot make request") } req.URL = visitURL addCookie(req, agent.Username, &client.Key.Public) var resp LegacyAgentResponse if err := c.Do(ctx, req, &resp); err != nil { return errgo.Mask(err) } if !resp.AgentLogin { return errors.New("agent login failed") } return nil } // relativeURL returns newPath relative to an original URL. func relativeURL(base, new string) (*url.URL, error) { if new == "" { return nil, errgo.Newf("empty URL") } baseURL, err := url.Parse(base) if err != nil { return nil, errgo.Notef(err, "cannot parse URL") } newURL, err := url.Parse(new) if err != nil { return nil, errgo.Notef(err, "cannot parse URL") } return baseURL.ResolveReference(newURL), nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/dependencies.tsv���������������������������0000644�0610621�0607500�00000003525�13172163311�027340� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������github.com/golang/protobuf git 4bd1920723d7b7c925de087aa32e2187708897f7 2016-11-09T07:27:36Z github.com/juju/errors git 1b5e39b83d1835fa480e0c2ddefb040ee82d58b3 2015-09-16T12:56:42Z github.com/juju/httprequest git 97888e5c00b07a163549c16d7c1f549d14704571 2017-08-21T12:10:43Z github.com/juju/loggo git 8232ab8918d91c72af1a9fb94d3edbe31d88b790 2017-06-05T01:46:07Z github.com/juju/retry git 62c62032529169c7ec02fa48f93349604c345e1f 2015-10-29T02:48:21Z github.com/juju/schema git 075de04f9b7d7580d60a1e12a0b3f50bb18e6998 2016-04-20T04:42:03Z github.com/juju/testing git fce9bc4ebf7a77310c262ac4884e03b778eae06a 2017-02-22T09:01:19Z github.com/juju/utils git 9f8aeb9b09e2d8c769be8317ccfa23f7eec62c26 2017-02-15T08:19:00Z github.com/juju/version git 1f41e27e54f21acccf9b2dddae063a782a8a7ceb 2016-10-31T05:19:06Z github.com/juju/webbrowser git 54b8c57083b4afb7dc75da7f13e2967b2606a507 2016-03-09T14:36:29Z github.com/julienschmidt/httprouter git 77a895ad01ebc98a4dc95d8355bc825ce80a56f6 2015-10-13T22:55:20Z github.com/rogpeppe/fastuuid git 6724a57986aff9bff1a1770e9347036def7c89f6 2015-01-06T09:32:20Z golang.org/x/crypto git f6b343c37ca80bfa8ea539da67a0b621f84fab1d 2016-12-21T23:57:47Z golang.org/x/net git a04bdaca5b32abe1c069418fb7088ae607de5bd0 2017-10-04T03:46:48Z golang.org/x/sys git 7a6e5648d140666db5d920909e082ca00a87ba2c 2017-02-01T05:12:45Z gopkg.in/check.v1 git 4f90aeace3a26ad7021961c297b22c42160c7b25 2016-01-05T16:49:36Z gopkg.in/errgo.v1 git 442357a80af5c6bf9b6d51ae791a39c3421004f3 2016-12-22T12:58:16Z gopkg.in/juju/environschema.v1 git 7359fc7857abe2b11b5b3e23811a9c64cb6b01e0 2015-11-04T11:58:10Z gopkg.in/macaroon.v2-unstable git 431c217c17128ef03baada4f97b33b01688c3c90 2017-10-06T15:42:45Z gopkg.in/mgo.v2 git f2b6f6c918c452ad107eec89615f074e3bd80e33 2016-08-18T01:52:18Z gopkg.in/yaml.v2 git a3f3340b5840cee44f372bddb5880fcbc419b46a 2017-02-08T14:18:51Z ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/cmd/���������������������������������������0000755�0610621�0607500�00000000000�13172163311�024712� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/cmd/bakery-keygen/�������������������������0000755�0610621�0607500�00000000000�13172163311�027447� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/cmd/bakery-keygen/main.go������������������0000644�0610621�0607500�00000000531�13172163311�030721� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "os" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) func main() { kp, err := bakery.GenerateKey() if err != nil { fmt.Fprintf(os.Stderr, "cannot generate key: %s\n", err) os.Exit(1) } b, err := json.MarshalIndent(kp, "", "\t") if err != nil { panic(err) } fmt.Printf("%s\n", b) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakerytest/��������������������������������0000755�0610621�0607500�00000000000�13172163311�026324� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakerytest/rendezvous.go�������������������0000644�0610621�0607500�00000011225�13172163311�031060� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakerytest import ( "bytes" "fmt" "sync" "time" errgo "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) // Rendezvous implements a place where discharge information // can be stored, recovered and waited for. type Rendezvous struct { mu sync.Mutex maxId int waiting map[string]*dischargeFuture } func NewRendezvous() *Rendezvous { return &Rendezvous{ waiting: make(map[string]*dischargeFuture), } } type dischargeFuture struct { info *bakery.ThirdPartyCaveatInfo done chan struct{} caveats []checkers.Caveat err error } // NewDischarge creates a new discharge in the rendezvous // associated with the given caveat information. // It returns an identifier for the discharge that can // later be used to complete the discharge or find // out the information again. func (r *Rendezvous) NewDischarge(cav *bakery.ThirdPartyCaveatInfo) string { r.mu.Lock() defer r.mu.Unlock() dischargeId := fmt.Sprintf("%d", r.maxId) r.maxId++ r.waiting[dischargeId] = &dischargeFuture{ info: cav, done: make(chan struct{}), } return dischargeId } // Info returns information on the given discharge id // and reports whether the information has been found. func (r *Rendezvous) Info(dischargeId string) (*bakery.ThirdPartyCaveatInfo, bool) { r.mu.Lock() defer r.mu.Unlock() d := r.waiting[dischargeId] if d == nil { return nil, false } return d.info, true } // DischargeComplete marks the discharge with the given id // as completed with the given caveats, // which will be associated with the given discharge id // and returned from Await. func (r *Rendezvous) DischargeComplete(dischargeId string, caveats []checkers.Caveat) { r.dischargeDone(dischargeId, caveats, nil) } // DischargeFailed marks the discharge with the given id // as failed with the given error, which will be // returned from Await or CheckToken when they're // called with that id. func (r *Rendezvous) DischargeFailed(dischargeId string, err error) { r.dischargeDone(dischargeId, nil, err) } func (r *Rendezvous) dischargeDone(dischargeId string, caveats []checkers.Caveat, err error) { r.mu.Lock() defer r.mu.Unlock() d := r.waiting[dischargeId] if d == nil { panic(errgo.Newf("invalid discharge id %q", dischargeId)) } select { case <-d.done: panic(errgo.Newf("DischargeComplete called twice")) default: } d.caveats, d.err = caveats, err close(d.done) } // Await waits for DischargeComplete or DischargeFailed to be called, // and returns either the caveats passed to DischargeComplete // or the error passed to DischargeFailed. // // It waits for at least the given duration. If timeout is zero, // it returns the information only if it is already available. func (r *Rendezvous) Await(dischargeId string, timeout time.Duration) ([]checkers.Caveat, error) { r.mu.Lock() d := r.waiting[dischargeId] r.mu.Unlock() if d == nil { return nil, errgo.Newf("invalid discharge id %q", dischargeId) } if timeout == 0 { select { case <-d.done: default: return nil, errgo.New("rendezvous has not completed") } } else { select { case <-d.done: case <-time.After(timeout): return nil, errgo.New("timeout waiting for rendezvous to complete") } } if d.err != nil { return nil, errgo.Mask(d.err, errgo.Any) } return d.caveats, nil } func (r *Rendezvous) DischargeToken(dischargeId string) *httpbakery.DischargeToken { _, err := r.Await(dischargeId, 0) if err != nil { panic(errgo.Notef(err, "cannot obtain discharge token for %q", dischargeId)) } return &httpbakery.DischargeToken{ Kind: "discharge-id", Value: []byte(dischargeId), } } // CheckToken checks that the given token is valid for discharging the // given caveat, and returns any caveats passed to DischargeComplete // if it is. func (r *Rendezvous) CheckToken(token *httpbakery.DischargeToken, cav *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { if token.Kind != "discharge-id" { return nil, errgo.Newf("invalid discharge token kind %q", token.Kind) } info, ok := r.Info(string(token.Value)) if !ok { return nil, errgo.Newf("discharge token %q not found", token.Value) } if !bytes.Equal(info.Caveat, cav.Caveat) { return nil, errgo.Newf("caveat provided to CheckToken does not match original") } if !bytes.Equal(info.Id, cav.Id) { return nil, errgo.Newf("caveat id provided to CheckToken does not match original") } caveats, err := r.Await(string(token.Value), 0) if err != nil { // Don't mask the error because we want the cause to remain // unchanged if it was passed to DischargeFailed. return nil, errgo.Mask(err, errgo.Any) } return caveats, nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakerytest/package_test.go�����������������0000644�0610621�0607500�00000000174�13172163311�031307� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakerytest_test import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakerytest/bakerytest_test.go��������������0000644�0610621�0607500�00000031766�13172163311�032104� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakerytest_test import ( "fmt" "net/http" "net/url" "sync" "time" "github.com/juju/httprequest" jujutesting "github.com/juju/testing" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/bakerytest" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) type suite struct { jujutesting.LoggingSuite client *httpbakery.Client } func (s *suite) SetUpTest(c *gc.C) { s.LoggingSuite.SetUpTest(c) s.client = httpbakery.NewClient() } var _ = gc.Suite(&suite{}) var ( ages = time.Now().Add(time.Hour) dischargeOp = bakery.Op{"thirdparty", "x"} ) func (s *suite) TestDischargerSimple(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() b := bakery.New(bakery.BakeryParams{ Location: "here", Locator: d, Key: bakery.MustGenerateKey(), }) m, err := b.Oven.NewMacaroon(context.Background(), bakery.LatestVersion, ages, []checkers.Caveat{{ Location: d.Location(), Condition: "something", }}, dischargeOp) c.Assert(err, gc.IsNil) ms, err := s.client.DischargeAll(context.Background(), m) c.Assert(err, gc.IsNil) c.Assert(ms, gc.HasLen, 2) _, err = b.Checker.Auth(ms).Allow(context.Background(), dischargeOp) c.Assert(err, gc.IsNil) } func (s *suite) TestDischargerTwoLevels(c *gc.C) { d1checker := func(cond, arg string) ([]checkers.Caveat, error) { if cond != "xtrue" { return nil, fmt.Errorf("caveat refused") } return nil, nil } d1 := bakerytest.NewDischarger(nil) d1.Checker = bakerytest.ConditionParser(d1checker) defer d1.Close() d2checker := func(cond, arg string) ([]checkers.Caveat, error) { return []checkers.Caveat{{ Location: d1.Location(), Condition: "x" + cond, }}, nil } d2 := bakerytest.NewDischarger(d1) d2.Checker = bakerytest.ConditionParser(d2checker) defer d2.Close() locator := bakery.NewThirdPartyStore() locator.AddInfo(d1.Location(), bakery.ThirdPartyInfo{ PublicKey: d1.Key.Public, Version: bakery.LatestVersion, }) locator.AddInfo(d2.Location(), bakery.ThirdPartyInfo{ PublicKey: d2.Key.Public, Version: bakery.LatestVersion, }) b := bakery.New(bakery.BakeryParams{ Location: "here", Locator: locator, Key: bakery.MustGenerateKey(), }) m, err := b.Oven.NewMacaroon(context.Background(), bakery.LatestVersion, ages, []checkers.Caveat{{ Location: d2.Location(), Condition: "true", }}, dischargeOp) c.Assert(err, gc.IsNil) ms, err := s.client.DischargeAll(context.Background(), m) c.Assert(err, gc.IsNil) c.Assert(ms, gc.HasLen, 3) _, err = b.Checker.Auth(ms).Allow(context.Background(), dischargeOp) c.Assert(err, gc.IsNil) err = b.Oven.AddCaveat(context.Background(), m, checkers.Caveat{ Location: d2.Location(), Condition: "nope", }) c.Assert(err, gc.IsNil) ms, err = s.client.DischargeAll(context.Background(), m) c.Assert(err, gc.ErrorMatches, `cannot get discharge from "https://[^"]*": third party refused discharge: cannot discharge: caveat refused`) c.Assert(ms, gc.HasLen, 0) } func (s *suite) TestInsecureSkipVerifyRestoration(c *gc.C) { d1 := bakerytest.NewDischarger(nil) d2 := bakerytest.NewDischarger(nil) d2.Close() c.Assert(http.DefaultTransport.(*http.Transport).TLSClientConfig.InsecureSkipVerify, gc.Equals, true) d1.Close() c.Assert(http.DefaultTransport.(*http.Transport).TLSClientConfig.InsecureSkipVerify, gc.Equals, false) // When InsecureSkipVerify is already true, it should not // be restored to false. http.DefaultTransport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true d3 := bakerytest.NewDischarger(nil) d3.Close() c.Assert(http.DefaultTransport.(*http.Transport).TLSClientConfig.InsecureSkipVerify, gc.Equals, true) } func (s *suite) TestConcurrentDischargers(c *gc.C) { var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func() { d := bakerytest.NewDischarger(nil) d.Close() wg.Done() }() } wg.Wait() c.Assert(http.DefaultTransport.(*http.Transport).TLSClientConfig.InsecureSkipVerify, gc.Equals, false) } func (s *suite) TestInteractiveDischarger(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() rendezvous := bakerytest.NewRendezvous() visited := false waited := false d.AddHTTPHandlers(VisitWaitHandlers(VisitWaiter{ Visit: func(p httprequest.Params, dischargeId string) error { visited = true rendezvous.DischargeComplete(dischargeId, []checkers.Caveat{{ Condition: "test pass", }}) return nil }, WaitToken: func(p httprequest.Params, dischargeId string) (*httpbakery.DischargeToken, error) { waited = true _, err := rendezvous.Await(dischargeId, 5*time.Second) if err != nil { return nil, errgo.Mask(err) } return rendezvous.DischargeToken(dischargeId), nil }, })) d.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if string(cav.Condition) != "something" { return nil, errgo.Newf("wrong condition") } if token != nil { return rendezvous.CheckToken(token, cav) } err := NewVisitWaitError(req, rendezvous.NewDischarge(cav)) return nil, errgo.Mask(err, errgo.Any) }) var r recordingChecker b := bakery.New(bakery.BakeryParams{ Location: "here", Locator: d, Checker: &r, Key: bakery.MustGenerateKey(), }) m, err := b.Oven.NewMacaroon(context.Background(), bakery.LatestVersion, ages, []checkers.Caveat{{ Location: d.Location(), Condition: "something", }}, dischargeOp) c.Assert(err, gc.IsNil) client := httpbakery.NewClient() client.AddInteractor(newTestInteractor()) ms, err := client.DischargeAll(context.Background(), m) c.Assert(err, gc.IsNil) c.Assert(ms, gc.HasLen, 2) _, err = b.Checker.Auth(ms).Allow(context.Background(), dischargeOp) c.Assert(err, gc.IsNil) // First caveat is time-before caveat added by NewMacaroon. // Second is the one added by the discharger above. c.Assert(r.caveats, gc.HasLen, 2) c.Assert(r.caveats[1], gc.Equals, "test pass") c.Check(visited, gc.Equals, true) c.Check(waited, gc.Equals, true) } func (s *suite) TestLoginDischargerError(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() rendezvous := bakerytest.NewRendezvous() d.AddHTTPHandlers(VisitWaitHandlers(VisitWaiter{ Visit: func(p httprequest.Params, dischargeId string) error { rendezvous.DischargeFailed(dischargeId, errgo.Newf("test error")) return nil }, WaitToken: func(p httprequest.Params, dischargeId string) (*httpbakery.DischargeToken, error) { _, err := rendezvous.Await(dischargeId, 5*time.Second) if err != nil { return nil, errgo.Mask(err) } return nil, errgo.Newf("await succeeded unexpectedly") }, })) d.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if string(cav.Condition) != "something" { return nil, errgo.Newf("wrong condition") } if token != nil { return nil, errgo.Newf("token received unexpectedly") } err := NewVisitWaitError(req, rendezvous.NewDischarge(cav)) return nil, errgo.Mask(err, errgo.Any) }) b := bakery.New(bakery.BakeryParams{ Location: "here", Locator: d, Key: bakery.MustGenerateKey(), }) m, err := b.Oven.NewMacaroon(context.Background(), bakery.LatestVersion, ages, []checkers.Caveat{{ Location: d.Location(), Condition: "something", }}, dischargeOp) c.Assert(err, gc.IsNil) client := httpbakery.NewClient() client.AddInteractor(newTestInteractor()) _, err = client.DischargeAll(context.Background(), m) c.Assert(err, gc.ErrorMatches, `cannot get discharge from ".*": cannot acquire discharge token: test error`) } func (s *suite) TestInteractiveDischargerRedirection(c *gc.C) { d := bakerytest.NewDischarger(nil) defer d.Close() rendezvous := bakerytest.NewRendezvous() d.AddHTTPHandlers(VisitWaitHandlers(VisitWaiter{ Visit: func(p httprequest.Params, dischargeId string) error { http.Redirect(p.Response, p.Request, d.Location()+"/redirect?dischargeid="+dischargeId, http.StatusFound, ) return nil }, WaitToken: func(p httprequest.Params, dischargeId string) (*httpbakery.DischargeToken, error) { _, err := rendezvous.Await(dischargeId, 5*time.Second) if err != nil { return nil, errgo.Mask(err) } return rendezvous.DischargeToken(dischargeId), nil }, })) d.Mux.GET("/redirect", func(w http.ResponseWriter, req *http.Request, p httprouter.Params) { req.ParseForm() rendezvous.DischargeComplete(req.Form.Get("dischargeid"), []checkers.Caveat{{ Condition: "condition", }}) }) d.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if string(cav.Condition) != "something" { return nil, errgo.Newf("wrong condition") } if token != nil { return rendezvous.CheckToken(token, cav) } err := NewVisitWaitError(req, rendezvous.NewDischarge(cav)) return nil, errgo.Mask(err, errgo.Any) }) var r recordingChecker b := bakery.New(bakery.BakeryParams{ Location: "here", Locator: d, Key: bakery.MustGenerateKey(), Checker: &r, }) m, err := b.Oven.NewMacaroon(context.Background(), bakery.LatestVersion, ages, []checkers.Caveat{{ Location: d.Location(), Condition: "something", }}, dischargeOp) c.Assert(err, gc.IsNil) client := httpbakery.NewClient() client.AddInteractor(newTestInteractor()) ms, err := client.DischargeAll(context.Background(), m) c.Assert(err, gc.IsNil) c.Assert(ms, gc.HasLen, 2) _, err = b.Checker.Auth(ms).Allow(context.Background(), dischargeOp) c.Assert(err, gc.IsNil) // Note: the first caveat is the "time-before" caveat // that's always created. c.Assert(r.caveats[1:], gc.DeepEquals, []string{"condition"}) } type recordingChecker struct { caveats []string } func (c *recordingChecker) CheckFirstPartyCaveat(ctx context.Context, caveat string) error { c.caveats = append(c.caveats, caveat) return nil } func (c *recordingChecker) Namespace() *checkers.Namespace { return nil } func newTestInteractor() httpbakery.WebBrowserInteractor { return httpbakery.WebBrowserInteractor{ OpenWebBrowser: func(u *url.URL) error { resp, err := http.Get(u.String()) if err != nil { return errgo.Mask(err) } resp.Body.Close() if resp.StatusCode != http.StatusOK { return errgo.Newf("unexpected status %q", resp.Status) } return nil }, } } // NewVisitWaitError returns a new interaction-required error // that func NewVisitWaitError(req *http.Request, dischargeId string) *httpbakery.Error { err := httpbakery.NewInteractionRequiredError(nil, req) visitURL := "/visit?dischargeid=" + dischargeId httpbakery.SetWebBrowserInteraction(err, visitURL, "/wait-token?dischargeid="+dischargeId) httpbakery.SetLegacyInteraction(err, visitURL, "/wait?dischargeid="+dischargeId) return err } // VisitWaiter represents a handler for visit-wait interactions. // Each member corresponds to an HTTP endpoint, type VisitWaiter struct { Visit func(p httprequest.Params, dischargeId string) error Wait func(p httprequest.Params, dischargeId string) (*bakery.Macaroon, error) WaitToken func(p httprequest.Params, dischargeId string) (*httpbakery.DischargeToken, error) } var reqServer = httprequest.Server{ ErrorMapper: httpbakery.ErrorToResponse, } func VisitWaitHandlers(vw VisitWaiter) []httprequest.Handler { return reqServer.Handlers(func(p httprequest.Params) (visitWaitHandlers, context.Context, error) { return visitWaitHandlers{vw}, p.Context, nil }) } type visitWaitHandlers struct { vw VisitWaiter } type visitRequest struct { httprequest.Route `httprequest:"GET /visit"` DischargeId string `httprequest:"dischargeid,form"` } func (h visitWaitHandlers) Visit(p httprequest.Params, r *visitRequest) error { if h.vw.Visit == nil { return errgo.Newf("visit not implemented") } return h.vw.Visit(p, r.DischargeId) } type waitTokenRequest struct { httprequest.Route `httprequest:"GET /wait-token"` DischargeId string `httprequest:"dischargeid,form"` } func (h visitWaitHandlers) WaitToken(p httprequest.Params, r *waitTokenRequest) (*httpbakery.WaitTokenResponse, error) { if h.vw.WaitToken == nil { return nil, errgo.Newf("wait-token not implemented") } token, err := h.vw.WaitToken(p, r.DischargeId) if err != nil { return nil, errgo.Mask(err, errgo.Any) } return &httpbakery.WaitTokenResponse{ Kind: token.Kind, Token: string(token.Value), }, nil } type waitRequest struct { httprequest.Route `httprequest:"GET /wait"` DischargeId string `httprequest:"dischargeid,form"` } func (h visitWaitHandlers) Wait(p httprequest.Params, r *waitRequest) (*httpbakery.WaitResponse, error) { if h.vw.Wait == nil { return nil, errgo.Newf("wait not implemented") } m, err := h.vw.Wait(p, r.DischargeId) if err != nil { return nil, errgo.Mask(err, errgo.Any) } return &httpbakery.WaitResponse{ Macaroon: m, }, nil } ����������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakerytest/bakerytest.go�������������������0000644�0610621�0607500�00000013673�13172163311�031042� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package bakerytest provides test helper functions for // the bakery. package bakerytest import ( "crypto/tls" "net/http" "net/http/httptest" "sync" "github.com/juju/httprequest" "github.com/juju/loggo" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) var logger = loggo.GetLogger("bakerytest") // Discharger represents a third party caveat discharger server. type Discharger struct { server *httptest.Server // Mux holds the HTTP multiplexor used by // the discharger server. Mux *httprouter.Router // Key holds the discharger's private key. Key *bakery.KeyPair // Locator holds the third party locator // used when adding a third party caveat // returned by a third party caveat checker. Locator bakery.ThirdPartyLocator // Checker is called to check third party caveats // when they're discharged. When it's nil, caveats // will be discharged unconditionally. Checker httpbakery.ThirdPartyCaveatChecker } // NewDischarger returns a new discharger server that can be used to // discharge third party caveats. It uses the given locator to add third // party caveats returned by the Checker. The discharger also acts as a // locator, returning locator information for itself only. // // The returned discharger should be closed after use. func NewDischarger(locator bakery.ThirdPartyLocator) *Discharger { key, err := bakery.GenerateKey() if err != nil { panic(err) } d := &Discharger{ Mux: httprouter.New(), Key: key, Locator: locator, } d.server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { d.Mux.ServeHTTP(w, req) })) bd := httpbakery.NewDischarger(httpbakery.DischargerParams{ Key: key, Locator: locator, Checker: d, }) d.AddHTTPHandlers(bd.Handlers()) startSkipVerify() return d } // AddHTTPHandlers adds the given HTTP handlers to the // set of endpoints handled by the discharger. func (d *Discharger) AddHTTPHandlers(hs []httprequest.Handler) { for _, h := range hs { d.Mux.Handle(h.Method, h.Path, h.Handle) } } // Close shuts down the server. It may be called more than // once on the same discharger. func (d *Discharger) Close() { if d.server == nil { return } d.server.Close() stopSkipVerify() d.server = nil } // Location returns the location of the discharger, suitable // for setting as the location in a third party caveat. // This will be the URL of the server. func (d *Discharger) Location() string { return d.server.URL } // PublicKeyForLocation implements bakery.PublicKeyLocator // by returning information on the discharger's server location // only. func (d *Discharger) ThirdPartyInfo(ctx context.Context, loc string) (bakery.ThirdPartyInfo, error) { if loc == d.Location() { return bakery.ThirdPartyInfo{ PublicKey: d.Key.Public, Version: bakery.LatestVersion, }, nil } return bakery.ThirdPartyInfo{}, bakery.ErrNotFound } // DischargeMacaroon returns a discharge macaroon // for the given caveat information with the given // caveats added. It assumed the actual third party // caveat has already been checked. func (d *Discharger) DischargeMacaroon( ctx context.Context, cav *bakery.ThirdPartyCaveatInfo, caveats []checkers.Caveat, ) (*bakery.Macaroon, error) { return bakery.Discharge(ctx, bakery.DischargeParams{ Id: cav.Id, Caveat: cav.Caveat, Key: d.Key, Checker: bakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, cav *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { return caveats, nil }), Locator: d.Locator, }) } var ErrTokenNotRecognized = errgo.New("discharge token not recognized") // CheckThirdPartyCaveat implements httpbakery.ThirdPartyCaveatChecker. // If d.Checker is nil, it will always discharge the caveat; // otherwise it calls d.Checker.CheckThirdPartyCaveat // to do the check, and retains the error cause in any // returned error. func (d *Discharger) CheckThirdPartyCaveat(ctx context.Context, cav *bakery.ThirdPartyCaveatInfo, req *http.Request, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if d.Checker == nil { return nil, nil } caveats, err := d.Checker.CheckThirdPartyCaveat(ctx, cav, req, token) if err != nil { return nil, errgo.Mask(err, errgo.Any) } return caveats, nil } // ConditionParser adapts the given function into an httpbakery.ThirdPartyCaveatChecker. // It parses the caveat's condition and calls the function with the result. func ConditionParser(check func(cond, arg string) ([]checkers.Caveat, error)) httpbakery.ThirdPartyCaveatChecker { f := func(ctx context.Context, req *http.Request, cav *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { cond, arg, err := checkers.ParseCaveat(string(cav.Condition)) if err != nil { return nil, err } return check(cond, arg) } return httpbakery.ThirdPartyCaveatCheckerFunc(f) } var skipVerify struct { mu sync.Mutex refCount int oldSkipVerify bool } func startSkipVerify() { v := &skipVerify v.mu.Lock() defer v.mu.Unlock() if v.refCount++; v.refCount > 1 { return } transport, ok := http.DefaultTransport.(*http.Transport) if !ok { return } if transport.TLSClientConfig != nil { v.oldSkipVerify = transport.TLSClientConfig.InsecureSkipVerify transport.TLSClientConfig.InsecureSkipVerify = true } else { v.oldSkipVerify = false transport.TLSClientConfig = &tls.Config{ InsecureSkipVerify: true, } } } func stopSkipVerify() { v := &skipVerify v.mu.Lock() defer v.mu.Unlock() if v.refCount--; v.refCount > 0 { return } transport, ok := http.DefaultTransport.(*http.Transport) if !ok { return } // technically this doesn't return us to the original state, // as TLSClientConfig may have been nil before but won't // be now, but that should be equivalent. transport.TLSClientConfig.InsecureSkipVerify = v.oldSkipVerify } ���������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/������������������������������������0000755�0610621�0607500�00000000000�13172163311�025424� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/version.go��������������������������0000644�0610621�0607500�00000001445�13172163311�027444� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import "gopkg.in/macaroon.v2-unstable" // Version represents a version of the bakery protocol. type Version int const ( // In version 0, discharge-required errors use status 407 Version0 Version = 0 // In version 1, discharge-required errors use status 401. Version1 Version = 1 // In version 2, binary macaroons and caveat ids are supported. Version2 Version = 2 // In version 3, we support operations associated with macaroons // and external third party caveats. Version3 Version = 3 LatestVersion = Version3 ) // MacaroonVersion returns the macaroon version that should // be used with the given bakery Version. func MacaroonVersion(v Version) macaroon.Version { switch v { case Version0, Version1: return macaroon.V1 default: return macaroon.V2 } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/store_test.go�����������������������0000644�0610621�0607500�00000001672�13172163311�030154� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) type StoreSuite struct{} var _ = gc.Suite(&StoreSuite{}) func (*StoreSuite) TestMemStore(c *gc.C) { store := bakery.NewMemRootKeyStore() key, err := store.Get(nil, []byte("x")) c.Assert(err, gc.Equals, bakery.ErrNotFound) c.Assert(key, gc.IsNil) key, err = store.Get(nil, []byte("0")) c.Assert(err, gc.Equals, bakery.ErrNotFound) c.Assert(key, gc.IsNil) key, id, err := store.RootKey(nil) c.Assert(err, gc.IsNil) c.Assert(key, gc.HasLen, 24) c.Assert(string(id), gc.Equals, "0") key1, id1, err := store.RootKey(nil) c.Assert(err, gc.IsNil) c.Assert(key1, jc.DeepEquals, key) c.Assert(id1, gc.DeepEquals, id) key2, err := store.Get(nil, id) c.Assert(err, gc.IsNil) c.Assert(key2, jc.DeepEquals, key) _, err = store.Get(nil, []byte("1")) c.Assert(err, gc.Equals, bakery.ErrNotFound) } ����������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/store.go����������������������������0000644�0610621�0607500�00000010700�13172163311�027105� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "sync" "time" "golang.org/x/net/context" "gopkg.in/macaroon.v2-unstable" ) // RootKeyStore defines store for macaroon root keys. type RootKeyStore interface { // Get returns the root key for the given id. // If the item is not there, it returns ErrNotFound. Get(ctx context.Context, id []byte) ([]byte, error) // RootKey returns the root key to be used for making a new // macaroon, and an id that can be used to look it up later with // the Get method. // // Note that the root keys should remain available for as long // as the macaroons using them are valid. // // Note that there is no need for it to return a new root key // for every call - keys may be reused, although some key // cycling is over time is advisable. RootKey(ctx context.Context) (rootKey []byte, id []byte, err error) } // NewMemRootKeyStore returns an implementation of // Store that generates a single key and always // returns that from RootKey. The same id ("0") is always // used. func NewMemRootKeyStore() RootKeyStore { return new(memRootKeyStore) } type memRootKeyStore struct { mu sync.Mutex key []byte } // Get implements Store.Get. func (s *memRootKeyStore) Get(_ context.Context, id []byte) ([]byte, error) { s.mu.Lock() defer s.mu.Unlock() if len(id) != 1 || id[0] != '0' || s.key == nil { return nil, ErrNotFound } return s.key, nil } // RootKey implements Store.RootKey by always returning the same root // key. func (s *memRootKeyStore) RootKey(context.Context) (rootKey, id []byte, err error) { s.mu.Lock() defer s.mu.Unlock() if s.key == nil { newKey, err := randomBytes(24) if err != nil { return nil, nil, err } s.key = newKey } return s.key, []byte("0"), nil } // MacaroonOpStore provides a mapping from a set of macaroons to their // associated operations and caveats. type MacaroonOpStore interface { // MacaroonOps verifies the signature of the given macaroon and returns // information on its associated operations, and all the first party // caveat conditions that need to be checked. // // This method should not check first party caveats itself. // // It should return a *VerificationError if the error occurred // because the macaroon signature failed or the root key // was not found - any other error will be treated as fatal // by Checker and cause authorization to terminate. MacaroonOps(ctx context.Context, ms macaroon.Slice) ([]Op, []string, error) } // OpsStore defines a persistent store for operation sets // stored by the Oven. // // Implementations must be suitable for concurrent use. type OpsStore interface { // PutOps creates an entry in the store associated with the given // key. A subsequent Get of the same key should result in the // same set of entities. Multiple puts of the same key should be // idempotent. The value associated with a given key will always // be the same. // // The context is derived from the context provided to Authorize // or Capability. // // The key must persist at least until the given expiry time. // // Implementations may assume that the operations // are in canonical order and contain no duplicates. PutOps(ctx context.Context, key string, ops []Op, expiry time.Time) error // GetOps returns the set of operations for a given key. // If the key was not found, it should return an error with an // ErrNotFound cause. // // The context is derived from the context provided to Authorize or Capability. // // TODO Perhaps this should return an interface that // can be used to check membership rather than the // whole set of operations. Then an implementation // might be able to scale more easily to large sets of // operations, for example by using a bloom filter. GetOps(ctx context.Context, key string) ([]Op, error) } type memOpsStore struct { mu sync.Mutex ops map[string][]Op } // NewMemOpsStore returns a new multi-op store that stores // the operations in memory. func NewMemOpsStore() OpsStore { return &memOpsStore{ ops: make(map[string][]Op), } } // PutOps implements OpsStore.PutOps. // TODO implement garbage collection of old operations. func (s *memOpsStore) PutOps(_ context.Context, key string, ops []Op, _ time.Time) error { s.mu.Lock() defer s.mu.Unlock() s.ops[key] = append([]Op(nil), ops...) return nil } // GetOps implements OpsStore.GetOps. func (s *memOpsStore) GetOps(_ context.Context, key string) ([]Op, error) { s.mu.Lock() defer s.mu.Unlock() ops, ok := s.ops[key] if !ok { return nil, ErrNotFound } return ops, nil } ����������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/slice_test.go�����������������������0000644�0610621�0607500�00000014663�13172163311�030123� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "fmt" "time" "github.com/juju/testing" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type SliceSuite struct { testing.IsolationSuite } var _ = gc.Suite(&SliceSuite{}) func (*SliceSuite) TestAddMoreCaveats(c *gc.C) { getDischarge := func(_ context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { c.Check(payload, gc.IsNil) m, err := bakery.NewMacaroon([]byte("root key "+string(cav.Id)), cav.Id, "", bakery.LatestVersion, nil) c.Assert(err, gc.Equals, nil) return m, nil } rootKey := []byte("root key") m, err := bakery.NewMacaroon(rootKey, []byte("id0"), "loc0", bakery.LatestVersion, testChecker.Namespace()) c.Assert(err, gc.Equals, nil) err = m.M().AddThirdPartyCaveat([]byte("root key id1"), []byte("id1"), "somewhere") c.Assert(err, gc.Equals, nil) ms, err := bakery.Slice{m}.DischargeAll(testContext, getDischarge, nil) c.Assert(err, gc.Equals, nil) c.Assert(ms, gc.HasLen, 2) mms := ms.Bind() c.Assert(mms, gc.HasLen, len(ms)) err = mms[0].Verify(rootKey, alwaysOK, mms[1:]) c.Assert(err, gc.Equals, nil) // Add another caveat and to the root macaroon and discharge it. err = ms[0].M().AddThirdPartyCaveat([]byte("root key id2"), []byte("id2"), "somewhere else") c.Assert(err, gc.Equals, nil) ms, err = ms.DischargeAll(testContext, getDischarge, nil) c.Assert(err, gc.Equals, nil) c.Assert(ms, gc.HasLen, 3) mms = ms.Bind() err = mms[0].Verify(rootKey, alwaysOK, mms[1:]) c.Assert(err, gc.Equals, nil) // Check that we can remove the original discharge and still re-acquire it OK. ms = bakery.Slice{ms[0], ms[2]} ms, err = ms.DischargeAll(testContext, getDischarge, nil) c.Assert(err, gc.Equals, nil) c.Assert(ms, gc.HasLen, 3) mms = ms.Bind() err = mms[0].Verify(rootKey, alwaysOK, mms[1:]) c.Assert(err, gc.Equals, nil) } func (*SliceSuite) TestPurge(c *gc.C) { t0 := time.Date(2000, time.October, 1, 12, 0, 0, 0, time.UTC) clock := &stoppedClock{ t: t0, } ctx := checkers.ContextWithClock(testContext, clock) checkCond := func(cond string) error { return testChecker.CheckFirstPartyCaveat(ctx, cond) } rootKey := []byte("root key") m, err := bakery.NewMacaroon(rootKey, []byte("id0"), "loc0", bakery.LatestVersion, testChecker.Namespace()) c.Assert(err, gc.Equals, nil) err = m.AddCaveat(ctx, checkers.TimeBeforeCaveat(t0.Add(time.Hour)), nil, nil) c.Assert(err, gc.Equals, nil) err = m.M().AddThirdPartyCaveat([]byte("root key id1"), []byte("id1"), "somewhere") c.Assert(err, gc.Equals, nil) ms := bakery.Slice{m} getDischarge := func(_ context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { c.Check(payload, gc.IsNil) m, err := bakery.NewMacaroon([]byte("root key "+string(cav.Id)), cav.Id, "", bakery.LatestVersion, testChecker.Namespace()) c.Assert(err, gc.Equals, nil) err = m.AddCaveat(ctx, checkers.TimeBeforeCaveat(clock.t.Add(time.Minute)), nil, nil) c.Assert(err, gc.Equals, nil) return m, nil } ms, err = ms.DischargeAll(testContext, getDischarge, nil) c.Assert(err, gc.Equals, nil) c.Assert(ms, gc.HasLen, 2) mms := ms.Bind() err = mms[0].Verify(rootKey, checkCond, mms[1:]) c.Assert(err, gc.Equals, nil) // Sanity check that verification fails when the discharge time has expired. clock.t = t0.Add(2 * time.Minute) err = mms[0].Verify(rootKey, checkCond, mms[1:]) c.Assert(err, gc.ErrorMatches, `.*: macaroon has expired`) // Purge removes the discharge macaroon when it's out of date. ms = ms.Purge(clock.t) c.Assert(ms, gc.HasLen, 1) // Reacquire a discharge macaroon. ms, err = ms.DischargeAll(testContext, getDischarge, nil) c.Assert(err, gc.Equals, nil) c.Assert(ms, gc.HasLen, 2) // The macaroons should now be valid again. mms = ms.Bind() err = mms[0].Verify(rootKey, checkCond, mms[1:]) c.Assert(err, gc.Equals, nil) // Check that when the time has gone beyond the primary // macaroon's expiry time, Purge removes all the macaroons. // Reacquire a discharge macaroon just before the primary // macaroon's expiry time. clock.t = t0.Add(time.Hour - time.Second) ms = ms.Purge(clock.t) c.Assert(ms, gc.HasLen, 1) ms, err = ms.DischargeAll(testContext, getDischarge, nil) c.Assert(err, gc.Equals, nil) c.Assert(ms, gc.HasLen, 2) // The macaroons should now be valid again. mms = ms.Bind() err = mms[0].Verify(rootKey, checkCond, mms[1:]) c.Assert(err, gc.Equals, nil) // But once we've passed the hour, the primary expires // even though the discharge is valid, and purging // removes both primary and discharge. ms = ms.Purge(t0.Add(time.Hour + time.Millisecond)) c.Assert(ms, gc.HasLen, 0) } func (*SliceSuite) TestDischargeAllAcquiresManyMacaroonsAsPossible(c *gc.C) { failIds := map[string]bool{ "id1": true, "id3": true, } getDischarge := func(_ context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { if failIds[string(cav.Id)] { return nil, errgo.Newf("discharge failure on %q", cav.Id) } m, err := bakery.NewMacaroon([]byte("root key "+string(cav.Id)), cav.Id, "", bakery.LatestVersion, nil) c.Assert(err, gc.Equals, nil) return m, nil } rootKey := []byte("root key") m, err := bakery.NewMacaroon(rootKey, []byte("id-root"), "", bakery.LatestVersion, testChecker.Namespace()) c.Assert(err, gc.Equals, nil) for i := 0; i < 5; i++ { id := fmt.Sprintf("id%d", i) err = m.M().AddThirdPartyCaveat([]byte("root key "+id), []byte(id), "somewhere") c.Assert(err, gc.Equals, nil) } ms := bakery.Slice{m} ms, err = ms.DischargeAll(testContext, getDischarge, nil) c.Check(err, gc.ErrorMatches, `cannot get discharge from "somewhere": discharge failure on "id1"`) c.Assert(ms, gc.HasLen, 4) // Try again without id1 failing - we should acquire one more discharge. // Mark the other ones as failing because we shouldn't be trying to acquire // them because they're already in the slice. failIds = map[string]bool{ "id0": true, "id3": true, "id4": true, } ms, err = ms.DischargeAll(testContext, getDischarge, nil) c.Check(err, gc.ErrorMatches, `cannot get discharge from "somewhere": discharge failure on "id3"`) c.Assert(ms, gc.HasLen, 5) failIds["id3"] = false ms, err = ms.DischargeAll(testContext, getDischarge, nil) c.Check(err, gc.Equals, nil) c.Assert(ms, gc.HasLen, 6) mms := ms.Bind() err = mms[0].Verify(rootKey, alwaysOK, mms[1:]) c.Assert(err, gc.Equals, nil) } �����������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/slice.go����������������������������0000644�0610621�0607500�00000007624�13172163311�027063� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "fmt" "time" "golang.org/x/net/context" errgo "gopkg.in/errgo.v1" macaroon "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // Slice holds a slice of unbound macaroons. type Slice []*Macaroon // Bind prepares the macaroon slice for use in a request. This must be // done before presenting the macaroons to a service for use as // authorization tokens. The result will only be valid // if s contains discharge macaroons for all third party // caveats. // // All the macaroons in the returned slice will be copies // of this in s, not references. func (s Slice) Bind() macaroon.Slice { if len(s) == 0 { return nil } ms := make(macaroon.Slice, len(s)) ms[0] = s[0].M().Clone() rootSig := ms[0].Signature() for i, m := range s[1:] { m1 := m.M().Clone() m1.Bind(rootSig) ms[i+1] = m1 } return ms } // Purge returns a new slice holding all macaroons in s // that expire after the given time. func (ms Slice) Purge(t time.Time) Slice { ms1 := make(Slice, 0, len(ms)) for i, m := range ms { et, ok := checkers.ExpiryTime(m.Namespace(), m.M().Caveats()) if !ok || et.After(t) { ms1 = append(ms1, m) } else if i == 0 { // The primary macaroon has expired, so all its discharges // have expired too. // TODO purge all discharge macaroons when the macaroon // containing their third-party caveat expires. return nil } } return ms1 } // DischargeAll discharges all the third party caveats in the slice for // which discharge macaroons are not already present, using getDischarge // to acquire the discharge macaroons. It always returns the slice with // any acquired discharge macaroons added, even on error. It returns an // error if all the discharges could not be acquired. // // Note that this differs from DischargeAll in that it can be given several existing // discharges, and that the resulting discharges are not bound to the primary, // so it's still possible to add caveats and reacquire expired discharges // without reacquiring the primary macaroon. func (ms Slice) DischargeAll(ctx context.Context, getDischarge func(ctx context.Context, cav macaroon.Caveat, encryptedCaveat []byte) (*Macaroon, error), localKey *KeyPair) (Slice, error) { if len(ms) == 0 { return nil, errgo.Newf("no macaroons to discharge") } ms1 := make(Slice, len(ms)) copy(ms1, ms) // have holds the keys of all the macaroon ids in the slice. type needCaveat struct { // cav holds the caveat that needs discharge. cav macaroon.Caveat // encryptedCaveat holds encrypted caveat // if it was held externally. encryptedCaveat []byte } var need []needCaveat have := make(map[string]bool) for _, m := range ms[1:] { have[string(m.M().Id())] = true } // addCaveats adds any required third party caveats to the need slice // that aren't already present . addCaveats := func(m *Macaroon) { for _, cav := range m.M().Caveats() { if len(cav.VerificationId) == 0 || have[string(cav.Id)] { continue } need = append(need, needCaveat{ cav: cav, encryptedCaveat: m.caveatData[string(cav.Id)], }) } } for _, m := range ms { addCaveats(m) } var errs []error for len(need) > 0 { cav := need[0] need = need[1:] var dm *Macaroon var err error if localKey != nil && cav.cav.Location == "local" { // TODO use a small caveat id. dm, err = Discharge(ctx, DischargeParams{ Key: localKey, Checker: localDischargeChecker, Caveat: cav.encryptedCaveat, Id: cav.cav.Id, Locator: emptyLocator{}, }) } else { dm, err = getDischarge(ctx, cav.cav, cav.encryptedCaveat) } if err != nil { errs = append(errs, errgo.NoteMask(err, fmt.Sprintf("cannot get discharge from %q", cav.cav.Location), errgo.Any)) continue } ms1 = append(ms1, dm) addCaveats(dm) } if errs != nil { // TODO log other errors? Return them all? return ms1, errgo.Mask(errs[0], errgo.Any) } return ms1, nil } ������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/package_test.go���������������������0000644�0610621�0607500�00000000170�13172163311�030403� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/oven_test.go������������������������0000644�0610621�0607500�00000011413�13172163311�027761� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "fmt" jujutesting "github.com/juju/testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) type ovenSuite struct { jujutesting.LoggingSuite } var _ = gc.Suite(&ovenSuite{}) var canonicalOpsTests = []struct { about string ops []bakery.Op expect []bakery.Op }{{ about: "empty slice", }, { about: "one element", ops: []bakery.Op{{"a", "a"}}, expect: []bakery.Op{{"a", "a"}}, }, { about: "all in order", ops: []bakery.Op{{"a", "a"}, {"a", "b"}, {"c", "c"}}, expect: []bakery.Op{{"a", "a"}, {"a", "b"}, {"c", "c"}}, }, { about: "out of order", ops: []bakery.Op{{"c", "c"}, {"a", "b"}, {"a", "a"}}, expect: []bakery.Op{{"a", "a"}, {"a", "b"}, {"c", "c"}}, }, { about: "with duplicates", ops: []bakery.Op{{"c", "c"}, {"a", "b"}, {"a", "a"}, {"c", "a"}, {"c", "b"}, {"c", "c"}, {"a", "a"}}, expect: []bakery.Op{{"a", "a"}, {"a", "b"}, {"c", "a"}, {"c", "b"}, {"c", "c"}}, }, { about: "make sure we've got the fields right", ops: []bakery.Op{{Entity: "read", Action: "two"}, {Entity: "read", Action: "one"}, {Entity: "write", Action: "one"}}, expect: []bakery.Op{{Entity: "read", Action: "one"}, {Entity: "read", Action: "two"}, {Entity: "write", Action: "one"}}, }} func (*ovenSuite) TestCanonicalOps(c *gc.C) { for i, test := range canonicalOpsTests { c.Logf("test %d: %v", i, test.about) ops := append([]bakery.Op(nil), test.ops...) c.Assert(bakery.CanonicalOps(ops), jc.DeepEquals, test.expect) // Verify that the original slice isn't changed. c.Assert(ops, jc.DeepEquals, test.ops) } } func (*ovenSuite) TestMultipleOps(c *gc.C) { oven := bakery.NewOven(bakery.OvenParams{ OpsStore: bakery.NewMemOpsStore(), }) ops := []bakery.Op{{"one", "read"}, {"one", "write"}, {"two", "read"}} m, err := oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, ops...) c.Assert(err, gc.IsNil) gotOps, conds, err := oven.MacaroonOps(testContext, macaroon.Slice{m.M()}) c.Assert(err, gc.IsNil) c.Assert(conds, gc.HasLen, 1) // time-before caveat. c.Assert(bakery.CanonicalOps(gotOps), jc.DeepEquals, ops) } func (*ovenSuite) TestMultipleOpsInId(c *gc.C) { oven := bakery.NewOven(bakery.OvenParams{}) ops := []bakery.Op{{"one", "read"}, {"one", "write"}, {"two", "read"}} m, err := oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, ops...) c.Assert(err, gc.IsNil) gotOps, conds, err := oven.MacaroonOps(testContext, macaroon.Slice{m.M()}) c.Assert(err, gc.IsNil) c.Assert(conds, gc.HasLen, 1) // time-before caveat. c.Assert(bakery.CanonicalOps(gotOps), jc.DeepEquals, ops) } func (*ovenSuite) TestMultipleOpsInIdWithVersion1(c *gc.C) { oven := bakery.NewOven(bakery.OvenParams{}) ops := []bakery.Op{{"one", "read"}, {"one", "write"}, {"two", "read"}} m, err := oven.NewMacaroon(testContext, bakery.Version1, ages, nil, ops...) c.Assert(err, gc.IsNil) gotOps, conds, err := oven.MacaroonOps(testContext, macaroon.Slice{m.M()}) c.Assert(err, gc.IsNil) c.Assert(conds, gc.HasLen, 1) // time-before caveat. c.Assert(bakery.CanonicalOps(gotOps), jc.DeepEquals, ops) } func (*ovenSuite) TestHugeNumberOfOpsGivesSmallMacaroon(c *gc.C) { oven := bakery.NewOven(bakery.OvenParams{ OpsStore: bakery.NewMemOpsStore(), }) ops := make([]bakery.Op, 30000) for i := range ops { ops[i] = bakery.Op{fmt.Sprintf("entity%d", i), fmt.Sprintf("action%d", i)} } m, err := oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, ops...) c.Assert(err, gc.IsNil) // Sanity-check that all the operations really are stored there. gotOps, _, err := oven.MacaroonOps(testContext, macaroon.Slice{m.M()}) c.Assert(err, gc.IsNil) c.Assert(bakery.CanonicalOps(gotOps), jc.DeepEquals, bakery.CanonicalOps(ops)) data, err := m.MarshalJSON() c.Assert(err, gc.IsNil) c.Logf("size %d", len(data)) if want := 300; len(data) > want { c.Fatalf("encoded macaroon bigger than expected; got %d want < %d", len(data), want) } } func (*ovenSuite) TestOpsStoredOnlyOnce(c *gc.C) { store := bakery.NewMemOpsStore() oven := bakery.NewOven(bakery.OvenParams{ OpsStore: store, }) ops := []bakery.Op{{"one", "read"}, {"one", "write"}, {"two", "read"}} m, err := oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, ops...) c.Assert(err, gc.IsNil) gotOps, _, err := oven.MacaroonOps(testContext, macaroon.Slice{m.M()}) c.Assert(err, gc.IsNil) c.Assert(bakery.CanonicalOps(gotOps), jc.DeepEquals, bakery.CanonicalOps(ops)) // Make another macaroon containing the same ops in a different order. ops = []bakery.Op{{"one", "write"}, {"one", "read"}, {"one", "read"}, {"two", "read"}} _, err = oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, ops...) c.Assert(err, gc.IsNil) c.Assert(bakery.MemOpsStoreLen(store), gc.Equals, 1) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/oven.go�����������������������������0000644�0610621�0607500�00000030062�13172163311�026723� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "bytes" "crypto/sha256" "encoding/base64" "sort" "strings" "time" "github.com/rogpeppe/fastuuid" "golang.org/x/net/context" errgo "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/bakery/internal/macaroonpb" ) var uuidGen = fastuuid.MustNewGenerator() // Oven bakes macaroons. They emerge sweet and delicious // and ready for use in a Checker. // // All macaroons are associated with one or more operations (see // the Op type) which define the capabilities of the macaroon. // // There is one special operation, "login" (defined by LoginOp) // which grants the capability to speak for a particular user. // The login capability will never be mixed with other capabilities. // // It is up to the caller to decide on semantics for other operations. type Oven struct { p OvenParams } type OvenParams struct { // Namespace holds the namespace to use when adding first party caveats. // If this is nil, checkers.New(nil).Namespace will be used. Namespace *checkers.Namespace // RootKeyStoreForEntity returns the macaroon storage to be // used for root keys associated with macaroons created // wth NewMacaroon. // // If this is nil, NewMemRootKeyStore will be used to create // a new store to be used for all entities. RootKeyStoreForOps func(ops []Op) RootKeyStore // OpsStore is used to persistently store the association of // multi-op entities with their associated operations // when NewMacaroon is called with multiple operations. // // If this is nil, embed the operations will be stored directly in the macaroon id. // Note that this can make the macaroons large. // // When this is in use, operation entities with the prefix "multi-" are // reserved - a "multi-"-prefixed entity represents a set of operations // stored in the OpsStore. OpsStore OpsStore // Key holds the private key pair used to encrypt third party caveats. // If it is nil, no third party caveats can be created. Key *KeyPair // Location holds the location that will be associated with new macaroons // (as returned by Macaroon.Location). Location string // Locator is used to find out information on third parties when // adding third party caveats. If this is nil, no non-local third // party caveats can be added. Locator ThirdPartyLocator // TODO max macaroon or macaroon id size? } // NewOven returns a new oven using the given parameters. func NewOven(p OvenParams) *Oven { if p.Locator == nil { p.Locator = emptyLocator{} } if p.RootKeyStoreForOps == nil { store := NewMemRootKeyStore() p.RootKeyStoreForOps = func(ops []Op) RootKeyStore { return store } } if p.Namespace == nil { p.Namespace = checkers.New(nil).Namespace() } return &Oven{ p: p, } } // MacaroonOps implements MacaroonOpStore.MacaroonOps, making Oven // an instance of MacaroonOpStore. // // For macaroons minted with previous bakery versions, it always // returns a single LoginOp operation. func (o *Oven) MacaroonOps(ctx context.Context, ms macaroon.Slice) (ops []Op, conditions []string, err error) { if len(ms) == 0 { return nil, nil, errgo.Newf("no macaroons in slice") } storageId, ops, err := decodeMacaroonId(ms[0].Id()) if err != nil { return nil, nil, errgo.Mask(err) } rootKey, err := o.p.RootKeyStoreForOps(ops).Get(ctx, storageId) if err != nil { if errgo.Cause(err) != ErrNotFound { return nil, nil, errgo.Notef(err, "cannot get macaroon") } // If the macaroon was not found, it is probably // because it's been removed after time-expiry, // so return a verification error. return nil, nil, &VerificationError{ Reason: errgo.Newf("macaroon not found in storage"), } } conditions, err = ms[0].VerifySignature(rootKey, ms[1:]) if err != nil { return nil, nil, &VerificationError{ Reason: errgo.Mask(err), } } if o.p.OpsStore != nil && len(ops) == 1 && strings.HasPrefix(ops[0].Entity, "multi-") { // It's a multi-op entity, so retrieve the actual operations it's associated with. ops, err = o.p.OpsStore.GetOps(ctx, ops[0].Entity) if err != nil { return nil, nil, errgo.Notef(err, "cannot get operations for %q", ops[0].Entity) } } return ops, conditions, nil } func decodeMacaroonId(id []byte) (storageId []byte, ops []Op, err error) { base64Decoded := false if id[0] == 'A' { // The first byte is not a version number and it's 'A', which is the // base64 encoding of the top 6 bits (all zero) of the version number 2 or 3, // so we assume that it's the base64 encoding of a new-style // macaroon id, so we base64 decode it. // // Note that old-style ids always start with an ASCII character >= 4 // (> 32 in fact) so this logic won't be triggered for those. dec := make([]byte, base64.RawURLEncoding.DecodedLen(len(id))) n, err := base64.RawURLEncoding.Decode(dec, id) if err == nil { // Set the id only on success - if it's a bad encoding, we'll get a not-found error // which is fine because "not found" is a correct description of the issue - we // can't find the root key for the given id. id = dec[0:n] base64Decoded = true } } // Trim any extraneous information from the id before retrieving // it from storage, including the UUID that's added when // creating macaroons to make all macaroons unique even if // they're using the same root key. switch id[0] { case byte(Version2): // Skip the UUID at the start of the id. storageId = id[1+16:] case byte(Version3): var id1 macaroonpb.MacaroonId if err := id1.UnmarshalBinary(id[1:]); err != nil { return nil, nil, errgo.Notef(err, "cannot unmarshal macaroon id") } if len(id1.Ops) == 0 || len(id1.Ops[0].Actions) == 0 { return nil, nil, errgo.Newf("no operations found in macaroon") } ops = make([]Op, 0, len(id1.Ops)) for _, op := range id1.Ops { for _, action := range op.Actions { ops = append(ops, Op{ Entity: op.Entity, Action: action, }) } } return id1.StorageId, ops, nil } if !base64Decoded && isLowerCaseHexChar(id[0]) { // It's an old-style id, probably with a hyphenated UUID. // so trim that off. if i := bytes.LastIndexByte(id, '-'); i >= 0 { storageId = id[0:i] } } return storageId, []Op{LoginOp}, nil } // NewMacaroon takes a macaroon with the given version from the oven, associates it with the given operations // and attaches the given caveats. There must be at least one operation specified. // // The macaroon will expire at the given time - a TimeBefore first party caveat will be added with // that time. func (o *Oven) NewMacaroon(ctx context.Context, version Version, expiry time.Time, caveats []checkers.Caveat, ops ...Op) (*Macaroon, error) { if len(ops) == 0 { return nil, errgo.Newf("cannot mint a macaroon associated with no operations") } ops = CanonicalOps(ops) rootKey, storageId, err := o.p.RootKeyStoreForOps(ops).RootKey(ctx) if err != nil { return nil, errgo.Mask(err) } id, err := o.newMacaroonId(ctx, ops, storageId, expiry) if err != nil { return nil, errgo.Mask(err) } idBytesNoVersion, err := id.MarshalBinary() if err != nil { return nil, errgo.Mask(err) } idBytes := make([]byte, len(idBytesNoVersion)+1) idBytes[0] = byte(LatestVersion) // TODO We could use a proto.Buffer to avoid this copy. copy(idBytes[1:], idBytesNoVersion) if MacaroonVersion(version) < macaroon.V2 { // The old macaroon format required valid text for the macaroon id, // so base64-encode it. b64data := make([]byte, base64.RawURLEncoding.EncodedLen(len(idBytes))) base64.RawURLEncoding.Encode(b64data, idBytes) idBytes = b64data } m, err := NewMacaroon(rootKey, idBytes, o.p.Location, version, o.p.Namespace) if err != nil { return nil, errgo.Notef(err, "cannot create macaroon with version %v", version) } if err := o.AddCaveat(ctx, m, checkers.TimeBeforeCaveat(expiry)); err != nil { return nil, errgo.Mask(err) } if err := o.AddCaveats(ctx, m, caveats); err != nil { return nil, errgo.Mask(err) } return m, nil } // AddCaveat adds a caveat to the given macaroon. func (o *Oven) AddCaveat(ctx context.Context, m *Macaroon, cav checkers.Caveat) error { return m.AddCaveat(ctx, cav, o.p.Key, o.p.Locator) } // AddCaveats adds all the caveats to the given macaroon. func (o *Oven) AddCaveats(ctx context.Context, m *Macaroon, caveats []checkers.Caveat) error { return m.AddCaveats(ctx, caveats, o.p.Key, o.p.Locator) } // Key returns the oven's private/public key par. func (o *Oven) Key() *KeyPair { return o.p.Key } // Locator returns the third party locator that the // oven was created with. func (o *Oven) Locator() ThirdPartyLocator { return o.p.Locator } // CanonicalOps returns the given operations slice sorted // with duplicates removed. func CanonicalOps(ops []Op) []Op { canonOps := opsByValue(ops) needNewSlice := false for i := 1; i < len(ops); i++ { if !canonOps.Less(i-1, i) { needNewSlice = true break } } if !needNewSlice { return ops } canonOps = make([]Op, len(ops)) copy(canonOps, ops) sort.Sort(canonOps) // Note we know that there's at least one operation here // because we'd have returned earlier if the slice was empty. j := 0 for _, op := range canonOps[1:] { if op != canonOps[j] { j++ canonOps[j] = op } } return canonOps[0 : j+1] } func (o *Oven) newMacaroonId(ctx context.Context, ops []Op, storageId []byte, expiry time.Time) (*macaroonpb.MacaroonId, error) { uuid := uuidGen.Next() nonce := uuid[0:16] if len(ops) == 1 || o.p.OpsStore == nil { return &macaroonpb.MacaroonId{ Nonce: nonce, StorageId: storageId, Ops: macaroonIdOps(ops), }, nil } // We've got several operations and a multi-op store, so use the store. // TODO use the store only if the encoded macaroon id exceeds some size? entity := newOpsEntity(ops) if err := o.p.OpsStore.PutOps(ctx, entity, ops, expiry); err != nil { return nil, errgo.Notef(err, "cannot store ops") } return &macaroonpb.MacaroonId{ Nonce: nonce, StorageId: storageId, Ops: []*macaroonpb.Op{{ Entity: entity, Actions: []string{"*"}, }}, }, nil } // newOpsEntity returns a new multi-op entity name that represents // all the given operations and caveats. It returns the same value regardless // of the ordering of the operations. It assumes that the operations // have been canonicalized and that there's at least one operation. func newOpsEntity(ops []Op) string { // Hash the operations, removing duplicates as we go. h := sha256.New() data := make([]byte, len(ops[0].Action)+len(ops[0].Entity)+2) for _, op := range ops { data = data[:0] data = append(data, op.Action...) data = append(data, '\n') data = append(data, op.Entity...) data = append(data, '\n') h.Write(data) } entity := make([]byte, len("multi-")+base64.RawURLEncoding.EncodedLen(sha256.Size)) copy(entity, "multi-") base64.RawURLEncoding.Encode(entity[len("multi-"):], h.Sum(data[:0])) return string(entity) } // macaroonIdOps returns operations suitable for serializing // as part of an *macaroonpb.MacaroonId. It assumes that // ops has been canonicalized and that there's at least // one operation. func macaroonIdOps(ops []Op) []*macaroonpb.Op { idOps := make([]macaroonpb.Op, 0, len(ops)) idOps = append(idOps, macaroonpb.Op{ Entity: ops[0].Entity, Actions: []string{ops[0].Action}, }) i := 0 idOp := &idOps[0] for _, op := range ops[1:] { if op.Entity != idOp.Entity { idOps = append(idOps, macaroonpb.Op{ Entity: op.Entity, Actions: []string{op.Action}, }) i++ idOp = &idOps[i] continue } if op.Action != idOp.Actions[len(idOp.Actions)-1] { idOp.Actions = append(idOp.Actions, op.Action) } } idOpPtrs := make([]*macaroonpb.Op, len(idOps)) for i := range idOps { idOpPtrs[i] = &idOps[i] } return idOpPtrs } type opsByValue []Op func (o opsByValue) Less(i, j int) bool { o0, o1 := o[i], o[j] if o0.Entity != o1.Entity { return o0.Entity < o1.Entity } return o0.Action < o1.Action } func (o opsByValue) Swap(i, j int) { o[i], o[j] = o[j], o[i] } func (o opsByValue) Len() int { return len(o) } func isLowerCaseHexChar(c byte) bool { switch { case '0' <= c && c <= '9': return true case 'a' <= c && c <= 'f': return true } return false } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/mgorootkeystore/��������������������0000755�0610621�0607500�00000000000�13172163311�030700� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/mgorootkeystore/rootkey_test.go�����0000644�0610621�0607500�00000035130�13172163311�033764� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package mgorootkeystore_test import ( "fmt" "time" "github.com/juju/testing" jc "github.com/juju/testing/checkers" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/mgo.v2" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/mgorootkeystore" ) type RootKeyStoreSuite struct { testing.IsolatedMgoSuite } var _ = gc.Suite(&RootKeyStoreSuite{}) var epoch = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC) var isValidWithPolicyTests = []struct { about string policy mgorootkeystore.Policy now time.Time key mgorootkeystore.RootKey expect bool }{{ about: "success", policy: mgorootkeystore.Policy{ GenerateInterval: 2 * time.Minute, ExpiryDuration: 3 * time.Minute, }, now: epoch.Add(20 * time.Minute), key: mgorootkeystore.RootKey{ Created: epoch.Add(19 * time.Minute), Expires: epoch.Add(24 * time.Minute), Id: []byte("id"), RootKey: []byte("key"), }, expect: true, }, { about: "empty root key", policy: mgorootkeystore.Policy{ GenerateInterval: 2 * time.Minute, ExpiryDuration: 3 * time.Minute, }, now: epoch.Add(20 * time.Minute), key: mgorootkeystore.RootKey{}, expect: false, }, { about: "created too early", policy: mgorootkeystore.Policy{ GenerateInterval: 2 * time.Minute, ExpiryDuration: 3 * time.Minute, }, now: epoch.Add(20 * time.Minute), key: mgorootkeystore.RootKey{ Created: epoch.Add(18*time.Minute - time.Millisecond), Expires: epoch.Add(24 * time.Minute), Id: []byte("id"), RootKey: []byte("key"), }, expect: false, }, { about: "expires too early", policy: mgorootkeystore.Policy{ GenerateInterval: 2 * time.Minute, ExpiryDuration: 3 * time.Minute, }, now: epoch.Add(20 * time.Minute), key: mgorootkeystore.RootKey{ Created: epoch.Add(19 * time.Minute), Expires: epoch.Add(21 * time.Minute), Id: []byte("id"), RootKey: []byte("key"), }, expect: false, }, { about: "expires too late", policy: mgorootkeystore.Policy{ GenerateInterval: 2 * time.Minute, ExpiryDuration: 3 * time.Minute, }, now: epoch.Add(20 * time.Minute), key: mgorootkeystore.RootKey{ Created: epoch.Add(19 * time.Minute), Expires: epoch.Add(25*time.Minute + time.Millisecond), Id: []byte("id"), RootKey: []byte("key"), }, expect: false, }} func (s *RootKeyStoreSuite) TestIsValidWithPolicy(c *gc.C) { var now time.Time s.PatchValue(mgorootkeystore.TimeNow, func() time.Time { return now }) for i, test := range isValidWithPolicyTests { c.Logf("test %d: %v", i, test.about) now = test.now c.Assert(mgorootkeystore.IsValidWithPolicy(test.key, test.policy), gc.Equals, test.expect) } } func (s *RootKeyStoreSuite) TestRootKeyUsesKeysValidWithPolicy(c *gc.C) { // We re-use the TestIsValidWithPolicy tests so that we // know that the mongo logic uses the same behaviour. var now time.Time s.PatchValue(mgorootkeystore.TimeNow, func() time.Time { return now }) for i, test := range isValidWithPolicyTests { c.Logf("test %d: %v", i, test.about) if test.key.RootKey == nil { // We don't store empty root keys in the database. c.Logf("skipping test with empty root key") continue } // Prime the collection with the root key document. _, err := s.coll().RemoveAll(nil) c.Assert(err, gc.IsNil) err = s.coll().Insert(test.key) c.Assert(err, gc.IsNil) store := mgorootkeystore.NewRootKeys(10).NewStore(s.coll(), test.policy) now = test.now key, id, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) if test.expect { c.Assert(string(id), gc.Equals, "id") c.Assert(string(key), gc.Equals, "key") } else { // If it didn't match then RootKey will have // generated a new key. c.Assert(key, gc.HasLen, 24) c.Assert(id, gc.HasLen, 32) } } } func (s *RootKeyStoreSuite) TestRootKey(c *gc.C) { now := epoch s.PatchValue(mgorootkeystore.TimeNow, func() time.Time { return now }) store := mgorootkeystore.NewRootKeys(10).NewStore(s.coll(), mgorootkeystore.Policy{ GenerateInterval: 2 * time.Minute, ExpiryDuration: 5 * time.Minute, }) key, id, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(key, gc.HasLen, 24) c.Assert(id, gc.HasLen, 32) // If we get a key within the generate interval, we should // get the same one. now = epoch.Add(time.Minute) key1, id1, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(key1, gc.DeepEquals, key) c.Assert(id1, gc.DeepEquals, id) // A different store instance should get the same root key. store1 := mgorootkeystore.NewRootKeys(10).NewStore(s.coll(), mgorootkeystore.Policy{ GenerateInterval: 2 * time.Minute, ExpiryDuration: 5 * time.Minute, }) key1, id1, err = store1.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(key1, gc.DeepEquals, key) c.Assert(id1, gc.DeepEquals, id) // After the generation interval has passed, we should generate a new key. now = epoch.Add(2*time.Minute + time.Second) key1, id1, err = store.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(key, gc.HasLen, 24) c.Assert(id, gc.HasLen, 32) c.Assert(key1, gc.Not(gc.DeepEquals), key) c.Assert(id1, gc.Not(gc.DeepEquals), id) // The other store should pick it up too. key2, id2, err := store1.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(key2, gc.DeepEquals, key1) c.Assert(id2, gc.DeepEquals, id1) } func (s *RootKeyStoreSuite) TestRootKeyDefaultGenerateInterval(c *gc.C) { now := epoch s.PatchValue(mgorootkeystore.TimeNow, func() time.Time { return now }) store := mgorootkeystore.NewRootKeys(10).NewStore(s.coll(), mgorootkeystore.Policy{ ExpiryDuration: 5 * time.Minute, }) key, id, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) now = epoch.Add(5 * time.Minute) key1, id1, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(key1, jc.DeepEquals, key) c.Assert(id1, jc.DeepEquals, id) now = epoch.Add(5*time.Minute + time.Millisecond) key1, id1, err = store.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(string(key1), gc.Not(gc.Equals), string(key)) c.Assert(string(id1), gc.Not(gc.Equals), string(id)) } var preferredRootKeyTests = []struct { about string now time.Time keys []mgorootkeystore.RootKey policy mgorootkeystore.Policy expectId []byte }{{ about: "latest creation time is preferred", now: epoch.Add(5 * time.Minute), keys: []mgorootkeystore.RootKey{{ Created: epoch.Add(4 * time.Minute), Expires: epoch.Add(15 * time.Minute), Id: []byte("id0"), RootKey: []byte("key0"), }, { Created: epoch.Add(5*time.Minute + 30*time.Second), Expires: epoch.Add(16 * time.Minute), Id: []byte("id1"), RootKey: []byte("key1"), }, { Created: epoch.Add(5 * time.Minute), Expires: epoch.Add(16 * time.Minute), Id: []byte("id2"), RootKey: []byte("key2"), }}, policy: mgorootkeystore.Policy{ GenerateInterval: 5 * time.Minute, ExpiryDuration: 7 * time.Minute, }, expectId: []byte("id1"), }, { about: "ineligible keys are exluded", now: epoch.Add(5 * time.Minute), keys: []mgorootkeystore.RootKey{{ Created: epoch.Add(4 * time.Minute), Expires: epoch.Add(15 * time.Minute), Id: []byte("id0"), RootKey: []byte("key0"), }, { Created: epoch.Add(5 * time.Minute), Expires: epoch.Add(16*time.Minute + 30*time.Second), Id: []byte("id1"), RootKey: []byte("key1"), }, { Created: epoch.Add(6 * time.Minute), Expires: epoch.Add(time.Hour), Id: []byte("id2"), RootKey: []byte("key2"), }}, policy: mgorootkeystore.Policy{ GenerateInterval: 5 * time.Minute, ExpiryDuration: 7 * time.Minute, }, expectId: []byte("id1"), }} func (s *RootKeyStoreSuite) TestPreferredRootKeyFromDatabase(c *gc.C) { var now time.Time s.PatchValue(mgorootkeystore.TimeNow, func() time.Time { return now }) for i, test := range preferredRootKeyTests { c.Logf("%d: %v", i, test.about) _, err := s.coll().RemoveAll(nil) c.Assert(err, gc.IsNil) for _, key := range test.keys { err := s.coll().Insert(key) c.Assert(err, gc.IsNil) } store := mgorootkeystore.NewRootKeys(10).NewStore(s.coll(), test.policy) now = test.now _, id, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(id, gc.DeepEquals, test.expectId) } } func (s *RootKeyStoreSuite) TestPreferredRootKeyFromCache(c *gc.C) { var now time.Time s.PatchValue(mgorootkeystore.TimeNow, func() time.Time { return now }) for i, test := range preferredRootKeyTests { c.Logf("%d: %v", i, test.about) for _, key := range test.keys { err := s.coll().Insert(key) c.Assert(err, gc.IsNil) } store := mgorootkeystore.NewRootKeys(10).NewStore(s.coll(), test.policy) // Ensure that all the keys are in cache by getting all of them. for _, key := range test.keys { got, err := store.Get(context.Background(), key.Id) c.Assert(err, gc.IsNil) c.Assert(got, jc.DeepEquals, key.RootKey) } // Remove all the keys from the collection so that // we know we must be acquiring them from the cache. _, err := s.coll().RemoveAll(nil) c.Assert(err, gc.IsNil) // Test that RootKey returns the expected key. now = test.now _, id, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(id, jc.DeepEquals, test.expectId) } } func (s *RootKeyStoreSuite) TestGet(c *gc.C) { now := epoch s.PatchValue(mgorootkeystore.TimeNow, func() time.Time { return now }) store := mgorootkeystore.NewRootKeys(5).NewStore(s.coll(), mgorootkeystore.Policy{ GenerateInterval: 1 * time.Minute, ExpiryDuration: 30 * time.Minute, }) type idKey struct { id string key []byte } var keys []idKey keyIds := make(map[string]bool) for i := 0; i < 20; i++ { key, id, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(keyIds[string(id)], gc.Equals, false) keys = append(keys, idKey{string(id), key}) now = now.Add(time.Minute + time.Second) } for i, k := range keys { key, err := store.Get(context.Background(), []byte(k.id)) c.Assert(err, gc.IsNil, gc.Commentf("key %d (%s)", i, k.id)) c.Assert(key, gc.DeepEquals, k.key, gc.Commentf("key %d (%s)", i, k.id)) } // Check that the keys are cached. // // Since the cache size is 5, the most recent 5 items will be in // the primary cache; the 5 items before that will be in the old // cache and nothing else will be cached. // // The first time we fetch an item from the old cache, a new // primary cache will be allocated, all existing items in the // old cache except that item will be evicted, and all items in // the current primary cache moved to the old cache. // // The upshot of that is that all but the first 6 calls to Get // should result in a database fetch. var fetched []string s.PatchValue(mgorootkeystore.MgoCollectionFindId, func(coll *mgo.Collection, id interface{}) *mgo.Query { fetched = append(fetched, string(id.([]byte))) return coll.FindId(id) }) c.Logf("testing cache") for i := len(keys) - 1; i >= 0; i-- { k := keys[i] key, err := store.Get(context.Background(), []byte(k.id)) c.Assert(err, gc.IsNil) c.Assert(err, gc.IsNil, gc.Commentf("key %d (%s)", i, k.id)) c.Assert(key, gc.DeepEquals, k.key, gc.Commentf("key %d (%s)", i, k.id)) } c.Assert(len(fetched), gc.Equals, len(keys)-6) for i, id := range fetched { c.Assert(id, gc.Equals, keys[len(keys)-6-i-1].id) } } func (s *RootKeyStoreSuite) TestGetCachesMisses(c *gc.C) { store := mgorootkeystore.NewRootKeys(5).NewStore(s.coll(), mgorootkeystore.Policy{ GenerateInterval: 1 * time.Minute, ExpiryDuration: 30 * time.Minute, }) var fetched []string s.PatchValue(mgorootkeystore.MgoCollectionFindId, func(coll *mgo.Collection, id interface{}) *mgo.Query { fetched = append(fetched, fmt.Sprintf("%#v", id)) return coll.FindId(id) }) key, err := store.Get(context.Background(), []byte("foo")) c.Assert(err, gc.Equals, bakery.ErrNotFound) c.Assert(key, gc.IsNil) // This should check twice first using a []byte second using a string c.Assert(fetched, jc.DeepEquals, []string{fmt.Sprintf("%#v", []byte("foo")), fmt.Sprintf("%#v", "foo")}) fetched = nil key, err = store.Get(context.Background(), []byte("foo")) c.Assert(err, gc.Equals, bakery.ErrNotFound) c.Assert(key, gc.IsNil) c.Assert(fetched, gc.IsNil) } func (s *RootKeyStoreSuite) TestGetExpiredItemFromCache(c *gc.C) { now := epoch s.PatchValue(mgorootkeystore.TimeNow, func() time.Time { return now }) store := mgorootkeystore.NewRootKeys(10).NewStore(s.coll(), mgorootkeystore.Policy{ ExpiryDuration: 5 * time.Minute, }) _, id, err := store.RootKey(context.Background()) c.Assert(err, gc.IsNil) s.PatchValue(mgorootkeystore.MgoCollectionFindId, func(*mgo.Collection, interface{}) *mgo.Query { c.Errorf("FindId unexpectedly called") return nil }) now = epoch.Add(15 * time.Minute) _, err = store.Get(context.Background(), id) c.Assert(err, gc.Equals, bakery.ErrNotFound) } func (s *RootKeyStoreSuite) TestEnsureIndex(c *gc.C) { keys := mgorootkeystore.NewRootKeys(5) err := keys.EnsureIndex(s.coll()) c.Assert(err, gc.IsNil) // This code can take up to 60s to run; there's no way // to force it to run more quickly, but it provides reassurance // that the code actually works. // Reenable the rest of this test if concerned about index behaviour. c.SucceedNow() _, id1, err := keys.NewStore(s.coll(), mgorootkeystore.Policy{ ExpiryDuration: 100 * time.Millisecond, }).RootKey(context.Background()) c.Assert(err, gc.IsNil) _, id2, err := keys.NewStore(s.coll(), mgorootkeystore.Policy{ ExpiryDuration: time.Hour, }).RootKey(context.Background()) c.Assert(err, gc.IsNil) c.Assert(id2, gc.Not(gc.Equals), id1) // Sanity check that the keys are in the collection. n, err := s.coll().Find(nil).Count() c.Assert(err, gc.IsNil) c.Assert(n, gc.Equals, 2) for i := 0; i < 100; i++ { n, err := s.coll().Find(nil).Count() c.Assert(err, gc.IsNil) switch n { case 1: c.SucceedNow() case 2: time.Sleep(time.Second) default: c.Fatalf("unexpected key count %v", n) } } c.Fatalf("key was never removed from database") } type legacyRootKey struct { Id string `bson:"_id"` Created time.Time Expires time.Time RootKey []byte } func (s *RootKeyStoreSuite) TestLegacy(c *gc.C) { err := s.coll().Insert(&legacyRootKey{ Id: "foo", RootKey: []byte("a key"), Created: time.Now(), Expires: time.Now().Add(10 * time.Minute), }) c.Assert(err, gc.IsNil) store := mgorootkeystore.NewRootKeys(10).NewStore(s.coll(), mgorootkeystore.Policy{ ExpiryDuration: 5 * time.Minute, }) rk, err := store.Get(context.Background(), []byte("foo")) c.Assert(err, gc.IsNil) c.Assert(string(rk), gc.Equals, "a key") } func (s *RootKeyStoreSuite) coll() *mgo.Collection { return s.Session.DB("test").C("items") } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/mgorootkeystore/rootkey.go����������0000644�0610621�0607500�00000024566�13172163311�032740� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package mgorootkeystore provides an implementation of bakery.RootKeyStore // that uses MongoDB as a persistent store. package mgorootkeystore import ( "crypto/rand" "fmt" "sync" "time" "github.com/juju/loggo" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) // Functions defined as variables so they can be overidden // for testing. var ( timeNow = time.Now mgoCollectionFindId = (*mgo.Collection).FindId ) var logger = loggo.GetLogger("bakery.mgorootkeystore") // maxPolicyCache holds the maximum number of store policies that can // hold cached keys in a given RootKeys instance. // // 100 is probably overkill, given that practical systems will // likely only have a small number of active policies on any given // macaroon collection. const maxPolicyCache = 100 // RootKeys represents a cache of macaroon root keys. type RootKeys struct { maxCacheSize int // TODO (rogpeppe) use RWMutex instead of Mutex here so that // it's faster in the probably-common case that we // have many contended readers. mu sync.Mutex oldCache map[string]rootKey cache map[string]rootKey // current holds the current root key for each store policy. current map[Policy]rootKey } type rootKey struct { Id []byte `bson:"_id"` Created time.Time Expires time.Time RootKey []byte } // isValid reports whether the root key contains a key. Note that we // always generate non-empty root keys, so we use this to find // whether the root key is empty or not. func (rk rootKey) isValid() bool { return rk.RootKey != nil } // isValidWithPolicy reports whether the given root key // is currently valid to use with the given store policy. func (rk rootKey) isValidWithPolicy(p Policy) bool { if !rk.isValid() { return false } now := timeNow() return afterEq(rk.Created, now.Add(-p.GenerateInterval)) && afterEq(rk.Expires, now.Add(p.ExpiryDuration)) && beforeEq(rk.Expires, now.Add(p.ExpiryDuration+p.GenerateInterval)) } // NewRootKeys returns a root-keys cache that // is limited in size to approximately the given size. // // The NewStore method returns a store implementation // that uses a specific mongo collection and store // policy. func NewRootKeys(maxCacheSize int) *RootKeys { return &RootKeys{ maxCacheSize: maxCacheSize, cache: make(map[string]rootKey), current: make(map[Policy]rootKey), } } // Policy holds a store policy for root keys. type Policy struct { // GenerateInterval holds the maximum length of time // for which a root key will be returned from RootKey. // If this is zero, it defaults to ExpiryDuration. GenerateInterval time.Duration // ExpiryDuration holds the minimum length of time that // root keys will be valid for after they are returned from // RootKey. The maximum length of time that they // will be valid for is ExpiryDuration + GenerateInterval. ExpiryDuration time.Duration } // NewStore returns a new RootKeyStore implementation that // stores and obtains root keys from the given collection. // // Root keys will be generated and stored following the // given store policy. // // It is expected that all collections passed to a given Store's // NewStore method should refer to the same underlying collection. func (s *RootKeys) NewStore(c *mgo.Collection, policy Policy) bakery.RootKeyStore { if policy.GenerateInterval == 0 { policy.GenerateInterval = policy.ExpiryDuration } return &store{ keys: s, coll: c, policy: policy, } } var indexes = []mgo.Index{{ Key: []string{"-created"}, }, { Key: []string{"expires"}, ExpireAfter: time.Second, }} // EnsureIndex ensures that the required indexes exist on the // collection that will be used for root key store. // This should be called at least once before using NewStore. func (s *RootKeys) EnsureIndex(c *mgo.Collection) error { for _, idx := range indexes { if err := c.EnsureIndex(idx); err != nil { return errgo.Notef(err, "cannot ensure index for %q on %q", idx.Key, c.Name) } } return nil } // get gets the root key for the given id, trying the cache first and // falling back to calling fallback if it's not found there. // // If the key does not exist or has expired, it returns // bakery.ErrNotFound. // // Called with s.mu locked. func (s *RootKeys) get(id []byte, fallback func(id []byte) (rootKey, error)) (rootKey, error) { key, cached, err := s.get0(id, fallback) if err != nil && err != bakery.ErrNotFound { return rootKey{}, errgo.Mask(err) } if err == nil && timeNow().After(key.Expires) { key = rootKey{} err = bakery.ErrNotFound } if !cached { s.addCache(id, key) } return key, err } // get0 is the inner version of RootKeys.get. It returns an item and reports // whether it was found in the cache, but doesn't check whether the // item has expired or move the returned item to s.cache. func (s *RootKeys) get0(id []byte, fallback func(id []byte) (rootKey, error)) (key rootKey, inCache bool, err error) { if k, ok := s.cache[string(id)]; ok { if !k.isValid() { return rootKey{}, true, bakery.ErrNotFound } return k, true, nil } if k, ok := s.oldCache[string(id)]; ok { if !k.isValid() { return rootKey{}, false, bakery.ErrNotFound } return k, false, nil } logger.Infof("cache miss for %q", id) k, err := fallback(id) return k, false, err } // addCache adds the given key to the cache. // Called with s.mu locked. func (s *RootKeys) addCache(id []byte, k rootKey) { if len(s.cache) >= s.maxCacheSize { s.oldCache = s.cache s.cache = make(map[string]rootKey) } s.cache[string(id)] = k } // setCurrent sets the current key for the given store policy. // Called with s.mu locked. func (s *RootKeys) setCurrent(policy Policy, key rootKey) { if len(s.current) > maxPolicyCache { // Sanity check to avoid possibly memory leak: // if some client is using arbitrarily many store // policies, we don't want s.keys.current to endlessly // expand, so just kill the cache if it grows too big. // This will result in worse performance but it shouldn't // happen in practice and it's better than using endless // space. s.current = make(map[Policy]rootKey) } s.current[policy] = key } type store struct { keys *RootKeys policy Policy coll *mgo.Collection } // Get implements bakery.RootKeyStore.Get. func (s *store) Get(ctx context.Context, id []byte) ([]byte, error) { s.keys.mu.Lock() defer s.keys.mu.Unlock() key, err := s.keys.get(id, s.getFromMongo) if err != nil { return nil, err } return key.RootKey, nil } func (s *store) getFromMongo(id []byte) (rootKey, error) { var key rootKey err := mgoCollectionFindId(s.coll, id).One(&key) if err != nil { if err == mgo.ErrNotFound { return s.getLegacyFromMongo(string(id)) } return rootKey{}, errgo.Notef(err, "cannot get key from database") } // TODO migrate the key from the old format to the new format. return key, nil } // getLegacyFromMongo gets a value from the old version of the // root key document which used a string key rather than a []byte // key. func (s *store) getLegacyFromMongo(id string) (rootKey, error) { var key rootKey err := mgoCollectionFindId(s.coll, id).One(&key) if err != nil { if err == mgo.ErrNotFound { return rootKey{}, bakery.ErrNotFound } return rootKey{}, errgo.Notef(err, "cannot get key from database") } return key, nil } // RootKey implements bakery.RootKeyStore.RootKey by // returning an existing key from the cache when compatible // with the current policy. func (s *store) RootKey(context.Context) ([]byte, []byte, error) { if key := s.rootKeyFromCache(); key.isValid() { return key.RootKey, key.Id, nil } logger.Debugf("root key cache miss") // Try to find a root key from the collection. // It doesn't matter much if two concurrent mongo // clients are doing this at the same time because // we don't mind if there are more keys than necessary. // // Note that this query mirrors the logic found in // store.rootKeyFromCache. now := timeNow() var key rootKey err := s.coll.Find(bson.D{{ "created", bson.D{{"$gte", now.Add(-s.policy.GenerateInterval)}}, }, { "expires", bson.D{ {"$gte", now.Add(s.policy.ExpiryDuration)}, {"$lte", now.Add(s.policy.ExpiryDuration + s.policy.GenerateInterval)}, }, }}).Sort("-created").One(&key) if err != nil && err != mgo.ErrNotFound { return nil, nil, errgo.Notef(err, "cannot query existing keys") } if !key.isValid() { // No keys found anywhere, so let's create one. var err error key, err = s.generateKey() if err != nil { return nil, nil, errgo.Notef(err, "cannot generate key") } logger.Infof("new root key id %q; created %v; expires %v", key.Id, key.Created, key.Expires) if err := s.coll.Insert(key); err != nil { return nil, nil, errgo.Notef(err, "cannot create root key") } } s.keys.mu.Lock() defer s.keys.mu.Unlock() s.keys.addCache(key.Id, key) s.keys.setCurrent(s.policy, key) return key.RootKey, key.Id, nil } // rootKeyFromCache returns a root key from the cached keys. // If no keys are found that are valid for s.policy, it returns // the zero key. func (s *store) rootKeyFromCache() rootKey { s.keys.mu.Lock() defer s.keys.mu.Unlock() if k, ok := s.keys.current[s.policy]; ok && k.isValidWithPolicy(s.policy) { return k } // Find the most recently created key that's consistent with the // store policy. var current rootKey for _, k := range s.keys.cache { if k.isValidWithPolicy(s.policy) && k.Created.After(current.Created) { current = k } } if current.isValid() { s.keys.current[s.policy] = current return current } return rootKey{} } func (s *store) generateKey() (rootKey, error) { newKey, err := randomBytes(24) if err != nil { return rootKey{}, err } newId, err := randomBytes(16) if err != nil { return rootKey{}, err } now := timeNow() return rootKey{ Created: now, Expires: now.Add(s.policy.ExpiryDuration + s.policy.GenerateInterval), // TODO return just newId when we know we can always // use non-text macaroon ids. Id: []byte(fmt.Sprintf("%x", newId)), RootKey: newKey, }, nil } func randomBytes(n int) ([]byte, error) { b := make([]byte, n) _, err := rand.Read(b) if err != nil { return nil, fmt.Errorf("cannot generate %d random bytes: %v", n, err) } return b, nil } // afterEq reports whether t0 is after or equal to t1. func afterEq(t0, t1 time.Time) bool { return !t0.Before(t1) } // beforeEq reports whether t1 is before or equal to t0. func beforeEq(t0, t1 time.Time) bool { return !t0.After(t1) } ������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/mgorootkeystore/package_test.go�����0000644�0610621�0607500�00000000244�13172163311�033661� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package mgorootkeystore_test import ( "testing" jujutesting "github.com/juju/testing" ) func TestPackage(t *testing.T) { jujutesting.MgoTestPackage(t, nil) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/mgorootkeystore/export_test.go������0000644�0610621�0607500�00000000341�13172163311�033605� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package mgorootkeystore var ( TimeNow = &timeNow MgoCollectionFindId = &mgoCollectionFindId ) type RootKey rootKey func IsValidWithPolicy(k RootKey, p Policy) bool { return rootKey(k).isValidWithPolicy(p) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/macaroon_test.go��������������������0000644�0610621�0607500�00000017123�13172163311�030615� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "encoding/json" jujutesting "github.com/juju/testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type macaroonSuite struct { jujutesting.LoggingSuite } var _ = gc.Suite(&macaroonSuite{}) func (*macaroonSuite) TestNewMacaroon(c *gc.C) { ns := checkers.NewNamespace(nil) m, err := bakery.NewMacaroon([]byte("rootkey"), []byte("some id"), "here", bakery.LatestVersion, ns) c.Assert(err, gc.IsNil) c.Assert(m.Namespace(), gc.Equals, ns) c.Assert(m.Version(), gc.Equals, bakery.LatestVersion) c.Assert(string(m.M().Id()), gc.Equals, "some id") c.Assert(m.M().Location(), gc.Equals, "here") c.Assert(m.M().Version(), gc.Equals, bakery.MacaroonVersion(bakery.LatestVersion)) } func (*macaroonSuite) TestAddFirstPartyCaveat(c *gc.C) { ns := checkers.NewNamespace(nil) ns.Register("someuri", "x") m, err := bakery.NewMacaroon([]byte("rootkey"), []byte("some id"), "here", bakery.LatestVersion, ns) c.Assert(err, gc.IsNil) err = m.AddCaveat(testContext, checkers.Caveat{ Condition: "something", Namespace: "someuri", }, nil, nil) c.Assert(err, gc.IsNil) c.Assert(m.M().Caveats(), jc.DeepEquals, []macaroon.Caveat{{ Id: []byte("x:something"), }}) } // lbv holds the latest bakery version as used in the // third party caveat id. var lbv = byte(bakery.LatestVersion) var addThirdPartyCaveatTests = []struct { about string baseId []byte existingCaveatIds [][]byte expectId []byte }{{ about: "no existing id", expectId: []byte{lbv, 0}, }, { about: "several existing ids", existingCaveatIds: [][]byte{ {lbv, 0}, {lbv, 1}, {lbv, 2}, }, expectId: []byte{lbv, 3}, }, { about: "with base id", existingCaveatIds: [][]byte{ {lbv, 0}, }, baseId: []byte{lbv, 0}, expectId: []byte{lbv, 0, 0}, }, { about: "with base id and existing id", existingCaveatIds: [][]byte{ {lbv, 0, 0}, }, baseId: []byte{lbv, 0}, expectId: []byte{lbv, 0, 1}, }} func (*macaroonSuite) TestAddThirdPartyCaveat(c *gc.C) { locator := bakery.NewThirdPartyStore() as := newBakery("as-loc", locator) for i, test := range addThirdPartyCaveatTests { c.Logf("test %d: %v", i, test.about) m, err := bakery.NewMacaroon([]byte("root key"), []byte("id"), "location", bakery.LatestVersion, nil) c.Assert(err, gc.IsNil) for _, id := range test.existingCaveatIds { err := m.M().AddThirdPartyCaveat(nil, id, "") c.Assert(err, gc.IsNil) } bakery.SetMacaroonCaveatIdPrefix(m, test.baseId) err = m.AddCaveat(testContext, checkers.Caveat{ Location: "as-loc", Condition: "something", }, as.Oven.Key(), locator) c.Assert(err, gc.IsNil) c.Assert(m.M().Caveats()[len(test.existingCaveatIds)].Id, jc.DeepEquals, test.expectId) } } func (*macaroonSuite) TestMarshalJSONLatestVersion(c *gc.C) { locator := bakery.NewThirdPartyStore() as := newBakery("as-loc", locator) ns := checkers.NewNamespace(map[string]string{ "testns": "x", "otherns": "y", }) m, err := bakery.NewMacaroon([]byte("root key"), []byte("id"), "location", bakery.LatestVersion, ns) c.Assert(err, gc.IsNil) err = m.AddCaveat(testContext, checkers.Caveat{ Location: "as-loc", Condition: "something", }, as.Oven.Key(), locator) c.Assert(err, gc.IsNil) data, err := json.Marshal(m) c.Assert(err, gc.IsNil) var m1 *bakery.Macaroon err = json.Unmarshal(data, &m1) c.Assert(err, gc.IsNil) // Just check the signature and version - we're not interested in fully // checking the macaroon marshaling here. c.Assert(m1.M().Signature(), jc.DeepEquals, m.M().Signature()) c.Assert(m1.M().Version(), gc.Equals, m.M().Version()) c.Assert(m1.M().Caveats(), gc.HasLen, 1) c.Assert(m1.Namespace(), jc.DeepEquals, m.Namespace()) c.Assert(bakery.MacaroonCaveatData(m1), jc.DeepEquals, bakery.MacaroonCaveatData(m)) } func (s *macaroonSuite) TestMarshalJSONVersion1(c *gc.C) { s.testMarshalJSONWithVersion(c, bakery.Version1) } func (s *macaroonSuite) TestMarshalJSONVersion2(c *gc.C) { s.testMarshalJSONWithVersion(c, bakery.Version2) } func (*macaroonSuite) testMarshalJSONWithVersion(c *gc.C, version bakery.Version) { locator := bakery.NewThirdPartyStore() as := newBakery("as-loc", locator) ns := checkers.NewNamespace(map[string]string{ "testns": "x", }) m, err := bakery.NewMacaroon([]byte("root key"), []byte("id"), "location", version, ns) c.Assert(err, gc.IsNil) err = m.AddCaveat(testContext, checkers.Caveat{ Location: "as-loc", Condition: "something", }, as.Oven.Key(), locator) c.Assert(err, gc.IsNil) // Sanity check that no external caveat data has been added. c.Assert(bakery.MacaroonCaveatData(m), gc.HasLen, 0) data, err := json.Marshal(m) c.Assert(err, gc.IsNil) var m1 *bakery.Macaroon err = json.Unmarshal(data, &m1) c.Assert(err, gc.IsNil) // Just check the signature and version - we're not interested in fully // checking the macaroon marshaling here. c.Assert(m1.M().Signature(), jc.DeepEquals, m.M().Signature()) c.Assert(m1.M().Version(), gc.Equals, bakery.MacaroonVersion(version)) c.Assert(m1.M().Caveats(), gc.HasLen, 1) // Namespace information has been thrown away. c.Assert(m1.Namespace(), jc.DeepEquals, bakery.LegacyNamespace()) c.Assert(bakery.MacaroonCaveatData(m1), gc.HasLen, 0) // Check that we can unmarshal it directly as a V2 macaroon var m2 *macaroon.Macaroon err = json.Unmarshal(data, &m2) c.Assert(err, gc.IsNil) c.Assert(m2.Signature(), jc.DeepEquals, m.M().Signature()) c.Assert(m2.Version(), gc.Equals, bakery.MacaroonVersion(version)) c.Assert(m2.Caveats(), gc.HasLen, 1) } func (*macaroonSuite) TestUnmarshalJSONUnknownVersion(c *gc.C) { m, err := macaroon.New(nil, nil, "", macaroon.V2) c.Assert(err, gc.IsNil) data, err := json.Marshal(bakery.MacaroonJSON{ Macaroon: m, Version: bakery.LatestVersion + 1, }) c.Assert(err, gc.IsNil) var m1 *bakery.Macaroon err = json.Unmarshal([]byte(data), &m1) c.Assert(err, gc.ErrorMatches, `unexpected bakery macaroon version; got 4 want 3`) } func (*macaroonSuite) TestUnmarshalJSONInconsistentVersion(c *gc.C) { m, err := macaroon.New(nil, nil, "", macaroon.V1) c.Assert(err, gc.IsNil) data, err := json.Marshal(bakery.MacaroonJSON{ Macaroon: m, Version: bakery.LatestVersion, }) c.Assert(err, gc.IsNil) var m1 *bakery.Macaroon err = json.Unmarshal([]byte(data), &m1) c.Assert(err, gc.ErrorMatches, `underlying macaroon has inconsistent version; got 1 want 2`) } func (*macaroonSuite) TestClone(c *gc.C) { locator := bakery.NewThirdPartyStore() as := newBakery("as-loc", locator) ns := checkers.NewNamespace(map[string]string{ "testns": "x", }) m, err := bakery.NewMacaroon([]byte("root key"), []byte("id"), "location", bakery.LatestVersion, ns) c.Assert(err, gc.IsNil) err = m.AddCaveat(testContext, checkers.Caveat{ Location: "as-loc", Condition: "something", }, as.Oven.Key(), locator) c.Assert(err, gc.IsNil) m1 := m.Clone() c.Assert(m.M().Caveats(), gc.HasLen, 1) c.Assert(m1.M().Caveats(), gc.HasLen, 1) c.Assert(bakery.MacaroonCaveatData(m), gc.DeepEquals, bakery.MacaroonCaveatData(m1)) err = m.AddCaveat(testContext, checkers.Caveat{ Location: "as-loc", Condition: "something", }, as.Oven.Key(), locator) c.Assert(err, gc.IsNil) c.Assert(m.M().Caveats(), gc.HasLen, 2) c.Assert(m1.M().Caveats(), gc.HasLen, 1) c.Assert(bakery.MacaroonCaveatData(m), gc.Not(gc.DeepEquals), bakery.MacaroonCaveatData(m1)) } func (*macaroonSuite) TestUnmarshalBadData(c *gc.C) { var m1 *bakery.Macaroon err := json.Unmarshal([]byte(`{"m": []}`), &m1) c.Assert(err, gc.ErrorMatches, `json: cannot unmarshal array .*`) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/macaroon.go�������������������������0000644�0610621�0607500�00000027120�13172163311�027554� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "bytes" "encoding/base64" "encoding/binary" "encoding/json" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // legacyNamespace holds the standard namespace as used by // pre-version3 macaroons. func legacyNamespace() *checkers.Namespace { ns := checkers.NewNamespace(nil) ns.Register(checkers.StdNamespace, "") return ns } // Macaroon represents an undischarged macaroon along with its first // party caveat namespace and associated third party caveat information // which should be passed to the third party when discharging a caveat. type Macaroon struct { // m holds the underlying macaroon. m *macaroon.Macaroon // version holds the version of the macaroon. version Version // caveatData maps from a third party caveat id to its // associated information, usually public-key encrypted with the // third party's public key. // // If version is less than Version3, this will always be nil, // because clients prior to that version do not support // macaroon-external caveat ids. caveatData map[string][]byte // namespace holds the first-party caveat namespace of the macaroon. namespace *checkers.Namespace // caveatIdPrefix holds the prefix to use for the ids of any third // party caveats created. This can be set when Discharge creates a // discharge macaroon. caveatIdPrefix []byte } // NewLegacyMacaroon returns a new macaroon holding m. // This should only be used when there's no alternative // (for example when m has been unmarshaled // from some alternative format). func NewLegacyMacaroon(m *macaroon.Macaroon) (*Macaroon, error) { v, err := bakeryVersion(m.Version()) if err != nil { return nil, errgo.Mask(err) } return &Macaroon{ m: m, version: v, namespace: legacyNamespace(), }, nil } type macaroonJSON struct { Macaroon *macaroon.Macaroon `json:"m"` Version Version `json:"v"` // Note: CaveatData is encoded using URL-base64-encoded keys // because JSON cannot deal with arbitrary byte sequences // in its strings, and URL-base64 values to match the // standard macaroon encoding. CaveatData map[string]string `json:"cdata,omitempty"` Namespace *checkers.Namespace `json:"ns"` } // Clone returns a copy of the macaroon. Note that the the new // macaroon's namespace still points to the same underlying Namespace - // copying the macaroon does not make a copy of the namespace. func (m *Macaroon) Clone() *Macaroon { m1 := *m m1.m = m1.m.Clone() m1.caveatData = make(map[string][]byte) for id, data := range m.caveatData { m1.caveatData[id] = data } return &m1 } // MarshalJSON implements json.Marshaler by marshaling // the macaroon into the original macaroon format if the // version is earlier than Version3. func (m *Macaroon) MarshalJSON() ([]byte, error) { if m.version < Version3 { if len(m.caveatData) > 0 { return nil, errgo.Newf("cannot marshal pre-version3 macaroon with external caveat data") } return m.m.MarshalJSON() } caveatData := make(map[string]string) for id, data := range m.caveatData { caveatData[base64.RawURLEncoding.EncodeToString([]byte(id))] = base64.RawURLEncoding.EncodeToString(data) } return json.Marshal(macaroonJSON{ Macaroon: m.m, Version: m.version, CaveatData: caveatData, Namespace: m.namespace, }) } // UnmarshalJSON implements json.Unmarshaler by unmarshaling in a // backwardly compatible way - if provided with a previous macaroon // version, it will unmarshal that too. func (m *Macaroon) UnmarshalJSON(data []byte) error { // First try with new data format. var m1 macaroonJSON if err := json.Unmarshal(data, &m1); err != nil { // If we get an unmarshal error, we won't be able // to unmarshal into the old format either, as extra fields // are ignored. return errgo.Mask(err) } if m1.Macaroon == nil { return m.unmarshalJSONOldFormat(data) } // We've got macaroon field - it's the new format. if m1.Version < Version3 || m1.Version > LatestVersion { return errgo.Newf("unexpected bakery macaroon version; got %d want %d", m1.Version, Version3) } if got, want := m1.Macaroon.Version(), MacaroonVersion(m1.Version); got != want { return errgo.Newf("underlying macaroon has inconsistent version; got %d want %d", got, want) } caveatData := make(map[string][]byte) for id64, data64 := range m1.CaveatData { id, err := macaroon.Base64Decode([]byte(id64)) if err != nil { return errgo.Notef(err, "cannot decode caveat id") } data, err := macaroon.Base64Decode([]byte(data64)) if err != nil { return errgo.Notef(err, "cannot decode caveat") } caveatData[string(id)] = data } m.caveatData = caveatData m.m = m1.Macaroon m.namespace = m1.Namespace // TODO should we allow version > LatestVersion here? m.version = m1.Version return nil } // unmarshalJSONOldFormat unmarshals the data from an old format // macaroon (without any external caveats or namespace). func (m *Macaroon) unmarshalJSONOldFormat(data []byte) error { // Try to unmarshal from the original format. var m1 *macaroon.Macaroon if err := json.Unmarshal(data, &m1); err != nil { return errgo.Mask(err) } m2, err := NewLegacyMacaroon(m1) if err != nil { return errgo.Mask(err) } *m = *m2 return nil } // bakeryVersion returns a bakery version that corresponds to // the macaroon version v. It is necessarily approximate because // several bakery versions can correspond to a single macaroon // version, so it's only of use when decoding legacy formats // (in Macaroon.UnmarshalJSON). // // It will return an error if it doesn't recognize the version. func bakeryVersion(v macaroon.Version) (Version, error) { switch v { case macaroon.V1: // Use version 1 because we don't know of any existing // version 0 clients. return Version1, nil case macaroon.V2: // Note that this could also correspond to Version3, but // this logic is explicitly for legacy versions. return Version2, nil default: return 0, errgo.Newf("unknown macaroon version when legacy-unmarshaling bakery macaroon; got %d", v) } } // NewMacaroon creates and returns a new macaroon with the given root // key, id and location. If the version is more than the latest known // version, the latest known version will be used. The namespace is that // of the service creating it. func NewMacaroon(rootKey, id []byte, location string, version Version, ns *checkers.Namespace) (*Macaroon, error) { if version > LatestVersion { version = LatestVersion } m, err := macaroon.New(rootKey, id, location, MacaroonVersion(version)) if err != nil { return nil, errgo.Notef(err, "cannot create macaroon") } return &Macaroon{ m: m, version: version, namespace: ns, }, nil } // M returns the underlying macaroon held within m. func (m *Macaroon) M() *macaroon.Macaroon { return m.m } // Version returns the bakery version of the first party // that created the macaroon. func (m *Macaroon) Version() Version { return m.version } // Namespace returns the first party caveat namespace of the macaroon. func (m *Macaroon) Namespace() *checkers.Namespace { return m.namespace } // AddCaveats is a convenienced method that calls m.AddCaveat for each // caveat in cavs. func (m *Macaroon) AddCaveats(ctx context.Context, cavs []checkers.Caveat, key *KeyPair, loc ThirdPartyLocator) error { for _, cav := range cavs { if err := m.AddCaveat(ctx, cav, key, loc); err != nil { return errgo.Notef(err, "cannot add caveat %#v", cav) } } return nil } // AddCaveat adds a caveat to the given macaroon. // // If it's a third-party caveat, it encrypts it using the given key pair // and by looking up the location using the given locator. If it's a // first party cavat, key and loc are unused. // // As a special case, if the caveat's Location field has the prefix // "local " the caveat is added as a client self-discharge caveat using // the public key base64-encoded in the rest of the location. In this // case, the Condition field must be empty. The resulting third-party // caveat will encode the condition "true" encrypted with that public // key. See LocalThirdPartyCaveat for a way of creating such caveats. func (m *Macaroon) AddCaveat(ctx context.Context, cav checkers.Caveat, key *KeyPair, loc ThirdPartyLocator) error { if cav.Location == "" { if err := m.m.AddFirstPartyCaveat(m.namespace.ResolveCaveat(cav).Condition); err != nil { return errgo.Mask(err) } return nil } if key == nil { return errgo.Newf("no private key to encrypt third party caveat") } var info ThirdPartyInfo if localInfo, ok := parseLocalLocation(cav.Location); ok { info = localInfo cav.Location = "local" if cav.Condition != "" { return errgo.New("cannot specify caveat condition in local third-party caveat") } cav.Condition = "true" } else { if loc == nil { return errgo.Newf("no locator when adding third party caveat") } var err error info, err = loc.ThirdPartyInfo(ctx, cav.Location) if err != nil { return errgo.Notef(err, "cannot find public key for location %q", cav.Location) } } rootKey, err := randomBytes(24) if err != nil { return errgo.Notef(err, "cannot generate third party secret") } // Use the least supported version to encode the caveat. if m.version < info.Version { info.Version = m.version } caveatInfo, err := encodeCaveat(cav.Condition, rootKey, info, key, m.namespace) if err != nil { return errgo.Notef(err, "cannot create third party caveat at %q", cav.Location) } var id []byte if info.Version < Version3 { // We're encoding for an earlier client or third party which does // not understand bundled caveat info, so use the encoded // caveat information as the caveat id. id = caveatInfo } else { id = m.newCaveatId(m.caveatIdPrefix) if m.caveatData == nil { m.caveatData = make(map[string][]byte) } m.caveatData[string(id)] = caveatInfo } if err := m.m.AddThirdPartyCaveat(rootKey, id, cav.Location); err != nil { return errgo.Notef(err, "cannot add third party caveat") } return nil } // newCaveatId returns a third party caveat id that // does not duplicate any third party caveat ids already inside m. // // If base is non-empty, it is used as the id prefix. func (m *Macaroon) newCaveatId(base []byte) []byte { var id []byte if len(base) > 0 { id = make([]byte, len(base), len(base)+binary.MaxVarintLen64) copy(id, base) } else { id = make([]byte, 0, 1+binary.MaxVarintLen32) // Add a version byte to the caveat id. Technically // this is unnecessary as the caveat-decoding logic // that looks at versions should never see this id, // but if the caveat payload isn't provided with the // payload, having this version gives a strong indication // that the payload has been omitted so we can produce // a better error for the user. id = append(id, byte(Version3)) } // Iterate through integers looking for one that isn't already used, // starting from n so that if everyone is using this same algorithm, // we'll only perform one iteration. // // Note that although this looks like an infinite loop, // there's no way that it can run for more iterations // than the total number of existing third party caveats, // whatever their ids. caveats := m.m.Caveats() again: for i := len(m.caveatData); ; i++ { // We append a varint to the end of the id and assume that // any client that's created the id that we're using as a base // is using similar conventions - in the worst case they might // end up with a duplicate third party caveat id and thus create // a macaroon that cannot be discharged. id1 := appendUvarint(id, uint64(i)) for _, cav := range caveats { if cav.VerificationId != nil && bytes.Equal(cav.Id, id1) { continue again } } return id1 } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/keys_test.go������������������������0000644�0610621�0607500�00000007373�13172163311�027777� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "encoding/base64" "encoding/json" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/yaml.v2" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) type KeysSuite struct{} var _ = gc.Suite(&KeysSuite{}) var testKey = newTestKey(0) func (*KeysSuite) TestMarshalBinary(c *gc.C) { data, err := testKey.MarshalBinary() c.Assert(err, gc.IsNil) c.Assert(data, jc.DeepEquals, []byte(testKey[:])) var key1 bakery.Key err = key1.UnmarshalBinary(data) c.Assert(err, gc.IsNil) c.Assert(key1, gc.DeepEquals, testKey) } func (*KeysSuite) TestMarshalText(c *gc.C) { data, err := testKey.MarshalText() c.Assert(err, gc.IsNil) c.Assert(string(data), gc.Equals, base64.StdEncoding.EncodeToString([]byte(testKey[:]))) var key1 bakery.Key err = key1.UnmarshalText(data) c.Assert(err, gc.IsNil) c.Assert(key1, gc.Equals, testKey) } func (*KeysSuite) TestUnmarshalTextWrongKeyLength(c *gc.C) { var key bakery.Key err := key.UnmarshalText([]byte("aGVsbG8K")) c.Assert(err, gc.ErrorMatches, `wrong length for key, got 6 want 32`) } func (*KeysSuite) TestKeyPairMarshalJSON(c *gc.C) { kp := bakery.KeyPair{ Public: bakery.PublicKey{testKey}, Private: bakery.PrivateKey{testKey}, } kp.Private.Key[0] = 99 data, err := json.Marshal(kp) c.Assert(err, gc.IsNil) var x map[string]interface{} err = json.Unmarshal(data, &x) c.Assert(err, gc.IsNil) // Check that the fields have marshaled as strings. c.Assert(x["private"], gc.FitsTypeOf, "") c.Assert(x["public"], gc.FitsTypeOf, "") var kp1 bakery.KeyPair err = json.Unmarshal(data, &kp1) c.Assert(err, gc.IsNil) c.Assert(kp1, jc.DeepEquals, kp) } func (*KeysSuite) TestKeyPairMarshalYAML(c *gc.C) { kp := bakery.KeyPair{ Public: bakery.PublicKey{testKey}, Private: bakery.PrivateKey{testKey}, } kp.Private.Key[0] = 99 data, err := yaml.Marshal(kp) c.Assert(err, gc.IsNil) var x map[string]interface{} err = yaml.Unmarshal(data, &x) c.Assert(err, gc.IsNil) // Check that the fields have marshaled as strings. c.Assert(x["private"], gc.FitsTypeOf, "") c.Assert(x["public"], gc.FitsTypeOf, "") var kp1 bakery.KeyPair err = yaml.Unmarshal(data, &kp1) c.Assert(err, gc.IsNil) c.Assert(kp1, jc.DeepEquals, kp) } func (*KeysSuite) TestKeyPairUnmarshalJSONMissingPublicKey(c *gc.C) { data := `{"private": "7ZcOvDAW9opAIPzJ7FdSbz2i2qL8bFZapDlmNLpMzpU="}` var k bakery.KeyPair err := json.Unmarshal([]byte(data), &k) c.Assert(err, gc.ErrorMatches, `missing public key`) } func (*KeysSuite) TestKeyPairUnmarshalJSONMissingPrivateKey(c *gc.C) { data := `{"public": "7ZcOvDAW9opAIPzJ7FdSbz2i2qL8bFZapDlmNLpMzpU="}` var k bakery.KeyPair err := json.Unmarshal([]byte(data), &k) c.Assert(err, gc.ErrorMatches, `missing private key`) } func (*KeysSuite) TestKeyPairUnmarshalJSONEmptyKeys(c *gc.C) { data := `{"private": "", "public": ""}` var k bakery.KeyPair err := json.Unmarshal([]byte(data), &k) c.Assert(err, gc.ErrorMatches, `wrong length for key, got 0 want 32`) } func (*KeysSuite) TestKeyPairUnmarshalJSONNoKeys(c *gc.C) { data := `{}` var k bakery.KeyPair err := json.Unmarshal([]byte(data), &k) c.Assert(err, gc.ErrorMatches, `missing public key`) } func (*KeysSuite) TestKeyPairUnmarshalYAMLMissingPublicKey(c *gc.C) { data := ` private: 7ZcOvDAW9opAIPzJ7FdSbz2i2qL8bFZapDlmNLpMzpU= ` var k bakery.KeyPair err := yaml.Unmarshal([]byte(data), &k) c.Assert(err, gc.ErrorMatches, `missing public key`) } func (*KeysSuite) TestKeyPairUnmarshalYAMLMissingPrivateKey(c *gc.C) { data := ` public: 7ZcOvDAW9opAIPzJ7FdSbz2i2qL8bFZapDlmNLpMzpU= ` var k bakery.KeyPair err := yaml.Unmarshal([]byte(data), &k) c.Assert(err, gc.ErrorMatches, `missing private key`) } func newTestKey(n byte) bakery.Key { var k bakery.Key for i := range k { k[i] = n + byte(i) } return k } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/keys.go�����������������������������0000644�0610621�0607500�00000012523�13172163311�026731� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "crypto/rand" "encoding/base64" "encoding/json" "strings" "sync" "golang.org/x/crypto/nacl/box" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" ) // KeyLen is the byte length of the Ed25519 public and private keys used for // caveat id encryption. const KeyLen = 32 // NonceLen is the byte length of the nonce values used for caveat id // encryption. const NonceLen = 24 // PublicKey is a 256-bit Ed25519 public key. type PublicKey struct { Key } // PrivateKey is a 256-bit Ed25519 private key. type PrivateKey struct { Key } // Key is a 256-bit Ed25519 key. type Key [KeyLen]byte // String returns the base64 representation of the key. func (k Key) String() string { return base64.StdEncoding.EncodeToString(k[:]) } // MarshalBinary implements encoding.BinaryMarshaler.MarshalBinary. func (k Key) MarshalBinary() ([]byte, error) { return k[:], nil } // isZero reports whether the key consists entirely of zeros. func (k Key) isZero() bool { return k == Key{} } // UnmarshalBinary implements encoding.BinaryUnmarshaler.UnmarshalBinary. func (k *Key) UnmarshalBinary(data []byte) error { if len(data) != len(k) { return errgo.Newf("wrong length for key, got %d want %d", len(data), len(k)) } copy(k[:], data) return nil } // MarshalText implements encoding.TextMarshaler.MarshalText. func (k Key) MarshalText() ([]byte, error) { data := make([]byte, base64.StdEncoding.EncodedLen(len(k))) base64.StdEncoding.Encode(data, k[:]) return data, nil } // boxKey returns the box package's type for a key. func (k Key) boxKey() *[KeyLen]byte { return (*[KeyLen]byte)(&k) } // UnmarshalText implements encoding.TextUnmarshaler.UnmarshalText. func (k *Key) UnmarshalText(text []byte) error { data, err := macaroon.Base64Decode(text) if err != nil { return errgo.Notef(err, "cannot decode base64 key") } if len(data) != len(k) { return errgo.Newf("wrong length for key, got %d want %d", len(data), len(k)) } copy(k[:], data) return nil } // ThirdPartyInfo holds information on a given third party // discharge service. type ThirdPartyInfo struct { // PublicKey holds the public key of the third party. PublicKey PublicKey // Version holds latest the bakery protocol version supported // by the discharger. Version Version } // ThirdPartyLocator is used to find information on third // party discharge services. type ThirdPartyLocator interface { // ThirdPartyInfo returns information on the third // party at the given location. It returns ErrNotFound if no match is found. // This method must be safe to call concurrently. ThirdPartyInfo(ctx context.Context, loc string) (ThirdPartyInfo, error) } // ThirdPartyStore implements a simple ThirdPartyLocator. // A trailing slash on locations is ignored. type ThirdPartyStore struct { mu sync.RWMutex m map[string]ThirdPartyInfo } // NewThirdPartyStore returns a new instance of ThirdPartyStore // that stores locations in memory. func NewThirdPartyStore() *ThirdPartyStore { return &ThirdPartyStore{ m: make(map[string]ThirdPartyInfo), } } // AddInfo associates the given information with the // given location, ignoring any trailing slash. // This method is OK to call concurrently with sThirdPartyInfo. func (s *ThirdPartyStore) AddInfo(loc string, info ThirdPartyInfo) { s.mu.Lock() defer s.mu.Unlock() s.m[canonicalLocation(loc)] = info } func canonicalLocation(loc string) string { return strings.TrimSuffix(loc, "/") } // ThirdPartyInfo implements the ThirdPartyLocator interface. func (s *ThirdPartyStore) ThirdPartyInfo(ctx context.Context, loc string) (ThirdPartyInfo, error) { s.mu.RLock() defer s.mu.RUnlock() if info, ok := s.m[canonicalLocation(loc)]; ok { return info, nil } return ThirdPartyInfo{}, ErrNotFound } // KeyPair holds a public/private pair of keys. type KeyPair struct { Public PublicKey `json:"public"` Private PrivateKey `json:"private"` } // UnmarshalJSON implements json.Unmarshaler. func (k *KeyPair) UnmarshalJSON(data []byte) error { type keyPair KeyPair if err := json.Unmarshal(data, (*keyPair)(k)); err != nil { return err } return k.validate() } // UnmarshalYAML implements yaml.Unmarshaler. func (k *KeyPair) UnmarshalYAML(unmarshal func(interface{}) error) error { type keyPair KeyPair if err := unmarshal((*keyPair)(k)); err != nil { return err } return k.validate() } func (k *KeyPair) validate() error { if k.Public.isZero() { return errgo.Newf("missing public key") } if k.Private.isZero() { return errgo.Newf("missing private key") } return nil } // GenerateKey generates a new key pair. func GenerateKey() (*KeyPair, error) { var key KeyPair pub, priv, err := box.GenerateKey(rand.Reader) if err != nil { return nil, err } key.Public = PublicKey{*pub} key.Private = PrivateKey{*priv} return &key, nil } // MustGenerateKey is like GenerateKey but panics if GenerateKey returns // an error - useful in tests. func MustGenerateKey() *KeyPair { key, err := GenerateKey() if err != nil { panic(errgo.Notef(err, "cannot generate key")) } return key } // String implements the fmt.Stringer interface // by returning the base64 representation of the // public key part of key. func (key *KeyPair) String() string { return key.Public.String() } type emptyLocator struct{} func (emptyLocator) ThirdPartyInfo(context.Context, string) (ThirdPartyInfo, error) { return ThirdPartyInfo{}, ErrNotFound } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/internal/���������������������������0000755�0610621�0607500�00000000000�13172163311�027240� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/internal/macaroonpb/����������������0000755�0610621�0607500�00000000000�13172163311�031361� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/internal/macaroonpb/id.proto��������0000644�0610621�0607500�00000000314�13172163311�033040� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������syntax="proto3"; option go_package = "macaroonpb"; message MacaroonId { bytes nonce = 1; bytes storageId = 2; repeated Op ops = 3; } message Op { string entity = 1; repeated string actions = 2; } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/internal/macaroonpb/id.pb.go��������0000644�0610621�0607500�00000006045�13172163311�032711� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. // source: id.proto // DO NOT EDIT! /* Package macaroonpb is a generated protocol buffer package. It is generated from these files: id.proto It has these top-level messages: MacaroonId Op */ package macaroonpb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type MacaroonId struct { Nonce []byte `protobuf:"bytes,1,opt,name=nonce,proto3" json:"nonce,omitempty"` StorageId []byte `protobuf:"bytes,2,opt,name=storageId,proto3" json:"storageId,omitempty"` Ops []*Op `protobuf:"bytes,3,rep,name=ops" json:"ops,omitempty"` } func (m *MacaroonId) Reset() { *m = MacaroonId{} } func (m *MacaroonId) String() string { return proto.CompactTextString(m) } func (*MacaroonId) ProtoMessage() {} func (*MacaroonId) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *MacaroonId) GetOps() []*Op { if m != nil { return m.Ops } return nil } type Op struct { Entity string `protobuf:"bytes,1,opt,name=entity" json:"entity,omitempty"` Actions []string `protobuf:"bytes,2,rep,name=actions" json:"actions,omitempty"` } func (m *Op) Reset() { *m = Op{} } func (m *Op) String() string { return proto.CompactTextString(m) } func (*Op) ProtoMessage() {} func (*Op) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func init() { proto.RegisterType((*MacaroonId)(nil), "MacaroonId") proto.RegisterType((*Op)(nil), "Op") } func init() { proto.RegisterFile("id.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 161 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0xc8, 0x4c, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x57, 0x0a, 0xe7, 0xe2, 0xf2, 0x4d, 0x4c, 0x4e, 0x2c, 0xca, 0xcf, 0xcf, 0xf3, 0x4c, 0x11, 0x12, 0xe1, 0x62, 0xcd, 0xcb, 0xcf, 0x4b, 0x4e, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x09, 0x82, 0x70, 0x84, 0x64, 0xb8, 0x38, 0x8b, 0x4b, 0xf2, 0x8b, 0x12, 0xd3, 0x53, 0x3d, 0x53, 0x24, 0x98, 0xc0, 0x32, 0x08, 0x01, 0x21, 0x51, 0x2e, 0xe6, 0xfc, 0x82, 0x62, 0x09, 0x66, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x66, 0x3d, 0xff, 0x82, 0x20, 0x10, 0x5f, 0xc9, 0x8c, 0x8b, 0xc9, 0xbf, 0x40, 0x48, 0x8c, 0x8b, 0x2d, 0x35, 0xaf, 0x24, 0xb3, 0xa4, 0x12, 0x6c, 0x22, 0x67, 0x10, 0x94, 0x27, 0x24, 0xc1, 0xc5, 0x9e, 0x98, 0x5c, 0x92, 0x99, 0x9f, 0x57, 0x2c, 0xc1, 0xa4, 0xc0, 0xac, 0xc1, 0x19, 0x04, 0xe3, 0x3a, 0xf1, 0x44, 0x71, 0xe5, 0x42, 0x1d, 0x54, 0x90, 0x94, 0xc4, 0x06, 0x76, 0xa5, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x18, 0x25, 0xab, 0x17, 0xb1, 0x00, 0x00, 0x00, } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/internal/macaroonpb/id.go�����������0000644�0610621�0607500�00000001012�13172163311�032276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package macaroonpb is an internal package that allows us to hide the internal // serialization details of macaroon ids. package macaroonpb import ( "github.com/golang/protobuf/proto" ) //go:generate protoc --go_out . id.proto // MarshalBinary implements encoding.BinaryMarshal. func (id *MacaroonId) MarshalBinary() ([]byte, error) { return proto.Marshal(id) } // UnmarshalBinary implements encoding.UnmarshalBinary. func (id *MacaroonId) UnmarshalBinary(data []byte) error { return proto.Unmarshal(data, id) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/identity.go�������������������������0000644�0610621�0607500�00000006042�13172163311�027606� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // IdentityClient represents an abstract identity manager. User // identities can be based on local informaton (for example // HTTP basic auth) or by reference to an external trusted // third party (an identity manager). type IdentityClient interface { // IdentityFromContext returns the identity based on information in the context. // If it cannot determine the identity based on the context, then it // should return a set of caveats containing a third party caveat that, // when discharged, can be used to obtain the identity with DeclaredIdentity. // // It should only return an error if it cannot check the identity // (for example because of a database access error) - it's // OK to return all zero values when there's // no identity found and no third party to address caveats to. IdentityFromContext(ctx context.Context) (Identity, []checkers.Caveat, error) // DeclaredIdentity parses the identity declaration from the given // declared attributes. // TODO take the set of first party caveat conditions instead? DeclaredIdentity(ctx context.Context, declared map[string]string) (Identity, error) } // Identity holds identity information declared in a first party caveat // added when discharging a third party caveat. type Identity interface { // Id returns the id of the user, which may be an // opaque blob with no human meaning. // An id is only considered to be unique // with a given domain. Id() string // Domain holds the domain of the user. This // will be empty if the user was authenticated // directly with the identity provider. Domain() string } // noIdentities defines the null identity provider - it never returns any identities. type noIdentities struct{} // IdentityFromContext implements IdentityClient.IdentityFromContext by // never returning a declared identity or any caveats. func (noIdentities) IdentityFromContext(ctx context.Context) (Identity, []checkers.Caveat, error) { return nil, nil, nil } // DeclaredIdentity implements IdentityClient.DeclaredIdentity by // always returning an error. func (noIdentities) DeclaredIdentity(ctx context.Context, declared map[string]string) (Identity, error) { return nil, errgo.Newf("no identity declared or possible") } var _ ACLIdentity = SimpleIdentity("") // SimpleIdentity implements a simple form of identity where // the user is represented by a string. type SimpleIdentity string // Domain implements Identity.Domain by always // returning the empty domain. func (SimpleIdentity) Domain() string { return "" } // Id returns id as a string. func (id SimpleIdentity) Id() string { return string(id) } // Allow implements ACLIdentity by allowing the identity access to // ACL members that are equal to id. That is, some user u is considered // a member of group u and no other. func (id SimpleIdentity) Allow(ctx context.Context, acl []string) (bool, error) { for _, g := range acl { if string(id) == g { return true, nil } } return false, nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/export_test.go����������������������0000644�0610621�0607500�00000000525�13172163311�030335� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery func MemOpsStoreLen(store OpsStore) int { return len(store.(*memOpsStore).ops) } func SetMacaroonCaveatIdPrefix(m *Macaroon, prefix []byte) { m.caveatIdPrefix = prefix } func MacaroonCaveatData(m *Macaroon) map[string][]byte { return m.caveatData } var LegacyNamespace = legacyNamespace type MacaroonJSON macaroonJSON ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/����������������������������0000755�0610621�0607500�00000000000�13172163311�027057� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/targetservice.go������������0000644�0610621�0607500�00000006511�13172163311�032260� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "net/http" "strings" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) type targetServiceHandler struct { checker *bakery.Checker oven *httpbakery.Oven authEndpoint string endpoint string mux *http.ServeMux } // targetService implements a "target service", representing // an arbitrary web service that wants to delegate authorization // to third parties. // func targetService(endpoint, authEndpoint string, authPK *bakery.PublicKey) (http.Handler, error) { key, err := bakery.GenerateKey() if err != nil { return nil, err } pkLocator := httpbakery.NewThirdPartyLocator(nil, nil) pkLocator.AllowInsecure() b := bakery.New(bakery.BakeryParams{ Key: key, Location: endpoint, Locator: pkLocator, Checker: httpbakery.NewChecker(), Authorizer: authorizer{ thirdPartyLocation: authEndpoint, }, }) mux := http.NewServeMux() srv := &targetServiceHandler{ checker: b.Checker, oven: &httpbakery.Oven{Oven: b.Oven}, authEndpoint: authEndpoint, } mux.Handle("/gold/", srv.auth(http.HandlerFunc(srv.serveGold))) mux.Handle("/silver/", srv.auth(http.HandlerFunc(srv.serveSilver))) return mux, nil } func (srv *targetServiceHandler) serveGold(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "all is golden") } func (srv *targetServiceHandler) serveSilver(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "every cloud has a silver lining") } // auth wraps the given handler with a handler that provides // authorization by inspecting the HTTP request // to decide what authorization is required. func (srv *targetServiceHandler) auth(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { ctx := httpbakery.ContextWithRequest(context.TODO(), req) ops, err := opsForRequest(req) if err != nil { fail(w, http.StatusInternalServerError, "%v", err) return } authChecker := srv.checker.Auth(httpbakery.RequestMacaroons(req)...) if _, err = authChecker.Allow(ctx, ops...); err != nil { httpbakery.WriteError(ctx, w, srv.oven.Error(ctx, req, err)) return } h.ServeHTTP(w, req) }) } // opsForRequest returns the required operations // implied by the given HTTP request. func opsForRequest(req *http.Request) ([]bakery.Op, error) { if !strings.HasPrefix(req.URL.Path, "/") { return nil, errgo.Newf("bad path") } elems := strings.Split(req.URL.Path, "/") if len(elems) < 2 { return nil, errgo.Newf("bad path") } return []bakery.Op{{ Entity: elems[1], Action: req.Method, }}, nil } func fail(w http.ResponseWriter, code int, msg string, args ...interface{}) { http.Error(w, fmt.Sprintf(msg, args...), code) } type authorizer struct { thirdPartyLocation string } // Authorize implements bakery.Authorizer.Authorize by // allowing anyone to do anything if a third party // approves it. func (a authorizer) Authorize(ctx context.Context, id bakery.Identity, ops []bakery.Op) (allowed []bool, caveats []checkers.Caveat, err error) { allowed = make([]bool, len(ops)) for i := range allowed { allowed[i] = true } caveats = []checkers.Caveat{{ Location: a.thirdPartyLocation, Condition: "access-allowed", }} return } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/meeting/��������������������0000755�0610621�0607500�00000000000�13172163311�030507� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/meeting/package_test.go�����0000644�0610621�0607500�00000000213�13172163311�033464� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build ignore package meeting_test import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/meeting/meeting_test.go�����0000644�0610621�0607500�00000003315�13172163311�033527� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build ignore package meeting_test import ( "time" gc "gopkg.in/check.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/example/meeting" ) type suite struct{} var _ = gc.Suite(&suite{}) func (*suite) TestRendezvousWaitBeforeDone(c *gc.C) { m := meeting.New() id, err := m.NewRendezvous([]byte("first data")) c.Assert(err, gc.IsNil) c.Assert(id, gc.Not(gc.Equals), "") waitDone := make(chan struct{}) go func() { data0, data1, err := m.Wait(id) c.Check(err, gc.IsNil) c.Check(string(data0), gc.Equals, "first data") c.Check(string(data1), gc.Equals, "second data") close(waitDone) }() time.Sleep(10 * time.Millisecond) err = m.Done(id, []byte("second data")) c.Assert(err, gc.IsNil) select { case <-waitDone: case <-time.After(2 * time.Second): c.Errorf("timed out waiting for rendezvous") } // Check that item has now been deleted. data0, data1, err := m.Wait(id) c.Assert(data0, gc.IsNil) c.Assert(data1, gc.IsNil) c.Assert(err, gc.ErrorMatches, `rendezvous ".*" not found`) } func (*suite) TestRendezvousDoneBeforeWait(c *gc.C) { m := meeting.New() id, err := m.NewRendezvous([]byte("first data")) c.Assert(err, gc.IsNil) c.Assert(id, gc.Not(gc.Equals), "") err = m.Done(id, []byte("second data")) c.Assert(err, gc.IsNil) err = m.Done(id, []byte("other second data")) c.Assert(err, gc.ErrorMatches, `rendezvous ".*" done twice`) data0, data1, err := m.Wait(id) c.Assert(err, gc.IsNil) c.Assert(string(data0), gc.Equals, "first data") c.Assert(string(data1), gc.Equals, "second data") // Check that item has now been deleted. data0, data1, err = m.Wait(id) c.Assert(data0, gc.IsNil) c.Assert(data1, gc.IsNil) c.Assert(err, gc.ErrorMatches, `rendezvous ".*" not found`) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/meeting/meeting.go����������0000644�0610621�0607500�00000002504�13172163311�032467� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build ignore package meeting import ( "crypto/rand" "fmt" "sync" ) type Place struct { mu sync.Mutex items map[string]*item } type item struct { c chan struct{} data0 []byte data1 []byte } func New() *Place { return &Place{ items: make(map[string]*item), } } func newId() (string, error) { var id [12]byte if _, err := rand.Read(id[:]); err != nil { return "", fmt.Errorf("cannot read random id: %v", err) } return fmt.Sprintf("%x", id[:]), nil } func (m *Place) NewRendezvous(data []byte) (string, error) { id, err := newId() if err != nil { return "", err } m.mu.Lock() defer m.mu.Unlock() m.items[id] = &item{ c: make(chan struct{}), data0: data, } return id, nil } func (m *Place) Wait(id string) (data0, data1 []byte, err error) { m.mu.Lock() item := m.items[id] m.mu.Unlock() if item == nil { return nil, nil, fmt.Errorf("rendezvous %q not found", id) } <-item.c m.mu.Lock() defer m.mu.Unlock() delete(m.items, id) return item.data0, item.data1, nil } func (m *Place) Done(id string, data []byte) error { m.mu.Lock() item := m.items[id] defer m.mu.Unlock() if item == nil { return fmt.Errorf("rendezvous %q not found", id) } select { case <-item.c: return fmt.Errorf("rendezvous %q done twice", id) default: item.data1 = data close(item.c) } return nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/main.go���������������������0000644�0610621�0607500�00000004153�13172163311�030335� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// This example demonstrates three components: // // - A target service, representing a web server that // wishes to use macaroons for authorization. // It delegates authorization to a third-party // authorization server by adding third-party // caveats to macaroons that it sends to the user. // // - A client, representing a client wanting to make // requests to the server. // // - An authorization server. // // In a real system, these three components would // live on different machines; the client component // could also be a web browser. // (TODO: write javascript discharge gatherer) package main import ( "fmt" "log" "net" "net/http" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) var defaultHTTPClient = httpbakery.NewHTTPClient() func main() { key, err := bakery.GenerateKey() if err != nil { log.Fatalf("cannot generate auth service key pair: %v", err) } authPublicKey := &key.Public authEndpoint := mustServe(func(endpoint string) (http.Handler, error) { return authService(endpoint, key) }) serverEndpoint := mustServe(func(endpoint string) (http.Handler, error) { return targetService(endpoint, authEndpoint, authPublicKey) }) resp, err := clientRequest(newClient(), serverEndpoint) if err != nil { log.Fatalf("client failed: %v", err) } fmt.Printf("client success: %q\n", resp) } func mustServe(newHandler func(string) (http.Handler, error)) (endpointURL string) { endpoint, err := serve(newHandler) if err != nil { log.Fatalf("cannot serve: %v", err) } return endpoint } func serve(newHandler func(string) (http.Handler, error)) (endpointURL string, err error) { listener, err := net.Listen("tcp", "localhost:0") if err != nil { return "", fmt.Errorf("cannot listen: %v", err) } endpointURL = "http://" + listener.Addr().String() handler, err := newHandler(endpointURL) if err != nil { return "", fmt.Errorf("cannot start handler: %v", err) } go http.Serve(listener, handler) return endpointURL, nil } func newClient() *httpbakery.Client { c := httpbakery.NewClient() c.AddInteractor(httpbakery.WebBrowserInteractor{}) return c } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/example_test.go�������������0000644�0610621�0607500�00000003171�13172163311�032102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "net/http" "testing" jujutesting "github.com/juju/testing" gc "gopkg.in/check.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" ) func TestPackage(t *testing.T) { gc.TestingT(t) } type exampleSuite struct { jujutesting.LoggingSuite authEndpoint string authPublicKey *bakery.PublicKey } var _ = gc.Suite(&exampleSuite{}) func (s *exampleSuite) SetUpSuite(c *gc.C) { s.LoggingSuite.SetUpSuite(c) key, err := bakery.GenerateKey() c.Assert(err, gc.IsNil) s.authPublicKey = &key.Public s.authEndpoint, err = serve(func(endpoint string) (http.Handler, error) { return authService(endpoint, key) }) c.Assert(err, gc.IsNil) } func (s *exampleSuite) TestExample(c *gc.C) { client := newClient() serverEndpoint, err := serve(func(endpoint string) (http.Handler, error) { return targetService(endpoint, s.authEndpoint, s.authPublicKey) }) c.Assert(err, gc.IsNil) c.Logf("gold request") resp, err := clientRequest(client, serverEndpoint+"/gold") c.Assert(err, gc.IsNil) c.Assert(resp, gc.Equals, "all is golden") c.Logf("silver request") resp, err = clientRequest(client, serverEndpoint+"/silver") c.Assert(err, gc.IsNil) c.Assert(resp, gc.Equals, "every cloud has a silver lining") } func (s *exampleSuite) BenchmarkExample(c *gc.C) { client := newClient() serverEndpoint, err := serve(func(endpoint string) (http.Handler, error) { return targetService(endpoint, s.authEndpoint, s.authPublicKey) }) c.Assert(err, gc.IsNil) c.ResetTimer() for i := 0; i < c.N; i++ { resp, err := clientRequest(client, serverEndpoint) c.Assert(err, gc.IsNil) c.Assert(resp, gc.Equals, "hello, world\n") } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/client.go�������������������0000644�0610621�0607500�00000001751�13172163311�030670� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "net/http" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) // client represents a client of the target service. // In this simple example, it just tries a GET // request, which will fail unless the client // has the required authorization. func clientRequest(client *httpbakery.Client, serverEndpoint string) (string, error) { // The Do function implements the mechanics // of actually gathering discharge macaroons // when required, and retrying the request // when necessary. req, err := http.NewRequest("GET", serverEndpoint, nil) if err != nil { return "", errgo.Notef(err, "cannot make new HTTP request") } resp, err := client.Do(req) if err != nil { return "", errgo.NoteMask(err, "GET failed", errgo.Any) } defer resp.Body.Close() // TODO(rog) unmarshal error data, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("cannot read response: %v", err) } return string(data), nil } �����������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/example/authservice.go��������������0000644�0610621�0607500�00000002615�13172163311�031734� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "net/http" "golang.org/x/net/context" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) // authService implements an authorization service, // that can discharge third-party caveats added // to other macaroons. func authService(endpoint string, key *bakery.KeyPair) (http.Handler, error) { d := httpbakery.NewDischarger(httpbakery.DischargerParams{ Checker: httpbakery.ThirdPartyCaveatCheckerFunc(thirdPartyChecker), Key: bakery.MustGenerateKey(), }) mux := http.NewServeMux() d.AddMuxHandlers(mux, "/") return mux, nil } // thirdPartyChecker is used to check third party caveats added by other // services. The HTTP request is that of the client - it is attempting // to gather a discharge macaroon. // // Note how this function can return additional first- and third-party // caveats which will be added to the original macaroon's caveats. func thirdPartyChecker(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) { if string(info.Condition) != "access-allowed" { return nil, checkers.ErrCaveatNotRecognized } // TODO check that the HTTP request has cookies that prove // something about the client. return []checkers.Caveat{ httpbakery.SameClientIPAddrCaveat(req), }, nil } �������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/error.go����������������������������0000644�0610621�0607500�00000004031�13172163311�027102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "fmt" errgo "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) var ( // ErrNotFound is returned by Store.Get implementations // to signal that an id has not been found. ErrNotFound = errgo.New("not found") // ErrPermissionDenied is returned from AuthChecker when // permission has been denied. ErrPermissionDenied = errgo.New("permission denied") ) // DischargeRequiredError is returned when authorization has failed and a // discharged macaroon might fix it. // // A caller should grant the user the ability to authorize by minting a // macaroon associated with Ops (see MacaroonStore.MacaroonIdInfo for // how the associated operations are retrieved) and adding Caveats. If // the user succeeds in discharging the caveats, the authorization will // be granted. type DischargeRequiredError struct { // Message holds some reason why the authorization was denied. // TODO this is insufficient (and maybe unnecessary) because we // can have multiple errors. Message string // Ops holds all the operations that were not authorized. // If Ops contains a single LoginOp member, the macaroon // should be treated as an login token. Login tokens (also // known as authentication macaroons) usually have a longer // life span than other macaroons. Ops []Op // Caveats holds the caveats that must be added // to macaroons that authorize the above operations. Caveats []checkers.Caveat } func (e *DischargeRequiredError) Error() string { return "macaroon discharge required: " + e.Message } func isDischargeRequiredError(err error) bool { _, ok := err.(*DischargeRequiredError) return ok } // VerificationError is used to signify that an error is because // of a verification failure rather than because verification // could not be done. type VerificationError struct { Reason error } func (e *VerificationError) Error() string { return fmt.Sprintf("verification failed: %v", e.Reason) } func isVerificationError(err error) bool { _, ok := errgo.Cause(err).(*VerificationError) return ok } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/doc.go������������������������������0000644�0610621�0607500�00000007147�13172163311�026531� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// The bakery package layers on top of the macaroon package, providing // a transport and store-agnostic way of using macaroons to assert // client capabilities. // // Summary // // The Bakery type is probably where you want to start. // It encapsulates a Checker type, which performs checking // of operations, and an Oven type, which encapsulates // the actual details of the macaroon encoding conventions. // // Most other types and functions are designed either to plug // into one of the above types (the various Authorizer // implementations, for example), or to expose some independent // functionality that's potentially useful (Discharge, for example). // // The rest of this introduction introduces some of the concepts // used by the bakery package. // // Identity and entities // // An Identity represents some authenticated user (or agent), usually // the client in a network protocol. An identity can be authenticated by // an external identity server (with a third party macaroon caveat) or // by locally provided information such as a username and password. // // The Checker type is not responsible for determining identity - that // functionality is represented by the IdentityClient interface. // // The Checker uses identities to decide whether something should be // allowed or not - the Authorizer interface is used to ask whether a // given identity should be allowed to perform some set of operations. // // Operations // // An operation defines some requested action on an entity. For example, // if file system server defines an entity for every file in the server, // an operation to read a file might look like: // // Op{ // Entity: "/foo", // Action: "write", // } // // The exact set of entities and actions is up to the caller, but should // be kept stable over time because authorization tokens will contain // these names. // // To authorize some request on behalf of a remote user, first find out // what operations that request needs to perform. For example, if the // user tries to delete a file, the entity might be the path to the // file's directory and the action might be "write". It may often be // possible to determine the operations required by a request without // reference to anything external, when the request itself contains all // the necessary information. // // The LoginOp operation is special - any macaroon associated with this // operation is treated as a bearer of identity information. If two // valid LoginOp macaroons are presented, only the first one will be // used for identity. // // Authorization // // The Authorizer interface is responsible for determining whether a // given authenticated identity is authorized to perform a set of // operations. This is used when the macaroons provided to Auth are not // sufficient to authorize the operations themselves. // // Capabilities // // A "capability" is represented by a macaroon that's associated with // one or more operations, and grants the capability to perform all // those operations. The AllowCapability method reports whether a // capability is allowed. It takes into account any authenticated // identity and any other capabilities provided. // // Third party caveats // // Sometimes authorization will only be granted if a third party caveat // is discharged. This will happen when an IdentityClient or Authorizer // returns a third party caveat. // // When this happens, a DischargeRequiredError will be returned // containing the caveats and the operations required. The caller is // responsible for creating a macaroon with those caveats associated // with those operations and for passing that macaroon to the client to // discharge. package bakery �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/dischargeall_test.go����������������0000644�0610621�0607500�00000012120�13172163311�031430� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "fmt" "github.com/juju/testing" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type DischargeSuite struct { testing.IsolationSuite } var _ = gc.Suite(&DischargeSuite{}) func alwaysOK(string) error { return nil } var macaroonCurrentVersion = bakery.MacaroonVersion(bakery.LatestVersion) func (*DischargeSuite) TestDischargeAllNoDischarges(c *gc.C) { rootKey := []byte("root key") m, err := bakery.NewMacaroon(rootKey, []byte("id0"), "loc0", bakery.LatestVersion, testChecker.Namespace()) c.Assert(err, gc.IsNil) ms, err := bakery.DischargeAll(testContext, m, noDischarge(c)) c.Assert(err, gc.IsNil) c.Assert(ms, gc.HasLen, 1) c.Assert(ms[0].Signature(), gc.DeepEquals, m.M().Signature()) err = m.M().Verify(rootKey, alwaysOK, nil) c.Assert(err, gc.IsNil) } func (*DischargeSuite) TestDischargeAllManyDischarges(c *gc.C) { rootKey := []byte("root key") m0, err := bakery.NewMacaroon(rootKey, []byte("id0"), "loc0", bakery.LatestVersion, nil) c.Assert(err, gc.IsNil) totalRequired := 40 id := 1 addCaveats := func(m *bakery.Macaroon) { for i := 0; i < 2; i++ { if totalRequired == 0 { break } cid := fmt.Sprint("id", id) err := m.M().AddThirdPartyCaveat([]byte("root key "+cid), []byte(cid), "somewhere") c.Assert(err, gc.IsNil) id++ totalRequired-- } } addCaveats(m0) getDischarge := func(_ context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { c.Check(payload, gc.IsNil) m, err := bakery.NewMacaroon([]byte("root key "+string(cav.Id)), cav.Id, "", bakery.LatestVersion, nil) c.Assert(err, gc.IsNil) addCaveats(m) return m, nil } ms, err := bakery.DischargeAll(testContext, m0, getDischarge) c.Assert(err, gc.IsNil) c.Assert(ms, gc.HasLen, 41) err = ms[0].Verify(rootKey, alwaysOK, ms[1:]) c.Assert(err, gc.IsNil) } func (*DischargeSuite) TestDischargeAllManyDischargesWithRealThirdPartyCaveats(c *gc.C) { // This is the same flow as TestDischargeAllManyDischarges except that we're // using actual third party caveats as added by Macaroon.AddCaveat and // we use a larger number of caveats so that caveat ids will need to get larger. locator := bakery.NewThirdPartyStore() bakeries := make(map[string]*bakery.Bakery) bakeryId := 0 addBakery := func() string { bakeryId++ loc := fmt.Sprint("loc", bakeryId) bakeries[loc] = newBakery(loc, locator) return loc } ts := newBakery("ts-loc", locator) const totalDischargesRequired = 40 stillRequired := totalDischargesRequired checker := func(_ context.Context, ci *bakery.ThirdPartyCaveatInfo) (caveats []checkers.Caveat, _ error) { if string(ci.Condition) != "something" { return nil, errgo.Newf("unexpected condition") } for i := 0; i < 3; i++ { if stillRequired <= 0 { break } caveats = append(caveats, checkers.Caveat{ Location: addBakery(), Condition: "something", }) stillRequired-- } return caveats, nil } rootKey := []byte("root key") m0, err := bakery.NewMacaroon(rootKey, []byte("id0"), "ts-loc", bakery.LatestVersion, nil) c.Assert(err, gc.IsNil) err = m0.AddCaveat(testContext, checkers.Caveat{ Location: addBakery(), Condition: "something", }, ts.Oven.Key(), locator) c.Assert(err, gc.IsNil) // We've added a caveat (the first) so one less caveat is required. stillRequired-- getDischarge := func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { return bakery.Discharge(ctx, bakery.DischargeParams{ Id: cav.Id, Caveat: payload, Key: bakeries[cav.Location].Oven.Key(), Checker: bakery.ThirdPartyCaveatCheckerFunc(checker), Locator: locator, }) } ms, err := bakery.DischargeAll(testContext, m0, getDischarge) c.Assert(err, gc.IsNil) c.Assert(ms, gc.HasLen, totalDischargesRequired+1) err = ms[0].Verify(rootKey, alwaysOK, ms[1:]) c.Assert(err, gc.IsNil) } func (*DischargeSuite) TestDischargeAllLocalDischarge(c *gc.C) { oc := newBakery("ts", nil) clientKey, err := bakery.GenerateKey() c.Assert(err, gc.IsNil) m, err := oc.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, []checkers.Caveat{ bakery.LocalThirdPartyCaveat(&clientKey.Public, bakery.LatestVersion), }, bakery.LoginOp) c.Assert(err, gc.IsNil) ms, err := bakery.DischargeAllWithKey(testContext, m, noDischarge(c), clientKey) c.Assert(err, gc.IsNil) _, err = oc.Checker.Auth(ms).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.IsNil) } func (*DischargeSuite) TestDischargeAllLocalDischargeVersion1(c *gc.C) { oc := newBakery("ts", nil) clientKey, err := bakery.GenerateKey() c.Assert(err, gc.IsNil) m, err := oc.Oven.NewMacaroon(testContext, bakery.Version1, ages, []checkers.Caveat{ bakery.LocalThirdPartyCaveat(&clientKey.Public, bakery.Version1), }, bakery.LoginOp) c.Assert(err, gc.IsNil) ms, err := bakery.DischargeAllWithKey(testContext, m, noDischarge(c), clientKey) c.Assert(err, gc.IsNil) _, err = oc.Checker.Auth(ms).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.IsNil) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/dischargeall.go���������������������0000644�0610621�0607500�00000003723�13172163311�030402� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // DischargeAll gathers discharge macaroons for all the third party // caveats in m (and any subsequent caveats required by those) using // getDischarge to acquire each discharge macaroon. It returns a slice // with m as the first element, followed by all the discharge macaroons. // All the discharge macaroons will be bound to the primary macaroon. // // The getDischarge function is passed the caveat to be discharged; // encryptedCaveat will be passed the external caveat payload found // in m, if any. func DischargeAll( ctx context.Context, m *Macaroon, getDischarge func(ctx context.Context, cav macaroon.Caveat, encryptedCaveat []byte) (*Macaroon, error), ) (macaroon.Slice, error) { return DischargeAllWithKey(ctx, m, getDischarge, nil) } // DischargeAllWithKey is like DischargeAll except that the localKey // parameter may optionally hold the key of the client, in which case it // will be used to discharge any third party caveats with the special // location "local". In this case, the caveat itself must be "true". This // can be used be a server to ask a client to prove ownership of the // private key. // // When localKey is nil, DischargeAllWithKey is exactly the same as // DischargeAll. func DischargeAllWithKey( ctx context.Context, m *Macaroon, getDischarge func(ctx context.Context, cav macaroon.Caveat, encodedCaveat []byte) (*Macaroon, error), localKey *KeyPair, ) (macaroon.Slice, error) { discharges, err := Slice{m}.DischargeAll(ctx, getDischarge, localKey) if err != nil { return nil, errgo.Mask(err, errgo.Any) } return discharges.Bind(), nil } var localDischargeChecker = ThirdPartyCaveatCheckerFunc(func(_ context.Context, info *ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { if string(info.Condition) != "true" { return nil, checkers.ErrCaveatNotRecognized } return nil, nil }) ���������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/discharge_test.go�������������������0000644�0610621�0607500�00000040215�13172163311�030745� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "fmt" "unicode/utf8" "github.com/juju/testing" jc "github.com/juju/testing/checkers" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type ServiceSuite struct { testing.IsolationSuite } var _ = gc.Suite(&ServiceSuite{}) // TestSingleServiceFirstParty creates a single service // with a macaroon with one first party caveat. // It creates a request with this macaroon and checks that the service // can verify this macaroon as valid. func (s *ServiceSuite) TestSingleServiceFirstParty(c *gc.C) { oc := newBakery("bakerytest", nil) primary, err := oc.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(primary.M().Location(), gc.Equals, "bakerytest") err = oc.Oven.AddCaveat(testContext, primary, strCaveat("something")) _, err = oc.Checker.Auth(macaroon.Slice{primary.M()}).Allow(strContext("something"), bakery.LoginOp) c.Assert(err, gc.IsNil) } // TestMacaroonPaperFig6 implements an example flow as described in the macaroons paper: // http://theory.stanford.edu/~ataly/Papers/macaroons.pdf // There are three services, ts, fs, as: // ts is a store service which has deligated authority to a forum service fs. // The forum service wants to require its users to be logged into to an authentication service as. // // The client obtains a macaroon from fs (minted by ts, with a third party caveat addressed to as). // The client obtains a discharge macaroon from as to satisfy this caveat. // The target service verifies the original macaroon it delegated to fs // No direct contact between as and ts is required func (s *ServiceSuite) TestMacaroonPaperFig6(c *gc.C) { locator := bakery.NewThirdPartyStore() as := newBakery("as-loc", locator) ts := newBakery("ts-loc", locator) fs := newBakery("fs-loc", locator) // ts creates a macaroon. tsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp) c.Assert(err, gc.IsNil) // ts somehow sends the macaroon to fs which adds a third party caveat to be discharged by as. err = fs.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: "as-loc", Condition: "user==bob"}) c.Assert(err, gc.IsNil) // client asks for a discharge macaroon for each third party caveat d, err := bakery.DischargeAll(testContext, tsMacaroon, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { c.Assert(cav.Location, gc.Equals, "as-loc") return discharge(ctx, as.Oven, thirdPartyStrcmpChecker("user==bob"), cav, payload) }) c.Assert(err, gc.IsNil) _, err = ts.Checker.Auth(d).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.IsNil) } func (s *ServiceSuite) TestDischargeWithVersion1Macaroon(c *gc.C) { locator := bakery.NewThirdPartyStore() as := newBakery("as-loc", locator) ts := newBakery("ts-loc", locator) // ts creates a old-version macaroon. tsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.Version1, ages, nil, bakery.LoginOp) c.Assert(err, gc.IsNil) err = ts.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: "as-loc", Condition: "something"}) c.Assert(err, gc.IsNil) // client asks for a discharge macaroon for each third party caveat d, err := bakery.DischargeAll(testContext, tsMacaroon, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { // Make sure that the caveat id really is old-style. c.Assert(cav.Id, jc.Satisfies, utf8.Valid) return discharge(ctx, as.Oven, thirdPartyStrcmpChecker("something"), cav, payload) }) c.Assert(err, gc.IsNil) _, err = ts.Checker.Auth(d).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.IsNil) for _, m := range d { c.Assert(m.Version(), gc.Equals, macaroon.V1) } } func (s *ServiceSuite) TestVersion1MacaroonId(c *gc.C) { // In the version 1 bakery, macaroon ids were hex-encoded with a hyphenated // UUID suffix. rootKeyStore := bakery.NewMemRootKeyStore() b := bakery.New(bakery.BakeryParams{ RootKeyStore: rootKeyStore, IdentityClient: oneIdentity{}, }) key, id, err := rootKeyStore.RootKey(testContext) c.Assert(err, gc.IsNil) _, err = rootKeyStore.Get(testContext, id) c.Assert(err, gc.IsNil) m, err := macaroon.New(key, []byte(fmt.Sprintf("%s-deadl00f", id)), "", macaroon.V1) c.Assert(err, gc.IsNil) _, err = b.Checker.Auth(macaroon.Slice{m}).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.IsNil) } // TestMacaroonPaperFig6FailsWithoutDischarges runs a similar test as TestMacaroonPaperFig6 // without the client discharging the third party caveats. func (s *ServiceSuite) TestMacaroonPaperFig6FailsWithoutDischarges(c *gc.C) { locator := bakery.NewThirdPartyStore() ts := newBakery("ts-loc", locator) fs := newBakery("fs-loc", locator) newBakery("as-loc", locator) // ts creates a macaroon. tsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp) c.Assert(err, gc.IsNil) // ts somehow sends the macaroon to fs which adds a third party caveat to be discharged by as. err = fs.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: "as-loc", Condition: "user==bob"}) c.Assert(err, gc.IsNil) // client makes request to ts _, err = ts.Checker.Auth(macaroon.Slice{tsMacaroon.M()}).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.ErrorMatches, `verification failed: cannot find discharge macaroon for caveat .*`, gc.Commentf("%#v", err)) } // TestMacaroonPaperFig6FailsWithBindingOnTamperedSignature runs a similar test as TestMacaroonPaperFig6 // with the discharge macaroon binding being done on a tampered signature. func (s *ServiceSuite) TestMacaroonPaperFig6FailsWithBindingOnTamperedSignature(c *gc.C) { locator := bakery.NewThirdPartyStore() as := newBakery("as-loc", locator) ts := newBakery("ts-loc", locator) fs := newBakery("fs-loc", locator) // ts creates a macaroon. tsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp) c.Assert(err, gc.IsNil) // ts somehow sends the macaroon to fs which adds a third party caveat to be discharged by as. err = fs.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: "as-loc", Condition: "user==bob"}) c.Assert(err, gc.IsNil) // client asks for a discharge macaroon for each third party caveat d, err := bakery.DischargeAll(testContext, tsMacaroon, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { c.Assert(cav.Location, gc.Equals, "as-loc") return discharge(ctx, as.Oven, thirdPartyStrcmpChecker("user==bob"), cav, payload) }) c.Assert(err, gc.IsNil) // client has all the discharge macaroons. For each discharge macaroon bind it to our tsMacaroon // and add it to our request. for _, dm := range d[1:] { dm.Bind([]byte("tampered-signature")) // Bind against an incorrect signature. } // client makes request to ts. _, err = ts.Checker.Auth(d).Allow(testContext, bakery.LoginOp) // TODO fix this error message. c.Assert(err, gc.ErrorMatches, "verification failed: signature mismatch after caveat verification") } func discharge(ctx context.Context, oven *bakery.Oven, checker bakery.ThirdPartyCaveatChecker, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { return bakery.Discharge(ctx, bakery.DischargeParams{ Key: oven.Key(), Locator: oven.Locator(), Id: cav.Id, Caveat: payload, Checker: checker, }) } func (s *ServiceSuite) TestNeedDeclared(c *gc.C) { locator := bakery.NewThirdPartyStore() firstParty := newBakery("first", locator) thirdParty := newBakery("third", locator) // firstParty mints a macaroon with a third-party caveat addressed // to thirdParty with a need-declared caveat. m, err := firstParty.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, []checkers.Caveat{ checkers.NeedDeclaredCaveat(checkers.Caveat{ Location: "third", Condition: "something", }, "foo", "bar"), }, bakery.LoginOp) c.Assert(err, gc.IsNil) // The client asks for a discharge macaroon for each third party caveat. d, err := bakery.DischargeAll(testContext, m, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { return discharge(ctx, thirdParty.Oven, thirdPartyStrcmpChecker("something"), cav, payload) }) c.Assert(err, gc.IsNil) // The required declared attributes should have been added // to the discharge macaroons. declared := checkers.InferDeclared(firstParty.Checker.Namespace(), d) c.Assert(declared, gc.DeepEquals, map[string]string{ "foo": "", "bar": "", }) // Make sure the macaroons actually check out correctly // when provided with the declared checker. ctx := checkers.ContextWithDeclared(testContext, declared) _, err = firstParty.Checker.Auth(d).Allow(ctx, bakery.LoginOp) c.Assert(err, gc.IsNil) // Try again when the third party does add a required declaration. // The client asks for a discharge macaroon for each third party caveat. d, err = bakery.DischargeAll(testContext, m, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { checker := thirdPartyCheckerWithCaveats{ checkers.DeclaredCaveat("foo", "a"), checkers.DeclaredCaveat("arble", "b"), } return discharge(ctx, thirdParty.Oven, checker, cav, payload) }) c.Assert(err, gc.IsNil) // One attribute should have been added, the other was already there. declared = checkers.InferDeclared(firstParty.Checker.Namespace(), d) c.Assert(declared, gc.DeepEquals, map[string]string{ "foo": "a", "bar": "", "arble": "b", }) ctx = checkers.ContextWithDeclared(testContext, declared) _, err = firstParty.Checker.Auth(d).Allow(ctx, bakery.LoginOp) c.Assert(err, gc.IsNil) // Try again, but this time pretend a client is sneakily trying // to add another "declared" attribute to alter the declarations. d, err = bakery.DischargeAll(testContext, m, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { checker := thirdPartyCheckerWithCaveats{ checkers.DeclaredCaveat("foo", "a"), checkers.DeclaredCaveat("arble", "b"), } // Sneaky client adds a first party caveat. m, err := discharge(ctx, thirdParty.Oven, checker, cav, payload) c.Assert(err, gc.IsNil) err = m.AddCaveat(ctx, checkers.DeclaredCaveat("foo", "c"), nil, nil) c.Assert(err, gc.IsNil) return m, nil }) c.Assert(err, gc.IsNil) declared = checkers.InferDeclared(firstParty.Checker.Namespace(), d) c.Assert(declared, gc.DeepEquals, map[string]string{ "bar": "", "arble": "b", }) ctx = checkers.ContextWithDeclared(testContext, declared) _, err = firstParty.Checker.Auth(d).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.ErrorMatches, `cannot authorize login macaroon: caveat "declared foo a" not satisfied: got foo=null, expected "a"`) } func (s *ServiceSuite) TestDischargeTwoNeedDeclared(c *gc.C) { locator := bakery.NewThirdPartyStore() firstParty := newBakery("first", locator) thirdParty := newBakery("third", locator) // firstParty mints a macaroon with two third party caveats // with overlapping attributes. m, err := firstParty.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, []checkers.Caveat{ checkers.NeedDeclaredCaveat(checkers.Caveat{ Location: "third", Condition: "x", }, "foo", "bar"), checkers.NeedDeclaredCaveat(checkers.Caveat{ Location: "third", Condition: "y", }, "bar", "baz"), }, bakery.LoginOp) c.Assert(err, gc.IsNil) // The client asks for a discharge macaroon for each third party caveat. // Since no declarations are added by the discharger, d, err := bakery.DischargeAll(testContext, m, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { return discharge(ctx, thirdParty.Oven, bakery.ThirdPartyCaveatCheckerFunc(func(context.Context, *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { return nil, nil }), cav, payload) }) c.Assert(err, gc.IsNil) declared := checkers.InferDeclared(firstParty.Checker.Namespace(), d) c.Assert(declared, gc.DeepEquals, map[string]string{ "foo": "", "bar": "", "baz": "", }) ctx := checkers.ContextWithDeclared(testContext, declared) _, err = firstParty.Checker.Auth(d).Allow(ctx, bakery.LoginOp) c.Assert(err, gc.IsNil) // If they return conflicting values, the discharge fails. // The client asks for a discharge macaroon for each third party caveat. // Since no declarations are added by the discharger, d, err = bakery.DischargeAll(testContext, m, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { return discharge(ctx, thirdParty.Oven, bakery.ThirdPartyCaveatCheckerFunc(func(_ context.Context, cavInfo *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { switch string(cavInfo.Condition) { case "x": return []checkers.Caveat{ checkers.DeclaredCaveat("foo", "fooval1"), }, nil case "y": return []checkers.Caveat{ checkers.DeclaredCaveat("foo", "fooval2"), checkers.DeclaredCaveat("baz", "bazval"), }, nil } return nil, fmt.Errorf("not matched") }), cav, payload) }) c.Assert(err, gc.IsNil) declared = checkers.InferDeclared(firstParty.Checker.Namespace(), d) c.Assert(declared, gc.DeepEquals, map[string]string{ "bar": "", "baz": "bazval", }) ctx = checkers.ContextWithDeclared(testContext, declared) _, err = firstParty.Checker.Auth(d).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.ErrorMatches, `cannot authorize login macaroon: caveat "declared foo fooval1" not satisfied: got foo=null, expected "fooval1"`) } func (s *ServiceSuite) TestDischargeMacaroonCannotBeUsedAsNormalMacaroon(c *gc.C) { locator := bakery.NewThirdPartyStore() firstParty := newBakery("first", locator) thirdParty := newBakery("third", locator) // First party mints a macaroon with a 3rd party caveat. m, err := firstParty.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, []checkers.Caveat{{ Location: "third", Condition: "true", }}, bakery.LoginOp) c.Assert(err, gc.IsNil) // Acquire the discharge macaroon, but don't bind it to the original. var unbound *macaroon.Macaroon _, err = bakery.DischargeAll(testContext, m, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { m, err := discharge(ctx, thirdParty.Oven, thirdPartyStrcmpChecker("true"), cav, payload) if err == nil { unbound = m.M().Clone() } return m, err }) c.Assert(err, gc.IsNil) c.Assert(unbound, gc.NotNil) // Make sure it cannot be used as a normal macaroon in the third party. _, err = thirdParty.Checker.Auth(macaroon.Slice{unbound}).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.ErrorMatches, `cannot retrieve macaroon: cannot unmarshal macaroon id: .*`) } func (s *ServiceSuite) TestThirdPartyDischargeMacaroonIdsAreSmall(c *gc.C) { locator := bakery.NewThirdPartyStore() bakeries := map[string]*bakery.Bakery{ "ts-loc": newBakery("ts-loc", locator), "as1-loc": newBakery("as1-loc", locator), "as2-loc": newBakery("as2-loc", locator), } ts := bakeries["ts-loc"] tsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp) c.Assert(err, gc.IsNil) err = ts.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: "as1-loc", Condition: "something"}) c.Assert(err, gc.IsNil) checker := func(loc string) bakery.ThirdPartyCaveatCheckerFunc { return func(_ context.Context, cavInfo *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { switch loc { case "as1-loc": return []checkers.Caveat{{ Condition: "something", Location: "as2-loc", }}, nil case "as2-loc": return nil, nil default: return nil, errgo.Newf("unknown location %q", loc) } } } d, err := bakery.DischargeAll(testContext, tsMacaroon, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { return discharge(ctx, bakeries[cav.Location].Oven, checker(cav.Location), cav, payload) }) c.Assert(err, gc.IsNil) _, err = ts.Checker.Auth(d).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.IsNil) for i, m := range d { for j, cav := range m.Caveats() { if cav.VerificationId != nil && len(cav.Id) > 3 { c.Errorf("caveat id on caveat %d of macaroon %d is too big (%q)", j, i, cav.Id) } } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/discharge.go������������������������0000644�0610621�0607500�00000022023�13172163311�027703� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "crypto/rand" "fmt" "strconv" "strings" "github.com/juju/loggo" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) var logger = loggo.GetLogger("bakery") // LocalThirdPartyCaveat returns a third-party caveat that, when added // to a macaroon with AddCaveat, results in a caveat // with the location "local", encrypted with the given public key. // This can be automatically discharged by DischargeAllWithKey. func LocalThirdPartyCaveat(key *PublicKey, version Version) checkers.Caveat { var loc string if version < Version2 { loc = "local " + key.String() } else { loc = fmt.Sprintf("local %d %s", version, key) } return checkers.Caveat{ Location: loc, } } // parseLocalLocation parses a local caveat location as generated by // LocalThirdPartyCaveat. This is of the form: // // local <version> <pubkey> // // where <version> is the bakery version of the client that we're // adding the local caveat for. // // It returns false if the location does not represent a local // caveat location. func parseLocalLocation(loc string) (ThirdPartyInfo, bool) { if !strings.HasPrefix(loc, "local ") { return ThirdPartyInfo{}, false } version := Version1 fields := strings.Fields(loc) fields = fields[1:] // Skip "local" switch len(fields) { case 2: v, err := strconv.Atoi(fields[0]) if err != nil { return ThirdPartyInfo{}, false } version = Version(v) fields = fields[1:] fallthrough case 1: var key PublicKey if err := key.UnmarshalText([]byte(fields[0])); err != nil { return ThirdPartyInfo{}, false } return ThirdPartyInfo{ PublicKey: key, Version: version, }, true default: return ThirdPartyInfo{}, false } } // DischargeParams holds parameters for a Discharge call. type DischargeParams struct { // Id holds the id to give to the discharge macaroon. // If Caveat is empty, then the id also holds the // encrypted third party caveat. Id []byte // Caveat holds the encrypted third party caveat. If this // is nil, Id will be used. Caveat []byte // Key holds the key to use to decrypt the third party // caveat information and to encrypt any additional // third party caveats returned by the caveat checker. Key *KeyPair // Checker is used to check the third party caveat, // and may also return further caveats to be added to // the discharge macaroon. Checker ThirdPartyCaveatChecker // Locator is used to information on third parties // referred to by third party caveats returned by the Checker. Locator ThirdPartyLocator } // Discharge creates a macaroon to discharges a third party caveat. // The given parameters specify the caveat and how it should be checked/ // // The condition implicit in the caveat is checked for validity using p.Checker. If // it is valid, a new macaroon is returned which discharges the caveat. // // The macaroon is created with a version derived from the version // that was used to encode the id. func Discharge(ctx context.Context, p DischargeParams) (*Macaroon, error) { var caveatIdPrefix []byte if p.Caveat == nil { // The caveat information is encoded in the id itself. p.Caveat = p.Id } else { // We've been given an explicit id, so when extra third party // caveats are added, use that id as the prefix // for any more ids. caveatIdPrefix = p.Id } cavInfo, err := decodeCaveat(p.Key, p.Caveat) if err != nil { return nil, errgo.Notef(err, "discharger cannot decode caveat id") } cavInfo.Id = p.Id logger.Infof("decoded discharge caveat %x as version %v", p.Caveat, cavInfo.Version) // Note that we don't check the error - we allow the // third party checker to see even caveats that we can't // understand. cond, arg, _ := checkers.ParseCaveat(string(cavInfo.Condition)) var caveats []checkers.Caveat if cond == checkers.CondNeedDeclared { cavInfo.Condition = []byte(arg) caveats, err = checkNeedDeclared(ctx, cavInfo, p.Checker) } else { caveats, err = p.Checker.CheckThirdPartyCaveat(ctx, cavInfo) } if err != nil { return nil, errgo.Mask(err, errgo.Any) } // Note that the discharge macaroon does not need to // be stored persistently. Indeed, it would be a problem if // we did, because then the macaroon could potentially be used // for normal authorization with the third party. m, err := NewMacaroon(cavInfo.RootKey, p.Id, "", cavInfo.Version, cavInfo.Namespace) if err != nil { return nil, errgo.Mask(err) } m.caveatIdPrefix = caveatIdPrefix for _, cav := range caveats { if err := m.AddCaveat(ctx, cav, p.Key, p.Locator); err != nil { return nil, errgo.Notef(err, "could not add caveat") } } return m, nil } func checkNeedDeclared(ctx context.Context, cavInfo *ThirdPartyCaveatInfo, checker ThirdPartyCaveatChecker) ([]checkers.Caveat, error) { arg := string(cavInfo.Condition) i := strings.Index(arg, " ") if i <= 0 { return nil, errgo.Newf("need-declared caveat requires an argument, got %q", arg) } needDeclared := strings.Split(arg[0:i], ",") for _, d := range needDeclared { if d == "" { return nil, errgo.New("need-declared caveat with empty required attribute") } } if len(needDeclared) == 0 { return nil, fmt.Errorf("need-declared caveat with no required attributes") } cavInfo.Condition = []byte(arg[i+1:]) caveats, err := checker.CheckThirdPartyCaveat(ctx, cavInfo) if err != nil { return nil, errgo.Mask(err, errgo.Any) } declared := make(map[string]bool) for _, cav := range caveats { if cav.Location != "" { continue } // Note that we ignore the error. We allow the service to // generate caveats that we don't understand here. cond, arg, _ := checkers.ParseCaveat(cav.Condition) if cond != checkers.CondDeclared { continue } parts := strings.SplitN(arg, " ", 2) if len(parts) != 2 { return nil, errgo.Newf("declared caveat has no value") } declared[parts[0]] = true } // Add empty declarations for everything mentioned in need-declared // that was not actually declared. for _, d := range needDeclared { if !declared[d] { caveats = append(caveats, checkers.DeclaredCaveat(d, "")) } } return caveats, nil } func randomBytes(n int) ([]byte, error) { b := make([]byte, n) _, err := rand.Read(b) if err != nil { return nil, fmt.Errorf("cannot generate %d random bytes: %v", n, err) } return b, nil } // ThirdPartyCaveatInfo holds the information decoded from // a third party caveat id. type ThirdPartyCaveatInfo struct { // Condition holds the third party condition to be discharged. // This is the only field that most third party dischargers will // need to consider. Condition []byte // FirstPartyPublicKey holds the public key of the party // that created the third party caveat. FirstPartyPublicKey PublicKey // ThirdPartyKeyPair holds the key pair used to decrypt // the caveat - the key pair of the discharging service. ThirdPartyKeyPair KeyPair // RootKey holds the secret root key encoded by the caveat. RootKey []byte // CaveatId holds the full encoded caveat id from which all // the other fields are derived. Caveat []byte // Version holds the version that was used to encode // the caveat id. Version Version // Id holds the id of the third party caveat (the id that // the discharge macaroon should be given). This // will differ from Caveat when the caveat information // is encoded separately. Id []byte // Namespace holds the namespace of the first party // that created the macaroon, as encoded by the party // that added the third party caveat. Namespace *checkers.Namespace } // ThirdPartyCaveatChecker holds a function that checks third party caveats // for validity. If the caveat is valid, it returns a nil error and // optionally a slice of extra caveats that will be added to the // discharge macaroon. The caveatId parameter holds the still-encoded id // of the caveat. // // If the caveat kind was not recognised, the checker should return an // error with a ErrCaveatNotRecognized cause. type ThirdPartyCaveatChecker interface { CheckThirdPartyCaveat(ctx context.Context, info *ThirdPartyCaveatInfo) ([]checkers.Caveat, error) } // ThirdPartyCaveatCheckerFunc implements ThirdPartyCaveatChecker by calling a function. type ThirdPartyCaveatCheckerFunc func(context.Context, *ThirdPartyCaveatInfo) ([]checkers.Caveat, error) // CheckThirdPartyCaveat implements ThirdPartyCaveatChecker.CheckThirdPartyCaveat by calling // the receiver with the given arguments func (c ThirdPartyCaveatCheckerFunc) CheckThirdPartyCaveat(ctx context.Context, info *ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { return c(ctx, info) } // FirstPartyCaveatChecker is used to check first party caveats // for validity with respect to information in the provided context. // // If the caveat kind was not recognised, the checker should return // ErrCaveatNotRecognized. type FirstPartyCaveatChecker interface { // CheckFirstPartyCaveat checks that the given caveat condition // is valid with respect to the given context information. CheckFirstPartyCaveat(ctx context.Context, caveat string) error // Namespace returns the namespace associated with the // caveat checker. Namespace() *checkers.Namespace } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/common_test.go����������������������0000644�0610621�0607500�00000010701�13172163311�030301� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "encoding/json" "fmt" "time" "github.com/juju/loggo" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // testContext holds the testing background context - its associated time when checking // time-before caveats will always be the value of epoch. var testContext = checkers.ContextWithClock(context.Background(), stoppedClock{epoch}) var logger = loggo.GetLogger("bakery.bakery_test") var ( epoch = time.Date(1900, 11, 17, 19, 00, 13, 0, time.UTC) ages = epoch.Add(24 * time.Hour) ) var testChecker = func() *checkers.Checker { c := checkers.New(nil) c.Namespace().Register("testns", "") c.Register("str", "testns", strCheck) c.Register("true", "testns", trueCheck) return c }() // newBakery returns a new Bakery instance using a new // key pair, and registers the key with the given locator if provided. // // It uses testChecker to check first party caveats. func newBakery(location string, locator *bakery.ThirdPartyStore) *bakery.Bakery { key := mustGenerateKey() p := bakery.BakeryParams{ Key: key, Checker: testChecker, Location: location, IdentityClient: oneIdentity{}, } if locator != nil { p.Locator = locator locator.AddInfo(location, bakery.ThirdPartyInfo{ PublicKey: key.Public, Version: bakery.LatestVersion, }) } return bakery.New(p) } func noDischarge(c *gc.C) func(context.Context, macaroon.Caveat, []byte) (*bakery.Macaroon, error) { return func(context.Context, macaroon.Caveat, []byte) (*bakery.Macaroon, error) { c.Errorf("getDischarge called unexpectedly") return nil, fmt.Errorf("nothing") } } // oneIdentity is an IdentityClient implementation that always // returns a single identity from DeclaredIdentity, allowing // Allow(LoginOp) to work even when there are no declaration // caveats (this is mostly to support the legacy tests which do their // own checking of declaration caveats. type oneIdentity struct{} func (oneIdentity) IdentityFromContext(ctx context.Context) (bakery.Identity, []checkers.Caveat, error) { return nil, nil, nil } func (oneIdentity) DeclaredIdentity(ctx context.Context, declared map[string]string) (bakery.Identity, error) { return noone{}, nil } type noone struct{} func (noone) Id() string { return "noone" } func (noone) Domain() string { return "" } type strKey struct{} func strContext(s string) context.Context { return context.WithValue(testContext, strKey{}, s) } func strCaveat(s string) checkers.Caveat { return checkers.Caveat{ Condition: "str " + s, Namespace: "testns", } } func trueCaveat(s string) checkers.Caveat { return checkers.Caveat{ Condition: "true " + s, Namespace: "testns", } } // trueCheck always succeeds. func trueCheck(ctx context.Context, cond, args string) error { return nil } // strCheck checks that the string value in the context // matches the argument to the condition. func strCheck(ctx context.Context, cond, args string) error { expect, _ := ctx.Value(strKey{}).(string) if args != expect { return fmt.Errorf("%s doesn't match %s", cond, expect) } return nil } type thirdPartyStrcmpChecker string func (c thirdPartyStrcmpChecker) CheckThirdPartyCaveat(_ context.Context, cavInfo *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { if string(cavInfo.Condition) != string(c) { return nil, fmt.Errorf("%s doesn't match %s", cavInfo.Condition, c) } return nil, nil } type thirdPartyCheckerWithCaveats []checkers.Caveat func (c thirdPartyCheckerWithCaveats) CheckThirdPartyCaveat(_ context.Context, cavInfo *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { return c, nil } func macStr(m *macaroon.Macaroon) string { data, err := json.MarshalIndent(m, "\t", "\t") if err != nil { panic(err) } return string(data) } type stoppedClock struct { t time.Time } func (t stoppedClock) Now() time.Time { return t.t } type basicAuthKey struct{} type basicAuth struct { user, password string } func contextWithBasicAuth(ctx context.Context, user, password string) context.Context { return context.WithValue(ctx, basicAuthKey{}, basicAuth{user, password}) } func basicAuthFromContext(ctx context.Context) (user, password string) { auth, _ := ctx.Value(basicAuthKey{}).(basicAuth) return auth.user, auth.password } func mustGenerateKey() *bakery.KeyPair { key, err := bakery.GenerateKey() if err != nil { panic(err) } return key } ���������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/codec_test.go�����������������������0000644�0610621�0607500�00000013411�13172163311�030067� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "bytes" jc "github.com/juju/testing/checkers" "golang.org/x/crypto/nacl/box" gc "gopkg.in/check.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type codecSuite struct { firstPartyKey *KeyPair thirdPartyKey *KeyPair } var _ = gc.Suite(&codecSuite{}) func (s *codecSuite) SetUpTest(c *gc.C) { var err error s.firstPartyKey, err = GenerateKey() c.Assert(err, gc.IsNil) s.thirdPartyKey, err = GenerateKey() c.Assert(err, gc.IsNil) } func (s *codecSuite) TestV1RoundTrip(c *gc.C) { cid, err := encodeCaveatV1( "is-authenticated-user", []byte("a random string"), &s.thirdPartyKey.Public, s.firstPartyKey) c.Assert(err, gc.IsNil) res, err := decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.IsNil) c.Assert(res, jc.DeepEquals, &ThirdPartyCaveatInfo{ FirstPartyPublicKey: s.firstPartyKey.Public, RootKey: []byte("a random string"), Condition: []byte("is-authenticated-user"), Caveat: cid, ThirdPartyKeyPair: *s.thirdPartyKey, Version: Version1, Namespace: legacyNamespace(), }) } func (s *codecSuite) TestV2RoundTrip(c *gc.C) { cid, err := encodeCaveatV2("is-authenticated-user", []byte("a random string"), &s.thirdPartyKey.Public, s.firstPartyKey) c.Assert(err, gc.IsNil) res, err := decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.IsNil) c.Assert(res, jc.DeepEquals, &ThirdPartyCaveatInfo{ FirstPartyPublicKey: s.firstPartyKey.Public, RootKey: []byte("a random string"), Condition: []byte("is-authenticated-user"), Caveat: cid, ThirdPartyKeyPair: *s.thirdPartyKey, Version: Version2, Namespace: legacyNamespace(), }) } func (s *codecSuite) TestV3RoundTrip(c *gc.C) { ns := checkers.NewNamespace(nil) ns.Register("testns", "x") cid, err := encodeCaveatV3("is-authenticated-user", []byte("a random string"), &s.thirdPartyKey.Public, s.firstPartyKey, ns) c.Assert(err, gc.IsNil) c.Logf("cid %x", cid) res, err := decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.IsNil) c.Assert(res, jc.DeepEquals, &ThirdPartyCaveatInfo{ FirstPartyPublicKey: s.firstPartyKey.Public, RootKey: []byte("a random string"), Condition: []byte("is-authenticated-user"), Caveat: cid, ThirdPartyKeyPair: *s.thirdPartyKey, Version: Version3, Namespace: ns, }) } func (s *codecSuite) TestEmptyCaveatId(c *gc.C) { _, err := decodeCaveat(s.thirdPartyKey, []byte{}) c.Assert(err, gc.ErrorMatches, "empty third party caveat") } func (s *codecSuite) TestCaveatIdBadVersion(c *gc.C) { _, err := decodeCaveat(s.thirdPartyKey, []byte{1}) c.Assert(err, gc.ErrorMatches, "caveat has unsupported version 1") } func (s *codecSuite) TestV2TooShort(c *gc.C) { _, err := decodeCaveat(s.thirdPartyKey, []byte{2}) c.Assert(err, gc.ErrorMatches, "caveat id too short") } func (s *codecSuite) TestV2BadKey(c *gc.C) { cid, err := encodeCaveatV2("is-authenticated-user", []byte("a random string"), &s.thirdPartyKey.Public, s.firstPartyKey) c.Assert(err, gc.IsNil) cid[1] ^= 1 _, err = decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.ErrorMatches, "public key mismatch") } func (s *codecSuite) TestV2DecryptionError(c *gc.C) { cid, err := encodeCaveatV2("is-authenticated-user", []byte("a random string"), &s.thirdPartyKey.Public, s.firstPartyKey) c.Assert(err, gc.IsNil) cid[5] ^= 1 _, err = decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.ErrorMatches, "cannot decrypt caveat id") } func (s *codecSuite) TestV2EmptySecretPart(c *gc.C) { cid, err := encodeCaveatV2("is-authenticated-user", []byte("a random string"), &s.thirdPartyKey.Public, s.firstPartyKey) c.Assert(err, gc.IsNil) cid = s.replaceV2SecretPart(cid, []byte{}) _, err = decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.ErrorMatches, "invalid secret part: secret part too short") } func (s *codecSuite) TestV2BadSecretPartVersion(c *gc.C) { cid, err := encodeCaveatV2("is-authenticated-user", []byte("a random string"), &s.thirdPartyKey.Public, s.firstPartyKey) c.Assert(err, gc.IsNil) cid = s.replaceV2SecretPart(cid, []byte{1}) _, err = decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.ErrorMatches, "invalid secret part: unexpected secret part version, got 1 want 2") } func (s *codecSuite) TestV2EmptyRootKey(c *gc.C) { cid, err := encodeCaveatV2("is-authenticated-user", []byte{}, &s.thirdPartyKey.Public, s.firstPartyKey) c.Assert(err, gc.IsNil) res, err := decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.IsNil) c.Assert(res, jc.DeepEquals, &ThirdPartyCaveatInfo{ FirstPartyPublicKey: s.firstPartyKey.Public, RootKey: []byte{}, Condition: []byte("is-authenticated-user"), Caveat: cid, ThirdPartyKeyPair: *s.thirdPartyKey, Version: Version2, Namespace: legacyNamespace(), }) } func (s *codecSuite) TestV2LongRootKey(c *gc.C) { cid, err := encodeCaveatV2("is-authenticated-user", bytes.Repeat([]byte{0}, 65536), &s.thirdPartyKey.Public, s.firstPartyKey) c.Assert(err, gc.IsNil) res, err := decodeCaveat(s.thirdPartyKey, cid) c.Assert(err, gc.IsNil) c.Assert(res, jc.DeepEquals, &ThirdPartyCaveatInfo{ FirstPartyPublicKey: s.firstPartyKey.Public, RootKey: bytes.Repeat([]byte{0}, 65536), Condition: []byte("is-authenticated-user"), Caveat: cid, ThirdPartyKeyPair: *s.thirdPartyKey, Version: Version2, Namespace: legacyNamespace(), }) } func (s *codecSuite) replaceV2SecretPart(cid, replacement []byte) []byte { cid = cid[:1+publicKeyPrefixLen+KeyLen+NonceLen] var nonce [NonceLen]byte copy(nonce[:], cid[1+publicKeyPrefixLen+KeyLen:]) return box.Seal(cid, replacement, &nonce, s.firstPartyKey.Public.boxKey(), s.thirdPartyKey.Private.boxKey()) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/codec.go����������������������������0000644�0610621�0607500�00000027311�13172163311�027034� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "bytes" "crypto/rand" "encoding/base64" "encoding/binary" "encoding/json" "golang.org/x/crypto/nacl/box" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type caveatRecord struct { RootKey []byte Condition string } // caveatJSON defines the format of a V1 JSON-encoded third party caveat id. type caveatJSON struct { ThirdPartyPublicKey *PublicKey FirstPartyPublicKey *PublicKey Nonce []byte Id string } // encodeCaveat encrypts a third-party caveat with the given condtion // and root key. The thirdPartyInfo key holds information about the // third party we're encrypting the caveat for; the key is the // public/private key pair of the party that's adding the caveat. // // The caveat will be encoded according to the version information // found in thirdPartyInfo. func encodeCaveat( condition string, rootKey []byte, thirdPartyInfo ThirdPartyInfo, key *KeyPair, ns *checkers.Namespace, ) ([]byte, error) { switch thirdPartyInfo.Version { case Version0, Version1: return encodeCaveatV1(condition, rootKey, &thirdPartyInfo.PublicKey, key) case Version2: return encodeCaveatV2(condition, rootKey, &thirdPartyInfo.PublicKey, key) default: // Version 3 or later - use V3. return encodeCaveatV3(condition, rootKey, &thirdPartyInfo.PublicKey, key, ns) } } // encodeCaveatV1 creates a JSON-encoded third-party caveat // with the given condtion and root key. The thirdPartyPubKey key // represents the public key of the third party we're encrypting // the caveat for; the key is the public/private key pair of the party // that's adding the caveat. func encodeCaveatV1( condition string, rootKey []byte, thirdPartyPubKey *PublicKey, key *KeyPair, ) ([]byte, error) { var nonce [NonceLen]byte if _, err := rand.Read(nonce[:]); err != nil { return nil, errgo.Notef(err, "cannot generate random number for nonce") } plain := caveatRecord{ RootKey: rootKey, Condition: condition, } plainData, err := json.Marshal(&plain) if err != nil { return nil, errgo.Notef(err, "cannot marshal %#v", &plain) } sealed := box.Seal(nil, plainData, &nonce, thirdPartyPubKey.boxKey(), key.Private.boxKey()) id := caveatJSON{ ThirdPartyPublicKey: thirdPartyPubKey, FirstPartyPublicKey: &key.Public, Nonce: nonce[:], Id: base64.StdEncoding.EncodeToString(sealed), } data, err := json.Marshal(id) if err != nil { return nil, errgo.Notef(err, "cannot marshal %#v", id) } buf := make([]byte, base64.StdEncoding.EncodedLen(len(data))) base64.StdEncoding.Encode(buf, data) return buf, nil } // encodeCaveatV2 creates a version 2 third-party caveat. func encodeCaveatV2( condition string, rootKey []byte, thirdPartyPubKey *PublicKey, key *KeyPair, ) ([]byte, error) { return encodeCaveatV2V3(Version2, condition, rootKey, thirdPartyPubKey, key, nil) } // encodeCaveatV3 creates a version 3 third-party caveat. func encodeCaveatV3( condition string, rootKey []byte, thirdPartyPubKey *PublicKey, key *KeyPair, ns *checkers.Namespace, ) ([]byte, error) { return encodeCaveatV2V3(Version3, condition, rootKey, thirdPartyPubKey, key, ns) } const publicKeyPrefixLen = 4 // version3CaveatMinLen holds an underestimate of the // minimum length of a version 3 caveat. const version3CaveatMinLen = 1 + 4 + 32 + 24 + box.Overhead + 1 // encodeCaveatV3 creates a version 2 or version 3 third-party caveat. // // The format has the following packed binary fields (note // that all fields up to and including the nonce are the same // as the v2 format): // // version 2 or 3 [1 byte] // first 4 bytes of third-party Curve25519 public key [4 bytes] // first-party Curve25519 public key [32 bytes] // nonce [24 bytes] // encrypted secret part [rest of message] // // The encrypted part encrypts the following fields // with box.Seal: // // version 2 or 3 [1 byte] // length of root key [n: uvarint] // root key [n bytes] // length of encoded namespace [n: uvarint] (Version 3 only) // encoded namespace [n bytes] (Version 3 only) // condition [rest of encrypted part] func encodeCaveatV2V3( version Version, condition string, rootKey []byte, thirdPartyPubKey *PublicKey, key *KeyPair, ns *checkers.Namespace, ) ([]byte, error) { var nsData []byte if version >= Version3 { data, err := ns.MarshalText() if err != nil { return nil, errgo.Mask(err) } nsData = data } // dataLen is our estimate of how long the data will be. // As we always use append, this doesn't have to be strictly // accurate but it's nice to avoid allocations. dataLen := 0 + 1 + // version publicKeyPrefixLen + KeyLen + NonceLen + box.Overhead + 1 + // version uvarintLen(uint64(len(rootKey))) + len(rootKey) + uvarintLen(uint64(len(nsData))) + len(nsData) + len(condition) var nonce [NonceLen]byte = uuidGen.Next() data := make([]byte, 0, dataLen) data = append(data, byte(version)) data = append(data, thirdPartyPubKey.Key[:publicKeyPrefixLen]...) data = append(data, key.Public.Key[:]...) data = append(data, nonce[:]...) secret := encodeSecretPartV2V3(version, condition, rootKey, nsData) return box.Seal(data, secret, &nonce, thirdPartyPubKey.boxKey(), key.Private.boxKey()), nil } // encodeSecretPartV2V3 creates a version 2 or version 3 secret part of the third party // caveat. The returned data is not encrypted. // // The format has the following packed binary fields: // version 2 or 3 [1 byte] // root key length [n: uvarint] // root key [n bytes] // namespace length [n: uvarint] (v3 only) // namespace [n bytes] (v3 only) // predicate [rest of message] func encodeSecretPartV2V3(version Version, condition string, rootKey, nsData []byte) []byte { data := make([]byte, 0, 1+binary.MaxVarintLen64+len(rootKey)+len(condition)) data = append(data, byte(version)) // version data = appendUvarint(data, uint64(len(rootKey))) data = append(data, rootKey...) if version >= Version3 { data = appendUvarint(data, uint64(len(nsData))) data = append(data, nsData...) } data = append(data, condition...) return data } // decodeCaveat attempts to decode caveat by decrypting the encrypted part // using key. func decodeCaveat(key *KeyPair, caveat []byte) (*ThirdPartyCaveatInfo, error) { if len(caveat) == 0 { return nil, errgo.New("empty third party caveat") } switch caveat[0] { case byte(Version2): return decodeCaveatV2V3(Version2, key, caveat) case byte(Version3): if len(caveat) < version3CaveatMinLen { // If it has the version 3 caveat tag and it's too short, it's // almost certainly an id, not an encrypted payload. return nil, errgo.Newf("caveat id payload not provided for caveat id %q", caveat) } return decodeCaveatV2V3(Version3, key, caveat) case 'e': // 'e' will be the first byte if the caveatid is a base64 encoded JSON object. return decodeCaveatV1(key, caveat) default: return nil, errgo.Newf("caveat has unsupported version %d", caveat[0]) } } // decodeCaveatV1 attempts to decode a base64 encoded JSON id. This // encoding is nominally version -1. func decodeCaveatV1(key *KeyPair, caveat []byte) (*ThirdPartyCaveatInfo, error) { data := make([]byte, (3*len(caveat)+3)/4) n, err := base64.StdEncoding.Decode(data, caveat) if err != nil { return nil, errgo.Notef(err, "cannot base64-decode caveat") } data = data[:n] var wrapper caveatJSON if err := json.Unmarshal(data, &wrapper); err != nil { return nil, errgo.Notef(err, "cannot unmarshal caveat %q", data) } if !bytes.Equal(key.Public.Key[:], wrapper.ThirdPartyPublicKey.Key[:]) { return nil, errgo.New("public key mismatch") } if wrapper.FirstPartyPublicKey == nil { return nil, errgo.New("target service public key not specified") } // The encrypted string is base64 encoded in the JSON representation. secret, err := base64.StdEncoding.DecodeString(wrapper.Id) if err != nil { return nil, errgo.Notef(err, "cannot base64-decode encrypted data") } var nonce [NonceLen]byte if copy(nonce[:], wrapper.Nonce) < NonceLen { return nil, errgo.Newf("nonce too short %x", wrapper.Nonce) } c, ok := box.Open(nil, secret, &nonce, wrapper.FirstPartyPublicKey.boxKey(), key.Private.boxKey()) if !ok { return nil, errgo.Newf("cannot decrypt caveat %#v", wrapper) } var record caveatRecord if err := json.Unmarshal(c, &record); err != nil { return nil, errgo.Notef(err, "cannot decode third party caveat record") } return &ThirdPartyCaveatInfo{ Condition: []byte(record.Condition), FirstPartyPublicKey: *wrapper.FirstPartyPublicKey, ThirdPartyKeyPair: *key, RootKey: record.RootKey, Caveat: caveat, Version: Version1, Namespace: legacyNamespace(), }, nil } // decodeCaveatV2V3 decodes a version 2 or version 3 caveat. func decodeCaveatV2V3(version Version, key *KeyPair, caveat []byte) (*ThirdPartyCaveatInfo, error) { origCaveat := caveat if len(caveat) < 1+publicKeyPrefixLen+KeyLen+NonceLen+box.Overhead { return nil, errgo.New("caveat id too short") } caveat = caveat[1:] // skip version (already checked) publicKeyPrefix, caveat := caveat[:publicKeyPrefixLen], caveat[publicKeyPrefixLen:] if !bytes.Equal(key.Public.Key[:publicKeyPrefixLen], publicKeyPrefix) { return nil, errgo.New("public key mismatch") } var firstPartyPub PublicKey copy(firstPartyPub.Key[:], caveat[:KeyLen]) caveat = caveat[KeyLen:] var nonce [NonceLen]byte copy(nonce[:], caveat[:NonceLen]) caveat = caveat[NonceLen:] data, ok := box.Open(nil, caveat, &nonce, firstPartyPub.boxKey(), key.Private.boxKey()) if !ok { return nil, errgo.Newf("cannot decrypt caveat id") } rootKey, ns, condition, err := decodeSecretPartV2V3(version, data) if err != nil { return nil, errgo.Notef(err, "invalid secret part") } return &ThirdPartyCaveatInfo{ Condition: condition, FirstPartyPublicKey: firstPartyPub, ThirdPartyKeyPair: *key, RootKey: rootKey, Caveat: origCaveat, Version: version, Namespace: ns, }, nil } func decodeSecretPartV2V3(version Version, data []byte) (rootKey []byte, ns *checkers.Namespace, condition []byte, err error) { fail := func(err error) ([]byte, *checkers.Namespace, []byte, error) { return nil, nil, nil, err } if len(data) < 1 { return fail(errgo.New("secret part too short")) } gotVersion, data := data[0], data[1:] if version != Version(gotVersion) { return fail(errgo.Newf("unexpected secret part version, got %d want %d", gotVersion, version)) } l, n := binary.Uvarint(data) if n <= 0 || uint64(n)+l > uint64(len(data)) { return fail(errgo.Newf("invalid root key length")) } data = data[n:] rootKey, data = data[:l], data[l:] if version >= Version3 { var nsData []byte var ns1 checkers.Namespace l, n = binary.Uvarint(data) if n <= 0 || uint64(n)+l > uint64(len(data)) { return fail(errgo.Newf("invalid namespace length")) } data = data[n:] nsData, data = data[:l], data[l:] if err := ns1.UnmarshalText(nsData); err != nil { return fail(errgo.Notef(err, "cannot unmarshal namespace")) } ns = &ns1 } else { ns = legacyNamespace() } return rootKey, ns, data, nil } // appendUvarint appends n to data encoded as a variable-length // unsigned integer. func appendUvarint(data []byte, n uint64) []byte { // Ensure the capacity is sufficient. If our space calculations when // allocating data were correct, this should never happen, // but be defensive just in case. for need := uvarintLen(n); cap(data)-len(data) < need; { data1 := append(data[0:cap(data)], 0) data = data1[0:len(data)] } nlen := binary.PutUvarint(data[len(data):cap(data)], n) return data[0 : len(data)+nlen] } // uvarintLen returns the number of bytes that n will require // when encoded with binary.PutUvarint. func uvarintLen(n uint64) int { len := 1 n >>= 7 for ; n > 0; n >>= 7 { len++ } return len } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/���������������������������0000755�0610621�0607500�00000000000�13172163311�027213� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/time_test.go���������������0000644�0610621�0607500�00000007632�13172163311�031547� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package checkers_test import ( "time" gc "gopkg.in/check.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type timeSuite struct{} var _ = gc.Suite(&timeSuite{}) var t1 = time.Now() var t2 = t1.Add(1 * time.Hour) var t3 = t2.Add(1 * time.Hour) var expireTimeTests = []struct { about string caveats []macaroon.Caveat expectTime time.Time expectExpires bool }{{ about: "nil caveats", }, { about: "empty caveats", caveats: []macaroon.Caveat{}, }, { about: "single time-before caveat", caveats: []macaroon.Caveat{ macaroon.Caveat{ Id: []byte(checkers.TimeBeforeCaveat(t1).Condition), }, }, expectTime: t1, expectExpires: true, }, { about: "single deny caveat", caveats: []macaroon.Caveat{ macaroon.Caveat{ Id: []byte(checkers.DenyCaveat("abc").Condition), }, }, }, { about: "multiple time-before caveat", caveats: []macaroon.Caveat{ macaroon.Caveat{ Id: []byte(checkers.TimeBeforeCaveat(t2).Condition), }, macaroon.Caveat{ Id: []byte(checkers.TimeBeforeCaveat(t1).Condition), }, }, expectTime: t1, expectExpires: true, }, { about: "mixed caveats", caveats: []macaroon.Caveat{ macaroon.Caveat{ Id: []byte(checkers.TimeBeforeCaveat(t1).Condition), }, macaroon.Caveat{ Id: []byte(checkers.AllowCaveat("abc").Condition), }, macaroon.Caveat{ Id: []byte(checkers.TimeBeforeCaveat(t2).Condition), }, macaroon.Caveat{ Id: []byte(checkers.DenyCaveat("def").Condition), }, }, expectTime: t1, expectExpires: true, }, { about: "invalid time-before caveat", caveats: []macaroon.Caveat{ macaroon.Caveat{ Id: []byte(checkers.CondTimeBefore + " tomorrow"), }, }, }} func (s *timeSuite) TestExpireTime(c *gc.C) { for i, test := range expireTimeTests { c.Logf("%d. %s", i, test.about) t, expires := checkers.ExpiryTime(nil, test.caveats) c.Assert(t.Equal(test.expectTime), gc.Equals, true, gc.Commentf("obtained: %s, expected: %s", t, test.expectTime)) c.Assert(expires, gc.Equals, test.expectExpires) } } var macaroonsExpireTimeTests = []struct { about string macaroons macaroon.Slice expectTime time.Time expectExpires bool }{{ about: "nil macaroons", }, { about: "empty macaroons", macaroons: macaroon.Slice{}, }, { about: "single macaroon without caveats", macaroons: macaroon.Slice{ mustNewMacaroon(), }, }, { about: "multiple macaroon without caveats", macaroons: macaroon.Slice{ mustNewMacaroon(), mustNewMacaroon(), }, }, { about: "single macaroon with time-before caveat", macaroons: macaroon.Slice{ mustNewMacaroon( checkers.TimeBeforeCaveat(t1).Condition, ), }, expectTime: t1, expectExpires: true, }, { about: "single macaroon with multiple time-before caveats", macaroons: macaroon.Slice{ mustNewMacaroon( checkers.TimeBeforeCaveat(t2).Condition, checkers.TimeBeforeCaveat(t1).Condition, ), }, expectTime: t1, expectExpires: true, }, { about: "multiple macaroons with multiple time-before caveats", macaroons: macaroon.Slice{ mustNewMacaroon( checkers.TimeBeforeCaveat(t3).Condition, checkers.TimeBeforeCaveat(t2).Condition, ), mustNewMacaroon( checkers.TimeBeforeCaveat(t3).Condition, checkers.TimeBeforeCaveat(t1).Condition, ), }, expectTime: t1, expectExpires: true, }} func (s *timeSuite) TestMacaroonsExpireTime(c *gc.C) { for i, test := range macaroonsExpireTimeTests { c.Logf("%d. %s", i, test.about) t, expires := checkers.MacaroonsExpiryTime(nil, test.macaroons) c.Assert(t.Equal(test.expectTime), gc.Equals, true, gc.Commentf("obtained: %s, expected: %s", t, test.expectTime)) c.Assert(expires, gc.Equals, test.expectExpires) } } func mustNewMacaroon(cavs ...string) *macaroon.Macaroon { m, err := macaroon.New(nil, nil, "", macaroon.LatestVersion) if err != nil { panic(err) } for _, cav := range cavs { if err := m.AddFirstPartyCaveat(cav); err != nil { panic(err) } } return m } ������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/time.go��������������������0000644�0610621�0607500�00000004463�13172163311�030507� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package checkers import ( "fmt" "time" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" ) // Clock represents a clock that can be faked for testing purposes. type Clock interface { Now() time.Time } type timeKey struct{} func ContextWithClock(ctx context.Context, clock Clock) context.Context { if clock == nil { return ctx } return context.WithValue(ctx, timeKey{}, clock) } func clockFromContext(ctx context.Context) Clock { c, _ := ctx.Value(timeKey{}).(Clock) return c } func checkTimeBefore(ctx context.Context, _, arg string) error { var now time.Time if clock := clockFromContext(ctx); clock != nil { now = clock.Now() } else { now = time.Now() } t, err := time.Parse(time.RFC3339Nano, arg) if err != nil { return errgo.Mask(err) } if !now.Before(t) { return fmt.Errorf("macaroon has expired") } return nil } // TimeBeforeCaveat returns a caveat that specifies that // the time that it is checked should be before t. func TimeBeforeCaveat(t time.Time) Caveat { return firstParty(CondTimeBefore, t.UTC().Format(time.RFC3339Nano)) } // ExpiryTime returns the minimum time of any time-before caveats found // in the given slice and whether there were any such caveats found. // // The ns parameter is used to determine the standard namespace prefix - if // the standard namespace is not found, the empty prefix is assumed. func ExpiryTime(ns *Namespace, cavs []macaroon.Caveat) (time.Time, bool) { prefix, _ := ns.Resolve(StdNamespace) timeBeforeCond := ConditionWithPrefix(prefix, CondTimeBefore) var t time.Time var expires bool for _, cav := range cavs { cav := string(cav.Id) name, rest, _ := ParseCaveat(cav) if name != timeBeforeCond { continue } et, err := time.Parse(time.RFC3339Nano, rest) if err != nil { continue } if !expires || et.Before(t) { t = et expires = true } } return t, expires } // MacaroonsExpiryTime returns the minimum time of any time-before // caveats found in the given macaroons and whether there were // any such caveats found. func MacaroonsExpiryTime(ns *Namespace, ms macaroon.Slice) (time.Time, bool) { var t time.Time var expires bool for _, m := range ms { if et, ex := ExpiryTime(ns, m.Caveats()); ex { if !expires || et.Before(t) { t = et expires = true } } } return t, expires } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/package_test.go������������0000644�0610621�0607500�00000000172�13172163311�032174� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package checkers_test import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/operations.go��������������0000644�0610621�0607500�00000005151�13172163311�031727� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package checkers import ( "fmt" "strings" "golang.org/x/net/context" errgo "gopkg.in/errgo.v1" ) type opKey struct{} // ContextWithOperations returns a context which is associated with all the // given operations. An allow caveat will succeed only if one of the allowed // operations is in ops; a deny caveat will succeed only if none of the denied // operations are in ops. func ContextWithOperations(ctx context.Context, ops ...string) context.Context { return context.WithValue(ctx, opKey{}, ops) } func operationsFromContext(ctx context.Context) []string { ops, _ := ctx.Value(opKey{}).([]string) return ops } // AllowCaveat returns a caveat that will deny attempts to use the // macaroon to perform any operation other than those listed. Operations // must not contain a space. func AllowCaveat(op ...string) Caveat { if len(op) == 0 { return ErrorCaveatf("no operations allowed") } return operationCaveat(CondAllow, op) } // DenyCaveat returns a caveat that will deny attempts to use the // macaroon to perform any of the listed operations. Operations // must not contain a space. func DenyCaveat(op ...string) Caveat { return operationCaveat(CondDeny, op) } // operationCaveat is a helper for AllowCaveat and DenyCaveat. It checks // that all operation names are valid before createing the caveat. func operationCaveat(cond string, op []string) Caveat { for _, o := range op { if strings.IndexByte(o, ' ') != -1 { return ErrorCaveatf("invalid operation name %q", o) } } return firstParty(cond, strings.Join(op, " ")) } func checkAllow(ctx context.Context, _, arg string) error { return checkOperation(ctx, true, arg) } func checkDeny(ctx context.Context, _, arg string) error { return checkOperation(ctx, false, arg) } // checkOperation checks an allow or a deny caveat. The needOps // parameter specifies whether we require all the operations in the // caveat to be declared in the context. func checkOperation(ctx context.Context, needOps bool, arg string) error { ctxOps := operationsFromContext(ctx) if len(ctxOps) == 0 { if needOps { f := strings.Fields(arg) if len(f) == 0 { return errgo.New("no operations allowed") } return errgo.Newf("%s not allowed", f[0]) } return nil } fields := strings.Fields(arg) for _, op := range ctxOps { if err := checkOneOp(op, needOps, fields); err != nil { return errgo.Mask(err) } } return nil } func checkOneOp(ctxOp string, needOp bool, fields []string) error { var found bool for _, op := range fields { if op == ctxOp { found = true break } } if found != needOp { return fmt.Errorf("%s not allowed", ctxOp) } return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/namespace_test.go����������0000644�0610621�0607500�00000015456�13172163311�032550� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package checkers_test import ( jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type NamespaceSuite struct{} var _ = gc.Suite(&NamespaceSuite{}) var resolveTests = []struct { about string ns *checkers.Namespace uri string expectPrefix string expectOK bool }{{ about: "successful resolve", ns: checkers.NewNamespace(map[string]string{"testns": "t"}), uri: "testns", expectPrefix: "t", expectOK: true, }, { about: "unsuccessful resolve", ns: checkers.NewNamespace(map[string]string{"testns": "t"}), uri: "foo", }, { about: "several of the same prefix", ns: checkers.NewNamespace(map[string]string{"testns": "t", "otherns": "t"}), uri: "otherns", expectPrefix: "t", expectOK: true, }, { about: "resolve with nil Namespace", uri: "testns", }} func (*NamespaceSuite) TestResolve(c *gc.C) { for i, test := range resolveTests { c.Logf("test %d: %s", i, test.about) prefix, ok := test.ns.Resolve(test.uri) c.Check(ok, gc.Equals, test.expectOK) c.Check(prefix, gc.Equals, test.expectPrefix) } } func (*NamespaceSuite) TestRegister(c *gc.C) { ns := checkers.NewNamespace(nil) ns.Register("testns", "t") prefix, ok := ns.Resolve("testns") c.Assert(prefix, gc.Equals, "t") c.Assert(ok, gc.Equals, true) ns.Register("other", "o") prefix, ok = ns.Resolve("other") c.Assert(prefix, gc.Equals, "o") c.Assert(ok, gc.Equals, true) // If we re-register the same URL, it does nothing. ns.Register("other", "p") prefix, ok = ns.Resolve("other") c.Assert(prefix, gc.Equals, "o") c.Assert(ok, gc.Equals, true) } func (*NamespaceSuite) TestRegisterBadURI(c *gc.C) { ns := checkers.NewNamespace(nil) c.Assert(func() { ns.Register("", "x") }, gc.PanicMatches, `cannot register invalid URI "" \(prefix "x"\)`) } func (*NamespaceSuite) TestRegisterBadPrefix(c *gc.C) { ns := checkers.NewNamespace(nil) c.Assert(func() { ns.Register("std", "x:1") }, gc.PanicMatches, `cannot register invalid prefix "x:1" for URI "std"`) } var resolveCaveatTests = []struct { about string ns map[string]string caveat checkers.Caveat expect checkers.Caveat }{{ about: "no namespace", caveat: checkers.Caveat{ Condition: "foo", }, expect: checkers.Caveat{ Condition: "foo", }, }, { about: "with registered namespace", ns: map[string]string{ "testns": "t", }, caveat: checkers.Caveat{ Condition: "foo", Namespace: "testns", }, expect: checkers.Caveat{ Condition: "t:foo", }, }, { about: "with unregistered namespace", caveat: checkers.Caveat{ Condition: "foo", Namespace: "testns", }, expect: checkers.Caveat{ Condition: `error caveat "foo" in unregistered namespace "testns"`, }, }, { about: "with empty prefix", ns: map[string]string{ "testns": "", }, caveat: checkers.Caveat{ Condition: "foo", Namespace: "testns", }, expect: checkers.Caveat{ Condition: "foo", }, }} func (*NamespaceSuite) TestResolveCaveatWithNamespace(c *gc.C) { for i, test := range resolveCaveatTests { c.Logf("test %d: %s", i, test.about) ns := checkers.NewNamespace(test.ns) c.Assert(ns.ResolveCaveat(test.caveat), jc.DeepEquals, test.expect) } } var namespaceMarshalTests = []struct { about string ns map[string]string expect string }{{ about: "empty namespace", }, { about: "standard namespace", ns: map[string]string{ "std": "", }, expect: "std:", }, { about: "several elements", ns: map[string]string{ "std": "", "http://blah.blah": "blah", "one": "two", "foo.com/x.v0.1": "z", }, expect: "foo.com/x.v0.1:z http://blah.blah:blah one:two std:", }, { about: "sort by URI not by field", ns: map[string]string{ "a": "one", "a1": "two", // Note that '1' < ':' }, expect: "a:one a1:two", }} func (*NamespaceSuite) TestMarshal(c *gc.C) { for i, test := range namespaceMarshalTests { c.Logf("test %d: %v", i, test.about) ns := checkers.NewNamespace(test.ns) data, err := ns.MarshalText() c.Assert(err, gc.Equals, nil) c.Assert(string(data), gc.Equals, test.expect) c.Assert(ns.String(), gc.Equals, test.expect) // Check that it can be unmarshaled to the same thing: var ns1 checkers.Namespace err = ns1.UnmarshalText(data) c.Assert(err, gc.Equals, nil) c.Assert(&ns1, jc.DeepEquals, ns) } } var namespaceUnmarshalTests = []struct { about string text string expect map[string]string expectError string }{{ about: "empty text", }, { about: "fields with extra space", text: " x:y \t\nz:\r", expect: map[string]string{ "x": "y", "z": "", }, }, { about: "field without colon", text: "foo:x bar baz:g", expectError: `no colon in namespace field "bar"`, }, { about: "invalid URI", text: "foo\xff:a", expectError: `invalid URI "foo\\xff" in namespace field "foo\\xff:a"`, }, { about: "empty URI", text: "blah:x :b", expectError: `invalid URI "" in namespace field ":b"`, }, { about: "invalid prefix", text: "p:\xff", expectError: `invalid prefix "\\xff" in namespace field "p:\\xff"`, }, { about: "duplicate URI", text: "std: std:p", expectError: `duplicate URI "std" in namespace "std: std:p"`, }} func (*NamespaceSuite) TestUnmarshal(c *gc.C) { for i, test := range namespaceUnmarshalTests { c.Logf("test %d: %v", i, test.about) var ns checkers.Namespace err := ns.UnmarshalText([]byte(test.text)) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) } else { c.Assert(err, gc.Equals, nil) c.Assert(&ns, jc.DeepEquals, checkers.NewNamespace(test.expect)) } } } func (*NamespaceSuite) TestMarshalNil(c *gc.C) { var ns *checkers.Namespace data, err := ns.MarshalText() c.Assert(err, gc.Equals, nil) c.Assert(data, gc.HasLen, 0) } var validTests = []struct { about string test func(string) bool s string expect bool }{{ about: "URI with schema", test: checkers.IsValidSchemaURI, s: "http://foo.com", expect: true, }, { about: "URI with space", test: checkers.IsValidSchemaURI, s: "a\rb", }, { about: "URI with unicode space", test: checkers.IsValidSchemaURI, s: "x\u2003y", }, { about: "empty URI", test: checkers.IsValidSchemaURI, }, { about: "URI with invalid UTF-8", test: checkers.IsValidSchemaURI, s: "\xff", }, { about: "prefix with colon", test: checkers.IsValidPrefix, s: "x:y", }, { about: "prefix with space", test: checkers.IsValidPrefix, s: "x y", }, { about: "prefix with unicode space", test: checkers.IsValidPrefix, s: "\u3000", }, { about: "empty prefix", test: checkers.IsValidPrefix, expect: true, }} func (*NamespaceSuite) TestValid(c *gc.C) { for i, test := range validTests { c.Check(test.test(test.s), gc.Equals, test.expect, gc.Commentf("test %d: %s", i, test.about)) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/namespace.go���������������0000644�0610621�0607500�00000013506�13172163311�031503� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package checkers import ( "sort" "strings" "unicode" "unicode/utf8" errgo "gopkg.in/errgo.v1" ) // Namespace holds maps from schema URIs to the // prefixes that are used to encode them in first party // caveats. Several different URIs may map to the same // prefix - this is usual when several different backwardly // compatible schema versions are registered. type Namespace struct { uriToPrefix map[string]string } // NewNamespace returns a new namespace with the // given initial contents. It will panic if any of the // URI keys or their associated prefix are invalid // (see IsValidSchemaURI and IsValidPrefix). func NewNamespace(uriToPrefix map[string]string) *Namespace { ns := &Namespace{ uriToPrefix: make(map[string]string), } for uri, prefix := range uriToPrefix { ns.Register(uri, prefix) } return ns } // String returns the namespace representation as returned by // ns.MarshalText. func (ns *Namespace) String() string { data, _ := ns.MarshalText() return string(data) } // MarshalText implements encoding.TextMarshaler by // returning all the elements in the namespace sorted by // URI, joined to the associated prefix with a colon and // separated with spaces. func (ns *Namespace) MarshalText() ([]byte, error) { if ns == nil || len(ns.uriToPrefix) == 0 { return nil, nil } uris := make([]string, 0, len(ns.uriToPrefix)) dataLen := 0 for uri, prefix := range ns.uriToPrefix { uris = append(uris, uri) dataLen += len(uri) + 1 + len(prefix) + 1 } sort.Strings(uris) data := make([]byte, 0, dataLen) for i, uri := range uris { if i > 0 { data = append(data, ' ') } data = append(data, uri...) data = append(data, ':') data = append(data, ns.uriToPrefix[uri]...) } return data, nil } func (ns *Namespace) UnmarshalText(data []byte) error { uriToPrefix := make(map[string]string) elems := strings.Fields(string(data)) for _, elem := range elems { i := strings.LastIndex(elem, ":") if i == -1 { return errgo.Newf("no colon in namespace field %q", elem) } uri, prefix := elem[0:i], elem[i+1:] if !IsValidSchemaURI(uri) { // Currently this can't happen because the only invalid URIs // are those which contain a space return errgo.Newf("invalid URI %q in namespace field %q", uri, elem) } if !IsValidPrefix(prefix) { return errgo.Newf("invalid prefix %q in namespace field %q", prefix, elem) } if _, ok := uriToPrefix[uri]; ok { return errgo.Newf("duplicate URI %q in namespace %q", uri, data) } uriToPrefix[uri] = prefix } ns.uriToPrefix = uriToPrefix return nil } // EnsureResolved tries to resolve the given schema URI to a prefix and // returns the prefix and whether the resolution was successful. If the // URI hasn't been registered but a compatible version has, the // given URI is registered with the same prefix. func (ns *Namespace) EnsureResolved(uri string) (string, bool) { // TODO(rog) compatibility return ns.Resolve(uri) } // Resolve resolves the given schema URI to its registered prefix and // returns the prefix and whether the resolution was successful. // // If ns is nil, it is treated as if it were empty. // // Resolve does not mutate ns and may be called concurrently // with other non-mutating Namespace methods. func (ns *Namespace) Resolve(uri string) (string, bool) { if ns == nil { return "", false } prefix, ok := ns.uriToPrefix[uri] return prefix, ok } // ResolveCaveat resolves the given caveat by using // Resolve to map from its schema namespace to the appropriate prefix using // Resolve. If there is no registered prefix for the namespace, // it returns an error caveat. // // If ns.Namespace is empty or ns.Location is non-empty, it returns cav unchanged. // // If ns is nil, it is treated as if it were empty. // // ResolveCaveat does not mutate ns and may be called concurrently // with other non-mutating Namespace methods. func (ns *Namespace) ResolveCaveat(cav Caveat) Caveat { // TODO(rog) If a namespace isn't registered, try to resolve it by // resolving it to the latest compatible version that is // registered. if cav.Namespace == "" || cav.Location != "" { return cav } prefix, ok := ns.Resolve(cav.Namespace) if !ok { errCav := ErrorCaveatf("caveat %q in unregistered namespace %q", cav.Condition, cav.Namespace) if errCav.Namespace != cav.Namespace { prefix, _ = ns.Resolve(errCav.Namespace) } cav = errCav } if prefix != "" { cav.Condition = ConditionWithPrefix(prefix, cav.Condition) } cav.Namespace = "" return cav } // ConditionWithPrefix returns the given string prefixed by the // given prefix. If the prefix is non-empty, a colon // is used to separate them. func ConditionWithPrefix(prefix, condition string) string { if prefix == "" { return condition } return prefix + ":" + condition } // Register registers the given URI and associates it // with the given prefix. If the URI has already been registered, // this is a no-op. func (ns *Namespace) Register(uri, prefix string) { if !IsValidSchemaURI(uri) { panic(errgo.Newf("cannot register invalid URI %q (prefix %q)", uri, prefix)) } if !IsValidPrefix(prefix) { panic(errgo.Newf("cannot register invalid prefix %q for URI %q", prefix, uri)) } if _, ok := ns.uriToPrefix[uri]; !ok { ns.uriToPrefix[uri] = prefix } } func invalidSchemaRune(r rune) bool { return unicode.IsSpace(r) } // IsValidSchemaURI reports whether the given argument is suitable for // use as a namespace schema URI. It must be non-empty, a valid UTF-8 // string and it must not contain white space. func IsValidSchemaURI(uri string) bool { // TODO more stringent requirements? return len(uri) > 0 && utf8.ValidString(uri) && strings.IndexFunc(uri, invalidSchemaRune) == -1 } func invalidPrefixRune(r rune) bool { return r == ' ' || r == ':' || unicode.IsSpace(r) } func IsValidPrefix(prefix string) bool { return utf8.ValidString(prefix) && strings.IndexFunc(prefix, invalidPrefixRune) == -1 } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/declared.go����������������0000644�0610621�0607500�00000007367�13172163311�031322� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package checkers import ( "strings" "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" ) type declaredKey struct{} // ContextWithDeclared returns a context with attached declared information, // as returned from InferDeclared. func ContextWithDeclared(ctx context.Context, declared map[string]string) context.Context { return context.WithValue(ctx, declaredKey{}, declared) } func declaredFromContext(ctx context.Context) map[string]string { m, _ := ctx.Value(declaredKey{}).(map[string]string) return m } // DeclaredCaveat returns a "declared" caveat asserting that the given key is // set to the given value. If a macaroon has exactly one first party // caveat asserting the value of a particular key, then InferDeclared // will be able to infer the value, and then DeclaredChecker will allow // the declared value if it has the value specified here. // // If the key is empty or contains a space, DeclaredCaveat // will return an error caveat. func DeclaredCaveat(key string, value string) Caveat { if strings.Contains(key, " ") || key == "" { return ErrorCaveatf("invalid caveat 'declared' key %q", key) } return firstParty(CondDeclared, key+" "+value) } // NeedDeclaredCaveat returns a third party caveat that // wraps the provided third party caveat and requires // that the third party must add "declared" caveats for // all the named keys. // TODO(rog) namespaces in third party caveats? func NeedDeclaredCaveat(cav Caveat, keys ...string) Caveat { if cav.Location == "" { return ErrorCaveatf("need-declared caveat is not third-party") } return Caveat{ Location: cav.Location, Condition: CondNeedDeclared + " " + strings.Join(keys, ",") + " " + cav.Condition, } } func checkDeclared(ctx context.Context, _, arg string) error { parts := strings.SplitN(arg, " ", 2) if len(parts) != 2 { return errgo.Newf("declared caveat has no value") } attrs := declaredFromContext(ctx) val, ok := attrs[parts[0]] if !ok { return errgo.Newf("got %s=null, expected %q", parts[0], parts[1]) } if val != parts[1] { return errgo.Newf("got %s=%q, expected %q", parts[0], val, parts[1]) } return nil } // InferDeclared retrieves any declared information from // the given macaroons and returns it as a key-value map. // // Information is declared with a first party caveat as created // by DeclaredCaveat. // // If there are two caveats that declare the same key with // different values, the information is omitted from the map. // When the caveats are later checked, this will cause the // check to fail. func InferDeclared(ns *Namespace, ms macaroon.Slice) map[string]string { var conditions []string for _, m := range ms { for _, cav := range m.Caveats() { if cav.Location == "" { conditions = append(conditions, string(cav.Id)) } } } return InferDeclaredFromConditions(ns, conditions) } // InferDeclaredFromConditions is like InferDeclared except that // it is passed a set of first party caveat conditions rather than a set of macaroons. func InferDeclaredFromConditions(ns *Namespace, conds []string) map[string]string { var conflicts []string // If we can't resolve that standard namespace, then we'll look for // just bare "declared" caveats which will work OK for legacy // macaroons with no namespace. prefix, _ := ns.Resolve(StdNamespace) declaredCond := prefix + CondDeclared info := make(map[string]string) for _, cond := range conds { name, rest, _ := ParseCaveat(cond) if name != declaredCond { continue } parts := strings.SplitN(rest, " ", 2) if len(parts) != 2 { continue } key, val := parts[0], parts[1] if oldVal, ok := info[key]; ok && oldVal != val { conflicts = append(conflicts, key) continue } info[key] = val } for _, key := range conflicts { delete(info, key) } return info } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/checkers_test.go�����������0000644�0610621�0607500�00000036646�13172163311�032407� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package checkers_test import ( "fmt" "time" jc "github.com/juju/testing/checkers" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type CheckersSuite struct{} var _ = gc.Suite(&CheckersSuite{}) // A frozen time for the tests. var now = time.Date(2006, time.January, 2, 15, 4, 5, int(123*time.Millisecond), time.UTC) // testClock is a Clock implementation that always returns the above time. type testClock struct{} func (testClock) Now() time.Time { return now } // FirstPartyCaveatChecker is declared here so we can avoid a cyclic // dependency on the bakery. type FirstPartyCaveatChecker interface { CheckFirstPartyCaveat(ctx context.Context, caveat string) error } type checkTest struct { caveat string expectError string expectCause func(err error) bool } var isCaveatNotRecognized = errgo.Is(checkers.ErrCaveatNotRecognized) var checkerTests = []struct { about string addContext func(context.Context) context.Context checks []checkTest }{{ about: "nothing in context, no extra checkers", checks: []checkTest{{ caveat: "something", expectError: `caveat "something" not satisfied: caveat not recognized`, expectCause: isCaveatNotRecognized, }, { caveat: "", expectError: `cannot parse caveat "": empty caveat`, expectCause: isCaveatNotRecognized, }, { caveat: " hello", expectError: `cannot parse caveat " hello": caveat starts with space character`, expectCause: isCaveatNotRecognized, }}, }, { about: "one failed caveat", checks: []checkTest{{ caveat: "t:a aval", }, { caveat: "t:b bval", }, { caveat: "t:a wrong", expectError: `caveat "t:a wrong" not satisfied: wrong arg`, expectCause: errgo.Is(errWrongArg), }}, }, { about: "time from clock", addContext: func(ctx context.Context) context.Context { return checkers.ContextWithClock(ctx, testClock{}) }, checks: []checkTest{{ caveat: checkers.TimeBeforeCaveat(now.Add(1)).Condition, }, { caveat: checkers.TimeBeforeCaveat(now).Condition, expectError: `caveat "time-before 2006-01-02T15:04:05.123Z" not satisfied: macaroon has expired`, }, { caveat: checkers.TimeBeforeCaveat(now.Add(-1)).Condition, expectError: `caveat "time-before 2006-01-02T15:04:05.122999999Z" not satisfied: macaroon has expired`, }, { caveat: `time-before bad-date`, expectError: `caveat "time-before bad-date" not satisfied: parsing time "bad-date" as "2006-01-02T15:04:05.999999999Z07:00": cannot parse "bad-date" as "2006"`, }, { caveat: checkers.TimeBeforeCaveat(now).Condition + " ", expectError: `caveat "time-before 2006-01-02T15:04:05.123Z " not satisfied: parsing time "2006-01-02T15:04:05.123Z ": extra text: `, }}, }, { about: "real time", checks: []checkTest{{ caveat: checkers.TimeBeforeCaveat(time.Date(2010, time.January, 1, 0, 0, 0, 0, time.UTC)).Condition, expectError: `caveat "time-before 2010-01-01T00:00:00Z" not satisfied: macaroon has expired`, }, { caveat: checkers.TimeBeforeCaveat(time.Date(3000, time.January, 1, 0, 0, 0, 0, time.UTC)).Condition, }}, }, { about: "declared, no entries", checks: []checkTest{{ caveat: checkers.DeclaredCaveat("a", "aval").Condition, expectError: `caveat "declared a aval" not satisfied: got a=null, expected "aval"`, }, { caveat: checkers.CondDeclared, expectError: `caveat "declared" not satisfied: declared caveat has no value`, }}, }, { about: "declared, some entries", addContext: func(ctx context.Context) context.Context { return checkers.ContextWithDeclared(ctx, map[string]string{ "a": "aval", "b": "bval", "spc": " a b", }) }, checks: []checkTest{{ caveat: checkers.DeclaredCaveat("a", "aval").Condition, }, { caveat: checkers.DeclaredCaveat("b", "bval").Condition, }, { caveat: checkers.DeclaredCaveat("spc", " a b").Condition, }, { caveat: checkers.DeclaredCaveat("a", "bval").Condition, expectError: `caveat "declared a bval" not satisfied: got a="aval", expected "bval"`, }, { caveat: checkers.DeclaredCaveat("a", " aval").Condition, expectError: `caveat "declared a aval" not satisfied: got a="aval", expected " aval"`, }, { caveat: checkers.DeclaredCaveat("spc", "a b").Condition, expectError: `caveat "declared spc a b" not satisfied: got spc=" a b", expected "a b"`, }, { caveat: checkers.DeclaredCaveat("", "a b").Condition, expectError: `caveat "error invalid caveat 'declared' key \\"\\"" not satisfied: bad caveat`, }, { caveat: checkers.DeclaredCaveat("a b", "a b").Condition, expectError: `caveat "error invalid caveat 'declared' key \\"a b\\"" not satisfied: bad caveat`, }}, }, { about: "error caveat", checks: []checkTest{{ caveat: checkers.ErrorCaveatf("").Condition, expectError: `caveat "error" not satisfied: bad caveat`, }, { caveat: checkers.ErrorCaveatf("something %d", 134).Condition, expectError: `caveat "error something 134" not satisfied: bad caveat`, }}, }} var errWrongArg = errgo.New("wrong arg") // argChecker returns a checker function that checks // that the caveat condition is checkArg. func argChecker(c *gc.C, expectCond, checkArg string) checkers.Func { return func(_ context.Context, cond, arg string) error { c.Assert(cond, gc.Equals, expectCond) if arg != checkArg { return errWrongArg } return nil } } func (s *CheckersSuite) TestCheckers(c *gc.C) { checker := checkers.New(nil) checker.Namespace().Register("testns", "t") checker.Register("a", "testns", argChecker(c, "t:a", "aval")) checker.Register("b", "testns", argChecker(c, "t:b", "bval")) for i, test := range checkerTests { c.Logf("test %d: %s", i, test.about) ctx := context.Background() if test.addContext != nil { ctx = test.addContext(ctx) } for j, check := range test.checks { c.Logf("\tcheck %d", j) err := checker.CheckFirstPartyCaveat(ctx, check.caveat) if check.expectError != "" { c.Assert(err, gc.ErrorMatches, check.expectError) if check.expectCause == nil { check.expectCause = errgo.Any } c.Assert(check.expectCause(errgo.Cause(err)), gc.Equals, true) } else { c.Assert(err, gc.IsNil) } } } } var inferDeclaredTests = []struct { about string caveats [][]checkers.Caveat expect map[string]string namespace map[string]string }{{ about: "no macaroons", expect: map[string]string{}, }, { about: "single macaroon with one declaration", caveats: [][]checkers.Caveat{{{ Condition: "declared foo bar", }}}, expect: map[string]string{ "foo": "bar", }, }, { about: "only one argument to declared", caveats: [][]checkers.Caveat{{{ Condition: "declared foo", }}}, expect: map[string]string{}, }, { about: "spaces in value", caveats: [][]checkers.Caveat{{{ Condition: "declared foo bar bloggs", }}}, expect: map[string]string{ "foo": "bar bloggs", }, }, { about: "attribute with declared prefix", caveats: [][]checkers.Caveat{{{ Condition: "declaredccf foo", }}}, expect: map[string]string{}, }, { about: "several macaroons with different declares", caveats: [][]checkers.Caveat{{ checkers.DeclaredCaveat("a", "aval"), checkers.DeclaredCaveat("b", "bval"), }, { checkers.DeclaredCaveat("c", "cval"), checkers.DeclaredCaveat("d", "dval"), }}, expect: map[string]string{ "a": "aval", "b": "bval", "c": "cval", "d": "dval", }, }, { about: "duplicate values", caveats: [][]checkers.Caveat{{ checkers.DeclaredCaveat("a", "aval"), checkers.DeclaredCaveat("a", "aval"), checkers.DeclaredCaveat("b", "bval"), }, { checkers.DeclaredCaveat("a", "aval"), checkers.DeclaredCaveat("b", "bval"), checkers.DeclaredCaveat("c", "cval"), checkers.DeclaredCaveat("d", "dval"), }}, expect: map[string]string{ "a": "aval", "b": "bval", "c": "cval", "d": "dval", }, }, { about: "conflicting values", caveats: [][]checkers.Caveat{{ checkers.DeclaredCaveat("a", "aval"), checkers.DeclaredCaveat("a", "conflict"), checkers.DeclaredCaveat("b", "bval"), }, { checkers.DeclaredCaveat("a", "conflict"), checkers.DeclaredCaveat("b", "another conflict"), checkers.DeclaredCaveat("c", "cval"), checkers.DeclaredCaveat("d", "dval"), }}, expect: map[string]string{ "c": "cval", "d": "dval", }, }, { about: "third party caveats ignored", caveats: [][]checkers.Caveat{{{ Condition: "declared a no conflict", Location: "location", }, checkers.DeclaredCaveat("a", "aval"), }}, expect: map[string]string{ "a": "aval", }, }, { about: "unparseable caveats ignored", caveats: [][]checkers.Caveat{{{ Condition: " bad", }, checkers.DeclaredCaveat("a", "aval"), }}, expect: map[string]string{ "a": "aval", }, }, { about: "infer with namespace", namespace: map[string]string{ checkers.StdNamespace: "", "testns": "t", }, caveats: [][]checkers.Caveat{{ checkers.DeclaredCaveat("a", "aval"), // A declared caveat from a different namespace doesn't // interfere. caveatWithNamespace(checkers.DeclaredCaveat("a", "bval"), "testns"), }}, expect: map[string]string{ "a": "aval", }, }} func caveatWithNamespace(cav checkers.Caveat, uri string) checkers.Caveat { cav.Namespace = uri return cav } func (*CheckersSuite) TestInferDeclared(c *gc.C) { for i, test := range inferDeclaredTests { if test.namespace == nil { test.namespace = map[string]string{ checkers.StdNamespace: "", } } ns := checkers.NewNamespace(test.namespace) c.Logf("test %d: %s", i, test.about) ms := make(macaroon.Slice, len(test.caveats)) for i, caveats := range test.caveats { m, err := macaroon.New(nil, []byte(fmt.Sprint(i)), "", macaroon.LatestVersion) c.Assert(err, gc.IsNil) for _, cav := range caveats { cav = ns.ResolveCaveat(cav) if cav.Location == "" { m.AddFirstPartyCaveat(cav.Condition) } else { m.AddThirdPartyCaveat(nil, []byte(cav.Condition), cav.Location) } } ms[i] = m } c.Assert(checkers.InferDeclared(nil, ms), jc.DeepEquals, test.expect) } } var operationsCheckerTests = []struct { about string caveat checkers.Caveat ops []string expectError string }{{ about: "all allowed", caveat: checkers.AllowCaveat("op1", "op2", "op4", "op3"), ops: []string{"op1", "op3", "op2"}, }, { about: "none denied", caveat: checkers.DenyCaveat("op1", "op2"), ops: []string{"op3", "op4"}, }, { about: "one not allowed", caveat: checkers.AllowCaveat("op1", "op2"), ops: []string{"op1", "op3"}, expectError: `op3 not allowed`, }, { about: "one denied", caveat: checkers.DenyCaveat("op1", "op2"), ops: []string{"op4", "op5", "op2"}, expectError: `op2 not allowed`, }, { about: "no operations, allow caveat", caveat: checkers.AllowCaveat("op1"), ops: []string{}, expectError: `op1 not allowed`, }, { about: "no operations, deny caveat", caveat: checkers.DenyCaveat("op1"), ops: []string{}, }, { about: "no operations, empty allow caveat", caveat: checkers.Caveat{ Condition: checkers.CondAllow, }, ops: []string{}, expectError: `no operations allowed`, }} func (*CheckersSuite) TestOperationsChecker(c *gc.C) { checker := checkers.New(nil) for i, test := range operationsCheckerTests { c.Logf("%d: %s", i, test.about) ctx := checkers.ContextWithOperations(context.Background(), test.ops...) err := checker.CheckFirstPartyCaveat(ctx, test.caveat.Condition) if test.expectError == "" { c.Assert(err, gc.IsNil) continue } c.Assert(err, gc.ErrorMatches, ".*: "+test.expectError) } } var operationErrorCaveatTests = []struct { about string caveat checkers.Caveat expectCondition string }{{ about: "empty allow", caveat: checkers.AllowCaveat(), expectCondition: "error no operations allowed", }, { about: "allow: invalid operation name", caveat: checkers.AllowCaveat("op1", "operation number 2"), expectCondition: `error invalid operation name "operation number 2"`, }, { about: "deny: invalid operation name", caveat: checkers.DenyCaveat("op1", "operation number 2"), expectCondition: `error invalid operation name "operation number 2"`, }} func (*CheckersSuite) TestOperationErrorCaveatTest(c *gc.C) { for i, test := range operationErrorCaveatTests { c.Logf("%d: %s", i, test.about) c.Assert(test.caveat.Condition, gc.Matches, test.expectCondition) } } func (*CheckersSuite) TestRegisterNilFuncPanics(c *gc.C) { checker := checkers.New(nil) c.Assert(func() { checker.Register("x", checkers.StdNamespace, nil) }, gc.PanicMatches, `nil check function registered for namespace ".*" when registering condition "x"`) } func (*CheckersSuite) TestRegisterNoRegisteredNamespace(c *gc.C) { checker := checkers.New(nil) c.Assert(func() { checker.Register("x", "testns", succeed) }, gc.PanicMatches, `no prefix registered for namespace "testns" when registering condition "x"`) } func (*CheckersSuite) TestRegisterEmptyPrefixConditionWithColon(c *gc.C) { checker := checkers.New(nil) checker.Namespace().Register("testns", "") c.Assert(func() { checker.Register("x:y", "testns", succeed) }, gc.PanicMatches, `caveat condition "x:y" in namespace "testns" contains a colon but its prefix is empty`) } func (*CheckersSuite) TestRegisterTwiceSameNamespace(c *gc.C) { checker := checkers.New(nil) checker.Namespace().Register("testns", "t") checker.Register("x", "testns", succeed) c.Assert(func() { checker.Register("x", "testns", succeed) }, gc.PanicMatches, `checker for "t:x" \(namespace "testns"\) already registered in namespace "testns"`) } func (*CheckersSuite) TestRegisterTwiceDifferentNamespace(c *gc.C) { checker := checkers.New(nil) checker.Namespace().Register("testns", "t") checker.Namespace().Register("otherns", "t") checker.Register("x", "testns", succeed) c.Assert(func() { checker.Register("x", "otherns", succeed) }, gc.PanicMatches, `checker for "t:x" \(namespace "otherns"\) already registered in namespace "testns"`) } func (*CheckersSuite) TestCheckerInfo(c *gc.C) { checker := checkers.NewEmpty(nil) checker.Namespace().Register("one", "t") checker.Namespace().Register("two", "t") checker.Namespace().Register("three", "") checker.Namespace().Register("four", "s") var calledVal string register := func(name, ns string) { checker.Register(name, ns, func(ctx context.Context, cond, arg string) error { calledVal = name + " " + ns return nil }) } register("x", "one") register("y", "one") register("z", "two") register("a", "two") register("something", "three") register("other", "three") register("xxx", "four") expect := []checkers.CheckerInfo{{ Namespace: "four", Name: "xxx", Prefix: "s", }, { Namespace: "one", Name: "x", Prefix: "t", }, { Namespace: "one", Name: "y", Prefix: "t", }, { Namespace: "three", Name: "other", Prefix: "", }, { Namespace: "three", Name: "something", Prefix: "", }, { Namespace: "two", Name: "a", Prefix: "t", }, { Namespace: "two", Name: "z", Prefix: "t", }} infos := checker.Info() // We can't use DeepEqual on functions so check that the right functions are // there by calling them, then set them to nil. c.Assert(infos, gc.HasLen, len(expect)) for i := range infos { info := &infos[i] calledVal = "" info.Check(nil, "", "") c.Check(calledVal, gc.Equals, expect[i].Name+" "+expect[i].Namespace, gc.Commentf("index %d", i)) info.Check = nil } c.Assert(infos, jc.DeepEquals, expect) } func succeed(ctx context.Context, cond, arg string) error { return nil } ������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers/checkers.go����������������0000644�0610621�0607500�00000017000�13172163311�031327� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// The checkers package provides some standard first-party // caveat checkers and some primitives for combining them. package checkers import ( "fmt" "sort" "strings" "golang.org/x/net/context" "gopkg.in/errgo.v1" ) // StdNamespace holds the URI of the standard checkers schema. const StdNamespace = "std" // Constants for all the standard caveat conditions. // First and third party caveat conditions are both defined here, // even though notionally they exist in separate name spaces. const ( CondDeclared = "declared" CondTimeBefore = "time-before" CondError = "error" CondAllow = "allow" CondDeny = "deny" ) const ( CondNeedDeclared = "need-declared" ) // Func is the type of a function used by Checker to check a caveat. The // cond parameter will hold the caveat condition including any namespace // prefix; the arg parameter will hold any additional caveat argument // text. type Func func(ctx context.Context, cond, arg string) error // CheckerInfo holds information on a registered checker. type CheckerInfo struct { // Check holds the actual checker function. Check Func // Prefix holds the prefix for the checker condition. Prefix string // Name holds the name of the checker condition. Name string // Namespace holds the namespace URI for the checker's // schema. Namespace string } var allCheckers = map[string]Func{ CondTimeBefore: checkTimeBefore, CondDeclared: checkDeclared, CondAllow: checkAllow, CondDeny: checkDeny, CondError: checkError, } // NewEmpty returns a checker using the given namespace // that has no registered checkers. // If ns is nil, a new one will be created. func NewEmpty(ns *Namespace) *Checker { if ns == nil { ns = NewNamespace(nil) } return &Checker{ namespace: ns, checkers: make(map[string]CheckerInfo), } } // RegisterStd registers all the standard checkers in the given checker. // If not present already, the standard checkers schema (StdNamespace) is // added to the checker's namespace with an empty prefix. func RegisterStd(c *Checker) { c.namespace.Register(StdNamespace, "") for cond, check := range allCheckers { c.Register(cond, StdNamespace, check) } } // New returns a checker with all the standard caveats checkers registered. // If ns is nil, a new one will be created. // The standard namespace is also added to ns if not present. func New(ns *Namespace) *Checker { c := NewEmpty(ns) RegisterStd(c) return c } // Checker holds a set of checkers for first party caveats. // It implements bakery.CheckFirstParty caveat. type Checker struct { namespace *Namespace checkers map[string]CheckerInfo } // Register registers the given condition in the given namespace URI // to be checked with the given check function. // It will panic if the namespace is not registered or // if the condition has already been registered. func (c *Checker) Register(cond, uri string, check Func) { if check == nil { panic(fmt.Errorf("nil check function registered for namespace %q when registering condition %q", uri, cond)) } prefix, ok := c.namespace.Resolve(uri) if !ok { panic(fmt.Errorf("no prefix registered for namespace %q when registering condition %q", uri, cond)) } if prefix == "" && strings.Contains(cond, ":") { panic(fmt.Errorf("caveat condition %q in namespace %q contains a colon but its prefix is empty", cond, uri)) } fullCond := ConditionWithPrefix(prefix, cond) if info, ok := c.checkers[fullCond]; ok { panic(fmt.Errorf("checker for %q (namespace %q) already registered in namespace %q", fullCond, uri, info.Namespace)) } c.checkers[fullCond] = CheckerInfo{ Check: check, Namespace: uri, Name: cond, Prefix: prefix, } } // Info returns information on all the registered checkers, sorted by namespace // and then name. func (c *Checker) Info() []CheckerInfo { checkers := make([]CheckerInfo, 0, len(c.checkers)) for _, c := range c.checkers { checkers = append(checkers, c) } sort.Sort(checkerInfoByName(checkers)) return checkers } // Namespace returns the namespace associated with the // checker. It implements bakery.FirstPartyCaveatChecker.Namespace. func (c *Checker) Namespace() *Namespace { return c.namespace } // CheckFirstPartyCaveat implements bakery.FirstPartyCaveatChecker // by checking the caveat against all registered caveats conditions. func (c *Checker) CheckFirstPartyCaveat(ctx context.Context, cav string) error { cond, arg, err := ParseCaveat(cav) if err != nil { // If we can't parse it, perhaps it's in some other format, // return a not-recognised error. return errgo.WithCausef(err, ErrCaveatNotRecognized, "cannot parse caveat %q", cav) } cf, ok := c.checkers[cond] if !ok { return errgo.NoteMask(ErrCaveatNotRecognized, fmt.Sprintf("caveat %q not satisfied", cav), errgo.Any) } if err := cf.Check(ctx, cond, arg); err != nil { return errgo.NoteMask(err, fmt.Sprintf("caveat %q not satisfied", cav), errgo.Any) } return nil } var errBadCaveat = errgo.New("bad caveat") func checkError(ctx context.Context, _, arg string) error { return errBadCaveat } // ErrCaveatNotRecognized is the cause of errors returned // from caveat checkers when the caveat was not // recognized. var ErrCaveatNotRecognized = errgo.New("caveat not recognized") // Caveat represents a condition that must be true for a check to // complete successfully. If Location is non-empty, the caveat must be // discharged by a third party at the given location. // The Namespace field holds the namespace URI of the // condition - if it is non-empty, it will be converted to // a namespace prefix before adding to the macaroon. type Caveat struct { Condition string Namespace string Location string } // Condition builds a caveat condition from the given name and argument. func Condition(name, arg string) string { if arg == "" { return name } return name + " " + arg } func firstParty(name, arg string) Caveat { return Caveat{ Condition: Condition(name, arg), Namespace: StdNamespace, } } // ParseCaveat parses a caveat into an identifier, identifying the // checker that should be used, and the argument to the checker (the // rest of the string). // // The identifier is taken from all the characters before the first // space character. func ParseCaveat(cav string) (cond, arg string, err error) { if cav == "" { return "", "", fmt.Errorf("empty caveat") } i := strings.IndexByte(cav, ' ') if i < 0 { return cav, "", nil } if i == 0 { return "", "", fmt.Errorf("caveat starts with space character") } return cav[0:i], cav[i+1:], nil } // ErrorCaveatf returns a caveat that will never be satisfied, holding // the given fmt.Sprintf formatted text as the text of the caveat. // // This should only be used for highly unusual conditions that are never // expected to happen in practice, such as a malformed key that is // conventionally passed as a constant. It's not a panic but you should // only use it in cases where a panic might possibly be appropriate. // // This mechanism means that caveats can be created without error // checking and a later systematic check at a higher level (in the // bakery package) can produce an error instead. func ErrorCaveatf(f string, a ...interface{}) Caveat { return firstParty(CondError, fmt.Sprintf(f, a...)) } type checkerInfoByName []CheckerInfo func (c checkerInfoByName) Less(i, j int) bool { info0, info1 := &c[i], &c[j] if info0.Namespace != info1.Namespace { return info0.Namespace < info1.Namespace } return info0.Name < info1.Name } func (c checkerInfoByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c checkerInfoByName) Len() int { return len(c) } lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checker_test.go���������������������0000644�0610621�0607500�00000106132�13172163311�030421� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "sort" "strings" "time" jujutesting "github.com/juju/testing" jc "github.com/juju/testing/checkers" "golang.org/x/net/context" gc "gopkg.in/check.v1" errgo "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type dischargeRecord struct { location string user string } type checkerSuite struct { jujutesting.LoggingSuite discharges []dischargeRecord } var _ = gc.Suite(&checkerSuite{}) func (s *checkerSuite) SetUpTest(c *gc.C) { s.discharges = nil s.LoggingSuite.SetUpTest(c) } func (s *checkerSuite) TestAuthorizeWithOpenAccessAndNoMacaroons(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("something"): {bakery.Everyone}} ts := newService(auth, ids, locator) client := newClient(locator) authInfo, err := client.do(testContext, ts, readOp("something")) c.Assert(err, gc.IsNil) c.Assert(s.discharges, gc.HasLen, 0) c.Assert(authInfo, gc.NotNil) c.Assert(authInfo.Identity, gc.Equals, nil) c.Assert(authInfo.Macaroons, gc.HasLen, 0) } func (s *checkerSuite) TestAuthorizationDenied(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := bakery.ClosedAuthorizer ts := newService(auth, ids, locator) client := newClient(locator) authInfo, err := client.do(asUser("bob"), ts, readOp("something")) c.Assert(err, gc.ErrorMatches, `permission denied`) c.Assert(authInfo, gc.IsNil) } func (s *checkerSuite) TestAuthorizeWithAuthenticationRequired(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("something"): {"bob"}} ts := newService(auth, ids, locator) client := newClient(locator) authInfo, err := client.do(asUser("bob"), ts, readOp("something")) c.Assert(err, gc.IsNil) c.Assert(s.discharges, jc.DeepEquals, []dischargeRecord{{ location: "ids", user: "bob", }}) c.Assert(authInfo, gc.NotNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("bob")) c.Assert(authInfo.Macaroons, gc.HasLen, 1) } func asUser(username string) context.Context { return contextWithDischargeUser(testContext, username) } func (s *checkerSuite) TestAuthorizeMultipleOps(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("something"): {"bob"}, readOp("otherthing"): {"bob"}} ts := newService(auth, ids, locator) client := newClient(locator) _, err := client.do(asUser("bob"), ts, readOp("something"), readOp("otherthing")) c.Assert(err, gc.IsNil) c.Assert(s.discharges, jc.DeepEquals, []dischargeRecord{{ location: "ids", user: "bob", }}) } func (s *checkerSuite) TestCapability(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("something"): {"bob"}} ts := newService(auth, ids, locator) client := newClient(locator) m, err := client.dischargedCapability(asUser("bob"), ts, readOp("something")) c.Assert(err, gc.IsNil) // Check that we can exercise the capability directly on the service // with no discharging required. authInfo, err := ts.do(testContext, []macaroon.Slice{m}, readOp("something")) c.Assert(err, gc.IsNil) c.Assert(authInfo, gc.NotNil) c.Assert(authInfo.Identity, gc.Equals, nil) c.Assert(authInfo.Macaroons, gc.HasLen, 1) c.Assert(authInfo.Macaroons[0][0].Id(), jc.DeepEquals, m[0].Id()) } func (s *checkerSuite) TestCapabilityMultipleEntities(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"bob"}, readOp("e2"): {"bob"}, readOp("e3"): {"bob"}} ts := newService(auth, ids, locator) client := newClient(locator) m, err := client.dischargedCapability(asUser("bob"), ts, readOp("e1"), readOp("e2"), readOp("e3")) c.Assert(err, gc.IsNil) c.Assert(s.discharges, jc.DeepEquals, []dischargeRecord{{ location: "ids", user: "bob", }}) // Check that we can exercise the capability directly on the service // with no discharging required. _, err = ts.do(testContext, []macaroon.Slice{m}, readOp("e1"), readOp("e2"), readOp("e3")) c.Assert(err, gc.IsNil) // Check that we can exercise the capability to act on a subset of the operations. _, err = ts.do(testContext, []macaroon.Slice{m}, readOp("e2"), readOp("e3")) c.Assert(err, gc.IsNil) _, err = ts.do(testContext, []macaroon.Slice{m}, readOp("e3")) c.Assert(err, gc.IsNil) } func (s *checkerSuite) TestMultipleCapabilities(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"alice"}, readOp("e2"): {"bob"}} ts := newService(auth, ids, locator) // Acquire two capabilities as different users and check // that we can combine them together to do both operations // at once. m1, err := newClient(locator).dischargedCapability(asUser("alice"), ts, readOp("e1")) c.Assert(err, gc.IsNil) m2, err := newClient(locator).dischargedCapability(asUser("bob"), ts, readOp("e2")) c.Assert(err, gc.IsNil) c.Assert(s.discharges, jc.DeepEquals, []dischargeRecord{{ location: "ids", user: "alice", }, { location: "ids", user: "bob", }}) authInfo, err := ts.do(testContext, []macaroon.Slice{m1, m2}, readOp("e1"), readOp("e2")) c.Assert(err, gc.IsNil) c.Assert(authInfo, gc.NotNil) c.Assert(authInfo.Identity, gc.Equals, nil) c.Assert(authInfo.Macaroons, gc.HasLen, 2) c.Assert(authInfo.Macaroons[0][0].Id(), jc.DeepEquals, m1[0].Id()) c.Assert(authInfo.Macaroons[1][0].Id(), jc.DeepEquals, m2[0].Id()) } func (s *checkerSuite) TestCombineCapabilities(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"alice"}, readOp("e2"): {"bob"}, readOp("e3"): {"bob", "alice"}} ts := newService(auth, ids, locator) // Acquire two capabilities as different users and check // that we can combine them together into a single capability // capable of both operations. m1, err := newClient(locator).dischargedCapability(asUser("alice"), ts, readOp("e1"), readOp("e3")) c.Assert(err, gc.IsNil) m2, err := newClient(locator).dischargedCapability(asUser("bob"), ts, readOp("e2")) c.Assert(err, gc.IsNil) m, err := ts.capability(testContext, []macaroon.Slice{m1, m2}, readOp("e1"), readOp("e2"), readOp("e3")) c.Assert(err, gc.IsNil) _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, readOp("e1"), readOp("e2"), readOp("e3")) c.Assert(err, gc.IsNil) } func (s *checkerSuite) TestPartiallyAuthorizedRequest(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"alice"}, readOp("e2"): {"bob"}} ts := newService(auth, ids, locator) // Acquire a capability for e1 but rely on authentication to // authorize e2. m, err := newClient(locator).dischargedCapability(asUser("alice"), ts, readOp("e1")) c.Assert(err, gc.IsNil) client := newClient(locator) client.addMacaroon(ts, "authz", m) _, err = client.do(asUser("bob"), ts, readOp("e1"), readOp("e2")) c.Assert(err, gc.IsNil) } func (s *checkerSuite) TestAuthWithThirdPartyCaveats(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) // We make an authorizer that requires a third party discharge // when authorizing. auth := bakery.AuthorizerFunc(func(_ context.Context, id bakery.Identity, op bakery.Op) (bool, []checkers.Caveat, error) { if id == bakery.SimpleIdentity("bob") && op == readOp("something") { return true, []checkers.Caveat{{ Condition: "question", Location: "other third party", }}, nil } return false, nil, nil }) ts := newService(auth, ids, locator) locator["other third party"] = &discharger{ key: mustGenerateKey(), checker: bakery.ThirdPartyCaveatCheckerFunc(func(ctx context.Context, info *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { if string(info.Condition) != "question" { return nil, errgo.Newf("third party condition not recognized") } s.discharges = append(s.discharges, dischargeRecord{ location: "other third party", user: dischargeUserFromContext(ctx), }) return nil, nil }), locator: locator, } client := newClient(locator) _, err := client.do(asUser("bob"), ts, readOp("something")) c.Assert(err, gc.IsNil) c.Assert(s.discharges, jc.DeepEquals, []dischargeRecord{{ location: "ids", user: "bob", }, { location: "other third party", user: "bob", }}) } func (s *checkerSuite) TestCapabilityCombinesFirstPartyCaveats(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"alice"}, readOp("e2"): {"bob"}} ts := newService(auth, ids, locator) // Acquire two capabilities as different users, add some first party caveats // // that we can combine them together into a single capability // capable of both operations. m1, err := newClient(locator).capability(asUser("alice"), ts, readOp("e1")) c.Assert(err, gc.IsNil) m1.M().AddFirstPartyCaveat("true 1") m1.M().AddFirstPartyCaveat("true 2") m2, err := newClient(locator).capability(asUser("bob"), ts, readOp("e2")) c.Assert(err, gc.IsNil) m2.M().AddFirstPartyCaveat("true 3") m2.M().AddFirstPartyCaveat("true 4") client := newClient(locator) client.addMacaroon(ts, "authz1", macaroon.Slice{m1.M()}) client.addMacaroon(ts, "authz2", macaroon.Slice{m2.M()}) m, err := client.capability(testContext, ts, readOp("e1"), readOp("e2")) c.Assert(err, gc.IsNil) c.Assert(macaroonConditions(m.M().Caveats(), false), jc.DeepEquals, []string{ "true 1", "true 2", "true 3", "true 4", }) } var firstPartyCaveatSquashingTests = []struct { about string caveats []checkers.Caveat expect []checkers.Caveat }{{ about: "duplicates removed", caveats: []checkers.Caveat{ trueCaveat("1"), trueCaveat("2"), trueCaveat("1"), trueCaveat("2"), trueCaveat("3"), }, expect: []checkers.Caveat{ trueCaveat("1"), trueCaveat("2"), trueCaveat("3"), }, }, { about: "earliest time before", caveats: []checkers.Caveat{ checkers.TimeBeforeCaveat(epoch.Add(24 * time.Hour)), trueCaveat("1"), checkers.TimeBeforeCaveat(epoch.Add(1 * time.Hour)), checkers.TimeBeforeCaveat(epoch.Add(5 * time.Minute)), }, expect: []checkers.Caveat{ checkers.TimeBeforeCaveat(epoch.Add(5 * time.Minute)), trueCaveat("1"), }, }, { about: "operations and declared caveats removed", caveats: []checkers.Caveat{ checkers.DenyCaveat("foo"), checkers.AllowCaveat("read", "write"), checkers.DeclaredCaveat("username", "bob"), trueCaveat("1"), }, expect: []checkers.Caveat{ trueCaveat("1"), }, }} func (s *checkerSuite) TestFirstPartyCaveatSquashing(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"alice"}, readOp("e2"): {"alice"}} ts := newService(auth, ids, locator) for i, test := range firstPartyCaveatSquashingTests { c.Logf("test %d: %v", i, test.about) // Make a first macaroon with all the required first party caveats. m1, err := newClient(locator).capability(asUser("alice"), ts, readOp("e1")) c.Assert(err, gc.IsNil) err = m1.AddCaveats(testContext, test.caveats, nil, nil) c.Assert(err, gc.IsNil) // Make a second macaroon that's not used to check that it's // caveats are not added. m2, err := newClient(locator).capability(asUser("alice"), ts, readOp("e2")) c.Assert(err, gc.IsNil) err = m2.AddCaveat(testContext, trueCaveat("notused"), nil, nil) c.Assert(err, gc.IsNil) client := newClient(locator) client.addMacaroon(ts, "authz1", macaroon.Slice{m1.M()}) client.addMacaroon(ts, "authz2", macaroon.Slice{m2.M()}) m3, err := client.capability(testContext, ts, readOp("e1")) c.Assert(err, gc.IsNil) c.Assert(macaroonConditions(m3.M().Caveats(), false), jc.DeepEquals, resolveCaveats(m3.Namespace(), test.expect)) } } func (s *checkerSuite) TestLoginOnly(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := bakery.ClosedAuthorizer ts := newService(auth, ids, locator) authInfo, err := newClient(locator).do(asUser("bob"), ts, bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("bob")) } func (s *checkerSuite) TestAllowAny(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"alice"}, readOp("e2"): {"bob"}} ts := newService(auth, ids, locator) // Acquire a capability for e1 but rely on authentication to // authorize e2. m, err := newClient(locator).dischargedCapability(asUser("alice"), ts, readOp("e1")) c.Assert(err, gc.IsNil) client := newClient(locator) client.addMacaroon(ts, "authz", m) s.discharges = nil authInfo, allowed, err := client.doAny(asUser("bob"), ts, readOp("e1"), readOp("e2"), bakery.LoginOp) c.Assert(err, gc.ErrorMatches, `discharge required`) c.Assert(authInfo, gc.NotNil) c.Check(authInfo.Macaroons, gc.HasLen, 1) c.Check(allowed, jc.DeepEquals, []bool{true, false, false}) c.Assert(s.discharges, gc.HasLen, 0) // We shouldn't have discharged. // Log in as bob. _, err = client.do(asUser("bob"), ts, bakery.LoginOp) c.Assert(err, gc.IsNil) // All the previous actions should now be allowed. authInfo, allowed, err = client.doAny(asUser("bob"), ts, readOp("e1"), readOp("e2"), bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("bob")) c.Assert(authInfo.Macaroons, gc.HasLen, 2) c.Assert(allowed, jc.DeepEquals, []bool{true, true, true}) } func (s *checkerSuite) TestAllowed(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{ readOp("e1"): {"alice"}, readOp("e2"): {"alice"}, readOp("e3"): {"alice"}, } ts := newService(auth, ids, locator) // Get two capabilities with overlapping operations. client := newClient(locator) m1, err := client.dischargedCapability(asUser("alice"), ts, readOp("e1"), readOp("e2")) c.Assert(err, gc.IsNil) m2, err := client.dischargedCapability(asUser("alice"), ts, readOp("e2"), readOp("e3")) c.Assert(err, gc.IsNil) authInfo, ops, err := ts.checker.Auth(m1, m2).Allowed(context.Background()) c.Assert(err, gc.IsNil) c.Assert(ops, jc.DeepEquals, map[bakery.Op]bool{ readOp("e1"): true, readOp("e2"): true, readOp("e3"): true, }) c.Assert(authInfo.Identity, gc.Equals, nil) c.Assert(authInfo.Macaroons, gc.HasLen, 2) // Try again but including the authentication macaroon from the client too. mss := append(client.requestMacaroons(ts), m1, m2) authInfo, ops, err = ts.checker.Auth(mss...).Allowed(context.Background()) c.Assert(err, gc.IsNil) c.Assert(ops, jc.DeepEquals, map[bakery.Op]bool{ readOp("e1"): true, readOp("e2"): true, readOp("e3"): true, bakery.LoginOp: true, }) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("alice")) c.Assert(authInfo.Macaroons, gc.HasLen, 3) } func (s *checkerSuite) TestAuthWithIdentityFromContext(c *gc.C) { locator := make(dischargerLocator) ids := basicAuthIdService{} auth := opACL{readOp("e1"): {"sherlock"}, readOp("e2"): {"bob"}} ts := newService(auth, ids, locator) // Check that we can perform the ops with basic auth in the // context. authInfo, err := newClient(locator).do(contextWithBasicAuth(testContext, "sherlock", "holmes"), ts, readOp("e1")) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("sherlock")) c.Assert(authInfo.Macaroons, gc.HasLen, 0) } func (s *checkerSuite) TestAuthLoginOpWithIdentityFromContext(c *gc.C) { locator := make(dischargerLocator) ids := basicAuthIdService{} ts := newService(nil, ids, locator) // Check that we can use LoginOp when auth isn't granted through macaroons. authInfo, err := newClient(locator).do(contextWithBasicAuth(testContext, "sherlock", "holmes"), ts, bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("sherlock")) c.Assert(authInfo.Macaroons, gc.HasLen, 0) } func (s *checkerSuite) TestOperationAllowCaveat(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"bob"}, writeOp("e1"): {"bob"}, readOp("e2"): {"bob"}} ts := newService(auth, ids, locator) client := newClient(locator) m, err := client.capability(asUser("bob"), ts, readOp("e1"), writeOp("e1"), readOp("e2")) c.Assert(err, gc.IsNil) // Sanity check that we can do a write. _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, writeOp("e1")) c.Assert(err, gc.IsNil) err = m.AddCaveat(testContext, checkers.AllowCaveat("read"), nil, nil) c.Assert(err, gc.IsNil) // A read operation should work. _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, readOp("e1"), readOp("e2")) c.Assert(err, gc.IsNil) // A write operation should fail even though the original macaroon allowed it. _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, writeOp("e1")) c.Assert(err, gc.ErrorMatches, `discharge required`) } func (s *checkerSuite) TestOperationDenyCaveat(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := opACL{readOp("e1"): {"bob"}, writeOp("e1"): {"bob"}, readOp("e2"): {"bob"}} ts := newService(auth, ids, locator) client := newClient(locator) m, err := client.capability(asUser("bob"), ts, readOp("e1"), writeOp("e1"), readOp("e2")) c.Assert(err, gc.IsNil) // Sanity check that we can do a write. _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, writeOp("e1")) c.Assert(err, gc.IsNil) err = m.AddCaveat(testContext, checkers.DenyCaveat("write"), nil, nil) c.Assert(err, gc.IsNil) // A read operation should work. _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, readOp("e1"), readOp("e2")) c.Assert(err, gc.IsNil) // A write operation should fail even though the original macaroon allowed it. _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, writeOp("e1")) c.Assert(err, gc.ErrorMatches, `discharge required`) } func (s *checkerSuite) TestAllowWithOpsAuthorizer(c *gc.C) { locator := make(dischargerLocator) store := newMacaroonStore(mustGenerateKey(), locator) ts := &service{ // Note: we're making a checker with no Authorizer and no IdentityClient. checker: bakery.NewChecker(bakery.CheckerParams{ Checker: testChecker, OpsAuthorizer: hierarchicalOpsAuthorizer{}, MacaroonOpStore: store, }), store: store, } // Manufacture a macaroon granting access to /user/bob and // everything underneath it (by virtue of the hierarchicalOpsAuthorizer). m, err := ts.store.NewMacaroon(testContext, []bakery.Op{{ Entity: "path-/user/bob", Action: "*", }}, nil, ts.checker.Namespace()) c.Assert(err, gc.Equals, nil) // Check that we can do some operation. _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, writeOp("path-/user/bob/foo")) c.Assert(err, gc.Equals, nil) // Check that we can't do an operation on an entity outside the // original operation's purview. _, err = ts.do(testContext, []macaroon.Slice{{m.M()}}, writeOp("path-/user/alice")) c.Assert(err, gc.ErrorMatches, `permission denied`) } func (s *checkerSuite) TestAllowAnyWithOpsAuthorizer(c *gc.C) { locator := make(dischargerLocator) store := newMacaroonStore(mustGenerateKey(), locator) ts := &service{ // Note: we're making a checker with no Authorizer and no IdentityClient. checker: bakery.NewChecker(bakery.CheckerParams{ Checker: testChecker, OpsAuthorizer: hierarchicalOpsAuthorizer{}, MacaroonOpStore: store, }), store: store, } // Manufacture a macaroon granting read-only access to /user/bob and // everything underneath it (by virtue of the hierarchicalOpsAuthorizer). m, err := ts.store.NewMacaroon(testContext, []bakery.Op{{ Entity: "path-/user/bob", Action: "read", }}, nil, ts.checker.Namespace()) c.Assert(err, gc.Equals, nil) ai, allowed, err := ts.doAny(testContext, []macaroon.Slice{{m.M()}}, writeOp("path-/user/bob"), readOp("path-/user/bob"), readOp("path-/user/bob/foo"), readOp("other"), ) c.Check(err, gc.ErrorMatches, `permission denied`) c.Check(allowed, jc.DeepEquals, []bool{false, true, true, false}) c.Check(ai.Identity, gc.Equals, nil) c.Check(ai.Macaroons, gc.HasLen, 1) } func (s *checkerSuite) TestAllowAnyWithOpsAuthorizerAndMultipleMacaroons(c *gc.C) { locator := make(dischargerLocator) store := newMacaroonStore(mustGenerateKey(), locator) ts := &service{ // Note: we're making a checker with no Authorizer and no IdentityClient. checker: bakery.NewChecker(bakery.CheckerParams{ Checker: testChecker, OpsAuthorizer: hierarchicalOpsAuthorizer{}, MacaroonOpStore: store, }), store: store, } m1, err := ts.store.NewMacaroon(testContext, []bakery.Op{{ Entity: "path-/user/bob", Action: "read", }}, nil, ts.checker.Namespace()) c.Assert(err, gc.Equals, nil) m2, err := ts.store.NewMacaroon(testContext, []bakery.Op{{ Entity: "path-/user/alice", Action: "*", }}, nil, ts.checker.Namespace()) c.Assert(err, gc.Equals, nil) ai, allowed, err := ts.doAny(testContext, []macaroon.Slice{{m1.M()}, {m2.M()}}, writeOp("path-/user/bob"), readOp("path-/user/alice/foo"), writeOp("path-/user/alice/bar"), readOp("path-/user/bob/foo"), readOp("path-/"), ) c.Check(err, gc.ErrorMatches, `permission denied`) c.Check(allowed, jc.DeepEquals, []bool{false, true, true, true, false}) c.Check(ai.Identity, gc.Equals, nil) c.Check(ai.Macaroons, gc.HasLen, 2) // Check with all operations authorized so that we can cover the // return-early-when-all-OK path in checkIndirect. ai, allowed, err = ts.doAny(testContext, []macaroon.Slice{{m1.M()}, {m2.M()}}, readOp("path-/user/bob"), readOp("path-/user/bob/foo"), ) c.Check(err, gc.Equals, nil) c.Check(allowed, gc.IsNil) c.Check(ai.Identity, gc.Equals, nil) c.Check(ai.Macaroons, gc.HasLen, 1) } func (s *checkerSuite) TestDuplicateLoginMacaroons(c *gc.C) { locator := make(dischargerLocator) ids := s.newIdService("ids", locator) auth := bakery.ClosedAuthorizer ts := newService(auth, ids, locator) // Acquire a login macaroon for bob. client1 := newClient(locator) authInfo, err := client1.do(asUser("bob"), ts, bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("bob")) // Acquire a login macaroon for alice. client2 := newClient(locator) authInfo, err = client2.do(asUser("alice"), ts, bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("alice")) // Combine the two login macaroons into one client. client3 := newClient(locator) client3.addMacaroon(ts, "1.bob", client1.macaroons[ts]["authn"]) client3.addMacaroon(ts, "2.alice", client2.macaroons[ts]["authn"]) // We should authenticate as bob (because macaroons are presented ordered // by "cookie" name) authInfo, err = client3.do(testContext, ts, bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("bob")) c.Assert(authInfo.Macaroons, gc.HasLen, 1) // Try them the other way around and we should authenticate as alice. client3 = newClient(locator) client3.addMacaroon(ts, "1.alice", client2.macaroons[ts]["authn"]) client3.addMacaroon(ts, "2.bob", client1.macaroons[ts]["authn"]) authInfo, err = client3.do(testContext, ts, bakery.LoginOp) c.Assert(err, gc.IsNil) c.Assert(authInfo.Identity, gc.Equals, bakery.SimpleIdentity("alice")) c.Assert(authInfo.Macaroons, gc.HasLen, 1) } func (s *checkerSuite) TestMacaroonOpsFatalError(c *gc.C) { // When we get a non-VerificationError error from the // opstore, we don't do any more verification. checker := bakery.NewChecker(bakery.CheckerParams{ MacaroonOpStore: macaroonStoreWithError{errgo.New("an error")}, }) m, err := macaroon.New(nil, nil, "", macaroon.V2) c.Assert(err, gc.IsNil) _, err = checker.Auth(macaroon.Slice{m}).Allow(testContext, bakery.LoginOp) c.Assert(err, gc.ErrorMatches, `cannot retrieve macaroon: an error`) } // resolveCaveats resolves all the given caveats with the // given namespace and includes the condition // from each one. It will panic if it finds a third party caveat. func resolveCaveats(ns *checkers.Namespace, caveats []checkers.Caveat) []string { conds := make([]string, len(caveats)) for i, cav := range caveats { if cav.Location != "" { panic("found unexpected third party caveat") } conds[i] = ns.ResolveCaveat(cav).Condition } return conds } func macaroonConditions(caveats []macaroon.Caveat, allowThird bool) []string { conds := make([]string, len(caveats)) for i, cav := range caveats { if cav.Location != "" { if !allowThird { panic("found unexpected third party caveat") } continue } conds[i] = string(cav.Id) } return conds } func firstPartyMacaroonCaveats(conds ...string) []macaroon.Caveat { caveats := make([]macaroon.Caveat, len(conds)) for i, cond := range conds { caveats[i].Id = []byte(cond) } return caveats } func readOp(entity string) bakery.Op { return bakery.Op{ Entity: entity, Action: "read", } } func writeOp(entity string) bakery.Op { return bakery.Op{ Entity: entity, Action: "write", } } // opACL implements bakery.Authorizer by looking the operation // up in the given map. If the username is in the associated slice // or the slice contains "everyone", authorization is granted. type opACL map[bakery.Op][]string func (auth opACL) Authorize(ctx context.Context, id bakery.Identity, ops []bakery.Op) (allowed []bool, caveats []checkers.Caveat, err error) { return bakery.ACLAuthorizer{ GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) { return auth[op], true, nil }, }.Authorize(ctx, id, ops) } type idService struct { location string *discharger suite *checkerSuite } func (s *checkerSuite) newIdService(location string, locator dischargerLocator) *idService { ids := &idService{ location: location, suite: s, } key := mustGenerateKey() ids.discharger = &discharger{ key: key, checker: ids, locator: locator, } locator[location] = ids.discharger return ids } func (ids *idService) CheckThirdPartyCaveat(ctx context.Context, info *bakery.ThirdPartyCaveatInfo) ([]checkers.Caveat, error) { if string(info.Condition) != "is-authenticated-user" { return nil, errgo.Newf("third party condition not recognized") } username := dischargeUserFromContext(ctx) if username == "" { return nil, errgo.Newf("no current user") } ids.suite.discharges = append(ids.suite.discharges, dischargeRecord{ location: ids.location, user: username, }) return []checkers.Caveat{ checkers.DeclaredCaveat("username", username), }, nil } func (ids *idService) IdentityFromContext(ctx context.Context) (bakery.Identity, []checkers.Caveat, error) { return nil, []checkers.Caveat{{ Location: ids.location, Condition: "is-authenticated-user", }}, nil } func (ids *idService) DeclaredIdentity(ctx context.Context, declared map[string]string) (bakery.Identity, error) { user, ok := declared["username"] if !ok { return nil, errgo.Newf("no username declared") } return bakery.SimpleIdentity(user), nil } type dischargeUserKey struct{} func contextWithDischargeUser(ctx context.Context, username string) context.Context { return context.WithValue(ctx, dischargeUserKey{}, username) } func dischargeUserFromContext(ctx context.Context) string { username, _ := ctx.Value(dischargeUserKey{}).(string) return username } type basicAuthIdService struct{} func (basicAuthIdService) IdentityFromContext(ctx context.Context) (bakery.Identity, []checkers.Caveat, error) { user, pass := basicAuthFromContext(ctx) if user != "sherlock" || pass != "holmes" { return nil, nil, nil } return bakery.SimpleIdentity(user), nil, nil } func (basicAuthIdService) DeclaredIdentity(ctx context.Context, declared map[string]string) (bakery.Identity, error) { return nil, errgo.Newf("no identity declarations in basic auth id service") } // service represents a service that requires authorization. // Clients can make requests to the service to perform operations // and may receive a macaroon to discharge if the authorization // process requires it. type service struct { checker *bakery.Checker store *macaroonStore } func newService(auth bakery.Authorizer, idm bakery.IdentityClient, locator bakery.ThirdPartyLocator) *service { store := newMacaroonStore(mustGenerateKey(), locator) return &service{ checker: bakery.NewChecker(bakery.CheckerParams{ Checker: testChecker, Authorizer: auth, IdentityClient: idm, MacaroonOpStore: store, }), store: store, } } // do makes a request to the service to perform the given operations // using the given macaroons for authorization. // It may return a dischargeRequiredError containing a macaroon // that needs to be discharged. func (svc *service) do(ctx context.Context, ms []macaroon.Slice, ops ...bakery.Op) (*bakery.AuthInfo, error) { authInfo, err := svc.checker.Auth(ms...).Allow(ctx, ops...) return authInfo, svc.maybeDischargeRequiredError(err) } // doAny makes a request to the service to perform any of the given // operations. It reports which operations have succeeded. func (svc *service) doAny(ctx context.Context, ms []macaroon.Slice, ops ...bakery.Op) (*bakery.AuthInfo, []bool, error) { authInfo, allowed, err := svc.checker.Auth(ms...).AllowAny(ctx, ops...) return authInfo, allowed, svc.maybeDischargeRequiredError(err) } func (svc *service) capability(ctx context.Context, ms []macaroon.Slice, ops ...bakery.Op) (*bakery.Macaroon, error) { conds, err := svc.checker.Auth(ms...).AllowCapability(ctx, ops...) if err != nil { return nil, svc.maybeDischargeRequiredError(err) } m, err := svc.store.NewMacaroon(ctx, ops, nil, svc.checker.Namespace()) if err != nil { return nil, errgo.Mask(err) } for _, cond := range conds { if err := m.M().AddFirstPartyCaveat(cond); err != nil { return nil, errgo.Mask(err) } } return m, nil } func (svc *service) maybeDischargeRequiredError(err error) error { derr, ok := errgo.Cause(err).(*bakery.DischargeRequiredError) if !ok { return errgo.Mask(err) } m, err := svc.store.NewMacaroon(testContext, derr.Ops, derr.Caveats, svc.checker.Namespace()) if err != nil { return errgo.Mask(err) } name := "authz" if len(derr.Ops) == 1 && derr.Ops[0] == bakery.LoginOp { name = "authn" } return &dischargeRequiredError{ name: name, m: m, } } type discharger struct { key *bakery.KeyPair locator bakery.ThirdPartyLocator checker bakery.ThirdPartyCaveatChecker } type dischargeRequiredError struct { name string m *bakery.Macaroon } func (*dischargeRequiredError) Error() string { return "discharge required" } func (d *discharger) discharge(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { m, err := bakery.Discharge(ctx, bakery.DischargeParams{ Id: cav.Id, Caveat: payload, Key: d.key, Checker: d.checker, Locator: d.locator, }) if err != nil { return nil, errgo.Mask(err) } return m, nil } type dischargerLocator map[string]*discharger // ThirdPartyInfo implements the bakery.ThirdPartyLocator interface. func (l dischargerLocator) ThirdPartyInfo(ctx context.Context, loc string) (bakery.ThirdPartyInfo, error) { d, ok := l[loc] if !ok { return bakery.ThirdPartyInfo{}, bakery.ErrNotFound } return bakery.ThirdPartyInfo{ PublicKey: d.key.Public, Version: bakery.LatestVersion, }, nil } type hierarchicalOpsAuthorizer struct{} func (a hierarchicalOpsAuthorizer) AuthorizeOps(ctx context.Context, authorizedOp bakery.Op, queryOps []bakery.Op) ([]bool, error) { ok := make([]bool, len(queryOps)) for i, op := range queryOps { if isParentPathEntity(authorizedOp.Entity, op.Entity) && (authorizedOp.Action == op.Action || authorizedOp.Action == "*") { ok[i] = true } } return ok, nil } // isParentPathEntity reports whether both entity1 and entity2 // represent paths and entity1 is a parent of entity2. func isParentPathEntity(entity1, entity2 string) bool { path1, path2 := strings.TrimPrefix(entity1, "path-"), strings.TrimPrefix(entity2, "path-") if len(path1) == len(entity1) || len(path2) == len(entity2) { return false } if !strings.HasPrefix(path2, path1) { return false } if len(path1) == len(path2) { return true } return path2[len(path1)] == '/' } type client struct { key *bakery.KeyPair macaroons map[*service]map[string]macaroon.Slice dischargers dischargerLocator } func newClient(dischargers dischargerLocator) *client { return &client{ key: mustGenerateKey(), dischargers: dischargers, // macaroons holds the macaroons applicable to each service. // This is the test equivalent of the cookie jar used by httpbakery. macaroons: make(map[*service]map[string]macaroon.Slice), } } const maxRetries = 3 // do performs a set of operations on the given service. // It includes all the macaroons in c.macaroons[svc] as authorization // information on the request. func (c *client) do(ctx context.Context, svc *service, ops ...bakery.Op) (*bakery.AuthInfo, error) { var authInfo *bakery.AuthInfo err := c.doFunc(ctx, svc, func(ms []macaroon.Slice) (err error) { authInfo, err = svc.do(ctx, ms, ops...) return }) return authInfo, err } func (c *client) doAny(ctx context.Context, svc *service, ops ...bakery.Op) (*bakery.AuthInfo, []bool, error) { return svc.doAny(ctx, c.requestMacaroons(svc), ops...) } // capability returns a capability macaroon for the given operations. func (c *client) capability(ctx context.Context, svc *service, ops ...bakery.Op) (*bakery.Macaroon, error) { var m *bakery.Macaroon err := c.doFunc(ctx, svc, func(ms []macaroon.Slice) (err error) { m, err = svc.capability(ctx, ms, ops...) return }) return m, err } func (c *client) dischargedCapability(ctx context.Context, svc *service, ops ...bakery.Op) (macaroon.Slice, error) { m, err := c.capability(ctx, svc, ops...) if err != nil { return nil, errgo.Mask(err) } return c.dischargeAll(ctx, m) } func (c *client) doFunc(ctx context.Context, svc *service, f func(ms []macaroon.Slice) error) error { for i := 0; i < maxRetries; i++ { err := f(c.requestMacaroons(svc)) derr, ok := errgo.Cause(err).(*dischargeRequiredError) if !ok { return err } ms, err := c.dischargeAll(ctx, derr.m) if err != nil { return errgo.Mask(err) } c.addMacaroon(svc, derr.name, ms) } return errgo.New("discharge failed too many times") } func (c *client) clearMacaroons(svc *service) { if svc == nil { c.macaroons = make(map[*service]map[string]macaroon.Slice) return } delete(c.macaroons, svc) } func (c *client) addMacaroon(svc *service, name string, m macaroon.Slice) { if c.macaroons[svc] == nil { c.macaroons[svc] = make(map[string]macaroon.Slice) } c.macaroons[svc][name] = m } func (c *client) requestMacaroons(svc *service) []macaroon.Slice { mmap := c.macaroons[svc] // Put all the macaroons in the slice ordered by key // so that we have deterministic behaviour in the tests. names := make([]string, 0, len(mmap)) for name := range mmap { names = append(names, name) } sort.Strings(names) ms := make([]macaroon.Slice, len(names)) for i, name := range names { logger.Infof("macaroon %d: %v", i, name) ms[i] = mmap[name] } return ms } func (c *client) dischargeAll(ctx context.Context, m *bakery.Macaroon) (macaroon.Slice, error) { return bakery.DischargeAll(ctx, m, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) { d := c.dischargers[cav.Location] if d == nil { return nil, errgo.Newf("third party discharger %q not found", cav.Location) } return d.discharge(ctx, cav, payload) }) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/checker.go��������������������������0000644�0610621�0607500�00000047566�13172163311�027401� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "sort" "sync" "time" "golang.org/x/net/context" errgo "gopkg.in/errgo.v1" macaroon "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // LoginOp represents a login (authentication) operation. // A macaroon that is associated with this operation generally // carries authentication information with it. var LoginOp = Op{ Entity: "login", Action: "login", } // Op holds an entity and action to be authorized on that entity. type Op struct { // Entity holds the name of the entity to be authorized. // Entity names should not contain spaces and should // not start with the prefix "login" or "multi-" (conventionally, // entity names will be prefixed with the entity type followed // by a hyphen. Entity string // Action holds the action to perform on the entity, such as "read" // or "delete". It is up to the service using a checker to define // a set of operations and keep them consistent over time. Action string } // CheckerParams holds parameters for NewChecker. type CheckerParams struct { // CaveatChecker is used to check first party caveats when authorizing. // If this is nil NewChecker will use checkers.New(nil). Checker FirstPartyCaveatChecker // Authorizer is used to check whether an authenticated user is // allowed to perform operations. If it is nil, NewChecker will // use ClosedAuthorizer. // // The identity parameter passed to Authorizer.Allow will // always have been obtained from a call to // IdentityClient.DeclaredIdentity. Authorizer Authorizer // OpsAuthorizer is used to check whether operations are authorized // by some other already-authorized operation. If it is nil, // NewChecker will assume no operation is authorized by any // operation except itself. OpsAuthorizer OpsAuthorizer // IdentityClient is used for interactions with the external // identity service used for authentication. // // If this is nil, no authentication will be possible. IdentityClient IdentityClient // MacaroonOps is used to retrieve macaroon root keys // and other associated information. MacaroonOpStore MacaroonOpStore } // AuthInfo information about an authorization decision. type AuthInfo struct { // Identity holds information on the authenticated user as returned // from IdentityClient. It may be nil after a // successful authorization if LoginOp access was not required. Identity Identity // Macaroons holds all the macaroons that were used for the // authorization. Macaroons that were invalid or unnecessary are // not included. Macaroons []macaroon.Slice // TODO add information on user ids that have contributed // to the authorization: // After a successful call to Authorize or Capability, // AuthorizingUserIds returns the user ids that were used to // create the capability macaroons used to authorize the call. // Note that this is distinct from UserId, as there can only be // one authenticated user associated with the checker. // AuthorizingUserIds []string } // Checker wraps a FirstPartyCaveatChecker and adds authentication and authorization checks. // // It uses macaroons as authorization tokens but it is not itself responsible for // creating the macaroons - see the Oven type (TODO) for one way of doing that. type Checker struct { FirstPartyCaveatChecker p CheckerParams } // NewChecker returns a new Checker using the given parameters. func NewChecker(p CheckerParams) *Checker { if p.Checker == nil { p.Checker = checkers.New(nil) } if p.Authorizer == nil { p.Authorizer = ClosedAuthorizer } if p.IdentityClient == nil { p.IdentityClient = noIdentities{} } return &Checker{ FirstPartyCaveatChecker: p.Checker, p: p, } } // Auth makes a new AuthChecker instance using the // given macaroons to inform authorization decisions. func (c *Checker) Auth(mss ...macaroon.Slice) *AuthChecker { return &AuthChecker{ Checker: c, macaroons: mss, } } // AuthChecker authorizes operations with respect to a user's request. // The identity is authenticated only once, the first time any method // of the AuthChecker is called, using the context passed in then. // // To find out any declared identity without requiring a login, // use Allow(ctx); to require authentication but no additional operations, // use Allow(ctx, LoginOp). type AuthChecker struct { // Checker is used to check first party caveats. *Checker macaroons []macaroon.Slice // conditions holds the first party caveat conditions // that apply to each of the above macaroons. conditions [][]string initOnce sync.Once initError error initErrors []error identity Identity identityCaveats []checkers.Caveat // authIndexes holds for each potentially authorized operation // the indexes of the macaroons that authorize it. authIndexes map[Op][]int } func (a *AuthChecker) init(ctx context.Context) error { a.initOnce.Do(func() { a.initError = a.initOnceFunc(ctx) }) return a.initError } func (a *AuthChecker) initOnceFunc(ctx context.Context) error { a.authIndexes = make(map[Op][]int) a.conditions = make([][]string, len(a.macaroons)) for i, ms := range a.macaroons { ops, conditions, err := a.p.MacaroonOpStore.MacaroonOps(ctx, ms) if err != nil { if !isVerificationError(err) { return errgo.Notef(err, "cannot retrieve macaroon") } a.initErrors = append(a.initErrors, errgo.Mask(err)) continue } logger.Debugf("checking macaroon %d; ops %q, conditions %q", i, ops, conditions) // It's a valid macaroon (in principle - we haven't checked first party caveats). a.conditions[i] = conditions isLogin := false for _, op := range ops { if op == LoginOp { // Don't associate the macaroon with the login operation // until we've verified that it is valid below isLogin = true } else { a.authIndexes[op] = append(a.authIndexes[op], i) } } if !isLogin { continue } // It's a login macaroon. Check the conditions now - // all calls want to see the same authentication // information so that callers have a consistent idea of // the client's identity. // // If the conditions fail, we won't use the macaroon for // identity, but we can still potentially use it for its // other operations if the conditions succeed for those. declared, err := a.checkConditions(ctx, LoginOp, conditions) if err != nil { a.initErrors = append(a.initErrors, errgo.Notef(err, "cannot authorize login macaroon")) continue } if a.identity != nil { // We've already found a login macaroon so ignore this one // for the purposes of identity. continue } identity, err := a.p.IdentityClient.DeclaredIdentity(ctx, declared) if err != nil { a.initErrors = append(a.initErrors, errgo.Notef(err, "cannot decode declared identity: %v", err)) continue } a.authIndexes[LoginOp] = append(a.authIndexes[LoginOp], i) a.identity = identity } if a.identity == nil { // No identity yet, so try to get one based on the context. identity, caveats, err := a.p.IdentityClient.IdentityFromContext(ctx) if err != nil { a.initErrors = append(a.initErrors, errgo.Notef(err, "could not determine identity")) } a.identity, a.identityCaveats = identity, caveats } logger.Infof("after init, identity: %#v, authIndexes %v; errors %q", a.identity, a.authIndexes, a.initErrors) return nil } // Allow checks that the authorizer's request is authorized to // perform all the given operations. Note that Allow does not check // first party caveats - if there is more than one macaroon that may // authorize the request, it will choose the first one that does regardless // // If all the operations are allowed, an AuthInfo is returned holding // details of the decision and any first party caveats that must be // checked before actually executing any operation. // // If operations include LoginOp, the request should contain an // authentication macaroon proving the client's identity. Once an // authentication macaroon is chosen, it will be used for all other // authorization requests. // // If an operation was not allowed, an error will be returned which may // be *DischargeRequiredError holding the operations that remain to // be authorized in order to allow authorization to // proceed. func (a *AuthChecker) Allow(ctx context.Context, ops ...Op) (*AuthInfo, error) { authInfo, _, err := a.AllowAny(ctx, ops...) if err != nil { return nil, err } return authInfo, nil } // AllowAny is like Allow except that it will authorize as many of the // operations as possible without requiring any to be authorized. If all // the operations succeeded, the returned error and slice will be nil. // // If any the operations failed, the returned error will be the same // that Allow would return and each element in the returned slice will // hold whether its respective operation was allowed. // // If all the operations succeeded, the returned slice will be nil. // // The returned *AuthInfo will always be non-nil. // // The LoginOp operation is treated specially - it is always required if // present in ops. func (a *AuthChecker) AllowAny(ctx context.Context, ops ...Op) (*AuthInfo, []bool, error) { authed, used, err := a.allowAny(ctx, ops) return a.newAuthInfo(used), authed, err } // Allowed returns all the operations allowed by the provided macaroons // as keys in the returned map (all the associated values will be true). // Note that this does not include operations that would be indirectly // allowed via the OpAuthorizer. // // It also returns the AuthInfo (always non-nil) similarly to AllowAny. // // Allowed returns an error only when there is an underlying storage failure, // not when operations are not authorized. func (a *AuthChecker) Allowed(ctx context.Context) (*AuthInfo, map[Op]bool, error) { used := make([]bool, len(a.macaroons)) if err := a.init(ctx); err != nil { return a.newAuthInfo(used), nil, errgo.Mask(err) } ops := make(map[Op]bool) // TODO this is non-deterministic; perhaps we should sort the // operations before ranging over them? for op, indexes := range a.authIndexes { for _, mindex := range indexes { _, err := a.checkConditions(ctx, op, a.conditions[mindex]) if err == nil { used[mindex] = true ops[op] = true break } } } return a.newAuthInfo(used), ops, nil } func (a *AuthChecker) newAuthInfo(used []bool) *AuthInfo { info := &AuthInfo{ Identity: a.identity, Macaroons: make([]macaroon.Slice, 0, len(a.macaroons)), } for i, isUsed := range used { if isUsed { info.Macaroons = append(info.Macaroons, a.macaroons[i]) } } return info } // allowContext holds temporary state used by AuthChecker.allowAny. type allowContext struct { checker *AuthChecker // used holds which elements of the request macaroons // have been used by the authorization logic. used []bool // authed holds which of the requested operations have // been authorized so far. authed []bool // need holds all of the requested operations that // are remaining to be authorized. needIndex holds the // index of each of these operations in the original operations slice need []Op needIndex []int // errors holds any errors encountered during authorization. errors []error } // allowAny is the internal version of AllowAny. Instead of returning an // authInfo struct, it returns a slice describing which operations have // been successfully authorized and a slice describing which macaroons // have been used in the authorization. // If all operations were authorized, authed and err will be nil. func (a *AuthChecker) allowAny(ctx context.Context, ops []Op) (authed, used []bool, err error) { if err := a.init(ctx); err != nil { return nil, nil, errgo.Mask(err) } actx := &allowContext{ checker: a, used: make([]bool, len(a.macaroons)), authed: make([]bool, len(ops)), need: append([]Op(nil), ops...), needIndex: make([]int, len(ops)), } for i := range actx.needIndex { actx.needIndex[i] = i } actx.checkDirect(ctx) if len(actx.need) == 0 { return nil, actx.used, nil } actx.checkIndirect(ctx) if len(actx.need) == 0 { return nil, actx.used, nil } caveats, err := actx.checkWithAuthorizer(ctx) if err != nil { return actx.authed, actx.used, errgo.Mask(err) } if len(actx.need) == 0 && len(caveats) == 0 { // No more ops need to be authenticated and no caveats to be discharged. return actx.authed, actx.used, nil } logger.Debugf("operations still needed after auth check: %#v", actx.need) if a.identity == nil && len(a.identityCaveats) > 0 { return actx.authed, actx.used, &DischargeRequiredError{ Message: "authentication required", Ops: []Op{LoginOp}, Caveats: a.identityCaveats, } } if len(caveats) == 0 { allErrors := make([]error, 0, len(a.initErrors)+len(actx.errors)) allErrors = append(allErrors, a.initErrors...) allErrors = append(allErrors, actx.errors...) var err error if len(allErrors) > 0 { // TODO return all errors? logger.Infof("all auth errors: %q", allErrors) err = allErrors[0] } return actx.authed, actx.used, errgo.WithCausef(err, ErrPermissionDenied, "") } return actx.authed, actx.used, &DischargeRequiredError{ Message: "some operations have extra caveats", Ops: ops, Caveats: caveats, } } // checkDirect checks which operations are directly authorized by // the macaroon operations. func (a *allowContext) checkDirect(ctx context.Context) { defer a.updateNeed() for i, op := range a.need { authed := false for _, mindex := range a.checker.authIndexes[op] { _, err := a.checker.checkConditions(ctx, op, a.checker.conditions[mindex]) if err == nil { // Use the first authorized macaroon only. a.used[mindex] = true authed = true break } logger.Infof("condition check %q failed: %v", a.checker.conditions[mindex], err) a.addError(err) } // Allow LoginOp when there's an authenticated user even // when there's no macaroon that specifically authorizes it. authed = authed || (op == LoginOp && a.checker.identity != nil) if authed { a.authed[a.needIndex[i]] = true } } if a.checker.identity == nil { return } // We've authenticated as a user, so even if the operations didn't // specifically require it, we add the login macaroon // to the macaroons used. // Note that the LoginOp conditions have already been checked // successfully in initOnceFunc so no need to check again. // Note also that there may not be any macaroons if the // identity client decided on an identity even with no // macaroons. for _, i := range a.checker.authIndexes[LoginOp] { a.used[i] = true } } // checkIndirect checks to see if any of the remaining operations are authorized // indirectly with the already-authorized operations. func (a *allowContext) checkIndirect(ctx context.Context) { if a.checker.p.OpsAuthorizer == nil { return } for op, mindexes := range a.checker.authIndexes { if len(a.need) == 0 { return } authedOK, err := a.checker.p.OpsAuthorizer.AuthorizeOps(ctx, op, a.need) if err != nil { // TODO this probably means "can't check" rather than "authorization denied"; // perhaps we should return rather than carrying on? a.addError(err) continue } for i, ok := range authedOK { if !ok { continue } // This operation is potentially authorized. See whether we have a macaroon // that actually allows this operation. for _, mindex := range mindexes { if _, err := a.checker.checkConditions(ctx, a.need[i], a.checker.conditions[mindex]); err != nil { a.addError(err) continue } // Operation is authorized. Mark the appropriate macaroon as used, // and remove the operation from the needed list so that we don't // bother AuthorizeOps with it again. a.used[mindex] = true a.authed[a.needIndex[i]] = true } } a.updateNeed() } } // checkWithAuthorizer checks which operations are authorized by the // Authorizer instance. We call Authorize even when we haven't got an // authenticated identity. func (a *allowContext) checkWithAuthorizer(ctx context.Context) ([]checkers.Caveat, error) { oks, caveats, err := a.checker.p.Authorizer.Authorize(ctx, a.checker.identity, a.need) if err != nil { // TODO if there are macaroons supplied that have failed, perhaps we shouldn't // do this but return those errors instead? Doing things the current // way means that we lose the previous errors. return nil, errgo.Notef(err, "cannot check permissions") } for i, ok := range oks { if ok { a.authed[a.needIndex[i]] = true } } a.updateNeed() return caveats, nil } // updateNeed removes all authorized operations from a.need // and updates a.needIndex appropriately too. func (a *allowContext) updateNeed() { j := 0 for i, opIndex := range a.needIndex { if a.authed[opIndex] { continue } if i != j { a.need[j], a.needIndex[j] = a.need[i], a.needIndex[i] } j++ } a.need, a.needIndex = a.need[0:j], a.needIndex[0:j] } func (a *allowContext) addError(err error) { a.errors = append(a.errors, err) } // AllowCapability checks that the user is allowed to perform all the // given operations. If not, the error will be as returned from Allow. // // If AllowCapability succeeds, it returns a list of first party caveat // conditions that must be applied to any macaroon granting capability // to execute the operations. Those caveat conditions will not // include any declarations contained in login macaroons - the // caller must be careful not to mint a macaroon associated // with the LoginOp operation unless they add the expected // declaration caveat too - in general, clients should not create capabilities // that grant LoginOp rights. // // The operations must include at least one non-LoginOp operation. func (a *AuthChecker) AllowCapability(ctx context.Context, ops ...Op) ([]string, error) { nops := 0 for _, op := range ops { if op != LoginOp { nops++ } } if nops == 0 { return nil, errgo.Newf("no non-login operations required in capability") } _, used, err := a.allowAny(ctx, ops) if err != nil { return nil, errgo.Mask(err, isDischargeRequiredError) } var squasher caveatSquasher for i, isUsed := range used { if !isUsed { continue } for _, cond := range a.conditions[i] { squasher.add(cond) } } return squasher.final(), nil } // caveatSquasher rationalizes first party caveats created for a capability // by: // - including only the earliest time-before caveat. // - excluding allow and deny caveats (operations are checked by // virtue of the operations associated with the macaroon). // - removing declared caveats. // - removing duplicates. type caveatSquasher struct { expiry time.Time conds []string } func (c *caveatSquasher) add(cond string) { if c.add0(cond) { c.conds = append(c.conds, cond) } } func (c *caveatSquasher) add0(cond string) bool { cond, args, err := checkers.ParseCaveat(cond) if err != nil { // Be safe - if we can't parse the caveat, just leave it there. return true } switch cond { case checkers.CondTimeBefore: et, err := time.Parse(time.RFC3339Nano, args) if err != nil || et.IsZero() { // Again, if it doesn't seem valid, leave it alone. return true } if c.expiry.IsZero() || et.Before(c.expiry) { c.expiry = et } return false case checkers.CondAllow, checkers.CondDeny, checkers.CondDeclared: return false } return true } func (c *caveatSquasher) final() []string { if !c.expiry.IsZero() { c.conds = append(c.conds, checkers.TimeBeforeCaveat(c.expiry).Condition) } if len(c.conds) == 0 { return nil } // Make deterministic and eliminate duplicates. sort.Strings(c.conds) prev := c.conds[0] j := 1 for _, cond := range c.conds[1:] { if cond != prev { c.conds[j] = cond prev = cond j++ } } c.conds = c.conds[:j] return c.conds } func (a *AuthChecker) checkConditions(ctx context.Context, op Op, conds []string) (map[string]string, error) { declared := checkers.InferDeclaredFromConditions(a.Namespace(), conds) ctx = checkers.ContextWithOperations(ctx, op.Action) ctx = checkers.ContextWithDeclared(ctx, declared) for _, cond := range conds { if err := a.CheckFirstPartyCaveat(ctx, cond); err != nil { return nil, errgo.Mask(err) } } return declared, nil } ������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/bakery.go���������������������������0000644�0610621�0607500�00000005756�13172163311�027245� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // Bakery is a convenience type that contains both an Oven // and a Checker. type Bakery struct { Oven *Oven Checker *Checker } // BakeryParams holds a selection of parameters for the Oven // and the Checker created by New. // // For more fine-grained control of parameters, create the // Oven or Checker directly. // // The zero value is OK to use, but won't allow any authentication // or third party caveats to be added. type BakeryParams struct { // Checker holds the checker used to check first party caveats. // If this is nil, New will use checkers.New(nil). Checker FirstPartyCaveatChecker // RootKeyStore holds the root key store to use. If you need to // use a different root key store for different operations, // you'll need to pass a RootKeyStoreForOps value to NewOven // directly. // // If this is nil, New will use NewMemRootKeyStore(). // Note that that is almost certain insufficient for production services // that are spread across multiple instances or that need // to persist keys across restarts. RootKeyStore RootKeyStore // Locator is used to find out information on third parties when // adding third party caveats. If this is nil, no non-local third // party caveats can be added. Locator ThirdPartyLocator // Key holds the private key of the oven. If this is nil, // no third party caveats may be added. Key *KeyPair // IdentityClient holds the identity implementation to use for // authentication. If this is nil, no authentication will be possible. IdentityClient IdentityClient // Authorizer is used to check whether an authenticated user is // allowed to perform operations. If it is nil, New will // use ClosedAuthorizer. // // The identity parameter passed to Authorizer.Allow will // always have been obtained from a call to // IdentityClient.DeclaredIdentity. Authorizer Authorizer // OpsStore is used to persistently store the association of // multi-op entities with their associated operations // when Oven.NewMacaroon is called with multiple operations. // // See OvenParams.OpsStore for details. OpsStore OpsStore // Location holds the location to use when creating new macaroons. Location string } // New returns a new Bakery instance which combines an Oven with a // Checker for the convenience of callers that wish to use both // together. func New(p BakeryParams) *Bakery { if p.Checker == nil { p.Checker = checkers.New(nil) } ovenParams := OvenParams{ Key: p.Key, Namespace: p.Checker.Namespace(), Location: p.Location, Locator: p.Locator, OpsStore: p.OpsStore, } if p.RootKeyStore != nil { ovenParams.RootKeyStoreForOps = func(ops []Op) RootKeyStore { return p.RootKeyStore } } oven := NewOven(ovenParams) checker := NewChecker(CheckerParams{ Checker: p.Checker, MacaroonOpStore: oven, IdentityClient: p.IdentityClient, Authorizer: p.Authorizer, }) return &Bakery{ Oven: oven, Checker: checker, } } ������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/authstore_test.go�������������������0000644�0610621�0607500�00000006272�13172163311�031037� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( "encoding/json" "golang.org/x/net/context" errgo "gopkg.in/errgo.v1" "gopkg.in/macaroon.v2-unstable" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type macaroonStore struct { rootKeyStore bakery.RootKeyStore key *bakery.KeyPair locator bakery.ThirdPartyLocator } // newMacaroonStore returns a MacaroonOpStore implementation // that stores root keys in memory and puts all operations // in the macaroon id. func newMacaroonStore(key *bakery.KeyPair, locator bakery.ThirdPartyLocator) *macaroonStore { return &macaroonStore{ rootKeyStore: bakery.NewMemRootKeyStore(), key: key, locator: locator, } } type macaroonId struct { Id []byte Ops []bakery.Op } func (s *macaroonStore) NewMacaroon(ctx context.Context, ops []bakery.Op, caveats []checkers.Caveat, ns *checkers.Namespace) (*bakery.Macaroon, error) { rootKey, id, err := s.rootKeyStore.RootKey(ctx) if err != nil { return nil, errgo.Mask(err) } mid := macaroonId{ Id: id, Ops: ops, } data, _ := json.Marshal(mid) m, err := bakery.NewMacaroon(rootKey, data, "", bakery.LatestVersion, ns) if err != nil { return nil, errgo.Mask(err) } if err := m.AddCaveats(ctx, caveats, s.key, s.locator); err != nil { return nil, errgo.Mask(err) } return m, nil } func (s *macaroonStore) MacaroonOps(ctx context.Context, ms macaroon.Slice) (ops []bakery.Op, conditions []string, err error) { if len(ms) == 0 { return nil, nil, &bakery.VerificationError{ Reason: errgo.Newf("no macaroons in slice"), } } id := ms[0].Id() var mid macaroonId if err := json.Unmarshal(id, &mid); err != nil { return nil, nil, &bakery.VerificationError{ Reason: errgo.Notef(err, "bad macaroon id"), } } rootKey, err := s.rootKeyStore.Get(ctx, mid.Id) if err != nil { if errgo.Cause(err) == bakery.ErrNotFound { return nil, nil, &bakery.VerificationError{ Reason: errgo.Notef(err, "cannot find root key"), } } return nil, nil, errgo.Notef(err, "cannot find root key") } conditions, err = ms[0].VerifySignature(rootKey, ms[1:]) if err != nil { return nil, nil, &bakery.VerificationError{ Reason: errgo.Mask(err), } } return mid.Ops, conditions, nil } // macaroonStoreWithError is an implementation of MacaroonOpStore that // returns the given error on all store operations. type macaroonStoreWithError struct { err error } func (s macaroonStoreWithError) NewMacaroon(ctx context.Context, ops []bakery.Op, caveats []checkers.Caveat, ns *checkers.Namespace) (*macaroon.Macaroon, error) { return nil, errgo.Mask(s.err, errgo.Any) } func (s macaroonStoreWithError) MacaroonOps(ctx context.Context, ms macaroon.Slice) (ops []bakery.Op, conditions []string, err error) { return nil, nil, errgo.Mask(s.err, errgo.Any) } func withoutLoginOp(ops []bakery.Op) []bakery.Op { // Remove LoginOp from the operations associated with the new macaroon. hasLoginOp := false for _, op := range ops { if op == bakery.LoginOp { hasLoginOp = true break } } if !hasLoginOp { return ops } newOps := make([]bakery.Op, 0, len(ops)) for _, op := range ops { if op != bakery.LoginOp { newOps = append(newOps, op) } } return newOps } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/authorizer_test.go������������������0000644�0610621�0607500�00000011215�13172163311�031206� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery_test import ( jujutesting "github.com/juju/testing" jc "github.com/juju/testing/checkers" "golang.org/x/net/context" gc "gopkg.in/check.v1" errgo "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) type authorizerSuite struct { jujutesting.LoggingSuite } var _ = gc.Suite(&authorizerSuite{}) func (*authorizerSuite) TestAuthorizerFunc(c *gc.C) { f := func(ctx context.Context, id bakery.Identity, op bakery.Op) (bool, []checkers.Caveat, error) { c.Assert(ctx, gc.Equals, testContext) c.Assert(id, gc.Equals, bakery.SimpleIdentity("bob")) switch op.Entity { case "a": return false, nil, nil case "b": return true, nil, nil case "c": return true, []checkers.Caveat{{ Location: "somewhere", Condition: "c", }}, nil case "d": return true, []checkers.Caveat{{ Location: "somewhere", Condition: "d", }}, nil } c.Fatalf("unexpected entity: %q", op.Entity) return false, nil, nil } allowed, caveats, err := bakery.AuthorizerFunc(f).Authorize(testContext, bakery.SimpleIdentity("bob"), []bakery.Op{{"a", "x"}, {"b", "x"}, {"c", "x"}, {"d", "x"}}) c.Assert(err, gc.IsNil) c.Assert(allowed, jc.DeepEquals, []bool{false, true, true, true}) c.Assert(caveats, jc.DeepEquals, []checkers.Caveat{{ Location: "somewhere", Condition: "c", }, { Location: "somewhere", Condition: "d", }}) } var aclAuthorizerTests = []struct { about string auth bakery.ACLAuthorizer identity bakery.Identity ops []bakery.Op expectAllowed []bool expectError string }{{ about: "no ops, no problem", auth: bakery.ACLAuthorizer{ GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) { return nil, false, nil }, }, }, { about: "identity that does not implement ACLIdentity; user should be denied except for everyone group", auth: bakery.ACLAuthorizer{ GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) { if op.Entity == "a" { return []string{bakery.Everyone}, true, nil } else { return []string{"alice"}, false, nil } }, }, identity: simplestIdentity("bob"), ops: []bakery.Op{{ Entity: "a", Action: "a", }, { Entity: "b", Action: "b", }}, expectAllowed: []bool{true, false}, }, { about: "identity that does not implement ACLIdentity with user == Id; user should be denied except for everyone group", auth: bakery.ACLAuthorizer{ GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) { if op.Entity == "a" { return []string{bakery.Everyone}, true, nil } else { return []string{"bob"}, false, nil } }, }, identity: simplestIdentity("bob"), ops: []bakery.Op{{ Entity: "a", Action: "a", }, { Entity: "b", Action: "b", }}, expectAllowed: []bool{true, false}, }, { about: "permission denied for everyone without allow-public", auth: bakery.ACLAuthorizer{ GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) { return []string{bakery.Everyone}, false, nil }, }, identity: simplestIdentity("bob"), ops: []bakery.Op{{ Entity: "a", Action: "a", }}, expectAllowed: []bool{false}, }, { about: "permission granted to anyone with no identity with allow-public", auth: bakery.ACLAuthorizer{ GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) { return []string{bakery.Everyone}, true, nil }, }, ops: []bakery.Op{{ Entity: "a", Action: "a", }}, expectAllowed: []bool{true}, }, { about: "error return causes all authorization to fail", auth: bakery.ACLAuthorizer{ GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) { if op.Entity == "a" { return []string{bakery.Everyone}, true, nil } else { return nil, false, errgo.New("some error") } }, }, ops: []bakery.Op{{ Entity: "a", Action: "a", }, { Entity: "b", Action: "b", }}, expectError: "some error", }} func (*authorizerSuite) TestACLAuthorizer(c *gc.C) { for i, test := range aclAuthorizerTests { c.Logf("test %d: %v", i, test.about) allowed, caveats, err := test.auth.Authorize(context.Background(), test.identity, test.ops) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) c.Assert(allowed, gc.IsNil) c.Assert(caveats, gc.IsNil) continue } c.Assert(err, gc.IsNil) c.Assert(caveats, gc.IsNil) c.Assert(allowed, jc.DeepEquals, test.expectAllowed) } } // simplestIdentity implements Identity for a string. Unlike // simpleIdentity, it does not implement ACLIdentity. type simplestIdentity string func (id simplestIdentity) Id() string { return string(id) } func (simplestIdentity) Domain() string { return "" } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/bakery/authorizer.go�����������������������0000644�0610621�0607500�00000013107�13172163311�030151� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package bakery import ( "golang.org/x/net/context" "gopkg.in/errgo.v1" "gopkg.in/macaroon-bakery.v2-unstable/bakery/checkers" ) // Authorizer is used to check whether a given user is allowed // to perform a set of operations. type Authorizer interface { // Authorize checks whether the given identity (which will be nil // when there is no authenticated user) is allowed to perform // the given operations. It should return an error only when // the authorization cannot be determined, not when the // user has been denied access. // // On success, each element of allowed holds whether the respective // element of ops has been allowed, and caveats holds any additional // third party caveats that apply. // If allowed is shorter then ops, the additional elements are assumed to // be false. Authorize(ctx context.Context, id Identity, ops []Op) (allowed []bool, caveats []checkers.Caveat, err error) } // OpsAuthorizer is used to check whether an operation authorizes some other // operation. For example, a macaroon with an operation allowing general access to a service // might also grant access to a more specific operation. type OpsAuthorizer interface { // AuthorizeOp reports which elements of queryOps are authorized by // authorizedOp. On return, each element of the slice should represent // whether the respective element in queryOps has been authorized. // An empty returned slice indicates that no operations are authorized. AuthorizeOps(ctx context.Context, authorizedOp Op, queryOps []Op) ([]bool, error) } var ( // OpenAuthorizer is an Authorizer implementation that will authorize all operations without question. OpenAuthorizer openAuthorizer // ClosedAuthorizer is an Authorizer implementation that will return ErrPermissionDenied // on all authorization requests. ClosedAuthorizer closedAuthorizer ) var ( _ Authorizer = OpenAuthorizer _ Authorizer = ClosedAuthorizer _ Authorizer = AuthorizerFunc(nil) _ Authorizer = ACLAuthorizer{} ) type openAuthorizer struct{} // Authorize implements Authorizer.Authorize. func (openAuthorizer) Authorize(ctx context.Context, id Identity, ops []Op) (allowed []bool, caveats []checkers.Caveat, err error) { allowed = make([]bool, len(ops)) for i := range allowed { allowed[i] = true } return allowed, nil, nil } type closedAuthorizer struct{} // Authorize implements Authorizer.Authorize. func (closedAuthorizer) Authorize(ctx context.Context, id Identity, ops []Op) (allowed []bool, caveats []checkers.Caveat, err error) { return make([]bool, len(ops)), nil, nil } // AuthorizerFunc implements a simplified version of Authorizer // that operates on a single operation at a time. type AuthorizerFunc func(ctx context.Context, id Identity, op Op) (bool, []checkers.Caveat, error) // Authorize implements Authorizer.Authorize by calling f // with the given identity for each operation. func (f AuthorizerFunc) Authorize(ctx context.Context, id Identity, ops []Op) (allowed []bool, caveats []checkers.Caveat, err error) { allowed = make([]bool, len(ops)) for i, op := range ops { ok, fcaveats, err := f(ctx, id, op) if err != nil { return nil, nil, errgo.Mask(err) } allowed[i] = ok // TODO merge identical caveats? caveats = append(caveats, fcaveats...) } return allowed, caveats, nil } // Everyone is recognized by ACLAuthorizer as the name of a // group that has everyone in it. const Everyone = "everyone" // ACLIdentity may be implemented by Identity implementions // to report group membership information. // See ACLAuthorizer for details. type ACLIdentity interface { Identity // Allow reports whether the user should be allowed to access // any of the users or groups in the given ACL slice. Allow(ctx context.Context, acl []string) (bool, error) } // ACLAuthorizer is an Authorizer implementation that will check access // control list (ACL) membership of users. It uses GetACL to find out // the ACLs that apply to the requested operations and will authorize an // operation if an ACL contains the group "everyone" or if the context // contains an AuthInfo (see ContextWithAuthInfo) that holds an Identity // that implements ACLIdentity and its Allow method returns true for the // ACL. type ACLAuthorizer struct { // GetACL returns the ACL that applies to the given operation, // and reports whether non-authenticated users should // be allowed access when the ACL contains "everyone". // // If an entity cannot be found or the action is not recognised, // GetACLs should return an empty ACL but no error. GetACL func(ctx context.Context, op Op) (acl []string, allowPublic bool, err error) } // Authorize implements Authorizer.Authorize by calling ident.Allow to determine // whether the identity is a member of the ACLs associated with the given // operations. func (a ACLAuthorizer) Authorize(ctx context.Context, ident Identity, ops []Op) (allowed []bool, caveats []checkers.Caveat, err error) { if len(ops) == 0 { // Anyone is allowed to do nothing. return nil, nil, nil } ident1, _ := ident.(ACLIdentity) allowed = make([]bool, len(ops)) for i, op := range ops { acl, allowPublic, err := a.GetACL(ctx, op) if err != nil { return nil, nil, errgo.Mask(err) } if ident1 != nil { allowed[i], err = ident1.Allow(ctx, acl) if err != nil { return nil, nil, errgo.Notef(err, "cannot check permissions") } } else { // TODO should we allow "everyone" when the identity is // non-nil but isn't an ACLIdentity? allowed[i] = allowPublic && isPublicACL(acl) } } return allowed, nil, nil } func isPublicACL(acl []string) bool { for _, g := range acl { if g == Everyone { return true } } return false } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/TODO���������������������������������������0000644�0610621�0607500�00000000224�13172163311�024635� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������all: - when API is stable, move to gopkg.in/macaroon.v1 macaroon: - change all signature calculations to correspond exactly with libmacaroons. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/README.md����������������������������������0000644�0610621�0607500�00000000550�13172163311�025426� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# The macaroon bakery This repository is a companion to http://github.com/go-macaroon . It holds higher level operations for building systems with macaroons. For documentation, see: - http://godoc.org/gopkg.in/macaroon-bakery.v1/bakery - http://godoc.org/gopkg.in/macaroon-bakery.v1/httpbakery - http://godoc.org/gopkg.in/macaroon-bakery.v1/bakery/checkers ��������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/macaroon-bakery.v2-unstable/LICENSE������������������������������������0000644�0610621�0607500�00000021133�13172163311�025154� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright © 2014, Roger Peppe, Canonical Inc. This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/���������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163307�020231� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/yamlprivateh.go������������������������������������������������0000644�0610621�0607500�00000011541�13172163307�023267� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml const ( // The size of the input raw buffer. input_raw_buffer_size = 512 // The size of the input buffer. // It should be possible to decode the whole raw buffer. input_buffer_size = input_raw_buffer_size * 3 // The size of the output buffer. output_buffer_size = 128 // The size of the output raw buffer. // It should be possible to encode the whole output buffer. output_raw_buffer_size = (output_buffer_size*2 + 2) // The size of other stacks and queues. initial_stack_size = 16 initial_queue_size = 16 initial_string_size = 16 ) // Check if the character at the specified position is an alphabetical // character, a digit, '_', or '-'. func is_alpha(b []byte, i int) bool { return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' } // Check if the character at the specified position is a digit. func is_digit(b []byte, i int) bool { return b[i] >= '0' && b[i] <= '9' } // Get the value of a digit. func as_digit(b []byte, i int) int { return int(b[i]) - '0' } // Check if the character at the specified position is a hex-digit. func is_hex(b []byte, i int) bool { return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' } // Get the value of a hex-digit. func as_hex(b []byte, i int) int { bi := b[i] if bi >= 'A' && bi <= 'F' { return int(bi) - 'A' + 10 } if bi >= 'a' && bi <= 'f' { return int(bi) - 'a' + 10 } return int(bi) - '0' } // Check if the character is ASCII. func is_ascii(b []byte, i int) bool { return b[i] <= 0x7F } // Check if the character at the start of the buffer can be printed unescaped. func is_printable(b []byte, i int) bool { return ((b[i] == 0x0A) || // . == #x0A (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF (b[i] > 0xC2 && b[i] < 0xED) || (b[i] == 0xED && b[i+1] < 0xA0) || (b[i] == 0xEE) || (b[i] == 0xEF && // #xE000 <= . <= #xFFFD !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) } // Check if the character at the specified position is NUL. func is_z(b []byte, i int) bool { return b[i] == 0x00 } // Check if the beginning of the buffer is a BOM. func is_bom(b []byte, i int) bool { return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF } // Check if the character at the specified position is space. func is_space(b []byte, i int) bool { return b[i] == ' ' } // Check if the character at the specified position is tab. func is_tab(b []byte, i int) bool { return b[i] == '\t' } // Check if the character at the specified position is blank (space or tab). func is_blank(b []byte, i int) bool { //return is_space(b, i) || is_tab(b, i) return b[i] == ' ' || b[i] == '\t' } // Check if the character at the specified position is a line break. func is_break(b []byte, i int) bool { return (b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) } func is_crlf(b []byte, i int) bool { return b[i] == '\r' && b[i+1] == '\n' } // Check if the character is a line break or NUL. func is_breakz(b []byte, i int) bool { //return is_break(b, i) || is_z(b, i) return ( // is_break: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) // is_z: b[i] == 0) } // Check if the character is a line break, space, or NUL. func is_spacez(b []byte, i int) bool { //return is_space(b, i) || is_breakz(b, i) return ( // is_space: b[i] == ' ' || // is_breakz: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) b[i] == 0) } // Check if the character is a line break, space, tab, or NUL. func is_blankz(b []byte, i int) bool { //return is_blank(b, i) || is_breakz(b, i) return ( // is_blank: b[i] == ' ' || b[i] == '\t' || // is_breakz: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) b[i] == 0) } // Determine the width of the character. func width(b byte) int { // Don't replace these by a switch without first // confirming that it is being inlined. if b&0x80 == 0x00 { return 1 } if b&0xE0 == 0xC0 { return 2 } if b&0xF0 == 0xE0 { return 3 } if b&0xF8 == 0xF0 { return 4 } return 0 } ���������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/yamlh.go�������������������������������������������������������0000644�0610621�0607500�00000061502�13172163307�021676� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "io" ) // The version directive data. type yaml_version_directive_t struct { major int8 // The major version number. minor int8 // The minor version number. } // The tag directive data. type yaml_tag_directive_t struct { handle []byte // The tag handle. prefix []byte // The tag prefix. } type yaml_encoding_t int // The stream encoding. const ( // Let the parser choose the encoding. yaml_ANY_ENCODING yaml_encoding_t = iota yaml_UTF8_ENCODING // The default UTF-8 encoding. yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. ) type yaml_break_t int // Line break types. const ( // Let the parser choose the break type. yaml_ANY_BREAK yaml_break_t = iota yaml_CR_BREAK // Use CR for line breaks (Mac style). yaml_LN_BREAK // Use LN for line breaks (Unix style). yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). ) type yaml_error_type_t int // Many bad things could happen with the parser and emitter. const ( // No error is produced. yaml_NO_ERROR yaml_error_type_t = iota yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. yaml_READER_ERROR // Cannot read or decode the input stream. yaml_SCANNER_ERROR // Cannot scan the input stream. yaml_PARSER_ERROR // Cannot parse the input stream. yaml_COMPOSER_ERROR // Cannot compose a YAML document. yaml_WRITER_ERROR // Cannot write to the output stream. yaml_EMITTER_ERROR // Cannot emit a YAML stream. ) // The pointer position. type yaml_mark_t struct { index int // The position index. line int // The position line. column int // The position column. } // Node Styles type yaml_style_t int8 type yaml_scalar_style_t yaml_style_t // Scalar styles. const ( // Let the emitter choose the style. yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota yaml_PLAIN_SCALAR_STYLE // The plain scalar style. yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. yaml_LITERAL_SCALAR_STYLE // The literal scalar style. yaml_FOLDED_SCALAR_STYLE // The folded scalar style. ) type yaml_sequence_style_t yaml_style_t // Sequence styles. const ( // Let the emitter choose the style. yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. ) type yaml_mapping_style_t yaml_style_t // Mapping styles. const ( // Let the emitter choose the style. yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota yaml_BLOCK_MAPPING_STYLE // The block mapping style. yaml_FLOW_MAPPING_STYLE // The flow mapping style. ) // Tokens type yaml_token_type_t int // Token types. const ( // An empty token. yaml_NO_TOKEN yaml_token_type_t = iota yaml_STREAM_START_TOKEN // A STREAM-START token. yaml_STREAM_END_TOKEN // A STREAM-END token. yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. yaml_BLOCK_END_TOKEN // A BLOCK-END token. yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. yaml_KEY_TOKEN // A KEY token. yaml_VALUE_TOKEN // A VALUE token. yaml_ALIAS_TOKEN // An ALIAS token. yaml_ANCHOR_TOKEN // An ANCHOR token. yaml_TAG_TOKEN // A TAG token. yaml_SCALAR_TOKEN // A SCALAR token. ) func (tt yaml_token_type_t) String() string { switch tt { case yaml_NO_TOKEN: return "yaml_NO_TOKEN" case yaml_STREAM_START_TOKEN: return "yaml_STREAM_START_TOKEN" case yaml_STREAM_END_TOKEN: return "yaml_STREAM_END_TOKEN" case yaml_VERSION_DIRECTIVE_TOKEN: return "yaml_VERSION_DIRECTIVE_TOKEN" case yaml_TAG_DIRECTIVE_TOKEN: return "yaml_TAG_DIRECTIVE_TOKEN" case yaml_DOCUMENT_START_TOKEN: return "yaml_DOCUMENT_START_TOKEN" case yaml_DOCUMENT_END_TOKEN: return "yaml_DOCUMENT_END_TOKEN" case yaml_BLOCK_SEQUENCE_START_TOKEN: return "yaml_BLOCK_SEQUENCE_START_TOKEN" case yaml_BLOCK_MAPPING_START_TOKEN: return "yaml_BLOCK_MAPPING_START_TOKEN" case yaml_BLOCK_END_TOKEN: return "yaml_BLOCK_END_TOKEN" case yaml_FLOW_SEQUENCE_START_TOKEN: return "yaml_FLOW_SEQUENCE_START_TOKEN" case yaml_FLOW_SEQUENCE_END_TOKEN: return "yaml_FLOW_SEQUENCE_END_TOKEN" case yaml_FLOW_MAPPING_START_TOKEN: return "yaml_FLOW_MAPPING_START_TOKEN" case yaml_FLOW_MAPPING_END_TOKEN: return "yaml_FLOW_MAPPING_END_TOKEN" case yaml_BLOCK_ENTRY_TOKEN: return "yaml_BLOCK_ENTRY_TOKEN" case yaml_FLOW_ENTRY_TOKEN: return "yaml_FLOW_ENTRY_TOKEN" case yaml_KEY_TOKEN: return "yaml_KEY_TOKEN" case yaml_VALUE_TOKEN: return "yaml_VALUE_TOKEN" case yaml_ALIAS_TOKEN: return "yaml_ALIAS_TOKEN" case yaml_ANCHOR_TOKEN: return "yaml_ANCHOR_TOKEN" case yaml_TAG_TOKEN: return "yaml_TAG_TOKEN" case yaml_SCALAR_TOKEN: return "yaml_SCALAR_TOKEN" } return "<unknown token>" } // The token structure. type yaml_token_t struct { // The token type. typ yaml_token_type_t // The start/end of the token. start_mark, end_mark yaml_mark_t // The stream encoding (for yaml_STREAM_START_TOKEN). encoding yaml_encoding_t // The alias/anchor/scalar value or tag/tag directive handle // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). value []byte // The tag suffix (for yaml_TAG_TOKEN). suffix []byte // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). prefix []byte // The scalar style (for yaml_SCALAR_TOKEN). style yaml_scalar_style_t // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). major, minor int8 } // Events type yaml_event_type_t int8 // Event types. const ( // An empty event. yaml_NO_EVENT yaml_event_type_t = iota yaml_STREAM_START_EVENT // A STREAM-START event. yaml_STREAM_END_EVENT // A STREAM-END event. yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. yaml_ALIAS_EVENT // An ALIAS event. yaml_SCALAR_EVENT // A SCALAR event. yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. yaml_MAPPING_START_EVENT // A MAPPING-START event. yaml_MAPPING_END_EVENT // A MAPPING-END event. ) // The event structure. type yaml_event_t struct { // The event type. typ yaml_event_type_t // The start and end of the event. start_mark, end_mark yaml_mark_t // The document encoding (for yaml_STREAM_START_EVENT). encoding yaml_encoding_t // The version directive (for yaml_DOCUMENT_START_EVENT). version_directive *yaml_version_directive_t // The list of tag directives (for yaml_DOCUMENT_START_EVENT). tag_directives []yaml_tag_directive_t // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). anchor []byte // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). tag []byte // The scalar value (for yaml_SCALAR_EVENT). value []byte // Is the document start/end indicator implicit, or the tag optional? // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). implicit bool // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). quoted_implicit bool // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). style yaml_style_t } func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } // Nodes const ( yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. // Not in original libyaml. yaml_BINARY_TAG = "tag:yaml.org,2002:binary" yaml_MERGE_TAG = "tag:yaml.org,2002:merge" yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. ) type yaml_node_type_t int // Node types. const ( // An empty node. yaml_NO_NODE yaml_node_type_t = iota yaml_SCALAR_NODE // A scalar node. yaml_SEQUENCE_NODE // A sequence node. yaml_MAPPING_NODE // A mapping node. ) // An element of a sequence node. type yaml_node_item_t int // An element of a mapping node. type yaml_node_pair_t struct { key int // The key of the element. value int // The value of the element. } // The node structure. type yaml_node_t struct { typ yaml_node_type_t // The node type. tag []byte // The node tag. // The node data. // The scalar parameters (for yaml_SCALAR_NODE). scalar struct { value []byte // The scalar value. length int // The length of the scalar value. style yaml_scalar_style_t // The scalar style. } // The sequence parameters (for YAML_SEQUENCE_NODE). sequence struct { items_data []yaml_node_item_t // The stack of sequence items. style yaml_sequence_style_t // The sequence style. } // The mapping parameters (for yaml_MAPPING_NODE). mapping struct { pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). pairs_start *yaml_node_pair_t // The beginning of the stack. pairs_end *yaml_node_pair_t // The end of the stack. pairs_top *yaml_node_pair_t // The top of the stack. style yaml_mapping_style_t // The mapping style. } start_mark yaml_mark_t // The beginning of the node. end_mark yaml_mark_t // The end of the node. } // The document structure. type yaml_document_t struct { // The document nodes. nodes []yaml_node_t // The version directive. version_directive *yaml_version_directive_t // The list of tag directives. tag_directives_data []yaml_tag_directive_t tag_directives_start int // The beginning of the tag directives list. tag_directives_end int // The end of the tag directives list. start_implicit int // Is the document start indicator implicit? end_implicit int // Is the document end indicator implicit? // The start/end of the document. start_mark, end_mark yaml_mark_t } // The prototype of a read handler. // // The read handler is called when the parser needs to read more bytes from the // source. The handler should write not more than size bytes to the buffer. // The number of written bytes should be set to the size_read variable. // // [in,out] data A pointer to an application data specified by // yaml_parser_set_input(). // [out] buffer The buffer to write the data from the source. // [in] size The size of the buffer. // [out] size_read The actual number of bytes read from the source. // // On success, the handler should return 1. If the handler failed, // the returned value should be 0. On EOF, the handler should set the // size_read to 0 and return 1. type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) // This structure holds information about a potential simple key. type yaml_simple_key_t struct { possible bool // Is a simple key possible? required bool // Is a simple key required? token_number int // The number of the token. mark yaml_mark_t // The position mark. } // The states of the parser. type yaml_parser_state_t int const ( yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. yaml_PARSE_END_STATE // Expect nothing. ) func (ps yaml_parser_state_t) String() string { switch ps { case yaml_PARSE_STREAM_START_STATE: return "yaml_PARSE_STREAM_START_STATE" case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" case yaml_PARSE_DOCUMENT_START_STATE: return "yaml_PARSE_DOCUMENT_START_STATE" case yaml_PARSE_DOCUMENT_CONTENT_STATE: return "yaml_PARSE_DOCUMENT_CONTENT_STATE" case yaml_PARSE_DOCUMENT_END_STATE: return "yaml_PARSE_DOCUMENT_END_STATE" case yaml_PARSE_BLOCK_NODE_STATE: return "yaml_PARSE_BLOCK_NODE_STATE" case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" case yaml_PARSE_FLOW_NODE_STATE: return "yaml_PARSE_FLOW_NODE_STATE" case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" case yaml_PARSE_FLOW_MAPPING_KEY_STATE: return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" case yaml_PARSE_END_STATE: return "yaml_PARSE_END_STATE" } return "<unknown parser state>" } // This structure holds aliases data. type yaml_alias_data_t struct { anchor []byte // The anchor. index int // The node id. mark yaml_mark_t // The anchor mark. } // The parser structure. // // All members are internal. Manage the structure using the // yaml_parser_ family of functions. type yaml_parser_t struct { // Error handling error yaml_error_type_t // Error type. problem string // Error description. // The byte about which the problem occurred. problem_offset int problem_value int problem_mark yaml_mark_t // The error context. context string context_mark yaml_mark_t // Reader stuff read_handler yaml_read_handler_t // Read handler. input_file io.Reader // File input data. input []byte // String input data. input_pos int eof bool // EOF flag buffer []byte // The working buffer. buffer_pos int // The current position of the buffer. unread int // The number of unread characters in the buffer. raw_buffer []byte // The raw buffer. raw_buffer_pos int // The current position of the buffer. encoding yaml_encoding_t // The input encoding. offset int // The offset of the current position (in bytes). mark yaml_mark_t // The mark of the current position. // Scanner stuff stream_start_produced bool // Have we started to scan the input stream? stream_end_produced bool // Have we reached the end of the input stream? flow_level int // The number of unclosed '[' and '{' indicators. tokens []yaml_token_t // The tokens queue. tokens_head int // The head of the tokens queue. tokens_parsed int // The number of tokens fetched from the queue. token_available bool // Does the tokens queue contain a token ready for dequeueing. indent int // The current indentation level. indents []int // The indentation levels stack. simple_key_allowed bool // May a simple key occur at the current position? simple_keys []yaml_simple_key_t // The stack of simple keys. // Parser stuff state yaml_parser_state_t // The current parser state. states []yaml_parser_state_t // The parser states stack. marks []yaml_mark_t // The stack of marks. tag_directives []yaml_tag_directive_t // The list of TAG directives. // Dumper stuff aliases []yaml_alias_data_t // The alias data. document *yaml_document_t // The currently parsed document. } // Emitter Definitions // The prototype of a write handler. // // The write handler is called when the emitter needs to flush the accumulated // characters to the output. The handler should write @a size bytes of the // @a buffer to the output. // // @param[in,out] data A pointer to an application data specified by // yaml_emitter_set_output(). // @param[in] buffer The buffer with bytes to be written. // @param[in] size The size of the buffer. // // @returns On success, the handler should return @c 1. If the handler failed, // the returned value should be @c 0. // type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error type yaml_emitter_state_t int // The emitter states. const ( // Expect STREAM-START. yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. yaml_EMIT_END_STATE // Expect nothing. ) // The emitter structure. // // All members are internal. Manage the structure using the @c yaml_emitter_ // family of functions. type yaml_emitter_t struct { // Error handling error yaml_error_type_t // Error type. problem string // Error description. // Writer stuff write_handler yaml_write_handler_t // Write handler. output_buffer *[]byte // String output data. output_file io.Writer // File output data. buffer []byte // The working buffer. buffer_pos int // The current position of the buffer. raw_buffer []byte // The raw buffer. raw_buffer_pos int // The current position of the buffer. encoding yaml_encoding_t // The stream encoding. // Emitter stuff canonical bool // If the output is in the canonical style? best_indent int // The number of indentation spaces. best_width int // The preferred width of the output lines. unicode bool // Allow unescaped non-ASCII characters? line_break yaml_break_t // The preferred line break. state yaml_emitter_state_t // The current emitter state. states []yaml_emitter_state_t // The stack of states. events []yaml_event_t // The event queue. events_head int // The head of the event queue. indents []int // The stack of indentation levels. tag_directives []yaml_tag_directive_t // The list of tag directives. indent int // The current indentation level. flow_level int // The current flow level. root_context bool // Is it the document root context? sequence_context bool // Is it a sequence context? mapping_context bool // Is it a mapping context? simple_key_context bool // Is it a simple mapping key context? line int // The current line. column int // The current column. whitespace bool // If the last character was a whitespace? indention bool // If the last character was an indentation character (' ', '-', '?', ':')? open_ended bool // If an explicit document end is required? // Anchor analysis. anchor_data struct { anchor []byte // The anchor value. alias bool // Is it an alias? } // Tag analysis. tag_data struct { handle []byte // The tag handle. suffix []byte // The tag suffix. } // Scalar analysis. scalar_data struct { value []byte // The scalar value. multiline bool // Does the scalar contain line breaks? flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? block_plain_allowed bool // Can the scalar be expressed in the block plain style? single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? block_allowed bool // Can the scalar be expressed in the literal or folded styles? style yaml_scalar_style_t // The output style. } // Dumper stuff opened bool // If the stream was already opened? closed bool // If the stream was already closed? // The information associated with the document nodes. anchors *struct { references int // The number of references. anchor int // The anchor id. serialized bool // If the node has been emitted? } last_anchor_id int // The last assigned anchor id. document *yaml_document_t // The currently emitted document. } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/yaml.go��������������������������������������������������������0000644�0610621�0607500�00000024015�13172163307�021524� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package yaml implements YAML support for the Go language. // // Source code and other details for the project are available at GitHub: // // https://github.com/go-yaml/yaml // package yaml import ( "errors" "fmt" "reflect" "strings" "sync" ) // MapSlice encodes and decodes as a YAML map. // The order of keys is preserved when encoding and decoding. type MapSlice []MapItem // MapItem is an item in a MapSlice. type MapItem struct { Key, Value interface{} } // The Unmarshaler interface may be implemented by types to customize their // behavior when being unmarshaled from a YAML document. The UnmarshalYAML // method receives a function that may be called to unmarshal the original // YAML value into a field or variable. It is safe to call the unmarshal // function parameter more than once if necessary. type Unmarshaler interface { UnmarshalYAML(unmarshal func(interface{}) error) error } // The Marshaler interface may be implemented by types to customize their // behavior when being marshaled into a YAML document. The returned value // is marshaled in place of the original value implementing Marshaler. // // If an error is returned by MarshalYAML, the marshaling procedure stops // and returns with the provided error. type Marshaler interface { MarshalYAML() (interface{}, error) } // Unmarshal decodes the first document found within the in byte slice // and assigns decoded values into the out value. // // Maps and pointers (to a struct, string, int, etc) are accepted as out // values. If an internal pointer within a struct is not initialized, // the yaml package will initialize it if necessary for unmarshalling // the provided data. The out parameter must not be nil. // // The type of the decoded values should be compatible with the respective // values in out. If one or more values cannot be decoded due to a type // mismatches, decoding continues partially until the end of the YAML // content, and a *yaml.TypeError is returned with details for all // missed values. // // Struct fields are only unmarshalled if they are exported (have an // upper case first letter), and are unmarshalled using the field name // lowercased as the default key. Custom keys may be defined via the // "yaml" name in the field tag: the content preceding the first comma // is used as the key, and the following comma-separated options are // used to tweak the marshalling process (see Marshal). // Conflicting names result in a runtime error. // // For example: // // type T struct { // F int `yaml:"a,omitempty"` // B int // } // var t T // yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) // // See the documentation of Marshal for the format of tags and a list of // supported tag options. // func Unmarshal(in []byte, out interface{}) (err error) { return unmarshal(in, out, false) } // UnmarshalStrict is like Unmarshal except that any fields that are found // in the data that do not have corresponding struct members will result in // an error. func UnmarshalStrict(in []byte, out interface{}) (err error) { return unmarshal(in, out, true) } func unmarshal(in []byte, out interface{}, strict bool) (err error) { defer handleErr(&err) d := newDecoder(strict) p := newParser(in) defer p.destroy() node := p.parse() if node != nil { v := reflect.ValueOf(out) if v.Kind() == reflect.Ptr && !v.IsNil() { v = v.Elem() } d.unmarshal(node, v) } if len(d.terrors) > 0 { return &TypeError{d.terrors} } return nil } // Marshal serializes the value provided into a YAML document. The structure // of the generated document will reflect the structure of the value itself. // Maps and pointers (to struct, string, int, etc) are accepted as the in value. // // Struct fields are only unmarshalled if they are exported (have an upper case // first letter), and are unmarshalled using the field name lowercased as the // default key. Custom keys may be defined via the "yaml" name in the field // tag: the content preceding the first comma is used as the key, and the // following comma-separated options are used to tweak the marshalling process. // Conflicting names result in a runtime error. // // The field tag format accepted is: // // `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)` // // The following flags are currently supported: // // omitempty Only include the field if it's not set to the zero // value for the type or to empty slices or maps. // Does not apply to zero valued structs. // // flow Marshal using a flow style (useful for structs, // sequences and maps). // // inline Inline the field, which must be a struct or a map, // causing all of its fields or keys to be processed as if // they were part of the outer struct. For maps, keys must // not conflict with the yaml keys of other struct fields. // // In addition, if the key is "-", the field is ignored. // // For example: // // type T struct { // F int "a,omitempty" // B int // } // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" // yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" // func Marshal(in interface{}) (out []byte, err error) { defer handleErr(&err) e := newEncoder() defer e.destroy() e.marshal("", reflect.ValueOf(in)) e.finish() out = e.out return } func handleErr(err *error) { if v := recover(); v != nil { if e, ok := v.(yamlError); ok { *err = e.err } else { panic(v) } } } type yamlError struct { err error } func fail(err error) { panic(yamlError{err}) } func failf(format string, args ...interface{}) { panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) } // A TypeError is returned by Unmarshal when one or more fields in // the YAML document cannot be properly decoded into the requested // types. When this error is returned, the value is still // unmarshaled partially. type TypeError struct { Errors []string } func (e *TypeError) Error() string { return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) } // -------------------------------------------------------------------------- // Maintain a mapping of keys to structure field indexes // The code in this section was copied from mgo/bson. // structInfo holds details for the serialization of fields of // a given struct. type structInfo struct { FieldsMap map[string]fieldInfo FieldsList []fieldInfo // InlineMap is the number of the field in the struct that // contains an ,inline map, or -1 if there's none. InlineMap int } type fieldInfo struct { Key string Num int OmitEmpty bool Flow bool // Inline holds the field index if the field is part of an inlined struct. Inline []int } var structMap = make(map[reflect.Type]*structInfo) var fieldMapMutex sync.RWMutex func getStructInfo(st reflect.Type) (*structInfo, error) { fieldMapMutex.RLock() sinfo, found := structMap[st] fieldMapMutex.RUnlock() if found { return sinfo, nil } n := st.NumField() fieldsMap := make(map[string]fieldInfo) fieldsList := make([]fieldInfo, 0, n) inlineMap := -1 for i := 0; i != n; i++ { field := st.Field(i) if field.PkgPath != "" && !field.Anonymous { continue // Private field } info := fieldInfo{Num: i} tag := field.Tag.Get("yaml") if tag == "" && strings.Index(string(field.Tag), ":") < 0 { tag = string(field.Tag) } if tag == "-" { continue } inline := false fields := strings.Split(tag, ",") if len(fields) > 1 { for _, flag := range fields[1:] { switch flag { case "omitempty": info.OmitEmpty = true case "flow": info.Flow = true case "inline": inline = true default: return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) } } tag = fields[0] } if inline { switch field.Type.Kind() { case reflect.Map: if inlineMap >= 0 { return nil, errors.New("Multiple ,inline maps in struct " + st.String()) } if field.Type.Key() != reflect.TypeOf("") { return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) } inlineMap = info.Num case reflect.Struct: sinfo, err := getStructInfo(field.Type) if err != nil { return nil, err } for _, finfo := range sinfo.FieldsList { if _, found := fieldsMap[finfo.Key]; found { msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() return nil, errors.New(msg) } if finfo.Inline == nil { finfo.Inline = []int{i, finfo.Num} } else { finfo.Inline = append([]int{i}, finfo.Inline...) } fieldsMap[finfo.Key] = finfo fieldsList = append(fieldsList, finfo) } default: //return nil, errors.New("Option ,inline needs a struct value or map field") return nil, errors.New("Option ,inline needs a struct value field") } continue } if tag != "" { info.Key = tag } else { info.Key = strings.ToLower(field.Name) } if _, found = fieldsMap[info.Key]; found { msg := "Duplicated key '" + info.Key + "' in struct " + st.String() return nil, errors.New(msg) } fieldsList = append(fieldsList, info) fieldsMap[info.Key] = info } sinfo = &structInfo{fieldsMap, fieldsList, inlineMap} fieldMapMutex.Lock() structMap[st] = sinfo fieldMapMutex.Unlock() return sinfo, nil } func isZero(v reflect.Value) bool { switch v.Kind() { case reflect.String: return len(v.String()) == 0 case reflect.Interface, reflect.Ptr: return v.IsNil() case reflect.Slice: return v.Len() == 0 case reflect.Map: return v.Len() == 0 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Bool: return !v.Bool() case reflect.Struct: vt := v.Type() for i := v.NumField() - 1; i >= 0; i-- { if vt.Field(i).PkgPath != "" { continue // Private field } if !isZero(v.Field(i)) { return false } } return true } return false } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/writerc.go�����������������������������������������������������0000644�0610621�0607500�00000004603�13172163307�022242� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml // Set the writer error and return false. func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { emitter.error = yaml_WRITER_ERROR emitter.problem = problem return false } // Flush the output buffer. func yaml_emitter_flush(emitter *yaml_emitter_t) bool { if emitter.write_handler == nil { panic("write handler not set") } // Check if the buffer is empty. if emitter.buffer_pos == 0 { return true } // If the output encoding is UTF-8, we don't need to recode the buffer. if emitter.encoding == yaml_UTF8_ENCODING { if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) } emitter.buffer_pos = 0 return true } // Recode the buffer into the raw buffer. var low, high int if emitter.encoding == yaml_UTF16LE_ENCODING { low, high = 0, 1 } else { high, low = 1, 0 } pos := 0 for pos < emitter.buffer_pos { // See the "reader.c" code for more details on UTF-8 encoding. Note // that we assume that the buffer contains a valid UTF-8 sequence. // Read the next UTF-8 character. octet := emitter.buffer[pos] var w int var value rune switch { case octet&0x80 == 0x00: w, value = 1, rune(octet&0x7F) case octet&0xE0 == 0xC0: w, value = 2, rune(octet&0x1F) case octet&0xF0 == 0xE0: w, value = 3, rune(octet&0x0F) case octet&0xF8 == 0xF0: w, value = 4, rune(octet&0x07) } for k := 1; k < w; k++ { octet = emitter.buffer[pos+k] value = (value << 6) + (rune(octet) & 0x3F) } pos += w // Write the character. if value < 0x10000 { var b [2]byte b[high] = byte(value >> 8) b[low] = byte(value & 0xFF) emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1]) } else { // Write the character using a surrogate pair (check "reader.c"). var b [4]byte value -= 0x10000 b[high] = byte(0xD8 + (value >> 18)) b[low] = byte((value >> 10) & 0xFF) b[high+2] = byte(0xDC + ((value >> 8) & 0xFF)) b[low+2] = byte(value & 0xFF) emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3]) } } // Write the raw buffer. if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil { return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) } emitter.buffer_pos = 0 emitter.raw_buffer = emitter.raw_buffer[:0] return true } �����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/suite_test.go��������������������������������������������������0000644�0610621�0607500�00000000217�13172163307�022750� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml_test import ( . "gopkg.in/check.v1" "testing" ) func Test(t *testing.T) { TestingT(t) } type S struct{} var _ = Suite(&S{}) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/sorter.go������������������������������������������������������0000644�0610621�0607500�00000004654�13172163307�022107� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "reflect" "unicode" ) type keyList []reflect.Value func (l keyList) Len() int { return len(l) } func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (l keyList) Less(i, j int) bool { a := l[i] b := l[j] ak := a.Kind() bk := b.Kind() for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { a = a.Elem() ak = a.Kind() } for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { b = b.Elem() bk = b.Kind() } af, aok := keyFloat(a) bf, bok := keyFloat(b) if aok && bok { if af != bf { return af < bf } if ak != bk { return ak < bk } return numLess(a, b) } if ak != reflect.String || bk != reflect.String { return ak < bk } ar, br := []rune(a.String()), []rune(b.String()) for i := 0; i < len(ar) && i < len(br); i++ { if ar[i] == br[i] { continue } al := unicode.IsLetter(ar[i]) bl := unicode.IsLetter(br[i]) if al && bl { return ar[i] < br[i] } if al || bl { return bl } var ai, bi int var an, bn int64 for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { an = an*10 + int64(ar[ai]-'0') } for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { bn = bn*10 + int64(br[bi]-'0') } if an != bn { return an < bn } if ai != bi { return ai < bi } return ar[i] < br[i] } return len(ar) < len(br) } // keyFloat returns a float value for v if it is a number/bool // and whether it is a number/bool or not. func keyFloat(v reflect.Value) (f float64, ok bool) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return float64(v.Int()), true case reflect.Float32, reflect.Float64: return v.Float(), true case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return float64(v.Uint()), true case reflect.Bool: if v.Bool() { return 1, true } return 0, true } return 0, false } // numLess returns whether a < b. // a and b must necessarily have the same kind. func numLess(a, b reflect.Value) bool { switch a.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return a.Int() < b.Int() case reflect.Float32, reflect.Float64: return a.Float() < b.Float() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return a.Uint() < b.Uint() case reflect.Bool: return !a.Bool() && b.Bool() } panic("not a number") } ������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/scannerc.go����������������������������������������������������0000644�0610621�0607500�00000226653�13172163307�022372� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "bytes" "fmt" ) // Introduction // ************ // // The following notes assume that you are familiar with the YAML specification // (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in // some cases we are less restrictive that it requires. // // The process of transforming a YAML stream into a sequence of events is // divided on two steps: Scanning and Parsing. // // The Scanner transforms the input stream into a sequence of tokens, while the // parser transform the sequence of tokens produced by the Scanner into a // sequence of parsing events. // // The Scanner is rather clever and complicated. The Parser, on the contrary, // is a straightforward implementation of a recursive-descendant parser (or, // LL(1) parser, as it is usually called). // // Actually there are two issues of Scanning that might be called "clever", the // rest is quite straightforward. The issues are "block collection start" and // "simple keys". Both issues are explained below in details. // // Here the Scanning step is explained and implemented. We start with the list // of all the tokens produced by the Scanner together with short descriptions. // // Now, tokens: // // STREAM-START(encoding) # The stream start. // STREAM-END # The stream end. // VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. // TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. // DOCUMENT-START # '---' // DOCUMENT-END # '...' // BLOCK-SEQUENCE-START # Indentation increase denoting a block // BLOCK-MAPPING-START # sequence or a block mapping. // BLOCK-END # Indentation decrease. // FLOW-SEQUENCE-START # '[' // FLOW-SEQUENCE-END # ']' // BLOCK-SEQUENCE-START # '{' // BLOCK-SEQUENCE-END # '}' // BLOCK-ENTRY # '-' // FLOW-ENTRY # ',' // KEY # '?' or nothing (simple keys). // VALUE # ':' // ALIAS(anchor) # '*anchor' // ANCHOR(anchor) # '&anchor' // TAG(handle,suffix) # '!handle!suffix' // SCALAR(value,style) # A scalar. // // The following two tokens are "virtual" tokens denoting the beginning and the // end of the stream: // // STREAM-START(encoding) // STREAM-END // // We pass the information about the input stream encoding with the // STREAM-START token. // // The next two tokens are responsible for tags: // // VERSION-DIRECTIVE(major,minor) // TAG-DIRECTIVE(handle,prefix) // // Example: // // %YAML 1.1 // %TAG ! !foo // %TAG !yaml! tag:yaml.org,2002: // --- // // The correspoding sequence of tokens: // // STREAM-START(utf-8) // VERSION-DIRECTIVE(1,1) // TAG-DIRECTIVE("!","!foo") // TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") // DOCUMENT-START // STREAM-END // // Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole // line. // // The document start and end indicators are represented by: // // DOCUMENT-START // DOCUMENT-END // // Note that if a YAML stream contains an implicit document (without '---' // and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be // produced. // // In the following examples, we present whole documents together with the // produced tokens. // // 1. An implicit document: // // 'a scalar' // // Tokens: // // STREAM-START(utf-8) // SCALAR("a scalar",single-quoted) // STREAM-END // // 2. An explicit document: // // --- // 'a scalar' // ... // // Tokens: // // STREAM-START(utf-8) // DOCUMENT-START // SCALAR("a scalar",single-quoted) // DOCUMENT-END // STREAM-END // // 3. Several documents in a stream: // // 'a scalar' // --- // 'another scalar' // --- // 'yet another scalar' // // Tokens: // // STREAM-START(utf-8) // SCALAR("a scalar",single-quoted) // DOCUMENT-START // SCALAR("another scalar",single-quoted) // DOCUMENT-START // SCALAR("yet another scalar",single-quoted) // STREAM-END // // We have already introduced the SCALAR token above. The following tokens are // used to describe aliases, anchors, tag, and scalars: // // ALIAS(anchor) // ANCHOR(anchor) // TAG(handle,suffix) // SCALAR(value,style) // // The following series of examples illustrate the usage of these tokens: // // 1. A recursive sequence: // // &A [ *A ] // // Tokens: // // STREAM-START(utf-8) // ANCHOR("A") // FLOW-SEQUENCE-START // ALIAS("A") // FLOW-SEQUENCE-END // STREAM-END // // 2. A tagged scalar: // // !!float "3.14" # A good approximation. // // Tokens: // // STREAM-START(utf-8) // TAG("!!","float") // SCALAR("3.14",double-quoted) // STREAM-END // // 3. Various scalar styles: // // --- # Implicit empty plain scalars do not produce tokens. // --- a plain scalar // --- 'a single-quoted scalar' // --- "a double-quoted scalar" // --- |- // a literal scalar // --- >- // a folded // scalar // // Tokens: // // STREAM-START(utf-8) // DOCUMENT-START // DOCUMENT-START // SCALAR("a plain scalar",plain) // DOCUMENT-START // SCALAR("a single-quoted scalar",single-quoted) // DOCUMENT-START // SCALAR("a double-quoted scalar",double-quoted) // DOCUMENT-START // SCALAR("a literal scalar",literal) // DOCUMENT-START // SCALAR("a folded scalar",folded) // STREAM-END // // Now it's time to review collection-related tokens. We will start with // flow collections: // // FLOW-SEQUENCE-START // FLOW-SEQUENCE-END // FLOW-MAPPING-START // FLOW-MAPPING-END // FLOW-ENTRY // KEY // VALUE // // The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and // FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' // correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the // indicators '?' and ':', which are used for denoting mapping keys and values, // are represented by the KEY and VALUE tokens. // // The following examples show flow collections: // // 1. A flow sequence: // // [item 1, item 2, item 3] // // Tokens: // // STREAM-START(utf-8) // FLOW-SEQUENCE-START // SCALAR("item 1",plain) // FLOW-ENTRY // SCALAR("item 2",plain) // FLOW-ENTRY // SCALAR("item 3",plain) // FLOW-SEQUENCE-END // STREAM-END // // 2. A flow mapping: // // { // a simple key: a value, # Note that the KEY token is produced. // ? a complex key: another value, // } // // Tokens: // // STREAM-START(utf-8) // FLOW-MAPPING-START // KEY // SCALAR("a simple key",plain) // VALUE // SCALAR("a value",plain) // FLOW-ENTRY // KEY // SCALAR("a complex key",plain) // VALUE // SCALAR("another value",plain) // FLOW-ENTRY // FLOW-MAPPING-END // STREAM-END // // A simple key is a key which is not denoted by the '?' indicator. Note that // the Scanner still produce the KEY token whenever it encounters a simple key. // // For scanning block collections, the following tokens are used (note that we // repeat KEY and VALUE here): // // BLOCK-SEQUENCE-START // BLOCK-MAPPING-START // BLOCK-END // BLOCK-ENTRY // KEY // VALUE // // The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation // increase that precedes a block collection (cf. the INDENT token in Python). // The token BLOCK-END denote indentation decrease that ends a block collection // (cf. the DEDENT token in Python). However YAML has some syntax pecularities // that makes detections of these tokens more complex. // // The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators // '-', '?', and ':' correspondingly. // // The following examples show how the tokens BLOCK-SEQUENCE-START, // BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: // // 1. Block sequences: // // - item 1 // - item 2 // - // - item 3.1 // - item 3.2 // - // key 1: value 1 // key 2: value 2 // // Tokens: // // STREAM-START(utf-8) // BLOCK-SEQUENCE-START // BLOCK-ENTRY // SCALAR("item 1",plain) // BLOCK-ENTRY // SCALAR("item 2",plain) // BLOCK-ENTRY // BLOCK-SEQUENCE-START // BLOCK-ENTRY // SCALAR("item 3.1",plain) // BLOCK-ENTRY // SCALAR("item 3.2",plain) // BLOCK-END // BLOCK-ENTRY // BLOCK-MAPPING-START // KEY // SCALAR("key 1",plain) // VALUE // SCALAR("value 1",plain) // KEY // SCALAR("key 2",plain) // VALUE // SCALAR("value 2",plain) // BLOCK-END // BLOCK-END // STREAM-END // // 2. Block mappings: // // a simple key: a value # The KEY token is produced here. // ? a complex key // : another value // a mapping: // key 1: value 1 // key 2: value 2 // a sequence: // - item 1 // - item 2 // // Tokens: // // STREAM-START(utf-8) // BLOCK-MAPPING-START // KEY // SCALAR("a simple key",plain) // VALUE // SCALAR("a value",plain) // KEY // SCALAR("a complex key",plain) // VALUE // SCALAR("another value",plain) // KEY // SCALAR("a mapping",plain) // BLOCK-MAPPING-START // KEY // SCALAR("key 1",plain) // VALUE // SCALAR("value 1",plain) // KEY // SCALAR("key 2",plain) // VALUE // SCALAR("value 2",plain) // BLOCK-END // KEY // SCALAR("a sequence",plain) // VALUE // BLOCK-SEQUENCE-START // BLOCK-ENTRY // SCALAR("item 1",plain) // BLOCK-ENTRY // SCALAR("item 2",plain) // BLOCK-END // BLOCK-END // STREAM-END // // YAML does not always require to start a new block collection from a new // line. If the current line contains only '-', '?', and ':' indicators, a new // block collection may start at the current line. The following examples // illustrate this case: // // 1. Collections in a sequence: // // - - item 1 // - item 2 // - key 1: value 1 // key 2: value 2 // - ? complex key // : complex value // // Tokens: // // STREAM-START(utf-8) // BLOCK-SEQUENCE-START // BLOCK-ENTRY // BLOCK-SEQUENCE-START // BLOCK-ENTRY // SCALAR("item 1",plain) // BLOCK-ENTRY // SCALAR("item 2",plain) // BLOCK-END // BLOCK-ENTRY // BLOCK-MAPPING-START // KEY // SCALAR("key 1",plain) // VALUE // SCALAR("value 1",plain) // KEY // SCALAR("key 2",plain) // VALUE // SCALAR("value 2",plain) // BLOCK-END // BLOCK-ENTRY // BLOCK-MAPPING-START // KEY // SCALAR("complex key") // VALUE // SCALAR("complex value") // BLOCK-END // BLOCK-END // STREAM-END // // 2. Collections in a mapping: // // ? a sequence // : - item 1 // - item 2 // ? a mapping // : key 1: value 1 // key 2: value 2 // // Tokens: // // STREAM-START(utf-8) // BLOCK-MAPPING-START // KEY // SCALAR("a sequence",plain) // VALUE // BLOCK-SEQUENCE-START // BLOCK-ENTRY // SCALAR("item 1",plain) // BLOCK-ENTRY // SCALAR("item 2",plain) // BLOCK-END // KEY // SCALAR("a mapping",plain) // VALUE // BLOCK-MAPPING-START // KEY // SCALAR("key 1",plain) // VALUE // SCALAR("value 1",plain) // KEY // SCALAR("key 2",plain) // VALUE // SCALAR("value 2",plain) // BLOCK-END // BLOCK-END // STREAM-END // // YAML also permits non-indented sequences if they are included into a block // mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: // // key: // - item 1 # BLOCK-SEQUENCE-START is NOT produced here. // - item 2 // // Tokens: // // STREAM-START(utf-8) // BLOCK-MAPPING-START // KEY // SCALAR("key",plain) // VALUE // BLOCK-ENTRY // SCALAR("item 1",plain) // BLOCK-ENTRY // SCALAR("item 2",plain) // BLOCK-END // // Ensure that the buffer contains the required number of characters. // Return true on success, false on failure (reader error or memory error). func cache(parser *yaml_parser_t, length int) bool { // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) return parser.unread >= length || yaml_parser_update_buffer(parser, length) } // Advance the buffer pointer. func skip(parser *yaml_parser_t) { parser.mark.index++ parser.mark.column++ parser.unread-- parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) } func skip_line(parser *yaml_parser_t) { if is_crlf(parser.buffer, parser.buffer_pos) { parser.mark.index += 2 parser.mark.column = 0 parser.mark.line++ parser.unread -= 2 parser.buffer_pos += 2 } else if is_break(parser.buffer, parser.buffer_pos) { parser.mark.index++ parser.mark.column = 0 parser.mark.line++ parser.unread-- parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) } } // Copy a character to a string buffer and advance pointers. func read(parser *yaml_parser_t, s []byte) []byte { w := width(parser.buffer[parser.buffer_pos]) if w == 0 { panic("invalid character sequence") } if len(s) == 0 { s = make([]byte, 0, 32) } if w == 1 && len(s)+w <= cap(s) { s = s[:len(s)+1] s[len(s)-1] = parser.buffer[parser.buffer_pos] parser.buffer_pos++ } else { s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) parser.buffer_pos += w } parser.mark.index++ parser.mark.column++ parser.unread-- return s } // Copy a line break character to a string buffer and advance pointers. func read_line(parser *yaml_parser_t, s []byte) []byte { buf := parser.buffer pos := parser.buffer_pos switch { case buf[pos] == '\r' && buf[pos+1] == '\n': // CR LF . LF s = append(s, '\n') parser.buffer_pos += 2 parser.mark.index++ parser.unread-- case buf[pos] == '\r' || buf[pos] == '\n': // CR|LF . LF s = append(s, '\n') parser.buffer_pos += 1 case buf[pos] == '\xC2' && buf[pos+1] == '\x85': // NEL . LF s = append(s, '\n') parser.buffer_pos += 2 case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): // LS|PS . LS|PS s = append(s, buf[parser.buffer_pos:pos+3]...) parser.buffer_pos += 3 default: return s } parser.mark.index++ parser.mark.column = 0 parser.mark.line++ parser.unread-- return s } // Get the next token. func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { // Erase the token object. *token = yaml_token_t{} // [Go] Is this necessary? // No tokens after STREAM-END or error. if parser.stream_end_produced || parser.error != yaml_NO_ERROR { return true } // Ensure that the tokens queue contains enough tokens. if !parser.token_available { if !yaml_parser_fetch_more_tokens(parser) { return false } } // Fetch the next token from the queue. *token = parser.tokens[parser.tokens_head] parser.tokens_head++ parser.tokens_parsed++ parser.token_available = false if token.typ == yaml_STREAM_END_TOKEN { parser.stream_end_produced = true } return true } // Set the scanner error and return false. func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { parser.error = yaml_SCANNER_ERROR parser.context = context parser.context_mark = context_mark parser.problem = problem parser.problem_mark = parser.mark return false } func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { context := "while parsing a tag" if directive { context = "while parsing a %TAG directive" } return yaml_parser_set_scanner_error(parser, context, context_mark, problem) } func trace(args ...interface{}) func() { pargs := append([]interface{}{"+++"}, args...) fmt.Println(pargs...) pargs = append([]interface{}{"---"}, args...) return func() { fmt.Println(pargs...) } } // Ensure that the tokens queue contains at least one token which can be // returned to the Parser. func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { // While we need more tokens to fetch, do it. for { // Check if we really need to fetch more tokens. need_more_tokens := false if parser.tokens_head == len(parser.tokens) { // Queue is empty. need_more_tokens = true } else { // Check if any potential simple key may occupy the head position. if !yaml_parser_stale_simple_keys(parser) { return false } for i := range parser.simple_keys { simple_key := &parser.simple_keys[i] if simple_key.possible && simple_key.token_number == parser.tokens_parsed { need_more_tokens = true break } } } // We are finished. if !need_more_tokens { break } // Fetch the next token. if !yaml_parser_fetch_next_token(parser) { return false } } parser.token_available = true return true } // The dispatcher for token fetchers. func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { // Ensure that the buffer is initialized. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } // Check if we just started scanning. Fetch STREAM-START then. if !parser.stream_start_produced { return yaml_parser_fetch_stream_start(parser) } // Eat whitespaces and comments until we reach the next token. if !yaml_parser_scan_to_next_token(parser) { return false } // Remove obsolete potential simple keys. if !yaml_parser_stale_simple_keys(parser) { return false } // Check the indentation level against the current column. if !yaml_parser_unroll_indent(parser, parser.mark.column) { return false } // Ensure that the buffer contains at least 4 characters. 4 is the length // of the longest indicators ('--- ' and '... '). if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { return false } // Is it the end of the stream? if is_z(parser.buffer, parser.buffer_pos) { return yaml_parser_fetch_stream_end(parser) } // Is it a directive? if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { return yaml_parser_fetch_directive(parser) } buf := parser.buffer pos := parser.buffer_pos // Is it the document start indicator? if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) } // Is it the document end indicator? if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) } // Is it the flow sequence start indicator? if buf[pos] == '[' { return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) } // Is it the flow mapping start indicator? if parser.buffer[parser.buffer_pos] == '{' { return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) } // Is it the flow sequence end indicator? if parser.buffer[parser.buffer_pos] == ']' { return yaml_parser_fetch_flow_collection_end(parser, yaml_FLOW_SEQUENCE_END_TOKEN) } // Is it the flow mapping end indicator? if parser.buffer[parser.buffer_pos] == '}' { return yaml_parser_fetch_flow_collection_end(parser, yaml_FLOW_MAPPING_END_TOKEN) } // Is it the flow entry indicator? if parser.buffer[parser.buffer_pos] == ',' { return yaml_parser_fetch_flow_entry(parser) } // Is it the block entry indicator? if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { return yaml_parser_fetch_block_entry(parser) } // Is it the key indicator? if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { return yaml_parser_fetch_key(parser) } // Is it the value indicator? if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { return yaml_parser_fetch_value(parser) } // Is it an alias? if parser.buffer[parser.buffer_pos] == '*' { return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) } // Is it an anchor? if parser.buffer[parser.buffer_pos] == '&' { return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) } // Is it a tag? if parser.buffer[parser.buffer_pos] == '!' { return yaml_parser_fetch_tag(parser) } // Is it a literal scalar? if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { return yaml_parser_fetch_block_scalar(parser, true) } // Is it a folded scalar? if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { return yaml_parser_fetch_block_scalar(parser, false) } // Is it a single-quoted scalar? if parser.buffer[parser.buffer_pos] == '\'' { return yaml_parser_fetch_flow_scalar(parser, true) } // Is it a double-quoted scalar? if parser.buffer[parser.buffer_pos] == '"' { return yaml_parser_fetch_flow_scalar(parser, false) } // Is it a plain scalar? // // A plain scalar may start with any non-blank characters except // // '-', '?', ':', ',', '[', ']', '{', '}', // '#', '&', '*', '!', '|', '>', '\'', '\"', // '%', '@', '`'. // // In the block context (and, for the '-' indicator, in the flow context // too), it may also start with the characters // // '-', '?', ':' // // if it is followed by a non-space character. // // The last rule is more restrictive than the specification requires. // [Go] Make this logic more reasonable. //switch parser.buffer[parser.buffer_pos] { //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': //} if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || (parser.flow_level == 0 && (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && !is_blankz(parser.buffer, parser.buffer_pos+1)) { return yaml_parser_fetch_plain_scalar(parser) } // If we don't determine the token type so far, it is an error. return yaml_parser_set_scanner_error(parser, "while scanning for the next token", parser.mark, "found character that cannot start any token") } // Check the list of potential simple keys and remove the positions that // cannot contain simple keys anymore. func yaml_parser_stale_simple_keys(parser *yaml_parser_t) bool { // Check for a potential simple key for each flow level. for i := range parser.simple_keys { simple_key := &parser.simple_keys[i] // The specification requires that a simple key // // - is limited to a single line, // - is shorter than 1024 characters. if simple_key.possible && (simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index) { // Check if the potential simple key to be removed is required. if simple_key.required { return yaml_parser_set_scanner_error(parser, "while scanning a simple key", simple_key.mark, "could not find expected ':'") } simple_key.possible = false } } return true } // Check if a simple key may start at the current position and add it if // needed. func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { // A simple key is required at the current position if the scanner is in // the block context and the current column coincides with the indentation // level. required := parser.flow_level == 0 && parser.indent == parser.mark.column // A simple key is required only when it is the first token in the current // line. Therefore it is always allowed. But we add a check anyway. if required && !parser.simple_key_allowed { panic("should not happen") } // // If the current position may start a simple key, save it. // if parser.simple_key_allowed { simple_key := yaml_simple_key_t{ possible: true, required: required, token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), } simple_key.mark = parser.mark if !yaml_parser_remove_simple_key(parser) { return false } parser.simple_keys[len(parser.simple_keys)-1] = simple_key } return true } // Remove a potential simple key at the current flow level. func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { i := len(parser.simple_keys) - 1 if parser.simple_keys[i].possible { // If the key is required, it is an error. if parser.simple_keys[i].required { return yaml_parser_set_scanner_error(parser, "while scanning a simple key", parser.simple_keys[i].mark, "could not find expected ':'") } } // Remove the key from the stack. parser.simple_keys[i].possible = false return true } // Increase the flow level and resize the simple key list if needed. func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { // Reset the simple key on the next level. parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) // Increase the flow level. parser.flow_level++ return true } // Decrease the flow level. func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { if parser.flow_level > 0 { parser.flow_level-- parser.simple_keys = parser.simple_keys[:len(parser.simple_keys)-1] } return true } // Push the current indentation level to the stack and set the new level // the current column is greater than the indentation level. In this case, // append or insert the specified token into the token queue. func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { // In the flow context, do nothing. if parser.flow_level > 0 { return true } if parser.indent < column { // Push the current indentation level to the stack and set the new // indentation level. parser.indents = append(parser.indents, parser.indent) parser.indent = column // Create a token and insert it into the queue. token := yaml_token_t{ typ: typ, start_mark: mark, end_mark: mark, } if number > -1 { number -= parser.tokens_parsed } yaml_insert_token(parser, number, &token) } return true } // Pop indentation levels from the indents stack until the current level // becomes less or equal to the column. For each indentation level, append // the BLOCK-END token. func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { // In the flow context, do nothing. if parser.flow_level > 0 { return true } // Loop through the indentation levels in the stack. for parser.indent > column { // Create a token and append it to the queue. token := yaml_token_t{ typ: yaml_BLOCK_END_TOKEN, start_mark: parser.mark, end_mark: parser.mark, } yaml_insert_token(parser, -1, &token) // Pop the indentation level. parser.indent = parser.indents[len(parser.indents)-1] parser.indents = parser.indents[:len(parser.indents)-1] } return true } // Initialize the scanner and produce the STREAM-START token. func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { // Set the initial indentation. parser.indent = -1 // Initialize the simple key stack. parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) // A simple key is allowed at the beginning of the stream. parser.simple_key_allowed = true // We have started. parser.stream_start_produced = true // Create the STREAM-START token and append it to the queue. token := yaml_token_t{ typ: yaml_STREAM_START_TOKEN, start_mark: parser.mark, end_mark: parser.mark, encoding: parser.encoding, } yaml_insert_token(parser, -1, &token) return true } // Produce the STREAM-END token and shut down the scanner. func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { // Force new line. if parser.mark.column != 0 { parser.mark.column = 0 parser.mark.line++ } // Reset the indentation level. if !yaml_parser_unroll_indent(parser, -1) { return false } // Reset simple keys. if !yaml_parser_remove_simple_key(parser) { return false } parser.simple_key_allowed = false // Create the STREAM-END token and append it to the queue. token := yaml_token_t{ typ: yaml_STREAM_END_TOKEN, start_mark: parser.mark, end_mark: parser.mark, } yaml_insert_token(parser, -1, &token) return true } // Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { // Reset the indentation level. if !yaml_parser_unroll_indent(parser, -1) { return false } // Reset simple keys. if !yaml_parser_remove_simple_key(parser) { return false } parser.simple_key_allowed = false // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. token := yaml_token_t{} if !yaml_parser_scan_directive(parser, &token) { return false } // Append the token to the queue. yaml_insert_token(parser, -1, &token) return true } // Produce the DOCUMENT-START or DOCUMENT-END token. func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { // Reset the indentation level. if !yaml_parser_unroll_indent(parser, -1) { return false } // Reset simple keys. if !yaml_parser_remove_simple_key(parser) { return false } parser.simple_key_allowed = false // Consume the token. start_mark := parser.mark skip(parser) skip(parser) skip(parser) end_mark := parser.mark // Create the DOCUMENT-START or DOCUMENT-END token. token := yaml_token_t{ typ: typ, start_mark: start_mark, end_mark: end_mark, } // Append the token to the queue. yaml_insert_token(parser, -1, &token) return true } // Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { // The indicators '[' and '{' may start a simple key. if !yaml_parser_save_simple_key(parser) { return false } // Increase the flow level. if !yaml_parser_increase_flow_level(parser) { return false } // A simple key may follow the indicators '[' and '{'. parser.simple_key_allowed = true // Consume the token. start_mark := parser.mark skip(parser) end_mark := parser.mark // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. token := yaml_token_t{ typ: typ, start_mark: start_mark, end_mark: end_mark, } // Append the token to the queue. yaml_insert_token(parser, -1, &token) return true } // Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { // Reset any potential simple key on the current flow level. if !yaml_parser_remove_simple_key(parser) { return false } // Decrease the flow level. if !yaml_parser_decrease_flow_level(parser) { return false } // No simple keys after the indicators ']' and '}'. parser.simple_key_allowed = false // Consume the token. start_mark := parser.mark skip(parser) end_mark := parser.mark // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. token := yaml_token_t{ typ: typ, start_mark: start_mark, end_mark: end_mark, } // Append the token to the queue. yaml_insert_token(parser, -1, &token) return true } // Produce the FLOW-ENTRY token. func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { // Reset any potential simple keys on the current flow level. if !yaml_parser_remove_simple_key(parser) { return false } // Simple keys are allowed after ','. parser.simple_key_allowed = true // Consume the token. start_mark := parser.mark skip(parser) end_mark := parser.mark // Create the FLOW-ENTRY token and append it to the queue. token := yaml_token_t{ typ: yaml_FLOW_ENTRY_TOKEN, start_mark: start_mark, end_mark: end_mark, } yaml_insert_token(parser, -1, &token) return true } // Produce the BLOCK-ENTRY token. func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { // Check if the scanner is in the block context. if parser.flow_level == 0 { // Check if we are allowed to start a new entry. if !parser.simple_key_allowed { return yaml_parser_set_scanner_error(parser, "", parser.mark, "block sequence entries are not allowed in this context") } // Add the BLOCK-SEQUENCE-START token if needed. if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { return false } } else { // It is an error for the '-' indicator to occur in the flow context, // but we let the Parser detect and report about it because the Parser // is able to point to the context. } // Reset any potential simple keys on the current flow level. if !yaml_parser_remove_simple_key(parser) { return false } // Simple keys are allowed after '-'. parser.simple_key_allowed = true // Consume the token. start_mark := parser.mark skip(parser) end_mark := parser.mark // Create the BLOCK-ENTRY token and append it to the queue. token := yaml_token_t{ typ: yaml_BLOCK_ENTRY_TOKEN, start_mark: start_mark, end_mark: end_mark, } yaml_insert_token(parser, -1, &token) return true } // Produce the KEY token. func yaml_parser_fetch_key(parser *yaml_parser_t) bool { // In the block context, additional checks are required. if parser.flow_level == 0 { // Check if we are allowed to start a new key (not nessesary simple). if !parser.simple_key_allowed { return yaml_parser_set_scanner_error(parser, "", parser.mark, "mapping keys are not allowed in this context") } // Add the BLOCK-MAPPING-START token if needed. if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { return false } } // Reset any potential simple keys on the current flow level. if !yaml_parser_remove_simple_key(parser) { return false } // Simple keys are allowed after '?' in the block context. parser.simple_key_allowed = parser.flow_level == 0 // Consume the token. start_mark := parser.mark skip(parser) end_mark := parser.mark // Create the KEY token and append it to the queue. token := yaml_token_t{ typ: yaml_KEY_TOKEN, start_mark: start_mark, end_mark: end_mark, } yaml_insert_token(parser, -1, &token) return true } // Produce the VALUE token. func yaml_parser_fetch_value(parser *yaml_parser_t) bool { simple_key := &parser.simple_keys[len(parser.simple_keys)-1] // Have we found a simple key? if simple_key.possible { // Create the KEY token and insert it into the queue. token := yaml_token_t{ typ: yaml_KEY_TOKEN, start_mark: simple_key.mark, end_mark: simple_key.mark, } yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) // In the block context, we may need to add the BLOCK-MAPPING-START token. if !yaml_parser_roll_indent(parser, simple_key.mark.column, simple_key.token_number, yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { return false } // Remove the simple key. simple_key.possible = false // A simple key cannot follow another simple key. parser.simple_key_allowed = false } else { // The ':' indicator follows a complex key. // In the block context, extra checks are required. if parser.flow_level == 0 { // Check if we are allowed to start a complex value. if !parser.simple_key_allowed { return yaml_parser_set_scanner_error(parser, "", parser.mark, "mapping values are not allowed in this context") } // Add the BLOCK-MAPPING-START token if needed. if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { return false } } // Simple keys after ':' are allowed in the block context. parser.simple_key_allowed = parser.flow_level == 0 } // Consume the token. start_mark := parser.mark skip(parser) end_mark := parser.mark // Create the VALUE token and append it to the queue. token := yaml_token_t{ typ: yaml_VALUE_TOKEN, start_mark: start_mark, end_mark: end_mark, } yaml_insert_token(parser, -1, &token) return true } // Produce the ALIAS or ANCHOR token. func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { // An anchor or an alias could be a simple key. if !yaml_parser_save_simple_key(parser) { return false } // A simple key cannot follow an anchor or an alias. parser.simple_key_allowed = false // Create the ALIAS or ANCHOR token and append it to the queue. var token yaml_token_t if !yaml_parser_scan_anchor(parser, &token, typ) { return false } yaml_insert_token(parser, -1, &token) return true } // Produce the TAG token. func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { // A tag could be a simple key. if !yaml_parser_save_simple_key(parser) { return false } // A simple key cannot follow a tag. parser.simple_key_allowed = false // Create the TAG token and append it to the queue. var token yaml_token_t if !yaml_parser_scan_tag(parser, &token) { return false } yaml_insert_token(parser, -1, &token) return true } // Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { // Remove any potential simple keys. if !yaml_parser_remove_simple_key(parser) { return false } // A simple key may follow a block scalar. parser.simple_key_allowed = true // Create the SCALAR token and append it to the queue. var token yaml_token_t if !yaml_parser_scan_block_scalar(parser, &token, literal) { return false } yaml_insert_token(parser, -1, &token) return true } // Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { // A plain scalar could be a simple key. if !yaml_parser_save_simple_key(parser) { return false } // A simple key cannot follow a flow scalar. parser.simple_key_allowed = false // Create the SCALAR token and append it to the queue. var token yaml_token_t if !yaml_parser_scan_flow_scalar(parser, &token, single) { return false } yaml_insert_token(parser, -1, &token) return true } // Produce the SCALAR(...,plain) token. func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { // A plain scalar could be a simple key. if !yaml_parser_save_simple_key(parser) { return false } // A simple key cannot follow a flow scalar. parser.simple_key_allowed = false // Create the SCALAR token and append it to the queue. var token yaml_token_t if !yaml_parser_scan_plain_scalar(parser, &token) { return false } yaml_insert_token(parser, -1, &token) return true } // Eat whitespaces and comments until the next token is found. func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { // Until the next token is not found. for { // Allow the BOM mark to start a line. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { skip(parser) } // Eat whitespaces. // Tabs are allowed: // - in the flow context // - in the block context, but not at the beginning of the line or // after '-', '?', or ':' (complex value). if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Eat a comment until a line break. if parser.buffer[parser.buffer_pos] == '#' { for !is_breakz(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } } // If it is a line break, eat it. if is_break(parser.buffer, parser.buffer_pos) { if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } skip_line(parser) // In the block context, a new line may start a simple key. if parser.flow_level == 0 { parser.simple_key_allowed = true } } else { break // We have found a token. } } return true } // Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. // // Scope: // %YAML 1.1 # a comment \n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // %TAG !yaml! tag:yaml.org,2002: \n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { // Eat '%'. start_mark := parser.mark skip(parser) // Scan the directive name. var name []byte if !yaml_parser_scan_directive_name(parser, start_mark, &name) { return false } // Is it a YAML directive? if bytes.Equal(name, []byte("YAML")) { // Scan the VERSION directive value. var major, minor int8 if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { return false } end_mark := parser.mark // Create a VERSION-DIRECTIVE token. *token = yaml_token_t{ typ: yaml_VERSION_DIRECTIVE_TOKEN, start_mark: start_mark, end_mark: end_mark, major: major, minor: minor, } // Is it a TAG directive? } else if bytes.Equal(name, []byte("TAG")) { // Scan the TAG directive value. var handle, prefix []byte if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { return false } end_mark := parser.mark // Create a TAG-DIRECTIVE token. *token = yaml_token_t{ typ: yaml_TAG_DIRECTIVE_TOKEN, start_mark: start_mark, end_mark: end_mark, value: handle, prefix: prefix, } // Unknown directive. } else { yaml_parser_set_scanner_error(parser, "while scanning a directive", start_mark, "found unknown directive name") return false } // Eat the rest of the line including any comments. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for is_blank(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } if parser.buffer[parser.buffer_pos] == '#' { for !is_breakz(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } } // Check if we are at the end of the line. if !is_breakz(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a directive", start_mark, "did not find expected comment or line break") return false } // Eat a line break. if is_break(parser.buffer, parser.buffer_pos) { if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } skip_line(parser) } return true } // Scan the directive name. // // Scope: // %YAML 1.1 # a comment \n // ^^^^ // %TAG !yaml! tag:yaml.org,2002: \n // ^^^ // func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { // Consume the directive name. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } var s []byte for is_alpha(parser.buffer, parser.buffer_pos) { s = read(parser, s) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Check if the name is empty. if len(s) == 0 { yaml_parser_set_scanner_error(parser, "while scanning a directive", start_mark, "could not find expected directive name") return false } // Check for an blank character after the name. if !is_blankz(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a directive", start_mark, "found unexpected non-alphabetical character") return false } *name = s return true } // Scan the value of VERSION-DIRECTIVE. // // Scope: // %YAML 1.1 # a comment \n // ^^^^^^ func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { // Eat whitespaces. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for is_blank(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Consume the major version number. if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { return false } // Eat '.'. if parser.buffer[parser.buffer_pos] != '.' { return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", start_mark, "did not find expected digit or '.' character") } skip(parser) // Consume the minor version number. if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { return false } return true } const max_number_length = 2 // Scan the version number of VERSION-DIRECTIVE. // // Scope: // %YAML 1.1 # a comment \n // ^ // %YAML 1.1 # a comment \n // ^ func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { // Repeat while the next character is digit. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } var value, length int8 for is_digit(parser.buffer, parser.buffer_pos) { // Check if the number is too long. length++ if length > max_number_length { return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", start_mark, "found extremely long version number") } value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Check if the number was present. if length == 0 { return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", start_mark, "did not find expected version number") } *number = value return true } // Scan the value of a TAG-DIRECTIVE token. // // Scope: // %TAG !yaml! tag:yaml.org,2002: \n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { var handle_value, prefix_value []byte // Eat whitespaces. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for is_blank(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Scan a handle. if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { return false } // Expect a whitespace. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } if !is_blank(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", start_mark, "did not find expected whitespace") return false } // Eat whitespaces. for is_blank(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Scan a prefix. if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { return false } // Expect a whitespace or line break. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } if !is_blankz(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", start_mark, "did not find expected whitespace or line break") return false } *handle = handle_value *prefix = prefix_value return true } func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { var s []byte // Eat the indicator character. start_mark := parser.mark skip(parser) // Consume the value. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for is_alpha(parser.buffer, parser.buffer_pos) { s = read(parser, s) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } end_mark := parser.mark /* * Check if length of the anchor is greater than 0 and it is followed by * a whitespace character or one of the indicators: * * '?', ':', ',', ']', '}', '%', '@', '`'. */ if len(s) == 0 || !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') { context := "while scanning an alias" if typ == yaml_ANCHOR_TOKEN { context = "while scanning an anchor" } yaml_parser_set_scanner_error(parser, context, start_mark, "did not find expected alphabetic or numeric character") return false } // Create a token. *token = yaml_token_t{ typ: typ, start_mark: start_mark, end_mark: end_mark, value: s, } return true } /* * Scan a TAG token. */ func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { var handle, suffix []byte start_mark := parser.mark // Check if the tag is in the canonical form. if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } if parser.buffer[parser.buffer_pos+1] == '<' { // Keep the handle as '' // Eat '!<' skip(parser) skip(parser) // Consume the tag value. if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { return false } // Check for '>' and eat it. if parser.buffer[parser.buffer_pos] != '>' { yaml_parser_set_scanner_error(parser, "while scanning a tag", start_mark, "did not find the expected '>'") return false } skip(parser) } else { // The tag has either the '!suffix' or the '!handle!suffix' form. // First, try to scan a handle. if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { return false } // Check if it is, indeed, handle. if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { // Scan the suffix now. if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { return false } } else { // It wasn't a handle after all. Scan the rest of the tag. if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { return false } // Set the handle to '!'. handle = []byte{'!'} // A special case: the '!' tag. Set the handle to '' and the // suffix to '!'. if len(suffix) == 0 { handle, suffix = suffix, handle } } } // Check the character which ends the tag. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } if !is_blankz(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a tag", start_mark, "did not find expected whitespace or line break") return false } end_mark := parser.mark // Create a token. *token = yaml_token_t{ typ: yaml_TAG_TOKEN, start_mark: start_mark, end_mark: end_mark, value: handle, suffix: suffix, } return true } // Scan a tag handle. func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { // Check the initial '!' character. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } if parser.buffer[parser.buffer_pos] != '!' { yaml_parser_set_scanner_tag_error(parser, directive, start_mark, "did not find expected '!'") return false } var s []byte // Copy the '!' character. s = read(parser, s) // Copy all subsequent alphabetical and numerical characters. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for is_alpha(parser.buffer, parser.buffer_pos) { s = read(parser, s) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Check if the trailing character is '!' and copy it. if parser.buffer[parser.buffer_pos] == '!' { s = read(parser, s) } else { // It's either the '!' tag or not really a tag handle. If it's a %TAG // directive, it's an error. If it's a tag token, it must be a part of URI. if directive && string(s) != "!" { yaml_parser_set_scanner_tag_error(parser, directive, start_mark, "did not find expected '!'") return false } } *handle = s return true } // Scan a tag. func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { //size_t length = head ? strlen((char *)head) : 0 var s []byte hasTag := len(head) > 0 // Copy the head if needed. // // Note that we don't copy the leading '!' character. if len(head) > 1 { s = append(s, head[1:]...) } // Scan the tag. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } // The set of characters that may appear in URI is as follows: // // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', // '%'. // [Go] Convert this into more reasonable logic. for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '%' { // Check if it is a URI-escape sequence. if parser.buffer[parser.buffer_pos] == '%' { if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { return false } } else { s = read(parser, s) } if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } hasTag = true } if !hasTag { yaml_parser_set_scanner_tag_error(parser, directive, start_mark, "did not find expected tag URI") return false } *uri = s return true } // Decode an URI-escape sequence corresponding to a single UTF-8 character. func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { // Decode the required number of characters. w := 1024 for w > 0 { // Check for a URI-escaped octet. if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { return false } if !(parser.buffer[parser.buffer_pos] == '%' && is_hex(parser.buffer, parser.buffer_pos+1) && is_hex(parser.buffer, parser.buffer_pos+2)) { return yaml_parser_set_scanner_tag_error(parser, directive, start_mark, "did not find URI escaped octet") } // Get the octet. octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) // If it is the leading octet, determine the length of the UTF-8 sequence. if w == 1024 { w = width(octet) if w == 0 { return yaml_parser_set_scanner_tag_error(parser, directive, start_mark, "found an incorrect leading UTF-8 octet") } } else { // Check if the trailing octet is correct. if octet&0xC0 != 0x80 { return yaml_parser_set_scanner_tag_error(parser, directive, start_mark, "found an incorrect trailing UTF-8 octet") } } // Copy the octet and move the pointers. *s = append(*s, octet) skip(parser) skip(parser) skip(parser) w-- } return true } // Scan a block scalar. func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { // Eat the indicator '|' or '>'. start_mark := parser.mark skip(parser) // Scan the additional block scalar indicators. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } // Check for a chomping indicator. var chomping, increment int if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { // Set the chomping method and eat the indicator. if parser.buffer[parser.buffer_pos] == '+' { chomping = +1 } else { chomping = -1 } skip(parser) // Check for an indentation indicator. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } if is_digit(parser.buffer, parser.buffer_pos) { // Check that the indentation is greater than 0. if parser.buffer[parser.buffer_pos] == '0' { yaml_parser_set_scanner_error(parser, "while scanning a block scalar", start_mark, "found an indentation indicator equal to 0") return false } // Get the indentation level and eat the indicator. increment = as_digit(parser.buffer, parser.buffer_pos) skip(parser) } } else if is_digit(parser.buffer, parser.buffer_pos) { // Do the same as above, but in the opposite order. if parser.buffer[parser.buffer_pos] == '0' { yaml_parser_set_scanner_error(parser, "while scanning a block scalar", start_mark, "found an indentation indicator equal to 0") return false } increment = as_digit(parser.buffer, parser.buffer_pos) skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { if parser.buffer[parser.buffer_pos] == '+' { chomping = +1 } else { chomping = -1 } skip(parser) } } // Eat whitespaces and comments to the end of the line. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for is_blank(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } if parser.buffer[parser.buffer_pos] == '#' { for !is_breakz(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } } // Check if we are at the end of the line. if !is_breakz(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a block scalar", start_mark, "did not find expected comment or line break") return false } // Eat a line break. if is_break(parser.buffer, parser.buffer_pos) { if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } skip_line(parser) } end_mark := parser.mark // Set the indentation level if it was specified. var indent int if increment > 0 { if parser.indent >= 0 { indent = parser.indent + increment } else { indent = increment } } // Scan the leading line breaks and determine the indentation level if needed. var s, leading_break, trailing_breaks []byte if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { return false } // Scan the block scalar content. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } var leading_blank, trailing_blank bool for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { // We are at the beginning of a non-empty line. // Is it a trailing whitespace? trailing_blank = is_blank(parser.buffer, parser.buffer_pos) // Check if we need to fold the leading line break. if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { // Do we need to join the lines by space? if len(trailing_breaks) == 0 { s = append(s, ' ') } } else { s = append(s, leading_break...) } leading_break = leading_break[:0] // Append the remaining line breaks. s = append(s, trailing_breaks...) trailing_breaks = trailing_breaks[:0] // Is it a leading whitespace? leading_blank = is_blank(parser.buffer, parser.buffer_pos) // Consume the current line. for !is_breakz(parser.buffer, parser.buffer_pos) { s = read(parser, s) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Consume the line break. if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } leading_break = read_line(parser, leading_break) // Eat the following indentation spaces and line breaks. if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { return false } } // Chomp the tail. if chomping != -1 { s = append(s, leading_break...) } if chomping == 1 { s = append(s, trailing_breaks...) } // Create a token. *token = yaml_token_t{ typ: yaml_SCALAR_TOKEN, start_mark: start_mark, end_mark: end_mark, value: s, style: yaml_LITERAL_SCALAR_STYLE, } if !literal { token.style = yaml_FOLDED_SCALAR_STYLE } return true } // Scan indentation spaces and line breaks for a block scalar. Determine the // indentation level if needed. func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { *end_mark = parser.mark // Eat the indentation spaces and line breaks. max_indent := 0 for { // Eat the indentation spaces. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } if parser.mark.column > max_indent { max_indent = parser.mark.column } // Check for a tab character messing the indentation. if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", start_mark, "found a tab character where an indentation space is expected") } // Have we found a non-empty line? if !is_break(parser.buffer, parser.buffer_pos) { break } // Consume the line break. if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } // [Go] Should really be returning breaks instead. *breaks = read_line(parser, *breaks) *end_mark = parser.mark } // Determine the indentation level if needed. if *indent == 0 { *indent = max_indent if *indent < parser.indent+1 { *indent = parser.indent + 1 } if *indent < 1 { *indent = 1 } } return true } // Scan a quoted scalar. func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { // Eat the left quote. start_mark := parser.mark skip(parser) // Consume the content of the quoted scalar. var s, leading_break, trailing_breaks, whitespaces []byte for { // Check that there are no document indicators at the beginning of the line. if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { return false } if parser.mark.column == 0 && ((parser.buffer[parser.buffer_pos+0] == '-' && parser.buffer[parser.buffer_pos+1] == '-' && parser.buffer[parser.buffer_pos+2] == '-') || (parser.buffer[parser.buffer_pos+0] == '.' && parser.buffer[parser.buffer_pos+1] == '.' && parser.buffer[parser.buffer_pos+2] == '.')) && is_blankz(parser.buffer, parser.buffer_pos+3) { yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", start_mark, "found unexpected document indicator") return false } // Check for EOF. if is_z(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", start_mark, "found unexpected end of stream") return false } // Consume non-blank characters. leading_blanks := false for !is_blankz(parser.buffer, parser.buffer_pos) { if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { // Is is an escaped single quote. s = append(s, '\'') skip(parser) skip(parser) } else if single && parser.buffer[parser.buffer_pos] == '\'' { // It is a right single quote. break } else if !single && parser.buffer[parser.buffer_pos] == '"' { // It is a right double quote. break } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { // It is an escaped line break. if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { return false } skip(parser) skip_line(parser) leading_blanks = true break } else if !single && parser.buffer[parser.buffer_pos] == '\\' { // It is an escape sequence. code_length := 0 // Check the escape character. switch parser.buffer[parser.buffer_pos+1] { case '0': s = append(s, 0) case 'a': s = append(s, '\x07') case 'b': s = append(s, '\x08') case 't', '\t': s = append(s, '\x09') case 'n': s = append(s, '\x0A') case 'v': s = append(s, '\x0B') case 'f': s = append(s, '\x0C') case 'r': s = append(s, '\x0D') case 'e': s = append(s, '\x1B') case ' ': s = append(s, '\x20') case '"': s = append(s, '"') case '\'': s = append(s, '\'') case '\\': s = append(s, '\\') case 'N': // NEL (#x85) s = append(s, '\xC2') s = append(s, '\x85') case '_': // #xA0 s = append(s, '\xC2') s = append(s, '\xA0') case 'L': // LS (#x2028) s = append(s, '\xE2') s = append(s, '\x80') s = append(s, '\xA8') case 'P': // PS (#x2029) s = append(s, '\xE2') s = append(s, '\x80') s = append(s, '\xA9') case 'x': code_length = 2 case 'u': code_length = 4 case 'U': code_length = 8 default: yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", start_mark, "found unknown escape character") return false } skip(parser) skip(parser) // Consume an arbitrary escape code. if code_length > 0 { var value int // Scan the character value. if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { return false } for k := 0; k < code_length; k++ { if !is_hex(parser.buffer, parser.buffer_pos+k) { yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", start_mark, "did not find expected hexdecimal number") return false } value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) } // Check the value and write the character. if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", start_mark, "found invalid Unicode character escape code") return false } if value <= 0x7F { s = append(s, byte(value)) } else if value <= 0x7FF { s = append(s, byte(0xC0+(value>>6))) s = append(s, byte(0x80+(value&0x3F))) } else if value <= 0xFFFF { s = append(s, byte(0xE0+(value>>12))) s = append(s, byte(0x80+((value>>6)&0x3F))) s = append(s, byte(0x80+(value&0x3F))) } else { s = append(s, byte(0xF0+(value>>18))) s = append(s, byte(0x80+((value>>12)&0x3F))) s = append(s, byte(0x80+((value>>6)&0x3F))) s = append(s, byte(0x80+(value&0x3F))) } // Advance the pointer. for k := 0; k < code_length; k++ { skip(parser) } } } else { // It is a non-escaped non-blank character. s = read(parser, s) } if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } } // Check if we are at the end of the scalar. if single { if parser.buffer[parser.buffer_pos] == '\'' { break } } else { if parser.buffer[parser.buffer_pos] == '"' { break } } // Consume blank characters. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { if is_blank(parser.buffer, parser.buffer_pos) { // Consume a space or a tab character. if !leading_blanks { whitespaces = read(parser, whitespaces) } else { skip(parser) } } else { if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } // Check if it is a first line break. if !leading_blanks { whitespaces = whitespaces[:0] leading_break = read_line(parser, leading_break) leading_blanks = true } else { trailing_breaks = read_line(parser, trailing_breaks) } } if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Join the whitespaces or fold line breaks. if leading_blanks { // Do we need to fold line breaks? if len(leading_break) > 0 && leading_break[0] == '\n' { if len(trailing_breaks) == 0 { s = append(s, ' ') } else { s = append(s, trailing_breaks...) } } else { s = append(s, leading_break...) s = append(s, trailing_breaks...) } trailing_breaks = trailing_breaks[:0] leading_break = leading_break[:0] } else { s = append(s, whitespaces...) whitespaces = whitespaces[:0] } } // Eat the right quote. skip(parser) end_mark := parser.mark // Create a token. *token = yaml_token_t{ typ: yaml_SCALAR_TOKEN, start_mark: start_mark, end_mark: end_mark, value: s, style: yaml_SINGLE_QUOTED_SCALAR_STYLE, } if !single { token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE } return true } // Scan a plain scalar. func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { var s, leading_break, trailing_breaks, whitespaces []byte var leading_blanks bool var indent = parser.indent + 1 start_mark := parser.mark end_mark := parser.mark // Consume the content of the plain scalar. for { // Check for a document indicator. if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { return false } if parser.mark.column == 0 && ((parser.buffer[parser.buffer_pos+0] == '-' && parser.buffer[parser.buffer_pos+1] == '-' && parser.buffer[parser.buffer_pos+2] == '-') || (parser.buffer[parser.buffer_pos+0] == '.' && parser.buffer[parser.buffer_pos+1] == '.' && parser.buffer[parser.buffer_pos+2] == '.')) && is_blankz(parser.buffer, parser.buffer_pos+3) { break } // Check for a comment. if parser.buffer[parser.buffer_pos] == '#' { break } // Consume non-blank characters. for !is_blankz(parser.buffer, parser.buffer_pos) { // Check for 'x:x' in the flow context. TODO: Fix the test "spec-08-13". if parser.flow_level > 0 && parser.buffer[parser.buffer_pos] == ':' && !is_blankz(parser.buffer, parser.buffer_pos+1) { yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", start_mark, "found unexpected ':'") return false } // Check for indicators that may end a plain scalar. if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || (parser.flow_level > 0 && (parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || parser.buffer[parser.buffer_pos] == '}')) { break } // Check if we need to join whitespaces and breaks. if leading_blanks || len(whitespaces) > 0 { if leading_blanks { // Do we need to fold line breaks? if leading_break[0] == '\n' { if len(trailing_breaks) == 0 { s = append(s, ' ') } else { s = append(s, trailing_breaks...) } } else { s = append(s, leading_break...) s = append(s, trailing_breaks...) } trailing_breaks = trailing_breaks[:0] leading_break = leading_break[:0] leading_blanks = false } else { s = append(s, whitespaces...) whitespaces = whitespaces[:0] } } // Copy the character. s = read(parser, s) end_mark = parser.mark if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } } // Is it the end? if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { break } // Consume blank characters. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { if is_blank(parser.buffer, parser.buffer_pos) { // Check for tab character that abuse indentation. if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", start_mark, "found a tab character that violate indentation") return false } // Consume a space or a tab character. if !leading_blanks { whitespaces = read(parser, whitespaces) } else { skip(parser) } } else { if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { return false } // Check if it is a first line break. if !leading_blanks { whitespaces = whitespaces[:0] leading_break = read_line(parser, leading_break) leading_blanks = true } else { trailing_breaks = read_line(parser, trailing_breaks) } } if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false } } // Check indentation level. if parser.flow_level == 0 && parser.mark.column < indent { break } } // Create a token. *token = yaml_token_t{ typ: yaml_SCALAR_TOKEN, start_mark: start_mark, end_mark: end_mark, value: s, style: yaml_PLAIN_SCALAR_STYLE, } // Note that we change the 'simple_key_allowed' flag. if leading_blanks { parser.simple_key_allowed = true } return true } �������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/resolve.go�����������������������������������������������������0000644�0610621�0607500�00000012170�13172163307�022240� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "encoding/base64" "math" "regexp" "strconv" "strings" "unicode/utf8" ) type resolveMapItem struct { value interface{} tag string } var resolveTable = make([]byte, 256) var resolveMap = make(map[string]resolveMapItem) func init() { t := resolveTable t[int('+')] = 'S' // Sign t[int('-')] = 'S' for _, c := range "0123456789" { t[int(c)] = 'D' // Digit } for _, c := range "yYnNtTfFoO~" { t[int(c)] = 'M' // In map } t[int('.')] = '.' // Float (potentially in map) var resolveMapList = []struct { v interface{} tag string l []string }{ {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, {"<<", yaml_MERGE_TAG, []string{"<<"}}, } m := resolveMap for _, item := range resolveMapList { for _, s := range item.l { m[s] = resolveMapItem{item.v, item.tag} } } } const longTagPrefix = "tag:yaml.org,2002:" func shortTag(tag string) string { // TODO This can easily be made faster and produce less garbage. if strings.HasPrefix(tag, longTagPrefix) { return "!!" + tag[len(longTagPrefix):] } return tag } func longTag(tag string) string { if strings.HasPrefix(tag, "!!") { return longTagPrefix + tag[2:] } return tag } func resolvableTag(tag string) bool { switch tag { case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG: return true } return false } var yamlStyleFloat = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+][0-9]+)?$`) func resolve(tag string, in string) (rtag string, out interface{}) { if !resolvableTag(tag) { return tag, in } defer func() { switch tag { case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: return } failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) }() // Any data is accepted as a !!str or !!binary. // Otherwise, the prefix is enough of a hint about what it might be. hint := byte('N') if in != "" { hint = resolveTable[in[0]] } if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { // Handle things we can lookup in a map. if item, ok := resolveMap[in]; ok { return item.tag, item.value } // Base 60 floats are a bad idea, were dropped in YAML 1.2, and // are purposefully unsupported here. They're still quoted on // the way out for compatibility with other parser, though. switch hint { case 'M': // We've already checked the map above. case '.': // Not in the map, so maybe a normal float. floatv, err := strconv.ParseFloat(in, 64) if err == nil { return yaml_FLOAT_TAG, floatv } case 'D', 'S': // Int, float, or timestamp. plain := strings.Replace(in, "_", "", -1) intv, err := strconv.ParseInt(plain, 0, 64) if err == nil { if intv == int64(int(intv)) { return yaml_INT_TAG, int(intv) } else { return yaml_INT_TAG, intv } } uintv, err := strconv.ParseUint(plain, 0, 64) if err == nil { return yaml_INT_TAG, uintv } if yamlStyleFloat.MatchString(plain) { floatv, err := strconv.ParseFloat(plain, 64) if err == nil { return yaml_FLOAT_TAG, floatv } } if strings.HasPrefix(plain, "0b") { intv, err := strconv.ParseInt(plain[2:], 2, 64) if err == nil { if intv == int64(int(intv)) { return yaml_INT_TAG, int(intv) } else { return yaml_INT_TAG, intv } } uintv, err := strconv.ParseUint(plain[2:], 2, 64) if err == nil { return yaml_INT_TAG, uintv } } else if strings.HasPrefix(plain, "-0b") { intv, err := strconv.ParseInt(plain[3:], 2, 64) if err == nil { if intv == int64(int(intv)) { return yaml_INT_TAG, -int(intv) } else { return yaml_INT_TAG, -intv } } } // XXX Handle timestamps here. default: panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") } } if tag == yaml_BINARY_TAG { return yaml_BINARY_TAG, in } if utf8.ValidString(in) { return yaml_STR_TAG, in } return yaml_BINARY_TAG, encodeBase64(in) } // encodeBase64 encodes s as base64 that is broken up into multiple lines // as appropriate for the resulting length. func encodeBase64(s string) string { const lineLen = 70 encLen := base64.StdEncoding.EncodedLen(len(s)) lines := encLen/lineLen + 1 buf := make([]byte, encLen*2+lines) in := buf[0:encLen] out := buf[encLen:] base64.StdEncoding.Encode(in, []byte(s)) k := 0 for i := 0; i < len(in); i += lineLen { j := i + lineLen if j > len(in) { j = len(in) } k += copy(out[k:], in[i:j]) if lines > 1 { out[k] = '\n' k++ } } return string(out[:k]) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/readerc.go�����������������������������������������������������0000644�0610621�0607500�00000027256�13172163307�022201� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "io" ) // Set the reader error and return 0. func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { parser.error = yaml_READER_ERROR parser.problem = problem parser.problem_offset = offset parser.problem_value = value return false } // Byte order marks. const ( bom_UTF8 = "\xef\xbb\xbf" bom_UTF16LE = "\xff\xfe" bom_UTF16BE = "\xfe\xff" ) // Determine the input stream encoding by checking the BOM symbol. If no BOM is // found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { // Ensure that we had enough bytes in the raw buffer. for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { if !yaml_parser_update_raw_buffer(parser) { return false } } // Determine the encoding. buf := parser.raw_buffer pos := parser.raw_buffer_pos avail := len(buf) - pos if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { parser.encoding = yaml_UTF16LE_ENCODING parser.raw_buffer_pos += 2 parser.offset += 2 } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { parser.encoding = yaml_UTF16BE_ENCODING parser.raw_buffer_pos += 2 parser.offset += 2 } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { parser.encoding = yaml_UTF8_ENCODING parser.raw_buffer_pos += 3 parser.offset += 3 } else { parser.encoding = yaml_UTF8_ENCODING } return true } // Update the raw buffer. func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { size_read := 0 // Return if the raw buffer is full. if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { return true } // Return on EOF. if parser.eof { return true } // Move the remaining bytes in the raw buffer to the beginning. if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) } parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] parser.raw_buffer_pos = 0 // Call the read handler to fill the buffer. size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] if err == io.EOF { parser.eof = true } else if err != nil { return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) } return true } // Ensure that the buffer contains at least `length` characters. // Return true on success, false on failure. // // The length is supposed to be significantly less that the buffer size. func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { if parser.read_handler == nil { panic("read handler must be set") } // If the EOF flag is set and the raw buffer is empty, do nothing. if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { return true } // Return if the buffer contains enough characters. if parser.unread >= length { return true } // Determine the input encoding if it is not known yet. if parser.encoding == yaml_ANY_ENCODING { if !yaml_parser_determine_encoding(parser) { return false } } // Move the unread characters to the beginning of the buffer. buffer_len := len(parser.buffer) if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { copy(parser.buffer, parser.buffer[parser.buffer_pos:]) buffer_len -= parser.buffer_pos parser.buffer_pos = 0 } else if parser.buffer_pos == buffer_len { buffer_len = 0 parser.buffer_pos = 0 } // Open the whole buffer for writing, and cut it before returning. parser.buffer = parser.buffer[:cap(parser.buffer)] // Fill the buffer until it has enough characters. first := true for parser.unread < length { // Fill the raw buffer if necessary. if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { if !yaml_parser_update_raw_buffer(parser) { parser.buffer = parser.buffer[:buffer_len] return false } } first = false // Decode the raw buffer. inner: for parser.raw_buffer_pos != len(parser.raw_buffer) { var value rune var width int raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos // Decode the next character. switch parser.encoding { case yaml_UTF8_ENCODING: // Decode a UTF-8 character. Check RFC 3629 // (http://www.ietf.org/rfc/rfc3629.txt) for more details. // // The following table (taken from the RFC) is used for // decoding. // // Char. number range | UTF-8 octet sequence // (hexadecimal) | (binary) // --------------------+------------------------------------ // 0000 0000-0000 007F | 0xxxxxxx // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // // Additionally, the characters in the range 0xD800-0xDFFF // are prohibited as they are reserved for use with UTF-16 // surrogate pairs. // Determine the length of the UTF-8 sequence. octet := parser.raw_buffer[parser.raw_buffer_pos] switch { case octet&0x80 == 0x00: width = 1 case octet&0xE0 == 0xC0: width = 2 case octet&0xF0 == 0xE0: width = 3 case octet&0xF8 == 0xF0: width = 4 default: // The leading octet is invalid. return yaml_parser_set_reader_error(parser, "invalid leading UTF-8 octet", parser.offset, int(octet)) } // Check if the raw buffer contains an incomplete character. if width > raw_unread { if parser.eof { return yaml_parser_set_reader_error(parser, "incomplete UTF-8 octet sequence", parser.offset, -1) } break inner } // Decode the leading octet. switch { case octet&0x80 == 0x00: value = rune(octet & 0x7F) case octet&0xE0 == 0xC0: value = rune(octet & 0x1F) case octet&0xF0 == 0xE0: value = rune(octet & 0x0F) case octet&0xF8 == 0xF0: value = rune(octet & 0x07) default: value = 0 } // Check and decode the trailing octets. for k := 1; k < width; k++ { octet = parser.raw_buffer[parser.raw_buffer_pos+k] // Check if the octet is valid. if (octet & 0xC0) != 0x80 { return yaml_parser_set_reader_error(parser, "invalid trailing UTF-8 octet", parser.offset+k, int(octet)) } // Decode the octet. value = (value << 6) + rune(octet&0x3F) } // Check the length of the sequence against the value. switch { case width == 1: case width == 2 && value >= 0x80: case width == 3 && value >= 0x800: case width == 4 && value >= 0x10000: default: return yaml_parser_set_reader_error(parser, "invalid length of a UTF-8 sequence", parser.offset, -1) } // Check the range of the value. if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { return yaml_parser_set_reader_error(parser, "invalid Unicode character", parser.offset, int(value)) } case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: var low, high int if parser.encoding == yaml_UTF16LE_ENCODING { low, high = 0, 1 } else { low, high = 1, 0 } // The UTF-16 encoding is not as simple as one might // naively think. Check RFC 2781 // (http://www.ietf.org/rfc/rfc2781.txt). // // Normally, two subsequent bytes describe a Unicode // character. However a special technique (called a // surrogate pair) is used for specifying character // values larger than 0xFFFF. // // A surrogate pair consists of two pseudo-characters: // high surrogate area (0xD800-0xDBFF) // low surrogate area (0xDC00-0xDFFF) // // The following formulas are used for decoding // and encoding characters using surrogate pairs: // // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) // W1 = 110110yyyyyyyyyy // W2 = 110111xxxxxxxxxx // // where U is the character value, W1 is the high surrogate // area, W2 is the low surrogate area. // Check for incomplete UTF-16 character. if raw_unread < 2 { if parser.eof { return yaml_parser_set_reader_error(parser, "incomplete UTF-16 character", parser.offset, -1) } break inner } // Get the character. value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) // Check for unexpected low surrogate area. if value&0xFC00 == 0xDC00 { return yaml_parser_set_reader_error(parser, "unexpected low surrogate area", parser.offset, int(value)) } // Check for a high surrogate area. if value&0xFC00 == 0xD800 { width = 4 // Check for incomplete surrogate pair. if raw_unread < 4 { if parser.eof { return yaml_parser_set_reader_error(parser, "incomplete UTF-16 surrogate pair", parser.offset, -1) } break inner } // Get the next character. value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) // Check for a low surrogate area. if value2&0xFC00 != 0xDC00 { return yaml_parser_set_reader_error(parser, "expected low surrogate area", parser.offset+2, int(value2)) } // Generate the value of the surrogate pair. value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) } else { width = 2 } default: panic("impossible") } // Check if the character is in the allowed range: // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) // | [#x10000-#x10FFFF] (32 bit) switch { case value == 0x09: case value == 0x0A: case value == 0x0D: case value >= 0x20 && value <= 0x7E: case value == 0x85: case value >= 0xA0 && value <= 0xD7FF: case value >= 0xE000 && value <= 0xFFFD: case value >= 0x10000 && value <= 0x10FFFF: default: return yaml_parser_set_reader_error(parser, "control characters are not allowed", parser.offset, int(value)) } // Move the raw pointers. parser.raw_buffer_pos += width parser.offset += width // Finally put the character into the buffer. if value <= 0x7F { // 0000 0000-0000 007F . 0xxxxxxx parser.buffer[buffer_len+0] = byte(value) buffer_len += 1 } else if value <= 0x7FF { // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) buffer_len += 2 } else if value <= 0xFFFF { // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) buffer_len += 3 } else { // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) buffer_len += 4 } parser.unread++ } // On EOF, put NUL into the buffer and return. if parser.eof { parser.buffer[buffer_len] = 0 buffer_len++ parser.unread++ break } } parser.buffer = parser.buffer[:buffer_len] return true } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/parserc.go�����������������������������������������������������0000644�0610621�0607500�00000103711�13172163307�022222� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "bytes" ) // The parser implements the following grammar: // // stream ::= STREAM-START implicit_document? explicit_document* STREAM-END // implicit_document ::= block_node DOCUMENT-END* // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* // block_node_or_indentless_sequence ::= // ALIAS // | properties (block_content | indentless_block_sequence)? // | block_content // | indentless_block_sequence // block_node ::= ALIAS // | properties block_content? // | block_content // flow_node ::= ALIAS // | properties flow_content? // | flow_content // properties ::= TAG ANCHOR? | ANCHOR TAG? // block_content ::= block_collection | flow_collection | SCALAR // flow_content ::= flow_collection | SCALAR // block_collection ::= block_sequence | block_mapping // flow_collection ::= flow_sequence | flow_mapping // block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END // indentless_sequence ::= (BLOCK-ENTRY block_node?)+ // block_mapping ::= BLOCK-MAPPING_START // ((KEY block_node_or_indentless_sequence?)? // (VALUE block_node_or_indentless_sequence?)?)* // BLOCK-END // flow_sequence ::= FLOW-SEQUENCE-START // (flow_sequence_entry FLOW-ENTRY)* // flow_sequence_entry? // FLOW-SEQUENCE-END // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // flow_mapping ::= FLOW-MAPPING-START // (flow_mapping_entry FLOW-ENTRY)* // flow_mapping_entry? // FLOW-MAPPING-END // flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // Peek the next token in the token queue. func peek_token(parser *yaml_parser_t) *yaml_token_t { if parser.token_available || yaml_parser_fetch_more_tokens(parser) { return &parser.tokens[parser.tokens_head] } return nil } // Remove the next token from the queue (must be called after peek_token). func skip_token(parser *yaml_parser_t) { parser.token_available = false parser.tokens_parsed++ parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN parser.tokens_head++ } // Get the next event. func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { // Erase the event object. *event = yaml_event_t{} // No events after the end of the stream or error. if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { return true } // Generate the next event. return yaml_parser_state_machine(parser, event) } // Set parser error. func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { parser.error = yaml_PARSER_ERROR parser.problem = problem parser.problem_mark = problem_mark return false } func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { parser.error = yaml_PARSER_ERROR parser.context = context parser.context_mark = context_mark parser.problem = problem parser.problem_mark = problem_mark return false } // State dispatcher. func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { //trace("yaml_parser_state_machine", "state:", parser.state.String()) switch parser.state { case yaml_PARSE_STREAM_START_STATE: return yaml_parser_parse_stream_start(parser, event) case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: return yaml_parser_parse_document_start(parser, event, true) case yaml_PARSE_DOCUMENT_START_STATE: return yaml_parser_parse_document_start(parser, event, false) case yaml_PARSE_DOCUMENT_CONTENT_STATE: return yaml_parser_parse_document_content(parser, event) case yaml_PARSE_DOCUMENT_END_STATE: return yaml_parser_parse_document_end(parser, event) case yaml_PARSE_BLOCK_NODE_STATE: return yaml_parser_parse_node(parser, event, true, false) case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: return yaml_parser_parse_node(parser, event, true, true) case yaml_PARSE_FLOW_NODE_STATE: return yaml_parser_parse_node(parser, event, false, false) case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: return yaml_parser_parse_block_sequence_entry(parser, event, true) case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: return yaml_parser_parse_block_sequence_entry(parser, event, false) case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: return yaml_parser_parse_indentless_sequence_entry(parser, event) case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: return yaml_parser_parse_block_mapping_key(parser, event, true) case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: return yaml_parser_parse_block_mapping_key(parser, event, false) case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: return yaml_parser_parse_block_mapping_value(parser, event) case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: return yaml_parser_parse_flow_sequence_entry(parser, event, true) case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: return yaml_parser_parse_flow_sequence_entry(parser, event, false) case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: return yaml_parser_parse_flow_mapping_key(parser, event, true) case yaml_PARSE_FLOW_MAPPING_KEY_STATE: return yaml_parser_parse_flow_mapping_key(parser, event, false) case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: return yaml_parser_parse_flow_mapping_value(parser, event, false) case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: return yaml_parser_parse_flow_mapping_value(parser, event, true) default: panic("invalid parser state") } } // Parse the production: // stream ::= STREAM-START implicit_document? explicit_document* STREAM-END // ************ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { return false } if token.typ != yaml_STREAM_START_TOKEN { return yaml_parser_set_parser_error(parser, "did not find expected <stream-start>", token.start_mark) } parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE *event = yaml_event_t{ typ: yaml_STREAM_START_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, encoding: token.encoding, } skip_token(parser) return true } // Parse the productions: // implicit_document ::= block_node DOCUMENT-END* // * // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* // ************************* func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { token := peek_token(parser) if token == nil { return false } // Parse extra document end indicators. if !implicit { for token.typ == yaml_DOCUMENT_END_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } } } if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && token.typ != yaml_TAG_DIRECTIVE_TOKEN && token.typ != yaml_DOCUMENT_START_TOKEN && token.typ != yaml_STREAM_END_TOKEN { // Parse an implicit document. if !yaml_parser_process_directives(parser, nil, nil) { return false } parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) parser.state = yaml_PARSE_BLOCK_NODE_STATE *event = yaml_event_t{ typ: yaml_DOCUMENT_START_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, } } else if token.typ != yaml_STREAM_END_TOKEN { // Parse an explicit document. var version_directive *yaml_version_directive_t var tag_directives []yaml_tag_directive_t start_mark := token.start_mark if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { return false } token = peek_token(parser) if token == nil { return false } if token.typ != yaml_DOCUMENT_START_TOKEN { yaml_parser_set_parser_error(parser, "did not find expected <document start>", token.start_mark) return false } parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE end_mark := token.end_mark *event = yaml_event_t{ typ: yaml_DOCUMENT_START_EVENT, start_mark: start_mark, end_mark: end_mark, version_directive: version_directive, tag_directives: tag_directives, implicit: false, } skip_token(parser) } else { // Parse the stream end. parser.state = yaml_PARSE_END_STATE *event = yaml_event_t{ typ: yaml_STREAM_END_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, } skip_token(parser) } return true } // Parse the productions: // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* // *********** // func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { return false } if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN || token.typ == yaml_DOCUMENT_START_TOKEN || token.typ == yaml_DOCUMENT_END_TOKEN || token.typ == yaml_STREAM_END_TOKEN { parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] return yaml_parser_process_empty_scalar(parser, event, token.start_mark) } return yaml_parser_parse_node(parser, event, true, false) } // Parse the productions: // implicit_document ::= block_node DOCUMENT-END* // ************* // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* // func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { return false } start_mark := token.start_mark end_mark := token.start_mark implicit := true if token.typ == yaml_DOCUMENT_END_TOKEN { end_mark = token.end_mark skip_token(parser) implicit = false } parser.tag_directives = parser.tag_directives[:0] parser.state = yaml_PARSE_DOCUMENT_START_STATE *event = yaml_event_t{ typ: yaml_DOCUMENT_END_EVENT, start_mark: start_mark, end_mark: end_mark, implicit: implicit, } return true } // Parse the productions: // block_node_or_indentless_sequence ::= // ALIAS // ***** // | properties (block_content | indentless_block_sequence)? // ********** * // | block_content | indentless_block_sequence // * // block_node ::= ALIAS // ***** // | properties block_content? // ********** * // | block_content // * // flow_node ::= ALIAS // ***** // | properties flow_content? // ********** * // | flow_content // * // properties ::= TAG ANCHOR? | ANCHOR TAG? // ************************* // block_content ::= block_collection | flow_collection | SCALAR // ****** // flow_content ::= flow_collection | SCALAR // ****** func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() token := peek_token(parser) if token == nil { return false } if token.typ == yaml_ALIAS_TOKEN { parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] *event = yaml_event_t{ typ: yaml_ALIAS_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, anchor: token.value, } skip_token(parser) return true } start_mark := token.start_mark end_mark := token.start_mark var tag_token bool var tag_handle, tag_suffix, anchor []byte var tag_mark yaml_mark_t if token.typ == yaml_ANCHOR_TOKEN { anchor = token.value start_mark = token.start_mark end_mark = token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.typ == yaml_TAG_TOKEN { tag_token = true tag_handle = token.value tag_suffix = token.suffix tag_mark = token.start_mark end_mark = token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } } } else if token.typ == yaml_TAG_TOKEN { tag_token = true tag_handle = token.value tag_suffix = token.suffix start_mark = token.start_mark tag_mark = token.start_mark end_mark = token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.typ == yaml_ANCHOR_TOKEN { anchor = token.value end_mark = token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } } } var tag []byte if tag_token { if len(tag_handle) == 0 { tag = tag_suffix tag_suffix = nil } else { for i := range parser.tag_directives { if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { tag = append([]byte(nil), parser.tag_directives[i].prefix...) tag = append(tag, tag_suffix...) break } } if len(tag) == 0 { yaml_parser_set_parser_error_context(parser, "while parsing a node", start_mark, "found undefined tag handle", tag_mark) return false } } } implicit := len(tag) == 0 if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE *event = yaml_event_t{ typ: yaml_SEQUENCE_START_EVENT, start_mark: start_mark, end_mark: end_mark, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), } return true } if token.typ == yaml_SCALAR_TOKEN { var plain_implicit, quoted_implicit bool end_mark = token.end_mark if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { plain_implicit = true } else if len(tag) == 0 { quoted_implicit = true } parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] *event = yaml_event_t{ typ: yaml_SCALAR_EVENT, start_mark: start_mark, end_mark: end_mark, anchor: anchor, tag: tag, value: token.value, implicit: plain_implicit, quoted_implicit: quoted_implicit, style: yaml_style_t(token.style), } skip_token(parser) return true } if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { // [Go] Some of the events below can be merged as they differ only on style. end_mark = token.end_mark parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE *event = yaml_event_t{ typ: yaml_SEQUENCE_START_EVENT, start_mark: start_mark, end_mark: end_mark, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), } return true } if token.typ == yaml_FLOW_MAPPING_START_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE *event = yaml_event_t{ typ: yaml_MAPPING_START_EVENT, start_mark: start_mark, end_mark: end_mark, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), } return true } if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE *event = yaml_event_t{ typ: yaml_SEQUENCE_START_EVENT, start_mark: start_mark, end_mark: end_mark, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), } return true } if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE *event = yaml_event_t{ typ: yaml_MAPPING_START_EVENT, start_mark: start_mark, end_mark: end_mark, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), } return true } if len(anchor) > 0 || len(tag) > 0 { parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] *event = yaml_event_t{ typ: yaml_SCALAR_EVENT, start_mark: start_mark, end_mark: end_mark, anchor: anchor, tag: tag, implicit: implicit, quoted_implicit: false, style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), } return true } context := "while parsing a flow node" if block { context = "while parsing a block node" } yaml_parser_set_parser_error_context(parser, context, start_mark, "did not find expected node content", token.start_mark) return false } // Parse the productions: // block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END // ******************** *********** * ********* // func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) parser.marks = append(parser.marks, token.start_mark) skip_token(parser) } token := peek_token(parser) if token == nil { return false } if token.typ == yaml_BLOCK_ENTRY_TOKEN { mark := token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) return yaml_parser_parse_node(parser, event, true, false) } else { parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE return yaml_parser_process_empty_scalar(parser, event, mark) } } if token.typ == yaml_BLOCK_END_TOKEN { parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] parser.marks = parser.marks[:len(parser.marks)-1] *event = yaml_event_t{ typ: yaml_SEQUENCE_END_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, } skip_token(parser) return true } context_mark := parser.marks[len(parser.marks)-1] parser.marks = parser.marks[:len(parser.marks)-1] return yaml_parser_set_parser_error_context(parser, "while parsing a block collection", context_mark, "did not find expected '-' indicator", token.start_mark) } // Parse the productions: // indentless_sequence ::= (BLOCK-ENTRY block_node?)+ // *********** * func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { return false } if token.typ == yaml_BLOCK_ENTRY_TOKEN { mark := token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_KEY_TOKEN && token.typ != yaml_VALUE_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) return yaml_parser_parse_node(parser, event, true, false) } parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE return yaml_parser_process_empty_scalar(parser, event, mark) } parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] *event = yaml_event_t{ typ: yaml_SEQUENCE_END_EVENT, start_mark: token.start_mark, end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? } return true } // Parse the productions: // block_mapping ::= BLOCK-MAPPING_START // ******************* // ((KEY block_node_or_indentless_sequence?)? // *** * // (VALUE block_node_or_indentless_sequence?)?)* // // BLOCK-END // ********* // func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) parser.marks = append(parser.marks, token.start_mark) skip_token(parser) } token := peek_token(parser) if token == nil { return false } if token.typ == yaml_KEY_TOKEN { mark := token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.typ != yaml_KEY_TOKEN && token.typ != yaml_VALUE_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) return yaml_parser_parse_node(parser, event, true, true) } else { parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE return yaml_parser_process_empty_scalar(parser, event, mark) } } else if token.typ == yaml_BLOCK_END_TOKEN { parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] parser.marks = parser.marks[:len(parser.marks)-1] *event = yaml_event_t{ typ: yaml_MAPPING_END_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, } skip_token(parser) return true } context_mark := parser.marks[len(parser.marks)-1] parser.marks = parser.marks[:len(parser.marks)-1] return yaml_parser_set_parser_error_context(parser, "while parsing a block mapping", context_mark, "did not find expected key", token.start_mark) } // Parse the productions: // block_mapping ::= BLOCK-MAPPING_START // // ((KEY block_node_or_indentless_sequence?)? // // (VALUE block_node_or_indentless_sequence?)?)* // ***** * // BLOCK-END // // func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { return false } if token.typ == yaml_VALUE_TOKEN { mark := token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.typ != yaml_KEY_TOKEN && token.typ != yaml_VALUE_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) return yaml_parser_parse_node(parser, event, true, true) } parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE return yaml_parser_process_empty_scalar(parser, event, mark) } parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE return yaml_parser_process_empty_scalar(parser, event, token.start_mark) } // Parse the productions: // flow_sequence ::= FLOW-SEQUENCE-START // ******************* // (flow_sequence_entry FLOW-ENTRY)* // * ********** // flow_sequence_entry? // * // FLOW-SEQUENCE-END // ***************** // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // * // func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) parser.marks = append(parser.marks, token.start_mark) skip_token(parser) } token := peek_token(parser) if token == nil { return false } if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { if !first { if token.typ == yaml_FLOW_ENTRY_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } } else { context_mark := parser.marks[len(parser.marks)-1] parser.marks = parser.marks[:len(parser.marks)-1] return yaml_parser_set_parser_error_context(parser, "while parsing a flow sequence", context_mark, "did not find expected ',' or ']'", token.start_mark) } } if token.typ == yaml_KEY_TOKEN { parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE *event = yaml_event_t{ typ: yaml_MAPPING_START_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, implicit: true, style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), } skip_token(parser) return true } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) return yaml_parser_parse_node(parser, event, false, false) } } parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] parser.marks = parser.marks[:len(parser.marks)-1] *event = yaml_event_t{ typ: yaml_SEQUENCE_END_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, } skip_token(parser) return true } // // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // *** * // func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { return false } if token.typ != yaml_VALUE_TOKEN && token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) return yaml_parser_parse_node(parser, event, false, false) } mark := token.end_mark skip_token(parser) parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE return yaml_parser_process_empty_scalar(parser, event, mark) } // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // ***** * // func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { return false } if token.typ == yaml_VALUE_TOKEN { skip_token(parser) token := peek_token(parser) if token == nil { return false } if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) return yaml_parser_parse_node(parser, event, false, false) } } parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE return yaml_parser_process_empty_scalar(parser, event, token.start_mark) } // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // * // func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { return false } parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE *event = yaml_event_t{ typ: yaml_MAPPING_END_EVENT, start_mark: token.start_mark, end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? } return true } // Parse the productions: // flow_mapping ::= FLOW-MAPPING-START // ****************** // (flow_mapping_entry FLOW-ENTRY)* // * ********** // flow_mapping_entry? // ****************** // FLOW-MAPPING-END // **************** // flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // * *** * // func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) parser.marks = append(parser.marks, token.start_mark) skip_token(parser) } token := peek_token(parser) if token == nil { return false } if token.typ != yaml_FLOW_MAPPING_END_TOKEN { if !first { if token.typ == yaml_FLOW_ENTRY_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } } else { context_mark := parser.marks[len(parser.marks)-1] parser.marks = parser.marks[:len(parser.marks)-1] return yaml_parser_set_parser_error_context(parser, "while parsing a flow mapping", context_mark, "did not find expected ',' or '}'", token.start_mark) } } if token.typ == yaml_KEY_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.typ != yaml_VALUE_TOKEN && token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) return yaml_parser_parse_node(parser, event, false, false) } else { parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE return yaml_parser_process_empty_scalar(parser, event, token.start_mark) } } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) return yaml_parser_parse_node(parser, event, false, false) } } parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] parser.marks = parser.marks[:len(parser.marks)-1] *event = yaml_event_t{ typ: yaml_MAPPING_END_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, } skip_token(parser) return true } // Parse the productions: // flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? // * ***** * // func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { token := peek_token(parser) if token == nil { return false } if empty { parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE return yaml_parser_process_empty_scalar(parser, event, token.start_mark) } if token.typ == yaml_VALUE_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) return yaml_parser_parse_node(parser, event, false, false) } } parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE return yaml_parser_process_empty_scalar(parser, event, token.start_mark) } // Generate an empty scalar event. func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { *event = yaml_event_t{ typ: yaml_SCALAR_EVENT, start_mark: mark, end_mark: mark, value: nil, // Empty implicit: true, style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), } return true } var default_tag_directives = []yaml_tag_directive_t{ {[]byte("!"), []byte("!")}, {[]byte("!!"), []byte("tag:yaml.org,2002:")}, } // Parse directives. func yaml_parser_process_directives(parser *yaml_parser_t, version_directive_ref **yaml_version_directive_t, tag_directives_ref *[]yaml_tag_directive_t) bool { var version_directive *yaml_version_directive_t var tag_directives []yaml_tag_directive_t token := peek_token(parser) if token == nil { return false } for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { if version_directive != nil { yaml_parser_set_parser_error(parser, "found duplicate %YAML directive", token.start_mark) return false } if token.major != 1 || token.minor != 1 { yaml_parser_set_parser_error(parser, "found incompatible YAML document", token.start_mark) return false } version_directive = &yaml_version_directive_t{ major: token.major, minor: token.minor, } } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { value := yaml_tag_directive_t{ handle: token.value, prefix: token.prefix, } if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { return false } tag_directives = append(tag_directives, value) } skip_token(parser) token = peek_token(parser) if token == nil { return false } } for i := range default_tag_directives { if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { return false } } if version_directive_ref != nil { *version_directive_ref = version_directive } if tag_directives_ref != nil { *tag_directives_ref = tag_directives } return true } // Append a tag directive to the directives stack. func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { for i := range parser.tag_directives { if bytes.Equal(value.handle, parser.tag_directives[i].handle) { if allow_duplicates { return true } return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) } } // [Go] I suspect the copy is unnecessary. This was likely done // because there was no way to track ownership of the data. value_copy := yaml_tag_directive_t{ handle: make([]byte, len(value.handle)), prefix: make([]byte, len(value.prefix)), } copy(value_copy.handle, value.handle) copy(value_copy.prefix, value.prefix) parser.tag_directives = append(parser.tag_directives, value_copy) return true } �������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/example_embedded_test.go���������������������������������������0000644�0610621�0607500�00000001355�13172163307�025067� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml_test import ( "fmt" "log" "gopkg.in/yaml.v2" ) // An example showing how to unmarshal embedded // structs from YAML. type StructA struct { A string `yaml:"a"` } type StructB struct { // Embedded structs are not treated as embedded in YAML by default. To do that, // add the ",inline" annotation below StructA `yaml:",inline"` B string `yaml:"b"` } var data = ` a: a string from struct A b: a string from struct B ` func ExampleUnmarshal_embedded() { var b StructB err := yaml.Unmarshal([]byte(data), &b) if err != nil { log.Fatal("cannot unmarshal data: %v", err) } fmt.Println(b.A) fmt.Println(b.B) // Output: // a string from struct A // a string from struct B } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/encode_test.go�������������������������������������������������0000644�0610621�0607500�00000021641�13172163307�023060� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml_test import ( "fmt" "math" "strconv" "strings" "time" . "gopkg.in/check.v1" "gopkg.in/yaml.v2" "net" "os" ) var marshalIntTest = 123 var marshalTests = []struct { value interface{} data string }{ { nil, "null\n", }, { &struct{}{}, "{}\n", }, { map[string]string{"v": "hi"}, "v: hi\n", }, { map[string]interface{}{"v": "hi"}, "v: hi\n", }, { map[string]string{"v": "true"}, "v: \"true\"\n", }, { map[string]string{"v": "false"}, "v: \"false\"\n", }, { map[string]interface{}{"v": true}, "v: true\n", }, { map[string]interface{}{"v": false}, "v: false\n", }, { map[string]interface{}{"v": 10}, "v: 10\n", }, { map[string]interface{}{"v": -10}, "v: -10\n", }, { map[string]uint{"v": 42}, "v: 42\n", }, { map[string]interface{}{"v": int64(4294967296)}, "v: 4294967296\n", }, { map[string]int64{"v": int64(4294967296)}, "v: 4294967296\n", }, { map[string]uint64{"v": 4294967296}, "v: 4294967296\n", }, { map[string]interface{}{"v": "10"}, "v: \"10\"\n", }, { map[string]interface{}{"v": 0.1}, "v: 0.1\n", }, { map[string]interface{}{"v": float64(0.1)}, "v: 0.1\n", }, { map[string]interface{}{"v": -0.1}, "v: -0.1\n", }, { map[string]interface{}{"v": math.Inf(+1)}, "v: .inf\n", }, { map[string]interface{}{"v": math.Inf(-1)}, "v: -.inf\n", }, { map[string]interface{}{"v": math.NaN()}, "v: .nan\n", }, { map[string]interface{}{"v": nil}, "v: null\n", }, { map[string]interface{}{"v": ""}, "v: \"\"\n", }, { map[string][]string{"v": []string{"A", "B"}}, "v:\n- A\n- B\n", }, { map[string][]string{"v": []string{"A", "B\nC"}}, "v:\n- A\n- |-\n B\n C\n", }, { map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}}, "v:\n- A\n- 1\n- B:\n - 2\n - 3\n", }, { map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, "a:\n b: c\n", }, { map[string]interface{}{"a": "-"}, "a: '-'\n", }, // Simple values. { &marshalIntTest, "123\n", }, // Structures { &struct{ Hello string }{"world"}, "hello: world\n", }, { &struct { A struct { B string } }{struct{ B string }{"c"}}, "a:\n b: c\n", }, { &struct { A *struct { B string } }{&struct{ B string }{"c"}}, "a:\n b: c\n", }, { &struct { A *struct { B string } }{}, "a: null\n", }, { &struct{ A int }{1}, "a: 1\n", }, { &struct{ A []int }{[]int{1, 2}}, "a:\n- 1\n- 2\n", }, { &struct { B int "a" }{1}, "a: 1\n", }, { &struct{ A bool }{true}, "a: true\n", }, // Conditional flag { &struct { A int "a,omitempty" B int "b,omitempty" }{1, 0}, "a: 1\n", }, { &struct { A int "a,omitempty" B int "b,omitempty" }{0, 0}, "{}\n", }, { &struct { A *struct{ X, y int } "a,omitempty,flow" }{&struct{ X, y int }{1, 2}}, "a: {x: 1}\n", }, { &struct { A *struct{ X, y int } "a,omitempty,flow" }{nil}, "{}\n", }, { &struct { A *struct{ X, y int } "a,omitempty,flow" }{&struct{ X, y int }{}}, "a: {x: 0}\n", }, { &struct { A struct{ X, y int } "a,omitempty,flow" }{struct{ X, y int }{1, 2}}, "a: {x: 1}\n", }, { &struct { A struct{ X, y int } "a,omitempty,flow" }{struct{ X, y int }{0, 1}}, "{}\n", }, { &struct { A float64 "a,omitempty" B float64 "b,omitempty" }{1, 0}, "a: 1\n", }, // Flow flag { &struct { A []int "a,flow" }{[]int{1, 2}}, "a: [1, 2]\n", }, { &struct { A map[string]string "a,flow" }{map[string]string{"b": "c", "d": "e"}}, "a: {b: c, d: e}\n", }, { &struct { A struct { B, D string } "a,flow" }{struct{ B, D string }{"c", "e"}}, "a: {b: c, d: e}\n", }, // Unexported field { &struct { u int A int }{0, 1}, "a: 1\n", }, // Ignored field { &struct { A int B int "-" }{1, 2}, "a: 1\n", }, // Struct inlining { &struct { A int C inlineB `yaml:",inline"` }{1, inlineB{2, inlineC{3}}}, "a: 1\nb: 2\nc: 3\n", }, // Map inlining { &struct { A int C map[string]int `yaml:",inline"` }{1, map[string]int{"b": 2, "c": 3}}, "a: 1\nb: 2\nc: 3\n", }, // Duration { map[string]time.Duration{"a": 3 * time.Second}, "a: 3s\n", }, // Issue #24: bug in map merging logic. { map[string]string{"a": "<foo>"}, "a: <foo>\n", }, // Issue #34: marshal unsupported base 60 floats quoted for compatibility // with old YAML 1.1 parsers. { map[string]string{"a": "1:1"}, "a: \"1:1\"\n", }, // Binary data. { map[string]string{"a": "\x00"}, "a: \"\\0\"\n", }, { map[string]string{"a": "\x80\x81\x82"}, "a: !!binary gIGC\n", }, { map[string]string{"a": strings.Repeat("\x90", 54)}, "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", }, // Ordered maps. { &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n", }, // Encode unicode as utf-8 rather than in escaped form. { map[string]string{"a": "你好"}, "a: 你好\n", }, // Support encoding.TextMarshaler. { map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, "a: 1.2.3.4\n", }, { map[string]time.Time{"a": time.Unix(1424801979, 0)}, "a: 2015-02-24T18:19:39Z\n", }, // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible). { map[string]string{"a": "b: c"}, "a: 'b: c'\n", }, // Containing hash mark ('#') in string should be quoted { map[string]string{"a": "Hello #comment"}, "a: 'Hello #comment'\n", }, { map[string]string{"a": "你好 #comment"}, "a: '你好 #comment'\n", }, } func (s *S) TestMarshal(c *C) { defer os.Setenv("TZ", os.Getenv("TZ")) os.Setenv("TZ", "UTC") for _, item := range marshalTests { data, err := yaml.Marshal(item.value) c.Assert(err, IsNil) c.Assert(string(data), Equals, item.data) } } var marshalErrorTests = []struct { value interface{} error string panic string }{{ value: &struct { B int inlineB ",inline" }{1, inlineB{2, inlineC{3}}}, panic: `Duplicated key 'b' in struct struct \{ B int; .*`, }, { value: &struct { A int B map[string]int ",inline" }{1, map[string]int{"a": 2}}, panic: `Can't have key "a" in inlined map; conflicts with struct field`, }} func (s *S) TestMarshalErrors(c *C) { for _, item := range marshalErrorTests { if item.panic != "" { c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic) } else { _, err := yaml.Marshal(item.value) c.Assert(err, ErrorMatches, item.error) } } } func (s *S) TestMarshalTypeCache(c *C) { var data []byte var err error func() { type T struct{ A int } data, err = yaml.Marshal(&T{}) c.Assert(err, IsNil) }() func() { type T struct{ B int } data, err = yaml.Marshal(&T{}) c.Assert(err, IsNil) }() c.Assert(string(data), Equals, "b: 0\n") } var marshalerTests = []struct { data string value interface{} }{ {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}}, {"_:\n- 1\n- A\n", []interface{}{1, "A"}}, {"_: 10\n", 10}, {"_: null\n", nil}, {"_: BAR!\n", "BAR!"}, } type marshalerType struct { value interface{} } func (o marshalerType) MarshalText() ([]byte, error) { panic("MarshalText called on type with MarshalYAML") } func (o marshalerType) MarshalYAML() (interface{}, error) { return o.value, nil } type marshalerValue struct { Field marshalerType "_" } func (s *S) TestMarshaler(c *C) { for _, item := range marshalerTests { obj := &marshalerValue{} obj.Field.value = item.value data, err := yaml.Marshal(obj) c.Assert(err, IsNil) c.Assert(string(data), Equals, string(item.data)) } } func (s *S) TestMarshalerWholeDocument(c *C) { obj := &marshalerType{} obj.value = map[string]string{"hello": "world!"} data, err := yaml.Marshal(obj) c.Assert(err, IsNil) c.Assert(string(data), Equals, "hello: world!\n") } type failingMarshaler struct{} func (ft *failingMarshaler) MarshalYAML() (interface{}, error) { return nil, failingErr } func (s *S) TestMarshalerError(c *C) { _, err := yaml.Marshal(&failingMarshaler{}) c.Assert(err, Equals, failingErr) } func (s *S) TestSortedOutput(c *C) { order := []interface{}{ false, true, 1, uint(1), 1.0, 1.1, 1.2, 2, uint(2), 2.0, 2.1, "", ".1", ".2", ".a", "1", "2", "a!10", "a/2", "a/10", "a~10", "ab/1", "b/1", "b/01", "b/2", "b/02", "b/3", "b/03", "b1", "b01", "b3", "c2.10", "c10.2", "d1", "d12", "d12a", } m := make(map[interface{}]int) for _, k := range order { m[k] = 1 } data, err := yaml.Marshal(m) c.Assert(err, IsNil) out := "\n" + string(data) last := 0 for i, k := range order { repr := fmt.Sprint(k) if s, ok := k.(string); ok { if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil { repr = `"` + repr + `"` } } index := strings.Index(out, "\n"+repr+":") if index == -1 { c.Fatalf("%#v is not in the output: %#v", k, out) } if index < last { c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out) } last = index } } �����������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/encode.go������������������������������������������������������0000644�0610621�0607500�00000016442�13172163307�022024� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "encoding" "fmt" "reflect" "regexp" "sort" "strconv" "strings" "time" ) type encoder struct { emitter yaml_emitter_t event yaml_event_t out []byte flow bool } func newEncoder() (e *encoder) { e = &encoder{} e.must(yaml_emitter_initialize(&e.emitter)) yaml_emitter_set_output_string(&e.emitter, &e.out) yaml_emitter_set_unicode(&e.emitter, true) e.must(yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)) e.emit() e.must(yaml_document_start_event_initialize(&e.event, nil, nil, true)) e.emit() return e } func (e *encoder) finish() { e.must(yaml_document_end_event_initialize(&e.event, true)) e.emit() e.emitter.open_ended = false e.must(yaml_stream_end_event_initialize(&e.event)) e.emit() } func (e *encoder) destroy() { yaml_emitter_delete(&e.emitter) } func (e *encoder) emit() { // This will internally delete the e.event value. if !yaml_emitter_emit(&e.emitter, &e.event) && e.event.typ != yaml_DOCUMENT_END_EVENT && e.event.typ != yaml_STREAM_END_EVENT { e.must(false) } } func (e *encoder) must(ok bool) { if !ok { msg := e.emitter.problem if msg == "" { msg = "unknown problem generating YAML content" } failf("%s", msg) } } func (e *encoder) marshal(tag string, in reflect.Value) { if !in.IsValid() { e.nilv() return } iface := in.Interface() if m, ok := iface.(Marshaler); ok { v, err := m.MarshalYAML() if err != nil { fail(err) } if v == nil { e.nilv() return } in = reflect.ValueOf(v) } else if m, ok := iface.(encoding.TextMarshaler); ok { text, err := m.MarshalText() if err != nil { fail(err) } in = reflect.ValueOf(string(text)) } switch in.Kind() { case reflect.Interface: if in.IsNil() { e.nilv() } else { e.marshal(tag, in.Elem()) } case reflect.Map: e.mapv(tag, in) case reflect.Ptr: if in.IsNil() { e.nilv() } else { e.marshal(tag, in.Elem()) } case reflect.Struct: e.structv(tag, in) case reflect.Slice: if in.Type().Elem() == mapItemType { e.itemsv(tag, in) } else { e.slicev(tag, in) } case reflect.String: e.stringv(tag, in) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if in.Type() == durationType { e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String())) } else { e.intv(tag, in) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: e.uintv(tag, in) case reflect.Float32, reflect.Float64: e.floatv(tag, in) case reflect.Bool: e.boolv(tag, in) default: panic("cannot marshal type: " + in.Type().String()) } } func (e *encoder) mapv(tag string, in reflect.Value) { e.mappingv(tag, func() { keys := keyList(in.MapKeys()) sort.Sort(keys) for _, k := range keys { e.marshal("", k) e.marshal("", in.MapIndex(k)) } }) } func (e *encoder) itemsv(tag string, in reflect.Value) { e.mappingv(tag, func() { slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem) for _, item := range slice { e.marshal("", reflect.ValueOf(item.Key)) e.marshal("", reflect.ValueOf(item.Value)) } }) } func (e *encoder) structv(tag string, in reflect.Value) { sinfo, err := getStructInfo(in.Type()) if err != nil { panic(err) } e.mappingv(tag, func() { for _, info := range sinfo.FieldsList { var value reflect.Value if info.Inline == nil { value = in.Field(info.Num) } else { value = in.FieldByIndex(info.Inline) } if info.OmitEmpty && isZero(value) { continue } e.marshal("", reflect.ValueOf(info.Key)) e.flow = info.Flow e.marshal("", value) } if sinfo.InlineMap >= 0 { m := in.Field(sinfo.InlineMap) if m.Len() > 0 { e.flow = false keys := keyList(m.MapKeys()) sort.Sort(keys) for _, k := range keys { if _, found := sinfo.FieldsMap[k.String()]; found { panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String())) } e.marshal("", k) e.flow = false e.marshal("", m.MapIndex(k)) } } } }) } func (e *encoder) mappingv(tag string, f func()) { implicit := tag == "" style := yaml_BLOCK_MAPPING_STYLE if e.flow { e.flow = false style = yaml_FLOW_MAPPING_STYLE } e.must(yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) e.emit() f() e.must(yaml_mapping_end_event_initialize(&e.event)) e.emit() } func (e *encoder) slicev(tag string, in reflect.Value) { implicit := tag == "" style := yaml_BLOCK_SEQUENCE_STYLE if e.flow { e.flow = false style = yaml_FLOW_SEQUENCE_STYLE } e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) e.emit() n := in.Len() for i := 0; i < n; i++ { e.marshal("", in.Index(i)) } e.must(yaml_sequence_end_event_initialize(&e.event)) e.emit() } // isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. // // The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported // in YAML 1.2 and by this package, but these should be marshalled quoted for // the time being for compatibility with other parsers. func isBase60Float(s string) (result bool) { // Fast path. if s == "" { return false } c := s[0] if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { return false } // Do the full match. return base60float.MatchString(s) } // From http://yaml.org/type/float.html, except the regular expression there // is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) func (e *encoder) stringv(tag string, in reflect.Value) { var style yaml_scalar_style_t s := in.String() rtag, rs := resolve("", s) if rtag == yaml_BINARY_TAG { if tag == "" || tag == yaml_STR_TAG { tag = rtag s = rs.(string) } else if tag == yaml_BINARY_TAG { failf("explicitly tagged !!binary data must be base64-encoded") } else { failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) } } if tag == "" && (rtag != yaml_STR_TAG || isBase60Float(s)) { style = yaml_DOUBLE_QUOTED_SCALAR_STYLE } else if strings.Contains(s, "\n") { style = yaml_LITERAL_SCALAR_STYLE } else { style = yaml_PLAIN_SCALAR_STYLE } e.emitScalar(s, "", tag, style) } func (e *encoder) boolv(tag string, in reflect.Value) { var s string if in.Bool() { s = "true" } else { s = "false" } e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } func (e *encoder) intv(tag string, in reflect.Value) { s := strconv.FormatInt(in.Int(), 10) e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } func (e *encoder) uintv(tag string, in reflect.Value) { s := strconv.FormatUint(in.Uint(), 10) e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } func (e *encoder) floatv(tag string, in reflect.Value) { // FIXME: Handle 64 bits here. s := strconv.FormatFloat(float64(in.Float()), 'g', -1, 32) switch s { case "+Inf": s = ".inf" case "-Inf": s = "-.inf" case "NaN": s = ".nan" } e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } func (e *encoder) nilv() { e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) } func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { implicit := tag == "" e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) e.emit() } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/emitterc.go����������������������������������������������������0000644�0610621�0607500�00000130352�13172163307�022400� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "bytes" ) // Flush the buffer if needed. func flush(emitter *yaml_emitter_t) bool { if emitter.buffer_pos+5 >= len(emitter.buffer) { return yaml_emitter_flush(emitter) } return true } // Put a character to the output buffer. func put(emitter *yaml_emitter_t, value byte) bool { if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { return false } emitter.buffer[emitter.buffer_pos] = value emitter.buffer_pos++ emitter.column++ return true } // Put a line break to the output buffer. func put_break(emitter *yaml_emitter_t) bool { if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { return false } switch emitter.line_break { case yaml_CR_BREAK: emitter.buffer[emitter.buffer_pos] = '\r' emitter.buffer_pos += 1 case yaml_LN_BREAK: emitter.buffer[emitter.buffer_pos] = '\n' emitter.buffer_pos += 1 case yaml_CRLN_BREAK: emitter.buffer[emitter.buffer_pos+0] = '\r' emitter.buffer[emitter.buffer_pos+1] = '\n' emitter.buffer_pos += 2 default: panic("unknown line break setting") } emitter.column = 0 emitter.line++ return true } // Copy a character from a string into buffer. func write(emitter *yaml_emitter_t, s []byte, i *int) bool { if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { return false } p := emitter.buffer_pos w := width(s[*i]) switch w { case 4: emitter.buffer[p+3] = s[*i+3] fallthrough case 3: emitter.buffer[p+2] = s[*i+2] fallthrough case 2: emitter.buffer[p+1] = s[*i+1] fallthrough case 1: emitter.buffer[p+0] = s[*i+0] default: panic("unknown character width") } emitter.column++ emitter.buffer_pos += w *i += w return true } // Write a whole string into buffer. func write_all(emitter *yaml_emitter_t, s []byte) bool { for i := 0; i < len(s); { if !write(emitter, s, &i) { return false } } return true } // Copy a line break character from a string into buffer. func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { if s[*i] == '\n' { if !put_break(emitter) { return false } *i++ } else { if !write(emitter, s, i) { return false } emitter.column = 0 emitter.line++ } return true } // Set an emitter error and return false. func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { emitter.error = yaml_EMITTER_ERROR emitter.problem = problem return false } // Emit an event. func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { emitter.events = append(emitter.events, *event) for !yaml_emitter_need_more_events(emitter) { event := &emitter.events[emitter.events_head] if !yaml_emitter_analyze_event(emitter, event) { return false } if !yaml_emitter_state_machine(emitter, event) { return false } yaml_event_delete(event) emitter.events_head++ } return true } // Check if we need to accumulate more events before emitting. // // We accumulate extra // - 1 event for DOCUMENT-START // - 2 events for SEQUENCE-START // - 3 events for MAPPING-START // func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { if emitter.events_head == len(emitter.events) { return true } var accumulate int switch emitter.events[emitter.events_head].typ { case yaml_DOCUMENT_START_EVENT: accumulate = 1 break case yaml_SEQUENCE_START_EVENT: accumulate = 2 break case yaml_MAPPING_START_EVENT: accumulate = 3 break default: return false } if len(emitter.events)-emitter.events_head > accumulate { return false } var level int for i := emitter.events_head; i < len(emitter.events); i++ { switch emitter.events[i].typ { case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: level++ case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: level-- } if level == 0 { return false } } return true } // Append a directive to the directives stack. func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { for i := 0; i < len(emitter.tag_directives); i++ { if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { if allow_duplicates { return true } return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") } } // [Go] Do we actually need to copy this given garbage collection // and the lack of deallocating destructors? tag_copy := yaml_tag_directive_t{ handle: make([]byte, len(value.handle)), prefix: make([]byte, len(value.prefix)), } copy(tag_copy.handle, value.handle) copy(tag_copy.prefix, value.prefix) emitter.tag_directives = append(emitter.tag_directives, tag_copy) return true } // Increase the indentation level. func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { emitter.indents = append(emitter.indents, emitter.indent) if emitter.indent < 0 { if flow { emitter.indent = emitter.best_indent } else { emitter.indent = 0 } } else if !indentless { emitter.indent += emitter.best_indent } return true } // State dispatcher. func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { switch emitter.state { default: case yaml_EMIT_STREAM_START_STATE: return yaml_emitter_emit_stream_start(emitter, event) case yaml_EMIT_FIRST_DOCUMENT_START_STATE: return yaml_emitter_emit_document_start(emitter, event, true) case yaml_EMIT_DOCUMENT_START_STATE: return yaml_emitter_emit_document_start(emitter, event, false) case yaml_EMIT_DOCUMENT_CONTENT_STATE: return yaml_emitter_emit_document_content(emitter, event) case yaml_EMIT_DOCUMENT_END_STATE: return yaml_emitter_emit_document_end(emitter, event) case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: return yaml_emitter_emit_flow_sequence_item(emitter, event, true) case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: return yaml_emitter_emit_flow_sequence_item(emitter, event, false) case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: return yaml_emitter_emit_flow_mapping_key(emitter, event, true) case yaml_EMIT_FLOW_MAPPING_KEY_STATE: return yaml_emitter_emit_flow_mapping_key(emitter, event, false) case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: return yaml_emitter_emit_flow_mapping_value(emitter, event, true) case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: return yaml_emitter_emit_flow_mapping_value(emitter, event, false) case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: return yaml_emitter_emit_block_sequence_item(emitter, event, true) case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: return yaml_emitter_emit_block_sequence_item(emitter, event, false) case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: return yaml_emitter_emit_block_mapping_key(emitter, event, true) case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: return yaml_emitter_emit_block_mapping_key(emitter, event, false) case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: return yaml_emitter_emit_block_mapping_value(emitter, event, true) case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: return yaml_emitter_emit_block_mapping_value(emitter, event, false) case yaml_EMIT_END_STATE: return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") } panic("invalid emitter state") } // Expect STREAM-START. func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { if event.typ != yaml_STREAM_START_EVENT { return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") } if emitter.encoding == yaml_ANY_ENCODING { emitter.encoding = event.encoding if emitter.encoding == yaml_ANY_ENCODING { emitter.encoding = yaml_UTF8_ENCODING } } if emitter.best_indent < 2 || emitter.best_indent > 9 { emitter.best_indent = 2 } if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { emitter.best_width = 80 } if emitter.best_width < 0 { emitter.best_width = 1<<31 - 1 } if emitter.line_break == yaml_ANY_BREAK { emitter.line_break = yaml_LN_BREAK } emitter.indent = -1 emitter.line = 0 emitter.column = 0 emitter.whitespace = true emitter.indention = true if emitter.encoding != yaml_UTF8_ENCODING { if !yaml_emitter_write_bom(emitter) { return false } } emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE return true } // Expect DOCUMENT-START or STREAM-END. func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { if event.typ == yaml_DOCUMENT_START_EVENT { if event.version_directive != nil { if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { return false } } for i := 0; i < len(event.tag_directives); i++ { tag_directive := &event.tag_directives[i] if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { return false } if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { return false } } for i := 0; i < len(default_tag_directives); i++ { tag_directive := &default_tag_directives[i] if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { return false } } implicit := event.implicit if !first || emitter.canonical { implicit = false } if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { return false } if !yaml_emitter_write_indent(emitter) { return false } } if event.version_directive != nil { implicit = false if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { return false } if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { return false } if !yaml_emitter_write_indent(emitter) { return false } } if len(event.tag_directives) > 0 { implicit = false for i := 0; i < len(event.tag_directives); i++ { tag_directive := &event.tag_directives[i] if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { return false } if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { return false } if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { return false } if !yaml_emitter_write_indent(emitter) { return false } } } if yaml_emitter_check_empty_document(emitter) { implicit = false } if !implicit { if !yaml_emitter_write_indent(emitter) { return false } if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { return false } if emitter.canonical { if !yaml_emitter_write_indent(emitter) { return false } } } emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE return true } if event.typ == yaml_STREAM_END_EVENT { if emitter.open_ended { if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { return false } if !yaml_emitter_write_indent(emitter) { return false } } if !yaml_emitter_flush(emitter) { return false } emitter.state = yaml_EMIT_END_STATE return true } return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") } // Expect the root node. func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) return yaml_emitter_emit_node(emitter, event, true, false, false, false) } // Expect DOCUMENT-END. func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { if event.typ != yaml_DOCUMENT_END_EVENT { return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") } if !yaml_emitter_write_indent(emitter) { return false } if !event.implicit { // [Go] Allocate the slice elsewhere. if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { return false } if !yaml_emitter_write_indent(emitter) { return false } } if !yaml_emitter_flush(emitter) { return false } emitter.state = yaml_EMIT_DOCUMENT_START_STATE emitter.tag_directives = emitter.tag_directives[:0] return true } // Expect a flow item node. func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { if first { if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { return false } if !yaml_emitter_increase_indent(emitter, true, false) { return false } emitter.flow_level++ } if event.typ == yaml_SEQUENCE_END_EVENT { emitter.flow_level-- emitter.indent = emitter.indents[len(emitter.indents)-1] emitter.indents = emitter.indents[:len(emitter.indents)-1] if emitter.canonical && !first { if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { return false } if !yaml_emitter_write_indent(emitter) { return false } } if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { return false } emitter.state = emitter.states[len(emitter.states)-1] emitter.states = emitter.states[:len(emitter.states)-1] return true } if !first { if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { return false } } if emitter.canonical || emitter.column > emitter.best_width { if !yaml_emitter_write_indent(emitter) { return false } } emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) return yaml_emitter_emit_node(emitter, event, false, true, false, false) } // Expect a flow key node. func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { if first { if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { return false } if !yaml_emitter_increase_indent(emitter, true, false) { return false } emitter.flow_level++ } if event.typ == yaml_MAPPING_END_EVENT { emitter.flow_level-- emitter.indent = emitter.indents[len(emitter.indents)-1] emitter.indents = emitter.indents[:len(emitter.indents)-1] if emitter.canonical && !first { if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { return false } if !yaml_emitter_write_indent(emitter) { return false } } if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { return false } emitter.state = emitter.states[len(emitter.states)-1] emitter.states = emitter.states[:len(emitter.states)-1] return true } if !first { if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { return false } } if emitter.canonical || emitter.column > emitter.best_width { if !yaml_emitter_write_indent(emitter) { return false } } if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) return yaml_emitter_emit_node(emitter, event, false, false, true, true) } if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { return false } emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) return yaml_emitter_emit_node(emitter, event, false, false, true, false) } // Expect a flow value node. func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { if simple { if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { return false } } else { if emitter.canonical || emitter.column > emitter.best_width { if !yaml_emitter_write_indent(emitter) { return false } } if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { return false } } emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) return yaml_emitter_emit_node(emitter, event, false, false, true, false) } // Expect a block item node. func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { if first { if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { return false } } if event.typ == yaml_SEQUENCE_END_EVENT { emitter.indent = emitter.indents[len(emitter.indents)-1] emitter.indents = emitter.indents[:len(emitter.indents)-1] emitter.state = emitter.states[len(emitter.states)-1] emitter.states = emitter.states[:len(emitter.states)-1] return true } if !yaml_emitter_write_indent(emitter) { return false } if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { return false } emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) return yaml_emitter_emit_node(emitter, event, false, true, false, false) } // Expect a block key node. func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { if first { if !yaml_emitter_increase_indent(emitter, false, false) { return false } } if event.typ == yaml_MAPPING_END_EVENT { emitter.indent = emitter.indents[len(emitter.indents)-1] emitter.indents = emitter.indents[:len(emitter.indents)-1] emitter.state = emitter.states[len(emitter.states)-1] emitter.states = emitter.states[:len(emitter.states)-1] return true } if !yaml_emitter_write_indent(emitter) { return false } if yaml_emitter_check_simple_key(emitter) { emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) return yaml_emitter_emit_node(emitter, event, false, false, true, true) } if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { return false } emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) return yaml_emitter_emit_node(emitter, event, false, false, true, false) } // Expect a block value node. func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { if simple { if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { return false } } else { if !yaml_emitter_write_indent(emitter) { return false } if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { return false } } emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) return yaml_emitter_emit_node(emitter, event, false, false, true, false) } // Expect a node. func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, root bool, sequence bool, mapping bool, simple_key bool) bool { emitter.root_context = root emitter.sequence_context = sequence emitter.mapping_context = mapping emitter.simple_key_context = simple_key switch event.typ { case yaml_ALIAS_EVENT: return yaml_emitter_emit_alias(emitter, event) case yaml_SCALAR_EVENT: return yaml_emitter_emit_scalar(emitter, event) case yaml_SEQUENCE_START_EVENT: return yaml_emitter_emit_sequence_start(emitter, event) case yaml_MAPPING_START_EVENT: return yaml_emitter_emit_mapping_start(emitter, event) default: return yaml_emitter_set_emitter_error(emitter, "expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS") } } // Expect ALIAS. func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { if !yaml_emitter_process_anchor(emitter) { return false } emitter.state = emitter.states[len(emitter.states)-1] emitter.states = emitter.states[:len(emitter.states)-1] return true } // Expect SCALAR. func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { if !yaml_emitter_select_scalar_style(emitter, event) { return false } if !yaml_emitter_process_anchor(emitter) { return false } if !yaml_emitter_process_tag(emitter) { return false } if !yaml_emitter_increase_indent(emitter, true, false) { return false } if !yaml_emitter_process_scalar(emitter) { return false } emitter.indent = emitter.indents[len(emitter.indents)-1] emitter.indents = emitter.indents[:len(emitter.indents)-1] emitter.state = emitter.states[len(emitter.states)-1] emitter.states = emitter.states[:len(emitter.states)-1] return true } // Expect SEQUENCE-START. func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { if !yaml_emitter_process_anchor(emitter) { return false } if !yaml_emitter_process_tag(emitter) { return false } if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || yaml_emitter_check_empty_sequence(emitter) { emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE } else { emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE } return true } // Expect MAPPING-START. func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { if !yaml_emitter_process_anchor(emitter) { return false } if !yaml_emitter_process_tag(emitter) { return false } if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || yaml_emitter_check_empty_mapping(emitter) { emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE } else { emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE } return true } // Check if the document content is an empty scalar. func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { return false // [Go] Huh? } // Check if the next events represent an empty sequence. func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { if len(emitter.events)-emitter.events_head < 2 { return false } return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT } // Check if the next events represent an empty mapping. func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { if len(emitter.events)-emitter.events_head < 2 { return false } return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT } // Check if the next node can be expressed as a simple key. func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { length := 0 switch emitter.events[emitter.events_head].typ { case yaml_ALIAS_EVENT: length += len(emitter.anchor_data.anchor) case yaml_SCALAR_EVENT: if emitter.scalar_data.multiline { return false } length += len(emitter.anchor_data.anchor) + len(emitter.tag_data.handle) + len(emitter.tag_data.suffix) + len(emitter.scalar_data.value) case yaml_SEQUENCE_START_EVENT: if !yaml_emitter_check_empty_sequence(emitter) { return false } length += len(emitter.anchor_data.anchor) + len(emitter.tag_data.handle) + len(emitter.tag_data.suffix) case yaml_MAPPING_START_EVENT: if !yaml_emitter_check_empty_mapping(emitter) { return false } length += len(emitter.anchor_data.anchor) + len(emitter.tag_data.handle) + len(emitter.tag_data.suffix) default: return false } return length <= 128 } // Determine an acceptable scalar style. func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 if no_tag && !event.implicit && !event.quoted_implicit { return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") } style := event.scalar_style() if style == yaml_ANY_SCALAR_STYLE { style = yaml_PLAIN_SCALAR_STYLE } if emitter.canonical { style = yaml_DOUBLE_QUOTED_SCALAR_STYLE } if emitter.simple_key_context && emitter.scalar_data.multiline { style = yaml_DOUBLE_QUOTED_SCALAR_STYLE } if style == yaml_PLAIN_SCALAR_STYLE { if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { style = yaml_SINGLE_QUOTED_SCALAR_STYLE } if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { style = yaml_SINGLE_QUOTED_SCALAR_STYLE } if no_tag && !event.implicit { style = yaml_SINGLE_QUOTED_SCALAR_STYLE } } if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { if !emitter.scalar_data.single_quoted_allowed { style = yaml_DOUBLE_QUOTED_SCALAR_STYLE } } if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { style = yaml_DOUBLE_QUOTED_SCALAR_STYLE } } if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { emitter.tag_data.handle = []byte{'!'} } emitter.scalar_data.style = style return true } // Write an achor. func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { if emitter.anchor_data.anchor == nil { return true } c := []byte{'&'} if emitter.anchor_data.alias { c[0] = '*' } if !yaml_emitter_write_indicator(emitter, c, true, false, false) { return false } return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) } // Write a tag. func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { return true } if len(emitter.tag_data.handle) > 0 { if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { return false } if len(emitter.tag_data.suffix) > 0 { if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { return false } } } else { // [Go] Allocate these slices elsewhere. if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { return false } if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { return false } if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { return false } } return true } // Write a scalar. func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { switch emitter.scalar_data.style { case yaml_PLAIN_SCALAR_STYLE: return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_SINGLE_QUOTED_SCALAR_STYLE: return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_DOUBLE_QUOTED_SCALAR_STYLE: return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) case yaml_LITERAL_SCALAR_STYLE: return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) case yaml_FOLDED_SCALAR_STYLE: return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) } panic("unknown scalar style") } // Check if a %YAML directive is valid. func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { if version_directive.major != 1 || version_directive.minor != 1 { return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") } return true } // Check if a %TAG directive is valid. func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { handle := tag_directive.handle prefix := tag_directive.prefix if len(handle) == 0 { return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") } if handle[0] != '!' { return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") } if handle[len(handle)-1] != '!' { return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") } for i := 1; i < len(handle)-1; i += width(handle[i]) { if !is_alpha(handle, i) { return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") } } if len(prefix) == 0 { return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") } return true } // Check if an anchor is valid. func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { if len(anchor) == 0 { problem := "anchor value must not be empty" if alias { problem = "alias value must not be empty" } return yaml_emitter_set_emitter_error(emitter, problem) } for i := 0; i < len(anchor); i += width(anchor[i]) { if !is_alpha(anchor, i) { problem := "anchor value must contain alphanumerical characters only" if alias { problem = "alias value must contain alphanumerical characters only" } return yaml_emitter_set_emitter_error(emitter, problem) } } emitter.anchor_data.anchor = anchor emitter.anchor_data.alias = alias return true } // Check if a tag is valid. func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { if len(tag) == 0 { return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") } for i := 0; i < len(emitter.tag_directives); i++ { tag_directive := &emitter.tag_directives[i] if bytes.HasPrefix(tag, tag_directive.prefix) { emitter.tag_data.handle = tag_directive.handle emitter.tag_data.suffix = tag[len(tag_directive.prefix):] return true } } emitter.tag_data.suffix = tag return true } // Check if a scalar is valid. func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { var ( block_indicators = false flow_indicators = false line_breaks = false special_characters = false leading_space = false leading_break = false trailing_space = false trailing_break = false break_space = false space_break = false preceded_by_whitespace = false followed_by_whitespace = false previous_space = false previous_break = false ) emitter.scalar_data.value = value if len(value) == 0 { emitter.scalar_data.multiline = false emitter.scalar_data.flow_plain_allowed = false emitter.scalar_data.block_plain_allowed = true emitter.scalar_data.single_quoted_allowed = true emitter.scalar_data.block_allowed = false return true } if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { block_indicators = true flow_indicators = true } preceded_by_whitespace = true for i, w := 0, 0; i < len(value); i += w { w = width(value[i]) followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) if i == 0 { switch value[i] { case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': flow_indicators = true block_indicators = true case '?', ':': flow_indicators = true if followed_by_whitespace { block_indicators = true } case '-': if followed_by_whitespace { flow_indicators = true block_indicators = true } } } else { switch value[i] { case ',', '?', '[', ']', '{', '}': flow_indicators = true case ':': flow_indicators = true if followed_by_whitespace { block_indicators = true } case '#': if preceded_by_whitespace { flow_indicators = true block_indicators = true } } } if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { special_characters = true } if is_space(value, i) { if i == 0 { leading_space = true } if i+width(value[i]) == len(value) { trailing_space = true } if previous_break { break_space = true } previous_space = true previous_break = false } else if is_break(value, i) { line_breaks = true if i == 0 { leading_break = true } if i+width(value[i]) == len(value) { trailing_break = true } if previous_space { space_break = true } previous_space = false previous_break = true } else { previous_space = false previous_break = false } // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. preceded_by_whitespace = is_blankz(value, i) } emitter.scalar_data.multiline = line_breaks emitter.scalar_data.flow_plain_allowed = true emitter.scalar_data.block_plain_allowed = true emitter.scalar_data.single_quoted_allowed = true emitter.scalar_data.block_allowed = true if leading_space || leading_break || trailing_space || trailing_break { emitter.scalar_data.flow_plain_allowed = false emitter.scalar_data.block_plain_allowed = false } if trailing_space { emitter.scalar_data.block_allowed = false } if break_space { emitter.scalar_data.flow_plain_allowed = false emitter.scalar_data.block_plain_allowed = false emitter.scalar_data.single_quoted_allowed = false } if space_break || special_characters { emitter.scalar_data.flow_plain_allowed = false emitter.scalar_data.block_plain_allowed = false emitter.scalar_data.single_quoted_allowed = false emitter.scalar_data.block_allowed = false } if line_breaks { emitter.scalar_data.flow_plain_allowed = false emitter.scalar_data.block_plain_allowed = false } if flow_indicators { emitter.scalar_data.flow_plain_allowed = false } if block_indicators { emitter.scalar_data.block_plain_allowed = false } return true } // Check if the event data is valid. func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { emitter.anchor_data.anchor = nil emitter.tag_data.handle = nil emitter.tag_data.suffix = nil emitter.scalar_data.value = nil switch event.typ { case yaml_ALIAS_EVENT: if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { return false } case yaml_SCALAR_EVENT: if len(event.anchor) > 0 { if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { return false } } if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { if !yaml_emitter_analyze_tag(emitter, event.tag) { return false } } if !yaml_emitter_analyze_scalar(emitter, event.value) { return false } case yaml_SEQUENCE_START_EVENT: if len(event.anchor) > 0 { if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { return false } } if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { if !yaml_emitter_analyze_tag(emitter, event.tag) { return false } } case yaml_MAPPING_START_EVENT: if len(event.anchor) > 0 { if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { return false } } if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { if !yaml_emitter_analyze_tag(emitter, event.tag) { return false } } } return true } // Write the BOM character. func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { if !flush(emitter) { return false } pos := emitter.buffer_pos emitter.buffer[pos+0] = '\xEF' emitter.buffer[pos+1] = '\xBB' emitter.buffer[pos+2] = '\xBF' emitter.buffer_pos += 3 return true } func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { indent := emitter.indent if indent < 0 { indent = 0 } if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { if !put_break(emitter) { return false } } for emitter.column < indent { if !put(emitter, ' ') { return false } } emitter.whitespace = true emitter.indention = true return true } func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { if need_whitespace && !emitter.whitespace { if !put(emitter, ' ') { return false } } if !write_all(emitter, indicator) { return false } emitter.whitespace = is_whitespace emitter.indention = (emitter.indention && is_indention) emitter.open_ended = false return true } func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { if !write_all(emitter, value) { return false } emitter.whitespace = false emitter.indention = false return true } func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { if !emitter.whitespace { if !put(emitter, ' ') { return false } } if !write_all(emitter, value) { return false } emitter.whitespace = false emitter.indention = false return true } func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { if need_whitespace && !emitter.whitespace { if !put(emitter, ' ') { return false } } for i := 0; i < len(value); { var must_write bool switch value[i] { case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': must_write = true default: must_write = is_alpha(value, i) } if must_write { if !write(emitter, value, &i) { return false } } else { w := width(value[i]) for k := 0; k < w; k++ { octet := value[i] i++ if !put(emitter, '%') { return false } c := octet >> 4 if c < 10 { c += '0' } else { c += 'A' - 10 } if !put(emitter, c) { return false } c = octet & 0x0f if c < 10 { c += '0' } else { c += 'A' - 10 } if !put(emitter, c) { return false } } } } emitter.whitespace = false emitter.indention = false return true } func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { if !emitter.whitespace { if !put(emitter, ' ') { return false } } spaces := false breaks := false for i := 0; i < len(value); { if is_space(value, i) { if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { if !yaml_emitter_write_indent(emitter) { return false } i += width(value[i]) } else { if !write(emitter, value, &i) { return false } } spaces = true } else if is_break(value, i) { if !breaks && value[i] == '\n' { if !put_break(emitter) { return false } } if !write_break(emitter, value, &i) { return false } emitter.indention = true breaks = true } else { if breaks { if !yaml_emitter_write_indent(emitter) { return false } } if !write(emitter, value, &i) { return false } emitter.indention = false spaces = false breaks = false } } emitter.whitespace = false emitter.indention = false if emitter.root_context { emitter.open_ended = true } return true } func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { return false } spaces := false breaks := false for i := 0; i < len(value); { if is_space(value, i) { if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { if !yaml_emitter_write_indent(emitter) { return false } i += width(value[i]) } else { if !write(emitter, value, &i) { return false } } spaces = true } else if is_break(value, i) { if !breaks && value[i] == '\n' { if !put_break(emitter) { return false } } if !write_break(emitter, value, &i) { return false } emitter.indention = true breaks = true } else { if breaks { if !yaml_emitter_write_indent(emitter) { return false } } if value[i] == '\'' { if !put(emitter, '\'') { return false } } if !write(emitter, value, &i) { return false } emitter.indention = false spaces = false breaks = false } } if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { return false } emitter.whitespace = false emitter.indention = false return true } func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { spaces := false if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { return false } for i := 0; i < len(value); { if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || is_bom(value, i) || is_break(value, i) || value[i] == '"' || value[i] == '\\' { octet := value[i] var w int var v rune switch { case octet&0x80 == 0x00: w, v = 1, rune(octet&0x7F) case octet&0xE0 == 0xC0: w, v = 2, rune(octet&0x1F) case octet&0xF0 == 0xE0: w, v = 3, rune(octet&0x0F) case octet&0xF8 == 0xF0: w, v = 4, rune(octet&0x07) } for k := 1; k < w; k++ { octet = value[i+k] v = (v << 6) + (rune(octet) & 0x3F) } i += w if !put(emitter, '\\') { return false } var ok bool switch v { case 0x00: ok = put(emitter, '0') case 0x07: ok = put(emitter, 'a') case 0x08: ok = put(emitter, 'b') case 0x09: ok = put(emitter, 't') case 0x0A: ok = put(emitter, 'n') case 0x0b: ok = put(emitter, 'v') case 0x0c: ok = put(emitter, 'f') case 0x0d: ok = put(emitter, 'r') case 0x1b: ok = put(emitter, 'e') case 0x22: ok = put(emitter, '"') case 0x5c: ok = put(emitter, '\\') case 0x85: ok = put(emitter, 'N') case 0xA0: ok = put(emitter, '_') case 0x2028: ok = put(emitter, 'L') case 0x2029: ok = put(emitter, 'P') default: if v <= 0xFF { ok = put(emitter, 'x') w = 2 } else if v <= 0xFFFF { ok = put(emitter, 'u') w = 4 } else { ok = put(emitter, 'U') w = 8 } for k := (w - 1) * 4; ok && k >= 0; k -= 4 { digit := byte((v >> uint(k)) & 0x0F) if digit < 10 { ok = put(emitter, digit+'0') } else { ok = put(emitter, digit+'A'-10) } } } if !ok { return false } spaces = false } else if is_space(value, i) { if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { if !yaml_emitter_write_indent(emitter) { return false } if is_space(value, i+1) { if !put(emitter, '\\') { return false } } i += width(value[i]) } else if !write(emitter, value, &i) { return false } spaces = true } else { if !write(emitter, value, &i) { return false } spaces = false } } if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { return false } emitter.whitespace = false emitter.indention = false return true } func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { if is_space(value, 0) || is_break(value, 0) { indent_hint := []byte{'0' + byte(emitter.best_indent)} if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { return false } } emitter.open_ended = false var chomp_hint [1]byte if len(value) == 0 { chomp_hint[0] = '-' } else { i := len(value) - 1 for value[i]&0xC0 == 0x80 { i-- } if !is_break(value, i) { chomp_hint[0] = '-' } else if i == 0 { chomp_hint[0] = '+' emitter.open_ended = true } else { i-- for value[i]&0xC0 == 0x80 { i-- } if is_break(value, i) { chomp_hint[0] = '+' emitter.open_ended = true } } } if chomp_hint[0] != 0 { if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { return false } } return true } func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { return false } if !yaml_emitter_write_block_scalar_hints(emitter, value) { return false } if !put_break(emitter) { return false } emitter.indention = true emitter.whitespace = true breaks := true for i := 0; i < len(value); { if is_break(value, i) { if !write_break(emitter, value, &i) { return false } emitter.indention = true breaks = true } else { if breaks { if !yaml_emitter_write_indent(emitter) { return false } } if !write(emitter, value, &i) { return false } emitter.indention = false breaks = false } } return true } func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { return false } if !yaml_emitter_write_block_scalar_hints(emitter, value) { return false } if !put_break(emitter) { return false } emitter.indention = true emitter.whitespace = true breaks := true leading_spaces := true for i := 0; i < len(value); { if is_break(value, i) { if !breaks && !leading_spaces && value[i] == '\n' { k := 0 for is_break(value, k) { k += width(value[k]) } if !is_blankz(value, k) { if !put_break(emitter) { return false } } } if !write_break(emitter, value, &i) { return false } emitter.indention = true breaks = true } else { if breaks { if !yaml_emitter_write_indent(emitter) { return false } leading_spaces = is_blank(value, i) } if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { if !yaml_emitter_write_indent(emitter) { return false } i += width(value[i]) } else { if !write(emitter, value, &i) { return false } } emitter.indention = false breaks = false } } return true } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/decode_test.go�������������������������������������������������0000644�0610621�0607500�00000054364�13172163307�023056� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml_test import ( "errors" . "gopkg.in/check.v1" "gopkg.in/yaml.v2" "math" "net" "reflect" "strings" "time" ) var unmarshalIntTest = 123 var unmarshalTests = []struct { data string value interface{} }{ { "", &struct{}{}, }, { "{}", &struct{}{}, }, { "v: hi", map[string]string{"v": "hi"}, }, { "v: hi", map[string]interface{}{"v": "hi"}, }, { "v: true", map[string]string{"v": "true"}, }, { "v: true", map[string]interface{}{"v": true}, }, { "v: 10", map[string]interface{}{"v": 10}, }, { "v: 0b10", map[string]interface{}{"v": 2}, }, { "v: 0xA", map[string]interface{}{"v": 10}, }, { "v: 4294967296", map[string]int64{"v": 4294967296}, }, { "v: 0.1", map[string]interface{}{"v": 0.1}, }, { "v: .1", map[string]interface{}{"v": 0.1}, }, { "v: .Inf", map[string]interface{}{"v": math.Inf(+1)}, }, { "v: -.Inf", map[string]interface{}{"v": math.Inf(-1)}, }, { "v: -10", map[string]interface{}{"v": -10}, }, { "v: -.1", map[string]interface{}{"v": -0.1}, }, // Simple values. { "123", &unmarshalIntTest, }, // Floats from spec { "canonical: 6.8523e+5", map[string]interface{}{"canonical": 6.8523e+5}, }, { "expo: 685.230_15e+03", map[string]interface{}{"expo": 685.23015e+03}, }, { "fixed: 685_230.15", map[string]interface{}{"fixed": 685230.15}, }, { "neginf: -.inf", map[string]interface{}{"neginf": math.Inf(-1)}, }, { "fixed: 685_230.15", map[string]float64{"fixed": 685230.15}, }, //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails. // Bools from spec { "canonical: y", map[string]interface{}{"canonical": true}, }, { "answer: NO", map[string]interface{}{"answer": false}, }, { "logical: True", map[string]interface{}{"logical": true}, }, { "option: on", map[string]interface{}{"option": true}, }, { "option: on", map[string]bool{"option": true}, }, // Ints from spec { "canonical: 685230", map[string]interface{}{"canonical": 685230}, }, { "decimal: +685_230", map[string]interface{}{"decimal": 685230}, }, { "octal: 02472256", map[string]interface{}{"octal": 685230}, }, { "hexa: 0x_0A_74_AE", map[string]interface{}{"hexa": 685230}, }, { "bin: 0b1010_0111_0100_1010_1110", map[string]interface{}{"bin": 685230}, }, { "bin: -0b101010", map[string]interface{}{"bin": -42}, }, { "decimal: +685_230", map[string]int{"decimal": 685230}, }, //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported // Nulls from spec { "empty:", map[string]interface{}{"empty": nil}, }, { "canonical: ~", map[string]interface{}{"canonical": nil}, }, { "english: null", map[string]interface{}{"english": nil}, }, { "~: null key", map[interface{}]string{nil: "null key"}, }, { "empty:", map[string]*bool{"empty": nil}, }, // Flow sequence { "seq: [A,B]", map[string]interface{}{"seq": []interface{}{"A", "B"}}, }, { "seq: [A,B,C,]", map[string][]string{"seq": []string{"A", "B", "C"}}, }, { "seq: [A,1,C]", map[string][]string{"seq": []string{"A", "1", "C"}}, }, { "seq: [A,1,C]", map[string][]int{"seq": []int{1}}, }, { "seq: [A,1,C]", map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, }, // Block sequence { "seq:\n - A\n - B", map[string]interface{}{"seq": []interface{}{"A", "B"}}, }, { "seq:\n - A\n - B\n - C", map[string][]string{"seq": []string{"A", "B", "C"}}, }, { "seq:\n - A\n - 1\n - C", map[string][]string{"seq": []string{"A", "1", "C"}}, }, { "seq:\n - A\n - 1\n - C", map[string][]int{"seq": []int{1}}, }, { "seq:\n - A\n - 1\n - C", map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, }, // Literal block scalar { "scalar: | # Comment\n\n literal\n\n \ttext\n\n", map[string]string{"scalar": "\nliteral\n\n\ttext\n"}, }, // Folded block scalar { "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n", map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"}, }, // Map inside interface with no type hints. { "a: {b: c}", map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, }, // Structs and type conversions. { "hello: world", &struct{ Hello string }{"world"}, }, { "a: {b: c}", &struct{ A struct{ B string } }{struct{ B string }{"c"}}, }, { "a: {b: c}", &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}, }, { "a: {b: c}", &struct{ A map[string]string }{map[string]string{"b": "c"}}, }, { "a: {b: c}", &struct{ A *map[string]string }{&map[string]string{"b": "c"}}, }, { "a:", &struct{ A map[string]string }{}, }, { "a: 1", &struct{ A int }{1}, }, { "a: 1", &struct{ A float64 }{1}, }, { "a: 1.0", &struct{ A int }{1}, }, { "a: 1.0", &struct{ A uint }{1}, }, { "a: [1, 2]", &struct{ A []int }{[]int{1, 2}}, }, { "a: 1", &struct{ B int }{0}, }, { "a: 1", &struct { B int "a" }{1}, }, { "a: y", &struct{ A bool }{true}, }, // Some cross type conversions { "v: 42", map[string]uint{"v": 42}, }, { "v: -42", map[string]uint{}, }, { "v: 4294967296", map[string]uint64{"v": 4294967296}, }, { "v: -4294967296", map[string]uint64{}, }, // int { "int_max: 2147483647", map[string]int{"int_max": math.MaxInt32}, }, { "int_min: -2147483648", map[string]int{"int_min": math.MinInt32}, }, { "int_overflow: 9223372036854775808", // math.MaxInt64 + 1 map[string]int{}, }, // int64 { "int64_max: 9223372036854775807", map[string]int64{"int64_max": math.MaxInt64}, }, { "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111", map[string]int64{"int64_max_base2": math.MaxInt64}, }, { "int64_min: -9223372036854775808", map[string]int64{"int64_min": math.MinInt64}, }, { "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111", map[string]int64{"int64_neg_base2": -math.MaxInt64}, }, { "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1 map[string]int64{}, }, // uint { "uint_min: 0", map[string]uint{"uint_min": 0}, }, { "uint_max: 4294967295", map[string]uint{"uint_max": math.MaxUint32}, }, { "uint_underflow: -1", map[string]uint{}, }, // uint64 { "uint64_min: 0", map[string]uint{"uint64_min": 0}, }, { "uint64_max: 18446744073709551615", map[string]uint64{"uint64_max": math.MaxUint64}, }, { "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111", map[string]uint64{"uint64_max_base2": math.MaxUint64}, }, { "uint64_maxint64: 9223372036854775807", map[string]uint64{"uint64_maxint64": math.MaxInt64}, }, { "uint64_underflow: -1", map[string]uint64{}, }, // float32 { "float32_max: 3.40282346638528859811704183484516925440e+38", map[string]float32{"float32_max": math.MaxFloat32}, }, { "float32_nonzero: 1.401298464324817070923729583289916131280e-45", map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32}, }, { "float32_maxuint64: 18446744073709551615", map[string]float32{"float32_maxuint64": float32(math.MaxUint64)}, }, { "float32_maxuint64+1: 18446744073709551616", map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)}, }, // float64 { "float64_max: 1.797693134862315708145274237317043567981e+308", map[string]float64{"float64_max": math.MaxFloat64}, }, { "float64_nonzero: 4.940656458412465441765687928682213723651e-324", map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64}, }, { "float64_maxuint64: 18446744073709551615", map[string]float64{"float64_maxuint64": float64(math.MaxUint64)}, }, { "float64_maxuint64+1: 18446744073709551616", map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)}, }, // Overflow cases. { "v: 4294967297", map[string]int32{}, }, { "v: 128", map[string]int8{}, }, // Quoted values. { "'1': '\"2\"'", map[interface{}]interface{}{"1": "\"2\""}, }, { "v:\n- A\n- 'B\n\n C'\n", map[string][]string{"v": []string{"A", "B\nC"}}, }, // Explicit tags. { "v: !!float '1.1'", map[string]interface{}{"v": 1.1}, }, { "v: !!null ''", map[string]interface{}{"v": nil}, }, { "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'", map[string]interface{}{"v": 1}, }, // Non-specific tag (Issue #75) { "v: ! test", map[string]interface{}{"v": "test"}, }, // Anchors and aliases. { "a: &x 1\nb: &y 2\nc: *x\nd: *y\n", &struct{ A, B, C, D int }{1, 2, 1, 2}, }, { "a: &a {c: 1}\nb: *a", &struct { A, B struct { C int } }{struct{ C int }{1}, struct{ C int }{1}}, }, { "a: &a [1, 2]\nb: *a", &struct{ B []int }{[]int{1, 2}}, }, { "b: *a\na: &a {c: 1}", &struct { A, B struct { C int } }{struct{ C int }{1}, struct{ C int }{1}}, }, // Bug #1133337 { "foo: ''", map[string]*string{"foo": new(string)}, }, { "foo: null", map[string]string{"foo": ""}, }, { "foo: null", map[string]interface{}{"foo": nil}, }, // Ignored field { "a: 1\nb: 2\n", &struct { A int B int "-" }{1, 0}, }, // Bug #1191981 { "" + "%YAML 1.1\n" + "--- !!str\n" + `"Generic line break (no glyph)\n\` + "\n" + ` Generic line break (glyphed)\n\` + "\n" + ` Line separator\u2028\` + "\n" + ` Paragraph separator\u2029"` + "\n", "" + "Generic line break (no glyph)\n" + "Generic line break (glyphed)\n" + "Line separator\u2028Paragraph separator\u2029", }, // Struct inlining { "a: 1\nb: 2\nc: 3\n", &struct { A int C inlineB `yaml:",inline"` }{1, inlineB{2, inlineC{3}}}, }, // Map inlining { "a: 1\nb: 2\nc: 3\n", &struct { A int C map[string]int `yaml:",inline"` }{1, map[string]int{"b": 2, "c": 3}}, }, // bug 1243827 { "a: -b_c", map[string]interface{}{"a": "-b_c"}, }, { "a: +b_c", map[string]interface{}{"a": "+b_c"}, }, { "a: 50cent_of_dollar", map[string]interface{}{"a": "50cent_of_dollar"}, }, // Duration { "a: 3s", map[string]time.Duration{"a": 3 * time.Second}, }, // Issue #24. { "a: <foo>", map[string]string{"a": "<foo>"}, }, // Base 60 floats are obsolete and unsupported. { "a: 1:1\n", map[string]string{"a": "1:1"}, }, // Binary data. { "a: !!binary gIGC\n", map[string]string{"a": "\x80\x81\x82"}, }, { "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", map[string]string{"a": strings.Repeat("\x90", 54)}, }, { "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n", map[string]string{"a": strings.Repeat("\x00", 52)}, }, // Ordered maps. { "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}", &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, }, // Issue #39. { "a:\n b:\n c: d\n", map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}}, }, // Custom map type. { "a: {b: c}", M{"a": M{"b": "c"}}, }, // Support encoding.TextUnmarshaler. { "a: 1.2.3.4\n", map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, }, { "a: 2015-02-24T18:19:39Z\n", map[string]time.Time{"a": time.Unix(1424801979, 0).In(time.UTC)}, }, // Encode empty lists as zero-length slices. { "a: []", &struct{ A []int }{[]int{}}, }, // UTF-16-LE { "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00", M{"ñoño": "very yes"}, }, // UTF-16-LE with surrogate. { "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00", M{"ñoño": "very yes 🟔"}, }, // UTF-16-BE { "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n", M{"ñoño": "very yes"}, }, // UTF-16-BE with surrogate. { "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n", M{"ñoño": "very yes 🟔"}, }, // YAML Float regex shouldn't match this { "a: 123456e1\n", M{"a": "123456e1"}, }, { "a: 123456E1\n", M{"a": "123456E1"}, }, } type M map[interface{}]interface{} type inlineB struct { B int inlineC `yaml:",inline"` } type inlineC struct { C int } func (s *S) TestUnmarshal(c *C) { for i, item := range unmarshalTests { c.Logf("test %d: %q", i, item.data) t := reflect.ValueOf(item.value).Type() var value interface{} switch t.Kind() { case reflect.Map: value = reflect.MakeMap(t).Interface() case reflect.String: value = reflect.New(t).Interface() case reflect.Ptr: value = reflect.New(t.Elem()).Interface() default: c.Fatalf("missing case for %s", t) } err := yaml.Unmarshal([]byte(item.data), value) if _, ok := err.(*yaml.TypeError); !ok { c.Assert(err, IsNil) } if t.Kind() == reflect.String { c.Assert(*value.(*string), Equals, item.value) } else { c.Assert(value, DeepEquals, item.value) } } } func (s *S) TestUnmarshalNaN(c *C) { value := map[string]interface{}{} err := yaml.Unmarshal([]byte("notanum: .NaN"), &value) c.Assert(err, IsNil) c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true) } var unmarshalErrorTests = []struct { data, error string }{ {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"}, {"v: [A,", "yaml: line 1: did not find expected node content"}, {"v:\n- [A,", "yaml: line 2: did not find expected node content"}, {"a: *b\n", "yaml: unknown anchor 'b' referenced"}, {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"}, {"value: -", "yaml: block sequence entries are not allowed in this context"}, {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"}, {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`}, {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`}, {"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"}, } func (s *S) TestUnmarshalErrors(c *C) { for _, item := range unmarshalErrorTests { var value interface{} err := yaml.Unmarshal([]byte(item.data), &value) c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value)) } } var unmarshalerTests = []struct { data, tag string value interface{} }{ {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}}, {"_: [1,A]", "!!seq", []interface{}{1, "A"}}, {"_: 10", "!!int", 10}, {"_: null", "!!null", nil}, {`_: BAR!`, "!!str", "BAR!"}, {`_: "BAR!"`, "!!str", "BAR!"}, {"_: !!foo 'BAR!'", "!!foo", "BAR!"}, {`_: ""`, "!!str", ""}, } var unmarshalerResult = map[int]error{} type unmarshalerType struct { value interface{} } func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error { if err := unmarshal(&o.value); err != nil { return err } if i, ok := o.value.(int); ok { if result, ok := unmarshalerResult[i]; ok { return result } } return nil } type unmarshalerPointer struct { Field *unmarshalerType "_" } type unmarshalerValue struct { Field unmarshalerType "_" } func (s *S) TestUnmarshalerPointerField(c *C) { for _, item := range unmarshalerTests { obj := &unmarshalerPointer{} err := yaml.Unmarshal([]byte(item.data), obj) c.Assert(err, IsNil) if item.value == nil { c.Assert(obj.Field, IsNil) } else { c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) c.Assert(obj.Field.value, DeepEquals, item.value) } } } func (s *S) TestUnmarshalerValueField(c *C) { for _, item := range unmarshalerTests { obj := &unmarshalerValue{} err := yaml.Unmarshal([]byte(item.data), obj) c.Assert(err, IsNil) c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) c.Assert(obj.Field.value, DeepEquals, item.value) } } func (s *S) TestUnmarshalerWholeDocument(c *C) { obj := &unmarshalerType{} err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj) c.Assert(err, IsNil) value, ok := obj.value.(map[interface{}]interface{}) c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value)) c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value) } func (s *S) TestUnmarshalerTypeError(c *C) { unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}} unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}} defer func() { delete(unmarshalerResult, 2) delete(unmarshalerResult, 4) }() type T struct { Before int After int M map[string]*unmarshalerType } var v T data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}` err := yaml.Unmarshal([]byte(data), &v) c.Assert(err, ErrorMatches, ""+ "yaml: unmarshal errors:\n"+ " line 1: cannot unmarshal !!str `A` into int\n"+ " foo\n"+ " bar\n"+ " line 1: cannot unmarshal !!str `B` into int") c.Assert(v.M["abc"], NotNil) c.Assert(v.M["def"], IsNil) c.Assert(v.M["ghi"], NotNil) c.Assert(v.M["jkl"], IsNil) c.Assert(v.M["abc"].value, Equals, 1) c.Assert(v.M["ghi"].value, Equals, 3) } type proxyTypeError struct{} func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error { var s string var a int32 var b int64 if err := unmarshal(&s); err != nil { panic(err) } if s == "a" { if err := unmarshal(&b); err == nil { panic("should have failed") } return unmarshal(&a) } if err := unmarshal(&a); err == nil { panic("should have failed") } return unmarshal(&b) } func (s *S) TestUnmarshalerTypeErrorProxying(c *C) { type T struct { Before int After int M map[string]*proxyTypeError } var v T data := `{before: A, m: {abc: a, def: b}, after: B}` err := yaml.Unmarshal([]byte(data), &v) c.Assert(err, ErrorMatches, ""+ "yaml: unmarshal errors:\n"+ " line 1: cannot unmarshal !!str `A` into int\n"+ " line 1: cannot unmarshal !!str `a` into int32\n"+ " line 1: cannot unmarshal !!str `b` into int64\n"+ " line 1: cannot unmarshal !!str `B` into int") } type failingUnmarshaler struct{} var failingErr = errors.New("failingErr") func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { return failingErr } func (s *S) TestUnmarshalerError(c *C) { err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{}) c.Assert(err, Equals, failingErr) } type sliceUnmarshaler []int func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { var slice []int err := unmarshal(&slice) if err == nil { *su = slice return nil } var intVal int err = unmarshal(&intVal) if err == nil { *su = []int{intVal} return nil } return err } func (s *S) TestUnmarshalerRetry(c *C) { var su sliceUnmarshaler err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su) c.Assert(err, IsNil) c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3})) err = yaml.Unmarshal([]byte("1"), &su) c.Assert(err, IsNil) c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1})) } // From http://yaml.org/type/merge.html var mergeTests = ` anchors: list: - &CENTER { "x": 1, "y": 2 } - &LEFT { "x": 0, "y": 2 } - &BIG { "r": 10 } - &SMALL { "r": 1 } # All the following maps are equal: plain: # Explicit keys "x": 1 "y": 2 "r": 10 label: center/big mergeOne: # Merge one map << : *CENTER "r": 10 label: center/big mergeMultiple: # Merge multiple maps << : [ *CENTER, *BIG ] label: center/big override: # Override << : [ *BIG, *LEFT, *SMALL ] "x": 1 label: center/big shortTag: # Explicit short merge tag !!merge "<<" : [ *CENTER, *BIG ] label: center/big longTag: # Explicit merge long tag !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ] label: center/big inlineMap: # Inlined map << : {"x": 1, "y": 2, "r": 10} label: center/big inlineSequenceMap: # Inlined map in sequence << : [ *CENTER, {"r": 10} ] label: center/big ` func (s *S) TestMerge(c *C) { var want = map[interface{}]interface{}{ "x": 1, "y": 2, "r": 10, "label": "center/big", } var m map[interface{}]interface{} err := yaml.Unmarshal([]byte(mergeTests), &m) c.Assert(err, IsNil) for name, test := range m { if name == "anchors" { continue } c.Assert(test, DeepEquals, want, Commentf("test %q failed", name)) } } func (s *S) TestMergeStruct(c *C) { type Data struct { X, Y, R int Label string } want := Data{1, 2, 10, "center/big"} var m map[string]Data err := yaml.Unmarshal([]byte(mergeTests), &m) c.Assert(err, IsNil) for name, test := range m { if name == "anchors" { continue } c.Assert(test, Equals, want, Commentf("test %q failed", name)) } } var unmarshalNullTests = []func() interface{}{ func() interface{} { var v interface{}; v = "v"; return &v }, func() interface{} { var s = "s"; return &s }, func() interface{} { var s = "s"; sptr := &s; return &sptr }, func() interface{} { var i = 1; return &i }, func() interface{} { var i = 1; iptr := &i; return &iptr }, func() interface{} { m := map[string]int{"s": 1}; return &m }, func() interface{} { m := map[string]int{"s": 1}; return m }, } func (s *S) TestUnmarshalNull(c *C) { for _, test := range unmarshalNullTests { item := test() zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface() err := yaml.Unmarshal([]byte("null"), item) c.Assert(err, IsNil) if reflect.TypeOf(item).Kind() == reflect.Map { c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface()) } else { c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero) } } } func (s *S) TestUnmarshalSliceOnPreset(c *C) { // Issue #48. v := struct{ A []int }{[]int{1}} yaml.Unmarshal([]byte("a: [2]"), &v) c.Assert(v.A, DeepEquals, []int{2}) } func (s *S) TestUnmarshalStrict(c *C) { v := struct{ A, B int }{} err := yaml.UnmarshalStrict([]byte("a: 1\nb: 2"), &v) c.Check(err, IsNil) err = yaml.Unmarshal([]byte("a: 1\nb: 2\nc: 3"), &v) c.Check(err, IsNil) err = yaml.UnmarshalStrict([]byte("a: 1\nb: 2\nc: 3"), &v) c.Check(err, ErrorMatches, "yaml: unmarshal errors:\n line 1: field c not found in struct struct { A int; B int }") } //var data []byte //func init() { // var err error // data, err = ioutil.ReadFile("/tmp/file.yaml") // if err != nil { // panic(err) // } //} // //func (s *S) BenchmarkUnmarshal(c *C) { // var err error // for i := 0; i < c.N; i++ { // var v map[string]interface{} // err = yaml.Unmarshal(data, &v) // } // if err != nil { // panic(err) // } //} // //func (s *S) BenchmarkMarshal(c *C) { // var v map[string]interface{} // yaml.Unmarshal(data, &v) // c.ResetTimer() // for i := 0; i < c.N; i++ { // yaml.Marshal(&v) // } //} ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/decode.go������������������������������������������������������0000644�0610621�0607500�00000036427�13172163307�022017� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "encoding" "encoding/base64" "fmt" "math" "reflect" "strconv" "time" ) const ( documentNode = 1 << iota mappingNode sequenceNode scalarNode aliasNode ) type node struct { kind int line, column int tag string value string implicit bool children []*node anchors map[string]*node } // ---------------------------------------------------------------------------- // Parser, produces a node tree out of a libyaml event stream. type parser struct { parser yaml_parser_t event yaml_event_t doc *node } func newParser(b []byte) *parser { p := parser{} if !yaml_parser_initialize(&p.parser) { panic("failed to initialize YAML emitter") } if len(b) == 0 { b = []byte{'\n'} } yaml_parser_set_input_string(&p.parser, b) p.skip() if p.event.typ != yaml_STREAM_START_EVENT { panic("expected stream start event, got " + strconv.Itoa(int(p.event.typ))) } p.skip() return &p } func (p *parser) destroy() { if p.event.typ != yaml_NO_EVENT { yaml_event_delete(&p.event) } yaml_parser_delete(&p.parser) } func (p *parser) skip() { if p.event.typ != yaml_NO_EVENT { if p.event.typ == yaml_STREAM_END_EVENT { failf("attempted to go past the end of stream; corrupted value?") } yaml_event_delete(&p.event) } if !yaml_parser_parse(&p.parser, &p.event) { p.fail() } } func (p *parser) fail() { var where string var line int if p.parser.problem_mark.line != 0 { line = p.parser.problem_mark.line } else if p.parser.context_mark.line != 0 { line = p.parser.context_mark.line } if line != 0 { where = "line " + strconv.Itoa(line) + ": " } var msg string if len(p.parser.problem) > 0 { msg = p.parser.problem } else { msg = "unknown problem parsing YAML content" } failf("%s%s", where, msg) } func (p *parser) anchor(n *node, anchor []byte) { if anchor != nil { p.doc.anchors[string(anchor)] = n } } func (p *parser) parse() *node { switch p.event.typ { case yaml_SCALAR_EVENT: return p.scalar() case yaml_ALIAS_EVENT: return p.alias() case yaml_MAPPING_START_EVENT: return p.mapping() case yaml_SEQUENCE_START_EVENT: return p.sequence() case yaml_DOCUMENT_START_EVENT: return p.document() case yaml_STREAM_END_EVENT: // Happens when attempting to decode an empty buffer. return nil default: panic("attempted to parse unknown event: " + strconv.Itoa(int(p.event.typ))) } } func (p *parser) node(kind int) *node { return &node{ kind: kind, line: p.event.start_mark.line, column: p.event.start_mark.column, } } func (p *parser) document() *node { n := p.node(documentNode) n.anchors = make(map[string]*node) p.doc = n p.skip() n.children = append(n.children, p.parse()) if p.event.typ != yaml_DOCUMENT_END_EVENT { panic("expected end of document event but got " + strconv.Itoa(int(p.event.typ))) } p.skip() return n } func (p *parser) alias() *node { n := p.node(aliasNode) n.value = string(p.event.anchor) p.skip() return n } func (p *parser) scalar() *node { n := p.node(scalarNode) n.value = string(p.event.value) n.tag = string(p.event.tag) n.implicit = p.event.implicit p.anchor(n, p.event.anchor) p.skip() return n } func (p *parser) sequence() *node { n := p.node(sequenceNode) p.anchor(n, p.event.anchor) p.skip() for p.event.typ != yaml_SEQUENCE_END_EVENT { n.children = append(n.children, p.parse()) } p.skip() return n } func (p *parser) mapping() *node { n := p.node(mappingNode) p.anchor(n, p.event.anchor) p.skip() for p.event.typ != yaml_MAPPING_END_EVENT { n.children = append(n.children, p.parse(), p.parse()) } p.skip() return n } // ---------------------------------------------------------------------------- // Decoder, unmarshals a node into a provided value. type decoder struct { doc *node aliases map[string]bool mapType reflect.Type terrors []string strict bool } var ( mapItemType = reflect.TypeOf(MapItem{}) durationType = reflect.TypeOf(time.Duration(0)) defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) ifaceType = defaultMapType.Elem() ) func newDecoder(strict bool) *decoder { d := &decoder{mapType: defaultMapType, strict: strict} d.aliases = make(map[string]bool) return d } func (d *decoder) terror(n *node, tag string, out reflect.Value) { if n.tag != "" { tag = n.tag } value := n.value if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { if len(value) > 10 { value = " `" + value[:7] + "...`" } else { value = " `" + value + "`" } } d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type())) } func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { terrlen := len(d.terrors) err := u.UnmarshalYAML(func(v interface{}) (err error) { defer handleErr(&err) d.unmarshal(n, reflect.ValueOf(v)) if len(d.terrors) > terrlen { issues := d.terrors[terrlen:] d.terrors = d.terrors[:terrlen] return &TypeError{issues} } return nil }) if e, ok := err.(*TypeError); ok { d.terrors = append(d.terrors, e.Errors...) return false } if err != nil { fail(err) } return true } // d.prepare initializes and dereferences pointers and calls UnmarshalYAML // if a value is found to implement it. // It returns the initialized and dereferenced out value, whether // unmarshalling was already done by UnmarshalYAML, and if so whether // its types unmarshalled appropriately. // // If n holds a null value, prepare returns before doing anything. func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "" && n.implicit) { return out, false, false } again := true for again { again = false if out.Kind() == reflect.Ptr { if out.IsNil() { out.Set(reflect.New(out.Type().Elem())) } out = out.Elem() again = true } if out.CanAddr() { if u, ok := out.Addr().Interface().(Unmarshaler); ok { good = d.callUnmarshaler(n, u) return out, true, good } } } return out, false, false } func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) { switch n.kind { case documentNode: return d.document(n, out) case aliasNode: return d.alias(n, out) } out, unmarshaled, good := d.prepare(n, out) if unmarshaled { return good } switch n.kind { case scalarNode: good = d.scalar(n, out) case mappingNode: good = d.mapping(n, out) case sequenceNode: good = d.sequence(n, out) default: panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) } return good } func (d *decoder) document(n *node, out reflect.Value) (good bool) { if len(n.children) == 1 { d.doc = n d.unmarshal(n.children[0], out) return true } return false } func (d *decoder) alias(n *node, out reflect.Value) (good bool) { an, ok := d.doc.anchors[n.value] if !ok { failf("unknown anchor '%s' referenced", n.value) } if d.aliases[n.value] { failf("anchor '%s' value contains itself", n.value) } d.aliases[n.value] = true good = d.unmarshal(an, out) delete(d.aliases, n.value) return good } var zeroValue reflect.Value func resetMap(out reflect.Value) { for _, k := range out.MapKeys() { out.SetMapIndex(k, zeroValue) } } func (d *decoder) scalar(n *node, out reflect.Value) (good bool) { var tag string var resolved interface{} if n.tag == "" && !n.implicit { tag = yaml_STR_TAG resolved = n.value } else { tag, resolved = resolve(n.tag, n.value) if tag == yaml_BINARY_TAG { data, err := base64.StdEncoding.DecodeString(resolved.(string)) if err != nil { failf("!!binary value contains invalid base64 data") } resolved = string(data) } } if resolved == nil { if out.Kind() == reflect.Map && !out.CanAddr() { resetMap(out) } else { out.Set(reflect.Zero(out.Type())) } return true } if s, ok := resolved.(string); ok && out.CanAddr() { if u, ok := out.Addr().Interface().(encoding.TextUnmarshaler); ok { err := u.UnmarshalText([]byte(s)) if err != nil { fail(err) } return true } } switch out.Kind() { case reflect.String: if tag == yaml_BINARY_TAG { out.SetString(resolved.(string)) good = true } else if resolved != nil { out.SetString(n.value) good = true } case reflect.Interface: if resolved == nil { out.Set(reflect.Zero(out.Type())) } else { out.Set(reflect.ValueOf(resolved)) } good = true case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: switch resolved := resolved.(type) { case int: if !out.OverflowInt(int64(resolved)) { out.SetInt(int64(resolved)) good = true } case int64: if !out.OverflowInt(resolved) { out.SetInt(resolved) good = true } case uint64: if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { out.SetInt(int64(resolved)) good = true } case float64: if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { out.SetInt(int64(resolved)) good = true } case string: if out.Type() == durationType { d, err := time.ParseDuration(resolved) if err == nil { out.SetInt(int64(d)) good = true } } } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: switch resolved := resolved.(type) { case int: if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { out.SetUint(uint64(resolved)) good = true } case int64: if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { out.SetUint(uint64(resolved)) good = true } case uint64: if !out.OverflowUint(uint64(resolved)) { out.SetUint(uint64(resolved)) good = true } case float64: if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { out.SetUint(uint64(resolved)) good = true } } case reflect.Bool: switch resolved := resolved.(type) { case bool: out.SetBool(resolved) good = true } case reflect.Float32, reflect.Float64: switch resolved := resolved.(type) { case int: out.SetFloat(float64(resolved)) good = true case int64: out.SetFloat(float64(resolved)) good = true case uint64: out.SetFloat(float64(resolved)) good = true case float64: out.SetFloat(resolved) good = true } case reflect.Ptr: if out.Type().Elem() == reflect.TypeOf(resolved) { // TODO DOes this make sense? When is out a Ptr except when decoding a nil value? elem := reflect.New(out.Type().Elem()) elem.Elem().Set(reflect.ValueOf(resolved)) out.Set(elem) good = true } } if !good { d.terror(n, tag, out) } return good } func settableValueOf(i interface{}) reflect.Value { v := reflect.ValueOf(i) sv := reflect.New(v.Type()).Elem() sv.Set(v) return sv } func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { l := len(n.children) var iface reflect.Value switch out.Kind() { case reflect.Slice: out.Set(reflect.MakeSlice(out.Type(), l, l)) case reflect.Interface: // No type hints. Will have to use a generic sequence. iface = out out = settableValueOf(make([]interface{}, l)) default: d.terror(n, yaml_SEQ_TAG, out) return false } et := out.Type().Elem() j := 0 for i := 0; i < l; i++ { e := reflect.New(et).Elem() if ok := d.unmarshal(n.children[i], e); ok { out.Index(j).Set(e) j++ } } out.Set(out.Slice(0, j)) if iface.IsValid() { iface.Set(out) } return true } func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { switch out.Kind() { case reflect.Struct: return d.mappingStruct(n, out) case reflect.Slice: return d.mappingSlice(n, out) case reflect.Map: // okay case reflect.Interface: if d.mapType.Kind() == reflect.Map { iface := out out = reflect.MakeMap(d.mapType) iface.Set(out) } else { slicev := reflect.New(d.mapType).Elem() if !d.mappingSlice(n, slicev) { return false } out.Set(slicev) return true } default: d.terror(n, yaml_MAP_TAG, out) return false } outt := out.Type() kt := outt.Key() et := outt.Elem() mapType := d.mapType if outt.Key() == ifaceType && outt.Elem() == ifaceType { d.mapType = outt } if out.IsNil() { out.Set(reflect.MakeMap(outt)) } l := len(n.children) for i := 0; i < l; i += 2 { if isMerge(n.children[i]) { d.merge(n.children[i+1], out) continue } k := reflect.New(kt).Elem() if d.unmarshal(n.children[i], k) { kkind := k.Kind() if kkind == reflect.Interface { kkind = k.Elem().Kind() } if kkind == reflect.Map || kkind == reflect.Slice { failf("invalid map key: %#v", k.Interface()) } e := reflect.New(et).Elem() if d.unmarshal(n.children[i+1], e) { out.SetMapIndex(k, e) } } } d.mapType = mapType return true } func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { outt := out.Type() if outt.Elem() != mapItemType { d.terror(n, yaml_MAP_TAG, out) return false } mapType := d.mapType d.mapType = outt var slice []MapItem var l = len(n.children) for i := 0; i < l; i += 2 { if isMerge(n.children[i]) { d.merge(n.children[i+1], out) continue } item := MapItem{} k := reflect.ValueOf(&item.Key).Elem() if d.unmarshal(n.children[i], k) { v := reflect.ValueOf(&item.Value).Elem() if d.unmarshal(n.children[i+1], v) { slice = append(slice, item) } } } out.Set(reflect.ValueOf(slice)) d.mapType = mapType return true } func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { sinfo, err := getStructInfo(out.Type()) if err != nil { panic(err) } name := settableValueOf("") l := len(n.children) var inlineMap reflect.Value var elemType reflect.Type if sinfo.InlineMap != -1 { inlineMap = out.Field(sinfo.InlineMap) inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) elemType = inlineMap.Type().Elem() } for i := 0; i < l; i += 2 { ni := n.children[i] if isMerge(ni) { d.merge(n.children[i+1], out) continue } if !d.unmarshal(ni, name) { continue } if info, ok := sinfo.FieldsMap[name.String()]; ok { var field reflect.Value if info.Inline == nil { field = out.Field(info.Num) } else { field = out.FieldByIndex(info.Inline) } d.unmarshal(n.children[i+1], field) } else if sinfo.InlineMap != -1 { if inlineMap.IsNil() { inlineMap.Set(reflect.MakeMap(inlineMap.Type())) } value := reflect.New(elemType).Elem() d.unmarshal(n.children[i+1], value) inlineMap.SetMapIndex(name, value) } else if d.strict { d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in struct %s", n.line+1, name.String(), out.Type())) } } return true } func failWantMap() { failf("map merge requires map or sequence of maps as the value") } func (d *decoder) merge(n *node, out reflect.Value) { switch n.kind { case mappingNode: d.unmarshal(n, out) case aliasNode: an, ok := d.doc.anchors[n.value] if ok && an.kind != mappingNode { failWantMap() } d.unmarshal(n, out) case sequenceNode: // Step backwards as earlier nodes take precedence. for i := len(n.children) - 1; i >= 0; i-- { ni := n.children[i] if ni.kind == aliasNode { an, ok := d.doc.anchors[ni.value] if ok && an.kind != mappingNode { failWantMap() } } else if ni.kind != mappingNode { failWantMap() } d.unmarshal(ni, out) } default: failWantMap() } } func isMerge(n *node) bool { return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/apic.go��������������������������������������������������������0000644�0610621�0607500�00000051376�13172163307�021510� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package yaml import ( "io" "os" ) func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) // Check if we can move the queue at the beginning of the buffer. if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { if parser.tokens_head != len(parser.tokens) { copy(parser.tokens, parser.tokens[parser.tokens_head:]) } parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] parser.tokens_head = 0 } parser.tokens = append(parser.tokens, *token) if pos < 0 { return } copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) parser.tokens[parser.tokens_head+pos] = *token } // Create a new parser object. func yaml_parser_initialize(parser *yaml_parser_t) bool { *parser = yaml_parser_t{ raw_buffer: make([]byte, 0, input_raw_buffer_size), buffer: make([]byte, 0, input_buffer_size), } return true } // Destroy a parser object. func yaml_parser_delete(parser *yaml_parser_t) { *parser = yaml_parser_t{} } // String read handler. func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { if parser.input_pos == len(parser.input) { return 0, io.EOF } n = copy(buffer, parser.input[parser.input_pos:]) parser.input_pos += n return n, nil } // File read handler. func yaml_file_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { return parser.input_file.Read(buffer) } // Set a string input. func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { if parser.read_handler != nil { panic("must set the input source only once") } parser.read_handler = yaml_string_read_handler parser.input = input parser.input_pos = 0 } // Set a file input. func yaml_parser_set_input_file(parser *yaml_parser_t, file *os.File) { if parser.read_handler != nil { panic("must set the input source only once") } parser.read_handler = yaml_file_read_handler parser.input_file = file } // Set the source encoding. func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { if parser.encoding != yaml_ANY_ENCODING { panic("must set the encoding only once") } parser.encoding = encoding } // Create a new emitter object. func yaml_emitter_initialize(emitter *yaml_emitter_t) bool { *emitter = yaml_emitter_t{ buffer: make([]byte, output_buffer_size), raw_buffer: make([]byte, 0, output_raw_buffer_size), states: make([]yaml_emitter_state_t, 0, initial_stack_size), events: make([]yaml_event_t, 0, initial_queue_size), } return true } // Destroy an emitter object. func yaml_emitter_delete(emitter *yaml_emitter_t) { *emitter = yaml_emitter_t{} } // String write handler. func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { *emitter.output_buffer = append(*emitter.output_buffer, buffer...) return nil } // File write handler. func yaml_file_write_handler(emitter *yaml_emitter_t, buffer []byte) error { _, err := emitter.output_file.Write(buffer) return err } // Set a string output. func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { if emitter.write_handler != nil { panic("must set the output target only once") } emitter.write_handler = yaml_string_write_handler emitter.output_buffer = output_buffer } // Set a file output. func yaml_emitter_set_output_file(emitter *yaml_emitter_t, file io.Writer) { if emitter.write_handler != nil { panic("must set the output target only once") } emitter.write_handler = yaml_file_write_handler emitter.output_file = file } // Set the output encoding. func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { if emitter.encoding != yaml_ANY_ENCODING { panic("must set the output encoding only once") } emitter.encoding = encoding } // Set the canonical output style. func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { emitter.canonical = canonical } //// Set the indentation increment. func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { if indent < 2 || indent > 9 { indent = 2 } emitter.best_indent = indent } // Set the preferred line width. func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { if width < 0 { width = -1 } emitter.best_width = width } // Set if unescaped non-ASCII characters are allowed. func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { emitter.unicode = unicode } // Set the preferred line break character. func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { emitter.line_break = line_break } ///* // * Destroy a token object. // */ // //YAML_DECLARE(void) //yaml_token_delete(yaml_token_t *token) //{ // assert(token); // Non-NULL token object expected. // // switch (token.type) // { // case YAML_TAG_DIRECTIVE_TOKEN: // yaml_free(token.data.tag_directive.handle); // yaml_free(token.data.tag_directive.prefix); // break; // // case YAML_ALIAS_TOKEN: // yaml_free(token.data.alias.value); // break; // // case YAML_ANCHOR_TOKEN: // yaml_free(token.data.anchor.value); // break; // // case YAML_TAG_TOKEN: // yaml_free(token.data.tag.handle); // yaml_free(token.data.tag.suffix); // break; // // case YAML_SCALAR_TOKEN: // yaml_free(token.data.scalar.value); // break; // // default: // break; // } // // memset(token, 0, sizeof(yaml_token_t)); //} // ///* // * Check if a string is a valid UTF-8 sequence. // * // * Check 'reader.c' for more details on UTF-8 encoding. // */ // //static int //yaml_check_utf8(yaml_char_t *start, size_t length) //{ // yaml_char_t *end = start+length; // yaml_char_t *pointer = start; // // while (pointer < end) { // unsigned char octet; // unsigned int width; // unsigned int value; // size_t k; // // octet = pointer[0]; // width = (octet & 0x80) == 0x00 ? 1 : // (octet & 0xE0) == 0xC0 ? 2 : // (octet & 0xF0) == 0xE0 ? 3 : // (octet & 0xF8) == 0xF0 ? 4 : 0; // value = (octet & 0x80) == 0x00 ? octet & 0x7F : // (octet & 0xE0) == 0xC0 ? octet & 0x1F : // (octet & 0xF0) == 0xE0 ? octet & 0x0F : // (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; // if (!width) return 0; // if (pointer+width > end) return 0; // for (k = 1; k < width; k ++) { // octet = pointer[k]; // if ((octet & 0xC0) != 0x80) return 0; // value = (value << 6) + (octet & 0x3F); // } // if (!((width == 1) || // (width == 2 && value >= 0x80) || // (width == 3 && value >= 0x800) || // (width == 4 && value >= 0x10000))) return 0; // // pointer += width; // } // // return 1; //} // // Create STREAM-START. func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) bool { *event = yaml_event_t{ typ: yaml_STREAM_START_EVENT, encoding: encoding, } return true } // Create STREAM-END. func yaml_stream_end_event_initialize(event *yaml_event_t) bool { *event = yaml_event_t{ typ: yaml_STREAM_END_EVENT, } return true } // Create DOCUMENT-START. func yaml_document_start_event_initialize(event *yaml_event_t, version_directive *yaml_version_directive_t, tag_directives []yaml_tag_directive_t, implicit bool) bool { *event = yaml_event_t{ typ: yaml_DOCUMENT_START_EVENT, version_directive: version_directive, tag_directives: tag_directives, implicit: implicit, } return true } // Create DOCUMENT-END. func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) bool { *event = yaml_event_t{ typ: yaml_DOCUMENT_END_EVENT, implicit: implicit, } return true } ///* // * Create ALIAS. // */ // //YAML_DECLARE(int) //yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) //{ // mark yaml_mark_t = { 0, 0, 0 } // anchor_copy *yaml_char_t = NULL // // assert(event) // Non-NULL event object is expected. // assert(anchor) // Non-NULL anchor is expected. // // if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 // // anchor_copy = yaml_strdup(anchor) // if (!anchor_copy) // return 0 // // ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) // // return 1 //} // Create SCALAR. func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { *event = yaml_event_t{ typ: yaml_SCALAR_EVENT, anchor: anchor, tag: tag, value: value, implicit: plain_implicit, quoted_implicit: quoted_implicit, style: yaml_style_t(style), } return true } // Create SEQUENCE-START. func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { *event = yaml_event_t{ typ: yaml_SEQUENCE_START_EVENT, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(style), } return true } // Create SEQUENCE-END. func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { *event = yaml_event_t{ typ: yaml_SEQUENCE_END_EVENT, } return true } // Create MAPPING-START. func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) bool { *event = yaml_event_t{ typ: yaml_MAPPING_START_EVENT, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(style), } return true } // Create MAPPING-END. func yaml_mapping_end_event_initialize(event *yaml_event_t) bool { *event = yaml_event_t{ typ: yaml_MAPPING_END_EVENT, } return true } // Destroy an event object. func yaml_event_delete(event *yaml_event_t) { *event = yaml_event_t{} } ///* // * Create a document object. // */ // //YAML_DECLARE(int) //yaml_document_initialize(document *yaml_document_t, // version_directive *yaml_version_directive_t, // tag_directives_start *yaml_tag_directive_t, // tag_directives_end *yaml_tag_directive_t, // start_implicit int, end_implicit int) //{ // struct { // error yaml_error_type_t // } context // struct { // start *yaml_node_t // end *yaml_node_t // top *yaml_node_t // } nodes = { NULL, NULL, NULL } // version_directive_copy *yaml_version_directive_t = NULL // struct { // start *yaml_tag_directive_t // end *yaml_tag_directive_t // top *yaml_tag_directive_t // } tag_directives_copy = { NULL, NULL, NULL } // value yaml_tag_directive_t = { NULL, NULL } // mark yaml_mark_t = { 0, 0, 0 } // // assert(document) // Non-NULL document object is expected. // assert((tag_directives_start && tag_directives_end) || // (tag_directives_start == tag_directives_end)) // // Valid tag directives are expected. // // if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error // // if (version_directive) { // version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) // if (!version_directive_copy) goto error // version_directive_copy.major = version_directive.major // version_directive_copy.minor = version_directive.minor // } // // if (tag_directives_start != tag_directives_end) { // tag_directive *yaml_tag_directive_t // if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) // goto error // for (tag_directive = tag_directives_start // tag_directive != tag_directives_end; tag_directive ++) { // assert(tag_directive.handle) // assert(tag_directive.prefix) // if (!yaml_check_utf8(tag_directive.handle, // strlen((char *)tag_directive.handle))) // goto error // if (!yaml_check_utf8(tag_directive.prefix, // strlen((char *)tag_directive.prefix))) // goto error // value.handle = yaml_strdup(tag_directive.handle) // value.prefix = yaml_strdup(tag_directive.prefix) // if (!value.handle || !value.prefix) goto error // if (!PUSH(&context, tag_directives_copy, value)) // goto error // value.handle = NULL // value.prefix = NULL // } // } // // DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, // tag_directives_copy.start, tag_directives_copy.top, // start_implicit, end_implicit, mark, mark) // // return 1 // //error: // STACK_DEL(&context, nodes) // yaml_free(version_directive_copy) // while (!STACK_EMPTY(&context, tag_directives_copy)) { // value yaml_tag_directive_t = POP(&context, tag_directives_copy) // yaml_free(value.handle) // yaml_free(value.prefix) // } // STACK_DEL(&context, tag_directives_copy) // yaml_free(value.handle) // yaml_free(value.prefix) // // return 0 //} // ///* // * Destroy a document object. // */ // //YAML_DECLARE(void) //yaml_document_delete(document *yaml_document_t) //{ // struct { // error yaml_error_type_t // } context // tag_directive *yaml_tag_directive_t // // context.error = YAML_NO_ERROR // Eliminate a compliler warning. // // assert(document) // Non-NULL document object is expected. // // while (!STACK_EMPTY(&context, document.nodes)) { // node yaml_node_t = POP(&context, document.nodes) // yaml_free(node.tag) // switch (node.type) { // case YAML_SCALAR_NODE: // yaml_free(node.data.scalar.value) // break // case YAML_SEQUENCE_NODE: // STACK_DEL(&context, node.data.sequence.items) // break // case YAML_MAPPING_NODE: // STACK_DEL(&context, node.data.mapping.pairs) // break // default: // assert(0) // Should not happen. // } // } // STACK_DEL(&context, document.nodes) // // yaml_free(document.version_directive) // for (tag_directive = document.tag_directives.start // tag_directive != document.tag_directives.end // tag_directive++) { // yaml_free(tag_directive.handle) // yaml_free(tag_directive.prefix) // } // yaml_free(document.tag_directives.start) // // memset(document, 0, sizeof(yaml_document_t)) //} // ///** // * Get a document node. // */ // //YAML_DECLARE(yaml_node_t *) //yaml_document_get_node(document *yaml_document_t, index int) //{ // assert(document) // Non-NULL document object is expected. // // if (index > 0 && document.nodes.start + index <= document.nodes.top) { // return document.nodes.start + index - 1 // } // return NULL //} // ///** // * Get the root object. // */ // //YAML_DECLARE(yaml_node_t *) //yaml_document_get_root_node(document *yaml_document_t) //{ // assert(document) // Non-NULL document object is expected. // // if (document.nodes.top != document.nodes.start) { // return document.nodes.start // } // return NULL //} // ///* // * Add a scalar node to a document. // */ // //YAML_DECLARE(int) //yaml_document_add_scalar(document *yaml_document_t, // tag *yaml_char_t, value *yaml_char_t, length int, // style yaml_scalar_style_t) //{ // struct { // error yaml_error_type_t // } context // mark yaml_mark_t = { 0, 0, 0 } // tag_copy *yaml_char_t = NULL // value_copy *yaml_char_t = NULL // node yaml_node_t // // assert(document) // Non-NULL document object is expected. // assert(value) // Non-NULL value is expected. // // if (!tag) { // tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG // } // // if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error // tag_copy = yaml_strdup(tag) // if (!tag_copy) goto error // // if (length < 0) { // length = strlen((char *)value) // } // // if (!yaml_check_utf8(value, length)) goto error // value_copy = yaml_malloc(length+1) // if (!value_copy) goto error // memcpy(value_copy, value, length) // value_copy[length] = '\0' // // SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) // if (!PUSH(&context, document.nodes, node)) goto error // // return document.nodes.top - document.nodes.start // //error: // yaml_free(tag_copy) // yaml_free(value_copy) // // return 0 //} // ///* // * Add a sequence node to a document. // */ // //YAML_DECLARE(int) //yaml_document_add_sequence(document *yaml_document_t, // tag *yaml_char_t, style yaml_sequence_style_t) //{ // struct { // error yaml_error_type_t // } context // mark yaml_mark_t = { 0, 0, 0 } // tag_copy *yaml_char_t = NULL // struct { // start *yaml_node_item_t // end *yaml_node_item_t // top *yaml_node_item_t // } items = { NULL, NULL, NULL } // node yaml_node_t // // assert(document) // Non-NULL document object is expected. // // if (!tag) { // tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG // } // // if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error // tag_copy = yaml_strdup(tag) // if (!tag_copy) goto error // // if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error // // SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, // style, mark, mark) // if (!PUSH(&context, document.nodes, node)) goto error // // return document.nodes.top - document.nodes.start // //error: // STACK_DEL(&context, items) // yaml_free(tag_copy) // // return 0 //} // ///* // * Add a mapping node to a document. // */ // //YAML_DECLARE(int) //yaml_document_add_mapping(document *yaml_document_t, // tag *yaml_char_t, style yaml_mapping_style_t) //{ // struct { // error yaml_error_type_t // } context // mark yaml_mark_t = { 0, 0, 0 } // tag_copy *yaml_char_t = NULL // struct { // start *yaml_node_pair_t // end *yaml_node_pair_t // top *yaml_node_pair_t // } pairs = { NULL, NULL, NULL } // node yaml_node_t // // assert(document) // Non-NULL document object is expected. // // if (!tag) { // tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG // } // // if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error // tag_copy = yaml_strdup(tag) // if (!tag_copy) goto error // // if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error // // MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, // style, mark, mark) // if (!PUSH(&context, document.nodes, node)) goto error // // return document.nodes.top - document.nodes.start // //error: // STACK_DEL(&context, pairs) // yaml_free(tag_copy) // // return 0 //} // ///* // * Append an item to a sequence node. // */ // //YAML_DECLARE(int) //yaml_document_append_sequence_item(document *yaml_document_t, // sequence int, item int) //{ // struct { // error yaml_error_type_t // } context // // assert(document) // Non-NULL document is required. // assert(sequence > 0 // && document.nodes.start + sequence <= document.nodes.top) // // Valid sequence id is required. // assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) // // A sequence node is required. // assert(item > 0 && document.nodes.start + item <= document.nodes.top) // // Valid item id is required. // // if (!PUSH(&context, // document.nodes.start[sequence-1].data.sequence.items, item)) // return 0 // // return 1 //} // ///* // * Append a pair of a key and a value to a mapping node. // */ // //YAML_DECLARE(int) //yaml_document_append_mapping_pair(document *yaml_document_t, // mapping int, key int, value int) //{ // struct { // error yaml_error_type_t // } context // // pair yaml_node_pair_t // // assert(document) // Non-NULL document is required. // assert(mapping > 0 // && document.nodes.start + mapping <= document.nodes.top) // // Valid mapping id is required. // assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) // // A mapping node is required. // assert(key > 0 && document.nodes.start + key <= document.nodes.top) // // Valid key id is required. // assert(value > 0 && document.nodes.start + value <= document.nodes.top) // // Valid value id is required. // // pair.key = key // pair.value = value // // if (!PUSH(&context, // document.nodes.start[mapping-1].data.mapping.pairs, pair)) // return 0 // // return 1 //} // // ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/README.md������������������������������������������������������0000644�0610621�0607500�00000005142�13172163307�021512� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# YAML support for the Go language Introduction ------------ The yaml package enables Go programs to comfortably encode and decode YAML values. It was developed within [Canonical](https://www.canonical.com) as part of the [juju](https://juju.ubuntu.com) project, and is based on a pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) C library to parse and generate YAML data quickly and reliably. Compatibility ------------- The yaml package supports most of YAML 1.1 and 1.2, including support for anchors, tags, map merging, etc. Multi-document unmarshalling is not yet implemented, and base-60 floats from YAML 1.1 are purposefully not supported since they're a poor design and are gone in YAML 1.2. Installation and usage ---------------------- The import path for the package is *gopkg.in/yaml.v2*. To install it, run: go get gopkg.in/yaml.v2 API documentation ----------------- If opened in a browser, the import path itself leads to the API documentation: * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) API stability ------------- The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). License ------- The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. Example ------- Some more examples can be found in the "examples" folder. ```Go package main import ( "fmt" "log" "gopkg.in/yaml.v2" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` This example will generate the following output: ``` --- t: {Easy! {2 [3 4]}} --- t dump: a: Easy! b: c: 2 d: [3, 4] --- m: map[a:Easy! b:map[c:2 d:[3 4]]] --- m dump: a: Easy! b: c: 2 d: - 3 - 4 ``` ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/LICENSE.libyaml������������������������������������������������0000644�0610621�0607500�00000002441�13172163307�022667� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The following files were ported to Go from C files of libyaml, and thus are still covered by their original copyright and license: apic.go emitterc.go parserc.go readerc.go scannerc.go writerc.go yamlh.go yamlprivateh.go Copyright (c) 2006 Kirill Simonov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/LICENSE��������������������������������������������������������0000644�0610621�0607500�00000026135�13172163307�021245� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/gopkg.in/yaml.v2/.travis.yml����������������������������������������������������0000644�0610621�0607500�00000000134�13172163307�022340� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go: - 1.4 - 1.5 - 1.6 - tip go_import_path: gopkg.in/yaml.v2 ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/���������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163430�017261� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/��������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163430�020604� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/�������������������������������������������������0000755�0610621�0607500�00000000000�13172163430�023253� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/��������������������������������������0000755�0610621�0607500�00000000000�13172163430�025374� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/syscall_linux.go����������������������0000644�0610621�0607500�00000006527�13172163430�030626� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package capability import ( "syscall" "unsafe" ) type capHeader struct { version uint32 pid int } type capData struct { effective uint32 permitted uint32 inheritable uint32 } func capget(hdr *capHeader, data *capData) (err error) { _, _, e1 := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = e1 } return } func capset(hdr *capHeader, data *capData) (err error) { _, _, e1 := syscall.Syscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = e1 } return } // not yet in syscall const ( pr_CAP_AMBIENT = 47 pr_CAP_AMBIENT_IS_SET = uintptr(1) pr_CAP_AMBIENT_RAISE = uintptr(2) pr_CAP_AMBIENT_LOWER = uintptr(3) pr_CAP_AMBIENT_CLEAR_ALL = uintptr(4) ) func prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) { _, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0) if e1 != 0 { err = e1 } return } const ( vfsXattrName = "security.capability" vfsCapVerMask = 0xff000000 vfsCapVer1 = 0x01000000 vfsCapVer2 = 0x02000000 vfsCapFlagMask = ^vfsCapVerMask vfsCapFlageffective = 0x000001 vfscapDataSizeV1 = 4 * (1 + 2*1) vfscapDataSizeV2 = 4 * (1 + 2*2) ) type vfscapData struct { magic uint32 data [2]struct { permitted uint32 inheritable uint32 } effective [2]uint32 version int8 } var ( _vfsXattrName *byte ) func init() { _vfsXattrName, _ = syscall.BytePtrFromString(vfsXattrName) } func getVfsCap(path string, dest *vfscapData) (err error) { var _p0 *byte _p0, err = syscall.BytePtrFromString(path) if err != nil { return } r0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(dest)), vfscapDataSizeV2, 0, 0) if e1 != 0 { if e1 == syscall.ENODATA { dest.version = 2 return } err = e1 } switch dest.magic & vfsCapVerMask { case vfsCapVer1: dest.version = 1 if r0 != vfscapDataSizeV1 { return syscall.EINVAL } dest.data[1].permitted = 0 dest.data[1].inheritable = 0 case vfsCapVer2: dest.version = 2 if r0 != vfscapDataSizeV2 { return syscall.EINVAL } default: return syscall.EINVAL } if dest.magic&vfsCapFlageffective != 0 { dest.effective[0] = dest.data[0].permitted | dest.data[0].inheritable dest.effective[1] = dest.data[1].permitted | dest.data[1].inheritable } else { dest.effective[0] = 0 dest.effective[1] = 0 } return } func setVfsCap(path string, data *vfscapData) (err error) { var _p0 *byte _p0, err = syscall.BytePtrFromString(path) if err != nil { return } var size uintptr if data.version == 1 { data.magic = vfsCapVer1 size = vfscapDataSizeV1 } else if data.version == 2 { data.magic = vfsCapVer2 if data.effective[0] != 0 || data.effective[1] != 0 { data.magic |= vfsCapFlageffective } size = vfscapDataSizeV2 } else { return syscall.EINVAL } _, _, e1 := syscall.Syscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(data)), size, 0, 0) if e1 != 0 { err = e1 } return } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/enumgen/������������������������������0000755�0610621�0607500�00000000000�13172163430�027032� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/enumgen/gen.go������������������������0000644�0610621�0607500�00000004007�13172163430�030133� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "bytes" "fmt" "go/ast" "go/format" "go/parser" "go/token" "io/ioutil" "log" "os" "strings" ) const fileName = "enum.go" const genName = "enum_gen.go" type generator struct { buf bytes.Buffer caps []string } func (g *generator) writeHeader() { g.buf.WriteString("// generated file; DO NOT EDIT - use go generate in directory with source\n") g.buf.WriteString("\n") g.buf.WriteString("package capability") } func (g *generator) writeStringFunc() { g.buf.WriteString("\n") g.buf.WriteString("func (c Cap) String() string {\n") g.buf.WriteString("switch c {\n") for _, cap := range g.caps { fmt.Fprintf(&g.buf, "case %s:\n", cap) fmt.Fprintf(&g.buf, "return \"%s\"\n", strings.ToLower(cap[4:])) } g.buf.WriteString("}\n") g.buf.WriteString("return \"unknown\"\n") g.buf.WriteString("}\n") } func (g *generator) writeListFunc() { g.buf.WriteString("\n") g.buf.WriteString("// List returns list of all supported capabilities\n") g.buf.WriteString("func List() []Cap {\n") g.buf.WriteString("return []Cap{\n") for _, cap := range g.caps { fmt.Fprintf(&g.buf, "%s,\n", cap) } g.buf.WriteString("}\n") g.buf.WriteString("}\n") } func main() { fs := token.NewFileSet() parsedFile, err := parser.ParseFile(fs, fileName, nil, 0) if err != nil { log.Fatal(err) } var caps []string for _, decl := range parsedFile.Decls { decl, ok := decl.(*ast.GenDecl) if !ok || decl.Tok != token.CONST { continue } for _, spec := range decl.Specs { vspec := spec.(*ast.ValueSpec) name := vspec.Names[0].Name if strings.HasPrefix(name, "CAP_") { caps = append(caps, name) } } } g := &generator{caps: caps} g.writeHeader() g.writeStringFunc() g.writeListFunc() src, err := format.Source(g.buf.Bytes()) if err != nil { fmt.Println("generated invalid Go code") fmt.Println(g.buf.String()) log.Fatal(err) } fi, err := os.Stat(fileName) if err != nil { log.Fatal(err) } if err := ioutil.WriteFile(genName, src, fi.Mode().Perm()); err != nil { log.Fatal(err) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/enum_gen.go���������������������������0000644�0610621�0607500�00000004735�13172163430�027531� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// generated file; DO NOT EDIT - use go generate in directory with source package capability func (c Cap) String() string { switch c { case CAP_CHOWN: return "chown" case CAP_DAC_OVERRIDE: return "dac_override" case CAP_DAC_READ_SEARCH: return "dac_read_search" case CAP_FOWNER: return "fowner" case CAP_FSETID: return "fsetid" case CAP_KILL: return "kill" case CAP_SETGID: return "setgid" case CAP_SETUID: return "setuid" case CAP_SETPCAP: return "setpcap" case CAP_LINUX_IMMUTABLE: return "linux_immutable" case CAP_NET_BIND_SERVICE: return "net_bind_service" case CAP_NET_BROADCAST: return "net_broadcast" case CAP_NET_ADMIN: return "net_admin" case CAP_NET_RAW: return "net_raw" case CAP_IPC_LOCK: return "ipc_lock" case CAP_IPC_OWNER: return "ipc_owner" case CAP_SYS_MODULE: return "sys_module" case CAP_SYS_RAWIO: return "sys_rawio" case CAP_SYS_CHROOT: return "sys_chroot" case CAP_SYS_PTRACE: return "sys_ptrace" case CAP_SYS_PACCT: return "sys_pacct" case CAP_SYS_ADMIN: return "sys_admin" case CAP_SYS_BOOT: return "sys_boot" case CAP_SYS_NICE: return "sys_nice" case CAP_SYS_RESOURCE: return "sys_resource" case CAP_SYS_TIME: return "sys_time" case CAP_SYS_TTY_CONFIG: return "sys_tty_config" case CAP_MKNOD: return "mknod" case CAP_LEASE: return "lease" case CAP_AUDIT_WRITE: return "audit_write" case CAP_AUDIT_CONTROL: return "audit_control" case CAP_SETFCAP: return "setfcap" case CAP_MAC_OVERRIDE: return "mac_override" case CAP_MAC_ADMIN: return "mac_admin" case CAP_SYSLOG: return "syslog" case CAP_WAKE_ALARM: return "wake_alarm" case CAP_BLOCK_SUSPEND: return "block_suspend" case CAP_AUDIT_READ: return "audit_read" } return "unknown" } // List returns list of all supported capabilities func List() []Cap { return []Cap{ CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_DAC_READ_SEARCH, CAP_FOWNER, CAP_FSETID, CAP_KILL, CAP_SETGID, CAP_SETUID, CAP_SETPCAP, CAP_LINUX_IMMUTABLE, CAP_NET_BIND_SERVICE, CAP_NET_BROADCAST, CAP_NET_ADMIN, CAP_NET_RAW, CAP_IPC_LOCK, CAP_IPC_OWNER, CAP_SYS_MODULE, CAP_SYS_RAWIO, CAP_SYS_CHROOT, CAP_SYS_PTRACE, CAP_SYS_PACCT, CAP_SYS_ADMIN, CAP_SYS_BOOT, CAP_SYS_NICE, CAP_SYS_RESOURCE, CAP_SYS_TIME, CAP_SYS_TTY_CONFIG, CAP_MKNOD, CAP_LEASE, CAP_AUDIT_WRITE, CAP_AUDIT_CONTROL, CAP_SETFCAP, CAP_MAC_OVERRIDE, CAP_MAC_ADMIN, CAP_SYSLOG, CAP_WAKE_ALARM, CAP_BLOCK_SUSPEND, CAP_AUDIT_READ, } } �����������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/enum.go�������������������������������0000644�0610621�0607500�00000021014�13172163430�026665� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package capability type CapType uint func (c CapType) String() string { switch c { case EFFECTIVE: return "effective" case PERMITTED: return "permitted" case INHERITABLE: return "inheritable" case BOUNDING: return "bounding" case CAPS: return "caps" case AMBIENT: return "ambient" } return "unknown" } const ( EFFECTIVE CapType = 1 << iota PERMITTED INHERITABLE BOUNDING AMBIENT CAPS = EFFECTIVE | PERMITTED | INHERITABLE BOUNDS = BOUNDING AMBS = AMBIENT ) //go:generate go run enumgen/gen.go type Cap int // POSIX-draft defined capabilities. const ( // In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this // overrides the restriction of changing file ownership and group // ownership. CAP_CHOWN = Cap(0) // Override all DAC access, including ACL execute access if // [_POSIX_ACL] is defined. Excluding DAC access covered by // CAP_LINUX_IMMUTABLE. CAP_DAC_OVERRIDE = Cap(1) // Overrides all DAC restrictions regarding read and search on files // and directories, including ACL restrictions if [_POSIX_ACL] is // defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE. CAP_DAC_READ_SEARCH = Cap(2) // Overrides all restrictions about allowed operations on files, where // file owner ID must be equal to the user ID, except where CAP_FSETID // is applicable. It doesn't override MAC and DAC restrictions. CAP_FOWNER = Cap(3) // Overrides the following restrictions that the effective user ID // shall match the file owner ID when setting the S_ISUID and S_ISGID // bits on that file; that the effective group ID (or one of the // supplementary group IDs) shall match the file owner ID when setting // the S_ISGID bit on that file; that the S_ISUID and S_ISGID bits are // cleared on successful return from chown(2) (not implemented). CAP_FSETID = Cap(4) // Overrides the restriction that the real or effective user ID of a // process sending a signal must match the real or effective user ID // of the process receiving the signal. CAP_KILL = Cap(5) // Allows setgid(2) manipulation // Allows setgroups(2) // Allows forged gids on socket credentials passing. CAP_SETGID = Cap(6) // Allows set*uid(2) manipulation (including fsuid). // Allows forged pids on socket credentials passing. CAP_SETUID = Cap(7) // Linux-specific capabilities // Without VFS support for capabilities: // Transfer any capability in your permitted set to any pid, // remove any capability in your permitted set from any pid // With VFS support for capabilities (neither of above, but) // Add any capability from current's capability bounding set // to the current process' inheritable set // Allow taking bits out of capability bounding set // Allow modification of the securebits for a process CAP_SETPCAP = Cap(8) // Allow modification of S_IMMUTABLE and S_APPEND file attributes CAP_LINUX_IMMUTABLE = Cap(9) // Allows binding to TCP/UDP sockets below 1024 // Allows binding to ATM VCIs below 32 CAP_NET_BIND_SERVICE = Cap(10) // Allow broadcasting, listen to multicast CAP_NET_BROADCAST = Cap(11) // Allow interface configuration // Allow administration of IP firewall, masquerading and accounting // Allow setting debug option on sockets // Allow modification of routing tables // Allow setting arbitrary process / process group ownership on // sockets // Allow binding to any address for transparent proxying (also via NET_RAW) // Allow setting TOS (type of service) // Allow setting promiscuous mode // Allow clearing driver statistics // Allow multicasting // Allow read/write of device-specific registers // Allow activation of ATM control sockets CAP_NET_ADMIN = Cap(12) // Allow use of RAW sockets // Allow use of PACKET sockets // Allow binding to any address for transparent proxying (also via NET_ADMIN) CAP_NET_RAW = Cap(13) // Allow locking of shared memory segments // Allow mlock and mlockall (which doesn't really have anything to do // with IPC) CAP_IPC_LOCK = Cap(14) // Override IPC ownership checks CAP_IPC_OWNER = Cap(15) // Insert and remove kernel modules - modify kernel without limit CAP_SYS_MODULE = Cap(16) // Allow ioperm/iopl access // Allow sending USB messages to any device via /proc/bus/usb CAP_SYS_RAWIO = Cap(17) // Allow use of chroot() CAP_SYS_CHROOT = Cap(18) // Allow ptrace() of any process CAP_SYS_PTRACE = Cap(19) // Allow configuration of process accounting CAP_SYS_PACCT = Cap(20) // Allow configuration of the secure attention key // Allow administration of the random device // Allow examination and configuration of disk quotas // Allow setting the domainname // Allow setting the hostname // Allow calling bdflush() // Allow mount() and umount(), setting up new smb connection // Allow some autofs root ioctls // Allow nfsservctl // Allow VM86_REQUEST_IRQ // Allow to read/write pci config on alpha // Allow irix_prctl on mips (setstacksize) // Allow flushing all cache on m68k (sys_cacheflush) // Allow removing semaphores // Used instead of CAP_CHOWN to "chown" IPC message queues, semaphores // and shared memory // Allow locking/unlocking of shared memory segment // Allow turning swap on/off // Allow forged pids on socket credentials passing // Allow setting readahead and flushing buffers on block devices // Allow setting geometry in floppy driver // Allow turning DMA on/off in xd driver // Allow administration of md devices (mostly the above, but some // extra ioctls) // Allow tuning the ide driver // Allow access to the nvram device // Allow administration of apm_bios, serial and bttv (TV) device // Allow manufacturer commands in isdn CAPI support driver // Allow reading non-standardized portions of pci configuration space // Allow DDI debug ioctl on sbpcd driver // Allow setting up serial ports // Allow sending raw qic-117 commands // Allow enabling/disabling tagged queuing on SCSI controllers and sending // arbitrary SCSI commands // Allow setting encryption key on loopback filesystem // Allow setting zone reclaim policy CAP_SYS_ADMIN = Cap(21) // Allow use of reboot() CAP_SYS_BOOT = Cap(22) // Allow raising priority and setting priority on other (different // UID) processes // Allow use of FIFO and round-robin (realtime) scheduling on own // processes and setting the scheduling algorithm used by another // process. // Allow setting cpu affinity on other processes CAP_SYS_NICE = Cap(23) // Override resource limits. Set resource limits. // Override quota limits. // Override reserved space on ext2 filesystem // Modify data journaling mode on ext3 filesystem (uses journaling // resources) // NOTE: ext2 honors fsuid when checking for resource overrides, so // you can override using fsuid too // Override size restrictions on IPC message queues // Allow more than 64hz interrupts from the real-time clock // Override max number of consoles on console allocation // Override max number of keymaps CAP_SYS_RESOURCE = Cap(24) // Allow manipulation of system clock // Allow irix_stime on mips // Allow setting the real-time clock CAP_SYS_TIME = Cap(25) // Allow configuration of tty devices // Allow vhangup() of tty CAP_SYS_TTY_CONFIG = Cap(26) // Allow the privileged aspects of mknod() CAP_MKNOD = Cap(27) // Allow taking of leases on files CAP_LEASE = Cap(28) CAP_AUDIT_WRITE = Cap(29) CAP_AUDIT_CONTROL = Cap(30) CAP_SETFCAP = Cap(31) // Override MAC access. // The base kernel enforces no MAC policy. // An LSM may enforce a MAC policy, and if it does and it chooses // to implement capability based overrides of that policy, this is // the capability it should use to do so. CAP_MAC_OVERRIDE = Cap(32) // Allow MAC configuration or state changes. // The base kernel requires no MAC configuration. // An LSM may enforce a MAC policy, and if it does and it chooses // to implement capability based checks on modifications to that // policy or the data required to maintain it, this is the // capability it should use to do so. CAP_MAC_ADMIN = Cap(33) // Allow configuring the kernel's syslog (printk behaviour) CAP_SYSLOG = Cap(34) // Allow triggering something that will wake the system CAP_WAKE_ALARM = Cap(35) // Allow preventing system suspends CAP_BLOCK_SUSPEND = Cap(36) // Allow reading audit messages from the kernel CAP_AUDIT_READ = Cap(37) ) var ( // Highest valid capability of the running kernel. CAP_LAST_CAP = Cap(63) capUpperMask = ^uint32(0) ) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/capability_test.go��������������������0000644�0610621�0607500�00000004473�13172163430�031113� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package capability import "testing" func TestState(t *testing.T) { testEmpty := func(name string, c Capabilities, whats CapType) { for i := CapType(1); i <= BOUNDING; i <<= 1 { if (i&whats) != 0 && !c.Empty(i) { t.Errorf(name+": capabilities set %q wasn't empty", i) } } } testFull := func(name string, c Capabilities, whats CapType) { for i := CapType(1); i <= BOUNDING; i <<= 1 { if (i&whats) != 0 && !c.Full(i) { t.Errorf(name+": capabilities set %q wasn't full", i) } } } testPartial := func(name string, c Capabilities, whats CapType) { for i := CapType(1); i <= BOUNDING; i <<= 1 { if (i&whats) != 0 && (c.Empty(i) || c.Full(i)) { t.Errorf(name+": capabilities set %q wasn't partial", i) } } } testGet := func(name string, c Capabilities, whats CapType, max Cap) { for i := CapType(1); i <= BOUNDING; i <<= 1 { if (i & whats) == 0 { continue } for j := Cap(0); j <= max; j++ { if !c.Get(i, j) { t.Errorf(name+": capability %q wasn't found on %q", j, i) } } } } capf := new(capsFile) capf.data.version = 2 for _, tc := range []struct { name string c Capabilities sets CapType max Cap }{ {"v1", new(capsV1), EFFECTIVE | PERMITTED, CAP_AUDIT_CONTROL}, {"v3", new(capsV3), EFFECTIVE | PERMITTED | BOUNDING, CAP_LAST_CAP}, {"file_v1", new(capsFile), EFFECTIVE | PERMITTED, CAP_AUDIT_CONTROL}, {"file_v2", capf, EFFECTIVE | PERMITTED, CAP_LAST_CAP}, } { testEmpty(tc.name, tc.c, tc.sets) tc.c.Fill(CAPS | BOUNDS) testFull(tc.name, tc.c, tc.sets) testGet(tc.name, tc.c, tc.sets, tc.max) tc.c.Clear(CAPS | BOUNDS) testEmpty(tc.name, tc.c, tc.sets) for i := CapType(1); i <= BOUNDING; i <<= 1 { for j := Cap(0); j <= CAP_LAST_CAP; j++ { tc.c.Set(i, j) } } testFull(tc.name, tc.c, tc.sets) testGet(tc.name, tc.c, tc.sets, tc.max) for i := CapType(1); i <= BOUNDING; i <<= 1 { for j := Cap(0); j <= CAP_LAST_CAP; j++ { tc.c.Unset(i, j) } } testEmpty(tc.name, tc.c, tc.sets) tc.c.Set(PERMITTED, CAP_CHOWN) testPartial(tc.name, tc.c, PERMITTED) tc.c.Clear(CAPS | BOUNDS) testEmpty(tc.name, tc.c, tc.sets) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/capability_noop.go��������������������0000644�0610621�0607500�00000000660�13172163430�031101� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // +build !linux package capability import "errors" func newPid(pid int) (Capabilities, error) { return nil, errors.New("not supported") } func newFile(path string) (Capabilities, error) { return nil, errors.New("not supported") } ��������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/capability_linux.go�������������������0000644�0610621�0607500�00000030437�13172163430�031272� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package capability import ( "bufio" "errors" "fmt" "io" "os" "strings" "syscall" ) var errUnknownVers = errors.New("unknown capability version") const ( linuxCapVer1 = 0x19980330 linuxCapVer2 = 0x20071026 linuxCapVer3 = 0x20080522 ) var ( capVers uint32 capLastCap Cap ) func init() { var hdr capHeader capget(&hdr, nil) capVers = hdr.version if initLastCap() == nil { CAP_LAST_CAP = capLastCap if capLastCap > 31 { capUpperMask = (uint32(1) << (uint(capLastCap) - 31)) - 1 } else { capUpperMask = 0 } } } func initLastCap() error { if capLastCap != 0 { return nil } f, err := os.Open("/proc/sys/kernel/cap_last_cap") if err != nil { return err } defer f.Close() var b []byte = make([]byte, 11) _, err = f.Read(b) if err != nil { return err } fmt.Sscanf(string(b), "%d", &capLastCap) return nil } func mkStringCap(c Capabilities, which CapType) (ret string) { for i, first := Cap(0), true; i <= CAP_LAST_CAP; i++ { if !c.Get(which, i) { continue } if first { first = false } else { ret += ", " } ret += i.String() } return } func mkString(c Capabilities, max CapType) (ret string) { ret = "{" for i := CapType(1); i <= max; i <<= 1 { ret += " " + i.String() + "=\"" if c.Empty(i) { ret += "empty" } else if c.Full(i) { ret += "full" } else { ret += c.StringCap(i) } ret += "\"" } ret += " }" return } func newPid(pid int) (c Capabilities, err error) { switch capVers { case linuxCapVer1: p := new(capsV1) p.hdr.version = capVers p.hdr.pid = pid c = p case linuxCapVer2, linuxCapVer3: p := new(capsV3) p.hdr.version = capVers p.hdr.pid = pid c = p default: err = errUnknownVers return } err = c.Load() if err != nil { c = nil } return } type capsV1 struct { hdr capHeader data capData } func (c *capsV1) Get(which CapType, what Cap) bool { if what > 32 { return false } switch which { case EFFECTIVE: return (1<<uint(what))&c.data.effective != 0 case PERMITTED: return (1<<uint(what))&c.data.permitted != 0 case INHERITABLE: return (1<<uint(what))&c.data.inheritable != 0 } return false } func (c *capsV1) getData(which CapType) (ret uint32) { switch which { case EFFECTIVE: ret = c.data.effective case PERMITTED: ret = c.data.permitted case INHERITABLE: ret = c.data.inheritable } return } func (c *capsV1) Empty(which CapType) bool { return c.getData(which) == 0 } func (c *capsV1) Full(which CapType) bool { return (c.getData(which) & 0x7fffffff) == 0x7fffffff } func (c *capsV1) Set(which CapType, caps ...Cap) { for _, what := range caps { if what > 32 { continue } if which&EFFECTIVE != 0 { c.data.effective |= 1 << uint(what) } if which&PERMITTED != 0 { c.data.permitted |= 1 << uint(what) } if which&INHERITABLE != 0 { c.data.inheritable |= 1 << uint(what) } } } func (c *capsV1) Unset(which CapType, caps ...Cap) { for _, what := range caps { if what > 32 { continue } if which&EFFECTIVE != 0 { c.data.effective &= ^(1 << uint(what)) } if which&PERMITTED != 0 { c.data.permitted &= ^(1 << uint(what)) } if which&INHERITABLE != 0 { c.data.inheritable &= ^(1 << uint(what)) } } } func (c *capsV1) Fill(kind CapType) { if kind&CAPS == CAPS { c.data.effective = 0x7fffffff c.data.permitted = 0x7fffffff c.data.inheritable = 0 } } func (c *capsV1) Clear(kind CapType) { if kind&CAPS == CAPS { c.data.effective = 0 c.data.permitted = 0 c.data.inheritable = 0 } } func (c *capsV1) StringCap(which CapType) (ret string) { return mkStringCap(c, which) } func (c *capsV1) String() (ret string) { return mkString(c, BOUNDING) } func (c *capsV1) Load() (err error) { return capget(&c.hdr, &c.data) } func (c *capsV1) Apply(kind CapType) error { if kind&CAPS == CAPS { return capset(&c.hdr, &c.data) } return nil } type capsV3 struct { hdr capHeader data [2]capData bounds [2]uint32 ambient [2]uint32 } func (c *capsV3) Get(which CapType, what Cap) bool { var i uint if what > 31 { i = uint(what) >> 5 what %= 32 } switch which { case EFFECTIVE: return (1<<uint(what))&c.data[i].effective != 0 case PERMITTED: return (1<<uint(what))&c.data[i].permitted != 0 case INHERITABLE: return (1<<uint(what))&c.data[i].inheritable != 0 case BOUNDING: return (1<<uint(what))&c.bounds[i] != 0 case AMBIENT: return (1<<uint(what))&c.ambient[i] != 0 } return false } func (c *capsV3) getData(which CapType, dest []uint32) { switch which { case EFFECTIVE: dest[0] = c.data[0].effective dest[1] = c.data[1].effective case PERMITTED: dest[0] = c.data[0].permitted dest[1] = c.data[1].permitted case INHERITABLE: dest[0] = c.data[0].inheritable dest[1] = c.data[1].inheritable case BOUNDING: dest[0] = c.bounds[0] dest[1] = c.bounds[1] case AMBIENT: dest[0] = c.ambient[0] dest[1] = c.ambient[1] } } func (c *capsV3) Empty(which CapType) bool { var data [2]uint32 c.getData(which, data[:]) return data[0] == 0 && data[1] == 0 } func (c *capsV3) Full(which CapType) bool { var data [2]uint32 c.getData(which, data[:]) if (data[0] & 0xffffffff) != 0xffffffff { return false } return (data[1] & capUpperMask) == capUpperMask } func (c *capsV3) Set(which CapType, caps ...Cap) { for _, what := range caps { var i uint if what > 31 { i = uint(what) >> 5 what %= 32 } if which&EFFECTIVE != 0 { c.data[i].effective |= 1 << uint(what) } if which&PERMITTED != 0 { c.data[i].permitted |= 1 << uint(what) } if which&INHERITABLE != 0 { c.data[i].inheritable |= 1 << uint(what) } if which&BOUNDING != 0 { c.bounds[i] |= 1 << uint(what) } if which&AMBIENT != 0 { c.ambient[i] |= 1 << uint(what) } } } func (c *capsV3) Unset(which CapType, caps ...Cap) { for _, what := range caps { var i uint if what > 31 { i = uint(what) >> 5 what %= 32 } if which&EFFECTIVE != 0 { c.data[i].effective &= ^(1 << uint(what)) } if which&PERMITTED != 0 { c.data[i].permitted &= ^(1 << uint(what)) } if which&INHERITABLE != 0 { c.data[i].inheritable &= ^(1 << uint(what)) } if which&BOUNDING != 0 { c.bounds[i] &= ^(1 << uint(what)) } if which&AMBIENT != 0 { c.ambient[i] &= ^(1 << uint(what)) } } } func (c *capsV3) Fill(kind CapType) { if kind&CAPS == CAPS { c.data[0].effective = 0xffffffff c.data[0].permitted = 0xffffffff c.data[0].inheritable = 0 c.data[1].effective = 0xffffffff c.data[1].permitted = 0xffffffff c.data[1].inheritable = 0 } if kind&BOUNDS == BOUNDS { c.bounds[0] = 0xffffffff c.bounds[1] = 0xffffffff } if kind&AMBS == AMBS { c.ambient[0] = 0xffffffff c.ambient[1] = 0xffffffff } } func (c *capsV3) Clear(kind CapType) { if kind&CAPS == CAPS { c.data[0].effective = 0 c.data[0].permitted = 0 c.data[0].inheritable = 0 c.data[1].effective = 0 c.data[1].permitted = 0 c.data[1].inheritable = 0 } if kind&BOUNDS == BOUNDS { c.bounds[0] = 0 c.bounds[1] = 0 } if kind&AMBS == AMBS { c.ambient[0] = 0 c.ambient[1] = 0 } } func (c *capsV3) StringCap(which CapType) (ret string) { return mkStringCap(c, which) } func (c *capsV3) String() (ret string) { return mkString(c, BOUNDING) } func (c *capsV3) Load() (err error) { err = capget(&c.hdr, &c.data[0]) if err != nil { return } var status_path string if c.hdr.pid == 0 { status_path = fmt.Sprintf("/proc/self/status") } else { status_path = fmt.Sprintf("/proc/%d/status", c.hdr.pid) } f, err := os.Open(status_path) if err != nil { return } b := bufio.NewReader(f) for { line, e := b.ReadString('\n') if e != nil { if e != io.EOF { err = e } break } if strings.HasPrefix(line, "CapB") { fmt.Sscanf(line[4:], "nd: %08x%08x", &c.bounds[1], &c.bounds[0]) continue } if strings.HasPrefix(line, "CapA") { fmt.Sscanf(line[4:], "mb: %08x%08x", &c.ambient[1], &c.ambient[0]) continue } } f.Close() return } func (c *capsV3) Apply(kind CapType) (err error) { if kind&BOUNDS == BOUNDS { var data [2]capData err = capget(&c.hdr, &data[0]) if err != nil { return } if (1<<uint(CAP_SETPCAP))&data[0].effective != 0 { for i := Cap(0); i <= CAP_LAST_CAP; i++ { if c.Get(BOUNDING, i) { continue } err = prctl(syscall.PR_CAPBSET_DROP, uintptr(i), 0, 0, 0) if err != nil { // Ignore EINVAL since the capability may not be supported in this system. if errno, ok := err.(syscall.Errno); ok && errno == syscall.EINVAL { err = nil continue } return } } } } if kind&CAPS == CAPS { err = capset(&c.hdr, &c.data[0]) if err != nil { return } } if kind&AMBS == AMBS { for i := Cap(0); i <= CAP_LAST_CAP; i++ { action := pr_CAP_AMBIENT_LOWER if c.Get(AMBIENT, i) { action = pr_CAP_AMBIENT_RAISE } err := prctl(pr_CAP_AMBIENT, action, uintptr(i), 0, 0) // Ignore EINVAL as not supported on kernels before 4.3 if errno, ok := err.(syscall.Errno); ok && errno == syscall.EINVAL { err = nil continue } } } return } func newFile(path string) (c Capabilities, err error) { c = &capsFile{path: path} err = c.Load() if err != nil { c = nil } return } type capsFile struct { path string data vfscapData } func (c *capsFile) Get(which CapType, what Cap) bool { var i uint if what > 31 { if c.data.version == 1 { return false } i = uint(what) >> 5 what %= 32 } switch which { case EFFECTIVE: return (1<<uint(what))&c.data.effective[i] != 0 case PERMITTED: return (1<<uint(what))&c.data.data[i].permitted != 0 case INHERITABLE: return (1<<uint(what))&c.data.data[i].inheritable != 0 } return false } func (c *capsFile) getData(which CapType, dest []uint32) { switch which { case EFFECTIVE: dest[0] = c.data.effective[0] dest[1] = c.data.effective[1] case PERMITTED: dest[0] = c.data.data[0].permitted dest[1] = c.data.data[1].permitted case INHERITABLE: dest[0] = c.data.data[0].inheritable dest[1] = c.data.data[1].inheritable } } func (c *capsFile) Empty(which CapType) bool { var data [2]uint32 c.getData(which, data[:]) return data[0] == 0 && data[1] == 0 } func (c *capsFile) Full(which CapType) bool { var data [2]uint32 c.getData(which, data[:]) if c.data.version == 0 { return (data[0] & 0x7fffffff) == 0x7fffffff } if (data[0] & 0xffffffff) != 0xffffffff { return false } return (data[1] & capUpperMask) == capUpperMask } func (c *capsFile) Set(which CapType, caps ...Cap) { for _, what := range caps { var i uint if what > 31 { if c.data.version == 1 { continue } i = uint(what) >> 5 what %= 32 } if which&EFFECTIVE != 0 { c.data.effective[i] |= 1 << uint(what) } if which&PERMITTED != 0 { c.data.data[i].permitted |= 1 << uint(what) } if which&INHERITABLE != 0 { c.data.data[i].inheritable |= 1 << uint(what) } } } func (c *capsFile) Unset(which CapType, caps ...Cap) { for _, what := range caps { var i uint if what > 31 { if c.data.version == 1 { continue } i = uint(what) >> 5 what %= 32 } if which&EFFECTIVE != 0 { c.data.effective[i] &= ^(1 << uint(what)) } if which&PERMITTED != 0 { c.data.data[i].permitted &= ^(1 << uint(what)) } if which&INHERITABLE != 0 { c.data.data[i].inheritable &= ^(1 << uint(what)) } } } func (c *capsFile) Fill(kind CapType) { if kind&CAPS == CAPS { c.data.effective[0] = 0xffffffff c.data.data[0].permitted = 0xffffffff c.data.data[0].inheritable = 0 if c.data.version == 2 { c.data.effective[1] = 0xffffffff c.data.data[1].permitted = 0xffffffff c.data.data[1].inheritable = 0 } } } func (c *capsFile) Clear(kind CapType) { if kind&CAPS == CAPS { c.data.effective[0] = 0 c.data.data[0].permitted = 0 c.data.data[0].inheritable = 0 if c.data.version == 2 { c.data.effective[1] = 0 c.data.data[1].permitted = 0 c.data.data[1].inheritable = 0 } } } func (c *capsFile) StringCap(which CapType) (ret string) { return mkStringCap(c, which) } func (c *capsFile) String() (ret string) { return mkString(c, INHERITABLE) } func (c *capsFile) Load() (err error) { return getVfsCap(c.path, &c.data) } func (c *capsFile) Apply(kind CapType) (err error) { if kind&CAPS == CAPS { return setVfsCap(c.path, &c.data) } return } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/capability/capability.go�������������������������0000644�0610621�0607500�00000005021�13172163430�030042� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package capability provides utilities for manipulating POSIX capabilities. package capability type Capabilities interface { // Get check whether a capability present in the given // capabilities set. The 'which' value should be one of EFFECTIVE, // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. Get(which CapType, what Cap) bool // Empty check whether all capability bits of the given capabilities // set are zero. The 'which' value should be one of EFFECTIVE, // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. Empty(which CapType) bool // Full check whether all capability bits of the given capabilities // set are one. The 'which' value should be one of EFFECTIVE, // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. Full(which CapType) bool // Set sets capabilities of the given capabilities sets. The // 'which' value should be one or combination (OR'ed) of EFFECTIVE, // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. Set(which CapType, caps ...Cap) // Unset unsets capabilities of the given capabilities sets. The // 'which' value should be one or combination (OR'ed) of EFFECTIVE, // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. Unset(which CapType, caps ...Cap) // Fill sets all bits of the given capabilities kind to one. The // 'kind' value should be one or combination (OR'ed) of CAPS, // BOUNDS or AMBS. Fill(kind CapType) // Clear sets all bits of the given capabilities kind to zero. The // 'kind' value should be one or combination (OR'ed) of CAPS, // BOUNDS or AMBS. Clear(kind CapType) // String return current capabilities state of the given capabilities // set as string. The 'which' value should be one of EFFECTIVE, // PERMITTED, INHERITABLE BOUNDING or AMBIENT StringCap(which CapType) string // String return current capabilities state as string. String() string // Load load actual capabilities value. This will overwrite all // outstanding changes. Load() error // Apply apply the capabilities settings, so all changes will take // effect. Apply(kind CapType) error } // NewPid create new initialized Capabilities object for given pid when it // is nonzero, or for the current pid if pid is 0 func NewPid(pid int) (Capabilities, error) { return newPid(pid) } // NewFile create new initialized Capabilities object for given named file. func NewFile(name string) (Capabilities, error) { return newFile(name) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/syndtr/gocapability/LICENSE������������������������������������������0000644�0610621�0607500�00000002446�13172163430�024266� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright 2013 Suryandaru Triandana <syndtr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/�������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163427�020725� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/��������������������������������������������������������0000755�0610621�0607500�00000000000�13172163430�021665� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/version4.go���������������������������������������������0000644�0610621�0607500�00000001617�13172163430�023772� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid // Random returns a Random (Version 4) UUID or panics. // // The strength of the UUIDs is based on the strength of the crypto/rand // package. // // A note about uniqueness derived from from the UUID Wikipedia entry: // // Randomly generated UUIDs have 122 random bits. One's annual risk of being // hit by a meteorite is estimated to be one chance in 17 billion, that // means the probability is about 0.00000000006 (6 × 10−11), // equivalent to the odds of creating a few tens of trillions of UUIDs in a // year and having one duplicate. func NewRandom() UUID { uuid := make([]byte, 16) randomBits([]byte(uuid)) uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 return uuid } �����������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/version1.go���������������������������������������������0000644�0610621�0607500�00000002214�13172163430�023761� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "encoding/binary" ) // NewUUID returns a Version 1 UUID based on the current NodeID and clock // sequence, and the current time. If the NodeID has not been set by SetNodeID // or SetNodeInterface then it will be set automatically. If the NodeID cannot // be set NewUUID returns nil. If clock sequence has not been set by // SetClockSequence then it will be set automatically. If GetTime fails to // return the current NewUUID returns nil. func NewUUID() UUID { if nodeID == nil { SetNodeInterface("") } now, seq, err := GetTime() if err != nil { return nil } uuid := make([]byte, 16) time_low := uint32(now & 0xffffffff) time_mid := uint16((now >> 32) & 0xffff) time_hi := uint16((now >> 48) & 0x0fff) time_hi |= 0x1000 // Version 1 binary.BigEndian.PutUint32(uuid[0:], time_low) binary.BigEndian.PutUint16(uuid[4:], time_mid) binary.BigEndian.PutUint16(uuid[6:], time_hi) binary.BigEndian.PutUint16(uuid[8:], seq) copy(uuid[10:], nodeID) return uuid } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/uuid_test.go��������������������������������������������0000644�0610621�0607500�00000032454�13172163430�024231� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "bytes" "fmt" "os" "strings" "testing" "time" ) type test struct { in string version Version variant Variant isuuid bool } var tests = []test{ {"f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, RFC4122, true}, {"f47ac10b-58cc-1372-8567-0e02b2c3d479", 1, RFC4122, true}, {"f47ac10b-58cc-2372-8567-0e02b2c3d479", 2, RFC4122, true}, {"f47ac10b-58cc-3372-8567-0e02b2c3d479", 3, RFC4122, true}, {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-5372-8567-0e02b2c3d479", 5, RFC4122, true}, {"f47ac10b-58cc-6372-8567-0e02b2c3d479", 6, RFC4122, true}, {"f47ac10b-58cc-7372-8567-0e02b2c3d479", 7, RFC4122, true}, {"f47ac10b-58cc-8372-8567-0e02b2c3d479", 8, RFC4122, true}, {"f47ac10b-58cc-9372-8567-0e02b2c3d479", 9, RFC4122, true}, {"f47ac10b-58cc-a372-8567-0e02b2c3d479", 10, RFC4122, true}, {"f47ac10b-58cc-b372-8567-0e02b2c3d479", 11, RFC4122, true}, {"f47ac10b-58cc-c372-8567-0e02b2c3d479", 12, RFC4122, true}, {"f47ac10b-58cc-d372-8567-0e02b2c3d479", 13, RFC4122, true}, {"f47ac10b-58cc-e372-8567-0e02b2c3d479", 14, RFC4122, true}, {"f47ac10b-58cc-f372-8567-0e02b2c3d479", 15, RFC4122, true}, {"urn:uuid:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, {"URN:UUID:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-1567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-2567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-3567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-4567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-5567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-6567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-7567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-4372-9567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-4372-a567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-4372-b567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-4372-c567-0e02b2c3d479", 4, Microsoft, true}, {"f47ac10b-58cc-4372-d567-0e02b2c3d479", 4, Microsoft, true}, {"f47ac10b-58cc-4372-e567-0e02b2c3d479", 4, Future, true}, {"f47ac10b-58cc-4372-f567-0e02b2c3d479", 4, Future, true}, {"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false}, {"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false}, {"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false}, {"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false}, {"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false}, {"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false}, } var constants = []struct { c interface{} name string }{ {Person, "Person"}, {Group, "Group"}, {Org, "Org"}, {Invalid, "Invalid"}, {RFC4122, "RFC4122"}, {Reserved, "Reserved"}, {Microsoft, "Microsoft"}, {Future, "Future"}, {Domain(17), "Domain17"}, {Variant(42), "BadVariant42"}, } func testTest(t *testing.T, in string, tt test) { uuid := Parse(in) if ok := (uuid != nil); ok != tt.isuuid { t.Errorf("Parse(%s) got %v expected %v\b", in, ok, tt.isuuid) } if uuid == nil { return } if v := uuid.Variant(); v != tt.variant { t.Errorf("Variant(%s) got %d expected %d\b", in, v, tt.variant) } if v, _ := uuid.Version(); v != tt.version { t.Errorf("Version(%s) got %d expected %d\b", in, v, tt.version) } } func TestUUID(t *testing.T) { for _, tt := range tests { testTest(t, tt.in, tt) testTest(t, strings.ToUpper(tt.in), tt) } } func TestConstants(t *testing.T) { for x, tt := range constants { v, ok := tt.c.(fmt.Stringer) if !ok { t.Errorf("%x: %v: not a stringer", x, v) } else if s := v.String(); s != tt.name { v, _ := tt.c.(int) t.Errorf("%x: Constant %T:%d gives %q, expected %q", x, tt.c, v, s, tt.name) } } } func TestRandomUUID(t *testing.T) { m := make(map[string]bool) for x := 1; x < 32; x++ { uuid := NewRandom() s := uuid.String() if m[s] { t.Errorf("NewRandom returned duplicated UUID %s", s) } m[s] = true if v, _ := uuid.Version(); v != 4 { t.Errorf("Random UUID of version %s", v) } if uuid.Variant() != RFC4122 { t.Errorf("Random UUID is variant %d", uuid.Variant()) } } } func TestNew(t *testing.T) { m := make(map[string]bool) for x := 1; x < 32; x++ { s := New() if m[s] { t.Errorf("New returned duplicated UUID %s", s) } m[s] = true uuid := Parse(s) if uuid == nil { t.Errorf("New returned %q which does not decode", s) continue } if v, _ := uuid.Version(); v != 4 { t.Errorf("Random UUID of version %s", v) } if uuid.Variant() != RFC4122 { t.Errorf("Random UUID is variant %d", uuid.Variant()) } } } func clockSeq(t *testing.T, uuid UUID) int { seq, ok := uuid.ClockSequence() if !ok { t.Fatalf("%s: invalid clock sequence", uuid) } return seq } func TestClockSeq(t *testing.T) { // Fake time.Now for this test to return a monotonically advancing time; restore it at end. defer func(orig func() time.Time) { timeNow = orig }(timeNow) monTime := time.Now() timeNow = func() time.Time { monTime = monTime.Add(1 * time.Second) return monTime } SetClockSequence(-1) uuid1 := NewUUID() uuid2 := NewUUID() if clockSeq(t, uuid1) != clockSeq(t, uuid2) { t.Errorf("clock sequence %d != %d", clockSeq(t, uuid1), clockSeq(t, uuid2)) } SetClockSequence(-1) uuid2 = NewUUID() // Just on the very off chance we generated the same sequence // two times we try again. if clockSeq(t, uuid1) == clockSeq(t, uuid2) { SetClockSequence(-1) uuid2 = NewUUID() } if clockSeq(t, uuid1) == clockSeq(t, uuid2) { t.Errorf("Duplicate clock sequence %d", clockSeq(t, uuid1)) } SetClockSequence(0x1234) uuid1 = NewUUID() if seq := clockSeq(t, uuid1); seq != 0x1234 { t.Errorf("%s: expected seq 0x1234 got 0x%04x", uuid1, seq) } } func TestCoding(t *testing.T) { text := "7d444840-9dc0-11d1-b245-5ffdce74fad2" urn := "urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2" data := UUID{ 0x7d, 0x44, 0x48, 0x40, 0x9d, 0xc0, 0x11, 0xd1, 0xb2, 0x45, 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2, } if v := data.String(); v != text { t.Errorf("%x: encoded to %s, expected %s", data, v, text) } if v := data.URN(); v != urn { t.Errorf("%x: urn is %s, expected %s", data, v, urn) } uuid := Parse(text) if !Equal(uuid, data) { t.Errorf("%s: decoded to %s, expected %s", text, uuid, data) } } func TestVersion1(t *testing.T) { uuid1 := NewUUID() uuid2 := NewUUID() if Equal(uuid1, uuid2) { t.Errorf("%s:duplicate uuid", uuid1) } if v, _ := uuid1.Version(); v != 1 { t.Errorf("%s: version %s expected 1", uuid1, v) } if v, _ := uuid2.Version(); v != 1 { t.Errorf("%s: version %s expected 1", uuid2, v) } n1 := uuid1.NodeID() n2 := uuid2.NodeID() if !bytes.Equal(n1, n2) { t.Errorf("Different nodes %x != %x", n1, n2) } t1, ok := uuid1.Time() if !ok { t.Errorf("%s: invalid time", uuid1) } t2, ok := uuid2.Time() if !ok { t.Errorf("%s: invalid time", uuid2) } q1, ok := uuid1.ClockSequence() if !ok { t.Errorf("%s: invalid clock sequence", uuid1) } q2, ok := uuid2.ClockSequence() if !ok { t.Errorf("%s: invalid clock sequence", uuid2) } switch { case t1 == t2 && q1 == q2: t.Error("time stopped") case t1 > t2 && q1 == q2: t.Error("time reversed") case t1 < t2 && q1 != q2: t.Error("clock sequence chaned unexpectedly") } } func TestNode(t *testing.T) { // This test is mostly to make sure we don't leave nodeMu locked. ifname = "" if ni := NodeInterface(); ni != "" { t.Errorf("NodeInterface got %q, want %q", ni, "") } if SetNodeInterface("xyzzy") { t.Error("SetNodeInterface succeeded on a bad interface name") } if !SetNodeInterface("") { t.Error("SetNodeInterface failed") } if ni := NodeInterface(); ni == "" { t.Error("NodeInterface returned an empty string") } ni := NodeID() if len(ni) != 6 { t.Errorf("ni got %d bytes, want 6", len(ni)) } hasData := false for _, b := range ni { if b != 0 { hasData = true } } if !hasData { t.Error("nodeid is all zeros") } id := []byte{1, 2, 3, 4, 5, 6, 7, 8} SetNodeID(id) ni = NodeID() if !bytes.Equal(ni, id[:6]) { t.Errorf("got nodeid %v, want %v", ni, id[:6]) } if ni := NodeInterface(); ni != "user" { t.Errorf("got inteface %q, want %q", ni, "user") } } func TestNodeAndTime(t *testing.T) { // Time is February 5, 1998 12:30:23.136364800 AM GMT uuid := Parse("7d444840-9dc0-11d1-b245-5ffdce74fad2") node := []byte{0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2} ts, ok := uuid.Time() if ok { c := time.Unix(ts.UnixTime()) want := time.Date(1998, 2, 5, 0, 30, 23, 136364800, time.UTC) if !c.Equal(want) { t.Errorf("Got time %v, want %v", c, want) } } else { t.Errorf("%s: bad time", uuid) } if !bytes.Equal(node, uuid.NodeID()) { t.Errorf("Expected node %v got %v", node, uuid.NodeID()) } } func TestMD5(t *testing.T) { uuid := NewMD5(NameSpace_DNS, []byte("python.org")).String() want := "6fa459ea-ee8a-3ca4-894e-db77e160355e" if uuid != want { t.Errorf("MD5: got %q expected %q", uuid, want) } } func TestSHA1(t *testing.T) { uuid := NewSHA1(NameSpace_DNS, []byte("python.org")).String() want := "886313e1-3b8a-5372-9b90-0c9aee199e5d" if uuid != want { t.Errorf("SHA1: got %q expected %q", uuid, want) } } func TestNodeID(t *testing.T) { nid := []byte{1, 2, 3, 4, 5, 6} SetNodeInterface("") s := NodeInterface() if s == "" || s == "user" { t.Errorf("NodeInterface %q after SetInteface", s) } node1 := NodeID() if node1 == nil { t.Error("NodeID nil after SetNodeInterface", s) } SetNodeID(nid) s = NodeInterface() if s != "user" { t.Errorf("Expected NodeInterface %q got %q", "user", s) } node2 := NodeID() if node2 == nil { t.Error("NodeID nil after SetNodeID", s) } if bytes.Equal(node1, node2) { t.Error("NodeID not changed after SetNodeID", s) } else if !bytes.Equal(nid, node2) { t.Errorf("NodeID is %x, expected %x", node2, nid) } } func testDCE(t *testing.T, name string, uuid UUID, domain Domain, id uint32) { if uuid == nil { t.Errorf("%s failed", name) return } if v, _ := uuid.Version(); v != 2 { t.Errorf("%s: %s: expected version 2, got %s", name, uuid, v) return } if v, ok := uuid.Domain(); !ok || v != domain { if !ok { t.Errorf("%s: %d: Domain failed", name, uuid) } else { t.Errorf("%s: %s: expected domain %d, got %d", name, uuid, domain, v) } } if v, ok := uuid.Id(); !ok || v != id { if !ok { t.Errorf("%s: %d: Id failed", name, uuid) } else { t.Errorf("%s: %s: expected id %d, got %d", name, uuid, id, v) } } } func TestDCE(t *testing.T) { testDCE(t, "NewDCESecurity", NewDCESecurity(42, 12345678), 42, 12345678) testDCE(t, "NewDCEPerson", NewDCEPerson(), Person, uint32(os.Getuid())) testDCE(t, "NewDCEGroup", NewDCEGroup(), Group, uint32(os.Getgid())) } type badRand struct{} func (r badRand) Read(buf []byte) (int, error) { for i, _ := range buf { buf[i] = byte(i) } return len(buf), nil } func TestBadRand(t *testing.T) { SetRand(badRand{}) uuid1 := New() uuid2 := New() if uuid1 != uuid2 { t.Errorf("expected duplicates, got %q and %q", uuid1, uuid2) } SetRand(nil) uuid1 = New() uuid2 = New() if uuid1 == uuid2 { t.Errorf("unexpected duplicates, got %q", uuid1) } } func TestUUID_Array(t *testing.T) { expect := Array{ 0xf4, 0x7a, 0xc1, 0x0b, 0x58, 0xcc, 0x03, 0x72, 0x85, 0x67, 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79, } uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") if uuid == nil { t.Fatal("invalid uuid") } if uuid.Array() != expect { t.Fatal("invalid array") } } func TestArray_UUID(t *testing.T) { array := Array{ 0xf4, 0x7a, 0xc1, 0x0b, 0x58, 0xcc, 0x03, 0x72, 0x85, 0x67, 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79, } expect := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") if expect == nil { t.Fatal("invalid uuid") } if !bytes.Equal(array.UUID(), expect) { t.Fatal("invalid uuid") } } func BenchmarkParse(b *testing.B) { for i := 0; i < b.N; i++ { uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") if uuid == nil { b.Fatal("invalid uuid") } } } func BenchmarkNew(b *testing.B) { for i := 0; i < b.N; i++ { New() } } func BenchmarkUUID_String(b *testing.B) { uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") if uuid == nil { b.Fatal("invalid uuid") } for i := 0; i < b.N; i++ { if uuid.String() == "" { b.Fatal("invalid uuid") } } } func BenchmarkUUID_URN(b *testing.B) { uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") if uuid == nil { b.Fatal("invalid uuid") } for i := 0; i < b.N; i++ { if uuid.URN() == "" { b.Fatal("invalid uuid") } } } func BenchmarkUUID_Array(b *testing.B) { expect := Array{ 0xf4, 0x7a, 0xc1, 0x0b, 0x58, 0xcc, 0x03, 0x72, 0x85, 0x67, 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79, } uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") if uuid == nil { b.Fatal("invalid uuid") } for i := 0; i < b.N; i++ { if uuid.Array() != expect { b.Fatal("invalid array") } } } func BenchmarkArray_UUID(b *testing.B) { array := Array{ 0xf4, 0x7a, 0xc1, 0x0b, 0x58, 0xcc, 0x03, 0x72, 0x85, 0x67, 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79, } expect := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") if expect == nil { b.Fatal("invalid uuid") } for i := 0; i < b.N; i++ { if !bytes.Equal(array.UUID(), expect) { b.Fatal("invalid uuid") } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/uuid.go�������������������������������������������������0000644�0610621�0607500�00000010731�13172163430�023164� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "bytes" "crypto/rand" "encoding/hex" "fmt" "io" "strings" ) // Array is a pass-by-value UUID that can be used as an effecient key in a map. type Array [16]byte // UUID converts uuid into a slice. func (uuid Array) UUID() UUID { return uuid[:] } // String returns the string representation of uuid, // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. func (uuid Array) String() string { return uuid.UUID().String() } // A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC // 4122. type UUID []byte // A Version represents a UUIDs version. type Version byte // A Variant represents a UUIDs variant. type Variant byte // Constants returned by Variant. const ( Invalid = Variant(iota) // Invalid UUID RFC4122 // The variant specified in RFC4122 Reserved // Reserved, NCS backward compatibility. Microsoft // Reserved, Microsoft Corporation backward compatibility. Future // Reserved for future definition. ) var rander = rand.Reader // random function // New returns a new random (version 4) UUID as a string. It is a convenience // function for NewRandom().String(). func New() string { return NewRandom().String() } // Parse decodes s into a UUID or returns nil. Both the UUID form of // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded. func Parse(s string) UUID { if len(s) == 36+9 { if strings.ToLower(s[:9]) != "urn:uuid:" { return nil } s = s[9:] } else if len(s) != 36 { return nil } if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { return nil } var uuid [16]byte for i, x := range [16]int{ 0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} { if v, ok := xtob(s[x:]); !ok { return nil } else { uuid[i] = v } } return uuid[:] } // Equal returns true if uuid1 and uuid2 are equal. func Equal(uuid1, uuid2 UUID) bool { return bytes.Equal(uuid1, uuid2) } // Array returns an array representation of uuid that can be used as a map key. // Array panics if uuid is not valid. func (uuid UUID) Array() Array { if len(uuid) != 16 { panic("invalid uuid") } var a Array copy(a[:], uuid) return a } // String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // , or "" if uuid is invalid. func (uuid UUID) String() string { if len(uuid) != 16 { return "" } var buf [36]byte encodeHex(buf[:], uuid) return string(buf[:]) } // URN returns the RFC 2141 URN form of uuid, // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. func (uuid UUID) URN() string { if len(uuid) != 16 { return "" } var buf [36 + 9]byte copy(buf[:], "urn:uuid:") encodeHex(buf[9:], uuid) return string(buf[:]) } func encodeHex(dst []byte, uuid UUID) { hex.Encode(dst[:], uuid[:4]) dst[8] = '-' hex.Encode(dst[9:13], uuid[4:6]) dst[13] = '-' hex.Encode(dst[14:18], uuid[6:8]) dst[18] = '-' hex.Encode(dst[19:23], uuid[8:10]) dst[23] = '-' hex.Encode(dst[24:], uuid[10:]) } // Variant returns the variant encoded in uuid. It returns Invalid if // uuid is invalid. func (uuid UUID) Variant() Variant { if len(uuid) != 16 { return Invalid } switch { case (uuid[8] & 0xc0) == 0x80: return RFC4122 case (uuid[8] & 0xe0) == 0xc0: return Microsoft case (uuid[8] & 0xe0) == 0xe0: return Future default: return Reserved } } // Version returns the version of uuid. It returns false if uuid is not // valid. func (uuid UUID) Version() (Version, bool) { if len(uuid) != 16 { return 0, false } return Version(uuid[6] >> 4), true } func (v Version) String() string { if v > 15 { return fmt.Sprintf("BAD_VERSION_%d", v) } return fmt.Sprintf("VERSION_%d", v) } func (v Variant) String() string { switch v { case RFC4122: return "RFC4122" case Reserved: return "Reserved" case Microsoft: return "Microsoft" case Future: return "Future" case Invalid: return "Invalid" } return fmt.Sprintf("BadVariant%d", int(v)) } // SetRand sets the random number generator to r, which implements io.Reader. // If r.Read returns an error when the package requests random data then // a panic will be issued. // // Calling SetRand with nil sets the random number generator to the default // generator. func SetRand(r io.Reader) { if r == nil { rander = rand.Reader return } rander = r } ���������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/util.go�������������������������������������������������0000644�0610621�0607500�00000003611�13172163430�023172� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "io" ) // randomBits completely fills slice b with random data. func randomBits(b []byte) { if _, err := io.ReadFull(rander, b); err != nil { panic(err.Error()) // rand should never fail } } // xvalues returns the value of a byte as a hexadecimal digit or 255. var xvalues = [256]byte{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, } // xtob converts the the first two hex bytes of x into a byte. func xtob(x string) (byte, bool) { b1 := xvalues[x[0]] b2 := xvalues[x[1]] return (b1 << 4) | b2, b1 != 255 && b2 != 255 } �����������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/time.go�������������������������������������������������0000644�0610621�0607500�00000007240�13172163430�023155� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "encoding/binary" "sync" "time" ) // A Time represents a time as the number of 100's of nanoseconds since 15 Oct // 1582. type Time int64 const ( lillian = 2299160 // Julian day of 15 Oct 1582 unix = 2440587 // Julian day of 1 Jan 1970 epoch = unix - lillian // Days between epochs g1582 = epoch * 86400 // seconds between epochs g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs ) var ( timeMu sync.Mutex lasttime uint64 // last time we returned clock_seq uint16 // clock sequence for this run timeNow = time.Now // for testing ) // UnixTime converts t the number of seconds and nanoseconds using the Unix // epoch of 1 Jan 1970. func (t Time) UnixTime() (sec, nsec int64) { sec = int64(t - g1582ns100) nsec = (sec % 10000000) * 100 sec /= 10000000 return sec, nsec } // GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and // clock sequence as well as adjusting the clock sequence as needed. An error // is returned if the current time cannot be determined. func GetTime() (Time, uint16, error) { defer timeMu.Unlock() timeMu.Lock() return getTime() } func getTime() (Time, uint16, error) { t := timeNow() // If we don't have a clock sequence already, set one. if clock_seq == 0 { setClockSequence(-1) } now := uint64(t.UnixNano()/100) + g1582ns100 // If time has gone backwards with this clock sequence then we // increment the clock sequence if now <= lasttime { clock_seq = ((clock_seq + 1) & 0x3fff) | 0x8000 } lasttime = now return Time(now), clock_seq, nil } // ClockSequence returns the current clock sequence, generating one if not // already set. The clock sequence is only used for Version 1 UUIDs. // // The uuid package does not use global static storage for the clock sequence or // the last time a UUID was generated. Unless SetClockSequence a new random // clock sequence is generated the first time a clock sequence is requested by // ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated // for func ClockSequence() int { defer timeMu.Unlock() timeMu.Lock() return clockSequence() } func clockSequence() int { if clock_seq == 0 { setClockSequence(-1) } return int(clock_seq & 0x3fff) } // SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to // -1 causes a new sequence to be generated. func SetClockSequence(seq int) { defer timeMu.Unlock() timeMu.Lock() setClockSequence(seq) } func setClockSequence(seq int) { if seq == -1 { var b [2]byte randomBits(b[:]) // clock sequence seq = int(b[0])<<8 | int(b[1]) } old_seq := clock_seq clock_seq = uint16(seq&0x3fff) | 0x8000 // Set our variant if old_seq != clock_seq { lasttime = 0 } } // Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in // uuid. It returns false if uuid is not valid. The time is only well defined // for version 1 and 2 UUIDs. func (uuid UUID) Time() (Time, bool) { if len(uuid) != 16 { return 0, false } time := int64(binary.BigEndian.Uint32(uuid[0:4])) time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 return Time(time), true } // ClockSequence returns the clock sequence encoded in uuid. It returns false // if uuid is not valid. The clock sequence is only well defined for version 1 // and 2 UUIDs. func (uuid UUID) ClockSequence() (int, bool) { if len(uuid) != 16 { return 0, false } return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff, true } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/sql_test.go���������������������������������������������0000644�0610621�0607500�00000004061�13172163430�024053� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "strings" "testing" ) func TestScan(t *testing.T) { var stringTest string = "f47ac10b-58cc-0372-8567-0e02b2c3d479" var byteTest []byte = Parse(stringTest) var badTypeTest int = 6 var invalidTest string = "f47ac10b-58cc-0372-8567-0e02b2c3d4" // sunny day tests var uuid UUID err := (&uuid).Scan(stringTest) if err != nil { t.Fatal(err) } err = (&uuid).Scan([]byte(stringTest)) if err != nil { t.Fatal(err) } err = (&uuid).Scan(byteTest) if err != nil { t.Fatal(err) } // bad type tests err = (&uuid).Scan(badTypeTest) if err == nil { t.Error("int correctly parsed and shouldn't have") } if !strings.Contains(err.Error(), "unable to scan type") { t.Error("attempting to parse an int returned an incorrect error message") } // invalid/incomplete uuids err = (&uuid).Scan(invalidTest) if err == nil { t.Error("invalid uuid was parsed without error") } if !strings.Contains(err.Error(), "invalid UUID") { t.Error("attempting to parse an invalid UUID returned an incorrect error message") } err = (&uuid).Scan(byteTest[:len(byteTest)-2]) if err == nil { t.Error("invalid byte uuid was parsed without error") } if !strings.Contains(err.Error(), "invalid UUID") { t.Error("attempting to parse an invalid byte UUID returned an incorrect error message") } // empty tests uuid = nil var emptySlice []byte err = (&uuid).Scan(emptySlice) if err != nil { t.Fatal(err) } if uuid != nil { t.Error("UUID was not nil after scanning empty byte slice") } uuid = nil var emptyString string err = (&uuid).Scan(emptyString) if err != nil { t.Fatal(err) } if uuid != nil { t.Error("UUID was not nil after scanning empty string") } } func TestValue(t *testing.T) { stringTest := "f47ac10b-58cc-0372-8567-0e02b2c3d479" uuid := Parse(stringTest) val, _ := uuid.Value() if val != stringTest { t.Error("Value() did not return expected string") } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/sql.go��������������������������������������������������0000644�0610621�0607500�00000003056�13172163430�023017� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "database/sql/driver" "errors" "fmt" ) // Scan implements sql.Scanner so UUIDs can be read from databases transparently // Currently, database types that map to string and []byte are supported. Please // consult database-specific driver documentation for matching types. func (uuid *UUID) Scan(src interface{}) error { switch src.(type) { case string: // if an empty UUID comes from a table, we return a null UUID if src.(string) == "" { return nil } // see uuid.Parse for required string format parsed := Parse(src.(string)) if parsed == nil { return errors.New("Scan: invalid UUID format") } *uuid = parsed case []byte: b := src.([]byte) // if an empty UUID comes from a table, we return a null UUID if len(b) == 0 { return nil } // assumes a simple slice of bytes if 16 bytes // otherwise attempts to parse if len(b) == 16 { *uuid = UUID(b) } else { u := Parse(string(b)) if u == nil { return errors.New("Scan: invalid UUID format") } *uuid = u } default: return fmt.Errorf("Scan: unable to scan type %T into UUID", src) } return nil } // Value implements sql.Valuer so that UUIDs can be written to databases // transparently. Currently, UUIDs map to strings. Please consult // database-specific driver documentation for matching types. func (uuid UUID) Value() (driver.Value, error) { return uuid.String(), nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/seq_test.go���������������������������������������������0000644�0610621�0607500�00000002634�13172163430�024050� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "flag" "runtime" "testing" "time" ) // This test is only run when --regressions is passed on the go test line. var regressions = flag.Bool("regressions", false, "run uuid regression tests") // TestClockSeqRace tests for a particular race condition of returning two // identical Version1 UUIDs. The duration of 1 minute was chosen as the race // condition, before being fixed, nearly always occured in under 30 seconds. func TestClockSeqRace(t *testing.T) { if !*regressions { t.Skip("skipping regression tests") } duration := time.Minute done := make(chan struct{}) defer close(done) ch := make(chan UUID, 10000) ncpu := runtime.NumCPU() switch ncpu { case 0, 1: // We can't run the test effectively. t.Skip("skipping race test, only one CPU detected") return default: runtime.GOMAXPROCS(ncpu) } for i := 0; i < ncpu; i++ { go func() { for { select { case <-done: return case ch <- NewUUID(): } } }() } uuids := make(map[string]bool) cnt := 0 start := time.Now() for u := range ch { s := u.String() if uuids[s] { t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s) return } uuids[s] = true if time.Since(start) > duration { return } cnt++ } } ����������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/node.go�������������������������������������������������0000644�0610621�0607500�00000005310�13172163430�023140� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "net" "sync" ) var ( nodeMu sync.Mutex interfaces []net.Interface // cached list of interfaces ifname string // name of interface being used nodeID []byte // hardware for version 1 UUIDs ) // NodeInterface returns the name of the interface from which the NodeID was // derived. The interface "user" is returned if the NodeID was set by // SetNodeID. func NodeInterface() string { defer nodeMu.Unlock() nodeMu.Lock() return ifname } // SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. // If name is "" then the first usable interface found will be used or a random // Node ID will be generated. If a named interface cannot be found then false // is returned. // // SetNodeInterface never fails when name is "". func SetNodeInterface(name string) bool { defer nodeMu.Unlock() nodeMu.Lock() return setNodeInterface(name) } func setNodeInterface(name string) bool { if interfaces == nil { var err error interfaces, err = net.Interfaces() if err != nil && name != "" { return false } } for _, ifs := range interfaces { if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { if setNodeID(ifs.HardwareAddr) { ifname = ifs.Name return true } } } // We found no interfaces with a valid hardware address. If name // does not specify a specific interface generate a random Node ID // (section 4.1.6) if name == "" { if nodeID == nil { nodeID = make([]byte, 6) } randomBits(nodeID) return true } return false } // NodeID returns a slice of a copy of the current Node ID, setting the Node ID // if not already set. func NodeID() []byte { defer nodeMu.Unlock() nodeMu.Lock() if nodeID == nil { setNodeInterface("") } nid := make([]byte, 6) copy(nid, nodeID) return nid } // SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes // of id are used. If id is less than 6 bytes then false is returned and the // Node ID is not set. func SetNodeID(id []byte) bool { defer nodeMu.Unlock() nodeMu.Lock() if setNodeID(id) { ifname = "user" return true } return false } func setNodeID(id []byte) bool { if len(id) < 6 { return false } if nodeID == nil { nodeID = make([]byte, 6) } copy(nodeID, id) return true } // NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is // not valid. The NodeID is only well defined for version 1 and 2 UUIDs. func (uuid UUID) NodeID() []byte { if len(uuid) != 16 { return nil } node := make([]byte, 6) copy(node, uuid[10:]) return node } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/marshal_test.go�����������������������������������������0000644�0610621�0607500�00000005151�13172163430�024704� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "bytes" "encoding/json" "reflect" "testing" ) var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") var testArray = testUUID.Array() func TestJSON(t *testing.T) { type S struct { ID1 UUID ID2 UUID } s1 := S{ID1: testUUID} data, err := json.Marshal(&s1) if err != nil { t.Fatal(err) } var s2 S if err := json.Unmarshal(data, &s2); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&s1, &s2) { t.Errorf("got %#v, want %#v", s2, s1) } } func TestJSONArray(t *testing.T) { type S struct { ID1 Array ID2 Array } s1 := S{ID1: testArray} data, err := json.Marshal(&s1) if err != nil { t.Fatal(err) } var s2 S if err := json.Unmarshal(data, &s2); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&s1, &s2) { t.Errorf("got %#v, want %#v", s2, s1) } } func TestMarshal(t *testing.T) { data, err := testUUID.MarshalBinary() if err != nil { t.Fatalf("MarhsalBinary returned unexpected error %v", err) } if !bytes.Equal(data, testUUID) { t.Fatalf("MarhsalBinary returns %x, want %x", data, testUUID) } var u UUID u.UnmarshalBinary(data) if !Equal(data, u) { t.Fatalf("UnmarhsalBinary returns %v, want %v", u, testUUID) } } func TestMarshalArray(t *testing.T) { data, err := testArray.MarshalBinary() if err != nil { t.Fatalf("MarhsalBinary returned unexpected error %v", err) } if !bytes.Equal(data, testUUID) { t.Fatalf("MarhsalBinary returns %x, want %x", data, testUUID) } var a Array a.UnmarshalBinary(data) if a != testArray { t.Fatalf("UnmarhsalBinary returns %v, want %v", a, testArray) } } func TestMarshalTextArray(t *testing.T) { data, err := testArray.MarshalText() if err != nil { t.Fatalf("MarhsalText returned unexpected error %v", err) } var a Array a.UnmarshalText(data) if a != testArray { t.Fatalf("UnmarhsalText returns %v, want %v", a, testArray) } } func BenchmarkUUID_MarshalJSON(b *testing.B) { x := &struct { UUID UUID `json:"uuid"` }{} x.UUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") if x.UUID == nil { b.Fatal("invalid uuid") } for i := 0; i < b.N; i++ { js, err := json.Marshal(x) if err != nil { b.Fatalf("marshal json: %#v (%v)", js, err) } } } func BenchmarkUUID_UnmarshalJSON(b *testing.B) { js := []byte(`{"uuid":"f47ac10b-58cc-0372-8567-0e02b2c3d479"}`) var x *struct { UUID UUID `json:"uuid"` } for i := 0; i < b.N; i++ { err := json.Unmarshal(js, &x) if err != nil { b.Fatalf("marshal json: %#v (%v)", js, err) } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/marshal.go����������������������������������������������0000644�0610621�0607500�00000003404�13172163430�023644� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "errors" "fmt" ) // MarshalText implements encoding.TextMarshaler. func (u UUID) MarshalText() ([]byte, error) { if len(u) != 16 { return nil, nil } var js [36]byte encodeHex(js[:], u) return js[:], nil } // UnmarshalText implements encoding.TextUnmarshaler. func (u *UUID) UnmarshalText(data []byte) error { if len(data) == 0 { return nil } id := Parse(string(data)) if id == nil { return errors.New("invalid UUID") } *u = id return nil } // MarshalBinary implements encoding.BinaryMarshaler. func (u UUID) MarshalBinary() ([]byte, error) { return u[:], nil } // UnmarshalBinary implements encoding.BinaryUnmarshaler. func (u *UUID) UnmarshalBinary(data []byte) error { if len(data) == 0 { return nil } if len(data) != 16 { return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) } var id [16]byte copy(id[:], data) *u = id[:] return nil } // MarshalText implements encoding.TextMarshaler. func (u Array) MarshalText() ([]byte, error) { var js [36]byte encodeHex(js[:], u[:]) return js[:], nil } // UnmarshalText implements encoding.TextUnmarshaler. func (u *Array) UnmarshalText(data []byte) error { id := Parse(string(data)) if id == nil { return errors.New("invalid UUID") } *u = id.Array() return nil } // MarshalBinary implements encoding.BinaryMarshaler. func (u Array) MarshalBinary() ([]byte, error) { return u[:], nil } // UnmarshalBinary implements encoding.BinaryUnmarshaler. func (u *Array) UnmarshalBinary(data []byte) error { if len(data) != 16 { return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) } copy(u[:], data) return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/hash.go�������������������������������������������������0000644�0610621�0607500�00000003211�13172163430�023134� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "crypto/md5" "crypto/sha1" "hash" ) // Well known Name Space IDs and UUIDs var ( NameSpace_DNS = Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8") NameSpace_URL = Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8") NameSpace_OID = Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8") NameSpace_X500 = Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8") NIL = Parse("00000000-0000-0000-0000-000000000000") ) // NewHash returns a new UUID derived from the hash of space concatenated with // data generated by h. The hash should be at least 16 byte in length. The // first 16 bytes of the hash are used to form the UUID. The version of the // UUID will be the lower 4 bits of version. NewHash is used to implement // NewMD5 and NewSHA1. func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { h.Reset() h.Write(space) h.Write([]byte(data)) s := h.Sum(nil) uuid := make([]byte, 16) copy(uuid, s) uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant return uuid } // NewMD5 returns a new MD5 (Version 3) UUID based on the // supplied name space and data. // // NewHash(md5.New(), space, data, 3) func NewMD5(space UUID, data []byte) UUID { return NewHash(md5.New(), space, data, 3) } // NewSHA1 returns a new SHA1 (Version 5) UUID based on the // supplied name space and data. // // NewHash(sha1.New(), space, data, 5) func NewSHA1(space UUID, data []byte) UUID { return NewHash(sha1.New(), space, data, 5) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/doc.go��������������������������������������������������0000644�0610621�0607500�00000000461�13172163430�022762� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The uuid package generates and inspects UUIDs. // // UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services. package uuid ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/dce.go��������������������������������������������������0000644�0610621�0607500�00000004062�13172163430�022751� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "encoding/binary" "fmt" "os" ) // A Domain represents a Version 2 domain type Domain byte // Domain constants for DCE Security (Version 2) UUIDs. const ( Person = Domain(0) Group = Domain(1) Org = Domain(2) ) // NewDCESecurity returns a DCE Security (Version 2) UUID. // // The domain should be one of Person, Group or Org. // On a POSIX system the id should be the users UID for the Person // domain and the users GID for the Group. The meaning of id for // the domain Org or on non-POSIX systems is site defined. // // For a given domain/id pair the same token may be returned for up to // 7 minutes and 10 seconds. func NewDCESecurity(domain Domain, id uint32) UUID { uuid := NewUUID() if uuid != nil { uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 uuid[9] = byte(domain) binary.BigEndian.PutUint32(uuid[0:], id) } return uuid } // NewDCEPerson returns a DCE Security (Version 2) UUID in the person // domain with the id returned by os.Getuid. // // NewDCEPerson(Person, uint32(os.Getuid())) func NewDCEPerson() UUID { return NewDCESecurity(Person, uint32(os.Getuid())) } // NewDCEGroup returns a DCE Security (Version 2) UUID in the group // domain with the id returned by os.Getgid. // // NewDCEGroup(Group, uint32(os.Getgid())) func NewDCEGroup() UUID { return NewDCESecurity(Group, uint32(os.Getgid())) } // Domain returns the domain for a Version 2 UUID or false. func (uuid UUID) Domain() (Domain, bool) { if v, _ := uuid.Version(); v != 2 { return 0, false } return Domain(uuid[9]), true } // Id returns the id for a Version 2 UUID or false. func (uuid UUID) Id() (uint32, bool) { if v, _ := uuid.Version(); v != 2 { return 0, false } return binary.BigEndian.Uint32(uuid[0:4]), true } func (d Domain) String() string { switch d { case Person: return "Person" case Group: return "Group" case Org: return "Org" } return fmt.Sprintf("Domain%d", int(d)) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/README.md�����������������������������������������������0000644�0610621�0607500�00000001222�13172163430�023141� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������This project was automatically exported from code.google.com/p/go-uuid # uuid ![build status](https://travis-ci.org/pborman/uuid.svg?branch=master) The uuid package generates and inspects UUIDs based on [RFC 4122](http://tools.ietf.org/html/rfc4122) and DCE 1.1: Authentication and Security Services. ###### Install `go get github.com/pborman/uuid` ###### Documentation [![GoDoc](https://godoc.org/github.com/pborman/uuid?status.svg)](http://godoc.org/github.com/pborman/uuid) Full `go doc` style documentation for the package can be viewed online without installing this package by using the GoDoc site here: http://godoc.org/github.com/pborman/uuid ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/LICENSE�������������������������������������������������0000644�0610621�0607500�00000002710�13172163430�022672� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2009,2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ��������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/CONTRIBUTORS��������������������������������������������0000644�0610621�0607500�00000000040�13172163430�023537� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Paul Borman <borman@google.com> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/CONTRIBUTING.md�����������������������������������������0000644�0610621�0607500�00000000470�13172163430�024117� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# How to contribute We definitely welcome patches and contribution to this project! ### Legal requirements In order to protect both you and ourselves, you will need to sign the [Contributor License Agreement](https://cla.developers.google.com/clas). You may have already signed it for other Google projects. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/pborman/uuid/.travis.yml���������������������������������������������0000644�0610621�0607500�00000000114�13172163430�023772� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go: - 1.4.3 - 1.5.3 - tip script: - go test -v ./... ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163422�022310� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/���������������������������������������0000755�0610621�0607500�00000000000�13172163423�025207� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/petname_test.go������������������������0000644�0610621�0607500�00000002140�13172163423�030223� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* petname: test of library for generating human-readable, random names for objects (e.g. hostnames, containers, blobs) Copyright 2014 Dustin Kirkland <dustin.kirkland@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package petname is a library for generating human-readable, random // names for objects (e.g. hostnames, containers, blobs). package petname import ( "testing" ) // Make sure the generated names exist func TestPetName(t *testing.T) { for i:=0; i<10; i++ { name := Generate(i, "-") if name == "" { t.Fatalf("Did not generate a %d-word name, '%s'", i, name) } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/petname.go�����������������������������0000644�0610621�0607500�00000034514�13172163423�027176� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* petname: library for generating human-readable, random names for objects (e.g. hostnames, containers, blobs) Copyright 2014 Dustin Kirkland <dustin.kirkland@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package petname is a library for generating human-readable, random // names for objects (e.g. hostnames, containers, blobs). package petname import ( "math/rand" "strings" ) // These lists are autogenerated from the master lists in the project: // - https://github.com/dustinkirkland/petname // These lists only get modified after updating that branch, and then // automatically updated by ./debian/update-wordlists.sh as part of // my release process var ( adjectives = [...]string{"able", "above", "absolute", "accepted", "accurate", "ace", "active", "actual", "adapted", "adapting", "adequate", "adjusted", "advanced", "alert", "alive", "allowed", "allowing", "amazed", "amazing", "ample", "amused", "amusing", "apparent", "apt", "arriving", "artistic", "assured", "assuring", "awaited", "awake", "aware", "balanced", "becoming", "beloved", "better", "big", "blessed", "bold", "boss", "brave", "brief", "bright", "bursting", "busy", "calm", "capable", "capital", "careful", "caring", "casual", "causal", "central", "certain", "champion", "charmed", "charming", "cheerful", "chief", "choice", "civil", "classic", "clean", "clear", "clever", "climbing", "close", "closing", "coherent", "comic", "communal", "complete", "composed", "concise", "concrete", "content", "cool", "correct", "cosmic", "crack", "creative", "credible", "crisp", "crucial", "cuddly", "cunning", "curious", "current", "cute", "daring", "darling", "dashing", "dear", "decent", "deciding", "deep", "definite", "delicate", "desired", "destined", "devoted", "direct", "discrete", "distinct", "diverse", "divine", "dominant", "driven", "driving", "dynamic", "eager", "easy", "electric", "elegant", "emerging", "eminent", "enabled", "enabling", "endless", "engaged", "engaging", "enhanced", "enjoyed", "enormous", "enough", "epic", "equal", "equipped", "eternal", "ethical", "evident", "evolved", "evolving", "exact", "excited", "exciting", "exotic", "expert", "factual", "fair", "faithful", "famous", "fancy", "fast", "feasible", "fine", "finer", "firm", "first", "fit", "fitting", "fleet", "flexible", "flowing", "fluent", "flying", "fond", "frank", "free", "fresh", "full", "fun", "funky", "funny", "game", "generous", "gentle", "genuine", "giving", "glad", "glorious", "glowing", "golden", "good", "gorgeous", "grand", "grateful", "great", "growing", "grown", "guided", "guiding", "handy", "happy", "hardy", "harmless", "healthy", "helped", "helpful", "helping", "heroic", "hip", "holy", "honest", "hopeful", "hot", "huge", "humane", "humble", "humorous", "ideal", "immense", "immortal", "immune", "improved", "in", "included", "infinite", "informed", "innocent", "inspired", "integral", "intense", "intent", "internal", "intimate", "inviting", "joint", "just", "keen", "key", "kind", "knowing", "known", "large", "lasting", "leading", "learning", "legal", "legible", "lenient", "liberal", "light", "liked", "literate", "live", "living", "logical", "loved", "loving", "loyal", "lucky", "magical", "magnetic", "main", "major", "many", "massive", "master", "mature", "maximum", "measured", "meet", "merry", "mighty", "mint", "model", "modern", "modest", "moral", "more", "moved", "moving", "musical", "mutual", "national", "native", "natural", "nearby", "neat", "needed", "neutral", "new", "next", "nice", "noble", "normal", "notable", "noted", "novel", "obliging", "on", "one", "open", "optimal", "optimum", "organic", "oriented", "outgoing", "patient", "peaceful", "perfect", "pet", "picked", "pleasant", "pleased", "pleasing", "poetic", "polished", "polite", "popular", "positive", "possible", "powerful", "precious", "precise", "premium", "prepared", "present", "pretty", "primary", "prime", "pro", "probable", "profound", "promoted", "prompt", "proper", "proud", "proven", "pumped", "pure", "quality", "quick", "quiet", "rapid", "rare", "rational", "ready", "real", "refined", "regular", "related", "relative", "relaxed", "relaxing", "relevant", "relieved", "renewed", "renewing", "resolved", "rested", "rich", "right", "robust", "romantic", "ruling", "sacred", "safe", "saved", "saving", "secure", "select", "selected", "sensible", "set", "settled", "settling", "sharing", "sharp", "shining", "simple", "sincere", "singular", "skilled", "smart", "smashing", "smiling", "smooth", "social", "solid", "sought", "sound", "special", "splendid", "square", "stable", "star", "steady", "sterling", "still", "stirred", "stirring", "striking", "strong", "stunning", "subtle", "suitable", "suited", "summary", "sunny", "super", "superb", "supreme", "sure", "sweeping", "sweet", "talented", "teaching", "tender", "thankful", "thorough", "tidy", "tight", "together", "tolerant", "top", "topical", "tops", "touched", "touching", "tough", "true", "trusted", "trusting", "trusty", "ultimate", "unbiased", "uncommon", "unified", "unique", "united", "up", "upright", "upward", "usable", "useful", "valid", "valued", "vast", "verified", "viable", "vital", "vocal", "wanted", "warm", "wealthy", "welcome", "welcomed", "well", "whole", "willing", "winning", "wired", "wise", "witty", "wondrous", "workable", "working", "worthy"} adverbs = [...]string{"abnormally", "absolutely", "accurately", "actively", "actually", "adequately", "admittedly", "adversely", "allegedly", "amazingly", "annually", "apparently", "arguably", "awfully", "badly", "barely", "basically", "blatantly", "blindly", "briefly", "brightly", "broadly", "carefully", "centrally", "certainly", "cheaply", "cleanly", "clearly", "closely", "commonly", "completely", "constantly", "conversely", "correctly", "curiously", "currently", "daily", "deadly", "deeply", "definitely", "directly", "distinctly", "duly", "eagerly", "early", "easily", "eminently", "endlessly", "enormously", "entirely", "equally", "especially", "evenly", "evidently", "exactly", "explicitly", "externally", "extremely", "factually", "fairly", "finally", "firmly", "firstly", "forcibly", "formally", "formerly", "frankly", "freely", "frequently", "friendly", "fully", "generally", "gently", "genuinely", "ghastly", "gladly", "globally", "gradually", "gratefully", "greatly", "grossly", "happily", "hardly", "heartily", "heavily", "hideously", "highly", "honestly", "hopefully", "hopelessly", "horribly", "hugely", "humbly", "ideally", "illegally", "immensely", "implicitly", "incredibly", "indirectly", "infinitely", "informally", "inherently", "initially", "instantly", "intensely", "internally", "jointly", "jolly", "kindly", "largely", "lately", "legally", "lightly", "likely", "literally", "lively", "locally", "logically", "loosely", "loudly", "lovely", "luckily", "mainly", "manually", "marginally", "mentally", "merely", "mildly", "miserably", "mistakenly", "moderately", "monthly", "morally", "mostly", "multiply", "mutually", "namely", "nationally", "naturally", "nearly", "neatly", "needlessly", "newly", "nicely", "nominally", "normally", "notably", "noticeably", "obviously", "oddly", "officially", "only", "openly", "optionally", "overly", "painfully", "partially", "partly", "perfectly", "personally", "physically", "plainly", "pleasantly", "poorly", "positively", "possibly", "precisely", "preferably", "presently", "presumably", "previously", "primarily", "privately", "probably", "promptly", "properly", "publicly", "purely", "quickly", "quietly", "radically", "randomly", "rapidly", "rarely", "rationally", "readily", "really", "reasonably", "recently", "regularly", "reliably", "remarkably", "remotely", "repeatedly", "rightly", "roughly", "routinely", "sadly", "safely", "scarcely", "secondly", "secretly", "seemingly", "sensibly", "separately", "seriously", "severely", "sharply", "shortly", "similarly", "simply", "sincerely", "singularly", "slightly", "slowly", "smoothly", "socially", "solely", "specially", "steadily", "strangely", "strictly", "strongly", "subtly", "suddenly", "suitably", "supposedly", "surely", "terminally", "terribly", "thankfully", "thoroughly", "tightly", "totally", "trivially", "truly", "typically", "ultimately", "unduly", "uniformly", "uniquely", "unlikely", "urgently", "usefully", "usually", "utterly", "vaguely", "vastly", "verbally", "vertically", "vigorously", "violently", "virtually", "visually", "weekly", "wholly", "widely", "wildly", "willingly", "wrongly", "yearly"} names = [...]string{"ox", "ant", "ape", "asp", "bat", "bee", "boa", "bug", "cat", "cod", "cow", "cub", "doe", "dog", "eel", "eft", "elf", "elk", "emu", "ewe", "fly", "fox", "gar", "gnu", "hen", "hog", "imp", "jay", "kid", "kit", "koi", "lab", "man", "owl", "pig", "pug", "pup", "ram", "rat", "ray", "yak", "bass", "bear", "bird", "boar", "buck", "bull", "calf", "chow", "clam", "colt", "crab", "crow", "dane", "deer", "dodo", "dory", "dove", "drum", "duck", "fawn", "fish", "flea", "foal", "fowl", "frog", "gnat", "goat", "grub", "gull", "hare", "hawk", "ibex", "joey", "kite", "kiwi", "lamb", "lark", "lion", "loon", "lynx", "mako", "mink", "mite", "mole", "moth", "mule", "mutt", "newt", "orca", "oryx", "pika", "pony", "puma", "seal", "shad", "slug", "sole", "stag", "stud", "swan", "tahr", "teal", "tick", "toad", "tuna", "wasp", "wolf", "worm", "wren", "yeti", "adder", "akita", "alien", "aphid", "bison", "boxer", "bream", "bunny", "burro", "camel", "chimp", "civet", "cobra", "coral", "corgi", "crane", "dingo", "drake", "eagle", "egret", "filly", "finch", "gator", "gecko", "ghost", "ghoul", "goose", "guppy", "heron", "hippo", "horse", "hound", "husky", "hyena", "koala", "krill", "leech", "lemur", "liger", "llama", "louse", "macaw", "midge", "molly", "moose", "moray", "mouse", "panda", "perch", "prawn", "quail", "racer", "raven", "rhino", "robin", "satyr", "shark", "sheep", "shrew", "skink", "skunk", "sloth", "snail", "snake", "snipe", "squid", "stork", "swift", "swine", "tapir", "tetra", "tiger", "troll", "trout", "viper", "wahoo", "whale", "zebra", "alpaca", "amoeba", "baboon", "badger", "beagle", "bedbug", "beetle", "bengal", "bobcat", "caiman", "cattle", "cicada", "collie", "condor", "cougar", "coyote", "dassie", "donkey", "dragon", "earwig", "falcon", "feline", "ferret", "gannet", "gibbon", "glider", "goblin", "gopher", "grouse", "guinea", "hermit", "hornet", "iguana", "impala", "insect", "jackal", "jaguar", "jennet", "kitten", "kodiak", "lizard", "locust", "maggot", "magpie", "mammal", "mantis", "marlin", "marmot", "marten", "martin", "mayfly", "minnow", "monkey", "mullet", "muskox", "ocelot", "oriole", "osprey", "oyster", "parrot", "pigeon", "piglet", "poodle", "possum", "python", "quagga", "rabbit", "raptor", "rodent", "roughy", "salmon", "sawfly", "serval", "shiner", "shrimp", "spider", "sponge", "tarpon", "thrush", "tomcat", "toucan", "turkey", "turtle", "urchin", "vervet", "walrus", "weasel", "weevil", "wombat", "anchovy", "anemone", "bluejay", "buffalo", "bulldog", "buzzard", "caribou", "catfish", "chamois", "cheetah", "chicken", "chigger", "cowbird", "crappie", "crawdad", "cricket", "dogfish", "dolphin", "firefly", "garfish", "gazelle", "gelding", "giraffe", "gobbler", "gorilla", "goshawk", "grackle", "griffon", "grizzly", "grouper", "haddock", "hagfish", "halibut", "hamster", "herring", "jackass", "javelin", "jawfish", "jaybird", "katydid", "ladybug", "lamprey", "lemming", "leopard", "lioness", "lobster", "macaque", "mallard", "mammoth", "manatee", "mastiff", "meerkat", "mollusk", "monarch", "mongrel", "monitor", "monster", "mudfish", "muskrat", "mustang", "narwhal", "oarfish", "octopus", "opossum", "ostrich", "panther", "peacock", "pegasus", "pelican", "penguin", "phoenix", "piranha", "polecat", "primate", "quetzal", "raccoon", "rattler", "redbird", "redfish", "reptile", "rooster", "sawfish", "sculpin", "seagull", "skylark", "snapper", "spaniel", "sparrow", "sunbeam", "sunbird", "sunfish", "tadpole", "termite", "terrier", "unicorn", "vulture", "wallaby", "walleye", "warthog", "whippet", "wildcat", "aardvark", "airedale", "albacore", "anteater", "antelope", "arachnid", "barnacle", "basilisk", "blowfish", "bluebird", "bluegill", "bonefish", "bullfrog", "cardinal", "chipmunk", "cockatoo", "crayfish", "dinosaur", "doberman", "duckling", "elephant", "escargot", "flamingo", "flounder", "foxhound", "glowworm", "goldfish", "grubworm", "hedgehog", "honeybee", "hookworm", "humpback", "kangaroo", "killdeer", "kingfish", "labrador", "lacewing", "ladybird", "lionfish", "longhorn", "mackerel", "malamute", "marmoset", "mastodon", "moccasin", "mongoose", "monkfish", "mosquito", "pangolin", "parakeet", "pheasant", "pipefish", "platypus", "polliwog", "porpoise", "reindeer", "ringtail", "sailfish", "scorpion", "seahorse", "seasnail", "sheepdog", "shepherd", "silkworm", "squirrel", "stallion", "starfish", "starling", "stingray", "stinkbug", "sturgeon", "terrapin", "titmouse", "tortoise", "treefrog", "werewolf", "woodcock"} ) // Adverb returns a random adverb from a list of petname adverbs. func Adverb() string { return adverbs[rand.Intn(len(adverbs))] } // Adjective returns a random adjective from a list of petname adjectives. func Adjective() string { return adjectives[rand.Intn(len(adjectives))] } // Name returns a random name from a list of petname names. func Name() string { return names[rand.Intn(len(names))] } // Generate generates and returns a random pet name. // It takes two parameters: the number of words in the name, and a separator token. // If a single word is requested, simply a Name() is returned. // If two words are requested, a Adjective() and a Name() are returned. // If three or more words are requested, a variable number of Adverb() and a Adjective and a Name() is returned. // The separator can be any charater, string, or the empty string. func Generate(words int, separator string) string { if words == 1 { return Name() } else if words == 2 { return Adjective() + separator + Name() } var petname []string for i := 0; i < words-2; i++ { petname = append(petname, Adverb()) } petname = append(petname, Adjective(), Name()) return strings.Join(petname, separator) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/golang-petname.1�����������������������0000644�0610621�0607500�00000003264�13172163423�030174� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������.TH golang-petname 1 "15 December 2014" golang-petname "golang-petname" .SH NAME golang-petname \- utility to generate "pet names", consisting of a random combination of adverbs, an adjective, and a proper name .SH SYNOPSIS \fBgolang-petname\fP [-w|--words INT] [-s|--separator STR] .SH OPTIONS --words number of words in the name, default is 2 --separator string used to separate name words, default is '-' .SH DESCRIPTION This utility will generate "pet names", consisting of a random combination of an adverb, adjective, and proper name. These are useful for unique hostnames, for instance. The default packaging contains about 2000 names, 1300 adjectives, and 4000 adverbs, yielding nearly 10 billion unique combinations, covering over 32 bits of unique namespace. As such, PetName tries to follow the tenets of Zooko's triangle. Names are: - human meaningful - decentralized - secure .SH EXAMPLES $ golang-petname wiggly-Anna $ golang-petname --words 1 Marco $ golang-petname --words 3 quickly-scornful-Johnathan $ golang-petname --words 4 dolorously-leisurely-wee-Susan $ golang-petname --separator ":" hospitable:Isla $ golang-petname --separator "" --words 3 adeptlystaticNicole .SH SEE ALSO \fIpetname\fP(1) .SH AUTHOR This manpage and the utility were written by Dustin Kirkland <dustin.kirkland@gmail.com> for Ubuntu systems (but may be used by others). Permission is granted to copy, distribute and/or modify this document and the utility under the terms of the Apache2 License. The complete text of the Apache2 License can be found in \fI/usr/share/common-licenses/Apache-2.0\fP on Debian/Ubuntu systems. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/��������������������������������0000755�0610621�0607500�00000000000�13172163423�026431� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/update-wordlists.sh�������������0000755�0610621�0607500�00000001404�13172163423�032301� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/sh # This script only needs to be run by the upstream package maintainer (Dustin Kirkland) # if the upstream petname wordlists change set -e PKG="petname" [ -d .bzr/ ] && bzr revert ${PKG}.go || true for f in adverbs adjectives names; do rm -f "$f".txt.list printf " $f = [...]string{" > "$f".txt.list for w in $(cat /usr/share/petname/"$f".txt); do printf '"%s", ' "$w" >> "$f".txt.list done sed -i -e "s/, $/}\n/" "$f".txt.list sed -i "/^\s\+${f}\s\+= \[\.\.\.\]string{.*$/d" ${PKG}.go done printf "\n)\n\n" >> "$f".txt.list grep -B 1000 "^var (" ${PKG}.go > above grep -A 1000 "^// Adverb returns" ${PKG}.go > below cat above *.txt.list below > ${PKG}.go go fmt ${PKG}.go rm -f *.txt.list above below cat /usr/share/doc/petname/README.md > README.md ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/source/�������������������������0000755�0610621�0607500�00000000000�13172163423�027731� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/source/format�������������������0000644�0610621�0607500�00000000014�13172163423�031137� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������3.0 (quilt) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/rules���������������������������0000755�0610621�0607500�00000001020�13172163423�027502� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/make -f ifneq ($(shell ls -d /usr/share/doc/golang-any-shared-dev/),/usr/share/doc/golang-any-shared-dev/) export DH_OPTIONS := -Nlibgolang-petname1 endif export DH_GOPKG := github.com/dustinkirkland/golang-petname %: dh $@ --buildsystem=golang --with=golang override_dh_install: mkdir -p ${PWD}/debian/tmp/usr/lib dh_install ifeq ($(shell ls -d /usr/share/doc/golang-any-shared-dev/),/usr/share/doc/golang-any-shared-dev/) override_dh_gencontrol: dh_gencontrol -- -V'extra:Depends=libgolang-petname1' endif ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/lintian-overrides���������������0000644�0610621�0607500�00000000125�13172163423�032010� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������golang-petname: unstripped-binary-or-object golang-petname: statically-linked-binary �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/golang-petname.install����������0000755�0610621�0607500�00000000167�13172163423�032726� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/dh-exec usr/bin/petname => /usr/bin/golang-petname golang-petname.1 => /usr/share/man/man1/golang-petname.1 ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/golang-petname-dev.install������0000644�0610621�0607500�00000000242�13172163423�033471� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������petname.go /usr/share/gocode/src/github.com/dustinkirkland/golang-petname petname_test.go /usr/share/gocode/src/github.com/dustinkirkland/golang-petname usr/lib/ ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/copyright�����������������������0000644�0610621�0607500�00000001675�13172163423�030375� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: golang-petname Upstream-Contact: Dustin Kirkland <dustin.kirkland@gmail.com> Source: http://launchpad.net/golang-petname Files: * Copyright: 2014, Dustin Kirkland <dustin.kirkland@gmail.com> License: Apache-2 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. On Debian systems, the complete text of the Apache version 2.0 license can be found in "/usr/share/common-licenses/Apache-2.0". �������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/control�������������������������0000644�0610621�0607500�00000004577�13172163423�030051� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Source: golang-petname Section: admin Priority: optional Maintainer: Dustin Kirkland <kirkland@ubuntu.com> Build-Depends: debhelper (>= 9), dh-exec, dh-golang, golang-go, golang-any-shared-dev | dh-apparmor Standards-Version: 3.9.5 Homepage: http://launchpad.net/petname Vcs-Browser: http://bazaar.launchpad.net/~petname/petname/trunk/files Vcs-Bzr: https://code.launchpad.net/petname/petname/trunk Package: golang-petname Architecture: any Depends: ${misc:Depends}, ${shlibs:Depends} Built-Using: ${misc:Built-Using} Description: generate pronouncable, perhaps even memorable, pet names This utility will generate "pet names", consisting of a random combination of an adverb, adjective, and proper name. These are useful for unique hostnames, for instance. The default packaging contains about 2000 names, 1300 adjectives, and 4000 adverbs, yielding nearly 10 billion unique combinations, covering over 32 bits of unique namespace. As such, PetName tries to follow the tenets of Zooko's triangle: names are human meaningful, decentralized, and secure. Package: golang-petname-dev Architecture: any Depends: ${misc:Depends}, ${extra:Depends} Description: golang library for generating pronouncable, memorable, pet names This package provides a library for generating "pet names", consisting of a random combination of an adverb, adjective, and proper name. These are useful for unique hostnames, for instance. The default packaging contains about 2000 names, 1300 adjectives, and 4000 adverbs, yielding nearly 10 billion unique combinations, covering over 32 bits of unique namespace. As such, PetName tries to follow the tenets of Zooko's triangle: names are human meaningful, decentralized, and secure. Package: golang-github-dustinkirkland-golang-petname-dev Architecture: all Depends: ${misc:Depends}, golang-petname-dev Description: golang library for generating pronouncable, memorable, pet names This is a metapackage for golang-petname-dev, which adheres to the naming convention. Package: libgolang-petname1 Architecture: any Depends: ${misc:Depends}, ${shlibs:Depends} Provides: ${golang:Provides} Description: golang library for generating pronouncable, memorable, pet names -- shared library This package provides a library for generating "pet names", consisting of a random combination of an adverb, adjective, and proper name. . This package provides the library built as a shared library. ���������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/compat��������������������������0000644�0610621�0607500�00000000002�13172163423�027627� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������9 ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/debian/changelog�����������������������0000644�0610621�0607500�00000017220�13172163423�030305� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������golang-petname (2.9) unreleased; urgency=medium * UNRELEASED -- Dustin Kirkland <kirkland@ubuntu.com> Thu, 21 Sep 2017 17:06:36 -0500 golang-petname (2.8-0ubuntu1) artful; urgency=medium * petname.go, README.md: - update wordlists, from petname upstream changes -- Dustin Kirkland <kirkland@ubuntu.com> Thu, 21 Sep 2017 17:06:33 -0500 golang-petname (2.7-0ubuntu1) artful; urgency=medium [ Brian Fallik ] * README.md: - https://github.com/dustinkirkland/golang-petname/pull/3 - update README.md to be Markdown compliant #3 * cmd/petname/main.go, petname.go: - move random seeding to the main function - callers of our library will need to ensure their PRNG is properly seeded -- Dustin Kirkland <kirkland@ubuntu.com> Thu, 27 Apr 2017 18:08:47 -0500 golang-petname (2.6-0ubuntu1) zesty; urgency=medium [ Michael Hudson-Doyle ] * Fix repeated use of shlibs:Depends substvar that lead to broken Depends. - https://github.com/dustinkirkland/golang-petname/pull/2 -- Dustin Kirkland <kirkland@ubuntu.com> Thu, 05 Jan 2017 15:50:06 -0600 golang-petname (2.5-0ubuntu1) zesty; urgency=medium [ Alexander Sack ] * petname.go: - initialize with a random seed, https://github.com/dustinkirkland/golang-petname/pull/1 -- Dustin Kirkland <kirkland@ubuntu.com> Mon, 14 Nov 2016 09:34:59 -0600 golang-petname (2.4-0ubuntu1) yakkety; urgency=medium * debian/control, debian/rules: LP: #1625753 - fix uninstallable golang-petname-dev on xenial -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 20 Sep 2016 14:48:06 -0500 golang-petname (2.3-0ubuntu1) yakkety; urgency=medium * debian/rules: - don't build libgolang-petname1 on xenial -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 23 Aug 2016 09:26:37 -0400 golang-petname (2.2-0ubuntu1) yakkety; urgency=medium * debian/rules, === removed directory usr, === removed directory usr/lib: - fix shared library build on yakkety while maintaining xenial no-shared-lib build -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 09 Aug 2016 18:04:30 -0500 golang-petname (2.1-0ubuntu1) yakkety; urgency=medium [ Michael Hudson-Doyle ] * debian/control, debian/golang-petname-dev.install: - Build shared lib package. [ Dustin Kirkland ] * === added directory usr, === added directory usr/lib, debian/control, debian/golang-petname-dev.install: - add a couple of hacks, to not break the build on releases before yakkety + namely, use a dummy (dh-apparmor) to ensure we can meet a build-dependency on xenial + create the usr/lib dir, and always install it -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 09 Aug 2016 16:25:53 -0500 golang-petname (2.0-0ubuntu1) yakkety; urgency=medium [ Dustin Kirkland ] * petname.go, README.md: - remove some non-words * debian/control, debian/golang-petname-dev.install: - reverting Michael's shared library changes, as it's breaking the build * petname.go, README.md: - bump to petname 2.0, using animals instead of people names, major change - rebuild with simplest, smallest wordlist -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 09 Aug 2016 14:17:20 -0500 golang-petname (1.10-0ubuntu1) xenial; urgency=medium [ Michael Hudson-Doyle ] * Make packaging more typical for a package that uses dh-golang. -- Dustin Kirkland <kirkland@ubuntu.com> Mon, 01 Feb 2016 11:14:50 -0600 golang-petname (1.9-0ubuntu1) xenial; urgency=medium * debian/golang-petname-dev.install, debian/rules: - install the source code to the appropriate location per http://pkg-go.alioth.debian.org/packaging.html#_file_locations - simplify build rules, remove strip override -- Dustin Kirkland <kirkland@ubuntu.com> Thu, 03 Dec 2015 10:07:22 -0600 golang-petname (1.8-0ubuntu1) xenial; urgency=medium * debian/control, debian/rules, debian/update-wordlists.sh: - remove build dependency on petname; only the maintainer ever needs to run update-wordlists -- Dustin Kirkland <kirkland@ubuntu.com> Wed, 02 Dec 2015 17:19:08 -0600 golang-petname (1.7-0ubuntu1) xenial; urgency=medium * debian/control, debian/rules: LP: #1520687 - fixes for MIR of -dev library package - add a build-depends on dh-golang - build --with=golang - note the binary was Built-Using - add a metapackage that meets the Debian standard naming for go libs -- Dustin Kirkland <kirkland@ubuntu.com> Wed, 02 Dec 2015 16:55:42 -0600 golang-petname (1.6-0ubuntu1) xenial; urgency=medium * No op change, testing gopkg in git * petname.go: - update wordlists, pruning blacklisted words -- Dustin Kirkland <kirkland@ubuntu.com> Fri, 30 Oct 2015 10:20:27 -0500 golang-petname (1.5-0ubuntu1) vivid; urgency=medium * debian/update-wordlists.sh, petname.go, README.md: - rebuild and release with updated wordlists -- Dustin Kirkland <kirkland@ubuntu.com> Wed, 28 Jan 2015 16:10:03 -0600 golang-petname (1.4-0ubuntu1) vivid; urgency=medium * cmd/petname/main.go, petname.go, petname_test.go: - change petname.PetName() to petname.Generate() -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 13 Jan 2015 11:19:06 -0600 golang-petname (1.3-0ubuntu1) vivid; urgency=medium * petname.go: - add note that these lists aren't manually updated/modified - drop the "Rand" prefix, which is implicit - no need for time module * cmd/petname/main.go, petname.go: - move the prng seeding to the end caller of the function - add our import deps, math/rand, time -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 13 Jan 2015 11:19:03 -0600 golang-petname (1.2-0ubuntu1) vivid; urgency=medium * petname.go, petname_test.go: - add some inline godoc documentation, fix format * remove stray file * debian/control: - arch: any, let it build where it builds * debian/copyright: - update upstream name * debian/update-wordlists.sh: - update word list location to share * petname.go: - update wordlists -- Dustin Kirkland <kirkland@ubuntu.com> Mon, 12 Jan 2015 09:53:24 -0600 golang-petname (1.1-0ubuntu1) vivid; urgency=medium * debian/update-wordlists.sh, petname.go: - update wordlists from upstream -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 16 Dec 2014 14:33:23 -0600 golang-petname (1.0-0ubuntu1) vivid; urgency=medium * adverbs.txt, debian/control, debian/petname.install, debian/python- petname.install, __init__.py, Makefile, names.txt, petname.go.in, petname/petname.py, petname/petname.py.in, === removed directory petname, setup.py, update.sh: - rework to a golang only package, rename accordingly * debian/golang-petname.install, Makefile: - update build, install binary, fix name * debian/golang-petname.install, Makefile: - clean up, install in the right place * debian/control, debian/golang-petname.install, Makefile, update.sh => debian/update-wordlists.sh: - install binary into /usr/bin/golang-petname - build depend on petname, update wordlists at build time * adjectives.txt, adverbs.txt, names.txt: - drop txt files, we build depend on petname now * LICENSE: - add license file * README.md: - update readme * cmd/petname/main.go, debian/copyright, README.md: - update readme, add local location of license * debian/golang-petname.install, golang-petname.1: - add a manpage * debian/update-wordlists.sh: - add instruction to sync README.md from upstream * === renamed symlink src/github.com/dustinkirkland/petname => src/github.com/dustinkirkland/golang-petname: - fix symlink * debian/lintian-overrides: - ignore no-stripped, statically linked binary * README.md: - readme updated -- Dustin Kirkland <kirkland@ubuntu.com> Tue, 16 Dec 2014 14:07:44 -0600 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/cmd/�����������������������������������0000755�0610621�0607500�00000000000�13172163423�025752� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/cmd/petname/���������������������������0000755�0610621�0607500�00000000000�13172163423�027403� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/cmd/petname/main.go��������������������0000644�0610621�0607500�00000002232�13172163423�030655� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* petname: binary for generating human-readable, random names for objects (e.g. hostnames, containers, blobs) Copyright 2014 Dustin Kirkland <dustin.kirkland@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "flag" "fmt" "math/rand" "time" "github.com/dustinkirkland/golang-petname" ) var ( words = flag.Int("words", 2, "The number of words in the pet name") separator = flag.String("separator", "-", "The separator between words in the pet name") ) func init() { rand.Seed(time.Now().UTC().UnixNano()) } func main() { flag.Parse() rand.Seed(time.Now().UnixNano()) fmt.Println(petname.Generate(*words, *separator)) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/README.md������������������������������0000644�0610621�0607500�00000006061�13172163423�026471� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# petname ## NAME []() **petname** − a utility to generate "pet names", consisting of a random combination of adverbs, an adjective, and an animal name ## SYNOPSIS []() **petname** \[-w|--words INT\] \[-l|--letters INT\] \[-s|--separator STR\] \[-d|--dir STR\] \[-c|--complexity INT\] \[-u|--ubuntu\] ## OPTIONS []() - -w|--words number of words in the name, default is 2 - -l|--letters maximum number of letters in each word, default is unlimited - -s|--separator string used to separate name words, default is ’-’ - -d|--dir directory containing adverbs.txt, adjectives.txt, names.txt, default is */usr/share/petname/* - -c|--complexity \[0, 1, 2\]; 0 = easy words, 1 = standard words, 2 = complex words, default=1 - -u|--ubuntu generate ubuntu-style names, alliteration of first character of each word ## DESCRIPTION []() This utility will generate "pet names", consisting of a random combination of an adverb, adjective, and an animal name. These are useful for unique hostnames or container names, for instance. As such, PetName tries to follow the tenets of Zooko’s triangle. Names are: - human meaningful - decentralized - secure ## EXAMPLES []() ``` $ petname wiggly-yellowtail $ petname --words 1 robin $ petname --words 3 primly-lasting-toucan $ petname --words 4 angrily-impatiently-sage-longhorn $ petname --separator ":" cool:gobbler $ petname --separator "" --words 3 comparablyheartylionfish $ petname --ubuntu amazed-asp $ petname --complexity 0 massive-colt ``` ## CODE []() Besides this shell utility, there are also native libraries: python-petname, python3-petname, and golang-petname. Here are some programmatic examples in code: **Golang Example** ```golang package main import ( "flag" "fmt" "github.com/dustinkirkland/golang-petname" ) var ( words = flag.Int("words", 2, "The number of words in the pet name") separator = flag.String("separator", "-", "The separator between words in the pet name") ) func main() { flag.Parse() fmt.Println(petname.Generate(\*words, \*separator)) } ``` **Python Example** See: https://pypi.golang.org/pypi/petname ``` $ pip3 install petname $ sudo apt-get install python3-petname ``` ```python #!/usr/bin/python3 import argparse import petname parser = argparse.ArgumentParser(description="Generate human readable random names") parser.add_argument("-w", "--words", help="Number of words in name, default=2", default=2) parser.add_argument("-s", "--separator", help="Separator between words, default='-'", default="-") parser.options = parser.parse_args() print petname.Generate(int(parser.options.words), parser.options.separator) ``` ## AUTHOR []() This manpage and the utility were written by Dustin Kirkland &lt;dustin.kirkland@gmail.com&gt; for Ubuntu systems (but may be used by others). Permission is granted to copy, distribute and/or modify this document and the utility under the terms of the Apache2 License. The complete text of the Apache2 License can be found in */usr/share/common-licenses/Apache-2.0* on Debian/Ubuntu systems. ------------------------------------------------------------------------ �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/dustinkirkland/golang-petname/LICENSE��������������������������������0000644�0610621�0607500�00000026136�13172163423�026224� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163421�021117� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163422�022607� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/���������������������������������������������0000755�0610621�0607500�00000000000�13172163422�024104� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/����������������������������������0000755�0610621�0607500�00000000000�13172163422�026143� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/�������������������������0000755�0610621�0607500�00000000000�13172163422�030001� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/��������������������0000755�0610621�0607500�00000000000�13172163422�030743� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/value.go������������0000644�0610621�0607500�00000000454�13172163422�032411� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx // Value provides methods for extracting interface{} data in various // types. type Value struct { // data contains the raw data being managed by this Value data interface{} } // Data returns the raw data contained by this Value func (v *Value) Data() interface{} { return v.data } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������././@LongLink���������������������������������������������������������������������������������������0000644�0000000�0000000�00000000151�00000000000�011600� L����������������������������������������������������������������������������������������������������ustar �root����������������������������root�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/type_specific_codegen.go������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/type_specific_codege0000644�0610621�0607500�00000216146�13172163422�035034� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx /* Inter (interface{} and []interface{}) -------------------------------------------------- */ // Inter gets the value as a interface{}, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Inter(optionalDefault ...interface{}) interface{} { if s, ok := v.data.(interface{}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInter gets the value as a interface{}. // // Panics if the object is not a interface{}. func (v *Value) MustInter() interface{} { return v.data.(interface{}) } // InterSlice gets the value as a []interface{}, returns the optionalDefault // value or nil if the value is not a []interface{}. func (v *Value) InterSlice(optionalDefault ...[]interface{}) []interface{} { if s, ok := v.data.([]interface{}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInterSlice gets the value as a []interface{}. // // Panics if the object is not a []interface{}. func (v *Value) MustInterSlice() []interface{} { return v.data.([]interface{}) } // IsInter gets whether the object contained is a interface{} or not. func (v *Value) IsInter() bool { _, ok := v.data.(interface{}) return ok } // IsInterSlice gets whether the object contained is a []interface{} or not. func (v *Value) IsInterSlice() bool { _, ok := v.data.([]interface{}) return ok } // EachInter calls the specified callback for each object // in the []interface{}. // // Panics if the object is the wrong type. func (v *Value) EachInter(callback func(int, interface{}) bool) *Value { for index, val := range v.MustInterSlice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereInter uses the specified decider function to select items // from the []interface{}. The object contained in the result will contain // only the selected items. func (v *Value) WhereInter(decider func(int, interface{}) bool) *Value { var selected []interface{} v.EachInter(func(index int, val interface{}) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInter uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]interface{}. func (v *Value) GroupInter(grouper func(int, interface{}) string) *Value { groups := make(map[string][]interface{}) v.EachInter(func(index int, val interface{}) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]interface{}, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInter uses the specified function to replace each interface{}s // by iterating each item. The data in the returned result will be a // []interface{} containing the replaced items. func (v *Value) ReplaceInter(replacer func(int, interface{}) interface{}) *Value { arr := v.MustInterSlice() replaced := make([]interface{}, len(arr)) v.EachInter(func(index int, val interface{}) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInter uses the specified collector function to collect a value // for each of the interface{}s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Value { arr := v.MustInterSlice() collected := make([]interface{}, len(arr)) v.EachInter(func(index int, val interface{}) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* MSI (map[string]interface{} and []map[string]interface{}) -------------------------------------------------- */ // MSI gets the value as a map[string]interface{}, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} { if s, ok := v.data.(map[string]interface{}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustMSI gets the value as a map[string]interface{}. // // Panics if the object is not a map[string]interface{}. func (v *Value) MustMSI() map[string]interface{} { return v.data.(map[string]interface{}) } // MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault // value or nil if the value is not a []map[string]interface{}. func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} { if s, ok := v.data.([]map[string]interface{}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustMSISlice gets the value as a []map[string]interface{}. // // Panics if the object is not a []map[string]interface{}. func (v *Value) MustMSISlice() []map[string]interface{} { return v.data.([]map[string]interface{}) } // IsMSI gets whether the object contained is a map[string]interface{} or not. func (v *Value) IsMSI() bool { _, ok := v.data.(map[string]interface{}) return ok } // IsMSISlice gets whether the object contained is a []map[string]interface{} or not. func (v *Value) IsMSISlice() bool { _, ok := v.data.([]map[string]interface{}) return ok } // EachMSI calls the specified callback for each object // in the []map[string]interface{}. // // Panics if the object is the wrong type. func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value { for index, val := range v.MustMSISlice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereMSI uses the specified decider function to select items // from the []map[string]interface{}. The object contained in the result will contain // only the selected items. func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value { var selected []map[string]interface{} v.EachMSI(func(index int, val map[string]interface{}) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupMSI uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]map[string]interface{}. func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value { groups := make(map[string][]map[string]interface{}) v.EachMSI(func(index int, val map[string]interface{}) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]map[string]interface{}, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceMSI uses the specified function to replace each map[string]interface{}s // by iterating each item. The data in the returned result will be a // []map[string]interface{} containing the replaced items. func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value { arr := v.MustMSISlice() replaced := make([]map[string]interface{}, len(arr)) v.EachMSI(func(index int, val map[string]interface{}) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectMSI uses the specified collector function to collect a value // for each of the map[string]interface{}s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value { arr := v.MustMSISlice() collected := make([]interface{}, len(arr)) v.EachMSI(func(index int, val map[string]interface{}) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* ObjxMap ((Map) and [](Map)) -------------------------------------------------- */ // ObjxMap gets the value as a (Map), returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) ObjxMap(optionalDefault ...(Map)) Map { if s, ok := v.data.((Map)); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return New(nil) } // MustObjxMap gets the value as a (Map). // // Panics if the object is not a (Map). func (v *Value) MustObjxMap() Map { return v.data.((Map)) } // ObjxMapSlice gets the value as a [](Map), returns the optionalDefault // value or nil if the value is not a [](Map). func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { if s, ok := v.data.([](Map)); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustObjxMapSlice gets the value as a [](Map). // // Panics if the object is not a [](Map). func (v *Value) MustObjxMapSlice() [](Map) { return v.data.([](Map)) } // IsObjxMap gets whether the object contained is a (Map) or not. func (v *Value) IsObjxMap() bool { _, ok := v.data.((Map)) return ok } // IsObjxMapSlice gets whether the object contained is a [](Map) or not. func (v *Value) IsObjxMapSlice() bool { _, ok := v.data.([](Map)) return ok } // EachObjxMap calls the specified callback for each object // in the [](Map). // // Panics if the object is the wrong type. func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value { for index, val := range v.MustObjxMapSlice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereObjxMap uses the specified decider function to select items // from the [](Map). The object contained in the result will contain // only the selected items. func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value { var selected [](Map) v.EachObjxMap(func(index int, val Map) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupObjxMap uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][](Map). func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value { groups := make(map[string][](Map)) v.EachObjxMap(func(index int, val Map) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([](Map), 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceObjxMap uses the specified function to replace each (Map)s // by iterating each item. The data in the returned result will be a // [](Map) containing the replaced items. func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value { arr := v.MustObjxMapSlice() replaced := make([](Map), len(arr)) v.EachObjxMap(func(index int, val Map) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectObjxMap uses the specified collector function to collect a value // for each of the (Map)s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value { arr := v.MustObjxMapSlice() collected := make([]interface{}, len(arr)) v.EachObjxMap(func(index int, val Map) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Bool (bool and []bool) -------------------------------------------------- */ // Bool gets the value as a bool, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Bool(optionalDefault ...bool) bool { if s, ok := v.data.(bool); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return false } // MustBool gets the value as a bool. // // Panics if the object is not a bool. func (v *Value) MustBool() bool { return v.data.(bool) } // BoolSlice gets the value as a []bool, returns the optionalDefault // value or nil if the value is not a []bool. func (v *Value) BoolSlice(optionalDefault ...[]bool) []bool { if s, ok := v.data.([]bool); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustBoolSlice gets the value as a []bool. // // Panics if the object is not a []bool. func (v *Value) MustBoolSlice() []bool { return v.data.([]bool) } // IsBool gets whether the object contained is a bool or not. func (v *Value) IsBool() bool { _, ok := v.data.(bool) return ok } // IsBoolSlice gets whether the object contained is a []bool or not. func (v *Value) IsBoolSlice() bool { _, ok := v.data.([]bool) return ok } // EachBool calls the specified callback for each object // in the []bool. // // Panics if the object is the wrong type. func (v *Value) EachBool(callback func(int, bool) bool) *Value { for index, val := range v.MustBoolSlice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereBool uses the specified decider function to select items // from the []bool. The object contained in the result will contain // only the selected items. func (v *Value) WhereBool(decider func(int, bool) bool) *Value { var selected []bool v.EachBool(func(index int, val bool) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupBool uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]bool. func (v *Value) GroupBool(grouper func(int, bool) string) *Value { groups := make(map[string][]bool) v.EachBool(func(index int, val bool) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]bool, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceBool uses the specified function to replace each bools // by iterating each item. The data in the returned result will be a // []bool containing the replaced items. func (v *Value) ReplaceBool(replacer func(int, bool) bool) *Value { arr := v.MustBoolSlice() replaced := make([]bool, len(arr)) v.EachBool(func(index int, val bool) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectBool uses the specified collector function to collect a value // for each of the bools in the slice. The data returned will be a // []interface{}. func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value { arr := v.MustBoolSlice() collected := make([]interface{}, len(arr)) v.EachBool(func(index int, val bool) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Str (string and []string) -------------------------------------------------- */ // Str gets the value as a string, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Str(optionalDefault ...string) string { if s, ok := v.data.(string); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return "" } // MustStr gets the value as a string. // // Panics if the object is not a string. func (v *Value) MustStr() string { return v.data.(string) } // StrSlice gets the value as a []string, returns the optionalDefault // value or nil if the value is not a []string. func (v *Value) StrSlice(optionalDefault ...[]string) []string { if s, ok := v.data.([]string); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustStrSlice gets the value as a []string. // // Panics if the object is not a []string. func (v *Value) MustStrSlice() []string { return v.data.([]string) } // IsStr gets whether the object contained is a string or not. func (v *Value) IsStr() bool { _, ok := v.data.(string) return ok } // IsStrSlice gets whether the object contained is a []string or not. func (v *Value) IsStrSlice() bool { _, ok := v.data.([]string) return ok } // EachStr calls the specified callback for each object // in the []string. // // Panics if the object is the wrong type. func (v *Value) EachStr(callback func(int, string) bool) *Value { for index, val := range v.MustStrSlice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereStr uses the specified decider function to select items // from the []string. The object contained in the result will contain // only the selected items. func (v *Value) WhereStr(decider func(int, string) bool) *Value { var selected []string v.EachStr(func(index int, val string) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupStr uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]string. func (v *Value) GroupStr(grouper func(int, string) string) *Value { groups := make(map[string][]string) v.EachStr(func(index int, val string) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]string, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceStr uses the specified function to replace each strings // by iterating each item. The data in the returned result will be a // []string containing the replaced items. func (v *Value) ReplaceStr(replacer func(int, string) string) *Value { arr := v.MustStrSlice() replaced := make([]string, len(arr)) v.EachStr(func(index int, val string) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectStr uses the specified collector function to collect a value // for each of the strings in the slice. The data returned will be a // []interface{}. func (v *Value) CollectStr(collector func(int, string) interface{}) *Value { arr := v.MustStrSlice() collected := make([]interface{}, len(arr)) v.EachStr(func(index int, val string) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int (int and []int) -------------------------------------------------- */ // Int gets the value as a int, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int(optionalDefault ...int) int { if s, ok := v.data.(int); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt gets the value as a int. // // Panics if the object is not a int. func (v *Value) MustInt() int { return v.data.(int) } // IntSlice gets the value as a []int, returns the optionalDefault // value or nil if the value is not a []int. func (v *Value) IntSlice(optionalDefault ...[]int) []int { if s, ok := v.data.([]int); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustIntSlice gets the value as a []int. // // Panics if the object is not a []int. func (v *Value) MustIntSlice() []int { return v.data.([]int) } // IsInt gets whether the object contained is a int or not. func (v *Value) IsInt() bool { _, ok := v.data.(int) return ok } // IsIntSlice gets whether the object contained is a []int or not. func (v *Value) IsIntSlice() bool { _, ok := v.data.([]int) return ok } // EachInt calls the specified callback for each object // in the []int. // // Panics if the object is the wrong type. func (v *Value) EachInt(callback func(int, int) bool) *Value { for index, val := range v.MustIntSlice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereInt uses the specified decider function to select items // from the []int. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt(decider func(int, int) bool) *Value { var selected []int v.EachInt(func(index int, val int) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int. func (v *Value) GroupInt(grouper func(int, int) string) *Value { groups := make(map[string][]int) v.EachInt(func(index int, val int) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt uses the specified function to replace each ints // by iterating each item. The data in the returned result will be a // []int containing the replaced items. func (v *Value) ReplaceInt(replacer func(int, int) int) *Value { arr := v.MustIntSlice() replaced := make([]int, len(arr)) v.EachInt(func(index int, val int) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt uses the specified collector function to collect a value // for each of the ints in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt(collector func(int, int) interface{}) *Value { arr := v.MustIntSlice() collected := make([]interface{}, len(arr)) v.EachInt(func(index int, val int) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int8 (int8 and []int8) -------------------------------------------------- */ // Int8 gets the value as a int8, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int8(optionalDefault ...int8) int8 { if s, ok := v.data.(int8); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt8 gets the value as a int8. // // Panics if the object is not a int8. func (v *Value) MustInt8() int8 { return v.data.(int8) } // Int8Slice gets the value as a []int8, returns the optionalDefault // value or nil if the value is not a []int8. func (v *Value) Int8Slice(optionalDefault ...[]int8) []int8 { if s, ok := v.data.([]int8); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInt8Slice gets the value as a []int8. // // Panics if the object is not a []int8. func (v *Value) MustInt8Slice() []int8 { return v.data.([]int8) } // IsInt8 gets whether the object contained is a int8 or not. func (v *Value) IsInt8() bool { _, ok := v.data.(int8) return ok } // IsInt8Slice gets whether the object contained is a []int8 or not. func (v *Value) IsInt8Slice() bool { _, ok := v.data.([]int8) return ok } // EachInt8 calls the specified callback for each object // in the []int8. // // Panics if the object is the wrong type. func (v *Value) EachInt8(callback func(int, int8) bool) *Value { for index, val := range v.MustInt8Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereInt8 uses the specified decider function to select items // from the []int8. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt8(decider func(int, int8) bool) *Value { var selected []int8 v.EachInt8(func(index int, val int8) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt8 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int8. func (v *Value) GroupInt8(grouper func(int, int8) string) *Value { groups := make(map[string][]int8) v.EachInt8(func(index int, val int8) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int8, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt8 uses the specified function to replace each int8s // by iterating each item. The data in the returned result will be a // []int8 containing the replaced items. func (v *Value) ReplaceInt8(replacer func(int, int8) int8) *Value { arr := v.MustInt8Slice() replaced := make([]int8, len(arr)) v.EachInt8(func(index int, val int8) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt8 uses the specified collector function to collect a value // for each of the int8s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value { arr := v.MustInt8Slice() collected := make([]interface{}, len(arr)) v.EachInt8(func(index int, val int8) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int16 (int16 and []int16) -------------------------------------------------- */ // Int16 gets the value as a int16, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int16(optionalDefault ...int16) int16 { if s, ok := v.data.(int16); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt16 gets the value as a int16. // // Panics if the object is not a int16. func (v *Value) MustInt16() int16 { return v.data.(int16) } // Int16Slice gets the value as a []int16, returns the optionalDefault // value or nil if the value is not a []int16. func (v *Value) Int16Slice(optionalDefault ...[]int16) []int16 { if s, ok := v.data.([]int16); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInt16Slice gets the value as a []int16. // // Panics if the object is not a []int16. func (v *Value) MustInt16Slice() []int16 { return v.data.([]int16) } // IsInt16 gets whether the object contained is a int16 or not. func (v *Value) IsInt16() bool { _, ok := v.data.(int16) return ok } // IsInt16Slice gets whether the object contained is a []int16 or not. func (v *Value) IsInt16Slice() bool { _, ok := v.data.([]int16) return ok } // EachInt16 calls the specified callback for each object // in the []int16. // // Panics if the object is the wrong type. func (v *Value) EachInt16(callback func(int, int16) bool) *Value { for index, val := range v.MustInt16Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereInt16 uses the specified decider function to select items // from the []int16. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt16(decider func(int, int16) bool) *Value { var selected []int16 v.EachInt16(func(index int, val int16) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt16 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int16. func (v *Value) GroupInt16(grouper func(int, int16) string) *Value { groups := make(map[string][]int16) v.EachInt16(func(index int, val int16) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int16, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt16 uses the specified function to replace each int16s // by iterating each item. The data in the returned result will be a // []int16 containing the replaced items. func (v *Value) ReplaceInt16(replacer func(int, int16) int16) *Value { arr := v.MustInt16Slice() replaced := make([]int16, len(arr)) v.EachInt16(func(index int, val int16) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt16 uses the specified collector function to collect a value // for each of the int16s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value { arr := v.MustInt16Slice() collected := make([]interface{}, len(arr)) v.EachInt16(func(index int, val int16) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int32 (int32 and []int32) -------------------------------------------------- */ // Int32 gets the value as a int32, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int32(optionalDefault ...int32) int32 { if s, ok := v.data.(int32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt32 gets the value as a int32. // // Panics if the object is not a int32. func (v *Value) MustInt32() int32 { return v.data.(int32) } // Int32Slice gets the value as a []int32, returns the optionalDefault // value or nil if the value is not a []int32. func (v *Value) Int32Slice(optionalDefault ...[]int32) []int32 { if s, ok := v.data.([]int32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInt32Slice gets the value as a []int32. // // Panics if the object is not a []int32. func (v *Value) MustInt32Slice() []int32 { return v.data.([]int32) } // IsInt32 gets whether the object contained is a int32 or not. func (v *Value) IsInt32() bool { _, ok := v.data.(int32) return ok } // IsInt32Slice gets whether the object contained is a []int32 or not. func (v *Value) IsInt32Slice() bool { _, ok := v.data.([]int32) return ok } // EachInt32 calls the specified callback for each object // in the []int32. // // Panics if the object is the wrong type. func (v *Value) EachInt32(callback func(int, int32) bool) *Value { for index, val := range v.MustInt32Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereInt32 uses the specified decider function to select items // from the []int32. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt32(decider func(int, int32) bool) *Value { var selected []int32 v.EachInt32(func(index int, val int32) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt32 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int32. func (v *Value) GroupInt32(grouper func(int, int32) string) *Value { groups := make(map[string][]int32) v.EachInt32(func(index int, val int32) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int32, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt32 uses the specified function to replace each int32s // by iterating each item. The data in the returned result will be a // []int32 containing the replaced items. func (v *Value) ReplaceInt32(replacer func(int, int32) int32) *Value { arr := v.MustInt32Slice() replaced := make([]int32, len(arr)) v.EachInt32(func(index int, val int32) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt32 uses the specified collector function to collect a value // for each of the int32s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value { arr := v.MustInt32Slice() collected := make([]interface{}, len(arr)) v.EachInt32(func(index int, val int32) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int64 (int64 and []int64) -------------------------------------------------- */ // Int64 gets the value as a int64, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int64(optionalDefault ...int64) int64 { if s, ok := v.data.(int64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt64 gets the value as a int64. // // Panics if the object is not a int64. func (v *Value) MustInt64() int64 { return v.data.(int64) } // Int64Slice gets the value as a []int64, returns the optionalDefault // value or nil if the value is not a []int64. func (v *Value) Int64Slice(optionalDefault ...[]int64) []int64 { if s, ok := v.data.([]int64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInt64Slice gets the value as a []int64. // // Panics if the object is not a []int64. func (v *Value) MustInt64Slice() []int64 { return v.data.([]int64) } // IsInt64 gets whether the object contained is a int64 or not. func (v *Value) IsInt64() bool { _, ok := v.data.(int64) return ok } // IsInt64Slice gets whether the object contained is a []int64 or not. func (v *Value) IsInt64Slice() bool { _, ok := v.data.([]int64) return ok } // EachInt64 calls the specified callback for each object // in the []int64. // // Panics if the object is the wrong type. func (v *Value) EachInt64(callback func(int, int64) bool) *Value { for index, val := range v.MustInt64Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereInt64 uses the specified decider function to select items // from the []int64. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt64(decider func(int, int64) bool) *Value { var selected []int64 v.EachInt64(func(index int, val int64) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt64 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int64. func (v *Value) GroupInt64(grouper func(int, int64) string) *Value { groups := make(map[string][]int64) v.EachInt64(func(index int, val int64) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int64, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt64 uses the specified function to replace each int64s // by iterating each item. The data in the returned result will be a // []int64 containing the replaced items. func (v *Value) ReplaceInt64(replacer func(int, int64) int64) *Value { arr := v.MustInt64Slice() replaced := make([]int64, len(arr)) v.EachInt64(func(index int, val int64) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt64 uses the specified collector function to collect a value // for each of the int64s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value { arr := v.MustInt64Slice() collected := make([]interface{}, len(arr)) v.EachInt64(func(index int, val int64) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint (uint and []uint) -------------------------------------------------- */ // Uint gets the value as a uint, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint(optionalDefault ...uint) uint { if s, ok := v.data.(uint); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint gets the value as a uint. // // Panics if the object is not a uint. func (v *Value) MustUint() uint { return v.data.(uint) } // UintSlice gets the value as a []uint, returns the optionalDefault // value or nil if the value is not a []uint. func (v *Value) UintSlice(optionalDefault ...[]uint) []uint { if s, ok := v.data.([]uint); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUintSlice gets the value as a []uint. // // Panics if the object is not a []uint. func (v *Value) MustUintSlice() []uint { return v.data.([]uint) } // IsUint gets whether the object contained is a uint or not. func (v *Value) IsUint() bool { _, ok := v.data.(uint) return ok } // IsUintSlice gets whether the object contained is a []uint or not. func (v *Value) IsUintSlice() bool { _, ok := v.data.([]uint) return ok } // EachUint calls the specified callback for each object // in the []uint. // // Panics if the object is the wrong type. func (v *Value) EachUint(callback func(int, uint) bool) *Value { for index, val := range v.MustUintSlice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereUint uses the specified decider function to select items // from the []uint. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint(decider func(int, uint) bool) *Value { var selected []uint v.EachUint(func(index int, val uint) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint. func (v *Value) GroupUint(grouper func(int, uint) string) *Value { groups := make(map[string][]uint) v.EachUint(func(index int, val uint) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint uses the specified function to replace each uints // by iterating each item. The data in the returned result will be a // []uint containing the replaced items. func (v *Value) ReplaceUint(replacer func(int, uint) uint) *Value { arr := v.MustUintSlice() replaced := make([]uint, len(arr)) v.EachUint(func(index int, val uint) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint uses the specified collector function to collect a value // for each of the uints in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value { arr := v.MustUintSlice() collected := make([]interface{}, len(arr)) v.EachUint(func(index int, val uint) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint8 (uint8 and []uint8) -------------------------------------------------- */ // Uint8 gets the value as a uint8, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint8(optionalDefault ...uint8) uint8 { if s, ok := v.data.(uint8); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint8 gets the value as a uint8. // // Panics if the object is not a uint8. func (v *Value) MustUint8() uint8 { return v.data.(uint8) } // Uint8Slice gets the value as a []uint8, returns the optionalDefault // value or nil if the value is not a []uint8. func (v *Value) Uint8Slice(optionalDefault ...[]uint8) []uint8 { if s, ok := v.data.([]uint8); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUint8Slice gets the value as a []uint8. // // Panics if the object is not a []uint8. func (v *Value) MustUint8Slice() []uint8 { return v.data.([]uint8) } // IsUint8 gets whether the object contained is a uint8 or not. func (v *Value) IsUint8() bool { _, ok := v.data.(uint8) return ok } // IsUint8Slice gets whether the object contained is a []uint8 or not. func (v *Value) IsUint8Slice() bool { _, ok := v.data.([]uint8) return ok } // EachUint8 calls the specified callback for each object // in the []uint8. // // Panics if the object is the wrong type. func (v *Value) EachUint8(callback func(int, uint8) bool) *Value { for index, val := range v.MustUint8Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereUint8 uses the specified decider function to select items // from the []uint8. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint8(decider func(int, uint8) bool) *Value { var selected []uint8 v.EachUint8(func(index int, val uint8) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint8 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint8. func (v *Value) GroupUint8(grouper func(int, uint8) string) *Value { groups := make(map[string][]uint8) v.EachUint8(func(index int, val uint8) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint8, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint8 uses the specified function to replace each uint8s // by iterating each item. The data in the returned result will be a // []uint8 containing the replaced items. func (v *Value) ReplaceUint8(replacer func(int, uint8) uint8) *Value { arr := v.MustUint8Slice() replaced := make([]uint8, len(arr)) v.EachUint8(func(index int, val uint8) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint8 uses the specified collector function to collect a value // for each of the uint8s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value { arr := v.MustUint8Slice() collected := make([]interface{}, len(arr)) v.EachUint8(func(index int, val uint8) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint16 (uint16 and []uint16) -------------------------------------------------- */ // Uint16 gets the value as a uint16, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint16(optionalDefault ...uint16) uint16 { if s, ok := v.data.(uint16); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint16 gets the value as a uint16. // // Panics if the object is not a uint16. func (v *Value) MustUint16() uint16 { return v.data.(uint16) } // Uint16Slice gets the value as a []uint16, returns the optionalDefault // value or nil if the value is not a []uint16. func (v *Value) Uint16Slice(optionalDefault ...[]uint16) []uint16 { if s, ok := v.data.([]uint16); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUint16Slice gets the value as a []uint16. // // Panics if the object is not a []uint16. func (v *Value) MustUint16Slice() []uint16 { return v.data.([]uint16) } // IsUint16 gets whether the object contained is a uint16 or not. func (v *Value) IsUint16() bool { _, ok := v.data.(uint16) return ok } // IsUint16Slice gets whether the object contained is a []uint16 or not. func (v *Value) IsUint16Slice() bool { _, ok := v.data.([]uint16) return ok } // EachUint16 calls the specified callback for each object // in the []uint16. // // Panics if the object is the wrong type. func (v *Value) EachUint16(callback func(int, uint16) bool) *Value { for index, val := range v.MustUint16Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereUint16 uses the specified decider function to select items // from the []uint16. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint16(decider func(int, uint16) bool) *Value { var selected []uint16 v.EachUint16(func(index int, val uint16) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint16 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint16. func (v *Value) GroupUint16(grouper func(int, uint16) string) *Value { groups := make(map[string][]uint16) v.EachUint16(func(index int, val uint16) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint16, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint16 uses the specified function to replace each uint16s // by iterating each item. The data in the returned result will be a // []uint16 containing the replaced items. func (v *Value) ReplaceUint16(replacer func(int, uint16) uint16) *Value { arr := v.MustUint16Slice() replaced := make([]uint16, len(arr)) v.EachUint16(func(index int, val uint16) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint16 uses the specified collector function to collect a value // for each of the uint16s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value { arr := v.MustUint16Slice() collected := make([]interface{}, len(arr)) v.EachUint16(func(index int, val uint16) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint32 (uint32 and []uint32) -------------------------------------------------- */ // Uint32 gets the value as a uint32, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint32(optionalDefault ...uint32) uint32 { if s, ok := v.data.(uint32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint32 gets the value as a uint32. // // Panics if the object is not a uint32. func (v *Value) MustUint32() uint32 { return v.data.(uint32) } // Uint32Slice gets the value as a []uint32, returns the optionalDefault // value or nil if the value is not a []uint32. func (v *Value) Uint32Slice(optionalDefault ...[]uint32) []uint32 { if s, ok := v.data.([]uint32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUint32Slice gets the value as a []uint32. // // Panics if the object is not a []uint32. func (v *Value) MustUint32Slice() []uint32 { return v.data.([]uint32) } // IsUint32 gets whether the object contained is a uint32 or not. func (v *Value) IsUint32() bool { _, ok := v.data.(uint32) return ok } // IsUint32Slice gets whether the object contained is a []uint32 or not. func (v *Value) IsUint32Slice() bool { _, ok := v.data.([]uint32) return ok } // EachUint32 calls the specified callback for each object // in the []uint32. // // Panics if the object is the wrong type. func (v *Value) EachUint32(callback func(int, uint32) bool) *Value { for index, val := range v.MustUint32Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereUint32 uses the specified decider function to select items // from the []uint32. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint32(decider func(int, uint32) bool) *Value { var selected []uint32 v.EachUint32(func(index int, val uint32) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint32 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint32. func (v *Value) GroupUint32(grouper func(int, uint32) string) *Value { groups := make(map[string][]uint32) v.EachUint32(func(index int, val uint32) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint32, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint32 uses the specified function to replace each uint32s // by iterating each item. The data in the returned result will be a // []uint32 containing the replaced items. func (v *Value) ReplaceUint32(replacer func(int, uint32) uint32) *Value { arr := v.MustUint32Slice() replaced := make([]uint32, len(arr)) v.EachUint32(func(index int, val uint32) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint32 uses the specified collector function to collect a value // for each of the uint32s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value { arr := v.MustUint32Slice() collected := make([]interface{}, len(arr)) v.EachUint32(func(index int, val uint32) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint64 (uint64 and []uint64) -------------------------------------------------- */ // Uint64 gets the value as a uint64, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint64(optionalDefault ...uint64) uint64 { if s, ok := v.data.(uint64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint64 gets the value as a uint64. // // Panics if the object is not a uint64. func (v *Value) MustUint64() uint64 { return v.data.(uint64) } // Uint64Slice gets the value as a []uint64, returns the optionalDefault // value or nil if the value is not a []uint64. func (v *Value) Uint64Slice(optionalDefault ...[]uint64) []uint64 { if s, ok := v.data.([]uint64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUint64Slice gets the value as a []uint64. // // Panics if the object is not a []uint64. func (v *Value) MustUint64Slice() []uint64 { return v.data.([]uint64) } // IsUint64 gets whether the object contained is a uint64 or not. func (v *Value) IsUint64() bool { _, ok := v.data.(uint64) return ok } // IsUint64Slice gets whether the object contained is a []uint64 or not. func (v *Value) IsUint64Slice() bool { _, ok := v.data.([]uint64) return ok } // EachUint64 calls the specified callback for each object // in the []uint64. // // Panics if the object is the wrong type. func (v *Value) EachUint64(callback func(int, uint64) bool) *Value { for index, val := range v.MustUint64Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereUint64 uses the specified decider function to select items // from the []uint64. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint64(decider func(int, uint64) bool) *Value { var selected []uint64 v.EachUint64(func(index int, val uint64) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint64 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint64. func (v *Value) GroupUint64(grouper func(int, uint64) string) *Value { groups := make(map[string][]uint64) v.EachUint64(func(index int, val uint64) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint64, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint64 uses the specified function to replace each uint64s // by iterating each item. The data in the returned result will be a // []uint64 containing the replaced items. func (v *Value) ReplaceUint64(replacer func(int, uint64) uint64) *Value { arr := v.MustUint64Slice() replaced := make([]uint64, len(arr)) v.EachUint64(func(index int, val uint64) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint64 uses the specified collector function to collect a value // for each of the uint64s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value { arr := v.MustUint64Slice() collected := make([]interface{}, len(arr)) v.EachUint64(func(index int, val uint64) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uintptr (uintptr and []uintptr) -------------------------------------------------- */ // Uintptr gets the value as a uintptr, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uintptr(optionalDefault ...uintptr) uintptr { if s, ok := v.data.(uintptr); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUintptr gets the value as a uintptr. // // Panics if the object is not a uintptr. func (v *Value) MustUintptr() uintptr { return v.data.(uintptr) } // UintptrSlice gets the value as a []uintptr, returns the optionalDefault // value or nil if the value is not a []uintptr. func (v *Value) UintptrSlice(optionalDefault ...[]uintptr) []uintptr { if s, ok := v.data.([]uintptr); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUintptrSlice gets the value as a []uintptr. // // Panics if the object is not a []uintptr. func (v *Value) MustUintptrSlice() []uintptr { return v.data.([]uintptr) } // IsUintptr gets whether the object contained is a uintptr or not. func (v *Value) IsUintptr() bool { _, ok := v.data.(uintptr) return ok } // IsUintptrSlice gets whether the object contained is a []uintptr or not. func (v *Value) IsUintptrSlice() bool { _, ok := v.data.([]uintptr) return ok } // EachUintptr calls the specified callback for each object // in the []uintptr. // // Panics if the object is the wrong type. func (v *Value) EachUintptr(callback func(int, uintptr) bool) *Value { for index, val := range v.MustUintptrSlice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereUintptr uses the specified decider function to select items // from the []uintptr. The object contained in the result will contain // only the selected items. func (v *Value) WhereUintptr(decider func(int, uintptr) bool) *Value { var selected []uintptr v.EachUintptr(func(index int, val uintptr) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUintptr uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uintptr. func (v *Value) GroupUintptr(grouper func(int, uintptr) string) *Value { groups := make(map[string][]uintptr) v.EachUintptr(func(index int, val uintptr) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uintptr, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUintptr uses the specified function to replace each uintptrs // by iterating each item. The data in the returned result will be a // []uintptr containing the replaced items. func (v *Value) ReplaceUintptr(replacer func(int, uintptr) uintptr) *Value { arr := v.MustUintptrSlice() replaced := make([]uintptr, len(arr)) v.EachUintptr(func(index int, val uintptr) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUintptr uses the specified collector function to collect a value // for each of the uintptrs in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value { arr := v.MustUintptrSlice() collected := make([]interface{}, len(arr)) v.EachUintptr(func(index int, val uintptr) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Float32 (float32 and []float32) -------------------------------------------------- */ // Float32 gets the value as a float32, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Float32(optionalDefault ...float32) float32 { if s, ok := v.data.(float32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustFloat32 gets the value as a float32. // // Panics if the object is not a float32. func (v *Value) MustFloat32() float32 { return v.data.(float32) } // Float32Slice gets the value as a []float32, returns the optionalDefault // value or nil if the value is not a []float32. func (v *Value) Float32Slice(optionalDefault ...[]float32) []float32 { if s, ok := v.data.([]float32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustFloat32Slice gets the value as a []float32. // // Panics if the object is not a []float32. func (v *Value) MustFloat32Slice() []float32 { return v.data.([]float32) } // IsFloat32 gets whether the object contained is a float32 or not. func (v *Value) IsFloat32() bool { _, ok := v.data.(float32) return ok } // IsFloat32Slice gets whether the object contained is a []float32 or not. func (v *Value) IsFloat32Slice() bool { _, ok := v.data.([]float32) return ok } // EachFloat32 calls the specified callback for each object // in the []float32. // // Panics if the object is the wrong type. func (v *Value) EachFloat32(callback func(int, float32) bool) *Value { for index, val := range v.MustFloat32Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereFloat32 uses the specified decider function to select items // from the []float32. The object contained in the result will contain // only the selected items. func (v *Value) WhereFloat32(decider func(int, float32) bool) *Value { var selected []float32 v.EachFloat32(func(index int, val float32) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupFloat32 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]float32. func (v *Value) GroupFloat32(grouper func(int, float32) string) *Value { groups := make(map[string][]float32) v.EachFloat32(func(index int, val float32) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]float32, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceFloat32 uses the specified function to replace each float32s // by iterating each item. The data in the returned result will be a // []float32 containing the replaced items. func (v *Value) ReplaceFloat32(replacer func(int, float32) float32) *Value { arr := v.MustFloat32Slice() replaced := make([]float32, len(arr)) v.EachFloat32(func(index int, val float32) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectFloat32 uses the specified collector function to collect a value // for each of the float32s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value { arr := v.MustFloat32Slice() collected := make([]interface{}, len(arr)) v.EachFloat32(func(index int, val float32) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Float64 (float64 and []float64) -------------------------------------------------- */ // Float64 gets the value as a float64, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Float64(optionalDefault ...float64) float64 { if s, ok := v.data.(float64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustFloat64 gets the value as a float64. // // Panics if the object is not a float64. func (v *Value) MustFloat64() float64 { return v.data.(float64) } // Float64Slice gets the value as a []float64, returns the optionalDefault // value or nil if the value is not a []float64. func (v *Value) Float64Slice(optionalDefault ...[]float64) []float64 { if s, ok := v.data.([]float64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustFloat64Slice gets the value as a []float64. // // Panics if the object is not a []float64. func (v *Value) MustFloat64Slice() []float64 { return v.data.([]float64) } // IsFloat64 gets whether the object contained is a float64 or not. func (v *Value) IsFloat64() bool { _, ok := v.data.(float64) return ok } // IsFloat64Slice gets whether the object contained is a []float64 or not. func (v *Value) IsFloat64Slice() bool { _, ok := v.data.([]float64) return ok } // EachFloat64 calls the specified callback for each object // in the []float64. // // Panics if the object is the wrong type. func (v *Value) EachFloat64(callback func(int, float64) bool) *Value { for index, val := range v.MustFloat64Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereFloat64 uses the specified decider function to select items // from the []float64. The object contained in the result will contain // only the selected items. func (v *Value) WhereFloat64(decider func(int, float64) bool) *Value { var selected []float64 v.EachFloat64(func(index int, val float64) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupFloat64 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]float64. func (v *Value) GroupFloat64(grouper func(int, float64) string) *Value { groups := make(map[string][]float64) v.EachFloat64(func(index int, val float64) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]float64, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceFloat64 uses the specified function to replace each float64s // by iterating each item. The data in the returned result will be a // []float64 containing the replaced items. func (v *Value) ReplaceFloat64(replacer func(int, float64) float64) *Value { arr := v.MustFloat64Slice() replaced := make([]float64, len(arr)) v.EachFloat64(func(index int, val float64) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectFloat64 uses the specified collector function to collect a value // for each of the float64s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value { arr := v.MustFloat64Slice() collected := make([]interface{}, len(arr)) v.EachFloat64(func(index int, val float64) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Complex64 (complex64 and []complex64) -------------------------------------------------- */ // Complex64 gets the value as a complex64, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Complex64(optionalDefault ...complex64) complex64 { if s, ok := v.data.(complex64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustComplex64 gets the value as a complex64. // // Panics if the object is not a complex64. func (v *Value) MustComplex64() complex64 { return v.data.(complex64) } // Complex64Slice gets the value as a []complex64, returns the optionalDefault // value or nil if the value is not a []complex64. func (v *Value) Complex64Slice(optionalDefault ...[]complex64) []complex64 { if s, ok := v.data.([]complex64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustComplex64Slice gets the value as a []complex64. // // Panics if the object is not a []complex64. func (v *Value) MustComplex64Slice() []complex64 { return v.data.([]complex64) } // IsComplex64 gets whether the object contained is a complex64 or not. func (v *Value) IsComplex64() bool { _, ok := v.data.(complex64) return ok } // IsComplex64Slice gets whether the object contained is a []complex64 or not. func (v *Value) IsComplex64Slice() bool { _, ok := v.data.([]complex64) return ok } // EachComplex64 calls the specified callback for each object // in the []complex64. // // Panics if the object is the wrong type. func (v *Value) EachComplex64(callback func(int, complex64) bool) *Value { for index, val := range v.MustComplex64Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereComplex64 uses the specified decider function to select items // from the []complex64. The object contained in the result will contain // only the selected items. func (v *Value) WhereComplex64(decider func(int, complex64) bool) *Value { var selected []complex64 v.EachComplex64(func(index int, val complex64) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupComplex64 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]complex64. func (v *Value) GroupComplex64(grouper func(int, complex64) string) *Value { groups := make(map[string][]complex64) v.EachComplex64(func(index int, val complex64) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]complex64, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceComplex64 uses the specified function to replace each complex64s // by iterating each item. The data in the returned result will be a // []complex64 containing the replaced items. func (v *Value) ReplaceComplex64(replacer func(int, complex64) complex64) *Value { arr := v.MustComplex64Slice() replaced := make([]complex64, len(arr)) v.EachComplex64(func(index int, val complex64) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectComplex64 uses the specified collector function to collect a value // for each of the complex64s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Value { arr := v.MustComplex64Slice() collected := make([]interface{}, len(arr)) v.EachComplex64(func(index int, val complex64) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Complex128 (complex128 and []complex128) -------------------------------------------------- */ // Complex128 gets the value as a complex128, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Complex128(optionalDefault ...complex128) complex128 { if s, ok := v.data.(complex128); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustComplex128 gets the value as a complex128. // // Panics if the object is not a complex128. func (v *Value) MustComplex128() complex128 { return v.data.(complex128) } // Complex128Slice gets the value as a []complex128, returns the optionalDefault // value or nil if the value is not a []complex128. func (v *Value) Complex128Slice(optionalDefault ...[]complex128) []complex128 { if s, ok := v.data.([]complex128); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustComplex128Slice gets the value as a []complex128. // // Panics if the object is not a []complex128. func (v *Value) MustComplex128Slice() []complex128 { return v.data.([]complex128) } // IsComplex128 gets whether the object contained is a complex128 or not. func (v *Value) IsComplex128() bool { _, ok := v.data.(complex128) return ok } // IsComplex128Slice gets whether the object contained is a []complex128 or not. func (v *Value) IsComplex128Slice() bool { _, ok := v.data.([]complex128) return ok } // EachComplex128 calls the specified callback for each object // in the []complex128. // // Panics if the object is the wrong type. func (v *Value) EachComplex128(callback func(int, complex128) bool) *Value { for index, val := range v.MustComplex128Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // WhereComplex128 uses the specified decider function to select items // from the []complex128. The object contained in the result will contain // only the selected items. func (v *Value) WhereComplex128(decider func(int, complex128) bool) *Value { var selected []complex128 v.EachComplex128(func(index int, val complex128) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupComplex128 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]complex128. func (v *Value) GroupComplex128(grouper func(int, complex128) string) *Value { groups := make(map[string][]complex128) v.EachComplex128(func(index int, val complex128) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]complex128, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceComplex128 uses the specified function to replace each complex128s // by iterating each item. The data in the returned result will be a // []complex128 containing the replaced items. func (v *Value) ReplaceComplex128(replacer func(int, complex128) complex128) *Value { arr := v.MustComplex128Slice() replaced := make([]complex128, len(arr)) v.EachComplex128(func(index int, val complex128) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectComplex128 uses the specified collector function to collect a value // for each of the complex128s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectComplex128(collector func(int, complex128) interface{}) *Value { arr := v.MustComplex128Slice() collected := make([]interface{}, len(arr)) v.EachComplex128(func(index int, val complex128) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/tests.go������������0000644�0610621�0607500�00000000552�13172163422�032436� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx // Has gets whether there is something at the specified selector // or not. // // If m is nil, Has will always return false. func (m Map) Has(selector string) bool { if m == nil { return false } return !m.Get(selector).IsNil() } // IsNil gets whether the data is nil or not. func (v *Value) IsNil() bool { return v == nil || v.data == nil } ������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/security.go���������0000644�0610621�0607500�00000000421�13172163422�033136� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx import ( "crypto/sha1" "encoding/hex" ) // HashWithKey hashes the specified string using the security // key. func HashWithKey(data, key string) string { hash := sha1.New() hash.Write([]byte(data + ":" + key)) return hex.EncodeToString(hash.Sum(nil)) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/mutations.go��������0000644�0610621�0607500�00000004073�13172163422�033321� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx // Exclude returns a new Map with the keys in the specified []string // excluded. func (d Map) Exclude(exclude []string) Map { excluded := make(Map) for k, v := range d { var shouldInclude bool = true for _, toExclude := range exclude { if k == toExclude { shouldInclude = false break } } if shouldInclude { excluded[k] = v } } return excluded } // Copy creates a shallow copy of the Obj. func (m Map) Copy() Map { copied := make(map[string]interface{}) for k, v := range m { copied[k] = v } return New(copied) } // Merge blends the specified map with a copy of this map and returns the result. // // Keys that appear in both will be selected from the specified map. // This method requires that the wrapped object be a map[string]interface{} func (m Map) Merge(merge Map) Map { return m.Copy().MergeHere(merge) } // Merge blends the specified map with this map and returns the current map. // // Keys that appear in both will be selected from the specified map. The original map // will be modified. This method requires that // the wrapped object be a map[string]interface{} func (m Map) MergeHere(merge Map) Map { for k, v := range merge { m[k] = v } return m } // Transform builds a new Obj giving the transformer a chance // to change the keys and values as it goes. This method requires that // the wrapped object be a map[string]interface{} func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map { newMap := make(map[string]interface{}) for k, v := range m { modifiedKey, modifiedVal := transformer(k, v) newMap[modifiedKey] = modifiedVal } return New(newMap) } // TransformKeys builds a new map using the specified key mapping. // // Unspecified keys will be unaltered. // This method requires that the wrapped object be a map[string]interface{} func (m Map) TransformKeys(mapping map[string]string) Map { return m.Transform(func(key string, value interface{}) (string, interface{}) { if newKey, ok := mapping[key]; ok { return newKey, value } return key, value }) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/map.go��������������0000644�0610621�0607500�00000012466�13172163422�032060� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx import ( "encoding/base64" "encoding/json" "errors" "io/ioutil" "net/url" "strings" ) // MSIConvertable is an interface that defines methods for converting your // custom types to a map[string]interface{} representation. type MSIConvertable interface { // MSI gets a map[string]interface{} (msi) representing the // object. MSI() map[string]interface{} } // Map provides extended functionality for working with // untyped data, in particular map[string]interface (msi). type Map map[string]interface{} // Value returns the internal value instance func (m Map) Value() *Value { return &Value{data: m} } // Nil represents a nil Map. var Nil Map = New(nil) // New creates a new Map containing the map[string]interface{} in the data argument. // If the data argument is not a map[string]interface, New attempts to call the // MSI() method on the MSIConvertable interface to create one. func New(data interface{}) Map { if _, ok := data.(map[string]interface{}); !ok { if converter, ok := data.(MSIConvertable); ok { data = converter.MSI() } else { return nil } } return Map(data.(map[string]interface{})) } // MSI creates a map[string]interface{} and puts it inside a new Map. // // The arguments follow a key, value pattern. // // Panics // // Panics if any key arugment is non-string or if there are an odd number of arguments. // // Example // // To easily create Maps: // // m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true)) // // // creates an Map equivalent to // m := objx.New(map[string]interface{}{"name": "Mat", "age": 29, "subobj": map[string]interface{}{"active": true}}) func MSI(keyAndValuePairs ...interface{}) Map { newMap := make(map[string]interface{}) keyAndValuePairsLen := len(keyAndValuePairs) if keyAndValuePairsLen%2 != 0 { panic("objx: MSI must have an even number of arguments following the 'key, value' pattern.") } for i := 0; i < keyAndValuePairsLen; i = i + 2 { key := keyAndValuePairs[i] value := keyAndValuePairs[i+1] // make sure the key is a string keyString, keyStringOK := key.(string) if !keyStringOK { panic("objx: MSI must follow 'string, interface{}' pattern. " + keyString + " is not a valid key.") } newMap[keyString] = value } return New(newMap) } // ****** Conversion Constructors // MustFromJSON creates a new Map containing the data specified in the // jsonString. // // Panics if the JSON is invalid. func MustFromJSON(jsonString string) Map { o, err := FromJSON(jsonString) if err != nil { panic("objx: MustFromJSON failed with error: " + err.Error()) } return o } // FromJSON creates a new Map containing the data specified in the // jsonString. // // Returns an error if the JSON is invalid. func FromJSON(jsonString string) (Map, error) { var data interface{} err := json.Unmarshal([]byte(jsonString), &data) if err != nil { return Nil, err } return New(data), nil } // FromBase64 creates a new Obj containing the data specified // in the Base64 string. // // The string is an encoded JSON string returned by Base64 func FromBase64(base64String string) (Map, error) { decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64String)) decoded, err := ioutil.ReadAll(decoder) if err != nil { return nil, err } return FromJSON(string(decoded)) } // MustFromBase64 creates a new Obj containing the data specified // in the Base64 string and panics if there is an error. // // The string is an encoded JSON string returned by Base64 func MustFromBase64(base64String string) Map { result, err := FromBase64(base64String) if err != nil { panic("objx: MustFromBase64 failed with error: " + err.Error()) } return result } // FromSignedBase64 creates a new Obj containing the data specified // in the Base64 string. // // The string is an encoded JSON string returned by SignedBase64 func FromSignedBase64(base64String, key string) (Map, error) { parts := strings.Split(base64String, SignatureSeparator) if len(parts) != 2 { return nil, errors.New("objx: Signed base64 string is malformed.") } sig := HashWithKey(parts[0], key) if parts[1] != sig { return nil, errors.New("objx: Signature for base64 data does not match.") } return FromBase64(parts[0]) } // MustFromSignedBase64 creates a new Obj containing the data specified // in the Base64 string and panics if there is an error. // // The string is an encoded JSON string returned by Base64 func MustFromSignedBase64(base64String, key string) Map { result, err := FromSignedBase64(base64String, key) if err != nil { panic("objx: MustFromSignedBase64 failed with error: " + err.Error()) } return result } // FromURLQuery generates a new Obj by parsing the specified // query. // // For queries with multiple values, the first value is selected. func FromURLQuery(query string) (Map, error) { vals, err := url.ParseQuery(query) if err != nil { return nil, err } m := make(map[string]interface{}) for k, vals := range vals { m[k] = vals[0] } return New(m), nil } // MustFromURLQuery generates a new Obj by parsing the specified // query. // // For queries with multiple values, the first value is selected. // // Panics if it encounters an error func MustFromURLQuery(query string) Map { o, err := FromURLQuery(query) if err != nil { panic("objx: MustFromURLQuery failed with error: " + err.Error()) } return o } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/doc.go��������������0000644�0610621�0607500�00000004443�13172163422�032044� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// objx - Go package for dealing with maps, slices, JSON and other data. // // Overview // // Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes // a powerful `Get` method (among others) that allows you to easily and quickly get // access to data within the map, without having to worry too much about type assertions, // missing data, default values etc. // // Pattern // // Objx uses a preditable pattern to make access data from within `map[string]interface{}'s // easy. // // Call one of the `objx.` functions to create your `objx.Map` to get going: // // m, err := objx.FromJSON(json) // // NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, // the rest will be optimistic and try to figure things out without panicking. // // Use `Get` to access the value you're interested in. You can use dot and array // notation too: // // m.Get("places[0].latlng") // // Once you have saught the `Value` you're interested in, you can use the `Is*` methods // to determine its type. // // if m.Get("code").IsStr() { /* ... */ } // // Or you can just assume the type, and use one of the strong type methods to // extract the real value: // // m.Get("code").Int() // // If there's no value there (or if it's the wrong type) then a default value // will be returned, or you can be explicit about the default value. // // Get("code").Int(-1) // // If you're dealing with a slice of data as a value, Objx provides many useful // methods for iterating, manipulating and selecting that data. You can find out more // by exploring the index below. // // Reading data // // A simple example of how to use Objx: // // // use MustFromJSON to make an objx.Map from some JSON // m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) // // // get the details // name := m.Get("name").Str() // age := m.Get("age").Int() // // // get their nickname (or use their name if they // // don't have one) // nickname := m.Get("nickname").Str(name) // // Ranging // // Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For // example, to `range` the data, do what you would expect: // // m := objx.MustFromJSON(json) // for key, value := range m { // // /* ... do your magic ... */ // // } package objx �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/conversions.go������0000644�0610621�0607500�00000004775�13172163422�033657� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "net/url" ) // JSON converts the contained object to a JSON string // representation func (m Map) JSON() (string, error) { result, err := json.Marshal(m) if err != nil { err = errors.New("objx: JSON encode failed with: " + err.Error()) } return string(result), err } // MustJSON converts the contained object to a JSON string // representation and panics if there is an error func (m Map) MustJSON() string { result, err := m.JSON() if err != nil { panic(err.Error()) } return result } // Base64 converts the contained object to a Base64 string // representation of the JSON string representation func (m Map) Base64() (string, error) { var buf bytes.Buffer jsonData, err := m.JSON() if err != nil { return "", err } encoder := base64.NewEncoder(base64.StdEncoding, &buf) encoder.Write([]byte(jsonData)) encoder.Close() return buf.String(), nil } // MustBase64 converts the contained object to a Base64 string // representation of the JSON string representation and panics // if there is an error func (m Map) MustBase64() string { result, err := m.Base64() if err != nil { panic(err.Error()) } return result } // SignedBase64 converts the contained object to a Base64 string // representation of the JSON string representation and signs it // using the provided key. func (m Map) SignedBase64(key string) (string, error) { base64, err := m.Base64() if err != nil { return "", err } sig := HashWithKey(base64, key) return base64 + SignatureSeparator + sig, nil } // MustSignedBase64 converts the contained object to a Base64 string // representation of the JSON string representation and signs it // using the provided key and panics if there is an error func (m Map) MustSignedBase64(key string) string { result, err := m.SignedBase64(key) if err != nil { panic(err.Error()) } return result } /* URL Query ------------------------------------------------ */ // URLValues creates a url.Values object from an Obj. This // function requires that the wrapped object be a map[string]interface{} func (m Map) URLValues() url.Values { vals := make(url.Values) for k, v := range m { //TODO: can this be done without sprintf? vals.Set(k, fmt.Sprintf("%v", v)) } return vals } // URLQuery gets an encoded URL query representing the given // Obj. This function requires that the wrapped object be a // map[string]interface{} func (m Map) URLQuery() (string, error) { return m.URLValues().Encode(), nil } ���lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/constants.go��������0000644�0610621�0607500�00000000505�13172163422�033306� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx const ( // PathSeparator is the character used to separate the elements // of the keypath. // // For example, `location.address.city` PathSeparator string = "." // SignatureSeparator is the character that is used to // separate the Base64 string from the security signature. SignatureSeparator = "_" ) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/������������0000755�0610621�0607500�00000000000�13172163422�032347� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������././@LongLink���������������������������������������������������������������������������������������0000644�0000000�0000000�00000000147�00000000000�011605� L����������������������������������������������������������������������������������������������������ustar �root����������������������������root�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/types_list.txt��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/types_list.t0000644�0610621�0607500�00000001107�13172163422�034732� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Interface,interface{},"something",nil,Inter Map,map[string]interface{},map[string]interface{}{"name":"Tyler"},nil,MSI ObjxMap,(Map),New(1),New(nil),ObjxMap Bool,bool,true,false,Bool String,string,"hello","",Str Int,int,1,0,Int Int8,int8,1,0,Int8 Int16,int16,1,0,Int16 Int32,int32,1,0,Int32 Int64,int64,1,0,Int64 Uint,uint,1,0,Uint Uint8,uint8,1,0,Uint8 Uint16,uint16,1,0,Uint16 Uint32,uint32,1,0,Uint32 Uint64,uint64,1,0,Uint64 Uintptr,uintptr,1,0,Uintptr Float32,float32,1,0,Float32 Float64,float64,1,0,Float64 Complex64,complex64,1,0,Complex64 Complex128,complex128,1,0,Complex128 ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/template.txt0000644�0610621�0607500�00000015362�13172163422�034732� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* {4} ({1} and []{1}) -------------------------------------------------- */ // {4} gets the value as a {1}, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) {4}(optionalDefault ...{1}) {1} { if s, ok := v.data.({1}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return {3} } // Must{4} gets the value as a {1}. // // Panics if the object is not a {1}. func (v *Value) Must{4}() {1} { return v.data.({1}) } // {4}Slice gets the value as a []{1}, returns the optionalDefault // value or nil if the value is not a []{1}. func (v *Value) {4}Slice(optionalDefault ...[]{1}) []{1} { if s, ok := v.data.([]{1}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // Must{4}Slice gets the value as a []{1}. // // Panics if the object is not a []{1}. func (v *Value) Must{4}Slice() []{1} { return v.data.([]{1}) } // Is{4} gets whether the object contained is a {1} or not. func (v *Value) Is{4}() bool { _, ok := v.data.({1}) return ok } // Is{4}Slice gets whether the object contained is a []{1} or not. func (v *Value) Is{4}Slice() bool { _, ok := v.data.([]{1}) return ok } // Each{4} calls the specified callback for each object // in the []{1}. // // Panics if the object is the wrong type. func (v *Value) Each{4}(callback func(int, {1}) bool) *Value { for index, val := range v.Must{4}Slice() { carryon := callback(index, val) if carryon == false { break } } return v } // Where{4} uses the specified decider function to select items // from the []{1}. The object contained in the result will contain // only the selected items. func (v *Value) Where{4}(decider func(int, {1}) bool) *Value { var selected []{1} v.Each{4}(func(index int, val {1}) bool { shouldSelect := decider(index, val) if shouldSelect == false { selected = append(selected, val) } return true }) return &Value{data:selected} } // Group{4} uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]{1}. func (v *Value) Group{4}(grouper func(int, {1}) string) *Value { groups := make(map[string][]{1}) v.Each{4}(func(index int, val {1}) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]{1}, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data:groups} } // Replace{4} uses the specified function to replace each {1}s // by iterating each item. The data in the returned result will be a // []{1} containing the replaced items. func (v *Value) Replace{4}(replacer func(int, {1}) {1}) *Value { arr := v.Must{4}Slice() replaced := make([]{1}, len(arr)) v.Each{4}(func(index int, val {1}) bool { replaced[index] = replacer(index, val) return true }) return &Value{data:replaced} } // Collect{4} uses the specified collector function to collect a value // for each of the {1}s in the slice. The data returned will be a // []interface{}. func (v *Value) Collect{4}(collector func(int, {1}) interface{}) *Value { arr := v.Must{4}Slice() collected := make([]interface{}, len(arr)) v.Each{4}(func(index int, val {1}) bool { collected[index] = collector(index, val) return true }) return &Value{data:collected} } // ************************************************************ // TESTS // ************************************************************ func Test{4}(t *testing.T) { val := {1}( {2} ) m := map[string]interface{}{"value": val, "nothing": nil} assert.Equal(t, val, New(m).Get("value").{4}()) assert.Equal(t, val, New(m).Get("value").Must{4}()) assert.Equal(t, {1}({3}), New(m).Get("nothing").{4}()) assert.Equal(t, val, New(m).Get("nothing").{4}({2})) assert.Panics(t, func() { New(m).Get("age").Must{4}() }) } func Test{4}Slice(t *testing.T) { val := {1}( {2} ) m := map[string]interface{}{"value": []{1}{ val }, "nothing": nil} assert.Equal(t, val, New(m).Get("value").{4}Slice()[0]) assert.Equal(t, val, New(m).Get("value").Must{4}Slice()[0]) assert.Equal(t, []{1}(nil), New(m).Get("nothing").{4}Slice()) assert.Equal(t, val, New(m).Get("nothing").{4}Slice( []{1}{ {1}({2}) } )[0]) assert.Panics(t, func() { New(m).Get("nothing").Must{4}Slice() }) } func TestIs{4}(t *testing.T) { var v *Value v = &Value{data: {1}({2})} assert.True(t, v.Is{4}()) v = &Value{data: []{1}{ {1}({2}) }} assert.True(t, v.Is{4}Slice()) } func TestEach{4}(t *testing.T) { v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} count := 0 replacedVals := make([]{1}, 0) assert.Equal(t, v, v.Each{4}(func(i int, val {1}) bool { count++ replacedVals = append(replacedVals, val) // abort early if i == 2 { return false } return true })) assert.Equal(t, count, 3) assert.Equal(t, replacedVals[0], v.Must{4}Slice()[0]) assert.Equal(t, replacedVals[1], v.Must{4}Slice()[1]) assert.Equal(t, replacedVals[2], v.Must{4}Slice()[2]) } func TestWhere{4}(t *testing.T) { v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} selected := v.Where{4}(func(i int, val {1}) bool { return i%2==0 }).Must{4}Slice() assert.Equal(t, 3, len(selected)) } func TestGroup{4}(t *testing.T) { v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} grouped := v.Group{4}(func(i int, val {1}) string { return fmt.Sprintf("%v", i%2==0) }).data.(map[string][]{1}) assert.Equal(t, 2, len(grouped)) assert.Equal(t, 3, len(grouped["true"])) assert.Equal(t, 3, len(grouped["false"])) } func TestReplace{4}(t *testing.T) { v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} rawArr := v.Must{4}Slice() replaced := v.Replace{4}(func(index int, val {1}) {1} { if index < len(rawArr)-1 { return rawArr[index+1] } return rawArr[0] }) replacedArr := replaced.Must{4}Slice() if assert.Equal(t, 6, len(replacedArr)) { assert.Equal(t, replacedArr[0], rawArr[1]) assert.Equal(t, replacedArr[1], rawArr[2]) assert.Equal(t, replacedArr[2], rawArr[3]) assert.Equal(t, replacedArr[3], rawArr[4]) assert.Equal(t, replacedArr[4], rawArr[5]) assert.Equal(t, replacedArr[5], rawArr[0]) } } func TestCollect{4}(t *testing.T) { v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} collected := v.Collect{4}(func(index int, val {1}) interface{} { return index }) collectedArr := collected.MustInterSlice() if assert.Equal(t, 6, len(collectedArr)) { assert.Equal(t, collectedArr[0], 0) assert.Equal(t, collectedArr[1], 1) assert.Equal(t, collectedArr[2], 2) assert.Equal(t, collectedArr[3], 3) assert.Equal(t, collectedArr[4], 4) assert.Equal(t, collectedArr[5], 5) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/index.html��0000644�0610621�0607500�00000002614�13172163422�034347� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<html> <head> <title> Codegen </title> <style> body { width: 800px; margin: auto; } textarea { width: 100%; min-height: 100px; font-family: Courier; } </style> </head> <body> <h2> Template </h2> <p> Use <code>{x}</code> as a placeholder for each argument. </p> <textarea id="template"></textarea> <h2> Arguments (comma separated) </h2> <p> One block per line </p> <textarea id="args"></textarea> <h2> Output </h2> <input id="go" type="button" value="Generate code" /> <textarea id="output"></textarea> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(function(){ $("#go").click(function(){ var output = "" var template = $("#template").val() var args = $("#args").val() // collect the args var argLines = args.split("\n") for (var line in argLines) { var argLine = argLines[line]; var thisTemp = template // get individual args var args = argLine.split(",") for (var argI in args) { var argText = args[argI]; var argPlaceholder = "{" + argI + "}"; while (thisTemp.indexOf(argPlaceholder) > -1) { thisTemp = thisTemp.replace(argPlaceholder, argText); } } output += thisTemp } $("#output").val(output); }); }); </script> </body> </html> ��������������������������������������������������������������������������������������������������������������������././@LongLink���������������������������������������������������������������������������������������0000644�0000000�0000000�00000000151�00000000000�011600� L����������������������������������������������������������������������������������������������������ustar �root����������������������������root�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/array-access.txt������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/codegen/array-access0000644�0610621�0607500�00000000530�13172163422�034645� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� case []{1}: a := object.([]{1}) if isSet { a[index] = value.({1}) } else { if index >= len(a) { if panics { panic(fmt.Sprintf("objx: Index %d is out of range because the []{1} only contains %d items.", index, len(a))) } return nil } else { return a[index] } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/accessors.go��������0000644�0610621�0607500�00000010341�13172163422�033256� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package objx import ( "fmt" "regexp" "strconv" "strings" ) // arrayAccesRegexString is the regex used to extract the array number // from the access path const arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` // arrayAccesRegex is the compiled arrayAccesRegexString var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) // Get gets the value using the specified selector and // returns it inside a new Obj object. // // If it cannot find the value, Get will return a nil // value inside an instance of Obj. // // Get can only operate directly on map[string]interface{} and []interface. // // Example // // To access the title of the third chapter of the second book, do: // // o.Get("books[1].chapters[2].title") func (m Map) Get(selector string) *Value { rawObj := access(m, selector, nil, false, false) return &Value{data: rawObj} } // Set sets the value using the specified selector and // returns the object on which Set was called. // // Set can only operate directly on map[string]interface{} and []interface // // Example // // To set the title of the third chapter of the second book, do: // // o.Set("books[1].chapters[2].title","Time to Go") func (m Map) Set(selector string, value interface{}) Map { access(m, selector, value, true, false) return m } // access accesses the object using the selector and performs the // appropriate action. func access(current, selector, value interface{}, isSet, panics bool) interface{} { switch selector.(type) { case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: if array, ok := current.([]interface{}); ok { index := intFromInterface(selector) if index >= len(array) { if panics { panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) } return nil } return array[index] } return nil case string: selStr := selector.(string) selSegs := strings.SplitN(selStr, PathSeparator, 2) thisSel := selSegs[0] index := -1 var err error // https://github.com/stretchr/objx/issues/12 if strings.Contains(thisSel, "[") { arrayMatches := arrayAccesRegex.FindStringSubmatch(thisSel) if len(arrayMatches) > 0 { // Get the key into the map thisSel = arrayMatches[1] // Get the index into the array at the key index, err = strconv.Atoi(arrayMatches[2]) if err != nil { // This should never happen. If it does, something has gone // seriously wrong. Panic. panic("objx: Array index is not an integer. Must use array[int].") } } } if curMap, ok := current.(Map); ok { current = map[string]interface{}(curMap) } // get the object in question switch current.(type) { case map[string]interface{}: curMSI := current.(map[string]interface{}) if len(selSegs) <= 1 && isSet { curMSI[thisSel] = value return nil } else { current = curMSI[thisSel] } default: current = nil } if current == nil && panics { panic(fmt.Sprintf("objx: '%v' invalid on object.", selector)) } // do we need to access the item of an array? if index > -1 { if array, ok := current.([]interface{}); ok { if index < len(array) { current = array[index] } else { if panics { panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) } current = nil } } } if len(selSegs) > 1 { current = access(current, selSegs[1], value, isSet, panics) } } return current } // intFromInterface converts an interface object to the largest // representation of an unsigned integer using a type switch and // assertions func intFromInterface(selector interface{}) int { var value int switch selector.(type) { case int: value = selector.(int) case int8: value = int(selector.(int8)) case int16: value = int(selector.(int16)) case int32: value = int(selector.(int32)) case int64: value = int(selector.(int64)) case uint: value = int(selector.(uint)) case uint8: value = int(selector.(uint8)) case uint16: value = int(selector.(uint16)) case uint32: value = int(selector.(uint32)) case uint64: value = int(selector.(uint64)) default: panic("objx: array access argument is not an integer type (this should never happen)") } return value } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/README.md�����������0000644�0610621�0607500�00000000131�13172163422�032215� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# objx * Jump into the [API Documentation](http://godoc.org/github.com/stretchr/objx) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/LICENSE.md����������0000644�0610621�0607500�00000002137�13172163422�032352� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������objx - by Mat Ryer and Tyler Bunnell The MIT License (MIT) Copyright (c) 2014 Stretchr, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/pmezard/��������������������������0000755�0610621�0607500�00000000000�13172163422�027605� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/���������������0000755�0610621�0607500�00000000000�13172163422�031607� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib/�������0000755�0610621�0607500�00000000000�13172163422�033206� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������././@LongLink���������������������������������������������������������������������������������������0000644�0000000�0000000�00000000150�00000000000�011577� L����������������������������������������������������������������������������������������������������ustar �root����������������������������root�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib/difflib.go�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib/difflib0000644�0610621�0607500�00000054032�13172163422�034534� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package difflib is a partial port of Python difflib module. // // It provides tools to compare sequences of strings and generate textual diffs. // // The following class and functions have been ported: // // - SequenceMatcher // // - unified_diff // // - context_diff // // Getting unified diffs was the main goal of the port. Keep in mind this code // is mostly suitable to output text differences in a human friendly way, there // are no guarantees generated diffs are consumable by patch(1). package difflib import ( "bufio" "bytes" "fmt" "io" "strings" ) func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } func calculateRatio(matches, length int) float64 { if length > 0 { return 2.0 * float64(matches) / float64(length) } return 1.0 } type Match struct { A int B int Size int } type OpCode struct { Tag byte I1 int I2 int J1 int J2 int } // SequenceMatcher compares sequence of strings. The basic // algorithm predates, and is a little fancier than, an algorithm // published in the late 1980's by Ratcliff and Obershelp under the // hyperbolic name "gestalt pattern matching". The basic idea is to find // the longest contiguous matching subsequence that contains no "junk" // elements (R-O doesn't address junk). The same idea is then applied // recursively to the pieces of the sequences to the left and to the right // of the matching subsequence. This does not yield minimal edit // sequences, but does tend to yield matches that "look right" to people. // // SequenceMatcher tries to compute a "human-friendly diff" between two // sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the // longest *contiguous* & junk-free matching subsequence. That's what // catches peoples' eyes. The Windows(tm) windiff has another interesting // notion, pairing up elements that appear uniquely in each sequence. // That, and the method here, appear to yield more intuitive difference // reports than does diff. This method appears to be the least vulnerable // to synching up on blocks of "junk lines", though (like blank lines in // ordinary text files, or maybe "<P>" lines in HTML files). That may be // because this is the only method of the 3 that has a *concept* of // "junk" <wink>. // // Timing: Basic R-O is cubic time worst case and quadratic time expected // case. SequenceMatcher is quadratic time for the worst case and has // expected-case behavior dependent in a complicated way on how many // elements the sequences have in common; best case time is linear. type SequenceMatcher struct { a []string b []string b2j map[string][]int IsJunk func(string) bool autoJunk bool bJunk map[string]struct{} matchingBlocks []Match fullBCount map[string]int bPopular map[string]struct{} opCodes []OpCode } func NewMatcher(a, b []string) *SequenceMatcher { m := SequenceMatcher{autoJunk: true} m.SetSeqs(a, b) return &m } func NewMatcherWithJunk(a, b []string, autoJunk bool, isJunk func(string) bool) *SequenceMatcher { m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} m.SetSeqs(a, b) return &m } // Set two sequences to be compared. func (m *SequenceMatcher) SetSeqs(a, b []string) { m.SetSeq1(a) m.SetSeq2(b) } // Set the first sequence to be compared. The second sequence to be compared is // not changed. // // SequenceMatcher computes and caches detailed information about the second // sequence, so if you want to compare one sequence S against many sequences, // use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other // sequences. // // See also SetSeqs() and SetSeq2(). func (m *SequenceMatcher) SetSeq1(a []string) { if &a == &m.a { return } m.a = a m.matchingBlocks = nil m.opCodes = nil } // Set the second sequence to be compared. The first sequence to be compared is // not changed. func (m *SequenceMatcher) SetSeq2(b []string) { if &b == &m.b { return } m.b = b m.matchingBlocks = nil m.opCodes = nil m.fullBCount = nil m.chainB() } func (m *SequenceMatcher) chainB() { // Populate line -> index mapping b2j := map[string][]int{} for i, s := range m.b { indices := b2j[s] indices = append(indices, i) b2j[s] = indices } // Purge junk elements m.bJunk = map[string]struct{}{} if m.IsJunk != nil { junk := m.bJunk for s, _ := range b2j { if m.IsJunk(s) { junk[s] = struct{}{} } } for s, _ := range junk { delete(b2j, s) } } // Purge remaining popular elements popular := map[string]struct{}{} n := len(m.b) if m.autoJunk && n >= 200 { ntest := n/100 + 1 for s, indices := range b2j { if len(indices) > ntest { popular[s] = struct{}{} } } for s, _ := range popular { delete(b2j, s) } } m.bPopular = popular m.b2j = b2j } func (m *SequenceMatcher) isBJunk(s string) bool { _, ok := m.bJunk[s] return ok } // Find longest matching block in a[alo:ahi] and b[blo:bhi]. // // If IsJunk is not defined: // // Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where // alo <= i <= i+k <= ahi // blo <= j <= j+k <= bhi // and for all (i',j',k') meeting those conditions, // k >= k' // i <= i' // and if i == i', j <= j' // // In other words, of all maximal matching blocks, return one that // starts earliest in a, and of all those maximal matching blocks that // start earliest in a, return the one that starts earliest in b. // // If IsJunk is defined, first the longest matching block is // determined as above, but with the additional restriction that no // junk element appears in the block. Then that block is extended as // far as possible by matching (only) junk elements on both sides. So // the resulting block never matches on junk except as identical junk // happens to be adjacent to an "interesting" match. // // If no blocks match, return (alo, blo, 0). func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { // CAUTION: stripping common prefix or suffix would be incorrect. // E.g., // ab // acab // Longest matching block is "ab", but if common prefix is // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so // strip, so ends up claiming that ab is changed to acab by // inserting "ca" in the middle. That's minimal but unintuitive: // "it's obvious" that someone inserted "ac" at the front. // Windiff ends up at the same place as diff, but by pairing up // the unique 'b's and then matching the first two 'a's. besti, bestj, bestsize := alo, blo, 0 // find longest junk-free match // during an iteration of the loop, j2len[j] = length of longest // junk-free match ending with a[i-1] and b[j] j2len := map[int]int{} for i := alo; i != ahi; i++ { // look at all instances of a[i] in b; note that because // b2j has no junk keys, the loop is skipped if a[i] is junk newj2len := map[int]int{} for _, j := range m.b2j[m.a[i]] { // a[i] matches b[j] if j < blo { continue } if j >= bhi { break } k := j2len[j-1] + 1 newj2len[j] = k if k > bestsize { besti, bestj, bestsize = i-k+1, j-k+1, k } } j2len = newj2len } // Extend the best by non-junk elements on each end. In particular, // "popular" non-junk elements aren't in b2j, which greatly speeds // the inner loop above, but also means "the best" match so far // doesn't contain any junk *or* popular non-junk elements. for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && m.a[besti-1] == m.b[bestj-1] { besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 } for besti+bestsize < ahi && bestj+bestsize < bhi && !m.isBJunk(m.b[bestj+bestsize]) && m.a[besti+bestsize] == m.b[bestj+bestsize] { bestsize += 1 } // Now that we have a wholly interesting match (albeit possibly // empty!), we may as well suck up the matching junk on each // side of it too. Can't think of a good reason not to, and it // saves post-processing the (possibly considerable) expense of // figuring out what to do with it. In the case of an empty // interesting match, this is clearly the right thing to do, // because no other kind of match is possible in the regions. for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && m.a[besti-1] == m.b[bestj-1] { besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 } for besti+bestsize < ahi && bestj+bestsize < bhi && m.isBJunk(m.b[bestj+bestsize]) && m.a[besti+bestsize] == m.b[bestj+bestsize] { bestsize += 1 } return Match{A: besti, B: bestj, Size: bestsize} } // Return list of triples describing matching subsequences. // // Each triple is of the form (i, j, n), and means that // a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in // i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are // adjacent triples in the list, and the second is not the last triple in the // list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe // adjacent equal blocks. // // The last triple is a dummy, (len(a), len(b), 0), and is the only // triple with n==0. func (m *SequenceMatcher) GetMatchingBlocks() []Match { if m.matchingBlocks != nil { return m.matchingBlocks } var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { match := m.findLongestMatch(alo, ahi, blo, bhi) i, j, k := match.A, match.B, match.Size if match.Size > 0 { if alo < i && blo < j { matched = matchBlocks(alo, i, blo, j, matched) } matched = append(matched, match) if i+k < ahi && j+k < bhi { matched = matchBlocks(i+k, ahi, j+k, bhi, matched) } } return matched } matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) // It's possible that we have adjacent equal blocks in the // matching_blocks list now. nonAdjacent := []Match{} i1, j1, k1 := 0, 0, 0 for _, b := range matched { // Is this block adjacent to i1, j1, k1? i2, j2, k2 := b.A, b.B, b.Size if i1+k1 == i2 && j1+k1 == j2 { // Yes, so collapse them -- this just increases the length of // the first block by the length of the second, and the first // block so lengthened remains the block to compare against. k1 += k2 } else { // Not adjacent. Remember the first block (k1==0 means it's // the dummy we started with), and make the second block the // new block to compare against. if k1 > 0 { nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) } i1, j1, k1 = i2, j2, k2 } } if k1 > 0 { nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) } nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) m.matchingBlocks = nonAdjacent return m.matchingBlocks } // Return list of 5-tuples describing how to turn a into b. // // Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple // has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the // tuple preceding it, and likewise for j1 == the previous j2. // // The tags are characters, with these meanings: // // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] // // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. // // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. // // 'e' (equal): a[i1:i2] == b[j1:j2] func (m *SequenceMatcher) GetOpCodes() []OpCode { if m.opCodes != nil { return m.opCodes } i, j := 0, 0 matching := m.GetMatchingBlocks() opCodes := make([]OpCode, 0, len(matching)) for _, m := range matching { // invariant: we've pumped out correct diffs to change // a[:i] into b[:j], and the next matching block is // a[ai:ai+size] == b[bj:bj+size]. So we need to pump // out a diff to change a[i:ai] into b[j:bj], pump out // the matching block, and move (i,j) beyond the match ai, bj, size := m.A, m.B, m.Size tag := byte(0) if i < ai && j < bj { tag = 'r' } else if i < ai { tag = 'd' } else if j < bj { tag = 'i' } if tag > 0 { opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) } i, j = ai+size, bj+size // the list of matching blocks is terminated by a // sentinel with size 0 if size > 0 { opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) } } m.opCodes = opCodes return m.opCodes } // Isolate change clusters by eliminating ranges with no changes. // // Return a generator of groups with up to n lines of context. // Each group is in the same format as returned by GetOpCodes(). func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { if n < 0 { n = 3 } codes := m.GetOpCodes() if len(codes) == 0 { codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} } // Fixup leading and trailing groups if they show no changes. if codes[0].Tag == 'e' { c := codes[0] i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} } if codes[len(codes)-1].Tag == 'e' { c := codes[len(codes)-1] i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} } nn := n + n groups := [][]OpCode{} group := []OpCode{} for _, c := range codes { i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 // End the current group and start a new one whenever // there is a large range with no changes. if c.Tag == 'e' && i2-i1 > nn { group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}) groups = append(groups, group) group = []OpCode{} i1, j1 = max(i1, i2-n), max(j1, j2-n) } group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) } if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { groups = append(groups, group) } return groups } // Return a measure of the sequences' similarity (float in [0,1]). // // Where T is the total number of elements in both sequences, and // M is the number of matches, this is 2.0*M / T. // Note that this is 1 if the sequences are identical, and 0 if // they have nothing in common. // // .Ratio() is expensive to compute if you haven't already computed // .GetMatchingBlocks() or .GetOpCodes(), in which case you may // want to try .QuickRatio() or .RealQuickRation() first to get an // upper bound. func (m *SequenceMatcher) Ratio() float64 { matches := 0 for _, m := range m.GetMatchingBlocks() { matches += m.Size } return calculateRatio(matches, len(m.a)+len(m.b)) } // Return an upper bound on ratio() relatively quickly. // // This isn't defined beyond that it is an upper bound on .Ratio(), and // is faster to compute. func (m *SequenceMatcher) QuickRatio() float64 { // viewing a and b as multisets, set matches to the cardinality // of their intersection; this counts the number of matches // without regard to order, so is clearly an upper bound if m.fullBCount == nil { m.fullBCount = map[string]int{} for _, s := range m.b { m.fullBCount[s] = m.fullBCount[s] + 1 } } // avail[x] is the number of times x appears in 'b' less the // number of times we've seen it in 'a' so far ... kinda avail := map[string]int{} matches := 0 for _, s := range m.a { n, ok := avail[s] if !ok { n = m.fullBCount[s] } avail[s] = n - 1 if n > 0 { matches += 1 } } return calculateRatio(matches, len(m.a)+len(m.b)) } // Return an upper bound on ratio() very quickly. // // This isn't defined beyond that it is an upper bound on .Ratio(), and // is faster to compute than either .Ratio() or .QuickRatio(). func (m *SequenceMatcher) RealQuickRatio() float64 { la, lb := len(m.a), len(m.b) return calculateRatio(min(la, lb), la+lb) } // Convert range to the "ed" format func formatRangeUnified(start, stop int) string { // Per the diff spec at http://www.unix.org/single_unix_specification/ beginning := start + 1 // lines start numbering with one length := stop - start if length == 1 { return fmt.Sprintf("%d", beginning) } if length == 0 { beginning -= 1 // empty ranges begin at line just before the range } return fmt.Sprintf("%d,%d", beginning, length) } // Unified diff parameters type UnifiedDiff struct { A []string // First sequence lines FromFile string // First file name FromDate string // First file time B []string // Second sequence lines ToFile string // Second file name ToDate string // Second file time Eol string // Headers end of line, defaults to LF Context int // Number of context lines } // Compare two sequences of lines; generate the delta as a unified diff. // // Unified diffs are a compact way of showing line changes and a few // lines of context. The number of context lines is set by 'n' which // defaults to three. // // By default, the diff control lines (those with ---, +++, or @@) are // created with a trailing newline. This is helpful so that inputs // created from file.readlines() result in diffs that are suitable for // file.writelines() since both the inputs and outputs have trailing // newlines. // // For inputs that do not have trailing newlines, set the lineterm // argument to "" so that the output will be uniformly newline free. // // The unidiff format normally has a header for filenames and modification // times. Any or all of these may be specified using strings for // 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. // The modification times are normally expressed in the ISO 8601 format. func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { buf := bufio.NewWriter(writer) defer buf.Flush() w := func(format string, args ...interface{}) error { _, err := buf.WriteString(fmt.Sprintf(format, args...)) return err } if len(diff.Eol) == 0 { diff.Eol = "\n" } started := false m := NewMatcher(diff.A, diff.B) for _, g := range m.GetGroupedOpCodes(diff.Context) { if !started { started = true fromDate := "" if len(diff.FromDate) > 0 { fromDate = "\t" + diff.FromDate } toDate := "" if len(diff.ToDate) > 0 { toDate = "\t" + diff.ToDate } err := w("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) if err != nil { return err } err = w("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) if err != nil { return err } } first, last := g[0], g[len(g)-1] range1 := formatRangeUnified(first.I1, last.I2) range2 := formatRangeUnified(first.J1, last.J2) if err := w("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { return err } for _, c := range g { i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 if c.Tag == 'e' { for _, line := range diff.A[i1:i2] { if err := w(" " + line); err != nil { return err } } continue } if c.Tag == 'r' || c.Tag == 'd' { for _, line := range diff.A[i1:i2] { if err := w("-" + line); err != nil { return err } } } if c.Tag == 'r' || c.Tag == 'i' { for _, line := range diff.B[j1:j2] { if err := w("+" + line); err != nil { return err } } } } } return nil } // Like WriteUnifiedDiff but returns the diff a string. func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { w := &bytes.Buffer{} err := WriteUnifiedDiff(w, diff) return string(w.Bytes()), err } // Convert range to the "ed" format. func formatRangeContext(start, stop int) string { // Per the diff spec at http://www.unix.org/single_unix_specification/ beginning := start + 1 // lines start numbering with one length := stop - start if length == 0 { beginning -= 1 // empty ranges begin at line just before the range } if length <= 1 { return fmt.Sprintf("%d", beginning) } return fmt.Sprintf("%d,%d", beginning, beginning+length-1) } type ContextDiff UnifiedDiff // Compare two sequences of lines; generate the delta as a context diff. // // Context diffs are a compact way of showing line changes and a few // lines of context. The number of context lines is set by diff.Context // which defaults to three. // // By default, the diff control lines (those with *** or ---) are // created with a trailing newline. // // For inputs that do not have trailing newlines, set the diff.Eol // argument to "" so that the output will be uniformly newline free. // // The context diff format normally has a header for filenames and // modification times. Any or all of these may be specified using // strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. // The modification times are normally expressed in the ISO 8601 format. // If not specified, the strings default to blanks. func WriteContextDiff(writer io.Writer, diff ContextDiff) error { buf := bufio.NewWriter(writer) defer buf.Flush() var diffErr error w := func(format string, args ...interface{}) { _, err := buf.WriteString(fmt.Sprintf(format, args...)) if diffErr == nil && err != nil { diffErr = err } } if len(diff.Eol) == 0 { diff.Eol = "\n" } prefix := map[byte]string{ 'i': "+ ", 'd': "- ", 'r': "! ", 'e': " ", } started := false m := NewMatcher(diff.A, diff.B) for _, g := range m.GetGroupedOpCodes(diff.Context) { if !started { started = true fromDate := "" if len(diff.FromDate) > 0 { fromDate = "\t" + diff.FromDate } toDate := "" if len(diff.ToDate) > 0 { toDate = "\t" + diff.ToDate } w("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) w("--- %s%s%s", diff.ToFile, toDate, diff.Eol) } first, last := g[0], g[len(g)-1] w("***************" + diff.Eol) range1 := formatRangeContext(first.I1, last.I2) w("*** %s ****%s", range1, diff.Eol) for _, c := range g { if c.Tag == 'r' || c.Tag == 'd' { for _, cc := range g { if cc.Tag == 'i' { continue } for _, line := range diff.A[cc.I1:cc.I2] { w(prefix[cc.Tag] + line) } } break } } range2 := formatRangeContext(first.J1, last.J2) w("--- %s ----%s", range2, diff.Eol) for _, c := range g { if c.Tag == 'r' || c.Tag == 'i' { for _, cc := range g { if cc.Tag == 'd' { continue } for _, line := range diff.B[cc.J1:cc.J2] { w(prefix[cc.Tag] + line) } } break } } } return diffErr } // Like WriteContextDiff but returns the diff a string. func GetContextDiffString(diff ContextDiff) (string, error) { w := &bytes.Buffer{} err := WriteContextDiff(w, diff) return string(w.Bytes()), err } // Split a string on "\n" while preserving them. The output can be used // as input for UnifiedDiff and ContextDiff structures. func SplitLines(s string) []string { lines := strings.SplitAfter(s, "\n") lines[len(lines)-1] += "\n" return lines } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/LICENSE��������0000644�0610621�0607500�00000002645�13172163422�032623� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2013, Patrick Mezard All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. �������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/��������������������������0000755�0610621�0607500�00000000000�13172163422�027544� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/������������������0000755�0610621�0607500�00000000000�13172163422�031125� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/�������������0000755�0610621�0607500�00000000000�13172163422�032103� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/spew.go������0000644�0610621�0607500�00000013514�13172163422�033414� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * Copyright (c) 2013 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "fmt" "io" ) // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the formatted string as a value that satisfies error. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Errorf(format string, a ...interface{}) (err error) { return fmt.Errorf(format, convertArgs(a)...) } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprint(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprint(w, convertArgs(a)...) } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { return fmt.Fprintf(w, format, convertArgs(a)...) } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it // passed with a default Formatter interface returned by NewFormatter. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprintln(w, convertArgs(a)...) } // Print is a wrapper for fmt.Print that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) func Print(a ...interface{}) (n int, err error) { return fmt.Print(convertArgs(a)...) } // Printf is a wrapper for fmt.Printf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, convertArgs(a)...) } // Println is a wrapper for fmt.Println that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) func Println(a ...interface{}) (n int, err error) { return fmt.Println(convertArgs(a)...) } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) func Sprint(a ...interface{}) string { return fmt.Sprint(convertArgs(a)...) } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, convertArgs(a)...) } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it // were passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) func Sprintln(a ...interface{}) string { return fmt.Sprintln(convertArgs(a)...) } // convertArgs accepts a slice of arguments and returns a slice of the same // length with each argument converted to a default spew Formatter interface. func convertArgs(args []interface{}) (formatters []interface{}) { formatters = make([]interface{}, len(args)) for index, arg := range args { formatters[index] = NewFormatter(arg) } return formatters } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/format.go����0000644�0610621�0607500�00000026075�13172163422�033734� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * Copyright (c) 2013 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "reflect" "strconv" "strings" ) // supportedFlags is a list of all the character flags supported by fmt package. const supportedFlags = "0-+# " // formatState implements the fmt.Formatter interface and contains information // about the state of a formatting operation. The NewFormatter function can // be used to get a new Formatter which can be used directly as arguments // in standard fmt package printing calls. type formatState struct { value interface{} fs fmt.State depth int pointers map[uintptr]int ignoreNextType bool cs *ConfigState } // buildDefaultFormat recreates the original format string without precision // and width information to pass in to fmt.Sprintf in the case of an // unrecognized type. Unless new types are added to the language, this // function won't ever be called. func (f *formatState) buildDefaultFormat() (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } buf.WriteRune('v') format = buf.String() return format } // constructOrigFormat recreates the original format string including precision // and width information to pass along to the standard fmt package. This allows // automatic deferral of all format strings this package doesn't support. func (f *formatState) constructOrigFormat(verb rune) (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } if width, ok := f.fs.Width(); ok { buf.WriteString(strconv.Itoa(width)) } if precision, ok := f.fs.Precision(); ok { buf.Write(precisionBytes) buf.WriteString(strconv.Itoa(precision)) } buf.WriteRune(verb) format = buf.String() return format } // unpackValue returns values inside of non-nil interfaces when possible and // ensures that types for values which have been unpacked from an interface // are displayed when the show types flag is also set. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (f *formatState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface { f.ignoreNextType = false if !v.IsNil() { v = v.Elem() } } return v } // formatPtr handles formatting of pointers by indirecting them as necessary. func (f *formatState) formatPtr(v reflect.Value) { // Display nil if top level pointer is nil. showTypes := f.fs.Flag('#') if v.IsNil() && (!showTypes || f.ignoreNextType) { f.fs.Write(nilAngleBytes) return } // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range f.pointers { if depth >= f.depth { delete(f.pointers, k) } } // Keep list of all dereferenced pointers to possibly show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by derferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := f.pointers[addr]; ok && pd < f.depth { cycleFound = true indirects-- break } f.pointers[addr] = f.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type or indirection level depending on flags. if showTypes && !f.ignoreNextType { f.fs.Write(openParenBytes) f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) f.fs.Write([]byte(ve.Type().String())) f.fs.Write(closeParenBytes) } else { if nilFound || cycleFound { indirects += strings.Count(ve.Type().String(), "*") } f.fs.Write(openAngleBytes) f.fs.Write([]byte(strings.Repeat("*", indirects))) f.fs.Write(closeAngleBytes) } // Display pointer information depending on flags. if f.fs.Flag('+') && (len(pointerChain) > 0) { f.fs.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { f.fs.Write(pointerChainBytes) } printHexPtr(f.fs, addr) } f.fs.Write(closeParenBytes) } // Display dereferenced value. switch { case nilFound == true: f.fs.Write(nilAngleBytes) case cycleFound == true: f.fs.Write(circularShortBytes) default: f.ignoreNextType = true f.format(ve) } } // format is the main workhorse for providing the Formatter interface. It // uses the passed reflect value to figure out what kind of object we are // dealing with and formats it appropriately. It is a recursive function, // however circular data structures are detected and handled properly. func (f *formatState) format(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { f.fs.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { f.formatPtr(v) return } // Print type information unless already handled elsewhere. if !f.ignoreNextType && f.fs.Flag('#') { f.fs.Write(openParenBytes) f.fs.Write([]byte(v.Type().String())) f.fs.Write(closeParenBytes) } f.ignoreNextType = false // Call Stringer/error interfaces if they exist and the handle methods // flag is enabled. if !f.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(f.cs, f.fs, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(f.fs, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(f.fs, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(f.fs, v.Uint(), 10) case reflect.Float32: printFloat(f.fs, v.Float(), 32) case reflect.Float64: printFloat(f.fs, v.Float(), 64) case reflect.Complex64: printComplex(f.fs, v.Complex(), 32) case reflect.Complex128: printComplex(f.fs, v.Complex(), 64) case reflect.Slice: if v.IsNil() { f.fs.Write(nilAngleBytes) break } fallthrough case reflect.Array: f.fs.Write(openBracketBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { numEntries := v.Len() for i := 0; i < numEntries; i++ { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(v.Index(i))) } } f.depth-- f.fs.Write(closeBracketBytes) case reflect.String: f.fs.Write([]byte(v.String())) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { f.fs.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { f.fs.Write(nilAngleBytes) break } f.fs.Write(openMapBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { keys := v.MapKeys() if f.cs.SortKeys { sortValues(keys, f.cs) } for i, key := range keys { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(key)) f.fs.Write(colonBytes) f.ignoreNextType = true f.format(f.unpackValue(v.MapIndex(key))) } } f.depth-- f.fs.Write(closeMapBytes) case reflect.Struct: numFields := v.NumField() f.fs.Write(openBraceBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { vt := v.Type() for i := 0; i < numFields; i++ { if i > 0 { f.fs.Write(spaceBytes) } vtf := vt.Field(i) if f.fs.Flag('+') || f.fs.Flag('#') { f.fs.Write([]byte(vtf.Name)) f.fs.Write(colonBytes) } f.format(f.unpackValue(v.Field(i))) } } f.depth-- f.fs.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(f.fs, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(f.fs, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it if any get added. default: format := f.buildDefaultFormat() if v.CanInterface() { fmt.Fprintf(f.fs, format, v.Interface()) } else { fmt.Fprintf(f.fs, format, v.String()) } } } // Format satisfies the fmt.Formatter interface. See NewFormatter for usage // details. func (f *formatState) Format(fs fmt.State, verb rune) { f.fs = fs // Use standard formatting for verbs that are not v. if verb != 'v' { format := f.constructOrigFormat(verb) fmt.Fprintf(fs, format, f.value) return } if f.value == nil { if fs.Flag('#') { fs.Write(interfaceBytes) } fs.Write(nilAngleBytes) return } f.format(reflect.ValueOf(f.value)) } // newFormatter is a helper function to consolidate the logic from the various // public methods which take varying config states. func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { fs := &formatState{value: v, cs: cs} fs.pointers = make(map[uintptr]int) return fs } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as Printf, Println, or Fprintf. */ func NewFormatter(v interface{}) fmt.Formatter { return newFormatter(&Config, v) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/dump.go������0000644�0610621�0607500�00000032760�13172163422�033407� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * Copyright (c) 2013 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "encoding/hex" "fmt" "io" "os" "reflect" "regexp" "strconv" "strings" ) var ( // uint8Type is a reflect.Type representing a uint8. It is used to // convert cgo types to uint8 slices for hexdumping. uint8Type = reflect.TypeOf(uint8(0)) // cCharRE is a regular expression that matches a cgo char. // It is used to detect character arrays to hexdump them. cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") // cUnsignedCharRE is a regular expression that matches a cgo unsigned // char. It is used to detect unsigned character arrays to hexdump // them. cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") // cUint8tCharRE is a regular expression that matches a cgo uint8_t. // It is used to detect uint8_t arrays to hexdump them. cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") ) // dumpState contains information about the state of a dump operation. type dumpState struct { w io.Writer depth int pointers map[uintptr]int ignoreNextType bool ignoreNextIndent bool cs *ConfigState } // indent performs indentation according to the depth level and cs.Indent // option. func (d *dumpState) indent() { if d.ignoreNextIndent { d.ignoreNextIndent = false return } d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) } // unpackValue returns values inside of non-nil interfaces when possible. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } return v } // dumpPtr handles formatting of pointers by indirecting them as necessary. func (d *dumpState) dumpPtr(v reflect.Value) { // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range d.pointers { if depth >= d.depth { delete(d.pointers, k) } } // Keep list of all dereferenced pointers to show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by dereferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := d.pointers[addr]; ok && pd < d.depth { cycleFound = true indirects-- break } d.pointers[addr] = d.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type information. d.w.Write(openParenBytes) d.w.Write(bytes.Repeat(asteriskBytes, indirects)) d.w.Write([]byte(ve.Type().String())) d.w.Write(closeParenBytes) // Display pointer information. if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { d.w.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { d.w.Write(pointerChainBytes) } printHexPtr(d.w, addr) } d.w.Write(closeParenBytes) } // Display dereferenced value. d.w.Write(openParenBytes) switch { case nilFound == true: d.w.Write(nilAngleBytes) case cycleFound == true: d.w.Write(circularBytes) default: d.ignoreNextType = true d.dump(ve) } d.w.Write(closeParenBytes) } // dumpSlice handles formatting of arrays and slices. Byte (uint8 under // reflection) arrays and slices are dumped in hexdump -C fashion. func (d *dumpState) dumpSlice(v reflect.Value) { // Determine whether this type should be hex dumped or not. Also, // for types which should be hexdumped, try to use the underlying data // first, then fall back to trying to convert them to a uint8 slice. var buf []uint8 doConvert := false doHexDump := false numEntries := v.Len() if numEntries > 0 { vt := v.Index(0).Type() vts := vt.String() switch { // C types that need to be converted. case cCharRE.MatchString(vts): fallthrough case cUnsignedCharRE.MatchString(vts): fallthrough case cUint8tCharRE.MatchString(vts): doConvert = true // Try to use existing uint8 slices and fall back to converting // and copying if that fails. case vt.Kind() == reflect.Uint8: // We need an addressable interface to convert the type // to a byte slice. However, the reflect package won't // give us an interface on certain things like // unexported struct fields in order to enforce // visibility rules. We use unsafe, when available, to // bypass these restrictions since this package does not // mutate the values. vs := v if !vs.CanInterface() || !vs.CanAddr() { vs = unsafeReflectValue(vs) } if !UnsafeDisabled { vs = vs.Slice(0, numEntries) // Use the existing uint8 slice if it can be // type asserted. iface := vs.Interface() if slice, ok := iface.([]uint8); ok { buf = slice doHexDump = true break } } // The underlying data needs to be converted if it can't // be type asserted to a uint8 slice. doConvert = true } // Copy and convert the underlying type if needed. if doConvert && vt.ConvertibleTo(uint8Type) { // Convert and copy each element into a uint8 byte // slice. buf = make([]uint8, numEntries) for i := 0; i < numEntries; i++ { vv := v.Index(i) buf[i] = uint8(vv.Convert(uint8Type).Uint()) } doHexDump = true } } // Hexdump the entire slice as needed. if doHexDump { indent := strings.Repeat(d.cs.Indent, d.depth) str := indent + hex.Dump(buf) str = strings.Replace(str, "\n", "\n"+indent, -1) str = strings.TrimRight(str, d.cs.Indent) d.w.Write([]byte(str)) return } // Recursively call dump for each item. for i := 0; i < numEntries; i++ { d.dump(d.unpackValue(v.Index(i))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } // dump is the main workhorse for dumping a value. It uses the passed reflect // value to figure out what kind of object we are dealing with and formats it // appropriately. It is a recursive function, however circular data structures // are detected and handled properly. func (d *dumpState) dump(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { d.w.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { d.indent() d.dumpPtr(v) return } // Print type information unless already handled elsewhere. if !d.ignoreNextType { d.indent() d.w.Write(openParenBytes) d.w.Write([]byte(v.Type().String())) d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } d.ignoreNextType = false // Display length and capacity if the built-in len and cap functions // work with the value's kind and the len/cap itself is non-zero. valueLen, valueCap := 0, 0 switch v.Kind() { case reflect.Array, reflect.Slice, reflect.Chan: valueLen, valueCap = v.Len(), v.Cap() case reflect.Map, reflect.String: valueLen = v.Len() } if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { d.w.Write(openParenBytes) if valueLen != 0 { d.w.Write(lenEqualsBytes) printInt(d.w, int64(valueLen), 10) } if !d.cs.DisableCapacities && valueCap != 0 { if valueLen != 0 { d.w.Write(spaceBytes) } d.w.Write(capEqualsBytes) printInt(d.w, int64(valueCap), 10) } d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } // Call Stringer/error interfaces if they exist and the handle methods flag // is enabled if !d.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(d.cs, d.w, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(d.w, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(d.w, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(d.w, v.Uint(), 10) case reflect.Float32: printFloat(d.w, v.Float(), 32) case reflect.Float64: printFloat(d.w, v.Float(), 64) case reflect.Complex64: printComplex(d.w, v.Complex(), 32) case reflect.Complex128: printComplex(d.w, v.Complex(), 64) case reflect.Slice: if v.IsNil() { d.w.Write(nilAngleBytes) break } fallthrough case reflect.Array: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { d.dumpSlice(v) } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.String: d.w.Write([]byte(strconv.Quote(v.String()))) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { d.w.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { d.w.Write(nilAngleBytes) break } d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { numEntries := v.Len() keys := v.MapKeys() if d.cs.SortKeys { sortValues(keys, d.cs) } for i, key := range keys { d.dump(d.unpackValue(key)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.MapIndex(key))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Struct: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { vt := v.Type() numFields := v.NumField() for i := 0; i < numFields; i++ { d.indent() vtf := vt.Field(i) d.w.Write([]byte(vtf.Name)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.Field(i))) if i < (numFields - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(d.w, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(d.w, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it in case any new // types are added. default: if v.CanInterface() { fmt.Fprintf(d.w, "%v", v.Interface()) } else { fmt.Fprintf(d.w, "%v", v.String()) } } } // fdump is a helper function to consolidate the logic from the various public // methods which take varying writers and config states. func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { for _, arg := range a { if arg == nil { w.Write(interfaceBytes) w.Write(spaceBytes) w.Write(nilAngleBytes) w.Write(newlineBytes) continue } d := dumpState{w: w, cs: cs} d.pointers = make(map[uintptr]int) d.dump(reflect.ValueOf(arg)) d.w.Write(newlineBytes) } } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func Fdump(w io.Writer, a ...interface{}) { fdump(&Config, w, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(&Config, &buf, a...) return buf.String() } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by an exported package global, spew.Config. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func Dump(a ...interface{}) { fdump(&Config, os.Stdout, a...) } ����������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/doc.go�������0000644�0610621�0607500�00000017731�13172163422�033210� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * Copyright (c) 2013 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Package spew implements a deep pretty printer for Go data structures to aid in debugging. A quick overview of the additional features spew provides over the built-in printing facilities for Go data types are as follows: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output (only when using Dump style) There are two different approaches spew allows for dumping Go data structures: * Dump style which prints with newlines, customizable indentation, and additional debug information such as types and all pointer addresses used to indirect to the final value * A custom Formatter interface that integrates cleanly with the standard fmt package and replaces %v, %+v, %#v, and %#+v to provide inline printing similar to the default %v while providing the additional functionality outlined above and passing unsupported format verbs such as %x and %q along to fmt Quick Start This section demonstrates how to quickly get started with spew. See the sections below for further details on formatting and configuration options. To dump a variable with full newlines, indentation, type, and pointer information use Dump, Fdump, or Sdump: spew.Dump(myVar1, myVar2, ...) spew.Fdump(someWriter, myVar1, myVar2, ...) str := spew.Sdump(myVar1, myVar2, ...) Alternatively, if you would prefer to use format strings with a compacted inline printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses): spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) Configuration Options Configuration of spew is handled by fields in the ConfigState type. For convenience, all of the top-level functions use a global state available via the spew.Config global. It is also possible to create a ConfigState instance that provides methods equivalent to the top-level functions. This allows concurrent configuration options. See the ConfigState documentation for more details. The following configuration options are available: * Indent String to use for each indentation level for Dump functions. It is a single space by default. A popular alternative is "\t". * MaxDepth Maximum number of levels to descend into nested data structures. There is no limit by default. * DisableMethods Disables invocation of error and Stringer interface methods. Method invocation is enabled by default. * DisablePointerMethods Disables invocation of error and Stringer interface methods on types which only accept pointer receivers from non-pointer variables. Pointer method invocation is enabled by default. * ContinueOnMethod Enables recursion into types after invoking error and Stringer interface methods. Recursion after method invocation is disabled by default. * SortKeys Specifies map keys should be sorted before being printed. Use this to have a more deterministic, diffable output. Note that only native types (bool, int, uint, floats, uintptr and string) and types which implement error or Stringer interfaces are supported with other types sorted according to the reflect.Value.String() output which guarantees display stability. Natural map order is used by default. * SpewKeys Specifies that, as a last resort attempt, map keys should be spewed to strings and sorted by those strings. This is only considered if SortKeys is true. Dump Usage Simply call spew.Dump with a list of variables you want to dump: spew.Dump(myVar1, myVar2, ...) You may also call spew.Fdump if you would prefer to output to an arbitrary io.Writer. For example, to dump to standard error: spew.Fdump(os.Stderr, myVar1, myVar2, ...) A third option is to call spew.Sdump to get the formatted output as a string: str := spew.Sdump(myVar1, myVar2, ...) Sample Dump Output See the Dump example for details on the setup of the types and variables being shown here. (main.Foo) { unexportedField: (*main.Bar)(0xf84002e210)({ flag: (main.Flag) flagTwo, data: (uintptr) <nil> }), ExportedField: (map[interface {}]interface {}) (len=1) { (string) (len=3) "one": (bool) true } } Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C command as shown. ([]uint8) (len=32 cap=32) { 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| 00000020 31 32 |12| } Custom Formatter Spew provides a custom formatter that implements the fmt.Formatter interface so that it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Custom Formatter Usage The simplest way to make use of the spew custom formatter is to call one of the convenience functions such as spew.Printf, spew.Println, or spew.Printf. The functions have syntax you are most likely already familiar with: spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) spew.Println(myVar, myVar2) spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) See the Index for the full list convenience functions. Sample Formatter Output Double pointer to a uint8: %v: <**>5 %+v: <**>(0xf8400420d0->0xf8400420c8)5 %#v: (**uint8)5 %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 Pointer to circular struct with a uint8 field and a pointer to itself: %v: <*>{1 <*><shown>} %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>} %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>} %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>} See the Printf example for details on the setup of variables being shown here. Errors Since it is possible for custom Stringer/error interfaces to panic, spew detects them and handles them internally by printing the panic information inline with the output. Since spew is intended to provide deep pretty printing capabilities on structures, it intentionally does not return any errors. */ package spew ���������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/config.go����0000644�0610621�0607500�00000031045�13172163422�033702� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * Copyright (c) 2013 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "os" ) // ConfigState houses the configuration options used by spew to format and // display values. There is a global instance, Config, that is used to control // all top-level Formatter and Dump functionality. Each ConfigState instance // provides methods equivalent to the top-level functions. // // The zero value for ConfigState provides no indentation. You would typically // want to set it to a space or a tab. // // Alternatively, you can use NewDefaultConfig to get a ConfigState instance // with default settings. See the documentation of NewDefaultConfig for default // values. type ConfigState struct { // Indent specifies the string to use for each indentation level. The // global config instance that all top-level functions use set this to a // single space by default. If you would like more indentation, you might // set this to a tab with "\t" or perhaps two spaces with " ". Indent string // MaxDepth controls the maximum number of levels to descend into nested // data structures. The default, 0, means there is no limit. // // NOTE: Circular data structures are properly detected, so it is not // necessary to set this value unless you specifically want to limit deeply // nested data structures. MaxDepth int // DisableMethods specifies whether or not error and Stringer interfaces are // invoked for types that implement them. DisableMethods bool // DisablePointerMethods specifies whether or not to check for and invoke // error and Stringer interfaces on types which only accept a pointer // receiver when the current type is not a pointer. // // NOTE: This might be an unsafe action since calling one of these methods // with a pointer receiver could technically mutate the value, however, // in practice, types which choose to satisify an error or Stringer // interface with a pointer receiver should not be mutating their state // inside these interface methods. As a result, this option relies on // access to the unsafe package, so it will not have any effect when // running in environments without access to the unsafe package such as // Google App Engine or with the "safe" build tag specified. DisablePointerMethods bool // DisablePointerAddresses specifies whether to disable the printing of // pointer addresses. This is useful when diffing data structures in tests. DisablePointerAddresses bool // DisableCapacities specifies whether to disable the printing of capacities // for arrays, slices, maps and channels. This is useful when diffing // data structures in tests. DisableCapacities bool // ContinueOnMethod specifies whether or not recursion should continue once // a custom error or Stringer interface is invoked. The default, false, // means it will print the results of invoking the custom error or Stringer // interface and return immediately instead of continuing to recurse into // the internals of the data type. // // NOTE: This flag does not have any effect if method invocation is disabled // via the DisableMethods or DisablePointerMethods options. ContinueOnMethod bool // SortKeys specifies map keys should be sorted before being printed. Use // this to have a more deterministic, diffable output. Note that only // native types (bool, int, uint, floats, uintptr and string) and types // that support the error or Stringer interfaces (if methods are // enabled) are supported, with other types sorted according to the // reflect.Value.String() output which guarantees display stability. SortKeys bool // SpewKeys specifies that, as a last resort attempt, map keys should // be spewed to strings and sorted by those strings. This is only // considered if SortKeys is true. SpewKeys bool } // Config is the active configuration of the top-level functions. // The configuration can be changed by modifying the contents of spew.Config. var Config = ConfigState{Indent: " "} // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the formatted string as a value that satisfies error. See NewFormatter // for formatting details. // // This function is shorthand for the following syntax: // // fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { return fmt.Errorf(format, c.convertArgs(a)...) } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprint(w, c.convertArgs(a)...) } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { return fmt.Fprintf(w, format, c.convertArgs(a)...) } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it // passed with a Formatter interface returned by c.NewFormatter. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprintln(w, c.convertArgs(a)...) } // Print is a wrapper for fmt.Print that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Print(a ...interface{}) (n int, err error) { return fmt.Print(c.convertArgs(a)...) } // Printf is a wrapper for fmt.Printf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, c.convertArgs(a)...) } // Println is a wrapper for fmt.Println that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Println(a ...interface{}) (n int, err error) { return fmt.Println(c.convertArgs(a)...) } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprint(a ...interface{}) string { return fmt.Sprint(c.convertArgs(a)...) } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, c.convertArgs(a)...) } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it // were passed with a Formatter interface returned by c.NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprintln(a ...interface{}) string { return fmt.Sprintln(c.convertArgs(a)...) } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as c.Printf, c.Println, or c.Printf. */ func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { return newFormatter(c, v) } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { fdump(c, w, a...) } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by modifying the public members of c. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func (c *ConfigState) Dump(a ...interface{}) { fdump(c, os.Stdout, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func (c *ConfigState) Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(c, &buf, a...) return buf.String() } // convertArgs accepts a slice of arguments and returns a slice of the same // length with each argument converted to a spew Formatter interface using // the ConfigState associated with s. func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { formatters = make([]interface{}, len(args)) for index, arg := range args { formatters[index] = newFormatter(c, arg) } return formatters } // NewDefaultConfig returns a ConfigState with the following default settings. // // Indent: " " // MaxDepth: 0 // DisableMethods: false // DisablePointerMethods: false // ContinueOnMethod: false // SortKeys: false func NewDefaultConfig() *ConfigState { return &ConfigState{Indent: " "} } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/common.go����0000644�0610621�0607500�00000024167�13172163422�033734� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * Copyright (c) 2013 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "reflect" "sort" "strconv" ) // Some constants in the form of bytes to avoid string overhead. This mirrors // the technique used in the fmt package. var ( panicBytes = []byte("(PANIC=") plusBytes = []byte("+") iBytes = []byte("i") trueBytes = []byte("true") falseBytes = []byte("false") interfaceBytes = []byte("(interface {})") commaNewlineBytes = []byte(",\n") newlineBytes = []byte("\n") openBraceBytes = []byte("{") openBraceNewlineBytes = []byte("{\n") closeBraceBytes = []byte("}") asteriskBytes = []byte("*") colonBytes = []byte(":") colonSpaceBytes = []byte(": ") openParenBytes = []byte("(") closeParenBytes = []byte(")") spaceBytes = []byte(" ") pointerChainBytes = []byte("->") nilAngleBytes = []byte("<nil>") maxNewlineBytes = []byte("<max depth reached>\n") maxShortBytes = []byte("<max>") circularBytes = []byte("<already shown>") circularShortBytes = []byte("<shown>") invalidAngleBytes = []byte("<invalid>") openBracketBytes = []byte("[") closeBracketBytes = []byte("]") percentBytes = []byte("%") precisionBytes = []byte(".") openAngleBytes = []byte("<") closeAngleBytes = []byte(">") openMapBytes = []byte("map[") closeMapBytes = []byte("]") lenEqualsBytes = []byte("len=") capEqualsBytes = []byte("cap=") ) // hexDigits is used to map a decimal value to a hex digit. var hexDigits = "0123456789abcdef" // catchPanic handles any panics that might occur during the handleMethods // calls. func catchPanic(w io.Writer, v reflect.Value) { if err := recover(); err != nil { w.Write(panicBytes) fmt.Fprintf(w, "%v", err) w.Write(closeParenBytes) } } // handleMethods attempts to call the Error and String methods on the underlying // type the passed reflect.Value represents and outputes the result to Writer w. // // It handles panics in any called methods by catching and displaying the error // as the formatted value. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { // We need an interface to check if the type implements the error or // Stringer interface. However, the reflect package won't give us an // interface on certain things like unexported struct fields in order // to enforce visibility rules. We use unsafe, when it's available, // to bypass these restrictions since this package does not mutate the // values. if !v.CanInterface() { if UnsafeDisabled { return false } v = unsafeReflectValue(v) } // Choose whether or not to do error and Stringer interface lookups against // the base type or a pointer to the base type depending on settings. // Technically calling one of these methods with a pointer receiver can // mutate the value, however, types which choose to satisify an error or // Stringer interface with a pointer receiver should not be mutating their // state inside these interface methods. if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { v = unsafeReflectValue(v) } if v.CanAddr() { v = v.Addr() } // Is it an error or Stringer? switch iface := v.Interface().(type) { case error: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.Error())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.Error())) return true case fmt.Stringer: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.String())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.String())) return true } return false } // printBool outputs a boolean value as true or false to Writer w. func printBool(w io.Writer, val bool) { if val { w.Write(trueBytes) } else { w.Write(falseBytes) } } // printInt outputs a signed integer value to Writer w. func printInt(w io.Writer, val int64, base int) { w.Write([]byte(strconv.FormatInt(val, base))) } // printUint outputs an unsigned integer value to Writer w. func printUint(w io.Writer, val uint64, base int) { w.Write([]byte(strconv.FormatUint(val, base))) } // printFloat outputs a floating point value using the specified precision, // which is expected to be 32 or 64bit, to Writer w. func printFloat(w io.Writer, val float64, precision int) { w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) } // printComplex outputs a complex value using the specified float precision // for the real and imaginary parts to Writer w. func printComplex(w io.Writer, c complex128, floatPrecision int) { r := real(c) w.Write(openParenBytes) w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) i := imag(c) if i >= 0 { w.Write(plusBytes) } w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) w.Write(iBytes) w.Write(closeParenBytes) } // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' // prefix to Writer w. func printHexPtr(w io.Writer, p uintptr) { // Null pointer. num := uint64(p) if num == 0 { w.Write(nilAngleBytes) return } // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix buf := make([]byte, 18) // It's simpler to construct the hex string right to left. base := uint64(16) i := len(buf) - 1 for num >= base { buf[i] = hexDigits[num%base] num /= base i-- } buf[i] = hexDigits[num] // Add '0x' prefix. i-- buf[i] = 'x' i-- buf[i] = '0' // Strip unused leading bytes. buf = buf[i:] w.Write(buf) } // valuesSorter implements sort.Interface to allow a slice of reflect.Value // elements to be sorted. type valuesSorter struct { values []reflect.Value strings []string // either nil or same len and values cs *ConfigState } // newValuesSorter initializes a valuesSorter instance, which holds a set of // surrogate keys on which the data should be sorted. It uses flags in // ConfigState to decide if and how to populate those surrogate keys. func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { vs := &valuesSorter{values: values, cs: cs} if canSortSimply(vs.values[0].Kind()) { return vs } if !cs.DisableMethods { vs.strings = make([]string, len(values)) for i := range vs.values { b := bytes.Buffer{} if !handleMethods(cs, &b, vs.values[i]) { vs.strings = nil break } vs.strings[i] = b.String() } } if vs.strings == nil && cs.SpewKeys { vs.strings = make([]string, len(values)) for i := range vs.values { vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) } } return vs } // canSortSimply tests whether a reflect.Kind is a primitive that can be sorted // directly, or whether it should be considered for sorting by surrogate keys // (if the ConfigState allows it). func canSortSimply(kind reflect.Kind) bool { // This switch parallels valueSortLess, except for the default case. switch kind { case reflect.Bool: return true case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return true case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return true case reflect.Float32, reflect.Float64: return true case reflect.String: return true case reflect.Uintptr: return true case reflect.Array: return true } return false } // Len returns the number of values in the slice. It is part of the // sort.Interface implementation. func (s *valuesSorter) Len() int { return len(s.values) } // Swap swaps the values at the passed indices. It is part of the // sort.Interface implementation. func (s *valuesSorter) Swap(i, j int) { s.values[i], s.values[j] = s.values[j], s.values[i] if s.strings != nil { s.strings[i], s.strings[j] = s.strings[j], s.strings[i] } } // valueSortLess returns whether the first value should sort before the second // value. It is used by valueSorter.Less as part of the sort.Interface // implementation. func valueSortLess(a, b reflect.Value) bool { switch a.Kind() { case reflect.Bool: return !a.Bool() && b.Bool() case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return a.Int() < b.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return a.Uint() < b.Uint() case reflect.Float32, reflect.Float64: return a.Float() < b.Float() case reflect.String: return a.String() < b.String() case reflect.Uintptr: return a.Uint() < b.Uint() case reflect.Array: // Compare the contents of both arrays. l := a.Len() for i := 0; i < l; i++ { av := a.Index(i) bv := b.Index(i) if av.Interface() == bv.Interface() { continue } return valueSortLess(av, bv) } } return a.String() < b.String() } // Less returns whether the value at index i should sort before the // value at index j. It is part of the sort.Interface implementation. func (s *valuesSorter) Less(i, j int) bool { if s.strings == nil { return valueSortLess(s.values[i], s.values[j]) } return s.strings[i] < s.strings[j] } // sortValues is a sort function that handles both native types and any type that // can be converted to error or Stringer. Other inputs are sorted according to // their Value.String() value to ensure display stability. func sortValues(values []reflect.Value, cs *ConfigState) { if len(values) == 0 { return } sort.Sort(newValuesSorter(values, cs)) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go0000644�0610621�0607500�00000003301�13172163422�034567� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2015 Dave Collins <dave@davec.name> // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled // when the code is running on Google App Engine, compiled by GopherJS, or // "-tags safe" is added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. // +build js appengine safe disableunsafe package spew import "reflect" const ( // UnsafeDisabled is a build-time constant which specifies whether or // not access to the unsafe package is available. UnsafeDisabled = true ) // unsafeReflectValue typically converts the passed reflect.Value into a one // that bypasses the typical safety restrictions preventing access to // unaddressable and unexported data. However, doing this relies on access to // the unsafe package. This is a stub version which simply returns the passed // reflect.Value when the unsafe package is not available. func unsafeReflectValue(v reflect.Value) reflect.Value { return v } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypass.go����0000644�0610621�0607500�00000013230�13172163422�033732� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2015 Dave Collins <dave@davec.name> // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled // when the code is not running on Google App Engine, compiled by GopherJS, and // "-tags safe" is not added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. // +build !js,!appengine,!safe,!disableunsafe package spew import ( "reflect" "unsafe" ) const ( // UnsafeDisabled is a build-time constant which specifies whether or // not access to the unsafe package is available. UnsafeDisabled = false // ptrSize is the size of a pointer on the current arch. ptrSize = unsafe.Sizeof((*byte)(nil)) ) var ( // offsetPtr, offsetScalar, and offsetFlag are the offsets for the // internal reflect.Value fields. These values are valid before golang // commit ecccf07e7f9d which changed the format. The are also valid // after commit 82f48826c6c7 which changed the format again to mirror // the original format. Code in the init function updates these offsets // as necessary. offsetPtr = uintptr(ptrSize) offsetScalar = uintptr(0) offsetFlag = uintptr(ptrSize * 2) // flagKindWidth and flagKindShift indicate various bits that the // reflect package uses internally to track kind information. // // flagRO indicates whether or not the value field of a reflect.Value is // read-only. // // flagIndir indicates whether the value field of a reflect.Value is // the actual data or a pointer to the data. // // These values are valid before golang commit 90a7c3c86944 which // changed their positions. Code in the init function updates these // flags as necessary. flagKindWidth = uintptr(5) flagKindShift = uintptr(flagKindWidth - 1) flagRO = uintptr(1 << 0) flagIndir = uintptr(1 << 1) ) func init() { // Older versions of reflect.Value stored small integers directly in the // ptr field (which is named val in the older versions). Versions // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named // scalar for this purpose which unfortunately came before the flag // field, so the offset of the flag field is different for those // versions. // // This code constructs a new reflect.Value from a known small integer // and checks if the size of the reflect.Value struct indicates it has // the scalar field. When it does, the offsets are updated accordingly. vv := reflect.ValueOf(0xf00) if unsafe.Sizeof(vv) == (ptrSize * 4) { offsetScalar = ptrSize * 2 offsetFlag = ptrSize * 3 } // Commit 90a7c3c86944 changed the flag positions such that the low // order bits are the kind. This code extracts the kind from the flags // field and ensures it's the correct type. When it's not, the flag // order has been changed to the newer format, so the flags are updated // accordingly. upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag) upfv := *(*uintptr)(upf) flagKindMask := uintptr((1<<flagKindWidth - 1) << flagKindShift) if (upfv&flagKindMask)>>flagKindShift != uintptr(reflect.Int) { flagKindShift = 0 flagRO = 1 << 5 flagIndir = 1 << 6 // Commit adf9b30e5594 modified the flags to separate the // flagRO flag into two bits which specifies whether or not the // field is embedded. This causes flagIndir to move over a bit // and means that flagRO is the combination of either of the // original flagRO bit and the new bit. // // This code detects the change by extracting what used to be // the indirect bit to ensure it's set. When it's not, the flag // order has been changed to the newer format, so the flags are // updated accordingly. if upfv&flagIndir == 0 { flagRO = 3 << 5 flagIndir = 1 << 7 } } } // unsafeReflectValue converts the passed reflect.Value into a one that bypasses // the typical safety restrictions preventing access to unaddressable and // unexported data. It works by digging the raw pointer to the underlying // value out of the protected value and generating a new unprotected (unsafe) // reflect.Value to it. // // This allows us to check for implementations of the Stringer and error // interfaces to be used for pretty printing ordinarily unaddressable and // inaccessible values such as unexported struct fields. func unsafeReflectValue(v reflect.Value) (rv reflect.Value) { indirects := 1 vt := v.Type() upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) if rvf&flagIndir != 0 { vt = reflect.PtrTo(v.Type()) indirects++ } else if offsetScalar != 0 { // The value is in the scalar field when it's not one of the // reference types. switch vt.Kind() { case reflect.Uintptr: case reflect.Chan: case reflect.Func: case reflect.Map: case reflect.Ptr: case reflect.UnsafePointer: default: upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetScalar) } } pv := reflect.NewAt(vt, upv) rv = pv for i := 0; i < indirects; i++ { rv = rv.Elem() } return rv } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/LICENSE�����������0000644�0610621�0607500�00000001373�13172163422�032136� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ISC License Copyright (c) 2012-2013 Dave Collins <dave@davec.name> Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/suite/����������������������������������������������0000755�0610621�0607500�00000000000�13172163422�023740� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/suite/suite_test.go���������������������������������0000644�0610621�0607500�00000020725�13172163422�026465� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package suite import ( "errors" "io/ioutil" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // SuiteRequireTwice is intended to test the usage of suite.Require in two // different tests type SuiteRequireTwice struct{ Suite } // TestSuiteRequireTwice checks for regressions of issue #149 where // suite.requirements was not initialised in suite.SetT() // A regression would result on these tests panicking rather than failing. func TestSuiteRequireTwice(t *testing.T) { ok := testing.RunTests( allTestsFilter, []testing.InternalTest{{ Name: "TestSuiteRequireTwice", F: func(t *testing.T) { suite := new(SuiteRequireTwice) Run(t, suite) }, }}, ) assert.Equal(t, false, ok) } func (s *SuiteRequireTwice) TestRequireOne() { r := s.Require() r.Equal(1, 2) } func (s *SuiteRequireTwice) TestRequireTwo() { r := s.Require() r.Equal(1, 2) } // This suite is intended to store values to make sure that only // testing-suite-related methods are run. It's also a fully // functional example of a testing suite, using setup/teardown methods // and a helper method that is ignored by testify. To make this look // more like a real world example, all tests in the suite perform some // type of assertion. type SuiteTester struct { // Include our basic suite logic. Suite // Keep counts of how many times each method is run. SetupSuiteRunCount int TearDownSuiteRunCount int SetupTestRunCount int TearDownTestRunCount int TestOneRunCount int TestTwoRunCount int NonTestMethodRunCount int SuiteNameBefore []string TestNameBefore []string SuiteNameAfter []string TestNameAfter []string TimeBefore []time.Time TimeAfter []time.Time } type SuiteSkipTester struct { // Include our basic suite logic. Suite // Keep counts of how many times each method is run. SetupSuiteRunCount int TearDownSuiteRunCount int } // The SetupSuite method will be run by testify once, at the very // start of the testing suite, before any tests are run. func (suite *SuiteTester) SetupSuite() { suite.SetupSuiteRunCount++ } func (suite *SuiteTester) BeforeTest(suiteName, testName string) { suite.SuiteNameBefore = append(suite.SuiteNameBefore, suiteName) suite.TestNameBefore = append(suite.TestNameBefore, testName) suite.TimeBefore = append(suite.TimeBefore, time.Now()) } func (suite *SuiteTester) AfterTest(suiteName, testName string) { suite.SuiteNameAfter = append(suite.SuiteNameAfter, suiteName) suite.TestNameAfter = append(suite.TestNameAfter, testName) suite.TimeAfter = append(suite.TimeAfter, time.Now()) } func (suite *SuiteSkipTester) SetupSuite() { suite.SetupSuiteRunCount++ suite.T().Skip() } // The TearDownSuite method will be run by testify once, at the very // end of the testing suite, after all tests have been run. func (suite *SuiteTester) TearDownSuite() { suite.TearDownSuiteRunCount++ } func (suite *SuiteSkipTester) TearDownSuite() { suite.TearDownSuiteRunCount++ } // The SetupTest method will be run before every test in the suite. func (suite *SuiteTester) SetupTest() { suite.SetupTestRunCount++ } // The TearDownTest method will be run after every test in the suite. func (suite *SuiteTester) TearDownTest() { suite.TearDownTestRunCount++ } // Every method in a testing suite that begins with "Test" will be run // as a test. TestOne is an example of a test. For the purposes of // this example, we've included assertions in the tests, since most // tests will issue assertions. func (suite *SuiteTester) TestOne() { beforeCount := suite.TestOneRunCount suite.TestOneRunCount++ assert.Equal(suite.T(), suite.TestOneRunCount, beforeCount+1) suite.Equal(suite.TestOneRunCount, beforeCount+1) } // TestTwo is another example of a test. func (suite *SuiteTester) TestTwo() { beforeCount := suite.TestTwoRunCount suite.TestTwoRunCount++ assert.NotEqual(suite.T(), suite.TestTwoRunCount, beforeCount) suite.NotEqual(suite.TestTwoRunCount, beforeCount) } func (suite *SuiteTester) TestSkip() { suite.T().Skip() } // NonTestMethod does not begin with "Test", so it will not be run by // testify as a test in the suite. This is useful for creating helper // methods for your tests. func (suite *SuiteTester) NonTestMethod() { suite.NonTestMethodRunCount++ } // TestRunSuite will be run by the 'go test' command, so within it, we // can run our suite using the Run(*testing.T, TestingSuite) function. func TestRunSuite(t *testing.T) { suiteTester := new(SuiteTester) Run(t, suiteTester) // Normally, the test would end here. The following are simply // some assertions to ensure that the Run function is working as // intended - they are not part of the example. // The suite was only run once, so the SetupSuite and TearDownSuite // methods should have each been run only once. assert.Equal(t, suiteTester.SetupSuiteRunCount, 1) assert.Equal(t, suiteTester.TearDownSuiteRunCount, 1) assert.Equal(t, len(suiteTester.SuiteNameAfter), 3) assert.Equal(t, len(suiteTester.SuiteNameBefore), 3) assert.Equal(t, len(suiteTester.TestNameAfter), 3) assert.Equal(t, len(suiteTester.TestNameBefore), 3) assert.Contains(t, suiteTester.TestNameAfter, "TestOne") assert.Contains(t, suiteTester.TestNameAfter, "TestTwo") assert.Contains(t, suiteTester.TestNameAfter, "TestSkip") assert.Contains(t, suiteTester.TestNameBefore, "TestOne") assert.Contains(t, suiteTester.TestNameBefore, "TestTwo") assert.Contains(t, suiteTester.TestNameBefore, "TestSkip") for _, suiteName := range suiteTester.SuiteNameAfter { assert.Equal(t, "SuiteTester", suiteName) } for _, suiteName := range suiteTester.SuiteNameBefore { assert.Equal(t, "SuiteTester", suiteName) } for _, when := range suiteTester.TimeAfter { assert.False(t, when.IsZero()) } for _, when := range suiteTester.TimeBefore { assert.False(t, when.IsZero()) } // There are three test methods (TestOne, TestTwo, and TestSkip), so // the SetupTest and TearDownTest methods (which should be run once for // each test) should have been run three times. assert.Equal(t, suiteTester.SetupTestRunCount, 3) assert.Equal(t, suiteTester.TearDownTestRunCount, 3) // Each test should have been run once. assert.Equal(t, suiteTester.TestOneRunCount, 1) assert.Equal(t, suiteTester.TestTwoRunCount, 1) // Methods that don't match the test method identifier shouldn't // have been run at all. assert.Equal(t, suiteTester.NonTestMethodRunCount, 0) suiteSkipTester := new(SuiteSkipTester) Run(t, suiteSkipTester) // The suite was only run once, so the SetupSuite and TearDownSuite // methods should have each been run only once, even though SetupSuite // called Skip() assert.Equal(t, suiteSkipTester.SetupSuiteRunCount, 1) assert.Equal(t, suiteSkipTester.TearDownSuiteRunCount, 1) } func TestSuiteGetters(t *testing.T) { suite := new(SuiteTester) suite.SetT(t) assert.NotNil(t, suite.Assert()) assert.Equal(t, suite.Assertions, suite.Assert()) assert.NotNil(t, suite.Require()) assert.Equal(t, suite.require, suite.Require()) } type SuiteLoggingTester struct { Suite } func (s *SuiteLoggingTester) TestLoggingPass() { s.T().Log("TESTLOGPASS") } func (s *SuiteLoggingTester) TestLoggingFail() { s.T().Log("TESTLOGFAIL") assert.NotNil(s.T(), nil) // expected to fail } type StdoutCapture struct { oldStdout *os.File readPipe *os.File } func (sc *StdoutCapture) StartCapture() { sc.oldStdout = os.Stdout sc.readPipe, os.Stdout, _ = os.Pipe() } func (sc *StdoutCapture) StopCapture() (string, error) { if sc.oldStdout == nil || sc.readPipe == nil { return "", errors.New("StartCapture not called before StopCapture") } os.Stdout.Close() os.Stdout = sc.oldStdout bytes, err := ioutil.ReadAll(sc.readPipe) if err != nil { return "", err } return string(bytes), nil } func TestSuiteLogging(t *testing.T) { suiteLoggingTester := new(SuiteLoggingTester) capture := StdoutCapture{} internalTest := testing.InternalTest{ Name: "SomeTest", F: func(subT *testing.T) { Run(subT, suiteLoggingTester) }, } capture.StartCapture() testing.RunTests(allTestsFilter, []testing.InternalTest{internalTest}) output, err := capture.StopCapture() require.NoError(t, err, "Got an error trying to capture stdout and stderr!") require.NotEmpty(t, output, "output content must not be empty") // Failed tests' output is always printed assert.Contains(t, output, "TESTLOGFAIL") if testing.Verbose() { // In verbose mode, output from successful tests is also printed assert.Contains(t, output, "TESTLOGPASS") } else { assert.NotContains(t, output, "TESTLOGPASS") } } �������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/suite/suite.go��������������������������������������0000644�0610621�0607500�00000007015�13172163422�025423� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package suite import ( "flag" "fmt" "os" "reflect" "regexp" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var allTestsFilter = func(_, _ string) (bool, error) { return true, nil } var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run") // Suite is a basic testing suite with methods for storing and // retrieving the current *testing.T context. type Suite struct { *assert.Assertions require *require.Assertions t *testing.T } // T retrieves the current *testing.T context. func (suite *Suite) T() *testing.T { return suite.t } // SetT sets the current *testing.T context. func (suite *Suite) SetT(t *testing.T) { suite.t = t suite.Assertions = assert.New(t) suite.require = require.New(t) } // Require returns a require context for suite. func (suite *Suite) Require() *require.Assertions { if suite.require == nil { suite.require = require.New(suite.T()) } return suite.require } // Assert returns an assert context for suite. Normally, you can call // `suite.NoError(expected, actual)`, but for situations where the embedded // methods are overridden (for example, you might want to override // assert.Assertions with require.Assertions), this method is provided so you // can call `suite.Assert().NoError()`. func (suite *Suite) Assert() *assert.Assertions { if suite.Assertions == nil { suite.Assertions = assert.New(suite.T()) } return suite.Assertions } // Run takes a testing suite and runs all of the tests attached // to it. func Run(t *testing.T, suite TestingSuite) { suite.SetT(t) if setupAllSuite, ok := suite.(SetupAllSuite); ok { setupAllSuite.SetupSuite() } defer func() { if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { tearDownAllSuite.TearDownSuite() } }() methodFinder := reflect.TypeOf(suite) tests := []testing.InternalTest{} for index := 0; index < methodFinder.NumMethod(); index++ { method := methodFinder.Method(index) ok, err := methodFilter(method.Name) if err != nil { fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) os.Exit(1) } if ok { test := testing.InternalTest{ Name: method.Name, F: func(t *testing.T) { parentT := suite.T() suite.SetT(t) if setupTestSuite, ok := suite.(SetupTestSuite); ok { setupTestSuite.SetupTest() } if beforeTestSuite, ok := suite.(BeforeTest); ok { beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) } defer func() { if afterTestSuite, ok := suite.(AfterTest); ok { afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name) } if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { tearDownTestSuite.TearDownTest() } suite.SetT(parentT) }() method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) }, } tests = append(tests, test) } } runTests(t, tests) } func runTests(t testing.TB, tests []testing.InternalTest) { r, ok := t.(runner) if !ok { // backwards compatibility with Go 1.6 and below if !testing.RunTests(allTestsFilter, tests) { t.Fail() } return } for _, test := range tests { r.Run(test.Name, test.F) } } // Filtering method according to set regular expression // specified command-line argument -m func methodFilter(name string) (bool, error) { if ok, _ := regexp.MatchString("^Test", name); !ok { return false, nil } return regexp.MatchString(*matchMethod, name) } type runner interface { Run(name string, f func(t *testing.T)) bool } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/suite/interfaces.go���������������������������������0000644�0610621�0607500�00000002240�13172163422�026410� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package suite import "testing" // TestingSuite can store and return the current *testing.T context // generated by 'go test'. type TestingSuite interface { T() *testing.T SetT(*testing.T) } // SetupAllSuite has a SetupSuite method, which will run before the // tests in the suite are run. type SetupAllSuite interface { SetupSuite() } // SetupTestSuite has a SetupTest method, which will run before each // test in the suite. type SetupTestSuite interface { SetupTest() } // TearDownAllSuite has a TearDownSuite method, which will run after // all the tests in the suite have been run. type TearDownAllSuite interface { TearDownSuite() } // TearDownTestSuite has a TearDownTest method, which will run after // each test in the suite. type TearDownTestSuite interface { TearDownTest() } // BeforeTest has a function to be executed right before the test // starts and receives the suite and test names as input type BeforeTest interface { BeforeTest(suiteName, testName string) } // AfterTest has a function to be executed right after the test // finishes and receives the suite and test names as input type AfterTest interface { AfterTest(suiteName, testName string) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/suite/doc.go����������������������������������������0000644�0610621�0607500�00000005172�13172163422�025041� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package suite contains logic for creating testing suite structs // and running the methods on those structs as tests. The most useful // piece of this package is that you can create setup/teardown methods // on your testing suites, which will run before/after the whole suite // or individual tests (depending on which interface(s) you // implement). // // A testing suite is usually built by first extending the built-in // suite functionality from suite.Suite in testify. Alternatively, // you could reproduce that logic on your own if you wanted (you // just need to implement the TestingSuite interface from // suite/interfaces.go). // // After that, you can implement any of the interfaces in // suite/interfaces.go to add setup/teardown functionality to your // suite, and add any methods that start with "Test" to add tests. // Methods that do not match any suite interfaces and do not begin // with "Test" will not be run by testify, and can safely be used as // helper methods. // // Once you've built your testing suite, you need to run the suite // (using suite.Run from testify) inside any function that matches the // identity that "go test" is already looking for (i.e. // func(*testing.T)). // // Regular expression to select test suites specified command-line // argument "-run". Regular expression to select the methods // of test suites specified command-line argument "-m". // Suite object has assertion methods. // // A crude example: // // Basic imports // import ( // "testing" // "github.com/stretchr/testify/assert" // "github.com/stretchr/testify/suite" // ) // // // Define the suite, and absorb the built-in basic suite // // functionality from testify - including a T() method which // // returns the current testing context // type ExampleTestSuite struct { // suite.Suite // VariableThatShouldStartAtFive int // } // // // Make sure that VariableThatShouldStartAtFive is set to five // // before each test // func (suite *ExampleTestSuite) SetupTest() { // suite.VariableThatShouldStartAtFive = 5 // } // // // All methods that begin with "Test" are run as tests within a // // suite. // func (suite *ExampleTestSuite) TestExample() { // assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) // suite.Equal(5, suite.VariableThatShouldStartAtFive) // } // // // In order for 'go test' to run this suite, we need to create // // a normal test function and pass our suite to suite.Run // func TestExampleTestSuite(t *testing.T) { // suite.Run(t, new(ExampleTestSuite)) // } package suite ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/��������������������������������������������0000755�0610621�0607500�00000000000�13172163422�024263� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/requirements_test.go������������������������0000644�0610621�0607500�00000016262�13172163422�030403� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package require import ( "errors" "testing" "time" ) // AssertionTesterInterface defines an interface to be used for testing assertion methods type AssertionTesterInterface interface { TestMethod() } // AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface type AssertionTesterConformingObject struct { } func (a *AssertionTesterConformingObject) TestMethod() { } // AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface type AssertionTesterNonConformingObject struct { } type MockT struct { Failed bool } func (t *MockT) FailNow() { t.Failed = true } func (t *MockT) Errorf(format string, args ...interface{}) { _, _ = format, args } func TestImplements(t *testing.T) { Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) mockT := new(MockT) Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestIsType(t *testing.T) { IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) mockT := new(MockT) IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestEqual(t *testing.T) { Equal(t, 1, 1) mockT := new(MockT) Equal(mockT, 1, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestNotEqual(t *testing.T) { NotEqual(t, 1, 2) mockT := new(MockT) NotEqual(mockT, 2, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestExactly(t *testing.T) { a := float32(1) b := float32(1) c := float64(1) Exactly(t, a, b) mockT := new(MockT) Exactly(mockT, a, c) if !mockT.Failed { t.Error("Check should fail") } } func TestNotNil(t *testing.T) { NotNil(t, new(AssertionTesterConformingObject)) mockT := new(MockT) NotNil(mockT, nil) if !mockT.Failed { t.Error("Check should fail") } } func TestNil(t *testing.T) { Nil(t, nil) mockT := new(MockT) Nil(mockT, new(AssertionTesterConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestTrue(t *testing.T) { True(t, true) mockT := new(MockT) True(mockT, false) if !mockT.Failed { t.Error("Check should fail") } } func TestFalse(t *testing.T) { False(t, false) mockT := new(MockT) False(mockT, true) if !mockT.Failed { t.Error("Check should fail") } } func TestContains(t *testing.T) { Contains(t, "Hello World", "Hello") mockT := new(MockT) Contains(mockT, "Hello World", "Salut") if !mockT.Failed { t.Error("Check should fail") } } func TestNotContains(t *testing.T) { NotContains(t, "Hello World", "Hello!") mockT := new(MockT) NotContains(mockT, "Hello World", "Hello") if !mockT.Failed { t.Error("Check should fail") } } func TestPanics(t *testing.T) { Panics(t, func() { panic("Panic!") }) mockT := new(MockT) Panics(mockT, func() {}) if !mockT.Failed { t.Error("Check should fail") } } func TestNotPanics(t *testing.T) { NotPanics(t, func() {}) mockT := new(MockT) NotPanics(mockT, func() { panic("Panic!") }) if !mockT.Failed { t.Error("Check should fail") } } func TestNoError(t *testing.T) { NoError(t, nil) mockT := new(MockT) NoError(mockT, errors.New("some error")) if !mockT.Failed { t.Error("Check should fail") } } func TestError(t *testing.T) { Error(t, errors.New("some error")) mockT := new(MockT) Error(mockT, nil) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualError(t *testing.T) { EqualError(t, errors.New("some error"), "some error") mockT := new(MockT) EqualError(mockT, errors.New("some error"), "Not some error") if !mockT.Failed { t.Error("Check should fail") } } func TestEmpty(t *testing.T) { Empty(t, "") mockT := new(MockT) Empty(mockT, "x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotEmpty(t *testing.T) { NotEmpty(t, "x") mockT := new(MockT) NotEmpty(mockT, "") if !mockT.Failed { t.Error("Check should fail") } } func TestWithinDuration(t *testing.T) { a := time.Now() b := a.Add(10 * time.Second) WithinDuration(t, a, b, 15*time.Second) mockT := new(MockT) WithinDuration(mockT, a, b, 5*time.Second) if !mockT.Failed { t.Error("Check should fail") } } func TestInDelta(t *testing.T) { InDelta(t, 1.001, 1, 0.01) mockT := new(MockT) InDelta(mockT, 1, 2, 0.5) if !mockT.Failed { t.Error("Check should fail") } } func TestZero(t *testing.T) { Zero(t, "") mockT := new(MockT) Zero(mockT, "x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotZero(t *testing.T) { NotZero(t, "x") mockT := new(MockT) NotZero(mockT, "") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_EqualSONString(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEq_EquivalentButNotEqual(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { mockT := new(MockT) JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") if mockT.Failed { t.Error("Check should pass") } } func TestJSONEq_Array(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_HashesNotEquivalent(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_ActualIsNotJSON(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `{"foo": "bar"}`, "Not JSON") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { mockT := new(MockT) JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { mockT := new(MockT) JSONEq(mockT, "Not JSON", "Not JSON") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) if !mockT.Failed { t.Error("Check should fail") } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/requirements.go�����������������������������0000644�0610621�0607500�00000000414�13172163422�027334� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package require // TestingT is an interface wrapper around *testing.T type TestingT interface { Errorf(format string, args ...interface{}) FailNow() } //go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl -include-format-funcs ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/require_forward.go.tmpl���������������������0000644�0610621�0607500�00000000177�13172163422�030772� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{.CommentWithoutT "a"}} func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) { {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/require_forward.go��������������������������0000644�0610621�0607500�00000072505�13172163422�030023� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package require import ( assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { Condition(a.t, comp, msgAndArgs...) } // Conditionf uses a Comparison to assert a complex condition. func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...interface{}) { Conditionf(a.t, comp, msg, args...) } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Contains("Hello World", "World") // a.Contains(["Hello", "World"], "World") // a.Contains({"Hello": "World"}, "Hello") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { Contains(a.t, s, contains, msgAndArgs...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Containsf("Hello World", "World", "error message %s", "formatted") // a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") // a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) { Containsf(a.t, s, contains, msg, args...) } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Empty(obj) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { Empty(a.t, object, msgAndArgs...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Emptyf(obj, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) { Emptyf(a.t, object, msg, args...) } // Equal asserts that two objects are equal. // // a.Equal(123, 123) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { Equal(a.t, expected, actual, msgAndArgs...) } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualError(err, expectedErrorString) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { EqualError(a.t, theError, errString, msgAndArgs...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) { EqualErrorf(a.t, theError, errString, msg, args...) } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValues(uint32(123), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { EqualValues(a.t, expected, actual, msgAndArgs...) } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { EqualValuesf(a.t, expected, actual, msg, args...) } // Equalf asserts that two objects are equal. // // a.Equalf(123, 123, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) { Equalf(a.t, expected, actual, msg, args...) } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Error(err) { // assert.Equal(t, expectedError, err) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { Error(a.t, err, msgAndArgs...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Errorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { Errorf(a.t, err, msg, args...) } // Exactly asserts that two objects are equal is value and type. // // a.Exactly(int32(123), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { Exactly(a.t, expected, actual, msgAndArgs...) } // Exactlyf asserts that two objects are equal is value and type. // // a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) { Exactlyf(a.t, expected, actual, msg, args...) } // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { Fail(a.t, failureMessage, msgAndArgs...) } // FailNow fails test func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { FailNow(a.t, failureMessage, msgAndArgs...) } // FailNowf fails test func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) { FailNowf(a.t, failureMessage, msg, args...) } // Failf reports a failure through func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) { Failf(a.t, failureMessage, msg, args...) } // False asserts that the specified value is false. // // a.False(myBool) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { False(a.t, value, msgAndArgs...) } // Falsef asserts that the specified value is false. // // a.Falsef(myBool, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) { Falsef(a.t, value, msg, args...) } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { HTTPBodyContains(a.t, handler, method, url, values, str) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { HTTPBodyContainsf(a.t, handler, method, url, values, str) } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { HTTPBodyNotContains(a.t, handler, method, url, values, str) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { HTTPBodyNotContainsf(a.t, handler, method, url, values, str) } // HTTPError asserts that a specified handler returns an error status code. // // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) { HTTPError(a.t, handler, method, url, values) } // HTTPErrorf asserts that a specified handler returns an error status code. // // a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values) { HTTPErrorf(a.t, handler, method, url, values) } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) { HTTPRedirect(a.t, handler, method, url, values) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values) { HTTPRedirectf(a.t, handler, method, url, values) } // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) { HTTPSuccess(a.t, handler, method, url, values) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values) { HTTPSuccessf(a.t, handler, method, url, values) } // Implements asserts that an object is implemented by the specified interface. // // a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { Implements(a.t, interfaceObject, object, msgAndArgs...) } // Implementsf asserts that an object is implemented by the specified interface. // // a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { Implementsf(a.t, interfaceObject, object, msg, args...) } // InDelta asserts that the two numerals are within delta of each other. // // a.InDelta(math.Pi, (22 / 7.0), 0.01) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { InDelta(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaSlice is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { InDeltaSlicef(a.t, expected, actual, delta, msg, args...) } // InDeltaf asserts that the two numerals are within delta of each other. // // a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { InDeltaf(a.t, expected, actual, delta, msg, args...) } // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { InEpsilonf(a.t, expected, actual, epsilon, msg, args...) } // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { IsType(a.t, expectedType, object, msgAndArgs...) } // IsTypef asserts that the specified objects are of the same type. func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) { IsTypef(a.t, expectedType, object, msg, args...) } // JSONEq asserts that two JSON strings are equivalent. // // a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { JSONEq(a.t, expected, actual, msgAndArgs...) } // JSONEqf asserts that two JSON strings are equivalent. // // a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) { JSONEqf(a.t, expected, actual, msg, args...) } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // a.Len(mySlice, 3) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { Len(a.t, object, length, msgAndArgs...) } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // a.Lenf(mySlice, 3, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) { Lenf(a.t, object, length, msg, args...) } // Nil asserts that the specified object is nil. // // a.Nil(err) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { Nil(a.t, object, msgAndArgs...) } // Nilf asserts that the specified object is nil. // // a.Nilf(err, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) { Nilf(a.t, object, msg, args...) } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoError(err) { // assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { NoError(a.t, err, msgAndArgs...) } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoErrorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) { NoErrorf(a.t, err, msg, args...) } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContains("Hello World", "Earth") // a.NotContains(["Hello", "World"], "Earth") // a.NotContains({"Hello": "World"}, "Earth") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { NotContains(a.t, s, contains, msgAndArgs...) } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") // a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") // a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) { NotContainsf(a.t, s, contains, msg, args...) } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmpty(obj) { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { NotEmpty(a.t, object, msgAndArgs...) } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmptyf(obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) { NotEmptyf(a.t, object, msg, args...) } // NotEqual asserts that the specified values are NOT equal. // // a.NotEqual(obj1, obj2) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { NotEqual(a.t, expected, actual, msgAndArgs...) } // NotEqualf asserts that the specified values are NOT equal. // // a.NotEqualf(obj1, obj2, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) { NotEqualf(a.t, expected, actual, msg, args...) } // NotNil asserts that the specified object is not nil. // // a.NotNil(err) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { NotNil(a.t, object, msgAndArgs...) } // NotNilf asserts that the specified object is not nil. // // a.NotNilf(err, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) { NotNilf(a.t, object, msg, args...) } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanics(func(){ RemainCalm() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { NotPanics(a.t, f, msgAndArgs...) } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { NotPanicsf(a.t, f, msg, args...) } // NotRegexp asserts that a specified regexp does not match a string. // // a.NotRegexp(regexp.MustCompile("starts"), "it's starting") // a.NotRegexp("^start", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { NotRegexp(a.t, rx, str, msgAndArgs...) } // NotRegexpf asserts that a specified regexp does not match a string. // // a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") // a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { NotRegexpf(a.t, rx, str, msg, args...) } // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { NotSubset(a.t, list, subset, msgAndArgs...) } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { NotSubsetf(a.t, list, subset, msg, args...) } // NotZero asserts that i is not the zero value for its type and returns the truth. func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { NotZero(a.t, i, msgAndArgs...) } // NotZerof asserts that i is not the zero value for its type and returns the truth. func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) { NotZerof(a.t, i, msg, args...) } // Panics asserts that the code inside the specified PanicTestFunc panics. // // a.Panics(func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { Panics(a.t, f, msgAndArgs...) } // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // a.PanicsWithValue("crazy error", func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { PanicsWithValue(a.t, expected, f, msgAndArgs...) } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { PanicsWithValuef(a.t, expected, f, msg, args...) } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { Panicsf(a.t, f, msg, args...) } // Regexp asserts that a specified regexp matches a string. // // a.Regexp(regexp.MustCompile("start"), "it's starting") // a.Regexp("start...$", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { Regexp(a.t, rx, str, msgAndArgs...) } // Regexpf asserts that a specified regexp matches a string. // // a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") // a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { Regexpf(a.t, rx, str, msg, args...) } // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { Subset(a.t, list, subset, msgAndArgs...) } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { Subsetf(a.t, list, subset, msg, args...) } // True asserts that the specified value is true. // // a.True(myBool) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { True(a.t, value, msgAndArgs...) } // Truef asserts that the specified value is true. // // a.Truef(myBool, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { Truef(a.t, value, msg, args...) } // WithinDuration asserts that the two times are within duration delta of each other. // // a.WithinDuration(time.Now(), time.Now(), 10*time.Second) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } // WithinDurationf asserts that the two times are within duration delta of each other. // // a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { WithinDurationf(a.t, expected, actual, delta, msg, args...) } // Zero asserts that i is the zero value for its type and returns the truth. func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { Zero(a.t, i, msgAndArgs...) } // Zerof asserts that i is the zero value for its type and returns the truth. func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) { Zerof(a.t, i, msg, args...) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/require.go.tmpl�����������������������������0000644�0610621�0607500�00000000213�13172163422�027235� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{.Comment}} func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { if !assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { t.FailNow() } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/require.go����������������������������������0000644�0610621�0607500�00000077525�13172163422�026306� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package require import ( assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { if !assert.Condition(t, comp, msgAndArgs...) { t.FailNow() } } // Conditionf uses a Comparison to assert a complex condition. func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{}) { if !assert.Conditionf(t, comp, msg, args...) { t.FailNow() } } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World") // assert.Contains(t, ["Hello", "World"], "World") // assert.Contains(t, {"Hello": "World"}, "Hello") // // Returns whether the assertion was successful (true) or not (false). func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if !assert.Contains(t, s, contains, msgAndArgs...) { t.FailNow() } } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") // assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") // assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { if !assert.Containsf(t, s, contains, msg, args...) { t.FailNow() } } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Empty(t, obj) // // Returns whether the assertion was successful (true) or not (false). func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Empty(t, object, msgAndArgs...) { t.FailNow() } } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Emptyf(t, obj, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { if !assert.Emptyf(t, object, msg, args...) { t.FailNow() } } // Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.Equal(t, expected, actual, msgAndArgs...) { t.FailNow() } } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualError(t, err, expectedErrorString) // // Returns whether the assertion was successful (true) or not (false). func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { if !assert.EqualError(t, theError, errString, msgAndArgs...) { t.FailNow() } } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { if !assert.EqualErrorf(t, theError, errString, msg, args...) { t.FailNow() } } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.EqualValues(t, expected, actual, msgAndArgs...) { t.FailNow() } } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if !assert.EqualValuesf(t, expected, actual, msg, args...) { t.FailNow() } } // Equalf asserts that two objects are equal. // // assert.Equalf(t, 123, 123, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if !assert.Equalf(t, expected, actual, msg, args...) { t.FailNow() } } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Error(t, err) { // assert.Equal(t, expectedError, err) // } // // Returns whether the assertion was successful (true) or not (false). func Error(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.Error(t, err, msgAndArgs...) { t.FailNow() } } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Errorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } // // Returns whether the assertion was successful (true) or not (false). func Errorf(t TestingT, err error, msg string, args ...interface{}) { if !assert.Errorf(t, err, msg, args...) { t.FailNow() } } // Exactly asserts that two objects are equal is value and type. // // assert.Exactly(t, int32(123), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.Exactly(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Exactlyf asserts that two objects are equal is value and type. // // assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if !assert.Exactlyf(t, expected, actual, msg, args...) { t.FailNow() } } // Fail reports a failure through func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { if !assert.Fail(t, failureMessage, msgAndArgs...) { t.FailNow() } } // FailNow fails test func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { if !assert.FailNow(t, failureMessage, msgAndArgs...) { t.FailNow() } } // FailNowf fails test func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { if !assert.FailNowf(t, failureMessage, msg, args...) { t.FailNow() } } // Failf reports a failure through func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { if !assert.Failf(t, failureMessage, msg, args...) { t.FailNow() } } // False asserts that the specified value is false. // // assert.False(t, myBool) // // Returns whether the assertion was successful (true) or not (false). func False(t TestingT, value bool, msgAndArgs ...interface{}) { if !assert.False(t, value, msgAndArgs...) { t.FailNow() } } // Falsef asserts that the specified value is false. // // assert.Falsef(t, myBool, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Falsef(t TestingT, value bool, msg string, args ...interface{}) { if !assert.Falsef(t, value, msg, args...) { t.FailNow() } } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { if !assert.HTTPBodyContains(t, handler, method, url, values, str) { t.FailNow() } } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { if !assert.HTTPBodyContainsf(t, handler, method, url, values, str) { t.FailNow() } } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { if !assert.HTTPBodyNotContains(t, handler, method, url, values, str) { t.FailNow() } } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { if !assert.HTTPBodyNotContainsf(t, handler, method, url, values, str) { t.FailNow() } } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPError(t, handler, method, url, values) { t.FailNow() } } // HTTPErrorf asserts that a specified handler returns an error status code. // // assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPErrorf(t, handler, method, url, values) { t.FailNow() } } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPRedirect(t, handler, method, url, values) { t.FailNow() } } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPRedirectf(t, handler, method, url, values) { t.FailNow() } } // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPSuccess(t, handler, method, url, values) { t.FailNow() } } // HTTPSuccessf asserts that a specified handler returns a success status code. // // assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPSuccessf(t, handler, method, url, values) { t.FailNow() } } // Implements asserts that an object is implemented by the specified interface. // // assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { t.FailNow() } } // Implementsf asserts that an object is implemented by the specified interface. // // assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { if !assert.Implementsf(t, interfaceObject, object, msg, args...) { t.FailNow() } } // InDelta asserts that the two numerals are within delta of each other. // // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) // // Returns whether the assertion was successful (true) or not (false). func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDeltaSlice is the same as InDelta, except it compares two slices. func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if !assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDeltaSlicef is the same as InDelta, except it compares two slices. func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if !assert.InDeltaSlicef(t, expected, actual, delta, msg, args...) { t.FailNow() } } // InDeltaf asserts that the two numerals are within delta of each other. // // assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) // // Returns whether the assertion was successful (true) or not (false). func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if !assert.InDeltaf(t, expected, actual, delta, msg, args...) { t.FailNow() } } // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { t.FailNow() } } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if !assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) { t.FailNow() } } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { if !assert.InEpsilonSlicef(t, expected, actual, epsilon, msg, args...) { t.FailNow() } } // InEpsilonf asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { if !assert.InEpsilonf(t, expected, actual, epsilon, msg, args...) { t.FailNow() } } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.IsType(t, expectedType, object, msgAndArgs...) { t.FailNow() } } // IsTypef asserts that the specified objects are of the same type. func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) { if !assert.IsTypef(t, expectedType, object, msg, args...) { t.FailNow() } } // JSONEq asserts that two JSON strings are equivalent. // // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) // // Returns whether the assertion was successful (true) or not (false). func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { if !assert.JSONEq(t, expected, actual, msgAndArgs...) { t.FailNow() } } // JSONEqf asserts that two JSON strings are equivalent. // // assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { if !assert.JSONEqf(t, expected, actual, msg, args...) { t.FailNow() } } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // assert.Len(t, mySlice, 3) // // Returns whether the assertion was successful (true) or not (false). func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { if !assert.Len(t, object, length, msgAndArgs...) { t.FailNow() } } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // assert.Lenf(t, mySlice, 3, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { if !assert.Lenf(t, object, length, msg, args...) { t.FailNow() } } // Nil asserts that the specified object is nil. // // assert.Nil(t, err) // // Returns whether the assertion was successful (true) or not (false). func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Nil(t, object, msgAndArgs...) { t.FailNow() } } // Nilf asserts that the specified object is nil. // // assert.Nilf(t, err, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { if !assert.Nilf(t, object, msg, args...) { t.FailNow() } } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { // assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). func NoError(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.NoError(t, err, msgAndArgs...) { t.FailNow() } } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoErrorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { if !assert.NoErrorf(t, err, msg, args...) { t.FailNow() } } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContains(t, "Hello World", "Earth") // assert.NotContains(t, ["Hello", "World"], "Earth") // assert.NotContains(t, {"Hello": "World"}, "Earth") // // Returns whether the assertion was successful (true) or not (false). func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if !assert.NotContains(t, s, contains, msgAndArgs...) { t.FailNow() } } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") // assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") // assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { if !assert.NotContainsf(t, s, contains, msg, args...) { t.FailNow() } } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmpty(t, obj) { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotEmpty(t, object, msgAndArgs...) { t.FailNow() } } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmptyf(t, obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { if !assert.NotEmptyf(t, object, msg, args...) { t.FailNow() } } // NotEqual asserts that the specified values are NOT equal. // // assert.NotEqual(t, obj1, obj2) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.NotEqual(t, expected, actual, msgAndArgs...) { t.FailNow() } } // NotEqualf asserts that the specified values are NOT equal. // // assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if !assert.NotEqualf(t, expected, actual, msg, args...) { t.FailNow() } } // NotNil asserts that the specified object is not nil. // // assert.NotNil(t, err) // // Returns whether the assertion was successful (true) or not (false). func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotNil(t, object, msgAndArgs...) { t.FailNow() } } // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { if !assert.NotNilf(t, object, msg, args...) { t.FailNow() } } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanics(t, func(){ RemainCalm() }) // // Returns whether the assertion was successful (true) or not (false). func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.NotPanics(t, f, msgAndArgs...) { t.FailNow() } } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { if !assert.NotPanicsf(t, f, msg, args...) { t.FailNow() } } // NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if !assert.NotRegexp(t, rx, str, msgAndArgs...) { t.FailNow() } } // NotRegexpf asserts that a specified regexp does not match a string. // // assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") // assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { if !assert.NotRegexpf(t, rx, str, msg, args...) { t.FailNow() } } // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") // // Returns whether the assertion was successful (true) or not (false). func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { if !assert.NotSubset(t, list, subset, msgAndArgs...) { t.FailNow() } } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { if !assert.NotSubsetf(t, list, subset, msg, args...) { t.FailNow() } } // NotZero asserts that i is not the zero value for its type and returns the truth. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if !assert.NotZero(t, i, msgAndArgs...) { t.FailNow() } } // NotZerof asserts that i is not the zero value for its type and returns the truth. func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { if !assert.NotZerof(t, i, msg, args...) { t.FailNow() } } // Panics asserts that the code inside the specified PanicTestFunc panics. // // assert.Panics(t, func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.Panics(t, f, msgAndArgs...) { t.FailNow() } } // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.PanicsWithValue(t, expected, f, msgAndArgs...) { t.FailNow() } } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { if !assert.PanicsWithValuef(t, expected, f, msg, args...) { t.FailNow() } } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { if !assert.Panicsf(t, f, msg, args...) { t.FailNow() } } // Regexp asserts that a specified regexp matches a string. // // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") // assert.Regexp(t, "start...$", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if !assert.Regexp(t, rx, str, msgAndArgs...) { t.FailNow() } } // Regexpf asserts that a specified regexp matches a string. // // assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") // assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { if !assert.Regexpf(t, rx, str, msg, args...) { t.FailNow() } } // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") // // Returns whether the assertion was successful (true) or not (false). func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { if !assert.Subset(t, list, subset, msgAndArgs...) { t.FailNow() } } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { if !assert.Subsetf(t, list, subset, msg, args...) { t.FailNow() } } // True asserts that the specified value is true. // // assert.True(t, myBool) // // Returns whether the assertion was successful (true) or not (false). func True(t TestingT, value bool, msgAndArgs ...interface{}) { if !assert.True(t, value, msgAndArgs...) { t.FailNow() } } // Truef asserts that the specified value is true. // // assert.Truef(t, myBool, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Truef(t TestingT, value bool, msg string, args ...interface{}) { if !assert.Truef(t, value, msg, args...) { t.FailNow() } } // WithinDuration asserts that the two times are within duration delta of each other. // // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) // // Returns whether the assertion was successful (true) or not (false). func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // WithinDurationf asserts that the two times are within duration delta of each other. // // assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { if !assert.WithinDurationf(t, expected, actual, delta, msg, args...) { t.FailNow() } } // Zero asserts that i is the zero value for its type and returns the truth. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if !assert.Zero(t, i, msgAndArgs...) { t.FailNow() } } // Zerof asserts that i is the zero value for its type and returns the truth. func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) { if !assert.Zerof(t, i, msg, args...) { t.FailNow() } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/forward_requirements_test.go����������������0000644�0610621�0607500�00000020333�13172163422�032121� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package require import ( "errors" "testing" "time" ) func TestImplementsWrapper(t *testing.T) { require := New(t) require.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestIsTypeWrapper(t *testing.T) { require := New(t) require.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualWrapper(t *testing.T) { require := New(t) require.Equal(1, 1) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Equal(1, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestNotEqualWrapper(t *testing.T) { require := New(t) require.NotEqual(1, 2) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotEqual(2, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestExactlyWrapper(t *testing.T) { require := New(t) a := float32(1) b := float32(1) c := float64(1) require.Exactly(a, b) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Exactly(a, c) if !mockT.Failed { t.Error("Check should fail") } } func TestNotNilWrapper(t *testing.T) { require := New(t) require.NotNil(t, new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotNil(nil) if !mockT.Failed { t.Error("Check should fail") } } func TestNilWrapper(t *testing.T) { require := New(t) require.Nil(nil) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Nil(new(AssertionTesterConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestTrueWrapper(t *testing.T) { require := New(t) require.True(true) mockT := new(MockT) mockRequire := New(mockT) mockRequire.True(false) if !mockT.Failed { t.Error("Check should fail") } } func TestFalseWrapper(t *testing.T) { require := New(t) require.False(false) mockT := new(MockT) mockRequire := New(mockT) mockRequire.False(true) if !mockT.Failed { t.Error("Check should fail") } } func TestContainsWrapper(t *testing.T) { require := New(t) require.Contains("Hello World", "Hello") mockT := new(MockT) mockRequire := New(mockT) mockRequire.Contains("Hello World", "Salut") if !mockT.Failed { t.Error("Check should fail") } } func TestNotContainsWrapper(t *testing.T) { require := New(t) require.NotContains("Hello World", "Hello!") mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotContains("Hello World", "Hello") if !mockT.Failed { t.Error("Check should fail") } } func TestPanicsWrapper(t *testing.T) { require := New(t) require.Panics(func() { panic("Panic!") }) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Panics(func() {}) if !mockT.Failed { t.Error("Check should fail") } } func TestNotPanicsWrapper(t *testing.T) { require := New(t) require.NotPanics(func() {}) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotPanics(func() { panic("Panic!") }) if !mockT.Failed { t.Error("Check should fail") } } func TestNoErrorWrapper(t *testing.T) { require := New(t) require.NoError(nil) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NoError(errors.New("some error")) if !mockT.Failed { t.Error("Check should fail") } } func TestErrorWrapper(t *testing.T) { require := New(t) require.Error(errors.New("some error")) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Error(nil) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualErrorWrapper(t *testing.T) { require := New(t) require.EqualError(errors.New("some error"), "some error") mockT := new(MockT) mockRequire := New(mockT) mockRequire.EqualError(errors.New("some error"), "Not some error") if !mockT.Failed { t.Error("Check should fail") } } func TestEmptyWrapper(t *testing.T) { require := New(t) require.Empty("") mockT := new(MockT) mockRequire := New(mockT) mockRequire.Empty("x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotEmptyWrapper(t *testing.T) { require := New(t) require.NotEmpty("x") mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotEmpty("") if !mockT.Failed { t.Error("Check should fail") } } func TestWithinDurationWrapper(t *testing.T) { require := New(t) a := time.Now() b := a.Add(10 * time.Second) require.WithinDuration(a, b, 15*time.Second) mockT := new(MockT) mockRequire := New(mockT) mockRequire.WithinDuration(a, b, 5*time.Second) if !mockT.Failed { t.Error("Check should fail") } } func TestInDeltaWrapper(t *testing.T) { require := New(t) require.InDelta(1.001, 1, 0.01) mockT := new(MockT) mockRequire := New(mockT) mockRequire.InDelta(1, 2, 0.5) if !mockT.Failed { t.Error("Check should fail") } } func TestZeroWrapper(t *testing.T) { require := New(t) require.Zero(0) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Zero(1) if !mockT.Failed { t.Error("Check should fail") } } func TestNotZeroWrapper(t *testing.T) { require := New(t) require.NotZero(1) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotZero(0) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_EqualSONString(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") if mockT.Failed { t.Error("Check should pass") } } func TestJSONEqWrapper_Array(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`{"foo": "bar"}`, "Not JSON") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq("Not JSON", "Not JSON") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) if !mockT.Failed { t.Error("Check should fail") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/forward_requirements.go���������������������0000644�0610621�0607500�00000000604�13172163422�031061� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package require // Assertions provides assertion methods around the // TestingT interface. type Assertions struct { t TestingT } // New makes a new Assertions object for the specified TestingT. func New(t TestingT) *Assertions { return &Assertions{ t: t, } } //go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl -include-format-funcs ����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/require/doc.go��������������������������������������0000644�0610621�0607500�00000001554�13172163422�025364� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package require implements the same assertions as the `assert` package but // stops test execution when a test fails. // // Example Usage // // The following is a complete example using require in a standard test function: // import ( // "testing" // "github.com/stretchr/testify/require" // ) // // func TestSomething(t *testing.T) { // // var a string = "Hello" // var b string = "Hello" // // require.Equal(t, a, b, "The two words should be the same.") // // } // // Assertions // // The `require` package have same global functions as in the `assert` package, // but instead of returning a boolean result they call `t.FailNow()`. // // Every assertion function also takes an optional string message as the final argument, // allowing custom error messages to be appended to the message the assertion method outputs. package require ����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/package_test.go�������������������������������������0000644�0610621�0607500�00000000271�13172163422�025570� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package testify import ( "github.com/stretchr/testify/assert" "testing" ) func TestImports(t *testing.T) { if assert.Equal(t, 1, 1) != true { t.Error("Something is wrong.") } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/mock/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163422�023540� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/mock/mock_test.go�����������������������������������0000644�0610621�0607500�00000101355�13172163422�026064� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package mock import ( "errors" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) /* Test objects */ // ExampleInterface represents an example interface. type ExampleInterface interface { TheExampleMethod(a, b, c int) (int, error) } // TestExampleImplementation is a test implementation of ExampleInterface type TestExampleImplementation struct { Mock } func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) { args := i.Called(a, b, c) return args.Int(0), errors.New("Whoops") } func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) { i.Called(yesorno) } type ExampleType struct { ran bool } func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error { args := i.Called(et) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error { args := i.Called(fn) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error { args := i.Called(a) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error { args := i.Called(a) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodMixedVariadic(a int, b ...int) error { args := i.Called(a, b) return args.Error(0) } type ExampleFuncType func(string) error func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error { args := i.Called(fn) return args.Error(0) } /* Mock */ func Test_Mock_TestData(t *testing.T) { var mockedService = new(TestExampleImplementation) if assert.NotNil(t, mockedService.TestData()) { mockedService.TestData().Set("something", 123) assert.Equal(t, 123, mockedService.TestData().Get("something").Data()) } } func Test_Mock_On(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.On("TheExampleMethod") assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, "TheExampleMethod", c.Method) } func Test_Mock_Chained_On(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) mockedService. On("TheExampleMethod", 1, 2, 3). Return(0). On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). Return(nil) expectedCalls := []*Call{ &Call{ Parent: &mockedService.Mock, Method: "TheExampleMethod", Arguments: []interface{}{1, 2, 3}, ReturnArguments: []interface{}{0}, }, &Call{ Parent: &mockedService.Mock, Method: "TheExampleMethod3", Arguments: []interface{}{AnythingOfType("*mock.ExampleType")}, ReturnArguments: []interface{}{nil}, }, } assert.Equal(t, expectedCalls, mockedService.ExpectedCalls) } func Test_Mock_On_WithArgs(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.On("TheExampleMethod", 1, 2, 3, 4) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, "TheExampleMethod", c.Method) assert.Equal(t, Arguments{1, 2, 3, 4}, c.Arguments) } func Test_Mock_On_WithFuncArg(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethodFunc", AnythingOfType("func(string) error")). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, "TheExampleMethodFunc", c.Method) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, AnythingOfType("func(string) error"), c.Arguments[0]) fn := func(string) error { return nil } assert.NotPanics(t, func() { mockedService.TheExampleMethodFunc(fn) }) } func Test_Mock_On_WithIntArgMatcher(t *testing.T) { var mockedService TestExampleImplementation mockedService.On("TheExampleMethod", MatchedBy(func(a int) bool { return a == 1 }), MatchedBy(func(b int) bool { return b == 2 }), MatchedBy(func(c int) bool { return c == 3 })).Return(0, nil) assert.Panics(t, func() { mockedService.TheExampleMethod(1, 2, 4) }) assert.Panics(t, func() { mockedService.TheExampleMethod(2, 2, 3) }) assert.NotPanics(t, func() { mockedService.TheExampleMethod(1, 2, 3) }) } func Test_Mock_On_WithPtrArgMatcher(t *testing.T) { var mockedService TestExampleImplementation mockedService.On("TheExampleMethod3", MatchedBy(func(a *ExampleType) bool { return a.ran == true }), ).Return(nil) mockedService.On("TheExampleMethod3", MatchedBy(func(a *ExampleType) bool { return a.ran == false }), ).Return(errors.New("error")) assert.Equal(t, mockedService.TheExampleMethod3(&ExampleType{true}), nil) assert.EqualError(t, mockedService.TheExampleMethod3(&ExampleType{false}), "error") } func Test_Mock_On_WithFuncArgMatcher(t *testing.T) { var mockedService TestExampleImplementation fixture1, fixture2 := errors.New("fixture1"), errors.New("fixture2") mockedService.On("TheExampleMethodFunc", MatchedBy(func(a func(string) error) bool { return a("string") == fixture1 }), ).Return(errors.New("fixture1")) mockedService.On("TheExampleMethodFunc", MatchedBy(func(a func(string) error) bool { return a("string") == fixture2 }), ).Return(errors.New("fixture2")) assert.EqualError(t, mockedService.TheExampleMethodFunc( func(string) error { return fixture1 }), "fixture1") assert.EqualError(t, mockedService.TheExampleMethodFunc( func(string) error { return fixture2 }), "fixture2") } func Test_Mock_On_WithVariadicFunc(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethodVariadic", []int{1, 2, 3}). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, []int{1, 2, 3}, c.Arguments[0]) assert.NotPanics(t, func() { mockedService.TheExampleMethodVariadic(1, 2, 3) }) assert.Panics(t, func() { mockedService.TheExampleMethodVariadic(1, 2) }) } func Test_Mock_On_WithMixedVariadicFunc(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethodMixedVariadic", 1, []int{2, 3, 4}). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 2, len(c.Arguments)) assert.Equal(t, 1, c.Arguments[0]) assert.Equal(t, []int{2, 3, 4}, c.Arguments[1]) assert.NotPanics(t, func() { mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 4) }) assert.Panics(t, func() { mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 5) }) } func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, []interface{}{1, 2, 3}, c.Arguments[0]) assert.NotPanics(t, func() { mockedService.TheExampleMethodVariadicInterface(1, 2, 3) }) assert.Panics(t, func() { mockedService.TheExampleMethodVariadicInterface(1, 2) }) } func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) var expected []interface{} c := mockedService. On("TheExampleMethodVariadicInterface", expected). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, expected, c.Arguments[0]) assert.NotPanics(t, func() { mockedService.TheExampleMethodVariadicInterface() }) assert.Panics(t, func() { mockedService.TheExampleMethodVariadicInterface(1, 2) }) } func Test_Mock_On_WithFuncPanics(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) assert.Panics(t, func() { mockedService.On("TheExampleMethodFunc", func(string) error { return nil }) }) } func Test_Mock_On_WithFuncTypeArg(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), c.Arguments[0]) fn := func(string) error { return nil } assert.NotPanics(t, func() { mockedService.TheExampleMethodFuncType(fn) }) } func Test_Mock_Return(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethod", "A", "B", true). Return(1, "two", true) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 0, call.Repeatability) assert.Nil(t, call.WaitFor) } func Test_Mock_Return_WaitUntil(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) ch := time.After(time.Second) c := mockedService.Mock. On("TheExampleMethod", "A", "B", true). WaitUntil(ch). Return(1, "two", true) // assert that the call was created require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 0, call.Repeatability) assert.Equal(t, ch, call.WaitFor) } func Test_Mock_Return_After(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.Mock. On("TheExampleMethod", "A", "B", true). Return(1, "two", true). After(time.Second) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.Mock.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 0, call.Repeatability) assert.NotEqual(t, nil, call.WaitFor) } func Test_Mock_Return_Run(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) fn := func(args Arguments) { arg := args.Get(0).(*ExampleType) arg.ran = true } c := mockedService.Mock. On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). Return(nil). Run(fn) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.Mock.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod3", call.Method) assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) assert.Equal(t, nil, call.ReturnArguments[0]) assert.Equal(t, 0, call.Repeatability) assert.NotEqual(t, nil, call.WaitFor) assert.NotNil(t, call.Run) et := ExampleType{} assert.Equal(t, false, et.ran) mockedService.TheExampleMethod3(&et) assert.Equal(t, true, et.ran) } func Test_Mock_Return_Run_Out_Of_Order(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) f := func(args Arguments) { arg := args.Get(0).(*ExampleType) arg.ran = true } c := mockedService.Mock. On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). Run(f). Return(nil) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.Mock.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod3", call.Method) assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) assert.Equal(t, nil, call.ReturnArguments[0]) assert.Equal(t, 0, call.Repeatability) assert.NotEqual(t, nil, call.WaitFor) assert.NotNil(t, call.Run) } func Test_Mock_Return_Once(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.On("TheExampleMethod", "A", "B", true). Return(1, "two", true). Once() require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 1, call.Repeatability) assert.Nil(t, call.WaitFor) } func Test_Mock_Return_Twice(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethod", "A", "B", true). Return(1, "two", true). Twice() require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 2, call.Repeatability) assert.Nil(t, call.WaitFor) } func Test_Mock_Return_Times(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethod", "A", "B", true). Return(1, "two", true). Times(5) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 5, call.Repeatability) assert.Nil(t, call.WaitFor) } func Test_Mock_Return_Nothing(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethod", "A", "B", true). Return() require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 0, len(call.ReturnArguments)) } func Test_Mock_findExpectedCall(t *testing.T) { m := new(Mock) m.On("One", 1).Return("one") m.On("Two", 2).Return("two") m.On("Two", 3).Return("three") f, c := m.findExpectedCall("Two", 3) if assert.Equal(t, 2, f) { if assert.NotNil(t, c) { assert.Equal(t, "Two", c.Method) assert.Equal(t, 3, c.Arguments[0]) assert.Equal(t, "three", c.ReturnArguments[0]) } } } func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) { m := new(Mock) m.On("One", 1).Return("one") m.On("Two", 2).Return("two") m.On("Two", 3).Return("three") f, _ := m.findExpectedCall("Two") assert.Equal(t, -1, f) } func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) { m := new(Mock) m.On("One", 1).Return("one") m.On("Two", 2).Return("two").Once() m.On("Two", 3).Return("three").Twice() m.On("Two", 3).Return("three").Times(8) f, c := m.findExpectedCall("Two", 3) if assert.Equal(t, 2, f) { if assert.NotNil(t, c) { assert.Equal(t, "Two", c.Method) assert.Equal(t, 3, c.Arguments[0]) assert.Equal(t, "three", c.ReturnArguments[0]) } } } func Test_callString(t *testing.T) { assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false)) } func Test_Mock_Called(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true) returnArguments := mockedService.Called(1, 2, 3) if assert.Equal(t, 1, len(mockedService.Calls)) { assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method) assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) } if assert.Equal(t, 3, len(returnArguments)) { assert.Equal(t, 5, returnArguments[0]) assert.Equal(t, "6", returnArguments[1]) assert.Equal(t, true, returnArguments[2]) } } func asyncCall(m *Mock, ch chan Arguments) { ch <- m.Called(1, 2, 3) } func Test_Mock_Called_blocks(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond) ch := make(chan Arguments) go asyncCall(&mockedService.Mock, ch) select { case <-ch: t.Fatal("should have waited") case <-time.After(1 * time.Millisecond): } returnArguments := <-ch if assert.Equal(t, 1, len(mockedService.Mock.Calls)) { assert.Equal(t, "asyncCall", mockedService.Mock.Calls[0].Method) assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0]) assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1]) assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2]) } if assert.Equal(t, 3, len(returnArguments)) { assert.Equal(t, 5, returnArguments[0]) assert.Equal(t, "6", returnArguments[1]) assert.Equal(t, true, returnArguments[2]) } } func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService. On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). Return(5, "6", true). Once() mockedService. On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). Return(-1, "hi", false) returnArguments1 := mockedService.Called(1, 2, 3) returnArguments2 := mockedService.Called(1, 2, 3) if assert.Equal(t, 2, len(mockedService.Calls)) { assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method) assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method) assert.Equal(t, 1, mockedService.Calls[1].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[1].Arguments[1]) assert.Equal(t, 3, mockedService.Calls[1].Arguments[2]) } if assert.Equal(t, 3, len(returnArguments1)) { assert.Equal(t, 5, returnArguments1[0]) assert.Equal(t, "6", returnArguments1[1]) assert.Equal(t, true, returnArguments1[2]) } if assert.Equal(t, 3, len(returnArguments2)) { assert.Equal(t, -1, returnArguments2[0]) assert.Equal(t, "hi", returnArguments2[1]) assert.Equal(t, false, returnArguments2[2]) } } func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4) mockedService.TheExampleMethod(1, 2, 3) mockedService.TheExampleMethod(1, 2, 3) mockedService.TheExampleMethod(1, 2, 3) mockedService.TheExampleMethod(1, 2, 3) assert.Panics(t, func() { mockedService.TheExampleMethod(1, 2, 3) }) } func Test_Mock_Called_Unexpected(t *testing.T) { var mockedService = new(TestExampleImplementation) // make sure it panics if no expectation was made assert.Panics(t, func() { mockedService.Called(1, 2, 3) }, "Calling unexpected method should panic") } func Test_AssertExpectationsForObjects_Helper(t *testing.T) { var mockedService1 = new(TestExampleImplementation) var mockedService2 = new(TestExampleImplementation) var mockedService3 = new(TestExampleImplementation) mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return() mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return() mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return() mockedService1.Called(1) mockedService2.Called(2) mockedService3.Called(3) assert.True(t, AssertExpectationsForObjects(t, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock)) assert.True(t, AssertExpectationsForObjects(t, mockedService1, mockedService2, mockedService3)) } func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) { var mockedService1 = new(TestExampleImplementation) var mockedService2 = new(TestExampleImplementation) var mockedService3 = new(TestExampleImplementation) mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return() mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return() mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return() mockedService1.Called(1) mockedService3.Called(3) tt := new(testing.T) assert.False(t, AssertExpectationsForObjects(tt, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock)) assert.False(t, AssertExpectationsForObjects(tt, mockedService1, mockedService2, mockedService3)) } func Test_Mock_AssertExpectations(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7) tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.Called(1, 2, 3) // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectations_Placeholder_NoArgs(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(5, 6, 7).Once() mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(7, 6, 5) tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.Called() // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectations_Placeholder(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations_Placeholder", 1, 2, 3).Return(5, 6, 7).Once() mockedService.On("Test_Mock_AssertExpectations_Placeholder", 3, 2, 1).Return(7, 6, 5) tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.Called(1, 2, 3) // now assert expectations assert.False(t, mockedService.AssertExpectations(tt)) // make call to the second expectation mockedService.Called(3, 2, 1) // now assert expectations again assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectations_With_Pointers(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{1}).Return(1) mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{2}).Return(2) tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) s := struct{ Foo int }{1} // make the calls now mockedService.Called(&s) s.Foo = 2 mockedService.Called(&s) // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectationsCustomType(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once() tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.TheExampleMethod3(&ExampleType{}) // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice() tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.Called(1, 2, 3) assert.False(t, mockedService.AssertExpectations(tt)) mockedService.Called(1, 2, 3) // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7) mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7) args1 := mockedService.Called(1, 2, 3) assert.Equal(t, 5, args1.Int(0)) assert.Equal(t, 6, args1.Int(1)) assert.Equal(t, 7, args1.Int(2)) args2 := mockedService.Called(4, 5, 6) assert.Equal(t, 5, args2.Int(0)) assert.Equal(t, 6, args2.Int(1)) assert.Equal(t, 7, args2.Int(2)) } func Test_Mock_AssertNumberOfCalls(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1)) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2)) } func Test_Mock_AssertCalled(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3)) } func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService. On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything). Return() mockedService.Called(1, "two", []uint8("three")) assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8"))) } func Test_Mock_AssertCalled_WithArguments(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) tt := new(testing.T) assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3)) assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4)) } func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once() mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once() mockedService.Called(1, 2, 3) mockedService.Called(2, 3, 4) tt := new(testing.T) assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3)) assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4)) assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5)) } func Test_Mock_AssertNotCalled(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled")) } /* Arguments helper methods */ func Test_Arguments_Get(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, "string", args.Get(0).(string)) assert.Equal(t, 123, args.Get(1).(int)) assert.Equal(t, true, args.Get(2).(bool)) } func Test_Arguments_Is(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.True(t, args.Is("string", 123, true)) assert.False(t, args.Is("wrong", 456, false)) } func Test_Arguments_Diff(t *testing.T) { var args = Arguments([]interface{}{"Hello World", 123, true}) var diff string var count int diff, count = args.Diff([]interface{}{"Hello World", 456, "false"}) assert.Equal(t, 2, count) assert.Contains(t, diff, `%!s(int=456) != %!s(int=123)`) assert.Contains(t, diff, `false != %!s(bool=true)`) } func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) var diff string var count int diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"}) assert.Equal(t, 3, count) assert.Contains(t, diff, `extra != (Missing)`) } func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) var count int _, count = args.Diff([]interface{}{"string", Anything, true}) assert.Equal(t, 0, count) } func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) { var args = Arguments([]interface{}{"string", Anything, true}) var count int _, count = args.Diff([]interface{}{"string", 123, true}) assert.Equal(t, 0, count) } func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) { var args = Arguments([]interface{}{"string", AnythingOfType("int"), true}) var count int _, count = args.Diff([]interface{}{"string", 123, true}) assert.Equal(t, 0, count) } func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) { var args = Arguments([]interface{}{"string", AnythingOfType("string"), true}) var count int var diff string diff, count = args.Diff([]interface{}{"string", 123, true}) assert.Equal(t, 1, count) assert.Contains(t, diff, `string != type int - %!s(int=123)`) } func Test_Arguments_Diff_WithArgMatcher(t *testing.T) { matchFn := func(a int) bool { return a == 123 } var args = Arguments([]interface{}{"string", MatchedBy(matchFn), true}) diff, count := args.Diff([]interface{}{"string", 124, true}) assert.Equal(t, 1, count) assert.Contains(t, diff, `%!s(int=124) not matched by func(int) bool`) diff, count = args.Diff([]interface{}{"string", false, true}) assert.Equal(t, 1, count) assert.Contains(t, diff, `%!s(bool=false) not matched by func(int) bool`) diff, count = args.Diff([]interface{}{"string", 123, false}) assert.Contains(t, diff, `%!s(int=123) matched by func(int) bool`) diff, count = args.Diff([]interface{}{"string", 123, true}) assert.Equal(t, 0, count) assert.Contains(t, diff, `No differences.`) } func Test_Arguments_Assert(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.True(t, args.Assert(t, "string", 123, true)) } func Test_Arguments_String_Representation(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, `string,int,bool`, args.String()) } func Test_Arguments_String(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, "string", args.String(0)) } func Test_Arguments_Error(t *testing.T) { var err = errors.New("An Error") var args = Arguments([]interface{}{"string", 123, true, err}) assert.Equal(t, err, args.Error(3)) } func Test_Arguments_Error_Nil(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true, nil}) assert.Equal(t, nil, args.Error(3)) } func Test_Arguments_Int(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, 123, args.Int(1)) } func Test_Arguments_Bool(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, true, args.Bool(2)) } func Test_WaitUntil_Parallel(t *testing.T) { // make a test impl object var mockedService *TestExampleImplementation = new(TestExampleImplementation) ch1 := make(chan time.Time) ch2 := make(chan time.Time) mockedService.Mock.On("TheExampleMethod2", true).Return().WaitUntil(ch2).Run(func(args Arguments) { ch1 <- time.Now() }) mockedService.Mock.On("TheExampleMethod2", false).Return().WaitUntil(ch1) // Lock both goroutines on the .WaitUntil method go func() { mockedService.TheExampleMethod2(false) }() go func() { mockedService.TheExampleMethod2(true) }() // Allow the first call to execute, so the second one executes afterwards ch2 <- time.Now() } func Test_MockMethodCalled(t *testing.T) { m := new(Mock) m.On("foo", "hello").Return("world") retArgs := m.MethodCalled("foo", "hello") require.True(t, len(retArgs) == 1) require.Equal(t, "world", retArgs[0]) m.AssertExpectations(t) } // Test to validate fix for racy concurrent call access in MethodCalled() func Test_MockReturnAndCalledConcurrent(t *testing.T) { iterations := 1000 m := &Mock{} call := m.On("ConcurrencyTestMethod") wg := sync.WaitGroup{} wg.Add(2) go func() { for i := 0; i < iterations; i++ { call.Return(10) } wg.Done() }() go func() { for i := 0; i < iterations; i++ { ConcurrencyTestMethod(m) } wg.Done() }() wg.Wait() } func ConcurrencyTestMethod(m *Mock) { m.Called() } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/mock/mock.go����������������������������������������0000644�0610621�0607500�00000054445�13172163422�025034� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package mock import ( "fmt" "reflect" "regexp" "runtime" "strings" "sync" "time" "github.com/davecgh/go-spew/spew" "github.com/pmezard/go-difflib/difflib" "github.com/stretchr/objx" "github.com/stretchr/testify/assert" ) // TestingT is an interface wrapper around *testing.T type TestingT interface { Logf(format string, args ...interface{}) Errorf(format string, args ...interface{}) FailNow() } /* Call */ // Call represents a method call and is used for setting expectations, // as well as recording activity. type Call struct { Parent *Mock // The name of the method that was or will be called. Method string // Holds the arguments of the method. Arguments Arguments // Holds the arguments that should be returned when // this method is called. ReturnArguments Arguments // The number of times to return the return arguments when setting // expectations. 0 means to always return the value. Repeatability int // Amount of times this call has been called totalCalls int // Holds a channel that will be used to block the Return until it either // receives a message or is closed. nil means it returns immediately. WaitFor <-chan time.Time // Holds a handler used to manipulate arguments content that are passed by // reference. It's useful when mocking methods such as unmarshalers or // decoders. RunFn func(Arguments) } func newCall(parent *Mock, methodName string, methodArguments ...interface{}) *Call { return &Call{ Parent: parent, Method: methodName, Arguments: methodArguments, ReturnArguments: make([]interface{}, 0), Repeatability: 0, WaitFor: nil, RunFn: nil, } } func (c *Call) lock() { c.Parent.mutex.Lock() } func (c *Call) unlock() { c.Parent.mutex.Unlock() } // Return specifies the return arguments for the expectation. // // Mock.On("DoSomething").Return(errors.New("failed")) func (c *Call) Return(returnArguments ...interface{}) *Call { c.lock() defer c.unlock() c.ReturnArguments = returnArguments return c } // Once indicates that that the mock should only return the value once. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() func (c *Call) Once() *Call { return c.Times(1) } // Twice indicates that that the mock should only return the value twice. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() func (c *Call) Twice() *Call { return c.Times(2) } // Times indicates that that the mock should only return the indicated number // of times. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) func (c *Call) Times(i int) *Call { c.lock() defer c.unlock() c.Repeatability = i return c } // WaitUntil sets the channel that will block the mock's return until its closed // or a message is received. // // Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second)) func (c *Call) WaitUntil(w <-chan time.Time) *Call { c.lock() defer c.unlock() c.WaitFor = w return c } // After sets how long to block until the call returns // // Mock.On("MyMethod", arg1, arg2).After(time.Second) func (c *Call) After(d time.Duration) *Call { return c.WaitUntil(time.After(d)) } // Run sets a handler to be called before returning. It can be used when // mocking a method such as unmarshalers that takes a pointer to a struct and // sets properties in such struct // // Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}").Return().Run(func(args Arguments) { // arg := args.Get(0).(*map[string]interface{}) // arg["foo"] = "bar" // }) func (c *Call) Run(fn func(args Arguments)) *Call { c.lock() defer c.unlock() c.RunFn = fn return c } // On chains a new expectation description onto the mocked interface. This // allows syntax like. // // Mock. // On("MyMethod", 1).Return(nil). // On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error")) func (c *Call) On(methodName string, arguments ...interface{}) *Call { return c.Parent.On(methodName, arguments...) } // Mock is the workhorse used to track activity on another object. // For an example of its usage, refer to the "Example Usage" section at the top // of this document. type Mock struct { // Represents the calls that are expected of // an object. ExpectedCalls []*Call // Holds the calls that were made to this mocked object. Calls []Call // TestData holds any data that might be useful for testing. Testify ignores // this data completely allowing you to do whatever you like with it. testData objx.Map mutex sync.Mutex } // TestData holds any data that might be useful for testing. Testify ignores // this data completely allowing you to do whatever you like with it. func (m *Mock) TestData() objx.Map { if m.testData == nil { m.testData = make(objx.Map) } return m.testData } /* Setting expectations */ // On starts a description of an expectation of the specified method // being called. // // Mock.On("MyMethod", arg1, arg2) func (m *Mock) On(methodName string, arguments ...interface{}) *Call { for _, arg := range arguments { if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) } } m.mutex.Lock() defer m.mutex.Unlock() c := newCall(m, methodName, arguments...) m.ExpectedCalls = append(m.ExpectedCalls, c) return c } // /* // Recording and responding to activity // */ func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) { for i, call := range m.ExpectedCalls { if call.Method == method && call.Repeatability > -1 { _, diffCount := call.Arguments.Diff(arguments) if diffCount == 0 { return i, call } } } return -1, nil } func (m *Mock) findClosestCall(method string, arguments ...interface{}) (bool, *Call) { diffCount := 0 var closestCall *Call for _, call := range m.expectedCalls() { if call.Method == method { _, tempDiffCount := call.Arguments.Diff(arguments) if tempDiffCount < diffCount || diffCount == 0 { diffCount = tempDiffCount closestCall = call } } } if closestCall == nil { return false, nil } return true, closestCall } func callString(method string, arguments Arguments, includeArgumentValues bool) string { var argValsString string if includeArgumentValues { var argVals []string for argIndex, arg := range arguments { argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg)) } argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t")) } return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString) } // Called tells the mock object that a method has been called, and gets an array // of arguments to return. Panics if the call is unexpected (i.e. not preceded by // appropriate .On .Return() calls) // If Call.WaitFor is set, blocks until the channel is closed or receives a message. func (m *Mock) Called(arguments ...interface{}) Arguments { // get the calling function's name pc, _, _, ok := runtime.Caller(1) if !ok { panic("Couldn't get the caller information") } functionPath := runtime.FuncForPC(pc).Name() //Next four lines are required to use GCCGO function naming conventions. //For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock //uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree //With GCCGO we need to remove interface information starting from pN<dd>. re := regexp.MustCompile("\\.pN\\d+_") if re.MatchString(functionPath) { functionPath = re.Split(functionPath, -1)[0] } parts := strings.Split(functionPath, ".") functionName := parts[len(parts)-1] return m.MethodCalled(functionName, arguments...) } // MethodCalled tells the mock object that the given method has been called, and gets // an array of arguments to return. Panics if the call is unexpected (i.e. not preceded // by appropriate .On .Return() calls) // If Call.WaitFor is set, blocks until the channel is closed or receives a message. func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments { m.mutex.Lock() found, call := m.findExpectedCall(methodName, arguments...) if found < 0 { // we have to fail here - because we don't know what to do // as the return arguments. This is because: // // a) this is a totally unexpected call to this method, // b) the arguments are not what was expected, or // c) the developer has forgotten to add an accompanying On...Return pair. closestFound, closestCall := m.findClosestCall(methodName, arguments...) m.mutex.Unlock() if closestFound { panic(fmt.Sprintf("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\n", callString(methodName, arguments, true), callString(methodName, closestCall.Arguments, true), diffArguments(arguments, closestCall.Arguments))) } else { panic(fmt.Sprintf("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", methodName, methodName, callString(methodName, arguments, true), assert.CallerInfo())) } } switch { case call.Repeatability == 1: call.Repeatability = -1 call.totalCalls++ case call.Repeatability > 1: call.Repeatability-- call.totalCalls++ case call.Repeatability == 0: call.totalCalls++ } // add the call m.Calls = append(m.Calls, *newCall(m, methodName, arguments...)) m.mutex.Unlock() // block if specified if call.WaitFor != nil { <-call.WaitFor } m.mutex.Lock() runFn := call.RunFn m.mutex.Unlock() if runFn != nil { runFn(arguments) } m.mutex.Lock() returnArgs := call.ReturnArguments m.mutex.Unlock() return returnArgs } /* Assertions */ type assertExpectationser interface { AssertExpectations(TestingT) bool } // AssertExpectationsForObjects asserts that everything specified with On and Return // of the specified objects was in fact called as expected. // // Calls may have occurred in any order. func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { for _, obj := range testObjects { if m, ok := obj.(Mock); ok { t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") obj = &m } m := obj.(assertExpectationser) if !m.AssertExpectations(t) { return false } } return true } // AssertExpectations asserts that everything specified with On and Return was // in fact called as expected. Calls may have occurred in any order. func (m *Mock) AssertExpectations(t TestingT) bool { m.mutex.Lock() defer m.mutex.Unlock() var somethingMissing bool var failedExpectations int // iterate through each expectation expectedCalls := m.expectedCalls() for _, expectedCall := range expectedCalls { if !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 { somethingMissing = true failedExpectations++ t.Logf("\u274C\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) } else { if expectedCall.Repeatability > 0 { somethingMissing = true failedExpectations++ } else { t.Logf("\u2705\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) } } } if somethingMissing { t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) } return !somethingMissing } // AssertNumberOfCalls asserts that the method was called expectedCalls times. func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { m.mutex.Lock() defer m.mutex.Unlock() var actualCalls int for _, call := range m.calls() { if call.Method == methodName { actualCalls++ } } return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) } // AssertCalled asserts that the method was called. // It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { m.mutex.Lock() defer m.mutex.Unlock() if !assert.True(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method should have been called with %d argument(s), but was not.", methodName, len(arguments))) { t.Logf("%v", m.expectedCalls()) return false } return true } // AssertNotCalled asserts that the method was not called. // It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { m.mutex.Lock() defer m.mutex.Unlock() if !assert.False(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method was called with %d argument(s), but should NOT have been.", methodName, len(arguments))) { t.Logf("%v", m.expectedCalls()) return false } return true } func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { for _, call := range m.calls() { if call.Method == methodName { _, differences := Arguments(expected).Diff(call.Arguments) if differences == 0 { // found the expected call return true } } } // we didn't find the expected call return false } func (m *Mock) expectedCalls() []*Call { return append([]*Call{}, m.ExpectedCalls...) } func (m *Mock) calls() []Call { return append([]Call{}, m.Calls...) } /* Arguments */ // Arguments holds an array of method arguments or return values. type Arguments []interface{} const ( // Anything is used in Diff and Assert when the argument being tested // shouldn't be taken into consideration. Anything string = "mock.Anything" ) // AnythingOfTypeArgument is a string that contains the type of an argument // for use when type checking. Used in Diff and Assert. type AnythingOfTypeArgument string // AnythingOfType returns an AnythingOfTypeArgument object containing the // name of the type to check for. Used in Diff and Assert. // // For example: // Assert(t, AnythingOfType("string"), AnythingOfType("int")) func AnythingOfType(t string) AnythingOfTypeArgument { return AnythingOfTypeArgument(t) } // argumentMatcher performs custom argument matching, returning whether or // not the argument is matched by the expectation fixture function. type argumentMatcher struct { // fn is a function which accepts one argument, and returns a bool. fn reflect.Value } func (f argumentMatcher) Matches(argument interface{}) bool { expectType := f.fn.Type().In(0) if reflect.TypeOf(argument).AssignableTo(expectType) { result := f.fn.Call([]reflect.Value{reflect.ValueOf(argument)}) return result[0].Bool() } return false } func (f argumentMatcher) String() string { return fmt.Sprintf("func(%s) bool", f.fn.Type().In(0).Name()) } // MatchedBy can be used to match a mock call based on only certain properties // from a complex struct or some calculation. It takes a function that will be // evaluated with the called argument and will return true when there's a match // and false otherwise. // // Example: // m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" })) // // |fn|, must be a function accepting a single argument (of the expected type) // which returns a bool. If |fn| doesn't match the required signature, // MatchedBy() panics. func MatchedBy(fn interface{}) argumentMatcher { fnType := reflect.TypeOf(fn) if fnType.Kind() != reflect.Func { panic(fmt.Sprintf("assert: arguments: %s is not a func", fn)) } if fnType.NumIn() != 1 { panic(fmt.Sprintf("assert: arguments: %s does not take exactly one argument", fn)) } if fnType.NumOut() != 1 || fnType.Out(0).Kind() != reflect.Bool { panic(fmt.Sprintf("assert: arguments: %s does not return a bool", fn)) } return argumentMatcher{fn: reflect.ValueOf(fn)} } // Get Returns the argument at the specified index. func (args Arguments) Get(index int) interface{} { if index+1 > len(args) { panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) } return args[index] } // Is gets whether the objects match the arguments specified. func (args Arguments) Is(objects ...interface{}) bool { for i, obj := range args { if obj != objects[i] { return false } } return true } // Diff gets a string describing the differences between the arguments // and the specified objects. // // Returns the diff string and number of differences found. func (args Arguments) Diff(objects []interface{}) (string, int) { var output = "\n" var differences int var maxArgCount = len(args) if len(objects) > maxArgCount { maxArgCount = len(objects) } for i := 0; i < maxArgCount; i++ { var actual, expected interface{} if len(objects) <= i { actual = "(Missing)" } else { actual = objects[i] } if len(args) <= i { expected = "(Missing)" } else { expected = args[i] } if matcher, ok := expected.(argumentMatcher); ok { if matcher.Matches(actual) { output = fmt.Sprintf("%s\t%d: \u2705 %s matched by %s\n", output, i, actual, matcher) } else { differences++ output = fmt.Sprintf("%s\t%d: \u2705 %s not matched by %s\n", output, i, actual, matcher) } } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { // type checking if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { // not match differences++ output = fmt.Sprintf("%s\t%d: \u274C type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actual) } } else { // normal checking if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { // match output = fmt.Sprintf("%s\t%d: \u2705 %s == %s\n", output, i, actual, expected) } else { // not match differences++ output = fmt.Sprintf("%s\t%d: \u274C %s != %s\n", output, i, actual, expected) } } } if differences == 0 { return "No differences.", differences } return output, differences } // Assert compares the arguments with the specified objects and fails if // they do not exactly match. func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { // get the differences diff, diffCount := args.Diff(objects) if diffCount == 0 { return true } // there are differences... report them... t.Logf(diff) t.Errorf("%sArguments do not match.", assert.CallerInfo()) return false } // String gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type. // // If no index is provided, String() returns a complete string representation // of the arguments. func (args Arguments) String(indexOrNil ...int) string { if len(indexOrNil) == 0 { // normal String() method - return a string representation of the args var argsStr []string for _, arg := range args { argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg))) } return strings.Join(argsStr, ",") } else if len(indexOrNil) == 1 { // Index has been specified - get the argument at that index var index = indexOrNil[0] var s string var ok bool if s, ok = args.Get(index).(string); !ok { panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) } return s } panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) } // Int gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type. func (args Arguments) Int(index int) int { var s int var ok bool if s, ok = args.Get(index).(int); !ok { panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s } // Error gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type. func (args Arguments) Error(index int) error { obj := args.Get(index) var s error var ok bool if obj == nil { return nil } if s, ok = obj.(error); !ok { panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s } // Bool gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type. func (args Arguments) Bool(index int) bool { var s bool var ok bool if s, ok = args.Get(index).(bool); !ok { panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s } func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { t := reflect.TypeOf(v) k := t.Kind() if k == reflect.Ptr { t = t.Elem() k = t.Kind() } return t, k } func diffArguments(expected Arguments, actual Arguments) string { if len(expected) != len(actual) { return fmt.Sprintf("Provided %v arguments, mocked for %v arguments", len(expected), len(actual)) } for x := range expected { if diffString := diff(expected[x], actual[x]); diffString != "" { return fmt.Sprintf("Difference found in argument %v:\n\n%s", x, diffString) } } return "" } // diff returns a diff of both values as long as both are of the same type and // are a struct, map, slice or array. Otherwise it returns an empty string. func diff(expected interface{}, actual interface{}) string { if expected == nil || actual == nil { return "" } et, ek := typeAndKind(expected) at, _ := typeAndKind(actual) if et != at { return "" } if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { return "" } e := spewConfig.Sdump(expected) a := spewConfig.Sdump(actual) diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ A: difflib.SplitLines(e), B: difflib.SplitLines(a), FromFile: "Expected", FromDate: "", ToFile: "Actual", ToDate: "", Context: 1, }) return diff } var spewConfig = spew.ConfigState{ Indent: " ", DisablePointerAddresses: true, DisableCapacities: true, SortKeys: true, } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/mock/doc.go�����������������������������������������0000644�0610621�0607500�00000003075�13172163422�024641� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package mock provides a system by which it is possible to mock your objects // and verify calls are happening as expected. // // Example Usage // // The mock package provides an object, Mock, that tracks activity on another object. It is usually // embedded into a test object as shown below: // // type MyTestObject struct { // // add a Mock object instance // mock.Mock // // // other fields go here as normal // } // // When implementing the methods of an interface, you wire your functions up // to call the Mock.Called(args...) method, and return the appropriate values. // // For example, to mock a method that saves the name and age of a person and returns // the year of their birth or an error, you might write this: // // func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { // args := o.Called(firstname, lastname, age) // return args.Int(0), args.Error(1) // } // // The Int, Error and Bool methods are examples of strongly typed getters that take the argument // index position. Given this argument list: // // (12, true, "Something") // // You could read them out strongly typed like this: // // args.Int(0) // args.Bool(1) // args.String(2) // // For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: // // return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) // // This may cause a panic if the object you are getting is nil (the type assertion will fail), in those // cases you should check for nil first. package mock �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/http/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163422�023566� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/http/test_round_tripper.go��������������������������0000644�0610621�0607500�00000000571�13172163422�030053� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package http import ( "github.com/stretchr/testify/mock" "net/http" ) // TestRoundTripper DEPRECATED USE net/http/httptest type TestRoundTripper struct { mock.Mock } // RoundTrip DEPRECATED USE net/http/httptest func (t *TestRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { args := t.Called(req) return args.Get(0).(*http.Response), args.Error(1) } ���������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/http/test_response_writer.go������������������������0000644�0610621�0607500�00000002307�13172163422�030410� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package http import ( "net/http" ) // TestResponseWriter DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. type TestResponseWriter struct { // StatusCode is the last int written by the call to WriteHeader(int) StatusCode int // Output is a string containing the written bytes using the Write([]byte) func. Output string // header is the internal storage of the http.Header object header http.Header } // Header DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. func (rw *TestResponseWriter) Header() http.Header { if rw.header == nil { rw.header = make(http.Header) } return rw.header } // Write DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. func (rw *TestResponseWriter) Write(bytes []byte) (int, error) { // assume 200 success if no header has been set if rw.StatusCode == 0 { rw.WriteHeader(200) } // add these bytes to the output string rw.Output = rw.Output + string(bytes) // return normal values return 0, nil } // WriteHeader DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. func (rw *TestResponseWriter) WriteHeader(i int) { rw.StatusCode = i } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/http/doc.go�����������������������������������������0000644�0610621�0607500�00000000076�13172163422�024665� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package http DEPRECATED USE net/http/httptest package http ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/doc.go����������������������������������������������0000644�0610621�0607500�00000001654�13172163422�023711� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. // // testify contains the following packages: // // The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. // // The http package contains tools to make it easier to test http activity using the Go testing system. // // The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. // // The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces. package testify // blank imports help docs. import ( // assert package _ "github.com/stretchr/testify/assert" // http package _ "github.com/stretchr/testify/http" // mock package _ "github.com/stretchr/testify/mock" ) ������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/���������������������������������������������0000755�0610621�0607500�00000000000�13172163422�024110� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/http_assertions_test.go����������������������0000644�0610621�0607500�00000010150�13172163422�030724� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package assert import ( "fmt" "net/http" "net/url" "testing" ) func httpOK(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } func httpRedirect(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTemporaryRedirect) } func httpError(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) } func TestHTTPSuccess(t *testing.T) { assert := New(t) mockT1 := new(testing.T) assert.Equal(HTTPSuccess(mockT1, httpOK, "GET", "/", nil), true) assert.False(mockT1.Failed()) mockT2 := new(testing.T) assert.Equal(HTTPSuccess(mockT2, httpRedirect, "GET", "/", nil), false) assert.True(mockT2.Failed()) mockT3 := new(testing.T) assert.Equal(HTTPSuccess(mockT3, httpError, "GET", "/", nil), false) assert.True(mockT3.Failed()) } func TestHTTPRedirect(t *testing.T) { assert := New(t) mockT1 := new(testing.T) assert.Equal(HTTPRedirect(mockT1, httpOK, "GET", "/", nil), false) assert.True(mockT1.Failed()) mockT2 := new(testing.T) assert.Equal(HTTPRedirect(mockT2, httpRedirect, "GET", "/", nil), true) assert.False(mockT2.Failed()) mockT3 := new(testing.T) assert.Equal(HTTPRedirect(mockT3, httpError, "GET", "/", nil), false) assert.True(mockT3.Failed()) } func TestHTTPError(t *testing.T) { assert := New(t) mockT1 := new(testing.T) assert.Equal(HTTPError(mockT1, httpOK, "GET", "/", nil), false) assert.True(mockT1.Failed()) mockT2 := new(testing.T) assert.Equal(HTTPError(mockT2, httpRedirect, "GET", "/", nil), false) assert.True(mockT2.Failed()) mockT3 := new(testing.T) assert.Equal(HTTPError(mockT3, httpError, "GET", "/", nil), true) assert.False(mockT3.Failed()) } func TestHTTPStatusesWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) } func httpHelloName(w http.ResponseWriter, r *http.Request) { name := r.FormValue("name") w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) } func TestHttpBody(t *testing.T) { assert := New(t) mockT := new(testing.T) assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) } func TestHttpBodyWrappers(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/http_assertions.go���������������������������0000644�0610621�0607500�00000010502�13172163422�027666� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package assert import ( "fmt" "net/http" "net/http/httptest" "net/url" "strings" ) // httpCode is a helper that returns HTTP code of the response. It returns -1 and // an error if building a new request fails. func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { w := httptest.NewRecorder() req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) if err != nil { return -1, err } handler(w, req) return w.Code, nil } // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent if !isSuccessCode { Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) } return isSuccessCode } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect if !isRedirectCode { Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) } return isRedirectCode } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } isErrorCode := code >= http.StatusBadRequest if !isErrorCode { Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) } return isErrorCode } // HTTPBody is a helper that returns HTTP body of the response. It returns // empty string if building a new request fails. func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { w := httptest.NewRecorder() req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) if err != nil { return "" } handler(w, req) return w.Body.String() } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { body := HTTPBody(handler, method, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if !contains { Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) } return contains } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { body := HTTPBody(handler, method, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if contains { Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) } return !contains } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/forward_assertions_test.go�������������������0000644�0610621�0607500�00000041411�13172163422�031415� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package assert import ( "errors" "regexp" "testing" "time" ) func TestImplementsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") } if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") } } func TestIsTypeWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") } if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") } } func TestEqualWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Equal("Hello World", "Hello World") { t.Error("Equal should return true") } if !assert.Equal(123, 123) { t.Error("Equal should return true") } if !assert.Equal(123.5, 123.5) { t.Error("Equal should return true") } if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { t.Error("Equal should return true") } if !assert.Equal(nil, nil) { t.Error("Equal should return true") } } func TestEqualValuesWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.EqualValues(uint32(10), int32(10)) { t.Error("EqualValues should return true") } } func TestNotNilWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotNil(new(AssertionTesterConformingObject)) { t.Error("NotNil should return true: object is not nil") } if assert.NotNil(nil) { t.Error("NotNil should return false: object is nil") } } func TestNilWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Nil(nil) { t.Error("Nil should return true: object is nil") } if assert.Nil(new(AssertionTesterConformingObject)) { t.Error("Nil should return false: object is not nil") } } func TestTrueWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.True(true) { t.Error("True should return true") } if assert.True(false) { t.Error("True should return false") } } func TestFalseWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.False(false) { t.Error("False should return true") } if assert.False(true) { t.Error("False should return false") } } func TestExactlyWrapper(t *testing.T) { assert := New(new(testing.T)) a := float32(1) b := float64(1) c := float32(1) d := float32(2) if assert.Exactly(a, b) { t.Error("Exactly should return false") } if assert.Exactly(a, d) { t.Error("Exactly should return false") } if !assert.Exactly(a, c) { t.Error("Exactly should return true") } if assert.Exactly(nil, a) { t.Error("Exactly should return false") } if assert.Exactly(a, nil) { t.Error("Exactly should return false") } } func TestNotEqualWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotEqual("Hello World", "Hello World!") { t.Error("NotEqual should return true") } if !assert.NotEqual(123, 1234) { t.Error("NotEqual should return true") } if !assert.NotEqual(123.5, 123.55) { t.Error("NotEqual should return true") } if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { t.Error("NotEqual should return true") } if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { t.Error("NotEqual should return true") } } func TestContainsWrapper(t *testing.T) { assert := New(new(testing.T)) list := []string{"Foo", "Bar"} if !assert.Contains("Hello World", "Hello") { t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") } if assert.Contains("Hello World", "Salut") { t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") } if !assert.Contains(list, "Foo") { t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } if assert.Contains(list, "Salut") { t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") } } func TestNotContainsWrapper(t *testing.T) { assert := New(new(testing.T)) list := []string{"Foo", "Bar"} if !assert.NotContains("Hello World", "Hello!") { t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") } if assert.NotContains("Hello World", "Hello") { t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") } if !assert.NotContains(list, "Foo!") { t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") } if assert.NotContains(list, "Foo") { t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } } func TestConditionWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Condition(func() bool { return true }, "Truth") { t.Error("Condition should return true") } if assert.Condition(func() bool { return false }, "Lie") { t.Error("Condition should return false") } } func TestDidPanicWrapper(t *testing.T) { if funcDidPanic, _ := didPanic(func() { panic("Panic!") }); !funcDidPanic { t.Error("didPanic should return true") } if funcDidPanic, _ := didPanic(func() { }); funcDidPanic { t.Error("didPanic should return false") } } func TestPanicsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Panics(func() { panic("Panic!") }) { t.Error("Panics should return true") } if assert.Panics(func() { }) { t.Error("Panics should return false") } } func TestNotPanicsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotPanics(func() { }) { t.Error("NotPanics should return true") } if assert.NotPanics(func() { panic("Panic!") }) { t.Error("NotPanics should return false") } } func TestNoErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") // now set an error err = errors.New("Some error") assert.False(mockAssert.NoError(err), "NoError with error should return False") } func TestErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.False(mockAssert.Error(err), "Error should return False for nil arg") // now set an error err = errors.New("Some error") assert.True(mockAssert.Error(err), "Error with error should return True") } func TestEqualErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.False(mockAssert.EqualError(err, ""), "EqualError should return false for nil arg") // now set an error err = errors.New("some error") assert.False(mockAssert.EqualError(err, "Not some error"), "EqualError should return false for different error string") assert.True(mockAssert.EqualError(err, "some error"), "EqualError should return true") } func TestEmptyWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.True(mockAssert.Empty(""), "Empty string is empty") assert.True(mockAssert.Empty(nil), "Nil is empty") assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") assert.True(mockAssert.Empty(0), "Zero int value is empty") assert.True(mockAssert.Empty(false), "False value is empty") assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") assert.False(mockAssert.Empty(true), "True value is not empty") } func TestNotEmptyWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.False(mockAssert.NotEmpty(""), "Empty string is empty") assert.False(mockAssert.NotEmpty(nil), "Nil is empty") assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") assert.False(mockAssert.NotEmpty(false), "False value is empty") assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") assert.True(mockAssert.NotEmpty(true), "True value is not empty") } func TestLenWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.False(mockAssert.Len(nil, 0), "nil does not have length") assert.False(mockAssert.Len(0, 0), "int does not have length") assert.False(mockAssert.Len(true, 0), "true does not have length") assert.False(mockAssert.Len(false, 0), "false does not have length") assert.False(mockAssert.Len('A', 0), "Rune does not have length") assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 cases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range cases { assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) } } func TestWithinDurationWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) a := time.Now() b := a.Add(10 * time.Second) assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") } func TestInDeltaWrapper(t *testing.T) { assert := New(new(testing.T)) True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") cases := []struct { a, b interface{} delta float64 }{ {uint8(2), uint8(1), 1}, {uint16(2), uint16(1), 1}, {uint32(2), uint32(1), 1}, {uint64(2), uint64(1), 1}, {int(2), int(1), 1}, {int8(2), int8(1), 1}, {int16(2), int16(1), 1}, {int32(2), int32(1), 1}, {int64(2), int64(1), 1}, {float32(2), float32(1), 1}, {float64(2), float64(1), 1}, } for _, tc := range cases { True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) } } func TestInEpsilonWrapper(t *testing.T) { assert := New(new(testing.T)) cases := []struct { a, b interface{} epsilon float64 }{ {uint8(2), uint16(2), .001}, {2.1, 2.2, 0.1}, {2.2, 2.1, 0.1}, {-2.1, -2.2, 0.1}, {-2.2, -2.1, 0.1}, {uint64(100), uint8(101), 0.01}, {0.1, -0.1, 2}, } for _, tc := range cases { True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } cases = []struct { a, b interface{} epsilon float64 }{ {uint8(2), int16(-2), .001}, {uint64(100), uint8(102), 0.01}, {2.1, 2.2, 0.001}, {2.2, 2.1, 0.001}, {2.1, -2.2, 1}, {2.1, "bla-bla", 0}, {0.1, -0.1, 1.99}, } for _, tc := range cases { False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } } func TestRegexpWrapper(t *testing.T) { assert := New(new(testing.T)) cases := []struct { rx, str string }{ {"^start", "start of the line"}, {"end$", "in the end"}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, } for _, tc := range cases { True(t, assert.Regexp(tc.rx, tc.str)) True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) False(t, assert.NotRegexp(tc.rx, tc.str)) False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) } cases = []struct { rx, str string }{ {"^asdfastart", "Not the start of the line"}, {"end$", "in the end."}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, } for _, tc := range cases { False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) True(t, assert.NotRegexp(tc.rx, tc.str)) True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) } } func TestZeroWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) for _, test := range zeros { assert.True(mockAssert.Zero(test), "Zero should return true for %v", test) } for _, test := range nonZeros { assert.False(mockAssert.Zero(test), "Zero should return false for %v", test) } } func TestNotZeroWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) for _, test := range zeros { assert.False(mockAssert.NotZero(test), "Zero should return true for %v", test) } for _, test := range nonZeros { assert.True(mockAssert.NotZero(test), "Zero should return false for %v", test) } } func TestJSONEqWrapper_EqualSONString(t *testing.T) { assert := New(new(testing.T)) if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) { t.Error("JSONEq should return true") } } func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { assert := New(new(testing.T)) if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) { t.Error("JSONEq should return true") } } func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { assert := New(new(testing.T)) if !assert.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") { t.Error("JSONEq should return true") } } func TestJSONEqWrapper_Array(t *testing.T) { assert := New(new(testing.T)) if !assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) { t.Error("JSONEq should return true") } } func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq(`{"foo": "bar"}`, "Not JSON") { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq("Not JSON", "Not JSON") { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) { t.Error("JSONEq should return false") } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/forward_assertions.go������������������������0000644�0610621�0607500�00000000604�13172163422�030355� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package assert // Assertions provides assertion methods around the // TestingT interface. type Assertions struct { t TestingT } // New makes a new Assertions object for the specified TestingT. func New(t TestingT) *Assertions { return &Assertions{ t: t, } } //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs ����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/errors.go������������������������������������0000644�0610621�0607500�00000000506�13172163422�025754� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package assert import ( "errors" ) // AnError is an error instance useful for testing. If the code does not care // about error specifics, and only needs to return the error for example, this // error should be used to make the test code more readable. var AnError = errors.New("assert.AnError general error for testing") ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/doc.go���������������������������������������0000644�0610621�0607500�00000002543�13172163422�025210� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. // // Example Usage // // The following is a complete example using assert in a standard test function: // import ( // "testing" // "github.com/stretchr/testify/assert" // ) // // func TestSomething(t *testing.T) { // // var a string = "Hello" // var b string = "Hello" // // assert.Equal(t, a, b, "The two words should be the same.") // // } // // if you assert many times, use the format below: // // import ( // "testing" // "github.com/stretchr/testify/assert" // ) // // func TestSomething(t *testing.T) { // assert := assert.New(t) // // var a string = "Hello" // var b string = "Hello" // // assert.Equal(a, b, "The two words should be the same.") // } // // Assertions // // Assertions allow you to easily write test code, and are global funcs in the `assert` package. // All assertion functions take, as the first argument, the `*testing.T` object provided by the // testing framework. This allows the assertion funcs to write the failings and other details to // the correct place. // // Every assertion function also takes an optional string message as the final argument, // allowing custom error messages to be appended to the message the assertion method outputs. package assert �������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/assertions_test.go���������������������������0000644�0610621�0607500�00000110011�13172163422�027662� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package assert import ( "bytes" "errors" "fmt" "io" "math" "os" "reflect" "regexp" "runtime" "strings" "testing" "time" ) var ( i interface{} zeros = []interface{}{ false, byte(0), complex64(0), complex128(0), float32(0), float64(0), int(0), int8(0), int16(0), int32(0), int64(0), rune(0), uint(0), uint8(0), uint16(0), uint32(0), uint64(0), uintptr(0), "", [0]interface{}{}, []interface{}(nil), struct{ x int }{}, (*interface{})(nil), (func())(nil), nil, interface{}(nil), map[interface{}]interface{}(nil), (chan interface{})(nil), (<-chan interface{})(nil), (chan<- interface{})(nil), } nonZeros = []interface{}{ true, byte(1), complex64(1), complex128(1), float32(1), float64(1), int(1), int8(1), int16(1), int32(1), int64(1), rune(1), uint(1), uint8(1), uint16(1), uint32(1), uint64(1), uintptr(1), "s", [1]interface{}{1}, []interface{}{}, struct{ x int }{1}, (*interface{})(&i), (func())(func() {}), interface{}(1), map[interface{}]interface{}{}, (chan interface{})(make(chan interface{})), (<-chan interface{})(make(chan interface{})), (chan<- interface{})(make(chan interface{})), } ) // AssertionTesterInterface defines an interface to be used for testing assertion methods type AssertionTesterInterface interface { TestMethod() } // AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface type AssertionTesterConformingObject struct { } func (a *AssertionTesterConformingObject) TestMethod() { } // AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface type AssertionTesterNonConformingObject struct { } func TestObjectsAreEqual(t *testing.T) { if !ObjectsAreEqual("Hello World", "Hello World") { t.Error("objectsAreEqual should return true") } if !ObjectsAreEqual(123, 123) { t.Error("objectsAreEqual should return true") } if !ObjectsAreEqual(123.5, 123.5) { t.Error("objectsAreEqual should return true") } if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) { t.Error("objectsAreEqual should return true") } if !ObjectsAreEqual(nil, nil) { t.Error("objectsAreEqual should return true") } if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual('x', "x") { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual("x", 'x') { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(0, 0.1) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(0.1, 0) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(uint32(10), int32(10)) { t.Error("objectsAreEqual should return false") } if !ObjectsAreEqualValues(uint32(10), int32(10)) { t.Error("ObjectsAreEqualValues should return true") } if ObjectsAreEqualValues(0, nil) { t.Fail() } if ObjectsAreEqualValues(nil, 0) { t.Fail() } } func TestImplements(t *testing.T) { mockT := new(testing.T) if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") } if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") } } func TestIsType(t *testing.T) { mockT := new(testing.T) if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") } if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") } } func TestEqual(t *testing.T) { mockT := new(testing.T) if !Equal(mockT, "Hello World", "Hello World") { t.Error("Equal should return true") } if !Equal(mockT, 123, 123) { t.Error("Equal should return true") } if !Equal(mockT, 123.5, 123.5) { t.Error("Equal should return true") } if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) { t.Error("Equal should return true") } if !Equal(mockT, nil, nil) { t.Error("Equal should return true") } if !Equal(mockT, int32(123), int32(123)) { t.Error("Equal should return true") } if !Equal(mockT, uint64(123), uint64(123)) { t.Error("Equal should return true") } if !Equal(mockT, &struct{}{}, &struct{}{}) { t.Error("Equal should return true (pointer equality is based on equality of underlying value)") } var m map[string]interface{} if Equal(mockT, m["bar"], "something") { t.Error("Equal should return false") } } // bufferT implements TestingT. Its implementation of Errorf writes the output that would be produced by // testing.T.Errorf to an internal bytes.Buffer. type bufferT struct { buf bytes.Buffer } func (t *bufferT) Errorf(format string, args ...interface{}) { // implementation of decorate is copied from testing.T decorate := func(s string) string { _, file, line, ok := runtime.Caller(3) // decorate + log + public function. if ok { // Truncate file name at last file name separator. if index := strings.LastIndex(file, "/"); index >= 0 { file = file[index+1:] } else if index = strings.LastIndex(file, "\\"); index >= 0 { file = file[index+1:] } } else { file = "???" line = 1 } buf := new(bytes.Buffer) // Every line is indented at least one tab. buf.WriteByte('\t') fmt.Fprintf(buf, "%s:%d: ", file, line) lines := strings.Split(s, "\n") if l := len(lines); l > 1 && lines[l-1] == "" { lines = lines[:l-1] } for i, line := range lines { if i > 0 { // Second and subsequent lines are indented an extra tab. buf.WriteString("\n\t\t") } buf.WriteString(line) } buf.WriteByte('\n') return buf.String() } t.buf.WriteString(decorate(fmt.Sprintf(format, args...))) } func TestEqualFormatting(t *testing.T) { for i, currCase := range []struct { equalWant string equalGot string msgAndArgs []interface{} want string }{ {equalWant: "want", equalGot: "got", want: "\tassertions.go:[0-9]+: \r \r\tError Trace:\t\n\t\t\r\tError: \tNot equal: \n\t\t\r\t \texpected: \"want\"\n\t\t\r\t \tactual: \"got\"\n"}, {equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{"hello, %v!", "world"}, want: "\tassertions.go:[0-9]+: \r \r\tError Trace:\t\n\t\t\r\tError: \tNot equal: \n\t\t\r\t \texpected: \"want\"\n\t\t\r\t \tactual: \"got\"\n\t\t\r\tMessages: \thello, world!\n"}, } { mockT := &bufferT{} Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...) Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i) } } func TestFormatUnequalValues(t *testing.T) { expected, actual := formatUnequalValues("foo", "bar") Equal(t, `"foo"`, expected, "value should not include type") Equal(t, `"bar"`, actual, "value should not include type") expected, actual = formatUnequalValues(123, 123) Equal(t, `123`, expected, "value should not include type") Equal(t, `123`, actual, "value should not include type") expected, actual = formatUnequalValues(int64(123), int32(123)) Equal(t, `int64(123)`, expected, "value should include type") Equal(t, `int32(123)`, actual, "value should include type") expected, actual = formatUnequalValues(int64(123), nil) Equal(t, `int64(123)`, expected, "value should include type") Equal(t, `<nil>(<nil>)`, actual, "value should include type") type testStructType struct { Val string } expected, actual = formatUnequalValues(&testStructType{Val: "test"}, &testStructType{Val: "test"}) Equal(t, `&assert.testStructType{Val:"test"}`, expected, "value should not include type annotation") Equal(t, `&assert.testStructType{Val:"test"}`, actual, "value should not include type annotation") } func TestNotNil(t *testing.T) { mockT := new(testing.T) if !NotNil(mockT, new(AssertionTesterConformingObject)) { t.Error("NotNil should return true: object is not nil") } if NotNil(mockT, nil) { t.Error("NotNil should return false: object is nil") } if NotNil(mockT, (*struct{})(nil)) { t.Error("NotNil should return false: object is (*struct{})(nil)") } } func TestNil(t *testing.T) { mockT := new(testing.T) if !Nil(mockT, nil) { t.Error("Nil should return true: object is nil") } if !Nil(mockT, (*struct{})(nil)) { t.Error("Nil should return true: object is (*struct{})(nil)") } if Nil(mockT, new(AssertionTesterConformingObject)) { t.Error("Nil should return false: object is not nil") } } func TestTrue(t *testing.T) { mockT := new(testing.T) if !True(mockT, true) { t.Error("True should return true") } if True(mockT, false) { t.Error("True should return false") } } func TestFalse(t *testing.T) { mockT := new(testing.T) if !False(mockT, false) { t.Error("False should return true") } if False(mockT, true) { t.Error("False should return false") } } func TestExactly(t *testing.T) { mockT := new(testing.T) a := float32(1) b := float64(1) c := float32(1) d := float32(2) if Exactly(mockT, a, b) { t.Error("Exactly should return false") } if Exactly(mockT, a, d) { t.Error("Exactly should return false") } if !Exactly(mockT, a, c) { t.Error("Exactly should return true") } if Exactly(mockT, nil, a) { t.Error("Exactly should return false") } if Exactly(mockT, a, nil) { t.Error("Exactly should return false") } } func TestNotEqual(t *testing.T) { mockT := new(testing.T) if !NotEqual(mockT, "Hello World", "Hello World!") { t.Error("NotEqual should return true") } if !NotEqual(mockT, 123, 1234) { t.Error("NotEqual should return true") } if !NotEqual(mockT, 123.5, 123.55) { t.Error("NotEqual should return true") } if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) { t.Error("NotEqual should return true") } if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) { t.Error("NotEqual should return true") } funcA := func() int { return 23 } funcB := func() int { return 42 } if NotEqual(mockT, funcA, funcB) { t.Error("NotEqual should return false") } if NotEqual(mockT, "Hello World", "Hello World") { t.Error("NotEqual should return false") } if NotEqual(mockT, 123, 123) { t.Error("NotEqual should return false") } if NotEqual(mockT, 123.5, 123.5) { t.Error("NotEqual should return false") } if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { t.Error("NotEqual should return false") } if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { t.Error("NotEqual should return false") } if NotEqual(mockT, &struct{}{}, &struct{}{}) { t.Error("NotEqual should return false") } } type A struct { Name, Value string } func TestContains(t *testing.T) { mockT := new(testing.T) list := []string{"Foo", "Bar"} complexList := []*A{ {"b", "c"}, {"d", "e"}, {"g", "h"}, {"j", "k"}, } simpleMap := map[interface{}]interface{}{"Foo": "Bar"} if !Contains(mockT, "Hello World", "Hello") { t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") } if Contains(mockT, "Hello World", "Salut") { t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") } if !Contains(mockT, list, "Bar") { t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") } if Contains(mockT, list, "Salut") { t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") } if !Contains(mockT, complexList, &A{"g", "h"}) { t.Error("Contains should return true: complexList contains {\"g\", \"h\"}") } if Contains(mockT, complexList, &A{"g", "e"}) { t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") } if Contains(mockT, complexList, &A{"g", "e"}) { t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") } if !Contains(mockT, simpleMap, "Foo") { t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"") } if Contains(mockT, simpleMap, "Bar") { t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"") } } func TestNotContains(t *testing.T) { mockT := new(testing.T) list := []string{"Foo", "Bar"} simpleMap := map[interface{}]interface{}{"Foo": "Bar"} if !NotContains(mockT, "Hello World", "Hello!") { t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") } if NotContains(mockT, "Hello World", "Hello") { t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") } if !NotContains(mockT, list, "Foo!") { t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") } if NotContains(mockT, list, "Foo") { t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } if NotContains(mockT, simpleMap, "Foo") { t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"") } if !NotContains(mockT, simpleMap, "Bar") { t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"") } } func TestSubset(t *testing.T) { mockT := new(testing.T) if !Subset(mockT, []int{1, 2, 3}, nil) { t.Error("Subset should return true: given subset is nil") } if !Subset(mockT, []int{1, 2, 3}, []int{}) { t.Error("Subset should return true: any set contains the nil set") } if !Subset(mockT, []int{1, 2, 3}, []int{1, 2}) { t.Error("Subset should return true: [1, 2, 3] contains [1, 2]") } if !Subset(mockT, []int{1, 2, 3}, []int{1, 2, 3}) { t.Error("Subset should return true: [1, 2, 3] contains [1, 2, 3]") } if !Subset(mockT, []string{"hello", "world"}, []string{"hello"}) { t.Error("Subset should return true: [\"hello\", \"world\"] contains [\"hello\"]") } if Subset(mockT, []string{"hello", "world"}, []string{"hello", "testify"}) { t.Error("Subset should return false: [\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]") } if Subset(mockT, []int{1, 2, 3}, []int{4, 5}) { t.Error("Subset should return false: [1, 2, 3] does not contain [4, 5]") } if Subset(mockT, []int{1, 2, 3}, []int{1, 5}) { t.Error("Subset should return false: [1, 2, 3] does not contain [1, 5]") } } func TestNotSubset(t *testing.T) { mockT := new(testing.T) if NotSubset(mockT, []int{1, 2, 3}, nil) { t.Error("NotSubset should return false: given subset is nil") } if NotSubset(mockT, []int{1, 2, 3}, []int{}) { t.Error("NotSubset should return false: any set contains the nil set") } if NotSubset(mockT, []int{1, 2, 3}, []int{1, 2}) { t.Error("NotSubset should return false: [1, 2, 3] contains [1, 2]") } if NotSubset(mockT, []int{1, 2, 3}, []int{1, 2, 3}) { t.Error("NotSubset should return false: [1, 2, 3] contains [1, 2, 3]") } if NotSubset(mockT, []string{"hello", "world"}, []string{"hello"}) { t.Error("NotSubset should return false: [\"hello\", \"world\"] contains [\"hello\"]") } if !NotSubset(mockT, []string{"hello", "world"}, []string{"hello", "testify"}) { t.Error("NotSubset should return true: [\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]") } if !NotSubset(mockT, []int{1, 2, 3}, []int{4, 5}) { t.Error("NotSubset should return true: [1, 2, 3] does not contain [4, 5]") } if !NotSubset(mockT, []int{1, 2, 3}, []int{1, 5}) { t.Error("NotSubset should return true: [1, 2, 3] does not contain [1, 5]") } } func Test_includeElement(t *testing.T) { list1 := []string{"Foo", "Bar"} list2 := []int{1, 2} simpleMap := map[interface{}]interface{}{"Foo": "Bar"} ok, found := includeElement("Hello World", "World") True(t, ok) True(t, found) ok, found = includeElement(list1, "Foo") True(t, ok) True(t, found) ok, found = includeElement(list1, "Bar") True(t, ok) True(t, found) ok, found = includeElement(list2, 1) True(t, ok) True(t, found) ok, found = includeElement(list2, 2) True(t, ok) True(t, found) ok, found = includeElement(list1, "Foo!") True(t, ok) False(t, found) ok, found = includeElement(list2, 3) True(t, ok) False(t, found) ok, found = includeElement(list2, "1") True(t, ok) False(t, found) ok, found = includeElement(simpleMap, "Foo") True(t, ok) True(t, found) ok, found = includeElement(simpleMap, "Bar") True(t, ok) False(t, found) ok, found = includeElement(1433, "1") False(t, ok) False(t, found) } func TestCondition(t *testing.T) { mockT := new(testing.T) if !Condition(mockT, func() bool { return true }, "Truth") { t.Error("Condition should return true") } if Condition(mockT, func() bool { return false }, "Lie") { t.Error("Condition should return false") } } func TestDidPanic(t *testing.T) { if funcDidPanic, _ := didPanic(func() { panic("Panic!") }); !funcDidPanic { t.Error("didPanic should return true") } if funcDidPanic, _ := didPanic(func() { }); funcDidPanic { t.Error("didPanic should return false") } } func TestPanics(t *testing.T) { mockT := new(testing.T) if !Panics(mockT, func() { panic("Panic!") }) { t.Error("Panics should return true") } if Panics(mockT, func() { }) { t.Error("Panics should return false") } } func TestPanicsWithValue(t *testing.T) { mockT := new(testing.T) if !PanicsWithValue(mockT, "Panic!", func() { panic("Panic!") }) { t.Error("PanicsWithValue should return true") } if PanicsWithValue(mockT, "Panic!", func() { }) { t.Error("PanicsWithValue should return false") } if PanicsWithValue(mockT, "at the disco", func() { panic("Panic!") }) { t.Error("PanicsWithValue should return false") } } func TestNotPanics(t *testing.T) { mockT := new(testing.T) if !NotPanics(mockT, func() { }) { t.Error("NotPanics should return true") } if NotPanics(mockT, func() { panic("Panic!") }) { t.Error("NotPanics should return false") } } func TestNoError(t *testing.T) { mockT := new(testing.T) // start with a nil error var err error True(t, NoError(mockT, err), "NoError should return True for nil arg") // now set an error err = errors.New("some error") False(t, NoError(mockT, err), "NoError with error should return False") // returning an empty error interface err = func() error { var err *customError if err != nil { t.Fatal("err should be nil here") } return err }() if err == nil { // err is not nil here! t.Errorf("Error should be nil due to empty interface: %s", err) } False(t, NoError(mockT, err), "NoError should fail with empty error interface") } type customError struct{} func (*customError) Error() string { return "fail" } func TestError(t *testing.T) { mockT := new(testing.T) // start with a nil error var err error False(t, Error(mockT, err), "Error should return False for nil arg") // now set an error err = errors.New("some error") True(t, Error(mockT, err), "Error with error should return True") // go vet check True(t, Errorf(mockT, err, "example with %s", "formatted message"), "Errorf with error should rturn True") // returning an empty error interface err = func() error { var err *customError if err != nil { t.Fatal("err should be nil here") } return err }() if err == nil { // err is not nil here! t.Errorf("Error should be nil due to empty interface: %s", err) } True(t, Error(mockT, err), "Error should pass with empty error interface") } func TestEqualError(t *testing.T) { mockT := new(testing.T) // start with a nil error var err error False(t, EqualError(mockT, err, ""), "EqualError should return false for nil arg") // now set an error err = errors.New("some error") False(t, EqualError(mockT, err, "Not some error"), "EqualError should return false for different error string") True(t, EqualError(mockT, err, "some error"), "EqualError should return true") } func Test_isEmpty(t *testing.T) { chWithValue := make(chan struct{}, 1) chWithValue <- struct{}{} True(t, isEmpty("")) True(t, isEmpty(nil)) True(t, isEmpty([]string{})) True(t, isEmpty(0)) True(t, isEmpty(int32(0))) True(t, isEmpty(int64(0))) True(t, isEmpty(false)) True(t, isEmpty(map[string]string{})) True(t, isEmpty(new(time.Time))) True(t, isEmpty(time.Time{})) True(t, isEmpty(make(chan struct{}))) False(t, isEmpty("something")) False(t, isEmpty(errors.New("something"))) False(t, isEmpty([]string{"something"})) False(t, isEmpty(1)) False(t, isEmpty(true)) False(t, isEmpty(map[string]string{"Hello": "World"})) False(t, isEmpty(chWithValue)) } func TestEmpty(t *testing.T) { mockT := new(testing.T) chWithValue := make(chan struct{}, 1) chWithValue <- struct{}{} var tiP *time.Time var tiNP time.Time var s *string var f *os.File True(t, Empty(mockT, ""), "Empty string is empty") True(t, Empty(mockT, nil), "Nil is empty") True(t, Empty(mockT, []string{}), "Empty string array is empty") True(t, Empty(mockT, 0), "Zero int value is empty") True(t, Empty(mockT, false), "False value is empty") True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty") True(t, Empty(mockT, s), "Nil string pointer is empty") True(t, Empty(mockT, f), "Nil os.File pointer is empty") True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty") True(t, Empty(mockT, tiNP), "time.Time is empty") False(t, Empty(mockT, "something"), "Non Empty string is not empty") False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty") False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty") False(t, Empty(mockT, 1), "Non-zero int value is not empty") False(t, Empty(mockT, true), "True value is not empty") False(t, Empty(mockT, chWithValue), "Channel with values is not empty") } func TestNotEmpty(t *testing.T) { mockT := new(testing.T) chWithValue := make(chan struct{}, 1) chWithValue <- struct{}{} False(t, NotEmpty(mockT, ""), "Empty string is empty") False(t, NotEmpty(mockT, nil), "Nil is empty") False(t, NotEmpty(mockT, []string{}), "Empty string array is empty") False(t, NotEmpty(mockT, 0), "Zero int value is empty") False(t, NotEmpty(mockT, false), "False value is empty") False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty") True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty") True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty") True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty") True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty") True(t, NotEmpty(mockT, true), "True value is not empty") True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty") } func Test_getLen(t *testing.T) { falseCases := []interface{}{ nil, 0, true, false, 'A', struct{}{}, } for _, v := range falseCases { ok, l := getLen(v) False(t, ok, "Expected getLen fail to get length of %#v", v) Equal(t, 0, l, "getLen should return 0 for %#v", v) } ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 trueCases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range trueCases { ok, l := getLen(c.v) True(t, ok, "Expected getLen success to get length of %#v", c.v) Equal(t, c.l, l) } } func TestLen(t *testing.T) { mockT := new(testing.T) False(t, Len(mockT, nil, 0), "nil does not have length") False(t, Len(mockT, 0, 0), "int does not have length") False(t, Len(mockT, true, 0), "true does not have length") False(t, Len(mockT, false, 0), "false does not have length") False(t, Len(mockT, 'A', 0), "Rune does not have length") False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 cases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range cases { True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) } cases = []struct { v interface{} l int }{ {[]int{1, 2, 3}, 4}, {[...]int{1, 2, 3}, 2}, {"ABC", 2}, {map[int]int{1: 2, 2: 4, 3: 6}, 4}, {ch, 2}, {[]int{}, 1}, {map[int]int{}, 1}, {make(chan int), 1}, {[]int(nil), 1}, {map[int]int(nil), 1}, {(chan int)(nil), 1}, } for _, c := range cases { False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) } } func TestWithinDuration(t *testing.T) { mockT := new(testing.T) a := time.Now() b := a.Add(10 * time.Second) True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference") False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") } func TestInDelta(t *testing.T) { mockT := new(testing.T) True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail") False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail") cases := []struct { a, b interface{} delta float64 }{ {uint8(2), uint8(1), 1}, {uint16(2), uint16(1), 1}, {uint32(2), uint32(1), 1}, {uint64(2), uint64(1), 1}, {int(2), int(1), 1}, {int8(2), int8(1), 1}, {int16(2), int16(1), 1}, {int32(2), int32(1), 1}, {int64(2), int64(1), 1}, {float32(2), float32(1), 1}, {float64(2), float64(1), 1}, } for _, tc := range cases { True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) } } func TestInDeltaSlice(t *testing.T) { mockT := new(testing.T) True(t, InDeltaSlice(mockT, []float64{1.001, 0.999}, []float64{1, 1}, 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1") True(t, InDeltaSlice(mockT, []float64{1, 2}, []float64{0, 3}, 1), "{1, 2} is element-wise close to {0, 3} in delta=1") False(t, InDeltaSlice(mockT, []float64{1, 2}, []float64{0, 3}, 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1") False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") } func TestInEpsilon(t *testing.T) { mockT := new(testing.T) cases := []struct { a, b interface{} epsilon float64 }{ {uint8(2), uint16(2), .001}, {2.1, 2.2, 0.1}, {2.2, 2.1, 0.1}, {-2.1, -2.2, 0.1}, {-2.2, -2.1, 0.1}, {uint64(100), uint8(101), 0.01}, {0.1, -0.1, 2}, {0.1, 0, 2}, {time.Second, time.Second + time.Millisecond, 0.002}, } for _, tc := range cases { True(t, InEpsilon(t, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon), "test: %q", tc) } cases = []struct { a, b interface{} epsilon float64 }{ {uint8(2), int16(-2), .001}, {uint64(100), uint8(102), 0.01}, {2.1, 2.2, 0.001}, {2.2, 2.1, 0.001}, {2.1, -2.2, 1}, {2.1, "bla-bla", 0}, {0.1, -0.1, 1.99}, {0, 0.1, 2}, // expected must be different to zero {time.Second, time.Second + 10*time.Millisecond, 0.002}, } for _, tc := range cases { False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } } func TestInEpsilonSlice(t *testing.T) { mockT := new(testing.T) True(t, InEpsilonSlice(mockT, []float64{2.2, 2.0}, []float64{2.1, 2.1}, 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06") False(t, InEpsilonSlice(mockT, []float64{2.2, 2.0}, []float64{2.1, 2.1}, 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04") False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") } func TestRegexp(t *testing.T) { mockT := new(testing.T) cases := []struct { rx, str string }{ {"^start", "start of the line"}, {"end$", "in the end"}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, } for _, tc := range cases { True(t, Regexp(mockT, tc.rx, tc.str)) True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) False(t, NotRegexp(mockT, tc.rx, tc.str)) False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) } cases = []struct { rx, str string }{ {"^asdfastart", "Not the start of the line"}, {"end$", "in the end."}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, } for _, tc := range cases { False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) True(t, NotRegexp(mockT, tc.rx, tc.str)) True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) } } func testAutogeneratedFunction() { defer func() { if err := recover(); err == nil { panic("did not panic") } CallerInfo() }() t := struct { io.Closer }{} var c io.Closer c = t c.Close() } func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) { NotPanics(t, func() { testAutogeneratedFunction() }) } func TestZero(t *testing.T) { mockT := new(testing.T) for _, test := range zeros { True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) } for _, test := range nonZeros { False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) } } func TestNotZero(t *testing.T) { mockT := new(testing.T) for _, test := range zeros { False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) } for _, test := range nonZeros { True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) } } func TestJSONEq_EqualSONString(t *testing.T) { mockT := new(testing.T) True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`)) } func TestJSONEq_EquivalentButNotEqual(t *testing.T) { mockT := new(testing.T) True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)) } func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { mockT := new(testing.T) True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}")) } func TestJSONEq_Array(t *testing.T) { mockT := new(testing.T) True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`)) } func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`)) } func TestJSONEq_HashesNotEquivalent(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)) } func TestJSONEq_ActualIsNotJSON(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON")) } func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`)) } func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, "Not JSON", "Not JSON")) } func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`)) } func TestDiff(t *testing.T) { expected := ` Diff: --- Expected +++ Actual @@ -1,3 +1,3 @@ (struct { foo string }) { - foo: (string) (len=5) "hello" + foo: (string) (len=3) "bar" } ` actual := diff( struct{ foo string }{"hello"}, struct{ foo string }{"bar"}, ) Equal(t, expected, actual) expected = ` Diff: --- Expected +++ Actual @@ -2,5 +2,5 @@ (int) 1, - (int) 2, (int) 3, - (int) 4 + (int) 5, + (int) 7 } ` actual = diff( []int{1, 2, 3, 4}, []int{1, 3, 5, 7}, ) Equal(t, expected, actual) expected = ` Diff: --- Expected +++ Actual @@ -2,4 +2,4 @@ (int) 1, - (int) 2, - (int) 3 + (int) 3, + (int) 5 } ` actual = diff( []int{1, 2, 3, 4}[0:3], []int{1, 3, 5, 7}[0:3], ) Equal(t, expected, actual) expected = ` Diff: --- Expected +++ Actual @@ -1,6 +1,6 @@ (map[string]int) (len=4) { - (string) (len=4) "four": (int) 4, + (string) (len=4) "five": (int) 5, (string) (len=3) "one": (int) 1, - (string) (len=5) "three": (int) 3, - (string) (len=3) "two": (int) 2 + (string) (len=5) "seven": (int) 7, + (string) (len=5) "three": (int) 3 } ` actual = diff( map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}, map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7}, ) Equal(t, expected, actual) } func TestDiffEmptyCases(t *testing.T) { Equal(t, "", diff(nil, nil)) Equal(t, "", diff(struct{ foo string }{}, nil)) Equal(t, "", diff(nil, struct{ foo string }{})) Equal(t, "", diff(1, 2)) Equal(t, "", diff(1, 2)) Equal(t, "", diff([]int{1}, []bool{true})) } // Ensure there are no data races func TestDiffRace(t *testing.T) { t.Parallel() expected := map[string]string{ "a": "A", "b": "B", "c": "C", } actual := map[string]string{ "d": "D", "e": "E", "f": "F", } // run diffs in parallel simulating tests with t.Parallel() numRoutines := 10 rChans := make([]chan string, numRoutines) for idx := range rChans { rChans[idx] = make(chan string) go func(ch chan string) { defer close(ch) ch <- diff(expected, actual) }(rChans[idx]) } for _, ch := range rChans { for msg := range ch { NotZero(t, msg) // dummy assert } } } type mockTestingT struct { } func (m *mockTestingT) Errorf(format string, args ...interface{}) {} func TestFailNowWithPlainTestingT(t *testing.T) { mockT := &mockTestingT{} Panics(t, func() { FailNow(mockT, "failed") }, "should panic since mockT is missing FailNow()") } type mockFailNowTestingT struct { } func (m *mockFailNowTestingT) Errorf(format string, args ...interface{}) {} func (m *mockFailNowTestingT) FailNow() {} func TestFailNowWithFullTestingT(t *testing.T) { mockT := &mockFailNowTestingT{} NotPanics(t, func() { FailNow(mockT, "failed") }, "should call mockT.FailNow() rather than panicking") } func TestBytesEqual(t *testing.T) { var cases = []struct { a, b []byte }{ {make([]byte, 2), make([]byte, 2)}, {make([]byte, 2), make([]byte, 2, 3)}, {nil, make([]byte, 0)}, } for i, c := range cases { Equal(t, reflect.DeepEqual(c.a, c.b), ObjectsAreEqual(c.a, c.b), "case %d failed", i+1) } } func BenchmarkBytesEqual(b *testing.B) { const size = 1024 * 8 s := make([]byte, size) for i := range s { s[i] = byte(i % 255) } s2 := make([]byte, size) copy(s2, s) mockT := &mockFailNowTestingT{} b.ResetTimer() for i := 0; i < b.N; i++ { Equal(mockT, s, s2) } } func TestEqualArgsValidation(t *testing.T) { err := validateEqualArgs(time.Now, time.Now) EqualError(t, err, "cannot take func type as argument") } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/assertions.go��������������������������������0000644�0610621�0607500�00000103572�13172163422�026641� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package assert import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "math" "reflect" "regexp" "runtime" "strings" "time" "unicode" "unicode/utf8" "github.com/davecgh/go-spew/spew" "github.com/pmezard/go-difflib/difflib" ) //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl // TestingT is an interface wrapper around *testing.T type TestingT interface { Errorf(format string, args ...interface{}) } // Comparison a custom function that returns true on success and false on failure type Comparison func() (success bool) /* Helper functions */ // ObjectsAreEqual determines if two objects are considered equal. // // This function does no assertion of any kind. func ObjectsAreEqual(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } if exp, ok := expected.([]byte); ok { act, ok := actual.([]byte) if !ok { return false } else if exp == nil || act == nil { return exp == nil && act == nil } return bytes.Equal(exp, act) } return reflect.DeepEqual(expected, actual) } // ObjectsAreEqualValues gets whether two objects are equal, or if their // values are equal. func ObjectsAreEqualValues(expected, actual interface{}) bool { if ObjectsAreEqual(expected, actual) { return true } actualType := reflect.TypeOf(actual) if actualType == nil { return false } expectedValue := reflect.ValueOf(expected) if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { // Attempt comparison after type conversion return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) } return false } /* CallerInfo is necessary because the assert functions use the testing object internally, causing it to print the file:line of the assert method, rather than where the problem actually occurred in calling code.*/ // CallerInfo returns an array of strings containing the file and line number // of each stack frame leading from the current test to the assert call that // failed. func CallerInfo() []string { pc := uintptr(0) file := "" line := 0 ok := false name := "" callers := []string{} for i := 0; ; i++ { pc, file, line, ok = runtime.Caller(i) if !ok { // The breaks below failed to terminate the loop, and we ran off the // end of the call stack. break } // This is a huge edge case, but it will panic if this is the case, see #180 if file == "<autogenerated>" { break } f := runtime.FuncForPC(pc) if f == nil { break } name = f.Name() // testing.tRunner is the standard library function that calls // tests. Subtests are called directly by tRunner, without going through // the Test/Benchmark/Example function that contains the t.Run calls, so // with subtests we should break when we hit tRunner, without adding it // to the list of callers. if name == "testing.tRunner" { break } parts := strings.Split(file, "/") file = parts[len(parts)-1] if len(parts) > 1 { dir := parts[len(parts)-2] if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { callers = append(callers, fmt.Sprintf("%s:%d", file, line)) } } // Drop the package segments := strings.Split(name, ".") name = segments[len(segments)-1] if isTest(name, "Test") || isTest(name, "Benchmark") || isTest(name, "Example") { break } } return callers } // Stolen from the `go test` tool. // isTest tells whether name looks like a test (or benchmark, according to prefix). // It is a Test (say) if there is a character after Test that is not a lower-case letter. // We don't want TesticularCancer. func isTest(name, prefix string) bool { if !strings.HasPrefix(name, prefix) { return false } if len(name) == len(prefix) { // "Test" is ok return true } rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) return !unicode.IsLower(rune) } // getWhitespaceString returns a string that is long enough to overwrite the default // output from the go testing framework. func getWhitespaceString() string { _, file, line, ok := runtime.Caller(1) if !ok { return "" } parts := strings.Split(file, "/") file = parts[len(parts)-1] return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) } func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { if len(msgAndArgs) == 0 || msgAndArgs == nil { return "" } if len(msgAndArgs) == 1 { return msgAndArgs[0].(string) } if len(msgAndArgs) > 1 { return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) } return "" } // Aligns the provided message so that all lines after the first line start at the same location as the first line. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the // basis on which the alignment occurs). func indentMessageLines(message string, longestLabelLen int) string { outBuf := new(bytes.Buffer) for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { // no need to align first line because it starts at the correct location (after the label) if i != 0 { // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab outBuf.WriteString("\n\r\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") } outBuf.WriteString(scanner.Text()) } return outBuf.String() } type failNower interface { FailNow() } // FailNow fails test func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { Fail(t, failureMessage, msgAndArgs...) // We cannot extend TestingT with FailNow() and // maintain backwards compatibility, so we fallback // to panicking when FailNow is not available in // TestingT. // See issue #263 if t, ok := t.(failNower); ok { t.FailNow() } else { panic("test failed and t is missing `FailNow()`") } return false } // Fail reports a failure through func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { content := []labeledContent{ {"Error Trace", strings.Join(CallerInfo(), "\n\r\t\t\t")}, {"Error", failureMessage}, } message := messageFromMsgAndArgs(msgAndArgs...) if len(message) > 0 { content = append(content, labeledContent{"Messages", message}) } t.Errorf("%s", "\r"+getWhitespaceString()+labeledOutput(content...)) return false } type labeledContent struct { label string content string } // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: // // \r\t{{label}}:{{align_spaces}}\t{{content}}\n // // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this // alignment is achieved, "\t{{content}}\n" is added for the output. // // If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. func labeledOutput(content ...labeledContent) string { longestLabel := 0 for _, v := range content { if len(v.label) > longestLabel { longestLabel = len(v.label) } } var output string for _, v := range content { output += "\r\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" } return output } // Implements asserts that an object is implemented by the specified interface. // // assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { interfaceType := reflect.TypeOf(interfaceObject).Elem() if !reflect.TypeOf(object).Implements(interfaceType) { return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) } return true } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) } return true } // Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if err := validateEqualArgs(expected, actual); err != nil { return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", expected, actual, err), msgAndArgs...) } if !ObjectsAreEqual(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ "actual: %s%s", expected, actual, diff), msgAndArgs...) } return true } // formatUnequalValues takes two values of arbitrary types and returns string // representations appropriate to be presented to the user. // // If the values are not of like type, the returned strings will be prefixed // with the type name, and the value will be enclosed in parenthesis similar // to a type conversion in the Go grammar. func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { return fmt.Sprintf("%T(%#v)", expected, expected), fmt.Sprintf("%T(%#v)", actual, actual) } return fmt.Sprintf("%#v", expected), fmt.Sprintf("%#v", actual) } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if !ObjectsAreEqualValues(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ "actual: %s%s", expected, actual, diff), msgAndArgs...) } return true } // Exactly asserts that two objects are equal is value and type. // // assert.Exactly(t, int32(123), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { aType := reflect.TypeOf(expected) bType := reflect.TypeOf(actual) if aType != bType { return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...) } return Equal(t, expected, actual, msgAndArgs...) } // NotNil asserts that the specified object is not nil. // // assert.NotNil(t, err) // // Returns whether the assertion was successful (true) or not (false). func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if !isNil(object) { return true } return Fail(t, "Expected value not to be nil.", msgAndArgs...) } // isNil checks if a specified object is nil or not, without Failing. func isNil(object interface{}) bool { if object == nil { return true } value := reflect.ValueOf(object) kind := value.Kind() if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { return true } return false } // Nil asserts that the specified object is nil. // // assert.Nil(t, err) // // Returns whether the assertion was successful (true) or not (false). func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if isNil(object) { return true } return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) } var numericZeros = []interface{}{ int(0), int8(0), int16(0), int32(0), int64(0), uint(0), uint8(0), uint16(0), uint32(0), uint64(0), float32(0), float64(0), } // isEmpty gets whether the specified object is considered empty or not. func isEmpty(object interface{}) bool { if object == nil { return true } else if object == "" { return true } else if object == false { return true } for _, v := range numericZeros { if object == v { return true } } objValue := reflect.ValueOf(object) switch objValue.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: { return (objValue.Len() == 0) } case reflect.Struct: switch object.(type) { case time.Time: return object.(time.Time).IsZero() } case reflect.Ptr: { if objValue.IsNil() { return true } switch object.(type) { case *time.Time: return object.(*time.Time).IsZero() default: return false } } } return false } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Empty(t, obj) // // Returns whether the assertion was successful (true) or not (false). func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { pass := isEmpty(object) if !pass { Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) } return pass } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmpty(t, obj) { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { pass := !isEmpty(object) if !pass { Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) } return pass } // getLen try to get length of object. // return (false, 0) if impossible. func getLen(x interface{}) (ok bool, length int) { v := reflect.ValueOf(x) defer func() { if e := recover(); e != nil { ok = false } }() return true, v.Len() } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // assert.Len(t, mySlice, 3) // // Returns whether the assertion was successful (true) or not (false). func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { ok, l := getLen(object) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) } if l != length { return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) } return true } // True asserts that the specified value is true. // // assert.True(t, myBool) // // Returns whether the assertion was successful (true) or not (false). func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { if value != true { return Fail(t, "Should be true", msgAndArgs...) } return true } // False asserts that the specified value is false. // // assert.False(t, myBool) // // Returns whether the assertion was successful (true) or not (false). func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { if value != false { return Fail(t, "Should be false", msgAndArgs...) } return true } // NotEqual asserts that the specified values are NOT equal. // // assert.NotEqual(t, obj1, obj2) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if err := validateEqualArgs(expected, actual); err != nil { return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)", expected, actual, err), msgAndArgs...) } if ObjectsAreEqual(expected, actual) { return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) } return true } // containsElement try loop over the list check if the list includes the element. // return (false, false) if impossible. // return (true, false) if element was not found. // return (true, true) if element was found. func includeElement(list interface{}, element interface{}) (ok, found bool) { listValue := reflect.ValueOf(list) elementValue := reflect.ValueOf(element) defer func() { if e := recover(); e != nil { ok = false found = false } }() if reflect.TypeOf(list).Kind() == reflect.String { return true, strings.Contains(listValue.String(), elementValue.String()) } if reflect.TypeOf(list).Kind() == reflect.Map { mapKeys := listValue.MapKeys() for i := 0; i < len(mapKeys); i++ { if ObjectsAreEqual(mapKeys[i].Interface(), element) { return true, true } } return true, false } for i := 0; i < listValue.Len(); i++ { if ObjectsAreEqual(listValue.Index(i).Interface(), element) { return true, true } } return true, false } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World") // assert.Contains(t, ["Hello", "World"], "World") // assert.Contains(t, {"Hello": "World"}, "Hello") // // Returns whether the assertion was successful (true) or not (false). func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { ok, found := includeElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) } return true } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContains(t, "Hello World", "Earth") // assert.NotContains(t, ["Hello", "World"], "Earth") // assert.NotContains(t, {"Hello": "World"}, "Earth") // // Returns whether the assertion was successful (true) or not (false). func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { ok, found := includeElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) } if found { return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) } return true } // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") // // Returns whether the assertion was successful (true) or not (false). func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if subset == nil { return true // we consider nil to be equal to the nil set } subsetValue := reflect.ValueOf(subset) defer func() { if e := recover(); e != nil { ok = false } }() listKind := reflect.TypeOf(list).Kind() subsetKind := reflect.TypeOf(subset).Kind() if listKind != reflect.Array && listKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) } if subsetKind != reflect.Array && subsetKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) } for i := 0; i < subsetValue.Len(); i++ { element := subsetValue.Index(i).Interface() ok, found := includeElement(list, element) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...) } } return true } // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") // // Returns whether the assertion was successful (true) or not (false). func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if subset == nil { return false // we consider nil to be equal to the nil set } subsetValue := reflect.ValueOf(subset) defer func() { if e := recover(); e != nil { ok = false } }() listKind := reflect.TypeOf(list).Kind() subsetKind := reflect.TypeOf(subset).Kind() if listKind != reflect.Array && listKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) } if subsetKind != reflect.Array && subsetKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) } for i := 0; i < subsetValue.Len(); i++ { element := subsetValue.Index(i).Interface() ok, found := includeElement(list, element) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) } if !found { return true } } return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) } // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { result := comp() if !result { Fail(t, "Condition failed!", msgAndArgs...) } return result } // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics // methods, and represents a simple func that takes no arguments, and returns nothing. type PanicTestFunc func() // didPanic returns true if the function passed to it panics. Otherwise, it returns false. func didPanic(f PanicTestFunc) (bool, interface{}) { didPanic := false var message interface{} func() { defer func() { if message = recover(); message != nil { didPanic = true } }() // call the target function f() }() return didPanic, message } // Panics asserts that the code inside the specified PanicTestFunc panics. // // assert.Panics(t, func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) } return true } // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { funcDidPanic, panicValue := didPanic(f) if !funcDidPanic { return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) } if panicValue != expected { return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%v\n\r\tPanic value:\t%v", f, expected, panicValue), msgAndArgs...) } return true } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanics(t, func(){ RemainCalm() }) // // Returns whether the assertion was successful (true) or not (false). func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { if funcDidPanic, panicValue := didPanic(f); funcDidPanic { return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) } return true } // WithinDuration asserts that the two times are within duration delta of each other. // // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) // // Returns whether the assertion was successful (true) or not (false). func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { dt := expected.Sub(actual) if dt < -delta || dt > delta { return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) } return true } func toFloat(x interface{}) (float64, bool) { var xf float64 xok := true switch xn := x.(type) { case uint8: xf = float64(xn) case uint16: xf = float64(xn) case uint32: xf = float64(xn) case uint64: xf = float64(xn) case int: xf = float64(xn) case int8: xf = float64(xn) case int16: xf = float64(xn) case int32: xf = float64(xn) case int64: xf = float64(xn) case float32: xf = float64(xn) case float64: xf = float64(xn) case time.Duration: xf = float64(xn) default: xok = false } return xf, xok } // InDelta asserts that the two numerals are within delta of each other. // // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) // // Returns whether the assertion was successful (true) or not (false). func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { af, aok := toFloat(expected) bf, bok := toFloat(actual) if !aok || !bok { return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) } if math.IsNaN(af) { return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...) } if math.IsNaN(bf) { return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) } dt := af - bf if dt < -delta || dt > delta { return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) } return true } // InDeltaSlice is the same as InDelta, except it compares two slices. func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Slice || reflect.TypeOf(expected).Kind() != reflect.Slice { return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) } actualSlice := reflect.ValueOf(actual) expectedSlice := reflect.ValueOf(expected) for i := 0; i < actualSlice.Len(); i++ { result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...) if !result { return result } } return true } func calcRelativeError(expected, actual interface{}) (float64, error) { af, aok := toFloat(expected) if !aok { return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) } if af == 0 { return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") } bf, bok := toFloat(actual) if !bok { return 0, fmt.Errorf("actual value %q cannot be converted to float", actual) } return math.Abs(af-bf) / math.Abs(af), nil } // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { actualEpsilon, err := calcRelativeError(expected, actual) if err != nil { return Fail(t, err.Error(), msgAndArgs...) } if actualEpsilon > epsilon { return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...) } return true } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Slice || reflect.TypeOf(expected).Kind() != reflect.Slice { return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) } actualSlice := reflect.ValueOf(actual) expectedSlice := reflect.ValueOf(expected) for i := 0; i < actualSlice.Len(); i++ { result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) if !result { return result } } return true } /* Errors */ // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { // assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { if err != nil { return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) } return true } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Error(t, err) { // assert.Equal(t, expectedError, err) // } // // Returns whether the assertion was successful (true) or not (false). func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { if err == nil { return Fail(t, "An error is expected but got nil.", msgAndArgs...) } return true } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualError(t, err, expectedErrorString) // // Returns whether the assertion was successful (true) or not (false). func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { if !Error(t, theError, msgAndArgs...) { return false } expected := errString actual := theError.Error() // don't need to use deep equals here, we know they are both strings if expected != actual { return Fail(t, fmt.Sprintf("Error message not equal:\n"+ "expected: %q\n"+ "actual: %q", expected, actual), msgAndArgs...) } return true } // matchRegexp return true if a specified regexp matches a string. func matchRegexp(rx interface{}, str interface{}) bool { var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { r = rr } else { r = regexp.MustCompile(fmt.Sprint(rx)) } return (r.FindStringIndex(fmt.Sprint(str)) != nil) } // Regexp asserts that a specified regexp matches a string. // // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") // assert.Regexp(t, "start...$", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { match := matchRegexp(rx, str) if !match { Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) } return match } // NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { match := matchRegexp(rx, str) if match { Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) } return !match } // Zero asserts that i is the zero value for its type and returns the truth. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) } return true } // NotZero asserts that i is not the zero value for its type and returns the truth. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) } return true } // JSONEq asserts that two JSON strings are equivalent. // // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) // // Returns whether the assertion was successful (true) or not (false). func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { var expectedJSONAsInterface, actualJSONAsInterface interface{} if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) } if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) } return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) } func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { t := reflect.TypeOf(v) k := t.Kind() if k == reflect.Ptr { t = t.Elem() k = t.Kind() } return t, k } // diff returns a diff of both values as long as both are of the same type and // are a struct, map, slice or array. Otherwise it returns an empty string. func diff(expected interface{}, actual interface{}) string { if expected == nil || actual == nil { return "" } et, ek := typeAndKind(expected) at, _ := typeAndKind(actual) if et != at { return "" } if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { return "" } e := spewConfig.Sdump(expected) a := spewConfig.Sdump(actual) diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ A: difflib.SplitLines(e), B: difflib.SplitLines(a), FromFile: "Expected", FromDate: "", ToFile: "Actual", ToDate: "", Context: 1, }) return "\n\nDiff:\n" + diff } // validateEqualArgs checks whether provided arguments can be safely used in the // Equal/NotEqual functions. func validateEqualArgs(expected, actual interface{}) error { if isFunction(expected) || isFunction(actual) { return errors.New("cannot take func type as argument") } return nil } func isFunction(arg interface{}) bool { if arg == nil { return false } return reflect.TypeOf(arg).Kind() == reflect.Func } var spewConfig = spew.ConfigState{ Indent: " ", DisablePointerAddresses: true, DisableCapacities: true, SortKeys: true, } ��������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/assertion_forward.go.tmpl��������������������0000644�0610621�0607500�00000000213�13172163422�031141� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{.CommentWithoutT "a"}} func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/assertion_forward.go�������������������������0000644�0610621�0607500�00000074267�13172163422�030212� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package assert import ( http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { return Condition(a.t, comp, msgAndArgs...) } // Conditionf uses a Comparison to assert a complex condition. func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool { return Conditionf(a.t, comp, msg, args...) } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Contains("Hello World", "World") // a.Contains(["Hello", "World"], "World") // a.Contains({"Hello": "World"}, "Hello") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { return Contains(a.t, s, contains, msgAndArgs...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Containsf("Hello World", "World", "error message %s", "formatted") // a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") // a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { return Containsf(a.t, s, contains, msg, args...) } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Empty(obj) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { return Empty(a.t, object, msgAndArgs...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Emptyf(obj, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool { return Emptyf(a.t, object, msg, args...) } // Equal asserts that two objects are equal. // // a.Equal(123, 123) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return Equal(a.t, expected, actual, msgAndArgs...) } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualError(err, expectedErrorString) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { return EqualError(a.t, theError, errString, msgAndArgs...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool { return EqualErrorf(a.t, theError, errString, msg, args...) } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValues(uint32(123), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return EqualValues(a.t, expected, actual, msgAndArgs...) } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { return EqualValuesf(a.t, expected, actual, msg, args...) } // Equalf asserts that two objects are equal. // // a.Equalf(123, 123, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { return Equalf(a.t, expected, actual, msg, args...) } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Error(err) { // assert.Equal(t, expectedError, err) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { return Error(a.t, err, msgAndArgs...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Errorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { return Errorf(a.t, err, msg, args...) } // Exactly asserts that two objects are equal is value and type. // // a.Exactly(int32(123), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return Exactly(a.t, expected, actual, msgAndArgs...) } // Exactlyf asserts that two objects are equal is value and type. // // a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { return Exactlyf(a.t, expected, actual, msg, args...) } // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { return Fail(a.t, failureMessage, msgAndArgs...) } // FailNow fails test func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { return FailNow(a.t, failureMessage, msgAndArgs...) } // FailNowf fails test func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool { return FailNowf(a.t, failureMessage, msg, args...) } // Failf reports a failure through func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool { return Failf(a.t, failureMessage, msg, args...) } // False asserts that the specified value is false. // // a.False(myBool) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { return False(a.t, value, msgAndArgs...) } // Falsef asserts that the specified value is false. // // a.Falsef(myBool, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool { return Falsef(a.t, value, msg, args...) } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { return HTTPBodyContains(a.t, handler, method, url, values, str) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { return HTTPBodyContainsf(a.t, handler, method, url, values, str) } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { return HTTPBodyNotContains(a.t, handler, method, url, values, str) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { return HTTPBodyNotContainsf(a.t, handler, method, url, values, str) } // HTTPError asserts that a specified handler returns an error status code. // // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPError(a.t, handler, method, url, values) } // HTTPErrorf asserts that a specified handler returns an error status code. // // a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPErrorf(a.t, handler, method, url, values) } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPRedirect(a.t, handler, method, url, values) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPRedirectf(a.t, handler, method, url, values) } // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPSuccess(a.t, handler, method, url, values) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPSuccessf(a.t, handler, method, url, values) } // Implements asserts that an object is implemented by the specified interface. // // a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { return Implements(a.t, interfaceObject, object, msgAndArgs...) } // Implementsf asserts that an object is implemented by the specified interface. // // a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { return Implementsf(a.t, interfaceObject, object, msg, args...) } // InDelta asserts that the two numerals are within delta of each other. // // a.InDelta(math.Pi, (22 / 7.0), 0.01) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { return InDelta(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaSlice is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { return InDeltaSlicef(a.t, expected, actual, delta, msg, args...) } // InDeltaf asserts that the two numerals are within delta of each other. // // a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { return InDeltaf(a.t, expected, actual, delta, msg, args...) } // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { return InEpsilonf(a.t, expected, actual, epsilon, msg, args...) } // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { return IsType(a.t, expectedType, object, msgAndArgs...) } // IsTypef asserts that the specified objects are of the same type. func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { return IsTypef(a.t, expectedType, object, msg, args...) } // JSONEq asserts that two JSON strings are equivalent. // // a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { return JSONEq(a.t, expected, actual, msgAndArgs...) } // JSONEqf asserts that two JSON strings are equivalent. // // a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool { return JSONEqf(a.t, expected, actual, msg, args...) } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // a.Len(mySlice, 3) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { return Len(a.t, object, length, msgAndArgs...) } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // a.Lenf(mySlice, 3, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool { return Lenf(a.t, object, length, msg, args...) } // Nil asserts that the specified object is nil. // // a.Nil(err) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { return Nil(a.t, object, msgAndArgs...) } // Nilf asserts that the specified object is nil. // // a.Nilf(err, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool { return Nilf(a.t, object, msg, args...) } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoError(err) { // assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { return NoError(a.t, err, msgAndArgs...) } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoErrorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool { return NoErrorf(a.t, err, msg, args...) } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContains("Hello World", "Earth") // a.NotContains(["Hello", "World"], "Earth") // a.NotContains({"Hello": "World"}, "Earth") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { return NotContains(a.t, s, contains, msgAndArgs...) } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") // a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") // a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { return NotContainsf(a.t, s, contains, msg, args...) } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmpty(obj) { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { return NotEmpty(a.t, object, msgAndArgs...) } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmptyf(obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool { return NotEmptyf(a.t, object, msg, args...) } // NotEqual asserts that the specified values are NOT equal. // // a.NotEqual(obj1, obj2) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return NotEqual(a.t, expected, actual, msgAndArgs...) } // NotEqualf asserts that the specified values are NOT equal. // // a.NotEqualf(obj1, obj2, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { return NotEqualf(a.t, expected, actual, msg, args...) } // NotNil asserts that the specified object is not nil. // // a.NotNil(err) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { return NotNil(a.t, object, msgAndArgs...) } // NotNilf asserts that the specified object is not nil. // // a.NotNilf(err, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool { return NotNilf(a.t, object, msg, args...) } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanics(func(){ RemainCalm() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { return NotPanics(a.t, f, msgAndArgs...) } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool { return NotPanicsf(a.t, f, msg, args...) } // NotRegexp asserts that a specified regexp does not match a string. // // a.NotRegexp(regexp.MustCompile("starts"), "it's starting") // a.NotRegexp("^start", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { return NotRegexp(a.t, rx, str, msgAndArgs...) } // NotRegexpf asserts that a specified regexp does not match a string. // // a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") // a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { return NotRegexpf(a.t, rx, str, msg, args...) } // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { return NotSubset(a.t, list, subset, msgAndArgs...) } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { return NotSubsetf(a.t, list, subset, msg, args...) } // NotZero asserts that i is not the zero value for its type and returns the truth. func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { return NotZero(a.t, i, msgAndArgs...) } // NotZerof asserts that i is not the zero value for its type and returns the truth. func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bool { return NotZerof(a.t, i, msg, args...) } // Panics asserts that the code inside the specified PanicTestFunc panics. // // a.Panics(func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { return Panics(a.t, f, msgAndArgs...) } // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // a.PanicsWithValue("crazy error", func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { return PanicsWithValue(a.t, expected, f, msgAndArgs...) } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { return PanicsWithValuef(a.t, expected, f, msg, args...) } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool { return Panicsf(a.t, f, msg, args...) } // Regexp asserts that a specified regexp matches a string. // // a.Regexp(regexp.MustCompile("start"), "it's starting") // a.Regexp("start...$", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { return Regexp(a.t, rx, str, msgAndArgs...) } // Regexpf asserts that a specified regexp matches a string. // // a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") // a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { return Regexpf(a.t, rx, str, msg, args...) } // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { return Subset(a.t, list, subset, msgAndArgs...) } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { return Subsetf(a.t, list, subset, msg, args...) } // True asserts that the specified value is true. // // a.True(myBool) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { return True(a.t, value, msgAndArgs...) } // Truef asserts that the specified value is true. // // a.Truef(myBool, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool { return Truef(a.t, value, msg, args...) } // WithinDuration asserts that the two times are within duration delta of each other. // // a.WithinDuration(time.Now(), time.Now(), 10*time.Second) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } // WithinDurationf asserts that the two times are within duration delta of each other. // // a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { return WithinDurationf(a.t, expected, actual, delta, msg, args...) } // Zero asserts that i is the zero value for its type and returns the truth. func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { return Zero(a.t, i, msgAndArgs...) } // Zerof asserts that i is the zero value for its type and returns the truth. func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool { return Zerof(a.t, i, msg, args...) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/assertion_format.go.tmpl���������������������0000644�0610621�0607500�00000000214�13172163422�030766� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{{.CommentFormat}} func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool { return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}}) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/assert/assertion_format.go��������������������������0000644�0610621�0607500�00000041623�13172163422�030024� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package assert import ( http "net/http" url "net/url" time "time" ) // Conditionf uses a Comparison to assert a complex condition. func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool { return Condition(t, comp, append([]interface{}{msg}, args...)...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") // assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") // assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { return Contains(t, s, contains, append([]interface{}{msg}, args...)...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Emptyf(t, obj, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { return Empty(t, object, append([]interface{}{msg}, args...)...) } // Equalf asserts that two objects are equal. // // assert.Equalf(t, 123, 123, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { return Equal(t, expected, actual, append([]interface{}{msg}, args...)...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Errorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } // // Returns whether the assertion was successful (true) or not (false). func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { return Error(t, err, append([]interface{}{msg}, args...)...) } // Exactlyf asserts that two objects are equal is value and type. // // assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...) } // Failf reports a failure through func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { return Fail(t, failureMessage, append([]interface{}{msg}, args...)...) } // FailNowf fails test func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...) } // Falsef asserts that the specified value is false. // // assert.Falsef(t, myBool, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { return False(t, value, append([]interface{}{msg}, args...)...) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { return HTTPBodyContains(t, handler, method, url, values, str) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { return HTTPBodyNotContains(t, handler, method, url, values, str) } // HTTPErrorf asserts that a specified handler returns an error status code. // // assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPError(t, handler, method, url, values) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPRedirect(t, handler, method, url, values) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPSuccess(t, handler, method, url, values) } // Implementsf asserts that an object is implemented by the specified interface. // // assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) } // InDeltaf asserts that the two numerals are within delta of each other. // // assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) // // Returns whether the assertion was successful (true) or not (false). func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) } // IsTypef asserts that the specified objects are of the same type. func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...) } // JSONEqf asserts that two JSON strings are equivalent. // // assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...) } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // assert.Lenf(t, mySlice, 3, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { return Len(t, object, length, append([]interface{}{msg}, args...)...) } // Nilf asserts that the specified object is nil. // // assert.Nilf(t, err, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { return Nil(t, object, append([]interface{}{msg}, args...)...) } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoErrorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { return NoError(t, err, append([]interface{}{msg}, args...)...) } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") // assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") // assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmptyf(t, obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { return NotEmpty(t, object, append([]interface{}{msg}, args...)...) } // NotEqualf asserts that the specified values are NOT equal. // // assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) } // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { return NotNil(t, object, append([]interface{}{msg}, args...)...) } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { return NotPanics(t, f, append([]interface{}{msg}, args...)...) } // NotRegexpf asserts that a specified regexp does not match a string. // // assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") // assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...) } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...) } // NotZerof asserts that i is not the zero value for its type and returns the truth. func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { return NotZero(t, i, append([]interface{}{msg}, args...)...) } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { return Panics(t, f, append([]interface{}{msg}, args...)...) } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...) } // Regexpf asserts that a specified regexp matches a string. // // assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") // assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { return Regexp(t, rx, str, append([]interface{}{msg}, args...)...) } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { return Subset(t, list, subset, append([]interface{}{msg}, args...)...) } // Truef asserts that the specified value is true. // // assert.Truef(t, myBool, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { return True(t, value, append([]interface{}{msg}, args...)...) } // WithinDurationf asserts that the two times are within duration delta of each other. // // assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // Zerof asserts that i is the zero value for its type and returns the truth. func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { return Zero(t, i, append([]interface{}{msg}, args...)...) } �������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/_codegen/�������������������������������������������0000755�0610621�0607500�00000000000�13172163422�024352� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/_codegen/main.go������������������������������������0000644�0610621�0607500�00000016552�13172163422�025636� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// This program reads all assertion functions from the assert package and // automatically generates the corresponding requires and forwarded assertions package main import ( "bytes" "flag" "fmt" "go/ast" "go/build" "go/doc" "go/format" "go/importer" "go/parser" "go/token" "go/types" "io" "io/ioutil" "log" "os" "path" "regexp" "strings" "text/template" "github.com/ernesto-jimenez/gogen/imports" ) var ( pkg = flag.String("assert-path", "github.com/stretchr/testify/assert", "Path to the assert package") includeF = flag.Bool("include-format-funcs", false, "include format functions such as Errorf and Equalf") outputPkg = flag.String("output-package", "", "package for the resulting code") tmplFile = flag.String("template", "", "What file to load the function template from") out = flag.String("out", "", "What file to write the source code to") ) func main() { flag.Parse() scope, docs, err := parsePackageSource(*pkg) if err != nil { log.Fatal(err) } importer, funcs, err := analyzeCode(scope, docs) if err != nil { log.Fatal(err) } if err := generateCode(importer, funcs); err != nil { log.Fatal(err) } } func generateCode(importer imports.Importer, funcs []testFunc) error { buff := bytes.NewBuffer(nil) tmplHead, tmplFunc, err := parseTemplates() if err != nil { return err } // Generate header if err := tmplHead.Execute(buff, struct { Name string Imports map[string]string }{ *outputPkg, importer.Imports(), }); err != nil { return err } // Generate funcs for _, fn := range funcs { buff.Write([]byte("\n\n")) if err := tmplFunc.Execute(buff, &fn); err != nil { return err } } code, err := format.Source(buff.Bytes()) if err != nil { return err } // Write file output, err := outputFile() if err != nil { return err } defer output.Close() _, err = io.Copy(output, bytes.NewReader(code)) return err } func parseTemplates() (*template.Template, *template.Template, error) { tmplHead, err := template.New("header").Parse(headerTemplate) if err != nil { return nil, nil, err } if *tmplFile != "" { f, err := ioutil.ReadFile(*tmplFile) if err != nil { return nil, nil, err } funcTemplate = string(f) } tmpl, err := template.New("function").Parse(funcTemplate) if err != nil { return nil, nil, err } return tmplHead, tmpl, nil } func outputFile() (*os.File, error) { filename := *out if filename == "-" || (filename == "" && *tmplFile == "") { return os.Stdout, nil } if filename == "" { filename = strings.TrimSuffix(strings.TrimSuffix(*tmplFile, ".tmpl"), ".go") + ".go" } return os.Create(filename) } // analyzeCode takes the types scope and the docs and returns the import // information and information about all the assertion functions. func analyzeCode(scope *types.Scope, docs *doc.Package) (imports.Importer, []testFunc, error) { testingT := scope.Lookup("TestingT").Type().Underlying().(*types.Interface) importer := imports.New(*outputPkg) var funcs []testFunc // Go through all the top level functions for _, fdocs := range docs.Funcs { // Find the function obj := scope.Lookup(fdocs.Name) fn, ok := obj.(*types.Func) if !ok { continue } // Check function signature has at least two arguments sig := fn.Type().(*types.Signature) if sig.Params().Len() < 2 { continue } // Check first argument is of type testingT first, ok := sig.Params().At(0).Type().(*types.Named) if !ok { continue } firstType, ok := first.Underlying().(*types.Interface) if !ok { continue } if !types.Implements(firstType, testingT) { continue } // Skip functions ending with f if strings.HasSuffix(fdocs.Name, "f") && !*includeF { continue } funcs = append(funcs, testFunc{*outputPkg, fdocs, fn}) importer.AddImportsFrom(sig.Params()) } return importer, funcs, nil } // parsePackageSource returns the types scope and the package documentation from the package func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error) { pd, err := build.Import(pkg, ".", 0) if err != nil { return nil, nil, err } fset := token.NewFileSet() files := make(map[string]*ast.File) fileList := make([]*ast.File, len(pd.GoFiles)) for i, fname := range pd.GoFiles { src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname)) if err != nil { return nil, nil, err } f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors) if err != nil { return nil, nil, err } files[fname] = f fileList[i] = f } cfg := types.Config{ Importer: importer.Default(), } info := types.Info{ Defs: make(map[*ast.Ident]types.Object), } tp, err := cfg.Check(pkg, fset, fileList, &info) if err != nil { return nil, nil, err } scope := tp.Scope() ap, _ := ast.NewPackage(fset, files, nil, nil) docs := doc.New(ap, pkg, 0) return scope, docs, nil } type testFunc struct { CurrentPkg string DocInfo *doc.Func TypeInfo *types.Func } func (f *testFunc) Qualifier(p *types.Package) string { if p == nil || p.Name() == f.CurrentPkg { return "" } return p.Name() } func (f *testFunc) Params() string { sig := f.TypeInfo.Type().(*types.Signature) params := sig.Params() p := "" comma := "" to := params.Len() var i int if sig.Variadic() { to-- } for i = 1; i < to; i++ { param := params.At(i) p += fmt.Sprintf("%s%s %s", comma, param.Name(), types.TypeString(param.Type(), f.Qualifier)) comma = ", " } if sig.Variadic() { param := params.At(params.Len() - 1) p += fmt.Sprintf("%s%s ...%s", comma, param.Name(), types.TypeString(param.Type().(*types.Slice).Elem(), f.Qualifier)) } return p } func (f *testFunc) ForwardedParams() string { sig := f.TypeInfo.Type().(*types.Signature) params := sig.Params() p := "" comma := "" to := params.Len() var i int if sig.Variadic() { to-- } for i = 1; i < to; i++ { param := params.At(i) p += fmt.Sprintf("%s%s", comma, param.Name()) comma = ", " } if sig.Variadic() { param := params.At(params.Len() - 1) p += fmt.Sprintf("%s%s...", comma, param.Name()) } return p } func (f *testFunc) ParamsFormat() string { return strings.Replace(f.Params(), "msgAndArgs", "msg string, args", 1) } func (f *testFunc) ForwardedParamsFormat() string { return strings.Replace(f.ForwardedParams(), "msgAndArgs", "append([]interface{}{msg}, args...)", 1) } func (f *testFunc) Comment() string { return "// " + strings.Replace(strings.TrimSpace(f.DocInfo.Doc), "\n", "\n// ", -1) } func (f *testFunc) CommentFormat() string { search := fmt.Sprintf("%s", f.DocInfo.Name) replace := fmt.Sprintf("%sf", f.DocInfo.Name) comment := strings.Replace(f.Comment(), search, replace, -1) exp := regexp.MustCompile(replace + `\(((\(\)|[^)])+)\)`) return exp.ReplaceAllString(comment, replace+`($1, "error message %s", "formatted")`) } func (f *testFunc) CommentWithoutT(receiver string) string { search := fmt.Sprintf("assert.%s(t, ", f.DocInfo.Name) replace := fmt.Sprintf("%s.%s(", receiver, f.DocInfo.Name) return strings.Replace(f.Comment(), search, replace, -1) } var headerTemplate = `/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package {{.Name}} import ( {{range $path, $name := .Imports}} {{$name}} "{{$path}}"{{end}} ) ` var funcTemplate = `{{.Comment}} func (fwd *AssertionsForwarder) {{.DocInfo.Name}}({{.Params}}) bool { return assert.{{.DocInfo.Name}}({{.ForwardedParams}}) }` ������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/README.md�������������������������������������������0000644�0610621�0607500�00000026035�13172163422�024074� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Testify - Thou Shalt Write Tests ================================ [![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify) Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend. Features include: * [Easy assertions](#assert-package) * [Mocking](#mock-package) * [HTTP response trapping](#http-package) * [Testing suite interfaces and functions](#suite-package) Get started: * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date) * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing * Check out the API Documentation http://godoc.org/github.com/stretchr/testify * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc) * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development) [`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package ------------------------------------------------------------------------------------------- The `assert` package provides some helpful methods that allow you to write better test code in Go. * Prints friendly, easy to read failure descriptions * Allows for very readable code * Optionally annotate each assertion with a message See it in action: ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { // assert equality assert.Equal(t, 123, 123, "they should be equal") // assert inequality assert.NotEqual(t, 123, 456, "they should not be equal") // assert for nil (good for errors) assert.Nil(t, object) // assert for not nil (good when you expect something) if assert.NotNil(t, object) { // now we know that object isn't nil, we are safe to make // further assertions without causing any errors assert.Equal(t, "Something", object.Value) } } ``` * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities. * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions. if you assert many times, use the below: ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { assert := assert.New(t) // assert equality assert.Equal(123, 123, "they should be equal") // assert inequality assert.NotEqual(123, 456, "they should not be equal") // assert for nil (good for errors) assert.Nil(object) // assert for not nil (good when you expect something) if assert.NotNil(object) { // now we know that object isn't nil, we are safe to make // further assertions without causing any errors assert.Equal("Something", object.Value) } } ``` [`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package --------------------------------------------------------------------------------------------- The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test. See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details. [`http`](http://godoc.org/github.com/stretchr/testify/http "API documentation") package --------------------------------------------------------------------------------------- The `http` package contains test objects useful for testing code that relies on the `net/http` package. Check out the [(deprecated) API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http). We recommend you use [httptest](http://golang.org/pkg/net/http/httptest) instead. [`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package ---------------------------------------------------------------------------------------- The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code. An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened: ```go package yours import ( "testing" "github.com/stretchr/testify/mock" ) /* Test objects */ // MyMockedObject is a mocked object that implements an interface // that describes an object that the code I am testing relies on. type MyMockedObject struct{ mock.Mock } // DoSomething is a method on MyMockedObject that implements some interface // and just records the activity, and returns what the Mock object tells it to. // // In the real object, this method would do something useful, but since this // is a mocked object - we're just going to stub it out. // // NOTE: This method is not being tested here, code that uses this object is. func (m *MyMockedObject) DoSomething(number int) (bool, error) { args := m.Called(number) return args.Bool(0), args.Error(1) } /* Actual test functions */ // TestSomething is an example of how to use our test object to // make assertions about some target code we are testing. func TestSomething(t *testing.T) { // create an instance of our test object testObj := new(MyMockedObject) // setup expectations testObj.On("DoSomething", 123).Return(true, nil) // call the code we are testing targetFuncThatDoesSomethingWithObj(testObj) // assert that the expectations were met testObj.AssertExpectations(t) } ``` For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock). You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker. [`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package ----------------------------------------------------------------------------------------- The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal. An example suite is shown below: ```go // Basic imports import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including a T() method which // returns the current testing context type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } // Make sure that VariableThatShouldStartAtFive is set to five // before each test func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } // All methods that begin with "Test" are run as tests within a // suite. func (suite *ExampleTestSuite) TestExample() { assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) } ``` For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go) For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite). `Suite` object has assertion methods: ```go // Basic imports import ( "testing" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including assertion methods. type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } // Make sure that VariableThatShouldStartAtFive is set to five // before each test func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } // All methods that begin with "Test" are run as tests within a // suite. func (suite *ExampleTestSuite) TestExample() { suite.Equal(suite.VariableThatShouldStartAtFive, 5) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) } ``` ------ Installation ============ To install Testify, use `go get`: * Latest version: go get github.com/stretchr/testify * Specific version: go get gopkg.in/stretchr/testify.v1 This will then make the following packages available to you: github.com/stretchr/testify/assert github.com/stretchr/testify/mock github.com/stretchr/testify/http Import the `testify/assert` package into your code using this template: ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { assert.True(t, true, "True is true!") } ``` ------ Staying up to date ================== To update Testify to the latest version, use `go get -u github.com/stretchr/testify`. ------ Version History =============== * 1.0 - New package versioning strategy adopted. ------ Contributing ============ Please feel free to submit issues, fork the repository and send pull requests! When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it. ------ Licence ======= Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell Please consider promoting this project if you find it useful. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/LICENSE���������������������������������������������0000644�0610621�0607500�00000002200�13172163422�023606� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell Please consider promoting this project if you find it useful. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/LICENCE.txt�����������������������������������������0000644�0610621�0607500�00000002200�13172163422�024404� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell Please consider promoting this project if you find it useful. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/Godeps/���������������������������������������������0000755�0610621�0607500�00000000000�13172163422�024030� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/Godeps/Readme���������������������������������������0000644�0610621�0607500�00000000210�13172163422�025141� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������This directory tree is generated automatically by godep. Please do not edit. See https://github.com/tools/godep for more information. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/Godeps/Godeps.json����������������������������������0000644�0610621�0607500�00000001003�13172163422�026136� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "ImportPath": "github.com/stretchr/testify", "GoVersion": "go1.5", "GodepVersion": "v74", "Packages": [ "./..." ], "Deps": [ { "ImportPath": "github.com/davecgh/go-spew/spew", "Comment": "v1.0.0-3-g6d21280", "Rev": "04cdfd42973bb9c8589fd6a731800cf222fde1a9" }, { "ImportPath": "github.com/pmezard/go-difflib/difflib", "Rev": "d8ed2627bdf02c080bf22230dbb337003b7aba2d" }, { "ImportPath": "github.com/stretchr/objx", "Rev": "cbeaeb16a013161a98496fad62933b1d21786672" } ] } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/.travis.yml�����������������������������������������0000644�0610621�0607500�00000000267�13172163422�024725� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go sudo: false go: - 1.4 - 1.5 - 1.6 - 1.7 - 1.8 - tip script: - ./.travis.gogenerate.sh - ./.travis.gofmt.sh - ./.travis.govet.sh - go test -v ./... �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/.travis.govet.sh������������������������������������0000755�0610621�0607500�00000000212�13172163422�025652� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash cd "$(dirname $0)" DIRS=". assert require mock _codegen" set -e for subdir in $DIRS; do pushd $subdir go vet popd done ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/.travis.gogenerate.sh�������������������������������0000755�0610621�0607500�00000000357�13172163422�026660� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash if [[ "$TRAVIS_GO_VERSION" =~ ^1\.[45](\..*)?$ ]]; then exit 0 fi go get github.com/ernesto-jimenez/gogen/imports go generate ./... if [ -n "$(git diff)" ]; then echo "Go generate had not been run" git diff exit 1 fi ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/stretchr/testify/.travis.gofmt.sh������������������������������������0000755�0610621�0607500�00000000151�13172163422�025644� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash if [ -n "$(gofmt -l .)" ]; then echo "Go code is not formatted:" gofmt -d . exit 1 fi �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/����������������������������������������������������������0000755�0610621�0607500�00000000000�13172163417�021447� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/����������������������������������������������0000755�0610621�0607500�00000000000�13172163417�023773� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/wrap_test.go����������������������������������0000644�0610621�0607500�00000003030�13172163417�026326� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Oleku Konko All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. // This module is a Table Writer API for the Go Programming Language. // The protocols were written in pure Go and works on windows and unix systems package tablewriter import ( "strings" "testing" "github.com/mattn/go-runewidth" ) var text = "The quick brown fox jumps over the lazy dog." func TestWrap(t *testing.T) { exp := []string{ "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."} got, _ := WrapString(text, 6) if len(exp) != len(got) { t.Fail() } } func TestWrapOneLine(t *testing.T) { exp := "The quick brown fox jumps over the lazy dog." words, _ := WrapString(text, 500) got := strings.Join(words, string(sp)) if exp != got { t.Errorf("expected: %q, got: %q", exp, got) } } func TestUnicode(t *testing.T) { input := "ÄŒeská Å™eÅ™icha" var wordsUnicode []string if runewidth.IsEastAsian() { wordsUnicode, _ = WrapString(input, 14) } else { wordsUnicode, _ = WrapString(input, 13) } // input contains 13 (or 14 for CJK) runes, so it fits on one line. if len(wordsUnicode) != 1 { t.Fail() } } func TestDisplayWidth(t *testing.T) { input := "ÄŒeská Å™eÅ™icha" want := 13 if runewidth.IsEastAsian() { want = 14 } if n := DisplayWidth(input); n != want { t.Errorf("Wants: %d Got: %d", want, n) } input = "\033[43;30m" + input + "\033[00m" if n := DisplayWidth(input); n != want { t.Errorf("Wants: %d Got: %d", want, n) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/wrap.go���������������������������������������0000644�0610621�0607500�00000005215�13172163417�025276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Oleku Konko All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. // This module is a Table Writer API for the Go Programming Language. // The protocols were written in pure Go and works on windows and unix systems package tablewriter import ( "math" "strings" "github.com/mattn/go-runewidth" ) var ( nl = "\n" sp = " " ) const defaultPenalty = 1e5 // Wrap wraps s into a paragraph of lines of length lim, with minimal // raggedness. func WrapString(s string, lim int) ([]string, int) { words := strings.Split(strings.Replace(s, nl, sp, -1), sp) var lines []string max := 0 for _, v := range words { max = runewidth.StringWidth(v) if max > lim { lim = max } } for _, line := range WrapWords(words, 1, lim, defaultPenalty) { lines = append(lines, strings.Join(line, sp)) } return lines, lim } // WrapWords is the low-level line-breaking algorithm, useful if you need more // control over the details of the text wrapping process. For most uses, // WrapString will be sufficient and more convenient. // // WrapWords splits a list of words into lines with minimal "raggedness", // treating each rune as one unit, accounting for spc units between adjacent // words on each line, and attempting to limit lines to lim units. Raggedness // is the total error over all lines, where error is the square of the // difference of the length of the line and lim. Too-long lines (which only // happen when a single word is longer than lim units) have pen penalty units // added to the error. func WrapWords(words []string, spc, lim, pen int) [][]string { n := len(words) length := make([][]int, n) for i := 0; i < n; i++ { length[i] = make([]int, n) length[i][i] = runewidth.StringWidth(words[i]) for j := i + 1; j < n; j++ { length[i][j] = length[i][j-1] + spc + runewidth.StringWidth(words[j]) } } nbrk := make([]int, n) cost := make([]int, n) for i := range cost { cost[i] = math.MaxInt32 } for i := n - 1; i >= 0; i-- { if length[i][n-1] <= lim { cost[i] = 0 nbrk[i] = n } else { for j := i + 1; j < n; j++ { d := lim - length[i][j-1] c := d*d + cost[j] if length[i][j-1] > lim { c += pen // too-long lines get a worse penalty } if c < cost[i] { cost[i] = c nbrk[i] = j } } } } var lines [][]string i := 0 for i < n { lines = append(lines, words[i:nbrk[i]]) i = nbrk[i] } return lines } // getLines decomposes a multiline string into a slice of strings. func getLines(s string) []string { var lines []string for _, line := range strings.Split(s, nl) { lines = append(lines, line) } return lines } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/util.go���������������������������������������0000644�0610621�0607500�00000003420�13172163417�025276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Oleku Konko All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. // This module is a Table Writer API for the Go Programming Language. // The protocols were written in pure Go and works on windows and unix systems package tablewriter import ( "math" "regexp" "strings" "github.com/mattn/go-runewidth" ) var ansi = regexp.MustCompile("\033\\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]") func DisplayWidth(str string) int { return runewidth.StringWidth(ansi.ReplaceAllLiteralString(str, "")) } // Simple Condition for string // Returns value based on condition func ConditionString(cond bool, valid, inValid string) string { if cond { return valid } return inValid } // Format Table Header // Replace _ , . and spaces func Title(name string) string { name = strings.Replace(name, "_", " ", -1) name = strings.Replace(name, ".", " ", -1) name = strings.TrimSpace(name) return strings.ToUpper(name) } // Pad String // Attempts to play string in the center func Pad(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { gapLeft := int(math.Ceil(float64(gap / 2))) gapRight := gap - gapLeft return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight) } return s } // Pad String Right position // This would pace string at the left side fo the screen func PadRight(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { return s + strings.Repeat(string(pad), gap) } return s } // Pad String Left position // This would pace string at the right side fo the screen func PadLeft(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { return strings.Repeat(string(pad), gap) + s } return s } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/test_info.csv���������������������������������0000644�0610621�0607500�00000000221�13172163417�026475� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Field,Type,Null,Key,Default,Extra user_id,smallint(5),NO,PRI,NULL,auto_increment username,varchar(10),NO,,NULL, password,varchar(100),NO,,NULL, �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/test.csv��������������������������������������0000644�0610621�0607500�00000000123�13172163417�025463� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������first_name,last_name,ssn John,Barry,123456 Kathy,Smith,687987 Bob,McCornick,3979870���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/table_with_color.go���������������������������0000644�0610621�0607500�00000004662�13172163417�027652� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package tablewriter import ( "fmt" "strconv" "strings" ) const ESC = "\033" const SEP = ";" const ( BgBlackColor int = iota + 40 BgRedColor BgGreenColor BgYellowColor BgBlueColor BgMagentaColor BgCyanColor BgWhiteColor ) const ( FgBlackColor int = iota + 30 FgRedColor FgGreenColor FgYellowColor FgBlueColor FgMagentaColor FgCyanColor FgWhiteColor ) const ( BgHiBlackColor int = iota + 100 BgHiRedColor BgHiGreenColor BgHiYellowColor BgHiBlueColor BgHiMagentaColor BgHiCyanColor BgHiWhiteColor ) const ( FgHiBlackColor int = iota + 90 FgHiRedColor FgHiGreenColor FgHiYellowColor FgHiBlueColor FgHiMagentaColor FgHiCyanColor FgHiWhiteColor ) const ( Normal = 0 Bold = 1 UnderlineSingle = 4 Italic ) type Colors []int func startFormat(seq string) string { return fmt.Sprintf("%s[%sm", ESC, seq) } func stopFormat() string { return fmt.Sprintf("%s[%dm", ESC, Normal) } // Making the SGR (Select Graphic Rendition) sequence. func makeSequence(codes []int) string { codesInString := []string{} for _, code := range codes { codesInString = append(codesInString, strconv.Itoa(code)) } return strings.Join(codesInString, SEP) } // Adding ANSI escape sequences before and after string func format(s string, codes interface{}) string { var seq string switch v := codes.(type) { case string: seq = v case []int: seq = makeSequence(v) default: return s } if len(seq) == 0 { return s } return startFormat(seq) + s + stopFormat() } // Adding header colors (ANSI codes) func (t *Table) SetHeaderColor(colors ...Colors) { if t.colSize != len(colors) { panic("Number of header colors must be equal to number of headers.") } for i := 0; i < len(colors); i++ { t.headerParams = append(t.headerParams, makeSequence(colors[i])) } } // Adding column colors (ANSI codes) func (t *Table) SetColumnColor(colors ...Colors) { if t.colSize != len(colors) { panic("Number of column colors must be equal to number of headers.") } for i := 0; i < len(colors); i++ { t.columnsParams = append(t.columnsParams, makeSequence(colors[i])) } } // Adding column colors (ANSI codes) func (t *Table) SetFooterColor(colors ...Colors) { if len(t.footers) != len(colors) { panic("Number of footer colors must be equal to number of footer.") } for i := 0; i < len(colors); i++ { t.footerParams = append(t.footerParams, makeSequence(colors[i])) } } func Color(colors ...int) []int { return colors } ������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/table_test.go���������������������������������0000644�0610621�0607500�00000064173�13172163417�026463� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Oleku Konko All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. // This module is a Table Writer API for the Go Programming Language. // The protocols were written in pure Go and works on windows and unix systems package tablewriter import ( "bytes" "fmt" "io" "os" "reflect" "strings" "testing" ) func ExampleShort() { data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } table := NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Sign", "Rating"}) for _, v := range data { table.Append(v) } table.Render() // Output: +------+-----------------------+--------+ // | NAME | SIGN | RATING | // +------+-----------------------+--------+ // | A | The Good | 500 | // | B | The Very very Bad Man | 288 | // | C | The Ugly | 120 | // | D | The Gopher | 800 | // +------+-----------------------+--------+ } func ExampleLong() { data := [][]string{ []string{"Learn East has computers with adapted keyboards with enlarged print etc", " Some Data ", " Another Data"}, []string{"Instead of lining up the letters all ", "the way across, he splits the keyboard in two", "Like most ergonomic keyboards", "See Data"}, } table := NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Sign", "Rating"}) table.SetCenterSeparator("*") table.SetRowSeparator("=") for _, v := range data { table.Append(v) } table.Render() } func ExampleCSV() { table, _ := NewCSV(os.Stdout, "test.csv", true) table.SetCenterSeparator("*") table.SetRowSeparator("=") table.Render() // Output: *============*===========*=========* // | FIRST NAME | LAST NAME | SSN | // *============*===========*=========* // | John | Barry | 123456 | // | Kathy | Smith | 687987 | // | Bob | McCornick | 3979870 | // *============*===========*=========* } func TestCSVInfo(t *testing.T) { buf := &bytes.Buffer{} table, err := NewCSV(buf, "test_info.csv", true) if err != nil { t.Error(err) return } table.SetAlignment(ALIGN_LEFT) table.SetBorder(false) table.Render() got := buf.String() want := ` FIELD | TYPE | NULL | KEY | DEFAULT | EXTRA +----------+--------------+------+-----+---------+----------------+ user_id | smallint(5) | NO | PRI | NULL | auto_increment username | varchar(10) | NO | | NULL | password | varchar(100) | NO | | NULL | ` if got != want { t.Errorf("CSV info failed\ngot:\n[%s]\nwant:\n[%s]\n", got, want) } } func TestCSVSeparator(t *testing.T) { buf := &bytes.Buffer{} table, err := NewCSV(buf, "test.csv", true) if err != nil { t.Error(err) return } table.SetRowLine(true) table.SetCenterSeparator("+") table.SetColumnSeparator("|") table.SetRowSeparator("-") table.SetAlignment(ALIGN_LEFT) table.Render() want := `+------------+-----------+---------+ | FIRST NAME | LAST NAME | SSN | +------------+-----------+---------+ | John | Barry | 123456 | +------------+-----------+---------+ | Kathy | Smith | 687987 | +------------+-----------+---------+ | Bob | McCornick | 3979870 | +------------+-----------+---------+ ` got := buf.String() if got != want { t.Errorf("CSV info failed\ngot:\n[%s]\nwant:\n[%s]\n", got, want) } } func TestNoBorder(t *testing.T) { data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"", " (empty)\n (empty)", "", ""}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, []string{"1/4/2014", " (Discount)", "2233", "-$1.00"}, } var buf bytes.Buffer table := NewWriter(&buf) table.SetAutoWrapText(false) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$145.93"}) // Add Footer table.SetBorder(false) // Set Border to false table.AppendBulk(data) // Add Bulk Data table.Render() want := ` DATE | DESCRIPTION | CV2 | AMOUNT +----------+--------------------------+-------+---------+ 1/1/2014 | Domain name | 2233 | $10.98 1/1/2014 | January Hosting | 2233 | $54.95 | (empty) | | | (empty) | | 1/4/2014 | February Hosting | 2233 | $51.00 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 1/4/2014 | (Discount) | 2233 | -$1.00 +----------+--------------------------+-------+---------+ TOTAL | $145 93 +-------+---------+ ` got := buf.String() if got != want { t.Errorf("border table rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestWithBorder(t *testing.T) { data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"", " (empty)\n (empty)", "", ""}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, []string{"1/4/2014", " (Discount)", "2233", "-$1.00"}, } var buf bytes.Buffer table := NewWriter(&buf) table.SetAutoWrapText(false) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$145.93"}) // Add Footer table.AppendBulk(data) // Add Bulk Data table.Render() want := `+----------+--------------------------+-------+---------+ | DATE | DESCRIPTION | CV2 | AMOUNT | +----------+--------------------------+-------+---------+ | 1/1/2014 | Domain name | 2233 | $10.98 | | 1/1/2014 | January Hosting | 2233 | $54.95 | | | (empty) | | | | | (empty) | | | | 1/4/2014 | February Hosting | 2233 | $51.00 | | 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 | | 1/4/2014 | (Discount) | 2233 | -$1.00 | +----------+--------------------------+-------+---------+ | TOTAL | $145 93 | +----------+--------------------------+-------+---------+ ` got := buf.String() if got != want { t.Errorf("border table rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintingInMarkdown(t *testing.T) { data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, } var buf bytes.Buffer table := NewWriter(&buf) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.AppendBulk(data) // Add Bulk Data table.SetBorders(Border{Left: true, Top: false, Right: true, Bottom: false}) table.SetCenterSeparator("|") table.Render() want := `| DATE | DESCRIPTION | CV2 | AMOUNT | |----------|--------------------------|------|--------| | 1/1/2014 | Domain name | 2233 | $10.98 | | 1/1/2014 | January Hosting | 2233 | $54.95 | | 1/4/2014 | February Hosting | 2233 | $51.00 | | 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 | ` got := buf.String() if got != want { t.Errorf("border table rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintHeading(t *testing.T) { var buf bytes.Buffer table := NewWriter(&buf) table.SetHeader([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"}) table.printHeading() want := `| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | +---+---+---+---+---+---+---+---+---+---+---+---+ ` got := buf.String() if got != want { t.Errorf("header rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintHeadingWithoutAutoFormat(t *testing.T) { var buf bytes.Buffer table := NewWriter(&buf) table.SetHeader([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"}) table.SetAutoFormatHeaders(false) table.printHeading() want := `| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | +---+---+---+---+---+---+---+---+---+---+---+---+ ` got := buf.String() if got != want { t.Errorf("header rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintFooter(t *testing.T) { var buf bytes.Buffer table := NewWriter(&buf) table.SetHeader([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"}) table.SetFooter([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"}) table.printFooter() want := `| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | +---+---+---+---+---+---+---+---+---+---+---+---+ ` got := buf.String() if got != want { t.Errorf("footer rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintFooterWithoutAutoFormat(t *testing.T) { var buf bytes.Buffer table := NewWriter(&buf) table.SetAutoFormatHeaders(false) table.SetHeader([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"}) table.SetFooter([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"}) table.printFooter() want := `| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | +---+---+---+---+---+---+---+---+---+---+---+---+ ` got := buf.String() if got != want { t.Errorf("footer rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintShortCaption(t *testing.T) { var buf bytes.Buffer data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } table := NewWriter(&buf) table.SetHeader([]string{"Name", "Sign", "Rating"}) table.SetCaption(true, "Short caption.") for _, v := range data { table.Append(v) } table.Render() want := `+------+-----------------------+--------+ | NAME | SIGN | RATING | +------+-----------------------+--------+ | A | The Good | 500 | | B | The Very very Bad Man | 288 | | C | The Ugly | 120 | | D | The Gopher | 800 | +------+-----------------------+--------+ Short caption. ` got := buf.String() if got != want { t.Errorf("long caption for short example rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintLongCaptionWithShortExample(t *testing.T) { var buf bytes.Buffer data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } table := NewWriter(&buf) table.SetHeader([]string{"Name", "Sign", "Rating"}) table.SetCaption(true, "This is a very long caption. The text should wrap. If not, we have a problem that needs to be solved.") for _, v := range data { table.Append(v) } table.Render() want := `+------+-----------------------+--------+ | NAME | SIGN | RATING | +------+-----------------------+--------+ | A | The Good | 500 | | B | The Very very Bad Man | 288 | | C | The Ugly | 120 | | D | The Gopher | 800 | +------+-----------------------+--------+ This is a very long caption. The text should wrap. If not, we have a problem that needs to be solved. ` got := buf.String() if got != want { t.Errorf("long caption for short example rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintCaptionWithFooter(t *testing.T) { data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, } var buf bytes.Buffer table := NewWriter(&buf) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer table.SetCaption(true, "This is a very long caption. The text should wrap to the width of the table.") // Add caption table.SetBorder(false) // Set Border to false table.AppendBulk(data) // Add Bulk Data table.Render() want := ` DATE | DESCRIPTION | CV2 | AMOUNT +----------+--------------------------+-------+---------+ 1/1/2014 | Domain name | 2233 | $10.98 1/1/2014 | January Hosting | 2233 | $54.95 1/4/2014 | February Hosting | 2233 | $51.00 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 +----------+--------------------------+-------+---------+ TOTAL | $146 93 +-------+---------+ This is a very long caption. The text should wrap to the width of the table. ` got := buf.String() if got != want { t.Errorf("border table rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintLongCaptionWithLongExample(t *testing.T) { var buf bytes.Buffer data := [][]string{ []string{"Learn East has computers with adapted keyboards with enlarged print etc", "Some Data", "Another Data"}, []string{"Instead of lining up the letters all", "the way across, he splits the keyboard in two", "Like most ergonomic keyboards"}, } table := NewWriter(&buf) table.SetCaption(true, "This is a very long caption. The text should wrap. If not, we have a problem that needs to be solved.") table.SetHeader([]string{"Name", "Sign", "Rating"}) for _, v := range data { table.Append(v) } table.Render() want := `+--------------------------------+--------------------------------+-------------------------------+ | NAME | SIGN | RATING | +--------------------------------+--------------------------------+-------------------------------+ | Learn East has computers | Some Data | Another Data | | with adapted keyboards with | | | | enlarged print etc | | | | Instead of lining up the | the way across, he splits the | Like most ergonomic keyboards | | letters all | keyboard in two | | +--------------------------------+--------------------------------+-------------------------------+ This is a very long caption. The text should wrap. If not, we have a problem that needs to be solved. ` got := buf.String() if got != want { t.Errorf("long caption for long example rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintTableWithAndWithoutAutoWrap(t *testing.T) { var buf bytes.Buffer var multiline = `A multiline string with some lines being really long.` with := NewWriter(&buf) with.Append([]string{multiline}) with.Render() want := `+--------------------------------+ | A multiline string with some | | lines being really long. | +--------------------------------+ ` got := buf.String() if got != want { t.Errorf("multiline text rendering with wrapping failed\ngot:\n%s\nwant:\n%s\n", got, want) } buf.Truncate(0) without := NewWriter(&buf) without.SetAutoWrapText(false) without.Append([]string{multiline}) without.Render() want = `+-------------------------------------------+ | A multiline | | string with some lines being really long. | +-------------------------------------------+ ` got = buf.String() if got != want { t.Errorf("multiline text rendering without wrapping rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestPrintLine(t *testing.T) { header := make([]string, 12) val := " " want := "" for i := range header { header[i] = val want = fmt.Sprintf("%s+-%s-", want, strings.Replace(val, " ", "-", -1)) val = val + " " } want = want + "+" var buf bytes.Buffer table := NewWriter(&buf) table.SetHeader(header) table.printLine(false) got := buf.String() if got != want { t.Errorf("line rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestAnsiStrip(t *testing.T) { header := make([]string, 12) val := " " want := "" for i := range header { header[i] = "\033[43;30m" + val + "\033[00m" want = fmt.Sprintf("%s+-%s-", want, strings.Replace(val, " ", "-", -1)) val = val + " " } want = want + "+" var buf bytes.Buffer table := NewWriter(&buf) table.SetHeader(header) table.printLine(false) got := buf.String() if got != want { t.Errorf("line rendering failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func NewCustomizedTable(out io.Writer) *Table { table := NewWriter(out) table.SetCenterSeparator("") table.SetColumnSeparator("") table.SetRowSeparator("") table.SetBorder(false) table.SetAlignment(ALIGN_LEFT) table.SetHeader([]string{}) return table } func TestSubclass(t *testing.T) { buf := new(bytes.Buffer) table := NewCustomizedTable(buf) data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } for _, v := range data { table.Append(v) } table.Render() output := string(buf.Bytes()) want := ` A The Good 500 B The Very very Bad Man 288 C The Ugly 120 D The Gopher 800 ` if output != want { t.Error(fmt.Sprintf("Unexpected output '%v' != '%v'", output, want)) } } func TestAutoMergeRows(t *testing.T) { data := [][]string{ []string{"A", "The Good", "500"}, []string{"A", "The Very very Bad Man", "288"}, []string{"B", "The Very very Bad Man", "120"}, []string{"B", "The Very very Bad Man", "200"}, } var buf bytes.Buffer table := NewWriter(&buf) table.SetHeader([]string{"Name", "Sign", "Rating"}) for _, v := range data { table.Append(v) } table.SetAutoMergeCells(true) table.Render() want := `+------+-----------------------+--------+ | NAME | SIGN | RATING | +------+-----------------------+--------+ | A | The Good | 500 | | | The Very very Bad Man | 288 | | B | | 120 | | | | 200 | +------+-----------------------+--------+ ` got := buf.String() if got != want { t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want) } buf.Reset() table = NewWriter(&buf) table.SetHeader([]string{"Name", "Sign", "Rating"}) for _, v := range data { table.Append(v) } table.SetAutoMergeCells(true) table.SetRowLine(true) table.Render() want = `+------+-----------------------+--------+ | NAME | SIGN | RATING | +------+-----------------------+--------+ | A | The Good | 500 | + +-----------------------+--------+ | | The Very very Bad Man | 288 | +------+ +--------+ | B | | 120 | + + +--------+ | | | 200 | +------+-----------------------+--------+ ` got = buf.String() if got != want { t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want) } buf.Reset() table = NewWriter(&buf) table.SetHeader([]string{"Name", "Sign", "Rating"}) dataWithlongText := [][]string{ []string{"A", "The Good", "500"}, []string{"A", "The Very very very very very Bad Man", "288"}, []string{"B", "The Very very very very very Bad Man", "120"}, []string{"C", "The Very very Bad Man", "200"}, } table.AppendBulk(dataWithlongText) table.SetAutoMergeCells(true) table.SetRowLine(true) table.Render() want = `+------+--------------------------------+--------+ | NAME | SIGN | RATING | +------+--------------------------------+--------+ | A | The Good | 500 | +------+--------------------------------+--------+ | A | The Very very very very very | 288 | | | Bad Man | | +------+ +--------+ | B | | 120 | | | | | +------+--------------------------------+--------+ | C | The Very very Bad Man | 200 | +------+--------------------------------+--------+ ` got = buf.String() if got != want { t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestClearRows(t *testing.T) { data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, } var buf bytes.Buffer table := NewWriter(&buf) table.SetAutoWrapText(false) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$145.93"}) // Add Footer table.AppendBulk(data) // Add Bulk Data table.Render() originalWant := `+----------+-------------+-------+---------+ | DATE | DESCRIPTION | CV2 | AMOUNT | +----------+-------------+-------+---------+ | 1/1/2014 | Domain name | 2233 | $10.98 | +----------+-------------+-------+---------+ | TOTAL | $145 93 | +----------+-------------+-------+---------+ ` want := originalWant got := buf.String() if got != want { t.Errorf("table clear rows failed\ngot:\n%s\nwant:\n%s\n", got, want) } buf.Reset() table.ClearRows() table.Render() want = `+----------+-------------+-------+---------+ | DATE | DESCRIPTION | CV2 | AMOUNT | +----------+-------------+-------+---------+ +----------+-------------+-------+---------+ | TOTAL | $145 93 | +----------+-------------+-------+---------+ ` got = buf.String() if got != want { t.Errorf("table clear failed\ngot:\n%s\nwant:\n%s\n", got, want) } buf.Reset() table.AppendBulk(data) // Add Bulk Data table.Render() want = `+----------+-------------+-------+---------+ | DATE | DESCRIPTION | CV2 | AMOUNT | +----------+-------------+-------+---------+ | 1/1/2014 | Domain name | 2233 | $10.98 | +----------+-------------+-------+---------+ | TOTAL | $145 93 | +----------+-------------+-------+---------+ ` got = buf.String() if got != want { t.Errorf("table clear rows failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestClearFooters(t *testing.T) { data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, } var buf bytes.Buffer table := NewWriter(&buf) table.SetAutoWrapText(false) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$145.93"}) // Add Footer table.AppendBulk(data) // Add Bulk Data table.Render() buf.Reset() table.ClearFooter() table.Render() want := `+----------+-------------+-------+---------+ | DATE | DESCRIPTION | CV2 | AMOUNT | +----------+-------------+-------+---------+ | 1/1/2014 | Domain name | 2233 | $10.98 | +----------+-------------+-------+---------+ ` got := buf.String() if got != want { t.Errorf("table clear rows failed\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestMoreDataColumnsThanHeaders(t *testing.T) { var ( buf = &bytes.Buffer{} table = NewWriter(buf) header = []string{"A", "B", "C"} data = [][]string{ []string{"a", "b", "c", "d"}, []string{"1", "2", "3", "4"}, } want = `+---+---+---+---+ | A | B | C | | +---+---+---+---+ | a | b | c | d | | 1 | 2 | 3 | 4 | +---+---+---+---+ ` ) table.SetHeader(header) // table.SetFooter(ctx.tableCtx.footer) table.AppendBulk(data) table.Render() got := buf.String() if got != want { t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestMoreFooterColumnsThanHeaders(t *testing.T) { var ( buf = &bytes.Buffer{} table = NewWriter(buf) header = []string{"A", "B", "C"} data = [][]string{ []string{"a", "b", "c", "d"}, []string{"1", "2", "3", "4"}, } footer = []string{"a", "b", "c", "d", "e"} want = `+---+---+---+---+---+ | A | B | C | | | +---+---+---+---+---+ | a | b | c | d | | 1 | 2 | 3 | 4 | +---+---+---+---+---+ | A | B | C | D | E | +---+---+---+---+---+ ` ) table.SetHeader(header) table.SetFooter(footer) table.AppendBulk(data) table.Render() got := buf.String() if got != want { t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestSetColMinWidth(t *testing.T) { var ( buf = &bytes.Buffer{} table = NewWriter(buf) header = []string{"AAA", "BBB", "CCC"} data = [][]string{ []string{"a", "b", "c"}, []string{"1", "2", "3"}, } footer = []string{"a", "b", "cccc"} want = `+-----+-----+-------+ | AAA | BBB | CCC | +-----+-----+-------+ | a | b | c | | 1 | 2 | 3 | +-----+-----+-------+ | A | B | CCCC | +-----+-----+-------+ ` ) table.SetHeader(header) table.SetFooter(footer) table.AppendBulk(data) table.SetColMinWidth(2, 5) table.Render() got := buf.String() if got != want { t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want) } } func TestWrapString(t *testing.T) { want := []string{"ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚", "ã‚ã‚ã‚ã‚ã‚ã‚ã‚"} got, _ := WrapString("ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ã‚ ã‚ã‚ã‚ã‚ã‚ã‚ã‚", 55) if !reflect.DeepEqual(got, want) { t.Errorf("\ngot:\n%v\nwant:\n%v\n", got, want) } } func TestCustomAlign(t *testing.T) { var ( buf = &bytes.Buffer{} table = NewWriter(buf) header = []string{"AAA", "BBB", "CCC"} data = [][]string{ []string{"a", "b", "c"}, []string{"1", "2", "3"}, } footer = []string{"a", "b", "cccc"} want = `+-----+-----+-------+ | AAA | BBB | CCC | +-----+-----+-------+ | a | b | c | | 1 | 2 | 3 | +-----+-----+-------+ | A | B | CCCC | +-----+-----+-------+ ` ) table.SetHeader(header) table.SetFooter(footer) table.AppendBulk(data) table.SetColMinWidth(2, 5) table.SetColumnAlignment([]int{ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT}) table.Render() got := buf.String() if got != want { t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/table.go��������������������������������������0000644�0610621�0607500�00000042222�13172163417�025413� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Oleku Konko All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. // This module is a Table Writer API for the Go Programming Language. // The protocols were written in pure Go and works on windows and unix systems // Create & Generate text based table package tablewriter import ( "bytes" "fmt" "io" "regexp" "strings" ) const ( MAX_ROW_WIDTH = 30 ) const ( CENTER = "+" ROW = "-" COLUMN = "|" SPACE = " " NEWLINE = "\n" ) const ( ALIGN_DEFAULT = iota ALIGN_CENTER ALIGN_RIGHT ALIGN_LEFT ) var ( decimal = regexp.MustCompile(`^-*\d*\.?\d*$`) percent = regexp.MustCompile(`^-*\d*\.?\d*$%$`) ) type Border struct { Left bool Right bool Top bool Bottom bool } type Table struct { out io.Writer rows [][]string lines [][][]string cs map[int]int rs map[int]int headers []string footers []string caption bool captionText string autoFmt bool autoWrap bool mW int pCenter string pRow string pColumn string tColumn int tRow int hAlign int fAlign int align int newLine string rowLine bool autoMergeCells bool hdrLine bool borders Border colSize int headerParams []string columnsParams []string footerParams []string columnsAlign []int } // Start New Table // Take io.Writer Directly func NewWriter(writer io.Writer) *Table { t := &Table{ out: writer, rows: [][]string{}, lines: [][][]string{}, cs: make(map[int]int), rs: make(map[int]int), headers: []string{}, footers: []string{}, caption: false, captionText: "Table caption.", autoFmt: true, autoWrap: true, mW: MAX_ROW_WIDTH, pCenter: CENTER, pRow: ROW, pColumn: COLUMN, tColumn: -1, tRow: -1, hAlign: ALIGN_DEFAULT, fAlign: ALIGN_DEFAULT, align: ALIGN_DEFAULT, newLine: NEWLINE, rowLine: false, hdrLine: true, borders: Border{Left: true, Right: true, Bottom: true, Top: true}, colSize: -1, headerParams: []string{}, columnsParams: []string{}, footerParams: []string{}, columnsAlign: []int{}} return t } // Render table output func (t *Table) Render() { if t.borders.Top { t.printLine(true) } t.printHeading() if t.autoMergeCells { t.printRowsMergeCells() } else { t.printRows() } if !t.rowLine && t.borders.Bottom { t.printLine(true) } t.printFooter() if t.caption { t.printCaption() } } // Set table header func (t *Table) SetHeader(keys []string) { t.colSize = len(keys) for i, v := range keys { t.parseDimension(v, i, -1) t.headers = append(t.headers, v) } } // Set table Footer func (t *Table) SetFooter(keys []string) { //t.colSize = len(keys) for i, v := range keys { t.parseDimension(v, i, -1) t.footers = append(t.footers, v) } } // Set table Caption func (t *Table) SetCaption(caption bool, captionText ...string) { t.caption = caption if len(captionText) == 1 { t.captionText = captionText[0] } } // Turn header autoformatting on/off. Default is on (true). func (t *Table) SetAutoFormatHeaders(auto bool) { t.autoFmt = auto } // Turn automatic multiline text adjustment on/off. Default is on (true). func (t *Table) SetAutoWrapText(auto bool) { t.autoWrap = auto } // Set the Default column width func (t *Table) SetColWidth(width int) { t.mW = width } // Set the minimal width for a column func (t *Table) SetColMinWidth(column int, width int) { t.cs[column] = width } // Set the Column Separator func (t *Table) SetColumnSeparator(sep string) { t.pColumn = sep } // Set the Row Separator func (t *Table) SetRowSeparator(sep string) { t.pRow = sep } // Set the center Separator func (t *Table) SetCenterSeparator(sep string) { t.pCenter = sep } // Set Header Alignment func (t *Table) SetHeaderAlignment(hAlign int) { t.hAlign = hAlign } // Set Footer Alignment func (t *Table) SetFooterAlignment(fAlign int) { t.fAlign = fAlign } // Set Table Alignment func (t *Table) SetAlignment(align int) { t.align = align } func (t *Table) SetColumnAlignment(keys []int) { for _, v := range keys { switch v { case ALIGN_CENTER: break case ALIGN_LEFT: break case ALIGN_RIGHT: break default: v = ALIGN_DEFAULT } t.columnsAlign = append(t.columnsAlign, v) } } // Set New Line func (t *Table) SetNewLine(nl string) { t.newLine = nl } // Set Header Line // This would enable / disable a line after the header func (t *Table) SetHeaderLine(line bool) { t.hdrLine = line } // Set Row Line // This would enable / disable a line on each row of the table func (t *Table) SetRowLine(line bool) { t.rowLine = line } // Set Auto Merge Cells // This would enable / disable the merge of cells with identical values func (t *Table) SetAutoMergeCells(auto bool) { t.autoMergeCells = auto } // Set Table Border // This would enable / disable line around the table func (t *Table) SetBorder(border bool) { t.SetBorders(Border{border, border, border, border}) } func (t *Table) SetBorders(border Border) { t.borders = border } // Append row to table func (t *Table) Append(row []string) { rowSize := len(t.headers) if rowSize > t.colSize { t.colSize = rowSize } n := len(t.lines) line := [][]string{} for i, v := range row { // Detect string width // Detect String height // Break strings into words out := t.parseDimension(v, i, n) // Append broken words line = append(line, out) } t.lines = append(t.lines, line) } // Allow Support for Bulk Append // Eliminates repeated for loops func (t *Table) AppendBulk(rows [][]string) { for _, row := range rows { t.Append(row) } } // Clear rows func (t *Table) ClearRows() { t.lines = [][][]string{} } // Clear footer func (t *Table) ClearFooter() { t.footers = []string{} } // Print line based on row width func (t *Table) printLine(nl bool) { fmt.Fprint(t.out, t.pCenter) for i := 0; i < len(t.cs); i++ { v := t.cs[i] fmt.Fprintf(t.out, "%s%s%s%s", t.pRow, strings.Repeat(string(t.pRow), v), t.pRow, t.pCenter) } if nl { fmt.Fprint(t.out, t.newLine) } } // Print line based on row width with our without cell separator func (t *Table) printLineOptionalCellSeparators(nl bool, displayCellSeparator []bool) { fmt.Fprint(t.out, t.pCenter) for i := 0; i < len(t.cs); i++ { v := t.cs[i] if i > len(displayCellSeparator) || displayCellSeparator[i] { // Display the cell separator fmt.Fprintf(t.out, "%s%s%s%s", t.pRow, strings.Repeat(string(t.pRow), v), t.pRow, t.pCenter) } else { // Don't display the cell separator for this cell fmt.Fprintf(t.out, "%s%s", strings.Repeat(" ", v+2), t.pCenter) } } if nl { fmt.Fprint(t.out, t.newLine) } } // Return the PadRight function if align is left, PadLeft if align is right, // and Pad by default func pad(align int) func(string, string, int) string { padFunc := Pad switch align { case ALIGN_LEFT: padFunc = PadRight case ALIGN_RIGHT: padFunc = PadLeft } return padFunc } // Print heading information func (t *Table) printHeading() { // Check if headers is available if len(t.headers) < 1 { return } // Check if border is set // Replace with space if not set fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE)) // Identify last column end := len(t.cs) - 1 // Get pad function padFunc := pad(t.hAlign) // Checking for ANSI escape sequences for header is_esc_seq := false if len(t.headerParams) > 0 { is_esc_seq = true } // Print Heading column for i := 0; i <= end; i++ { v := t.cs[i] h := "" if i < len(t.headers) { h = t.headers[i] } if t.autoFmt { h = Title(h) } pad := ConditionString((i == end && !t.borders.Left), SPACE, t.pColumn) if is_esc_seq { fmt.Fprintf(t.out, " %s %s", format(padFunc(h, SPACE, v), t.headerParams[i]), pad) } else { fmt.Fprintf(t.out, " %s %s", padFunc(h, SPACE, v), pad) } } // Next line fmt.Fprint(t.out, t.newLine) if t.hdrLine { t.printLine(true) } } // Print heading information func (t *Table) printFooter() { // Check if headers is available if len(t.footers) < 1 { return } // Only print line if border is not set if !t.borders.Bottom { t.printLine(true) } // Check if border is set // Replace with space if not set fmt.Fprint(t.out, ConditionString(t.borders.Bottom, t.pColumn, SPACE)) // Identify last column end := len(t.cs) - 1 // Get pad function padFunc := pad(t.fAlign) // Checking for ANSI escape sequences for header is_esc_seq := false if len(t.footerParams) > 0 { is_esc_seq = true } // Print Heading column for i := 0; i <= end; i++ { v := t.cs[i] f := t.footers[i] if t.autoFmt { f = Title(f) } pad := ConditionString((i == end && !t.borders.Top), SPACE, t.pColumn) if len(t.footers[i]) == 0 { pad = SPACE } if is_esc_seq { fmt.Fprintf(t.out, " %s %s", format(padFunc(f, SPACE, v), t.footerParams[i]), pad) } else { fmt.Fprintf(t.out, " %s %s", padFunc(f, SPACE, v), pad) } //fmt.Fprintf(t.out, " %s %s", // padFunc(f, SPACE, v), // pad) } // Next line fmt.Fprint(t.out, t.newLine) //t.printLine(true) hasPrinted := false for i := 0; i <= end; i++ { v := t.cs[i] pad := t.pRow center := t.pCenter length := len(t.footers[i]) if length > 0 { hasPrinted = true } // Set center to be space if length is 0 if length == 0 && !t.borders.Right { center = SPACE } // Print first junction if i == 0 { fmt.Fprint(t.out, center) } // Pad With space of length is 0 if length == 0 { pad = SPACE } // Ignore left space of it has printed before if hasPrinted || t.borders.Left { pad = t.pRow center = t.pCenter } // Change Center start position if center == SPACE { if i < end && len(t.footers[i+1]) != 0 { center = t.pCenter } } // Print the footer fmt.Fprintf(t.out, "%s%s%s%s", pad, strings.Repeat(string(pad), v), pad, center) } fmt.Fprint(t.out, t.newLine) } // Print caption text func (t Table) printCaption() { width := t.getTableWidth() paragraph, _ := WrapString(t.captionText, width) for linecount := 0; linecount < len(paragraph); linecount++ { fmt.Fprintln(t.out, paragraph[linecount]) } } // Calculate the total number of characters in a row func (t Table) getTableWidth() int { var chars int for _, v := range t.cs { chars += v } // Add chars, spaces, seperators to calculate the total width of the table. // ncols := t.colSize // spaces := ncols * 2 // seps := ncols + 1 return (chars + (3 * t.colSize) + 2) } func (t Table) printRows() { for i, lines := range t.lines { t.printRow(lines, i) } } func (t *Table) fillAlignment(num int) { if len(t.columnsAlign) < num { t.columnsAlign = make([]int, num) for i := range t.columnsAlign { t.columnsAlign[i] = t.align } } } // Print Row Information // Adjust column alignment based on type func (t *Table) printRow(columns [][]string, colKey int) { // Get Maximum Height max := t.rs[colKey] total := len(columns) // TODO Fix uneven col size // if total < t.colSize { // for n := t.colSize - total; n < t.colSize ; n++ { // columns = append(columns, []string{SPACE}) // t.cs[n] = t.mW // } //} // Pad Each Height // pads := []int{} pads := []int{} // Checking for ANSI escape sequences for columns is_esc_seq := false if len(t.columnsParams) > 0 { is_esc_seq = true } t.fillAlignment(total) for i, line := range columns { length := len(line) pad := max - length pads = append(pads, pad) for n := 0; n < pad; n++ { columns[i] = append(columns[i], " ") } } //fmt.Println(max, "\n") for x := 0; x < max; x++ { for y := 0; y < total; y++ { // Check if border is set fmt.Fprint(t.out, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn)) fmt.Fprintf(t.out, SPACE) str := columns[y][x] // Embedding escape sequence with column value if is_esc_seq { str = format(str, t.columnsParams[y]) } // This would print alignment // Default alignment would use multiple configuration switch t.columnsAlign[y] { case ALIGN_CENTER: // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) case ALIGN_RIGHT: fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y])) case ALIGN_LEFT: fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) default: if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) { fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y])) } else { fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) // TODO Custom alignment per column //if max == 1 || pads[y] > 0 { // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) //} else { // fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) //} } } fmt.Fprintf(t.out, SPACE) } // Check if border is set // Replace with space if not set fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE)) fmt.Fprint(t.out, t.newLine) } if t.rowLine { t.printLine(true) } } // Print the rows of the table and merge the cells that are identical func (t *Table) printRowsMergeCells() { var previousLine []string var displayCellBorder []bool var tmpWriter bytes.Buffer for i, lines := range t.lines { // We store the display of the current line in a tmp writer, as we need to know which border needs to be print above previousLine, displayCellBorder = t.printRowMergeCells(&tmpWriter, lines, i, previousLine) if i > 0 { //We don't need to print borders above first line if t.rowLine { t.printLineOptionalCellSeparators(true, displayCellBorder) } } tmpWriter.WriteTo(t.out) } //Print the end of the table if t.rowLine { t.printLine(true) } } // Print Row Information to a writer and merge identical cells. // Adjust column alignment based on type func (t *Table) printRowMergeCells(writer io.Writer, columns [][]string, colKey int, previousLine []string) ([]string, []bool) { // Get Maximum Height max := t.rs[colKey] total := len(columns) // Pad Each Height pads := []int{} for i, line := range columns { length := len(line) pad := max - length pads = append(pads, pad) for n := 0; n < pad; n++ { columns[i] = append(columns[i], " ") } } var displayCellBorder []bool t.fillAlignment(total) for x := 0; x < max; x++ { for y := 0; y < total; y++ { // Check if border is set fmt.Fprint(writer, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn)) fmt.Fprintf(writer, SPACE) str := columns[y][x] if t.autoMergeCells { //Store the full line to merge mutli-lines cells fullLine := strings.Join(columns[y], " ") if len(previousLine) > y && fullLine == previousLine[y] && fullLine != "" { // If this cell is identical to the one above but not empty, we don't display the border and keep the cell empty. displayCellBorder = append(displayCellBorder, false) str = "" } else { // First line or different content, keep the content and print the cell border displayCellBorder = append(displayCellBorder, true) } } // This would print alignment // Default alignment would use multiple configuration switch t.columnsAlign[y] { case ALIGN_CENTER: // fmt.Fprintf(writer, "%s", Pad(str, SPACE, t.cs[y])) case ALIGN_RIGHT: fmt.Fprintf(writer, "%s", PadLeft(str, SPACE, t.cs[y])) case ALIGN_LEFT: fmt.Fprintf(writer, "%s", PadRight(str, SPACE, t.cs[y])) default: if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) { fmt.Fprintf(writer, "%s", PadLeft(str, SPACE, t.cs[y])) } else { fmt.Fprintf(writer, "%s", PadRight(str, SPACE, t.cs[y])) } } fmt.Fprintf(writer, SPACE) } // Check if border is set // Replace with space if not set fmt.Fprint(writer, ConditionString(t.borders.Left, t.pColumn, SPACE)) fmt.Fprint(writer, t.newLine) } //The new previous line is the current one previousLine = make([]string, total) for y := 0; y < total; y++ { previousLine[y] = strings.Join(columns[y], " ") //Store the full line for multi-lines cells } //Returns the newly added line and wether or not a border should be displayed above. return previousLine, displayCellBorder } func (t *Table) parseDimension(str string, colKey, rowKey int) []string { var ( raw []string max int ) w := DisplayWidth(str) // Calculate Width // Check if with is grater than maximum width if w > t.mW { w = t.mW } // Check if width exists v, ok := t.cs[colKey] if !ok || v < w || v == 0 { t.cs[colKey] = w } if rowKey == -1 { return raw } // Calculate Height if t.autoWrap { raw, _ = WrapString(str, t.cs[colKey]) } else { raw = getLines(str) } for _, line := range raw { if w := DisplayWidth(line); w > max { max = w } } // Make sure the with is the same length as maximum word // Important for cases where the width is smaller than maxu word if max > t.cs[colKey] { t.cs[colKey] = max } h := len(raw) v, ok = t.rs[rowKey] if !ok || v < h || v == 0 { t.rs[rowKey] = h } //fmt.Printf("Raw %+v %d\n", raw, len(raw)) return raw } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/csv2table/������������������������������������0000755�0610621�0607500�00000000000�13172163417�025660� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/csv2table/csv2table.go������������������������0000644�0610621�0607500�00000003211�13172163417�030071� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/csv" "flag" "fmt" "io" "os" "unicode/utf8" "github.com/olekukonko/tablewriter" ) var ( fileName = flag.String("f", "", "Set file with eg. sample.csv") delimiter = flag.String("d", ",", "Set CSV File delimiter eg. ,|;|\t ") header = flag.Bool("h", true, "Set header options eg. true|false ") align = flag.String("a", "none", "Set aligmement with eg. none|left|right|center") pipe = flag.Bool("p", false, "Suport for Piping from STDIN") border = flag.Bool("b", true, "Enable / disable table border") ) func main() { flag.Parse() fmt.Println() if *pipe || hasArg("-p") { process(os.Stdin) } else { if *fileName == "" { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) flag.PrintDefaults() fmt.Println() os.Exit(1) } processFile() } fmt.Println() } func hasArg(name string) bool { for _, v := range os.Args { if name == v { return true } } return false } func processFile() { r, err := os.Open(*fileName) if err != nil { exit(err) } defer r.Close() process(r) } func process(r io.Reader) { csvReader := csv.NewReader(r) rune, size := utf8.DecodeRuneInString(*delimiter) if size == 0 { rune = ',' } csvReader.Comma = rune table, err := tablewriter.NewCSVReader(os.Stdout, csvReader, *header) if err != nil { exit(err) } switch *align { case "left": table.SetAlignment(tablewriter.ALIGN_LEFT) case "right": table.SetAlignment(tablewriter.ALIGN_RIGHT) case "center": table.SetAlignment(tablewriter.ALIGN_CENTER) } table.SetBorder(*border) table.Render() } func exit(err error) { fmt.Fprintf(os.Stderr, "#Error : %s", err) os.Exit(1) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/csv2table/README.md���������������������������0000644�0610621�0607500�00000001517�13172163417�027143� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ASCII Table Writer Tool ========= Generate ASCII table on the fly via command line ... Installation is simple as #### Get Tool go get github.com/olekukonko/tablewriter/csv2table #### Install Tool go install github.com/olekukonko/tablewriter/csv2table #### Usage csv2table -f test.csv #### Support for Piping cat test.csv | csv2table -p=true #### Output ``` +------------+-----------+---------+ | FIRST NAME | LAST NAME | SSN | +------------+-----------+---------+ | John | Barry | 123456 | | Kathy | Smith | 687987 | | Bob | McCornick | 3979870 | +------------+-----------+---------+ ``` #### Another Piping with Header set to `false` echo dance,with,me | csv2table -p=true -h=false #### Output +-------+------+-----+ | dance | with | me | +-------+------+-----+ ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/csv.go����������������������������������������0000644�0610621�0607500�00000002464�13172163417�025123� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Oleku Konko All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. // This module is a Table Writer API for the Go Programming Language. // The protocols were written in pure Go and works on windows and unix systems package tablewriter import ( "encoding/csv" "io" "os" ) // Start A new table by importing from a CSV file // Takes io.Writer and csv File name func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) { file, err := os.Open(fileName) if err != nil { return &Table{}, err } defer file.Close() csvReader := csv.NewReader(file) t, err := NewCSVReader(writer, csvReader, hasHeader) return t, err } // Start a New Table Writer with csv.Reader // This enables customisation such as reader.Comma = ';' // See http://golang.org/src/pkg/encoding/csv/reader.go?s=3213:3671#L94 func NewCSVReader(writer io.Writer, csvReader *csv.Reader, hasHeader bool) (*Table, error) { t := NewWriter(writer) if hasHeader { // Read the first row headers, err := csvReader.Read() if err != nil { return &Table{}, err } t.SetHeader(headers) } for { record, err := csvReader.Read() if err == io.EOF { break } else if err != nil { return &Table{}, err } t.Append(record) } return t, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/README.md�������������������������������������0000644�0610621�0607500�00000022105�13172163417�025252� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ASCII Table Writer ========= [![Build Status](https://travis-ci.org/olekukonko/tablewriter.png?branch=master)](https://travis-ci.org/olekukonko/tablewriter) [![Total views](https://img.shields.io/sourcegraph/rrc/github.com/olekukonko/tablewriter.svg)](https://sourcegraph.com/github.com/olekukonko/tablewriter) Generate ASCII table on the fly ... Installation is simple as go get github.com/olekukonko/tablewriter #### Features - Automatic Padding - Support Multiple Lines - Supports Alignment - Support Custom Separators - Automatic Alignment of numbers & percentage - Write directly to http , file etc via `io.Writer` - Read directly from CSV file - Optional row line via `SetRowLine` - Normalise table header - Make CSV Headers optional - Enable or disable table border - Set custom footer support - Optional identical cells merging - Set custom caption #### Example 1 - Basic ```go data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Sign", "Rating"}) for _, v := range data { table.Append(v) } table.Render() // Send output ``` ##### Output 1 ``` +------+-----------------------+--------+ | NAME | SIGN | RATING | +------+-----------------------+--------+ | A | The Good | 500 | | B | The Very very Bad Man | 288 | | C | The Ugly | 120 | | D | The Gopher | 800 | +------+-----------------------+--------+ ``` #### Example 2 - Without Border / Footer / Bulk Append ```go data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer table.SetBorder(false) // Set Border to false table.AppendBulk(data) // Add Bulk Data table.Render() ``` ##### Output 2 ``` DATE | DESCRIPTION | CV2 | AMOUNT +----------+--------------------------+-------+---------+ 1/1/2014 | Domain name | 2233 | $10.98 1/1/2014 | January Hosting | 2233 | $54.95 1/4/2014 | February Hosting | 2233 | $51.00 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 +----------+--------------------------+-------+---------+ TOTAL | $146 93 +-------+---------+ ``` #### Example 3 - CSV ```go table, _ := tablewriter.NewCSV(os.Stdout, "test_info.csv", true) table.SetAlignment(tablewriter.ALIGN_LEFT) // Set Alignment table.Render() ``` ##### Output 3 ``` +----------+--------------+------+-----+---------+----------------+ | FIELD | TYPE | NULL | KEY | DEFAULT | EXTRA | +----------+--------------+------+-----+---------+----------------+ | user_id | smallint(5) | NO | PRI | NULL | auto_increment | | username | varchar(10) | NO | | NULL | | | password | varchar(100) | NO | | NULL | | +----------+--------------+------+-----+---------+----------------+ ``` #### Example 4 - Custom Separator ```go table, _ := tablewriter.NewCSV(os.Stdout, "test.csv", true) table.SetRowLine(true) // Enable row line // Change table lines table.SetCenterSeparator("*") table.SetColumnSeparator("‡") table.SetRowSeparator("-") table.SetAlignment(tablewriter.ALIGN_LEFT) table.Render() ``` ##### Output 4 ``` *------------*-----------*---------* ╪ FIRST NAME ╪ LAST NAME ╪ SSN ╪ *------------*-----------*---------* ╪ John ╪ Barry ╪ 123456 ╪ *------------*-----------*---------* ╪ Kathy ╪ Smith ╪ 687987 ╪ *------------*-----------*---------* ╪ Bob ╪ McCornick ╪ 3979870 ╪ *------------*-----------*---------* ``` #### Example 5 - Markdown Format ```go data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) table.SetCenterSeparator("|") table.AppendBulk(data) // Add Bulk Data table.Render() ``` ##### Output 5 ``` | DATE | DESCRIPTION | CV2 | AMOUNT | |----------|--------------------------|------|--------| | 1/1/2014 | Domain name | 2233 | $10.98 | | 1/1/2014 | January Hosting | 2233 | $54.95 | | 1/4/2014 | February Hosting | 2233 | $51.00 | | 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 | ``` #### Example 6 - Identical cells merging ```go data := [][]string{ []string{"1/1/2014", "Domain name", "1234", "$10.98"}, []string{"1/1/2014", "January Hosting", "2345", "$54.95"}, []string{"1/4/2014", "February Hosting", "3456", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "4567", "$30.00"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$146.93"}) table.SetAutoMergeCells(true) table.SetRowLine(true) table.AppendBulk(data) table.Render() ``` ##### Output 6 ``` +----------+--------------------------+-------+---------+ | DATE | DESCRIPTION | CV2 | AMOUNT | +----------+--------------------------+-------+---------+ | 1/1/2014 | Domain name | 1234 | $10.98 | + +--------------------------+-------+---------+ | | January Hosting | 2345 | $54.95 | +----------+--------------------------+-------+---------+ | 1/4/2014 | February Hosting | 3456 | $51.00 | + +--------------------------+-------+---------+ | | February Extra Bandwidth | 4567 | $30.00 | +----------+--------------------------+-------+---------+ | TOTAL | $146 93 | +----------+--------------------------+-------+---------+ ``` #### Table with color ```go data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer table.SetBorder(false) // Set Border to false table.SetHeaderAttributes(tablewriter.Add(tablewriter.Bold, tablewriter.BgGreenColor), tablewriter.Add(tablewriter.FgHiRedColor, tablewriter.Bold, tablewriter.BgBlackColor), tablewriter.Add(tablewriter.BgRedColor, tablewriter.FgWhiteColor), tablewriter.Add(tablewriter.BgCyanColor, tablewriter.FgWhiteColor)) table.SetColumnAttributes(tablewriter.Add(tablewriter.Bold, tablewriter.FgHiBlackColor), tablewriter.Add(tablewriter.Bold, tablewriter.FgHiRedColor), tablewriter.Add(tablewriter.Bold, tablewriter.FgHiBlackColor), tablewriter.Add(tablewriter.Bold, tablewriter.FgBlackColor)) table.SetFooterAttributes(tablewriter.Add(), tablewriter.Add(), tablewriter.Add(tablewriter.Bold), tablewriter.Add(tablewriter.FgHiRedColor)) table.AppendBulk(data) table.Render() ``` #### Table with color Output ![Table with Color](https://cloud.githubusercontent.com/assets/6460392/21101956/bbc7b356-c0a1-11e6-9f36-dba694746efc.png) #### Example 6 - Set table caption ```go data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Sign", "Rating"}) table.SetCaption(true, "Movie ratings.") for _, v := range data { table.Append(v) } table.Render() // Send output ``` Note: Caption text will wrap with total width of rendered table. ##### Output 6 ``` +------+-----------------------+--------+ | NAME | SIGN | RATING | +------+-----------------------+--------+ | A | The Good | 500 | | B | The Very very Bad Man | 288 | | C | The Ugly | 120 | | D | The Gopher | 800 | +------+-----------------------+--------+ Movie ratings. ``` #### TODO - ~~Import Directly from CSV~~ - `done` - ~~Support for `SetFooter`~~ - `done` - ~~Support for `SetBorder`~~ - `done` - ~~Support table with uneven rows~~ - `done` - Support custom alignment - General Improvement & Optimisation - `NewHTML` Parse table from HTML �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/LICENCE.md������������������������������������0000644�0610621�0607500�00000002041�13172163417�025354� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (C) 2014 by Oleku Konko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/olekukonko/tablewriter/.travis.yml�����������������������������������0000644�0610621�0607500�00000000132�13172163417�026100� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go: - 1.1 - 1.2 - 1.3 - 1.4 - 1.5 - 1.6 - 1.7 - 1.8 - tip ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/���������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163423�020406� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163427�022401� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/tool/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163427�023356� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/tool/upgrade.go�������������������������������������0000644�0610621�0607500�00000003565�13172163427�025345� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build ignore package main import ( "archive/zip" "bytes" "fmt" "io" "io/ioutil" "log" "net/http" "os" "path" "path/filepath" "strings" "github.com/PuerkitoBio/goquery" ) func main() { site := "https://www.sqlite.org/download.html" fmt.Printf("scraping %v\n", site) doc, err := goquery.NewDocument(site) if err != nil { log.Fatal(err) } var url string doc.Find("a").Each(func(_ int, s *goquery.Selection) { if url == "" && strings.HasPrefix(s.Text(), "sqlite-amalgamation-") { url = "https://www.sqlite.org/2017/" + s.Text() } }) if url == "" { return } fmt.Printf("downloading %v\n", url) resp, err := http.Get(url) if err != nil { log.Fatal(err) } b, err := ioutil.ReadAll(resp.Body) if err != nil { resp.Body.Close() log.Fatal(err) } fmt.Printf("extracting %v\n", path.Base(url)) r, err := zip.NewReader(bytes.NewReader(b), resp.ContentLength) if err != nil { resp.Body.Close() log.Fatal(err) } resp.Body.Close() for _, zf := range r.File { var f *os.File switch path.Base(zf.Name) { case "sqlite3.c": f, err = os.Create("sqlite3-binding.c") case "sqlite3.h": f, err = os.Create("sqlite3-binding.h") case "sqlite3ext.h": f, err = os.Create("sqlite3ext.h") default: continue } if err != nil { log.Fatal(err) } zr, err := zf.Open() if err != nil { log.Fatal(err) } _, err = io.WriteString(f, "#ifndef USE_LIBSQLITE3\n") if err != nil { zr.Close() f.Close() log.Fatal(err) } _, err = io.Copy(f, zr) if err != nil { zr.Close() f.Close() log.Fatal(err) } _, err = io.WriteString(f, "#else // USE_LIBSQLITE3\n // If users really want to link against the system sqlite3 we\n// need to make this file a noop.\n #endif") if err != nil { zr.Close() f.Close() log.Fatal(err) } zr.Close() f.Close() fmt.Printf("extracted %v\n", filepath.Base(f.Name())) } } �������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3ext.h����������������������������������������0000644�0610621�0607500�00000072713�13172163427�024671� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#ifndef USE_LIBSQLITE3 /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the SQLite interface for use by ** shared libraries that want to be imported as extensions into ** an SQLite instance. Shared libraries that intend to be loaded ** as extensions by SQLite should #include this file instead of ** sqlite3.h. */ #ifndef SQLITE3EXT_H #define SQLITE3EXT_H #include "sqlite3.h" /* ** The following structure holds pointers to all of the SQLite API ** routines. ** ** WARNING: In order to maintain backwards compatibility, add new ** interfaces to the end of this structure only. If you insert new ** interfaces in the middle of this structure, then older different ** versions of SQLite will not be able to load each other's shared ** libraries! */ struct sqlite3_api_routines { void * (*aggregate_context)(sqlite3_context*,int nBytes); int (*aggregate_count)(sqlite3_context*); int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); int (*bind_double)(sqlite3_stmt*,int,double); int (*bind_int)(sqlite3_stmt*,int,int); int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); int (*bind_null)(sqlite3_stmt*,int); int (*bind_parameter_count)(sqlite3_stmt*); int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); const char * (*bind_parameter_name)(sqlite3_stmt*,int); int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); int (*busy_timeout)(sqlite3*,int ms); int (*changes)(sqlite3*); int (*close)(sqlite3*); int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, int eTextRep,const char*)); int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, int eTextRep,const void*)); const void * (*column_blob)(sqlite3_stmt*,int iCol); int (*column_bytes)(sqlite3_stmt*,int iCol); int (*column_bytes16)(sqlite3_stmt*,int iCol); int (*column_count)(sqlite3_stmt*pStmt); const char * (*column_database_name)(sqlite3_stmt*,int); const void * (*column_database_name16)(sqlite3_stmt*,int); const char * (*column_decltype)(sqlite3_stmt*,int i); const void * (*column_decltype16)(sqlite3_stmt*,int); double (*column_double)(sqlite3_stmt*,int iCol); int (*column_int)(sqlite3_stmt*,int iCol); sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); const char * (*column_name)(sqlite3_stmt*,int); const void * (*column_name16)(sqlite3_stmt*,int); const char * (*column_origin_name)(sqlite3_stmt*,int); const void * (*column_origin_name16)(sqlite3_stmt*,int); const char * (*column_table_name)(sqlite3_stmt*,int); const void * (*column_table_name16)(sqlite3_stmt*,int); const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); const void * (*column_text16)(sqlite3_stmt*,int iCol); int (*column_type)(sqlite3_stmt*,int iCol); sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); void * (*commit_hook)(sqlite3*,int(*)(void*),void*); int (*complete)(const char*sql); int (*complete16)(const void*sql); int (*create_collation)(sqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*)); int (*create_collation16)(sqlite3*,const void*,int,void*, int(*)(void*,int,const void*,int,const void*)); int (*create_function)(sqlite3*,const char*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*)); int (*create_function16)(sqlite3*,const void*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*)); int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); int (*data_count)(sqlite3_stmt*pStmt); sqlite3 * (*db_handle)(sqlite3_stmt*); int (*declare_vtab)(sqlite3*,const char*); int (*enable_shared_cache)(int); int (*errcode)(sqlite3*db); const char * (*errmsg)(sqlite3*); const void * (*errmsg16)(sqlite3*); int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); int (*expired)(sqlite3_stmt*); int (*finalize)(sqlite3_stmt*pStmt); void (*free)(void*); void (*free_table)(char**result); int (*get_autocommit)(sqlite3*); void * (*get_auxdata)(sqlite3_context*,int); int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); int (*global_recover)(void); void (*interruptx)(sqlite3*); sqlite_int64 (*last_insert_rowid)(sqlite3*); const char * (*libversion)(void); int (*libversion_number)(void); void *(*malloc)(int); char * (*mprintf)(const char*,...); int (*open)(const char*,sqlite3**); int (*open16)(const void*,sqlite3**); int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); void *(*realloc)(void*,int); int (*reset)(sqlite3_stmt*pStmt); void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_double)(sqlite3_context*,double); void (*result_error)(sqlite3_context*,const char*,int); void (*result_error16)(sqlite3_context*,const void*,int); void (*result_int)(sqlite3_context*,int); void (*result_int64)(sqlite3_context*,sqlite_int64); void (*result_null)(sqlite3_context*); void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_value)(sqlite3_context*,sqlite3_value*); void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, const char*,const char*),void*); void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); char * (*snprintf)(int,char*,const char*,...); int (*step)(sqlite3_stmt*); int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, char const**,char const**,int*,int*,int*); void (*thread_cleanup)(void); int (*total_changes)(sqlite3*); void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, sqlite_int64),void*); void * (*user_data)(sqlite3_context*); const void * (*value_blob)(sqlite3_value*); int (*value_bytes)(sqlite3_value*); int (*value_bytes16)(sqlite3_value*); double (*value_double)(sqlite3_value*); int (*value_int)(sqlite3_value*); sqlite_int64 (*value_int64)(sqlite3_value*); int (*value_numeric_type)(sqlite3_value*); const unsigned char * (*value_text)(sqlite3_value*); const void * (*value_text16)(sqlite3_value*); const void * (*value_text16be)(sqlite3_value*); const void * (*value_text16le)(sqlite3_value*); int (*value_type)(sqlite3_value*); char *(*vmprintf)(const char*,va_list); /* Added ??? */ int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); /* Added by 3.3.13 */ int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); int (*clear_bindings)(sqlite3_stmt*); /* Added by 3.4.1 */ int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, void (*xDestroy)(void *)); /* Added by 3.5.0 */ int (*bind_zeroblob)(sqlite3_stmt*,int,int); int (*blob_bytes)(sqlite3_blob*); int (*blob_close)(sqlite3_blob*); int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, int,sqlite3_blob**); int (*blob_read)(sqlite3_blob*,void*,int,int); int (*blob_write)(sqlite3_blob*,const void*,int,int); int (*create_collation_v2)(sqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*), void(*)(void*)); int (*file_control)(sqlite3*,const char*,int,void*); sqlite3_int64 (*memory_highwater)(int); sqlite3_int64 (*memory_used)(void); sqlite3_mutex *(*mutex_alloc)(int); void (*mutex_enter)(sqlite3_mutex*); void (*mutex_free)(sqlite3_mutex*); void (*mutex_leave)(sqlite3_mutex*); int (*mutex_try)(sqlite3_mutex*); int (*open_v2)(const char*,sqlite3**,int,const char*); int (*release_memory)(int); void (*result_error_nomem)(sqlite3_context*); void (*result_error_toobig)(sqlite3_context*); int (*sleep)(int); void (*soft_heap_limit)(int); sqlite3_vfs *(*vfs_find)(const char*); int (*vfs_register)(sqlite3_vfs*,int); int (*vfs_unregister)(sqlite3_vfs*); int (*xthreadsafe)(void); void (*result_zeroblob)(sqlite3_context*,int); void (*result_error_code)(sqlite3_context*,int); int (*test_control)(int, ...); void (*randomness)(int,void*); sqlite3 *(*context_db_handle)(sqlite3_context*); int (*extended_result_codes)(sqlite3*,int); int (*limit)(sqlite3*,int,int); sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); const char *(*sql)(sqlite3_stmt*); int (*status)(int,int*,int*,int); int (*backup_finish)(sqlite3_backup*); sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); int (*backup_pagecount)(sqlite3_backup*); int (*backup_remaining)(sqlite3_backup*); int (*backup_step)(sqlite3_backup*,int); const char *(*compileoption_get)(int); int (*compileoption_used)(const char*); int (*create_function_v2)(sqlite3*,const char*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*)); int (*db_config)(sqlite3*,int,...); sqlite3_mutex *(*db_mutex)(sqlite3*); int (*db_status)(sqlite3*,int,int*,int*,int); int (*extended_errcode)(sqlite3*); void (*log)(int,const char*,...); sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); const char *(*sourceid)(void); int (*stmt_status)(sqlite3_stmt*,int,int); int (*strnicmp)(const char*,const char*,int); int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); int (*wal_autocheckpoint)(sqlite3*,int); int (*wal_checkpoint)(sqlite3*,const char*); void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); int (*vtab_config)(sqlite3*,int op,...); int (*vtab_on_conflict)(sqlite3*); /* Version 3.7.16 and later */ int (*close_v2)(sqlite3*); const char *(*db_filename)(sqlite3*,const char*); int (*db_readonly)(sqlite3*,const char*); int (*db_release_memory)(sqlite3*); const char *(*errstr)(int); int (*stmt_busy)(sqlite3_stmt*); int (*stmt_readonly)(sqlite3_stmt*); int (*stricmp)(const char*,const char*); int (*uri_boolean)(const char*,const char*,int); sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); const char *(*uri_parameter)(const char*,const char*); char *(*vsnprintf)(int,char*,const char*,va_list); int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); /* Version 3.8.7 and later */ int (*auto_extension)(void(*)(void)); int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64, void(*)(void*)); int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64, void(*)(void*),unsigned char); int (*cancel_auto_extension)(void(*)(void)); int (*load_extension)(sqlite3*,const char*,const char*,char**); void *(*malloc64)(sqlite3_uint64); sqlite3_uint64 (*msize)(void*); void *(*realloc64)(void*,sqlite3_uint64); void (*reset_auto_extension)(void); void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64, void(*)(void*)); void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64, void(*)(void*), unsigned char); int (*strglob)(const char*,const char*); /* Version 3.8.11 and later */ sqlite3_value *(*value_dup)(const sqlite3_value*); void (*value_free)(sqlite3_value*); int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64); int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64); /* Version 3.9.0 and later */ unsigned int (*value_subtype)(sqlite3_value*); void (*result_subtype)(sqlite3_context*,unsigned int); /* Version 3.10.0 and later */ int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int); int (*strlike)(const char*,const char*,unsigned int); int (*db_cacheflush)(sqlite3*); /* Version 3.12.0 and later */ int (*system_errno)(sqlite3*); /* Version 3.14.0 and later */ int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); char *(*expanded_sql)(sqlite3_stmt*); }; /* ** This is the function signature used for all extension entry points. It ** is also defined in the file "loadext.c". */ typedef int (*sqlite3_loadext_entry)( sqlite3 *db, /* Handle to the database. */ char **pzErrMsg, /* Used to set error string on failure. */ const sqlite3_api_routines *pThunk /* Extension API function pointers. */ ); /* ** The following macros redefine the API routines so that they are ** redirected through the global sqlite3_api structure. ** ** This header file is also used by the loadext.c source file ** (part of the main SQLite library - not an extension) so that ** it can get access to the sqlite3_api_routines structure ** definition. But the main library does not want to redefine ** the API. So the redefinition macros are only valid if the ** SQLITE_CORE macros is undefined. */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) #define sqlite3_aggregate_context sqlite3_api->aggregate_context #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_aggregate_count sqlite3_api->aggregate_count #endif #define sqlite3_bind_blob sqlite3_api->bind_blob #define sqlite3_bind_double sqlite3_api->bind_double #define sqlite3_bind_int sqlite3_api->bind_int #define sqlite3_bind_int64 sqlite3_api->bind_int64 #define sqlite3_bind_null sqlite3_api->bind_null #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name #define sqlite3_bind_text sqlite3_api->bind_text #define sqlite3_bind_text16 sqlite3_api->bind_text16 #define sqlite3_bind_value sqlite3_api->bind_value #define sqlite3_busy_handler sqlite3_api->busy_handler #define sqlite3_busy_timeout sqlite3_api->busy_timeout #define sqlite3_changes sqlite3_api->changes #define sqlite3_close sqlite3_api->close #define sqlite3_collation_needed sqlite3_api->collation_needed #define sqlite3_collation_needed16 sqlite3_api->collation_needed16 #define sqlite3_column_blob sqlite3_api->column_blob #define sqlite3_column_bytes sqlite3_api->column_bytes #define sqlite3_column_bytes16 sqlite3_api->column_bytes16 #define sqlite3_column_count sqlite3_api->column_count #define sqlite3_column_database_name sqlite3_api->column_database_name #define sqlite3_column_database_name16 sqlite3_api->column_database_name16 #define sqlite3_column_decltype sqlite3_api->column_decltype #define sqlite3_column_decltype16 sqlite3_api->column_decltype16 #define sqlite3_column_double sqlite3_api->column_double #define sqlite3_column_int sqlite3_api->column_int #define sqlite3_column_int64 sqlite3_api->column_int64 #define sqlite3_column_name sqlite3_api->column_name #define sqlite3_column_name16 sqlite3_api->column_name16 #define sqlite3_column_origin_name sqlite3_api->column_origin_name #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 #define sqlite3_column_table_name sqlite3_api->column_table_name #define sqlite3_column_table_name16 sqlite3_api->column_table_name16 #define sqlite3_column_text sqlite3_api->column_text #define sqlite3_column_text16 sqlite3_api->column_text16 #define sqlite3_column_type sqlite3_api->column_type #define sqlite3_column_value sqlite3_api->column_value #define sqlite3_commit_hook sqlite3_api->commit_hook #define sqlite3_complete sqlite3_api->complete #define sqlite3_complete16 sqlite3_api->complete16 #define sqlite3_create_collation sqlite3_api->create_collation #define sqlite3_create_collation16 sqlite3_api->create_collation16 #define sqlite3_create_function sqlite3_api->create_function #define sqlite3_create_function16 sqlite3_api->create_function16 #define sqlite3_create_module sqlite3_api->create_module #define sqlite3_create_module_v2 sqlite3_api->create_module_v2 #define sqlite3_data_count sqlite3_api->data_count #define sqlite3_db_handle sqlite3_api->db_handle #define sqlite3_declare_vtab sqlite3_api->declare_vtab #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache #define sqlite3_errcode sqlite3_api->errcode #define sqlite3_errmsg sqlite3_api->errmsg #define sqlite3_errmsg16 sqlite3_api->errmsg16 #define sqlite3_exec sqlite3_api->exec #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_expired sqlite3_api->expired #endif #define sqlite3_finalize sqlite3_api->finalize #define sqlite3_free sqlite3_api->free #define sqlite3_free_table sqlite3_api->free_table #define sqlite3_get_autocommit sqlite3_api->get_autocommit #define sqlite3_get_auxdata sqlite3_api->get_auxdata #define sqlite3_get_table sqlite3_api->get_table #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_global_recover sqlite3_api->global_recover #endif #define sqlite3_interrupt sqlite3_api->interruptx #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid #define sqlite3_libversion sqlite3_api->libversion #define sqlite3_libversion_number sqlite3_api->libversion_number #define sqlite3_malloc sqlite3_api->malloc #define sqlite3_mprintf sqlite3_api->mprintf #define sqlite3_open sqlite3_api->open #define sqlite3_open16 sqlite3_api->open16 #define sqlite3_prepare sqlite3_api->prepare #define sqlite3_prepare16 sqlite3_api->prepare16 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 #define sqlite3_profile sqlite3_api->profile #define sqlite3_progress_handler sqlite3_api->progress_handler #define sqlite3_realloc sqlite3_api->realloc #define sqlite3_reset sqlite3_api->reset #define sqlite3_result_blob sqlite3_api->result_blob #define sqlite3_result_double sqlite3_api->result_double #define sqlite3_result_error sqlite3_api->result_error #define sqlite3_result_error16 sqlite3_api->result_error16 #define sqlite3_result_int sqlite3_api->result_int #define sqlite3_result_int64 sqlite3_api->result_int64 #define sqlite3_result_null sqlite3_api->result_null #define sqlite3_result_text sqlite3_api->result_text #define sqlite3_result_text16 sqlite3_api->result_text16 #define sqlite3_result_text16be sqlite3_api->result_text16be #define sqlite3_result_text16le sqlite3_api->result_text16le #define sqlite3_result_value sqlite3_api->result_value #define sqlite3_rollback_hook sqlite3_api->rollback_hook #define sqlite3_set_authorizer sqlite3_api->set_authorizer #define sqlite3_set_auxdata sqlite3_api->set_auxdata #define sqlite3_snprintf sqlite3_api->snprintf #define sqlite3_step sqlite3_api->step #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup #define sqlite3_total_changes sqlite3_api->total_changes #define sqlite3_trace sqlite3_api->trace #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings #endif #define sqlite3_update_hook sqlite3_api->update_hook #define sqlite3_user_data sqlite3_api->user_data #define sqlite3_value_blob sqlite3_api->value_blob #define sqlite3_value_bytes sqlite3_api->value_bytes #define sqlite3_value_bytes16 sqlite3_api->value_bytes16 #define sqlite3_value_double sqlite3_api->value_double #define sqlite3_value_int sqlite3_api->value_int #define sqlite3_value_int64 sqlite3_api->value_int64 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type #define sqlite3_value_text sqlite3_api->value_text #define sqlite3_value_text16 sqlite3_api->value_text16 #define sqlite3_value_text16be sqlite3_api->value_text16be #define sqlite3_value_text16le sqlite3_api->value_text16le #define sqlite3_value_type sqlite3_api->value_type #define sqlite3_vmprintf sqlite3_api->vmprintf #define sqlite3_vsnprintf sqlite3_api->vsnprintf #define sqlite3_overload_function sqlite3_api->overload_function #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 #define sqlite3_clear_bindings sqlite3_api->clear_bindings #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob #define sqlite3_blob_bytes sqlite3_api->blob_bytes #define sqlite3_blob_close sqlite3_api->blob_close #define sqlite3_blob_open sqlite3_api->blob_open #define sqlite3_blob_read sqlite3_api->blob_read #define sqlite3_blob_write sqlite3_api->blob_write #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 #define sqlite3_file_control sqlite3_api->file_control #define sqlite3_memory_highwater sqlite3_api->memory_highwater #define sqlite3_memory_used sqlite3_api->memory_used #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc #define sqlite3_mutex_enter sqlite3_api->mutex_enter #define sqlite3_mutex_free sqlite3_api->mutex_free #define sqlite3_mutex_leave sqlite3_api->mutex_leave #define sqlite3_mutex_try sqlite3_api->mutex_try #define sqlite3_open_v2 sqlite3_api->open_v2 #define sqlite3_release_memory sqlite3_api->release_memory #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig #define sqlite3_sleep sqlite3_api->sleep #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit #define sqlite3_vfs_find sqlite3_api->vfs_find #define sqlite3_vfs_register sqlite3_api->vfs_register #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister #define sqlite3_threadsafe sqlite3_api->xthreadsafe #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob #define sqlite3_result_error_code sqlite3_api->result_error_code #define sqlite3_test_control sqlite3_api->test_control #define sqlite3_randomness sqlite3_api->randomness #define sqlite3_context_db_handle sqlite3_api->context_db_handle #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes #define sqlite3_limit sqlite3_api->limit #define sqlite3_next_stmt sqlite3_api->next_stmt #define sqlite3_sql sqlite3_api->sql #define sqlite3_status sqlite3_api->status #define sqlite3_backup_finish sqlite3_api->backup_finish #define sqlite3_backup_init sqlite3_api->backup_init #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount #define sqlite3_backup_remaining sqlite3_api->backup_remaining #define sqlite3_backup_step sqlite3_api->backup_step #define sqlite3_compileoption_get sqlite3_api->compileoption_get #define sqlite3_compileoption_used sqlite3_api->compileoption_used #define sqlite3_create_function_v2 sqlite3_api->create_function_v2 #define sqlite3_db_config sqlite3_api->db_config #define sqlite3_db_mutex sqlite3_api->db_mutex #define sqlite3_db_status sqlite3_api->db_status #define sqlite3_extended_errcode sqlite3_api->extended_errcode #define sqlite3_log sqlite3_api->log #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 #define sqlite3_sourceid sqlite3_api->sourceid #define sqlite3_stmt_status sqlite3_api->stmt_status #define sqlite3_strnicmp sqlite3_api->strnicmp #define sqlite3_unlock_notify sqlite3_api->unlock_notify #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint #define sqlite3_wal_hook sqlite3_api->wal_hook #define sqlite3_blob_reopen sqlite3_api->blob_reopen #define sqlite3_vtab_config sqlite3_api->vtab_config #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict /* Version 3.7.16 and later */ #define sqlite3_close_v2 sqlite3_api->close_v2 #define sqlite3_db_filename sqlite3_api->db_filename #define sqlite3_db_readonly sqlite3_api->db_readonly #define sqlite3_db_release_memory sqlite3_api->db_release_memory #define sqlite3_errstr sqlite3_api->errstr #define sqlite3_stmt_busy sqlite3_api->stmt_busy #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly #define sqlite3_stricmp sqlite3_api->stricmp #define sqlite3_uri_boolean sqlite3_api->uri_boolean #define sqlite3_uri_int64 sqlite3_api->uri_int64 #define sqlite3_uri_parameter sqlite3_api->uri_parameter #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 /* Version 3.8.7 and later */ #define sqlite3_auto_extension sqlite3_api->auto_extension #define sqlite3_bind_blob64 sqlite3_api->bind_blob64 #define sqlite3_bind_text64 sqlite3_api->bind_text64 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension #define sqlite3_load_extension sqlite3_api->load_extension #define sqlite3_malloc64 sqlite3_api->malloc64 #define sqlite3_msize sqlite3_api->msize #define sqlite3_realloc64 sqlite3_api->realloc64 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension #define sqlite3_result_blob64 sqlite3_api->result_blob64 #define sqlite3_result_text64 sqlite3_api->result_text64 #define sqlite3_strglob sqlite3_api->strglob /* Version 3.8.11 and later */ #define sqlite3_value_dup sqlite3_api->value_dup #define sqlite3_value_free sqlite3_api->value_free #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64 /* Version 3.9.0 and later */ #define sqlite3_value_subtype sqlite3_api->value_subtype #define sqlite3_result_subtype sqlite3_api->result_subtype /* Version 3.10.0 and later */ #define sqlite3_status64 sqlite3_api->status64 #define sqlite3_strlike sqlite3_api->strlike #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush /* Version 3.12.0 and later */ #define sqlite3_system_errno sqlite3_api->system_errno /* Version 3.14.0 and later */ #define sqlite3_trace_v2 sqlite3_api->trace_v2 #define sqlite3_expanded_sql sqlite3_api->expanded_sql #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) /* This case when the file really is being compiled as a loadable ** extension */ # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; # define SQLITE_EXTENSION_INIT3 \ extern const sqlite3_api_routines *sqlite3_api; #else /* This case when the file is being statically linked into the ** application */ # define SQLITE_EXTENSION_INIT1 /*no-op*/ # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ # define SQLITE_EXTENSION_INIT3 /*no-op*/ #endif #endif /* SQLITE3EXT_H */ #else // USE_LIBSQLITE3 // If users really want to link against the system sqlite3 we // need to make this file a noop. #endif�����������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_windows.go����������������������������������0000644�0610621�0607500�00000000573�13172163427�026073� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build windows package sqlite3 /* #cgo CFLAGS: -I. -fno-stack-check -fno-stack-protector -mno-stack-arg-probe #cgo windows,386 CFLAGS: -D_USE_32BIT_TIME_T #cgo LDFLAGS: -lmingwex -lmingw32 */ import "C" �������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_vtable_test.go������������������������������0000644�0610621�0607500�00000025660�13172163427�026721� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build vtable package sqlite3 import ( "database/sql" "errors" "fmt" "os" "reflect" "strings" "testing" ) type testModule struct { t *testing.T intarray []int } type testVTab struct { intarray []int } type testVTabCursor struct { vTab *testVTab index int } func (m testModule) Create(c *SQLiteConn, args []string) (VTab, error) { if len(args) != 6 { m.t.Fatal("six arguments expected") } if args[0] != "test" { m.t.Fatal("module name") } if args[1] != "main" { m.t.Fatal("db name") } if args[2] != "vtab" { m.t.Fatal("table name") } if args[3] != "'1'" { m.t.Fatal("first arg") } if args[4] != "2" { m.t.Fatal("second arg") } if args[5] != "three" { m.t.Fatal("third argsecond arg") } err := c.DeclareVTab("CREATE TABLE x(test TEXT)") if err != nil { return nil, err } return &testVTab{m.intarray}, nil } func (m testModule) Connect(c *SQLiteConn, args []string) (VTab, error) { return m.Create(c, args) } func (m testModule) DestroyModule() {} func (v *testVTab) BestIndex(cst []InfoConstraint, ob []InfoOrderBy) (*IndexResult, error) { used := make([]bool, 0, len(cst)) for range cst { used = append(used, false) } return &IndexResult{ Used: used, IdxNum: 0, IdxStr: "test-index", AlreadyOrdered: true, EstimatedCost: 100, EstimatedRows: 200, }, nil } func (v *testVTab) Disconnect() error { return nil } func (v *testVTab) Destroy() error { return nil } func (v *testVTab) Open() (VTabCursor, error) { return &testVTabCursor{v, 0}, nil } func (vc *testVTabCursor) Close() error { return nil } func (vc *testVTabCursor) Filter(idxNum int, idxStr string, vals []interface{}) error { vc.index = 0 return nil } func (vc *testVTabCursor) Next() error { vc.index++ return nil } func (vc *testVTabCursor) EOF() bool { return vc.index >= len(vc.vTab.intarray) } func (vc *testVTabCursor) Column(c *SQLiteContext, col int) error { if col != 0 { return fmt.Errorf("column index out of bounds: %d", col) } c.ResultInt(vc.vTab.intarray[vc.index]) return nil } func (vc *testVTabCursor) Rowid() (int64, error) { return int64(vc.index), nil } func TestCreateModule(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) intarray := []int{1, 2, 3} sql.Register("sqlite3_TestCreateModule", &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { return conn.CreateModule("test", testModule{t, intarray}) }, }) db, err := sql.Open("sqlite3_TestCreateModule", tempFilename) if err != nil { t.Fatalf("could not open db: %v", err) } _, err = db.Exec("CREATE VIRTUAL TABLE vtab USING test('1', 2, three)") if err != nil { t.Fatalf("could not create vtable: %v", err) } var i, value int rows, err := db.Query("SELECT rowid, * FROM vtab WHERE test = '3'") if err != nil { t.Fatalf("couldn't select from virtual table: %v", err) } for rows.Next() { rows.Scan(&i, &value) if intarray[i] != value { t.Fatalf("want %v but %v", intarray[i], value) } } _, err = db.Exec("DROP TABLE vtab") if err != nil { t.Fatalf("couldn't drop virtual table: %v", err) } } func TestVUpdate(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) // create module updateMod := &vtabUpdateModule{t, make(map[string]*vtabUpdateTable)} // register module sql.Register("sqlite3_TestVUpdate", &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { return conn.CreateModule("updatetest", updateMod) }, }) // connect db, err := sql.Open("sqlite3_TestVUpdate", tempFilename) if err != nil { t.Fatalf("could not open db: %v", err) } // create test table _, err = db.Exec(`CREATE VIRTUAL TABLE vt USING updatetest(f1 integer, f2 text, f3 text)`) if err != nil { t.Fatalf("could not create updatetest vtable vt, got: %v", err) } // check that table is defined properly if len(updateMod.tables) != 1 { t.Fatalf("expected exactly 1 table to exist, got: %d", len(updateMod.tables)) } if _, ok := updateMod.tables["vt"]; !ok { t.Fatalf("expected table `vt` to exist in tables") } // check nothing in updatetest rows, err := db.Query(`select * from vt`) if err != nil { t.Fatalf("could not query vt, got: %v", err) } i, err := getRowCount(rows) if err != nil { t.Fatalf("expected no error, got: %v", err) } if i != 0 { t.Fatalf("expected no rows in vt, got: %d", i) } _, err = db.Exec(`delete from vt where f1 = 'yes'`) if err != nil { t.Fatalf("expected error on delete, got nil") } // test bad column name _, err = db.Exec(`insert into vt (f4) values('a')`) if err == nil { t.Fatalf("expected error on insert, got nil") } // insert to vt res, err := db.Exec(`insert into vt (f1, f2, f3) values (115, 'b', 'c'), (116, 'd', 'e')`) if err != nil { t.Fatalf("expected no error on insert, got: %v", err) } n, err := res.RowsAffected() if err != nil { t.Fatalf("expected no error, got: %v", err) } if n != 2 { t.Fatalf("expected 1 row affected, got: %d", n) } // check vt table vt := updateMod.tables["vt"] if len(vt.data) != 2 { t.Fatalf("expected table vt to have exactly 2 rows, got: %d", len(vt.data)) } if !reflect.DeepEqual(vt.data[0], []interface{}{int64(115), "b", "c"}) { t.Fatalf("expected table vt entry 0 to be [115 b c], instead: %v", vt.data[0]) } if !reflect.DeepEqual(vt.data[1], []interface{}{int64(116), "d", "e"}) { t.Fatalf("expected table vt entry 1 to be [116 d e], instead: %v", vt.data[1]) } // query vt var f1 int var f2, f3 string err = db.QueryRow(`select * from vt where f1 = 115`).Scan(&f1, &f2, &f3) if err != nil { t.Fatalf("expected no error on vt query, got: %v", err) } // check column values if f1 != 115 || f2 != "b" || f3 != "c" { t.Errorf("expected f1==115, f2==b, f3==c, got: %d, %q, %q", f1, f2, f3) } // update vt res, err = db.Exec(`update vt set f1=117, f2='f' where f3='e'`) if err != nil { t.Fatalf("expected no error, got: %v", err) } n, err = res.RowsAffected() if err != nil { t.Fatalf("expected no error, got: %v", err) } if n != 1 { t.Fatalf("expected exactly one row updated, got: %d", n) } // check vt table if len(vt.data) != 2 { t.Fatalf("expected table vt to have exactly 2 rows, got: %d", len(vt.data)) } if !reflect.DeepEqual(vt.data[0], []interface{}{int64(115), "b", "c"}) { t.Fatalf("expected table vt entry 0 to be [115 b c], instead: %v", vt.data[0]) } if !reflect.DeepEqual(vt.data[1], []interface{}{int64(117), "f", "e"}) { t.Fatalf("expected table vt entry 1 to be [117 f e], instead: %v", vt.data[1]) } // delete from vt res, err = db.Exec(`delete from vt where f1 = 117`) if err != nil { t.Fatalf("expected no error, got: %v", err) } n, err = res.RowsAffected() if err != nil { t.Fatalf("expected no error, got: %v", err) } if n != 1 { t.Fatalf("expected exactly one row deleted, got: %d", n) } // check vt table if len(vt.data) != 1 { t.Fatalf("expected table vt to have exactly 1 row, got: %d", len(vt.data)) } if !reflect.DeepEqual(vt.data[0], []interface{}{int64(115), "b", "c"}) { t.Fatalf("expected table vt entry 0 to be [115 b c], instead: %v", vt.data[0]) } // check updatetest has 1 result rows, err = db.Query(`select * from vt`) if err != nil { t.Fatalf("could not query vt, got: %v", err) } i, err = getRowCount(rows) if err != nil { t.Fatalf("expected no error, got: %v", err) } if i != 1 { t.Fatalf("expected 1 row in vt, got: %d", i) } } func getRowCount(rows *sql.Rows) (int, error) { var i int for rows.Next() { i++ } return i, nil } type vtabUpdateModule struct { t *testing.T tables map[string]*vtabUpdateTable } func (m *vtabUpdateModule) Create(c *SQLiteConn, args []string) (VTab, error) { if len(args) < 2 { return nil, errors.New("must declare at least one column") } // get database name, table name, and column declarations ... dbname, tname, decls := args[1], args[2], args[3:] // extract column names + types from parameters declarations cols, typs := make([]string, len(decls)), make([]string, len(decls)) for i := 0; i < len(decls); i++ { n, typ := decls[i], "" if j := strings.IndexAny(n, " \t\n"); j != -1 { typ, n = strings.TrimSpace(n[j+1:]), n[:j] } cols[i], typs[i] = n, typ } // declare table err := c.DeclareVTab(fmt.Sprintf(`CREATE TABLE "%s"."%s" (%s)`, dbname, tname, strings.Join(decls, ","))) if err != nil { return nil, err } // create table vtab := &vtabUpdateTable{m.t, dbname, tname, cols, typs, make([][]interface{}, 0)} m.tables[tname] = vtab return vtab, nil } func (m *vtabUpdateModule) Connect(c *SQLiteConn, args []string) (VTab, error) { return m.Create(c, args) } func (m *vtabUpdateModule) DestroyModule() {} type vtabUpdateTable struct { t *testing.T db string name string cols []string typs []string data [][]interface{} } func (t *vtabUpdateTable) Open() (VTabCursor, error) { return &vtabUpdateCursor{t, 0}, nil } func (t *vtabUpdateTable) BestIndex(cst []InfoConstraint, ob []InfoOrderBy) (*IndexResult, error) { return &IndexResult{Used: make([]bool, len(cst))}, nil } func (t *vtabUpdateTable) Disconnect() error { return nil } func (t *vtabUpdateTable) Destroy() error { return nil } func (t *vtabUpdateTable) Insert(id interface{}, vals []interface{}) (int64, error) { var i int64 if id == nil { i, t.data = int64(len(t.data)), append(t.data, vals) return i, nil } var ok bool i, ok = id.(int64) if !ok { return 0, fmt.Errorf("id is invalid type: %T", id) } t.data[i] = vals return i, nil } func (t *vtabUpdateTable) Update(id interface{}, vals []interface{}) error { i, ok := id.(int64) if !ok { return fmt.Errorf("id is invalid type: %T", id) } if int(i) >= len(t.data) || i < 0 { return fmt.Errorf("invalid row id %d", i) } t.data[int(i)] = vals return nil } func (t *vtabUpdateTable) Delete(id interface{}) error { i, ok := id.(int64) if !ok { return fmt.Errorf("id is invalid type: %T", id) } if int(i) >= len(t.data) || i < 0 { return fmt.Errorf("invalid row id %d", i) } t.data = append(t.data[:i], t.data[i+1:]...) return nil } type vtabUpdateCursor struct { t *vtabUpdateTable i int } func (c *vtabUpdateCursor) Column(ctxt *SQLiteContext, col int) error { switch x := c.t.data[c.i][col].(type) { case []byte: ctxt.ResultBlob(x) case bool: ctxt.ResultBool(x) case float64: ctxt.ResultDouble(x) case int: ctxt.ResultInt(x) case int64: ctxt.ResultInt64(x) case nil: ctxt.ResultNull() case string: ctxt.ResultText(x) default: ctxt.ResultText(fmt.Sprintf("%v", x)) } return nil } func (c *vtabUpdateCursor) Filter(ixNum int, ixName string, vals []interface{}) error { return nil } func (c *vtabUpdateCursor) Next() error { c.i++ return nil } func (c *vtabUpdateCursor) EOF() bool { return c.i >= len(c.t.data) } func (c *vtabUpdateCursor) Rowid() (int64, error) { return int64(c.i), nil } func (c *vtabUpdateCursor) Close() error { return nil } ��������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_vtable.go�����������������������������������0000644�0610621�0607500�00000042427�13172163427�025662� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build vtable package sqlite3 /* #cgo CFLAGS: -std=gnu99 #cgo CFLAGS: -DSQLITE_ENABLE_RTREE -DSQLITE_THREADSAFE #cgo CFLAGS: -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS4_UNICODE61 #cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15 #cgo CFLAGS: -DSQLITE_ENABLE_COLUMN_METADATA=1 #cgo CFLAGS: -Wno-deprecated-declarations #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif #include <stdlib.h> #include <stdint.h> #include <memory.h> static inline char *_sqlite3_mprintf(char *zFormat, char *arg) { return sqlite3_mprintf(zFormat, arg); } typedef struct goVTab goVTab; struct goVTab { sqlite3_vtab base; void *vTab; }; uintptr_t goMInit(void *db, void *pAux, int argc, char **argv, char **pzErr, int isCreate); static int cXInit(sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char **pzErr, int isCreate) { void *vTab = (void *)goMInit(db, pAux, argc, (char**)argv, pzErr, isCreate); if (!vTab || *pzErr) { return SQLITE_ERROR; } goVTab *pvTab = (goVTab *)sqlite3_malloc(sizeof(goVTab)); if (!pvTab) { *pzErr = sqlite3_mprintf("%s", "Out of memory"); return SQLITE_NOMEM; } memset(pvTab, 0, sizeof(goVTab)); pvTab->vTab = vTab; *ppVTab = (sqlite3_vtab *)pvTab; *pzErr = 0; return SQLITE_OK; } static inline int cXCreate(sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char **pzErr) { return cXInit(db, pAux, argc, argv, ppVTab, pzErr, 1); } static inline int cXConnect(sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char **pzErr) { return cXInit(db, pAux, argc, argv, ppVTab, pzErr, 0); } char* goVBestIndex(void *pVTab, void *icp); static inline int cXBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *info) { char *pzErr = goVBestIndex(((goVTab*)pVTab)->vTab, info); if (pzErr) { if (pVTab->zErrMsg) sqlite3_free(pVTab->zErrMsg); pVTab->zErrMsg = pzErr; return SQLITE_ERROR; } return SQLITE_OK; } char* goVRelease(void *pVTab, int isDestroy); static int cXRelease(sqlite3_vtab *pVTab, int isDestroy) { char *pzErr = goVRelease(((goVTab*)pVTab)->vTab, isDestroy); if (pzErr) { if (pVTab->zErrMsg) sqlite3_free(pVTab->zErrMsg); pVTab->zErrMsg = pzErr; return SQLITE_ERROR; } if (pVTab->zErrMsg) sqlite3_free(pVTab->zErrMsg); sqlite3_free(pVTab); return SQLITE_OK; } static inline int cXDisconnect(sqlite3_vtab *pVTab) { return cXRelease(pVTab, 0); } static inline int cXDestroy(sqlite3_vtab *pVTab) { return cXRelease(pVTab, 1); } typedef struct goVTabCursor goVTabCursor; struct goVTabCursor { sqlite3_vtab_cursor base; void *vTabCursor; }; uintptr_t goVOpen(void *pVTab, char **pzErr); static int cXOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor) { void *vTabCursor = (void *)goVOpen(((goVTab*)pVTab)->vTab, &(pVTab->zErrMsg)); goVTabCursor *pCursor = (goVTabCursor *)sqlite3_malloc(sizeof(goVTabCursor)); if (!pCursor) { return SQLITE_NOMEM; } memset(pCursor, 0, sizeof(goVTabCursor)); pCursor->vTabCursor = vTabCursor; *ppCursor = (sqlite3_vtab_cursor *)pCursor; return SQLITE_OK; } static int setErrMsg(sqlite3_vtab_cursor *pCursor, char *pzErr) { if (pCursor->pVtab->zErrMsg) sqlite3_free(pCursor->pVtab->zErrMsg); pCursor->pVtab->zErrMsg = pzErr; return SQLITE_ERROR; } char* goVClose(void *pCursor); static int cXClose(sqlite3_vtab_cursor *pCursor) { char *pzErr = goVClose(((goVTabCursor*)pCursor)->vTabCursor); if (pzErr) { return setErrMsg(pCursor, pzErr); } sqlite3_free(pCursor); return SQLITE_OK; } char* goVFilter(void *pCursor, int idxNum, char* idxName, int argc, sqlite3_value **argv); static int cXFilter(sqlite3_vtab_cursor *pCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv) { char *pzErr = goVFilter(((goVTabCursor*)pCursor)->vTabCursor, idxNum, (char*)idxStr, argc, argv); if (pzErr) { return setErrMsg(pCursor, pzErr); } return SQLITE_OK; } char* goVNext(void *pCursor); static int cXNext(sqlite3_vtab_cursor *pCursor) { char *pzErr = goVNext(((goVTabCursor*)pCursor)->vTabCursor); if (pzErr) { return setErrMsg(pCursor, pzErr); } return SQLITE_OK; } int goVEof(void *pCursor); static inline int cXEof(sqlite3_vtab_cursor *pCursor) { return goVEof(((goVTabCursor*)pCursor)->vTabCursor); } char* goVColumn(void *pCursor, void *cp, int col); static int cXColumn(sqlite3_vtab_cursor *pCursor, sqlite3_context *ctx, int i) { char *pzErr = goVColumn(((goVTabCursor*)pCursor)->vTabCursor, ctx, i); if (pzErr) { return setErrMsg(pCursor, pzErr); } return SQLITE_OK; } char* goVRowid(void *pCursor, sqlite3_int64 *pRowid); static int cXRowid(sqlite3_vtab_cursor *pCursor, sqlite3_int64 *pRowid) { char *pzErr = goVRowid(((goVTabCursor*)pCursor)->vTabCursor, pRowid); if (pzErr) { return setErrMsg(pCursor, pzErr); } return SQLITE_OK; } char* goVUpdate(void *pVTab, int argc, sqlite3_value **argv, sqlite3_int64 *pRowid); static int cXUpdate(sqlite3_vtab *pVTab, int argc, sqlite3_value **argv, sqlite3_int64 *pRowid) { char *pzErr = goVUpdate(((goVTab*)pVTab)->vTab, argc, argv, pRowid); if (pzErr) { if (pVTab->zErrMsg) sqlite3_free(pVTab->zErrMsg); pVTab->zErrMsg = pzErr; return SQLITE_ERROR; } return SQLITE_OK; } static sqlite3_module goModule = { 0, // iVersion cXCreate, // xCreate - create a table cXConnect, // xConnect - connect to an existing table cXBestIndex, // xBestIndex - Determine search strategy cXDisconnect, // xDisconnect - Disconnect from a table cXDestroy, // xDestroy - Drop a table cXOpen, // xOpen - open a cursor cXClose, // xClose - close a cursor cXFilter, // xFilter - configure scan constraints cXNext, // xNext - advance a cursor cXEof, // xEof cXColumn, // xColumn - read data cXRowid, // xRowid - read data cXUpdate, // xUpdate - write data // Not implemented 0, // xBegin - begin transaction 0, // xSync - sync transaction 0, // xCommit - commit transaction 0, // xRollback - rollback transaction 0, // xFindFunction - function overloading 0, // xRename - rename the table 0, // xSavepoint 0, // xRelease 0 // xRollbackTo }; void goMDestroy(void*); static int _sqlite3_create_module(sqlite3 *db, const char *zName, uintptr_t pClientData) { return sqlite3_create_module_v2(db, zName, &goModule, (void*) pClientData, goMDestroy); } */ import "C" import ( "fmt" "math" "reflect" "unsafe" ) type sqliteModule struct { c *SQLiteConn name string module Module } type sqliteVTab struct { module *sqliteModule vTab VTab } type sqliteVTabCursor struct { vTab *sqliteVTab vTabCursor VTabCursor } // Op is type of operations. type Op uint8 // Op mean identity of operations. const ( OpEQ Op = 2 OpGT = 4 OpLE = 8 OpLT = 16 OpGE = 32 OpMATCH = 64 OpLIKE = 65 /* 3.10.0 and later only */ OpGLOB = 66 /* 3.10.0 and later only */ OpREGEXP = 67 /* 3.10.0 and later only */ OpScanUnique = 1 /* Scan visits at most 1 row */ ) // InfoConstraint give information of constraint. type InfoConstraint struct { Column int Op Op Usable bool } // InfoOrderBy give information of order-by. type InfoOrderBy struct { Column int Desc bool } func constraints(info *C.sqlite3_index_info) []InfoConstraint { l := info.nConstraint slice := (*[1 << 30]C.struct_sqlite3_index_constraint)(unsafe.Pointer(info.aConstraint))[:l:l] cst := make([]InfoConstraint, 0, l) for _, c := range slice { var usable bool if c.usable > 0 { usable = true } cst = append(cst, InfoConstraint{ Column: int(c.iColumn), Op: Op(c.op), Usable: usable, }) } return cst } func orderBys(info *C.sqlite3_index_info) []InfoOrderBy { l := info.nOrderBy slice := (*[1 << 30]C.struct_sqlite3_index_orderby)(unsafe.Pointer(info.aOrderBy))[:l:l] ob := make([]InfoOrderBy, 0, l) for _, c := range slice { var desc bool if c.desc > 0 { desc = true } ob = append(ob, InfoOrderBy{ Column: int(c.iColumn), Desc: desc, }) } return ob } // IndexResult is a Go struct representation of what eventually ends up in the // output fields for `sqlite3_index_info` // See: https://www.sqlite.org/c3ref/index_info.html type IndexResult struct { Used []bool // aConstraintUsage IdxNum int IdxStr string AlreadyOrdered bool // orderByConsumed EstimatedCost float64 EstimatedRows float64 } // mPrintf is a utility wrapper around sqlite3_mprintf func mPrintf(format, arg string) *C.char { cf := C.CString(format) defer C.free(unsafe.Pointer(cf)) ca := C.CString(arg) defer C.free(unsafe.Pointer(ca)) return C._sqlite3_mprintf(cf, ca) } //export goMInit func goMInit(db, pClientData unsafe.Pointer, argc C.int, argv **C.char, pzErr **C.char, isCreate C.int) C.uintptr_t { m := lookupHandle(uintptr(pClientData)).(*sqliteModule) if m.c.db != (*C.sqlite3)(db) { *pzErr = mPrintf("%s", "Inconsistent db handles") return 0 } args := make([]string, argc) var A []*C.char slice := reflect.SliceHeader{Data: uintptr(unsafe.Pointer(argv)), Len: int(argc), Cap: int(argc)} a := reflect.NewAt(reflect.TypeOf(A), unsafe.Pointer(&slice)).Elem().Interface() for i, s := range a.([]*C.char) { args[i] = C.GoString(s) } var vTab VTab var err error if isCreate == 1 { vTab, err = m.module.Create(m.c, args) } else { vTab, err = m.module.Connect(m.c, args) } if err != nil { *pzErr = mPrintf("%s", err.Error()) return 0 } vt := sqliteVTab{m, vTab} *pzErr = nil return C.uintptr_t(newHandle(m.c, &vt)) } //export goVRelease func goVRelease(pVTab unsafe.Pointer, isDestroy C.int) *C.char { vt := lookupHandle(uintptr(pVTab)).(*sqliteVTab) var err error if isDestroy == 1 { err = vt.vTab.Destroy() } else { err = vt.vTab.Disconnect() } if err != nil { return mPrintf("%s", err.Error()) } return nil } //export goVOpen func goVOpen(pVTab unsafe.Pointer, pzErr **C.char) C.uintptr_t { vt := lookupHandle(uintptr(pVTab)).(*sqliteVTab) vTabCursor, err := vt.vTab.Open() if err != nil { *pzErr = mPrintf("%s", err.Error()) return 0 } vtc := sqliteVTabCursor{vt, vTabCursor} *pzErr = nil return C.uintptr_t(newHandle(vt.module.c, &vtc)) } //export goVBestIndex func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char { vt := lookupHandle(uintptr(pVTab)).(*sqliteVTab) info := (*C.sqlite3_index_info)(icp) csts := constraints(info) res, err := vt.vTab.BestIndex(csts, orderBys(info)) if err != nil { return mPrintf("%s", err.Error()) } if len(res.Used) != len(csts) { return mPrintf("Result.Used != expected value", "") } // Get a pointer to constraint_usage struct so we can update in place. l := info.nConstraint s := (*[1 << 30]C.struct_sqlite3_index_constraint_usage)(unsafe.Pointer(info.aConstraintUsage))[:l:l] index := 1 for i := C.int(0); i < info.nConstraint; i++ { if res.Used[i] { s[i].argvIndex = C.int(index) s[i].omit = C.uchar(1) index++ } } info.idxNum = C.int(res.IdxNum) idxStr := C.CString(res.IdxStr) defer C.free(unsafe.Pointer(idxStr)) info.idxStr = idxStr info.needToFreeIdxStr = C.int(0) if res.AlreadyOrdered { info.orderByConsumed = C.int(1) } info.estimatedCost = C.double(res.EstimatedCost) info.estimatedRows = C.sqlite3_int64(res.EstimatedRows) return nil } //export goVClose func goVClose(pCursor unsafe.Pointer) *C.char { vtc := lookupHandle(uintptr(pCursor)).(*sqliteVTabCursor) err := vtc.vTabCursor.Close() if err != nil { return mPrintf("%s", err.Error()) } return nil } //export goMDestroy func goMDestroy(pClientData unsafe.Pointer) { m := lookupHandle(uintptr(pClientData)).(*sqliteModule) m.module.DestroyModule() } //export goVFilter func goVFilter(pCursor unsafe.Pointer, idxNum C.int, idxName *C.char, argc C.int, argv **C.sqlite3_value) *C.char { vtc := lookupHandle(uintptr(pCursor)).(*sqliteVTabCursor) args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc] vals := make([]interface{}, 0, argc) for _, v := range args { conv, err := callbackArgGeneric(v) if err != nil { return mPrintf("%s", err.Error()) } vals = append(vals, conv.Interface()) } err := vtc.vTabCursor.Filter(int(idxNum), C.GoString(idxName), vals) if err != nil { return mPrintf("%s", err.Error()) } return nil } //export goVNext func goVNext(pCursor unsafe.Pointer) *C.char { vtc := lookupHandle(uintptr(pCursor)).(*sqliteVTabCursor) err := vtc.vTabCursor.Next() if err != nil { return mPrintf("%s", err.Error()) } return nil } //export goVEof func goVEof(pCursor unsafe.Pointer) C.int { vtc := lookupHandle(uintptr(pCursor)).(*sqliteVTabCursor) err := vtc.vTabCursor.EOF() if err { return 1 } return 0 } //export goVColumn func goVColumn(pCursor, cp unsafe.Pointer, col C.int) *C.char { vtc := lookupHandle(uintptr(pCursor)).(*sqliteVTabCursor) c := (*SQLiteContext)(cp) err := vtc.vTabCursor.Column(c, int(col)) if err != nil { return mPrintf("%s", err.Error()) } return nil } //export goVRowid func goVRowid(pCursor unsafe.Pointer, pRowid *C.sqlite3_int64) *C.char { vtc := lookupHandle(uintptr(pCursor)).(*sqliteVTabCursor) rowid, err := vtc.vTabCursor.Rowid() if err != nil { return mPrintf("%s", err.Error()) } *pRowid = C.sqlite3_int64(rowid) return nil } //export goVUpdate func goVUpdate(pVTab unsafe.Pointer, argc C.int, argv **C.sqlite3_value, pRowid *C.sqlite3_int64) *C.char { vt := lookupHandle(uintptr(pVTab)).(*sqliteVTab) var tname string if n, ok := vt.vTab.(interface { TableName() string }); ok { tname = n.TableName() + " " } err := fmt.Errorf("virtual %s table %sis read-only", vt.module.name, tname) if v, ok := vt.vTab.(VTabUpdater); ok { // convert argv args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc] vals := make([]interface{}, 0, argc) for _, v := range args { conv, err := callbackArgGeneric(v) if err != nil { return mPrintf("%s", err.Error()) } // work around for SQLITE_NULL x := conv.Interface() if z, ok := x.([]byte); ok && z == nil { x = nil } vals = append(vals, x) } switch { case argc == 1: err = v.Delete(vals[0]) case argc > 1 && vals[0] == nil: var id int64 id, err = v.Insert(vals[1], vals[2:]) if err == nil { *pRowid = C.sqlite3_int64(id) } case argc > 1: err = v.Update(vals[1], vals[2:]) } } if err != nil { return mPrintf("%s", err.Error()) } return nil } // Module is a "virtual table module", it defines the implementation of a // virtual tables. See: http://sqlite.org/c3ref/module.html type Module interface { // http://sqlite.org/vtab.html#xcreate Create(c *SQLiteConn, args []string) (VTab, error) // http://sqlite.org/vtab.html#xconnect Connect(c *SQLiteConn, args []string) (VTab, error) // http://sqlite.org/c3ref/create_module.html DestroyModule() } // VTab describes a particular instance of the virtual table. // See: http://sqlite.org/c3ref/vtab.html type VTab interface { // http://sqlite.org/vtab.html#xbestindex BestIndex([]InfoConstraint, []InfoOrderBy) (*IndexResult, error) // http://sqlite.org/vtab.html#xdisconnect Disconnect() error // http://sqlite.org/vtab.html#sqlite3_module.xDestroy Destroy() error // http://sqlite.org/vtab.html#xopen Open() (VTabCursor, error) } // VTabUpdater is a type that allows a VTab to be inserted, updated, or // deleted. // See: https://sqlite.org/vtab.html#xupdate type VTabUpdater interface { Delete(interface{}) error Insert(interface{}, []interface{}) (int64, error) Update(interface{}, []interface{}) error } // VTabCursor describes cursors that point into the virtual table and are used // to loop through the virtual table. See: http://sqlite.org/c3ref/vtab_cursor.html type VTabCursor interface { // http://sqlite.org/vtab.html#xclose Close() error // http://sqlite.org/vtab.html#xfilter Filter(idxNum int, idxStr string, vals []interface{}) error // http://sqlite.org/vtab.html#xnext Next() error // http://sqlite.org/vtab.html#xeof EOF() bool // http://sqlite.org/vtab.html#xcolumn Column(c *SQLiteContext, col int) error // http://sqlite.org/vtab.html#xrowid Rowid() (int64, error) } // DeclareVTab declares the Schema of a virtual table. // See: http://sqlite.org/c3ref/declare_vtab.html func (c *SQLiteConn) DeclareVTab(sql string) error { zSQL := C.CString(sql) defer C.free(unsafe.Pointer(zSQL)) rv := C.sqlite3_declare_vtab(c.db, zSQL) if rv != C.SQLITE_OK { return c.lastError() } return nil } // CreateModule registers a virtual table implementation. // See: http://sqlite.org/c3ref/create_module.html func (c *SQLiteConn) CreateModule(moduleName string, module Module) error { mname := C.CString(moduleName) defer C.free(unsafe.Pointer(mname)) udm := sqliteModule{c, moduleName, module} rv := C._sqlite3_create_module(c.db, mname, C.uintptr_t(newHandle(c, &udm))) if rv != C.SQLITE_OK { return c.lastError() } return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_type.go�������������������������������������0000644�0610621�0607500�00000002626�13172163427�025363� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package sqlite3 /* #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif */ import "C" import ( "reflect" "time" ) // ColumnTypeDatabaseTypeName implement RowsColumnTypeDatabaseTypeName. func (rc *SQLiteRows) ColumnTypeDatabaseTypeName(i int) string { return C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))) } /* func (rc *SQLiteRows) ColumnTypeLength(index int) (length int64, ok bool) { return 0, false } func (rc *SQLiteRows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { return 0, 0, false } */ // ColumnTypeNullable implement RowsColumnTypeNullable. func (rc *SQLiteRows) ColumnTypeNullable(i int) (nullable, ok bool) { return true, true } // ColumnTypeScanType implement RowsColumnTypeScanType. func (rc *SQLiteRows) ColumnTypeScanType(i int) reflect.Type { switch C.sqlite3_column_type(rc.s.s, C.int(i)) { case C.SQLITE_INTEGER: switch C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))) { case "timestamp", "datetime", "date": return reflect.TypeOf(time.Time{}) case "boolean": return reflect.TypeOf(false) } return reflect.TypeOf(int64(0)) case C.SQLITE_FLOAT: return reflect.TypeOf(float64(0)) case C.SQLITE_BLOB: return reflect.SliceOf(reflect.TypeOf(byte(0))) case C.SQLITE_NULL: return reflect.TypeOf(nil) case C.SQLITE_TEXT: return reflect.TypeOf("") } return reflect.SliceOf(reflect.TypeOf(byte(0))) } ����������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_trace_test.go�������������������������������0000644�0610621�0607500�00000003125�13172163427�026532� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2016 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build trace package sqlite3 import ( "database/sql" "testing" ) type sumAggregator int64 func (s *sumAggregator) Step(x int64) { *s += sumAggregator(x) } func (s *sumAggregator) Done() int64 { return int64(*s) } func TestAggregatorRegistration(t *testing.T) { customSum := func() *sumAggregator { var ret sumAggregator return &ret } sql.Register("sqlite3_AggregatorRegistration", &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { if err := conn.RegisterAggregator("customSum", customSum, true); err != nil { return err } return nil }, }) db, err := sql.Open("sqlite3_AggregatorRegistration", ":memory:") if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("create table foo (department integer, profits integer)") if err != nil { // trace feature is not implemented t.Skip("Failed to create table:", err) } _, err = db.Exec("insert into foo values (1, 10), (1, 20), (2, 42)") if err != nil { t.Fatal("Failed to insert records:", err) } tests := []struct { dept, sum int64 }{ {1, 30}, {2, 42}, } for _, test := range tests { var ret int64 err = db.QueryRow("select customSum(profits) from foo where department = $1 group by department", test.dept).Scan(&ret) if err != nil { t.Fatal("Query failed:", err) } if ret != test.sum { t.Fatalf("Custom sum returned wrong value, got %d, want %d", ret, test.sum) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_trace.go������������������������������������0000644�0610621�0607500�00000030563�13172163427�025501� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2016 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build trace package sqlite3 /* #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif #include <stdlib.h> void stepTrampoline(sqlite3_context*, int, sqlite3_value**); void doneTrampoline(sqlite3_context*); int traceCallbackTrampoline(unsigned int traceEventCode, void *ctx, void *p, void *x); */ import "C" import ( "errors" "fmt" "reflect" "strings" "sync" "unsafe" ) // Trace... constants identify the possible events causing callback invocation. // Values are same as the corresponding SQLite Trace Event Codes. const ( TraceStmt = C.SQLITE_TRACE_STMT TraceProfile = C.SQLITE_TRACE_PROFILE TraceRow = C.SQLITE_TRACE_ROW TraceClose = C.SQLITE_TRACE_CLOSE ) type TraceInfo struct { // Pack together the shorter fields, to keep the struct smaller. // On a 64-bit machine there would be padding // between EventCode and ConnHandle; having AutoCommit here is "free": EventCode uint32 AutoCommit bool ConnHandle uintptr // Usually filled, unless EventCode = TraceClose = SQLITE_TRACE_CLOSE: // identifier for a prepared statement: StmtHandle uintptr // Two strings filled when EventCode = TraceStmt = SQLITE_TRACE_STMT: // (1) either the unexpanded SQL text of the prepared statement, or // an SQL comment that indicates the invocation of a trigger; // (2) expanded SQL, if requested and if (1) is not an SQL comment. StmtOrTrigger string ExpandedSQL string // only if requested (TraceConfig.WantExpandedSQL = true) // filled when EventCode = TraceProfile = SQLITE_TRACE_PROFILE: // estimated number of nanoseconds that the prepared statement took to run: RunTimeNanosec int64 DBError Error } // TraceUserCallback gives the signature for a trace function // provided by the user (Go application programmer). // SQLite 3.14 documentation (as of September 2, 2016) // for SQL Trace Hook = sqlite3_trace_v2(): // The integer return value from the callback is currently ignored, // though this may change in future releases. Callback implementations // should return zero to ensure future compatibility. type TraceUserCallback func(TraceInfo) int type TraceConfig struct { Callback TraceUserCallback EventMask C.uint WantExpandedSQL bool } func fillDBError(dbErr *Error, db *C.sqlite3) { // See SQLiteConn.lastError(), in file 'sqlite3.go' at the time of writing (Sept 5, 2016) dbErr.Code = ErrNo(C.sqlite3_errcode(db)) dbErr.ExtendedCode = ErrNoExtended(C.sqlite3_extended_errcode(db)) dbErr.err = C.GoString(C.sqlite3_errmsg(db)) } func fillExpandedSQL(info *TraceInfo, db *C.sqlite3, pStmt unsafe.Pointer) { if pStmt == nil { panic("No SQLite statement pointer in P arg of trace_v2 callback") } expSQLiteCStr := C.sqlite3_expanded_sql((*C.sqlite3_stmt)(pStmt)) if expSQLiteCStr == nil { fillDBError(&info.DBError, db) return } info.ExpandedSQL = C.GoString(expSQLiteCStr) } //export traceCallbackTrampoline func traceCallbackTrampoline( traceEventCode C.uint, // Parameter named 'C' in SQLite docs = Context given at registration: ctx unsafe.Pointer, // Parameter named 'P' in SQLite docs (Primary event data?): p unsafe.Pointer, // Parameter named 'X' in SQLite docs (eXtra event data?): xValue unsafe.Pointer) C.int { if ctx == nil { panic(fmt.Sprintf("No context (ev 0x%x)", traceEventCode)) } contextDB := (*C.sqlite3)(ctx) connHandle := uintptr(ctx) var traceConf TraceConfig var found bool if traceEventCode == TraceClose { // clean up traceMap: 'pop' means get and delete traceConf, found = popTraceMapping(connHandle) } else { traceConf, found = lookupTraceMapping(connHandle) } if !found { panic(fmt.Sprintf("Mapping not found for handle 0x%x (ev 0x%x)", connHandle, traceEventCode)) } var info TraceInfo info.EventCode = uint32(traceEventCode) info.AutoCommit = (int(C.sqlite3_get_autocommit(contextDB)) != 0) info.ConnHandle = connHandle switch traceEventCode { case TraceStmt: info.StmtHandle = uintptr(p) var xStr string if xValue != nil { xStr = C.GoString((*C.char)(xValue)) } info.StmtOrTrigger = xStr if !strings.HasPrefix(xStr, "--") { // Not SQL comment, therefore the current event // is not related to a trigger. // The user might want to receive the expanded SQL; // let's check: if traceConf.WantExpandedSQL { fillExpandedSQL(&info, contextDB, p) } } case TraceProfile: info.StmtHandle = uintptr(p) if xValue == nil { panic("NULL pointer in X arg of trace_v2 callback for SQLITE_TRACE_PROFILE event") } info.RunTimeNanosec = *(*int64)(xValue) // sample the error //TODO: is it safe? is it useful? fillDBError(&info.DBError, contextDB) case TraceRow: info.StmtHandle = uintptr(p) case TraceClose: handle := uintptr(p) if handle != info.ConnHandle { panic(fmt.Sprintf("Different conn handle 0x%x (expected 0x%x) in SQLITE_TRACE_CLOSE event.", handle, info.ConnHandle)) } default: // Pass unsupported events to the user callback (if configured); // let the user callback decide whether to panic or ignore them. } // Do not execute user callback when the event was not requested by user! // Remember that the Close event is always selected when // registering this callback trampoline with SQLite --- for cleanup. // In the future there may be more events forced to "selected" in SQLite // for the driver's needs. if traceConf.EventMask&traceEventCode == 0 { return 0 } r := 0 if traceConf.Callback != nil { r = traceConf.Callback(info) } return C.int(r) } type traceMapEntry struct { config TraceConfig } var traceMapLock sync.Mutex var traceMap = make(map[uintptr]traceMapEntry) func addTraceMapping(connHandle uintptr, traceConf TraceConfig) { traceMapLock.Lock() defer traceMapLock.Unlock() oldEntryCopy, found := traceMap[connHandle] if found { panic(fmt.Sprintf("Adding trace config %v: handle 0x%x already registered (%v).", traceConf, connHandle, oldEntryCopy.config)) } traceMap[connHandle] = traceMapEntry{config: traceConf} fmt.Printf("Added trace config %v: handle 0x%x.\n", traceConf, connHandle) } func lookupTraceMapping(connHandle uintptr) (TraceConfig, bool) { traceMapLock.Lock() defer traceMapLock.Unlock() entryCopy, found := traceMap[connHandle] return entryCopy.config, found } // 'pop' = get and delete from map before returning the value to the caller func popTraceMapping(connHandle uintptr) (TraceConfig, bool) { traceMapLock.Lock() defer traceMapLock.Unlock() entryCopy, found := traceMap[connHandle] if found { delete(traceMap, connHandle) fmt.Printf("Pop handle 0x%x: deleted trace config %v.\n", connHandle, entryCopy.config) } return entryCopy.config, found } // RegisterAggregator makes a Go type available as a SQLite aggregation function. // // Because aggregation is incremental, it's implemented in Go with a // type that has 2 methods: func Step(values) accumulates one row of // data into the accumulator, and func Done() ret finalizes and // returns the aggregate value. "values" and "ret" may be any type // supported by RegisterFunc. // // RegisterAggregator takes as implementation a constructor function // that constructs an instance of the aggregator type each time an // aggregation begins. The constructor must return a pointer to a // type, or an interface that implements Step() and Done(). // // The constructor function and the Step/Done methods may optionally // return an error in addition to their other return values. // // See _example/go_custom_funcs for a detailed example. func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error { var ai aggInfo ai.constructor = reflect.ValueOf(impl) t := ai.constructor.Type() if t.Kind() != reflect.Func { return errors.New("non-function passed to RegisterAggregator") } if t.NumOut() != 1 && t.NumOut() != 2 { return errors.New("SQLite aggregator constructors must return 1 or 2 values") } if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) { return errors.New("Second return value of SQLite function must be error") } if t.NumIn() != 0 { return errors.New("SQLite aggregator constructors must not have arguments") } agg := t.Out(0) switch agg.Kind() { case reflect.Ptr, reflect.Interface: default: return errors.New("SQlite aggregator constructor must return a pointer object") } stepFn, found := agg.MethodByName("Step") if !found { return errors.New("SQlite aggregator doesn't have a Step() function") } step := stepFn.Type if step.NumOut() != 0 && step.NumOut() != 1 { return errors.New("SQlite aggregator Step() function must return 0 or 1 values") } if step.NumOut() == 1 && !step.Out(0).Implements(reflect.TypeOf((*error)(nil)).Elem()) { return errors.New("type of SQlite aggregator Step() return value must be error") } stepNArgs := step.NumIn() start := 0 if agg.Kind() == reflect.Ptr { // Skip over the method receiver stepNArgs-- start++ } if step.IsVariadic() { stepNArgs-- } for i := start; i < start+stepNArgs; i++ { conv, err := callbackArg(step.In(i)) if err != nil { return err } ai.stepArgConverters = append(ai.stepArgConverters, conv) } if step.IsVariadic() { conv, err := callbackArg(t.In(start + stepNArgs).Elem()) if err != nil { return err } ai.stepVariadicConverter = conv // Pass -1 to sqlite so that it allows any number of // arguments. The call helper verifies that the minimum number // of arguments is present for variadic functions. stepNArgs = -1 } doneFn, found := agg.MethodByName("Done") if !found { return errors.New("SQlite aggregator doesn't have a Done() function") } done := doneFn.Type doneNArgs := done.NumIn() if agg.Kind() == reflect.Ptr { // Skip over the method receiver doneNArgs-- } if doneNArgs != 0 { return errors.New("SQlite aggregator Done() function must have no arguments") } if done.NumOut() != 1 && done.NumOut() != 2 { return errors.New("SQLite aggregator Done() function must return 1 or 2 values") } if done.NumOut() == 2 && !done.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) { return errors.New("second return value of SQLite aggregator Done() function must be error") } conv, err := callbackRet(done.Out(0)) if err != nil { return err } ai.doneRetConverter = conv ai.active = make(map[int64]reflect.Value) ai.next = 1 // ai must outlast the database connection, or we'll have dangling pointers. c.aggregators = append(c.aggregators, &ai) cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) opts := C.SQLITE_UTF8 if pure { opts |= C.SQLITE_DETERMINISTIC } rv := sqlite3CreateFunction(c.db, cname, C.int(stepNArgs), C.int(opts), newHandle(c, &ai), nil, C.stepTrampoline, C.doneTrampoline) if rv != C.SQLITE_OK { return c.lastError() } return nil } // SetTrace installs or removes the trace callback for the given database connection. // It's not named 'RegisterTrace' because only one callback can be kept and called. // Calling SetTrace a second time on same database connection // overrides (cancels) any prior callback and all its settings: // event mask, etc. func (c *SQLiteConn) SetTrace(requested *TraceConfig) error { connHandle := uintptr(unsafe.Pointer(c.db)) _, _ = popTraceMapping(connHandle) if requested == nil { // The traceMap entry was deleted already by popTraceMapping(): // can disable all events now, no need to watch for TraceClose. err := c.setSQLiteTrace(0) return err } reqCopy := *requested // Disable potentially expensive operations // if their result will not be used. We are doing this // just in case the caller provided nonsensical input. if reqCopy.EventMask&TraceStmt == 0 { reqCopy.WantExpandedSQL = false } addTraceMapping(connHandle, reqCopy) // The callback trampoline function does cleanup on Close event, // regardless of the presence or absence of the user callback. // Therefore it needs the Close event to be selected: actualEventMask := uint(reqCopy.EventMask | TraceClose) err := c.setSQLiteTrace(actualEventMask) return err } func (c *SQLiteConn) setSQLiteTrace(sqliteEventMask uint) error { rv := C.sqlite3_trace_v2(c.db, C.uint(sqliteEventMask), (*[0]byte)(unsafe.Pointer(C.traceCallbackTrampoline)), unsafe.Pointer(c.db)) // Fourth arg is same as first: we are // passing the database connection handle as callback context. if rv != C.SQLITE_OK { return c.lastError() } return nil } ���������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_test.go�������������������������������������0000644�0610621�0607500�00000140161�13172163427�025356� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 import ( "bytes" "database/sql" "database/sql/driver" "errors" "fmt" "io/ioutil" "math/rand" "net/url" "os" "reflect" "regexp" "strconv" "strings" "sync" "testing" "time" ) func TempFilename(t *testing.T) string { f, err := ioutil.TempFile("", "go-sqlite3-test-") if err != nil { t.Fatal(err) } f.Close() return f.Name() } func doTestOpen(t *testing.T, option string) (string, error) { var url string tempFilename := TempFilename(t) defer os.Remove(tempFilename) if option != "" { url = tempFilename + option } else { url = tempFilename } db, err := sql.Open("sqlite3", url) if err != nil { return "Failed to open database:", err } defer os.Remove(tempFilename) defer db.Close() _, err = db.Exec("drop table foo") _, err = db.Exec("create table foo (id integer)") if err != nil { return "Failed to create table:", err } if stat, err := os.Stat(tempFilename); err != nil || stat.IsDir() { return "Failed to create ./foo.db", nil } return "", nil } func TestOpen(t *testing.T) { cases := map[string]bool{ "": true, "?_txlock=immediate": true, "?_txlock=deferred": true, "?_txlock=exclusive": true, "?_txlock=bogus": false, } for option, expectedPass := range cases { result, err := doTestOpen(t, option) if result == "" { if !expectedPass { errmsg := fmt.Sprintf("_txlock error not caught at dbOpen with option: %s", option) t.Fatal(errmsg) } } else if expectedPass { if err == nil { t.Fatal(result) } else { t.Fatal(result, err) } } } } func TestReadonly(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db1, err := sql.Open("sqlite3", "file:"+tempFilename) if err != nil { t.Fatal(err) } db1.Exec("CREATE TABLE test (x int, y float)") db2, err := sql.Open("sqlite3", "file:"+tempFilename+"?mode=ro") if err != nil { t.Fatal(err) } _ = db2 _, err = db2.Exec("INSERT INTO test VALUES (1, 3.14)") if err == nil { t.Fatal("didn't expect INSERT into read-only database to work") } } func TestForeignKeys(t *testing.T) { cases := map[string]bool{ "?_foreign_keys=1": true, "?_foreign_keys=0": false, } for option, want := range cases { fname := TempFilename(t) uri := "file:" + fname + option db, err := sql.Open("sqlite3", uri) if err != nil { os.Remove(fname) t.Errorf("sql.Open(\"sqlite3\", %q): %v", uri, err) continue } var enabled bool err = db.QueryRow("PRAGMA foreign_keys;").Scan(&enabled) db.Close() os.Remove(fname) if err != nil { t.Errorf("query foreign_keys for %s: %v", uri, err) continue } if enabled != want { t.Errorf("\"PRAGMA foreign_keys;\" for %q = %t; want %t", uri, enabled, want) continue } } } func TestRecursiveTriggers(t *testing.T) { cases := map[string]bool{ "?_recursive_triggers=1": true, "?_recursive_triggers=0": false, } for option, want := range cases { fname := TempFilename(t) uri := "file:" + fname + option db, err := sql.Open("sqlite3", uri) if err != nil { os.Remove(fname) t.Errorf("sql.Open(\"sqlite3\", %q): %v", uri, err) continue } var enabled bool err = db.QueryRow("PRAGMA recursive_triggers;").Scan(&enabled) db.Close() os.Remove(fname) if err != nil { t.Errorf("query recursive_triggers for %s: %v", uri, err) continue } if enabled != want { t.Errorf("\"PRAGMA recursive_triggers;\" for %q = %t; want %t", uri, enabled, want) continue } } } func TestClose(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } _, err = db.Exec("drop table foo") _, err = db.Exec("create table foo (id integer)") if err != nil { t.Fatal("Failed to create table:", err) } stmt, err := db.Prepare("select id from foo where id = ?") if err != nil { t.Fatal("Failed to select records:", err) } db.Close() _, err = stmt.Exec(1) if err == nil { t.Fatal("Failed to operate closed statement") } } func TestInsert(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("drop table foo") _, err = db.Exec("create table foo (id integer)") if err != nil { t.Fatal("Failed to create table:", err) } res, err := db.Exec("insert into foo(id) values(123)") if err != nil { t.Fatal("Failed to insert record:", err) } affected, _ := res.RowsAffected() if affected != 1 { t.Fatalf("Expected %d for affected rows, but %d:", 1, affected) } rows, err := db.Query("select id from foo") if err != nil { t.Fatal("Failed to select records:", err) } defer rows.Close() rows.Next() var result int rows.Scan(&result) if result != 123 { t.Errorf("Expected %d for fetched result, but %d:", 123, result) } } func TestUpdate(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("drop table foo") _, err = db.Exec("create table foo (id integer)") if err != nil { t.Fatal("Failed to create table:", err) } res, err := db.Exec("insert into foo(id) values(123)") if err != nil { t.Fatal("Failed to insert record:", err) } expected, err := res.LastInsertId() if err != nil { t.Fatal("Failed to get LastInsertId:", err) } affected, _ := res.RowsAffected() if err != nil { t.Fatal("Failed to get RowsAffected:", err) } if affected != 1 { t.Fatalf("Expected %d for affected rows, but %d:", 1, affected) } res, err = db.Exec("update foo set id = 234") if err != nil { t.Fatal("Failed to update record:", err) } lastID, err := res.LastInsertId() if err != nil { t.Fatal("Failed to get LastInsertId:", err) } if expected != lastID { t.Errorf("Expected %q for last Id, but %q:", expected, lastID) } affected, _ = res.RowsAffected() if err != nil { t.Fatal("Failed to get RowsAffected:", err) } if affected != 1 { t.Fatalf("Expected %d for affected rows, but %d:", 1, affected) } rows, err := db.Query("select id from foo") if err != nil { t.Fatal("Failed to select records:", err) } defer rows.Close() rows.Next() var result int rows.Scan(&result) if result != 234 { t.Errorf("Expected %d for fetched result, but %d:", 234, result) } } func TestDelete(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("drop table foo") _, err = db.Exec("create table foo (id integer)") if err != nil { t.Fatal("Failed to create table:", err) } res, err := db.Exec("insert into foo(id) values(123)") if err != nil { t.Fatal("Failed to insert record:", err) } expected, err := res.LastInsertId() if err != nil { t.Fatal("Failed to get LastInsertId:", err) } affected, err := res.RowsAffected() if err != nil { t.Fatal("Failed to get RowsAffected:", err) } if affected != 1 { t.Errorf("Expected %d for cout of affected rows, but %q:", 1, affected) } res, err = db.Exec("delete from foo where id = 123") if err != nil { t.Fatal("Failed to delete record:", err) } lastID, err := res.LastInsertId() if err != nil { t.Fatal("Failed to get LastInsertId:", err) } if expected != lastID { t.Errorf("Expected %q for last Id, but %q:", expected, lastID) } affected, err = res.RowsAffected() if err != nil { t.Fatal("Failed to get RowsAffected:", err) } if affected != 1 { t.Errorf("Expected %d for cout of affected rows, but %q:", 1, affected) } rows, err := db.Query("select id from foo") if err != nil { t.Fatal("Failed to select records:", err) } defer rows.Close() if rows.Next() { t.Error("Fetched row but expected not rows") } } func TestBooleanRoundtrip(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("DROP TABLE foo") _, err = db.Exec("CREATE TABLE foo(id INTEGER, value BOOL)") if err != nil { t.Fatal("Failed to create table:", err) } _, err = db.Exec("INSERT INTO foo(id, value) VALUES(1, ?)", true) if err != nil { t.Fatal("Failed to insert true value:", err) } _, err = db.Exec("INSERT INTO foo(id, value) VALUES(2, ?)", false) if err != nil { t.Fatal("Failed to insert false value:", err) } rows, err := db.Query("SELECT id, value FROM foo") if err != nil { t.Fatal("Unable to query foo table:", err) } defer rows.Close() for rows.Next() { var id int var value bool if err := rows.Scan(&id, &value); err != nil { t.Error("Unable to scan results:", err) continue } if id == 1 && !value { t.Error("Value for id 1 should be true, not false") } else if id == 2 && value { t.Error("Value for id 2 should be false, not true") } } } func timezone(t time.Time) string { return t.Format("-07:00") } func TestTimestamp(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("DROP TABLE foo") _, err = db.Exec("CREATE TABLE foo(id INTEGER, ts timeSTAMP, dt DATETIME)") if err != nil { t.Fatal("Failed to create table:", err) } timestamp1 := time.Date(2012, time.April, 6, 22, 50, 0, 0, time.UTC) timestamp2 := time.Date(2006, time.January, 2, 15, 4, 5, 123456789, time.UTC) timestamp3 := time.Date(2012, time.November, 4, 0, 0, 0, 0, time.UTC) tzTest := time.FixedZone("TEST", -9*3600-13*60) tests := []struct { value interface{} expected time.Time }{ {"nonsense", time.Time{}}, {"0000-00-00 00:00:00", time.Time{}}, {time.Time{}.Unix(), time.Time{}}, {timestamp1, timestamp1}, {timestamp2.Unix(), timestamp2.Truncate(time.Second)}, {timestamp2.UnixNano() / int64(time.Millisecond), timestamp2.Truncate(time.Millisecond)}, {timestamp1.In(tzTest), timestamp1.In(tzTest)}, {timestamp1.Format("2006-01-02 15:04:05.000"), timestamp1}, {timestamp1.Format("2006-01-02T15:04:05.000"), timestamp1}, {timestamp1.Format("2006-01-02 15:04:05"), timestamp1}, {timestamp1.Format("2006-01-02T15:04:05"), timestamp1}, {timestamp2, timestamp2}, {"2006-01-02 15:04:05.123456789", timestamp2}, {"2006-01-02T15:04:05.123456789", timestamp2}, {"2006-01-02T05:51:05.123456789-09:13", timestamp2.In(tzTest)}, {"2012-11-04", timestamp3}, {"2012-11-04 00:00", timestamp3}, {"2012-11-04 00:00:00", timestamp3}, {"2012-11-04 00:00:00.000", timestamp3}, {"2012-11-04T00:00", timestamp3}, {"2012-11-04T00:00:00", timestamp3}, {"2012-11-04T00:00:00.000", timestamp3}, {"2006-01-02T15:04:05.123456789Z", timestamp2}, {"2012-11-04Z", timestamp3}, {"2012-11-04 00:00Z", timestamp3}, {"2012-11-04 00:00:00Z", timestamp3}, {"2012-11-04 00:00:00.000Z", timestamp3}, {"2012-11-04T00:00Z", timestamp3}, {"2012-11-04T00:00:00Z", timestamp3}, {"2012-11-04T00:00:00.000Z", timestamp3}, } for i := range tests { _, err = db.Exec("INSERT INTO foo(id, ts, dt) VALUES(?, ?, ?)", i, tests[i].value, tests[i].value) if err != nil { t.Fatal("Failed to insert timestamp:", err) } } rows, err := db.Query("SELECT id, ts, dt FROM foo ORDER BY id ASC") if err != nil { t.Fatal("Unable to query foo table:", err) } defer rows.Close() seen := 0 for rows.Next() { var id int var ts, dt time.Time if err := rows.Scan(&id, &ts, &dt); err != nil { t.Error("Unable to scan results:", err) continue } if id < 0 || id >= len(tests) { t.Error("Bad row id: ", id) continue } seen++ if !tests[id].expected.Equal(ts) { t.Errorf("Timestamp value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt) } if !tests[id].expected.Equal(dt) { t.Errorf("Datetime value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt) } if timezone(tests[id].expected) != timezone(ts) { t.Errorf("Timezone for id %v (%v) should be %v, not %v", id, tests[id].value, timezone(tests[id].expected), timezone(ts)) } if timezone(tests[id].expected) != timezone(dt) { t.Errorf("Timezone for id %v (%v) should be %v, not %v", id, tests[id].value, timezone(tests[id].expected), timezone(dt)) } } if seen != len(tests) { t.Errorf("Expected to see %d rows", len(tests)) } } func TestBoolean(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("CREATE TABLE foo(id INTEGER, fbool BOOLEAN)") if err != nil { t.Fatal("Failed to create table:", err) } bool1 := true _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(1, ?)", bool1) if err != nil { t.Fatal("Failed to insert boolean:", err) } bool2 := false _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(2, ?)", bool2) if err != nil { t.Fatal("Failed to insert boolean:", err) } bool3 := "nonsense" _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(3, ?)", bool3) if err != nil { t.Fatal("Failed to insert nonsense:", err) } rows, err := db.Query("SELECT id, fbool FROM foo where fbool = ?", bool1) if err != nil { t.Fatal("Unable to query foo table:", err) } counter := 0 var id int var fbool bool for rows.Next() { if err := rows.Scan(&id, &fbool); err != nil { t.Fatal("Unable to scan results:", err) } counter++ } if counter != 1 { t.Fatalf("Expected 1 row but %v", counter) } if id != 1 && fbool != true { t.Fatalf("Value for id 1 should be %v, not %v", bool1, fbool) } rows, err = db.Query("SELECT id, fbool FROM foo where fbool = ?", bool2) if err != nil { t.Fatal("Unable to query foo table:", err) } counter = 0 for rows.Next() { if err := rows.Scan(&id, &fbool); err != nil { t.Fatal("Unable to scan results:", err) } counter++ } if counter != 1 { t.Fatalf("Expected 1 row but %v", counter) } if id != 2 && fbool != false { t.Fatalf("Value for id 2 should be %v, not %v", bool2, fbool) } // make sure "nonsense" triggered an error rows, err = db.Query("SELECT id, fbool FROM foo where id=?;", 3) if err != nil { t.Fatal("Unable to query foo table:", err) } rows.Next() err = rows.Scan(&id, &fbool) if err == nil { t.Error("Expected error from \"nonsense\" bool") } } func TestFloat32(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("CREATE TABLE foo(id INTEGER)") if err != nil { t.Fatal("Failed to create table:", err) } _, err = db.Exec("INSERT INTO foo(id) VALUES(null)") if err != nil { t.Fatal("Failed to insert null:", err) } rows, err := db.Query("SELECT id FROM foo") if err != nil { t.Fatal("Unable to query foo table:", err) } if !rows.Next() { t.Fatal("Unable to query results:", err) } var id interface{} if err := rows.Scan(&id); err != nil { t.Fatal("Unable to scan results:", err) } if id != nil { t.Error("Expected nil but not") } } func TestNull(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() rows, err := db.Query("SELECT 3.141592") if err != nil { t.Fatal("Unable to query foo table:", err) } if !rows.Next() { t.Fatal("Unable to query results:", err) } var v interface{} if err := rows.Scan(&v); err != nil { t.Fatal("Unable to scan results:", err) } f, ok := v.(float64) if !ok { t.Error("Expected float but not") } if f != 3.141592 { t.Error("Expected 3.141592 but not") } } func TestTransaction(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("CREATE TABLE foo(id INTEGER)") if err != nil { t.Fatal("Failed to create table:", err) } tx, err := db.Begin() if err != nil { t.Fatal("Failed to begin transaction:", err) } _, err = tx.Exec("INSERT INTO foo(id) VALUES(1)") if err != nil { t.Fatal("Failed to insert null:", err) } rows, err := tx.Query("SELECT id from foo") if err != nil { t.Fatal("Unable to query foo table:", err) } err = tx.Rollback() if err != nil { t.Fatal("Failed to rollback transaction:", err) } if rows.Next() { t.Fatal("Unable to query results:", err) } tx, err = db.Begin() if err != nil { t.Fatal("Failed to begin transaction:", err) } _, err = tx.Exec("INSERT INTO foo(id) VALUES(1)") if err != nil { t.Fatal("Failed to insert null:", err) } err = tx.Commit() if err != nil { t.Fatal("Failed to commit transaction:", err) } rows, err = tx.Query("SELECT id from foo") if err == nil { t.Fatal("Expected failure to query") } } func TestWAL(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() if _, err = db.Exec("PRAGMA journal_mode=WAL;"); err != nil { t.Fatal("Failed to Exec PRAGMA journal_mode:", err) } if _, err = db.Exec("PRAGMA locking_mode=EXCLUSIVE;"); err != nil { t.Fatal("Failed to Exec PRAGMA locking_mode:", err) } if _, err = db.Exec("CREATE TABLE test (id SERIAL, user TEXT NOT NULL, name TEXT NOT NULL);"); err != nil { t.Fatal("Failed to Exec CREATE TABLE:", err) } if _, err = db.Exec("INSERT INTO test (user, name) VALUES ('user','name');"); err != nil { t.Fatal("Failed to Exec INSERT:", err) } trans, err := db.Begin() if err != nil { t.Fatal("Failed to Begin:", err) } s, err := trans.Prepare("INSERT INTO test (user, name) VALUES (?, ?);") if err != nil { t.Fatal("Failed to Prepare:", err) } var count int if err = trans.QueryRow("SELECT count(user) FROM test;").Scan(&count); err != nil { t.Fatal("Failed to QueryRow:", err) } if _, err = s.Exec("bbbb", "aaaa"); err != nil { t.Fatal("Failed to Exec prepared statement:", err) } if err = s.Close(); err != nil { t.Fatal("Failed to Close prepared statement:", err) } if err = trans.Commit(); err != nil { t.Fatal("Failed to Commit:", err) } } func TestTimezoneConversion(t *testing.T) { zones := []string{"UTC", "US/Central", "US/Pacific", "Local"} for _, tz := range zones { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename+"?_loc="+url.QueryEscape(tz)) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("DROP TABLE foo") _, err = db.Exec("CREATE TABLE foo(id INTEGER, ts TIMESTAMP, dt DATETIME)") if err != nil { t.Fatal("Failed to create table:", err) } loc, err := time.LoadLocation(tz) if err != nil { t.Fatal("Failed to load location:", err) } timestamp1 := time.Date(2012, time.April, 6, 22, 50, 0, 0, time.UTC) timestamp2 := time.Date(2006, time.January, 2, 15, 4, 5, 123456789, time.UTC) timestamp3 := time.Date(2012, time.November, 4, 0, 0, 0, 0, time.UTC) tests := []struct { value interface{} expected time.Time }{ {"nonsense", time.Time{}.In(loc)}, {"0000-00-00 00:00:00", time.Time{}.In(loc)}, {timestamp1, timestamp1.In(loc)}, {timestamp1.Unix(), timestamp1.In(loc)}, {timestamp1.In(time.FixedZone("TEST", -7*3600)), timestamp1.In(loc)}, {timestamp1.Format("2006-01-02 15:04:05.000"), timestamp1.In(loc)}, {timestamp1.Format("2006-01-02T15:04:05.000"), timestamp1.In(loc)}, {timestamp1.Format("2006-01-02 15:04:05"), timestamp1.In(loc)}, {timestamp1.Format("2006-01-02T15:04:05"), timestamp1.In(loc)}, {timestamp2, timestamp2.In(loc)}, {"2006-01-02 15:04:05.123456789", timestamp2.In(loc)}, {"2006-01-02T15:04:05.123456789", timestamp2.In(loc)}, {"2012-11-04", timestamp3.In(loc)}, {"2012-11-04 00:00", timestamp3.In(loc)}, {"2012-11-04 00:00:00", timestamp3.In(loc)}, {"2012-11-04 00:00:00.000", timestamp3.In(loc)}, {"2012-11-04T00:00", timestamp3.In(loc)}, {"2012-11-04T00:00:00", timestamp3.In(loc)}, {"2012-11-04T00:00:00.000", timestamp3.In(loc)}, } for i := range tests { _, err = db.Exec("INSERT INTO foo(id, ts, dt) VALUES(?, ?, ?)", i, tests[i].value, tests[i].value) if err != nil { t.Fatal("Failed to insert timestamp:", err) } } rows, err := db.Query("SELECT id, ts, dt FROM foo ORDER BY id ASC") if err != nil { t.Fatal("Unable to query foo table:", err) } defer rows.Close() seen := 0 for rows.Next() { var id int var ts, dt time.Time if err := rows.Scan(&id, &ts, &dt); err != nil { t.Error("Unable to scan results:", err) continue } if id < 0 || id >= len(tests) { t.Error("Bad row id: ", id) continue } seen++ if !tests[id].expected.Equal(ts) { t.Errorf("Timestamp value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, ts) } if !tests[id].expected.Equal(dt) { t.Errorf("Datetime value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt) } if tests[id].expected.Location().String() != ts.Location().String() { t.Errorf("Location for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected.Location().String(), ts.Location().String()) } if tests[id].expected.Location().String() != dt.Location().String() { t.Errorf("Location for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected.Location().String(), dt.Location().String()) } } if seen != len(tests) { t.Errorf("Expected to see %d rows", len(tests)) } } } // TODO: Execer & Queryer currently disabled // https://github.com/mattn/go-sqlite3/issues/82 func TestExecer(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec(` create table foo (id integer); -- one comment insert into foo(id) values(?); insert into foo(id) values(?); insert into foo(id) values(?); -- another comment `, 1, 2, 3) if err != nil { t.Error("Failed to call db.Exec:", err) } } func TestQueryer(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec(` create table foo (id integer); `) if err != nil { t.Error("Failed to call db.Query:", err) } rows, err := db.Query(` insert into foo(id) values(?); insert into foo(id) values(?); insert into foo(id) values(?); select id from foo order by id; `, 3, 2, 1) if err != nil { t.Error("Failed to call db.Query:", err) } defer rows.Close() n := 1 if rows != nil { for rows.Next() { var id int err = rows.Scan(&id) if err != nil { t.Error("Failed to db.Query:", err) } if id != n { t.Error("Failed to db.Query: not matched results") } } } } func TestStress(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } db.Exec("CREATE TABLE foo (id int);") db.Exec("INSERT INTO foo VALUES(1);") db.Exec("INSERT INTO foo VALUES(2);") db.Close() for i := 0; i < 10000; i++ { db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } for j := 0; j < 3; j++ { rows, err := db.Query("select * from foo where id=1;") if err != nil { t.Error("Failed to call db.Query:", err) } for rows.Next() { var i int if err := rows.Scan(&i); err != nil { t.Errorf("Scan failed: %v\n", err) } } if err := rows.Err(); err != nil { t.Errorf("Post-scan failed: %v\n", err) } rows.Close() } db.Close() } } func TestDateTimeLocal(t *testing.T) { zone := "Asia/Tokyo" tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename+"?_loc="+zone) if err != nil { t.Fatal("Failed to open database:", err) } db.Exec("CREATE TABLE foo (dt datetime);") db.Exec("INSERT INTO foo VALUES('2015-03-05 15:16:17');") row := db.QueryRow("select * from foo") var d time.Time err = row.Scan(&d) if err != nil { t.Fatal("Failed to scan datetime:", err) } if d.Hour() == 15 || !strings.Contains(d.String(), "JST") { t.Fatal("Result should have timezone", d) } db.Close() db, err = sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } row = db.QueryRow("select * from foo") err = row.Scan(&d) if err != nil { t.Fatal("Failed to scan datetime:", err) } if d.UTC().Hour() != 15 || !strings.Contains(d.String(), "UTC") { t.Fatalf("Result should not have timezone %v %v", zone, d.String()) } _, err = db.Exec("DELETE FROM foo") if err != nil { t.Fatal("Failed to delete table:", err) } dt, err := time.Parse("2006/1/2 15/4/5 -0700 MST", "2015/3/5 15/16/17 +0900 JST") if err != nil { t.Fatal("Failed to parse datetime:", err) } db.Exec("INSERT INTO foo VALUES(?);", dt) db.Close() db, err = sql.Open("sqlite3", tempFilename+"?_loc="+zone) if err != nil { t.Fatal("Failed to open database:", err) } row = db.QueryRow("select * from foo") err = row.Scan(&d) if err != nil { t.Fatal("Failed to scan datetime:", err) } if d.Hour() != 15 || !strings.Contains(d.String(), "JST") { t.Fatalf("Result should have timezone %v %v", zone, d.String()) } } func TestVersion(t *testing.T) { s, n, id := Version() if s == "" || n == 0 || id == "" { t.Errorf("Version failed %q, %d, %q\n", s, n, id) } } func TestStringContainingZero(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec(` create table foo (id integer, name, extra text); `) if err != nil { t.Error("Failed to call db.Query:", err) } const text = "foo\x00bar" _, err = db.Exec(`insert into foo(id, name, extra) values($1, $2, $2)`, 1, text) if err != nil { t.Error("Failed to call db.Exec:", err) } row := db.QueryRow(`select id, extra from foo where id = $1 and extra = $2`, 1, text) if row == nil { t.Error("Failed to call db.QueryRow") } var id int var extra string err = row.Scan(&id, &extra) if err != nil { t.Error("Failed to db.Scan:", err) } if id != 1 || extra != text { t.Error("Failed to db.QueryRow: not matched results") } } const CurrentTimeStamp = "2006-01-02 15:04:05" type TimeStamp struct{ *time.Time } func (t TimeStamp) Scan(value interface{}) error { var err error switch v := value.(type) { case string: *t.Time, err = time.Parse(CurrentTimeStamp, v) case []byte: *t.Time, err = time.Parse(CurrentTimeStamp, string(v)) default: err = errors.New("invalid type for current_timestamp") } return err } func (t TimeStamp) Value() (driver.Value, error) { return t.Time.Format(CurrentTimeStamp), nil } func TestDateTimeNow(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() var d time.Time err = db.QueryRow("SELECT datetime('now')").Scan(TimeStamp{&d}) if err != nil { t.Fatal("Failed to scan datetime:", err) } } func TestFunctionRegistration(t *testing.T) { addi8_16_32 := func(a int8, b int16) int32 { return int32(a) + int32(b) } addi64 := func(a, b int64) int64 { return a + b } addu8_16_32 := func(a uint8, b uint16) uint32 { return uint32(a) + uint32(b) } addu64 := func(a, b uint64) uint64 { return a + b } addiu := func(a int, b uint) int64 { return int64(a) + int64(b) } addf32_64 := func(a float32, b float64) float64 { return float64(a) + b } not := func(a bool) bool { return !a } regex := func(re, s string) (bool, error) { return regexp.MatchString(re, s) } generic := func(a interface{}) int64 { switch a.(type) { case int64: return 1 case float64: return 2 case []byte: return 3 case string: return 4 default: panic("unreachable") } } variadic := func(a, b int64, c ...int64) int64 { ret := a + b for _, d := range c { ret += d } return ret } variadicGeneric := func(a ...interface{}) int64 { return int64(len(a)) } sql.Register("sqlite3_FunctionRegistration", &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { if err := conn.RegisterFunc("addi8_16_32", addi8_16_32, true); err != nil { return err } if err := conn.RegisterFunc("addi64", addi64, true); err != nil { return err } if err := conn.RegisterFunc("addu8_16_32", addu8_16_32, true); err != nil { return err } if err := conn.RegisterFunc("addu64", addu64, true); err != nil { return err } if err := conn.RegisterFunc("addiu", addiu, true); err != nil { return err } if err := conn.RegisterFunc("addf32_64", addf32_64, true); err != nil { return err } if err := conn.RegisterFunc("not", not, true); err != nil { return err } if err := conn.RegisterFunc("regex", regex, true); err != nil { return err } if err := conn.RegisterFunc("generic", generic, true); err != nil { return err } if err := conn.RegisterFunc("variadic", variadic, true); err != nil { return err } if err := conn.RegisterFunc("variadicGeneric", variadicGeneric, true); err != nil { return err } return nil }, }) db, err := sql.Open("sqlite3_FunctionRegistration", ":memory:") if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() ops := []struct { query string expected interface{} }{ {"SELECT addi8_16_32(1,2)", int32(3)}, {"SELECT addi64(1,2)", int64(3)}, {"SELECT addu8_16_32(1,2)", uint32(3)}, {"SELECT addu64(1,2)", uint64(3)}, {"SELECT addiu(1,2)", int64(3)}, {"SELECT addf32_64(1.5,1.5)", float64(3)}, {"SELECT not(1)", false}, {"SELECT not(0)", true}, {`SELECT regex("^foo.*", "foobar")`, true}, {`SELECT regex("^foo.*", "barfoobar")`, false}, {"SELECT generic(1)", int64(1)}, {"SELECT generic(1.1)", int64(2)}, {`SELECT generic(NULL)`, int64(3)}, {`SELECT generic("foo")`, int64(4)}, {"SELECT variadic(1,2)", int64(3)}, {"SELECT variadic(1,2,3,4)", int64(10)}, {"SELECT variadic(1,1,1,1,1,1,1,1,1,1)", int64(10)}, {`SELECT variadicGeneric(1,"foo",2.3, NULL)`, int64(4)}, } for _, op := range ops { ret := reflect.New(reflect.TypeOf(op.expected)) err = db.QueryRow(op.query).Scan(ret.Interface()) if err != nil { t.Errorf("Query %q failed: %s", op.query, err) } else if !reflect.DeepEqual(ret.Elem().Interface(), op.expected) { t.Errorf("Query %q returned wrong value: got %v (%T), want %v (%T)", op.query, ret.Elem().Interface(), ret.Elem().Interface(), op.expected, op.expected) } } } func rot13(r rune) rune { switch { case r >= 'A' && r <= 'Z': return 'A' + (r-'A'+13)%26 case r >= 'a' && r <= 'z': return 'a' + (r-'a'+13)%26 } return r } func TestCollationRegistration(t *testing.T) { collateRot13 := func(a, b string) int { ra, rb := strings.Map(rot13, a), strings.Map(rot13, b) return strings.Compare(ra, rb) } collateRot13Reverse := func(a, b string) int { return collateRot13(b, a) } sql.Register("sqlite3_CollationRegistration", &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { if err := conn.RegisterCollation("rot13", collateRot13); err != nil { return err } if err := conn.RegisterCollation("rot13reverse", collateRot13Reverse); err != nil { return err } return nil }, }) db, err := sql.Open("sqlite3_CollationRegistration", ":memory:") if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() populate := []string{ `CREATE TABLE test (s TEXT)`, `INSERT INTO test VALUES ("aaaa")`, `INSERT INTO test VALUES ("ffff")`, `INSERT INTO test VALUES ("qqqq")`, `INSERT INTO test VALUES ("tttt")`, `INSERT INTO test VALUES ("zzzz")`, } for _, stmt := range populate { if _, err := db.Exec(stmt); err != nil { t.Fatal("Failed to populate test DB:", err) } } ops := []struct { query string want []string }{ { "SELECT * FROM test ORDER BY s COLLATE rot13 ASC", []string{ "qqqq", "tttt", "zzzz", "aaaa", "ffff", }, }, { "SELECT * FROM test ORDER BY s COLLATE rot13 DESC", []string{ "ffff", "aaaa", "zzzz", "tttt", "qqqq", }, }, { "SELECT * FROM test ORDER BY s COLLATE rot13reverse ASC", []string{ "ffff", "aaaa", "zzzz", "tttt", "qqqq", }, }, { "SELECT * FROM test ORDER BY s COLLATE rot13reverse DESC", []string{ "qqqq", "tttt", "zzzz", "aaaa", "ffff", }, }, } for _, op := range ops { rows, err := db.Query(op.query) if err != nil { t.Fatalf("Query %q failed: %s", op.query, err) } got := []string{} defer rows.Close() for rows.Next() { var s string if err = rows.Scan(&s); err != nil { t.Fatalf("Reading row for %q: %s", op.query, err) } got = append(got, s) } if err = rows.Err(); err != nil { t.Fatalf("Reading rows for %q: %s", op.query, err) } if !reflect.DeepEqual(got, op.want) { t.Fatalf("Unexpected output from %q\ngot:\n%s\n\nwant:\n%s", op.query, strings.Join(got, "\n"), strings.Join(op.want, "\n")) } } } func TestDeclTypes(t *testing.T) { d := SQLiteDriver{} conn, err := d.Open(":memory:") if err != nil { t.Fatal("Failed to begin transaction:", err) } defer conn.Close() sqlite3conn := conn.(*SQLiteConn) _, err = sqlite3conn.Exec("create table foo (id integer not null primary key, name text)", nil) if err != nil { t.Fatal("Failed to create table:", err) } _, err = sqlite3conn.Exec("insert into foo(name) values(\"bar\")", nil) if err != nil { t.Fatal("Failed to insert:", err) } rs, err := sqlite3conn.Query("select * from foo", nil) if err != nil { t.Fatal("Failed to select:", err) } defer rs.Close() declTypes := rs.(*SQLiteRows).DeclTypes() if !reflect.DeepEqual(declTypes, []string{"integer", "text"}) { t.Fatal("Unexpected declTypes:", declTypes) } } func TestPinger(t *testing.T) { db, err := sql.Open("sqlite3", ":memory:") if err != nil { t.Fatal(err) } err = db.Ping() if err != nil { t.Fatal(err) } db.Close() err = db.Ping() if err == nil { t.Fatal("Should be closed") } } func TestUpdateAndTransactionHooks(t *testing.T) { var events []string var commitHookReturn = 0 sql.Register("sqlite3_UpdateHook", &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { conn.RegisterCommitHook(func() int { events = append(events, "commit") return commitHookReturn }) conn.RegisterRollbackHook(func() { events = append(events, "rollback") }) conn.RegisterUpdateHook(func(op int, db string, table string, rowid int64) { events = append(events, fmt.Sprintf("update(op=%v db=%v table=%v rowid=%v)", op, db, table, rowid)) }) return nil }, }) db, err := sql.Open("sqlite3_UpdateHook", ":memory:") if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() statements := []string{ "create table foo (id integer primary key)", "insert into foo values (9)", "update foo set id = 99 where id = 9", "delete from foo where id = 99", } for _, statement := range statements { _, err = db.Exec(statement) if err != nil { t.Fatalf("Unable to prepare test data [%v]: %v", statement, err) } } commitHookReturn = 1 _, err = db.Exec("insert into foo values (5)") if err == nil { t.Error("Commit hook failed to rollback transaction") } var expected = []string{ "commit", fmt.Sprintf("update(op=%v db=main table=foo rowid=9)", SQLITE_INSERT), "commit", fmt.Sprintf("update(op=%v db=main table=foo rowid=99)", SQLITE_UPDATE), "commit", fmt.Sprintf("update(op=%v db=main table=foo rowid=99)", SQLITE_DELETE), "commit", fmt.Sprintf("update(op=%v db=main table=foo rowid=5)", SQLITE_INSERT), "commit", "rollback", } if !reflect.DeepEqual(events, expected) { t.Errorf("Expected notifications %v but got %v", expected, events) } } func TestNilAndEmptyBytes(t *testing.T) { db, err := sql.Open("sqlite3", ":memory:") if err != nil { t.Fatal(err) } defer db.Close() actualNil := []byte("use this to use an actual nil not a reference to nil") emptyBytes := []byte{} for tsti, tst := range []struct { name string columnType string insertBytes []byte expectedBytes []byte }{ {"actual nil blob", "blob", actualNil, nil}, {"referenced nil blob", "blob", nil, nil}, {"empty blob", "blob", emptyBytes, emptyBytes}, {"actual nil text", "text", actualNil, nil}, {"referenced nil text", "text", nil, nil}, {"empty text", "text", emptyBytes, emptyBytes}, } { if _, err = db.Exec(fmt.Sprintf("create table tbl%d (txt %s)", tsti, tst.columnType)); err != nil { t.Fatal(tst.name, err) } if bytes.Equal(tst.insertBytes, actualNil) { if _, err = db.Exec(fmt.Sprintf("insert into tbl%d (txt) values (?)", tsti), nil); err != nil { t.Fatal(tst.name, err) } } else { if _, err = db.Exec(fmt.Sprintf("insert into tbl%d (txt) values (?)", tsti), &tst.insertBytes); err != nil { t.Fatal(tst.name, err) } } rows, err := db.Query(fmt.Sprintf("select txt from tbl%d", tsti)) if err != nil { t.Fatal(tst.name, err) } if !rows.Next() { t.Fatal(tst.name, "no rows") } var scanBytes []byte if err = rows.Scan(&scanBytes); err != nil { t.Fatal(tst.name, err) } if err = rows.Err(); err != nil { t.Fatal(tst.name, err) } if tst.expectedBytes == nil && scanBytes != nil { t.Errorf("%s: %#v != %#v", tst.name, scanBytes, tst.expectedBytes) } else if !bytes.Equal(scanBytes, tst.expectedBytes) { t.Errorf("%s: %#v != %#v", tst.name, scanBytes, tst.expectedBytes) } } } var customFunctionOnce sync.Once func BenchmarkCustomFunctions(b *testing.B) { customFunctionOnce.Do(func() { customAdd := func(a, b int64) int64 { return a + b } sql.Register("sqlite3_BenchmarkCustomFunctions", &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { // Impure function to force sqlite to reexecute it each time. if err := conn.RegisterFunc("custom_add", customAdd, false); err != nil { return err } return nil }, }) }) db, err := sql.Open("sqlite3_BenchmarkCustomFunctions", ":memory:") if err != nil { b.Fatal("Failed to open database:", err) } defer db.Close() b.ResetTimer() for i := 0; i < b.N; i++ { var i int64 err = db.QueryRow("SELECT custom_add(1,2)").Scan(&i) if err != nil { b.Fatal("Failed to run custom add:", err) } } } func TestSuite(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) d, err := sql.Open("sqlite3", tempFilename+"?_busy_timeout=99999") if err != nil { t.Fatal(err) } defer d.Close() db = &TestDB{t, d, SQLITE, sync.Once{}} testing.RunTests(func(string, string) (bool, error) { return true, nil }, tests) if !testing.Short() { for _, b := range benchmarks { fmt.Printf("%-20s", b.Name) r := testing.Benchmark(b.F) fmt.Printf("%10d %10.0f req/s\n", r.N, float64(r.N)/r.T.Seconds()) } } db.tearDown() } // Dialect is a type of dialect of databases. type Dialect int // Dialects for databases. const ( SQLITE Dialect = iota // SQLITE mean SQLite3 dialect POSTGRESQL // POSTGRESQL mean PostgreSQL dialect MYSQL // MYSQL mean MySQL dialect ) // DB provide context for the tests type TestDB struct { *testing.T *sql.DB dialect Dialect once sync.Once } var db *TestDB // the following tables will be created and dropped during the test var testTables = []string{"foo", "bar", "t", "bench"} var tests = []testing.InternalTest{ {Name: "TestResult", F: testResult}, {Name: "TestBlobs", F: testBlobs}, {Name: "TestManyQueryRow", F: testManyQueryRow}, {Name: "TestTxQuery", F: testTxQuery}, {Name: "TestPreparedStmt", F: testPreparedStmt}, } var benchmarks = []testing.InternalBenchmark{ {Name: "BenchmarkExec", F: benchmarkExec}, {Name: "BenchmarkQuery", F: benchmarkQuery}, {Name: "BenchmarkParams", F: benchmarkParams}, {Name: "BenchmarkStmt", F: benchmarkStmt}, {Name: "BenchmarkRows", F: benchmarkRows}, {Name: "BenchmarkStmtRows", F: benchmarkStmtRows}, } func (db *TestDB) mustExec(sql string, args ...interface{}) sql.Result { res, err := db.Exec(sql, args...) if err != nil { db.Fatalf("Error running %q: %v", sql, err) } return res } func (db *TestDB) tearDown() { for _, tbl := range testTables { switch db.dialect { case SQLITE: db.mustExec("drop table if exists " + tbl) case MYSQL, POSTGRESQL: db.mustExec("drop table if exists " + tbl) default: db.Fatal("unknown dialect") } } } // q replaces ? parameters if needed func (db *TestDB) q(sql string) string { switch db.dialect { case POSTGRESQL: // repace with $1, $2, .. qrx := regexp.MustCompile(`\?`) n := 0 return qrx.ReplaceAllStringFunc(sql, func(string) string { n++ return "$" + strconv.Itoa(n) }) } return sql } func (db *TestDB) blobType(size int) string { switch db.dialect { case SQLITE: return fmt.Sprintf("blob[%d]", size) case POSTGRESQL: return "bytea" case MYSQL: return fmt.Sprintf("VARBINARY(%d)", size) } panic("unknown dialect") } func (db *TestDB) serialPK() string { switch db.dialect { case SQLITE: return "integer primary key autoincrement" case POSTGRESQL: return "serial primary key" case MYSQL: return "integer primary key auto_increment" } panic("unknown dialect") } func (db *TestDB) now() string { switch db.dialect { case SQLITE: return "datetime('now')" case POSTGRESQL: return "now()" case MYSQL: return "now()" } panic("unknown dialect") } func makeBench() { if _, err := db.Exec("create table bench (n varchar(32), i integer, d double, s varchar(32), t datetime)"); err != nil { panic(err) } st, err := db.Prepare("insert into bench values (?, ?, ?, ?, ?)") if err != nil { panic(err) } defer st.Close() for i := 0; i < 100; i++ { if _, err = st.Exec(nil, i, float64(i), fmt.Sprintf("%d", i), time.Now()); err != nil { panic(err) } } } // testResult is test for result func testResult(t *testing.T) { db.tearDown() db.mustExec("create temporary table test (id " + db.serialPK() + ", name varchar(10))") for i := 1; i < 3; i++ { r := db.mustExec(db.q("insert into test (name) values (?)"), fmt.Sprintf("row %d", i)) n, err := r.RowsAffected() if err != nil { t.Fatal(err) } if n != 1 { t.Errorf("got %v, want %v", n, 1) } n, err = r.LastInsertId() if err != nil { t.Fatal(err) } if n != int64(i) { t.Errorf("got %v, want %v", n, i) } } if _, err := db.Exec("error!"); err == nil { t.Fatalf("expected error") } } // testBlobs is test for blobs func testBlobs(t *testing.T) { db.tearDown() var blob = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} db.mustExec("create table foo (id integer primary key, bar " + db.blobType(16) + ")") db.mustExec(db.q("insert into foo (id, bar) values(?,?)"), 0, blob) want := fmt.Sprintf("%x", blob) b := make([]byte, 16) err := db.QueryRow(db.q("select bar from foo where id = ?"), 0).Scan(&b) got := fmt.Sprintf("%x", b) if err != nil { t.Errorf("[]byte scan: %v", err) } else if got != want { t.Errorf("for []byte, got %q; want %q", got, want) } err = db.QueryRow(db.q("select bar from foo where id = ?"), 0).Scan(&got) want = string(blob) if err != nil { t.Errorf("string scan: %v", err) } else if got != want { t.Errorf("for string, got %q; want %q", got, want) } } // testManyQueryRow is test for many query row func testManyQueryRow(t *testing.T) { if testing.Short() { t.Log("skipping in short mode") return } db.tearDown() db.mustExec("create table foo (id integer primary key, name varchar(50))") db.mustExec(db.q("insert into foo (id, name) values(?,?)"), 1, "bob") var name string for i := 0; i < 10000; i++ { err := db.QueryRow(db.q("select name from foo where id = ?"), 1).Scan(&name) if err != nil || name != "bob" { t.Fatalf("on query %d: err=%v, name=%q", i, err, name) } } } // testTxQuery is test for transactional query func testTxQuery(t *testing.T) { db.tearDown() tx, err := db.Begin() if err != nil { t.Fatal(err) } defer tx.Rollback() _, err = tx.Exec("create table foo (id integer primary key, name varchar(50))") if err != nil { t.Fatal(err) } _, err = tx.Exec(db.q("insert into foo (id, name) values(?,?)"), 1, "bob") if err != nil { t.Fatal(err) } r, err := tx.Query(db.q("select name from foo where id = ?"), 1) if err != nil { t.Fatal(err) } defer r.Close() if !r.Next() { if r.Err() != nil { t.Fatal(err) } t.Fatal("expected one rows") } var name string err = r.Scan(&name) if err != nil { t.Fatal(err) } } // testPreparedStmt is test for prepared statement func testPreparedStmt(t *testing.T) { db.tearDown() db.mustExec("CREATE TABLE t (count INT)") sel, err := db.Prepare("SELECT count FROM t ORDER BY count DESC") if err != nil { t.Fatalf("prepare 1: %v", err) } ins, err := db.Prepare(db.q("INSERT INTO t (count) VALUES (?)")) if err != nil { t.Fatalf("prepare 2: %v", err) } for n := 1; n <= 3; n++ { if _, err := ins.Exec(n); err != nil { t.Fatalf("insert(%d) = %v", n, err) } } const nRuns = 10 var wg sync.WaitGroup for i := 0; i < nRuns; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < 10; j++ { count := 0 if err := sel.QueryRow().Scan(&count); err != nil && err != sql.ErrNoRows { t.Errorf("Query: %v", err) return } if _, err := ins.Exec(rand.Intn(100)); err != nil { t.Errorf("Insert: %v", err) return } } }() } wg.Wait() } // Benchmarks need to use panic() since b.Error errors are lost when // running via testing.Benchmark() I would like to run these via go // test -bench but calling Benchmark() from a benchmark test // currently hangs go. // benchmarkExec is benchmark for exec func benchmarkExec(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := db.Exec("select 1"); err != nil { panic(err) } } } // benchmarkQuery is benchmark for query func benchmarkQuery(b *testing.B) { for i := 0; i < b.N; i++ { var n sql.NullString var i int var f float64 var s string // var t time.Time if err := db.QueryRow("select null, 1, 1.1, 'foo'").Scan(&n, &i, &f, &s); err != nil { panic(err) } } } // benchmarkParams is benchmark for params func benchmarkParams(b *testing.B) { for i := 0; i < b.N; i++ { var n sql.NullString var i int var f float64 var s string // var t time.Time if err := db.QueryRow("select ?, ?, ?, ?", nil, 1, 1.1, "foo").Scan(&n, &i, &f, &s); err != nil { panic(err) } } } // benchmarkStmt is benchmark for statement func benchmarkStmt(b *testing.B) { st, err := db.Prepare("select ?, ?, ?, ?") if err != nil { panic(err) } defer st.Close() for n := 0; n < b.N; n++ { var n sql.NullString var i int var f float64 var s string // var t time.Time if err := st.QueryRow(nil, 1, 1.1, "foo").Scan(&n, &i, &f, &s); err != nil { panic(err) } } } // benchmarkRows is benchmark for rows func benchmarkRows(b *testing.B) { db.once.Do(makeBench) for n := 0; n < b.N; n++ { var n sql.NullString var i int var f float64 var s string var t time.Time r, err := db.Query("select * from bench") if err != nil { panic(err) } for r.Next() { if err = r.Scan(&n, &i, &f, &s, &t); err != nil { panic(err) } } if err = r.Err(); err != nil { panic(err) } } } // benchmarkStmtRows is benchmark for statement rows func benchmarkStmtRows(b *testing.B) { db.once.Do(makeBench) st, err := db.Prepare("select * from bench") if err != nil { panic(err) } defer st.Close() for n := 0; n < b.N; n++ { var n sql.NullString var i int var f float64 var s string var t time.Time r, err := st.Query() if err != nil { panic(err) } for r.Next() { if err = r.Scan(&n, &i, &f, &s, &t); err != nil { panic(err) } } if err = r.Err(); err != nil { panic(err) } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_other.go������������������������������������0000644�0610621�0607500�00000000445�13172163427�025520� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build !windows package sqlite3 /* #cgo CFLAGS: -I. #cgo linux LDFLAGS: -ldl #cgo solaris LDFLAGS: -lc */ import "C" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_omit_load_extension.go����������������������0000644�0610621�0607500�00000001112�13172163427�030432� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build sqlite_omit_load_extension package sqlite3 /* #cgo CFLAGS: -DSQLITE_OMIT_LOAD_EXTENSION */ import "C" import ( "errors" ) func (c *SQLiteConn) loadExtensions(extensions []string) error { return errors.New("Extensions have been disabled for static builds") } func (c *SQLiteConn) LoadExtension(lib string, entry string) error { return errors.New("Extensions have been disabled for static builds") } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_load_extension.go���������������������������0000644�0610621�0607500�00000003216�13172163427�027411� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build !sqlite_omit_load_extension package sqlite3 /* #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif #include <stdlib.h> */ import "C" import ( "errors" "unsafe" ) func (c *SQLiteConn) loadExtensions(extensions []string) error { rv := C.sqlite3_enable_load_extension(c.db, 1) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } for _, extension := range extensions { cext := C.CString(extension) defer C.free(unsafe.Pointer(cext)) rv = C.sqlite3_load_extension(c.db, cext, nil, nil) if rv != C.SQLITE_OK { C.sqlite3_enable_load_extension(c.db, 0) return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } } rv = C.sqlite3_enable_load_extension(c.db, 0) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } return nil } // LoadExtension load the sqlite3 extension. func (c *SQLiteConn) LoadExtension(lib string, entry string) error { rv := C.sqlite3_enable_load_extension(c.db, 1) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } clib := C.CString(lib) defer C.free(unsafe.Pointer(clib)) centry := C.CString(entry) defer C.free(unsafe.Pointer(centry)) rv = C.sqlite3_load_extension(c.db, clib, centry, nil) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } rv = C.sqlite3_enable_load_extension(c.db, 0) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_libsqlite3.go�������������������������������0000644�0610621�0607500�00000000572�13172163427�026453� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build libsqlite3 package sqlite3 /* #cgo CFLAGS: -DUSE_LIBSQLITE3 #cgo linux LDFLAGS: -lsqlite3 #cgo darwin LDFLAGS: -L/usr/local/opt/sqlite/lib -lsqlite3 #cgo solaris LDFLAGS: -lsqlite3 */ import "C" ��������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_json1.go������������������������������������0000644�0610621�0607500�00000000401�13172163427�025421� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build json1 package sqlite3 /* #cgo CFLAGS: -DSQLITE_ENABLE_JSON1 */ import "C" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_icu.go��������������������������������������0000644�0610621�0607500�00000000435�13172163427�025156� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build icu package sqlite3 /* #cgo LDFLAGS: -licuuc -licui18n #cgo CFLAGS: -DSQLITE_ENABLE_ICU */ import "C" �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_go18_test.go��������������������������������0000644�0610621�0607500�00000006224�13172163427�026215� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build go1.8 package sqlite3 import ( "context" "database/sql" "fmt" "math/rand" "os" "testing" "time" ) func TestNamedParams(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec(` create table foo (id integer, name text, extra text); `) if err != nil { t.Error("Failed to call db.Query:", err) } _, err = db.Exec(`insert into foo(id, name, extra) values(:id, :name, :name)`, sql.Named("name", "foo"), sql.Named("id", 1)) if err != nil { t.Error("Failed to call db.Exec:", err) } row := db.QueryRow(`select id, extra from foo where id = :id and extra = :extra`, sql.Named("id", 1), sql.Named("extra", "foo")) if row == nil { t.Error("Failed to call db.QueryRow") } var id int var extra string err = row.Scan(&id, &extra) if err != nil { t.Error("Failed to db.Scan:", err) } if id != 1 || extra != "foo" { t.Error("Failed to db.QueryRow: not matched results") } } var ( testTableStatements = []string{ `DROP TABLE IF EXISTS test_table`, ` CREATE TABLE IF NOT EXISTS test_table ( key1 VARCHAR(64) PRIMARY KEY, key_id VARCHAR(64) NOT NULL, key2 VARCHAR(64) NOT NULL, key3 VARCHAR(64) NOT NULL, key4 VARCHAR(64) NOT NULL, key5 VARCHAR(64) NOT NULL, key6 VARCHAR(64) NOT NULL, data BLOB NOT NULL );`, } letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ) func randStringBytes(n int) string { b := make([]byte, n) for i := range b { b[i] = letterBytes[rand.Intn(len(letterBytes))] } return string(b) } func initDatabase(t *testing.T, db *sql.DB, rowCount int64) { t.Logf("Executing db initializing statements") for _, query := range testTableStatements { _, err := db.Exec(query) if err != nil { t.Fatal(err) } } for i := int64(0); i < rowCount; i++ { query := `INSERT INTO test_table (key1, key_id, key2, key3, key4, key5, key6, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?);` args := []interface{}{ randStringBytes(50), fmt.Sprint(i), randStringBytes(50), randStringBytes(50), randStringBytes(50), randStringBytes(50), randStringBytes(50), randStringBytes(50), randStringBytes(2048), } _, err := db.Exec(query, args...) if err != nil { t.Fatal(err) } } } func TestShortTimeout(t *testing.T) { srcTempFilename := TempFilename(t) defer os.Remove(srcTempFilename) db, err := sql.Open("sqlite3", srcTempFilename) if err != nil { t.Fatal(err) } defer db.Close() initDatabase(t, db, 100) ctx, cancel := context.WithTimeout(context.Background(), 1*time.Microsecond) defer cancel() query := `SELECT key1, key_id, key2, key3, key4, key5, key6, data FROM test_table ORDER BY key2 ASC` _, err = db.QueryContext(ctx, query) if err != nil && err != context.DeadlineExceeded { t.Fatal(err) } if ctx.Err() != nil && ctx.Err() != context.DeadlineExceeded { t.Fatal(ctx.Err()) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_go18.go�������������������������������������0000644�0610621�0607500�00000003525�13172163427�025157� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build go1.8 package sqlite3 import ( "database/sql/driver" "errors" "context" ) // Ping implement Pinger. func (c *SQLiteConn) Ping(ctx context.Context) error { if c.db == nil { return errors.New("Connection was closed") } return nil } // QueryContext implement QueryerContext. func (c *SQLiteConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, nv := range args { list[i] = namedValue(nv) } return c.query(ctx, query, list) } // ExecContext implement ExecerContext. func (c *SQLiteConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { list := make([]namedValue, len(args)) for i, nv := range args { list[i] = namedValue(nv) } return c.exec(ctx, query, list) } // PrepareContext implement ConnPrepareContext. func (c *SQLiteConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { return c.prepare(ctx, query) } // BeginTx implement ConnBeginTx. func (c *SQLiteConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { return c.begin(ctx) } // QueryContext implement QueryerContext. func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, nv := range args { list[i] = namedValue(nv) } return s.query(ctx, list) } // ExecContext implement ExecerContext. func (s *SQLiteStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { list := make([]namedValue, len(args)) for i, nv := range args { list[i] = namedValue(nv) } return s.exec(ctx, list) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_fts5.go�������������������������������������0000644�0610621�0607500�00000000421�13172163427�025252� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build fts5 package sqlite3 /* #cgo CFLAGS: -DSQLITE_ENABLE_FTS5 #cgo LDFLAGS: -lm */ import "C" �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_fts3_test.go��������������������������������0000644�0610621�0607500�00000006355�13172163427�026323� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2015 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 import ( "database/sql" "os" "testing" ) func TestFTS3(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("DROP TABLE foo") _, err = db.Exec("CREATE VIRTUAL TABLE foo USING fts3(id INTEGER PRIMARY KEY, value TEXT)") if err != nil { t.Fatal("Failed to create table:", err) } _, err = db.Exec("INSERT INTO foo(id, value) VALUES(?, ?)", 1, `今日㮠晩御飯㯠天麩羅よ`) if err != nil { t.Fatal("Failed to insert value:", err) } _, err = db.Exec("INSERT INTO foo(id, value) VALUES(?, ?)", 2, `今日㯠ã„ㄠ天気ã `) if err != nil { t.Fatal("Failed to insert value:", err) } rows, err := db.Query("SELECT id, value FROM foo WHERE value MATCH '今日* 天*'") if err != nil { t.Fatal("Unable to query foo table:", err) } defer rows.Close() for rows.Next() { var id int var value string if err := rows.Scan(&id, &value); err != nil { t.Error("Unable to scan results:", err) continue } if id == 1 && value != `今日㮠晩御飯㯠天麩羅よ` { t.Error("Value for id 1 should be `今日㮠晩御飯㯠天麩羅よ`, but:", value) } else if id == 2 && value != `今日㯠ã„ㄠ天気ã ` { t.Error("Value for id 2 should be `今日㯠ã„ㄠ天気ã `, but:", value) } } rows, err = db.Query("SELECT value FROM foo WHERE value MATCH '今日* 天麩羅*'") if err != nil { t.Fatal("Unable to query foo table:", err) } defer rows.Close() var value string if !rows.Next() { t.Fatal("Result should be only one") } if err := rows.Scan(&value); err != nil { t.Fatal("Unable to scan results:", err) } if value != `今日㮠晩御飯㯠天麩羅よ` { t.Fatal("Value should be `今日㮠晩御飯㯠天麩羅よ`, but:", value) } if rows.Next() { t.Fatal("Result should be only one") } } func TestFTS4(t *testing.T) { tempFilename := TempFilename(t) defer os.Remove(tempFilename) db, err := sql.Open("sqlite3", tempFilename) if err != nil { t.Fatal("Failed to open database:", err) } defer db.Close() _, err = db.Exec("DROP TABLE foo") _, err = db.Exec("CREATE VIRTUAL TABLE foo USING fts4(tokenize=unicode61, id INTEGER PRIMARY KEY, value TEXT)") switch { case err != nil && err.Error() == "unknown tokenizer: unicode61": t.Skip("FTS4 not supported") case err != nil: t.Fatal("Failed to create table:", err) } _, err = db.Exec("INSERT INTO foo(id, value) VALUES(?, ?)", 1, `février`) if err != nil { t.Fatal("Failed to insert value:", err) } rows, err := db.Query("SELECT value FROM foo WHERE value MATCH 'fevrier'") if err != nil { t.Fatal("Unable to query foo table:", err) } defer rows.Close() var value string if !rows.Next() { t.Fatal("Result should be only one") } if err := rows.Scan(&value); err != nil { t.Fatal("Unable to scan results:", err) } if value != `février` { t.Fatal("Value should be `février`, but:", value) } if rows.Next() { t.Fatal("Result should be only one") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3_context.go����������������������������������0000644�0610621�0607500�00000005721�13172163427�026065� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 /* #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif #include <stdlib.h> // These wrappers are necessary because SQLITE_TRANSIENT // is a pointer constant, and cgo doesn't translate them correctly. static inline void my_result_text(sqlite3_context *ctx, char *p, int np) { sqlite3_result_text(ctx, p, np, SQLITE_TRANSIENT); } static inline void my_result_blob(sqlite3_context *ctx, void *p, int np) { sqlite3_result_blob(ctx, p, np, SQLITE_TRANSIENT); } */ import "C" import ( "math" "reflect" "unsafe" ) const i64 = unsafe.Sizeof(int(0)) > 4 // SQLiteContext behave sqlite3_context type SQLiteContext C.sqlite3_context // ResultBool sets the result of an SQL function. func (c *SQLiteContext) ResultBool(b bool) { if b { c.ResultInt(1) } else { c.ResultInt(0) } } // ResultBlob sets the result of an SQL function. // See: sqlite3_result_blob, http://sqlite.org/c3ref/result_blob.html func (c *SQLiteContext) ResultBlob(b []byte) { if i64 && len(b) > math.MaxInt32 { C.sqlite3_result_error_toobig((*C.sqlite3_context)(c)) return } var p *byte if len(b) > 0 { p = &b[0] } C.my_result_blob((*C.sqlite3_context)(c), unsafe.Pointer(p), C.int(len(b))) } // ResultDouble sets the result of an SQL function. // See: sqlite3_result_double, http://sqlite.org/c3ref/result_blob.html func (c *SQLiteContext) ResultDouble(d float64) { C.sqlite3_result_double((*C.sqlite3_context)(c), C.double(d)) } // ResultInt sets the result of an SQL function. // See: sqlite3_result_int, http://sqlite.org/c3ref/result_blob.html func (c *SQLiteContext) ResultInt(i int) { if i64 && (i > math.MaxInt32 || i < math.MinInt32) { C.sqlite3_result_int64((*C.sqlite3_context)(c), C.sqlite3_int64(i)) } else { C.sqlite3_result_int((*C.sqlite3_context)(c), C.int(i)) } } // ResultInt64 sets the result of an SQL function. // See: sqlite3_result_int64, http://sqlite.org/c3ref/result_blob.html func (c *SQLiteContext) ResultInt64(i int64) { C.sqlite3_result_int64((*C.sqlite3_context)(c), C.sqlite3_int64(i)) } // ResultNull sets the result of an SQL function. // See: sqlite3_result_null, http://sqlite.org/c3ref/result_blob.html func (c *SQLiteContext) ResultNull() { C.sqlite3_result_null((*C.sqlite3_context)(c)) } // ResultText sets the result of an SQL function. // See: sqlite3_result_text, http://sqlite.org/c3ref/result_blob.html func (c *SQLiteContext) ResultText(s string) { h := (*reflect.StringHeader)(unsafe.Pointer(&s)) cs, l := (*C.char)(unsafe.Pointer(h.Data)), C.int(h.Len) C.my_result_text((*C.sqlite3_context)(c), cs, l) } // ResultZeroblob sets the result of an SQL function. // See: sqlite3_result_zeroblob, http://sqlite.org/c3ref/result_blob.html func (c *SQLiteContext) ResultZeroblob(n int) { C.sqlite3_result_zeroblob((*C.sqlite3_context)(c), C.int(n)) } �����������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3.go������������������������������������������0000644�0610621�0607500�00000071342�13172163427�024323� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 /* #cgo CFLAGS: -std=gnu99 #cgo CFLAGS: -DSQLITE_ENABLE_RTREE -DSQLITE_THREADSAFE=1 #cgo CFLAGS: -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS4_UNICODE61 #cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15 #cgo CFLAGS: -DSQLITE_DISABLE_INTRINSIC #cgo CFLAGS: -Wno-deprecated-declarations #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif #include <stdlib.h> #include <string.h> #ifdef __CYGWIN__ # include <errno.h> #endif #ifndef SQLITE_OPEN_READWRITE # define SQLITE_OPEN_READWRITE 0 #endif #ifndef SQLITE_OPEN_FULLMUTEX # define SQLITE_OPEN_FULLMUTEX 0 #endif #ifndef SQLITE_DETERMINISTIC # define SQLITE_DETERMINISTIC 0 #endif static int _sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) { #ifdef SQLITE_OPEN_URI return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs); #else return sqlite3_open_v2(filename, ppDb, flags, zVfs); #endif } static int _sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) { return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT); } static int _sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) { return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT); } #include <stdio.h> #include <stdint.h> static int _sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes) { int rv = sqlite3_exec(db, pcmd, 0, 0, 0); *rowid = (long long) sqlite3_last_insert_rowid(db); *changes = (long long) sqlite3_changes(db); return rv; } static int _sqlite3_step(sqlite3_stmt* stmt, long long* rowid, long long* changes) { int rv = sqlite3_step(stmt); sqlite3* db = sqlite3_db_handle(stmt); *rowid = (long long) sqlite3_last_insert_rowid(db); *changes = (long long) sqlite3_changes(db); return rv; } void _sqlite3_result_text(sqlite3_context* ctx, const char* s) { sqlite3_result_text(ctx, s, -1, &free); } void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) { sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT); } int _sqlite3_create_function( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, uintptr_t pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ) { return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal); } void callbackTrampoline(sqlite3_context*, int, sqlite3_value**); int compareTrampoline(void*, int, char*, int, char*); int commitHookTrampoline(void*); void rollbackHookTrampoline(void*); void updateHookTrampoline(void*, int, char*, char*, sqlite3_int64); */ import "C" import ( "database/sql" "database/sql/driver" "errors" "fmt" "io" "net/url" "reflect" "runtime" "strconv" "strings" "sync" "time" "unsafe" "golang.org/x/net/context" ) // SQLiteTimestampFormats is timestamp formats understood by both this module // and SQLite. The first format in the slice will be used when saving time // values into the database. When parsing a string from a timestamp or datetime // column, the formats are tried in order. var SQLiteTimestampFormats = []string{ // By default, store timestamps with whatever timezone they come with. // When parsed, they will be returned with the same timezone. "2006-01-02 15:04:05.999999999-07:00", "2006-01-02T15:04:05.999999999-07:00", "2006-01-02 15:04:05.999999999", "2006-01-02T15:04:05.999999999", "2006-01-02 15:04:05", "2006-01-02T15:04:05", "2006-01-02 15:04", "2006-01-02T15:04", "2006-01-02", } func init() { sql.Register("sqlite3", &SQLiteDriver{}) } // Version returns SQLite library version information. func Version() (libVersion string, libVersionNumber int, sourceID string) { libVersion = C.GoString(C.sqlite3_libversion()) libVersionNumber = int(C.sqlite3_libversion_number()) sourceID = C.GoString(C.sqlite3_sourceid()) return libVersion, libVersionNumber, sourceID } const ( SQLITE_DELETE = C.SQLITE_DELETE SQLITE_INSERT = C.SQLITE_INSERT SQLITE_UPDATE = C.SQLITE_UPDATE ) // SQLiteDriver implement sql.Driver. type SQLiteDriver struct { Extensions []string ConnectHook func(*SQLiteConn) error } // SQLiteConn implement sql.Conn. type SQLiteConn struct { mu sync.Mutex db *C.sqlite3 loc *time.Location txlock string funcs []*functionInfo aggregators []*aggInfo } // SQLiteTx implemen sql.Tx. type SQLiteTx struct { c *SQLiteConn } // SQLiteStmt implement sql.Stmt. type SQLiteStmt struct { mu sync.Mutex c *SQLiteConn s *C.sqlite3_stmt t string closed bool cls bool } // SQLiteResult implement sql.Result. type SQLiteResult struct { id int64 changes int64 } // SQLiteRows implement sql.Rows. type SQLiteRows struct { s *SQLiteStmt nc int cols []string decltype []string cls bool closed bool done chan struct{} } type functionInfo struct { f reflect.Value argConverters []callbackArgConverter variadicConverter callbackArgConverter retConverter callbackRetConverter } func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) { args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter) if err != nil { callbackError(ctx, err) return } ret := fi.f.Call(args) if len(ret) == 2 && ret[1].Interface() != nil { callbackError(ctx, ret[1].Interface().(error)) return } err = fi.retConverter(ctx, ret[0]) if err != nil { callbackError(ctx, err) return } } type aggInfo struct { constructor reflect.Value // Active aggregator objects for aggregations in flight. The // aggregators are indexed by a counter stored in the aggregation // user data space provided by sqlite. active map[int64]reflect.Value next int64 stepArgConverters []callbackArgConverter stepVariadicConverter callbackArgConverter doneRetConverter callbackRetConverter } func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) { aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8))) if *aggIdx == 0 { *aggIdx = ai.next ret := ai.constructor.Call(nil) if len(ret) == 2 && ret[1].Interface() != nil { return 0, reflect.Value{}, ret[1].Interface().(error) } if ret[0].IsNil() { return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state") } ai.next++ ai.active[*aggIdx] = ret[0] } return *aggIdx, ai.active[*aggIdx], nil } func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) { _, agg, err := ai.agg(ctx) if err != nil { callbackError(ctx, err) return } args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter) if err != nil { callbackError(ctx, err) return } ret := agg.MethodByName("Step").Call(args) if len(ret) == 1 && ret[0].Interface() != nil { callbackError(ctx, ret[0].Interface().(error)) return } } func (ai *aggInfo) Done(ctx *C.sqlite3_context) { idx, agg, err := ai.agg(ctx) if err != nil { callbackError(ctx, err) return } defer func() { delete(ai.active, idx) }() ret := agg.MethodByName("Done").Call(nil) if len(ret) == 2 && ret[1].Interface() != nil { callbackError(ctx, ret[1].Interface().(error)) return } err = ai.doneRetConverter(ctx, ret[0]) if err != nil { callbackError(ctx, err) return } } // Commit transaction. func (tx *SQLiteTx) Commit() error { _, err := tx.c.exec(context.Background(), "COMMIT", nil) if err != nil && err.(Error).Code == C.SQLITE_BUSY { // sqlite3 will leave the transaction open in this scenario. // However, database/sql considers the transaction complete once we // return from Commit() - we must clean up to honour its semantics. tx.c.exec(context.Background(), "ROLLBACK", nil) } return err } // Rollback transaction. func (tx *SQLiteTx) Rollback() error { _, err := tx.c.exec(context.Background(), "ROLLBACK", nil) return err } // RegisterCollation makes a Go function available as a collation. // // cmp receives two UTF-8 strings, a and b. The result should be 0 if // a==b, -1 if a < b, and +1 if a > b. // // cmp must always return the same result given the same // inputs. Additionally, it must have the following properties for all // strings A, B and C: if A==B then B==A; if A==B and B==C then A==C; // if A<B then B>A; if A<B and B<C then A<C. // // If cmp does not obey these constraints, sqlite3's behavior is // undefined when the collation is used. func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error { handle := newHandle(c, cmp) cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) rv := C.sqlite3_create_collation(c.db, cname, C.SQLITE_UTF8, unsafe.Pointer(handle), (*[0]byte)(unsafe.Pointer(C.compareTrampoline))) if rv != C.SQLITE_OK { return c.lastError() } return nil } // RegisterCommitHook sets the commit hook for a connection. // // If the callback returns non-zero the transaction will become a rollback. // // If there is an existing commit hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. func (c *SQLiteConn) RegisterCommitHook(callback func() int) { if callback == nil { C.sqlite3_commit_hook(c.db, nil, nil) } else { C.sqlite3_commit_hook(c.db, (*[0]byte)(unsafe.Pointer(C.commitHookTrampoline)), unsafe.Pointer(newHandle(c, callback))) } } // RegisterRollbackHook sets the rollback hook for a connection. // // If there is an existing rollback hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. func (c *SQLiteConn) RegisterRollbackHook(callback func()) { if callback == nil { C.sqlite3_rollback_hook(c.db, nil, nil) } else { C.sqlite3_rollback_hook(c.db, (*[0]byte)(unsafe.Pointer(C.rollbackHookTrampoline)), unsafe.Pointer(newHandle(c, callback))) } } // RegisterUpdateHook sets the update hook for a connection. // // The parameters to the callback are the operation (one of the constants // SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), the database name, the // table name, and the rowid. // // If there is an existing update hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) { if callback == nil { C.sqlite3_update_hook(c.db, nil, nil) } else { C.sqlite3_update_hook(c.db, (*[0]byte)(unsafe.Pointer(C.updateHookTrampoline)), unsafe.Pointer(newHandle(c, callback))) } } // RegisterFunc makes a Go function available as a SQLite function. // // The Go function can have arguments of the following types: any // numeric type except complex, bool, []byte, string and // interface{}. interface{} arguments are given the direct translation // of the SQLite data type: int64 for INTEGER, float64 for FLOAT, // []byte for BLOB, string for TEXT. // // The function can additionally be variadic, as long as the type of // the variadic argument is one of the above. // // If pure is true. SQLite will assume that the function's return // value depends only on its inputs, and make more aggressive // optimizations in its queries. // // See _example/go_custom_funcs for a detailed example. func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error { var fi functionInfo fi.f = reflect.ValueOf(impl) t := fi.f.Type() if t.Kind() != reflect.Func { return errors.New("Non-function passed to RegisterFunc") } if t.NumOut() != 1 && t.NumOut() != 2 { return errors.New("SQLite functions must return 1 or 2 values") } if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) { return errors.New("Second return value of SQLite function must be error") } numArgs := t.NumIn() if t.IsVariadic() { numArgs-- } for i := 0; i < numArgs; i++ { conv, err := callbackArg(t.In(i)) if err != nil { return err } fi.argConverters = append(fi.argConverters, conv) } if t.IsVariadic() { conv, err := callbackArg(t.In(numArgs).Elem()) if err != nil { return err } fi.variadicConverter = conv // Pass -1 to sqlite so that it allows any number of // arguments. The call helper verifies that the minimum number // of arguments is present for variadic functions. numArgs = -1 } conv, err := callbackRet(t.Out(0)) if err != nil { return err } fi.retConverter = conv // fi must outlast the database connection, or we'll have dangling pointers. c.funcs = append(c.funcs, &fi) cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) opts := C.SQLITE_UTF8 if pure { opts |= C.SQLITE_DETERMINISTIC } rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil) if rv != C.SQLITE_OK { return c.lastError() } return nil } func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTextRep C.int, pApp uintptr, xFunc unsafe.Pointer, xStep unsafe.Pointer, xFinal unsafe.Pointer) C.int { return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(pApp), (*[0]byte)(unsafe.Pointer(xFunc)), (*[0]byte)(unsafe.Pointer(xStep)), (*[0]byte)(unsafe.Pointer(xFinal))) } // AutoCommit return which currently auto commit or not. func (c *SQLiteConn) AutoCommit() bool { return int(C.sqlite3_get_autocommit(c.db)) != 0 } func (c *SQLiteConn) lastError() error { return lastError(c.db) } func lastError(db *C.sqlite3) error { rv := C.sqlite3_errcode(db) if rv == C.SQLITE_OK { return nil } return Error{ Code: ErrNo(rv), ExtendedCode: ErrNoExtended(C.sqlite3_extended_errcode(db)), err: C.GoString(C.sqlite3_errmsg(db)), } } // Exec implements Execer. func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return c.exec(context.Background(), query, list) } func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) { start := 0 for { s, err := c.prepare(ctx, query) if err != nil { return nil, err } var res driver.Result if s.(*SQLiteStmt).s != nil { na := s.NumInput() if len(args) < na { s.Close() return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args)) } for i := 0; i < na; i++ { args[i].Ordinal -= start } res, err = s.(*SQLiteStmt).exec(ctx, args[:na]) if err != nil && err != driver.ErrSkip { s.Close() return nil, err } args = args[na:] start += na } tail := s.(*SQLiteStmt).t s.Close() if tail == "" { return res, nil } query = tail } } type namedValue struct { Name string Ordinal int Value driver.Value } // Query implements Queryer. func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return c.query(context.Background(), query, list) } func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) { start := 0 for { s, err := c.prepare(ctx, query) if err != nil { return nil, err } s.(*SQLiteStmt).cls = true na := s.NumInput() if len(args) < na { return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args)) } for i := 0; i < na; i++ { args[i].Ordinal -= start } rows, err := s.(*SQLiteStmt).query(ctx, args[:na]) if err != nil && err != driver.ErrSkip { s.Close() return rows, err } args = args[na:] start += na tail := s.(*SQLiteStmt).t if tail == "" { return rows, nil } rows.Close() s.Close() query = tail } } // Begin transaction. func (c *SQLiteConn) Begin() (driver.Tx, error) { return c.begin(context.Background()) } func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) { if _, err := c.exec(ctx, c.txlock, nil); err != nil { return nil, err } return &SQLiteTx{c}, nil } func errorString(err Error) string { return C.GoString(C.sqlite3_errstr(C.int(err.Code))) } // Open database and return a new connection. // You can specify a DSN string using a URI as the filename. // test.db // file:test.db?cache=shared&mode=memory // :memory: // file::memory: // go-sqlite3 adds the following query parameters to those used by SQLite: // _loc=XXX // Specify location of time format. It's possible to specify "auto". // _busy_timeout=XXX // Specify value for sqlite3_busy_timeout. // _txlock=XXX // Specify locking behavior for transactions. XXX can be "immediate", // "deferred", "exclusive". // _foreign_keys=X // Enable or disable enforcement of foreign keys. X can be 1 or 0. // _recursive_triggers=X // Enable or disable recursive triggers. X can be 1 or 0. func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) { if C.sqlite3_threadsafe() == 0 { return nil, errors.New("sqlite library was not compiled for thread-safe operation") } var loc *time.Location txlock := "BEGIN" busyTimeout := 5000 foreignKeys := -1 recursiveTriggers := -1 pos := strings.IndexRune(dsn, '?') if pos >= 1 { params, err := url.ParseQuery(dsn[pos+1:]) if err != nil { return nil, err } // _loc if val := params.Get("_loc"); val != "" { if val == "auto" { loc = time.Local } else { loc, err = time.LoadLocation(val) if err != nil { return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err) } } } // _busy_timeout if val := params.Get("_busy_timeout"); val != "" { iv, err := strconv.ParseInt(val, 10, 64) if err != nil { return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err) } busyTimeout = int(iv) } // _txlock if val := params.Get("_txlock"); val != "" { switch val { case "immediate": txlock = "BEGIN IMMEDIATE" case "exclusive": txlock = "BEGIN EXCLUSIVE" case "deferred": txlock = "BEGIN" default: return nil, fmt.Errorf("Invalid _txlock: %v", val) } } // _foreign_keys if val := params.Get("_foreign_keys"); val != "" { switch val { case "1": foreignKeys = 1 case "0": foreignKeys = 0 default: return nil, fmt.Errorf("Invalid _foreign_keys: %v", val) } } // _recursive_triggers if val := params.Get("_recursive_triggers"); val != "" { switch val { case "1": recursiveTriggers = 1 case "0": recursiveTriggers = 0 default: return nil, fmt.Errorf("Invalid _recursive_triggers: %v", val) } } if !strings.HasPrefix(dsn, "file:") { dsn = dsn[:pos] } } var db *C.sqlite3 name := C.CString(dsn) defer C.free(unsafe.Pointer(name)) rv := C._sqlite3_open_v2(name, &db, C.SQLITE_OPEN_FULLMUTEX| C.SQLITE_OPEN_READWRITE| C.SQLITE_OPEN_CREATE, nil) if rv != 0 { return nil, Error{Code: ErrNo(rv)} } if db == nil { return nil, errors.New("sqlite succeeded without returning a database") } rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout)) if rv != C.SQLITE_OK { C.sqlite3_close_v2(db) return nil, Error{Code: ErrNo(rv)} } exec := func(s string) error { cs := C.CString(s) rv := C.sqlite3_exec(db, cs, nil, nil, nil) C.free(unsafe.Pointer(cs)) if rv != C.SQLITE_OK { return lastError(db) } return nil } if foreignKeys == 0 { if err := exec("PRAGMA foreign_keys = OFF;"); err != nil { C.sqlite3_close_v2(db) return nil, err } } else if foreignKeys == 1 { if err := exec("PRAGMA foreign_keys = ON;"); err != nil { C.sqlite3_close_v2(db) return nil, err } } if recursiveTriggers == 0 { if err := exec("PRAGMA recursive_triggers = OFF;"); err != nil { C.sqlite3_close_v2(db) return nil, err } } else if recursiveTriggers == 1 { if err := exec("PRAGMA recursive_triggers = ON;"); err != nil { C.sqlite3_close_v2(db) return nil, err } } conn := &SQLiteConn{db: db, loc: loc, txlock: txlock} if len(d.Extensions) > 0 { if err := conn.loadExtensions(d.Extensions); err != nil { conn.Close() return nil, err } } if d.ConnectHook != nil { if err := d.ConnectHook(conn); err != nil { conn.Close() return nil, err } } runtime.SetFinalizer(conn, (*SQLiteConn).Close) return conn, nil } // Close the connection. func (c *SQLiteConn) Close() error { rv := C.sqlite3_close_v2(c.db) if rv != C.SQLITE_OK { return c.lastError() } deleteHandles(c) c.mu.Lock() c.db = nil c.mu.Unlock() runtime.SetFinalizer(c, nil) return nil } func (c *SQLiteConn) dbConnOpen() bool { if c == nil { return false } c.mu.Lock() defer c.mu.Unlock() return c.db != nil } // Prepare the query string. Return a new statement. func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) { return c.prepare(context.Background(), query) } func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) { pquery := C.CString(query) defer C.free(unsafe.Pointer(pquery)) var s *C.sqlite3_stmt var tail *C.char rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &tail) if rv != C.SQLITE_OK { return nil, c.lastError() } var t string if tail != nil && *tail != '\000' { t = strings.TrimSpace(C.GoString(tail)) } ss := &SQLiteStmt{c: c, s: s, t: t} runtime.SetFinalizer(ss, (*SQLiteStmt).Close) return ss, nil } // Close the statement. func (s *SQLiteStmt) Close() error { s.mu.Lock() defer s.mu.Unlock() if s.closed { return nil } s.closed = true if !s.c.dbConnOpen() { return errors.New("sqlite statement with already closed database connection") } rv := C.sqlite3_finalize(s.s) s.s = nil if rv != C.SQLITE_OK { return s.c.lastError() } runtime.SetFinalizer(s, nil) return nil } // NumInput return a number of parameters. func (s *SQLiteStmt) NumInput() int { return int(C.sqlite3_bind_parameter_count(s.s)) } type bindArg struct { n int v driver.Value } var placeHolder = []byte{0} func (s *SQLiteStmt) bind(args []namedValue) error { rv := C.sqlite3_reset(s.s) if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE { return s.c.lastError() } for i, v := range args { if v.Name != "" { cname := C.CString(":" + v.Name) args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname)) C.free(unsafe.Pointer(cname)) } } for _, arg := range args { n := C.int(arg.Ordinal) switch v := arg.Value.(type) { case nil: rv = C.sqlite3_bind_null(s.s, n) case string: if len(v) == 0 { rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0)) } else { b := []byte(v) rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b))) } case int64: rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v)) case bool: if bool(v) { rv = C.sqlite3_bind_int(s.s, n, 1) } else { rv = C.sqlite3_bind_int(s.s, n, 0) } case float64: rv = C.sqlite3_bind_double(s.s, n, C.double(v)) case []byte: ln := len(v) if ln == 0 { v = placeHolder } rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln)) case time.Time: b := []byte(v.Format(SQLiteTimestampFormats[0])) rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b))) } if rv != C.SQLITE_OK { return s.c.lastError() } } return nil } // Query the statement with arguments. Return records. func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return s.query(context.Background(), list) } func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) { if err := s.bind(args); err != nil { return nil, err } rows := &SQLiteRows{ s: s, nc: int(C.sqlite3_column_count(s.s)), cols: nil, decltype: nil, cls: s.cls, closed: false, done: make(chan struct{}), } go func(db *C.sqlite3) { select { case <-ctx.Done(): select { case <-rows.done: default: C.sqlite3_interrupt(db) rows.Close() } case <-rows.done: } }(s.c.db) return rows, nil } // LastInsertId teturn last inserted ID. func (r *SQLiteResult) LastInsertId() (int64, error) { return r.id, nil } // RowsAffected return how many rows affected. func (r *SQLiteResult) RowsAffected() (int64, error) { return r.changes, nil } // Exec execute the statement with arguments. Return result object. func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return s.exec(context.Background(), list) } func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) { if err := s.bind(args); err != nil { C.sqlite3_reset(s.s) C.sqlite3_clear_bindings(s.s) return nil, err } done := make(chan struct{}) defer close(done) go func(db *C.sqlite3) { select { case <-ctx.Done(): C.sqlite3_interrupt(db) case <-done: } }(s.c.db) var rowid, changes C.longlong rv := C._sqlite3_step(s.s, &rowid, &changes) if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE { err := s.c.lastError() C.sqlite3_reset(s.s) C.sqlite3_clear_bindings(s.s) return nil, err } return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil } // Close the rows. func (rc *SQLiteRows) Close() error { rc.s.mu.Lock() if rc.s.closed || rc.closed { rc.s.mu.Unlock() return nil } rc.closed = true if rc.done != nil { close(rc.done) } if rc.cls { rc.s.mu.Unlock() return rc.s.Close() } rv := C.sqlite3_reset(rc.s.s) if rv != C.SQLITE_OK { rc.s.mu.Unlock() return rc.s.c.lastError() } rc.s.mu.Unlock() return nil } // Columns return column names. func (rc *SQLiteRows) Columns() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() if rc.s.s != nil && rc.nc != len(rc.cols) { rc.cols = make([]string, rc.nc) for i := 0; i < rc.nc; i++ { rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i))) } } return rc.cols } func (rc *SQLiteRows) declTypes() []string { if rc.s.s != nil && rc.decltype == nil { rc.decltype = make([]string, rc.nc) for i := 0; i < rc.nc; i++ { rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i)))) } } return rc.decltype } // DeclTypes return column types. func (rc *SQLiteRows) DeclTypes() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() return rc.declTypes() } // Next move cursor to next. func (rc *SQLiteRows) Next(dest []driver.Value) error { if rc.s.closed { return io.EOF } rc.s.mu.Lock() defer rc.s.mu.Unlock() rv := C.sqlite3_step(rc.s.s) if rv == C.SQLITE_DONE { return io.EOF } if rv != C.SQLITE_ROW { rv = C.sqlite3_reset(rc.s.s) if rv != C.SQLITE_OK { return rc.s.c.lastError() } return nil } rc.declTypes() for i := range dest { switch C.sqlite3_column_type(rc.s.s, C.int(i)) { case C.SQLITE_INTEGER: val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i))) switch rc.decltype[i] { case "timestamp", "datetime", "date": var t time.Time // Assume a millisecond unix timestamp if it's 13 digits -- too // large to be a reasonable timestamp in seconds. if val > 1e12 || val < -1e12 { val *= int64(time.Millisecond) // convert ms to nsec t = time.Unix(0, val) } else { t = time.Unix(val, 0) } t = t.UTC() if rc.s.c.loc != nil { t = t.In(rc.s.c.loc) } dest[i] = t case "boolean": dest[i] = val > 0 default: dest[i] = val } case C.SQLITE_FLOAT: dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i))) case C.SQLITE_BLOB: p := C.sqlite3_column_blob(rc.s.s, C.int(i)) if p == nil { dest[i] = nil continue } n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i))) switch dest[i].(type) { case sql.RawBytes: dest[i] = (*[1 << 30]byte)(unsafe.Pointer(p))[0:n] default: slice := make([]byte, n) copy(slice[:], (*[1 << 30]byte)(unsafe.Pointer(p))[0:n]) dest[i] = slice } case C.SQLITE_NULL: dest[i] = nil case C.SQLITE_TEXT: var err error var timeVal time.Time n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i))) s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n)) switch rc.decltype[i] { case "timestamp", "datetime", "date": var t time.Time s = strings.TrimSuffix(s, "Z") for _, format := range SQLiteTimestampFormats { if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil { t = timeVal break } } if err != nil { // The column is a time value, so return the zero time on parse failure. t = time.Time{} } if rc.s.c.loc != nil { t = t.In(rc.s.c.loc) } dest[i] = t default: dest[i] = []byte(s) } } } return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3-binding.h�����������������������������������0000644�0610621�0607500�00001711652�13172163427�025563� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#ifndef USE_LIBSQLITE3 /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the SQLite library ** presents to client programs. If a C-function, structure, datatype, ** or constant definition does not appear in this file, then it is ** not a published API of SQLite, is subject to change without ** notice, and should not be referenced by programs that use SQLite. ** ** Some of the definitions that are in this file are marked as ** "experimental". Experimental interfaces are normally new ** features recently added to SQLite. We do not anticipate changes ** to experimental interfaces but reserve the right to make minor changes ** if experience from use "in the wild" suggest such changes are prudent. ** ** The official C-language API documentation for SQLite is derived ** from comments in this file. This file is the authoritative source ** on how SQLite interfaces are supposed to operate. ** ** The name of this file under configuration management is "sqlite.h.in". ** The makefile makes some minor changes to this file (such as inserting ** the version number) and changes its name to "sqlite3.h" as ** part of the build process. */ #ifndef SQLITE3_H #define SQLITE3_H #include <stdarg.h> /* Needed for the definition of va_list */ /* ** Make sure we can call this stuff from C++. */ #ifdef __cplusplus extern "C" { #endif /* ** Provide the ability to override linkage features of the interface. */ #ifndef SQLITE_EXTERN # define SQLITE_EXTERN extern #endif #ifndef SQLITE_API # define SQLITE_API #endif #ifndef SQLITE_CDECL # define SQLITE_CDECL #endif #ifndef SQLITE_APICALL # define SQLITE_APICALL #endif #ifndef SQLITE_STDCALL # define SQLITE_STDCALL SQLITE_APICALL #endif #ifndef SQLITE_CALLBACK # define SQLITE_CALLBACK #endif #ifndef SQLITE_SYSAPI # define SQLITE_SYSAPI #endif /* ** These no-op macros are used in front of interfaces to mark those ** interfaces as either deprecated or experimental. New applications ** should not use deprecated interfaces - they are supported for backwards ** compatibility only. Application writers should be aware that ** experimental interfaces are subject to change in point releases. ** ** These macros used to resolve to various kinds of compiler magic that ** would generate warning messages when they were used. But that ** compiler magic ended up generating such a flurry of bug reports ** that we have taken it all out and gone back to using simple ** noop macros. */ #define SQLITE_DEPRECATED #define SQLITE_EXPERIMENTAL /* ** Ensure these symbols were not defined by some previous header file. */ #ifdef SQLITE_VERSION # undef SQLITE_VERSION #endif #ifdef SQLITE_VERSION_NUMBER # undef SQLITE_VERSION_NUMBER #endif /* ** CAPI3REF: Compile-Time Library Version Numbers ** ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header ** evaluates to a string literal that is the SQLite version in the ** format "X.Y.Z" where X is the major version number (always 3 for ** SQLite3) and Y is the minor version number and Z is the release number.)^ ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same ** numbers used in [SQLITE_VERSION].)^ ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also ** be larger than the release from which it is derived. Either Y will ** be held constant and Z will be incremented or else Y will be incremented ** and Z will be reset to zero. ** ** Since [version 3.6.18] ([dateof:3.6.18]), ** SQLite source code has been stored in the ** <a href="http://www.fossil-scm.org/">Fossil configuration management ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to ** a string which identifies a particular check-in of SQLite ** within its configuration management system. ^The SQLITE_SOURCE_ID ** string contains the date and time of the check-in (UTC) and an SHA1 ** hash of the entire source tree. ** ** See also: [sqlite3_libversion()], ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ #define SQLITE_VERSION "3.17.0" #define SQLITE_VERSION_NUMBER 3017000 #define SQLITE_SOURCE_ID "2017-02-13 16:02:40 ada05cfa86ad7f5645450ac7a2a21c9aa6e57d2c" /* ** CAPI3REF: Run-Time Library Version Numbers ** KEYWORDS: sqlite3_version sqlite3_sourceid ** ** These interfaces provide the same information as the [SQLITE_VERSION], ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros ** but are associated with the library instead of the header file. ^(Cautious ** programmers might include assert() statements in their application to ** verify that values returned by these interfaces match the macros in ** the header, and thus ensure that the application is ** compiled with matching library and header files. ** ** <blockquote><pre> ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER ); ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 ); ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 ); ** </pre></blockquote>)^ ** ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] ** macro. ^The sqlite3_libversion() function returns a pointer to the ** to the sqlite3_version[] string constant. The sqlite3_libversion() ** function is provided for use in DLLs since DLL users usually do not have ** direct access to string constants within the DLL. ^The ** sqlite3_libversion_number() function returns an integer equal to ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns ** a pointer to a string constant whose value is the same as the ** [SQLITE_SOURCE_ID] C preprocessor macro. ** ** See also: [sqlite_version()] and [sqlite_source_id()]. */ SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; SQLITE_API const char *sqlite3_libversion(void); SQLITE_API const char *sqlite3_sourceid(void); SQLITE_API int sqlite3_libversion_number(void); /* ** CAPI3REF: Run-Time Library Compilation Options Diagnostics ** ** ^The sqlite3_compileoption_used() function returns 0 or 1 ** indicating whether the specified option was defined at ** compile time. ^The SQLITE_ prefix may be omitted from the ** option name passed to sqlite3_compileoption_used(). ** ** ^The sqlite3_compileoption_get() function allows iterating ** over the list of options that were defined at compile time by ** returning the N-th compile time option string. ^If N is out of range, ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ ** prefix is omitted from any strings returned by ** sqlite3_compileoption_get(). ** ** ^Support for the diagnostic functions sqlite3_compileoption_used() ** and sqlite3_compileoption_get() may be omitted by specifying the ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. ** ** See also: SQL functions [sqlite_compileoption_used()] and ** [sqlite_compileoption_get()] and the [compile_options pragma]. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS SQLITE_API int sqlite3_compileoption_used(const char *zOptName); SQLITE_API const char *sqlite3_compileoption_get(int N); #endif /* ** CAPI3REF: Test To See If The Library Is Threadsafe ** ** ^The sqlite3_threadsafe() function returns zero if and only if ** SQLite was compiled with mutexing code omitted due to the ** [SQLITE_THREADSAFE] compile-time option being set to 0. ** ** SQLite can be compiled with or without mutexes. When ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes ** are enabled and SQLite is threadsafe. When the ** [SQLITE_THREADSAFE] macro is 0, ** the mutexes are omitted. Without the mutexes, it is not safe ** to use SQLite concurrently from more than one thread. ** ** Enabling mutexes incurs a measurable performance penalty. ** So if speed is of utmost importance, it makes sense to disable ** the mutexes. But for maximum safety, mutexes should be enabled. ** ^The default behavior is for mutexes to be enabled. ** ** This interface can be used by an application to make sure that the ** version of SQLite that it is linking against was compiled with ** the desired setting of the [SQLITE_THREADSAFE] macro. ** ** This interface only reports on the compile-time mutex setting ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but ** can be fully or partially disabled using a call to [sqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the ** sqlite3_threadsafe() function shows only the compile-time setting of ** thread safety, not any run-time changes to that setting made by ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() ** is unchanged by calls to sqlite3_config().)^ ** ** See the [threading mode] documentation for additional information. */ SQLITE_API int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle ** KEYWORDS: {database connection} {database connections} ** ** Each open SQLite database is represented by a pointer to an instance of ** the opaque structure named "sqlite3". It is useful to think of an sqlite3 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] ** and [sqlite3_close_v2()] are its destructors. There are many other ** interfaces (such as ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and ** [sqlite3_busy_timeout()] to name but three) that are methods on an ** sqlite3 object. */ typedef struct sqlite3 sqlite3; /* ** CAPI3REF: 64-Bit Integer Types ** KEYWORDS: sqlite_int64 sqlite_uint64 ** ** Because there is no cross-platform way to specify 64-bit integer types ** SQLite includes typedefs for 64-bit signed and unsigned integers. ** ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards ** compatibility only. ** ** ^The sqlite3_int64 and sqlite_int64 types can store integer values ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The ** sqlite3_uint64 and sqlite_uint64 types can store integer values ** between 0 and +18446744073709551615 inclusive. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; # ifdef SQLITE_UINT64_TYPE typedef SQLITE_UINT64_TYPE sqlite_uint64; # else typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; # endif #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef __int64 sqlite_int64; typedef unsigned __int64 sqlite_uint64; #else typedef long long int sqlite_int64; typedef unsigned long long int sqlite_uint64; #endif typedef sqlite_int64 sqlite3_int64; typedef sqlite_uint64 sqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point. */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite3_int64 #endif /* ** CAPI3REF: Closing A Database Connection ** DESTRUCTOR: sqlite3 ** ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors ** for the [sqlite3] object. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if ** the [sqlite3] object is successfully destroyed and all associated ** resources are deallocated. ** ** ^If the database connection is associated with unfinalized prepared ** statements or unfinished sqlite3_backup objects then sqlite3_close() ** will leave the database connection open and return [SQLITE_BUSY]. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements ** and/or unfinished sqlite3_backups, then the database connection becomes ** an unusable "zombie" which will automatically be deallocated when the ** last prepared statement is finalized or the last sqlite3_backup is ** finished. The sqlite3_close_v2() interface is intended for use with ** host languages that are garbage collected, and where the order in which ** destructors are called is arbitrary. ** ** Applications should [sqlite3_finalize | finalize] all [prepared statements], ** [sqlite3_blob_close | close] all [BLOB handles], and ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated ** with the [sqlite3] object prior to attempting to close the object. ^If ** sqlite3_close_v2() is called on a [database connection] that still has ** outstanding [prepared statements], [BLOB handles], and/or ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation ** of resources is deferred until all [prepared statements], [BLOB handles], ** and [sqlite3_backup] objects are also destroyed. ** ** ^If an [sqlite3] object is destroyed while a transaction is open, ** the transaction is automatically rolled back. ** ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] ** must be either a NULL ** pointer or an [sqlite3] object pointer obtained ** from [sqlite3_open()], [sqlite3_open16()], or ** [sqlite3_open_v2()], and not previously closed. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer ** argument is a harmless no-op. */ SQLITE_API int sqlite3_close(sqlite3*); SQLITE_API int sqlite3_close_v2(sqlite3*); /* ** The type for a callback function. ** This is legacy and deprecated. It is included for historical ** compatibility and is not documented. */ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface ** METHOD: sqlite3 ** ** The sqlite3_exec() interface is a convenience wrapper around ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], ** that allows an application to run multiple statements of SQL ** without having to use a lot of C code. ** ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, ** semicolon-separate SQL statements passed into its 2nd argument, ** in the context of the [database connection] passed in as its 1st ** argument. ^If the callback function of the 3rd argument to ** sqlite3_exec() is not NULL, then it is invoked for each result row ** coming out of the evaluated SQL statements. ^The 4th argument to ** sqlite3_exec() is relayed through to the 1st argument of each ** callback invocation. ^If the callback pointer to sqlite3_exec() ** is NULL, then no callback is ever invoked and result rows are ** ignored. ** ** ^If an error occurs while evaluating the SQL statements passed into ** sqlite3_exec(), then execution of the current statement stops and ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() ** is not NULL then any error message is written into memory obtained ** from [sqlite3_malloc()] and passed back through the 5th parameter. ** To avoid memory leaks, the application should invoke [sqlite3_free()] ** on error message strings returned through the 5th parameter of ** sqlite3_exec() after the error message string is no longer needed. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to ** NULL before returning. ** ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() ** routine returns SQLITE_ABORT without invoking the callback again and ** without running any subsequent SQL statements. ** ** ^The 2nd argument to the sqlite3_exec() callback function is the ** number of columns in the result. ^The 3rd argument to the sqlite3_exec() ** callback is an array of pointers to strings obtained as if from ** [sqlite3_column_text()], one for each column. ^If an element of a ** result row is NULL then the corresponding string pointer for the ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the ** sqlite3_exec() callback is an array of pointers to strings where each ** entry represents the name of corresponding result column as obtained ** from [sqlite3_column_name()]. ** ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer ** to an empty string, or a pointer that contains only whitespace and/or ** SQL comments, then no SQL statements are evaluated and the database ** is not changed. ** ** Restrictions: ** ** <ul> ** <li> The application must ensure that the 1st parameter to sqlite3_exec() ** is a valid and open [database connection]. ** <li> The application must not close the [database connection] specified by ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. ** <li> The application must not modify the SQL statement text passed into ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. ** </ul> */ SQLITE_API int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); /* ** CAPI3REF: Result Codes ** KEYWORDS: {result code definitions} ** ** Many SQLite functions return an integer result code from the set shown ** here in order to indicate success or failure. ** ** New error codes may be added in future versions of SQLite. ** ** See also: [extended result code definitions] */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ #define SQLITE_ERROR 1 /* SQL error or missing database */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ #define SQLITE_BUSY 5 /* The database file is locked */ #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ #define SQLITE_EMPTY 16 /* Database is empty */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ #define SQLITE_MISMATCH 20 /* Data type mismatch */ #define SQLITE_MISUSE 21 /* Library used incorrectly */ #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ #define SQLITE_AUTH 23 /* Authorization denied */ #define SQLITE_FORMAT 24 /* Auxiliary database format error */ #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ #define SQLITE_NOTADB 26 /* File opened that is not a database file */ #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ /* end-of-error-codes */ /* ** CAPI3REF: Extended Result Codes ** KEYWORDS: {extended result code definitions} ** ** In its default configuration, SQLite API routines return one of 30 integer ** [result codes]. However, experience has shown that many of ** these result codes are too coarse-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8] ** and later) include ** support for additional result codes that provide more detailed information ** about errors. These [extended result codes] are enabled or disabled ** on a per database connection basis using the ** [sqlite3_extended_result_codes()] API. Or, the extended code for ** the most recent error can be obtained using ** [sqlite3_extended_errcode()]. */ #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8)) #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) /* ** CAPI3REF: Flags For File Open Operations ** ** These bit values are intended for use in the ** 3rd parameter to the [sqlite3_open_v2()] interface and ** in the 4th parameter to the [sqlite3_vfs.xOpen] method. */ #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ /* Reserved: 0x00F00000 */ /* ** CAPI3REF: Device Characteristics ** ** The xDeviceCharacteristics method of the [sqlite3_io_methods] ** object returns an integer which is a vector of these ** bit values expressing I/O characteristics of the mass storage ** device that holds the file that the [sqlite3_io_methods] ** refers to. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that ** after reboot following a crash or power loss, the only bytes in a ** file that were written at the application level might have changed ** and that adjacent bytes, even bytes within the same sector are ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN ** flag indicates that a file cannot be deleted when open. The ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on ** read-only media and cannot be changed even by processes with ** elevated privileges. */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 #define SQLITE_IOCAP_ATOMIC1K 0x00000004 #define SQLITE_IOCAP_ATOMIC2K 0x00000008 #define SQLITE_IOCAP_ATOMIC4K 0x00000010 #define SQLITE_IOCAP_ATOMIC8K 0x00000020 #define SQLITE_IOCAP_ATOMIC16K 0x00000040 #define SQLITE_IOCAP_ATOMIC32K 0x00000080 #define SQLITE_IOCAP_ATOMIC64K 0x00000100 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 /* ** CAPI3REF: File Locking Levels ** ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 #define SQLITE_LOCK_RESERVED 2 #define SQLITE_LOCK_PENDING 3 #define SQLITE_LOCK_EXCLUSIVE 4 /* ** CAPI3REF: Synchronization Type Flags ** ** When SQLite invokes the xSync() method of an ** [sqlite3_io_methods] object it uses a combination of ** these integer values as the second argument. ** ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the ** sync operation only needs to flush data to mass storage. Inode ** information need not be flushed. If the lower four bits of the flag ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. ** If the lower four bits equal SQLITE_SYNC_FULL, that means ** to use Mac OS X style fullsync instead of fsync(). ** ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL ** settings. The [synchronous pragma] determines when calls to the ** xSync VFS method occur and applies uniformly across all platforms. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how ** energetic or rigorous or forceful the sync operations are and ** only make a difference on Mac OSX for the default SQLite code. ** (Third-party VFS implementations might also make the distinction ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the ** operating systems natively supported by SQLite, only Mac OSX ** cares about the difference.) */ #define SQLITE_SYNC_NORMAL 0x00002 #define SQLITE_SYNC_FULL 0x00003 #define SQLITE_SYNC_DATAONLY 0x00010 /* ** CAPI3REF: OS Interface Open File Handle ** ** An [sqlite3_file] object represents an open file in the ** [sqlite3_vfs | OS interface layer]. Individual OS interface ** implementations will ** want to subclass this object by appending additional fields ** for their own use. The pMethods entry is a pointer to an ** [sqlite3_io_methods] object that defines methods for performing ** I/O operations on the open file. */ typedef struct sqlite3_file sqlite3_file; struct sqlite3_file { const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ }; /* ** CAPI3REF: OS Interface File Virtual Methods Object ** ** Every file opened by the [sqlite3_vfs.xOpen] method populates an ** [sqlite3_file] object (or, more commonly, a subclass of the ** [sqlite3_file] object) with a pointer to an instance of this object. ** This object defines the methods used to perform various operations ** against the open file represented by the [sqlite3_file] object. ** ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element ** to NULL. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] ** flag may be ORed in to indicate that only the data of the file ** and not its inode needs to be synced. ** ** The integer values to xLock() and xUnlock() are one of ** <ul> ** <li> [SQLITE_LOCK_NONE], ** <li> [SQLITE_LOCK_SHARED], ** <li> [SQLITE_LOCK_RESERVED], ** <li> [SQLITE_LOCK_PENDING], or ** <li> [SQLITE_LOCK_EXCLUSIVE]. ** </ul> ** xLock() increases the lock. xUnlock() decreases the lock. ** The xCheckReservedLock() method checks whether any database connection, ** either in this process or in some other process, is holding a RESERVED, ** PENDING, or EXCLUSIVE lock on the file. It returns true ** if such a lock exists and false otherwise. ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the ** [sqlite3_file_control()] interface. The second "op" argument is an ** integer opcode. The third argument is a generic pointer intended to ** point to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be ** functions to enable blocking locks with timeouts, to change the ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite ** core reserves all opcodes less than 100 for its own use. ** A [file control opcodes | list of opcodes] less than 100 is available. ** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. VFS implementations should ** return [SQLITE_NOTFOUND] for file control opcodes that they do not ** recognize. ** ** The xSectorSize() method returns the sector size of the ** device that underlies the file. The sector size is the ** minimum write that can be performed without disturbing ** other bytes in the file. The xDeviceCharacteristics() ** method returns a bit vector describing behaviors of the ** underlying device: ** ** <ul> ** <li> [SQLITE_IOCAP_ATOMIC] ** <li> [SQLITE_IOCAP_ATOMIC512] ** <li> [SQLITE_IOCAP_ATOMIC1K] ** <li> [SQLITE_IOCAP_ATOMIC2K] ** <li> [SQLITE_IOCAP_ATOMIC4K] ** <li> [SQLITE_IOCAP_ATOMIC8K] ** <li> [SQLITE_IOCAP_ATOMIC16K] ** <li> [SQLITE_IOCAP_ATOMIC32K] ** <li> [SQLITE_IOCAP_ATOMIC64K] ** <li> [SQLITE_IOCAP_SAFE_APPEND] ** <li> [SQLITE_IOCAP_SEQUENTIAL] ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN] ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE] ** <li> [SQLITE_IOCAP_IMMUTABLE] ** </ul> ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). ** ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill ** in the unread portions of the buffer with zeros. A VFS that ** fails to zero-fill short reads might seem to work. However, ** failure to zero-fill short reads will eventually lead to ** database corruption. */ typedef struct sqlite3_io_methods sqlite3_io_methods; struct sqlite3_io_methods { int iVersion; int (*xClose)(sqlite3_file*); int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); int (*xSync)(sqlite3_file*, int flags); int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); int (*xLock)(sqlite3_file*, int); int (*xUnlock)(sqlite3_file*, int); int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); int (*xFileControl)(sqlite3_file*, int op, void *pArg); int (*xSectorSize)(sqlite3_file*); int (*xDeviceCharacteristics)(sqlite3_file*); /* Methods above are valid for version 1 */ int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); void (*xShmBarrier)(sqlite3_file*); int (*xShmUnmap)(sqlite3_file*, int deleteFlag); /* Methods above are valid for version 2 */ int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); /* Methods above are valid for version 3 */ /* Additional methods may be added in future releases */ }; /* ** CAPI3REF: Standard File Control Opcodes ** KEYWORDS: {file control opcodes} {file control opcode} ** ** These integer constants are opcodes for the xFileControl method ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] ** interface. ** ** <ul> ** <li>[[SQLITE_FCNTL_LOCKSTATE]] ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This ** opcode causes the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) ** into an integer that the pArg argument points to. This capability ** is used during testing and is only available when the SQLITE_TEST ** compile-time option is used. ** ** <li>[[SQLITE_FCNTL_SIZE_HINT]] ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS ** layer a hint of how large the database file will grow to be during the ** current transaction. This hint is not guaranteed to be accurate but it ** is often close. The underlying VFS might choose to preallocate database ** file space based on this hint in order to help writes to the database ** file run faster. ** ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]] ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS ** extends and truncates the database file in chunks of a size specified ** by the user. The fourth argument to [sqlite3_file_control()] should ** point to an integer (type int) containing the new chunk-size to use ** for the nominated database. Allocating database file space in large ** chunks (say 1MB at a time), may reduce file-system fragmentation and ** improve performance on some systems. ** ** <li>[[SQLITE_FCNTL_FILE_POINTER]] ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with a particular database ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. ** ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]] ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with the journal file (either ** the [rollback journal] or the [write-ahead log]) for a particular database ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]] ** No longer in use. ** ** <li>[[SQLITE_FCNTL_SYNC]] ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and ** sent to the VFS immediately before the xSync method is invoked on a ** database file descriptor. Or, if the xSync method is not invoked ** because the user has configured SQLite with ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place ** of the xSync method. In most cases, the pointer argument passed with ** this file-control is NULL. However, if the database file is being synced ** as part of a multi-database commit, the argument points to a nul-terminated ** string containing the transactions master-journal file name. VFSes that ** do not need this signal should silently ignore this opcode. Applications ** should not call [sqlite3_file_control()] with this opcode as doing so may ** disrupt the operation of the specialized VFSes that do require it. ** ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]] ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite ** and sent to the VFS after a transaction has been committed immediately ** but before the database is unlocked. VFSes that do not need this signal ** should silently ignore this opcode. Applications should not call ** [sqlite3_file_control()] with this opcode as doing so may disrupt the ** operation of the specialized VFSes that do require it. ** ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]] ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic ** retry counts and intervals for certain disk I/O operations for the ** windows [VFS] in order to provide robustness in the presence of ** anti-virus programs. By default, the windows VFS will retry file read, ** file write, and file delete operations up to 10 times, with a delay ** of 25 milliseconds before the first retry and with the delay increasing ** by an additional 25 milliseconds with each subsequent retry. This ** opcode allows these two values (10 retries and 25 milliseconds of delay) ** to be adjusted. The values are changed for all database connections ** within the same process. The argument is a pointer to an array of two ** integers where the first integer i the new retry count and the second ** integer is the delay. If either integer is negative, then the setting ** is not changed but instead the prior value of that setting is written ** into the array entry, allowing the current retry settings to be ** interrogated. The zDbName parameter is ignored. ** ** <li>[[SQLITE_FCNTL_PERSIST_WAL]] ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary ** write ahead log and shared memory files used for transaction control ** are automatically deleted when the latest connection to the database ** closes. Setting persistent WAL mode causes those files to persist after ** close. Persisting the files is useful when other processes that do not ** have write permission on the directory containing the database file want ** to read the database file, as the WAL and shared memory files must exist ** in order for the database to be readable. The fourth parameter to ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent ** WAL mode. If the integer is -1, then it is overwritten with the current ** WAL persistence setting. ** ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the ** xDeviceCharacteristics methods. The fourth parameter to ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage ** mode. If the integer is -1, then it is overwritten with the current ** zero-damage mode setting. ** ** <li>[[SQLITE_FCNTL_OVERWRITE]] ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening ** a write transaction to indicate that, unless it is rolled back for some ** reason, the entire database file will be overwritten by the current ** transaction. This is used by VACUUM operations. ** ** <li>[[SQLITE_FCNTL_VFSNAME]] ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of ** all [VFSes] in the VFS stack. The names are of all VFS shims and the ** final bottom-level VFS are written into memory obtained from ** [sqlite3_malloc()] and the result is stored in the char* variable ** that the fourth parameter of [sqlite3_file_control()] points to. ** The caller is responsible for freeing the memory when done. As with ** all file-control actions, there is no guarantee that this will actually ** do anything. Callers should initialize the char* variable to a NULL ** pointer in case this file-control is not implemented. This file-control ** is intended for diagnostic use only. ** ** <li>[[SQLITE_FCNTL_VFS_POINTER]] ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level ** [VFSes] currently in use. ^(The argument X in ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be ** of type "[sqlite3_vfs] **". This opcodes will set *X ** to a pointer to the top-level VFS.)^ ** ^When there are multiple VFS shims in the stack, this opcode finds the ** upper-most shim only. ** ** <li>[[SQLITE_FCNTL_PRAGMA]] ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] ** file control is sent to the open [sqlite3_file] object corresponding ** to the database file to which the pragma statement refers. ^The argument ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of ** pointers to strings (char**) in which the second element of the array ** is the name of the pragma and the third element is the argument to the ** pragma or NULL if the pragma has no argument. ^The handler for an ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element ** of the char** argument point to a string obtained from [sqlite3_mprintf()] ** or the equivalent and that string will become the result of the pragma or ** the error message if the pragma fails. ^If the ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] ** file control returns [SQLITE_OK], then the parser assumes that the ** VFS has handled the PRAGMA itself and the parser generates a no-op ** prepared statement if result string is NULL, or that returns a copy ** of the result string if the string is non-NULL. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means ** that the VFS encountered an error while handling the [PRAGMA] and the ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] ** file control occurs at the beginning of pragma statement analysis and so ** it is able to override built-in [PRAGMA] statements. ** ** <li>[[SQLITE_FCNTL_BUSYHANDLER]] ** ^The [SQLITE_FCNTL_BUSYHANDLER] ** file-control may be invoked by SQLite on the database file handle ** shortly after it is opened in order to provide a custom VFS with access ** to the connections busy-handler callback. The argument is of type (void **) ** - an array of two (void *) values. The first (void *) actually points ** to a function of type (int (*)(void *)). In order to invoke the connections ** busy-handler, this function should be invoked with the second (void *) in ** the array as the only argument. If it returns non-zero, then the operation ** should be retried. If it returns zero, the custom VFS should abandon the ** current operation. ** ** <li>[[SQLITE_FCNTL_TEMPFILENAME]] ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control ** to have SQLite generate a ** temporary filename using the same algorithm that is followed to generate ** temporary filenames for TEMP tables and other internal uses. The ** argument should be a char** which will be filled with the filename ** written into memory obtained from [sqlite3_malloc()]. The caller should ** invoke [sqlite3_free()] on the result to avoid a memory leak. ** ** <li>[[SQLITE_FCNTL_MMAP_SIZE]] ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the ** maximum number of bytes that will be used for memory-mapped I/O. ** The argument is a pointer to a value of type sqlite3_int64 that ** is an advisory maximum number of bytes in the file to memory map. The ** pointer is overwritten with the old value. The limit is not changed if ** the value originally pointed to is negative, and so the current limit ** can be queried by passing in a pointer to a negative number. This ** file-control is used internally to implement [PRAGMA mmap_size]. ** ** <li>[[SQLITE_FCNTL_TRACE]] ** The [SQLITE_FCNTL_TRACE] file control provides advisory information ** to the VFS about what the higher layers of the SQLite stack are doing. ** This file control is used by some VFS activity tracing [shims]. ** The argument is a zero-terminated string. Higher layers in the ** SQLite stack may generate instances of this file control if ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled. ** ** <li>[[SQLITE_FCNTL_HAS_MOVED]] ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a ** pointer to an integer and it writes a boolean into that integer depending ** on whether or not the file has been renamed, moved, or deleted since it ** was first opened. ** ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]] ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the ** underlying native file handle associated with a file handle. This file ** control interprets its argument as a pointer to a native file handle and ** writes the resulting value there. ** ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]] ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This ** opcode causes the xFileControl method to swap the file handle with the one ** pointed to by the pArg argument. This capability is used during testing ** and only needs to be supported when SQLITE_TEST is defined. ** ** <li>[[SQLITE_FCNTL_WAL_BLOCK]] ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might ** be advantageous to block on the next WAL lock if the lock is not immediately ** available. The WAL subsystem issues this signal during rare ** circumstances in order to fix a problem with priority inversion. ** Applications should <em>not</em> use this file-control. ** ** <li>[[SQLITE_FCNTL_ZIPVFS]] ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other ** VFS should return SQLITE_NOTFOUND for this opcode. ** ** <li>[[SQLITE_FCNTL_RBU]] ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for ** this opcode. ** </ul> */ #define SQLITE_FCNTL_LOCKSTATE 1 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3 #define SQLITE_FCNTL_LAST_ERRNO 4 #define SQLITE_FCNTL_SIZE_HINT 5 #define SQLITE_FCNTL_CHUNK_SIZE 6 #define SQLITE_FCNTL_FILE_POINTER 7 #define SQLITE_FCNTL_SYNC_OMITTED 8 #define SQLITE_FCNTL_WIN32_AV_RETRY 9 #define SQLITE_FCNTL_PERSIST_WAL 10 #define SQLITE_FCNTL_OVERWRITE 11 #define SQLITE_FCNTL_VFSNAME 12 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 #define SQLITE_FCNTL_PRAGMA 14 #define SQLITE_FCNTL_BUSYHANDLER 15 #define SQLITE_FCNTL_TEMPFILENAME 16 #define SQLITE_FCNTL_MMAP_SIZE 18 #define SQLITE_FCNTL_TRACE 19 #define SQLITE_FCNTL_HAS_MOVED 20 #define SQLITE_FCNTL_SYNC 21 #define SQLITE_FCNTL_COMMIT_PHASETWO 22 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23 #define SQLITE_FCNTL_WAL_BLOCK 24 #define SQLITE_FCNTL_ZIPVFS 25 #define SQLITE_FCNTL_RBU 26 #define SQLITE_FCNTL_VFS_POINTER 27 #define SQLITE_FCNTL_JOURNAL_POINTER 28 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29 #define SQLITE_FCNTL_PDB 30 /* deprecated names */ #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO /* ** CAPI3REF: Mutex Handle ** ** The mutex module within SQLite defines [sqlite3_mutex] to be an ** abstract type for a mutex object. The SQLite core never looks ** at the internal representation of an [sqlite3_mutex]. It only ** deals with pointers to the [sqlite3_mutex] object. ** ** Mutexes are created using [sqlite3_mutex_alloc()]. */ typedef struct sqlite3_mutex sqlite3_mutex; /* ** CAPI3REF: Loadable Extension Thunk ** ** A pointer to the opaque sqlite3_api_routines structure is passed as ** the third parameter to entry points of [loadable extensions]. This ** structure must be typedefed in order to work around compiler warnings ** on some platforms. */ typedef struct sqlite3_api_routines sqlite3_api_routines; /* ** CAPI3REF: OS Interface Object ** ** An instance of the sqlite3_vfs object defines the interface between ** the SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". See ** the [VFS | VFS documentation] for further information. ** ** The value of the iVersion field is initially 1 but may be larger in ** future versions of SQLite. Additional fields may be appended to this ** object when the iVersion value is increased. Note that the structure ** of the sqlite3_vfs object changes in the transaction between ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not ** modified. ** ** The szOsFile field is the size of the subclassed [sqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** ** Registered sqlite3_vfs objects are kept on a linked list formed by ** the pNext pointer. The [sqlite3_vfs_register()] ** and [sqlite3_vfs_unregister()] interfaces manage this list ** in a thread-safe way. The [sqlite3_vfs_find()] interface ** searches the list. Neither the application code nor the VFS ** implementation should use the pNext pointer. ** ** The pNext field is the only field in the sqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. ** The application should never modify anything within the sqlite3_vfs ** object once the object has been registered. ** ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** ** [[sqlite3_vfs.xOpen]] ** ^SQLite guarantees that the zFilename parameter to xOpen ** is either a NULL pointer or string obtained ** from xFullPathname() with an optional suffix added. ** ^If a suffix is added to the zFilename parameter, it will ** consist of a single "-" character followed by no more than ** 11 alphanumeric and/or "-" characters. ** ^SQLite further guarantees that ** the string will be valid and unchanged until xClose() is ** called. Because of the previous sentence, ** the [sqlite3_file] can safely store a pointer to the ** filename if it needs to remember the filename for some reason. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen ** must invent its own temporary name for the file. ^Whenever the ** xFilename parameter is NULL it will also be the case that the ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** The flags argument to xOpen() includes all bits set in ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] ** or [sqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. ** If xOpen() opens a file read-only then it sets *pOutFlags to ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. ** ** ^(SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: ** ** <ul> ** <li> [SQLITE_OPEN_MAIN_DB] ** <li> [SQLITE_OPEN_MAIN_JOURNAL] ** <li> [SQLITE_OPEN_TEMP_DB] ** <li> [SQLITE_OPEN_TEMP_JOURNAL] ** <li> [SQLITE_OPEN_TRANSIENT_DB] ** <li> [SQLITE_OPEN_SUBJOURNAL] ** <li> [SQLITE_OPEN_MASTER_JOURNAL] ** <li> [SQLITE_OPEN_WAL] ** </ul>)^ ** ** The file I/O implementation can use the object type flags to ** change the way it deals with files. For example, an application ** that does not care about crash recovery or rollback might make ** the open of a journal file a no-op. Writes to this journal would ** also be no-ops, and any attempt to read the journal would return ** SQLITE_IOERR. Or the implementation might recognize that a database ** file will be doing page-aligned sector reads and writes in a random ** order and set up its I/O subsystem accordingly. ** ** SQLite might also add one of the following flags to the xOpen method: ** ** <ul> ** <li> [SQLITE_OPEN_DELETEONCLOSE] ** <li> [SQLITE_OPEN_EXCLUSIVE] ** </ul> ** ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] ** will be set for TEMP databases and their journals, transient ** databases, and subjournals. ** ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction ** with the [SQLITE_OPEN_CREATE] flag, which are both directly ** analogous to the O_EXCL and O_CREAT flags of the POSIX open() ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the ** SQLITE_OPEN_CREATE, is used to indicate that file should always ** be created, and that it is an error if it already exists. ** It is <i>not</i> used to indicate the file should be opened ** for exclusive access. ** ** ^At least szOsFile bytes of memory are allocated by SQLite ** to hold the [sqlite3_file] structure passed as the third ** argument to xOpen. The xOpen method does not have to ** allocate the structure; it should just fill it in. Note that ** the xOpen method must set the sqlite3_file.pMethods to either ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods ** element will be valid after xOpen returns regardless of the success ** or failure of the xOpen call. ** ** [[sqlite3_vfs.xAccess]] ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] ** to test whether a file is at least readable. The file can be a ** directory. ** ** ^SQLite will always allocate at least mxPathname+1 bytes for the ** output buffer xFullPathname. The exact size of the output buffer ** is also passed as a parameter to both methods. If the output buffer ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is ** handled as a fatal error by SQLite, vfs implementations should endeavor ** to prevent this by setting mxPathname to a sufficiently large value. ** ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() ** interfaces are not strictly a part of the filesystem, but they are ** included in the VFS structure for completeness. ** The xRandomness() function attempts to return nBytes bytes ** of good-quality randomness into zOut. The return value is ** the actual number of bytes of randomness obtained. ** The xSleep() method causes the calling thread to sleep for at ** least the number of microseconds given. ^The xCurrentTime() ** method returns a Julian Day Number for the current date and time as ** a floating point value. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian ** Day Number multiplied by 86400000 (the number of milliseconds in ** a 24-hour day). ** ^SQLite will use the xCurrentTimeInt64() method to get the current ** date and time if that method is available (if iVersion is 2 or ** greater and the function pointer is not NULL) and will fall back ** to xCurrentTime() if xCurrentTimeInt64() is unavailable. ** ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces ** are not used by the SQLite core. These optional interfaces are provided ** by some VFSes to facilitate testing of the VFS code. By overriding ** system calls with functions under its control, a test program can ** simulate faults and error conditions that would otherwise be difficult ** or impossible to induce. The set of system calls that can be overridden ** varies from one VFS to another, and from one version of the same VFS to the ** next. Applications that use these interfaces must be prepared for any ** or all of these interfaces to be NULL or for their behavior to change ** from one release to the next. Applications must not attempt to access ** any of these methods if the iVersion of the VFS is less than 3. */ typedef struct sqlite3_vfs sqlite3_vfs; typedef void (*sqlite3_syscall_ptr)(void); struct sqlite3_vfs { int iVersion; /* Structure version number (currently 3) */ int szOsFile; /* Size of subclassed sqlite3_file */ int mxPathname; /* Maximum file pathname length */ sqlite3_vfs *pNext; /* Next registered VFS */ const char *zName; /* Name of this virtual file system */ void *pAppData; /* Pointer to application-specific data */ int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags); int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); void (*xDlClose)(sqlite3_vfs*, void*); int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); int (*xSleep)(sqlite3_vfs*, int microseconds); int (*xCurrentTime)(sqlite3_vfs*, double*); int (*xGetLastError)(sqlite3_vfs*, int, char *); /* ** The methods above are in version 1 of the sqlite_vfs object ** definition. Those that follow are added in version 2 or later */ int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); /* ** The methods above are in versions 1 and 2 of the sqlite_vfs object. ** Those below are for version 3 and greater. */ int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); /* ** The methods above are in versions 1 through 3 of the sqlite_vfs object. ** New fields may be appended in future versions. The iVersion ** value will increment whenever this happens. */ }; /* ** CAPI3REF: Flags for the xAccess VFS method ** ** These integer constants can be used as the third parameter to ** the xAccess method of an [sqlite3_vfs] object. They determine ** what kind of permissions the xAccess method is looking for. ** With SQLITE_ACCESS_EXISTS, the xAccess method ** simply checks whether the file exists. ** With SQLITE_ACCESS_READWRITE, the xAccess method ** checks whether the named directory is both readable and writable ** (in other words, if files can be added, removed, and renamed within ** the directory). ** The SQLITE_ACCESS_READWRITE constant is currently used only by the ** [temp_store_directory pragma], though this could change in a future ** release of SQLite. ** With SQLITE_ACCESS_READ, the xAccess method ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is ** currently unused, though it might be used in a future release of ** SQLite. */ #define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ #define SQLITE_ACCESS_READ 2 /* Unused */ /* ** CAPI3REF: Flags for the xShmLock VFS method ** ** These integer constants define the various locking operations ** allowed by the xShmLock method of [sqlite3_io_methods]. The ** following are the only legal combinations of flags to the ** xShmLock method: ** ** <ul> ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE ** </ul> ** ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as ** was given on the corresponding lock. ** ** The xShmLock method can transition between unlocked and SHARED or ** between unlocked and EXCLUSIVE. It cannot transition between SHARED ** and EXCLUSIVE. */ #define SQLITE_SHM_UNLOCK 1 #define SQLITE_SHM_LOCK 2 #define SQLITE_SHM_SHARED 4 #define SQLITE_SHM_EXCLUSIVE 8 /* ** CAPI3REF: Maximum xShmLock index ** ** The xShmLock method on [sqlite3_io_methods] may use values ** between 0 and this upper bound as its "offset" argument. ** The SQLite core will never attempt to acquire or release a ** lock outside of this range */ #define SQLITE_SHM_NLOCK 8 /* ** CAPI3REF: Initialize The SQLite Library ** ** ^The sqlite3_initialize() routine initializes the ** SQLite library. ^The sqlite3_shutdown() routine ** deallocates any resources that were allocated by sqlite3_initialize(). ** These routines are designed to aid in process initialization and ** shutdown on embedded systems. Workstation applications using ** SQLite normally do not need to invoke either of these routines. ** ** A call to sqlite3_initialize() is an "effective" call if it is ** the first time sqlite3_initialize() is invoked during the lifetime of ** the process, or if it is the first time sqlite3_initialize() is invoked ** following a call to sqlite3_shutdown(). ^(Only an effective call ** of sqlite3_initialize() does any initialization. All other calls ** are harmless no-ops.)^ ** ** A call to sqlite3_shutdown() is an "effective" call if it is the first ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only ** an effective call to sqlite3_shutdown() does any deinitialization. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ ** ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() ** is not. The sqlite3_shutdown() interface must only be called from a ** single thread. All open [database connections] must be closed and all ** other SQLite resources must be deallocated prior to invoking ** sqlite3_shutdown(). ** ** Among other things, ^sqlite3_initialize() will invoke ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() ** will invoke sqlite3_os_end(). ** ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. ** ^If for some reason, sqlite3_initialize() is unable to initialize ** the library (perhaps it is unable to allocate a needed resource such ** as a mutex) it returns an [error code] other than [SQLITE_OK]. ** ** ^The sqlite3_initialize() routine is called internally by many other ** SQLite interfaces so that an application usually does not need to ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] ** calls sqlite3_initialize() so the SQLite library will be automatically ** initialized when [sqlite3_open()] is called if it has not be initialized ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] ** compile-time option, then the automatic calls to sqlite3_initialize() ** are omitted and the application must call sqlite3_initialize() directly ** prior to using any other SQLite interface. For maximum portability, ** it is recommended that applications always invoke sqlite3_initialize() ** directly prior to using any other SQLite interface. Future releases ** of SQLite may require this. In other words, the behavior exhibited ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the ** default behavior in some future release of SQLite. ** ** The sqlite3_os_init() routine does operating-system specific ** initialization of the SQLite library. The sqlite3_os_end() ** routine undoes the effect of sqlite3_os_init(). Typical tasks ** performed by these routines include allocation or deallocation ** of static resources, initialization of global variables, ** setting up a default [sqlite3_vfs] module, or setting up ** a default configuration using [sqlite3_config()]. ** ** The application should never invoke either sqlite3_os_init() ** or sqlite3_os_end() directly. The application should only invoke ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() ** interface is called automatically by sqlite3_initialize() and ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate ** implementations for sqlite3_os_init() and sqlite3_os_end() ** are built into SQLite when it is compiled for Unix, Windows, or OS/2. ** When [custom builds | built for other platforms] ** (using the [SQLITE_OS_OTHER=1] compile-time ** option) the application must supply a suitable implementation for ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied ** implementation of sqlite3_os_init() or sqlite3_os_end() ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ SQLITE_API int sqlite3_initialize(void); SQLITE_API int sqlite3_shutdown(void); SQLITE_API int sqlite3_os_init(void); SQLITE_API int sqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library ** ** The sqlite3_config() interface is used to make global configuration ** changes to SQLite in order to tune SQLite to the specific needs of ** the application. The default configuration is recommended for most ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** ** <b>The sqlite3_config() interface is not threadsafe. The application ** must ensure that no other SQLite interfaces are invoked by other ** threads while sqlite3_config() is running.</b> ** ** The sqlite3_config() interface ** may only be invoked prior to library initialization using ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. ** Note, however, that ^sqlite3_config() can be called as part of the ** implementation of an application-defined [sqlite3_os_init()]. ** ** The first argument to sqlite3_config() is an integer ** [configuration option] that determines ** what property of SQLite is to be configured. Subsequent arguments ** vary depending on the [configuration option] ** in the first argument. ** ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. ** ^If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. */ SQLITE_API int sqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections ** METHOD: sqlite3 ** ** The sqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to ** [sqlite3_config()] except that the changes apply to a single ** [database connection] (specified in the first argument). ** ** The second argument to sqlite3_db_config(D,V,...) is the ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code ** that indicates what aspect of the [database connection] is being configured. ** Subsequent arguments vary depending on the configuration verb. ** ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if ** the call is considered successful. */ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines ** ** An instance of this object defines the interface between SQLite ** and low-level memory allocation routines. ** ** This object is used in only one place in the SQLite interface. ** A pointer to an instance of this object is the argument to ** [sqlite3_config()] when the configuration option is ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. ** By creating an instance of this object ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) ** during configuration, an application can specify an alternative ** memory allocation subsystem for SQLite to use for all of its ** dynamic memory needs. ** ** Note that SQLite comes with several [built-in memory allocators] ** that are perfectly adequate for the overwhelming majority of applications ** and that this object is only useful to a tiny minority of applications ** with specialized memory allocation requirements. This object is ** also used during testing of SQLite in order to specify an alternative ** memory allocator that simulates memory out-of-memory conditions in ** order to verify that SQLite recovers gracefully from such ** conditions. ** ** The xMalloc, xRealloc, and xFree methods must work like the ** malloc(), realloc() and free() functions from the standard C library. ** ^SQLite guarantees that the second argument to ** xRealloc is always a value returned by a prior call to xRoundup. ** ** xSize should return the allocated size of a memory allocation ** previously obtained from xMalloc or xRealloc. The allocated size ** is always at least as big as the requested size but may be larger. ** ** The xRoundup method returns what would be the allocated size of ** a memory allocation given a particular requested size. Most memory ** allocators round up memory allocations at least to the next multiple ** of 8. Some allocators round up to a larger multiple or to a power of 2. ** Every memory allocation request coming in through [sqlite3_malloc()] ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, ** that causes the corresponding memory allocation to fail. ** ** The xInit method initializes the memory allocator. For example, ** it might allocate any require mutexes or initialize internal data ** structures. The xShutdown method is invoked (indirectly) by ** [sqlite3_shutdown()] and should deallocate any resources acquired ** by xInit. The pAppData pointer is used as the only parameter to ** xInit and xShutdown. ** ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes ** the xInit method, so the xInit method need not be threadsafe. The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. For all other methods, SQLite ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which ** it is by default) and so the methods are automatically serialized. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other ** methods must be threadsafe or else make their own arrangements for ** serialization. ** ** SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). */ typedef struct sqlite3_mem_methods sqlite3_mem_methods; struct sqlite3_mem_methods { void *(*xMalloc)(int); /* Memory allocation function */ void (*xFree)(void*); /* Free a prior allocation */ void *(*xRealloc)(void*,int); /* Resize an allocation */ int (*xSize)(void*); /* Return the size of an allocation */ int (*xRoundup)(int); /* Round up request size to allocation size */ int (*xInit)(void*); /* Initialize the memory allocator */ void (*xShutdown)(void*); /* Deinitialize the memory allocator */ void *pAppData; /* Argument to xInit() and xShutdown() */ }; /* ** CAPI3REF: Configuration Options ** KEYWORDS: {configuration option} ** ** These constants are the available integer configuration options that ** can be passed as the first argument to the [sqlite3_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_config()] to make sure that ** the call worked. The [sqlite3_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** ** <dl> ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt> ** <dd>There are no arguments to this option. ^This option sets the ** [threading mode] to Single-thread. In other words, it disables ** all mutexing and puts SQLite into a mode where it can only be used ** by a single thread. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to change the [threading mode] from its default ** value of Single-thread and so [sqlite3_config()] will return ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD ** configuration option.</dd> ** ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt> ** <dd>There are no arguments to this option. ^This option sets the ** [threading mode] to Multi-thread. In other words, it disables ** mutexing on [database connection] and [prepared statement] objects. ** The application is responsible for serializing access to ** [database connections] and [prepared statements]. But other mutexes ** are enabled so that SQLite will be safe to use in a multi-threaded ** environment as long as no two threads attempt to use the same ** [database connection] at the same time. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Multi-thread [threading mode] and ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd> ** ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt> ** <dd>There are no arguments to this option. ^This option sets the ** [threading mode] to Serialized. In other words, this option enables ** all mutexes including the recursive ** mutexes on [database connection] and [prepared statement] objects. ** In this mode (which is the default when SQLite is compiled with ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access ** to [database connections] and [prepared statements] so that the ** application is free to use the same [database connection] or the ** same [prepared statement] in different threads at the same time. ** ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Serialized [threading mode] and ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_SERIALIZED configuration option.</dd> ** ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt> ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is ** a pointer to an instance of the [sqlite3_mem_methods] structure. ** The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.)^ ^SQLite makes ** its own private copy of the content of the [sqlite3_mem_methods] structure ** before the [sqlite3_config()] call returns.</dd> ** ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt> ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which ** is a pointer to an instance of the [sqlite3_mem_methods] structure. ** The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example. </dd> ** ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt> ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, ** interpreted as a boolean, which enables or disables the collection of ** memory allocation statistics. ^(When memory allocation statistics are ** disabled, the following SQLite interfaces become non-operational: ** <ul> ** <li> [sqlite3_memory_used()] ** <li> [sqlite3_memory_highwater()] ** <li> [sqlite3_soft_heap_limit64()] ** <li> [sqlite3_status64()] ** </ul>)^ ** ^Memory allocation statistics are enabled by default unless SQLite is ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory ** allocation statistics are disabled by default. ** </dd> ** ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt> ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer ** that SQLite can use for scratch memory. ^(There are three arguments ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte ** aligned memory buffer from which the scratch allocations will be ** drawn, the size of each scratch allocation (sz), ** and the maximum number of scratch allocations (N).)^ ** The first argument must be a pointer to an 8-byte aligned buffer ** of at least sz*N bytes of memory. ** ^SQLite will not use more than one scratch buffers per thread. ** ^SQLite will never request a scratch buffer that is more than 6 ** times the database page size. ** ^If SQLite needs needs additional ** scratch memory beyond what is provided by this configuration option, then ** [sqlite3_malloc()] will be used to obtain the memory needed.<p> ** ^When the application provides any amount of scratch memory using ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large ** [sqlite3_malloc|heap allocations]. ** This can help [Robson proof|prevent memory allocation failures] due to heap ** fragmentation in low-memory embedded systems. ** </dd> ** ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt> ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool ** that SQLite can use for the database page cache with the default page ** cache implementation. ** This configuration option is a no-op if an application-define page ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to ** 8-byte aligned memory (pMem), the size of each page cache line (sz), ** and the number of cache lines (N). ** The sz argument should be the size of the largest database page ** (a power of two between 512 and 65536) plus some extra bytes for each ** page header. ^The number of extra bytes needed by the page header ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ]. ** ^It is harmless, apart from the wasted memory, ** for the sz parameter to be larger than necessary. The pMem ** argument must be either a NULL pointer or a pointer to an 8-byte ** aligned block of memory of at least sz*N bytes, otherwise ** subsequent behavior is undefined. ** ^When pMem is not NULL, SQLite will strive to use the memory provided ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if ** a page cache line is larger than sz bytes or if all of the pMem buffer ** is exhausted. ** ^If pMem is NULL and N is non-zero, then each database connection ** does an initial bulk allocation for page cache memory ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or ** of -1024*N bytes if N is negative, . ^If additional ** page cache memory is needed beyond what is provided by the initial ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each ** additional cache line. </dd> ** ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt> ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer ** that SQLite will use for all of its dynamic memory allocation needs ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and ** [SQLITE_CONFIG_PAGECACHE]. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns ** [SQLITE_ERROR] if invoked otherwise. ** ^There are three arguments to SQLITE_CONFIG_HEAP: ** An 8-byte aligned pointer to the memory, ** the number of bytes in the memory buffer, and the minimum allocation size. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts ** to using its default memory allocator (the system malloc() implementation), ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the ** memory pointer is not NULL then the alternative memory ** allocator is engaged to handle all of SQLites memory allocation needs. ** The first pointer (the memory pointer) must be aligned to an 8-byte ** boundary or subsequent behavior of SQLite will be undefined. ** The minimum allocation size is capped at 2**12. Reasonable values ** for the minimum allocation size are 2**5 through 2**8.</dd> ** ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt> ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a ** pointer to an instance of the [sqlite3_mutex_methods] structure. ** The argument specifies alternative low-level mutex routines to be used ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of ** the content of the [sqlite3_mutex_methods] structure before the call to ** [sqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will ** return [SQLITE_ERROR].</dd> ** ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt> ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The ** [sqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines.)^ ** This option can be used to overload the default mutex allocation ** routines with a wrapper used to track mutex usage for performance ** profiling or testing, for example. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will ** return [SQLITE_ERROR].</dd> ** ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt> ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine ** the default size of lookaside memory on each [database connection]. ** The first argument is the ** size of each lookaside buffer slot and the second is the number of ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] ** option to [sqlite3_db_config()] can be used to change the lookaside ** configuration on individual connections.)^ </dd> ** ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies ** the interface to a custom page cache implementation.)^ ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd> ** ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of ** the current page cache implementation into that object.)^ </dd> ** ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt> ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite ** global [error log]. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a ** function with a call signature of void(*)(void*,int,const char*), ** and a pointer to void. ^If the function pointer is not NULL, it is ** invoked by [sqlite3_log()] to process each logging event. ^If the ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is ** passed through as the first parameter to the application-defined logger ** function whenever that function is invoked. ^The second parameter to ** the logger function is a copy of the first parameter to the corresponding ** [sqlite3_log()] call and is intended to be a [result code] or an ** [extended result code]. ^The third parameter passed to the logger is ** log message after formatting via [sqlite3_snprintf()]. ** The SQLite logging interface is not reentrant; the logger function ** supplied by the application must not invoke any SQLite interface. ** In a multi-threaded application, the application-defined logger ** function must be threadsafe. </dd> ** ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int. ** If non-zero, then URI handling is globally enabled. If the parameter is zero, ** then URI handling is globally disabled.)^ ^If URI handling is globally ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], ** [sqlite3_open16()] or ** specified as part of [ATTACH] commands are interpreted as URIs, regardless ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database ** connection is opened. ^If it is globally disabled, filenames are ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the ** database connection is opened. ^(By default, URI handling is globally ** disabled. The default value may be changed by compiling with the ** [SQLITE_USE_URI] symbol defined.)^ ** ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer ** argument which is interpreted as a boolean in order to enable or disable ** the use of covering indices for full table scans in the query optimizer. ** ^The default setting is determined ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" ** if that compile-time option is omitted. ** The ability to disable the use of covering indices for full table scans ** is because some incorrectly coded legacy applications might malfunction ** when the optimization is enabled. Providing the ability to ** disable the optimization allows the older, buggy application code to work ** without change even with newer versions of SQLite. ** ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE ** <dd> These options are obsolete and should not be used by new code. ** They are retained for backwards compatibility but are now no-ops. ** </dd> ** ** [[SQLITE_CONFIG_SQLLOG]] ** <dt>SQLITE_CONFIG_SQLLOG ** <dd>This option is only available if sqlite is compiled with the ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). ** The second should be of type (void*). The callback is invoked by the library ** in three separate circumstances, identified by the value passed as the ** fourth parameter. If the fourth parameter is 0, then the database connection ** passed as the second argument has just been opened. The third argument ** points to a buffer containing the name of the main database file. If the ** fourth parameter is 1, then the SQL statement that the third parameter ** points to has just been executed. Or, if the fourth parameter is 2, then ** the connection being passed as the second parameter is being closed. The ** third parameter is passed NULL In this case. An example of using this ** configuration option can be seen in the "test_sqllog.c" source file in ** the canonical SQLite source tree.</dd> ** ** [[SQLITE_CONFIG_MMAP_SIZE]] ** <dt>SQLITE_CONFIG_MMAP_SIZE ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values ** that are the default mmap size limit (the default setting for ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. ** ^The default setting can be overridden by each database connection using ** either the [PRAGMA mmap_size] command, or by using the ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size ** will be silently truncated if necessary so that it does not exceed the ** compile-time maximum mmap size set by the ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ ** ^If either argument to this option is negative, then that argument is ** changed to its compile-time default. ** ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]] ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value ** that specifies the maximum size of the created heap. ** ** [[SQLITE_CONFIG_PCACHE_HDRSZ]] ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which ** is a pointer to an integer and writes into that integer the number of extra ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE]. ** The amount of extra space required can change depending on the compiler, ** target platform, and SQLite version. ** ** [[SQLITE_CONFIG_PMASZ]] ** <dt>SQLITE_CONFIG_PMASZ ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded ** sorter to that integer. The default minimum PMA Size is set by the ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched ** to help with sort operations when multithreaded sorting ** is enabled (using the [PRAGMA threads] command) and the amount of content ** to be sorted exceeds the page size times the minimum of the ** [PRAGMA cache_size] setting and this value. ** ** [[SQLITE_CONFIG_STMTJRNL_SPILL]] ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which ** becomes the [statement journal] spill-to-disk threshold. ** [Statement journals] are held in memory until their size (in bytes) ** exceeds this threshold, at which point they are written to disk. ** Or if the threshold is -1, statement journals are always held ** exclusively in memory. ** Since many statement journals never become large, setting the spill ** threshold to a value such as 64KiB can greatly reduce the amount of ** I/O required to support statement rollback. ** The default value for this setting is controlled by the ** [SQLITE_STMTJRNL_SPILL] compile-time option. ** </dl> */ #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */ #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ #define SQLITE_CONFIG_PCACHE 14 /* no-op */ #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ #define SQLITE_CONFIG_URI 17 /* int */ #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ /* ** CAPI3REF: Database Connection Configuration Options ** ** These constants are the available integer configuration options that ** can be passed as the second argument to the [sqlite3_db_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_db_config()] to make sure that ** the call worked. ^The [sqlite3_db_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** ** <dl> ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt> ** <dd> ^This option takes three additional arguments that determine the ** [lookaside memory allocator] configuration for the [database connection]. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a ** pointer to a memory buffer to use for lookaside memory. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb ** may be NULL in which case SQLite will allocate the ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the ** size of each lookaside buffer slot. ^The third argument is the number of ** slots. The size of the buffer in the first argument must be greater than ** or equal to the product of the second and third arguments. The buffer ** must be aligned to an 8-byte boundary. ^If the second argument to ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally ** rounded down to the next smaller multiple of 8. ^(The lookaside memory ** configuration for a database connection can only be changed when that ** connection is not currently using lookaside memory, or in other words ** when the "current value" returned by ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. ** Any attempt to change the lookaside memory configuration when lookaside ** memory is in use leaves the configuration unchanged and returns ** [SQLITE_BUSY].)^</dd> ** ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt> ** <dd> ^This option is used to enable or disable the enforcement of ** [foreign key constraints]. There should be two additional arguments. ** The first argument is an integer which is 0 to disable FK enforcement, ** positive to enable FK enforcement or negative to leave FK enforcement ** unchanged. The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether FK enforcement is off or on ** following this call. The second parameter may be a NULL pointer, in ** which case the FK enforcement setting is not reported back. </dd> ** ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt> ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers]. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable triggers, ** positive to enable triggers or negative to leave the setting unchanged. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether triggers are disabled or enabled ** following this call. The second parameter may be a NULL pointer, in ** which case the trigger setting is not reported back. </dd> ** ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt> ** <dd> ^This option is used to enable or disable the two-argument ** version of the [fts3_tokenizer()] function which is part of the ** [FTS3] full-text search engine extension. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or ** positive to enable fts3_tokenizer() or negative to leave the setting ** unchanged. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled ** following this call. The second parameter may be a NULL pointer, in ** which case the new setting is not reported back. </dd> ** ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt> ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()] ** interface independently of the [load_extension()] SQL function. ** The [sqlite3_enable_load_extension()] API enables or disables both the ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. ** There should be two additional arguments. ** When the first argument to this interface is 1, then only the C-API is ** enabled and the SQL function remains disabled. If the first argument to ** this interface is 0, then both the C-API and the SQL function are disabled. ** If the first argument is -1, then no changes are made to state of either the ** C-API or the SQL function. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface ** is disabled or enabled following this call. The second parameter may ** be a NULL pointer, in which case the new setting is not reported back. ** </dd> ** ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> ** <dd> ^This option is used to change the name of the "main" database ** schema. ^The sole argument is a pointer to a constant UTF8 string ** which will become the new schema name in place of "main". ^SQLite ** does not make a copy of the new main schema name string, so the application ** must ensure that the argument passed into this DBCONFIG option is unchanged ** until after the database connection closes. ** </dd> ** ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt> ** <dd> Usually, when a database in wal mode is closed or detached from a ** database handle, SQLite checks if this will mean that there are now no ** connections at all to the database. If so, it performs a checkpoint ** operation before closing the connection. This option may be used to ** override this behaviour. The first parameter passed to this operation ** is an integer - non-zero to disable checkpoints-on-close, or zero (the ** default) to enable them. The second parameter is a pointer to an integer ** into which is written 0 or 1 to indicate whether checkpoints-on-close ** have been disabled - 0 if they are not disabled, 1 if they are. ** </dd> ** ** </dl> */ #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */ #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes ** METHOD: sqlite3 ** ** ^The sqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. ^The extended result ** codes are disabled by default for historical compatibility. */ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid ** METHOD: sqlite3 ** ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) ** has a unique 64-bit signed ** integer key called the [ROWID | "rowid"]. ^The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those ** names are not also used by explicitly declared columns. ^If ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the ** most recent successful [INSERT] into a rowid table or [virtual table] ** on database connection D. ** ^Inserts into [WITHOUT ROWID] tables are not recorded. ** ^If no successful [INSERT]s into rowid tables ** have ever occurred on the database connection D, ** then sqlite3_last_insert_rowid(D) returns zero. ** ** ^(If an [INSERT] occurs within a trigger or within a [virtual table] ** method, then this routine will return the [rowid] of the inserted ** row as long as the trigger or virtual table method is running. ** But once the trigger or virtual table method ends, the value returned ** by this routine reverts to what it was before the trigger or virtual ** table method began.)^ ** ** ^An [INSERT] that fails due to a constraint violation is not a ** successful [INSERT] and does not change the value returned by this ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, ** and INSERT OR ABORT make no changes to the return value of this ** routine when their insertion fails. ^(When INSERT OR REPLACE ** encounters a constraint violation, it does not fail. The ** INSERT continues to completion after deleting rows that caused ** the constraint problem so INSERT OR REPLACE will always change ** the return value of this interface.)^ ** ** ^For the purposes of this routine, an [INSERT] is considered to ** be successful even if it is subsequently rolled back. ** ** This function is accessible to SQL statements via the ** [last_insert_rowid() SQL function]. ** ** If a separate thread performs a new [INSERT] on the same ** database connection while the [sqlite3_last_insert_rowid()] ** function is running and thus changes the last insert [rowid], ** then the value returned by [sqlite3_last_insert_rowid()] is ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified ** METHOD: sqlite3 ** ** ^This function returns the number of rows modified, inserted or ** deleted by the most recently completed INSERT, UPDATE or DELETE ** statement on the database connection specified by the only parameter. ** ^Executing any other type of SQL statement does not modify the value ** returned by this function. ** ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], ** [foreign key actions] or [REPLACE] constraint resolution are not counted. ** ** Changes to a view that are intercepted by ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or ** DELETE statement run on a view is always zero. Only changes made to real ** tables are counted. ** ** Things are more complicated if the sqlite3_changes() function is ** executed while a trigger program is running. This may happen if the ** program uses the [changes() SQL function], or if some other callback ** function invokes sqlite3_changes() directly. Essentially: ** ** <ul> ** <li> ^(Before entering a trigger program the value returned by ** sqlite3_changes() function is saved. After the trigger program ** has finished, the original value is restored.)^ ** ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE ** statement sets the value returned by sqlite3_changes() ** upon completion as normal. Of course, this value will not include ** any changes performed by sub-triggers, as the sqlite3_changes() ** value will be saved and restored after each sub-trigger has run.)^ ** </ul> ** ** ^This means that if the changes() SQL function (or similar) is used ** by the first INSERT, UPDATE or DELETE statement within a trigger, it ** returns the value as set when the calling statement began executing. ** ^If it is used by the second or subsequent such statement within a trigger ** program, the value returned reflects the number of rows modified by the ** previous INSERT, UPDATE or DELETE statement within the same trigger. ** ** See also the [sqlite3_total_changes()] interface, the ** [count_changes pragma], and the [changes() SQL function]. ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. */ SQLITE_API int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified ** METHOD: sqlite3 ** ** ^This function returns the total number of rows inserted, modified or ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed ** since the database connection was opened, including those executed as ** part of trigger programs. ^Executing any other type of SQL statement ** does not affect the value returned by sqlite3_total_changes(). ** ** ^Changes made as part of [foreign key actions] are included in the ** count, but those made as part of REPLACE constraint resolution are ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers ** are not counted. ** ** See also the [sqlite3_changes()] interface, the ** [count_changes pragma], and the [total_changes() SQL function]. ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. */ SQLITE_API int sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query ** METHOD: sqlite3 ** ** ^This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically ** called in response to a user action such as pressing "Cancel" ** or Ctrl-C where the user wants a long query operation to halt ** immediately. ** ** ^It is safe to call this routine from a thread different from the ** thread that is currently running the database operation. But it ** is not safe to call this routine with a [database connection] that ** is closed or might close before sqlite3_interrupt() returns. ** ** ^If an SQL operation is very nearly finished at the time when ** sqlite3_interrupt() is called, then it might not have an opportunity ** to be interrupted and might continue to completion. ** ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE ** that is inside an explicit transaction, then the entire transaction ** will be rolled back automatically. ** ** ^The sqlite3_interrupt(D) call is in effect until all currently running ** SQL statements on [database connection] D complete. ^Any new SQL statements ** that are started after the sqlite3_interrupt() call and before the ** running statements reaches zero are interrupted as if they had been ** running prior to the sqlite3_interrupt() call. ^New SQL statements ** that are started after the running statement count reaches zero are ** not effected by the sqlite3_interrupt(). ** ^A call to sqlite3_interrupt(D) that occurs when there are no running ** SQL statements is a no-op and has no effect on SQL statements ** that are started after the sqlite3_interrupt() call returns. ** ** If the database connection closes while [sqlite3_interrupt()] ** is running then bad things will likely happen. */ SQLITE_API void sqlite3_interrupt(sqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete ** ** These routines are useful during command-line input to determine if the ** currently entered text seems to form a complete SQL statement or ** if additional input is needed before sending the text into ** SQLite for parsing. ^These routines return 1 if the input string ** appears to be a complete SQL statement. ^A statement is judged to be ** complete if it ends with a semicolon token and is not a prefix of a ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within ** string literals or quoted identifier names or comments are not ** independent tokens (they are part of the token in which they are ** embedded) and thus do not count as a statement terminator. ^Whitespace ** and comments that follow the final semicolon are ignored. ** ** ^These routines return 0 if the statement is incomplete. ^If a ** memory allocation fails, then SQLITE_NOMEM is returned. ** ** ^These routines do not parse the SQL statements thus ** will not detect syntactically incorrect SQL. ** ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked ** automatically by sqlite3_complete16(). If that initialization fails, ** then the return value from sqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete.)^ ** ** The input to [sqlite3_complete()] must be a zero-terminated ** UTF-8 string. ** ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors ** KEYWORDS: {busy-handler callback} {busy handler} ** METHOD: sqlite3 ** ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X ** that might be invoked with argument P whenever ** an attempt is made to access a database table associated with ** [database connection] D when another thread ** or process has the table locked. ** The sqlite3_busy_handler() interface is used to implement ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. ** ** ^If the busy callback is NULL, then [SQLITE_BUSY] ** is returned immediately upon encountering the lock. ^If the busy callback ** is not NULL, then the callback might be invoked with two arguments. ** ** ^The first argument to the busy handler is a copy of the void* pointer which ** is the third argument to sqlite3_busy_handler(). ^The second argument to ** the busy handler callback is the number of times that the busy handler has ** been invoked previously for the same locking event. ^If the ** busy callback returns 0, then no additional attempts are made to ** access the database and [SQLITE_BUSY] is returned ** to the application. ** ^If the callback returns non-zero, then another attempt ** is made to access the database and the cycle repeats. ** ** The presence of a busy handler does not guarantee that it will be invoked ** when there is lock contention. ^If SQLite determines that invoking the busy ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] ** to the application instead of invoking the ** busy handler. ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying ** to promote to an exclusive lock. The first process cannot proceed ** because it is blocked by the second and the second process cannot ** proceed because it is blocked by the first. If both processes ** invoke the busy handlers, neither will make any progress. Therefore, ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this ** will induce the first process to release its read lock and allow ** the second process to proceed. ** ** ^The default busy callback is NULL. ** ** ^(There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] ** or evaluating [PRAGMA busy_timeout=N] will change the ** busy handler and thus clear any previously set busy handler. ** ** The busy callback should not take any actions which modify the ** database connection that invoked the busy handler. In other words, ** the busy handler is not reentrant. Any such actions ** result in undefined behavior. ** ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); /* ** CAPI3REF: Set A Busy Timeout ** METHOD: sqlite3 ** ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. ^The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. ^After at least "ms" milliseconds of sleeping, ** the handler returns 0 which causes [sqlite3_step()] to return ** [SQLITE_BUSY]. ** ** ^Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** ** ^(There can only be a single busy handler for a particular ** [database connection] at any given moment. If another busy handler ** was defined (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared.)^ ** ** See also: [PRAGMA busy_timeout] */ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries ** METHOD: sqlite3 ** ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. ** ** Definition: A <b>result table</b> is memory data structure created by the ** [sqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** ** The table conceptually has a number of rows and columns. But ** these numbers are not part of the result table itself. These ** numbers are obtained separately. Let N be the number of rows ** and M be the number of columns. ** ** A result table is an array of pointers to zero-terminated UTF-8 strings. ** There are (N+1)*M elements in the array. The first M pointers point ** to zero-terminated strings that contain the names of the columns. ** The remaining entries all point to query results. NULL values result ** in NULL pointers. All other values are in their UTF-8 zero-terminated ** string representation as returned by [sqlite3_column_text()]. ** ** A result table might consist of one or more memory allocations. ** It is not safe to pass a result table directly to [sqlite3_free()]. ** A result table should be deallocated using [sqlite3_free_table()]. ** ** ^(As an example of the result table format, suppose a query result ** is as follows: ** ** <blockquote><pre> ** Name | Age ** ----------------------- ** Alice | 43 ** Bob | 28 ** Cindy | 21 ** </pre></blockquote> ** ** There are two column (M==2) and three rows (N==3). Thus the ** result table has 8 entries. Suppose the result table is stored ** in an array names azResult. Then azResult holds this content: ** ** <blockquote><pre> ** azResult&#91;0] = "Name"; ** azResult&#91;1] = "Age"; ** azResult&#91;2] = "Alice"; ** azResult&#91;3] = "43"; ** azResult&#91;4] = "Bob"; ** azResult&#91;5] = "28"; ** azResult&#91;6] = "Cindy"; ** azResult&#91;7] = "21"; ** </pre></blockquote>)^ ** ** ^The sqlite3_get_table() function evaluates one or more ** semicolon-separated SQL statements in the zero-terminated UTF-8 ** string of its 2nd parameter and returns a result table to the ** pointer given in its 3rd parameter. ** ** After the application has finished with the result from sqlite3_get_table(), ** it must pass the result table pointer to sqlite3_free_table() in order to ** release the memory that was malloced. Because of the way the ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling ** function must not try to call [sqlite3_free()] directly. Only ** [sqlite3_free_table()] is able to release the memory properly and safely. ** ** The sqlite3_get_table() interface is implemented as a wrapper around ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access ** to any internal data structures of SQLite. It uses only the public ** interface defined here. As a consequence, errors that occur in the ** wrapper layer outside of the internal [sqlite3_exec()] call are not ** reflected in subsequent calls to [sqlite3_errcode()] or ** [sqlite3_errmsg()]. */ SQLITE_API int sqlite3_get_table( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows written here */ int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); SQLITE_API void sqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions ** ** These routines are work-alikes of the "printf()" family of functions ** from the standard C library. ** These routines understand most of the common K&R formatting options, ** plus some additional non-standard formats, detailed below. ** Note that some of the more obscure formatting options from recent ** C-library standards are omitted from this implementation. ** ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. ** The strings returned by these two routines should be ** released by [sqlite3_free()]. ^Both routines return a ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough ** memory to hold the resulting string. ** ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by ** the first parameter. Note that the order of the ** first two parameters is reversed from snprintf().)^ This is an ** historical accident that cannot be fixed without breaking ** backwards compatibility. ^(Note also that sqlite3_snprintf() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer.)^ We admit that ** the number of characters written would be a more useful return ** value but we cannot change the implementation of sqlite3_snprintf() ** now without breaking compatibility. ** ** ^As long as the buffer size is greater than zero, sqlite3_snprintf() ** guarantees that the buffer is always zero-terminated. ^The first ** parameter "n" is the total size of the buffer, including space for ** the zero terminator. So the longest string that can be completely ** written will be n-1 characters. ** ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). ** ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. ** All of the usual printf() formatting options apply. In addition, there ** is are "%q", "%Q", "%w" and "%z" options. ** ** ^(The %q option works like %s in that it substitutes a nul-terminated ** string from the argument list. But %q also doubles every '\'' character. ** %q is designed for use inside a string literal.)^ By doubling each '\'' ** character it escapes that character and allows it to be inserted into ** the string. ** ** For example, assume the string variable zText contains text as follows: ** ** <blockquote><pre> ** char *zText = "It's a happy day!"; ** </pre></blockquote> ** ** One can use this text in an SQL statement as follows: ** ** <blockquote><pre> ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); ** sqlite3_exec(db, zSQL, 0, 0, 0); ** sqlite3_free(zSQL); ** </pre></blockquote> ** ** Because the %q format string is used, the '\'' character in zText ** is escaped and the SQL generated is as follows: ** ** <blockquote><pre> ** INSERT INTO table1 VALUES('It''s a happy day!') ** </pre></blockquote> ** ** This is correct. Had we used %s instead of %q, the generated SQL ** would have looked like this: ** ** <blockquote><pre> ** INSERT INTO table1 VALUES('It's a happy day!'); ** </pre></blockquote> ** ** This second example is an SQL syntax error. As a general rule you should ** always use %q instead of %s when inserting text into a string literal. ** ** ^(The %Q option works like %q except it also adds single quotes around ** the outside of the total string. Additionally, if the parameter in the ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without ** single quotes).)^ So, for example, one could say: ** ** <blockquote><pre> ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); ** sqlite3_exec(db, zSQL, 0, 0, 0); ** sqlite3_free(zSQL); ** </pre></blockquote> ** ** The code above will render a correct SQL statement in the zSQL ** variable even if the zText variable is a NULL pointer. ** ** ^(The "%w" formatting option is like "%q" except that it expects to ** be contained within double-quotes instead of single quotes, and it ** escapes the double-quote character instead of the single-quote ** character.)^ The "%w" formatting option is intended for safely inserting ** table and column names into a constructed SQL statement. ** ** ^(The "%z" formatting option works like "%s" but with the ** addition that after the string has been read and copied into ** the result, [sqlite3_free()] is called on the input string.)^ */ SQLITE_API char *sqlite3_mprintf(const char*,...); SQLITE_API char *sqlite3_vmprintf(const char*, va_list); SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); /* ** CAPI3REF: Memory Allocation Subsystem ** ** The SQLite core uses these three routines for all of its own ** internal memory allocation needs. "Core" in the previous sentence ** does not include operating-system specific VFS implementation. The ** Windows VFS uses native malloc() and free() for some operations. ** ** ^The sqlite3_malloc() routine returns a pointer to a block ** of memory at least N bytes in length, where N is the parameter. ** ^If sqlite3_malloc() is unable to obtain sufficient free ** memory, it returns a NULL pointer. ^If the parameter N to ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns ** a NULL pointer. ** ** ^The sqlite3_malloc64(N) routine works just like ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead ** of a signed 32-bit integer. ** ** ^Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. ^The sqlite3_free() routine is ** a no-op if is called with a NULL pointer. Passing a NULL pointer ** to sqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. ** Memory corruption, a segmentation fault, or other severe error ** might result if sqlite3_free() is called with a non-NULL pointer that ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). ** ** ^The sqlite3_realloc(X,N) interface attempts to resize a ** prior memory allocation X to be at least N bytes. ** ^If the X parameter to sqlite3_realloc(X,N) ** is a NULL pointer then its behavior is identical to calling ** sqlite3_malloc(N). ** ^If the N parameter to sqlite3_realloc(X,N) is zero or ** negative then the behavior is exactly the same as calling ** sqlite3_free(X). ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation ** of at least N bytes in size or NULL if insufficient memory is available. ** ^If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned ** by sqlite3_realloc(X,N) and the prior allocation is freed. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the ** prior allocation is not freed. ** ** ^The sqlite3_realloc64(X,N) interfaces works the same as ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead ** of a 32-bit signed integer. ** ** ^If X is a memory allocation previously obtained from sqlite3_malloc(), ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then ** sqlite3_msize(X) returns the size of that memory allocation in bytes. ** ^The value returned by sqlite3_msize(X) might be larger than the number ** of bytes requested when X was allocated. ^If X is a NULL pointer then ** sqlite3_msize(X) returns zero. If X points to something that is not ** the beginning of memory allocation, or if it points to a formerly ** valid memory allocation that has now been freed, then the behavior ** of sqlite3_msize(X) is undefined and possibly harmful. ** ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), ** sqlite3_malloc64(), and sqlite3_realloc64() ** is always aligned to at least an 8 byte boundary, or to a ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time ** option is used. ** ** In SQLite version 3.5.0 and 3.5.1, it was possible to define ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in ** implementation of these routines to be omitted. That capability ** is no longer provided. Only built-in memory allocators can be used. ** ** Prior to SQLite version 3.7.10, the Windows OS interface layer called ** the system malloc() and free() directly when converting ** filenames between the UTF-8 encoding used by SQLite ** and whatever filename encoding is used by the particular Windows ** installation. Memory allocation errors were detected, but ** they were reported back as [SQLITE_CANTOPEN] or ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. ** ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] ** must be either NULL or else pointers obtained from a prior ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have ** not yet been released. ** ** The application must not read or write any part of ** a block of memory after it has been released using ** [sqlite3_free()] or [sqlite3_realloc()]. */ SQLITE_API void *sqlite3_malloc(int); SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); SQLITE_API void *sqlite3_realloc(void*, int); SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); SQLITE_API void sqlite3_free(void*); SQLITE_API sqlite3_uint64 sqlite3_msize(void*); /* ** CAPI3REF: Memory Allocator Statistics ** ** SQLite provides these two interfaces for reporting on the status ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] ** routines, which form the built-in memory allocation subsystem. ** ** ^The [sqlite3_memory_used()] routine returns the number of bytes ** of memory currently outstanding (malloced but not freed). ** ^The [sqlite3_memory_highwater()] routine returns the maximum ** value of [sqlite3_memory_used()] since the high-water mark ** was last reset. ^The values returned by [sqlite3_memory_used()] and ** [sqlite3_memory_highwater()] include any overhead ** added by SQLite in its implementation of [sqlite3_malloc()], ** but not overhead added by the any underlying system library ** routines that [sqlite3_malloc()] may call. ** ** ^The memory high-water mark is reset to the current value of ** [sqlite3_memory_used()] if and only if the parameter to ** [sqlite3_memory_highwater()] is true. ^The value returned ** by [sqlite3_memory_highwater(1)] is the high-water mark ** prior to the reset. */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void); SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator ** ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to ** select random [ROWID | ROWIDs] when inserting new records into a table that ** already uses the largest possible [ROWID]. The PRNG is also used for ** the build-in random() and randomblob() SQL functions. This interface allows ** applications to access the same PRNG for other purposes. ** ** ^A call to this routine stores N bytes of randomness into buffer P. ** ^The P parameter can be a NULL pointer. ** ** ^If this routine has not been previously called or if the previous ** call had N less than one or a NULL pointer for P, then the PRNG is ** seeded using randomness obtained from the xRandomness method of ** the default [sqlite3_vfs] object. ** ^If the previous call to this routine had an N of 1 or more and a ** non-NULL P then the pseudo-randomness is generated ** internally and without recourse to the [sqlite3_vfs] xRandomness ** method. */ SQLITE_API void sqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks ** METHOD: sqlite3 ** ** ^This routine registers an authorizer callback with a particular ** [database connection], supplied in the first argument. ** ^The authorizer callback is invoked as SQL statements are being compiled ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. ^The authorizer callback should ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the ** specific action but allow the SQL statement to continue to be ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be ** rejected with an error. ^If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] ** then the [sqlite3_prepare_v2()] or equivalent call that triggered ** the authorizer will fail with an error message. ** ** When the callback returns [SQLITE_OK], that means the operation ** requested is ok. ^When the callback returns [SQLITE_DENY], the ** [sqlite3_prepare_v2()] or equivalent call that triggered the ** authorizer will fail with an error message explaining that ** access is denied. ** ** ^The first parameter to the authorizer callback is a copy of the third ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter ** to the callback is an integer [SQLITE_COPY | action code] that specifies ** the particular action to be authorized. ^The third through sixth parameters ** to the callback are zero-terminated strings that contain additional ** details about the action to be authorized. ** ** ^If the action code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the ** [prepared statement] statement is constructed to substitute ** a NULL value in place of the table column that would have ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. ** ^If the action code is [SQLITE_DELETE] and the callback returns ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the ** [truncate optimization] is disabled and all rows are deleted individually. ** ** An authorizer is used when [sqlite3_prepare | preparing] ** SQL statements from an untrusted source, to ensure that the SQL statements ** do not try to access data they are not allowed to see, or that they do not ** try to execute malicious statements that damage the database. For ** example, an application may allow a user to enter arbitrary ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the ** user-entered SQL is being [sqlite3_prepare | prepared] that ** disallows everything except [SELECT] statements. ** ** Applications that need to process SQL from untrusted sources ** might also consider lowering resource limits using [sqlite3_limit()] ** and limiting database size using the [max_page_count] [PRAGMA] ** in addition to using an authorizer. ** ** ^(Only a single authorizer can be in place on a database connection ** at a time. Each call to sqlite3_set_authorizer overrides the ** previous call.)^ ^Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the ** statement might be re-prepared during [sqlite3_step()] due to a ** schema change. Hence, the application should ensure that the ** correct authorizer callback remains in place during the [sqlite3_step()]. ** ** ^Note that the authorizer callback is invoked only during ** [sqlite3_prepare()] or its variants. Authorization is not ** performed during statement evaluation in [sqlite3_step()], unless ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); /* ** CAPI3REF: Authorizer Return Codes ** ** The [sqlite3_set_authorizer | authorizer callback function] must ** return either [SQLITE_OK] or one of these two constants in order ** to signal SQLite whether or not the action is permitted. See the ** [sqlite3_set_authorizer | authorizer documentation] for additional ** information. ** ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] ** returned from the [sqlite3_vtab_on_conflict()] interface. */ #define SQLITE_DENY 1 /* Abort the SQL statement with an error */ #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ /* ** CAPI3REF: Authorizer Action Codes ** ** The [sqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorize certain SQL statement actions. The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that ** the authorizer callback may be passed. ** ** These action code values signify what kind of operation is to be ** authorized. The 3rd and 4th parameters to the authorization ** callback function will be parameters or NULL depending on which of these ** codes is used as the second parameter. ^(The 5th parameter to the ** authorizer callback is the name of the database ("main", "temp", ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback ** is the name of the inner-most trigger or view that is responsible for ** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ #define SQLITE_CREATE_VIEW 8 /* View Name NULL */ #define SQLITE_DELETE 9 /* Table Name NULL */ #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ #define SQLITE_DROP_TABLE 11 /* Table Name NULL */ #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ #define SQLITE_DROP_VIEW 17 /* View Name NULL */ #define SQLITE_INSERT 18 /* Table Name NULL */ #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ #define SQLITE_READ 20 /* Table Name Column Name */ #define SQLITE_SELECT 21 /* NULL NULL */ #define SQLITE_TRANSACTION 22 /* Operation NULL */ #define SQLITE_UPDATE 23 /* Table Name Column Name */ #define SQLITE_ATTACH 24 /* Filename NULL */ #define SQLITE_DETACH 25 /* Database Name NULL */ #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ #define SQLITE_REINDEX 27 /* Index Name NULL */ #define SQLITE_ANALYZE 28 /* Table Name NULL */ #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ #define SQLITE_FUNCTION 31 /* NULL Function Name */ #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ #define SQLITE_COPY 0 /* No longer used */ #define SQLITE_RECURSIVE 33 /* NULL NULL */ /* ** CAPI3REF: Tracing And Profiling Functions ** METHOD: sqlite3 ** ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface ** instead of the routines described here. ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** ** ^The callback function registered by sqlite3_trace() is invoked at ** various times when an SQL statement is being run by [sqlite3_step()]. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the ** SQL statement text as the statement first begins executing. ** ^(Additional sqlite3_trace() callbacks might occur ** as each triggered subprogram is entered. The callbacks for triggers ** contain a UTF-8 SQL comment that identifies the trigger.)^ ** ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit ** the length of [bound parameter] expansion in the output of sqlite3_trace(). ** ** ^The callback function registered by sqlite3_profile() is invoked ** as each SQL statement finishes. ^The profile callback contains ** the original statement text and an estimate of wall-clock time ** of how long that statement took to run. ^The profile callback ** time is in units of nanoseconds, however the current implementation ** is only capable of millisecond resolution so the six least significant ** digits in the time are meaningless. Future versions of SQLite ** might provide greater resolution on the profiler callback. The ** sqlite3_profile() function is considered experimental and is ** subject to change in future versions of SQLite. */ SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, void(*xProfile)(void*,const char*,sqlite3_uint64), void*); /* ** CAPI3REF: SQL Trace Event Codes ** KEYWORDS: SQLITE_TRACE ** ** These constants identify classes of events that can be monitored ** using the [sqlite3_trace_v2()] tracing logic. The third argument ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of ** the following constants. ^The first argument to the trace callback ** is one of the following constants. ** ** New tracing constants may be added in future releases. ** ** ^A trace callback has four arguments: xCallback(T,C,P,X). ** ^The T argument is one of the integer type codes above. ** ^The C argument is a copy of the context pointer passed in as the ** fourth argument to [sqlite3_trace_v2()]. ** The P and X arguments are pointers whose meanings depend on T. ** ** <dl> ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt> ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement ** first begins running and possibly at other times during the ** execution of the prepared statement, such as at the start of each ** trigger subprogram. ^The P argument is a pointer to the ** [prepared statement]. ^The X argument is a pointer to a string which ** is the unexpanded SQL text of the prepared statement or an SQL comment ** that indicates the invocation of a trigger. ^The callback can compute ** the same text that would have been returned by the legacy [sqlite3_trace()] ** interface by using the X argument when X begins with "--" and invoking ** [sqlite3_expanded_sql(P)] otherwise. ** ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt> ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same ** information as is provided by the [sqlite3_profile()] callback. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument points to a 64-bit integer which is the estimated of ** the number of nanosecond that the prepared statement took to run. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes. ** ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt> ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared ** statement generates a single row of result. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument is unused. ** ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt> ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database ** connection closes. ** ^The P argument is a pointer to the [database connection] object ** and the X argument is unused. ** </dl> */ #define SQLITE_TRACE_STMT 0x01 #define SQLITE_TRACE_PROFILE 0x02 #define SQLITE_TRACE_ROW 0x04 #define SQLITE_TRACE_CLOSE 0x08 /* ** CAPI3REF: SQL Trace Hook ** METHOD: sqlite3 ** ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback ** function X against [database connection] D, using property mask M ** and context pointer P. ^If the X callback is ** NULL or if the M mask is zero, then tracing is disabled. The ** M argument should be the bitwise OR-ed combination of ** zero or more [SQLITE_TRACE] constants. ** ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2(). ** ** ^The X callback is invoked whenever any of the events identified by ** mask M occur. ^The integer return value from the callback is currently ** ignored, though this may change in future releases. Callback ** implementations should return zero to ensure future compatibility. ** ** ^A trace callback is invoked with four arguments: callback(T,C,P,X). ** ^The T argument is one of the [SQLITE_TRACE] ** constants to indicate why the callback was invoked. ** ^The C argument is a copy of the context pointer. ** The P and X arguments are pointers whose meanings depend on T. ** ** The sqlite3_trace_v2() interface is intended to replace the legacy ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which ** are deprecated. */ SQLITE_API int sqlite3_trace_v2( sqlite3*, unsigned uMask, int(*xCallback)(unsigned,void*,void*,void*), void *pCtx ); /* ** CAPI3REF: Query Progress Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback ** function X to be invoked periodically during long running calls to ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for ** database connection D. An example use for this ** interface is to keep a GUI updated during a large query. ** ** ^The parameter P is passed through as the only parameter to the ** callback function X. ^The parameter N is the approximate number of ** [virtual machine instructions] that are evaluated between successive ** invocations of the callback X. ^If N is less than one then the progress ** handler is disabled. ** ** ^Only a single progress handler may be defined at one time per ** [database connection]; setting a new progress handler cancels the ** old one. ^Setting parameter X to NULL disables the progress handler. ** ^The progress handler is also disabled by setting N to a value less ** than 1. ** ** ^If the progress callback returns non-zero, the operation is ** interrupted. This feature can be used to implement a ** "Cancel" button on a GUI progress dialog box. ** ** The progress handler callback must not do anything that will modify ** the database connection that invoked the progress handler. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** */ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection ** CONSTRUCTOR: sqlite3 ** ** ^These routines open an SQLite database file as specified by the ** filename argument. ^The filename argument is interpreted as UTF-8 for ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte ** order for sqlite3_open16(). ^(A [database connection] handle is usually ** returned in *ppDb, even if an error occurs. The only exception is that ** if SQLite is unable to allocate memory to hold the [sqlite3] object, ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] ** object.)^ ^(If the database is opened (and/or created) successfully, then ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error following a failure of any ** of the sqlite3_open() routines. ** ** ^The default encoding will be UTF-8 for databases created using ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases ** created using sqlite3_open16() will be UTF-16 in the native byte order. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by ** passing it to [sqlite3_close()] when it is no longer required. ** ** The sqlite3_open_v2() interface works like sqlite3_open() ** except that it accepts two additional parameters for additional control ** over the new database connection. ^(The flags parameter to ** sqlite3_open_v2() can take one of ** the following three values, optionally combined with the ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ ** ** <dl> ** ^(<dt>[SQLITE_OPEN_READONLY]</dt> ** <dd>The database is opened in read-only mode. If the database does not ** already exist, an error is returned.</dd>)^ ** ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt> ** <dd>The database is opened for reading and writing if possible, or reading ** only if the file is write protected by the operating system. In either ** case the database must already exist, otherwise an error is returned.</dd>)^ ** ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt> ** <dd>The database is opened for reading and writing, and is created if ** it does not already exist. This is the behavior that is always used for ** sqlite3_open() and sqlite3_open16().</dd>)^ ** </dl> ** ** If the 3rd parameter to sqlite3_open_v2() is not one of the ** combinations shown above optionally combined with other ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] ** then the behavior is undefined. ** ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection ** opens in the multi-thread [threading mode] as long as the single-thread ** mode has not been set at compile-time or start-time. ^If the ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens ** in the serialized [threading mode] unless single-thread was ** previously selected at compile-time or start-time. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be ** eligible to use [shared cache mode], regardless of whether or not shared ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not ** participate in [shared cache mode] even if it is enabled. ** ** ^The fourth parameter to sqlite3_open_v2() is the name of the ** [sqlite3_vfs] object that defines the operating system interface that ** the new database connection should use. ^If the fourth parameter is ** a NULL pointer then the default [sqlite3_vfs] object is used. ** ** ^If the filename is ":memory:", then a private, temporary in-memory database ** is created for the connection. ^This in-memory database will vanish when ** the database connection is closed. Future versions of SQLite might ** make use of additional special filenames that begin with the ":" character. ** It is recommended that when a database filename actually does begin with ** a ":" character you should prefix the filename with a pathname such as ** "./" to avoid ambiguity. ** ** ^If the filename is an empty string, then a private, temporary ** on-disk database will be created. ^This private database will be ** automatically deleted as soon as the database connection is closed. ** ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3> ** ** ^If [URI filename] interpretation is enabled, and the filename argument ** begins with "file:", then the filename is interpreted as a URI. ^URI ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is ** set in the fourth argument to sqlite3_open_v2(), or if it has ** been enabled globally using the [SQLITE_CONFIG_URI] option with the ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. ** As of SQLite version 3.7.7, URI filename interpretation is turned off ** by default, but future releases of SQLite might enable URI filename ** interpretation by default. See "[URI filenames]" for additional ** information. ** ** URI filenames are parsed according to RFC 3986. ^If the URI contains an ** authority, then it must be either an empty string or the string ** "localhost". ^If the authority is not an empty string or "localhost", an ** error is returned to the caller. ^The fragment component of a URI, if ** present, is ignored. ** ** ^SQLite uses the path component of the URI as the name of the disk file ** which contains the database. ^If the path begins with a '/' character, ** then it is interpreted as an absolute path. ^If the path does not begin ** with a '/' (meaning that the authority section is omitted from the URI) ** then the path is interpreted as a relative path. ** ^(On windows, the first component of an absolute path ** is a drive specification (e.g. "C:").)^ ** ** [[core URI query parameters]] ** The query component of a URI may contain parameters that are interpreted ** either by SQLite itself, or by a [VFS | custom VFS implementation]. ** SQLite and its built-in [VFSes] interpret the ** following query parameters: ** ** <ul> ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of ** a VFS object that provides the operating system interface that should ** be used to access the database file on disk. ^If this option is set to ** an empty string the default VFS object is used. ^Specifying an unknown ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is ** present, then the VFS specified by the option takes precedence over ** the value passed as the fourth parameter to sqlite3_open_v2(). ** ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw", ** "rwc", or "memory". Attempting to set it to any other value is ** an error)^. ** ^If "ro" is specified, then the database is opened for read-only ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the ** third argument to sqlite3_open_v2(). ^If the mode option is set to ** "rw", then the database is opened for read-write (but not create) ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had ** been set. ^Value "rwc" is equivalent to setting both ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is ** set to "memory" then a pure [in-memory database] that never reads ** or writes from disk is used. ^It is an error to specify a value for ** the mode parameter that is less restrictive than that specified by ** the flags passed in the third parameter to sqlite3_open_v2(). ** ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or ** "private". ^Setting it to "shared" is equivalent to setting the ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in ** a URI filename, its value overrides any behavior requested by setting ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. ** ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the ** [powersafe overwrite] property does or does not apply to the ** storage media on which the database file resides. ** ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter ** which if set disables file locking in rollback journal modes. This ** is useful for accessing a database on a filesystem that does not ** support locking. Caution: Database corruption might result if two ** or more processes write to the same database and any one of those ** processes uses nolock=1. ** ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query ** parameter that indicates that the database file is stored on ** read-only media. ^When immutable is set, SQLite assumes that the ** database file cannot be changed, even by a process with higher ** privilege, and so the database is opened read-only and all locking ** and change detection is disabled. Caution: Setting the immutable ** property on a database file that does in fact change can result ** in incorrect query results and/or [SQLITE_CORRUPT] errors. ** See also: [SQLITE_IOCAP_IMMUTABLE]. ** ** </ul> ** ** ^Specifying an unknown parameter in the query component of a URI is not an ** error. Future versions of SQLite might understand additional query ** parameters. See "[query parameters with special meaning to SQLite]" for ** additional information. ** ** [[URI filename examples]] <h3>URI filename examples</h3> ** ** <table border="1" align=center cellpadding=5> ** <tr><th> URI filenames <th> Results ** <tr><td> file:data.db <td> ** Open the file "data.db" in the current directory. ** <tr><td> file:/home/fred/data.db<br> ** file:///home/fred/data.db <br> ** file://localhost/home/fred/data.db <br> <td> ** Open the database file "/home/fred/data.db". ** <tr><td> file://darkstar/home/fred/data.db <td> ** An error. "darkstar" is not a recognized authority. ** <tr><td style="white-space:nowrap"> ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db ** <td> Windows only: Open the file "data.db" on fred's desktop on drive ** C:. Note that the %20 escaping in this example is not strictly ** necessary - space characters can be used literally ** in URI filenames. ** <tr><td> file:data.db?mode=ro&cache=private <td> ** Open file "data.db" in the current directory for read-only access. ** Regardless of whether or not shared-cache mode is enabled by ** default, use a private cache. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td> ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile" ** that uses dot-files in place of posix advisory locking. ** <tr><td> file:data.db?mode=readonly <td> ** An error. "readonly" is not a valid option for the "mode" parameter. ** </table> ** ** ^URI hexadecimal escape sequences (%HH) are supported within the path and ** query components of a URI. A hexadecimal escape sequence consists of a ** percent sign - "%" - followed by exactly two hexadecimal digits ** specifying an octet value. ^Before the path or query components of a ** URI filename are interpreted, they are encoded using UTF-8 and all ** hexadecimal escape sequences replaced by a single byte containing the ** corresponding octet. If this process generates an invalid UTF-8 encoding, ** the results are undefined. ** ** <b>Note to Windows users:</b> The encoding used for the filename argument ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into ** sqlite3_open() or sqlite3_open_v2(). ** ** <b>Note to Windows Runtime users:</b> The temporary directory must be set ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various ** features that require the use of temporary files may fail. ** ** See also: [sqlite3_temp_directory] */ SQLITE_API int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open16( const void *filename, /* Database filename (UTF-16) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); /* ** CAPI3REF: Obtain Values For URI Parameters ** ** These are utility routines, useful to VFS implementations, that check ** to see if a database file was a URI that contained a specific query ** parameter, and if so obtains the value of that query parameter. ** ** If F is the database filename pointer passed into the xOpen() method of ** a VFS implementation when the flags parameter to xOpen() has one or ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and ** P is the name of the query parameter, then ** sqlite3_uri_parameter(F,P) returns the value of the P ** parameter if it exists or a NULL pointer if P does not appear as a ** query parameter on F. If P is a query parameter of F ** has no explicit value, then sqlite3_uri_parameter(F,P) returns ** a pointer to an empty string. ** ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean ** parameter and returns true (1) or false (0) according to the value ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the ** value of query parameter P is one of "yes", "true", or "on" in any ** case or if the value begins with a non-zero number. The ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of ** query parameter P is one of "no", "false", or "off" in any case or ** if the value begins with a numeric zero. If P is not a query ** parameter on F or if the value of P is does not match any of the ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). ** ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a ** 64-bit signed integer and returns that integer, or D if P does not ** exist. If the value of P is something other than an integer, then ** zero is returned. ** ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and ** is not a database file pathname pointer that SQLite passed into the xOpen ** VFS method, then the behavior of this routine is undefined and probably ** undesirable. */ SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); /* ** CAPI3REF: Error Codes And Messages ** METHOD: sqlite3 ** ** ^If the most recent sqlite3_* API call associated with ** [database connection] D failed, then the sqlite3_errcode(D) interface ** returns the numeric [result code] or [extended result code] for that ** API call. ** If the most recent API call was successful, ** then the return value from sqlite3_errcode() is undefined. ** ^The sqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. ** ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language ** text that describes the error, as either UTF-8 or UTF-16 respectively. ** ^(Memory to hold the error message string is managed internally. ** The application does not need to worry about freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions.)^ ** ** ^The sqlite3_errstr() interface returns the English-language text ** that describes the [result code], as UTF-8. ** ^(Memory to hold the error message string is managed internally ** and must not be freed by the application)^. ** ** When the serialized [threading mode] is in use, it might be the ** case that a second error occurs on a separate thread in between ** the time of the first error and the call to these interfaces. ** When that happens, the second error will be reported since these ** interfaces always report the most recent result. To avoid ** this, each thread can obtain exclusive use of the [database connection] D ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after ** all calls to the interfaces listed here are completed. ** ** If an interface fails with SQLITE_MISUSE, that means the interface ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. */ SQLITE_API int sqlite3_errcode(sqlite3 *db); SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); SQLITE_API const char *sqlite3_errmsg(sqlite3*); SQLITE_API const void *sqlite3_errmsg16(sqlite3*); SQLITE_API const char *sqlite3_errstr(int); /* ** CAPI3REF: Prepared Statement Object ** KEYWORDS: {prepared statement} {prepared statements} ** ** An instance of this object represents a single SQL statement that ** has been compiled into binary form and is ready to be evaluated. ** ** Think of each SQL statement as a separate computer program. The ** original SQL text is source code. A prepared statement object ** is the compiled object code. All SQL must be converted into a ** prepared statement before it can be run. ** ** The life-cycle of a prepared statement object usually goes like this: ** ** <ol> ** <li> Create the prepared statement object using [sqlite3_prepare_v2()]. ** <li> Bind values to [parameters] using the sqlite3_bind_*() ** interfaces. ** <li> Run the SQL by calling [sqlite3_step()] one or more times. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. ** <li> Destroy the object using [sqlite3_finalize()]. ** </ol> */ typedef struct sqlite3_stmt sqlite3_stmt; /* ** CAPI3REF: Run-time Limits ** METHOD: sqlite3 ** ** ^(This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the ** [database connection] whose limit is to be set or queried. The ** second parameter is one of the [limit categories] that define a ** class of constructs to be size limited. The third parameter is the ** new limit for that construct.)^ ** ** ^If the new limit is a negative number, the limit is unchanged. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a ** [limits | hard upper bound] ** set at compile-time by a C preprocessor macro called ** [limits | SQLITE_MAX_<i>NAME</i>]. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^ ** ^Attempts to increase a limit above its hard upper bound are ** silently truncated to the hard upper bound. ** ** ^Regardless of whether or not the limit was changed, the ** [sqlite3_limit()] interface returns the prior value of the limit. ** ^Hence, to find the current value of a limit without changing it, ** simply invoke this interface with the third parameter set to -1. ** ** Run-time limits are intended for use in applications that manage ** both their own internal database and also databases that are controlled ** by untrusted external sources. An example application might be a ** web browser that has its own databases for storing history and ** separate databases controlled by JavaScript applications downloaded ** off the Internet. The internal databases can be given the ** large, default limits. Databases managed by external sources can ** be given much smaller limits designed to prevent a denial of service ** attack. Developers might also want to use the [sqlite3_set_authorizer()] ** interface to further control untrusted SQL. The size of the database ** created by an untrusted script can be contained using the ** [max_page_count] [PRAGMA]. ** ** New run-time limit categories may be added in future releases. */ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories ** KEYWORDS: {limit category} {*limit categories} ** ** These constants define various performance limits ** that can be lowered at run-time using [sqlite3_limit()]. ** The synopsis of the meanings of the various limits is shown below. ** Additional information is available at [limits | Limits in SQLite]. ** ** <dl> ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt> ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^ ** ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt> ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^ ** ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt> ** <dd>The maximum number of columns in a table definition or in the ** result set of a [SELECT] or the maximum number of columns in an index ** or in an ORDER BY or GROUP BY clause.</dd>)^ ** ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt> ** <dd>The maximum depth of the parse tree on any expression.</dd>)^ ** ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt> ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^ ** ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt> ** <dd>The maximum number of instructions in a virtual machine program ** used to implement an SQL statement. This limit is not currently ** enforced, though that might be added in some future release of ** SQLite.</dd>)^ ** ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt> ** <dd>The maximum number of arguments on a function.</dd>)^ ** ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt> ** <dd>The maximum number of [ATTACH | attached databases].)^</dd> ** ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt> ** <dd>The maximum length of the pattern argument to the [LIKE] or ** [GLOB] operators.</dd>)^ ** ** [[SQLITE_LIMIT_VARIABLE_NUMBER]] ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt> ** <dd>The maximum index number of any [parameter] in an SQL statement.)^ ** ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt> ** <dd>The maximum depth of recursion for triggers.</dd>)^ ** ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt> ** <dd>The maximum number of auxiliary worker threads that a single ** [prepared statement] may start.</dd>)^ ** </dl> */ #define SQLITE_LIMIT_LENGTH 0 #define SQLITE_LIMIT_SQL_LENGTH 1 #define SQLITE_LIMIT_COLUMN 2 #define SQLITE_LIMIT_EXPR_DEPTH 3 #define SQLITE_LIMIT_COMPOUND_SELECT 4 #define SQLITE_LIMIT_VDBE_OP 5 #define SQLITE_LIMIT_FUNCTION_ARG 6 #define SQLITE_LIMIT_ATTACHED 7 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 #define SQLITE_LIMIT_WORKER_THREADS 11 /* ** CAPI3REF: Compiling An SQL Statement ** KEYWORDS: {SQL statement compiler} ** METHOD: sqlite3 ** CONSTRUCTOR: sqlite3_stmt ** ** To execute an SQL query, it must first be compiled into a byte-code ** program using one of these routines. ** ** The first argument, "db", is a [database connection] obtained from a ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or ** [sqlite3_open16()]. The database connection must not have been closed. ** ** The second argument, "zSql", is the statement to be compiled, encoded ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() ** use UTF-16. ** ** ^If the nByte argument is negative, then zSql is read up to the ** first zero terminator. ^If nByte is positive, then it is the ** number of bytes read from zSql. ^If nByte is zero, then no prepared ** statement is generated. ** If the caller knows that the supplied string is nul-terminated, then ** there is a small performance advantage to passing an nByte parameter that ** is the number of bytes in the input string <i>including</i> ** the nul-terminator. ** ** ^If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only ** compile the first statement in zSql, so *pzTail is left pointing to ** what remains uncompiled. ** ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set ** to NULL. ^If the input text contains no SQL (if the input is an empty ** string or a comment) then *ppStmt is set to NULL. ** The calling procedure is responsible for deleting the compiled ** SQL statement using [sqlite3_finalize()] after it has finished with it. ** ppStmt may not be NULL. ** ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; ** otherwise an [error code] is returned. ** ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are ** recommended for all new programs. The two older interfaces are retained ** for backwards compatibility, but their use is discouraged. ** ^In the "v2" interfaces, the prepared statement ** that is returned (the [sqlite3_stmt] object) contains a copy of the ** original SQL text. This causes the [sqlite3_step()] interface to ** behave differently in three ways: ** ** <ol> ** <li> ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it ** always used to do, [sqlite3_step()] will automatically recompile the SQL ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] ** retries will occur before sqlite3_step() gives up and returns an error. ** </li> ** ** <li> ** ^When an error occurs, [sqlite3_step()] will return one of the detailed ** [error codes] or [extended error codes]. ^The legacy behavior was that ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code ** and the application would have to make a second call to [sqlite3_reset()] ** in order to find the underlying cause of the problem. With the "v2" prepare ** interfaces, the underlying reason for the error is returned immediately. ** </li> ** ** <li> ** ^If the specific value bound to [parameter | host parameter] in the ** WHERE clause might influence the choice of query plan for a statement, ** then the statement will be automatically recompiled, as if there had been ** a schema change, on the first [sqlite3_step()] call following any change ** to the [sqlite3_bind_text | bindings] of that [parameter]. ** ^The specific value of WHERE-clause [parameter] might influence the ** choice of query plan if the parameter is the left-hand side of a [LIKE] ** or [GLOB] operator or if the parameter is compared to an indexed column ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. ** </li> ** </ol> */ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16_v2( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* ** CAPI3REF: Retrieving Statement SQL ** METHOD: sqlite3_stmt ** ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 ** SQL text used to create [prepared statement] P if P was ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 ** string containing the SQL text of prepared statement P with ** [bound parameters] expanded. ** ** ^(For example, if a prepared statement is created using the SQL ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345 ** and parameter :xyz is unbound, then sqlite3_sql() will return ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql() ** will return "SELECT 2345,NULL".)^ ** ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory ** is available to hold the result, or if the result would exceed the ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. ** ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time ** option causes sqlite3_expanded_sql() to always return NULL. ** ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is ** automatically freed when the prepared statement is finalized. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand, ** is obtained from [sqlite3_malloc()] and must be free by the application ** by passing it to [sqlite3_free()]. */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If An SQL Statement Writes The Database ** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if ** and only if the [prepared statement] X makes no direct changes to ** the content of the database file. ** ** Note that [application-defined SQL functions] or ** [virtual tables] might change the database indirectly as a side effect. ** ^(For example, if an application defines a function "eval()" that ** calls [sqlite3_exec()], then the following SQL statement would ** change the database file through side-effects: ** ** <blockquote><pre> ** SELECT eval('DELETE FROM t1') FROM t2; ** </pre></blockquote> ** ** But because the [SELECT] statement does not change the database file ** directly, sqlite3_stmt_readonly() would still return true.)^ ** ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, ** since the statements themselves do not actually modify the database but ** rather they control the timing of when other statements modify the ** database. ^The [ATTACH] and [DETACH] statements also cause ** sqlite3_stmt_readonly() to return true since, while those statements ** change the configuration of a database connection, they do not make ** changes to the content of the database files on disk. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so ** sqlite3_stmt_readonly() returns false for those commands. */ SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If A Prepared Statement Has Been Reset ** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the ** [prepared statement] S has been stepped at least once using ** [sqlite3_step(S)] but has neither run to completion (returned ** [SQLITE_DONE] from [sqlite3_step(S)]) nor ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) ** interface returns false if S is a NULL pointer. If S is not a ** NULL pointer and is not a pointer to a valid [prepared statement] ** object, then the behavior is undefined and probably undesirable. ** ** This interface can be used in combination [sqlite3_next_stmt()] ** to locate all prepared statements associated with a database ** connection that are in need of being reset. This can be used, ** for example, in diagnostic routines to search for prepared ** statements that are holding a transaction open. */ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); /* ** CAPI3REF: Dynamically Typed Value Object ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} ** ** SQLite uses the sqlite3_value object to represent all values ** that can be stored in a database table. SQLite uses dynamic typing ** for the values it stores. ^Values stored in sqlite3_value objects ** can be integers, floating point values, strings, BLOBs, or NULL. ** ** An sqlite3_value object may be either "protected" or "unprotected". ** Some interfaces require a protected sqlite3_value. Other interfaces ** will accept either a protected or an unprotected sqlite3_value. ** Every interface that accepts sqlite3_value arguments specifies ** whether or not it requires a protected sqlite3_value. The ** [sqlite3_value_dup()] interface can be used to construct a new ** protected sqlite3_value from an unprotected sqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. An internal mutex is held for a protected ** sqlite3_value object but no mutex is held for an unprotected ** sqlite3_value object. If SQLite is compiled to be single-threaded ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) ** or if SQLite is run in one of reduced mutex modes ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] ** then there is no distinction between protected and unprotected ** sqlite3_value objects and they can be used interchangeably. However, ** for maximum code portability it is recommended that applications ** still make the distinction between protected and unprotected ** sqlite3_value objects even when not strictly required. ** ** ^The sqlite3_value objects that are passed as parameters into the ** implementation of [application-defined SQL functions] are protected. ** ^The sqlite3_value object returned by ** [sqlite3_column_value()] is unprotected. ** Unprotected sqlite3_value objects may only be used with ** [sqlite3_result_value()] and [sqlite3_bind_value()]. ** The [sqlite3_value_blob | sqlite3_value_type()] family of ** interfaces require protected sqlite3_value objects. */ typedef struct Mem sqlite3_value; /* ** CAPI3REF: SQL Function Context Object ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. ^A pointer to an sqlite3_context object ** is always first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], ** [sqlite3_aggregate_context()], [sqlite3_user_data()], ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], ** and/or [sqlite3_set_auxdata()]. */ typedef struct sqlite3_context sqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} ** METHOD: sqlite3_stmt ** ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] that matches one of following ** templates: ** ** <ul> ** <li> ? ** <li> ?NNN ** <li> :VVV ** <li> @VVV ** <li> $VVV ** </ul> ** ** In the templates above, NNN represents an integer literal, ** and VVV represents an alphanumeric identifier.)^ ^The values of these ** parameters (also called "host parameter names" or "SQL parameters") ** can be set using the sqlite3_bind_*() routines defined here. ** ** ^The first argument to the sqlite3_bind_*() routines is always ** a pointer to the [sqlite3_stmt] object returned from ** [sqlite3_prepare_v2()] or its variants. ** ** ^The second argument is the index of the SQL parameter to be set. ** ^The leftmost SQL parameter has an index of 1. ^When the same named ** SQL parameter is used more than once, second and subsequent ** occurrences have the same index as the first occurrence. ** ^The index for named parameters can be looked up using the ** [sqlite3_bind_parameter_index()] API if desired. ^The index ** for "?NNN" parameters is the value of NNN. ** ^The NNN value must be between 1 and the [sqlite3_limit()] ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). ** ** ^The third argument is the value to bind to the parameter. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter ** is ignored and the end result is the same as sqlite3_bind_null(). ** ** ^(In those routines that have a fourth argument, its value is the ** number of bytes in the parameter. To be clear: the value is the ** number of <u>bytes</u> in the value, not the number of characters.)^ ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() ** is negative, then the length of the string is ** the number of bytes up to the first zero terminator. ** If the fourth parameter to sqlite3_bind_blob() is negative, then ** the behavior is undefined. ** If a non-negative fourth parameter is provided to sqlite3_bind_text() ** or sqlite3_bind_text16() or sqlite3_bind_text64() then ** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL ** terminated. If any NUL characters occur at byte offsets less than ** the value of the fourth parameter then the resulting string value will ** contain embedded NULs. The result of expressions involving strings ** with embedded NULs is undefined. ** ** ^The fifth argument to the BLOB and string binding interfaces ** is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. ^The destructor is called ** to dispose of the BLOB or string even if the call to bind API fails. ** ^If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before ** the sqlite3_bind_*() routine returns. ** ** ^The sixth argument to sqlite3_bind_text64() must be one of ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] ** to specify the encoding of the text in the third parameter. If ** the sixth argument to sqlite3_bind_text64() is not one of the ** allowed values shown above, or if the text encoding is different ** from the encoding specified by the sixth parameter, then the behavior ** is undefined. ** ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. ** Zeroblobs are intended to serve as placeholders for BLOBs whose ** content is later written using ** [sqlite3_blob_open | incremental BLOB I/O] routines. ** ^A negative value for the zeroblob results in a zero-length BLOB. ** ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer ** for the [prepared statement] or with a prepared statement for which ** [sqlite3_step()] has been called more recently than [sqlite3_reset()], ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() ** routine is passed a [prepared statement] that has been finalized, the ** result is undefined and probably harmful. ** ** ^Bindings are not cleared by the [sqlite3_reset()] routine. ** ^Unbound parameters are interpreted as NULL. ** ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an ** [error code] if anything goes wrong. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or ** [SQLITE_MAX_LENGTH]. ** ^[SQLITE_RANGE] is returned if the parameter ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. ** ** See also: [sqlite3_bind_parameter_count()], ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. */ SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, void(*)(void*)); SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, void(*)(void*), unsigned char encoding); SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); /* ** CAPI3REF: Number Of SQL Parameters ** METHOD: sqlite3_stmt ** ** ^This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as ** placeholders for values that are [sqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** ^(This routine actually returns the index of the largest (rightmost) ** parameter. For all forms except ?NNN, this will correspond to the ** number of unique parameters. If parameters of the ?NNN form are used, ** there may be gaps in the list.)^ ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_name()], and ** [sqlite3_bind_parameter_index()]. */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter ** METHOD: sqlite3_stmt ** ** ^The sqlite3_bind_parameter_name(P,N) interface returns ** the name of the N-th [SQL parameter] in the [prepared statement] P. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" ** respectively. ** In other words, the initial ":" or "$" or "@" or "?" ** is included as part of the name.)^ ** ^Parameters of the form "?" without a following integer have no name ** and are referred to as "nameless" or "anonymous parameters". ** ** ^The first host parameter has an index of 1, not 0. ** ** ^If the value N is out of range or if the N-th parameter is ** nameless, then NULL is returned. ^The returned string is ** always in UTF-8 encoding even if the named parameter was ** originally specified as UTF-16 in [sqlite3_prepare16()] or ** [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name ** METHOD: sqlite3_stmt ** ** ^Return the index of an SQL parameter given its name. ^The ** index value returned is suitable for use as the second ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero ** is returned if no matching parameter is found. ^The parameter ** name must be given in UTF-8 even if the original statement ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_name()]. */ SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement ** METHOD: sqlite3_stmt ** ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. ** ^Use this routine to reset all host parameters to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set ** METHOD: sqlite3_stmt ** ** ^Return the number of columns in the result set returned by the ** [prepared statement]. ^If this routine returns 0, that means the ** [prepared statement] returns no data (for example an [UPDATE]). ** ^However, just because this routine returns a positive number does not ** mean that one or more rows of data will be returned. ^A SELECT statement ** will always have a positive sqlite3_column_count() but depending on the ** WHERE clause constraints and the table content, it might return no rows. ** ** See also: [sqlite3_data_count()] */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set ** METHOD: sqlite3_stmt ** ** ^These routines return the name assigned to a particular column ** in the result set of a [SELECT] statement. ^The sqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF-8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated ** UTF-16 string. ^The first parameter is the [prepared statement] ** that implements the [SELECT] statement. ^The second parameter is the ** column number. ^The leftmost column is number 0. ** ** ^The returned string pointer is valid until either the [prepared statement] ** is destroyed by [sqlite3_finalize()] or until the statement is automatically ** reprepared by the first call to [sqlite3_step()] for a particular run ** or until the next call to ** sqlite3_column_name() or sqlite3_column_name16() on the same column. ** ** ^If sqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. ** ** ^The name of a result column is the value of the "AS" clause for ** that column, if there is an AS clause. If there is no AS clause ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. */ SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result ** METHOD: sqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and ** table column that is the origin of a particular result column in ** [SELECT] statement. ** ^The name of the database or table or column can be returned as ** either a UTF-8 or UTF-16 string. ^The _database_ routines return ** the database name, the _table_ routines return the table name, and ** the origin_ routines return the column name. ** ^The returned string is valid until the [prepared statement] is destroyed ** using [sqlite3_finalize()] or until the statement is automatically ** reprepared by the first call to [sqlite3_step()] for a particular run ** or until the same information is requested ** again in a different encoding. ** ** ^The names returned are the original un-aliased names of the ** database, table, and column. ** ** ^The first argument to these interfaces is a [prepared statement]. ** ^These functions return information about the Nth result column returned by ** the statement, where N is the second function argument. ** ^The left-most column is column 0 for these routines. ** ** ^If the Nth column returned by the statement is an expression or ** subquery and is not a column value, then all of these functions return ** NULL. ^These routine might also return NULL if a memory allocation error ** occurs. ^Otherwise, they return the name of the attached database, table, ** or column that query result column was extracted from. ** ** ^As with all other SQLite APIs, those whose names end with "16" return ** UTF-16 encoded strings and the other functions return UTF-8. ** ** ^These APIs are only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. ** ** If two or more threads call one or more of these routines against the same ** prepared statement and column at the same time then the results are ** undefined. ** ** If two or more threads call one or more ** [sqlite3_column_database_name | column metadata interfaces] ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result ** METHOD: sqlite3_stmt ** ** ^(The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the ** returned result set of that [SELECT] is a table column (not an ** expression or subquery) then the declared type of the table ** column is returned.)^ ^If the Nth column of the result set is an ** expression or subquery, then a NULL pointer is returned. ** ^The returned string is always UTF-8 encoded. ** ** ^(For example, given the database schema: ** ** CREATE TABLE t1(c1 VARIANT); ** ** and the following statement to be compiled: ** ** SELECT c1 + 1, c1 FROM t1; ** ** this routine would return the string "VARIANT" for the second result ** column (i==1), and a NULL pointer for the first result column (i==0).)^ ** ** ^SQLite uses dynamic run-time typing. ^So just because a column ** is declared to contain a particular type does not mean that the ** data stored in that column is of the declared type. SQLite is ** strongly typed, but the typing is dynamic not static. ^Type ** is associated with individual values, not with the containers ** used to hold those values. */ SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement ** METHOD: sqlite3_stmt ** ** After a [prepared statement] has been prepared using either ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function ** must be called one or more times to evaluate the statement. ** ** The details of the behavior of the sqlite3_step() interface depend ** on whether the statement was prepared using the newer "v2" interface ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the ** new "v2" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** ** ^In the legacy interface, the return value will be either [SQLITE_BUSY], ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. ** ^With the "v2" interface, any of the other [result codes] or ** [extended result codes] might be returned as well. ** ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the ** database locks it needs to do its job. ^If the statement is a [COMMIT] ** or occurs outside of an explicit transaction, then you can retry the ** statement. If the statement is not a [COMMIT] and occurs within an ** explicit transaction then you should rollback the transaction before ** continuing. ** ** ^[SQLITE_DONE] means that the statement has finished executing ** successfully. sqlite3_step() should not be called again on this virtual ** machine without first calling [sqlite3_reset()] to reset the virtual ** machine back to its initial state. ** ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] ** is returned each time a new row of data is ready for processing by the ** caller. The values may be accessed using the [column access functions]. ** sqlite3_step() is called again to retrieve the next row of data. ** ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint ** violation) has occurred. sqlite3_step() should not be called again on ** the VM. More information may be found by calling [sqlite3_errmsg()]. ** ^With the legacy interface, a more specific error code (for example, ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) ** can be obtained by calling [sqlite3_reset()] on the ** [prepared statement]. ^In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has ** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** ** For all versions of SQLite up to and including 3.6.23.1, a call to ** [sqlite3_reset()] was required after sqlite3_step() returned anything ** other than [SQLITE_ROW] before any subsequent invocation of ** sqlite3_step(). Failure to reset the prepared statement using ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], ** sqlite3_step() began ** calling [sqlite3_reset()] automatically in this circumstance rather ** than returning [SQLITE_MISUSE]. This is not considered a compatibility ** break because any application that ever receives an SQLITE_MISUSE error ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option ** can be used to restore the legacy behavior. ** ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step() ** API always returns a generic error code, [SQLITE_ERROR], following any ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the ** specific [error codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, ** then the more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. */ SQLITE_API int sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set ** METHOD: sqlite3_stmt ** ** ^The sqlite3_data_count(P) interface returns the number of columns in the ** current row of the result set of [prepared statement] P. ** ^If prepared statement P does not have results ready to return ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of ** interfaces) then sqlite3_data_count(P) returns 0. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) ** will return non-zero if previous call to [sqlite3_step](P) returned ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] ** where it always returns zero since each step of that multi-step ** pragma returns 0 columns of data. ** ** See also: [sqlite3_column_count()] */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes ** KEYWORDS: SQLITE_TEXT ** ** ^(Every value in SQLite has one of five fundamental datatypes: ** ** <ul> ** <li> 64-bit signed integer ** <li> 64-bit IEEE floating point number ** <li> string ** <li> BLOB ** <li> NULL ** </ul>)^ ** ** These constants are codes for each of those types. ** ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 ** for a completely different meaning. Software that links against both ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not ** SQLITE_TEXT. */ #define SQLITE_INTEGER 1 #define SQLITE_FLOAT 2 #define SQLITE_BLOB 4 #define SQLITE_NULL 5 #ifdef SQLITE_TEXT # undef SQLITE_TEXT #else # define SQLITE_TEXT 3 #endif #define SQLITE3_TEXT 3 /* ** CAPI3REF: Result Values From A Query ** KEYWORDS: {column access functions} ** METHOD: sqlite3_stmt ** ** ^These routines return information about a single column of the current ** result row of a query. ^In every case the first argument is a pointer ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] ** that was returned from [sqlite3_prepare_v2()] or one of its variants) ** and the second argument is the index of the column for which information ** should be returned. ^The leftmost column of the result set has the index 0. ** ^The number of columns in the result can be determined using ** [sqlite3_column_count()]. ** ** If the SQL statement does not currently point to a valid row, or if the ** column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. ** If any of these routines are called after [sqlite3_reset()] or ** [sqlite3_finalize()] or after [sqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] ** are called from a different thread while any of these routines ** are pending, then the results are undefined. ** ** ^The sqlite3_column_type() routine returns the ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. ^The returned value is one of [SQLITE_INTEGER], ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value ** returned by sqlite3_column_type() is only meaningful if no type ** conversions have occurred as described below. After a type conversion, ** the value returned by sqlite3_column_type() is undefined. Future ** versions of SQLite may change the behavior of sqlite3_column_type() ** following a type conversion. ** ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. ** ^If the result is a numeric value then sqlite3_column_bytes() uses ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns ** the number of bytes in that string. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero. ** ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() ** routine returns the number of bytes in that BLOB or string. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts ** the string to UTF-16 and then returns the number of bytes. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns ** the number of bytes in that string. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. ** ** ^The values returned by [sqlite3_column_bytes()] and ** [sqlite3_column_bytes16()] do not include the zero terminators at the end ** of the string. ^For clarity: the values returned by ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of ** bytes in the string, not the number of characters. ** ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), ** even empty strings, are always zero-terminated. ^The return ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. ** ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an ** [unprotected sqlite3_value] object. In a multithreaded environment, ** an unprotected sqlite3_value object may only be used safely with ** [sqlite3_bind_value()] and [sqlite3_result_value()]. ** If the [unprotected sqlite3_value] object returned by ** [sqlite3_column_value()] is used in any other way, including calls ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], ** or [sqlite3_value_bytes()], the behavior is not threadsafe. ** ** These routines attempt to convert the value where appropriate. ^For ** example, if the internal representation is FLOAT and a text result ** is requested, [sqlite3_snprintf()] is used internally to perform the ** conversion automatically. ^(The following table details the conversions ** that are applied: ** ** <blockquote> ** <table border="1"> ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion ** ** <tr><td> NULL <td> INTEGER <td> Result is 0 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL ** <tr><td> TEXT <td> BLOB <td> No change ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed ** </table> ** </blockquote>)^ ** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or ** sqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** ** <ul> ** <li> The initial content is a BLOB and sqlite3_column_text() or ** sqlite3_column_text16() is called. A zero-terminator might ** need to be added to the string.</li> ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or ** sqlite3_column_text16() is called. The content must be converted ** to UTF-16.</li> ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or ** sqlite3_column_text() is called. The content must be converted ** to UTF-8.</li> ** </ul> ** ** ^Conversions between UTF-16be and UTF-16le are always done in place and do ** not invalidate a prior pointer, though of course the content of the buffer ** that the prior pointer references will have been modified. Other kinds ** of conversion are done in place when it is possible, but sometimes they ** are not possible and in those cases prior pointers are invalidated. ** ** The safest policy is to invoke these routines ** in one of the following ways: ** ** <ul> ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> ** </ul> ** ** In other words, you should call sqlite3_column_text(), ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result ** into the desired format, then invoke sqlite3_column_bytes() or ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls ** to sqlite3_column_text() or sqlite3_column_blob() with calls to ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() ** with calls to sqlite3_column_bytes(). ** ** ^The pointers returned are valid until a type conversion occurs as ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or ** [sqlite3_finalize()] is called. ^The memory space used to hold strings ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into ** [sqlite3_free()]. ** ** ^(If a memory allocation error occurs during the evaluation of any ** of these routines, a default value is returned. The default value ** is either the integer 0, the floating point number 0.0, or a NULL ** pointer. Subsequent calls to [sqlite3_errcode()] will return ** [SQLITE_NOMEM].)^ */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object ** DESTRUCTOR: sqlite3_stmt ** ** ^The sqlite3_finalize() function is called to delete a [prepared statement]. ** ^If the most recent evaluation of the statement encountered no errors ** or if the statement is never been evaluated, then sqlite3_finalize() returns ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then ** sqlite3_finalize(S) returns the appropriate [error code] or ** [extended error code]. ** ** ^The sqlite3_finalize(S) routine can be called at any point during ** the life cycle of [prepared statement] S: ** before statement S is ever evaluated, after ** one or more calls to [sqlite3_reset()], or after any call ** to [sqlite3_step()] regardless of whether or not the statement has ** completed execution. ** ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. ** ** The application must finalize every [prepared statement] in order to avoid ** resource leaks. It is a grievous error for the application to try to use ** a prepared statement after it has been finalized. Any use of a prepared ** statement after it has been finalized can result in undefined and ** undesirable behavior such as segfaults and heap corruption. */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object ** METHOD: sqlite3_stmt ** ** The sqlite3_reset() function is called to reset a [prepared statement] ** object back to its initial state, ready to be re-executed. ** ^Any SQL statement variables that had values bound to them using ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. ** Use [sqlite3_clear_bindings()] to reset the bindings. ** ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S ** back to the beginning of its program. ** ** ^If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], ** or if [sqlite3_step(S)] has never before been called on S, ** then [sqlite3_reset(S)] returns [SQLITE_OK]. ** ** ^If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S indicated an error, then ** [sqlite3_reset(S)] returns an appropriate [error code]. ** ** ^The [sqlite3_reset(S)] interface does not change the values ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions ** KEYWORDS: {function creation routines} ** KEYWORDS: {application-defined SQL function} ** KEYWORDS: {application-defined SQL functions} ** METHOD: sqlite3 ** ** ^These functions (collectively known as "function creation routines") ** are used to add SQL functions or aggregates or to redefine the behavior ** of existing SQL functions or aggregates. The only differences between ** these routines are the text encoding expected for ** the second parameter (the name of the function being created) ** and the presence or absence of a destructor callback for ** the application data pointer. ** ** ^The first parameter is the [database connection] to which the SQL ** function is to be added. ^If an application uses more than one database ** connection then application-defined SQL functions must be added ** to each database connection separately. ** ** ^The second parameter is the name of the SQL function to be created or ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 ** representation, exclusive of the zero-terminator. ^Note that the name ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. ** ^Any attempt to create a function with a longer name ** will result in [SQLITE_MISUSE] being returned. ** ** ^The third parameter (nArg) ** is the number of arguments that the SQL function or ** aggregate takes. ^If this parameter is -1, then the SQL function or ** aggregate may take any number of arguments between 0 and the limit ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third ** parameter is less than -1 or greater than 127 then the behavior is ** undefined. ** ** ^The fourth parameter, eTextRep, specifies what ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. The application should set this parameter to ** [SQLITE_UTF16LE] if the function implementation invokes ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the ** implementation invokes [sqlite3_value_text16be()] on an input, or ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] ** otherwise. ^The same SQL function may be registered multiple times using ** different preferred text encodings, with different implementations for ** each encoding. ** ^When multiple implementations of the same function are available, SQLite ** will pick the one that involves the least amount of data conversion. ** ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC] ** to signal that the function will always return the same result given ** the same inputs within a single SQL statement. Most SQL functions are ** deterministic. The built-in [random()] SQL function is an example of a ** function that is not deterministic. The SQLite query planner is able to ** perform additional optimizations on deterministic functions, so use ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. ** ** ^(The fifth parameter is an arbitrary pointer. The implementation of the ** function can gain access to this pointer using [sqlite3_user_data()].)^ ** ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are ** pointers to C-language functions that implement the SQL function or ** aggregate. ^A scalar SQL function requires an implementation of the xFunc ** callback only; NULL pointers must be passed as the xStep and xFinal ** parameters. ^An aggregate SQL function requires an implementation of xStep ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing ** SQL function or aggregate, pass NULL pointers for all three function ** callbacks. ** ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, ** then it is destructor for the application data pointer. ** The destructor is invoked when the function is deleted, either by being ** overloaded or when the database connection closes.)^ ** ^The destructor is also invoked if the call to ** sqlite3_create_function_v2() fails. ** ^When the destructor callback of the tenth parameter is invoked, it ** is passed a single argument which is a copy of the application data ** pointer which was the fifth parameter to sqlite3_create_function_v2(). ** ** ^It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of ** arguments or differing preferred text encodings. ^SQLite will use ** the implementation that most closely matches the way in which the ** SQL function is used. ^A function implementation with a non-negative ** nArg parameter is a better match than a function implementation with ** a negative nArg. ^A function where the preferred text encoding ** matches the database encoding is a better ** match than a function where the encoding is different. ** ^A function where the encoding difference is between UTF16le and UTF16be ** is a closer match than a function where the encoding difference is ** between UTF8 and UTF16. ** ** ^Built-in functions may be overloaded by new application-defined functions. ** ** ^An application-defined function is permitted to call other ** SQLite interfaces. However, such calls must not ** close the database connection nor finalize or reset the prepared ** statement in which the function is running. */ SQLITE_API int sqlite3_create_function( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function16( sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function_v2( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*) ); /* ** CAPI3REF: Text Encodings ** ** These constant define integer codes that represent the various ** text encodings supported by SQLite. */ #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ /* ** CAPI3REF: Function Flags ** ** These constants may be ORed together with the ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument ** to [sqlite3_create_function()], [sqlite3_create_function16()], or ** [sqlite3_create_function_v2()]. */ #define SQLITE_DETERMINISTIC 0x800 /* ** CAPI3REF: Deprecated Functions ** DEPRECATED ** ** These functions are [deprecated]. In order to maintain ** backwards compatibility with older code, these functions continue ** to be supported. However, new applications should avoid ** the use of these functions. To encourage programmers to avoid ** these functions, we will not explain what they do. */ #ifndef SQLITE_OMIT_DEPRECATED SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), void*,sqlite3_int64); #endif /* ** CAPI3REF: Obtaining SQL Values ** METHOD: sqlite3_value ** ** The C-language implementation of SQL functions and aggregates uses ** this set of interface routines to access the parameter values on ** the function or aggregate. ** ** The xFunc (for scalar functions) or xStep (for aggregates) parameters ** to [sqlite3_create_function()] and [sqlite3_create_function16()] ** define callbacks that implement the SQL functions and aggregates. ** The 3rd parameter to these callbacks is an array of pointers to ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** ** These routines work only with [protected sqlite3_value] objects. ** Any attempt to use these routines on an [unprotected sqlite3_value] ** object results in undefined behavior. ** ** ^These routines work just like the corresponding [column access functions] ** except that these routines take a single [protected sqlite3_value] object ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. ** ** ^The sqlite3_value_text16() interface extracts a UTF-16 string ** in the native byte-order of the host machine. ^The ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces ** extract UTF-16 strings as big-endian and little-endian respectively. ** ** ^(The sqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other ** words, if the value is a string that looks like a number) ** then the conversion is performed. Otherwise no conversion occurs. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ ** ** Please pay particular attention to the fact that the pointer returned ** from [sqlite3_value_blob()], [sqlite3_value_text()], or ** [sqlite3_value_text16()] can be invalidated by a subsequent call to ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], ** or [sqlite3_value_text16()]. ** ** These routines must be called from the same thread as ** the SQL function that supplied the [sqlite3_value*] parameters. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API int sqlite3_value_bytes(sqlite3_value*); SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); SQLITE_API double sqlite3_value_double(sqlite3_value*); SQLITE_API int sqlite3_value_int(sqlite3_value*); SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); SQLITE_API int sqlite3_value_type(sqlite3_value*); SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); /* ** CAPI3REF: Finding The Subtype Of SQL Values ** METHOD: sqlite3_value ** ** The sqlite3_value_subtype(V) function returns the subtype for ** an [application-defined SQL function] argument V. The subtype ** information can be used to pass a limited amount of context from ** one SQL function to another. Use the [sqlite3_result_subtype()] ** routine to set the subtype for the return value of an SQL function. ** ** SQLite makes no use of subtype itself. It merely passes the subtype ** from the result of one [application-defined SQL function] into the ** input of another. */ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); /* ** CAPI3REF: Copy And Free SQL Values ** METHOD: sqlite3_value ** ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned ** is a [protected sqlite3_value] object even if the input is not. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a ** memory allocation fails. ** ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer ** then sqlite3_value_free(V) is a harmless no-op. */ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); SQLITE_API void sqlite3_value_free(sqlite3_value*); /* ** CAPI3REF: Obtain Aggregate Function Context ** METHOD: sqlite3_context ** ** Implementations of aggregate SQL functions use this ** routine to allocate memory for storing their state. ** ** ^The first time the sqlite3_aggregate_context(C,N) routine is called ** for a particular aggregate function, SQLite ** allocates N of memory, zeroes out that memory, and returns a pointer ** to the new memory. ^On second and subsequent calls to ** sqlite3_aggregate_context() for the same aggregate function instance, ** the same buffer is returned. Sqlite3_aggregate_context() is normally ** called once for each invocation of the xStep callback and then one ** last time when the xFinal callback is invoked. ^(When no rows match ** an aggregate query, the xStep() callback of the aggregate function ** implementation is never called and xFinal() is called exactly once. ** In those cases, sqlite3_aggregate_context() might be called for the ** first time from within xFinal().)^ ** ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer ** when first called if N is less than or equal to zero or if a memory ** allocate error occurs. ** ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is ** determined by the N parameter on first successful call. Changing the ** value of N in subsequent call to sqlite3_aggregate_context() within ** the same aggregate function instance will not resize the memory ** allocation.)^ Within the xFinal callback, it is customary to set ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no ** pointless memory allocations occur. ** ** ^SQLite automatically frees the memory allocated by ** sqlite3_aggregate_context() when the aggregate query concludes. ** ** The first parameter must be a copy of the ** [sqlite3_context | SQL function context] that is the first parameter ** to the xStep or xFinal callback routine that implements the aggregate ** function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions ** METHOD: sqlite3_context ** ** ^The sqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. ** ** This routine must be called from the same thread in which ** the application-defined function is running. */ SQLITE_API void *sqlite3_user_data(sqlite3_context*); /* ** CAPI3REF: Database Connection For Functions ** METHOD: sqlite3_context ** ** ^The sqlite3_context_db_handle() interface returns a copy of ** the pointer to the [database connection] (the 1st parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. */ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); /* ** CAPI3REF: Function Auxiliary Data ** METHOD: sqlite3_context ** ** These functions may be used by (non-aggregate) SQL functions to ** associate metadata with argument values. If the same value is passed to ** multiple invocations of the same SQL function during query execution, under ** some circumstances the associated metadata may be preserved. An example ** of where this might be useful is in a regular-expression matching ** function. The compiled version of the regular expression can be stored as ** metadata associated with the pattern string. ** Then as long as the pattern string remains the same, ** the compiled regular expression can be reused on multiple ** invocations of the same function. ** ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata ** associated by the sqlite3_set_auxdata() function with the Nth argument ** value to the application-defined function. ^If there is no metadata ** associated with the function argument, this sqlite3_get_auxdata() interface ** returns a NULL pointer. ** ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th ** argument of the application-defined function. ^Subsequent ** calls to sqlite3_get_auxdata(C,N) return P from the most recent ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or ** NULL if the metadata has been discarded. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, ** SQLite will invoke the destructor function X with parameter P exactly ** once, when the metadata is discarded. ** SQLite is free to discard the metadata at any time, including: <ul> ** <li> ^(when the corresponding function parameter changes)^, or ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the ** SQL statement)^, or ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same ** parameter)^, or ** <li> ^(during the original sqlite3_set_auxdata() call when a memory ** allocation error occurs.)^ </ul> ** ** Note the last bullet in particular. The destructor X in ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() ** should be called near the end of the function implementation and the ** function implementation should not make any use of P after ** sqlite3_set_auxdata() has been called. ** ** ^(In practice, metadata is preserved between function calls for ** function parameters that are compile-time constants, including literal ** values and [parameters] and expressions composed from the same.)^ ** ** These routines must be called from the same thread in which ** the SQL function is running. */ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior ** ** These are special values for the destructor that is passed in as the ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant ** and will never change. It does not need to be destroyed. ^The ** SQLITE_TRANSIENT value means that the content will likely change in ** the near future and that SQLite should make its own private copy of ** the content before returning. ** ** The typedef is necessary to work around problems in certain ** C++ compilers. */ typedef void (*sqlite3_destructor_type)(void*); #define SQLITE_STATIC ((sqlite3_destructor_type)0) #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) /* ** CAPI3REF: Setting The Result Of An SQL Function ** METHOD: sqlite3_context ** ** These routines are used by the xFunc or xFinal callbacks that ** implement SQL functions and aggregates. See ** [sqlite3_create_function()] and [sqlite3_create_function16()] ** for additional information. ** ** These functions work very much like the [parameter binding] family of ** functions used to bind values to host parameters in prepared statements. ** Refer to the [SQL parameter] documentation for additional information. ** ** ^The sqlite3_result_blob() interface sets the result from ** an application-defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the ** third parameter. ** ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) ** interfaces set the result of the application-defined function to be ** a BLOB containing all zero bytes and N bytes in size. ** ** ^The sqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified ** by its 2nd argument. ** ** ^The sqlite3_result_error() and sqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. ** ^SQLite uses the string pointed to by the ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() ** as the text of an error message. ^SQLite interprets the error ** message string from sqlite3_result_error() as UTF-8. ^SQLite ** interprets the string from sqlite3_result_error16() as UTF-16 in native ** byte order. ^If the third parameter to sqlite3_result_error() ** or sqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. ** ^If the third parameter to sqlite3_result_error() or ** sqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. ** ^The sqlite3_result_error() and sqlite3_result_error16() ** routines make a private copy of the error message text before ** they return. Hence, the calling function can deallocate or ** modify the text after they return without harm. ** ^The sqlite3_result_error_code() function changes the error code ** returned by SQLite as a result of an error in a function. ^By default, ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. ** ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an ** error indicating that a string or BLOB is too long to represent. ** ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an ** error indicating that a memory allocation failed. ** ** ^The sqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. ** ^The sqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** ** ^The sqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** ** ^The sqlite3_result_text(), sqlite3_result_text16(), ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. ** ^The sqlite3_result_text64() interface sets the return value of an ** application-defined function to be a text string in an encoding ** specified by the fifth (and last) parameter, which must be one ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. ** ^SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces ** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. If the 3rd parameter is non-negative, then it ** must be the byte offset into the string where the NUL terminator would ** appear if the string where NUL terminated. If any NUL characters occur ** in the string at a byte offset that is less than the value of the 3rd ** parameter, then the resulting string will contain embedded NULs and the ** result of expressions operating on strings with embedded NULs is undefined. ** ^If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that ** function as the destructor on the text or BLOB result when it has ** finished using that result. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite ** assumes that the text or BLOB result is in constant space and does not ** copy the content of the parameter nor call a destructor on the content ** when it has finished using that result. ** ^If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** ** ^The sqlite3_result_value() interface sets the result of ** the application-defined function to be a copy of the ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] ** so that the [sqlite3_value] specified in the parameter may change or ** be deallocated after sqlite3_result_value() returns without harm. ** ^A [protected sqlite3_value] object may always be used where an ** [unprotected sqlite3_value] object is required, so either ** kind of [sqlite3_value] object can be used with this interface. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that received ** the [sqlite3_context] pointer, the results are undefined. */ SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, sqlite3_uint64,void(*)(void*)); SQLITE_API void sqlite3_result_double(sqlite3_context*, double); SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); SQLITE_API void sqlite3_result_int(sqlite3_context*, int); SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); SQLITE_API void sqlite3_result_null(sqlite3_context*); SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, void(*)(void*), unsigned char encoding); SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); /* ** CAPI3REF: Setting The Subtype Of An SQL Function ** METHOD: sqlite3_context ** ** The sqlite3_result_subtype(C,T) function causes the subtype of ** the result from the [application-defined SQL function] with ** [sqlite3_context] C to be the value T. Only the lower 8 bits ** of the subtype T are preserved in current versions of SQLite; ** higher order bits are discarded. ** The number of subtype bytes preserved by SQLite might increase ** in future releases of SQLite. */ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); /* ** CAPI3REF: Define New Collating Sequences ** METHOD: sqlite3 ** ** ^These functions add, remove, or modify a [collation] associated ** with the [database connection] specified as the first argument. ** ** ^The name of the collation is a UTF-8 string ** for sqlite3_create_collation() and sqlite3_create_collation_v2() ** and a UTF-16 string in native byte order for sqlite3_create_collation16(). ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are ** considered to be the same name. ** ** ^(The third argument (eTextRep) must be one of the constants: ** <ul> ** <li> [SQLITE_UTF8], ** <li> [SQLITE_UTF16LE], ** <li> [SQLITE_UTF16BE], ** <li> [SQLITE_UTF16], or ** <li> [SQLITE_UTF16_ALIGNED]. ** </ul>)^ ** ^The eTextRep argument determines the encoding of strings passed ** to the collating function callback, xCallback. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep ** force strings to be UTF16 with native byte order. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin ** on an even byte address. ** ** ^The fourth argument, pArg, is an application data pointer that is passed ** through as the first argument to the collating function callback. ** ** ^The fifth argument, xCallback, is a pointer to the collating function. ** ^Multiple collating functions can be registered using the same name but ** with different eTextRep parameters and SQLite will use whichever ** function requires the least amount of data transformation. ** ^If the xCallback argument is NULL then the collating function is ** deleted. ^When all collating functions having the same name are deleted, ** that collation is no longer usable. ** ** ^The collating function callback is invoked with a copy of the pArg ** application data pointer and with two strings in the encoding specified ** by the eTextRep argument. The collating function must return an ** integer that is negative, zero, or positive ** if the first string is less than, equal to, or greater than the second, ** respectively. A collating function must always return the same answer ** given the same inputs. If two or more collating functions are registered ** to the same collation name (using different eTextRep values) then all ** must give an equivalent answer when invoked with equivalent strings. ** The collating function must obey the following properties for all ** strings A, B, and C: ** ** <ol> ** <li> If A==B then B==A. ** <li> If A==B and B==C then A==C. ** <li> If A&lt;B THEN B&gt;A. ** <li> If A&lt;B and B&lt;C then A&lt;C. ** </ol> ** ** If a collating function fails any of the above constraints and that ** collating function is registered and used, then the behavior of SQLite ** is undefined. ** ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() ** with the addition that the xDestroy callback is invoked on pArg when ** the collating function is deleted. ** ^Collating functions are deleted when they are overridden by later ** calls to the collation creation functions or when the ** [database connection] is closed using [sqlite3_close()]. ** ** ^The xDestroy callback is <u>not</u> called if the ** sqlite3_create_collation_v2() function fails. Applications that invoke ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should ** check the return code and dispose of the application data pointer ** themselves rather than expecting SQLite to deal with it for them. ** This is different from every other SQLite interface. The inconsistency ** is unfortunate but cannot be changed without breaking backwards ** compatibility. ** ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. */ SQLITE_API int sqlite3_create_collation( sqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); SQLITE_API int sqlite3_create_collation_v2( sqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDestroy)(void*) ); SQLITE_API int sqlite3_create_collation16( sqlite3*, const void *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); /* ** CAPI3REF: Collation Needed Callbacks ** METHOD: sqlite3 ** ** ^To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the ** [database connection] to be invoked whenever an undefined collation ** sequence is required. ** ** ^If the function is registered using the sqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, ** the names are passed as UTF-16 in machine native byte order. ** ^A call to either function replaces the existing collation-needed callback. ** ** ^(When the callback is invoked, the first argument passed is a copy ** of the second argument to sqlite3_collation_needed() or ** sqlite3_collation_needed16(). The second argument is the database ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation ** sequence function required. The fourth parameter is the name of the ** required collation sequence.)^ ** ** The callback function should register the desired collation using ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or ** [sqlite3_create_collation_v2()]. */ SQLITE_API int sqlite3_collation_needed( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const char*) ); SQLITE_API int sqlite3_collation_needed16( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const void*) ); #ifdef SQLITE_HAS_CODEC /* ** Specify the key for an encrypted database. This routine should be ** called right after sqlite3_open(). ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_key( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The key */ ); SQLITE_API int sqlite3_key_v2( sqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The key */ ); /* ** Change the key on an open database. If the current database is not ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the ** database is decrypted. ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_rekey( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); SQLITE_API int sqlite3_rekey_v2( sqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The new key */ ); /* ** Specify the activation key for a SEE database. Unless ** activated, none of the SEE routines will work. */ SQLITE_API void sqlite3_activate_see( const char *zPassPhrase /* Activation phrase */ ); #endif #ifdef SQLITE_ENABLE_CEROD /* ** Specify the activation key for a CEROD database. Unless ** activated, none of the CEROD routines will work. */ SQLITE_API void sqlite3_activate_cerod( const char *zPassPhrase /* Activation phrase */ ); #endif /* ** CAPI3REF: Suspend Execution For A Short Time ** ** The sqlite3_sleep() function causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** ** If the operating system does not support sleep requests with ** millisecond time resolution, then the time will be rounded up to ** the nearest second. The number of milliseconds of sleep actually ** requested from the operating system is returned. ** ** ^SQLite implements this interface by calling the xSleep() ** method of the default [sqlite3_vfs] object. If the xSleep() method ** of the default VFS is not implemented correctly, or not implemented at ** all, then the behavior of sqlite3_sleep() may deviate from the description ** in the previous paragraphs. */ SQLITE_API int sqlite3_sleep(int); /* ** CAPI3REF: Name Of The Folder Holding Temporary Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all temporary files ** created by SQLite when using a built-in [sqlite3_vfs | VFS] ** will be placed in that directory.)^ ^If this variable ** is a NULL pointer, then SQLite performs a search for an appropriate ** temporary file directory. ** ** Applications are strongly discouraged from using this global variable. ** It is required to set a temporary folder on Windows Runtime (WinRT). ** But for all other platforms, it is highly recommended that applications ** neither read nor write this variable. This global variable is a relic ** that exists for backwards compatibility of legacy applications and should ** be avoided in new projects. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** ^The [temp_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, ** the [temp_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [temp_store_directory pragma] should be avoided. ** Except when requested by the [temp_store_directory pragma], SQLite ** does not free the memory that sqlite3_temp_directory points to. If ** the application wants that memory to be freed, it must do ** so itself, taking care to only do so after all [database connection] ** objects have been destroyed. ** ** <b>Note to Windows Runtime users:</b> The temporary directory must be set ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various ** features that require the use of temporary files may fail. Here is an ** example of how to do this using C++ with the Windows Runtime: ** ** <blockquote><pre> ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current-> ** &nbsp; TemporaryFolder->Path->Data(); ** char zPathBuf&#91;MAX_PATH + 1&#93;; ** memset(zPathBuf, 0, sizeof(zPathBuf)); ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf), ** &nbsp; NULL, NULL); ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf); ** </pre></blockquote> */ SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; /* ** CAPI3REF: Name Of The Folder Holding Database Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all database files ** specified with a relative pathname and created or accessed by ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed ** to be relative to that directory.)^ ^If this variable is a NULL ** pointer, then SQLite assumes that all database files specified ** with a relative pathname are relative to the current directory ** for the process. Only the windows VFS makes use of this global ** variable; it is ignored by the unix VFS. ** ** Changing the value of this variable while a database connection is ** open can result in a corrupt database. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** ^The [data_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, ** the [data_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [data_store_directory pragma] should be avoided. */ SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory; /* ** CAPI3REF: Test For Auto-Commit Mode ** KEYWORDS: {autocommit mode} ** METHOD: sqlite3 ** ** ^The sqlite3_get_autocommit() interface returns non-zero or ** zero if the given database connection is or is not in autocommit mode, ** respectively. ^Autocommit mode is on by default. ** ^Autocommit mode is disabled by a [BEGIN] statement. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. ** ** If certain kinds of errors occur on a statement within a multi-statement ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the ** transaction might be rolled back automatically. The only way to ** find out whether SQLite automatically rolled back the transaction after ** an error is to use this function. ** ** If another thread changes the autocommit status of the database ** connection while this routine is running, then the return value ** is undefined. */ SQLITE_API int sqlite3_get_autocommit(sqlite3*); /* ** CAPI3REF: Find The Database Handle Of A Prepared Statement ** METHOD: sqlite3_stmt ** ** ^The sqlite3_db_handle interface returns the [database connection] handle ** to which a [prepared statement] belongs. ^The [database connection] ** returned by sqlite3_db_handle is the same [database connection] ** that was the first argument ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to ** create the statement in the first place. */ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); /* ** CAPI3REF: Return The Filename For A Database Connection ** METHOD: sqlite3 ** ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename ** associated with database N of connection D. ^The main database file ** has the name "main". If there is no attached database N on the database ** connection D, or if database N is a temporary or in-memory database, then ** a NULL pointer is returned. ** ** ^The filename returned by this function is the output of the ** xFullPathname method of the [VFS]. ^In other words, the filename ** will be an absolute pathname, even if the filename used ** to open the database originally was a URI or relative pathname. */ SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); /* ** CAPI3REF: Determine if a database is read-only ** METHOD: sqlite3 ** ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N ** of connection D is read-only, 0 if it is read/write, or -1 if N is not ** the name of a database on connection D. */ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); /* ** CAPI3REF: Find the next prepared statement ** METHOD: sqlite3 ** ** ^This interface returns a pointer to the next [prepared statement] after ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL ** then this interface returns a pointer to the first prepared statement ** associated with the database connection pDb. ^If no prepared statement ** satisfies the conditions of this routine, it returns NULL. ** ** The [database connection] pointer D in a call to ** [sqlite3_next_stmt(D,S)] must refer to an open database ** connection and in particular must not be a NULL pointer. */ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is [COMMIT | committed]. ** ^Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. ** ^The sqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. ** ^Any callback set by a previous call to sqlite3_rollback_hook() ** for the same database connection is overridden. ** ^The pArg argument is passed through to the callback. ** ^If the callback on a commit hook function returns non-zero, ** then the commit is converted into a rollback. ** ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions ** return the P argument from the previous call of the same function ** on the same [database connection] D, or NULL for ** the first call for each function on D. ** ** The commit and rollback hook callbacks are not reentrant. ** The callback implementation must not do anything that will modify ** the database connection that invoked the callback. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the commit ** or rollback hook in the first place. ** Note that running any other SQL statements, including SELECT statements, ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify ** the database connections for the meaning of "modify" in this paragraph. ** ** ^Registering a NULL function disables the callback. ** ** ^When the commit hook callback routine returns zero, the [COMMIT] ** operation is allowed to continue normally. ^If the commit hook ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. ** ^The rollback hook is invoked on a rollback that results from a commit ** hook returning non-zero, just as it would be with any other rollback. ** ** ^For the purposes of this API, a transaction is said to have been ** rolled back if an explicit "ROLLBACK" statement is executed, or ** an error or constraint causes an implicit rollback to occur. ** ^The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. ** ** See also the [sqlite3_update_hook()] interface. */ SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument ** to be invoked whenever a row is updated, inserted or deleted in ** a [rowid table]. ** ^Any callback set by a previous call to this function ** for the same database connection is overridden. ** ** ^The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted in a rowid table. ** ^The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], ** or [SQLITE_UPDATE], depending on the operation that caused the callback ** to be invoked. ** ^The third and fourth arguments to the callback contain pointers to the ** database and table name containing the affected row. ** ^The final callback parameter is the [rowid] of the row. ** ^In the case of an update, this is the [rowid] after the update takes place. ** ** ^(The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence).)^ ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. ** ** ^In the current implementation, the update hook ** is not invoked when conflicting rows are deleted because of an ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook ** invoked when rows are deleted using the [truncate optimization]. ** The exceptions defined in this paragraph might change in a future ** release of SQLite. ** ** The update hook implementation must not do anything that will modify ** the database connection that invoked the update hook. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the update hook. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** ^The sqlite3_update_hook(D,C,P) function ** returns the P argument from the previous call ** on the same [database connection] D, or NULL for ** the first call on D. ** ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], ** and [sqlite3_preupdate_hook()] interfaces. */ SQLITE_API void *sqlite3_update_hook( sqlite3*, void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); /* ** CAPI3REF: Enable Or Disable Shared Pager Cache ** ** ^(This routine enables or disables the sharing of the database cache ** and schema data structures between [database connection | connections] ** to the same database. Sharing is enabled if the argument is true ** and disabled if the argument is false.)^ ** ** ^Cache sharing is enabled and disabled for an entire process. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). ** In prior versions of SQLite, ** sharing was enabled or disabled for each thread separately. ** ** ^(The cache sharing mode set by this interface effects all subsequent ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. ** Existing database connections continue use the sharing mode ** that was in effect at the time they were opened.)^ ** ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled ** successfully. An [error code] is returned otherwise.)^ ** ** ^Shared cache is disabled by default. But this might change in ** future releases of SQLite. Applications that care about shared ** cache setting should set it explicitly. ** ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 ** and will always return SQLITE_MISUSE. On those systems, ** shared cache mode should be enabled per-database connection via ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. ** ** This interface is threadsafe on processors where writing a ** 32-bit integer is atomic. ** ** See Also: [SQLite Shared-Cache Mode] */ SQLITE_API int sqlite3_enable_shared_cache(int); /* ** CAPI3REF: Attempt To Free Heap Memory ** ** ^The sqlite3_release_memory() interface attempts to free N bytes ** of heap memory by deallocating non-essential memory allocations ** held by the database library. Memory used to cache database ** pages to improve performance is an example of non-essential memory. ** ^sqlite3_release_memory() returns the number of bytes actually freed, ** which might be more or less than the amount requested. ** ^The sqlite3_release_memory() routine is a no-op returning zero ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** ** See also: [sqlite3_db_release_memory()] */ SQLITE_API int sqlite3_release_memory(int); /* ** CAPI3REF: Free Memory Used By A Database Connection ** METHOD: sqlite3 ** ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap ** memory as possible from database connection D. Unlike the ** [sqlite3_release_memory()] interface, this interface is in effect even ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is ** omitted. ** ** See also: [sqlite3_release_memory()] */ SQLITE_API int sqlite3_db_release_memory(sqlite3*); /* ** CAPI3REF: Impose A Limit On Heap Size ** ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the ** soft limit on the amount of heap memory that may be allocated by SQLite. ** ^SQLite strives to keep heap memory utilization below the soft heap ** limit by reducing the number of pages held in the page cache ** as heap memory usages approaches the limit. ** ^The soft heap limit is "soft" because even though SQLite strives to stay ** below the limit, it will exceed the limit rather than generate ** an [SQLITE_NOMEM] error. In other words, the soft heap limit ** is advisory only. ** ** ^The return value from sqlite3_soft_heap_limit64() is the size of ** the soft heap limit prior to the call, or negative in the case of an ** error. ^If the argument N is negative ** then no change is made to the soft heap limit. Hence, the current ** size of the soft heap limit can be determined by invoking ** sqlite3_soft_heap_limit64() with a negative argument. ** ** ^If the argument N is zero then the soft heap limit is disabled. ** ** ^(The soft heap limit is not enforced in the current implementation ** if one or more of following conditions are true: ** ** <ul> ** <li> The soft heap limit is set to zero. ** <li> Memory accounting is disabled using a combination of the ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. ** <li> An alternative page cache implementation is specified using ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). ** <li> The page cache allocates from its own memory pool supplied ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than ** from the heap. ** </ul>)^ ** ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), ** the soft heap limit is enforced ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], ** the soft heap limit is enforced on every memory allocation. Without ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced ** when memory is allocated by the page cache. Testing suggests that because ** the page cache is the predominate memory user in SQLite, most ** applications will achieve adequate soft heap limit enforcement without ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** ** The circumstances under which SQLite will enforce the soft heap limit may ** changes in future releases of SQLite. */ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); /* ** CAPI3REF: Deprecated Soft Heap Limit Interface ** DEPRECATED ** ** This is a deprecated version of the [sqlite3_soft_heap_limit64()] ** interface. This routine is provided for historical compatibility ** only. All new applications should use the ** [sqlite3_soft_heap_limit64()] interface rather than this one. */ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); /* ** CAPI3REF: Extract Metadata About A Column Of A Table ** METHOD: sqlite3 ** ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns ** information about column C of table T in database D ** on [database connection] X.)^ ^The sqlite3_table_column_metadata() ** interface returns SQLITE_OK and fills in the non-NULL pointers in ** the final five arguments with appropriate values if the specified ** column exists. ^The sqlite3_table_column_metadata() interface returns ** SQLITE_ERROR and if the specified column does not exist. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a ** NULL pointer, then this routine simply checks for the existence of the ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it ** does not. ** ** ^The column is identified by the second, third and fourth parameters to ** this function. ^(The second parameter is either the name of the database ** (i.e. "main", "temp", or an attached database) containing the specified ** table or NULL.)^ ^If it is NULL, then all attached databases are searched ** for the table using the same algorithm used by the database engine to ** resolve unqualified table references. ** ** ^The third and fourth parameters to this function are the table and column ** name of the desired column, respectively. ** ** ^Metadata is returned by writing to the memory locations passed as the 5th ** and subsequent parameters to this function. ^Any of these arguments may be ** NULL, in which case the corresponding element of metadata is omitted. ** ** ^(<blockquote> ** <table border="1"> ** <tr><th> Parameter <th> Output<br>Type <th> Description ** ** <tr><td> 5th <td> const char* <td> Data type ** <tr><td> 6th <td> const char* <td> Name of default collation sequence ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT] ** </table> ** </blockquote>)^ ** ** ^The memory pointed to by the character pointers returned for the ** declaration type and collation sequence is valid until the next ** call to any SQLite API function. ** ** ^If the specified table is actually a view, an [error code] is returned. ** ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table ** is not a [WITHOUT ROWID] table and an ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output ** parameters are set for the explicitly declared column. ^(If there is no ** [INTEGER PRIMARY KEY] column, then the outputs ** for the [rowid] are set as follows: ** ** <pre> ** data type: "INTEGER" ** collation sequence: "BINARY" ** not null: 0 ** primary key: 1 ** auto increment: 0 ** </pre>)^ ** ** ^This function causes all database schemas to be read from disk and ** parsed, if that has not already been done, and returns an error if ** any errors are encountered while loading the schema. */ SQLITE_API int sqlite3_table_column_metadata( sqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ char const **pzDataType, /* OUTPUT: Declared data type */ char const **pzCollSeq, /* OUTPUT: Collation sequence name */ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ int *pAutoinc /* OUTPUT: True if column is auto-increment */ ); /* ** CAPI3REF: Load An Extension ** METHOD: sqlite3 ** ** ^This interface loads an SQLite extension library from the named file. ** ** ^The sqlite3_load_extension() interface attempts to load an ** [SQLite extension] library contained in the file zFile. If ** the file cannot be loaded directly, attempts are made to load ** with various operating-system specific extensions added. ** So for example, if "samplelib" cannot be loaded, then names like ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might ** be tried also. ** ** ^The entry point is zProc. ** ^(zProc may be 0, in which case SQLite will try to come up with an ** entry point name on its own. It first tries "sqlite3_extension_init". ** If that does not work, it constructs a name "sqlite3_X_init" where the ** X is consists of the lower-case equivalent of all ASCII alphabetic ** characters in the filename from the last "/" to the first following ** "." and omitting any initial "lib".)^ ** ^The sqlite3_load_extension() interface returns ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ^If an error occurs and pzErrMsg is not 0, then the ** [sqlite3_load_extension()] interface shall attempt to ** fill *pzErrMsg with error message text stored in memory ** obtained from [sqlite3_malloc()]. The calling function ** should free this memory by calling [sqlite3_free()]. ** ** ^Extension loading must be enabled using ** [sqlite3_enable_load_extension()] or ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) ** prior to calling this API, ** otherwise an error will be returned. ** ** <b>Security warning:</b> It is recommended that the ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this ** interface. The use of the [sqlite3_enable_load_extension()] interface ** should be avoided. This will keep the SQL function [load_extension()] ** disabled and prevent SQL injections from giving attackers ** access to extension loading capabilities. ** ** See also the [load_extension() SQL function]. */ SQLITE_API int sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Derived from zFile if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ); /* ** CAPI3REF: Enable Or Disable Extension Loading ** METHOD: sqlite3 ** ** ^So as not to open security holes in older applications that are ** unprepared to deal with [extension loading], and as a means of disabling ** [extension loading] while evaluating user-entered SQL, the following API ** is provided to turn the [sqlite3_load_extension()] mechanism on and off. ** ** ^Extension loading is off by default. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1 ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. ** ** ^This interface enables or disables both the C-API ** [sqlite3_load_extension()] and the SQL function [load_extension()]. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) ** to enable or disable only the C-API.)^ ** ** <b>Security warning:</b> It is recommended that extension loading ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method ** rather than this interface, so the [load_extension()] SQL function ** remains disabled. This will prevent SQL injections from giving attackers ** access to extension loading capabilities. */ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load Statically Linked Extensions ** ** ^This interface causes the xEntryPoint() function to be invoked for ** each new [database connection] that is created. The idea here is that ** xEntryPoint() is the entry point for a statically linked [SQLite extension] ** that is to be automatically loaded into all new database connections. ** ** ^(Even though the function prototype shows that xEntryPoint() takes ** no arguments and returns void, SQLite invokes xEntryPoint() with three ** arguments and expects an integer result as if the signature of the ** entry point where as follows: ** ** <blockquote><pre> ** &nbsp; int xEntryPoint( ** &nbsp; sqlite3 *db, ** &nbsp; const char **pzErrMsg, ** &nbsp; const struct sqlite3_api_routines *pThunk ** &nbsp; ); ** </pre></blockquote>)^ ** ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg ** point to an appropriate error message (obtained from [sqlite3_mprintf()]) ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg ** is NULL before calling the xEntryPoint(). ^SQLite will invoke ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. ** ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already ** on the list of automatic extensions is a harmless no-op. ^No entry point ** will be called more than once for each database connection that is opened. ** ** See also: [sqlite3_reset_auto_extension()] ** and [sqlite3_cancel_auto_extension()] */ SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Cancel Automatic Extension Loading ** ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the ** initialization routine X that was registered using a prior call to ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] ** routine returns 1 if initialization routine X was successfully ** unregistered and it returns 0 if X was not on the list of initialization ** routines. */ SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading ** ** ^This interface disables all automatic extensions previously ** registered using [sqlite3_auto_extension()]. */ SQLITE_API void sqlite3_reset_auto_extension(void); /* ** The interface to the virtual-table mechanism is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** Structures used by the virtual table interface */ typedef struct sqlite3_vtab sqlite3_vtab; typedef struct sqlite3_index_info sqlite3_index_info; typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; typedef struct sqlite3_module sqlite3_module; /* ** CAPI3REF: Virtual Table Object ** KEYWORDS: sqlite3_module {virtual table module} ** ** This structure, sometimes called a "virtual table module", ** defines the implementation of a [virtual tables]. ** This structure consists mostly of methods for the module. ** ** ^A virtual table module is created by filling in a persistent ** instance of this structure and passing a pointer to that instance ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. ** ^The registration remains valid until it is replaced by a different ** module or until the [database connection] closes. The content ** of this structure must not change while it is registered with ** any database connection. */ struct sqlite3_module { int iVersion; int (*xCreate)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xConnect)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); int (*xDisconnect)(sqlite3_vtab *pVTab); int (*xDestroy)(sqlite3_vtab *pVTab); int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); int (*xClose)(sqlite3_vtab_cursor*); int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, int argc, sqlite3_value **argv); int (*xNext)(sqlite3_vtab_cursor*); int (*xEof)(sqlite3_vtab_cursor*); int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); int (*xBegin)(sqlite3_vtab *pVTab); int (*xSync)(sqlite3_vtab *pVTab); int (*xCommit)(sqlite3_vtab *pVTab); int (*xRollback)(sqlite3_vtab *pVTab); int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), void **ppArg); int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); /* The methods above are in version 1 of the sqlite_module object. Those ** below are for version 2 and greater. */ int (*xSavepoint)(sqlite3_vtab *pVTab, int); int (*xRelease)(sqlite3_vtab *pVTab, int); int (*xRollbackTo)(sqlite3_vtab *pVTab, int); }; /* ** CAPI3REF: Virtual Table Indexing Information ** KEYWORDS: sqlite3_index_info ** ** The sqlite3_index_info structure and its substructures is used as part ** of the [virtual table] interface to ** pass information into and receive the reply from the [xBestIndex] ** method of a [virtual table module]. The fields under **Inputs** are the ** inputs to xBestIndex and are read-only. xBestIndex inserts its ** results into the **Outputs** fields. ** ** ^(The aConstraint[] array records WHERE clause constraints of the form: ** ** <blockquote>column OP expr</blockquote> ** ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is ** stored in aConstraint[].op using one of the ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ ** ^(The index of the column is stored in ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the ** expr on the right-hand side can be evaluated (and thus the constraint ** is usable) and false if it cannot.)^ ** ** ^The optimizer automatically inverts terms of the form "expr OP column" ** and makes other simplifications to the WHERE clause in an attempt to ** get as many WHERE clause terms into the form shown above as possible. ** ^The aConstraint[] array only reports WHERE clause terms that are ** relevant to the particular virtual table being queried. ** ** ^Information about the ORDER BY clause is stored in aOrderBy[]. ** ^Each term of aOrderBy records a column of the ORDER BY clause. ** ** The colUsed field indicates which columns of the virtual table may be ** required by the current scan. Virtual table columns are numbered from ** zero in the order in which they appear within the CREATE TABLE statement ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), ** the corresponding bit is set within the colUsed mask if the column may be ** required by SQLite. If the table has at least 64 columns and any column ** to the right of the first 63 is required, then bit 63 of colUsed is also ** set. In other words, column iCol may be required if the expression ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to ** non-zero. ** ** The [xBestIndex] method must fill aConstraintUsage[] with information ** about what parameters to pass to xFilter. ^If argvIndex>0 then ** the right-hand side of the corresponding aConstraint[] is evaluated ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit ** is true, then the constraint is assumed to be fully handled by the ** virtual table and is not checked again by SQLite.)^ ** ** ^The idxNum and idxPtr values are recorded and passed into the ** [xFilter] method. ** ^[sqlite3_free()] is used to free idxPtr if and only if ** needToFreeIdxPtr is true. ** ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in ** the correct order to satisfy the ORDER BY clause so that no separate ** sorting step is required. ** ** ^The estimatedCost value is an estimate of the cost of a particular ** strategy. A cost of N indicates that the cost of the strategy is similar ** to a linear scan of an SQLite table with N rows. A cost of log(N) ** indicates that the expense of the operation is similar to that of a ** binary search on a unique indexed field of an SQLite table with N rows. ** ** ^The estimatedRows value is an estimate of the number of rows that ** will be returned by the strategy. ** ** The xBestIndex method may optionally populate the idxFlags field with a ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag - ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite ** assumes that the strategy may visit at most one row. ** ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then ** SQLite also assumes that if a call to the xUpdate() method is made as ** part of the same statement to delete or update a virtual table row and the ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback ** any database changes. In other words, if the xUpdate() returns ** SQLITE_CONSTRAINT, the database contents must be exactly as they were ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by ** the xUpdate method are automatically rolled back by SQLite. ** ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). ** If a virtual table extension is ** used with an SQLite version earlier than 3.8.2, the results of attempting ** to read or write the estimatedRows field are undefined (but are likely ** to included crashing the application). The estimatedRows field should ** therefore only be used if [sqlite3_libversion_number()] returns a ** value greater than or equal to 3008002. Similarly, the idxFlags field ** was added for [version 3.9.0] ([dateof:3.9.0]). ** It may therefore only be used if ** sqlite3_libversion_number() returns a value greater than or equal to ** 3009000. */ struct sqlite3_index_info { /* Inputs */ int nConstraint; /* Number of entries in aConstraint */ struct sqlite3_index_constraint { int iColumn; /* Column constrained. -1 for ROWID */ unsigned char op; /* Constraint operator */ unsigned char usable; /* True if this constraint is usable */ int iTermOffset; /* Used internally - xBestIndex should ignore */ } *aConstraint; /* Table of WHERE clause constraints */ int nOrderBy; /* Number of terms in the ORDER BY clause */ struct sqlite3_index_orderby { int iColumn; /* Column number */ unsigned char desc; /* True for DESC. False for ASC. */ } *aOrderBy; /* The ORDER BY clause */ /* Outputs */ struct sqlite3_index_constraint_usage { int argvIndex; /* if >0, constraint is part of argv to xFilter */ unsigned char omit; /* Do not code a test for this constraint */ } *aConstraintUsage; int idxNum; /* Number used to identify the index */ char *idxStr; /* String, possibly obtained from sqlite3_malloc */ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ int orderByConsumed; /* True if output is already ordered */ double estimatedCost; /* Estimated cost of using this index */ /* Fields below are only available in SQLite 3.8.2 and later */ sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ /* Fields below are only available in SQLite 3.9.0 and later */ int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ /* Fields below are only available in SQLite 3.10.0 and later */ sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ }; /* ** CAPI3REF: Virtual Table Scan Flags */ #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */ /* ** CAPI3REF: Virtual Table Constraint Operator Codes ** ** These macros defined the allowed values for the ** [sqlite3_index_info].aConstraint[].op field. Each value represents ** an operator that is part of a constraint term in the wHERE clause of ** a query that uses a [virtual table]. */ #define SQLITE_INDEX_CONSTRAINT_EQ 2 #define SQLITE_INDEX_CONSTRAINT_GT 4 #define SQLITE_INDEX_CONSTRAINT_LE 8 #define SQLITE_INDEX_CONSTRAINT_LT 16 #define SQLITE_INDEX_CONSTRAINT_GE 32 #define SQLITE_INDEX_CONSTRAINT_MATCH 64 #define SQLITE_INDEX_CONSTRAINT_LIKE 65 #define SQLITE_INDEX_CONSTRAINT_GLOB 66 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67 /* ** CAPI3REF: Register A Virtual Table Implementation ** METHOD: sqlite3 ** ** ^These routines are used to register a new [virtual table module] name. ** ^Module names must be registered before ** creating a new [virtual table] using the module and before using a ** preexisting [virtual table] for the module. ** ** ^The module name is registered on the [database connection] specified ** by the first parameter. ^The name of the module is given by the ** second parameter. ^The third parameter is a pointer to ** the implementation of the [virtual table module]. ^The fourth ** parameter is an arbitrary client data pointer that is passed through ** into the [xCreate] and [xConnect] methods of the virtual table module ** when a new virtual table is be being created or reinitialized. ** ** ^The sqlite3_create_module_v2() interface has a fifth parameter which ** is a pointer to a destructor for the pClientData. ^SQLite will ** invoke the destructor function (if it is not NULL) when SQLite ** no longer needs the pClientData pointer. ^The destructor will also ** be invoked if the call to sqlite3_create_module_v2() fails. ** ^The sqlite3_create_module() ** interface is equivalent to sqlite3_create_module_v2() with a NULL ** destructor. */ SQLITE_API int sqlite3_create_module( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData /* Client data for xCreate/xConnect */ ); SQLITE_API int sqlite3_create_module_v2( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData, /* Client data for xCreate/xConnect */ void(*xDestroy)(void*) /* Module destructor function */ ); /* ** CAPI3REF: Virtual Table Instance Object ** KEYWORDS: sqlite3_vtab ** ** Every [virtual table module] implementation uses a subclass ** of this object to describe a particular instance ** of the [virtual table]. Each subclass will ** be tailored to the specific needs of the module implementation. ** The purpose of this superclass is to define certain fields that are ** common to all module implementations. ** ** ^Virtual tables methods can set an error message by assigning a ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should ** take care that any prior string is freed by a call to [sqlite3_free()] ** prior to assigning a new string to zErrMsg. ^After the error message ** is delivered up to the client application, the string will be automatically ** freed by sqlite3_free() and the zErrMsg field will be zeroed. */ struct sqlite3_vtab { const sqlite3_module *pModule; /* The module for this virtual table */ int nRef; /* Number of open cursors */ char *zErrMsg; /* Error message from sqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Virtual Table Cursor Object ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} ** ** Every [virtual table module] implementation uses a subclass of the ** following structure to describe cursors that point into the ** [virtual table] and are used ** to loop through the virtual table. Cursors are created using the ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed ** by the [sqlite3_module.xClose | xClose] method. Cursors are used ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods ** of the module. Each module implementation will define ** the content of a cursor structure to suit its own needs. ** ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. */ struct sqlite3_vtab_cursor { sqlite3_vtab *pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Declare The Schema Of A Virtual Table ** ** ^The [xCreate] and [xConnect] methods of a ** [virtual table module] call this interface ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table ** METHOD: sqlite3 ** ** ^(Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. ** But global versions of those functions ** must exist in order to be overloaded.)^ ** ** ^(This API makes sure a global version of a function with a particular ** name and number of parameters exists. If no such function exists ** before this API is called, a new function is created.)^ ^The implementation ** of the new function always causes an exception to be thrown. So ** the new function is not good for anything by itself. Its only ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up ** to a comment remarkably similar to this one) is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** CAPI3REF: A Handle To An Open BLOB ** KEYWORDS: {BLOB handle} {BLOB handles} ** ** An instance of this object represents an open BLOB on which ** [sqlite3_blob_open | incremental BLOB I/O] can be performed. ** ^Objects of this type are created by [sqlite3_blob_open()] ** and destroyed by [sqlite3_blob_close()]. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces ** can be used to read or write small subsections of the BLOB. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. */ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O ** METHOD: sqlite3 ** CONSTRUCTOR: sqlite3_blob ** ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; ** in other words, the same BLOB that would be selected by: ** ** <pre> ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow; ** </pre>)^ ** ** ^(Parameter zDb is not the filename that contains the database, but ** rather the symbolic name of the database. For attached databases, this is ** the name that appears after the AS keyword in the [ATTACH] statement. ** For the main database file, the database name is "main". For TEMP ** tables, the database name is "temp".)^ ** ** ^If the flags parameter is non-zero, then the BLOB is opened for read ** and write access. ^If the flags parameter is zero, the BLOB is opened for ** read-only access. ** ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored ** in *ppBlob. Otherwise an [error code] is returned and, unless the error ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided ** the API is not misused, it is always safe to call [sqlite3_blob_close()] ** on *ppBlob after this function it returns. ** ** This function fails with SQLITE_ERROR if any of the following are true: ** <ul> ** <li> ^(Database zDb does not exist)^, ** <li> ^(Table zTable does not exist within database zDb)^, ** <li> ^(Table zTable is a WITHOUT ROWID table)^, ** <li> ^(Column zColumn does not exist)^, ** <li> ^(Row iRow is not present in the table)^, ** <li> ^(The specified column of row iRow contains a value that is not ** a TEXT or BLOB value)^, ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE ** constraint and the blob is being opened for read/write access)^, ** <li> ^([foreign key constraints | Foreign key constraints] are enabled, ** column zColumn is part of a [child key] definition and the blob is ** being opened for read/write access)^. ** </ul> ** ** ^Unless it returns SQLITE_MISUSE, this function sets the ** [database connection] error code and message accessible via ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. ** ** A BLOB referenced by sqlite3_blob_open() may be read using the ** [sqlite3_blob_read()] interface and modified by using ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a ** different row of the same table using the [sqlite3_blob_reopen()] ** interface. However, the column, table, or database of a [BLOB handle] ** cannot be changed after the [BLOB handle] is opened. ** ** ^(If the row that a BLOB handle points to is modified by an ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects ** then the BLOB handle is marked as "expired". ** This is true if any column of the row is changed, even a column ** other than the one the BLOB handle is open on.)^ ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for ** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. ** ^(Changes written into a BLOB prior to the BLOB expiring are not ** rolled back by the expiration of the BLOB. Such changes will eventually ** commit if the transaction continues to completion.)^ ** ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of ** the opened blob. ^The size of a blob may not be changed by this ** interface. Use the [UPDATE] SQL command to change the size of a ** blob. ** ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function may be used to create a ** zero-filled blob to read or write using the incremental-blob interface. ** ** To avoid a resource leak, every open [BLOB handle] should eventually ** be released by a call to [sqlite3_blob_close()]. ** ** See also: [sqlite3_blob_close()], ** [sqlite3_blob_reopen()], [sqlite3_blob_read()], ** [sqlite3_blob_bytes()], [sqlite3_blob_write()]. */ SQLITE_API int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); /* ** CAPI3REF: Move a BLOB Handle to a New Row ** METHOD: sqlite3_blob ** ** ^This function is used to move an existing [BLOB handle] so that it points ** to a different row of the same database table. ^The new row is identified ** by the rowid value passed as the second argument. Only the row can be ** changed. ^The database, table and column on which the blob handle is open ** remain the same. Moving an existing [BLOB handle] to a new row is ** faster than closing the existing handle and opening a new one. ** ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - ** it must exist and there must be either a blob or text value stored in ** the nominated column.)^ ^If the new row is not present in the table, or if ** it does not contain a blob or text value, or if another error occurs, an ** SQLite error code is returned and the blob handle is considered aborted. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle ** always returns zero. ** ** ^This function sets the database handle error code and message. */ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); /* ** CAPI3REF: Close A BLOB Handle ** DESTRUCTOR: sqlite3_blob ** ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed ** unconditionally. Even if this routine returns an error code, the ** handle is still closed.)^ ** ** ^If the blob handle being closed was opened for read-write access, and if ** the database is in auto-commit mode and there are no other open read-write ** blob handles or active write statements, the current transaction is ** committed. ^If an error occurs while committing the transaction, an error ** code is returned and the transaction rolled back. ** ** Calling this function with an argument that is not a NULL pointer or an ** open blob handle results in undefined behaviour. ^Calling this routine ** with a null pointer (such as would be returned by a failed call to ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function ** is passed a valid open blob handle, the values returned by the ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB ** METHOD: sqlite3_blob ** ** ^Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. ^The ** incremental blob I/O routines can only read or overwriting existing ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); /* ** CAPI3REF: Read Data From A BLOB Incrementally ** METHOD: sqlite3_blob ** ** ^(This function is used to read data from an open [BLOB handle] into a ** caller-supplied buffer. N bytes of data are copied into buffer Z ** from the open BLOB, starting at offset iOffset.)^ ** ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is ** less than zero, [SQLITE_ERROR] is returned and no data is read. ** ^The size of the blob (and hence the maximum value of N+iOffset) ** can be determined using the [sqlite3_blob_bytes()] interface. ** ** ^An attempt to read from an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ** ** ^(On success, sqlite3_blob_read() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_write()]. */ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally ** METHOD: sqlite3_blob ** ** ^(This function is used to write data into an open [BLOB handle] from a ** caller-supplied buffer. N bytes of data are copied from the buffer Z ** into the open BLOB, starting at offset iOffset.)^ ** ** ^(On success, sqlite3_blob_write() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ^Unless SQLITE_MISUSE is returned, this function sets the ** [database connection] error code and message accessible via ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. ** ** ^If the [BLOB handle] passed as the first argument was not opened for ** writing (the flags parameter to [sqlite3_blob_open()] was zero), ** this function returns [SQLITE_READONLY]. ** ** This function may only modify the contents of the BLOB; it is ** not possible to increase the size of a BLOB using this API. ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is written. The size of the ** BLOB (and hence the maximum value of N+iOffset) can be determined ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less ** than zero [SQLITE_ERROR] is returned and no data is written. ** ** ^An attempt to write to an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred ** before the [BLOB handle] expired are not rolled back by the ** expiration of the handle, though of course those changes might ** have been overwritten by the statement that expired the BLOB handle ** or by other independent statements. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_read()]. */ SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); /* ** CAPI3REF: Virtual File System Objects ** ** A virtual filesystem (VFS) is an [sqlite3_vfs] object ** that SQLite uses to interact ** with the underlying operating system. Most SQLite builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. ** ^Names are case sensitive. ** ^Names are zero-terminated UTF-8 strings. ** ^If there is no match, a NULL pointer is returned. ** ^If zVfsName is NULL then the default VFS is returned. ** ** ^New VFSes are registered with sqlite3_vfs_register(). ** ^Each new VFS becomes the default VFS if the makeDflt flag is set. ** ^The same VFS can be registered multiple times without injury. ** ^To make an existing VFS into the default VFS, register it again ** with the makeDflt flag set. If two different VFSes with the ** same name are registered, the behavior is undefined. If a ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. ** ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. ** ^(If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary.)^ */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); /* ** CAPI3REF: Mutexes ** ** The SQLite core uses these routines for thread ** synchronization. Though they are intended for internal ** use by SQLite, code that links against SQLite is ** permitted to use any of these routines. ** ** The SQLite source code contains multiple implementations ** of these mutex routines. An appropriate implementation ** is selected automatically at compile-time. The following ** implementations are available in the SQLite core: ** ** <ul> ** <li> SQLITE_MUTEX_PTHREADS ** <li> SQLITE_MUTEX_W32 ** <li> SQLITE_MUTEX_NOOP ** </ul> ** ** The SQLITE_MUTEX_NOOP implementation is a set of routines ** that does no real locking and is appropriate for use in ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix ** and Windows. ** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. In this case the ** application must supply a custom mutex implementation using the ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function ** before calling sqlite3_initialize() or any other public sqlite3_ ** function that calls sqlite3_initialize(). ** ** ^The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() ** routine returns NULL if it is unable to allocate the requested ** mutex. The argument to sqlite3_mutex_alloc() must one of these ** integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST ** <li> SQLITE_MUTEX_RECURSIVE ** <li> SQLITE_MUTEX_STATIC_MASTER ** <li> SQLITE_MUTEX_STATIC_MEM ** <li> SQLITE_MUTEX_STATIC_OPEN ** <li> SQLITE_MUTEX_STATIC_PRNG ** <li> SQLITE_MUTEX_STATIC_LRU ** <li> SQLITE_MUTEX_STATIC_PMEM ** <li> SQLITE_MUTEX_STATIC_APP1 ** <li> SQLITE_MUTEX_STATIC_APP2 ** <li> SQLITE_MUTEX_STATIC_APP3 ** <li> SQLITE_MUTEX_STATIC_VFS1 ** <li> SQLITE_MUTEX_STATIC_VFS2 ** <li> SQLITE_MUTEX_STATIC_VFS3 ** </ul> ** ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) ** cause sqlite3_mutex_alloc() to create ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return ** a pointer to a static preexisting mutex. ^Nine static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. ^For the static ** mutex types, the same mutex is returned on every call that has ** the same type number. ** ** ^The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. Attempting to deallocate a static ** mutex results in undefined behavior. ** ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. ^If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] ** upon successful entry. ^(Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** In such cases, the ** mutex must be exited an equal number of times before another thread ** can enter.)^ If the same thread tries to enter any mutex other ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. ** ** ^(Some systems (for example, Windows 95) do not support the operation ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() ** will always return SQLITE_BUSY. The SQLite core only ever uses ** sqlite3_mutex_try() as an optimization so this is acceptable ** behavior.)^ ** ** ^The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. ** ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or ** sqlite3_mutex_leave() is a NULL pointer, then all three routines ** behave as no-ops. ** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); /* ** CAPI3REF: Mutex Methods Object ** ** An instance of this structure defines the low-level routines ** used to allocate and use mutexes. ** ** Usually, the default mutex implementations provided by SQLite are ** sufficient, however the application has the option of substituting a custom ** implementation for specialized deployments or systems for which SQLite ** does not provide a suitable implementation. In this case, the application ** creates and populates an instance of this structure to pass ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. ** Additionally, an instance of this structure can be used as an ** output variable when querying the system for the current mutex ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. ** ** ^The xMutexInit method defined by this structure is invoked as ** part of system initialization by the sqlite3_initialize() function. ** ^The xMutexInit routine is called by SQLite exactly once for each ** effective call to [sqlite3_initialize()]. ** ** ^The xMutexEnd method defined by this structure is invoked as ** part of system shutdown by the sqlite3_shutdown() function. The ** implementation of this method is expected to release all outstanding ** resources obtained by the mutex methods implementation, especially ** those obtained by the xMutexInit method. ^The xMutexEnd() ** interface is invoked exactly once for each call to [sqlite3_shutdown()]. ** ** ^(The remaining seven methods defined by this structure (xMutexAlloc, ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and ** xMutexNotheld) implement the following interfaces (respectively): ** ** <ul> ** <li> [sqlite3_mutex_alloc()] </li> ** <li> [sqlite3_mutex_free()] </li> ** <li> [sqlite3_mutex_enter()] </li> ** <li> [sqlite3_mutex_try()] </li> ** <li> [sqlite3_mutex_leave()] </li> ** <li> [sqlite3_mutex_held()] </li> ** <li> [sqlite3_mutex_notheld()] </li> ** </ul>)^ ** ** The only difference is that the public sqlite3_XXX functions enumerated ** above silently ignore any invocations that pass a NULL pointer instead ** of a valid mutex handle. The implementations of the methods defined ** by this structure are not required to handle this case, the results ** of passing a NULL pointer instead of a valid mutex handle are undefined ** (i.e. it is acceptable to provide an implementation that segfaults if ** it is passed a NULL pointer). ** ** The xMutexInit() method must be threadsafe. It must be harmless to ** invoke xMutexInit() multiple times within the same process and without ** intervening calls to xMutexEnd(). Second and subsequent calls to ** xMutexInit() must be no-ops. ** ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite ** memory allocation for a fast or recursive mutex. ** ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is ** called, but only if the prior call to xMutexInit returned SQLITE_OK. ** If xMutexInit fails in any way, it is expected to clean up after itself ** prior to returning. */ typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; struct sqlite3_mutex_methods { int (*xMutexInit)(void); int (*xMutexEnd)(void); sqlite3_mutex *(*xMutexAlloc)(int); void (*xMutexFree)(sqlite3_mutex *); void (*xMutexEnter)(sqlite3_mutex *); int (*xMutexTry)(sqlite3_mutex *); void (*xMutexLeave)(sqlite3_mutex *); int (*xMutexHeld)(sqlite3_mutex *); int (*xMutexNotheld)(sqlite3_mutex *); }; /* ** CAPI3REF: Mutex Verification Routines ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. The SQLite core only ** provides implementations for these routines when it is compiled ** with the SQLITE_DEBUG flag. External mutex implementations ** are only required to provide these routines if SQLITE_DEBUG is ** defined and if NDEBUG is not defined. ** ** These routines should return true if the mutex in their argument ** is held or not held, respectively, by the calling thread. ** ** The implementation is not required to provide versions of these ** routines that actually work. If the implementation does not provide working ** versions of these routines, it should at least provide stubs that always ** return true so that one does not get spurious assertion failures. ** ** If the argument to sqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. This seems counter-intuitive since ** clearly the mutex cannot be held if it does not exist. But ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the ** call to sqlite3_mutex_held() to fail, so a non-zero return is ** the appropriate thing to do. The sqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ #ifndef NDEBUG SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); #endif /* ** CAPI3REF: Mutex Types ** ** The [sqlite3_mutex_alloc()] interface takes a single argument ** which is one of these integer constants. ** ** The set of static mutexes may change from one SQLite release to the ** next. Applications that override the built-in mutex logic must be ** prepared to accommodate additional static mutexes. */ #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MASTER 2 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */ #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */ #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */ /* ** CAPI3REF: Retrieve the mutex for a database connection ** METHOD: sqlite3 ** ** ^This interface returns a pointer the [sqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** ^If the [threading mode] is Single-thread or Multi-thread then this ** routine returns a NULL pointer. */ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); /* ** CAPI3REF: Low-Level Control Of Database Files ** METHOD: sqlite3 ** ** ^The [sqlite3_file_control()] interface makes a direct call to the ** xFileControl method for the [sqlite3_io_methods] object associated ** with a particular database identified by the second argument. ^The ** name of the database is "main" for the main database or "temp" for the ** TEMP database, or the name that appears after the AS keyword for ** databases that are added using the [ATTACH] SQL command. ** ^A NULL pointer can be used in place of "main" to refer to the ** main database file. ** ^The third and fourth parameters to this routine ** are passed directly through to the second and third parameters of ** the xFileControl method. ^The return value of the xFileControl ** method becomes the return value of this routine. ** ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes ** a pointer to the underlying [sqlite3_file] object to be written into ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER ** case is a short-circuit path which does not actually invoke the ** underlying sqlite3_io_methods.xFileControl method. ** ** ^If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. ^This error ** code is not remembered and will not be recalled by [sqlite3_errcode()] ** or [sqlite3_errmsg()]. The underlying xFileControl method might ** also return SQLITE_ERROR. There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. ** ** See also: [SQLITE_FCNTL_LOCKSTATE] */ SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); /* ** CAPI3REF: Testing Interface ** ** ^The sqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. ^The first parameter is an operation code that determines ** the number, meaning, and operation of all subsequent parameters. ** ** This interface is not for use by applications. It exists solely ** for verifying the correct operation of the SQLite library. Depending ** on how the SQLite library is compiled, this interface might not exist. ** ** The details of the operation codes, their meanings, the parameters ** they take, and what they do are all subject to change without notice. ** Unlike most of the SQLite API, this function is not guaranteed to ** operate consistently from one release to the next. */ SQLITE_API int sqlite3_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes ** ** These constants are the valid operation code parameters used ** as the first argument to [sqlite3_test_control()]. ** ** These parameters and their meanings are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the ** [sqlite3_test_control()] interface. */ #define SQLITE_TESTCTRL_FIRST 5 #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 #define SQLITE_TESTCTRL_PRNG_RESET 7 #define SQLITE_TESTCTRL_BITVEC_TEST 8 #define SQLITE_TESTCTRL_FAULT_INSTALL 9 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 #define SQLITE_TESTCTRL_PENDING_BYTE 11 #define SQLITE_TESTCTRL_ASSERT 12 #define SQLITE_TESTCTRL_ALWAYS 13 #define SQLITE_TESTCTRL_RESERVE 14 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15 #define SQLITE_TESTCTRL_ISKEYWORD 16 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21 #define SQLITE_TESTCTRL_BYTEORDER 22 #define SQLITE_TESTCTRL_ISINIT 23 #define SQLITE_TESTCTRL_SORTER_MMAP 24 #define SQLITE_TESTCTRL_IMPOSTER 25 #define SQLITE_TESTCTRL_LAST 25 /* ** CAPI3REF: SQLite Runtime Status ** ** ^These interfaces are used to retrieve runtime status information ** about the performance of SQLite, and optionally to reset various ** highwater marks. ^The first argument is an integer code for ** the specific parameter to measure. ^(Recognized integer codes ** are of the form [status parameters | SQLITE_STATUS_...].)^ ** ^The current value of the parameter is returned into *pCurrent. ** ^The highest recorded value is returned in *pHighwater. ^If the ** resetFlag is true, then the highest record value is reset after ** *pHighwater is written. ^(Some parameters do not record the highest ** value. For those parameters ** nothing is written into *pHighwater and the resetFlag is ignored.)^ ** ^(Other parameters record only the highwater mark and not the current ** value. For these latter parameters nothing is written into *pCurrent.)^ ** ** ^The sqlite3_status() and sqlite3_status64() routines return ** SQLITE_OK on success and a non-zero [error code] on failure. ** ** If either the current value or the highwater mark is too large to ** be represented by a 32-bit integer, then the values returned by ** sqlite3_status() are undefined. ** ** See also: [sqlite3_db_status()] */ SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); SQLITE_API int sqlite3_status64( int op, sqlite3_int64 *pCurrent, sqlite3_int64 *pHighwater, int resetFlag ); /* ** CAPI3REF: Status Parameters ** KEYWORDS: {status parameters} ** ** These integer constants designate various run-time status parameters ** that can be returned by [sqlite3_status()]. ** ** <dl> ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt> ** <dd>This parameter is the current amount of memory checked out ** using [sqlite3_malloc()], either directly or indirectly. The ** figure includes calls made to [sqlite3_malloc()] by the application ** and internal memory usage by the SQLite library. Scratch memory ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** this parameter. The amount returned is the sum of the allocation ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^ ** ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt> ** <dd>This parameter records the largest memory allocation request ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their ** internal equivalents). Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt> ** <dd>This parameter records the number of separate memory allocations ** currently checked out.</dd>)^ ** ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt> ** <dd>This parameter returns the number of pages used out of the ** [pagecache memory allocator] that was configured using ** [SQLITE_CONFIG_PAGECACHE]. The ** value returned is in pages, not in bytes.</dd>)^ ** ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt> ** <dd>This parameter returns the number of bytes of page cache ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] ** buffer and where forced to overflow to [sqlite3_malloc()]. The ** returned value includes allocations that overflowed because they ** where too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because ** no space was left in the page cache.</dd>)^ ** ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt> ** <dd>This parameter records the largest memory allocation request ** handed to [pagecache memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt> ** <dd>This parameter returns the number of allocations used out of the ** [scratch memory allocator] configured using ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not ** in bytes. Since a single thread may only have one scratch allocation ** outstanding at time, this parameter also reports the number of threads ** using scratch memory at the same time.</dd>)^ ** ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt> ** <dd>This parameter returns the number of bytes of scratch memory ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] ** buffer and where forced to overflow to [sqlite3_malloc()]. The values ** returned include overflows because the requested allocation was too ** larger (that is, because the requested allocation was larger than the ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer ** slots were available. ** </dd>)^ ** ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt> ** <dd>This parameter records the largest memory allocation request ** handed to [scratch memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt> ** <dd>The *pHighwater parameter records the deepest parser stack. ** The *pCurrent value is undefined. The *pHighwater value is only ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^ ** </dl> ** ** New status parameters may be added from time to time. */ #define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 #define SQLITE_STATUS_SCRATCH_USED 3 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 #define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PAGECACHE_SIZE 7 #define SQLITE_STATUS_SCRATCH_SIZE 8 #define SQLITE_STATUS_MALLOC_COUNT 9 /* ** CAPI3REF: Database Connection Status ** METHOD: sqlite3 ** ** ^This interface is used to retrieve runtime status information ** about a single [database connection]. ^The first argument is the ** database connection object to be interrogated. ^The second argument ** is an integer constant, taken from the set of ** [SQLITE_DBSTATUS options], that ** determines the parameter to interrogate. The set of ** [SQLITE_DBSTATUS options] is likely ** to grow in future releases of SQLite. ** ** ^The current value of the requested parameter is written into *pCur ** and the highest instantaneous value is written into *pHiwtr. ^If ** the resetFlg is true, then the highest instantaneous value is ** reset back down to the current value. ** ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a ** non-zero [error code] on failure. ** ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. */ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); /* ** CAPI3REF: Status Parameters for database connections ** KEYWORDS: {SQLITE_DBSTATUS options} ** ** These constants are the available integer "verbs" that can be passed as ** the second argument to the [sqlite3_db_status()] interface. ** ** New verbs may be added in future releases of SQLite. Existing verbs ** might be discontinued. Applications should check the return code from ** [sqlite3_db_status()] to make sure that the call worked. ** The [sqlite3_db_status()] interface will return a non-zero error code ** if a discontinued or unsupported verb is invoked. ** ** <dl> ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt> ** <dd>This parameter returns the number of lookaside memory slots currently ** checked out.</dd>)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt> ** <dd>This parameter returns the number malloc attempts that were ** satisfied using lookaside memory. Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt> ** <dd>This parameter returns the number malloc attempts that might have ** been satisfied using lookaside memory but failed due to the amount of ** memory requested being larger than the lookaside slot size. ** Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt> ** <dd>This parameter returns the number malloc attempts that might have ** been satisfied using lookaside memory but failed due to all lookaside ** memory already being in use. ** Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap ** memory used by all pager caches associated with the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. ** ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt> ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a ** pager cache is shared between two or more connections the bytes of heap ** memory used by that pager cache is divided evenly between the attached ** connections.)^ In other words, if none of the pager caches associated ** with the database connection are shared, this request returns the same ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are ** shared, the value returned by this call will be smaller than that returned ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0. ** ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap ** memory used to store the schema for all databases associated ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ ** ^The full amount of memory used by the schemas is reported, even if the ** schema memory is shared with other database connections due to ** [shared cache mode] being enabled. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. ** ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap ** and lookaside memory used by all prepared statements associated with ** the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. ** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt> ** <dd>This parameter returns the number of pager cache hits that have ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT ** is always 0. ** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt> ** <dd>This parameter returns the number of pager cache misses that have ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS ** is always 0. ** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt> ** <dd>This parameter returns the number of dirty cache entries that have ** been written to disk. Specifically, the number of pages written to the ** wal file in wal mode databases, or the number of pages written to the ** database file in rollback mode databases. Any pages written as part of ** transaction rollback or database recovery operations are not included. ** If an IO or other error occurs while writing a page to disk, the effect ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. ** </dd> ** ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt> ** <dd>This parameter returns zero for the current value if and only if ** all foreign key constraints (deferred or immediate) have been ** resolved.)^ ^The highwater mark is always 0. ** </dd> ** </dl> */ #define SQLITE_DBSTATUS_LOOKASIDE_USED 0 #define SQLITE_DBSTATUS_CACHE_USED 1 #define SQLITE_DBSTATUS_SCHEMA_USED 2 #define SQLITE_DBSTATUS_STMT_USED 3 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 #define SQLITE_DBSTATUS_CACHE_HIT 7 #define SQLITE_DBSTATUS_CACHE_MISS 8 #define SQLITE_DBSTATUS_CACHE_WRITE 9 #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */ /* ** CAPI3REF: Prepared Statement Status ** METHOD: sqlite3_stmt ** ** ^(Each prepared statement maintains various ** [SQLITE_STMTSTATUS counters] that measure the number ** of times it has performed specific operations.)^ These counters can ** be used to monitor the performance characteristics of the prepared ** statements. For example, if the number of table steps greatly exceeds ** the number of table searches or result rows, that would tend to indicate ** that the prepared statement is using a full table scan rather than ** an index. ** ** ^(This interface is used to retrieve and reset counter values from ** a [prepared statement]. The first argument is the prepared statement ** object to be interrogated. The second argument ** is an integer code for a specific [SQLITE_STMTSTATUS counter] ** to be interrogated.)^ ** ^The current value of the requested counter is returned. ** ^If the resetFlg is true, then the counter is reset to zero after this ** interface call returns. ** ** See also: [sqlite3_status()] and [sqlite3_db_status()]. */ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); /* ** CAPI3REF: Status Parameters for prepared statements ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} ** ** These preprocessor macros define integer codes that name counter ** values associated with the [sqlite3_stmt_status()] interface. ** The meanings of the various counters are as follows: ** ** <dl> ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt> ** <dd>^This is the number of times that SQLite has stepped forward in ** a table as part of a full table scan. Large numbers for this counter ** may indicate opportunities for performance improvement through ** careful use of indices.</dd> ** ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt> ** <dd>^This is the number of sort operations that have occurred. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance through careful use of indices.</dd> ** ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt> ** <dd>^This is the number of rows inserted into transient indices that ** were created automatically in order to help joins run faster. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance by adding permanent indices that do not ** need to be reinitialized each time the statement is run.</dd> ** ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt> ** <dd>^This is the number of virtual machine operations executed ** by the prepared statement if that number is less than or equal ** to 2147483647. The number of virtual machine operations can be ** used as a proxy for the total work done by the prepared statement. ** If the number of virtual machine operations exceeds 2147483647 ** then the value returned by this statement status code is undefined. ** </dd> ** </dl> */ #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 #define SQLITE_STMTSTATUS_SORT 2 #define SQLITE_STMTSTATUS_AUTOINDEX 3 #define SQLITE_STMTSTATUS_VM_STEP 4 /* ** CAPI3REF: Custom Page Cache Object ** ** The sqlite3_pcache type is opaque. It is implemented by ** the pluggable module. The SQLite core has no knowledge of ** its size or internal structure and never deals with the ** sqlite3_pcache object except by holding and passing pointers ** to the object. ** ** See [sqlite3_pcache_methods2] for additional information. */ typedef struct sqlite3_pcache sqlite3_pcache; /* ** CAPI3REF: Custom Page Cache Object ** ** The sqlite3_pcache_page object represents a single page in the ** page cache. The page cache will allocate instances of this ** object. Various methods of the page cache use pointers to instances ** of this object as parameters or as their return value. ** ** See [sqlite3_pcache_methods2] for additional information. */ typedef struct sqlite3_pcache_page sqlite3_pcache_page; struct sqlite3_pcache_page { void *pBuf; /* The content of the page */ void *pExtra; /* Extra information associated with the page */ }; /* ** CAPI3REF: Application Defined Page Cache. ** KEYWORDS: {page cache} ** ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can ** register an alternative page cache implementation by passing in an ** instance of the sqlite3_pcache_methods2 structure.)^ ** In many applications, most of the heap memory allocated by ** SQLite is used for the page cache. ** By implementing a ** custom page cache using this API, an application can better control ** the amount of memory consumed by SQLite, the way in which ** that memory is allocated and released, and the policies used to ** determine exactly which parts of a database file are cached and for ** how long. ** ** The alternative page cache mechanism is an ** extreme measure that is only needed by the most demanding applications. ** The built-in page cache is recommended for most uses. ** ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an ** internal buffer by SQLite within the call to [sqlite3_config]. Hence ** the application may discard the parameter after the call to ** [sqlite3_config()] returns.)^ ** ** [[the xInit() page cache method]] ** ^(The xInit() method is called once for each effective ** call to [sqlite3_initialize()])^ ** (usually only once during the lifetime of the process). ^(The xInit() ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ ** The intent of the xInit() method is to set up global data structures ** required by the custom page cache implementation. ** ^(If the xInit() method is NULL, then the ** built-in default page cache is used instead of the application defined ** page cache.)^ ** ** [[the xShutdown() page cache method]] ** ^The xShutdown() method is called by [sqlite3_shutdown()]. ** It can be used to clean up ** any outstanding resources before process shutdown, if required. ** ^The xShutdown() method may be NULL. ** ** ^SQLite automatically serializes calls to the xInit method, ** so the xInit method need not be threadsafe. ^The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. All other methods must be threadsafe ** in multithreaded applications. ** ** ^SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). ** ** [[the xCreate() page cache methods]] ** ^SQLite invokes the xCreate() method to construct a new cache instance. ** SQLite will typically create one cache instance for each open database file, ** though this is not guaranteed. ^The ** first parameter, szPage, is the size in bytes of the pages that must ** be allocated by the cache. ^szPage will always a power of two. ^The ** second parameter szExtra is a number of bytes of extra storage ** associated with each page cache entry. ^The szExtra parameter will ** a number less than 250. SQLite will use the ** extra szExtra bytes on each page to store metadata about the underlying ** database page on disk. The value passed into szExtra depends ** on the SQLite version, the target platform, and how SQLite was compiled. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being ** created will be used to cache database pages of a file stored on disk, or ** false if it is used for an in-memory database. The cache implementation ** does not have to do anything special based with the value of bPurgeable; ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will ** never invoke xUnpin() except to deliberately delete a page. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to ** false will always have the "discard" flag set to true. ** ^Hence, a cache created with bPurgeable false will ** never contain any unpinned pages. ** ** [[the xCachesize() page cache method]] ** ^(The xCachesize() method may be called at any time by SQLite to set the ** suggested maximum cache-size (number of pages stored by) the cache ** instance passed as the first argument. This is the value configured using ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable ** parameter, the implementation is not required to do anything with this ** value; it is advisory only. ** ** [[the xPagecount() page cache methods]] ** The xPagecount() method must return the number of pages currently ** stored in the cache, both pinned and unpinned. ** ** [[the xFetch() page cache methods]] ** The xFetch() method locates a page in the cache and returns a pointer to ** an sqlite3_pcache_page object associated with that page, or a NULL pointer. ** The pBuf element of the returned sqlite3_pcache_page object will be a ** pointer to a buffer of szPage bytes used to store the content of a ** single database page. The pExtra element of sqlite3_pcache_page will be ** a pointer to the szExtra bytes of extra storage that SQLite has requested ** for each entry in the page cache. ** ** The page to be fetched is determined by the key. ^The minimum key value ** is 1. After it has been retrieved using xFetch, the page is considered ** to be "pinned". ** ** If the requested page is already in the page cache, then the page cache ** implementation must return a pointer to the page buffer with its content ** intact. If the requested page is not already in the cache, then the ** cache implementation should use the value of the createFlag ** parameter to help it determined what action to take: ** ** <table border=1 width=85% align=center> ** <tr><th> createFlag <th> Behavior when page is not already in cache ** <tr><td> 0 <td> Do not allocate a new page. Return NULL. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so. ** Otherwise return NULL. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return ** NULL if allocating a new page is effectively impossible. ** </table> ** ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite ** will only use a createFlag of 2 after a prior call with a createFlag of 1 ** failed.)^ In between the to xFetch() calls, SQLite may ** attempt to unpin one or more cache pages by spilling the content of ** pinned pages to disk and synching the operating system disk cache. ** ** [[the xUnpin() page cache method]] ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page ** as its second argument. If the third parameter, discard, is non-zero, ** then the page must be evicted from the cache. ** ^If the discard parameter is ** zero, then the page may be discarded or retained at the discretion of ** page cache implementation. ^The page cache implementation ** may choose to evict unpinned pages at any time. ** ** The cache must not perform any reference counting. A single ** call to xUnpin() unpins the page regardless of the number of prior calls ** to xFetch(). ** ** [[the xRekey() page cache methods]] ** The xRekey() method is used to change the key value associated with the ** page passed as the second argument. If the cache ** previously contains an entry associated with newKey, it must be ** discarded. ^Any prior cache entry associated with newKey is guaranteed not ** to be pinned. ** ** When SQLite calls the xTruncate() method, the cache must discard all ** existing cache entries with page numbers (keys) greater than or equal ** to the value of the iLimit parameter passed to xTruncate(). If any ** of these pages are pinned, they are implicitly unpinned, meaning that ** they can be safely discarded. ** ** [[the xDestroy() page cache method]] ** ^The xDestroy() method is used to delete a cache allocated by xCreate(). ** All resources associated with the specified cache should be freed. ^After ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] ** handle invalid, and will not use it with any other sqlite3_pcache_methods2 ** functions. ** ** [[the xShrink() page cache method]] ** ^SQLite invokes the xShrink() method when it wants the page cache to ** free up as much of heap memory as possible. The page cache implementation ** is not obligated to free any memory, but well-behaved implementations should ** do their best. */ typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; struct sqlite3_pcache_methods2 { int iVersion; void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); void (*xShrink)(sqlite3_pcache*); }; /* ** This is the obsolete pcache_methods object that has now been replaced ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is ** retained in the header file for backwards compatibility only. */ typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; struct sqlite3_pcache_methods { void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, void*, int discard); void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); }; /* ** CAPI3REF: Online Backup Object ** ** The sqlite3_backup object records state information about an ongoing ** online backup operation. ^The sqlite3_backup object is created by ** a call to [sqlite3_backup_init()] and is destroyed by a call to ** [sqlite3_backup_finish()]. ** ** See Also: [Using the SQLite Online Backup API] */ typedef struct sqlite3_backup sqlite3_backup; /* ** CAPI3REF: Online Backup API. ** ** The backup API copies the content of one database into another. ** It is useful either for creating backups of databases or ** for copying in-memory databases to or from persistent files. ** ** See Also: [Using the SQLite Online Backup API] ** ** ^SQLite holds a write transaction open on the destination database file ** for the duration of the backup operation. ** ^The source database is read-locked only while it is being read; ** it is not locked continuously for the entire backup operation. ** ^Thus, the backup may be performed on a live source database without ** preventing other database connections from ** reading or writing to the source database while the backup is underway. ** ** ^(To perform a backup operation: ** <ol> ** <li><b>sqlite3_backup_init()</b> is called once to initialize the ** backup, ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer ** the data between the two databases, and finally ** <li><b>sqlite3_backup_finish()</b> is called to release all resources ** associated with the backup operation. ** </ol>)^ ** There should be exactly one call to sqlite3_backup_finish() for each ** successful call to sqlite3_backup_init(). ** ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b> ** ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the ** [database connection] associated with the destination database ** and the database name, respectively. ** ^The database name is "main" for the main database, "temp" for the ** temporary database, or the name specified after the AS keyword in ** an [ATTACH] statement for an attached database. ** ^The S and M arguments passed to ** sqlite3_backup_init(D,N,S,M) identify the [database connection] ** and database name of the source database, respectively. ** ^The source and destination [database connections] (parameters S and D) ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with ** an error. ** ** ^A call to sqlite3_backup_init() will fail, returning NULL, if ** there is already a read or read-write transaction open on the ** destination database. ** ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is ** returned and an error code and error message are stored in the ** destination [database connection] D. ** ^The error code and message for the failed call to sqlite3_backup_init() ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or ** [sqlite3_errmsg16()] functions. ** ^A successful call to sqlite3_backup_init() returns a pointer to an ** [sqlite3_backup] object. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and ** sqlite3_backup_finish() functions to perform the specified backup ** operation. ** ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b> ** ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between ** the source and destination databases specified by [sqlite3_backup] object B. ** ^If N is negative, all remaining source pages are copied. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there ** are still more pages to be copied, then the function returns [SQLITE_OK]. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages ** from source to destination, then it returns [SQLITE_DONE]. ** ^If an error occurs while running sqlite3_backup_step(B,N), ** then an [error code] is returned. ^As well as [SQLITE_OK] and ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. ** ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if ** <ol> ** <li> the destination database was opened read-only, or ** <li> the destination database is using write-ahead-log journaling ** and the destination and source page sizes differ, or ** <li> the destination database is an in-memory database and the ** destination and source page sizes differ. ** </ol>)^ ** ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then ** the [sqlite3_busy_handler | busy-handler function] ** is invoked (if one is specified). ^If the ** busy-handler returns non-zero before the lock is available, then ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to ** sqlite3_backup_step() can be retried later. ^If the source ** [database connection] ** is being used to write to the source database when sqlite3_backup_step() ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this ** case the call to sqlite3_backup_step() can be retried later on. ^(If ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or ** [SQLITE_READONLY] is returned, then ** there is no point in retrying the call to sqlite3_backup_step(). These ** errors are considered fatal.)^ The application must accept ** that the backup operation has failed and pass the backup operation handle ** to the sqlite3_backup_finish() to release associated resources. ** ** ^The first call to sqlite3_backup_step() obtains an exclusive lock ** on the destination file. ^The exclusive lock is not released until either ** sqlite3_backup_finish() is called or the backup operation is complete ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to ** sqlite3_backup_step() obtains a [shared lock] on the source database that ** lasts for the duration of the sqlite3_backup_step() call. ** ^Because the source database is not locked between calls to ** sqlite3_backup_step(), the source database may be modified mid-way ** through the backup process. ^If the source database is modified by an ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be automatically ** restarted by the next call to sqlite3_backup_step(). ^If the source ** database is modified by the using the same database connection as is used ** by the backup operation, then the backup database is automatically ** updated at the same time. ** ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b> ** ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the ** application wishes to abandon the backup operation, the application ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). ** ^The sqlite3_backup_finish() interfaces releases all ** resources associated with the [sqlite3_backup] object. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any ** active write-transaction on the destination database is rolled back. ** The [sqlite3_backup] object is invalid ** and may not be used following a call to sqlite3_backup_finish(). ** ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no ** sqlite3_backup_step() errors occurred, regardless or whether or not ** sqlite3_backup_step() completed. ** ^If an out-of-memory condition or IO error occurred during any prior ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then ** sqlite3_backup_finish() returns the corresponding [error code]. ** ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() ** is not a permanent error and does not affect the return value of ** sqlite3_backup_finish(). ** ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b> ** ** ^The sqlite3_backup_remaining() routine returns the number of pages still ** to be backed up at the conclusion of the most recent sqlite3_backup_step(). ** ^The sqlite3_backup_pagecount() routine returns the total number of pages ** in the source database at the conclusion of the most recent ** sqlite3_backup_step(). ** ^(The values returned by these functions are only updated by ** sqlite3_backup_step(). If the source database is modified in a way that ** changes the size of the source database or the number of pages remaining, ** those changes are not reflected in the output of sqlite3_backup_pagecount() ** and sqlite3_backup_remaining() until after the next ** sqlite3_backup_step().)^ ** ** <b>Concurrent Usage of Database Handles</b> ** ** ^The source [database connection] may be used by the application for other ** purposes while a backup operation is underway or being initialized. ** ^If SQLite is compiled and configured to support threadsafe database ** connections, then the source database connection may be used concurrently ** from within other threads. ** ** However, the application must guarantee that the destination ** [database connection] is not passed to any other API (by any thread) after ** sqlite3_backup_init() is called and before the corresponding call to ** sqlite3_backup_finish(). SQLite does not currently check to see ** if the application incorrectly accesses the destination [database connection] ** and so no error code is reported, but the operations may malfunction ** nevertheless. Use of the destination database connection while a ** backup is in progress might also also cause a mutex deadlock. ** ** If running in [shared cache mode], the application must ** guarantee that the shared cache used by the destination database ** is not accessed while the backup is running. In practice this means ** that the application must guarantee that the disk file being ** backed up to is not accessed by any connection within the process, ** not just the specific connection that was passed to sqlite3_backup_init(). ** ** The [sqlite3_backup] object itself is partially threadsafe. Multiple ** threads may safely make multiple concurrent calls to sqlite3_backup_step(). ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() ** APIs are not strictly speaking threadsafe. If they are invoked at the ** same time as another thread is invoking sqlite3_backup_step() it is ** possible that they return invalid values. */ SQLITE_API sqlite3_backup *sqlite3_backup_init( sqlite3 *pDest, /* Destination database handle */ const char *zDestName, /* Destination database name */ sqlite3 *pSource, /* Source database handle */ const char *zSourceName /* Source database name */ ); SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); /* ** CAPI3REF: Unlock Notification ** METHOD: sqlite3 ** ** ^When running in shared-cache mode, a database operation may fail with ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or ** individual tables within the shared-cache cannot be obtained. See ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. ** ^This API may be used to register a callback that SQLite will invoke ** when the connection currently holding the required lock relinquishes it. ** ^This API is only available if the library was compiled with the ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. ** ** See Also: [Using the SQLite Unlock Notification Feature]. ** ** ^Shared-cache locks are released when a database connection concludes ** its current transaction, either by committing it or rolling it back. ** ** ^When a connection (known as the blocked connection) fails to obtain a ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the ** identity of the database connection (the blocking connection) that ** has locked the required resource is stored internally. ^After an ** application receives an SQLITE_LOCKED error, it may call the ** sqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked ** when the blocking connections current transaction is concluded. ^The ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] ** call that concludes the blocking connections transaction. ** ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, ** there is a chance that the blocking connection will have already ** concluded its transaction by the time sqlite3_unlock_notify() is invoked. ** If this happens, then the specified callback is invoked immediately, ** from within the call to sqlite3_unlock_notify().)^ ** ** ^If the blocked connection is attempting to obtain a write-lock on a ** shared-cache table, and more than one other connection currently holds ** a read-lock on the same table, then SQLite arbitrarily selects one of ** the other connections to use as the blocking connection. ** ** ^(There may be at most one unlock-notify callback registered by a ** blocked connection. If sqlite3_unlock_notify() is called when the ** blocked connection already has a registered unlock-notify callback, ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing ** unlock-notify callback is canceled. ^The blocked connections ** unlock-notify callback may also be canceled by closing the blocked ** connection using [sqlite3_close()]. ** ** The unlock-notify callback is not reentrant. If an application invokes ** any sqlite3_xxx API functions from within an unlock-notify callback, a ** crash or deadlock may be the result. ** ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always ** returns SQLITE_OK. ** ** <b>Callback Invocation Details</b> ** ** When an unlock-notify callback is registered, the application provides a ** single void* pointer that is passed to the callback when it is invoked. ** However, the signature of the callback function allows SQLite to pass ** it an array of void* context pointers. The first argument passed to ** an unlock-notify callback is a pointer to an array of void* pointers, ** and the second is the number of entries in the array. ** ** When a blocking connections transaction is concluded, there may be ** more than one blocked connection that has registered for an unlock-notify ** callback. ^If two or more such blocked connections have specified the ** same callback function, then instead of invoking the callback function ** multiple times, it is invoked once with the set of void* context pointers ** specified by the blocked connections bundled together into an array. ** This gives the application an opportunity to prioritize any actions ** related to the set of unblocked database connections. ** ** <b>Deadlock Detection</b> ** ** Assuming that after registering for an unlock-notify callback a ** database waits for the callback to be issued before taking any further ** action (a reasonable assumption), then using this API may cause the ** application to deadlock. For example, if connection X is waiting for ** connection Y's transaction to be concluded, and similarly connection ** Y is waiting on connection X's transaction, then neither connection ** will proceed and the system may remain deadlocked indefinitely. ** ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock ** detection. ^If a given call to sqlite3_unlock_notify() would put the ** system in a deadlocked state, then SQLITE_LOCKED is returned and no ** unlock-notify callback is registered. The system is said to be in ** a deadlocked state if connection A has registered for an unlock-notify ** callback on the conclusion of connection B's transaction, and connection ** B has itself registered for an unlock-notify callback when connection ** A's transaction is concluded. ^Indirect deadlock is also detected, so ** the system is also considered to be deadlocked if connection B has ** registered for an unlock-notify callback on the conclusion of connection ** C's transaction, where connection C is waiting on connection A. ^Any ** number of levels of indirection are allowed. ** ** <b>The "DROP TABLE" Exception</b> ** ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost ** always appropriate to call sqlite3_unlock_notify(). There is however, ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, ** SQLite checks if there are any currently executing SELECT statements ** that belong to the same connection. If there are, SQLITE_LOCKED is ** returned. In this case there is no "blocking connection", so invoking ** sqlite3_unlock_notify() results in the unlock-notify callback being ** invoked immediately. If the application then re-attempts the "DROP TABLE" ** or "DROP INDEX" query, an infinite loop might be the result. ** ** One way around this problem is to check the extended error code returned ** by an sqlite3_step() call. ^(If there is a blocking connection, then the ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in ** the special "DROP TABLE/INDEX" case, the extended error code is just ** SQLITE_LOCKED.)^ */ SQLITE_API int sqlite3_unlock_notify( sqlite3 *pBlocked, /* Waiting connection */ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ void *pNotifyArg /* Argument to pass to xNotify */ ); /* ** CAPI3REF: String Comparison ** ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications ** and extensions to compare the contents of two buffers containing UTF-8 ** strings in a case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ SQLITE_API int sqlite3_stricmp(const char *, const char *); SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); /* ** CAPI3REF: String Globbing * ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if ** string X matches the [GLOB] pattern P. ** ^The definition of [GLOB] pattern matching used in ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function ** is case sensitive. ** ** Note that this routine returns zero on a match and non-zero if the strings ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. ** ** See also: [sqlite3_strlike()]. */ SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); /* ** CAPI3REF: String LIKE Matching * ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if ** string X matches the [LIKE] pattern P with escape character E. ** ^The definition of [LIKE] pattern matching used in ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case ** insensitive - equivalent upper and lower case ASCII characters match ** one another. ** ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though ** only ASCII characters are case folded. ** ** Note that this routine returns zero on a match and non-zero if the strings ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. ** ** See also: [sqlite3_strglob()]. */ SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); /* ** CAPI3REF: Error Logging Interface ** ** ^The [sqlite3_log()] interface writes a message into the [error log] ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. ** ^If logging is enabled, the zFormat string and subsequent arguments are ** used with [sqlite3_snprintf()] to generate the final output string. ** ** The sqlite3_log() interface is intended for use by extensions such as ** virtual tables, collating functions, and SQL functions. While there is ** nothing to prevent an application from calling sqlite3_log(), doing so ** is considered bad form. ** ** The zFormat string must not be NULL. ** ** To avoid deadlocks and other threading problems, the sqlite3_log() routine ** will not use dynamically allocated memory. The log message is stored in ** a fixed-length buffer on the stack. If the log message is longer than ** a few hundred characters, it will be truncated to the length of the ** buffer. */ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); /* ** CAPI3REF: Write-Ahead Log Commit Hook ** METHOD: sqlite3 ** ** ^The [sqlite3_wal_hook()] function is used to register a callback that ** is invoked each time data is committed to a database in wal mode. ** ** ^(The callback is invoked by SQLite after the commit has taken place and ** the associated write-lock on the database released)^, so the implementation ** may read, write or [checkpoint] the database as required. ** ** ^The first parameter passed to the callback function when it is invoked ** is a copy of the third parameter passed to sqlite3_wal_hook() when ** registering the callback. ^The second is a copy of the database handle. ** ^The third parameter is the name of the database that was written to - ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter ** is the number of pages currently in the write-ahead log file, ** including those that were just committed. ** ** The callback function should normally return [SQLITE_OK]. ^If an error ** code is returned, that error will propagate back up through the ** SQLite code base to cause the statement that provoked the callback ** to report an error, though the commit will have still occurred. If the ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value ** that does not correspond to any valid SQLite error code, the results ** are undefined. ** ** A single database handle may have at most a single write-ahead log callback ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any ** previously registered write-ahead log callback. ^Note that the ** [sqlite3_wal_autocheckpoint()] interface and the ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will ** overwrite any prior [sqlite3_wal_hook()] settings. */ SQLITE_API void *sqlite3_wal_hook( sqlite3*, int(*)(void *,sqlite3*,const char*,int), void* ); /* ** CAPI3REF: Configure an auto-checkpoint ** METHOD: sqlite3 ** ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around ** [sqlite3_wal_hook()] that causes any database on [database connection] D ** to automatically [checkpoint] ** after committing a transaction if there are N or ** more frames in the [write-ahead log] file. ^Passing zero or ** a negative value as the nFrame parameter disables automatic ** checkpoints entirely. ** ** ^The callback registered by this function replaces any existing callback ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism ** configured by this function. ** ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface ** from SQL. ** ** ^Checkpoints initiated by this mechanism are ** [sqlite3_wal_checkpoint_v2|PASSIVE]. ** ** ^Every new [database connection] defaults to having the auto-checkpoint ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] ** pages. The use of this interface ** is only necessary if the default setting is found to be suboptimal ** for a particular application. */ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); /* ** CAPI3REF: Checkpoint a database ** METHOD: sqlite3 ** ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ ** ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the ** [write-ahead log] for database X on [database connection] D to be ** transferred into the database file and for the write-ahead log to ** be reset. See the [checkpointing] documentation for addition ** information. ** ** This interface used to be the only way to cause a checkpoint to ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] ** interface was added. This interface is retained for backwards ** compatibility and as a convenience for applications that need to manually ** start a callback but which do not need the full power (and corresponding ** complication) of [sqlite3_wal_checkpoint_v2()]. */ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); /* ** CAPI3REF: Checkpoint a database ** METHOD: sqlite3 ** ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint ** operation on database X of [database connection] D in mode M. Status ** information is written back into integers pointed to by L and C.)^ ** ^(The M parameter must be a valid [checkpoint mode]:)^ ** ** <dl> ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd> ** ^Checkpoint as many frames as possible without waiting for any database ** readers or writers to finish, then sync the database file if all frames ** in the log were checkpointed. ^The [busy-handler callback] ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode. ** ^On the other hand, passive mode might leave the checkpoint unfinished ** if there are concurrent readers or writers. ** ** <dt>SQLITE_CHECKPOINT_FULL<dd> ** ^This mode blocks (it invokes the ** [sqlite3_busy_handler|busy-handler callback]) until there is no ** database writer and all readers are reading from the most recent database ** snapshot. ^It then checkpoints all frames in the log file and syncs the ** database file. ^This mode blocks new database writers while it is pending, ** but new database readers are allowed to continue unimpeded. ** ** <dt>SQLITE_CHECKPOINT_RESTART<dd> ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition ** that after checkpointing the log file it blocks (calls the ** [busy-handler callback]) ** until all readers are reading from the database file only. ^This ensures ** that the next writer will restart the log file from the beginning. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new ** database writer attempts while it is pending, but does not impede readers. ** ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd> ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the ** addition that it also truncates the log file to zero bytes just prior ** to a successful return. ** </dl> ** ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in ** the log file or to -1 if the checkpoint could not run because ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the ** log file (including any that were already checkpointed before the function ** was called) or to -1 if the checkpoint could not run due to an error or ** because the database is not in WAL mode. ^Note that upon successful ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero. ** ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If ** any other process is running a checkpoint operation at the same time, the ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a ** busy-handler configured, it will not be invoked in this case. ** ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the ** exclusive "writer" lock on the database file. ^If the writer lock cannot be ** obtained immediately, and a busy-handler is configured, it is invoked and ** the writer lock retried until either the busy-handler returns 0 or the lock ** is successfully obtained. ^The busy-handler is also invoked while waiting for ** database readers as described above. ^If the busy-handler returns 0 before ** the writer lock is obtained or while waiting for database readers, the ** checkpoint operation proceeds from that point in the same way as ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible ** without blocking any further. ^SQLITE_BUSY is returned in this case. ** ** ^If parameter zDb is NULL or points to a zero length string, then the ** specified operation is attempted on all WAL databases [attached] to ** [database connection] db. In this case the ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If ** an SQLITE_BUSY error is encountered when processing one or more of the ** attached WAL databases, the operation is still attempted on any remaining ** attached databases and SQLITE_BUSY is returned at the end. ^If any other ** error occurs while processing an attached database, processing is abandoned ** and the error code is returned to the caller immediately. ^If no error ** (SQLITE_BUSY or otherwise) is encountered while processing the attached ** databases, SQLITE_OK is returned. ** ** ^If database zDb is the name of an attached database that is not in WAL ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If ** zDb is not NULL (or a zero length string) and is not the name of any ** attached database, SQLITE_ERROR is returned to the caller. ** ** ^Unless it returns SQLITE_MISUSE, ** the sqlite3_wal_checkpoint_v2() interface ** sets the error information that is queried by ** [sqlite3_errcode()] and [sqlite3_errmsg()]. ** ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface ** from SQL. */ SQLITE_API int sqlite3_wal_checkpoint_v2( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ int *pnCkpt /* OUT: Total number of frames checkpointed */ ); /* ** CAPI3REF: Checkpoint Mode Values ** KEYWORDS: {checkpoint mode} ** ** These constants define all valid values for the "checkpoint mode" passed ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the ** meaning of each of these checkpoint modes. */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */ #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */ /* ** CAPI3REF: Virtual Table Interface Configuration ** ** This function may be called by either the [xConnect] or [xCreate] method ** of a [virtual table] implementation to configure ** various facets of the virtual table interface. ** ** If this interface is invoked outside the context of an xConnect or ** xCreate virtual table method then the behavior is undefined. ** ** At present, there is only one option that may be configured using ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options ** may be added in the future. */ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); /* ** CAPI3REF: Virtual Table Configuration Options ** ** These macros define the various options to the ** [sqlite3_vtab_config()] interface that [virtual table] implementations ** can use to customize and optimize their behavior. ** ** <dl> ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT ** <dd>Calls of the form ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, ** where X is an integer. If X is zero, then the [virtual table] whose ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not ** support constraints. In this configuration (which is the default) if ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been ** specified as part of the users SQL statement, regardless of the actual ** ON CONFLICT mode specified. ** ** If X is non-zero, then the virtual table implementation guarantees ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before ** any modifications to internal or persistent data structures have been made. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite ** is able to roll back a statement or database transaction, and abandon ** or continue processing the current SQL statement as appropriate. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode ** had been ABORT. ** ** Virtual table implementations that are required to handle OR REPLACE ** must do so within the [xUpdate] method. If a call to the ** [sqlite3_vtab_on_conflict()] function indicates that the current ON ** CONFLICT policy is REPLACE, the virtual table implementation should ** silently replace the appropriate rows within the xUpdate callback and ** return SQLITE_OK. Or, if this is not possible, it may return ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT ** constraint handling. ** </dl> */ #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 /* ** CAPI3REF: Determine The Virtual Table Conflict Policy ** ** This function may only be called from within a call to the [xUpdate] method ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode ** of the SQL statement that triggered the call to the [xUpdate] method of the ** [virtual table]. */ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); /* ** CAPI3REF: Conflict resolution modes ** KEYWORDS: {conflict resolution mode} ** ** These constants are returned by [sqlite3_vtab_on_conflict()] to ** inform a [virtual table] implementation what the [ON CONFLICT] mode ** is for the SQL statement being evaluated. ** ** Note that the [SQLITE_IGNORE] constant is also used as a potential ** return value from the [sqlite3_set_authorizer()] callback and that ** [SQLITE_ABORT] is also a [result code]. */ #define SQLITE_ROLLBACK 1 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ #define SQLITE_FAIL 3 /* #define SQLITE_ABORT 4 // Also an error code */ #define SQLITE_REPLACE 5 /* ** CAPI3REF: Prepared Statement Scan Status Opcodes ** KEYWORDS: {scanstatus options} ** ** The following constants can be used for the T parameter to the ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a ** different metric for sqlite3_stmt_scanstatus() to return. ** ** When the value returned to V is a string, space to hold that string is ** managed by the prepared statement S and will be automatically freed when ** S is finalized. ** ** <dl> ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt> ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be ** set to the total number of times that the X-th loop has run.</dd> ** ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt> ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set ** to the total number of rows examined by all iterations of the X-th loop.</dd> ** ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt> ** <dd>^The "double" variable pointed to by the T parameter will be set to the ** query planner's estimate for the average number of rows output from each ** iteration of the X-th loop. If the query planner's estimates was accurate, ** then this value will approximate the quotient NVISIT/NLOOP and the ** product of this value for all prior loops with the same SELECTID will ** be the NLOOP value for the current loop. ** ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt> ** <dd>^The "const char *" variable pointed to by the T parameter will be set ** to a zero-terminated UTF-8 string containing the name of the index or table ** used for the X-th loop. ** ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt> ** <dd>^The "const char *" variable pointed to by the T parameter will be set ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] ** description for the X-th loop. ** ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt> ** <dd>^The "int" variable pointed to by the T parameter will be set to the ** "select-id" for the X-th loop. The select-id identifies which query or ** subquery the loop is part of. The main query has a select-id of zero. ** The select-id is the same value as is output in the first column ** of an [EXPLAIN QUERY PLAN] query. ** </dl> */ #define SQLITE_SCANSTAT_NLOOP 0 #define SQLITE_SCANSTAT_NVISIT 1 #define SQLITE_SCANSTAT_EST 2 #define SQLITE_SCANSTAT_NAME 3 #define SQLITE_SCANSTAT_EXPLAIN 4 #define SQLITE_SCANSTAT_SELECTID 5 /* ** CAPI3REF: Prepared Statement Scan Status ** METHOD: sqlite3_stmt ** ** This interface returns information about the predicted and measured ** performance for pStmt. Advanced applications can use this ** interface to compare the predicted and the measured performance and ** issue warnings and/or rerun [ANALYZE] if discrepancies are found. ** ** Since this interface is expected to be rarely used, it is only ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS] ** compile-time option. ** ** The "iScanStatusOp" parameter determines which status information to return. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior ** of this interface is undefined. ** ^The requested measurement is written into a variable pointed to by ** the "pOut" parameter. ** Parameter "idx" identifies the specific loop to retrieve statistics for. ** Loops are numbered starting from zero. ^If idx is out of range - less than ** zero or greater than or equal to the total number of loops used to implement ** the statement - a non-zero value is returned and the variable that pOut ** points to is unchanged. ** ** ^Statistics might not be available for all loops in all statements. ^In cases ** where there exist loops with no available statistics, this function behaves ** as if the loop did not exist - it returns non-zero and leave the variable ** that pOut points to unchanged. ** ** See also: [sqlite3_stmt_scanstatus_reset()] */ SQLITE_API int sqlite3_stmt_scanstatus( sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ void *pOut /* Result written here */ ); /* ** CAPI3REF: Zero Scan-Status Counters ** METHOD: sqlite3_stmt ** ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. ** ** This API is only available if the library is built with pre-processor ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. */ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); /* ** CAPI3REF: Flush caches to disk mid-transaction ** ** ^If a write-transaction is open on [database connection] D when the ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty ** pages in the pager-cache that are not currently in use are written out ** to disk. A dirty page may be in use if a database cursor created by an ** active SQL statement is reading from it, or if it is page 1 of a database ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] ** interface flushes caches for all schemas - "main", "temp", and ** any [attached] databases. ** ** ^If this function needs to obtain extra database locks before dirty pages ** can be flushed to disk, it does so. ^If those locks cannot be obtained ** immediately and there is a busy-handler callback configured, it is invoked ** in the usual manner. ^If the required lock still cannot be obtained, then ** the database is skipped and an attempt made to flush any dirty pages ** belonging to the next (if any) database. ^If any databases are skipped ** because locks cannot be obtained, but no other error occurs, this ** function returns SQLITE_BUSY. ** ** ^If any other error occurs while flushing dirty pages to disk (for ** example an IO error or out-of-memory condition), then processing is ** abandoned and an SQLite [error code] is returned to the caller immediately. ** ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. ** ** ^This function does not set the database handle error code or message ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. */ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); /* ** CAPI3REF: The pre-update hook. ** ** ^These interfaces are only available if SQLite is compiled using the ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. ** ** ^The [sqlite3_preupdate_hook()] interface registers a callback function ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation ** on a database table. ** ^At most one preupdate hook may be registered at a time on a single ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides ** the previous setting. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] ** with a NULL pointer as the second parameter. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as ** the first parameter to callbacks. ** ** ^The preupdate hook only fires for changes to real database tables; the ** preupdate hook is not invoked for changes to [virtual tables] or to ** system tables like sqlite_master or sqlite_stat1. ** ** ^The second parameter to the preupdate callback is a pointer to ** the [database connection] that registered the preupdate hook. ** ^The third parameter to the preupdate callback is one of the constants ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the ** kind of update operation that is about to occur. ** ^(The fourth parameter to the preupdate callback is the name of the ** database within the database connection that is being modified. This ** will be "main" for the main database or "temp" for TEMP tables or ** the name given after the AS keyword in the [ATTACH] statement for attached ** databases.)^ ** ^The fifth parameter to the preupdate callback is the name of the ** table that is being modified. ** ** For an UPDATE or DELETE operation on a [rowid table], the sixth ** parameter passed to the preupdate callback is the initial [rowid] of the ** row being modified or deleted. For an INSERT operation on a rowid table, ** or any operation on a WITHOUT ROWID table, the value of the sixth ** parameter is undefined. For an INSERT or UPDATE on a rowid table the ** seventh parameter is the final rowid value of the row being inserted ** or updated. The value of the seventh parameter passed to the callback ** function is not defined for operations on WITHOUT ROWID tables, or for ** INSERT operations on rowid tables. ** ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces ** provide additional information about a preupdate event. These routines ** may only be called from within a preupdate callback. Invoking any of ** these routines from outside of a preupdate callback or with a ** [database connection] pointer that is different from the one supplied ** to the preupdate callback results in undefined and probably undesirable ** behavior. ** ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns ** in the row that is being inserted, updated, or deleted. ** ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to ** a [protected sqlite3_value] that contains the value of the Nth column of ** the table row before it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the ** behavior is undefined. The [sqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to ** a [protected sqlite3_value] that contains the value of the Nth column of ** the table row after it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the ** behavior is undefined. The [sqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate ** callback was invoked as a result of a direct insert, update, or delete ** operation; or 1 for inserts, updates, or deletes invoked by top-level ** triggers; or 2 for changes resulting from triggers called by top-level ** triggers; and so forth. ** ** See also: [sqlite3_update_hook()] */ #if defined(SQLITE_ENABLE_PREUPDATE_HOOK) SQLITE_API void *sqlite3_preupdate_hook( sqlite3 *db, void(*xPreUpdate)( void *pCtx, /* Copy of third arg to preupdate_hook() */ sqlite3 *db, /* Database handle */ int op, /* SQLITE_UPDATE, DELETE or INSERT */ char const *zDb, /* Database name */ char const *zName, /* Table name */ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ ), void* ); SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); SQLITE_API int sqlite3_preupdate_count(sqlite3 *); SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); #endif /* ** CAPI3REF: Low-level system error code ** ** ^Attempt to return the underlying operating system error code or error ** number that caused the most recent I/O error or failure to open a file. ** The return value is OS-dependent. For example, on unix systems, after ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be ** called to get back the underlying "errno" that caused the problem, such ** as ENOSPC, EAUTH, EISDIR, and so forth. */ SQLITE_API int sqlite3_system_errno(sqlite3*); /* ** CAPI3REF: Database Snapshot ** KEYWORDS: {snapshot} {sqlite3_snapshot} ** EXPERIMENTAL ** ** An instance of the snapshot object records the state of a [WAL mode] ** database for some specific point in history. ** ** In [WAL mode], multiple [database connections] that are open on the ** same database file can each be reading a different historical version ** of the database file. When a [database connection] begins a read ** transaction, that connection sees an unchanging copy of the database ** as it existed for the point in time when the transaction first started. ** Subsequent changes to the database from other connections are not seen ** by the reader until a new read transaction is started. ** ** The sqlite3_snapshot object records state information about an historical ** version of the database file so that it is possible to later open a new read ** transaction that sees that historical version of the database rather than ** the most recent version. ** ** The constructor for this object is [sqlite3_snapshot_get()]. The ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer ** to an historical snapshot (if possible). The destructor for ** sqlite3_snapshot objects is [sqlite3_snapshot_free()]. */ typedef struct sqlite3_snapshot { unsigned char hidden[48]; } sqlite3_snapshot; /* ** CAPI3REF: Record A Database Snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a ** new [sqlite3_snapshot] object that records the current state of ** schema S in database connection D. ^On success, the ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK. ** If there is not already a read-transaction open on schema S when ** this function is called, one is opened automatically. ** ** The following must be true for this function to succeed. If any of ** the following statements are false when sqlite3_snapshot_get() is ** called, SQLITE_ERROR is returned. The final value of *P is undefined ** in this case. ** ** <ul> ** <li> The database handle must be in [autocommit mode]. ** ** <li> Schema S of [database connection] D must be a [WAL mode] database. ** ** <li> There must not be a write transaction open on schema S of database ** connection D. ** ** <li> One or more transactions must have been written to the current wal ** file since it was created on disk (by any connection). This means ** that a snapshot cannot be taken on a wal mode database with no wal ** file immediately after it is first opened. At least one transaction ** must be written to it first. ** </ul> ** ** This function may also return SQLITE_NOMEM. If it is called with the ** database handle in autocommit mode but fails for some other reason, ** whether or not a read transaction is opened on schema S is undefined. ** ** The [sqlite3_snapshot] object returned from a successful call to ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()] ** to avoid a memory leak. ** ** The [sqlite3_snapshot_get()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot ); /* ** CAPI3REF: Start a read transaction on an historical snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a ** read transaction for schema S of ** [database connection] D such that the read transaction ** refers to historical [snapshot] P, rather than the most ** recent change to the database. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success ** or an appropriate [error code] if it fails. ** ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be ** the first operation following the [BEGIN] that takes the schema S ** out of [autocommit mode]. ** ^In other words, schema S must not currently be in ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the ** database connection D must be out of [autocommit mode]. ** ^A [snapshot] will fail to open if it has been overwritten by a ** [checkpoint]. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the ** database connection D does not know that the database file for ** schema S is in [WAL mode]. A database connection might not know ** that the database file is in [WAL mode] if there has been no prior ** I/O on that database connection, or if the database entered [WAL mode] ** after the most recent I/O on the database connection.)^ ** (Hint: Run "[PRAGMA application_id]" against a newly opened ** database connection in order to make it ready to use snapshots.) ** ** The [sqlite3_snapshot_open()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot ); /* ** CAPI3REF: Destroy a snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P. ** The application must eventually free every [sqlite3_snapshot] object ** using this routine to avoid a memory leak. ** ** The [sqlite3_snapshot_free()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); /* ** CAPI3REF: Compare the ages of two snapshot handles. ** EXPERIMENTAL ** ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages ** of two valid snapshot handles. ** ** If the two snapshot handles are not associated with the same database ** file, the result of the comparison is undefined. ** ** Additionally, the result of the comparison is only valid if both of the ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the ** last time the wal file was deleted. The wal file is deleted when the ** database is changed back to rollback mode or when the number of database ** clients drops to zero. If either snapshot handle was obtained before the ** wal file was last deleted, the value returned by this function ** is undefined. ** ** Otherwise, this API returns a negative value if P1 refers to an older ** snapshot than P2, zero if the two handles refer to the same database ** snapshot, and a positive value if P1 is a newer snapshot than P2. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); /* ** CAPI3REF: Recover snapshots from a wal file ** EXPERIMENTAL ** ** If all connections disconnect from a database file but do not perform ** a checkpoint, the existing wal file is opened along with the database ** file the next time the database is opened. At this point it is only ** possible to successfully call sqlite3_snapshot_open() to open the most ** recent snapshot of the database (the one at the head of the wal file), ** even though the wal file may contain other valid snapshots for which ** clients have sqlite3_snapshot handles. ** ** This function attempts to scan the wal file associated with database zDb ** of database handle db and make all valid snapshots available to ** sqlite3_snapshot_open(). It is an error if there is already a read ** transaction open on the database, or if the database is not a wal mode ** database. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ #ifdef SQLITE_OMIT_FLOATING_POINT # undef double #endif #ifdef __cplusplus } /* End of the 'extern "C"' block */ #endif #endif /* SQLITE3_H */ /******** Begin file sqlite3rtree.h *********/ /* ** 2010 August 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* */ #ifndef _SQLITE3RTREE_H_ #define _SQLITE3RTREE_H_ #ifdef __cplusplus extern "C" { #endif typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; /* The double-precision datatype used by RTree depends on the ** SQLITE_RTREE_INT_ONLY compile-time option. */ #ifdef SQLITE_RTREE_INT_ONLY typedef sqlite3_int64 sqlite3_rtree_dbl; #else typedef double sqlite3_rtree_dbl; #endif /* ** Register a geometry callback named zGeom that can be used as part of an ** R-Tree geometry query as follows: ** ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...) */ SQLITE_API int sqlite3_rtree_geometry_callback( sqlite3 *db, const char *zGeom, int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*), void *pContext ); /* ** A pointer to a structure of the following type is passed as the first ** argument to callbacks registered using rtree_geometry_callback(). */ struct sqlite3_rtree_geometry { void *pContext; /* Copy of pContext passed to s_r_g_c() */ int nParam; /* Size of array aParam[] */ sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ void *pUser; /* Callback implementation user data */ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ }; /* ** Register a 2nd-generation geometry callback named zScore that can be ** used as part of an R-Tree geometry query as follows: ** ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...) */ SQLITE_API int sqlite3_rtree_query_callback( sqlite3 *db, const char *zQueryFunc, int (*xQueryFunc)(sqlite3_rtree_query_info*), void *pContext, void (*xDestructor)(void*) ); /* ** A pointer to a structure of the following type is passed as the ** argument to scored geometry callback registered using ** sqlite3_rtree_query_callback(). ** ** Note that the first 5 fields of this structure are identical to ** sqlite3_rtree_geometry. This structure is a subclass of ** sqlite3_rtree_geometry. */ struct sqlite3_rtree_query_info { void *pContext; /* pContext from when function registered */ int nParam; /* Number of function parameters */ sqlite3_rtree_dbl *aParam; /* value of function parameters */ void *pUser; /* callback can use this, if desired */ void (*xDelUser)(void*); /* function to free pUser */ sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ unsigned int *anQueue; /* Number of pending entries in the queue */ int nCoord; /* Number of coordinates */ int iLevel; /* Level of current node or entry */ int mxLevel; /* The largest iLevel value in the tree */ sqlite3_int64 iRowid; /* Rowid for current entry */ sqlite3_rtree_dbl rParentScore; /* Score of parent node */ int eParentWithin; /* Visibility of parent node */ int eWithin; /* OUT: Visiblity */ sqlite3_rtree_dbl rScore; /* OUT: Write the score here */ /* The following fields are only available in 3.8.11 and later */ sqlite3_value **apSqlParam; /* Original SQL values of parameters */ }; /* ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin. */ #define NOT_WITHIN 0 /* Object completely outside of query region */ #define PARTLY_WITHIN 1 /* Object partially overlaps query region */ #define FULLY_WITHIN 2 /* Object fully contained within query region */ #ifdef __cplusplus } /* end of the 'extern "C"' block */ #endif #endif /* ifndef _SQLITE3RTREE_H_ */ /******** End of sqlite3rtree.h *********/ /******** Begin file sqlite3session.h *********/ #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) #define __SQLITESESSION_H_ 1 /* ** Make sure we can call this stuff from C++. */ #ifdef __cplusplus extern "C" { #endif /* ** CAPI3REF: Session Object Handle */ typedef struct sqlite3_session sqlite3_session; /* ** CAPI3REF: Changeset Iterator Handle */ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; /* ** CAPI3REF: Create A New Session Object ** ** Create a new session object attached to database handle db. If successful, ** a pointer to the new object is written to *ppSession and SQLITE_OK is ** returned. If an error occurs, *ppSession is set to NULL and an SQLite ** error code (e.g. SQLITE_NOMEM) is returned. ** ** It is possible to create multiple session objects attached to a single ** database handle. ** ** Session objects created using this function should be deleted using the ** [sqlite3session_delete()] function before the database handle that they ** are attached to is itself closed. If the database handle is closed before ** the session object is deleted, then the results of calling any session ** module function, including [sqlite3session_delete()] on the session object ** are undefined. ** ** Because the session module uses the [sqlite3_preupdate_hook()] API, it ** is not possible for an application to register a pre-update hook on a ** database handle that has one or more session objects attached. Nor is ** it possible to create a session object attached to a database handle for ** which a pre-update hook is already defined. The results of attempting ** either of these things are undefined. ** ** The session object will be used to create changesets for tables in ** database zDb, where zDb is either "main", or "temp", or the name of an ** attached database. It is not an error if database zDb is not attached ** to the database when the session object is created. */ SQLITE_API int sqlite3session_create( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ sqlite3_session **ppSession /* OUT: New session object */ ); /* ** CAPI3REF: Delete A Session Object ** ** Delete a session object previously allocated using ** [sqlite3session_create()]. Once a session object has been deleted, the ** results of attempting to use pSession with any other session module ** function are undefined. ** ** Session objects must be deleted before the database handle to which they ** are attached is closed. Refer to the documentation for ** [sqlite3session_create()] for details. */ SQLITE_API void sqlite3session_delete(sqlite3_session *pSession); /* ** CAPI3REF: Enable Or Disable A Session Object ** ** Enable or disable the recording of changes by a session object. When ** enabled, a session object records changes made to the database. When ** disabled - it does not. A newly created session object is enabled. ** Refer to the documentation for [sqlite3session_changeset()] for further ** details regarding how enabling and disabling a session object affects ** the eventual changesets. ** ** Passing zero to this function disables the session. Passing a value ** greater than zero enables it. Passing a value less than zero is a ** no-op, and may be used to query the current state of the session. ** ** The return value indicates the final state of the session object: 0 if ** the session is disabled, or 1 if it is enabled. */ SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable); /* ** CAPI3REF: Set Or Clear the Indirect Change Flag ** ** Each change recorded by a session object is marked as either direct or ** indirect. A change is marked as indirect if either: ** ** <ul> ** <li> The session object "indirect" flag is set when the change is ** made, or ** <li> The change is made by an SQL trigger or foreign key action ** instead of directly as a result of a users SQL statement. ** </ul> ** ** If a single row is affected by more than one operation within a session, ** then the change is considered indirect if all operations meet the criteria ** for an indirect change above, or direct otherwise. ** ** This function is used to set, clear or query the session object indirect ** flag. If the second argument passed to this function is zero, then the ** indirect flag is cleared. If it is greater than zero, the indirect flag ** is set. Passing a value less than zero does not modify the current value ** of the indirect flag, and may be used to query the current state of the ** indirect flag for the specified session object. ** ** The return value indicates the final state of the indirect flag: 0 if ** it is clear, or 1 if it is set. */ SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); /* ** CAPI3REF: Attach A Table To A Session Object ** ** If argument zTab is not NULL, then it is the name of a table to attach ** to the session object passed as the first argument. All subsequent changes ** made to the table while the session object is enabled will be recorded. See ** documentation for [sqlite3session_changeset()] for further details. ** ** Or, if argument zTab is NULL, then changes are recorded for all tables ** in the database. If additional tables are added to the database (by ** executing "CREATE TABLE" statements) after this call is made, changes for ** the new tables are also recorded. ** ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly ** defined as part of their CREATE TABLE statement. It does not matter if the ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY ** KEY may consist of a single column, or may be a composite key. ** ** It is not an error if the named table does not exist in the database. Nor ** is it an error if the named table does not have a PRIMARY KEY. However, ** no changes will be recorded in either of these scenarios. ** ** Changes are not recorded for individual rows that have NULL values stored ** in one or more of their PRIMARY KEY columns. ** ** SQLITE_OK is returned if the call completes without error. Or, if an error ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. */ SQLITE_API int sqlite3session_attach( sqlite3_session *pSession, /* Session object */ const char *zTab /* Table name */ ); /* ** CAPI3REF: Set a table filter on a Session Object. ** ** The second argument (xFilter) is the "filter callback". For changes to rows ** in tables that are not attached to the Session object, the filter is called ** to determine whether changes to the table's rows should be tracked or not. ** If xFilter returns 0, changes is not tracked. Note that once a table is ** attached, xFilter will not be called again. */ SQLITE_API void sqlite3session_table_filter( sqlite3_session *pSession, /* Session object */ int(*xFilter)( void *pCtx, /* Copy of third arg to _filter_table() */ const char *zTab /* Table name */ ), void *pCtx /* First argument passed to xFilter */ ); /* ** CAPI3REF: Generate A Changeset From A Session Object ** ** Obtain a changeset containing changes to the tables attached to the ** session object passed as the first argument. If successful, ** set *ppChangeset to point to a buffer containing the changeset ** and *pnChangeset to the size of the changeset in bytes before returning ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to ** zero and return an SQLite error code. ** ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes, ** each representing a change to a single row of an attached table. An INSERT ** change contains the values of each field of a new database row. A DELETE ** contains the original values of each field of a deleted database row. An ** UPDATE change contains the original values of each field of an updated ** database row along with the updated values for each updated non-primary-key ** column. It is not possible for an UPDATE change to represent a change that ** modifies the values of primary key columns. If such a change is made, it ** is represented in a changeset as a DELETE followed by an INSERT. ** ** Changes are not recorded for rows that have NULL values stored in one or ** more of their PRIMARY KEY columns. If such a row is inserted or deleted, ** no corresponding change is present in the changesets returned by this ** function. If an existing row with one or more NULL values stored in ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL, ** only an INSERT is appears in the changeset. Similarly, if an existing row ** with non-NULL PRIMARY KEY values is updated so that one or more of its ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a ** DELETE change only. ** ** The contents of a changeset may be traversed using an iterator created ** using the [sqlite3changeset_start()] API. A changeset may be applied to ** a database with a compatible schema using the [sqlite3changeset_apply()] ** API. ** ** Within a changeset generated by this function, all changes related to a ** single table are grouped together. In other words, when iterating through ** a changeset or when applying a changeset to a database, all changes related ** to a single table are processed before moving on to the next table. Tables ** are sorted in the same order in which they were attached (or auto-attached) ** to the sqlite3_session object. The order in which the changes related to ** a single table are stored is undefined. ** ** Following a successful call to this function, it is the responsibility of ** the caller to eventually free the buffer that *ppChangeset points to using ** [sqlite3_free()]. ** ** <h3>Changeset Generation</h3> ** ** Once a table has been attached to a session object, the session object ** records the primary key values of all new rows inserted into the table. ** It also records the original primary key and other column values of any ** deleted or updated rows. For each unique primary key value, data is only ** recorded once - the first time a row with said primary key is inserted, ** updated or deleted in the lifetime of the session. ** ** There is one exception to the previous paragraph: when a row is inserted, ** updated or deleted, if one or more of its primary key columns contain a ** NULL value, no record of the change is made. ** ** The session object therefore accumulates two types of records - those ** that consist of primary key values only (created when the user inserts ** a new record) and those that consist of the primary key values and the ** original values of other table columns (created when the users deletes ** or updates a record). ** ** When this function is called, the requested changeset is created using ** both the accumulated records and the current contents of the database ** file. Specifically: ** ** <ul> ** <li> For each record generated by an insert, the database is queried ** for a row with a matching primary key. If one is found, an INSERT ** change is added to the changeset. If no such row is found, no change ** is added to the changeset. ** ** <li> For each record generated by an update or delete, the database is ** queried for a row with a matching primary key. If such a row is ** found and one or more of the non-primary key fields have been ** modified from their original values, an UPDATE change is added to ** the changeset. Or, if no such row is found in the table, a DELETE ** change is added to the changeset. If there is a row with a matching ** primary key in the database, but all fields contain their original ** values, no change is added to the changeset. ** </ul> ** ** This means, amongst other things, that if a row is inserted and then later ** deleted while a session object is active, neither the insert nor the delete ** will be present in the changeset. Or if a row is deleted and then later a ** row with the same primary key values inserted while a session object is ** active, the resulting changeset will contain an UPDATE change instead of ** a DELETE and an INSERT. ** ** When a session object is disabled (see the [sqlite3session_enable()] API), ** it does not accumulate records when rows are inserted, updated or deleted. ** This may appear to have some counter-intuitive effects if a single row ** is written to more than once during a session. For example, if a row ** is inserted while a session object is enabled, then later deleted while ** the same session object is disabled, no INSERT record will appear in the ** changeset, even though the delete took place while the session was disabled. ** Or, if one field of a row is updated while a session is disabled, and ** another field of the same row is updated while the session is enabled, the ** resulting changeset will contain an UPDATE change that updates both fields. */ SQLITE_API int sqlite3session_changeset( sqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ); /* ** CAPI3REF: Load The Difference Between Tables Into A Session ** ** If it is not already attached to the session object passed as the first ** argument, this function attaches table zTbl in the same manner as the ** [sqlite3session_attach()] function. If zTbl does not exist, or if it ** does not have a primary key, this function is a no-op (but does not return ** an error). ** ** Argument zFromDb must be the name of a database ("main", "temp" etc.) ** attached to the same database handle as the session object that contains ** a table compatible with the table attached to the session by this function. ** A table is considered compatible if it: ** ** <ul> ** <li> Has the same name, ** <li> Has the same set of columns declared in the same order, and ** <li> Has the same PRIMARY KEY definition. ** </ul> ** ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables ** are compatible but do not have any PRIMARY KEY columns, it is not an error ** but no changes are added to the session object. As with other session ** APIs, tables without PRIMARY KEYs are simply ignored. ** ** This function adds a set of changes to the session object that could be ** used to update the table in database zFrom (call this the "from-table") ** so that its content is the same as the table attached to the session ** object (call this the "to-table"). Specifically: ** ** <ul> ** <li> For each row (primary key) that exists in the to-table but not in ** the from-table, an INSERT record is added to the session object. ** ** <li> For each row (primary key) that exists in the to-table but not in ** the from-table, a DELETE record is added to the session object. ** ** <li> For each row (primary key) that exists in both tables, but features ** different non-PK values in each, an UPDATE record is added to the ** session. ** </ul> ** ** To clarify, if this function is called and then a changeset constructed ** using [sqlite3session_changeset()], then after applying that changeset to ** database zFrom the contents of the two compatible tables would be ** identical. ** ** It an error if database zFrom does not exist or does not contain the ** required compatible table. ** ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to free this buffer using ** sqlite3_free(). */ SQLITE_API int sqlite3session_diff( sqlite3_session *pSession, const char *zFromDb, const char *zTbl, char **pzErrMsg ); /* ** CAPI3REF: Generate A Patchset From A Session Object ** ** The differences between a patchset and a changeset are that: ** ** <ul> ** <li> DELETE records consist of the primary key fields only. The ** original values of other fields are omitted. ** <li> The original values of any modified fields are omitted from ** UPDATE records. ** </ul> ** ** A patchset blob may be used with up to date versions of all ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, ** attempting to use a patchset blob with old versions of the ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. ** ** Because the non-primary key "old.*" fields are omitted, no ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset ** is passed to the sqlite3changeset_apply() API. Other conflict types work ** in the same way as for changesets. ** ** Changes within a patchset are ordered in the same way as for changesets ** generated by the sqlite3session_changeset() function (i.e. all changes for ** a single table are grouped together, tables appear in the order in which ** they were attached to the session object). */ SQLITE_API int sqlite3session_patchset( sqlite3_session *pSession, /* Session object */ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ void **ppPatchset /* OUT: Buffer containing changeset */ ); /* ** CAPI3REF: Test if a changeset has recorded any changes. ** ** Return non-zero if no changes to attached tables have been recorded by ** the session object passed as the first argument. Otherwise, if one or ** more changes have been recorded, return zero. ** ** Even if this function returns zero, it is possible that calling ** [sqlite3session_changeset()] on the session handle may still return a ** changeset that contains no changes. This can happen when a row in ** an attached table is modified and then later on the original values ** are restored. However, if this function returns non-zero, then it is ** guaranteed that a call to sqlite3session_changeset() will return a ** changeset containing zero changes. */ SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession); /* ** CAPI3REF: Create An Iterator To Traverse A Changeset ** ** Create an iterator used to iterate through the contents of a changeset. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK ** is returned. Otherwise, if an error occurs, *pp is set to zero and an ** SQLite error code is returned. ** ** The following functions can be used to advance and query a changeset ** iterator created by this function: ** ** <ul> ** <li> [sqlite3changeset_next()] ** <li> [sqlite3changeset_op()] ** <li> [sqlite3changeset_new()] ** <li> [sqlite3changeset_old()] ** </ul> ** ** It is the responsibility of the caller to eventually destroy the iterator ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the ** changeset (pChangeset) must remain valid until after the iterator is ** destroyed. ** ** Assuming the changeset blob was created by one of the ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or ** [sqlite3changeset_invert()] functions, all changes within the changeset ** that apply to a single table are grouped together. This means that when ** an application iterates through a changeset using an iterator created by ** this function, all changes that relate to a single table are visited ** consecutively. There is no chance that the iterator will visit a change ** the applies to table X, then one for table Y, and then later on visit ** another change for table X. */ SQLITE_API int sqlite3changeset_start( sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ int nChangeset, /* Size of changeset blob in bytes */ void *pChangeset /* Pointer to blob containing changeset */ ); /* ** CAPI3REF: Advance A Changeset Iterator ** ** This function may only be used with iterators created by function ** [sqlite3changeset_start()]. If it is called on an iterator passed to ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE ** is returned and the call has no effect. ** ** Immediately after an iterator is created by sqlite3changeset_start(), it ** does not point to any change in the changeset. Assuming the changeset ** is not empty, the first call to this function advances the iterator to ** point to the first change in the changeset. Each subsequent call advances ** the iterator to point to the next change in the changeset (if any). If ** no error occurs and the iterator points to a valid change after a call ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. ** Otherwise, if all changes in the changeset have already been visited, ** SQLITE_DONE is returned. ** ** If an error occurs, an SQLite error code is returned. Possible error ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or ** SQLITE_NOMEM. */ SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter); /* ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this ** is not the case, this function returns [SQLITE_MISUSE]. ** ** If argument pzTab is not NULL, then *pzTab is set to point to a ** nul-terminated utf-8 encoded string containing the name of the table ** affected by the current change. The buffer remains valid until either ** sqlite3changeset_next() is called on the iterator or until the ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is ** set to the number of columns in the table affected by the change. If ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change ** is an indirect change, or false (0) otherwise. See the documentation for ** [sqlite3session_indirect()] for a description of direct and indirect ** changes. Finally, if pOp is not NULL, then *pOp is set to one of ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the ** type of change that the iterator currently points to. ** ** If no error occurs, SQLITE_OK is returned. If an error does occur, an ** SQLite error code is returned. The values of the output variables may not ** be trusted in this case. */ SQLITE_API int sqlite3changeset_op( sqlite3_changeset_iter *pIter, /* Iterator object */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ int *pbIndirect /* OUT: True for an 'indirect' change */ ); /* ** CAPI3REF: Obtain The Primary Key Definition Of A Table ** ** For each modified table, a changeset includes the following: ** ** <ul> ** <li> The number of columns in the table, and ** <li> Which of those columns make up the tables PRIMARY KEY. ** </ul> ** ** This function is used to find which columns comprise the PRIMARY KEY of ** the table modified by the change that iterator pIter currently points to. ** If successful, *pabPK is set to point to an array of nCol entries, where ** nCol is the number of columns in the table. Elements of *pabPK are set to ** 0x01 if the corresponding column is part of the tables primary key, or ** 0x00 if it is not. ** ** If argument pnCol is not NULL, then *pnCol is set to the number of columns ** in the table. ** ** If this function is called when the iterator does not point to a valid ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise, ** SQLITE_OK is returned and the output variables populated as described ** above. */ SQLITE_API int sqlite3changeset_pk( sqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ); /* ** CAPI3REF: Obtain old.* Values From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the vector of ** original row values stored as part of the UPDATE or DELETE change and ** returns SQLITE_OK. The name of the function comes from the fact that this ** is similar to the "old.*" columns available to update or delete triggers. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ SQLITE_API int sqlite3changeset_old( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain new.* Values From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the vector of ** new row values stored as part of the UPDATE or INSERT change and ** returns SQLITE_OK. If the change is an UPDATE and does not include ** a new value for the requested column, *ppValue is set to NULL and ** SQLITE_OK returned. The name of the function comes from the fact that ** this is similar to the "new.*" columns available to update or delete ** triggers. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ SQLITE_API int sqlite3changeset_new( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator ** ** This function should only be used with iterator objects passed to a ** conflict-handler callback by [sqlite3changeset_apply()] with either ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue ** is set to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the ** "conflicting row" associated with the current conflict-handler callback ** and returns SQLITE_OK. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ SQLITE_API int sqlite3changeset_conflict( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: Value from conflicting row */ ); /* ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations ** ** This function may only be called with an iterator passed to an ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case ** it sets the output variable to the total number of known foreign key ** violations in the destination database and returns SQLITE_OK. ** ** In all other cases this function returns SQLITE_MISUSE. */ SQLITE_API int sqlite3changeset_fk_conflicts( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ); /* ** CAPI3REF: Finalize A Changeset Iterator ** ** This function is used to finalize an iterator allocated with ** [sqlite3changeset_start()]. ** ** This function should only be called on iterators created using the ** [sqlite3changeset_start()] function. If an application calls this ** function with an iterator passed to a conflict-handler by ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the ** call has no effect. ** ** If an error was encountered within a call to an sqlite3changeset_xxx() ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding ** to that error is returned by this function. Otherwise, SQLITE_OK is ** returned. This is to allow the following pattern (pseudo-code): ** ** sqlite3changeset_start(); ** while( SQLITE_ROW==sqlite3changeset_next() ){ ** // Do something with change. ** } ** rc = sqlite3changeset_finalize(); ** if( rc!=SQLITE_OK ){ ** // An error has occurred ** } */ SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); /* ** CAPI3REF: Invert A Changeset ** ** This function is used to "invert" a changeset object. Applying an inverted ** changeset to a database reverses the effects of applying the uninverted ** changeset. Specifically: ** ** <ul> ** <li> Each DELETE change is changed to an INSERT, and ** <li> Each INSERT change is changed to a DELETE, and ** <li> For each UPDATE change, the old.* and new.* values are exchanged. ** </ul> ** ** This function does not change the order in which changes appear within ** the changeset. It merely reverses the sense of each individual change. ** ** If successful, a pointer to a buffer containing the inverted changeset ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are ** zeroed and an SQLite error code returned. ** ** It is the responsibility of the caller to eventually call sqlite3_free() ** on the *ppOut pointer to free the buffer allocation following a successful ** call to this function. ** ** WARNING/TODO: This function currently assumes that the input is a valid ** changeset. If it is not, the results are undefined. */ SQLITE_API int sqlite3changeset_invert( int nIn, const void *pIn, /* Input changeset */ int *pnOut, void **ppOut /* OUT: Inverse of input */ ); /* ** CAPI3REF: Concatenate Two Changeset Objects ** ** This function is used to concatenate two changesets, A and B, into a ** single changeset. The result is a changeset equivalent to applying ** changeset A followed by changeset B. ** ** This function combines the two input changesets using an ** sqlite3_changegroup object. Calling it produces similar results as the ** following code fragment: ** ** sqlite3_changegroup *pGrp; ** rc = sqlite3_changegroup_new(&pGrp); ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA); ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB); ** if( rc==SQLITE_OK ){ ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); ** }else{ ** *ppOut = 0; ** *pnOut = 0; ** } ** ** Refer to the sqlite3_changegroup documentation below for details. */ SQLITE_API int sqlite3changeset_concat( int nA, /* Number of bytes in buffer pA */ void *pA, /* Pointer to buffer containing changeset A */ int nB, /* Number of bytes in buffer pB */ void *pB, /* Pointer to buffer containing changeset B */ int *pnOut, /* OUT: Number of bytes in output changeset */ void **ppOut /* OUT: Buffer containing output changeset */ ); /* ** CAPI3REF: Changegroup Handle */ typedef struct sqlite3_changegroup sqlite3_changegroup; /* ** CAPI3REF: Create A New Changegroup Object ** ** An sqlite3_changegroup object is used to combine two or more changesets ** (or patchsets) into a single changeset (or patchset). A single changegroup ** object may combine changesets or patchsets, but not both. The output is ** always in the same format as the input. ** ** If successful, this function returns SQLITE_OK and populates (*pp) with ** a pointer to a new sqlite3_changegroup object before returning. The caller ** should eventually free the returned object using a call to ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. ** ** The usual usage pattern for an sqlite3_changegroup object is as follows: ** ** <ul> ** <li> It is created using a call to sqlite3changegroup_new(). ** ** <li> Zero or more changesets (or patchsets) are added to the object ** by calling sqlite3changegroup_add(). ** ** <li> The result of combining all input changesets together is obtained ** by the application via a call to sqlite3changegroup_output(). ** ** <li> The object is deleted using a call to sqlite3changegroup_delete(). ** </ul> ** ** Any number of calls to add() and output() may be made between the calls to ** new() and delete(), and in any order. ** ** As well as the regular sqlite3changegroup_add() and ** sqlite3changegroup_output() functions, also available are the streaming ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). */ int sqlite3changegroup_new(sqlite3_changegroup **pp); /* ** CAPI3REF: Add A Changeset To A Changegroup ** ** Add all changes within the changeset (or patchset) in buffer pData (size ** nData bytes) to the changegroup. ** ** If the buffer contains a patchset, then all prior calls to this function ** on the same changegroup object must also have specified patchsets. Or, if ** the buffer contains a changeset, so must have the earlier calls to this ** function. Otherwise, SQLITE_ERROR is returned and no changes are added ** to the changegroup. ** ** Rows within the changeset and changegroup are identified by the values in ** their PRIMARY KEY columns. A change in the changeset is considered to ** apply to the same row as a change already present in the changegroup if ** the two rows have the same primary key. ** ** Changes to rows that do not already appear in the changegroup are ** simply copied into it. Or, if both the new changeset and the changegroup ** contain changes that apply to a single row, the final contents of the ** changegroup depends on the type of each change, as follows: ** ** <table border=1 style="margin-left:8ex;margin-right:8ex"> ** <tr><th style="white-space:pre">Existing Change </th> ** <th style="white-space:pre">New Change </th> ** <th>Output Change ** <tr><td>INSERT <td>INSERT <td> ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. ** <tr><td>INSERT <td>UPDATE <td> ** The INSERT change remains in the changegroup. The values in the ** INSERT change are modified as if the row was inserted by the ** existing change and then updated according to the new change. ** <tr><td>INSERT <td>DELETE <td> ** The existing INSERT is removed from the changegroup. The DELETE is ** not added. ** <tr><td>UPDATE <td>INSERT <td> ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. ** <tr><td>UPDATE <td>UPDATE <td> ** The existing UPDATE remains within the changegroup. It is amended ** so that the accompanying values are as if the row was updated once ** by the existing change and then again by the new change. ** <tr><td>UPDATE <td>DELETE <td> ** The existing UPDATE is replaced by the new DELETE within the ** changegroup. ** <tr><td>DELETE <td>INSERT <td> ** If one or more of the column values in the row inserted by the ** new change differ from those in the row deleted by the existing ** change, the existing DELETE is replaced by an UPDATE within the ** changegroup. Otherwise, if the inserted row is exactly the same ** as the deleted row, the existing DELETE is simply discarded. ** <tr><td>DELETE <td>UPDATE <td> ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. ** <tr><td>DELETE <td>DELETE <td> ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. ** </table> ** ** If the new changeset contains changes to a table that is already present ** in the changegroup, then the number of columns and the position of the ** primary key columns for the table must be consistent. If this is not the ** case, this function fails with SQLITE_SCHEMA. If the input changeset ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is ** returned. Or, if an out-of-memory condition occurs during processing, this ** function returns SQLITE_NOMEM. In all cases, if an error occurs the ** final contents of the changegroup is undefined. ** ** If no error occurs, SQLITE_OK is returned. */ int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); /* ** CAPI3REF: Obtain A Composite Changeset From A Changegroup ** ** Obtain a buffer containing a changeset (or patchset) representing the ** current contents of the changegroup. If the inputs to the changegroup ** were themselves changesets, the output is a changeset. Or, if the ** inputs were patchsets, the output is also a patchset. ** ** As with the output of the sqlite3session_changeset() and ** sqlite3session_patchset() functions, all changes related to a single ** table are grouped together in the output of this function. Tables appear ** in the same order as for the very first changeset added to the changegroup. ** If the second or subsequent changesets added to the changegroup contain ** changes for tables that do not appear in the first changeset, they are ** appended onto the end of the output changeset, again in the order in ** which they are first encountered. ** ** If an error occurs, an SQLite error code is returned and the output ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK ** is returned and the output variables are set to the size of and a ** pointer to the output buffer, respectively. In this case it is the ** responsibility of the caller to eventually free the buffer using a ** call to sqlite3_free(). */ int sqlite3changegroup_output( sqlite3_changegroup*, int *pnData, /* OUT: Size of output buffer in bytes */ void **ppData /* OUT: Pointer to output buffer */ ); /* ** CAPI3REF: Delete A Changegroup Object */ void sqlite3changegroup_delete(sqlite3_changegroup*); /* ** CAPI3REF: Apply A Changeset To A Database ** ** Apply a changeset to a database. This function attempts to update the ** "main" database attached to handle db with the changes found in the ** changeset passed via the second and third arguments. ** ** The fourth argument (xFilter) passed to this function is the "filter ** callback". If it is not NULL, then for each table affected by at least one ** change in the changeset, the filter callback is invoked with ** the table name as the second argument, and a copy of the context pointer ** passed as the sixth argument to this function as the first. If the "filter ** callback" returns zero, then no attempt is made to apply any changes to ** the table. Otherwise, if the return value is non-zero or the xFilter ** argument to this function is NULL, all changes related to the table are ** attempted. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is ** considered compatible if all of the following are true: ** ** <ul> ** <li> The table has the same name as the name recorded in the ** changeset, and ** <li> The table has at least as many columns as recorded in the ** changeset, and ** <li> The table has primary key columns in the same position as ** recorded in the changeset. ** </ul> ** ** If there is no compatible table, it is not an error, but none of the ** changes associated with the table are applied. A warning message is issued ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made ** to modify the table contents according to the UPDATE, INSERT or DELETE ** change. If a change cannot be applied cleanly, the conflict handler ** function passed as the fifth argument to sqlite3changeset_apply() may be ** invoked. A description of exactly when the conflict handler is invoked for ** each type of change is below. ** ** Unlike the xFilter argument, xConflict may not be passed NULL. The results ** of passing anything other than a valid function pointer as the xConflict ** argument are undefined. ** ** Each time the conflict handler function is invoked, it must return one ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned ** if the second argument passed to the conflict handler is either ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler ** returns an illegal value, any changes already made are rolled back and ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different ** actions are taken by sqlite3changeset_apply() depending on the value ** returned by each invocation of the conflict-handler function. Refer to ** the documentation for the three ** [SQLITE_CHANGESET_OMIT|available return values] for details. ** ** <dl> ** <dt>DELETE Changes<dd> ** For each DELETE change, this function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in ** the changeset the row is deleted from the target database. ** ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from the original ** row value stored in the changeset, the conflict-handler function is ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the ** database table has more columns than are recorded in the changeset, ** only the values of those non-primary key fields are compared against ** the current database contents - any trailing database table columns ** are ignored. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] ** passed as the second argument. ** ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT ** (which can only happen if a foreign key constraint is violated), the ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT] ** passed as the second argument. This includes the case where the DELETE ** operation is attempted because an earlier call to the conflict handler ** function returned [SQLITE_CHANGESET_REPLACE]. ** ** <dt>INSERT Changes<dd> ** For each INSERT change, an attempt is made to insert the new row into ** the database. If the changeset row contains fewer fields than the ** database table, the trailing fields are populated with their default ** values. ** ** If the attempt to insert the row fails because the database already ** contains a row with the same primary key values, the conflict handler ** function is invoked with the second argument set to ** [SQLITE_CHANGESET_CONFLICT]. ** ** If the attempt to insert the row fails because of some other constraint ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT]. ** This includes the case where the INSERT operation is re-attempted because ** an earlier call to the conflict handler function returned ** [SQLITE_CHANGESET_REPLACE]. ** ** <dt>UPDATE Changes<dd> ** For each UPDATE change, this function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all modified non-primary key columns also match the values ** stored in the changeset the row is updated within the target database. ** ** If a row with matching primary key values is found, but one or more of ** the modified non-primary key fields contains a value different from an ** original row value stored in the changeset, the conflict-handler function ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since ** UPDATE changes only contain values for non-primary key fields that are ** to be modified, only those fields need to match the original values to ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] ** passed as the second argument. ** ** If the UPDATE operation is attempted, but SQLite returns ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument. ** This includes the case where the UPDATE operation is attempted after ** an earlier call to the conflict handler function returned ** [SQLITE_CHANGESET_REPLACE]. ** </dl> ** ** It is safe to execute SQL statements, including those that write to the ** table that the callback related to, from within the xConflict callback. ** This can be used to further customize the applications conflict ** resolution strategy. ** ** All changes made by this function are enclosed in a savepoint transaction. ** If any other error (aside from a constraint failure when attempting to ** write to the target database) occurs, then the savepoint transaction is ** rolled back, restoring the target database to its original state, and an ** SQLite error code returned. */ SQLITE_API int sqlite3changeset_apply( sqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); /* ** CAPI3REF: Constants Passed To The Conflict Handler ** ** Values that may be passed as the second argument to a conflict-handler. ** ** <dl> ** <dt>SQLITE_CHANGESET_DATA<dd> ** The conflict handler is invoked with CHANGESET_DATA as the second argument ** when processing a DELETE or UPDATE change if a row with the required ** PRIMARY KEY fields is present in the database, but one or more other ** (non primary-key) fields modified by the update do not contain the ** expected "before" values. ** ** The conflicting row, in this case, is the database row with the matching ** primary key. ** ** <dt>SQLITE_CHANGESET_NOTFOUND<dd> ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second ** argument when processing a DELETE or UPDATE change if a row with the ** required PRIMARY KEY fields is not present in the database. ** ** There is no conflicting row in this case. The results of invoking the ** sqlite3changeset_conflict() API are undefined. ** ** <dt>SQLITE_CHANGESET_CONFLICT<dd> ** CHANGESET_CONFLICT is passed as the second argument to the conflict ** handler while processing an INSERT change if the operation would result ** in duplicate primary key values. ** ** The conflicting row in this case is the database row with the matching ** primary key. ** ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd> ** If foreign key handling is enabled, and applying a changeset leaves the ** database in a state containing foreign key violations, the conflict ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument ** exactly once before the changeset is committed. If the conflict handler ** returns CHANGESET_OMIT, the changes, including those that caused the ** foreign key constraint violation, are committed. Or, if it returns ** CHANGESET_ABORT, the changeset is rolled back. ** ** No current or conflicting row information is provided. The only function ** it is possible to call on the supplied sqlite3_changeset_iter handle ** is sqlite3changeset_fk_conflicts(). ** ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd> ** If any other constraint violation occurs while applying a change (i.e. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is ** invoked with CHANGESET_CONSTRAINT as the second argument. ** ** There is no conflicting row in this case. The results of invoking the ** sqlite3changeset_conflict() API are undefined. ** ** </dl> */ #define SQLITE_CHANGESET_DATA 1 #define SQLITE_CHANGESET_NOTFOUND 2 #define SQLITE_CHANGESET_CONFLICT 3 #define SQLITE_CHANGESET_CONSTRAINT 4 #define SQLITE_CHANGESET_FOREIGN_KEY 5 /* ** CAPI3REF: Constants Returned By The Conflict Handler ** ** A conflict handler callback must return one of the following three values. ** ** <dl> ** <dt>SQLITE_CHANGESET_OMIT<dd> ** If a conflict handler returns this value no special action is taken. The ** change that caused the conflict is not applied. The session module ** continues to the next change in the changeset. ** ** <dt>SQLITE_CHANGESET_REPLACE<dd> ** This value may only be returned if the second argument to the conflict ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this ** is not the case, any changes applied so far are rolled back and the ** call to sqlite3changeset_apply() returns SQLITE_MISUSE. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict ** handler, then the conflicting row is either updated or deleted, depending ** on the type of change. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict ** handler, then the conflicting row is removed from the database and a ** second attempt to apply the change is made. If this second attempt fails, ** the original row is restored to the database before continuing. ** ** <dt>SQLITE_CHANGESET_ABORT<dd> ** If this value is returned, any changes applied so far are rolled back ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. ** </dl> */ #define SQLITE_CHANGESET_OMIT 0 #define SQLITE_CHANGESET_REPLACE 1 #define SQLITE_CHANGESET_ABORT 2 /* ** CAPI3REF: Streaming Versions of API functions. ** ** The six streaming API xxx_strm() functions serve similar purposes to the ** corresponding non-streaming API functions: ** ** <table border=1 style="margin-left:8ex;margin-right:8ex"> ** <tr><th>Streaming function<th>Non-streaming equivalent</th> ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply] ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat] ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert] ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start] ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset] ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset] ** </table> ** ** Non-streaming functions that accept changesets (or patchsets) as input ** require that the entire changeset be stored in a single buffer in memory. ** Similarly, those that return a changeset or patchset do so by returning ** a pointer to a single large buffer allocated using sqlite3_malloc(). ** Normally this is convenient. However, if an application running in a ** low-memory environment is required to handle very large changesets, the ** large contiguous memory allocations required can become onerous. ** ** In order to avoid this problem, instead of a single large buffer, input ** is passed to a streaming API functions by way of a callback function that ** the sessions module invokes to incrementally request input data as it is ** required. In all cases, a pair of API function parameters such as ** ** <pre> ** &nbsp; int nChangeset, ** &nbsp; void *pChangeset, ** </pre> ** ** Is replaced by: ** ** <pre> ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData), ** &nbsp; void *pIn, ** </pre> ** ** Each time the xInput callback is invoked by the sessions module, the first ** argument passed is a copy of the supplied pIn context pointer. The second ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no ** error occurs the xInput method should copy up to (*pnData) bytes of data ** into the buffer and set (*pnData) to the actual number of bytes copied ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) ** should be set to zero to indicate this. Or, if an error occurs, an SQLite ** error code should be returned. In all cases, if an xInput callback returns ** an error, all processing is abandoned and the streaming API function ** returns a copy of the error code to the caller. ** ** In the case of sqlite3changeset_start_strm(), the xInput callback may be ** invoked by the sessions module at any point during the lifetime of the ** iterator. If such an xInput callback returns an error, the iterator enters ** an error state, whereby all subsequent calls to iterator functions ** immediately fail with the same error code as returned by xInput. ** ** Similarly, streaming API functions that return changesets (or patchsets) ** return them in chunks by way of a callback function instead of via a ** pointer to a single large buffer. In this case, a pair of parameters such ** as: ** ** <pre> ** &nbsp; int *pnChangeset, ** &nbsp; void **ppChangeset, ** </pre> ** ** Is replaced by: ** ** <pre> ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData), ** &nbsp; void *pOut ** </pre> ** ** The xOutput callback is invoked zero or more times to return data to ** the application. The first parameter passed to each call is a copy of the ** pOut pointer supplied by the application. The second parameter, pData, ** points to a buffer nData bytes in size containing the chunk of output ** data being returned. If the xOutput callback successfully processes the ** supplied data, it should return SQLITE_OK to indicate success. Otherwise, ** it should return some other SQLite error code. In this case processing ** is immediately abandoned and the streaming API function returns a copy ** of the xOutput error code to the application. ** ** The sessions module never invokes an xOutput callback with the third ** parameter set to a value less than or equal to zero. Other than this, ** no guarantees are made as to the size of the chunks of data returned. */ SQLITE_API int sqlite3changeset_apply_strm( sqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); SQLITE_API int sqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), void *pInB, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); SQLITE_API int sqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); SQLITE_API int sqlite3changeset_start_strm( sqlite3_changeset_iter **pp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); SQLITE_API int sqlite3session_changeset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); SQLITE_API int sqlite3session_patchset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3changegroup_add_strm(sqlite3_changegroup*, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); int sqlite3changegroup_output_strm(sqlite3_changegroup*, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); /* ** Make sure we can call this stuff from C++. */ #ifdef __cplusplus } #endif #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */ /******** End of sqlite3session.h *********/ /******** Begin file fts5.h *********/ /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Interfaces to extend FTS5. Using the interfaces defined in this file, ** FTS5 may be extended with: ** ** * custom tokenizers, and ** * custom auxiliary functions. */ #ifndef _FTS5_H #define _FTS5_H #ifdef __cplusplus extern "C" { #endif /************************************************************************* ** CUSTOM AUXILIARY FUNCTIONS ** ** Virtual table implementations may overload SQL functions by implementing ** the sqlite3_module.xFindFunction() method. */ typedef struct Fts5ExtensionApi Fts5ExtensionApi; typedef struct Fts5Context Fts5Context; typedef struct Fts5PhraseIter Fts5PhraseIter; typedef void (*fts5_extension_function)( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ sqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ sqlite3_value **apVal /* Array of trailing arguments */ ); struct Fts5PhraseIter { const unsigned char *a; const unsigned char *b; }; /* ** EXTENSION API FUNCTIONS ** ** xUserData(pFts): ** Return a copy of the context pointer the extension function was ** registered with. ** ** xColumnTotalSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the FTS5 table. Or, if iCol is ** non-negative but less than the number of columns in the table, return ** the total number of tokens in column iCol, considering all rows in ** the FTS5 table. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** xColumnCount(pFts): ** Return the number of columns in the table. ** ** xColumnSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the current row. Or, if iCol is ** non-negative but less than the number of columns in the table, set ** *pnToken to the number of tokens in column iCol of the current row. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** This function may be quite inefficient if used with an FTS5 table ** created with the "columnsize=0" option. ** ** xColumnText: ** This function attempts to retrieve the text of column iCol of the ** current document. If successful, (*pz) is set to point to a buffer ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise, ** if an error occurs, an SQLite error code is returned and the final values ** of (*pz) and (*pn) are undefined. ** ** xPhraseCount: ** Returns the number of phrases in the current query expression. ** ** xPhraseSize: ** Returns the number of tokens in phrase iPhrase of the query. Phrases ** are numbered starting from zero. ** ** xInstCount: ** Set *pnInst to the total number of occurrences of all phrases within ** the query within the current row. Return SQLITE_OK if successful, or ** an error code (i.e. SQLITE_NOMEM) if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always returns 0. ** ** xInst: ** Query for the details of phrase match iIdx within the current row. ** Phrase matches are numbered starting from zero, so the iIdx argument ** should be greater than or equal to zero and smaller than the value ** output by xInstCount(). ** ** Usually, output parameter *piPhrase is set to the phrase number, *piCol ** to the column in which it occurs and *piOff the token offset of the ** first token of the phrase. The exception is if the table was created ** with the offsets=0 option specified. In this case *piOff is always ** set to -1. ** ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) ** if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. ** ** xRowid: ** Returns the rowid of the current row. ** ** xTokenize: ** Tokenize text using the tokenizer belonging to the FTS5 table. ** ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback): ** This API function is used to query the FTS table for phrase iPhrase ** of the current query. Specifically, a query equivalent to: ** ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid ** ** with $p set to a phrase equivalent to the phrase iPhrase of the ** current query is executed. Any column filter that applies to ** phrase iPhrase of the current query is included in $p. For each ** row visited, the callback function passed as the fourth argument ** is invoked. The context and API objects passed to the callback ** function may be used to access the properties of each matched row. ** Invoking Api.xUserData() returns a copy of the pointer passed as ** the third argument to pUserData. ** ** If the callback function returns any value other than SQLITE_OK, the ** query is abandoned and the xQueryPhrase function returns immediately. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK. ** Otherwise, the error code is propagated upwards. ** ** If the query runs to completion without incident, SQLITE_OK is returned. ** Or, if some error occurs before the query completes or is aborted by ** the callback, an SQLite error code is returned. ** ** ** xSetAuxdata(pFts5, pAux, xDelete) ** ** Save the pointer passed as the second argument as the extension functions ** "auxiliary data". The pointer may then be retrieved by the current or any ** future invocation of the same fts5 extension function made as part of ** of the same MATCH query using the xGetAuxdata() API. ** ** Each extension function is allocated a single auxiliary data slot for ** each FTS query (MATCH expression). If the extension function is invoked ** more than once for a single FTS query, then all invocations share a ** single auxiliary data context. ** ** If there is already an auxiliary data pointer when this function is ** invoked, then it is replaced by the new pointer. If an xDelete callback ** was specified along with the original pointer, it is invoked at this ** point. ** ** The xDelete callback, if one is specified, is also invoked on the ** auxiliary data pointer after the FTS5 query has finished. ** ** If an error (e.g. an OOM condition) occurs within this function, an ** the auxiliary data is set to NULL and an error code returned. If the ** xDelete parameter was not NULL, it is invoked on the auxiliary data ** pointer before returning. ** ** ** xGetAuxdata(pFts5, bClear) ** ** Returns the current auxiliary data pointer for the fts5 extension ** function. See the xSetAuxdata() method for details. ** ** If the bClear argument is non-zero, then the auxiliary data is cleared ** (set to NULL) before this function returns. In this case the xDelete, ** if any, is not invoked. ** ** ** xRowCount(pFts5, pnRow) ** ** This function is used to retrieve the total number of rows in the table. ** In other words, the same value that would be returned by: ** ** SELECT count(*) FROM ftstable; ** ** xPhraseFirst() ** This function is used, along with type Fts5PhraseIter and the xPhraseNext ** method, to iterate through all instances of a single query phrase within ** the current row. This is the same information as is accessible via the ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient ** to use, this API may be faster under some circumstances. To iterate ** through instances of phrase iPhrase, use the following code: ** ** Fts5PhraseIter iter; ** int iCol, iOff; ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff); ** iCol>=0; ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff) ** ){ ** // An instance of phrase iPhrase at offset iOff of column iCol ** } ** ** The Fts5PhraseIter structure is defined above. Applications should not ** modify this structure directly - it should only be used as shown above ** with the xPhraseFirst() and xPhraseNext() API methods (and by ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below). ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always iterates ** through an empty set (all calls to xPhraseFirst() set iCol to -1). ** ** xPhraseNext() ** See xPhraseFirst above. ** ** xPhraseFirstColumn() ** This function and xPhraseNextColumn() are similar to the xPhraseFirst() ** and xPhraseNext() APIs described above. The difference is that instead ** of iterating through all instances of a phrase in the current row, these ** APIs are used to iterate through the set of columns in the current row ** that contain one or more instances of a specified phrase. For example: ** ** Fts5PhraseIter iter; ** int iCol; ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol); ** iCol>=0; ** pApi->xPhraseNextColumn(pFts, &iter, &iCol) ** ){ ** // Column iCol contains at least one instance of phrase iPhrase ** } ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" option. If the FTS5 table is created with either ** "detail=none" "content=" option (i.e. if it is a contentless table), ** then this API always iterates through an empty set (all calls to ** xPhraseFirstColumn() set iCol to -1). ** ** The information accessed using this API and its companion ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext ** (or xInst/xInstCount). The chief advantage of this API is that it is ** significantly more efficient than those alternatives when used with ** "detail=column" tables. ** ** xPhraseNextColumn() ** See xPhraseFirstColumn above. */ struct Fts5ExtensionApi { int iVersion; /* Currently always set to 3 */ void *(*xUserData)(Fts5Context*); int (*xColumnCount)(Fts5Context*); int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); int (*xTokenize)(Fts5Context*, const char *pText, int nText, /* Text to tokenize */ void *pCtx, /* Context passed to xToken() */ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ); int (*xPhraseCount)(Fts5Context*); int (*xPhraseSize)(Fts5Context*, int iPhrase); int (*xInstCount)(Fts5Context*, int *pnInst); int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); sqlite3_int64 (*xRowid)(Fts5Context*); int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData, int(*)(const Fts5ExtensionApi*,Fts5Context*,void*) ); int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*)); void *(*xGetAuxdata)(Fts5Context*, int bClear); int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*); void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff); int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*); void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol); }; /* ** CUSTOM AUXILIARY FUNCTIONS *************************************************************************/ /************************************************************************* ** CUSTOM TOKENIZERS ** ** Applications may also register custom tokenizer types. A tokenizer ** is registered by providing fts5 with a populated instance of the ** following structure. All structure methods must be defined, setting ** any member of the fts5_tokenizer struct to NULL leads to undefined ** behaviour. The structure methods are expected to function as follows: ** ** xCreate: ** This function is used to allocate and initialize a tokenizer instance. ** A tokenizer instance is required to actually tokenize text. ** ** The first argument passed to this function is a copy of the (void*) ** pointer provided by the application when the fts5_tokenizer object ** was registered with FTS5 (the third argument to xCreateTokenizer()). ** The second and third arguments are an array of nul-terminated strings ** containing the tokenizer arguments, if any, specified following the ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used ** to create the FTS5 table. ** ** The final argument is an output variable. If successful, (*ppOut) ** should be set to point to the new tokenizer handle and SQLITE_OK ** returned. If an error occurs, some value other than SQLITE_OK should ** be returned. In this case, fts5 assumes that the final value of *ppOut ** is undefined. ** ** xDelete: ** This function is invoked to delete a tokenizer handle previously ** allocated using xCreate(). Fts5 guarantees that this function will ** be invoked exactly once for each successful call to xCreate(). ** ** xTokenize: ** This function is expected to tokenize the nText byte string indicated ** by argument pText. pText may or may not be nul-terminated. The first ** argument passed to this function is a pointer to an Fts5Tokenizer object ** returned by an earlier call to xCreate(). ** ** The second argument indicates the reason that FTS5 is requesting ** tokenization of the supplied text. This is always one of the following ** four values: ** ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into ** or removed from the FTS table. The tokenizer is being invoked to ** determine the set of tokens to add to (or delete from) the ** FTS index. ** ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed ** against the FTS index. The tokenizer is being called to tokenize ** a bareword or quoted string specified as part of the query. ** ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is ** followed by a "*" character, indicating that the last token ** returned by the tokenizer will be treated as a token prefix. ** ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to ** satisfy an fts5_api.xTokenize() request made by an auxiliary ** function. Or an fts5_api.xColumnSize() request made by the same ** on a columnsize=0 database. ** </ul> ** ** For each token in the input string, the supplied callback xToken() must ** be invoked. The first argument to it should be a copy of the pointer ** passed as the second argument to xTokenize(). The third and fourth ** arguments are a pointer to a buffer containing the token text, and the ** size of the token in bytes. The 4th and 5th arguments are the byte offsets ** of the first byte of and first byte immediately following the text from ** which the token is derived within the input. ** ** The second argument passed to the xToken() callback ("tflags") should ** normally be set to 0. The exception is if the tokenizer supports ** synonyms. In this case see the discussion below for details. ** ** FTS5 assumes the xToken() callback is invoked for each token in the ** order that they occur within the input text. ** ** If an xToken() callback returns any value other than SQLITE_OK, then ** the tokenization should be abandoned and the xTokenize() method should ** immediately return a copy of the xToken() return value. Or, if the ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally, ** if an error occurs with the xTokenize() implementation itself, it ** may abandon the tokenization and return any error code other than ** SQLITE_OK or SQLITE_DONE. ** ** SYNONYM SUPPORT ** ** Custom tokenizers may also support synonyms. Consider a case in which a ** user wishes to query for a phrase such as "first place". Using the ** built-in tokenizers, the FTS5 query 'first + place' will match instances ** of "first place" within the document set, but not alternative forms ** such as "1st place". In some applications, it would be better to match ** all instances of "first place" or "1st place" regardless of which form ** the user specified in the MATCH query text. ** ** There are several ways to approach this in FTS5: ** ** <ol><li> By mapping all synonyms to a single token. In this case, the ** In the above example, this means that the tokenizer returns the ** same token for inputs "first" and "1st". Say that token is in ** fact "first", so that when the user inserts the document "I won ** 1st place" entries are added to the index for tokens "i", "won", ** "first" and "place". If the user then queries for '1st + place', ** the tokenizer substitutes "first" for "1st" and the query works ** as expected. ** ** <li> By adding multiple synonyms for a single term to the FTS index. ** In this case, when tokenizing query text, the tokenizer may ** provide multiple synonyms for a single term within the document. ** FTS5 then queries the index for each synonym individually. For ** example, faced with the query: ** ** <codeblock> ** ... MATCH 'first place'</codeblock> ** ** the tokenizer offers both "1st" and "first" as synonyms for the ** first token in the MATCH query and FTS5 effectively runs a query ** similar to: ** ** <codeblock> ** ... MATCH '(first OR 1st) place'</codeblock> ** ** except that, for the purposes of auxiliary functions, the query ** still appears to contain just two phrases - "(first OR 1st)" ** being treated as a single phrase. ** ** <li> By adding multiple synonyms for a single term to the FTS index. ** Using this method, when tokenizing document text, the tokenizer ** provides multiple synonyms for each token. So that when a ** document such as "I won first place" is tokenized, entries are ** added to the FTS index for "i", "won", "first", "1st" and ** "place". ** ** This way, even if the tokenizer does not provide synonyms ** when tokenizing query text (it should not - to do would be ** inefficient), it doesn't matter if the user queries for ** 'first + place' or '1st + place', as there are entires in the ** FTS index corresponding to both forms of the first token. ** </ol> ** ** Whether it is parsing document or query text, any call to xToken that ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit ** is considered to supply a synonym for the previous token. For example, ** when parsing the document "I won first place", a tokenizer that supports ** synonyms would call xToken() 5 times, as follows: ** ** <codeblock> ** xToken(pCtx, 0, "i", 1, 0, 1); ** xToken(pCtx, 0, "won", 3, 2, 5); ** xToken(pCtx, 0, "first", 5, 6, 11); ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11); ** xToken(pCtx, 0, "place", 5, 12, 17); **</codeblock> ** ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time ** xToken() is called. Multiple synonyms may be specified for a single token ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. ** There is no limit to the number of synonyms that may be provided for a ** single token. ** ** In many cases, method (1) above is the best approach. It does not add ** extra data to the FTS index or require FTS5 to query for multiple terms, ** so it is efficient in terms of disk space and query speed. However, it ** does not support prefix queries very well. If, as suggested above, the ** token "first" is subsituted for "1st" by the tokenizer, then the query: ** ** <codeblock> ** ... MATCH '1s*'</codeblock> ** ** will not match documents that contain the token "1st" (as the tokenizer ** will probably not map "1s" to any prefix of "first"). ** ** For full prefix support, method (3) may be preferred. In this case, ** because the index contains entries for both "first" and "1st", prefix ** queries such as 'fi*' or '1s*' will match correctly. However, because ** extra entries are added to the FTS index, this method uses more space ** within the database. ** ** Method (2) offers a midpoint between (1) and (3). Using this method, ** a query such as '1s*' will match documents that contain the literal ** token "1st", but not "first" (assuming the tokenizer is not able to ** provide synonyms for prefixes). However, a non-prefix query like '1st' ** will match against "1st" and "first". This method does not require ** extra disk space, as no extra entries are added to the FTS index. ** On the other hand, it may require more CPU cycles to run MATCH queries, ** as separate queries of the FTS index are required for each synonym. ** ** When using methods (2) or (3), it is important that the tokenizer only ** provide synonyms when tokenizing document text (method (2)) or query ** text (method (3)), not both. Doing so will not cause any errors, but is ** inefficient. */ typedef struct Fts5Tokenizer Fts5Tokenizer; typedef struct fts5_tokenizer fts5_tokenizer; struct fts5_tokenizer { int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); void (*xDelete)(Fts5Tokenizer*); int (*xTokenize)(Fts5Tokenizer*, void *pCtx, int flags, /* Mask of FTS5_TOKENIZE_* flags */ const char *pText, int nText, int (*xToken)( void *pCtx, /* Copy of 2nd argument to xTokenize() */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Pointer to buffer containing token */ int nToken, /* Size of token in bytes */ int iStart, /* Byte offset of token within input text */ int iEnd /* Byte offset of end of token within input text */ ) ); }; /* Flags that may be passed as the third argument to xTokenize() */ #define FTS5_TOKENIZE_QUERY 0x0001 #define FTS5_TOKENIZE_PREFIX 0x0002 #define FTS5_TOKENIZE_DOCUMENT 0x0004 #define FTS5_TOKENIZE_AUX 0x0008 /* Flags that may be passed by the tokenizer implementation back to FTS5 ** as the third argument to the supplied xToken callback. */ #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */ /* ** END OF CUSTOM TOKENIZERS *************************************************************************/ /************************************************************************* ** FTS5 EXTENSION REGISTRATION API */ typedef struct fts5_api fts5_api; struct fts5_api { int iVersion; /* Currently always set to 2 */ /* Create a new tokenizer */ int (*xCreateTokenizer)( fts5_api *pApi, const char *zName, void *pContext, fts5_tokenizer *pTokenizer, void (*xDestroy)(void*) ); /* Find an existing tokenizer */ int (*xFindTokenizer)( fts5_api *pApi, const char *zName, void **ppContext, fts5_tokenizer *pTokenizer ); /* Create a new auxiliary function */ int (*xCreateFunction)( fts5_api *pApi, const char *zName, void *pContext, fts5_extension_function xFunction, void (*xDestroy)(void*) ); }; /* ** END OF REGISTRATION API *************************************************************************/ #ifdef __cplusplus } /* end of the 'extern "C"' block */ #endif #endif /* _FTS5_H */ /******** End of fts5.h *********/ #else // USE_LIBSQLITE3 // If users really want to link against the system sqlite3 we // need to make this file a noop. #endif��������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/sqlite3-binding.c�����������������������������������0000644�0610621�0607500�00032776634�13172163427�025575� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#ifndef USE_LIBSQLITE3 #define SQLITE_DISABLE_INTRINSIC 1 /****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite ** version 3.17.0. By combining all the individual C code files into this ** single large file, the entire code can be compiled as a single translation ** unit. This allows many compilers to do optimizations that would not be ** possible if the files were compiled separately. Performance improvements ** of 5% or more are commonly seen when SQLite is compiled as a single ** translation unit. ** ** This file is all you need to compile SQLite. To use SQLite in other ** programs, you need this file and the "sqlite3.h" header file that defines ** the programming interface to the SQLite library. (If you do not have ** the "sqlite3.h" header file at hand, you will find a copy embedded within ** the text of this file. Search for "Begin file sqlite3.h" to find the start ** of the embedded sqlite3.h header file.) Additional code files may be needed ** if you want a wrapper to interface SQLite with your choice of programming ** language. The code for the "sqlite3" command-line shell is also in a ** separate file. This file contains only code for the core SQLite library. */ #define SQLITE_CORE 1 #define SQLITE_AMALGAMATION 1 #ifndef SQLITE_PRIVATE # define SQLITE_PRIVATE static #endif /************** Begin file sqliteInt.h ***************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Internal interface definitions for SQLite. ** */ #ifndef SQLITEINT_H #define SQLITEINT_H /* Special Comments: ** ** Some comments have special meaning to the tools that measure test ** coverage: ** ** NO_TEST - The branches on this line are not ** measured by branch coverage. This is ** used on lines of code that actually ** implement parts of coverage testing. ** ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false ** and the correct answer is still obtained, ** though perhaps more slowly. ** ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true ** and the correct answer is still obtained, ** though perhaps more slowly. ** ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread ** that would be harmless and undetectable ** if it did occur. ** ** In all cases, the special comment must be enclosed in the usual ** slash-asterisk...asterisk-slash comment marks, with no spaces between the ** asterisks and the comment text. */ /* ** Make sure the Tcl calling convention macro is defined. This macro is ** only used by test code and Tcl integration code. */ #ifndef SQLITE_TCLAPI # define SQLITE_TCLAPI #endif /* ** Make sure that rand_s() is available on Windows systems with MSVC 2005 ** or higher. */ #if defined(_MSC_VER) && _MSC_VER>=1400 # define _CRT_RAND_S #endif /* ** Include the header file used to customize the compiler options for MSVC. ** This should be done first so that it can successfully prevent spurious ** compiler warnings due to subsequent content in this file and other files ** that are included by this file. */ /************** Include msvc.h in the middle of sqliteInt.h ******************/ /************** Begin file msvc.h ********************************************/ /* ** 2015 January 12 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to MSVC. */ #ifndef SQLITE_MSVC_H #define SQLITE_MSVC_H #if defined(_MSC_VER) #pragma warning(disable : 4054) #pragma warning(disable : 4055) #pragma warning(disable : 4100) #pragma warning(disable : 4127) #pragma warning(disable : 4130) #pragma warning(disable : 4152) #pragma warning(disable : 4189) #pragma warning(disable : 4206) #pragma warning(disable : 4210) #pragma warning(disable : 4232) #pragma warning(disable : 4244) #pragma warning(disable : 4305) #pragma warning(disable : 4306) #pragma warning(disable : 4702) #pragma warning(disable : 4706) #endif /* defined(_MSC_VER) */ #endif /* SQLITE_MSVC_H */ /************** End of msvc.h ************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* ** Special setup for VxWorks */ /************** Include vxworks.h in the middle of sqliteInt.h ***************/ /************** Begin file vxworks.h *****************************************/ /* ** 2015-03-02 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to Wind River's VxWorks */ #if defined(__RTP__) || defined(_WRS_KERNEL) /* This is VxWorks. Set up things specially for that OS */ #include <vxWorks.h> #include <pthread.h> /* amalgamator: dontcache */ #define OS_VXWORKS 1 #define SQLITE_OS_OTHER 0 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1 #define SQLITE_OMIT_LOAD_EXTENSION 1 #define SQLITE_ENABLE_LOCKING_STYLE 0 #define HAVE_UTIME 1 #else /* This is not VxWorks. */ #define OS_VXWORKS 0 #define HAVE_FCHOWN 1 #define HAVE_READLINK 1 #define HAVE_LSTAT 1 #endif /* defined(_WRS_KERNEL) */ /************** End of vxworks.h *********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* ** These #defines should enable >2GB file support on POSIX if the ** underlying operating system supports it. If the OS lacks ** large file support, or if the OS is windows, these should be no-ops. ** ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any ** system #includes. Hence, this block of code must be the very first ** code in all source files. ** ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch ** on the compiler command line. This is necessary if you are compiling ** on a recent machine (ex: Red Hat 7.2) but you want your code to work ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 ** without this option, LFS is enable. But LFS does not exist in the kernel ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary ** portability you should omit LFS. ** ** The previous paragraph was written in 2005. (This paragraph is written ** on 2008-11-28.) These days, all Linux kernels support large files, so ** you should probably leave LFS enabled. But some embedded platforms might ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful. ** ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. */ #ifndef SQLITE_DISABLE_LFS # define _LARGE_FILE 1 # ifndef _FILE_OFFSET_BITS # define _FILE_OFFSET_BITS 64 # endif # define _LARGEFILE_SOURCE 1 #endif /* The GCC_VERSION, CLANG_VERSION, and MSVC_VERSION macros are used to ** conditionally include optimizations for each of these compilers. A ** value of 0 means that compiler is not being used. The ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific ** optimizations, and hence set all compiler macros to 0 */ #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) #else # define GCC_VERSION 0 #endif #if defined(__clang__) && !defined(_WIN32) && !defined(SQLITE_DISABLE_INTRINSIC) # define CLANG_VERSION \ (__clang_major__*1000000+__clang_minor__*1000+__clang_patchlevel__) #else # define CLANG_VERSION 0 #endif #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) # define MSVC_VERSION _MSC_VER #else # define MSVC_VERSION 0 #endif /* Needed for various definitions... */ #if defined(__GNUC__) && !defined(_GNU_SOURCE) # define _GNU_SOURCE #endif #if defined(__OpenBSD__) && !defined(_BSD_SOURCE) # define _BSD_SOURCE #endif /* ** For MinGW, check to see if we can include the header file containing its ** version information, among other things. Normally, this internal MinGW ** header file would [only] be included automatically by other MinGW header ** files; however, the contained version information is now required by this ** header file to work around binary compatibility issues (see below) and ** this is the only known way to reliably obtain it. This entire #if block ** would be completely unnecessary if there was any other way of detecting ** MinGW via their preprocessor (e.g. if they customized their GCC to define ** some MinGW-specific macros). When compiling for MinGW, either the ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be ** defined; otherwise, detection of conditions specific to MinGW will be ** disabled. */ #if defined(_HAVE_MINGW_H) # include "mingw.h" #elif defined(_HAVE__MINGW_H) # include "_mingw.h" #endif /* ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T ** define is required to maintain binary compatibility with the MSVC runtime ** library in use (e.g. for Windows XP). */ #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \ defined(_WIN32) && !defined(_WIN64) && \ defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \ defined(__MSVCRT__) # define _USE_32BIT_TIME_T #endif /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for ** MinGW. */ /************** Include sqlite3.h in the middle of sqliteInt.h ***************/ /************** Begin file sqlite3.h *****************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the SQLite library ** presents to client programs. If a C-function, structure, datatype, ** or constant definition does not appear in this file, then it is ** not a published API of SQLite, is subject to change without ** notice, and should not be referenced by programs that use SQLite. ** ** Some of the definitions that are in this file are marked as ** "experimental". Experimental interfaces are normally new ** features recently added to SQLite. We do not anticipate changes ** to experimental interfaces but reserve the right to make minor changes ** if experience from use "in the wild" suggest such changes are prudent. ** ** The official C-language API documentation for SQLite is derived ** from comments in this file. This file is the authoritative source ** on how SQLite interfaces are supposed to operate. ** ** The name of this file under configuration management is "sqlite.h.in". ** The makefile makes some minor changes to this file (such as inserting ** the version number) and changes its name to "sqlite3.h" as ** part of the build process. */ #ifndef SQLITE3_H #define SQLITE3_H #include <stdarg.h> /* Needed for the definition of va_list */ /* ** Make sure we can call this stuff from C++. */ #if 0 extern "C" { #endif /* ** Provide the ability to override linkage features of the interface. */ #ifndef SQLITE_EXTERN # define SQLITE_EXTERN extern #endif #ifndef SQLITE_API # define SQLITE_API #endif #ifndef SQLITE_CDECL # define SQLITE_CDECL #endif #ifndef SQLITE_APICALL # define SQLITE_APICALL #endif #ifndef SQLITE_STDCALL # define SQLITE_STDCALL SQLITE_APICALL #endif #ifndef SQLITE_CALLBACK # define SQLITE_CALLBACK #endif #ifndef SQLITE_SYSAPI # define SQLITE_SYSAPI #endif /* ** These no-op macros are used in front of interfaces to mark those ** interfaces as either deprecated or experimental. New applications ** should not use deprecated interfaces - they are supported for backwards ** compatibility only. Application writers should be aware that ** experimental interfaces are subject to change in point releases. ** ** These macros used to resolve to various kinds of compiler magic that ** would generate warning messages when they were used. But that ** compiler magic ended up generating such a flurry of bug reports ** that we have taken it all out and gone back to using simple ** noop macros. */ #define SQLITE_DEPRECATED #define SQLITE_EXPERIMENTAL /* ** Ensure these symbols were not defined by some previous header file. */ #ifdef SQLITE_VERSION # undef SQLITE_VERSION #endif #ifdef SQLITE_VERSION_NUMBER # undef SQLITE_VERSION_NUMBER #endif /* ** CAPI3REF: Compile-Time Library Version Numbers ** ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header ** evaluates to a string literal that is the SQLite version in the ** format "X.Y.Z" where X is the major version number (always 3 for ** SQLite3) and Y is the minor version number and Z is the release number.)^ ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same ** numbers used in [SQLITE_VERSION].)^ ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also ** be larger than the release from which it is derived. Either Y will ** be held constant and Z will be incremented or else Y will be incremented ** and Z will be reset to zero. ** ** Since [version 3.6.18] ([dateof:3.6.18]), ** SQLite source code has been stored in the ** <a href="http://www.fossil-scm.org/">Fossil configuration management ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to ** a string which identifies a particular check-in of SQLite ** within its configuration management system. ^The SQLITE_SOURCE_ID ** string contains the date and time of the check-in (UTC) and an SHA1 ** hash of the entire source tree. ** ** See also: [sqlite3_libversion()], ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ #define SQLITE_VERSION "3.17.0" #define SQLITE_VERSION_NUMBER 3017000 #define SQLITE_SOURCE_ID "2017-02-13 16:02:40 ada05cfa86ad7f5645450ac7a2a21c9aa6e57d2c" /* ** CAPI3REF: Run-Time Library Version Numbers ** KEYWORDS: sqlite3_version sqlite3_sourceid ** ** These interfaces provide the same information as the [SQLITE_VERSION], ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros ** but are associated with the library instead of the header file. ^(Cautious ** programmers might include assert() statements in their application to ** verify that values returned by these interfaces match the macros in ** the header, and thus ensure that the application is ** compiled with matching library and header files. ** ** <blockquote><pre> ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER ); ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 ); ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 ); ** </pre></blockquote>)^ ** ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] ** macro. ^The sqlite3_libversion() function returns a pointer to the ** to the sqlite3_version[] string constant. The sqlite3_libversion() ** function is provided for use in DLLs since DLL users usually do not have ** direct access to string constants within the DLL. ^The ** sqlite3_libversion_number() function returns an integer equal to ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns ** a pointer to a string constant whose value is the same as the ** [SQLITE_SOURCE_ID] C preprocessor macro. ** ** See also: [sqlite_version()] and [sqlite_source_id()]. */ SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; SQLITE_API const char *sqlite3_libversion(void); SQLITE_API const char *sqlite3_sourceid(void); SQLITE_API int sqlite3_libversion_number(void); /* ** CAPI3REF: Run-Time Library Compilation Options Diagnostics ** ** ^The sqlite3_compileoption_used() function returns 0 or 1 ** indicating whether the specified option was defined at ** compile time. ^The SQLITE_ prefix may be omitted from the ** option name passed to sqlite3_compileoption_used(). ** ** ^The sqlite3_compileoption_get() function allows iterating ** over the list of options that were defined at compile time by ** returning the N-th compile time option string. ^If N is out of range, ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ ** prefix is omitted from any strings returned by ** sqlite3_compileoption_get(). ** ** ^Support for the diagnostic functions sqlite3_compileoption_used() ** and sqlite3_compileoption_get() may be omitted by specifying the ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. ** ** See also: SQL functions [sqlite_compileoption_used()] and ** [sqlite_compileoption_get()] and the [compile_options pragma]. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS SQLITE_API int sqlite3_compileoption_used(const char *zOptName); SQLITE_API const char *sqlite3_compileoption_get(int N); #endif /* ** CAPI3REF: Test To See If The Library Is Threadsafe ** ** ^The sqlite3_threadsafe() function returns zero if and only if ** SQLite was compiled with mutexing code omitted due to the ** [SQLITE_THREADSAFE] compile-time option being set to 0. ** ** SQLite can be compiled with or without mutexes. When ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes ** are enabled and SQLite is threadsafe. When the ** [SQLITE_THREADSAFE] macro is 0, ** the mutexes are omitted. Without the mutexes, it is not safe ** to use SQLite concurrently from more than one thread. ** ** Enabling mutexes incurs a measurable performance penalty. ** So if speed is of utmost importance, it makes sense to disable ** the mutexes. But for maximum safety, mutexes should be enabled. ** ^The default behavior is for mutexes to be enabled. ** ** This interface can be used by an application to make sure that the ** version of SQLite that it is linking against was compiled with ** the desired setting of the [SQLITE_THREADSAFE] macro. ** ** This interface only reports on the compile-time mutex setting ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but ** can be fully or partially disabled using a call to [sqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the ** sqlite3_threadsafe() function shows only the compile-time setting of ** thread safety, not any run-time changes to that setting made by ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() ** is unchanged by calls to sqlite3_config().)^ ** ** See the [threading mode] documentation for additional information. */ SQLITE_API int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle ** KEYWORDS: {database connection} {database connections} ** ** Each open SQLite database is represented by a pointer to an instance of ** the opaque structure named "sqlite3". It is useful to think of an sqlite3 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] ** and [sqlite3_close_v2()] are its destructors. There are many other ** interfaces (such as ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and ** [sqlite3_busy_timeout()] to name but three) that are methods on an ** sqlite3 object. */ typedef struct sqlite3 sqlite3; /* ** CAPI3REF: 64-Bit Integer Types ** KEYWORDS: sqlite_int64 sqlite_uint64 ** ** Because there is no cross-platform way to specify 64-bit integer types ** SQLite includes typedefs for 64-bit signed and unsigned integers. ** ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards ** compatibility only. ** ** ^The sqlite3_int64 and sqlite_int64 types can store integer values ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The ** sqlite3_uint64 and sqlite_uint64 types can store integer values ** between 0 and +18446744073709551615 inclusive. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; # ifdef SQLITE_UINT64_TYPE typedef SQLITE_UINT64_TYPE sqlite_uint64; # else typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; # endif #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef __int64 sqlite_int64; typedef unsigned __int64 sqlite_uint64; #else typedef long long int sqlite_int64; typedef unsigned long long int sqlite_uint64; #endif typedef sqlite_int64 sqlite3_int64; typedef sqlite_uint64 sqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point. */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite3_int64 #endif /* ** CAPI3REF: Closing A Database Connection ** DESTRUCTOR: sqlite3 ** ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors ** for the [sqlite3] object. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if ** the [sqlite3] object is successfully destroyed and all associated ** resources are deallocated. ** ** ^If the database connection is associated with unfinalized prepared ** statements or unfinished sqlite3_backup objects then sqlite3_close() ** will leave the database connection open and return [SQLITE_BUSY]. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements ** and/or unfinished sqlite3_backups, then the database connection becomes ** an unusable "zombie" which will automatically be deallocated when the ** last prepared statement is finalized or the last sqlite3_backup is ** finished. The sqlite3_close_v2() interface is intended for use with ** host languages that are garbage collected, and where the order in which ** destructors are called is arbitrary. ** ** Applications should [sqlite3_finalize | finalize] all [prepared statements], ** [sqlite3_blob_close | close] all [BLOB handles], and ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated ** with the [sqlite3] object prior to attempting to close the object. ^If ** sqlite3_close_v2() is called on a [database connection] that still has ** outstanding [prepared statements], [BLOB handles], and/or ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation ** of resources is deferred until all [prepared statements], [BLOB handles], ** and [sqlite3_backup] objects are also destroyed. ** ** ^If an [sqlite3] object is destroyed while a transaction is open, ** the transaction is automatically rolled back. ** ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] ** must be either a NULL ** pointer or an [sqlite3] object pointer obtained ** from [sqlite3_open()], [sqlite3_open16()], or ** [sqlite3_open_v2()], and not previously closed. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer ** argument is a harmless no-op. */ SQLITE_API int sqlite3_close(sqlite3*); SQLITE_API int sqlite3_close_v2(sqlite3*); /* ** The type for a callback function. ** This is legacy and deprecated. It is included for historical ** compatibility and is not documented. */ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface ** METHOD: sqlite3 ** ** The sqlite3_exec() interface is a convenience wrapper around ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], ** that allows an application to run multiple statements of SQL ** without having to use a lot of C code. ** ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, ** semicolon-separate SQL statements passed into its 2nd argument, ** in the context of the [database connection] passed in as its 1st ** argument. ^If the callback function of the 3rd argument to ** sqlite3_exec() is not NULL, then it is invoked for each result row ** coming out of the evaluated SQL statements. ^The 4th argument to ** sqlite3_exec() is relayed through to the 1st argument of each ** callback invocation. ^If the callback pointer to sqlite3_exec() ** is NULL, then no callback is ever invoked and result rows are ** ignored. ** ** ^If an error occurs while evaluating the SQL statements passed into ** sqlite3_exec(), then execution of the current statement stops and ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() ** is not NULL then any error message is written into memory obtained ** from [sqlite3_malloc()] and passed back through the 5th parameter. ** To avoid memory leaks, the application should invoke [sqlite3_free()] ** on error message strings returned through the 5th parameter of ** sqlite3_exec() after the error message string is no longer needed. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to ** NULL before returning. ** ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() ** routine returns SQLITE_ABORT without invoking the callback again and ** without running any subsequent SQL statements. ** ** ^The 2nd argument to the sqlite3_exec() callback function is the ** number of columns in the result. ^The 3rd argument to the sqlite3_exec() ** callback is an array of pointers to strings obtained as if from ** [sqlite3_column_text()], one for each column. ^If an element of a ** result row is NULL then the corresponding string pointer for the ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the ** sqlite3_exec() callback is an array of pointers to strings where each ** entry represents the name of corresponding result column as obtained ** from [sqlite3_column_name()]. ** ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer ** to an empty string, or a pointer that contains only whitespace and/or ** SQL comments, then no SQL statements are evaluated and the database ** is not changed. ** ** Restrictions: ** ** <ul> ** <li> The application must ensure that the 1st parameter to sqlite3_exec() ** is a valid and open [database connection]. ** <li> The application must not close the [database connection] specified by ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. ** <li> The application must not modify the SQL statement text passed into ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. ** </ul> */ SQLITE_API int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); /* ** CAPI3REF: Result Codes ** KEYWORDS: {result code definitions} ** ** Many SQLite functions return an integer result code from the set shown ** here in order to indicate success or failure. ** ** New error codes may be added in future versions of SQLite. ** ** See also: [extended result code definitions] */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ #define SQLITE_ERROR 1 /* SQL error or missing database */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ #define SQLITE_BUSY 5 /* The database file is locked */ #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ #define SQLITE_EMPTY 16 /* Database is empty */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ #define SQLITE_MISMATCH 20 /* Data type mismatch */ #define SQLITE_MISUSE 21 /* Library used incorrectly */ #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ #define SQLITE_AUTH 23 /* Authorization denied */ #define SQLITE_FORMAT 24 /* Auxiliary database format error */ #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ #define SQLITE_NOTADB 26 /* File opened that is not a database file */ #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ /* end-of-error-codes */ /* ** CAPI3REF: Extended Result Codes ** KEYWORDS: {extended result code definitions} ** ** In its default configuration, SQLite API routines return one of 30 integer ** [result codes]. However, experience has shown that many of ** these result codes are too coarse-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8] ** and later) include ** support for additional result codes that provide more detailed information ** about errors. These [extended result codes] are enabled or disabled ** on a per database connection basis using the ** [sqlite3_extended_result_codes()] API. Or, the extended code for ** the most recent error can be obtained using ** [sqlite3_extended_errcode()]. */ #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8)) #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) /* ** CAPI3REF: Flags For File Open Operations ** ** These bit values are intended for use in the ** 3rd parameter to the [sqlite3_open_v2()] interface and ** in the 4th parameter to the [sqlite3_vfs.xOpen] method. */ #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ /* Reserved: 0x00F00000 */ /* ** CAPI3REF: Device Characteristics ** ** The xDeviceCharacteristics method of the [sqlite3_io_methods] ** object returns an integer which is a vector of these ** bit values expressing I/O characteristics of the mass storage ** device that holds the file that the [sqlite3_io_methods] ** refers to. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that ** after reboot following a crash or power loss, the only bytes in a ** file that were written at the application level might have changed ** and that adjacent bytes, even bytes within the same sector are ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN ** flag indicates that a file cannot be deleted when open. The ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on ** read-only media and cannot be changed even by processes with ** elevated privileges. */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 #define SQLITE_IOCAP_ATOMIC1K 0x00000004 #define SQLITE_IOCAP_ATOMIC2K 0x00000008 #define SQLITE_IOCAP_ATOMIC4K 0x00000010 #define SQLITE_IOCAP_ATOMIC8K 0x00000020 #define SQLITE_IOCAP_ATOMIC16K 0x00000040 #define SQLITE_IOCAP_ATOMIC32K 0x00000080 #define SQLITE_IOCAP_ATOMIC64K 0x00000100 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 /* ** CAPI3REF: File Locking Levels ** ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 #define SQLITE_LOCK_RESERVED 2 #define SQLITE_LOCK_PENDING 3 #define SQLITE_LOCK_EXCLUSIVE 4 /* ** CAPI3REF: Synchronization Type Flags ** ** When SQLite invokes the xSync() method of an ** [sqlite3_io_methods] object it uses a combination of ** these integer values as the second argument. ** ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the ** sync operation only needs to flush data to mass storage. Inode ** information need not be flushed. If the lower four bits of the flag ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. ** If the lower four bits equal SQLITE_SYNC_FULL, that means ** to use Mac OS X style fullsync instead of fsync(). ** ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL ** settings. The [synchronous pragma] determines when calls to the ** xSync VFS method occur and applies uniformly across all platforms. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how ** energetic or rigorous or forceful the sync operations are and ** only make a difference on Mac OSX for the default SQLite code. ** (Third-party VFS implementations might also make the distinction ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the ** operating systems natively supported by SQLite, only Mac OSX ** cares about the difference.) */ #define SQLITE_SYNC_NORMAL 0x00002 #define SQLITE_SYNC_FULL 0x00003 #define SQLITE_SYNC_DATAONLY 0x00010 /* ** CAPI3REF: OS Interface Open File Handle ** ** An [sqlite3_file] object represents an open file in the ** [sqlite3_vfs | OS interface layer]. Individual OS interface ** implementations will ** want to subclass this object by appending additional fields ** for their own use. The pMethods entry is a pointer to an ** [sqlite3_io_methods] object that defines methods for performing ** I/O operations on the open file. */ typedef struct sqlite3_file sqlite3_file; struct sqlite3_file { const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ }; /* ** CAPI3REF: OS Interface File Virtual Methods Object ** ** Every file opened by the [sqlite3_vfs.xOpen] method populates an ** [sqlite3_file] object (or, more commonly, a subclass of the ** [sqlite3_file] object) with a pointer to an instance of this object. ** This object defines the methods used to perform various operations ** against the open file represented by the [sqlite3_file] object. ** ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element ** to NULL. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] ** flag may be ORed in to indicate that only the data of the file ** and not its inode needs to be synced. ** ** The integer values to xLock() and xUnlock() are one of ** <ul> ** <li> [SQLITE_LOCK_NONE], ** <li> [SQLITE_LOCK_SHARED], ** <li> [SQLITE_LOCK_RESERVED], ** <li> [SQLITE_LOCK_PENDING], or ** <li> [SQLITE_LOCK_EXCLUSIVE]. ** </ul> ** xLock() increases the lock. xUnlock() decreases the lock. ** The xCheckReservedLock() method checks whether any database connection, ** either in this process or in some other process, is holding a RESERVED, ** PENDING, or EXCLUSIVE lock on the file. It returns true ** if such a lock exists and false otherwise. ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the ** [sqlite3_file_control()] interface. The second "op" argument is an ** integer opcode. The third argument is a generic pointer intended to ** point to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be ** functions to enable blocking locks with timeouts, to change the ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite ** core reserves all opcodes less than 100 for its own use. ** A [file control opcodes | list of opcodes] less than 100 is available. ** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. VFS implementations should ** return [SQLITE_NOTFOUND] for file control opcodes that they do not ** recognize. ** ** The xSectorSize() method returns the sector size of the ** device that underlies the file. The sector size is the ** minimum write that can be performed without disturbing ** other bytes in the file. The xDeviceCharacteristics() ** method returns a bit vector describing behaviors of the ** underlying device: ** ** <ul> ** <li> [SQLITE_IOCAP_ATOMIC] ** <li> [SQLITE_IOCAP_ATOMIC512] ** <li> [SQLITE_IOCAP_ATOMIC1K] ** <li> [SQLITE_IOCAP_ATOMIC2K] ** <li> [SQLITE_IOCAP_ATOMIC4K] ** <li> [SQLITE_IOCAP_ATOMIC8K] ** <li> [SQLITE_IOCAP_ATOMIC16K] ** <li> [SQLITE_IOCAP_ATOMIC32K] ** <li> [SQLITE_IOCAP_ATOMIC64K] ** <li> [SQLITE_IOCAP_SAFE_APPEND] ** <li> [SQLITE_IOCAP_SEQUENTIAL] ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN] ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE] ** <li> [SQLITE_IOCAP_IMMUTABLE] ** </ul> ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). ** ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill ** in the unread portions of the buffer with zeros. A VFS that ** fails to zero-fill short reads might seem to work. However, ** failure to zero-fill short reads will eventually lead to ** database corruption. */ typedef struct sqlite3_io_methods sqlite3_io_methods; struct sqlite3_io_methods { int iVersion; int (*xClose)(sqlite3_file*); int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); int (*xSync)(sqlite3_file*, int flags); int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); int (*xLock)(sqlite3_file*, int); int (*xUnlock)(sqlite3_file*, int); int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); int (*xFileControl)(sqlite3_file*, int op, void *pArg); int (*xSectorSize)(sqlite3_file*); int (*xDeviceCharacteristics)(sqlite3_file*); /* Methods above are valid for version 1 */ int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); void (*xShmBarrier)(sqlite3_file*); int (*xShmUnmap)(sqlite3_file*, int deleteFlag); /* Methods above are valid for version 2 */ int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); /* Methods above are valid for version 3 */ /* Additional methods may be added in future releases */ }; /* ** CAPI3REF: Standard File Control Opcodes ** KEYWORDS: {file control opcodes} {file control opcode} ** ** These integer constants are opcodes for the xFileControl method ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] ** interface. ** ** <ul> ** <li>[[SQLITE_FCNTL_LOCKSTATE]] ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This ** opcode causes the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) ** into an integer that the pArg argument points to. This capability ** is used during testing and is only available when the SQLITE_TEST ** compile-time option is used. ** ** <li>[[SQLITE_FCNTL_SIZE_HINT]] ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS ** layer a hint of how large the database file will grow to be during the ** current transaction. This hint is not guaranteed to be accurate but it ** is often close. The underlying VFS might choose to preallocate database ** file space based on this hint in order to help writes to the database ** file run faster. ** ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]] ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS ** extends and truncates the database file in chunks of a size specified ** by the user. The fourth argument to [sqlite3_file_control()] should ** point to an integer (type int) containing the new chunk-size to use ** for the nominated database. Allocating database file space in large ** chunks (say 1MB at a time), may reduce file-system fragmentation and ** improve performance on some systems. ** ** <li>[[SQLITE_FCNTL_FILE_POINTER]] ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with a particular database ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. ** ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]] ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer ** to the [sqlite3_file] object associated with the journal file (either ** the [rollback journal] or the [write-ahead log]) for a particular database ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]] ** No longer in use. ** ** <li>[[SQLITE_FCNTL_SYNC]] ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and ** sent to the VFS immediately before the xSync method is invoked on a ** database file descriptor. Or, if the xSync method is not invoked ** because the user has configured SQLite with ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place ** of the xSync method. In most cases, the pointer argument passed with ** this file-control is NULL. However, if the database file is being synced ** as part of a multi-database commit, the argument points to a nul-terminated ** string containing the transactions master-journal file name. VFSes that ** do not need this signal should silently ignore this opcode. Applications ** should not call [sqlite3_file_control()] with this opcode as doing so may ** disrupt the operation of the specialized VFSes that do require it. ** ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]] ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite ** and sent to the VFS after a transaction has been committed immediately ** but before the database is unlocked. VFSes that do not need this signal ** should silently ignore this opcode. Applications should not call ** [sqlite3_file_control()] with this opcode as doing so may disrupt the ** operation of the specialized VFSes that do require it. ** ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]] ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic ** retry counts and intervals for certain disk I/O operations for the ** windows [VFS] in order to provide robustness in the presence of ** anti-virus programs. By default, the windows VFS will retry file read, ** file write, and file delete operations up to 10 times, with a delay ** of 25 milliseconds before the first retry and with the delay increasing ** by an additional 25 milliseconds with each subsequent retry. This ** opcode allows these two values (10 retries and 25 milliseconds of delay) ** to be adjusted. The values are changed for all database connections ** within the same process. The argument is a pointer to an array of two ** integers where the first integer i the new retry count and the second ** integer is the delay. If either integer is negative, then the setting ** is not changed but instead the prior value of that setting is written ** into the array entry, allowing the current retry settings to be ** interrogated. The zDbName parameter is ignored. ** ** <li>[[SQLITE_FCNTL_PERSIST_WAL]] ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary ** write ahead log and shared memory files used for transaction control ** are automatically deleted when the latest connection to the database ** closes. Setting persistent WAL mode causes those files to persist after ** close. Persisting the files is useful when other processes that do not ** have write permission on the directory containing the database file want ** to read the database file, as the WAL and shared memory files must exist ** in order for the database to be readable. The fourth parameter to ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent ** WAL mode. If the integer is -1, then it is overwritten with the current ** WAL persistence setting. ** ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the ** xDeviceCharacteristics methods. The fourth parameter to ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage ** mode. If the integer is -1, then it is overwritten with the current ** zero-damage mode setting. ** ** <li>[[SQLITE_FCNTL_OVERWRITE]] ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening ** a write transaction to indicate that, unless it is rolled back for some ** reason, the entire database file will be overwritten by the current ** transaction. This is used by VACUUM operations. ** ** <li>[[SQLITE_FCNTL_VFSNAME]] ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of ** all [VFSes] in the VFS stack. The names are of all VFS shims and the ** final bottom-level VFS are written into memory obtained from ** [sqlite3_malloc()] and the result is stored in the char* variable ** that the fourth parameter of [sqlite3_file_control()] points to. ** The caller is responsible for freeing the memory when done. As with ** all file-control actions, there is no guarantee that this will actually ** do anything. Callers should initialize the char* variable to a NULL ** pointer in case this file-control is not implemented. This file-control ** is intended for diagnostic use only. ** ** <li>[[SQLITE_FCNTL_VFS_POINTER]] ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level ** [VFSes] currently in use. ^(The argument X in ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be ** of type "[sqlite3_vfs] **". This opcodes will set *X ** to a pointer to the top-level VFS.)^ ** ^When there are multiple VFS shims in the stack, this opcode finds the ** upper-most shim only. ** ** <li>[[SQLITE_FCNTL_PRAGMA]] ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] ** file control is sent to the open [sqlite3_file] object corresponding ** to the database file to which the pragma statement refers. ^The argument ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of ** pointers to strings (char**) in which the second element of the array ** is the name of the pragma and the third element is the argument to the ** pragma or NULL if the pragma has no argument. ^The handler for an ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element ** of the char** argument point to a string obtained from [sqlite3_mprintf()] ** or the equivalent and that string will become the result of the pragma or ** the error message if the pragma fails. ^If the ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] ** file control returns [SQLITE_OK], then the parser assumes that the ** VFS has handled the PRAGMA itself and the parser generates a no-op ** prepared statement if result string is NULL, or that returns a copy ** of the result string if the string is non-NULL. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means ** that the VFS encountered an error while handling the [PRAGMA] and the ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] ** file control occurs at the beginning of pragma statement analysis and so ** it is able to override built-in [PRAGMA] statements. ** ** <li>[[SQLITE_FCNTL_BUSYHANDLER]] ** ^The [SQLITE_FCNTL_BUSYHANDLER] ** file-control may be invoked by SQLite on the database file handle ** shortly after it is opened in order to provide a custom VFS with access ** to the connections busy-handler callback. The argument is of type (void **) ** - an array of two (void *) values. The first (void *) actually points ** to a function of type (int (*)(void *)). In order to invoke the connections ** busy-handler, this function should be invoked with the second (void *) in ** the array as the only argument. If it returns non-zero, then the operation ** should be retried. If it returns zero, the custom VFS should abandon the ** current operation. ** ** <li>[[SQLITE_FCNTL_TEMPFILENAME]] ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control ** to have SQLite generate a ** temporary filename using the same algorithm that is followed to generate ** temporary filenames for TEMP tables and other internal uses. The ** argument should be a char** which will be filled with the filename ** written into memory obtained from [sqlite3_malloc()]. The caller should ** invoke [sqlite3_free()] on the result to avoid a memory leak. ** ** <li>[[SQLITE_FCNTL_MMAP_SIZE]] ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the ** maximum number of bytes that will be used for memory-mapped I/O. ** The argument is a pointer to a value of type sqlite3_int64 that ** is an advisory maximum number of bytes in the file to memory map. The ** pointer is overwritten with the old value. The limit is not changed if ** the value originally pointed to is negative, and so the current limit ** can be queried by passing in a pointer to a negative number. This ** file-control is used internally to implement [PRAGMA mmap_size]. ** ** <li>[[SQLITE_FCNTL_TRACE]] ** The [SQLITE_FCNTL_TRACE] file control provides advisory information ** to the VFS about what the higher layers of the SQLite stack are doing. ** This file control is used by some VFS activity tracing [shims]. ** The argument is a zero-terminated string. Higher layers in the ** SQLite stack may generate instances of this file control if ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled. ** ** <li>[[SQLITE_FCNTL_HAS_MOVED]] ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a ** pointer to an integer and it writes a boolean into that integer depending ** on whether or not the file has been renamed, moved, or deleted since it ** was first opened. ** ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]] ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the ** underlying native file handle associated with a file handle. This file ** control interprets its argument as a pointer to a native file handle and ** writes the resulting value there. ** ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]] ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This ** opcode causes the xFileControl method to swap the file handle with the one ** pointed to by the pArg argument. This capability is used during testing ** and only needs to be supported when SQLITE_TEST is defined. ** ** <li>[[SQLITE_FCNTL_WAL_BLOCK]] ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might ** be advantageous to block on the next WAL lock if the lock is not immediately ** available. The WAL subsystem issues this signal during rare ** circumstances in order to fix a problem with priority inversion. ** Applications should <em>not</em> use this file-control. ** ** <li>[[SQLITE_FCNTL_ZIPVFS]] ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other ** VFS should return SQLITE_NOTFOUND for this opcode. ** ** <li>[[SQLITE_FCNTL_RBU]] ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for ** this opcode. ** </ul> */ #define SQLITE_FCNTL_LOCKSTATE 1 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3 #define SQLITE_FCNTL_LAST_ERRNO 4 #define SQLITE_FCNTL_SIZE_HINT 5 #define SQLITE_FCNTL_CHUNK_SIZE 6 #define SQLITE_FCNTL_FILE_POINTER 7 #define SQLITE_FCNTL_SYNC_OMITTED 8 #define SQLITE_FCNTL_WIN32_AV_RETRY 9 #define SQLITE_FCNTL_PERSIST_WAL 10 #define SQLITE_FCNTL_OVERWRITE 11 #define SQLITE_FCNTL_VFSNAME 12 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 #define SQLITE_FCNTL_PRAGMA 14 #define SQLITE_FCNTL_BUSYHANDLER 15 #define SQLITE_FCNTL_TEMPFILENAME 16 #define SQLITE_FCNTL_MMAP_SIZE 18 #define SQLITE_FCNTL_TRACE 19 #define SQLITE_FCNTL_HAS_MOVED 20 #define SQLITE_FCNTL_SYNC 21 #define SQLITE_FCNTL_COMMIT_PHASETWO 22 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23 #define SQLITE_FCNTL_WAL_BLOCK 24 #define SQLITE_FCNTL_ZIPVFS 25 #define SQLITE_FCNTL_RBU 26 #define SQLITE_FCNTL_VFS_POINTER 27 #define SQLITE_FCNTL_JOURNAL_POINTER 28 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29 #define SQLITE_FCNTL_PDB 30 /* deprecated names */ #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO /* ** CAPI3REF: Mutex Handle ** ** The mutex module within SQLite defines [sqlite3_mutex] to be an ** abstract type for a mutex object. The SQLite core never looks ** at the internal representation of an [sqlite3_mutex]. It only ** deals with pointers to the [sqlite3_mutex] object. ** ** Mutexes are created using [sqlite3_mutex_alloc()]. */ typedef struct sqlite3_mutex sqlite3_mutex; /* ** CAPI3REF: Loadable Extension Thunk ** ** A pointer to the opaque sqlite3_api_routines structure is passed as ** the third parameter to entry points of [loadable extensions]. This ** structure must be typedefed in order to work around compiler warnings ** on some platforms. */ typedef struct sqlite3_api_routines sqlite3_api_routines; /* ** CAPI3REF: OS Interface Object ** ** An instance of the sqlite3_vfs object defines the interface between ** the SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". See ** the [VFS | VFS documentation] for further information. ** ** The value of the iVersion field is initially 1 but may be larger in ** future versions of SQLite. Additional fields may be appended to this ** object when the iVersion value is increased. Note that the structure ** of the sqlite3_vfs object changes in the transaction between ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not ** modified. ** ** The szOsFile field is the size of the subclassed [sqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** ** Registered sqlite3_vfs objects are kept on a linked list formed by ** the pNext pointer. The [sqlite3_vfs_register()] ** and [sqlite3_vfs_unregister()] interfaces manage this list ** in a thread-safe way. The [sqlite3_vfs_find()] interface ** searches the list. Neither the application code nor the VFS ** implementation should use the pNext pointer. ** ** The pNext field is the only field in the sqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. ** The application should never modify anything within the sqlite3_vfs ** object once the object has been registered. ** ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** ** [[sqlite3_vfs.xOpen]] ** ^SQLite guarantees that the zFilename parameter to xOpen ** is either a NULL pointer or string obtained ** from xFullPathname() with an optional suffix added. ** ^If a suffix is added to the zFilename parameter, it will ** consist of a single "-" character followed by no more than ** 11 alphanumeric and/or "-" characters. ** ^SQLite further guarantees that ** the string will be valid and unchanged until xClose() is ** called. Because of the previous sentence, ** the [sqlite3_file] can safely store a pointer to the ** filename if it needs to remember the filename for some reason. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen ** must invent its own temporary name for the file. ^Whenever the ** xFilename parameter is NULL it will also be the case that the ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** The flags argument to xOpen() includes all bits set in ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] ** or [sqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. ** If xOpen() opens a file read-only then it sets *pOutFlags to ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. ** ** ^(SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: ** ** <ul> ** <li> [SQLITE_OPEN_MAIN_DB] ** <li> [SQLITE_OPEN_MAIN_JOURNAL] ** <li> [SQLITE_OPEN_TEMP_DB] ** <li> [SQLITE_OPEN_TEMP_JOURNAL] ** <li> [SQLITE_OPEN_TRANSIENT_DB] ** <li> [SQLITE_OPEN_SUBJOURNAL] ** <li> [SQLITE_OPEN_MASTER_JOURNAL] ** <li> [SQLITE_OPEN_WAL] ** </ul>)^ ** ** The file I/O implementation can use the object type flags to ** change the way it deals with files. For example, an application ** that does not care about crash recovery or rollback might make ** the open of a journal file a no-op. Writes to this journal would ** also be no-ops, and any attempt to read the journal would return ** SQLITE_IOERR. Or the implementation might recognize that a database ** file will be doing page-aligned sector reads and writes in a random ** order and set up its I/O subsystem accordingly. ** ** SQLite might also add one of the following flags to the xOpen method: ** ** <ul> ** <li> [SQLITE_OPEN_DELETEONCLOSE] ** <li> [SQLITE_OPEN_EXCLUSIVE] ** </ul> ** ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] ** will be set for TEMP databases and their journals, transient ** databases, and subjournals. ** ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction ** with the [SQLITE_OPEN_CREATE] flag, which are both directly ** analogous to the O_EXCL and O_CREAT flags of the POSIX open() ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the ** SQLITE_OPEN_CREATE, is used to indicate that file should always ** be created, and that it is an error if it already exists. ** It is <i>not</i> used to indicate the file should be opened ** for exclusive access. ** ** ^At least szOsFile bytes of memory are allocated by SQLite ** to hold the [sqlite3_file] structure passed as the third ** argument to xOpen. The xOpen method does not have to ** allocate the structure; it should just fill it in. Note that ** the xOpen method must set the sqlite3_file.pMethods to either ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods ** element will be valid after xOpen returns regardless of the success ** or failure of the xOpen call. ** ** [[sqlite3_vfs.xAccess]] ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] ** to test whether a file is at least readable. The file can be a ** directory. ** ** ^SQLite will always allocate at least mxPathname+1 bytes for the ** output buffer xFullPathname. The exact size of the output buffer ** is also passed as a parameter to both methods. If the output buffer ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is ** handled as a fatal error by SQLite, vfs implementations should endeavor ** to prevent this by setting mxPathname to a sufficiently large value. ** ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() ** interfaces are not strictly a part of the filesystem, but they are ** included in the VFS structure for completeness. ** The xRandomness() function attempts to return nBytes bytes ** of good-quality randomness into zOut. The return value is ** the actual number of bytes of randomness obtained. ** The xSleep() method causes the calling thread to sleep for at ** least the number of microseconds given. ^The xCurrentTime() ** method returns a Julian Day Number for the current date and time as ** a floating point value. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian ** Day Number multiplied by 86400000 (the number of milliseconds in ** a 24-hour day). ** ^SQLite will use the xCurrentTimeInt64() method to get the current ** date and time if that method is available (if iVersion is 2 or ** greater and the function pointer is not NULL) and will fall back ** to xCurrentTime() if xCurrentTimeInt64() is unavailable. ** ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces ** are not used by the SQLite core. These optional interfaces are provided ** by some VFSes to facilitate testing of the VFS code. By overriding ** system calls with functions under its control, a test program can ** simulate faults and error conditions that would otherwise be difficult ** or impossible to induce. The set of system calls that can be overridden ** varies from one VFS to another, and from one version of the same VFS to the ** next. Applications that use these interfaces must be prepared for any ** or all of these interfaces to be NULL or for their behavior to change ** from one release to the next. Applications must not attempt to access ** any of these methods if the iVersion of the VFS is less than 3. */ typedef struct sqlite3_vfs sqlite3_vfs; typedef void (*sqlite3_syscall_ptr)(void); struct sqlite3_vfs { int iVersion; /* Structure version number (currently 3) */ int szOsFile; /* Size of subclassed sqlite3_file */ int mxPathname; /* Maximum file pathname length */ sqlite3_vfs *pNext; /* Next registered VFS */ const char *zName; /* Name of this virtual file system */ void *pAppData; /* Pointer to application-specific data */ int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags); int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); void (*xDlClose)(sqlite3_vfs*, void*); int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); int (*xSleep)(sqlite3_vfs*, int microseconds); int (*xCurrentTime)(sqlite3_vfs*, double*); int (*xGetLastError)(sqlite3_vfs*, int, char *); /* ** The methods above are in version 1 of the sqlite_vfs object ** definition. Those that follow are added in version 2 or later */ int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); /* ** The methods above are in versions 1 and 2 of the sqlite_vfs object. ** Those below are for version 3 and greater. */ int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); /* ** The methods above are in versions 1 through 3 of the sqlite_vfs object. ** New fields may be appended in future versions. The iVersion ** value will increment whenever this happens. */ }; /* ** CAPI3REF: Flags for the xAccess VFS method ** ** These integer constants can be used as the third parameter to ** the xAccess method of an [sqlite3_vfs] object. They determine ** what kind of permissions the xAccess method is looking for. ** With SQLITE_ACCESS_EXISTS, the xAccess method ** simply checks whether the file exists. ** With SQLITE_ACCESS_READWRITE, the xAccess method ** checks whether the named directory is both readable and writable ** (in other words, if files can be added, removed, and renamed within ** the directory). ** The SQLITE_ACCESS_READWRITE constant is currently used only by the ** [temp_store_directory pragma], though this could change in a future ** release of SQLite. ** With SQLITE_ACCESS_READ, the xAccess method ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is ** currently unused, though it might be used in a future release of ** SQLite. */ #define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ #define SQLITE_ACCESS_READ 2 /* Unused */ /* ** CAPI3REF: Flags for the xShmLock VFS method ** ** These integer constants define the various locking operations ** allowed by the xShmLock method of [sqlite3_io_methods]. The ** following are the only legal combinations of flags to the ** xShmLock method: ** ** <ul> ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE ** </ul> ** ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as ** was given on the corresponding lock. ** ** The xShmLock method can transition between unlocked and SHARED or ** between unlocked and EXCLUSIVE. It cannot transition between SHARED ** and EXCLUSIVE. */ #define SQLITE_SHM_UNLOCK 1 #define SQLITE_SHM_LOCK 2 #define SQLITE_SHM_SHARED 4 #define SQLITE_SHM_EXCLUSIVE 8 /* ** CAPI3REF: Maximum xShmLock index ** ** The xShmLock method on [sqlite3_io_methods] may use values ** between 0 and this upper bound as its "offset" argument. ** The SQLite core will never attempt to acquire or release a ** lock outside of this range */ #define SQLITE_SHM_NLOCK 8 /* ** CAPI3REF: Initialize The SQLite Library ** ** ^The sqlite3_initialize() routine initializes the ** SQLite library. ^The sqlite3_shutdown() routine ** deallocates any resources that were allocated by sqlite3_initialize(). ** These routines are designed to aid in process initialization and ** shutdown on embedded systems. Workstation applications using ** SQLite normally do not need to invoke either of these routines. ** ** A call to sqlite3_initialize() is an "effective" call if it is ** the first time sqlite3_initialize() is invoked during the lifetime of ** the process, or if it is the first time sqlite3_initialize() is invoked ** following a call to sqlite3_shutdown(). ^(Only an effective call ** of sqlite3_initialize() does any initialization. All other calls ** are harmless no-ops.)^ ** ** A call to sqlite3_shutdown() is an "effective" call if it is the first ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only ** an effective call to sqlite3_shutdown() does any deinitialization. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ ** ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() ** is not. The sqlite3_shutdown() interface must only be called from a ** single thread. All open [database connections] must be closed and all ** other SQLite resources must be deallocated prior to invoking ** sqlite3_shutdown(). ** ** Among other things, ^sqlite3_initialize() will invoke ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() ** will invoke sqlite3_os_end(). ** ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. ** ^If for some reason, sqlite3_initialize() is unable to initialize ** the library (perhaps it is unable to allocate a needed resource such ** as a mutex) it returns an [error code] other than [SQLITE_OK]. ** ** ^The sqlite3_initialize() routine is called internally by many other ** SQLite interfaces so that an application usually does not need to ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] ** calls sqlite3_initialize() so the SQLite library will be automatically ** initialized when [sqlite3_open()] is called if it has not be initialized ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] ** compile-time option, then the automatic calls to sqlite3_initialize() ** are omitted and the application must call sqlite3_initialize() directly ** prior to using any other SQLite interface. For maximum portability, ** it is recommended that applications always invoke sqlite3_initialize() ** directly prior to using any other SQLite interface. Future releases ** of SQLite may require this. In other words, the behavior exhibited ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the ** default behavior in some future release of SQLite. ** ** The sqlite3_os_init() routine does operating-system specific ** initialization of the SQLite library. The sqlite3_os_end() ** routine undoes the effect of sqlite3_os_init(). Typical tasks ** performed by these routines include allocation or deallocation ** of static resources, initialization of global variables, ** setting up a default [sqlite3_vfs] module, or setting up ** a default configuration using [sqlite3_config()]. ** ** The application should never invoke either sqlite3_os_init() ** or sqlite3_os_end() directly. The application should only invoke ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() ** interface is called automatically by sqlite3_initialize() and ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate ** implementations for sqlite3_os_init() and sqlite3_os_end() ** are built into SQLite when it is compiled for Unix, Windows, or OS/2. ** When [custom builds | built for other platforms] ** (using the [SQLITE_OS_OTHER=1] compile-time ** option) the application must supply a suitable implementation for ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied ** implementation of sqlite3_os_init() or sqlite3_os_end() ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ SQLITE_API int sqlite3_initialize(void); SQLITE_API int sqlite3_shutdown(void); SQLITE_API int sqlite3_os_init(void); SQLITE_API int sqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library ** ** The sqlite3_config() interface is used to make global configuration ** changes to SQLite in order to tune SQLite to the specific needs of ** the application. The default configuration is recommended for most ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** ** <b>The sqlite3_config() interface is not threadsafe. The application ** must ensure that no other SQLite interfaces are invoked by other ** threads while sqlite3_config() is running.</b> ** ** The sqlite3_config() interface ** may only be invoked prior to library initialization using ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. ** Note, however, that ^sqlite3_config() can be called as part of the ** implementation of an application-defined [sqlite3_os_init()]. ** ** The first argument to sqlite3_config() is an integer ** [configuration option] that determines ** what property of SQLite is to be configured. Subsequent arguments ** vary depending on the [configuration option] ** in the first argument. ** ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. ** ^If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. */ SQLITE_API int sqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections ** METHOD: sqlite3 ** ** The sqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to ** [sqlite3_config()] except that the changes apply to a single ** [database connection] (specified in the first argument). ** ** The second argument to sqlite3_db_config(D,V,...) is the ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code ** that indicates what aspect of the [database connection] is being configured. ** Subsequent arguments vary depending on the configuration verb. ** ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if ** the call is considered successful. */ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines ** ** An instance of this object defines the interface between SQLite ** and low-level memory allocation routines. ** ** This object is used in only one place in the SQLite interface. ** A pointer to an instance of this object is the argument to ** [sqlite3_config()] when the configuration option is ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. ** By creating an instance of this object ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) ** during configuration, an application can specify an alternative ** memory allocation subsystem for SQLite to use for all of its ** dynamic memory needs. ** ** Note that SQLite comes with several [built-in memory allocators] ** that are perfectly adequate for the overwhelming majority of applications ** and that this object is only useful to a tiny minority of applications ** with specialized memory allocation requirements. This object is ** also used during testing of SQLite in order to specify an alternative ** memory allocator that simulates memory out-of-memory conditions in ** order to verify that SQLite recovers gracefully from such ** conditions. ** ** The xMalloc, xRealloc, and xFree methods must work like the ** malloc(), realloc() and free() functions from the standard C library. ** ^SQLite guarantees that the second argument to ** xRealloc is always a value returned by a prior call to xRoundup. ** ** xSize should return the allocated size of a memory allocation ** previously obtained from xMalloc or xRealloc. The allocated size ** is always at least as big as the requested size but may be larger. ** ** The xRoundup method returns what would be the allocated size of ** a memory allocation given a particular requested size. Most memory ** allocators round up memory allocations at least to the next multiple ** of 8. Some allocators round up to a larger multiple or to a power of 2. ** Every memory allocation request coming in through [sqlite3_malloc()] ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, ** that causes the corresponding memory allocation to fail. ** ** The xInit method initializes the memory allocator. For example, ** it might allocate any require mutexes or initialize internal data ** structures. The xShutdown method is invoked (indirectly) by ** [sqlite3_shutdown()] and should deallocate any resources acquired ** by xInit. The pAppData pointer is used as the only parameter to ** xInit and xShutdown. ** ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes ** the xInit method, so the xInit method need not be threadsafe. The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. For all other methods, SQLite ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which ** it is by default) and so the methods are automatically serialized. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other ** methods must be threadsafe or else make their own arrangements for ** serialization. ** ** SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). */ typedef struct sqlite3_mem_methods sqlite3_mem_methods; struct sqlite3_mem_methods { void *(*xMalloc)(int); /* Memory allocation function */ void (*xFree)(void*); /* Free a prior allocation */ void *(*xRealloc)(void*,int); /* Resize an allocation */ int (*xSize)(void*); /* Return the size of an allocation */ int (*xRoundup)(int); /* Round up request size to allocation size */ int (*xInit)(void*); /* Initialize the memory allocator */ void (*xShutdown)(void*); /* Deinitialize the memory allocator */ void *pAppData; /* Argument to xInit() and xShutdown() */ }; /* ** CAPI3REF: Configuration Options ** KEYWORDS: {configuration option} ** ** These constants are the available integer configuration options that ** can be passed as the first argument to the [sqlite3_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_config()] to make sure that ** the call worked. The [sqlite3_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** ** <dl> ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt> ** <dd>There are no arguments to this option. ^This option sets the ** [threading mode] to Single-thread. In other words, it disables ** all mutexing and puts SQLite into a mode where it can only be used ** by a single thread. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to change the [threading mode] from its default ** value of Single-thread and so [sqlite3_config()] will return ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD ** configuration option.</dd> ** ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt> ** <dd>There are no arguments to this option. ^This option sets the ** [threading mode] to Multi-thread. In other words, it disables ** mutexing on [database connection] and [prepared statement] objects. ** The application is responsible for serializing access to ** [database connections] and [prepared statements]. But other mutexes ** are enabled so that SQLite will be safe to use in a multi-threaded ** environment as long as no two threads attempt to use the same ** [database connection] at the same time. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Multi-thread [threading mode] and ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd> ** ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt> ** <dd>There are no arguments to this option. ^This option sets the ** [threading mode] to Serialized. In other words, this option enables ** all mutexes including the recursive ** mutexes on [database connection] and [prepared statement] objects. ** In this mode (which is the default when SQLite is compiled with ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access ** to [database connections] and [prepared statements] so that the ** application is free to use the same [database connection] or the ** same [prepared statement] in different threads at the same time. ** ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Serialized [threading mode] and ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_SERIALIZED configuration option.</dd> ** ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt> ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is ** a pointer to an instance of the [sqlite3_mem_methods] structure. ** The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.)^ ^SQLite makes ** its own private copy of the content of the [sqlite3_mem_methods] structure ** before the [sqlite3_config()] call returns.</dd> ** ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt> ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which ** is a pointer to an instance of the [sqlite3_mem_methods] structure. ** The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example. </dd> ** ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt> ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, ** interpreted as a boolean, which enables or disables the collection of ** memory allocation statistics. ^(When memory allocation statistics are ** disabled, the following SQLite interfaces become non-operational: ** <ul> ** <li> [sqlite3_memory_used()] ** <li> [sqlite3_memory_highwater()] ** <li> [sqlite3_soft_heap_limit64()] ** <li> [sqlite3_status64()] ** </ul>)^ ** ^Memory allocation statistics are enabled by default unless SQLite is ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory ** allocation statistics are disabled by default. ** </dd> ** ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt> ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer ** that SQLite can use for scratch memory. ^(There are three arguments ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte ** aligned memory buffer from which the scratch allocations will be ** drawn, the size of each scratch allocation (sz), ** and the maximum number of scratch allocations (N).)^ ** The first argument must be a pointer to an 8-byte aligned buffer ** of at least sz*N bytes of memory. ** ^SQLite will not use more than one scratch buffers per thread. ** ^SQLite will never request a scratch buffer that is more than 6 ** times the database page size. ** ^If SQLite needs needs additional ** scratch memory beyond what is provided by this configuration option, then ** [sqlite3_malloc()] will be used to obtain the memory needed.<p> ** ^When the application provides any amount of scratch memory using ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large ** [sqlite3_malloc|heap allocations]. ** This can help [Robson proof|prevent memory allocation failures] due to heap ** fragmentation in low-memory embedded systems. ** </dd> ** ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt> ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool ** that SQLite can use for the database page cache with the default page ** cache implementation. ** This configuration option is a no-op if an application-define page ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to ** 8-byte aligned memory (pMem), the size of each page cache line (sz), ** and the number of cache lines (N). ** The sz argument should be the size of the largest database page ** (a power of two between 512 and 65536) plus some extra bytes for each ** page header. ^The number of extra bytes needed by the page header ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ]. ** ^It is harmless, apart from the wasted memory, ** for the sz parameter to be larger than necessary. The pMem ** argument must be either a NULL pointer or a pointer to an 8-byte ** aligned block of memory of at least sz*N bytes, otherwise ** subsequent behavior is undefined. ** ^When pMem is not NULL, SQLite will strive to use the memory provided ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if ** a page cache line is larger than sz bytes or if all of the pMem buffer ** is exhausted. ** ^If pMem is NULL and N is non-zero, then each database connection ** does an initial bulk allocation for page cache memory ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or ** of -1024*N bytes if N is negative, . ^If additional ** page cache memory is needed beyond what is provided by the initial ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each ** additional cache line. </dd> ** ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt> ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer ** that SQLite will use for all of its dynamic memory allocation needs ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and ** [SQLITE_CONFIG_PAGECACHE]. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns ** [SQLITE_ERROR] if invoked otherwise. ** ^There are three arguments to SQLITE_CONFIG_HEAP: ** An 8-byte aligned pointer to the memory, ** the number of bytes in the memory buffer, and the minimum allocation size. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts ** to using its default memory allocator (the system malloc() implementation), ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the ** memory pointer is not NULL then the alternative memory ** allocator is engaged to handle all of SQLites memory allocation needs. ** The first pointer (the memory pointer) must be aligned to an 8-byte ** boundary or subsequent behavior of SQLite will be undefined. ** The minimum allocation size is capped at 2**12. Reasonable values ** for the minimum allocation size are 2**5 through 2**8.</dd> ** ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt> ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a ** pointer to an instance of the [sqlite3_mutex_methods] structure. ** The argument specifies alternative low-level mutex routines to be used ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of ** the content of the [sqlite3_mutex_methods] structure before the call to ** [sqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will ** return [SQLITE_ERROR].</dd> ** ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt> ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The ** [sqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines.)^ ** This option can be used to overload the default mutex allocation ** routines with a wrapper used to track mutex usage for performance ** profiling or testing, for example. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will ** return [SQLITE_ERROR].</dd> ** ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt> ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine ** the default size of lookaside memory on each [database connection]. ** The first argument is the ** size of each lookaside buffer slot and the second is the number of ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] ** option to [sqlite3_db_config()] can be used to change the lookaside ** configuration on individual connections.)^ </dd> ** ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies ** the interface to a custom page cache implementation.)^ ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd> ** ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of ** the current page cache implementation into that object.)^ </dd> ** ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt> ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite ** global [error log]. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a ** function with a call signature of void(*)(void*,int,const char*), ** and a pointer to void. ^If the function pointer is not NULL, it is ** invoked by [sqlite3_log()] to process each logging event. ^If the ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is ** passed through as the first parameter to the application-defined logger ** function whenever that function is invoked. ^The second parameter to ** the logger function is a copy of the first parameter to the corresponding ** [sqlite3_log()] call and is intended to be a [result code] or an ** [extended result code]. ^The third parameter passed to the logger is ** log message after formatting via [sqlite3_snprintf()]. ** The SQLite logging interface is not reentrant; the logger function ** supplied by the application must not invoke any SQLite interface. ** In a multi-threaded application, the application-defined logger ** function must be threadsafe. </dd> ** ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int. ** If non-zero, then URI handling is globally enabled. If the parameter is zero, ** then URI handling is globally disabled.)^ ^If URI handling is globally ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], ** [sqlite3_open16()] or ** specified as part of [ATTACH] commands are interpreted as URIs, regardless ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database ** connection is opened. ^If it is globally disabled, filenames are ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the ** database connection is opened. ^(By default, URI handling is globally ** disabled. The default value may be changed by compiling with the ** [SQLITE_USE_URI] symbol defined.)^ ** ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer ** argument which is interpreted as a boolean in order to enable or disable ** the use of covering indices for full table scans in the query optimizer. ** ^The default setting is determined ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" ** if that compile-time option is omitted. ** The ability to disable the use of covering indices for full table scans ** is because some incorrectly coded legacy applications might malfunction ** when the optimization is enabled. Providing the ability to ** disable the optimization allows the older, buggy application code to work ** without change even with newer versions of SQLite. ** ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE ** <dd> These options are obsolete and should not be used by new code. ** They are retained for backwards compatibility but are now no-ops. ** </dd> ** ** [[SQLITE_CONFIG_SQLLOG]] ** <dt>SQLITE_CONFIG_SQLLOG ** <dd>This option is only available if sqlite is compiled with the ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). ** The second should be of type (void*). The callback is invoked by the library ** in three separate circumstances, identified by the value passed as the ** fourth parameter. If the fourth parameter is 0, then the database connection ** passed as the second argument has just been opened. The third argument ** points to a buffer containing the name of the main database file. If the ** fourth parameter is 1, then the SQL statement that the third parameter ** points to has just been executed. Or, if the fourth parameter is 2, then ** the connection being passed as the second parameter is being closed. The ** third parameter is passed NULL In this case. An example of using this ** configuration option can be seen in the "test_sqllog.c" source file in ** the canonical SQLite source tree.</dd> ** ** [[SQLITE_CONFIG_MMAP_SIZE]] ** <dt>SQLITE_CONFIG_MMAP_SIZE ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values ** that are the default mmap size limit (the default setting for ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. ** ^The default setting can be overridden by each database connection using ** either the [PRAGMA mmap_size] command, or by using the ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size ** will be silently truncated if necessary so that it does not exceed the ** compile-time maximum mmap size set by the ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ ** ^If either argument to this option is negative, then that argument is ** changed to its compile-time default. ** ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]] ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value ** that specifies the maximum size of the created heap. ** ** [[SQLITE_CONFIG_PCACHE_HDRSZ]] ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which ** is a pointer to an integer and writes into that integer the number of extra ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE]. ** The amount of extra space required can change depending on the compiler, ** target platform, and SQLite version. ** ** [[SQLITE_CONFIG_PMASZ]] ** <dt>SQLITE_CONFIG_PMASZ ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded ** sorter to that integer. The default minimum PMA Size is set by the ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched ** to help with sort operations when multithreaded sorting ** is enabled (using the [PRAGMA threads] command) and the amount of content ** to be sorted exceeds the page size times the minimum of the ** [PRAGMA cache_size] setting and this value. ** ** [[SQLITE_CONFIG_STMTJRNL_SPILL]] ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which ** becomes the [statement journal] spill-to-disk threshold. ** [Statement journals] are held in memory until their size (in bytes) ** exceeds this threshold, at which point they are written to disk. ** Or if the threshold is -1, statement journals are always held ** exclusively in memory. ** Since many statement journals never become large, setting the spill ** threshold to a value such as 64KiB can greatly reduce the amount of ** I/O required to support statement rollback. ** The default value for this setting is controlled by the ** [SQLITE_STMTJRNL_SPILL] compile-time option. ** </dl> */ #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */ #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ #define SQLITE_CONFIG_PCACHE 14 /* no-op */ #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ #define SQLITE_CONFIG_URI 17 /* int */ #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ /* ** CAPI3REF: Database Connection Configuration Options ** ** These constants are the available integer configuration options that ** can be passed as the second argument to the [sqlite3_db_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_db_config()] to make sure that ** the call worked. ^The [sqlite3_db_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** ** <dl> ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt> ** <dd> ^This option takes three additional arguments that determine the ** [lookaside memory allocator] configuration for the [database connection]. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a ** pointer to a memory buffer to use for lookaside memory. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb ** may be NULL in which case SQLite will allocate the ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the ** size of each lookaside buffer slot. ^The third argument is the number of ** slots. The size of the buffer in the first argument must be greater than ** or equal to the product of the second and third arguments. The buffer ** must be aligned to an 8-byte boundary. ^If the second argument to ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally ** rounded down to the next smaller multiple of 8. ^(The lookaside memory ** configuration for a database connection can only be changed when that ** connection is not currently using lookaside memory, or in other words ** when the "current value" returned by ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. ** Any attempt to change the lookaside memory configuration when lookaside ** memory is in use leaves the configuration unchanged and returns ** [SQLITE_BUSY].)^</dd> ** ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt> ** <dd> ^This option is used to enable or disable the enforcement of ** [foreign key constraints]. There should be two additional arguments. ** The first argument is an integer which is 0 to disable FK enforcement, ** positive to enable FK enforcement or negative to leave FK enforcement ** unchanged. The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether FK enforcement is off or on ** following this call. The second parameter may be a NULL pointer, in ** which case the FK enforcement setting is not reported back. </dd> ** ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt> ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers]. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable triggers, ** positive to enable triggers or negative to leave the setting unchanged. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether triggers are disabled or enabled ** following this call. The second parameter may be a NULL pointer, in ** which case the trigger setting is not reported back. </dd> ** ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt> ** <dd> ^This option is used to enable or disable the two-argument ** version of the [fts3_tokenizer()] function which is part of the ** [FTS3] full-text search engine extension. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or ** positive to enable fts3_tokenizer() or negative to leave the setting ** unchanged. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled ** following this call. The second parameter may be a NULL pointer, in ** which case the new setting is not reported back. </dd> ** ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt> ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()] ** interface independently of the [load_extension()] SQL function. ** The [sqlite3_enable_load_extension()] API enables or disables both the ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. ** There should be two additional arguments. ** When the first argument to this interface is 1, then only the C-API is ** enabled and the SQL function remains disabled. If the first argument to ** this interface is 0, then both the C-API and the SQL function are disabled. ** If the first argument is -1, then no changes are made to state of either the ** C-API or the SQL function. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface ** is disabled or enabled following this call. The second parameter may ** be a NULL pointer, in which case the new setting is not reported back. ** </dd> ** ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> ** <dd> ^This option is used to change the name of the "main" database ** schema. ^The sole argument is a pointer to a constant UTF8 string ** which will become the new schema name in place of "main". ^SQLite ** does not make a copy of the new main schema name string, so the application ** must ensure that the argument passed into this DBCONFIG option is unchanged ** until after the database connection closes. ** </dd> ** ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt> ** <dd> Usually, when a database in wal mode is closed or detached from a ** database handle, SQLite checks if this will mean that there are now no ** connections at all to the database. If so, it performs a checkpoint ** operation before closing the connection. This option may be used to ** override this behaviour. The first parameter passed to this operation ** is an integer - non-zero to disable checkpoints-on-close, or zero (the ** default) to enable them. The second parameter is a pointer to an integer ** into which is written 0 or 1 to indicate whether checkpoints-on-close ** have been disabled - 0 if they are not disabled, 1 if they are. ** </dd> ** ** </dl> */ #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */ #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes ** METHOD: sqlite3 ** ** ^The sqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. ^The extended result ** codes are disabled by default for historical compatibility. */ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid ** METHOD: sqlite3 ** ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) ** has a unique 64-bit signed ** integer key called the [ROWID | "rowid"]. ^The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those ** names are not also used by explicitly declared columns. ^If ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the ** most recent successful [INSERT] into a rowid table or [virtual table] ** on database connection D. ** ^Inserts into [WITHOUT ROWID] tables are not recorded. ** ^If no successful [INSERT]s into rowid tables ** have ever occurred on the database connection D, ** then sqlite3_last_insert_rowid(D) returns zero. ** ** ^(If an [INSERT] occurs within a trigger or within a [virtual table] ** method, then this routine will return the [rowid] of the inserted ** row as long as the trigger or virtual table method is running. ** But once the trigger or virtual table method ends, the value returned ** by this routine reverts to what it was before the trigger or virtual ** table method began.)^ ** ** ^An [INSERT] that fails due to a constraint violation is not a ** successful [INSERT] and does not change the value returned by this ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, ** and INSERT OR ABORT make no changes to the return value of this ** routine when their insertion fails. ^(When INSERT OR REPLACE ** encounters a constraint violation, it does not fail. The ** INSERT continues to completion after deleting rows that caused ** the constraint problem so INSERT OR REPLACE will always change ** the return value of this interface.)^ ** ** ^For the purposes of this routine, an [INSERT] is considered to ** be successful even if it is subsequently rolled back. ** ** This function is accessible to SQL statements via the ** [last_insert_rowid() SQL function]. ** ** If a separate thread performs a new [INSERT] on the same ** database connection while the [sqlite3_last_insert_rowid()] ** function is running and thus changes the last insert [rowid], ** then the value returned by [sqlite3_last_insert_rowid()] is ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified ** METHOD: sqlite3 ** ** ^This function returns the number of rows modified, inserted or ** deleted by the most recently completed INSERT, UPDATE or DELETE ** statement on the database connection specified by the only parameter. ** ^Executing any other type of SQL statement does not modify the value ** returned by this function. ** ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], ** [foreign key actions] or [REPLACE] constraint resolution are not counted. ** ** Changes to a view that are intercepted by ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or ** DELETE statement run on a view is always zero. Only changes made to real ** tables are counted. ** ** Things are more complicated if the sqlite3_changes() function is ** executed while a trigger program is running. This may happen if the ** program uses the [changes() SQL function], or if some other callback ** function invokes sqlite3_changes() directly. Essentially: ** ** <ul> ** <li> ^(Before entering a trigger program the value returned by ** sqlite3_changes() function is saved. After the trigger program ** has finished, the original value is restored.)^ ** ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE ** statement sets the value returned by sqlite3_changes() ** upon completion as normal. Of course, this value will not include ** any changes performed by sub-triggers, as the sqlite3_changes() ** value will be saved and restored after each sub-trigger has run.)^ ** </ul> ** ** ^This means that if the changes() SQL function (or similar) is used ** by the first INSERT, UPDATE or DELETE statement within a trigger, it ** returns the value as set when the calling statement began executing. ** ^If it is used by the second or subsequent such statement within a trigger ** program, the value returned reflects the number of rows modified by the ** previous INSERT, UPDATE or DELETE statement within the same trigger. ** ** See also the [sqlite3_total_changes()] interface, the ** [count_changes pragma], and the [changes() SQL function]. ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. */ SQLITE_API int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified ** METHOD: sqlite3 ** ** ^This function returns the total number of rows inserted, modified or ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed ** since the database connection was opened, including those executed as ** part of trigger programs. ^Executing any other type of SQL statement ** does not affect the value returned by sqlite3_total_changes(). ** ** ^Changes made as part of [foreign key actions] are included in the ** count, but those made as part of REPLACE constraint resolution are ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers ** are not counted. ** ** See also the [sqlite3_changes()] interface, the ** [count_changes pragma], and the [total_changes() SQL function]. ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. */ SQLITE_API int sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query ** METHOD: sqlite3 ** ** ^This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically ** called in response to a user action such as pressing "Cancel" ** or Ctrl-C where the user wants a long query operation to halt ** immediately. ** ** ^It is safe to call this routine from a thread different from the ** thread that is currently running the database operation. But it ** is not safe to call this routine with a [database connection] that ** is closed or might close before sqlite3_interrupt() returns. ** ** ^If an SQL operation is very nearly finished at the time when ** sqlite3_interrupt() is called, then it might not have an opportunity ** to be interrupted and might continue to completion. ** ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE ** that is inside an explicit transaction, then the entire transaction ** will be rolled back automatically. ** ** ^The sqlite3_interrupt(D) call is in effect until all currently running ** SQL statements on [database connection] D complete. ^Any new SQL statements ** that are started after the sqlite3_interrupt() call and before the ** running statements reaches zero are interrupted as if they had been ** running prior to the sqlite3_interrupt() call. ^New SQL statements ** that are started after the running statement count reaches zero are ** not effected by the sqlite3_interrupt(). ** ^A call to sqlite3_interrupt(D) that occurs when there are no running ** SQL statements is a no-op and has no effect on SQL statements ** that are started after the sqlite3_interrupt() call returns. ** ** If the database connection closes while [sqlite3_interrupt()] ** is running then bad things will likely happen. */ SQLITE_API void sqlite3_interrupt(sqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete ** ** These routines are useful during command-line input to determine if the ** currently entered text seems to form a complete SQL statement or ** if additional input is needed before sending the text into ** SQLite for parsing. ^These routines return 1 if the input string ** appears to be a complete SQL statement. ^A statement is judged to be ** complete if it ends with a semicolon token and is not a prefix of a ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within ** string literals or quoted identifier names or comments are not ** independent tokens (they are part of the token in which they are ** embedded) and thus do not count as a statement terminator. ^Whitespace ** and comments that follow the final semicolon are ignored. ** ** ^These routines return 0 if the statement is incomplete. ^If a ** memory allocation fails, then SQLITE_NOMEM is returned. ** ** ^These routines do not parse the SQL statements thus ** will not detect syntactically incorrect SQL. ** ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked ** automatically by sqlite3_complete16(). If that initialization fails, ** then the return value from sqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete.)^ ** ** The input to [sqlite3_complete()] must be a zero-terminated ** UTF-8 string. ** ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors ** KEYWORDS: {busy-handler callback} {busy handler} ** METHOD: sqlite3 ** ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X ** that might be invoked with argument P whenever ** an attempt is made to access a database table associated with ** [database connection] D when another thread ** or process has the table locked. ** The sqlite3_busy_handler() interface is used to implement ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. ** ** ^If the busy callback is NULL, then [SQLITE_BUSY] ** is returned immediately upon encountering the lock. ^If the busy callback ** is not NULL, then the callback might be invoked with two arguments. ** ** ^The first argument to the busy handler is a copy of the void* pointer which ** is the third argument to sqlite3_busy_handler(). ^The second argument to ** the busy handler callback is the number of times that the busy handler has ** been invoked previously for the same locking event. ^If the ** busy callback returns 0, then no additional attempts are made to ** access the database and [SQLITE_BUSY] is returned ** to the application. ** ^If the callback returns non-zero, then another attempt ** is made to access the database and the cycle repeats. ** ** The presence of a busy handler does not guarantee that it will be invoked ** when there is lock contention. ^If SQLite determines that invoking the busy ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] ** to the application instead of invoking the ** busy handler. ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying ** to promote to an exclusive lock. The first process cannot proceed ** because it is blocked by the second and the second process cannot ** proceed because it is blocked by the first. If both processes ** invoke the busy handlers, neither will make any progress. Therefore, ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this ** will induce the first process to release its read lock and allow ** the second process to proceed. ** ** ^The default busy callback is NULL. ** ** ^(There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] ** or evaluating [PRAGMA busy_timeout=N] will change the ** busy handler and thus clear any previously set busy handler. ** ** The busy callback should not take any actions which modify the ** database connection that invoked the busy handler. In other words, ** the busy handler is not reentrant. Any such actions ** result in undefined behavior. ** ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); /* ** CAPI3REF: Set A Busy Timeout ** METHOD: sqlite3 ** ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. ^The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. ^After at least "ms" milliseconds of sleeping, ** the handler returns 0 which causes [sqlite3_step()] to return ** [SQLITE_BUSY]. ** ** ^Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** ** ^(There can only be a single busy handler for a particular ** [database connection] at any given moment. If another busy handler ** was defined (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared.)^ ** ** See also: [PRAGMA busy_timeout] */ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries ** METHOD: sqlite3 ** ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. ** ** Definition: A <b>result table</b> is memory data structure created by the ** [sqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** ** The table conceptually has a number of rows and columns. But ** these numbers are not part of the result table itself. These ** numbers are obtained separately. Let N be the number of rows ** and M be the number of columns. ** ** A result table is an array of pointers to zero-terminated UTF-8 strings. ** There are (N+1)*M elements in the array. The first M pointers point ** to zero-terminated strings that contain the names of the columns. ** The remaining entries all point to query results. NULL values result ** in NULL pointers. All other values are in their UTF-8 zero-terminated ** string representation as returned by [sqlite3_column_text()]. ** ** A result table might consist of one or more memory allocations. ** It is not safe to pass a result table directly to [sqlite3_free()]. ** A result table should be deallocated using [sqlite3_free_table()]. ** ** ^(As an example of the result table format, suppose a query result ** is as follows: ** ** <blockquote><pre> ** Name | Age ** ----------------------- ** Alice | 43 ** Bob | 28 ** Cindy | 21 ** </pre></blockquote> ** ** There are two column (M==2) and three rows (N==3). Thus the ** result table has 8 entries. Suppose the result table is stored ** in an array names azResult. Then azResult holds this content: ** ** <blockquote><pre> ** azResult&#91;0] = "Name"; ** azResult&#91;1] = "Age"; ** azResult&#91;2] = "Alice"; ** azResult&#91;3] = "43"; ** azResult&#91;4] = "Bob"; ** azResult&#91;5] = "28"; ** azResult&#91;6] = "Cindy"; ** azResult&#91;7] = "21"; ** </pre></blockquote>)^ ** ** ^The sqlite3_get_table() function evaluates one or more ** semicolon-separated SQL statements in the zero-terminated UTF-8 ** string of its 2nd parameter and returns a result table to the ** pointer given in its 3rd parameter. ** ** After the application has finished with the result from sqlite3_get_table(), ** it must pass the result table pointer to sqlite3_free_table() in order to ** release the memory that was malloced. Because of the way the ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling ** function must not try to call [sqlite3_free()] directly. Only ** [sqlite3_free_table()] is able to release the memory properly and safely. ** ** The sqlite3_get_table() interface is implemented as a wrapper around ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access ** to any internal data structures of SQLite. It uses only the public ** interface defined here. As a consequence, errors that occur in the ** wrapper layer outside of the internal [sqlite3_exec()] call are not ** reflected in subsequent calls to [sqlite3_errcode()] or ** [sqlite3_errmsg()]. */ SQLITE_API int sqlite3_get_table( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows written here */ int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); SQLITE_API void sqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions ** ** These routines are work-alikes of the "printf()" family of functions ** from the standard C library. ** These routines understand most of the common K&R formatting options, ** plus some additional non-standard formats, detailed below. ** Note that some of the more obscure formatting options from recent ** C-library standards are omitted from this implementation. ** ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. ** The strings returned by these two routines should be ** released by [sqlite3_free()]. ^Both routines return a ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough ** memory to hold the resulting string. ** ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by ** the first parameter. Note that the order of the ** first two parameters is reversed from snprintf().)^ This is an ** historical accident that cannot be fixed without breaking ** backwards compatibility. ^(Note also that sqlite3_snprintf() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer.)^ We admit that ** the number of characters written would be a more useful return ** value but we cannot change the implementation of sqlite3_snprintf() ** now without breaking compatibility. ** ** ^As long as the buffer size is greater than zero, sqlite3_snprintf() ** guarantees that the buffer is always zero-terminated. ^The first ** parameter "n" is the total size of the buffer, including space for ** the zero terminator. So the longest string that can be completely ** written will be n-1 characters. ** ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). ** ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. ** All of the usual printf() formatting options apply. In addition, there ** is are "%q", "%Q", "%w" and "%z" options. ** ** ^(The %q option works like %s in that it substitutes a nul-terminated ** string from the argument list. But %q also doubles every '\'' character. ** %q is designed for use inside a string literal.)^ By doubling each '\'' ** character it escapes that character and allows it to be inserted into ** the string. ** ** For example, assume the string variable zText contains text as follows: ** ** <blockquote><pre> ** char *zText = "It's a happy day!"; ** </pre></blockquote> ** ** One can use this text in an SQL statement as follows: ** ** <blockquote><pre> ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); ** sqlite3_exec(db, zSQL, 0, 0, 0); ** sqlite3_free(zSQL); ** </pre></blockquote> ** ** Because the %q format string is used, the '\'' character in zText ** is escaped and the SQL generated is as follows: ** ** <blockquote><pre> ** INSERT INTO table1 VALUES('It''s a happy day!') ** </pre></blockquote> ** ** This is correct. Had we used %s instead of %q, the generated SQL ** would have looked like this: ** ** <blockquote><pre> ** INSERT INTO table1 VALUES('It's a happy day!'); ** </pre></blockquote> ** ** This second example is an SQL syntax error. As a general rule you should ** always use %q instead of %s when inserting text into a string literal. ** ** ^(The %Q option works like %q except it also adds single quotes around ** the outside of the total string. Additionally, if the parameter in the ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without ** single quotes).)^ So, for example, one could say: ** ** <blockquote><pre> ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); ** sqlite3_exec(db, zSQL, 0, 0, 0); ** sqlite3_free(zSQL); ** </pre></blockquote> ** ** The code above will render a correct SQL statement in the zSQL ** variable even if the zText variable is a NULL pointer. ** ** ^(The "%w" formatting option is like "%q" except that it expects to ** be contained within double-quotes instead of single quotes, and it ** escapes the double-quote character instead of the single-quote ** character.)^ The "%w" formatting option is intended for safely inserting ** table and column names into a constructed SQL statement. ** ** ^(The "%z" formatting option works like "%s" but with the ** addition that after the string has been read and copied into ** the result, [sqlite3_free()] is called on the input string.)^ */ SQLITE_API char *sqlite3_mprintf(const char*,...); SQLITE_API char *sqlite3_vmprintf(const char*, va_list); SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); /* ** CAPI3REF: Memory Allocation Subsystem ** ** The SQLite core uses these three routines for all of its own ** internal memory allocation needs. "Core" in the previous sentence ** does not include operating-system specific VFS implementation. The ** Windows VFS uses native malloc() and free() for some operations. ** ** ^The sqlite3_malloc() routine returns a pointer to a block ** of memory at least N bytes in length, where N is the parameter. ** ^If sqlite3_malloc() is unable to obtain sufficient free ** memory, it returns a NULL pointer. ^If the parameter N to ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns ** a NULL pointer. ** ** ^The sqlite3_malloc64(N) routine works just like ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead ** of a signed 32-bit integer. ** ** ^Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. ^The sqlite3_free() routine is ** a no-op if is called with a NULL pointer. Passing a NULL pointer ** to sqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. ** Memory corruption, a segmentation fault, or other severe error ** might result if sqlite3_free() is called with a non-NULL pointer that ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). ** ** ^The sqlite3_realloc(X,N) interface attempts to resize a ** prior memory allocation X to be at least N bytes. ** ^If the X parameter to sqlite3_realloc(X,N) ** is a NULL pointer then its behavior is identical to calling ** sqlite3_malloc(N). ** ^If the N parameter to sqlite3_realloc(X,N) is zero or ** negative then the behavior is exactly the same as calling ** sqlite3_free(X). ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation ** of at least N bytes in size or NULL if insufficient memory is available. ** ^If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned ** by sqlite3_realloc(X,N) and the prior allocation is freed. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the ** prior allocation is not freed. ** ** ^The sqlite3_realloc64(X,N) interfaces works the same as ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead ** of a 32-bit signed integer. ** ** ^If X is a memory allocation previously obtained from sqlite3_malloc(), ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then ** sqlite3_msize(X) returns the size of that memory allocation in bytes. ** ^The value returned by sqlite3_msize(X) might be larger than the number ** of bytes requested when X was allocated. ^If X is a NULL pointer then ** sqlite3_msize(X) returns zero. If X points to something that is not ** the beginning of memory allocation, or if it points to a formerly ** valid memory allocation that has now been freed, then the behavior ** of sqlite3_msize(X) is undefined and possibly harmful. ** ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), ** sqlite3_malloc64(), and sqlite3_realloc64() ** is always aligned to at least an 8 byte boundary, or to a ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time ** option is used. ** ** In SQLite version 3.5.0 and 3.5.1, it was possible to define ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in ** implementation of these routines to be omitted. That capability ** is no longer provided. Only built-in memory allocators can be used. ** ** Prior to SQLite version 3.7.10, the Windows OS interface layer called ** the system malloc() and free() directly when converting ** filenames between the UTF-8 encoding used by SQLite ** and whatever filename encoding is used by the particular Windows ** installation. Memory allocation errors were detected, but ** they were reported back as [SQLITE_CANTOPEN] or ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. ** ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] ** must be either NULL or else pointers obtained from a prior ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have ** not yet been released. ** ** The application must not read or write any part of ** a block of memory after it has been released using ** [sqlite3_free()] or [sqlite3_realloc()]. */ SQLITE_API void *sqlite3_malloc(int); SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); SQLITE_API void *sqlite3_realloc(void*, int); SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); SQLITE_API void sqlite3_free(void*); SQLITE_API sqlite3_uint64 sqlite3_msize(void*); /* ** CAPI3REF: Memory Allocator Statistics ** ** SQLite provides these two interfaces for reporting on the status ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] ** routines, which form the built-in memory allocation subsystem. ** ** ^The [sqlite3_memory_used()] routine returns the number of bytes ** of memory currently outstanding (malloced but not freed). ** ^The [sqlite3_memory_highwater()] routine returns the maximum ** value of [sqlite3_memory_used()] since the high-water mark ** was last reset. ^The values returned by [sqlite3_memory_used()] and ** [sqlite3_memory_highwater()] include any overhead ** added by SQLite in its implementation of [sqlite3_malloc()], ** but not overhead added by the any underlying system library ** routines that [sqlite3_malloc()] may call. ** ** ^The memory high-water mark is reset to the current value of ** [sqlite3_memory_used()] if and only if the parameter to ** [sqlite3_memory_highwater()] is true. ^The value returned ** by [sqlite3_memory_highwater(1)] is the high-water mark ** prior to the reset. */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void); SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator ** ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to ** select random [ROWID | ROWIDs] when inserting new records into a table that ** already uses the largest possible [ROWID]. The PRNG is also used for ** the build-in random() and randomblob() SQL functions. This interface allows ** applications to access the same PRNG for other purposes. ** ** ^A call to this routine stores N bytes of randomness into buffer P. ** ^The P parameter can be a NULL pointer. ** ** ^If this routine has not been previously called or if the previous ** call had N less than one or a NULL pointer for P, then the PRNG is ** seeded using randomness obtained from the xRandomness method of ** the default [sqlite3_vfs] object. ** ^If the previous call to this routine had an N of 1 or more and a ** non-NULL P then the pseudo-randomness is generated ** internally and without recourse to the [sqlite3_vfs] xRandomness ** method. */ SQLITE_API void sqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks ** METHOD: sqlite3 ** ** ^This routine registers an authorizer callback with a particular ** [database connection], supplied in the first argument. ** ^The authorizer callback is invoked as SQL statements are being compiled ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. ^The authorizer callback should ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the ** specific action but allow the SQL statement to continue to be ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be ** rejected with an error. ^If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] ** then the [sqlite3_prepare_v2()] or equivalent call that triggered ** the authorizer will fail with an error message. ** ** When the callback returns [SQLITE_OK], that means the operation ** requested is ok. ^When the callback returns [SQLITE_DENY], the ** [sqlite3_prepare_v2()] or equivalent call that triggered the ** authorizer will fail with an error message explaining that ** access is denied. ** ** ^The first parameter to the authorizer callback is a copy of the third ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter ** to the callback is an integer [SQLITE_COPY | action code] that specifies ** the particular action to be authorized. ^The third through sixth parameters ** to the callback are zero-terminated strings that contain additional ** details about the action to be authorized. ** ** ^If the action code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the ** [prepared statement] statement is constructed to substitute ** a NULL value in place of the table column that would have ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. ** ^If the action code is [SQLITE_DELETE] and the callback returns ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the ** [truncate optimization] is disabled and all rows are deleted individually. ** ** An authorizer is used when [sqlite3_prepare | preparing] ** SQL statements from an untrusted source, to ensure that the SQL statements ** do not try to access data they are not allowed to see, or that they do not ** try to execute malicious statements that damage the database. For ** example, an application may allow a user to enter arbitrary ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the ** user-entered SQL is being [sqlite3_prepare | prepared] that ** disallows everything except [SELECT] statements. ** ** Applications that need to process SQL from untrusted sources ** might also consider lowering resource limits using [sqlite3_limit()] ** and limiting database size using the [max_page_count] [PRAGMA] ** in addition to using an authorizer. ** ** ^(Only a single authorizer can be in place on a database connection ** at a time. Each call to sqlite3_set_authorizer overrides the ** previous call.)^ ^Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the ** statement might be re-prepared during [sqlite3_step()] due to a ** schema change. Hence, the application should ensure that the ** correct authorizer callback remains in place during the [sqlite3_step()]. ** ** ^Note that the authorizer callback is invoked only during ** [sqlite3_prepare()] or its variants. Authorization is not ** performed during statement evaluation in [sqlite3_step()], unless ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); /* ** CAPI3REF: Authorizer Return Codes ** ** The [sqlite3_set_authorizer | authorizer callback function] must ** return either [SQLITE_OK] or one of these two constants in order ** to signal SQLite whether or not the action is permitted. See the ** [sqlite3_set_authorizer | authorizer documentation] for additional ** information. ** ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] ** returned from the [sqlite3_vtab_on_conflict()] interface. */ #define SQLITE_DENY 1 /* Abort the SQL statement with an error */ #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ /* ** CAPI3REF: Authorizer Action Codes ** ** The [sqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorize certain SQL statement actions. The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that ** the authorizer callback may be passed. ** ** These action code values signify what kind of operation is to be ** authorized. The 3rd and 4th parameters to the authorization ** callback function will be parameters or NULL depending on which of these ** codes is used as the second parameter. ^(The 5th parameter to the ** authorizer callback is the name of the database ("main", "temp", ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback ** is the name of the inner-most trigger or view that is responsible for ** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ #define SQLITE_CREATE_VIEW 8 /* View Name NULL */ #define SQLITE_DELETE 9 /* Table Name NULL */ #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ #define SQLITE_DROP_TABLE 11 /* Table Name NULL */ #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ #define SQLITE_DROP_VIEW 17 /* View Name NULL */ #define SQLITE_INSERT 18 /* Table Name NULL */ #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ #define SQLITE_READ 20 /* Table Name Column Name */ #define SQLITE_SELECT 21 /* NULL NULL */ #define SQLITE_TRANSACTION 22 /* Operation NULL */ #define SQLITE_UPDATE 23 /* Table Name Column Name */ #define SQLITE_ATTACH 24 /* Filename NULL */ #define SQLITE_DETACH 25 /* Database Name NULL */ #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ #define SQLITE_REINDEX 27 /* Index Name NULL */ #define SQLITE_ANALYZE 28 /* Table Name NULL */ #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ #define SQLITE_FUNCTION 31 /* NULL Function Name */ #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ #define SQLITE_COPY 0 /* No longer used */ #define SQLITE_RECURSIVE 33 /* NULL NULL */ /* ** CAPI3REF: Tracing And Profiling Functions ** METHOD: sqlite3 ** ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface ** instead of the routines described here. ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** ** ^The callback function registered by sqlite3_trace() is invoked at ** various times when an SQL statement is being run by [sqlite3_step()]. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the ** SQL statement text as the statement first begins executing. ** ^(Additional sqlite3_trace() callbacks might occur ** as each triggered subprogram is entered. The callbacks for triggers ** contain a UTF-8 SQL comment that identifies the trigger.)^ ** ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit ** the length of [bound parameter] expansion in the output of sqlite3_trace(). ** ** ^The callback function registered by sqlite3_profile() is invoked ** as each SQL statement finishes. ^The profile callback contains ** the original statement text and an estimate of wall-clock time ** of how long that statement took to run. ^The profile callback ** time is in units of nanoseconds, however the current implementation ** is only capable of millisecond resolution so the six least significant ** digits in the time are meaningless. Future versions of SQLite ** might provide greater resolution on the profiler callback. The ** sqlite3_profile() function is considered experimental and is ** subject to change in future versions of SQLite. */ SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, void(*xProfile)(void*,const char*,sqlite3_uint64), void*); /* ** CAPI3REF: SQL Trace Event Codes ** KEYWORDS: SQLITE_TRACE ** ** These constants identify classes of events that can be monitored ** using the [sqlite3_trace_v2()] tracing logic. The third argument ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of ** the following constants. ^The first argument to the trace callback ** is one of the following constants. ** ** New tracing constants may be added in future releases. ** ** ^A trace callback has four arguments: xCallback(T,C,P,X). ** ^The T argument is one of the integer type codes above. ** ^The C argument is a copy of the context pointer passed in as the ** fourth argument to [sqlite3_trace_v2()]. ** The P and X arguments are pointers whose meanings depend on T. ** ** <dl> ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt> ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement ** first begins running and possibly at other times during the ** execution of the prepared statement, such as at the start of each ** trigger subprogram. ^The P argument is a pointer to the ** [prepared statement]. ^The X argument is a pointer to a string which ** is the unexpanded SQL text of the prepared statement or an SQL comment ** that indicates the invocation of a trigger. ^The callback can compute ** the same text that would have been returned by the legacy [sqlite3_trace()] ** interface by using the X argument when X begins with "--" and invoking ** [sqlite3_expanded_sql(P)] otherwise. ** ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt> ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same ** information as is provided by the [sqlite3_profile()] callback. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument points to a 64-bit integer which is the estimated of ** the number of nanosecond that the prepared statement took to run. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes. ** ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt> ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared ** statement generates a single row of result. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument is unused. ** ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt> ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database ** connection closes. ** ^The P argument is a pointer to the [database connection] object ** and the X argument is unused. ** </dl> */ #define SQLITE_TRACE_STMT 0x01 #define SQLITE_TRACE_PROFILE 0x02 #define SQLITE_TRACE_ROW 0x04 #define SQLITE_TRACE_CLOSE 0x08 /* ** CAPI3REF: SQL Trace Hook ** METHOD: sqlite3 ** ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback ** function X against [database connection] D, using property mask M ** and context pointer P. ^If the X callback is ** NULL or if the M mask is zero, then tracing is disabled. The ** M argument should be the bitwise OR-ed combination of ** zero or more [SQLITE_TRACE] constants. ** ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2(). ** ** ^The X callback is invoked whenever any of the events identified by ** mask M occur. ^The integer return value from the callback is currently ** ignored, though this may change in future releases. Callback ** implementations should return zero to ensure future compatibility. ** ** ^A trace callback is invoked with four arguments: callback(T,C,P,X). ** ^The T argument is one of the [SQLITE_TRACE] ** constants to indicate why the callback was invoked. ** ^The C argument is a copy of the context pointer. ** The P and X arguments are pointers whose meanings depend on T. ** ** The sqlite3_trace_v2() interface is intended to replace the legacy ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which ** are deprecated. */ SQLITE_API int sqlite3_trace_v2( sqlite3*, unsigned uMask, int(*xCallback)(unsigned,void*,void*,void*), void *pCtx ); /* ** CAPI3REF: Query Progress Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback ** function X to be invoked periodically during long running calls to ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for ** database connection D. An example use for this ** interface is to keep a GUI updated during a large query. ** ** ^The parameter P is passed through as the only parameter to the ** callback function X. ^The parameter N is the approximate number of ** [virtual machine instructions] that are evaluated between successive ** invocations of the callback X. ^If N is less than one then the progress ** handler is disabled. ** ** ^Only a single progress handler may be defined at one time per ** [database connection]; setting a new progress handler cancels the ** old one. ^Setting parameter X to NULL disables the progress handler. ** ^The progress handler is also disabled by setting N to a value less ** than 1. ** ** ^If the progress callback returns non-zero, the operation is ** interrupted. This feature can be used to implement a ** "Cancel" button on a GUI progress dialog box. ** ** The progress handler callback must not do anything that will modify ** the database connection that invoked the progress handler. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** */ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection ** CONSTRUCTOR: sqlite3 ** ** ^These routines open an SQLite database file as specified by the ** filename argument. ^The filename argument is interpreted as UTF-8 for ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte ** order for sqlite3_open16(). ^(A [database connection] handle is usually ** returned in *ppDb, even if an error occurs. The only exception is that ** if SQLite is unable to allocate memory to hold the [sqlite3] object, ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] ** object.)^ ^(If the database is opened (and/or created) successfully, then ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error following a failure of any ** of the sqlite3_open() routines. ** ** ^The default encoding will be UTF-8 for databases created using ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases ** created using sqlite3_open16() will be UTF-16 in the native byte order. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by ** passing it to [sqlite3_close()] when it is no longer required. ** ** The sqlite3_open_v2() interface works like sqlite3_open() ** except that it accepts two additional parameters for additional control ** over the new database connection. ^(The flags parameter to ** sqlite3_open_v2() can take one of ** the following three values, optionally combined with the ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ ** ** <dl> ** ^(<dt>[SQLITE_OPEN_READONLY]</dt> ** <dd>The database is opened in read-only mode. If the database does not ** already exist, an error is returned.</dd>)^ ** ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt> ** <dd>The database is opened for reading and writing if possible, or reading ** only if the file is write protected by the operating system. In either ** case the database must already exist, otherwise an error is returned.</dd>)^ ** ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt> ** <dd>The database is opened for reading and writing, and is created if ** it does not already exist. This is the behavior that is always used for ** sqlite3_open() and sqlite3_open16().</dd>)^ ** </dl> ** ** If the 3rd parameter to sqlite3_open_v2() is not one of the ** combinations shown above optionally combined with other ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] ** then the behavior is undefined. ** ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection ** opens in the multi-thread [threading mode] as long as the single-thread ** mode has not been set at compile-time or start-time. ^If the ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens ** in the serialized [threading mode] unless single-thread was ** previously selected at compile-time or start-time. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be ** eligible to use [shared cache mode], regardless of whether or not shared ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not ** participate in [shared cache mode] even if it is enabled. ** ** ^The fourth parameter to sqlite3_open_v2() is the name of the ** [sqlite3_vfs] object that defines the operating system interface that ** the new database connection should use. ^If the fourth parameter is ** a NULL pointer then the default [sqlite3_vfs] object is used. ** ** ^If the filename is ":memory:", then a private, temporary in-memory database ** is created for the connection. ^This in-memory database will vanish when ** the database connection is closed. Future versions of SQLite might ** make use of additional special filenames that begin with the ":" character. ** It is recommended that when a database filename actually does begin with ** a ":" character you should prefix the filename with a pathname such as ** "./" to avoid ambiguity. ** ** ^If the filename is an empty string, then a private, temporary ** on-disk database will be created. ^This private database will be ** automatically deleted as soon as the database connection is closed. ** ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3> ** ** ^If [URI filename] interpretation is enabled, and the filename argument ** begins with "file:", then the filename is interpreted as a URI. ^URI ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is ** set in the fourth argument to sqlite3_open_v2(), or if it has ** been enabled globally using the [SQLITE_CONFIG_URI] option with the ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. ** As of SQLite version 3.7.7, URI filename interpretation is turned off ** by default, but future releases of SQLite might enable URI filename ** interpretation by default. See "[URI filenames]" for additional ** information. ** ** URI filenames are parsed according to RFC 3986. ^If the URI contains an ** authority, then it must be either an empty string or the string ** "localhost". ^If the authority is not an empty string or "localhost", an ** error is returned to the caller. ^The fragment component of a URI, if ** present, is ignored. ** ** ^SQLite uses the path component of the URI as the name of the disk file ** which contains the database. ^If the path begins with a '/' character, ** then it is interpreted as an absolute path. ^If the path does not begin ** with a '/' (meaning that the authority section is omitted from the URI) ** then the path is interpreted as a relative path. ** ^(On windows, the first component of an absolute path ** is a drive specification (e.g. "C:").)^ ** ** [[core URI query parameters]] ** The query component of a URI may contain parameters that are interpreted ** either by SQLite itself, or by a [VFS | custom VFS implementation]. ** SQLite and its built-in [VFSes] interpret the ** following query parameters: ** ** <ul> ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of ** a VFS object that provides the operating system interface that should ** be used to access the database file on disk. ^If this option is set to ** an empty string the default VFS object is used. ^Specifying an unknown ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is ** present, then the VFS specified by the option takes precedence over ** the value passed as the fourth parameter to sqlite3_open_v2(). ** ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw", ** "rwc", or "memory". Attempting to set it to any other value is ** an error)^. ** ^If "ro" is specified, then the database is opened for read-only ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the ** third argument to sqlite3_open_v2(). ^If the mode option is set to ** "rw", then the database is opened for read-write (but not create) ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had ** been set. ^Value "rwc" is equivalent to setting both ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is ** set to "memory" then a pure [in-memory database] that never reads ** or writes from disk is used. ^It is an error to specify a value for ** the mode parameter that is less restrictive than that specified by ** the flags passed in the third parameter to sqlite3_open_v2(). ** ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or ** "private". ^Setting it to "shared" is equivalent to setting the ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in ** a URI filename, its value overrides any behavior requested by setting ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. ** ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the ** [powersafe overwrite] property does or does not apply to the ** storage media on which the database file resides. ** ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter ** which if set disables file locking in rollback journal modes. This ** is useful for accessing a database on a filesystem that does not ** support locking. Caution: Database corruption might result if two ** or more processes write to the same database and any one of those ** processes uses nolock=1. ** ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query ** parameter that indicates that the database file is stored on ** read-only media. ^When immutable is set, SQLite assumes that the ** database file cannot be changed, even by a process with higher ** privilege, and so the database is opened read-only and all locking ** and change detection is disabled. Caution: Setting the immutable ** property on a database file that does in fact change can result ** in incorrect query results and/or [SQLITE_CORRUPT] errors. ** See also: [SQLITE_IOCAP_IMMUTABLE]. ** ** </ul> ** ** ^Specifying an unknown parameter in the query component of a URI is not an ** error. Future versions of SQLite might understand additional query ** parameters. See "[query parameters with special meaning to SQLite]" for ** additional information. ** ** [[URI filename examples]] <h3>URI filename examples</h3> ** ** <table border="1" align=center cellpadding=5> ** <tr><th> URI filenames <th> Results ** <tr><td> file:data.db <td> ** Open the file "data.db" in the current directory. ** <tr><td> file:/home/fred/data.db<br> ** file:///home/fred/data.db <br> ** file://localhost/home/fred/data.db <br> <td> ** Open the database file "/home/fred/data.db". ** <tr><td> file://darkstar/home/fred/data.db <td> ** An error. "darkstar" is not a recognized authority. ** <tr><td style="white-space:nowrap"> ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db ** <td> Windows only: Open the file "data.db" on fred's desktop on drive ** C:. Note that the %20 escaping in this example is not strictly ** necessary - space characters can be used literally ** in URI filenames. ** <tr><td> file:data.db?mode=ro&cache=private <td> ** Open file "data.db" in the current directory for read-only access. ** Regardless of whether or not shared-cache mode is enabled by ** default, use a private cache. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td> ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile" ** that uses dot-files in place of posix advisory locking. ** <tr><td> file:data.db?mode=readonly <td> ** An error. "readonly" is not a valid option for the "mode" parameter. ** </table> ** ** ^URI hexadecimal escape sequences (%HH) are supported within the path and ** query components of a URI. A hexadecimal escape sequence consists of a ** percent sign - "%" - followed by exactly two hexadecimal digits ** specifying an octet value. ^Before the path or query components of a ** URI filename are interpreted, they are encoded using UTF-8 and all ** hexadecimal escape sequences replaced by a single byte containing the ** corresponding octet. If this process generates an invalid UTF-8 encoding, ** the results are undefined. ** ** <b>Note to Windows users:</b> The encoding used for the filename argument ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into ** sqlite3_open() or sqlite3_open_v2(). ** ** <b>Note to Windows Runtime users:</b> The temporary directory must be set ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various ** features that require the use of temporary files may fail. ** ** See also: [sqlite3_temp_directory] */ SQLITE_API int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open16( const void *filename, /* Database filename (UTF-16) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); /* ** CAPI3REF: Obtain Values For URI Parameters ** ** These are utility routines, useful to VFS implementations, that check ** to see if a database file was a URI that contained a specific query ** parameter, and if so obtains the value of that query parameter. ** ** If F is the database filename pointer passed into the xOpen() method of ** a VFS implementation when the flags parameter to xOpen() has one or ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and ** P is the name of the query parameter, then ** sqlite3_uri_parameter(F,P) returns the value of the P ** parameter if it exists or a NULL pointer if P does not appear as a ** query parameter on F. If P is a query parameter of F ** has no explicit value, then sqlite3_uri_parameter(F,P) returns ** a pointer to an empty string. ** ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean ** parameter and returns true (1) or false (0) according to the value ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the ** value of query parameter P is one of "yes", "true", or "on" in any ** case or if the value begins with a non-zero number. The ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of ** query parameter P is one of "no", "false", or "off" in any case or ** if the value begins with a numeric zero. If P is not a query ** parameter on F or if the value of P is does not match any of the ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). ** ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a ** 64-bit signed integer and returns that integer, or D if P does not ** exist. If the value of P is something other than an integer, then ** zero is returned. ** ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and ** is not a database file pathname pointer that SQLite passed into the xOpen ** VFS method, then the behavior of this routine is undefined and probably ** undesirable. */ SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); /* ** CAPI3REF: Error Codes And Messages ** METHOD: sqlite3 ** ** ^If the most recent sqlite3_* API call associated with ** [database connection] D failed, then the sqlite3_errcode(D) interface ** returns the numeric [result code] or [extended result code] for that ** API call. ** If the most recent API call was successful, ** then the return value from sqlite3_errcode() is undefined. ** ^The sqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. ** ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language ** text that describes the error, as either UTF-8 or UTF-16 respectively. ** ^(Memory to hold the error message string is managed internally. ** The application does not need to worry about freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions.)^ ** ** ^The sqlite3_errstr() interface returns the English-language text ** that describes the [result code], as UTF-8. ** ^(Memory to hold the error message string is managed internally ** and must not be freed by the application)^. ** ** When the serialized [threading mode] is in use, it might be the ** case that a second error occurs on a separate thread in between ** the time of the first error and the call to these interfaces. ** When that happens, the second error will be reported since these ** interfaces always report the most recent result. To avoid ** this, each thread can obtain exclusive use of the [database connection] D ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after ** all calls to the interfaces listed here are completed. ** ** If an interface fails with SQLITE_MISUSE, that means the interface ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. */ SQLITE_API int sqlite3_errcode(sqlite3 *db); SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); SQLITE_API const char *sqlite3_errmsg(sqlite3*); SQLITE_API const void *sqlite3_errmsg16(sqlite3*); SQLITE_API const char *sqlite3_errstr(int); /* ** CAPI3REF: Prepared Statement Object ** KEYWORDS: {prepared statement} {prepared statements} ** ** An instance of this object represents a single SQL statement that ** has been compiled into binary form and is ready to be evaluated. ** ** Think of each SQL statement as a separate computer program. The ** original SQL text is source code. A prepared statement object ** is the compiled object code. All SQL must be converted into a ** prepared statement before it can be run. ** ** The life-cycle of a prepared statement object usually goes like this: ** ** <ol> ** <li> Create the prepared statement object using [sqlite3_prepare_v2()]. ** <li> Bind values to [parameters] using the sqlite3_bind_*() ** interfaces. ** <li> Run the SQL by calling [sqlite3_step()] one or more times. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. ** <li> Destroy the object using [sqlite3_finalize()]. ** </ol> */ typedef struct sqlite3_stmt sqlite3_stmt; /* ** CAPI3REF: Run-time Limits ** METHOD: sqlite3 ** ** ^(This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the ** [database connection] whose limit is to be set or queried. The ** second parameter is one of the [limit categories] that define a ** class of constructs to be size limited. The third parameter is the ** new limit for that construct.)^ ** ** ^If the new limit is a negative number, the limit is unchanged. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a ** [limits | hard upper bound] ** set at compile-time by a C preprocessor macro called ** [limits | SQLITE_MAX_<i>NAME</i>]. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^ ** ^Attempts to increase a limit above its hard upper bound are ** silently truncated to the hard upper bound. ** ** ^Regardless of whether or not the limit was changed, the ** [sqlite3_limit()] interface returns the prior value of the limit. ** ^Hence, to find the current value of a limit without changing it, ** simply invoke this interface with the third parameter set to -1. ** ** Run-time limits are intended for use in applications that manage ** both their own internal database and also databases that are controlled ** by untrusted external sources. An example application might be a ** web browser that has its own databases for storing history and ** separate databases controlled by JavaScript applications downloaded ** off the Internet. The internal databases can be given the ** large, default limits. Databases managed by external sources can ** be given much smaller limits designed to prevent a denial of service ** attack. Developers might also want to use the [sqlite3_set_authorizer()] ** interface to further control untrusted SQL. The size of the database ** created by an untrusted script can be contained using the ** [max_page_count] [PRAGMA]. ** ** New run-time limit categories may be added in future releases. */ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories ** KEYWORDS: {limit category} {*limit categories} ** ** These constants define various performance limits ** that can be lowered at run-time using [sqlite3_limit()]. ** The synopsis of the meanings of the various limits is shown below. ** Additional information is available at [limits | Limits in SQLite]. ** ** <dl> ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt> ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^ ** ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt> ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^ ** ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt> ** <dd>The maximum number of columns in a table definition or in the ** result set of a [SELECT] or the maximum number of columns in an index ** or in an ORDER BY or GROUP BY clause.</dd>)^ ** ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt> ** <dd>The maximum depth of the parse tree on any expression.</dd>)^ ** ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt> ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^ ** ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt> ** <dd>The maximum number of instructions in a virtual machine program ** used to implement an SQL statement. This limit is not currently ** enforced, though that might be added in some future release of ** SQLite.</dd>)^ ** ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt> ** <dd>The maximum number of arguments on a function.</dd>)^ ** ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt> ** <dd>The maximum number of [ATTACH | attached databases].)^</dd> ** ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt> ** <dd>The maximum length of the pattern argument to the [LIKE] or ** [GLOB] operators.</dd>)^ ** ** [[SQLITE_LIMIT_VARIABLE_NUMBER]] ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt> ** <dd>The maximum index number of any [parameter] in an SQL statement.)^ ** ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt> ** <dd>The maximum depth of recursion for triggers.</dd>)^ ** ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt> ** <dd>The maximum number of auxiliary worker threads that a single ** [prepared statement] may start.</dd>)^ ** </dl> */ #define SQLITE_LIMIT_LENGTH 0 #define SQLITE_LIMIT_SQL_LENGTH 1 #define SQLITE_LIMIT_COLUMN 2 #define SQLITE_LIMIT_EXPR_DEPTH 3 #define SQLITE_LIMIT_COMPOUND_SELECT 4 #define SQLITE_LIMIT_VDBE_OP 5 #define SQLITE_LIMIT_FUNCTION_ARG 6 #define SQLITE_LIMIT_ATTACHED 7 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 #define SQLITE_LIMIT_WORKER_THREADS 11 /* ** CAPI3REF: Compiling An SQL Statement ** KEYWORDS: {SQL statement compiler} ** METHOD: sqlite3 ** CONSTRUCTOR: sqlite3_stmt ** ** To execute an SQL query, it must first be compiled into a byte-code ** program using one of these routines. ** ** The first argument, "db", is a [database connection] obtained from a ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or ** [sqlite3_open16()]. The database connection must not have been closed. ** ** The second argument, "zSql", is the statement to be compiled, encoded ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() ** use UTF-16. ** ** ^If the nByte argument is negative, then zSql is read up to the ** first zero terminator. ^If nByte is positive, then it is the ** number of bytes read from zSql. ^If nByte is zero, then no prepared ** statement is generated. ** If the caller knows that the supplied string is nul-terminated, then ** there is a small performance advantage to passing an nByte parameter that ** is the number of bytes in the input string <i>including</i> ** the nul-terminator. ** ** ^If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only ** compile the first statement in zSql, so *pzTail is left pointing to ** what remains uncompiled. ** ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set ** to NULL. ^If the input text contains no SQL (if the input is an empty ** string or a comment) then *ppStmt is set to NULL. ** The calling procedure is responsible for deleting the compiled ** SQL statement using [sqlite3_finalize()] after it has finished with it. ** ppStmt may not be NULL. ** ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; ** otherwise an [error code] is returned. ** ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are ** recommended for all new programs. The two older interfaces are retained ** for backwards compatibility, but their use is discouraged. ** ^In the "v2" interfaces, the prepared statement ** that is returned (the [sqlite3_stmt] object) contains a copy of the ** original SQL text. This causes the [sqlite3_step()] interface to ** behave differently in three ways: ** ** <ol> ** <li> ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it ** always used to do, [sqlite3_step()] will automatically recompile the SQL ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] ** retries will occur before sqlite3_step() gives up and returns an error. ** </li> ** ** <li> ** ^When an error occurs, [sqlite3_step()] will return one of the detailed ** [error codes] or [extended error codes]. ^The legacy behavior was that ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code ** and the application would have to make a second call to [sqlite3_reset()] ** in order to find the underlying cause of the problem. With the "v2" prepare ** interfaces, the underlying reason for the error is returned immediately. ** </li> ** ** <li> ** ^If the specific value bound to [parameter | host parameter] in the ** WHERE clause might influence the choice of query plan for a statement, ** then the statement will be automatically recompiled, as if there had been ** a schema change, on the first [sqlite3_step()] call following any change ** to the [sqlite3_bind_text | bindings] of that [parameter]. ** ^The specific value of WHERE-clause [parameter] might influence the ** choice of query plan if the parameter is the left-hand side of a [LIKE] ** or [GLOB] operator or if the parameter is compared to an indexed column ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. ** </li> ** </ol> */ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16_v2( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* ** CAPI3REF: Retrieving Statement SQL ** METHOD: sqlite3_stmt ** ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 ** SQL text used to create [prepared statement] P if P was ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 ** string containing the SQL text of prepared statement P with ** [bound parameters] expanded. ** ** ^(For example, if a prepared statement is created using the SQL ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345 ** and parameter :xyz is unbound, then sqlite3_sql() will return ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql() ** will return "SELECT 2345,NULL".)^ ** ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory ** is available to hold the result, or if the result would exceed the ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. ** ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time ** option causes sqlite3_expanded_sql() to always return NULL. ** ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is ** automatically freed when the prepared statement is finalized. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand, ** is obtained from [sqlite3_malloc()] and must be free by the application ** by passing it to [sqlite3_free()]. */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If An SQL Statement Writes The Database ** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if ** and only if the [prepared statement] X makes no direct changes to ** the content of the database file. ** ** Note that [application-defined SQL functions] or ** [virtual tables] might change the database indirectly as a side effect. ** ^(For example, if an application defines a function "eval()" that ** calls [sqlite3_exec()], then the following SQL statement would ** change the database file through side-effects: ** ** <blockquote><pre> ** SELECT eval('DELETE FROM t1') FROM t2; ** </pre></blockquote> ** ** But because the [SELECT] statement does not change the database file ** directly, sqlite3_stmt_readonly() would still return true.)^ ** ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, ** since the statements themselves do not actually modify the database but ** rather they control the timing of when other statements modify the ** database. ^The [ATTACH] and [DETACH] statements also cause ** sqlite3_stmt_readonly() to return true since, while those statements ** change the configuration of a database connection, they do not make ** changes to the content of the database files on disk. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so ** sqlite3_stmt_readonly() returns false for those commands. */ SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If A Prepared Statement Has Been Reset ** METHOD: sqlite3_stmt ** ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the ** [prepared statement] S has been stepped at least once using ** [sqlite3_step(S)] but has neither run to completion (returned ** [SQLITE_DONE] from [sqlite3_step(S)]) nor ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) ** interface returns false if S is a NULL pointer. If S is not a ** NULL pointer and is not a pointer to a valid [prepared statement] ** object, then the behavior is undefined and probably undesirable. ** ** This interface can be used in combination [sqlite3_next_stmt()] ** to locate all prepared statements associated with a database ** connection that are in need of being reset. This can be used, ** for example, in diagnostic routines to search for prepared ** statements that are holding a transaction open. */ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); /* ** CAPI3REF: Dynamically Typed Value Object ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} ** ** SQLite uses the sqlite3_value object to represent all values ** that can be stored in a database table. SQLite uses dynamic typing ** for the values it stores. ^Values stored in sqlite3_value objects ** can be integers, floating point values, strings, BLOBs, or NULL. ** ** An sqlite3_value object may be either "protected" or "unprotected". ** Some interfaces require a protected sqlite3_value. Other interfaces ** will accept either a protected or an unprotected sqlite3_value. ** Every interface that accepts sqlite3_value arguments specifies ** whether or not it requires a protected sqlite3_value. The ** [sqlite3_value_dup()] interface can be used to construct a new ** protected sqlite3_value from an unprotected sqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. An internal mutex is held for a protected ** sqlite3_value object but no mutex is held for an unprotected ** sqlite3_value object. If SQLite is compiled to be single-threaded ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) ** or if SQLite is run in one of reduced mutex modes ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] ** then there is no distinction between protected and unprotected ** sqlite3_value objects and they can be used interchangeably. However, ** for maximum code portability it is recommended that applications ** still make the distinction between protected and unprotected ** sqlite3_value objects even when not strictly required. ** ** ^The sqlite3_value objects that are passed as parameters into the ** implementation of [application-defined SQL functions] are protected. ** ^The sqlite3_value object returned by ** [sqlite3_column_value()] is unprotected. ** Unprotected sqlite3_value objects may only be used with ** [sqlite3_result_value()] and [sqlite3_bind_value()]. ** The [sqlite3_value_blob | sqlite3_value_type()] family of ** interfaces require protected sqlite3_value objects. */ typedef struct Mem sqlite3_value; /* ** CAPI3REF: SQL Function Context Object ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. ^A pointer to an sqlite3_context object ** is always first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], ** [sqlite3_aggregate_context()], [sqlite3_user_data()], ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], ** and/or [sqlite3_set_auxdata()]. */ typedef struct sqlite3_context sqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} ** METHOD: sqlite3_stmt ** ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] that matches one of following ** templates: ** ** <ul> ** <li> ? ** <li> ?NNN ** <li> :VVV ** <li> @VVV ** <li> $VVV ** </ul> ** ** In the templates above, NNN represents an integer literal, ** and VVV represents an alphanumeric identifier.)^ ^The values of these ** parameters (also called "host parameter names" or "SQL parameters") ** can be set using the sqlite3_bind_*() routines defined here. ** ** ^The first argument to the sqlite3_bind_*() routines is always ** a pointer to the [sqlite3_stmt] object returned from ** [sqlite3_prepare_v2()] or its variants. ** ** ^The second argument is the index of the SQL parameter to be set. ** ^The leftmost SQL parameter has an index of 1. ^When the same named ** SQL parameter is used more than once, second and subsequent ** occurrences have the same index as the first occurrence. ** ^The index for named parameters can be looked up using the ** [sqlite3_bind_parameter_index()] API if desired. ^The index ** for "?NNN" parameters is the value of NNN. ** ^The NNN value must be between 1 and the [sqlite3_limit()] ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). ** ** ^The third argument is the value to bind to the parameter. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter ** is ignored and the end result is the same as sqlite3_bind_null(). ** ** ^(In those routines that have a fourth argument, its value is the ** number of bytes in the parameter. To be clear: the value is the ** number of <u>bytes</u> in the value, not the number of characters.)^ ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() ** is negative, then the length of the string is ** the number of bytes up to the first zero terminator. ** If the fourth parameter to sqlite3_bind_blob() is negative, then ** the behavior is undefined. ** If a non-negative fourth parameter is provided to sqlite3_bind_text() ** or sqlite3_bind_text16() or sqlite3_bind_text64() then ** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL ** terminated. If any NUL characters occur at byte offsets less than ** the value of the fourth parameter then the resulting string value will ** contain embedded NULs. The result of expressions involving strings ** with embedded NULs is undefined. ** ** ^The fifth argument to the BLOB and string binding interfaces ** is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. ^The destructor is called ** to dispose of the BLOB or string even if the call to bind API fails. ** ^If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before ** the sqlite3_bind_*() routine returns. ** ** ^The sixth argument to sqlite3_bind_text64() must be one of ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] ** to specify the encoding of the text in the third parameter. If ** the sixth argument to sqlite3_bind_text64() is not one of the ** allowed values shown above, or if the text encoding is different ** from the encoding specified by the sixth parameter, then the behavior ** is undefined. ** ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. ** Zeroblobs are intended to serve as placeholders for BLOBs whose ** content is later written using ** [sqlite3_blob_open | incremental BLOB I/O] routines. ** ^A negative value for the zeroblob results in a zero-length BLOB. ** ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer ** for the [prepared statement] or with a prepared statement for which ** [sqlite3_step()] has been called more recently than [sqlite3_reset()], ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() ** routine is passed a [prepared statement] that has been finalized, the ** result is undefined and probably harmful. ** ** ^Bindings are not cleared by the [sqlite3_reset()] routine. ** ^Unbound parameters are interpreted as NULL. ** ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an ** [error code] if anything goes wrong. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or ** [SQLITE_MAX_LENGTH]. ** ^[SQLITE_RANGE] is returned if the parameter ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. ** ** See also: [sqlite3_bind_parameter_count()], ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. */ SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, void(*)(void*)); SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, void(*)(void*), unsigned char encoding); SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); /* ** CAPI3REF: Number Of SQL Parameters ** METHOD: sqlite3_stmt ** ** ^This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as ** placeholders for values that are [sqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** ^(This routine actually returns the index of the largest (rightmost) ** parameter. For all forms except ?NNN, this will correspond to the ** number of unique parameters. If parameters of the ?NNN form are used, ** there may be gaps in the list.)^ ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_name()], and ** [sqlite3_bind_parameter_index()]. */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter ** METHOD: sqlite3_stmt ** ** ^The sqlite3_bind_parameter_name(P,N) interface returns ** the name of the N-th [SQL parameter] in the [prepared statement] P. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" ** respectively. ** In other words, the initial ":" or "$" or "@" or "?" ** is included as part of the name.)^ ** ^Parameters of the form "?" without a following integer have no name ** and are referred to as "nameless" or "anonymous parameters". ** ** ^The first host parameter has an index of 1, not 0. ** ** ^If the value N is out of range or if the N-th parameter is ** nameless, then NULL is returned. ^The returned string is ** always in UTF-8 encoding even if the named parameter was ** originally specified as UTF-16 in [sqlite3_prepare16()] or ** [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name ** METHOD: sqlite3_stmt ** ** ^Return the index of an SQL parameter given its name. ^The ** index value returned is suitable for use as the second ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero ** is returned if no matching parameter is found. ^The parameter ** name must be given in UTF-8 even if the original statement ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_name()]. */ SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement ** METHOD: sqlite3_stmt ** ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. ** ^Use this routine to reset all host parameters to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set ** METHOD: sqlite3_stmt ** ** ^Return the number of columns in the result set returned by the ** [prepared statement]. ^If this routine returns 0, that means the ** [prepared statement] returns no data (for example an [UPDATE]). ** ^However, just because this routine returns a positive number does not ** mean that one or more rows of data will be returned. ^A SELECT statement ** will always have a positive sqlite3_column_count() but depending on the ** WHERE clause constraints and the table content, it might return no rows. ** ** See also: [sqlite3_data_count()] */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set ** METHOD: sqlite3_stmt ** ** ^These routines return the name assigned to a particular column ** in the result set of a [SELECT] statement. ^The sqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF-8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated ** UTF-16 string. ^The first parameter is the [prepared statement] ** that implements the [SELECT] statement. ^The second parameter is the ** column number. ^The leftmost column is number 0. ** ** ^The returned string pointer is valid until either the [prepared statement] ** is destroyed by [sqlite3_finalize()] or until the statement is automatically ** reprepared by the first call to [sqlite3_step()] for a particular run ** or until the next call to ** sqlite3_column_name() or sqlite3_column_name16() on the same column. ** ** ^If sqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. ** ** ^The name of a result column is the value of the "AS" clause for ** that column, if there is an AS clause. If there is no AS clause ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. */ SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result ** METHOD: sqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and ** table column that is the origin of a particular result column in ** [SELECT] statement. ** ^The name of the database or table or column can be returned as ** either a UTF-8 or UTF-16 string. ^The _database_ routines return ** the database name, the _table_ routines return the table name, and ** the origin_ routines return the column name. ** ^The returned string is valid until the [prepared statement] is destroyed ** using [sqlite3_finalize()] or until the statement is automatically ** reprepared by the first call to [sqlite3_step()] for a particular run ** or until the same information is requested ** again in a different encoding. ** ** ^The names returned are the original un-aliased names of the ** database, table, and column. ** ** ^The first argument to these interfaces is a [prepared statement]. ** ^These functions return information about the Nth result column returned by ** the statement, where N is the second function argument. ** ^The left-most column is column 0 for these routines. ** ** ^If the Nth column returned by the statement is an expression or ** subquery and is not a column value, then all of these functions return ** NULL. ^These routine might also return NULL if a memory allocation error ** occurs. ^Otherwise, they return the name of the attached database, table, ** or column that query result column was extracted from. ** ** ^As with all other SQLite APIs, those whose names end with "16" return ** UTF-16 encoded strings and the other functions return UTF-8. ** ** ^These APIs are only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. ** ** If two or more threads call one or more of these routines against the same ** prepared statement and column at the same time then the results are ** undefined. ** ** If two or more threads call one or more ** [sqlite3_column_database_name | column metadata interfaces] ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result ** METHOD: sqlite3_stmt ** ** ^(The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the ** returned result set of that [SELECT] is a table column (not an ** expression or subquery) then the declared type of the table ** column is returned.)^ ^If the Nth column of the result set is an ** expression or subquery, then a NULL pointer is returned. ** ^The returned string is always UTF-8 encoded. ** ** ^(For example, given the database schema: ** ** CREATE TABLE t1(c1 VARIANT); ** ** and the following statement to be compiled: ** ** SELECT c1 + 1, c1 FROM t1; ** ** this routine would return the string "VARIANT" for the second result ** column (i==1), and a NULL pointer for the first result column (i==0).)^ ** ** ^SQLite uses dynamic run-time typing. ^So just because a column ** is declared to contain a particular type does not mean that the ** data stored in that column is of the declared type. SQLite is ** strongly typed, but the typing is dynamic not static. ^Type ** is associated with individual values, not with the containers ** used to hold those values. */ SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement ** METHOD: sqlite3_stmt ** ** After a [prepared statement] has been prepared using either ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function ** must be called one or more times to evaluate the statement. ** ** The details of the behavior of the sqlite3_step() interface depend ** on whether the statement was prepared using the newer "v2" interface ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the ** new "v2" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** ** ^In the legacy interface, the return value will be either [SQLITE_BUSY], ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. ** ^With the "v2" interface, any of the other [result codes] or ** [extended result codes] might be returned as well. ** ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the ** database locks it needs to do its job. ^If the statement is a [COMMIT] ** or occurs outside of an explicit transaction, then you can retry the ** statement. If the statement is not a [COMMIT] and occurs within an ** explicit transaction then you should rollback the transaction before ** continuing. ** ** ^[SQLITE_DONE] means that the statement has finished executing ** successfully. sqlite3_step() should not be called again on this virtual ** machine without first calling [sqlite3_reset()] to reset the virtual ** machine back to its initial state. ** ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] ** is returned each time a new row of data is ready for processing by the ** caller. The values may be accessed using the [column access functions]. ** sqlite3_step() is called again to retrieve the next row of data. ** ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint ** violation) has occurred. sqlite3_step() should not be called again on ** the VM. More information may be found by calling [sqlite3_errmsg()]. ** ^With the legacy interface, a more specific error code (for example, ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) ** can be obtained by calling [sqlite3_reset()] on the ** [prepared statement]. ^In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has ** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** ** For all versions of SQLite up to and including 3.6.23.1, a call to ** [sqlite3_reset()] was required after sqlite3_step() returned anything ** other than [SQLITE_ROW] before any subsequent invocation of ** sqlite3_step(). Failure to reset the prepared statement using ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], ** sqlite3_step() began ** calling [sqlite3_reset()] automatically in this circumstance rather ** than returning [SQLITE_MISUSE]. This is not considered a compatibility ** break because any application that ever receives an SQLITE_MISUSE error ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option ** can be used to restore the legacy behavior. ** ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step() ** API always returns a generic error code, [SQLITE_ERROR], following any ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the ** specific [error codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, ** then the more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. */ SQLITE_API int sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set ** METHOD: sqlite3_stmt ** ** ^The sqlite3_data_count(P) interface returns the number of columns in the ** current row of the result set of [prepared statement] P. ** ^If prepared statement P does not have results ready to return ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of ** interfaces) then sqlite3_data_count(P) returns 0. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) ** will return non-zero if previous call to [sqlite3_step](P) returned ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] ** where it always returns zero since each step of that multi-step ** pragma returns 0 columns of data. ** ** See also: [sqlite3_column_count()] */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes ** KEYWORDS: SQLITE_TEXT ** ** ^(Every value in SQLite has one of five fundamental datatypes: ** ** <ul> ** <li> 64-bit signed integer ** <li> 64-bit IEEE floating point number ** <li> string ** <li> BLOB ** <li> NULL ** </ul>)^ ** ** These constants are codes for each of those types. ** ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 ** for a completely different meaning. Software that links against both ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not ** SQLITE_TEXT. */ #define SQLITE_INTEGER 1 #define SQLITE_FLOAT 2 #define SQLITE_BLOB 4 #define SQLITE_NULL 5 #ifdef SQLITE_TEXT # undef SQLITE_TEXT #else # define SQLITE_TEXT 3 #endif #define SQLITE3_TEXT 3 /* ** CAPI3REF: Result Values From A Query ** KEYWORDS: {column access functions} ** METHOD: sqlite3_stmt ** ** ^These routines return information about a single column of the current ** result row of a query. ^In every case the first argument is a pointer ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] ** that was returned from [sqlite3_prepare_v2()] or one of its variants) ** and the second argument is the index of the column for which information ** should be returned. ^The leftmost column of the result set has the index 0. ** ^The number of columns in the result can be determined using ** [sqlite3_column_count()]. ** ** If the SQL statement does not currently point to a valid row, or if the ** column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. ** If any of these routines are called after [sqlite3_reset()] or ** [sqlite3_finalize()] or after [sqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] ** are called from a different thread while any of these routines ** are pending, then the results are undefined. ** ** ^The sqlite3_column_type() routine returns the ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. ^The returned value is one of [SQLITE_INTEGER], ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value ** returned by sqlite3_column_type() is only meaningful if no type ** conversions have occurred as described below. After a type conversion, ** the value returned by sqlite3_column_type() is undefined. Future ** versions of SQLite may change the behavior of sqlite3_column_type() ** following a type conversion. ** ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. ** ^If the result is a numeric value then sqlite3_column_bytes() uses ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns ** the number of bytes in that string. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero. ** ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() ** routine returns the number of bytes in that BLOB or string. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts ** the string to UTF-16 and then returns the number of bytes. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns ** the number of bytes in that string. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. ** ** ^The values returned by [sqlite3_column_bytes()] and ** [sqlite3_column_bytes16()] do not include the zero terminators at the end ** of the string. ^For clarity: the values returned by ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of ** bytes in the string, not the number of characters. ** ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), ** even empty strings, are always zero-terminated. ^The return ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. ** ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an ** [unprotected sqlite3_value] object. In a multithreaded environment, ** an unprotected sqlite3_value object may only be used safely with ** [sqlite3_bind_value()] and [sqlite3_result_value()]. ** If the [unprotected sqlite3_value] object returned by ** [sqlite3_column_value()] is used in any other way, including calls ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], ** or [sqlite3_value_bytes()], the behavior is not threadsafe. ** ** These routines attempt to convert the value where appropriate. ^For ** example, if the internal representation is FLOAT and a text result ** is requested, [sqlite3_snprintf()] is used internally to perform the ** conversion automatically. ^(The following table details the conversions ** that are applied: ** ** <blockquote> ** <table border="1"> ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion ** ** <tr><td> NULL <td> INTEGER <td> Result is 0 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL ** <tr><td> TEXT <td> BLOB <td> No change ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed ** </table> ** </blockquote>)^ ** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or ** sqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** ** <ul> ** <li> The initial content is a BLOB and sqlite3_column_text() or ** sqlite3_column_text16() is called. A zero-terminator might ** need to be added to the string.</li> ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or ** sqlite3_column_text16() is called. The content must be converted ** to UTF-16.</li> ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or ** sqlite3_column_text() is called. The content must be converted ** to UTF-8.</li> ** </ul> ** ** ^Conversions between UTF-16be and UTF-16le are always done in place and do ** not invalidate a prior pointer, though of course the content of the buffer ** that the prior pointer references will have been modified. Other kinds ** of conversion are done in place when it is possible, but sometimes they ** are not possible and in those cases prior pointers are invalidated. ** ** The safest policy is to invoke these routines ** in one of the following ways: ** ** <ul> ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> ** </ul> ** ** In other words, you should call sqlite3_column_text(), ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result ** into the desired format, then invoke sqlite3_column_bytes() or ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls ** to sqlite3_column_text() or sqlite3_column_blob() with calls to ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() ** with calls to sqlite3_column_bytes(). ** ** ^The pointers returned are valid until a type conversion occurs as ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or ** [sqlite3_finalize()] is called. ^The memory space used to hold strings ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into ** [sqlite3_free()]. ** ** ^(If a memory allocation error occurs during the evaluation of any ** of these routines, a default value is returned. The default value ** is either the integer 0, the floating point number 0.0, or a NULL ** pointer. Subsequent calls to [sqlite3_errcode()] will return ** [SQLITE_NOMEM].)^ */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object ** DESTRUCTOR: sqlite3_stmt ** ** ^The sqlite3_finalize() function is called to delete a [prepared statement]. ** ^If the most recent evaluation of the statement encountered no errors ** or if the statement is never been evaluated, then sqlite3_finalize() returns ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then ** sqlite3_finalize(S) returns the appropriate [error code] or ** [extended error code]. ** ** ^The sqlite3_finalize(S) routine can be called at any point during ** the life cycle of [prepared statement] S: ** before statement S is ever evaluated, after ** one or more calls to [sqlite3_reset()], or after any call ** to [sqlite3_step()] regardless of whether or not the statement has ** completed execution. ** ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. ** ** The application must finalize every [prepared statement] in order to avoid ** resource leaks. It is a grievous error for the application to try to use ** a prepared statement after it has been finalized. Any use of a prepared ** statement after it has been finalized can result in undefined and ** undesirable behavior such as segfaults and heap corruption. */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object ** METHOD: sqlite3_stmt ** ** The sqlite3_reset() function is called to reset a [prepared statement] ** object back to its initial state, ready to be re-executed. ** ^Any SQL statement variables that had values bound to them using ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. ** Use [sqlite3_clear_bindings()] to reset the bindings. ** ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S ** back to the beginning of its program. ** ** ^If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], ** or if [sqlite3_step(S)] has never before been called on S, ** then [sqlite3_reset(S)] returns [SQLITE_OK]. ** ** ^If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S indicated an error, then ** [sqlite3_reset(S)] returns an appropriate [error code]. ** ** ^The [sqlite3_reset(S)] interface does not change the values ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions ** KEYWORDS: {function creation routines} ** KEYWORDS: {application-defined SQL function} ** KEYWORDS: {application-defined SQL functions} ** METHOD: sqlite3 ** ** ^These functions (collectively known as "function creation routines") ** are used to add SQL functions or aggregates or to redefine the behavior ** of existing SQL functions or aggregates. The only differences between ** these routines are the text encoding expected for ** the second parameter (the name of the function being created) ** and the presence or absence of a destructor callback for ** the application data pointer. ** ** ^The first parameter is the [database connection] to which the SQL ** function is to be added. ^If an application uses more than one database ** connection then application-defined SQL functions must be added ** to each database connection separately. ** ** ^The second parameter is the name of the SQL function to be created or ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 ** representation, exclusive of the zero-terminator. ^Note that the name ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. ** ^Any attempt to create a function with a longer name ** will result in [SQLITE_MISUSE] being returned. ** ** ^The third parameter (nArg) ** is the number of arguments that the SQL function or ** aggregate takes. ^If this parameter is -1, then the SQL function or ** aggregate may take any number of arguments between 0 and the limit ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third ** parameter is less than -1 or greater than 127 then the behavior is ** undefined. ** ** ^The fourth parameter, eTextRep, specifies what ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. The application should set this parameter to ** [SQLITE_UTF16LE] if the function implementation invokes ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the ** implementation invokes [sqlite3_value_text16be()] on an input, or ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] ** otherwise. ^The same SQL function may be registered multiple times using ** different preferred text encodings, with different implementations for ** each encoding. ** ^When multiple implementations of the same function are available, SQLite ** will pick the one that involves the least amount of data conversion. ** ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC] ** to signal that the function will always return the same result given ** the same inputs within a single SQL statement. Most SQL functions are ** deterministic. The built-in [random()] SQL function is an example of a ** function that is not deterministic. The SQLite query planner is able to ** perform additional optimizations on deterministic functions, so use ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. ** ** ^(The fifth parameter is an arbitrary pointer. The implementation of the ** function can gain access to this pointer using [sqlite3_user_data()].)^ ** ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are ** pointers to C-language functions that implement the SQL function or ** aggregate. ^A scalar SQL function requires an implementation of the xFunc ** callback only; NULL pointers must be passed as the xStep and xFinal ** parameters. ^An aggregate SQL function requires an implementation of xStep ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing ** SQL function or aggregate, pass NULL pointers for all three function ** callbacks. ** ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, ** then it is destructor for the application data pointer. ** The destructor is invoked when the function is deleted, either by being ** overloaded or when the database connection closes.)^ ** ^The destructor is also invoked if the call to ** sqlite3_create_function_v2() fails. ** ^When the destructor callback of the tenth parameter is invoked, it ** is passed a single argument which is a copy of the application data ** pointer which was the fifth parameter to sqlite3_create_function_v2(). ** ** ^It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of ** arguments or differing preferred text encodings. ^SQLite will use ** the implementation that most closely matches the way in which the ** SQL function is used. ^A function implementation with a non-negative ** nArg parameter is a better match than a function implementation with ** a negative nArg. ^A function where the preferred text encoding ** matches the database encoding is a better ** match than a function where the encoding is different. ** ^A function where the encoding difference is between UTF16le and UTF16be ** is a closer match than a function where the encoding difference is ** between UTF8 and UTF16. ** ** ^Built-in functions may be overloaded by new application-defined functions. ** ** ^An application-defined function is permitted to call other ** SQLite interfaces. However, such calls must not ** close the database connection nor finalize or reset the prepared ** statement in which the function is running. */ SQLITE_API int sqlite3_create_function( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function16( sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function_v2( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*) ); /* ** CAPI3REF: Text Encodings ** ** These constant define integer codes that represent the various ** text encodings supported by SQLite. */ #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ /* ** CAPI3REF: Function Flags ** ** These constants may be ORed together with the ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument ** to [sqlite3_create_function()], [sqlite3_create_function16()], or ** [sqlite3_create_function_v2()]. */ #define SQLITE_DETERMINISTIC 0x800 /* ** CAPI3REF: Deprecated Functions ** DEPRECATED ** ** These functions are [deprecated]. In order to maintain ** backwards compatibility with older code, these functions continue ** to be supported. However, new applications should avoid ** the use of these functions. To encourage programmers to avoid ** these functions, we will not explain what they do. */ #ifndef SQLITE_OMIT_DEPRECATED SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), void*,sqlite3_int64); #endif /* ** CAPI3REF: Obtaining SQL Values ** METHOD: sqlite3_value ** ** The C-language implementation of SQL functions and aggregates uses ** this set of interface routines to access the parameter values on ** the function or aggregate. ** ** The xFunc (for scalar functions) or xStep (for aggregates) parameters ** to [sqlite3_create_function()] and [sqlite3_create_function16()] ** define callbacks that implement the SQL functions and aggregates. ** The 3rd parameter to these callbacks is an array of pointers to ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** ** These routines work only with [protected sqlite3_value] objects. ** Any attempt to use these routines on an [unprotected sqlite3_value] ** object results in undefined behavior. ** ** ^These routines work just like the corresponding [column access functions] ** except that these routines take a single [protected sqlite3_value] object ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. ** ** ^The sqlite3_value_text16() interface extracts a UTF-16 string ** in the native byte-order of the host machine. ^The ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces ** extract UTF-16 strings as big-endian and little-endian respectively. ** ** ^(The sqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other ** words, if the value is a string that looks like a number) ** then the conversion is performed. Otherwise no conversion occurs. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ ** ** Please pay particular attention to the fact that the pointer returned ** from [sqlite3_value_blob()], [sqlite3_value_text()], or ** [sqlite3_value_text16()] can be invalidated by a subsequent call to ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], ** or [sqlite3_value_text16()]. ** ** These routines must be called from the same thread as ** the SQL function that supplied the [sqlite3_value*] parameters. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API int sqlite3_value_bytes(sqlite3_value*); SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); SQLITE_API double sqlite3_value_double(sqlite3_value*); SQLITE_API int sqlite3_value_int(sqlite3_value*); SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); SQLITE_API int sqlite3_value_type(sqlite3_value*); SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); /* ** CAPI3REF: Finding The Subtype Of SQL Values ** METHOD: sqlite3_value ** ** The sqlite3_value_subtype(V) function returns the subtype for ** an [application-defined SQL function] argument V. The subtype ** information can be used to pass a limited amount of context from ** one SQL function to another. Use the [sqlite3_result_subtype()] ** routine to set the subtype for the return value of an SQL function. ** ** SQLite makes no use of subtype itself. It merely passes the subtype ** from the result of one [application-defined SQL function] into the ** input of another. */ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); /* ** CAPI3REF: Copy And Free SQL Values ** METHOD: sqlite3_value ** ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned ** is a [protected sqlite3_value] object even if the input is not. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a ** memory allocation fails. ** ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer ** then sqlite3_value_free(V) is a harmless no-op. */ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); SQLITE_API void sqlite3_value_free(sqlite3_value*); /* ** CAPI3REF: Obtain Aggregate Function Context ** METHOD: sqlite3_context ** ** Implementations of aggregate SQL functions use this ** routine to allocate memory for storing their state. ** ** ^The first time the sqlite3_aggregate_context(C,N) routine is called ** for a particular aggregate function, SQLite ** allocates N of memory, zeroes out that memory, and returns a pointer ** to the new memory. ^On second and subsequent calls to ** sqlite3_aggregate_context() for the same aggregate function instance, ** the same buffer is returned. Sqlite3_aggregate_context() is normally ** called once for each invocation of the xStep callback and then one ** last time when the xFinal callback is invoked. ^(When no rows match ** an aggregate query, the xStep() callback of the aggregate function ** implementation is never called and xFinal() is called exactly once. ** In those cases, sqlite3_aggregate_context() might be called for the ** first time from within xFinal().)^ ** ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer ** when first called if N is less than or equal to zero or if a memory ** allocate error occurs. ** ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is ** determined by the N parameter on first successful call. Changing the ** value of N in subsequent call to sqlite3_aggregate_context() within ** the same aggregate function instance will not resize the memory ** allocation.)^ Within the xFinal callback, it is customary to set ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no ** pointless memory allocations occur. ** ** ^SQLite automatically frees the memory allocated by ** sqlite3_aggregate_context() when the aggregate query concludes. ** ** The first parameter must be a copy of the ** [sqlite3_context | SQL function context] that is the first parameter ** to the xStep or xFinal callback routine that implements the aggregate ** function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions ** METHOD: sqlite3_context ** ** ^The sqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. ** ** This routine must be called from the same thread in which ** the application-defined function is running. */ SQLITE_API void *sqlite3_user_data(sqlite3_context*); /* ** CAPI3REF: Database Connection For Functions ** METHOD: sqlite3_context ** ** ^The sqlite3_context_db_handle() interface returns a copy of ** the pointer to the [database connection] (the 1st parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. */ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); /* ** CAPI3REF: Function Auxiliary Data ** METHOD: sqlite3_context ** ** These functions may be used by (non-aggregate) SQL functions to ** associate metadata with argument values. If the same value is passed to ** multiple invocations of the same SQL function during query execution, under ** some circumstances the associated metadata may be preserved. An example ** of where this might be useful is in a regular-expression matching ** function. The compiled version of the regular expression can be stored as ** metadata associated with the pattern string. ** Then as long as the pattern string remains the same, ** the compiled regular expression can be reused on multiple ** invocations of the same function. ** ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata ** associated by the sqlite3_set_auxdata() function with the Nth argument ** value to the application-defined function. ^If there is no metadata ** associated with the function argument, this sqlite3_get_auxdata() interface ** returns a NULL pointer. ** ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th ** argument of the application-defined function. ^Subsequent ** calls to sqlite3_get_auxdata(C,N) return P from the most recent ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or ** NULL if the metadata has been discarded. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, ** SQLite will invoke the destructor function X with parameter P exactly ** once, when the metadata is discarded. ** SQLite is free to discard the metadata at any time, including: <ul> ** <li> ^(when the corresponding function parameter changes)^, or ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the ** SQL statement)^, or ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same ** parameter)^, or ** <li> ^(during the original sqlite3_set_auxdata() call when a memory ** allocation error occurs.)^ </ul> ** ** Note the last bullet in particular. The destructor X in ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() ** should be called near the end of the function implementation and the ** function implementation should not make any use of P after ** sqlite3_set_auxdata() has been called. ** ** ^(In practice, metadata is preserved between function calls for ** function parameters that are compile-time constants, including literal ** values and [parameters] and expressions composed from the same.)^ ** ** These routines must be called from the same thread in which ** the SQL function is running. */ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior ** ** These are special values for the destructor that is passed in as the ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant ** and will never change. It does not need to be destroyed. ^The ** SQLITE_TRANSIENT value means that the content will likely change in ** the near future and that SQLite should make its own private copy of ** the content before returning. ** ** The typedef is necessary to work around problems in certain ** C++ compilers. */ typedef void (*sqlite3_destructor_type)(void*); #define SQLITE_STATIC ((sqlite3_destructor_type)0) #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) /* ** CAPI3REF: Setting The Result Of An SQL Function ** METHOD: sqlite3_context ** ** These routines are used by the xFunc or xFinal callbacks that ** implement SQL functions and aggregates. See ** [sqlite3_create_function()] and [sqlite3_create_function16()] ** for additional information. ** ** These functions work very much like the [parameter binding] family of ** functions used to bind values to host parameters in prepared statements. ** Refer to the [SQL parameter] documentation for additional information. ** ** ^The sqlite3_result_blob() interface sets the result from ** an application-defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the ** third parameter. ** ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) ** interfaces set the result of the application-defined function to be ** a BLOB containing all zero bytes and N bytes in size. ** ** ^The sqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified ** by its 2nd argument. ** ** ^The sqlite3_result_error() and sqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. ** ^SQLite uses the string pointed to by the ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() ** as the text of an error message. ^SQLite interprets the error ** message string from sqlite3_result_error() as UTF-8. ^SQLite ** interprets the string from sqlite3_result_error16() as UTF-16 in native ** byte order. ^If the third parameter to sqlite3_result_error() ** or sqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. ** ^If the third parameter to sqlite3_result_error() or ** sqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. ** ^The sqlite3_result_error() and sqlite3_result_error16() ** routines make a private copy of the error message text before ** they return. Hence, the calling function can deallocate or ** modify the text after they return without harm. ** ^The sqlite3_result_error_code() function changes the error code ** returned by SQLite as a result of an error in a function. ^By default, ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. ** ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an ** error indicating that a string or BLOB is too long to represent. ** ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an ** error indicating that a memory allocation failed. ** ** ^The sqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. ** ^The sqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** ** ^The sqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** ** ^The sqlite3_result_text(), sqlite3_result_text16(), ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. ** ^The sqlite3_result_text64() interface sets the return value of an ** application-defined function to be a text string in an encoding ** specified by the fifth (and last) parameter, which must be one ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. ** ^SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces ** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. If the 3rd parameter is non-negative, then it ** must be the byte offset into the string where the NUL terminator would ** appear if the string where NUL terminated. If any NUL characters occur ** in the string at a byte offset that is less than the value of the 3rd ** parameter, then the resulting string will contain embedded NULs and the ** result of expressions operating on strings with embedded NULs is undefined. ** ^If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that ** function as the destructor on the text or BLOB result when it has ** finished using that result. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite ** assumes that the text or BLOB result is in constant space and does not ** copy the content of the parameter nor call a destructor on the content ** when it has finished using that result. ** ^If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** ** ^The sqlite3_result_value() interface sets the result of ** the application-defined function to be a copy of the ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] ** so that the [sqlite3_value] specified in the parameter may change or ** be deallocated after sqlite3_result_value() returns without harm. ** ^A [protected sqlite3_value] object may always be used where an ** [unprotected sqlite3_value] object is required, so either ** kind of [sqlite3_value] object can be used with this interface. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that received ** the [sqlite3_context] pointer, the results are undefined. */ SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, sqlite3_uint64,void(*)(void*)); SQLITE_API void sqlite3_result_double(sqlite3_context*, double); SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); SQLITE_API void sqlite3_result_int(sqlite3_context*, int); SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); SQLITE_API void sqlite3_result_null(sqlite3_context*); SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, void(*)(void*), unsigned char encoding); SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); /* ** CAPI3REF: Setting The Subtype Of An SQL Function ** METHOD: sqlite3_context ** ** The sqlite3_result_subtype(C,T) function causes the subtype of ** the result from the [application-defined SQL function] with ** [sqlite3_context] C to be the value T. Only the lower 8 bits ** of the subtype T are preserved in current versions of SQLite; ** higher order bits are discarded. ** The number of subtype bytes preserved by SQLite might increase ** in future releases of SQLite. */ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); /* ** CAPI3REF: Define New Collating Sequences ** METHOD: sqlite3 ** ** ^These functions add, remove, or modify a [collation] associated ** with the [database connection] specified as the first argument. ** ** ^The name of the collation is a UTF-8 string ** for sqlite3_create_collation() and sqlite3_create_collation_v2() ** and a UTF-16 string in native byte order for sqlite3_create_collation16(). ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are ** considered to be the same name. ** ** ^(The third argument (eTextRep) must be one of the constants: ** <ul> ** <li> [SQLITE_UTF8], ** <li> [SQLITE_UTF16LE], ** <li> [SQLITE_UTF16BE], ** <li> [SQLITE_UTF16], or ** <li> [SQLITE_UTF16_ALIGNED]. ** </ul>)^ ** ^The eTextRep argument determines the encoding of strings passed ** to the collating function callback, xCallback. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep ** force strings to be UTF16 with native byte order. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin ** on an even byte address. ** ** ^The fourth argument, pArg, is an application data pointer that is passed ** through as the first argument to the collating function callback. ** ** ^The fifth argument, xCallback, is a pointer to the collating function. ** ^Multiple collating functions can be registered using the same name but ** with different eTextRep parameters and SQLite will use whichever ** function requires the least amount of data transformation. ** ^If the xCallback argument is NULL then the collating function is ** deleted. ^When all collating functions having the same name are deleted, ** that collation is no longer usable. ** ** ^The collating function callback is invoked with a copy of the pArg ** application data pointer and with two strings in the encoding specified ** by the eTextRep argument. The collating function must return an ** integer that is negative, zero, or positive ** if the first string is less than, equal to, or greater than the second, ** respectively. A collating function must always return the same answer ** given the same inputs. If two or more collating functions are registered ** to the same collation name (using different eTextRep values) then all ** must give an equivalent answer when invoked with equivalent strings. ** The collating function must obey the following properties for all ** strings A, B, and C: ** ** <ol> ** <li> If A==B then B==A. ** <li> If A==B and B==C then A==C. ** <li> If A&lt;B THEN B&gt;A. ** <li> If A&lt;B and B&lt;C then A&lt;C. ** </ol> ** ** If a collating function fails any of the above constraints and that ** collating function is registered and used, then the behavior of SQLite ** is undefined. ** ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() ** with the addition that the xDestroy callback is invoked on pArg when ** the collating function is deleted. ** ^Collating functions are deleted when they are overridden by later ** calls to the collation creation functions or when the ** [database connection] is closed using [sqlite3_close()]. ** ** ^The xDestroy callback is <u>not</u> called if the ** sqlite3_create_collation_v2() function fails. Applications that invoke ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should ** check the return code and dispose of the application data pointer ** themselves rather than expecting SQLite to deal with it for them. ** This is different from every other SQLite interface. The inconsistency ** is unfortunate but cannot be changed without breaking backwards ** compatibility. ** ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. */ SQLITE_API int sqlite3_create_collation( sqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); SQLITE_API int sqlite3_create_collation_v2( sqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDestroy)(void*) ); SQLITE_API int sqlite3_create_collation16( sqlite3*, const void *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); /* ** CAPI3REF: Collation Needed Callbacks ** METHOD: sqlite3 ** ** ^To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the ** [database connection] to be invoked whenever an undefined collation ** sequence is required. ** ** ^If the function is registered using the sqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, ** the names are passed as UTF-16 in machine native byte order. ** ^A call to either function replaces the existing collation-needed callback. ** ** ^(When the callback is invoked, the first argument passed is a copy ** of the second argument to sqlite3_collation_needed() or ** sqlite3_collation_needed16(). The second argument is the database ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation ** sequence function required. The fourth parameter is the name of the ** required collation sequence.)^ ** ** The callback function should register the desired collation using ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or ** [sqlite3_create_collation_v2()]. */ SQLITE_API int sqlite3_collation_needed( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const char*) ); SQLITE_API int sqlite3_collation_needed16( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const void*) ); #ifdef SQLITE_HAS_CODEC /* ** Specify the key for an encrypted database. This routine should be ** called right after sqlite3_open(). ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_key( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The key */ ); SQLITE_API int sqlite3_key_v2( sqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The key */ ); /* ** Change the key on an open database. If the current database is not ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the ** database is decrypted. ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_rekey( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); SQLITE_API int sqlite3_rekey_v2( sqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The new key */ ); /* ** Specify the activation key for a SEE database. Unless ** activated, none of the SEE routines will work. */ SQLITE_API void sqlite3_activate_see( const char *zPassPhrase /* Activation phrase */ ); #endif #ifdef SQLITE_ENABLE_CEROD /* ** Specify the activation key for a CEROD database. Unless ** activated, none of the CEROD routines will work. */ SQLITE_API void sqlite3_activate_cerod( const char *zPassPhrase /* Activation phrase */ ); #endif /* ** CAPI3REF: Suspend Execution For A Short Time ** ** The sqlite3_sleep() function causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** ** If the operating system does not support sleep requests with ** millisecond time resolution, then the time will be rounded up to ** the nearest second. The number of milliseconds of sleep actually ** requested from the operating system is returned. ** ** ^SQLite implements this interface by calling the xSleep() ** method of the default [sqlite3_vfs] object. If the xSleep() method ** of the default VFS is not implemented correctly, or not implemented at ** all, then the behavior of sqlite3_sleep() may deviate from the description ** in the previous paragraphs. */ SQLITE_API int sqlite3_sleep(int); /* ** CAPI3REF: Name Of The Folder Holding Temporary Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all temporary files ** created by SQLite when using a built-in [sqlite3_vfs | VFS] ** will be placed in that directory.)^ ^If this variable ** is a NULL pointer, then SQLite performs a search for an appropriate ** temporary file directory. ** ** Applications are strongly discouraged from using this global variable. ** It is required to set a temporary folder on Windows Runtime (WinRT). ** But for all other platforms, it is highly recommended that applications ** neither read nor write this variable. This global variable is a relic ** that exists for backwards compatibility of legacy applications and should ** be avoided in new projects. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** ^The [temp_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, ** the [temp_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [temp_store_directory pragma] should be avoided. ** Except when requested by the [temp_store_directory pragma], SQLite ** does not free the memory that sqlite3_temp_directory points to. If ** the application wants that memory to be freed, it must do ** so itself, taking care to only do so after all [database connection] ** objects have been destroyed. ** ** <b>Note to Windows Runtime users:</b> The temporary directory must be set ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various ** features that require the use of temporary files may fail. Here is an ** example of how to do this using C++ with the Windows Runtime: ** ** <blockquote><pre> ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current-> ** &nbsp; TemporaryFolder->Path->Data(); ** char zPathBuf&#91;MAX_PATH + 1&#93;; ** memset(zPathBuf, 0, sizeof(zPathBuf)); ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf), ** &nbsp; NULL, NULL); ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf); ** </pre></blockquote> */ SQLITE_API char *sqlite3_temp_directory; /* ** CAPI3REF: Name Of The Folder Holding Database Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all database files ** specified with a relative pathname and created or accessed by ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed ** to be relative to that directory.)^ ^If this variable is a NULL ** pointer, then SQLite assumes that all database files specified ** with a relative pathname are relative to the current directory ** for the process. Only the windows VFS makes use of this global ** variable; it is ignored by the unix VFS. ** ** Changing the value of this variable while a database connection is ** open can result in a corrupt database. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** ^The [data_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, ** the [data_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [data_store_directory pragma] should be avoided. */ SQLITE_API char *sqlite3_data_directory; /* ** CAPI3REF: Test For Auto-Commit Mode ** KEYWORDS: {autocommit mode} ** METHOD: sqlite3 ** ** ^The sqlite3_get_autocommit() interface returns non-zero or ** zero if the given database connection is or is not in autocommit mode, ** respectively. ^Autocommit mode is on by default. ** ^Autocommit mode is disabled by a [BEGIN] statement. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. ** ** If certain kinds of errors occur on a statement within a multi-statement ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the ** transaction might be rolled back automatically. The only way to ** find out whether SQLite automatically rolled back the transaction after ** an error is to use this function. ** ** If another thread changes the autocommit status of the database ** connection while this routine is running, then the return value ** is undefined. */ SQLITE_API int sqlite3_get_autocommit(sqlite3*); /* ** CAPI3REF: Find The Database Handle Of A Prepared Statement ** METHOD: sqlite3_stmt ** ** ^The sqlite3_db_handle interface returns the [database connection] handle ** to which a [prepared statement] belongs. ^The [database connection] ** returned by sqlite3_db_handle is the same [database connection] ** that was the first argument ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to ** create the statement in the first place. */ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); /* ** CAPI3REF: Return The Filename For A Database Connection ** METHOD: sqlite3 ** ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename ** associated with database N of connection D. ^The main database file ** has the name "main". If there is no attached database N on the database ** connection D, or if database N is a temporary or in-memory database, then ** a NULL pointer is returned. ** ** ^The filename returned by this function is the output of the ** xFullPathname method of the [VFS]. ^In other words, the filename ** will be an absolute pathname, even if the filename used ** to open the database originally was a URI or relative pathname. */ SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); /* ** CAPI3REF: Determine if a database is read-only ** METHOD: sqlite3 ** ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N ** of connection D is read-only, 0 if it is read/write, or -1 if N is not ** the name of a database on connection D. */ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); /* ** CAPI3REF: Find the next prepared statement ** METHOD: sqlite3 ** ** ^This interface returns a pointer to the next [prepared statement] after ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL ** then this interface returns a pointer to the first prepared statement ** associated with the database connection pDb. ^If no prepared statement ** satisfies the conditions of this routine, it returns NULL. ** ** The [database connection] pointer D in a call to ** [sqlite3_next_stmt(D,S)] must refer to an open database ** connection and in particular must not be a NULL pointer. */ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is [COMMIT | committed]. ** ^Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. ** ^The sqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. ** ^Any callback set by a previous call to sqlite3_rollback_hook() ** for the same database connection is overridden. ** ^The pArg argument is passed through to the callback. ** ^If the callback on a commit hook function returns non-zero, ** then the commit is converted into a rollback. ** ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions ** return the P argument from the previous call of the same function ** on the same [database connection] D, or NULL for ** the first call for each function on D. ** ** The commit and rollback hook callbacks are not reentrant. ** The callback implementation must not do anything that will modify ** the database connection that invoked the callback. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the commit ** or rollback hook in the first place. ** Note that running any other SQL statements, including SELECT statements, ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify ** the database connections for the meaning of "modify" in this paragraph. ** ** ^Registering a NULL function disables the callback. ** ** ^When the commit hook callback routine returns zero, the [COMMIT] ** operation is allowed to continue normally. ^If the commit hook ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. ** ^The rollback hook is invoked on a rollback that results from a commit ** hook returning non-zero, just as it would be with any other rollback. ** ** ^For the purposes of this API, a transaction is said to have been ** rolled back if an explicit "ROLLBACK" statement is executed, or ** an error or constraint causes an implicit rollback to occur. ** ^The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. ** ** See also the [sqlite3_update_hook()] interface. */ SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks ** METHOD: sqlite3 ** ** ^The sqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument ** to be invoked whenever a row is updated, inserted or deleted in ** a [rowid table]. ** ^Any callback set by a previous call to this function ** for the same database connection is overridden. ** ** ^The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted in a rowid table. ** ^The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], ** or [SQLITE_UPDATE], depending on the operation that caused the callback ** to be invoked. ** ^The third and fourth arguments to the callback contain pointers to the ** database and table name containing the affected row. ** ^The final callback parameter is the [rowid] of the row. ** ^In the case of an update, this is the [rowid] after the update takes place. ** ** ^(The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence).)^ ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. ** ** ^In the current implementation, the update hook ** is not invoked when conflicting rows are deleted because of an ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook ** invoked when rows are deleted using the [truncate optimization]. ** The exceptions defined in this paragraph might change in a future ** release of SQLite. ** ** The update hook implementation must not do anything that will modify ** the database connection that invoked the update hook. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the update hook. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** ^The sqlite3_update_hook(D,C,P) function ** returns the P argument from the previous call ** on the same [database connection] D, or NULL for ** the first call on D. ** ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], ** and [sqlite3_preupdate_hook()] interfaces. */ SQLITE_API void *sqlite3_update_hook( sqlite3*, void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); /* ** CAPI3REF: Enable Or Disable Shared Pager Cache ** ** ^(This routine enables or disables the sharing of the database cache ** and schema data structures between [database connection | connections] ** to the same database. Sharing is enabled if the argument is true ** and disabled if the argument is false.)^ ** ** ^Cache sharing is enabled and disabled for an entire process. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). ** In prior versions of SQLite, ** sharing was enabled or disabled for each thread separately. ** ** ^(The cache sharing mode set by this interface effects all subsequent ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. ** Existing database connections continue use the sharing mode ** that was in effect at the time they were opened.)^ ** ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled ** successfully. An [error code] is returned otherwise.)^ ** ** ^Shared cache is disabled by default. But this might change in ** future releases of SQLite. Applications that care about shared ** cache setting should set it explicitly. ** ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 ** and will always return SQLITE_MISUSE. On those systems, ** shared cache mode should be enabled per-database connection via ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. ** ** This interface is threadsafe on processors where writing a ** 32-bit integer is atomic. ** ** See Also: [SQLite Shared-Cache Mode] */ SQLITE_API int sqlite3_enable_shared_cache(int); /* ** CAPI3REF: Attempt To Free Heap Memory ** ** ^The sqlite3_release_memory() interface attempts to free N bytes ** of heap memory by deallocating non-essential memory allocations ** held by the database library. Memory used to cache database ** pages to improve performance is an example of non-essential memory. ** ^sqlite3_release_memory() returns the number of bytes actually freed, ** which might be more or less than the amount requested. ** ^The sqlite3_release_memory() routine is a no-op returning zero ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** ** See also: [sqlite3_db_release_memory()] */ SQLITE_API int sqlite3_release_memory(int); /* ** CAPI3REF: Free Memory Used By A Database Connection ** METHOD: sqlite3 ** ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap ** memory as possible from database connection D. Unlike the ** [sqlite3_release_memory()] interface, this interface is in effect even ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is ** omitted. ** ** See also: [sqlite3_release_memory()] */ SQLITE_API int sqlite3_db_release_memory(sqlite3*); /* ** CAPI3REF: Impose A Limit On Heap Size ** ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the ** soft limit on the amount of heap memory that may be allocated by SQLite. ** ^SQLite strives to keep heap memory utilization below the soft heap ** limit by reducing the number of pages held in the page cache ** as heap memory usages approaches the limit. ** ^The soft heap limit is "soft" because even though SQLite strives to stay ** below the limit, it will exceed the limit rather than generate ** an [SQLITE_NOMEM] error. In other words, the soft heap limit ** is advisory only. ** ** ^The return value from sqlite3_soft_heap_limit64() is the size of ** the soft heap limit prior to the call, or negative in the case of an ** error. ^If the argument N is negative ** then no change is made to the soft heap limit. Hence, the current ** size of the soft heap limit can be determined by invoking ** sqlite3_soft_heap_limit64() with a negative argument. ** ** ^If the argument N is zero then the soft heap limit is disabled. ** ** ^(The soft heap limit is not enforced in the current implementation ** if one or more of following conditions are true: ** ** <ul> ** <li> The soft heap limit is set to zero. ** <li> Memory accounting is disabled using a combination of the ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. ** <li> An alternative page cache implementation is specified using ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). ** <li> The page cache allocates from its own memory pool supplied ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than ** from the heap. ** </ul>)^ ** ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), ** the soft heap limit is enforced ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], ** the soft heap limit is enforced on every memory allocation. Without ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced ** when memory is allocated by the page cache. Testing suggests that because ** the page cache is the predominate memory user in SQLite, most ** applications will achieve adequate soft heap limit enforcement without ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** ** The circumstances under which SQLite will enforce the soft heap limit may ** changes in future releases of SQLite. */ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); /* ** CAPI3REF: Deprecated Soft Heap Limit Interface ** DEPRECATED ** ** This is a deprecated version of the [sqlite3_soft_heap_limit64()] ** interface. This routine is provided for historical compatibility ** only. All new applications should use the ** [sqlite3_soft_heap_limit64()] interface rather than this one. */ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); /* ** CAPI3REF: Extract Metadata About A Column Of A Table ** METHOD: sqlite3 ** ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns ** information about column C of table T in database D ** on [database connection] X.)^ ^The sqlite3_table_column_metadata() ** interface returns SQLITE_OK and fills in the non-NULL pointers in ** the final five arguments with appropriate values if the specified ** column exists. ^The sqlite3_table_column_metadata() interface returns ** SQLITE_ERROR and if the specified column does not exist. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a ** NULL pointer, then this routine simply checks for the existence of the ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it ** does not. ** ** ^The column is identified by the second, third and fourth parameters to ** this function. ^(The second parameter is either the name of the database ** (i.e. "main", "temp", or an attached database) containing the specified ** table or NULL.)^ ^If it is NULL, then all attached databases are searched ** for the table using the same algorithm used by the database engine to ** resolve unqualified table references. ** ** ^The third and fourth parameters to this function are the table and column ** name of the desired column, respectively. ** ** ^Metadata is returned by writing to the memory locations passed as the 5th ** and subsequent parameters to this function. ^Any of these arguments may be ** NULL, in which case the corresponding element of metadata is omitted. ** ** ^(<blockquote> ** <table border="1"> ** <tr><th> Parameter <th> Output<br>Type <th> Description ** ** <tr><td> 5th <td> const char* <td> Data type ** <tr><td> 6th <td> const char* <td> Name of default collation sequence ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT] ** </table> ** </blockquote>)^ ** ** ^The memory pointed to by the character pointers returned for the ** declaration type and collation sequence is valid until the next ** call to any SQLite API function. ** ** ^If the specified table is actually a view, an [error code] is returned. ** ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table ** is not a [WITHOUT ROWID] table and an ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output ** parameters are set for the explicitly declared column. ^(If there is no ** [INTEGER PRIMARY KEY] column, then the outputs ** for the [rowid] are set as follows: ** ** <pre> ** data type: "INTEGER" ** collation sequence: "BINARY" ** not null: 0 ** primary key: 1 ** auto increment: 0 ** </pre>)^ ** ** ^This function causes all database schemas to be read from disk and ** parsed, if that has not already been done, and returns an error if ** any errors are encountered while loading the schema. */ SQLITE_API int sqlite3_table_column_metadata( sqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ char const **pzDataType, /* OUTPUT: Declared data type */ char const **pzCollSeq, /* OUTPUT: Collation sequence name */ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ int *pAutoinc /* OUTPUT: True if column is auto-increment */ ); /* ** CAPI3REF: Load An Extension ** METHOD: sqlite3 ** ** ^This interface loads an SQLite extension library from the named file. ** ** ^The sqlite3_load_extension() interface attempts to load an ** [SQLite extension] library contained in the file zFile. If ** the file cannot be loaded directly, attempts are made to load ** with various operating-system specific extensions added. ** So for example, if "samplelib" cannot be loaded, then names like ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might ** be tried also. ** ** ^The entry point is zProc. ** ^(zProc may be 0, in which case SQLite will try to come up with an ** entry point name on its own. It first tries "sqlite3_extension_init". ** If that does not work, it constructs a name "sqlite3_X_init" where the ** X is consists of the lower-case equivalent of all ASCII alphabetic ** characters in the filename from the last "/" to the first following ** "." and omitting any initial "lib".)^ ** ^The sqlite3_load_extension() interface returns ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ^If an error occurs and pzErrMsg is not 0, then the ** [sqlite3_load_extension()] interface shall attempt to ** fill *pzErrMsg with error message text stored in memory ** obtained from [sqlite3_malloc()]. The calling function ** should free this memory by calling [sqlite3_free()]. ** ** ^Extension loading must be enabled using ** [sqlite3_enable_load_extension()] or ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) ** prior to calling this API, ** otherwise an error will be returned. ** ** <b>Security warning:</b> It is recommended that the ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this ** interface. The use of the [sqlite3_enable_load_extension()] interface ** should be avoided. This will keep the SQL function [load_extension()] ** disabled and prevent SQL injections from giving attackers ** access to extension loading capabilities. ** ** See also the [load_extension() SQL function]. */ SQLITE_API int sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Derived from zFile if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ); /* ** CAPI3REF: Enable Or Disable Extension Loading ** METHOD: sqlite3 ** ** ^So as not to open security holes in older applications that are ** unprepared to deal with [extension loading], and as a means of disabling ** [extension loading] while evaluating user-entered SQL, the following API ** is provided to turn the [sqlite3_load_extension()] mechanism on and off. ** ** ^Extension loading is off by default. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1 ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. ** ** ^This interface enables or disables both the C-API ** [sqlite3_load_extension()] and the SQL function [load_extension()]. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) ** to enable or disable only the C-API.)^ ** ** <b>Security warning:</b> It is recommended that extension loading ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method ** rather than this interface, so the [load_extension()] SQL function ** remains disabled. This will prevent SQL injections from giving attackers ** access to extension loading capabilities. */ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load Statically Linked Extensions ** ** ^This interface causes the xEntryPoint() function to be invoked for ** each new [database connection] that is created. The idea here is that ** xEntryPoint() is the entry point for a statically linked [SQLite extension] ** that is to be automatically loaded into all new database connections. ** ** ^(Even though the function prototype shows that xEntryPoint() takes ** no arguments and returns void, SQLite invokes xEntryPoint() with three ** arguments and expects an integer result as if the signature of the ** entry point where as follows: ** ** <blockquote><pre> ** &nbsp; int xEntryPoint( ** &nbsp; sqlite3 *db, ** &nbsp; const char **pzErrMsg, ** &nbsp; const struct sqlite3_api_routines *pThunk ** &nbsp; ); ** </pre></blockquote>)^ ** ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg ** point to an appropriate error message (obtained from [sqlite3_mprintf()]) ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg ** is NULL before calling the xEntryPoint(). ^SQLite will invoke ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. ** ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already ** on the list of automatic extensions is a harmless no-op. ^No entry point ** will be called more than once for each database connection that is opened. ** ** See also: [sqlite3_reset_auto_extension()] ** and [sqlite3_cancel_auto_extension()] */ SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Cancel Automatic Extension Loading ** ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the ** initialization routine X that was registered using a prior call to ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] ** routine returns 1 if initialization routine X was successfully ** unregistered and it returns 0 if X was not on the list of initialization ** routines. */ SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading ** ** ^This interface disables all automatic extensions previously ** registered using [sqlite3_auto_extension()]. */ SQLITE_API void sqlite3_reset_auto_extension(void); /* ** The interface to the virtual-table mechanism is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** Structures used by the virtual table interface */ typedef struct sqlite3_vtab sqlite3_vtab; typedef struct sqlite3_index_info sqlite3_index_info; typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; typedef struct sqlite3_module sqlite3_module; /* ** CAPI3REF: Virtual Table Object ** KEYWORDS: sqlite3_module {virtual table module} ** ** This structure, sometimes called a "virtual table module", ** defines the implementation of a [virtual tables]. ** This structure consists mostly of methods for the module. ** ** ^A virtual table module is created by filling in a persistent ** instance of this structure and passing a pointer to that instance ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. ** ^The registration remains valid until it is replaced by a different ** module or until the [database connection] closes. The content ** of this structure must not change while it is registered with ** any database connection. */ struct sqlite3_module { int iVersion; int (*xCreate)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xConnect)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); int (*xDisconnect)(sqlite3_vtab *pVTab); int (*xDestroy)(sqlite3_vtab *pVTab); int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); int (*xClose)(sqlite3_vtab_cursor*); int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, int argc, sqlite3_value **argv); int (*xNext)(sqlite3_vtab_cursor*); int (*xEof)(sqlite3_vtab_cursor*); int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); int (*xBegin)(sqlite3_vtab *pVTab); int (*xSync)(sqlite3_vtab *pVTab); int (*xCommit)(sqlite3_vtab *pVTab); int (*xRollback)(sqlite3_vtab *pVTab); int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), void **ppArg); int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); /* The methods above are in version 1 of the sqlite_module object. Those ** below are for version 2 and greater. */ int (*xSavepoint)(sqlite3_vtab *pVTab, int); int (*xRelease)(sqlite3_vtab *pVTab, int); int (*xRollbackTo)(sqlite3_vtab *pVTab, int); }; /* ** CAPI3REF: Virtual Table Indexing Information ** KEYWORDS: sqlite3_index_info ** ** The sqlite3_index_info structure and its substructures is used as part ** of the [virtual table] interface to ** pass information into and receive the reply from the [xBestIndex] ** method of a [virtual table module]. The fields under **Inputs** are the ** inputs to xBestIndex and are read-only. xBestIndex inserts its ** results into the **Outputs** fields. ** ** ^(The aConstraint[] array records WHERE clause constraints of the form: ** ** <blockquote>column OP expr</blockquote> ** ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is ** stored in aConstraint[].op using one of the ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ ** ^(The index of the column is stored in ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the ** expr on the right-hand side can be evaluated (and thus the constraint ** is usable) and false if it cannot.)^ ** ** ^The optimizer automatically inverts terms of the form "expr OP column" ** and makes other simplifications to the WHERE clause in an attempt to ** get as many WHERE clause terms into the form shown above as possible. ** ^The aConstraint[] array only reports WHERE clause terms that are ** relevant to the particular virtual table being queried. ** ** ^Information about the ORDER BY clause is stored in aOrderBy[]. ** ^Each term of aOrderBy records a column of the ORDER BY clause. ** ** The colUsed field indicates which columns of the virtual table may be ** required by the current scan. Virtual table columns are numbered from ** zero in the order in which they appear within the CREATE TABLE statement ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), ** the corresponding bit is set within the colUsed mask if the column may be ** required by SQLite. If the table has at least 64 columns and any column ** to the right of the first 63 is required, then bit 63 of colUsed is also ** set. In other words, column iCol may be required if the expression ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to ** non-zero. ** ** The [xBestIndex] method must fill aConstraintUsage[] with information ** about what parameters to pass to xFilter. ^If argvIndex>0 then ** the right-hand side of the corresponding aConstraint[] is evaluated ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit ** is true, then the constraint is assumed to be fully handled by the ** virtual table and is not checked again by SQLite.)^ ** ** ^The idxNum and idxPtr values are recorded and passed into the ** [xFilter] method. ** ^[sqlite3_free()] is used to free idxPtr if and only if ** needToFreeIdxPtr is true. ** ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in ** the correct order to satisfy the ORDER BY clause so that no separate ** sorting step is required. ** ** ^The estimatedCost value is an estimate of the cost of a particular ** strategy. A cost of N indicates that the cost of the strategy is similar ** to a linear scan of an SQLite table with N rows. A cost of log(N) ** indicates that the expense of the operation is similar to that of a ** binary search on a unique indexed field of an SQLite table with N rows. ** ** ^The estimatedRows value is an estimate of the number of rows that ** will be returned by the strategy. ** ** The xBestIndex method may optionally populate the idxFlags field with a ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag - ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite ** assumes that the strategy may visit at most one row. ** ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then ** SQLite also assumes that if a call to the xUpdate() method is made as ** part of the same statement to delete or update a virtual table row and the ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback ** any database changes. In other words, if the xUpdate() returns ** SQLITE_CONSTRAINT, the database contents must be exactly as they were ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by ** the xUpdate method are automatically rolled back by SQLite. ** ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). ** If a virtual table extension is ** used with an SQLite version earlier than 3.8.2, the results of attempting ** to read or write the estimatedRows field are undefined (but are likely ** to included crashing the application). The estimatedRows field should ** therefore only be used if [sqlite3_libversion_number()] returns a ** value greater than or equal to 3008002. Similarly, the idxFlags field ** was added for [version 3.9.0] ([dateof:3.9.0]). ** It may therefore only be used if ** sqlite3_libversion_number() returns a value greater than or equal to ** 3009000. */ struct sqlite3_index_info { /* Inputs */ int nConstraint; /* Number of entries in aConstraint */ struct sqlite3_index_constraint { int iColumn; /* Column constrained. -1 for ROWID */ unsigned char op; /* Constraint operator */ unsigned char usable; /* True if this constraint is usable */ int iTermOffset; /* Used internally - xBestIndex should ignore */ } *aConstraint; /* Table of WHERE clause constraints */ int nOrderBy; /* Number of terms in the ORDER BY clause */ struct sqlite3_index_orderby { int iColumn; /* Column number */ unsigned char desc; /* True for DESC. False for ASC. */ } *aOrderBy; /* The ORDER BY clause */ /* Outputs */ struct sqlite3_index_constraint_usage { int argvIndex; /* if >0, constraint is part of argv to xFilter */ unsigned char omit; /* Do not code a test for this constraint */ } *aConstraintUsage; int idxNum; /* Number used to identify the index */ char *idxStr; /* String, possibly obtained from sqlite3_malloc */ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ int orderByConsumed; /* True if output is already ordered */ double estimatedCost; /* Estimated cost of using this index */ /* Fields below are only available in SQLite 3.8.2 and later */ sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ /* Fields below are only available in SQLite 3.9.0 and later */ int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ /* Fields below are only available in SQLite 3.10.0 and later */ sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ }; /* ** CAPI3REF: Virtual Table Scan Flags */ #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */ /* ** CAPI3REF: Virtual Table Constraint Operator Codes ** ** These macros defined the allowed values for the ** [sqlite3_index_info].aConstraint[].op field. Each value represents ** an operator that is part of a constraint term in the wHERE clause of ** a query that uses a [virtual table]. */ #define SQLITE_INDEX_CONSTRAINT_EQ 2 #define SQLITE_INDEX_CONSTRAINT_GT 4 #define SQLITE_INDEX_CONSTRAINT_LE 8 #define SQLITE_INDEX_CONSTRAINT_LT 16 #define SQLITE_INDEX_CONSTRAINT_GE 32 #define SQLITE_INDEX_CONSTRAINT_MATCH 64 #define SQLITE_INDEX_CONSTRAINT_LIKE 65 #define SQLITE_INDEX_CONSTRAINT_GLOB 66 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67 /* ** CAPI3REF: Register A Virtual Table Implementation ** METHOD: sqlite3 ** ** ^These routines are used to register a new [virtual table module] name. ** ^Module names must be registered before ** creating a new [virtual table] using the module and before using a ** preexisting [virtual table] for the module. ** ** ^The module name is registered on the [database connection] specified ** by the first parameter. ^The name of the module is given by the ** second parameter. ^The third parameter is a pointer to ** the implementation of the [virtual table module]. ^The fourth ** parameter is an arbitrary client data pointer that is passed through ** into the [xCreate] and [xConnect] methods of the virtual table module ** when a new virtual table is be being created or reinitialized. ** ** ^The sqlite3_create_module_v2() interface has a fifth parameter which ** is a pointer to a destructor for the pClientData. ^SQLite will ** invoke the destructor function (if it is not NULL) when SQLite ** no longer needs the pClientData pointer. ^The destructor will also ** be invoked if the call to sqlite3_create_module_v2() fails. ** ^The sqlite3_create_module() ** interface is equivalent to sqlite3_create_module_v2() with a NULL ** destructor. */ SQLITE_API int sqlite3_create_module( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData /* Client data for xCreate/xConnect */ ); SQLITE_API int sqlite3_create_module_v2( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData, /* Client data for xCreate/xConnect */ void(*xDestroy)(void*) /* Module destructor function */ ); /* ** CAPI3REF: Virtual Table Instance Object ** KEYWORDS: sqlite3_vtab ** ** Every [virtual table module] implementation uses a subclass ** of this object to describe a particular instance ** of the [virtual table]. Each subclass will ** be tailored to the specific needs of the module implementation. ** The purpose of this superclass is to define certain fields that are ** common to all module implementations. ** ** ^Virtual tables methods can set an error message by assigning a ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should ** take care that any prior string is freed by a call to [sqlite3_free()] ** prior to assigning a new string to zErrMsg. ^After the error message ** is delivered up to the client application, the string will be automatically ** freed by sqlite3_free() and the zErrMsg field will be zeroed. */ struct sqlite3_vtab { const sqlite3_module *pModule; /* The module for this virtual table */ int nRef; /* Number of open cursors */ char *zErrMsg; /* Error message from sqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Virtual Table Cursor Object ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} ** ** Every [virtual table module] implementation uses a subclass of the ** following structure to describe cursors that point into the ** [virtual table] and are used ** to loop through the virtual table. Cursors are created using the ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed ** by the [sqlite3_module.xClose | xClose] method. Cursors are used ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods ** of the module. Each module implementation will define ** the content of a cursor structure to suit its own needs. ** ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. */ struct sqlite3_vtab_cursor { sqlite3_vtab *pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Declare The Schema Of A Virtual Table ** ** ^The [xCreate] and [xConnect] methods of a ** [virtual table module] call this interface ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table ** METHOD: sqlite3 ** ** ^(Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. ** But global versions of those functions ** must exist in order to be overloaded.)^ ** ** ^(This API makes sure a global version of a function with a particular ** name and number of parameters exists. If no such function exists ** before this API is called, a new function is created.)^ ^The implementation ** of the new function always causes an exception to be thrown. So ** the new function is not good for anything by itself. Its only ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up ** to a comment remarkably similar to this one) is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** CAPI3REF: A Handle To An Open BLOB ** KEYWORDS: {BLOB handle} {BLOB handles} ** ** An instance of this object represents an open BLOB on which ** [sqlite3_blob_open | incremental BLOB I/O] can be performed. ** ^Objects of this type are created by [sqlite3_blob_open()] ** and destroyed by [sqlite3_blob_close()]. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces ** can be used to read or write small subsections of the BLOB. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. */ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O ** METHOD: sqlite3 ** CONSTRUCTOR: sqlite3_blob ** ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; ** in other words, the same BLOB that would be selected by: ** ** <pre> ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow; ** </pre>)^ ** ** ^(Parameter zDb is not the filename that contains the database, but ** rather the symbolic name of the database. For attached databases, this is ** the name that appears after the AS keyword in the [ATTACH] statement. ** For the main database file, the database name is "main". For TEMP ** tables, the database name is "temp".)^ ** ** ^If the flags parameter is non-zero, then the BLOB is opened for read ** and write access. ^If the flags parameter is zero, the BLOB is opened for ** read-only access. ** ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored ** in *ppBlob. Otherwise an [error code] is returned and, unless the error ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided ** the API is not misused, it is always safe to call [sqlite3_blob_close()] ** on *ppBlob after this function it returns. ** ** This function fails with SQLITE_ERROR if any of the following are true: ** <ul> ** <li> ^(Database zDb does not exist)^, ** <li> ^(Table zTable does not exist within database zDb)^, ** <li> ^(Table zTable is a WITHOUT ROWID table)^, ** <li> ^(Column zColumn does not exist)^, ** <li> ^(Row iRow is not present in the table)^, ** <li> ^(The specified column of row iRow contains a value that is not ** a TEXT or BLOB value)^, ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE ** constraint and the blob is being opened for read/write access)^, ** <li> ^([foreign key constraints | Foreign key constraints] are enabled, ** column zColumn is part of a [child key] definition and the blob is ** being opened for read/write access)^. ** </ul> ** ** ^Unless it returns SQLITE_MISUSE, this function sets the ** [database connection] error code and message accessible via ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. ** ** A BLOB referenced by sqlite3_blob_open() may be read using the ** [sqlite3_blob_read()] interface and modified by using ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a ** different row of the same table using the [sqlite3_blob_reopen()] ** interface. However, the column, table, or database of a [BLOB handle] ** cannot be changed after the [BLOB handle] is opened. ** ** ^(If the row that a BLOB handle points to is modified by an ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects ** then the BLOB handle is marked as "expired". ** This is true if any column of the row is changed, even a column ** other than the one the BLOB handle is open on.)^ ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for ** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. ** ^(Changes written into a BLOB prior to the BLOB expiring are not ** rolled back by the expiration of the BLOB. Such changes will eventually ** commit if the transaction continues to completion.)^ ** ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of ** the opened blob. ^The size of a blob may not be changed by this ** interface. Use the [UPDATE] SQL command to change the size of a ** blob. ** ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function may be used to create a ** zero-filled blob to read or write using the incremental-blob interface. ** ** To avoid a resource leak, every open [BLOB handle] should eventually ** be released by a call to [sqlite3_blob_close()]. ** ** See also: [sqlite3_blob_close()], ** [sqlite3_blob_reopen()], [sqlite3_blob_read()], ** [sqlite3_blob_bytes()], [sqlite3_blob_write()]. */ SQLITE_API int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); /* ** CAPI3REF: Move a BLOB Handle to a New Row ** METHOD: sqlite3_blob ** ** ^This function is used to move an existing [BLOB handle] so that it points ** to a different row of the same database table. ^The new row is identified ** by the rowid value passed as the second argument. Only the row can be ** changed. ^The database, table and column on which the blob handle is open ** remain the same. Moving an existing [BLOB handle] to a new row is ** faster than closing the existing handle and opening a new one. ** ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - ** it must exist and there must be either a blob or text value stored in ** the nominated column.)^ ^If the new row is not present in the table, or if ** it does not contain a blob or text value, or if another error occurs, an ** SQLite error code is returned and the blob handle is considered aborted. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle ** always returns zero. ** ** ^This function sets the database handle error code and message. */ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); /* ** CAPI3REF: Close A BLOB Handle ** DESTRUCTOR: sqlite3_blob ** ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed ** unconditionally. Even if this routine returns an error code, the ** handle is still closed.)^ ** ** ^If the blob handle being closed was opened for read-write access, and if ** the database is in auto-commit mode and there are no other open read-write ** blob handles or active write statements, the current transaction is ** committed. ^If an error occurs while committing the transaction, an error ** code is returned and the transaction rolled back. ** ** Calling this function with an argument that is not a NULL pointer or an ** open blob handle results in undefined behaviour. ^Calling this routine ** with a null pointer (such as would be returned by a failed call to ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function ** is passed a valid open blob handle, the values returned by the ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB ** METHOD: sqlite3_blob ** ** ^Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. ^The ** incremental blob I/O routines can only read or overwriting existing ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); /* ** CAPI3REF: Read Data From A BLOB Incrementally ** METHOD: sqlite3_blob ** ** ^(This function is used to read data from an open [BLOB handle] into a ** caller-supplied buffer. N bytes of data are copied into buffer Z ** from the open BLOB, starting at offset iOffset.)^ ** ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is ** less than zero, [SQLITE_ERROR] is returned and no data is read. ** ^The size of the blob (and hence the maximum value of N+iOffset) ** can be determined using the [sqlite3_blob_bytes()] interface. ** ** ^An attempt to read from an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ** ** ^(On success, sqlite3_blob_read() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_write()]. */ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally ** METHOD: sqlite3_blob ** ** ^(This function is used to write data into an open [BLOB handle] from a ** caller-supplied buffer. N bytes of data are copied from the buffer Z ** into the open BLOB, starting at offset iOffset.)^ ** ** ^(On success, sqlite3_blob_write() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ^Unless SQLITE_MISUSE is returned, this function sets the ** [database connection] error code and message accessible via ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. ** ** ^If the [BLOB handle] passed as the first argument was not opened for ** writing (the flags parameter to [sqlite3_blob_open()] was zero), ** this function returns [SQLITE_READONLY]. ** ** This function may only modify the contents of the BLOB; it is ** not possible to increase the size of a BLOB using this API. ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is written. The size of the ** BLOB (and hence the maximum value of N+iOffset) can be determined ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less ** than zero [SQLITE_ERROR] is returned and no data is written. ** ** ^An attempt to write to an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred ** before the [BLOB handle] expired are not rolled back by the ** expiration of the handle, though of course those changes might ** have been overwritten by the statement that expired the BLOB handle ** or by other independent statements. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_read()]. */ SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); /* ** CAPI3REF: Virtual File System Objects ** ** A virtual filesystem (VFS) is an [sqlite3_vfs] object ** that SQLite uses to interact ** with the underlying operating system. Most SQLite builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. ** ^Names are case sensitive. ** ^Names are zero-terminated UTF-8 strings. ** ^If there is no match, a NULL pointer is returned. ** ^If zVfsName is NULL then the default VFS is returned. ** ** ^New VFSes are registered with sqlite3_vfs_register(). ** ^Each new VFS becomes the default VFS if the makeDflt flag is set. ** ^The same VFS can be registered multiple times without injury. ** ^To make an existing VFS into the default VFS, register it again ** with the makeDflt flag set. If two different VFSes with the ** same name are registered, the behavior is undefined. If a ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. ** ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. ** ^(If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary.)^ */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); /* ** CAPI3REF: Mutexes ** ** The SQLite core uses these routines for thread ** synchronization. Though they are intended for internal ** use by SQLite, code that links against SQLite is ** permitted to use any of these routines. ** ** The SQLite source code contains multiple implementations ** of these mutex routines. An appropriate implementation ** is selected automatically at compile-time. The following ** implementations are available in the SQLite core: ** ** <ul> ** <li> SQLITE_MUTEX_PTHREADS ** <li> SQLITE_MUTEX_W32 ** <li> SQLITE_MUTEX_NOOP ** </ul> ** ** The SQLITE_MUTEX_NOOP implementation is a set of routines ** that does no real locking and is appropriate for use in ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix ** and Windows. ** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. In this case the ** application must supply a custom mutex implementation using the ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function ** before calling sqlite3_initialize() or any other public sqlite3_ ** function that calls sqlite3_initialize(). ** ** ^The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() ** routine returns NULL if it is unable to allocate the requested ** mutex. The argument to sqlite3_mutex_alloc() must one of these ** integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST ** <li> SQLITE_MUTEX_RECURSIVE ** <li> SQLITE_MUTEX_STATIC_MASTER ** <li> SQLITE_MUTEX_STATIC_MEM ** <li> SQLITE_MUTEX_STATIC_OPEN ** <li> SQLITE_MUTEX_STATIC_PRNG ** <li> SQLITE_MUTEX_STATIC_LRU ** <li> SQLITE_MUTEX_STATIC_PMEM ** <li> SQLITE_MUTEX_STATIC_APP1 ** <li> SQLITE_MUTEX_STATIC_APP2 ** <li> SQLITE_MUTEX_STATIC_APP3 ** <li> SQLITE_MUTEX_STATIC_VFS1 ** <li> SQLITE_MUTEX_STATIC_VFS2 ** <li> SQLITE_MUTEX_STATIC_VFS3 ** </ul> ** ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) ** cause sqlite3_mutex_alloc() to create ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return ** a pointer to a static preexisting mutex. ^Nine static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. ^For the static ** mutex types, the same mutex is returned on every call that has ** the same type number. ** ** ^The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. Attempting to deallocate a static ** mutex results in undefined behavior. ** ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. ^If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] ** upon successful entry. ^(Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** In such cases, the ** mutex must be exited an equal number of times before another thread ** can enter.)^ If the same thread tries to enter any mutex other ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. ** ** ^(Some systems (for example, Windows 95) do not support the operation ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() ** will always return SQLITE_BUSY. The SQLite core only ever uses ** sqlite3_mutex_try() as an optimization so this is acceptable ** behavior.)^ ** ** ^The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. ** ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or ** sqlite3_mutex_leave() is a NULL pointer, then all three routines ** behave as no-ops. ** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); /* ** CAPI3REF: Mutex Methods Object ** ** An instance of this structure defines the low-level routines ** used to allocate and use mutexes. ** ** Usually, the default mutex implementations provided by SQLite are ** sufficient, however the application has the option of substituting a custom ** implementation for specialized deployments or systems for which SQLite ** does not provide a suitable implementation. In this case, the application ** creates and populates an instance of this structure to pass ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. ** Additionally, an instance of this structure can be used as an ** output variable when querying the system for the current mutex ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. ** ** ^The xMutexInit method defined by this structure is invoked as ** part of system initialization by the sqlite3_initialize() function. ** ^The xMutexInit routine is called by SQLite exactly once for each ** effective call to [sqlite3_initialize()]. ** ** ^The xMutexEnd method defined by this structure is invoked as ** part of system shutdown by the sqlite3_shutdown() function. The ** implementation of this method is expected to release all outstanding ** resources obtained by the mutex methods implementation, especially ** those obtained by the xMutexInit method. ^The xMutexEnd() ** interface is invoked exactly once for each call to [sqlite3_shutdown()]. ** ** ^(The remaining seven methods defined by this structure (xMutexAlloc, ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and ** xMutexNotheld) implement the following interfaces (respectively): ** ** <ul> ** <li> [sqlite3_mutex_alloc()] </li> ** <li> [sqlite3_mutex_free()] </li> ** <li> [sqlite3_mutex_enter()] </li> ** <li> [sqlite3_mutex_try()] </li> ** <li> [sqlite3_mutex_leave()] </li> ** <li> [sqlite3_mutex_held()] </li> ** <li> [sqlite3_mutex_notheld()] </li> ** </ul>)^ ** ** The only difference is that the public sqlite3_XXX functions enumerated ** above silently ignore any invocations that pass a NULL pointer instead ** of a valid mutex handle. The implementations of the methods defined ** by this structure are not required to handle this case, the results ** of passing a NULL pointer instead of a valid mutex handle are undefined ** (i.e. it is acceptable to provide an implementation that segfaults if ** it is passed a NULL pointer). ** ** The xMutexInit() method must be threadsafe. It must be harmless to ** invoke xMutexInit() multiple times within the same process and without ** intervening calls to xMutexEnd(). Second and subsequent calls to ** xMutexInit() must be no-ops. ** ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite ** memory allocation for a fast or recursive mutex. ** ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is ** called, but only if the prior call to xMutexInit returned SQLITE_OK. ** If xMutexInit fails in any way, it is expected to clean up after itself ** prior to returning. */ typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; struct sqlite3_mutex_methods { int (*xMutexInit)(void); int (*xMutexEnd)(void); sqlite3_mutex *(*xMutexAlloc)(int); void (*xMutexFree)(sqlite3_mutex *); void (*xMutexEnter)(sqlite3_mutex *); int (*xMutexTry)(sqlite3_mutex *); void (*xMutexLeave)(sqlite3_mutex *); int (*xMutexHeld)(sqlite3_mutex *); int (*xMutexNotheld)(sqlite3_mutex *); }; /* ** CAPI3REF: Mutex Verification Routines ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. The SQLite core only ** provides implementations for these routines when it is compiled ** with the SQLITE_DEBUG flag. External mutex implementations ** are only required to provide these routines if SQLITE_DEBUG is ** defined and if NDEBUG is not defined. ** ** These routines should return true if the mutex in their argument ** is held or not held, respectively, by the calling thread. ** ** The implementation is not required to provide versions of these ** routines that actually work. If the implementation does not provide working ** versions of these routines, it should at least provide stubs that always ** return true so that one does not get spurious assertion failures. ** ** If the argument to sqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. This seems counter-intuitive since ** clearly the mutex cannot be held if it does not exist. But ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the ** call to sqlite3_mutex_held() to fail, so a non-zero return is ** the appropriate thing to do. The sqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ #ifndef NDEBUG SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); #endif /* ** CAPI3REF: Mutex Types ** ** The [sqlite3_mutex_alloc()] interface takes a single argument ** which is one of these integer constants. ** ** The set of static mutexes may change from one SQLite release to the ** next. Applications that override the built-in mutex logic must be ** prepared to accommodate additional static mutexes. */ #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MASTER 2 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */ #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */ #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */ /* ** CAPI3REF: Retrieve the mutex for a database connection ** METHOD: sqlite3 ** ** ^This interface returns a pointer the [sqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** ^If the [threading mode] is Single-thread or Multi-thread then this ** routine returns a NULL pointer. */ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); /* ** CAPI3REF: Low-Level Control Of Database Files ** METHOD: sqlite3 ** ** ^The [sqlite3_file_control()] interface makes a direct call to the ** xFileControl method for the [sqlite3_io_methods] object associated ** with a particular database identified by the second argument. ^The ** name of the database is "main" for the main database or "temp" for the ** TEMP database, or the name that appears after the AS keyword for ** databases that are added using the [ATTACH] SQL command. ** ^A NULL pointer can be used in place of "main" to refer to the ** main database file. ** ^The third and fourth parameters to this routine ** are passed directly through to the second and third parameters of ** the xFileControl method. ^The return value of the xFileControl ** method becomes the return value of this routine. ** ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes ** a pointer to the underlying [sqlite3_file] object to be written into ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER ** case is a short-circuit path which does not actually invoke the ** underlying sqlite3_io_methods.xFileControl method. ** ** ^If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. ^This error ** code is not remembered and will not be recalled by [sqlite3_errcode()] ** or [sqlite3_errmsg()]. The underlying xFileControl method might ** also return SQLITE_ERROR. There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. ** ** See also: [SQLITE_FCNTL_LOCKSTATE] */ SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); /* ** CAPI3REF: Testing Interface ** ** ^The sqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. ^The first parameter is an operation code that determines ** the number, meaning, and operation of all subsequent parameters. ** ** This interface is not for use by applications. It exists solely ** for verifying the correct operation of the SQLite library. Depending ** on how the SQLite library is compiled, this interface might not exist. ** ** The details of the operation codes, their meanings, the parameters ** they take, and what they do are all subject to change without notice. ** Unlike most of the SQLite API, this function is not guaranteed to ** operate consistently from one release to the next. */ SQLITE_API int sqlite3_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes ** ** These constants are the valid operation code parameters used ** as the first argument to [sqlite3_test_control()]. ** ** These parameters and their meanings are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the ** [sqlite3_test_control()] interface. */ #define SQLITE_TESTCTRL_FIRST 5 #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 #define SQLITE_TESTCTRL_PRNG_RESET 7 #define SQLITE_TESTCTRL_BITVEC_TEST 8 #define SQLITE_TESTCTRL_FAULT_INSTALL 9 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 #define SQLITE_TESTCTRL_PENDING_BYTE 11 #define SQLITE_TESTCTRL_ASSERT 12 #define SQLITE_TESTCTRL_ALWAYS 13 #define SQLITE_TESTCTRL_RESERVE 14 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15 #define SQLITE_TESTCTRL_ISKEYWORD 16 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21 #define SQLITE_TESTCTRL_BYTEORDER 22 #define SQLITE_TESTCTRL_ISINIT 23 #define SQLITE_TESTCTRL_SORTER_MMAP 24 #define SQLITE_TESTCTRL_IMPOSTER 25 #define SQLITE_TESTCTRL_LAST 25 /* ** CAPI3REF: SQLite Runtime Status ** ** ^These interfaces are used to retrieve runtime status information ** about the performance of SQLite, and optionally to reset various ** highwater marks. ^The first argument is an integer code for ** the specific parameter to measure. ^(Recognized integer codes ** are of the form [status parameters | SQLITE_STATUS_...].)^ ** ^The current value of the parameter is returned into *pCurrent. ** ^The highest recorded value is returned in *pHighwater. ^If the ** resetFlag is true, then the highest record value is reset after ** *pHighwater is written. ^(Some parameters do not record the highest ** value. For those parameters ** nothing is written into *pHighwater and the resetFlag is ignored.)^ ** ^(Other parameters record only the highwater mark and not the current ** value. For these latter parameters nothing is written into *pCurrent.)^ ** ** ^The sqlite3_status() and sqlite3_status64() routines return ** SQLITE_OK on success and a non-zero [error code] on failure. ** ** If either the current value or the highwater mark is too large to ** be represented by a 32-bit integer, then the values returned by ** sqlite3_status() are undefined. ** ** See also: [sqlite3_db_status()] */ SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); SQLITE_API int sqlite3_status64( int op, sqlite3_int64 *pCurrent, sqlite3_int64 *pHighwater, int resetFlag ); /* ** CAPI3REF: Status Parameters ** KEYWORDS: {status parameters} ** ** These integer constants designate various run-time status parameters ** that can be returned by [sqlite3_status()]. ** ** <dl> ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt> ** <dd>This parameter is the current amount of memory checked out ** using [sqlite3_malloc()], either directly or indirectly. The ** figure includes calls made to [sqlite3_malloc()] by the application ** and internal memory usage by the SQLite library. Scratch memory ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** this parameter. The amount returned is the sum of the allocation ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^ ** ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt> ** <dd>This parameter records the largest memory allocation request ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their ** internal equivalents). Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt> ** <dd>This parameter records the number of separate memory allocations ** currently checked out.</dd>)^ ** ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt> ** <dd>This parameter returns the number of pages used out of the ** [pagecache memory allocator] that was configured using ** [SQLITE_CONFIG_PAGECACHE]. The ** value returned is in pages, not in bytes.</dd>)^ ** ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt> ** <dd>This parameter returns the number of bytes of page cache ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] ** buffer and where forced to overflow to [sqlite3_malloc()]. The ** returned value includes allocations that overflowed because they ** where too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because ** no space was left in the page cache.</dd>)^ ** ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt> ** <dd>This parameter records the largest memory allocation request ** handed to [pagecache memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt> ** <dd>This parameter returns the number of allocations used out of the ** [scratch memory allocator] configured using ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not ** in bytes. Since a single thread may only have one scratch allocation ** outstanding at time, this parameter also reports the number of threads ** using scratch memory at the same time.</dd>)^ ** ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt> ** <dd>This parameter returns the number of bytes of scratch memory ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] ** buffer and where forced to overflow to [sqlite3_malloc()]. The values ** returned include overflows because the requested allocation was too ** larger (that is, because the requested allocation was larger than the ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer ** slots were available. ** </dd>)^ ** ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt> ** <dd>This parameter records the largest memory allocation request ** handed to [scratch memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt> ** <dd>The *pHighwater parameter records the deepest parser stack. ** The *pCurrent value is undefined. The *pHighwater value is only ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^ ** </dl> ** ** New status parameters may be added from time to time. */ #define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 #define SQLITE_STATUS_SCRATCH_USED 3 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 #define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PAGECACHE_SIZE 7 #define SQLITE_STATUS_SCRATCH_SIZE 8 #define SQLITE_STATUS_MALLOC_COUNT 9 /* ** CAPI3REF: Database Connection Status ** METHOD: sqlite3 ** ** ^This interface is used to retrieve runtime status information ** about a single [database connection]. ^The first argument is the ** database connection object to be interrogated. ^The second argument ** is an integer constant, taken from the set of ** [SQLITE_DBSTATUS options], that ** determines the parameter to interrogate. The set of ** [SQLITE_DBSTATUS options] is likely ** to grow in future releases of SQLite. ** ** ^The current value of the requested parameter is written into *pCur ** and the highest instantaneous value is written into *pHiwtr. ^If ** the resetFlg is true, then the highest instantaneous value is ** reset back down to the current value. ** ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a ** non-zero [error code] on failure. ** ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. */ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); /* ** CAPI3REF: Status Parameters for database connections ** KEYWORDS: {SQLITE_DBSTATUS options} ** ** These constants are the available integer "verbs" that can be passed as ** the second argument to the [sqlite3_db_status()] interface. ** ** New verbs may be added in future releases of SQLite. Existing verbs ** might be discontinued. Applications should check the return code from ** [sqlite3_db_status()] to make sure that the call worked. ** The [sqlite3_db_status()] interface will return a non-zero error code ** if a discontinued or unsupported verb is invoked. ** ** <dl> ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt> ** <dd>This parameter returns the number of lookaside memory slots currently ** checked out.</dd>)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt> ** <dd>This parameter returns the number malloc attempts that were ** satisfied using lookaside memory. Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt> ** <dd>This parameter returns the number malloc attempts that might have ** been satisfied using lookaside memory but failed due to the amount of ** memory requested being larger than the lookaside slot size. ** Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt> ** <dd>This parameter returns the number malloc attempts that might have ** been satisfied using lookaside memory but failed due to all lookaside ** memory already being in use. ** Only the high-water value is meaningful; ** the current value is always zero.)^ ** ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap ** memory used by all pager caches associated with the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. ** ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt> ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a ** pager cache is shared between two or more connections the bytes of heap ** memory used by that pager cache is divided evenly between the attached ** connections.)^ In other words, if none of the pager caches associated ** with the database connection are shared, this request returns the same ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are ** shared, the value returned by this call will be smaller than that returned ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0. ** ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap ** memory used to store the schema for all databases associated ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ ** ^The full amount of memory used by the schemas is reported, even if the ** schema memory is shared with other database connections due to ** [shared cache mode] being enabled. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. ** ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap ** and lookaside memory used by all prepared statements associated with ** the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. ** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt> ** <dd>This parameter returns the number of pager cache hits that have ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT ** is always 0. ** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt> ** <dd>This parameter returns the number of pager cache misses that have ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS ** is always 0. ** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt> ** <dd>This parameter returns the number of dirty cache entries that have ** been written to disk. Specifically, the number of pages written to the ** wal file in wal mode databases, or the number of pages written to the ** database file in rollback mode databases. Any pages written as part of ** transaction rollback or database recovery operations are not included. ** If an IO or other error occurs while writing a page to disk, the effect ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. ** </dd> ** ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt> ** <dd>This parameter returns zero for the current value if and only if ** all foreign key constraints (deferred or immediate) have been ** resolved.)^ ^The highwater mark is always 0. ** </dd> ** </dl> */ #define SQLITE_DBSTATUS_LOOKASIDE_USED 0 #define SQLITE_DBSTATUS_CACHE_USED 1 #define SQLITE_DBSTATUS_SCHEMA_USED 2 #define SQLITE_DBSTATUS_STMT_USED 3 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 #define SQLITE_DBSTATUS_CACHE_HIT 7 #define SQLITE_DBSTATUS_CACHE_MISS 8 #define SQLITE_DBSTATUS_CACHE_WRITE 9 #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */ /* ** CAPI3REF: Prepared Statement Status ** METHOD: sqlite3_stmt ** ** ^(Each prepared statement maintains various ** [SQLITE_STMTSTATUS counters] that measure the number ** of times it has performed specific operations.)^ These counters can ** be used to monitor the performance characteristics of the prepared ** statements. For example, if the number of table steps greatly exceeds ** the number of table searches or result rows, that would tend to indicate ** that the prepared statement is using a full table scan rather than ** an index. ** ** ^(This interface is used to retrieve and reset counter values from ** a [prepared statement]. The first argument is the prepared statement ** object to be interrogated. The second argument ** is an integer code for a specific [SQLITE_STMTSTATUS counter] ** to be interrogated.)^ ** ^The current value of the requested counter is returned. ** ^If the resetFlg is true, then the counter is reset to zero after this ** interface call returns. ** ** See also: [sqlite3_status()] and [sqlite3_db_status()]. */ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); /* ** CAPI3REF: Status Parameters for prepared statements ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} ** ** These preprocessor macros define integer codes that name counter ** values associated with the [sqlite3_stmt_status()] interface. ** The meanings of the various counters are as follows: ** ** <dl> ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt> ** <dd>^This is the number of times that SQLite has stepped forward in ** a table as part of a full table scan. Large numbers for this counter ** may indicate opportunities for performance improvement through ** careful use of indices.</dd> ** ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt> ** <dd>^This is the number of sort operations that have occurred. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance through careful use of indices.</dd> ** ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt> ** <dd>^This is the number of rows inserted into transient indices that ** were created automatically in order to help joins run faster. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance by adding permanent indices that do not ** need to be reinitialized each time the statement is run.</dd> ** ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt> ** <dd>^This is the number of virtual machine operations executed ** by the prepared statement if that number is less than or equal ** to 2147483647. The number of virtual machine operations can be ** used as a proxy for the total work done by the prepared statement. ** If the number of virtual machine operations exceeds 2147483647 ** then the value returned by this statement status code is undefined. ** </dd> ** </dl> */ #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 #define SQLITE_STMTSTATUS_SORT 2 #define SQLITE_STMTSTATUS_AUTOINDEX 3 #define SQLITE_STMTSTATUS_VM_STEP 4 /* ** CAPI3REF: Custom Page Cache Object ** ** The sqlite3_pcache type is opaque. It is implemented by ** the pluggable module. The SQLite core has no knowledge of ** its size or internal structure and never deals with the ** sqlite3_pcache object except by holding and passing pointers ** to the object. ** ** See [sqlite3_pcache_methods2] for additional information. */ typedef struct sqlite3_pcache sqlite3_pcache; /* ** CAPI3REF: Custom Page Cache Object ** ** The sqlite3_pcache_page object represents a single page in the ** page cache. The page cache will allocate instances of this ** object. Various methods of the page cache use pointers to instances ** of this object as parameters or as their return value. ** ** See [sqlite3_pcache_methods2] for additional information. */ typedef struct sqlite3_pcache_page sqlite3_pcache_page; struct sqlite3_pcache_page { void *pBuf; /* The content of the page */ void *pExtra; /* Extra information associated with the page */ }; /* ** CAPI3REF: Application Defined Page Cache. ** KEYWORDS: {page cache} ** ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can ** register an alternative page cache implementation by passing in an ** instance of the sqlite3_pcache_methods2 structure.)^ ** In many applications, most of the heap memory allocated by ** SQLite is used for the page cache. ** By implementing a ** custom page cache using this API, an application can better control ** the amount of memory consumed by SQLite, the way in which ** that memory is allocated and released, and the policies used to ** determine exactly which parts of a database file are cached and for ** how long. ** ** The alternative page cache mechanism is an ** extreme measure that is only needed by the most demanding applications. ** The built-in page cache is recommended for most uses. ** ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an ** internal buffer by SQLite within the call to [sqlite3_config]. Hence ** the application may discard the parameter after the call to ** [sqlite3_config()] returns.)^ ** ** [[the xInit() page cache method]] ** ^(The xInit() method is called once for each effective ** call to [sqlite3_initialize()])^ ** (usually only once during the lifetime of the process). ^(The xInit() ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ ** The intent of the xInit() method is to set up global data structures ** required by the custom page cache implementation. ** ^(If the xInit() method is NULL, then the ** built-in default page cache is used instead of the application defined ** page cache.)^ ** ** [[the xShutdown() page cache method]] ** ^The xShutdown() method is called by [sqlite3_shutdown()]. ** It can be used to clean up ** any outstanding resources before process shutdown, if required. ** ^The xShutdown() method may be NULL. ** ** ^SQLite automatically serializes calls to the xInit method, ** so the xInit method need not be threadsafe. ^The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. All other methods must be threadsafe ** in multithreaded applications. ** ** ^SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). ** ** [[the xCreate() page cache methods]] ** ^SQLite invokes the xCreate() method to construct a new cache instance. ** SQLite will typically create one cache instance for each open database file, ** though this is not guaranteed. ^The ** first parameter, szPage, is the size in bytes of the pages that must ** be allocated by the cache. ^szPage will always a power of two. ^The ** second parameter szExtra is a number of bytes of extra storage ** associated with each page cache entry. ^The szExtra parameter will ** a number less than 250. SQLite will use the ** extra szExtra bytes on each page to store metadata about the underlying ** database page on disk. The value passed into szExtra depends ** on the SQLite version, the target platform, and how SQLite was compiled. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being ** created will be used to cache database pages of a file stored on disk, or ** false if it is used for an in-memory database. The cache implementation ** does not have to do anything special based with the value of bPurgeable; ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will ** never invoke xUnpin() except to deliberately delete a page. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to ** false will always have the "discard" flag set to true. ** ^Hence, a cache created with bPurgeable false will ** never contain any unpinned pages. ** ** [[the xCachesize() page cache method]] ** ^(The xCachesize() method may be called at any time by SQLite to set the ** suggested maximum cache-size (number of pages stored by) the cache ** instance passed as the first argument. This is the value configured using ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable ** parameter, the implementation is not required to do anything with this ** value; it is advisory only. ** ** [[the xPagecount() page cache methods]] ** The xPagecount() method must return the number of pages currently ** stored in the cache, both pinned and unpinned. ** ** [[the xFetch() page cache methods]] ** The xFetch() method locates a page in the cache and returns a pointer to ** an sqlite3_pcache_page object associated with that page, or a NULL pointer. ** The pBuf element of the returned sqlite3_pcache_page object will be a ** pointer to a buffer of szPage bytes used to store the content of a ** single database page. The pExtra element of sqlite3_pcache_page will be ** a pointer to the szExtra bytes of extra storage that SQLite has requested ** for each entry in the page cache. ** ** The page to be fetched is determined by the key. ^The minimum key value ** is 1. After it has been retrieved using xFetch, the page is considered ** to be "pinned". ** ** If the requested page is already in the page cache, then the page cache ** implementation must return a pointer to the page buffer with its content ** intact. If the requested page is not already in the cache, then the ** cache implementation should use the value of the createFlag ** parameter to help it determined what action to take: ** ** <table border=1 width=85% align=center> ** <tr><th> createFlag <th> Behavior when page is not already in cache ** <tr><td> 0 <td> Do not allocate a new page. Return NULL. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so. ** Otherwise return NULL. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return ** NULL if allocating a new page is effectively impossible. ** </table> ** ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite ** will only use a createFlag of 2 after a prior call with a createFlag of 1 ** failed.)^ In between the to xFetch() calls, SQLite may ** attempt to unpin one or more cache pages by spilling the content of ** pinned pages to disk and synching the operating system disk cache. ** ** [[the xUnpin() page cache method]] ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page ** as its second argument. If the third parameter, discard, is non-zero, ** then the page must be evicted from the cache. ** ^If the discard parameter is ** zero, then the page may be discarded or retained at the discretion of ** page cache implementation. ^The page cache implementation ** may choose to evict unpinned pages at any time. ** ** The cache must not perform any reference counting. A single ** call to xUnpin() unpins the page regardless of the number of prior calls ** to xFetch(). ** ** [[the xRekey() page cache methods]] ** The xRekey() method is used to change the key value associated with the ** page passed as the second argument. If the cache ** previously contains an entry associated with newKey, it must be ** discarded. ^Any prior cache entry associated with newKey is guaranteed not ** to be pinned. ** ** When SQLite calls the xTruncate() method, the cache must discard all ** existing cache entries with page numbers (keys) greater than or equal ** to the value of the iLimit parameter passed to xTruncate(). If any ** of these pages are pinned, they are implicitly unpinned, meaning that ** they can be safely discarded. ** ** [[the xDestroy() page cache method]] ** ^The xDestroy() method is used to delete a cache allocated by xCreate(). ** All resources associated with the specified cache should be freed. ^After ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] ** handle invalid, and will not use it with any other sqlite3_pcache_methods2 ** functions. ** ** [[the xShrink() page cache method]] ** ^SQLite invokes the xShrink() method when it wants the page cache to ** free up as much of heap memory as possible. The page cache implementation ** is not obligated to free any memory, but well-behaved implementations should ** do their best. */ typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; struct sqlite3_pcache_methods2 { int iVersion; void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); void (*xShrink)(sqlite3_pcache*); }; /* ** This is the obsolete pcache_methods object that has now been replaced ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is ** retained in the header file for backwards compatibility only. */ typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; struct sqlite3_pcache_methods { void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, void*, int discard); void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); }; /* ** CAPI3REF: Online Backup Object ** ** The sqlite3_backup object records state information about an ongoing ** online backup operation. ^The sqlite3_backup object is created by ** a call to [sqlite3_backup_init()] and is destroyed by a call to ** [sqlite3_backup_finish()]. ** ** See Also: [Using the SQLite Online Backup API] */ typedef struct sqlite3_backup sqlite3_backup; /* ** CAPI3REF: Online Backup API. ** ** The backup API copies the content of one database into another. ** It is useful either for creating backups of databases or ** for copying in-memory databases to or from persistent files. ** ** See Also: [Using the SQLite Online Backup API] ** ** ^SQLite holds a write transaction open on the destination database file ** for the duration of the backup operation. ** ^The source database is read-locked only while it is being read; ** it is not locked continuously for the entire backup operation. ** ^Thus, the backup may be performed on a live source database without ** preventing other database connections from ** reading or writing to the source database while the backup is underway. ** ** ^(To perform a backup operation: ** <ol> ** <li><b>sqlite3_backup_init()</b> is called once to initialize the ** backup, ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer ** the data between the two databases, and finally ** <li><b>sqlite3_backup_finish()</b> is called to release all resources ** associated with the backup operation. ** </ol>)^ ** There should be exactly one call to sqlite3_backup_finish() for each ** successful call to sqlite3_backup_init(). ** ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b> ** ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the ** [database connection] associated with the destination database ** and the database name, respectively. ** ^The database name is "main" for the main database, "temp" for the ** temporary database, or the name specified after the AS keyword in ** an [ATTACH] statement for an attached database. ** ^The S and M arguments passed to ** sqlite3_backup_init(D,N,S,M) identify the [database connection] ** and database name of the source database, respectively. ** ^The source and destination [database connections] (parameters S and D) ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with ** an error. ** ** ^A call to sqlite3_backup_init() will fail, returning NULL, if ** there is already a read or read-write transaction open on the ** destination database. ** ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is ** returned and an error code and error message are stored in the ** destination [database connection] D. ** ^The error code and message for the failed call to sqlite3_backup_init() ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or ** [sqlite3_errmsg16()] functions. ** ^A successful call to sqlite3_backup_init() returns a pointer to an ** [sqlite3_backup] object. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and ** sqlite3_backup_finish() functions to perform the specified backup ** operation. ** ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b> ** ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between ** the source and destination databases specified by [sqlite3_backup] object B. ** ^If N is negative, all remaining source pages are copied. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there ** are still more pages to be copied, then the function returns [SQLITE_OK]. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages ** from source to destination, then it returns [SQLITE_DONE]. ** ^If an error occurs while running sqlite3_backup_step(B,N), ** then an [error code] is returned. ^As well as [SQLITE_OK] and ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. ** ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if ** <ol> ** <li> the destination database was opened read-only, or ** <li> the destination database is using write-ahead-log journaling ** and the destination and source page sizes differ, or ** <li> the destination database is an in-memory database and the ** destination and source page sizes differ. ** </ol>)^ ** ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then ** the [sqlite3_busy_handler | busy-handler function] ** is invoked (if one is specified). ^If the ** busy-handler returns non-zero before the lock is available, then ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to ** sqlite3_backup_step() can be retried later. ^If the source ** [database connection] ** is being used to write to the source database when sqlite3_backup_step() ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this ** case the call to sqlite3_backup_step() can be retried later on. ^(If ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or ** [SQLITE_READONLY] is returned, then ** there is no point in retrying the call to sqlite3_backup_step(). These ** errors are considered fatal.)^ The application must accept ** that the backup operation has failed and pass the backup operation handle ** to the sqlite3_backup_finish() to release associated resources. ** ** ^The first call to sqlite3_backup_step() obtains an exclusive lock ** on the destination file. ^The exclusive lock is not released until either ** sqlite3_backup_finish() is called or the backup operation is complete ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to ** sqlite3_backup_step() obtains a [shared lock] on the source database that ** lasts for the duration of the sqlite3_backup_step() call. ** ^Because the source database is not locked between calls to ** sqlite3_backup_step(), the source database may be modified mid-way ** through the backup process. ^If the source database is modified by an ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be automatically ** restarted by the next call to sqlite3_backup_step(). ^If the source ** database is modified by the using the same database connection as is used ** by the backup operation, then the backup database is automatically ** updated at the same time. ** ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b> ** ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the ** application wishes to abandon the backup operation, the application ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). ** ^The sqlite3_backup_finish() interfaces releases all ** resources associated with the [sqlite3_backup] object. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any ** active write-transaction on the destination database is rolled back. ** The [sqlite3_backup] object is invalid ** and may not be used following a call to sqlite3_backup_finish(). ** ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no ** sqlite3_backup_step() errors occurred, regardless or whether or not ** sqlite3_backup_step() completed. ** ^If an out-of-memory condition or IO error occurred during any prior ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then ** sqlite3_backup_finish() returns the corresponding [error code]. ** ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() ** is not a permanent error and does not affect the return value of ** sqlite3_backup_finish(). ** ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b> ** ** ^The sqlite3_backup_remaining() routine returns the number of pages still ** to be backed up at the conclusion of the most recent sqlite3_backup_step(). ** ^The sqlite3_backup_pagecount() routine returns the total number of pages ** in the source database at the conclusion of the most recent ** sqlite3_backup_step(). ** ^(The values returned by these functions are only updated by ** sqlite3_backup_step(). If the source database is modified in a way that ** changes the size of the source database or the number of pages remaining, ** those changes are not reflected in the output of sqlite3_backup_pagecount() ** and sqlite3_backup_remaining() until after the next ** sqlite3_backup_step().)^ ** ** <b>Concurrent Usage of Database Handles</b> ** ** ^The source [database connection] may be used by the application for other ** purposes while a backup operation is underway or being initialized. ** ^If SQLite is compiled and configured to support threadsafe database ** connections, then the source database connection may be used concurrently ** from within other threads. ** ** However, the application must guarantee that the destination ** [database connection] is not passed to any other API (by any thread) after ** sqlite3_backup_init() is called and before the corresponding call to ** sqlite3_backup_finish(). SQLite does not currently check to see ** if the application incorrectly accesses the destination [database connection] ** and so no error code is reported, but the operations may malfunction ** nevertheless. Use of the destination database connection while a ** backup is in progress might also also cause a mutex deadlock. ** ** If running in [shared cache mode], the application must ** guarantee that the shared cache used by the destination database ** is not accessed while the backup is running. In practice this means ** that the application must guarantee that the disk file being ** backed up to is not accessed by any connection within the process, ** not just the specific connection that was passed to sqlite3_backup_init(). ** ** The [sqlite3_backup] object itself is partially threadsafe. Multiple ** threads may safely make multiple concurrent calls to sqlite3_backup_step(). ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() ** APIs are not strictly speaking threadsafe. If they are invoked at the ** same time as another thread is invoking sqlite3_backup_step() it is ** possible that they return invalid values. */ SQLITE_API sqlite3_backup *sqlite3_backup_init( sqlite3 *pDest, /* Destination database handle */ const char *zDestName, /* Destination database name */ sqlite3 *pSource, /* Source database handle */ const char *zSourceName /* Source database name */ ); SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); /* ** CAPI3REF: Unlock Notification ** METHOD: sqlite3 ** ** ^When running in shared-cache mode, a database operation may fail with ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or ** individual tables within the shared-cache cannot be obtained. See ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. ** ^This API may be used to register a callback that SQLite will invoke ** when the connection currently holding the required lock relinquishes it. ** ^This API is only available if the library was compiled with the ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. ** ** See Also: [Using the SQLite Unlock Notification Feature]. ** ** ^Shared-cache locks are released when a database connection concludes ** its current transaction, either by committing it or rolling it back. ** ** ^When a connection (known as the blocked connection) fails to obtain a ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the ** identity of the database connection (the blocking connection) that ** has locked the required resource is stored internally. ^After an ** application receives an SQLITE_LOCKED error, it may call the ** sqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked ** when the blocking connections current transaction is concluded. ^The ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] ** call that concludes the blocking connections transaction. ** ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, ** there is a chance that the blocking connection will have already ** concluded its transaction by the time sqlite3_unlock_notify() is invoked. ** If this happens, then the specified callback is invoked immediately, ** from within the call to sqlite3_unlock_notify().)^ ** ** ^If the blocked connection is attempting to obtain a write-lock on a ** shared-cache table, and more than one other connection currently holds ** a read-lock on the same table, then SQLite arbitrarily selects one of ** the other connections to use as the blocking connection. ** ** ^(There may be at most one unlock-notify callback registered by a ** blocked connection. If sqlite3_unlock_notify() is called when the ** blocked connection already has a registered unlock-notify callback, ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing ** unlock-notify callback is canceled. ^The blocked connections ** unlock-notify callback may also be canceled by closing the blocked ** connection using [sqlite3_close()]. ** ** The unlock-notify callback is not reentrant. If an application invokes ** any sqlite3_xxx API functions from within an unlock-notify callback, a ** crash or deadlock may be the result. ** ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always ** returns SQLITE_OK. ** ** <b>Callback Invocation Details</b> ** ** When an unlock-notify callback is registered, the application provides a ** single void* pointer that is passed to the callback when it is invoked. ** However, the signature of the callback function allows SQLite to pass ** it an array of void* context pointers. The first argument passed to ** an unlock-notify callback is a pointer to an array of void* pointers, ** and the second is the number of entries in the array. ** ** When a blocking connections transaction is concluded, there may be ** more than one blocked connection that has registered for an unlock-notify ** callback. ^If two or more such blocked connections have specified the ** same callback function, then instead of invoking the callback function ** multiple times, it is invoked once with the set of void* context pointers ** specified by the blocked connections bundled together into an array. ** This gives the application an opportunity to prioritize any actions ** related to the set of unblocked database connections. ** ** <b>Deadlock Detection</b> ** ** Assuming that after registering for an unlock-notify callback a ** database waits for the callback to be issued before taking any further ** action (a reasonable assumption), then using this API may cause the ** application to deadlock. For example, if connection X is waiting for ** connection Y's transaction to be concluded, and similarly connection ** Y is waiting on connection X's transaction, then neither connection ** will proceed and the system may remain deadlocked indefinitely. ** ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock ** detection. ^If a given call to sqlite3_unlock_notify() would put the ** system in a deadlocked state, then SQLITE_LOCKED is returned and no ** unlock-notify callback is registered. The system is said to be in ** a deadlocked state if connection A has registered for an unlock-notify ** callback on the conclusion of connection B's transaction, and connection ** B has itself registered for an unlock-notify callback when connection ** A's transaction is concluded. ^Indirect deadlock is also detected, so ** the system is also considered to be deadlocked if connection B has ** registered for an unlock-notify callback on the conclusion of connection ** C's transaction, where connection C is waiting on connection A. ^Any ** number of levels of indirection are allowed. ** ** <b>The "DROP TABLE" Exception</b> ** ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost ** always appropriate to call sqlite3_unlock_notify(). There is however, ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, ** SQLite checks if there are any currently executing SELECT statements ** that belong to the same connection. If there are, SQLITE_LOCKED is ** returned. In this case there is no "blocking connection", so invoking ** sqlite3_unlock_notify() results in the unlock-notify callback being ** invoked immediately. If the application then re-attempts the "DROP TABLE" ** or "DROP INDEX" query, an infinite loop might be the result. ** ** One way around this problem is to check the extended error code returned ** by an sqlite3_step() call. ^(If there is a blocking connection, then the ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in ** the special "DROP TABLE/INDEX" case, the extended error code is just ** SQLITE_LOCKED.)^ */ SQLITE_API int sqlite3_unlock_notify( sqlite3 *pBlocked, /* Waiting connection */ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ void *pNotifyArg /* Argument to pass to xNotify */ ); /* ** CAPI3REF: String Comparison ** ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications ** and extensions to compare the contents of two buffers containing UTF-8 ** strings in a case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ SQLITE_API int sqlite3_stricmp(const char *, const char *); SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); /* ** CAPI3REF: String Globbing * ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if ** string X matches the [GLOB] pattern P. ** ^The definition of [GLOB] pattern matching used in ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function ** is case sensitive. ** ** Note that this routine returns zero on a match and non-zero if the strings ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. ** ** See also: [sqlite3_strlike()]. */ SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); /* ** CAPI3REF: String LIKE Matching * ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if ** string X matches the [LIKE] pattern P with escape character E. ** ^The definition of [LIKE] pattern matching used in ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case ** insensitive - equivalent upper and lower case ASCII characters match ** one another. ** ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though ** only ASCII characters are case folded. ** ** Note that this routine returns zero on a match and non-zero if the strings ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. ** ** See also: [sqlite3_strglob()]. */ SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); /* ** CAPI3REF: Error Logging Interface ** ** ^The [sqlite3_log()] interface writes a message into the [error log] ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. ** ^If logging is enabled, the zFormat string and subsequent arguments are ** used with [sqlite3_snprintf()] to generate the final output string. ** ** The sqlite3_log() interface is intended for use by extensions such as ** virtual tables, collating functions, and SQL functions. While there is ** nothing to prevent an application from calling sqlite3_log(), doing so ** is considered bad form. ** ** The zFormat string must not be NULL. ** ** To avoid deadlocks and other threading problems, the sqlite3_log() routine ** will not use dynamically allocated memory. The log message is stored in ** a fixed-length buffer on the stack. If the log message is longer than ** a few hundred characters, it will be truncated to the length of the ** buffer. */ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); /* ** CAPI3REF: Write-Ahead Log Commit Hook ** METHOD: sqlite3 ** ** ^The [sqlite3_wal_hook()] function is used to register a callback that ** is invoked each time data is committed to a database in wal mode. ** ** ^(The callback is invoked by SQLite after the commit has taken place and ** the associated write-lock on the database released)^, so the implementation ** may read, write or [checkpoint] the database as required. ** ** ^The first parameter passed to the callback function when it is invoked ** is a copy of the third parameter passed to sqlite3_wal_hook() when ** registering the callback. ^The second is a copy of the database handle. ** ^The third parameter is the name of the database that was written to - ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter ** is the number of pages currently in the write-ahead log file, ** including those that were just committed. ** ** The callback function should normally return [SQLITE_OK]. ^If an error ** code is returned, that error will propagate back up through the ** SQLite code base to cause the statement that provoked the callback ** to report an error, though the commit will have still occurred. If the ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value ** that does not correspond to any valid SQLite error code, the results ** are undefined. ** ** A single database handle may have at most a single write-ahead log callback ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any ** previously registered write-ahead log callback. ^Note that the ** [sqlite3_wal_autocheckpoint()] interface and the ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will ** overwrite any prior [sqlite3_wal_hook()] settings. */ SQLITE_API void *sqlite3_wal_hook( sqlite3*, int(*)(void *,sqlite3*,const char*,int), void* ); /* ** CAPI3REF: Configure an auto-checkpoint ** METHOD: sqlite3 ** ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around ** [sqlite3_wal_hook()] that causes any database on [database connection] D ** to automatically [checkpoint] ** after committing a transaction if there are N or ** more frames in the [write-ahead log] file. ^Passing zero or ** a negative value as the nFrame parameter disables automatic ** checkpoints entirely. ** ** ^The callback registered by this function replaces any existing callback ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism ** configured by this function. ** ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface ** from SQL. ** ** ^Checkpoints initiated by this mechanism are ** [sqlite3_wal_checkpoint_v2|PASSIVE]. ** ** ^Every new [database connection] defaults to having the auto-checkpoint ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] ** pages. The use of this interface ** is only necessary if the default setting is found to be suboptimal ** for a particular application. */ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); /* ** CAPI3REF: Checkpoint a database ** METHOD: sqlite3 ** ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ ** ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the ** [write-ahead log] for database X on [database connection] D to be ** transferred into the database file and for the write-ahead log to ** be reset. See the [checkpointing] documentation for addition ** information. ** ** This interface used to be the only way to cause a checkpoint to ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] ** interface was added. This interface is retained for backwards ** compatibility and as a convenience for applications that need to manually ** start a callback but which do not need the full power (and corresponding ** complication) of [sqlite3_wal_checkpoint_v2()]. */ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); /* ** CAPI3REF: Checkpoint a database ** METHOD: sqlite3 ** ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint ** operation on database X of [database connection] D in mode M. Status ** information is written back into integers pointed to by L and C.)^ ** ^(The M parameter must be a valid [checkpoint mode]:)^ ** ** <dl> ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd> ** ^Checkpoint as many frames as possible without waiting for any database ** readers or writers to finish, then sync the database file if all frames ** in the log were checkpointed. ^The [busy-handler callback] ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode. ** ^On the other hand, passive mode might leave the checkpoint unfinished ** if there are concurrent readers or writers. ** ** <dt>SQLITE_CHECKPOINT_FULL<dd> ** ^This mode blocks (it invokes the ** [sqlite3_busy_handler|busy-handler callback]) until there is no ** database writer and all readers are reading from the most recent database ** snapshot. ^It then checkpoints all frames in the log file and syncs the ** database file. ^This mode blocks new database writers while it is pending, ** but new database readers are allowed to continue unimpeded. ** ** <dt>SQLITE_CHECKPOINT_RESTART<dd> ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition ** that after checkpointing the log file it blocks (calls the ** [busy-handler callback]) ** until all readers are reading from the database file only. ^This ensures ** that the next writer will restart the log file from the beginning. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new ** database writer attempts while it is pending, but does not impede readers. ** ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd> ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the ** addition that it also truncates the log file to zero bytes just prior ** to a successful return. ** </dl> ** ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in ** the log file or to -1 if the checkpoint could not run because ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the ** log file (including any that were already checkpointed before the function ** was called) or to -1 if the checkpoint could not run due to an error or ** because the database is not in WAL mode. ^Note that upon successful ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero. ** ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If ** any other process is running a checkpoint operation at the same time, the ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a ** busy-handler configured, it will not be invoked in this case. ** ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the ** exclusive "writer" lock on the database file. ^If the writer lock cannot be ** obtained immediately, and a busy-handler is configured, it is invoked and ** the writer lock retried until either the busy-handler returns 0 or the lock ** is successfully obtained. ^The busy-handler is also invoked while waiting for ** database readers as described above. ^If the busy-handler returns 0 before ** the writer lock is obtained or while waiting for database readers, the ** checkpoint operation proceeds from that point in the same way as ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible ** without blocking any further. ^SQLITE_BUSY is returned in this case. ** ** ^If parameter zDb is NULL or points to a zero length string, then the ** specified operation is attempted on all WAL databases [attached] to ** [database connection] db. In this case the ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If ** an SQLITE_BUSY error is encountered when processing one or more of the ** attached WAL databases, the operation is still attempted on any remaining ** attached databases and SQLITE_BUSY is returned at the end. ^If any other ** error occurs while processing an attached database, processing is abandoned ** and the error code is returned to the caller immediately. ^If no error ** (SQLITE_BUSY or otherwise) is encountered while processing the attached ** databases, SQLITE_OK is returned. ** ** ^If database zDb is the name of an attached database that is not in WAL ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If ** zDb is not NULL (or a zero length string) and is not the name of any ** attached database, SQLITE_ERROR is returned to the caller. ** ** ^Unless it returns SQLITE_MISUSE, ** the sqlite3_wal_checkpoint_v2() interface ** sets the error information that is queried by ** [sqlite3_errcode()] and [sqlite3_errmsg()]. ** ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface ** from SQL. */ SQLITE_API int sqlite3_wal_checkpoint_v2( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ int *pnCkpt /* OUT: Total number of frames checkpointed */ ); /* ** CAPI3REF: Checkpoint Mode Values ** KEYWORDS: {checkpoint mode} ** ** These constants define all valid values for the "checkpoint mode" passed ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the ** meaning of each of these checkpoint modes. */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */ #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */ /* ** CAPI3REF: Virtual Table Interface Configuration ** ** This function may be called by either the [xConnect] or [xCreate] method ** of a [virtual table] implementation to configure ** various facets of the virtual table interface. ** ** If this interface is invoked outside the context of an xConnect or ** xCreate virtual table method then the behavior is undefined. ** ** At present, there is only one option that may be configured using ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options ** may be added in the future. */ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); /* ** CAPI3REF: Virtual Table Configuration Options ** ** These macros define the various options to the ** [sqlite3_vtab_config()] interface that [virtual table] implementations ** can use to customize and optimize their behavior. ** ** <dl> ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT ** <dd>Calls of the form ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, ** where X is an integer. If X is zero, then the [virtual table] whose ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not ** support constraints. In this configuration (which is the default) if ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been ** specified as part of the users SQL statement, regardless of the actual ** ON CONFLICT mode specified. ** ** If X is non-zero, then the virtual table implementation guarantees ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before ** any modifications to internal or persistent data structures have been made. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite ** is able to roll back a statement or database transaction, and abandon ** or continue processing the current SQL statement as appropriate. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode ** had been ABORT. ** ** Virtual table implementations that are required to handle OR REPLACE ** must do so within the [xUpdate] method. If a call to the ** [sqlite3_vtab_on_conflict()] function indicates that the current ON ** CONFLICT policy is REPLACE, the virtual table implementation should ** silently replace the appropriate rows within the xUpdate callback and ** return SQLITE_OK. Or, if this is not possible, it may return ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT ** constraint handling. ** </dl> */ #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 /* ** CAPI3REF: Determine The Virtual Table Conflict Policy ** ** This function may only be called from within a call to the [xUpdate] method ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode ** of the SQL statement that triggered the call to the [xUpdate] method of the ** [virtual table]. */ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); /* ** CAPI3REF: Conflict resolution modes ** KEYWORDS: {conflict resolution mode} ** ** These constants are returned by [sqlite3_vtab_on_conflict()] to ** inform a [virtual table] implementation what the [ON CONFLICT] mode ** is for the SQL statement being evaluated. ** ** Note that the [SQLITE_IGNORE] constant is also used as a potential ** return value from the [sqlite3_set_authorizer()] callback and that ** [SQLITE_ABORT] is also a [result code]. */ #define SQLITE_ROLLBACK 1 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ #define SQLITE_FAIL 3 /* #define SQLITE_ABORT 4 // Also an error code */ #define SQLITE_REPLACE 5 /* ** CAPI3REF: Prepared Statement Scan Status Opcodes ** KEYWORDS: {scanstatus options} ** ** The following constants can be used for the T parameter to the ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a ** different metric for sqlite3_stmt_scanstatus() to return. ** ** When the value returned to V is a string, space to hold that string is ** managed by the prepared statement S and will be automatically freed when ** S is finalized. ** ** <dl> ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt> ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be ** set to the total number of times that the X-th loop has run.</dd> ** ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt> ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set ** to the total number of rows examined by all iterations of the X-th loop.</dd> ** ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt> ** <dd>^The "double" variable pointed to by the T parameter will be set to the ** query planner's estimate for the average number of rows output from each ** iteration of the X-th loop. If the query planner's estimates was accurate, ** then this value will approximate the quotient NVISIT/NLOOP and the ** product of this value for all prior loops with the same SELECTID will ** be the NLOOP value for the current loop. ** ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt> ** <dd>^The "const char *" variable pointed to by the T parameter will be set ** to a zero-terminated UTF-8 string containing the name of the index or table ** used for the X-th loop. ** ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt> ** <dd>^The "const char *" variable pointed to by the T parameter will be set ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] ** description for the X-th loop. ** ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt> ** <dd>^The "int" variable pointed to by the T parameter will be set to the ** "select-id" for the X-th loop. The select-id identifies which query or ** subquery the loop is part of. The main query has a select-id of zero. ** The select-id is the same value as is output in the first column ** of an [EXPLAIN QUERY PLAN] query. ** </dl> */ #define SQLITE_SCANSTAT_NLOOP 0 #define SQLITE_SCANSTAT_NVISIT 1 #define SQLITE_SCANSTAT_EST 2 #define SQLITE_SCANSTAT_NAME 3 #define SQLITE_SCANSTAT_EXPLAIN 4 #define SQLITE_SCANSTAT_SELECTID 5 /* ** CAPI3REF: Prepared Statement Scan Status ** METHOD: sqlite3_stmt ** ** This interface returns information about the predicted and measured ** performance for pStmt. Advanced applications can use this ** interface to compare the predicted and the measured performance and ** issue warnings and/or rerun [ANALYZE] if discrepancies are found. ** ** Since this interface is expected to be rarely used, it is only ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS] ** compile-time option. ** ** The "iScanStatusOp" parameter determines which status information to return. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior ** of this interface is undefined. ** ^The requested measurement is written into a variable pointed to by ** the "pOut" parameter. ** Parameter "idx" identifies the specific loop to retrieve statistics for. ** Loops are numbered starting from zero. ^If idx is out of range - less than ** zero or greater than or equal to the total number of loops used to implement ** the statement - a non-zero value is returned and the variable that pOut ** points to is unchanged. ** ** ^Statistics might not be available for all loops in all statements. ^In cases ** where there exist loops with no available statistics, this function behaves ** as if the loop did not exist - it returns non-zero and leave the variable ** that pOut points to unchanged. ** ** See also: [sqlite3_stmt_scanstatus_reset()] */ SQLITE_API int sqlite3_stmt_scanstatus( sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ void *pOut /* Result written here */ ); /* ** CAPI3REF: Zero Scan-Status Counters ** METHOD: sqlite3_stmt ** ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. ** ** This API is only available if the library is built with pre-processor ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. */ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); /* ** CAPI3REF: Flush caches to disk mid-transaction ** ** ^If a write-transaction is open on [database connection] D when the ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty ** pages in the pager-cache that are not currently in use are written out ** to disk. A dirty page may be in use if a database cursor created by an ** active SQL statement is reading from it, or if it is page 1 of a database ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] ** interface flushes caches for all schemas - "main", "temp", and ** any [attached] databases. ** ** ^If this function needs to obtain extra database locks before dirty pages ** can be flushed to disk, it does so. ^If those locks cannot be obtained ** immediately and there is a busy-handler callback configured, it is invoked ** in the usual manner. ^If the required lock still cannot be obtained, then ** the database is skipped and an attempt made to flush any dirty pages ** belonging to the next (if any) database. ^If any databases are skipped ** because locks cannot be obtained, but no other error occurs, this ** function returns SQLITE_BUSY. ** ** ^If any other error occurs while flushing dirty pages to disk (for ** example an IO error or out-of-memory condition), then processing is ** abandoned and an SQLite [error code] is returned to the caller immediately. ** ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. ** ** ^This function does not set the database handle error code or message ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. */ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); /* ** CAPI3REF: The pre-update hook. ** ** ^These interfaces are only available if SQLite is compiled using the ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. ** ** ^The [sqlite3_preupdate_hook()] interface registers a callback function ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation ** on a database table. ** ^At most one preupdate hook may be registered at a time on a single ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides ** the previous setting. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] ** with a NULL pointer as the second parameter. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as ** the first parameter to callbacks. ** ** ^The preupdate hook only fires for changes to real database tables; the ** preupdate hook is not invoked for changes to [virtual tables] or to ** system tables like sqlite_master or sqlite_stat1. ** ** ^The second parameter to the preupdate callback is a pointer to ** the [database connection] that registered the preupdate hook. ** ^The third parameter to the preupdate callback is one of the constants ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the ** kind of update operation that is about to occur. ** ^(The fourth parameter to the preupdate callback is the name of the ** database within the database connection that is being modified. This ** will be "main" for the main database or "temp" for TEMP tables or ** the name given after the AS keyword in the [ATTACH] statement for attached ** databases.)^ ** ^The fifth parameter to the preupdate callback is the name of the ** table that is being modified. ** ** For an UPDATE or DELETE operation on a [rowid table], the sixth ** parameter passed to the preupdate callback is the initial [rowid] of the ** row being modified or deleted. For an INSERT operation on a rowid table, ** or any operation on a WITHOUT ROWID table, the value of the sixth ** parameter is undefined. For an INSERT or UPDATE on a rowid table the ** seventh parameter is the final rowid value of the row being inserted ** or updated. The value of the seventh parameter passed to the callback ** function is not defined for operations on WITHOUT ROWID tables, or for ** INSERT operations on rowid tables. ** ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces ** provide additional information about a preupdate event. These routines ** may only be called from within a preupdate callback. Invoking any of ** these routines from outside of a preupdate callback or with a ** [database connection] pointer that is different from the one supplied ** to the preupdate callback results in undefined and probably undesirable ** behavior. ** ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns ** in the row that is being inserted, updated, or deleted. ** ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to ** a [protected sqlite3_value] that contains the value of the Nth column of ** the table row before it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the ** behavior is undefined. The [sqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to ** a [protected sqlite3_value] that contains the value of the Nth column of ** the table row after it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the ** behavior is undefined. The [sqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate ** callback was invoked as a result of a direct insert, update, or delete ** operation; or 1 for inserts, updates, or deletes invoked by top-level ** triggers; or 2 for changes resulting from triggers called by top-level ** triggers; and so forth. ** ** See also: [sqlite3_update_hook()] */ #if defined(SQLITE_ENABLE_PREUPDATE_HOOK) SQLITE_API void *sqlite3_preupdate_hook( sqlite3 *db, void(*xPreUpdate)( void *pCtx, /* Copy of third arg to preupdate_hook() */ sqlite3 *db, /* Database handle */ int op, /* SQLITE_UPDATE, DELETE or INSERT */ char const *zDb, /* Database name */ char const *zName, /* Table name */ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ ), void* ); SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); SQLITE_API int sqlite3_preupdate_count(sqlite3 *); SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); #endif /* ** CAPI3REF: Low-level system error code ** ** ^Attempt to return the underlying operating system error code or error ** number that caused the most recent I/O error or failure to open a file. ** The return value is OS-dependent. For example, on unix systems, after ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be ** called to get back the underlying "errno" that caused the problem, such ** as ENOSPC, EAUTH, EISDIR, and so forth. */ SQLITE_API int sqlite3_system_errno(sqlite3*); /* ** CAPI3REF: Database Snapshot ** KEYWORDS: {snapshot} {sqlite3_snapshot} ** EXPERIMENTAL ** ** An instance of the snapshot object records the state of a [WAL mode] ** database for some specific point in history. ** ** In [WAL mode], multiple [database connections] that are open on the ** same database file can each be reading a different historical version ** of the database file. When a [database connection] begins a read ** transaction, that connection sees an unchanging copy of the database ** as it existed for the point in time when the transaction first started. ** Subsequent changes to the database from other connections are not seen ** by the reader until a new read transaction is started. ** ** The sqlite3_snapshot object records state information about an historical ** version of the database file so that it is possible to later open a new read ** transaction that sees that historical version of the database rather than ** the most recent version. ** ** The constructor for this object is [sqlite3_snapshot_get()]. The ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer ** to an historical snapshot (if possible). The destructor for ** sqlite3_snapshot objects is [sqlite3_snapshot_free()]. */ typedef struct sqlite3_snapshot { unsigned char hidden[48]; } sqlite3_snapshot; /* ** CAPI3REF: Record A Database Snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a ** new [sqlite3_snapshot] object that records the current state of ** schema S in database connection D. ^On success, the ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK. ** If there is not already a read-transaction open on schema S when ** this function is called, one is opened automatically. ** ** The following must be true for this function to succeed. If any of ** the following statements are false when sqlite3_snapshot_get() is ** called, SQLITE_ERROR is returned. The final value of *P is undefined ** in this case. ** ** <ul> ** <li> The database handle must be in [autocommit mode]. ** ** <li> Schema S of [database connection] D must be a [WAL mode] database. ** ** <li> There must not be a write transaction open on schema S of database ** connection D. ** ** <li> One or more transactions must have been written to the current wal ** file since it was created on disk (by any connection). This means ** that a snapshot cannot be taken on a wal mode database with no wal ** file immediately after it is first opened. At least one transaction ** must be written to it first. ** </ul> ** ** This function may also return SQLITE_NOMEM. If it is called with the ** database handle in autocommit mode but fails for some other reason, ** whether or not a read transaction is opened on schema S is undefined. ** ** The [sqlite3_snapshot] object returned from a successful call to ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()] ** to avoid a memory leak. ** ** The [sqlite3_snapshot_get()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot ); /* ** CAPI3REF: Start a read transaction on an historical snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a ** read transaction for schema S of ** [database connection] D such that the read transaction ** refers to historical [snapshot] P, rather than the most ** recent change to the database. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success ** or an appropriate [error code] if it fails. ** ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be ** the first operation following the [BEGIN] that takes the schema S ** out of [autocommit mode]. ** ^In other words, schema S must not currently be in ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the ** database connection D must be out of [autocommit mode]. ** ^A [snapshot] will fail to open if it has been overwritten by a ** [checkpoint]. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the ** database connection D does not know that the database file for ** schema S is in [WAL mode]. A database connection might not know ** that the database file is in [WAL mode] if there has been no prior ** I/O on that database connection, or if the database entered [WAL mode] ** after the most recent I/O on the database connection.)^ ** (Hint: Run "[PRAGMA application_id]" against a newly opened ** database connection in order to make it ready to use snapshots.) ** ** The [sqlite3_snapshot_open()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot ); /* ** CAPI3REF: Destroy a snapshot ** EXPERIMENTAL ** ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P. ** The application must eventually free every [sqlite3_snapshot] object ** using this routine to avoid a memory leak. ** ** The [sqlite3_snapshot_free()] interface is only available when the ** SQLITE_ENABLE_SNAPSHOT compile-time option is used. */ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); /* ** CAPI3REF: Compare the ages of two snapshot handles. ** EXPERIMENTAL ** ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages ** of two valid snapshot handles. ** ** If the two snapshot handles are not associated with the same database ** file, the result of the comparison is undefined. ** ** Additionally, the result of the comparison is only valid if both of the ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the ** last time the wal file was deleted. The wal file is deleted when the ** database is changed back to rollback mode or when the number of database ** clients drops to zero. If either snapshot handle was obtained before the ** wal file was last deleted, the value returned by this function ** is undefined. ** ** Otherwise, this API returns a negative value if P1 refers to an older ** snapshot than P2, zero if the two handles refer to the same database ** snapshot, and a positive value if P1 is a newer snapshot than P2. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); /* ** CAPI3REF: Recover snapshots from a wal file ** EXPERIMENTAL ** ** If all connections disconnect from a database file but do not perform ** a checkpoint, the existing wal file is opened along with the database ** file the next time the database is opened. At this point it is only ** possible to successfully call sqlite3_snapshot_open() to open the most ** recent snapshot of the database (the one at the head of the wal file), ** even though the wal file may contain other valid snapshots for which ** clients have sqlite3_snapshot handles. ** ** This function attempts to scan the wal file associated with database zDb ** of database handle db and make all valid snapshots available to ** sqlite3_snapshot_open(). It is an error if there is already a read ** transaction open on the database, or if the database is not a wal mode ** database. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ #ifdef SQLITE_OMIT_FLOATING_POINT # undef double #endif #if 0 } /* End of the 'extern "C"' block */ #endif #endif /* SQLITE3_H */ /******** Begin file sqlite3rtree.h *********/ /* ** 2010 August 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* */ #ifndef _SQLITE3RTREE_H_ #define _SQLITE3RTREE_H_ #if 0 extern "C" { #endif typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; /* The double-precision datatype used by RTree depends on the ** SQLITE_RTREE_INT_ONLY compile-time option. */ #ifdef SQLITE_RTREE_INT_ONLY typedef sqlite3_int64 sqlite3_rtree_dbl; #else typedef double sqlite3_rtree_dbl; #endif /* ** Register a geometry callback named zGeom that can be used as part of an ** R-Tree geometry query as follows: ** ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...) */ SQLITE_API int sqlite3_rtree_geometry_callback( sqlite3 *db, const char *zGeom, int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*), void *pContext ); /* ** A pointer to a structure of the following type is passed as the first ** argument to callbacks registered using rtree_geometry_callback(). */ struct sqlite3_rtree_geometry { void *pContext; /* Copy of pContext passed to s_r_g_c() */ int nParam; /* Size of array aParam[] */ sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ void *pUser; /* Callback implementation user data */ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ }; /* ** Register a 2nd-generation geometry callback named zScore that can be ** used as part of an R-Tree geometry query as follows: ** ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...) */ SQLITE_API int sqlite3_rtree_query_callback( sqlite3 *db, const char *zQueryFunc, int (*xQueryFunc)(sqlite3_rtree_query_info*), void *pContext, void (*xDestructor)(void*) ); /* ** A pointer to a structure of the following type is passed as the ** argument to scored geometry callback registered using ** sqlite3_rtree_query_callback(). ** ** Note that the first 5 fields of this structure are identical to ** sqlite3_rtree_geometry. This structure is a subclass of ** sqlite3_rtree_geometry. */ struct sqlite3_rtree_query_info { void *pContext; /* pContext from when function registered */ int nParam; /* Number of function parameters */ sqlite3_rtree_dbl *aParam; /* value of function parameters */ void *pUser; /* callback can use this, if desired */ void (*xDelUser)(void*); /* function to free pUser */ sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ unsigned int *anQueue; /* Number of pending entries in the queue */ int nCoord; /* Number of coordinates */ int iLevel; /* Level of current node or entry */ int mxLevel; /* The largest iLevel value in the tree */ sqlite3_int64 iRowid; /* Rowid for current entry */ sqlite3_rtree_dbl rParentScore; /* Score of parent node */ int eParentWithin; /* Visibility of parent node */ int eWithin; /* OUT: Visiblity */ sqlite3_rtree_dbl rScore; /* OUT: Write the score here */ /* The following fields are only available in 3.8.11 and later */ sqlite3_value **apSqlParam; /* Original SQL values of parameters */ }; /* ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin. */ #define NOT_WITHIN 0 /* Object completely outside of query region */ #define PARTLY_WITHIN 1 /* Object partially overlaps query region */ #define FULLY_WITHIN 2 /* Object fully contained within query region */ #if 0 } /* end of the 'extern "C"' block */ #endif #endif /* ifndef _SQLITE3RTREE_H_ */ /******** End of sqlite3rtree.h *********/ /******** Begin file sqlite3session.h *********/ #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) #define __SQLITESESSION_H_ 1 /* ** Make sure we can call this stuff from C++. */ #if 0 extern "C" { #endif /* ** CAPI3REF: Session Object Handle */ typedef struct sqlite3_session sqlite3_session; /* ** CAPI3REF: Changeset Iterator Handle */ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; /* ** CAPI3REF: Create A New Session Object ** ** Create a new session object attached to database handle db. If successful, ** a pointer to the new object is written to *ppSession and SQLITE_OK is ** returned. If an error occurs, *ppSession is set to NULL and an SQLite ** error code (e.g. SQLITE_NOMEM) is returned. ** ** It is possible to create multiple session objects attached to a single ** database handle. ** ** Session objects created using this function should be deleted using the ** [sqlite3session_delete()] function before the database handle that they ** are attached to is itself closed. If the database handle is closed before ** the session object is deleted, then the results of calling any session ** module function, including [sqlite3session_delete()] on the session object ** are undefined. ** ** Because the session module uses the [sqlite3_preupdate_hook()] API, it ** is not possible for an application to register a pre-update hook on a ** database handle that has one or more session objects attached. Nor is ** it possible to create a session object attached to a database handle for ** which a pre-update hook is already defined. The results of attempting ** either of these things are undefined. ** ** The session object will be used to create changesets for tables in ** database zDb, where zDb is either "main", or "temp", or the name of an ** attached database. It is not an error if database zDb is not attached ** to the database when the session object is created. */ SQLITE_API int sqlite3session_create( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ sqlite3_session **ppSession /* OUT: New session object */ ); /* ** CAPI3REF: Delete A Session Object ** ** Delete a session object previously allocated using ** [sqlite3session_create()]. Once a session object has been deleted, the ** results of attempting to use pSession with any other session module ** function are undefined. ** ** Session objects must be deleted before the database handle to which they ** are attached is closed. Refer to the documentation for ** [sqlite3session_create()] for details. */ SQLITE_API void sqlite3session_delete(sqlite3_session *pSession); /* ** CAPI3REF: Enable Or Disable A Session Object ** ** Enable or disable the recording of changes by a session object. When ** enabled, a session object records changes made to the database. When ** disabled - it does not. A newly created session object is enabled. ** Refer to the documentation for [sqlite3session_changeset()] for further ** details regarding how enabling and disabling a session object affects ** the eventual changesets. ** ** Passing zero to this function disables the session. Passing a value ** greater than zero enables it. Passing a value less than zero is a ** no-op, and may be used to query the current state of the session. ** ** The return value indicates the final state of the session object: 0 if ** the session is disabled, or 1 if it is enabled. */ SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable); /* ** CAPI3REF: Set Or Clear the Indirect Change Flag ** ** Each change recorded by a session object is marked as either direct or ** indirect. A change is marked as indirect if either: ** ** <ul> ** <li> The session object "indirect" flag is set when the change is ** made, or ** <li> The change is made by an SQL trigger or foreign key action ** instead of directly as a result of a users SQL statement. ** </ul> ** ** If a single row is affected by more than one operation within a session, ** then the change is considered indirect if all operations meet the criteria ** for an indirect change above, or direct otherwise. ** ** This function is used to set, clear or query the session object indirect ** flag. If the second argument passed to this function is zero, then the ** indirect flag is cleared. If it is greater than zero, the indirect flag ** is set. Passing a value less than zero does not modify the current value ** of the indirect flag, and may be used to query the current state of the ** indirect flag for the specified session object. ** ** The return value indicates the final state of the indirect flag: 0 if ** it is clear, or 1 if it is set. */ SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); /* ** CAPI3REF: Attach A Table To A Session Object ** ** If argument zTab is not NULL, then it is the name of a table to attach ** to the session object passed as the first argument. All subsequent changes ** made to the table while the session object is enabled will be recorded. See ** documentation for [sqlite3session_changeset()] for further details. ** ** Or, if argument zTab is NULL, then changes are recorded for all tables ** in the database. If additional tables are added to the database (by ** executing "CREATE TABLE" statements) after this call is made, changes for ** the new tables are also recorded. ** ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly ** defined as part of their CREATE TABLE statement. It does not matter if the ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY ** KEY may consist of a single column, or may be a composite key. ** ** It is not an error if the named table does not exist in the database. Nor ** is it an error if the named table does not have a PRIMARY KEY. However, ** no changes will be recorded in either of these scenarios. ** ** Changes are not recorded for individual rows that have NULL values stored ** in one or more of their PRIMARY KEY columns. ** ** SQLITE_OK is returned if the call completes without error. Or, if an error ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. */ SQLITE_API int sqlite3session_attach( sqlite3_session *pSession, /* Session object */ const char *zTab /* Table name */ ); /* ** CAPI3REF: Set a table filter on a Session Object. ** ** The second argument (xFilter) is the "filter callback". For changes to rows ** in tables that are not attached to the Session object, the filter is called ** to determine whether changes to the table's rows should be tracked or not. ** If xFilter returns 0, changes is not tracked. Note that once a table is ** attached, xFilter will not be called again. */ SQLITE_API void sqlite3session_table_filter( sqlite3_session *pSession, /* Session object */ int(*xFilter)( void *pCtx, /* Copy of third arg to _filter_table() */ const char *zTab /* Table name */ ), void *pCtx /* First argument passed to xFilter */ ); /* ** CAPI3REF: Generate A Changeset From A Session Object ** ** Obtain a changeset containing changes to the tables attached to the ** session object passed as the first argument. If successful, ** set *ppChangeset to point to a buffer containing the changeset ** and *pnChangeset to the size of the changeset in bytes before returning ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to ** zero and return an SQLite error code. ** ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes, ** each representing a change to a single row of an attached table. An INSERT ** change contains the values of each field of a new database row. A DELETE ** contains the original values of each field of a deleted database row. An ** UPDATE change contains the original values of each field of an updated ** database row along with the updated values for each updated non-primary-key ** column. It is not possible for an UPDATE change to represent a change that ** modifies the values of primary key columns. If such a change is made, it ** is represented in a changeset as a DELETE followed by an INSERT. ** ** Changes are not recorded for rows that have NULL values stored in one or ** more of their PRIMARY KEY columns. If such a row is inserted or deleted, ** no corresponding change is present in the changesets returned by this ** function. If an existing row with one or more NULL values stored in ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL, ** only an INSERT is appears in the changeset. Similarly, if an existing row ** with non-NULL PRIMARY KEY values is updated so that one or more of its ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a ** DELETE change only. ** ** The contents of a changeset may be traversed using an iterator created ** using the [sqlite3changeset_start()] API. A changeset may be applied to ** a database with a compatible schema using the [sqlite3changeset_apply()] ** API. ** ** Within a changeset generated by this function, all changes related to a ** single table are grouped together. In other words, when iterating through ** a changeset or when applying a changeset to a database, all changes related ** to a single table are processed before moving on to the next table. Tables ** are sorted in the same order in which they were attached (or auto-attached) ** to the sqlite3_session object. The order in which the changes related to ** a single table are stored is undefined. ** ** Following a successful call to this function, it is the responsibility of ** the caller to eventually free the buffer that *ppChangeset points to using ** [sqlite3_free()]. ** ** <h3>Changeset Generation</h3> ** ** Once a table has been attached to a session object, the session object ** records the primary key values of all new rows inserted into the table. ** It also records the original primary key and other column values of any ** deleted or updated rows. For each unique primary key value, data is only ** recorded once - the first time a row with said primary key is inserted, ** updated or deleted in the lifetime of the session. ** ** There is one exception to the previous paragraph: when a row is inserted, ** updated or deleted, if one or more of its primary key columns contain a ** NULL value, no record of the change is made. ** ** The session object therefore accumulates two types of records - those ** that consist of primary key values only (created when the user inserts ** a new record) and those that consist of the primary key values and the ** original values of other table columns (created when the users deletes ** or updates a record). ** ** When this function is called, the requested changeset is created using ** both the accumulated records and the current contents of the database ** file. Specifically: ** ** <ul> ** <li> For each record generated by an insert, the database is queried ** for a row with a matching primary key. If one is found, an INSERT ** change is added to the changeset. If no such row is found, no change ** is added to the changeset. ** ** <li> For each record generated by an update or delete, the database is ** queried for a row with a matching primary key. If such a row is ** found and one or more of the non-primary key fields have been ** modified from their original values, an UPDATE change is added to ** the changeset. Or, if no such row is found in the table, a DELETE ** change is added to the changeset. If there is a row with a matching ** primary key in the database, but all fields contain their original ** values, no change is added to the changeset. ** </ul> ** ** This means, amongst other things, that if a row is inserted and then later ** deleted while a session object is active, neither the insert nor the delete ** will be present in the changeset. Or if a row is deleted and then later a ** row with the same primary key values inserted while a session object is ** active, the resulting changeset will contain an UPDATE change instead of ** a DELETE and an INSERT. ** ** When a session object is disabled (see the [sqlite3session_enable()] API), ** it does not accumulate records when rows are inserted, updated or deleted. ** This may appear to have some counter-intuitive effects if a single row ** is written to more than once during a session. For example, if a row ** is inserted while a session object is enabled, then later deleted while ** the same session object is disabled, no INSERT record will appear in the ** changeset, even though the delete took place while the session was disabled. ** Or, if one field of a row is updated while a session is disabled, and ** another field of the same row is updated while the session is enabled, the ** resulting changeset will contain an UPDATE change that updates both fields. */ SQLITE_API int sqlite3session_changeset( sqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ); /* ** CAPI3REF: Load The Difference Between Tables Into A Session ** ** If it is not already attached to the session object passed as the first ** argument, this function attaches table zTbl in the same manner as the ** [sqlite3session_attach()] function. If zTbl does not exist, or if it ** does not have a primary key, this function is a no-op (but does not return ** an error). ** ** Argument zFromDb must be the name of a database ("main", "temp" etc.) ** attached to the same database handle as the session object that contains ** a table compatible with the table attached to the session by this function. ** A table is considered compatible if it: ** ** <ul> ** <li> Has the same name, ** <li> Has the same set of columns declared in the same order, and ** <li> Has the same PRIMARY KEY definition. ** </ul> ** ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables ** are compatible but do not have any PRIMARY KEY columns, it is not an error ** but no changes are added to the session object. As with other session ** APIs, tables without PRIMARY KEYs are simply ignored. ** ** This function adds a set of changes to the session object that could be ** used to update the table in database zFrom (call this the "from-table") ** so that its content is the same as the table attached to the session ** object (call this the "to-table"). Specifically: ** ** <ul> ** <li> For each row (primary key) that exists in the to-table but not in ** the from-table, an INSERT record is added to the session object. ** ** <li> For each row (primary key) that exists in the to-table but not in ** the from-table, a DELETE record is added to the session object. ** ** <li> For each row (primary key) that exists in both tables, but features ** different non-PK values in each, an UPDATE record is added to the ** session. ** </ul> ** ** To clarify, if this function is called and then a changeset constructed ** using [sqlite3session_changeset()], then after applying that changeset to ** database zFrom the contents of the two compatible tables would be ** identical. ** ** It an error if database zFrom does not exist or does not contain the ** required compatible table. ** ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to free this buffer using ** sqlite3_free(). */ SQLITE_API int sqlite3session_diff( sqlite3_session *pSession, const char *zFromDb, const char *zTbl, char **pzErrMsg ); /* ** CAPI3REF: Generate A Patchset From A Session Object ** ** The differences between a patchset and a changeset are that: ** ** <ul> ** <li> DELETE records consist of the primary key fields only. The ** original values of other fields are omitted. ** <li> The original values of any modified fields are omitted from ** UPDATE records. ** </ul> ** ** A patchset blob may be used with up to date versions of all ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, ** attempting to use a patchset blob with old versions of the ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. ** ** Because the non-primary key "old.*" fields are omitted, no ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset ** is passed to the sqlite3changeset_apply() API. Other conflict types work ** in the same way as for changesets. ** ** Changes within a patchset are ordered in the same way as for changesets ** generated by the sqlite3session_changeset() function (i.e. all changes for ** a single table are grouped together, tables appear in the order in which ** they were attached to the session object). */ SQLITE_API int sqlite3session_patchset( sqlite3_session *pSession, /* Session object */ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ void **ppPatchset /* OUT: Buffer containing changeset */ ); /* ** CAPI3REF: Test if a changeset has recorded any changes. ** ** Return non-zero if no changes to attached tables have been recorded by ** the session object passed as the first argument. Otherwise, if one or ** more changes have been recorded, return zero. ** ** Even if this function returns zero, it is possible that calling ** [sqlite3session_changeset()] on the session handle may still return a ** changeset that contains no changes. This can happen when a row in ** an attached table is modified and then later on the original values ** are restored. However, if this function returns non-zero, then it is ** guaranteed that a call to sqlite3session_changeset() will return a ** changeset containing zero changes. */ SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession); /* ** CAPI3REF: Create An Iterator To Traverse A Changeset ** ** Create an iterator used to iterate through the contents of a changeset. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK ** is returned. Otherwise, if an error occurs, *pp is set to zero and an ** SQLite error code is returned. ** ** The following functions can be used to advance and query a changeset ** iterator created by this function: ** ** <ul> ** <li> [sqlite3changeset_next()] ** <li> [sqlite3changeset_op()] ** <li> [sqlite3changeset_new()] ** <li> [sqlite3changeset_old()] ** </ul> ** ** It is the responsibility of the caller to eventually destroy the iterator ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the ** changeset (pChangeset) must remain valid until after the iterator is ** destroyed. ** ** Assuming the changeset blob was created by one of the ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or ** [sqlite3changeset_invert()] functions, all changes within the changeset ** that apply to a single table are grouped together. This means that when ** an application iterates through a changeset using an iterator created by ** this function, all changes that relate to a single table are visited ** consecutively. There is no chance that the iterator will visit a change ** the applies to table X, then one for table Y, and then later on visit ** another change for table X. */ SQLITE_API int sqlite3changeset_start( sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ int nChangeset, /* Size of changeset blob in bytes */ void *pChangeset /* Pointer to blob containing changeset */ ); /* ** CAPI3REF: Advance A Changeset Iterator ** ** This function may only be used with iterators created by function ** [sqlite3changeset_start()]. If it is called on an iterator passed to ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE ** is returned and the call has no effect. ** ** Immediately after an iterator is created by sqlite3changeset_start(), it ** does not point to any change in the changeset. Assuming the changeset ** is not empty, the first call to this function advances the iterator to ** point to the first change in the changeset. Each subsequent call advances ** the iterator to point to the next change in the changeset (if any). If ** no error occurs and the iterator points to a valid change after a call ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. ** Otherwise, if all changes in the changeset have already been visited, ** SQLITE_DONE is returned. ** ** If an error occurs, an SQLite error code is returned. Possible error ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or ** SQLITE_NOMEM. */ SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter); /* ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this ** is not the case, this function returns [SQLITE_MISUSE]. ** ** If argument pzTab is not NULL, then *pzTab is set to point to a ** nul-terminated utf-8 encoded string containing the name of the table ** affected by the current change. The buffer remains valid until either ** sqlite3changeset_next() is called on the iterator or until the ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is ** set to the number of columns in the table affected by the change. If ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change ** is an indirect change, or false (0) otherwise. See the documentation for ** [sqlite3session_indirect()] for a description of direct and indirect ** changes. Finally, if pOp is not NULL, then *pOp is set to one of ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the ** type of change that the iterator currently points to. ** ** If no error occurs, SQLITE_OK is returned. If an error does occur, an ** SQLite error code is returned. The values of the output variables may not ** be trusted in this case. */ SQLITE_API int sqlite3changeset_op( sqlite3_changeset_iter *pIter, /* Iterator object */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ int *pbIndirect /* OUT: True for an 'indirect' change */ ); /* ** CAPI3REF: Obtain The Primary Key Definition Of A Table ** ** For each modified table, a changeset includes the following: ** ** <ul> ** <li> The number of columns in the table, and ** <li> Which of those columns make up the tables PRIMARY KEY. ** </ul> ** ** This function is used to find which columns comprise the PRIMARY KEY of ** the table modified by the change that iterator pIter currently points to. ** If successful, *pabPK is set to point to an array of nCol entries, where ** nCol is the number of columns in the table. Elements of *pabPK are set to ** 0x01 if the corresponding column is part of the tables primary key, or ** 0x00 if it is not. ** ** If argument pnCol is not NULL, then *pnCol is set to the number of columns ** in the table. ** ** If this function is called when the iterator does not point to a valid ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise, ** SQLITE_OK is returned and the output variables populated as described ** above. */ SQLITE_API int sqlite3changeset_pk( sqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ); /* ** CAPI3REF: Obtain old.* Values From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the vector of ** original row values stored as part of the UPDATE or DELETE change and ** returns SQLITE_OK. The name of the function comes from the fact that this ** is similar to the "old.*" columns available to update or delete triggers. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ SQLITE_API int sqlite3changeset_old( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain new.* Values From A Changeset Iterator ** ** The pIter argument passed to this function may either be an iterator ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator ** created by [sqlite3changeset_start()]. In the latter case, the most recent ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the vector of ** new row values stored as part of the UPDATE or INSERT change and ** returns SQLITE_OK. If the change is an UPDATE and does not include ** a new value for the requested column, *ppValue is set to NULL and ** SQLITE_OK returned. The name of the function comes from the fact that ** this is similar to the "new.*" columns available to update or delete ** triggers. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ SQLITE_API int sqlite3changeset_new( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator ** ** This function should only be used with iterator objects passed to a ** conflict-handler callback by [sqlite3changeset_apply()] with either ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue ** is set to NULL. ** ** Argument iVal must be greater than or equal to 0, and less than the number ** of columns in the table affected by the current change. Otherwise, ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected ** sqlite3_value object containing the iVal'th value from the ** "conflicting row" associated with the current conflict-handler callback ** and returns SQLITE_OK. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ SQLITE_API int sqlite3changeset_conflict( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ sqlite3_value **ppValue /* OUT: Value from conflicting row */ ); /* ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations ** ** This function may only be called with an iterator passed to an ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case ** it sets the output variable to the total number of known foreign key ** violations in the destination database and returns SQLITE_OK. ** ** In all other cases this function returns SQLITE_MISUSE. */ SQLITE_API int sqlite3changeset_fk_conflicts( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ); /* ** CAPI3REF: Finalize A Changeset Iterator ** ** This function is used to finalize an iterator allocated with ** [sqlite3changeset_start()]. ** ** This function should only be called on iterators created using the ** [sqlite3changeset_start()] function. If an application calls this ** function with an iterator passed to a conflict-handler by ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the ** call has no effect. ** ** If an error was encountered within a call to an sqlite3changeset_xxx() ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding ** to that error is returned by this function. Otherwise, SQLITE_OK is ** returned. This is to allow the following pattern (pseudo-code): ** ** sqlite3changeset_start(); ** while( SQLITE_ROW==sqlite3changeset_next() ){ ** // Do something with change. ** } ** rc = sqlite3changeset_finalize(); ** if( rc!=SQLITE_OK ){ ** // An error has occurred ** } */ SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); /* ** CAPI3REF: Invert A Changeset ** ** This function is used to "invert" a changeset object. Applying an inverted ** changeset to a database reverses the effects of applying the uninverted ** changeset. Specifically: ** ** <ul> ** <li> Each DELETE change is changed to an INSERT, and ** <li> Each INSERT change is changed to a DELETE, and ** <li> For each UPDATE change, the old.* and new.* values are exchanged. ** </ul> ** ** This function does not change the order in which changes appear within ** the changeset. It merely reverses the sense of each individual change. ** ** If successful, a pointer to a buffer containing the inverted changeset ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are ** zeroed and an SQLite error code returned. ** ** It is the responsibility of the caller to eventually call sqlite3_free() ** on the *ppOut pointer to free the buffer allocation following a successful ** call to this function. ** ** WARNING/TODO: This function currently assumes that the input is a valid ** changeset. If it is not, the results are undefined. */ SQLITE_API int sqlite3changeset_invert( int nIn, const void *pIn, /* Input changeset */ int *pnOut, void **ppOut /* OUT: Inverse of input */ ); /* ** CAPI3REF: Concatenate Two Changeset Objects ** ** This function is used to concatenate two changesets, A and B, into a ** single changeset. The result is a changeset equivalent to applying ** changeset A followed by changeset B. ** ** This function combines the two input changesets using an ** sqlite3_changegroup object. Calling it produces similar results as the ** following code fragment: ** ** sqlite3_changegroup *pGrp; ** rc = sqlite3_changegroup_new(&pGrp); ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA); ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB); ** if( rc==SQLITE_OK ){ ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); ** }else{ ** *ppOut = 0; ** *pnOut = 0; ** } ** ** Refer to the sqlite3_changegroup documentation below for details. */ SQLITE_API int sqlite3changeset_concat( int nA, /* Number of bytes in buffer pA */ void *pA, /* Pointer to buffer containing changeset A */ int nB, /* Number of bytes in buffer pB */ void *pB, /* Pointer to buffer containing changeset B */ int *pnOut, /* OUT: Number of bytes in output changeset */ void **ppOut /* OUT: Buffer containing output changeset */ ); /* ** CAPI3REF: Changegroup Handle */ typedef struct sqlite3_changegroup sqlite3_changegroup; /* ** CAPI3REF: Create A New Changegroup Object ** ** An sqlite3_changegroup object is used to combine two or more changesets ** (or patchsets) into a single changeset (or patchset). A single changegroup ** object may combine changesets or patchsets, but not both. The output is ** always in the same format as the input. ** ** If successful, this function returns SQLITE_OK and populates (*pp) with ** a pointer to a new sqlite3_changegroup object before returning. The caller ** should eventually free the returned object using a call to ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. ** ** The usual usage pattern for an sqlite3_changegroup object is as follows: ** ** <ul> ** <li> It is created using a call to sqlite3changegroup_new(). ** ** <li> Zero or more changesets (or patchsets) are added to the object ** by calling sqlite3changegroup_add(). ** ** <li> The result of combining all input changesets together is obtained ** by the application via a call to sqlite3changegroup_output(). ** ** <li> The object is deleted using a call to sqlite3changegroup_delete(). ** </ul> ** ** Any number of calls to add() and output() may be made between the calls to ** new() and delete(), and in any order. ** ** As well as the regular sqlite3changegroup_add() and ** sqlite3changegroup_output() functions, also available are the streaming ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). */ int sqlite3changegroup_new(sqlite3_changegroup **pp); /* ** CAPI3REF: Add A Changeset To A Changegroup ** ** Add all changes within the changeset (or patchset) in buffer pData (size ** nData bytes) to the changegroup. ** ** If the buffer contains a patchset, then all prior calls to this function ** on the same changegroup object must also have specified patchsets. Or, if ** the buffer contains a changeset, so must have the earlier calls to this ** function. Otherwise, SQLITE_ERROR is returned and no changes are added ** to the changegroup. ** ** Rows within the changeset and changegroup are identified by the values in ** their PRIMARY KEY columns. A change in the changeset is considered to ** apply to the same row as a change already present in the changegroup if ** the two rows have the same primary key. ** ** Changes to rows that do not already appear in the changegroup are ** simply copied into it. Or, if both the new changeset and the changegroup ** contain changes that apply to a single row, the final contents of the ** changegroup depends on the type of each change, as follows: ** ** <table border=1 style="margin-left:8ex;margin-right:8ex"> ** <tr><th style="white-space:pre">Existing Change </th> ** <th style="white-space:pre">New Change </th> ** <th>Output Change ** <tr><td>INSERT <td>INSERT <td> ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. ** <tr><td>INSERT <td>UPDATE <td> ** The INSERT change remains in the changegroup. The values in the ** INSERT change are modified as if the row was inserted by the ** existing change and then updated according to the new change. ** <tr><td>INSERT <td>DELETE <td> ** The existing INSERT is removed from the changegroup. The DELETE is ** not added. ** <tr><td>UPDATE <td>INSERT <td> ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. ** <tr><td>UPDATE <td>UPDATE <td> ** The existing UPDATE remains within the changegroup. It is amended ** so that the accompanying values are as if the row was updated once ** by the existing change and then again by the new change. ** <tr><td>UPDATE <td>DELETE <td> ** The existing UPDATE is replaced by the new DELETE within the ** changegroup. ** <tr><td>DELETE <td>INSERT <td> ** If one or more of the column values in the row inserted by the ** new change differ from those in the row deleted by the existing ** change, the existing DELETE is replaced by an UPDATE within the ** changegroup. Otherwise, if the inserted row is exactly the same ** as the deleted row, the existing DELETE is simply discarded. ** <tr><td>DELETE <td>UPDATE <td> ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. ** <tr><td>DELETE <td>DELETE <td> ** The new change is ignored. This case does not occur if the new ** changeset was recorded immediately after the changesets already ** added to the changegroup. ** </table> ** ** If the new changeset contains changes to a table that is already present ** in the changegroup, then the number of columns and the position of the ** primary key columns for the table must be consistent. If this is not the ** case, this function fails with SQLITE_SCHEMA. If the input changeset ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is ** returned. Or, if an out-of-memory condition occurs during processing, this ** function returns SQLITE_NOMEM. In all cases, if an error occurs the ** final contents of the changegroup is undefined. ** ** If no error occurs, SQLITE_OK is returned. */ int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); /* ** CAPI3REF: Obtain A Composite Changeset From A Changegroup ** ** Obtain a buffer containing a changeset (or patchset) representing the ** current contents of the changegroup. If the inputs to the changegroup ** were themselves changesets, the output is a changeset. Or, if the ** inputs were patchsets, the output is also a patchset. ** ** As with the output of the sqlite3session_changeset() and ** sqlite3session_patchset() functions, all changes related to a single ** table are grouped together in the output of this function. Tables appear ** in the same order as for the very first changeset added to the changegroup. ** If the second or subsequent changesets added to the changegroup contain ** changes for tables that do not appear in the first changeset, they are ** appended onto the end of the output changeset, again in the order in ** which they are first encountered. ** ** If an error occurs, an SQLite error code is returned and the output ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK ** is returned and the output variables are set to the size of and a ** pointer to the output buffer, respectively. In this case it is the ** responsibility of the caller to eventually free the buffer using a ** call to sqlite3_free(). */ int sqlite3changegroup_output( sqlite3_changegroup*, int *pnData, /* OUT: Size of output buffer in bytes */ void **ppData /* OUT: Pointer to output buffer */ ); /* ** CAPI3REF: Delete A Changegroup Object */ void sqlite3changegroup_delete(sqlite3_changegroup*); /* ** CAPI3REF: Apply A Changeset To A Database ** ** Apply a changeset to a database. This function attempts to update the ** "main" database attached to handle db with the changes found in the ** changeset passed via the second and third arguments. ** ** The fourth argument (xFilter) passed to this function is the "filter ** callback". If it is not NULL, then for each table affected by at least one ** change in the changeset, the filter callback is invoked with ** the table name as the second argument, and a copy of the context pointer ** passed as the sixth argument to this function as the first. If the "filter ** callback" returns zero, then no attempt is made to apply any changes to ** the table. Otherwise, if the return value is non-zero or the xFilter ** argument to this function is NULL, all changes related to the table are ** attempted. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is ** considered compatible if all of the following are true: ** ** <ul> ** <li> The table has the same name as the name recorded in the ** changeset, and ** <li> The table has at least as many columns as recorded in the ** changeset, and ** <li> The table has primary key columns in the same position as ** recorded in the changeset. ** </ul> ** ** If there is no compatible table, it is not an error, but none of the ** changes associated with the table are applied. A warning message is issued ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made ** to modify the table contents according to the UPDATE, INSERT or DELETE ** change. If a change cannot be applied cleanly, the conflict handler ** function passed as the fifth argument to sqlite3changeset_apply() may be ** invoked. A description of exactly when the conflict handler is invoked for ** each type of change is below. ** ** Unlike the xFilter argument, xConflict may not be passed NULL. The results ** of passing anything other than a valid function pointer as the xConflict ** argument are undefined. ** ** Each time the conflict handler function is invoked, it must return one ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned ** if the second argument passed to the conflict handler is either ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler ** returns an illegal value, any changes already made are rolled back and ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different ** actions are taken by sqlite3changeset_apply() depending on the value ** returned by each invocation of the conflict-handler function. Refer to ** the documentation for the three ** [SQLITE_CHANGESET_OMIT|available return values] for details. ** ** <dl> ** <dt>DELETE Changes<dd> ** For each DELETE change, this function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in ** the changeset the row is deleted from the target database. ** ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from the original ** row value stored in the changeset, the conflict-handler function is ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the ** database table has more columns than are recorded in the changeset, ** only the values of those non-primary key fields are compared against ** the current database contents - any trailing database table columns ** are ignored. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] ** passed as the second argument. ** ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT ** (which can only happen if a foreign key constraint is violated), the ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT] ** passed as the second argument. This includes the case where the DELETE ** operation is attempted because an earlier call to the conflict handler ** function returned [SQLITE_CHANGESET_REPLACE]. ** ** <dt>INSERT Changes<dd> ** For each INSERT change, an attempt is made to insert the new row into ** the database. If the changeset row contains fewer fields than the ** database table, the trailing fields are populated with their default ** values. ** ** If the attempt to insert the row fails because the database already ** contains a row with the same primary key values, the conflict handler ** function is invoked with the second argument set to ** [SQLITE_CHANGESET_CONFLICT]. ** ** If the attempt to insert the row fails because of some other constraint ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT]. ** This includes the case where the INSERT operation is re-attempted because ** an earlier call to the conflict handler function returned ** [SQLITE_CHANGESET_REPLACE]. ** ** <dt>UPDATE Changes<dd> ** For each UPDATE change, this function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all modified non-primary key columns also match the values ** stored in the changeset the row is updated within the target database. ** ** If a row with matching primary key values is found, but one or more of ** the modified non-primary key fields contains a value different from an ** original row value stored in the changeset, the conflict-handler function ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since ** UPDATE changes only contain values for non-primary key fields that are ** to be modified, only those fields need to match the original values to ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] ** passed as the second argument. ** ** If the UPDATE operation is attempted, but SQLite returns ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument. ** This includes the case where the UPDATE operation is attempted after ** an earlier call to the conflict handler function returned ** [SQLITE_CHANGESET_REPLACE]. ** </dl> ** ** It is safe to execute SQL statements, including those that write to the ** table that the callback related to, from within the xConflict callback. ** This can be used to further customize the applications conflict ** resolution strategy. ** ** All changes made by this function are enclosed in a savepoint transaction. ** If any other error (aside from a constraint failure when attempting to ** write to the target database) occurs, then the savepoint transaction is ** rolled back, restoring the target database to its original state, and an ** SQLite error code returned. */ SQLITE_API int sqlite3changeset_apply( sqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); /* ** CAPI3REF: Constants Passed To The Conflict Handler ** ** Values that may be passed as the second argument to a conflict-handler. ** ** <dl> ** <dt>SQLITE_CHANGESET_DATA<dd> ** The conflict handler is invoked with CHANGESET_DATA as the second argument ** when processing a DELETE or UPDATE change if a row with the required ** PRIMARY KEY fields is present in the database, but one or more other ** (non primary-key) fields modified by the update do not contain the ** expected "before" values. ** ** The conflicting row, in this case, is the database row with the matching ** primary key. ** ** <dt>SQLITE_CHANGESET_NOTFOUND<dd> ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second ** argument when processing a DELETE or UPDATE change if a row with the ** required PRIMARY KEY fields is not present in the database. ** ** There is no conflicting row in this case. The results of invoking the ** sqlite3changeset_conflict() API are undefined. ** ** <dt>SQLITE_CHANGESET_CONFLICT<dd> ** CHANGESET_CONFLICT is passed as the second argument to the conflict ** handler while processing an INSERT change if the operation would result ** in duplicate primary key values. ** ** The conflicting row in this case is the database row with the matching ** primary key. ** ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd> ** If foreign key handling is enabled, and applying a changeset leaves the ** database in a state containing foreign key violations, the conflict ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument ** exactly once before the changeset is committed. If the conflict handler ** returns CHANGESET_OMIT, the changes, including those that caused the ** foreign key constraint violation, are committed. Or, if it returns ** CHANGESET_ABORT, the changeset is rolled back. ** ** No current or conflicting row information is provided. The only function ** it is possible to call on the supplied sqlite3_changeset_iter handle ** is sqlite3changeset_fk_conflicts(). ** ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd> ** If any other constraint violation occurs while applying a change (i.e. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is ** invoked with CHANGESET_CONSTRAINT as the second argument. ** ** There is no conflicting row in this case. The results of invoking the ** sqlite3changeset_conflict() API are undefined. ** ** </dl> */ #define SQLITE_CHANGESET_DATA 1 #define SQLITE_CHANGESET_NOTFOUND 2 #define SQLITE_CHANGESET_CONFLICT 3 #define SQLITE_CHANGESET_CONSTRAINT 4 #define SQLITE_CHANGESET_FOREIGN_KEY 5 /* ** CAPI3REF: Constants Returned By The Conflict Handler ** ** A conflict handler callback must return one of the following three values. ** ** <dl> ** <dt>SQLITE_CHANGESET_OMIT<dd> ** If a conflict handler returns this value no special action is taken. The ** change that caused the conflict is not applied. The session module ** continues to the next change in the changeset. ** ** <dt>SQLITE_CHANGESET_REPLACE<dd> ** This value may only be returned if the second argument to the conflict ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this ** is not the case, any changes applied so far are rolled back and the ** call to sqlite3changeset_apply() returns SQLITE_MISUSE. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict ** handler, then the conflicting row is either updated or deleted, depending ** on the type of change. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict ** handler, then the conflicting row is removed from the database and a ** second attempt to apply the change is made. If this second attempt fails, ** the original row is restored to the database before continuing. ** ** <dt>SQLITE_CHANGESET_ABORT<dd> ** If this value is returned, any changes applied so far are rolled back ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. ** </dl> */ #define SQLITE_CHANGESET_OMIT 0 #define SQLITE_CHANGESET_REPLACE 1 #define SQLITE_CHANGESET_ABORT 2 /* ** CAPI3REF: Streaming Versions of API functions. ** ** The six streaming API xxx_strm() functions serve similar purposes to the ** corresponding non-streaming API functions: ** ** <table border=1 style="margin-left:8ex;margin-right:8ex"> ** <tr><th>Streaming function<th>Non-streaming equivalent</th> ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply] ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat] ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert] ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start] ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset] ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset] ** </table> ** ** Non-streaming functions that accept changesets (or patchsets) as input ** require that the entire changeset be stored in a single buffer in memory. ** Similarly, those that return a changeset or patchset do so by returning ** a pointer to a single large buffer allocated using sqlite3_malloc(). ** Normally this is convenient. However, if an application running in a ** low-memory environment is required to handle very large changesets, the ** large contiguous memory allocations required can become onerous. ** ** In order to avoid this problem, instead of a single large buffer, input ** is passed to a streaming API functions by way of a callback function that ** the sessions module invokes to incrementally request input data as it is ** required. In all cases, a pair of API function parameters such as ** ** <pre> ** &nbsp; int nChangeset, ** &nbsp; void *pChangeset, ** </pre> ** ** Is replaced by: ** ** <pre> ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData), ** &nbsp; void *pIn, ** </pre> ** ** Each time the xInput callback is invoked by the sessions module, the first ** argument passed is a copy of the supplied pIn context pointer. The second ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no ** error occurs the xInput method should copy up to (*pnData) bytes of data ** into the buffer and set (*pnData) to the actual number of bytes copied ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) ** should be set to zero to indicate this. Or, if an error occurs, an SQLite ** error code should be returned. In all cases, if an xInput callback returns ** an error, all processing is abandoned and the streaming API function ** returns a copy of the error code to the caller. ** ** In the case of sqlite3changeset_start_strm(), the xInput callback may be ** invoked by the sessions module at any point during the lifetime of the ** iterator. If such an xInput callback returns an error, the iterator enters ** an error state, whereby all subsequent calls to iterator functions ** immediately fail with the same error code as returned by xInput. ** ** Similarly, streaming API functions that return changesets (or patchsets) ** return them in chunks by way of a callback function instead of via a ** pointer to a single large buffer. In this case, a pair of parameters such ** as: ** ** <pre> ** &nbsp; int *pnChangeset, ** &nbsp; void **ppChangeset, ** </pre> ** ** Is replaced by: ** ** <pre> ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData), ** &nbsp; void *pOut ** </pre> ** ** The xOutput callback is invoked zero or more times to return data to ** the application. The first parameter passed to each call is a copy of the ** pOut pointer supplied by the application. The second parameter, pData, ** points to a buffer nData bytes in size containing the chunk of output ** data being returned. If the xOutput callback successfully processes the ** supplied data, it should return SQLITE_OK to indicate success. Otherwise, ** it should return some other SQLite error code. In this case processing ** is immediately abandoned and the streaming API function returns a copy ** of the xOutput error code to the application. ** ** The sessions module never invokes an xOutput callback with the third ** parameter set to a value less than or equal to zero. Other than this, ** no guarantees are made as to the size of the chunks of data returned. */ SQLITE_API int sqlite3changeset_apply_strm( sqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); SQLITE_API int sqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), void *pInB, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); SQLITE_API int sqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); SQLITE_API int sqlite3changeset_start_strm( sqlite3_changeset_iter **pp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); SQLITE_API int sqlite3session_changeset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); SQLITE_API int sqlite3session_patchset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); int sqlite3changegroup_add_strm(sqlite3_changegroup*, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); int sqlite3changegroup_output_strm(sqlite3_changegroup*, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); /* ** Make sure we can call this stuff from C++. */ #if 0 } #endif #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */ /******** End of sqlite3session.h *********/ /******** Begin file fts5.h *********/ /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Interfaces to extend FTS5. Using the interfaces defined in this file, ** FTS5 may be extended with: ** ** * custom tokenizers, and ** * custom auxiliary functions. */ #ifndef _FTS5_H #define _FTS5_H #if 0 extern "C" { #endif /************************************************************************* ** CUSTOM AUXILIARY FUNCTIONS ** ** Virtual table implementations may overload SQL functions by implementing ** the sqlite3_module.xFindFunction() method. */ typedef struct Fts5ExtensionApi Fts5ExtensionApi; typedef struct Fts5Context Fts5Context; typedef struct Fts5PhraseIter Fts5PhraseIter; typedef void (*fts5_extension_function)( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ sqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ sqlite3_value **apVal /* Array of trailing arguments */ ); struct Fts5PhraseIter { const unsigned char *a; const unsigned char *b; }; /* ** EXTENSION API FUNCTIONS ** ** xUserData(pFts): ** Return a copy of the context pointer the extension function was ** registered with. ** ** xColumnTotalSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the FTS5 table. Or, if iCol is ** non-negative but less than the number of columns in the table, return ** the total number of tokens in column iCol, considering all rows in ** the FTS5 table. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** xColumnCount(pFts): ** Return the number of columns in the table. ** ** xColumnSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the current row. Or, if iCol is ** non-negative but less than the number of columns in the table, set ** *pnToken to the number of tokens in column iCol of the current row. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** This function may be quite inefficient if used with an FTS5 table ** created with the "columnsize=0" option. ** ** xColumnText: ** This function attempts to retrieve the text of column iCol of the ** current document. If successful, (*pz) is set to point to a buffer ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise, ** if an error occurs, an SQLite error code is returned and the final values ** of (*pz) and (*pn) are undefined. ** ** xPhraseCount: ** Returns the number of phrases in the current query expression. ** ** xPhraseSize: ** Returns the number of tokens in phrase iPhrase of the query. Phrases ** are numbered starting from zero. ** ** xInstCount: ** Set *pnInst to the total number of occurrences of all phrases within ** the query within the current row. Return SQLITE_OK if successful, or ** an error code (i.e. SQLITE_NOMEM) if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always returns 0. ** ** xInst: ** Query for the details of phrase match iIdx within the current row. ** Phrase matches are numbered starting from zero, so the iIdx argument ** should be greater than or equal to zero and smaller than the value ** output by xInstCount(). ** ** Usually, output parameter *piPhrase is set to the phrase number, *piCol ** to the column in which it occurs and *piOff the token offset of the ** first token of the phrase. The exception is if the table was created ** with the offsets=0 option specified. In this case *piOff is always ** set to -1. ** ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) ** if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. ** ** xRowid: ** Returns the rowid of the current row. ** ** xTokenize: ** Tokenize text using the tokenizer belonging to the FTS5 table. ** ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback): ** This API function is used to query the FTS table for phrase iPhrase ** of the current query. Specifically, a query equivalent to: ** ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid ** ** with $p set to a phrase equivalent to the phrase iPhrase of the ** current query is executed. Any column filter that applies to ** phrase iPhrase of the current query is included in $p. For each ** row visited, the callback function passed as the fourth argument ** is invoked. The context and API objects passed to the callback ** function may be used to access the properties of each matched row. ** Invoking Api.xUserData() returns a copy of the pointer passed as ** the third argument to pUserData. ** ** If the callback function returns any value other than SQLITE_OK, the ** query is abandoned and the xQueryPhrase function returns immediately. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK. ** Otherwise, the error code is propagated upwards. ** ** If the query runs to completion without incident, SQLITE_OK is returned. ** Or, if some error occurs before the query completes or is aborted by ** the callback, an SQLite error code is returned. ** ** ** xSetAuxdata(pFts5, pAux, xDelete) ** ** Save the pointer passed as the second argument as the extension functions ** "auxiliary data". The pointer may then be retrieved by the current or any ** future invocation of the same fts5 extension function made as part of ** of the same MATCH query using the xGetAuxdata() API. ** ** Each extension function is allocated a single auxiliary data slot for ** each FTS query (MATCH expression). If the extension function is invoked ** more than once for a single FTS query, then all invocations share a ** single auxiliary data context. ** ** If there is already an auxiliary data pointer when this function is ** invoked, then it is replaced by the new pointer. If an xDelete callback ** was specified along with the original pointer, it is invoked at this ** point. ** ** The xDelete callback, if one is specified, is also invoked on the ** auxiliary data pointer after the FTS5 query has finished. ** ** If an error (e.g. an OOM condition) occurs within this function, an ** the auxiliary data is set to NULL and an error code returned. If the ** xDelete parameter was not NULL, it is invoked on the auxiliary data ** pointer before returning. ** ** ** xGetAuxdata(pFts5, bClear) ** ** Returns the current auxiliary data pointer for the fts5 extension ** function. See the xSetAuxdata() method for details. ** ** If the bClear argument is non-zero, then the auxiliary data is cleared ** (set to NULL) before this function returns. In this case the xDelete, ** if any, is not invoked. ** ** ** xRowCount(pFts5, pnRow) ** ** This function is used to retrieve the total number of rows in the table. ** In other words, the same value that would be returned by: ** ** SELECT count(*) FROM ftstable; ** ** xPhraseFirst() ** This function is used, along with type Fts5PhraseIter and the xPhraseNext ** method, to iterate through all instances of a single query phrase within ** the current row. This is the same information as is accessible via the ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient ** to use, this API may be faster under some circumstances. To iterate ** through instances of phrase iPhrase, use the following code: ** ** Fts5PhraseIter iter; ** int iCol, iOff; ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff); ** iCol>=0; ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff) ** ){ ** // An instance of phrase iPhrase at offset iOff of column iCol ** } ** ** The Fts5PhraseIter structure is defined above. Applications should not ** modify this structure directly - it should only be used as shown above ** with the xPhraseFirst() and xPhraseNext() API methods (and by ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below). ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always iterates ** through an empty set (all calls to xPhraseFirst() set iCol to -1). ** ** xPhraseNext() ** See xPhraseFirst above. ** ** xPhraseFirstColumn() ** This function and xPhraseNextColumn() are similar to the xPhraseFirst() ** and xPhraseNext() APIs described above. The difference is that instead ** of iterating through all instances of a phrase in the current row, these ** APIs are used to iterate through the set of columns in the current row ** that contain one or more instances of a specified phrase. For example: ** ** Fts5PhraseIter iter; ** int iCol; ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol); ** iCol>=0; ** pApi->xPhraseNextColumn(pFts, &iter, &iCol) ** ){ ** // Column iCol contains at least one instance of phrase iPhrase ** } ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" option. If the FTS5 table is created with either ** "detail=none" "content=" option (i.e. if it is a contentless table), ** then this API always iterates through an empty set (all calls to ** xPhraseFirstColumn() set iCol to -1). ** ** The information accessed using this API and its companion ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext ** (or xInst/xInstCount). The chief advantage of this API is that it is ** significantly more efficient than those alternatives when used with ** "detail=column" tables. ** ** xPhraseNextColumn() ** See xPhraseFirstColumn above. */ struct Fts5ExtensionApi { int iVersion; /* Currently always set to 3 */ void *(*xUserData)(Fts5Context*); int (*xColumnCount)(Fts5Context*); int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); int (*xTokenize)(Fts5Context*, const char *pText, int nText, /* Text to tokenize */ void *pCtx, /* Context passed to xToken() */ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ); int (*xPhraseCount)(Fts5Context*); int (*xPhraseSize)(Fts5Context*, int iPhrase); int (*xInstCount)(Fts5Context*, int *pnInst); int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); sqlite3_int64 (*xRowid)(Fts5Context*); int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData, int(*)(const Fts5ExtensionApi*,Fts5Context*,void*) ); int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*)); void *(*xGetAuxdata)(Fts5Context*, int bClear); int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*); void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff); int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*); void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol); }; /* ** CUSTOM AUXILIARY FUNCTIONS *************************************************************************/ /************************************************************************* ** CUSTOM TOKENIZERS ** ** Applications may also register custom tokenizer types. A tokenizer ** is registered by providing fts5 with a populated instance of the ** following structure. All structure methods must be defined, setting ** any member of the fts5_tokenizer struct to NULL leads to undefined ** behaviour. The structure methods are expected to function as follows: ** ** xCreate: ** This function is used to allocate and initialize a tokenizer instance. ** A tokenizer instance is required to actually tokenize text. ** ** The first argument passed to this function is a copy of the (void*) ** pointer provided by the application when the fts5_tokenizer object ** was registered with FTS5 (the third argument to xCreateTokenizer()). ** The second and third arguments are an array of nul-terminated strings ** containing the tokenizer arguments, if any, specified following the ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used ** to create the FTS5 table. ** ** The final argument is an output variable. If successful, (*ppOut) ** should be set to point to the new tokenizer handle and SQLITE_OK ** returned. If an error occurs, some value other than SQLITE_OK should ** be returned. In this case, fts5 assumes that the final value of *ppOut ** is undefined. ** ** xDelete: ** This function is invoked to delete a tokenizer handle previously ** allocated using xCreate(). Fts5 guarantees that this function will ** be invoked exactly once for each successful call to xCreate(). ** ** xTokenize: ** This function is expected to tokenize the nText byte string indicated ** by argument pText. pText may or may not be nul-terminated. The first ** argument passed to this function is a pointer to an Fts5Tokenizer object ** returned by an earlier call to xCreate(). ** ** The second argument indicates the reason that FTS5 is requesting ** tokenization of the supplied text. This is always one of the following ** four values: ** ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into ** or removed from the FTS table. The tokenizer is being invoked to ** determine the set of tokens to add to (or delete from) the ** FTS index. ** ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed ** against the FTS index. The tokenizer is being called to tokenize ** a bareword or quoted string specified as part of the query. ** ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is ** followed by a "*" character, indicating that the last token ** returned by the tokenizer will be treated as a token prefix. ** ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to ** satisfy an fts5_api.xTokenize() request made by an auxiliary ** function. Or an fts5_api.xColumnSize() request made by the same ** on a columnsize=0 database. ** </ul> ** ** For each token in the input string, the supplied callback xToken() must ** be invoked. The first argument to it should be a copy of the pointer ** passed as the second argument to xTokenize(). The third and fourth ** arguments are a pointer to a buffer containing the token text, and the ** size of the token in bytes. The 4th and 5th arguments are the byte offsets ** of the first byte of and first byte immediately following the text from ** which the token is derived within the input. ** ** The second argument passed to the xToken() callback ("tflags") should ** normally be set to 0. The exception is if the tokenizer supports ** synonyms. In this case see the discussion below for details. ** ** FTS5 assumes the xToken() callback is invoked for each token in the ** order that they occur within the input text. ** ** If an xToken() callback returns any value other than SQLITE_OK, then ** the tokenization should be abandoned and the xTokenize() method should ** immediately return a copy of the xToken() return value. Or, if the ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally, ** if an error occurs with the xTokenize() implementation itself, it ** may abandon the tokenization and return any error code other than ** SQLITE_OK or SQLITE_DONE. ** ** SYNONYM SUPPORT ** ** Custom tokenizers may also support synonyms. Consider a case in which a ** user wishes to query for a phrase such as "first place". Using the ** built-in tokenizers, the FTS5 query 'first + place' will match instances ** of "first place" within the document set, but not alternative forms ** such as "1st place". In some applications, it would be better to match ** all instances of "first place" or "1st place" regardless of which form ** the user specified in the MATCH query text. ** ** There are several ways to approach this in FTS5: ** ** <ol><li> By mapping all synonyms to a single token. In this case, the ** In the above example, this means that the tokenizer returns the ** same token for inputs "first" and "1st". Say that token is in ** fact "first", so that when the user inserts the document "I won ** 1st place" entries are added to the index for tokens "i", "won", ** "first" and "place". If the user then queries for '1st + place', ** the tokenizer substitutes "first" for "1st" and the query works ** as expected. ** ** <li> By adding multiple synonyms for a single term to the FTS index. ** In this case, when tokenizing query text, the tokenizer may ** provide multiple synonyms for a single term within the document. ** FTS5 then queries the index for each synonym individually. For ** example, faced with the query: ** ** <codeblock> ** ... MATCH 'first place'</codeblock> ** ** the tokenizer offers both "1st" and "first" as synonyms for the ** first token in the MATCH query and FTS5 effectively runs a query ** similar to: ** ** <codeblock> ** ... MATCH '(first OR 1st) place'</codeblock> ** ** except that, for the purposes of auxiliary functions, the query ** still appears to contain just two phrases - "(first OR 1st)" ** being treated as a single phrase. ** ** <li> By adding multiple synonyms for a single term to the FTS index. ** Using this method, when tokenizing document text, the tokenizer ** provides multiple synonyms for each token. So that when a ** document such as "I won first place" is tokenized, entries are ** added to the FTS index for "i", "won", "first", "1st" and ** "place". ** ** This way, even if the tokenizer does not provide synonyms ** when tokenizing query text (it should not - to do would be ** inefficient), it doesn't matter if the user queries for ** 'first + place' or '1st + place', as there are entires in the ** FTS index corresponding to both forms of the first token. ** </ol> ** ** Whether it is parsing document or query text, any call to xToken that ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit ** is considered to supply a synonym for the previous token. For example, ** when parsing the document "I won first place", a tokenizer that supports ** synonyms would call xToken() 5 times, as follows: ** ** <codeblock> ** xToken(pCtx, 0, "i", 1, 0, 1); ** xToken(pCtx, 0, "won", 3, 2, 5); ** xToken(pCtx, 0, "first", 5, 6, 11); ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11); ** xToken(pCtx, 0, "place", 5, 12, 17); **</codeblock> ** ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time ** xToken() is called. Multiple synonyms may be specified for a single token ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. ** There is no limit to the number of synonyms that may be provided for a ** single token. ** ** In many cases, method (1) above is the best approach. It does not add ** extra data to the FTS index or require FTS5 to query for multiple terms, ** so it is efficient in terms of disk space and query speed. However, it ** does not support prefix queries very well. If, as suggested above, the ** token "first" is subsituted for "1st" by the tokenizer, then the query: ** ** <codeblock> ** ... MATCH '1s*'</codeblock> ** ** will not match documents that contain the token "1st" (as the tokenizer ** will probably not map "1s" to any prefix of "first"). ** ** For full prefix support, method (3) may be preferred. In this case, ** because the index contains entries for both "first" and "1st", prefix ** queries such as 'fi*' or '1s*' will match correctly. However, because ** extra entries are added to the FTS index, this method uses more space ** within the database. ** ** Method (2) offers a midpoint between (1) and (3). Using this method, ** a query such as '1s*' will match documents that contain the literal ** token "1st", but not "first" (assuming the tokenizer is not able to ** provide synonyms for prefixes). However, a non-prefix query like '1st' ** will match against "1st" and "first". This method does not require ** extra disk space, as no extra entries are added to the FTS index. ** On the other hand, it may require more CPU cycles to run MATCH queries, ** as separate queries of the FTS index are required for each synonym. ** ** When using methods (2) or (3), it is important that the tokenizer only ** provide synonyms when tokenizing document text (method (2)) or query ** text (method (3)), not both. Doing so will not cause any errors, but is ** inefficient. */ typedef struct Fts5Tokenizer Fts5Tokenizer; typedef struct fts5_tokenizer fts5_tokenizer; struct fts5_tokenizer { int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); void (*xDelete)(Fts5Tokenizer*); int (*xTokenize)(Fts5Tokenizer*, void *pCtx, int flags, /* Mask of FTS5_TOKENIZE_* flags */ const char *pText, int nText, int (*xToken)( void *pCtx, /* Copy of 2nd argument to xTokenize() */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Pointer to buffer containing token */ int nToken, /* Size of token in bytes */ int iStart, /* Byte offset of token within input text */ int iEnd /* Byte offset of end of token within input text */ ) ); }; /* Flags that may be passed as the third argument to xTokenize() */ #define FTS5_TOKENIZE_QUERY 0x0001 #define FTS5_TOKENIZE_PREFIX 0x0002 #define FTS5_TOKENIZE_DOCUMENT 0x0004 #define FTS5_TOKENIZE_AUX 0x0008 /* Flags that may be passed by the tokenizer implementation back to FTS5 ** as the third argument to the supplied xToken callback. */ #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */ /* ** END OF CUSTOM TOKENIZERS *************************************************************************/ /************************************************************************* ** FTS5 EXTENSION REGISTRATION API */ typedef struct fts5_api fts5_api; struct fts5_api { int iVersion; /* Currently always set to 2 */ /* Create a new tokenizer */ int (*xCreateTokenizer)( fts5_api *pApi, const char *zName, void *pContext, fts5_tokenizer *pTokenizer, void (*xDestroy)(void*) ); /* Find an existing tokenizer */ int (*xFindTokenizer)( fts5_api *pApi, const char *zName, void **ppContext, fts5_tokenizer *pTokenizer ); /* Create a new auxiliary function */ int (*xCreateFunction)( fts5_api *pApi, const char *zName, void *pContext, fts5_extension_function xFunction, void (*xDestroy)(void*) ); }; /* ** END OF REGISTRATION API *************************************************************************/ #if 0 } /* end of the 'extern "C"' block */ #endif #endif /* _FTS5_H */ /******** End of fts5.h *********/ /************** End of sqlite3.h *********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* ** Include the configuration header output by 'configure' if we're using the ** autoconf-based build */ #ifdef _HAVE_SQLITE_CONFIG_H #include "config.h" #endif /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ /************** Begin file sqliteLimit.h *************************************/ /* ** 2007 May 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file defines various limits of what SQLite can process. */ /* ** The maximum length of a TEXT or BLOB in bytes. This also ** limits the size of a row in a table or index. ** ** The hard limit is the ability of a 32-bit signed integer ** to count the size: 2^31-1 or 2147483647. */ #ifndef SQLITE_MAX_LENGTH # define SQLITE_MAX_LENGTH 1000000000 #endif /* ** This is the maximum number of ** ** * Columns in a table ** * Columns in an index ** * Columns in a view ** * Terms in the SET clause of an UPDATE statement ** * Terms in the result set of a SELECT statement ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. ** * Terms in the VALUES clause of an INSERT statement ** ** The hard upper limit here is 32676. Most database people will ** tell you that in a well-normalized database, you usually should ** not have more than a dozen or so columns in any table. And if ** that is the case, there is no point in having more than a few ** dozen values in any of the other situations described above. */ #ifndef SQLITE_MAX_COLUMN # define SQLITE_MAX_COLUMN 2000 #endif /* ** The maximum length of a single SQL statement in bytes. ** ** It used to be the case that setting this value to zero would ** turn the limit off. That is no longer true. It is not possible ** to turn this limit off. */ #ifndef SQLITE_MAX_SQL_LENGTH # define SQLITE_MAX_SQL_LENGTH 1000000000 #endif /* ** The maximum depth of an expression tree. This is limited to ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might ** want to place more severe limits on the complexity of an ** expression. ** ** A value of 0 used to mean that the limit was not enforced. ** But that is no longer true. The limit is now strictly enforced ** at all times. */ #ifndef SQLITE_MAX_EXPR_DEPTH # define SQLITE_MAX_EXPR_DEPTH 1000 #endif /* ** The maximum number of terms in a compound SELECT statement. ** The code generator for compound SELECT statements does one ** level of recursion for each term. A stack overflow can result ** if the number of terms is too large. In practice, most SQL ** never has more than 3 or 4 terms. Use a value of 0 to disable ** any limit on the number of terms in a compount SELECT. */ #ifndef SQLITE_MAX_COMPOUND_SELECT # define SQLITE_MAX_COMPOUND_SELECT 500 #endif /* ** The maximum number of opcodes in a VDBE program. ** Not currently enforced. */ #ifndef SQLITE_MAX_VDBE_OP # define SQLITE_MAX_VDBE_OP 25000 #endif /* ** The maximum number of arguments to an SQL function. */ #ifndef SQLITE_MAX_FUNCTION_ARG # define SQLITE_MAX_FUNCTION_ARG 127 #endif /* ** The suggested maximum number of in-memory pages to use for ** the main database table and for temporary tables. ** ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000, ** which means the cache size is limited to 2048000 bytes of memory. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options. */ #ifndef SQLITE_DEFAULT_CACHE_SIZE # define SQLITE_DEFAULT_CACHE_SIZE -2000 #endif /* ** The default number of frames to accumulate in the log file before ** checkpointing the database in WAL mode. */ #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 #endif /* ** The maximum number of attached databases. This must be between 0 ** and 125. The upper bound of 125 is because the attached databases are ** counted using a signed 8-bit integer which has a maximum value of 127 ** and we have to allow 2 extra counts for the "main" and "temp" databases. */ #ifndef SQLITE_MAX_ATTACHED # define SQLITE_MAX_ATTACHED 10 #endif /* ** The maximum value of a ?nnn wildcard that the parser will accept. */ #ifndef SQLITE_MAX_VARIABLE_NUMBER # define SQLITE_MAX_VARIABLE_NUMBER 999 #endif /* Maximum page size. The upper bound on this value is 65536. This a limit ** imposed by the use of 16-bit offsets within each page. ** ** Earlier versions of SQLite allowed the user to change this value at ** compile time. This is no longer permitted, on the grounds that it creates ** a library that is technically incompatible with an SQLite library ** compiled with a different limit. If a process operating on a database ** with a page-size of 65536 bytes crashes, then an instance of SQLite ** compiled with the default page-size limit will not be able to rollback ** the aborted transaction. This could lead to database corruption. */ #ifdef SQLITE_MAX_PAGE_SIZE # undef SQLITE_MAX_PAGE_SIZE #endif #define SQLITE_MAX_PAGE_SIZE 65536 /* ** The default size of a database page. */ #ifndef SQLITE_DEFAULT_PAGE_SIZE # define SQLITE_DEFAULT_PAGE_SIZE 4096 #endif #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE # undef SQLITE_DEFAULT_PAGE_SIZE # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE #endif /* ** Ordinarily, if no value is explicitly provided, SQLite creates databases ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain ** device characteristics (sector-size and atomic write() support), ** SQLite may choose a larger value. This constant is the maximum value ** SQLite will choose on its own. */ #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 #endif #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE # undef SQLITE_MAX_DEFAULT_PAGE_SIZE # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE #endif /* ** Maximum number of pages in one database file. ** ** This is really just the default value for the max_page_count pragma. ** This value can be lowered (or raised) at run-time using that the ** max_page_count macro. */ #ifndef SQLITE_MAX_PAGE_COUNT # define SQLITE_MAX_PAGE_COUNT 1073741823 #endif /* ** Maximum length (in bytes) of the pattern in a LIKE or GLOB ** operator. */ #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 #endif /* ** Maximum depth of recursion for triggers. ** ** A value of 1 means that a trigger program will not be able to itself ** fire any triggers. A value of 0 means that no trigger programs at all ** may be executed. */ #ifndef SQLITE_MAX_TRIGGER_DEPTH # define SQLITE_MAX_TRIGGER_DEPTH 1000 #endif /************** End of sqliteLimit.h *****************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* Disable nuisance warnings on Borland compilers */ #if defined(__BORLANDC__) #pragma warn -rch /* unreachable code */ #pragma warn -ccc /* Condition is always true or false */ #pragma warn -aus /* Assigned value is never used */ #pragma warn -csu /* Comparing signed and unsigned */ #pragma warn -spa /* Suspicious pointer arithmetic */ #endif /* ** Include standard header files as necessary */ #ifdef HAVE_STDINT_H #include <stdint.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif /* ** The following macros are used to cast pointers to integers and ** integers to pointers. The way you do this varies from one compiler ** to the next, so we have developed the following set of #if statements ** to generate appropriate macros for a wide range of compilers. ** ** The correct "ANSI" way to do this is to use the intptr_t type. ** Unfortunately, that typedef is not available on all compilers, or ** if it is available, it requires an #include of specific headers ** that vary from one machine to the next. ** ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). ** So we have to define the macros in different ways depending on the ** compiler. */ #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) #elif !defined(__GNUC__) /* Works for compilers other than LLVM */ # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) #else /* Generates a warning - but it always works */ # define SQLITE_INT_TO_PTR(X) ((void*)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(X)) #endif /* ** A macro to hint to the compiler that a function should not be ** inlined. */ #if defined(__GNUC__) # define SQLITE_NOINLINE __attribute__((noinline)) #elif defined(_MSC_VER) && _MSC_VER>=1310 # define SQLITE_NOINLINE __declspec(noinline) #else # define SQLITE_NOINLINE #endif /* ** Make sure that the compiler intrinsics we desire are enabled when ** compiling with an appropriate version of MSVC unless prevented by ** the SQLITE_DISABLE_INTRINSIC define. */ #if !defined(SQLITE_DISABLE_INTRINSIC) # if defined(_MSC_VER) && _MSC_VER>=1400 # if !defined(_WIN32_WCE) # include <intrin.h> # pragma intrinsic(_byteswap_ushort) # pragma intrinsic(_byteswap_ulong) # pragma intrinsic(_byteswap_uint64) # pragma intrinsic(_ReadWriteBarrier) # else # include <cmnintrin.h> # endif # endif #endif /* ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. ** 0 means mutexes are permanently disable and the library is never ** threadsafe. 1 means the library is serialized which is the highest ** level of threadsafety. 2 means the library is multithreaded - multiple ** threads can use SQLite as long as no two threads try to use the same ** database connection at the same time. ** ** Older versions of SQLite used an optional THREADSAFE macro. ** We support that for legacy. */ #if !defined(SQLITE_THREADSAFE) # if defined(THREADSAFE) # define SQLITE_THREADSAFE THREADSAFE # else # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ # endif #endif /* ** Powersafe overwrite is on by default. But can be turned off using ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option. */ #ifndef SQLITE_POWERSAFE_OVERWRITE # define SQLITE_POWERSAFE_OVERWRITE 1 #endif /* ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in ** which case memory allocation statistics are disabled by default. */ #if !defined(SQLITE_DEFAULT_MEMSTATUS) # define SQLITE_DEFAULT_MEMSTATUS 1 #endif /* ** Exactly one of the following macros must be defined in order to ** specify which memory allocation subsystem to use. ** ** SQLITE_SYSTEM_MALLOC // Use normal system malloc() ** SQLITE_WIN32_MALLOC // Use Win32 native heap API ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails ** SQLITE_MEMDEBUG // Debugging version of system malloc() ** ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the ** assert() macro is enabled, each call into the Win32 native heap subsystem ** will cause HeapValidate to be called. If heap validation should fail, an ** assertion will be triggered. ** ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as ** the default. */ #if defined(SQLITE_SYSTEM_MALLOC) \ + defined(SQLITE_WIN32_MALLOC) \ + defined(SQLITE_ZERO_MALLOC) \ + defined(SQLITE_MEMDEBUG)>1 # error "Two or more of the following compile-time configuration options\ are defined but at most one is allowed:\ SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\ SQLITE_ZERO_MALLOC" #endif #if defined(SQLITE_SYSTEM_MALLOC) \ + defined(SQLITE_WIN32_MALLOC) \ + defined(SQLITE_ZERO_MALLOC) \ + defined(SQLITE_MEMDEBUG)==0 # define SQLITE_SYSTEM_MALLOC 1 #endif /* ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the ** sizes of memory allocations below this value where possible. */ #if !defined(SQLITE_MALLOC_SOFT_LIMIT) # define SQLITE_MALLOC_SOFT_LIMIT 1024 #endif /* ** We need to define _XOPEN_SOURCE as follows in order to enable ** recursive mutexes on most Unix systems and fchmod() on OpenBSD. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit ** it. */ #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) # define _XOPEN_SOURCE 600 #endif /* ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true, ** make it true by defining or undefining NDEBUG. ** ** Setting NDEBUG makes the code smaller and faster by disabling the ** assert() statements in the code. So we want the default action ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out ** feature. */ #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif #if defined(NDEBUG) && defined(SQLITE_DEBUG) # undef NDEBUG #endif /* ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on. */ #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG) # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1 #endif /* ** The testcase() macro is used to aid in coverage testing. When ** doing coverage testing, the condition inside the argument to ** testcase() must be evaluated both true and false in order to ** get full branch coverage. The testcase() macro is inserted ** to help ensure adequate test coverage in places where simple ** condition/decision coverage is inadequate. For example, testcase() ** can be used to make sure boundary values are tested. For ** bitmask tests, testcase() can be used to make sure each bit ** is significant and used at least once. On switch statements ** where multiple cases go to the same block of code, testcase() ** can insure that all cases are evaluated. ** */ #ifdef SQLITE_COVERAGE_TEST SQLITE_PRIVATE void sqlite3Coverage(int); # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } #else # define testcase(X) #endif /* ** The TESTONLY macro is used to enclose variable declarations or ** other bits of code that are needed to support the arguments ** within testcase() and assert() macros. */ #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) # define TESTONLY(X) X #else # define TESTONLY(X) #endif /* ** Sometimes we need a small amount of code such as a variable initialization ** to setup for a later assert() statement. We do not want this code to ** appear when assert() is disabled. The following macro is therefore ** used to contain that setup code. The "VVA" acronym stands for ** "Verification, Validation, and Accreditation". In other words, the ** code within VVA_ONLY() will only run during verification processes. */ #ifndef NDEBUG # define VVA_ONLY(X) X #else # define VVA_ONLY(X) #endif /* ** The ALWAYS and NEVER macros surround boolean expressions which ** are intended to always be true or false, respectively. Such ** expressions could be omitted from the code completely. But they ** are included in a few cases in order to enhance the resilience ** of SQLite to unexpected behavior - to make the code "self-healing" ** or "ductile" rather than being "brittle" and crashing at the first ** hint of unplanned behavior. ** ** In other words, ALWAYS and NEVER are added for defensive code. ** ** When doing coverage testing ALWAYS and NEVER are hard-coded to ** be true and false so that the unreachable code they specify will ** not be counted as untested code. */ #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) # define ALWAYS(X) (1) # define NEVER(X) (0) #elif !defined(NDEBUG) # define ALWAYS(X) ((X)?1:(assert(0),0)) # define NEVER(X) ((X)?(assert(0),1):0) #else # define ALWAYS(X) (X) # define NEVER(X) (X) #endif /* ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is ** defined. We need to defend against those failures when testing with ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches ** during a normal build. The following macro can be used to disable tests ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set. */ #if defined(SQLITE_TEST_REALLOC_STRESS) # define ONLY_IF_REALLOC_STRESS(X) (X) #elif !defined(NDEBUG) # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0) #else # define ONLY_IF_REALLOC_STRESS(X) (0) #endif /* ** Declarations used for tracing the operating system interfaces. */ #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \ (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) extern int sqlite3OSTrace; # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X # define SQLITE_HAVE_OS_TRACE #else # define OSTRACE(X) # undef SQLITE_HAVE_OS_TRACE #endif /* ** Is the sqlite3ErrName() function needed in the build? Currently, ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when ** OSTRACE is enabled), and by several "test*.c" files (which are ** compiled using SQLITE_TEST). */ #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \ (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) # define SQLITE_NEED_ERR_NAME #else # undef SQLITE_NEED_ERR_NAME #endif /* ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_OMIT_EXPLAIN # undef SQLITE_ENABLE_EXPLAIN_COMMENTS #endif /* ** Return true (non-zero) if the input is an integer that is too large ** to fit in 32-bits. This macro is used inside of various testcase() ** macros to verify that we have tested SQLite for large-file support. */ #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) /* ** The macro unlikely() is a hint that surrounds a boolean ** expression that is usually false. Macro likely() surrounds ** a boolean expression that is usually true. These hints could, ** in theory, be used by the compiler to generate better code, but ** currently they are just comments for human readers. */ #define likely(X) (X) #define unlikely(X) (X) /************** Include hash.h in the middle of sqliteInt.h ******************/ /************** Begin file hash.h ********************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for the generic hash-table implementation ** used in SQLite. */ #ifndef SQLITE_HASH_H #define SQLITE_HASH_H /* Forward declarations of structures. */ typedef struct Hash Hash; typedef struct HashElem HashElem; /* A complete hash table is an instance of the following structure. ** The internals of this structure are intended to be opaque -- client ** code should not attempt to access or modify the fields of this structure ** directly. Change this structure only by using the routines below. ** However, some of the "procedures" and "functions" for modifying and ** accessing this structure are really macros, so we can't really make ** this structure opaque. ** ** All elements of the hash table are on a single doubly-linked list. ** Hash.first points to the head of this list. ** ** There are Hash.htsize buckets. Each bucket points to a spot in ** the global doubly-linked list. The contents of the bucket are the ** element pointed to plus the next _ht.count-1 elements in the list. ** ** Hash.htsize and Hash.ht may be zero. In that case lookup is done ** by a linear search of the global list. For small tables, the ** Hash.ht table is never allocated because if there are few elements ** in the table, it is faster to do a linear search than to manage ** the hash table. */ struct Hash { unsigned int htsize; /* Number of buckets in the hash table */ unsigned int count; /* Number of entries in this table */ HashElem *first; /* The first element of the array */ struct _ht { /* the hash table */ int count; /* Number of entries with this hash */ HashElem *chain; /* Pointer to first entry with this hash */ } *ht; }; /* Each element in the hash table is an instance of the following ** structure. All elements are stored on a single doubly-linked list. ** ** Again, this structure is intended to be opaque, but it can't really ** be opaque because it is used by macros. */ struct HashElem { HashElem *next, *prev; /* Next and previous elements in the table */ void *data; /* Data associated with this element */ const char *pKey; /* Key associated with this element */ }; /* ** Access routines. To delete, insert a NULL pointer. */ SQLITE_PRIVATE void sqlite3HashInit(Hash*); SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData); SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey); SQLITE_PRIVATE void sqlite3HashClear(Hash*); /* ** Macros for looping over all elements of a hash table. The idiom is ** like this: ** ** Hash h; ** HashElem *p; ** ... ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ ** SomeStructure *pData = sqliteHashData(p); ** // do something with pData ** } */ #define sqliteHashFirst(H) ((H)->first) #define sqliteHashNext(E) ((E)->next) #define sqliteHashData(E) ((E)->data) /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ /* ** Number of entries in a hash table */ /* #define sqliteHashCount(H) ((H)->count) // NOT USED */ #endif /* SQLITE_HASH_H */ /************** End of hash.h ************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include parse.h in the middle of sqliteInt.h *****************/ /************** Begin file parse.h *******************************************/ #define TK_SEMI 1 #define TK_EXPLAIN 2 #define TK_QUERY 3 #define TK_PLAN 4 #define TK_BEGIN 5 #define TK_TRANSACTION 6 #define TK_DEFERRED 7 #define TK_IMMEDIATE 8 #define TK_EXCLUSIVE 9 #define TK_COMMIT 10 #define TK_END 11 #define TK_ROLLBACK 12 #define TK_SAVEPOINT 13 #define TK_RELEASE 14 #define TK_TO 15 #define TK_TABLE 16 #define TK_CREATE 17 #define TK_IF 18 #define TK_NOT 19 #define TK_EXISTS 20 #define TK_TEMP 21 #define TK_LP 22 #define TK_RP 23 #define TK_AS 24 #define TK_WITHOUT 25 #define TK_COMMA 26 #define TK_OR 27 #define TK_AND 28 #define TK_IS 29 #define TK_MATCH 30 #define TK_LIKE_KW 31 #define TK_BETWEEN 32 #define TK_IN 33 #define TK_ISNULL 34 #define TK_NOTNULL 35 #define TK_NE 36 #define TK_EQ 37 #define TK_GT 38 #define TK_LE 39 #define TK_LT 40 #define TK_GE 41 #define TK_ESCAPE 42 #define TK_BITAND 43 #define TK_BITOR 44 #define TK_LSHIFT 45 #define TK_RSHIFT 46 #define TK_PLUS 47 #define TK_MINUS 48 #define TK_STAR 49 #define TK_SLASH 50 #define TK_REM 51 #define TK_CONCAT 52 #define TK_COLLATE 53 #define TK_BITNOT 54 #define TK_ID 55 #define TK_INDEXED 56 #define TK_ABORT 57 #define TK_ACTION 58 #define TK_AFTER 59 #define TK_ANALYZE 60 #define TK_ASC 61 #define TK_ATTACH 62 #define TK_BEFORE 63 #define TK_BY 64 #define TK_CASCADE 65 #define TK_CAST 66 #define TK_COLUMNKW 67 #define TK_CONFLICT 68 #define TK_DATABASE 69 #define TK_DESC 70 #define TK_DETACH 71 #define TK_EACH 72 #define TK_FAIL 73 #define TK_FOR 74 #define TK_IGNORE 75 #define TK_INITIALLY 76 #define TK_INSTEAD 77 #define TK_NO 78 #define TK_KEY 79 #define TK_OF 80 #define TK_OFFSET 81 #define TK_PRAGMA 82 #define TK_RAISE 83 #define TK_RECURSIVE 84 #define TK_REPLACE 85 #define TK_RESTRICT 86 #define TK_ROW 87 #define TK_TRIGGER 88 #define TK_VACUUM 89 #define TK_VIEW 90 #define TK_VIRTUAL 91 #define TK_WITH 92 #define TK_REINDEX 93 #define TK_RENAME 94 #define TK_CTIME_KW 95 #define TK_ANY 96 #define TK_STRING 97 #define TK_JOIN_KW 98 #define TK_CONSTRAINT 99 #define TK_DEFAULT 100 #define TK_NULL 101 #define TK_PRIMARY 102 #define TK_UNIQUE 103 #define TK_CHECK 104 #define TK_REFERENCES 105 #define TK_AUTOINCR 106 #define TK_ON 107 #define TK_INSERT 108 #define TK_DELETE 109 #define TK_UPDATE 110 #define TK_SET 111 #define TK_DEFERRABLE 112 #define TK_FOREIGN 113 #define TK_DROP 114 #define TK_UNION 115 #define TK_ALL 116 #define TK_EXCEPT 117 #define TK_INTERSECT 118 #define TK_SELECT 119 #define TK_VALUES 120 #define TK_DISTINCT 121 #define TK_DOT 122 #define TK_FROM 123 #define TK_JOIN 124 #define TK_USING 125 #define TK_ORDER 126 #define TK_GROUP 127 #define TK_HAVING 128 #define TK_LIMIT 129 #define TK_WHERE 130 #define TK_INTO 131 #define TK_FLOAT 132 #define TK_BLOB 133 #define TK_INTEGER 134 #define TK_VARIABLE 135 #define TK_CASE 136 #define TK_WHEN 137 #define TK_THEN 138 #define TK_ELSE 139 #define TK_INDEX 140 #define TK_ALTER 141 #define TK_ADD 142 #define TK_TO_TEXT 143 #define TK_TO_BLOB 144 #define TK_TO_NUMERIC 145 #define TK_TO_INT 146 #define TK_TO_REAL 147 #define TK_ISNOT 148 #define TK_END_OF_FILE 149 #define TK_UNCLOSED_STRING 150 #define TK_FUNCTION 151 #define TK_COLUMN 152 #define TK_AGG_FUNCTION 153 #define TK_AGG_COLUMN 154 #define TK_UMINUS 155 #define TK_UPLUS 156 #define TK_REGISTER 157 #define TK_VECTOR 158 #define TK_SELECT_COLUMN 159 #define TK_ASTERISK 160 #define TK_SPAN 161 #define TK_SPACE 162 #define TK_ILLEGAL 163 /* The token codes above must all fit in 8 bits */ #define TKFLG_MASK 0xff /* Flags that can be added to a token code when it is not ** being stored in a u8: */ #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */ /************** End of parse.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stddef.h> /* ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY. ** This allows better measurements of where memcpy() is used when running ** cachegrind. But this macro version of memcpy() is very slow so it ** should not be used in production. This is a performance measurement ** hack only. */ #ifdef SQLITE_INLINE_MEMCPY # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\ int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);} #endif /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite_int64 # define float sqlite_int64 # define LONGDOUBLE_TYPE sqlite_int64 # ifndef SQLITE_BIG_DBL # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) # endif # define SQLITE_OMIT_DATETIME_FUNCS 1 # define SQLITE_OMIT_TRACE 1 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT # undef SQLITE_HAVE_ISNAN #endif #ifndef SQLITE_BIG_DBL # define SQLITE_BIG_DBL (1e99) #endif /* ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 ** afterward. Having this macro allows us to cause the C compiler ** to omit code used by TEMP tables without messy #ifndef statements. */ #ifdef SQLITE_OMIT_TEMPDB #define OMIT_TEMPDB 1 #else #define OMIT_TEMPDB 0 #endif /* ** The "file format" number is an integer that is incremented whenever ** the VDBE-level file format changes. The following macros define the ** the default file format for new databases and the maximum file format ** that the library can read. */ #define SQLITE_MAX_FILE_FORMAT 4 #ifndef SQLITE_DEFAULT_FILE_FORMAT # define SQLITE_DEFAULT_FILE_FORMAT 4 #endif /* ** Determine whether triggers are recursive by default. This can be ** changed at run-time using a pragma. */ #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 #endif /* ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified ** on the command-line */ #ifndef SQLITE_TEMP_STORE # define SQLITE_TEMP_STORE 1 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */ #endif /* ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it ** to zero. */ #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0 # undef SQLITE_MAX_WORKER_THREADS # define SQLITE_MAX_WORKER_THREADS 0 #endif #ifndef SQLITE_MAX_WORKER_THREADS # define SQLITE_MAX_WORKER_THREADS 8 #endif #ifndef SQLITE_DEFAULT_WORKER_THREADS # define SQLITE_DEFAULT_WORKER_THREADS 0 #endif #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS # undef SQLITE_MAX_WORKER_THREADS # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS #endif /* ** The default initial allocation for the pagecache when using separate ** pagecaches for each database connection. A positive number is the ** number of pages. A negative number N translations means that a buffer ** of -1024*N bytes is allocated and used for as many pages as it will hold. ** ** The default value of "20" was choosen to minimize the run-time of the ** speedtest1 test program with options: --shrink-memory --reprepare */ #ifndef SQLITE_DEFAULT_PCACHE_INITSZ # define SQLITE_DEFAULT_PCACHE_INITSZ 20 #endif /* ** GCC does not define the offsetof() macro so we'll have to do it ** ourselves. */ #ifndef offsetof #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) #endif /* ** Macros to compute minimum and maximum of two numbers. */ #ifndef MIN # define MIN(A,B) ((A)<(B)?(A):(B)) #endif #ifndef MAX # define MAX(A,B) ((A)>(B)?(A):(B)) #endif /* ** Swap two objects of type TYPE. */ #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} /* ** Check to see if this machine uses EBCDIC. (Yes, believe it or ** not, there are still machines out there that use EBCDIC.) */ #if 'A' == '\301' # define SQLITE_EBCDIC 1 #else # define SQLITE_ASCII 1 #endif /* ** Integers of known sizes. These typedefs might change for architectures ** where the sizes very. Preprocessor macros are available so that the ** types can be conveniently redefined at compile-type. Like this: ** ** cc '-DUINTPTR_TYPE=long long int' ... */ #ifndef UINT32_TYPE # ifdef HAVE_UINT32_T # define UINT32_TYPE uint32_t # else # define UINT32_TYPE unsigned int # endif #endif #ifndef UINT16_TYPE # ifdef HAVE_UINT16_T # define UINT16_TYPE uint16_t # else # define UINT16_TYPE unsigned short int # endif #endif #ifndef INT16_TYPE # ifdef HAVE_INT16_T # define INT16_TYPE int16_t # else # define INT16_TYPE short int # endif #endif #ifndef UINT8_TYPE # ifdef HAVE_UINT8_T # define UINT8_TYPE uint8_t # else # define UINT8_TYPE unsigned char # endif #endif #ifndef INT8_TYPE # ifdef HAVE_INT8_T # define INT8_TYPE int8_t # else # define INT8_TYPE signed char # endif #endif #ifndef LONGDOUBLE_TYPE # define LONGDOUBLE_TYPE long double #endif typedef sqlite_int64 i64; /* 8-byte signed integer */ typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ typedef INT16_TYPE i16; /* 2-byte signed integer */ typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ typedef INT8_TYPE i8; /* 1-byte signed integer */ /* ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value ** that can be stored in a u32 without loss of data. The value ** is 0x00000000ffffffff. But because of quirks of some compilers, we ** have to specify the value in the less intuitive manner shown: */ #define SQLITE_MAX_U32 ((((u64)1)<<32)-1) /* ** The datatype used to store estimates of the number of rows in a ** table or index. This is an unsigned integer type. For 99.9% of ** the world, a 32-bit integer is sufficient. But a 64-bit integer ** can be used at compile-time if desired. */ #ifdef SQLITE_64BIT_STATS typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */ #else typedef u32 tRowcnt; /* 32-bit is the default */ #endif /* ** Estimated quantities used for query planning are stored as 16-bit ** logarithms. For quantity X, the value stored is 10*log2(X). This ** gives a possible range of values of approximately 1.0e986 to 1e-986. ** But the allowed values are "grainy". Not every value is representable. ** For example, quantities 16 and 17 are both represented by a LogEst ** of 40. However, since LogEst quantities are suppose to be estimates, ** not exact values, this imprecision is not a problem. ** ** "LogEst" is short for "Logarithmic Estimate". ** ** Examples: ** 1 -> 0 20 -> 43 10000 -> 132 ** 2 -> 10 25 -> 46 25000 -> 146 ** 3 -> 16 100 -> 66 1000000 -> 199 ** 4 -> 20 1000 -> 99 1048576 -> 200 ** 10 -> 33 1024 -> 100 4294967296 -> 320 ** ** The LogEst can be negative to indicate fractional values. ** Examples: ** ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40 */ typedef INT16_TYPE LogEst; /* ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer */ #ifndef SQLITE_PTRSIZE # if defined(__SIZEOF_POINTER__) # define SQLITE_PTRSIZE __SIZEOF_POINTER__ # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \ defined(_M_ARM) || defined(__arm__) || defined(__x86) # define SQLITE_PTRSIZE 4 # else # define SQLITE_PTRSIZE 8 # endif #endif /* The uptr type is an unsigned integer large enough to hold a pointer */ #if defined(HAVE_STDINT_H) typedef uintptr_t uptr; #elif SQLITE_PTRSIZE==4 typedef u32 uptr; #else typedef u64 uptr; #endif /* ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to ** something between S (inclusive) and E (exclusive). ** ** In other words, S is a buffer and E is a pointer to the first byte after ** the end of buffer S. This macro returns true if P points to something ** contained within the buffer S. */ #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E))) /* ** Macros to determine whether the machine is big or little endian, ** and whether or not that determination is run-time or compile-time. ** ** For best performance, an attempt is made to guess at the byte-order ** using C-preprocessor macros. If that is unsuccessful, or if ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined ** at run-time. */ #ifndef SQLITE_BYTEORDER # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ defined(__arm__) # define SQLITE_BYTEORDER 1234 # elif defined(sparc) || defined(__ppc__) # define SQLITE_BYTEORDER 4321 # else # define SQLITE_BYTEORDER 0 # endif #endif #if SQLITE_BYTEORDER==4321 # define SQLITE_BIGENDIAN 1 # define SQLITE_LITTLEENDIAN 0 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE #elif SQLITE_BYTEORDER==1234 # define SQLITE_BIGENDIAN 0 # define SQLITE_LITTLEENDIAN 1 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE #else # ifdef SQLITE_AMALGAMATION const int sqlite3one = 1; # else extern const int sqlite3one; # endif # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) #endif /* ** Constants for the largest and smallest possible 64-bit signed integers. ** These macros are designed to work correctly on both 32-bit and 64-bit ** compilers. */ #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) /* ** Round up a number to the next larger multiple of 8. This is used ** to force 8-byte alignment on 64-bit architectures. */ #define ROUND8(x) (((x)+7)&~7) /* ** Round down to the nearest multiple of 8 */ #define ROUNDDOWN8(x) ((x)&~7) /* ** Assert that the pointer X is aligned to an 8-byte boundary. This ** macro is used only within assert() to verify that the code gets ** all alignment restrictions correct. ** ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the ** underlying malloc() implementation might return us 4-byte aligned ** pointers. In that case, only verify 4-byte alignment. */ #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) #else # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) #endif /* ** Disable MMAP on platforms where it is known to not work */ #if defined(__OpenBSD__) || defined(__QNXNTO__) # undef SQLITE_MAX_MMAP_SIZE # define SQLITE_MAX_MMAP_SIZE 0 #endif /* ** Default maximum size of memory used by memory-mapped I/O in the VFS */ #ifdef __APPLE__ # include <TargetConditionals.h> #endif #ifndef SQLITE_MAX_MMAP_SIZE # if defined(__linux__) \ || defined(_WIN32) \ || (defined(__APPLE__) && defined(__MACH__)) \ || defined(__sun) \ || defined(__FreeBSD__) \ || defined(__DragonFly__) # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */ # else # define SQLITE_MAX_MMAP_SIZE 0 # endif # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */ #endif /* ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger ** default MMAP_SIZE is specified at compile-time, make sure that it does ** not exceed the maximum mmap size. */ #ifndef SQLITE_DEFAULT_MMAP_SIZE # define SQLITE_DEFAULT_MMAP_SIZE 0 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */ #endif #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE # undef SQLITE_DEFAULT_MMAP_SIZE # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE #endif /* ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also ** define SQLITE_ENABLE_STAT3_OR_STAT4 */ #ifdef SQLITE_ENABLE_STAT4 # undef SQLITE_ENABLE_STAT3 # define SQLITE_ENABLE_STAT3_OR_STAT4 1 #elif SQLITE_ENABLE_STAT3 # define SQLITE_ENABLE_STAT3_OR_STAT4 1 #elif SQLITE_ENABLE_STAT3_OR_STAT4 # undef SQLITE_ENABLE_STAT3_OR_STAT4 #endif /* ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not ** the Select query generator tracing logic is turned on. */ #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE) # define SELECTTRACE_ENABLED 1 #else # define SELECTTRACE_ENABLED 0 #endif /* ** An instance of the following structure is used to store the busy-handler ** callback for a given sqlite handle. ** ** The sqlite.busyHandler member of the sqlite struct contains the busy ** callback for the database handle. Each pager opened via the sqlite ** handle is passed a pointer to sqlite.busyHandler. The busy-handler ** callback is currently invoked only from within pager.c. */ typedef struct BusyHandler BusyHandler; struct BusyHandler { int (*xFunc)(void *,int); /* The busy callback */ void *pArg; /* First arg to busy callback */ int nBusy; /* Incremented with each busy call */ }; /* ** Name of the master database table. The master database table ** is a special table that holds the names and attributes of all ** user tables and indices. */ #define MASTER_NAME "sqlite_master" #define TEMP_MASTER_NAME "sqlite_temp_master" /* ** The root-page of the master database table. */ #define MASTER_ROOT 1 /* ** The name of the schema table. */ #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) /* ** A convenience macro that returns the number of elements in ** an array. */ #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) /* ** Determine if the argument is a power of two */ #define IsPowerOfTwo(X) (((X)&((X)-1))==0) /* ** The following value as a destructor means to use sqlite3DbFree(). ** The sqlite3DbFree() routine requires two parameters instead of the ** one parameter that destructors normally want. So we have to introduce ** this magic value that the code knows to handle differently. Any ** pointer will work here as long as it is distinct from SQLITE_STATIC ** and SQLITE_TRANSIENT. */ #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize) /* ** When SQLITE_OMIT_WSD is defined, it means that the target platform does ** not support Writable Static Data (WSD) such as global and static variables. ** All variables must either be on the stack or dynamically allocated from ** the heap. When WSD is unsupported, the variable declarations scattered ** throughout the SQLite code must become constants instead. The SQLITE_WSD ** macro is used for this purpose. And instead of referencing the variable ** directly, we use its constant as a key to lookup the run-time allocated ** buffer that holds real variable. The constant is also the initializer ** for the run-time allocated buffer. ** ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL ** macros become no-ops and have zero performance impact. */ #ifdef SQLITE_OMIT_WSD #define SQLITE_WSD const #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) SQLITE_API int sqlite3_wsd_init(int N, int J); SQLITE_API void *sqlite3_wsd_find(void *K, int L); #else #define SQLITE_WSD #define GLOBAL(t,v) v #define sqlite3GlobalConfig sqlite3Config #endif /* ** The following macros are used to suppress compiler warnings and to ** make it clear to human readers when a function parameter is deliberately ** left unused within the body of a function. This usually happens when ** a function is called via a function pointer. For example the ** implementation of an SQL aggregate step callback may not use the ** parameter indicating the number of arguments passed to the aggregate, ** if it knows that this is enforced elsewhere. ** ** When a function parameter is not used at all within the body of a function, ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. ** However, these macros may also be used to suppress warnings related to ** parameters that may or may not be used depending on compilation options. ** For example those parameters only used in assert() statements. In these ** cases the parameters are named as per the usual conventions. */ #define UNUSED_PARAMETER(x) (void)(x) #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) /* ** Forward references to structures */ typedef struct AggInfo AggInfo; typedef struct AuthContext AuthContext; typedef struct AutoincInfo AutoincInfo; typedef struct Bitvec Bitvec; typedef struct CollSeq CollSeq; typedef struct Column Column; typedef struct Db Db; typedef struct Schema Schema; typedef struct Expr Expr; typedef struct ExprList ExprList; typedef struct ExprSpan ExprSpan; typedef struct FKey FKey; typedef struct FuncDestructor FuncDestructor; typedef struct FuncDef FuncDef; typedef struct FuncDefHash FuncDefHash; typedef struct IdList IdList; typedef struct Index Index; typedef struct IndexSample IndexSample; typedef struct KeyClass KeyClass; typedef struct KeyInfo KeyInfo; typedef struct Lookaside Lookaside; typedef struct LookasideSlot LookasideSlot; typedef struct Module Module; typedef struct NameContext NameContext; typedef struct Parse Parse; typedef struct PreUpdate PreUpdate; typedef struct PrintfArguments PrintfArguments; typedef struct RowSet RowSet; typedef struct Savepoint Savepoint; typedef struct Select Select; typedef struct SQLiteThread SQLiteThread; typedef struct SelectDest SelectDest; typedef struct SrcList SrcList; typedef struct StrAccum StrAccum; typedef struct Table Table; typedef struct TableLock TableLock; typedef struct Token Token; typedef struct TreeView TreeView; typedef struct Trigger Trigger; typedef struct TriggerPrg TriggerPrg; typedef struct TriggerStep TriggerStep; typedef struct UnpackedRecord UnpackedRecord; typedef struct VTable VTable; typedef struct VtabCtx VtabCtx; typedef struct Walker Walker; typedef struct WhereInfo WhereInfo; typedef struct With With; /* A VList object records a mapping between parameters/variables/wildcards ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer ** variable number associated with that parameter. See the format description ** on the sqlite3VListAdd() routine for more information. A VList is really ** just an array of integers. */ typedef int VList; /* ** Defer sourcing vdbe.h and btree.h until after the "u8" and ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque ** pointer types (i.e. FuncDef) defined above. */ /************** Include btree.h in the middle of sqliteInt.h *****************/ /************** Begin file btree.h *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite B-Tree file ** subsystem. See comments in the source code for a detailed description ** of what each interface routine does. */ #ifndef SQLITE_BTREE_H #define SQLITE_BTREE_H /* TODO: This definition is just included so other modules compile. It ** needs to be revisited. */ #define SQLITE_N_BTREE_META 16 /* ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise ** it must be turned on for each database using "PRAGMA auto_vacuum = 1". */ #ifndef SQLITE_DEFAULT_AUTOVACUUM #define SQLITE_DEFAULT_AUTOVACUUM 0 #endif #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ /* ** Forward declarations of structure */ typedef struct Btree Btree; typedef struct BtCursor BtCursor; typedef struct BtShared BtShared; typedef struct BtreePayload BtreePayload; SQLITE_PRIVATE int sqlite3BtreeOpen( sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ const char *zFilename, /* Name of database file to open */ sqlite3 *db, /* Associated database connection */ Btree **ppBtree, /* Return open Btree* here */ int flags, /* Flags */ int vfsFlags /* Flags passed through to VFS open */ ); /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the ** following values. ** ** NOTE: These values must match the corresponding PAGER_ values in ** pager.h. */ #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ #define BTREE_MEMORY 2 /* This is an in-memory DB */ #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */ #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */ SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int); #if SQLITE_MAX_MMAP_SIZE>0 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64); #endif SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned); SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*); SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p); SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int); SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int); SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); #ifndef SQLITE_OMIT_SHARED_CACHE SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); #endif SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR ** of the flags shown below. ** ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL ** indices.) */ #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ #define BTREE_BLOBKEY 2 /* Table has keys only - no data */ SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int); SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); /* ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta ** should be one of the following values. The integer values are assigned ** to constants so that the offset of the corresponding field in an ** SQLite database header may be found using the following formula: ** ** offset = 36 + (idx * 4) ** ** For example, the free-page-count field is located at byte offset 36 of ** the database file header. The incr-vacuum-flag field is located at ** byte offset 64 (== 36+4*7). ** ** The BTREE_DATA_VERSION value is not really a value stored in the header. ** It is a read-only number computed by the pager. But we merge it with ** the header value access routines since its access pattern is the same. ** Call it a "virtual meta value". */ #define BTREE_FREE_PAGE_COUNT 0 #define BTREE_SCHEMA_VERSION 1 #define BTREE_FILE_FORMAT 2 #define BTREE_DEFAULT_CACHE_SIZE 3 #define BTREE_LARGEST_ROOT_PAGE 4 #define BTREE_TEXT_ENCODING 5 #define BTREE_USER_VERSION 6 #define BTREE_INCR_VACUUM 7 #define BTREE_APPLICATION_ID 8 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */ /* ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint() ** interface. ** ** BTREE_HINT_RANGE (arguments: Expr*, Mem*) ** ** The first argument is an Expr* (which is guaranteed to be constant for ** the lifetime of the cursor) that defines constraints on which rows ** might be fetched with this cursor. The Expr* tree may contain ** TK_REGISTER nodes that refer to values stored in the array of registers ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER ** then the value of the node is the value in Mem[pExpr.iTable]. Any ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th ** column of the b-tree of the cursor. The Expr tree will not contain ** any function calls nor subqueries nor references to b-trees other than ** the cursor being hinted. ** ** The design of the _RANGE hint is aid b-tree implementations that try ** to prefetch content from remote machines - to provide those ** implementations with limits on what needs to be prefetched and thereby ** reduce network bandwidth. ** ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by ** standard SQLite. The other hints are provided for extentions that use ** the SQLite parser and code generator but substitute their own storage ** engine. */ #define BTREE_HINT_RANGE 0 /* Range constraints on queries */ /* ** Values that may be OR'd together to form the argument to the ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint(): ** ** The BTREE_BULKLOAD flag is set on index cursors when the index is going ** to be filled with content that is already in sorted order. ** ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or ** OP_SeekLE opcodes for a range search, but where the range of entries ** selected will all have the same key. In other words, the cursor will ** be used only for equality key searches. ** */ #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */ #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */ /* ** Flags passed as the third argument to sqlite3BtreeCursor(). ** ** For read-only cursors the wrFlag argument is always zero. For read-write ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will ** only be used by SQLite for the following: ** ** * to seek to and then delete specific entries, and/or ** ** * to read values that will be used to create keys that other ** BTREE_FORDELETE cursors will seek to and delete. ** ** The BTREE_FORDELETE flag is an optimization hint. It is not used by ** by this, the native b-tree engine of SQLite, but it is available to ** alternative storage engines that might be substituted in place of this ** b-tree system. For alternative storage engines in which a delete of ** the main table row automatically deletes corresponding index rows, ** the FORDELETE flag hint allows those alternative storage engines to ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK ** and DELETE operations as no-ops, and any READ operation against a ** FORDELETE cursor may return a null row: 0x01 0x00. */ #define BTREE_WRCSR 0x00000004 /* read-write cursor */ #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */ SQLITE_PRIVATE int sqlite3BtreeCursor( Btree*, /* BTree containing table to open */ int iTable, /* Index of root page */ int wrFlag, /* 1 for writing. 0 for read-only */ struct KeyInfo*, /* First argument to compare function */ BtCursor *pCursor /* Space to write cursor structure */ ); SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned); #ifdef SQLITE_ENABLE_CURSOR_HINTS SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...); #endif SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( BtCursor*, UnpackedRecord *pUnKey, i64 intKey, int bias, int *pRes ); SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*); SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags); /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */ #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */ #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */ #define BTREE_APPEND 0x08 /* Insert is likely an append */ /* An instance of the BtreePayload object describes the content of a single ** entry in either an index or table btree. ** ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain ** an arbitrary key and no data. These btrees have pKey,nKey set to their ** key and pData,nData,nZero set to zero. ** ** Table btrees (used for rowid tables) contain an integer rowid used as ** the key and passed in the nKey field. The pKey field is zero. ** pData,nData hold the content of the new entry. nZero extra zero bytes ** are appended to the end of the content when constructing the entry. ** ** This object is used to pass information into sqlite3BtreeInsert(). The ** same information used to be passed as five separate parameters. But placing ** the information into this object helps to keep the interface more ** organized and understandable, and it also helps the resulting code to ** run a little faster by using fewer registers for parameter passing. */ struct BtreePayload { const void *pKey; /* Key content for indexes. NULL for tables */ sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */ const void *pData; /* Data for tables. NULL for indexes */ struct Mem *aMem; /* First of nMem value in the unpacked pKey */ u16 nMem; /* Number of aMem[] value. Might be zero */ int nData; /* Size of pData. 0 if none. */ int nZero; /* Extra zero data appended after pData,nData */ }; SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload, int flags, int seekResult); SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*); SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt); SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*); SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); #ifndef SQLITE_OMIT_INCRBLOB SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *); #endif SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask); SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt); SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void); #ifndef NDEBUG SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); #endif SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*); #ifndef SQLITE_OMIT_BTREECOUNT SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); #endif #ifndef SQLITE_OMIT_WAL SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); #endif /* ** If we are not using shared cache, then there is no need to ** use mutexes to access the BtShared structures. So make the ** Enter and Leave procedures no-ops. */ #ifndef SQLITE_OMIT_SHARED_CACHE SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*); SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*); #else # define sqlite3BtreeEnter(X) # define sqlite3BtreeEnterAll(X) # define sqlite3BtreeSharable(X) 0 # define sqlite3BtreeEnterCursor(X) # define sqlite3BtreeConnectionCount(X) 1 #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); #ifndef NDEBUG /* These routines are used inside assert() statements only. */ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); #endif #else # define sqlite3BtreeLeave(X) # define sqlite3BtreeLeaveCursor(X) # define sqlite3BtreeLeaveAll(X) # define sqlite3BtreeHoldsMutex(X) 1 # define sqlite3BtreeHoldsAllMutexes(X) 1 # define sqlite3SchemaMutexHeld(X,Y,Z) 1 #endif #endif /* SQLITE_BTREE_H */ /************** End of btree.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include vdbe.h in the middle of sqliteInt.h ******************/ /************** Begin file vdbe.h ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Header file for the Virtual DataBase Engine (VDBE) ** ** This header defines the interface to the virtual database engine ** or VDBE. The VDBE implements an abstract machine that runs a ** simple program to access and modify the underlying database. */ #ifndef SQLITE_VDBE_H #define SQLITE_VDBE_H /* #include <stdio.h> */ /* ** A single VDBE is an opaque structure named "Vdbe". Only routines ** in the source file sqliteVdbe.c are allowed to see the insides ** of this structure. */ typedef struct Vdbe Vdbe; /* ** The names of the following types declared in vdbeInt.h are required ** for the VdbeOp definition. */ typedef struct Mem Mem; typedef struct SubProgram SubProgram; /* ** A single instruction of the virtual machine has an opcode ** and as many as three operands. The instruction is recorded ** as an instance of the following structure: */ struct VdbeOp { u8 opcode; /* What operation to perform */ signed char p4type; /* One of the P4_xxx constants for p4 */ u16 p5; /* Fifth parameter is an unsigned 16-bit integer */ int p1; /* First operand */ int p2; /* Second parameter (often the jump destination) */ int p3; /* The third parameter */ union p4union { /* fourth parameter */ int i; /* Integer value if p4type==P4_INT32 */ void *p; /* Generic pointer */ char *z; /* Pointer to data for string (char array) types */ i64 *pI64; /* Used when p4type is P4_INT64 */ double *pReal; /* Used when p4type is P4_REAL */ FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */ CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ Mem *pMem; /* Used when p4type is P4_MEM */ VTable *pVtab; /* Used when p4type is P4_VTAB */ KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ int *ai; /* Used when p4type is P4_INTARRAY */ SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ Table *pTab; /* Used when p4type is P4_TABLE */ #ifdef SQLITE_ENABLE_CURSOR_HINTS Expr *pExpr; /* Used when p4type is P4_EXPR */ #endif int (*xAdvance)(BtCursor *, int *); } p4; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS char *zComment; /* Comment to improve readability */ #endif #ifdef VDBE_PROFILE u32 cnt; /* Number of times this instruction was executed */ u64 cycles; /* Total time spent executing this instruction */ #endif #ifdef SQLITE_VDBE_COVERAGE int iSrcLine; /* Source-code line that generated this opcode */ #endif }; typedef struct VdbeOp VdbeOp; /* ** A sub-routine used to implement a trigger program. */ struct SubProgram { VdbeOp *aOp; /* Array of opcodes for sub-program */ int nOp; /* Elements in aOp[] */ int nMem; /* Number of memory cells required */ int nCsr; /* Number of cursors required */ void *token; /* id that may be used to recursive triggers */ SubProgram *pNext; /* Next sub-program already visited */ }; /* ** A smaller version of VdbeOp used for the VdbeAddOpList() function because ** it takes up less space. */ struct VdbeOpList { u8 opcode; /* What operation to perform */ signed char p1; /* First operand */ signed char p2; /* Second parameter (often the jump destination) */ signed char p3; /* Third parameter */ }; typedef struct VdbeOpList VdbeOpList; /* ** Allowed values of VdbeOp.p4type */ #define P4_NOTUSED 0 /* The P4 parameter is not used */ #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ #define P4_STATIC (-2) /* Pointer to a static string */ #define P4_COLLSEQ (-3) /* P4 is a pointer to a CollSeq structure */ #define P4_FUNCDEF (-4) /* P4 is a pointer to a FuncDef structure */ #define P4_KEYINFO (-5) /* P4 is a pointer to a KeyInfo structure */ #define P4_EXPR (-6) /* P4 is a pointer to an Expr tree */ #define P4_MEM (-7) /* P4 is a pointer to a Mem* structure */ #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ #define P4_VTAB (-8) /* P4 is a pointer to an sqlite3_vtab structure */ #define P4_REAL (-9) /* P4 is a 64-bit floating point value */ #define P4_INT64 (-10) /* P4 is a 64-bit signed integer */ #define P4_INT32 (-11) /* P4 is a 32-bit signed integer */ #define P4_INTARRAY (-12) /* P4 is a vector of 32-bit integers */ #define P4_SUBPROGRAM (-13) /* P4 is a pointer to a SubProgram structure */ #define P4_ADVANCE (-14) /* P4 is a pointer to BtreeNext() or BtreePrev() */ #define P4_TABLE (-15) /* P4 is a pointer to a Table structure */ #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */ /* Error message codes for OP_Halt */ #define P5_ConstraintNotNull 1 #define P5_ConstraintUnique 2 #define P5_ConstraintCheck 3 #define P5_ConstraintFK 4 /* ** The Vdbe.aColName array contains 5n Mem structures, where n is the ** number of columns of data returned by the statement. */ #define COLNAME_NAME 0 #define COLNAME_DECLTYPE 1 #define COLNAME_DATABASE 2 #define COLNAME_TABLE 3 #define COLNAME_COLUMN 4 #ifdef SQLITE_ENABLE_COLUMN_METADATA # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ #else # ifdef SQLITE_OMIT_DECLTYPE # define COLNAME_N 1 /* Store only the name */ # else # define COLNAME_N 2 /* Store the name and decltype */ # endif #endif /* ** The following macro converts a relative address in the p2 field ** of a VdbeOp structure into a negative number so that ** sqlite3VdbeAddOpList() knows that the address is relative. Calling ** the macro again restores the address. */ #define ADDR(X) (-1-(X)) /* ** The makefile scans the vdbe.c source file and creates the "opcodes.h" ** header file that defines a number for each opcode used by the VDBE. */ /************** Include opcodes.h in the middle of vdbe.h ********************/ /************** Begin file opcodes.h *****************************************/ /* Automatically generated. Do not edit */ /* See the tool/mkopcodeh.tcl script for details */ #define OP_Savepoint 0 #define OP_AutoCommit 1 #define OP_Transaction 2 #define OP_SorterNext 3 #define OP_PrevIfOpen 4 #define OP_NextIfOpen 5 #define OP_Prev 6 #define OP_Next 7 #define OP_Checkpoint 8 #define OP_JournalMode 9 #define OP_Vacuum 10 #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */ #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */ #define OP_Goto 13 #define OP_Gosub 14 #define OP_InitCoroutine 15 #define OP_Yield 16 #define OP_MustBeInt 17 #define OP_Jump 18 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */ #define OP_Once 20 #define OP_If 21 #define OP_IfNot 22 #define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */ #define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */ #define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */ #define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */ #define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */ #define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */ #define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */ #define OP_NotFound 30 /* synopsis: key=r[P3@P4] */ #define OP_Found 31 /* synopsis: key=r[P3@P4] */ #define OP_SeekRowid 32 /* synopsis: intkey=r[P3] */ #define OP_NotExists 33 /* synopsis: intkey=r[P3] */ #define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */ #define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */ #define OP_Ne 36 /* same as TK_NE, synopsis: IF r[P3]!=r[P1] */ #define OP_Eq 37 /* same as TK_EQ, synopsis: IF r[P3]==r[P1] */ #define OP_Gt 38 /* same as TK_GT, synopsis: IF r[P3]>r[P1] */ #define OP_Le 39 /* same as TK_LE, synopsis: IF r[P3]<=r[P1] */ #define OP_Lt 40 /* same as TK_LT, synopsis: IF r[P3]<r[P1] */ #define OP_Ge 41 /* same as TK_GE, synopsis: IF r[P3]>=r[P1] */ #define OP_ElseNotEq 42 /* same as TK_ESCAPE */ #define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ #define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ #define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */ #define OP_ShiftRight 46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */ #define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */ #define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */ #define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */ #define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */ #define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */ #define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */ #define OP_Last 53 #define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */ #define OP_SorterSort 55 #define OP_Sort 56 #define OP_Rewind 57 #define OP_IdxLE 58 /* synopsis: key=r[P3@P4] */ #define OP_IdxGT 59 /* synopsis: key=r[P3@P4] */ #define OP_IdxLT 60 /* synopsis: key=r[P3@P4] */ #define OP_IdxGE 61 /* synopsis: key=r[P3@P4] */ #define OP_RowSetRead 62 /* synopsis: r[P3]=rowset(P1) */ #define OP_RowSetTest 63 /* synopsis: if r[P3] in rowset(P1) goto P2 */ #define OP_Program 64 #define OP_FkIfZero 65 /* synopsis: if fkctr[P1]==0 goto P2 */ #define OP_IfPos 66 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ #define OP_IfNotZero 67 /* synopsis: if r[P1]!=0 then r[P1]--, goto P2 */ #define OP_DecrJumpZero 68 /* synopsis: if (--r[P1])==0 goto P2 */ #define OP_IncrVacuum 69 #define OP_VNext 70 #define OP_Init 71 /* synopsis: Start at P2 */ #define OP_Return 72 #define OP_EndCoroutine 73 #define OP_HaltIfNull 74 /* synopsis: if r[P3]=null halt */ #define OP_Halt 75 #define OP_Integer 76 /* synopsis: r[P2]=P1 */ #define OP_Int64 77 /* synopsis: r[P2]=P4 */ #define OP_String 78 /* synopsis: r[P2]='P4' (len=P1) */ #define OP_Null 79 /* synopsis: r[P2..P3]=NULL */ #define OP_SoftNull 80 /* synopsis: r[P1]=NULL */ #define OP_Blob 81 /* synopsis: r[P2]=P4 (len=P1) */ #define OP_Variable 82 /* synopsis: r[P2]=parameter(P1,P4) */ #define OP_Move 83 /* synopsis: r[P2@P3]=r[P1@P3] */ #define OP_Copy 84 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ #define OP_SCopy 85 /* synopsis: r[P2]=r[P1] */ #define OP_IntCopy 86 /* synopsis: r[P2]=r[P1] */ #define OP_ResultRow 87 /* synopsis: output=r[P1@P2] */ #define OP_CollSeq 88 #define OP_Function0 89 /* synopsis: r[P3]=func(r[P2@P5]) */ #define OP_Function 90 /* synopsis: r[P3]=func(r[P2@P5]) */ #define OP_AddImm 91 /* synopsis: r[P1]=r[P1]+P2 */ #define OP_RealAffinity 92 #define OP_Cast 93 /* synopsis: affinity(r[P1]) */ #define OP_Permutation 94 #define OP_Compare 95 /* synopsis: r[P1@P3] <-> r[P2@P3] */ #define OP_Column 96 /* synopsis: r[P3]=PX */ #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */ #define OP_Affinity 98 /* synopsis: affinity(r[P1@P2]) */ #define OP_MakeRecord 99 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ #define OP_Count 100 /* synopsis: r[P2]=count() */ #define OP_ReadCookie 101 #define OP_SetCookie 102 #define OP_ReopenIdx 103 /* synopsis: root=P2 iDb=P3 */ #define OP_OpenRead 104 /* synopsis: root=P2 iDb=P3 */ #define OP_OpenWrite 105 /* synopsis: root=P2 iDb=P3 */ #define OP_OpenAutoindex 106 /* synopsis: nColumn=P2 */ #define OP_OpenEphemeral 107 /* synopsis: nColumn=P2 */ #define OP_SorterOpen 108 #define OP_SequenceTest 109 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ #define OP_OpenPseudo 110 /* synopsis: P3 columns in r[P2] */ #define OP_Close 111 #define OP_ColumnsUsed 112 #define OP_Sequence 113 /* synopsis: r[P2]=cursor[P1].ctr++ */ #define OP_NewRowid 114 /* synopsis: r[P2]=rowid */ #define OP_Insert 115 /* synopsis: intkey=r[P3] data=r[P2] */ #define OP_InsertInt 116 /* synopsis: intkey=P3 data=r[P2] */ #define OP_Delete 117 #define OP_ResetCount 118 #define OP_SorterCompare 119 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ #define OP_SorterData 120 /* synopsis: r[P2]=data */ #define OP_RowData 121 /* synopsis: r[P2]=data */ #define OP_Rowid 122 /* synopsis: r[P2]=rowid */ #define OP_NullRow 123 #define OP_SorterInsert 124 /* synopsis: key=r[P2] */ #define OP_IdxInsert 125 /* synopsis: key=r[P2] */ #define OP_IdxDelete 126 /* synopsis: key=r[P2@P3] */ #define OP_Seek 127 /* synopsis: Move P3 to P1.rowid */ #define OP_IdxRowid 128 /* synopsis: r[P2]=rowid */ #define OP_Destroy 129 #define OP_Clear 130 #define OP_ResetSorter 131 #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ #define OP_CreateIndex 133 /* synopsis: r[P2]=root iDb=P1 */ #define OP_CreateTable 134 /* synopsis: r[P2]=root iDb=P1 */ #define OP_ParseSchema 135 #define OP_LoadAnalysis 136 #define OP_DropTable 137 #define OP_DropIndex 138 #define OP_DropTrigger 139 #define OP_IntegrityCk 140 #define OP_RowSetAdd 141 /* synopsis: rowset(P1)=r[P2] */ #define OP_Param 142 #define OP_FkCounter 143 /* synopsis: fkctr[P1]+=P2 */ #define OP_MemMax 144 /* synopsis: r[P1]=max(r[P1],r[P2]) */ #define OP_OffsetLimit 145 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ #define OP_AggStep0 146 /* synopsis: accum=r[P3] step(r[P2@P5]) */ #define OP_AggStep 147 /* synopsis: accum=r[P3] step(r[P2@P5]) */ #define OP_AggFinal 148 /* synopsis: accum=r[P1] N=P2 */ #define OP_Expire 149 #define OP_TableLock 150 /* synopsis: iDb=P1 root=P2 write=P3 */ #define OP_VBegin 151 #define OP_VCreate 152 #define OP_VDestroy 153 #define OP_VOpen 154 #define OP_VColumn 155 /* synopsis: r[P3]=vcolumn(P2) */ #define OP_VRename 156 #define OP_Pagecount 157 #define OP_MaxPgcnt 158 #define OP_CursorHint 159 #define OP_Noop 160 #define OP_Explain 161 /* Properties such as "out2" or "jump" that are specified in ** comments following the "case" for each opcode in the vdbe.c ** are encoded into bitvectors as follows: */ #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */ #define OPFLG_IN1 0x02 /* in1: P1 is an input */ #define OPFLG_IN2 0x04 /* in2: P2 is an input */ #define OPFLG_IN3 0x08 /* in3: P3 is an input */ #define OPFLG_OUT2 0x10 /* out2: P2 is an output */ #define OPFLG_OUT3 0x20 /* out3: P3 is an output */ #define OPFLG_INITIALIZER {\ /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\ /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\ /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\ /* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\ /* 32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\ /* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\ /* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\ /* 56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b,\ /* 64 */ 0x01, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x01,\ /* 72 */ 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10,\ /* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00,\ /* 88 */ 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\ /* 96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\ /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ /* 112 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\ /* 120 */ 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00, 0x00,\ /* 128 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00,\ /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00,\ /* 144 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\ /* 160 */ 0x00, 0x00,} /* The sqlite3P2Values() routine is able to run faster if it knows ** the value of the largest JUMP opcode. The smaller the maximum ** JUMP opcode the better, so the mkopcodeh.tcl script that ** generated this include file strives to group all JUMP opcodes ** together near the beginning of the list. */ #define SQLITE_MX_JUMP_OPCODE 71 /* Maximum JUMP opcode */ /************** End of opcodes.h *********************************************/ /************** Continuing where we left off in vdbe.h ***********************/ /* ** Prototypes for the VDBE interface. See comments on the implementation ** for a description of what each of these routines does. */ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*); SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*); SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...); SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int); SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int); #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N); SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p); #else # define sqlite3VdbeVerifyNoMallocRequired(A,B) # define sqlite3VdbeVerifyNoResultRow(A) #endif SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno); SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8); SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1); SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2); SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3); SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5); SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr); SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op); SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type); SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*); SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*); SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*); SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); #endif SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8); SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); #ifndef SQLITE_OMIT_TRACE SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); #endif SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int); SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*); typedef int (*RecordCompare)(int,const void*,UnpackedRecord*); SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*); #ifndef SQLITE_OMIT_TRIGGER SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); #endif /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on ** each VDBE opcode. ** ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op ** comments in VDBE programs that show key decision points in the code ** generator. */ #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); # define VdbeComment(X) sqlite3VdbeComment X SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); # define VdbeNoopComment(X) sqlite3VdbeNoopComment X # ifdef SQLITE_ENABLE_MODULE_COMMENTS # define VdbeModuleComment(X) sqlite3VdbeNoopComment X # else # define VdbeModuleComment(X) # endif #else # define VdbeComment(X) # define VdbeNoopComment(X) # define VdbeModuleComment(X) #endif /* ** The VdbeCoverage macros are used to set a coverage testing point ** for VDBE branch instructions. The coverage testing points are line ** numbers in the sqlite3.c source file. VDBE branch coverage testing ** only works with an amalagmation build. That's ok since a VDBE branch ** coverage build designed for testing the test suite only. No application ** should ever ship with VDBE branch coverage measuring turned on. ** ** VdbeCoverage(v) // Mark the previously coded instruction ** // as a branch ** ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true ** ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken ** ** VdbeCoverageNeverTaken(v) // Previous branch is never taken ** ** Every VDBE branch operation must be tagged with one of the macros above. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch() ** routine in vdbe.c, alerting the developer to the missed tag. */ #ifdef SQLITE_VDBE_COVERAGE SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int); # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__) # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__) # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2); # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1); # define VDBE_OFFSET_LINENO(x) (__LINE__+x) #else # define VdbeCoverage(v) # define VdbeCoverageIf(v,x) # define VdbeCoverageAlwaysTaken(v) # define VdbeCoverageNeverTaken(v) # define VDBE_OFFSET_LINENO(x) 0 #endif #ifdef SQLITE_ENABLE_STMT_SCANSTATUS SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*); #else # define sqlite3VdbeScanStatus(a,b,c,d,e) #endif #endif /* SQLITE_VDBE_H */ /************** End of vdbe.h ************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include pager.h in the middle of sqliteInt.h *****************/ /************** Begin file pager.h *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite page cache ** subsystem. The page cache subsystem reads and writes a file a page ** at a time and provides a journal for rollback. */ #ifndef SQLITE_PAGER_H #define SQLITE_PAGER_H /* ** Default maximum size for persistent journal files. A negative ** value means no limit. This value may be overridden using the ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". */ #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 #endif /* ** The type used to represent a page number. The first page in a file ** is called page 1. 0 is used to represent "not a page". */ typedef u32 Pgno; /* ** Each open file is managed by a separate instance of the "Pager" structure. */ typedef struct Pager Pager; /* ** Handle type for pages. */ typedef struct PgHdr DbPage; /* ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is ** reserved for working around a windows/posix incompatibility). It is ** used in the journal to signify that the remainder of the journal file ** is devoted to storing a master journal name - there are no more pages to ** roll back. See comments for function writeMasterJournal() in pager.c ** for details. */ #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) /* ** Allowed values for the flags parameter to sqlite3PagerOpen(). ** ** NOTE: These values must match the corresponding BTREE_ values in btree.h. */ #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ #define PAGER_MEMORY 0x0002 /* In-memory database */ /* ** Valid values for the second argument to sqlite3PagerLockingMode(). */ #define PAGER_LOCKINGMODE_QUERY -1 #define PAGER_LOCKINGMODE_NORMAL 0 #define PAGER_LOCKINGMODE_EXCLUSIVE 1 /* ** Numeric constants that encode the journalmode. ** ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY) ** are exposed in the API via the "PRAGMA journal_mode" command and ** therefore cannot be changed without a compatibility break. */ #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ /* ** Flags that make up the mask passed to sqlite3PagerGet(). */ #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */ #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */ /* ** Flags for sqlite3PagerSetFlags() ** ** Value constraints (enforced via assert()): ** PAGER_FULLFSYNC == SQLITE_FullFSync ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync ** PAGER_CACHE_SPILL == SQLITE_CacheSpill */ #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */ #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */ #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */ #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */ #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */ #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */ #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */ #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */ #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */ /* ** The remainder of this file contains the declarations of the functions ** that make up the Pager sub-system API. See source code comments for ** a detailed description of each routine. */ /* Open and close a Pager connection. */ SQLITE_PRIVATE int sqlite3PagerOpen( sqlite3_vfs*, Pager **ppPager, const char*, int, int, int, void(*)(DbPage*) ); SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*); SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); /* Functions used to configure a Pager object. */ SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); #ifdef SQLITE_HAS_CODEC SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*); #endif SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int); SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64); SQLITE_PRIVATE void sqlite3PagerShrink(Pager*); SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned); SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); SQLITE_PRIVATE int sqlite3PagerFlush(Pager*); /* Functions used to obtain and release page references. */ SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*); /* Operations on page references. */ SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); /* Functions used to manage pager transactions and savepoints. */ SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster); SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); #ifndef SQLITE_OMIT_WAL SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*); SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*); # ifdef SQLITE_DIRECT_OVERFLOW_READ SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno); # endif # ifdef SQLITE_ENABLE_SNAPSHOT SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot); SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot); SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager); # endif #else # define sqlite3PagerUseWal(x,y) 0 #endif #ifdef SQLITE_ENABLE_ZIPVFS SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager); #endif /* Functions used to query pager state and configuration. */ SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); #endif SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int); SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*); SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*); SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *); SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*); SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *); /* Functions used to truncate the database file. */ SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16); #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); #endif /* Functions to support testing and debugging. */ #if !defined(NDEBUG) || defined(SQLITE_TEST) SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); void disable_simulated_io_errors(void); void enable_simulated_io_errors(void); #else # define disable_simulated_io_errors() # define enable_simulated_io_errors() #endif #endif /* SQLITE_PAGER_H */ /************** End of pager.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include pcache.h in the middle of sqliteInt.h ****************/ /************** Begin file pcache.h ******************************************/ /* ** 2008 August 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite page cache ** subsystem. */ #ifndef _PCACHE_H_ typedef struct PgHdr PgHdr; typedef struct PCache PCache; /* ** Every page in the cache is controlled by an instance of the following ** structure. */ struct PgHdr { sqlite3_pcache_page *pPage; /* Pcache object page handle */ void *pData; /* Page data */ void *pExtra; /* Extra content */ PgHdr *pDirty; /* Transient list of dirty sorted by pgno */ Pager *pPager; /* The pager this page is part of */ Pgno pgno; /* Page number for this page */ #ifdef SQLITE_CHECK_PAGES u32 pageHash; /* Hash of page content */ #endif u16 flags; /* PGHDR flags defined below */ /********************************************************************** ** Elements above are public. All that follows is private to pcache.c ** and should not be accessed by other modules. */ i16 nRef; /* Number of users of this page */ PCache *pCache; /* Cache that owns this page */ PgHdr *pDirtyNext; /* Next element in list of dirty pages */ PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ }; /* Bit values for PgHdr.flags */ #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */ #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */ #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */ #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before ** writing this page to the database */ #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */ #define PGHDR_MMAP 0x020 /* This is an mmap page object */ #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */ /* Initialize and shutdown the page cache subsystem */ SQLITE_PRIVATE int sqlite3PcacheInitialize(void); SQLITE_PRIVATE void sqlite3PcacheShutdown(void); /* Page cache buffer management: ** These routines implement SQLITE_CONFIG_PAGECACHE. */ SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); /* Create a new pager cache. ** Under memory stress, invoke xStress to try to make pages clean. ** Only clean and unpinned pages can be reclaimed. */ SQLITE_PRIVATE int sqlite3PcacheOpen( int szPage, /* Size of every page */ int szExtra, /* Extra space associated with each page */ int bPurgeable, /* True if pages are on backing store */ int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ void *pStress, /* Argument to xStress */ PCache *pToInit /* Preallocated space for the PCache */ ); /* Modify the page-size after the cache has been created. */ SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int); /* Return the size in bytes of a PCache object. Used to preallocate ** storage space. */ SQLITE_PRIVATE int sqlite3PcacheSize(void); /* One release per successful fetch. Page is pinned until released. ** Reference counted. */ SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag); SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**); SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage); SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*); /* Change a page number. Used by incr-vacuum. */ SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); /* Remove all pages with pgno>x. Reset the cache if x==0 */ SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); /* Get a list of all dirty pages in the cache, sorted by page number */ SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); /* Reset and close the cache object */ SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); /* Clear flags from pages of the page cache */ SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); /* Discard the contents of the cache */ SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); /* Return the total number of outstanding page references */ SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); /* Increment the reference count of an existing page */ SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); /* Return the total number of pages stored in the cache */ SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) /* Iterate through all dirty pages currently stored in the cache. This ** interface is only available if SQLITE_CHECK_PAGES is defined when the ** library is built. */ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); #endif #if defined(SQLITE_DEBUG) /* Check invariants on a PgHdr object */ SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*); #endif /* Set and get the suggested cache-size for the specified pager-cache. ** ** If no global maximum is configured, then the system attempts to limit ** the total number of pages cached by purgeable pager-caches to the sum ** of the suggested cache-sizes. */ SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); #endif /* Set or get the suggested spill-size for the specified pager-cache. ** ** The spill-size is the minimum number of pages in cache before the cache ** will attempt to spill dirty pages by calling xStress. */ SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int); /* Free up as much memory as possible from the page cache */ SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*); #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* Try to return memory used by the pcache module to the main memory heap */ SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); #endif SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); /* Return the header size */ SQLITE_PRIVATE int sqlite3HeaderSizePcache(void); SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void); /* Number of dirty pages as a percentage of the configured cache size */ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*); #endif /* _PCACHE_H_ */ /************** End of pcache.h **********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include os.h in the middle of sqliteInt.h ********************/ /************** Begin file os.h **********************************************/ /* ** 2001 September 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file (together with is companion C source-code file ** "os.c") attempt to abstract the underlying operating system so that ** the SQLite library will work on both POSIX and windows systems. ** ** This header file is #include-ed by sqliteInt.h and thus ends up ** being included by every source file. */ #ifndef _SQLITE_OS_H_ #define _SQLITE_OS_H_ /* ** Attempt to automatically detect the operating system and setup the ** necessary pre-processor macros for it. */ /************** Include os_setup.h in the middle of os.h *********************/ /************** Begin file os_setup.h ****************************************/ /* ** 2013 November 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains pre-processor directives related to operating system ** detection and/or setup. */ #ifndef SQLITE_OS_SETUP_H #define SQLITE_OS_SETUP_H /* ** Figure out if we are dealing with Unix, Windows, or some other operating ** system. ** ** After the following block of preprocess macros, all of SQLITE_OS_UNIX, ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of ** the three will be 1. The other two will be 0. */ #if defined(SQLITE_OS_OTHER) # if SQLITE_OS_OTHER==1 # undef SQLITE_OS_UNIX # define SQLITE_OS_UNIX 0 # undef SQLITE_OS_WIN # define SQLITE_OS_WIN 0 # else # undef SQLITE_OS_OTHER # endif #endif #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) # define SQLITE_OS_OTHER 0 # ifndef SQLITE_OS_WIN # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \ defined(__MINGW32__) || defined(__BORLANDC__) # define SQLITE_OS_WIN 1 # define SQLITE_OS_UNIX 0 # else # define SQLITE_OS_WIN 0 # define SQLITE_OS_UNIX 1 # endif # else # define SQLITE_OS_UNIX 0 # endif #else # ifndef SQLITE_OS_WIN # define SQLITE_OS_WIN 0 # endif #endif #endif /* SQLITE_OS_SETUP_H */ /************** End of os_setup.h ********************************************/ /************** Continuing where we left off in os.h *************************/ /* If the SET_FULLSYNC macro is not defined above, then make it ** a no-op */ #ifndef SET_FULLSYNC # define SET_FULLSYNC(x,y) #endif /* ** The default size of a disk sector */ #ifndef SQLITE_DEFAULT_SECTOR_SIZE # define SQLITE_DEFAULT_SECTOR_SIZE 4096 #endif /* ** Temporary files are named starting with this prefix followed by 16 random ** alphanumeric characters, and no file extension. They are stored in the ** OS's standard temporary file directory, and are deleted prior to exit. ** If sqlite is being embedded in another program, you may wish to change the ** prefix to reflect your program's name, so that if your program exits ** prematurely, old temporary files can be easily identified. This can be done ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. ** ** 2006-10-31: The default prefix used to be "sqlite_". But then ** Mcafee started using SQLite in their anti-virus product and it ** started putting files with the "sqlite" name in the c:/temp folder. ** This annoyed many windows users. Those users would then do a ** Google search for "sqlite", find the telephone numbers of the ** developers and call to wake them up at night and complain. ** For this reason, the default name prefix is changed to be "sqlite" ** spelled backwards. So the temp files are still identified, but ** anybody smart enough to figure out the code is also likely smart ** enough to know that calling the developer will not help get rid ** of the file. */ #ifndef SQLITE_TEMP_FILE_PREFIX # define SQLITE_TEMP_FILE_PREFIX "etilqs_" #endif /* ** The following values may be passed as the second argument to ** sqlite3OsLock(). The various locks exhibit the following semantics: ** ** SHARED: Any number of processes may hold a SHARED lock simultaneously. ** RESERVED: A single process may hold a RESERVED lock on a file at ** any time. Other processes may hold and obtain new SHARED locks. ** PENDING: A single process may hold a PENDING lock on a file at ** any one time. Existing SHARED locks may persist, but no new ** SHARED locks may be obtained by other processes. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. ** ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a ** process that requests an EXCLUSIVE lock may actually obtain a PENDING ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to ** sqlite3OsLock(). */ #define NO_LOCK 0 #define SHARED_LOCK 1 #define RESERVED_LOCK 2 #define PENDING_LOCK 3 #define EXCLUSIVE_LOCK 4 /* ** File Locking Notes: (Mostly about windows but also some info for Unix) ** ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because ** those functions are not available. So we use only LockFile() and ** UnlockFile(). ** ** LockFile() prevents not just writing but also reading by other processes. ** A SHARED_LOCK is obtained by locking a single randomly-chosen ** byte out of a specific range of bytes. The lock byte is obtained at ** random so two separate readers can probably access the file at the ** same time, unless they are unlucky and choose the same lock byte. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. ** There can only be one writer. A RESERVED_LOCK is obtained by locking ** a single byte of the file that is designated as the reserved lock byte. ** A PENDING_LOCK is obtained by locking a designated byte different from ** the RESERVED_LOCK byte. ** ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, ** which means we can use reader/writer locks. When reader/writer locks ** are used, the lock is placed on the same range of bytes that is used ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme ** will support two or more Win95 readers or two or more WinNT readers. ** But a single Win95 reader will lock out all WinNT readers and a single ** WinNT reader will lock out all other Win95 readers. ** ** The following #defines specify the range of bytes used for locking. ** SHARED_SIZE is the number of bytes available in the pool from which ** a random byte is selected for a shared lock. The pool of bytes for ** shared locks begins at SHARED_FIRST. ** ** The same locking strategy and ** byte ranges are used for Unix. This leaves open the possibility of having ** clients on win95, winNT, and unix all talking to the same shared file ** and all locking correctly. To do so would require that samba (or whatever ** tool is being used for file sharing) implements locks correctly between ** windows and unix. I'm guessing that isn't likely to happen, but by ** using the same locking range we are at least open to the possibility. ** ** Locking in windows is manditory. For this reason, we cannot store ** actual data in the bytes used for locking. The pager never allocates ** the pages involved in locking therefore. SHARED_SIZE is selected so ** that all locks will fit on a single page even at the minimum page size. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE ** is set high so that we don't have to allocate an unused page except ** for very large databases. But one should test the page skipping logic ** by setting PENDING_BYTE low and running the entire regression suite. ** ** Changing the value of PENDING_BYTE results in a subtly incompatible ** file format. Depending on how it is changed, you might not notice ** the incompatibility right away, even running a full regression test. ** The default location of PENDING_BYTE is the first byte past the ** 1GB boundary. ** */ #ifdef SQLITE_OMIT_WSD # define PENDING_BYTE (0x40000000) #else # define PENDING_BYTE sqlite3PendingByte #endif #define RESERVED_BYTE (PENDING_BYTE+1) #define SHARED_FIRST (PENDING_BYTE+2) #define SHARED_SIZE 510 /* ** Wrapper around OS specific sqlite3_os_init() function. */ SQLITE_PRIVATE int sqlite3OsInit(void); /* ** Functions for accessing sqlite3_file methods */ SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*); SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*); #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **); SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *); /* ** Functions for accessing sqlite3_vfs methods */ SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); #ifndef SQLITE_OMIT_LOAD_EXTENSION SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); #endif /* SQLITE_OMIT_LOAD_EXTENSION */ SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*); SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); /* ** Convenience functions for opening and closing files using ** sqlite3_malloc() to obtain space for the file-handle structure. */ SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *); #endif /* _SQLITE_OS_H_ */ /************** End of os.h **************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include mutex.h in the middle of sqliteInt.h *****************/ /************** Begin file mutex.h *******************************************/ /* ** 2007 August 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the common header for all mutex implementations. ** The sqliteInt.h header #includes this file so that it is available ** to all source files. We break it out in an effort to keep the code ** better organized. ** ** NOTE: source files should *not* #include this header file directly. ** Source files should #include the sqliteInt.h file and let that file ** include this one indirectly. */ /* ** Figure out what version of the code to use. The choices are ** ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The ** mutexes implementation cannot be overridden ** at start-time. ** ** SQLITE_MUTEX_NOOP For single-threaded applications. No ** mutual exclusion is provided. But this ** implementation can be overridden at ** start-time. ** ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. ** ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. */ #if !SQLITE_THREADSAFE # define SQLITE_MUTEX_OMIT #endif #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) # if SQLITE_OS_UNIX # define SQLITE_MUTEX_PTHREADS # elif SQLITE_OS_WIN # define SQLITE_MUTEX_W32 # else # define SQLITE_MUTEX_NOOP # endif #endif #ifdef SQLITE_MUTEX_OMIT /* ** If this is a no-op implementation, implement everything as macros. */ #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) #define sqlite3_mutex_free(X) #define sqlite3_mutex_enter(X) #define sqlite3_mutex_try(X) SQLITE_OK #define sqlite3_mutex_leave(X) #define sqlite3_mutex_held(X) ((void)(X),1) #define sqlite3_mutex_notheld(X) ((void)(X),1) #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) #define sqlite3MutexInit() SQLITE_OK #define sqlite3MutexEnd() #define MUTEX_LOGIC(X) #else #define MUTEX_LOGIC(X) X #endif /* defined(SQLITE_MUTEX_OMIT) */ /************** End of mutex.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default ** synchronous setting to EXTRA. It is no longer supported. */ #ifdef SQLITE_EXTRA_DURABLE # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE # define SQLITE_DEFAULT_SYNCHRONOUS 3 #endif /* ** Default synchronous levels. ** ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1. ** ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS ** OFF 1 0 ** NORMAL 2 1 ** FULL 3 2 ** EXTRA 4 3 ** ** The "PRAGMA synchronous" statement also uses the zero-based numbers. ** In other words, the zero-based numbers are used for all external interfaces ** and the one-based values are used internally. */ #ifndef SQLITE_DEFAULT_SYNCHRONOUS # define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1) #endif #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS #endif /* ** Each database file to be accessed by the system is an instance ** of the following structure. There are normally two of these structures ** in the sqlite.aDb[] array. aDb[0] is the main database file and ** aDb[1] is the database file used to hold temporary tables. Additional ** databases may be attached. */ struct Db { char *zDbSName; /* Name of this database. (schema name, not filename) */ Btree *pBt; /* The B*Tree structure for this database file */ u8 safety_level; /* How aggressive at syncing data to disk */ u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */ Schema *pSchema; /* Pointer to database schema (possibly shared) */ }; /* ** An instance of the following structure stores a database schema. ** ** Most Schema objects are associated with a Btree. The exception is ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. ** In shared cache mode, a single Schema object can be shared by multiple ** Btrees that refer to the same underlying BtShared object. ** ** Schema objects are automatically deallocated when the last Btree that ** references them is destroyed. The TEMP Schema is manually freed by ** sqlite3_close(). * ** A thread must be holding a mutex on the corresponding Btree in order ** to access Schema content. This implies that the thread must also be ** holding a mutex on the sqlite3 connection pointer that owns the Btree. ** For a TEMP Schema, only the connection mutex is required. */ struct Schema { int schema_cookie; /* Database schema version number for this file */ int iGeneration; /* Generation counter. Incremented with each change */ Hash tblHash; /* All tables indexed by name */ Hash idxHash; /* All (named) indices indexed by name */ Hash trigHash; /* All triggers indexed by name */ Hash fkeyHash; /* All foreign keys by referenced table name */ Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ u8 file_format; /* Schema format version for this file */ u8 enc; /* Text encoding used by this database */ u16 schemaFlags; /* Flags associated with this schema */ int cache_size; /* Number of pages to use in the cache */ }; /* ** These macros can be used to test, set, or clear bits in the ** Db.pSchema->flags field. */ #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P)) #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0) #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P) #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P) /* ** Allowed values for the DB.pSchema->flags field. ** ** The DB_SchemaLoaded flag is set after the database schema has been ** read into internal hash tables. ** ** DB_UnresetViews means that one or more views have column names that ** have been filled out. If the schema changes, these column names might ** changes and so the view will need to be reset. */ #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ #define DB_UnresetViews 0x0002 /* Some views have defined column names */ #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ /* ** The number of different kinds of things that can be limited ** using the sqlite3_limit() interface. */ #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1) /* ** Lookaside malloc is a set of fixed-size buffers that can be used ** to satisfy small transient memory allocation requests for objects ** associated with a particular database connection. The use of ** lookaside malloc provides a significant performance enhancement ** (approx 10%) by avoiding numerous malloc/free requests while parsing ** SQL statements. ** ** The Lookaside structure holds configuration information about the ** lookaside malloc subsystem. Each available memory allocation in ** the lookaside subsystem is stored on a linked list of LookasideSlot ** objects. ** ** Lookaside allocations are only allowed for objects that are associated ** with a particular database connection. Hence, schema information cannot ** be stored in lookaside because in shared cache mode the schema information ** is shared by multiple database connections. Therefore, while parsing ** schema information, the Lookaside.bEnabled flag is cleared so that ** lookaside allocations are not used to construct the schema objects. */ struct Lookaside { u32 bDisable; /* Only operate the lookaside when zero */ u16 sz; /* Size of each buffer in bytes */ u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ int nOut; /* Number of buffers currently checked out */ int mxOut; /* Highwater mark for nOut */ int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ LookasideSlot *pFree; /* List of available buffers */ void *pStart; /* First byte of available memory space */ void *pEnd; /* First byte past end of available space */ }; struct LookasideSlot { LookasideSlot *pNext; /* Next buffer in the list of free buffers */ }; /* ** A hash table for built-in function definitions. (Application-defined ** functions use a regular table table from hash.h.) ** ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. ** Collisions are on the FuncDef.u.pHash chain. */ #define SQLITE_FUNC_HASH_SZ 23 struct FuncDefHash { FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */ }; #ifdef SQLITE_USER_AUTHENTICATION /* ** Information held in the "sqlite3" database connection object and used ** to manage user authentication. */ typedef struct sqlite3_userauth sqlite3_userauth; struct sqlite3_userauth { u8 authLevel; /* Current authentication level */ int nAuthPW; /* Size of the zAuthPW in bytes */ char *zAuthPW; /* Password used to authenticate */ char *zAuthUser; /* User name used to authenticate */ }; /* Allowed values for sqlite3_userauth.authLevel */ #define UAUTH_Unknown 0 /* Authentication not yet checked */ #define UAUTH_Fail 1 /* User authentication failed */ #define UAUTH_User 2 /* Authenticated as a normal user */ #define UAUTH_Admin 3 /* Authenticated as an administrator */ /* Functions used only by user authorization logic */ SQLITE_PRIVATE int sqlite3UserAuthTable(const char*); SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*); SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*); SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**); #endif /* SQLITE_USER_AUTHENTICATION */ /* ** typedef for the authorization callback function. */ #ifdef SQLITE_USER_AUTHENTICATION typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, const char*, const char*); #else typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, const char*); #endif #ifndef SQLITE_OMIT_DEPRECATED /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing ** in the style of sqlite3_trace() */ #define SQLITE_TRACE_LEGACY 0x80 #else #define SQLITE_TRACE_LEGACY 0 #endif /* SQLITE_OMIT_DEPRECATED */ /* ** Each database connection is an instance of the following structure. */ struct sqlite3 { sqlite3_vfs *pVfs; /* OS Interface */ struct Vdbe *pVdbe; /* List of active virtual machines */ CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ sqlite3_mutex *mutex; /* Connection mutex */ Db *aDb; /* All backends */ int nDb; /* Number of backends currently in use */ int flags; /* Miscellaneous flags. See below */ i64 lastRowid; /* ROWID of most recent insert (see above) */ i64 szMmap; /* Default mmap_size setting */ unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ int errCode; /* Most recent error code (SQLITE_*) */ int errMask; /* & result codes with this before returning */ int iSysErrno; /* Errno value from last system error */ u16 dbOptFlags; /* Flags to enable/disable optimizations */ u8 enc; /* Text encoding */ u8 autoCommit; /* The auto-commit flag. */ u8 temp_store; /* 1: file 2: memory 0: default */ u8 mallocFailed; /* True if we have seen a malloc failure */ u8 bBenignMalloc; /* Do not require OOMs if true */ u8 dfltLockMode; /* Default locking-mode for attached dbs */ signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ u8 suppressErr; /* Do not issue error messages if true */ u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ u8 mTrace; /* zero or more SQLITE_TRACE flags */ u8 skipBtreeMutex; /* True if no shared-cache backends */ int nextPagesize; /* Pagesize after VACUUM if >0 */ u32 magic; /* Magic number for detect library misuse */ int nChange; /* Value returned by sqlite3_changes() */ int nTotalChange; /* Value returned by sqlite3_total_changes() */ int aLimit[SQLITE_N_LIMIT]; /* Limits */ int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */ struct sqlite3InitInfo { /* Information used during initialization */ int newTnum; /* Rootpage of table being initialized */ u8 iDb; /* Which db file is being initialized */ u8 busy; /* TRUE if currently initializing */ u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ u8 imposterTable; /* Building an imposter table */ } init; int nVdbeActive; /* Number of VDBEs currently running */ int nVdbeRead; /* Number of active VDBEs that read or write */ int nVdbeWrite; /* Number of active VDBEs that read and write */ int nVdbeExec; /* Number of nested calls to VdbeExec() */ int nVDestroy; /* Number of active OP_VDestroy operations */ int nExtension; /* Number of loaded extensions */ void **aExtension; /* Array of shared library handles */ int (*xTrace)(u32,void*,void*,void*); /* Trace function */ void *pTraceArg; /* Argument to the trace function */ void (*xProfile)(void*,const char*,u64); /* Profiling function */ void *pProfileArg; /* Argument to profile function */ void *pCommitArg; /* Argument to xCommitCallback() */ int (*xCommitCallback)(void*); /* Invoked at every commit. */ void *pRollbackArg; /* Argument to xRollbackCallback() */ void (*xRollbackCallback)(void*); /* Invoked at every commit. */ void *pUpdateArg; void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK void *pPreUpdateArg; /* First argument to xPreUpdateCallback */ void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64 ); PreUpdate *pPreUpdate; /* Context for active pre-update callback */ #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifndef SQLITE_OMIT_WAL int (*xWalCallback)(void *, sqlite3 *, const char *, int); void *pWalArg; #endif void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); void *pCollNeededArg; sqlite3_value *pErr; /* Most recent error message */ union { volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ double notUsed1; /* Spacer */ } u1; Lookaside lookaside; /* Lookaside malloc configuration */ #ifndef SQLITE_OMIT_AUTHORIZATION sqlite3_xauth xAuth; /* Access authorization function */ void *pAuthArg; /* 1st argument to the access auth function */ #endif #ifndef SQLITE_OMIT_PROGRESS_CALLBACK int (*xProgress)(void *); /* The progress callback */ void *pProgressArg; /* Argument to the progress callback */ unsigned nProgressOps; /* Number of opcodes for progress callback */ #endif #ifndef SQLITE_OMIT_VIRTUALTABLE int nVTrans; /* Allocated size of aVTrans */ Hash aModule; /* populated by sqlite3_create_module() */ VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ VTable **aVTrans; /* Virtual tables with open transactions */ VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ #endif Hash aFunc; /* Hash table of connection functions */ Hash aCollSeq; /* All collating sequences */ BusyHandler busyHandler; /* Busy callback */ Db aDbStatic[2]; /* Static space for the 2 default backends */ Savepoint *pSavepoint; /* List of active savepoints */ int busyTimeout; /* Busy handler timeout, in msec */ int nSavepoint; /* Number of non-transaction savepoints */ int nStatement; /* Number of nested statement-transactions */ i64 nDeferredCons; /* Net deferred constraints this transaction. */ i64 nDeferredImmCons; /* Net deferred immediate constraints */ int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY /* The following variables are all protected by the STATIC_MASTER ** mutex, not by sqlite3.mutex. They are used by code in notify.c. ** ** When X.pUnlockConnection==Y, that means that X is waiting for Y to ** unlock so that it can proceed. ** ** When X.pBlockingConnection==Y, that means that something that X tried ** tried to do recently failed with an SQLITE_LOCKED error due to locks ** held by Y. */ sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ void *pUnlockArg; /* Argument to xUnlockNotify */ void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ #endif #ifdef SQLITE_USER_AUTHENTICATION sqlite3_userauth auth; /* User authentication information */ #endif }; /* ** A macro to discover the encoding of a database. */ #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc) #define ENC(db) ((db)->enc) /* ** Possible values for the sqlite3.flags. ** ** Value constraints (enforced via assert()): ** SQLITE_FullFSync == PAGER_FULLFSYNC ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC ** SQLITE_CacheSpill == PAGER_CACHE_SPILL */ #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */ #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */ #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */ #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */ #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */ #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ /* DELETE, or UPDATE and return */ /* the count using a callback. */ #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ /* result set is empty */ #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */ #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */ #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */ #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */ #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */ #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */ #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */ #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */ #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */ #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */ #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */ #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */ #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */ #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */ #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */ #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */ #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */ #define SQLITE_NoCkptOnClose 0x80000000 /* No checkpoint on close()/DETACH */ /* ** Bits of the sqlite3.dbOptFlags field that are used by the ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to ** selectively disable various optimizations. */ #define SQLITE_QueryFlattener 0x0001 /* Query flattening */ #define SQLITE_ColumnCache 0x0002 /* Column cache */ #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */ #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */ /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */ #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */ #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */ #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */ #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */ #define SQLITE_Transitive 0x0200 /* Transitive constraints */ #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */ #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */ #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */ #define SQLITE_AllOpts 0xffff /* All optimizations */ /* ** Macros for testing whether or not optimizations are enabled or disabled. */ #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0) #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0) /* ** Return true if it OK to factor constant expressions into the initialization ** code. The argument is a Parse object for the code generator. */ #define ConstFactorOk(P) ((P)->okConstFactor) /* ** Possible values for the sqlite.magic field. ** The numbers are obtained at random and have no special meaning, other ** than being distinct from one another. */ #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */ /* ** Each SQL function is defined by an instance of the following ** structure. For global built-in functions (ex: substr(), max(), count()) ** a pointer to this structure is held in the sqlite3BuiltinFunctions object. ** For per-connection application-defined functions, a pointer to this ** structure is held in the db->aHash hash table. ** ** The u.pHash field is used by the global built-ins. The u.pDestructor ** field is used by per-connection app-def functions. */ struct FuncDef { i8 nArg; /* Number of arguments. -1 means unlimited */ u16 funcFlags; /* Some combination of SQLITE_FUNC_* */ void *pUserData; /* User data parameter */ FuncDef *pNext; /* Next function with same name */ void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */ void (*xFinalize)(sqlite3_context*); /* Agg finalizer */ const char *zName; /* SQL name of the function. */ union { FuncDef *pHash; /* Next with a different name but the same hash */ FuncDestructor *pDestructor; /* Reference counted destructor function */ } u; }; /* ** This structure encapsulates a user-function destructor callback (as ** configured using create_function_v2()) and a reference counter. When ** create_function_v2() is called to create a function with a destructor, ** a single object of this type is allocated. FuncDestructor.nRef is set to ** the number of FuncDef objects created (either 1 or 3, depending on whether ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor ** member of each of the new FuncDef objects is set to point to the allocated ** FuncDestructor. ** ** Thereafter, when one of the FuncDef objects is deleted, the reference ** count on this object is decremented. When it reaches 0, the destructor ** is invoked and the FuncDestructor structure freed. */ struct FuncDestructor { int nRef; void (*xDestroy)(void *); void *pUserData; }; /* ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There ** are assert() statements in the code to verify this. ** ** Value constraints (enforced via assert()): ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API */ #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */ #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */ #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */ #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */ #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/ #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */ #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */ #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */ #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */ #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */ #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */ #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */ #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a ** single query - might change over time */ #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */ /* ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are ** used to create the initializers for the FuncDef structures. ** ** FUNCTION(zName, nArg, iArg, bNC, xFunc) ** Used to create a scalar function definition of a function zName ** implemented by C function xFunc that accepts nArg arguments. The ** value passed as iArg is cast to a (void*) and made available ** as the user-data (sqlite3_user_data()) for the function. If ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. ** ** VFUNCTION(zName, nArg, iArg, bNC, xFunc) ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag. ** ** DFUNCTION(zName, nArg, iArg, bNC, xFunc) ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions ** and functions like sqlite_version() that can change, but not during ** a single query. ** ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) ** Used to create an aggregate function definition implemented by ** the C functions xStep and xFinal. The first four parameters ** are interpreted in the same way as the first 4 parameters to ** FUNCTION(). ** ** LIKEFUNC(zName, nArg, pArg, flags) ** Used to create a scalar function definition of a function zName ** that accepts nArg arguments and is implemented by a call to C ** function likeFunc. Argument pArg is cast to a (void *) and made ** available as the function user-data (sqlite3_user_data()). The ** FuncDef.flags variable is set to the value passed as the flags ** parameter. */ #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \ {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ pArg, 0, xFunc, 0, #zName, } #define LIKEFUNC(zName, nArg, arg, flags) \ {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \ (void *)arg, 0, likeFunc, 0, #zName, {0} } #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \ SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}} #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \ {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \ SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}} /* ** All current savepoints are stored in a linked list starting at ** sqlite3.pSavepoint. The first element in the list is the most recently ** opened savepoint. Savepoints are added to the list by the vdbe ** OP_Savepoint instruction. */ struct Savepoint { char *zName; /* Savepoint name (nul-terminated) */ i64 nDeferredCons; /* Number of deferred fk violations */ i64 nDeferredImmCons; /* Number of deferred imm fk. */ Savepoint *pNext; /* Parent savepoint (if any) */ }; /* ** The following are used as the second parameter to sqlite3Savepoint(), ** and as the P1 argument to the OP_Savepoint instruction. */ #define SAVEPOINT_BEGIN 0 #define SAVEPOINT_RELEASE 1 #define SAVEPOINT_ROLLBACK 2 /* ** Each SQLite module (virtual table definition) is defined by an ** instance of the following structure, stored in the sqlite3.aModule ** hash table. */ struct Module { const sqlite3_module *pModule; /* Callback pointers */ const char *zName; /* Name passed to create_module() */ void *pAux; /* pAux passed to create_module() */ void (*xDestroy)(void *); /* Module destructor function */ Table *pEpoTab; /* Eponymous table for this module */ }; /* ** information about each column of an SQL table is held in an instance ** of this structure. */ struct Column { char *zName; /* Name of this column, \000, then the type */ Expr *pDflt; /* Default value of this column */ char *zColl; /* Collating sequence. If NULL, use the default */ u8 notNull; /* An OE_ code for handling a NOT NULL constraint */ char affinity; /* One of the SQLITE_AFF_... values */ u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */ u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */ }; /* Allowed values for Column.colFlags: */ #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */ /* ** A "Collating Sequence" is defined by an instance of the following ** structure. Conceptually, a collating sequence consists of a name and ** a comparison routine that defines the order of that sequence. ** ** If CollSeq.xCmp is NULL, it means that the ** collating sequence is undefined. Indices built on an undefined ** collating sequence may not be read or written. */ struct CollSeq { char *zName; /* Name of the collating sequence, UTF-8 encoded */ u8 enc; /* Text encoding handled by xCmp() */ void *pUser; /* First argument to xCmp() */ int (*xCmp)(void*,int, const void*, int, const void*); void (*xDel)(void*); /* Destructor for pUser */ }; /* ** A sort order can be either ASC or DESC. */ #define SQLITE_SO_ASC 0 /* Sort in ascending order */ #define SQLITE_SO_DESC 1 /* Sort in ascending order */ #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */ /* ** Column affinity types. ** ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve ** the speed a little by numbering the values consecutively. ** ** But rather than start with 0 or 1, we begin with 'A'. That way, ** when multiple affinity types are concatenated into a string and ** used as the P4 operand, they will be more readable. ** ** Note also that the numeric types are grouped together so that testing ** for a numeric type is a single comparison. And the BLOB type is first. */ #define SQLITE_AFF_BLOB 'A' #define SQLITE_AFF_TEXT 'B' #define SQLITE_AFF_NUMERIC 'C' #define SQLITE_AFF_INTEGER 'D' #define SQLITE_AFF_REAL 'E' #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) /* ** The SQLITE_AFF_MASK values masks off the significant bits of an ** affinity value. */ #define SQLITE_AFF_MASK 0x47 /* ** Additional bit values that can be ORed with an affinity without ** changing the affinity. ** ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL. ** It causes an assert() to fire if either operand to a comparison ** operator is NULL. It is added to certain comparison operators to ** prove that the operands are always NOT NULL. */ #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */ #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */ #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */ #define SQLITE_NULLEQ 0x80 /* NULL=NULL */ #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */ /* ** An object of this type is created for each virtual table present in ** the database schema. ** ** If the database schema is shared, then there is one instance of this ** structure for each database connection (sqlite3*) that uses the shared ** schema. This is because each database connection requires its own unique ** instance of the sqlite3_vtab* handle used to access the virtual table ** implementation. sqlite3_vtab* handles can not be shared between ** database connections, even when the rest of the in-memory database ** schema is shared, as the implementation often stores the database ** connection handle passed to it via the xConnect() or xCreate() method ** during initialization internally. This database connection handle may ** then be used by the virtual table implementation to access real tables ** within the database. So that they appear as part of the callers ** transaction, these accesses need to be made via the same database ** connection as that used to execute SQL operations on the virtual table. ** ** All VTable objects that correspond to a single table in a shared ** database schema are initially stored in a linked-list pointed to by ** the Table.pVTable member variable of the corresponding Table object. ** When an sqlite3_prepare() operation is required to access the virtual ** table, it searches the list for the VTable that corresponds to the ** database connection doing the preparing so as to use the correct ** sqlite3_vtab* handle in the compiled query. ** ** When an in-memory Table object is deleted (for example when the ** schema is being reloaded for some reason), the VTable objects are not ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed ** immediately. Instead, they are moved from the Table.pVTable list to ** another linked list headed by the sqlite3.pDisconnect member of the ** corresponding sqlite3 structure. They are then deleted/xDisconnected ** next time a statement is prepared using said sqlite3*. This is done ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. ** Refer to comments above function sqlite3VtabUnlockList() for an ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect ** list without holding the corresponding sqlite3.mutex mutex. ** ** The memory for objects of this type is always allocated by ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as ** the first argument. */ struct VTable { sqlite3 *db; /* Database connection associated with this table */ Module *pMod; /* Pointer to module implementation */ sqlite3_vtab *pVtab; /* Pointer to vtab instance */ int nRef; /* Number of pointers to this structure */ u8 bConstraint; /* True if constraints are supported */ int iSavepoint; /* Depth of the SAVEPOINT stack */ VTable *pNext; /* Next in linked list (see above) */ }; /* ** The schema for each SQL table and view is represented in memory ** by an instance of the following structure. */ struct Table { char *zName; /* Name of the table or view */ Column *aCol; /* Information about each column */ Index *pIndex; /* List of SQL indexes on this table. */ Select *pSelect; /* NULL for tables. Points to definition if a view. */ FKey *pFKey; /* Linked list of all foreign keys in this table */ char *zColAff; /* String defining the affinity of each column */ ExprList *pCheck; /* All CHECK constraints */ /* ... also used as column name list in a VIEW */ int tnum; /* Root BTree page for this table */ u32 nTabRef; /* Number of pointers to this Table */ i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */ i16 nCol; /* Number of columns in this table */ LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */ LogEst szTabRow; /* Estimated size of each table row in bytes */ #ifdef SQLITE_ENABLE_COSTMULT LogEst costMult; /* Cost multiplier for using this table */ #endif u8 tabFlags; /* Mask of TF_* values */ u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ #ifndef SQLITE_OMIT_ALTERTABLE int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ #endif #ifndef SQLITE_OMIT_VIRTUALTABLE int nModuleArg; /* Number of arguments to the module */ char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */ VTable *pVTable; /* List of VTable objects. */ #endif Trigger *pTrigger; /* List of triggers stored in pSchema */ Schema *pSchema; /* Schema that contains this table */ Table *pNextZombie; /* Next on the Parse.pZombieTab list */ }; /* ** Allowed values for Table.tabFlags. ** ** TF_OOOHidden applies to tables or view that have hidden columns that are ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden, ** the TF_OOOHidden attribute would apply in this case. Such tables require ** special handling during INSERT processing. */ #define TF_Readonly 0x01 /* Read-only system table */ #define TF_Ephemeral 0x02 /* An ephemeral table */ #define TF_HasPrimaryKey 0x04 /* Table has a primary key */ #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ #define TF_Virtual 0x10 /* Is a virtual table */ #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */ #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */ #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */ /* ** Test to see whether or not a table is a virtual table. This is ** done as a macro so that it will be optimized out when virtual ** table support is omitted from the build. */ #ifndef SQLITE_OMIT_VIRTUALTABLE # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) #else # define IsVirtual(X) 0 #endif /* ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn() ** only works for non-virtual tables (ordinary tables and views) and is ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The ** IsHiddenColumn() macro is general purpose. */ #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS) # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) #elif !defined(SQLITE_OMIT_VIRTUALTABLE) # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) # define IsOrdinaryHiddenColumn(X) 0 #else # define IsHiddenColumn(X) 0 # define IsOrdinaryHiddenColumn(X) 0 #endif /* Does the table have a rowid */ #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0) #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0) /* ** Each foreign key constraint is an instance of the following structure. ** ** A foreign key is associated with two tables. The "from" table is ** the table that contains the REFERENCES clause that creates the foreign ** key. The "to" table is the table that is named in the REFERENCES clause. ** Consider this example: ** ** CREATE TABLE ex1( ** a INTEGER PRIMARY KEY, ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) ** ); ** ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". ** Equivalent names: ** ** from-table == child-table ** to-table == parent-table ** ** Each REFERENCES clause generates an instance of the following structure ** which is attached to the from-table. The to-table need not exist when ** the from-table is created. The existence of the to-table is not checked. ** ** The list of all parents for child Table X is held at X.pFKey. ** ** A list of all children for a table named Z (which might not even exist) ** is held in Schema.fkeyHash with a hash key of Z. */ struct FKey { Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */ char *zTo; /* Name of table that the key points to (aka: Parent) */ FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */ FKey *pPrevTo; /* Previous with the same zTo */ int nCol; /* Number of columns in this key */ /* EV: R-30323-21917 */ u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ Trigger *apTrigger[2];/* Triggers for aAction[] actions */ struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ int iFrom; /* Index of column in pFrom */ char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */ } aCol[1]; /* One entry for each of nCol columns */ }; /* ** SQLite supports many different ways to resolve a constraint ** error. ROLLBACK processing means that a constraint violation ** causes the operation in process to fail and for the current transaction ** to be rolled back. ABORT processing means the operation in process ** fails and any prior changes from that one operation are backed out, ** but the transaction is not rolled back. FAIL processing means that ** the operation in progress stops and returns an error code. But prior ** changes due to the same operation are not backed out and no rollback ** occurs. IGNORE means that the particular row that caused the constraint ** error is not inserted or updated. Processing continues and no error ** is returned. REPLACE means that preexisting database rows that caused ** a UNIQUE constraint violation are removed so that the new insert or ** update can proceed. Processing continues and no error is reported. ** ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the ** referenced table row is propagated into the row that holds the ** foreign key. ** ** The following symbolic values are used to record which type ** of action to take. */ #define OE_None 0 /* There is no constraint to check */ #define OE_Rollback 1 /* Fail the operation and rollback the transaction */ #define OE_Abort 2 /* Back out changes but do no rollback transaction */ #define OE_Fail 3 /* Stop the operation but leave all prior changes */ #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ #define OE_SetNull 7 /* Set the foreign key value to NULL */ #define OE_SetDflt 8 /* Set the foreign key value to its default */ #define OE_Cascade 9 /* Cascade the changes */ #define OE_Default 10 /* Do whatever the default action is */ /* ** An instance of the following structure is passed as the first ** argument to sqlite3VdbeKeyCompare and is used to control the ** comparison of the two index keys. ** ** Note that aSortOrder[] and aColl[] have nField+1 slots. There ** are nField slots for the columns of an index then one extra slot ** for the rowid at the end. */ struct KeyInfo { u32 nRef; /* Number of references to this KeyInfo object */ u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ u16 nField; /* Number of key columns in the index */ u16 nXField; /* Number of columns beyond the key columns */ sqlite3 *db; /* The database connection */ u8 *aSortOrder; /* Sort order for each column. */ CollSeq *aColl[1]; /* Collating sequence for each term of the key */ }; /* ** This object holds a record which has been parsed out into individual ** fields, for the purposes of doing a comparison. ** ** A record is an object that contains one or more fields of data. ** Records are used to store the content of a table row and to store ** the key of an index. A blob encoding of a record is created by ** the OP_MakeRecord opcode of the VDBE and is disassembled by the ** OP_Column opcode. ** ** An instance of this object serves as a "key" for doing a search on ** an index b+tree. The goal of the search is to find the entry that ** is closed to the key described by this object. This object might hold ** just a prefix of the key. The number of fields is given by ** pKeyInfo->nField. ** ** The r1 and r2 fields are the values to return if this key is less than ** or greater than a key in the btree, respectively. These are normally ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree ** is in DESC order. ** ** The key comparison functions actually return default_rc when they find ** an equals comparison. default_rc can be -1, 0, or +1. If there are ** multiple entries in the b-tree with the same key (when only looking ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to ** cause the search to find the last match, or +1 to cause the search to ** find the first match. ** ** The key comparison functions will set eqSeen to true if they ever ** get and equal results when comparing this structure to a b-tree record. ** When default_rc!=0, the search might end up on the record immediately ** before the first match or immediately after the last match. The ** eqSeen field will indicate whether or not an exact match exists in the ** b-tree. */ struct UnpackedRecord { KeyInfo *pKeyInfo; /* Collation and sort-order information */ Mem *aMem; /* Values */ u16 nField; /* Number of entries in apMem[] */ i8 default_rc; /* Comparison result if keys are equal */ u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */ i8 r1; /* Value to return if (lhs > rhs) */ i8 r2; /* Value to return if (rhs < lhs) */ u8 eqSeen; /* True if an equality comparison has been seen */ }; /* ** Each SQL index is represented in memory by an ** instance of the following structure. ** ** The columns of the table that are to be indexed are described ** by the aiColumn[] field of this structure. For example, suppose ** we have the following table and index: ** ** CREATE TABLE Ex1(c1 int, c2 int, c3 text); ** CREATE INDEX Ex2 ON Ex1(c3,c1); ** ** In the Table structure describing Ex1, nCol==3 because there are ** three columns in the table. In the Index structure describing ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. ** The second column to be indexed (c1) has an index of 0 in ** Ex1.aCol[], hence Ex2.aiColumn[1]==0. ** ** The Index.onError field determines whether or not the indexed columns ** must be unique and what to do if they are not. When Index.onError=OE_None, ** it means this is not a unique index. Otherwise it is a unique index ** and the value of Index.onError indicate the which conflict resolution ** algorithm to employ whenever an attempt is made to insert a non-unique ** element. ** ** While parsing a CREATE TABLE or CREATE INDEX statement in order to ** generate VDBE code (as opposed to parsing one read from an sqlite_master ** table as part of parsing an existing database schema), transient instances ** of this structure may be created. In this case the Index.tnum variable is ** used to store the address of a VDBE instruction, not a database page ** number (it cannot - the database page is not allocated until the VDBE ** program is executed). See convertToWithoutRowidTable() for details. */ struct Index { char *zName; /* Name of this index */ i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */ LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */ Table *pTable; /* The SQL table being indexed */ char *zColAff; /* String defining the affinity of each column */ Index *pNext; /* The next index associated with the same table */ Schema *pSchema; /* Schema containing this index */ u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ const char **azColl; /* Array of collation sequence names for index */ Expr *pPartIdxWhere; /* WHERE clause for partial indices */ ExprList *aColExpr; /* Column expressions */ int tnum; /* DB Page containing root of this index */ LogEst szIdxRow; /* Estimated average row size in bytes */ u16 nKeyCol; /* Number of columns forming the key */ u16 nColumn; /* Number of columns stored in the index */ u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ unsigned bUnordered:1; /* Use this index for == or IN queries only */ unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */ unsigned isResized:1; /* True if resizeIndexObject() has been called */ unsigned isCovering:1; /* True if this is a covering index */ unsigned noSkipScan:1; /* Do not try to use skip-scan if true */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int nSample; /* Number of elements in aSample[] */ int nSampleCol; /* Size of IndexSample.anEq[] and so on */ tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */ IndexSample *aSample; /* Samples of the left-most key */ tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */ tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */ #endif }; /* ** Allowed values for Index.idxType */ #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */ #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */ #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */ /* Return true if index X is a PRIMARY KEY index */ #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY) /* Return true if index X is a UNIQUE index */ #define IsUniqueIndex(X) ((X)->onError!=OE_None) /* The Index.aiColumn[] values are normally positive integer. But ** there are some negative values that have special meaning: */ #define XN_ROWID (-1) /* Indexed column is the rowid */ #define XN_EXPR (-2) /* Indexed column is an expression */ /* ** Each sample stored in the sqlite_stat3 table is represented in memory ** using a structure of this type. See documentation at the top of the ** analyze.c source file for additional information. */ struct IndexSample { void *p; /* Pointer to sampled record */ int n; /* Size of record in bytes */ tRowcnt *anEq; /* Est. number of rows where the key equals this sample */ tRowcnt *anLt; /* Est. number of rows where key is less than this sample */ tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */ }; /* ** Each token coming out of the lexer is an instance of ** this structure. Tokens are also used as part of an expression. ** ** Note if Token.z==0 then Token.dyn and Token.n are undefined and ** may contain random values. Do not make any assumptions about Token.dyn ** and Token.n when Token.z==0. */ struct Token { const char *z; /* Text of the token. Not NULL-terminated! */ unsigned int n; /* Number of characters in this token */ }; /* ** An instance of this structure contains information needed to generate ** code for a SELECT that contains aggregate functions. ** ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a ** pointer to this structure. The Expr.iColumn field is the index in ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate ** code for that node. ** ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the ** original Select structure that describes the SELECT statement. These ** fields do not need to be freed when deallocating the AggInfo structure. */ struct AggInfo { u8 directMode; /* Direct rendering mode means take data directly ** from source tables rather than from accumulators */ u8 useSortingIdx; /* In direct mode, reference the sorting index rather ** than the source table */ int sortingIdx; /* Cursor number of the sorting index */ int sortingIdxPTab; /* Cursor number of pseudo-table */ int nSortingColumn; /* Number of columns in the sorting index */ int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */ ExprList *pGroupBy; /* The group by clause */ struct AggInfo_col { /* For each column used in source tables */ Table *pTab; /* Source table */ int iTable; /* Cursor number of the source table */ int iColumn; /* Column number within the source table */ int iSorterColumn; /* Column number in the sorting index */ int iMem; /* Memory location that acts as accumulator */ Expr *pExpr; /* The original expression */ } *aCol; int nColumn; /* Number of used entries in aCol[] */ int nAccumulator; /* Number of columns that show through to the output. ** Additional columns are used only as parameters to ** aggregate functions */ struct AggInfo_func { /* For each aggregate function */ Expr *pExpr; /* Expression encoding the function */ FuncDef *pFunc; /* The aggregate function implementation */ int iMem; /* Memory location that acts as accumulator */ int iDistinct; /* Ephemeral table used to enforce DISTINCT */ } *aFunc; int nFunc; /* Number of entries in aFunc[] */ }; /* ** The datatype ynVar is a signed integer, either 16-bit or 32-bit. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater ** than 32767 we have to make it 32-bit. 16-bit is preferred because ** it uses less memory in the Expr object, which is a big memory user ** in systems with lots of prepared statements. And few applications ** need more than about 10 or 20 variables. But some extreme users want ** to have prepared statements with over 32767 variables, and for them ** the option is available (at compile-time). */ #if SQLITE_MAX_VARIABLE_NUMBER<=32767 typedef i16 ynVar; #else typedef int ynVar; #endif /* ** Each node of an expression in the parse tree is an instance ** of this structure. ** ** Expr.op is the opcode. The integer parser token codes are reused ** as opcodes here. For example, the parser defines TK_GE to be an integer ** code representing the ">=" operator. This same integer code is reused ** to represent the greater-than-or-equal-to operator in the expression ** tree. ** ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, ** or TK_STRING), then Expr.token contains the text of the SQL literal. If ** the expression is a variable (TK_VARIABLE), then Expr.token contains the ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), ** then Expr.token contains the name of the function. ** ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a ** binary operator. Either or both may be NULL. ** ** Expr.x.pList is a list of arguments if the expression is an SQL function, ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)". ** Expr.x.pSelect is used if the expression is a sub-select or an expression of ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is ** valid. ** ** An expression of the form ID or ID.ID refers to a column in a table. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is ** the integer cursor number of a VDBE cursor pointing to that table and ** Expr.iColumn is the column number for the specific column. If the ** expression is used as a result in an aggregate SELECT, then the ** value is also stored in the Expr.iAgg column in the aggregate so that ** it can be accessed after all aggregates are computed. ** ** If the expression is an unbound variable marker (a question mark ** character '?' in the original SQL) then the Expr.iTable holds the index ** number for that variable. ** ** If the expression is a subquery then Expr.iColumn holds an integer ** register number containing the result of the subquery. If the ** subquery gives a constant result, then iTable is -1. If the subquery ** gives a different answer at different times during statement processing ** then iTable is the address of a subroutine that computes the subquery. ** ** If the Expr is of type OP_Column, and the table it is selecting from ** is a disk table or the "old.*" pseudo-table, then pTab points to the ** corresponding table definition. ** ** ALLOCATION NOTES: ** ** Expr objects can use a lot of memory space in database schema. To ** help reduce memory requirements, sometimes an Expr object will be ** truncated. And to reduce the number of memory allocations, sometimes ** two or more Expr objects will be stored in a single memory allocation, ** together with Expr.zToken strings. ** ** If the EP_Reduced and EP_TokenOnly flags are set when ** an Expr object is truncated. When EP_Reduced is set, then all ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees ** are contained within the same memory allocation. Note, however, that ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately ** allocated, regardless of whether or not EP_Reduced is set. */ struct Expr { u8 op; /* Operation performed by this node */ char affinity; /* The affinity of the column or 0 if not a column */ u32 flags; /* Various flags. EP_* See below */ union { char *zToken; /* Token value. Zero terminated and dequoted */ int iValue; /* Non-negative integer value if EP_IntValue */ } u; /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no ** space is allocated for the fields below this point. An attempt to ** access them will result in a segfault or malfunction. *********************************************************************/ Expr *pLeft; /* Left subnode */ Expr *pRight; /* Right subnode */ union { ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */ Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */ } x; /* If the EP_Reduced flag is set in the Expr.flags mask, then no ** space is allocated for the fields below this point. An attempt to ** access them will result in a segfault or malfunction. *********************************************************************/ #if SQLITE_MAX_EXPR_DEPTH>0 int nHeight; /* Height of the tree headed by this node */ #endif int iTable; /* TK_COLUMN: cursor number of table holding column ** TK_REGISTER: register number ** TK_TRIGGER: 1 -> new, 0 -> old ** EP_Unlikely: 134217728 times likelihood ** TK_SELECT: 1st register of result vector */ ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid. ** TK_VARIABLE: variable number (always >= 1). ** TK_SELECT_COLUMN: column of the result vector */ i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */ i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */ u8 op2; /* TK_REGISTER: original value of Expr.op ** TK_COLUMN: the value of p5 for OP_Column ** TK_AGG_FUNCTION: nesting depth */ AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */ Table *pTab; /* Table for TK_COLUMN expressions. */ }; /* ** The following are the meanings of bits in the Expr.flags field. */ #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */ #define EP_Agg 0x000002 /* Contains one or more aggregate functions */ #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */ #define EP_Error 0x000008 /* Expression contains one or more errors */ #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */ #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */ #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */ #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */ #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */ #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */ #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */ #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */ #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */ #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */ #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */ #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */ #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */ #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */ #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */ #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */ #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */ #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */ #define EP_Alias 0x400000 /* Is an alias for a result set column */ #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */ /* ** Combinations of two or more EP_* flags */ #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */ /* ** These macros can be used to test, set, or clear bits in the ** Expr.flags field. */ #define ExprHasProperty(E,P) (((E)->flags&(P))!=0) #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P)) #define ExprSetProperty(E,P) (E)->flags|=(P) #define ExprClearProperty(E,P) (E)->flags&=~(P) /* The ExprSetVVAProperty() macro is used for Verification, Validation, ** and Accreditation only. It works like ExprSetProperty() during VVA ** processes but is a no-op for delivery. */ #ifdef SQLITE_DEBUG # define ExprSetVVAProperty(E,P) (E)->flags|=(P) #else # define ExprSetVVAProperty(E,P) #endif /* ** Macros to determine the number of bytes required by a normal Expr ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags ** and an Expr struct with the EP_TokenOnly flag set. */ #define EXPR_FULLSIZE sizeof(Expr) /* Full size */ #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */ #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */ /* ** Flags passed to the sqlite3ExprDup() function. See the header comment ** above sqlite3ExprDup() for details. */ #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */ /* ** A list of expressions. Each expression may optionally have a ** name. An expr/name combination can be used in several ways, such ** as the list of "expr AS ID" fields following a "SELECT" or in the ** list of "ID = expr" items in an UPDATE. A list of expressions can ** also be used as the argument to a function, in which case the a.zName ** field is not used. ** ** By default the Expr.zSpan field holds a human-readable description of ** the expression that is used in the generation of error messages and ** column labels. In this case, Expr.zSpan is typically the text of a ** column expression as it exists in a SELECT statement. However, if ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name ** of the result column in the form: DATABASE.TABLE.COLUMN. This later ** form is used for name resolution with nested FROM clauses. */ struct ExprList { int nExpr; /* Number of expressions on the list */ struct ExprList_item { /* For each expression in the list */ Expr *pExpr; /* The list of expressions */ char *zName; /* Token associated with this expression */ char *zSpan; /* Original text of the expression */ u8 sortOrder; /* 1 for DESC or 0 for ASC */ unsigned done :1; /* A flag to indicate when processing is finished */ unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */ unsigned reusable :1; /* Constant expression is reusable */ union { struct { u16 iOrderByCol; /* For ORDER BY, column number in result set */ u16 iAlias; /* Index into Parse.aAlias[] for zName */ } x; int iConstExprReg; /* Register in which Expr value is cached */ } u; } *a; /* Alloc a power of two greater or equal to nExpr */ }; /* ** An instance of this structure is used by the parser to record both ** the parse tree for an expression and the span of input text for an ** expression. */ struct ExprSpan { Expr *pExpr; /* The expression parse tree */ const char *zStart; /* First character of input text */ const char *zEnd; /* One character past the end of input text */ }; /* ** An instance of this structure can hold a simple list of identifiers, ** such as the list "a,b,c" in the following statements: ** ** INSERT INTO t(a,b,c) VALUES ...; ** CREATE INDEX idx ON t(a,b,c); ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...; ** ** The IdList.a.idx field is used when the IdList represents the list of ** column names after a table name in an INSERT statement. In the statement ** ** INSERT INTO t(a,b,c) ... ** ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k. */ struct IdList { struct IdList_item { char *zName; /* Name of the identifier */ int idx; /* Index in some Table.aCol[] of a column named zName */ } *a; int nId; /* Number of identifiers on the list */ }; /* ** The bitmask datatype defined below is used for various optimizations. ** ** Changing this from a 64-bit to a 32-bit type limits the number of ** tables in a join to 32 instead of 64. But it also reduces the size ** of the library by 738 bytes on ix86. */ #ifdef SQLITE_BITMASK_TYPE typedef SQLITE_BITMASK_TYPE Bitmask; #else typedef u64 Bitmask; #endif /* ** The number of bits in a Bitmask. "BMS" means "BitMask Size". */ #define BMS ((int)(sizeof(Bitmask)*8)) /* ** A bit in a Bitmask */ #define MASKBIT(n) (((Bitmask)1)<<(n)) #define MASKBIT32(n) (((unsigned int)1)<<(n)) #define ALLBITS ((Bitmask)-1) /* ** The following structure describes the FROM clause of a SELECT statement. ** Each table or subquery in the FROM clause is a separate element of ** the SrcList.a[] array. ** ** With the addition of multiple database support, the following structure ** can also be used to describe a particular table such as the table that ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL, ** such a table must be a simple name: ID. But in SQLite, the table can ** now be identified by a database name, a dot, then the table name: ID.ID. ** ** The jointype starts out showing the join type between the current table ** and the next table on the list. The parser builds the list this way. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each ** jointype expresses the join between the table and the previous table. ** ** In the colUsed field, the high-order bit (bit 63) is set if the table ** contains more than 63 columns and the 64-th or later column is used. */ struct SrcList { int nSrc; /* Number of tables or subqueries in the FROM clause */ u32 nAlloc; /* Number of entries allocated in a[] below */ struct SrcList_item { Schema *pSchema; /* Schema to which this item is fixed */ char *zDatabase; /* Name of database holding this table */ char *zName; /* Name of the table */ char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */ Table *pTab; /* An SQL table corresponding to zName */ Select *pSelect; /* A SELECT statement used in place of a table name */ int addrFillSub; /* Address of subroutine to manifest a subquery */ int regReturn; /* Register holding return address of addrFillSub */ int regResult; /* Registers holding results of a co-routine */ struct { u8 jointype; /* Type of join between this table and the previous */ unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */ unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */ unsigned isTabFunc :1; /* True if table-valued-function syntax */ unsigned isCorrelated :1; /* True if sub-query is correlated */ unsigned viaCoroutine :1; /* Implemented as a co-routine */ unsigned isRecursive :1; /* True for recursive reference in WITH */ } fg; #ifndef SQLITE_OMIT_EXPLAIN u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */ #endif int iCursor; /* The VDBE cursor number used to access this table */ Expr *pOn; /* The ON clause of a join */ IdList *pUsing; /* The USING clause of a join */ Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */ union { char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */ ExprList *pFuncArg; /* Arguments to table-valued-function */ } u1; Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */ } a[1]; /* One entry for each identifier on the list */ }; /* ** Permitted values of the SrcList.a.jointype field */ #define JT_INNER 0x0001 /* Any kind of inner or cross join */ #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */ #define JT_NATURAL 0x0004 /* True for a "natural" join */ #define JT_LEFT 0x0008 /* Left outer join */ #define JT_RIGHT 0x0010 /* Right outer join */ #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */ #define JT_ERROR 0x0040 /* unknown or unsupported join type */ /* ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin() ** and the WhereInfo.wctrlFlags member. ** ** Value constraints (enforced via assert()): ** WHERE_USE_LIMIT == SF_FixedLimit */ #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */ #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */ #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */ #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */ #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */ #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */ #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of ** the OR optimization */ #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */ #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */ #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */ #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */ #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */ #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */ #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */ /* 0x2000 not currently used */ #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */ /* 0x8000 not currently used */ /* Allowed return values from sqlite3WhereIsDistinct() */ #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */ #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */ #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */ #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */ /* ** A NameContext defines a context in which to resolve table and column ** names. The context consists of a list of tables (the pSrcList) field and ** a list of named expression (pEList). The named expression list may ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or ** to the table being operated on by INSERT, UPDATE, or DELETE. The ** pEList corresponds to the result set of a SELECT and is NULL for ** other statements. ** ** NameContexts can be nested. When resolving names, the inner-most ** context is searched first. If no match is found, the next outer ** context is checked. If there is still no match, the next context ** is checked. This process continues until either a match is found ** or all contexts are check. When a match is found, the nRef member of ** the context containing the match is incremented. ** ** Each subquery gets a new NameContext. The pNext field points to the ** NameContext in the parent query. Thus the process of scanning the ** NameContext list corresponds to searching through successively outer ** subqueries looking for a match. */ struct NameContext { Parse *pParse; /* The parser */ SrcList *pSrcList; /* One or more tables used to resolve names */ ExprList *pEList; /* Optional list of result-set columns */ AggInfo *pAggInfo; /* Information about aggregates at this level */ NameContext *pNext; /* Next outer name context. NULL for outermost */ int nRef; /* Number of names resolved by this context */ int nErr; /* Number of errors encountered while resolving names */ u16 ncFlags; /* Zero or more NC_* flags defined below */ }; /* ** Allowed values for the NameContext, ncFlags field. ** ** Value constraints (all checked via assert()): ** NC_HasAgg == SF_HasAgg ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX ** */ #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */ #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */ #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */ #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */ #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */ #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */ #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */ #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */ /* ** An instance of the following structure contains all information ** needed to generate code for a single SELECT statement. ** ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0. ** If there is a LIMIT clause, the parser sets nLimit to the value of the ** limit and nOffset to the value of the offset (or 0 if there is not ** offset). But later on, nLimit and nOffset become the memory locations ** in the VDBE that record the limit and offset counters. ** ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. ** These addresses must be stored so that we can go back and fill in ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor ** the number of columns in P2 can be computed at the same time ** as the OP_OpenEphm instruction is coded because not ** enough information about the compound query is known at that point. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating ** sequences for the ORDER BY clause. */ struct Select { ExprList *pEList; /* The fields of the result */ u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */ LogEst nSelectRow; /* Estimated number of result rows */ u32 selFlags; /* Various SF_* values */ int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ #if SELECTTRACE_ENABLED char zSelName[12]; /* Symbolic name of this SELECT use for debugging */ #endif int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */ SrcList *pSrc; /* The FROM clause */ Expr *pWhere; /* The WHERE clause */ ExprList *pGroupBy; /* The GROUP BY clause */ Expr *pHaving; /* The HAVING clause */ ExprList *pOrderBy; /* The ORDER BY clause */ Select *pPrior; /* Prior select in a compound select statement */ Select *pNext; /* Next select to the left in a compound */ Expr *pLimit; /* LIMIT expression. NULL means not used. */ Expr *pOffset; /* OFFSET expression. NULL means not used. */ With *pWith; /* WITH clause attached to this select. Or NULL. */ }; /* ** Allowed values for Select.selFlags. The "SF" prefix stands for ** "Select Flag". ** ** Value constraints (all checked via assert()) ** SF_HasAgg == NC_HasAgg ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX ** SF_FixedLimit == WHERE_USE_LIMIT */ #define SF_Distinct 0x00001 /* Output should be DISTINCT */ #define SF_All 0x00002 /* Includes the ALL keyword */ #define SF_Resolved 0x00004 /* Identifiers have been resolved */ #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */ #define SF_HasAgg 0x00010 /* Contains aggregate functions */ #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */ #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */ #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */ #define SF_Compound 0x00100 /* Part of a compound query */ #define SF_Values 0x00200 /* Synthesized from VALUES clause */ #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */ #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */ #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */ #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */ #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */ #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */ #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */ #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */ /* ** The results of a SELECT can be distributed in several ways, as defined ** by one of the following macros. The "SRT" prefix means "SELECT Result ** Type". ** ** SRT_Union Store results as a key in a temporary index ** identified by pDest->iSDParm. ** ** SRT_Except Remove results from the temporary index pDest->iSDParm. ** ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result ** set is not empty. ** ** SRT_Discard Throw the results away. This is used by SELECT ** statements within triggers whose only purpose is ** the side-effects of functions. ** ** All of the above are free to ignore their ORDER BY clause. Those that ** follow must honor the ORDER BY clause. ** ** SRT_Output Generate a row of output (using the OP_ResultRow ** opcode) for each row in the result set. ** ** SRT_Mem Only valid if the result is a single column. ** Store the first column of the first result row ** in register pDest->iSDParm then abandon the rest ** of the query. This destination implies "LIMIT 1". ** ** SRT_Set The result must be a single column. Store each ** row of result as the key in table pDest->iSDParm. ** Apply the affinity pDest->affSdst before storing ** results. Used to implement "IN (SELECT ...)". ** ** SRT_EphemTab Create an temporary table pDest->iSDParm and store ** the result there. The cursor is left open after ** returning. This is like SRT_Table except that ** this destination uses OP_OpenEphemeral to create ** the table first. ** ** SRT_Coroutine Generate a co-routine that returns a new row of ** results each time it is invoked. The entry point ** of the co-routine is stored in register pDest->iSDParm ** and the result row is stored in pDest->nDest registers ** starting with pDest->iSdst. ** ** SRT_Table Store results in temporary table pDest->iSDParm. ** SRT_Fifo This is like SRT_EphemTab except that the table ** is assumed to already be open. SRT_Fifo has ** the additional property of being able to ignore ** the ORDER BY clause. ** ** SRT_DistFifo Store results in a temporary table pDest->iSDParm. ** But also use temporary table pDest->iSDParm+1 as ** a record of all prior results and ignore any duplicate ** rows. Name means: "Distinct Fifo". ** ** SRT_Queue Store results in priority queue pDest->iSDParm (really ** an index). Append a sequence number so that all entries ** are distinct. ** ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if ** the same record has never been stored before. The ** index at pDest->iSDParm+1 hold all prior stores. */ #define SRT_Union 1 /* Store result as keys in an index */ #define SRT_Except 2 /* Remove result from a UNION index */ #define SRT_Exists 3 /* Store 1 if the result is not empty */ #define SRT_Discard 4 /* Do not save the results anywhere */ #define SRT_Fifo 5 /* Store result as data with an automatic rowid */ #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */ #define SRT_Queue 7 /* Store result in an queue */ #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */ /* The ORDER BY clause is ignored for all of the above */ #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue) #define SRT_Output 9 /* Output each row of result */ #define SRT_Mem 10 /* Store result in a memory cell */ #define SRT_Set 11 /* Store results as keys in an index */ #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */ #define SRT_Coroutine 13 /* Generate a single row of result */ #define SRT_Table 14 /* Store result as data with an automatic rowid */ /* ** An instance of this object describes where to put of the results of ** a SELECT statement. */ struct SelectDest { u8 eDest; /* How to dispose of the results. On of SRT_* above. */ char *zAffSdst; /* Affinity used when eDest==SRT_Set */ int iSDParm; /* A parameter used by the eDest disposal method */ int iSdst; /* Base register where results are written */ int nSdst; /* Number of registers allocated */ ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */ }; /* ** During code generation of statements that do inserts into AUTOINCREMENT ** tables, the following information is attached to the Table.u.autoInc.p ** pointer of each autoincrement table to record some side information that ** the code generator needs. We have to keep per-table autoincrement ** information in case inserts are done within triggers. Triggers do not ** normally coordinate their activities, but we do need to coordinate the ** loading and saving of autoincrement information. */ struct AutoincInfo { AutoincInfo *pNext; /* Next info block in a list of them all */ Table *pTab; /* Table this info block refers to */ int iDb; /* Index in sqlite3.aDb[] of database holding pTab */ int regCtr; /* Memory register holding the rowid counter */ }; /* ** Size of the column cache */ #ifndef SQLITE_N_COLCACHE # define SQLITE_N_COLCACHE 10 #endif /* ** At least one instance of the following structure is created for each ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE ** statement. All such objects are stored in the linked list headed at ** Parse.pTriggerPrg and deleted once statement compilation has been ** completed. ** ** A Vdbe sub-program that implements the body and WHEN clause of trigger ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable. ** The Parse.pTriggerPrg list never contains two entries with the same ** values for both pTrigger and orconf. ** ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns ** accessed (or set to 0 for triggers fired as a result of INSERT ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to ** a mask of new.* columns used by the program. */ struct TriggerPrg { Trigger *pTrigger; /* Trigger this program was coded from */ TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */ SubProgram *pProgram; /* Program implementing pTrigger/orconf */ int orconf; /* Default ON CONFLICT policy */ u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */ }; /* ** The yDbMask datatype for the bitmask of all attached databases. */ #if SQLITE_MAX_ATTACHED>30 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8]; # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0) # define DbMaskZero(M) memset((M),0,sizeof(M)) # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7)) # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M) # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0) #else typedef unsigned int yDbMask; # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0) # define DbMaskZero(M) (M)=0 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I)) # define DbMaskAllZero(M) (M)==0 # define DbMaskNonZero(M) (M)!=0 #endif /* ** An SQL parser context. A copy of this structure is passed through ** the parser and down into all the parser action routine in order to ** carry around information that is global to the entire parse. ** ** The structure is divided into two parts. When the parser and code ** generate call themselves recursively, the first part of the structure ** is constant but the second part is reset at the beginning and end of ** each recursion. ** ** The nTableLock and aTableLock variables are only used if the shared-cache ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are ** used to store the set of table-locks required by the statement being ** compiled. Function sqlite3TableLock() is used to add entries to the ** list. */ struct Parse { sqlite3 *db; /* The main database structure */ char *zErrMsg; /* An error message */ Vdbe *pVdbe; /* An engine for executing database bytecode */ int rc; /* Return code from execution */ u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */ u8 checkSchema; /* Causes schema cookie check after an error */ u8 nested; /* Number of nested calls to the parser/code generator */ u8 nTempReg; /* Number of temporary registers in aTempReg[] */ u8 isMultiWrite; /* True if statement may modify/insert multiple rows */ u8 mayAbort; /* True if statement may throw an ABORT exception */ u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */ u8 okConstFactor; /* OK to factor out constants */ u8 disableLookaside; /* Number of times lookaside has been disabled */ u8 nColCache; /* Number of entries in aColCache[] */ int nRangeReg; /* Size of the temporary register block */ int iRangeReg; /* First register in temporary register block */ int nErr; /* Number of errors seen */ int nTab; /* Number of previously allocated VDBE cursors */ int nMem; /* Number of memory cells used so far */ int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */ int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */ int ckBase; /* Base register of data during check constraints */ int iSelfTab; /* Table of an index whose exprs are being coded */ int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */ int iCacheCnt; /* Counter used to generate aColCache[].lru values */ int nLabel; /* Number of labels used */ int *aLabel; /* Space to hold the labels */ ExprList *pConstExpr;/* Constant expressions */ Token constraintName;/* Name of the constraint currently being parsed */ yDbMask writeMask; /* Start a write transaction on these databases */ yDbMask cookieMask; /* Bitmask of schema verified databases */ int regRowid; /* Register holding rowid of CREATE TABLE entry */ int regRoot; /* Register holding root page number for new objects */ int nMaxArg; /* Max args passed to user function by sub-program */ #if SELECTTRACE_ENABLED int nSelect; /* Number of SELECT statements seen */ int nSelectIndent; /* How far to indent SELECTTRACE() output */ #endif #ifndef SQLITE_OMIT_SHARED_CACHE int nTableLock; /* Number of locks in aTableLock */ TableLock *aTableLock; /* Required table locks for shared-cache mode */ #endif AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */ Parse *pToplevel; /* Parse structure for main program (or NULL) */ Table *pTriggerTab; /* Table triggers are being coded for */ int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */ u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ u32 oldmask; /* Mask of old.* columns referenced */ u32 newmask; /* Mask of new.* columns referenced */ u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */ u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */ u8 disableTriggers; /* True to disable triggers */ /************************************************************************** ** Fields above must be initialized to zero. The fields that follow, ** down to the beginning of the recursive section, do not need to be ** initialized as they will be set before being used. The boundary is ** determined by offsetof(Parse,aColCache). **************************************************************************/ struct yColCache { int iTable; /* Table cursor number */ i16 iColumn; /* Table column number */ u8 tempReg; /* iReg is a temp register that needs to be freed */ int iLevel; /* Nesting level */ int iReg; /* Reg with value of this column. 0 means none. */ int lru; /* Least recently used entry has the smallest value */ } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */ int aTempReg[8]; /* Holding area for temporary registers */ Token sNameToken; /* Token with unqualified schema object name */ /************************************************************************ ** Above is constant between recursions. Below is reset before and after ** each recursion. The boundary between these two regions is determined ** using offsetof(Parse,sLastToken) so the sLastToken field must be the ** first field in the recursive region. ************************************************************************/ Token sLastToken; /* The last token parsed */ ynVar nVar; /* Number of '?' variables seen in the SQL so far */ u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */ u8 explain; /* True if the EXPLAIN flag is found on the query */ #ifndef SQLITE_OMIT_VIRTUALTABLE u8 declareVtab; /* True if inside sqlite3_declare_vtab() */ int nVtabLock; /* Number of virtual tables to lock */ #endif int nHeight; /* Expression tree height of current sub-select */ #ifndef SQLITE_OMIT_EXPLAIN int iSelectId; /* ID of current select for EXPLAIN output */ int iNextSelectId; /* Next available select ID for EXPLAIN output */ #endif VList *pVList; /* Mapping between variable names and numbers */ Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */ const char *zTail; /* All SQL text past the last semicolon parsed */ Table *pNewTable; /* A table being constructed by CREATE TABLE */ Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */ const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */ #ifndef SQLITE_OMIT_VIRTUALTABLE Token sArg; /* Complete text of a module argument */ Table **apVtabLock; /* Pointer to virtual tables needing locking */ #endif Table *pZombieTab; /* List of Table objects to delete after code gen */ TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */ With *pWith; /* Current WITH clause, or NULL */ With *pWithToFree; /* Free this WITH object at the end of the parse */ }; /* ** Sizes and pointers of various parts of the Parse object. */ #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/ #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */ #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */ #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */ /* ** Return true if currently inside an sqlite3_declare_vtab() call. */ #ifdef SQLITE_OMIT_VIRTUALTABLE #define IN_DECLARE_VTAB 0 #else #define IN_DECLARE_VTAB (pParse->declareVtab) #endif /* ** An instance of the following structure can be declared on a stack and used ** to save the Parse.zAuthContext value so that it can be restored later. */ struct AuthContext { const char *zAuthContext; /* Put saved Parse.zAuthContext here */ Parse *pParse; /* The Parse structure */ }; /* ** Bitfield flags for P5 value in various opcodes. ** ** Value constraints (enforced via assert()): ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF ** OPFLAG_BULKCSR == BTREE_BULKLOAD ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ ** OPFLAG_FORDELETE == BTREE_FORDELETE ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION ** OPFLAG_AUXDELETE == BTREE_AUXDELETE */ #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */ /* Also used in P2 (not P5) of OP_Delete */ #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */ #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */ #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */ #define OPFLAG_APPEND 0x08 /* This is likely to be an append */ #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */ #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */ #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */ #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */ #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */ #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */ #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */ #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */ #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */ #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */ #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */ /* * Each trigger present in the database schema is stored as an instance of * struct Trigger. * * Pointers to instances of struct Trigger are stored in two ways. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the * database). This allows Trigger structures to be retrieved by name. * 2. All triggers associated with a single table form a linked list, using the * pNext member of struct Trigger. A pointer to the first element of the * linked list is stored as the "pTrigger" member of the associated * struct Table. * * The "step_list" member points to the first element of a linked list * containing the SQL statements specified as the trigger program. */ struct Trigger { char *zName; /* The name of the trigger */ char *table; /* The table or view to which the trigger applies */ u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */ u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */ IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger, the <column-list> is stored here */ Schema *pSchema; /* Schema containing the trigger */ Schema *pTabSchema; /* Schema containing the table */ TriggerStep *step_list; /* Link list of trigger program steps */ Trigger *pNext; /* Next trigger associated with the table */ }; /* ** A trigger is either a BEFORE or an AFTER trigger. The following constants ** determine which. ** ** If there are multiple triggers, you might of some BEFORE and some AFTER. ** In that cases, the constants below can be ORed together. */ #define TRIGGER_BEFORE 1 #define TRIGGER_AFTER 2 /* * An instance of struct TriggerStep is used to store a single SQL statement * that is a part of a trigger-program. * * Instances of struct TriggerStep are stored in a singly linked list (linked * using the "pNext" member) referenced by the "step_list" member of the * associated struct Trigger instance. The first element of the linked list is * the first step of the trigger-program. * * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or * "SELECT" statement. The meanings of the other members is determined by the * value of "op" as follows: * * (op == TK_INSERT) * orconf -> stores the ON CONFLICT algorithm * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then * this stores a pointer to the SELECT statement. Otherwise NULL. * zTarget -> Dequoted name of the table to insert into. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then * this stores values to be inserted. Otherwise NULL. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ... * statement, then this stores the column-names to be * inserted into. * * (op == TK_DELETE) * zTarget -> Dequoted name of the table to delete from. * pWhere -> The WHERE clause of the DELETE statement if one is specified. * Otherwise NULL. * * (op == TK_UPDATE) * zTarget -> Dequoted name of the table to update. * pWhere -> The WHERE clause of the UPDATE statement if one is specified. * Otherwise NULL. * pExprList -> A list of the columns to update and the expressions to update * them to. See sqlite3Update() documentation of "pChanges" * argument. * */ struct TriggerStep { u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */ u8 orconf; /* OE_Rollback etc. */ Trigger *pTrig; /* The trigger that this step is a part of */ Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */ char *zTarget; /* Target table for DELETE, UPDATE, INSERT */ Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */ ExprList *pExprList; /* SET clause for UPDATE. */ IdList *pIdList; /* Column names for INSERT */ TriggerStep *pNext; /* Next in the link-list */ TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */ }; /* ** The following structure contains information used by the sqliteFix... ** routines as they walk the parse tree to make database references ** explicit. */ typedef struct DbFixer DbFixer; struct DbFixer { Parse *pParse; /* The parsing context. Error messages written here */ Schema *pSchema; /* Fix items to this schema */ int bVarOnly; /* Check for variable references only */ const char *zDb; /* Make sure all objects are contained in this database */ const char *zType; /* Type of the container - used for error messages */ const Token *pName; /* Name of the container - used for error messages */ }; /* ** An objected used to accumulate the text of a string where we ** do not necessarily know how big the string will be in the end. */ struct StrAccum { sqlite3 *db; /* Optional database for lookaside. Can be NULL */ char *zBase; /* A base allocation. Not from malloc. */ char *zText; /* The string collected so far */ u32 nChar; /* Length of the string so far */ u32 nAlloc; /* Amount of space allocated in zText */ u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */ u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */ u8 printfFlags; /* SQLITE_PRINTF flags below */ }; #define STRACCUM_NOMEM 1 #define STRACCUM_TOOBIG 2 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */ #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */ #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */ #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0) /* ** A pointer to this structure is used to communicate information ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback. */ typedef struct { sqlite3 *db; /* The database being initialized */ char **pzErrMsg; /* Error message stored here */ int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */ int rc; /* Result code stored here */ } InitData; /* ** Structure containing global configuration data for the SQLite library. ** ** This structure also contains some state information. */ struct Sqlite3Config { int bMemstat; /* True to enable memory status */ int bCoreMutex; /* True to enable core mutexing */ int bFullMutex; /* True to enable full mutexing */ int bOpenUri; /* True to interpret filenames as URIs */ int bUseCis; /* Use covering indices for full-scans */ int mxStrlen; /* Maximum string length */ int neverCorrupt; /* Database is always well-formed */ int szLookaside; /* Default lookaside buffer size */ int nLookaside; /* Default lookaside buffer count */ int nStmtSpill; /* Stmt-journal spill-to-disk threshold */ sqlite3_mem_methods m; /* Low-level memory allocation interface */ sqlite3_mutex_methods mutex; /* Low-level mutex interface */ sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */ void *pHeap; /* Heap storage space */ int nHeap; /* Size of pHeap[] */ int mnReq, mxReq; /* Min and max heap requests sizes */ sqlite3_int64 szMmap; /* mmap() space per open file */ sqlite3_int64 mxMmap; /* Maximum value for szMmap */ void *pScratch; /* Scratch memory */ int szScratch; /* Size of each scratch buffer */ int nScratch; /* Number of scratch buffers */ void *pPage; /* Page cache memory */ int szPage; /* Size of each page in pPage[] */ int nPage; /* Number of pages in pPage[] */ int mxParserStack; /* maximum depth of the parser stack */ int sharedCacheEnabled; /* true if shared-cache mode enabled */ u32 szPma; /* Maximum Sorter PMA size */ /* The above might be initialized to non-zero. The following need to always ** initially be zero, however. */ int isInit; /* True after initialization has finished */ int inProgress; /* True while initialization in progress */ int isMutexInit; /* True after mutexes are initialized */ int isMallocInit; /* True after malloc is initialized */ int isPCacheInit; /* True after malloc is initialized */ int nRefInitMutex; /* Number of users of pInitMutex */ sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ void (*xLog)(void*,int,const char*); /* Function for logging */ void *pLogArg; /* First argument to xLog() */ #ifdef SQLITE_ENABLE_SQLLOG void(*xSqllog)(void*,sqlite3*,const char*, int); void *pSqllogArg; #endif #ifdef SQLITE_VDBE_COVERAGE /* The following callback (if not NULL) is invoked on every VDBE branch ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE. */ void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */ void *pVdbeBranchArg; /* 1st argument */ #endif #ifndef SQLITE_UNTESTABLE int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */ #endif int bLocaltimeFault; /* True to fail localtime() calls */ int iOnceResetThreshold; /* When to reset OP_Once counters */ }; /* ** This macro is used inside of assert() statements to indicate that ** the assert is only valid on a well-formed database. Instead of: ** ** assert( X ); ** ** One writes: ** ** assert( X || CORRUPT_DB ); ** ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate ** that the database is definitely corrupt, only that it might be corrupt. ** For most test cases, CORRUPT_DB is set to false using a special ** sqlite3_test_control(). This enables assert() statements to prove ** things that are always true for well-formed databases. */ #define CORRUPT_DB (sqlite3Config.neverCorrupt==0) /* ** Context pointer passed down through the tree-walk. */ struct Walker { Parse *pParse; /* Parser context. */ int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */ int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */ void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */ int walkerDepth; /* Number of subqueries */ u8 eCode; /* A small processing code */ union { /* Extra data for callback */ NameContext *pNC; /* Naming context */ int n; /* A counter */ int iCur; /* A cursor number */ SrcList *pSrcList; /* FROM clause */ struct SrcCount *pSrcCount; /* Counting column references */ struct CCurHint *pCCurHint; /* Used by codeCursorHint() */ int *aiCol; /* array of column indexes */ struct IdxCover *pIdxCover; /* Check for index coverage */ } u; }; /* Forward declarations */ SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*); SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*); SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*); SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*); SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*); SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*); /* ** Return code from the parse-tree walking primitives and their ** callbacks. */ #define WRC_Continue 0 /* Continue down into children */ #define WRC_Prune 1 /* Omit children but continue walking siblings */ #define WRC_Abort 2 /* Abandon the tree walk */ /* ** An instance of this structure represents a set of one or more CTEs ** (common table expressions) created by a single WITH clause. */ struct With { int nCte; /* Number of CTEs in the WITH clause */ With *pOuter; /* Containing WITH clause, or NULL */ struct Cte { /* For each CTE in the WITH clause.... */ char *zName; /* Name of this CTE */ ExprList *pCols; /* List of explicit column names, or NULL */ Select *pSelect; /* The definition of this CTE */ const char *zCteErr; /* Error message for circular references */ } a[1]; }; #ifdef SQLITE_DEBUG /* ** An instance of the TreeView object is used for printing the content of ** data structures on sqlite3DebugPrintf() using a tree-like view. */ struct TreeView { int iLevel; /* Which level of the tree we are on */ u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */ }; #endif /* SQLITE_DEBUG */ /* ** Assuming zIn points to the first byte of a UTF-8 character, ** advance zIn to point to the first byte of the next UTF-8 character. */ #define SQLITE_SKIP_UTF8(zIn) { \ if( (*(zIn++))>=0xc0 ){ \ while( (*zIn & 0xc0)==0x80 ){ zIn++; } \ } \ } /* ** The SQLITE_*_BKPT macros are substitutes for the error codes with ** the same name but without the _BKPT suffix. These macros invoke ** routines that report the line-number on which the error originated ** using sqlite3_log(). The routines also provide a convenient place ** to set a debugger breakpoint. */ SQLITE_PRIVATE int sqlite3CorruptError(int); SQLITE_PRIVATE int sqlite3MisuseError(int); SQLITE_PRIVATE int sqlite3CantopenError(int); #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__) #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__) #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__) #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3NomemError(int); SQLITE_PRIVATE int sqlite3IoerrnomemError(int); # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__) # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__) #else # define SQLITE_NOMEM_BKPT SQLITE_NOMEM # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM #endif /* ** FTS3 and FTS4 both require virtual table support */ #if defined(SQLITE_OMIT_VIRTUALTABLE) # undef SQLITE_ENABLE_FTS3 # undef SQLITE_ENABLE_FTS4 #endif /* ** FTS4 is really an extension for FTS3. It is enabled using the ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3. */ #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) # define SQLITE_ENABLE_FTS3 1 #endif /* ** The ctype.h header is needed for non-ASCII systems. It is also ** needed by FTS3 when FTS3 is included in the amalgamation. */ #if !defined(SQLITE_ASCII) || \ (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION)) # include <ctype.h> #endif /* ** The following macros mimic the standard library functions toupper(), ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The ** sqlite versions only work for ASCII characters, regardless of locale. */ #ifdef SQLITE_ASCII # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01) # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06) # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02) # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04) # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08) # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)]) # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80) #else # define sqlite3Toupper(x) toupper((unsigned char)(x)) # define sqlite3Isspace(x) isspace((unsigned char)(x)) # define sqlite3Isalnum(x) isalnum((unsigned char)(x)) # define sqlite3Isalpha(x) isalpha((unsigned char)(x)) # define sqlite3Isdigit(x) isdigit((unsigned char)(x)) # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x)) # define sqlite3Tolower(x) tolower((unsigned char)(x)) # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`') #endif #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS SQLITE_PRIVATE int sqlite3IsIdChar(u8); #endif /* ** Internal function prototypes */ SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*); SQLITE_PRIVATE int sqlite3Strlen30(const char*); SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*); #define sqlite3StrNICmp sqlite3_strnicmp SQLITE_PRIVATE int sqlite3MallocInit(void); SQLITE_PRIVATE void sqlite3MallocEnd(void); SQLITE_PRIVATE void *sqlite3Malloc(u64); SQLITE_PRIVATE void *sqlite3MallocZero(u64); SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64); SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64); SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64); SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*); SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64); SQLITE_PRIVATE void *sqlite3Realloc(void*, u64); SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64); SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64); SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*); SQLITE_PRIVATE int sqlite3MallocSize(void*); SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*); SQLITE_PRIVATE void *sqlite3ScratchMalloc(int); SQLITE_PRIVATE void sqlite3ScratchFree(void*); SQLITE_PRIVATE void *sqlite3PageMalloc(int); SQLITE_PRIVATE void sqlite3PageFree(void*); SQLITE_PRIVATE void sqlite3MemSetDefault(void); #ifndef SQLITE_UNTESTABLE SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void)); #endif SQLITE_PRIVATE int sqlite3HeapNearlyFull(void); /* ** On systems with ample stack space and that support alloca(), make ** use of alloca() to obtain space for large automatic objects. By default, ** obtain space from malloc(). ** ** The alloca() routine never returns NULL. This will cause code paths ** that deal with sqlite3StackAlloc() failures to be unreachable. */ #ifdef SQLITE_USE_ALLOCA # define sqlite3StackAllocRaw(D,N) alloca(N) # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N) # define sqlite3StackFree(D,P) #else # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N) # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N) # define sqlite3StackFree(D,P) sqlite3DbFree(D,P) #endif /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they ** are, disable MEMSYS3 */ #ifdef SQLITE_ENABLE_MEMSYS5 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void); #undef SQLITE_ENABLE_MEMSYS3 #endif #ifdef SQLITE_ENABLE_MEMSYS3 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void); #endif #ifndef SQLITE_MUTEX_OMIT SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void); SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void); SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int); SQLITE_PRIVATE int sqlite3MutexInit(void); SQLITE_PRIVATE int sqlite3MutexEnd(void); #endif #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP) SQLITE_PRIVATE void sqlite3MemoryBarrier(void); #else # define sqlite3MemoryBarrier() #endif SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int); SQLITE_PRIVATE void sqlite3StatusUp(int, int); SQLITE_PRIVATE void sqlite3StatusDown(int, int); SQLITE_PRIVATE void sqlite3StatusHighwater(int, int); /* Access to mutexes used by sqlite3_status() */ SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void); SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void); #ifndef SQLITE_OMIT_FLOATING_POINT SQLITE_PRIVATE int sqlite3IsNaN(double); #else # define sqlite3IsNaN(X) 0 #endif /* ** An instance of the following structure holds information about SQL ** functions arguments that are the parameters to the printf() function. */ struct PrintfArguments { int nArg; /* Total number of arguments */ int nUsed; /* Number of arguments used so far */ sqlite3_value **apArg; /* The argument values */ }; SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list); SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...); SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...); SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list); #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...); #endif #if defined(SQLITE_TEST) SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*); #endif #if defined(SQLITE_DEBUG) SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8); SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*); SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*); SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8); SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8); #endif SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*); SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...); SQLITE_PRIVATE void sqlite3Dequote(char*); SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*); SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int); SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **); SQLITE_PRIVATE void sqlite3FinishCoding(Parse*); SQLITE_PRIVATE int sqlite3GetTempReg(Parse*); SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int); SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int); SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int); SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int); #endif SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int); SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*); SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*); SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*); SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*); SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*); SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*); SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32); SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*); SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*); SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*); SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int); SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int); SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*); SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*); SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*); SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**); SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**); SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int); #ifndef SQLITE_OMIT_VIRTUALTABLE SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName); #endif SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*); SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int); SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*); SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*); SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*); SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**); SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*); SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*); SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int); SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*); SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16); SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); #if SQLITE_ENABLE_HIDDEN_COLUMNS SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*); #else # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */ #endif SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*); SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int); SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int); SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*); SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*); SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*); SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*); SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*, sqlite3_vfs**,char**,char **); SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*); #ifdef SQLITE_UNTESTABLE # define sqlite3FaultSim(X) SQLITE_OK #else SQLITE_PRIVATE int sqlite3FaultSim(int); #endif SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32); SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32); SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32); SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32); SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*); SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*); SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*); #ifndef SQLITE_UNTESTABLE SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*); #endif SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int); SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*); SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64); SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64); SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*); SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int); #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*); #else # define sqlite3ViewGetColumnNames(A,B) 0 #endif #if SQLITE_MAX_ATTACHED>30 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask); #endif SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int); SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int); SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*); #ifndef SQLITE_OMIT_AUTOINCREMENT SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse); SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse); #else # define sqlite3AutoincrementBegin(X) # define sqlite3AutoincrementEnd(X) #endif SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int); SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*); SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*); SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*); SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int); SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*); SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*, Select*, Expr*, IdList*); SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *); SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*); SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *); SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*); SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*); SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*); SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*); SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**); SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, Expr*, int, int, u8); SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int); SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*); SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*, Expr*,ExprList*,u32,Expr*,Expr*); SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*); SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*); SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int); SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*); #endif SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*); SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int); SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int); SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*); SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*); SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*); #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */ #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */ #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */ SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int); SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int); SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int); SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int); SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*); SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*); SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int); SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*); SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int); SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int); SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int); SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*); SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int); SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8); #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */ #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */ #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */ #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int); SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int); SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int); SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*); #define LOCATE_VIEW 0x01 #define LOCATE_NOERR 0x02 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*); SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *); SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*); SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*); SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int); SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*); SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int); SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int); SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx); SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*); SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*); #ifndef SQLITE_UNTESTABLE SQLITE_PRIVATE void sqlite3PrngSaveState(void); SQLITE_PRIVATE void sqlite3PrngRestoreState(void); #endif SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int); SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int); SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb); SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int); SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*); SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*); SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*); SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *); SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*); SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*); SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*); SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8); SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int); #ifdef SQLITE_ENABLE_CURSOR_HINTS SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*); #endif SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*); SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*); SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char); SQLITE_PRIVATE int sqlite3IsRowid(const char*); SQLITE_PRIVATE void sqlite3GenerateRowDelete( Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int); SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int); SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int); SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int); SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int, u8,u8,int,int*,int*); #ifdef SQLITE_ENABLE_NULL_TRIM SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*); #else # define sqlite3SetMakeRecordP5(A,B) #endif SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int); SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*); SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int); SQLITE_PRIVATE void sqlite3MultiWrite(Parse*); SQLITE_PRIVATE void sqlite3MayAbort(Parse*); SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8); SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*); SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*); SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int); SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int); SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int); SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*); SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int); #if SELECTTRACE_ENABLED SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*); #else # define sqlite3SelectSetName(A,B) #endif SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int); SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8); SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void); SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void); SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*); SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*); SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*); SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int); #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int); #endif #ifndef SQLITE_OMIT_TRIGGER SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*, Expr*,int, int); SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*); SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int); SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*); SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask); SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *); SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *, int, int, int); SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int); void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*); SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*); SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*); SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*, Select*,u8); SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8); SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*); SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*); SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p)) # define sqlite3IsToplevel(p) ((p)->pToplevel==0) #else # define sqlite3TriggersExist(B,C,D,E,F) 0 # define sqlite3DeleteTrigger(A,B) # define sqlite3DropTriggerPtr(A,B) # define sqlite3UnlinkAndDeleteTrigger(A,B,C) # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F) # define sqlite3TriggerList(X, Y) 0 # define sqlite3ParseToplevel(p) p # define sqlite3IsToplevel(p) 1 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0 #endif SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*); SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int); #ifndef SQLITE_OMIT_AUTHORIZATION SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*); SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*); SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*); SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*); SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int); #else # define sqlite3AuthRead(a,b,c,d) # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK # define sqlite3AuthContextPush(a,b,c) # define sqlite3AuthContextPop(a) ((void)(a)) #endif SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*); SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*); SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*); SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*); SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*); SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*); SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*); SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*); SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8); SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*); SQLITE_PRIVATE int sqlite3Atoi(const char*); SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar); SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte); SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**); SQLITE_PRIVATE LogEst sqlite3LogEst(u64); SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst); #ifndef SQLITE_OMIT_VIRTUALTABLE SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double); #endif #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst); #endif SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int); SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int); SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int); /* ** Routines to read and write variable-length integers. These used to ** be defined locally, but now we use the varint routines in the util.c ** file. */ SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64); SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *); SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *); SQLITE_PRIVATE int sqlite3VarintLen(u64 v); /* ** The common case is for a varint to be a single byte. They following ** macros handle the common case without a procedure call, but then call ** the procedure for larger varints. */ #define getVarint32(A,B) \ (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B))) #define putVarint32(A,B) \ (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\ sqlite3PutVarint((A),(B))) #define getVarint sqlite3GetVarint #define putVarint sqlite3PutVarint SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*); SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int); SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2); SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity); SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int); SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr); SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8); SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*); SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...); SQLITE_PRIVATE void sqlite3Error(sqlite3*,int); SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int); SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n); SQLITE_PRIVATE u8 sqlite3HexToInt(int h); SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **); #if defined(SQLITE_NEED_ERR_NAME) SQLITE_PRIVATE const char *sqlite3ErrName(int); #endif SQLITE_PRIVATE const char *sqlite3ErrStr(int); SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse); SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int); SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName); SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr); SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int); SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*); SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*); SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *); SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *); SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int); SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64); SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64); SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64); SQLITE_PRIVATE int sqlite3AbsInt32(int); #ifdef SQLITE_ENABLE_8_3_NAMES SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*); #else # define sqlite3FileSuffix3(X,Y) #endif SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8); SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8); SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8); SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, void(*)(void*)); SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*); SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*); SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *); SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8); SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **); SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); #ifndef SQLITE_AMALGAMATION SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]; SQLITE_PRIVATE const char sqlite3StrBINARY[]; SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[]; SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[]; SQLITE_PRIVATE const Token sqlite3IntTokens[]; SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config; SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; #ifndef SQLITE_OMIT_WSD SQLITE_PRIVATE int sqlite3PendingByte; #endif #endif SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int); SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*); SQLITE_PRIVATE void sqlite3AlterFunctions(void); SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *); SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...); SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*); SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int); SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*); SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p); SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*); SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*); SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*); SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*); SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*); SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*); SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int); SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *); SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *); SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*); SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*); SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*); SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*); SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*); SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *); SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB); SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*); SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*); SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int); SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*); SQLITE_PRIVATE void sqlite3SchemaClear(void *); SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *); SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *); SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int); SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*); SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*); SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*); #endif SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*), FuncDestructor *pDestructor ); SQLITE_PRIVATE void sqlite3OomFault(sqlite3*); SQLITE_PRIVATE void sqlite3OomClear(sqlite3*); SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int); SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *); SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int); SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int); SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*); SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char); SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*); SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*); SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int); SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int); SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *); SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *); #ifndef SQLITE_OMIT_SUBQUERY SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*); #else # define sqlite3ExprCheckIN(x,y) SQLITE_OK #endif #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void); SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*); SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**); SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*); SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**); SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int); #endif /* ** The interface to the LEMON-generated parser */ #ifndef SQLITE_AMALGAMATION SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64)); SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*)); #endif SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*); #ifdef YYTRACKMAXSTACKDEPTH SQLITE_PRIVATE int sqlite3ParserStackPeak(void*); #endif SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*); #ifndef SQLITE_OMIT_LOAD_EXTENSION SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*); #else # define sqlite3CloseExtensions(X) #endif #ifndef SQLITE_OMIT_SHARED_CACHE SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *); #else #define sqlite3TableLock(v,w,x,y,z) #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*); #endif #ifdef SQLITE_OMIT_VIRTUALTABLE # define sqlite3VtabClear(Y) # define sqlite3VtabSync(X,Y) SQLITE_OK # define sqlite3VtabRollback(X) # define sqlite3VtabCommit(X) # define sqlite3VtabInSync(db) 0 # define sqlite3VtabLock(X) # define sqlite3VtabUnlock(X) # define sqlite3VtabUnlockList(X) # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK # define sqlite3GetVTable(X,Y) ((VTable*)0) #else SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*); SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p); SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*); SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db); SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db); SQLITE_PRIVATE void sqlite3VtabLock(VTable *); SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *); SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*); SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int); SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*); SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*); SQLITE_PRIVATE Module *sqlite3VtabCreateModule( sqlite3*, const char*, const sqlite3_module*, void*, void(*)(void*) ); # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0) #endif SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*); SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*); SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*); SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int); SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*); SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*); SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*); SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **); SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*); SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *); SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *); SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*); SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**); SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*); SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int); SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *); SQLITE_PRIVATE void sqlite3ParserReset(Parse*); SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*); SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*); SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *); SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*); SQLITE_PRIVATE const char *sqlite3JournalModename(int); #ifndef SQLITE_OMIT_WAL SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*); SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int); #endif #ifndef SQLITE_OMIT_CTE SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*); SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*); SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8); #else #define sqlite3WithPush(x,y,z) #define sqlite3WithDelete(x,y) #endif /* Declarations for functions in fkey.c. All of these are replaced by ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign ** key functionality is available. If OMIT_TRIGGER is defined but ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In ** this case foreign keys are parsed, but no other functionality is ** provided (enforcement of FK constraints requires the triggers sub-system). */ #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int); SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*); SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int); SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int); SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*); SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *); #else #define sqlite3FkActions(a,b,c,d,e,f) #define sqlite3FkCheck(a,b,c,d,e,f) #define sqlite3FkDropTable(a,b,c) #define sqlite3FkOldmask(a,b) 0 #define sqlite3FkRequired(a,b,c,d) 0 #define sqlite3FkReferences(a) 0 #endif #ifndef SQLITE_OMIT_FOREIGN_KEY SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*); SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**); #else #define sqlite3FkDelete(a,b) #define sqlite3FkLocateIndex(a,b,c,d,e) #endif /* ** Available fault injectors. Should be numbered beginning with 0. */ #define SQLITE_FAULTINJECTOR_MALLOC 0 #define SQLITE_FAULTINJECTOR_COUNT 1 /* ** The interface to the code in fault.c used for identifying "benign" ** malloc failures. This is only present if SQLITE_UNTESTABLE ** is not defined. */ #ifndef SQLITE_UNTESTABLE SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void); SQLITE_PRIVATE void sqlite3EndBenignMalloc(void); #else #define sqlite3BeginBenignMalloc() #define sqlite3EndBenignMalloc() #endif /* ** Allowed return values from sqlite3FindInIndex() */ #define IN_INDEX_ROWID 1 /* Search the rowid of the table */ #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */ #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */ #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */ #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */ /* ** Allowed flags for the 3rd parameter to sqlite3FindInIndex(). */ #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */ #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */ #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */ SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*); SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int); SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *); #ifdef SQLITE_ENABLE_ATOMIC_WRITE SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *); #endif SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p); SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *); SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p); #if SQLITE_MAX_EXPR_DEPTH>0 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *); SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int); #else #define sqlite3SelectExprHeight(x) 0 #define sqlite3ExprCheckHeight(x,y) #endif SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*); SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32); #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *); SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db); SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db); #else #define sqlite3ConnectionBlocked(x,y) #define sqlite3ConnectionUnlocked(x) #define sqlite3ConnectionClosed(x) #endif #ifdef SQLITE_DEBUG SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *); #endif /* ** If the SQLITE_ENABLE IOTRACE exists then the global variable ** sqlite3IoTrace is a pointer to a printf-like routine used to ** print I/O tracing messages. */ #ifdef SQLITE_ENABLE_IOTRACE # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; } SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*); SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...); #else # define IOTRACE(A) # define sqlite3VdbeIOTraceSql(X) #endif /* ** These routines are available for the mem2.c debugging memory allocator ** only. They are used to verify that different "types" of memory ** allocations are properly tracked by the system. ** ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of ** the MEMTYPE_* macros defined below. The type must be a bitmask with ** a single bit set. ** ** sqlite3MemdebugHasType() returns true if any of the bits in its second ** argument match the type set by the previous sqlite3MemdebugSetType(). ** sqlite3MemdebugHasType() is intended for use inside assert() statements. ** ** sqlite3MemdebugNoType() returns true if none of the bits in its second ** argument match the type set by the previous sqlite3MemdebugSetType(). ** ** Perhaps the most important point is the difference between MEMTYPE_HEAP ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means ** it might have been allocated by lookaside, except the allocation was ** too large or lookaside was already full. It is important to verify ** that allocations that might have been satisfied by lookaside are not ** passed back to non-lookaside free() routines. Asserts such as the ** example above are placed on the non-lookaside free() routines to verify ** this constraint. ** ** All of this is no-op for a production build. It only comes into ** play when the SQLITE_MEMDEBUG compile-time option is used. */ #ifdef SQLITE_MEMDEBUG SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8); SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8); SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8); #else # define sqlite3MemdebugSetType(X,Y) /* no-op */ # define sqlite3MemdebugHasType(X,Y) 1 # define sqlite3MemdebugNoType(X,Y) 1 #endif #define MEMTYPE_HEAP 0x01 /* General heap allocations */ #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */ #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */ #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */ /* ** Threading interface */ #if SQLITE_MAX_WORKER_THREADS>0 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*); SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**); #endif #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST) SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*); #endif SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr); SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr); SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int); SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int); SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*); #endif /* SQLITEINT_H */ /************** End of sqliteInt.h *******************************************/ /************** Begin file global.c ******************************************/ /* ** 2008 June 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains definitions of global variables and constants. */ /* #include "sqliteInt.h" */ /* An array to map all upper-case characters into their corresponding ** lower-case character. ** ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not ** handle case conversions for the UTF character set since the tables ** involved are nearly as big or bigger than SQLite itself. */ SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = { #ifdef SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 #endif #ifdef SQLITE_EBCDIC 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */ 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */ 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */ 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */ 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */ 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */ 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */ 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */ 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */ 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */ 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */ 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */ #endif }; /* ** The following 256 byte lookup table is used to support SQLites built-in ** equivalents to the following standard library functions: ** ** isspace() 0x01 ** isalpha() 0x02 ** isdigit() 0x04 ** isalnum() 0x06 ** isxdigit() 0x08 ** toupper() 0x20 ** SQLite identifier character 0x40 ** Quote character 0x80 ** ** Bit 0x20 is set if the mapped character requires translation to upper ** case. i.e. if the character is a lower-case ASCII character. ** If x is a lower-case ASCII character, then its upper-case equivalent ** is (x - 0x20). Therefore toupper() can be implemented as: ** ** (x & ~(map[x]&0x20)) ** ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[] ** array. tolower() is used more often than toupper() by SQLite. ** ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any ** non-ASCII UTF character. Hence the test for whether or not a character is ** part of an identifier is 0x46. */ #ifdef SQLITE_ASCII SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */ 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */ 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */ 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */ 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */ 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */ 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */ }; #endif /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards ** compatibility for legacy applications, the URI filename capability is ** disabled by default. ** ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options. ** ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally ** disabled. The default value may be changed by compiling with the ** SQLITE_USE_URI symbol defined. */ #ifndef SQLITE_USE_URI # define SQLITE_USE_URI 0 #endif /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if ** that compile-time option is omitted. */ #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1 #endif /* The minimum PMA size is set to this value multiplied by the database ** page size in bytes. */ #ifndef SQLITE_SORTER_PMASZ # define SQLITE_SORTER_PMASZ 250 #endif /* Statement journals spill to disk when their size exceeds the following ** threshold (in bytes). 0 means that statement journals are created and ** written to disk immediately (the default behavior for SQLite versions ** before 3.12.0). -1 means always keep the entire statement journal in ** memory. (The statement journal is also always held entirely in memory ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this ** setting.) */ #ifndef SQLITE_STMTJRNL_SPILL # define SQLITE_STMTJRNL_SPILL (64*1024) #endif /* ** The default lookaside-configuration, the format "SZ,N". SZ is the ** number of bytes in each lookaside slot (should be a multiple of 8) ** and N is the number of slots. The lookaside-configuration can be ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE) ** or at run-time for an individual database connection using ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE); */ #ifndef SQLITE_DEFAULT_LOOKASIDE # define SQLITE_DEFAULT_LOOKASIDE 1200,100 #endif /* ** The following singleton contains the global configuration for ** the SQLite library. */ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */ 1, /* bCoreMutex */ SQLITE_THREADSAFE==1, /* bFullMutex */ SQLITE_USE_URI, /* bOpenUri */ SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */ 0x7ffffffe, /* mxStrlen */ 0, /* neverCorrupt */ SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */ SQLITE_STMTJRNL_SPILL, /* nStmtSpill */ {0,0,0,0,0,0,0,0}, /* m */ {0,0,0,0,0,0,0,0,0}, /* mutex */ {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */ (void*)0, /* pHeap */ 0, /* nHeap */ 0, 0, /* mnHeap, mxHeap */ SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */ SQLITE_MAX_MMAP_SIZE, /* mxMmap */ (void*)0, /* pScratch */ 0, /* szScratch */ 0, /* nScratch */ (void*)0, /* pPage */ 0, /* szPage */ SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */ 0, /* mxParserStack */ 0, /* sharedCacheEnabled */ SQLITE_SORTER_PMASZ, /* szPma */ /* All the rest should always be initialized to zero */ 0, /* isInit */ 0, /* inProgress */ 0, /* isMutexInit */ 0, /* isMallocInit */ 0, /* isPCacheInit */ 0, /* nRefInitMutex */ 0, /* pInitMutex */ 0, /* xLog */ 0, /* pLogArg */ #ifdef SQLITE_ENABLE_SQLLOG 0, /* xSqllog */ 0, /* pSqllogArg */ #endif #ifdef SQLITE_VDBE_COVERAGE 0, /* xVdbeBranch */ 0, /* pVbeBranchArg */ #endif #ifndef SQLITE_UNTESTABLE 0, /* xTestCallback */ #endif 0, /* bLocaltimeFault */ 0x7ffffffe /* iOnceResetThreshold */ }; /* ** Hash table for global functions - functions common to all ** database connections. After initialization, this table is ** read-only. */ SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; /* ** Constant tokens for values 0 and 1. */ SQLITE_PRIVATE const Token sqlite3IntTokens[] = { { "0", 1 }, { "1", 1 } }; /* ** The value of the "pending" byte must be 0x40000000 (1 byte past the ** 1-gibabyte boundary) in a compatible database. SQLite never uses ** the database page that contains the pending byte. It never attempts ** to read or write that page. The pending byte page is set aside ** for use by the VFS layers as space for managing file locks. ** ** During testing, it is often desirable to move the pending byte to ** a different position in the file. This allows code that has to ** deal with the pending byte to run on files that are much smaller ** than 1 GiB. The sqlite3_test_control() interface can be used to ** move the pending byte. ** ** IMPORTANT: Changing the pending byte to any value other than ** 0x40000000 results in an incompatible database file format! ** Changing the pending byte during operation will result in undefined ** and incorrect behavior. */ #ifndef SQLITE_OMIT_WSD SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000; #endif /* #include "opcodes.h" */ /* ** Properties of opcodes. The OPFLG_INITIALIZER macro is ** created by mkopcodeh.awk during compilation. Data is obtained ** from the comments following the "case OP_xxxx:" statements in ** the vdbe.c file. */ SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER; /* ** Name of the default collating sequence */ SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY"; /************** End of global.c **********************************************/ /************** Begin file ctime.c *******************************************/ /* ** 2010 February 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements routines used to report what compile-time options ** SQLite was built with. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* #include "sqliteInt.h" */ /* ** An array of names of all compile-time options. This array should ** be sorted A-Z. ** ** This array looks large, but in a typical installation actually uses ** only a handful of compile-time options, so most times this array is usually ** rather short and uses little memory space. */ static const char * const azCompileOpt[] = { /* These macros are provided to "stringify" the value of the define ** for those options in which the value is meaningful. */ #define CTIMEOPT_VAL_(opt) #opt #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) #if SQLITE_32BIT_ROWID "32BIT_ROWID", #endif #if SQLITE_4_BYTE_ALIGNED_MALLOC "4_BYTE_ALIGNED_MALLOC", #endif #if SQLITE_CASE_SENSITIVE_LIKE "CASE_SENSITIVE_LIKE", #endif #if SQLITE_CHECK_PAGES "CHECK_PAGES", #endif #if defined(__clang__) && defined(__clang_major__) "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "." CTIMEOPT_VAL(__clang_minor__) "." CTIMEOPT_VAL(__clang_patchlevel__), #elif defined(_MSC_VER) "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER), #elif defined(__GNUC__) && defined(__VERSION__) "COMPILER=gcc-" __VERSION__, #endif #if SQLITE_COVERAGE_TEST "COVERAGE_TEST", #endif #if SQLITE_DEBUG "DEBUG", #endif #if SQLITE_DEFAULT_LOCKING_MODE "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), #endif #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc) "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE), #endif #if SQLITE_DIRECT_OVERFLOW_READ "DIRECT_OVERFLOW_READ", #endif #if SQLITE_DISABLE_DIRSYNC "DISABLE_DIRSYNC", #endif #if SQLITE_DISABLE_LFS "DISABLE_LFS", #endif #if SQLITE_ENABLE_8_3_NAMES "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES), #endif #if SQLITE_ENABLE_API_ARMOR "ENABLE_API_ARMOR", #endif #if SQLITE_ENABLE_ATOMIC_WRITE "ENABLE_ATOMIC_WRITE", #endif #if SQLITE_ENABLE_CEROD "ENABLE_CEROD", #endif #if SQLITE_ENABLE_COLUMN_METADATA "ENABLE_COLUMN_METADATA", #endif #if SQLITE_ENABLE_DBSTAT_VTAB "ENABLE_DBSTAT_VTAB", #endif #if SQLITE_ENABLE_EXPENSIVE_ASSERT "ENABLE_EXPENSIVE_ASSERT", #endif #if SQLITE_ENABLE_FTS1 "ENABLE_FTS1", #endif #if SQLITE_ENABLE_FTS2 "ENABLE_FTS2", #endif #if SQLITE_ENABLE_FTS3 "ENABLE_FTS3", #endif #if SQLITE_ENABLE_FTS3_PARENTHESIS "ENABLE_FTS3_PARENTHESIS", #endif #if SQLITE_ENABLE_FTS4 "ENABLE_FTS4", #endif #if SQLITE_ENABLE_FTS5 "ENABLE_FTS5", #endif #if SQLITE_ENABLE_ICU "ENABLE_ICU", #endif #if SQLITE_ENABLE_IOTRACE "ENABLE_IOTRACE", #endif #if SQLITE_ENABLE_JSON1 "ENABLE_JSON1", #endif #if SQLITE_ENABLE_LOAD_EXTENSION "ENABLE_LOAD_EXTENSION", #endif #if SQLITE_ENABLE_LOCKING_STYLE "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), #endif #if SQLITE_ENABLE_MEMORY_MANAGEMENT "ENABLE_MEMORY_MANAGEMENT", #endif #if SQLITE_ENABLE_MEMSYS3 "ENABLE_MEMSYS3", #endif #if SQLITE_ENABLE_MEMSYS5 "ENABLE_MEMSYS5", #endif #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK "ENABLE_OVERSIZE_CELL_CHECK", #endif #if SQLITE_ENABLE_RTREE "ENABLE_RTREE", #endif #if defined(SQLITE_ENABLE_STAT4) "ENABLE_STAT4", #elif defined(SQLITE_ENABLE_STAT3) "ENABLE_STAT3", #endif #if SQLITE_ENABLE_UNLOCK_NOTIFY "ENABLE_UNLOCK_NOTIFY", #endif #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT "ENABLE_UPDATE_DELETE_LIMIT", #endif #if defined(SQLITE_ENABLE_URI_00_ERROR) "ENABLE_URI_00_ERROR", #endif #if SQLITE_HAS_CODEC "HAS_CODEC", #endif #if HAVE_ISNAN || SQLITE_HAVE_ISNAN "HAVE_ISNAN", #endif #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX "HOMEGROWN_RECURSIVE_MUTEX", #endif #if SQLITE_IGNORE_AFP_LOCK_ERRORS "IGNORE_AFP_LOCK_ERRORS", #endif #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS "IGNORE_FLOCK_LOCK_ERRORS", #endif #ifdef SQLITE_INT64_TYPE "INT64_TYPE", #endif #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS "LIKE_DOESNT_MATCH_BLOBS", #endif #if SQLITE_LOCK_TRACE "LOCK_TRACE", #endif #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc) "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE), #endif #ifdef SQLITE_MAX_SCHEMA_RETRY "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY), #endif #if SQLITE_MEMDEBUG "MEMDEBUG", #endif #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT "MIXED_ENDIAN_64BIT_FLOAT", #endif #if SQLITE_NO_SYNC "NO_SYNC", #endif #if SQLITE_OMIT_ALTERTABLE "OMIT_ALTERTABLE", #endif #if SQLITE_OMIT_ANALYZE "OMIT_ANALYZE", #endif #if SQLITE_OMIT_ATTACH "OMIT_ATTACH", #endif #if SQLITE_OMIT_AUTHORIZATION "OMIT_AUTHORIZATION", #endif #if SQLITE_OMIT_AUTOINCREMENT "OMIT_AUTOINCREMENT", #endif #if SQLITE_OMIT_AUTOINIT "OMIT_AUTOINIT", #endif #if SQLITE_OMIT_AUTOMATIC_INDEX "OMIT_AUTOMATIC_INDEX", #endif #if SQLITE_OMIT_AUTORESET "OMIT_AUTORESET", #endif #if SQLITE_OMIT_AUTOVACUUM "OMIT_AUTOVACUUM", #endif #if SQLITE_OMIT_BETWEEN_OPTIMIZATION "OMIT_BETWEEN_OPTIMIZATION", #endif #if SQLITE_OMIT_BLOB_LITERAL "OMIT_BLOB_LITERAL", #endif #if SQLITE_OMIT_BTREECOUNT "OMIT_BTREECOUNT", #endif #if SQLITE_OMIT_CAST "OMIT_CAST", #endif #if SQLITE_OMIT_CHECK "OMIT_CHECK", #endif #if SQLITE_OMIT_COMPLETE "OMIT_COMPLETE", #endif #if SQLITE_OMIT_COMPOUND_SELECT "OMIT_COMPOUND_SELECT", #endif #if SQLITE_OMIT_CTE "OMIT_CTE", #endif #if SQLITE_OMIT_DATETIME_FUNCS "OMIT_DATETIME_FUNCS", #endif #if SQLITE_OMIT_DECLTYPE "OMIT_DECLTYPE", #endif #if SQLITE_OMIT_DEPRECATED "OMIT_DEPRECATED", #endif #if SQLITE_OMIT_DISKIO "OMIT_DISKIO", #endif #if SQLITE_OMIT_EXPLAIN "OMIT_EXPLAIN", #endif #if SQLITE_OMIT_FLAG_PRAGMAS "OMIT_FLAG_PRAGMAS", #endif #if SQLITE_OMIT_FLOATING_POINT "OMIT_FLOATING_POINT", #endif #if SQLITE_OMIT_FOREIGN_KEY "OMIT_FOREIGN_KEY", #endif #if SQLITE_OMIT_GET_TABLE "OMIT_GET_TABLE", #endif #if SQLITE_OMIT_INCRBLOB "OMIT_INCRBLOB", #endif #if SQLITE_OMIT_INTEGRITY_CHECK "OMIT_INTEGRITY_CHECK", #endif #if SQLITE_OMIT_LIKE_OPTIMIZATION "OMIT_LIKE_OPTIMIZATION", #endif #if SQLITE_OMIT_LOAD_EXTENSION "OMIT_LOAD_EXTENSION", #endif #if SQLITE_OMIT_LOCALTIME "OMIT_LOCALTIME", #endif #if SQLITE_OMIT_LOOKASIDE "OMIT_LOOKASIDE", #endif #if SQLITE_OMIT_MEMORYDB "OMIT_MEMORYDB", #endif #if SQLITE_OMIT_OR_OPTIMIZATION "OMIT_OR_OPTIMIZATION", #endif #if SQLITE_OMIT_PAGER_PRAGMAS "OMIT_PAGER_PRAGMAS", #endif #if SQLITE_OMIT_PRAGMA "OMIT_PRAGMA", #endif #if SQLITE_OMIT_PROGRESS_CALLBACK "OMIT_PROGRESS_CALLBACK", #endif #if SQLITE_OMIT_QUICKBALANCE "OMIT_QUICKBALANCE", #endif #if SQLITE_OMIT_REINDEX "OMIT_REINDEX", #endif #if SQLITE_OMIT_SCHEMA_PRAGMAS "OMIT_SCHEMA_PRAGMAS", #endif #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS "OMIT_SCHEMA_VERSION_PRAGMAS", #endif #if SQLITE_OMIT_SHARED_CACHE "OMIT_SHARED_CACHE", #endif #if SQLITE_OMIT_SUBQUERY "OMIT_SUBQUERY", #endif #if SQLITE_OMIT_TCL_VARIABLE "OMIT_TCL_VARIABLE", #endif #if SQLITE_OMIT_TEMPDB "OMIT_TEMPDB", #endif #if SQLITE_OMIT_TRACE "OMIT_TRACE", #endif #if SQLITE_OMIT_TRIGGER "OMIT_TRIGGER", #endif #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION "OMIT_TRUNCATE_OPTIMIZATION", #endif #if SQLITE_OMIT_UTF16 "OMIT_UTF16", #endif #if SQLITE_OMIT_VACUUM "OMIT_VACUUM", #endif #if SQLITE_OMIT_VIEW "OMIT_VIEW", #endif #if SQLITE_OMIT_VIRTUALTABLE "OMIT_VIRTUALTABLE", #endif #if SQLITE_OMIT_WAL "OMIT_WAL", #endif #if SQLITE_OMIT_WSD "OMIT_WSD", #endif #if SQLITE_OMIT_XFER_OPT "OMIT_XFER_OPT", #endif #if SQLITE_PERFORMANCE_TRACE "PERFORMANCE_TRACE", #endif #if SQLITE_PROXY_DEBUG "PROXY_DEBUG", #endif #if SQLITE_RTREE_INT_ONLY "RTREE_INT_ONLY", #endif #if SQLITE_SECURE_DELETE "SECURE_DELETE", #endif #if SQLITE_SMALL_STACK "SMALL_STACK", #endif #if SQLITE_SOUNDEX "SOUNDEX", #endif #if SQLITE_SYSTEM_MALLOC "SYSTEM_MALLOC", #endif #if SQLITE_TCL "TCL", #endif #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc) "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE), #endif #if SQLITE_TEST "TEST", #endif #if defined(SQLITE_THREADSAFE) "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE), #endif #if SQLITE_UNTESTABLE "UNTESTABLE" #endif #if SQLITE_USE_ALLOCA "USE_ALLOCA", #endif #if SQLITE_USER_AUTHENTICATION "USER_AUTHENTICATION", #endif #if SQLITE_WIN32_MALLOC "WIN32_MALLOC", #endif #if SQLITE_ZERO_MALLOC "ZERO_MALLOC" #endif }; /* ** Given the name of a compile-time option, return true if that option ** was used and false if not. ** ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix ** is not required for a match. */ SQLITE_API int sqlite3_compileoption_used(const char *zOptName){ int i, n; #if SQLITE_ENABLE_API_ARMOR if( zOptName==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7; n = sqlite3Strlen30(zOptName); /* Since ArraySize(azCompileOpt) is normally in single digits, a ** linear search is adequate. No need for a binary search. */ for(i=0; i<ArraySize(azCompileOpt); i++){ if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0 ){ return 1; } } return 0; } /* ** Return the N-th compile-time option string. If N is out of range, ** return a NULL pointer. */ SQLITE_API const char *sqlite3_compileoption_get(int N){ if( N>=0 && N<ArraySize(azCompileOpt) ){ return azCompileOpt[N]; } return 0; } #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ /************** End of ctime.c ***********************************************/ /************** Begin file status.c ******************************************/ /* ** 2008 June 18 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This module implements the sqlite3_status() interface and related ** functionality. */ /* #include "sqliteInt.h" */ /************** Include vdbeInt.h in the middle of status.c ******************/ /************** Begin file vdbeInt.h *****************************************/ /* ** 2003 September 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for information that is private to the ** VDBE. This information used to all be at the top of the single ** source code file "vdbe.c". When that file became too big (over ** 6000 lines long) it was split up into several smaller files and ** this header information was factored out. */ #ifndef SQLITE_VDBEINT_H #define SQLITE_VDBEINT_H /* ** The maximum number of times that a statement will try to reparse ** itself before giving up and returning SQLITE_SCHEMA. */ #ifndef SQLITE_MAX_SCHEMA_RETRY # define SQLITE_MAX_SCHEMA_RETRY 50 #endif /* ** VDBE_DISPLAY_P4 is true or false depending on whether or not the ** "explain" P4 display logic is enabled. */ #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \ || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) # define VDBE_DISPLAY_P4 1 #else # define VDBE_DISPLAY_P4 0 #endif /* ** SQL is translated into a sequence of instructions to be ** executed by a virtual machine. Each instruction is an instance ** of the following structure. */ typedef struct VdbeOp Op; /* ** Boolean values */ typedef unsigned Bool; /* Opaque type used by code in vdbesort.c */ typedef struct VdbeSorter VdbeSorter; /* Elements of the linked list at Vdbe.pAuxData */ typedef struct AuxData AuxData; /* Types of VDBE cursors */ #define CURTYPE_BTREE 0 #define CURTYPE_SORTER 1 #define CURTYPE_VTAB 2 #define CURTYPE_PSEUDO 3 /* ** A VdbeCursor is an superclass (a wrapper) for various cursor objects: ** ** * A b-tree cursor ** - In the main database or in an ephemeral database ** - On either an index or a table ** * A sorter ** * A virtual table ** * A one-row "pseudotable" stored in a single register */ typedef struct VdbeCursor VdbeCursor; struct VdbeCursor { u8 eCurType; /* One of the CURTYPE_* values above */ i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */ u8 nullRow; /* True if pointing to a row with no data */ u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ u8 isTable; /* True for rowid tables. False for indexes */ #ifdef SQLITE_DEBUG u8 seekOp; /* Most recent seek operation on this cursor */ u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */ #endif Bool isEphemeral:1; /* True for an ephemeral table */ Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */ Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */ Btree *pBtx; /* Separate file holding temporary table */ i64 seqCount; /* Sequence counter */ int *aAltMap; /* Mapping from table to index column numbers */ /* Cached OP_Column parse information is only valid if cacheStatus matches ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that ** the cache is out of date. */ u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0 ** if there have been no prior seeks on the cursor. */ /* NB: seekResult does not distinguish between "no seeks have ever occurred ** on this cursor" and "the most recent seek was an exact match". */ /* When a new VdbeCursor is allocated, only the fields above are zeroed. ** The fields that follow are uninitialized, and must be individually ** initialized prior to first use. */ VdbeCursor *pAltCursor; /* Associated index cursor from which to read */ union { BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */ sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */ int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */ VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */ } uc; KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */ u32 iHdrOffset; /* Offset to next unparsed byte of the header */ Pgno pgnoRoot; /* Root page of the open btree cursor */ i16 nField; /* Number of fields in the header */ u16 nHdrParsed; /* Number of header fields parsed so far */ i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ u32 *aOffset; /* Pointer to aType[nField] */ const u8 *aRow; /* Data for the current row, if all on one page */ u32 payloadSize; /* Total number of bytes in the record */ u32 szRow; /* Byte available in aRow */ #ifdef SQLITE_ENABLE_COLUMN_USED_MASK u64 maskUsed; /* Mask of columns used by this cursor */ #endif /* 2*nField extra array elements allocated for aType[], beyond the one ** static element declared in the structure. nField total array slots for ** aType[] and nField+1 array slots for aOffset[] */ u32 aType[1]; /* Type values record decode. MUST BE LAST */ }; /* ** A value for VdbeCursor.cacheStatus that means the cache is always invalid. */ #define CACHE_STALE 0 /* ** When a sub-program is executed (OP_Program), a structure of this type ** is allocated to store the current value of the program counter, as ** well as the current memory cell array and various other frame specific ** values stored in the Vdbe struct. When the sub-program is finished, ** these values are copied back to the Vdbe from the VdbeFrame structure, ** restoring the state of the VM to as it was before the sub-program ** began executing. ** ** The memory for a VdbeFrame object is allocated and managed by a memory ** cell in the parent (calling) frame. When the memory cell is deleted or ** overwritten, the VdbeFrame object is not freed immediately. Instead, it ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing ** this instead of deleting the VdbeFrame immediately is to avoid recursive ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the ** child frame are released. ** ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is ** set to NULL if the currently executing frame is the main program. */ typedef struct VdbeFrame VdbeFrame; struct VdbeFrame { Vdbe *v; /* VM this frame belongs to */ VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */ Op *aOp; /* Program instructions for parent frame */ i64 *anExec; /* Event counters from parent frame */ Mem *aMem; /* Array of memory cells for parent frame */ VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */ void *token; /* Copy of SubProgram.token */ i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ AuxData *pAuxData; /* Linked list of auxdata allocations */ int nCursor; /* Number of entries in apCsr */ int pc; /* Program Counter in parent (calling) frame */ int nOp; /* Size of aOp array */ int nMem; /* Number of entries in aMem */ int nChildMem; /* Number of memory cells for child frame */ int nChildCsr; /* Number of cursors for child frame */ int nChange; /* Statement changes (Vdbe.nChange) */ int nDbChange; /* Value of db->nChange */ }; #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))]) /* ** Internally, the vdbe manipulates nearly all SQL values as Mem ** structures. Each Mem struct may cache multiple representations (string, ** integer etc.) of the same value. */ struct Mem { union MemValue { double r; /* Real value used when MEM_Real is set in flags */ i64 i; /* Integer value used when MEM_Int is set in flags */ int nZero; /* Used when bit MEM_Zero is set in flags */ FuncDef *pDef; /* Used only when flags==MEM_Agg */ RowSet *pRowSet; /* Used only when flags==MEM_RowSet */ VdbeFrame *pFrame; /* Used when flags==MEM_Frame */ } u; u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ u8 eSubtype; /* Subtype for this value */ int n; /* Number of characters in string value, excluding '\0' */ char *z; /* String or BLOB value */ /* ShallowCopy only needs to copy the information above */ char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */ int szMalloc; /* Size of the zMalloc allocation */ u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */ sqlite3 *db; /* The associated database connection */ void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */ #ifdef SQLITE_DEBUG Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */ #endif }; /* ** Size of struct Mem not including the Mem.zMalloc member or anything that ** follows. */ #define MEMCELLSIZE offsetof(Mem,zMalloc) /* One or more of the following flags are set to indicate the validOK ** representations of the value stored in the Mem struct. ** ** If the MEM_Null flag is set, then the value is an SQL NULL value. ** No other flags may be set in this case. ** ** If the MEM_Str flag is set then Mem.z points at a string representation. ** Usually this is encoded in the same unicode encoding as the main ** database (see below for exceptions). If the MEM_Term flag is also ** set, then the string is nul terminated. The MEM_Int and MEM_Real ** flags may coexist with the MEM_Str flag. */ #define MEM_Null 0x0001 /* Value is NULL */ #define MEM_Str 0x0002 /* Value is a string */ #define MEM_Int 0x0004 /* Value is an integer */ #define MEM_Real 0x0008 /* Value is a real number */ #define MEM_Blob 0x0010 /* Value is a BLOB */ #define MEM_AffMask 0x001f /* Mask of affinity bits */ #define MEM_RowSet 0x0020 /* Value is a RowSet object */ #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */ #define MEM_Undefined 0x0080 /* Value is undefined */ #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */ #define MEM_TypeMask 0x81ff /* Mask of type bits */ /* Whenever Mem contains a valid string or blob representation, one of ** the following flags must be set to determine the memory management ** policy for Mem.z. The MEM_Term flag tells us whether or not the ** string is \000 or \u0000 terminated */ #define MEM_Term 0x0200 /* String rep is nul terminated */ #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */ #define MEM_Static 0x0800 /* Mem.z points to a static string */ #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */ #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */ #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */ #ifdef SQLITE_OMIT_INCRBLOB #undef MEM_Zero #define MEM_Zero 0x0000 #endif /* Return TRUE if Mem X contains dynamically allocated content - anything ** that needs to be deallocated to avoid a leak. */ #define VdbeMemDynamic(X) \ (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0) /* ** Clear any existing type flags from a Mem and replace them with f */ #define MemSetTypeFlag(p, f) \ ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) /* ** Return true if a memory cell is not marked as invalid. This macro ** is for use inside assert() statements only. */ #ifdef SQLITE_DEBUG #define memIsValid(M) ((M)->flags & MEM_Undefined)==0 #endif /* ** Each auxiliary data pointer stored by a user defined function ** implementation calling sqlite3_set_auxdata() is stored in an instance ** of this structure. All such structures associated with a single VM ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed ** when the VM is halted (if not before). */ struct AuxData { int iOp; /* Instruction number of OP_Function opcode */ int iArg; /* Index of function argument. */ void *pAux; /* Aux data pointer */ void (*xDelete)(void *); /* Destructor for the aux data */ AuxData *pNext; /* Next element in list */ }; /* ** The "context" argument for an installable function. A pointer to an ** instance of this structure is the first argument to the routines used ** implement the SQL functions. ** ** There is a typedef for this structure in sqlite.h. So all routines, ** even the public interface to SQLite, can use a pointer to this structure. ** But this file is the only place where the internal details of this ** structure are known. ** ** This structure is defined inside of vdbeInt.h because it uses substructures ** (Mem) which are only defined there. */ struct sqlite3_context { Mem *pOut; /* The return value is stored here */ FuncDef *pFunc; /* Pointer to function information */ Mem *pMem; /* Memory cell used to store aggregate context */ Vdbe *pVdbe; /* The VM that owns this context */ int iOp; /* Instruction number of OP_Function */ int isError; /* Error code returned by the function. */ u8 skipFlag; /* Skip accumulator loading if true */ u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */ u8 argc; /* Number of arguments */ sqlite3_value *argv[1]; /* Argument set */ }; /* A bitfield type for use inside of structures. Always follow with :N where ** N is the number of bits. */ typedef unsigned bft; /* Bit Field Type */ typedef struct ScanStatus ScanStatus; struct ScanStatus { int addrExplain; /* OP_Explain for loop */ int addrLoop; /* Address of "loops" counter */ int addrVisit; /* Address of "rows visited" counter */ int iSelectID; /* The "Select-ID" for this loop */ LogEst nEst; /* Estimated output rows per loop */ char *zName; /* Name of table or index */ }; /* ** An instance of the virtual machine. This structure contains the complete ** state of the virtual machine. ** ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare() ** is really a pointer to an instance of this structure. */ struct Vdbe { sqlite3 *db; /* The database connection that owns this statement */ Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */ Parse *pParse; /* Parsing context used to create this Vdbe */ ynVar nVar; /* Number of entries in aVar[] */ u32 magic; /* Magic number for sanity checking */ int nMem; /* Number of memory locations currently allocated */ int nCursor; /* Number of slots in apCsr[] */ u32 cacheCtr; /* VdbeCursor row cache generation counter */ int pc; /* The program counter */ int rc; /* Value to return */ int nChange; /* Number of db changes made since last reset */ int iStatement; /* Statement number (or 0 if has not opened stmt) */ i64 iCurrentTime; /* Value of julianday('now') for this statement */ i64 nFkConstraint; /* Number of imm. FK constraints this VM */ i64 nStmtDefCons; /* Number of def. constraints when stmt started */ i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */ /* When allocating a new Vdbe object, all of the fields below should be ** initialized to zero or NULL */ Op *aOp; /* Space to hold the virtual machine's program */ Mem *aMem; /* The memory locations */ Mem **apArg; /* Arguments to currently executing user function */ Mem *aColName; /* Column names to return */ Mem *pResultSet; /* Pointer to an array of results */ char *zErrMsg; /* Error message written here */ VdbeCursor **apCsr; /* One element of this array for each open cursor */ Mem *aVar; /* Values for the OP_Variable opcode. */ VList *pVList; /* Name of variables */ #ifndef SQLITE_OMIT_TRACE i64 startTime; /* Time when query started - used for profiling */ #endif int nOp; /* Number of instructions in the program */ #ifdef SQLITE_DEBUG int rcApp; /* errcode set by sqlite3_result_error_code() */ #endif u16 nResColumn; /* Number of columns in one row of the result set */ u8 errorAction; /* Recovery action to do in case of an error */ u8 minWriteFileFormat; /* Minimum file format for writable database files */ bft expired:1; /* True if the VM needs to be recompiled */ bft doingRerun:1; /* True if rerunning after an auto-reprepare */ bft explain:2; /* True if EXPLAIN present on SQL command */ bft changeCntOn:1; /* True to update the change-counter */ bft runOnlyOnce:1; /* Automatically expire on reset */ bft usesStmtJournal:1; /* True if uses a statement journal */ bft readOnly:1; /* True for statements that do not write */ bft bIsReader:1; /* True for statements that read */ bft isPrepareV2:1; /* True if prepared with prepare_v2() */ yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */ yDbMask lockMask; /* Subset of btreeMask that requires a lock */ u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */ char *zSql; /* Text of the SQL statement that generated this */ void *pFree; /* Free this when deleting the vdbe */ VdbeFrame *pFrame; /* Parent frame */ VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */ int nFrame; /* Number of frames in pFrame list */ u32 expmask; /* Binding to these vars invalidates VM */ SubProgram *pProgram; /* Linked list of all sub-programs used by VM */ AuxData *pAuxData; /* Linked list of auxdata allocations */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS i64 *anExec; /* Number of times each op has been executed */ int nScan; /* Entries in aScan[] */ ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */ #endif }; /* ** The following are allowed values for Vdbe.magic */ #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */ #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */ #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */ #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */ #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */ /* ** Structure used to store the context required by the ** sqlite3_preupdate_*() API functions. */ struct PreUpdate { Vdbe *v; VdbeCursor *pCsr; /* Cursor to read old values from */ int op; /* One of SQLITE_INSERT, UPDATE, DELETE */ u8 *aRecord; /* old.* database record */ KeyInfo keyinfo; UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */ UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */ int iNewReg; /* Register for new.* values */ i64 iKey1; /* First key value passed to hook */ i64 iKey2; /* Second key value passed to hook */ Mem *aNew; /* Array of new.* values */ Table *pTab; /* Schema object being upated */ Index *pPk; /* PK index if pTab is WITHOUT ROWID */ }; /* ** Function prototypes */ SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...); SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); void sqliteVdbePopStack(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*); SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*); #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*); #endif SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32); SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8); SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*); SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32); SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int); int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*); SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*); SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int); SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*); SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*); SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); #ifdef SQLITE_OMIT_FLOATING_POINT # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 #else SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double); #endif SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16); SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*); SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int); SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8); SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*); SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*); SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*); SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8); SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*); SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p); SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*); SQLITE_PRIVATE const char *sqlite3OpcodeName(int); SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve); SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n); SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int); SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int); #endif SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p); SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *); SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *); SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *); SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *); SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *); SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *); SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *); SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *); #if !defined(SQLITE_OMIT_SHARED_CACHE) SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*); #else # define sqlite3VdbeEnter(X) #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*); #else # define sqlite3VdbeLeave(X) #endif #ifdef SQLITE_DEBUG SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*); SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*); #endif #ifndef SQLITE_OMIT_FOREIGN_KEY SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int); #else # define sqlite3VdbeCheckFk(p,i) 0 #endif SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8); #ifdef SQLITE_DEBUG SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf); #endif SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem); #ifndef SQLITE_OMIT_INCRBLOB SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *); #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0) #else #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK #define ExpandBlob(P) SQLITE_OK #endif #endif /* !defined(SQLITE_VDBEINT_H) */ /************** End of vdbeInt.h *********************************************/ /************** Continuing where we left off in status.c *********************/ /* ** Variables in which to record status information. */ #if SQLITE_PTRSIZE>4 typedef sqlite3_int64 sqlite3StatValueType; #else typedef u32 sqlite3StatValueType; #endif typedef struct sqlite3StatType sqlite3StatType; static SQLITE_WSD struct sqlite3StatType { sqlite3StatValueType nowValue[10]; /* Current value */ sqlite3StatValueType mxValue[10]; /* Maximum value */ } sqlite3Stat = { {0,}, {0,} }; /* ** Elements of sqlite3Stat[] are protected by either the memory allocator ** mutex, or by the pcache1 mutex. The following array determines which. */ static const char statMutex[] = { 0, /* SQLITE_STATUS_MEMORY_USED */ 1, /* SQLITE_STATUS_PAGECACHE_USED */ 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */ 0, /* SQLITE_STATUS_SCRATCH_USED */ 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */ 0, /* SQLITE_STATUS_MALLOC_SIZE */ 0, /* SQLITE_STATUS_PARSER_STACK */ 1, /* SQLITE_STATUS_PAGECACHE_SIZE */ 0, /* SQLITE_STATUS_SCRATCH_SIZE */ 0, /* SQLITE_STATUS_MALLOC_COUNT */ }; /* The "wsdStat" macro will resolve to the status information ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Stat" state vector declared above. */ #ifdef SQLITE_OMIT_WSD # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat) # define wsdStat x[0] #else # define wsdStatInit # define wsdStat sqlite3Stat #endif /* ** Return the current value of a status parameter. The caller must ** be holding the appropriate mutex. */ SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){ wsdStatInit; assert( op>=0 && op<ArraySize(wsdStat.nowValue) ); assert( op>=0 && op<ArraySize(statMutex) ); assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex()) ); return wsdStat.nowValue[op]; } /* ** Add N to the value of a status record. The caller must hold the ** appropriate mutex. (Locking is checked by assert()). ** ** The StatusUp() routine can accept positive or negative values for N. ** The value of N is added to the current status value and the high-water ** mark is adjusted if necessary. ** ** The StatusDown() routine lowers the current value by N. The highwater ** mark is unchanged. N must be non-negative for StatusDown(). */ SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){ wsdStatInit; assert( op>=0 && op<ArraySize(wsdStat.nowValue) ); assert( op>=0 && op<ArraySize(statMutex) ); assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex()) ); wsdStat.nowValue[op] += N; if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){ wsdStat.mxValue[op] = wsdStat.nowValue[op]; } } SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){ wsdStatInit; assert( N>=0 ); assert( op>=0 && op<ArraySize(statMutex) ); assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex()) ); assert( op>=0 && op<ArraySize(wsdStat.nowValue) ); wsdStat.nowValue[op] -= N; } /* ** Adjust the highwater mark if necessary. ** The caller must hold the appropriate mutex. */ SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){ sqlite3StatValueType newValue; wsdStatInit; assert( X>=0 ); newValue = (sqlite3StatValueType)X; assert( op>=0 && op<ArraySize(wsdStat.nowValue) ); assert( op>=0 && op<ArraySize(statMutex) ); assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex()) ); assert( op==SQLITE_STATUS_MALLOC_SIZE || op==SQLITE_STATUS_PAGECACHE_SIZE || op==SQLITE_STATUS_SCRATCH_SIZE || op==SQLITE_STATUS_PARSER_STACK ); if( newValue>wsdStat.mxValue[op] ){ wsdStat.mxValue[op] = newValue; } } /* ** Query status information. */ SQLITE_API int sqlite3_status64( int op, sqlite3_int64 *pCurrent, sqlite3_int64 *pHighwater, int resetFlag ){ sqlite3_mutex *pMutex; wsdStatInit; if( op<0 || op>=ArraySize(wsdStat.nowValue) ){ return SQLITE_MISUSE_BKPT; } #ifdef SQLITE_ENABLE_API_ARMOR if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT; #endif pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex(); sqlite3_mutex_enter(pMutex); *pCurrent = wsdStat.nowValue[op]; *pHighwater = wsdStat.mxValue[op]; if( resetFlag ){ wsdStat.mxValue[op] = wsdStat.nowValue[op]; } sqlite3_mutex_leave(pMutex); (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */ return SQLITE_OK; } SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){ sqlite3_int64 iCur = 0, iHwtr = 0; int rc; #ifdef SQLITE_ENABLE_API_ARMOR if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT; #endif rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag); if( rc==0 ){ *pCurrent = (int)iCur; *pHighwater = (int)iHwtr; } return rc; } /* ** Query status information for a single database connection */ SQLITE_API int sqlite3_db_status( sqlite3 *db, /* The database connection whose status is desired */ int op, /* Status verb */ int *pCurrent, /* Write current value here */ int *pHighwater, /* Write high-water mark here */ int resetFlag /* Reset high-water mark if true */ ){ int rc = SQLITE_OK; /* Return code */ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); switch( op ){ case SQLITE_DBSTATUS_LOOKASIDE_USED: { *pCurrent = db->lookaside.nOut; *pHighwater = db->lookaside.mxOut; if( resetFlag ){ db->lookaside.mxOut = db->lookaside.nOut; } break; } case SQLITE_DBSTATUS_LOOKASIDE_HIT: case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE: case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: { testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT ); testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE ); testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL ); assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 ); assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 ); *pCurrent = 0; *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT]; if( resetFlag ){ db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; } break; } /* ** Return an approximation for the amount of memory currently used ** by all pagers associated with the given database connection. The ** highwater mark is meaningless and is returned as zero. */ case SQLITE_DBSTATUS_CACHE_USED_SHARED: case SQLITE_DBSTATUS_CACHE_USED: { int totalUsed = 0; int i; sqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ Pager *pPager = sqlite3BtreePager(pBt); int nByte = sqlite3PagerMemUsed(pPager); if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){ nByte = nByte / sqlite3BtreeConnectionCount(pBt); } totalUsed += nByte; } } sqlite3BtreeLeaveAll(db); *pCurrent = totalUsed; *pHighwater = 0; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store the schema for all databases (main, temp, and any ATTACHed ** databases. *pHighwater is set to zero. */ case SQLITE_DBSTATUS_SCHEMA_USED: { int i; /* Used to iterate through schemas */ int nByte = 0; /* Used to accumulate return value */ sqlite3BtreeEnterAll(db); db->pnBytesFreed = &nByte; for(i=0; i<db->nDb; i++){ Schema *pSchema = db->aDb[i].pSchema; if( ALWAYS(pSchema!=0) ){ HashElem *p; nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( pSchema->tblHash.count + pSchema->trigHash.count + pSchema->idxHash.count + pSchema->fkeyHash.count ); nByte += sqlite3_msize(pSchema->tblHash.ht); nByte += sqlite3_msize(pSchema->trigHash.ht); nByte += sqlite3_msize(pSchema->idxHash.ht); nByte += sqlite3_msize(pSchema->fkeyHash.ht); for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){ sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)); } for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ sqlite3DeleteTable(db, (Table *)sqliteHashData(p)); } } } db->pnBytesFreed = 0; sqlite3BtreeLeaveAll(db); *pHighwater = 0; *pCurrent = nByte; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store all prepared statements. ** *pHighwater is set to zero. */ case SQLITE_DBSTATUS_STMT_USED: { struct Vdbe *pVdbe; /* Used to iterate through VMs */ int nByte = 0; /* Used to accumulate return value */ db->pnBytesFreed = &nByte; for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){ sqlite3VdbeClearObject(db, pVdbe); sqlite3DbFree(db, pVdbe); } db->pnBytesFreed = 0; *pHighwater = 0; /* IMP: R-64479-57858 */ *pCurrent = nByte; break; } /* ** Set *pCurrent to the total cache hits or misses encountered by all ** pagers the database handle is connected to. *pHighwater is always set ** to zero. */ case SQLITE_DBSTATUS_CACHE_HIT: case SQLITE_DBSTATUS_CACHE_MISS: case SQLITE_DBSTATUS_CACHE_WRITE:{ int i; int nRet = 0; assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 ); assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 ); for(i=0; i<db->nDb; i++){ if( db->aDb[i].pBt ){ Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt); sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet); } } *pHighwater = 0; /* IMP: R-42420-56072 */ /* IMP: R-54100-20147 */ /* IMP: R-29431-39229 */ *pCurrent = nRet; break; } /* Set *pCurrent to non-zero if there are unresolved deferred foreign ** key constraints. Set *pCurrent to zero if all foreign key constraints ** have been satisfied. The *pHighwater is always set to zero. */ case SQLITE_DBSTATUS_DEFERRED_FKS: { *pHighwater = 0; /* IMP: R-11967-56545 */ *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0; break; } default: { rc = SQLITE_ERROR; } } sqlite3_mutex_leave(db->mutex); return rc; } /************** End of status.c **********************************************/ /************** Begin file date.c ********************************************/ /* ** 2003 October 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement date and time ** functions for SQLite. ** ** There is only one exported symbol in this file - the function ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. ** All other code has file scope. ** ** SQLite processes all times and dates as julian day numbers. The ** dates and times are stored as the number of days since noon ** in Greenwich on November 24, 4714 B.C. according to the Gregorian ** calendar system. ** ** 1970-01-01 00:00:00 is JD 2440587.5 ** 2000-01-01 00:00:00 is JD 2451544.5 ** ** This implementation requires years to be expressed as a 4-digit number ** which means that only dates between 0000-01-01 and 9999-12-31 can ** be represented, even though julian day numbers allow a much wider ** range of dates. ** ** The Gregorian calendar system is used for all dates and times, ** even those that predate the Gregorian calendar. Historians usually ** use the julian calendar for dates prior to 1582-10-15 and for some ** dates afterwards, depending on locale. Beware of this difference. ** ** The conversion algorithms are implemented based on descriptions ** in the following text: ** ** Jean Meeus ** Astronomical Algorithms, 2nd Edition, 1998 ** ISBM 0-943396-61-1 ** Willmann-Bell, Inc ** Richmond, Virginia (USA) */ /* #include "sqliteInt.h" */ /* #include <stdlib.h> */ /* #include <assert.h> */ #include <time.h> #ifndef SQLITE_OMIT_DATETIME_FUNCS /* ** The MSVC CRT on Windows CE may not have a localtime() function. ** So declare a substitute. The substitute function itself is ** defined in "os_win.c". */ #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \ (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API) struct tm *__cdecl localtime(const time_t *); #endif /* ** A structure for holding a single date and time. */ typedef struct DateTime DateTime; struct DateTime { sqlite3_int64 iJD; /* The julian day number times 86400000 */ int Y, M, D; /* Year, month, and day */ int h, m; /* Hour and minutes */ int tz; /* Timezone offset in minutes */ double s; /* Seconds */ char validJD; /* True (1) if iJD is valid */ char rawS; /* Raw numeric value stored in s */ char validYMD; /* True (1) if Y,M,D are valid */ char validHMS; /* True (1) if h,m,s are valid */ char validTZ; /* True (1) if tz is valid */ char tzSet; /* Timezone was set explicitly */ char isError; /* An overflow has occurred */ }; /* ** Convert zDate into one or more integers according to the conversion ** specifier zFormat. ** ** zFormat[] contains 4 characters for each integer converted, except for ** the last integer which is specified by three characters. The meaning ** of a four-character format specifiers ABCD is: ** ** A: number of digits to convert. Always "2" or "4". ** B: minimum value. Always "0" or "1". ** C: maximum value, decoded as: ** a: 12 ** b: 14 ** c: 24 ** d: 31 ** e: 59 ** f: 9999 ** D: the separator character, or \000 to indicate this is the ** last number to convert. ** ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-". ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates ** the 2-digit day which is the last integer in the set. ** ** The function returns the number of successful conversions. */ static int getDigits(const char *zDate, const char *zFormat, ...){ /* The aMx[] array translates the 3rd character of each format ** spec into a max size: a b c d e f */ static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 }; va_list ap; int cnt = 0; char nextC; va_start(ap, zFormat); do{ char N = zFormat[0] - '0'; char min = zFormat[1] - '0'; int val = 0; u16 max; assert( zFormat[2]>='a' && zFormat[2]<='f' ); max = aMx[zFormat[2] - 'a']; nextC = zFormat[3]; val = 0; while( N-- ){ if( !sqlite3Isdigit(*zDate) ){ goto end_getDigits; } val = val*10 + *zDate - '0'; zDate++; } if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){ goto end_getDigits; } *va_arg(ap,int*) = val; zDate++; cnt++; zFormat += 4; }while( nextC ); end_getDigits: va_end(ap); return cnt; } /* ** Parse a timezone extension on the end of a date-time. ** The extension is of the form: ** ** (+/-)HH:MM ** ** Or the "zulu" notation: ** ** Z ** ** If the parse is successful, write the number of minutes ** of change in p->tz and return 0. If a parser error occurs, ** return non-zero. ** ** A missing specifier is not considered an error. */ static int parseTimezone(const char *zDate, DateTime *p){ int sgn = 0; int nHr, nMn; int c; while( sqlite3Isspace(*zDate) ){ zDate++; } p->tz = 0; c = *zDate; if( c=='-' ){ sgn = -1; }else if( c=='+' ){ sgn = +1; }else if( c=='Z' || c=='z' ){ zDate++; goto zulu_time; }else{ return c!=0; } zDate++; if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){ return 1; } zDate += 5; p->tz = sgn*(nMn + nHr*60); zulu_time: while( sqlite3Isspace(*zDate) ){ zDate++; } p->tzSet = 1; return *zDate!=0; } /* ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF. ** The HH, MM, and SS must each be exactly 2 digits. The ** fractional seconds FFFF can be one or more digits. ** ** Return 1 if there is a parsing error and 0 on success. */ static int parseHhMmSs(const char *zDate, DateTime *p){ int h, m, s; double ms = 0.0; if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){ return 1; } zDate += 5; if( *zDate==':' ){ zDate++; if( getDigits(zDate, "20e", &s)!=1 ){ return 1; } zDate += 2; if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){ double rScale = 1.0; zDate++; while( sqlite3Isdigit(*zDate) ){ ms = ms*10.0 + *zDate - '0'; rScale *= 10.0; zDate++; } ms /= rScale; } }else{ s = 0; } p->validJD = 0; p->rawS = 0; p->validHMS = 1; p->h = h; p->m = m; p->s = s + ms; if( parseTimezone(zDate, p) ) return 1; p->validTZ = (p->tz!=0)?1:0; return 0; } /* ** Put the DateTime object into its error state. */ static void datetimeError(DateTime *p){ memset(p, 0, sizeof(*p)); p->isError = 1; } /* ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume ** that the YYYY-MM-DD is according to the Gregorian calendar. ** ** Reference: Meeus page 61 */ static void computeJD(DateTime *p){ int Y, M, D, A, B, X1, X2; if( p->validJD ) return; if( p->validYMD ){ Y = p->Y; M = p->M; D = p->D; }else{ Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ M = 1; D = 1; } if( Y<-4713 || Y>9999 || p->rawS ){ datetimeError(p); return; } if( M<=2 ){ Y--; M += 12; } A = Y/100; B = 2 - A + (A/4); X1 = 36525*(Y+4716)/100; X2 = 306001*(M+1)/10000; p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000); p->validJD = 1; if( p->validHMS ){ p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000); if( p->validTZ ){ p->iJD -= p->tz*60000; p->validYMD = 0; p->validHMS = 0; p->validTZ = 0; } } } /* ** Parse dates of the form ** ** YYYY-MM-DD HH:MM:SS.FFF ** YYYY-MM-DD HH:MM:SS ** YYYY-MM-DD HH:MM ** YYYY-MM-DD ** ** Write the result into the DateTime structure and return 0 ** on success and 1 if the input string is not a well-formed ** date. */ static int parseYyyyMmDd(const char *zDate, DateTime *p){ int Y, M, D, neg; if( zDate[0]=='-' ){ zDate++; neg = 1; }else{ neg = 0; } if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){ return 1; } zDate += 10; while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; } if( parseHhMmSs(zDate, p)==0 ){ /* We got the time */ }else if( *zDate==0 ){ p->validHMS = 0; }else{ return 1; } p->validJD = 0; p->validYMD = 1; p->Y = neg ? -Y : Y; p->M = M; p->D = D; if( p->validTZ ){ computeJD(p); } return 0; } /* ** Set the time to the current time reported by the VFS. ** ** Return the number of errors. */ static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){ p->iJD = sqlite3StmtCurrentTime(context); if( p->iJD>0 ){ p->validJD = 1; return 0; }else{ return 1; } } /* ** Input "r" is a numeric quantity which might be a julian day number, ** or the number of seconds since 1970. If the value if r is within ** range of a julian day number, install it as such and set validJD. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS. */ static void setRawDateNumber(DateTime *p, double r){ p->s = r; p->rawS = 1; if( r>=0.0 && r<5373484.5 ){ p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5); p->validJD = 1; } } /* ** Attempt to parse the given string into a julian day number. Return ** the number of errors. ** ** The following are acceptable forms for the input string: ** ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM ** DDDD.DD ** now ** ** In the first form, the +/-HH:MM is always optional. The fractional ** seconds extension (the ".FFF") is optional. The seconds portion ** (":SS.FFF") is option. The year and date can be omitted as long ** as there is a time string. The time string can be omitted as long ** as there is a year and date. */ static int parseDateOrTime( sqlite3_context *context, const char *zDate, DateTime *p ){ double r; if( parseYyyyMmDd(zDate,p)==0 ){ return 0; }else if( parseHhMmSs(zDate, p)==0 ){ return 0; }else if( sqlite3StrICmp(zDate,"now")==0){ return setDateTimeToCurrent(context, p); }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){ setRawDateNumber(p, r); return 0; } return 1; } /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value ** for DateTime.iJD. ** ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with ** such a large integer literal, so we have to encode it. */ #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff) /* ** Return TRUE if the given julian day number is within range. ** ** The input is the JulianDay times 86400000. */ static int validJulianDay(sqlite3_int64 iJD){ return iJD>=0 && iJD<=INT_464269060799999; } /* ** Compute the Year, Month, and Day from the julian day number. */ static void computeYMD(DateTime *p){ int Z, A, B, C, D, E, X1; if( p->validYMD ) return; if( !p->validJD ){ p->Y = 2000; p->M = 1; p->D = 1; }else{ assert( validJulianDay(p->iJD) ); Z = (int)((p->iJD + 43200000)/86400000); A = (int)((Z - 1867216.25)/36524.25); A = Z + 1 + A - (A/4); B = A + 1524; C = (int)((B - 122.1)/365.25); D = (36525*(C&32767))/100; E = (int)((B-D)/30.6001); X1 = (int)(30.6001*E); p->D = B - D - X1; p->M = E<14 ? E-1 : E-13; p->Y = p->M>2 ? C - 4716 : C - 4715; } p->validYMD = 1; } /* ** Compute the Hour, Minute, and Seconds from the julian day number. */ static void computeHMS(DateTime *p){ int s; if( p->validHMS ) return; computeJD(p); s = (int)((p->iJD + 43200000) % 86400000); p->s = s/1000.0; s = (int)p->s; p->s -= s; p->h = s/3600; s -= p->h*3600; p->m = s/60; p->s += s - p->m*60; p->rawS = 0; p->validHMS = 1; } /* ** Compute both YMD and HMS */ static void computeYMD_HMS(DateTime *p){ computeYMD(p); computeHMS(p); } /* ** Clear the YMD and HMS and the TZ */ static void clearYMD_HMS_TZ(DateTime *p){ p->validYMD = 0; p->validHMS = 0; p->validTZ = 0; } #ifndef SQLITE_OMIT_LOCALTIME /* ** On recent Windows platforms, the localtime_s() function is available ** as part of the "Secure CRT". It is essentially equivalent to ** localtime_r() available under most POSIX platforms, except that the ** order of the parameters is reversed. ** ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx. ** ** If the user has not indicated to use localtime_r() or localtime_s() ** already, check for an MSVC build environment that provides ** localtime_s(). */ #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \ && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE) #undef HAVE_LOCALTIME_S #define HAVE_LOCALTIME_S 1 #endif /* ** The following routine implements the rough equivalent of localtime_r() ** using whatever operating-system specific localtime facility that ** is available. This routine returns 0 on success and ** non-zero on any kind of error. ** ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this ** routine will always fail. ** ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C ** library function localtime_r() is used to assist in the calculation of ** local time. */ static int osLocaltime(time_t *t, struct tm *pTm){ int rc; #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S struct tm *pX; #if SQLITE_THREADSAFE>0 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter(mutex); pX = localtime(t); #ifndef SQLITE_UNTESTABLE if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0; #endif if( pX ) *pTm = *pX; sqlite3_mutex_leave(mutex); rc = pX==0; #else #ifndef SQLITE_UNTESTABLE if( sqlite3GlobalConfig.bLocaltimeFault ) return 1; #endif #if HAVE_LOCALTIME_R rc = localtime_r(t, pTm)==0; #else rc = localtime_s(pTm, t); #endif /* HAVE_LOCALTIME_R */ #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */ return rc; } #endif /* SQLITE_OMIT_LOCALTIME */ #ifndef SQLITE_OMIT_LOCALTIME /* ** Compute the difference (in milliseconds) between localtime and UTC ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs, ** return this value and set *pRc to SQLITE_OK. ** ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value ** is undefined in this case. */ static sqlite3_int64 localtimeOffset( DateTime *p, /* Date at which to calculate offset */ sqlite3_context *pCtx, /* Write error here if one occurs */ int *pRc /* OUT: Error code. SQLITE_OK or ERROR */ ){ DateTime x, y; time_t t; struct tm sLocal; /* Initialize the contents of sLocal to avoid a compiler warning. */ memset(&sLocal, 0, sizeof(sLocal)); x = *p; computeYMD_HMS(&x); if( x.Y<1971 || x.Y>=2038 ){ /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only ** works for years between 1970 and 2037. For dates outside this range, ** SQLite attempts to map the year into an equivalent year within this ** range, do the calculation, then map the year back. */ x.Y = 2000; x.M = 1; x.D = 1; x.h = 0; x.m = 0; x.s = 0.0; } else { int s = (int)(x.s + 0.5); x.s = s; } x.tz = 0; x.validJD = 0; computeJD(&x); t = (time_t)(x.iJD/1000 - 21086676*(i64)10000); if( osLocaltime(&t, &sLocal) ){ sqlite3_result_error(pCtx, "local time unavailable", -1); *pRc = SQLITE_ERROR; return 0; } y.Y = sLocal.tm_year + 1900; y.M = sLocal.tm_mon + 1; y.D = sLocal.tm_mday; y.h = sLocal.tm_hour; y.m = sLocal.tm_min; y.s = sLocal.tm_sec; y.validYMD = 1; y.validHMS = 1; y.validJD = 0; y.rawS = 0; y.validTZ = 0; y.isError = 0; computeJD(&y); *pRc = SQLITE_OK; return y.iJD - x.iJD; } #endif /* SQLITE_OMIT_LOCALTIME */ /* ** The following table defines various date transformations of the form ** ** 'NNN days' ** ** Where NNN is an arbitrary floating-point number and "days" can be one ** of several units of time. */ static const struct { u8 eType; /* Transformation type code */ u8 nName; /* Length of th name */ char *zName; /* Name of the transformation */ double rLimit; /* Maximum NNN value for this transform */ double rXform; /* Constant used for this transform */ } aXformType[] = { { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) }, { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) }, { 0, 4, "hour", 128963628.0, 86400000.0/24.0 }, { 0, 3, "day", 5373485.0, 86400000.0 }, { 1, 5, "month", 176546.0, 30.0*86400000.0 }, { 2, 4, "year", 14713.0, 365.0*86400000.0 }, }; /* ** Process a modifier to a date-time stamp. The modifiers are ** as follows: ** ** NNN days ** NNN hours ** NNN minutes ** NNN.NNNN seconds ** NNN months ** NNN years ** start of month ** start of year ** start of week ** start of day ** weekday N ** unixepoch ** localtime ** utc ** ** Return 0 on success and 1 if there is any kind of error. If the error ** is in a system call (i.e. localtime()), then an error message is written ** to context pCtx. If the error is an unrecognized modifier, no error is ** written to pCtx. */ static int parseModifier( sqlite3_context *pCtx, /* Function context */ const char *z, /* The text of the modifier */ int n, /* Length of zMod in bytes */ DateTime *p /* The date/time value to be modified */ ){ int rc = 1; double r; switch(sqlite3UpperToLower[(u8)z[0]] ){ #ifndef SQLITE_OMIT_LOCALTIME case 'l': { /* localtime ** ** Assuming the current time value is UTC (a.k.a. GMT), shift it to ** show local time. */ if( sqlite3_stricmp(z, "localtime")==0 ){ computeJD(p); p->iJD += localtimeOffset(p, pCtx, &rc); clearYMD_HMS_TZ(p); } break; } #endif case 'u': { /* ** unixepoch ** ** Treat the current value of p->s as the number of ** seconds since 1970. Convert to a real julian day number. */ if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){ r = p->s*1000.0 + 210866760000000.0; if( r>=0.0 && r<464269060800000.0 ){ clearYMD_HMS_TZ(p); p->iJD = (sqlite3_int64)r; p->validJD = 1; p->rawS = 0; rc = 0; } } #ifndef SQLITE_OMIT_LOCALTIME else if( sqlite3_stricmp(z, "utc")==0 ){ if( p->tzSet==0 ){ sqlite3_int64 c1; computeJD(p); c1 = localtimeOffset(p, pCtx, &rc); if( rc==SQLITE_OK ){ p->iJD -= c1; clearYMD_HMS_TZ(p); p->iJD += c1 - localtimeOffset(p, pCtx, &rc); } p->tzSet = 1; }else{ rc = SQLITE_OK; } } #endif break; } case 'w': { /* ** weekday N ** ** Move the date to the same time on the next occurrence of ** weekday N where 0==Sunday, 1==Monday, and so forth. If the ** date is already on the appropriate weekday, this is a no-op. */ if( sqlite3_strnicmp(z, "weekday ", 8)==0 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8) && (n=(int)r)==r && n>=0 && r<7 ){ sqlite3_int64 Z; computeYMD_HMS(p); p->validTZ = 0; p->validJD = 0; computeJD(p); Z = ((p->iJD + 129600000)/86400000) % 7; if( Z>n ) Z -= 7; p->iJD += (n - Z)*86400000; clearYMD_HMS_TZ(p); rc = 0; } break; } case 's': { /* ** start of TTTTT ** ** Move the date backwards to the beginning of the current day, ** or month or year. */ if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break; z += 9; computeYMD(p); p->validHMS = 1; p->h = p->m = 0; p->s = 0.0; p->validTZ = 0; p->validJD = 0; if( sqlite3_stricmp(z,"month")==0 ){ p->D = 1; rc = 0; }else if( sqlite3_stricmp(z,"year")==0 ){ computeYMD(p); p->M = 1; p->D = 1; rc = 0; }else if( sqlite3_stricmp(z,"day")==0 ){ rc = 0; } break; } case '+': case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { double rRounder; int i; for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){} if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){ rc = 1; break; } if( z[n]==':' ){ /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the ** specified number of hours, minutes, seconds, and fractional seconds ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be ** omitted. */ const char *z2 = z; DateTime tx; sqlite3_int64 day; if( !sqlite3Isdigit(*z2) ) z2++; memset(&tx, 0, sizeof(tx)); if( parseHhMmSs(z2, &tx) ) break; computeJD(&tx); tx.iJD -= 43200000; day = tx.iJD/86400000; tx.iJD -= day*86400000; if( z[0]=='-' ) tx.iJD = -tx.iJD; computeJD(p); clearYMD_HMS_TZ(p); p->iJD += tx.iJD; rc = 0; break; } /* If control reaches this point, it means the transformation is ** one of the forms like "+NNN days". */ z += n; while( sqlite3Isspace(*z) ) z++; n = sqlite3Strlen30(z); if( n>10 || n<3 ) break; if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--; computeJD(p); rc = 1; rRounder = r<0 ? -0.5 : +0.5; for(i=0; i<ArraySize(aXformType); i++){ if( aXformType[i].nName==n && sqlite3_strnicmp(aXformType[i].zName, z, n)==0 && r>-aXformType[i].rLimit && r<aXformType[i].rLimit ){ switch( aXformType[i].eType ){ case 1: { /* Special processing to add months */ int x; computeYMD_HMS(p); p->M += (int)r; x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; p->Y += x; p->M -= x*12; p->validJD = 0; r -= (int)r; break; } case 2: { /* Special processing to add years */ int y = (int)r; computeYMD_HMS(p); p->Y += y; p->validJD = 0; r -= (int)r; break; } } computeJD(p); p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder); rc = 0; break; } } clearYMD_HMS_TZ(p); break; } default: { break; } } return rc; } /* ** Process time function arguments. argv[0] is a date-time stamp. ** argv[1] and following are modifiers. Parse them all and write ** the resulting time into the DateTime structure p. Return 0 ** on success and 1 if there are any errors. ** ** If there are zero parameters (if even argv[0] is undefined) ** then assume a default value of "now" for argv[0]. */ static int isDate( sqlite3_context *context, int argc, sqlite3_value **argv, DateTime *p ){ int i, n; const unsigned char *z; int eType; memset(p, 0, sizeof(*p)); if( argc==0 ){ return setDateTimeToCurrent(context, p); } if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT || eType==SQLITE_INTEGER ){ setRawDateNumber(p, sqlite3_value_double(argv[0])); }else{ z = sqlite3_value_text(argv[0]); if( !z || parseDateOrTime(context, (char*)z, p) ){ return 1; } } for(i=1; i<argc; i++){ z = sqlite3_value_text(argv[i]); n = sqlite3_value_bytes(argv[i]); if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1; } computeJD(p); if( p->isError || !validJulianDay(p->iJD) ) return 1; return 0; } /* ** The following routines implement the various date and time functions ** of SQLite. */ /* ** julianday( TIMESTRING, MOD, MOD, ...) ** ** Return the julian day number of the date specified in the arguments */ static void juliandayFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ DateTime x; if( isDate(context, argc, argv, &x)==0 ){ computeJD(&x); sqlite3_result_double(context, x.iJD/86400000.0); } } /* ** datetime( TIMESTRING, MOD, MOD, ...) ** ** Return YYYY-MM-DD HH:MM:SS */ static void datetimeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ DateTime x; if( isDate(context, argc, argv, &x)==0 ){ char zBuf[100]; computeYMD_HMS(&x); sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d", x.Y, x.M, x.D, x.h, x.m, (int)(x.s)); sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } /* ** time( TIMESTRING, MOD, MOD, ...) ** ** Return HH:MM:SS */ static void timeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ DateTime x; if( isDate(context, argc, argv, &x)==0 ){ char zBuf[100]; computeHMS(&x); sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s); sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } /* ** date( TIMESTRING, MOD, MOD, ...) ** ** Return YYYY-MM-DD */ static void dateFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ DateTime x; if( isDate(context, argc, argv, &x)==0 ){ char zBuf[100]; computeYMD(&x); sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D); sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } /* ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...) ** ** Return a string described by FORMAT. Conversions as follows: ** ** %d day of month ** %f ** fractional seconds SS.SSS ** %H hour 00-24 ** %j day of year 000-366 ** %J ** julian day number ** %m month 01-12 ** %M minute 00-59 ** %s seconds since 1970-01-01 ** %S seconds 00-59 ** %w day of week 0-6 sunday==0 ** %W week of year 00-53 ** %Y year 0000-9999 ** %% % */ static void strftimeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ DateTime x; u64 n; size_t i,j; char *z; sqlite3 *db; const char *zFmt; char zBuf[100]; if( argc==0 ) return; zFmt = (const char*)sqlite3_value_text(argv[0]); if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return; db = sqlite3_context_db_handle(context); for(i=0, n=1; zFmt[i]; i++, n++){ if( zFmt[i]=='%' ){ switch( zFmt[i+1] ){ case 'd': case 'H': case 'm': case 'M': case 'S': case 'W': n++; /* fall thru */ case 'w': case '%': break; case 'f': n += 8; break; case 'j': n += 3; break; case 'Y': n += 8; break; case 's': case 'J': n += 50; break; default: return; /* ERROR. return a NULL */ } i++; } } testcase( n==sizeof(zBuf)-1 ); testcase( n==sizeof(zBuf) ); testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ); if( n<sizeof(zBuf) ){ z = zBuf; }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){ sqlite3_result_error_toobig(context); return; }else{ z = sqlite3DbMallocRawNN(db, (int)n); if( z==0 ){ sqlite3_result_error_nomem(context); return; } } computeJD(&x); computeYMD_HMS(&x); for(i=j=0; zFmt[i]; i++){ if( zFmt[i]!='%' ){ z[j++] = zFmt[i]; }else{ i++; switch( zFmt[i] ){ case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break; case 'f': { double s = x.s; if( s>59.999 ) s = 59.999; sqlite3_snprintf(7, &z[j],"%06.3f", s); j += sqlite3Strlen30(&z[j]); break; } case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break; case 'W': /* Fall thru */ case 'j': { int nDay; /* Number of days since 1st day of year */ DateTime y = x; y.validJD = 0; y.M = 1; y.D = 1; computeJD(&y); nDay = (int)((x.iJD-y.iJD+43200000)/86400000); if( zFmt[i]=='W' ){ int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */ wd = (int)(((x.iJD+43200000)/86400000)%7); sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7); j += 2; }else{ sqlite3_snprintf(4, &z[j],"%03d",nDay+1); j += 3; } break; } case 'J': { sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0); j+=sqlite3Strlen30(&z[j]); break; } case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break; case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break; case 's': { sqlite3_snprintf(30,&z[j],"%lld", (i64)(x.iJD/1000 - 21086676*(i64)10000)); j += sqlite3Strlen30(&z[j]); break; } case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break; case 'w': { z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0'; break; } case 'Y': { sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]); break; } default: z[j++] = '%'; break; } } } z[j] = 0; sqlite3_result_text(context, z, -1, z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC); } /* ** current_time() ** ** This function returns the same value as time('now'). */ static void ctimeFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); timeFunc(context, 0, 0); } /* ** current_date() ** ** This function returns the same value as date('now'). */ static void cdateFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); dateFunc(context, 0, 0); } /* ** current_timestamp() ** ** This function returns the same value as datetime('now'). */ static void ctimestampFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); datetimeFunc(context, 0, 0); } #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */ #ifdef SQLITE_OMIT_DATETIME_FUNCS /* ** If the library is compiled to omit the full-scale date and time ** handling (to get a smaller binary), the following minimal version ** of the functions current_time(), current_date() and current_timestamp() ** are included instead. This is to support column declarations that ** include "DEFAULT CURRENT_TIME" etc. ** ** This function uses the C-library functions time(), gmtime() ** and strftime(). The format string to pass to strftime() is supplied ** as the user-data for the function. */ static void currentTimeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ time_t t; char *zFormat = (char *)sqlite3_user_data(context); sqlite3_int64 iT; struct tm *pTm; struct tm sNow; char zBuf[20]; UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); iT = sqlite3StmtCurrentTime(context); if( iT<=0 ) return; t = iT/1000 - 10000*(sqlite3_int64)21086676; #if HAVE_GMTIME_R pTm = gmtime_r(&t, &sNow); #else sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); pTm = gmtime(&t); if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); #endif if( pTm ){ strftime(zBuf, 20, zFormat, &sNow); sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } #endif /* ** This function registered all of the above C functions as SQL ** functions. This should be the only routine in this file with ** external linkage. */ SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){ static FuncDef aDateTimeFuncs[] = { #ifndef SQLITE_OMIT_DATETIME_FUNCS DFUNCTION(julianday, -1, 0, 0, juliandayFunc ), DFUNCTION(date, -1, 0, 0, dateFunc ), DFUNCTION(time, -1, 0, 0, timeFunc ), DFUNCTION(datetime, -1, 0, 0, datetimeFunc ), DFUNCTION(strftime, -1, 0, 0, strftimeFunc ), DFUNCTION(current_time, 0, 0, 0, ctimeFunc ), DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc), DFUNCTION(current_date, 0, 0, 0, cdateFunc ), #else STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc), STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc), STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), #endif }; sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs)); } /************** End of date.c ************************************************/ /************** Begin file os.c **********************************************/ /* ** 2005 November 29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains OS interface code that is common to all ** architectures. */ /* #include "sqliteInt.h" */ /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */ SQLITE_API int sqlite3_diskfull_pending = 0; SQLITE_API int sqlite3_diskfull = 0; #endif /* defined(SQLITE_TEST) */ /* ** When testing, also keep a count of the number of open files. */ #if defined(SQLITE_TEST) SQLITE_API int sqlite3_open_file_count = 0; #endif /* defined(SQLITE_TEST) */ /* ** The default SQLite sqlite3_vfs implementations do not allocate ** memory (actually, os_unix.c allocates a small amount of memory ** from within OsOpen()), but some third-party implementations may. ** So we test the effects of a malloc() failing and the sqlite3OsXXX() ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. ** ** The following functions are instrumented for malloc() failure ** testing: ** ** sqlite3OsRead() ** sqlite3OsWrite() ** sqlite3OsSync() ** sqlite3OsFileSize() ** sqlite3OsLock() ** sqlite3OsCheckReservedLock() ** sqlite3OsFileControl() ** sqlite3OsShmMap() ** sqlite3OsOpen() ** sqlite3OsDelete() ** sqlite3OsAccess() ** sqlite3OsFullPathname() ** */ #if defined(SQLITE_TEST) SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1; #define DO_OS_MALLOC_TEST(x) \ if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \ void *pTstAlloc = sqlite3Malloc(10); \ if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \ sqlite3_free(pTstAlloc); \ } #else #define DO_OS_MALLOC_TEST(x) #endif /* ** The following routines are convenience wrappers around methods ** of the sqlite3_file object. This is mostly just syntactic sugar. All ** of this would be completely automatic if SQLite were coded using ** C++ instead of plain old C. */ SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){ if( pId->pMethods ){ pId->pMethods->xClose(pId); pId->pMethods = 0; } } SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){ DO_OS_MALLOC_TEST(id); return id->pMethods->xRead(id, pBuf, amt, offset); } SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){ DO_OS_MALLOC_TEST(id); return id->pMethods->xWrite(id, pBuf, amt, offset); } SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){ return id->pMethods->xTruncate(id, size); } SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){ DO_OS_MALLOC_TEST(id); return id->pMethods->xSync(id, flags); } SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){ DO_OS_MALLOC_TEST(id); return id->pMethods->xFileSize(id, pSize); } SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){ DO_OS_MALLOC_TEST(id); return id->pMethods->xLock(id, lockType); } SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){ return id->pMethods->xUnlock(id, lockType); } SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){ DO_OS_MALLOC_TEST(id); return id->pMethods->xCheckReservedLock(id, pResOut); } /* ** Use sqlite3OsFileControl() when we are doing something that might fail ** and we need to know about the failures. Use sqlite3OsFileControlHint() ** when simply tossing information over the wall to the VFS and we do not ** really care if the VFS receives and understands the information since it ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint() ** routine has no return value since the return value would be meaningless. */ SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ #ifdef SQLITE_TEST if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){ /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite ** is using a regular VFS, it is called after the corresponding ** transaction has been committed. Injecting a fault at this point ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM ** but the transaction is committed anyway. ** ** The core must call OsFileControl() though, not OsFileControlHint(), ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably ** means the commit really has failed and an error should be returned ** to the user. */ DO_OS_MALLOC_TEST(id); } #endif return id->pMethods->xFileControl(id, op, pArg); } SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){ (void)id->pMethods->xFileControl(id, op, pArg); } SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){ int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); } SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ return id->pMethods->xDeviceCharacteristics(id); } SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){ return id->pMethods->xShmLock(id, offset, n, flags); } SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){ id->pMethods->xShmBarrier(id); } SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){ return id->pMethods->xShmUnmap(id, deleteFlag); } SQLITE_PRIVATE int sqlite3OsShmMap( sqlite3_file *id, /* Database file handle */ int iPage, int pgsz, int bExtend, /* True to extend file if necessary */ void volatile **pp /* OUT: Pointer to mapping */ ){ DO_OS_MALLOC_TEST(id); return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp); } #if SQLITE_MAX_MMAP_SIZE>0 /* The real implementation of xFetch and xUnfetch */ SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ DO_OS_MALLOC_TEST(id); return id->pMethods->xFetch(id, iOff, iAmt, pp); } SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ return id->pMethods->xUnfetch(id, iOff, p); } #else /* No-op stubs to use when memory-mapped I/O is disabled */ SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ *pp = 0; return SQLITE_OK; } SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ return SQLITE_OK; } #endif /* ** The next group of routines are convenience wrappers around the ** VFS methods. */ SQLITE_PRIVATE int sqlite3OsOpen( sqlite3_vfs *pVfs, const char *zPath, sqlite3_file *pFile, int flags, int *pFlagsOut ){ int rc; DO_OS_MALLOC_TEST(0); /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before ** reaching the VFS. */ rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut); assert( rc==SQLITE_OK || pFile->pMethods==0 ); return rc; } SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ DO_OS_MALLOC_TEST(0); assert( dirSync==0 || dirSync==1 ); return pVfs->xDelete(pVfs, zPath, dirSync); } SQLITE_PRIVATE int sqlite3OsAccess( sqlite3_vfs *pVfs, const char *zPath, int flags, int *pResOut ){ DO_OS_MALLOC_TEST(0); return pVfs->xAccess(pVfs, zPath, flags, pResOut); } SQLITE_PRIVATE int sqlite3OsFullPathname( sqlite3_vfs *pVfs, const char *zPath, int nPathOut, char *zPathOut ){ DO_OS_MALLOC_TEST(0); zPathOut[0] = 0; return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); } #ifndef SQLITE_OMIT_LOAD_EXTENSION SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ return pVfs->xDlOpen(pVfs, zPath); } SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ pVfs->xDlError(pVfs, nByte, zBufOut); } SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){ return pVfs->xDlSym(pVfs, pHdle, zSym); } SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){ pVfs->xDlClose(pVfs, pHandle); } #endif /* SQLITE_OMIT_LOAD_EXTENSION */ SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ return pVfs->xRandomness(pVfs, nByte, zBufOut); } SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){ return pVfs->xSleep(pVfs, nMicro); } SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){ return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0; } SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ int rc; /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() ** method to get the current date and time if that method is available ** (if iVersion is 2 or greater and the function pointer is not NULL) and ** will fall back to xCurrentTime() if xCurrentTimeInt64() is ** unavailable. */ if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut); }else{ double r; rc = pVfs->xCurrentTime(pVfs, &r); *pTimeOut = (sqlite3_int64)(r*86400000.0); } return rc; } SQLITE_PRIVATE int sqlite3OsOpenMalloc( sqlite3_vfs *pVfs, const char *zFile, sqlite3_file **ppFile, int flags, int *pOutFlags ){ int rc; sqlite3_file *pFile; pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile); if( pFile ){ rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags); if( rc!=SQLITE_OK ){ sqlite3_free(pFile); }else{ *ppFile = pFile; } }else{ rc = SQLITE_NOMEM_BKPT; } return rc; } SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){ assert( pFile ); sqlite3OsClose(pFile); sqlite3_free(pFile); } /* ** This function is a wrapper around the OS specific implementation of ** sqlite3_os_init(). The purpose of the wrapper is to provide the ** ability to simulate a malloc failure, so that the handling of an ** error in sqlite3_os_init() by the upper layers can be tested. */ SQLITE_PRIVATE int sqlite3OsInit(void){ void *p = sqlite3_malloc(10); if( p==0 ) return SQLITE_NOMEM_BKPT; sqlite3_free(p); return sqlite3_os_init(); } /* ** The list of all registered VFS implementations. */ static sqlite3_vfs * SQLITE_WSD vfsList = 0; #define vfsList GLOBAL(sqlite3_vfs *, vfsList) /* ** Locate a VFS by name. If no name is given, simply return the ** first VFS on the list. */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){ sqlite3_vfs *pVfs = 0; #if SQLITE_THREADSAFE sqlite3_mutex *mutex; #endif #ifndef SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if( rc ) return 0; #endif #if SQLITE_THREADSAFE mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter(mutex); for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){ if( zVfs==0 ) break; if( strcmp(zVfs, pVfs->zName)==0 ) break; } sqlite3_mutex_leave(mutex); return pVfs; } /* ** Unlink a VFS from the linked list */ static void vfsUnlink(sqlite3_vfs *pVfs){ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ); if( pVfs==0 ){ /* No-op */ }else if( vfsList==pVfs ){ vfsList = pVfs->pNext; }else if( vfsList ){ sqlite3_vfs *p = vfsList; while( p->pNext && p->pNext!=pVfs ){ p = p->pNext; } if( p->pNext==pVfs ){ p->pNext = pVfs->pNext; } } } /* ** Register a VFS with the system. It is harmless to register the same ** VFS multiple times. The new VFS becomes the default if makeDflt is ** true. */ SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ MUTEX_LOGIC(sqlite3_mutex *mutex;) #ifndef SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if( rc ) return rc; #endif #ifdef SQLITE_ENABLE_API_ARMOR if( pVfs==0 ) return SQLITE_MISUSE_BKPT; #endif MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) sqlite3_mutex_enter(mutex); vfsUnlink(pVfs); if( makeDflt || vfsList==0 ){ pVfs->pNext = vfsList; vfsList = pVfs; }else{ pVfs->pNext = vfsList->pNext; vfsList->pNext = pVfs; } assert(vfsList); sqlite3_mutex_leave(mutex); return SQLITE_OK; } /* ** Unregister a VFS so that it is no longer accessible. */ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter(mutex); vfsUnlink(pVfs); sqlite3_mutex_leave(mutex); return SQLITE_OK; } /************** End of os.c **************************************************/ /************** Begin file fault.c *******************************************/ /* ** 2008 Jan 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code to support the concept of "benign" ** malloc failures (when the xMalloc() or xRealloc() method of the ** sqlite3_mem_methods structure fails to allocate a block of memory ** and returns 0). ** ** Most malloc failures are non-benign. After they occur, SQLite ** abandons the current operation and returns an error code (usually ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily ** fatal. For example, if a malloc fails while resizing a hash table, this ** is completely recoverable simply by not carrying out the resize. The ** hash table will continue to function normally. So a malloc failure ** during a hash table resize is a benign fault. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_UNTESTABLE /* ** Global variables. */ typedef struct BenignMallocHooks BenignMallocHooks; static SQLITE_WSD struct BenignMallocHooks { void (*xBenignBegin)(void); void (*xBenignEnd)(void); } sqlite3Hooks = { 0, 0 }; /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks ** structure. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdHooks can refer directly ** to the "sqlite3Hooks" state vector declared above. */ #ifdef SQLITE_OMIT_WSD # define wsdHooksInit \ BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks) # define wsdHooks x[0] #else # define wsdHooksInit # define wsdHooks sqlite3Hooks #endif /* ** Register hooks to call when sqlite3BeginBenignMalloc() and ** sqlite3EndBenignMalloc() are called, respectively. */ SQLITE_PRIVATE void sqlite3BenignMallocHooks( void (*xBenignBegin)(void), void (*xBenignEnd)(void) ){ wsdHooksInit; wsdHooks.xBenignBegin = xBenignBegin; wsdHooks.xBenignEnd = xBenignEnd; } /* ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() ** indicates that subsequent malloc failures are non-benign. */ SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){ wsdHooksInit; if( wsdHooks.xBenignBegin ){ wsdHooks.xBenignBegin(); } } SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){ wsdHooksInit; if( wsdHooks.xBenignEnd ){ wsdHooks.xBenignEnd(); } } #endif /* #ifndef SQLITE_UNTESTABLE */ /************** End of fault.c ***********************************************/ /************** Begin file mem0.c ********************************************/ /* ** 2008 October 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains a no-op memory allocation drivers for use when ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented ** here always fail. SQLite will not operate with these drivers. These ** are merely placeholders. Real drivers must be substituted using ** sqlite3_config() before SQLite will operate. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is the default. It is ** used when no other memory allocator is specified using compile-time ** macros. */ #ifdef SQLITE_ZERO_MALLOC /* ** No-op versions of all memory allocation routines */ static void *sqlite3MemMalloc(int nByte){ return 0; } static void sqlite3MemFree(void *pPrior){ return; } static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; } static int sqlite3MemSize(void *pPrior){ return 0; } static int sqlite3MemRoundup(int n){ return n; } static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; } static void sqlite3MemShutdown(void *NotUsed){ return; } /* ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ static const sqlite3_mem_methods defaultMethods = { sqlite3MemMalloc, sqlite3MemFree, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, sqlite3MemInit, sqlite3MemShutdown, 0 }; sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } #endif /* SQLITE_ZERO_MALLOC */ /************** End of mem0.c ************************************************/ /************** Begin file mem1.c ********************************************/ /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains low-level memory allocation drivers for when ** SQLite will use the standard C-library malloc/realloc/free interface ** to obtain the memory it needs. ** ** This file contains implementations of the low-level memory allocation ** routines specified in the sqlite3_mem_methods object. The content of ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The ** default configuration is to use memory allocation routines in this ** file. ** ** C-preprocessor macro summary: ** ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if ** the malloc_usable_size() interface exists ** on the target platform. Or, this symbol ** can be set manually, if desired. ** If an equivalent interface exists by ** a different name, using a separate -D ** option to rename it. ** ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone ** memory allocator. Set this symbol to enable ** building on older macs. ** ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of ** _msize() on windows systems. This might ** be necessary when compiling for Delphi, ** for example. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is the default. It is ** used when no other memory allocator is specified using compile-time ** macros. */ #ifdef SQLITE_SYSTEM_MALLOC #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) /* ** Use the zone allocator available on apple products unless the ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined. */ #include <sys/sysctl.h> #include <malloc/malloc.h> #include <libkern/OSAtomic.h> static malloc_zone_t* _sqliteZone_; #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x)) #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x)); #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y)) #define SQLITE_MALLOCSIZE(x) \ (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x)) #else /* if not __APPLE__ */ /* ** Use standard C library malloc and free on non-Apple systems. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined. */ #define SQLITE_MALLOC(x) malloc(x) #define SQLITE_FREE(x) free(x) #define SQLITE_REALLOC(x,y) realloc((x),(y)) /* ** The malloc.h header file is needed for malloc_usable_size() function ** on some systems (e.g. Linux). */ #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE # define SQLITE_USE_MALLOC_H 1 # define SQLITE_USE_MALLOC_USABLE_SIZE 1 /* ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The ** use of _msize() is automatic, but can be disabled by compiling with ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires ** the malloc.h header file. */ #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE) # define SQLITE_USE_MALLOC_H # define SQLITE_USE_MSIZE #endif /* ** Include the malloc.h header file, if necessary. Also set define macro ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize() ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux). ** The memory size function can always be overridden manually by defining ** the macro SQLITE_MALLOCSIZE to the desired function name. */ #if defined(SQLITE_USE_MALLOC_H) # include <malloc.h> # if defined(SQLITE_USE_MALLOC_USABLE_SIZE) # if !defined(SQLITE_MALLOCSIZE) # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x) # endif # elif defined(SQLITE_USE_MSIZE) # if !defined(SQLITE_MALLOCSIZE) # define SQLITE_MALLOCSIZE _msize # endif # endif #endif /* defined(SQLITE_USE_MALLOC_H) */ #endif /* __APPLE__ or not __APPLE__ */ /* ** Like malloc(), but remember the size of the allocation ** so that we can find it later using sqlite3MemSize(). ** ** For this low-level routine, we are guaranteed that nByte>0 because ** cases of nByte<=0 will be intercepted and dealt with by higher level ** routines. */ static void *sqlite3MemMalloc(int nByte){ #ifdef SQLITE_MALLOCSIZE void *p; testcase( ROUND8(nByte)==nByte ); p = SQLITE_MALLOC( nByte ); if( p==0 ){ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); } return p; #else sqlite3_int64 *p; assert( nByte>0 ); testcase( ROUND8(nByte)!=nByte ); p = SQLITE_MALLOC( nByte+8 ); if( p ){ p[0] = nByte; p++; }else{ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); } return (void *)p; #endif } /* ** Like free() but works for allocations obtained from sqlite3MemMalloc() ** or sqlite3MemRealloc(). ** ** For this low-level routine, we already know that pPrior!=0 since ** cases where pPrior==0 will have been intecepted and dealt with ** by higher-level routines. */ static void sqlite3MemFree(void *pPrior){ #ifdef SQLITE_MALLOCSIZE SQLITE_FREE(pPrior); #else sqlite3_int64 *p = (sqlite3_int64*)pPrior; assert( pPrior!=0 ); p--; SQLITE_FREE(p); #endif } /* ** Report the allocated size of a prior return from xMalloc() ** or xRealloc(). */ static int sqlite3MemSize(void *pPrior){ #ifdef SQLITE_MALLOCSIZE assert( pPrior!=0 ); return (int)SQLITE_MALLOCSIZE(pPrior); #else sqlite3_int64 *p; assert( pPrior!=0 ); p = (sqlite3_int64*)pPrior; p--; return (int)p[0]; #endif } /* ** Like realloc(). Resize an allocation previously obtained from ** sqlite3MemMalloc(). ** ** For this low-level interface, we know that pPrior!=0. Cases where ** pPrior==0 while have been intercepted by higher-level routine and ** redirected to xMalloc. Similarly, we know that nByte>0 because ** cases where nByte<=0 will have been intercepted by higher-level ** routines and redirected to xFree. */ static void *sqlite3MemRealloc(void *pPrior, int nByte){ #ifdef SQLITE_MALLOCSIZE void *p = SQLITE_REALLOC(pPrior, nByte); if( p==0 ){ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed memory resize %u to %u bytes", SQLITE_MALLOCSIZE(pPrior), nByte); } return p; #else sqlite3_int64 *p = (sqlite3_int64*)pPrior; assert( pPrior!=0 && nByte>0 ); assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */ p--; p = SQLITE_REALLOC(p, nByte+8 ); if( p ){ p[0] = nByte; p++; }else{ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed memory resize %u to %u bytes", sqlite3MemSize(pPrior), nByte); } return (void*)p; #endif } /* ** Round up a request size to the next valid allocation size. */ static int sqlite3MemRoundup(int n){ return ROUND8(n); } /* ** Initialize this module. */ static int sqlite3MemInit(void *NotUsed){ #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) int cpuCount; size_t len; if( _sqliteZone_ ){ return SQLITE_OK; } len = sizeof(cpuCount); /* One usually wants to use hw.acctivecpu for MT decisions, but not here */ sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0); if( cpuCount>1 ){ /* defer MT decisions to system malloc */ _sqliteZone_ = malloc_default_zone(); }else{ /* only 1 core, use our own zone to contention over global locks, ** e.g. we have our own dedicated locks */ bool success; malloc_zone_t* newzone = malloc_create_zone(4096, 0); malloc_set_zone_name(newzone, "Sqlite_Heap"); do{ success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, (void * volatile *)&_sqliteZone_); }while(!_sqliteZone_); if( !success ){ /* somebody registered a zone first */ malloc_destroy_zone(newzone); } } #endif UNUSED_PARAMETER(NotUsed); return SQLITE_OK; } /* ** Deinitialize this module. */ static void sqlite3MemShutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); return; } /* ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ static const sqlite3_mem_methods defaultMethods = { sqlite3MemMalloc, sqlite3MemFree, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, sqlite3MemInit, sqlite3MemShutdown, 0 }; sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } #endif /* SQLITE_SYSTEM_MALLOC */ /************** End of mem1.c ************************************************/ /************** Begin file mem2.c ********************************************/ /* ** 2007 August 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains low-level memory allocation drivers for when ** SQLite will use the standard C-library malloc/realloc/free interface ** to obtain the memory it needs while adding lots of additional debugging ** information to each allocation in order to help detect and fix memory ** leaks and memory usage errors. ** ** This file contains implementations of the low-level memory allocation ** routines specified in the sqlite3_mem_methods object. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is used only if the ** SQLITE_MEMDEBUG macro is defined */ #ifdef SQLITE_MEMDEBUG /* ** The backtrace functionality is only available with GLIBC */ #ifdef __GLIBC__ extern int backtrace(void**,int); extern void backtrace_symbols_fd(void*const*,int,int); #else # define backtrace(A,B) 1 # define backtrace_symbols_fd(A,B,C) #endif /* #include <stdio.h> */ /* ** Each memory allocation looks like this: ** ** ------------------------------------------------------------------------ ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard | ** ------------------------------------------------------------------------ ** ** The application code sees only a pointer to the allocation. We have ** to back up from the allocation pointer to find the MemBlockHdr. The ** MemBlockHdr tells us the size of the allocation and the number of ** backtrace pointers. There is also a guard word at the end of the ** MemBlockHdr. */ struct MemBlockHdr { i64 iSize; /* Size of this allocation */ struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */ char nBacktrace; /* Number of backtraces on this alloc */ char nBacktraceSlots; /* Available backtrace slots */ u8 nTitle; /* Bytes of title; includes '\0' */ u8 eType; /* Allocation type code */ int iForeGuard; /* Guard word for sanity */ }; /* ** Guard words */ #define FOREGUARD 0x80F5E153 #define REARGUARD 0xE4676B53 /* ** Number of malloc size increments to track. */ #define NCSIZE 1000 /* ** All of the static variables used by this module are collected ** into a single structure named "mem". This is to keep the ** static variables organized and to reduce namespace pollution ** when this module is combined with other in the amalgamation. */ static struct { /* ** Mutex to control access to the memory allocation subsystem. */ sqlite3_mutex *mutex; /* ** Head and tail of a linked list of all outstanding allocations */ struct MemBlockHdr *pFirst; struct MemBlockHdr *pLast; /* ** The number of levels of backtrace to save in new allocations. */ int nBacktrace; void (*xBacktrace)(int, int, void **); /* ** Title text to insert in front of each block */ int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */ char zTitle[100]; /* The title text */ /* ** sqlite3MallocDisallow() increments the following counter. ** sqlite3MallocAllow() decrements it. */ int disallow; /* Do not allow memory allocation */ /* ** Gather statistics on the sizes of memory allocations. ** nAlloc[i] is the number of allocation attempts of i*8 ** bytes. i==NCSIZE is the number of allocation attempts for ** sizes more than NCSIZE*8 bytes. */ int nAlloc[NCSIZE]; /* Total number of allocations */ int nCurrent[NCSIZE]; /* Current number of allocations */ int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */ } mem; /* ** Adjust memory usage statistics */ static void adjustStats(int iSize, int increment){ int i = ROUND8(iSize)/8; if( i>NCSIZE-1 ){ i = NCSIZE - 1; } if( increment>0 ){ mem.nAlloc[i]++; mem.nCurrent[i]++; if( mem.nCurrent[i]>mem.mxCurrent[i] ){ mem.mxCurrent[i] = mem.nCurrent[i]; } }else{ mem.nCurrent[i]--; assert( mem.nCurrent[i]>=0 ); } } /* ** Given an allocation, find the MemBlockHdr for that allocation. ** ** This routine checks the guards at either end of the allocation and ** if they are incorrect it asserts. */ static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ struct MemBlockHdr *p; int *pInt; u8 *pU8; int nReserve; p = (struct MemBlockHdr*)pAllocation; p--; assert( p->iForeGuard==(int)FOREGUARD ); nReserve = ROUND8(p->iSize); pInt = (int*)pAllocation; pU8 = (u8*)pAllocation; assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD ); /* This checks any of the "extra" bytes allocated due ** to rounding up to an 8 byte boundary to ensure ** they haven't been overwritten. */ while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 ); return p; } /* ** Return the number of bytes currently allocated at address p. */ static int sqlite3MemSize(void *p){ struct MemBlockHdr *pHdr; if( !p ){ return 0; } pHdr = sqlite3MemsysGetHeader(p); return (int)pHdr->iSize; } /* ** Initialize the memory allocation subsystem. */ static int sqlite3MemInit(void *NotUsed){ UNUSED_PARAMETER(NotUsed); assert( (sizeof(struct MemBlockHdr)&7) == 0 ); if( !sqlite3GlobalConfig.bMemstat ){ /* If memory status is enabled, then the malloc.c wrapper will already ** hold the STATIC_MEM mutex when the routines here are invoked. */ mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } return SQLITE_OK; } /* ** Deinitialize the memory allocation subsystem. */ static void sqlite3MemShutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); mem.mutex = 0; } /* ** Round up a request size to the next valid allocation size. */ static int sqlite3MemRoundup(int n){ return ROUND8(n); } /* ** Fill a buffer with pseudo-random bytes. This is used to preset ** the content of a new memory allocation to unpredictable values and ** to clear the content of a freed allocation to unpredictable values. */ static void randomFill(char *pBuf, int nByte){ unsigned int x, y, r; x = SQLITE_PTR_TO_INT(pBuf); y = nByte | 1; while( nByte >= 4 ){ x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); y = y*1103515245 + 12345; r = x ^ y; *(int*)pBuf = r; pBuf += 4; nByte -= 4; } while( nByte-- > 0 ){ x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); y = y*1103515245 + 12345; r = x ^ y; *(pBuf++) = r & 0xff; } } /* ** Allocate nByte bytes of memory. */ static void *sqlite3MemMalloc(int nByte){ struct MemBlockHdr *pHdr; void **pBt; char *z; int *pInt; void *p = 0; int totalSize; int nReserve; sqlite3_mutex_enter(mem.mutex); assert( mem.disallow==0 ); nReserve = ROUND8(nByte); totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + mem.nBacktrace*sizeof(void*) + mem.nTitle; p = malloc(totalSize); if( p ){ z = p; pBt = (void**)&z[mem.nTitle]; pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace]; pHdr->pNext = 0; pHdr->pPrev = mem.pLast; if( mem.pLast ){ mem.pLast->pNext = pHdr; }else{ mem.pFirst = pHdr; } mem.pLast = pHdr; pHdr->iForeGuard = FOREGUARD; pHdr->eType = MEMTYPE_HEAP; pHdr->nBacktraceSlots = mem.nBacktrace; pHdr->nTitle = mem.nTitle; if( mem.nBacktrace ){ void *aAddr[40]; pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); assert(pBt[0]); if( mem.xBacktrace ){ mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); } }else{ pHdr->nBacktrace = 0; } if( mem.nTitle ){ memcpy(z, mem.zTitle, mem.nTitle); } pHdr->iSize = nByte; adjustStats(nByte, +1); pInt = (int*)&pHdr[1]; pInt[nReserve/sizeof(int)] = REARGUARD; randomFill((char*)pInt, nByte); memset(((char*)pInt)+nByte, 0x65, nReserve-nByte); p = (void*)pInt; } sqlite3_mutex_leave(mem.mutex); return p; } /* ** Free memory. */ static void sqlite3MemFree(void *pPrior){ struct MemBlockHdr *pHdr; void **pBt; char *z; assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 || mem.mutex!=0 ); pHdr = sqlite3MemsysGetHeader(pPrior); pBt = (void**)pHdr; pBt -= pHdr->nBacktraceSlots; sqlite3_mutex_enter(mem.mutex); if( pHdr->pPrev ){ assert( pHdr->pPrev->pNext==pHdr ); pHdr->pPrev->pNext = pHdr->pNext; }else{ assert( mem.pFirst==pHdr ); mem.pFirst = pHdr->pNext; } if( pHdr->pNext ){ assert( pHdr->pNext->pPrev==pHdr ); pHdr->pNext->pPrev = pHdr->pPrev; }else{ assert( mem.pLast==pHdr ); mem.pLast = pHdr->pPrev; } z = (char*)pBt; z -= pHdr->nTitle; adjustStats((int)pHdr->iSize, -1); randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + (int)pHdr->iSize + sizeof(int) + pHdr->nTitle); free(z); sqlite3_mutex_leave(mem.mutex); } /* ** Change the size of an existing memory allocation. ** ** For this debugging implementation, we *always* make a copy of the ** allocation into a new place in memory. In this way, if the ** higher level code is using pointer to the old allocation, it is ** much more likely to break and we are much more liking to find ** the error. */ static void *sqlite3MemRealloc(void *pPrior, int nByte){ struct MemBlockHdr *pOldHdr; void *pNew; assert( mem.disallow==0 ); assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */ pOldHdr = sqlite3MemsysGetHeader(pPrior); pNew = sqlite3MemMalloc(nByte); if( pNew ){ memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize)); if( nByte>pOldHdr->iSize ){ randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); } sqlite3MemFree(pPrior); } return pNew; } /* ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ static const sqlite3_mem_methods defaultMethods = { sqlite3MemMalloc, sqlite3MemFree, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, sqlite3MemInit, sqlite3MemShutdown, 0 }; sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } /* ** Set the "type" of an allocation. */ SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){ if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ struct MemBlockHdr *pHdr; pHdr = sqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); pHdr->eType = eType; } } /* ** Return TRUE if the mask of type in eType matches the type of the ** allocation p. Also return true if p==NULL. ** ** This routine is designed for use within an assert() statement, to ** verify the type of an allocation. For example: ** ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); */ SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){ int rc = 1; if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ struct MemBlockHdr *pHdr; pHdr = sqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ if( (pHdr->eType&eType)==0 ){ rc = 0; } } return rc; } /* ** Return TRUE if the mask of type in eType matches no bits of the type of the ** allocation p. Also return true if p==NULL. ** ** This routine is designed for use within an assert() statement, to ** verify the type of an allocation. For example: ** ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); */ SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){ int rc = 1; if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ struct MemBlockHdr *pHdr; pHdr = sqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ if( (pHdr->eType&eType)!=0 ){ rc = 0; } } return rc; } /* ** Set the number of backtrace levels kept for each allocation. ** A value of zero turns off backtracing. The number is always rounded ** up to a multiple of 2. */ SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){ if( depth<0 ){ depth = 0; } if( depth>20 ){ depth = 20; } depth = (depth+1)&0xfe; mem.nBacktrace = depth; } SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ mem.xBacktrace = xBacktrace; } /* ** Set the title string for subsequent allocations. */ SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){ unsigned int n = sqlite3Strlen30(zTitle) + 1; sqlite3_mutex_enter(mem.mutex); if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; memcpy(mem.zTitle, zTitle, n); mem.zTitle[n] = 0; mem.nTitle = ROUND8(n); sqlite3_mutex_leave(mem.mutex); } SQLITE_PRIVATE void sqlite3MemdebugSync(){ struct MemBlockHdr *pHdr; for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ void **pBt = (void**)pHdr; pBt -= pHdr->nBacktraceSlots; mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); } } /* ** Open the file indicated and write a log of all unfreed memory ** allocations into that log. */ SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){ FILE *out; struct MemBlockHdr *pHdr; void **pBt; int i; out = fopen(zFilename, "w"); if( out==0 ){ fprintf(stderr, "** Unable to output memory debug output log: %s **\n", zFilename); return; } for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ char *z = (char*)pHdr; z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; fprintf(out, "**** %lld bytes at %p from %s ****\n", pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); if( pHdr->nBacktrace ){ fflush(out); pBt = (void**)pHdr; pBt -= pHdr->nBacktraceSlots; backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); fprintf(out, "\n"); } } fprintf(out, "COUNTS:\n"); for(i=0; i<NCSIZE-1; i++){ if( mem.nAlloc[i] ){ fprintf(out, " %5d: %10d %10d %10d\n", i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]); } } if( mem.nAlloc[NCSIZE-1] ){ fprintf(out, " %5d: %10d %10d %10d\n", NCSIZE*8-8, mem.nAlloc[NCSIZE-1], mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]); } fclose(out); } /* ** Return the number of times sqlite3MemMalloc() has been called. */ SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){ int i; int nTotal = 0; for(i=0; i<NCSIZE; i++){ nTotal += mem.nAlloc[i]; } return nTotal; } #endif /* SQLITE_MEMDEBUG */ /************** End of mem2.c ************************************************/ /************** Begin file mem3.c ********************************************/ /* ** 2007 October 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement a memory ** allocation subsystem for use by SQLite. ** ** This version of the memory allocation subsystem omits all ** use of malloc(). The SQLite user supplies a block of memory ** before calling sqlite3_initialize() from which allocations ** are made and returned by the xMalloc() and xRealloc() ** implementations. Once sqlite3_initialize() has been called, ** the amount of memory available to SQLite is fixed and cannot ** be changed. ** ** This version of the memory allocation subsystem is included ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is only built into the library ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not ** mean that the library will use a memory-pool by default, just that ** it is available. The mempool allocator is activated by calling ** sqlite3_config(). */ #ifdef SQLITE_ENABLE_MEMSYS3 /* ** Maximum size (in Mem3Blocks) of a "small" chunk. */ #define MX_SMALL 10 /* ** Number of freelist hash slots */ #define N_HASH 61 /* ** A memory allocation (also called a "chunk") consists of two or ** more blocks where each block is 8 bytes. The first 8 bytes are ** a header that is not returned to the user. ** ** A chunk is two or more blocks that is either checked out or ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the ** size of the allocation in blocks if the allocation is free. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit ** is true if the previous chunk is checked out and false if the ** previous chunk is free. The u.hdr.prevSize field is the size of ** the previous chunk in blocks if the previous chunk is on the ** freelist. If the previous chunk is checked out, then ** u.hdr.prevSize can be part of the data for that chunk and should ** not be read or written. ** ** We often identify a chunk by its index in mem3.aPool[]. When ** this is done, the chunk index refers to the second block of ** the chunk. In this way, the first chunk has an index of 1. ** A chunk index of 0 means "no such chunk" and is the equivalent ** of a NULL pointer. ** ** The second block of free chunks is of the form u.list. The ** two fields form a double-linked list of chunks of related sizes. ** Pointers to the head of the list are stored in mem3.aiSmall[] ** for smaller chunks and mem3.aiHash[] for larger chunks. ** ** The second block of a chunk is user data if the chunk is checked ** out. If a chunk is checked out, the user data may extend into ** the u.hdr.prevSize value of the following chunk. */ typedef struct Mem3Block Mem3Block; struct Mem3Block { union { struct { u32 prevSize; /* Size of previous chunk in Mem3Block elements */ u32 size4x; /* 4x the size of current chunk in Mem3Block elements */ } hdr; struct { u32 next; /* Index in mem3.aPool[] of next free chunk */ u32 prev; /* Index in mem3.aPool[] of previous free chunk */ } list; } u; }; /* ** All of the static variables used by this module are collected ** into a single structure named "mem3". This is to keep the ** static variables organized and to reduce namespace pollution ** when this module is combined with other in the amalgamation. */ static SQLITE_WSD struct Mem3Global { /* ** Memory available for allocation. nPool is the size of the array ** (in Mem3Blocks) pointed to by aPool less 2. */ u32 nPool; Mem3Block *aPool; /* ** True if we are evaluating an out-of-memory callback. */ int alarmBusy; /* ** Mutex to control access to the memory allocation subsystem. */ sqlite3_mutex *mutex; /* ** The minimum amount of free space that we have seen. */ u32 mnMaster; /* ** iMaster is the index of the master chunk. Most new allocations ** occur off of this chunk. szMaster is the size (in Mem3Blocks) ** of the current master. iMaster is 0 if there is not master chunk. ** The master chunk is not in either the aiHash[] or aiSmall[]. */ u32 iMaster; u32 szMaster; /* ** Array of lists of free blocks according to the block size ** for smaller chunks, or a hash on the block size for larger ** chunks. */ u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */ u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */ } mem3 = { 97535575 }; #define mem3 GLOBAL(struct Mem3Global, mem3) /* ** Unlink the chunk at mem3.aPool[i] from list it is currently ** on. *pRoot is the list that i is a member of. */ static void memsys3UnlinkFromList(u32 i, u32 *pRoot){ u32 next = mem3.aPool[i].u.list.next; u32 prev = mem3.aPool[i].u.list.prev; assert( sqlite3_mutex_held(mem3.mutex) ); if( prev==0 ){ *pRoot = next; }else{ mem3.aPool[prev].u.list.next = next; } if( next ){ mem3.aPool[next].u.list.prev = prev; } mem3.aPool[i].u.list.next = 0; mem3.aPool[i].u.list.prev = 0; } /* ** Unlink the chunk at index i from ** whatever list is currently a member of. */ static void memsys3Unlink(u32 i){ u32 size, hash; assert( sqlite3_mutex_held(mem3.mutex) ); assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); assert( i>=1 ); size = mem3.aPool[i-1].u.hdr.size4x/4; assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); assert( size>=2 ); if( size <= MX_SMALL ){ memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]); }else{ hash = size % N_HASH; memsys3UnlinkFromList(i, &mem3.aiHash[hash]); } } /* ** Link the chunk at mem3.aPool[i] so that is on the list rooted ** at *pRoot. */ static void memsys3LinkIntoList(u32 i, u32 *pRoot){ assert( sqlite3_mutex_held(mem3.mutex) ); mem3.aPool[i].u.list.next = *pRoot; mem3.aPool[i].u.list.prev = 0; if( *pRoot ){ mem3.aPool[*pRoot].u.list.prev = i; } *pRoot = i; } /* ** Link the chunk at index i into either the appropriate ** small chunk list, or into the large chunk hash table. */ static void memsys3Link(u32 i){ u32 size, hash; assert( sqlite3_mutex_held(mem3.mutex) ); assert( i>=1 ); assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); size = mem3.aPool[i-1].u.hdr.size4x/4; assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); assert( size>=2 ); if( size <= MX_SMALL ){ memsys3LinkIntoList(i, &mem3.aiSmall[size-2]); }else{ hash = size % N_HASH; memsys3LinkIntoList(i, &mem3.aiHash[hash]); } } /* ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex ** will already be held (obtained by code in malloc.c) if ** sqlite3GlobalConfig.bMemStat is true. */ static void memsys3Enter(void){ if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){ mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } sqlite3_mutex_enter(mem3.mutex); } static void memsys3Leave(void){ sqlite3_mutex_leave(mem3.mutex); } /* ** Called when we are unable to satisfy an allocation of nBytes. */ static void memsys3OutOfMemory(int nByte){ if( !mem3.alarmBusy ){ mem3.alarmBusy = 1; assert( sqlite3_mutex_held(mem3.mutex) ); sqlite3_mutex_leave(mem3.mutex); sqlite3_release_memory(nByte); sqlite3_mutex_enter(mem3.mutex); mem3.alarmBusy = 0; } } /* ** Chunk i is a free chunk that has been unlinked. Adjust its ** size parameters for check-out and return a pointer to the ** user portion of the chunk. */ static void *memsys3Checkout(u32 i, u32 nBlock){ u32 x; assert( sqlite3_mutex_held(mem3.mutex) ); assert( i>=1 ); assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ); assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock ); x = mem3.aPool[i-1].u.hdr.size4x; mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2); mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock; mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2; return &mem3.aPool[i]; } /* ** Carve a piece off of the end of the mem3.iMaster free chunk. ** Return a pointer to the new allocation. Or, if the master chunk ** is not large enough, return 0. */ static void *memsys3FromMaster(u32 nBlock){ assert( sqlite3_mutex_held(mem3.mutex) ); assert( mem3.szMaster>=nBlock ); if( nBlock>=mem3.szMaster-1 ){ /* Use the entire master */ void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster); mem3.iMaster = 0; mem3.szMaster = 0; mem3.mnMaster = 0; return p; }else{ /* Split the master block. Return the tail. */ u32 newi, x; newi = mem3.iMaster + mem3.szMaster - nBlock; assert( newi > mem3.iMaster+1 ); mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock; mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2; mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; mem3.szMaster -= nBlock; mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster; x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; if( mem3.szMaster < mem3.mnMaster ){ mem3.mnMaster = mem3.szMaster; } return (void*)&mem3.aPool[newi]; } } /* ** *pRoot is the head of a list of free chunks of the same size ** or same size hash. In other words, *pRoot is an entry in either ** mem3.aiSmall[] or mem3.aiHash[]. ** ** This routine examines all entries on the given list and tries ** to coalesce each entries with adjacent free chunks. ** ** If it sees a chunk that is larger than mem3.iMaster, it replaces ** the current mem3.iMaster with the new larger chunk. In order for ** this mem3.iMaster replacement to work, the master chunk must be ** linked into the hash tables. That is not the normal state of ** affairs, of course. The calling routine must link the master ** chunk before invoking this routine, then must unlink the (possibly ** changed) master chunk once this routine has finished. */ static void memsys3Merge(u32 *pRoot){ u32 iNext, prev, size, i, x; assert( sqlite3_mutex_held(mem3.mutex) ); for(i=*pRoot; i>0; i=iNext){ iNext = mem3.aPool[i].u.list.next; size = mem3.aPool[i-1].u.hdr.size4x; assert( (size&1)==0 ); if( (size&2)==0 ){ memsys3UnlinkFromList(i, pRoot); assert( i > mem3.aPool[i-1].u.hdr.prevSize ); prev = i - mem3.aPool[i-1].u.hdr.prevSize; if( prev==iNext ){ iNext = mem3.aPool[prev].u.list.next; } memsys3Unlink(prev); size = i + size/4 - prev; x = mem3.aPool[prev-1].u.hdr.size4x & 2; mem3.aPool[prev-1].u.hdr.size4x = size*4 | x; mem3.aPool[prev+size-1].u.hdr.prevSize = size; memsys3Link(prev); i = prev; }else{ size /= 4; } if( size>mem3.szMaster ){ mem3.iMaster = i; mem3.szMaster = size; } } } /* ** Return a block of memory of at least nBytes in size. ** Return NULL if unable. ** ** This function assumes that the necessary mutexes, if any, are ** already held by the caller. Hence "Unsafe". */ static void *memsys3MallocUnsafe(int nByte){ u32 i; u32 nBlock; u32 toFree; assert( sqlite3_mutex_held(mem3.mutex) ); assert( sizeof(Mem3Block)==8 ); if( nByte<=12 ){ nBlock = 2; }else{ nBlock = (nByte + 11)/8; } assert( nBlock>=2 ); /* STEP 1: ** Look for an entry of the correct size in either the small ** chunk table or in the large chunk hash table. This is ** successful most of the time (about 9 times out of 10). */ if( nBlock <= MX_SMALL ){ i = mem3.aiSmall[nBlock-2]; if( i>0 ){ memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]); return memsys3Checkout(i, nBlock); } }else{ int hash = nBlock % N_HASH; for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){ if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){ memsys3UnlinkFromList(i, &mem3.aiHash[hash]); return memsys3Checkout(i, nBlock); } } } /* STEP 2: ** Try to satisfy the allocation by carving a piece off of the end ** of the master chunk. This step usually works if step 1 fails. */ if( mem3.szMaster>=nBlock ){ return memsys3FromMaster(nBlock); } /* STEP 3: ** Loop through the entire memory pool. Coalesce adjacent free ** chunks. Recompute the master chunk as the largest free chunk. ** Then try again to satisfy the allocation by carving a piece off ** of the end of the master chunk. This step happens very ** rarely (we hope!) */ for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){ memsys3OutOfMemory(toFree); if( mem3.iMaster ){ memsys3Link(mem3.iMaster); mem3.iMaster = 0; mem3.szMaster = 0; } for(i=0; i<N_HASH; i++){ memsys3Merge(&mem3.aiHash[i]); } for(i=0; i<MX_SMALL-1; i++){ memsys3Merge(&mem3.aiSmall[i]); } if( mem3.szMaster ){ memsys3Unlink(mem3.iMaster); if( mem3.szMaster>=nBlock ){ return memsys3FromMaster(nBlock); } } } /* If none of the above worked, then we fail. */ return 0; } /* ** Free an outstanding memory allocation. ** ** This function assumes that the necessary mutexes, if any, are ** already held by the caller. Hence "Unsafe". */ static void memsys3FreeUnsafe(void *pOld){ Mem3Block *p = (Mem3Block*)pOld; int i; u32 size, x; assert( sqlite3_mutex_held(mem3.mutex) ); assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] ); i = p - mem3.aPool; assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 ); size = mem3.aPool[i-1].u.hdr.size4x/4; assert( i+size<=mem3.nPool+1 ); mem3.aPool[i-1].u.hdr.size4x &= ~1; mem3.aPool[i+size-1].u.hdr.prevSize = size; mem3.aPool[i+size-1].u.hdr.size4x &= ~2; memsys3Link(i); /* Try to expand the master using the newly freed chunk */ if( mem3.iMaster ){ while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){ size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize; mem3.iMaster -= size; mem3.szMaster += size; memsys3Unlink(mem3.iMaster); x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; } x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){ memsys3Unlink(mem3.iMaster+mem3.szMaster); mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4; mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; } } } /* ** Return the size of an outstanding allocation, in bytes. The ** size returned omits the 8-byte header overhead. This only ** works for chunks that are currently checked out. */ static int memsys3Size(void *p){ Mem3Block *pBlock; assert( p!=0 ); pBlock = (Mem3Block*)p; assert( (pBlock[-1].u.hdr.size4x&1)!=0 ); return (pBlock[-1].u.hdr.size4x&~3)*2 - 4; } /* ** Round up a request size to the next valid allocation size. */ static int memsys3Roundup(int n){ if( n<=12 ){ return 12; }else{ return ((n+11)&~7) - 4; } } /* ** Allocate nBytes of memory. */ static void *memsys3Malloc(int nBytes){ sqlite3_int64 *p; assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */ memsys3Enter(); p = memsys3MallocUnsafe(nBytes); memsys3Leave(); return (void*)p; } /* ** Free memory. */ static void memsys3Free(void *pPrior){ assert( pPrior ); memsys3Enter(); memsys3FreeUnsafe(pPrior); memsys3Leave(); } /* ** Change the size of an existing memory allocation */ static void *memsys3Realloc(void *pPrior, int nBytes){ int nOld; void *p; if( pPrior==0 ){ return sqlite3_malloc(nBytes); } if( nBytes<=0 ){ sqlite3_free(pPrior); return 0; } nOld = memsys3Size(pPrior); if( nBytes<=nOld && nBytes>=nOld-128 ){ return pPrior; } memsys3Enter(); p = memsys3MallocUnsafe(nBytes); if( p ){ if( nOld<nBytes ){ memcpy(p, pPrior, nOld); }else{ memcpy(p, pPrior, nBytes); } memsys3FreeUnsafe(pPrior); } memsys3Leave(); return p; } /* ** Initialize this module. */ static int memsys3Init(void *NotUsed){ UNUSED_PARAMETER(NotUsed); if( !sqlite3GlobalConfig.pHeap ){ return SQLITE_ERROR; } /* Store a pointer to the memory block in global structure mem3. */ assert( sizeof(Mem3Block)==8 ); mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap; mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2; /* Initialize the master block. */ mem3.szMaster = mem3.nPool; mem3.mnMaster = mem3.szMaster; mem3.iMaster = 1; mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2; mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool; mem3.aPool[mem3.nPool].u.hdr.size4x = 1; return SQLITE_OK; } /* ** Deinitialize this module. */ static void memsys3Shutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); mem3.mutex = 0; return; } /* ** Open the file indicated and write a log of all unfreed memory ** allocations into that log. */ SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){ #ifdef SQLITE_DEBUG FILE *out; u32 i, j; u32 size; if( zFilename==0 || zFilename[0]==0 ){ out = stdout; }else{ out = fopen(zFilename, "w"); if( out==0 ){ fprintf(stderr, "** Unable to output memory debug output log: %s **\n", zFilename); return; } } memsys3Enter(); fprintf(out, "CHUNKS:\n"); for(i=1; i<=mem3.nPool; i+=size/4){ size = mem3.aPool[i-1].u.hdr.size4x; if( size/4<=1 ){ fprintf(out, "%p size error\n", &mem3.aPool[i]); assert( 0 ); break; } if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){ fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]); assert( 0 ); break; } if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){ fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]); assert( 0 ); break; } if( size&1 ){ fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8); }else{ fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8, i==mem3.iMaster ? " **master**" : ""); } } for(i=0; i<MX_SMALL-1; i++){ if( mem3.aiSmall[i]==0 ) continue; fprintf(out, "small(%2d):", i); for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){ fprintf(out, " %p(%d)", &mem3.aPool[j], (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); } fprintf(out, "\n"); } for(i=0; i<N_HASH; i++){ if( mem3.aiHash[i]==0 ) continue; fprintf(out, "hash(%2d):", i); for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){ fprintf(out, " %p(%d)", &mem3.aPool[j], (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); } fprintf(out, "\n"); } fprintf(out, "master=%d\n", mem3.iMaster); fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8); fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8); sqlite3_mutex_leave(mem3.mutex); if( out==stdout ){ fflush(stdout); }else{ fclose(out); } #else UNUSED_PARAMETER(zFilename); #endif } /* ** This routine is the only routine in this file with external ** linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. The ** arguments specify the block of memory to manage. ** ** This routine is only called by sqlite3_config(), and therefore ** is not required to be threadsafe (it is not). */ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ static const sqlite3_mem_methods mempoolMethods = { memsys3Malloc, memsys3Free, memsys3Realloc, memsys3Size, memsys3Roundup, memsys3Init, memsys3Shutdown, 0 }; return &mempoolMethods; } #endif /* SQLITE_ENABLE_MEMSYS3 */ /************** End of mem3.c ************************************************/ /************** Begin file mem5.c ********************************************/ /* ** 2007 October 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement a memory ** allocation subsystem for use by SQLite. ** ** This version of the memory allocation subsystem omits all ** use of malloc(). The application gives SQLite a block of memory ** before calling sqlite3_initialize() from which allocations ** are made and returned by the xMalloc() and xRealloc() ** implementations. Once sqlite3_initialize() has been called, ** the amount of memory available to SQLite is fixed and cannot ** be changed. ** ** This version of the memory allocation subsystem is included ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined. ** ** This memory allocator uses the following algorithm: ** ** 1. All memory allocation sizes are rounded up to a power of 2. ** ** 2. If two adjacent free blocks are the halves of a larger block, ** then the two blocks are coalesced into the single larger block. ** ** 3. New memory is allocated from the first available free block. ** ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions ** Concerning Dynamic Storage Allocation". Journal of the Association for ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499. ** ** Let n be the size of the largest allocation divided by the minimum ** allocation size (after rounding all sizes up to a power of 2.) Let M ** be the maximum amount of memory ever outstanding at one time. Let ** N be the total amount of memory available for allocation. Robson ** proved that this memory allocator will never breakdown due to ** fragmentation as long as the following constraint holds: ** ** N >= M*(1 + log2(n)/2) - n + 1 ** ** The sqlite3_status() logic tracks the maximum values of n and M so ** that an application can, at any time, verify this constraint. */ /* #include "sqliteInt.h" */ /* ** This version of the memory allocator is used only when ** SQLITE_ENABLE_MEMSYS5 is defined. */ #ifdef SQLITE_ENABLE_MEMSYS5 /* ** A minimum allocation is an instance of the following structure. ** Larger allocations are an array of these structures where the ** size of the array is a power of 2. ** ** The size of this object must be a power of two. That fact is ** verified in memsys5Init(). */ typedef struct Mem5Link Mem5Link; struct Mem5Link { int next; /* Index of next free chunk */ int prev; /* Index of previous free chunk */ }; /* ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since ** mem5.szAtom is always at least 8 and 32-bit integers are used, ** it is not actually possible to reach this limit. */ #define LOGMAX 30 /* ** Masks used for mem5.aCtrl[] elements. */ #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */ #define CTRL_FREE 0x20 /* True if not checked out */ /* ** All of the static variables used by this module are collected ** into a single structure named "mem5". This is to keep the ** static variables organized and to reduce namespace pollution ** when this module is combined with other in the amalgamation. */ static SQLITE_WSD struct Mem5Global { /* ** Memory available for allocation */ int szAtom; /* Smallest possible allocation in bytes */ int nBlock; /* Number of szAtom sized blocks in zPool */ u8 *zPool; /* Memory available to be allocated */ /* ** Mutex to control access to the memory allocation subsystem. */ sqlite3_mutex *mutex; #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* ** Performance statistics */ u64 nAlloc; /* Total number of calls to malloc */ u64 totalAlloc; /* Total of all malloc calls - includes internal frag */ u64 totalExcess; /* Total internal fragmentation */ u32 currentOut; /* Current checkout, including internal fragmentation */ u32 currentCount; /* Current number of distinct checkouts */ u32 maxOut; /* Maximum instantaneous currentOut */ u32 maxCount; /* Maximum instantaneous currentCount */ u32 maxRequest; /* Largest allocation (exclusive of internal frag) */ #endif /* ** Lists of free blocks. aiFreelist[0] is a list of free blocks of ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth. */ int aiFreelist[LOGMAX+1]; /* ** Space for tracking which blocks are checked out and the size ** of each block. One byte per block. */ u8 *aCtrl; } mem5; /* ** Access the static variable through a macro for SQLITE_OMIT_WSD. */ #define mem5 GLOBAL(struct Mem5Global, mem5) /* ** Assuming mem5.zPool is divided up into an array of Mem5Link ** structures, return a pointer to the idx-th such link. */ #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom])) /* ** Unlink the chunk at mem5.aPool[i] from list it is currently ** on. It should be found on mem5.aiFreelist[iLogsize]. */ static void memsys5Unlink(int i, int iLogsize){ int next, prev; assert( i>=0 && i<mem5.nBlock ); assert( iLogsize>=0 && iLogsize<=LOGMAX ); assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); next = MEM5LINK(i)->next; prev = MEM5LINK(i)->prev; if( prev<0 ){ mem5.aiFreelist[iLogsize] = next; }else{ MEM5LINK(prev)->next = next; } if( next>=0 ){ MEM5LINK(next)->prev = prev; } } /* ** Link the chunk at mem5.aPool[i] so that is on the iLogsize ** free list. */ static void memsys5Link(int i, int iLogsize){ int x; assert( sqlite3_mutex_held(mem5.mutex) ); assert( i>=0 && i<mem5.nBlock ); assert( iLogsize>=0 && iLogsize<=LOGMAX ); assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize]; MEM5LINK(i)->prev = -1; if( x>=0 ){ assert( x<mem5.nBlock ); MEM5LINK(x)->prev = i; } mem5.aiFreelist[iLogsize] = i; } /* ** Obtain or release the mutex needed to access global data structures. */ static void memsys5Enter(void){ sqlite3_mutex_enter(mem5.mutex); } static void memsys5Leave(void){ sqlite3_mutex_leave(mem5.mutex); } /* ** Return the size of an outstanding allocation, in bytes. ** This only works for chunks that are currently checked out. */ static int memsys5Size(void *p){ int iSize, i; assert( p!=0 ); i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom); assert( i>=0 && i<mem5.nBlock ); iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE)); return iSize; } /* ** Return a block of memory of at least nBytes in size. ** Return NULL if unable. Return NULL if nBytes==0. ** ** The caller guarantees that nByte is positive. ** ** The caller has obtained a mutex prior to invoking this ** routine so there is never any chance that two or more ** threads can be in this routine at the same time. */ static void *memsys5MallocUnsafe(int nByte){ int i; /* Index of a mem5.aPool[] slot */ int iBin; /* Index into mem5.aiFreelist[] */ int iFullSz; /* Size of allocation rounded up to power of 2 */ int iLogsize; /* Log2 of iFullSz/POW2_MIN */ /* nByte must be a positive */ assert( nByte>0 ); /* No more than 1GiB per allocation */ if( nByte > 0x40000000 ) return 0; #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* Keep track of the maximum allocation request. Even unfulfilled ** requests are counted */ if( (u32)nByte>mem5.maxRequest ){ mem5.maxRequest = nByte; } #endif /* Round nByte up to the next valid power of two */ for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){} /* Make sure mem5.aiFreelist[iLogsize] contains at least one free ** block. If not, then split a block of the next larger power of ** two in order to create a new free block of size iLogsize. */ for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){} if( iBin>LOGMAX ){ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte); return 0; } i = mem5.aiFreelist[iBin]; memsys5Unlink(i, iBin); while( iBin>iLogsize ){ int newSize; iBin--; newSize = 1 << iBin; mem5.aCtrl[i+newSize] = CTRL_FREE | iBin; memsys5Link(i+newSize, iBin); } mem5.aCtrl[i] = iLogsize; #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* Update allocator performance statistics. */ mem5.nAlloc++; mem5.totalAlloc += iFullSz; mem5.totalExcess += iFullSz - nByte; mem5.currentCount++; mem5.currentOut += iFullSz; if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount; if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut; #endif #ifdef SQLITE_DEBUG /* Make sure the allocated memory does not assume that it is set to zero ** or retains a value from a previous allocation */ memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz); #endif /* Return a pointer to the allocated memory. */ return (void*)&mem5.zPool[i*mem5.szAtom]; } /* ** Free an outstanding memory allocation. */ static void memsys5FreeUnsafe(void *pOld){ u32 size, iLogsize; int iBlock; /* Set iBlock to the index of the block pointed to by pOld in ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool. */ iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom); /* Check that the pointer pOld points to a valid, non-free block. */ assert( iBlock>=0 && iBlock<mem5.nBlock ); assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 ); assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 ); iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE; size = 1<<iLogsize; assert( iBlock+size-1<(u32)mem5.nBlock ); mem5.aCtrl[iBlock] |= CTRL_FREE; mem5.aCtrl[iBlock+size-1] |= CTRL_FREE; #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) assert( mem5.currentCount>0 ); assert( mem5.currentOut>=(size*mem5.szAtom) ); mem5.currentCount--; mem5.currentOut -= size*mem5.szAtom; assert( mem5.currentOut>0 || mem5.currentCount==0 ); assert( mem5.currentCount>0 || mem5.currentOut==0 ); #endif mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize; while( ALWAYS(iLogsize<LOGMAX) ){ int iBuddy; if( (iBlock>>iLogsize) & 1 ){ iBuddy = iBlock - size; assert( iBuddy>=0 ); }else{ iBuddy = iBlock + size; if( iBuddy>=mem5.nBlock ) break; } if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break; memsys5Unlink(iBuddy, iLogsize); iLogsize++; if( iBuddy<iBlock ){ mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize; mem5.aCtrl[iBlock] = 0; iBlock = iBuddy; }else{ mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize; mem5.aCtrl[iBuddy] = 0; } size *= 2; } #ifdef SQLITE_DEBUG /* Overwrite freed memory with the 0x55 bit pattern to verify that it is ** not used after being freed */ memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size); #endif memsys5Link(iBlock, iLogsize); } /* ** Allocate nBytes of memory. */ static void *memsys5Malloc(int nBytes){ sqlite3_int64 *p = 0; if( nBytes>0 ){ memsys5Enter(); p = memsys5MallocUnsafe(nBytes); memsys5Leave(); } return (void*)p; } /* ** Free memory. ** ** The outer layer memory allocator prevents this routine from ** being called with pPrior==0. */ static void memsys5Free(void *pPrior){ assert( pPrior!=0 ); memsys5Enter(); memsys5FreeUnsafe(pPrior); memsys5Leave(); } /* ** Change the size of an existing memory allocation. ** ** The outer layer memory allocator prevents this routine from ** being called with pPrior==0. ** ** nBytes is always a value obtained from a prior call to ** memsys5Round(). Hence nBytes is always a non-negative power ** of two. If nBytes==0 that means that an oversize allocation ** (an allocation larger than 0x40000000) was requested and this ** routine should return 0 without freeing pPrior. */ static void *memsys5Realloc(void *pPrior, int nBytes){ int nOld; void *p; assert( pPrior!=0 ); assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */ assert( nBytes>=0 ); if( nBytes==0 ){ return 0; } nOld = memsys5Size(pPrior); if( nBytes<=nOld ){ return pPrior; } p = memsys5Malloc(nBytes); if( p ){ memcpy(p, pPrior, nOld); memsys5Free(pPrior); } return p; } /* ** Round up a request size to the next valid allocation size. If ** the allocation is too large to be handled by this allocation system, ** return 0. ** ** All allocations must be a power of two and must be expressed by a ** 32-bit signed integer. Hence the largest allocation is 0x40000000 ** or 1073741824 bytes. */ static int memsys5Roundup(int n){ int iFullSz; if( n > 0x40000000 ) return 0; for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2); return iFullSz; } /* ** Return the ceiling of the logarithm base 2 of iValue. ** ** Examples: memsys5Log(1) -> 0 ** memsys5Log(2) -> 1 ** memsys5Log(4) -> 2 ** memsys5Log(5) -> 3 ** memsys5Log(8) -> 3 ** memsys5Log(9) -> 4 */ static int memsys5Log(int iValue){ int iLog; for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++); return iLog; } /* ** Initialize the memory allocator. ** ** This routine is not threadsafe. The caller must be holding a mutex ** to prevent multiple threads from entering at the same time. */ static int memsys5Init(void *NotUsed){ int ii; /* Loop counter */ int nByte; /* Number of bytes of memory available to this allocator */ u8 *zByte; /* Memory usable by this allocator */ int nMinLog; /* Log base 2 of minimum allocation size in bytes */ int iOffset; /* An offset into mem5.aCtrl[] */ UNUSED_PARAMETER(NotUsed); /* For the purposes of this routine, disable the mutex */ mem5.mutex = 0; /* The size of a Mem5Link object must be a power of two. Verify that ** this is case. */ assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 ); nByte = sqlite3GlobalConfig.nHeap; zByte = (u8*)sqlite3GlobalConfig.pHeap; assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */ /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */ nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq); mem5.szAtom = (1<<nMinLog); while( (int)sizeof(Mem5Link)>mem5.szAtom ){ mem5.szAtom = mem5.szAtom << 1; } mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8))); mem5.zPool = zByte; mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom]; for(ii=0; ii<=LOGMAX; ii++){ mem5.aiFreelist[ii] = -1; } iOffset = 0; for(ii=LOGMAX; ii>=0; ii--){ int nAlloc = (1<<ii); if( (iOffset+nAlloc)<=mem5.nBlock ){ mem5.aCtrl[iOffset] = ii | CTRL_FREE; memsys5Link(iOffset, ii); iOffset += nAlloc; } assert((iOffset+nAlloc)>mem5.nBlock); } /* If a mutex is required for normal operation, allocate one */ if( sqlite3GlobalConfig.bMemstat==0 ){ mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } return SQLITE_OK; } /* ** Deinitialize this module. */ static void memsys5Shutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); mem5.mutex = 0; return; } #ifdef SQLITE_TEST /* ** Open the file indicated and write a log of all unfreed memory ** allocations into that log. */ SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){ FILE *out; int i, j, n; int nMinLog; if( zFilename==0 || zFilename[0]==0 ){ out = stdout; }else{ out = fopen(zFilename, "w"); if( out==0 ){ fprintf(stderr, "** Unable to output memory debug output log: %s **\n", zFilename); return; } } memsys5Enter(); nMinLog = memsys5Log(mem5.szAtom); for(i=0; i<=LOGMAX && i+nMinLog<32; i++){ for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){} fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n); } fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc); fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc); fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess); fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut); fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount); fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut); fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount); fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest); memsys5Leave(); if( out==stdout ){ fflush(stdout); }else{ fclose(out); } } #endif /* ** This routine is the only routine in this file with external ** linkage. It returns a pointer to a static sqlite3_mem_methods ** struct populated with the memsys5 methods. */ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){ static const sqlite3_mem_methods memsys5Methods = { memsys5Malloc, memsys5Free, memsys5Realloc, memsys5Size, memsys5Roundup, memsys5Init, memsys5Shutdown, 0 }; return &memsys5Methods; } #endif /* SQLITE_ENABLE_MEMSYS5 */ /************** End of mem5.c ************************************************/ /************** Begin file mutex.c *******************************************/ /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes. ** ** This file contains code that is common across all mutex implementations. */ /* #include "sqliteInt.h" */ #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT) /* ** For debugging purposes, record when the mutex subsystem is initialized ** and uninitialized so that we can assert() if there is an attempt to ** allocate a mutex while the system is uninitialized. */ static SQLITE_WSD int mutexIsInit = 0; #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */ #ifndef SQLITE_MUTEX_OMIT /* ** Initialize the mutex system. */ SQLITE_PRIVATE int sqlite3MutexInit(void){ int rc = SQLITE_OK; if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){ /* If the xMutexAlloc method has not been set, then the user did not ** install a mutex implementation via sqlite3_config() prior to ** sqlite3_initialize() being called. This block copies pointers to ** the default implementation into the sqlite3GlobalConfig structure. */ sqlite3_mutex_methods const *pFrom; sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex; if( sqlite3GlobalConfig.bCoreMutex ){ pFrom = sqlite3DefaultMutex(); }else{ pFrom = sqlite3NoopMutex(); } pTo->xMutexInit = pFrom->xMutexInit; pTo->xMutexEnd = pFrom->xMutexEnd; pTo->xMutexFree = pFrom->xMutexFree; pTo->xMutexEnter = pFrom->xMutexEnter; pTo->xMutexTry = pFrom->xMutexTry; pTo->xMutexLeave = pFrom->xMutexLeave; pTo->xMutexHeld = pFrom->xMutexHeld; pTo->xMutexNotheld = pFrom->xMutexNotheld; sqlite3MemoryBarrier(); pTo->xMutexAlloc = pFrom->xMutexAlloc; } assert( sqlite3GlobalConfig.mutex.xMutexInit ); rc = sqlite3GlobalConfig.mutex.xMutexInit(); #ifdef SQLITE_DEBUG GLOBAL(int, mutexIsInit) = 1; #endif return rc; } /* ** Shutdown the mutex system. This call frees resources allocated by ** sqlite3MutexInit(). */ SQLITE_PRIVATE int sqlite3MutexEnd(void){ int rc = SQLITE_OK; if( sqlite3GlobalConfig.mutex.xMutexEnd ){ rc = sqlite3GlobalConfig.mutex.xMutexEnd(); } #ifdef SQLITE_DEBUG GLOBAL(int, mutexIsInit) = 0; #endif return rc; } /* ** Retrieve a pointer to a static mutex or allocate a new dynamic one. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){ #ifndef SQLITE_OMIT_AUTOINIT if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0; if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0; #endif assert( sqlite3GlobalConfig.mutex.xMutexAlloc ); return sqlite3GlobalConfig.mutex.xMutexAlloc(id); } SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){ if( !sqlite3GlobalConfig.bCoreMutex ){ return 0; } assert( GLOBAL(int, mutexIsInit) ); assert( sqlite3GlobalConfig.mutex.xMutexAlloc ); return sqlite3GlobalConfig.mutex.xMutexAlloc(id); } /* ** Free a dynamic mutex. */ SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){ if( p ){ assert( sqlite3GlobalConfig.mutex.xMutexFree ); sqlite3GlobalConfig.mutex.xMutexFree(p); } } /* ** Obtain the mutex p. If some other thread already has the mutex, block ** until it can be obtained. */ SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){ if( p ){ assert( sqlite3GlobalConfig.mutex.xMutexEnter ); sqlite3GlobalConfig.mutex.xMutexEnter(p); } } /* ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. */ SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){ int rc = SQLITE_OK; if( p ){ assert( sqlite3GlobalConfig.mutex.xMutexTry ); return sqlite3GlobalConfig.mutex.xMutexTry(p); } return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was previously ** entered by the same thread. The behavior is undefined if the mutex ** is not currently entered. If a NULL pointer is passed as an argument ** this function is a no-op. */ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){ if( p ){ assert( sqlite3GlobalConfig.mutex.xMutexLeave ); sqlite3GlobalConfig.mutex.xMutexLeave(p); } } #ifndef NDEBUG /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use inside assert() statements. */ SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){ assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld ); return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p); } SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){ assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld ); return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p); } #endif #endif /* !defined(SQLITE_MUTEX_OMIT) */ /************** End of mutex.c ***********************************************/ /************** Begin file mutex_noop.c **************************************/ /* ** 2008 October 07 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes. ** ** This implementation in this file does not provide any mutual ** exclusion and is thus suitable for use only in applications ** that use SQLite in a single thread. The routines defined ** here are place-holders. Applications can substitute working ** mutex routines at start-time using the ** ** sqlite3_config(SQLITE_CONFIG_MUTEX,...) ** ** interface. ** ** If compiled with SQLITE_DEBUG, then additional logic is inserted ** that does error checking on mutexes to make sure they are being ** called correctly. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_MUTEX_OMIT #ifndef SQLITE_DEBUG /* ** Stub routines for all mutex methods. ** ** This routines provide no mutual exclusion or error checking. */ static int noopMutexInit(void){ return SQLITE_OK; } static int noopMutexEnd(void){ return SQLITE_OK; } static sqlite3_mutex *noopMutexAlloc(int id){ UNUSED_PARAMETER(id); return (sqlite3_mutex*)8; } static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } static int noopMutexTry(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return SQLITE_OK; } static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ static const sqlite3_mutex_methods sMutex = { noopMutexInit, noopMutexEnd, noopMutexAlloc, noopMutexFree, noopMutexEnter, noopMutexTry, noopMutexLeave, 0, 0, }; return &sMutex; } #endif /* !SQLITE_DEBUG */ #ifdef SQLITE_DEBUG /* ** In this implementation, error checking is provided for testing ** and debugging purposes. The mutexes still do not provide any ** mutual exclusion. */ /* ** The mutex object */ typedef struct sqlite3_debug_mutex { int id; /* The mutex type */ int cnt; /* Number of entries without a matching leave */ } sqlite3_debug_mutex; /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use inside assert() statements. */ static int debugMutexHeld(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; return p==0 || p->cnt>0; } static int debugMutexNotheld(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; return p==0 || p->cnt==0; } /* ** Initialize and deinitialize the mutex subsystem. */ static int debugMutexInit(void){ return SQLITE_OK; } static int debugMutexEnd(void){ return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. */ static sqlite3_mutex *debugMutexAlloc(int id){ static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1]; sqlite3_debug_mutex *pNew = 0; switch( id ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { pNew = sqlite3Malloc(sizeof(*pNew)); if( pNew ){ pNew->id = id; pNew->cnt = 0; } break; } default: { #ifdef SQLITE_ENABLE_API_ARMOR if( id-2<0 || id-2>=ArraySize(aStatic) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif pNew = &aStatic[id-2]; pNew->id = id; break; } } return (sqlite3_mutex*)pNew; } /* ** This routine deallocates a previously allocated mutex. */ static void debugMutexFree(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; assert( p->cnt==0 ); if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){ sqlite3_free(p); }else{ #ifdef SQLITE_ENABLE_API_ARMOR (void)SQLITE_MISUSE_BKPT; #endif } } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void debugMutexEnter(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); p->cnt++; } static int debugMutexTry(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); p->cnt++; return SQLITE_OK; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void debugMutexLeave(sqlite3_mutex *pX){ sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; assert( debugMutexHeld(pX) ); p->cnt--; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); } SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ static const sqlite3_mutex_methods sMutex = { debugMutexInit, debugMutexEnd, debugMutexAlloc, debugMutexFree, debugMutexEnter, debugMutexTry, debugMutexLeave, debugMutexHeld, debugMutexNotheld }; return &sMutex; } #endif /* SQLITE_DEBUG */ /* ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation ** is used regardless of the run-time threadsafety setting. */ #ifdef SQLITE_MUTEX_NOOP SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ return sqlite3NoopMutex(); } #endif /* defined(SQLITE_MUTEX_NOOP) */ #endif /* !defined(SQLITE_MUTEX_OMIT) */ /************** End of mutex_noop.c ******************************************/ /************** Begin file mutex_unix.c **************************************/ /* ** 2007 August 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for pthreads */ /* #include "sqliteInt.h" */ /* ** The code in this file is only used if we are compiling threadsafe ** under unix with pthreads. ** ** Note that this implementation requires a version of pthreads that ** supports recursive mutexes. */ #ifdef SQLITE_MUTEX_PTHREADS #include <pthread.h> /* ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields ** are necessary under two condidtions: (1) Debug builds and (2) using ** home-grown mutexes. Encapsulate these conditions into a single #define. */ #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX) # define SQLITE_MUTEX_NREF 1 #else # define SQLITE_MUTEX_NREF 0 #endif /* ** Each recursive mutex is an instance of the following structure. */ struct sqlite3_mutex { pthread_mutex_t mutex; /* Mutex controlling the lock */ #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) int id; /* Mutex type */ #endif #if SQLITE_MUTEX_NREF volatile int nRef; /* Number of entrances */ volatile pthread_t owner; /* Thread that is within this mutex */ int trace; /* True to trace changes */ #endif }; #if SQLITE_MUTEX_NREF #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0} #elif defined(SQLITE_ENABLE_API_ARMOR) #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 } #else #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER } #endif /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use only inside assert() statements. On some platforms, ** there might be race conditions that can cause these routines to ** deliver incorrect results. In particular, if pthread_equal() is ** not an atomic operation, then these routines might delivery ** incorrect results. On most platforms, pthread_equal() is a ** comparison of two integers and is therefore atomic. But we are ** told that HPUX is not such a platform. If so, then these routines ** will not always work correctly on HPUX. ** ** On those platforms where pthread_equal() is not atomic, SQLite ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to ** make sure no assert() statements are evaluated and hence these ** routines are never called. */ #if !defined(NDEBUG) || defined(SQLITE_DEBUG) static int pthreadMutexHeld(sqlite3_mutex *p){ return (p->nRef!=0 && pthread_equal(p->owner, pthread_self())); } static int pthreadMutexNotheld(sqlite3_mutex *p){ return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0; } #endif /* ** Try to provide a memory barrier operation, needed for initialization ** and also for the implementation of xShmBarrier in the VFS in cases ** where SQLite is compiled without mutexes. */ SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ #if defined(SQLITE_MEMORY_BARRIER) SQLITE_MEMORY_BARRIER; #elif defined(__GNUC__) && GCC_VERSION>=4001000 __sync_synchronize(); #endif } /* ** Initialize and deinitialize the mutex subsystem. */ static int pthreadMutexInit(void){ return SQLITE_OK; } static int pthreadMutexEnd(void){ return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. SQLite ** will unwind its stack and return an error. The argument ** to sqlite3_mutex_alloc() is one of these integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST ** <li> SQLITE_MUTEX_RECURSIVE ** <li> SQLITE_MUTEX_STATIC_MASTER ** <li> SQLITE_MUTEX_STATIC_MEM ** <li> SQLITE_MUTEX_STATIC_OPEN ** <li> SQLITE_MUTEX_STATIC_PRNG ** <li> SQLITE_MUTEX_STATIC_LRU ** <li> SQLITE_MUTEX_STATIC_PMEM ** <li> SQLITE_MUTEX_STATIC_APP1 ** <li> SQLITE_MUTEX_STATIC_APP2 ** <li> SQLITE_MUTEX_STATIC_APP3 ** <li> SQLITE_MUTEX_STATIC_VFS1 ** <li> SQLITE_MUTEX_STATIC_VFS2 ** <li> SQLITE_MUTEX_STATIC_VFS3 ** </ul> ** ** The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. But SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ static sqlite3_mutex *pthreadMutexAlloc(int iType){ static sqlite3_mutex staticMutexes[] = { SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER }; sqlite3_mutex *p; switch( iType ){ case SQLITE_MUTEX_RECURSIVE: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX /* If recursive mutexes are not available, we will have to ** build our own. See below. */ pthread_mutex_init(&p->mutex, 0); #else /* Use a recursive mutex if it is available */ pthread_mutexattr_t recursiveAttr; pthread_mutexattr_init(&recursiveAttr); pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&p->mutex, &recursiveAttr); pthread_mutexattr_destroy(&recursiveAttr); #endif } break; } case SQLITE_MUTEX_FAST: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ pthread_mutex_init(&p->mutex, 0); } break; } default: { #ifdef SQLITE_ENABLE_API_ARMOR if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif p = &staticMutexes[iType-2]; break; } } #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) if( p ) p->id = iType; #endif return p; } /* ** This routine deallocates a previously ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ static void pthreadMutexFree(sqlite3_mutex *p){ assert( p->nRef==0 ); #if SQLITE_ENABLE_API_ARMOR if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ) #endif { pthread_mutex_destroy(&p->mutex); sqlite3_free(p); } #ifdef SQLITE_ENABLE_API_ARMOR else{ (void)SQLITE_MISUSE_BKPT; } #endif } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void pthreadMutexEnter(sqlite3_mutex *p){ assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX /* If recursive mutexes are not available, then we have to grow ** our own. This implementation assumes that pthread_equal() ** is atomic - that it cannot be deceived into thinking self ** and p->owner are equal if p->owner changes between two values ** that are not equal to self while the comparison is taking place. ** This implementation also assumes a coherent cache - that ** separate processes cannot read different values from the same ** address at the same time. If either of these two conditions ** are not met, then the mutexes will fail and problems will result. */ { pthread_t self = pthread_self(); if( p->nRef>0 && pthread_equal(p->owner, self) ){ p->nRef++; }else{ pthread_mutex_lock(&p->mutex); assert( p->nRef==0 ); p->owner = self; p->nRef = 1; } } #else /* Use the built-in recursive mutexes if they are available. */ pthread_mutex_lock(&p->mutex); #if SQLITE_MUTEX_NREF assert( p->nRef>0 || p->owner==0 ); p->owner = pthread_self(); p->nRef++; #endif #endif #ifdef SQLITE_DEBUG if( p->trace ){ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif } static int pthreadMutexTry(sqlite3_mutex *p){ int rc; assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX /* If recursive mutexes are not available, then we have to grow ** our own. This implementation assumes that pthread_equal() ** is atomic - that it cannot be deceived into thinking self ** and p->owner are equal if p->owner changes between two values ** that are not equal to self while the comparison is taking place. ** This implementation also assumes a coherent cache - that ** separate processes cannot read different values from the same ** address at the same time. If either of these two conditions ** are not met, then the mutexes will fail and problems will result. */ { pthread_t self = pthread_self(); if( p->nRef>0 && pthread_equal(p->owner, self) ){ p->nRef++; rc = SQLITE_OK; }else if( pthread_mutex_trylock(&p->mutex)==0 ){ assert( p->nRef==0 ); p->owner = self; p->nRef = 1; rc = SQLITE_OK; }else{ rc = SQLITE_BUSY; } } #else /* Use the built-in recursive mutexes if they are available. */ if( pthread_mutex_trylock(&p->mutex)==0 ){ #if SQLITE_MUTEX_NREF p->owner = pthread_self(); p->nRef++; #endif rc = SQLITE_OK; }else{ rc = SQLITE_BUSY; } #endif #ifdef SQLITE_DEBUG if( rc==SQLITE_OK && p->trace ){ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void pthreadMutexLeave(sqlite3_mutex *p){ assert( pthreadMutexHeld(p) ); #if SQLITE_MUTEX_NREF p->nRef--; if( p->nRef==0 ) p->owner = 0; #endif assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX if( p->nRef==0 ){ pthread_mutex_unlock(&p->mutex); } #else pthread_mutex_unlock(&p->mutex); #endif #ifdef SQLITE_DEBUG if( p->trace ){ printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif } SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ static const sqlite3_mutex_methods sMutex = { pthreadMutexInit, pthreadMutexEnd, pthreadMutexAlloc, pthreadMutexFree, pthreadMutexEnter, pthreadMutexTry, pthreadMutexLeave, #ifdef SQLITE_DEBUG pthreadMutexHeld, pthreadMutexNotheld #else 0, 0 #endif }; return &sMutex; } #endif /* SQLITE_MUTEX_PTHREADS */ /************** End of mutex_unix.c ******************************************/ /************** Begin file mutex_w32.c ***************************************/ /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for Win32. */ /* #include "sqliteInt.h" */ #if SQLITE_OS_WIN /* ** Include code that is common to all os_*.c files */ /************** Include os_common.h in the middle of mutex_w32.c *************/ /************** Begin file os_common.h ***************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. */ #ifndef _OS_COMMON_H_ #define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #ifdef MEMORY_DEBUG # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #ifdef SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ /************** Include hwtime.h in the middle of os_common.h ****************/ /************** Begin file hwtime.h ******************************************/ /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if (defined(__GNUC__) || defined(_MSC_VER)) && \ (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; } #elif defined(_MSC_VER) __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else #error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif #endif /* !defined(SQLITE_HWTIME_H) */ /************** End of hwtime.h **********************************************/ /************** Continuing where we left off in os_common.h ******************/ static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; #define TIMER_START g_start=sqlite3Hwtime() #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START #define TIMER_END #define TIMER_ELAPSED ((sqlite_uint64)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_io_error_hit; SQLITE_API extern int sqlite3_io_error_hardhit; SQLITE_API extern int sqlite3_io_error_pending; SQLITE_API extern int sqlite3_io_error_persist; SQLITE_API extern int sqlite3_io_error_benign; SQLITE_API extern int sqlite3_diskfull_pending; SQLITE_API extern int sqlite3_diskfull; #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ || sqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); sqlite3_io_error_hit++; if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ if( sqlite3_diskfull_pending ){ \ if( sqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ sqlite3_diskfull = 1; \ sqlite3_io_error_hit = 1; \ CODE; \ }else{ \ sqlite3_diskfull_pending--; \ } \ } #else #define SimulateIOErrorBenign(X) #define SimulateIOError(A) #define SimulateDiskfullError(A) #endif /* defined(SQLITE_TEST) */ /* ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_open_file_count; #define OpenCounter(X) sqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ #endif /* !defined(_OS_COMMON_H_) */ /************** End of os_common.h *******************************************/ /************** Continuing where we left off in mutex_w32.c ******************/ /* ** Include the header file for the Windows VFS. */ /************** Include os_win.h in the middle of mutex_w32.c ****************/ /************** Begin file os_win.h ******************************************/ /* ** 2013 November 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to Windows. */ #ifndef SQLITE_OS_WIN_H #define SQLITE_OS_WIN_H /* ** Include the primary Windows SDK header file. */ #include "windows.h" #ifdef __CYGWIN__ # include <sys/cygwin.h> # include <errno.h> /* amalgamator: dontcache */ #endif /* ** Determine if we are dealing with Windows NT. ** ** We ought to be able to determine if we are compiling for Windows 9x or ** Windows NT using the _WIN32_WINNT macro as follows: ** ** #if defined(_WIN32_WINNT) ** # define SQLITE_OS_WINNT 1 ** #else ** # define SQLITE_OS_WINNT 0 ** #endif ** ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as ** it ought to, so the above test does not work. We'll just assume that ** everything is Windows NT unless the programmer explicitly says otherwise ** by setting SQLITE_OS_WINNT to 0. */ #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT) # define SQLITE_OS_WINNT 1 #endif /* ** Determine if we are dealing with Windows CE - which has a much reduced ** API. */ #if defined(_WIN32_WCE) # define SQLITE_OS_WINCE 1 #else # define SQLITE_OS_WINCE 0 #endif /* ** Determine if we are dealing with WinRT, which provides only a subset of ** the full Win32 API. */ #if !defined(SQLITE_OS_WINRT) # define SQLITE_OS_WINRT 0 #endif /* ** For WinCE, some API function parameters do not appear to be declared as ** volatile. */ #if SQLITE_OS_WINCE # define SQLITE_WIN32_VOLATILE #else # define SQLITE_WIN32_VOLATILE volatile #endif /* ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex() ** functions are not available (e.g. those not using MSVC, Cygwin, etc). */ #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ SQLITE_THREADSAFE>0 && !defined(__CYGWIN__) # define SQLITE_OS_WIN_THREADS 1 #else # define SQLITE_OS_WIN_THREADS 0 #endif #endif /* SQLITE_OS_WIN_H */ /************** End of os_win.h **********************************************/ /************** Continuing where we left off in mutex_w32.c ******************/ #endif /* ** The code in this file is only used if we are compiling multithreaded ** on a Win32 system. */ #ifdef SQLITE_MUTEX_W32 /* ** Each recursive mutex is an instance of the following structure. */ struct sqlite3_mutex { CRITICAL_SECTION mutex; /* Mutex controlling the lock */ int id; /* Mutex type */ #ifdef SQLITE_DEBUG volatile int nRef; /* Number of enterances */ volatile DWORD owner; /* Thread holding this mutex */ volatile int trace; /* True to trace changes */ #endif }; /* ** These are the initializer values used when declaring a "static" mutex ** on Win32. It should be noted that all mutexes require initialization ** on the Win32 platform. */ #define SQLITE_W32_MUTEX_INITIALIZER { 0 } #ifdef SQLITE_DEBUG #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \ 0L, (DWORD)0, 0 } #else #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 } #endif #ifdef SQLITE_DEBUG /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use only inside assert() statements. */ static int winMutexHeld(sqlite3_mutex *p){ return p->nRef!=0 && p->owner==GetCurrentThreadId(); } static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){ return p->nRef==0 || p->owner!=tid; } static int winMutexNotheld(sqlite3_mutex *p){ DWORD tid = GetCurrentThreadId(); return winMutexNotheld2(p, tid); } #endif /* ** Try to provide a memory barrier operation, needed for initialization ** and also for the xShmBarrier method of the VFS in cases when SQLite is ** compiled without mutexes (SQLITE_THREADSAFE=0). */ SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ #if defined(SQLITE_MEMORY_BARRIER) SQLITE_MEMORY_BARRIER; #elif defined(__GNUC__) __sync_synchronize(); #elif MSVC_VERSION>=1300 _ReadWriteBarrier(); #elif defined(MemoryBarrier) MemoryBarrier(); #endif } /* ** Initialize and deinitialize the mutex subsystem. */ static sqlite3_mutex winMutex_staticMutexes[] = { SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER, SQLITE3_MUTEX_INITIALIZER }; static int winMutex_isInit = 0; static int winMutex_isNt = -1; /* <0 means "need to query" */ /* As the winMutexInit() and winMutexEnd() functions are called as part ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the ** "interlocked" magic used here is probably not strictly necessary. */ static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0; SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */ SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */ static int winMutexInit(void){ /* The first to increment to 1 does actual initialization */ if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){ int i; for(i=0; i<ArraySize(winMutex_staticMutexes); i++){ #if SQLITE_OS_WINRT InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0); #else InitializeCriticalSection(&winMutex_staticMutexes[i].mutex); #endif } winMutex_isInit = 1; }else{ /* Another thread is (in the process of) initializing the static ** mutexes */ while( !winMutex_isInit ){ sqlite3_win32_sleep(1); } } return SQLITE_OK; } static int winMutexEnd(void){ /* The first to decrement to 0 does actual shutdown ** (which should be the last to shutdown.) */ if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){ if( winMutex_isInit==1 ){ int i; for(i=0; i<ArraySize(winMutex_staticMutexes); i++){ DeleteCriticalSection(&winMutex_staticMutexes[i].mutex); } winMutex_isInit = 0; } } return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. SQLite ** will unwind its stack and return an error. The argument ** to sqlite3_mutex_alloc() is one of these integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST ** <li> SQLITE_MUTEX_RECURSIVE ** <li> SQLITE_MUTEX_STATIC_MASTER ** <li> SQLITE_MUTEX_STATIC_MEM ** <li> SQLITE_MUTEX_STATIC_OPEN ** <li> SQLITE_MUTEX_STATIC_PRNG ** <li> SQLITE_MUTEX_STATIC_LRU ** <li> SQLITE_MUTEX_STATIC_PMEM ** <li> SQLITE_MUTEX_STATIC_APP1 ** <li> SQLITE_MUTEX_STATIC_APP2 ** <li> SQLITE_MUTEX_STATIC_APP3 ** <li> SQLITE_MUTEX_STATIC_VFS1 ** <li> SQLITE_MUTEX_STATIC_VFS2 ** <li> SQLITE_MUTEX_STATIC_VFS3 ** </ul> ** ** The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. But SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ static sqlite3_mutex *winMutexAlloc(int iType){ sqlite3_mutex *p; switch( iType ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ p->id = iType; #ifdef SQLITE_DEBUG #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC p->trace = 1; #endif #endif #if SQLITE_OS_WINRT InitializeCriticalSectionEx(&p->mutex, 0, 0); #else InitializeCriticalSection(&p->mutex); #endif } break; } default: { #ifdef SQLITE_ENABLE_API_ARMOR if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif p = &winMutex_staticMutexes[iType-2]; p->id = iType; #ifdef SQLITE_DEBUG #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC p->trace = 1; #endif #endif break; } } return p; } /* ** This routine deallocates a previously ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ static void winMutexFree(sqlite3_mutex *p){ assert( p ); assert( p->nRef==0 && p->owner==0 ); if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){ DeleteCriticalSection(&p->mutex); sqlite3_free(p); }else{ #ifdef SQLITE_ENABLE_API_ARMOR (void)SQLITE_MISUSE_BKPT; #endif } } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void winMutexEnter(sqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif #ifdef SQLITE_DEBUG assert( p ); assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); #else assert( p ); #endif assert( winMutex_isInit==1 ); EnterCriticalSection(&p->mutex); #ifdef SQLITE_DEBUG assert( p->nRef>0 || p->owner==0 ); p->owner = tid; p->nRef++; if( p->trace ){ OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n", tid, p, p->trace, p->nRef)); } #endif } static int winMutexTry(sqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif int rc = SQLITE_BUSY; assert( p ); assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); /* ** The sqlite3_mutex_try() routine is very rarely used, and when it ** is used it is merely an optimization. So it is OK for it to always ** fail. ** ** The TryEnterCriticalSection() interface is only available on WinNT. ** And some windows compilers complain if you try to use it without ** first doing some #defines that prevent SQLite from building on Win98. ** For that reason, we will omit this optimization for now. See ** ticket #2685. */ #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400 assert( winMutex_isInit==1 ); assert( winMutex_isNt>=-1 && winMutex_isNt<=1 ); if( winMutex_isNt<0 ){ winMutex_isNt = sqlite3_win32_is_nt(); } assert( winMutex_isNt==0 || winMutex_isNt==1 ); if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){ #ifdef SQLITE_DEBUG p->owner = tid; p->nRef++; #endif rc = SQLITE_OK; } #else UNUSED_PARAMETER(p); #endif #ifdef SQLITE_DEBUG if( p->trace ){ OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n", tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc))); } #endif return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void winMutexLeave(sqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif assert( p ); #ifdef SQLITE_DEBUG assert( p->nRef>0 ); assert( p->owner==tid ); p->nRef--; if( p->nRef==0 ) p->owner = 0; assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); #endif assert( winMutex_isInit==1 ); LeaveCriticalSection(&p->mutex); #ifdef SQLITE_DEBUG if( p->trace ){ OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n", tid, p, p->trace, p->nRef)); } #endif } SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ static const sqlite3_mutex_methods sMutex = { winMutexInit, winMutexEnd, winMutexAlloc, winMutexFree, winMutexEnter, winMutexTry, winMutexLeave, #ifdef SQLITE_DEBUG winMutexHeld, winMutexNotheld #else 0, 0 #endif }; return &sMutex; } #endif /* SQLITE_MUTEX_W32 */ /************** End of mutex_w32.c *******************************************/ /************** Begin file malloc.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** Memory allocation functions used throughout sqlite. */ /* #include "sqliteInt.h" */ /* #include <stdarg.h> */ /* ** Attempt to release up to n bytes of non-essential memory currently ** held by SQLite. An example of non-essential memory is memory used to ** cache database pages that are not currently in use. */ SQLITE_API int sqlite3_release_memory(int n){ #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT return sqlite3PcacheReleaseMemory(n); #else /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine ** is a no-op returning zero if SQLite is not compiled with ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */ UNUSED_PARAMETER(n); return 0; #endif } /* ** An instance of the following object records the location of ** each unused scratch buffer. */ typedef struct ScratchFreeslot { struct ScratchFreeslot *pNext; /* Next unused scratch buffer */ } ScratchFreeslot; /* ** State information local to the memory allocation subsystem. */ static SQLITE_WSD struct Mem0Global { sqlite3_mutex *mutex; /* Mutex to serialize access */ sqlite3_int64 alarmThreshold; /* The soft heap limit */ /* ** Pointers to the end of sqlite3GlobalConfig.pScratch memory ** (so that a range test can be used to determine if an allocation ** being freed came from pScratch) and a pointer to the list of ** unused scratch allocations. */ void *pScratchEnd; ScratchFreeslot *pScratchFree; u32 nScratchFree; /* ** True if heap is nearly "full" where "full" is defined by the ** sqlite3_soft_heap_limit() setting. */ int nearlyFull; } mem0 = { 0, 0, 0, 0, 0, 0 }; #define mem0 GLOBAL(struct Mem0Global, mem0) /* ** Return the memory allocator mutex. sqlite3_status() needs it. */ SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){ return mem0.mutex; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Deprecated external interface. It used to set an alarm callback ** that was invoked when memory usage grew too large. Now it is a ** no-op. */ SQLITE_API int sqlite3_memory_alarm( void(*xCallback)(void *pArg, sqlite3_int64 used,int N), void *pArg, sqlite3_int64 iThreshold ){ (void)xCallback; (void)pArg; (void)iThreshold; return SQLITE_OK; } #endif /* ** Set the soft heap-size limit for the library. Passing a zero or ** negative value indicates no limit. */ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){ sqlite3_int64 priorLimit; sqlite3_int64 excess; sqlite3_int64 nUsed; #ifndef SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if( rc ) return -1; #endif sqlite3_mutex_enter(mem0.mutex); priorLimit = mem0.alarmThreshold; if( n<0 ){ sqlite3_mutex_leave(mem0.mutex); return priorLimit; } mem0.alarmThreshold = n; nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); mem0.nearlyFull = (n>0 && n<=nUsed); sqlite3_mutex_leave(mem0.mutex); excess = sqlite3_memory_used() - n; if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff)); return priorLimit; } SQLITE_API void sqlite3_soft_heap_limit(int n){ if( n<0 ) n = 0; sqlite3_soft_heap_limit64(n); } /* ** Initialize the memory allocation subsystem. */ SQLITE_PRIVATE int sqlite3MallocInit(void){ int rc; if( sqlite3GlobalConfig.m.xMalloc==0 ){ sqlite3MemSetDefault(); } memset(&mem0, 0, sizeof(mem0)); mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100 && sqlite3GlobalConfig.nScratch>0 ){ int i, n, sz; ScratchFreeslot *pSlot; sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch); sqlite3GlobalConfig.szScratch = sz; pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch; n = sqlite3GlobalConfig.nScratch; mem0.pScratchFree = pSlot; mem0.nScratchFree = n; for(i=0; i<n-1; i++){ pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot); pSlot = pSlot->pNext; } pSlot->pNext = 0; mem0.pScratchEnd = (void*)&pSlot[1]; }else{ mem0.pScratchEnd = 0; sqlite3GlobalConfig.pScratch = 0; sqlite3GlobalConfig.szScratch = 0; sqlite3GlobalConfig.nScratch = 0; } if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512 || sqlite3GlobalConfig.nPage<=0 ){ sqlite3GlobalConfig.pPage = 0; sqlite3GlobalConfig.szPage = 0; } rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData); if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0)); return rc; } /* ** Return true if the heap is currently under memory pressure - in other ** words if the amount of heap used is close to the limit set by ** sqlite3_soft_heap_limit(). */ SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){ return mem0.nearlyFull; } /* ** Deinitialize the memory allocation subsystem. */ SQLITE_PRIVATE void sqlite3MallocEnd(void){ if( sqlite3GlobalConfig.m.xShutdown ){ sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData); } memset(&mem0, 0, sizeof(mem0)); } /* ** Return the amount of memory currently checked out. */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void){ sqlite3_int64 res, mx; sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0); return res; } /* ** Return the maximum amount of memory that has ever been ** checked out since either the beginning of this process ** or since the most recent reset. */ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){ sqlite3_int64 res, mx; sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag); return mx; } /* ** Trigger the alarm */ static void sqlite3MallocAlarm(int nByte){ if( mem0.alarmThreshold<=0 ) return; sqlite3_mutex_leave(mem0.mutex); sqlite3_release_memory(nByte); sqlite3_mutex_enter(mem0.mutex); } /* ** Do a memory allocation with statistics and alarms. Assume the ** lock is already held. */ static void mallocWithAlarm(int n, void **pp){ void *p; int nFull; assert( sqlite3_mutex_held(mem0.mutex) ); assert( n>0 ); /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal ** implementation of malloc_good_size(), which must be called in debug ** mode and specifically when the DMD "Dark Matter Detector" is enabled ** or else a crash results. Hence, do not attempt to optimize out the ** following xRoundup() call. */ nFull = sqlite3GlobalConfig.m.xRoundup(n); sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n); if( mem0.alarmThreshold>0 ){ sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); if( nUsed >= mem0.alarmThreshold - nFull ){ mem0.nearlyFull = 1; sqlite3MallocAlarm(nFull); }else{ mem0.nearlyFull = 0; } } p = sqlite3GlobalConfig.m.xMalloc(nFull); #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT if( p==0 && mem0.alarmThreshold>0 ){ sqlite3MallocAlarm(nFull); p = sqlite3GlobalConfig.m.xMalloc(nFull); } #endif if( p ){ nFull = sqlite3MallocSize(p); sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull); sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1); } *pp = p; } /* ** Allocate memory. This routine is like sqlite3_malloc() except that it ** assumes the memory subsystem has already been initialized. */ SQLITE_PRIVATE void *sqlite3Malloc(u64 n){ void *p; if( n==0 || n>=0x7fffff00 ){ /* A memory allocation of a number of bytes which is near the maximum ** signed integer value might cause an integer overflow inside of the ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving ** 255 bytes of overhead. SQLite itself will never use anything near ** this amount. The only way to reach the limit is with sqlite3_malloc() */ p = 0; }else if( sqlite3GlobalConfig.bMemstat ){ sqlite3_mutex_enter(mem0.mutex); mallocWithAlarm((int)n, &p); sqlite3_mutex_leave(mem0.mutex); }else{ p = sqlite3GlobalConfig.m.xMalloc((int)n); } assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */ return p; } /* ** This version of the memory allocation is for use by the application. ** First make sure the memory subsystem is initialized, then do the ** allocation. */ SQLITE_API void *sqlite3_malloc(int n){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return n<=0 ? 0 : sqlite3Malloc(n); } SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return sqlite3Malloc(n); } /* ** Each thread may only have a single outstanding allocation from ** xScratchMalloc(). We verify this constraint in the single-threaded ** case by setting scratchAllocOut to 1 when an allocation ** is outstanding clearing it when the allocation is freed. */ #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) static int scratchAllocOut = 0; #endif /* ** Allocate memory that is to be used and released right away. ** This routine is similar to alloca() in that it is not intended ** for situations where the memory might be held long-term. This ** routine is intended to get memory to old large transient data ** structures that would not normally fit on the stack of an ** embedded processor. */ SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){ void *p; assert( n>0 ); sqlite3_mutex_enter(mem0.mutex); sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n); if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){ p = mem0.pScratchFree; mem0.pScratchFree = mem0.pScratchFree->pNext; mem0.nScratchFree--; sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1); sqlite3_mutex_leave(mem0.mutex); }else{ sqlite3_mutex_leave(mem0.mutex); p = sqlite3Malloc(n); if( sqlite3GlobalConfig.bMemstat && p ){ sqlite3_mutex_enter(mem0.mutex); sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p)); sqlite3_mutex_leave(mem0.mutex); } sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH); } assert( sqlite3_mutex_notheld(mem0.mutex) ); #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch ** buffers per thread. ** ** This can only be checked in single-threaded mode. */ assert( scratchAllocOut==0 ); if( p ) scratchAllocOut++; #endif return p; } SQLITE_PRIVATE void sqlite3ScratchFree(void *p){ if( p ){ #if SQLITE_THREADSAFE==0 && !defined(NDEBUG) /* Verify that no more than two scratch allocation per thread ** is outstanding at one time. (This is only checked in the ** single-threaded case since checking in the multi-threaded case ** would be much more complicated.) */ assert( scratchAllocOut>=1 && scratchAllocOut<=2 ); scratchAllocOut--; #endif if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){ /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */ ScratchFreeslot *pSlot; pSlot = (ScratchFreeslot*)p; sqlite3_mutex_enter(mem0.mutex); pSlot->pNext = mem0.pScratchFree; mem0.pScratchFree = pSlot; mem0.nScratchFree++; assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch ); sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1); sqlite3_mutex_leave(mem0.mutex); }else{ /* Release memory back to the heap */ assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) ); assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); if( sqlite3GlobalConfig.bMemstat ){ int iSize = sqlite3MallocSize(p); sqlite3_mutex_enter(mem0.mutex); sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize); sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize); sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); sqlite3GlobalConfig.m.xFree(p); sqlite3_mutex_leave(mem0.mutex); }else{ sqlite3GlobalConfig.m.xFree(p); } } } } /* ** TRUE if p is a lookaside memory allocation from db */ #ifndef SQLITE_OMIT_LOOKASIDE static int isLookaside(sqlite3 *db, void *p){ return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd); } #else #define isLookaside(A,B) 0 #endif /* ** Return the size of a memory allocation previously obtained from ** sqlite3Malloc() or sqlite3_malloc(). */ SQLITE_PRIVATE int sqlite3MallocSize(void *p){ assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); return sqlite3GlobalConfig.m.xSize(p); } SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){ assert( p!=0 ); if( db==0 || !isLookaside(db,p) ){ #if SQLITE_DEBUG if( db==0 ){ assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); }else{ assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); } #endif return sqlite3GlobalConfig.m.xSize(p); }else{ assert( sqlite3_mutex_held(db->mutex) ); return db->lookaside.sz; } } SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){ assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); return p ? sqlite3GlobalConfig.m.xSize(p) : 0; } /* ** Free memory previously obtained from sqlite3Malloc(). */ SQLITE_API void sqlite3_free(void *p){ if( p==0 ) return; /* IMP: R-49053-54554 */ assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); if( sqlite3GlobalConfig.bMemstat ){ sqlite3_mutex_enter(mem0.mutex); sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p)); sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); sqlite3GlobalConfig.m.xFree(p); sqlite3_mutex_leave(mem0.mutex); }else{ sqlite3GlobalConfig.m.xFree(p); } } /* ** Add the size of memory allocation "p" to the count in ** *db->pnBytesFreed. */ static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){ *db->pnBytesFreed += sqlite3DbMallocSize(db,p); } /* ** Free memory that might be associated with a particular database ** connection. */ SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){ assert( db==0 || sqlite3_mutex_held(db->mutex) ); if( p==0 ) return; if( db ){ if( db->pnBytesFreed ){ measureAllocationSize(db, p); return; } if( isLookaside(db, p) ){ LookasideSlot *pBuf = (LookasideSlot*)p; #if SQLITE_DEBUG /* Trash all content in the buffer being freed */ memset(p, 0xaa, db->lookaside.sz); #endif pBuf->pNext = db->lookaside.pFree; db->lookaside.pFree = pBuf; db->lookaside.nOut--; return; } } assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); sqlite3_free(p); } /* ** Change the size of an existing memory allocation */ SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){ int nOld, nNew, nDiff; void *pNew; assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) ); if( pOld==0 ){ return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ } if( nBytes==0 ){ sqlite3_free(pOld); /* IMP: R-26507-47431 */ return 0; } if( nBytes>=0x7fffff00 ){ /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ return 0; } nOld = sqlite3MallocSize(pOld); /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second ** argument to xRealloc is always a value returned by a prior call to ** xRoundup. */ nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes); if( nOld==nNew ){ pNew = pOld; }else if( sqlite3GlobalConfig.bMemstat ){ sqlite3_mutex_enter(mem0.mutex); sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes); nDiff = nNew - nOld; if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= mem0.alarmThreshold-nDiff ){ sqlite3MallocAlarm(nDiff); } pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); if( pNew==0 && mem0.alarmThreshold>0 ){ sqlite3MallocAlarm((int)nBytes); pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); } if( pNew ){ nNew = sqlite3MallocSize(pNew); sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld); } sqlite3_mutex_leave(mem0.mutex); }else{ pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); } assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */ return pNew; } /* ** The public interface to sqlite3Realloc. Make sure that the memory ** subsystem is initialized prior to invoking sqliteRealloc. */ SQLITE_API void *sqlite3_realloc(void *pOld, int n){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif if( n<0 ) n = 0; /* IMP: R-26507-47431 */ return sqlite3Realloc(pOld, n); } SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return sqlite3Realloc(pOld, n); } /* ** Allocate and zero memory. */ SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){ void *p = sqlite3Malloc(n); if( p ){ memset(p, 0, (size_t)n); } return p; } /* ** Allocate and zero memory. If the allocation fails, make ** the mallocFailed flag in the connection pointer. */ SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){ void *p; testcase( db==0 ); p = sqlite3DbMallocRaw(db, n); if( p ) memset(p, 0, (size_t)n); return p; } /* Finish the work of sqlite3DbMallocRawNN for the unusual and ** slower case when the allocation cannot be fulfilled using lookaside. */ static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){ void *p; assert( db!=0 ); p = sqlite3Malloc(n); if( !p ) sqlite3OomFault(db); sqlite3MemdebugSetType(p, (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP); return p; } /* ** Allocate memory, either lookaside (if possible) or heap. ** If the allocation fails, set the mallocFailed flag in ** the connection pointer. ** ** If db!=0 and db->mallocFailed is true (indicating a prior malloc ** failure on the same database connection) then always return 0. ** Hence for a particular database connection, once malloc starts ** failing, it fails consistently until mallocFailed is reset. ** This is an important assumption. There are many places in the ** code that do things like this: ** ** int *a = (int*)sqlite3DbMallocRaw(db, 100); ** int *b = (int*)sqlite3DbMallocRaw(db, 200); ** if( b ) a[10] = 9; ** ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed ** that all prior mallocs (ex: "a") worked too. ** ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is ** not a NULL pointer. */ SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){ void *p; if( db ) return sqlite3DbMallocRawNN(db, n); p = sqlite3Malloc(n); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); return p; } SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){ #ifndef SQLITE_OMIT_LOOKASIDE LookasideSlot *pBuf; assert( db!=0 ); assert( sqlite3_mutex_held(db->mutex) ); assert( db->pnBytesFreed==0 ); if( db->lookaside.bDisable==0 ){ assert( db->mallocFailed==0 ); if( n>db->lookaside.sz ){ db->lookaside.anStat[1]++; }else if( (pBuf = db->lookaside.pFree)==0 ){ db->lookaside.anStat[2]++; }else{ db->lookaside.pFree = pBuf->pNext; db->lookaside.nOut++; db->lookaside.anStat[0]++; if( db->lookaside.nOut>db->lookaside.mxOut ){ db->lookaside.mxOut = db->lookaside.nOut; } return (void*)pBuf; } }else if( db->mallocFailed ){ return 0; } #else assert( db!=0 ); assert( sqlite3_mutex_held(db->mutex) ); assert( db->pnBytesFreed==0 ); if( db->mallocFailed ){ return 0; } #endif return dbMallocRawFinish(db, n); } /* Forward declaration */ static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n); /* ** Resize the block of memory pointed to by p to n bytes. If the ** resize fails, set the mallocFailed flag in the connection object. */ SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){ assert( db!=0 ); if( p==0 ) return sqlite3DbMallocRawNN(db, n); assert( sqlite3_mutex_held(db->mutex) ); if( isLookaside(db,p) && n<=db->lookaside.sz ) return p; return dbReallocFinish(db, p, n); } static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){ void *pNew = 0; assert( db!=0 ); assert( p!=0 ); if( db->mallocFailed==0 ){ if( isLookaside(db, p) ){ pNew = sqlite3DbMallocRawNN(db, n); if( pNew ){ memcpy(pNew, p, db->lookaside.sz); sqlite3DbFree(db, p); } }else{ assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); pNew = sqlite3_realloc64(p, n); if( !pNew ){ sqlite3OomFault(db); } sqlite3MemdebugSetType(pNew, (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); } } return pNew; } /* ** Attempt to reallocate p. If the reallocation fails, then free p ** and set the mallocFailed flag in the database connection. */ SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){ void *pNew; pNew = sqlite3DbRealloc(db, p, n); if( !pNew ){ sqlite3DbFree(db, p); } return pNew; } /* ** Make a copy of a string in memory obtained from sqliteMalloc(). These ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This ** is because when memory debugging is turned on, these two functions are ** called via macros that record the current file and line number in the ** ThreadData structure. */ SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){ char *zNew; size_t n; if( z==0 ){ return 0; } n = strlen(z) + 1; zNew = sqlite3DbMallocRaw(db, n); if( zNew ){ memcpy(zNew, z, n); } return zNew; } SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ char *zNew; assert( db!=0 ); if( z==0 ){ return 0; } assert( (n&0x7fffffff)==n ); zNew = sqlite3DbMallocRawNN(db, n+1); if( zNew ){ memcpy(zNew, z, (size_t)n); zNew[n] = 0; } return zNew; } /* ** Free any prior content in *pz and replace it with a copy of zNew. */ SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){ sqlite3DbFree(db, *pz); *pz = sqlite3DbStrDup(db, zNew); } /* ** Call this routine to record the fact that an OOM (out-of-memory) error ** has happened. This routine will set db->mallocFailed, and also ** temporarily disable the lookaside memory allocator and interrupt ** any running VDBEs. */ SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){ if( db->mallocFailed==0 && db->bBenignMalloc==0 ){ db->mallocFailed = 1; if( db->nVdbeExec>0 ){ db->u1.isInterrupted = 1; } db->lookaside.bDisable++; } } /* ** This routine reactivates the memory allocator and clears the ** db->mallocFailed flag as necessary. ** ** The memory allocator is not restarted if there are running ** VDBEs. */ SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){ if( db->mallocFailed && db->nVdbeExec==0 ){ db->mallocFailed = 0; db->u1.isInterrupted = 0; assert( db->lookaside.bDisable>0 ); db->lookaside.bDisable--; } } /* ** Take actions at the end of an API call to indicate an OOM error */ static SQLITE_NOINLINE int apiOomError(sqlite3 *db){ sqlite3OomClear(db); sqlite3Error(db, SQLITE_NOMEM); return SQLITE_NOMEM_BKPT; } /* ** This function must be called before exiting any API function (i.e. ** returning control to the user) that has called sqlite3_malloc or ** sqlite3_realloc. ** ** The returned value is normally a copy of the second argument to this ** function. However, if a malloc() failure has occurred since the previous ** invocation SQLITE_NOMEM is returned instead. ** ** If an OOM as occurred, then the connection error-code (the value ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM. */ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){ /* If the db handle must hold the connection handle mutex here. ** Otherwise the read (and possible write) of db->mallocFailed ** is unsafe, as is the call to sqlite3Error(). */ assert( db!=0 ); assert( sqlite3_mutex_held(db->mutex) ); if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){ return apiOomError(db); } return rc & db->errMask; } /************** End of malloc.c **********************************************/ /************** Begin file printf.c ******************************************/ /* ** The "printf" code that follows dates from the 1980's. It is in ** the public domain. ** ************************************************************************** ** ** This file contains code for a set of "printf"-like routines. These ** routines format strings much like the printf() from the standard C ** library, though the implementation here has enhancements to support ** SQLite. */ /* #include "sqliteInt.h" */ /* ** Conversion types fall into various categories as defined by the ** following enumeration. */ #define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */ #define etFLOAT 1 /* Floating point. %f */ #define etEXP 2 /* Exponentional notation. %e and %E */ #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */ #define etSIZE 4 /* Return number of characters processed so far. %n */ #define etSTRING 5 /* Strings. %s */ #define etDYNSTRING 6 /* Dynamically allocated strings. %z */ #define etPERCENT 7 /* Percent symbol. %% */ #define etCHARX 8 /* Characters. %c */ /* The rest are extensions, not normally found in printf() */ #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */ #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '', NULL pointers replaced by SQL NULL. %Q */ #define etTOKEN 11 /* a pointer to a Token structure */ #define etSRCLIST 12 /* a pointer to a SrcList */ #define etPOINTER 13 /* The %p conversion */ #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */ #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ #define etINVALID 16 /* Any unrecognized conversion type */ /* ** An "etByte" is an 8-bit unsigned value. */ typedef unsigned char etByte; /* ** Each builtin conversion character (ex: the 'd' in "%d") is described ** by an instance of the following structure */ typedef struct et_info { /* Information about each format field */ char fmttype; /* The format field code letter */ etByte base; /* The base for radix conversion */ etByte flags; /* One or more of FLAG_ constants below */ etByte type; /* Conversion paradigm */ etByte charset; /* Offset into aDigits[] of the digits string */ etByte prefix; /* Offset into aPrefix[] of the prefix string */ } et_info; /* ** Allowed values for et_info.flags */ #define FLAG_SIGNED 1 /* True if the value to convert is signed */ #define FLAG_STRING 4 /* Allow infinity precision */ /* ** The following table is searched linearly, so it is good to put the ** most frequently used conversion types first. */ static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; static const char aPrefix[] = "-x0\000X0"; static const et_info fmtinfo[] = { { 'd', 10, 1, etRADIX, 0, 0 }, { 's', 0, 4, etSTRING, 0, 0 }, { 'g', 0, 1, etGENERIC, 30, 0 }, { 'z', 0, 4, etDYNSTRING, 0, 0 }, { 'q', 0, 4, etSQLESCAPE, 0, 0 }, { 'Q', 0, 4, etSQLESCAPE2, 0, 0 }, { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, { 'c', 0, 0, etCHARX, 0, 0 }, { 'o', 8, 0, etRADIX, 0, 2 }, { 'u', 10, 0, etRADIX, 0, 0 }, { 'x', 16, 0, etRADIX, 16, 1 }, { 'X', 16, 0, etRADIX, 0, 4 }, #ifndef SQLITE_OMIT_FLOATING_POINT { 'f', 0, 1, etFLOAT, 0, 0 }, { 'e', 0, 1, etEXP, 30, 0 }, { 'E', 0, 1, etEXP, 14, 0 }, { 'G', 0, 1, etGENERIC, 14, 0 }, #endif { 'i', 10, 1, etRADIX, 0, 0 }, { 'n', 0, 0, etSIZE, 0, 0 }, { '%', 0, 0, etPERCENT, 0, 0 }, { 'p', 16, 0, etPOINTER, 0, 1 }, /* All the rest are undocumented and are for internal use only */ { 'T', 0, 0, etTOKEN, 0, 0 }, { 'S', 0, 0, etSRCLIST, 0, 0 }, { 'r', 10, 1, etORDINAL, 0, 0 }, }; /* ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point ** conversions will work. */ #ifndef SQLITE_OMIT_FLOATING_POINT /* ** "*val" is a double such that 0.1 <= *val < 10.0 ** Return the ascii code for the leading digit of *val, then ** multiply "*val" by 10.0 to renormalize. ** ** Example: ** input: *val = 3.14159 ** output: *val = 1.4159 function return = '3' ** ** The counter *cnt is incremented each time. After counter exceeds ** 16 (the number of significant digits in a 64-bit float) '0' is ** always returned. */ static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){ int digit; LONGDOUBLE_TYPE d; if( (*cnt)<=0 ) return '0'; (*cnt)--; digit = (int)*val; d = digit; digit += '0'; *val = (*val - d)*10.0; return (char)digit; } #endif /* SQLITE_OMIT_FLOATING_POINT */ /* ** Set the StrAccum object to an error mode. */ static void setStrAccumError(StrAccum *p, u8 eError){ assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG ); p->accError = eError; p->nAlloc = 0; } /* ** Extra argument values from a PrintfArguments object */ static sqlite3_int64 getIntArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0; return sqlite3_value_int64(p->apArg[p->nUsed++]); } static double getDoubleArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0.0; return sqlite3_value_double(p->apArg[p->nUsed++]); } static char *getTextArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0; return (char*)sqlite3_value_text(p->apArg[p->nUsed++]); } /* ** On machines with a small stack size, you can redefine the ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired. */ #ifndef SQLITE_PRINT_BUF_SIZE # define SQLITE_PRINT_BUF_SIZE 70 #endif #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */ /* ** Render a string given by "fmt" into the StrAccum object. */ SQLITE_PRIVATE void sqlite3VXPrintf( StrAccum *pAccum, /* Accumulate results here */ const char *fmt, /* Format string */ va_list ap /* arguments */ ){ int c; /* Next character in the format string */ char *bufpt; /* Pointer to the conversion buffer */ int precision; /* Precision of the current field */ int length; /* Length of the field */ int idx; /* A general purpose loop counter */ int width; /* Width of the current field */ etByte flag_leftjustify; /* True if "-" flag is present */ etByte flag_plussign; /* True if "+" flag is present */ etByte flag_blanksign; /* True if " " flag is present */ etByte flag_alternateform; /* True if "#" flag is present */ etByte flag_altform2; /* True if "!" flag is present */ etByte flag_zeropad; /* True if field width constant starts with zero */ etByte flag_long; /* True if "l" flag is present */ etByte flag_longlong; /* True if the "ll" flag is present */ etByte done; /* Loop termination flag */ etByte xtype = etINVALID; /* Conversion paradigm */ u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */ char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ sqlite_uint64 longvalue; /* Value for integer types */ LONGDOUBLE_TYPE realvalue; /* Value for real types */ const et_info *infop; /* Pointer to the appropriate info structure */ char *zOut; /* Rendering buffer */ int nOut; /* Size of the rendering buffer */ char *zExtra = 0; /* Malloced memory used by some conversion */ #ifndef SQLITE_OMIT_FLOATING_POINT int exp, e2; /* exponent of real numbers */ int nsd; /* Number of significant digits returned */ double rounder; /* Used for rounding floating point values */ etByte flag_dp; /* True if decimal point should be shown */ etByte flag_rtz; /* True if trailing zeros should be removed */ #endif PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */ char buf[etBUFSIZE]; /* Conversion buffer */ bufpt = 0; if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){ pArgList = va_arg(ap, PrintfArguments*); bArgList = 1; }else{ bArgList = 0; } for(; (c=(*fmt))!=0; ++fmt){ if( c!='%' ){ bufpt = (char *)fmt; #if HAVE_STRCHRNUL fmt = strchrnul(fmt, '%'); #else do{ fmt++; }while( *fmt && *fmt != '%' ); #endif sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt)); if( *fmt==0 ) break; } if( (c=(*++fmt))==0 ){ sqlite3StrAccumAppend(pAccum, "%", 1); break; } /* Find out what flags are present */ flag_leftjustify = flag_plussign = flag_blanksign = flag_alternateform = flag_altform2 = flag_zeropad = 0; done = 0; do{ switch( c ){ case '-': flag_leftjustify = 1; break; case '+': flag_plussign = 1; break; case ' ': flag_blanksign = 1; break; case '#': flag_alternateform = 1; break; case '!': flag_altform2 = 1; break; case '0': flag_zeropad = 1; break; default: done = 1; break; } }while( !done && (c=(*++fmt))!=0 ); /* Get the field width */ if( c=='*' ){ if( bArgList ){ width = (int)getIntArg(pArgList); }else{ width = va_arg(ap,int); } if( width<0 ){ flag_leftjustify = 1; width = width >= -2147483647 ? -width : 0; } c = *++fmt; }else{ unsigned wx = 0; while( c>='0' && c<='9' ){ wx = wx*10 + c - '0'; c = *++fmt; } testcase( wx>0x7fffffff ); width = wx & 0x7fffffff; } assert( width>=0 ); #ifdef SQLITE_PRINTF_PRECISION_LIMIT if( width>SQLITE_PRINTF_PRECISION_LIMIT ){ width = SQLITE_PRINTF_PRECISION_LIMIT; } #endif /* Get the precision */ if( c=='.' ){ c = *++fmt; if( c=='*' ){ if( bArgList ){ precision = (int)getIntArg(pArgList); }else{ precision = va_arg(ap,int); } c = *++fmt; if( precision<0 ){ precision = precision >= -2147483647 ? -precision : -1; } }else{ unsigned px = 0; while( c>='0' && c<='9' ){ px = px*10 + c - '0'; c = *++fmt; } testcase( px>0x7fffffff ); precision = px & 0x7fffffff; } }else{ precision = -1; } assert( precision>=(-1) ); #ifdef SQLITE_PRINTF_PRECISION_LIMIT if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){ precision = SQLITE_PRINTF_PRECISION_LIMIT; } #endif /* Get the conversion type modifier */ if( c=='l' ){ flag_long = 1; c = *++fmt; if( c=='l' ){ flag_longlong = 1; c = *++fmt; }else{ flag_longlong = 0; } }else{ flag_long = flag_longlong = 0; } /* Fetch the info entry for the field */ infop = &fmtinfo[0]; xtype = etINVALID; for(idx=0; idx<ArraySize(fmtinfo); idx++){ if( c==fmtinfo[idx].fmttype ){ infop = &fmtinfo[idx]; xtype = infop->type; break; } } /* ** At this point, variables are initialized as follows: ** ** flag_alternateform TRUE if a '#' is present. ** flag_altform2 TRUE if a '!' is present. ** flag_plussign TRUE if a '+' is present. ** flag_leftjustify TRUE if a '-' is present or if the ** field width was negative. ** flag_zeropad TRUE if the width began with 0. ** flag_long TRUE if the letter 'l' (ell) prefixed ** the conversion character. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed ** the conversion character. ** flag_blanksign TRUE if a ' ' is present. ** width The specified field width. This is ** always non-negative. Zero is the default. ** precision The specified precision. The default ** is -1. ** xtype The class of the conversion. ** infop Pointer to the appropriate info struct. */ switch( xtype ){ case etPOINTER: flag_longlong = sizeof(char*)==sizeof(i64); flag_long = sizeof(char*)==sizeof(long int); /* Fall through into the next case */ case etORDINAL: case etRADIX: if( infop->flags & FLAG_SIGNED ){ i64 v; if( bArgList ){ v = getIntArg(pArgList); }else if( flag_longlong ){ v = va_arg(ap,i64); }else if( flag_long ){ v = va_arg(ap,long int); }else{ v = va_arg(ap,int); } if( v<0 ){ if( v==SMALLEST_INT64 ){ longvalue = ((u64)1)<<63; }else{ longvalue = -v; } prefix = '-'; }else{ longvalue = v; if( flag_plussign ) prefix = '+'; else if( flag_blanksign ) prefix = ' '; else prefix = 0; } }else{ if( bArgList ){ longvalue = (u64)getIntArg(pArgList); }else if( flag_longlong ){ longvalue = va_arg(ap,u64); }else if( flag_long ){ longvalue = va_arg(ap,unsigned long int); }else{ longvalue = va_arg(ap,unsigned int); } prefix = 0; } if( longvalue==0 ) flag_alternateform = 0; if( flag_zeropad && precision<width-(prefix!=0) ){ precision = width-(prefix!=0); } if( precision<etBUFSIZE-10 ){ nOut = etBUFSIZE; zOut = buf; }else{ nOut = precision + 10; zOut = zExtra = sqlite3Malloc( nOut ); if( zOut==0 ){ setStrAccumError(pAccum, STRACCUM_NOMEM); return; } } bufpt = &zOut[nOut-1]; if( xtype==etORDINAL ){ static const char zOrd[] = "thstndrd"; int x = (int)(longvalue % 10); if( x>=4 || (longvalue/10)%10==1 ){ x = 0; } *(--bufpt) = zOrd[x*2+1]; *(--bufpt) = zOrd[x*2]; } { const char *cset = &aDigits[infop->charset]; u8 base = infop->base; do{ /* Convert to ascii */ *(--bufpt) = cset[longvalue%base]; longvalue = longvalue/base; }while( longvalue>0 ); } length = (int)(&zOut[nOut-1]-bufpt); for(idx=precision-length; idx>0; idx--){ *(--bufpt) = '0'; /* Zero pad */ } if( prefix ) *(--bufpt) = prefix; /* Add sign */ if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ const char *pre; char x; pre = &aPrefix[infop->prefix]; for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; } length = (int)(&zOut[nOut-1]-bufpt); break; case etFLOAT: case etEXP: case etGENERIC: if( bArgList ){ realvalue = getDoubleArg(pArgList); }else{ realvalue = va_arg(ap,double); } #ifdef SQLITE_OMIT_FLOATING_POINT length = 0; #else if( precision<0 ) precision = 6; /* Set default precision */ if( realvalue<0.0 ){ realvalue = -realvalue; prefix = '-'; }else{ if( flag_plussign ) prefix = '+'; else if( flag_blanksign ) prefix = ' '; else prefix = 0; } if( xtype==etGENERIC && precision>0 ) precision--; testcase( precision>0xfff ); for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){} if( xtype==etFLOAT ) realvalue += rounder; /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ exp = 0; if( sqlite3IsNaN((double)realvalue) ){ bufpt = "NaN"; length = 3; break; } if( realvalue>0.0 ){ LONGDOUBLE_TYPE scale = 1.0; while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;} while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; } while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; } realvalue /= scale; while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; } while( realvalue<1.0 ){ realvalue *= 10.0; exp--; } if( exp>350 ){ bufpt = buf; buf[0] = prefix; memcpy(buf+(prefix!=0),"Inf",4); length = 3+(prefix!=0); break; } } bufpt = buf; /* ** If the field type is etGENERIC, then convert to either etEXP ** or etFLOAT, as appropriate. */ if( xtype!=etFLOAT ){ realvalue += rounder; if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; } } if( xtype==etGENERIC ){ flag_rtz = !flag_alternateform; if( exp<-4 || exp>precision ){ xtype = etEXP; }else{ precision = precision - exp; xtype = etFLOAT; } }else{ flag_rtz = flag_altform2; } if( xtype==etEXP ){ e2 = 0; }else{ e2 = exp; } if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){ bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 ); if( bufpt==0 ){ setStrAccumError(pAccum, STRACCUM_NOMEM); return; } } zOut = bufpt; nsd = 16 + flag_altform2*10; flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2; /* The sign in front of the number */ if( prefix ){ *(bufpt++) = prefix; } /* Digits prior to the decimal point */ if( e2<0 ){ *(bufpt++) = '0'; }else{ for(; e2>=0; e2--){ *(bufpt++) = et_getdigit(&realvalue,&nsd); } } /* The decimal point */ if( flag_dp ){ *(bufpt++) = '.'; } /* "0" digits after the decimal point but before the first ** significant digit of the number */ for(e2++; e2<0; precision--, e2++){ assert( precision>0 ); *(bufpt++) = '0'; } /* Significant digits after the decimal point */ while( (precision--)>0 ){ *(bufpt++) = et_getdigit(&realvalue,&nsd); } /* Remove trailing zeros and the "." if no digits follow the "." */ if( flag_rtz && flag_dp ){ while( bufpt[-1]=='0' ) *(--bufpt) = 0; assert( bufpt>zOut ); if( bufpt[-1]=='.' ){ if( flag_altform2 ){ *(bufpt++) = '0'; }else{ *(--bufpt) = 0; } } } /* Add the "eNNN" suffix */ if( xtype==etEXP ){ *(bufpt++) = aDigits[infop->charset]; if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; }else{ *(bufpt++) = '+'; } if( exp>=100 ){ *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */ exp %= 100; } *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */ *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */ } *bufpt = 0; /* The converted number is in buf[] and zero terminated. Output it. ** Note that the number is in the usual order, not reversed as with ** integer conversions. */ length = (int)(bufpt-zOut); bufpt = zOut; /* Special case: Add leading zeros if the flag_zeropad flag is ** set and we are not left justified */ if( flag_zeropad && !flag_leftjustify && length < width){ int i; int nPad = width - length; for(i=width; i>=nPad; i--){ bufpt[i] = bufpt[i-nPad]; } i = prefix!=0; while( nPad-- ) bufpt[i++] = '0'; length = width; } #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */ break; case etSIZE: if( !bArgList ){ *(va_arg(ap,int*)) = pAccum->nChar; } length = width = 0; break; case etPERCENT: buf[0] = '%'; bufpt = buf; length = 1; break; case etCHARX: if( bArgList ){ bufpt = getTextArg(pArgList); c = bufpt ? bufpt[0] : 0; }else{ c = va_arg(ap,int); } if( precision>1 ){ width -= precision-1; if( width>1 && !flag_leftjustify ){ sqlite3AppendChar(pAccum, width-1, ' '); width = 0; } sqlite3AppendChar(pAccum, precision-1, c); } length = 1; buf[0] = c; bufpt = buf; break; case etSTRING: case etDYNSTRING: if( bArgList ){ bufpt = getTextArg(pArgList); xtype = etSTRING; }else{ bufpt = va_arg(ap,char*); } if( bufpt==0 ){ bufpt = ""; }else if( xtype==etDYNSTRING ){ zExtra = bufpt; } if( precision>=0 ){ for(length=0; length<precision && bufpt[length]; length++){} }else{ length = sqlite3Strlen30(bufpt); } break; case etSQLESCAPE: /* Escape ' characters */ case etSQLESCAPE2: /* Escape ' and enclose in '...' */ case etSQLESCAPE3: { /* Escape " characters */ int i, j, k, n, isnull; int needQuote; char ch; char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */ char *escarg; if( bArgList ){ escarg = getTextArg(pArgList); }else{ escarg = va_arg(ap,char*); } isnull = escarg==0; if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)"); k = precision; for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){ if( ch==q ) n++; } needQuote = !isnull && xtype==etSQLESCAPE2; n += i + 3; if( n>etBUFSIZE ){ bufpt = zExtra = sqlite3Malloc( n ); if( bufpt==0 ){ setStrAccumError(pAccum, STRACCUM_NOMEM); return; } }else{ bufpt = buf; } j = 0; if( needQuote ) bufpt[j++] = q; k = i; for(i=0; i<k; i++){ bufpt[j++] = ch = escarg[i]; if( ch==q ) bufpt[j++] = ch; } if( needQuote ) bufpt[j++] = q; bufpt[j] = 0; length = j; /* The precision in %q and %Q means how many input characters to ** consume, not the length of the output... ** if( precision>=0 && precision<length ) length = precision; */ break; } case etTOKEN: { Token *pToken; if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return; pToken = va_arg(ap, Token*); assert( bArgList==0 ); if( pToken && pToken->n ){ sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n); } length = width = 0; break; } case etSRCLIST: { SrcList *pSrc; int k; struct SrcList_item *pItem; if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return; pSrc = va_arg(ap, SrcList*); k = va_arg(ap, int); pItem = &pSrc->a[k]; assert( bArgList==0 ); assert( k>=0 && k<pSrc->nSrc ); if( pItem->zDatabase ){ sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase); sqlite3StrAccumAppend(pAccum, ".", 1); } sqlite3StrAccumAppendAll(pAccum, pItem->zName); length = width = 0; break; } default: { assert( xtype==etINVALID ); return; } }/* End switch over the format type */ /* ** The text of the conversion is pointed to by "bufpt" and is ** "length" characters long. The field width is "width". Do ** the output. */ width -= length; if( width>0 ){ if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); sqlite3StrAccumAppend(pAccum, bufpt, length); if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); }else{ sqlite3StrAccumAppend(pAccum, bufpt, length); } if( zExtra ){ sqlite3DbFree(pAccum->db, zExtra); zExtra = 0; } }/* End for loop over the format string */ } /* End of function */ /* ** Enlarge the memory allocation on a StrAccum object so that it is ** able to accept at least N more bytes of text. ** ** Return the number of bytes of text that StrAccum is able to accept ** after the attempted enlargement. The value returned might be zero. */ static int sqlite3StrAccumEnlarge(StrAccum *p, int N){ char *zNew; assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */ if( p->accError ){ testcase(p->accError==STRACCUM_TOOBIG); testcase(p->accError==STRACCUM_NOMEM); return 0; } if( p->mxAlloc==0 ){ N = p->nAlloc - p->nChar - 1; setStrAccumError(p, STRACCUM_TOOBIG); return N; }else{ char *zOld = isMalloced(p) ? p->zText : 0; i64 szNew = p->nChar; assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); szNew += N + 1; if( szNew+p->nChar<=p->mxAlloc ){ /* Force exponential buffer size growth as long as it does not overflow, ** to avoid having to call this routine too often */ szNew += p->nChar; } if( szNew > p->mxAlloc ){ sqlite3StrAccumReset(p); setStrAccumError(p, STRACCUM_TOOBIG); return 0; }else{ p->nAlloc = (int)szNew; } if( p->db ){ zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); }else{ zNew = sqlite3_realloc64(zOld, p->nAlloc); } if( zNew ){ assert( p->zText!=0 || p->nChar==0 ); if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); p->zText = zNew; p->nAlloc = sqlite3DbMallocSize(p->db, zNew); p->printfFlags |= SQLITE_PRINTF_MALLOCED; }else{ sqlite3StrAccumReset(p); setStrAccumError(p, STRACCUM_NOMEM); return 0; } } return N; } /* ** Append N copies of character c to the given string buffer. */ SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){ testcase( p->nChar + (i64)N > 0x7fffffff ); if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){ return; } assert( (p->zText==p->zBase)==!isMalloced(p) ); while( (N--)>0 ) p->zText[p->nChar++] = c; } /* ** The StrAccum "p" is not large enough to accept N new bytes of z[]. ** So enlarge if first, then do the append. ** ** This is a helper routine to sqlite3StrAccumAppend() that does special-case ** work (enlarging the buffer) using tail recursion, so that the ** sqlite3StrAccumAppend() routine can use fast calling semantics. */ static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){ N = sqlite3StrAccumEnlarge(p, N); if( N>0 ){ memcpy(&p->zText[p->nChar], z, N); p->nChar += N; } assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); } /* ** Append N bytes of text from z to the StrAccum object. Increase the ** size of the memory allocation for StrAccum if necessary. */ SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ assert( z!=0 || N==0 ); assert( p->zText!=0 || p->nChar==0 || p->accError ); assert( N>=0 ); assert( p->accError==0 || p->nAlloc==0 ); if( p->nChar+N >= p->nAlloc ){ enlargeAndAppend(p,z,N); }else if( N ){ assert( p->zText ); p->nChar += N; memcpy(&p->zText[p->nChar-N], z, N); } } /* ** Append the complete text of zero-terminated string z[] to the p string. */ SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){ sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z)); } /* ** Finish off a string by making sure it is zero-terminated. ** Return a pointer to the resulting string. Return a NULL ** pointer if any kind of error was encountered. */ static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){ assert( p->mxAlloc>0 && !isMalloced(p) ); p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); if( p->zText ){ memcpy(p->zText, p->zBase, p->nChar+1); p->printfFlags |= SQLITE_PRINTF_MALLOCED; }else{ setStrAccumError(p, STRACCUM_NOMEM); } return p->zText; } SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){ if( p->zText ){ assert( (p->zText==p->zBase)==!isMalloced(p) ); p->zText[p->nChar] = 0; if( p->mxAlloc>0 && !isMalloced(p) ){ return strAccumFinishRealloc(p); } } return p->zText; } /* ** Reset an StrAccum string. Reclaim all malloced memory. */ SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){ assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); if( isMalloced(p) ){ sqlite3DbFree(p->db, p->zText); p->printfFlags &= ~SQLITE_PRINTF_MALLOCED; } p->zText = 0; } /* ** Initialize a string accumulator. ** ** p: The accumulator to be initialized. ** db: Pointer to a database connection. May be NULL. Lookaside ** memory is used if not NULL. db->mallocFailed is set appropriately ** when not NULL. ** zBase: An initial buffer. May be NULL in which case the initial buffer ** is malloced. ** n: Size of zBase in bytes. If total space requirements never exceed ** n then no memory allocations ever occur. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory ** allocations will ever occur. */ SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){ p->zText = p->zBase = zBase; p->db = db; p->nChar = 0; p->nAlloc = n; p->mxAlloc = mx; p->accError = 0; p->printfFlags = 0; } /* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; StrAccum acc; assert( db!=0 ); sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase), db->aLimit[SQLITE_LIMIT_LENGTH]); acc.printfFlags = SQLITE_PRINTF_INTERNAL; sqlite3VXPrintf(&acc, zFormat, ap); z = sqlite3StrAccumFinish(&acc); if( acc.accError==STRACCUM_NOMEM ){ sqlite3OomFault(db); } return z; } /* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ va_list ap; char *z; va_start(ap, zFormat); z = sqlite3VMPrintf(db, zFormat, ap); va_end(ap); return z; } /* ** Print into memory obtained from sqlite3_malloc(). Omit the internal ** %-conversion extensions. */ SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){ char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; StrAccum acc; #ifdef SQLITE_ENABLE_API_ARMOR if( zFormat==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH); sqlite3VXPrintf(&acc, zFormat, ap); z = sqlite3StrAccumFinish(&acc); return z; } /* ** Print into memory obtained from sqlite3_malloc()(). Omit the internal ** %-conversion extensions. */ SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){ va_list ap; char *z; #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif va_start(ap, zFormat); z = sqlite3_vmprintf(zFormat, ap); va_end(ap); return z; } /* ** sqlite3_snprintf() works like snprintf() except that it ignores the ** current locale settings. This is important for SQLite because we ** are not able to use a "," as the decimal point in place of "." as ** specified by some locales. ** ** Oops: The first two arguments of sqlite3_snprintf() are backwards ** from the snprintf() standard. Unfortunately, it is too late to change ** this without breaking compatibility, so we just have to live with the ** mistake. ** ** sqlite3_vsnprintf() is the varargs version. */ SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ StrAccum acc; if( n<=0 ) return zBuf; #ifdef SQLITE_ENABLE_API_ARMOR if( zBuf==0 || zFormat==0 ) { (void)SQLITE_MISUSE_BKPT; if( zBuf ) zBuf[0] = 0; return zBuf; } #endif sqlite3StrAccumInit(&acc, 0, zBuf, n, 0); sqlite3VXPrintf(&acc, zFormat, ap); zBuf[acc.nChar] = 0; return zBuf; } SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ char *z; va_list ap; va_start(ap,zFormat); z = sqlite3_vsnprintf(n, zBuf, zFormat, ap); va_end(ap); return z; } /* ** This is the routine that actually formats the sqlite3_log() message. ** We house it in a separate routine from sqlite3_log() to avoid using ** stack space on small-stack systems when logging is disabled. ** ** sqlite3_log() must render into a static buffer. It cannot dynamically ** allocate memory because it might be called while the memory allocator ** mutex is held. ** ** sqlite3VXPrintf() might ask for *temporary* memory allocations for ** certain format characters (%q) or for very large precisions or widths. ** Care must be taken that any sqlite3_log() calls that occur while the ** memory mutex is held do not use these mechanisms. */ static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ StrAccum acc; /* String accumulator */ char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0); sqlite3VXPrintf(&acc, zFormat, ap); sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, sqlite3StrAccumFinish(&acc)); } /* ** Format and write a message to the log if logging is enabled. */ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){ va_list ap; /* Vararg list */ if( sqlite3GlobalConfig.xLog ){ va_start(ap, zFormat); renderLogMsg(iErrCode, zFormat, ap); va_end(ap); } } #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) /* ** A version of printf() that understands %lld. Used for debugging. ** The printf() built into some versions of windows does not understand %lld ** and segfaults if you give it a long long int. */ SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){ va_list ap; StrAccum acc; char zBuf[500]; sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); va_start(ap,zFormat); sqlite3VXPrintf(&acc, zFormat, ap); va_end(ap); sqlite3StrAccumFinish(&acc); fprintf(stdout,"%s", zBuf); fflush(stdout); } #endif /* ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats. */ SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){ va_list ap; va_start(ap,zFormat); sqlite3VXPrintf(p, zFormat, ap); va_end(ap); } /************** End of printf.c **********************************************/ /************** Begin file treeview.c ****************************************/ /* ** 2015-06-08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains C code to implement the TreeView debugging routines. ** These routines print a parse tree to standard output for debugging and ** analysis. ** ** The interfaces in this file is only available when compiling ** with SQLITE_DEBUG. */ /* #include "sqliteInt.h" */ #ifdef SQLITE_DEBUG /* ** Add a new subitem to the tree. The moreToFollow flag indicates that this ** is not the last item in the tree. */ static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){ if( p==0 ){ p = sqlite3_malloc64( sizeof(*p) ); if( p==0 ) return 0; memset(p, 0, sizeof(*p)); }else{ p->iLevel++; } assert( moreToFollow==0 || moreToFollow==1 ); if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow; return p; } /* ** Finished with one layer of the tree */ static void sqlite3TreeViewPop(TreeView *p){ if( p==0 ) return; p->iLevel--; if( p->iLevel<0 ) sqlite3_free(p); } /* ** Generate a single line of output for the tree, with a prefix that contains ** all the appropriate tree lines */ static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){ va_list ap; int i; StrAccum acc; char zBuf[500]; sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); if( p ){ for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){ sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4); } sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4); } va_start(ap, zFormat); sqlite3VXPrintf(&acc, zFormat, ap); va_end(ap); assert( acc.nChar>0 ); if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1); sqlite3StrAccumFinish(&acc); fprintf(stdout,"%s", zBuf); fflush(stdout); } /* ** Shorthand for starting a new tree item that consists of a single label */ static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){ p = sqlite3TreeViewPush(p, moreFollows); sqlite3TreeViewLine(p, "%s", zLabel); } /* ** Generate a human-readable description of a WITH clause. */ SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){ int i; if( pWith==0 ) return; if( pWith->nCte==0 ) return; if( pWith->pOuter ){ sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter); }else{ sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith); } if( pWith->nCte>0 ){ pView = sqlite3TreeViewPush(pView, 1); for(i=0; i<pWith->nCte; i++){ StrAccum x; char zLine[1000]; const struct Cte *pCte = &pWith->a[i]; sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); sqlite3XPrintf(&x, "%s", pCte->zName); if( pCte->pCols && pCte->pCols->nExpr>0 ){ char cSep = '('; int j; for(j=0; j<pCte->pCols->nExpr; j++){ sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName); cSep = ','; } sqlite3XPrintf(&x, ")"); } sqlite3XPrintf(&x, " AS"); sqlite3StrAccumFinish(&x); sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1); sqlite3TreeViewSelect(pView, pCte->pSelect, 0); sqlite3TreeViewPop(pView); } sqlite3TreeViewPop(pView); } } /* ** Generate a human-readable description of a Select object. */ SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){ int n = 0; int cnt = 0; pView = sqlite3TreeViewPush(pView, moreToFollow); if( p->pWith ){ sqlite3TreeViewWith(pView, p->pWith, 1); cnt = 1; sqlite3TreeViewPush(pView, 1); } do{ sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d", ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""), ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags, (int)p->nSelectRow ); if( cnt++ ) sqlite3TreeViewPop(pView); if( p->pPrior ){ n = 1000; }else{ n = 0; if( p->pSrc && p->pSrc->nSrc ) n++; if( p->pWhere ) n++; if( p->pGroupBy ) n++; if( p->pHaving ) n++; if( p->pOrderBy ) n++; if( p->pLimit ) n++; if( p->pOffset ) n++; } sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set"); if( p->pSrc && p->pSrc->nSrc ){ int i; pView = sqlite3TreeViewPush(pView, (n--)>0); sqlite3TreeViewLine(pView, "FROM"); for(i=0; i<p->pSrc->nSrc; i++){ struct SrcList_item *pItem = &p->pSrc->a[i]; StrAccum x; char zLine[100]; sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor); if( pItem->zDatabase ){ sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName); }else if( pItem->zName ){ sqlite3XPrintf(&x, " %s", pItem->zName); } if( pItem->pTab ){ sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName); } if( pItem->zAlias ){ sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias); } if( pItem->fg.jointype & JT_LEFT ){ sqlite3XPrintf(&x, " LEFT-JOIN"); } sqlite3StrAccumFinish(&x); sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1); if( pItem->pSelect ){ sqlite3TreeViewSelect(pView, pItem->pSelect, 0); } if( pItem->fg.isTabFunc ){ sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:"); } sqlite3TreeViewPop(pView); } sqlite3TreeViewPop(pView); } if( p->pWhere ){ sqlite3TreeViewItem(pView, "WHERE", (n--)>0); sqlite3TreeViewExpr(pView, p->pWhere, 0); sqlite3TreeViewPop(pView); } if( p->pGroupBy ){ sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY"); } if( p->pHaving ){ sqlite3TreeViewItem(pView, "HAVING", (n--)>0); sqlite3TreeViewExpr(pView, p->pHaving, 0); sqlite3TreeViewPop(pView); } if( p->pOrderBy ){ sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY"); } if( p->pLimit ){ sqlite3TreeViewItem(pView, "LIMIT", (n--)>0); sqlite3TreeViewExpr(pView, p->pLimit, 0); sqlite3TreeViewPop(pView); } if( p->pOffset ){ sqlite3TreeViewItem(pView, "OFFSET", (n--)>0); sqlite3TreeViewExpr(pView, p->pOffset, 0); sqlite3TreeViewPop(pView); } if( p->pPrior ){ const char *zOp = "UNION"; switch( p->op ){ case TK_ALL: zOp = "UNION ALL"; break; case TK_INTERSECT: zOp = "INTERSECT"; break; case TK_EXCEPT: zOp = "EXCEPT"; break; } sqlite3TreeViewItem(pView, zOp, 1); } p = p->pPrior; }while( p!=0 ); sqlite3TreeViewPop(pView); } /* ** Generate a human-readable explanation of an expression tree. */ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){ const char *zBinOp = 0; /* Binary operator */ const char *zUniOp = 0; /* Unary operator */ char zFlgs[30]; pView = sqlite3TreeViewPush(pView, moreToFollow); if( pExpr==0 ){ sqlite3TreeViewLine(pView, "nil"); sqlite3TreeViewPop(pView); return; } if( pExpr->flags ){ sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags); }else{ zFlgs[0] = 0; } switch( pExpr->op ){ case TK_AGG_COLUMN: { sqlite3TreeViewLine(pView, "AGG{%d:%d}%s", pExpr->iTable, pExpr->iColumn, zFlgs); break; } case TK_COLUMN: { if( pExpr->iTable<0 ){ /* This only happens when coding check constraints */ sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs); }else{ sqlite3TreeViewLine(pView, "{%d:%d}%s", pExpr->iTable, pExpr->iColumn, zFlgs); } break; } case TK_INTEGER: { if( pExpr->flags & EP_IntValue ){ sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue); }else{ sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken); } break; } #ifndef SQLITE_OMIT_FLOATING_POINT case TK_FLOAT: { sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); break; } #endif case TK_STRING: { sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken); break; } case TK_NULL: { sqlite3TreeViewLine(pView,"NULL"); break; } #ifndef SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: { sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); break; } #endif case TK_VARIABLE: { sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)", pExpr->u.zToken, pExpr->iColumn); break; } case TK_REGISTER: { sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable); break; } case TK_ID: { sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken); break; } #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken); sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } #endif /* SQLITE_OMIT_CAST */ case TK_LT: zBinOp = "LT"; break; case TK_LE: zBinOp = "LE"; break; case TK_GT: zBinOp = "GT"; break; case TK_GE: zBinOp = "GE"; break; case TK_NE: zBinOp = "NE"; break; case TK_EQ: zBinOp = "EQ"; break; case TK_IS: zBinOp = "IS"; break; case TK_ISNOT: zBinOp = "ISNOT"; break; case TK_AND: zBinOp = "AND"; break; case TK_OR: zBinOp = "OR"; break; case TK_PLUS: zBinOp = "ADD"; break; case TK_STAR: zBinOp = "MUL"; break; case TK_MINUS: zBinOp = "SUB"; break; case TK_REM: zBinOp = "REM"; break; case TK_BITAND: zBinOp = "BITAND"; break; case TK_BITOR: zBinOp = "BITOR"; break; case TK_SLASH: zBinOp = "DIV"; break; case TK_LSHIFT: zBinOp = "LSHIFT"; break; case TK_RSHIFT: zBinOp = "RSHIFT"; break; case TK_CONCAT: zBinOp = "CONCAT"; break; case TK_DOT: zBinOp = "DOT"; break; case TK_UMINUS: zUniOp = "UMINUS"; break; case TK_UPLUS: zUniOp = "UPLUS"; break; case TK_BITNOT: zUniOp = "BITNOT"; break; case TK_NOT: zUniOp = "NOT"; break; case TK_ISNULL: zUniOp = "ISNULL"; break; case TK_NOTNULL: zUniOp = "NOTNULL"; break; case TK_SPAN: { sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken); sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } case TK_COLLATE: { sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken); sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } case TK_AGG_FUNCTION: case TK_FUNCTION: { ExprList *pFarg; /* List of function arguments */ if( ExprHasProperty(pExpr, EP_TokenOnly) ){ pFarg = 0; }else{ pFarg = pExpr->x.pList; } if( pExpr->op==TK_AGG_FUNCTION ){ sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q", pExpr->op2, pExpr->u.zToken); }else{ sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken); } if( pFarg ){ sqlite3TreeViewExprList(pView, pFarg, 0, 0); } break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_EXISTS: { sqlite3TreeViewLine(pView, "EXISTS-expr"); sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); break; } case TK_SELECT: { sqlite3TreeViewLine(pView, "SELECT-expr"); sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); break; } case TK_IN: { sqlite3TreeViewLine(pView, "IN"); sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); }else{ sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); } break; } #endif /* SQLITE_OMIT_SUBQUERY */ /* ** x BETWEEN y AND z ** ** This is equivalent to ** ** x>=y AND x<=z ** ** X is stored in pExpr->pLeft. ** Y is stored in pExpr->pList->a[0].pExpr. ** Z is stored in pExpr->pList->a[1].pExpr. */ case TK_BETWEEN: { Expr *pX = pExpr->pLeft; Expr *pY = pExpr->x.pList->a[0].pExpr; Expr *pZ = pExpr->x.pList->a[1].pExpr; sqlite3TreeViewLine(pView, "BETWEEN"); sqlite3TreeViewExpr(pView, pX, 1); sqlite3TreeViewExpr(pView, pY, 1); sqlite3TreeViewExpr(pView, pZ, 0); break; } case TK_TRIGGER: { /* If the opcode is TK_TRIGGER, then the expression is a reference ** to a column in the new.* or old.* pseudo-tables available to ** trigger programs. In this case Expr.iTable is set to 1 for the ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn ** is set to the column of the pseudo-table to read, or to -1 to ** read the rowid field. */ sqlite3TreeViewLine(pView, "%s(%d)", pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn); break; } case TK_CASE: { sqlite3TreeViewLine(pView, "CASE"); sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); break; } #ifndef SQLITE_OMIT_TRIGGER case TK_RAISE: { const char *zType = "unk"; switch( pExpr->affinity ){ case OE_Rollback: zType = "rollback"; break; case OE_Abort: zType = "abort"; break; case OE_Fail: zType = "fail"; break; case OE_Ignore: zType = "ignore"; break; } sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken); break; } #endif case TK_MATCH: { sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s", pExpr->iTable, pExpr->iColumn, zFlgs); sqlite3TreeViewExpr(pView, pExpr->pRight, 0); break; } case TK_VECTOR: { sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR"); break; } case TK_SELECT_COLUMN: { sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn); sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0); break; } default: { sqlite3TreeViewLine(pView, "op=%d", pExpr->op); break; } } if( zBinOp ){ sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs); sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); sqlite3TreeViewExpr(pView, pExpr->pRight, 0); }else if( zUniOp ){ sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs); sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); } sqlite3TreeViewPop(pView); } /* ** Generate a human-readable explanation of an expression list. */ SQLITE_PRIVATE void sqlite3TreeViewBareExprList( TreeView *pView, const ExprList *pList, const char *zLabel ){ if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST"; if( pList==0 ){ sqlite3TreeViewLine(pView, "%s (empty)", zLabel); }else{ int i; sqlite3TreeViewLine(pView, "%s", zLabel); for(i=0; i<pList->nExpr; i++){ int j = pList->a[i].u.x.iOrderByCol; if( j ){ sqlite3TreeViewPush(pView, 0); sqlite3TreeViewLine(pView, "iOrderByCol=%d", j); } sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1); if( j ) sqlite3TreeViewPop(pView); } } } SQLITE_PRIVATE void sqlite3TreeViewExprList( TreeView *pView, const ExprList *pList, u8 moreToFollow, const char *zLabel ){ pView = sqlite3TreeViewPush(pView, moreToFollow); sqlite3TreeViewBareExprList(pView, pList, zLabel); sqlite3TreeViewPop(pView); } #endif /* SQLITE_DEBUG */ /************** End of treeview.c ********************************************/ /************** Begin file random.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code to implement a pseudo-random number ** generator (PRNG) for SQLite. ** ** Random numbers are used by some of the database backends in order ** to generate random integer keys for tables or random filenames. */ /* #include "sqliteInt.h" */ /* All threads share a single random number generator. ** This structure is the current state of the generator. */ static SQLITE_WSD struct sqlite3PrngType { unsigned char isInit; /* True if initialized */ unsigned char i, j; /* State variables */ unsigned char s[256]; /* State variables */ } sqlite3Prng; /* ** Return N random bytes. */ SQLITE_API void sqlite3_randomness(int N, void *pBuf){ unsigned char t; unsigned char *zBuf = pBuf; /* The "wsdPrng" macro will resolve to the pseudo-random number generator ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdPrng can refer directly ** to the "sqlite3Prng" state vector declared above. */ #ifdef SQLITE_OMIT_WSD struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); # define wsdPrng p[0] #else # define wsdPrng sqlite3Prng #endif #if SQLITE_THREADSAFE sqlite3_mutex *mutex; #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return; #endif #if SQLITE_THREADSAFE mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); #endif sqlite3_mutex_enter(mutex); if( N<=0 || pBuf==0 ){ wsdPrng.isInit = 0; sqlite3_mutex_leave(mutex); return; } /* Initialize the state of the random number generator once, ** the first time this routine is called. The seed value does ** not need to contain a lot of randomness since we are not ** trying to do secure encryption or anything like that... ** ** Nothing in this file or anywhere else in SQLite does any kind of ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random ** number generator) not as an encryption device. */ if( !wsdPrng.isInit ){ int i; char k[256]; wsdPrng.j = 0; wsdPrng.i = 0; sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k); for(i=0; i<256; i++){ wsdPrng.s[i] = (u8)i; } for(i=0; i<256; i++){ wsdPrng.j += wsdPrng.s[i] + k[i]; t = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; wsdPrng.s[i] = t; } wsdPrng.isInit = 1; } assert( N>0 ); do{ wsdPrng.i++; t = wsdPrng.s[wsdPrng.i]; wsdPrng.j += t; wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = t; t += wsdPrng.s[wsdPrng.i]; *(zBuf++) = wsdPrng.s[t]; }while( --N ); sqlite3_mutex_leave(mutex); } #ifndef SQLITE_UNTESTABLE /* ** For testing purposes, we sometimes want to preserve the state of ** PRNG and restore the PRNG to its saved state at a later time, or ** to reset the PRNG to its initial state. These routines accomplish ** those tasks. ** ** The sqlite3_test_control() interface calls these routines to ** control the PRNG. */ static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng; SQLITE_PRIVATE void sqlite3PrngSaveState(void){ memcpy( &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), &GLOBAL(struct sqlite3PrngType, sqlite3Prng), sizeof(sqlite3Prng) ); } SQLITE_PRIVATE void sqlite3PrngRestoreState(void){ memcpy( &GLOBAL(struct sqlite3PrngType, sqlite3Prng), &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), sizeof(sqlite3Prng) ); } #endif /* SQLITE_UNTESTABLE */ /************** End of random.c **********************************************/ /************** Begin file threads.c *****************************************/ /* ** 2012 July 21 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file presents a simple cross-platform threading interface for ** use internally by SQLite. ** ** A "thread" can be created using sqlite3ThreadCreate(). This thread ** runs independently of its creator until it is joined using ** sqlite3ThreadJoin(), at which point it terminates. ** ** Threads do not have to be real. It could be that the work of the ** "thread" is done by the main thread at either the sqlite3ThreadCreate() ** or sqlite3ThreadJoin() call. This is, in fact, what happens in ** single threaded systems. Nothing in SQLite requires multiple threads. ** This interface exists so that applications that want to take advantage ** of multiple cores can do so, while also allowing applications to stay ** single-threaded if desired. */ /* #include "sqliteInt.h" */ #if SQLITE_OS_WIN /* # include "os_win.h" */ #endif #if SQLITE_MAX_WORKER_THREADS>0 /********************************* Unix Pthreads ****************************/ #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */ /* #include <pthread.h> */ /* A running thread */ struct SQLiteThread { pthread_t tid; /* Thread ID */ int done; /* Set to true when thread finishes */ void *pOut; /* Result returned by the thread */ void *(*xTask)(void*); /* The thread routine */ void *pIn; /* Argument to the thread */ }; /* Create a new thread */ SQLITE_PRIVATE int sqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ ){ SQLiteThread *p; int rc; assert( ppThread!=0 ); assert( xTask!=0 ); /* This routine is never used in single-threaded mode */ assert( sqlite3GlobalConfig.bCoreMutex!=0 ); *ppThread = 0; p = sqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; memset(p, 0, sizeof(*p)); p->xTask = xTask; p->pIn = pIn; /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a ** function that returns SQLITE_ERROR when passed the argument 200, that ** forces worker threads to run sequentially and deterministically ** for testing purposes. */ if( sqlite3FaultSim(200) ){ rc = 1; }else{ rc = pthread_create(&p->tid, 0, xTask, pIn); } if( rc ){ p->done = 1; p->pOut = xTask(pIn); } *ppThread = p; return SQLITE_OK; } /* Get the results of the thread */ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ int rc; assert( ppOut!=0 ); if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; if( p->done ){ *ppOut = p->pOut; rc = SQLITE_OK; }else{ rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK; } sqlite3_free(p); return rc; } #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */ /******************************** End Unix Pthreads *************************/ /********************************* Win32 Threads ****************************/ #if SQLITE_OS_WIN_THREADS #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */ #include <process.h> /* A running thread */ struct SQLiteThread { void *tid; /* The thread handle */ unsigned id; /* The thread identifier */ void *(*xTask)(void*); /* The routine to run as a thread */ void *pIn; /* Argument to xTask */ void *pResult; /* Result of xTask */ }; /* Thread procedure Win32 compatibility shim */ static unsigned __stdcall sqlite3ThreadProc( void *pArg /* IN: Pointer to the SQLiteThread structure */ ){ SQLiteThread *p = (SQLiteThread *)pArg; assert( p!=0 ); #if 0 /* ** This assert appears to trigger spuriously on certain ** versions of Windows, possibly due to _beginthreadex() ** and/or CreateThread() not fully setting their thread ** ID parameter before starting the thread. */ assert( p->id==GetCurrentThreadId() ); #endif assert( p->xTask!=0 ); p->pResult = p->xTask(p->pIn); _endthreadex(0); return 0; /* NOT REACHED */ } /* Create a new thread */ SQLITE_PRIVATE int sqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ ){ SQLiteThread *p; assert( ppThread!=0 ); assert( xTask!=0 ); *ppThread = 0; p = sqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a ** function that returns SQLITE_ERROR when passed the argument 200, that ** forces worker threads to run sequentially and deterministically ** (via the sqlite3FaultSim() term of the conditional) for testing ** purposes. */ if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){ memset(p, 0, sizeof(*p)); }else{ p->xTask = xTask; p->pIn = pIn; p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id); if( p->tid==0 ){ memset(p, 0, sizeof(*p)); } } if( p->xTask==0 ){ p->id = GetCurrentThreadId(); p->pResult = xTask(pIn); } *ppThread = p; return SQLITE_OK; } SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */ /* Get the results of the thread */ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ DWORD rc; BOOL bRc; assert( ppOut!=0 ); if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; if( p->xTask==0 ){ /* assert( p->id==GetCurrentThreadId() ); */ rc = WAIT_OBJECT_0; assert( p->tid==0 ); }else{ assert( p->id!=0 && p->id!=GetCurrentThreadId() ); rc = sqlite3Win32Wait((HANDLE)p->tid); assert( rc!=WAIT_IO_COMPLETION ); bRc = CloseHandle((HANDLE)p->tid); assert( bRc ); } if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult; sqlite3_free(p); return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR; } #endif /* SQLITE_OS_WIN_THREADS */ /******************************** End Win32 Threads *************************/ /********************************* Single-Threaded **************************/ #ifndef SQLITE_THREADS_IMPLEMENTED /* ** This implementation does not actually create a new thread. It does the ** work of the thread in the main thread, when either the thread is created ** or when it is joined */ /* A running thread */ struct SQLiteThread { void *(*xTask)(void*); /* The routine to run as a thread */ void *pIn; /* Argument to xTask */ void *pResult; /* Result of xTask */ }; /* Create a new thread */ SQLITE_PRIVATE int sqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ ){ SQLiteThread *p; assert( ppThread!=0 ); assert( xTask!=0 ); *ppThread = 0; p = sqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; if( (SQLITE_PTR_TO_INT(p)/17)&1 ){ p->xTask = xTask; p->pIn = pIn; }else{ p->xTask = 0; p->pResult = xTask(pIn); } *ppThread = p; return SQLITE_OK; } /* Get the results of the thread */ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ assert( ppOut!=0 ); if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; if( p->xTask ){ *ppOut = p->xTask(p->pIn); }else{ *ppOut = p->pResult; } sqlite3_free(p); #if defined(SQLITE_TEST) { void *pTstAlloc = sqlite3Malloc(10); if (!pTstAlloc) return SQLITE_NOMEM_BKPT; sqlite3_free(pTstAlloc); } #endif return SQLITE_OK; } #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */ /****************************** End Single-Threaded *************************/ #endif /* SQLITE_MAX_WORKER_THREADS>0 */ /************** End of threads.c *********************************************/ /************** Begin file utf.c *********************************************/ /* ** 2004 April 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used to translate between UTF-8, ** UTF-16, UTF-16BE, and UTF-16LE. ** ** Notes on UTF-8: ** ** Byte-0 Byte-1 Byte-2 Byte-3 Value ** 0xxxxxxx 00000000 00000000 0xxxxxxx ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** ** ** Notes on UTF-16: (with wwww+1==uuuuu) ** ** Word-0 Word-1 Value ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx ** ** ** BOM or Byte Order Mark: ** 0xff 0xfe little-endian utf-16 follows ** 0xfe 0xff big-endian utf-16 follows ** */ /* #include "sqliteInt.h" */ /* #include <assert.h> */ /* #include "vdbeInt.h" */ #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0 /* ** The following constant value is used by the SQLITE_BIGENDIAN and ** SQLITE_LITTLEENDIAN macros. */ SQLITE_PRIVATE const int sqlite3one = 1; #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */ /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. */ static const unsigned char sqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; #define WRITE_UTF8(zOut, c) { \ if( c<0x00080 ){ \ *zOut++ = (u8)(c&0xFF); \ } \ else if( c<0x00800 ){ \ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ else if( c<0x10000 ){ \ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ }else{ \ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ } #define WRITE_UTF16LE(zOut, c) { \ if( c<=0xFFFF ){ \ *zOut++ = (u8)(c&0x00FF); \ *zOut++ = (u8)((c>>8)&0x00FF); \ }else{ \ *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ *zOut++ = (u8)(c&0x00FF); \ *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ } \ } #define WRITE_UTF16BE(zOut, c) { \ if( c<=0xFFFF ){ \ *zOut++ = (u8)((c>>8)&0x00FF); \ *zOut++ = (u8)(c&0x00FF); \ }else{ \ *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ *zOut++ = (u8)(c&0x00FF); \ } \ } #define READ_UTF16LE(zIn, TERM, c){ \ c = (*zIn++); \ c += ((*zIn++)<<8); \ if( c>=0xD800 && c<0xE000 && TERM ){ \ int c2 = (*zIn++); \ c2 += ((*zIn++)<<8); \ c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ } \ } #define READ_UTF16BE(zIn, TERM, c){ \ c = ((*zIn++)<<8); \ c += (*zIn++); \ if( c>=0xD800 && c<0xE000 && TERM ){ \ int c2 = ((*zIn++)<<8); \ c2 += (*zIn++); \ c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ } \ } /* ** Translate a single UTF-8 character. Return the unicode value. ** ** During translation, assume that the byte that zTerm points ** is a 0x00. ** ** Write a pointer to the next unread byte back into *pzNext. ** ** Notes On Invalid UTF-8: ** ** * This routine never allows a 7-bit character (0x00 through 0x7f) to ** be encoded as a multi-byte character. Any multi-byte character that ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. ** ** * This routine never allows a UTF16 surrogate value to be encoded. ** If a multi-byte character attempts to encode a value between ** 0xd800 and 0xe000 then it is rendered as 0xfffd. ** ** * Bytes in the range of 0x80 through 0xbf which occur as the first ** byte of a character are interpreted as single-byte characters ** and rendered as themselves even though they are technically ** invalid characters. ** ** * This routine accepts over-length UTF8 encodings ** for unicode values 0x80 and greater. It does not change over-length ** encodings to 0xfffd as some systems recommend. */ #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = sqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ if( c<0x80 \ || (c&0xFFFFF800)==0xD800 \ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } SQLITE_PRIVATE u32 sqlite3Utf8Read( const unsigned char **pz /* Pointer to string from which to read char */ ){ unsigned int c; /* Same as READ_UTF8() above but without the zTerm parameter. ** For this routine, we assume the UTF8 string is always zero-terminated. */ c = *((*pz)++); if( c>=0xc0 ){ c = sqlite3Utf8Trans1[c-0xc0]; while( (*(*pz) & 0xc0)==0x80 ){ c = (c<<6) + (0x3f & *((*pz)++)); } if( c<0x80 || (c&0xFFFFF800)==0xD800 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } } return c; } /* ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). */ /* #define TRANSLATE_TRACE 1 */ #ifndef SQLITE_OMIT_UTF16 /* ** This routine transforms the internal text encoding used by pMem to ** desiredEnc. It is an error if the string is already of the desired ** encoding, or if *pMem does not contain a string value. */ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){ int len; /* Maximum length of output string in bytes */ unsigned char *zOut; /* Output buffer */ unsigned char *zIn; /* Input iterator */ unsigned char *zTerm; /* End of input */ unsigned char *z; /* Output iterator */ unsigned int c; assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( pMem->flags&MEM_Str ); assert( pMem->enc!=desiredEnc ); assert( pMem->enc!=0 ); assert( pMem->n>=0 ); #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "INPUT: %s\n", zBuf); } #endif /* If the translation is between UTF-16 little and big endian, then ** all that is required is to swap the byte order. This case is handled ** differently from the others. */ if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ u8 temp; int rc; rc = sqlite3VdbeMemMakeWriteable(pMem); if( rc!=SQLITE_OK ){ assert( rc==SQLITE_NOMEM ); return SQLITE_NOMEM_BKPT; } zIn = (u8*)pMem->z; zTerm = &zIn[pMem->n&~1]; while( zIn<zTerm ){ temp = *zIn; *zIn = *(zIn+1); zIn++; *zIn++ = temp; } pMem->enc = desiredEnc; goto translate_out; } /* Set len to the maximum number of bytes required in the output buffer. */ if( desiredEnc==SQLITE_UTF8 ){ /* When converting from UTF-16, the maximum growth results from ** translating a 2-byte character to a 4-byte UTF-8 character. ** A single byte is required for the output string ** nul-terminator. */ pMem->n &= ~1; len = pMem->n * 2 + 1; }else{ /* When converting from UTF-8 to UTF-16 the maximum growth is caused ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 ** character. Two bytes are required in the output buffer for the ** nul-terminator. */ len = pMem->n * 2 + 2; } /* Set zIn to point at the start of the input buffer and zTerm to point 1 ** byte past the end. ** ** Variable zOut is set to point at the output buffer, space obtained ** from sqlite3_malloc(). */ zIn = (u8*)pMem->z; zTerm = &zIn[pMem->n]; zOut = sqlite3DbMallocRaw(pMem->db, len); if( !zOut ){ return SQLITE_NOMEM_BKPT; } z = zOut; if( pMem->enc==SQLITE_UTF8 ){ if( desiredEnc==SQLITE_UTF16LE ){ /* UTF-8 -> UTF-16 Little-endian */ while( zIn<zTerm ){ READ_UTF8(zIn, zTerm, c); WRITE_UTF16LE(z, c); } }else{ assert( desiredEnc==SQLITE_UTF16BE ); /* UTF-8 -> UTF-16 Big-endian */ while( zIn<zTerm ){ READ_UTF8(zIn, zTerm, c); WRITE_UTF16BE(z, c); } } pMem->n = (int)(z - zOut); *z++ = 0; }else{ assert( desiredEnc==SQLITE_UTF8 ); if( pMem->enc==SQLITE_UTF16LE ){ /* UTF-16 Little-endian -> UTF-8 */ while( zIn<zTerm ){ READ_UTF16LE(zIn, zIn<zTerm, c); WRITE_UTF8(z, c); } }else{ /* UTF-16 Big-endian -> UTF-8 */ while( zIn<zTerm ){ READ_UTF16BE(zIn, zIn<zTerm, c); WRITE_UTF8(z, c); } } pMem->n = (int)(z - zOut); } *z = 0; assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); c = pMem->flags; sqlite3VdbeMemRelease(pMem); pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype)); pMem->enc = desiredEnc; pMem->z = (char*)zOut; pMem->zMalloc = pMem->z; pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z); translate_out: #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "OUTPUT: %s\n", zBuf); } #endif return SQLITE_OK; } /* ** This routine checks for a byte-order mark at the beginning of the ** UTF-16 string stored in *pMem. If one is present, it is removed and ** the encoding of the Mem adjusted. This routine does not do any ** byte-swapping, it just sets Mem.enc appropriately. ** ** The allocation (static, dynamic etc.) and encoding of the Mem may be ** changed by this function. */ SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){ int rc = SQLITE_OK; u8 bom = 0; assert( pMem->n>=0 ); if( pMem->n>1 ){ u8 b1 = *(u8 *)pMem->z; u8 b2 = *(((u8 *)pMem->z) + 1); if( b1==0xFE && b2==0xFF ){ bom = SQLITE_UTF16BE; } if( b1==0xFF && b2==0xFE ){ bom = SQLITE_UTF16LE; } } if( bom ){ rc = sqlite3VdbeMemMakeWriteable(pMem); if( rc==SQLITE_OK ){ pMem->n -= 2; memmove(pMem->z, &pMem->z[2], pMem->n); pMem->z[pMem->n] = '\0'; pMem->z[pMem->n+1] = '\0'; pMem->flags |= MEM_Term; pMem->enc = bom; } } return rc; } #endif /* SQLITE_OMIT_UTF16 */ /* ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, ** return the number of unicode characters in pZ up to (but not including) ** the first 0x00 byte. If nByte is not less than zero, return the ** number of unicode characters in the first nByte of pZ (or up to ** the first 0x00, whichever comes first). */ SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){ int r = 0; const u8 *z = (const u8*)zIn; const u8 *zTerm; if( nByte>=0 ){ zTerm = &z[nByte]; }else{ zTerm = (const u8*)(-1); } assert( z<=zTerm ); while( *z!=0 && z<zTerm ){ SQLITE_SKIP_UTF8(z); r++; } return r; } /* This test function is not currently used by the automated test-suite. ** Hence it is only available in debug builds. */ #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) /* ** Translate UTF-8 to UTF-8. ** ** This has the effect of making sure that the string is well-formed ** UTF-8. Miscoded characters are removed. ** ** The translation is done in-place and aborted if the output ** overruns the input. */ SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){ unsigned char *zOut = zIn; unsigned char *zStart = zIn; u32 c; while( zIn[0] && zOut<=zIn ){ c = sqlite3Utf8Read((const u8**)&zIn); if( c!=0xfffd ){ WRITE_UTF8(zOut, c); } } *zOut = 0; return (int)(zOut - zStart); } #endif #ifndef SQLITE_OMIT_UTF16 /* ** Convert a UTF-16 string in the native encoding into a UTF-8 string. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must ** be freed by the calling function. ** ** NULL is returned if there is an allocation error. */ SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){ Mem m; memset(&m, 0, sizeof(m)); m.db = db; sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC); sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8); if( db->mallocFailed ){ sqlite3VdbeMemRelease(&m); m.z = 0; } assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); assert( (m.flags & MEM_Str)!=0 || db->mallocFailed ); assert( m.z || db->mallocFailed ); return m.z; } /* ** zIn is a UTF-16 encoded unicode string at least nChar characters long. ** Return the number of bytes in the first nChar unicode characters ** in pZ. nChar must be non-negative. */ SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){ int c; unsigned char const *z = zIn; int n = 0; if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){ while( n<nChar ){ READ_UTF16BE(z, 1, c); n++; } }else{ while( n<nChar ){ READ_UTF16LE(z, 1, c); n++; } } return (int)(z-(unsigned char const *)zIn); } #if defined(SQLITE_TEST) /* ** This routine is called from the TCL test function "translate_selftest". ** It checks that the primitives for serializing and deserializing ** characters in each encoding are inverses of each other. */ SQLITE_PRIVATE void sqlite3UtfSelfTest(void){ unsigned int i, t; unsigned char zBuf[20]; unsigned char *z; int n; unsigned int c; for(i=0; i<0x00110000; i++){ z = zBuf; WRITE_UTF8(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; c = sqlite3Utf8Read((const u8**)&z); t = i; if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; assert( c==t ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16LE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16LE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16BE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16BE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } } #endif /* SQLITE_TEST */ #endif /* SQLITE_OMIT_UTF16 */ /************** End of utf.c *************************************************/ /************** Begin file util.c ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Utility functions used throughout sqlite. ** ** This file contains functions for allocating memory, comparing ** strings, and stuff like that. ** */ /* #include "sqliteInt.h" */ /* #include <stdarg.h> */ #if HAVE_ISNAN || SQLITE_HAVE_ISNAN # include <math.h> #endif /* ** Routine needed to support the testcase() macro. */ #ifdef SQLITE_COVERAGE_TEST SQLITE_PRIVATE void sqlite3Coverage(int x){ static unsigned dummy = 0; dummy += (unsigned)x; } #endif /* ** Give a callback to the test harness that can be used to simulate faults ** in places where it is difficult or expensive to do so purely by means ** of inputs. ** ** The intent of the integer argument is to let the fault simulator know ** which of multiple sqlite3FaultSim() calls has been hit. ** ** Return whatever integer value the test callback returns, or return ** SQLITE_OK if no test callback is installed. */ #ifndef SQLITE_UNTESTABLE SQLITE_PRIVATE int sqlite3FaultSim(int iTest){ int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback; return xCallback ? xCallback(iTest) : SQLITE_OK; } #endif #ifndef SQLITE_OMIT_FLOATING_POINT /* ** Return true if the floating point value is Not a Number (NaN). ** ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. ** Otherwise, we have our own implementation that works on most systems. */ SQLITE_PRIVATE int sqlite3IsNaN(double x){ int rc; /* The value return */ #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN /* ** Systems that support the isnan() library function should probably ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have ** found that many systems do not have a working isnan() function so ** this implementation is provided as an alternative. ** ** This NaN test sometimes fails if compiled on GCC with -ffast-math. ** On the other hand, the use of -ffast-math comes with the following ** warning: ** ** This option [-ffast-math] should never be turned on by any ** -O option since it can result in incorrect output for programs ** which depend on an exact implementation of IEEE or ISO ** rules/specifications for math functions. ** ** Under MSVC, this NaN test may fail if compiled with a floating- ** point precision mode other than /fp:precise. From the MSDN ** documentation: ** ** The compiler [with /fp:precise] will properly handle comparisons ** involving NaN. For example, x != x evaluates to true if x is NaN ** ... */ #ifdef __FAST_MATH__ # error SQLite will not work correctly with the -ffast-math option of GCC. #endif volatile double y = x; volatile double z = y; rc = (y!=z); #else /* if HAVE_ISNAN */ rc = isnan(x); #endif /* HAVE_ISNAN */ testcase( rc ); return rc; } #endif /* SQLITE_OMIT_FLOATING_POINT */ /* ** Compute a string length that is limited to what can be stored in ** lower 30 bits of a 32-bit signed integer. ** ** The value returned will never be negative. Nor will it ever be greater ** than the actual length of the string. For very long strings (greater ** than 1GiB) the value returned might be less than the true string length. */ SQLITE_PRIVATE int sqlite3Strlen30(const char *z){ if( z==0 ) return 0; return 0x3fffffff & (int)strlen(z); } /* ** Return the declared type of a column. Or return zDflt if the column ** has no declared type. ** ** The column type is an extra string stored after the zero-terminator on ** the column name if and only if the COLFLAG_HASTYPE flag is set. */ SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){ if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt; return pCol->zName + strlen(pCol->zName) + 1; } /* ** Helper function for sqlite3Error() - called rarely. Broken out into ** a separate routine to avoid unnecessary register saves on entry to ** sqlite3Error(). */ static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){ if( db->pErr ) sqlite3ValueSetNull(db->pErr); sqlite3SystemError(db, err_code); } /* ** Set the current error code to err_code and clear any prior error message. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates ** that would be appropriate. */ SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){ assert( db!=0 ); db->errCode = err_code; if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code); } /* ** Load the sqlite3.iSysErrno field if that is an appropriate thing ** to do based on the SQLite error code in rc. */ SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){ if( rc==SQLITE_IOERR_NOMEM ) return; rc &= 0xff; if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){ db->iSysErrno = sqlite3OsGetLastError(db->pVfs); } } /* ** Set the most recent error code and error string for the sqlite ** handle "db". The error code is set to "err_code". ** ** If it is not NULL, string zFormat specifies the format of the ** error string in the style of the printf functions: The following ** format characters are allowed: ** ** %s Insert a string ** %z A string that should be freed after use ** %d Insert an integer ** %T Insert a token ** %S Insert the first element of a SrcList ** ** zFormat and any string tokens that follow it are assumed to be ** encoded in UTF-8. ** ** To clear the most recent error for sqlite handle "db", sqlite3Error ** should be called with err_code set to SQLITE_OK and zFormat set ** to NULL. */ SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){ assert( db!=0 ); db->errCode = err_code; sqlite3SystemError(db, err_code); if( zFormat==0 ){ sqlite3Error(db, err_code); }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){ char *z; va_list ap; va_start(ap, zFormat); z = sqlite3VMPrintf(db, zFormat, ap); va_end(ap); sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC); } } /* ** Add an error message to pParse->zErrMsg and increment pParse->nErr. ** The following formatting characters are allowed: ** ** %s Insert a string ** %z A string that should be freed after use ** %d Insert an integer ** %T Insert a token ** %S Insert the first element of a SrcList ** ** This function should be used to report any error that occurs while ** compiling an SQL statement (i.e. within sqlite3_prepare()). The ** last thing the sqlite3_prepare() function does is copy the error ** stored by this function into the database handle using sqlite3Error(). ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used ** during statement execution (sqlite3_step() etc.). */ SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ char *zMsg; va_list ap; sqlite3 *db = pParse->db; va_start(ap, zFormat); zMsg = sqlite3VMPrintf(db, zFormat, ap); va_end(ap); if( db->suppressErr ){ sqlite3DbFree(db, zMsg); }else{ pParse->nErr++; sqlite3DbFree(db, pParse->zErrMsg); pParse->zErrMsg = zMsg; pParse->rc = SQLITE_ERROR; } } /* ** Convert an SQL-style quoted string into a normal string by removing ** the quote characters. The conversion is done in-place. If the ** input does not begin with a quote character, then this routine ** is a no-op. ** ** The input string must be zero-terminated. A new zero-terminator ** is added to the dequoted string. ** ** The return value is -1 if no dequoting occurs or the length of the ** dequoted string, exclusive of the zero terminator, if dequoting does ** occur. ** ** 2002-Feb-14: This routine is extended to remove MS-Access style ** brackets from around identifiers. For example: "[a-b-c]" becomes ** "a-b-c". */ SQLITE_PRIVATE void sqlite3Dequote(char *z){ char quote; int i, j; if( z==0 ) return; quote = z[0]; if( !sqlite3Isquote(quote) ) return; if( quote=='[' ) quote = ']'; for(i=1, j=0;; i++){ assert( z[i] ); if( z[i]==quote ){ if( z[i+1]==quote ){ z[j++] = quote; i++; }else{ break; } }else{ z[j++] = z[i]; } } z[j] = 0; } /* ** Generate a Token object from a string */ SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){ p->z = z; p->n = sqlite3Strlen30(z); } /* Convenient short-hand */ #define UpperToLower sqlite3UpperToLower /* ** Some systems have stricmp(). Others have strcasecmp(). Because ** there is no consistency, we will define our own. ** ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and ** sqlite3_strnicmp() APIs allow applications and extensions to compare ** the contents of two buffers containing UTF-8 strings in a ** case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){ if( zLeft==0 ){ return zRight ? -1 : 0; }else if( zRight==0 ){ return 1; } return sqlite3StrICmp(zLeft, zRight); } SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){ unsigned char *a, *b; int c; a = (unsigned char *)zLeft; b = (unsigned char *)zRight; for(;;){ c = (int)UpperToLower[*a] - (int)UpperToLower[*b]; if( c || *a==0 ) break; a++; b++; } return c; } SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ register unsigned char *a, *b; if( zLeft==0 ){ return zRight ? -1 : 0; }else if( zRight==0 ){ return 1; } a = (unsigned char *)zLeft; b = (unsigned char *)zRight; while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; } return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b]; } /* ** The string z[] is an text representation of a real number. ** Convert this string to a double and write it into *pResult. ** ** The string z[] is length bytes in length (bytes, not characters) and ** uses the encoding enc. The string is not necessarily zero-terminated. ** ** Return TRUE if the result is a valid real number (or integer) and FALSE ** if the string is empty or contains extraneous text. Valid numbers ** are in one of these formats: ** ** [+-]digits[E[+-]digits] ** [+-]digits.[digits][E[+-]digits] ** [+-].digits[E[+-]digits] ** ** Leading and trailing whitespace is ignored for the purpose of determining ** validity. ** ** If some prefix of the input string is a valid number, this routine ** returns FALSE but it still converts the prefix and writes the result ** into *pResult. */ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ #ifndef SQLITE_OMIT_FLOATING_POINT int incr; const char *zEnd = z + length; /* sign * significand * (10 ^ (esign * exponent)) */ int sign = 1; /* sign of significand */ i64 s = 0; /* significand */ int d = 0; /* adjust exponent for shifting decimal point */ int esign = 1; /* sign of exponent */ int e = 0; /* exponent */ int eValid = 1; /* True exponent is either not used or is well-formed */ double result; int nDigits = 0; int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); *pResult = 0.0; /* Default return value, in case of an error */ if( enc==SQLITE_UTF8 ){ incr = 1; }else{ int i; incr = 2; assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); for(i=3-enc; i<length && z[i]==0; i+=2){} nonNum = i<length; zEnd = &z[i^1]; z += (enc&1); } /* skip leading spaces */ while( z<zEnd && sqlite3Isspace(*z) ) z+=incr; if( z>=zEnd ) return 0; /* get sign of significand */ if( *z=='-' ){ sign = -1; z+=incr; }else if( *z=='+' ){ z+=incr; } /* copy max significant digits to significand */ while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){ s = s*10 + (*z - '0'); z+=incr, nDigits++; } /* skip non-significant significand digits ** (increase exponent by d to shift decimal left) */ while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++; if( z>=zEnd ) goto do_atof_calc; /* if decimal point is present */ if( *z=='.' ){ z+=incr; /* copy digits from after decimal to significand ** (decrease exponent by d to shift decimal right) */ while( z<zEnd && sqlite3Isdigit(*z) ){ if( s<((LARGEST_INT64-9)/10) ){ s = s*10 + (*z - '0'); d--; } z+=incr, nDigits++; } } if( z>=zEnd ) goto do_atof_calc; /* if exponent is present */ if( *z=='e' || *z=='E' ){ z+=incr; eValid = 0; /* This branch is needed to avoid a (harmless) buffer overread. The ** special comment alerts the mutation tester that the correct answer ** is obtained even if the branch is omitted */ if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/ /* get sign of exponent */ if( *z=='-' ){ esign = -1; z+=incr; }else if( *z=='+' ){ z+=incr; } /* copy digits to exponent */ while( z<zEnd && sqlite3Isdigit(*z) ){ e = e<10000 ? (e*10 + (*z - '0')) : 10000; z+=incr; eValid = 1; } } /* skip trailing spaces */ while( z<zEnd && sqlite3Isspace(*z) ) z+=incr; do_atof_calc: /* adjust exponent by d, and update sign */ e = (e*esign) + d; if( e<0 ) { esign = -1; e *= -1; } else { esign = 1; } if( s==0 ) { /* In the IEEE 754 standard, zero is signed. */ result = sign<0 ? -(double)0 : (double)0; } else { /* Attempt to reduce exponent. ** ** Branches that are not required for the correct answer but which only ** help to obtain the correct answer faster are marked with special ** comments, as a hint to the mutation tester. */ while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/ if( esign>0 ){ if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/ s *= 10; }else{ if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/ s /= 10; } e--; } /* adjust the sign of significand */ s = sign<0 ? -s : s; if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/ result = (double)s; }else{ LONGDOUBLE_TYPE scale = 1.0; /* attempt to handle extremely small/large numbers better */ if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/ if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/ while( e%308 ) { scale *= 1.0e+1; e -= 1; } if( esign<0 ){ result = s / scale; result /= 1.0e+308; }else{ result = s * scale; result *= 1.0e+308; } }else{ assert( e>=342 ); if( esign<0 ){ result = 0.0*s; }else{ result = 1e308*1e308*s; /* Infinity */ } } }else{ /* 1.0e+22 is the largest power of 10 than can be ** represented exactly. */ while( e%22 ) { scale *= 1.0e+1; e -= 1; } while( e>0 ) { scale *= 1.0e+22; e -= 22; } if( esign<0 ){ result = s / scale; }else{ result = s * scale; } } } } /* store the result */ *pResult = result; /* return true if number and no extra non-whitespace chracters after */ return z==zEnd && nDigits>0 && eValid && nonNum==0; #else return !sqlite3Atoi64(z, pResult, length, enc); #endif /* SQLITE_OMIT_FLOATING_POINT */ } /* ** Compare the 19-character string zNum against the text representation ** value 2^63: 9223372036854775808. Return negative, zero, or positive ** if zNum is less than, equal to, or greater than the string. ** Note that zNum must contain exactly 19 characters. ** ** Unlike memcmp() this routine is guaranteed to return the difference ** in the values of the last digit if the only difference is in the ** last digit. So, for example, ** ** compare2pow63("9223372036854775800", 1) ** ** will return -8. */ static int compare2pow63(const char *zNum, int incr){ int c = 0; int i; /* 012345678901234567 */ const char *pow63 = "922337203685477580"; for(i=0; c==0 && i<18; i++){ c = (zNum[i*incr]-pow63[i])*10; } if( c==0 ){ c = zNum[18*incr] - '8'; testcase( c==(-1) ); testcase( c==0 ); testcase( c==(+1) ); } return c; } /* ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This ** routine does *not* accept hexadecimal notation. ** ** If the zNum value is representable as a 64-bit twos-complement ** integer, then write that value into *pNum and return 0. ** ** If zNum is exactly 9223372036854775808, return 2. This special ** case is broken out because while 9223372036854775808 cannot be a ** signed 64-bit integer, its negative -9223372036854775808 can be. ** ** If zNum is too big for a 64-bit integer and is not ** 9223372036854775808 or if zNum contains any non-numeric text, ** then return 1. ** ** length is the number of bytes in the string (bytes, not characters). ** The string is not necessarily zero-terminated. The encoding is ** given by enc. */ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){ int incr; u64 u = 0; int neg = 0; /* assume positive */ int i; int c = 0; int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ const char *zStart; const char *zEnd = zNum + length; assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); if( enc==SQLITE_UTF8 ){ incr = 1; }else{ incr = 2; assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); for(i=3-enc; i<length && zNum[i]==0; i+=2){} nonNum = i<length; zEnd = &zNum[i^1]; zNum += (enc&1); } while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr; if( zNum<zEnd ){ if( *zNum=='-' ){ neg = 1; zNum+=incr; }else if( *zNum=='+' ){ zNum+=incr; } } zStart = zNum; while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */ for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){ u = u*10 + c - '0'; } if( u>LARGEST_INT64 ){ *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64; }else if( neg ){ *pNum = -(i64)u; }else{ *pNum = (i64)u; } testcase( i==18 ); testcase( i==19 ); testcase( i==20 ); if( &zNum[i]<zEnd /* Extra bytes at the end */ || (i==0 && zStart==zNum) /* No digits */ || i>19*incr /* Too many digits */ || nonNum /* UTF16 with high-order bytes non-zero */ ){ /* zNum is empty or contains non-numeric text or is longer ** than 19 digits (thus guaranteeing that it is too large) */ return 1; }else if( i<19*incr ){ /* Less than 19 digits, so we know that it fits in 64 bits */ assert( u<=LARGEST_INT64 ); return 0; }else{ /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ c = compare2pow63(zNum, incr); if( c<0 ){ /* zNum is less than 9223372036854775808 so it fits */ assert( u<=LARGEST_INT64 ); return 0; }else if( c>0 ){ /* zNum is greater than 9223372036854775808 so it overflows */ return 1; }else{ /* zNum is exactly 9223372036854775808. Fits if negative. The ** special case 2 overflow if positive */ assert( u-1==LARGEST_INT64 ); return neg ? 0 : 2; } } } /* ** Transform a UTF-8 integer literal, in either decimal or hexadecimal, ** into a 64-bit signed integer. This routine accepts hexadecimal literals, ** whereas sqlite3Atoi64() does not. ** ** Returns: ** ** 0 Successful transformation. Fits in a 64-bit signed integer. ** 1 Integer too large for a 64-bit signed integer or is malformed ** 2 Special case of 9223372036854775808 */ SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){ #ifndef SQLITE_OMIT_HEX_INTEGER if( z[0]=='0' && (z[1]=='x' || z[1]=='X') ){ u64 u = 0; int i, k; for(i=2; z[i]=='0'; i++){} for(k=i; sqlite3Isxdigit(z[k]); k++){ u = u*16 + sqlite3HexToInt(z[k]); } memcpy(pOut, &u, 8); return (z[k]==0 && k-i<=16) ? 0 : 1; }else #endif /* SQLITE_OMIT_HEX_INTEGER */ { return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8); } } /* ** If zNum represents an integer that will fit in 32-bits, then set ** *pValue to that integer and return true. Otherwise return false. ** ** This routine accepts both decimal and hexadecimal notation for integers. ** ** Any non-numeric characters that following zNum are ignored. ** This is different from sqlite3Atoi64() which requires the ** input number to be zero-terminated. */ SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ sqlite_int64 v = 0; int i, c; int neg = 0; if( zNum[0]=='-' ){ neg = 1; zNum++; }else if( zNum[0]=='+' ){ zNum++; } #ifndef SQLITE_OMIT_HEX_INTEGER else if( zNum[0]=='0' && (zNum[1]=='x' || zNum[1]=='X') && sqlite3Isxdigit(zNum[2]) ){ u32 u = 0; zNum += 2; while( zNum[0]=='0' ) zNum++; for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){ u = u*16 + sqlite3HexToInt(zNum[i]); } if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){ memcpy(pValue, &u, 4); return 1; }else{ return 0; } } #endif while( zNum[0]=='0' ) zNum++; for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){ v = v*10 + c; } /* The longest decimal representation of a 32 bit integer is 10 digits: ** ** 1234567890 ** 2^31 -> 2147483648 */ testcase( i==10 ); if( i>10 ){ return 0; } testcase( v-neg==2147483647 ); if( v-neg>2147483647 ){ return 0; } if( neg ){ v = -v; } *pValue = (int)v; return 1; } /* ** Return a 32-bit integer value extracted from a string. If the ** string is not an integer, just return 0. */ SQLITE_PRIVATE int sqlite3Atoi(const char *z){ int x = 0; if( z ) sqlite3GetInt32(z, &x); return x; } /* ** The variable-length integer encoding is as follows: ** ** KEY: ** A = 0xxxxxxx 7 bits of data and one flag bit ** B = 1xxxxxxx 7 bits of data and one flag bit ** C = xxxxxxxx 8 bits of data ** ** 7 bits - A ** 14 bits - BA ** 21 bits - BBA ** 28 bits - BBBA ** 35 bits - BBBBA ** 42 bits - BBBBBA ** 49 bits - BBBBBBA ** 56 bits - BBBBBBBA ** 64 bits - BBBBBBBBC */ /* ** Write a 64-bit variable-length integer to memory starting at p[0]. ** The length of data write will be between 1 and 9 bytes. The number ** of bytes written is returned. ** ** A variable-length integer consists of the lower 7 bits of each byte ** for all bytes that have the 8th bit set and one byte with the 8th ** bit clear. Except, if we get to the 9th byte, it stores the full ** 8 bits and is the last byte. */ static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){ int i, j, n; u8 buf[10]; if( v & (((u64)0xff000000)<<32) ){ p[8] = (u8)v; v >>= 8; for(i=7; i>=0; i--){ p[i] = (u8)((v & 0x7f) | 0x80); v >>= 7; } return 9; } n = 0; do{ buf[n++] = (u8)((v & 0x7f) | 0x80); v >>= 7; }while( v!=0 ); buf[0] &= 0x7f; assert( n<=9 ); for(i=0, j=n-1; j>=0; j--, i++){ p[i] = buf[j]; } return n; } SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){ if( v<=0x7f ){ p[0] = v&0x7f; return 1; } if( v<=0x3fff ){ p[0] = ((v>>7)&0x7f)|0x80; p[1] = v&0x7f; return 2; } return putVarint64(p,v); } /* ** Bitmasks used by sqlite3GetVarint(). These precomputed constants ** are defined here rather than simply putting the constant expressions ** inline in order to work around bugs in the RVT compiler. ** ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f ** ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 */ #define SLOT_2_0 0x001fc07f #define SLOT_4_2_0 0xf01fc07f /* ** Read a 64-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read. The value is stored in *v. */ SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ u32 a,b,s; a = *p; /* a: p0 (unmasked) */ if (!(a&0x80)) { *v = a; return 1; } p++; b = *p; /* b: p1 (unmasked) */ if (!(b&0x80)) { a &= 0x7f; a = a<<7; a |= b; *v = a; return 2; } /* Verify that constants are precomputed correctly */ assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) ); assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) ); p++; a = a<<14; a |= *p; /* a: p0<<14 | p2 (unmasked) */ if (!(a&0x80)) { a &= SLOT_2_0; b &= 0x7f; b = b<<7; a |= b; *v = a; return 3; } /* CSE1 from below */ a &= SLOT_2_0; p++; b = b<<14; b |= *p; /* b: p1<<14 | p3 (unmasked) */ if (!(b&0x80)) { b &= SLOT_2_0; /* moved CSE1 up */ /* a &= (0x7f<<14)|(0x7f); */ a = a<<7; a |= b; *v = a; return 4; } /* a: p0<<14 | p2 (masked) */ /* b: p1<<14 | p3 (unmasked) */ /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ /* moved CSE1 up */ /* a &= (0x7f<<14)|(0x7f); */ b &= SLOT_2_0; s = a; /* s: p0<<14 | p2 (masked) */ p++; a = a<<14; a |= *p; /* a: p0<<28 | p2<<14 | p4 (unmasked) */ if (!(a&0x80)) { /* we can skip these cause they were (effectively) done above ** while calculating s */ /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ /* b &= (0x7f<<14)|(0x7f); */ b = b<<7; a |= b; s = s>>18; *v = ((u64)s)<<32 | a; return 5; } /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ s = s<<7; s |= b; /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ p++; b = b<<14; b |= *p; /* b: p1<<28 | p3<<14 | p5 (unmasked) */ if (!(b&0x80)) { /* we can skip this cause it was (effectively) done above in calc'ing s */ /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ a &= SLOT_2_0; a = a<<7; a |= b; s = s>>18; *v = ((u64)s)<<32 | a; return 6; } p++; a = a<<14; a |= *p; /* a: p2<<28 | p4<<14 | p6 (unmasked) */ if (!(a&0x80)) { a &= SLOT_4_2_0; b &= SLOT_2_0; b = b<<7; a |= b; s = s>>11; *v = ((u64)s)<<32 | a; return 7; } /* CSE2 from below */ a &= SLOT_2_0; p++; b = b<<14; b |= *p; /* b: p3<<28 | p5<<14 | p7 (unmasked) */ if (!(b&0x80)) { b &= SLOT_4_2_0; /* moved CSE2 up */ /* a &= (0x7f<<14)|(0x7f); */ a = a<<7; a |= b; s = s>>4; *v = ((u64)s)<<32 | a; return 8; } p++; a = a<<15; a |= *p; /* a: p4<<29 | p6<<15 | p8 (unmasked) */ /* moved CSE2 up */ /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ b &= SLOT_2_0; b = b<<8; a |= b; s = s<<4; b = p[-4]; b &= 0x7f; b = b>>3; s |= b; *v = ((u64)s)<<32 | a; return 9; } /* ** Read a 32-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read. The value is stored in *v. ** ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned ** integer, then set *v to 0xffffffff. ** ** A MACRO version, getVarint32, is provided which inlines the ** single-byte case. All code should use the MACRO version as ** this function assumes the single-byte case has already been handled. */ SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ u32 a,b; /* The 1-byte case. Overwhelmingly the most common. Handled inline ** by the getVarin32() macro */ a = *p; /* a: p0 (unmasked) */ #ifndef getVarint32 if (!(a&0x80)) { /* Values between 0 and 127 */ *v = a; return 1; } #endif /* The 2-byte case */ p++; b = *p; /* b: p1 (unmasked) */ if (!(b&0x80)) { /* Values between 128 and 16383 */ a &= 0x7f; a = a<<7; *v = a | b; return 2; } /* The 3-byte case */ p++; a = a<<14; a |= *p; /* a: p0<<14 | p2 (unmasked) */ if (!(a&0x80)) { /* Values between 16384 and 2097151 */ a &= (0x7f<<14)|(0x7f); b &= 0x7f; b = b<<7; *v = a | b; return 3; } /* A 32-bit varint is used to store size information in btrees. ** Objects are rarely larger than 2MiB limit of a 3-byte varint. ** A 3-byte varint is sufficient, for example, to record the size ** of a 1048569-byte BLOB or string. ** ** We only unroll the first 1-, 2-, and 3- byte cases. The very ** rare larger cases can be handled by the slower 64-bit varint ** routine. */ #if 1 { u64 v64; u8 n; p -= 2; n = sqlite3GetVarint(p, &v64); assert( n>3 && n<=9 ); if( (v64 & SQLITE_MAX_U32)!=v64 ){ *v = 0xffffffff; }else{ *v = (u32)v64; } return n; } #else /* For following code (kept for historical record only) shows an ** unrolling for the 3- and 4-byte varint cases. This code is ** slightly faster, but it is also larger and much harder to test. */ p++; b = b<<14; b |= *p; /* b: p1<<14 | p3 (unmasked) */ if (!(b&0x80)) { /* Values between 2097152 and 268435455 */ b &= (0x7f<<14)|(0x7f); a &= (0x7f<<14)|(0x7f); a = a<<7; *v = a | b; return 4; } p++; a = a<<14; a |= *p; /* a: p0<<28 | p2<<14 | p4 (unmasked) */ if (!(a&0x80)) { /* Values between 268435456 and 34359738367 */ a &= SLOT_4_2_0; b &= SLOT_4_2_0; b = b<<7; *v = a | b; return 5; } /* We can only reach this point when reading a corrupt database ** file. In that case we are not in any hurry. Use the (relatively ** slow) general-purpose sqlite3GetVarint() routine to extract the ** value. */ { u64 v64; u8 n; p -= 4; n = sqlite3GetVarint(p, &v64); assert( n>5 && n<=9 ); *v = (u32)v64; return n; } #endif } /* ** Return the number of bytes that will be needed to store the given ** 64-bit integer. */ SQLITE_PRIVATE int sqlite3VarintLen(u64 v){ int i; for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); } return i; } /* ** Read or write a four-byte big-endian integer value. */ SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ #if SQLITE_BYTEORDER==4321 u32 x; memcpy(&x,p,4); return x; #elif SQLITE_BYTEORDER==1234 && (GCC_VERSION>=4003000 || CLANG_VERSION>=3000000) u32 x; memcpy(&x,p,4); return __builtin_bswap32(x); #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u32 x; memcpy(&x,p,4); return _byteswap_ulong(x); #else testcase( p[0]&0x80 ); return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]; #endif } SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ #if SQLITE_BYTEORDER==4321 memcpy(p,&v,4); #elif SQLITE_BYTEORDER==1234 && (GCC_VERSION>=4003000 || CLANG_VERSION>=3000000) u32 x = __builtin_bswap32(v); memcpy(p,&x,4); #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u32 x = _byteswap_ulong(v); memcpy(p,&x,4); #else p[0] = (u8)(v>>24); p[1] = (u8)(v>>16); p[2] = (u8)(v>>8); p[3] = (u8)v; #endif } /* ** Translate a single byte of Hex into an integer. ** This routine only works if h really is a valid hexadecimal ** character: 0..9a..fA..F */ SQLITE_PRIVATE u8 sqlite3HexToInt(int h){ assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); #ifdef SQLITE_ASCII h += 9*(1&(h>>6)); #endif #ifdef SQLITE_EBCDIC h += 9*(1&~(h>>4)); #endif return (u8)(h & 0xf); } #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) /* ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary ** value. Return a pointer to its binary value. Space to hold the ** binary value has been obtained from malloc and must be freed by ** the calling routine. */ SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ char *zBlob; int i; zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1); n--; if( zBlob ){ for(i=0; i<n; i+=2){ zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]); } zBlob[i/2] = 0; } return zBlob; } #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */ /* ** Log an error that is an API call on a connection pointer that should ** not have been used. The "type" of connection pointer is given as the ** argument. The zType is a word like "NULL" or "closed" or "invalid". */ static void logBadConnection(const char *zType){ sqlite3_log(SQLITE_MISUSE, "API call with %s database connection pointer", zType ); } /* ** Check to make sure we have a valid db pointer. This test is not ** foolproof but it does provide some measure of protection against ** misuse of the interface such as passing in db pointers that are ** NULL or which have been previously closed. If this routine returns ** 1 it means that the db pointer is valid and 0 if it should not be ** dereferenced for any reason. The calling function should invoke ** SQLITE_MISUSE immediately. ** ** sqlite3SafetyCheckOk() requires that the db pointer be valid for ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to ** open properly and is not fit for general use but which can be ** used as an argument to sqlite3_errmsg() or sqlite3_close(). */ SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){ u32 magic; if( db==0 ){ logBadConnection("NULL"); return 0; } magic = db->magic; if( magic!=SQLITE_MAGIC_OPEN ){ if( sqlite3SafetyCheckSickOrOk(db) ){ testcase( sqlite3GlobalConfig.xLog!=0 ); logBadConnection("unopened"); } return 0; }else{ return 1; } } SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ u32 magic; magic = db->magic; if( magic!=SQLITE_MAGIC_SICK && magic!=SQLITE_MAGIC_OPEN && magic!=SQLITE_MAGIC_BUSY ){ testcase( sqlite3GlobalConfig.xLog!=0 ); logBadConnection("invalid"); return 0; }else{ return 1; } } /* ** Attempt to add, substract, or multiply the 64-bit signed value iB against ** the other 64-bit signed integer at *pA and store the result in *pA. ** Return 0 on success. Or if the operation would have resulted in an ** overflow, leave *pA unchanged and return 1. */ SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){ #if GCC_VERSION>=5004000 || CLANG_VERSION>=4000000 return __builtin_add_overflow(*pA, iB, pA); #else i64 iA = *pA; testcase( iA==0 ); testcase( iA==1 ); testcase( iB==-1 ); testcase( iB==0 ); if( iB>=0 ){ testcase( iA>0 && LARGEST_INT64 - iA == iB ); testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 ); if( iA>0 && LARGEST_INT64 - iA < iB ) return 1; }else{ testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 ); testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 ); if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1; } *pA += iB; return 0; #endif } SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){ #if GCC_VERSION>=5004000 || CLANG_VERSION>=4000000 return __builtin_sub_overflow(*pA, iB, pA); #else testcase( iB==SMALLEST_INT64+1 ); if( iB==SMALLEST_INT64 ){ testcase( (*pA)==(-1) ); testcase( (*pA)==0 ); if( (*pA)>=0 ) return 1; *pA -= iB; return 0; }else{ return sqlite3AddInt64(pA, -iB); } #endif } SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){ #if GCC_VERSION>=5004000 || CLANG_VERSION>=4000000 return __builtin_mul_overflow(*pA, iB, pA); #else i64 iA = *pA; if( iB>0 ){ if( iA>LARGEST_INT64/iB ) return 1; if( iA<SMALLEST_INT64/iB ) return 1; }else if( iB<0 ){ if( iA>0 ){ if( iB<SMALLEST_INT64/iA ) return 1; }else if( iA<0 ){ if( iB==SMALLEST_INT64 ) return 1; if( iA==SMALLEST_INT64 ) return 1; if( -iA>LARGEST_INT64/-iB ) return 1; } } *pA = iA*iB; return 0; #endif } /* ** Compute the absolute value of a 32-bit signed integer, of possible. Or ** if the integer has a value of -2147483648, return +2147483647 */ SQLITE_PRIVATE int sqlite3AbsInt32(int x){ if( x>=0 ) return x; if( x==(int)0x80000000 ) return 0x7fffffff; return -x; } #ifdef SQLITE_ENABLE_8_3_NAMES /* ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than ** three characters, then shorten the suffix on z[] to be the last three ** characters of the original suffix. ** ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always ** do the suffix shortening regardless of URI parameter. ** ** Examples: ** ** test.db-journal => test.nal ** test.db-wal => test.wal ** test.db-shm => test.shm ** test.db-mj7f3319fa => test.9fa */ SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){ #if SQLITE_ENABLE_8_3_NAMES<2 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) ) #endif { int i, sz; sz = sqlite3Strlen30(z); for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4); } } #endif /* ** Find (an approximate) sum of two LogEst values. This computation is ** not a simple "+" operator because LogEst is stored as a logarithmic ** value. ** */ SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){ static const unsigned char x[] = { 10, 10, /* 0,1 */ 9, 9, /* 2,3 */ 8, 8, /* 4,5 */ 7, 7, 7, /* 6,7,8 */ 6, 6, 6, /* 9,10,11 */ 5, 5, 5, /* 12-14 */ 4, 4, 4, 4, /* 15-18 */ 3, 3, 3, 3, 3, 3, /* 19-24 */ 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ }; if( a>=b ){ if( a>b+49 ) return a; if( a>b+31 ) return a+1; return a+x[a-b]; }else{ if( b>a+49 ) return b; if( b>a+31 ) return b+1; return b+x[b-a]; } } /* ** Convert an integer into a LogEst. In other words, compute an ** approximation for 10*log2(x). */ SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){ static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; LogEst y = 40; if( x<8 ){ if( x<2 ) return 0; while( x<8 ){ y -= 10; x <<= 1; } }else{ while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/ while( x>15 ){ y += 10; x >>= 1; } } return a[x&7] + y - 10; } #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Convert a double into a LogEst ** In other words, compute an approximation for 10*log2(x). */ SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){ u64 a; LogEst e; assert( sizeof(x)==8 && sizeof(a)==8 ); if( x<=1 ) return 0; if( x<=2000000000 ) return sqlite3LogEst((u64)x); memcpy(&a, &x, 8); e = (a>>52) - 1022; return e*10; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) /* ** Convert a LogEst into an integer. ** ** Note that this routine is only used when one or more of various ** non-standard compile-time options is enabled. */ SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){ u64 n; n = x%10; x /= 10; if( n>=5 ) n -= 2; else if( n>=1 ) n -= 1; #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) if( x>60 ) return (u64)LARGEST_INT64; #else /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input ** possible to this routine is 310, resulting in a maximum x of 31 */ assert( x<=60 ); #endif return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x); } #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */ /* ** Add a new name/number pair to a VList. This might require that the ** VList object be reallocated, so return the new VList. If an OOM ** error occurs, the original VList returned and the ** db->mallocFailed flag is set. ** ** A VList is really just an array of integers. To destroy a VList, ** simply pass it to sqlite3DbFree(). ** ** The first integer is the number of integers allocated for the whole ** VList. The second integer is the number of integers actually used. ** Each name/number pair is encoded by subsequent groups of 3 or more ** integers. ** ** Each name/number pair starts with two integers which are the numeric ** value for the pair and the size of the name/number pair, respectively. ** The text name overlays one or more following integers. The text name ** is always zero-terminated. ** ** Conceptually: ** ** struct VList { ** int nAlloc; // Number of allocated slots ** int nUsed; // Number of used slots ** struct VListEntry { ** int iValue; // Value for this entry ** int nSlot; // Slots used by this entry ** // ... variable name goes here ** } a[0]; ** } ** ** During code generation, pointers to the variable names within the ** VList are taken. When that happens, nAlloc is set to zero as an ** indication that the VList may never again be enlarged, since the ** accompanying realloc() would invalidate the pointers. */ SQLITE_PRIVATE VList *sqlite3VListAdd( sqlite3 *db, /* The database connection used for malloc() */ VList *pIn, /* The input VList. Might be NULL */ const char *zName, /* Name of symbol to add */ int nName, /* Bytes of text in zName */ int iVal /* Value to associate with zName */ ){ int nInt; /* number of sizeof(int) objects needed for zName */ char *z; /* Pointer to where zName will be stored */ int i; /* Index in pIn[] where zName is stored */ nInt = nName/4 + 3; assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */ if( pIn==0 || pIn[1]+nInt > pIn[0] ){ /* Enlarge the allocation */ int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt; VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int)); if( pOut==0 ) return pIn; if( pIn==0 ) pOut[1] = 2; pIn = pOut; pIn[0] = nAlloc; } i = pIn[1]; pIn[i] = iVal; pIn[i+1] = nInt; z = (char*)&pIn[i+2]; pIn[1] = i+nInt; assert( pIn[1]<=pIn[0] ); memcpy(z, zName, nName); z[nName] = 0; return pIn; } /* ** Return a pointer to the name of a variable in the given VList that ** has the value iVal. Or return a NULL if there is no such variable in ** the list */ SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){ int i, mx; if( pIn==0 ) return 0; mx = pIn[1]; i = 2; do{ if( pIn[i]==iVal ) return (char*)&pIn[i+2]; i += pIn[i+1]; }while( i<mx ); return 0; } /* ** Return the number of the variable named zName, if it is in VList. ** or return 0 if there is no such variable. */ SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){ int i, mx; if( pIn==0 ) return 0; mx = pIn[1]; i = 2; do{ const char *z = (const char*)&pIn[i+2]; if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i]; i += pIn[i+1]; }while( i<mx ); return 0; } /************** End of util.c ************************************************/ /************** Begin file hash.c ********************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of generic hash-tables ** used in SQLite. */ /* #include "sqliteInt.h" */ /* #include <assert.h> */ /* Turn bulk memory into a hash table object by initializing the ** fields of the Hash structure. ** ** "pNew" is a pointer to the hash table that is to be initialized. */ SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){ assert( pNew!=0 ); pNew->first = 0; pNew->count = 0; pNew->htsize = 0; pNew->ht = 0; } /* Remove all entries from a hash table. Reclaim all memory. ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){ HashElem *elem; /* For looping over all elements of the table */ assert( pH!=0 ); elem = pH->first; pH->first = 0; sqlite3_free(pH->ht); pH->ht = 0; pH->htsize = 0; while( elem ){ HashElem *next_elem = elem->next; sqlite3_free(elem); elem = next_elem; } pH->count = 0; } /* ** The hashing function. */ static unsigned int strHash(const char *z){ unsigned int h = 0; unsigned char c; while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/ /* Knuth multiplicative hashing. (Sorting & Searching, p. 510). ** 0x9e3779b1 is 2654435761 which is the closest prime number to ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */ h += sqlite3UpperToLower[c]; h *= 0x9e3779b1; } return h; } /* Link pNew element into the hash table pH. If pEntry!=0 then also ** insert pNew into the pEntry hash bucket. */ static void insertElement( Hash *pH, /* The complete hash table */ struct _ht *pEntry, /* The entry into which pNew is inserted */ HashElem *pNew /* The element to be inserted */ ){ HashElem *pHead; /* First element already in pEntry */ if( pEntry ){ pHead = pEntry->count ? pEntry->chain : 0; pEntry->count++; pEntry->chain = pNew; }else{ pHead = 0; } if( pHead ){ pNew->next = pHead; pNew->prev = pHead->prev; if( pHead->prev ){ pHead->prev->next = pNew; } else { pH->first = pNew; } pHead->prev = pNew; }else{ pNew->next = pH->first; if( pH->first ){ pH->first->prev = pNew; } pNew->prev = 0; pH->first = pNew; } } /* Resize the hash table so that it cantains "new_size" buckets. ** ** The hash table might fail to resize if sqlite3_malloc() fails or ** if the new size is the same as the prior size. ** Return TRUE if the resize occurs and false if not. */ static int rehash(Hash *pH, unsigned int new_size){ struct _ht *new_ht; /* The new hash table */ HashElem *elem, *next_elem; /* For looping over existing elements */ #if SQLITE_MALLOC_SOFT_LIMIT>0 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){ new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht); } if( new_size==pH->htsize ) return 0; #endif /* The inability to allocates space for a larger hash table is ** a performance hit but it is not a fatal error. So mark the ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero() ** only zeroes the requested number of bytes whereas this module will ** use the actual amount of space allocated for the hash table (which ** may be larger than the requested amount). */ sqlite3BeginBenignMalloc(); new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) ); sqlite3EndBenignMalloc(); if( new_ht==0 ) return 0; sqlite3_free(pH->ht); pH->ht = new_ht; pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); memset(new_ht, 0, new_size*sizeof(struct _ht)); for(elem=pH->first, pH->first=0; elem; elem = next_elem){ unsigned int h = strHash(elem->pKey) % new_size; next_elem = elem->next; insertElement(pH, &new_ht[h], elem); } return 1; } /* This function (for internal use only) locates an element in an ** hash table that matches the given key. The hash for this key is ** also computed and returned in the *pH parameter. */ static HashElem *findElementWithHash( const Hash *pH, /* The pH to be searched */ const char *pKey, /* The key we are searching for */ unsigned int *pHash /* Write the hash value here */ ){ HashElem *elem; /* Used to loop thru the element list */ int count; /* Number of elements left to test */ unsigned int h; /* The computed hash */ if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/ struct _ht *pEntry; h = strHash(pKey) % pH->htsize; pEntry = &pH->ht[h]; elem = pEntry->chain; count = pEntry->count; }else{ h = 0; elem = pH->first; count = pH->count; } *pHash = h; while( count-- ){ assert( elem!=0 ); if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ return elem; } elem = elem->next; } return 0; } /* Remove a single entry from the hash table given a pointer to that ** element and a hash on the element's key. */ static void removeElementGivenHash( Hash *pH, /* The pH containing "elem" */ HashElem* elem, /* The element to be removed from the pH */ unsigned int h /* Hash value for the element */ ){ struct _ht *pEntry; if( elem->prev ){ elem->prev->next = elem->next; }else{ pH->first = elem->next; } if( elem->next ){ elem->next->prev = elem->prev; } if( pH->ht ){ pEntry = &pH->ht[h]; if( pEntry->chain==elem ){ pEntry->chain = elem->next; } pEntry->count--; assert( pEntry->count>=0 ); } sqlite3_free( elem ); pH->count--; if( pH->count==0 ){ assert( pH->first==0 ); assert( pH->count==0 ); sqlite3HashClear(pH); } } /* Attempt to locate an element of the hash table pH with a key ** that matches pKey. Return the data for this element if it is ** found, or NULL if there is no match. */ SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){ HashElem *elem; /* The element that matches key */ unsigned int h; /* A hash on key */ assert( pH!=0 ); assert( pKey!=0 ); elem = findElementWithHash(pH, pKey, &h); return elem ? elem->data : 0; } /* Insert an element into the hash table pH. The key is pKey ** and the data is "data". ** ** If no element exists with a matching key, then a new ** element is created and NULL is returned. ** ** If another element already exists with the same key, then the ** new data replaces the old data and the old data is returned. ** The key is not copied in this instance. If a malloc fails, then ** the new data is returned and the hash table is unchanged. ** ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ unsigned int h; /* the hash of the key modulo hash table size */ HashElem *elem; /* Used to loop thru the element list */ HashElem *new_elem; /* New element added to the pH */ assert( pH!=0 ); assert( pKey!=0 ); elem = findElementWithHash(pH,pKey,&h); if( elem ){ void *old_data = elem->data; if( data==0 ){ removeElementGivenHash(pH,elem,h); }else{ elem->data = data; elem->pKey = pKey; } return old_data; } if( data==0 ) return 0; new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) ); if( new_elem==0 ) return data; new_elem->pKey = pKey; new_elem->data = data; pH->count++; if( pH->count>=10 && pH->count > 2*pH->htsize ){ if( rehash(pH, pH->count*2) ){ assert( pH->htsize>0 ); h = strHash(pKey) % pH->htsize; } } insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem); return 0; } /************** End of hash.c ************************************************/ /************** Begin file opcodes.c *****************************************/ /* Automatically generated. Do not edit */ /* See the tool/mkopcodec.tcl script for details. */ #if !defined(SQLITE_OMIT_EXPLAIN) \ || defined(VDBE_PROFILE) \ || defined(SQLITE_DEBUG) #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG) # define OpHelp(X) "\0" X #else # define OpHelp(X) #endif SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ static const char *const azName[] = { /* 0 */ "Savepoint" OpHelp(""), /* 1 */ "AutoCommit" OpHelp(""), /* 2 */ "Transaction" OpHelp(""), /* 3 */ "SorterNext" OpHelp(""), /* 4 */ "PrevIfOpen" OpHelp(""), /* 5 */ "NextIfOpen" OpHelp(""), /* 6 */ "Prev" OpHelp(""), /* 7 */ "Next" OpHelp(""), /* 8 */ "Checkpoint" OpHelp(""), /* 9 */ "JournalMode" OpHelp(""), /* 10 */ "Vacuum" OpHelp(""), /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"), /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"), /* 13 */ "Goto" OpHelp(""), /* 14 */ "Gosub" OpHelp(""), /* 15 */ "InitCoroutine" OpHelp(""), /* 16 */ "Yield" OpHelp(""), /* 17 */ "MustBeInt" OpHelp(""), /* 18 */ "Jump" OpHelp(""), /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"), /* 20 */ "Once" OpHelp(""), /* 21 */ "If" OpHelp(""), /* 22 */ "IfNot" OpHelp(""), /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"), /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"), /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"), /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"), /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"), /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"), /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"), /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"), /* 31 */ "Found" OpHelp("key=r[P3@P4]"), /* 32 */ "SeekRowid" OpHelp("intkey=r[P3]"), /* 33 */ "NotExists" OpHelp("intkey=r[P3]"), /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"), /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"), /* 36 */ "Ne" OpHelp("IF r[P3]!=r[P1]"), /* 37 */ "Eq" OpHelp("IF r[P3]==r[P1]"), /* 38 */ "Gt" OpHelp("IF r[P3]>r[P1]"), /* 39 */ "Le" OpHelp("IF r[P3]<=r[P1]"), /* 40 */ "Lt" OpHelp("IF r[P3]<r[P1]"), /* 41 */ "Ge" OpHelp("IF r[P3]>=r[P1]"), /* 42 */ "ElseNotEq" OpHelp(""), /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"), /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"), /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"), /* 46 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"), /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"), /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"), /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"), /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"), /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"), /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"), /* 53 */ "Last" OpHelp(""), /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"), /* 55 */ "SorterSort" OpHelp(""), /* 56 */ "Sort" OpHelp(""), /* 57 */ "Rewind" OpHelp(""), /* 58 */ "IdxLE" OpHelp("key=r[P3@P4]"), /* 59 */ "IdxGT" OpHelp("key=r[P3@P4]"), /* 60 */ "IdxLT" OpHelp("key=r[P3@P4]"), /* 61 */ "IdxGE" OpHelp("key=r[P3@P4]"), /* 62 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"), /* 63 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"), /* 64 */ "Program" OpHelp(""), /* 65 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"), /* 66 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), /* 67 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"), /* 68 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), /* 69 */ "IncrVacuum" OpHelp(""), /* 70 */ "VNext" OpHelp(""), /* 71 */ "Init" OpHelp("Start at P2"), /* 72 */ "Return" OpHelp(""), /* 73 */ "EndCoroutine" OpHelp(""), /* 74 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), /* 75 */ "Halt" OpHelp(""), /* 76 */ "Integer" OpHelp("r[P2]=P1"), /* 77 */ "Int64" OpHelp("r[P2]=P4"), /* 78 */ "String" OpHelp("r[P2]='P4' (len=P1)"), /* 79 */ "Null" OpHelp("r[P2..P3]=NULL"), /* 80 */ "SoftNull" OpHelp("r[P1]=NULL"), /* 81 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), /* 82 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"), /* 83 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), /* 84 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), /* 85 */ "SCopy" OpHelp("r[P2]=r[P1]"), /* 86 */ "IntCopy" OpHelp("r[P2]=r[P1]"), /* 87 */ "ResultRow" OpHelp("output=r[P1@P2]"), /* 88 */ "CollSeq" OpHelp(""), /* 89 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"), /* 90 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"), /* 91 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), /* 92 */ "RealAffinity" OpHelp(""), /* 93 */ "Cast" OpHelp("affinity(r[P1])"), /* 94 */ "Permutation" OpHelp(""), /* 95 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), /* 96 */ "Column" OpHelp("r[P3]=PX"), /* 97 */ "String8" OpHelp("r[P2]='P4'"), /* 98 */ "Affinity" OpHelp("affinity(r[P1@P2])"), /* 99 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), /* 100 */ "Count" OpHelp("r[P2]=count()"), /* 101 */ "ReadCookie" OpHelp(""), /* 102 */ "SetCookie" OpHelp(""), /* 103 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), /* 104 */ "OpenRead" OpHelp("root=P2 iDb=P3"), /* 105 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), /* 106 */ "OpenAutoindex" OpHelp("nColumn=P2"), /* 107 */ "OpenEphemeral" OpHelp("nColumn=P2"), /* 108 */ "SorterOpen" OpHelp(""), /* 109 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), /* 110 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), /* 111 */ "Close" OpHelp(""), /* 112 */ "ColumnsUsed" OpHelp(""), /* 113 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), /* 114 */ "NewRowid" OpHelp("r[P2]=rowid"), /* 115 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), /* 116 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"), /* 117 */ "Delete" OpHelp(""), /* 118 */ "ResetCount" OpHelp(""), /* 119 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), /* 120 */ "SorterData" OpHelp("r[P2]=data"), /* 121 */ "RowData" OpHelp("r[P2]=data"), /* 122 */ "Rowid" OpHelp("r[P2]=rowid"), /* 123 */ "NullRow" OpHelp(""), /* 124 */ "SorterInsert" OpHelp("key=r[P2]"), /* 125 */ "IdxInsert" OpHelp("key=r[P2]"), /* 126 */ "IdxDelete" OpHelp("key=r[P2@P3]"), /* 127 */ "Seek" OpHelp("Move P3 to P1.rowid"), /* 128 */ "IdxRowid" OpHelp("r[P2]=rowid"), /* 129 */ "Destroy" OpHelp(""), /* 130 */ "Clear" OpHelp(""), /* 131 */ "ResetSorter" OpHelp(""), /* 132 */ "Real" OpHelp("r[P2]=P4"), /* 133 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"), /* 134 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"), /* 135 */ "ParseSchema" OpHelp(""), /* 136 */ "LoadAnalysis" OpHelp(""), /* 137 */ "DropTable" OpHelp(""), /* 138 */ "DropIndex" OpHelp(""), /* 139 */ "DropTrigger" OpHelp(""), /* 140 */ "IntegrityCk" OpHelp(""), /* 141 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), /* 142 */ "Param" OpHelp(""), /* 143 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), /* 144 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"), /* 145 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), /* 146 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"), /* 147 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"), /* 148 */ "AggFinal" OpHelp("accum=r[P1] N=P2"), /* 149 */ "Expire" OpHelp(""), /* 150 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), /* 151 */ "VBegin" OpHelp(""), /* 152 */ "VCreate" OpHelp(""), /* 153 */ "VDestroy" OpHelp(""), /* 154 */ "VOpen" OpHelp(""), /* 155 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), /* 156 */ "VRename" OpHelp(""), /* 157 */ "Pagecount" OpHelp(""), /* 158 */ "MaxPgcnt" OpHelp(""), /* 159 */ "CursorHint" OpHelp(""), /* 160 */ "Noop" OpHelp(""), /* 161 */ "Explain" OpHelp(""), }; return azName[i]; } #endif /************** End of opcodes.c *********************************************/ /************** Begin file os_unix.c *****************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains the VFS implementation for unix-like operating systems ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others. ** ** There are actually several different VFS implementations in this file. ** The differences are in the way that file locking is done. The default ** implementation uses Posix Advisory Locks. Alternative implementations ** use flock(), dot-files, various proprietary locking schemas, or simply ** skip locking all together. ** ** This source file is organized into divisions where the logic for various ** subfunctions is contained within the appropriate division. PLEASE ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed ** in the correct division and should be clearly labeled. ** ** The layout of divisions is as follows: ** ** * General-purpose declarations and utility functions. ** * Unique file ID logic used by VxWorks. ** * Various locking primitive implementations (all except proxy locking): ** + for Posix Advisory Locks ** + for no-op locks ** + for dot-file locks ** + for flock() locking ** + for named semaphore locks (VxWorks only) ** + for AFP filesystem locks (MacOSX only) ** * sqlite3_file methods not associated with locking. ** * Definitions of sqlite3_io_methods objects for all locking ** methods plus "finder" functions for each locking method. ** * sqlite3_vfs method implementations. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only) ** * Definitions of sqlite3_vfs objects for all locking methods ** plus implementations of sqlite3_os_init() and sqlite3_os_end(). */ /* #include "sqliteInt.h" */ #if SQLITE_OS_UNIX /* This file is used on unix only */ /* ** There are various methods for file locking used for concurrency ** control: ** ** 1. POSIX locking (the default), ** 2. No locking, ** 3. Dot-file locking, ** 4. flock() locking, ** 5. AFP locking (OSX only), ** 6. Named POSIX semaphores (VXWorks only), ** 7. proxy locking. (OSX only) ** ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic ** selection of the appropriate locking style based on the filesystem ** where the database is located. */ #if !defined(SQLITE_ENABLE_LOCKING_STYLE) # if defined(__APPLE__) # define SQLITE_ENABLE_LOCKING_STYLE 1 # else # define SQLITE_ENABLE_LOCKING_STYLE 0 # endif #endif /* Use pread() and pwrite() if they are available */ #if defined(__APPLE__) # define HAVE_PREAD 1 # define HAVE_PWRITE 1 #endif #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64) # undef USE_PREAD # define USE_PREAD64 1 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE) # undef USE_PREAD64 # define USE_PREAD 1 #endif /* ** standard include files. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> /* #include <time.h> */ #include <sys/time.h> #include <errno.h> #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 # include <sys/mman.h> #endif #if SQLITE_ENABLE_LOCKING_STYLE # include <sys/ioctl.h> # include <sys/file.h> # include <sys/param.h> #endif /* SQLITE_ENABLE_LOCKING_STYLE */ #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \ (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000)) # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \ && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0)) # define HAVE_GETHOSTUUID 1 # else # warning "gethostuuid() is disabled." # endif #endif #if OS_VXWORKS /* # include <sys/ioctl.h> */ # include <semaphore.h> # include <limits.h> #endif /* OS_VXWORKS */ #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE # include <sys/mount.h> #endif #ifdef HAVE_UTIME # include <utime.h> #endif /* ** Allowed values of unixFile.fsFlags */ #define SQLITE_FSFLAGS_IS_MSDOS 0x1 /* ** If we are to be thread-safe, include the pthreads header and define ** the SQLITE_UNIX_THREADS macro. */ #if SQLITE_THREADSAFE /* # include <pthread.h> */ # define SQLITE_UNIX_THREADS 1 #endif /* ** Default permissions when creating a new file */ #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644 #endif /* ** Default permissions when creating auto proxy dir */ #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755 #endif /* ** Maximum supported path-length. */ #define MAX_PATHNAME 512 /* ** Maximum supported symbolic links */ #define SQLITE_MAX_SYMLINKS 100 /* Always cast the getpid() return type for compatibility with ** kernel modules in VxWorks. */ #define osGetpid(X) (pid_t)getpid() /* ** Only set the lastErrno if the error code is a real error and not ** a normal expected return code of SQLITE_BUSY or SQLITE_OK */ #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY)) /* Forward references */ typedef struct unixShm unixShm; /* Connection shared memory */ typedef struct unixShmNode unixShmNode; /* Shared memory instance */ typedef struct unixInodeInfo unixInodeInfo; /* An i-node */ typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */ /* ** Sometimes, after a file handle is closed by SQLite, the file descriptor ** cannot be closed immediately. In these cases, instances of the following ** structure are used to store the file descriptor while waiting for an ** opportunity to either close or reuse it. */ struct UnixUnusedFd { int fd; /* File descriptor to close */ int flags; /* Flags this file descriptor was opened with */ UnixUnusedFd *pNext; /* Next unused file descriptor on same file */ }; /* ** The unixFile structure is subclass of sqlite3_file specific to the unix ** VFS implementations. */ typedef struct unixFile unixFile; struct unixFile { sqlite3_io_methods const *pMethod; /* Always the first entry */ sqlite3_vfs *pVfs; /* The VFS that created this unixFile */ unixInodeInfo *pInode; /* Info about locks on this inode */ int h; /* The file descriptor */ unsigned char eFileLock; /* The type of lock held on this fd */ unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */ int lastErrno; /* The unix errno from last I/O error */ void *lockingContext; /* Locking style specific state */ UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */ const char *zPath; /* Name of the file */ unixShm *pShm; /* Shared memory segment information */ int szChunk; /* Configured by FCNTL_CHUNK_SIZE */ #if SQLITE_MAX_MMAP_SIZE>0 int nFetchOut; /* Number of outstanding xFetch refs */ sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */ sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */ sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ void *pMapRegion; /* Memory mapped region */ #endif #ifdef __QNXNTO__ int sectorSize; /* Device sector size */ int deviceCharacteristics; /* Precomputed device characteristics */ #endif #if SQLITE_ENABLE_LOCKING_STYLE int openFlags; /* The flags specified at open() */ #endif #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__) unsigned fsFlags; /* cached details from statfs() */ #endif #if OS_VXWORKS struct vxworksFileId *pId; /* Unique file ID */ #endif #ifdef SQLITE_DEBUG /* The next group of variables are used to track whether or not the ** transaction counter in bytes 24-27 of database files are updated ** whenever any part of the database changes. An assertion fault will ** occur if a file is updated without also updating the transaction ** counter. This test is made to avoid new problems similar to the ** one described by ticket #3584. */ unsigned char transCntrChng; /* True if the transaction counter changed */ unsigned char dbUpdate; /* True if any part of database file changed */ unsigned char inNormalWrite; /* True if in a normal write operation */ #endif #ifdef SQLITE_TEST /* In test mode, increase the size of this structure a bit so that ** it is larger than the struct CrashFile defined in test6.c. */ char aPadding[32]; #endif }; /* This variable holds the process id (pid) from when the xRandomness() ** method was called. If xOpen() is called from a different process id, ** indicating that a fork() has occurred, the PRNG will be reset. */ static pid_t randomnessPid = 0; /* ** Allowed values for the unixFile.ctrlFlags bitmask: */ #define UNIXFILE_EXCL 0x01 /* Connections from one process only */ #define UNIXFILE_RDONLY 0x02 /* Connection is read only */ #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ #ifndef SQLITE_DISABLE_DIRSYNC # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */ #else # define UNIXFILE_DIRSYNC 0x00 #endif #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ #define UNIXFILE_DELETE 0x20 /* Delete on close */ #define UNIXFILE_URI 0x40 /* Filename might have query parameters */ #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */ /* ** Include code that is common to all os_*.c files */ /************** Include os_common.h in the middle of os_unix.c ***************/ /************** Begin file os_common.h ***************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. */ #ifndef _OS_COMMON_H_ #define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #ifdef MEMORY_DEBUG # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #ifdef SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ /************** Include hwtime.h in the middle of os_common.h ****************/ /************** Begin file hwtime.h ******************************************/ /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if (defined(__GNUC__) || defined(_MSC_VER)) && \ (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; } #elif defined(_MSC_VER) __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else #error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif #endif /* !defined(SQLITE_HWTIME_H) */ /************** End of hwtime.h **********************************************/ /************** Continuing where we left off in os_common.h ******************/ static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; #define TIMER_START g_start=sqlite3Hwtime() #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START #define TIMER_END #define TIMER_ELAPSED ((sqlite_uint64)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_io_error_hit; SQLITE_API extern int sqlite3_io_error_hardhit; SQLITE_API extern int sqlite3_io_error_pending; SQLITE_API extern int sqlite3_io_error_persist; SQLITE_API extern int sqlite3_io_error_benign; SQLITE_API extern int sqlite3_diskfull_pending; SQLITE_API extern int sqlite3_diskfull; #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ || sqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); sqlite3_io_error_hit++; if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ if( sqlite3_diskfull_pending ){ \ if( sqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ sqlite3_diskfull = 1; \ sqlite3_io_error_hit = 1; \ CODE; \ }else{ \ sqlite3_diskfull_pending--; \ } \ } #else #define SimulateIOErrorBenign(X) #define SimulateIOError(A) #define SimulateDiskfullError(A) #endif /* defined(SQLITE_TEST) */ /* ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_open_file_count; #define OpenCounter(X) sqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ #endif /* !defined(_OS_COMMON_H_) */ /************** End of os_common.h *******************************************/ /************** Continuing where we left off in os_unix.c ********************/ /* ** Define various macros that are missing from some systems. */ #ifndef O_LARGEFILE # define O_LARGEFILE 0 #endif #ifdef SQLITE_DISABLE_LFS # undef O_LARGEFILE # define O_LARGEFILE 0 #endif #ifndef O_NOFOLLOW # define O_NOFOLLOW 0 #endif #ifndef O_BINARY # define O_BINARY 0 #endif /* ** The threadid macro resolves to the thread-id or to 0. Used for ** testing and debugging only. */ #if SQLITE_THREADSAFE #define threadid pthread_self() #else #define threadid 0 #endif /* ** HAVE_MREMAP defaults to true on Linux and false everywhere else. */ #if !defined(HAVE_MREMAP) # if defined(__linux__) && defined(_GNU_SOURCE) # define HAVE_MREMAP 1 # else # define HAVE_MREMAP 0 # endif #endif /* ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek() ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined. */ #ifdef __ANDROID__ # define lseek lseek64 #endif /* ** Different Unix systems declare open() in different ways. Same use ** open(const char*,int,mode_t). Others use open(const char*,int,...). ** The difference is important when using a pointer to the function. ** ** The safest way to deal with the problem is to always use this wrapper ** which always has the same well-defined interface. */ static int posixOpen(const char *zFile, int flags, int mode){ return open(zFile, flags, mode); } /* Forward reference */ static int openDirectory(const char*, int*); static int unixGetpagesize(void); /* ** Many system calls are accessed through pointer-to-functions so that ** they may be overridden at runtime to facilitate fault injection during ** testing and sandboxing. The following array holds the names and pointers ** to all overrideable system calls. */ static struct unix_syscall { const char *zName; /* Name of the system call */ sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ sqlite3_syscall_ptr pDefault; /* Default value */ } aSyscall[] = { { "open", (sqlite3_syscall_ptr)posixOpen, 0 }, #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent) { "close", (sqlite3_syscall_ptr)close, 0 }, #define osClose ((int(*)(int))aSyscall[1].pCurrent) { "access", (sqlite3_syscall_ptr)access, 0 }, #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent) { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent) { "stat", (sqlite3_syscall_ptr)stat, 0 }, #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) /* ** The DJGPP compiler environment looks mostly like Unix, but it ** lacks the fcntl() system call. So redefine fcntl() to be something ** that always succeeds. This means that locking does not occur under ** DJGPP. But it is DOS - what did you expect? */ #ifdef __DJGPP__ { "fstat", 0, 0 }, #define osFstat(a,b,c) 0 #else { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent) #endif { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 }, #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent) { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 }, #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent) { "read", (sqlite3_syscall_ptr)read, 0 }, #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent) #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE { "pread", (sqlite3_syscall_ptr)pread, 0 }, #else { "pread", (sqlite3_syscall_ptr)0, 0 }, #endif #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent) #if defined(USE_PREAD64) { "pread64", (sqlite3_syscall_ptr)pread64, 0 }, #else { "pread64", (sqlite3_syscall_ptr)0, 0 }, #endif #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent) { "write", (sqlite3_syscall_ptr)write, 0 }, #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent) #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 }, #else { "pwrite", (sqlite3_syscall_ptr)0, 0 }, #endif #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\ aSyscall[12].pCurrent) #if defined(USE_PREAD64) { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 }, #else { "pwrite64", (sqlite3_syscall_ptr)0, 0 }, #endif #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\ aSyscall[13].pCurrent) { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 }, #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent) #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 }, #else { "fallocate", (sqlite3_syscall_ptr)0, 0 }, #endif #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent) { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent) { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent) { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent) { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent) #if defined(HAVE_FCHOWN) { "fchown", (sqlite3_syscall_ptr)fchown, 0 }, #else { "fchown", (sqlite3_syscall_ptr)0, 0 }, #endif #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent) { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 }, #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "mmap", (sqlite3_syscall_ptr)mmap, 0 }, #else { "mmap", (sqlite3_syscall_ptr)0, 0 }, #endif #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "munmap", (sqlite3_syscall_ptr)munmap, 0 }, #else { "munmap", (sqlite3_syscall_ptr)0, 0 }, #endif #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent) #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) { "mremap", (sqlite3_syscall_ptr)mremap, 0 }, #else { "mremap", (sqlite3_syscall_ptr)0, 0 }, #endif #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 }, #else { "getpagesize", (sqlite3_syscall_ptr)0, 0 }, #endif #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent) #if defined(HAVE_READLINK) { "readlink", (sqlite3_syscall_ptr)readlink, 0 }, #else { "readlink", (sqlite3_syscall_ptr)0, 0 }, #endif #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent) #if defined(HAVE_LSTAT) { "lstat", (sqlite3_syscall_ptr)lstat, 0 }, #else { "lstat", (sqlite3_syscall_ptr)0, 0 }, #endif #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent) }; /* End of the overrideable system calls */ /* ** On some systems, calls to fchown() will trigger a message in a security ** log if they come from non-root processes. So avoid calling fchown() if ** we are not running as root. */ static int robustFchown(int fd, uid_t uid, gid_t gid){ #if defined(HAVE_FCHOWN) return osGeteuid() ? 0 : osFchown(fd,uid,gid); #else return 0; #endif } /* ** This is the xSetSystemCall() method of sqlite3_vfs for all of the ** "unix" VFSes. Return SQLITE_OK opon successfully updating the ** system call pointer, or SQLITE_NOTFOUND if there is no configurable ** system call named zName. */ static int unixSetSystemCall( sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ const char *zName, /* Name of system call to override */ sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ ){ unsigned int i; int rc = SQLITE_NOTFOUND; UNUSED_PARAMETER(pNotUsed); if( zName==0 ){ /* If no zName is given, restore all system calls to their default ** settings and return NULL */ rc = SQLITE_OK; for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ if( aSyscall[i].pDefault ){ aSyscall[i].pCurrent = aSyscall[i].pDefault; } } }else{ /* If zName is specified, operate on only the one system call ** specified. */ for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ if( strcmp(zName, aSyscall[i].zName)==0 ){ if( aSyscall[i].pDefault==0 ){ aSyscall[i].pDefault = aSyscall[i].pCurrent; } rc = SQLITE_OK; if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault; aSyscall[i].pCurrent = pNewFunc; break; } } } return rc; } /* ** Return the value of a system call. Return NULL if zName is not a ** recognized system call name. NULL is also returned if the system call ** is currently undefined. */ static sqlite3_syscall_ptr unixGetSystemCall( sqlite3_vfs *pNotUsed, const char *zName ){ unsigned int i; UNUSED_PARAMETER(pNotUsed); for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent; } return 0; } /* ** Return the name of the first system call after zName. If zName==NULL ** then return the name of the first system call. Return NULL if zName ** is the last system call or if zName is not the name of a valid ** system call. */ static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){ int i = -1; UNUSED_PARAMETER(p); if( zName ){ for(i=0; i<ArraySize(aSyscall)-1; i++){ if( strcmp(zName, aSyscall[i].zName)==0 ) break; } } for(i++; i<ArraySize(aSyscall); i++){ if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName; } return 0; } /* ** Do not accept any file descriptor less than this value, in order to avoid ** opening database file using file descriptors that are commonly used for ** standard input, output, and error. */ #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3 #endif /* ** Invoke open(). Do so multiple times, until it either succeeds or ** fails for some reason other than EINTR. ** ** If the file creation mode "m" is 0 then set it to the default for ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally ** 0644) as modified by the system umask. If m is not 0, then ** make the file creation mode be exactly m ignoring the umask. ** ** The m parameter will be non-zero only when creating -wal, -journal, ** and -shm files. We want those files to have *exactly* the same ** permissions as their original database, unadulterated by the umask. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a ** transaction crashes and leaves behind hot journals, then any ** process that is able to write to the database will also be able to ** recover the hot journals. */ static int robust_open(const char *z, int f, mode_t m){ int fd; mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS; while(1){ #if defined(O_CLOEXEC) fd = osOpen(z,f|O_CLOEXEC,m2); #else fd = osOpen(z,f,m2); #endif if( fd<0 ){ if( errno==EINTR ) continue; break; } if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break; osClose(fd); sqlite3_log(SQLITE_WARNING, "attempt to open \"%s\" as file descriptor %d", z, fd); fd = -1; if( osOpen("/dev/null", f, m)<0 ) break; } if( fd>=0 ){ if( m!=0 ){ struct stat statbuf; if( osFstat(fd, &statbuf)==0 && statbuf.st_size==0 && (statbuf.st_mode&0777)!=m ){ osFchmod(fd, m); } } #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC); #endif } return fd; } /* ** Helper functions to obtain and relinquish the global mutex. The ** global mutex is used to protect the unixInodeInfo and ** vxworksFileId objects used by this file, all of which may be ** shared by multiple threads. ** ** Function unixMutexHeld() is used to assert() that the global mutex ** is held when required. This function is only used as part of assert() ** statements. e.g. ** ** unixEnterMutex() ** assert( unixMutexHeld() ); ** unixEnterLeave() */ static void unixEnterMutex(void){ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } static void unixLeaveMutex(void){ sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } #ifdef SQLITE_DEBUG static int unixMutexHeld(void) { return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } #endif #ifdef SQLITE_HAVE_OS_TRACE /* ** Helper function for printing out trace information from debugging ** binaries. This returns the string representation of the supplied ** integer lock-type. */ static const char *azFileLock(int eFileLock){ switch( eFileLock ){ case NO_LOCK: return "NONE"; case SHARED_LOCK: return "SHARED"; case RESERVED_LOCK: return "RESERVED"; case PENDING_LOCK: return "PENDING"; case EXCLUSIVE_LOCK: return "EXCLUSIVE"; } return "ERROR"; } #endif #ifdef SQLITE_LOCK_TRACE /* ** Print out information about all locking operations. ** ** This routine is used for troubleshooting locks on multithreaded ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE ** command-line option on the compiler. This code is normally ** turned off. */ static int lockTrace(int fd, int op, struct flock *p){ char *zOpName, *zType; int s; int savedErrno; if( op==F_GETLK ){ zOpName = "GETLK"; }else if( op==F_SETLK ){ zOpName = "SETLK"; }else{ s = osFcntl(fd, op, p); sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s); return s; } if( p->l_type==F_RDLCK ){ zType = "RDLCK"; }else if( p->l_type==F_WRLCK ){ zType = "WRLCK"; }else if( p->l_type==F_UNLCK ){ zType = "UNLCK"; }else{ assert( 0 ); } assert( p->l_whence==SEEK_SET ); s = osFcntl(fd, op, p); savedErrno = errno; sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n", threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len, (int)p->l_pid, s); if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){ struct flock l2; l2 = *p; osFcntl(fd, F_GETLK, &l2); if( l2.l_type==F_RDLCK ){ zType = "RDLCK"; }else if( l2.l_type==F_WRLCK ){ zType = "WRLCK"; }else if( l2.l_type==F_UNLCK ){ zType = "UNLCK"; }else{ assert( 0 ); } sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n", zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid); } errno = savedErrno; return s; } #undef osFcntl #define osFcntl lockTrace #endif /* SQLITE_LOCK_TRACE */ /* ** Retry ftruncate() calls that fail due to EINTR ** ** All calls to ftruncate() within this file should be made through ** this wrapper. On the Android platform, bypassing the logic below ** could lead to a corrupt database. */ static int robust_ftruncate(int h, sqlite3_int64 sz){ int rc; #ifdef __ANDROID__ /* On Android, ftruncate() always uses 32-bit offsets, even if ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to ** truncate a file to any size larger than 2GiB. Silently ignore any ** such attempts. */ if( sz>(sqlite3_int64)0x7FFFFFFF ){ rc = SQLITE_OK; }else #endif do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR ); return rc; } /* ** This routine translates a standard POSIX errno code into something ** useful to the clients of the sqlite3 functions. Specifically, it is ** intended to translate a variety of "try again" errors into SQLITE_BUSY ** and a variety of "please close the file descriptor NOW" errors into ** SQLITE_IOERR ** ** Errors during initialization of locks, or file system support for locks, ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately. */ static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) { assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || (sqliteIOErr == SQLITE_IOERR_UNLOCK) || (sqliteIOErr == SQLITE_IOERR_RDLOCK) || (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ); switch (posixError) { case EACCES: case EAGAIN: case ETIMEDOUT: case EBUSY: case EINTR: case ENOLCK: /* random NFS retry error, unless during file system support * introspection, in which it actually means what it says */ return SQLITE_BUSY; case EPERM: return SQLITE_PERM; default: return sqliteIOErr; } } /****************************************************************************** ****************** Begin Unique File ID Utility Used By VxWorks *************** ** ** On most versions of unix, we can get a unique ID for a file by concatenating ** the device number and the inode number. But this does not work on VxWorks. ** On VxWorks, a unique file id must be based on the canonical filename. ** ** A pointer to an instance of the following structure can be used as a ** unique file ID in VxWorks. Each instance of this structure contains ** a copy of the canonical filename. There is also a reference count. ** The structure is reclaimed when the number of pointers to it drops to ** zero. ** ** There are never very many files open at one time and lookups are not ** a performance-critical path, so it is sufficient to put these ** structures on a linked list. */ struct vxworksFileId { struct vxworksFileId *pNext; /* Next in a list of them all */ int nRef; /* Number of references to this one */ int nName; /* Length of the zCanonicalName[] string */ char *zCanonicalName; /* Canonical filename */ }; #if OS_VXWORKS /* ** All unique filenames are held on a linked list headed by this ** variable: */ static struct vxworksFileId *vxworksFileList = 0; /* ** Simplify a filename into its canonical form ** by making the following changes: ** ** * removing any trailing and duplicate / ** * convert /./ into just / ** * convert /A/../ where A is any simple name into just / ** ** Changes are made in-place. Return the new name length. ** ** The original filename is in z[0..n-1]. Return the number of ** characters in the simplified name. */ static int vxworksSimplifyName(char *z, int n){ int i, j; while( n>1 && z[n-1]=='/' ){ n--; } for(i=j=0; i<n; i++){ if( z[i]=='/' ){ if( z[i+1]=='/' ) continue; if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){ i += 1; continue; } if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){ while( j>0 && z[j-1]!='/' ){ j--; } if( j>0 ){ j--; } i += 2; continue; } } z[j++] = z[i]; } z[j] = 0; return j; } /* ** Find a unique file ID for the given absolute pathname. Return ** a pointer to the vxworksFileId object. This pointer is the unique ** file ID. ** ** The nRef field of the vxworksFileId object is incremented before ** the object is returned. A new vxworksFileId object is created ** and added to the global list if necessary. ** ** If a memory allocation error occurs, return NULL. */ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ struct vxworksFileId *pNew; /* search key and new file ID */ struct vxworksFileId *pCandidate; /* For looping over existing file IDs */ int n; /* Length of zAbsoluteName string */ assert( zAbsoluteName[0]=='/' ); n = (int)strlen(zAbsoluteName); pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) ); if( pNew==0 ) return 0; pNew->zCanonicalName = (char*)&pNew[1]; memcpy(pNew->zCanonicalName, zAbsoluteName, n+1); n = vxworksSimplifyName(pNew->zCanonicalName, n); /* Search for an existing entry that matching the canonical name. ** If found, increment the reference count and return a pointer to ** the existing file ID. */ unixEnterMutex(); for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){ if( pCandidate->nName==n && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0 ){ sqlite3_free(pNew); pCandidate->nRef++; unixLeaveMutex(); return pCandidate; } } /* No match was found. We will make a new file ID */ pNew->nRef = 1; pNew->nName = n; pNew->pNext = vxworksFileList; vxworksFileList = pNew; unixLeaveMutex(); return pNew; } /* ** Decrement the reference count on a vxworksFileId object. Free ** the object when the reference count reaches zero. */ static void vxworksReleaseFileId(struct vxworksFileId *pId){ unixEnterMutex(); assert( pId->nRef>0 ); pId->nRef--; if( pId->nRef==0 ){ struct vxworksFileId **pp; for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){} assert( *pp==pId ); *pp = pId->pNext; sqlite3_free(pId); } unixLeaveMutex(); } #endif /* OS_VXWORKS */ /*************** End of Unique File ID Utility Used By VxWorks **************** ******************************************************************************/ /****************************************************************************** *************************** Posix Advisory Locking **************************** ** ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996) ** section 6.5.2.2 lines 483 through 490 specify that when a process ** sets or clears a lock, that operation overrides any prior locks set ** by the same process. It does not explicitly say so, but this implies ** that it overrides locks set by the same process using a different ** file descriptor. Consider this test case: ** ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644); ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644); ** ** Suppose ./file1 and ./file2 are really the same file (because ** one is a hard or symbolic link to the other) then if you set ** an exclusive lock on fd1, then try to get an exclusive lock ** on fd2, it works. I would have expected the second lock to ** fail since there was already a lock on the file due to fd1. ** But not so. Since both locks came from the same process, the ** second overrides the first, even though they were on different ** file descriptors opened on different file names. ** ** This means that we cannot use POSIX locks to synchronize file access ** among competing threads of the same process. POSIX locks will work fine ** to synchronize access for threads in separate processes, but not ** threads within the same process. ** ** To work around the problem, SQLite has to manage file locks internally ** on its own. Whenever a new database is opened, we have to find the ** specific inode of the database file (the inode is determined by the ** st_dev and st_ino fields of the stat structure that fstat() fills in) ** and check for locks already existing on that inode. When locks are ** created or removed, we have to look at our own internal record of the ** locks to see if another thread has previously set a lock on that same ** inode. ** ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks. ** For VxWorks, we have to use the alternative unique ID system based on ** canonical filename and implemented in the previous division.) ** ** The sqlite3_file structure for POSIX is no longer just an integer file ** descriptor. It is now a structure that holds the integer file ** descriptor and a pointer to a structure that describes the internal ** locks on the corresponding inode. There is one locking structure ** per inode, so if the same inode is opened twice, both unixFile structures ** point to the same locking structure. The locking structure keeps ** a reference count (so we will know when to delete it) and a "cnt" ** field that tells us its internal lock status. cnt==0 means the ** file is unlocked. cnt==-1 means the file has an exclusive lock. ** cnt>0 means there are cnt shared locks on the file. ** ** Any attempt to lock or unlock a file first checks the locking ** structure. The fcntl() system call is only invoked to set a ** POSIX lock if the internal lock structure transitions between ** a locked and an unlocked state. ** ** But wait: there are yet more problems with POSIX advisory locks. ** ** If you close a file descriptor that points to a file that has locks, ** all locks on that file that are owned by the current process are ** released. To work around this problem, each unixInodeInfo object ** maintains a count of the number of pending locks on tha inode. ** When an attempt is made to close an unixFile, if there are ** other unixFile open on the same inode that are holding locks, the call ** to close() the file descriptor is deferred until all of the locks clear. ** The unixInodeInfo structure keeps a list of file descriptors that need to ** be closed and that list is walked (and cleared) when the last lock ** clears. ** ** Yet another problem: LinuxThreads do not play well with posix locks. ** ** Many older versions of linux use the LinuxThreads library which is ** not posix compliant. Under LinuxThreads, a lock created by thread ** A cannot be modified or overridden by a different thread B. ** Only thread A can modify the lock. Locking behavior is correct ** if the appliation uses the newer Native Posix Thread Library (NPTL) ** on linux - with NPTL a lock created by thread A can override locks ** in thread B. But there is no way to know at compile-time which ** threading library is being used. So there is no way to know at ** compile-time whether or not thread A can override locks on thread B. ** One has to do a run-time check to discover the behavior of the ** current process. ** ** SQLite used to support LinuxThreads. But support for LinuxThreads ** was dropped beginning with version 3.7.0. SQLite will still work with ** LinuxThreads provided that (1) there is no more than one connection ** per database file in the same process and (2) database connections ** do not move across threads. */ /* ** An instance of the following structure serves as the key used ** to locate a particular unixInodeInfo object. */ struct unixFileId { dev_t dev; /* Device number */ #if OS_VXWORKS struct vxworksFileId *pId; /* Unique file ID for vxworks. */ #else /* We are told that some versions of Android contain a bug that ** sizes ino_t at only 32-bits instead of 64-bits. (See ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c) ** To work around this, always allocate 64-bits for the inode number. ** On small machines that only have 32-bit inodes, this wastes 4 bytes, ** but that should not be a big deal. */ /* WAS: ino_t ino; */ u64 ino; /* Inode number */ #endif }; /* ** An instance of the following structure is allocated for each open ** inode. Or, on LinuxThreads, there is one of these structures for ** each inode opened by each thread. ** ** A single inode can have multiple file descriptors, so each unixFile ** structure contains a pointer to an instance of this object and this ** object keeps a count of the number of unixFile pointing to it. */ struct unixInodeInfo { struct unixFileId fileId; /* The lookup key */ int nShared; /* Number of SHARED locks held */ unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ unsigned char bProcessLock; /* An exclusive process lock is held */ int nRef; /* Number of pointers to this structure */ unixShmNode *pShmNode; /* Shared memory associated with this inode */ int nLock; /* Number of outstanding file locks */ UnixUnusedFd *pUnused; /* Unused file descriptors to close */ unixInodeInfo *pNext; /* List of all unixInodeInfo objects */ unixInodeInfo *pPrev; /* .... doubly linked */ #if SQLITE_ENABLE_LOCKING_STYLE unsigned long long sharedByte; /* for AFP simulated shared lock */ #endif #if OS_VXWORKS sem_t *pSem; /* Named POSIX semaphore */ char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */ #endif }; /* ** A lists of all unixInodeInfo objects. */ static unixInodeInfo *inodeList = 0; /* ** ** This function - unixLogErrorAtLine(), is only ever called via the macro ** unixLogError(). ** ** It is invoked after an error occurs in an OS function and errno has been ** set. It logs a message using sqlite3_log() containing the current value of ** errno and, if possible, the human-readable equivalent from strerror() or ** strerror_r(). ** ** The first argument passed to the macro should be the error code that ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). ** The two subsequent arguments should be the name of the OS function that ** failed (e.g. "unlink", "open") and the associated file-system path, ** if any. */ #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__) static int unixLogErrorAtLine( int errcode, /* SQLite error code */ const char *zFunc, /* Name of OS function that failed */ const char *zPath, /* File path associated with error */ int iLine /* Source line number where error occurred */ ){ char *zErr; /* Message from strerror() or equivalent */ int iErrno = errno; /* Saved syscall error number */ /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use ** the strerror() function to obtain the human-readable error message ** equivalent to errno. Otherwise, use strerror_r(). */ #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R) char aErr[80]; memset(aErr, 0, sizeof(aErr)); zErr = aErr; /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined, ** assume that the system provides the GNU version of strerror_r() that ** returns a pointer to a buffer containing the error message. That pointer ** may point to aErr[], or it may point to some static storage somewhere. ** Otherwise, assume that the system provides the POSIX version of ** strerror_r(), which always writes an error message into aErr[]. ** ** If the code incorrectly assumes that it is the POSIX version that is ** available, the error message will often be an empty string. Not a ** huge problem. Incorrectly concluding that the GNU version is available ** could lead to a segfault though. */ #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU) zErr = # endif strerror_r(iErrno, aErr, sizeof(aErr)-1); #elif SQLITE_THREADSAFE /* This is a threadsafe build, but strerror_r() is not available. */ zErr = ""; #else /* Non-threadsafe build, use strerror(). */ zErr = strerror(iErrno); #endif if( zPath==0 ) zPath = ""; sqlite3_log(errcode, "os_unix.c:%d: (%d) %s(%s) - %s", iLine, iErrno, zFunc, zPath, zErr ); return errcode; } /* ** Close a file descriptor. ** ** We assume that close() almost always works, since it is only in a ** very sick application or on a very sick platform that it might fail. ** If it does fail, simply leak the file descriptor, but do log the ** error. ** ** Note that it is not safe to retry close() after EINTR since the ** file descriptor might have already been reused by another thread. ** So we don't even try to recover from an EINTR. Just log the error ** and move on. */ static void robust_close(unixFile *pFile, int h, int lineno){ if( osClose(h) ){ unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close", pFile ? pFile->zPath : 0, lineno); } } /* ** Set the pFile->lastErrno. Do this in a subroutine as that provides ** a convenient place to set a breakpoint. */ static void storeLastErrno(unixFile *pFile, int error){ pFile->lastErrno = error; } /* ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list. */ static void closePendingFds(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; UnixUnusedFd *p; UnixUnusedFd *pNext; for(p=pInode->pUnused; p; p=pNext){ pNext = p->pNext; robust_close(pFile, p->fd, __LINE__); sqlite3_free(p); } pInode->pUnused = 0; } /* ** Release a unixInodeInfo structure previously allocated by findInodeInfo(). ** ** The mutex entered using the unixEnterMutex() function must be held ** when this function is called. */ static void releaseInodeInfo(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; assert( unixMutexHeld() ); if( ALWAYS(pInode) ){ pInode->nRef--; if( pInode->nRef==0 ){ assert( pInode->pShmNode==0 ); closePendingFds(pFile); if( pInode->pPrev ){ assert( pInode->pPrev->pNext==pInode ); pInode->pPrev->pNext = pInode->pNext; }else{ assert( inodeList==pInode ); inodeList = pInode->pNext; } if( pInode->pNext ){ assert( pInode->pNext->pPrev==pInode ); pInode->pNext->pPrev = pInode->pPrev; } sqlite3_free(pInode); } } } /* ** Given a file descriptor, locate the unixInodeInfo object that ** describes that file descriptor. Create a new one if necessary. The ** return value might be uninitialized if an error occurs. ** ** The mutex entered using the unixEnterMutex() function must be held ** when this function is called. ** ** Return an appropriate error code. */ static int findInodeInfo( unixFile *pFile, /* Unix file with file desc used in the key */ unixInodeInfo **ppInode /* Return the unixInodeInfo object here */ ){ int rc; /* System call return code */ int fd; /* The file descriptor for pFile */ struct unixFileId fileId; /* Lookup key for the unixInodeInfo */ struct stat statbuf; /* Low-level file information */ unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */ assert( unixMutexHeld() ); /* Get low-level information about the file that we can used to ** create a unique name for the file. */ fd = pFile->h; rc = osFstat(fd, &statbuf); if( rc!=0 ){ storeLastErrno(pFile, errno); #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS) if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS; #endif return SQLITE_IOERR; } #ifdef __APPLE__ /* On OS X on an msdos filesystem, the inode number is reported ** incorrectly for zero-size files. See ticket #3260. To work ** around this problem (we consider it a bug in OS X, not SQLite) ** we always increase the file size to 1 by writing a single byte ** prior to accessing the inode number. The one byte written is ** an ASCII 'S' character which also happens to be the first byte ** in the header of every SQLite database. In this way, if there ** is a race condition such that another thread has already populated ** the first page of the database, no damage is done. */ if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){ do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR ); if( rc!=1 ){ storeLastErrno(pFile, errno); return SQLITE_IOERR; } rc = osFstat(fd, &statbuf); if( rc!=0 ){ storeLastErrno(pFile, errno); return SQLITE_IOERR; } } #endif memset(&fileId, 0, sizeof(fileId)); fileId.dev = statbuf.st_dev; #if OS_VXWORKS fileId.pId = pFile->pId; #else fileId.ino = (u64)statbuf.st_ino; #endif pInode = inodeList; while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){ pInode = pInode->pNext; } if( pInode==0 ){ pInode = sqlite3_malloc64( sizeof(*pInode) ); if( pInode==0 ){ return SQLITE_NOMEM_BKPT; } memset(pInode, 0, sizeof(*pInode)); memcpy(&pInode->fileId, &fileId, sizeof(fileId)); pInode->nRef = 1; pInode->pNext = inodeList; pInode->pPrev = 0; if( inodeList ) inodeList->pPrev = pInode; inodeList = pInode; }else{ pInode->nRef++; } *ppInode = pInode; return SQLITE_OK; } /* ** Return TRUE if pFile has been renamed or unlinked since it was first opened. */ static int fileHasMoved(unixFile *pFile){ #if OS_VXWORKS return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId; #else struct stat buf; return pFile->pInode!=0 && (osStat(pFile->zPath, &buf)!=0 || (u64)buf.st_ino!=pFile->pInode->fileId.ino); #endif } /* ** Check a unixFile that is a database. Verify the following: ** ** (1) There is exactly one hard link on the file ** (2) The file is not a symbolic link ** (3) The file has not been renamed or unlinked ** ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right. */ static void verifyDbFile(unixFile *pFile){ struct stat buf; int rc; /* These verifications occurs for the main database only */ if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return; rc = osFstat(pFile->h, &buf); if( rc!=0 ){ sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); return; } if( buf.st_nlink==0 ){ sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); return; } if( buf.st_nlink>1 ){ sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath); return; } if( fileHasMoved(pFile) ){ sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath); return; } } /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); assert( pFile->eFileLock<=SHARED_LOCK ); unixEnterMutex(); /* Because pFile->pInode is shared across threads */ /* Check if a thread in this process holds such a lock */ if( pFile->pInode->eFileLock>SHARED_LOCK ){ reserved = 1; } /* Otherwise see if some other process holds it. */ #ifndef __DJGPP__ if( !reserved && !pFile->pInode->bProcessLock ){ struct flock lock; lock.l_whence = SEEK_SET; lock.l_start = RESERVED_BYTE; lock.l_len = 1; lock.l_type = F_WRLCK; if( osFcntl(pFile->h, F_GETLK, &lock) ){ rc = SQLITE_IOERR_CHECKRESERVEDLOCK; storeLastErrno(pFile, errno); } else if( lock.l_type!=F_UNLCK ){ reserved = 1; } } #endif unixLeaveMutex(); OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved)); *pResOut = reserved; return rc; } /* ** Attempt to set a system-lock on the file pFile. The lock is ** described by pLock. ** ** If the pFile was opened read/write from unix-excl, then the only lock ** ever obtained is an exclusive lock, and it is obtained exactly once ** the first time any lock is attempted. All subsequent system locking ** operations become no-ops. Locking operations still happen internally, ** in order to coordinate access between separate database connections ** within this process, but all of that is handled in memory and the ** operating system does not participate. ** ** This function is a pass-through to fcntl(F_SETLK) if pFile is using ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl" ** and is read-only. ** ** Zero is returned if the call completes successfully, or -1 if a call ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()). */ static int unixFileLock(unixFile *pFile, struct flock *pLock){ int rc; unixInodeInfo *pInode = pFile->pInode; assert( unixMutexHeld() ); assert( pInode!=0 ); if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){ if( pInode->bProcessLock==0 ){ struct flock lock; assert( pInode->nLock==0 ); lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; lock.l_type = F_WRLCK; rc = osFcntl(pFile->h, F_SETLK, &lock); if( rc<0 ) return rc; pInode->bProcessLock = 1; pInode->nLock++; }else{ rc = 0; } }else{ rc = osFcntl(pFile->h, F_SETLK, pLock); } return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int unixLock(sqlite3_file *id, int eFileLock){ /* The following describes the implementation of the various locks and ** lock transitions in terms of the POSIX advisory shared and exclusive ** lock primitives (called read-locks and write-locks below, to avoid ** confusion with SQLite lock names). The algorithms are complicated ** slightly in order to be compatible with Windows95 systems simultaneously ** accessing the same database file, in case that is ever required. ** ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved ** byte', each single bytes at well known offsets, and the 'shared byte ** range', a range of 510 bytes at a well known offset. ** ** To obtain a SHARED lock, a read-lock is obtained on the 'pending ** byte'. If this is successful, 'shared byte range' is read-locked ** and the lock on the 'pending byte' released. (Legacy note: When ** SQLite was first developed, Windows95 systems were still very common, ** and Widnows95 lacks a shared-lock capability. So on Windows95, a ** single randomly selected by from the 'shared byte range' is locked. ** Windows95 is now pretty much extinct, but this work-around for the ** lack of shared-locks on Windows95 lives on, for backwards ** compatibility.) ** ** A process may only obtain a RESERVED lock after it has a SHARED lock. ** A RESERVED lock is implemented by grabbing a write-lock on the ** 'reserved byte'. ** ** A process may only obtain a PENDING lock after it has obtained a ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock ** on the 'pending byte'. This ensures that no new SHARED locks can be ** obtained, but existing SHARED locks are allowed to persist. A process ** does not have to obtain a RESERVED lock on the way to a PENDING lock. ** This property is used by the algorithm for rolling back a journal file ** after a crash. ** ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is ** implemented by obtaining a write-lock on the entire 'shared byte ** range'. Since all other locks require a read-lock on one of the bytes ** within this range, this ensures that no other locks are held on the ** database. */ int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode; struct flock lock; int tErrno = 0; assert( pFile ); OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h, azFileLock(eFileLock), azFileLock(pFile->eFileLock), azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared, osGetpid(0))); /* If there is already a lock of this type or more restrictive on the ** unixFile, do nothing. Don't use the end_lock: exit path, as ** unixEnterMutex() hasn't been called yet. */ if( pFile->eFileLock>=eFileLock ){ OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h, azFileLock(eFileLock))); return SQLITE_OK; } /* Make sure the locking sequence is correct. ** (1) We never move from unlocked to anything higher than shared lock. ** (2) SQLite never explicitly requests a pendig lock. ** (3) A shared lock is always held when a reserve lock is requested. */ assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); assert( eFileLock!=PENDING_LOCK ); assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); /* This mutex is needed because pFile->pInode is shared across threads */ unixEnterMutex(); pInode = pFile->pInode; /* If some thread using this PID has a lock via a different unixFile* ** handle that precludes the requested lock, return BUSY. */ if( (pFile->eFileLock!=pInode->eFileLock && (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) ){ rc = SQLITE_BUSY; goto end_lock; } /* If a SHARED lock is requested, and some thread using this PID already ** has a SHARED or RESERVED lock, then increment reference counts and ** return SQLITE_OK. */ if( eFileLock==SHARED_LOCK && (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ assert( eFileLock==SHARED_LOCK ); assert( pFile->eFileLock==0 ); assert( pInode->nShared>0 ); pFile->eFileLock = SHARED_LOCK; pInode->nShared++; pInode->nLock++; goto end_lock; } /* A PENDING lock is needed before acquiring a SHARED lock and before ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will ** be released. */ lock.l_len = 1L; lock.l_whence = SEEK_SET; if( eFileLock==SHARED_LOCK || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK) ){ lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK); lock.l_start = PENDING_BYTE; if( unixFileLock(pFile, &lock) ){ tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( rc!=SQLITE_BUSY ){ storeLastErrno(pFile, tErrno); } goto end_lock; } } /* If control gets to this point, then actually go ahead and make ** operating system calls for the specified lock. */ if( eFileLock==SHARED_LOCK ){ assert( pInode->nShared==0 ); assert( pInode->eFileLock==0 ); assert( rc==SQLITE_OK ); /* Now get the read-lock */ lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; if( unixFileLock(pFile, &lock) ){ tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); } /* Drop the temporary PENDING lock */ lock.l_start = PENDING_BYTE; lock.l_len = 1L; lock.l_type = F_UNLCK; if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){ /* This could happen with a network mount */ tErrno = errno; rc = SQLITE_IOERR_UNLOCK; } if( rc ){ if( rc!=SQLITE_BUSY ){ storeLastErrno(pFile, tErrno); } goto end_lock; }else{ pFile->eFileLock = SHARED_LOCK; pInode->nLock++; pInode->nShared = 1; } }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ /* We are trying for an exclusive lock but another thread in this ** same process is still holding a shared lock. */ rc = SQLITE_BUSY; }else{ /* The request was for a RESERVED or EXCLUSIVE lock. It is ** assumed that there is a SHARED or greater lock on the file ** already. */ assert( 0!=pFile->eFileLock ); lock.l_type = F_WRLCK; assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK ); if( eFileLock==RESERVED_LOCK ){ lock.l_start = RESERVED_BYTE; lock.l_len = 1L; }else{ lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; } if( unixFileLock(pFile, &lock) ){ tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( rc!=SQLITE_BUSY ){ storeLastErrno(pFile, tErrno); } } } #ifdef SQLITE_DEBUG /* Set up the transaction-counter change checking flags when ** transitioning from a SHARED to a RESERVED lock. The change ** from SHARED to RESERVED marks the beginning of a normal ** write operation (not a hot journal rollback). */ if( rc==SQLITE_OK && pFile->eFileLock<=SHARED_LOCK && eFileLock==RESERVED_LOCK ){ pFile->transCntrChng = 0; pFile->dbUpdate = 0; pFile->inNormalWrite = 1; } #endif if( rc==SQLITE_OK ){ pFile->eFileLock = eFileLock; pInode->eFileLock = eFileLock; }else if( eFileLock==EXCLUSIVE_LOCK ){ pFile->eFileLock = PENDING_LOCK; pInode->eFileLock = PENDING_LOCK; } end_lock: unixLeaveMutex(); OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); return rc; } /* ** Add the file descriptor used by file handle pFile to the corresponding ** pUnused list. */ static void setPendingFd(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; UnixUnusedFd *p = pFile->pUnused; p->pNext = pInode->pUnused; pInode->pUnused = p; pFile->h = -1; pFile->pUnused = 0; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. ** ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED ** the byte range is divided into 2 parts and the first part is unlocked then ** set to a read lock, then the other part is simply unlocked. This works ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to ** remove the write lock on a region when a read lock is set. */ static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){ unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode; struct flock lock; int rc = SQLITE_OK; assert( pFile ); OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock, pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); if( pFile->eFileLock<=eFileLock ){ return SQLITE_OK; } unixEnterMutex(); pInode = pFile->pInode; assert( pInode->nShared!=0 ); if( pFile->eFileLock>SHARED_LOCK ){ assert( pInode->eFileLock==pFile->eFileLock ); #ifdef SQLITE_DEBUG /* When reducing a lock such that other processes can start ** reading the database file again, make sure that the ** transaction counter was updated if any part of the database ** file changed. If the transaction counter is not updated, ** other connections to the same file might not realize that ** the file has changed and hence might not know to flush their ** cache. The use of a stale cache can lead to database corruption. */ pFile->inNormalWrite = 0; #endif /* downgrading to a shared lock on NFS involves clearing the write lock ** before establishing the readlock - to avoid a race condition we downgrade ** the lock in 2 blocks, so that part of the range will be covered by a ** write lock until the rest is covered by a read lock: ** 1: [WWWWW] ** 2: [....W] ** 3: [RRRRW] ** 4: [RRRR.] */ if( eFileLock==SHARED_LOCK ){ #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE (void)handleNFSUnlock; assert( handleNFSUnlock==0 ); #endif #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE if( handleNFSUnlock ){ int tErrno; /* Error code from system call errors */ off_t divSize = SHARED_SIZE - 1; lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = divSize; if( unixFileLock(pFile, &lock)==(-1) ){ tErrno = errno; rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, tErrno); goto end_unlock; } lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = divSize; if( unixFileLock(pFile, &lock)==(-1) ){ tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK); if( IS_LOCK_ERROR(rc) ){ storeLastErrno(pFile, tErrno); } goto end_unlock; } lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST+divSize; lock.l_len = SHARED_SIZE-divSize; if( unixFileLock(pFile, &lock)==(-1) ){ tErrno = errno; rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, tErrno); goto end_unlock; } }else #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ { lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; if( unixFileLock(pFile, &lock) ){ /* In theory, the call to unixFileLock() cannot fail because another ** process is holding an incompatible lock. If it does, this ** indicates that the other process is not following the locking ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning ** SQLITE_BUSY would confuse the upper layer (in practice it causes ** an assert to fail). */ rc = SQLITE_IOERR_RDLOCK; storeLastErrno(pFile, errno); goto end_unlock; } } } lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = PENDING_BYTE; lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE ); if( unixFileLock(pFile, &lock)==0 ){ pInode->eFileLock = SHARED_LOCK; }else{ rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, errno); goto end_unlock; } } if( eFileLock==NO_LOCK ){ /* Decrement the shared lock counter. Release the lock using an ** OS call only when all threads in this same process have released ** the lock. */ pInode->nShared--; if( pInode->nShared==0 ){ lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = lock.l_len = 0L; if( unixFileLock(pFile, &lock)==0 ){ pInode->eFileLock = NO_LOCK; }else{ rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, errno); pInode->eFileLock = NO_LOCK; pFile->eFileLock = NO_LOCK; } } /* Decrement the count of locks against this same file. When the ** count reaches zero, close any other file descriptors whose close ** was deferred because of outstanding locks. */ pInode->nLock--; assert( pInode->nLock>=0 ); if( pInode->nLock==0 ){ closePendingFds(pFile); } } end_unlock: unixLeaveMutex(); if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock; return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int unixUnlock(sqlite3_file *id, int eFileLock){ #if SQLITE_MAX_MMAP_SIZE>0 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 ); #endif return posixUnlock(id, eFileLock, 0); } #if SQLITE_MAX_MMAP_SIZE>0 static int unixMapfile(unixFile *pFd, i64 nByte); static void unixUnmapfile(unixFile *pFd); #endif /* ** This function performs the parts of the "close file" operation ** common to all locking schemes. It closes the directory and file ** handles, if they are valid, and sets all fields of the unixFile ** structure to 0. ** ** It is *not* necessary to hold the mutex when this routine is called, ** even on VxWorks. A mutex will be acquired on VxWorks by the ** vxworksReleaseFileId() routine. */ static int closeUnixFile(sqlite3_file *id){ unixFile *pFile = (unixFile*)id; #if SQLITE_MAX_MMAP_SIZE>0 unixUnmapfile(pFile); #endif if( pFile->h>=0 ){ robust_close(pFile, pFile->h, __LINE__); pFile->h = -1; } #if OS_VXWORKS if( pFile->pId ){ if( pFile->ctrlFlags & UNIXFILE_DELETE ){ osUnlink(pFile->pId->zCanonicalName); } vxworksReleaseFileId(pFile->pId); pFile->pId = 0; } #endif #ifdef SQLITE_UNLINK_AFTER_CLOSE if( pFile->ctrlFlags & UNIXFILE_DELETE ){ osUnlink(pFile->zPath); sqlite3_free(*(char**)&pFile->zPath); pFile->zPath = 0; } #endif OSTRACE(("CLOSE %-3d\n", pFile->h)); OpenCounter(-1); sqlite3_free(pFile->pUnused); memset(pFile, 0, sizeof(unixFile)); return SQLITE_OK; } /* ** Close a file. */ static int unixClose(sqlite3_file *id){ int rc = SQLITE_OK; unixFile *pFile = (unixFile *)id; verifyDbFile(pFile); unixUnlock(id, NO_LOCK); unixEnterMutex(); /* unixFile.pInode is always valid here. Otherwise, a different close ** routine (e.g. nolockClose()) would be called instead. */ assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 ); if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){ /* If there are outstanding locks, do not actually close the file just ** yet because that would clear those locks. Instead, add the file ** descriptor to pInode->pUnused list. It will be automatically closed ** when the last lock is cleared. */ setPendingFd(pFile); } releaseInodeInfo(pFile); rc = closeUnixFile(id); unixLeaveMutex(); return rc; } /************** End of the posix advisory lock implementation ***************** ******************************************************************************/ /****************************************************************************** ****************************** No-op Locking ********************************** ** ** Of the various locking implementations available, this is by far the ** simplest: locking is ignored. No attempt is made to lock the database ** file for reading or writing. ** ** This locking mode is appropriate for use on read-only databases ** (ex: databases that are burned into CD-ROM, for example.) It can ** also be used if the application employs some external mechanism to ** prevent simultaneous access of the same database by two or more ** database connections. But there is a serious risk of database ** corruption if this locking mode is used in situations where multiple ** database connections are accessing the same database file at the same ** time and one or more of those connections are writing. */ static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){ UNUSED_PARAMETER(NotUsed); *pResOut = 0; return SQLITE_OK; } static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return SQLITE_OK; } static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return SQLITE_OK; } /* ** Close the file. */ static int nolockClose(sqlite3_file *id) { return closeUnixFile(id); } /******************* End of the no-op lock implementation ********************* ******************************************************************************/ /****************************************************************************** ************************* Begin dot-file Locking ****************************** ** ** The dotfile locking implementation uses the existence of separate lock ** files (really a directory) to control access to the database. This works ** on just about every filesystem imaginable. But there are serious downsides: ** ** (1) There is zero concurrency. A single reader blocks all other ** connections from reading or writing the database. ** ** (2) An application crash or power loss can leave stale lock files ** sitting around that need to be cleared manually. ** ** Nevertheless, a dotlock is an appropriate locking mode for use if no ** other locking strategy is available. ** ** Dotfile locking works by creating a subdirectory in the same directory as ** the database and with the same name but with a ".lock" extension added. ** The existence of a lock directory implies an EXCLUSIVE lock. All other ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE. */ /* ** The file suffix added to the data base filename in order to create the ** lock directory. */ #define DOTLOCK_SUFFIX ".lock" /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. ** ** In dotfile locking, either a lock exists or it does not. So in this ** variation of CheckReservedLock(), *pResOut is set to true if any lock ** is held on the file and false if the file is unlocked. */ static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); reserved = osAccess((const char*)pFile->lockingContext, 0)==0; OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved)); *pResOut = reserved; return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. ** ** With dotfile locking, we really only support state (4): EXCLUSIVE. ** But we track the other locking levels internally. */ static int dotlockLock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; char *zLockFile = (char *)pFile->lockingContext; int rc = SQLITE_OK; /* If we have any lock, then the lock file already exists. All we have ** to do is adjust our internal record of the lock level. */ if( pFile->eFileLock > NO_LOCK ){ pFile->eFileLock = eFileLock; /* Always update the timestamp on the old file */ #ifdef HAVE_UTIME utime(zLockFile, NULL); #else utimes(zLockFile, NULL); #endif return SQLITE_OK; } /* grab an exclusive lock */ rc = osMkdir(zLockFile, 0777); if( rc<0 ){ /* failed to open/create the lock directory */ int tErrno = errno; if( EEXIST == tErrno ){ rc = SQLITE_BUSY; } else { rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( rc!=SQLITE_BUSY ){ storeLastErrno(pFile, tErrno); } } return rc; } /* got it, set the type and return ok */ pFile->eFileLock = eFileLock; return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. ** ** When the locking level reaches NO_LOCK, delete the lock file. */ static int dotlockUnlock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; char *zLockFile = (char *)pFile->lockingContext; int rc; assert( pFile ); OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock, pFile->eFileLock, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); /* no-op if possible */ if( pFile->eFileLock==eFileLock ){ return SQLITE_OK; } /* To downgrade to shared, simply update our internal notion of the ** lock state. No need to mess with the file on disk. */ if( eFileLock==SHARED_LOCK ){ pFile->eFileLock = SHARED_LOCK; return SQLITE_OK; } /* To fully unlock the database, delete the lock file */ assert( eFileLock==NO_LOCK ); rc = osRmdir(zLockFile); if( rc<0 ){ int tErrno = errno; if( tErrno==ENOENT ){ rc = SQLITE_OK; }else{ rc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, tErrno); } return rc; } pFile->eFileLock = NO_LOCK; return SQLITE_OK; } /* ** Close a file. Make sure the lock has been released before closing. */ static int dotlockClose(sqlite3_file *id) { unixFile *pFile = (unixFile*)id; assert( id!=0 ); dotlockUnlock(id, NO_LOCK); sqlite3_free(pFile->lockingContext); return closeUnixFile(id); } /****************** End of the dot-file lock implementation ******************* ******************************************************************************/ /****************************************************************************** ************************** Begin flock Locking ******************************** ** ** Use the flock() system call to do file locking. ** ** flock() locking is like dot-file locking in that the various ** fine-grain locking levels supported by SQLite are collapsed into ** a single exclusive lock. In other words, SHARED, RESERVED, and ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite ** still works when you do this, but concurrency is reduced since ** only a single process can be reading the database at a time. ** ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off */ #if SQLITE_ENABLE_LOCKING_STYLE /* ** Retry flock() calls that fail with EINTR */ #ifdef EINTR static int robust_flock(int fd, int op){ int rc; do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR ); return rc; } #else # define robust_flock(a,b) flock(a,b) #endif /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); /* Check if a thread in this process holds such a lock */ if( pFile->eFileLock>SHARED_LOCK ){ reserved = 1; } /* Otherwise see if some other process holds it. */ if( !reserved ){ /* attempt to get the lock */ int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB); if( !lrc ){ /* got the lock, unlock it */ lrc = robust_flock(pFile->h, LOCK_UN); if ( lrc ) { int tErrno = errno; /* unlock failed with an error */ lrc = SQLITE_IOERR_UNLOCK; storeLastErrno(pFile, tErrno); rc = lrc; } } else { int tErrno = errno; reserved = 1; /* someone else might have it reserved */ lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( IS_LOCK_ERROR(lrc) ){ storeLastErrno(pFile, tErrno); rc = lrc; } } } OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved)); #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ rc = SQLITE_OK; reserved=1; } #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ *pResOut = reserved; return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** flock() only really support EXCLUSIVE locks. We track intermediate ** lock states in the sqlite3_file structure, but all locks SHARED or ** above are really EXCLUSIVE locks and exclude all other processes from ** access the file. ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int flockLock(sqlite3_file *id, int eFileLock) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; assert( pFile ); /* if we already have a lock, it is exclusive. ** Just adjust level and punt on outta here. */ if (pFile->eFileLock > NO_LOCK) { pFile->eFileLock = eFileLock; return SQLITE_OK; } /* grab an exclusive lock */ if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) { int tErrno = errno; /* didn't get, must be busy */ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); if( IS_LOCK_ERROR(rc) ){ storeLastErrno(pFile, tErrno); } } else { /* got it, set the type and return ok */ pFile->eFileLock = eFileLock; } OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ rc = SQLITE_BUSY; } #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int flockUnlock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; assert( pFile ); OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock, pFile->eFileLock, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); /* no-op if possible */ if( pFile->eFileLock==eFileLock ){ return SQLITE_OK; } /* shared can just be set because we always have an exclusive */ if (eFileLock==SHARED_LOCK) { pFile->eFileLock = eFileLock; return SQLITE_OK; } /* no, really, unlock. */ if( robust_flock(pFile->h, LOCK_UN) ){ #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS return SQLITE_OK; #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ return SQLITE_IOERR_UNLOCK; }else{ pFile->eFileLock = NO_LOCK; return SQLITE_OK; } } /* ** Close a file. */ static int flockClose(sqlite3_file *id) { assert( id!=0 ); flockUnlock(id, NO_LOCK); return closeUnixFile(id); } #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */ /******************* End of the flock lock implementation ********************* ******************************************************************************/ /****************************************************************************** ************************ Begin Named Semaphore Locking ************************ ** ** Named semaphore locking is only supported on VxWorks. ** ** Semaphore locking is like dot-lock and flock in that it really only ** supports EXCLUSIVE locking. Only a single process can read or write ** the database file at a time. This reduces potential concurrency, but ** makes the lock implementation much easier. */ #if OS_VXWORKS /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) { int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); /* Check if a thread in this process holds such a lock */ if( pFile->eFileLock>SHARED_LOCK ){ reserved = 1; } /* Otherwise see if some other process holds it. */ if( !reserved ){ sem_t *pSem = pFile->pInode->pSem; if( sem_trywait(pSem)==-1 ){ int tErrno = errno; if( EAGAIN != tErrno ){ rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK); storeLastErrno(pFile, tErrno); } else { /* someone else has the lock when we are in NO_LOCK */ reserved = (pFile->eFileLock < SHARED_LOCK); } }else{ /* we could have it if we want it */ sem_post(pSem); } } OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved)); *pResOut = reserved; return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate ** lock states in the sqlite3_file structure, but all locks SHARED or ** above are really EXCLUSIVE locks and exclude all other processes from ** access the file. ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int semXLock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; sem_t *pSem = pFile->pInode->pSem; int rc = SQLITE_OK; /* if we already have a lock, it is exclusive. ** Just adjust level and punt on outta here. */ if (pFile->eFileLock > NO_LOCK) { pFile->eFileLock = eFileLock; rc = SQLITE_OK; goto sem_end_lock; } /* lock semaphore now but bail out when already locked. */ if( sem_trywait(pSem)==-1 ){ rc = SQLITE_BUSY; goto sem_end_lock; } /* got it, set the type and return ok */ pFile->eFileLock = eFileLock; sem_end_lock: return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int semXUnlock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; sem_t *pSem = pFile->pInode->pSem; assert( pFile ); assert( pSem ); OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock, pFile->eFileLock, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); /* no-op if possible */ if( pFile->eFileLock==eFileLock ){ return SQLITE_OK; } /* shared can just be set because we always have an exclusive */ if (eFileLock==SHARED_LOCK) { pFile->eFileLock = eFileLock; return SQLITE_OK; } /* no, really unlock. */ if ( sem_post(pSem)==-1 ) { int rc, tErrno = errno; rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); if( IS_LOCK_ERROR(rc) ){ storeLastErrno(pFile, tErrno); } return rc; } pFile->eFileLock = NO_LOCK; return SQLITE_OK; } /* ** Close a file. */ static int semXClose(sqlite3_file *id) { if( id ){ unixFile *pFile = (unixFile*)id; semXUnlock(id, NO_LOCK); assert( pFile ); unixEnterMutex(); releaseInodeInfo(pFile); unixLeaveMutex(); closeUnixFile(id); } return SQLITE_OK; } #endif /* OS_VXWORKS */ /* ** Named semaphore locking is only available on VxWorks. ** *************** End of the named semaphore lock implementation **************** ******************************************************************************/ /****************************************************************************** *************************** Begin AFP Locking ********************************* ** ** AFP is the Apple Filing Protocol. AFP is a network filesystem found ** on Apple Macintosh computers - both OS9 and OSX. ** ** Third-party implementations of AFP are available. But this code here ** only works on OSX. */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** The afpLockingContext structure contains all afp lock specific state */ typedef struct afpLockingContext afpLockingContext; struct afpLockingContext { int reserved; const char *dbPath; /* Name of the open file */ }; struct ByteRangeLockPB2 { unsigned long long offset; /* offset to first byte to lock */ unsigned long long length; /* nbr of bytes to lock */ unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */ unsigned char unLockFlag; /* 1 = unlock, 0 = lock */ unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */ int fd; /* file desc to assoc this lock with */ }; #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2) /* ** This is a utility for setting or clearing a bit-range lock on an ** AFP filesystem. ** ** Return SQLITE_OK on success, SQLITE_BUSY on failure. */ static int afpSetLock( const char *path, /* Name of the file to be locked or unlocked */ unixFile *pFile, /* Open file descriptor on path */ unsigned long long offset, /* First byte to be locked */ unsigned long long length, /* Number of bytes to lock */ int setLockFlag /* True to set lock. False to clear lock */ ){ struct ByteRangeLockPB2 pb; int err; pb.unLockFlag = setLockFlag ? 0 : 1; pb.startEndFlag = 0; pb.offset = offset; pb.length = length; pb.fd = pFile->h; OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""), offset, length)); err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0); if ( err==-1 ) { int rc; int tErrno = errno; OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n", path, tErrno, strerror(tErrno))); #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS rc = SQLITE_BUSY; #else rc = sqliteErrorFromPosixError(tErrno, setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */ if( IS_LOCK_ERROR(rc) ){ storeLastErrno(pFile, tErrno); } return rc; } else { return SQLITE_OK; } } /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; afpLockingContext *context; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); assert( pFile ); context = (afpLockingContext *) pFile->lockingContext; if( context->reserved ){ *pResOut = 1; return SQLITE_OK; } unixEnterMutex(); /* Because pFile->pInode is shared across threads */ /* Check if a thread in this process holds such a lock */ if( pFile->pInode->eFileLock>SHARED_LOCK ){ reserved = 1; } /* Otherwise see if some other process holds it. */ if( !reserved ){ /* lock the RESERVED byte */ int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); if( SQLITE_OK==lrc ){ /* if we succeeded in taking the reserved lock, unlock it to restore ** the original state */ lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); } else { /* if we failed to get the lock then someone else must have it */ reserved = 1; } if( IS_LOCK_ERROR(lrc) ){ rc=lrc; } } unixLeaveMutex(); OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved)); *pResOut = reserved; return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int afpLock(sqlite3_file *id, int eFileLock){ int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode = pFile->pInode; afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; assert( pFile ); OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h, azFileLock(eFileLock), azFileLock(pFile->eFileLock), azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0))); /* If there is already a lock of this type or more restrictive on the ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as ** unixEnterMutex() hasn't been called yet. */ if( pFile->eFileLock>=eFileLock ){ OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h, azFileLock(eFileLock))); return SQLITE_OK; } /* Make sure the locking sequence is correct ** (1) We never move from unlocked to anything higher than shared lock. ** (2) SQLite never explicitly requests a pendig lock. ** (3) A shared lock is always held when a reserve lock is requested. */ assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); assert( eFileLock!=PENDING_LOCK ); assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); /* This mutex is needed because pFile->pInode is shared across threads */ unixEnterMutex(); pInode = pFile->pInode; /* If some thread using this PID has a lock via a different unixFile* ** handle that precludes the requested lock, return BUSY. */ if( (pFile->eFileLock!=pInode->eFileLock && (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) ){ rc = SQLITE_BUSY; goto afp_end_lock; } /* If a SHARED lock is requested, and some thread using this PID already ** has a SHARED or RESERVED lock, then increment reference counts and ** return SQLITE_OK. */ if( eFileLock==SHARED_LOCK && (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ assert( eFileLock==SHARED_LOCK ); assert( pFile->eFileLock==0 ); assert( pInode->nShared>0 ); pFile->eFileLock = SHARED_LOCK; pInode->nShared++; pInode->nLock++; goto afp_end_lock; } /* A PENDING lock is needed before acquiring a SHARED lock and before ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will ** be released. */ if( eFileLock==SHARED_LOCK || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK) ){ int failed; failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1); if (failed) { rc = failed; goto afp_end_lock; } } /* If control gets to this point, then actually go ahead and make ** operating system calls for the specified lock. */ if( eFileLock==SHARED_LOCK ){ int lrc1, lrc2, lrc1Errno = 0; long lk, mask; assert( pInode->nShared==0 ); assert( pInode->eFileLock==0 ); mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff; /* Now get the read-lock SHARED_LOCK */ /* note that the quality of the randomness doesn't matter that much */ lk = random(); pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1); lrc1 = afpSetLock(context->dbPath, pFile, SHARED_FIRST+pInode->sharedByte, 1, 1); if( IS_LOCK_ERROR(lrc1) ){ lrc1Errno = pFile->lastErrno; } /* Drop the temporary PENDING lock */ lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); if( IS_LOCK_ERROR(lrc1) ) { storeLastErrno(pFile, lrc1Errno); rc = lrc1; goto afp_end_lock; } else if( IS_LOCK_ERROR(lrc2) ){ rc = lrc2; goto afp_end_lock; } else if( lrc1 != SQLITE_OK ) { rc = lrc1; } else { pFile->eFileLock = SHARED_LOCK; pInode->nLock++; pInode->nShared = 1; } }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ /* We are trying for an exclusive lock but another thread in this ** same process is still holding a shared lock. */ rc = SQLITE_BUSY; }else{ /* The request was for a RESERVED or EXCLUSIVE lock. It is ** assumed that there is a SHARED or greater lock on the file ** already. */ int failed = 0; assert( 0!=pFile->eFileLock ); if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) { /* Acquire a RESERVED lock */ failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); if( !failed ){ context->reserved = 1; } } if (!failed && eFileLock == EXCLUSIVE_LOCK) { /* Acquire an EXCLUSIVE lock */ /* Remove the shared lock before trying the range. we'll need to ** reestablish the shared lock if we can't get the afpUnlock */ if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST + pInode->sharedByte, 1, 0)) ){ int failed2 = SQLITE_OK; /* now attemmpt to get the exclusive lock range */ failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 1); if( failed && (failed2 = afpSetLock(context->dbPath, pFile, SHARED_FIRST + pInode->sharedByte, 1, 1)) ){ /* Can't reestablish the shared lock. Sqlite can't deal, this is ** a critical I/O error */ rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : SQLITE_IOERR_LOCK; goto afp_end_lock; } }else{ rc = failed; } } if( failed ){ rc = failed; } } if( rc==SQLITE_OK ){ pFile->eFileLock = eFileLock; pInode->eFileLock = eFileLock; }else if( eFileLock==EXCLUSIVE_LOCK ){ pFile->eFileLock = PENDING_LOCK; pInode->eFileLock = PENDING_LOCK; } afp_end_lock: unixLeaveMutex(); OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int afpUnlock(sqlite3_file *id, int eFileLock) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode; afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; int skipShared = 0; #ifdef SQLITE_TEST int h = pFile->h; #endif assert( pFile ); OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock, pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, osGetpid(0))); assert( eFileLock<=SHARED_LOCK ); if( pFile->eFileLock<=eFileLock ){ return SQLITE_OK; } unixEnterMutex(); pInode = pFile->pInode; assert( pInode->nShared!=0 ); if( pFile->eFileLock>SHARED_LOCK ){ assert( pInode->eFileLock==pFile->eFileLock ); SimulateIOErrorBenign(1); SimulateIOError( h=(-1) ) SimulateIOErrorBenign(0); #ifdef SQLITE_DEBUG /* When reducing a lock such that other processes can start ** reading the database file again, make sure that the ** transaction counter was updated if any part of the database ** file changed. If the transaction counter is not updated, ** other connections to the same file might not realize that ** the file has changed and hence might not know to flush their ** cache. The use of a stale cache can lead to database corruption. */ assert( pFile->inNormalWrite==0 || pFile->dbUpdate==0 || pFile->transCntrChng==1 ); pFile->inNormalWrite = 0; #endif if( pFile->eFileLock==EXCLUSIVE_LOCK ){ rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0); if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){ /* only re-establish the shared lock if necessary */ int sharedLockByte = SHARED_FIRST+pInode->sharedByte; rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1); } else { skipShared = 1; } } if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){ rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); } if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){ rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); if( !rc ){ context->reserved = 0; } } if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){ pInode->eFileLock = SHARED_LOCK; } } if( rc==SQLITE_OK && eFileLock==NO_LOCK ){ /* Decrement the shared lock counter. Release the lock using an ** OS call only when all threads in this same process have released ** the lock. */ unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte; pInode->nShared--; if( pInode->nShared==0 ){ SimulateIOErrorBenign(1); SimulateIOError( h=(-1) ) SimulateIOErrorBenign(0); if( !skipShared ){ rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0); } if( !rc ){ pInode->eFileLock = NO_LOCK; pFile->eFileLock = NO_LOCK; } } if( rc==SQLITE_OK ){ pInode->nLock--; assert( pInode->nLock>=0 ); if( pInode->nLock==0 ){ closePendingFds(pFile); } } } unixLeaveMutex(); if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock; return rc; } /* ** Close a file & cleanup AFP specific locking context */ static int afpClose(sqlite3_file *id) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; assert( id!=0 ); afpUnlock(id, NO_LOCK); unixEnterMutex(); if( pFile->pInode && pFile->pInode->nLock ){ /* If there are outstanding locks, do not actually close the file just ** yet because that would clear those locks. Instead, add the file ** descriptor to pInode->aPending. It will be automatically closed when ** the last lock is cleared. */ setPendingFd(pFile); } releaseInodeInfo(pFile); sqlite3_free(pFile->lockingContext); rc = closeUnixFile(id); unixLeaveMutex(); return rc; } #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ /* ** The code above is the AFP lock implementation. The code is specific ** to MacOSX and does not work on other unix platforms. No alternative ** is available. If you don't compile for a mac, then the "unix-afp" ** VFS is not available. ** ********************* End of the AFP lock implementation ********************** ******************************************************************************/ /****************************************************************************** *************************** Begin NFS Locking ********************************/ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int nfsUnlock(sqlite3_file *id, int eFileLock){ return posixUnlock(id, eFileLock, 1); } #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ /* ** The code above is the NFS lock implementation. The code is specific ** to MacOSX and does not work on other unix platforms. No alternative ** is available. ** ********************* End of the NFS lock implementation ********************** ******************************************************************************/ /****************************************************************************** **************** Non-locking sqlite3_file methods ***************************** ** ** The next division contains implementations for all methods of the ** sqlite3_file object other than the locking methods. The locking ** methods were defined in divisions above (one locking method per ** division). Those methods that are common to all locking modes ** are gather together into this division. */ /* ** Seek to the offset passed as the second argument, then read cnt ** bytes into pBuf. Return the number of bytes actually read. ** ** NB: If you define USE_PREAD or USE_PREAD64, then it might also ** be necessary to define _XOPEN_SOURCE to be 500. This varies from ** one system to another. Since SQLite does not define USE_PREAD ** in any form by default, we will not attempt to define _XOPEN_SOURCE. ** See tickets #2741 and #2681. ** ** To avoid stomping the errno value on a failed read the lastErrno value ** is set before returning. */ static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ int got; int prior = 0; #if (!defined(USE_PREAD) && !defined(USE_PREAD64)) i64 newOffset; #endif TIMER_START; assert( cnt==(cnt&0x1ffff) ); assert( id->h>2 ); do{ #if defined(USE_PREAD) got = osPread(id->h, pBuf, cnt, offset); SimulateIOError( got = -1 ); #elif defined(USE_PREAD64) got = osPread64(id->h, pBuf, cnt, offset); SimulateIOError( got = -1 ); #else newOffset = lseek(id->h, offset, SEEK_SET); SimulateIOError( newOffset = -1 ); if( newOffset<0 ){ storeLastErrno((unixFile*)id, errno); return -1; } got = osRead(id->h, pBuf, cnt); #endif if( got==cnt ) break; if( got<0 ){ if( errno==EINTR ){ got = 1; continue; } prior = 0; storeLastErrno((unixFile*)id, errno); break; }else if( got>0 ){ cnt -= got; offset += got; prior += got; pBuf = (void*)(got + (char*)pBuf); } }while( got>0 ); TIMER_END; OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got+prior, offset-prior, TIMER_ELAPSED)); return got+prior; } /* ** Read data from a file into a buffer. Return SQLITE_OK if all ** bytes were read successfully and SQLITE_IOERR if anything goes ** wrong. */ static int unixRead( sqlite3_file *id, void *pBuf, int amt, sqlite3_int64 offset ){ unixFile *pFile = (unixFile *)id; int got; assert( id ); assert( offset>=0 ); assert( amt>0 ); /* If this is a database file (not a journal, master-journal or temp ** file), the bytes in the locking range should never be read or written. */ #if 0 assert( pFile->pUnused==0 || offset>=PENDING_BYTE+512 || offset+amt<=PENDING_BYTE ); #endif #if SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this read request as possible by transfering ** data from the memory mapping using memcpy(). */ if( offset<pFile->mmapSize ){ if( offset+amt <= pFile->mmapSize ){ memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); return SQLITE_OK; }else{ int nCopy = pFile->mmapSize - offset; memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; } } #endif got = seekAndRead(pFile, offset, pBuf, amt); if( got==amt ){ return SQLITE_OK; }else if( got<0 ){ /* lastErrno set by seekAndRead */ return SQLITE_IOERR_READ; }else{ storeLastErrno(pFile, 0); /* not a system error */ /* Unread parts of the buffer must be zero-filled */ memset(&((char*)pBuf)[got], 0, amt-got); return SQLITE_IOERR_SHORT_READ; } } /* ** Attempt to seek the file-descriptor passed as the first argument to ** absolute offset iOff, then attempt to write nBuf bytes of data from ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, ** return the actual number of bytes written (which may be less than ** nBuf). */ static int seekAndWriteFd( int fd, /* File descriptor to write to */ i64 iOff, /* File offset to begin writing at */ const void *pBuf, /* Copy data from this buffer to the file */ int nBuf, /* Size of buffer pBuf in bytes */ int *piErrno /* OUT: Error number if error occurs */ ){ int rc = 0; /* Value returned by system call */ assert( nBuf==(nBuf&0x1ffff) ); assert( fd>2 ); assert( piErrno!=0 ); nBuf &= 0x1ffff; TIMER_START; #if defined(USE_PREAD) do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR ); #elif defined(USE_PREAD64) do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR); #else do{ i64 iSeek = lseek(fd, iOff, SEEK_SET); SimulateIOError( iSeek = -1 ); if( iSeek<0 ){ rc = -1; break; } rc = osWrite(fd, pBuf, nBuf); }while( rc<0 && errno==EINTR ); #endif TIMER_END; OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); if( rc<0 ) *piErrno = errno; return rc; } /* ** Seek to the offset in id->offset then read cnt bytes into pBuf. ** Return the number of bytes actually read. Update the offset. ** ** To avoid stomping the errno value on a failed write the lastErrno value ** is set before returning. */ static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); } /* ** Write data from a buffer into a file. Return SQLITE_OK on success ** or some other error code on failure. */ static int unixWrite( sqlite3_file *id, const void *pBuf, int amt, sqlite3_int64 offset ){ unixFile *pFile = (unixFile*)id; int wrote = 0; assert( id ); assert( amt>0 ); /* If this is a database file (not a journal, master-journal or temp ** file), the bytes in the locking range should never be read or written. */ #if 0 assert( pFile->pUnused==0 || offset>=PENDING_BYTE+512 || offset+amt<=PENDING_BYTE ); #endif #ifdef SQLITE_DEBUG /* If we are doing a normal write to a database file (as opposed to ** doing a hot-journal rollback or a write to some file other than a ** normal database file) then record the fact that the database ** has changed. If the transaction counter is modified, record that ** fact too. */ if( pFile->inNormalWrite ){ pFile->dbUpdate = 1; /* The database has been modified */ if( offset<=24 && offset+amt>=27 ){ int rc; char oldCntr[4]; SimulateIOErrorBenign(1); rc = seekAndRead(pFile, 24, oldCntr, 4); SimulateIOErrorBenign(0); if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ pFile->transCntrChng = 1; /* The transaction counter has changed */ } } } #endif #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this write request as possible by transfering ** data from the memory mapping using memcpy(). */ if( offset<pFile->mmapSize ){ if( offset+amt <= pFile->mmapSize ){ memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); return SQLITE_OK; }else{ int nCopy = pFile->mmapSize - offset; memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; } } #endif while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){ amt -= wrote; offset += wrote; pBuf = &((char*)pBuf)[wrote]; } SimulateIOError(( wrote=(-1), amt=1 )); SimulateDiskfullError(( wrote=0, amt=1 )); if( amt>wrote ){ if( wrote<0 && pFile->lastErrno!=ENOSPC ){ /* lastErrno set by seekAndWrite */ return SQLITE_IOERR_WRITE; }else{ storeLastErrno(pFile, 0); /* not a system error */ return SQLITE_FULL; } } return SQLITE_OK; } #ifdef SQLITE_TEST /* ** Count the number of fullsyncs and normal syncs. This is used to test ** that syncs and fullsyncs are occurring at the right times. */ SQLITE_API int sqlite3_sync_count = 0; SQLITE_API int sqlite3_fullsync_count = 0; #endif /* ** We do not trust systems to provide a working fdatasync(). Some do. ** Others do no. To be safe, we will stick with the (slightly slower) ** fsync(). If you know that your system does support fdatasync() correctly, ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC */ #if !defined(fdatasync) && !HAVE_FDATASYNC # define fdatasync fsync #endif /* ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently ** only available on Mac OS X. But that could change. */ #ifdef F_FULLFSYNC # define HAVE_FULLFSYNC 1 #else # define HAVE_FULLFSYNC 0 #endif /* ** The fsync() system call does not work as advertised on many ** unix systems. The following procedure is an attempt to make ** it work better. ** ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful ** for testing when we want to run through the test suite quickly. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash ** or power failure will likely corrupt the database file. ** ** SQLite sets the dataOnly flag if the size of the file is unchanged. ** The idea behind dataOnly is that it should only write the file content ** to disk, not the inode. We only set dataOnly if the file size is ** unchanged since the file size is part of the inode. However, ** Ted Ts'o tells us that fdatasync() will also write the inode if the ** file size has changed. The only real difference between fdatasync() ** and fsync(), Ted tells us, is that fdatasync() will not flush the ** inode if the mtime or owner or other inode attributes have changed. ** We only care about the file size, not the other file attributes, so ** as far as SQLite is concerned, an fdatasync() is always adequate. ** So, we always use fdatasync() if it is available, regardless of ** the value of the dataOnly flag. */ static int full_fsync(int fd, int fullSync, int dataOnly){ int rc; /* The following "ifdef/elif/else/" block has the same structure as ** the one below. It is replicated here solely to avoid cluttering ** up the real code with the UNUSED_PARAMETER() macros. */ #ifdef SQLITE_NO_SYNC UNUSED_PARAMETER(fd); UNUSED_PARAMETER(fullSync); UNUSED_PARAMETER(dataOnly); #elif HAVE_FULLFSYNC UNUSED_PARAMETER(dataOnly); #else UNUSED_PARAMETER(fullSync); UNUSED_PARAMETER(dataOnly); #endif /* Record the number of times that we do a normal fsync() and ** FULLSYNC. This is used during testing to verify that this procedure ** gets called with the correct arguments. */ #ifdef SQLITE_TEST if( fullSync ) sqlite3_fullsync_count++; sqlite3_sync_count++; #endif /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a ** no-op. But go ahead and call fstat() to validate the file ** descriptor as we need a method to provoke a failure during ** coverate testing. */ #ifdef SQLITE_NO_SYNC { struct stat buf; rc = osFstat(fd, &buf); } #elif HAVE_FULLFSYNC if( fullSync ){ rc = osFcntl(fd, F_FULLFSYNC, 0); }else{ rc = 1; } /* If the FULLFSYNC failed, fall back to attempting an fsync(). ** It shouldn't be possible for fullfsync to fail on the local ** file system (on OSX), so failure indicates that FULLFSYNC ** isn't supported for this file system. So, attempt an fsync ** and (for now) ignore the overhead of a superfluous fcntl call. ** It'd be better to detect fullfsync support once and avoid ** the fcntl call every time sync is called. */ if( rc ) rc = fsync(fd); #elif defined(__APPLE__) /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly ** so currently we default to the macro that redefines fdatasync to fsync */ rc = fsync(fd); #else rc = fdatasync(fd); #if OS_VXWORKS if( rc==-1 && errno==ENOTSUP ){ rc = fsync(fd); } #endif /* OS_VXWORKS */ #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ if( OS_VXWORKS && rc!= -1 ){ rc = 0; } return rc; } /* ** Open a file descriptor to the directory containing file zFilename. ** If successful, *pFd is set to the opened file descriptor and ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined ** value. ** ** The directory file descriptor is used for only one thing - to ** fsync() a directory to make sure file creation and deletion events ** are flushed to disk. Such fsyncs are not needed on newer ** journaling filesystems, but are required on older filesystems. ** ** This routine can be overridden using the xSetSysCall interface. ** The ability to override this routine was added in support of the ** chromium sandbox. Opening a directory is a security risk (we are ** told) so making it overrideable allows the chromium sandbox to ** replace this routine with a harmless no-op. To make this routine ** a no-op, replace it with a stub that returns SQLITE_OK but leaves ** *pFd set to a negative number. ** ** If SQLITE_OK is returned, the caller is responsible for closing ** the file descriptor *pFd using close(). */ static int openDirectory(const char *zFilename, int *pFd){ int ii; int fd = -1; char zDirname[MAX_PATHNAME+1]; sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--); if( ii>0 ){ zDirname[ii] = '\0'; }else{ if( zDirname[0]!='/' ) zDirname[0] = '.'; zDirname[1] = 0; } fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0); if( fd>=0 ){ OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); } *pFd = fd; if( fd>=0 ) return SQLITE_OK; return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname); } /* ** Make sure all writes to a particular file are committed to disk. ** ** If dataOnly==0 then both the file itself and its metadata (file ** size, access time, etc) are synced. If dataOnly!=0 then only the ** file data is synced. ** ** Under Unix, also make sure that the directory entry for the file ** has been created by fsync-ing the directory that contains the file. ** If we do not do this and we encounter a power failure, the directory ** entry for the journal might not exist after we reboot. The next ** SQLite to access the file will not know that the journal exists (because ** the directory entry for the journal was never created) and the transaction ** will not roll back - possibly leading to database corruption. */ static int unixSync(sqlite3_file *id, int flags){ int rc; unixFile *pFile = (unixFile*)id; int isDataOnly = (flags&SQLITE_SYNC_DATAONLY); int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL; /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ assert((flags&0x0F)==SQLITE_SYNC_NORMAL || (flags&0x0F)==SQLITE_SYNC_FULL ); /* Unix cannot, but some systems may return SQLITE_FULL from here. This ** line is to test that doing so does not cause any problems. */ SimulateDiskfullError( return SQLITE_FULL ); assert( pFile ); OSTRACE(("SYNC %-3d\n", pFile->h)); rc = full_fsync(pFile->h, isFullsync, isDataOnly); SimulateIOError( rc=1 ); if( rc ){ storeLastErrno(pFile, errno); return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath); } /* Also fsync the directory containing the file if the DIRSYNC flag ** is set. This is a one-time occurrence. Many systems (examples: AIX) ** are unable to fsync a directory, so ignore errors on the fsync. */ if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){ int dirfd; OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, HAVE_FULLFSYNC, isFullsync)); rc = osOpenDirectory(pFile->zPath, &dirfd); if( rc==SQLITE_OK ){ full_fsync(dirfd, 0, 0); robust_close(pFile, dirfd, __LINE__); }else{ assert( rc==SQLITE_CANTOPEN ); rc = SQLITE_OK; } pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC; } return rc; } /* ** Truncate an open file to a specified size */ static int unixTruncate(sqlite3_file *id, i64 nByte){ unixFile *pFile = (unixFile *)id; int rc; assert( pFile ); SimulateIOError( return SQLITE_IOERR_TRUNCATE ); /* If the user has configured a chunk-size for this file, truncate the ** file so that it consists of an integer number of chunks (i.e. the ** actual file size after the operation may be larger than the requested ** size). */ if( pFile->szChunk>0 ){ nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; } rc = robust_ftruncate(pFile->h, nByte); if( rc ){ storeLastErrno(pFile, errno); return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); }else{ #ifdef SQLITE_DEBUG /* If we are doing a normal write to a database file (as opposed to ** doing a hot-journal rollback or a write to some file other than a ** normal database file) and we truncate the file to zero length, ** that effectively updates the change counter. This might happen ** when restoring a database using the backup API from a zero-length ** source. */ if( pFile->inNormalWrite && nByte==0 ){ pFile->transCntrChng = 1; } #endif #if SQLITE_MAX_MMAP_SIZE>0 /* If the file was just truncated to a size smaller than the currently ** mapped region, reduce the effective mapping size as well. SQLite will ** use read() and write() to access data beyond this point from now on. */ if( nByte<pFile->mmapSize ){ pFile->mmapSize = nByte; } #endif return SQLITE_OK; } } /* ** Determine the current size of a file in bytes */ static int unixFileSize(sqlite3_file *id, i64 *pSize){ int rc; struct stat buf; assert( id ); rc = osFstat(((unixFile*)id)->h, &buf); SimulateIOError( rc=1 ); if( rc!=0 ){ storeLastErrno((unixFile*)id, errno); return SQLITE_IOERR_FSTAT; } *pSize = buf.st_size; /* When opening a zero-size database, the findInodeInfo() procedure ** writes a single byte into that file in order to work around a bug ** in the OS-X msdos filesystem. In order to avoid problems with upper ** layers, we need to report this file size as zero even though it is ** really 1. Ticket #3260. */ if( *pSize==1 ) *pSize = 0; return SQLITE_OK; } #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) /* ** Handler for proxy-locking file-control verbs. Defined below in the ** proxying locking division. */ static int proxyFileControl(sqlite3_file*,int,void*); #endif /* ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT ** file-control operation. Enlarge the database to nBytes in size ** (rounded up to the next chunk-size). If the database is already ** nBytes or larger, this routine is a no-op. */ static int fcntlSizeHint(unixFile *pFile, i64 nByte){ if( pFile->szChunk>0 ){ i64 nSize; /* Required file size */ struct stat buf; /* Used to hold return values of fstat() */ if( osFstat(pFile->h, &buf) ){ return SQLITE_IOERR_FSTAT; } nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; if( nSize>(i64)buf.st_size ){ #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE /* The code below is handling the return value of osFallocate() ** correctly. posix_fallocate() is defined to "returns zero on success, ** or an error number on failure". See the manpage for details. */ int err; do{ err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size); }while( err==EINTR ); if( err ) return SQLITE_IOERR_WRITE; #else /* If the OS does not have posix_fallocate(), fake it. Write a ** single byte to the last byte in each block that falls entirely ** within the extended region. Then, if required, a single byte ** at offset (nSize-1), to set the size of the file correctly. ** This is a similar technique to that used by glibc on systems ** that do not have a real fallocate() call. */ int nBlk = buf.st_blksize; /* File-system block size */ int nWrite = 0; /* Number of bytes written by seekAndWrite */ i64 iWrite; /* Next offset to write to */ iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1; assert( iWrite>=buf.st_size ); assert( ((iWrite+1)%nBlk)==0 ); for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){ if( iWrite>=nSize ) iWrite = nSize - 1; nWrite = seekAndWrite(pFile, iWrite, "", 1); if( nWrite!=1 ) return SQLITE_IOERR_WRITE; } #endif } } #if SQLITE_MAX_MMAP_SIZE>0 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){ int rc; if( pFile->szChunk<=0 ){ if( robust_ftruncate(pFile->h, nByte) ){ storeLastErrno(pFile, errno); return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); } } rc = unixMapfile(pFile, nByte); return rc; } #endif return SQLITE_OK; } /* ** If *pArg is initially negative then this is a query. Set *pArg to ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. ** ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. */ static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){ if( *pArg<0 ){ *pArg = (pFile->ctrlFlags & mask)!=0; }else if( (*pArg)==0 ){ pFile->ctrlFlags &= ~mask; }else{ pFile->ctrlFlags |= mask; } } /* Forward declaration */ static int unixGetTempname(int nBuf, char *zBuf); /* ** Information and control of an open file handle. */ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ unixFile *pFile = (unixFile*)id; switch( op ){ case SQLITE_FCNTL_LOCKSTATE: { *(int*)pArg = pFile->eFileLock; return SQLITE_OK; } case SQLITE_FCNTL_LAST_ERRNO: { *(int*)pArg = pFile->lastErrno; return SQLITE_OK; } case SQLITE_FCNTL_CHUNK_SIZE: { pFile->szChunk = *(int *)pArg; return SQLITE_OK; } case SQLITE_FCNTL_SIZE_HINT: { int rc; SimulateIOErrorBenign(1); rc = fcntlSizeHint(pFile, *(i64 *)pArg); SimulateIOErrorBenign(0); return rc; } case SQLITE_FCNTL_PERSIST_WAL: { unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg); return SQLITE_OK; } case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg); return SQLITE_OK; } case SQLITE_FCNTL_VFSNAME: { *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); return SQLITE_OK; } case SQLITE_FCNTL_TEMPFILENAME: { char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname ); if( zTFile ){ unixGetTempname(pFile->pVfs->mxPathname, zTFile); *(char**)pArg = zTFile; } return SQLITE_OK; } case SQLITE_FCNTL_HAS_MOVED: { *(int*)pArg = fileHasMoved(pFile); return SQLITE_OK; } #if SQLITE_MAX_MMAP_SIZE>0 case SQLITE_FCNTL_MMAP_SIZE: { i64 newLimit = *(i64*)pArg; int rc = SQLITE_OK; if( newLimit>sqlite3GlobalConfig.mxMmap ){ newLimit = sqlite3GlobalConfig.mxMmap; } *(i64*)pArg = pFile->mmapSizeMax; if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ pFile->mmapSizeMax = newLimit; if( pFile->mmapSize>0 ){ unixUnmapfile(pFile); rc = unixMapfile(pFile, -1); } } return rc; } #endif #ifdef SQLITE_DEBUG /* The pager calls this method to signal that it has done ** a rollback and that the database is therefore unchanged and ** it hence it is OK for the transaction change counter to be ** unchanged. */ case SQLITE_FCNTL_DB_UNCHANGED: { ((unixFile*)id)->dbUpdate = 0; return SQLITE_OK; } #endif #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) case SQLITE_FCNTL_SET_LOCKPROXYFILE: case SQLITE_FCNTL_GET_LOCKPROXYFILE: { return proxyFileControl(id,op,pArg); } #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */ } return SQLITE_NOTFOUND; } /* ** Return the sector size in bytes of the underlying block device for ** the specified file. This is almost always 512 bytes, but may be ** larger for some devices. ** ** SQLite code assumes this function cannot fail. It also assumes that ** if two files are created in the same file-system directory (i.e. ** a database and its journal file) that the sector size will be the ** same for both. */ #ifndef __QNXNTO__ static int unixSectorSize(sqlite3_file *NotUsed){ UNUSED_PARAMETER(NotUsed); return SQLITE_DEFAULT_SECTOR_SIZE; } #endif /* ** The following version of unixSectorSize() is optimized for QNX. */ #ifdef __QNXNTO__ #include <sys/dcmd_blk.h> #include <sys/statvfs.h> static int unixSectorSize(sqlite3_file *id){ unixFile *pFile = (unixFile*)id; if( pFile->sectorSize == 0 ){ struct statvfs fsInfo; /* Set defaults for non-supported filesystems */ pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; pFile->deviceCharacteristics = 0; if( fstatvfs(pFile->h, &fsInfo) == -1 ) { return pFile->sectorSize; } if( !strcmp(fsInfo.f_basetype, "tmp") ) { pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until ** the write succeeds */ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else if( strstr(fsInfo.f_basetype, "etfs") ){ pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = /* etfs cluster size writes are atomic */ (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) | SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until ** the write succeeds */ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){ pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until ** the write succeeds */ SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){ pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = /* full bitset of atomics from max sector size and smaller */ ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 | SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else if( strstr(fsInfo.f_basetype, "dos") ){ pFile->sectorSize = fsInfo.f_bsize; pFile->deviceCharacteristics = /* full bitset of atomics from max sector size and smaller */ ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 | SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind ** so it is ordered */ 0; }else{ pFile->deviceCharacteristics = SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */ SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until ** the write succeeds */ 0; } } /* Last chance verification. If the sector size isn't a multiple of 512 ** then it isn't valid.*/ if( pFile->sectorSize % 512 != 0 ){ pFile->deviceCharacteristics = 0; pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; } return pFile->sectorSize; } #endif /* __QNXNTO__ */ /* ** Return the device characteristics for the file. ** ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default. ** However, that choice is controversial since technically the underlying ** file system does not always provide powersafe overwrites. (In other ** words, after a power-loss event, parts of the file that were never ** written might end up being altered.) However, non-PSOW behavior is very, ** very rare. And asserting PSOW makes a large reduction in the amount ** of required I/O for journaling, since a lot of padding is eliminated. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control ** available to turn it off and URI query parameter available to turn it off. */ static int unixDeviceCharacteristics(sqlite3_file *id){ unixFile *p = (unixFile*)id; int rc = 0; #ifdef __QNXNTO__ if( p->sectorSize==0 ) unixSectorSize(id); rc = p->deviceCharacteristics; #endif if( p->ctrlFlags & UNIXFILE_PSOW ){ rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; } return rc; } #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 /* ** Return the system page size. ** ** This function should not be called directly by other code in this file. ** Instead, it should be called via macro osGetpagesize(). */ static int unixGetpagesize(void){ #if OS_VXWORKS return 1024; #elif defined(_BSD_SOURCE) return getpagesize(); #else return (int)sysconf(_SC_PAGESIZE); #endif } #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */ #ifndef SQLITE_OMIT_WAL /* ** Object used to represent an shared memory buffer. ** ** When multiple threads all reference the same wal-index, each thread ** has its own unixShm object, but they all point to a single instance ** of this unixShmNode object. In other words, each wal-index is opened ** only once per process. ** ** Each unixShmNode object is connected to a single unixInodeInfo object. ** We could coalesce this object into unixInodeInfo, but that would mean ** every open file that does not use shared memory (in other words, most ** open files) would have to carry around this extra information. So ** the unixInodeInfo object contains a pointer to this unixShmNode object ** and the unixShmNode object is created only when needed. ** ** unixMutexHeld() must be true when creating or destroying ** this object or while reading or writing the following fields: ** ** nRef ** ** The following fields are read-only after the object is created: ** ** fid ** zFilename ** ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and ** unixMutexHeld() is true when reading or writing any other field ** in this structure. */ struct unixShmNode { unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */ sqlite3_mutex *mutex; /* Mutex to access this object */ char *zFilename; /* Name of the mmapped file */ int h; /* Open file descriptor */ int szRegion; /* Size of shared-memory regions */ u16 nRegion; /* Size of array apRegion */ u8 isReadonly; /* True if read-only */ char **apRegion; /* Array of mapped shared-memory regions */ int nRef; /* Number of unixShm objects pointing to this */ unixShm *pFirst; /* All unixShm objects pointing to this */ #ifdef SQLITE_DEBUG u8 exclMask; /* Mask of exclusive locks held */ u8 sharedMask; /* Mask of shared locks held */ u8 nextShmId; /* Next available unixShm.id value */ #endif }; /* ** Structure used internally by this VFS to record the state of an ** open shared memory connection. ** ** The following fields are initialized when this object is created and ** are read-only thereafter: ** ** unixShm.pFile ** unixShm.id ** ** All other fields are read/write. The unixShm.pFile->mutex must be held ** while accessing any read/write fields. */ struct unixShm { unixShmNode *pShmNode; /* The underlying unixShmNode object */ unixShm *pNext; /* Next unixShm with the same unixShmNode */ u8 hasMutex; /* True if holding the unixShmNode mutex */ u8 id; /* Id of this connection within its unixShmNode */ u16 sharedMask; /* Mask of shared locks held */ u16 exclMask; /* Mask of exclusive locks held */ }; /* ** Constants used for locking */ #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ /* ** Apply posix advisory locks for all bytes from ofst through ofst+n-1. ** ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking ** otherwise. */ static int unixShmSystemLock( unixFile *pFile, /* Open connection to the WAL file */ int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */ int ofst, /* First byte of the locking range */ int n /* Number of bytes to lock */ ){ unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */ struct flock f; /* The posix advisory locking structure */ int rc = SQLITE_OK; /* Result code form fcntl() */ /* Access to the unixShmNode object is serialized by the caller */ pShmNode = pFile->pInode->pShmNode; assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 ); /* Shared locks never span more than one byte */ assert( n==1 || lockType!=F_RDLCK ); /* Locks are within range */ assert( n>=1 && n<=SQLITE_SHM_NLOCK ); if( pShmNode->h>=0 ){ /* Initialize the locking parameters */ memset(&f, 0, sizeof(f)); f.l_type = lockType; f.l_whence = SEEK_SET; f.l_start = ofst; f.l_len = n; rc = osFcntl(pShmNode->h, F_SETLK, &f); rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY; } /* Update the global lock state and do debug tracing */ #ifdef SQLITE_DEBUG { u16 mask; OSTRACE(("SHM-LOCK ")); mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst); if( rc==SQLITE_OK ){ if( lockType==F_UNLCK ){ OSTRACE(("unlock %d ok", ofst)); pShmNode->exclMask &= ~mask; pShmNode->sharedMask &= ~mask; }else if( lockType==F_RDLCK ){ OSTRACE(("read-lock %d ok", ofst)); pShmNode->exclMask &= ~mask; pShmNode->sharedMask |= mask; }else{ assert( lockType==F_WRLCK ); OSTRACE(("write-lock %d ok", ofst)); pShmNode->exclMask |= mask; pShmNode->sharedMask &= ~mask; } }else{ if( lockType==F_UNLCK ){ OSTRACE(("unlock %d failed", ofst)); }else if( lockType==F_RDLCK ){ OSTRACE(("read-lock failed")); }else{ assert( lockType==F_WRLCK ); OSTRACE(("write-lock %d failed", ofst)); } } OSTRACE((" - afterwards %03x,%03x\n", pShmNode->sharedMask, pShmNode->exclMask)); } #endif return rc; } /* ** Return the minimum number of 32KB shm regions that should be mapped at ** a time, assuming that each mapping must be an integer multiple of the ** current system page-size. ** ** Usually, this is 1. The exception seems to be systems that are configured ** to use 64KB pages - in this case each mapping must cover at least two ** shm regions. */ static int unixShmRegionPerMap(void){ int shmsz = 32*1024; /* SHM region size */ int pgsz = osGetpagesize(); /* System page size */ assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */ if( pgsz<shmsz ) return 1; return pgsz/shmsz; } /* ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0. ** ** This is not a VFS shared-memory method; it is a utility function called ** by VFS shared-memory methods. */ static void unixShmPurge(unixFile *pFd){ unixShmNode *p = pFd->pInode->pShmNode; assert( unixMutexHeld() ); if( p && ALWAYS(p->nRef==0) ){ int nShmPerMap = unixShmRegionPerMap(); int i; assert( p->pInode==pFd->pInode ); sqlite3_mutex_free(p->mutex); for(i=0; i<p->nRegion; i+=nShmPerMap){ if( p->h>=0 ){ osMunmap(p->apRegion[i], p->szRegion); }else{ sqlite3_free(p->apRegion[i]); } } sqlite3_free(p->apRegion); if( p->h>=0 ){ robust_close(pFd, p->h, __LINE__); p->h = -1; } p->pInode->pShmNode = 0; sqlite3_free(p); } } /* ** Open a shared-memory area associated with open database file pDbFd. ** This particular implementation uses mmapped files. ** ** The file used to implement shared-memory is in the same directory ** as the open database file and has the same name as the open database ** file with the "-shm" suffix added. For example, if the database file ** is "/home/user1/config.db" then the file that is created and mmapped ** for shared memory will be called "/home/user1/config.db-shm". ** ** Another approach to is to use files in /dev/shm or /dev/tmp or an ** some other tmpfs mount. But if a file in a different directory ** from the database file is used, then differing access permissions ** or a chroot() might cause two different processes on the same ** database to end up using different files for shared memory - ** meaning that their memory would not really be shared - resulting ** in database corruption. Nevertheless, this tmpfs file usage ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm" ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time ** option results in an incompatible build of SQLite; builds of SQLite ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the ** same database file at the same time, database corruption will likely ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered ** "unsupported" and may go away in a future SQLite release. ** ** When opening a new shared-memory file, if no other instances of that ** file are currently open, in this process or in other processes, then ** the file must be truncated to zero length or have its header cleared. ** ** If the original database file (pDbFd) is using the "unix-excl" VFS ** that means that an exclusive lock is held on the database file and ** that no other processes are able to read or write the database. In ** that case, we do not really need shared memory. No shared memory ** file is created. The shared memory will be simulated with heap memory. */ static int unixOpenSharedMemory(unixFile *pDbFd){ struct unixShm *p = 0; /* The connection to be opened */ struct unixShmNode *pShmNode; /* The underlying mmapped file */ int rc; /* Result code */ unixInodeInfo *pInode; /* The inode of fd */ char *zShmFilename; /* Name of the file used for SHM */ int nShmFilename; /* Size of the SHM filename in bytes */ /* Allocate space for the new unixShm object. */ p = sqlite3_malloc64( sizeof(*p) ); if( p==0 ) return SQLITE_NOMEM_BKPT; memset(p, 0, sizeof(*p)); assert( pDbFd->pShm==0 ); /* Check to see if a unixShmNode object already exists. Reuse an existing ** one if present. Create a new one if necessary. */ unixEnterMutex(); pInode = pDbFd->pInode; pShmNode = pInode->pShmNode; if( pShmNode==0 ){ struct stat sStat; /* fstat() info for database file */ #ifndef SQLITE_SHM_DIRECTORY const char *zBasePath = pDbFd->zPath; #endif /* Call fstat() to figure out the permissions on the database file. If ** a new *-shm file is created, an attempt will be made to create it ** with the same permissions. */ if( osFstat(pDbFd->h, &sStat) ){ rc = SQLITE_IOERR_FSTAT; goto shm_open_err; } #ifdef SQLITE_SHM_DIRECTORY nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31; #else nShmFilename = 6 + (int)strlen(zBasePath); #endif pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename ); if( pShmNode==0 ){ rc = SQLITE_NOMEM_BKPT; goto shm_open_err; } memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename); zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1]; #ifdef SQLITE_SHM_DIRECTORY sqlite3_snprintf(nShmFilename, zShmFilename, SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x", (u32)sStat.st_ino, (u32)sStat.st_dev); #else sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath); sqlite3FileSuffix3(pDbFd->zPath, zShmFilename); #endif pShmNode->h = -1; pDbFd->pInode->pShmNode = pShmNode; pShmNode->pInode = pDbFd->pInode; if( sqlite3GlobalConfig.bCoreMutex ){ pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); if( pShmNode->mutex==0 ){ rc = SQLITE_NOMEM_BKPT; goto shm_open_err; } } if( pInode->bProcessLock==0 ){ int openFlags = O_RDWR | O_CREAT; if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ openFlags = O_RDONLY; pShmNode->isReadonly = 1; } pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777)); if( pShmNode->h<0 ){ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename); goto shm_open_err; } /* If this process is running as root, make sure that the SHM file ** is owned by the same user that owns the original database. Otherwise, ** the original owner will not be able to connect. */ robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid); /* Check to see if another process is holding the dead-man switch. ** If not, truncate the file to zero length. */ rc = SQLITE_OK; if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){ if( robust_ftruncate(pShmNode->h, 0) ){ rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename); } } if( rc==SQLITE_OK ){ rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1); } if( rc ) goto shm_open_err; } } /* Make the new connection a child of the unixShmNode */ p->pShmNode = pShmNode; #ifdef SQLITE_DEBUG p->id = pShmNode->nextShmId++; #endif pShmNode->nRef++; pDbFd->pShm = p; unixLeaveMutex(); /* The reference count on pShmNode has already been incremented under ** the cover of the unixEnterMutex() mutex and the pointer from the ** new (struct unixShm) object to the pShmNode has been set. All that is ** left to do is to link the new object into the linked list starting ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex ** mutex. */ sqlite3_mutex_enter(pShmNode->mutex); p->pNext = pShmNode->pFirst; pShmNode->pFirst = p; sqlite3_mutex_leave(pShmNode->mutex); return SQLITE_OK; /* Jump here on any error */ shm_open_err: unixShmPurge(pDbFd); /* This call frees pShmNode if required */ sqlite3_free(p); unixLeaveMutex(); return rc; } /* ** This function is called to obtain a pointer to region iRegion of the ** shared-memory associated with the database file fd. Shared-memory regions ** are numbered starting from zero. Each shared-memory region is szRegion ** bytes in size. ** ** If an error occurs, an error code is returned and *pp is set to NULL. ** ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory ** region has not been allocated (by any client, including one running in a ** separate process), then *pp is set to NULL and SQLITE_OK returned. If ** bExtend is non-zero and the requested shared-memory region has not yet ** been allocated, it is allocated by this function. ** ** If the shared-memory region has already been allocated or is allocated by ** this call as described above, then it is mapped into this processes ** address space (if it is not already), *pp is set to point to the mapped ** memory and SQLITE_OK returned. */ static int unixShmMap( sqlite3_file *fd, /* Handle open on database file */ int iRegion, /* Region to retrieve */ int szRegion, /* Size of regions */ int bExtend, /* True to extend file if necessary */ void volatile **pp /* OUT: Mapped memory */ ){ unixFile *pDbFd = (unixFile*)fd; unixShm *p; unixShmNode *pShmNode; int rc = SQLITE_OK; int nShmPerMap = unixShmRegionPerMap(); int nReqRegion; /* If the shared-memory file has not yet been opened, open it now. */ if( pDbFd->pShm==0 ){ rc = unixOpenSharedMemory(pDbFd); if( rc!=SQLITE_OK ) return rc; } p = pDbFd->pShm; pShmNode = p->pShmNode; sqlite3_mutex_enter(pShmNode->mutex); assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); assert( pShmNode->pInode==pDbFd->pInode ); assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); /* Minimum number of regions required to be mapped. */ nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap; if( pShmNode->nRegion<nReqRegion ){ char **apNew; /* New apRegion[] array */ int nByte = nReqRegion*szRegion; /* Minimum required file size */ struct stat sStat; /* Used by fstat() */ pShmNode->szRegion = szRegion; if( pShmNode->h>=0 ){ /* The requested region is not mapped into this processes address space. ** Check to see if it has been allocated (i.e. if the wal-index file is ** large enough to contain the requested region). */ if( osFstat(pShmNode->h, &sStat) ){ rc = SQLITE_IOERR_SHMSIZE; goto shmpage_out; } if( sStat.st_size<nByte ){ /* The requested memory region does not exist. If bExtend is set to ** false, exit early. *pp will be set to NULL and SQLITE_OK returned. */ if( !bExtend ){ goto shmpage_out; } /* Alternatively, if bExtend is true, extend the file. Do this by ** writing a single byte to the end of each (OS) page being ** allocated or extended. Technically, we need only write to the ** last page in order to extend the file. But writing to all new ** pages forces the OS to allocate them immediately, which reduces ** the chances of SIGBUS while accessing the mapped region later on. */ else{ static const int pgsz = 4096; int iPg; /* Write to the last byte of each newly allocated or extended page */ assert( (nByte % pgsz)==0 ); for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){ int x = 0; if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){ const char *zFile = pShmNode->zFilename; rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile); goto shmpage_out; } } } } } /* Map the requested memory region into this processes address space. */ apNew = (char **)sqlite3_realloc( pShmNode->apRegion, nReqRegion*sizeof(char *) ); if( !apNew ){ rc = SQLITE_IOERR_NOMEM_BKPT; goto shmpage_out; } pShmNode->apRegion = apNew; while( pShmNode->nRegion<nReqRegion ){ int nMap = szRegion*nShmPerMap; int i; void *pMem; if( pShmNode->h>=0 ){ pMem = osMmap(0, nMap, pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion ); if( pMem==MAP_FAILED ){ rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename); goto shmpage_out; } }else{ pMem = sqlite3_malloc64(szRegion); if( pMem==0 ){ rc = SQLITE_NOMEM_BKPT; goto shmpage_out; } memset(pMem, 0, szRegion); } for(i=0; i<nShmPerMap; i++){ pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i]; } pShmNode->nRegion += nShmPerMap; } } shmpage_out: if( pShmNode->nRegion>iRegion ){ *pp = pShmNode->apRegion[iRegion]; }else{ *pp = 0; } if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY; sqlite3_mutex_leave(pShmNode->mutex); return rc; } /* ** Change the lock state for a shared-memory segment. ** ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little ** different here than in posix. In xShmLock(), one can go from unlocked ** to shared and back or from unlocked to exclusive and back. But one may ** not go from shared to exclusive or from exclusive to shared. */ static int unixShmLock( sqlite3_file *fd, /* Database file holding the shared memory */ int ofst, /* First lock to acquire or release */ int n, /* Number of locks to acquire or release */ int flags /* What to do with the lock */ ){ unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */ unixShm *p = pDbFd->pShm; /* The shared memory being locked */ unixShm *pX; /* For looping over all siblings */ unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */ int rc = SQLITE_OK; /* Result code */ u16 mask; /* Mask of locks to take or release */ assert( pShmNode==pDbFd->pInode->pShmNode ); assert( pShmNode->pInode==pDbFd->pInode ); assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); assert( n>=1 ); assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); mask = (1<<(ofst+n)) - (1<<ofst); assert( n>1 || mask==(1<<ofst) ); sqlite3_mutex_enter(pShmNode->mutex); if( flags & SQLITE_SHM_UNLOCK ){ u16 allMask = 0; /* Mask of locks held by siblings */ /* See if any siblings hold this same lock */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( pX==p ) continue; assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 ); allMask |= pX->sharedMask; } /* Unlock the system-level locks */ if( (mask & allMask)==0 ){ rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n); }else{ rc = SQLITE_OK; } /* Undo the local locks */ if( rc==SQLITE_OK ){ p->exclMask &= ~mask; p->sharedMask &= ~mask; } }else if( flags & SQLITE_SHM_SHARED ){ u16 allShared = 0; /* Union of locks held by connections other than "p" */ /* Find out which shared locks are already held by sibling connections. ** If any sibling already holds an exclusive lock, go ahead and return ** SQLITE_BUSY. */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( (pX->exclMask & mask)!=0 ){ rc = SQLITE_BUSY; break; } allShared |= pX->sharedMask; } /* Get shared locks at the system level, if necessary */ if( rc==SQLITE_OK ){ if( (allShared & mask)==0 ){ rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n); }else{ rc = SQLITE_OK; } } /* Get the local shared locks */ if( rc==SQLITE_OK ){ p->sharedMask |= mask; } }else{ /* Make sure no sibling connections hold locks that will block this ** lock. If any do, return SQLITE_BUSY right away. */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){ rc = SQLITE_BUSY; break; } } /* Get the exclusive locks at the system level. Then if successful ** also mark the local connection as being locked. */ if( rc==SQLITE_OK ){ rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n); if( rc==SQLITE_OK ){ assert( (p->sharedMask & mask)==0 ); p->exclMask |= mask; } } } sqlite3_mutex_leave(pShmNode->mutex); OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n", p->id, osGetpid(0), p->sharedMask, p->exclMask)); return rc; } /* ** Implement a memory barrier or memory fence on shared memory. ** ** All loads and stores begun before the barrier must complete before ** any load or store begun after the barrier. */ static void unixShmBarrier( sqlite3_file *fd /* Database file holding the shared memory */ ){ UNUSED_PARAMETER(fd); sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ unixEnterMutex(); /* Also mutex, for redundancy */ unixLeaveMutex(); } /* ** Close a connection to shared-memory. Delete the underlying ** storage if deleteFlag is true. ** ** If there is no shared memory associated with the connection then this ** routine is a harmless no-op. */ static int unixShmUnmap( sqlite3_file *fd, /* The underlying database file */ int deleteFlag /* Delete shared-memory if true */ ){ unixShm *p; /* The connection to be closed */ unixShmNode *pShmNode; /* The underlying shared-memory file */ unixShm **pp; /* For looping over sibling connections */ unixFile *pDbFd; /* The underlying database file */ pDbFd = (unixFile*)fd; p = pDbFd->pShm; if( p==0 ) return SQLITE_OK; pShmNode = p->pShmNode; assert( pShmNode==pDbFd->pInode->pShmNode ); assert( pShmNode->pInode==pDbFd->pInode ); /* Remove connection p from the set of connections associated ** with pShmNode */ sqlite3_mutex_enter(pShmNode->mutex); for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} *pp = p->pNext; /* Free the connection p */ sqlite3_free(p); pDbFd->pShm = 0; sqlite3_mutex_leave(pShmNode->mutex); /* If pShmNode->nRef has reached 0, then close the underlying ** shared-memory file, too */ unixEnterMutex(); assert( pShmNode->nRef>0 ); pShmNode->nRef--; if( pShmNode->nRef==0 ){ if( deleteFlag && pShmNode->h>=0 ){ osUnlink(pShmNode->zFilename); } unixShmPurge(pDbFd); } unixLeaveMutex(); return SQLITE_OK; } #else # define unixShmMap 0 # define unixShmLock 0 # define unixShmBarrier 0 # define unixShmUnmap 0 #endif /* #ifndef SQLITE_OMIT_WAL */ #if SQLITE_MAX_MMAP_SIZE>0 /* ** If it is currently memory mapped, unmap file pFd. */ static void unixUnmapfile(unixFile *pFd){ assert( pFd->nFetchOut==0 ); if( pFd->pMapRegion ){ osMunmap(pFd->pMapRegion, pFd->mmapSizeActual); pFd->pMapRegion = 0; pFd->mmapSize = 0; pFd->mmapSizeActual = 0; } } /* ** Attempt to set the size of the memory mapping maintained by file ** descriptor pFd to nNew bytes. Any existing mapping is discarded. ** ** If successful, this function sets the following variables: ** ** unixFile.pMapRegion ** unixFile.mmapSize ** unixFile.mmapSizeActual ** ** If unsuccessful, an error message is logged via sqlite3_log() and ** the three variables above are zeroed. In this case SQLite should ** continue accessing the database using the xRead() and xWrite() ** methods. */ static void unixRemapfile( unixFile *pFd, /* File descriptor object */ i64 nNew /* Required mapping size */ ){ const char *zErr = "mmap"; int h = pFd->h; /* File descriptor open on db file */ u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */ i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */ u8 *pNew = 0; /* Location of new mapping */ int flags = PROT_READ; /* Flags to pass to mmap() */ assert( pFd->nFetchOut==0 ); assert( nNew>pFd->mmapSize ); assert( nNew<=pFd->mmapSizeMax ); assert( nNew>0 ); assert( pFd->mmapSizeActual>=pFd->mmapSize ); assert( MAP_FAILED!=0 ); #ifdef SQLITE_MMAP_READWRITE if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE; #endif if( pOrig ){ #if HAVE_MREMAP i64 nReuse = pFd->mmapSize; #else const int szSyspage = osGetpagesize(); i64 nReuse = (pFd->mmapSize & ~(szSyspage-1)); #endif u8 *pReq = &pOrig[nReuse]; /* Unmap any pages of the existing mapping that cannot be reused. */ if( nReuse!=nOrig ){ osMunmap(pReq, nOrig-nReuse); } #if HAVE_MREMAP pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE); zErr = "mremap"; #else pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse); if( pNew!=MAP_FAILED ){ if( pNew!=pReq ){ osMunmap(pNew, nNew - nReuse); pNew = 0; }else{ pNew = pOrig; } } #endif /* The attempt to extend the existing mapping failed. Free it. */ if( pNew==MAP_FAILED || pNew==0 ){ osMunmap(pOrig, nReuse); } } /* If pNew is still NULL, try to create an entirely new mapping. */ if( pNew==0 ){ pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0); } if( pNew==MAP_FAILED ){ pNew = 0; nNew = 0; unixLogError(SQLITE_OK, zErr, pFd->zPath); /* If the mmap() above failed, assume that all subsequent mmap() calls ** will probably fail too. Fall back to using xRead/xWrite exclusively ** in this case. */ pFd->mmapSizeMax = 0; } pFd->pMapRegion = (void *)pNew; pFd->mmapSize = pFd->mmapSizeActual = nNew; } /* ** Memory map or remap the file opened by file-descriptor pFd (if the file ** is already mapped, the existing mapping is replaced by the new). Or, if ** there already exists a mapping for this file, and there are still ** outstanding xFetch() references to it, this function is a no-op. ** ** If parameter nByte is non-negative, then it is the requested size of ** the mapping to create. Otherwise, if nByte is less than zero, then the ** requested size is the size of the file on disk. The actual size of the ** created mapping is either the requested size or the value configured ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller. ** ** SQLITE_OK is returned if no error occurs (even if the mapping is not ** recreated as a result of outstanding references) or an SQLite error ** code otherwise. */ static int unixMapfile(unixFile *pFd, i64 nMap){ assert( nMap>=0 || pFd->nFetchOut==0 ); assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) ); if( pFd->nFetchOut>0 ) return SQLITE_OK; if( nMap<0 ){ struct stat statbuf; /* Low-level file information */ if( osFstat(pFd->h, &statbuf) ){ return SQLITE_IOERR_FSTAT; } nMap = statbuf.st_size; } if( nMap>pFd->mmapSizeMax ){ nMap = pFd->mmapSizeMax; } assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) ); if( nMap!=pFd->mmapSize ){ unixRemapfile(pFd, nMap); } return SQLITE_OK; } #endif /* SQLITE_MAX_MMAP_SIZE>0 */ /* ** If possible, return a pointer to a mapping of file fd starting at offset ** iOff. The mapping must be valid for at least nAmt bytes. ** ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. ** Finally, if an error does occur, return an SQLite error code. The final ** value of *pp is undefined in this case. ** ** If this function does return a pointer, the caller must eventually ** release the reference by calling unixUnfetch(). */ static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ #if SQLITE_MAX_MMAP_SIZE>0 unixFile *pFd = (unixFile *)fd; /* The underlying database file */ #endif *pp = 0; #if SQLITE_MAX_MMAP_SIZE>0 if( pFd->mmapSizeMax>0 ){ if( pFd->pMapRegion==0 ){ int rc = unixMapfile(pFd, -1); if( rc!=SQLITE_OK ) return rc; } if( pFd->mmapSize >= iOff+nAmt ){ *pp = &((u8 *)pFd->pMapRegion)[iOff]; pFd->nFetchOut++; } } #endif return SQLITE_OK; } /* ** If the third argument is non-NULL, then this function releases a ** reference obtained by an earlier call to unixFetch(). The second ** argument passed to this function must be the same as the corresponding ** argument that was passed to the unixFetch() invocation. ** ** Or, if the third argument is NULL, then this function is being called ** to inform the VFS layer that, according to POSIX, any existing mapping ** may now be invalid and should be unmapped. */ static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){ #if SQLITE_MAX_MMAP_SIZE>0 unixFile *pFd = (unixFile *)fd; /* The underlying database file */ UNUSED_PARAMETER(iOff); /* If p==0 (unmap the entire file) then there must be no outstanding ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), ** then there must be at least one outstanding. */ assert( (p==0)==(pFd->nFetchOut==0) ); /* If p!=0, it must match the iOff value. */ assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); if( p ){ pFd->nFetchOut--; }else{ unixUnmapfile(pFd); } assert( pFd->nFetchOut>=0 ); #else UNUSED_PARAMETER(fd); UNUSED_PARAMETER(p); UNUSED_PARAMETER(iOff); #endif return SQLITE_OK; } /* ** Here ends the implementation of all sqlite3_file methods. ** ********************** End sqlite3_file Methods ******************************* ******************************************************************************/ /* ** This division contains definitions of sqlite3_io_methods objects that ** implement various file locking strategies. It also contains definitions ** of "finder" functions. A finder-function is used to locate the appropriate ** sqlite3_io_methods object for a particular database file. The pAppData ** field of the sqlite3_vfs VFS objects are initialized to be pointers to ** the correct finder-function for that VFS. ** ** Most finder functions return a pointer to a fixed sqlite3_io_methods ** object. The only interesting finder-function is autolockIoFinder, which ** looks at the filesystem type and tries to guess the best locking ** strategy from that. ** ** For finder-function F, two objects are created: ** ** (1) The real finder-function named "FImpt()". ** ** (2) A constant pointer to this function named just "F". ** ** ** A pointer to the F pointer is used as the pAppData value for VFS ** objects. We have to do this instead of letting pAppData point ** directly at the finder-function since C90 rules prevent a void* ** from be cast into a function pointer. ** ** ** Each instance of this macro generates two objects: ** ** * A constant sqlite3_io_methods object call METHOD that has locking ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. ** ** * An I/O method finder function called FINDER that returns a pointer ** to the METHOD object in the previous bullet. */ #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \ static const sqlite3_io_methods METHOD = { \ VERSION, /* iVersion */ \ CLOSE, /* xClose */ \ unixRead, /* xRead */ \ unixWrite, /* xWrite */ \ unixTruncate, /* xTruncate */ \ unixSync, /* xSync */ \ unixFileSize, /* xFileSize */ \ LOCK, /* xLock */ \ UNLOCK, /* xUnlock */ \ CKLOCK, /* xCheckReservedLock */ \ unixFileControl, /* xFileControl */ \ unixSectorSize, /* xSectorSize */ \ unixDeviceCharacteristics, /* xDeviceCapabilities */ \ SHMMAP, /* xShmMap */ \ unixShmLock, /* xShmLock */ \ unixShmBarrier, /* xShmBarrier */ \ unixShmUnmap, /* xShmUnmap */ \ unixFetch, /* xFetch */ \ unixUnfetch, /* xUnfetch */ \ }; \ static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \ UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \ return &METHOD; \ } \ static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \ = FINDER##Impl; /* ** Here are all of the sqlite3_io_methods objects for each of the ** locking strategies. Functions that return pointers to these methods ** are also created. */ IOMETHODS( posixIoFinder, /* Finder function name */ posixIoMethods, /* sqlite3_io_methods object name */ 3, /* shared memory and mmap are enabled */ unixClose, /* xClose method */ unixLock, /* xLock method */ unixUnlock, /* xUnlock method */ unixCheckReservedLock, /* xCheckReservedLock method */ unixShmMap /* xShmMap method */ ) IOMETHODS( nolockIoFinder, /* Finder function name */ nolockIoMethods, /* sqlite3_io_methods object name */ 3, /* shared memory is disabled */ nolockClose, /* xClose method */ nolockLock, /* xLock method */ nolockUnlock, /* xUnlock method */ nolockCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) IOMETHODS( dotlockIoFinder, /* Finder function name */ dotlockIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ dotlockClose, /* xClose method */ dotlockLock, /* xLock method */ dotlockUnlock, /* xUnlock method */ dotlockCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #if SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( flockIoFinder, /* Finder function name */ flockIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ flockClose, /* xClose method */ flockLock, /* xLock method */ flockUnlock, /* xUnlock method */ flockCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif #if OS_VXWORKS IOMETHODS( semIoFinder, /* Finder function name */ semIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ semXClose, /* xClose method */ semXLock, /* xLock method */ semXUnlock, /* xUnlock method */ semXCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( afpIoFinder, /* Finder function name */ afpIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ afpClose, /* xClose method */ afpLock, /* xLock method */ afpUnlock, /* xUnlock method */ afpCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif /* ** The proxy locking method is a "super-method" in the sense that it ** opens secondary file descriptors for the conch and lock files and ** it uses proxy, dot-file, AFP, and flock() locking methods on those ** secondary files. For this reason, the division that implements ** proxy locking is located much further down in the file. But we need ** to go ahead and define the sqlite3_io_methods and finder function ** for proxy locking here. So we forward declare the I/O methods. */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE static int proxyClose(sqlite3_file*); static int proxyLock(sqlite3_file*, int); static int proxyUnlock(sqlite3_file*, int); static int proxyCheckReservedLock(sqlite3_file*, int*); IOMETHODS( proxyIoFinder, /* Finder function name */ proxyIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ proxyClose, /* xClose method */ proxyLock, /* xLock method */ proxyUnlock, /* xUnlock method */ proxyCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( nfsIoFinder, /* Finder function name */ nfsIoMethods, /* sqlite3_io_methods object name */ 1, /* shared memory is disabled */ unixClose, /* xClose method */ unixLock, /* xLock method */ nfsUnlock, /* xUnlock method */ unixCheckReservedLock, /* xCheckReservedLock method */ 0 /* xShmMap method */ ) #endif #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** This "finder" function attempts to determine the best locking strategy ** for the database file "filePath". It then returns the sqlite3_io_methods ** object that implements that strategy. ** ** This is for MacOSX only. */ static const sqlite3_io_methods *autolockIoFinderImpl( const char *filePath, /* name of the database file */ unixFile *pNew /* open file object for the database file */ ){ static const struct Mapping { const char *zFilesystem; /* Filesystem type name */ const sqlite3_io_methods *pMethods; /* Appropriate locking method */ } aMap[] = { { "hfs", &posixIoMethods }, { "ufs", &posixIoMethods }, { "afpfs", &afpIoMethods }, { "smbfs", &afpIoMethods }, { "webdav", &nolockIoMethods }, { 0, 0 } }; int i; struct statfs fsInfo; struct flock lockInfo; if( !filePath ){ /* If filePath==NULL that means we are dealing with a transient file ** that does not need to be locked. */ return &nolockIoMethods; } if( statfs(filePath, &fsInfo) != -1 ){ if( fsInfo.f_flags & MNT_RDONLY ){ return &nolockIoMethods; } for(i=0; aMap[i].zFilesystem; i++){ if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){ return aMap[i].pMethods; } } } /* Default case. Handles, amongst others, "nfs". ** Test byte-range lock using fcntl(). If the call succeeds, ** assume that the file-system supports POSIX style locks. */ lockInfo.l_len = 1; lockInfo.l_start = 0; lockInfo.l_whence = SEEK_SET; lockInfo.l_type = F_RDLCK; if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){ return &nfsIoMethods; } else { return &posixIoMethods; } }else{ return &dotlockIoMethods; } } static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ #if OS_VXWORKS /* ** This "finder" function for VxWorks checks to see if posix advisory ** locking works. If it does, then that is what is used. If it does not ** work, then fallback to named semaphore locking. */ static const sqlite3_io_methods *vxworksIoFinderImpl( const char *filePath, /* name of the database file */ unixFile *pNew /* the open file object */ ){ struct flock lockInfo; if( !filePath ){ /* If filePath==NULL that means we are dealing with a transient file ** that does not need to be locked. */ return &nolockIoMethods; } /* Test if fcntl() is supported and use POSIX style locks. ** Otherwise fall back to the named semaphore method. */ lockInfo.l_len = 1; lockInfo.l_start = 0; lockInfo.l_whence = SEEK_SET; lockInfo.l_type = F_RDLCK; if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { return &posixIoMethods; }else{ return &semIoMethods; } } static const sqlite3_io_methods *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl; #endif /* OS_VXWORKS */ /* ** An abstract type for a pointer to an IO method finder function: */ typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*); /**************************************************************************** **************************** sqlite3_vfs methods **************************** ** ** This division contains the implementation of methods on the ** sqlite3_vfs object. */ /* ** Initialize the contents of the unixFile structure pointed to by pId. */ static int fillInUnixFile( sqlite3_vfs *pVfs, /* Pointer to vfs object */ int h, /* Open file descriptor of file being opened */ sqlite3_file *pId, /* Write to the unixFile structure here */ const char *zFilename, /* Name of the file being opened */ int ctrlFlags /* Zero or more UNIXFILE_* values */ ){ const sqlite3_io_methods *pLockingStyle; unixFile *pNew = (unixFile *)pId; int rc = SQLITE_OK; assert( pNew->pInode==NULL ); /* Usually the path zFilename should not be a relative pathname. The ** exception is when opening the proxy "conch" file in builds that ** include the special Apple locking styles. */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE assert( zFilename==0 || zFilename[0]=='/' || pVfs->pAppData==(void*)&autolockIoFinder ); #else assert( zFilename==0 || zFilename[0]=='/' ); #endif /* No locking occurs in temporary files */ assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 ); OSTRACE(("OPEN %-3d %s\n", h, zFilename)); pNew->h = h; pNew->pVfs = pVfs; pNew->zPath = zFilename; pNew->ctrlFlags = (u8)ctrlFlags; #if SQLITE_MAX_MMAP_SIZE>0 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap; #endif if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), "psow", SQLITE_POWERSAFE_OVERWRITE) ){ pNew->ctrlFlags |= UNIXFILE_PSOW; } if( strcmp(pVfs->zName,"unix-excl")==0 ){ pNew->ctrlFlags |= UNIXFILE_EXCL; } #if OS_VXWORKS pNew->pId = vxworksFindFileId(zFilename); if( pNew->pId==0 ){ ctrlFlags |= UNIXFILE_NOLOCK; rc = SQLITE_NOMEM_BKPT; } #endif if( ctrlFlags & UNIXFILE_NOLOCK ){ pLockingStyle = &nolockIoMethods; }else{ pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); #if SQLITE_ENABLE_LOCKING_STYLE /* Cache zFilename in the locking context (AFP and dotlock override) for ** proxyLock activation is possible (remote proxy is based on db name) ** zFilename remains valid until file is closed, to support */ pNew->lockingContext = (void*)zFilename; #endif } if( pLockingStyle == &posixIoMethods #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE || pLockingStyle == &nfsIoMethods #endif ){ unixEnterMutex(); rc = findInodeInfo(pNew, &pNew->pInode); if( rc!=SQLITE_OK ){ /* If an error occurred in findInodeInfo(), close the file descriptor ** immediately, before releasing the mutex. findInodeInfo() may fail ** in two scenarios: ** ** (a) A call to fstat() failed. ** (b) A malloc failed. ** ** Scenario (b) may only occur if the process is holding no other ** file descriptors open on the same file. If there were other file ** descriptors on this file, then no malloc would be required by ** findInodeInfo(). If this is the case, it is quite safe to close ** handle h - as it is guaranteed that no posix locks will be released ** by doing so. ** ** If scenario (a) caused the error then things are not so safe. The ** implicit assumption here is that if fstat() fails, things are in ** such bad shape that dropping a lock or two doesn't matter much. */ robust_close(pNew, h, __LINE__); h = -1; } unixLeaveMutex(); } #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) else if( pLockingStyle == &afpIoMethods ){ /* AFP locking uses the file path so it needs to be included in ** the afpLockingContext. */ afpLockingContext *pCtx; pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) ); if( pCtx==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ /* NB: zFilename exists and remains valid until the file is closed ** according to requirement F11141. So we do not need to make a ** copy of the filename. */ pCtx->dbPath = zFilename; pCtx->reserved = 0; srandomdev(); unixEnterMutex(); rc = findInodeInfo(pNew, &pNew->pInode); if( rc!=SQLITE_OK ){ sqlite3_free(pNew->lockingContext); robust_close(pNew, h, __LINE__); h = -1; } unixLeaveMutex(); } } #endif else if( pLockingStyle == &dotlockIoMethods ){ /* Dotfile locking uses the file path so it needs to be included in ** the dotlockLockingContext */ char *zLockFile; int nFilename; assert( zFilename!=0 ); nFilename = (int)strlen(zFilename) + 6; zLockFile = (char *)sqlite3_malloc64(nFilename); if( zLockFile==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); } pNew->lockingContext = zLockFile; } #if OS_VXWORKS else if( pLockingStyle == &semIoMethods ){ /* Named semaphore locking uses the file path so it needs to be ** included in the semLockingContext */ unixEnterMutex(); rc = findInodeInfo(pNew, &pNew->pInode); if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){ char *zSemName = pNew->pInode->aSemName; int n; sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem", pNew->pId->zCanonicalName); for( n=1; zSemName[n]; n++ ) if( zSemName[n]=='/' ) zSemName[n] = '_'; pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1); if( pNew->pInode->pSem == SEM_FAILED ){ rc = SQLITE_NOMEM_BKPT; pNew->pInode->aSemName[0] = '\0'; } } unixLeaveMutex(); } #endif storeLastErrno(pNew, 0); #if OS_VXWORKS if( rc!=SQLITE_OK ){ if( h>=0 ) robust_close(pNew, h, __LINE__); h = -1; osUnlink(zFilename); pNew->ctrlFlags |= UNIXFILE_DELETE; } #endif if( rc!=SQLITE_OK ){ if( h>=0 ) robust_close(pNew, h, __LINE__); }else{ pNew->pMethod = pLockingStyle; OpenCounter(+1); verifyDbFile(pNew); } return rc; } /* ** Return the name of a directory in which to put temporary files. ** If no suitable temporary file directory can be found, return NULL. */ static const char *unixTempFileDir(void){ static const char *azDirs[] = { 0, 0, "/var/tmp", "/usr/tmp", "/tmp", "." }; unsigned int i = 0; struct stat buf; const char *zDir = sqlite3_temp_directory; if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); while(1){ if( zDir!=0 && osStat(zDir, &buf)==0 && S_ISDIR(buf.st_mode) && osAccess(zDir, 03)==0 ){ return zDir; } if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break; zDir = azDirs[i++]; } return 0; } /* ** Create a temporary file name in zBuf. zBuf must be allocated ** by the calling process and must be big enough to hold at least ** pVfs->mxPathname bytes. */ static int unixGetTempname(int nBuf, char *zBuf){ const char *zDir; int iLimit = 0; /* It's odd to simulate an io-error here, but really this is just ** using the io-error infrastructure to test that SQLite handles this ** function failing. */ zBuf[0] = 0; SimulateIOError( return SQLITE_IOERR ); zDir = unixTempFileDir(); if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH; do{ u64 r; sqlite3_randomness(sizeof(r), &r); assert( nBuf>2 ); zBuf[nBuf-2] = 0; sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c", zDir, r, 0); if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR; }while( osAccess(zBuf,0)==0 ); return SQLITE_OK; } #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) /* ** Routine to transform a unixFile into a proxy-locking unixFile. ** Implementation in the proxy-lock division, but used by unixOpen() ** if SQLITE_PREFER_PROXY_LOCKING is defined. */ static int proxyTransformUnixFile(unixFile*, const char*); #endif /* ** Search for an unused file descriptor that was opened on the database ** file (not a journal or master-journal file) identified by pathname ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second ** argument to this function. ** ** Such a file descriptor may exist if a database connection was closed ** but the associated file descriptor could not be closed because some ** other file descriptor open on the same file is holding a file-lock. ** Refer to comments in the unixClose() function and the lengthy comment ** describing "Posix Advisory Locking" at the start of this file for ** further details. Also, ticket #4018. ** ** If a suitable file descriptor is found, then it is returned. If no ** such file descriptor is located, -1 is returned. */ static UnixUnusedFd *findReusableFd(const char *zPath, int flags){ UnixUnusedFd *pUnused = 0; /* Do not search for an unused file descriptor on vxworks. Not because ** vxworks would not benefit from the change (it might, we're not sure), ** but because no way to test it is currently available. It is better ** not to risk breaking vxworks support for the sake of such an obscure ** feature. */ #if !OS_VXWORKS struct stat sStat; /* Results of stat() call */ /* A stat() call may fail for various reasons. If this happens, it is ** almost certain that an open() call on the same path will also fail. ** For this reason, if an error occurs in the stat() call here, it is ** ignored and -1 is returned. The caller will try to open a new file ** descriptor on the same path, fail, and return an error to SQLite. ** ** Even if a subsequent open() call does succeed, the consequences of ** not searching for a reusable file descriptor are not dire. */ if( 0==osStat(zPath, &sStat) ){ unixInodeInfo *pInode; unixEnterMutex(); pInode = inodeList; while( pInode && (pInode->fileId.dev!=sStat.st_dev || pInode->fileId.ino!=(u64)sStat.st_ino) ){ pInode = pInode->pNext; } if( pInode ){ UnixUnusedFd **pp; for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); pUnused = *pp; if( pUnused ){ *pp = pUnused->pNext; } } unixLeaveMutex(); } #endif /* if !OS_VXWORKS */ return pUnused; } /* ** Find the mode, uid and gid of file zFile. */ static int getFileMode( const char *zFile, /* File name */ mode_t *pMode, /* OUT: Permissions of zFile */ uid_t *pUid, /* OUT: uid of zFile. */ gid_t *pGid /* OUT: gid of zFile. */ ){ struct stat sStat; /* Output of stat() on database file */ int rc = SQLITE_OK; if( 0==osStat(zFile, &sStat) ){ *pMode = sStat.st_mode & 0777; *pUid = sStat.st_uid; *pGid = sStat.st_gid; }else{ rc = SQLITE_IOERR_FSTAT; } return rc; } /* ** This function is called by unixOpen() to determine the unix permissions ** to create new files with. If no error occurs, then SQLITE_OK is returned ** and a value suitable for passing as the third argument to open(2) is ** written to *pMode. If an IO error occurs, an SQLite error code is ** returned and the value of *pMode is not modified. ** ** In most cases, this routine sets *pMode to 0, which will become ** an indication to robust_open() to create the file using ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask. ** But if the file being opened is a WAL or regular journal file, then ** this function queries the file-system for the permissions on the ** corresponding database file and sets *pMode to this value. Whenever ** possible, WAL and journal files are created using the same permissions ** as the associated database file. ** ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the ** original filename is unavailable. But 8_3_NAMES is only used for ** FAT filesystems and permissions do not matter there, so just use ** the default permissions. */ static int findCreateFileMode( const char *zPath, /* Path of file (possibly) being created */ int flags, /* Flags passed as 4th argument to xOpen() */ mode_t *pMode, /* OUT: Permissions to open file with */ uid_t *pUid, /* OUT: uid to set on the file */ gid_t *pGid /* OUT: gid to set on the file */ ){ int rc = SQLITE_OK; /* Return Code */ *pMode = 0; *pUid = 0; *pGid = 0; if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ char zDb[MAX_PATHNAME+1]; /* Database file path */ int nDb; /* Number of valid bytes in zDb */ /* zPath is a path to a WAL or journal file. The following block derives ** the path to the associated database file from zPath. This block handles ** the following naming conventions: ** ** "<path to db>-journal" ** "<path to db>-wal" ** "<path to db>-journalNN" ** "<path to db>-walNN" ** ** where NN is a decimal number. The NN naming schemes are ** used by the test_multiplex.c module. */ nDb = sqlite3Strlen30(zPath) - 1; while( zPath[nDb]!='-' ){ #ifndef SQLITE_ENABLE_8_3_NAMES /* In the normal case (8+3 filenames disabled) the journal filename ** is guaranteed to contain a '-' character. */ assert( nDb>0 ); assert( sqlite3Isalnum(zPath[nDb]) ); #else /* If 8+3 names are possible, then the journal file might not contain ** a '-' character. So check for that case and return early. */ if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK; #endif nDb--; } memcpy(zDb, zPath, nDb); zDb[nDb] = '\0'; rc = getFileMode(zDb, pMode, pUid, pGid); }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){ *pMode = 0600; }else if( flags & SQLITE_OPEN_URI ){ /* If this is a main database file and the file was opened using a URI ** filename, check for the "modeof" parameter. If present, interpret ** its value as a filename and try to copy the mode, uid and gid from ** that file. */ const char *z = sqlite3_uri_parameter(zPath, "modeof"); if( z ){ rc = getFileMode(z, pMode, pUid, pGid); } } return rc; } /* ** Open the file zPath. ** ** Previously, the SQLite OS layer used three functions in place of this ** one: ** ** sqlite3OsOpenReadWrite(); ** sqlite3OsOpenReadOnly(); ** sqlite3OsOpenExclusive(); ** ** These calls correspond to the following combinations of flags: ** ** ReadWrite() -> (READWRITE | CREATE) ** ReadOnly() -> (READONLY) ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE) ** ** The old OpenExclusive() accepted a boolean argument - "delFlag". If ** true, the file was configured to be automatically deleted when the ** file handle closed. To achieve the same effect using this new ** interface, add the DELETEONCLOSE flag to those specified above for ** OpenExclusive(). */ static int unixOpen( sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ const char *zPath, /* Pathname of file to be opened */ sqlite3_file *pFile, /* The file descriptor to be filled in */ int flags, /* Input flags to control the opening */ int *pOutFlags /* Output flags returned to SQLite core */ ){ unixFile *p = (unixFile *)pFile; int fd = -1; /* File descriptor returned by open() */ int openFlags = 0; /* Flags to pass to open() */ int eType = flags&0xFFFFFF00; /* Type of file to open */ int noLock; /* True to omit locking primitives */ int rc = SQLITE_OK; /* Function Return Code */ int ctrlFlags = 0; /* UNIXFILE_* flags */ int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); int isCreate = (flags & SQLITE_OPEN_CREATE); int isReadonly = (flags & SQLITE_OPEN_READONLY); int isReadWrite = (flags & SQLITE_OPEN_READWRITE); #if SQLITE_ENABLE_LOCKING_STYLE int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY); #endif #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE struct statfs fsInfo; #endif /* If creating a master or main-file journal, this function will open ** a file-descriptor on the directory too. The first time unixSync() ** is called the directory file descriptor will be fsync()ed and close()d. */ int syncDir = (isCreate && ( eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_WAL )); /* If argument zPath is a NULL pointer, this function is required to open ** a temporary file. Use this buffer to store the file name in. */ char zTmpname[MAX_PATHNAME+2]; const char *zName = zPath; /* Check the following statements are true: ** ** (a) Exactly one of the READWRITE and READONLY flags must be set, and ** (b) if CREATE is set, then READWRITE must also be set, and ** (c) if EXCLUSIVE is set, then CREATE must also be set. ** (d) if DELETEONCLOSE is set, then CREATE must also be set. */ assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); assert(isCreate==0 || isReadWrite); assert(isExclusive==0 || isCreate); assert(isDelete==0 || isCreate); /* The main DB, main journal, WAL file and master journal are never ** automatically deleted. Nor are they ever temporary files. */ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); /* Assert that the upper layer has set one of the "file-type" flags. */ assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL ); /* Detect a pid change and reset the PRNG. There is a race condition ** here such that two or more threads all trying to open databases at ** the same instant might all reset the PRNG. But multiple resets ** are harmless. */ if( randomnessPid!=osGetpid(0) ){ randomnessPid = osGetpid(0); sqlite3_randomness(0,0); } memset(p, 0, sizeof(unixFile)); if( eType==SQLITE_OPEN_MAIN_DB ){ UnixUnusedFd *pUnused; pUnused = findReusableFd(zName, flags); if( pUnused ){ fd = pUnused->fd; }else{ pUnused = sqlite3_malloc64(sizeof(*pUnused)); if( !pUnused ){ return SQLITE_NOMEM_BKPT; } } p->pUnused = pUnused; /* Database filenames are double-zero terminated if they are not ** URIs with parameters. Hence, they can always be passed into ** sqlite3_uri_parameter(). */ assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 ); }else if( !zName ){ /* If zName is NULL, the upper layer is requesting a temp file. */ assert(isDelete && !syncDir); rc = unixGetTempname(pVfs->mxPathname, zTmpname); if( rc!=SQLITE_OK ){ return rc; } zName = zTmpname; /* Generated temporary filenames are always double-zero terminated ** for use by sqlite3_uri_parameter(). */ assert( zName[strlen(zName)+1]==0 ); } /* Determine the value of the flags parameter passed to POSIX function ** open(). These must be calculated even if open() is not called, as ** they may be stored as part of the file handle and used by the ** 'conch file' locking functions later on. */ if( isReadonly ) openFlags |= O_RDONLY; if( isReadWrite ) openFlags |= O_RDWR; if( isCreate ) openFlags |= O_CREAT; if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW); openFlags |= (O_LARGEFILE|O_BINARY); if( fd<0 ){ mode_t openMode; /* Permissions to create file with */ uid_t uid; /* Userid for the file */ gid_t gid; /* Groupid for the file */ rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid); if( rc!=SQLITE_OK ){ assert( !p->pUnused ); assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL ); return rc; } fd = robust_open(zName, openFlags, openMode); OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); assert( !isExclusive || (openFlags & O_CREAT)!=0 ); if( fd<0 && errno!=EISDIR && isReadWrite ){ /* Failed to open the file for read/write access. Try read-only. */ flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); openFlags &= ~(O_RDWR|O_CREAT); flags |= SQLITE_OPEN_READONLY; openFlags |= O_RDONLY; isReadonly = 1; fd = robust_open(zName, openFlags, openMode); } if( fd<0 ){ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName); goto open_finished; } /* If this process is running as root and if creating a new rollback ** journal or WAL file, set the ownership of the journal or WAL to be ** the same as the original database. */ if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ robustFchown(fd, uid, gid); } } assert( fd>=0 ); if( pOutFlags ){ *pOutFlags = flags; } if( p->pUnused ){ p->pUnused->fd = fd; p->pUnused->flags = flags; } if( isDelete ){ #if OS_VXWORKS zPath = zName; #elif defined(SQLITE_UNLINK_AFTER_CLOSE) zPath = sqlite3_mprintf("%s", zName); if( zPath==0 ){ robust_close(p, fd, __LINE__); return SQLITE_NOMEM_BKPT; } #else osUnlink(zName); #endif } #if SQLITE_ENABLE_LOCKING_STYLE else{ p->openFlags = openFlags; } #endif #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE if( fstatfs(fd, &fsInfo) == -1 ){ storeLastErrno(p, errno); robust_close(p, fd, __LINE__); return SQLITE_IOERR_ACCESS; } if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) { ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; } if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) { ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; } #endif /* Set up appropriate ctrlFlags */ if( isDelete ) ctrlFlags |= UNIXFILE_DELETE; if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY; noLock = eType!=SQLITE_OPEN_MAIN_DB; if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK; if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC; if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI; #if SQLITE_ENABLE_LOCKING_STYLE #if SQLITE_PREFER_PROXY_LOCKING isAutoProxy = 1; #endif if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){ char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); int useProxy = 0; /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means ** never use proxy, NULL means use proxy for non-local files only. */ if( envforce!=NULL ){ useProxy = atoi(envforce)>0; }else{ useProxy = !(fsInfo.f_flags&MNT_LOCAL); } if( useProxy ){ rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); if( rc==SQLITE_OK ){ rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); if( rc!=SQLITE_OK ){ /* Use unixClose to clean up the resources added in fillInUnixFile ** and clear all the structure's references. Specifically, ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op */ unixClose(pFile); return rc; } } goto open_finished; } } #endif rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); open_finished: if( rc!=SQLITE_OK ){ sqlite3_free(p->pUnused); } return rc; } /* ** Delete the file at zPath. If the dirSync argument is true, fsync() ** the directory after deleting the file. */ static int unixDelete( sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ const char *zPath, /* Name of file to be deleted */ int dirSync /* If true, fsync() directory after deleting file */ ){ int rc = SQLITE_OK; UNUSED_PARAMETER(NotUsed); SimulateIOError(return SQLITE_IOERR_DELETE); if( osUnlink(zPath)==(-1) ){ if( errno==ENOENT #if OS_VXWORKS || osAccess(zPath,0)!=0 #endif ){ rc = SQLITE_IOERR_DELETE_NOENT; }else{ rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath); } return rc; } #ifndef SQLITE_DISABLE_DIRSYNC if( (dirSync & 1)!=0 ){ int fd; rc = osOpenDirectory(zPath, &fd); if( rc==SQLITE_OK ){ if( full_fsync(fd,0,0) ){ rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath); } robust_close(0, fd, __LINE__); }else{ assert( rc==SQLITE_CANTOPEN ); rc = SQLITE_OK; } } #endif return rc; } /* ** Test the existence of or access permissions of file zPath. The ** test performed depends on the value of flags: ** ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable. ** ** Otherwise return 0. */ static int unixAccess( sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ const char *zPath, /* Path of the file to examine */ int flags, /* What do we want to learn about the zPath file? */ int *pResOut /* Write result boolean here */ ){ UNUSED_PARAMETER(NotUsed); SimulateIOError( return SQLITE_IOERR_ACCESS; ); assert( pResOut!=0 ); /* The spec says there are three possible values for flags. But only ** two of them are actually used */ assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE ); if( flags==SQLITE_ACCESS_EXISTS ){ struct stat buf; *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0); }else{ *pResOut = osAccess(zPath, W_OK|R_OK)==0; } return SQLITE_OK; } /* ** */ static int mkFullPathname( const char *zPath, /* Input path */ char *zOut, /* Output buffer */ int nOut /* Allocated size of buffer zOut */ ){ int nPath = sqlite3Strlen30(zPath); int iOff = 0; if( zPath[0]!='/' ){ if( osGetcwd(zOut, nOut-2)==0 ){ return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath); } iOff = sqlite3Strlen30(zOut); zOut[iOff++] = '/'; } if( (iOff+nPath+1)>nOut ){ /* SQLite assumes that xFullPathname() nul-terminates the output buffer ** even if it returns an error. */ zOut[iOff] = '\0'; return SQLITE_CANTOPEN_BKPT; } sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath); return SQLITE_OK; } /* ** Turn a relative pathname into a full pathname. The relative path ** is stored as a nul-terminated string in the buffer pointed to by ** zPath. ** ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes ** (in this case, MAX_PATHNAME bytes). The full-path is written to ** this buffer before returning. */ static int unixFullPathname( sqlite3_vfs *pVfs, /* Pointer to vfs object */ const char *zPath, /* Possibly relative input path */ int nOut, /* Size of output buffer in bytes */ char *zOut /* Output buffer */ ){ #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT) return mkFullPathname(zPath, zOut, nOut); #else int rc = SQLITE_OK; int nByte; int nLink = 1; /* Number of symbolic links followed so far */ const char *zIn = zPath; /* Input path for each iteration of loop */ char *zDel = 0; assert( pVfs->mxPathname==MAX_PATHNAME ); UNUSED_PARAMETER(pVfs); /* It's odd to simulate an io-error here, but really this is just ** using the io-error infrastructure to test that SQLite handles this ** function failing. This function could fail if, for example, the ** current working directory has been unlinked. */ SimulateIOError( return SQLITE_ERROR ); do { /* Call stat() on path zIn. Set bLink to true if the path is a symbolic ** link, or false otherwise. */ int bLink = 0; struct stat buf; if( osLstat(zIn, &buf)!=0 ){ if( errno!=ENOENT ){ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn); } }else{ bLink = S_ISLNK(buf.st_mode); } if( bLink ){ if( zDel==0 ){ zDel = sqlite3_malloc(nOut); if( zDel==0 ) rc = SQLITE_NOMEM_BKPT; }else if( ++nLink>SQLITE_MAX_SYMLINKS ){ rc = SQLITE_CANTOPEN_BKPT; } if( rc==SQLITE_OK ){ nByte = osReadlink(zIn, zDel, nOut-1); if( nByte<0 ){ rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn); }else{ if( zDel[0]!='/' ){ int n; for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--); if( nByte+n+1>nOut ){ rc = SQLITE_CANTOPEN_BKPT; }else{ memmove(&zDel[n], zDel, nByte+1); memcpy(zDel, zIn, n); nByte += n; } } zDel[nByte] = '\0'; } } zIn = zDel; } assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' ); if( rc==SQLITE_OK && zIn!=zOut ){ rc = mkFullPathname(zIn, zOut, nOut); } if( bLink==0 ) break; zIn = zOut; }while( rc==SQLITE_OK ); sqlite3_free(zDel); return rc; #endif /* HAVE_READLINK && HAVE_LSTAT */ } #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** Interfaces for opening a shared library, finding entry points ** within the shared library, and closing the shared library. */ #include <dlfcn.h> static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){ UNUSED_PARAMETER(NotUsed); return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL); } /* ** SQLite calls this function immediately after a call to unixDlSym() or ** unixDlOpen() fails (returns a null pointer). If a more detailed error ** message is available, it is written to zBufOut. If no error message ** is available, zBufOut is left unmodified and SQLite uses a default ** error message. */ static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){ const char *zErr; UNUSED_PARAMETER(NotUsed); unixEnterMutex(); zErr = dlerror(); if( zErr ){ sqlite3_snprintf(nBuf, zBufOut, "%s", zErr); } unixLeaveMutex(); } static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ /* ** GCC with -pedantic-errors says that C90 does not allow a void* to be ** cast into a pointer to a function. And yet the library dlsym() routine ** returns a void* which is really a pointer to a function. So how do we ** use dlsym() with -pedantic-errors? ** ** Variable x below is defined to be a pointer to a function taking ** parameters void* and const char* and returning a pointer to a function. ** We initialize x by assigning it a pointer to the dlsym() function. ** (That assignment requires a cast.) Then we call the function that ** x points to. ** ** This work-around is unlikely to work correctly on any system where ** you really cannot cast a function pointer into void*. But then, on the ** other hand, dlsym() will not work on such a system either, so we have ** not really lost anything. */ void (*(*x)(void*,const char*))(void); UNUSED_PARAMETER(NotUsed); x = (void(*(*)(void*,const char*))(void))dlsym; return (*x)(p, zSym); } static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){ UNUSED_PARAMETER(NotUsed); dlclose(pHandle); } #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ #define unixDlOpen 0 #define unixDlError 0 #define unixDlSym 0 #define unixDlClose 0 #endif /* ** Write nBuf bytes of random data to the supplied buffer zBuf. */ static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ UNUSED_PARAMETER(NotUsed); assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int))); /* We have to initialize zBuf to prevent valgrind from reporting ** errors. The reports issued by valgrind are incorrect - we would ** prefer that the randomness be increased by making use of the ** uninitialized space in zBuf - but valgrind errors tend to worry ** some users. Rather than argue, it seems easier just to initialize ** the whole array and silence valgrind, even if that means less randomness ** in the random seed. ** ** When testing, initializing zBuf[] to zero is all we do. That means ** that we always use the same random number sequence. This makes the ** tests repeatable. */ memset(zBuf, 0, nBuf); randomnessPid = osGetpid(0); #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) { int fd, got; fd = robust_open("/dev/urandom", O_RDONLY, 0); if( fd<0 ){ time_t t; time(&t); memcpy(zBuf, &t, sizeof(t)); memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid)); assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf ); nBuf = sizeof(t) + sizeof(randomnessPid); }else{ do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR ); robust_close(0, fd, __LINE__); } } #endif return nBuf; } /* ** Sleep for a little while. Return the amount of time slept. ** The argument is the number of microseconds we want to sleep. ** The return value is the number of microseconds of sleep actually ** requested from the underlying operating system, a number which ** might be greater than or equal to the argument, but not less ** than the argument. */ static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ #if OS_VXWORKS struct timespec sp; sp.tv_sec = microseconds / 1000000; sp.tv_nsec = (microseconds % 1000000) * 1000; nanosleep(&sp, NULL); UNUSED_PARAMETER(NotUsed); return microseconds; #elif defined(HAVE_USLEEP) && HAVE_USLEEP usleep(microseconds); UNUSED_PARAMETER(NotUsed); return microseconds; #else int seconds = (microseconds+999999)/1000000; sleep(seconds); UNUSED_PARAMETER(NotUsed); return seconds*1000000; #endif } /* ** The following variable, if set to a non-zero value, is interpreted as ** the number of seconds since 1970 and is used to set the result of ** sqlite3OsCurrentTime() during testing. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ #endif /* ** Find the current time (in Universal Coordinated Time). Write into *piNow ** the current time and date as a Julian Day number times 86_400_000. In ** other words, write into *piNow the number of milliseconds since the Julian ** epoch of noon in Greenwich on November 24, 4714 B.C according to the ** proleptic Gregorian calendar. ** ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date ** cannot be found. */ static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){ static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; int rc = SQLITE_OK; #if defined(NO_GETTOD) time_t t; time(&t); *piNow = ((sqlite3_int64)t)*1000 + unixEpoch; #elif OS_VXWORKS struct timespec sNow; clock_gettime(CLOCK_REALTIME, &sNow); *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000; #else struct timeval sNow; (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */ *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; #endif #ifdef SQLITE_TEST if( sqlite3_current_time ){ *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; } #endif UNUSED_PARAMETER(NotUsed); return rc; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Find the current time (in Universal Coordinated Time). Write the ** current time and date as a Julian Day number into *prNow and ** return 0. Return 1 if the time and date cannot be found. */ static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){ sqlite3_int64 i = 0; int rc; UNUSED_PARAMETER(NotUsed); rc = unixCurrentTimeInt64(0, &i); *prNow = i/86400000.0; return rc; } #else # define unixCurrentTime 0 #endif /* ** The xGetLastError() method is designed to return a better ** low-level error message when operating-system problems come up ** during SQLite operation. Only the integer return code is currently ** used. */ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ UNUSED_PARAMETER(NotUsed); UNUSED_PARAMETER(NotUsed2); UNUSED_PARAMETER(NotUsed3); return errno; } /* ************************ End of sqlite3_vfs methods *************************** ******************************************************************************/ /****************************************************************************** ************************** Begin Proxy Locking ******************************** ** ** Proxy locking is a "uber-locking-method" in this sense: It uses the ** other locking methods on secondary lock files. Proxy locking is a ** meta-layer over top of the primitive locking implemented above. For ** this reason, the division that implements of proxy locking is deferred ** until late in the file (here) after all of the other I/O methods have ** been defined - so that the primitive locking methods are available ** as services to help with the implementation of proxy locking. ** **** ** ** The default locking schemes in SQLite use byte-range locks on the ** database file to coordinate safe, concurrent access by multiple readers ** and writers [http://sqlite.org/lockingv3.html]. The five file locking ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented ** as POSIX read & write locks over fixed set of locations (via fsctl), ** on AFP and SMB only exclusive byte-range locks are available via fsctl ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected ** address in the shared range is taken for a SHARED lock, the entire ** shared range is taken for an EXCLUSIVE lock): ** ** PENDING_BYTE 0x40000000 ** RESERVED_BYTE 0x40000001 ** SHARED_RANGE 0x40000002 -> 0x40000200 ** ** This works well on the local file system, but shows a nearly 100x ** slowdown in read performance on AFP because the AFP client disables ** the read cache when byte-range locks are present. Enabling the read ** cache exposes a cache coherency problem that is present on all OS X ** supported network file systems. NFS and AFP both observe the ** close-to-open semantics for ensuring cache coherency ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively ** address the requirements for concurrent database access by multiple ** readers and writers ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html]. ** ** To address the performance and cache coherency issues, proxy file locking ** changes the way database access is controlled by limiting access to a ** single host at a time and moving file locks off of the database file ** and onto a proxy file on the local file system. ** ** ** Using proxy locks ** ----------------- ** ** C APIs ** ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE, ** <proxy_path> | ":auto:"); ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE, ** &<proxy_path>); ** ** ** SQL pragmas ** ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto: ** PRAGMA [database.]lock_proxy_file ** ** Specifying ":auto:" means that if there is a conch file with a matching ** host ID in it, the proxy path in the conch file will be used, otherwise ** a proxy path based on the user's temp dir ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the ** actual proxy file name is generated from the name and path of the ** database file. For example: ** ** For database path "/Users/me/foo.db" ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:") ** ** Once a lock proxy is configured for a database connection, it can not ** be removed, however it may be switched to a different proxy path via ** the above APIs (assuming the conch file is not being held by another ** connection or process). ** ** ** How proxy locking works ** ----------------------- ** ** Proxy file locking relies primarily on two new supporting files: ** ** * conch file to limit access to the database file to a single host ** at a time ** ** * proxy file to act as a proxy for the advisory locks normally ** taken on the database ** ** The conch file - to use a proxy file, sqlite must first "hold the conch" ** by taking an sqlite-style shared lock on the conch file, reading the ** contents and comparing the host's unique host ID (see below) and lock ** proxy path against the values stored in the conch. The conch file is ** stored in the same directory as the database file and the file name ** is patterned after the database file name as ".<databasename>-conch". ** If the conch file does not exist, or its contents do not match the ** host ID and/or proxy path, then the lock is escalated to an exclusive ** lock and the conch file contents is updated with the host ID and proxy ** path and the lock is downgraded to a shared lock again. If the conch ** is held by another process (with a shared lock), the exclusive lock ** will fail and SQLITE_BUSY is returned. ** ** The proxy file - a single-byte file used for all advisory file locks ** normally taken on the database file. This allows for safe sharing ** of the database file for multiple readers and writers on the same ** host (the conch ensures that they all use the same local lock file). ** ** Requesting the lock proxy does not immediately take the conch, it is ** only taken when the first request to lock database file is made. ** This matches the semantics of the traditional locking behavior, where ** opening a connection to a database file does not take a lock on it. ** The shared lock and an open file descriptor are maintained until ** the connection to the database is closed. ** ** The proxy file and the lock file are never deleted so they only need ** to be created the first time they are used. ** ** Configuration options ** --------------------- ** ** SQLITE_PREFER_PROXY_LOCKING ** ** Database files accessed on non-local file systems are ** automatically configured for proxy locking, lock files are ** named automatically using the same logic as ** PRAGMA lock_proxy_file=":auto:" ** ** SQLITE_PROXY_DEBUG ** ** Enables the logging of error messages during host id file ** retrieval and creation ** ** LOCKPROXYDIR ** ** Overrides the default directory used for lock proxy files that ** are named automatically via the ":auto:" setting ** ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS ** ** Permissions to use when creating a directory for storing the ** lock proxy files, only used when LOCKPROXYDIR is not set. ** ** ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING, ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will ** force proxy locking to be used for every database file opened, and 0 ** will force automatic proxy locking to be disabled for all database ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING). */ /* ** Proxy locking is only available on MacOSX */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** The proxyLockingContext has the path and file structures for the remote ** and local proxy files in it */ typedef struct proxyLockingContext proxyLockingContext; struct proxyLockingContext { unixFile *conchFile; /* Open conch file */ char *conchFilePath; /* Name of the conch file */ unixFile *lockProxy; /* Open proxy lock file */ char *lockProxyPath; /* Name of the proxy lock file */ char *dbPath; /* Name of the open file */ int conchHeld; /* 1 if the conch is held, -1 if lockless */ int nFails; /* Number of conch taking failures */ void *oldLockingContext; /* Original lockingcontext to restore on close */ sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ }; /* ** The proxy lock file path for the database at dbPath is written into lPath, ** which must point to valid, writable memory large enough for a maxLen length ** file path. */ static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ int len; int dbLen; int i; #ifdef LOCKPROXYDIR len = strlcpy(lPath, LOCKPROXYDIR, maxLen); #else # ifdef _CS_DARWIN_USER_TEMP_DIR { if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){ OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n", lPath, errno, osGetpid(0))); return SQLITE_IOERR_LOCK; } len = strlcat(lPath, "sqliteplocks", maxLen); } # else len = strlcpy(lPath, "/tmp/", maxLen); # endif #endif if( lPath[len-1]!='/' ){ len = strlcat(lPath, "/", maxLen); } /* transform the db path to a unique cache name */ dbLen = (int)strlen(dbPath); for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){ char c = dbPath[i]; lPath[i+len] = (c=='/')?'_':c; } lPath[i+len]='\0'; strlcat(lPath, ":auto:", maxLen); OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0))); return SQLITE_OK; } /* ** Creates the lock file and any missing directories in lockPath */ static int proxyCreateLockPath(const char *lockPath){ int i, len; char buf[MAXPATHLEN]; int start = 0; assert(lockPath!=NULL); /* try to create all the intermediate directories */ len = (int)strlen(lockPath); buf[0] = lockPath[0]; for( i=1; i<len; i++ ){ if( lockPath[i] == '/' && (i - start > 0) ){ /* only mkdir if leaf dir != "." or "/" or ".." */ if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){ buf[i]='\0'; if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){ int err=errno; if( err!=EEXIST ) { OSTRACE(("CREATELOCKPATH FAILED creating %s, " "'%s' proxy lock path=%s pid=%d\n", buf, strerror(err), lockPath, osGetpid(0))); return err; } } } start=i+1; } buf[i] = lockPath[i]; } OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0))); return 0; } /* ** Create a new VFS file descriptor (stored in memory obtained from ** sqlite3_malloc) and open the file named "path" in the file descriptor. ** ** The caller is responsible not only for closing the file descriptor ** but also for freeing the memory associated with the file descriptor. */ static int proxyCreateUnixFile( const char *path, /* path for the new unixFile */ unixFile **ppFile, /* unixFile created and returned by ref */ int islockfile /* if non zero missing dirs will be created */ ) { int fd = -1; unixFile *pNew; int rc = SQLITE_OK; int openFlags = O_RDWR | O_CREAT; sqlite3_vfs dummyVfs; int terrno = 0; UnixUnusedFd *pUnused = NULL; /* 1. first try to open/create the file ** 2. if that fails, and this is a lock file (not-conch), try creating ** the parent directories and then try again. ** 3. if that fails, try to open the file read-only ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file */ pUnused = findReusableFd(path, openFlags); if( pUnused ){ fd = pUnused->fd; }else{ pUnused = sqlite3_malloc64(sizeof(*pUnused)); if( !pUnused ){ return SQLITE_NOMEM_BKPT; } } if( fd<0 ){ fd = robust_open(path, openFlags, 0); terrno = errno; if( fd<0 && errno==ENOENT && islockfile ){ if( proxyCreateLockPath(path) == SQLITE_OK ){ fd = robust_open(path, openFlags, 0); } } } if( fd<0 ){ openFlags = O_RDONLY; fd = robust_open(path, openFlags, 0); terrno = errno; } if( fd<0 ){ if( islockfile ){ return SQLITE_BUSY; } switch (terrno) { case EACCES: return SQLITE_PERM; case EIO: return SQLITE_IOERR_LOCK; /* even though it is the conch */ default: return SQLITE_CANTOPEN_BKPT; } } pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew)); if( pNew==NULL ){ rc = SQLITE_NOMEM_BKPT; goto end_create_proxy; } memset(pNew, 0, sizeof(unixFile)); pNew->openFlags = openFlags; memset(&dummyVfs, 0, sizeof(dummyVfs)); dummyVfs.pAppData = (void*)&autolockIoFinder; dummyVfs.zName = "dummy"; pUnused->fd = fd; pUnused->flags = openFlags; pNew->pUnused = pUnused; rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0); if( rc==SQLITE_OK ){ *ppFile = pNew; return SQLITE_OK; } end_create_proxy: robust_close(pNew, fd, __LINE__); sqlite3_free(pNew); sqlite3_free(pUnused); return rc; } #ifdef SQLITE_TEST /* simulate multiple hosts by creating unique hostid file paths */ SQLITE_API int sqlite3_hostid_num = 0; #endif #define PROXY_HOSTIDLEN 16 /* conch file host id length */ #ifdef HAVE_GETHOSTUUID /* Not always defined in the headers as it ought to be */ extern int gethostuuid(uuid_t id, const struct timespec *wait); #endif /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN ** bytes of writable memory. */ static int proxyGetHostID(unsigned char *pHostID, int *pError){ assert(PROXY_HOSTIDLEN == sizeof(uuid_t)); memset(pHostID, 0, PROXY_HOSTIDLEN); #ifdef HAVE_GETHOSTUUID { struct timespec timeout = {1, 0}; /* 1 sec timeout */ if( gethostuuid(pHostID, &timeout) ){ int err = errno; if( pError ){ *pError = err; } return SQLITE_IOERR; } } #else UNUSED_PARAMETER(pError); #endif #ifdef SQLITE_TEST /* simulate multiple hosts by creating unique hostid file paths */ if( sqlite3_hostid_num != 0){ pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF)); } #endif return SQLITE_OK; } /* The conch file contains the header, host id and lock file path */ #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */ #define PROXY_HEADERLEN 1 /* conch file header length */ #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN) #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN) /* ** Takes an open conch file, copies the contents to a new path and then moves ** it back. The newly created file's file descriptor is assigned to the ** conch file structure and finally the original conch file descriptor is ** closed. Returns zero if successful. */ static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; unixFile *conchFile = pCtx->conchFile; char tPath[MAXPATHLEN]; char buf[PROXY_MAXCONCHLEN]; char *cPath = pCtx->conchFilePath; size_t readLen = 0; size_t pathLen = 0; char errmsg[64] = ""; int fd = -1; int rc = -1; UNUSED_PARAMETER(myHostID); /* create a new path by replace the trailing '-conch' with '-break' */ pathLen = strlcpy(tPath, cPath, MAXPATHLEN); if( pathLen>MAXPATHLEN || pathLen<6 || (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen); goto end_breaklock; } /* read the conch content */ readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); if( readLen<PROXY_PATHINDEX ){ sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen); goto end_breaklock; } /* write it out to the temporary break file */ fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0); if( fd<0 ){ sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno); goto end_breaklock; } if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){ sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno); goto end_breaklock; } if( rename(tPath, cPath) ){ sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno); goto end_breaklock; } rc = 0; fprintf(stderr, "broke stale lock on %s\n", cPath); robust_close(pFile, conchFile->h, __LINE__); conchFile->h = fd; conchFile->openFlags = O_RDWR | O_CREAT; end_breaklock: if( rc ){ if( fd>=0 ){ osUnlink(tPath); robust_close(pFile, fd, __LINE__); } fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg); } return rc; } /* Take the requested lock on the conch file and break a stale lock if the ** host id matches. */ static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; unixFile *conchFile = pCtx->conchFile; int rc = SQLITE_OK; int nTries = 0; struct timespec conchModTime; memset(&conchModTime, 0, sizeof(conchModTime)); do { rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); nTries ++; if( rc==SQLITE_BUSY ){ /* If the lock failed (busy): * 1st try: get the mod time of the conch, wait 0.5s and try again. * 2nd try: fail if the mod time changed or host id is different, wait * 10 sec and try again * 3rd try: break the lock unless the mod time has changed. */ struct stat buf; if( osFstat(conchFile->h, &buf) ){ storeLastErrno(pFile, errno); return SQLITE_IOERR_LOCK; } if( nTries==1 ){ conchModTime = buf.st_mtimespec; usleep(500000); /* wait 0.5 sec and try the lock again*/ continue; } assert( nTries>1 ); if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){ return SQLITE_BUSY; } if( nTries==2 ){ char tBuf[PROXY_MAXCONCHLEN]; int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0); if( len<0 ){ storeLastErrno(pFile, errno); return SQLITE_IOERR_LOCK; } if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){ /* don't break the lock if the host id doesn't match */ if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){ return SQLITE_BUSY; } }else{ /* don't break the lock on short read or a version mismatch */ return SQLITE_BUSY; } usleep(10000000); /* wait 10 sec and try the lock again */ continue; } assert( nTries==3 ); if( 0==proxyBreakConchLock(pFile, myHostID) ){ rc = SQLITE_OK; if( lockType==EXCLUSIVE_LOCK ){ rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); } if( !rc ){ rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); } } } } while( rc==SQLITE_BUSY && nTries<3 ); return rc; } /* Takes the conch by taking a shared lock and read the contents conch, if ** lockPath is non-NULL, the host ID and lock file path must match. A NULL ** lockPath means that the lockPath in the conch file will be used if the ** host IDs match, or a new lock path will be generated automatically ** and written to the conch file. */ static int proxyTakeConch(unixFile *pFile){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld!=0 ){ return SQLITE_OK; }else{ unixFile *conchFile = pCtx->conchFile; uuid_t myHostID; int pError = 0; char readBuf[PROXY_MAXCONCHLEN]; char lockPath[MAXPATHLEN]; char *tempLockPath = NULL; int rc = SQLITE_OK; int createConch = 0; int hostIdMatch = 0; int readLen = 0; int tryOldLockPath = 0; int forceNewLockPath = 0; OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h, (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), osGetpid(0))); rc = proxyGetHostID(myHostID, &pError); if( (rc&0xff)==SQLITE_IOERR ){ storeLastErrno(pFile, pError); goto end_takeconch; } rc = proxyConchLock(pFile, myHostID, SHARED_LOCK); if( rc!=SQLITE_OK ){ goto end_takeconch; } /* read the existing conch file */ readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN); if( readLen<0 ){ /* I/O error: lastErrno set by seekAndRead */ storeLastErrno(pFile, conchFile->lastErrno); rc = SQLITE_IOERR_READ; goto end_takeconch; }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || readBuf[0]!=(char)PROXY_CONCHVERSION ){ /* a short read or version format mismatch means we need to create a new ** conch file. */ createConch = 1; } /* if the host id matches and the lock path already exists in the conch ** we'll try to use the path there, if we can't open that path, we'll ** retry with a new auto-generated path */ do { /* in case we need to try again for an :auto: named lock file */ if( !createConch && !forceNewLockPath ){ hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); /* if the conch has data compare the contents */ if( !pCtx->lockProxyPath ){ /* for auto-named local lock file, just check the host ID and we'll ** use the local lock file path that's already in there */ if( hostIdMatch ){ size_t pathLen = (readLen - PROXY_PATHINDEX); if( pathLen>=MAXPATHLEN ){ pathLen=MAXPATHLEN-1; } memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); lockPath[pathLen] = 0; tempLockPath = lockPath; tryOldLockPath = 1; /* create a copy of the lock path if the conch is taken */ goto end_takeconch; } }else if( hostIdMatch && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX], readLen-PROXY_PATHINDEX) ){ /* conch host and lock path match */ goto end_takeconch; } } /* if the conch isn't writable and doesn't match, we can't take it */ if( (conchFile->openFlags&O_RDWR) == 0 ){ rc = SQLITE_BUSY; goto end_takeconch; } /* either the conch didn't match or we need to create a new one */ if( !pCtx->lockProxyPath ){ proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); tempLockPath = lockPath; /* create a copy of the lock path _only_ if the conch is taken */ } /* update conch with host and path (this will fail if other process ** has a shared lock already), if the host id matches, use the big ** stick. */ futimes(conchFile->h, NULL); if( hostIdMatch && !createConch ){ if( conchFile->pInode && conchFile->pInode->nShared>1 ){ /* We are trying for an exclusive lock but another thread in this ** same process is still holding a shared lock. */ rc = SQLITE_BUSY; } else { rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); } }else{ rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); } if( rc==SQLITE_OK ){ char writeBuffer[PROXY_MAXCONCHLEN]; int writeSize = 0; writeBuffer[0] = (char)PROXY_CONCHVERSION; memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); if( pCtx->lockProxyPath!=NULL ){ strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN); }else{ strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN); } writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]); robust_ftruncate(conchFile->h, writeSize); rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0); full_fsync(conchFile->h,0,0); /* If we created a new conch file (not just updated the contents of a ** valid conch file), try to match the permissions of the database */ if( rc==SQLITE_OK && createConch ){ struct stat buf; int err = osFstat(pFile->h, &buf); if( err==0 ){ mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP | S_IROTH|S_IWOTH); /* try to match the database file R/W permissions, ignore failure */ #ifndef SQLITE_PROXY_DEBUG osFchmod(conchFile->h, cmode); #else do{ rc = osFchmod(conchFile->h, cmode); }while( rc==(-1) && errno==EINTR ); if( rc!=0 ){ int code = errno; fprintf(stderr, "fchmod %o FAILED with %d %s\n", cmode, code, strerror(code)); } else { fprintf(stderr, "fchmod %o SUCCEDED\n",cmode); } }else{ int code = errno; fprintf(stderr, "STAT FAILED[%d] with %d %s\n", err, code, strerror(code)); #endif } } } conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); end_takeconch: OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h)); if( rc==SQLITE_OK && pFile->openFlags ){ int fd; if( pFile->h>=0 ){ robust_close(pFile, pFile->h, __LINE__); } pFile->h = -1; fd = robust_open(pCtx->dbPath, pFile->openFlags, 0); OSTRACE(("TRANSPROXY: OPEN %d\n", fd)); if( fd>=0 ){ pFile->h = fd; }else{ rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called during locking */ } } if( rc==SQLITE_OK && !pCtx->lockProxy ){ char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath; rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1); if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){ /* we couldn't create the proxy lock file with the old lock file path ** so try again via auto-naming */ forceNewLockPath = 1; tryOldLockPath = 0; continue; /* go back to the do {} while start point, try again */ } } if( rc==SQLITE_OK ){ /* Need to make a copy of path if we extracted the value ** from the conch file or the path was allocated on the stack */ if( tempLockPath ){ pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); if( !pCtx->lockProxyPath ){ rc = SQLITE_NOMEM_BKPT; } } } if( rc==SQLITE_OK ){ pCtx->conchHeld = 1; if( pCtx->lockProxy->pMethod == &afpIoMethods ){ afpLockingContext *afpCtx; afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext; afpCtx->dbPath = pCtx->lockProxyPath; } } else { conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); } OSTRACE(("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed")); return rc; } while (1); /* in case we need to retry the :auto: lock file - ** we should never get here except via the 'continue' call. */ } } /* ** If pFile holds a lock on a conch file, then release that lock. */ static int proxyReleaseConch(unixFile *pFile){ int rc = SQLITE_OK; /* Subroutine return code */ proxyLockingContext *pCtx; /* The locking context for the proxy lock */ unixFile *conchFile; /* Name of the conch file */ pCtx = (proxyLockingContext *)pFile->lockingContext; conchFile = pCtx->conchFile; OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h, (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), osGetpid(0))); if( pCtx->conchHeld>0 ){ rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); } pCtx->conchHeld = 0; OSTRACE(("RELEASECONCH %d %s\n", conchFile->h, (rc==SQLITE_OK ? "ok" : "failed"))); return rc; } /* ** Given the name of a database file, compute the name of its conch file. ** Store the conch filename in memory obtained from sqlite3_malloc64(). ** Make *pConchPath point to the new name. Return SQLITE_OK on success ** or SQLITE_NOMEM if unable to obtain memory. ** ** The caller is responsible for ensuring that the allocated memory ** space is eventually freed. ** ** *pConchPath is set to NULL if a memory allocation error occurs. */ static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ int i; /* Loop counter */ int len = (int)strlen(dbPath); /* Length of database filename - dbPath */ char *conchPath; /* buffer in which to construct conch name */ /* Allocate space for the conch filename and initialize the name to ** the name of the original database file. */ *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8); if( conchPath==0 ){ return SQLITE_NOMEM_BKPT; } memcpy(conchPath, dbPath, len+1); /* now insert a "." before the last / character */ for( i=(len-1); i>=0; i-- ){ if( conchPath[i]=='/' ){ i++; break; } } conchPath[i]='.'; while ( i<len ){ conchPath[i+1]=dbPath[i]; i++; } /* append the "-conch" suffix to the file */ memcpy(&conchPath[i+1], "-conch", 7); assert( (int)strlen(conchPath) == len+7 ); return SQLITE_OK; } /* Takes a fully configured proxy locking-style unix file and switches ** the local lock file path */ static int switchLockProxyPath(unixFile *pFile, const char *path) { proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; char *oldPath = pCtx->lockProxyPath; int rc = SQLITE_OK; if( pFile->eFileLock!=NO_LOCK ){ return SQLITE_BUSY; } /* nothing to do if the path is NULL, :auto: or matches the existing path */ if( !path || path[0]=='\0' || !strcmp(path, ":auto:") || (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){ return SQLITE_OK; }else{ unixFile *lockProxy = pCtx->lockProxy; pCtx->lockProxy=NULL; pCtx->conchHeld = 0; if( lockProxy!=NULL ){ rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy); if( rc ) return rc; sqlite3_free(lockProxy); } sqlite3_free(oldPath); pCtx->lockProxyPath = sqlite3DbStrDup(0, path); } return rc; } /* ** pFile is a file that has been opened by a prior xOpen call. dbPath ** is a string buffer at least MAXPATHLEN+1 characters in size. ** ** This routine find the filename associated with pFile and writes it ** int dbPath. */ static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ #if defined(__APPLE__) if( pFile->pMethod == &afpIoMethods ){ /* afp style keeps a reference to the db path in the filePath field ** of the struct */ assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN); } else #endif if( pFile->pMethod == &dotlockIoMethods ){ /* dot lock style uses the locking context to store the dot lock ** file path */ int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); memcpy(dbPath, (char *)pFile->lockingContext, len + 1); }else{ /* all other styles use the locking context to store the db file path */ assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN); } return SQLITE_OK; } /* ** Takes an already filled in unix file and alters it so all file locking ** will be performed on the local proxy lock file. The following fields ** are preserved in the locking context so that they can be restored and ** the unix structure properly cleaned up at close time: ** ->lockingContext ** ->pMethod */ static int proxyTransformUnixFile(unixFile *pFile, const char *path) { proxyLockingContext *pCtx; char dbPath[MAXPATHLEN+1]; /* Name of the database file */ char *lockPath=NULL; int rc = SQLITE_OK; if( pFile->eFileLock!=NO_LOCK ){ return SQLITE_BUSY; } proxyGetDbPathForUnixFile(pFile, dbPath); if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){ lockPath=NULL; }else{ lockPath=(char *)path; } OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h, (lockPath ? lockPath : ":auto:"), osGetpid(0))); pCtx = sqlite3_malloc64( sizeof(*pCtx) ); if( pCtx==0 ){ return SQLITE_NOMEM_BKPT; } memset(pCtx, 0, sizeof(*pCtx)); rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); if( rc==SQLITE_OK ){ rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0); if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){ /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and ** (c) the file system is read-only, then enable no-locking access. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts ** that openFlags will have only one of O_RDONLY or O_RDWR. */ struct statfs fsInfo; struct stat conchInfo; int goLockless = 0; if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) { int err = errno; if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){ goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY; } } if( goLockless ){ pCtx->conchHeld = -1; /* read only FS/ lockless */ rc = SQLITE_OK; } } } if( rc==SQLITE_OK && lockPath ){ pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); } if( rc==SQLITE_OK ){ pCtx->dbPath = sqlite3DbStrDup(0, dbPath); if( pCtx->dbPath==NULL ){ rc = SQLITE_NOMEM_BKPT; } } if( rc==SQLITE_OK ){ /* all memory is allocated, proxys are created and assigned, ** switch the locking context and pMethod then return. */ pCtx->oldLockingContext = pFile->lockingContext; pFile->lockingContext = pCtx; pCtx->pOldMethod = pFile->pMethod; pFile->pMethod = &proxyIoMethods; }else{ if( pCtx->conchFile ){ pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); sqlite3_free(pCtx->conchFile); } sqlite3DbFree(0, pCtx->lockProxyPath); sqlite3_free(pCtx->conchFilePath); sqlite3_free(pCtx); } OSTRACE(("TRANSPROXY %d %s\n", pFile->h, (rc==SQLITE_OK ? "ok" : "failed"))); return rc; } /* ** This routine handles sqlite3_file_control() calls that are specific ** to proxy locking. */ static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ switch( op ){ case SQLITE_FCNTL_GET_LOCKPROXYFILE: { unixFile *pFile = (unixFile*)id; if( pFile->pMethod == &proxyIoMethods ){ proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; proxyTakeConch(pFile); if( pCtx->lockProxyPath ){ *(const char **)pArg = pCtx->lockProxyPath; }else{ *(const char **)pArg = ":auto: (not held)"; } } else { *(const char **)pArg = NULL; } return SQLITE_OK; } case SQLITE_FCNTL_SET_LOCKPROXYFILE: { unixFile *pFile = (unixFile*)id; int rc = SQLITE_OK; int isProxyStyle = (pFile->pMethod == &proxyIoMethods); if( pArg==NULL || (const char *)pArg==0 ){ if( isProxyStyle ){ /* turn off proxy locking - not supported. If support is added for ** switching proxy locking mode off then it will need to fail if ** the journal mode is WAL mode. */ rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/; }else{ /* turn off proxy locking - already off - NOOP */ rc = SQLITE_OK; } }else{ const char *proxyPath = (const char *)pArg; if( isProxyStyle ){ proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; if( !strcmp(pArg, ":auto:") || (pCtx->lockProxyPath && !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN)) ){ rc = SQLITE_OK; }else{ rc = switchLockProxyPath(pFile, proxyPath); } }else{ /* turn on proxy file locking */ rc = proxyTransformUnixFile(pFile, proxyPath); } } return rc; } default: { assert( 0 ); /* The call assures that only valid opcodes are sent */ } } /*NOTREACHED*/ return SQLITE_ERROR; } /* ** Within this division (the proxying locking implementation) the procedures ** above this point are all utilities. The lock-related methods of the ** proxy-locking sqlite3_io_method object follow. */ /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, set *pResOut ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); }else{ /* conchHeld < 0 is lockless */ pResOut=0; } } return rc; } /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. Use the sqlite3OsUnlock() ** routine to lower a locking level. */ static int proxyLock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock); pFile->eFileLock = proxy->eFileLock; }else{ /* conchHeld < 0 is lockless */ } } return rc; } /* ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ static int proxyUnlock(sqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock); pFile->eFileLock = proxy->eFileLock; }else{ /* conchHeld < 0 is lockless */ } } return rc; } /* ** Close a file that uses proxy locks. */ static int proxyClose(sqlite3_file *id) { if( ALWAYS(id) ){ unixFile *pFile = (unixFile*)id; proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; unixFile *lockProxy = pCtx->lockProxy; unixFile *conchFile = pCtx->conchFile; int rc = SQLITE_OK; if( lockProxy ){ rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK); if( rc ) return rc; rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy); if( rc ) return rc; sqlite3_free(lockProxy); pCtx->lockProxy = 0; } if( conchFile ){ if( pCtx->conchHeld ){ rc = proxyReleaseConch(pFile); if( rc ) return rc; } rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); if( rc ) return rc; sqlite3_free(conchFile); } sqlite3DbFree(0, pCtx->lockProxyPath); sqlite3_free(pCtx->conchFilePath); sqlite3DbFree(0, pCtx->dbPath); /* restore the original locking context and pMethod then close it */ pFile->lockingContext = pCtx->oldLockingContext; pFile->pMethod = pCtx->pOldMethod; sqlite3_free(pCtx); return pFile->pMethod->xClose(id); } return SQLITE_OK; } #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ /* ** The proxy locking style is intended for use with AFP filesystems. ** And since AFP is only supported on MacOSX, the proxy locking is also ** restricted to MacOSX. ** ** ******************* End of the proxy lock implementation ********************** ******************************************************************************/ /* ** Initialize the operating system interface. ** ** This routine registers all VFS implementations for unix-like operating ** systems. This routine, and the sqlite3_os_end() routine that follows, ** should be the only routines in this file that are visible from other ** files. ** ** This routine is called once during SQLite initialization and by a ** single thread. The memory allocation and mutex subsystems have not ** necessarily been initialized when this routine is called, and so they ** should not be used. */ SQLITE_API int sqlite3_os_init(void){ /* ** The following macro defines an initializer for an sqlite3_vfs object. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer ** to the "finder" function. (pAppData is a pointer to a pointer because ** silly C90 rules prohibit a void* from being cast to a function pointer ** and so we have to go through the intermediate pointer to avoid problems ** when compiling with -pedantic-errors on GCC.) ** ** The FINDER parameter to this macro is the name of the pointer to the ** finder-function. The finder-function returns a pointer to the ** sqlite_io_methods object that implements the desired locking ** behaviors. See the division above that contains the IOMETHODS ** macro for addition information on finder-functions. ** ** Most finders simply return a pointer to a fixed sqlite3_io_methods ** object. But the "autolockIoFinder" available on MacOSX does a little ** more than that; it looks at the filesystem type that hosts the ** database file and tries to choose an locking method appropriate for ** that filesystem time. */ #define UNIXVFS(VFSNAME, FINDER) { \ 3, /* iVersion */ \ sizeof(unixFile), /* szOsFile */ \ MAX_PATHNAME, /* mxPathname */ \ 0, /* pNext */ \ VFSNAME, /* zName */ \ (void*)&FINDER, /* pAppData */ \ unixOpen, /* xOpen */ \ unixDelete, /* xDelete */ \ unixAccess, /* xAccess */ \ unixFullPathname, /* xFullPathname */ \ unixDlOpen, /* xDlOpen */ \ unixDlError, /* xDlError */ \ unixDlSym, /* xDlSym */ \ unixDlClose, /* xDlClose */ \ unixRandomness, /* xRandomness */ \ unixSleep, /* xSleep */ \ unixCurrentTime, /* xCurrentTime */ \ unixGetLastError, /* xGetLastError */ \ unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \ unixSetSystemCall, /* xSetSystemCall */ \ unixGetSystemCall, /* xGetSystemCall */ \ unixNextSystemCall, /* xNextSystemCall */ \ } /* ** All default VFSes for unix are contained in the following array. ** ** Note that the sqlite3_vfs.pNext field of the VFS object is modified ** by the SQLite core when the VFS is registered. So the following ** array cannot be const. */ static sqlite3_vfs aVfs[] = { #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) UNIXVFS("unix", autolockIoFinder ), #elif OS_VXWORKS UNIXVFS("unix", vxworksIoFinder ), #else UNIXVFS("unix", posixIoFinder ), #endif UNIXVFS("unix-none", nolockIoFinder ), UNIXVFS("unix-dotfile", dotlockIoFinder ), UNIXVFS("unix-excl", posixIoFinder ), #if OS_VXWORKS UNIXVFS("unix-namedsem", semIoFinder ), #endif #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS UNIXVFS("unix-posix", posixIoFinder ), #endif #if SQLITE_ENABLE_LOCKING_STYLE UNIXVFS("unix-flock", flockIoFinder ), #endif #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) UNIXVFS("unix-afp", afpIoFinder ), UNIXVFS("unix-nfs", nfsIoFinder ), UNIXVFS("unix-proxy", proxyIoFinder ), #endif }; unsigned int i; /* Loop counter */ /* Double-check that the aSyscall[] array has been constructed ** correctly. See ticket [bb3a86e890c8e96ab] */ assert( ArraySize(aSyscall)==28 ); /* Register all VFSes defined in the aVfs[] array */ for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ sqlite3_vfs_register(&aVfs[i], i==0); } return SQLITE_OK; } /* ** Shutdown the operating system interface. ** ** Some operating systems might need to do some cleanup in this routine, ** to release dynamically allocated objects. But not on unix. ** This routine is a no-op for unix. */ SQLITE_API int sqlite3_os_end(void){ return SQLITE_OK; } #endif /* SQLITE_OS_UNIX */ /************** End of os_unix.c *********************************************/ /************** Begin file os_win.c ******************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that is specific to Windows. */ /* #include "sqliteInt.h" */ #if SQLITE_OS_WIN /* This file is used for Windows only */ /* ** Include code that is common to all os_*.c files */ /************** Include os_common.h in the middle of os_win.c ****************/ /************** Begin file os_common.h ***************************************/ /* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. */ #ifndef _OS_COMMON_H_ #define _OS_COMMON_H_ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #ifdef MEMORY_DEBUG # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #ifdef SQLITE_PERFORMANCE_TRACE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ /************** Include hwtime.h in the middle of os_common.h ****************/ /************** Begin file hwtime.h ******************************************/ /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if (defined(__GNUC__) || defined(_MSC_VER)) && \ (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; } #elif defined(_MSC_VER) __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else #error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif #endif /* !defined(SQLITE_HWTIME_H) */ /************** End of hwtime.h **********************************************/ /************** Continuing where we left off in os_common.h ******************/ static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; #define TIMER_START g_start=sqlite3Hwtime() #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START #define TIMER_END #define TIMER_ELAPSED ((sqlite_uint64)0) #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_io_error_hit; SQLITE_API extern int sqlite3_io_error_hardhit; SQLITE_API extern int sqlite3_io_error_pending; SQLITE_API extern int sqlite3_io_error_persist; SQLITE_API extern int sqlite3_io_error_benign; SQLITE_API extern int sqlite3_diskfull_pending; SQLITE_API extern int sqlite3_diskfull; #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ || sqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); sqlite3_io_error_hit++; if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ if( sqlite3_diskfull_pending ){ \ if( sqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ sqlite3_diskfull = 1; \ sqlite3_io_error_hit = 1; \ CODE; \ }else{ \ sqlite3_diskfull_pending--; \ } \ } #else #define SimulateIOErrorBenign(X) #define SimulateIOError(A) #define SimulateDiskfullError(A) #endif /* defined(SQLITE_TEST) */ /* ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) SQLITE_API extern int sqlite3_open_file_count; #define OpenCounter(X) sqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ #endif /* !defined(_OS_COMMON_H_) */ /************** End of os_common.h *******************************************/ /************** Continuing where we left off in os_win.c *********************/ /* ** Include the header file for the Windows VFS. */ /* #include "os_win.h" */ /* ** Compiling and using WAL mode requires several APIs that are only ** available in Windows platforms based on the NT kernel. */ #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL) # error "WAL mode requires support from the Windows NT kernel, compile\ with SQLITE_OMIT_WAL." #endif #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0 # error "Memory mapped files require support from the Windows NT kernel,\ compile with SQLITE_MAX_MMAP_SIZE=0." #endif /* ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions ** based on the sub-platform)? */ #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI) # define SQLITE_WIN32_HAS_ANSI #endif /* ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions ** based on the sub-platform)? */ #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \ !defined(SQLITE_WIN32_NO_WIDE) # define SQLITE_WIN32_HAS_WIDE #endif /* ** Make sure at least one set of Win32 APIs is available. */ #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE) # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\ must be defined." #endif /* ** Define the required Windows SDK version constants if they are not ** already available. */ #ifndef NTDDI_WIN8 # define NTDDI_WIN8 0x06020000 #endif #ifndef NTDDI_WINBLUE # define NTDDI_WINBLUE 0x06030000 #endif #ifndef NTDDI_WINTHRESHOLD # define NTDDI_WINTHRESHOLD 0x06040000 #endif /* ** Check to see if the GetVersionEx[AW] functions are deprecated on the ** target system. GetVersionEx was first deprecated in Win8.1. */ #ifndef SQLITE_WIN32_GETVERSIONEX # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */ # else # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */ # endif #endif /* ** Check to see if the CreateFileMappingA function is supported on the ** target system. It is unavailable when using "mincore.lib" on Win10. ** When compiling for Windows 10, always assume "mincore.lib" is in use. */ #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD # define SQLITE_WIN32_CREATEFILEMAPPINGA 0 # else # define SQLITE_WIN32_CREATEFILEMAPPINGA 1 # endif #endif /* ** This constant should already be defined (in the "WinDef.h" SDK file). */ #ifndef MAX_PATH # define MAX_PATH (260) #endif /* ** Maximum pathname length (in chars) for Win32. This should normally be ** MAX_PATH. */ #ifndef SQLITE_WIN32_MAX_PATH_CHARS # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH) #endif /* ** This constant should already be defined (in the "WinNT.h" SDK file). */ #ifndef UNICODE_STRING_MAX_CHARS # define UNICODE_STRING_MAX_CHARS (32767) #endif /* ** Maximum pathname length (in chars) for WinNT. This should normally be ** UNICODE_STRING_MAX_CHARS. */ #ifndef SQLITE_WINNT_MAX_PATH_CHARS # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS) #endif /* ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in ** characters, so we allocate 4 bytes per character assuming worst-case of ** 4-bytes-per-character for UTF8. */ #ifndef SQLITE_WIN32_MAX_PATH_BYTES # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4) #endif /* ** Maximum pathname length (in bytes) for WinNT. This should normally be ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR). */ #ifndef SQLITE_WINNT_MAX_PATH_BYTES # define SQLITE_WINNT_MAX_PATH_BYTES \ (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS) #endif /* ** Maximum error message length (in chars) for WinRT. */ #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024) #endif /* ** Returns non-zero if the character should be treated as a directory ** separator. */ #ifndef winIsDirSep # define winIsDirSep(a) (((a) == '/') || ((a) == '\\')) #endif /* ** This macro is used when a local variable is set to a value that is ** [sometimes] not used by the code (e.g. via conditional compilation). */ #ifndef UNUSED_VARIABLE_VALUE # define UNUSED_VARIABLE_VALUE(x) (void)(x) #endif /* ** Returns the character that should be used as the directory separator. */ #ifndef winGetDirSep # define winGetDirSep() '\\' #endif /* ** Do we need to manually define the Win32 file mapping APIs for use with WAL ** mode or memory mapped files (e.g. these APIs are available in the Windows ** CE SDK; however, they are not present in the header file)? */ #if SQLITE_WIN32_FILEMAPPING_API && \ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) /* ** Two of the file mapping APIs are different under WinRT. Figure out which ** set we need. */ #if SQLITE_OS_WINRT WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \ LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR); WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T); #else #if defined(SQLITE_WIN32_HAS_ANSI) WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \ DWORD, DWORD, DWORD, LPCSTR); #endif /* defined(SQLITE_WIN32_HAS_ANSI) */ #if defined(SQLITE_WIN32_HAS_WIDE) WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \ DWORD, DWORD, DWORD, LPCWSTR); #endif /* defined(SQLITE_WIN32_HAS_WIDE) */ WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T); #endif /* SQLITE_OS_WINRT */ /* ** These file mapping APIs are common to both Win32 and WinRT. */ WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T); WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID); #endif /* SQLITE_WIN32_FILEMAPPING_API */ /* ** Some Microsoft compilers lack this definition. */ #ifndef INVALID_FILE_ATTRIBUTES # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) #endif #ifndef FILE_FLAG_MASK # define FILE_FLAG_MASK (0xFF3C0000) #endif #ifndef FILE_ATTRIBUTE_MASK # define FILE_ATTRIBUTE_MASK (0x0003FFF7) #endif #ifndef SQLITE_OMIT_WAL /* Forward references to structures used for WAL */ typedef struct winShm winShm; /* A connection to shared-memory */ typedef struct winShmNode winShmNode; /* A region of shared-memory */ #endif /* ** WinCE lacks native support for file locking so we have to fake it ** with some code of our own. */ #if SQLITE_OS_WINCE typedef struct winceLock { int nReaders; /* Number of reader locks obtained */ BOOL bPending; /* Indicates a pending lock has been obtained */ BOOL bReserved; /* Indicates a reserved lock has been obtained */ BOOL bExclusive; /* Indicates an exclusive lock has been obtained */ } winceLock; #endif /* ** The winFile structure is a subclass of sqlite3_file* specific to the win32 ** portability layer. */ typedef struct winFile winFile; struct winFile { const sqlite3_io_methods *pMethod; /*** Must be first ***/ sqlite3_vfs *pVfs; /* The VFS used to open this file */ HANDLE h; /* Handle for accessing the file */ u8 locktype; /* Type of lock currently held on this file */ short sharedLockByte; /* Randomly chosen byte used as a shared lock */ u8 ctrlFlags; /* Flags. See WINFILE_* below */ DWORD lastErrno; /* The Windows errno from the last I/O error */ #ifndef SQLITE_OMIT_WAL winShm *pShm; /* Instance of shared memory on this file */ #endif const char *zPath; /* Full pathname of this file */ int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */ #if SQLITE_OS_WINCE LPWSTR zDeleteOnClose; /* Name of file to delete when closing */ HANDLE hMutex; /* Mutex used to control access to shared lock */ HANDLE hShared; /* Shared memory segment used for locking */ winceLock local; /* Locks obtained by this instance of winFile */ winceLock *shared; /* Global shared lock memory for the file */ #endif #if SQLITE_MAX_MMAP_SIZE>0 int nFetchOut; /* Number of outstanding xFetch references */ HANDLE hMap; /* Handle for accessing memory mapping */ void *pMapRegion; /* Area memory mapped */ sqlite3_int64 mmapSize; /* Usable size of mapped region */ sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */ sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ #endif }; /* ** The winVfsAppData structure is used for the pAppData member for all of the ** Win32 VFS variants. */ typedef struct winVfsAppData winVfsAppData; struct winVfsAppData { const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */ void *pAppData; /* The extra pAppData, if any. */ BOOL bNoLock; /* Non-zero if locking is disabled. */ }; /* ** Allowed values for winFile.ctrlFlags */ #define WINFILE_RDONLY 0x02 /* Connection is read only */ #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ /* * The size of the buffer used by sqlite3_win32_write_debug(). */ #ifndef SQLITE_WIN32_DBG_BUF_SIZE # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD))) #endif /* * The value used with sqlite3_win32_set_directory() to specify that * the data directory should be changed. */ #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1) #endif /* * The value used with sqlite3_win32_set_directory() to specify that * the temporary directory should be changed. */ #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2) #endif /* * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the * various Win32 API heap functions instead of our own. */ #ifdef SQLITE_WIN32_MALLOC /* * If this is non-zero, an isolated heap will be created by the native Win32 * allocator subsystem; otherwise, the default process heap will be used. This * setting has no effect when compiling for WinRT. By default, this is enabled * and an isolated heap will be created to store all allocated data. * ****************************************************************************** * WARNING: It is important to note that when this setting is non-zero and the * winMemShutdown function is called (e.g. by the sqlite3_shutdown * function), all data that was allocated using the isolated heap will * be freed immediately and any attempt to access any of that freed * data will almost certainly result in an immediate access violation. ****************************************************************************** */ #ifndef SQLITE_WIN32_HEAP_CREATE # define SQLITE_WIN32_HEAP_CREATE (TRUE) #endif /* * This is cache size used in the calculation of the initial size of the * Win32-specific heap. It cannot be negative. */ #ifndef SQLITE_WIN32_CACHE_SIZE # if SQLITE_DEFAULT_CACHE_SIZE>=0 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE) # else # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE)) # endif #endif /* * The initial size of the Win32-specific heap. This value may be zero. */ #ifndef SQLITE_WIN32_HEAP_INIT_SIZE # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \ (SQLITE_DEFAULT_PAGE_SIZE) + 4194304) #endif /* * The maximum size of the Win32-specific heap. This value may be zero. */ #ifndef SQLITE_WIN32_HEAP_MAX_SIZE # define SQLITE_WIN32_HEAP_MAX_SIZE (0) #endif /* * The extra flags to use in calls to the Win32 heap APIs. This value may be * zero for the default behavior. */ #ifndef SQLITE_WIN32_HEAP_FLAGS # define SQLITE_WIN32_HEAP_FLAGS (0) #endif /* ** The winMemData structure stores information required by the Win32-specific ** sqlite3_mem_methods implementation. */ typedef struct winMemData winMemData; struct winMemData { #ifndef NDEBUG u32 magic1; /* Magic number to detect structure corruption. */ #endif HANDLE hHeap; /* The handle to our heap. */ BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */ #ifndef NDEBUG u32 magic2; /* Magic number to detect structure corruption. */ #endif }; #ifndef NDEBUG #define WINMEM_MAGIC1 0x42b2830b #define WINMEM_MAGIC2 0xbd4d7cf4 #endif static struct winMemData win_mem_data = { #ifndef NDEBUG WINMEM_MAGIC1, #endif NULL, FALSE #ifndef NDEBUG ,WINMEM_MAGIC2 #endif }; #ifndef NDEBUG #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 ) #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 ) #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2(); #else #define winMemAssertMagic() #endif #define winMemGetDataPtr() &win_mem_data #define winMemGetHeap() win_mem_data.hHeap #define winMemGetOwned() win_mem_data.bOwned static void *winMemMalloc(int nBytes); static void winMemFree(void *pPrior); static void *winMemRealloc(void *pPrior, int nBytes); static int winMemSize(void *p); static int winMemRoundup(int n); static int winMemInit(void *pAppData); static void winMemShutdown(void *pAppData); SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void); #endif /* SQLITE_WIN32_MALLOC */ /* ** The following variable is (normally) set once and never changes ** thereafter. It records whether the operating system is Win9x ** or WinNT. ** ** 0: Operating system unknown. ** 1: Operating system is Win9x. ** 2: Operating system is WinNT. ** ** In order to facilitate testing on a WinNT system, the test fixture ** can manually set this value to 1 to emulate Win98 behavior. */ #ifdef SQLITE_TEST SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; #else static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; #endif #ifndef SYSCALL # define SYSCALL sqlite3_syscall_ptr #endif /* ** This function is not available on Windows CE or WinRT. */ #if SQLITE_OS_WINCE || SQLITE_OS_WINRT # define osAreFileApisANSI() 1 #endif /* ** Many system calls are accessed through pointer-to-functions so that ** they may be overridden at runtime to facilitate fault injection during ** testing and sandboxing. The following array holds the names and pointers ** to all overrideable system calls. */ static struct win_syscall { const char *zName; /* Name of the system call */ sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ sqlite3_syscall_ptr pDefault; /* Default value */ } aSyscall[] = { #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 }, #else { "AreFileApisANSI", (SYSCALL)0, 0 }, #endif #ifndef osAreFileApisANSI #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent) #endif #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) { "CharLowerW", (SYSCALL)CharLowerW, 0 }, #else { "CharLowerW", (SYSCALL)0, 0 }, #endif #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent) #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) { "CharUpperW", (SYSCALL)CharUpperW, 0 }, #else { "CharUpperW", (SYSCALL)0, 0 }, #endif #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent) { "CloseHandle", (SYSCALL)CloseHandle, 0 }, #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "CreateFileA", (SYSCALL)CreateFileA, 0 }, #else { "CreateFileA", (SYSCALL)0, 0 }, #endif #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \ LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "CreateFileW", (SYSCALL)CreateFileW, 0 }, #else { "CreateFileW", (SYSCALL)0, 0 }, #endif #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \ LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \ SQLITE_WIN32_CREATEFILEMAPPINGA { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 }, #else { "CreateFileMappingA", (SYSCALL)0, 0 }, #endif #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent) #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)) { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 }, #else { "CreateFileMappingW", (SYSCALL)0, 0 }, #endif #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "CreateMutexW", (SYSCALL)CreateMutexW, 0 }, #else { "CreateMutexW", (SYSCALL)0, 0 }, #endif #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \ LPCWSTR))aSyscall[8].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "DeleteFileA", (SYSCALL)DeleteFileA, 0 }, #else { "DeleteFileA", (SYSCALL)0, 0 }, #endif #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "DeleteFileW", (SYSCALL)DeleteFileW, 0 }, #else { "DeleteFileW", (SYSCALL)0, 0 }, #endif #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent) #if SQLITE_OS_WINCE { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 }, #else { "FileTimeToLocalFileTime", (SYSCALL)0, 0 }, #endif #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \ LPFILETIME))aSyscall[11].pCurrent) #if SQLITE_OS_WINCE { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 }, #else { "FileTimeToSystemTime", (SYSCALL)0, 0 }, #endif #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \ LPSYSTEMTIME))aSyscall[12].pCurrent) { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 }, #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "FormatMessageA", (SYSCALL)FormatMessageA, 0 }, #else { "FormatMessageA", (SYSCALL)0, 0 }, #endif #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \ DWORD,va_list*))aSyscall[14].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "FormatMessageW", (SYSCALL)FormatMessageW, 0 }, #else { "FormatMessageW", (SYSCALL)0, 0 }, #endif #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \ DWORD,va_list*))aSyscall[15].pCurrent) #if !defined(SQLITE_OMIT_LOAD_EXTENSION) { "FreeLibrary", (SYSCALL)FreeLibrary, 0 }, #else { "FreeLibrary", (SYSCALL)0, 0 }, #endif #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent) { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 }, #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent) #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 }, #else { "GetDiskFreeSpaceA", (SYSCALL)0, 0 }, #endif #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \ LPDWORD))aSyscall[18].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 }, #else { "GetDiskFreeSpaceW", (SYSCALL)0, 0 }, #endif #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \ LPDWORD))aSyscall[19].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 }, #else { "GetFileAttributesA", (SYSCALL)0, 0 }, #endif #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 }, #else { "GetFileAttributesW", (SYSCALL)0, 0 }, #endif #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 }, #else { "GetFileAttributesExW", (SYSCALL)0, 0 }, #endif #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \ LPVOID))aSyscall[22].pCurrent) #if !SQLITE_OS_WINRT { "GetFileSize", (SYSCALL)GetFileSize, 0 }, #else { "GetFileSize", (SYSCALL)0, 0 }, #endif #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent) #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 }, #else { "GetFullPathNameA", (SYSCALL)0, 0 }, #endif #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \ LPSTR*))aSyscall[24].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 }, #else { "GetFullPathNameW", (SYSCALL)0, 0 }, #endif #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \ LPWSTR*))aSyscall[25].pCurrent) { "GetLastError", (SYSCALL)GetLastError, 0 }, #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent) #if !defined(SQLITE_OMIT_LOAD_EXTENSION) #if SQLITE_OS_WINCE /* The GetProcAddressA() routine is only available on Windows CE. */ { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 }, #else /* All other Windows platforms expect GetProcAddress() to take ** an ANSI string regardless of the _UNICODE setting */ { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 }, #endif #else { "GetProcAddressA", (SYSCALL)0, 0 }, #endif #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \ LPCSTR))aSyscall[27].pCurrent) #if !SQLITE_OS_WINRT { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 }, #else { "GetSystemInfo", (SYSCALL)0, 0 }, #endif #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent) { "GetSystemTime", (SYSCALL)GetSystemTime, 0 }, #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent) #if !SQLITE_OS_WINCE { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 }, #else { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 }, #endif #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \ LPFILETIME))aSyscall[30].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "GetTempPathA", (SYSCALL)GetTempPathA, 0 }, #else { "GetTempPathA", (SYSCALL)0, 0 }, #endif #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetTempPathW", (SYSCALL)GetTempPathW, 0 }, #else { "GetTempPathW", (SYSCALL)0, 0 }, #endif #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent) #if !SQLITE_OS_WINRT { "GetTickCount", (SYSCALL)GetTickCount, 0 }, #else { "GetTickCount", (SYSCALL)0, 0 }, #endif #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX { "GetVersionExA", (SYSCALL)GetVersionExA, 0 }, #else { "GetVersionExA", (SYSCALL)0, 0 }, #endif #define osGetVersionExA ((BOOL(WINAPI*)( \ LPOSVERSIONINFOA))aSyscall[34].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ SQLITE_WIN32_GETVERSIONEX { "GetVersionExW", (SYSCALL)GetVersionExW, 0 }, #else { "GetVersionExW", (SYSCALL)0, 0 }, #endif #define osGetVersionExW ((BOOL(WINAPI*)( \ LPOSVERSIONINFOW))aSyscall[35].pCurrent) { "HeapAlloc", (SYSCALL)HeapAlloc, 0 }, #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \ SIZE_T))aSyscall[36].pCurrent) #if !SQLITE_OS_WINRT { "HeapCreate", (SYSCALL)HeapCreate, 0 }, #else { "HeapCreate", (SYSCALL)0, 0 }, #endif #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \ SIZE_T))aSyscall[37].pCurrent) #if !SQLITE_OS_WINRT { "HeapDestroy", (SYSCALL)HeapDestroy, 0 }, #else { "HeapDestroy", (SYSCALL)0, 0 }, #endif #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent) { "HeapFree", (SYSCALL)HeapFree, 0 }, #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent) { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 }, #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \ SIZE_T))aSyscall[40].pCurrent) { "HeapSize", (SYSCALL)HeapSize, 0 }, #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \ LPCVOID))aSyscall[41].pCurrent) #if !SQLITE_OS_WINRT { "HeapValidate", (SYSCALL)HeapValidate, 0 }, #else { "HeapValidate", (SYSCALL)0, 0 }, #endif #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \ LPCVOID))aSyscall[42].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "HeapCompact", (SYSCALL)HeapCompact, 0 }, #else { "HeapCompact", (SYSCALL)0, 0 }, #endif #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION) { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 }, #else { "LoadLibraryA", (SYSCALL)0, 0 }, #endif #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent) #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ !defined(SQLITE_OMIT_LOAD_EXTENSION) { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 }, #else { "LoadLibraryW", (SYSCALL)0, 0 }, #endif #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent) #if !SQLITE_OS_WINRT { "LocalFree", (SYSCALL)LocalFree, 0 }, #else { "LocalFree", (SYSCALL)0, 0 }, #endif #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "LockFile", (SYSCALL)LockFile, 0 }, #else { "LockFile", (SYSCALL)0, 0 }, #endif #ifndef osLockFile #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ DWORD))aSyscall[47].pCurrent) #endif #if !SQLITE_OS_WINCE { "LockFileEx", (SYSCALL)LockFileEx, 0 }, #else { "LockFileEx", (SYSCALL)0, 0 }, #endif #ifndef osLockFileEx #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \ LPOVERLAPPED))aSyscall[48].pCurrent) #endif #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \ (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)) { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 }, #else { "MapViewOfFile", (SYSCALL)0, 0 }, #endif #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ SIZE_T))aSyscall[49].pCurrent) { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 }, #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \ int))aSyscall[50].pCurrent) { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 }, #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \ LARGE_INTEGER*))aSyscall[51].pCurrent) { "ReadFile", (SYSCALL)ReadFile, 0 }, #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \ LPOVERLAPPED))aSyscall[52].pCurrent) { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 }, #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent) #if !SQLITE_OS_WINRT { "SetFilePointer", (SYSCALL)SetFilePointer, 0 }, #else { "SetFilePointer", (SYSCALL)0, 0 }, #endif #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \ DWORD))aSyscall[54].pCurrent) #if !SQLITE_OS_WINRT { "Sleep", (SYSCALL)Sleep, 0 }, #else { "Sleep", (SYSCALL)0, 0 }, #endif #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent) { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 }, #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \ LPFILETIME))aSyscall[56].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "UnlockFile", (SYSCALL)UnlockFile, 0 }, #else { "UnlockFile", (SYSCALL)0, 0 }, #endif #ifndef osUnlockFile #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ DWORD))aSyscall[57].pCurrent) #endif #if !SQLITE_OS_WINCE { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 }, #else { "UnlockFileEx", (SYSCALL)0, 0 }, #endif #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ LPOVERLAPPED))aSyscall[58].pCurrent) #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 }, #else { "UnmapViewOfFile", (SYSCALL)0, 0 }, #endif #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent) { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 }, #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \ LPCSTR,LPBOOL))aSyscall[60].pCurrent) { "WriteFile", (SYSCALL)WriteFile, 0 }, #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \ LPOVERLAPPED))aSyscall[61].pCurrent) #if SQLITE_OS_WINRT { "CreateEventExW", (SYSCALL)CreateEventExW, 0 }, #else { "CreateEventExW", (SYSCALL)0, 0 }, #endif #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \ DWORD,DWORD))aSyscall[62].pCurrent) #if !SQLITE_OS_WINRT { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 }, #else { "WaitForSingleObject", (SYSCALL)0, 0 }, #endif #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \ DWORD))aSyscall[63].pCurrent) #if !SQLITE_OS_WINCE { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 }, #else { "WaitForSingleObjectEx", (SYSCALL)0, 0 }, #endif #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \ BOOL))aSyscall[64].pCurrent) #if SQLITE_OS_WINRT { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 }, #else { "SetFilePointerEx", (SYSCALL)0, 0 }, #endif #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \ PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent) #if SQLITE_OS_WINRT { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 }, #else { "GetFileInformationByHandleEx", (SYSCALL)0, 0 }, #endif #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \ FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent) #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 }, #else { "MapViewOfFileFromApp", (SYSCALL)0, 0 }, #endif #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \ SIZE_T))aSyscall[67].pCurrent) #if SQLITE_OS_WINRT { "CreateFile2", (SYSCALL)CreateFile2, 0 }, #else { "CreateFile2", (SYSCALL)0, 0 }, #endif #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \ LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent) #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION) { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 }, #else { "LoadPackagedLibrary", (SYSCALL)0, 0 }, #endif #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \ DWORD))aSyscall[69].pCurrent) #if SQLITE_OS_WINRT { "GetTickCount64", (SYSCALL)GetTickCount64, 0 }, #else { "GetTickCount64", (SYSCALL)0, 0 }, #endif #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent) #if SQLITE_OS_WINRT { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 }, #else { "GetNativeSystemInfo", (SYSCALL)0, 0 }, #endif #define osGetNativeSystemInfo ((VOID(WINAPI*)( \ LPSYSTEM_INFO))aSyscall[71].pCurrent) #if defined(SQLITE_WIN32_HAS_ANSI) { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 }, #else { "OutputDebugStringA", (SYSCALL)0, 0 }, #endif #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent) #if defined(SQLITE_WIN32_HAS_WIDE) { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 }, #else { "OutputDebugStringW", (SYSCALL)0, 0 }, #endif #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent) { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 }, #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent) #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 }, #else { "CreateFileMappingFromApp", (SYSCALL)0, 0 }, #endif #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \ LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent) /* ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function" ** is really just a macro that uses a compiler intrinsic (e.g. x64). ** So do not try to make this is into a redefinable interface. */ #if defined(InterlockedCompareExchange) { "InterlockedCompareExchange", (SYSCALL)0, 0 }, #define osInterlockedCompareExchange InterlockedCompareExchange #else { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 }, #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \ SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent) #endif /* defined(InterlockedCompareExchange) */ #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID { "UuidCreate", (SYSCALL)UuidCreate, 0 }, #else { "UuidCreate", (SYSCALL)0, 0 }, #endif #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent) #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 }, #else { "UuidCreateSequential", (SYSCALL)0, 0 }, #endif #define osUuidCreateSequential \ ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent) #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0 { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 }, #else { "FlushViewOfFile", (SYSCALL)0, 0 }, #endif #define osFlushViewOfFile \ ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent) }; /* End of the overrideable system calls */ /* ** This is the xSetSystemCall() method of sqlite3_vfs for all of the ** "win32" VFSes. Return SQLITE_OK opon successfully updating the ** system call pointer, or SQLITE_NOTFOUND if there is no configurable ** system call named zName. */ static int winSetSystemCall( sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ const char *zName, /* Name of system call to override */ sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ ){ unsigned int i; int rc = SQLITE_NOTFOUND; UNUSED_PARAMETER(pNotUsed); if( zName==0 ){ /* If no zName is given, restore all system calls to their default ** settings and return NULL */ rc = SQLITE_OK; for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ if( aSyscall[i].pDefault ){ aSyscall[i].pCurrent = aSyscall[i].pDefault; } } }else{ /* If zName is specified, operate on only the one system call ** specified. */ for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ if( strcmp(zName, aSyscall[i].zName)==0 ){ if( aSyscall[i].pDefault==0 ){ aSyscall[i].pDefault = aSyscall[i].pCurrent; } rc = SQLITE_OK; if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault; aSyscall[i].pCurrent = pNewFunc; break; } } } return rc; } /* ** Return the value of a system call. Return NULL if zName is not a ** recognized system call name. NULL is also returned if the system call ** is currently undefined. */ static sqlite3_syscall_ptr winGetSystemCall( sqlite3_vfs *pNotUsed, const char *zName ){ unsigned int i; UNUSED_PARAMETER(pNotUsed); for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent; } return 0; } /* ** Return the name of the first system call after zName. If zName==NULL ** then return the name of the first system call. Return NULL if zName ** is the last system call or if zName is not the name of a valid ** system call. */ static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){ int i = -1; UNUSED_PARAMETER(p); if( zName ){ for(i=0; i<ArraySize(aSyscall)-1; i++){ if( strcmp(zName, aSyscall[i].zName)==0 ) break; } } for(i++; i<ArraySize(aSyscall); i++){ if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName; } return 0; } #ifdef SQLITE_WIN32_MALLOC /* ** If a Win32 native heap has been configured, this function will attempt to ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The ** "pnLargest" argument, if non-zero, will be used to return the size of the ** largest committed free block in the heap, in bytes. */ SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){ int rc = SQLITE_OK; UINT nLargest = 0; HANDLE hHeap; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){ DWORD lastErrno = osGetLastError(); if( lastErrno==NO_ERROR ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p", (void*)hHeap); rc = SQLITE_NOMEM_BKPT; }else{ sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p", osGetLastError(), (void*)hHeap); rc = SQLITE_ERROR; } } #else sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p", (void*)hHeap); rc = SQLITE_NOTFOUND; #endif if( pnLargest ) *pnLargest = nLargest; return rc; } /* ** If a Win32 native heap has been configured, this function will attempt to ** destroy and recreate it. If the Win32 native heap is not isolated and/or ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will ** be returned and no changes will be made to the Win32 native heap. */ SQLITE_API int sqlite3_win32_reset_heap(){ int rc; MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */ MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); ) sqlite3_mutex_enter(pMaster); sqlite3_mutex_enter(pMem); winMemAssertMagic(); if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){ /* ** At this point, there should be no outstanding memory allocations on ** the heap. Also, since both the master and memsys locks are currently ** being held by us, no other function (i.e. from another thread) should ** be able to even access the heap. Attempt to destroy and recreate our ** isolated Win32 native heap now. */ assert( winMemGetHeap()!=NULL ); assert( winMemGetOwned() ); assert( sqlite3_memory_used()==0 ); winMemShutdown(winMemGetDataPtr()); assert( winMemGetHeap()==NULL ); assert( !winMemGetOwned() ); assert( sqlite3_memory_used()==0 ); rc = winMemInit(winMemGetDataPtr()); assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL ); assert( rc!=SQLITE_OK || winMemGetOwned() ); assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 ); }else{ /* ** The Win32 native heap cannot be modified because it may be in use. */ rc = SQLITE_BUSY; } sqlite3_mutex_leave(pMem); sqlite3_mutex_leave(pMaster); return rc; } #endif /* SQLITE_WIN32_MALLOC */ /* ** This function outputs the specified (ANSI) string to the Win32 debugger ** (if available). */ SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE]; int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */ if( nMin<-1 ) nMin = -1; /* all negative values become -1. */ assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE ); #ifdef SQLITE_ENABLE_API_ARMOR if( !zBuf ){ (void)SQLITE_MISUSE_BKPT; return; } #endif #if defined(SQLITE_WIN32_HAS_ANSI) if( nMin>0 ){ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); memcpy(zDbgBuf, zBuf, nMin); osOutputDebugStringA(zDbgBuf); }else{ osOutputDebugStringA(zBuf); } #elif defined(SQLITE_WIN32_HAS_WIDE) memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); if ( osMultiByteToWideChar( osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf, nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){ return; } osOutputDebugStringW((LPCWSTR)zDbgBuf); #else if( nMin>0 ){ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); memcpy(zDbgBuf, zBuf, nMin); fprintf(stderr, "%s", zDbgBuf); }else{ fprintf(stderr, "%s", zBuf); } #endif } /* ** The following routine suspends the current thread for at least ms ** milliseconds. This is equivalent to the Win32 Sleep() interface. */ #if SQLITE_OS_WINRT static HANDLE sleepObj = NULL; #endif SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){ #if SQLITE_OS_WINRT if ( sleepObj==NULL ){ sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET, SYNCHRONIZE); } assert( sleepObj!=NULL ); osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE); #else osSleep(milliseconds); #endif } #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ SQLITE_THREADSAFE>0 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){ DWORD rc; while( (rc = osWaitForSingleObjectEx(hObject, INFINITE, TRUE))==WAIT_IO_COMPLETION ){} return rc; } #endif /* ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, ** or WinCE. Return false (zero) for Win95, Win98, or WinME. ** ** Here is an interesting observation: Win95, Win98, and WinME lack ** the LockFileEx() API. But we can still statically link against that ** API as long as we don't call it when running Win95/98/ME. A call to ** this routine is used to determine if the host is Win95/98/ME or ** WinNT/2K/XP so that we will know whether or not we can safely call ** the LockFileEx() API. */ #if !SQLITE_WIN32_GETVERSIONEX # define osIsNT() (1) #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI) # define osIsNT() (1) #elif !defined(SQLITE_WIN32_HAS_WIDE) # define osIsNT() (0) #else # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt()) #endif /* ** This function determines if the machine is running a version of Windows ** based on the NT kernel. */ SQLITE_API int sqlite3_win32_is_nt(void){ #if SQLITE_OS_WINRT /* ** NOTE: The WinRT sub-platform is always assumed to be based on the NT ** kernel. */ return 1; #elif SQLITE_WIN32_GETVERSIONEX if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){ #if defined(SQLITE_WIN32_HAS_ANSI) OSVERSIONINFOA sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); osGetVersionExA(&sInfo); osInterlockedCompareExchange(&sqlite3_os_type, (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); #elif defined(SQLITE_WIN32_HAS_WIDE) OSVERSIONINFOW sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); osGetVersionExW(&sInfo); osInterlockedCompareExchange(&sqlite3_os_type, (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); #endif } return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; #elif SQLITE_TEST return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; #else /* ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are ** deprecated are always assumed to be based on the NT kernel. */ return 1; #endif } #ifdef SQLITE_WIN32_MALLOC /* ** Allocate nBytes of memory. */ static void *winMemMalloc(int nBytes){ HANDLE hHeap; void *p; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif assert( nBytes>=0 ); p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); if( !p ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p", nBytes, osGetLastError(), (void*)hHeap); } return p; } /* ** Free memory. */ static void winMemFree(void *pPrior){ HANDLE hHeap; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); #endif if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */ if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p", pPrior, osGetLastError(), (void*)hHeap); } } /* ** Change the size of an existing memory allocation */ static void *winMemRealloc(void *pPrior, int nBytes){ HANDLE hHeap; void *p; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); #endif assert( nBytes>=0 ); if( !pPrior ){ p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); }else{ p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes); } if( !p ){ sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p", pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(), (void*)hHeap); } return p; } /* ** Return the size of an outstanding allocation, in bytes. */ static int winMemSize(void *p){ HANDLE hHeap; SIZE_T n; winMemAssertMagic(); hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) ); #endif if( !p ) return 0; n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p); if( n==(SIZE_T)-1 ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p", p, osGetLastError(), (void*)hHeap); return 0; } return (int)n; } /* ** Round up a request size to the next valid allocation size. */ static int winMemRoundup(int n){ return n; } /* ** Initialize this module. */ static int winMemInit(void *pAppData){ winMemData *pWinMemData = (winMemData *)pAppData; if( !pWinMemData ) return SQLITE_ERROR; assert( pWinMemData->magic1==WINMEM_MAGIC1 ); assert( pWinMemData->magic2==WINMEM_MAGIC2 ); #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE if( !pWinMemData->hHeap ){ DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE; DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap; if( dwMaximumSize==0 ){ dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE; }else if( dwInitialSize>dwMaximumSize ){ dwInitialSize = dwMaximumSize; } pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS, dwInitialSize, dwMaximumSize); if( !pWinMemData->hHeap ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu", osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize, dwMaximumSize); return SQLITE_NOMEM_BKPT; } pWinMemData->bOwned = TRUE; assert( pWinMemData->bOwned ); } #else pWinMemData->hHeap = osGetProcessHeap(); if( !pWinMemData->hHeap ){ sqlite3_log(SQLITE_NOMEM, "failed to GetProcessHeap (%lu)", osGetLastError()); return SQLITE_NOMEM_BKPT; } pWinMemData->bOwned = FALSE; assert( !pWinMemData->bOwned ); #endif assert( pWinMemData->hHeap!=0 ); assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif return SQLITE_OK; } /* ** Deinitialize this module. */ static void winMemShutdown(void *pAppData){ winMemData *pWinMemData = (winMemData *)pAppData; if( !pWinMemData ) return; assert( pWinMemData->magic1==WINMEM_MAGIC1 ); assert( pWinMemData->magic2==WINMEM_MAGIC2 ); if( pWinMemData->hHeap ){ assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif if( pWinMemData->bOwned ){ if( !osHeapDestroy(pWinMemData->hHeap) ){ sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p", osGetLastError(), (void*)pWinMemData->hHeap); } pWinMemData->bOwned = FALSE; } pWinMemData->hHeap = NULL; } } /* ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. The ** arguments specify the block of memory to manage. ** ** This routine is only called by sqlite3_config(), and therefore ** is not required to be threadsafe (it is not). */ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){ static const sqlite3_mem_methods winMemMethods = { winMemMalloc, winMemFree, winMemRealloc, winMemSize, winMemRoundup, winMemInit, winMemShutdown, &win_mem_data }; return &winMemMethods; } SQLITE_PRIVATE void sqlite3MemSetDefault(void){ sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32()); } #endif /* SQLITE_WIN32_MALLOC */ /* ** Convert a UTF-8 string to Microsoft Unicode. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static LPWSTR winUtf8ToUnicode(const char *zText){ int nChar; LPWSTR zWideText; nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0); if( nChar==0 ){ return 0; } zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) ); if( zWideText==0 ){ return 0; } nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText, nChar); if( nChar==0 ){ sqlite3_free(zWideText); zWideText = 0; } return zWideText; } /* ** Convert a Microsoft Unicode string to UTF-8. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static char *winUnicodeToUtf8(LPCWSTR zWideText){ int nByte; char *zText; nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0); if( nByte == 0 ){ return 0; } zText = sqlite3MallocZero( nByte ); if( zText==0 ){ return 0; } nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte, 0, 0); if( nByte == 0 ){ sqlite3_free(zText); zText = 0; } return zText; } /* ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM ** code page. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){ int nByte; LPWSTR zMbcsText; int codepage = useAnsi ? CP_ACP : CP_OEMCP; nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL, 0)*sizeof(WCHAR); if( nByte==0 ){ return 0; } zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) ); if( zMbcsText==0 ){ return 0; } nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText, nByte); if( nByte==0 ){ sqlite3_free(zMbcsText); zMbcsText = 0; } return zMbcsText; } /* ** Convert a Microsoft Unicode string to a multi-byte character string, ** using the ANSI or OEM code page. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){ int nByte; char *zText; int codepage = useAnsi ? CP_ACP : CP_OEMCP; nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0); if( nByte == 0 ){ return 0; } zText = sqlite3MallocZero( nByte ); if( zText==0 ){ return 0; } nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText, nByte, 0, 0); if( nByte == 0 ){ sqlite3_free(zText); zText = 0; } return zText; } /* ** Convert a multi-byte character string to UTF-8. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static char *winMbcsToUtf8(const char *zText, int useAnsi){ char *zTextUtf8; LPWSTR zTmpWide; zTmpWide = winMbcsToUnicode(zText, useAnsi); if( zTmpWide==0 ){ return 0; } zTextUtf8 = winUnicodeToUtf8(zTmpWide); sqlite3_free(zTmpWide); return zTextUtf8; } /* ** Convert a UTF-8 string to a multi-byte character string. ** ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static char *winUtf8ToMbcs(const char *zText, int useAnsi){ char *zTextMbcs; LPWSTR zTmpWide; zTmpWide = winUtf8ToUnicode(zText); if( zTmpWide==0 ){ return 0; } zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi); sqlite3_free(zTmpWide); return zTextMbcs; } /* ** This is a public wrapper for the winUtf8ToUnicode() function. */ SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winUtf8ToUnicode(zText); } /* ** This is a public wrapper for the winUnicodeToUtf8() function. */ SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zWideText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winUnicodeToUtf8(zWideText); } /* ** This is a public wrapper for the winMbcsToUtf8() function. */ SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winMbcsToUtf8(zText, osAreFileApisANSI()); } /* ** This is a public wrapper for the winMbcsToUtf8() function. */ SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winMbcsToUtf8(zText, useAnsi); } /* ** This is a public wrapper for the winUtf8ToMbcs() function. */ SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winUtf8ToMbcs(zText, osAreFileApisANSI()); } /* ** This is a public wrapper for the winUtf8ToMbcs() function. */ SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize() ) return 0; #endif return winUtf8ToMbcs(zText, useAnsi); } /* ** This function sets the data directory or the temporary directory based on ** the provided arguments. The type argument must be 1 in order to set the ** data directory or 2 in order to set the temporary directory. The zValue ** argument is the name of the directory to use. The return value will be ** SQLITE_OK if successful. */ SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){ char **ppDirectory = 0; #ifndef SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if( rc ) return rc; #endif if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){ ppDirectory = &sqlite3_data_directory; }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){ ppDirectory = &sqlite3_temp_directory; } assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ); assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) ); if( ppDirectory ){ char *zValueUtf8 = 0; if( zValue && zValue[0] ){ zValueUtf8 = winUnicodeToUtf8(zValue); if ( zValueUtf8==0 ){ return SQLITE_NOMEM_BKPT; } } sqlite3_free(*ppDirectory); *ppDirectory = zValueUtf8; return SQLITE_OK; } return SQLITE_ERROR; } /* ** The return value of winGetLastErrorMsg ** is zero if the error message fits in the buffer, or non-zero ** otherwise (if the message was truncated). */ static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ /* FormatMessage returns 0 on failure. Otherwise it ** returns the number of TCHARs written to the output ** buffer, excluding the terminating null char. */ DWORD dwLen = 0; char *zOut = 0; if( osIsNT() ){ #if SQLITE_OS_WINRT WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1]; dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lastErrno, 0, zTempWide, SQLITE_WIN32_MAX_ERRMSG_CHARS, 0); #else LPWSTR zTempWide = NULL; dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lastErrno, 0, (LPWSTR) &zTempWide, 0, 0); #endif if( dwLen > 0 ){ /* allocate a buffer and convert to UTF8 */ sqlite3BeginBenignMalloc(); zOut = winUnicodeToUtf8(zTempWide); sqlite3EndBenignMalloc(); #if !SQLITE_OS_WINRT /* free the system buffer allocated by FormatMessage */ osLocalFree(zTempWide); #endif } } #ifdef SQLITE_WIN32_HAS_ANSI else{ char *zTemp = NULL; dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lastErrno, 0, (LPSTR) &zTemp, 0, 0); if( dwLen > 0 ){ /* allocate a buffer and convert to UTF8 */ sqlite3BeginBenignMalloc(); zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); sqlite3EndBenignMalloc(); /* free the system buffer allocated by FormatMessage */ osLocalFree(zTemp); } } #endif if( 0 == dwLen ){ sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno); }else{ /* copy a maximum of nBuf chars to output buffer */ sqlite3_snprintf(nBuf, zBuf, "%s", zOut); /* free the UTF8 buffer */ sqlite3_free(zOut); } return 0; } /* ** ** This function - winLogErrorAtLine() - is only ever called via the macro ** winLogError(). ** ** This routine is invoked after an error occurs in an OS function. ** It logs a message using sqlite3_log() containing the current value of ** error code and, if possible, the human-readable equivalent from ** FormatMessage. ** ** The first argument passed to the macro should be the error code that ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). ** The two subsequent arguments should be the name of the OS function that ** failed and the associated file-system path, if any. */ #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__) static int winLogErrorAtLine( int errcode, /* SQLite error code */ DWORD lastErrno, /* Win32 last error */ const char *zFunc, /* Name of OS function that failed */ const char *zPath, /* File path associated with error */ int iLine /* Source line number where error occurred */ ){ char zMsg[500]; /* Human readable error text */ int i; /* Loop counter */ zMsg[0] = 0; winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg); assert( errcode!=SQLITE_OK ); if( zPath==0 ) zPath = ""; for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){} zMsg[i] = 0; sqlite3_log(errcode, "os_win.c:%d: (%lu) %s(%s) - %s", iLine, lastErrno, zFunc, zPath, zMsg ); return errcode; } /* ** The number of times that a ReadFile(), WriteFile(), and DeleteFile() ** will be retried following a locking error - probably caused by ** antivirus software. Also the initial delay before the first retry. ** The delay increases linearly with each retry. */ #ifndef SQLITE_WIN32_IOERR_RETRY # define SQLITE_WIN32_IOERR_RETRY 10 #endif #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY # define SQLITE_WIN32_IOERR_RETRY_DELAY 25 #endif static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY; static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY; /* ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O ** error code obtained via GetLastError() is eligible to be retried. It ** must accept the error code DWORD as its only argument and should return ** non-zero if the error code is transient in nature and the operation ** responsible for generating the original error might succeed upon being ** retried. The argument to this macro should be a variable. ** ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it ** is defined, it will be consulted only when the macro "winIoerrCanRetry1" ** returns zero. The "winIoerrCanRetry2" macro is completely optional and ** may be used to include additional error codes in the set that should ** result in the failing I/O operation being retried by the caller. If ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics ** identical to those of the "winIoerrCanRetry1" macro. */ #if !defined(winIoerrCanRetry1) #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \ ((a)==ERROR_SHARING_VIOLATION) || \ ((a)==ERROR_LOCK_VIOLATION) || \ ((a)==ERROR_DEV_NOT_EXIST) || \ ((a)==ERROR_NETNAME_DELETED) || \ ((a)==ERROR_SEM_TIMEOUT) || \ ((a)==ERROR_NETWORK_UNREACHABLE)) #endif /* ** If a ReadFile() or WriteFile() error occurs, invoke this routine ** to see if it should be retried. Return TRUE to retry. Return FALSE ** to give up with an error. */ static int winRetryIoerr(int *pnRetry, DWORD *pError){ DWORD e = osGetLastError(); if( *pnRetry>=winIoerrRetry ){ if( pError ){ *pError = e; } return 0; } if( winIoerrCanRetry1(e) ){ sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); ++*pnRetry; return 1; } #if defined(winIoerrCanRetry2) else if( winIoerrCanRetry2(e) ){ sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); ++*pnRetry; return 1; } #endif if( pError ){ *pError = e; } return 0; } /* ** Log a I/O error retry episode. */ static void winLogIoerr(int nRetry, int lineno){ if( nRetry ){ sqlite3_log(SQLITE_NOTICE, "delayed %dms for lock/sharing conflict at line %d", winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno ); } } /* ** This #if does not rely on the SQLITE_OS_WINCE define because the ** corresponding section in "date.c" cannot use it. */ #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \ (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API) /* ** The MSVC CRT on Windows CE may not have a localtime() function. ** So define a substitute. */ /* # include <time.h> */ struct tm *__cdecl localtime(const time_t *t) { static struct tm y; FILETIME uTm, lTm; SYSTEMTIME pTm; sqlite3_int64 t64; t64 = *t; t64 = (t64 + 11644473600)*10000000; uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF); uTm.dwHighDateTime= (DWORD)(t64 >> 32); osFileTimeToLocalFileTime(&uTm,&lTm); osFileTimeToSystemTime(&lTm,&pTm); y.tm_year = pTm.wYear - 1900; y.tm_mon = pTm.wMonth - 1; y.tm_wday = pTm.wDayOfWeek; y.tm_mday = pTm.wDay; y.tm_hour = pTm.wHour; y.tm_min = pTm.wMinute; y.tm_sec = pTm.wSecond; return &y; } #endif #if SQLITE_OS_WINCE /************************************************************************* ** This section contains code for WinCE only. */ #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)] /* ** Acquire a lock on the handle h */ static void winceMutexAcquire(HANDLE h){ DWORD dwErr; do { dwErr = osWaitForSingleObject(h, INFINITE); } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED); } /* ** Release a lock acquired by winceMutexAcquire() */ #define winceMutexRelease(h) ReleaseMutex(h) /* ** Create the mutex and shared memory used for locking in the file ** descriptor pFile */ static int winceCreateLock(const char *zFilename, winFile *pFile){ LPWSTR zTok; LPWSTR zName; DWORD lastErrno; BOOL bLogged = FALSE; BOOL bInit = TRUE; zName = winUtf8ToUnicode(zFilename); if( zName==0 ){ /* out of memory */ return SQLITE_IOERR_NOMEM_BKPT; } /* Initialize the local lockdata */ memset(&pFile->local, 0, sizeof(pFile->local)); /* Replace the backslashes from the filename and lowercase it ** to derive a mutex name. */ zTok = osCharLowerW(zName); for (;*zTok;zTok++){ if (*zTok == '\\') *zTok = '_'; } /* Create/open the named mutex */ pFile->hMutex = osCreateMutexW(NULL, FALSE, zName); if (!pFile->hMutex){ pFile->lastErrno = osGetLastError(); sqlite3_free(zName); return winLogError(SQLITE_IOERR, pFile->lastErrno, "winceCreateLock1", zFilename); } /* Acquire the mutex before continuing */ winceMutexAcquire(pFile->hMutex); /* Since the names of named mutexes, semaphores, file mappings etc are ** case-sensitive, take advantage of that by uppercasing the mutex name ** and using that as the shared filemapping name. */ osCharUpperW(zName); pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(winceLock), zName); /* Set a flag that indicates we're the first to create the memory so it ** must be zero-initialized */ lastErrno = osGetLastError(); if (lastErrno == ERROR_ALREADY_EXISTS){ bInit = FALSE; } sqlite3_free(zName); /* If we succeeded in making the shared memory handle, map it. */ if( pFile->hShared ){ pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock)); /* If mapping failed, close the shared memory handle and erase it */ if( !pFile->shared ){ pFile->lastErrno = osGetLastError(); winLogError(SQLITE_IOERR, pFile->lastErrno, "winceCreateLock2", zFilename); bLogged = TRUE; osCloseHandle(pFile->hShared); pFile->hShared = NULL; } } /* If shared memory could not be created, then close the mutex and fail */ if( pFile->hShared==NULL ){ if( !bLogged ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_IOERR, pFile->lastErrno, "winceCreateLock3", zFilename); bLogged = TRUE; } winceMutexRelease(pFile->hMutex); osCloseHandle(pFile->hMutex); pFile->hMutex = NULL; return SQLITE_IOERR; } /* Initialize the shared memory if we're supposed to */ if( bInit ){ memset(pFile->shared, 0, sizeof(winceLock)); } winceMutexRelease(pFile->hMutex); return SQLITE_OK; } /* ** Destroy the part of winFile that deals with wince locks */ static void winceDestroyLock(winFile *pFile){ if (pFile->hMutex){ /* Acquire the mutex */ winceMutexAcquire(pFile->hMutex); /* The following blocks should probably assert in debug mode, but they are to cleanup in case any locks remained open */ if (pFile->local.nReaders){ pFile->shared->nReaders --; } if (pFile->local.bReserved){ pFile->shared->bReserved = FALSE; } if (pFile->local.bPending){ pFile->shared->bPending = FALSE; } if (pFile->local.bExclusive){ pFile->shared->bExclusive = FALSE; } /* De-reference and close our copy of the shared memory handle */ osUnmapViewOfFile(pFile->shared); osCloseHandle(pFile->hShared); /* Done with the mutex */ winceMutexRelease(pFile->hMutex); osCloseHandle(pFile->hMutex); pFile->hMutex = NULL; } } /* ** An implementation of the LockFile() API of Windows for CE */ static BOOL winceLockFile( LPHANDLE phFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh ){ winFile *pFile = HANDLE_TO_WINFILE(phFile); BOOL bReturn = FALSE; UNUSED_PARAMETER(dwFileOffsetHigh); UNUSED_PARAMETER(nNumberOfBytesToLockHigh); if (!pFile->hMutex) return TRUE; winceMutexAcquire(pFile->hMutex); /* Wanting an exclusive lock? */ if (dwFileOffsetLow == (DWORD)SHARED_FIRST && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){ if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){ pFile->shared->bExclusive = TRUE; pFile->local.bExclusive = TRUE; bReturn = TRUE; } } /* Want a read-only lock? */ else if (dwFileOffsetLow == (DWORD)SHARED_FIRST && nNumberOfBytesToLockLow == 1){ if (pFile->shared->bExclusive == 0){ pFile->local.nReaders ++; if (pFile->local.nReaders == 1){ pFile->shared->nReaders ++; } bReturn = TRUE; } } /* Want a pending lock? */ else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){ /* If no pending lock has been acquired, then acquire it */ if (pFile->shared->bPending == 0) { pFile->shared->bPending = TRUE; pFile->local.bPending = TRUE; bReturn = TRUE; } } /* Want a reserved lock? */ else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){ if (pFile->shared->bReserved == 0) { pFile->shared->bReserved = TRUE; pFile->local.bReserved = TRUE; bReturn = TRUE; } } winceMutexRelease(pFile->hMutex); return bReturn; } /* ** An implementation of the UnlockFile API of Windows for CE */ static BOOL winceUnlockFile( LPHANDLE phFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh ){ winFile *pFile = HANDLE_TO_WINFILE(phFile); BOOL bReturn = FALSE; UNUSED_PARAMETER(dwFileOffsetHigh); UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh); if (!pFile->hMutex) return TRUE; winceMutexAcquire(pFile->hMutex); /* Releasing a reader lock or an exclusive lock */ if (dwFileOffsetLow == (DWORD)SHARED_FIRST){ /* Did we have an exclusive lock? */ if (pFile->local.bExclusive){ assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE); pFile->local.bExclusive = FALSE; pFile->shared->bExclusive = FALSE; bReturn = TRUE; } /* Did we just have a reader lock? */ else if (pFile->local.nReaders){ assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1); pFile->local.nReaders --; if (pFile->local.nReaders == 0) { pFile->shared->nReaders --; } bReturn = TRUE; } } /* Releasing a pending lock */ else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){ if (pFile->local.bPending){ pFile->local.bPending = FALSE; pFile->shared->bPending = FALSE; bReturn = TRUE; } } /* Releasing a reserved lock */ else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){ if (pFile->local.bReserved) { pFile->local.bReserved = FALSE; pFile->shared->bReserved = FALSE; bReturn = TRUE; } } winceMutexRelease(pFile->hMutex); return bReturn; } /* ** End of the special code for wince *****************************************************************************/ #endif /* SQLITE_OS_WINCE */ /* ** Lock a file region. */ static BOOL winLockFile( LPHANDLE phFile, DWORD flags, DWORD offsetLow, DWORD offsetHigh, DWORD numBytesLow, DWORD numBytesHigh ){ #if SQLITE_OS_WINCE /* ** NOTE: Windows CE is handled differently here due its lack of the Win32 ** API LockFile. */ return winceLockFile(phFile, offsetLow, offsetHigh, numBytesLow, numBytesHigh); #else if( osIsNT() ){ OVERLAPPED ovlp; memset(&ovlp, 0, sizeof(OVERLAPPED)); ovlp.Offset = offsetLow; ovlp.OffsetHigh = offsetHigh; return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp); }else{ return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow, numBytesHigh); } #endif } /* ** Unlock a file region. */ static BOOL winUnlockFile( LPHANDLE phFile, DWORD offsetLow, DWORD offsetHigh, DWORD numBytesLow, DWORD numBytesHigh ){ #if SQLITE_OS_WINCE /* ** NOTE: Windows CE is handled differently here due its lack of the Win32 ** API UnlockFile. */ return winceUnlockFile(phFile, offsetLow, offsetHigh, numBytesLow, numBytesHigh); #else if( osIsNT() ){ OVERLAPPED ovlp; memset(&ovlp, 0, sizeof(OVERLAPPED)); ovlp.Offset = offsetLow; ovlp.OffsetHigh = offsetHigh; return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp); }else{ return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow, numBytesHigh); } #endif } /***************************************************************************** ** The next group of routines implement the I/O methods specified ** by the sqlite3_io_methods object. ******************************************************************************/ /* ** Some Microsoft compilers lack this definition. */ #ifndef INVALID_SET_FILE_POINTER # define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif /* ** Move the current position of the file handle passed as the first ** argument to offset iOffset within the file. If successful, return 0. ** Otherwise, set pFile->lastErrno and return non-zero. */ static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){ #if !SQLITE_OS_WINRT LONG upperBits; /* Most sig. 32 bits of new offset */ LONG lowerBits; /* Least sig. 32 bits of new offset */ DWORD dwRet; /* Value returned by SetFilePointer() */ DWORD lastErrno; /* Value returned by GetLastError() */ OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset)); upperBits = (LONG)((iOffset>>32) & 0x7fffffff); lowerBits = (LONG)(iOffset & 0xffffffff); /* API oddity: If successful, SetFilePointer() returns a dword ** containing the lower 32-bits of the new file-offset. Or, if it fails, ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine ** whether an error has actually occurred, it is also necessary to call ** GetLastError(). */ dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN); if( (dwRet==INVALID_SET_FILE_POINTER && ((lastErrno = osGetLastError())!=NO_ERROR)) ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno, "winSeekFile", pFile->zPath); OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h)); return 1; } OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h)); return 0; #else /* ** Same as above, except that this implementation works for WinRT. */ LARGE_INTEGER x; /* The new offset */ BOOL bRet; /* Value returned by SetFilePointerEx() */ x.QuadPart = iOffset; bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN); if(!bRet){ pFile->lastErrno = osGetLastError(); winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno, "winSeekFile", pFile->zPath); OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h)); return 1; } OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h)); return 0; #endif } #if SQLITE_MAX_MMAP_SIZE>0 /* Forward references to VFS helper methods used for memory mapped files */ static int winMapfile(winFile*, sqlite3_int64); static int winUnmapfile(winFile*); #endif /* ** Close a file. ** ** It is reported that an attempt to close a handle might sometimes ** fail. This is a very unreasonable result, but Windows is notorious ** for being unreasonable so I do not doubt that it might happen. If ** the close fails, we pause for 100 milliseconds and try again. As ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before ** giving up and returning an error. */ #define MX_CLOSE_ATTEMPT 3 static int winClose(sqlite3_file *id){ int rc, cnt = 0; winFile *pFile = (winFile*)id; assert( id!=0 ); #ifndef SQLITE_OMIT_WAL assert( pFile->pShm==0 ); #endif assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE ); OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n", osGetCurrentProcessId(), pFile, pFile->h)); #if SQLITE_MAX_MMAP_SIZE>0 winUnmapfile(pFile); #endif do{ rc = osCloseHandle(pFile->h); /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */ }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) ); #if SQLITE_OS_WINCE #define WINCE_DELETION_ATTEMPTS 3 { winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData; if( pAppData==NULL || !pAppData->bNoLock ){ winceDestroyLock(pFile); } } if( pFile->zDeleteOnClose ){ int cnt = 0; while( osDeleteFileW(pFile->zDeleteOnClose)==0 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff && cnt++ < WINCE_DELETION_ATTEMPTS ){ sqlite3_win32_sleep(100); /* Wait a little before trying again */ } sqlite3_free(pFile->zDeleteOnClose); } #endif if( rc ){ pFile->h = NULL; } OpenCounter(-1); OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n", osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed")); return rc ? SQLITE_OK : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(), "winClose", pFile->zPath); } /* ** Read data from a file into a buffer. Return SQLITE_OK if all ** bytes were read successfully and SQLITE_IOERR if anything goes ** wrong. */ static int winRead( sqlite3_file *id, /* File to read from */ void *pBuf, /* Write content into this buffer */ int amt, /* Number of bytes to read */ sqlite3_int64 offset /* Begin reading at this offset */ ){ #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) OVERLAPPED overlapped; /* The offset for ReadFile. */ #endif winFile *pFile = (winFile*)id; /* file handle */ DWORD nRead; /* Number of bytes actually read from file */ int nRetry = 0; /* Number of retrys */ assert( id!=0 ); assert( amt>0 ); assert( offset>=0 ); SimulateIOError(return SQLITE_IOERR_READ); OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, " "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, pFile->h, pBuf, amt, offset, pFile->locktype)); #if SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this read request as possible by transfering ** data from the memory mapping using memcpy(). */ if( offset<pFile->mmapSize ){ if( offset+amt <= pFile->mmapSize ){ memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; }else{ int nCopy = (int)(pFile->mmapSize - offset); memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; } } #endif #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) if( winSeekFile(pFile, offset) ){ OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_FULL; } while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){ #else memset(&overlapped, 0, sizeof(OVERLAPPED)); overlapped.Offset = (LONG)(offset & 0xffffffff); overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) && osGetLastError()!=ERROR_HANDLE_EOF ){ #endif DWORD lastErrno; if( winRetryIoerr(&nRetry, &lastErrno) ) continue; pFile->lastErrno = lastErrno; OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n", osGetCurrentProcessId(), pFile, pFile->h)); return winLogError(SQLITE_IOERR_READ, pFile->lastErrno, "winRead", pFile->zPath); } winLogIoerr(nRetry, __LINE__); if( nRead<(DWORD)amt ){ /* Unread parts of the buffer must be zero-filled */ memset(&((char*)pBuf)[nRead], 0, amt-nRead); OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_IOERR_SHORT_READ; } OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; } /* ** Write data from a buffer into a file. Return SQLITE_OK on success ** or some other error code on failure. */ static int winWrite( sqlite3_file *id, /* File to write into */ const void *pBuf, /* The bytes to be written */ int amt, /* Number of bytes to write */ sqlite3_int64 offset /* Offset into the file to begin writing at */ ){ int rc = 0; /* True if error has occurred, else false */ winFile *pFile = (winFile*)id; /* File handle */ int nRetry = 0; /* Number of retries */ assert( amt>0 ); assert( pFile ); SimulateIOError(return SQLITE_IOERR_WRITE); SimulateDiskfullError(return SQLITE_FULL); OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, " "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, pFile->h, pBuf, amt, offset, pFile->locktype)); #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 /* Deal with as much of this write request as possible by transfering ** data from the memory mapping using memcpy(). */ if( offset<pFile->mmapSize ){ if( offset+amt <= pFile->mmapSize ){ memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; }else{ int nCopy = (int)(pFile->mmapSize - offset); memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); pBuf = &((u8 *)pBuf)[nCopy]; amt -= nCopy; offset += nCopy; } } #endif #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) rc = winSeekFile(pFile, offset); if( rc==0 ){ #else { #endif #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) OVERLAPPED overlapped; /* The offset for WriteFile. */ #endif u8 *aRem = (u8 *)pBuf; /* Data yet to be written */ int nRem = amt; /* Number of bytes yet to be written */ DWORD nWrite; /* Bytes written by each WriteFile() call */ DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */ #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) memset(&overlapped, 0, sizeof(OVERLAPPED)); overlapped.Offset = (LONG)(offset & 0xffffffff); overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); #endif while( nRem>0 ){ #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){ #else if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){ #endif if( winRetryIoerr(&nRetry, &lastErrno) ) continue; break; } assert( nWrite==0 || nWrite<=(DWORD)nRem ); if( nWrite==0 || nWrite>(DWORD)nRem ){ lastErrno = osGetLastError(); break; } #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) offset += nWrite; overlapped.Offset = (LONG)(offset & 0xffffffff); overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); #endif aRem += nWrite; nRem -= nWrite; } if( nRem>0 ){ pFile->lastErrno = lastErrno; rc = 1; } } if( rc ){ if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ) || ( pFile->lastErrno==ERROR_DISK_FULL )){ OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", osGetCurrentProcessId(), pFile, pFile->h)); return winLogError(SQLITE_FULL, pFile->lastErrno, "winWrite1", pFile->zPath); } OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n", osGetCurrentProcessId(), pFile, pFile->h)); return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno, "winWrite2", pFile->zPath); }else{ winLogIoerr(nRetry, __LINE__); } OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; } /* ** Truncate an open file to a specified size */ static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ winFile *pFile = (winFile*)id; /* File handle object */ int rc = SQLITE_OK; /* Return code for this function */ DWORD lastErrno; assert( pFile ); SimulateIOError(return SQLITE_IOERR_TRUNCATE); OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype)); /* If the user has configured a chunk-size for this file, truncate the ** file so that it consists of an integer number of chunks (i.e. the ** actual file size after the operation may be larger than the requested ** size). */ if( pFile->szChunk>0 ){ nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; } /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */ if( winSeekFile(pFile, nByte) ){ rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, "winTruncate1", pFile->zPath); }else if( 0==osSetEndOfFile(pFile->h) && ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){ pFile->lastErrno = lastErrno; rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, "winTruncate2", pFile->zPath); } #if SQLITE_MAX_MMAP_SIZE>0 /* If the file was truncated to a size smaller than the currently ** mapped region, reduce the effective mapping size as well. SQLite will ** use read() and write() to access data beyond this point from now on. */ if( pFile->pMapRegion && nByte<pFile->mmapSize ){ pFile->mmapSize = nByte; } #endif OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n", osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc))); return rc; } #ifdef SQLITE_TEST /* ** Count the number of fullsyncs and normal syncs. This is used to test ** that syncs and fullsyncs are occuring at the right times. */ SQLITE_API int sqlite3_sync_count = 0; SQLITE_API int sqlite3_fullsync_count = 0; #endif /* ** Make sure all writes to a particular file are committed to disk. */ static int winSync(sqlite3_file *id, int flags){ #ifndef SQLITE_NO_SYNC /* ** Used only when SQLITE_NO_SYNC is not defined. */ BOOL rc; #endif #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \ defined(SQLITE_HAVE_OS_TRACE) /* ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or ** OSTRACE() macros. */ winFile *pFile = (winFile*)id; #else UNUSED_PARAMETER(id); #endif assert( pFile ); /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ assert((flags&0x0F)==SQLITE_SYNC_NORMAL || (flags&0x0F)==SQLITE_SYNC_FULL ); /* Unix cannot, but some systems may return SQLITE_FULL from here. This ** line is to test that doing so does not cause any problems. */ SimulateDiskfullError( return SQLITE_FULL ); OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n", osGetCurrentProcessId(), pFile, pFile->h, flags, pFile->locktype)); #ifndef SQLITE_TEST UNUSED_PARAMETER(flags); #else if( (flags&0x0F)==SQLITE_SYNC_FULL ){ sqlite3_fullsync_count++; } sqlite3_sync_count++; #endif /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a ** no-op */ #ifdef SQLITE_NO_SYNC OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; #else #if SQLITE_MAX_MMAP_SIZE>0 if( pFile->pMapRegion ){ if( osFlushViewOfFile(pFile->pMapRegion, 0) ){ OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " "rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->pMapRegion)); }else{ pFile->lastErrno = osGetLastError(); OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, pFile->pMapRegion)); return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, "winSync1", pFile->zPath); } } #endif rc = osFlushFileBuffers(pFile->h); SimulateIOError( rc=FALSE ); if( rc ){ OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile, pFile->h)); return SQLITE_OK; }else{ pFile->lastErrno = osGetLastError(); OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n", osGetCurrentProcessId(), pFile, pFile->h)); return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno, "winSync2", pFile->zPath); } #endif } /* ** Determine the current size of a file in bytes */ static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ winFile *pFile = (winFile*)id; int rc = SQLITE_OK; assert( id!=0 ); assert( pSize!=0 ); SimulateIOError(return SQLITE_IOERR_FSTAT); OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize)); #if SQLITE_OS_WINRT { FILE_STANDARD_INFO info; if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo, &info, sizeof(info)) ){ *pSize = info.EndOfFile.QuadPart; }else{ pFile->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, "winFileSize", pFile->zPath); } } #else { DWORD upperBits; DWORD lowerBits; DWORD lastErrno; lowerBits = osGetFileSize(pFile->h, &upperBits); *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; if( (lowerBits == INVALID_FILE_SIZE) && ((lastErrno = osGetLastError())!=NO_ERROR) ){ pFile->lastErrno = lastErrno; rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, "winFileSize", pFile->zPath); } } #endif OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n", pFile->h, pSize, *pSize, sqlite3ErrName(rc))); return rc; } /* ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems. */ #ifndef LOCKFILE_FAIL_IMMEDIATELY # define LOCKFILE_FAIL_IMMEDIATELY 1 #endif #ifndef LOCKFILE_EXCLUSIVE_LOCK # define LOCKFILE_EXCLUSIVE_LOCK 2 #endif /* ** Historically, SQLite has used both the LockFile and LockFileEx functions. ** When the LockFile function was used, it was always expected to fail ** immediately if the lock could not be obtained. Also, it always expected to ** obtain an exclusive lock. These flags are used with the LockFileEx function ** and reflect those expectations; therefore, they should not be changed. */ #ifndef SQLITE_LOCKFILE_FLAGS # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \ LOCKFILE_EXCLUSIVE_LOCK) #endif /* ** Currently, SQLite never calls the LockFileEx function without wanting the ** call to fail immediately if the lock cannot be obtained. */ #ifndef SQLITE_LOCKFILEEX_FLAGS # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY) #endif /* ** Acquire a reader lock. ** Different API routines are called depending on whether or not this ** is Win9x or WinNT. */ static int winGetReadLock(winFile *pFile){ int res; OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); if( osIsNT() ){ #if SQLITE_OS_WINCE /* ** NOTE: Windows CE is handled differently here due its lack of the Win32 ** API LockFileEx. */ res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0); #else res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0, SHARED_SIZE, 0); #endif } #ifdef SQLITE_WIN32_HAS_ANSI else{ int lk; sqlite3_randomness(sizeof(lk), &lk); pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); } #endif if( res == 0 ){ pFile->lastErrno = osGetLastError(); /* No need to log a failure to lock */ } OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res)); return res; } /* ** Undo a readlock */ static int winUnlockReadLock(winFile *pFile){ int res; DWORD lastErrno; OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); if( osIsNT() ){ res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); } #ifdef SQLITE_WIN32_HAS_ANSI else{ res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); } #endif if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno, "winUnlockReadLock", pFile->zPath); } OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res)); return res; } /* ** Lock the file with the lock specified by parameter locktype - one ** of the following: ** ** (1) SHARED_LOCK ** (2) RESERVED_LOCK ** (3) PENDING_LOCK ** (4) EXCLUSIVE_LOCK ** ** Sometimes when requesting one lock state, additional lock states ** are inserted in between. The locking might fail on one of the later ** transitions leaving the lock state different from what it started but ** still short of its goal. The following chart shows the allowed ** transitions and the inserted intermediate states: ** ** UNLOCKED -> SHARED ** SHARED -> RESERVED ** SHARED -> (PENDING) -> EXCLUSIVE ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** ** This routine will only increase a lock. The winUnlock() routine ** erases all locks at once and returns us immediately to locking level 0. ** It is not possible to lower the locking level one step at a time. You ** must go straight to locking level 0. */ static int winLock(sqlite3_file *id, int locktype){ int rc = SQLITE_OK; /* Return code from subroutines */ int res = 1; /* Result of a Windows lock call */ int newLocktype; /* Set pFile->locktype to this value before exiting */ int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */ winFile *pFile = (winFile*)id; DWORD lastErrno = NO_ERROR; assert( id!=0 ); OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n", pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); /* If there is already a lock of this type or more restrictive on the ** OsFile, do nothing. Don't use the end_lock: exit path, as ** sqlite3OsEnterMutex() hasn't been called yet. */ if( pFile->locktype>=locktype ){ OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } /* Do not allow any kind of write-lock on a read-only database */ if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){ return SQLITE_IOERR_LOCK; } /* Make sure the locking sequence is correct */ assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); assert( locktype!=PENDING_LOCK ); assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of ** the PENDING_LOCK byte is temporary. */ newLocktype = pFile->locktype; if( pFile->locktype==NO_LOCK || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK) ){ int cnt = 3; while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, PENDING_BYTE, 0, 1, 0))==0 ){ /* Try 3 times to get the pending lock. This is needed to work ** around problems caused by indexing and/or anti-virus software on ** Windows systems. ** If you are using this code as a model for alternative VFSes, do not ** copy this retry logic. It is a hack intended for Windows only. */ lastErrno = osGetLastError(); OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n", pFile->h, cnt, res)); if( lastErrno==ERROR_INVALID_HANDLE ){ pFile->lastErrno = lastErrno; rc = SQLITE_IOERR_LOCK; OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n", pFile->h, cnt, sqlite3ErrName(rc))); return rc; } if( cnt ) sqlite3_win32_sleep(1); } gotPendingLock = res; if( !res ){ lastErrno = osGetLastError(); } } /* Acquire a shared lock */ if( locktype==SHARED_LOCK && res ){ assert( pFile->locktype==NO_LOCK ); res = winGetReadLock(pFile); if( res ){ newLocktype = SHARED_LOCK; }else{ lastErrno = osGetLastError(); } } /* Acquire a RESERVED lock */ if( locktype==RESERVED_LOCK && res ){ assert( pFile->locktype==SHARED_LOCK ); res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0); if( res ){ newLocktype = RESERVED_LOCK; }else{ lastErrno = osGetLastError(); } } /* Acquire a PENDING lock */ if( locktype==EXCLUSIVE_LOCK && res ){ newLocktype = PENDING_LOCK; gotPendingLock = 0; } /* Acquire an EXCLUSIVE lock */ if( locktype==EXCLUSIVE_LOCK && res ){ assert( pFile->locktype>=SHARED_LOCK ); res = winUnlockReadLock(pFile); res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0, SHARED_SIZE, 0); if( res ){ newLocktype = EXCLUSIVE_LOCK; }else{ lastErrno = osGetLastError(); winGetReadLock(pFile); } } /* If we are holding a PENDING lock that ought to be released, then ** release it now. */ if( gotPendingLock && locktype==SHARED_LOCK ){ winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); } /* Update the state of the lock has held in the file descriptor then ** return the appropriate result code. */ if( res ){ rc = SQLITE_OK; }else{ pFile->lastErrno = lastErrno; rc = SQLITE_BUSY; OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n", pFile->h, locktype, newLocktype)); } pFile->locktype = (u8)newLocktype; OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n", pFile->h, pFile->locktype, sqlite3ErrName(rc))); return rc; } /* ** This routine checks if there is a RESERVED lock held on the specified ** file by this or any other process. If such a lock is held, return ** non-zero, otherwise zero. */ static int winCheckReservedLock(sqlite3_file *id, int *pResOut){ int res; winFile *pFile = (winFile*)id; SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut)); assert( id!=0 ); if( pFile->locktype>=RESERVED_LOCK ){ res = 1; OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res)); }else{ res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0); if( res ){ winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); } res = !res; OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res)); } *pResOut = res; OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", pFile->h, pResOut, *pResOut)); return SQLITE_OK; } /* ** Lower the locking level on file descriptor id to locktype. locktype ** must be either NO_LOCK or SHARED_LOCK. ** ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. ** ** It is not possible for this routine to fail if the second argument ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine ** might return SQLITE_IOERR; */ static int winUnlock(sqlite3_file *id, int locktype){ int type; winFile *pFile = (winFile*)id; int rc = SQLITE_OK; assert( pFile!=0 ); assert( locktype<=SHARED_LOCK ); OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n", pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); type = pFile->locktype; if( type>=EXCLUSIVE_LOCK ){ winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){ /* This should never happen. We should always be able to ** reacquire the read lock */ rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(), "winUnlock", pFile->zPath); } } if( type>=RESERVED_LOCK ){ winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); } if( locktype==NO_LOCK && type>=SHARED_LOCK ){ winUnlockReadLock(pFile); } if( type>=PENDING_LOCK ){ winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); } pFile->locktype = (u8)locktype; OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n", pFile->h, pFile->locktype, sqlite3ErrName(rc))); return rc; } /****************************************************************************** ****************************** No-op Locking ********************************** ** ** Of the various locking implementations available, this is by far the ** simplest: locking is ignored. No attempt is made to lock the database ** file for reading or writing. ** ** This locking mode is appropriate for use on read-only databases ** (ex: databases that are burned into CD-ROM, for example.) It can ** also be used if the application employs some external mechanism to ** prevent simultaneous access of the same database by two or more ** database connections. But there is a serious risk of database ** corruption if this locking mode is used in situations where multiple ** database connections are accessing the same database file at the same ** time and one or more of those connections are writing. */ static int winNolockLock(sqlite3_file *id, int locktype){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(locktype); return SQLITE_OK; } static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(pResOut); return SQLITE_OK; } static int winNolockUnlock(sqlite3_file *id, int locktype){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(locktype); return SQLITE_OK; } /******************* End of the no-op lock implementation ********************* ******************************************************************************/ /* ** If *pArg is initially negative then this is a query. Set *pArg to ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. ** ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. */ static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){ if( *pArg<0 ){ *pArg = (pFile->ctrlFlags & mask)!=0; }else if( (*pArg)==0 ){ pFile->ctrlFlags &= ~mask; }else{ pFile->ctrlFlags |= mask; } } /* Forward references to VFS helper methods used for temporary files */ static int winGetTempname(sqlite3_vfs *, char **); static int winIsDir(const void *); static BOOL winIsDriveLetterAndColon(const char *); /* ** Control and query of the open file handle. */ static int winFileControl(sqlite3_file *id, int op, void *pArg){ winFile *pFile = (winFile*)id; OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg)); switch( op ){ case SQLITE_FCNTL_LOCKSTATE: { *(int*)pArg = pFile->locktype; OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_LAST_ERRNO: { *(int*)pArg = (int)pFile->lastErrno; OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_CHUNK_SIZE: { pFile->szChunk = *(int *)pArg; OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_SIZE_HINT: { if( pFile->szChunk>0 ){ sqlite3_int64 oldSz; int rc = winFileSize(id, &oldSz); if( rc==SQLITE_OK ){ sqlite3_int64 newSz = *(sqlite3_int64*)pArg; if( newSz>oldSz ){ SimulateIOErrorBenign(1); rc = winTruncate(id, newSz); SimulateIOErrorBenign(0); } } OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); return rc; } OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_PERSIST_WAL: { winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg); OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { winModeBit(pFile, WINFILE_PSOW, (int*)pArg); OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_VFSNAME: { *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_WIN32_AV_RETRY: { int *a = (int*)pArg; if( a[0]>0 ){ winIoerrRetry = a[0]; }else{ a[0] = winIoerrRetry; } if( a[1]>0 ){ winIoerrRetryDelay = a[1]; }else{ a[1] = winIoerrRetryDelay; } OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } case SQLITE_FCNTL_WIN32_GET_HANDLE: { LPHANDLE phFile = (LPHANDLE)pArg; *phFile = pFile->h; OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } #ifdef SQLITE_TEST case SQLITE_FCNTL_WIN32_SET_HANDLE: { LPHANDLE phFile = (LPHANDLE)pArg; HANDLE hOldFile = pFile->h; pFile->h = *phFile; *phFile = hOldFile; OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n", hOldFile, pFile->h)); return SQLITE_OK; } #endif case SQLITE_FCNTL_TEMPFILENAME: { char *zTFile = 0; int rc = winGetTempname(pFile->pVfs, &zTFile); if( rc==SQLITE_OK ){ *(char**)pArg = zTFile; } OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); return rc; } #if SQLITE_MAX_MMAP_SIZE>0 case SQLITE_FCNTL_MMAP_SIZE: { i64 newLimit = *(i64*)pArg; int rc = SQLITE_OK; if( newLimit>sqlite3GlobalConfig.mxMmap ){ newLimit = sqlite3GlobalConfig.mxMmap; } *(i64*)pArg = pFile->mmapSizeMax; if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ pFile->mmapSizeMax = newLimit; if( pFile->mmapSize>0 ){ winUnmapfile(pFile); rc = winMapfile(pFile, -1); } } OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); return rc; } #endif } OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h)); return SQLITE_NOTFOUND; } /* ** Return the sector size in bytes of the underlying block device for ** the specified file. This is almost always 512 bytes, but may be ** larger for some devices. ** ** SQLite code assumes this function cannot fail. It also assumes that ** if two files are created in the same file-system directory (i.e. ** a database and its journal file) that the sector size will be the ** same for both. */ static int winSectorSize(sqlite3_file *id){ (void)id; return SQLITE_DEFAULT_SECTOR_SIZE; } /* ** Return a vector of device characteristics. */ static int winDeviceCharacteristics(sqlite3_file *id){ winFile *p = (winFile*)id; return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0); } /* ** Windows will only let you create file view mappings ** on allocation size granularity boundaries. ** During sqlite3_os_init() we do a GetSystemInfo() ** to get the granularity size. */ static SYSTEM_INFO winSysInfo; #ifndef SQLITE_OMIT_WAL /* ** Helper functions to obtain and relinquish the global mutex. The ** global mutex is used to protect the winLockInfo objects used by ** this file, all of which may be shared by multiple threads. ** ** Function winShmMutexHeld() is used to assert() that the global mutex ** is held when required. This function is only used as part of assert() ** statements. e.g. ** ** winShmEnterMutex() ** assert( winShmMutexHeld() ); ** winShmLeaveMutex() */ static void winShmEnterMutex(void){ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } static void winShmLeaveMutex(void){ sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } #ifndef NDEBUG static int winShmMutexHeld(void) { return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); } #endif /* ** Object used to represent a single file opened and mmapped to provide ** shared memory. When multiple threads all reference the same ** log-summary, each thread has its own winFile object, but they all ** point to a single instance of this object. In other words, each ** log-summary is opened only once per process. ** ** winShmMutexHeld() must be true when creating or destroying ** this object or while reading or writing the following fields: ** ** nRef ** pNext ** ** The following fields are read-only after the object is created: ** ** fid ** zFilename ** ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and ** winShmMutexHeld() is true when reading or writing any other field ** in this structure. ** */ struct winShmNode { sqlite3_mutex *mutex; /* Mutex to access this object */ char *zFilename; /* Name of the file */ winFile hFile; /* File handle from winOpen */ int szRegion; /* Size of shared-memory regions */ int nRegion; /* Size of array apRegion */ struct ShmRegion { HANDLE hMap; /* File handle from CreateFileMapping */ void *pMap; } *aRegion; DWORD lastErrno; /* The Windows errno from the last I/O error */ int nRef; /* Number of winShm objects pointing to this */ winShm *pFirst; /* All winShm objects pointing to this */ winShmNode *pNext; /* Next in list of all winShmNode objects */ #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) u8 nextShmId; /* Next available winShm.id value */ #endif }; /* ** A global array of all winShmNode objects. ** ** The winShmMutexHeld() must be true while reading or writing this list. */ static winShmNode *winShmNodeList = 0; /* ** Structure used internally by this VFS to record the state of an ** open shared memory connection. ** ** The following fields are initialized when this object is created and ** are read-only thereafter: ** ** winShm.pShmNode ** winShm.id ** ** All other fields are read/write. The winShm.pShmNode->mutex must be held ** while accessing any read/write fields. */ struct winShm { winShmNode *pShmNode; /* The underlying winShmNode object */ winShm *pNext; /* Next winShm with the same winShmNode */ u8 hasMutex; /* True if holding the winShmNode mutex */ u16 sharedMask; /* Mask of shared locks held */ u16 exclMask; /* Mask of exclusive locks held */ #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) u8 id; /* Id of this connection with its winShmNode */ #endif }; /* ** Constants used for locking */ #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ /* ** Apply advisory locks for all n bytes beginning at ofst. */ #define WINSHM_UNLCK 1 #define WINSHM_RDLCK 2 #define WINSHM_WRLCK 3 static int winShmSystemLock( winShmNode *pFile, /* Apply locks to this open shared-memory segment */ int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */ int ofst, /* Offset to first byte to be locked/unlocked */ int nByte /* Number of bytes to lock or unlock */ ){ int rc = 0; /* Result code form Lock/UnlockFileEx() */ /* Access to the winShmNode object is serialized by the caller */ assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 ); OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n", pFile->hFile.h, lockType, ofst, nByte)); /* Release/Acquire the system-level lock */ if( lockType==WINSHM_UNLCK ){ rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0); }else{ /* Initialize the locking parameters */ DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY; if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK; rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0); } if( rc!= 0 ){ rc = SQLITE_OK; }else{ pFile->lastErrno = osGetLastError(); rc = SQLITE_BUSY; } OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n", pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" : "winLockFile", pFile->lastErrno, sqlite3ErrName(rc))); return rc; } /* Forward references to VFS methods */ static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*); static int winDelete(sqlite3_vfs *,const char*,int); /* ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0. ** ** This is not a VFS shared-memory method; it is a utility function called ** by VFS shared-memory methods. */ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ winShmNode **pp; winShmNode *p; assert( winShmMutexHeld() ); OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n", osGetCurrentProcessId(), deleteFlag)); pp = &winShmNodeList; while( (p = *pp)!=0 ){ if( p->nRef==0 ){ int i; if( p->mutex ){ sqlite3_mutex_free(p->mutex); } for(i=0; i<p->nRegion; i++){ BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap); OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n", osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); UNUSED_VARIABLE_VALUE(bRc); bRc = osCloseHandle(p->aRegion[i].hMap); OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n", osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); UNUSED_VARIABLE_VALUE(bRc); } if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){ SimulateIOErrorBenign(1); winClose((sqlite3_file *)&p->hFile); SimulateIOErrorBenign(0); } if( deleteFlag ){ SimulateIOErrorBenign(1); sqlite3BeginBenignMalloc(); winDelete(pVfs, p->zFilename, 0); sqlite3EndBenignMalloc(); SimulateIOErrorBenign(0); } *pp = p->pNext; sqlite3_free(p->aRegion); sqlite3_free(p); }else{ pp = &p->pNext; } } } /* ** Open the shared-memory area associated with database file pDbFd. ** ** When opening a new shared-memory file, if no other instances of that ** file are currently open, in this process or in other processes, then ** the file must be truncated to zero length or have its header cleared. */ static int winOpenSharedMemory(winFile *pDbFd){ struct winShm *p; /* The connection to be opened */ struct winShmNode *pShmNode = 0; /* The underlying mmapped file */ int rc; /* Result code */ struct winShmNode *pNew; /* Newly allocated winShmNode */ int nName; /* Size of zName in bytes */ assert( pDbFd->pShm==0 ); /* Not previously opened */ /* Allocate space for the new sqlite3_shm object. Also speculatively ** allocate space for a new winShmNode and filename. */ p = sqlite3MallocZero( sizeof(*p) ); if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT; nName = sqlite3Strlen30(pDbFd->zPath); pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 ); if( pNew==0 ){ sqlite3_free(p); return SQLITE_IOERR_NOMEM_BKPT; } pNew->zFilename = (char*)&pNew[1]; sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); /* Look to see if there is an existing winShmNode that can be used. ** If no matching winShmNode currently exists, create a new one. */ winShmEnterMutex(); for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){ /* TBD need to come up with better match here. Perhaps ** use FILE_ID_BOTH_DIR_INFO Structure. */ if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; } if( pShmNode ){ sqlite3_free(pNew); }else{ pShmNode = pNew; pNew = 0; ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE; pShmNode->pNext = winShmNodeList; winShmNodeList = pShmNode; if( sqlite3GlobalConfig.bCoreMutex ){ pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); if( pShmNode->mutex==0 ){ rc = SQLITE_IOERR_NOMEM_BKPT; goto shm_open_err; } } rc = winOpen(pDbFd->pVfs, pShmNode->zFilename, /* Name of the file (UTF-8) */ (sqlite3_file*)&pShmNode->hFile, /* File handle here */ SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); if( SQLITE_OK!=rc ){ goto shm_open_err; } /* Check to see if another process is holding the dead-man switch. ** If not, truncate the file to zero length. */ if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){ rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0); if( rc!=SQLITE_OK ){ rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(), "winOpenShm", pDbFd->zPath); } } if( rc==SQLITE_OK ){ winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1); } if( rc ) goto shm_open_err; } /* Make the new connection a child of the winShmNode */ p->pShmNode = pShmNode; #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) p->id = pShmNode->nextShmId++; #endif pShmNode->nRef++; pDbFd->pShm = p; winShmLeaveMutex(); /* The reference count on pShmNode has already been incremented under ** the cover of the winShmEnterMutex() mutex and the pointer from the ** new (struct winShm) object to the pShmNode has been set. All that is ** left to do is to link the new object into the linked list starting ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex ** mutex. */ sqlite3_mutex_enter(pShmNode->mutex); p->pNext = pShmNode->pFirst; pShmNode->pFirst = p; sqlite3_mutex_leave(pShmNode->mutex); return SQLITE_OK; /* Jump here on any error */ shm_open_err: winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */ sqlite3_free(p); sqlite3_free(pNew); winShmLeaveMutex(); return rc; } /* ** Close a connection to shared-memory. Delete the underlying ** storage if deleteFlag is true. */ static int winShmUnmap( sqlite3_file *fd, /* Database holding shared memory */ int deleteFlag /* Delete after closing if true */ ){ winFile *pDbFd; /* Database holding shared-memory */ winShm *p; /* The connection to be closed */ winShmNode *pShmNode; /* The underlying shared-memory file */ winShm **pp; /* For looping over sibling connections */ pDbFd = (winFile*)fd; p = pDbFd->pShm; if( p==0 ) return SQLITE_OK; pShmNode = p->pShmNode; /* Remove connection p from the set of connections associated ** with pShmNode */ sqlite3_mutex_enter(pShmNode->mutex); for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} *pp = p->pNext; /* Free the connection p */ sqlite3_free(p); pDbFd->pShm = 0; sqlite3_mutex_leave(pShmNode->mutex); /* If pShmNode->nRef has reached 0, then close the underlying ** shared-memory file, too */ winShmEnterMutex(); assert( pShmNode->nRef>0 ); pShmNode->nRef--; if( pShmNode->nRef==0 ){ winShmPurge(pDbFd->pVfs, deleteFlag); } winShmLeaveMutex(); return SQLITE_OK; } /* ** Change the lock state for a shared-memory segment. */ static int winShmLock( sqlite3_file *fd, /* Database file holding the shared memory */ int ofst, /* First lock to acquire or release */ int n, /* Number of locks to acquire or release */ int flags /* What to do with the lock */ ){ winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */ winShm *p = pDbFd->pShm; /* The shared memory being locked */ winShm *pX; /* For looping over all siblings */ winShmNode *pShmNode = p->pShmNode; int rc = SQLITE_OK; /* Result code */ u16 mask; /* Mask of locks to take or release */ assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); assert( n>=1 ); assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); mask = (u16)((1U<<(ofst+n)) - (1U<<ofst)); assert( n>1 || mask==(1<<ofst) ); sqlite3_mutex_enter(pShmNode->mutex); if( flags & SQLITE_SHM_UNLOCK ){ u16 allMask = 0; /* Mask of locks held by siblings */ /* See if any siblings hold this same lock */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( pX==p ) continue; assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 ); allMask |= pX->sharedMask; } /* Unlock the system-level locks */ if( (mask & allMask)==0 ){ rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n); }else{ rc = SQLITE_OK; } /* Undo the local locks */ if( rc==SQLITE_OK ){ p->exclMask &= ~mask; p->sharedMask &= ~mask; } }else if( flags & SQLITE_SHM_SHARED ){ u16 allShared = 0; /* Union of locks held by connections other than "p" */ /* Find out which shared locks are already held by sibling connections. ** If any sibling already holds an exclusive lock, go ahead and return ** SQLITE_BUSY. */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( (pX->exclMask & mask)!=0 ){ rc = SQLITE_BUSY; break; } allShared |= pX->sharedMask; } /* Get shared locks at the system level, if necessary */ if( rc==SQLITE_OK ){ if( (allShared & mask)==0 ){ rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n); }else{ rc = SQLITE_OK; } } /* Get the local shared locks */ if( rc==SQLITE_OK ){ p->sharedMask |= mask; } }else{ /* Make sure no sibling connections hold locks that will block this ** lock. If any do, return SQLITE_BUSY right away. */ for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){ rc = SQLITE_BUSY; break; } } /* Get the exclusive locks at the system level. Then if successful ** also mark the local connection as being locked. */ if( rc==SQLITE_OK ){ rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n); if( rc==SQLITE_OK ){ assert( (p->sharedMask & mask)==0 ); p->exclMask |= mask; } } } sqlite3_mutex_leave(pShmNode->mutex); OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n", osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask, sqlite3ErrName(rc))); return rc; } /* ** Implement a memory barrier or memory fence on shared memory. ** ** All loads and stores begun before the barrier must complete before ** any load or store begun after the barrier. */ static void winShmBarrier( sqlite3_file *fd /* Database holding the shared memory */ ){ UNUSED_PARAMETER(fd); sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ winShmEnterMutex(); /* Also mutex, for redundancy */ winShmLeaveMutex(); } /* ** This function is called to obtain a pointer to region iRegion of the ** shared-memory associated with the database file fd. Shared-memory regions ** are numbered starting from zero. Each shared-memory region is szRegion ** bytes in size. ** ** If an error occurs, an error code is returned and *pp is set to NULL. ** ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory ** region has not been allocated (by any client, including one running in a ** separate process), then *pp is set to NULL and SQLITE_OK returned. If ** isWrite is non-zero and the requested shared-memory region has not yet ** been allocated, it is allocated by this function. ** ** If the shared-memory region has already been allocated or is allocated by ** this call as described above, then it is mapped into this processes ** address space (if it is not already), *pp is set to point to the mapped ** memory and SQLITE_OK returned. */ static int winShmMap( sqlite3_file *fd, /* Handle open on database file */ int iRegion, /* Region to retrieve */ int szRegion, /* Size of regions */ int isWrite, /* True to extend file if necessary */ void volatile **pp /* OUT: Mapped memory */ ){ winFile *pDbFd = (winFile*)fd; winShm *pShm = pDbFd->pShm; winShmNode *pShmNode; int rc = SQLITE_OK; if( !pShm ){ rc = winOpenSharedMemory(pDbFd); if( rc!=SQLITE_OK ) return rc; pShm = pDbFd->pShm; } pShmNode = pShm->pShmNode; sqlite3_mutex_enter(pShmNode->mutex); assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); if( pShmNode->nRegion<=iRegion ){ struct ShmRegion *apNew; /* New aRegion[] array */ int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ sqlite3_int64 sz; /* Current size of wal-index file */ pShmNode->szRegion = szRegion; /* The requested region is not mapped into this processes address space. ** Check to see if it has been allocated (i.e. if the wal-index file is ** large enough to contain the requested region). */ rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz); if( rc!=SQLITE_OK ){ rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), "winShmMap1", pDbFd->zPath); goto shmpage_out; } if( sz<nByte ){ /* The requested memory region does not exist. If isWrite is set to ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned. ** ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate ** the requested memory region. */ if( !isWrite ) goto shmpage_out; rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte); if( rc!=SQLITE_OK ){ rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), "winShmMap2", pDbFd->zPath); goto shmpage_out; } } /* Map the requested memory region into this processes address space. */ apNew = (struct ShmRegion *)sqlite3_realloc64( pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]) ); if( !apNew ){ rc = SQLITE_IOERR_NOMEM_BKPT; goto shmpage_out; } pShmNode->aRegion = apNew; while( pShmNode->nRegion<=iRegion ){ HANDLE hMap = NULL; /* file-mapping handle */ void *pMap = 0; /* Mapped memory region */ #if SQLITE_OS_WINRT hMap = osCreateFileMappingFromApp(pShmNode->hFile.h, NULL, PAGE_READWRITE, nByte, NULL ); #elif defined(SQLITE_WIN32_HAS_WIDE) hMap = osCreateFileMappingW(pShmNode->hFile.h, NULL, PAGE_READWRITE, 0, nByte, NULL ); #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA hMap = osCreateFileMappingA(pShmNode->hFile.h, NULL, PAGE_READWRITE, 0, nByte, NULL ); #endif OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n", osGetCurrentProcessId(), pShmNode->nRegion, nByte, hMap ? "ok" : "failed")); if( hMap ){ int iOffset = pShmNode->nRegion*szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; #if SQLITE_OS_WINRT pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ, iOffset - iOffsetShift, szRegion + iOffsetShift ); #else pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, iOffset - iOffsetShift, szRegion + iOffsetShift ); #endif OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n", osGetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion, pMap ? "ok" : "failed")); } if( !pMap ){ pShmNode->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno, "winShmMap3", pDbFd->zPath); if( hMap ) osCloseHandle(hMap); goto shmpage_out; } pShmNode->aRegion[pShmNode->nRegion].pMap = pMap; pShmNode->aRegion[pShmNode->nRegion].hMap = hMap; pShmNode->nRegion++; } } shmpage_out: if( pShmNode->nRegion>iRegion ){ int iOffset = iRegion*szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; char *p = (char *)pShmNode->aRegion[iRegion].pMap; *pp = (void *)&p[iOffsetShift]; }else{ *pp = 0; } sqlite3_mutex_leave(pShmNode->mutex); return rc; } #else # define winShmMap 0 # define winShmLock 0 # define winShmBarrier 0 # define winShmUnmap 0 #endif /* #ifndef SQLITE_OMIT_WAL */ /* ** Cleans up the mapped region of the specified file, if any. */ #if SQLITE_MAX_MMAP_SIZE>0 static int winUnmapfile(winFile *pFile){ assert( pFile!=0 ); OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, " "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n", osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion, pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax)); if( pFile->pMapRegion ){ if( !osUnmapViewOfFile(pFile->pMapRegion) ){ pFile->lastErrno = osGetLastError(); OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, " "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, pFile->pMapRegion)); return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, "winUnmapfile1", pFile->zPath); } pFile->pMapRegion = 0; pFile->mmapSize = 0; pFile->mmapSizeActual = 0; } if( pFile->hMap!=NULL ){ if( !osCloseHandle(pFile->hMap) ){ pFile->lastErrno = osGetLastError(); OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, pFile->hMap)); return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, "winUnmapfile2", pFile->zPath); } pFile->hMap = NULL; } OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFile)); return SQLITE_OK; } /* ** Memory map or remap the file opened by file-descriptor pFd (if the file ** is already mapped, the existing mapping is replaced by the new). Or, if ** there already exists a mapping for this file, and there are still ** outstanding xFetch() references to it, this function is a no-op. ** ** If parameter nByte is non-negative, then it is the requested size of ** the mapping to create. Otherwise, if nByte is less than zero, then the ** requested size is the size of the file on disk. The actual size of the ** created mapping is either the requested size or the value configured ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller. ** ** SQLITE_OK is returned if no error occurs (even if the mapping is not ** recreated as a result of outstanding references) or an SQLite error ** code otherwise. */ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ sqlite3_int64 nMap = nByte; int rc; assert( nMap>=0 || pFd->nFetchOut==0 ); OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n", osGetCurrentProcessId(), pFd, nByte)); if( pFd->nFetchOut>0 ) return SQLITE_OK; if( nMap<0 ){ rc = winFileSize((sqlite3_file*)pFd, &nMap); if( rc ){ OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n", osGetCurrentProcessId(), pFd)); return SQLITE_IOERR_FSTAT; } } if( nMap>pFd->mmapSizeMax ){ nMap = pFd->mmapSizeMax; } nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1); if( nMap==0 && pFd->mmapSize>0 ){ winUnmapfile(pFd); } if( nMap!=pFd->mmapSize ){ void *pNew = 0; DWORD protect = PAGE_READONLY; DWORD flags = FILE_MAP_READ; winUnmapfile(pFd); #ifdef SQLITE_MMAP_READWRITE if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){ protect = PAGE_READWRITE; flags |= FILE_MAP_WRITE; } #endif #if SQLITE_OS_WINRT pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL); #elif defined(SQLITE_WIN32_HAS_WIDE) pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect, (DWORD)((nMap>>32) & 0xffffffff), (DWORD)(nMap & 0xffffffff), NULL); #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect, (DWORD)((nMap>>32) & 0xffffffff), (DWORD)(nMap & 0xffffffff), NULL); #endif if( pFd->hMap==NULL ){ pFd->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno, "winMapfile1", pFd->zPath); /* Log the error, but continue normal operation using xRead/xWrite */ OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n", osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); return SQLITE_OK; } assert( (nMap % winSysInfo.dwPageSize)==0 ); assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff ); #if SQLITE_OS_WINRT pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap); #else pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap); #endif if( pNew==NULL ){ osCloseHandle(pFd->hMap); pFd->hMap = NULL; pFd->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno, "winMapfile2", pFd->zPath); /* Log the error, but continue normal operation using xRead/xWrite */ OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n", osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); return SQLITE_OK; } pFd->pMapRegion = pNew; pFd->mmapSize = nMap; pFd->mmapSizeActual = nMap; } OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), pFd)); return SQLITE_OK; } #endif /* SQLITE_MAX_MMAP_SIZE>0 */ /* ** If possible, return a pointer to a mapping of file fd starting at offset ** iOff. The mapping must be valid for at least nAmt bytes. ** ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. ** Finally, if an error does occur, return an SQLite error code. The final ** value of *pp is undefined in this case. ** ** If this function does return a pointer, the caller must eventually ** release the reference by calling winUnfetch(). */ static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ #if SQLITE_MAX_MMAP_SIZE>0 winFile *pFd = (winFile*)fd; /* The underlying database file */ #endif *pp = 0; OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n", osGetCurrentProcessId(), fd, iOff, nAmt, pp)); #if SQLITE_MAX_MMAP_SIZE>0 if( pFd->mmapSizeMax>0 ){ if( pFd->pMapRegion==0 ){ int rc = winMapfile(pFd, -1); if( rc!=SQLITE_OK ){ OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n", osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); return rc; } } if( pFd->mmapSize >= iOff+nAmt ){ *pp = &((u8 *)pFd->pMapRegion)[iOff]; pFd->nFetchOut++; } } #endif OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), fd, pp, *pp)); return SQLITE_OK; } /* ** If the third argument is non-NULL, then this function releases a ** reference obtained by an earlier call to winFetch(). The second ** argument passed to this function must be the same as the corresponding ** argument that was passed to the winFetch() invocation. ** ** Or, if the third argument is NULL, then this function is being called ** to inform the VFS layer that, according to POSIX, any existing mapping ** may now be invalid and should be unmapped. */ static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){ #if SQLITE_MAX_MMAP_SIZE>0 winFile *pFd = (winFile*)fd; /* The underlying database file */ /* If p==0 (unmap the entire file) then there must be no outstanding ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), ** then there must be at least one outstanding. */ assert( (p==0)==(pFd->nFetchOut==0) ); /* If p!=0, it must match the iOff value. */ assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n", osGetCurrentProcessId(), pFd, iOff, p)); if( p ){ pFd->nFetchOut--; }else{ /* FIXME: If Windows truly always prevents truncating or deleting a ** file while a mapping is held, then the following winUnmapfile() call ** is unnecessary can be omitted - potentially improving ** performance. */ winUnmapfile(pFd); } assert( pFd->nFetchOut>=0 ); #endif OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n", osGetCurrentProcessId(), fd)); return SQLITE_OK; } /* ** Here ends the implementation of all sqlite3_file methods. ** ********************** End sqlite3_file Methods ******************************* ******************************************************************************/ /* ** This vector defines all the methods that can operate on an ** sqlite3_file for win32. */ static const sqlite3_io_methods winIoMethod = { 3, /* iVersion */ winClose, /* xClose */ winRead, /* xRead */ winWrite, /* xWrite */ winTruncate, /* xTruncate */ winSync, /* xSync */ winFileSize, /* xFileSize */ winLock, /* xLock */ winUnlock, /* xUnlock */ winCheckReservedLock, /* xCheckReservedLock */ winFileControl, /* xFileControl */ winSectorSize, /* xSectorSize */ winDeviceCharacteristics, /* xDeviceCharacteristics */ winShmMap, /* xShmMap */ winShmLock, /* xShmLock */ winShmBarrier, /* xShmBarrier */ winShmUnmap, /* xShmUnmap */ winFetch, /* xFetch */ winUnfetch /* xUnfetch */ }; /* ** This vector defines all the methods that can operate on an ** sqlite3_file for win32 without performing any locking. */ static const sqlite3_io_methods winIoNolockMethod = { 3, /* iVersion */ winClose, /* xClose */ winRead, /* xRead */ winWrite, /* xWrite */ winTruncate, /* xTruncate */ winSync, /* xSync */ winFileSize, /* xFileSize */ winNolockLock, /* xLock */ winNolockUnlock, /* xUnlock */ winNolockCheckReservedLock, /* xCheckReservedLock */ winFileControl, /* xFileControl */ winSectorSize, /* xSectorSize */ winDeviceCharacteristics, /* xDeviceCharacteristics */ winShmMap, /* xShmMap */ winShmLock, /* xShmLock */ winShmBarrier, /* xShmBarrier */ winShmUnmap, /* xShmUnmap */ winFetch, /* xFetch */ winUnfetch /* xUnfetch */ }; static winVfsAppData winAppData = { &winIoMethod, /* pMethod */ 0, /* pAppData */ 0 /* bNoLock */ }; static winVfsAppData winNolockAppData = { &winIoNolockMethod, /* pMethod */ 0, /* pAppData */ 1 /* bNoLock */ }; /**************************************************************************** **************************** sqlite3_vfs methods **************************** ** ** This division contains the implementation of methods on the ** sqlite3_vfs object. */ #if defined(__CYGWIN__) /* ** Convert a filename from whatever the underlying operating system ** supports for filenames into UTF-8. Space to hold the result is ** obtained from malloc and must be freed by the calling function. */ static char *winConvertToUtf8Filename(const void *zFilename){ char *zConverted = 0; if( osIsNT() ){ zConverted = winUnicodeToUtf8(zFilename); } #ifdef SQLITE_WIN32_HAS_ANSI else{ zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI()); } #endif /* caller will handle out of memory */ return zConverted; } #endif /* ** Convert a UTF-8 filename into whatever form the underlying ** operating system wants filenames in. Space to hold the result ** is obtained from malloc and must be freed by the calling ** function. */ static void *winConvertFromUtf8Filename(const char *zFilename){ void *zConverted = 0; if( osIsNT() ){ zConverted = winUtf8ToUnicode(zFilename); } #ifdef SQLITE_WIN32_HAS_ANSI else{ zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI()); } #endif /* caller will handle out of memory */ return zConverted; } /* ** This function returns non-zero if the specified UTF-8 string buffer ** ends with a directory separator character or one was successfully ** added to it. */ static int winMakeEndInDirSep(int nBuf, char *zBuf){ if( zBuf ){ int nLen = sqlite3Strlen30(zBuf); if( nLen>0 ){ if( winIsDirSep(zBuf[nLen-1]) ){ return 1; }else if( nLen+1<nBuf ){ zBuf[nLen] = winGetDirSep(); zBuf[nLen+1] = '\0'; return 1; } } } return 0; } /* ** Create a temporary file name and store the resulting pointer into pzBuf. ** The pointer returned in pzBuf must be freed via sqlite3_free(). */ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ static char zChars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"; size_t i, j; int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX); int nMax, nBuf, nDir, nLen; char *zBuf; /* It's odd to simulate an io-error here, but really this is just ** using the io-error infrastructure to test that SQLite handles this ** function failing. */ SimulateIOError( return SQLITE_IOERR ); /* Allocate a temporary buffer to store the fully qualified file ** name for the temporary file. If this fails, we cannot continue. */ nMax = pVfs->mxPathname; nBuf = nMax + 2; zBuf = sqlite3MallocZero( nBuf ); if( !zBuf ){ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } /* Figure out the effective temporary directory. First, check if one ** has been explicitly set by the application; otherwise, use the one ** configured by the operating system. */ nDir = nMax - (nPre + 15); assert( nDir>0 ); if( sqlite3_temp_directory ){ int nDirLen = sqlite3Strlen30(sqlite3_temp_directory); if( nDirLen>0 ){ if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){ nDirLen++; } if( nDirLen>nDir ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0); } sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory); } } #if defined(__CYGWIN__) else{ static const char *azDirs[] = { 0, /* getenv("SQLITE_TMPDIR") */ 0, /* getenv("TMPDIR") */ 0, /* getenv("TMP") */ 0, /* getenv("TEMP") */ 0, /* getenv("USERPROFILE") */ "/var/tmp", "/usr/tmp", "/tmp", ".", 0 /* List terminator */ }; unsigned int i; const char *zDir = 0; if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); if( !azDirs[2] ) azDirs[2] = getenv("TMP"); if( !azDirs[3] ) azDirs[3] = getenv("TEMP"); if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE"); for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){ void *zConverted; if( zDir==0 ) continue; /* If the path starts with a drive letter followed by the colon ** character, assume it is already a native Win32 path; otherwise, ** it must be converted to a native Win32 path via the Cygwin API ** prior to using it. */ if( winIsDriveLetterAndColon(zDir) ){ zConverted = winConvertFromUtf8Filename(zDir); if( !zConverted ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } if( winIsDir(zConverted) ){ sqlite3_snprintf(nMax, zBuf, "%s", zDir); sqlite3_free(zConverted); break; } sqlite3_free(zConverted); }else{ zConverted = sqlite3MallocZero( nMax+1 ); if( !zConverted ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } if( cygwin_conv_path( osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir, zConverted, nMax+1)<0 ){ sqlite3_free(zConverted); sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n")); return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno, "winGetTempname2", zDir); } if( winIsDir(zConverted) ){ /* At this point, we know the candidate directory exists and should ** be used. However, we may need to convert the string containing ** its name into UTF-8 (i.e. if it is UTF-16 right now). */ char *zUtf8 = winConvertToUtf8Filename(zConverted); if( !zUtf8 ){ sqlite3_free(zConverted); sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); sqlite3_free(zUtf8); sqlite3_free(zConverted); break; } sqlite3_free(zConverted); } } } #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__) else if( osIsNT() ){ char *zMulti; LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) ); if( !zWidePath ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } if( osGetTempPathW(nMax, zWidePath)==0 ){ sqlite3_free(zWidePath); sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(), "winGetTempname2", 0); } zMulti = winUnicodeToUtf8(zWidePath); if( zMulti ){ sqlite3_snprintf(nMax, zBuf, "%s", zMulti); sqlite3_free(zMulti); sqlite3_free(zWidePath); }else{ sqlite3_free(zWidePath); sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } } #ifdef SQLITE_WIN32_HAS_ANSI else{ char *zUtf8; char *zMbcsPath = sqlite3MallocZero( nMax ); if( !zMbcsPath ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } if( osGetTempPathA(nMax, zMbcsPath)==0 ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(), "winGetTempname3", 0); } zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI()); if( zUtf8 ){ sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); sqlite3_free(zUtf8); }else{ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } } #endif /* SQLITE_WIN32_HAS_ANSI */ #endif /* !SQLITE_OS_WINRT */ /* ** Check to make sure the temporary directory ends with an appropriate ** separator. If it does not and there is not enough space left to add ** one, fail. */ if( !winMakeEndInDirSep(nDir+1, zBuf) ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0); } /* ** Check that the output buffer is large enough for the temporary file ** name in the following format: ** ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0" ** ** If not, return SQLITE_ERROR. The number 17 is used here in order to ** account for the space used by the 15 character random suffix and the ** two trailing NUL characters. The final directory separator character ** has already added if it was not already present. */ nLen = sqlite3Strlen30(zBuf); if( (nLen + nPre + 17) > nBuf ){ sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0); } sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); j = sqlite3Strlen30(zBuf); sqlite3_randomness(15, &zBuf[j]); for(i=0; i<15; i++, j++){ zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; } zBuf[j] = 0; zBuf[j+1] = 0; *pzBuf = zBuf; OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf)); return SQLITE_OK; } /* ** Return TRUE if the named file is really a directory. Return false if ** it is something other than a directory, or if there is any kind of memory ** allocation failure. */ static int winIsDir(const void *zConverted){ DWORD attr; int rc = 0; DWORD lastErrno; if( osIsNT() ){ int cnt = 0; WIN32_FILE_ATTRIBUTE_DATA sAttrData; memset(&sAttrData, 0, sizeof(sAttrData)); while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, GetFileExInfoStandard, &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} if( !rc ){ return 0; /* Invalid name? */ } attr = sAttrData.dwFileAttributes; #if SQLITE_OS_WINCE==0 }else{ attr = osGetFileAttributesA((char*)zConverted); #endif } return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY); } /* ** Open a file. */ static int winOpen( sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */ const char *zName, /* Name of the file (UTF-8) */ sqlite3_file *id, /* Write the SQLite file handle here */ int flags, /* Open mode flags */ int *pOutFlags /* Status return flags */ ){ HANDLE h; DWORD lastErrno = 0; DWORD dwDesiredAccess; DWORD dwShareMode; DWORD dwCreationDisposition; DWORD dwFlagsAndAttributes = 0; #if SQLITE_OS_WINCE int isTemp = 0; #endif winVfsAppData *pAppData; winFile *pFile = (winFile*)id; void *zConverted; /* Filename in OS encoding */ const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */ int cnt = 0; /* If argument zPath is a NULL pointer, this function is required to open ** a temporary file. Use this buffer to store the file name in. */ char *zTmpname = 0; /* For temporary filename, if necessary. */ int rc = SQLITE_OK; /* Function Return Code */ #if !defined(NDEBUG) || SQLITE_OS_WINCE int eType = flags&0xFFFFFF00; /* Type of file to open */ #endif int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); int isCreate = (flags & SQLITE_OPEN_CREATE); int isReadonly = (flags & SQLITE_OPEN_READONLY); int isReadWrite = (flags & SQLITE_OPEN_READWRITE); #ifndef NDEBUG int isOpenJournal = (isCreate && ( eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_WAL )); #endif OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n", zUtf8Name, id, flags, pOutFlags)); /* Check the following statements are true: ** ** (a) Exactly one of the READWRITE and READONLY flags must be set, and ** (b) if CREATE is set, then READWRITE must also be set, and ** (c) if EXCLUSIVE is set, then CREATE must also be set. ** (d) if DELETEONCLOSE is set, then CREATE must also be set. */ assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); assert(isCreate==0 || isReadWrite); assert(isExclusive==0 || isCreate); assert(isDelete==0 || isCreate); /* The main DB, main journal, WAL file and master journal are never ** automatically deleted. Nor are they ever temporary files. */ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); /* Assert that the upper layer has set one of the "file-type" flags. */ assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL ); assert( pFile!=0 ); memset(pFile, 0, sizeof(winFile)); pFile->h = INVALID_HANDLE_VALUE; #if SQLITE_OS_WINRT if( !zUtf8Name && !sqlite3_temp_directory ){ sqlite3_log(SQLITE_ERROR, "sqlite3_temp_directory variable should be set for WinRT"); } #endif /* If the second argument to this function is NULL, generate a ** temporary file name to use */ if( !zUtf8Name ){ assert( isDelete && !isOpenJournal ); rc = winGetTempname(pVfs, &zTmpname); if( rc!=SQLITE_OK ){ OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc))); return rc; } zUtf8Name = zTmpname; } /* Database filenames are double-zero terminated if they are not ** URIs with parameters. Hence, they can always be passed into ** sqlite3_uri_parameter(). */ assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) || zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 ); /* Convert the filename to the system encoding. */ zConverted = winConvertFromUtf8Filename(zUtf8Name); if( zConverted==0 ){ sqlite3_free(zTmpname); OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name)); return SQLITE_IOERR_NOMEM_BKPT; } if( winIsDir(zConverted) ){ sqlite3_free(zConverted); sqlite3_free(zTmpname); OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name)); return SQLITE_CANTOPEN_ISDIR; } if( isReadWrite ){ dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; }else{ dwDesiredAccess = GENERIC_READ; } /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is ** created. SQLite doesn't use it to indicate "exclusive access" ** as it is usually understood. */ if( isExclusive ){ /* Creates a new file, only if it does not already exist. */ /* If the file exists, it fails. */ dwCreationDisposition = CREATE_NEW; }else if( isCreate ){ /* Open existing file, or create if it doesn't exist */ dwCreationDisposition = OPEN_ALWAYS; }else{ /* Opens a file, only if it exists. */ dwCreationDisposition = OPEN_EXISTING; } dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; if( isDelete ){ #if SQLITE_OS_WINCE dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; isTemp = 1; #else dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY | FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE; #endif }else{ dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; } /* Reports from the internet are that performance is always ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */ #if SQLITE_OS_WINCE dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS; #endif if( osIsNT() ){ #if SQLITE_OS_WINRT CREATEFILE2_EXTENDED_PARAMETERS extendedParameters; extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); extendedParameters.dwFileAttributes = dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK; extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK; extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS; extendedParameters.lpSecurityAttributes = NULL; extendedParameters.hTemplateFile = NULL; while( (h = osCreateFile2((LPCWSTR)zConverted, dwDesiredAccess, dwShareMode, dwCreationDisposition, &extendedParameters))==INVALID_HANDLE_VALUE && winRetryIoerr(&cnt, &lastErrno) ){ /* Noop */ } #else while( (h = osCreateFileW((LPCWSTR)zConverted, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL))==INVALID_HANDLE_VALUE && winRetryIoerr(&cnt, &lastErrno) ){ /* Noop */ } #endif } #ifdef SQLITE_WIN32_HAS_ANSI else{ while( (h = osCreateFileA((LPCSTR)zConverted, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL))==INVALID_HANDLE_VALUE && winRetryIoerr(&cnt, &lastErrno) ){ /* Noop */ } } #endif winLogIoerr(cnt, __LINE__); OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name, dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); if( h==INVALID_HANDLE_VALUE ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name); sqlite3_free(zConverted); sqlite3_free(zTmpname); if( isReadWrite && !isExclusive ){ return winOpen(pVfs, zName, id, ((flags|SQLITE_OPEN_READONLY) & ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags); }else{ return SQLITE_CANTOPEN_BKPT; } } if( pOutFlags ){ if( isReadWrite ){ *pOutFlags = SQLITE_OPEN_READWRITE; }else{ *pOutFlags = SQLITE_OPEN_READONLY; } } OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, " "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ? *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); pAppData = (winVfsAppData*)pVfs->pAppData; #if SQLITE_OS_WINCE { if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB && ((pAppData==NULL) || !pAppData->bNoLock) && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK ){ osCloseHandle(h); sqlite3_free(zConverted); sqlite3_free(zTmpname); OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc))); return rc; } } if( isTemp ){ pFile->zDeleteOnClose = zConverted; }else #endif { sqlite3_free(zConverted); } sqlite3_free(zTmpname); pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod; pFile->pVfs = pVfs; pFile->h = h; if( isReadonly ){ pFile->ctrlFlags |= WINFILE_RDONLY; } if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){ pFile->ctrlFlags |= WINFILE_PSOW; } pFile->lastErrno = NO_ERROR; pFile->zPath = zName; #if SQLITE_MAX_MMAP_SIZE>0 pFile->hMap = NULL; pFile->pMapRegion = 0; pFile->mmapSize = 0; pFile->mmapSizeActual = 0; pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap; #endif OpenCounter(+1); return rc; } /* ** Delete the named file. ** ** Note that Windows does not allow a file to be deleted if some other ** process has it open. Sometimes a virus scanner or indexing program ** will open a journal file shortly after it is created in order to do ** whatever it does. While this other process is holding the ** file open, we will be unable to delete it. To work around this ** problem, we delay 100 milliseconds and try to delete again. Up ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving ** up and returning an error. */ static int winDelete( sqlite3_vfs *pVfs, /* Not used on win32 */ const char *zFilename, /* Name of file to delete */ int syncDir /* Not used on win32 */ ){ int cnt = 0; int rc; DWORD attr; DWORD lastErrno = 0; void *zConverted; UNUSED_PARAMETER(pVfs); UNUSED_PARAMETER(syncDir); SimulateIOError(return SQLITE_IOERR_DELETE); OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir)); zConverted = winConvertFromUtf8Filename(zFilename); if( zConverted==0 ){ OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); return SQLITE_IOERR_NOMEM_BKPT; } if( osIsNT() ){ do { #if SQLITE_OS_WINRT WIN32_FILE_ATTRIBUTE_DATA sAttrData; memset(&sAttrData, 0, sizeof(sAttrData)); if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard, &sAttrData) ){ attr = sAttrData.dwFileAttributes; }else{ lastErrno = osGetLastError(); if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ }else{ rc = SQLITE_ERROR; } break; } #else attr = osGetFileAttributesW(zConverted); #endif if ( attr==INVALID_FILE_ATTRIBUTES ){ lastErrno = osGetLastError(); if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ }else{ rc = SQLITE_ERROR; } break; } if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ rc = SQLITE_ERROR; /* Files only. */ break; } if ( osDeleteFileW(zConverted) ){ rc = SQLITE_OK; /* Deleted OK. */ break; } if ( !winRetryIoerr(&cnt, &lastErrno) ){ rc = SQLITE_ERROR; /* No more retries. */ break; } } while(1); } #ifdef SQLITE_WIN32_HAS_ANSI else{ do { attr = osGetFileAttributesA(zConverted); if ( attr==INVALID_FILE_ATTRIBUTES ){ lastErrno = osGetLastError(); if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){ rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ }else{ rc = SQLITE_ERROR; } break; } if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ rc = SQLITE_ERROR; /* Files only. */ break; } if ( osDeleteFileA(zConverted) ){ rc = SQLITE_OK; /* Deleted OK. */ break; } if ( !winRetryIoerr(&cnt, &lastErrno) ){ rc = SQLITE_ERROR; /* No more retries. */ break; } } while(1); } #endif if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){ rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename); }else{ winLogIoerr(cnt, __LINE__); } sqlite3_free(zConverted); OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc))); return rc; } /* ** Check the existence and status of a file. */ static int winAccess( sqlite3_vfs *pVfs, /* Not used on win32 */ const char *zFilename, /* Name of file to check */ int flags, /* Type of test to make on this file */ int *pResOut /* OUT: Result */ ){ DWORD attr; int rc = 0; DWORD lastErrno = 0; void *zConverted; UNUSED_PARAMETER(pVfs); SimulateIOError( return SQLITE_IOERR_ACCESS; ); OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n", zFilename, flags, pResOut)); zConverted = winConvertFromUtf8Filename(zFilename); if( zConverted==0 ){ OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); return SQLITE_IOERR_NOMEM_BKPT; } if( osIsNT() ){ int cnt = 0; WIN32_FILE_ATTRIBUTE_DATA sAttrData; memset(&sAttrData, 0, sizeof(sAttrData)); while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, GetFileExInfoStandard, &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} if( rc ){ /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file ** as if it does not exist. */ if( flags==SQLITE_ACCESS_EXISTS && sAttrData.nFileSizeHigh==0 && sAttrData.nFileSizeLow==0 ){ attr = INVALID_FILE_ATTRIBUTES; }else{ attr = sAttrData.dwFileAttributes; } }else{ winLogIoerr(cnt, __LINE__); if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ sqlite3_free(zConverted); return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename); }else{ attr = INVALID_FILE_ATTRIBUTES; } } } #ifdef SQLITE_WIN32_HAS_ANSI else{ attr = osGetFileAttributesA((char*)zConverted); } #endif sqlite3_free(zConverted); switch( flags ){ case SQLITE_ACCESS_READ: case SQLITE_ACCESS_EXISTS: rc = attr!=INVALID_FILE_ATTRIBUTES; break; case SQLITE_ACCESS_READWRITE: rc = attr!=INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_READONLY)==0; break; default: assert(!"Invalid flags argument"); } *pResOut = rc; OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", zFilename, pResOut, *pResOut)); return SQLITE_OK; } /* ** Returns non-zero if the specified path name starts with a drive letter ** followed by a colon character. */ static BOOL winIsDriveLetterAndColon( const char *zPathname ){ return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ); } /* ** Returns non-zero if the specified path name should be used verbatim. If ** non-zero is returned from this function, the calling function must simply ** use the provided path name verbatim -OR- resolve it into a full path name ** using the GetFullPathName Win32 API function (if available). */ static BOOL winIsVerbatimPathname( const char *zPathname ){ /* ** If the path name starts with a forward slash or a backslash, it is either ** a legal UNC name, a volume relative path, or an absolute path name in the ** "Unix" format on Windows. There is no easy way to differentiate between ** the final two cases; therefore, we return the safer return value of TRUE ** so that callers of this function will simply use it verbatim. */ if ( winIsDirSep(zPathname[0]) ){ return TRUE; } /* ** If the path name starts with a letter and a colon it is either a volume ** relative path or an absolute path. Callers of this function must not ** attempt to treat it as a relative path name (i.e. they should simply use ** it verbatim). */ if ( winIsDriveLetterAndColon(zPathname) ){ return TRUE; } /* ** If we get to this point, the path name should almost certainly be a purely ** relative one (i.e. not a UNC name, not absolute, and not volume relative). */ return FALSE; } /* ** Turn a relative pathname into a full pathname. Write the full ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname ** bytes in size. */ static int winFullPathname( sqlite3_vfs *pVfs, /* Pointer to vfs object */ const char *zRelative, /* Possibly relative input path */ int nFull, /* Size of output buffer in bytes */ char *zFull /* Output buffer */ ){ #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) DWORD nByte; void *zConverted; char *zOut; #endif /* If this path name begins with "/X:", where "X" is any alphabetic ** character, discard the initial "/" from the pathname. */ if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){ zRelative++; } #if defined(__CYGWIN__) SimulateIOError( return SQLITE_ERROR ); UNUSED_PARAMETER(nFull); assert( nFull>=pVfs->mxPathname ); if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a slash. */ char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); if( !zOut ){ return SQLITE_IOERR_NOMEM_BKPT; } if( cygwin_conv_path( (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) | CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){ sqlite3_free(zOut); return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, "winFullPathname1", zRelative); }else{ char *zUtf8 = winConvertToUtf8Filename(zOut); if( !zUtf8 ){ sqlite3_free(zOut); return SQLITE_IOERR_NOMEM_BKPT; } sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", sqlite3_data_directory, winGetDirSep(), zUtf8); sqlite3_free(zUtf8); sqlite3_free(zOut); } }else{ char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); if( !zOut ){ return SQLITE_IOERR_NOMEM_BKPT; } if( cygwin_conv_path( (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A), zRelative, zOut, pVfs->mxPathname+1)<0 ){ sqlite3_free(zOut); return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, "winFullPathname2", zRelative); }else{ char *zUtf8 = winConvertToUtf8Filename(zOut); if( !zUtf8 ){ sqlite3_free(zOut); return SQLITE_IOERR_NOMEM_BKPT; } sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8); sqlite3_free(zUtf8); sqlite3_free(zOut); } } return SQLITE_OK; #endif #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__) SimulateIOError( return SQLITE_ERROR ); /* WinCE has no concept of a relative pathname, or so I am told. */ /* WinRT has no way to convert a relative path to an absolute one. */ if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a backslash. */ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", sqlite3_data_directory, winGetDirSep(), zRelative); }else{ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative); } return SQLITE_OK; #endif #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) /* It's odd to simulate an io-error here, but really this is just ** using the io-error infrastructure to test that SQLite handles this ** function failing. This function could fail if, for example, the ** current working directory has been unlinked. */ SimulateIOError( return SQLITE_ERROR ); if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a backslash. */ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", sqlite3_data_directory, winGetDirSep(), zRelative); return SQLITE_OK; } zConverted = winConvertFromUtf8Filename(zRelative); if( zConverted==0 ){ return SQLITE_IOERR_NOMEM_BKPT; } if( osIsNT() ){ LPWSTR zTemp; nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0); if( nByte==0 ){ sqlite3_free(zConverted); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname1", zRelative); } nByte += 3; zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); if( zTemp==0 ){ sqlite3_free(zConverted); return SQLITE_IOERR_NOMEM_BKPT; } nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0); if( nByte==0 ){ sqlite3_free(zConverted); sqlite3_free(zTemp); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname2", zRelative); } sqlite3_free(zConverted); zOut = winUnicodeToUtf8(zTemp); sqlite3_free(zTemp); } #ifdef SQLITE_WIN32_HAS_ANSI else{ char *zTemp; nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0); if( nByte==0 ){ sqlite3_free(zConverted); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname3", zRelative); } nByte += 3; zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); if( zTemp==0 ){ sqlite3_free(zConverted); return SQLITE_IOERR_NOMEM_BKPT; } nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0); if( nByte==0 ){ sqlite3_free(zConverted); sqlite3_free(zTemp); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname4", zRelative); } sqlite3_free(zConverted); zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); sqlite3_free(zTemp); } #endif if( zOut ){ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); sqlite3_free(zOut); return SQLITE_OK; }else{ return SQLITE_IOERR_NOMEM_BKPT; } #endif } #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** Interfaces for opening a shared library, finding entry points ** within the shared library, and closing the shared library. */ static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ HANDLE h; #if defined(__CYGWIN__) int nFull = pVfs->mxPathname+1; char *zFull = sqlite3MallocZero( nFull ); void *zConverted = 0; if( zFull==0 ){ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){ sqlite3_free(zFull); OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } zConverted = winConvertFromUtf8Filename(zFull); sqlite3_free(zFull); #else void *zConverted = winConvertFromUtf8Filename(zFilename); UNUSED_PARAMETER(pVfs); #endif if( zConverted==0 ){ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } if( osIsNT() ){ #if SQLITE_OS_WINRT h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0); #else h = osLoadLibraryW((LPCWSTR)zConverted); #endif } #ifdef SQLITE_WIN32_HAS_ANSI else{ h = osLoadLibraryA((char*)zConverted); } #endif OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h)); sqlite3_free(zConverted); return (void*)h; } static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){ UNUSED_PARAMETER(pVfs); winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut); } static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ FARPROC proc; UNUSED_PARAMETER(pVfs); proc = osGetProcAddressA((HANDLE)pH, zSym); OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n", (void*)pH, zSym, (void*)proc)); return (void(*)(void))proc; } static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){ UNUSED_PARAMETER(pVfs); osFreeLibrary((HANDLE)pHandle); OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle)); } #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ #define winDlOpen 0 #define winDlError 0 #define winDlSym 0 #define winDlClose 0 #endif /* State information for the randomness gatherer. */ typedef struct EntropyGatherer EntropyGatherer; struct EntropyGatherer { unsigned char *a; /* Gather entropy into this buffer */ int na; /* Size of a[] in bytes */ int i; /* XOR next input into a[i] */ int nXor; /* Number of XOR operations done */ }; #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) /* Mix sz bytes of entropy into p. */ static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){ int j, k; for(j=0, k=p->i; j<sz; j++){ p->a[k++] ^= x[j]; if( k>=p->na ) k = 0; } p->i = k; p->nXor += sz; } #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */ /* ** Write up to nBuf bytes of randomness into zBuf. */ static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) UNUSED_PARAMETER(pVfs); memset(zBuf, 0, nBuf); return nBuf; #else EntropyGatherer e; UNUSED_PARAMETER(pVfs); memset(zBuf, 0, nBuf); #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */ #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */ e.a = (unsigned char*)zBuf; e.na = nBuf; e.nXor = 0; e.i = 0; { SYSTEMTIME x; osGetSystemTime(&x); xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME)); } { DWORD pid = osGetCurrentProcessId(); xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD)); } #if SQLITE_OS_WINRT { ULONGLONG cnt = osGetTickCount64(); xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG)); } #else { DWORD cnt = osGetTickCount(); xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD)); } #endif /* SQLITE_OS_WINRT */ { LARGE_INTEGER i; osQueryPerformanceCounter(&i); xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER)); } #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID { UUID id; memset(&id, 0, sizeof(UUID)); osUuidCreate(&id); xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); memset(&id, 0, sizeof(UUID)); osUuidCreateSequential(&id); xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); } #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */ return e.nXor>nBuf ? nBuf : e.nXor; #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */ } /* ** Sleep for a little while. Return the amount of time slept. */ static int winSleep(sqlite3_vfs *pVfs, int microsec){ sqlite3_win32_sleep((microsec+999)/1000); UNUSED_PARAMETER(pVfs); return ((microsec+999)/1000)*1000; } /* ** The following variable, if set to a non-zero value, is interpreted as ** the number of seconds since 1970 and is used to set the result of ** sqlite3OsCurrentTime() during testing. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ #endif /* ** Find the current time (in Universal Coordinated Time). Write into *piNow ** the current time and date as a Julian Day number times 86_400_000. In ** other words, write into *piNow the number of milliseconds since the Julian ** epoch of noon in Greenwich on November 24, 4714 B.C according to the ** proleptic Gregorian calendar. ** ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date ** cannot be found. */ static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ /* FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). */ FILETIME ft; static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000; #ifdef SQLITE_TEST static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; #endif /* 2^32 - to avoid use of LL and warnings in gcc */ static const sqlite3_int64 max32BitValue = (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296; #if SQLITE_OS_WINCE SYSTEMTIME time; osGetSystemTime(&time); /* if SystemTimeToFileTime() fails, it returns zero. */ if (!osSystemTimeToFileTime(&time,&ft)){ return SQLITE_ERROR; } #else osGetSystemTimeAsFileTime( &ft ); #endif *piNow = winFiletimeEpoch + ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; #ifdef SQLITE_TEST if( sqlite3_current_time ){ *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; } #endif UNUSED_PARAMETER(pVfs); return SQLITE_OK; } /* ** Find the current time (in Universal Coordinated Time). Write the ** current time and date as a Julian Day number into *prNow and ** return 0. Return 1 if the time and date cannot be found. */ static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){ int rc; sqlite3_int64 i; rc = winCurrentTimeInt64(pVfs, &i); if( !rc ){ *prNow = i/86400000.0; } return rc; } /* ** The idea is that this function works like a combination of ** GetLastError() and FormatMessage() on Windows (or errno and ** strerror_r() on Unix). After an error is returned by an OS ** function, SQLite calls this function with zBuf pointing to ** a buffer of nBuf bytes. The OS layer should populate the ** buffer with a nul-terminated UTF-8 encoded error message ** describing the last IO error to have occurred within the calling ** thread. ** ** If the error message is too large for the supplied buffer, ** it should be truncated. The return value of xGetLastError ** is zero if the error message fits in the buffer, or non-zero ** otherwise (if the message was truncated). If non-zero is returned, ** then it is not necessary to include the nul-terminator character ** in the output buffer. ** ** Not supplying an error message will have no adverse effect ** on SQLite. It is fine to have an implementation that never ** returns an error message: ** ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ ** assert(zBuf[0]=='\0'); ** return 0; ** } ** ** However if an error message is supplied, it will be incorporated ** by sqlite into the error message available to the user using ** sqlite3_errmsg(), possibly making IO errors easier to debug. */ static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ DWORD e = osGetLastError(); UNUSED_PARAMETER(pVfs); if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf); return e; } /* ** Initialize and deinitialize the operating system interface. */ SQLITE_API int sqlite3_os_init(void){ static sqlite3_vfs winVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ 0, /* pNext */ "win32", /* zName */ &winAppData, /* pAppData */ winOpen, /* xOpen */ winDelete, /* xDelete */ winAccess, /* xAccess */ winFullPathname, /* xFullPathname */ winDlOpen, /* xDlOpen */ winDlError, /* xDlError */ winDlSym, /* xDlSym */ winDlClose, /* xDlClose */ winRandomness, /* xRandomness */ winSleep, /* xSleep */ winCurrentTime, /* xCurrentTime */ winGetLastError, /* xGetLastError */ winCurrentTimeInt64, /* xCurrentTimeInt64 */ winSetSystemCall, /* xSetSystemCall */ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; #if defined(SQLITE_WIN32_HAS_WIDE) static sqlite3_vfs winLongPathVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ 0, /* pNext */ "win32-longpath", /* zName */ &winAppData, /* pAppData */ winOpen, /* xOpen */ winDelete, /* xDelete */ winAccess, /* xAccess */ winFullPathname, /* xFullPathname */ winDlOpen, /* xDlOpen */ winDlError, /* xDlError */ winDlSym, /* xDlSym */ winDlClose, /* xDlClose */ winRandomness, /* xRandomness */ winSleep, /* xSleep */ winCurrentTime, /* xCurrentTime */ winGetLastError, /* xGetLastError */ winCurrentTimeInt64, /* xCurrentTimeInt64 */ winSetSystemCall, /* xSetSystemCall */ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; #endif static sqlite3_vfs winNolockVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ 0, /* pNext */ "win32-none", /* zName */ &winNolockAppData, /* pAppData */ winOpen, /* xOpen */ winDelete, /* xDelete */ winAccess, /* xAccess */ winFullPathname, /* xFullPathname */ winDlOpen, /* xDlOpen */ winDlError, /* xDlError */ winDlSym, /* xDlSym */ winDlClose, /* xDlClose */ winRandomness, /* xRandomness */ winSleep, /* xSleep */ winCurrentTime, /* xCurrentTime */ winGetLastError, /* xGetLastError */ winCurrentTimeInt64, /* xCurrentTimeInt64 */ winSetSystemCall, /* xSetSystemCall */ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; #if defined(SQLITE_WIN32_HAS_WIDE) static sqlite3_vfs winLongPathNolockVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ 0, /* pNext */ "win32-longpath-none", /* zName */ &winNolockAppData, /* pAppData */ winOpen, /* xOpen */ winDelete, /* xDelete */ winAccess, /* xAccess */ winFullPathname, /* xFullPathname */ winDlOpen, /* xDlOpen */ winDlError, /* xDlError */ winDlSym, /* xDlSym */ winDlClose, /* xDlClose */ winRandomness, /* xRandomness */ winSleep, /* xSleep */ winCurrentTime, /* xCurrentTime */ winGetLastError, /* xGetLastError */ winCurrentTimeInt64, /* xCurrentTimeInt64 */ winSetSystemCall, /* xSetSystemCall */ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; #endif /* Double-check that the aSyscall[] array has been constructed ** correctly. See ticket [bb3a86e890c8e96ab] */ assert( ArraySize(aSyscall)==80 ); /* get memory map allocation granularity */ memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); #if SQLITE_OS_WINRT osGetNativeSystemInfo(&winSysInfo); #else osGetSystemInfo(&winSysInfo); #endif assert( winSysInfo.dwAllocationGranularity>0 ); assert( winSysInfo.dwPageSize>0 ); sqlite3_vfs_register(&winVfs, 1); #if defined(SQLITE_WIN32_HAS_WIDE) sqlite3_vfs_register(&winLongPathVfs, 0); #endif sqlite3_vfs_register(&winNolockVfs, 0); #if defined(SQLITE_WIN32_HAS_WIDE) sqlite3_vfs_register(&winLongPathNolockVfs, 0); #endif return SQLITE_OK; } SQLITE_API int sqlite3_os_end(void){ #if SQLITE_OS_WINRT if( sleepObj!=NULL ){ osCloseHandle(sleepObj); sleepObj = NULL; } #endif return SQLITE_OK; } #endif /* SQLITE_OS_WIN */ /************** End of os_win.c **********************************************/ /************** Begin file bitvec.c ******************************************/ /* ** 2008 February 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements an object that represents a fixed-length ** bitmap. Bits are numbered starting with 1. ** ** A bitmap is used to record which pages of a database file have been ** journalled during a transaction, or which pages have the "dont-write" ** property. Usually only a few pages are meet either condition. ** So the bitmap is usually sparse and has low cardinality. ** But sometimes (for example when during a DROP of a large table) most ** or all of the pages in a database can get journalled. In those cases, ** the bitmap becomes dense with high cardinality. The algorithm needs ** to handle both cases well. ** ** The size of the bitmap is fixed when the object is created. ** ** All bits are clear when the bitmap is created. Individual bits ** may be set or cleared one at a time. ** ** Test operations are about 100 times more common that set operations. ** Clear operations are exceedingly rare. There are usually between ** 5 and 500 set operations per Bitvec object, though the number of sets can ** sometimes grow into tens of thousands or larger. The size of the ** Bitvec object is the number of pages in the database file at the ** start of a transaction, and is thus usually less than a few thousand, ** but can be as large as 2 billion for a really big database. */ /* #include "sqliteInt.h" */ /* Size of the Bitvec structure in bytes. */ #define BITVEC_SZ 512 /* Round the union size down to the nearest pointer boundary, since that's how ** it will be aligned within the Bitvec struct. */ #define BITVEC_USIZE \ (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) /* Type of the array "element" for the bitmap representation. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. ** Setting this to the "natural word" size of your CPU may improve ** performance. */ #define BITVEC_TELEM u8 /* Size, in bits, of the bitmap element. */ #define BITVEC_SZELEM 8 /* Number of elements in a bitmap array. */ #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM)) /* Number of bits in the bitmap array. */ #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) /* Number of u32 values in hash table. */ #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) /* Maximum number of entries in hash table before ** sub-dividing and re-hashing. */ #define BITVEC_MXHASH (BITVEC_NINT/2) /* Hashing function for the aHash representation. ** Empirical testing showed that the *37 multiplier ** (an arbitrary prime)in the hash function provided ** no fewer collisions than the no-op *1. */ #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *)) /* ** A bitmap is an instance of the following structure. ** ** This bitmap records the existence of zero or more bits ** with values between 1 and iSize, inclusive. ** ** There are three possible representations of the bitmap. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight ** bitmap. The least significant bit is bit 1. ** ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is ** a hash table that will hold up to BITVEC_MXHASH distinct values. ** ** Otherwise, the value i is redirected into one of BITVEC_NPTR ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap ** handles up to iDivisor separate values of i. apSub[0] holds ** values between 1 and iDivisor. apSub[1] holds values between ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized ** to hold deal with values between 1 and iDivisor. */ struct Bitvec { u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ u32 nSet; /* Number of bits that are set - only valid for aHash ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, ** this would be 125. */ u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ /* Should >=0 for apSub element. */ /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ /* For a BITVEC_SZ of 512, this would be 34,359,739. */ union { BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */ u32 aHash[BITVEC_NINT]; /* Hash table representation */ Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */ } u; }; /* ** Create a new bitmap object able to handle bits between 0 and iSize, ** inclusive. Return a pointer to the new object. Return NULL if ** malloc fails. */ SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){ Bitvec *p; assert( sizeof(*p)==BITVEC_SZ ); p = sqlite3MallocZero( sizeof(*p) ); if( p ){ p->iSize = iSize; } return p; } /* ** Check to see if the i-th bit is set. Return true or false. ** If p is NULL (if the bitmap has not been created) or if ** i is out of range, then return false. */ SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){ assert( p!=0 ); i--; if( i>=p->iSize ) return 0; while( p->iDivisor ){ u32 bin = i/p->iDivisor; i = i%p->iDivisor; p = p->u.apSub[bin]; if (!p) { return 0; } } if( p->iSize<=BITVEC_NBIT ){ return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0; } else{ u32 h = BITVEC_HASH(i++); while( p->u.aHash[h] ){ if( p->u.aHash[h]==i ) return 1; h = (h+1) % BITVEC_NINT; } return 0; } } SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){ return p!=0 && sqlite3BitvecTestNotNull(p,i); } /* ** Set the i-th bit. Return 0 on success and an error code if ** anything goes wrong. ** ** This routine might cause sub-bitmaps to be allocated. Failing ** to get the memory needed to hold the sub-bitmap is the only ** that can go wrong with an insert, assuming p and i are valid. ** ** The calling function must ensure that p is a valid Bitvec object ** and that the value for "i" is within range of the Bitvec object. ** Otherwise the behavior is undefined. */ SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){ u32 h; if( p==0 ) return SQLITE_OK; assert( i>0 ); assert( i<=p->iSize ); i--; while((p->iSize > BITVEC_NBIT) && p->iDivisor) { u32 bin = i/p->iDivisor; i = i%p->iDivisor; if( p->u.apSub[bin]==0 ){ p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor ); if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT; } p = p->u.apSub[bin]; } if( p->iSize<=BITVEC_NBIT ){ p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1)); return SQLITE_OK; } h = BITVEC_HASH(i++); /* if there wasn't a hash collision, and this doesn't */ /* completely fill the hash, then just add it without */ /* worring about sub-dividing and re-hashing. */ if( !p->u.aHash[h] ){ if (p->nSet<(BITVEC_NINT-1)) { goto bitvec_set_end; } else { goto bitvec_set_rehash; } } /* there was a collision, check to see if it's already */ /* in hash, if not, try to find a spot for it */ do { if( p->u.aHash[h]==i ) return SQLITE_OK; h++; if( h>=BITVEC_NINT ) h = 0; } while( p->u.aHash[h] ); /* we didn't find it in the hash. h points to the first */ /* available free spot. check to see if this is going to */ /* make our hash too "full". */ bitvec_set_rehash: if( p->nSet>=BITVEC_MXHASH ){ unsigned int j; int rc; u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); if( aiValues==0 ){ return SQLITE_NOMEM_BKPT; }else{ memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); memset(p->u.apSub, 0, sizeof(p->u.apSub)); p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR; rc = sqlite3BitvecSet(p, i); for(j=0; j<BITVEC_NINT; j++){ if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]); } sqlite3StackFree(0, aiValues); return rc; } } bitvec_set_end: p->nSet++; p->u.aHash[h] = i; return SQLITE_OK; } /* ** Clear the i-th bit. ** ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage ** that BitvecClear can use to rebuilt its hash table. */ SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ if( p==0 ) return; assert( i>0 ); i--; while( p->iDivisor ){ u32 bin = i/p->iDivisor; i = i%p->iDivisor; p = p->u.apSub[bin]; if (!p) { return; } } if( p->iSize<=BITVEC_NBIT ){ p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1))); }else{ unsigned int j; u32 *aiValues = pBuf; memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); memset(p->u.aHash, 0, sizeof(p->u.aHash)); p->nSet = 0; for(j=0; j<BITVEC_NINT; j++){ if( aiValues[j] && aiValues[j]!=(i+1) ){ u32 h = BITVEC_HASH(aiValues[j]-1); p->nSet++; while( p->u.aHash[h] ){ h++; if( h>=BITVEC_NINT ) h = 0; } p->u.aHash[h] = aiValues[j]; } } } } /* ** Destroy a bitmap object. Reclaim all memory used. */ SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){ if( p==0 ) return; if( p->iDivisor ){ unsigned int i; for(i=0; i<BITVEC_NPTR; i++){ sqlite3BitvecDestroy(p->u.apSub[i]); } } sqlite3_free(p); } /* ** Return the value of the iSize parameter specified when Bitvec *p ** was created. */ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ return p->iSize; } #ifndef SQLITE_UNTESTABLE /* ** Let V[] be an array of unsigned characters sufficient to hold ** up to N bits. Let I be an integer between 0 and N. 0<=I<N. ** Then the following macros can be used to set, clear, or test ** individual bits within V. */ #define SETBIT(V,I) V[I>>3] |= (1<<(I&7)) #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 /* ** This routine runs an extensive test of the Bitvec code. ** ** The input is an array of integers that acts as a program ** to test the Bitvec. The integers are opcodes followed ** by 0, 1, or 3 operands, depending on the opcode. Another ** opcode follows immediately after the last operand. ** ** There are 6 opcodes numbered from 0 through 5. 0 is the ** "halt" opcode and causes the test to end. ** ** 0 Halt and return the number of errors ** 1 N S X Set N bits beginning with S and incrementing by X ** 2 N S X Clear N bits beginning with S and incrementing by X ** 3 N Set N randomly chosen bits ** 4 N Clear N randomly chosen bits ** 5 N S X Set N bits from S increment X in array only, not in bitvec ** ** The opcodes 1 through 4 perform set and clear operations are performed ** on both a Bitvec object and on a linear array of bits obtained from malloc. ** Opcode 5 works on the linear array only, not on the Bitvec. ** Opcode 5 is used to deliberately induce a fault in order to ** confirm that error detection works. ** ** At the conclusion of the test the linear array is compared ** against the Bitvec object. If there are any differences, ** an error is returned. If they are the same, zero is returned. ** ** If a memory allocation error occurs, return -1. */ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ Bitvec *pBitvec = 0; unsigned char *pV = 0; int rc = -1; int i, nx, pc, op; void *pTmpSpace; /* Allocate the Bitvec to be tested and a linear array of ** bits to act as the reference */ pBitvec = sqlite3BitvecCreate( sz ); pV = sqlite3MallocZero( (sz+7)/8 + 1 ); pTmpSpace = sqlite3_malloc64(BITVEC_SZ); if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end; /* NULL pBitvec tests */ sqlite3BitvecSet(0, 1); sqlite3BitvecClear(0, 1, pTmpSpace); /* Run the program */ pc = 0; while( (op = aOp[pc])!=0 ){ switch( op ){ case 1: case 2: case 5: { nx = 4; i = aOp[pc+2] - 1; aOp[pc+2] += aOp[pc+3]; break; } case 3: case 4: default: { nx = 2; sqlite3_randomness(sizeof(i), &i); break; } } if( (--aOp[pc+1]) > 0 ) nx = 0; pc += nx; i = (i & 0x7fffffff)%sz; if( (op & 1)!=0 ){ SETBIT(pV, (i+1)); if( op!=5 ){ if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end; } }else{ CLEARBIT(pV, (i+1)); sqlite3BitvecClear(pBitvec, i+1, pTmpSpace); } } /* Test to make sure the linear array exactly matches the ** Bitvec object. Start with the assumption that they do ** match (rc==0). Change rc to non-zero if a discrepancy ** is found. */ rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1) + sqlite3BitvecTest(pBitvec, 0) + (sqlite3BitvecSize(pBitvec) - sz); for(i=1; i<=sz; i++){ if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){ rc = i; break; } } /* Free allocated structure */ bitvec_end: sqlite3_free(pTmpSpace); sqlite3_free(pV); sqlite3BitvecDestroy(pBitvec); return rc; } #endif /* SQLITE_UNTESTABLE */ /************** End of bitvec.c **********************************************/ /************** Begin file pcache.c ******************************************/ /* ** 2008 August 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements that page cache. */ /* #include "sqliteInt.h" */ /* ** A complete page cache is an instance of this structure. Every ** entry in the cache holds a single page of the database file. The ** btree layer only operates on the cached copy of the database pages. ** ** A page cache entry is "clean" if it exactly matches what is currently ** on disk. A page is "dirty" if it has been modified and needs to be ** persisted to disk. ** ** pDirty, pDirtyTail, pSynced: ** All dirty pages are linked into the doubly linked list using ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order ** such that p was added to the list more recently than p->pDirtyNext. ** PCache.pDirty points to the first (newest) element in the list and ** pDirtyTail to the last (oldest). ** ** The PCache.pSynced variable is used to optimize searching for a dirty ** page to eject from the cache mid-transaction. It is better to eject ** a page that does not require a journal sync than one that does. ** Therefore, pSynced is maintained to that it *almost* always points ** to either the oldest page in the pDirty/pDirtyTail list that has a ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one ** (so that the right page to eject can be found by following pDirtyPrev ** pointers). */ struct PCache { PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */ PgHdr *pSynced; /* Last synced page in dirty page list */ int nRefSum; /* Sum of ref counts over all pages */ int szCache; /* Configured cache size */ int szSpill; /* Size before spilling occurs */ int szPage; /* Size of every page in this cache */ int szExtra; /* Size of extra space for each page */ u8 bPurgeable; /* True if pages are on backing store */ u8 eCreate; /* eCreate value for for xFetch() */ int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */ void *pStress; /* Argument to xStress */ sqlite3_pcache *pCache; /* Pluggable cache module */ }; /********************************** Test and Debug Logic **********************/ /* ** Debug tracing macros. Enable by by changing the "0" to "1" and ** recompiling. ** ** When sqlite3PcacheTrace is 1, single line trace messages are issued. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries ** is displayed for many operations, resulting in a lot of output. */ #if defined(SQLITE_DEBUG) && 0 int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */ int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */ # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;} void pcacheDump(PCache *pCache){ int N; int i, j; sqlite3_pcache_page *pLower; PgHdr *pPg; unsigned char *a; if( sqlite3PcacheTrace<2 ) return; if( pCache->pCache==0 ) return; N = sqlite3PcachePagecount(pCache); if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump; for(i=1; i<=N; i++){ pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0); if( pLower==0 ) continue; pPg = (PgHdr*)pLower->pExtra; printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags); a = (unsigned char *)pLower->pBuf; for(j=0; j<12; j++) printf("%02x", a[j]); printf("\n"); if( pPg->pPage==0 ){ sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0); } } } #else # define pcacheTrace(X) # define pcacheDump(X) #endif /* ** Check invariants on a PgHdr entry. Return true if everything is OK. ** Return false if any invariant is violated. ** ** This routine is for use inside of assert() statements only. For ** example: ** ** assert( sqlite3PcachePageSanity(pPg) ); */ #if SQLITE_DEBUG SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){ PCache *pCache; assert( pPg!=0 ); assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */ pCache = pPg->pCache; assert( pCache!=0 ); /* Every page has an associated PCache */ if( pPg->flags & PGHDR_CLEAN ){ assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */ assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */ assert( pCache->pDirtyTail!=pPg ); } /* WRITEABLE pages must also be DIRTY */ if( pPg->flags & PGHDR_WRITEABLE ){ assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */ } /* NEED_SYNC can be set independently of WRITEABLE. This can happen, ** for example, when using the sqlite3PagerDontWrite() optimization: ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK. ** (2) Page X moved to freelist, WRITEABLE is cleared ** (3) Page X reused, WRITEABLE is set again ** If NEED_SYNC had been cleared in step 2, then it would not be reset ** in step 3, and page might be written into the database without first ** syncing the rollback journal, which might cause corruption on a power ** loss. ** ** Another example is when the database page size is smaller than the ** disk sector size. When any page of a sector is journalled, all pages ** in that sector are marked NEED_SYNC even if they are still CLEAN, just ** in case they are later modified, since all pages in the same sector ** must be journalled and synced before any of those pages can be safely ** written. */ return 1; } #endif /* SQLITE_DEBUG */ /********************************** Linked List Management ********************/ /* Allowed values for second argument to pcacheManageDirtyList() */ #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */ #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */ #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */ /* ** Manage pPage's participation on the dirty list. Bits of the addRemove ** argument determines what operation to do. The 0x01 bit means first ** remove pPage from the dirty list. The 0x02 means add pPage back to ** the dirty list. Doing both moves pPage to the front of the dirty list. */ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){ PCache *p = pPage->pCache; pcacheTrace(("%p.DIRTYLIST.%s %d\n", p, addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT", pPage->pgno)); if( addRemove & PCACHE_DIRTYLIST_REMOVE ){ assert( pPage->pDirtyNext || pPage==p->pDirtyTail ); assert( pPage->pDirtyPrev || pPage==p->pDirty ); /* Update the PCache1.pSynced variable if necessary. */ if( p->pSynced==pPage ){ p->pSynced = pPage->pDirtyPrev; } if( pPage->pDirtyNext ){ pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev; }else{ assert( pPage==p->pDirtyTail ); p->pDirtyTail = pPage->pDirtyPrev; } if( pPage->pDirtyPrev ){ pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext; }else{ /* If there are now no dirty pages in the cache, set eCreate to 2. ** This is an optimization that allows sqlite3PcacheFetch() to skip ** searching for a dirty page to eject from the cache when it might ** otherwise have to. */ assert( pPage==p->pDirty ); p->pDirty = pPage->pDirtyNext; assert( p->bPurgeable || p->eCreate==2 ); if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/ assert( p->bPurgeable==0 || p->eCreate==1 ); p->eCreate = 2; } } pPage->pDirtyNext = 0; pPage->pDirtyPrev = 0; } if( addRemove & PCACHE_DIRTYLIST_ADD ){ assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage ); pPage->pDirtyNext = p->pDirty; if( pPage->pDirtyNext ){ assert( pPage->pDirtyNext->pDirtyPrev==0 ); pPage->pDirtyNext->pDirtyPrev = pPage; }else{ p->pDirtyTail = pPage; if( p->bPurgeable ){ assert( p->eCreate==2 ); p->eCreate = 1; } } p->pDirty = pPage; /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set ** pSynced to point to it. Checking the NEED_SYNC flag is an ** optimization, as if pSynced points to a page with the NEED_SYNC ** flag set sqlite3PcacheFetchStress() searches through all newer ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */ if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/ ){ p->pSynced = pPage; } } pcacheDump(p); } /* ** Wrapper around the pluggable caches xUnpin method. If the cache is ** being used for an in-memory database, this function is a no-op. */ static void pcacheUnpin(PgHdr *p){ if( p->pCache->bPurgeable ){ pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno)); sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0); pcacheDump(p->pCache); } } /* ** Compute the number of pages of cache requested. p->szCache is the ** cache size requested by the "PRAGMA cache_size" statement. */ static int numberOfCachePages(PCache *p){ if( p->szCache>=0 ){ /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the ** suggested cache size is set to N. */ return p->szCache; }else{ /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then ** the number of cache pages is adjusted to use approximately abs(N*1024) ** bytes of memory. */ return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra)); } } /*************************************************** General Interfaces ****** ** ** Initialize and shutdown the page cache subsystem. Neither of these ** functions are threadsafe. */ SQLITE_PRIVATE int sqlite3PcacheInitialize(void){ if( sqlite3GlobalConfig.pcache2.xInit==0 ){ /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the ** built-in default page cache is used instead of the application defined ** page cache. */ sqlite3PCacheSetDefault(); } return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg); } SQLITE_PRIVATE void sqlite3PcacheShutdown(void){ if( sqlite3GlobalConfig.pcache2.xShutdown ){ /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */ sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg); } } /* ** Return the size in bytes of a PCache object. */ SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); } /* ** Create a new PCache object. Storage space to hold the object ** has already been allocated and is passed in as the p pointer. ** The caller discovers how much space needs to be allocated by ** calling sqlite3PcacheSize(). ** ** szExtra is some extra space allocated for each page. The first ** 8 bytes of the extra space will be zeroed as the page is allocated, ** but remaining content will be uninitialized. Though it is opaque ** to this module, the extra space really ends up being the MemPage ** structure in the pager. */ SQLITE_PRIVATE int sqlite3PcacheOpen( int szPage, /* Size of every page */ int szExtra, /* Extra space associated with each page */ int bPurgeable, /* True if pages are on backing store */ int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */ void *pStress, /* Argument to xStress */ PCache *p /* Preallocated space for the PCache */ ){ memset(p, 0, sizeof(PCache)); p->szPage = 1; p->szExtra = szExtra; assert( szExtra>=8 ); /* First 8 bytes will be zeroed */ p->bPurgeable = bPurgeable; p->eCreate = 2; p->xStress = xStress; p->pStress = pStress; p->szCache = 100; p->szSpill = 1; pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable)); return sqlite3PcacheSetPageSize(p, szPage); } /* ** Change the page size for PCache object. The caller must ensure that there ** are no outstanding page references when this function is called. */ SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ assert( pCache->nRefSum==0 && pCache->pDirty==0 ); if( pCache->szPage ){ sqlite3_pcache *pNew; pNew = sqlite3GlobalConfig.pcache2.xCreate( szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)), pCache->bPurgeable ); if( pNew==0 ) return SQLITE_NOMEM_BKPT; sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache)); if( pCache->pCache ){ sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); } pCache->pCache = pNew; pCache->szPage = szPage; pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage)); } return SQLITE_OK; } /* ** Try to obtain a page from the cache. ** ** This routine returns a pointer to an sqlite3_pcache_page object if ** such an object is already in cache, or if a new one is created. ** This routine returns a NULL pointer if the object was not in cache ** and could not be created. ** ** The createFlags should be 0 to check for existing pages and should ** be 3 (not 1, but 3) to try to create a new page. ** ** If the createFlag is 0, then NULL is always returned if the page ** is not already in the cache. If createFlag is 1, then a new page ** is created only if that can be done without spilling dirty pages ** and without exceeding the cache size limit. ** ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly ** initialize the sqlite3_pcache_page object and convert it into a ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish() ** routines are split this way for performance reasons. When separated ** they can both (usually) operate without having to push values to ** the stack on entry and pop them back off on exit, which saves a ** lot of pushing and popping. */ SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number to obtain */ int createFlag /* If true, create page if it does not exist already */ ){ int eCreate; sqlite3_pcache_page *pRes; assert( pCache!=0 ); assert( pCache->pCache!=0 ); assert( createFlag==3 || createFlag==0 ); assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) ); /* eCreate defines what to do if the page does not exist. ** 0 Do not allocate a new page. (createFlag==0) ** 1 Allocate a new page if doing so is inexpensive. ** (createFlag==1 AND bPurgeable AND pDirty) ** 2 Allocate a new page even it doing so is difficult. ** (createFlag==1 AND !(bPurgeable AND pDirty) */ eCreate = createFlag & pCache->eCreate; assert( eCreate==0 || eCreate==1 || eCreate==2 ); assert( createFlag==0 || pCache->eCreate==eCreate ); assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) ); pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate); pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno, createFlag?" create":"",pRes)); return pRes; } /* ** If the sqlite3PcacheFetch() routine is unable to allocate a new ** page because no clean pages are available for reuse and the cache ** size limit has been reached, then this routine can be invoked to ** try harder to allocate a page. This routine might invoke the stress ** callback to spill dirty pages to the journal. It will then try to ** allocate the new page and will only fail to allocate a new page on ** an OOM error. ** ** This routine should be invoked only after sqlite3PcacheFetch() fails. */ SQLITE_PRIVATE int sqlite3PcacheFetchStress( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number to obtain */ sqlite3_pcache_page **ppPage /* Write result here */ ){ PgHdr *pPg; if( pCache->eCreate==2 ) return 0; if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){ /* Find a dirty page to write-out and recycle. First try to find a ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC ** cleared), but if that is not possible settle for any other ** unreferenced dirty page. ** ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC ** flag is currently referenced, then the following may leave pSynced ** set incorrectly (pointing to other than the LRU page with NEED_SYNC ** cleared). This is Ok, as pSynced is just an optimization. */ for(pPg=pCache->pSynced; pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); pPg=pPg->pDirtyPrev ); pCache->pSynced = pPg; if( !pPg ){ for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev); } if( pPg ){ int rc; #ifdef SQLITE_LOG_CACHE_SPILL sqlite3_log(SQLITE_FULL, "spill page %d making room for %d - cache used: %d/%d", pPg->pgno, pgno, sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache), numberOfCachePages(pCache)); #endif pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno)); rc = pCache->xStress(pCache->pStress, pPg); pcacheDump(pCache); if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){ return rc; } } } *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2); return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK; } /* ** This is a helper routine for sqlite3PcacheFetchFinish() ** ** In the uncommon case where the page being fetched has not been ** initialized, this routine is invoked to do the initialization. ** This routine is broken out into a separate function since it ** requires extra stack manipulation that can be avoided in the common ** case. */ static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number obtained */ sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ ){ PgHdr *pPgHdr; assert( pPage!=0 ); pPgHdr = (PgHdr*)pPage->pExtra; assert( pPgHdr->pPage==0 ); memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty)); pPgHdr->pPage = pPage; pPgHdr->pData = pPage->pBuf; pPgHdr->pExtra = (void *)&pPgHdr[1]; memset(pPgHdr->pExtra, 0, 8); pPgHdr->pCache = pCache; pPgHdr->pgno = pgno; pPgHdr->flags = PGHDR_CLEAN; return sqlite3PcacheFetchFinish(pCache,pgno,pPage); } /* ** This routine converts the sqlite3_pcache_page object returned by ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine ** must be called after sqlite3PcacheFetch() in order to get a usable ** result. */ SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number obtained */ sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ ){ PgHdr *pPgHdr; assert( pPage!=0 ); pPgHdr = (PgHdr *)pPage->pExtra; if( !pPgHdr->pPage ){ return pcacheFetchFinishWithInit(pCache, pgno, pPage); } pCache->nRefSum++; pPgHdr->nRef++; assert( sqlite3PcachePageSanity(pPgHdr) ); return pPgHdr; } /* ** Decrement the reference count on a page. If the page is clean and the ** reference count drops to 0, then it is made eligible for recycling. */ SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){ assert( p->nRef>0 ); p->pCache->nRefSum--; if( (--p->nRef)==0 ){ if( p->flags&PGHDR_CLEAN ){ pcacheUnpin(p); }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/ /* Move the page to the head of the dirty list. If p->pDirtyPrev==0, ** then page p is already at the head of the dirty list and the ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE ** tag above. */ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT); } } } /* ** Increase the reference count of a supplied page by 1. */ SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){ assert(p->nRef>0); assert( sqlite3PcachePageSanity(p) ); p->nRef++; p->pCache->nRefSum++; } /* ** Drop a page from the cache. There must be exactly one reference to the ** page. This function deletes that reference, so after it returns the ** page pointed to by p is invalid. */ SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){ assert( p->nRef==1 ); assert( sqlite3PcachePageSanity(p) ); if( p->flags&PGHDR_DIRTY ){ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE); } p->pCache->nRefSum--; sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1); } /* ** Make sure the page is marked as dirty. If it isn't dirty already, ** make it so. */ SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){ assert( p->nRef>0 ); assert( sqlite3PcachePageSanity(p) ); if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/ p->flags &= ~PGHDR_DONT_WRITE; if( p->flags & PGHDR_CLEAN ){ p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN); pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno)); assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY ); pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD); } assert( sqlite3PcachePageSanity(p) ); } } /* ** Make sure the page is marked as clean. If it isn't clean already, ** make it so. */ SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){ assert( sqlite3PcachePageSanity(p) ); if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){ assert( (p->flags & PGHDR_CLEAN)==0 ); pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE); p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE); p->flags |= PGHDR_CLEAN; pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno)); assert( sqlite3PcachePageSanity(p) ); if( p->nRef==0 ){ pcacheUnpin(p); } } } /* ** Make every page in the cache clean. */ SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){ PgHdr *p; pcacheTrace(("%p.CLEAN-ALL\n",pCache)); while( (p = pCache->pDirty)!=0 ){ sqlite3PcacheMakeClean(p); } } /* ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages. */ SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){ PgHdr *p; pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache)); for(p=pCache->pDirty; p; p=p->pDirtyNext){ p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE); } pCache->pSynced = pCache->pDirtyTail; } /* ** Clear the PGHDR_NEED_SYNC flag from all dirty pages. */ SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){ PgHdr *p; for(p=pCache->pDirty; p; p=p->pDirtyNext){ p->flags &= ~PGHDR_NEED_SYNC; } pCache->pSynced = pCache->pDirtyTail; } /* ** Change the page number of page p to newPgno. */ SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){ PCache *pCache = p->pCache; assert( p->nRef>0 ); assert( newPgno>0 ); assert( sqlite3PcachePageSanity(p) ); pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno)); sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno); p->pgno = newPgno; if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT); } } /* ** Drop every cache entry whose page number is greater than "pgno". The ** caller must ensure that there are no outstanding references to any pages ** other than page 1 with a page number greater than pgno. ** ** If there is a reference to page 1 and the pgno parameter passed to this ** function is 0, then the data area associated with page 1 is zeroed, but ** the page object is not dropped. */ SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){ if( pCache->pCache ){ PgHdr *p; PgHdr *pNext; pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno)); for(p=pCache->pDirty; p; p=pNext){ pNext = p->pDirtyNext; /* This routine never gets call with a positive pgno except right ** after sqlite3PcacheCleanAll(). So if there are dirty pages, ** it must be that pgno==0. */ assert( p->pgno>0 ); if( p->pgno>pgno ){ assert( p->flags&PGHDR_DIRTY ); sqlite3PcacheMakeClean(p); } } if( pgno==0 && pCache->nRefSum ){ sqlite3_pcache_page *pPage1; pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0); if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because ** pCache->nRefSum>0 */ memset(pPage1->pBuf, 0, pCache->szPage); pgno = 1; } } sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1); } } /* ** Close a cache. */ SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){ assert( pCache->pCache!=0 ); pcacheTrace(("%p.CLOSE\n",pCache)); sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); } /* ** Discard the contents of the cache. */ SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){ sqlite3PcacheTruncate(pCache, 0); } /* ** Merge two lists of pages connected by pDirty and in pgno order. ** Do not bother fixing the pDirtyPrev pointers. */ static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){ PgHdr result, *pTail; pTail = &result; assert( pA!=0 && pB!=0 ); for(;;){ if( pA->pgno<pB->pgno ){ pTail->pDirty = pA; pTail = pA; pA = pA->pDirty; if( pA==0 ){ pTail->pDirty = pB; break; } }else{ pTail->pDirty = pB; pTail = pB; pB = pB->pDirty; if( pB==0 ){ pTail->pDirty = pA; break; } } } return result.pDirty; } /* ** Sort the list of pages in accending order by pgno. Pages are ** connected by pDirty pointers. The pDirtyPrev pointers are ** corrupted by this sort. ** ** Since there cannot be more than 2^31 distinct pages in a database, ** there cannot be more than 31 buckets required by the merge sorter. ** One extra bucket is added to catch overflow in case something ** ever changes to make the previous sentence incorrect. */ #define N_SORT_BUCKET 32 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){ PgHdr *a[N_SORT_BUCKET], *p; int i; memset(a, 0, sizeof(a)); while( pIn ){ p = pIn; pIn = p->pDirty; p->pDirty = 0; for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){ if( a[i]==0 ){ a[i] = p; break; }else{ p = pcacheMergeDirtyList(a[i], p); a[i] = 0; } } if( NEVER(i==N_SORT_BUCKET-1) ){ /* To get here, there need to be 2^(N_SORT_BUCKET) elements in ** the input list. But that is impossible. */ a[i] = pcacheMergeDirtyList(a[i], p); } } p = a[0]; for(i=1; i<N_SORT_BUCKET; i++){ if( a[i]==0 ) continue; p = p ? pcacheMergeDirtyList(p, a[i]) : a[i]; } return p; } /* ** Return a list of all dirty pages in the cache, sorted by page number. */ SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){ PgHdr *p; for(p=pCache->pDirty; p; p=p->pDirtyNext){ p->pDirty = p->pDirtyNext; } return pcacheSortDirtyList(pCache->pDirty); } /* ** Return the total number of references to all pages held by the cache. ** ** This is not the total number of pages referenced, but the sum of the ** reference count for all pages. */ SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){ return pCache->nRefSum; } /* ** Return the number of references to the page supplied as an argument. */ SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){ return p->nRef; } /* ** Return the total number of pages in the cache. */ SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){ assert( pCache->pCache!=0 ); return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache); } #ifdef SQLITE_TEST /* ** Get the suggested cache-size value. */ SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){ return numberOfCachePages(pCache); } #endif /* ** Set the suggested cache-size value. */ SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){ assert( pCache->pCache!=0 ); pCache->szCache = mxPage; sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache, numberOfCachePages(pCache)); } /* ** Set the suggested cache-spill value. Make no changes if if the ** argument is zero. Return the effective cache-spill size, which will ** be the larger of the szSpill and szCache. */ SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){ int res; assert( p->pCache!=0 ); if( mxPage ){ if( mxPage<0 ){ mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra)); } p->szSpill = mxPage; } res = numberOfCachePages(p); if( res<p->szSpill ) res = p->szSpill; return res; } /* ** Free up as much memory as possible from the page cache. */ SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){ assert( pCache->pCache!=0 ); sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache); } /* ** Return the size of the header added by this middleware layer ** in the page-cache hierarchy. */ SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); } /* ** Return the number of dirty pages currently in the cache, as a percentage ** of the configured cache size. */ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){ PgHdr *pDirty; int nDirty = 0; int nCache = numberOfCachePages(pCache); for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++; return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0; } #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) /* ** For all dirty pages currently in the cache, invoke the specified ** callback. This is only used if the SQLITE_CHECK_PAGES macro is ** defined. */ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){ PgHdr *pDirty; for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){ xIter(pDirty); } } #endif /************** End of pcache.c **********************************************/ /************** Begin file pcache1.c *****************************************/ /* ** 2008 November 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements the default page cache implementation (the ** sqlite3_pcache interface). It also contains part of the implementation ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. ** If the default page cache implementation is overridden, then neither of ** these two features are available. ** ** A Page cache line looks like this: ** ** ------------------------------------------------------------- ** | database page content | PgHdr1 | MemPage | PgHdr | ** ------------------------------------------------------------- ** ** The database page content is up front (so that buffer overreads tend to ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage ** is the extension added by the btree.c module containing information such ** as the database page number and how that database page is used. PgHdr ** is added by the pcache.c layer and contains information used to keep track ** of which pages are "dirty". PgHdr1 is an extension added by this ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page. ** PgHdr1 contains information needed to look up a page by its page number. ** The superclass sqlite3_pcache_page.pBuf points to the start of the ** database page content and sqlite3_pcache_page.pExtra points to PgHdr. ** ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this ** size can vary according to architecture, compile-time options, and ** SQLite library version number. ** ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained ** using a separate memory allocation from the database page content. This ** seeks to overcome the "clownshoe" problem (also called "internal ** fragmentation" in academic literature) of allocating a few bytes more ** than a power of two with the memory allocator rounding up to the next ** power of two, and leaving the rounded-up space unused. ** ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates ** with this module. Information is passed back and forth as PgHdr1 pointers. ** ** The pcache.c and pager.c modules deal pointers to PgHdr objects. ** The btree.c module deals with pointers to MemPage objects. ** ** SOURCE OF PAGE CACHE MEMORY: ** ** Memory for a page might come from any of three sources: ** ** (1) The general-purpose memory allocator - sqlite3Malloc() ** (2) Global page-cache memory provided using sqlite3_config() with ** SQLITE_CONFIG_PAGECACHE. ** (3) PCache-local bulk allocation. ** ** The third case is a chunk of heap memory (defaulting to 100 pages worth) ** that is allocated when the page cache is created. The size of the local ** bulk allocation can be adjusted using ** ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N). ** ** If N is positive, then N pages worth of memory are allocated using a single ** sqlite3Malloc() call and that memory is used for the first N pages allocated. ** Or if N is negative, then -1024*N bytes of memory are allocated and used ** for as many pages as can be accomodated. ** ** Only one of (2) or (3) can be used. Once the memory available to (2) or ** (3) is exhausted, subsequent allocations fail over to the general-purpose ** memory allocator (1). ** ** Earlier versions of SQLite used only methods (1) and (2). But experiments ** show that method (3) with N==100 provides about a 5% performance boost for ** common workloads. */ /* #include "sqliteInt.h" */ typedef struct PCache1 PCache1; typedef struct PgHdr1 PgHdr1; typedef struct PgFreeslot PgFreeslot; typedef struct PGroup PGroup; /* ** Each cache entry is represented by an instance of the following ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of ** PgHdr1.pCache->szPage bytes is allocated directly before this structure ** in memory. */ struct PgHdr1 { sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */ unsigned int iKey; /* Key value (page number) */ u8 isPinned; /* Page in use, not on the LRU list */ u8 isBulkLocal; /* This page from bulk local storage */ u8 isAnchor; /* This is the PGroup.lru element */ PgHdr1 *pNext; /* Next in hash table chain */ PCache1 *pCache; /* Cache that currently owns this page */ PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */ PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */ }; /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set ** of one or more PCaches that are able to recycle each other's unpinned ** pages when they are under memory pressure. A PGroup is an instance of ** the following object. ** ** This page cache implementation works in one of two modes: ** ** (1) Every PCache is the sole member of its own PGroup. There is ** one PGroup per PCache. ** ** (2) There is a single global PGroup that all PCaches are a member ** of. ** ** Mode 1 uses more memory (since PCache instances are not able to rob ** unused pages from other PCaches) but it also operates without a mutex, ** and is therefore often faster. Mode 2 requires a mutex in order to be ** threadsafe, but recycles pages more efficiently. ** ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single ** PGroup which is the pcache1.grp global variable and its mutex is ** SQLITE_MUTEX_STATIC_LRU. */ struct PGroup { sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */ unsigned int nMaxPage; /* Sum of nMax for purgeable caches */ unsigned int nMinPage; /* Sum of nMin for purgeable caches */ unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */ unsigned int nCurrentPage; /* Number of purgeable pages allocated */ PgHdr1 lru; /* The beginning and end of the LRU list */ }; /* Each page cache is an instance of the following object. Every ** open database file (including each in-memory database and each ** temporary or transient database) has a single page cache which ** is an instance of this object. ** ** Pointers to structures of this type are cast and returned as ** opaque sqlite3_pcache* handles. */ struct PCache1 { /* Cache configuration parameters. Page size (szPage) and the purgeable ** flag (bPurgeable) are set when the cache is created. nMax may be ** modified at any time by a call to the pcache1Cachesize() method. ** The PGroup mutex must be held when accessing nMax. */ PGroup *pGroup; /* PGroup this cache belongs to */ int szPage; /* Size of database content section */ int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */ int szAlloc; /* Total size of one pcache line */ int bPurgeable; /* True if cache is purgeable */ unsigned int nMin; /* Minimum number of pages reserved */ unsigned int nMax; /* Configured "cache_size" value */ unsigned int n90pct; /* nMax*9/10 */ unsigned int iMaxKey; /* Largest key seen since xTruncate() */ /* Hash table of all pages. The following variables may only be accessed ** when the accessor is holding the PGroup mutex. */ unsigned int nRecyclable; /* Number of pages in the LRU list */ unsigned int nPage; /* Total number of pages in apHash */ unsigned int nHash; /* Number of slots in apHash[] */ PgHdr1 **apHash; /* Hash table for fast lookup by key */ PgHdr1 *pFree; /* List of unused pcache-local pages */ void *pBulk; /* Bulk memory used by pcache-local */ }; /* ** Free slots in the allocator used to divide up the global page cache ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism. */ struct PgFreeslot { PgFreeslot *pNext; /* Next free slot */ }; /* ** Global data used by this cache. */ static SQLITE_WSD struct PCacheGlobal { PGroup grp; /* The global PGroup for mode (2) */ /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all ** fixed at sqlite3_initialize() time and do not require mutex protection. ** The nFreeSlot and pFree values do require mutex protection. */ int isInit; /* True if initialized */ int separateCache; /* Use a new PGroup for each PCache */ int nInitPage; /* Initial bulk allocation size */ int szSlot; /* Size of each free slot */ int nSlot; /* The number of pcache slots */ int nReserve; /* Try to keep nFreeSlot above this */ void *pStart, *pEnd; /* Bounds of global page cache memory */ /* Above requires no mutex. Use mutex below for variable that follow. */ sqlite3_mutex *mutex; /* Mutex for accessing the following: */ PgFreeslot *pFree; /* Free page blocks */ int nFreeSlot; /* Number of unused pcache slots */ /* The following value requires a mutex to change. We skip the mutex on ** reading because (1) most platforms read a 32-bit integer atomically and ** (2) even if an incorrect value is read, no great harm is done since this ** is really just an optimization. */ int bUnderPressure; /* True if low on PAGECACHE memory */ } pcache1_g; /* ** All code in this file should access the global structure above via the ** alias "pcache1". This ensures that the WSD emulation is used when ** compiling for systems that do not support real WSD. */ #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g)) /* ** Macros to enter and leave the PCache LRU mutex. */ #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0 # define pcache1EnterMutex(X) assert((X)->mutex==0) # define pcache1LeaveMutex(X) assert((X)->mutex==0) # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0 #else # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex) # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex) # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1 #endif /******************************************************************************/ /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/ /* ** This function is called during initialization if a static buffer is ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE ** verb to sqlite3_config(). Parameter pBuf points to an allocation large ** enough to contain 'n' buffers of 'sz' bytes each. ** ** This routine is called from sqlite3_initialize() and so it is guaranteed ** to be serialized already. There is no need for further mutexing. */ SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){ if( pcache1.isInit ){ PgFreeslot *p; if( pBuf==0 ) sz = n = 0; sz = ROUNDDOWN8(sz); pcache1.szSlot = sz; pcache1.nSlot = pcache1.nFreeSlot = n; pcache1.nReserve = n>90 ? 10 : (n/10 + 1); pcache1.pStart = pBuf; pcache1.pFree = 0; pcache1.bUnderPressure = 0; while( n-- ){ p = (PgFreeslot*)pBuf; p->pNext = pcache1.pFree; pcache1.pFree = p; pBuf = (void*)&((char*)pBuf)[sz]; } pcache1.pEnd = pBuf; } } /* ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return ** true if pCache->pFree ends up containing one or more free pages. */ static int pcache1InitBulk(PCache1 *pCache){ i64 szBulk; char *zBulk; if( pcache1.nInitPage==0 ) return 0; /* Do not bother with a bulk allocation if the cache size very small */ if( pCache->nMax<3 ) return 0; sqlite3BeginBenignMalloc(); if( pcache1.nInitPage>0 ){ szBulk = pCache->szAlloc * (i64)pcache1.nInitPage; }else{ szBulk = -1024 * (i64)pcache1.nInitPage; } if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){ szBulk = pCache->szAlloc*(i64)pCache->nMax; } zBulk = pCache->pBulk = sqlite3Malloc( szBulk ); sqlite3EndBenignMalloc(); if( zBulk ){ int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc; int i; for(i=0; i<nBulk; i++){ PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage]; pX->page.pBuf = zBulk; pX->page.pExtra = &pX[1]; pX->isBulkLocal = 1; pX->isAnchor = 0; pX->pNext = pCache->pFree; pCache->pFree = pX; zBulk += pCache->szAlloc; } } return pCache->pFree!=0; } /* ** Malloc function used within this file to allocate space from the buffer ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no ** such buffer exists or there is no space left in it, this function falls ** back to sqlite3Malloc(). ** ** Multiple threads can run this routine at the same time. Global variables ** in pcache1 need to be protected via mutex. */ static void *pcache1Alloc(int nByte){ void *p = 0; assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); if( nByte<=pcache1.szSlot ){ sqlite3_mutex_enter(pcache1.mutex); p = (PgHdr1 *)pcache1.pFree; if( p ){ pcache1.pFree = pcache1.pFree->pNext; pcache1.nFreeSlot--; pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve; assert( pcache1.nFreeSlot>=0 ); sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1); } sqlite3_mutex_leave(pcache1.mutex); } if( p==0 ){ /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get ** it from sqlite3Malloc instead. */ p = sqlite3Malloc(nByte); #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS if( p ){ int sz = sqlite3MallocSize(p); sqlite3_mutex_enter(pcache1.mutex); sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz); sqlite3_mutex_leave(pcache1.mutex); } #endif sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); } return p; } /* ** Free an allocated buffer obtained from pcache1Alloc(). */ static void pcache1Free(void *p){ if( p==0 ) return; if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){ PgFreeslot *pSlot; sqlite3_mutex_enter(pcache1.mutex); sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1); pSlot = (PgFreeslot*)p; pSlot->pNext = pcache1.pFree; pcache1.pFree = pSlot; pcache1.nFreeSlot++; pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve; assert( pcache1.nFreeSlot<=pcache1.nSlot ); sqlite3_mutex_leave(pcache1.mutex); }else{ assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS { int nFreed = 0; nFreed = sqlite3MallocSize(p); sqlite3_mutex_enter(pcache1.mutex); sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed); sqlite3_mutex_leave(pcache1.mutex); } #endif sqlite3_free(p); } } #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* ** Return the size of a pcache allocation */ static int pcache1MemSize(void *p){ if( p>=pcache1.pStart && p<pcache1.pEnd ){ return pcache1.szSlot; }else{ int iSize; assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) ); sqlite3MemdebugSetType(p, MEMTYPE_HEAP); iSize = sqlite3MallocSize(p); sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); return iSize; } } #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */ /* ** Allocate a new page object initially associated with cache pCache. */ static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){ PgHdr1 *p = 0; void *pPg; assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){ p = pCache->pFree; pCache->pFree = p->pNext; p->pNext = 0; }else{ #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* The group mutex must be released before pcache1Alloc() is called. This ** is because it might call sqlite3_release_memory(), which assumes that ** this mutex is not held. */ assert( pcache1.separateCache==0 ); assert( pCache->pGroup==&pcache1.grp ); pcache1LeaveMutex(pCache->pGroup); #endif if( benignMalloc ){ sqlite3BeginBenignMalloc(); } #ifdef SQLITE_PCACHE_SEPARATE_HEADER pPg = pcache1Alloc(pCache->szPage); p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra); if( !pPg || !p ){ pcache1Free(pPg); sqlite3_free(p); pPg = 0; } #else pPg = pcache1Alloc(pCache->szAlloc); p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; #endif if( benignMalloc ){ sqlite3EndBenignMalloc(); } #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT pcache1EnterMutex(pCache->pGroup); #endif if( pPg==0 ) return 0; p->page.pBuf = pPg; p->page.pExtra = &p[1]; p->isBulkLocal = 0; p->isAnchor = 0; } if( pCache->bPurgeable ){ pCache->pGroup->nCurrentPage++; } return p; } /* ** Free a page object allocated by pcache1AllocPage(). */ static void pcache1FreePage(PgHdr1 *p){ PCache1 *pCache; assert( p!=0 ); pCache = p->pCache; assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) ); if( p->isBulkLocal ){ p->pNext = pCache->pFree; pCache->pFree = p; }else{ pcache1Free(p->page.pBuf); #ifdef SQLITE_PCACHE_SEPARATE_HEADER sqlite3_free(p); #endif } if( pCache->bPurgeable ){ pCache->pGroup->nCurrentPage--; } } /* ** Malloc function used by SQLite to obtain space from the buffer configured ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer ** exists, this function falls back to sqlite3Malloc(). */ SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){ return pcache1Alloc(sz); } /* ** Free an allocated buffer obtained from sqlite3PageMalloc(). */ SQLITE_PRIVATE void sqlite3PageFree(void *p){ pcache1Free(p); } /* ** Return true if it desirable to avoid allocating a new page cache ** entry. ** ** If memory was allocated specifically to the page cache using ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then ** it is desirable to avoid allocating a new page cache entry because ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient ** for all page cache needs and we should not need to spill the ** allocation onto the heap. ** ** Or, the heap is used for all page cache memory but the heap is ** under memory pressure, then again it is desirable to avoid ** allocating a new page cache entry in order to avoid stressing ** the heap even further. */ static int pcache1UnderMemoryPressure(PCache1 *pCache){ if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){ return pcache1.bUnderPressure; }else{ return sqlite3HeapNearlyFull(); } } /******************************************************************************/ /******** General Implementation Functions ************************************/ /* ** This function is used to resize the hash table used by the cache passed ** as the first argument. ** ** The PCache mutex must be held when this function is called. */ static void pcache1ResizeHash(PCache1 *p){ PgHdr1 **apNew; unsigned int nNew; unsigned int i; assert( sqlite3_mutex_held(p->pGroup->mutex) ); nNew = p->nHash*2; if( nNew<256 ){ nNew = 256; } pcache1LeaveMutex(p->pGroup); if( p->nHash ){ sqlite3BeginBenignMalloc(); } apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew); if( p->nHash ){ sqlite3EndBenignMalloc(); } pcache1EnterMutex(p->pGroup); if( apNew ){ for(i=0; i<p->nHash; i++){ PgHdr1 *pPage; PgHdr1 *pNext = p->apHash[i]; while( (pPage = pNext)!=0 ){ unsigned int h = pPage->iKey % nNew; pNext = pPage->pNext; pPage->pNext = apNew[h]; apNew[h] = pPage; } } sqlite3_free(p->apHash); p->apHash = apNew; p->nHash = nNew; } } /* ** This function is used internally to remove the page pPage from the ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup ** LRU list, then this function is a no-op. ** ** The PGroup mutex must be held when this function is called. */ static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){ PCache1 *pCache; assert( pPage!=0 ); assert( pPage->isPinned==0 ); pCache = pPage->pCache; assert( pPage->pLruNext ); assert( pPage->pLruPrev ); assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); pPage->pLruPrev->pLruNext = pPage->pLruNext; pPage->pLruNext->pLruPrev = pPage->pLruPrev; pPage->pLruNext = 0; pPage->pLruPrev = 0; pPage->isPinned = 1; assert( pPage->isAnchor==0 ); assert( pCache->pGroup->lru.isAnchor==1 ); pCache->nRecyclable--; return pPage; } /* ** Remove the page supplied as an argument from the hash table ** (PCache1.apHash structure) that it is currently stored in. ** Also free the page if freePage is true. ** ** The PGroup mutex must be held when this function is called. */ static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){ unsigned int h; PCache1 *pCache = pPage->pCache; PgHdr1 **pp; assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); h = pPage->iKey % pCache->nHash; for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext); *pp = (*pp)->pNext; pCache->nPage--; if( freeFlag ) pcache1FreePage(pPage); } /* ** If there are currently more than nMaxPage pages allocated, try ** to recycle pages to reduce the number allocated to nMaxPage. */ static void pcache1EnforceMaxPage(PCache1 *pCache){ PGroup *pGroup = pCache->pGroup; PgHdr1 *p; assert( sqlite3_mutex_held(pGroup->mutex) ); while( pGroup->nCurrentPage>pGroup->nMaxPage && (p=pGroup->lru.pLruPrev)->isAnchor==0 ){ assert( p->pCache->pGroup==pGroup ); assert( p->isPinned==0 ); pcache1PinPage(p); pcache1RemoveFromHash(p, 1); } if( pCache->nPage==0 && pCache->pBulk ){ sqlite3_free(pCache->pBulk); pCache->pBulk = pCache->pFree = 0; } } /* ** Discard all pages from cache pCache with a page number (key value) ** greater than or equal to iLimit. Any pinned pages that meet this ** criteria are unpinned before they are discarded. ** ** The PCache mutex must be held when this function is called. */ static void pcache1TruncateUnsafe( PCache1 *pCache, /* The cache to truncate */ unsigned int iLimit /* Drop pages with this pgno or larger */ ){ TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */ unsigned int h, iStop; assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); assert( pCache->iMaxKey >= iLimit ); assert( pCache->nHash > 0 ); if( pCache->iMaxKey - iLimit < pCache->nHash ){ /* If we are just shaving the last few pages off the end of the ** cache, then there is no point in scanning the entire hash table. ** Only scan those hash slots that might contain pages that need to ** be removed. */ h = iLimit % pCache->nHash; iStop = pCache->iMaxKey % pCache->nHash; TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */ }else{ /* This is the general case where many pages are being removed. ** It is necessary to scan the entire hash table */ h = pCache->nHash/2; iStop = h - 1; } for(;;){ PgHdr1 **pp; PgHdr1 *pPage; assert( h<pCache->nHash ); pp = &pCache->apHash[h]; while( (pPage = *pp)!=0 ){ if( pPage->iKey>=iLimit ){ pCache->nPage--; *pp = pPage->pNext; if( !pPage->isPinned ) pcache1PinPage(pPage); pcache1FreePage(pPage); }else{ pp = &pPage->pNext; TESTONLY( if( nPage>=0 ) nPage++; ) } } if( h==iStop ) break; h = (h+1) % pCache->nHash; } assert( nPage<0 || pCache->nPage==(unsigned)nPage ); } /******************************************************************************/ /******** sqlite3_pcache Methods **********************************************/ /* ** Implementation of the sqlite3_pcache.xInit method. */ static int pcache1Init(void *NotUsed){ UNUSED_PARAMETER(NotUsed); assert( pcache1.isInit==0 ); memset(&pcache1, 0, sizeof(pcache1)); /* ** The pcache1.separateCache variable is true if each PCache has its own ** private PGroup (mode-1). pcache1.separateCache is false if the single ** PGroup in pcache1.grp is used for all page caches (mode-2). ** ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT ** ** * Use a unified cache in single-threaded applications that have ** configured a start-time buffer for use as page-cache memory using ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL ** pBuf argument. ** ** * Otherwise use separate caches (mode-1) */ #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) pcache1.separateCache = 0; #elif SQLITE_THREADSAFE pcache1.separateCache = sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.bCoreMutex>0; #else pcache1.separateCache = sqlite3GlobalConfig.pPage==0; #endif #if SQLITE_THREADSAFE if( sqlite3GlobalConfig.bCoreMutex ){ pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU); pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM); } #endif if( pcache1.separateCache && sqlite3GlobalConfig.nPage!=0 && sqlite3GlobalConfig.pPage==0 ){ pcache1.nInitPage = sqlite3GlobalConfig.nPage; }else{ pcache1.nInitPage = 0; } pcache1.grp.mxPinned = 10; pcache1.isInit = 1; return SQLITE_OK; } /* ** Implementation of the sqlite3_pcache.xShutdown method. ** Note that the static mutex allocated in xInit does ** not need to be freed. */ static void pcache1Shutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); assert( pcache1.isInit!=0 ); memset(&pcache1, 0, sizeof(pcache1)); } /* forward declaration */ static void pcache1Destroy(sqlite3_pcache *p); /* ** Implementation of the sqlite3_pcache.xCreate method. ** ** Allocate a new cache. */ static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ PCache1 *pCache; /* The newly created page cache */ PGroup *pGroup; /* The group the new page cache will belong to */ int sz; /* Bytes of memory required to allocate the new cache */ assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 ); assert( szExtra < 300 ); sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache; pCache = (PCache1 *)sqlite3MallocZero(sz); if( pCache ){ if( pcache1.separateCache ){ pGroup = (PGroup*)&pCache[1]; pGroup->mxPinned = 10; }else{ pGroup = &pcache1.grp; } if( pGroup->lru.isAnchor==0 ){ pGroup->lru.isAnchor = 1; pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru; } pCache->pGroup = pGroup; pCache->szPage = szPage; pCache->szExtra = szExtra; pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1)); pCache->bPurgeable = (bPurgeable ? 1 : 0); pcache1EnterMutex(pGroup); pcache1ResizeHash(pCache); if( bPurgeable ){ pCache->nMin = 10; pGroup->nMinPage += pCache->nMin; pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; } pcache1LeaveMutex(pGroup); if( pCache->nHash==0 ){ pcache1Destroy((sqlite3_pcache*)pCache); pCache = 0; } } return (sqlite3_pcache *)pCache; } /* ** Implementation of the sqlite3_pcache.xCachesize method. ** ** Configure the cache_size limit for a cache. */ static void pcache1Cachesize(sqlite3_pcache *p, int nMax){ PCache1 *pCache = (PCache1 *)p; if( pCache->bPurgeable ){ PGroup *pGroup = pCache->pGroup; pcache1EnterMutex(pGroup); pGroup->nMaxPage += (nMax - pCache->nMax); pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; pCache->nMax = nMax; pCache->n90pct = pCache->nMax*9/10; pcache1EnforceMaxPage(pCache); pcache1LeaveMutex(pGroup); } } /* ** Implementation of the sqlite3_pcache.xShrink method. ** ** Free up as much memory as possible. */ static void pcache1Shrink(sqlite3_pcache *p){ PCache1 *pCache = (PCache1*)p; if( pCache->bPurgeable ){ PGroup *pGroup = pCache->pGroup; int savedMaxPage; pcache1EnterMutex(pGroup); savedMaxPage = pGroup->nMaxPage; pGroup->nMaxPage = 0; pcache1EnforceMaxPage(pCache); pGroup->nMaxPage = savedMaxPage; pcache1LeaveMutex(pGroup); } } /* ** Implementation of the sqlite3_pcache.xPagecount method. */ static int pcache1Pagecount(sqlite3_pcache *p){ int n; PCache1 *pCache = (PCache1*)p; pcache1EnterMutex(pCache->pGroup); n = pCache->nPage; pcache1LeaveMutex(pCache->pGroup); return n; } /* ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described ** in the header of the pcache1Fetch() procedure. ** ** This steps are broken out into a separate procedure because they are ** usually not needed, and by avoiding the stack initialization required ** for these steps, the main pcache1Fetch() procedure can run faster. */ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( PCache1 *pCache, unsigned int iKey, int createFlag ){ unsigned int nPinned; PGroup *pGroup = pCache->pGroup; PgHdr1 *pPage = 0; /* Step 3: Abort if createFlag is 1 but the cache is nearly full */ assert( pCache->nPage >= pCache->nRecyclable ); nPinned = pCache->nPage - pCache->nRecyclable; assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage ); assert( pCache->n90pct == pCache->nMax*9/10 ); if( createFlag==1 && ( nPinned>=pGroup->mxPinned || nPinned>=pCache->n90pct || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned) )){ return 0; } if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache); assert( pCache->nHash>0 && pCache->apHash ); /* Step 4. Try to recycle a page. */ if( pCache->bPurgeable && !pGroup->lru.pLruPrev->isAnchor && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache)) ){ PCache1 *pOther; pPage = pGroup->lru.pLruPrev; assert( pPage->isPinned==0 ); pcache1RemoveFromHash(pPage, 0); pcache1PinPage(pPage); pOther = pPage->pCache; if( pOther->szAlloc != pCache->szAlloc ){ pcache1FreePage(pPage); pPage = 0; }else{ pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable); } } /* Step 5. If a usable page buffer has still not been found, ** attempt to allocate a new one. */ if( !pPage ){ pPage = pcache1AllocPage(pCache, createFlag==1); } if( pPage ){ unsigned int h = iKey % pCache->nHash; pCache->nPage++; pPage->iKey = iKey; pPage->pNext = pCache->apHash[h]; pPage->pCache = pCache; pPage->pLruPrev = 0; pPage->pLruNext = 0; pPage->isPinned = 1; *(void **)pPage->page.pExtra = 0; pCache->apHash[h] = pPage; if( iKey>pCache->iMaxKey ){ pCache->iMaxKey = iKey; } } return pPage; } /* ** Implementation of the sqlite3_pcache.xFetch method. ** ** Fetch a page by key value. ** ** Whether or not a new page may be allocated by this function depends on ** the value of the createFlag argument. 0 means do not allocate a new ** page. 1 means allocate a new page if space is easily available. 2 ** means to try really hard to allocate a new page. ** ** For a non-purgeable cache (a cache used as the storage for an in-memory ** database) there is really no difference between createFlag 1 and 2. So ** the calling function (pcache.c) will never have a createFlag of 1 on ** a non-purgeable cache. ** ** There are three different approaches to obtaining space for a page, ** depending on the value of parameter createFlag (which may be 0, 1 or 2). ** ** 1. Regardless of the value of createFlag, the cache is searched for a ** copy of the requested page. If one is found, it is returned. ** ** 2. If createFlag==0 and the page is not already in the cache, NULL is ** returned. ** ** 3. If createFlag is 1, and the page is not already in the cache, then ** return NULL (do not allocate a new page) if any of the following ** conditions are true: ** ** (a) the number of pages pinned by the cache is greater than ** PCache1.nMax, or ** ** (b) the number of pages pinned by the cache is greater than ** the sum of nMax for all purgeable caches, less the sum of ** nMin for all other purgeable caches, or ** ** 4. If none of the first three conditions apply and the cache is marked ** as purgeable, and if one of the following is true: ** ** (a) The number of pages allocated for the cache is already ** PCache1.nMax, or ** ** (b) The number of pages allocated for all purgeable caches is ** already equal to or greater than the sum of nMax for all ** purgeable caches, ** ** (c) The system is under memory pressure and wants to avoid ** unnecessary pages cache entry allocations ** ** then attempt to recycle a page from the LRU list. If it is the right ** size, return the recycled buffer. Otherwise, free the buffer and ** proceed to step 5. ** ** 5. Otherwise, allocate and return a new page buffer. ** ** There are two versions of this routine. pcache1FetchWithMutex() is ** the general case. pcache1FetchNoMutex() is a faster implementation for ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper ** invokes the appropriate routine. */ static PgHdr1 *pcache1FetchNoMutex( sqlite3_pcache *p, unsigned int iKey, int createFlag ){ PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage = 0; /* Step 1: Search the hash table for an existing entry. */ pPage = pCache->apHash[iKey % pCache->nHash]; while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; } /* Step 2: If the page was found in the hash table, then return it. ** If the page was not in the hash table and createFlag is 0, abort. ** Otherwise (page not in hash and createFlag!=0) continue with ** subsequent steps to try to create the page. */ if( pPage ){ if( !pPage->isPinned ){ return pcache1PinPage(pPage); }else{ return pPage; } }else if( createFlag ){ /* Steps 3, 4, and 5 implemented by this subroutine */ return pcache1FetchStage2(pCache, iKey, createFlag); }else{ return 0; } } #if PCACHE1_MIGHT_USE_GROUP_MUTEX static PgHdr1 *pcache1FetchWithMutex( sqlite3_pcache *p, unsigned int iKey, int createFlag ){ PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage; pcache1EnterMutex(pCache->pGroup); pPage = pcache1FetchNoMutex(p, iKey, createFlag); assert( pPage==0 || pCache->iMaxKey>=iKey ); pcache1LeaveMutex(pCache->pGroup); return pPage; } #endif static sqlite3_pcache_page *pcache1Fetch( sqlite3_pcache *p, unsigned int iKey, int createFlag ){ #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG) PCache1 *pCache = (PCache1 *)p; #endif assert( offsetof(PgHdr1,page)==0 ); assert( pCache->bPurgeable || createFlag!=1 ); assert( pCache->bPurgeable || pCache->nMin==0 ); assert( pCache->bPurgeable==0 || pCache->nMin==10 ); assert( pCache->nMin==0 || pCache->bPurgeable ); assert( pCache->nHash>0 ); #if PCACHE1_MIGHT_USE_GROUP_MUTEX if( pCache->pGroup->mutex ){ return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag); }else #endif { return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag); } } /* ** Implementation of the sqlite3_pcache.xUnpin method. ** ** Mark a page as unpinned (eligible for asynchronous recycling). */ static void pcache1Unpin( sqlite3_pcache *p, sqlite3_pcache_page *pPg, int reuseUnlikely ){ PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage = (PgHdr1 *)pPg; PGroup *pGroup = pCache->pGroup; assert( pPage->pCache==pCache ); pcache1EnterMutex(pGroup); /* It is an error to call this function if the page is already ** part of the PGroup LRU list. */ assert( pPage->pLruPrev==0 && pPage->pLruNext==0 ); assert( pPage->isPinned==1 ); if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){ pcache1RemoveFromHash(pPage, 1); }else{ /* Add the page to the PGroup LRU list. */ PgHdr1 **ppFirst = &pGroup->lru.pLruNext; pPage->pLruPrev = &pGroup->lru; (pPage->pLruNext = *ppFirst)->pLruPrev = pPage; *ppFirst = pPage; pCache->nRecyclable++; pPage->isPinned = 0; } pcache1LeaveMutex(pCache->pGroup); } /* ** Implementation of the sqlite3_pcache.xRekey method. */ static void pcache1Rekey( sqlite3_pcache *p, sqlite3_pcache_page *pPg, unsigned int iOld, unsigned int iNew ){ PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage = (PgHdr1 *)pPg; PgHdr1 **pp; unsigned int h; assert( pPage->iKey==iOld ); assert( pPage->pCache==pCache ); pcache1EnterMutex(pCache->pGroup); h = iOld%pCache->nHash; pp = &pCache->apHash[h]; while( (*pp)!=pPage ){ pp = &(*pp)->pNext; } *pp = pPage->pNext; h = iNew%pCache->nHash; pPage->iKey = iNew; pPage->pNext = pCache->apHash[h]; pCache->apHash[h] = pPage; if( iNew>pCache->iMaxKey ){ pCache->iMaxKey = iNew; } pcache1LeaveMutex(pCache->pGroup); } /* ** Implementation of the sqlite3_pcache.xTruncate method. ** ** Discard all unpinned pages in the cache with a page number equal to ** or greater than parameter iLimit. Any pinned pages with a page number ** equal to or greater than iLimit are implicitly unpinned. */ static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){ PCache1 *pCache = (PCache1 *)p; pcache1EnterMutex(pCache->pGroup); if( iLimit<=pCache->iMaxKey ){ pcache1TruncateUnsafe(pCache, iLimit); pCache->iMaxKey = iLimit-1; } pcache1LeaveMutex(pCache->pGroup); } /* ** Implementation of the sqlite3_pcache.xDestroy method. ** ** Destroy a cache allocated using pcache1Create(). */ static void pcache1Destroy(sqlite3_pcache *p){ PCache1 *pCache = (PCache1 *)p; PGroup *pGroup = pCache->pGroup; assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) ); pcache1EnterMutex(pGroup); if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0); assert( pGroup->nMaxPage >= pCache->nMax ); pGroup->nMaxPage -= pCache->nMax; assert( pGroup->nMinPage >= pCache->nMin ); pGroup->nMinPage -= pCache->nMin; pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; pcache1EnforceMaxPage(pCache); pcache1LeaveMutex(pGroup); sqlite3_free(pCache->pBulk); sqlite3_free(pCache->apHash); sqlite3_free(pCache); } /* ** This function is called during initialization (sqlite3_initialize()) to ** install the default pluggable cache module, assuming the user has not ** already provided an alternative. */ SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){ static const sqlite3_pcache_methods2 defaultMethods = { 1, /* iVersion */ 0, /* pArg */ pcache1Init, /* xInit */ pcache1Shutdown, /* xShutdown */ pcache1Create, /* xCreate */ pcache1Cachesize, /* xCachesize */ pcache1Pagecount, /* xPagecount */ pcache1Fetch, /* xFetch */ pcache1Unpin, /* xUnpin */ pcache1Rekey, /* xRekey */ pcache1Truncate, /* xTruncate */ pcache1Destroy, /* xDestroy */ pcache1Shrink /* xShrink */ }; sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods); } /* ** Return the size of the header on each page of this PCACHE implementation. */ SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); } /* ** Return the global mutex used by this PCACHE implementation. The ** sqlite3_status() routine needs access to this mutex. */ SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){ return pcache1.mutex; } #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* ** This function is called to free superfluous dynamically allocated memory ** held by the pager system. Memory in use by any SQLite pager allocated ** by the current thread may be sqlite3_free()ed. ** ** nReq is the number of bytes of memory required. Once this much has ** been released, the function returns. The return value is the total number ** of bytes of memory released. */ SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){ int nFree = 0; assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); assert( sqlite3_mutex_notheld(pcache1.mutex) ); if( sqlite3GlobalConfig.nPage==0 ){ PgHdr1 *p; pcache1EnterMutex(&pcache1.grp); while( (nReq<0 || nFree<nReq) && (p=pcache1.grp.lru.pLruPrev)!=0 && p->isAnchor==0 ){ nFree += pcache1MemSize(p->page.pBuf); #ifdef SQLITE_PCACHE_SEPARATE_HEADER nFree += sqlite3MemSize(p); #endif assert( p->isPinned==0 ); pcache1PinPage(p); pcache1RemoveFromHash(p, 1); } pcache1LeaveMutex(&pcache1.grp); } return nFree; } #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */ #ifdef SQLITE_TEST /* ** This function is used by test procedures to inspect the internal state ** of the global cache. */ SQLITE_PRIVATE void sqlite3PcacheStats( int *pnCurrent, /* OUT: Total number of pages cached */ int *pnMax, /* OUT: Global maximum cache size */ int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */ int *pnRecyclable /* OUT: Total number of pages available for recycling */ ){ PgHdr1 *p; int nRecyclable = 0; for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){ assert( p->isPinned==0 ); nRecyclable++; } *pnCurrent = pcache1.grp.nCurrentPage; *pnMax = (int)pcache1.grp.nMaxPage; *pnMin = (int)pcache1.grp.nMinPage; *pnRecyclable = nRecyclable; } #endif /************** End of pcache1.c *********************************************/ /************** Begin file rowset.c ******************************************/ /* ** 2008 December 3 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This module implements an object we call a "RowSet". ** ** The RowSet object is a collection of rowids. Rowids ** are inserted into the RowSet in an arbitrary order. Inserts ** can be intermixed with tests to see if a given rowid has been ** previously inserted into the RowSet. ** ** After all inserts are finished, it is possible to extract the ** elements of the RowSet in sorted order. Once this extraction ** process has started, no new elements may be inserted. ** ** Hence, the primitive operations for a RowSet are: ** ** CREATE ** INSERT ** TEST ** SMALLEST ** DESTROY ** ** The CREATE and DESTROY primitives are the constructor and destructor, ** obviously. The INSERT primitive adds a new element to the RowSet. ** TEST checks to see if an element is already in the RowSet. SMALLEST ** extracts the least value from the RowSet. ** ** The INSERT primitive might allocate additional memory. Memory is ** allocated in chunks so most INSERTs do no allocation. There is an ** upper bound on the size of allocated memory. No memory is freed ** until DESTROY. ** ** The TEST primitive includes a "batch" number. The TEST primitive ** will only see elements that were inserted before the last change ** in the batch number. In other words, if an INSERT occurs between ** two TESTs where the TESTs have the same batch nubmer, then the ** value added by the INSERT will not be visible to the second TEST. ** The initial batch number is zero, so if the very first TEST contains ** a non-zero batch number, it will see all prior INSERTs. ** ** No INSERTs may occurs after a SMALLEST. An assertion will fail if ** that is attempted. ** ** The cost of an INSERT is roughly constant. (Sometimes new memory ** has to be allocated on an INSERT.) The cost of a TEST with a new ** batch number is O(NlogN) where N is the number of elements in the RowSet. ** The cost of a TEST using the same batch number is O(logN). The cost ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST ** primitives are constant time. The cost of DESTROY is O(N). ** ** TEST and SMALLEST may not be used by the same RowSet. This used to ** be possible, but the feature was not used, so it was removed in order ** to simplify the code. */ /* #include "sqliteInt.h" */ /* ** Target size for allocation chunks. */ #define ROWSET_ALLOCATION_SIZE 1024 /* ** The number of rowset entries per allocation chunk. */ #define ROWSET_ENTRY_PER_CHUNK \ ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry)) /* ** Each entry in a RowSet is an instance of the following object. ** ** This same object is reused to store a linked list of trees of RowSetEntry ** objects. In that alternative use, pRight points to the next entry ** in the list, pLeft points to the tree, and v is unused. The ** RowSet.pForest value points to the head of this forest list. */ struct RowSetEntry { i64 v; /* ROWID value for this entry */ struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */ struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */ }; /* ** RowSetEntry objects are allocated in large chunks (instances of the ** following structure) to reduce memory allocation overhead. The ** chunks are kept on a linked list so that they can be deallocated ** when the RowSet is destroyed. */ struct RowSetChunk { struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */ struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */ }; /* ** A RowSet in an instance of the following structure. ** ** A typedef of this structure if found in sqliteInt.h. */ struct RowSet { struct RowSetChunk *pChunk; /* List of all chunk allocations */ sqlite3 *db; /* The database connection */ struct RowSetEntry *pEntry; /* List of entries using pRight */ struct RowSetEntry *pLast; /* Last entry on the pEntry list */ struct RowSetEntry *pFresh; /* Source of new entry objects */ struct RowSetEntry *pForest; /* List of binary trees of entries */ u16 nFresh; /* Number of objects on pFresh */ u16 rsFlags; /* Various flags */ int iBatch; /* Current insert batch */ }; /* ** Allowed values for RowSet.rsFlags */ #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */ #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */ /* ** Turn bulk memory into a RowSet object. N bytes of memory ** are available at pSpace. The db pointer is used as a memory context ** for any subsequent allocations that need to occur. ** Return a pointer to the new RowSet object. ** ** It must be the case that N is sufficient to make a Rowset. If not ** an assertion fault occurs. ** ** If N is larger than the minimum, use the surplus as an initial ** allocation of entries available to be filled. */ SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){ RowSet *p; assert( N >= ROUND8(sizeof(*p)) ); p = pSpace; p->pChunk = 0; p->db = db; p->pEntry = 0; p->pLast = 0; p->pForest = 0; p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); p->rsFlags = ROWSET_SORTED; p->iBatch = 0; return p; } /* ** Deallocate all chunks from a RowSet. This frees all memory that ** the RowSet has allocated over its lifetime. This routine is ** the destructor for the RowSet. */ SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){ struct RowSetChunk *pChunk, *pNextChunk; for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){ pNextChunk = pChunk->pNextChunk; sqlite3DbFree(p->db, pChunk); } p->pChunk = 0; p->nFresh = 0; p->pEntry = 0; p->pLast = 0; p->pForest = 0; p->rsFlags = ROWSET_SORTED; } /* ** Allocate a new RowSetEntry object that is associated with the ** given RowSet. Return a pointer to the new and completely uninitialized ** objected. ** ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this ** routine returns NULL. */ static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ assert( p!=0 ); if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/ /* We could allocate a fresh RowSetEntry each time one is needed, but it ** is more efficient to pull a preallocated entry from the pool */ struct RowSetChunk *pNew; pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew)); if( pNew==0 ){ return 0; } pNew->pNextChunk = p->pChunk; p->pChunk = pNew; p->pFresh = pNew->aEntry; p->nFresh = ROWSET_ENTRY_PER_CHUNK; } p->nFresh--; return p->pFresh++; } /* ** Insert a new value into a RowSet. ** ** The mallocFailed flag of the database connection is set if a ** memory allocation fails. */ SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){ struct RowSetEntry *pEntry; /* The new entry */ struct RowSetEntry *pLast; /* The last prior entry */ /* This routine is never called after sqlite3RowSetNext() */ assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); pEntry = rowSetEntryAlloc(p); if( pEntry==0 ) return; pEntry->v = rowid; pEntry->pRight = 0; pLast = p->pLast; if( pLast ){ if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/ /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags ** where possible */ p->rsFlags &= ~ROWSET_SORTED; } pLast->pRight = pEntry; }else{ p->pEntry = pEntry; } p->pLast = pEntry; } /* ** Merge two lists of RowSetEntry objects. Remove duplicates. ** ** The input lists are connected via pRight pointers and are ** assumed to each already be in sorted order. */ static struct RowSetEntry *rowSetEntryMerge( struct RowSetEntry *pA, /* First sorted list to be merged */ struct RowSetEntry *pB /* Second sorted list to be merged */ ){ struct RowSetEntry head; struct RowSetEntry *pTail; pTail = &head; assert( pA!=0 && pB!=0 ); for(;;){ assert( pA->pRight==0 || pA->v<=pA->pRight->v ); assert( pB->pRight==0 || pB->v<=pB->pRight->v ); if( pA->v<=pB->v ){ if( pA->v<pB->v ) pTail = pTail->pRight = pA; pA = pA->pRight; if( pA==0 ){ pTail->pRight = pB; break; } }else{ pTail = pTail->pRight = pB; pB = pB->pRight; if( pB==0 ){ pTail->pRight = pA; break; } } } return head.pRight; } /* ** Sort all elements on the list of RowSetEntry objects into order of ** increasing v. */ static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){ unsigned int i; struct RowSetEntry *pNext, *aBucket[40]; memset(aBucket, 0, sizeof(aBucket)); while( pIn ){ pNext = pIn->pRight; pIn->pRight = 0; for(i=0; aBucket[i]; i++){ pIn = rowSetEntryMerge(aBucket[i], pIn); aBucket[i] = 0; } aBucket[i] = pIn; pIn = pNext; } pIn = aBucket[0]; for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){ if( aBucket[i]==0 ) continue; pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i]; } return pIn; } /* ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects. ** Convert this tree into a linked list connected by the pRight pointers ** and return pointers to the first and last elements of the new list. */ static void rowSetTreeToList( struct RowSetEntry *pIn, /* Root of the input tree */ struct RowSetEntry **ppFirst, /* Write head of the output list here */ struct RowSetEntry **ppLast /* Write tail of the output list here */ ){ assert( pIn!=0 ); if( pIn->pLeft ){ struct RowSetEntry *p; rowSetTreeToList(pIn->pLeft, ppFirst, &p); p->pRight = pIn; }else{ *ppFirst = pIn; } if( pIn->pRight ){ rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast); }else{ *ppLast = pIn; } assert( (*ppLast)->pRight==0 ); } /* ** Convert a sorted list of elements (connected by pRight) into a binary ** tree with depth of iDepth. A depth of 1 means the tree contains a single ** node taken from the head of *ppList. A depth of 2 means a tree with ** three nodes. And so forth. ** ** Use as many entries from the input list as required and update the ** *ppList to point to the unused elements of the list. If the input ** list contains too few elements, then construct an incomplete tree ** and leave *ppList set to NULL. ** ** Return a pointer to the root of the constructed binary tree. */ static struct RowSetEntry *rowSetNDeepTree( struct RowSetEntry **ppList, int iDepth ){ struct RowSetEntry *p; /* Root of the new tree */ struct RowSetEntry *pLeft; /* Left subtree */ if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/ /* Prevent unnecessary deep recursion when we run out of entries */ return 0; } if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/ /* This branch causes a *balanced* tree to be generated. A valid tree ** is still generated without this branch, but the tree is wildly ** unbalanced and inefficient. */ pLeft = rowSetNDeepTree(ppList, iDepth-1); p = *ppList; if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/ /* It is safe to always return here, but the resulting tree ** would be unbalanced */ return pLeft; } p->pLeft = pLeft; *ppList = p->pRight; p->pRight = rowSetNDeepTree(ppList, iDepth-1); }else{ p = *ppList; *ppList = p->pRight; p->pLeft = p->pRight = 0; } return p; } /* ** Convert a sorted list of elements into a binary tree. Make the tree ** as deep as it needs to be in order to contain the entire list. */ static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){ int iDepth; /* Depth of the tree so far */ struct RowSetEntry *p; /* Current tree root */ struct RowSetEntry *pLeft; /* Left subtree */ assert( pList!=0 ); p = pList; pList = p->pRight; p->pLeft = p->pRight = 0; for(iDepth=1; pList; iDepth++){ pLeft = p; p = pList; pList = p->pRight; p->pLeft = pLeft; p->pRight = rowSetNDeepTree(&pList, iDepth); } return p; } /* ** Extract the smallest element from the RowSet. ** Write the element into *pRowid. Return 1 on success. Return ** 0 if the RowSet is already empty. ** ** After this routine has been called, the sqlite3RowSetInsert() ** routine may not be called again. ** ** This routine may not be called after sqlite3RowSetTest() has ** been used. Older versions of RowSet allowed that, but as the ** capability was not used by the code generator, it was removed ** for code economy. */ SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ assert( p!=0 ); assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */ /* Merge the forest into a single sorted list on first call */ if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/ if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/ p->pEntry = rowSetEntrySort(p->pEntry); } p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT; } /* Return the next entry on the list */ if( p->pEntry ){ *pRowid = p->pEntry->v; p->pEntry = p->pEntry->pRight; if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/ /* Free memory immediately, rather than waiting on sqlite3_finalize() */ sqlite3RowSetClear(p); } return 1; }else{ return 0; } } /* ** Check to see if element iRowid was inserted into the rowset as ** part of any insert batch prior to iBatch. Return 1 or 0. ** ** If this is the first test of a new batch and if there exist entries ** on pRowSet->pEntry, then sort those entries into the forest at ** pRowSet->pForest so that they can be tested. */ SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){ struct RowSetEntry *p, *pTree; /* This routine is never called after sqlite3RowSetNext() */ assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 ); /* Sort entries into the forest on the first test of a new batch. ** To save unnecessary work, only do this when the batch number changes. */ if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/ p = pRowSet->pEntry; if( p ){ struct RowSetEntry **ppPrevTree = &pRowSet->pForest; if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/ /* Only sort the current set of entiries if they need it */ p = rowSetEntrySort(p); } for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ ppPrevTree = &pTree->pRight; if( pTree->pLeft==0 ){ pTree->pLeft = rowSetListToTree(p); break; }else{ struct RowSetEntry *pAux, *pTail; rowSetTreeToList(pTree->pLeft, &pAux, &pTail); pTree->pLeft = 0; p = rowSetEntryMerge(pAux, p); } } if( pTree==0 ){ *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet); if( pTree ){ pTree->v = 0; pTree->pRight = 0; pTree->pLeft = rowSetListToTree(p); } } pRowSet->pEntry = 0; pRowSet->pLast = 0; pRowSet->rsFlags |= ROWSET_SORTED; } pRowSet->iBatch = iBatch; } /* Test to see if the iRowid value appears anywhere in the forest. ** Return 1 if it does and 0 if not. */ for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ p = pTree->pLeft; while( p ){ if( p->v<iRowid ){ p = p->pRight; }else if( p->v>iRowid ){ p = p->pLeft; }else{ return 1; } } } return 0; } /************** End of rowset.c **********************************************/ /************** Begin file pager.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of the page cache subsystem or "pager". ** ** The pager is used to access a database disk file. It implements ** atomic commit and rollback through the use of a journal file that ** is separate from the database file. The pager also implements file ** locking to prevent two processes from writing the same database ** file simultaneously, or one process from reading the database while ** another is writing. */ #ifndef SQLITE_OMIT_DISKIO /* #include "sqliteInt.h" */ /************** Include wal.h in the middle of pager.c ***********************/ /************** Begin file wal.h *********************************************/ /* ** 2010 February 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface to the write-ahead logging ** system. Refer to the comments below and the header comment attached to ** the implementation of each function in log.c for further details. */ #ifndef SQLITE_WAL_H #define SQLITE_WAL_H /* #include "sqliteInt.h" */ /* Additional values that can be added to the sync_flags argument of ** sqlite3WalFrames(): */ #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */ #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */ #ifdef SQLITE_OMIT_WAL # define sqlite3WalOpen(x,y,z) 0 # define sqlite3WalLimit(x,y) # define sqlite3WalClose(v,w,x,y,z) 0 # define sqlite3WalBeginReadTransaction(y,z) 0 # define sqlite3WalEndReadTransaction(z) # define sqlite3WalDbsize(y) 0 # define sqlite3WalBeginWriteTransaction(y) 0 # define sqlite3WalEndWriteTransaction(x) 0 # define sqlite3WalUndo(x,y,z) 0 # define sqlite3WalSavepoint(y,z) # define sqlite3WalSavepointUndo(y,z) 0 # define sqlite3WalFrames(u,v,w,x,y,z) 0 # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0 # define sqlite3WalCallback(z) 0 # define sqlite3WalExclusiveMode(y,z) 0 # define sqlite3WalHeapMemory(z) 0 # define sqlite3WalFramesize(z) 0 # define sqlite3WalFindFrame(x,y,z) 0 # define sqlite3WalFile(x) 0 #else #define WAL_SAVEPOINT_NDATA 4 /* Connection to a write-ahead log (WAL) file. ** There is one object of this type for each pager. */ typedef struct Wal Wal; /* Open and close a connection to a write-ahead log. */ SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**); SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *); /* Set the limiting size of a WAL file. */ SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64); /* Used by readers to open (lock) and close (unlock) a snapshot. A ** snapshot is like a read-transaction. It is the state of the database ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and ** preserves the current state even if the other threads or processes ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the ** transaction and releases the lock. */ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *); SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal); /* Read a page from the write-ahead log, if it is present. */ SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *); SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *); /* If the WAL is not empty, return the size of the database. */ SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal); /* Obtain or release the WRITER lock. */ SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal); SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal); /* Undo any frames written (but not committed) to the log */ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx); /* Return an integer that records the current (uncommitted) write ** position in the WAL */ SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData); /* Move the write position of the WAL back to iFrame. Called in ** response to a ROLLBACK TO command. */ SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData); /* Write a frame or frames to the log. */ SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int); /* Copy pages from the log to the database file */ SQLITE_PRIVATE int sqlite3WalCheckpoint( Wal *pWal, /* Write-ahead log connection */ sqlite3 *db, /* Check this handle's interrupt flag */ int eMode, /* One of PASSIVE, FULL and RESTART */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ int sync_flags, /* Flags to sync db file with (or 0) */ int nBuf, /* Size of buffer nBuf */ u8 *zBuf, /* Temporary buffer to use */ int *pnLog, /* OUT: Number of frames in WAL */ int *pnCkpt /* OUT: Number of backfilled frames in WAL */ ); /* Return the value to pass to a sqlite3_wal_hook callback, the ** number of frames in the WAL at the point of the last commit since ** sqlite3WalCallback() was called. If no commits have occurred since ** the last call, then return 0. */ SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal); /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released) ** by the pager layer on the database file. */ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op); /* Return true if the argument is non-NULL and the WAL module is using ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the ** WAL module is using shared-memory, return false. */ SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal); #ifdef SQLITE_ENABLE_SNAPSHOT SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot); SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot); SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal); #endif #ifdef SQLITE_ENABLE_ZIPVFS /* If the WAL file is not empty, return the number of bytes of content ** stored in each frame (i.e. the db page-size when the WAL was created). */ SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal); #endif /* Return the sqlite3_file object for the WAL file */ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal); #endif /* ifndef SQLITE_OMIT_WAL */ #endif /* SQLITE_WAL_H */ /************** End of wal.h *************************************************/ /************** Continuing where we left off in pager.c **********************/ /******************* NOTES ON THE DESIGN OF THE PAGER ************************ ** ** This comment block describes invariants that hold when using a rollback ** journal. These invariants do not apply for journal_mode=WAL, ** journal_mode=MEMORY, or journal_mode=OFF. ** ** Within this comment block, a page is deemed to have been synced ** automatically as soon as it is written when PRAGMA synchronous=OFF. ** Otherwise, the page is not synced until the xSync method of the VFS ** is called successfully on the file containing the page. ** ** Definition: A page of the database file is said to be "overwriteable" if ** one or more of the following are true about the page: ** ** (a) The original content of the page as it was at the beginning of ** the transaction has been written into the rollback journal and ** synced. ** ** (b) The page was a freelist leaf page at the start of the transaction. ** ** (c) The page number is greater than the largest page that existed in ** the database file at the start of the transaction. ** ** (1) A page of the database file is never overwritten unless one of the ** following are true: ** ** (a) The page and all other pages on the same sector are overwriteable. ** ** (b) The atomic page write optimization is enabled, and the entire ** transaction other than the update of the transaction sequence ** number consists of a single page change. ** ** (2) The content of a page written into the rollback journal exactly matches ** both the content in the database when the rollback journal was written ** and the content in the database at the beginning of the current ** transaction. ** ** (3) Writes to the database file are an integer multiple of the page size ** in length and are aligned on a page boundary. ** ** (4) Reads from the database file are either aligned on a page boundary and ** an integer multiple of the page size in length or are taken from the ** first 100 bytes of the database file. ** ** (5) All writes to the database file are synced prior to the rollback journal ** being deleted, truncated, or zeroed. ** ** (6) If a master journal file is used, then all writes to the database file ** are synced prior to the master journal being deleted. ** ** Definition: Two databases (or the same database at two points it time) ** are said to be "logically equivalent" if they give the same answer to ** all queries. Note in particular the content of freelist leaf ** pages can be changed arbitrarily without affecting the logical equivalence ** of the database. ** ** (7) At any time, if any subset, including the empty set and the total set, ** of the unsynced changes to a rollback journal are removed and the ** journal is rolled back, the resulting database file will be logically ** equivalent to the database file at the beginning of the transaction. ** ** (8) When a transaction is rolled back, the xTruncate method of the VFS ** is called to restore the database file to the same size it was at ** the beginning of the transaction. (In some VFSes, the xTruncate ** method is a no-op, but that does not change the fact the SQLite will ** invoke it.) ** ** (9) Whenever the database file is modified, at least one bit in the range ** of bytes from 24 through 39 inclusive will be changed prior to releasing ** the EXCLUSIVE lock, thus signaling other connections on the same ** database to flush their caches. ** ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less ** than one billion transactions. ** ** (11) A database file is well-formed at the beginning and at the conclusion ** of every transaction. ** ** (12) An EXCLUSIVE lock is held on the database file when writing to ** the database file. ** ** (13) A SHARED lock is held on the database file while reading any ** content out of the database file. ** ******************************************************************************/ /* ** Macros for troubleshooting. Normally turned off */ #if 0 int sqlite3PagerTrace=1; /* True to enable tracing */ #define sqlite3DebugPrintf printf #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } #else #define PAGERTRACE(X) #endif /* ** The following two macros are used within the PAGERTRACE() macros above ** to print out file-descriptors. ** ** PAGERID() takes a pointer to a Pager struct as its argument. The ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file ** struct as its argument. */ #define PAGERID(p) ((int)(p->fd)) #define FILEHANDLEID(fd) ((int)fd) /* ** The Pager.eState variable stores the current 'state' of a pager. A ** pager may be in any one of the seven states shown in the following ** state diagram. ** ** OPEN <------+------+ ** | | | ** V | | ** +---------> READER-------+ | ** | | | ** | V | ** |<-------WRITER_LOCKED------> ERROR ** | | ^ ** | V | ** |<------WRITER_CACHEMOD-------->| ** | | | ** | V | ** |<-------WRITER_DBMOD---------->| ** | | | ** | V | ** +<------WRITER_FINISHED-------->+ ** ** ** List of state transitions and the C [function] that performs each: ** ** OPEN -> READER [sqlite3PagerSharedLock] ** READER -> OPEN [pager_unlock] ** ** READER -> WRITER_LOCKED [sqlite3PagerBegin] ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal] ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal] ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne] ** WRITER_*** -> READER [pager_end_transaction] ** ** WRITER_*** -> ERROR [pager_error] ** ERROR -> OPEN [pager_unlock] ** ** ** OPEN: ** ** The pager starts up in this state. Nothing is guaranteed in this ** state - the file may or may not be locked and the database size is ** unknown. The database may not be read or written. ** ** * No read or write transaction is active. ** * Any lock, or no lock at all, may be held on the database file. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted. ** ** READER: ** ** In this state all the requirements for reading the database in ** rollback (non-WAL) mode are met. Unless the pager is (or recently ** was) in exclusive-locking mode, a user-level read transaction is ** open. The database size is known in this state. ** ** A connection running with locking_mode=normal enters this state when ** it opens a read-transaction on the database and returns to state ** OPEN after the read-transaction is completed. However a connection ** running in locking_mode=exclusive (including temp databases) remains in ** this state even after the read-transaction is closed. The only way ** a locking_mode=exclusive connection can transition from READER to OPEN ** is via the ERROR state (see below). ** ** * A read transaction may be active (but a write-transaction cannot). ** * A SHARED or greater lock is held on the database file. ** * The dbSize variable may be trusted (even if a user-level read ** transaction is not active). The dbOrigSize and dbFileSize variables ** may not be trusted at this point. ** * If the database is a WAL database, then the WAL connection is open. ** * Even if a read-transaction is not open, it is guaranteed that ** there is no hot-journal in the file-system. ** ** WRITER_LOCKED: ** ** The pager moves to this state from READER when a write-transaction ** is first opened on the database. In WRITER_LOCKED state, all locks ** required to start a write-transaction are held, but no actual ** modifications to the cache or database have taken place. ** ** In rollback mode, a RESERVED or (if the transaction was opened with ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when ** moving to this state, but the journal file is not written to or opened ** to in this state. If the transaction is committed or rolled back while ** in WRITER_LOCKED state, all that is required is to unlock the database ** file. ** ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file. ** If the connection is running with locking_mode=exclusive, an attempt ** is made to obtain an EXCLUSIVE lock on the database file. ** ** * A write transaction is active. ** * If the connection is open in rollback-mode, a RESERVED or greater ** lock is held on the database file. ** * If the connection is open in WAL-mode, a WAL write transaction ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully ** called). ** * The dbSize, dbOrigSize and dbFileSize variables are all valid. ** * The contents of the pager cache have not been modified. ** * The journal file may or may not be open. ** * Nothing (not even the first header) has been written to the journal. ** ** WRITER_CACHEMOD: ** ** A pager moves from WRITER_LOCKED state to this state when a page is ** first modified by the upper layer. In rollback mode the journal file ** is opened (if it is not already open) and a header written to the ** start of it. The database file on disk has not been modified. ** ** * A write transaction is active. ** * A RESERVED or greater lock is held on the database file. ** * The journal file is open and the first header has been written ** to it, but the header has not been synced to disk. ** * The contents of the page cache have been modified. ** ** WRITER_DBMOD: ** ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state ** when it modifies the contents of the database file. WAL connections ** never enter this state (since they do not modify the database file, ** just the log file). ** ** * A write transaction is active. ** * An EXCLUSIVE or greater lock is held on the database file. ** * The journal file is open and the first header has been written ** and synced to disk. ** * The contents of the page cache have been modified (and possibly ** written to disk). ** ** WRITER_FINISHED: ** ** It is not possible for a WAL connection to enter this state. ** ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD ** state after the entire transaction has been successfully written into the ** database file. In this state the transaction may be committed simply ** by finalizing the journal file. Once in WRITER_FINISHED state, it is ** not possible to modify the database further. At this point, the upper ** layer must either commit or rollback the transaction. ** ** * A write transaction is active. ** * An EXCLUSIVE or greater lock is held on the database file. ** * All writing and syncing of journal and database data has finished. ** If no error occurred, all that remains is to finalize the journal to ** commit the transaction. If an error did occur, the caller will need ** to rollback the transaction. ** ** ERROR: ** ** The ERROR state is entered when an IO or disk-full error (including ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it ** difficult to be sure that the in-memory pager state (cache contents, ** db size etc.) are consistent with the contents of the file-system. ** ** Temporary pager files may enter the ERROR state, but in-memory pagers ** cannot. ** ** For example, if an IO error occurs while performing a rollback, ** the contents of the page-cache may be left in an inconsistent state. ** At this point it would be dangerous to change back to READER state ** (as usually happens after a rollback). Any subsequent readers might ** report database corruption (due to the inconsistent cache), and if ** they upgrade to writers, they may inadvertently corrupt the database ** file. To avoid this hazard, the pager switches into the ERROR state ** instead of READER following such an error. ** ** Once it has entered the ERROR state, any attempt to use the pager ** to read or write data returns an error. Eventually, once all ** outstanding transactions have been abandoned, the pager is able to ** transition back to OPEN state, discarding the contents of the ** page-cache and any other in-memory state at the same time. Everything ** is reloaded from disk (and, if necessary, hot-journal rollback peformed) ** when a read-transaction is next opened on the pager (transitioning ** the pager into READER state). At that point the system has recovered ** from the error. ** ** Specifically, the pager jumps into the ERROR state if: ** ** 1. An error occurs while attempting a rollback. This happens in ** function sqlite3PagerRollback(). ** ** 2. An error occurs while attempting to finalize a journal file ** following a commit in function sqlite3PagerCommitPhaseTwo(). ** ** 3. An error occurs while attempting to write to the journal or ** database file in function pagerStress() in order to free up ** memory. ** ** In other cases, the error is returned to the b-tree layer. The b-tree ** layer then attempts a rollback operation. If the error condition ** persists, the pager enters the ERROR state via condition (1) above. ** ** Condition (3) is necessary because it can be triggered by a read-only ** statement executed within a transaction. In this case, if the error ** code were simply returned to the user, the b-tree layer would not ** automatically attempt a rollback, as it assumes that an error in a ** read-only statement cannot leave the pager in an internally inconsistent ** state. ** ** * The Pager.errCode variable is set to something other than SQLITE_OK. ** * There are one or more outstanding references to pages (after the ** last reference is dropped the pager should move back to OPEN state). ** * The pager is not an in-memory pager. ** ** ** Notes: ** ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the ** connection is open in WAL mode. A WAL connection is always in one ** of the first four states. ** ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN ** state. There are two exceptions: immediately after exclusive-mode has ** been turned on (and before any read or write transactions are ** executed), and when the pager is leaving the "error state". ** ** * See also: assert_pager_state(). */ #define PAGER_OPEN 0 #define PAGER_READER 1 #define PAGER_WRITER_LOCKED 2 #define PAGER_WRITER_CACHEMOD 3 #define PAGER_WRITER_DBMOD 4 #define PAGER_WRITER_FINISHED 5 #define PAGER_ERROR 6 /* ** The Pager.eLock variable is almost always set to one of the ** following locking-states, according to the lock currently held on ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. ** This variable is kept up to date as locks are taken and released by ** the pagerLockDb() and pagerUnlockDb() wrappers. ** ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not ** the operation was successful. In these circumstances pagerLockDb() and ** pagerUnlockDb() take a conservative approach - eLock is always updated ** when unlocking the file, and only updated when locking the file if the ** VFS call is successful. This way, the Pager.eLock variable may be set ** to a less exclusive (lower) value than the lock that is actually held ** at the system level, but it is never set to a more exclusive value. ** ** This is usually safe. If an xUnlock fails or appears to fail, there may ** be a few redundant xLock() calls or a lock may be held for longer than ** required, but nothing really goes wrong. ** ** The exception is when the database file is unlocked as the pager moves ** from ERROR to OPEN state. At this point there may be a hot-journal file ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED ** transition, by the same pager or any other). If the call to xUnlock() ** fails at this point and the pager is left holding an EXCLUSIVE lock, this ** can confuse the call to xCheckReservedLock() call made later as part ** of hot-journal detection. ** ** xCheckReservedLock() is defined as returning true "if there is a RESERVED ** lock held by this process or any others". So xCheckReservedLock may ** return true because the caller itself is holding an EXCLUSIVE lock (but ** doesn't know it because of a previous error in xUnlock). If this happens ** a hot-journal may be mistaken for a journal being created by an active ** transaction in another process, causing SQLite to read from the database ** without rolling it back. ** ** To work around this, if a call to xUnlock() fails when unlocking the ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It ** is only changed back to a real locking state after a successful call ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE ** lock on the database file before attempting to roll it back. See function ** PagerSharedLock() for more detail. ** ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in ** PAGER_OPEN state. */ #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1) /* ** A macro used for invoking the codec if there is one */ #ifdef SQLITE_HAS_CODEC # define CODEC1(P,D,N,X,E) \ if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; } # define CODEC2(P,D,N,X,E,O) \ if( P->xCodec==0 ){ O=(char*)D; }else \ if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; } #else # define CODEC1(P,D,N,X,E) /* NO-OP */ # define CODEC2(P,D,N,X,E,O) O=(char*)D #endif /* ** The maximum allowed sector size. 64KiB. If the xSectorsize() method ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. ** This could conceivably cause corruption following a power failure on ** such a system. This is currently an undocumented limit. */ #define MAX_SECTOR_SIZE 0x10000 /* ** An instance of the following structure is allocated for each active ** savepoint and statement transaction in the system. All such structures ** are stored in the Pager.aSavepoint[] array, which is allocated and ** resized using sqlite3Realloc(). ** ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is ** set to 0. If a journal-header is written into the main journal while ** the savepoint is active, then iHdrOffset is set to the byte offset ** immediately following the last journal record written into the main ** journal before the journal-header. This is required during savepoint ** rollback (see pagerPlaybackSavepoint()). */ typedef struct PagerSavepoint PagerSavepoint; struct PagerSavepoint { i64 iOffset; /* Starting offset in main journal */ i64 iHdrOffset; /* See above */ Bitvec *pInSavepoint; /* Set of pages in this savepoint */ Pgno nOrig; /* Original number of pages in file */ Pgno iSubRec; /* Index of first record in sub-journal */ #ifndef SQLITE_OMIT_WAL u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */ #endif }; /* ** Bits of the Pager.doNotSpill flag. See further description below. */ #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */ #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */ #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */ /* ** An open page cache is an instance of struct Pager. A description of ** some of the more important member variables follows: ** ** eState ** ** The current 'state' of the pager object. See the comment and state ** diagram above for a description of the pager state. ** ** eLock ** ** For a real on-disk database, the current lock held on the database file - ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. ** ** For a temporary or in-memory database (neither of which require any ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such ** databases always have Pager.exclusiveMode==1, this tricks the pager ** logic into thinking that it already has all the locks it will ever ** need (and no reason to release them). ** ** In some (obscure) circumstances, this variable may also be set to ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for ** details. ** ** changeCountDone ** ** This boolean variable is used to make sure that the change-counter ** (the 4-byte header field at byte offset 24 of the database file) is ** not updated more often than necessary. ** ** It is set to true when the change-counter field is updated, which ** can only happen if an exclusive lock is held on the database file. ** It is cleared (set to false) whenever an exclusive lock is ** relinquished on the database file. Each time a transaction is committed, ** The changeCountDone flag is inspected. If it is true, the work of ** updating the change-counter is omitted for the current transaction. ** ** This mechanism means that when running in exclusive mode, a connection ** need only update the change-counter once, for the first transaction ** committed. ** ** setMaster ** ** When PagerCommitPhaseOne() is called to commit a transaction, it may ** (or may not) specify a master-journal name to be written into the ** journal file before it is synced to disk. ** ** Whether or not a journal file contains a master-journal pointer affects ** the way in which the journal file is finalized after the transaction is ** committed or rolled back when running in "journal_mode=PERSIST" mode. ** If a journal file does not contain a master-journal pointer, it is ** finalized by overwriting the first journal header with zeroes. If ** it does contain a master-journal pointer the journal file is finalized ** by truncating it to zero bytes, just as if the connection were ** running in "journal_mode=truncate" mode. ** ** Journal files that contain master journal pointers cannot be finalized ** simply by overwriting the first journal-header with zeroes, as the ** master journal pointer could interfere with hot-journal rollback of any ** subsequently interrupted transaction that reuses the journal file. ** ** The flag is cleared as soon as the journal file is finalized (either ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the ** journal file from being successfully finalized, the setMaster flag ** is cleared anyway (and the pager will move to ERROR state). ** ** doNotSpill ** ** This variables control the behavior of cache-spills (calls made by ** the pcache module to the pagerStress() routine to write cached data ** to the file-system in order to free up memory). ** ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set, ** writing to the database from pagerStress() is disabled altogether. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that ** comes up during savepoint rollback that requires the pcache module ** to allocate a new page to prevent the journal file from being written ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF ** case is a user preference. ** ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from ** pagerStress() is permitted, but syncing the journal file is not. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size ** is larger than the database page-size in order to prevent a journal sync ** from happening in between the journalling of two pages on the same sector. ** ** subjInMemory ** ** This is a boolean variable. If true, then any required sub-journal ** is opened as an in-memory journal file. If false, then in-memory ** sub-journals are only used for in-memory pager files. ** ** This variable is updated by the upper layer each time a new ** write-transaction is opened. ** ** dbSize, dbOrigSize, dbFileSize ** ** Variable dbSize is set to the number of pages in the database file. ** It is valid in PAGER_READER and higher states (all states except for ** OPEN and ERROR). ** ** dbSize is set based on the size of the database file, which may be ** larger than the size of the database (the value stored at offset ** 28 of the database header by the btree). If the size of the file ** is not an integer multiple of the page-size, the value stored in ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2). ** Except, any file that is greater than 0 bytes in size is considered ** to have at least one page. (i.e. a 1KB file with 2K page-size leads ** to dbSize==1). ** ** During a write-transaction, if pages with page-numbers greater than ** dbSize are modified in the cache, dbSize is updated accordingly. ** Similarly, if the database is truncated using PagerTruncateImage(), ** dbSize is updated. ** ** Variables dbOrigSize and dbFileSize are valid in states ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize ** variable at the start of the transaction. It is used during rollback, ** and to determine whether or not pages need to be journalled before ** being modified. ** ** Throughout a write-transaction, dbFileSize contains the size of ** the file on disk in pages. It is set to a copy of dbSize when the ** write-transaction is first opened, and updated when VFS calls are made ** to write or truncate the database file on disk. ** ** The only reason the dbFileSize variable is required is to suppress ** unnecessary calls to xTruncate() after committing a transaction. If, ** when a transaction is committed, the dbFileSize variable indicates ** that the database file is larger than the database image (Pager.dbSize), ** pager_truncate() is called. The pager_truncate() call uses xFilesize() ** to measure the database file on disk, and then truncates it if required. ** dbFileSize is not used when rolling back a transaction. In this case ** pager_truncate() is called unconditionally (which means there may be ** a call to xFilesize() that is not strictly required). In either case, ** pager_truncate() may cause the file to become smaller or larger. ** ** dbHintSize ** ** The dbHintSize variable is used to limit the number of calls made to ** the VFS xFileControl(FCNTL_SIZE_HINT) method. ** ** dbHintSize is set to a copy of the dbSize variable when a ** write-transaction is opened (at the same time as dbFileSize and ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called, ** dbHintSize is increased to the number of pages that correspond to the ** size-hint passed to the method call. See pager_write_pagelist() for ** details. ** ** errCode ** ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX ** sub-codes. */ struct Pager { sqlite3_vfs *pVfs; /* OS functions to use for IO */ u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */ u8 useJournal; /* Use a rollback journal on this file */ u8 noSync; /* Do not sync the journal if true */ u8 fullSync; /* Do extra syncs of the journal for robustness */ u8 extraSync; /* sync directory after journal delete */ u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */ u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */ u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */ u8 tempFile; /* zFilename is a temporary or immutable file */ u8 noLock; /* Do not lock (except in WAL mode) */ u8 readOnly; /* True for a read-only database */ u8 memDb; /* True to inhibit all file I/O */ /************************************************************************** ** The following block contains those class members that change during ** routine operation. Class members not in this block are either fixed ** when the pager is first created or else only change when there is a ** significant mode change (such as changing the page_size, locking_mode, ** or the journal_mode). From another view, these class members describe ** the "state" of the pager, while other class members describe the ** "configuration" of the pager. */ u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */ u8 eLock; /* Current lock held on database file */ u8 changeCountDone; /* Set after incrementing the change-counter */ u8 setMaster; /* True if a m-j name has been written to jrnl */ u8 doNotSpill; /* Do not spill the cache when non-zero */ u8 subjInMemory; /* True to use in-memory sub-journals */ u8 bUseFetch; /* True to use xFetch() */ u8 hasHeldSharedLock; /* True if a shared lock has ever been held */ Pgno dbSize; /* Number of pages in the database */ Pgno dbOrigSize; /* dbSize before the current transaction */ Pgno dbFileSize; /* Number of pages in the database file */ Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */ int errCode; /* One of several kinds of errors */ int nRec; /* Pages journalled since last j-header written */ u32 cksumInit; /* Quasi-random value added to every checksum */ u32 nSubRec; /* Number of records written to sub-journal */ Bitvec *pInJournal; /* One bit for each page in the database file */ sqlite3_file *fd; /* File descriptor for database */ sqlite3_file *jfd; /* File descriptor for main journal */ sqlite3_file *sjfd; /* File descriptor for sub-journal */ i64 journalOff; /* Current write offset in the journal file */ i64 journalHdr; /* Byte offset to previous journal header */ sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */ PagerSavepoint *aSavepoint; /* Array of active savepoints */ int nSavepoint; /* Number of elements in aSavepoint[] */ u32 iDataVersion; /* Changes whenever database content changes */ char dbFileVers[16]; /* Changes whenever database file changes */ int nMmapOut; /* Number of mmap pages currently outstanding */ sqlite3_int64 szMmap; /* Desired maximum mmap size */ PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */ /* ** End of the routinely-changing class members ***************************************************************************/ u16 nExtra; /* Add this many bytes to each in-memory page */ i16 nReserve; /* Number of unused bytes at end of each page */ u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ u32 sectorSize; /* Assumed sector size during rollback */ int pageSize; /* Number of bytes in a page */ Pgno mxPgno; /* Maximum allowed size of the database */ i64 journalSizeLimit; /* Size limit for persistent journal files */ char *zFilename; /* Name of the database file */ char *zJournal; /* Name of the journal file */ int (*xBusyHandler)(void*); /* Function to call when busy */ void *pBusyHandlerArg; /* Context argument for xBusyHandler */ int aStat[3]; /* Total cache hits, misses and writes */ #ifdef SQLITE_TEST int nRead; /* Database pages read */ #endif void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */ int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */ #ifdef SQLITE_HAS_CODEC void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ void (*xCodecFree)(void*); /* Destructor for the codec */ void *pCodec; /* First argument to xCodec... methods */ #endif char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ PCache *pPCache; /* Pointer to page cache object */ #ifndef SQLITE_OMIT_WAL Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */ char *zWal; /* File name for write-ahead log */ #endif }; /* ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS ** or CACHE_WRITE to sqlite3_db_status(). */ #define PAGER_STAT_HIT 0 #define PAGER_STAT_MISS 1 #define PAGER_STAT_WRITE 2 /* ** The following global variables hold counters used for ** testing purposes only. These variables do not exist in ** a non-testing build. These variables are not thread-safe. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ # define PAGER_INCR(v) v++ #else # define PAGER_INCR(v) #endif /* ** Journal files begin with the following magic string. The data ** was obtained from /dev/random. It is used only as a sanity check. ** ** Since version 2.8.0, the journal format contains additional sanity ** checking information. If the power fails while the journal is being ** written, semi-random garbage data might appear in the journal ** file after power is restored. If an attempt is then made ** to roll the journal back, the database could be corrupted. The additional ** sanity checking data is an attempt to discover the garbage in the ** journal and ignore it. ** ** The sanity checking information for the new journal format consists ** of a 32-bit checksum on each page of data. The checksum covers both ** the page number and the pPager->pageSize bytes of data for the page. ** This cksum is initialized to a 32-bit random value that appears in the ** journal file right after the header. The random initializer is important, ** because garbage data that appears at the end of a journal is likely ** data that was once in other files that have now been deleted. If the ** garbage data came from an obsolete journal file, the checksums might ** be correct. But by initializing the checksum to random value which ** is different for every journal, we minimize that risk. */ static const unsigned char aJournalMagic[] = { 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7, }; /* ** The size of the of each page record in the journal is given by ** the following macro. */ #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8) /* ** The journal header size for this pager. This is usually the same ** size as a single disk sector. See also setSectorSize(). */ #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize) /* ** The macro MEMDB is true if we are dealing with an in-memory database. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set, ** the value of MEMDB will be a constant and the compiler will optimize ** out code that would never execute. */ #ifdef SQLITE_OMIT_MEMORYDB # define MEMDB 0 #else # define MEMDB pPager->memDb #endif /* ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch ** interfaces to access the database using memory-mapped I/O. */ #if SQLITE_MAX_MMAP_SIZE>0 # define USEFETCH(x) ((x)->bUseFetch) #else # define USEFETCH(x) 0 #endif /* ** The maximum legal page number is (2^31 - 1). */ #define PAGER_MAX_PGNO 2147483647 /* ** The argument to this macro is a file descriptor (type sqlite3_file*). ** Return 0 if it is not open, or non-zero (but not 1) if it is. ** ** This is so that expressions can be written as: ** ** if( isOpen(pPager->jfd) ){ ... ** ** instead of ** ** if( pPager->jfd->pMethods ){ ... */ #define isOpen(pFd) ((pFd)->pMethods!=0) /* ** Return true if this pager uses a write-ahead log to read page pgno. ** Return false if the pager reads pgno directly from the database. */ #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ) SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){ u32 iRead = 0; int rc; if( pPager->pWal==0 ) return 0; rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead); return rc || iRead; } #endif #ifndef SQLITE_OMIT_WAL # define pagerUseWal(x) ((x)->pWal!=0) #else # define pagerUseWal(x) 0 # define pagerRollbackWal(x) 0 # define pagerWalFrames(v,w,x,y) 0 # define pagerOpenWalIfPresent(z) SQLITE_OK # define pagerBeginReadTransaction(z) SQLITE_OK #endif #ifndef NDEBUG /* ** Usage: ** ** assert( assert_pager_state(pPager) ); ** ** This function runs many asserts to try to find inconsistencies in ** the internal state of the Pager object. */ static int assert_pager_state(Pager *p){ Pager *pPager = p; /* State must be valid. */ assert( p->eState==PAGER_OPEN || p->eState==PAGER_READER || p->eState==PAGER_WRITER_LOCKED || p->eState==PAGER_WRITER_CACHEMOD || p->eState==PAGER_WRITER_DBMOD || p->eState==PAGER_WRITER_FINISHED || p->eState==PAGER_ERROR ); /* Regardless of the current state, a temp-file connection always behaves ** as if it has an exclusive lock on the database file. It never updates ** the change-counter field, so the changeCountDone flag is always set. */ assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK ); assert( p->tempFile==0 || pPager->changeCountDone ); /* If the useJournal flag is clear, the journal-mode must be "OFF". ** And if the journal-mode is "OFF", the journal file must not be open. */ assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal ); assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) ); /* Check that MEMDB implies noSync. And an in-memory journal. Since ** this means an in-memory pager performs no IO at all, it cannot encounter ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing ** a journal file. (although the in-memory journal implementation may ** return SQLITE_IOERR_NOMEM while the journal file is being written). It ** is therefore not possible for an in-memory pager to enter the ERROR ** state. */ if( MEMDB ){ assert( !isOpen(p->fd) ); assert( p->noSync ); assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_MEMORY ); assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN ); assert( pagerUseWal(p)==0 ); } /* If changeCountDone is set, a RESERVED lock or greater must be held ** on the file. */ assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK ); assert( p->eLock!=PENDING_LOCK ); switch( p->eState ){ case PAGER_OPEN: assert( !MEMDB ); assert( pPager->errCode==SQLITE_OK ); assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile ); break; case PAGER_READER: assert( pPager->errCode==SQLITE_OK ); assert( p->eLock!=UNKNOWN_LOCK ); assert( p->eLock>=SHARED_LOCK ); break; case PAGER_WRITER_LOCKED: assert( p->eLock!=UNKNOWN_LOCK ); assert( pPager->errCode==SQLITE_OK ); if( !pagerUseWal(pPager) ){ assert( p->eLock>=RESERVED_LOCK ); } assert( pPager->dbSize==pPager->dbOrigSize ); assert( pPager->dbOrigSize==pPager->dbFileSize ); assert( pPager->dbOrigSize==pPager->dbHintSize ); assert( pPager->setMaster==0 ); break; case PAGER_WRITER_CACHEMOD: assert( p->eLock!=UNKNOWN_LOCK ); assert( pPager->errCode==SQLITE_OK ); if( !pagerUseWal(pPager) ){ /* It is possible that if journal_mode=wal here that neither the ** journal file nor the WAL file are open. This happens during ** a rollback transaction that switches from journal_mode=off ** to journal_mode=wal. */ assert( p->eLock>=RESERVED_LOCK ); assert( isOpen(p->jfd) || p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_WAL ); } assert( pPager->dbOrigSize==pPager->dbFileSize ); assert( pPager->dbOrigSize==pPager->dbHintSize ); break; case PAGER_WRITER_DBMOD: assert( p->eLock==EXCLUSIVE_LOCK ); assert( pPager->errCode==SQLITE_OK ); assert( !pagerUseWal(pPager) ); assert( p->eLock>=EXCLUSIVE_LOCK ); assert( isOpen(p->jfd) || p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_WAL ); assert( pPager->dbOrigSize<=pPager->dbHintSize ); break; case PAGER_WRITER_FINISHED: assert( p->eLock==EXCLUSIVE_LOCK ); assert( pPager->errCode==SQLITE_OK ); assert( !pagerUseWal(pPager) ); assert( isOpen(p->jfd) || p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_WAL ); break; case PAGER_ERROR: /* There must be at least one outstanding reference to the pager if ** in ERROR state. Otherwise the pager should have already dropped ** back to OPEN state. */ assert( pPager->errCode!=SQLITE_OK ); assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile ); break; } return 1; } #endif /* ifndef NDEBUG */ #ifdef SQLITE_DEBUG /* ** Return a pointer to a human readable string in a static buffer ** containing the state of the Pager object passed as an argument. This ** is intended to be used within debuggers. For example, as an alternative ** to "print *pPager" in gdb: ** ** (gdb) printf "%s", print_pager_state(pPager) */ static char *print_pager_state(Pager *p){ static char zRet[1024]; sqlite3_snprintf(1024, zRet, "Filename: %s\n" "State: %s errCode=%d\n" "Lock: %s\n" "Locking mode: locking_mode=%s\n" "Journal mode: journal_mode=%s\n" "Backing store: tempFile=%d memDb=%d useJournal=%d\n" "Journal: journalOff=%lld journalHdr=%lld\n" "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n" , p->zFilename , p->eState==PAGER_OPEN ? "OPEN" : p->eState==PAGER_READER ? "READER" : p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" : p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" : p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" : p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" : p->eState==PAGER_ERROR ? "ERROR" : "?error?" , (int)p->errCode , p->eLock==NO_LOCK ? "NO_LOCK" : p->eLock==RESERVED_LOCK ? "RESERVED" : p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" : p->eLock==SHARED_LOCK ? "SHARED" : p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?" , p->exclusiveMode ? "exclusive" : "normal" , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" : p->journalMode==PAGER_JOURNALMODE_OFF ? "off" : p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" : p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" : p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" : p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?" , (int)p->tempFile, (int)p->memDb, (int)p->useJournal , p->journalOff, p->journalHdr , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize ); return zRet; } #endif /* Forward references to the various page getters */ static int getPageNormal(Pager*,Pgno,DbPage**,int); static int getPageError(Pager*,Pgno,DbPage**,int); #if SQLITE_MAX_MMAP_SIZE>0 static int getPageMMap(Pager*,Pgno,DbPage**,int); #endif /* ** Set the Pager.xGet method for the appropriate routine used to fetch ** content from the pager. */ static void setGetterMethod(Pager *pPager){ if( pPager->errCode ){ pPager->xGet = getPageError; #if SQLITE_MAX_MMAP_SIZE>0 }else if( USEFETCH(pPager) #ifdef SQLITE_HAS_CODEC && pPager->xCodec==0 #endif ){ pPager->xGet = getPageMMap; #endif /* SQLITE_MAX_MMAP_SIZE>0 */ }else{ pPager->xGet = getPageNormal; } } /* ** Return true if it is necessary to write page *pPg into the sub-journal. ** A page needs to be written into the sub-journal if there exists one ** or more open savepoints for which: ** ** * The page-number is less than or equal to PagerSavepoint.nOrig, and ** * The bit corresponding to the page-number is not set in ** PagerSavepoint.pInSavepoint. */ static int subjRequiresPage(PgHdr *pPg){ Pager *pPager = pPg->pPager; PagerSavepoint *p; Pgno pgno = pPg->pgno; int i; for(i=0; i<pPager->nSavepoint; i++){ p = &pPager->aSavepoint[i]; if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){ return 1; } } return 0; } #ifdef SQLITE_DEBUG /* ** Return true if the page is already in the journal file. */ static int pageInJournal(Pager *pPager, PgHdr *pPg){ return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno); } #endif /* ** Read a 32-bit integer from the given file descriptor. Store the integer ** that is read in *pRes. Return SQLITE_OK if everything worked, or an ** error code is something goes wrong. ** ** All values are stored on disk as big-endian. */ static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){ unsigned char ac[4]; int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset); if( rc==SQLITE_OK ){ *pRes = sqlite3Get4byte(ac); } return rc; } /* ** Write a 32-bit integer into a string buffer in big-endian byte order. */ #define put32bits(A,B) sqlite3Put4byte((u8*)A,B) /* ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK ** on success or an error code is something goes wrong. */ static int write32bits(sqlite3_file *fd, i64 offset, u32 val){ char ac[4]; put32bits(ac, val); return sqlite3OsWrite(fd, ac, 4, offset); } /* ** Unlock the database file to level eLock, which must be either NO_LOCK ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock() ** succeeds, set the Pager.eLock variable to match the (attempted) new lock. ** ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is ** called, do not modify it. See the comment above the #define of ** UNKNOWN_LOCK for an explanation of this. */ static int pagerUnlockDb(Pager *pPager, int eLock){ int rc = SQLITE_OK; assert( !pPager->exclusiveMode || pPager->eLock==eLock ); assert( eLock==NO_LOCK || eLock==SHARED_LOCK ); assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 ); if( isOpen(pPager->fd) ){ assert( pPager->eLock>=eLock ); rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock); if( pPager->eLock!=UNKNOWN_LOCK ){ pPager->eLock = (u8)eLock; } IOTRACE(("UNLOCK %p %d\n", pPager, eLock)) } return rc; } /* ** Lock the database file to level eLock, which must be either SHARED_LOCK, ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the ** Pager.eLock variable to the new locking state. ** ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. ** See the comment above the #define of UNKNOWN_LOCK for an explanation ** of this. */ static int pagerLockDb(Pager *pPager, int eLock){ int rc = SQLITE_OK; assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK ); if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){ rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock); if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){ pPager->eLock = (u8)eLock; IOTRACE(("LOCK %p %d\n", pPager, eLock)) } } return rc; } /* ** This function determines whether or not the atomic-write optimization ** can be used with this pager. The optimization can be used if: ** ** (a) the value returned by OsDeviceCharacteristics() indicates that ** a database page may be written atomically, and ** (b) the value returned by OsSectorSize() is less than or equal ** to the page size. ** ** The optimization is also always enabled for temporary files. It is ** an error to call this function if pPager is opened on an in-memory ** database. ** ** If the optimization cannot be used, 0 is returned. If it can be used, ** then the value returned is the size of the journal file when it ** contains rollback data for exactly one page. */ #ifdef SQLITE_ENABLE_ATOMIC_WRITE static int jrnlBufferSize(Pager *pPager){ assert( !MEMDB ); if( !pPager->tempFile ){ int dc; /* Device characteristics */ int nSector; /* Sector size */ int szPage; /* Page size */ assert( isOpen(pPager->fd) ); dc = sqlite3OsDeviceCharacteristics(pPager->fd); nSector = pPager->sectorSize; szPage = pPager->pageSize; assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){ return 0; } } return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager); } #else # define jrnlBufferSize(x) 0 #endif /* ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking ** on the cache using a hash function. This is used for testing ** and debugging only. */ #ifdef SQLITE_CHECK_PAGES /* ** Return a 32-bit hash of the page data for pPage. */ static u32 pager_datahash(int nByte, unsigned char *pData){ u32 hash = 0; int i; for(i=0; i<nByte; i++){ hash = (hash*1039) + pData[i]; } return hash; } static u32 pager_pagehash(PgHdr *pPage){ return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData); } static void pager_set_pagehash(PgHdr *pPage){ pPage->pageHash = pager_pagehash(pPage); } /* ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES ** is defined, and NDEBUG is not defined, an assert() statement checks ** that the page is either dirty or still matches the calculated page-hash. */ #define CHECK_PAGE(x) checkPage(x) static void checkPage(PgHdr *pPg){ Pager *pPager = pPg->pPager; assert( pPager->eState!=PAGER_ERROR ); assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) ); } #else #define pager_datahash(X,Y) 0 #define pager_pagehash(X) 0 #define pager_set_pagehash(X) #define CHECK_PAGE(x) #endif /* SQLITE_CHECK_PAGES */ /* ** When this is called the journal file for pager pPager must be open. ** This function attempts to read a master journal file name from the ** end of the file and, if successful, copies it into memory supplied ** by the caller. See comments above writeMasterJournal() for the format ** used to store a master journal file name at the end of a journal file. ** ** zMaster must point to a buffer of at least nMaster bytes allocated by ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is ** enough space to write the master journal name). If the master journal ** name in the journal is longer than nMaster bytes (including a ** nul-terminator), then this is handled as if no master journal name ** were present in the journal. ** ** If a master journal file name is present at the end of the journal ** file, then it is copied into the buffer pointed to by zMaster. A ** nul-terminator byte is appended to the buffer following the master ** journal file name. ** ** If it is determined that no master journal file name is present ** zMaster[0] is set to 0 and SQLITE_OK returned. ** ** If an error occurs while reading from the journal file, an SQLite ** error code is returned. */ static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){ int rc; /* Return code */ u32 len; /* Length in bytes of master journal name */ i64 szJ; /* Total size in bytes of journal file pJrnl */ u32 cksum; /* MJ checksum value read from journal */ u32 u; /* Unsigned loop counter */ unsigned char aMagic[8]; /* A buffer to hold the magic header */ zMaster[0] = '\0'; if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) || szJ<16 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len)) || len>=nMaster || len==0 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum)) || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) || memcmp(aMagic, aJournalMagic, 8) || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len)) ){ return rc; } /* See if the checksum matches the master journal name */ for(u=0; u<len; u++){ cksum -= zMaster[u]; } if( cksum ){ /* If the checksum doesn't add up, then one or more of the disk sectors ** containing the master journal filename is corrupted. This means ** definitely roll back, so just return SQLITE_OK and report a (nul) ** master-journal filename. */ len = 0; } zMaster[len] = '\0'; return SQLITE_OK; } /* ** Return the offset of the sector boundary at or immediately ** following the value in pPager->journalOff, assuming a sector ** size of pPager->sectorSize bytes. ** ** i.e for a sector size of 512: ** ** Pager.journalOff Return value ** --------------------------------------- ** 0 0 ** 512 512 ** 100 512 ** 2000 2048 ** */ static i64 journalHdrOffset(Pager *pPager){ i64 offset = 0; i64 c = pPager->journalOff; if( c ){ offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager); } assert( offset%JOURNAL_HDR_SZ(pPager)==0 ); assert( offset>=c ); assert( (offset-c)<JOURNAL_HDR_SZ(pPager) ); return offset; } /* ** The journal file must be open when this function is called. ** ** This function is a no-op if the journal file has not been written to ** within the current transaction (i.e. if Pager.journalOff==0). ** ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is ** set to 0, then truncate the journal file to zero bytes in size. Otherwise, ** zero the 28-byte header at the start of the journal file. In either case, ** if the pager is not in no-sync mode, sync the journal file immediately ** after writing or truncating it. ** ** If Pager.journalSizeLimit is set to a positive, non-zero value, and ** following the truncation or zeroing described above the size of the ** journal file in bytes is larger than this value, then truncate the ** journal file to Pager.journalSizeLimit bytes. The journal file does ** not need to be synced following this operation. ** ** If an IO error occurs, abandon processing and return the IO error code. ** Otherwise, return SQLITE_OK. */ static int zeroJournalHdr(Pager *pPager, int doTruncate){ int rc = SQLITE_OK; /* Return code */ assert( isOpen(pPager->jfd) ); assert( !sqlite3JournalIsInMemory(pPager->jfd) ); if( pPager->journalOff ){ const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */ IOTRACE(("JZEROHDR %p\n", pPager)) if( doTruncate || iLimit==0 ){ rc = sqlite3OsTruncate(pPager->jfd, 0); }else{ static const char zeroHdr[28] = {0}; rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0); } if( rc==SQLITE_OK && !pPager->noSync ){ rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags); } /* At this point the transaction is committed but the write lock ** is still held on the file. If there is a size limit configured for ** the persistent journal and the journal file currently consumes more ** space than that limit allows for, truncate it now. There is no need ** to sync the file following this operation. */ if( rc==SQLITE_OK && iLimit>0 ){ i64 sz; rc = sqlite3OsFileSize(pPager->jfd, &sz); if( rc==SQLITE_OK && sz>iLimit ){ rc = sqlite3OsTruncate(pPager->jfd, iLimit); } } } return rc; } /* ** The journal file must be open when this routine is called. A journal ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the ** current location. ** ** The format for the journal header is as follows: ** - 8 bytes: Magic identifying journal format. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on. ** - 4 bytes: Random number used for page hash. ** - 4 bytes: Initial database page count. ** - 4 bytes: Sector size used by the process that wrote this journal. ** - 4 bytes: Database page size. ** ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space. */ static int writeJournalHdr(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */ u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */ u32 nWrite; /* Bytes of header sector written */ int ii; /* Loop counter */ assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ if( nHeader>JOURNAL_HDR_SZ(pPager) ){ nHeader = JOURNAL_HDR_SZ(pPager); } /* If there are active savepoints and any of them were created ** since the most recent journal header was written, update the ** PagerSavepoint.iHdrOffset fields now. */ for(ii=0; ii<pPager->nSavepoint; ii++){ if( pPager->aSavepoint[ii].iHdrOffset==0 ){ pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff; } } pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager); /* ** Write the nRec Field - the number of page records that follow this ** journal header. Normally, zero is written to this value at this time. ** After the records are added to the journal (and the journal synced, ** if in full-sync mode), the zero is overwritten with the true number ** of records (see syncJournal()). ** ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When ** reading the journal this value tells SQLite to assume that the ** rest of the journal file contains valid page records. This assumption ** is dangerous, as if a failure occurred whilst writing to the journal ** file it may contain some garbage data. There are two scenarios ** where this risk can be ignored: ** ** * When the pager is in no-sync mode. Corruption can follow a ** power failure in this case anyway. ** ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees ** that garbage data is never appended to the journal file. */ assert( isOpen(pPager->fd) || pPager->noSync ); if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY) || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) ){ memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff); }else{ memset(zHeader, 0, sizeof(aJournalMagic)+4); } /* The random check-hash initializer */ sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit); put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit); /* The initial database size */ put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize); /* The assumed sector size for this process */ put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize); /* The page size */ put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize); /* Initializing the tail of the buffer is not necessary. Everything ** works find if the following memset() is omitted. But initializing ** the memory prevents valgrind from complaining, so we are willing to ** take the performance hit. */ memset(&zHeader[sizeof(aJournalMagic)+20], 0, nHeader-(sizeof(aJournalMagic)+20)); /* In theory, it is only necessary to write the 28 bytes that the ** journal header consumes to the journal file here. Then increment the ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next ** record is written to the following sector (leaving a gap in the file ** that will be implicitly filled in by the OS). ** ** However it has been discovered that on some systems this pattern can ** be significantly slower than contiguously writing data to the file, ** even if that means explicitly writing data to the block of ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what ** is done. ** ** The loop is required here in case the sector-size is larger than the ** database page size. Since the zHeader buffer is only Pager.pageSize ** bytes in size, more than one call to sqlite3OsWrite() may be required ** to populate the entire journal header sector. */ for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){ IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader)) rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff); assert( pPager->journalHdr <= pPager->journalOff ); pPager->journalOff += nHeader; } return rc; } /* ** The journal file must be open when this is called. A journal header file ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal ** file. The current location in the journal file is given by ** pPager->journalOff. See comments above function writeJournalHdr() for ** a description of the journal header format. ** ** If the header is read successfully, *pNRec is set to the number of ** page records following this header and *pDbSize is set to the size of the ** database before the transaction began, in pages. Also, pPager->cksumInit ** is set to the value read from the journal header. SQLITE_OK is returned ** in this case. ** ** If the journal header file appears to be corrupted, SQLITE_DONE is ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes ** cannot be read from the journal file an error code is returned. */ static int readJournalHdr( Pager *pPager, /* Pager object */ int isHot, i64 journalSize, /* Size of the open journal file in bytes */ u32 *pNRec, /* OUT: Value read from the nRec field */ u32 *pDbSize /* OUT: Value of original database size field */ ){ int rc; /* Return code */ unsigned char aMagic[8]; /* A buffer to hold the magic header */ i64 iHdrOff; /* Offset of journal header being read */ assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ /* Advance Pager.journalOff to the start of the next sector. If the ** journal file is too small for there to be a header stored at this ** point, return SQLITE_DONE. */ pPager->journalOff = journalHdrOffset(pPager); if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){ return SQLITE_DONE; } iHdrOff = pPager->journalOff; /* Read in the first 8 bytes of the journal header. If they do not match ** the magic string found at the start of each journal header, return ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise, ** proceed. */ if( isHot || iHdrOff!=pPager->journalHdr ){ rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff); if( rc ){ return rc; } if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){ return SQLITE_DONE; } } /* Read the first three 32-bit fields of the journal header: The nRec ** field, the checksum-initializer and the database size at the start ** of the transaction. Return an error code if anything goes wrong. */ if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec)) || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit)) || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize)) ){ return rc; } if( pPager->journalOff==0 ){ u32 iPageSize; /* Page-size field of journal header */ u32 iSectorSize; /* Sector-size field of journal header */ /* Read the page-size and sector-size journal header fields. */ if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize)) || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize)) ){ return rc; } /* Versions of SQLite prior to 3.5.8 set the page-size field of the ** journal header to zero. In this case, assume that the Pager.pageSize ** variable is already set to the correct page size. */ if( iPageSize==0 ){ iPageSize = pPager->pageSize; } /* Check that the values read from the page-size and sector-size fields ** are within range. To be 'in range', both values need to be a power ** of two greater than or equal to 512 or 32, and not greater than their ** respective compile time maximum limits. */ if( iPageSize<512 || iSectorSize<32 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0 ){ /* If the either the page-size or sector-size in the journal-header is ** invalid, then the process that wrote the journal-header must have ** crashed before the header was synced. In this case stop reading ** the journal file here. */ return SQLITE_DONE; } /* Update the page-size to match the value read from the journal. ** Use a testcase() macro to make sure that malloc failure within ** PagerSetPagesize() is tested. */ rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1); testcase( rc!=SQLITE_OK ); /* Update the assumed sector-size to match the value used by ** the process that created this journal. If this journal was ** created by a process other than this one, then this routine ** is being called from within pager_playback(). The local value ** of Pager.sectorSize is restored at the end of that routine. */ pPager->sectorSize = iSectorSize; } pPager->journalOff += JOURNAL_HDR_SZ(pPager); return rc; } /* ** Write the supplied master journal name into the journal file for pager ** pPager at the current location. The master journal name must be the last ** thing written to a journal file. If the pager is in full-sync mode, the ** journal file descriptor is advanced to the next sector boundary before ** anything is written. The format is: ** ** + 4 bytes: PAGER_MJ_PGNO. ** + N bytes: Master journal filename in utf-8. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator). ** + 4 bytes: Master journal name checksum. ** + 8 bytes: aJournalMagic[]. ** ** The master journal page checksum is the sum of the bytes in the master ** journal name, where each byte is interpreted as a signed 8-bit integer. ** ** If zMaster is a NULL pointer (occurs for a single database transaction), ** this call is a no-op. */ static int writeMasterJournal(Pager *pPager, const char *zMaster){ int rc; /* Return code */ int nMaster; /* Length of string zMaster */ i64 iHdrOff; /* Offset of header in journal file */ i64 jrnlSize; /* Size of journal file on disk */ u32 cksum = 0; /* Checksum of string zMaster */ assert( pPager->setMaster==0 ); assert( !pagerUseWal(pPager) ); if( !zMaster || pPager->journalMode==PAGER_JOURNALMODE_MEMORY || !isOpen(pPager->jfd) ){ return SQLITE_OK; } pPager->setMaster = 1; assert( pPager->journalHdr <= pPager->journalOff ); /* Calculate the length in bytes and the checksum of zMaster */ for(nMaster=0; zMaster[nMaster]; nMaster++){ cksum += zMaster[nMaster]; } /* If in full-sync mode, advance to the next disk sector before writing ** the master journal name. This is in case the previous page written to ** the journal has already been synced. */ if( pPager->fullSync ){ pPager->journalOff = journalHdrOffset(pPager); } iHdrOff = pPager->journalOff; /* Write the master journal data to the end of the journal file. If ** an error occurs, return the error code to the caller. */ if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager)))) || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4))) || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster))) || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum))) || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8))) ){ return rc; } pPager->journalOff += (nMaster+20); /* If the pager is in peristent-journal mode, then the physical ** journal-file may extend past the end of the master-journal name ** and 8 bytes of magic data just written to the file. This is ** dangerous because the code to rollback a hot-journal file ** will not be able to find the master-journal name to determine ** whether or not the journal is hot. ** ** Easiest thing to do in this scenario is to truncate the journal ** file to the required size. */ if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize)) && jrnlSize>pPager->journalOff ){ rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff); } return rc; } /* ** Discard the entire contents of the in-memory page-cache. */ static void pager_reset(Pager *pPager){ pPager->iDataVersion++; sqlite3BackupRestart(pPager->pBackup); sqlite3PcacheClear(pPager->pPCache); } /* ** Return the pPager->iDataVersion value */ SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){ assert( pPager->eState>PAGER_OPEN ); return pPager->iDataVersion; } /* ** Free all structures in the Pager.aSavepoint[] array and set both ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal ** if it is open and the pager is not in exclusive mode. */ static void releaseAllSavepoints(Pager *pPager){ int ii; /* Iterator for looping through Pager.aSavepoint */ for(ii=0; ii<pPager->nSavepoint; ii++){ sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); } if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){ sqlite3OsClose(pPager->sjfd); } sqlite3_free(pPager->aSavepoint); pPager->aSavepoint = 0; pPager->nSavepoint = 0; pPager->nSubRec = 0; } /* ** Set the bit number pgno in the PagerSavepoint.pInSavepoint ** bitvecs of all open savepoints. Return SQLITE_OK if successful ** or SQLITE_NOMEM if a malloc failure occurs. */ static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){ int ii; /* Loop counter */ int rc = SQLITE_OK; /* Result code */ for(ii=0; ii<pPager->nSavepoint; ii++){ PagerSavepoint *p = &pPager->aSavepoint[ii]; if( pgno<=p->nOrig ){ rc |= sqlite3BitvecSet(p->pInSavepoint, pgno); testcase( rc==SQLITE_NOMEM ); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); } } return rc; } /* ** This function is a no-op if the pager is in exclusive mode and not ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN ** state. ** ** If the pager is not in exclusive-access mode, the database file is ** completely unlocked. If the file is unlocked and the file-system does ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is ** closed (if it is open). ** ** If the pager is in ERROR state when this function is called, the ** contents of the pager cache are discarded before switching back to ** the OPEN state. Regardless of whether the pager is in exclusive-mode ** or not, any journal file left in the file-system will be treated ** as a hot-journal and rolled back the next time a read-transaction ** is opened (by this or by any other connection). */ static void pager_unlock(Pager *pPager){ assert( pPager->eState==PAGER_READER || pPager->eState==PAGER_OPEN || pPager->eState==PAGER_ERROR ); sqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; releaseAllSavepoints(pPager); if( pagerUseWal(pPager) ){ assert( !isOpen(pPager->jfd) ); sqlite3WalEndReadTransaction(pPager->pWal); pPager->eState = PAGER_OPEN; }else if( !pPager->exclusiveMode ){ int rc; /* Error code returned by pagerUnlockDb() */ int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0; /* If the operating system support deletion of open files, then ** close the journal file when dropping the database lock. Otherwise ** another connection with journal_mode=delete might delete the file ** out from under us. */ assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 ); assert( (PAGER_JOURNALMODE_OFF & 5)!=1 ); assert( (PAGER_JOURNALMODE_WAL & 5)!=1 ); assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 ); assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN) || 1!=(pPager->journalMode & 5) ){ sqlite3OsClose(pPager->jfd); } /* If the pager is in the ERROR state and the call to unlock the database ** file fails, set the current lock to UNKNOWN_LOCK. See the comment ** above the #define for UNKNOWN_LOCK for an explanation of why this ** is necessary. */ rc = pagerUnlockDb(pPager, NO_LOCK); if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){ pPager->eLock = UNKNOWN_LOCK; } /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here ** without clearing the error code. This is intentional - the error ** code is cleared and the cache reset in the block below. */ assert( pPager->errCode || pPager->eState!=PAGER_ERROR ); pPager->changeCountDone = 0; pPager->eState = PAGER_OPEN; } /* If Pager.errCode is set, the contents of the pager cache cannot be ** trusted. Now that there are no outstanding references to the pager, ** it can safely move back to PAGER_OPEN state. This happens in both ** normal and exclusive-locking mode. */ assert( pPager->errCode==SQLITE_OK || !MEMDB ); if( pPager->errCode ){ if( pPager->tempFile==0 ){ pager_reset(pPager); pPager->changeCountDone = 0; pPager->eState = PAGER_OPEN; }else{ pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER); } if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); pPager->errCode = SQLITE_OK; setGetterMethod(pPager); } pPager->journalOff = 0; pPager->journalHdr = 0; pPager->setMaster = 0; } /* ** This function is called whenever an IOERR or FULL error that requires ** the pager to transition into the ERROR state may ahve occurred. ** The first argument is a pointer to the pager structure, the second ** the error-code about to be returned by a pager API function. The ** value returned is a copy of the second argument to this function. ** ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the ** IOERR sub-codes, the pager enters the ERROR state and the error code ** is stored in Pager.errCode. While the pager remains in the ERROR state, ** all major API calls on the Pager will immediately return Pager.errCode. ** ** The ERROR state indicates that the contents of the pager-cache ** cannot be trusted. This state can be cleared by completely discarding ** the contents of the pager-cache. If a transaction was active when ** the persistent error occurred, then the rollback journal may need ** to be replayed to restore the contents of the database file (as if ** it were a hot-journal). */ static int pager_error(Pager *pPager, int rc){ int rc2 = rc & 0xff; assert( rc==SQLITE_OK || !MEMDB ); assert( pPager->errCode==SQLITE_FULL || pPager->errCode==SQLITE_OK || (pPager->errCode & 0xff)==SQLITE_IOERR ); if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){ pPager->errCode = rc; pPager->eState = PAGER_ERROR; setGetterMethod(pPager); } return rc; } static int pager_truncate(Pager *pPager, Pgno nPage); /* ** The write transaction open on pPager is being committed (bCommit==1) ** or rolled back (bCommit==0). ** ** Return TRUE if and only if all dirty pages should be flushed to disk. ** ** Rules: ** ** * For non-TEMP databases, always sync to disk. This is necessary ** for transactions to be durable. ** ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing ** file has been created already (via a spill on pagerStress()) and ** when the number of dirty pages in memory exceeds 25% of the total ** cache size. */ static int pagerFlushOnCommit(Pager *pPager, int bCommit){ if( pPager->tempFile==0 ) return 1; if( !bCommit ) return 0; if( !isOpen(pPager->fd) ) return 0; return (sqlite3PCachePercentDirty(pPager->pPCache)>=25); } /* ** This routine ends a transaction. A transaction is usually ended by ** either a COMMIT or a ROLLBACK operation. This routine may be called ** after rollback of a hot-journal, or if an error occurs while opening ** the journal file or writing the very first journal-header of a ** database transaction. ** ** This routine is never called in PAGER_ERROR state. If it is called ** in PAGER_NONE or PAGER_SHARED state and the lock held is less ** exclusive than a RESERVED lock, it is a no-op. ** ** Otherwise, any active savepoints are released. ** ** If the journal file is open, then it is "finalized". Once a journal ** file has been finalized it is not possible to use it to roll back a ** transaction. Nor will it be considered to be a hot-journal by this ** or any other database connection. Exactly how a journal is finalized ** depends on whether or not the pager is running in exclusive mode and ** the current journal-mode (Pager.journalMode value), as follows: ** ** journalMode==MEMORY ** Journal file descriptor is simply closed. This destroys an ** in-memory journal. ** ** journalMode==TRUNCATE ** Journal file is truncated to zero bytes in size. ** ** journalMode==PERSIST ** The first 28 bytes of the journal file are zeroed. This invalidates ** the first journal header in the file, and hence the entire journal ** file. An invalid journal file cannot be rolled back. ** ** journalMode==DELETE ** The journal file is closed and deleted using sqlite3OsDelete(). ** ** If the pager is running in exclusive mode, this method of finalizing ** the journal file is never used. Instead, if the journalMode is ** DELETE and the pager is in exclusive mode, the method described under ** journalMode==PERSIST is used instead. ** ** After the journal is finalized, the pager moves to PAGER_READER state. ** If running in non-exclusive rollback mode, the lock on the file is ** downgraded to a SHARED_LOCK. ** ** SQLITE_OK is returned if no error occurs. If an error occurs during ** any of the IO operations to finalize the journal file or unlock the ** database then the IO error code is returned to the user. If the ** operation to finalize the journal file fails, then the code still ** tries to unlock the database file if not in exclusive mode. If the ** unlock operation fails as well, then the first error code related ** to the first error encountered (the journal finalization one) is ** returned. */ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){ int rc = SQLITE_OK; /* Error code from journal finalization operation */ int rc2 = SQLITE_OK; /* Error code from db file unlock operation */ /* Do nothing if the pager does not have an open write transaction ** or at least a RESERVED lock. This function may be called when there ** is no write-transaction active but a RESERVED or greater lock is ** held under two circumstances: ** ** 1. After a successful hot-journal rollback, it is called with ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK. ** ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE ** lock switches back to locking_mode=normal and then executes a ** read-transaction, this function is called with eState==PAGER_READER ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed. */ assert( assert_pager_state(pPager) ); assert( pPager->eState!=PAGER_ERROR ); if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){ return SQLITE_OK; } releaseAllSavepoints(pPager); assert( isOpen(pPager->jfd) || pPager->pInJournal==0 ); if( isOpen(pPager->jfd) ){ assert( !pagerUseWal(pPager) ); /* Finalize the journal file. */ if( sqlite3JournalIsInMemory(pPager->jfd) ){ /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */ sqlite3OsClose(pPager->jfd); }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){ if( pPager->journalOff==0 ){ rc = SQLITE_OK; }else{ rc = sqlite3OsTruncate(pPager->jfd, 0); if( rc==SQLITE_OK && pPager->fullSync ){ /* Make sure the new file size is written into the inode right away. ** Otherwise the journal might resurrect following a power loss and ** cause the last transaction to roll back. See ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773 */ rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); } } pPager->journalOff = 0; }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL) ){ rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile); pPager->journalOff = 0; }else{ /* This branch may be executed with Pager.journalMode==MEMORY if ** a hot-journal was just rolled back. In this case the journal ** file should be closed and deleted. If this connection writes to ** the database file, it will do so using an in-memory journal. */ int bDelete = !pPager->tempFile; assert( sqlite3JournalIsInMemory(pPager->jfd)==0 ); assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->journalMode==PAGER_JOURNALMODE_WAL ); sqlite3OsClose(pPager->jfd); if( bDelete ){ rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync); } } } #ifdef SQLITE_CHECK_PAGES sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash); if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){ PgHdr *p = sqlite3PagerLookup(pPager, 1); if( p ){ p->pageHash = 0; sqlite3PagerUnrefNotNull(p); } } #endif sqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; pPager->nRec = 0; if( rc==SQLITE_OK ){ if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){ sqlite3PcacheCleanAll(pPager->pPCache); }else{ sqlite3PcacheClearWritable(pPager->pPCache); } sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize); } if( pagerUseWal(pPager) ){ /* Drop the WAL write-lock, if any. Also, if the connection was in ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE ** lock held on the database file. */ rc2 = sqlite3WalEndWriteTransaction(pPager->pWal); assert( rc2==SQLITE_OK ); }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){ /* This branch is taken when committing a transaction in rollback-journal ** mode if the database file on disk is larger than the database image. ** At this point the journal has been finalized and the transaction ** successfully committed, but the EXCLUSIVE lock is still held on the ** file. So it is safe to truncate the database file to its minimum ** required size. */ assert( pPager->eLock==EXCLUSIVE_LOCK ); rc = pager_truncate(pPager, pPager->dbSize); } if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){ rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0); if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; } if( !pPager->exclusiveMode && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0)) ){ rc2 = pagerUnlockDb(pPager, SHARED_LOCK); pPager->changeCountDone = 0; } pPager->eState = PAGER_READER; pPager->setMaster = 0; return (rc==SQLITE_OK?rc2:rc); } /* ** Execute a rollback if a transaction is active and unlock the ** database file. ** ** If the pager has already entered the ERROR state, do not attempt ** the rollback at this time. Instead, pager_unlock() is called. The ** call to pager_unlock() will discard all in-memory pages, unlock ** the database file and move the pager back to OPEN state. If this ** means that there is a hot-journal left in the file-system, the next ** connection to obtain a shared lock on the pager (which may be this one) ** will roll it back. ** ** If the pager has not already entered the ERROR state, but an IO or ** malloc error occurs during a rollback, then this will itself cause ** the pager to enter the ERROR state. Which will be cleared by the ** call to pager_unlock(), as described above. */ static void pagerUnlockAndRollback(Pager *pPager){ if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){ assert( assert_pager_state(pPager) ); if( pPager->eState>=PAGER_WRITER_LOCKED ){ sqlite3BeginBenignMalloc(); sqlite3PagerRollback(pPager); sqlite3EndBenignMalloc(); }else if( !pPager->exclusiveMode ){ assert( pPager->eState==PAGER_READER ); pager_end_transaction(pPager, 0, 0); } } pager_unlock(pPager); } /* ** Parameter aData must point to a buffer of pPager->pageSize bytes ** of data. Compute and return a checksum based ont the contents of the ** page of data and the current value of pPager->cksumInit. ** ** This is not a real checksum. It is really just the sum of the ** random initial value (pPager->cksumInit) and every 200th byte ** of the page data, starting with byte offset (pPager->pageSize%200). ** Each byte is interpreted as an 8-bit unsigned integer. ** ** Changing the formula used to compute this checksum results in an ** incompatible journal file format. ** ** If journal corruption occurs due to a power failure, the most likely ** scenario is that one end or the other of the record will be changed. ** It is much less likely that the two ends of the journal record will be ** correct and the middle be corrupt. Thus, this "checksum" scheme, ** though fast and simple, catches the mostly likely kind of corruption. */ static u32 pager_cksum(Pager *pPager, const u8 *aData){ u32 cksum = pPager->cksumInit; /* Checksum value to return */ int i = pPager->pageSize-200; /* Loop counter */ while( i>0 ){ cksum += aData[i]; i -= 200; } return cksum; } /* ** Report the current page size and number of reserved bytes back ** to the codec. */ #ifdef SQLITE_HAS_CODEC static void pagerReportSize(Pager *pPager){ if( pPager->xCodecSizeChng ){ pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize, (int)pPager->nReserve); } } #else # define pagerReportSize(X) /* No-op if we do not support a codec */ #endif #ifdef SQLITE_HAS_CODEC /* ** Make sure the number of reserved bits is the same in the destination ** pager as it is in the source. This comes up when a VACUUM changes the ** number of reserved bits to the "optimal" amount. */ SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){ if( pDest->nReserve!=pSrc->nReserve ){ pDest->nReserve = pSrc->nReserve; pagerReportSize(pDest); } } #endif /* ** Read a single page from either the journal file (if isMainJrnl==1) or ** from the sub-journal (if isMainJrnl==0) and playback that page. ** The page begins at offset *pOffset into the file. The *pOffset ** value is increased to the start of the next page in the journal. ** ** The main rollback journal uses checksums - the statement journal does ** not. ** ** If the page number of the page record read from the (sub-)journal file ** is greater than the current value of Pager.dbSize, then playback is ** skipped and SQLITE_OK is returned. ** ** If pDone is not NULL, then it is a record of pages that have already ** been played back. If the page at *pOffset has already been played back ** (if the corresponding pDone bit is set) then skip the playback. ** Make sure the pDone bit corresponding to the *pOffset page is set ** prior to returning. ** ** If the page record is successfully read from the (sub-)journal file ** and played back, then SQLITE_OK is returned. If an IO error occurs ** while reading the record from the (sub-)journal file or while writing ** to the database file, then the IO error code is returned. If data ** is successfully read from the (sub-)journal file but appears to be ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in ** two circumstances: ** ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or ** * If the record is being rolled back from the main journal file ** and the checksum field does not match the record content. ** ** Neither of these two scenarios are possible during a savepoint rollback. ** ** If this is a savepoint rollback, then memory may have to be dynamically ** allocated by this function. If this is the case and an allocation fails, ** SQLITE_NOMEM is returned. */ static int pager_playback_one_page( Pager *pPager, /* The pager being played back */ i64 *pOffset, /* Offset of record to playback */ Bitvec *pDone, /* Bitvec of pages already played back */ int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */ int isSavepnt /* True for a savepoint rollback */ ){ int rc; PgHdr *pPg; /* An existing page in the cache */ Pgno pgno; /* The page number of a page in journal */ u32 cksum; /* Checksum used for sanity checking */ char *aData; /* Temporary storage for the page */ sqlite3_file *jfd; /* The file descriptor for the journal file */ int isSynced; /* True if journal page is synced */ assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */ assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */ assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */ assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */ aData = pPager->pTmpSpace; assert( aData ); /* Temp storage must have already been allocated */ assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) ); /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction ** or savepoint rollback done at the request of the caller) or this is ** a hot-journal rollback. If it is a hot-journal rollback, the pager ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback ** only reads from the main journal, not the sub-journal. */ assert( pPager->eState>=PAGER_WRITER_CACHEMOD || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK) ); assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl ); /* Read the page number and page data from the journal or sub-journal ** file. Return an error code to the caller if an IO error occurs. */ jfd = isMainJrnl ? pPager->jfd : pPager->sjfd; rc = read32bits(jfd, *pOffset, &pgno); if( rc!=SQLITE_OK ) return rc; rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4); if( rc!=SQLITE_OK ) return rc; *pOffset += pPager->pageSize + 4 + isMainJrnl*4; /* Sanity checking on the page. This is more important that I originally ** thought. If a power failure occurs while the journal is being written, ** it could cause invalid data to be written into the journal. We need to ** detect this invalid data (with high probability) and ignore it. */ if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){ assert( !isSavepnt ); return SQLITE_DONE; } if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){ return SQLITE_OK; } if( isMainJrnl ){ rc = read32bits(jfd, (*pOffset)-4, &cksum); if( rc ) return rc; if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){ return SQLITE_DONE; } } /* If this page has already been played back before during the current ** rollback, then don't bother to play it back again. */ if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){ return rc; } /* When playing back page 1, restore the nReserve setting */ if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){ pPager->nReserve = ((u8*)aData)[20]; pagerReportSize(pPager); } /* If the pager is in CACHEMOD state, then there must be a copy of this ** page in the pager cache. In this case just update the pager cache, ** not the database file. The page is left marked dirty in this case. ** ** An exception to the above rule: If the database is in no-sync mode ** and a page is moved during an incremental vacuum then the page may ** not be in the pager cache. Later: if a malloc() or IO error occurs ** during a Movepage() call, then the page may not be in the cache ** either. So the condition described in the above paragraph is not ** assert()able. ** ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the ** pager cache if it exists and the main file. The page is then marked ** not dirty. Since this code is only executed in PAGER_OPEN state for ** a hot-journal rollback, it is guaranteed that the page-cache is empty ** if the pager is in OPEN state. ** ** Ticket #1171: The statement journal might contain page content that is ** different from the page content at the start of the transaction. ** This occurs when a page is changed prior to the start of a statement ** then changed again within the statement. When rolling back such a ** statement we must not write to the original database unless we know ** for certain that original page contents are synced into the main rollback ** journal. Otherwise, a power loss might leave modified data in the ** database file without an entry in the rollback journal that can ** restore the database to its original form. Two conditions must be ** met before writing to the database files. (1) the database must be ** locked. (2) we know that the original page content is fully synced ** in the main journal either because the page is not in cache or else ** the page is marked as needSync==0. ** ** 2008-04-14: When attempting to vacuum a corrupt database file, it ** is possible to fail a statement on a database that does not yet exist. ** Do not attempt to write if database file has never been opened. */ if( pagerUseWal(pPager) ){ pPg = 0; }else{ pPg = sqlite3PagerLookup(pPager, pgno); } assert( pPg || !MEMDB ); assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile ); PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n", PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData), (isMainJrnl?"main-journal":"sub-journal") )); if( isMainJrnl ){ isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr); }else{ isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC)); } if( isOpen(pPager->fd) && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) && isSynced ){ i64 ofst = (pgno-1)*(i64)pPager->pageSize; testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 ); assert( !pagerUseWal(pPager) ); rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); if( pgno>pPager->dbFileSize ){ pPager->dbFileSize = pgno; } if( pPager->pBackup ){ CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT); sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData); } }else if( !isMainJrnl && pPg==0 ){ /* If this is a rollback of a savepoint and data was not written to ** the database and the page is not in-memory, there is a potential ** problem. When the page is next fetched by the b-tree layer, it ** will be read from the database file, which may or may not be ** current. ** ** There are a couple of different ways this can happen. All are quite ** obscure. When running in synchronous mode, this can only happen ** if the page is on the free-list at the start of the transaction, then ** populated, then moved using sqlite3PagerMovepage(). ** ** The solution is to add an in-memory page to the cache containing ** the data just read from the sub-journal. Mark the page as dirty ** and if the pager requires a journal-sync, then mark the page as ** requiring a journal-sync before it is written. */ assert( isSavepnt ); assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 ); pPager->doNotSpill |= SPILLFLAG_ROLLBACK; rc = sqlite3PagerGet(pPager, pgno, &pPg, 1); assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 ); pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK; if( rc!=SQLITE_OK ) return rc; sqlite3PcacheMakeDirty(pPg); } if( pPg ){ /* No page should ever be explicitly rolled back that is in use, except ** for page 1 which is held in use in order to keep the lock on the ** database active. However such a page may be rolled back as a result ** of an internal error resulting in an automatic call to ** sqlite3PagerRollback(). */ void *pData; pData = pPg->pData; memcpy(pData, (u8*)aData, pPager->pageSize); pPager->xReiniter(pPg); /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But ** that call was dangerous and had no detectable benefit since the cache ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so ** has been removed. */ pager_set_pagehash(pPg); /* If this was page 1, then restore the value of Pager.dbFileVers. ** Do this before any decoding. */ if( pgno==1 ){ memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers)); } /* Decode the page just read from disk */ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); sqlite3PcacheRelease(pPg); } return rc; } /* ** Parameter zMaster is the name of a master journal file. A single journal ** file that referred to the master journal file has just been rolled back. ** This routine checks if it is possible to delete the master journal file, ** and does so if it is. ** ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not ** available for use within this function. ** ** When a master journal file is created, it is populated with the names ** of all of its child journals, one after another, formatted as utf-8 ** encoded text. The end of each child journal file is marked with a ** nul-terminator byte (0x00). i.e. the entire contents of a master journal ** file for a transaction involving two databases might be: ** ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" ** ** A master journal file may only be deleted once all of its child ** journals have been rolled back. ** ** This function reads the contents of the master-journal file into ** memory and loops through each of the child journal names. For ** each child journal, it checks if: ** ** * if the child journal exists, and if so ** * if the child journal contains a reference to master journal ** file zMaster ** ** If a child journal can be found that matches both of the criteria ** above, this function returns without doing anything. Otherwise, if ** no such child journal can be found, file zMaster is deleted from ** the file-system using sqlite3OsDelete(). ** ** If an IO error within this function, an error code is returned. This ** function allocates memory by calling sqlite3Malloc(). If an allocation ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors ** occur, SQLITE_OK is returned. ** ** TODO: This function allocates a single block of memory to load ** the entire contents of the master journal file. This could be ** a couple of kilobytes or so - potentially larger than the page ** size. */ static int pager_delmaster(Pager *pPager, const char *zMaster){ sqlite3_vfs *pVfs = pPager->pVfs; int rc; /* Return code */ sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */ sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ char *zMasterJournal = 0; /* Contents of master journal file */ i64 nMasterJournal; /* Size of master journal file */ char *zJournal; /* Pointer to one journal within MJ file */ char *zMasterPtr; /* Space to hold MJ filename from a journal file */ int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */ /* Allocate space for both the pJournal and pMaster file descriptors. ** If successful, open the master journal file for reading. */ pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2); pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile); if( !pMaster ){ rc = SQLITE_NOMEM_BKPT; }else{ const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL); rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0); } if( rc!=SQLITE_OK ) goto delmaster_out; /* Load the entire master journal file into space obtained from ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain ** sufficient space (in zMasterPtr) to hold the names of master ** journal files extracted from regular rollback-journals. */ rc = sqlite3OsFileSize(pMaster, &nMasterJournal); if( rc!=SQLITE_OK ) goto delmaster_out; nMasterPtr = pVfs->mxPathname+1; zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1); if( !zMasterJournal ){ rc = SQLITE_NOMEM_BKPT; goto delmaster_out; } zMasterPtr = &zMasterJournal[nMasterJournal+1]; rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0); if( rc!=SQLITE_OK ) goto delmaster_out; zMasterJournal[nMasterJournal] = 0; zJournal = zMasterJournal; while( (zJournal-zMasterJournal)<nMasterJournal ){ int exists; rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists); if( rc!=SQLITE_OK ){ goto delmaster_out; } if( exists ){ /* One of the journals pointed to by the master journal exists. ** Open it and check if it points at the master journal. If ** so, return without deleting the master journal file. */ int c; int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL); rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0); if( rc!=SQLITE_OK ){ goto delmaster_out; } rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr); sqlite3OsClose(pJournal); if( rc!=SQLITE_OK ){ goto delmaster_out; } c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0; if( c ){ /* We have a match. Do not delete the master journal file. */ goto delmaster_out; } } zJournal += (sqlite3Strlen30(zJournal)+1); } sqlite3OsClose(pMaster); rc = sqlite3OsDelete(pVfs, zMaster, 0); delmaster_out: sqlite3_free(zMasterJournal); if( pMaster ){ sqlite3OsClose(pMaster); assert( !isOpen(pJournal) ); sqlite3_free(pMaster); } return rc; } /* ** This function is used to change the actual size of the database ** file in the file-system. This only happens when committing a transaction, ** or rolling back a transaction (including rolling back a hot-journal). ** ** If the main database file is not open, or the pager is not in either ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). ** If the file on disk is currently larger than nPage pages, then use the VFS ** xTruncate() method to truncate it. ** ** Or, it might be the case that the file on disk is smaller than ** nPage pages. Some operating system implementations can get confused if ** you try to truncate a file to some size that is larger than it ** currently is, so detect this case and write a single zero byte to ** the end of the new file instead. ** ** If successful, return SQLITE_OK. If an IO error occurs while modifying ** the database file, return the error code to the caller. */ static int pager_truncate(Pager *pPager, Pgno nPage){ int rc = SQLITE_OK; assert( pPager->eState!=PAGER_ERROR ); assert( pPager->eState!=PAGER_READER ); if( isOpen(pPager->fd) && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) ){ i64 currentSize, newSize; int szPage = pPager->pageSize; assert( pPager->eLock==EXCLUSIVE_LOCK ); /* TODO: Is it safe to use Pager.dbFileSize here? */ rc = sqlite3OsFileSize(pPager->fd, &currentSize); newSize = szPage*(i64)nPage; if( rc==SQLITE_OK && currentSize!=newSize ){ if( currentSize>newSize ){ rc = sqlite3OsTruncate(pPager->fd, newSize); }else if( (currentSize+szPage)<=newSize ){ char *pTmp = pPager->pTmpSpace; memset(pTmp, 0, szPage); testcase( (newSize-szPage) == currentSize ); testcase( (newSize-szPage) > currentSize ); rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage); } if( rc==SQLITE_OK ){ pPager->dbFileSize = nPage; } } } return rc; } /* ** Return a sanitized version of the sector-size of OS file pFile. The ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE. */ SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){ int iRet = sqlite3OsSectorSize(pFile); if( iRet<32 ){ iRet = 512; }else if( iRet>MAX_SECTOR_SIZE ){ assert( MAX_SECTOR_SIZE>=512 ); iRet = MAX_SECTOR_SIZE; } return iRet; } /* ** Set the value of the Pager.sectorSize variable for the given ** pager based on the value returned by the xSectorSize method ** of the open database file. The sector size will be used ** to determine the size and alignment of journal header and ** master journal pointers within created journal files. ** ** For temporary files the effective sector size is always 512 bytes. ** ** Otherwise, for non-temporary files, the effective sector size is ** the value returned by the xSectorSize() method rounded up to 32 if ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it ** is greater than MAX_SECTOR_SIZE. ** ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set ** the effective sector size to its minimum value (512). The purpose of ** pPager->sectorSize is to define the "blast radius" of bytes that ** might change if a crash occurs while writing to a single byte in ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector ** size. For backwards compatibility of the rollback journal file format, ** we cannot reduce the effective sector size below 512. */ static void setSectorSize(Pager *pPager){ assert( isOpen(pPager->fd) || pPager->tempFile ); if( pPager->tempFile || (sqlite3OsDeviceCharacteristics(pPager->fd) & SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0 ){ /* Sector size doesn't matter for temporary files. Also, the file ** may not have been opened yet, in which case the OsSectorSize() ** call will segfault. */ pPager->sectorSize = 512; }else{ pPager->sectorSize = sqlite3SectorSize(pPager->fd); } } /* ** Playback the journal and thus restore the database file to ** the state it was in before we started making changes. ** ** The journal file format is as follows: ** ** (1) 8 byte prefix. A copy of aJournalMagic[]. ** (2) 4 byte big-endian integer which is the number of valid page records ** in the journal. If this value is 0xffffffff, then compute the ** number of page records from the journal size. ** (3) 4 byte big-endian integer which is the initial value for the ** sanity checksum. ** (4) 4 byte integer which is the number of pages to truncate the ** database to during a rollback. ** (5) 4 byte big-endian integer which is the sector size. The header ** is this many bytes in size. ** (6) 4 byte big-endian integer which is the page size. ** (7) zero padding out to the next sector size. ** (8) Zero or more pages instances, each as follows: ** + 4 byte page number. ** + pPager->pageSize bytes of data. ** + 4 byte checksum ** ** When we speak of the journal header, we mean the first 7 items above. ** Each entry in the journal is an instance of the 8th item. ** ** Call the value from the second bullet "nRec". nRec is the number of ** valid page entries in the journal. In most cases, you can compute the ** value of nRec from the size of the journal file. But if a power ** failure occurred while the journal was being written, it could be the ** case that the size of the journal file had already been increased but ** the extra entries had not yet made it safely to disk. In such a case, ** the value of nRec computed from the file size would be too large. For ** that reason, we always use the nRec value in the header. ** ** If the nRec value is 0xffffffff it means that nRec should be computed ** from the file size. This value is used when the user selects the ** no-sync option for the journal. A power failure could lead to corruption ** in this case. But for things like temporary table (which will be ** deleted when the power is restored) we don't care. ** ** If the file opened as the journal file is not a well-formed ** journal file then all pages up to the first corrupted page are rolled ** back (or no pages if the journal header is corrupted). The journal file ** is then deleted and SQLITE_OK returned, just as if no corruption had ** been encountered. ** ** If an I/O or malloc() error occurs, the journal-file is not deleted ** and an error code is returned. ** ** The isHot parameter indicates that we are trying to rollback a journal ** that might be a hot journal. Or, it could be that the journal is ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE. ** If the journal really is hot, reset the pager cache prior rolling ** back any content. If the journal is merely persistent, no reset is ** needed. */ static int pager_playback(Pager *pPager, int isHot){ sqlite3_vfs *pVfs = pPager->pVfs; i64 szJ; /* Size of the journal file in bytes */ u32 nRec; /* Number of Records in the journal */ u32 u; /* Unsigned loop counter */ Pgno mxPg = 0; /* Size of the original file in pages */ int rc; /* Result code of a subroutine */ int res = 1; /* Value returned by sqlite3OsAccess() */ char *zMaster = 0; /* Name of master journal file if any */ int needPagerReset; /* True to reset page prior to first page rollback */ int nPlayback = 0; /* Total number of pages restored from journal */ /* Figure out how many records are in the journal. Abort early if ** the journal is empty. */ assert( isOpen(pPager->jfd) ); rc = sqlite3OsFileSize(pPager->jfd, &szJ); if( rc!=SQLITE_OK ){ goto end_playback; } /* Read the master journal name from the journal, if it is present. ** If a master journal file name is specified, but the file is not ** present on disk, then the journal is not hot and does not need to be ** played back. ** ** TODO: Technically the following is an error because it assumes that ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, ** mxPathname is 512, which is the same as the minimum allowable value ** for pageSize. */ zMaster = pPager->pTmpSpace; rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); if( rc==SQLITE_OK && zMaster[0] ){ rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); } zMaster = 0; if( rc!=SQLITE_OK || !res ){ goto end_playback; } pPager->journalOff = 0; needPagerReset = isHot; /* This loop terminates either when a readJournalHdr() or ** pager_playback_one_page() call returns SQLITE_DONE or an IO error ** occurs. */ while( 1 ){ /* Read the next journal header from the journal file. If there are ** not enough bytes left in the journal file for a complete header, or ** it is corrupted, then a process must have failed while writing it. ** This indicates nothing more needs to be rolled back. */ rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg); if( rc!=SQLITE_OK ){ if( rc==SQLITE_DONE ){ rc = SQLITE_OK; } goto end_playback; } /* If nRec is 0xffffffff, then this journal was created by a process ** working in no-sync mode. This means that the rest of the journal ** file consists of pages, there are no more journal headers. Compute ** the value of nRec based on this assumption. */ if( nRec==0xffffffff ){ assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ); nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager)); } /* If nRec is 0 and this rollback is of a transaction created by this ** process and if this is the final header in the journal, then it means ** that this part of the journal was being filled but has not yet been ** synced to disk. Compute the number of pages based on the remaining ** size of the file. ** ** The third term of the test was added to fix ticket #2565. ** When rolling back a hot journal, nRec==0 always means that the next ** chunk of the journal contains zero pages to be rolled back. But ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in ** the journal, it means that the journal might contain additional ** pages that need to be rolled back and that the number of pages ** should be computed based on the journal file size. */ if( nRec==0 && !isHot && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){ nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager)); } /* If this is the first header read from the journal, truncate the ** database file back to its original size. */ if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){ rc = pager_truncate(pPager, mxPg); if( rc!=SQLITE_OK ){ goto end_playback; } pPager->dbSize = mxPg; } /* Copy original pages out of the journal and back into the ** database file and/or page cache. */ for(u=0; u<nRec; u++){ if( needPagerReset ){ pager_reset(pPager); needPagerReset = 0; } rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0); if( rc==SQLITE_OK ){ nPlayback++; }else{ if( rc==SQLITE_DONE ){ pPager->journalOff = szJ; break; }else if( rc==SQLITE_IOERR_SHORT_READ ){ /* If the journal has been truncated, simply stop reading and ** processing the journal. This might happen if the journal was ** not completely written and synced prior to a crash. In that ** case, the database should have never been written in the ** first place so it is OK to simply abandon the rollback. */ rc = SQLITE_OK; goto end_playback; }else{ /* If we are unable to rollback, quit and return the error ** code. This will cause the pager to enter the error state ** so that no further harm will be done. Perhaps the next ** process to come along will be able to rollback the database. */ goto end_playback; } } } } /*NOTREACHED*/ assert( 0 ); end_playback: /* Following a rollback, the database file should be back in its original ** state prior to the start of the transaction, so invoke the ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the ** assertion that the transaction counter was modified. */ #ifdef SQLITE_DEBUG if( pPager->fd->pMethods ){ sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0); } #endif /* If this playback is happening automatically as a result of an IO or ** malloc error that occurred after the change-counter was updated but ** before the transaction was committed, then the change-counter ** modification may just have been reverted. If this happens in exclusive ** mode, then subsequent transactions performed by the connection will not ** update the change-counter at all. This may lead to cache inconsistency ** problems for other processes at some point in the future. So, just ** in case this has happened, clear the changeCountDone flag now. */ pPager->changeCountDone = pPager->tempFile; if( rc==SQLITE_OK ){ zMaster = pPager->pTmpSpace; rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); testcase( rc!=SQLITE_OK ); } if( rc==SQLITE_OK && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) ){ rc = sqlite3PagerSync(pPager, 0); } if( rc==SQLITE_OK ){ rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0); testcase( rc!=SQLITE_OK ); } if( rc==SQLITE_OK && zMaster[0] && res ){ /* If there was a master journal and this routine will return success, ** see if it is possible to delete the master journal. */ rc = pager_delmaster(pPager, zMaster); testcase( rc!=SQLITE_OK ); } if( isHot && nPlayback ){ sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s", nPlayback, pPager->zJournal); } /* The Pager.sectorSize variable may have been updated while rolling ** back a journal created by a process with a different sector size ** value. Reset it to the correct value for this process. */ setSectorSize(pPager); return rc; } /* ** Read the content for page pPg out of the database file and into ** pPg->pData. A shared lock or greater must be held on the database ** file before this function is called. ** ** If page 1 is read, then the value of Pager.dbFileVers[] is set to ** the value read from the database file. ** ** If an IO error occurs, then the IO error is returned to the caller. ** Otherwise, SQLITE_OK is returned. */ static int readDbPage(PgHdr *pPg, u32 iFrame){ Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */ Pgno pgno = pPg->pgno; /* Page number to read */ int rc = SQLITE_OK; /* Return code */ int pgsz = pPager->pageSize; /* Number of bytes to read */ assert( pPager->eState>=PAGER_READER && !MEMDB ); assert( isOpen(pPager->fd) ); #ifndef SQLITE_OMIT_WAL if( iFrame ){ /* Try to pull the page from the write-ahead log. */ rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData); }else #endif { i64 iOffset = (pgno-1)*(i64)pPager->pageSize; rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } } if( pgno==1 ){ if( rc ){ /* If the read is unsuccessful, set the dbFileVers[] to something ** that will never be a valid file version. dbFileVers[] is a copy ** of bytes 24..39 of the database. Bytes 28..31 should always be ** zero or the size of the database in page. Bytes 32..35 and 35..39 ** should be page numbers which are never 0xffffffff. So filling ** pPager->dbFileVers[] with all 0xff bytes should suffice. ** ** For an encrypted database, the situation is more complex: bytes ** 24..39 of the database are white noise. But the probability of ** white noise equaling 16 bytes of 0xff is vanishingly small so ** we should still be ok. */ memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers)); }else{ u8 *dbFileVers = &((u8*)pPg->pData)[24]; memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); } } CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT); PAGER_INCR(sqlite3_pager_readdb_count); PAGER_INCR(pPager->nRead); IOTRACE(("PGIN %p %d\n", pPager, pgno)); PAGERTRACE(("FETCH %d page %d hash(%08x)\n", PAGERID(pPager), pgno, pager_pagehash(pPg))); return rc; } /* ** Update the value of the change-counter at offsets 24 and 92 in ** the header and the sqlite version number at offset 96. ** ** This is an unconditional update. See also the pager_incr_changecounter() ** routine which only updates the change-counter if the update is actually ** needed, as determined by the pPager->changeCountDone state variable. */ static void pager_write_changecounter(PgHdr *pPg){ u32 change_counter; /* Increment the value just read and write it back to byte 24. */ change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1; put32bits(((char*)pPg->pData)+24, change_counter); /* Also store the SQLite version number in bytes 96..99 and in ** bytes 92..95 store the change counter for which the version number ** is valid. */ put32bits(((char*)pPg->pData)+92, change_counter); put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER); } #ifndef SQLITE_OMIT_WAL /* ** This function is invoked once for each page that has already been ** written into the log file when a WAL transaction is rolled back. ** Parameter iPg is the page number of said page. The pCtx argument ** is actually a pointer to the Pager structure. ** ** If page iPg is present in the cache, and has no outstanding references, ** it is discarded. Otherwise, if there are one or more outstanding ** references, the page content is reloaded from the database. If the ** attempt to reload content from the database is required and fails, ** return an SQLite error code. Otherwise, SQLITE_OK. */ static int pagerUndoCallback(void *pCtx, Pgno iPg){ int rc = SQLITE_OK; Pager *pPager = (Pager *)pCtx; PgHdr *pPg; assert( pagerUseWal(pPager) ); pPg = sqlite3PagerLookup(pPager, iPg); if( pPg ){ if( sqlite3PcachePageRefcount(pPg)==1 ){ sqlite3PcacheDrop(pPg); }else{ u32 iFrame = 0; rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame); if( rc==SQLITE_OK ){ rc = readDbPage(pPg, iFrame); } if( rc==SQLITE_OK ){ pPager->xReiniter(pPg); } sqlite3PagerUnrefNotNull(pPg); } } /* Normally, if a transaction is rolled back, any backup processes are ** updated as data is copied out of the rollback journal and into the ** database. This is not generally possible with a WAL database, as ** rollback involves simply truncating the log file. Therefore, if one ** or more frames have already been written to the log (and therefore ** also copied into the backup databases) as part of this transaction, ** the backups must be restarted. */ sqlite3BackupRestart(pPager->pBackup); return rc; } /* ** This function is called to rollback a transaction on a WAL database. */ static int pagerRollbackWal(Pager *pPager){ int rc; /* Return Code */ PgHdr *pList; /* List of dirty pages to revert */ /* For all pages in the cache that are currently dirty or have already ** been written (but not committed) to the log file, do one of the ** following: ** ** + Discard the cached page (if refcount==0), or ** + Reload page content from the database (if refcount>0). */ pPager->dbSize = pPager->dbOrigSize; rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager); pList = sqlite3PcacheDirtyList(pPager->pPCache); while( pList && rc==SQLITE_OK ){ PgHdr *pNext = pList->pDirty; rc = pagerUndoCallback((void *)pPager, pList->pgno); pList = pNext; } return rc; } /* ** This function is a wrapper around sqlite3WalFrames(). As well as logging ** the contents of the list of pages headed by pList (connected by pDirty), ** this function notifies any active backup processes that the pages have ** changed. ** ** The list of pages passed into this routine is always sorted by page number. ** Hence, if page 1 appears anywhere on the list, it will be the first page. */ static int pagerWalFrames( Pager *pPager, /* Pager object */ PgHdr *pList, /* List of frames to log */ Pgno nTruncate, /* Database size after this commit */ int isCommit /* True if this is a commit */ ){ int rc; /* Return code */ int nList; /* Number of pages in pList */ PgHdr *p; /* For looping over pages */ assert( pPager->pWal ); assert( pList ); #ifdef SQLITE_DEBUG /* Verify that the page list is in accending order */ for(p=pList; p && p->pDirty; p=p->pDirty){ assert( p->pgno < p->pDirty->pgno ); } #endif assert( pList->pDirty==0 || isCommit ); if( isCommit ){ /* If a WAL transaction is being committed, there is no point in writing ** any pages with page numbers greater than nTruncate into the WAL file. ** They will never be read by any client. So remove them from the pDirty ** list here. */ PgHdr **ppNext = &pList; nList = 0; for(p=pList; (*ppNext = p)!=0; p=p->pDirty){ if( p->pgno<=nTruncate ){ ppNext = &p->pDirty; nList++; } } assert( pList ); }else{ nList = 1; } pPager->aStat[PAGER_STAT_WRITE] += nList; if( pList->pgno==1 ) pager_write_changecounter(pList); rc = sqlite3WalFrames(pPager->pWal, pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags ); if( rc==SQLITE_OK && pPager->pBackup ){ for(p=pList; p; p=p->pDirty){ sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData); } } #ifdef SQLITE_CHECK_PAGES pList = sqlite3PcacheDirtyList(pPager->pPCache); for(p=pList; p; p=p->pDirty){ pager_set_pagehash(p); } #endif return rc; } /* ** Begin a read transaction on the WAL. ** ** This routine used to be called "pagerOpenSnapshot()" because it essentially ** makes a snapshot of the database at the current point in time and preserves ** that snapshot for use by the reader in spite of concurrently changes by ** other writers or checkpointers. */ static int pagerBeginReadTransaction(Pager *pPager){ int rc; /* Return code */ int changed = 0; /* True if cache must be reset */ assert( pagerUseWal(pPager) ); assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); /* sqlite3WalEndReadTransaction() was not called for the previous ** transaction in locking_mode=EXCLUSIVE. So call it now. If we ** are in locking_mode=NORMAL and EndRead() was previously called, ** the duplicate call is harmless. */ sqlite3WalEndReadTransaction(pPager->pWal); rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed); if( rc!=SQLITE_OK || changed ){ pager_reset(pPager); if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); } return rc; } #endif /* ** This function is called as part of the transition from PAGER_OPEN ** to PAGER_READER state to determine the size of the database file ** in pages (assuming the page size currently stored in Pager.pageSize). ** ** If no error occurs, SQLITE_OK is returned and the size of the database ** in pages is stored in *pnPage. Otherwise, an error code (perhaps ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified. */ static int pagerPagecount(Pager *pPager, Pgno *pnPage){ Pgno nPage; /* Value to return via *pnPage */ /* Query the WAL sub-system for the database size. The WalDbsize() ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or ** if the database size is not available. The database size is not ** available from the WAL sub-system if the log file is empty or ** contains no valid committed transactions. */ assert( pPager->eState==PAGER_OPEN ); assert( pPager->eLock>=SHARED_LOCK ); assert( isOpen(pPager->fd) ); assert( pPager->tempFile==0 ); nPage = sqlite3WalDbsize(pPager->pWal); /* If the number of pages in the database is not available from the ** WAL sub-system, determine the page counte based on the size of ** the database file. If the size of the database file is not an ** integer multiple of the page-size, round up the result. */ if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){ i64 n = 0; /* Size of db file in bytes */ int rc = sqlite3OsFileSize(pPager->fd, &n); if( rc!=SQLITE_OK ){ return rc; } nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize); } /* If the current number of pages in the file is greater than the ** configured maximum pager number, increase the allowed limit so ** that the file can be read. */ if( nPage>pPager->mxPgno ){ pPager->mxPgno = (Pgno)nPage; } *pnPage = nPage; return SQLITE_OK; } #ifndef SQLITE_OMIT_WAL /* ** Check if the *-wal file that corresponds to the database opened by pPager ** exists if the database is not empy, or verify that the *-wal file does ** not exist (by deleting it) if the database file is empty. ** ** If the database is not empty and the *-wal file exists, open the pager ** in WAL mode. If the database is empty or if no *-wal file exists and ** if no error occurs, make sure Pager.journalMode is not set to ** PAGER_JOURNALMODE_WAL. ** ** Return SQLITE_OK or an error code. ** ** The caller must hold a SHARED lock on the database file to call this ** function. Because an EXCLUSIVE lock on the db file is required to delete ** a WAL on a none-empty database, this ensures there is no race condition ** between the xAccess() below and an xDelete() being executed by some ** other connection. */ static int pagerOpenWalIfPresent(Pager *pPager){ int rc = SQLITE_OK; assert( pPager->eState==PAGER_OPEN ); assert( pPager->eLock>=SHARED_LOCK ); if( !pPager->tempFile ){ int isWal; /* True if WAL file exists */ Pgno nPage; /* Size of the database file */ rc = pagerPagecount(pPager, &nPage); if( rc ) return rc; if( nPage==0 ){ rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0); if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK; isWal = 0; }else{ rc = sqlite3OsAccess( pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal ); } if( rc==SQLITE_OK ){ if( isWal ){ testcase( sqlite3PcachePagecount(pPager->pPCache)==0 ); rc = sqlite3PagerOpenWal(pPager, 0); }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){ pPager->journalMode = PAGER_JOURNALMODE_DELETE; } } } return rc; } #endif /* ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback ** the entire master journal file. The case pSavepoint==NULL occurs when ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction ** savepoint. ** ** When pSavepoint is not NULL (meaning a non-transaction savepoint is ** being rolled back), then the rollback consists of up to three stages, ** performed in the order specified: ** ** * Pages are played back from the main journal starting at byte ** offset PagerSavepoint.iOffset and continuing to ** PagerSavepoint.iHdrOffset, or to the end of the main journal ** file if PagerSavepoint.iHdrOffset is zero. ** ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played ** back starting from the journal header immediately following ** PagerSavepoint.iHdrOffset to the end of the main journal file. ** ** * Pages are then played back from the sub-journal file, starting ** with the PagerSavepoint.iSubRec and continuing to the end of ** the journal file. ** ** Throughout the rollback process, each time a page is rolled back, the ** corresponding bit is set in a bitvec structure (variable pDone in the ** implementation below). This is used to ensure that a page is only ** rolled back the first time it is encountered in either journal. ** ** If pSavepoint is NULL, then pages are only played back from the main ** journal file. There is no need for a bitvec in this case. ** ** In either case, before playback commences the Pager.dbSize variable ** is reset to the value that it held at the start of the savepoint ** (or transaction). No page with a page-number greater than this value ** is played back. If one is encountered it is simply skipped. */ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ i64 szJ; /* Effective size of the main journal */ i64 iHdrOff; /* End of first segment of main-journal records */ int rc = SQLITE_OK; /* Return code */ Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */ assert( pPager->eState!=PAGER_ERROR ); assert( pPager->eState>=PAGER_WRITER_LOCKED ); /* Allocate a bitvec to use to store the set of pages rolled back */ if( pSavepoint ){ pDone = sqlite3BitvecCreate(pSavepoint->nOrig); if( !pDone ){ return SQLITE_NOMEM_BKPT; } } /* Set the database size back to the value it was before the savepoint ** being reverted was opened. */ pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize; pPager->changeCountDone = pPager->tempFile; if( !pSavepoint && pagerUseWal(pPager) ){ return pagerRollbackWal(pPager); } /* Use pPager->journalOff as the effective size of the main rollback ** journal. The actual file might be larger than this in ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything ** past pPager->journalOff is off-limits to us. */ szJ = pPager->journalOff; assert( pagerUseWal(pPager)==0 || szJ==0 ); /* Begin by rolling back records from the main journal starting at ** PagerSavepoint.iOffset and continuing to the next journal header. ** There might be records in the main journal that have a page number ** greater than the current database size (pPager->dbSize) but those ** will be skipped automatically. Pages are added to pDone as they ** are played back. */ if( pSavepoint && !pagerUseWal(pPager) ){ iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ; pPager->journalOff = pSavepoint->iOffset; while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){ rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1); } assert( rc!=SQLITE_DONE ); }else{ pPager->journalOff = 0; } /* Continue rolling back records out of the main journal starting at ** the first journal header seen and continuing until the effective end ** of the main journal file. Continue to skip out-of-range pages and ** continue adding pages rolled back to pDone. */ while( rc==SQLITE_OK && pPager->journalOff<szJ ){ u32 ii; /* Loop counter */ u32 nJRec = 0; /* Number of Journal Records */ u32 dummy; rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy); assert( rc!=SQLITE_DONE ); /* ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff" ** test is related to ticket #2565. See the discussion in the ** pager_playback() function for additional information. */ if( nJRec==0 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){ nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager)); } for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){ rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1); } assert( rc!=SQLITE_DONE ); } assert( rc!=SQLITE_OK || pPager->journalOff>=szJ ); /* Finally, rollback pages from the sub-journal. Page that were ** previously rolled back out of the main journal (and are hence in pDone) ** will be skipped. Out-of-range pages are also skipped. */ if( pSavepoint ){ u32 ii; /* Loop counter */ i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize); if( pagerUseWal(pPager) ){ rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData); } for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){ assert( offset==(i64)ii*(4+pPager->pageSize) ); rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1); } assert( rc!=SQLITE_DONE ); } sqlite3BitvecDestroy(pDone); if( rc==SQLITE_OK ){ pPager->journalOff = szJ; } return rc; } /* ** Change the maximum number of in-memory pages that are allowed ** before attempting to recycle clean and unused pages. */ SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){ sqlite3PcacheSetCachesize(pPager->pPCache, mxPage); } /* ** Change the maximum number of in-memory pages that are allowed ** before attempting to spill pages to journal. */ SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){ return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage); } /* ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap. */ static void pagerFixMaplimit(Pager *pPager){ #if SQLITE_MAX_MMAP_SIZE>0 sqlite3_file *fd = pPager->fd; if( isOpen(fd) && fd->pMethods->iVersion>=3 ){ sqlite3_int64 sz; sz = pPager->szMmap; pPager->bUseFetch = (sz>0); setGetterMethod(pPager); sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz); } #endif } /* ** Change the maximum size of any memory mapping made of the database file. */ SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){ pPager->szMmap = szMmap; pagerFixMaplimit(pPager); } /* ** Free as much memory as possible from the pager. */ SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){ sqlite3PcacheShrink(pPager->pPCache); } /* ** Adjust settings of the pager to those specified in the pgFlags parameter. ** ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness ** of the database to damage due to OS crashes or power failures by ** changing the number of syncs()s when writing the journals. ** There are four levels: ** ** OFF sqlite3OsSync() is never called. This is the default ** for temporary and transient files. ** ** NORMAL The journal is synced once before writes begin on the ** database. This is normally adequate protection, but ** it is theoretically possible, though very unlikely, ** that an inopertune power failure could leave the journal ** in a state which would cause damage to the database ** when it is rolled back. ** ** FULL The journal is synced twice before writes begin on the ** database (with some additional information - the nRec field ** of the journal header - being written in between the two ** syncs). If we assume that writing a ** single disk sector is atomic, then this mode provides ** assurance that the journal will not be corrupted to the ** point of causing damage to the database during rollback. ** ** EXTRA This is like FULL except that is also syncs the directory ** that contains the rollback journal after the rollback ** journal is unlinked. ** ** The above is for a rollback-journal mode. For WAL mode, OFF continues ** to mean that no syncs ever occur. NORMAL means that the WAL is synced ** prior to the start of checkpoint and that the database file is synced ** at the conclusion of the checkpoint if the entire content of the WAL ** was written back into the database. But no sync operations occur for ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL ** file is synced following each commit operation, in addition to the ** syncs associated with NORMAL. There is no difference between FULL ** and EXTRA for WAL mode. ** ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the ** synchronous=FULL versus synchronous=NORMAL setting determines when ** the xSync primitive is called and is relevant to all platforms. ** ** Numeric values associated with these states are OFF==1, NORMAL=2, ** and FULL=3. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS SQLITE_PRIVATE void sqlite3PagerSetFlags( Pager *pPager, /* The pager to set safety level for */ unsigned pgFlags /* Various flags */ ){ unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK; if( pPager->tempFile ){ pPager->noSync = 1; pPager->fullSync = 0; pPager->extraSync = 0; }else{ pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0; pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0; pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0; } if( pPager->noSync ){ pPager->syncFlags = 0; pPager->ckptSyncFlags = 0; }else if( pgFlags & PAGER_FULLFSYNC ){ pPager->syncFlags = SQLITE_SYNC_FULL; pPager->ckptSyncFlags = SQLITE_SYNC_FULL; }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){ pPager->syncFlags = SQLITE_SYNC_NORMAL; pPager->ckptSyncFlags = SQLITE_SYNC_FULL; }else{ pPager->syncFlags = SQLITE_SYNC_NORMAL; pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; } pPager->walSyncFlags = pPager->syncFlags; if( pPager->fullSync ){ pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS; } if( pgFlags & PAGER_CACHESPILL ){ pPager->doNotSpill &= ~SPILLFLAG_OFF; }else{ pPager->doNotSpill |= SPILLFLAG_OFF; } } #endif /* ** The following global variable is incremented whenever the library ** attempts to open a temporary file. This information is used for ** testing and analysis only. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_opentemp_count = 0; #endif /* ** Open a temporary file. ** ** Write the file descriptor into *pFile. Return SQLITE_OK on success ** or some other error code if we fail. The OS will automatically ** delete the temporary file when it is closed. ** ** The flags passed to the VFS layer xOpen() call are those specified ** by parameter vfsFlags ORed with the following: ** ** SQLITE_OPEN_READWRITE ** SQLITE_OPEN_CREATE ** SQLITE_OPEN_EXCLUSIVE ** SQLITE_OPEN_DELETEONCLOSE */ static int pagerOpentemp( Pager *pPager, /* The pager object */ sqlite3_file *pFile, /* Write the file descriptor here */ int vfsFlags /* Flags passed through to the VFS */ ){ int rc; /* Return code */ #ifdef SQLITE_TEST sqlite3_opentemp_count++; /* Used for testing and analysis only */ #endif vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0); assert( rc!=SQLITE_OK || isOpen(pFile) ); return rc; } /* ** Set the busy handler function. ** ** The pager invokes the busy-handler if sqlite3OsLock() returns ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE ** lock. It does *not* invoke the busy handler when upgrading from ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE ** (which occurs during hot-journal rollback). Summary: ** ** Transition | Invokes xBusyHandler ** -------------------------------------------------------- ** NO_LOCK -> SHARED_LOCK | Yes ** SHARED_LOCK -> RESERVED_LOCK | No ** SHARED_LOCK -> EXCLUSIVE_LOCK | No ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes ** ** If the busy-handler callback returns non-zero, the lock is ** retried. If it returns zero, then the SQLITE_BUSY error is ** returned to the caller of the pager API function. */ SQLITE_PRIVATE void sqlite3PagerSetBusyhandler( Pager *pPager, /* Pager object */ int (*xBusyHandler)(void *), /* Pointer to busy-handler function */ void *pBusyHandlerArg /* Argument to pass to xBusyHandler */ ){ pPager->xBusyHandler = xBusyHandler; pPager->pBusyHandlerArg = pBusyHandlerArg; if( isOpen(pPager->fd) ){ void **ap = (void **)&pPager->xBusyHandler; assert( ((int(*)(void *))(ap[0]))==xBusyHandler ); assert( ap[1]==pBusyHandlerArg ); sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap); } } /* ** Change the page size used by the Pager object. The new page size ** is passed in *pPageSize. ** ** If the pager is in the error state when this function is called, it ** is a no-op. The value returned is the error state error code (i.e. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL). ** ** Otherwise, if all of the following are true: ** ** * the new page size (value of *pPageSize) is valid (a power ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and ** ** * there are no outstanding page references, and ** ** * the database is either not an in-memory database or it is ** an in-memory database that currently consists of zero pages. ** ** then the pager object page size is set to *pPageSize. ** ** If the page size is changed, then this function uses sqlite3PagerMalloc() ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. ** In all other cases, SQLITE_OK is returned. ** ** If the page size is not changed, either because one of the enumerated ** conditions above is not true, the pager was in error state when this ** function was called, or because the memory allocation attempt failed, ** then *pPageSize is set to the old, retained page size before returning. */ SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){ int rc = SQLITE_OK; /* It is not possible to do a full assert_pager_state() here, as this ** function may be called from within PagerOpen(), before the state ** of the Pager object is internally consistent. ** ** At one point this function returned an error if the pager was in ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that ** there is at least one outstanding page reference, this function ** is a no-op for that case anyhow. */ u32 pageSize = *pPageSize; assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) ); if( (pPager->memDb==0 || pPager->dbSize==0) && sqlite3PcacheRefCount(pPager->pPCache)==0 && pageSize && pageSize!=(u32)pPager->pageSize ){ char *pNew = NULL; /* New temp space */ i64 nByte = 0; if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){ rc = sqlite3OsFileSize(pPager->fd, &nByte); } if( rc==SQLITE_OK ){ pNew = (char *)sqlite3PageMalloc(pageSize); if( !pNew ) rc = SQLITE_NOMEM_BKPT; } if( rc==SQLITE_OK ){ pager_reset(pPager); rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize); } if( rc==SQLITE_OK ){ sqlite3PageFree(pPager->pTmpSpace); pPager->pTmpSpace = pNew; pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize); pPager->pageSize = pageSize; }else{ sqlite3PageFree(pNew); } } *pPageSize = pPager->pageSize; if( rc==SQLITE_OK ){ if( nReserve<0 ) nReserve = pPager->nReserve; assert( nReserve>=0 && nReserve<1000 ); pPager->nReserve = (i16)nReserve; pagerReportSize(pPager); pagerFixMaplimit(pPager); } return rc; } /* ** Return a pointer to the "temporary page" buffer held internally ** by the pager. This is a buffer that is big enough to hold the ** entire content of a database page. This buffer is used internally ** during rollback and will be overwritten whenever a rollback ** occurs. But other modules are free to use it too, as long as ** no rollbacks are happening. */ SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){ return pPager->pTmpSpace; } /* ** Attempt to set the maximum database page count if mxPage is positive. ** Make no changes if mxPage is zero or negative. And never reduce the ** maximum page count below the current size of the database. ** ** Regardless of mxPage, return the current maximum page count. */ SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){ if( mxPage>0 ){ pPager->mxPgno = mxPage; } assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */ assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */ return pPager->mxPgno; } /* ** The following set of routines are used to disable the simulated ** I/O error mechanism. These routines are used to avoid simulated ** errors in places where we do not care about errors. ** ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops ** and generate no code. */ #ifdef SQLITE_TEST SQLITE_API extern int sqlite3_io_error_pending; SQLITE_API extern int sqlite3_io_error_hit; static int saved_cnt; void disable_simulated_io_errors(void){ saved_cnt = sqlite3_io_error_pending; sqlite3_io_error_pending = -1; } void enable_simulated_io_errors(void){ sqlite3_io_error_pending = saved_cnt; } #else # define disable_simulated_io_errors() # define enable_simulated_io_errors() #endif /* ** Read the first N bytes from the beginning of the file into memory ** that pDest points to. ** ** If the pager was opened on a transient file (zFilename==""), or ** opened on a file less than N bytes in size, the output buffer is ** zeroed and SQLITE_OK returned. The rationale for this is that this ** function is used to read database headers, and a new transient or ** zero sized database has a header than consists entirely of zeroes. ** ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered, ** the error code is returned to the caller and the contents of the ** output buffer undefined. */ SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){ int rc = SQLITE_OK; memset(pDest, 0, N); assert( isOpen(pPager->fd) || pPager->tempFile ); /* This routine is only called by btree immediately after creating ** the Pager object. There has not been an opportunity to transition ** to WAL mode yet. */ assert( !pagerUseWal(pPager) ); if( isOpen(pPager->fd) ){ IOTRACE(("DBHDR %p 0 %d\n", pPager, N)) rc = sqlite3OsRead(pPager->fd, pDest, N, 0); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } } return rc; } /* ** This function may only be called when a read-transaction is open on ** the pager. It returns the total number of pages in the database. ** ** However, if the file is between 1 and <page-size> bytes in size, then ** this is considered a 1 page file. */ SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){ assert( pPager->eState>=PAGER_READER ); assert( pPager->eState!=PAGER_WRITER_FINISHED ); *pnPage = (int)pPager->dbSize; } /* ** Try to obtain a lock of type locktype on the database file. If ** a similar or greater lock is already held, this function is a no-op ** (returning SQLITE_OK immediately). ** ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke ** the busy callback if the lock is currently not available. Repeat ** until the busy callback returns false or until the attempt to ** obtain the lock succeeds. ** ** Return SQLITE_OK on success and an error code if we cannot obtain ** the lock. If the lock is obtained successfully, set the Pager.state ** variable to locktype before returning. */ static int pager_wait_on_lock(Pager *pPager, int locktype){ int rc; /* Return code */ /* Check that this is either a no-op (because the requested lock is ** already held), or one of the transitions that the busy-handler ** may be invoked during, according to the comment above ** sqlite3PagerSetBusyhandler(). */ assert( (pPager->eLock>=locktype) || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK) || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK) ); do { rc = pagerLockDb(pPager, locktype); }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) ); return rc; } /* ** Function assertTruncateConstraint(pPager) checks that one of the ** following is true for all dirty pages currently in the page-cache: ** ** a) The page number is less than or equal to the size of the ** current database image, in pages, OR ** ** b) if the page content were written at this time, it would not ** be necessary to write the current content out to the sub-journal ** (as determined by function subjRequiresPage()). ** ** If the condition asserted by this function were not true, and the ** dirty page were to be discarded from the cache via the pagerStress() ** routine, pagerStress() would not write the current page content to ** the database file. If a savepoint transaction were rolled back after ** this happened, the correct behavior would be to restore the current ** content of the page. However, since this content is not present in either ** the database file or the portion of the rollback journal and ** sub-journal rolled back the content could not be restored and the ** database image would become corrupt. It is therefore fortunate that ** this circumstance cannot arise. */ #if defined(SQLITE_DEBUG) static void assertTruncateConstraintCb(PgHdr *pPg){ assert( pPg->flags&PGHDR_DIRTY ); assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize ); } static void assertTruncateConstraint(Pager *pPager){ sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb); } #else # define assertTruncateConstraint(pPager) #endif /* ** Truncate the in-memory database file image to nPage pages. This ** function does not actually modify the database file on disk. It ** just sets the internal state of the pager object so that the ** truncation will be done when the current transaction is committed. ** ** This function is only called right before committing a transaction. ** Once this function has been called, the transaction must either be ** rolled back or committed. It is not safe to call this function and ** then continue writing to the database. */ SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ assert( pPager->dbSize>=nPage ); assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); pPager->dbSize = nPage; /* At one point the code here called assertTruncateConstraint() to ** ensure that all pages being truncated away by this operation are, ** if one or more savepoints are open, present in the savepoint ** journal so that they can be restored if the savepoint is rolled ** back. This is no longer necessary as this function is now only ** called right before committing a transaction. So although the ** Pager object may still have open savepoints (Pager.nSavepoint!=0), ** they cannot be rolled back. So the assertTruncateConstraint() call ** is no longer correct. */ } /* ** This function is called before attempting a hot-journal rollback. It ** syncs the journal file to disk, then sets pPager->journalHdr to the ** size of the journal file so that the pager_playback() routine knows ** that the entire journal file has been synced. ** ** Syncing a hot-journal to disk before attempting to roll it back ensures ** that if a power-failure occurs during the rollback, the process that ** attempts rollback following system recovery sees the same journal ** content as this process. ** ** If everything goes as planned, SQLITE_OK is returned. Otherwise, ** an SQLite error code. */ static int pagerSyncHotJournal(Pager *pPager){ int rc = SQLITE_OK; if( !pPager->noSync ){ rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL); } if( rc==SQLITE_OK ){ rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr); } return rc; } #if SQLITE_MAX_MMAP_SIZE>0 /* ** Obtain a reference to a memory mapped page object for page number pgno. ** The new object will use the pointer pData, obtained from xFetch(). ** If successful, set *ppPage to point to the new page reference ** and return SQLITE_OK. Otherwise, return an SQLite error code and set ** *ppPage to zero. ** ** Page references obtained by calling this function should be released ** by calling pagerReleaseMapPage(). */ static int pagerAcquireMapPage( Pager *pPager, /* Pager object */ Pgno pgno, /* Page number */ void *pData, /* xFetch()'d data for this page */ PgHdr **ppPage /* OUT: Acquired page object */ ){ PgHdr *p; /* Memory mapped page to return */ if( pPager->pMmapFreelist ){ *ppPage = p = pPager->pMmapFreelist; pPager->pMmapFreelist = p->pDirty; p->pDirty = 0; assert( pPager->nExtra>=8 ); memset(p->pExtra, 0, 8); }else{ *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra); if( p==0 ){ sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData); return SQLITE_NOMEM_BKPT; } p->pExtra = (void *)&p[1]; p->flags = PGHDR_MMAP; p->nRef = 1; p->pPager = pPager; } assert( p->pExtra==(void *)&p[1] ); assert( p->pPage==0 ); assert( p->flags==PGHDR_MMAP ); assert( p->pPager==pPager ); assert( p->nRef==1 ); p->pgno = pgno; p->pData = pData; pPager->nMmapOut++; return SQLITE_OK; } #endif /* ** Release a reference to page pPg. pPg must have been returned by an ** earlier call to pagerAcquireMapPage(). */ static void pagerReleaseMapPage(PgHdr *pPg){ Pager *pPager = pPg->pPager; pPager->nMmapOut--; pPg->pDirty = pPager->pMmapFreelist; pPager->pMmapFreelist = pPg; assert( pPager->fd->pMethods->iVersion>=3 ); sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData); } /* ** Free all PgHdr objects stored in the Pager.pMmapFreelist list. */ static void pagerFreeMapHdrs(Pager *pPager){ PgHdr *p; PgHdr *pNext; for(p=pPager->pMmapFreelist; p; p=pNext){ pNext = p->pDirty; sqlite3_free(p); } } /* ** Shutdown the page cache. Free all memory and close all files. ** ** If a transaction was in progress when this routine is called, that ** transaction is rolled back. All outstanding pages are invalidated ** and their memory is freed. Any attempt to use a page associated ** with this page cache after this function returns will likely ** result in a coredump. ** ** This function always succeeds. If a transaction is active an attempt ** is made to roll it back. If an error occurs during the rollback ** a hot journal may be left in the filesystem but no error is returned ** to the caller. */ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){ u8 *pTmp = (u8 *)pPager->pTmpSpace; assert( db || pagerUseWal(pPager)==0 ); assert( assert_pager_state(pPager) ); disable_simulated_io_errors(); sqlite3BeginBenignMalloc(); pagerFreeMapHdrs(pPager); /* pPager->errCode = 0; */ pPager->exclusiveMode = 0; #ifndef SQLITE_OMIT_WAL assert( db || pPager->pWal==0 ); sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags, pPager->pageSize, (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp) ); pPager->pWal = 0; #endif pager_reset(pPager); if( MEMDB ){ pager_unlock(pPager); }else{ /* If it is open, sync the journal file before calling UnlockAndRollback. ** If this is not done, then an unsynced portion of the open journal ** file may be played back into the database. If a power failure occurs ** while this is happening, the database could become corrupt. ** ** If an error occurs while trying to sync the journal, shift the pager ** into the ERROR state. This causes UnlockAndRollback to unlock the ** database and close the journal file without attempting to roll it ** back or finalize it. The next database user will have to do hot-journal ** rollback before accessing the database file. */ if( isOpen(pPager->jfd) ){ pager_error(pPager, pagerSyncHotJournal(pPager)); } pagerUnlockAndRollback(pPager); } sqlite3EndBenignMalloc(); enable_simulated_io_errors(); PAGERTRACE(("CLOSE %d\n", PAGERID(pPager))); IOTRACE(("CLOSE %p\n", pPager)) sqlite3OsClose(pPager->jfd); sqlite3OsClose(pPager->fd); sqlite3PageFree(pTmp); sqlite3PcacheClose(pPager->pPCache); #ifdef SQLITE_HAS_CODEC if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); #endif assert( !pPager->aSavepoint && !pPager->pInJournal ); assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ); sqlite3_free(pPager); return SQLITE_OK; } #if !defined(NDEBUG) || defined(SQLITE_TEST) /* ** Return the page number for page pPg. */ SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){ return pPg->pgno; } #endif /* ** Increment the reference count for page pPg. */ SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){ sqlite3PcacheRef(pPg); } /* ** Sync the journal. In other words, make sure all the pages that have ** been written to the journal have actually reached the surface of the ** disk and can be restored in the event of a hot-journal rollback. ** ** If the Pager.noSync flag is set, then this function is a no-op. ** Otherwise, the actions required depend on the journal-mode and the ** device characteristics of the file-system, as follows: ** ** * If the journal file is an in-memory journal file, no action need ** be taken. ** ** * Otherwise, if the device does not support the SAFE_APPEND property, ** then the nRec field of the most recently written journal header ** is updated to contain the number of journal records that have ** been written following it. If the pager is operating in full-sync ** mode, then the journal file is synced before this field is updated. ** ** * If the device does not support the SEQUENTIAL property, then ** journal file is synced. ** ** Or, in pseudo-code: ** ** if( NOT <in-memory journal> ){ ** if( NOT SAFE_APPEND ){ ** if( <full-sync mode> ) xSync(<journal file>); ** <update nRec field> ** } ** if( NOT SEQUENTIAL ) xSync(<journal file>); ** } ** ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every ** page currently held in memory before returning SQLITE_OK. If an IO ** error is encountered, then the IO error code is returned to the caller. */ static int syncJournal(Pager *pPager, int newHdr){ int rc; /* Return code */ assert( pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD ); assert( assert_pager_state(pPager) ); assert( !pagerUseWal(pPager) ); rc = sqlite3PagerExclusiveLock(pPager); if( rc!=SQLITE_OK ) return rc; if( !pPager->noSync ){ assert( !pPager->tempFile ); if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){ const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); assert( isOpen(pPager->jfd) ); if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ /* This block deals with an obscure problem. If the last connection ** that wrote to this database was operating in persistent-journal ** mode, then the journal file may at this point actually be larger ** than Pager.journalOff bytes. If the next thing in the journal ** file happens to be a journal-header (written as part of the ** previous connection's transaction), and a crash or power-failure ** occurs after nRec is updated but before this connection writes ** anything else to the journal file (or commits/rolls back its ** transaction), then SQLite may become confused when doing the ** hot-journal rollback following recovery. It may roll back all ** of this connections data, then proceed to rolling back the old, ** out-of-date data that follows it. Database corruption. ** ** To work around this, if the journal file does appear to contain ** a valid header following Pager.journalOff, then write a 0x00 ** byte to the start of it to prevent it from being recognized. ** ** Variable iNextHdrOffset is set to the offset at which this ** problematic header will occur, if it exists. aMagic is used ** as a temporary buffer to inspect the first couple of bytes of ** the potential journal header. */ i64 iNextHdrOffset; u8 aMagic[8]; u8 zHeader[sizeof(aJournalMagic)+4]; memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec); iNextHdrOffset = journalHdrOffset(pPager); rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset); if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){ static const u8 zerobyte = 0; rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset); } if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ return rc; } /* Write the nRec value into the journal file header. If in ** full-synchronous mode, sync the journal first. This ensures that ** all data has really hit the disk before nRec is updated to mark ** it as a candidate for rollback. ** ** This is not required if the persistent media supports the ** SAFE_APPEND property. Because in this case it is not possible ** for garbage data to be appended to the file, the nRec field ** is populated with 0xFFFFFFFF when the journal header is written ** and never needs to be updated. */ if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); IOTRACE(("JSYNC %p\n", pPager)) rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); if( rc!=SQLITE_OK ) return rc; } IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr)); rc = sqlite3OsWrite( pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr ); if( rc!=SQLITE_OK ) return rc; } if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); IOTRACE(("JSYNC %p\n", pPager)) rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0) ); if( rc!=SQLITE_OK ) return rc; } pPager->journalHdr = pPager->journalOff; if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ pPager->nRec = 0; rc = writeJournalHdr(pPager); if( rc!=SQLITE_OK ) return rc; } }else{ pPager->journalHdr = pPager->journalOff; } } /* Unless the pager is in noSync mode, the journal file was just ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on ** all pages. */ sqlite3PcacheClearSyncFlags(pPager->pPCache); pPager->eState = PAGER_WRITER_DBMOD; assert( assert_pager_state(pPager) ); return SQLITE_OK; } /* ** The argument is the first in a linked list of dirty pages connected ** by the PgHdr.pDirty pointer. This function writes each one of the ** in-memory pages in the list to the database file. The argument may ** be NULL, representing an empty list. In this case this function is ** a no-op. ** ** The pager must hold at least a RESERVED lock when this function ** is called. Before writing anything to the database file, this lock ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained, ** SQLITE_BUSY is returned and no data is written to the database file. ** ** If the pager is a temp-file pager and the actual file-system file ** is not yet open, it is created and opened before any data is ** written out. ** ** Once the lock has been upgraded and, if necessary, the file opened, ** the pages are written out to the database file in list order. Writing ** a page is skipped if it meets either of the following criteria: ** ** * The page number is greater than Pager.dbSize, or ** * The PGHDR_DONT_WRITE flag is set on the page. ** ** If writing out a page causes the database file to grow, Pager.dbFileSize ** is updated accordingly. If page 1 is written out, then the value cached ** in Pager.dbFileVers[] is updated to match the new value stored in ** the database file. ** ** If everything is successful, SQLITE_OK is returned. If an IO error ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot ** be obtained, SQLITE_BUSY is returned. */ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ int rc = SQLITE_OK; /* Return code */ /* This function is only called for rollback pagers in WRITER_DBMOD state. */ assert( !pagerUseWal(pPager) ); assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD ); assert( pPager->eLock==EXCLUSIVE_LOCK ); assert( isOpen(pPager->fd) || pList->pDirty==0 ); /* If the file is a temp-file has not yet been opened, open it now. It ** is not possible for rc to be other than SQLITE_OK if this branch ** is taken, as pager_wait_on_lock() is a no-op for temp-files. */ if( !isOpen(pPager->fd) ){ assert( pPager->tempFile && rc==SQLITE_OK ); rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags); } /* Before the first write, give the VFS a hint of what the final ** file size will be. */ assert( rc!=SQLITE_OK || isOpen(pPager->fd) ); if( rc==SQLITE_OK && pPager->dbHintSize<pPager->dbSize && (pList->pDirty || pList->pgno>pPager->dbHintSize) ){ sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize; sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile); pPager->dbHintSize = pPager->dbSize; } while( rc==SQLITE_OK && pList ){ Pgno pgno = pList->pgno; /* If there are dirty pages in the page cache with page numbers greater ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to ** make the file smaller (presumably by auto-vacuum code). Do not write ** any such pages to the file. ** ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag ** set (set by sqlite3PagerDontWrite()). */ if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){ i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ char *pData; /* Data to write */ assert( (pList->flags&PGHDR_NEED_SYNC)==0 ); if( pList->pgno==1 ) pager_write_changecounter(pList); /* Encode the database */ CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData); /* Write out the page data. */ rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset); /* If page 1 was just written, update Pager.dbFileVers to match ** the value now stored in the database file. If writing this ** page caused the database file to grow, update dbFileSize. */ if( pgno==1 ){ memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers)); } if( pgno>pPager->dbFileSize ){ pPager->dbFileSize = pgno; } pPager->aStat[PAGER_STAT_WRITE]++; /* Update any backup objects copying the contents of this pager. */ sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData); PAGERTRACE(("STORE %d page %d hash(%08x)\n", PAGERID(pPager), pgno, pager_pagehash(pList))); IOTRACE(("PGOUT %p %d\n", pPager, pgno)); PAGER_INCR(sqlite3_pager_writedb_count); }else{ PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno)); } pager_set_pagehash(pList); pList = pList->pDirty; } return rc; } /* ** Ensure that the sub-journal file is open. If it is already open, this ** function is a no-op. ** ** SQLITE_OK is returned if everything goes according to plan. An ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() ** fails. */ static int openSubJournal(Pager *pPager){ int rc = SQLITE_OK; if( !isOpen(pPager->sjfd) ){ const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; int nStmtSpill = sqlite3Config.nStmtSpill; if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){ nStmtSpill = -1; } rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill); } return rc; } /* ** Append a record of the current state of page pPg to the sub-journal. ** ** If successful, set the bit corresponding to pPg->pgno in the bitvecs ** for all open savepoints before returning. ** ** This function returns SQLITE_OK if everything is successful, an IO ** error code if the attempt to write to the sub-journal fails, or ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint ** bitvec. */ static int subjournalPage(PgHdr *pPg){ int rc = SQLITE_OK; Pager *pPager = pPg->pPager; if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ /* Open the sub-journal, if it has not already been opened */ assert( pPager->useJournal ); assert( isOpen(pPager->jfd) || pagerUseWal(pPager) ); assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 ); assert( pagerUseWal(pPager) || pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize ); rc = openSubJournal(pPager); /* If the sub-journal was opened successfully (or was already open), ** write the journal record into the file. */ if( rc==SQLITE_OK ){ void *pData = pPg->pData; i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize); char *pData2; CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2); PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno)); rc = write32bits(pPager->sjfd, offset, pPg->pgno); if( rc==SQLITE_OK ){ rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4); } } } if( rc==SQLITE_OK ){ pPager->nSubRec++; assert( pPager->nSavepoint>0 ); rc = addToSavepointBitvecs(pPager, pPg->pgno); } return rc; } static int subjournalPageIfRequired(PgHdr *pPg){ if( subjRequiresPage(pPg) ){ return subjournalPage(pPg); }else{ return SQLITE_OK; } } /* ** This function is called by the pcache layer when it has reached some ** soft memory limit. The first argument is a pointer to a Pager object ** (cast as a void*). The pager is always 'purgeable' (not an in-memory ** database). The second argument is a reference to a page that is ** currently dirty but has no outstanding references. The page ** is always associated with the Pager object passed as the first ** argument. ** ** The job of this function is to make pPg clean by writing its contents ** out to the database file, if possible. This may involve syncing the ** journal file. ** ** If successful, sqlite3PcacheMakeClean() is called on the page and ** SQLITE_OK returned. If an IO error occurs while trying to make the ** page clean, the IO error code is returned. If the page cannot be ** made clean for some other reason, but no error occurs, then SQLITE_OK ** is returned by sqlite3PcacheMakeClean() is not called. */ static int pagerStress(void *p, PgHdr *pPg){ Pager *pPager = (Pager *)p; int rc = SQLITE_OK; assert( pPg->pPager==pPager ); assert( pPg->flags&PGHDR_DIRTY ); /* The doNotSpill NOSYNC bit is set during times when doing a sync of ** journal (and adding a new header) is not allowed. This occurs ** during calls to sqlite3PagerWrite() while trying to journal multiple ** pages belonging to the same sector. ** ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling ** regardless of whether or not a sync is required. This is set during ** a rollback or by user request, respectively. ** ** Spilling is also prohibited when in an error state since that could ** lead to database corruption. In the current implementation it ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3 ** while in the error state, hence it is impossible for this routine to ** be called in the error state. Nevertheless, we include a NEVER() ** test for the error state as a safeguard against future changes. */ if( NEVER(pPager->errCode) ) return SQLITE_OK; testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK ); testcase( pPager->doNotSpill & SPILLFLAG_OFF ); testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC ); if( pPager->doNotSpill && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0 || (pPg->flags & PGHDR_NEED_SYNC)!=0) ){ return SQLITE_OK; } pPg->pDirty = 0; if( pagerUseWal(pPager) ){ /* Write a single frame for this page to the log. */ rc = subjournalPageIfRequired(pPg); if( rc==SQLITE_OK ){ rc = pagerWalFrames(pPager, pPg, 0, 0); } }else{ /* Sync the journal file if required. */ if( pPg->flags&PGHDR_NEED_SYNC || pPager->eState==PAGER_WRITER_CACHEMOD ){ rc = syncJournal(pPager, 1); } /* Write the contents of the page out to the database file. */ if( rc==SQLITE_OK ){ assert( (pPg->flags&PGHDR_NEED_SYNC)==0 ); rc = pager_write_pagelist(pPager, pPg); } } /* Mark the page as clean. */ if( rc==SQLITE_OK ){ PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno)); sqlite3PcacheMakeClean(pPg); } return pager_error(pPager, rc); } /* ** Flush all unreferenced dirty pages to disk. */ SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){ int rc = pPager->errCode; if( !MEMDB ){ PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); assert( assert_pager_state(pPager) ); while( rc==SQLITE_OK && pList ){ PgHdr *pNext = pList->pDirty; if( pList->nRef==0 ){ rc = pagerStress((void*)pPager, pList); } pList = pNext; } } return rc; } /* ** Allocate and initialize a new Pager object and put a pointer to it ** in *ppPager. The pager should eventually be freed by passing it ** to sqlite3PagerClose(). ** ** The zFilename argument is the path to the database file to open. ** If zFilename is NULL then a randomly-named temporary file is created ** and used as the file to be cached. Temporary files are be deleted ** automatically when they are closed. If zFilename is ":memory:" then ** all information is held in cache. It is never written to disk. ** This can be used to implement an in-memory database. ** ** The nExtra parameter specifies the number of bytes of space allocated ** along with each page reference. This space is available to the user ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the ** first 8 bytes of this space are zeroed but the remainder is uninitialized. ** (The extra space is used by btree as the MemPage object.) ** ** The flags argument is used to specify properties that affect the ** operation of the pager. It should be passed some bitwise combination ** of the PAGER_* flags. ** ** The vfsFlags parameter is a bitmask to pass to the flags parameter ** of the xOpen() method of the supplied VFS when opening files. ** ** If the pager object is allocated and the specified file opened ** successfully, SQLITE_OK is returned and *ppPager set to point to ** the new pager object. If an error occurs, *ppPager is set to NULL ** and error code returned. This function may return SQLITE_NOMEM ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or ** various SQLITE_IO_XXX errors. */ SQLITE_PRIVATE int sqlite3PagerOpen( sqlite3_vfs *pVfs, /* The virtual file system to use */ Pager **ppPager, /* OUT: Return the Pager structure here */ const char *zFilename, /* Name of the database file to open */ int nExtra, /* Extra bytes append to each in-memory page */ int flags, /* flags controlling this file */ int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ void (*xReinit)(DbPage*) /* Function to reinitialize pages */ ){ u8 *pPtr; Pager *pPager = 0; /* Pager object to allocate and return */ int rc = SQLITE_OK; /* Return code */ int tempFile = 0; /* True for temp files (incl. in-memory files) */ int memDb = 0; /* True if this is an in-memory file */ int readOnly = 0; /* True if this is a read-only file */ int journalFileSize; /* Bytes to allocate for each journal fd */ char *zPathname = 0; /* Full path to database file */ int nPathname = 0; /* Number of bytes in zPathname */ int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */ int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ const char *zUri = 0; /* URI args to copy */ int nUri = 0; /* Number of bytes of URI args at *zUri */ /* Figure out how much space is required for each journal file-handle ** (there are two of them, the main journal and the sub-journal). */ journalFileSize = ROUND8(sqlite3JournalSize(pVfs)); /* Set the output variable to NULL in case an error occurs. */ *ppPager = 0; #ifndef SQLITE_OMIT_MEMORYDB if( flags & PAGER_MEMORY ){ memDb = 1; if( zFilename && zFilename[0] ){ zPathname = sqlite3DbStrDup(0, zFilename); if( zPathname==0 ) return SQLITE_NOMEM_BKPT; nPathname = sqlite3Strlen30(zPathname); zFilename = 0; } } #endif /* Compute and store the full pathname in an allocated buffer pointed ** to by zPathname, length nPathname. Or, if this is a temporary file, ** leave both nPathname and zPathname set to 0. */ if( zFilename && zFilename[0] ){ const char *z; nPathname = pVfs->mxPathname+1; zPathname = sqlite3DbMallocRaw(0, nPathname*2); if( zPathname==0 ){ return SQLITE_NOMEM_BKPT; } zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); nPathname = sqlite3Strlen30(zPathname); z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1]; while( *z ){ z += sqlite3Strlen30(z)+1; z += sqlite3Strlen30(z)+1; } nUri = (int)(&z[1] - zUri); assert( nUri>=0 ); if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){ /* This branch is taken when the journal path required by ** the database being opened will be more than pVfs->mxPathname ** bytes in length. This means the database cannot be opened, ** as it will not be possible to open the journal file or even ** check for a hot-journal before reading. */ rc = SQLITE_CANTOPEN_BKPT; } if( rc!=SQLITE_OK ){ sqlite3DbFree(0, zPathname); return rc; } } /* Allocate memory for the Pager structure, PCache object, the ** three file descriptors, the database file name and the journal ** file name. The layout in memory is as follows: ** ** Pager object (sizeof(Pager) bytes) ** PCache object (sqlite3PcacheSize() bytes) ** Database file handle (pVfs->szOsFile bytes) ** Sub-journal file handle (journalFileSize bytes) ** Main journal file handle (journalFileSize bytes) ** Database file name (nPathname+1 bytes) ** Journal file name (nPathname+8+1 bytes) */ pPtr = (u8 *)sqlite3MallocZero( ROUND8(sizeof(*pPager)) + /* Pager structure */ ROUND8(pcacheSize) + /* PCache object */ ROUND8(pVfs->szOsFile) + /* The main db file */ journalFileSize * 2 + /* The two journal files */ nPathname + 1 + nUri + /* zFilename */ nPathname + 8 + 2 /* zJournal */ #ifndef SQLITE_OMIT_WAL + nPathname + 4 + 2 /* zWal */ #endif ); assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) ); if( !pPtr ){ sqlite3DbFree(0, zPathname); return SQLITE_NOMEM_BKPT; } pPager = (Pager*)(pPtr); pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager))); pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize)); pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile)); pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize); pPager->zFilename = (char*)(pPtr += journalFileSize); assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ if( zPathname ){ assert( nPathname>0 ); pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri); memcpy(pPager->zFilename, zPathname, nPathname); if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri); memcpy(pPager->zJournal, zPathname, nPathname); memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2); sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal); #ifndef SQLITE_OMIT_WAL pPager->zWal = &pPager->zJournal[nPathname+8+1]; memcpy(pPager->zWal, zPathname, nPathname); memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1); sqlite3FileSuffix3(pPager->zFilename, pPager->zWal); #endif sqlite3DbFree(0, zPathname); } pPager->pVfs = pVfs; pPager->vfsFlags = vfsFlags; /* Open the pager file. */ if( zFilename && zFilename[0] ){ int fout = 0; /* VFS flags returned by xOpen() */ rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); assert( !memDb ); readOnly = (fout&SQLITE_OPEN_READONLY); /* If the file was successfully opened for read/write access, ** choose a default page size in case we have to create the ** database file. The default page size is the maximum of: ** ** + SQLITE_DEFAULT_PAGE_SIZE, ** + The value returned by sqlite3OsSectorSize() ** + The largest page size that can be written atomically. */ if( rc==SQLITE_OK ){ int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); if( !readOnly ){ setSectorSize(pPager); assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE); if( szPageDflt<pPager->sectorSize ){ if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){ szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE; }else{ szPageDflt = (u32)pPager->sectorSize; } } #ifdef SQLITE_ENABLE_ATOMIC_WRITE { int ii; assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536); for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){ if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){ szPageDflt = ii; } } } #endif } pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0); if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0 || sqlite3_uri_boolean(zFilename, "immutable", 0) ){ vfsFlags |= SQLITE_OPEN_READONLY; goto act_like_temp_file; } } }else{ /* If a temporary file is requested, it is not opened immediately. ** In this case we accept the default page size and delay actually ** opening the file until the first call to OsWrite(). ** ** This branch is also run for an in-memory database. An in-memory ** database is the same as a temp-file that is never written out to ** disk and uses an in-memory rollback journal. ** ** This branch also runs for files marked as immutable. */ act_like_temp_file: tempFile = 1; pPager->eState = PAGER_READER; /* Pretend we already have a lock */ pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */ pPager->noLock = 1; /* Do no locking */ readOnly = (vfsFlags&SQLITE_OPEN_READONLY); } /* The following call to PagerSetPagesize() serves to set the value of ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer. */ if( rc==SQLITE_OK ){ assert( pPager->memDb==0 ); rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1); testcase( rc!=SQLITE_OK ); } /* Initialize the PCache object. */ if( rc==SQLITE_OK ){ nExtra = ROUND8(nExtra); assert( nExtra>=8 && nExtra<1000 ); rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb, !memDb?pagerStress:0, (void *)pPager, pPager->pPCache); } /* If an error occurred above, free the Pager structure and close the file. */ if( rc!=SQLITE_OK ){ sqlite3OsClose(pPager->fd); sqlite3PageFree(pPager->pTmpSpace); sqlite3_free(pPager); return rc; } PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename)); IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename)) pPager->useJournal = (u8)useJournal; /* pPager->stmtOpen = 0; */ /* pPager->stmtInUse = 0; */ /* pPager->nRef = 0; */ /* pPager->stmtSize = 0; */ /* pPager->stmtJSize = 0; */ /* pPager->nPage = 0; */ pPager->mxPgno = SQLITE_MAX_PAGE_COUNT; /* pPager->state = PAGER_UNLOCK; */ /* pPager->errMask = 0; */ pPager->tempFile = (u8)tempFile; assert( tempFile==PAGER_LOCKINGMODE_NORMAL || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE ); assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 ); pPager->exclusiveMode = (u8)tempFile; pPager->changeCountDone = pPager->tempFile; pPager->memDb = (u8)memDb; pPager->readOnly = (u8)readOnly; assert( useJournal || pPager->tempFile ); pPager->noSync = pPager->tempFile; if( pPager->noSync ){ assert( pPager->fullSync==0 ); assert( pPager->extraSync==0 ); assert( pPager->syncFlags==0 ); assert( pPager->walSyncFlags==0 ); assert( pPager->ckptSyncFlags==0 ); }else{ pPager->fullSync = 1; pPager->extraSync = 0; pPager->syncFlags = SQLITE_SYNC_NORMAL; pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS; pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; } /* pPager->pFirst = 0; */ /* pPager->pFirstSynced = 0; */ /* pPager->pLast = 0; */ pPager->nExtra = (u16)nExtra; pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT; assert( isOpen(pPager->fd) || tempFile ); setSectorSize(pPager); if( !useJournal ){ pPager->journalMode = PAGER_JOURNALMODE_OFF; }else if( memDb ){ pPager->journalMode = PAGER_JOURNALMODE_MEMORY; } /* pPager->xBusyHandler = 0; */ /* pPager->pBusyHandlerArg = 0; */ pPager->xReiniter = xReinit; setGetterMethod(pPager); /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */ *ppPager = pPager; return SQLITE_OK; } /* Verify that the database file has not be deleted or renamed out from ** under the pager. Return SQLITE_OK if the database is still were it ought ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error ** code from sqlite3OsAccess()) if the database has gone missing. */ static int databaseIsUnmoved(Pager *pPager){ int bHasMoved = 0; int rc; if( pPager->tempFile ) return SQLITE_OK; if( pPager->dbSize==0 ) return SQLITE_OK; assert( pPager->zFilename && pPager->zFilename[0] ); rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved); if( rc==SQLITE_NOTFOUND ){ /* If the HAS_MOVED file-control is unimplemented, assume that the file ** has not been moved. That is the historical behavior of SQLite: prior to ** version 3.8.3, it never checked */ rc = SQLITE_OK; }else if( rc==SQLITE_OK && bHasMoved ){ rc = SQLITE_READONLY_DBMOVED; } return rc; } /* ** This function is called after transitioning from PAGER_UNLOCK to ** PAGER_SHARED state. It tests if there is a hot journal present in ** the file-system for the given pager. A hot journal is one that ** needs to be played back. According to this function, a hot-journal ** file exists if the following criteria are met: ** ** * The journal file exists in the file system, and ** * No process holds a RESERVED or greater lock on the database file, and ** * The database file itself is greater than 0 bytes in size, and ** * The first byte of the journal file exists and is not 0x00. ** ** If the current size of the database file is 0 but a journal file ** exists, that is probably an old journal left over from a prior ** database with the same name. In this case the journal file is ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK ** is returned. ** ** This routine does not check if there is a master journal filename ** at the end of the file. If there is, and that master journal file ** does not exist, then the journal file is not really hot. In this ** case this routine will return a false-positive. The pager_playback() ** routine will discover that the journal file is not really hot and ** will not roll it back. ** ** If a hot-journal file is found to exist, *pExists is set to 1 and ** SQLITE_OK returned. If no hot-journal file is present, *pExists is ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying ** to determine whether or not a hot-journal file exists, the IO error ** code is returned and the value of *pExists is undefined. */ static int hasHotJournal(Pager *pPager, int *pExists){ sqlite3_vfs * const pVfs = pPager->pVfs; int rc = SQLITE_OK; /* Return code */ int exists = 1; /* True if a journal file is present */ int jrnlOpen = !!isOpen(pPager->jfd); assert( pPager->useJournal ); assert( isOpen(pPager->fd) ); assert( pPager->eState==PAGER_OPEN ); assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN )); *pExists = 0; if( !jrnlOpen ){ rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists); } if( rc==SQLITE_OK && exists ){ int locked = 0; /* True if some process holds a RESERVED lock */ /* Race condition here: Another process might have been holding the ** the RESERVED lock and have a journal open at the sqlite3OsAccess() ** call above, but then delete the journal and drop the lock before ** we get to the following sqlite3OsCheckReservedLock() call. If that ** is the case, this routine might think there is a hot journal when ** in fact there is none. This results in a false-positive which will ** be dealt with by the playback routine. Ticket #3883. */ rc = sqlite3OsCheckReservedLock(pPager->fd, &locked); if( rc==SQLITE_OK && !locked ){ Pgno nPage; /* Number of pages in database file */ assert( pPager->tempFile==0 ); rc = pagerPagecount(pPager, &nPage); if( rc==SQLITE_OK ){ /* If the database is zero pages in size, that means that either (1) the ** journal is a remnant from a prior database with the same name where ** the database file but not the journal was deleted, or (2) the initial ** transaction that populates a new database is being rolled back. ** In either case, the journal file can be deleted. However, take care ** not to delete the journal file if it is already open due to ** journal_mode=PERSIST. */ if( nPage==0 && !jrnlOpen ){ sqlite3BeginBenignMalloc(); if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){ sqlite3OsDelete(pVfs, pPager->zJournal, 0); if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); } sqlite3EndBenignMalloc(); }else{ /* The journal file exists and no other connection has a reserved ** or greater lock on the database file. Now check that there is ** at least one non-zero bytes at the start of the journal file. ** If there is, then we consider this journal to be hot. If not, ** it can be ignored. */ if( !jrnlOpen ){ int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL; rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f); } if( rc==SQLITE_OK ){ u8 first = 0; rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } if( !jrnlOpen ){ sqlite3OsClose(pPager->jfd); } *pExists = (first!=0); }else if( rc==SQLITE_CANTOPEN ){ /* If we cannot open the rollback journal file in order to see if ** it has a zero header, that might be due to an I/O error, or ** it might be due to the race condition described above and in ** ticket #3883. Either way, assume that the journal is hot. ** This might be a false positive. But if it is, then the ** automatic journal playback and recovery mechanism will deal ** with it under an EXCLUSIVE lock where we do not need to ** worry so much with race conditions. */ *pExists = 1; rc = SQLITE_OK; } } } } } return rc; } /* ** This function is called to obtain a shared lock on the database file. ** It is illegal to call sqlite3PagerGet() until after this function ** has been successfully called. If a shared-lock is already held when ** this function is called, it is a no-op. ** ** The following operations are also performed by this function. ** ** 1) If the pager is currently in PAGER_OPEN state (no lock held ** on the database file), then an attempt is made to obtain a ** SHARED lock on the database file. Immediately after obtaining ** the SHARED lock, the file-system is checked for a hot-journal, ** which is played back if present. Following any hot-journal ** rollback, the contents of the cache are validated by checking ** the 'change-counter' field of the database file header and ** discarded if they are found to be invalid. ** ** 2) If the pager is running in exclusive-mode, and there are currently ** no outstanding references to any pages, and is in the error state, ** then an attempt is made to clear the error state by discarding ** the contents of the page cache and rolling back any open journal ** file. ** ** If everything is successful, SQLITE_OK is returned. If an IO error ** occurs while locking the database, checking for a hot-journal file or ** rolling back a journal file, the IO error code is returned. */ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ /* This routine is only called from b-tree and only when there are no ** outstanding pages. This implies that the pager state should either ** be OPEN or READER. READER is only possible if the pager is or was in ** exclusive access mode. */ assert( sqlite3PcacheRefCount(pPager->pPCache)==0 ); assert( assert_pager_state(pPager) ); assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); assert( pPager->errCode==SQLITE_OK ); if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){ int bHotJournal = 1; /* True if there exists a hot journal-file */ assert( !MEMDB ); assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK ); rc = pager_wait_on_lock(pPager, SHARED_LOCK); if( rc!=SQLITE_OK ){ assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK ); goto failed; } /* If a journal file exists, and there is no RESERVED lock on the ** database file, then it either needs to be played back or deleted. */ if( pPager->eLock<=SHARED_LOCK ){ rc = hasHotJournal(pPager, &bHotJournal); } if( rc!=SQLITE_OK ){ goto failed; } if( bHotJournal ){ if( pPager->readOnly ){ rc = SQLITE_READONLY_ROLLBACK; goto failed; } /* Get an EXCLUSIVE lock on the database file. At this point it is ** important that a RESERVED lock is not obtained on the way to the ** EXCLUSIVE lock. If it were, another process might open the ** database file, detect the RESERVED lock, and conclude that the ** database is safe to read while this process is still rolling the ** hot-journal back. ** ** Because the intermediate RESERVED lock is not requested, any ** other process attempting to access the database file will get to ** this point in the code and fail to obtain its own EXCLUSIVE lock ** on the database file. ** ** Unless the pager is in locking_mode=exclusive mode, the lock is ** downgraded to SHARED_LOCK before this function returns. */ rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); if( rc!=SQLITE_OK ){ goto failed; } /* If it is not already open and the file exists on disk, open the ** journal for read/write access. Write access is required because ** in exclusive-access mode the file descriptor will be kept open ** and possibly used for a transaction later on. Also, write-access ** is usually required to finalize the journal in journal_mode=persist ** mode (and also for journal_mode=truncate on some systems). ** ** If the journal does not exist, it usually means that some ** other connection managed to get in and roll it back before ** this connection obtained the exclusive lock above. Or, it ** may mean that the pager was in the error-state when this ** function was called and the journal file does not exist. */ if( !isOpen(pPager->jfd) ){ sqlite3_vfs * const pVfs = pPager->pVfs; int bExists; /* True if journal file exists */ rc = sqlite3OsAccess( pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists); if( rc==SQLITE_OK && bExists ){ int fout = 0; int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL; assert( !pPager->tempFile ); rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){ rc = SQLITE_CANTOPEN_BKPT; sqlite3OsClose(pPager->jfd); } } } /* Playback and delete the journal. Drop the database write ** lock and reacquire the read lock. Purge the cache before ** playing back the hot-journal so that we don't end up with ** an inconsistent cache. Sync the hot journal before playing ** it back since the process that crashed and left the hot journal ** probably did not sync it and we are required to always sync ** the journal before playing it back. */ if( isOpen(pPager->jfd) ){ assert( rc==SQLITE_OK ); rc = pagerSyncHotJournal(pPager); if( rc==SQLITE_OK ){ rc = pager_playback(pPager, !pPager->tempFile); pPager->eState = PAGER_OPEN; } }else if( !pPager->exclusiveMode ){ pagerUnlockDb(pPager, SHARED_LOCK); } if( rc!=SQLITE_OK ){ /* This branch is taken if an error occurs while trying to open ** or roll back a hot-journal while holding an EXCLUSIVE lock. The ** pager_unlock() routine will be called before returning to unlock ** the file. If the unlock attempt fails, then Pager.eLock must be ** set to UNKNOWN_LOCK (see the comment above the #define for ** UNKNOWN_LOCK above for an explanation). ** ** In order to get pager_unlock() to do this, set Pager.eState to ** PAGER_ERROR now. This is not actually counted as a transition ** to ERROR state in the state diagram at the top of this file, ** since we know that the same call to pager_unlock() will very ** shortly transition the pager object to the OPEN state. Calling ** assert_pager_state() would fail now, as it should not be possible ** to be in ERROR state when there are zero outstanding page ** references. */ pager_error(pPager, rc); goto failed; } assert( pPager->eState==PAGER_OPEN ); assert( (pPager->eLock==SHARED_LOCK) || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK) ); } if( !pPager->tempFile && pPager->hasHeldSharedLock ){ /* The shared-lock has just been acquired then check to ** see if the database has been modified. If the database has changed, ** flush the cache. The hasHeldSharedLock flag prevents this from ** occurring on the very first access to a file, in order to save a ** single unnecessary sqlite3OsRead() call at the start-up. ** ** Database changes are detected by looking at 15 bytes beginning ** at offset 24 into the file. The first 4 of these 16 bytes are ** a 32-bit counter that is incremented with each change. The ** other bytes change randomly with each file change when ** a codec is in use. ** ** There is a vanishingly small chance that a change will not be ** detected. The chance of an undetected change is so small that ** it can be neglected. */ Pgno nPage = 0; char dbFileVers[sizeof(pPager->dbFileVers)]; rc = pagerPagecount(pPager, &nPage); if( rc ) goto failed; if( nPage>0 ){ IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers))); rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24); if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ goto failed; } }else{ memset(dbFileVers, 0, sizeof(dbFileVers)); } if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){ pager_reset(pPager); /* Unmap the database file. It is possible that external processes ** may have truncated the database file and then extended it back ** to its original size while this process was not holding a lock. ** In this case there may exist a Pager.pMap mapping that appears ** to be the right size but is not actually valid. Avoid this ** possibility by unmapping the db here. */ if( USEFETCH(pPager) ){ sqlite3OsUnfetch(pPager->fd, 0, 0); } } } /* If there is a WAL file in the file-system, open this database in WAL ** mode. Otherwise, the following function call is a no-op. */ rc = pagerOpenWalIfPresent(pPager); #ifndef SQLITE_OMIT_WAL assert( pPager->pWal==0 || rc==SQLITE_OK ); #endif } if( pagerUseWal(pPager) ){ assert( rc==SQLITE_OK ); rc = pagerBeginReadTransaction(pPager); } if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){ rc = pagerPagecount(pPager, &pPager->dbSize); } failed: if( rc!=SQLITE_OK ){ assert( !MEMDB ); pager_unlock(pPager); assert( pPager->eState==PAGER_OPEN ); }else{ pPager->eState = PAGER_READER; pPager->hasHeldSharedLock = 1; } return rc; } /* ** If the reference count has reached zero, rollback any active ** transaction and unlock the pager. ** ** Except, in locking_mode=EXCLUSIVE when there is nothing to in ** the rollback journal, the unlock is not performed and there is ** nothing to rollback, so this routine is a no-op. */ static void pagerUnlockIfUnused(Pager *pPager){ if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){ pagerUnlockAndRollback(pPager); } } /* ** The page getter methods each try to acquire a reference to a ** page with page number pgno. If the requested reference is ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. ** ** There are different implementations of the getter method depending ** on the current state of the pager. ** ** getPageNormal() -- The normal getter ** getPageError() -- Used if the pager is in an error state ** getPageMmap() -- Used if memory-mapped I/O is enabled ** ** If the requested page is already in the cache, it is returned. ** Otherwise, a new page object is allocated and populated with data ** read from the database file. In some cases, the pcache module may ** choose not to allocate a new page object and may reuse an existing ** object with no outstanding references. ** ** The extra data appended to a page is always initialized to zeros the ** first time a page is loaded into memory. If the page requested is ** already in the cache when this function is called, then the extra ** data is left as it was when the page object was last used. ** ** If the database image is smaller than the requested page or if ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the ** requested page is not already stored in the cache, then no ** actual disk read occurs. In this case the memory image of the ** page is initialized to all zeros. ** ** If PAGER_GET_NOCONTENT is true, it means that we do not care about ** the contents of the page. This occurs in two scenarios: ** ** a) When reading a free-list leaf page from the database, and ** ** b) When a savepoint is being rolled back and we need to load ** a new page into the cache to be filled with the data read ** from the savepoint journal. ** ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead ** of being read from the database. Additionally, the bits corresponding ** to pgno in Pager.pInJournal (bitvec of pages already written to the ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open ** savepoints are set. This means if the page is made writable at any ** point in the future, using a call to sqlite3PagerWrite(), its contents ** will not be journaled. This saves IO. ** ** The acquisition might fail for several reasons. In all cases, ** an appropriate error code is returned and *ppPage is set to NULL. ** ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt ** to find a page in the in-memory cache first. If the page is not already ** in memory, this routine goes to disk to read it in whereas Lookup() ** just returns 0. This routine acquires a read-lock the first time it ** has to go to disk, and could also playback an old journal if necessary. ** Since Lookup() never goes to disk, it never has to deal with locks ** or journal files. */ static int getPageNormal( Pager *pPager, /* The pager open on the database file */ Pgno pgno, /* Page number to fetch */ DbPage **ppPage, /* Write a pointer to the page here */ int flags /* PAGER_GET_XXX flags */ ){ int rc = SQLITE_OK; PgHdr *pPg; u8 noContent; /* True if PAGER_GET_NOCONTENT is set */ sqlite3_pcache_page *pBase; assert( pPager->errCode==SQLITE_OK ); assert( pPager->eState>=PAGER_READER ); assert( assert_pager_state(pPager) ); assert( pPager->hasHeldSharedLock==1 ); if( pgno==0 ) return SQLITE_CORRUPT_BKPT; pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3); if( pBase==0 ){ pPg = 0; rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase); if( rc!=SQLITE_OK ) goto pager_acquire_err; if( pBase==0 ){ rc = SQLITE_NOMEM_BKPT; goto pager_acquire_err; } } pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase); assert( pPg==(*ppPage) ); assert( pPg->pgno==pgno ); assert( pPg->pPager==pPager || pPg->pPager==0 ); noContent = (flags & PAGER_GET_NOCONTENT)!=0; if( pPg->pPager && !noContent ){ /* In this case the pcache already contains an initialized copy of ** the page. Return without further ado. */ assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) ); pPager->aStat[PAGER_STAT_HIT]++; return SQLITE_OK; }else{ /* The pager cache has created a new page. Its content needs to ** be initialized. But first some error checks: ** ** (1) The maximum page number is 2^31 ** (2) Never try to fetch the locking page */ if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){ rc = SQLITE_CORRUPT_BKPT; goto pager_acquire_err; } pPg->pPager = pPager; assert( !isOpen(pPager->fd) || !MEMDB ); if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){ if( pgno>pPager->mxPgno ){ rc = SQLITE_FULL; goto pager_acquire_err; } if( noContent ){ /* Failure to set the bits in the InJournal bit-vectors is benign. ** It merely means that we might do some extra work to journal a ** page that does not need to be journaled. Nevertheless, be sure ** to test the case where a malloc error occurs while trying to set ** a bit in a bit vector. */ sqlite3BeginBenignMalloc(); if( pgno<=pPager->dbOrigSize ){ TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno); testcase( rc==SQLITE_NOMEM ); } TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); testcase( rc==SQLITE_NOMEM ); sqlite3EndBenignMalloc(); } memset(pPg->pData, 0, pPager->pageSize); IOTRACE(("ZERO %p %d\n", pPager, pgno)); }else{ u32 iFrame = 0; /* Frame to read from WAL file */ if( pagerUseWal(pPager) ){ rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); if( rc!=SQLITE_OK ) goto pager_acquire_err; } assert( pPg->pPager==pPager ); pPager->aStat[PAGER_STAT_MISS]++; rc = readDbPage(pPg, iFrame); if( rc!=SQLITE_OK ){ goto pager_acquire_err; } } pager_set_pagehash(pPg); } return SQLITE_OK; pager_acquire_err: assert( rc!=SQLITE_OK ); if( pPg ){ sqlite3PcacheDrop(pPg); } pagerUnlockIfUnused(pPager); *ppPage = 0; return rc; } #if SQLITE_MAX_MMAP_SIZE>0 /* The page getter for when memory-mapped I/O is enabled */ static int getPageMMap( Pager *pPager, /* The pager open on the database file */ Pgno pgno, /* Page number to fetch */ DbPage **ppPage, /* Write a pointer to the page here */ int flags /* PAGER_GET_XXX flags */ ){ int rc = SQLITE_OK; PgHdr *pPg = 0; u32 iFrame = 0; /* Frame to read from WAL file */ /* It is acceptable to use a read-only (mmap) page for any page except ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY ** flag was specified by the caller. And so long as the db is not a ** temporary or in-memory database. */ const int bMmapOk = (pgno>1 && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY)) ); assert( USEFETCH(pPager) ); #ifdef SQLITE_HAS_CODEC assert( pPager->xCodec==0 ); #endif /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here ** allows the compiler optimizer to reuse the results of the "pgno>1" ** test in the previous statement, and avoid testing pgno==0 in the ** common case where pgno is large. */ if( pgno<=1 && pgno==0 ){ return SQLITE_CORRUPT_BKPT; } assert( pPager->eState>=PAGER_READER ); assert( assert_pager_state(pPager) ); assert( pPager->hasHeldSharedLock==1 ); assert( pPager->errCode==SQLITE_OK ); if( bMmapOk && pagerUseWal(pPager) ){ rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); if( rc!=SQLITE_OK ){ *ppPage = 0; return rc; } } if( bMmapOk && iFrame==0 ){ void *pData = 0; rc = sqlite3OsFetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData ); if( rc==SQLITE_OK && pData ){ if( pPager->eState>PAGER_READER || pPager->tempFile ){ pPg = sqlite3PagerLookup(pPager, pgno); } if( pPg==0 ){ rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg); }else{ sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData); } if( pPg ){ assert( rc==SQLITE_OK ); *ppPage = pPg; return SQLITE_OK; } } if( rc!=SQLITE_OK ){ *ppPage = 0; return rc; } } return getPageNormal(pPager, pgno, ppPage, flags); } #endif /* SQLITE_MAX_MMAP_SIZE>0 */ /* The page getter method for when the pager is an error state */ static int getPageError( Pager *pPager, /* The pager open on the database file */ Pgno pgno, /* Page number to fetch */ DbPage **ppPage, /* Write a pointer to the page here */ int flags /* PAGER_GET_XXX flags */ ){ UNUSED_PARAMETER(pgno); UNUSED_PARAMETER(flags); assert( pPager->errCode!=SQLITE_OK ); *ppPage = 0; return pPager->errCode; } /* Dispatch all page fetch requests to the appropriate getter method. */ SQLITE_PRIVATE int sqlite3PagerGet( Pager *pPager, /* The pager open on the database file */ Pgno pgno, /* Page number to fetch */ DbPage **ppPage, /* Write a pointer to the page here */ int flags /* PAGER_GET_XXX flags */ ){ return pPager->xGet(pPager, pgno, ppPage, flags); } /* ** Acquire a page if it is already in the in-memory cache. Do ** not read the page from disk. Return a pointer to the page, ** or 0 if the page is not in cache. ** ** See also sqlite3PagerGet(). The difference between this routine ** and sqlite3PagerGet() is that _get() will go to the disk and read ** in the page if the page is not already in cache. This routine ** returns NULL if the page is not in cache or if a disk I/O error ** has ever happened. */ SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){ sqlite3_pcache_page *pPage; assert( pPager!=0 ); assert( pgno!=0 ); assert( pPager->pPCache!=0 ); pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0); assert( pPage==0 || pPager->hasHeldSharedLock ); if( pPage==0 ) return 0; return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage); } /* ** Release a page reference. ** ** If the number of references to the page drop to zero, then the ** page is added to the LRU list. When all references to all pages ** are released, a rollback occurs and the lock on the database is ** removed. */ SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){ Pager *pPager; assert( pPg!=0 ); pPager = pPg->pPager; if( pPg->flags & PGHDR_MMAP ){ pagerReleaseMapPage(pPg); }else{ sqlite3PcacheRelease(pPg); } pagerUnlockIfUnused(pPager); } SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){ if( pPg ) sqlite3PagerUnrefNotNull(pPg); } /* ** This function is called at the start of every write transaction. ** There must already be a RESERVED or EXCLUSIVE lock on the database ** file when this routine is called. ** ** Open the journal file for pager pPager and write a journal header ** to the start of it. If there are active savepoints, open the sub-journal ** as well. This function is only used when the journal file is being ** opened to write a rollback log for a transaction. It is not used ** when opening a hot journal file to roll it back. ** ** If the journal file is already open (as it may be in exclusive mode), ** then this function just writes a journal header to the start of the ** already open file. ** ** Whether or not the journal file is opened by this function, the ** Pager.pInJournal bitvec structure is allocated. ** ** Return SQLITE_OK if everything is successful. Otherwise, return ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or ** an IO error code if opening or writing the journal file fails. */ static int pager_open_journal(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */ assert( pPager->eState==PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); assert( pPager->pInJournal==0 ); /* If already in the error state, this function is a no-op. But on ** the other hand, this routine is never called if we are already in ** an error state. */ if( NEVER(pPager->errCode) ) return pPager->errCode; if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize); if( pPager->pInJournal==0 ){ return SQLITE_NOMEM_BKPT; } /* Open the journal file if it is not already open. */ if( !isOpen(pPager->jfd) ){ if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){ sqlite3MemJournalOpen(pPager->jfd); }else{ int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; int nSpill; if( pPager->tempFile ){ flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL); nSpill = sqlite3Config.nStmtSpill; }else{ flags |= SQLITE_OPEN_MAIN_JOURNAL; nSpill = jrnlBufferSize(pPager); } /* Verify that the database still has the same name as it did when ** it was originally opened. */ rc = databaseIsUnmoved(pPager); if( rc==SQLITE_OK ){ rc = sqlite3JournalOpen ( pVfs, pPager->zJournal, pPager->jfd, flags, nSpill ); } } assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); } /* Write the first journal header to the journal file and open ** the sub-journal if necessary. */ if( rc==SQLITE_OK ){ /* TODO: Check if all of these are really required. */ pPager->nRec = 0; pPager->journalOff = 0; pPager->setMaster = 0; pPager->journalHdr = 0; rc = writeJournalHdr(pPager); } } if( rc!=SQLITE_OK ){ sqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; }else{ assert( pPager->eState==PAGER_WRITER_LOCKED ); pPager->eState = PAGER_WRITER_CACHEMOD; } return rc; } /* ** Begin a write-transaction on the specified pager object. If a ** write-transaction has already been opened, this function is a no-op. ** ** If the exFlag argument is false, then acquire at least a RESERVED ** lock on the database file. If exFlag is true, then acquire at least ** an EXCLUSIVE lock. If such a lock is already held, no locking ** functions need be called. ** ** If the subjInMemory argument is non-zero, then any sub-journal opened ** within this transaction will be opened as an in-memory file. This ** has no effect if the sub-journal is already opened (as it may be when ** running in exclusive mode) or if the transaction does not require a ** sub-journal. If the subjInMemory argument is zero, then any required ** sub-journal is implemented in-memory if pPager is an in-memory database, ** or using a temporary file otherwise. */ SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){ int rc = SQLITE_OK; if( pPager->errCode ) return pPager->errCode; assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR ); pPager->subjInMemory = (u8)subjInMemory; if( ALWAYS(pPager->eState==PAGER_READER) ){ assert( pPager->pInJournal==0 ); if( pagerUseWal(pPager) ){ /* If the pager is configured to use locking_mode=exclusive, and an ** exclusive lock on the database is not already held, obtain it now. */ if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){ rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); if( rc!=SQLITE_OK ){ return rc; } (void)sqlite3WalExclusiveMode(pPager->pWal, 1); } /* Grab the write lock on the log file. If successful, upgrade to ** PAGER_RESERVED state. Otherwise, return an error code to the caller. ** The busy-handler is not invoked if another connection already ** holds the write-lock. If possible, the upper layer will call it. */ rc = sqlite3WalBeginWriteTransaction(pPager->pWal); }else{ /* Obtain a RESERVED lock on the database file. If the exFlag parameter ** is true, then immediately upgrade this to an EXCLUSIVE lock. The ** busy-handler callback can be used when upgrading to the EXCLUSIVE ** lock, but not when obtaining the RESERVED lock. */ rc = pagerLockDb(pPager, RESERVED_LOCK); if( rc==SQLITE_OK && exFlag ){ rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); } } if( rc==SQLITE_OK ){ /* Change to WRITER_LOCKED state. ** ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD ** when it has an open transaction, but never to DBMOD or FINISHED. ** This is because in those states the code to roll back savepoint ** transactions may copy data from the sub-journal into the database ** file as well as into the page cache. Which would be incorrect in ** WAL mode. */ pPager->eState = PAGER_WRITER_LOCKED; pPager->dbHintSize = pPager->dbSize; pPager->dbFileSize = pPager->dbSize; pPager->dbOrigSize = pPager->dbSize; pPager->journalOff = 0; } assert( rc==SQLITE_OK || pPager->eState==PAGER_READER ); assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); } PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager))); return rc; } /* ** Write page pPg onto the end of the rollback journal. */ static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){ Pager *pPager = pPg->pPager; int rc; u32 cksum; char *pData2; i64 iOff = pPager->journalOff; /* We should never write to the journal file the page that ** contains the database locks. The following assert verifies ** that we do not. */ assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) ); assert( pPager->journalHdr<=pPager->journalOff ); CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2); cksum = pager_cksum(pPager, (u8*)pData2); /* Even if an IO or diskfull error occurs while journalling the ** page in the block above, set the need-sync flag for the page. ** Otherwise, when the transaction is rolled back, the logic in ** playback_one_page() will think that the page needs to be restored ** in the database file. And if an IO error occurs while doing so, ** then corruption may follow. */ pPg->flags |= PGHDR_NEED_SYNC; rc = write32bits(pPager->jfd, iOff, pPg->pgno); if( rc!=SQLITE_OK ) return rc; rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4); if( rc!=SQLITE_OK ) return rc; rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum); if( rc!=SQLITE_OK ) return rc; IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, pPager->journalOff, pPager->pageSize)); PAGER_INCR(sqlite3_pager_writej_count); PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n", PAGERID(pPager), pPg->pgno, ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg))); pPager->journalOff += 8 + pPager->pageSize; pPager->nRec++; assert( pPager->pInJournal!=0 ); rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno); testcase( rc==SQLITE_NOMEM ); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); rc |= addToSavepointBitvecs(pPager, pPg->pgno); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); return rc; } /* ** Mark a single data page as writeable. The page is written into the ** main journal or sub-journal as required. If the page is written into ** one of the journals, the corresponding bit is set in the ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs ** of any open savepoints as appropriate. */ static int pager_write(PgHdr *pPg){ Pager *pPager = pPg->pPager; int rc = SQLITE_OK; /* This routine is not called unless a write-transaction has already ** been started. The journal file may or may not be open at this point. ** It is never called in the ERROR state. */ assert( pPager->eState==PAGER_WRITER_LOCKED || pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD ); assert( assert_pager_state(pPager) ); assert( pPager->errCode==0 ); assert( pPager->readOnly==0 ); CHECK_PAGE(pPg); /* The journal file needs to be opened. Higher level routines have already ** obtained the necessary locks to begin the write-transaction, but the ** rollback journal might not yet be open. Open it now if this is the case. ** ** This is done before calling sqlite3PcacheMakeDirty() on the page. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then ** an error might occur and the pager would end up in WRITER_LOCKED state ** with pages marked as dirty in the cache. */ if( pPager->eState==PAGER_WRITER_LOCKED ){ rc = pager_open_journal(pPager); if( rc!=SQLITE_OK ) return rc; } assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); assert( assert_pager_state(pPager) ); /* Mark the page that is about to be modified as dirty. */ sqlite3PcacheMakeDirty(pPg); /* If a rollback journal is in use, them make sure the page that is about ** to change is in the rollback journal, or if the page is a new page off ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC. */ assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) ); if( pPager->pInJournal!=0 && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0 ){ assert( pagerUseWal(pPager)==0 ); if( pPg->pgno<=pPager->dbOrigSize ){ rc = pagerAddPageToRollbackJournal(pPg); if( rc!=SQLITE_OK ){ return rc; } }else{ if( pPager->eState!=PAGER_WRITER_DBMOD ){ pPg->flags |= PGHDR_NEED_SYNC; } PAGERTRACE(("APPEND %d page %d needSync=%d\n", PAGERID(pPager), pPg->pgno, ((pPg->flags&PGHDR_NEED_SYNC)?1:0))); } } /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list ** and before writing the page into the rollback journal. Wait until now, ** after the page has been successfully journalled, before setting the ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified. */ pPg->flags |= PGHDR_WRITEABLE; /* If the statement journal is open and the page is not in it, ** then write the page into the statement journal. */ if( pPager->nSavepoint>0 ){ rc = subjournalPageIfRequired(pPg); } /* Update the database size and return. */ if( pPager->dbSize<pPg->pgno ){ pPager->dbSize = pPg->pgno; } return rc; } /* ** This is a variant of sqlite3PagerWrite() that runs when the sector size ** is larger than the page size. SQLite makes the (reasonable) assumption that ** all bytes of a sector are written together by hardware. Hence, all bytes of ** a sector need to be journalled in case of a power loss in the middle of ** a write. ** ** Usually, the sector size is less than or equal to the page size, in which ** case pages can be individually written. This routine only runs in the ** exceptional case where the page size is smaller than the sector size. */ static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){ int rc = SQLITE_OK; /* Return code */ Pgno nPageCount; /* Total number of pages in database file */ Pgno pg1; /* First page of the sector pPg is located on. */ int nPage = 0; /* Number of pages starting at pg1 to journal */ int ii; /* Loop counter */ int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */ Pager *pPager = pPg->pPager; /* The pager that owns pPg */ Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize); /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow ** a journal header to be written between the pages journaled by ** this function. */ assert( !MEMDB ); assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 ); pPager->doNotSpill |= SPILLFLAG_NOSYNC; /* This trick assumes that both the page-size and sector-size are ** an integer power of 2. It sets variable pg1 to the identifier ** of the first page of the sector pPg is located on. */ pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1; nPageCount = pPager->dbSize; if( pPg->pgno>nPageCount ){ nPage = (pPg->pgno - pg1)+1; }else if( (pg1+nPagePerSector-1)>nPageCount ){ nPage = nPageCount+1-pg1; }else{ nPage = nPagePerSector; } assert(nPage>0); assert(pg1<=pPg->pgno); assert((pg1+nPage)>pPg->pgno); for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){ Pgno pg = pg1+ii; PgHdr *pPage; if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){ if( pg!=PAGER_MJ_PGNO(pPager) ){ rc = sqlite3PagerGet(pPager, pg, &pPage, 0); if( rc==SQLITE_OK ){ rc = pager_write(pPage); if( pPage->flags&PGHDR_NEED_SYNC ){ needSync = 1; } sqlite3PagerUnrefNotNull(pPage); } } }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){ if( pPage->flags&PGHDR_NEED_SYNC ){ needSync = 1; } sqlite3PagerUnrefNotNull(pPage); } } /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages ** starting at pg1, then it needs to be set for all of them. Because ** writing to any of these nPage pages may damage the others, the ** journal file must contain sync()ed copies of all of them ** before any of them can be written out to the database file. */ if( rc==SQLITE_OK && needSync ){ assert( !MEMDB ); for(ii=0; ii<nPage; ii++){ PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii); if( pPage ){ pPage->flags |= PGHDR_NEED_SYNC; sqlite3PagerUnrefNotNull(pPage); } } } assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 ); pPager->doNotSpill &= ~SPILLFLAG_NOSYNC; return rc; } /* ** Mark a data page as writeable. This routine must be called before ** making changes to a page. The caller must check the return value ** of this function and be careful not to change any page data unless ** this routine returns SQLITE_OK. ** ** The difference between this function and pager_write() is that this ** function also deals with the special case where 2 or more pages ** fit on a single disk sector. In this case all co-resident pages ** must have been written to the journal file before returning. ** ** If an error occurs, SQLITE_NOMEM or an IO error code is returned ** as appropriate. Otherwise, SQLITE_OK. */ SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){ Pager *pPager = pPg->pPager; assert( (pPg->flags & PGHDR_MMAP)==0 ); assert( pPager->eState>=PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){ if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg); return SQLITE_OK; }else if( pPager->errCode ){ return pPager->errCode; }else if( pPager->sectorSize > (u32)pPager->pageSize ){ assert( pPager->tempFile==0 ); return pagerWriteLargeSector(pPg); }else{ return pager_write(pPg); } } /* ** Return TRUE if the page given in the argument was previously passed ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok ** to change the content of the page. */ #ifndef NDEBUG SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){ return pPg->flags & PGHDR_WRITEABLE; } #endif /* ** A call to this routine tells the pager that it is not necessary to ** write the information on page pPg back to the disk, even though ** that page might be marked as dirty. This happens, for example, when ** the page has been added as a leaf of the freelist and so its ** content no longer matters. ** ** The overlying software layer calls this routine when all of the data ** on the given page is unused. The pager marks the page as clean so ** that it does not get written to disk. ** ** Tests show that this optimization can quadruple the speed of large ** DELETE operations. ** ** This optimization cannot be used with a temp-file, as the page may ** have been dirty at the start of the transaction. In that case, if ** memory pressure forces page pPg out of the cache, the data does need ** to be written out to disk so that it may be read back in if the ** current transaction is rolled back. */ SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){ Pager *pPager = pPg->pPager; if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){ PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager))); IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno)) pPg->flags |= PGHDR_DONT_WRITE; pPg->flags &= ~PGHDR_WRITEABLE; testcase( pPg->flags & PGHDR_NEED_SYNC ); pager_set_pagehash(pPg); } } /* ** This routine is called to increment the value of the database file ** change-counter, stored as a 4-byte big-endian integer starting at ** byte offset 24 of the pager file. The secondary change counter at ** 92 is also updated, as is the SQLite version number at offset 96. ** ** But this only happens if the pPager->changeCountDone flag is false. ** To avoid excess churning of page 1, the update only happens once. ** See also the pager_write_changecounter() routine that does an ** unconditional update of the change counters. ** ** If the isDirectMode flag is zero, then this is done by calling ** sqlite3PagerWrite() on page 1, then modifying the contents of the ** page data. In this case the file will be updated when the current ** transaction is committed. ** ** The isDirectMode flag may only be non-zero if the library was compiled ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, ** if isDirect is non-zero, then the database file is updated directly ** by writing an updated version of page 1 using a call to the ** sqlite3OsWrite() function. */ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ int rc = SQLITE_OK; assert( pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD ); assert( assert_pager_state(pPager) ); /* Declare and initialize constant integer 'isDirect'. If the ** atomic-write optimization is enabled in this build, then isDirect ** is initialized to the value passed as the isDirectMode parameter ** to this function. Otherwise, it is always set to zero. ** ** The idea is that if the atomic-write optimization is not ** enabled at compile time, the compiler can omit the tests of ** 'isDirect' below, as well as the block enclosed in the ** "if( isDirect )" condition. */ #ifndef SQLITE_ENABLE_ATOMIC_WRITE # define DIRECT_MODE 0 assert( isDirectMode==0 ); UNUSED_PARAMETER(isDirectMode); #else # define DIRECT_MODE isDirectMode #endif if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){ PgHdr *pPgHdr; /* Reference to page 1 */ assert( !pPager->tempFile && isOpen(pPager->fd) ); /* Open page 1 of the file for writing. */ rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0); assert( pPgHdr==0 || rc==SQLITE_OK ); /* If page one was fetched successfully, and this function is not ** operating in direct-mode, make page 1 writable. When not in ** direct mode, page 1 is always held in cache and hence the PagerGet() ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. */ if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){ rc = sqlite3PagerWrite(pPgHdr); } if( rc==SQLITE_OK ){ /* Actually do the update of the change counter */ pager_write_changecounter(pPgHdr); /* If running in direct mode, write the contents of page 1 to the file. */ if( DIRECT_MODE ){ const void *zBuf; assert( pPager->dbFileSize>0 ); CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf); if( rc==SQLITE_OK ){ rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0); pPager->aStat[PAGER_STAT_WRITE]++; } if( rc==SQLITE_OK ){ /* Update the pager's copy of the change-counter. Otherwise, the ** next time a read transaction is opened the cache will be ** flushed (as the change-counter values will not match). */ const void *pCopy = (const void *)&((const char *)zBuf)[24]; memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers)); pPager->changeCountDone = 1; } }else{ pPager->changeCountDone = 1; } } /* Release the page reference. */ sqlite3PagerUnref(pPgHdr); } return rc; } /* ** Sync the database file to disk. This is a no-op for in-memory databases ** or pages with the Pager.noSync flag set. ** ** If successful, or if called on a pager for which it is a no-op, this ** function returns SQLITE_OK. Otherwise, an IO error code is returned. */ SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){ int rc = SQLITE_OK; if( isOpen(pPager->fd) ){ void *pArg = (void*)zMaster; rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg); if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; } if( rc==SQLITE_OK && !pPager->noSync ){ assert( !MEMDB ); rc = sqlite3OsSync(pPager->fd, pPager->syncFlags); } return rc; } /* ** This function may only be called while a write-transaction is active in ** rollback. If the connection is in WAL mode, this call is a no-op. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on ** the database file, an attempt is made to obtain one. ** ** If the EXCLUSIVE lock is already held or the attempt to obtain it is ** successful, or the connection is in WAL mode, SQLITE_OK is returned. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is ** returned. */ SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){ int rc = pPager->errCode; assert( assert_pager_state(pPager) ); if( rc==SQLITE_OK ){ assert( pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD || pPager->eState==PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); if( 0==pagerUseWal(pPager) ){ rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); } } return rc; } /* ** Sync the database file for the pager pPager. zMaster points to the name ** of a master journal file that should be written into the individual ** journal file. zMaster may be NULL, which is interpreted as no master ** journal (a single database transaction). ** ** This routine ensures that: ** ** * The database file change-counter is updated, ** * the journal is synced (unless the atomic-write optimization is used), ** * all dirty pages are written to the database file, ** * the database file is truncated (if required), and ** * the database file synced. ** ** The only thing that remains to commit the transaction is to finalize ** (delete, truncate or zero the first part of) the journal file (or ** delete the master journal file if specified). ** ** Note that if zMaster==NULL, this does not overwrite a previous value ** passed to an sqlite3PagerCommitPhaseOne() call. ** ** If the final parameter - noSync - is true, then the database file itself ** is not synced. The caller must call sqlite3PagerSync() directly to ** sync the database file before calling CommitPhaseTwo() to delete the ** journal file in this case. */ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( Pager *pPager, /* Pager object */ const char *zMaster, /* If not NULL, the master journal name */ int noSync /* True to omit the xSync on the db file */ ){ int rc = SQLITE_OK; /* Return code */ assert( pPager->eState==PAGER_WRITER_LOCKED || pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD || pPager->eState==PAGER_ERROR ); assert( assert_pager_state(pPager) ); /* If a prior error occurred, report that error again. */ if( NEVER(pPager->errCode) ) return pPager->errCode; /* Provide the ability to easily simulate an I/O error during testing */ if( sqlite3FaultSim(400) ) return SQLITE_IOERR; PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", pPager->zFilename, zMaster, pPager->dbSize)); /* If no database changes have been made, return early. */ if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK; assert( MEMDB==0 || pPager->tempFile ); assert( isOpen(pPager->fd) || pPager->tempFile ); if( 0==pagerFlushOnCommit(pPager, 1) ){ /* If this is an in-memory db, or no pages have been written to, or this ** function has already been called, it is mostly a no-op. However, any ** backup in progress needs to be restarted. */ sqlite3BackupRestart(pPager->pBackup); }else{ if( pagerUseWal(pPager) ){ PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); PgHdr *pPageOne = 0; if( pList==0 ){ /* Must have at least one page for the WAL commit flag. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */ rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0); pList = pPageOne; pList->pDirty = 0; } assert( rc==SQLITE_OK ); if( ALWAYS(pList) ){ rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1); } sqlite3PagerUnref(pPageOne); if( rc==SQLITE_OK ){ sqlite3PcacheCleanAll(pPager->pPCache); } }else{ /* The following block updates the change-counter. Exactly how it ** does this depends on whether or not the atomic-update optimization ** was enabled at compile time, and if this transaction meets the ** runtime criteria to use the operation: ** ** * The file-system supports the atomic-write property for ** blocks of size page-size, and ** * This commit is not part of a multi-file transaction, and ** * Exactly one page has been modified and store in the journal file. ** ** If the optimization was not enabled at compile time, then the ** pager_incr_changecounter() function is called to update the change ** counter in 'indirect-mode'. If the optimization is compiled in but ** is not applicable to this transaction, call sqlite3JournalCreate() ** to make sure the journal file has actually been created, then call ** pager_incr_changecounter() to update the change-counter in indirect ** mode. ** ** Otherwise, if the optimization is both enabled and applicable, ** then call pager_incr_changecounter() to update the change-counter ** in 'direct' mode. In this case the journal file will never be ** created for this transaction. */ #ifdef SQLITE_ENABLE_ATOMIC_WRITE PgHdr *pPg; assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF || pPager->journalMode==PAGER_JOURNALMODE_WAL ); if( !zMaster && isOpen(pPager->jfd) && pPager->journalOff==jrnlBufferSize(pPager) && pPager->dbSize>=pPager->dbOrigSize && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty) ){ /* Update the db file change counter via the direct-write method. The ** following call will modify the in-memory representation of page 1 ** to include the updated change counter and then write page 1 ** directly to the database file. Because of the atomic-write ** property of the host file-system, this is safe. */ rc = pager_incr_changecounter(pPager, 1); }else{ rc = sqlite3JournalCreate(pPager->jfd); if( rc==SQLITE_OK ){ rc = pager_incr_changecounter(pPager, 0); } } #else rc = pager_incr_changecounter(pPager, 0); #endif if( rc!=SQLITE_OK ) goto commit_phase_one_exit; /* Write the master journal name into the journal file. If a master ** journal file name has already been written to the journal file, ** or if zMaster is NULL (no master journal), then this call is a no-op. */ rc = writeMasterJournal(pPager, zMaster); if( rc!=SQLITE_OK ) goto commit_phase_one_exit; /* Sync the journal file and write all dirty pages to the database. ** If the atomic-update optimization is being used, this sync will not ** create the journal file or perform any real IO. ** ** Because the change-counter page was just modified, unless the ** atomic-update optimization is used it is almost certain that the ** journal requires a sync here. However, in locking_mode=exclusive ** on a system under memory pressure it is just possible that this is ** not the case. In this case it is likely enough that the redundant ** xSync() call will be changed to a no-op by the OS anyhow. */ rc = syncJournal(pPager, 0); if( rc!=SQLITE_OK ) goto commit_phase_one_exit; rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache)); if( rc!=SQLITE_OK ){ assert( rc!=SQLITE_IOERR_BLOCKED ); goto commit_phase_one_exit; } sqlite3PcacheCleanAll(pPager->pPCache); /* If the file on disk is smaller than the database image, use ** pager_truncate to grow the file here. This can happen if the database ** image was extended as part of the current transaction and then the ** last page in the db image moved to the free-list. In this case the ** last page is never written out to disk, leaving the database file ** undersized. Fix this now if it is the case. */ if( pPager->dbSize>pPager->dbFileSize ){ Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager)); assert( pPager->eState==PAGER_WRITER_DBMOD ); rc = pager_truncate(pPager, nNew); if( rc!=SQLITE_OK ) goto commit_phase_one_exit; } /* Finally, sync the database file. */ if( !noSync ){ rc = sqlite3PagerSync(pPager, zMaster); } IOTRACE(("DBSYNC %p\n", pPager)) } } commit_phase_one_exit: if( rc==SQLITE_OK && !pagerUseWal(pPager) ){ pPager->eState = PAGER_WRITER_FINISHED; } return rc; } /* ** When this function is called, the database file has been completely ** updated to reflect the changes made by the current transaction and ** synced to disk. The journal file still exists in the file-system ** though, and if a failure occurs at this point it will eventually ** be used as a hot-journal and the current transaction rolled back. ** ** This function finalizes the journal file, either by deleting, ** truncating or partially zeroing it, so that it cannot be used ** for hot-journal rollback. Once this is done the transaction is ** irrevocably committed. ** ** If an error occurs, an IO error code is returned and the pager ** moves into the error state. Otherwise, SQLITE_OK is returned. */ SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ /* This routine should not be called if a prior error has occurred. ** But if (due to a coding error elsewhere in the system) it does get ** called, just return the same error code without doing anything. */ if( NEVER(pPager->errCode) ) return pPager->errCode; assert( pPager->eState==PAGER_WRITER_LOCKED || pPager->eState==PAGER_WRITER_FINISHED || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD) ); assert( assert_pager_state(pPager) ); /* An optimization. If the database was not actually modified during ** this transaction, the pager is running in exclusive-mode and is ** using persistent journals, then this function is a no-op. ** ** The start of the journal file currently contains a single journal ** header with the nRec field set to 0. If such a journal is used as ** a hot-journal during hot-journal rollback, 0 changes will be made ** to the database file. So there is no need to zero the journal ** header. Since the pager is in exclusive mode, there is no need ** to drop any locks either. */ if( pPager->eState==PAGER_WRITER_LOCKED && pPager->exclusiveMode && pPager->journalMode==PAGER_JOURNALMODE_PERSIST ){ assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff ); pPager->eState = PAGER_READER; return SQLITE_OK; } PAGERTRACE(("COMMIT %d\n", PAGERID(pPager))); pPager->iDataVersion++; rc = pager_end_transaction(pPager, pPager->setMaster, 1); return pager_error(pPager, rc); } /* ** If a write transaction is open, then all changes made within the ** transaction are reverted and the current write-transaction is closed. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR ** state if an error occurs. ** ** If the pager is already in PAGER_ERROR state when this function is called, ** it returns Pager.errCode immediately. No work is performed in this case. ** ** Otherwise, in rollback mode, this function performs two functions: ** ** 1) It rolls back the journal file, restoring all database file and ** in-memory cache pages to the state they were in when the transaction ** was opened, and ** ** 2) It finalizes the journal file, so that it is not used for hot ** rollback at any point in the future. ** ** Finalization of the journal file (task 2) is only performed if the ** rollback is successful. ** ** In WAL mode, all cache-entries containing data modified within the ** current transaction are either expelled from the cache or reverted to ** their pre-transaction state by re-reading data from the database or ** WAL files. The WAL transaction is then closed. */ SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager))); /* PagerRollback() is a no-op if called in READER or OPEN state. If ** the pager is already in the ERROR state, the rollback is not ** attempted here. Instead, the error code is returned to the caller. */ assert( assert_pager_state(pPager) ); if( pPager->eState==PAGER_ERROR ) return pPager->errCode; if( pPager->eState<=PAGER_READER ) return SQLITE_OK; if( pagerUseWal(pPager) ){ int rc2; rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1); rc2 = pager_end_transaction(pPager, pPager->setMaster, 0); if( rc==SQLITE_OK ) rc = rc2; }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){ int eState = pPager->eState; rc = pager_end_transaction(pPager, 0, 0); if( !MEMDB && eState>PAGER_WRITER_LOCKED ){ /* This can happen using journal_mode=off. Move the pager to the error ** state to indicate that the contents of the cache may not be trusted. ** Any active readers will get SQLITE_ABORT. */ pPager->errCode = SQLITE_ABORT; pPager->eState = PAGER_ERROR; setGetterMethod(pPager); return rc; } }else{ rc = pager_playback(pPager, 0); } assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK ); assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR || rc==SQLITE_CANTOPEN ); /* If an error occurs during a ROLLBACK, we can no longer trust the pager ** cache. So call pager_error() on the way out to make any error persistent. */ return pager_error(pPager, rc); } /* ** Return TRUE if the database file is opened read-only. Return FALSE ** if the database is (in theory) writable. */ SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){ return pPager->readOnly; } #ifdef SQLITE_DEBUG /* ** Return the sum of the reference counts for all pages held by pPager. */ SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){ return sqlite3PcacheRefCount(pPager->pPCache); } #endif /* ** Return the approximate number of bytes of memory currently ** used by the pager and its associated cache. */ SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){ int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr) + 5*sizeof(void*); return perPageSize*sqlite3PcachePagecount(pPager->pPCache) + sqlite3MallocSize(pPager) + pPager->pageSize; } /* ** Return the number of references to the specified page. */ SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){ return sqlite3PcachePageRefcount(pPage); } #ifdef SQLITE_TEST /* ** This routine is used for testing and analysis only. */ SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){ static int a[11]; a[0] = sqlite3PcacheRefCount(pPager->pPCache); a[1] = sqlite3PcachePagecount(pPager->pPCache); a[2] = sqlite3PcacheGetCachesize(pPager->pPCache); a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize; a[4] = pPager->eState; a[5] = pPager->errCode; a[6] = pPager->aStat[PAGER_STAT_HIT]; a[7] = pPager->aStat[PAGER_STAT_MISS]; a[8] = 0; /* Used to be pPager->nOvfl */ a[9] = pPager->nRead; a[10] = pPager->aStat[PAGER_STAT_WRITE]; return a; } #endif /* ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the ** current cache hit or miss count, according to the value of eStat. If the ** reset parameter is non-zero, the cache hit or miss count is zeroed before ** returning. */ SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){ assert( eStat==SQLITE_DBSTATUS_CACHE_HIT || eStat==SQLITE_DBSTATUS_CACHE_MISS || eStat==SQLITE_DBSTATUS_CACHE_WRITE ); assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS ); assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE ); assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 ); *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT]; if( reset ){ pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0; } } /* ** Return true if this is an in-memory or temp-file backed pager. */ SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){ return pPager->tempFile; } /* ** Check that there are at least nSavepoint savepoints open. If there are ** currently less than nSavepoints open, then open one or more savepoints ** to make up the difference. If the number of savepoints is already ** equal to nSavepoint, then this function is a no-op. ** ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error ** occurs while opening the sub-journal file, then an IO error code is ** returned. Otherwise, SQLITE_OK. */ static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){ int rc = SQLITE_OK; /* Return code */ int nCurrent = pPager->nSavepoint; /* Current number of savepoints */ int ii; /* Iterator variable */ PagerSavepoint *aNew; /* New Pager.aSavepoint array */ assert( pPager->eState>=PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); assert( nSavepoint>nCurrent && pPager->useJournal ); /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM ** if the allocation fails. Otherwise, zero the new portion in case a ** malloc failure occurs while populating it in the for(...) loop below. */ aNew = (PagerSavepoint *)sqlite3Realloc( pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint ); if( !aNew ){ return SQLITE_NOMEM_BKPT; } memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint)); pPager->aSavepoint = aNew; /* Populate the PagerSavepoint structures just allocated. */ for(ii=nCurrent; ii<nSavepoint; ii++){ aNew[ii].nOrig = pPager->dbSize; if( isOpen(pPager->jfd) && pPager->journalOff>0 ){ aNew[ii].iOffset = pPager->journalOff; }else{ aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager); } aNew[ii].iSubRec = pPager->nSubRec; aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize); if( !aNew[ii].pInSavepoint ){ return SQLITE_NOMEM_BKPT; } if( pagerUseWal(pPager) ){ sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData); } pPager->nSavepoint = ii+1; } assert( pPager->nSavepoint==nSavepoint ); assertTruncateConstraint(pPager); return rc; } SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ assert( pPager->eState>=PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){ return pagerOpenSavepoint(pPager, nSavepoint); }else{ return SQLITE_OK; } } /* ** This function is called to rollback or release (commit) a savepoint. ** The savepoint to release or rollback need not be the most recently ** created savepoint. ** ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes ** that have occurred since the specified savepoint was created. ** ** The savepoint to rollback or release is identified by parameter ** iSavepoint. A value of 0 means to operate on the outermost savepoint ** (the first created). A value of (Pager.nSavepoint-1) means operate ** on the most recently created savepoint. If iSavepoint is greater than ** (Pager.nSavepoint-1), then this function is a no-op. ** ** If a negative value is passed to this function, then the current ** transaction is rolled back. This is different to calling ** sqlite3PagerRollback() because this function does not terminate ** the transaction or unlock the database, it just restores the ** contents of the database to its original state. ** ** In any case, all savepoints with an index greater than iSavepoint ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE), ** then savepoint iSavepoint is also destroyed. ** ** This function may return SQLITE_NOMEM if a memory allocation fails, ** or an IO error code if an IO error occurs while rolling back a ** savepoint. If no errors occur, SQLITE_OK is returned. */ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ int rc = pPager->errCode; #ifdef SQLITE_ENABLE_ZIPVFS if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK; #endif assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK ); if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){ int ii; /* Iterator variable */ int nNew; /* Number of remaining savepoints after this op. */ /* Figure out how many savepoints will still be active after this ** operation. Store this value in nNew. Then free resources associated ** with any savepoints that are destroyed by this operation. */ nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1); for(ii=nNew; ii<pPager->nSavepoint; ii++){ sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); } pPager->nSavepoint = nNew; /* If this is a release of the outermost savepoint, truncate ** the sub-journal to zero bytes in size. */ if( op==SAVEPOINT_RELEASE ){ if( nNew==0 && isOpen(pPager->sjfd) ){ /* Only truncate if it is an in-memory sub-journal. */ if( sqlite3JournalIsInMemory(pPager->sjfd) ){ rc = sqlite3OsTruncate(pPager->sjfd, 0); assert( rc==SQLITE_OK ); } pPager->nSubRec = 0; } } /* Else this is a rollback operation, playback the specified savepoint. ** If this is a temp-file, it is possible that the journal file has ** not yet been opened. In this case there have been no changes to ** the database file, so the playback operation can be skipped. */ else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){ PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1]; rc = pagerPlaybackSavepoint(pPager, pSavepoint); assert(rc!=SQLITE_DONE); } #ifdef SQLITE_ENABLE_ZIPVFS /* If the cache has been modified but the savepoint cannot be rolled ** back journal_mode=off, put the pager in the error state. This way, ** if the VFS used by this pager includes ZipVFS, the entire transaction ** can be rolled back at the ZipVFS level. */ else if( pPager->journalMode==PAGER_JOURNALMODE_OFF && pPager->eState>=PAGER_WRITER_CACHEMOD ){ pPager->errCode = SQLITE_ABORT; pPager->eState = PAGER_ERROR; setGetterMethod(pPager); } #endif } return rc; } /* ** Return the full pathname of the database file. ** ** Except, if the pager is in-memory only, then return an empty string if ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when ** used to report the filename to the user, for compatibility with legacy ** behavior. But when the Btree needs to know the filename for matching to ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can ** participate in shared-cache. */ SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){ return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename; } /* ** Return the VFS structure for the pager. */ SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){ return pPager->pVfs; } /* ** Return the file handle for the database file associated ** with the pager. This might return NULL if the file has ** not yet been opened. */ SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){ return pPager->fd; } /* ** Return the file handle for the journal file (if it exists). ** This will be either the rollback journal or the WAL file. */ SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){ #if SQLITE_OMIT_WAL return pPager->jfd; #else return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd; #endif } /* ** Return the full pathname of the journal file. */ SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){ return pPager->zJournal; } #ifdef SQLITE_HAS_CODEC /* ** Set or retrieve the codec for this pager */ SQLITE_PRIVATE void sqlite3PagerSetCodec( Pager *pPager, void *(*xCodec)(void*,void*,Pgno,int), void (*xCodecSizeChng)(void*,int,int), void (*xCodecFree)(void*), void *pCodec ){ if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); pPager->xCodec = pPager->memDb ? 0 : xCodec; pPager->xCodecSizeChng = xCodecSizeChng; pPager->xCodecFree = xCodecFree; pPager->pCodec = pCodec; setGetterMethod(pPager); pagerReportSize(pPager); } SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){ return pPager->pCodec; } /* ** This function is called by the wal module when writing page content ** into the log file. ** ** This function returns a pointer to a buffer containing the encrypted ** page content. If a malloc fails, this function may return NULL. */ SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){ void *aData = 0; CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData); return aData; } /* ** Return the current pager state */ SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){ return pPager->eState; } #endif /* SQLITE_HAS_CODEC */ #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Move the page pPg to location pgno in the file. ** ** There must be no references to the page previously located at ** pgno (which we call pPgOld) though that page is allowed to be ** in cache. If the page previously located at pgno is not already ** in the rollback journal, it is not put there by by this routine. ** ** References to the page pPg remain valid. Updating any ** meta-data associated with pPg (i.e. data stored in the nExtra bytes ** allocated along with the page) is the responsibility of the caller. ** ** A transaction must be active when this routine is called. It used to be ** required that a statement transaction was not active, but this restriction ** has been removed (CREATE INDEX needs to move a page when a statement ** transaction is active). ** ** If the fourth argument, isCommit, is non-zero, then this page is being ** moved as part of a database reorganization just before the transaction ** is being committed. In this case, it is guaranteed that the database page ** pPg refers to will not be written to again within this transaction. ** ** This function may return SQLITE_NOMEM or an IO error code if an error ** occurs. Otherwise, it returns SQLITE_OK. */ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){ PgHdr *pPgOld; /* The page being overwritten. */ Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */ int rc; /* Return code */ Pgno origPgno; /* The original page number */ assert( pPg->nRef>0 ); assert( pPager->eState==PAGER_WRITER_CACHEMOD || pPager->eState==PAGER_WRITER_DBMOD ); assert( assert_pager_state(pPager) ); /* In order to be able to rollback, an in-memory database must journal ** the page we are moving from. */ assert( pPager->tempFile || !MEMDB ); if( pPager->tempFile ){ rc = sqlite3PagerWrite(pPg); if( rc ) return rc; } /* If the page being moved is dirty and has not been saved by the latest ** savepoint, then save the current contents of the page into the ** sub-journal now. This is required to handle the following scenario: ** ** BEGIN; ** <journal page X, then modify it in memory> ** SAVEPOINT one; ** <Move page X to location Y> ** ROLLBACK TO one; ** ** If page X were not written to the sub-journal here, it would not ** be possible to restore its contents when the "ROLLBACK TO one" ** statement were is processed. ** ** subjournalPage() may need to allocate space to store pPg->pgno into ** one or more savepoint bitvecs. This is the reason this function ** may return SQLITE_NOMEM. */ if( (pPg->flags & PGHDR_DIRTY)!=0 && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg)) ){ return rc; } PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno)); IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno)) /* If the journal needs to be sync()ed before page pPg->pgno can ** be written to, store pPg->pgno in local variable needSyncPgno. ** ** If the isCommit flag is set, there is no need to remember that ** the journal needs to be sync()ed before database page pPg->pgno ** can be written to. The caller has already promised not to write to it. */ if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){ needSyncPgno = pPg->pgno; assert( pPager->journalMode==PAGER_JOURNALMODE_OFF || pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize ); assert( pPg->flags&PGHDR_DIRTY ); } /* If the cache contains a page with page-number pgno, remove it ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for ** page pgno before the 'move' operation, it needs to be retained ** for the page moved there. */ pPg->flags &= ~PGHDR_NEED_SYNC; pPgOld = sqlite3PagerLookup(pPager, pgno); assert( !pPgOld || pPgOld->nRef==1 ); if( pPgOld ){ pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC); if( pPager->tempFile ){ /* Do not discard pages from an in-memory database since we might ** need to rollback later. Just move the page out of the way. */ sqlite3PcacheMove(pPgOld, pPager->dbSize+1); }else{ sqlite3PcacheDrop(pPgOld); } } origPgno = pPg->pgno; sqlite3PcacheMove(pPg, pgno); sqlite3PcacheMakeDirty(pPg); /* For an in-memory database, make sure the original page continues ** to exist, in case the transaction needs to roll back. Use pPgOld ** as the original page since it has already been allocated. */ if( pPager->tempFile && pPgOld ){ sqlite3PcacheMove(pPgOld, origPgno); sqlite3PagerUnrefNotNull(pPgOld); } if( needSyncPgno ){ /* If needSyncPgno is non-zero, then the journal file needs to be ** sync()ed before any data is written to database file page needSyncPgno. ** Currently, no such page exists in the page-cache and the ** "is journaled" bitvec flag has been set. This needs to be remedied by ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC ** flag. ** ** If the attempt to load the page into the page-cache fails, (due ** to a malloc() or IO failure), clear the bit in the pInJournal[] ** array. Otherwise, if the page is loaded and written again in ** this transaction, it may be written to the database file before ** it is synced into the journal file. This way, it may end up in ** the journal file twice, but that is not a problem. */ PgHdr *pPgHdr; rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0); if( rc!=SQLITE_OK ){ if( needSyncPgno<=pPager->dbOrigSize ){ assert( pPager->pTmpSpace!=0 ); sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace); } return rc; } pPgHdr->flags |= PGHDR_NEED_SYNC; sqlite3PcacheMakeDirty(pPgHdr); sqlite3PagerUnrefNotNull(pPgHdr); } return SQLITE_OK; } #endif /* ** The page handle passed as the first argument refers to a dirty page ** with a page number other than iNew. This function changes the page's ** page number to iNew and sets the value of the PgHdr.flags field to ** the value passed as the third parameter. */ SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){ assert( pPg->pgno!=iNew ); pPg->flags = flags; sqlite3PcacheMove(pPg, iNew); } /* ** Return a pointer to the data for the specified page. */ SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){ assert( pPg->nRef>0 || pPg->pPager->memDb ); return pPg->pData; } /* ** Return a pointer to the Pager.nExtra bytes of "extra" space ** allocated along with the specified page. */ SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){ return pPg->pExtra; } /* ** Get/set the locking-mode for this pager. Parameter eMode must be one ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then ** the locking-mode is set to the value specified. ** ** The returned value is either PAGER_LOCKINGMODE_NORMAL or ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) ** locking-mode. */ SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){ assert( eMode==PAGER_LOCKINGMODE_QUERY || eMode==PAGER_LOCKINGMODE_NORMAL || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); assert( PAGER_LOCKINGMODE_QUERY<0 ); assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 ); assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) ); if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){ pPager->exclusiveMode = (u8)eMode; } return (int)pPager->exclusiveMode; } /* ** Set the journal-mode for this pager. Parameter eMode must be one of: ** ** PAGER_JOURNALMODE_DELETE ** PAGER_JOURNALMODE_TRUNCATE ** PAGER_JOURNALMODE_PERSIST ** PAGER_JOURNALMODE_OFF ** PAGER_JOURNALMODE_MEMORY ** PAGER_JOURNALMODE_WAL ** ** The journalmode is set to the value specified if the change is allowed. ** The change may be disallowed for the following reasons: ** ** * An in-memory database can only have its journal_mode set to _OFF ** or _MEMORY. ** ** * Temporary databases cannot have _WAL journalmode. ** ** The returned indicate the current (possibly updated) journal-mode. */ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ u8 eOld = pPager->journalMode; /* Prior journalmode */ #ifdef SQLITE_DEBUG /* The print_pager_state() routine is intended to be used by the debugger ** only. We invoke it once here to suppress a compiler warning. */ print_pager_state(pPager); #endif /* The eMode parameter is always valid */ assert( eMode==PAGER_JOURNALMODE_DELETE || eMode==PAGER_JOURNALMODE_TRUNCATE || eMode==PAGER_JOURNALMODE_PERSIST || eMode==PAGER_JOURNALMODE_OFF || eMode==PAGER_JOURNALMODE_WAL || eMode==PAGER_JOURNALMODE_MEMORY ); /* This routine is only called from the OP_JournalMode opcode, and ** the logic there will never allow a temporary file to be changed ** to WAL mode. */ assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL ); /* Do allow the journalmode of an in-memory database to be set to ** anything other than MEMORY or OFF */ if( MEMDB ){ assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF ); if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){ eMode = eOld; } } if( eMode!=eOld ){ /* Change the journal mode. */ assert( pPager->eState!=PAGER_ERROR ); pPager->journalMode = (u8)eMode; /* When transistioning from TRUNCATE or PERSIST to any other journal ** mode except WAL, unless the pager is in locking_mode=exclusive mode, ** delete the journal file. */ assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); assert( (PAGER_JOURNALMODE_DELETE & 5)==0 ); assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 ); assert( (PAGER_JOURNALMODE_OFF & 5)==0 ); assert( (PAGER_JOURNALMODE_WAL & 5)==5 ); assert( isOpen(pPager->fd) || pPager->exclusiveMode ); if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){ /* In this case we would like to delete the journal file. If it is ** not possible, then that is not a problem. Deleting the journal file ** here is an optimization only. ** ** Before deleting the journal file, obtain a RESERVED lock on the ** database file. This ensures that the journal file is not deleted ** while it is in use by some other client. */ sqlite3OsClose(pPager->jfd); if( pPager->eLock>=RESERVED_LOCK ){ sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); }else{ int rc = SQLITE_OK; int state = pPager->eState; assert( state==PAGER_OPEN || state==PAGER_READER ); if( state==PAGER_OPEN ){ rc = sqlite3PagerSharedLock(pPager); } if( pPager->eState==PAGER_READER ){ assert( rc==SQLITE_OK ); rc = pagerLockDb(pPager, RESERVED_LOCK); } if( rc==SQLITE_OK ){ sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); } if( rc==SQLITE_OK && state==PAGER_READER ){ pagerUnlockDb(pPager, SHARED_LOCK); }else if( state==PAGER_OPEN ){ pager_unlock(pPager); } assert( state==pPager->eState ); } }else if( eMode==PAGER_JOURNALMODE_OFF ){ sqlite3OsClose(pPager->jfd); } } /* Return the new journal mode */ return (int)pPager->journalMode; } /* ** Return the current journal mode. */ SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){ return (int)pPager->journalMode; } /* ** Return TRUE if the pager is in a state where it is OK to change the ** journalmode. Journalmode changes can only happen when the database ** is unmodified. */ SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){ assert( assert_pager_state(pPager) ); if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0; if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0; return 1; } /* ** Get/set the size-limit used for persistent journal files. ** ** Setting the size limit to -1 means no limit is enforced. ** An attempt to set a limit smaller than -1 is a no-op. */ SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ if( iLimit>=-1 ){ pPager->journalSizeLimit = iLimit; sqlite3WalLimit(pPager->pWal, iLimit); } return pPager->journalSizeLimit; } /* ** Return a pointer to the pPager->pBackup variable. The backup module ** in backup.c maintains the content of this variable. This module ** uses it opaquely as an argument to sqlite3BackupRestart() and ** sqlite3BackupUpdate() only. */ SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){ return &pPager->pBackup; } #ifndef SQLITE_OMIT_VACUUM /* ** Unless this is an in-memory or temporary database, clear the pager cache. */ SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){ assert( MEMDB==0 || pPager->tempFile ); if( pPager->tempFile==0 ) pager_reset(pPager); } #endif #ifndef SQLITE_OMIT_WAL /* ** This function is called when the user invokes "PRAGMA wal_checkpoint", ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint() ** or wal_blocking_checkpoint() API functions. ** ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. */ SQLITE_PRIVATE int sqlite3PagerCheckpoint( Pager *pPager, /* Checkpoint on this pager */ sqlite3 *db, /* Db handle used to check for interrupts */ int eMode, /* Type of checkpoint */ int *pnLog, /* OUT: Final number of frames in log */ int *pnCkpt /* OUT: Final number of checkpointed frames */ ){ int rc = SQLITE_OK; if( pPager->pWal ){ rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode, (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler), pPager->pBusyHandlerArg, pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, pnLog, pnCkpt ); } return rc; } SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){ return sqlite3WalCallback(pPager->pWal); } /* ** Return true if the underlying VFS for the given pager supports the ** primitives necessary for write-ahead logging. */ SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){ const sqlite3_io_methods *pMethods = pPager->fd->pMethods; if( pPager->noLock ) return 0; return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap); } /* ** Attempt to take an exclusive lock on the database file. If a PENDING lock ** is obtained instead, immediately release it. */ static int pagerExclusiveLock(Pager *pPager){ int rc; /* Return code */ assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); if( rc!=SQLITE_OK ){ /* If the attempt to grab the exclusive lock failed, release the ** pending lock that may have been obtained instead. */ pagerUnlockDb(pPager, SHARED_LOCK); } return rc; } /* ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in ** exclusive-locking mode when this function is called, take an EXCLUSIVE ** lock on the database file and use heap-memory to store the wal-index ** in. Otherwise, use the normal shared-memory. */ static int pagerOpenWal(Pager *pPager){ int rc = SQLITE_OK; assert( pPager->pWal==0 && pPager->tempFile==0 ); assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); /* If the pager is already in exclusive-mode, the WAL module will use ** heap-memory for the wal-index instead of the VFS shared-memory ** implementation. Take the exclusive lock now, before opening the WAL ** file, to make sure this is safe. */ if( pPager->exclusiveMode ){ rc = pagerExclusiveLock(pPager); } /* Open the connection to the log file. If this operation fails, ** (e.g. due to malloc() failure), return an error code. */ if( rc==SQLITE_OK ){ rc = sqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, pPager->exclusiveMode, pPager->journalSizeLimit, &pPager->pWal ); } pagerFixMaplimit(pPager); return rc; } /* ** The caller must be holding a SHARED lock on the database file to call ** this function. ** ** If the pager passed as the first argument is open on a real database ** file (not a temp file or an in-memory database), and the WAL file ** is not already open, make an attempt to open it now. If successful, ** return SQLITE_OK. If an error occurs or the VFS used by the pager does ** not support the xShmXXX() methods, return an error code. *pbOpen is ** not modified in either case. ** ** If the pager is open on a temp-file (or in-memory database), or if ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK ** without doing anything. */ SQLITE_PRIVATE int sqlite3PagerOpenWal( Pager *pPager, /* Pager object */ int *pbOpen /* OUT: Set to true if call is a no-op */ ){ int rc = SQLITE_OK; /* Return code */ assert( assert_pager_state(pPager) ); assert( pPager->eState==PAGER_OPEN || pbOpen ); assert( pPager->eState==PAGER_READER || !pbOpen ); assert( pbOpen==0 || *pbOpen==0 ); assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) ); if( !pPager->tempFile && !pPager->pWal ){ if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN; /* Close any rollback journal previously open */ sqlite3OsClose(pPager->jfd); rc = pagerOpenWal(pPager); if( rc==SQLITE_OK ){ pPager->journalMode = PAGER_JOURNALMODE_WAL; pPager->eState = PAGER_OPEN; } }else{ *pbOpen = 1; } return rc; } /* ** This function is called to close the connection to the log file prior ** to switching from WAL to rollback mode. ** ** Before closing the log file, this function attempts to take an ** EXCLUSIVE lock on the database file. If this cannot be obtained, an ** error (SQLITE_BUSY) is returned and the log connection is not closed. ** If successful, the EXCLUSIVE lock is not released before returning. */ SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){ int rc = SQLITE_OK; assert( pPager->journalMode==PAGER_JOURNALMODE_WAL ); /* If the log file is not already open, but does exist in the file-system, ** it may need to be checkpointed before the connection can switch to ** rollback mode. Open it now so this can happen. */ if( !pPager->pWal ){ int logexists = 0; rc = pagerLockDb(pPager, SHARED_LOCK); if( rc==SQLITE_OK ){ rc = sqlite3OsAccess( pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists ); } if( rc==SQLITE_OK && logexists ){ rc = pagerOpenWal(pPager); } } /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on ** the database file, the log and log-summary files will be deleted. */ if( rc==SQLITE_OK && pPager->pWal ){ rc = pagerExclusiveLock(pPager); if( rc==SQLITE_OK ){ rc = sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags, pPager->pageSize, (u8*)pPager->pTmpSpace); pPager->pWal = 0; pagerFixMaplimit(pPager); if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); } } return rc; } #ifdef SQLITE_ENABLE_SNAPSHOT /* ** If this is a WAL database, obtain a snapshot handle for the snapshot ** currently open. Otherwise, return an error. */ SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){ int rc = SQLITE_ERROR; if( pPager->pWal ){ rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot); } return rc; } /* ** If this is a WAL database, store a pointer to pSnapshot. Next time a ** read transaction is opened, attempt to read from the snapshot it ** identifies. If this is not a WAL database, return an error. */ SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){ int rc = SQLITE_OK; if( pPager->pWal ){ sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot); }else{ rc = SQLITE_ERROR; } return rc; } /* ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this ** is not a WAL database, return an error. */ SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){ int rc; if( pPager->pWal ){ rc = sqlite3WalSnapshotRecover(pPager->pWal); }else{ rc = SQLITE_ERROR; } return rc; } #endif /* SQLITE_ENABLE_SNAPSHOT */ #endif /* !SQLITE_OMIT_WAL */ #ifdef SQLITE_ENABLE_ZIPVFS /* ** A read-lock must be held on the pager when this function is called. If ** the pager is in WAL mode and the WAL file currently contains one or more ** frames, return the size in bytes of the page images stored within the ** WAL frames. Otherwise, if this is not a WAL database or the WAL file ** is empty, return 0. */ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){ assert( pPager->eState>=PAGER_READER ); return sqlite3WalFramesize(pPager->pWal); } #endif #endif /* SQLITE_OMIT_DISKIO */ /************** End of pager.c ***********************************************/ /************** Begin file wal.c *********************************************/ /* ** 2010 February 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the implementation of a write-ahead log (WAL) used in ** "journal_mode=WAL" mode. ** ** WRITE-AHEAD LOG (WAL) FILE FORMAT ** ** A WAL file consists of a header followed by zero or more "frames". ** Each frame records the revised content of a single page from the ** database file. All changes to the database are recorded by writing ** frames into the WAL. Transactions commit when a frame is written that ** contains a commit marker. A single WAL can and usually does record ** multiple transactions. Periodically, the content of the WAL is ** transferred back into the database file in an operation called a ** "checkpoint". ** ** A single WAL file can be used multiple times. In other words, the ** WAL can fill up with frames and then be checkpointed and then new ** frames can overwrite the old ones. A WAL always grows from beginning ** toward the end. Checksums and counters attached to each frame are ** used to determine which frames within the WAL are valid and which ** are leftovers from prior checkpoints. ** ** The WAL header is 32 bytes in size and consists of the following eight ** big-endian 32-bit unsigned integer values: ** ** 0: Magic number. 0x377f0682 or 0x377f0683 ** 4: File format version. Currently 3007000 ** 8: Database page size. Example: 1024 ** 12: Checkpoint sequence number ** 16: Salt-1, random integer incremented with each checkpoint ** 20: Salt-2, a different random integer changing with each ckpt ** 24: Checksum-1 (first part of checksum for first 24 bytes of header). ** 28: Checksum-2 (second part of checksum for first 24 bytes of header). ** ** Immediately following the wal-header are zero or more frames. Each ** frame consists of a 24-byte frame-header followed by a <page-size> bytes ** of page data. The frame-header is six big-endian 32-bit unsigned ** integer values, as follows: ** ** 0: Page number. ** 4: For commit records, the size of the database image in pages ** after the commit. For all other records, zero. ** 8: Salt-1 (copied from the header) ** 12: Salt-2 (copied from the header) ** 16: Checksum-1. ** 20: Checksum-2. ** ** A frame is considered valid if and only if the following conditions are ** true: ** ** (1) The salt-1 and salt-2 values in the frame-header match ** salt values in the wal-header ** ** (2) The checksum values in the final 8 bytes of the frame-header ** exactly match the checksum computed consecutively on the ** WAL header and the first 8 bytes and the content of all frames ** up to and including the current frame. ** ** The checksum is computed using 32-bit big-endian integers if the ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it ** is computed using little-endian if the magic number is 0x377f0682. ** The checksum values are always stored in the frame header in a ** big-endian format regardless of which byte order is used to compute ** the checksum. The checksum is computed by interpreting the input as ** an even number of unsigned 32-bit integers: x[0] through x[N]. The ** algorithm used for the checksum is as follows: ** ** for i from 0 to n-1 step 2: ** s0 += x[i] + s1; ** s1 += x[i+1] + s0; ** endfor ** ** Note that s0 and s1 are both weighted checksums using fibonacci weights ** in reverse order (the largest fibonacci weight occurs on the first element ** of the sequence being summed.) The s1 value spans all 32-bit ** terms of the sequence whereas s0 omits the final term. ** ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the ** WAL is transferred into the database, then the database is VFS.xSync-ed. ** The VFS.xSync operations serve as write barriers - all writes launched ** before the xSync must complete before any write that launches after the ** xSync begins. ** ** After each checkpoint, the salt-1 value is incremented and the salt-2 ** value is randomized. This prevents old and new frames in the WAL from ** being considered valid at the same time and being checkpointing together ** following a crash. ** ** READER ALGORITHM ** ** To read a page from the database (call it page number P), a reader ** first checks the WAL to see if it contains page P. If so, then the ** last valid instance of page P that is a followed by a commit frame ** or is a commit frame itself becomes the value read. If the WAL ** contains no copies of page P that are valid and which are a commit ** frame or are followed by a commit frame, then page P is read from ** the database file. ** ** To start a read transaction, the reader records the index of the last ** valid frame in the WAL. The reader uses this recorded "mxFrame" value ** for all subsequent read operations. New transactions can be appended ** to the WAL, but as long as the reader uses its original mxFrame value ** and ignores the newly appended content, it will see a consistent snapshot ** of the database from a single point in time. This technique allows ** multiple concurrent readers to view different versions of the database ** content simultaneously. ** ** The reader algorithm in the previous paragraphs works correctly, but ** because frames for page P can appear anywhere within the WAL, the ** reader has to scan the entire WAL looking for page P frames. If the ** WAL is large (multiple megabytes is typical) that scan can be slow, ** and read performance suffers. To overcome this problem, a separate ** data structure called the wal-index is maintained to expedite the ** search for frames of a particular page. ** ** WAL-INDEX FORMAT ** ** Conceptually, the wal-index is shared memory, though VFS implementations ** might choose to implement the wal-index using a mmapped file. Because ** the wal-index is shared memory, SQLite does not support journal_mode=WAL ** on a network filesystem. All users of the database must be able to ** share memory. ** ** The wal-index is transient. After a crash, the wal-index can (and should ** be) reconstructed from the original WAL file. In fact, the VFS is required ** to either truncate or zero the header of the wal-index when the last ** connection to it closes. Because the wal-index is transient, it can ** use an architecture-specific format; it does not have to be cross-platform. ** Hence, unlike the database and WAL file formats which store all values ** as big endian, the wal-index can store multi-byte values in the native ** byte order of the host computer. ** ** The purpose of the wal-index is to answer this question quickly: Given ** a page number P and a maximum frame index M, return the index of the ** last frame in the wal before frame M for page P in the WAL, or return ** NULL if there are no frames for page P in the WAL prior to M. ** ** The wal-index consists of a header region, followed by an one or ** more index blocks. ** ** The wal-index header contains the total number of frames within the WAL ** in the mxFrame field. ** ** Each index block except for the first contains information on ** HASHTABLE_NPAGE frames. The first index block contains information on ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and ** HASHTABLE_NPAGE are selected so that together the wal-index header and ** first index block are the same size as all other index blocks in the ** wal-index. ** ** Each index block contains two sections, a page-mapping that contains the ** database page number associated with each wal frame, and a hash-table ** that allows readers to query an index block for a specific page number. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE ** for the first index block) 32-bit page numbers. The first entry in the ** first index-block contains the database page number corresponding to the ** first frame in the WAL file. The first entry in the second index block ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in ** the log, and so on. ** ** The last index block in a wal-index usually contains less than the full ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers, ** depending on the contents of the WAL file. This does not change the ** allocated size of the page-mapping array - the page-mapping array merely ** contains unused entries. ** ** Even without using the hash table, the last frame for page P ** can be found by scanning the page-mapping sections of each index block ** starting with the last index block and moving toward the first, and ** within each index block, starting at the end and moving toward the ** beginning. The first entry that equals P corresponds to the frame ** holding the content for that page. ** ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the ** hash table for each page number in the mapping section, so the hash ** table is never more than half full. The expected number of collisions ** prior to finding a match is 1. Each entry of the hash table is an ** 1-based index of an entry in the mapping section of the same ** index block. Let K be the 1-based index of the largest entry in ** the mapping section. (For index blocks other than the last, K will ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table ** contain a value of 0. ** ** To look for page P in the hash table, first compute a hash iKey on ** P as follows: ** ** iKey = (P * 383) % HASHTABLE_NSLOT ** ** Then start scanning entries of the hash table, starting with iKey ** (wrapping around to the beginning when the end of the hash table is ** reached) until an unused hash slot is found. Let the first unused slot ** be at index iUnused. (iUnused might be less than iKey if there was ** wrap-around.) Because the hash table is never more than half full, ** the search is guaranteed to eventually hit an unused entry. Let ** iMax be the value between iKey and iUnused, closest to iUnused, ** where aHash[iMax]==P. If there is no iMax entry (if there exists ** no hash slot such that aHash[i]==p) then page P is not in the ** current index block. Otherwise the iMax-th mapping entry of the ** current index block corresponds to the last entry that references ** page P. ** ** A hash search begins with the last index block and moves toward the ** first index block, looking for entries corresponding to page P. On ** average, only two or three slots in each index block need to be ** examined in order to either find the last entry for page P, or to ** establish that no such entry exists in the block. Each index block ** holds over 4000 entries. So two or three index blocks are sufficient ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10 ** comparisons (on average) suffice to either locate a frame in the ** WAL or to establish that the frame does not exist in the WAL. This ** is much faster than scanning the entire 10MB WAL. ** ** Note that entries are added in order of increasing K. Hence, one ** reader might be using some value K0 and a second reader that started ** at a later time (after additional transactions were added to the WAL ** and to the wal-index) might be using a different value K1, where K1>K0. ** Both readers can use the same hash table and mapping section to get ** the correct result. There may be entries in the hash table with ** K>K0 but to the first reader, those entries will appear to be unused ** slots in the hash table and so the first reader will get an answer as ** if no values greater than K0 had ever been inserted into the hash table ** in the first place - which is what reader one wants. Meanwhile, the ** second reader using K1 will see additional values that were inserted ** later, which is exactly what reader two wants. ** ** When a rollback occurs, the value of K is decreased. Hash table entries ** that correspond to frames greater than the new K value are removed ** from the hash table at this point. */ #ifndef SQLITE_OMIT_WAL /* #include "wal.h" */ /* ** Trace output macros */ #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) SQLITE_PRIVATE int sqlite3WalTrace = 0; # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X #else # define WALTRACE(X) #endif /* ** The maximum (and only) versions of the wal and wal-index formats ** that may be interpreted by this version of SQLite. ** ** If a client begins recovering a WAL file and finds that (a) the checksum ** values in the wal-header are correct and (b) the version field is not ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN. ** ** Similarly, if a client successfully reads a wal-index header (i.e. the ** checksum test is successful) and finds that the version field is not ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite ** returns SQLITE_CANTOPEN. */ #define WAL_MAX_VERSION 3007000 #define WALINDEX_MAX_VERSION 3007000 /* ** Indices of various locking bytes. WAL_NREADER is the number ** of available reader locks and should be at least 3. The default ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5. */ #define WAL_WRITE_LOCK 0 #define WAL_ALL_BUT_WRITE 1 #define WAL_CKPT_LOCK 1 #define WAL_RECOVER_LOCK 2 #define WAL_READ_LOCK(I) (3+(I)) #define WAL_NREADER (SQLITE_SHM_NLOCK-3) /* Object declarations */ typedef struct WalIndexHdr WalIndexHdr; typedef struct WalIterator WalIterator; typedef struct WalCkptInfo WalCkptInfo; /* ** The following object holds a copy of the wal-index header content. ** ** The actual header in the wal-index consists of two copies of this ** object followed by one instance of the WalCkptInfo object. ** For all versions of SQLite through 3.10.0 and probably beyond, ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and ** the total header size is 136 bytes. ** ** The szPage value can be any power of 2 between 512 and 32768, inclusive. ** Or it can be 1 to represent a 65536-byte page. The latter case was ** added in 3.7.1 when support for 64K pages was added. */ struct WalIndexHdr { u32 iVersion; /* Wal-index version */ u32 unused; /* Unused (padding) field */ u32 iChange; /* Counter incremented each transaction */ u8 isInit; /* 1 when initialized */ u8 bigEndCksum; /* True if checksums in WAL are big-endian */ u16 szPage; /* Database page size in bytes. 1==64K */ u32 mxFrame; /* Index of last valid frame in the WAL */ u32 nPage; /* Size of database in pages */ u32 aFrameCksum[2]; /* Checksum of last frame in log */ u32 aSalt[2]; /* Two salt values copied from WAL header */ u32 aCksum[2]; /* Checksum over all prior fields */ }; /* ** A copy of the following object occurs in the wal-index immediately ** following the second copy of the WalIndexHdr. This object stores ** information used by checkpoint. ** ** nBackfill is the number of frames in the WAL that have been written ** back into the database. (We call the act of moving content from WAL to ** database "backfilling".) The nBackfill number is never greater than ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread). ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from ** mxFrame back to zero when the WAL is reset. ** ** nBackfillAttempted is the largest value of nBackfill that a checkpoint ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however ** the nBackfillAttempted is set before any backfilling is done and the ** nBackfill is only set after all backfilling completes. So if a checkpoint ** crashes, nBackfillAttempted might be larger than nBackfill. The ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted. ** ** The aLock[] field is a set of bytes used for locking. These bytes should ** never be read or written. ** ** There is one entry in aReadMark[] for each reader lock. If a reader ** holds read-lock K, then the value in aReadMark[K] is no greater than ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff) ** for any aReadMark[] means that entry is unused. aReadMark[0] is ** a special case; its value is never used and it exists as a place-holder ** to avoid having to offset aReadMark[] indexs by one. Readers holding ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content ** directly from the database. ** ** The value of aReadMark[K] may only be changed by a thread that ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of ** aReadMark[K] cannot changed while there is a reader is using that mark ** since the reader will be holding a shared lock on WAL_READ_LOCK(K). ** ** The checkpointer may only transfer frames from WAL to database where ** the frame numbers are less than or equal to every aReadMark[] that is ** in use (that is, every aReadMark[j] for which there is a corresponding ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the ** largest value and will increase an unused aReadMark[] to mxFrame if there ** is not already an aReadMark[] equal to mxFrame. The exception to the ** previous sentence is when nBackfill equals mxFrame (meaning that everything ** in the WAL has been backfilled into the database) then new readers ** will choose aReadMark[0] which has value 0 and hence such reader will ** get all their all content directly from the database file and ignore ** the WAL. ** ** Writers normally append new frames to the end of the WAL. However, ** if nBackfill equals mxFrame (meaning that all WAL content has been ** written back into the database) and if no readers are using the WAL ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then ** the writer will first "reset" the WAL back to the beginning and start ** writing new content beginning at frame 1. ** ** We assume that 32-bit loads are atomic and so no locks are needed in ** order to read from any aReadMark[] entries. */ struct WalCkptInfo { u32 nBackfill; /* Number of WAL frames backfilled into DB */ u32 aReadMark[WAL_NREADER]; /* Reader marks */ u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */ u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */ u32 notUsed0; /* Available for future enhancements */ }; #define READMARK_NOT_USED 0xffffffff /* A block of WALINDEX_LOCK_RESERVED bytes beginning at ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems ** only support mandatory file-locks, we do not read or write data ** from the region of the file on which locks are applied. */ #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock)) #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo)) /* Size of header before each frame in wal */ #define WAL_FRAME_HDRSIZE 24 /* Size of write ahead log header, including checksum. */ /* #define WAL_HDRSIZE 24 */ #define WAL_HDRSIZE 32 /* WAL magic value. Either this value, or the same value with the least ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit ** big-endian format in the first 4 bytes of a WAL file. ** ** If the LSB is set, then the checksums for each frame within the WAL ** file are calculated by treating all data as an array of 32-bit ** big-endian words. Otherwise, they are calculated by interpreting ** all data as 32-bit little-endian words. */ #define WAL_MAGIC 0x377f0682 /* ** Return the offset of frame iFrame in the write-ahead log file, ** assuming a database page size of szPage bytes. The offset returned ** is to the start of the write-ahead log frame-header. */ #define walFrameOffset(iFrame, szPage) ( \ WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \ ) /* ** An open write-ahead log file is represented by an instance of the ** following object. */ struct Wal { sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ sqlite3_file *pDbFd; /* File handle for the database file */ sqlite3_file *pWalFd; /* File handle for WAL file */ u32 iCallback; /* Value to pass to log callback (or 0) */ i64 mxWalSize; /* Truncate WAL to this size upon reset */ int nWiData; /* Size of array apWiData */ int szFirstBlock; /* Size of first block written to WAL file */ volatile u32 **apWiData; /* Pointer to wal-index content in memory */ u32 szPage; /* Database page size */ i16 readLock; /* Which read lock is being held. -1 for none */ u8 syncFlags; /* Flags to use to sync header writes */ u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */ u8 writeLock; /* True if in a write transaction */ u8 ckptLock; /* True if holding a checkpoint lock */ u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */ u8 truncateOnCommit; /* True to truncate WAL file on commit */ u8 syncHeader; /* Fsync the WAL header if true */ u8 padToSectorBoundary; /* Pad transactions out to the next sector */ WalIndexHdr hdr; /* Wal-index header for current transaction */ u32 minFrame; /* Ignore wal frames before this one */ u32 iReCksum; /* On commit, recalculate checksums from here */ const char *zWalName; /* Name of WAL file */ u32 nCkpt; /* Checkpoint sequence counter in the wal-header */ #ifdef SQLITE_DEBUG u8 lockError; /* True if a locking error has occurred */ #endif #ifdef SQLITE_ENABLE_SNAPSHOT WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */ #endif }; /* ** Candidate values for Wal.exclusiveMode. */ #define WAL_NORMAL_MODE 0 #define WAL_EXCLUSIVE_MODE 1 #define WAL_HEAPMEMORY_MODE 2 /* ** Possible values for WAL.readOnly */ #define WAL_RDWR 0 /* Normal read/write connection */ #define WAL_RDONLY 1 /* The WAL file is readonly */ #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */ /* ** Each page of the wal-index mapping contains a hash-table made up of ** an array of HASHTABLE_NSLOT elements of the following type. */ typedef u16 ht_slot; /* ** This structure is used to implement an iterator that loops through ** all frames in the WAL in database page order. Where two or more frames ** correspond to the same database page, the iterator visits only the ** frame most recently written to the WAL (in other words, the frame with ** the largest index). ** ** The internals of this structure are only accessed by: ** ** walIteratorInit() - Create a new iterator, ** walIteratorNext() - Step an iterator, ** walIteratorFree() - Free an iterator. ** ** This functionality is used by the checkpoint code (see walCheckpoint()). */ struct WalIterator { int iPrior; /* Last result returned from the iterator */ int nSegment; /* Number of entries in aSegment[] */ struct WalSegment { int iNext; /* Next slot in aIndex[] not yet returned */ ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */ u32 *aPgno; /* Array of page numbers. */ int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */ int iZero; /* Frame number associated with aPgno[0] */ } aSegment[1]; /* One for every 32KB page in the wal-index */ }; /* ** Define the parameters of the hash tables in the wal-index file. There ** is a hash-table following every HASHTABLE_NPAGE page numbers in the ** wal-index. ** ** Changing any of these constants will alter the wal-index format and ** create incompatibilities. */ #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */ #define HASHTABLE_HASH_1 383 /* Should be prime */ #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */ /* ** The block of page numbers associated with the first hash-table in a ** wal-index is smaller than usual. This is so that there is a complete ** hash-table on each aligned 32KB page of the wal-index. */ #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32))) /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */ #define WALINDEX_PGSZ ( \ sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \ ) /* ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are ** numbered from zero. ** ** If this call is successful, *ppPage is set to point to the wal-index ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs, ** then an SQLite error code is returned and *ppPage is set to 0. */ static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){ int rc = SQLITE_OK; /* Enlarge the pWal->apWiData[] array if required */ if( pWal->nWiData<=iPage ){ int nByte = sizeof(u32*)*(iPage+1); volatile u32 **apNew; apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte); if( !apNew ){ *ppPage = 0; return SQLITE_NOMEM_BKPT; } memset((void*)&apNew[pWal->nWiData], 0, sizeof(u32*)*(iPage+1-pWal->nWiData)); pWal->apWiData = apNew; pWal->nWiData = iPage+1; } /* Request a pointer to the required page from the VFS */ if( pWal->apWiData[iPage]==0 ){ if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ); if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT; }else{ rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, pWal->writeLock, (void volatile **)&pWal->apWiData[iPage] ); if( rc==SQLITE_READONLY ){ pWal->readOnly |= WAL_SHM_RDONLY; rc = SQLITE_OK; } } } *ppPage = pWal->apWiData[iPage]; assert( iPage==0 || *ppPage || rc!=SQLITE_OK ); return rc; } /* ** Return a pointer to the WalCkptInfo structure in the wal-index. */ static volatile WalCkptInfo *walCkptInfo(Wal *pWal){ assert( pWal->nWiData>0 && pWal->apWiData[0] ); return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]); } /* ** Return a pointer to the WalIndexHdr structure in the wal-index. */ static volatile WalIndexHdr *walIndexHdr(Wal *pWal){ assert( pWal->nWiData>0 && pWal->apWiData[0] ); return (volatile WalIndexHdr*)pWal->apWiData[0]; } /* ** The argument to this macro must be of type u32. On a little-endian ** architecture, it returns the u32 value that results from interpreting ** the 4 bytes as a big-endian value. On a big-endian architecture, it ** returns the value that would be produced by interpreting the 4 bytes ** of the input value as a little-endian integer. */ #define BYTESWAP32(x) ( \ (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \ + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \ ) /* ** Generate or extend an 8 byte checksum based on the data in ** array aByte[] and the initial values of aIn[0] and aIn[1] (or ** initial values of 0 and 0 if aIn==NULL). ** ** The checksum is written back into aOut[] before returning. ** ** nByte must be a positive multiple of 8. */ static void walChecksumBytes( int nativeCksum, /* True for native byte-order, false for non-native */ u8 *a, /* Content to be checksummed */ int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */ const u32 *aIn, /* Initial checksum value input */ u32 *aOut /* OUT: Final checksum value output */ ){ u32 s1, s2; u32 *aData = (u32 *)a; u32 *aEnd = (u32 *)&a[nByte]; if( aIn ){ s1 = aIn[0]; s2 = aIn[1]; }else{ s1 = s2 = 0; } assert( nByte>=8 ); assert( (nByte&0x00000007)==0 ); if( nativeCksum ){ do { s1 += *aData++ + s2; s2 += *aData++ + s1; }while( aData<aEnd ); }else{ do { s1 += BYTESWAP32(aData[0]) + s2; s2 += BYTESWAP32(aData[1]) + s1; aData += 2; }while( aData<aEnd ); } aOut[0] = s1; aOut[1] = s2; } static void walShmBarrier(Wal *pWal){ if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){ sqlite3OsShmBarrier(pWal->pDbFd); } } /* ** Write the header information in pWal->hdr into the wal-index. ** ** The checksum on pWal->hdr is updated before it is written. */ static void walIndexWriteHdr(Wal *pWal){ volatile WalIndexHdr *aHdr = walIndexHdr(pWal); const int nCksum = offsetof(WalIndexHdr, aCksum); assert( pWal->writeLock ); pWal->hdr.isInit = 1; pWal->hdr.iVersion = WALINDEX_MAX_VERSION; walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum); memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); walShmBarrier(pWal); memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); } /* ** This function encodes a single frame header and writes it to a buffer ** supplied by the caller. A frame-header is made up of a series of ** 4-byte big-endian integers, as follows: ** ** 0: Page number. ** 4: For commit records, the size of the database image in pages ** after the commit. For all other records, zero. ** 8: Salt-1 (copied from the wal-header) ** 12: Salt-2 (copied from the wal-header) ** 16: Checksum-1. ** 20: Checksum-2. */ static void walEncodeFrame( Wal *pWal, /* The write-ahead log */ u32 iPage, /* Database page number for frame */ u32 nTruncate, /* New db size (or 0 for non-commit frames) */ u8 *aData, /* Pointer to page data */ u8 *aFrame /* OUT: Write encoded frame here */ ){ int nativeCksum; /* True for native byte-order checksums */ u32 *aCksum = pWal->hdr.aFrameCksum; assert( WAL_FRAME_HDRSIZE==24 ); sqlite3Put4byte(&aFrame[0], iPage); sqlite3Put4byte(&aFrame[4], nTruncate); if( pWal->iReCksum==0 ){ memcpy(&aFrame[8], pWal->hdr.aSalt, 8); nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); sqlite3Put4byte(&aFrame[16], aCksum[0]); sqlite3Put4byte(&aFrame[20], aCksum[1]); }else{ memset(&aFrame[8], 0, 16); } } /* ** Check to see if the frame with header in aFrame[] and content ** in aData[] is valid. If it is a valid frame, fill *piPage and ** *pnTruncate and return true. Return if the frame is not valid. */ static int walDecodeFrame( Wal *pWal, /* The write-ahead log */ u32 *piPage, /* OUT: Database page number for frame */ u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */ u8 *aData, /* Pointer to page data (for checksum) */ u8 *aFrame /* Frame data */ ){ int nativeCksum; /* True for native byte-order checksums */ u32 *aCksum = pWal->hdr.aFrameCksum; u32 pgno; /* Page number of the frame */ assert( WAL_FRAME_HDRSIZE==24 ); /* A frame is only valid if the salt values in the frame-header ** match the salt values in the wal-header. */ if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){ return 0; } /* A frame is only valid if the page number is creater than zero. */ pgno = sqlite3Get4byte(&aFrame[0]); if( pgno==0 ){ return 0; } /* A frame is only valid if a checksum of the WAL header, ** all prior frams, the first 16 bytes of this frame-header, ** and the frame-data matches the checksum in the last 8 ** bytes of this frame-header. */ nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) ){ /* Checksum failed. */ return 0; } /* If we reach this point, the frame is valid. Return the page number ** and the new database size. */ *piPage = pgno; *pnTruncate = sqlite3Get4byte(&aFrame[4]); return 1; } #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) /* ** Names of locks. This routine is used to provide debugging output and is not ** a part of an ordinary build. */ static const char *walLockName(int lockIdx){ if( lockIdx==WAL_WRITE_LOCK ){ return "WRITE-LOCK"; }else if( lockIdx==WAL_CKPT_LOCK ){ return "CKPT-LOCK"; }else if( lockIdx==WAL_RECOVER_LOCK ){ return "RECOVER-LOCK"; }else{ static char zName[15]; sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]", lockIdx-WAL_READ_LOCK(0)); return zName; } } #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ /* ** Set or release locks on the WAL. Locks are either shared or exclusive. ** A lock cannot be moved directly between shared and exclusive - it must go ** through the unlocked state first. ** ** In locking_mode=EXCLUSIVE, all of these routines become no-ops. */ static int walLockShared(Wal *pWal, int lockIdx){ int rc; if( pWal->exclusiveMode ) return SQLITE_OK; rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, SQLITE_SHM_LOCK | SQLITE_SHM_SHARED); WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal, walLockName(lockIdx), rc ? "failed" : "ok")); VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); ) return rc; } static void walUnlockShared(Wal *pWal, int lockIdx){ if( pWal->exclusiveMode ) return; (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED); WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx))); } static int walLockExclusive(Wal *pWal, int lockIdx, int n){ int rc; if( pWal->exclusiveMode ) return SQLITE_OK; rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE); WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal, walLockName(lockIdx), n, rc ? "failed" : "ok")); VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); ) return rc; } static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){ if( pWal->exclusiveMode ) return; (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE); WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal, walLockName(lockIdx), n)); } /* ** Compute a hash on a page number. The resulting hash value must land ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances ** the hash to the next value in the event of a collision. */ static int walHash(u32 iPage){ assert( iPage>0 ); assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 ); return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1); } static int walNextHash(int iPriorHash){ return (iPriorHash+1)&(HASHTABLE_NSLOT-1); } /* ** Return pointers to the hash table and page number array stored on ** page iHash of the wal-index. The wal-index is broken into 32KB pages ** numbered starting from 0. ** ** Set output variable *paHash to point to the start of the hash table ** in the wal-index file. Set *piZero to one less than the frame ** number of the first frame indexed by this hash table. If a ** slot in the hash table is set to N, it refers to frame number ** (*piZero+N) in the log. ** ** Finally, set *paPgno so that *paPgno[1] is the page number of the ** first frame indexed by the hash table, frame (*piZero+1). */ static int walHashGet( Wal *pWal, /* WAL handle */ int iHash, /* Find the iHash'th table */ volatile ht_slot **paHash, /* OUT: Pointer to hash index */ volatile u32 **paPgno, /* OUT: Pointer to page number array */ u32 *piZero /* OUT: Frame associated with *paPgno[0] */ ){ int rc; /* Return code */ volatile u32 *aPgno; rc = walIndexPage(pWal, iHash, &aPgno); assert( rc==SQLITE_OK || iHash>0 ); if( rc==SQLITE_OK ){ u32 iZero; volatile ht_slot *aHash; aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE]; if( iHash==0 ){ aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)]; iZero = 0; }else{ iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE; } *paPgno = &aPgno[-1]; *paHash = aHash; *piZero = iZero; } return rc; } /* ** Return the number of the wal-index page that contains the hash-table ** and page-number array that contain entries corresponding to WAL frame ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages ** are numbered starting from 0. */ static int walFramePage(u32 iFrame){ int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE; assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE) && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE) && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)) && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE) && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE)) ); return iHash; } /* ** Return the page number associated with frame iFrame in this WAL. */ static u32 walFramePgno(Wal *pWal, u32 iFrame){ int iHash = walFramePage(iFrame); if( iHash==0 ){ return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1]; } return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE]; } /* ** Remove entries from the hash table that point to WAL slots greater ** than pWal->hdr.mxFrame. ** ** This function is called whenever pWal->hdr.mxFrame is decreased due ** to a rollback or savepoint. ** ** At most only the hash table containing pWal->hdr.mxFrame needs to be ** updated. Any later hash tables will be automatically cleared when ** pWal->hdr.mxFrame advances to the point where those hash tables are ** actually needed. */ static void walCleanupHash(Wal *pWal){ volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */ volatile u32 *aPgno = 0; /* Page number array for hash table */ u32 iZero = 0; /* frame == (aHash[x]+iZero) */ int iLimit = 0; /* Zero values greater than this */ int nByte; /* Number of bytes to zero in aPgno[] */ int i; /* Used to iterate through aHash[] */ assert( pWal->writeLock ); testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 ); testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE ); testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 ); if( pWal->hdr.mxFrame==0 ) return; /* Obtain pointers to the hash-table and page-number array containing ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed ** that the page said hash-table and array reside on is already mapped. */ assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) ); assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] ); walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero); /* Zero all hash-table entries that correspond to frame numbers greater ** than pWal->hdr.mxFrame. */ iLimit = pWal->hdr.mxFrame - iZero; assert( iLimit>0 ); for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i]>iLimit ){ aHash[i] = 0; } } /* Zero the entries in the aPgno array that correspond to frames with ** frame numbers greater than pWal->hdr.mxFrame. */ nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]); memset((void *)&aPgno[iLimit+1], 0, nByte); #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT /* Verify that the every entry in the mapping region is still reachable ** via the hash table even after the cleanup. */ if( iLimit ){ int j; /* Loop counter */ int iKey; /* Hash key */ for(j=1; j<=iLimit; j++){ for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){ if( aHash[iKey]==j ) break; } assert( aHash[iKey]==j ); } } #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ } /* ** Set an entry in the wal-index that will map database page number ** pPage into WAL frame iFrame. */ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ int rc; /* Return code */ u32 iZero = 0; /* One less than frame number of aPgno[1] */ volatile u32 *aPgno = 0; /* Page number array */ volatile ht_slot *aHash = 0; /* Hash table */ rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero); /* Assuming the wal-index file was successfully mapped, populate the ** page number array and hash table entry. */ if( rc==SQLITE_OK ){ int iKey; /* Hash table key */ int idx; /* Value to write to hash-table slot */ int nCollide; /* Number of hash collisions */ idx = iFrame - iZero; assert( idx <= HASHTABLE_NSLOT/2 + 1 ); /* If this is the first entry to be added to this hash-table, zero the ** entire hash table and aPgno[] array before proceeding. */ if( idx==1 ){ int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]); memset((void*)&aPgno[1], 0, nByte); } /* If the entry in aPgno[] is already set, then the previous writer ** must have exited unexpectedly in the middle of a transaction (after ** writing one or more dirty pages to the WAL to free up memory). ** Remove the remnants of that writers uncommitted transaction from ** the hash-table before writing any new entries. */ if( aPgno[idx] ){ walCleanupHash(pWal); assert( !aPgno[idx] ); } /* Write the aPgno[] array entry and the hash-table slot. */ nCollide = idx; for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){ if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT; } aPgno[idx] = iPage; aHash[iKey] = (ht_slot)idx; #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT /* Verify that the number of entries in the hash table exactly equals ** the number of entries in the mapping region. */ { int i; /* Loop counter */ int nEntry = 0; /* Number of entries in the hash table */ for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; } assert( nEntry==idx ); } /* Verify that the every entry in the mapping region is reachable ** via the hash table. This turns out to be a really, really expensive ** thing to check, so only do this occasionally - not on every ** iteration. */ if( (idx&0x3ff)==0 ){ int i; /* Loop counter */ for(i=1; i<=idx; i++){ for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){ if( aHash[iKey]==i ) break; } assert( aHash[iKey]==i ); } } #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ } return rc; } /* ** Recover the wal-index by reading the write-ahead log file. ** ** This routine first tries to establish an exclusive lock on the ** wal-index to prevent other threads/processes from doing anything ** with the WAL or wal-index while recovery is running. The ** WAL_RECOVER_LOCK is also held so that other threads will know ** that this thread is running recovery. If unable to establish ** the necessary locks, this routine returns SQLITE_BUSY. */ static int walIndexRecover(Wal *pWal){ int rc; /* Return Code */ i64 nSize; /* Size of log file */ u32 aFrameCksum[2] = {0, 0}; int iLock; /* Lock offset to lock for checkpoint */ int nLock; /* Number of locks to hold */ /* Obtain an exclusive lock on all byte in the locking range not already ** locked by the caller. The caller is guaranteed to have locked the ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte. ** If successful, the same bytes that are locked here are unlocked before ** this function returns. */ assert( pWal->ckptLock==1 || pWal->ckptLock==0 ); assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 ); assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE ); assert( pWal->writeLock ); iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock; nLock = SQLITE_SHM_NLOCK - iLock; rc = walLockExclusive(pWal, iLock, nLock); if( rc ){ return rc; } WALTRACE(("WAL%p: recovery begin...\n", pWal)); memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); rc = sqlite3OsFileSize(pWal->pWalFd, &nSize); if( rc!=SQLITE_OK ){ goto recovery_error; } if( nSize>WAL_HDRSIZE ){ u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */ u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ int szFrame; /* Number of bytes in buffer aFrame[] */ u8 *aData; /* Pointer to data part of aFrame buffer */ int iFrame; /* Index of last frame read */ i64 iOffset; /* Next offset to read from log file */ int szPage; /* Page size according to the log */ u32 magic; /* Magic value read from WAL header */ u32 version; /* Magic value read from WAL header */ int isValid; /* True if this frame is valid */ /* Read in the WAL header. */ rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); if( rc!=SQLITE_OK ){ goto recovery_error; } /* If the database page size is not a power of two, or is greater than ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid ** data. Similarly, if the 'magic' value is invalid, ignore the whole ** WAL file. */ magic = sqlite3Get4byte(&aBuf[0]); szPage = sqlite3Get4byte(&aBuf[8]); if( (magic&0xFFFFFFFE)!=WAL_MAGIC || szPage&(szPage-1) || szPage>SQLITE_MAX_PAGE_SIZE || szPage<512 ){ goto finished; } pWal->hdr.bigEndCksum = (u8)(magic&0x00000001); pWal->szPage = szPage; pWal->nCkpt = sqlite3Get4byte(&aBuf[12]); memcpy(&pWal->hdr.aSalt, &aBuf[16], 8); /* Verify that the WAL header checksum is correct */ walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum ); if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24]) || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28]) ){ goto finished; } /* Verify that the version number on the WAL format is one that ** are able to understand */ version = sqlite3Get4byte(&aBuf[4]); if( version!=WAL_MAX_VERSION ){ rc = SQLITE_CANTOPEN_BKPT; goto finished; } /* Malloc a buffer to read frames into. */ szFrame = szPage + WAL_FRAME_HDRSIZE; aFrame = (u8 *)sqlite3_malloc64(szFrame); if( !aFrame ){ rc = SQLITE_NOMEM_BKPT; goto recovery_error; } aData = &aFrame[WAL_FRAME_HDRSIZE]; /* Read all frames from the log file. */ iFrame = 0; for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){ u32 pgno; /* Database page number for frame */ u32 nTruncate; /* dbsize field from frame header */ /* Read and decode the next log frame. */ iFrame++; rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); if( rc!=SQLITE_OK ) break; isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame); if( !isValid ) break; rc = walIndexAppend(pWal, iFrame, pgno); if( rc!=SQLITE_OK ) break; /* If nTruncate is non-zero, this is a commit record. */ if( nTruncate ){ pWal->hdr.mxFrame = iFrame; pWal->hdr.nPage = nTruncate; pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); testcase( szPage<=32768 ); testcase( szPage>=65536 ); aFrameCksum[0] = pWal->hdr.aFrameCksum[0]; aFrameCksum[1] = pWal->hdr.aFrameCksum[1]; } } sqlite3_free(aFrame); } finished: if( rc==SQLITE_OK ){ volatile WalCkptInfo *pInfo; int i; pWal->hdr.aFrameCksum[0] = aFrameCksum[0]; pWal->hdr.aFrameCksum[1] = aFrameCksum[1]; walIndexWriteHdr(pWal); /* Reset the checkpoint-header. This is safe because this thread is ** currently holding locks that exclude all other readers, writers and ** checkpointers. */ pInfo = walCkptInfo(pWal); pInfo->nBackfill = 0; pInfo->nBackfillAttempted = pWal->hdr.mxFrame; pInfo->aReadMark[0] = 0; for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED; if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame; /* If more than one frame was recovered from the log file, report an ** event via sqlite3_log(). This is to help with identifying performance ** problems caused by applications routinely shutting down without ** checkpointing the log file. */ if( pWal->hdr.nPage ){ sqlite3_log(SQLITE_NOTICE_RECOVER_WAL, "recovered %d frames from WAL file %s", pWal->hdr.mxFrame, pWal->zWalName ); } } recovery_error: WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok")); walUnlockExclusive(pWal, iLock, nLock); return rc; } /* ** Close an open wal-index. */ static void walIndexClose(Wal *pWal, int isDelete){ if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ int i; for(i=0; i<pWal->nWiData; i++){ sqlite3_free((void *)pWal->apWiData[i]); pWal->apWiData[i] = 0; } }else{ sqlite3OsShmUnmap(pWal->pDbFd, isDelete); } } /* ** Open a connection to the WAL file zWalName. The database file must ** already be opened on connection pDbFd. The buffer that zWalName points ** to must remain valid for the lifetime of the returned Wal* handle. ** ** A SHARED lock should be held on the database file when this function ** is called. The purpose of this SHARED lock is to prevent any other ** client from unlinking the WAL or wal-index file. If another process ** were to do this just after this client opened one of these files, the ** system would be badly broken. ** ** If the log file is successfully opened, SQLITE_OK is returned and ** *ppWal is set to point to a new WAL handle. If an error occurs, ** an SQLite error code is returned and *ppWal is left unmodified. */ SQLITE_PRIVATE int sqlite3WalOpen( sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */ sqlite3_file *pDbFd, /* The open database file */ const char *zWalName, /* Name of the WAL file */ int bNoShm, /* True to run in heap-memory mode */ i64 mxWalSize, /* Truncate WAL to this size on reset */ Wal **ppWal /* OUT: Allocated Wal handle */ ){ int rc; /* Return Code */ Wal *pRet; /* Object to allocate and return */ int flags; /* Flags passed to OsOpen() */ assert( zWalName && zWalName[0] ); assert( pDbFd ); /* In the amalgamation, the os_unix.c and os_win.c source files come before ** this source file. Verify that the #defines of the locking byte offsets ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value. ** For that matter, if the lock offset ever changes from its initial design ** value of 120, we need to know that so there is an assert() to check it. */ assert( 120==WALINDEX_LOCK_OFFSET ); assert( 136==WALINDEX_HDR_SIZE ); #ifdef WIN_SHM_BASE assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET ); #endif #ifdef UNIX_SHM_BASE assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET ); #endif /* Allocate an instance of struct Wal to return. */ *ppWal = 0; pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile); if( !pRet ){ return SQLITE_NOMEM_BKPT; } pRet->pVfs = pVfs; pRet->pWalFd = (sqlite3_file *)&pRet[1]; pRet->pDbFd = pDbFd; pRet->readLock = -1; pRet->mxWalSize = mxWalSize; pRet->zWalName = zWalName; pRet->syncHeader = 1; pRet->padToSectorBoundary = 1; pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE); /* Open file handle on the write-ahead log file. */ flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL); rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags); if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){ pRet->readOnly = WAL_RDONLY; } if( rc!=SQLITE_OK ){ walIndexClose(pRet, 0); sqlite3OsClose(pRet->pWalFd); sqlite3_free(pRet); }else{ int iDC = sqlite3OsDeviceCharacteristics(pDbFd); if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; } if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){ pRet->padToSectorBoundary = 0; } *ppWal = pRet; WALTRACE(("WAL%d: opened\n", pRet)); } return rc; } /* ** Change the size to which the WAL file is trucated on each reset. */ SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){ if( pWal ) pWal->mxWalSize = iLimit; } /* ** Find the smallest page number out of all pages held in the WAL that ** has not been returned by any prior invocation of this method on the ** same WalIterator object. Write into *piFrame the frame index where ** that page was last written into the WAL. Write into *piPage the page ** number. ** ** Return 0 on success. If there are no pages in the WAL with a page ** number larger than *piPage, then return 1. */ static int walIteratorNext( WalIterator *p, /* Iterator */ u32 *piPage, /* OUT: The page number of the next page */ u32 *piFrame /* OUT: Wal frame index of next page */ ){ u32 iMin; /* Result pgno must be greater than iMin */ u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */ int i; /* For looping through segments */ iMin = p->iPrior; assert( iMin<0xffffffff ); for(i=p->nSegment-1; i>=0; i--){ struct WalSegment *pSegment = &p->aSegment[i]; while( pSegment->iNext<pSegment->nEntry ){ u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]]; if( iPg>iMin ){ if( iPg<iRet ){ iRet = iPg; *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext]; } break; } pSegment->iNext++; } } *piPage = p->iPrior = iRet; return (iRet==0xFFFFFFFF); } /* ** This function merges two sorted lists into a single sorted list. ** ** aLeft[] and aRight[] are arrays of indices. The sort key is ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following ** is guaranteed for all J<K: ** ** aContent[aLeft[J]] < aContent[aLeft[K]] ** aContent[aRight[J]] < aContent[aRight[K]] ** ** This routine overwrites aRight[] with a new (probably longer) sequence ** of indices such that the aRight[] contains every index that appears in ** either aLeft[] or the old aRight[] and such that the second condition ** above is still met. ** ** The aContent[aLeft[X]] values will be unique for all X. And the ** aContent[aRight[X]] values will be unique too. But there might be ** one or more combinations of X and Y such that ** ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]] ** ** When that happens, omit the aLeft[X] and use the aRight[Y] index. */ static void walMerge( const u32 *aContent, /* Pages in wal - keys for the sort */ ht_slot *aLeft, /* IN: Left hand input list */ int nLeft, /* IN: Elements in array *paLeft */ ht_slot **paRight, /* IN/OUT: Right hand input list */ int *pnRight, /* IN/OUT: Elements in *paRight */ ht_slot *aTmp /* Temporary buffer */ ){ int iLeft = 0; /* Current index in aLeft */ int iRight = 0; /* Current index in aRight */ int iOut = 0; /* Current index in output buffer */ int nRight = *pnRight; ht_slot *aRight = *paRight; assert( nLeft>0 && nRight>0 ); while( iRight<nRight || iLeft<nLeft ){ ht_slot logpage; Pgno dbpage; if( (iLeft<nLeft) && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]]) ){ logpage = aLeft[iLeft++]; }else{ logpage = aRight[iRight++]; } dbpage = aContent[logpage]; aTmp[iOut++] = logpage; if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++; assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage ); assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage ); } *paRight = aLeft; *pnRight = iOut; memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut); } /* ** Sort the elements in list aList using aContent[] as the sort key. ** Remove elements with duplicate keys, preferring to keep the ** larger aList[] values. ** ** The aList[] entries are indices into aContent[]. The values in ** aList[] are to be sorted so that for all J<K: ** ** aContent[aList[J]] < aContent[aList[K]] ** ** For any X and Y such that ** ** aContent[aList[X]] == aContent[aList[Y]] ** ** Keep the larger of the two values aList[X] and aList[Y] and discard ** the smaller. */ static void walMergesort( const u32 *aContent, /* Pages in wal */ ht_slot *aBuffer, /* Buffer of at least *pnList items to use */ ht_slot *aList, /* IN/OUT: List to sort */ int *pnList /* IN/OUT: Number of elements in aList[] */ ){ struct Sublist { int nList; /* Number of elements in aList */ ht_slot *aList; /* Pointer to sub-list content */ }; const int nList = *pnList; /* Size of input list */ int nMerge = 0; /* Number of elements in list aMerge */ ht_slot *aMerge = 0; /* List to be merged */ int iList; /* Index into input list */ u32 iSub = 0; /* Index into aSub array */ struct Sublist aSub[13]; /* Array of sub-lists */ memset(aSub, 0, sizeof(aSub)); assert( nList<=HASHTABLE_NPAGE && nList>0 ); assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) ); for(iList=0; iList<nList; iList++){ nMerge = 1; aMerge = &aList[iList]; for(iSub=0; iList & (1<<iSub); iSub++){ struct Sublist *p; assert( iSub<ArraySize(aSub) ); p = &aSub[iSub]; assert( p->aList && p->nList<=(1<<iSub) ); assert( p->aList==&aList[iList&~((2<<iSub)-1)] ); walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer); } aSub[iSub].aList = aMerge; aSub[iSub].nList = nMerge; } for(iSub++; iSub<ArraySize(aSub); iSub++){ if( nList & (1<<iSub) ){ struct Sublist *p; assert( iSub<ArraySize(aSub) ); p = &aSub[iSub]; assert( p->nList<=(1<<iSub) ); assert( p->aList==&aList[nList&~((2<<iSub)-1)] ); walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer); } } assert( aMerge==aList ); *pnList = nMerge; #ifdef SQLITE_DEBUG { int i; for(i=1; i<*pnList; i++){ assert( aContent[aList[i]] > aContent[aList[i-1]] ); } } #endif } /* ** Free an iterator allocated by walIteratorInit(). */ static void walIteratorFree(WalIterator *p){ sqlite3_free(p); } /* ** Construct a WalInterator object that can be used to loop over all ** pages in the WAL in ascending order. The caller must hold the checkpoint ** lock. ** ** On success, make *pp point to the newly allocated WalInterator object ** return SQLITE_OK. Otherwise, return an error code. If this routine ** returns an error, the value of *pp is undefined. ** ** The calling routine should invoke walIteratorFree() to destroy the ** WalIterator object when it has finished with it. */ static int walIteratorInit(Wal *pWal, WalIterator **pp){ WalIterator *p; /* Return value */ int nSegment; /* Number of segments to merge */ u32 iLast; /* Last frame in log */ int nByte; /* Number of bytes to allocate */ int i; /* Iterator variable */ ht_slot *aTmp; /* Temp space used by merge-sort */ int rc = SQLITE_OK; /* Return Code */ /* This routine only runs while holding the checkpoint lock. And ** it only runs if there is actually content in the log (mxFrame>0). */ assert( pWal->ckptLock && pWal->hdr.mxFrame>0 ); iLast = pWal->hdr.mxFrame; /* Allocate space for the WalIterator object. */ nSegment = walFramePage(iLast) + 1; nByte = sizeof(WalIterator) + (nSegment-1)*sizeof(struct WalSegment) + iLast*sizeof(ht_slot); p = (WalIterator *)sqlite3_malloc64(nByte); if( !p ){ return SQLITE_NOMEM_BKPT; } memset(p, 0, nByte); p->nSegment = nSegment; /* Allocate temporary space used by the merge-sort routine. This block ** of memory will be freed before this function returns. */ aTmp = (ht_slot *)sqlite3_malloc64( sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast) ); if( !aTmp ){ rc = SQLITE_NOMEM_BKPT; } for(i=0; rc==SQLITE_OK && i<nSegment; i++){ volatile ht_slot *aHash; u32 iZero; volatile u32 *aPgno; rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero); if( rc==SQLITE_OK ){ int j; /* Counter variable */ int nEntry; /* Number of entries in this segment */ ht_slot *aIndex; /* Sorted index for this segment */ aPgno++; if( (i+1)==nSegment ){ nEntry = (int)(iLast - iZero); }else{ nEntry = (int)((u32*)aHash - (u32*)aPgno); } aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero]; iZero++; for(j=0; j<nEntry; j++){ aIndex[j] = (ht_slot)j; } walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry); p->aSegment[i].iZero = iZero; p->aSegment[i].nEntry = nEntry; p->aSegment[i].aIndex = aIndex; p->aSegment[i].aPgno = (u32 *)aPgno; } } sqlite3_free(aTmp); if( rc!=SQLITE_OK ){ walIteratorFree(p); } *pp = p; return rc; } /* ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and ** n. If the attempt fails and parameter xBusy is not NULL, then it is a ** busy-handler function. Invoke it and retry the lock until either the ** lock is successfully obtained or the busy-handler returns 0. */ static int walBusyLock( Wal *pWal, /* WAL connection */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ int lockIdx, /* Offset of first byte to lock */ int n /* Number of bytes to lock */ ){ int rc; do { rc = walLockExclusive(pWal, lockIdx, n); }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) ); return rc; } /* ** The cache of the wal-index header must be valid to call this function. ** Return the page-size in bytes used by the database. */ static int walPagesize(Wal *pWal){ return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); } /* ** The following is guaranteed when this function is called: ** ** a) the WRITER lock is held, ** b) the entire log file has been checkpointed, and ** c) any existing readers are reading exclusively from the database ** file - there are no readers that may attempt to read a frame from ** the log file. ** ** This function updates the shared-memory structures so that the next ** client to write to the database (which may be this one) does so by ** writing frames into the start of the log file. ** ** The value of parameter salt1 is used as the aSalt[1] value in the ** new wal-index header. It should be passed a pseudo-random value (i.e. ** one obtained from sqlite3_randomness()). */ static void walRestartHdr(Wal *pWal, u32 salt1){ volatile WalCkptInfo *pInfo = walCkptInfo(pWal); int i; /* Loop counter */ u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */ pWal->nCkpt++; pWal->hdr.mxFrame = 0; sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0])); memcpy(&pWal->hdr.aSalt[1], &salt1, 4); walIndexWriteHdr(pWal); pInfo->nBackfill = 0; pInfo->nBackfillAttempted = 0; pInfo->aReadMark[1] = 0; for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED; assert( pInfo->aReadMark[0]==0 ); } /* ** Copy as much content as we can from the WAL back into the database file ** in response to an sqlite3_wal_checkpoint() request or the equivalent. ** ** The amount of information copies from WAL to database might be limited ** by active readers. This routine will never overwrite a database page ** that a concurrent reader might be using. ** ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if ** checkpoints are always run by a background thread or background ** process, foreground threads will never block on a lengthy fsync call. ** ** Fsync is called on the WAL before writing content out of the WAL and ** into the database. This ensures that if the new content is persistent ** in the WAL and can be recovered following a power-loss or hard reset. ** ** Fsync is also called on the database file if (and only if) the entire ** WAL content is copied into the database file. This second fsync makes ** it safe to delete the WAL since the new content will persist in the ** database file. ** ** This routine uses and updates the nBackfill field of the wal-index header. ** This is the only routine that will increase the value of nBackfill. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase ** its value.) ** ** The caller must be holding sufficient locks to ensure that no other ** checkpoint is running (in any other thread or process) at the same ** time. */ static int walCheckpoint( Wal *pWal, /* Wal connection */ sqlite3 *db, /* Check for interrupts on this handle */ int eMode, /* One of PASSIVE, FULL or RESTART */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ int sync_flags, /* Flags for OsSync() (or 0) */ u8 *zBuf /* Temporary buffer to use */ ){ int rc = SQLITE_OK; /* Return code */ int szPage; /* Database page-size */ WalIterator *pIter = 0; /* Wal iterator context */ u32 iDbpage = 0; /* Next database page to write */ u32 iFrame = 0; /* Wal frame containing data for iDbpage */ u32 mxSafeFrame; /* Max frame that can be backfilled */ u32 mxPage; /* Max database page to write */ int i; /* Loop counter */ volatile WalCkptInfo *pInfo; /* The checkpoint status information */ szPage = walPagesize(pWal); testcase( szPage<=32768 ); testcase( szPage>=65536 ); pInfo = walCkptInfo(pWal); if( pInfo->nBackfill<pWal->hdr.mxFrame ){ /* Allocate the iterator */ rc = walIteratorInit(pWal, &pIter); if( rc!=SQLITE_OK ){ return rc; } assert( pIter ); /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); /* Compute in mxSafeFrame the index of the last frame of the WAL that is ** safe to write into the database. Frames beyond mxSafeFrame might ** overwrite database pages that are in use by active readers and thus ** cannot be backfilled from the WAL. */ mxSafeFrame = pWal->hdr.mxFrame; mxPage = pWal->hdr.nPage; for(i=1; i<WAL_NREADER; i++){ /* Thread-sanitizer reports that the following is an unsafe read, ** as some other thread may be in the process of updating the value ** of the aReadMark[] slot. The assumption here is that if that is ** happening, the other client may only be increasing the value, ** not decreasing it. So assuming either that either the "old" or ** "new" version of the value is read, and not some arbitrary value ** that would never be written by a real client, things are still ** safe. */ u32 y = pInfo->aReadMark[i]; if( mxSafeFrame>y ){ assert( y<=pWal->hdr.mxFrame ); rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1); if( rc==SQLITE_OK ){ pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED); walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); }else if( rc==SQLITE_BUSY ){ mxSafeFrame = y; xBusy = 0; }else{ goto walcheckpoint_out; } } } if( pInfo->nBackfill<mxSafeFrame && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK ){ i64 nSize; /* Current size of database file */ u32 nBackfill = pInfo->nBackfill; pInfo->nBackfillAttempted = mxSafeFrame; /* Sync the WAL to disk */ if( sync_flags ){ rc = sqlite3OsSync(pWal->pWalFd, sync_flags); } /* If the database may grow as a result of this checkpoint, hint ** about the eventual size of the db file to the VFS layer. */ if( rc==SQLITE_OK ){ i64 nReq = ((i64)mxPage * szPage); rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); if( rc==SQLITE_OK && nSize<nReq ){ sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq); } } /* Iterate through the contents of the WAL, copying data to the db file */ while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ i64 iOffset; assert( walFramePgno(pWal, iFrame)==iDbpage ); if( db->u1.isInterrupted ){ rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; break; } if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){ continue; } iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE; /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); if( rc!=SQLITE_OK ) break; iOffset = (iDbpage-1)*(i64)szPage; testcase( IS_BIG_INT(iOffset) ); rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); if( rc!=SQLITE_OK ) break; } /* If work was actually accomplished... */ if( rc==SQLITE_OK ){ if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ i64 szDb = pWal->hdr.nPage*(i64)szPage; testcase( IS_BIG_INT(szDb) ); rc = sqlite3OsTruncate(pWal->pDbFd, szDb); if( rc==SQLITE_OK && sync_flags ){ rc = sqlite3OsSync(pWal->pDbFd, sync_flags); } } if( rc==SQLITE_OK ){ pInfo->nBackfill = mxSafeFrame; } } /* Release the reader lock held while backfilling */ walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1); } if( rc==SQLITE_BUSY ){ /* Reset the return code so as not to report a checkpoint failure ** just because there are active readers. */ rc = SQLITE_OK; } } /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the ** entire wal file has been copied into the database file, then block ** until all readers have finished using the wal file. This ensures that ** the next process to write to the database restarts the wal file. */ if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){ assert( pWal->writeLock ); if( pInfo->nBackfill<pWal->hdr.mxFrame ){ rc = SQLITE_BUSY; }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){ u32 salt1; sqlite3_randomness(4, &salt1); assert( pInfo->nBackfill==pWal->hdr.mxFrame ); rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1); if( rc==SQLITE_OK ){ if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){ /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as ** SQLITE_CHECKPOINT_RESTART with the addition that it also ** truncates the log file to zero bytes just prior to a ** successful return. ** ** In theory, it might be safe to do this without updating the ** wal-index header in shared memory, as all subsequent reader or ** writer clients should see that the entire log file has been ** checkpointed and behave accordingly. This seems unsafe though, ** as it would leave the system in a state where the contents of ** the wal-index header do not match the contents of the ** file-system. To avoid this, update the wal-index header to ** indicate that the log file contains zero valid frames. */ walRestartHdr(pWal, salt1); rc = sqlite3OsTruncate(pWal->pWalFd, 0); } walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); } } } walcheckpoint_out: walIteratorFree(pIter); return rc; } /* ** If the WAL file is currently larger than nMax bytes in size, truncate ** it to exactly nMax bytes. If an error occurs while doing so, ignore it. */ static void walLimitSize(Wal *pWal, i64 nMax){ i64 sz; int rx; sqlite3BeginBenignMalloc(); rx = sqlite3OsFileSize(pWal->pWalFd, &sz); if( rx==SQLITE_OK && (sz > nMax ) ){ rx = sqlite3OsTruncate(pWal->pWalFd, nMax); } sqlite3EndBenignMalloc(); if( rx ){ sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName); } } /* ** Close a connection to a log file. */ SQLITE_PRIVATE int sqlite3WalClose( Wal *pWal, /* Wal to close */ sqlite3 *db, /* For interrupt flag */ int sync_flags, /* Flags to pass to OsSync() (or 0) */ int nBuf, u8 *zBuf /* Buffer of at least nBuf bytes */ ){ int rc = SQLITE_OK; if( pWal ){ int isDelete = 0; /* True to unlink wal and wal-index files */ /* If an EXCLUSIVE lock can be obtained on the database file (using the ** ordinary, rollback-mode locking methods, this guarantees that the ** connection associated with this log file is the only connection to ** the database. In this case checkpoint the database and unlink both ** the wal and wal-index files. ** ** The EXCLUSIVE lock is not released before returning. */ if( zBuf!=0 && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE)) ){ if( pWal->exclusiveMode==WAL_NORMAL_MODE ){ pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; } rc = sqlite3WalCheckpoint(pWal, db, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0 ); if( rc==SQLITE_OK ){ int bPersist = -1; sqlite3OsFileControlHint( pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist ); if( bPersist!=1 ){ /* Try to delete the WAL file if the checkpoint completed and ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal ** mode (!bPersist) */ isDelete = 1; }else if( pWal->mxWalSize>=0 ){ /* Try to truncate the WAL file to zero bytes if the checkpoint ** completed and fsynced (rc==SQLITE_OK) and we are in persistent ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a ** non-negative value (pWal->mxWalSize>=0). Note that we truncate ** to zero bytes as truncating to the journal_size_limit might ** leave a corrupt WAL file on disk. */ walLimitSize(pWal, 0); } } } walIndexClose(pWal, isDelete); sqlite3OsClose(pWal->pWalFd); if( isDelete ){ sqlite3BeginBenignMalloc(); sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0); sqlite3EndBenignMalloc(); } WALTRACE(("WAL%p: closed\n", pWal)); sqlite3_free((void *)pWal->apWiData); sqlite3_free(pWal); } return rc; } /* ** Try to read the wal-index header. Return 0 on success and 1 if ** there is a problem. ** ** The wal-index is in shared memory. Another thread or process might ** be writing the header at the same time this procedure is trying to ** read it, which might result in inconsistency. A dirty read is detected ** by verifying that both copies of the header are the same and also by ** a checksum on the header. ** ** If and only if the read is consistent and the header is different from ** pWal->hdr, then pWal->hdr is updated to the content of the new header ** and *pChanged is set to 1. ** ** If the checksum cannot be verified return non-zero. If the header ** is read successfully and the checksum verified, return zero. */ static int walIndexTryHdr(Wal *pWal, int *pChanged){ u32 aCksum[2]; /* Checksum on the header content */ WalIndexHdr h1, h2; /* Two copies of the header content */ WalIndexHdr volatile *aHdr; /* Header in shared memory */ /* The first page of the wal-index must be mapped at this point. */ assert( pWal->nWiData>0 && pWal->apWiData[0] ); /* Read the header. This might happen concurrently with a write to the ** same area of shared memory on a different CPU in a SMP, ** meaning it is possible that an inconsistent snapshot is read ** from the file. If this happens, return non-zero. ** ** There are two copies of the header at the beginning of the wal-index. ** When reading, read [0] first then [1]. Writes are in the reverse order. ** Memory barriers are used to prevent the compiler or the hardware from ** reordering the reads and writes. */ aHdr = walIndexHdr(pWal); memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); walShmBarrier(pWal); memcpy(&h2, (void *)&aHdr[1], sizeof(h2)); if( memcmp(&h1, &h2, sizeof(h1))!=0 ){ return 1; /* Dirty read */ } if( h1.isInit==0 ){ return 1; /* Malformed header - probably all zeros */ } walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum); if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){ return 1; /* Checksum does not match */ } if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){ *pChanged = 1; memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr)); pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); testcase( pWal->szPage<=32768 ); testcase( pWal->szPage>=65536 ); } /* The header was successfully read. Return zero. */ return 0; } /* ** Read the wal-index header from the wal-index and into pWal->hdr. ** If the wal-header appears to be corrupt, try to reconstruct the ** wal-index from the WAL before returning. ** ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is ** changed by this operation. If pWal->hdr is unchanged, set *pChanged ** to 0. ** ** If the wal-index header is successfully read, return SQLITE_OK. ** Otherwise an SQLite error code. */ static int walIndexReadHdr(Wal *pWal, int *pChanged){ int rc; /* Return code */ int badHdr; /* True if a header read failed */ volatile u32 *page0; /* Chunk of wal-index containing header */ /* Ensure that page 0 of the wal-index (the page that contains the ** wal-index header) is mapped. Return early if an error occurs here. */ assert( pChanged ); rc = walIndexPage(pWal, 0, &page0); if( rc!=SQLITE_OK ){ return rc; }; assert( page0 || pWal->writeLock==0 ); /* If the first page of the wal-index has been mapped, try to read the ** wal-index header immediately, without holding any lock. This usually ** works, but may fail if the wal-index header is corrupt or currently ** being modified by another thread or process. */ badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1); /* If the first attempt failed, it might have been due to a race ** with a writer. So get a WRITE lock and try again. */ assert( badHdr==0 || pWal->writeLock==0 ); if( badHdr ){ if( pWal->readOnly & WAL_SHM_RDONLY ){ if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){ walUnlockShared(pWal, WAL_WRITE_LOCK); rc = SQLITE_READONLY_RECOVERY; } }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){ pWal->writeLock = 1; if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){ badHdr = walIndexTryHdr(pWal, pChanged); if( badHdr ){ /* If the wal-index header is still malformed even while holding ** a WRITE lock, it can only mean that the header is corrupted and ** needs to be reconstructed. So run recovery to do exactly that. */ rc = walIndexRecover(pWal); *pChanged = 1; } } pWal->writeLock = 0; walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); } } /* If the header is read successfully, check the version number to make ** sure the wal-index was not constructed with some future format that ** this version of SQLite cannot understand. */ if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){ rc = SQLITE_CANTOPEN_BKPT; } return rc; } /* ** This is the value that walTryBeginRead returns when it needs to ** be retried. */ #define WAL_RETRY (-1) /* ** Attempt to start a read transaction. This might fail due to a race or ** other transient condition. When that happens, it returns WAL_RETRY to ** indicate to the caller that it is safe to retry immediately. ** ** On success return SQLITE_OK. On a permanent failure (such an ** I/O error or an SQLITE_BUSY because another process is running ** recovery) return a positive error code. ** ** The useWal parameter is true to force the use of the WAL and disable ** the case where the WAL is bypassed because it has been completely ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr() ** to make a copy of the wal-index header into pWal->hdr. If the ** wal-index header has changed, *pChanged is set to 1 (as an indication ** to the caller that the local paget cache is obsolete and needs to be ** flushed.) When useWal==1, the wal-index header is assumed to already ** be loaded and the pChanged parameter is unused. ** ** The caller must set the cnt parameter to the number of prior calls to ** this routine during the current read attempt that returned WAL_RETRY. ** This routine will start taking more aggressive measures to clear the ** race conditions after multiple WAL_RETRY returns, and after an excessive ** number of errors will ultimately return SQLITE_PROTOCOL. The ** SQLITE_PROTOCOL return indicates that some other process has gone rogue ** and is not honoring the locking protocol. There is a vanishingly small ** chance that SQLITE_PROTOCOL could be returned because of a run of really ** bad luck when there is lots of contention for the wal-index, but that ** possibility is so small that it can be safely neglected, we believe. ** ** On success, this routine obtains a read lock on ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1) ** that means the Wal does not hold any read lock. The reader must not ** access any database page that is modified by a WAL frame up to and ** including frame number aReadMark[pWal->readLock]. The reader will ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0 ** Or if pWal->readLock==0, then the reader will ignore the WAL ** completely and get all content directly from the database file. ** If the useWal parameter is 1 then the WAL will never be ignored and ** this routine will always set pWal->readLock>0 on success. ** When the read transaction is completed, the caller must release the ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1. ** ** This routine uses the nBackfill and aReadMark[] fields of the header ** to select a particular WAL_READ_LOCK() that strives to let the ** checkpoint process do as much work as possible. This routine might ** update values of the aReadMark[] array in the header, but if it does ** so it takes care to hold an exclusive lock on the corresponding ** WAL_READ_LOCK() while changing values. */ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */ u32 mxReadMark; /* Largest aReadMark[] value */ int mxI; /* Index of largest aReadMark[] value */ int i; /* Loop counter */ int rc = SQLITE_OK; /* Return code */ u32 mxFrame; /* Wal frame to lock to */ assert( pWal->readLock<0 ); /* Not currently locked */ /* Take steps to avoid spinning forever if there is a protocol error. ** ** Circumstances that cause a RETRY should only last for the briefest ** instances of time. No I/O or other system calls are done while the ** locks are held, so the locks should not be held for very long. But ** if we are unlucky, another process that is holding a lock might get ** paged out or take a page-fault that is time-consuming to resolve, ** during the few nanoseconds that it is holding the lock. In that case, ** it might take longer than normal for the lock to free. ** ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this ** is more of a scheduler yield than an actual delay. But on the 10th ** an subsequent retries, the delays start becoming longer and longer, ** so that on the 100th (and last) RETRY we delay for 323 milliseconds. ** The total delay time before giving up is less than 10 seconds. */ if( cnt>5 ){ int nDelay = 1; /* Pause time in microseconds */ if( cnt>100 ){ VVA_ONLY( pWal->lockError = 1; ) return SQLITE_PROTOCOL; } if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39; sqlite3OsSleep(pWal->pVfs, nDelay); } if( !useWal ){ rc = walIndexReadHdr(pWal, pChanged); if( rc==SQLITE_BUSY ){ /* If there is not a recovery running in another thread or process ** then convert BUSY errors to WAL_RETRY. If recovery is known to ** be running, convert BUSY to BUSY_RECOVERY. There is a race here ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY ** would be technically correct. But the race is benign since with ** WAL_RETRY this routine will be called again and will probably be ** right on the second iteration. */ if( pWal->apWiData[0]==0 ){ /* This branch is taken when the xShmMap() method returns SQLITE_BUSY. ** We assume this is a transient condition, so return WAL_RETRY. The ** xShmMap() implementation used by the default unix and win32 VFS ** modules may return SQLITE_BUSY due to a race condition in the ** code that determines whether or not the shared-memory region ** must be zeroed before the requested page is returned. */ rc = WAL_RETRY; }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){ walUnlockShared(pWal, WAL_RECOVER_LOCK); rc = WAL_RETRY; }else if( rc==SQLITE_BUSY ){ rc = SQLITE_BUSY_RECOVERY; } } if( rc!=SQLITE_OK ){ return rc; } } pInfo = walCkptInfo(pWal); if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame #ifdef SQLITE_ENABLE_SNAPSHOT && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0 || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr))) #endif ){ /* The WAL has been completely backfilled (or it is empty). ** and can be safely ignored. */ rc = walLockShared(pWal, WAL_READ_LOCK(0)); walShmBarrier(pWal); if( rc==SQLITE_OK ){ if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ /* It is not safe to allow the reader to continue here if frames ** may have been appended to the log before READ_LOCK(0) was obtained. ** When holding READ_LOCK(0), the reader ignores the entire log file, ** which implies that the database file contains a trustworthy ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from ** happening, this is usually correct. ** ** However, if frames have been appended to the log (or if the log ** is wrapped and written for that matter) before the READ_LOCK(0) ** is obtained, that is not necessarily true. A checkpointer may ** have started to backfill the appended frames but crashed before ** it finished. Leaving a corrupt image in the database file. */ walUnlockShared(pWal, WAL_READ_LOCK(0)); return WAL_RETRY; } pWal->readLock = 0; return SQLITE_OK; }else if( rc!=SQLITE_BUSY ){ return rc; } } /* If we get this far, it means that the reader will want to use ** the WAL to get at content from recent commits. The job now is ** to select one of the aReadMark[] entries that is closest to ** but not exceeding pWal->hdr.mxFrame and lock that entry. */ mxReadMark = 0; mxI = 0; mxFrame = pWal->hdr.mxFrame; #ifdef SQLITE_ENABLE_SNAPSHOT if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){ mxFrame = pWal->pSnapshot->mxFrame; } #endif for(i=1; i<WAL_NREADER; i++){ u32 thisMark = pInfo->aReadMark[i]; if( mxReadMark<=thisMark && thisMark<=mxFrame ){ assert( thisMark!=READMARK_NOT_USED ); mxReadMark = thisMark; mxI = i; } } if( (pWal->readOnly & WAL_SHM_RDONLY)==0 && (mxReadMark<mxFrame || mxI==0) ){ for(i=1; i<WAL_NREADER; i++){ rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1); if( rc==SQLITE_OK ){ mxReadMark = pInfo->aReadMark[i] = mxFrame; mxI = i; walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); break; }else if( rc!=SQLITE_BUSY ){ return rc; } } } if( mxI==0 ){ assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 ); return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK; } rc = walLockShared(pWal, WAL_READ_LOCK(mxI)); if( rc ){ return rc==SQLITE_BUSY ? WAL_RETRY : rc; } /* Now that the read-lock has been obtained, check that neither the ** value in the aReadMark[] array or the contents of the wal-index ** header have changed. ** ** It is necessary to check that the wal-index header did not change ** between the time it was read and when the shared-lock was obtained ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility ** that the log file may have been wrapped by a writer, or that frames ** that occur later in the log than pWal->hdr.mxFrame may have been ** copied into the database by a checkpointer. If either of these things ** happened, then reading the database with the current value of ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry ** instead. ** ** Before checking that the live wal-index header has not changed ** since it was read, set Wal.minFrame to the first frame in the wal ** file that has not yet been checkpointed. This client will not need ** to read any frames earlier than minFrame from the wal file - they ** can be safely read directly from the database file. ** ** Because a ShmBarrier() call is made between taking the copy of ** nBackfill and checking that the wal-header in shared-memory still ** matches the one cached in pWal->hdr, it is guaranteed that the ** checkpointer that set nBackfill was not working with a wal-index ** header newer than that cached in pWal->hdr. If it were, that could ** cause a problem. The checkpointer could omit to checkpoint ** a version of page X that lies before pWal->minFrame (call that version ** A) on the basis that there is a newer version (version B) of the same ** page later in the wal file. But if version B happens to like past ** frame pWal->hdr.mxFrame - then the client would incorrectly assume ** that it can read version A from the database file. However, since ** we can guarantee that the checkpointer that set nBackfill could not ** see any pages past pWal->hdr.mxFrame, this problem does not come up. */ pWal->minFrame = pInfo->nBackfill+1; walShmBarrier(pWal); if( pInfo->aReadMark[mxI]!=mxReadMark || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ walUnlockShared(pWal, WAL_READ_LOCK(mxI)); return WAL_RETRY; }else{ assert( mxReadMark<=pWal->hdr.mxFrame ); pWal->readLock = (i16)mxI; } return rc; } #ifdef SQLITE_ENABLE_SNAPSHOT /* ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted ** variable so that older snapshots can be accessed. To do this, loop ** through all wal frames from nBackfillAttempted to (nBackfill+1), ** comparing their content to the corresponding page with the database ** file, if any. Set nBackfillAttempted to the frame number of the ** first frame for which the wal file content matches the db file. ** ** This is only really safe if the file-system is such that any page ** writes made by earlier checkpointers were atomic operations, which ** is not always true. It is also possible that nBackfillAttempted ** may be left set to a value larger than expected, if a wal frame ** contains content that duplicate of an earlier version of the same ** page. ** ** SQLITE_OK is returned if successful, or an SQLite error code if an ** error occurs. It is not an error if nBackfillAttempted cannot be ** decreased at all. */ SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){ int rc; assert( pWal->readLock>=0 ); rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); if( rc==SQLITE_OK ){ volatile WalCkptInfo *pInfo = walCkptInfo(pWal); int szPage = (int)pWal->szPage; i64 szDb; /* Size of db file in bytes */ rc = sqlite3OsFileSize(pWal->pDbFd, &szDb); if( rc==SQLITE_OK ){ void *pBuf1 = sqlite3_malloc(szPage); void *pBuf2 = sqlite3_malloc(szPage); if( pBuf1==0 || pBuf2==0 ){ rc = SQLITE_NOMEM; }else{ u32 i = pInfo->nBackfillAttempted; for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){ volatile ht_slot *dummy; volatile u32 *aPgno; /* Array of page numbers */ u32 iZero; /* Frame corresponding to aPgno[0] */ u32 pgno; /* Page number in db file */ i64 iDbOff; /* Offset of db file entry */ i64 iWalOff; /* Offset of wal file entry */ rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero); if( rc!=SQLITE_OK ) break; pgno = aPgno[i-iZero]; iDbOff = (i64)(pgno-1) * szPage; if( iDbOff+szPage<=szDb ){ iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE; rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff); if( rc==SQLITE_OK ){ rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff); } if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){ break; } } pInfo->nBackfillAttempted = i-1; } } sqlite3_free(pBuf1); sqlite3_free(pBuf2); } walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); } return rc; } #endif /* SQLITE_ENABLE_SNAPSHOT */ /* ** Begin a read transaction on the database. ** ** This routine used to be called sqlite3OpenSnapshot() and with good reason: ** it takes a snapshot of the state of the WAL and wal-index for the current ** instant in time. The current thread will continue to use this snapshot. ** Other threads might append new content to the WAL and wal-index but ** that extra content is ignored by the current thread. ** ** If the database contents have changes since the previous read ** transaction, then *pChanged is set to 1 before returning. The ** Pager layer will use this to know that is cache is stale and ** needs to be flushed. */ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ int rc; /* Return code */ int cnt = 0; /* Number of TryBeginRead attempts */ #ifdef SQLITE_ENABLE_SNAPSHOT int bChanged = 0; WalIndexHdr *pSnapshot = pWal->pSnapshot; if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ bChanged = 1; } #endif do{ rc = walTryBeginRead(pWal, pChanged, 0, ++cnt); }while( rc==WAL_RETRY ); testcase( (rc&0xff)==SQLITE_BUSY ); testcase( (rc&0xff)==SQLITE_IOERR ); testcase( rc==SQLITE_PROTOCOL ); testcase( rc==SQLITE_OK ); #ifdef SQLITE_ENABLE_SNAPSHOT if( rc==SQLITE_OK ){ if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ /* At this point the client has a lock on an aReadMark[] slot holding ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr ** is populated with the wal-index header corresponding to the head ** of the wal file. Verify that pSnapshot is still valid before ** continuing. Reasons why pSnapshot might no longer be valid: ** ** (1) The WAL file has been reset since the snapshot was taken. ** In this case, the salt will have changed. ** ** (2) A checkpoint as been attempted that wrote frames past ** pSnapshot->mxFrame into the database file. Note that the ** checkpoint need not have completed for this to cause problems. */ volatile WalCkptInfo *pInfo = walCkptInfo(pWal); assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 ); assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame ); /* It is possible that there is a checkpointer thread running ** concurrent with this code. If this is the case, it may be that the ** checkpointer has already determined that it will checkpoint ** snapshot X, where X is later in the wal file than pSnapshot, but ** has not yet set the pInfo->nBackfillAttempted variable to indicate ** its intent. To avoid the race condition this leads to, ensure that ** there is no checkpointer process by taking a shared CKPT lock ** before checking pInfo->nBackfillAttempted. ** ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing ** this already? */ rc = walLockShared(pWal, WAL_CKPT_LOCK); if( rc==SQLITE_OK ){ /* Check that the wal file has not been wrapped. Assuming that it has ** not, also check that no checkpointer has attempted to checkpoint any ** frames beyond pSnapshot->mxFrame. If either of these conditions are ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr ** with *pSnapshot and set *pChanged as appropriate for opening the ** snapshot. */ if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)) && pSnapshot->mxFrame>=pInfo->nBackfillAttempted ){ assert( pWal->readLock>0 ); memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr)); *pChanged = bChanged; }else{ rc = SQLITE_BUSY_SNAPSHOT; } /* Release the shared CKPT lock obtained above. */ walUnlockShared(pWal, WAL_CKPT_LOCK); } if( rc!=SQLITE_OK ){ sqlite3WalEndReadTransaction(pWal); } } } #endif return rc; } /* ** Finish with a read transaction. All this does is release the ** read-lock. */ SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){ sqlite3WalEndWriteTransaction(pWal); if( pWal->readLock>=0 ){ walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); pWal->readLock = -1; } } /* ** Search the wal file for page pgno. If found, set *piRead to the frame that ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead ** to zero. ** ** Return SQLITE_OK if successful, or an error code if an error occurs. If an ** error does occur, the final value of *piRead is undefined. */ SQLITE_PRIVATE int sqlite3WalFindFrame( Wal *pWal, /* WAL handle */ Pgno pgno, /* Database page number to read data for */ u32 *piRead /* OUT: Frame number (or zero) */ ){ u32 iRead = 0; /* If !=0, WAL frame to return data from */ u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */ int iHash; /* Used to loop through N hash tables */ int iMinHash; /* This routine is only be called from within a read transaction. */ assert( pWal->readLock>=0 || pWal->lockError ); /* If the "last page" field of the wal-index header snapshot is 0, then ** no data will be read from the wal under any circumstances. Return early ** in this case as an optimization. Likewise, if pWal->readLock==0, ** then the WAL is ignored by the reader so return early, as if the ** WAL were empty. */ if( iLast==0 || pWal->readLock==0 ){ *piRead = 0; return SQLITE_OK; } /* Search the hash table or tables for an entry matching page number ** pgno. Each iteration of the following for() loop searches one ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames). ** ** This code might run concurrently to the code in walIndexAppend() ** that adds entries to the wal-index (and possibly to this hash ** table). This means the value just read from the hash ** slot (aHash[iKey]) may have been added before or after the ** current read transaction was opened. Values added after the ** read transaction was opened may have been written incorrectly - ** i.e. these slots may contain garbage data. However, we assume ** that any slots written before the current read transaction was ** opened remain unmodified. ** ** For the reasons above, the if(...) condition featured in the inner ** loop of the following block is more stringent that would be required ** if we had exclusive access to the hash-table: ** ** (aPgno[iFrame]==pgno): ** This condition filters out normal hash-table collisions. ** ** (iFrame<=iLast): ** This condition filters out entries that were added to the hash ** table after the current read-transaction had started. */ iMinHash = walFramePage(pWal->minFrame); for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){ volatile ht_slot *aHash; /* Pointer to hash table */ volatile u32 *aPgno; /* Pointer to array of page numbers */ u32 iZero; /* Frame number corresponding to aPgno[0] */ int iKey; /* Hash slot index */ int nCollide; /* Number of hash collisions remaining */ int rc; /* Error code */ rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero); if( rc!=SQLITE_OK ){ return rc; } nCollide = HASHTABLE_NSLOT; for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){ u32 iFrame = aHash[iKey] + iZero; if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){ assert( iFrame>iRead || CORRUPT_DB ); iRead = iFrame; } if( (nCollide--)==0 ){ return SQLITE_CORRUPT_BKPT; } } } #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT /* If expensive assert() statements are available, do a linear search ** of the wal-index file content. Make sure the results agree with the ** result obtained using the hash indexes above. */ { u32 iRead2 = 0; u32 iTest; assert( pWal->minFrame>0 ); for(iTest=iLast; iTest>=pWal->minFrame; iTest--){ if( walFramePgno(pWal, iTest)==pgno ){ iRead2 = iTest; break; } } assert( iRead==iRead2 ); } #endif *piRead = iRead; return SQLITE_OK; } /* ** Read the contents of frame iRead from the wal file into buffer pOut ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an ** error code otherwise. */ SQLITE_PRIVATE int sqlite3WalReadFrame( Wal *pWal, /* WAL handle */ u32 iRead, /* Frame to read */ int nOut, /* Size of buffer pOut in bytes */ u8 *pOut /* Buffer to write page data to */ ){ int sz; i64 iOffset; sz = pWal->hdr.szPage; sz = (sz&0xfe00) + ((sz&0x0001)<<16); testcase( sz<=32768 ); testcase( sz>=65536 ); iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE; /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */ return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); } /* ** Return the size of the database in pages (or zero, if unknown). */ SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){ if( pWal && ALWAYS(pWal->readLock>=0) ){ return pWal->hdr.nPage; } return 0; } /* ** This function starts a write transaction on the WAL. ** ** A read transaction must have already been started by a prior call ** to sqlite3WalBeginReadTransaction(). ** ** If another thread or process has written into the database since ** the read transaction was started, then it is not possible for this ** thread to write as doing so would cause a fork. So this routine ** returns SQLITE_BUSY in that case and no write transaction is started. ** ** There can only be a single writer active at a time. */ SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){ int rc; /* Cannot start a write transaction without first holding a read ** transaction. */ assert( pWal->readLock>=0 ); assert( pWal->writeLock==0 && pWal->iReCksum==0 ); if( pWal->readOnly ){ return SQLITE_READONLY; } /* Only one writer allowed at a time. Get the write lock. Return ** SQLITE_BUSY if unable. */ rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1); if( rc ){ return rc; } pWal->writeLock = 1; /* If another connection has written to the database file since the ** time the read transaction on this connection was started, then ** the write is disallowed. */ if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); pWal->writeLock = 0; rc = SQLITE_BUSY_SNAPSHOT; } return rc; } /* ** End a write transaction. The commit has already been done. This ** routine merely releases the lock. */ SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){ if( pWal->writeLock ){ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); pWal->writeLock = 0; pWal->iReCksum = 0; pWal->truncateOnCommit = 0; } return SQLITE_OK; } /* ** If any data has been written (but not committed) to the log file, this ** function moves the write-pointer back to the start of the transaction. ** ** Additionally, the callback function is invoked for each frame written ** to the WAL since the start of the transaction. If the callback returns ** other than SQLITE_OK, it is not invoked again and the error code is ** returned to the caller. ** ** Otherwise, if the callback function does not return an error, this ** function returns SQLITE_OK. */ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){ int rc = SQLITE_OK; if( ALWAYS(pWal->writeLock) ){ Pgno iMax = pWal->hdr.mxFrame; Pgno iFrame; /* Restore the clients cache of the wal-index header to the state it ** was in before the client began writing to the database. */ memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr)); for(iFrame=pWal->hdr.mxFrame+1; ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; iFrame++ ){ /* This call cannot fail. Unless the page for which the page number ** is passed as the second argument is (a) in the cache and ** (b) has an outstanding reference, then xUndo is either a no-op ** (if (a) is false) or simply expels the page from the cache (if (b) ** is false). ** ** If the upper layer is doing a rollback, it is guaranteed that there ** are no outstanding references to any page other than page 1. And ** page 1 is never written to the log until the transaction is ** committed. As a result, the call to xUndo may not fail. */ assert( walFramePgno(pWal, iFrame)!=1 ); rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame)); } if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal); } return rc; } /* ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 ** values. This function populates the array with values required to ** "rollback" the write position of the WAL handle back to the current ** point in the event of a savepoint rollback (via WalSavepointUndo()). */ SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ assert( pWal->writeLock ); aWalData[0] = pWal->hdr.mxFrame; aWalData[1] = pWal->hdr.aFrameCksum[0]; aWalData[2] = pWal->hdr.aFrameCksum[1]; aWalData[3] = pWal->nCkpt; } /* ** Move the write position of the WAL back to the point identified by ** the values in the aWalData[] array. aWalData must point to an array ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated ** by a call to WalSavepoint(). */ SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ int rc = SQLITE_OK; assert( pWal->writeLock ); assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame ); if( aWalData[3]!=pWal->nCkpt ){ /* This savepoint was opened immediately after the write-transaction ** was started. Right after that, the writer decided to wrap around ** to the start of the log. Update the savepoint values to match. */ aWalData[0] = 0; aWalData[3] = pWal->nCkpt; } if( aWalData[0]<pWal->hdr.mxFrame ){ pWal->hdr.mxFrame = aWalData[0]; pWal->hdr.aFrameCksum[0] = aWalData[1]; pWal->hdr.aFrameCksum[1] = aWalData[2]; walCleanupHash(pWal); } return rc; } /* ** This function is called just before writing a set of frames to the log ** file (see sqlite3WalFrames()). It checks to see if, instead of appending ** to the current log file, it is possible to overwrite the start of the ** existing log file with the new frames (i.e. "reset" the log). If so, ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left ** unchanged. ** ** SQLITE_OK is returned if no error is encountered (regardless of whether ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned ** if an error occurs. */ static int walRestartLog(Wal *pWal){ int rc = SQLITE_OK; int cnt; if( pWal->readLock==0 ){ volatile WalCkptInfo *pInfo = walCkptInfo(pWal); assert( pInfo->nBackfill==pWal->hdr.mxFrame ); if( pInfo->nBackfill>0 ){ u32 salt1; sqlite3_randomness(4, &salt1); rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); if( rc==SQLITE_OK ){ /* If all readers are using WAL_READ_LOCK(0) (in other words if no ** readers are currently using the WAL), then the transactions ** frames will overwrite the start of the existing log. Update the ** wal-index header to reflect this. ** ** In theory it would be Ok to update the cache of the header only ** at this point. But updating the actual wal-index header is also ** safe and means there is no special case for sqlite3WalUndo() ** to handle if this transaction is rolled back. */ walRestartHdr(pWal, salt1); walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); }else if( rc!=SQLITE_BUSY ){ return rc; } } walUnlockShared(pWal, WAL_READ_LOCK(0)); pWal->readLock = -1; cnt = 0; do{ int notUsed; rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt); }while( rc==WAL_RETRY ); assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */ testcase( (rc&0xff)==SQLITE_IOERR ); testcase( rc==SQLITE_PROTOCOL ); testcase( rc==SQLITE_OK ); } return rc; } /* ** Information about the current state of the WAL file and where ** the next fsync should occur - passed from sqlite3WalFrames() into ** walWriteToLog(). */ typedef struct WalWriter { Wal *pWal; /* The complete WAL information */ sqlite3_file *pFd; /* The WAL file to which we write */ sqlite3_int64 iSyncPoint; /* Fsync at this offset */ int syncFlags; /* Flags for the fsync */ int szPage; /* Size of one page */ } WalWriter; /* ** Write iAmt bytes of content into the WAL file beginning at iOffset. ** Do a sync when crossing the p->iSyncPoint boundary. ** ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt, ** first write the part before iSyncPoint, then sync, then write the ** rest. */ static int walWriteToLog( WalWriter *p, /* WAL to write to */ void *pContent, /* Content to be written */ int iAmt, /* Number of bytes to write */ sqlite3_int64 iOffset /* Start writing at this offset */ ){ int rc; if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){ int iFirstAmt = (int)(p->iSyncPoint - iOffset); rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset); if( rc ) return rc; iOffset += iFirstAmt; iAmt -= iFirstAmt; pContent = (void*)(iFirstAmt + (char*)pContent); assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) ); rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK); if( iAmt==0 || rc ) return rc; } rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset); return rc; } /* ** Write out a single frame of the WAL */ static int walWriteOneFrame( WalWriter *p, /* Where to write the frame */ PgHdr *pPage, /* The page of the frame to be written */ int nTruncate, /* The commit flag. Usually 0. >0 for commit */ sqlite3_int64 iOffset /* Byte offset at which to write */ ){ int rc; /* Result code from subfunctions */ void *pData; /* Data actually written */ u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */ #if defined(SQLITE_HAS_CODEC) if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT; #else pData = pPage->pData; #endif walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame); rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset); if( rc ) return rc; /* Write the page data */ rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame)); return rc; } /* ** This function is called as part of committing a transaction within which ** one or more frames have been overwritten. It updates the checksums for ** all frames written to the wal file by the current transaction starting ** with the earliest to have been overwritten. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ static int walRewriteChecksums(Wal *pWal, u32 iLast){ const int szPage = pWal->szPage;/* Database page size */ int rc = SQLITE_OK; /* Return code */ u8 *aBuf; /* Buffer to load data from wal file into */ u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */ u32 iRead; /* Next frame to read from wal file */ i64 iCksumOff; aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE); if( aBuf==0 ) return SQLITE_NOMEM_BKPT; /* Find the checksum values to use as input for the recalculating the ** first checksum. If the first frame is frame 1 (implying that the current ** transaction restarted the wal file), these values must be read from the ** wal-file header. Otherwise, read them from the frame header of the ** previous frame. */ assert( pWal->iReCksum>0 ); if( pWal->iReCksum==1 ){ iCksumOff = 24; }else{ iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16; } rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff); pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf); pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]); iRead = pWal->iReCksum; pWal->iReCksum = 0; for(; rc==SQLITE_OK && iRead<=iLast; iRead++){ i64 iOff = walFrameOffset(iRead, szPage); rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff); if( rc==SQLITE_OK ){ u32 iPgno, nDbSize; iPgno = sqlite3Get4byte(aBuf); nDbSize = sqlite3Get4byte(&aBuf[4]); walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame); rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff); } } sqlite3_free(aBuf); return rc; } /* ** Write a set of frames to the log. The caller must hold the write-lock ** on the log file (obtained using sqlite3WalBeginWriteTransaction()). */ SQLITE_PRIVATE int sqlite3WalFrames( Wal *pWal, /* Wal handle to write to */ int szPage, /* Database page-size in bytes */ PgHdr *pList, /* List of dirty pages to write */ Pgno nTruncate, /* Database size after this commit */ int isCommit, /* True if this is a commit */ int sync_flags /* Flags to pass to OsSync() (or 0) */ ){ int rc; /* Used to catch return codes */ u32 iFrame; /* Next frame address */ PgHdr *p; /* Iterator to run through pList with. */ PgHdr *pLast = 0; /* Last frame in list */ int nExtra = 0; /* Number of extra copies of last page */ int szFrame; /* The size of a single frame */ i64 iOffset; /* Next byte to write in WAL file */ WalWriter w; /* The writer */ u32 iFirst = 0; /* First frame that may be overwritten */ WalIndexHdr *pLive; /* Pointer to shared header */ assert( pList ); assert( pWal->writeLock ); /* If this frame set completes a transaction, then nTruncate>0. If ** nTruncate==0 then this frame set does not complete the transaction. */ assert( (isCommit!=0)==(nTruncate!=0) ); #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){} WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n", pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill")); } #endif pLive = (WalIndexHdr*)walIndexHdr(pWal); if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){ iFirst = pLive->mxFrame+1; } /* See if it is possible to write these frames into the start of the ** log file, instead of appending to it at pWal->hdr.mxFrame. */ if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){ return rc; } /* If this is the first frame written into the log, write the WAL ** header to the start of the WAL file. See comments at the top of ** this source file for a description of the WAL header format. */ iFrame = pWal->hdr.mxFrame; if( iFrame==0 ){ u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */ u32 aCksum[2]; /* Checksum for wal-header */ sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN)); sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION); sqlite3Put4byte(&aWalHdr[8], szPage); sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt); memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8); walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum); sqlite3Put4byte(&aWalHdr[24], aCksum[0]); sqlite3Put4byte(&aWalHdr[28], aCksum[1]); pWal->szPage = szPage; pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN; pWal->hdr.aFrameCksum[0] = aCksum[0]; pWal->hdr.aFrameCksum[1] = aCksum[1]; pWal->truncateOnCommit = 1; rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0); WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok")); if( rc!=SQLITE_OK ){ return rc; } /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise ** an out-of-order write following a WAL restart could result in ** database corruption. See the ticket: ** ** http://localhost:591/sqlite/info/ff5be73dee */ if( pWal->syncHeader && sync_flags ){ rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK); if( rc ) return rc; } } assert( (int)pWal->szPage==szPage ); /* Setup information needed to write frames into the WAL */ w.pWal = pWal; w.pFd = pWal->pWalFd; w.iSyncPoint = 0; w.syncFlags = sync_flags; w.szPage = szPage; iOffset = walFrameOffset(iFrame+1, szPage); szFrame = szPage + WAL_FRAME_HDRSIZE; /* Write all frames into the log file exactly once */ for(p=pList; p; p=p->pDirty){ int nDbSize; /* 0 normally. Positive == commit flag */ /* Check if this page has already been written into the wal file by ** the current transaction. If so, overwrite the existing frame and ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that ** checksums must be recomputed when the transaction is committed. */ if( iFirst && (p->pDirty || isCommit==0) ){ u32 iWrite = 0; VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite); assert( rc==SQLITE_OK || iWrite==0 ); if( iWrite>=iFirst ){ i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE; void *pData; if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){ pWal->iReCksum = iWrite; } #if defined(SQLITE_HAS_CODEC) if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM; #else pData = p->pData; #endif rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff); if( rc ) return rc; p->flags &= ~PGHDR_WAL_APPEND; continue; } } iFrame++; assert( iOffset==walFrameOffset(iFrame, szPage) ); nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0; rc = walWriteOneFrame(&w, p, nDbSize, iOffset); if( rc ) return rc; pLast = p; iOffset += szFrame; p->flags |= PGHDR_WAL_APPEND; } /* Recalculate checksums within the wal file if required. */ if( isCommit && pWal->iReCksum ){ rc = walRewriteChecksums(pWal, iFrame); if( rc ) return rc; } /* If this is the end of a transaction, then we might need to pad ** the transaction and/or sync the WAL file. ** ** Padding and syncing only occur if this set of frames complete a ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL ** or synchronous==OFF, then no padding or syncing are needed. ** ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not ** needed and only the sync is done. If padding is needed, then the ** final frame is repeated (with its commit mark) until the next sector ** boundary is crossed. Only the part of the WAL prior to the last ** sector boundary is synced; the part of the last frame that extends ** past the sector boundary is written after the sync. */ if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){ int bSync = 1; if( pWal->padToSectorBoundary ){ int sectorSize = sqlite3SectorSize(pWal->pWalFd); w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize; bSync = (w.iSyncPoint==iOffset); testcase( bSync ); while( iOffset<w.iSyncPoint ){ rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset); if( rc ) return rc; iOffset += szFrame; nExtra++; } } if( bSync ){ assert( rc==SQLITE_OK ); rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK); } } /* If this frame set completes the first transaction in the WAL and ** if PRAGMA journal_size_limit is set, then truncate the WAL to the ** journal size limit, if possible. */ if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){ i64 sz = pWal->mxWalSize; if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){ sz = walFrameOffset(iFrame+nExtra+1, szPage); } walLimitSize(pWal, sz); pWal->truncateOnCommit = 0; } /* Append data to the wal-index. It is not necessary to lock the ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index ** guarantees that there are no other writers, and no data that may ** be in use by existing readers is being overwritten. */ iFrame = pWal->hdr.mxFrame; for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){ if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue; iFrame++; rc = walIndexAppend(pWal, iFrame, p->pgno); } while( rc==SQLITE_OK && nExtra>0 ){ iFrame++; nExtra--; rc = walIndexAppend(pWal, iFrame, pLast->pgno); } if( rc==SQLITE_OK ){ /* Update the private copy of the header. */ pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); testcase( szPage<=32768 ); testcase( szPage>=65536 ); pWal->hdr.mxFrame = iFrame; if( isCommit ){ pWal->hdr.iChange++; pWal->hdr.nPage = nTruncate; } /* If this is a commit, update the wal-index header too. */ if( isCommit ){ walIndexWriteHdr(pWal); pWal->iCallback = iFrame; } } WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok")); return rc; } /* ** This routine is called to implement sqlite3_wal_checkpoint() and ** related interfaces. ** ** Obtain a CHECKPOINT lock and then backfill as much information as ** we can from WAL into the database. ** ** If parameter xBusy is not NULL, it is a pointer to a busy-handler ** callback. In this case this function runs a blocking checkpoint. */ SQLITE_PRIVATE int sqlite3WalCheckpoint( Wal *pWal, /* Wal connection */ sqlite3 *db, /* Check this handle's interrupt flag */ int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ int sync_flags, /* Flags to sync db file with (or 0) */ int nBuf, /* Size of temporary buffer */ u8 *zBuf, /* Temporary buffer to use */ int *pnLog, /* OUT: Number of frames in WAL */ int *pnCkpt /* OUT: Number of backfilled frames in WAL */ ){ int rc; /* Return code */ int isChanged = 0; /* True if a new wal-index header is loaded */ int eMode2 = eMode; /* Mode to pass to walCheckpoint() */ int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */ assert( pWal->ckptLock==0 ); assert( pWal->writeLock==0 ); /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); if( pWal->readOnly ) return SQLITE_READONLY; WALTRACE(("WAL%p: checkpoint begins\n", pWal)); /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive ** "checkpoint" lock on the database file. */ rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); if( rc ){ /* EVIDENCE-OF: R-10421-19736 If any other process is running a ** checkpoint operation at the same time, the lock cannot be obtained and ** SQLITE_BUSY is returned. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured, ** it will not be invoked in this case. */ testcase( rc==SQLITE_BUSY ); testcase( xBusy!=0 ); return rc; } pWal->ckptLock = 1; /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and ** TRUNCATE modes also obtain the exclusive "writer" lock on the database ** file. ** ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained ** immediately, and a busy-handler is configured, it is invoked and the ** writer lock retried until either the busy-handler returns 0 or the ** lock is successfully obtained. */ if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){ rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1); if( rc==SQLITE_OK ){ pWal->writeLock = 1; }else if( rc==SQLITE_BUSY ){ eMode2 = SQLITE_CHECKPOINT_PASSIVE; xBusy2 = 0; rc = SQLITE_OK; } } /* Read the wal-index header. */ if( rc==SQLITE_OK ){ rc = walIndexReadHdr(pWal, &isChanged); if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){ sqlite3OsUnfetch(pWal->pDbFd, 0, 0); } } /* Copy data from the log to the database file. */ if( rc==SQLITE_OK ){ if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){ rc = SQLITE_CORRUPT_BKPT; }else{ rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf); } /* If no error occurred, set the output variables. */ if( rc==SQLITE_OK || rc==SQLITE_BUSY ){ if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame; if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill); } } if( isChanged ){ /* If a new wal-index header was loaded before the checkpoint was ** performed, then the pager-cache associated with pWal is now ** out of date. So zero the cached wal-index header to ensure that ** next time the pager opens a snapshot on this database it knows that ** the cache needs to be reset. */ memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); } /* Release the locks. */ sqlite3WalEndWriteTransaction(pWal); walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); pWal->ckptLock = 0; WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok")); return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc); } /* Return the value to pass to a sqlite3_wal_hook callback, the ** number of frames in the WAL at the point of the last commit since ** sqlite3WalCallback() was called. If no commits have occurred since ** the last call, then return 0. */ SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){ u32 ret = 0; if( pWal ){ ret = pWal->iCallback; pWal->iCallback = 0; } return (int)ret; } /* ** This function is called to change the WAL subsystem into or out ** of locking_mode=EXCLUSIVE. ** ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE ** into locking_mode=NORMAL. This means that we must acquire a lock ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL ** or if the acquisition of the lock fails, then return 0. If the ** transition out of exclusive-mode is successful, return 1. This ** operation must occur while the pager is still holding the exclusive ** lock on the main database file. ** ** If op is one, then change from locking_mode=NORMAL into ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must ** be released. Return 1 if the transition is made and 0 if the ** WAL is already in exclusive-locking mode - meaning that this ** routine is a no-op. The pager must already hold the exclusive lock ** on the main database file before invoking this operation. ** ** If op is negative, then do a dry-run of the op==1 case but do ** not actually change anything. The pager uses this to see if it ** should acquire the database exclusive lock prior to invoking ** the op==1 case. */ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){ int rc; assert( pWal->writeLock==0 ); assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 ); /* pWal->readLock is usually set, but might be -1 if there was a ** prior error while attempting to acquire are read-lock. This cannot ** happen if the connection is actually in exclusive mode (as no xShmLock ** locks are taken in this case). Nor should the pager attempt to ** upgrade to exclusive-mode following such an error. */ assert( pWal->readLock>=0 || pWal->lockError ); assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) ); if( op==0 ){ if( pWal->exclusiveMode ){ pWal->exclusiveMode = 0; if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){ pWal->exclusiveMode = 1; } rc = pWal->exclusiveMode==0; }else{ /* Already in locking_mode=NORMAL */ rc = 0; } }else if( op>0 ){ assert( pWal->exclusiveMode==0 ); assert( pWal->readLock>=0 ); walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); pWal->exclusiveMode = 1; rc = 1; }else{ rc = pWal->exclusiveMode==0; } return rc; } /* ** Return true if the argument is non-NULL and the WAL module is using ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the ** WAL module is using shared-memory, return false. */ SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){ return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ); } #ifdef SQLITE_ENABLE_SNAPSHOT /* Create a snapshot object. The content of a snapshot is opaque to ** every other subsystem, so the WAL module can put whatever it needs ** in the object. */ SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){ int rc = SQLITE_OK; WalIndexHdr *pRet; static const u32 aZero[4] = { 0, 0, 0, 0 }; assert( pWal->readLock>=0 && pWal->writeLock==0 ); if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){ *ppSnapshot = 0; return SQLITE_ERROR; } pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr)); if( pRet==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr)); *ppSnapshot = (sqlite3_snapshot*)pRet; } return rc; } /* Try to open on pSnapshot when the next read-transaction starts */ SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){ pWal->pSnapshot = (WalIndexHdr*)pSnapshot; } /* ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if ** p1 is older than p2 and zero if p1 and p2 are the same snapshot. */ SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){ WalIndexHdr *pHdr1 = (WalIndexHdr*)p1; WalIndexHdr *pHdr2 = (WalIndexHdr*)p2; /* aSalt[0] is a copy of the value stored in the wal file header. It ** is incremented each time the wal file is restarted. */ if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1; if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1; if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1; if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1; return 0; } #endif /* SQLITE_ENABLE_SNAPSHOT */ #ifdef SQLITE_ENABLE_ZIPVFS /* ** If the argument is not NULL, it points to a Wal object that holds a ** read-lock. This function returns the database page-size if it is known, ** or zero if it is not (or if pWal is NULL). */ SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){ assert( pWal==0 || pWal->readLock>=0 ); return (pWal ? pWal->szPage : 0); } #endif /* Return the sqlite3_file object for the WAL file */ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){ return pWal->pWalFd; } #endif /* #ifndef SQLITE_OMIT_WAL */ /************** End of wal.c *************************************************/ /************** Begin file btmutex.c *****************************************/ /* ** 2007 August 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to implement mutexes on Btree objects. ** This code really belongs in btree.c. But btree.c is getting too ** big and we want to break it down some. This packaged seemed like ** a good breakout. */ /************** Include btreeInt.h in the middle of btmutex.c ****************/ /************** Begin file btreeInt.h ****************************************/ /* ** 2004 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements an external (disk-based) database using BTrees. ** For a detailed discussion of BTrees, refer to ** ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: ** "Sorting And Searching", pages 473-480. Addison-Wesley ** Publishing Company, Reading, Massachusetts. ** ** The basic idea is that each page of the file contains N database ** entries and N+1 pointers to subpages. ** ** ---------------------------------------------------------------- ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | ** ---------------------------------------------------------------- ** ** All of the keys on the page that Ptr(0) points to have values less ** than Key(0). All of the keys on page Ptr(1) and its subpages have ** values greater than Key(0) and less than Key(1). All of the keys ** on Ptr(N) and its subpages have values greater than Key(N-1). And ** so forth. ** ** Finding a particular key requires reading O(log(M)) pages from the ** disk where M is the number of entries in the tree. ** ** In this implementation, a single file can hold one or more separate ** BTrees. Each BTree is identified by the index of its root page. The ** key and data for any entry are combined to form the "payload". A ** fixed amount of payload can be carried directly on the database ** page. If the payload is larger than the preset amount then surplus ** bytes are stored on overflow pages. The payload for an entry ** and the preceding pointer are combined to form a "Cell". Each ** page has a small header which contains the Ptr(N) pointer and other ** information such as the size of key and data. ** ** FORMAT DETAILS ** ** The file is divided into pages. The first page is called page 1, ** the second is page 2, and so forth. A page number of zero indicates ** "no such page". The page size can be any power of 2 between 512 and 65536. ** Each page can be either a btree page, a freelist page, an overflow ** page, or a pointer-map page. ** ** The first page is always a btree page. The first 100 bytes of the first ** page contain a special header (the "file header") that describes the file. ** The format of the file header is as follows: ** ** OFFSET SIZE DESCRIPTION ** 0 16 Header string: "SQLite format 3\000" ** 16 2 Page size in bytes. (1 means 65536) ** 18 1 File format write version ** 19 1 File format read version ** 20 1 Bytes of unused space at the end of each page ** 21 1 Max embedded payload fraction (must be 64) ** 22 1 Min embedded payload fraction (must be 32) ** 23 1 Min leaf payload fraction (must be 32) ** 24 4 File change counter ** 28 4 Reserved for future use ** 32 4 First freelist page ** 36 4 Number of freelist pages in the file ** 40 60 15 4-byte meta values passed to higher layers ** ** 40 4 Schema cookie ** 44 4 File format of schema layer ** 48 4 Size of page cache ** 52 4 Largest root-page (auto/incr_vacuum) ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be ** 60 4 User version ** 64 4 Incremental vacuum mode ** 68 4 Application-ID ** 72 20 unused ** 92 4 The version-valid-for number ** 96 4 SQLITE_VERSION_NUMBER ** ** All of the integer values are big-endian (most significant byte first). ** ** The file change counter is incremented when the database is changed ** This counter allows other processes to know when the file has changed ** and thus when they need to flush their cache. ** ** The max embedded payload fraction is the amount of the total usable ** space in a page that can be consumed by a single cell for standard ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default ** is to limit the maximum cell size so that at least 4 cells will fit ** on one page. Thus the default max embedded payload fraction is 64. ** ** If the payload for a cell is larger than the max payload, then extra ** payload is spilled to overflow pages. Once an overflow page is allocated, ** as many bytes as possible are moved into the overflow pages without letting ** the cell size drop below the min embedded payload fraction. ** ** The min leaf payload fraction is like the min embedded payload fraction ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it ** not specified in the header. ** ** Each btree pages is divided into three sections: The header, the ** cell pointer array, and the cell content area. Page 1 also has a 100-byte ** file header that occurs before the page header. ** ** |----------------| ** | file header | 100 bytes. Page 1 only. ** |----------------| ** | page header | 8 bytes for leaves. 12 bytes for interior nodes ** |----------------| ** | cell pointer | | 2 bytes per cell. Sorted order. ** | array | | Grows downward ** | | v ** |----------------| ** | unallocated | ** | space | ** |----------------| ^ Grows upwards ** | cell content | | Arbitrary order interspersed with freeblocks. ** | area | | and free space fragments. ** |----------------| ** ** The page headers looks like this: ** ** OFFSET SIZE DESCRIPTION ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf ** 1 2 byte offset to the first freeblock ** 3 2 number of cells on this page ** 5 2 first byte of the cell content area ** 7 1 number of fragmented free bytes ** 8 4 Right child (the Ptr(N) value). Omitted on leaves. ** ** The flags define the format of this btree page. The leaf flag means that ** this page has no children. The zerodata flag means that this page carries ** only keys and no data. The intkey flag means that the key is an integer ** which is stored in the key size entry of the cell header rather than in ** the payload area. ** ** The cell pointer array begins on the first byte after the page header. ** The cell pointer array contains zero or more 2-byte numbers which are ** offsets from the beginning of the page to the cell content in the cell ** content area. The cell pointers occur in sorted order. The system strives ** to keep free space after the last cell pointer so that new cells can ** be easily added without having to defragment the page. ** ** Cell content is stored at the very end of the page and grows toward the ** beginning of the page. ** ** Unused space within the cell content area is collected into a linked list of ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset ** to the first freeblock is given in the header. Freeblocks occur in ** increasing order. Because a freeblock must be at least 4 bytes in size, ** any group of 3 or fewer unused bytes in the cell content area cannot ** exist on the freeblock chain. A group of 3 or fewer free bytes is called ** a fragment. The total number of bytes in all fragments is recorded. ** in the page header at offset 7. ** ** SIZE DESCRIPTION ** 2 Byte offset of the next freeblock ** 2 Bytes in this freeblock ** ** Cells are of variable length. Cells are stored in the cell content area at ** the end of the page. Pointers to the cells are in the cell pointer array ** that immediately follows the page header. Cells is not necessarily ** contiguous or in order, but cell pointers are contiguous and in order. ** ** Cell content makes use of variable length integers. A variable ** length integer is 1 to 9 bytes where the lower 7 bits of each ** byte are used. The integer consists of all bytes that have bit 8 set and ** the first byte with bit 8 clear. The most significant byte of the integer ** appears first. A variable-length integer may not be more than 9 bytes long. ** As a special case, all 8 bytes of the 9th byte are used as data. This ** allows a 64-bit integer to be encoded in 9 bytes. ** ** 0x00 becomes 0x00000000 ** 0x7f becomes 0x0000007f ** 0x81 0x00 becomes 0x00000080 ** 0x82 0x00 becomes 0x00000100 ** 0x80 0x7f becomes 0x0000007f ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 ** ** Variable length integers are used for rowids and to hold the number of ** bytes of key and data in a btree cell. ** ** The content of a cell looks like this: ** ** SIZE DESCRIPTION ** 4 Page number of the left child. Omitted if leaf flag is set. ** var Number of bytes of data. Omitted if the zerodata flag is set. ** var Number of bytes of key. Or the key itself if intkey flag is set. ** * Payload ** 4 First page of the overflow chain. Omitted if no overflow ** ** Overflow pages form a linked list. Each page except the last is completely ** filled with data (pagesize - 4 bytes). The last page can have as little ** as 1 byte of data. ** ** SIZE DESCRIPTION ** 4 Page number of next overflow page ** * Data ** ** Freelist pages come in two subtypes: trunk pages and leaf pages. The ** file header points to the first in a linked list of trunk page. Each trunk ** page points to multiple leaf pages. The content of a leaf page is ** unspecified. A trunk page looks like this: ** ** SIZE DESCRIPTION ** 4 Page number of next trunk page ** 4 Number of leaf pointers on this page ** * zero or more pages numbers of leaves */ /* #include "sqliteInt.h" */ /* The following value is the maximum cell size assuming a maximum page ** size give above. */ #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8)) /* The maximum number of cells on a single page of the database. This ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself ** plus 2 bytes for the index to the cell in the page header). Such ** small cells will be rare, but they are possible. */ #define MX_CELL(pBt) ((pBt->pageSize-8)/6) /* Forward declarations */ typedef struct MemPage MemPage; typedef struct BtLock BtLock; typedef struct CellInfo CellInfo; /* ** This is a magic string that appears at the beginning of every ** SQLite database in order to identify the file as a real database. ** ** You can change this value at compile-time by specifying a ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The ** header must be exactly 16 bytes including the zero-terminator so ** the string itself should be 15 characters long. If you change ** the header, then your custom library will not be able to read ** databases generated by the standard tools and the standard tools ** will not be able to read databases created by your custom library. */ #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */ # define SQLITE_FILE_HEADER "SQLite format 3" #endif /* ** Page type flags. An ORed combination of these flags appear as the ** first byte of on-disk image of every BTree page. */ #define PTF_INTKEY 0x01 #define PTF_ZERODATA 0x02 #define PTF_LEAFDATA 0x04 #define PTF_LEAF 0x08 /* ** An instance of this object stores information about each a single database ** page that has been loaded into memory. The information in this object ** is derived from the raw on-disk page content. ** ** As each database page is loaded into memory, the pager allocats an ** instance of this object and zeros the first 8 bytes. (This is the ** "extra" information associated with each page of the pager.) ** ** Access to all fields of this structure is controlled by the mutex ** stored in MemPage.pBt->mutex. */ struct MemPage { u8 isInit; /* True if previously initialized. MUST BE FIRST! */ u8 bBusy; /* Prevent endless loops on corrupt database files */ u8 intKey; /* True if table b-trees. False for index b-trees */ u8 intKeyLeaf; /* True if the leaf of an intKey table */ Pgno pgno; /* Page number for this page */ /* Only the first 8 bytes (above) are zeroed by pager.c when a new page ** is allocated. All fields that follow must be initialized before use */ u8 leaf; /* True if a leaf page */ u8 hdrOffset; /* 100 for page 1. 0 otherwise */ u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ u8 max1bytePayload; /* min(maxLocal,127) */ u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ u16 cellOffset; /* Index in aData of first cell pointer */ u16 nFree; /* Number of free bytes on the page */ u16 nCell; /* Number of cells on this page, local and ovfl */ u16 maskPage; /* Mask for page offset */ u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th ** non-overflow cell */ u8 *apOvfl[4]; /* Pointers to the body of overflow cells */ BtShared *pBt; /* Pointer to BtShared that this page is part of */ u8 *aData; /* Pointer to disk image of the page data */ u8 *aDataEnd; /* One byte past the end of usable data */ u8 *aCellIdx; /* The cell index area */ u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */ DbPage *pDbPage; /* Pager page handle */ u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */ void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */ }; /* ** A linked list of the following structures is stored at BtShared.pLock. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor ** is opened on the table with root page BtShared.iTable. Locks are removed ** from this list when a transaction is committed or rolled back, or when ** a btree handle is closed. */ struct BtLock { Btree *pBtree; /* Btree handle holding this lock */ Pgno iTable; /* Root page of table */ u8 eLock; /* READ_LOCK or WRITE_LOCK */ BtLock *pNext; /* Next in BtShared.pLock list */ }; /* Candidate values for BtLock.eLock */ #define READ_LOCK 1 #define WRITE_LOCK 2 /* A Btree handle ** ** A database connection contains a pointer to an instance of ** this object for every database file that it has open. This structure ** is opaque to the database connection. The database connection cannot ** see the internals of this structure and only deals with pointers to ** this structure. ** ** For some database files, the same underlying database cache might be ** shared between multiple connections. In that case, each connection ** has it own instance of this object. But each instance of this object ** points to the same BtShared object. The database cache and the ** schema associated with the database file are all contained within ** the BtShared object. ** ** All fields in this structure are accessed under sqlite3.mutex. ** The pBt pointer itself may not be changed while there exists cursors ** in the referenced BtShared that point back to this Btree since those ** cursors have to go through this Btree to find their BtShared and ** they often do so without holding sqlite3.mutex. */ struct Btree { sqlite3 *db; /* The database connection holding this btree */ BtShared *pBt; /* Sharable content of this btree */ u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ u8 sharable; /* True if we can share pBt with another db */ u8 locked; /* True if db currently has pBt locked */ u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */ int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ int nBackup; /* Number of backup operations reading this btree */ u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */ Btree *pNext; /* List of other sharable Btrees from the same db */ Btree *pPrev; /* Back pointer of the same list */ #ifndef SQLITE_OMIT_SHARED_CACHE BtLock lock; /* Object used to lock page 1 */ #endif }; /* ** Btree.inTrans may take one of the following values. ** ** If the shared-data extension is enabled, there may be multiple users ** of the Btree structure. At most one of these may open a write transaction, ** but any number may have active read transactions. */ #define TRANS_NONE 0 #define TRANS_READ 1 #define TRANS_WRITE 2 /* ** An instance of this object represents a single database file. ** ** A single database file can be in use at the same time by two ** or more database connections. When two or more connections are ** sharing the same database file, each connection has it own ** private Btree object for the file and each of those Btrees points ** to this one BtShared object. BtShared.nRef is the number of ** connections currently sharing this database file. ** ** Fields in this structure are accessed under the BtShared.mutex ** mutex, except for nRef and pNext which are accessed under the ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field ** may not be modified once it is initially set as long as nRef>0. ** The pSchema field may be set once under BtShared.mutex and ** thereafter is unchanged as long as nRef>0. ** ** isPending: ** ** If a BtShared client fails to obtain a write-lock on a database ** table (because there exists one or more read-locks on the table), ** the shared-cache enters 'pending-lock' state and isPending is ** set to true. ** ** The shared-cache leaves the 'pending lock' state when either of ** the following occur: ** ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR ** 2) The number of locks held by other connections drops to zero. ** ** while in the 'pending-lock' state, no connection may start a new ** transaction. ** ** This feature is included to help prevent writer-starvation. */ struct BtShared { Pager *pPager; /* The page cache */ sqlite3 *db; /* Database connection currently using this Btree */ BtCursor *pCursor; /* A list of all open cursors */ MemPage *pPage1; /* First page of the database */ u8 openFlags; /* Flags to sqlite3BtreeOpen() */ #ifndef SQLITE_OMIT_AUTOVACUUM u8 autoVacuum; /* True if auto-vacuum is enabled */ u8 incrVacuum; /* True if incr-vacuum is enabled */ u8 bDoTruncate; /* True to truncate db on commit */ #endif u8 inTransaction; /* Transaction state */ u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */ #ifdef SQLITE_HAS_CODEC u8 optimalReserve; /* Desired amount of reserved space per page */ #endif u16 btsFlags; /* Boolean parameters. See BTS_* macros below */ u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */ u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */ u16 minLeaf; /* Minimum local payload in a LEAFDATA table */ u32 pageSize; /* Total number of bytes on a page */ u32 usableSize; /* Number of usable bytes on each page */ int nTransaction; /* Number of open transactions (read + write) */ u32 nPage; /* Number of pages in the database */ void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */ Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */ #ifndef SQLITE_OMIT_SHARED_CACHE int nRef; /* Number of references to this structure */ BtShared *pNext; /* Next on a list of sharable BtShared structs */ BtLock *pLock; /* List of locks held on this shared-btree struct */ Btree *pWriter; /* Btree with currently open write transaction */ #endif u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */ }; /* ** Allowed values for BtShared.btsFlags */ #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */ #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */ #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */ #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */ #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */ #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */ #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */ /* ** An instance of the following structure is used to hold information ** about a cell. The parseCellPtr() function fills in this structure ** based on information extract from the raw disk page. */ struct CellInfo { i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */ u8 *pPayload; /* Pointer to the start of payload */ u32 nPayload; /* Bytes of payload */ u16 nLocal; /* Amount of payload held locally, not on overflow */ u16 nSize; /* Size of the cell content on the main b-tree page */ }; /* ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than ** this will be declared corrupt. This value is calculated based on a ** maximum database size of 2^31 pages a minimum fanout of 2 for a ** root-node and 3 for all other internal nodes. ** ** If a tree that appears to be taller than this is encountered, it is ** assumed that the database is corrupt. */ #define BTCURSOR_MAX_DEPTH 20 /* ** A cursor is a pointer to a particular entry within a particular ** b-tree within a database file. ** ** The entry is identified by its MemPage and the index in ** MemPage.aCell[] of the entry. ** ** A single database file can be shared by two more database connections, ** but cursors cannot be shared. Each cursor is associated with a ** particular database connection identified BtCursor.pBtree.db. ** ** Fields in this structure are accessed under the BtShared.mutex ** found at self->pBt->mutex. ** ** skipNext meaning: ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op. ** eState==FAULT: Cursor fault with skipNext as error code. */ struct BtCursor { Btree *pBtree; /* The Btree to which this cursor belongs */ BtShared *pBt; /* The BtShared this cursor points to */ BtCursor *pNext; /* Forms a linked list of all cursors */ Pgno *aOverflow; /* Cache of overflow page locations */ CellInfo info; /* A parse of the cell we are pointing at */ i64 nKey; /* Size of pKey, or last integer key */ void *pKey; /* Saved key that was cursor last known position */ Pgno pgnoRoot; /* The root page of this tree */ int nOvflAlloc; /* Allocated size of aOverflow[] array */ int skipNext; /* Prev() is noop if negative. Next() is noop if positive. ** Error code if eState==CURSOR_FAULT */ u8 curFlags; /* zero or more BTCF_* flags defined below */ u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */ u8 eState; /* One of the CURSOR_XXX constants (see below) */ u8 hints; /* As configured by CursorSetHints() */ /* All fields above are zeroed when the cursor is allocated. See ** sqlite3BtreeCursorZero(). Fields that follow must be manually ** initialized. */ i8 iPage; /* Index of current page in apPage */ u8 curIntKey; /* Value of apPage[0]->intKey */ struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */ void *padding1; /* Make object size a multiple of 16 */ u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */ MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */ }; /* ** Legal values for BtCursor.curFlags */ #define BTCF_WriteFlag 0x01 /* True if a write cursor */ #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */ #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */ #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */ #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */ #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */ /* ** Potential values for BtCursor.eState. ** ** CURSOR_INVALID: ** Cursor does not point to a valid entry. This can happen (for example) ** because the table is empty or because BtreeCursorFirst() has not been ** called. ** ** CURSOR_VALID: ** Cursor points to a valid entry. getPayload() etc. may be called. ** ** CURSOR_SKIPNEXT: ** Cursor is valid except that the Cursor.skipNext field is non-zero ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious() ** operation should be a no-op. ** ** CURSOR_REQUIRESEEK: ** The table that this cursor was opened on still exists, but has been ** modified since the cursor was last used. The cursor position is saved ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in ** this state, restoreCursorPosition() can be called to attempt to ** seek the cursor to the saved position. ** ** CURSOR_FAULT: ** An unrecoverable error (an I/O error or a malloc failure) has occurred ** on a different connection that shares the BtShared cache with this ** cursor. The error has left the cache in an inconsistent state. ** Do nothing else with this cursor. Any attempt to use the cursor ** should return the error code stored in BtCursor.skipNext */ #define CURSOR_INVALID 0 #define CURSOR_VALID 1 #define CURSOR_SKIPNEXT 2 #define CURSOR_REQUIRESEEK 3 #define CURSOR_FAULT 4 /* ** The database page the PENDING_BYTE occupies. This page is never used. */ # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt) /* ** These macros define the location of the pointer-map entry for a ** database page. The first argument to each is the number of usable ** bytes on each page of the database (often 1024). The second is the ** page number to look up in the pointer map. ** ** PTRMAP_PAGENO returns the database page number of the pointer-map ** page that stores the required pointer. PTRMAP_PTROFFSET returns ** the offset of the requested map entry. ** ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements ** this test. */ #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno) #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1)) #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno)) /* ** The pointer map is a lookup table that identifies the parent page for ** each child page in the database file. The parent page is the page that ** contains a pointer to the child. Every page in the database contains ** 0 or 1 parent pages. (In this context 'database page' refers ** to any page that is not part of the pointer map itself.) Each pointer map ** entry consists of a single byte 'type' and a 4 byte parent page number. ** The PTRMAP_XXX identifiers below are the valid types. ** ** The purpose of the pointer map is to facility moving pages from one ** position in the file to another as part of autovacuum. When a page ** is moved, the pointer in its parent must be updated to point to the ** new location. The pointer map is used to locate the parent page quickly. ** ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not ** used in this case. ** ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number ** is not used in this case. ** ** PTRMAP_OVERFLOW1: The database page is the first page in a list of ** overflow pages. The page number identifies the page that ** contains the cell with a pointer to this overflow page. ** ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of ** overflow pages. The page-number identifies the previous ** page in the overflow page list. ** ** PTRMAP_BTREE: The database page is a non-root btree page. The page number ** identifies the parent page in the btree. */ #define PTRMAP_ROOTPAGE 1 #define PTRMAP_FREEPAGE 2 #define PTRMAP_OVERFLOW1 3 #define PTRMAP_OVERFLOW2 4 #define PTRMAP_BTREE 5 /* A bunch of assert() statements to check the transaction state variables ** of handle p (type Btree*) are internally consistent. */ #define btreeIntegrity(p) \ assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \ assert( p->pBt->inTransaction>=p->inTrans ); /* ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine ** if the database supports auto-vacuum or not. Because it is used ** within an expression that is an argument to another macro ** (sqliteMallocRaw), it is not possible to use conditional compilation. ** So, this macro is defined instead. */ #ifndef SQLITE_OMIT_AUTOVACUUM #define ISAUTOVACUUM (pBt->autoVacuum) #else #define ISAUTOVACUUM 0 #endif /* ** This structure is passed around through all the sanity checking routines ** in order to keep track of some global state information. ** ** The aRef[] array is allocated so that there is 1 bit for each page in ** the database. As the integrity-check proceeds, for each page used in ** the database the corresponding bit is set. This allows integrity-check to ** detect pages that are used twice and orphaned pages (both of which ** indicate corruption). */ typedef struct IntegrityCk IntegrityCk; struct IntegrityCk { BtShared *pBt; /* The tree being checked out */ Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */ u8 *aPgRef; /* 1 bit per page in the db (see above) */ Pgno nPage; /* Number of pages in the database */ int mxErr; /* Stop accumulating errors when this reaches zero */ int nErr; /* Number of messages written to zErrMsg so far */ int mallocFailed; /* A memory allocation error has occurred */ const char *zPfx; /* Error message prefix */ int v1, v2; /* Values for up to two %d fields in zPfx */ StrAccum errMsg; /* Accumulate the error message text here */ u32 *heap; /* Min-heap used for analyzing cell coverage */ }; /* ** Routines to read or write a two- and four-byte big-endian integer values. */ #define get2byte(x) ((x)[0]<<8 | (x)[1]) #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) #define get4byte sqlite3Get4byte #define put4byte sqlite3Put4byte /* ** get2byteAligned(), unlike get2byte(), requires that its argument point to a ** two-byte aligned address. get2bytea() is only used for accessing the ** cell addresses in a btree header. */ #if SQLITE_BYTEORDER==4321 # define get2byteAligned(x) (*(u16*)(x)) #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000 # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x)) #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x)) #else # define get2byteAligned(x) ((x)[0]<<8 | (x)[1]) #endif /************** End of btreeInt.h ********************************************/ /************** Continuing where we left off in btmutex.c ********************/ #ifndef SQLITE_OMIT_SHARED_CACHE #if SQLITE_THREADSAFE /* ** Obtain the BtShared mutex associated with B-Tree handle p. Also, ** set BtShared.db to the database handle associated with p and the ** p->locked boolean to true. */ static void lockBtreeMutex(Btree *p){ assert( p->locked==0 ); assert( sqlite3_mutex_notheld(p->pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3_mutex_enter(p->pBt->mutex); p->pBt->db = p->db; p->locked = 1; } /* ** Release the BtShared mutex associated with B-Tree handle p and ** clear the p->locked boolean. */ static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){ BtShared *pBt = p->pBt; assert( p->locked==1 ); assert( sqlite3_mutex_held(pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); assert( p->db==pBt->db ); sqlite3_mutex_leave(pBt->mutex); p->locked = 0; } /* Forward reference */ static void SQLITE_NOINLINE btreeLockCarefully(Btree *p); /* ** Enter a mutex on the given BTree object. ** ** If the object is not sharable, then no mutex is ever required ** and this routine is a no-op. The underlying mutex is non-recursive. ** But we keep a reference count in Btree.wantToLock so the behavior ** of this interface is recursive. ** ** To avoid deadlocks, multiple Btrees are locked in the same order ** by all database connections. The p->pNext is a list of other ** Btrees belonging to the same database connection as the p Btree ** which need to be locked after p. If we cannot get a lock on ** p, then first unlock all of the others on p->pNext, then wait ** for the lock to become available on p, then relock all of the ** subsequent Btrees that desire a lock. */ SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ /* Some basic sanity checking on the Btree. The list of Btrees ** connected by pNext and pPrev should be in sorted order by ** Btree.pBt value. All elements of the list should belong to ** the same connection. Only shared Btrees are on the list. */ assert( p->pNext==0 || p->pNext->pBt>p->pBt ); assert( p->pPrev==0 || p->pPrev->pBt<p->pBt ); assert( p->pNext==0 || p->pNext->db==p->db ); assert( p->pPrev==0 || p->pPrev->db==p->db ); assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); /* Check for locking consistency */ assert( !p->locked || p->wantToLock>0 ); assert( p->sharable || p->wantToLock==0 ); /* We should already hold a lock on the database connection */ assert( sqlite3_mutex_held(p->db->mutex) ); /* Unless the database is sharable and unlocked, then BtShared.db ** should already be set correctly. */ assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); if( !p->sharable ) return; p->wantToLock++; if( p->locked ) return; btreeLockCarefully(p); } /* This is a helper function for sqlite3BtreeLock(). By moving ** complex, but seldom used logic, out of sqlite3BtreeLock() and ** into this routine, we avoid unnecessary stack pointer changes ** and thus help the sqlite3BtreeLock() routine to run much faster ** in the common case. */ static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){ Btree *pLater; /* In most cases, we should be able to acquire the lock we ** want without having to go through the ascending lock ** procedure that follows. Just be sure not to block. */ if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ p->pBt->db = p->db; p->locked = 1; return; } /* To avoid deadlock, first release all locks with a larger ** BtShared address. Then acquire our lock. Then reacquire ** the other BtShared locks that we used to hold in ascending ** order. */ for(pLater=p->pNext; pLater; pLater=pLater->pNext){ assert( pLater->sharable ); assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); assert( !pLater->locked || pLater->wantToLock>0 ); if( pLater->locked ){ unlockBtreeMutex(pLater); } } lockBtreeMutex(p); for(pLater=p->pNext; pLater; pLater=pLater->pNext){ if( pLater->wantToLock ){ lockBtreeMutex(pLater); } } } /* ** Exit the recursive mutex on a Btree. */ SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){ assert( sqlite3_mutex_held(p->db->mutex) ); if( p->sharable ){ assert( p->wantToLock>0 ); p->wantToLock--; if( p->wantToLock==0 ){ unlockBtreeMutex(p); } } } #ifndef NDEBUG /* ** Return true if the BtShared mutex is held on the btree, or if the ** B-Tree is not marked as sharable. ** ** This routine is used only from within assert() statements. */ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){ assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); return (p->sharable==0 || p->locked); } #endif /* ** Enter the mutex on every Btree associated with a database ** connection. This is needed (for example) prior to parsing ** a statement since we will be comparing table and column names ** against all schemas and we do not want those schemas being ** reset out from under us. ** ** There is a corresponding leave-all procedures. ** ** Enter the mutexes in accending order by BtShared pointer address ** to avoid the possibility of deadlock when two threads with ** two or more btrees in common both try to lock all their btrees ** at the same instant. */ static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){ int i; int skipOk = 1; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ p = db->aDb[i].pBt; if( p && p->sharable ){ sqlite3BtreeEnter(p); skipOk = 0; } } db->skipBtreeMutex = skipOk; } SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ if( db->skipBtreeMutex==0 ) btreeEnterAll(db); } static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){ int i; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ p = db->aDb[i].pBt; if( p ) sqlite3BtreeLeave(p); } } SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){ if( db->skipBtreeMutex==0 ) btreeLeaveAll(db); } #ifndef NDEBUG /* ** Return true if the current thread holds the database connection ** mutex and all required BtShared mutexes. ** ** This routine is used inside assert() statements only. */ SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ int i; if( !sqlite3_mutex_held(db->mutex) ){ return 0; } for(i=0; i<db->nDb; i++){ Btree *p; p = db->aDb[i].pBt; if( p && p->sharable && (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ return 0; } } return 1; } #endif /* NDEBUG */ #ifndef NDEBUG /* ** Return true if the correct mutexes are held for accessing the ** db->aDb[iDb].pSchema structure. The mutexes required for schema ** access are: ** ** (1) The mutex on db ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. ** ** If pSchema is not NULL, then iDb is computed from pSchema and ** db using sqlite3SchemaToIndex(). */ SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){ Btree *p; assert( db!=0 ); if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); assert( iDb>=0 && iDb<db->nDb ); if( !sqlite3_mutex_held(db->mutex) ) return 0; if( iDb==1 ) return 1; p = db->aDb[iDb].pBt; assert( p!=0 ); return p->sharable==0 || p->locked==1; } #endif /* NDEBUG */ #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ /* ** The following are special cases for mutex enter routines for use ** in single threaded applications that use shared cache. Except for ** these two routines, all mutex operations are no-ops in that case and ** are null #defines in btree.h. ** ** If shared cache is disabled, then all btree mutex routines, including ** the ones below, are no-ops and are null #defines in btree.h. */ SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ p->pBt->db = p->db; } SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ int i; for(i=0; i<db->nDb; i++){ Btree *p = db->aDb[i].pBt; if( p ){ p->pBt->db = p->db; } } } #endif /* if SQLITE_THREADSAFE */ #ifndef SQLITE_OMIT_INCRBLOB /* ** Enter a mutex on a Btree given a cursor owned by that Btree. ** ** These entry points are used by incremental I/O only. Enter() is required ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not ** the build is threadsafe. Leave() is only required by threadsafe builds. */ SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){ sqlite3BtreeEnter(pCur->pBtree); } # if SQLITE_THREADSAFE SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){ sqlite3BtreeLeave(pCur->pBtree); } # endif #endif /* ifndef SQLITE_OMIT_INCRBLOB */ #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */ /************** End of btmutex.c *********************************************/ /************** Begin file btree.c *******************************************/ /* ** 2004 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements an external (disk-based) database using BTrees. ** See the header comment on "btreeInt.h" for additional information. ** Including a description of file format and an overview of operation. */ /* #include "btreeInt.h" */ /* ** The header string that appears at the beginning of every ** SQLite database. */ static const char zMagicHeader[] = SQLITE_FILE_HEADER; /* ** Set this global variable to 1 to enable tracing using the TRACE ** macro. */ #if 0 int sqlite3BtreeTrace=1; /* True to enable tracing */ # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} #else # define TRACE(X) #endif /* ** Extract a 2-byte big-endian integer from an array of unsigned bytes. ** But if the value is zero, make it 65536. ** ** This routine is used to extract the "offset to cell content area" value ** from the header of a btree page. If the page size is 65536 and the page ** is empty, the offset should be 65536, but the 2-byte value stores zero. ** This routine makes the necessary adjustment to 65536. */ #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) /* ** Values passed as the 5th argument to allocateBtreePage() */ #define BTALLOC_ANY 0 /* Allocate any page */ #define BTALLOC_EXACT 1 /* Allocate exact page if possible */ #define BTALLOC_LE 2 /* Allocate any page <= the parameter */ /* ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not ** defined, or 0 if it is. For example: ** ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); */ #ifndef SQLITE_OMIT_AUTOVACUUM #define IfNotOmitAV(expr) (expr) #else #define IfNotOmitAV(expr) 0 #endif #ifndef SQLITE_OMIT_SHARED_CACHE /* ** A list of BtShared objects that are eligible for participation ** in shared cache. This variable has file scope during normal builds, ** but the test harness needs to access it so we make it global for ** test builds. ** ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. */ #ifdef SQLITE_TEST SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; #else static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; #endif #endif /* SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_SHARED_CACHE /* ** Enable or disable the shared pager and schema features. ** ** This routine has no effect on existing database connections. ** The shared cache setting effects only future calls to ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). */ SQLITE_API int sqlite3_enable_shared_cache(int enable){ sqlite3GlobalConfig.sharedCacheEnabled = enable; return SQLITE_OK; } #endif #ifdef SQLITE_OMIT_SHARED_CACHE /* ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), ** and clearAllSharedCacheTableLocks() ** manipulate entries in the BtShared.pLock linked list used to store ** shared-cache table level locks. If the library is compiled with the ** shared-cache feature disabled, then there is only ever one user ** of each BtShared structure and so this locking is not necessary. ** So define the lock related functions as no-ops. */ #define querySharedCacheTableLock(a,b,c) SQLITE_OK #define setSharedCacheTableLock(a,b,c) SQLITE_OK #define clearAllSharedCacheTableLocks(a) #define downgradeAllSharedCacheTableLocks(a) #define hasSharedCacheTableLock(a,b,c,d) 1 #define hasReadConflicts(a, b) 0 #endif #ifndef SQLITE_OMIT_SHARED_CACHE #ifdef SQLITE_DEBUG /* **** This function is only used as part of an assert() statement. *** ** ** Check to see if pBtree holds the required locks to read or write to the ** table with root page iRoot. Return 1 if it does and 0 if not. ** ** For example, when writing to a table with root-page iRoot via ** Btree connection pBtree: ** ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); ** ** When writing to an index that resides in a sharable database, the ** caller should have first obtained a lock specifying the root page of ** the corresponding table. This makes things a bit more complicated, ** as this module treats each table as a separate structure. To determine ** the table corresponding to the index being written, this ** function has to search through the database schema. ** ** Instead of a lock on the table/index rooted at page iRoot, the caller may ** hold a write-lock on the schema table (root page 1). This is also ** acceptable. */ static int hasSharedCacheTableLock( Btree *pBtree, /* Handle that must hold lock */ Pgno iRoot, /* Root page of b-tree */ int isIndex, /* True if iRoot is the root of an index b-tree */ int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ ){ Schema *pSchema = (Schema *)pBtree->pBt->pSchema; Pgno iTab = 0; BtLock *pLock; /* If this database is not shareable, or if the client is reading ** and has the read-uncommitted flag set, then no lock is required. ** Return true immediately. */ if( (pBtree->sharable==0) || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted)) ){ return 1; } /* If the client is reading or writing an index and the schema is ** not loaded, then it is too difficult to actually check to see if ** the correct locks are held. So do not bother - just return true. ** This case does not come up very often anyhow. */ if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){ return 1; } /* Figure out the root-page that the lock should be held on. For table ** b-trees, this is just the root page of the b-tree being read or ** written. For index b-trees, it is the root page of the associated ** table. */ if( isIndex ){ HashElem *p; for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ Index *pIdx = (Index *)sqliteHashData(p); if( pIdx->tnum==(int)iRoot ){ if( iTab ){ /* Two or more indexes share the same root page. There must ** be imposter tables. So just return true. The assert is not ** useful in that case. */ return 1; } iTab = pIdx->pTable->tnum; } } }else{ iTab = iRoot; } /* Search for the required lock. Either a write-lock on root-page iTab, a ** write-lock on the schema table, or (if the client is reading) a ** read-lock on iTab will suffice. Return 1 if any of these are found. */ for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ if( pLock->pBtree==pBtree && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1)) && pLock->eLock>=eLockType ){ return 1; } } /* Failed to find the required lock. */ return 0; } #endif /* SQLITE_DEBUG */ #ifdef SQLITE_DEBUG /* **** This function may be used as part of assert() statements only. **** ** ** Return true if it would be illegal for pBtree to write into the ** table or index rooted at iRoot because other shared connections are ** simultaneously reading that same table or index. ** ** It is illegal for pBtree to write if some other Btree object that ** shares the same BtShared object is currently reading or writing ** the iRoot table. Except, if the other Btree object has the ** read-uncommitted flag set, then it is OK for the other object to ** have a read cursor. ** ** For example, before writing to any part of the table or index ** rooted at page iRoot, one should call: ** ** assert( !hasReadConflicts(pBtree, iRoot) ); */ static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ BtCursor *p; for(p=pBtree->pBt->pCursor; p; p=p->pNext){ if( p->pgnoRoot==iRoot && p->pBtree!=pBtree && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted) ){ return 1; } } return 0; } #endif /* #ifdef SQLITE_DEBUG */ /* ** Query to see if Btree handle p may obtain a lock of type eLock ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return ** SQLITE_OK if the lock may be obtained (by calling ** setSharedCacheTableLock()), or SQLITE_LOCKED if not. */ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ BtShared *pBt = p->pBt; BtLock *pIter; assert( sqlite3BtreeHoldsMutex(p) ); assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); assert( p->db!=0 ); assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 ); /* If requesting a write-lock, then the Btree must have an open write ** transaction on this file. And, obviously, for this to be so there ** must be an open write transaction on the file itself. */ assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) ); assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); /* This routine is a no-op if the shared-cache is not enabled */ if( !p->sharable ){ return SQLITE_OK; } /* If some other connection is holding an exclusive lock, the ** requested lock may not be obtained. */ if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); return SQLITE_LOCKED_SHAREDCACHE; } for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ /* The condition (pIter->eLock!=eLock) in the following if(...) ** statement is a simplification of: ** ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) ** ** since we know that if eLock==WRITE_LOCK, then no other connection ** may hold a WRITE_LOCK on any table in this file (since there can ** only be a single writer). */ assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); if( eLock==WRITE_LOCK ){ assert( p==pBt->pWriter ); pBt->btsFlags |= BTS_PENDING; } return SQLITE_LOCKED_SHAREDCACHE; } } return SQLITE_OK; } #endif /* !SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_SHARED_CACHE /* ** Add a lock on the table with root-page iTable to the shared-btree used ** by Btree handle p. Parameter eLock must be either READ_LOCK or ** WRITE_LOCK. ** ** This function assumes the following: ** ** (a) The specified Btree object p is connected to a sharable ** database (one with the BtShared.sharable flag set), and ** ** (b) No other Btree objects hold a lock that conflicts ** with the requested lock (i.e. querySharedCacheTableLock() has ** already been called and returned SQLITE_OK). ** ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM ** is returned if a malloc attempt fails. */ static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ BtShared *pBt = p->pBt; BtLock *pLock = 0; BtLock *pIter; assert( sqlite3BtreeHoldsMutex(p) ); assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); assert( p->db!=0 ); /* A connection with the read-uncommitted flag set will never try to ** obtain a read-lock using this function. The only read-lock obtained ** by a connection in read-uncommitted mode is on the sqlite_master ** table, and that lock is obtained in BtreeBeginTrans(). */ assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK ); /* This function should only be called on a sharable b-tree after it ** has been determined that no other b-tree holds a conflicting lock. */ assert( p->sharable ); assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); /* First search the list for an existing lock on this table. */ for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ if( pIter->iTable==iTable && pIter->pBtree==p ){ pLock = pIter; break; } } /* If the above search did not find a BtLock struct associating Btree p ** with table iTable, allocate one and link it into the list. */ if( !pLock ){ pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); if( !pLock ){ return SQLITE_NOMEM_BKPT; } pLock->iTable = iTable; pLock->pBtree = p; pLock->pNext = pBt->pLock; pBt->pLock = pLock; } /* Set the BtLock.eLock variable to the maximum of the current lock ** and the requested lock. This means if a write-lock was already held ** and a read-lock requested, we don't incorrectly downgrade the lock. */ assert( WRITE_LOCK>READ_LOCK ); if( eLock>pLock->eLock ){ pLock->eLock = eLock; } return SQLITE_OK; } #endif /* !SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_SHARED_CACHE /* ** Release all the table locks (locks obtained via calls to ** the setSharedCacheTableLock() procedure) held by Btree object p. ** ** This function assumes that Btree p has an open read or write ** transaction. If it does not, then the BTS_PENDING flag ** may be incorrectly cleared. */ static void clearAllSharedCacheTableLocks(Btree *p){ BtShared *pBt = p->pBt; BtLock **ppIter = &pBt->pLock; assert( sqlite3BtreeHoldsMutex(p) ); assert( p->sharable || 0==*ppIter ); assert( p->inTrans>0 ); while( *ppIter ){ BtLock *pLock = *ppIter; assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); assert( pLock->pBtree->inTrans>=pLock->eLock ); if( pLock->pBtree==p ){ *ppIter = pLock->pNext; assert( pLock->iTable!=1 || pLock==&p->lock ); if( pLock->iTable!=1 ){ sqlite3_free(pLock); } }else{ ppIter = &pLock->pNext; } } assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); if( pBt->pWriter==p ){ pBt->pWriter = 0; pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); }else if( pBt->nTransaction==2 ){ /* This function is called when Btree p is concluding its ** transaction. If there currently exists a writer, and p is not ** that writer, then the number of locks held by connections other ** than the writer must be about to drop to zero. In this case ** set the BTS_PENDING flag to 0. ** ** If there is not currently a writer, then BTS_PENDING must ** be zero already. So this next line is harmless in that case. */ pBt->btsFlags &= ~BTS_PENDING; } } /* ** This function changes all write-locks held by Btree p into read-locks. */ static void downgradeAllSharedCacheTableLocks(Btree *p){ BtShared *pBt = p->pBt; if( pBt->pWriter==p ){ BtLock *pLock; pBt->pWriter = 0; pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); pLock->eLock = READ_LOCK; } } } #endif /* SQLITE_OMIT_SHARED_CACHE */ static void releasePage(MemPage *pPage); /* Forward reference */ /* ***** This routine is used inside of assert() only **** ** ** Verify that the cursor holds the mutex on its BtShared */ #ifdef SQLITE_DEBUG static int cursorHoldsMutex(BtCursor *p){ return sqlite3_mutex_held(p->pBt->mutex); } /* Verify that the cursor and the BtShared agree about what is the current ** database connetion. This is important in shared-cache mode. If the database ** connection pointers get out-of-sync, it is possible for routines like ** btreeInitPage() to reference an stale connection pointer that references a ** a connection that has already closed. This routine is used inside assert() ** statements only and for the purpose of double-checking that the btree code ** does keep the database connection pointers up-to-date. */ static int cursorOwnsBtShared(BtCursor *p){ assert( cursorHoldsMutex(p) ); return (p->pBtree->db==p->pBt->db); } #endif /* ** Invalidate the overflow cache of the cursor passed as the first argument. ** on the shared btree structure pBt. */ #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl) /* ** Invalidate the overflow page-list cache for all cursors opened ** on the shared btree structure pBt. */ static void invalidateAllOverflowCache(BtShared *pBt){ BtCursor *p; assert( sqlite3_mutex_held(pBt->mutex) ); for(p=pBt->pCursor; p; p=p->pNext){ invalidateOverflowCache(p); } } #ifndef SQLITE_OMIT_INCRBLOB /* ** This function is called before modifying the contents of a table ** to invalidate any incrblob cursors that are open on the ** row or one of the rows being modified. ** ** If argument isClearTable is true, then the entire contents of the ** table is about to be deleted. In this case invalidate all incrblob ** cursors open on any row within the table with root-page pgnoRoot. ** ** Otherwise, if argument isClearTable is false, then the row with ** rowid iRow is being replaced or deleted. In this case invalidate ** only those incrblob cursors open on that specific row. */ static void invalidateIncrblobCursors( Btree *pBtree, /* The database file to check */ i64 iRow, /* The rowid that might be changing */ int isClearTable /* True if all rows are being deleted */ ){ BtCursor *p; if( pBtree->hasIncrblobCur==0 ) return; assert( sqlite3BtreeHoldsMutex(pBtree) ); pBtree->hasIncrblobCur = 0; for(p=pBtree->pBt->pCursor; p; p=p->pNext){ if( (p->curFlags & BTCF_Incrblob)!=0 ){ pBtree->hasIncrblobCur = 1; if( isClearTable || p->info.nKey==iRow ){ p->eState = CURSOR_INVALID; } } } } #else /* Stub function when INCRBLOB is omitted */ #define invalidateIncrblobCursors(x,y,z) #endif /* SQLITE_OMIT_INCRBLOB */ /* ** Set bit pgno of the BtShared.pHasContent bitvec. This is called ** when a page that previously contained data becomes a free-list leaf ** page. ** ** The BtShared.pHasContent bitvec exists to work around an obscure ** bug caused by the interaction of two useful IO optimizations surrounding ** free-list leaf pages: ** ** 1) When all data is deleted from a page and the page becomes ** a free-list leaf page, the page is not written to the database ** (as free-list leaf pages contain no meaningful data). Sometimes ** such a page is not even journalled (as it will not be modified, ** why bother journalling it?). ** ** 2) When a free-list leaf page is reused, its content is not read ** from the database or written to the journal file (why should it ** be, if it is not at all meaningful?). ** ** By themselves, these optimizations work fine and provide a handy ** performance boost to bulk delete or insert operations. However, if ** a page is moved to the free-list and then reused within the same ** transaction, a problem comes up. If the page is not journalled when ** it is moved to the free-list and it is also not journalled when it ** is extracted from the free-list and reused, then the original data ** may be lost. In the event of a rollback, it may not be possible ** to restore the database to its original configuration. ** ** The solution is the BtShared.pHasContent bitvec. Whenever a page is ** moved to become a free-list leaf page, the corresponding bit is ** set in the bitvec. Whenever a leaf page is extracted from the free-list, ** optimization 2 above is omitted if the corresponding bit is already ** set in BtShared.pHasContent. The contents of the bitvec are cleared ** at the end of every transaction. */ static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ int rc = SQLITE_OK; if( !pBt->pHasContent ){ assert( pgno<=pBt->nPage ); pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); if( !pBt->pHasContent ){ rc = SQLITE_NOMEM_BKPT; } } if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ rc = sqlite3BitvecSet(pBt->pHasContent, pgno); } return rc; } /* ** Query the BtShared.pHasContent vector. ** ** This function is called when a free-list leaf page is removed from the ** free-list for reuse. It returns false if it is safe to retrieve the ** page from the pager layer with the 'no-content' flag set. True otherwise. */ static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ Bitvec *p = pBt->pHasContent; return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno))); } /* ** Clear (destroy) the BtShared.pHasContent bitvec. This should be ** invoked at the conclusion of each write-transaction. */ static void btreeClearHasContent(BtShared *pBt){ sqlite3BitvecDestroy(pBt->pHasContent); pBt->pHasContent = 0; } /* ** Release all of the apPage[] pages for a cursor. */ static void btreeReleaseAllCursorPages(BtCursor *pCur){ int i; for(i=0; i<=pCur->iPage; i++){ releasePage(pCur->apPage[i]); pCur->apPage[i] = 0; } pCur->iPage = -1; } /* ** The cursor passed as the only argument must point to a valid entry ** when this function is called (i.e. have eState==CURSOR_VALID). This ** function saves the current cursor key in variables pCur->nKey and ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error ** code otherwise. ** ** If the cursor is open on an intkey table, then the integer key ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is ** set to point to a malloced buffer pCur->nKey bytes in size containing ** the key. */ static int saveCursorKey(BtCursor *pCur){ int rc = SQLITE_OK; assert( CURSOR_VALID==pCur->eState ); assert( 0==pCur->pKey ); assert( cursorHoldsMutex(pCur) ); if( pCur->curIntKey ){ /* Only the rowid is required for a table btree */ pCur->nKey = sqlite3BtreeIntegerKey(pCur); }else{ /* For an index btree, save the complete key content */ void *pKey; pCur->nKey = sqlite3BtreePayloadSize(pCur); pKey = sqlite3Malloc( pCur->nKey ); if( pKey ){ rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey); if( rc==SQLITE_OK ){ pCur->pKey = pKey; }else{ sqlite3_free(pKey); } }else{ rc = SQLITE_NOMEM_BKPT; } } assert( !pCur->curIntKey || !pCur->pKey ); return rc; } /* ** Save the current cursor position in the variables BtCursor.nKey ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. ** ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) ** prior to calling this routine. */ static int saveCursorPosition(BtCursor *pCur){ int rc; assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState ); assert( 0==pCur->pKey ); assert( cursorHoldsMutex(pCur) ); if( pCur->eState==CURSOR_SKIPNEXT ){ pCur->eState = CURSOR_VALID; }else{ pCur->skipNext = 0; } rc = saveCursorKey(pCur); if( rc==SQLITE_OK ){ btreeReleaseAllCursorPages(pCur); pCur->eState = CURSOR_REQUIRESEEK; } pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast); return rc; } /* Forward reference */ static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*); /* ** Save the positions of all cursors (except pExcept) that are open on ** the table with root-page iRoot. "Saving the cursor position" means that ** the location in the btree is remembered in such a way that it can be ** moved back to the same spot after the btree has been modified. This ** routine is called just before cursor pExcept is used to modify the ** table, for example in BtreeDelete() or BtreeInsert(). ** ** If there are two or more cursors on the same btree, then all such ** cursors should have their BTCF_Multiple flag set. The btreeCursor() ** routine enforces that rule. This routine only needs to be called in ** the uncommon case when pExpect has the BTCF_Multiple flag set. ** ** If pExpect!=NULL and if no other cursors are found on the same root-page, ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another ** pointless call to this routine. ** ** Implementation note: This routine merely checks to see if any cursors ** need to be saved. It calls out to saveCursorsOnList() in the (unusual) ** event that cursors are in need to being saved. */ static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ BtCursor *p; assert( sqlite3_mutex_held(pBt->mutex) ); assert( pExcept==0 || pExcept->pBt==pBt ); for(p=pBt->pCursor; p; p=p->pNext){ if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; } if( p ) return saveCursorsOnList(p, iRoot, pExcept); if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple; return SQLITE_OK; } /* This helper routine to saveAllCursors does the actual work of saving ** the cursors if and when a cursor is found that actually requires saving. ** The common case is that no cursors need to be saved, so this routine is ** broken out from its caller to avoid unnecessary stack pointer movement. */ static int SQLITE_NOINLINE saveCursorsOnList( BtCursor *p, /* The first cursor that needs saving */ Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */ BtCursor *pExcept /* Do not save this cursor */ ){ do{ if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ int rc = saveCursorPosition(p); if( SQLITE_OK!=rc ){ return rc; } }else{ testcase( p->iPage>0 ); btreeReleaseAllCursorPages(p); } } p = p->pNext; }while( p ); return SQLITE_OK; } /* ** Clear the current cursor position. */ SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); sqlite3_free(pCur->pKey); pCur->pKey = 0; pCur->eState = CURSOR_INVALID; } /* ** In this version of BtreeMoveto, pKey is a packed index record ** such as is generated by the OP_MakeRecord opcode. Unpack the ** record and then call BtreeMovetoUnpacked() to do the work. */ static int btreeMoveto( BtCursor *pCur, /* Cursor open on the btree to be searched */ const void *pKey, /* Packed key if the btree is an index */ i64 nKey, /* Integer key for tables. Size of pKey for indices */ int bias, /* Bias search to the high end */ int *pRes /* Write search results here */ ){ int rc; /* Status code */ UnpackedRecord *pIdxKey; /* Unpacked index key */ if( pKey ){ assert( nKey==(i64)(int)nKey ); pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo); if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT; sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey); if( pIdxKey->nField==0 ){ rc = SQLITE_CORRUPT_BKPT; goto moveto_done; } }else{ pIdxKey = 0; } rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); moveto_done: if( pIdxKey ){ sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey); } return rc; } /* ** Restore the cursor to the position it was in (or as close to as possible) ** when saveCursorPosition() was called. Note that this call deletes the ** saved position info stored by saveCursorPosition(), so there can be ** at most one effective restoreCursorPosition() call after each ** saveCursorPosition(). */ static int btreeRestoreCursorPosition(BtCursor *pCur){ int rc; int skipNext; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState>=CURSOR_REQUIRESEEK ); if( pCur->eState==CURSOR_FAULT ){ return pCur->skipNext; } pCur->eState = CURSOR_INVALID; rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); if( rc==SQLITE_OK ){ sqlite3_free(pCur->pKey); pCur->pKey = 0; assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); pCur->skipNext |= skipNext; if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ pCur->eState = CURSOR_SKIPNEXT; } } return rc; } #define restoreCursorPosition(p) \ (p->eState>=CURSOR_REQUIRESEEK ? \ btreeRestoreCursorPosition(p) : \ SQLITE_OK) /* ** Determine whether or not a cursor has moved from the position where ** it was last placed, or has been invalidated for any other reason. ** Cursors can move when the row they are pointing at is deleted out ** from under them, for example. Cursor might also move if a btree ** is rebalanced. ** ** Calling this routine with a NULL cursor pointer returns false. ** ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor ** back to where it ought to be if this routine returns true. */ SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ return pCur->eState!=CURSOR_VALID; } /* ** This routine restores a cursor back to its original position after it ** has been moved by some outside activity (such as a btree rebalance or ** a row having been deleted out from under the cursor). ** ** On success, the *pDifferentRow parameter is false if the cursor is left ** pointing at exactly the same row. *pDifferntRow is the row the cursor ** was pointing to has been deleted, forcing the cursor to point to some ** nearby row. ** ** This routine should only be called for a cursor that just returned ** TRUE from sqlite3BtreeCursorHasMoved(). */ SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ int rc; assert( pCur!=0 ); assert( pCur->eState!=CURSOR_VALID ); rc = restoreCursorPosition(pCur); if( rc ){ *pDifferentRow = 1; return rc; } if( pCur->eState!=CURSOR_VALID ){ *pDifferentRow = 1; }else{ assert( pCur->skipNext==0 ); *pDifferentRow = 0; } return SQLITE_OK; } #ifdef SQLITE_ENABLE_CURSOR_HINTS /* ** Provide hints to the cursor. The particular hint given (and the type ** and number of the varargs parameters) is determined by the eHintType ** parameter. See the definitions of the BTREE_HINT_* macros for details. */ SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ /* Used only by system that substitute their own storage engine */ } #endif /* ** Provide flag hints to the cursor. */ SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 ); pCur->hints = x; } #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Given a page number of a regular database page, return the page ** number for the pointer-map page that contains the entry for the ** input page number. ** ** Return 0 (not a valid page) for pgno==1 since there is ** no pointer map associated with page 1. The integrity_check logic ** requires that ptrmapPageno(*,1)!=1. */ static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ int nPagesPerMapPage; Pgno iPtrMap, ret; assert( sqlite3_mutex_held(pBt->mutex) ); if( pgno<2 ) return 0; nPagesPerMapPage = (pBt->usableSize/5)+1; iPtrMap = (pgno-2)/nPagesPerMapPage; ret = (iPtrMap*nPagesPerMapPage) + 2; if( ret==PENDING_BYTE_PAGE(pBt) ){ ret++; } return ret; } /* ** Write an entry into the pointer map. ** ** This routine updates the pointer map entry for page number 'key' ** so that it maps to type 'eType' and parent page number 'pgno'. ** ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is ** a no-op. If an error occurs, the appropriate error code is written ** into *pRC. */ static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ DbPage *pDbPage; /* The pointer map page */ u8 *pPtrmap; /* The pointer map data */ Pgno iPtrmap; /* The pointer map page number */ int offset; /* Offset in pointer map page */ int rc; /* Return code from subfunctions */ if( *pRC ) return; assert( sqlite3_mutex_held(pBt->mutex) ); /* The master-journal page number must never be used as a pointer map page */ assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); assert( pBt->autoVacuum ); if( key==0 ){ *pRC = SQLITE_CORRUPT_BKPT; return; } iPtrmap = PTRMAP_PAGENO(pBt, key); rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); if( rc!=SQLITE_OK ){ *pRC = rc; return; } offset = PTRMAP_PTROFFSET(iPtrmap, key); if( offset<0 ){ *pRC = SQLITE_CORRUPT_BKPT; goto ptrmap_exit; } assert( offset <= (int)pBt->usableSize-5 ); pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); *pRC= rc = sqlite3PagerWrite(pDbPage); if( rc==SQLITE_OK ){ pPtrmap[offset] = eType; put4byte(&pPtrmap[offset+1], parent); } } ptrmap_exit: sqlite3PagerUnref(pDbPage); } /* ** Read an entry from the pointer map. ** ** This routine retrieves the pointer map entry for page 'key', writing ** the type and parent page number to *pEType and *pPgno respectively. ** An error code is returned if something goes wrong, otherwise SQLITE_OK. */ static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ DbPage *pDbPage; /* The pointer map page */ int iPtrmap; /* Pointer map page index */ u8 *pPtrmap; /* Pointer map page data */ int offset; /* Offset of entry in pointer map */ int rc; assert( sqlite3_mutex_held(pBt->mutex) ); iPtrmap = PTRMAP_PAGENO(pBt, key); rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); if( rc!=0 ){ return rc; } pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); offset = PTRMAP_PTROFFSET(iPtrmap, key); if( offset<0 ){ sqlite3PagerUnref(pDbPage); return SQLITE_CORRUPT_BKPT; } assert( offset <= (int)pBt->usableSize-5 ); assert( pEType!=0 ); *pEType = pPtrmap[offset]; if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); sqlite3PagerUnref(pDbPage); if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; return SQLITE_OK; } #else /* if defined SQLITE_OMIT_AUTOVACUUM */ #define ptrmapPut(w,x,y,z,rc) #define ptrmapGet(w,x,y,z) SQLITE_OK #define ptrmapPutOvflPtr(x, y, rc) #endif /* ** Given a btree page and a cell index (0 means the first cell on ** the page, 1 means the second cell, and so forth) return a pointer ** to the cell content. ** ** findCellPastPtr() does the same except it skips past the initial ** 4-byte child pointer found on interior pages, if there is one. ** ** This routine works only for pages that do not contain overflow cells. */ #define findCell(P,I) \ ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) #define findCellPastPtr(P,I) \ ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) /* ** This is common tail processing for btreeParseCellPtr() and ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely ** on a single B-tree page. Make necessary adjustments to the CellInfo ** structure. */ static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow( MemPage *pPage, /* Page containing the cell */ u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ /* If the payload will not fit completely on the local page, we have ** to decide how much to store locally and how much to spill onto ** overflow pages. The strategy is to minimize the amount of unused ** space on overflow pages while keeping the amount of local storage ** in between minLocal and maxLocal. ** ** Warning: changing the way overflow payload is distributed in any ** way will result in an incompatible file format. */ int minLocal; /* Minimum amount of payload held locally */ int maxLocal; /* Maximum amount of payload held locally */ int surplus; /* Overflow payload available for local storage */ minLocal = pPage->minLocal; maxLocal = pPage->maxLocal; surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4); testcase( surplus==maxLocal ); testcase( surplus==maxLocal+1 ); if( surplus <= maxLocal ){ pInfo->nLocal = (u16)surplus; }else{ pInfo->nLocal = (u16)minLocal; } pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4; } /* ** The following routines are implementations of the MemPage.xParseCell() ** method. ** ** Parse a cell content block and fill in the CellInfo structure. ** ** btreeParseCellPtr() => table btree leaf nodes ** btreeParseCellNoPayload() => table btree internal nodes ** btreeParseCellPtrIndex() => index btree nodes ** ** There is also a wrapper function btreeParseCell() that works for ** all MemPage types and that references the cell by index rather than ** by pointer. */ static void btreeParseCellPtrNoPayload( MemPage *pPage, /* Page containing the cell */ u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 ); assert( pPage->childPtrSize==4 ); #ifndef SQLITE_DEBUG UNUSED_PARAMETER(pPage); #endif pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey); pInfo->nPayload = 0; pInfo->nLocal = 0; pInfo->pPayload = 0; return; } static void btreeParseCellPtr( MemPage *pPage, /* Page containing the cell */ u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ u8 *pIter; /* For scanning through pCell */ u32 nPayload; /* Number of bytes of cell payload */ u64 iKey; /* Extracted Key value */ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 || pPage->leaf==1 ); assert( pPage->intKeyLeaf ); assert( pPage->childPtrSize==0 ); pIter = pCell; /* The next block of code is equivalent to: ** ** pIter += getVarint32(pIter, nPayload); ** ** The code is inlined to avoid a function call. */ nPayload = *pIter; if( nPayload>=0x80 ){ u8 *pEnd = &pIter[8]; nPayload &= 0x7f; do{ nPayload = (nPayload<<7) | (*++pIter & 0x7f); }while( (*pIter)>=0x80 && pIter<pEnd ); } pIter++; /* The next block of code is equivalent to: ** ** pIter += getVarint(pIter, (u64*)&pInfo->nKey); ** ** The code is inlined to avoid a function call. */ iKey = *pIter; if( iKey>=0x80 ){ u8 *pEnd = &pIter[7]; iKey &= 0x7f; while(1){ iKey = (iKey<<7) | (*++pIter & 0x7f); if( (*pIter)<0x80 ) break; if( pIter>=pEnd ){ iKey = (iKey<<8) | *++pIter; break; } } } pIter++; pInfo->nKey = *(i64*)&iKey; pInfo->nPayload = nPayload; pInfo->pPayload = pIter; testcase( nPayload==pPage->maxLocal ); testcase( nPayload==pPage->maxLocal+1 ); if( nPayload<=pPage->maxLocal ){ /* This is the (easy) common case where the entire payload fits ** on the local page. No overflow is required. */ pInfo->nSize = nPayload + (u16)(pIter - pCell); if( pInfo->nSize<4 ) pInfo->nSize = 4; pInfo->nLocal = (u16)nPayload; }else{ btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); } } static void btreeParseCellPtrIndex( MemPage *pPage, /* Page containing the cell */ u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ u8 *pIter; /* For scanning through pCell */ u32 nPayload; /* Number of bytes of cell payload */ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 || pPage->leaf==1 ); assert( pPage->intKeyLeaf==0 ); pIter = pCell + pPage->childPtrSize; nPayload = *pIter; if( nPayload>=0x80 ){ u8 *pEnd = &pIter[8]; nPayload &= 0x7f; do{ nPayload = (nPayload<<7) | (*++pIter & 0x7f); }while( *(pIter)>=0x80 && pIter<pEnd ); } pIter++; pInfo->nKey = nPayload; pInfo->nPayload = nPayload; pInfo->pPayload = pIter; testcase( nPayload==pPage->maxLocal ); testcase( nPayload==pPage->maxLocal+1 ); if( nPayload<=pPage->maxLocal ){ /* This is the (easy) common case where the entire payload fits ** on the local page. No overflow is required. */ pInfo->nSize = nPayload + (u16)(pIter - pCell); if( pInfo->nSize<4 ) pInfo->nSize = 4; pInfo->nLocal = (u16)nPayload; }else{ btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); } } static void btreeParseCell( MemPage *pPage, /* Page containing the cell */ int iCell, /* The cell index. First cell is 0 */ CellInfo *pInfo /* Fill in this structure */ ){ pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo); } /* ** The following routines are implementations of the MemPage.xCellSize ** method. ** ** Compute the total number of bytes that a Cell needs in the cell ** data area of the btree-page. The return number includes the cell ** data header and the local payload, but not any overflow page or ** the space used by the cell pointer. ** ** cellSizePtrNoPayload() => table internal nodes ** cellSizePtr() => all index nodes & table leaf nodes */ static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */ u8 *pEnd; /* End mark for a varint */ u32 nSize; /* Size value to return */ #ifdef SQLITE_DEBUG /* The value returned by this function should always be the same as ** the (CellInfo.nSize) value found by doing a full parse of the ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of ** this function verifies that this invariant is not violated. */ CellInfo debuginfo; pPage->xParseCell(pPage, pCell, &debuginfo); #endif nSize = *pIter; if( nSize>=0x80 ){ pEnd = &pIter[8]; nSize &= 0x7f; do{ nSize = (nSize<<7) | (*++pIter & 0x7f); }while( *(pIter)>=0x80 && pIter<pEnd ); } pIter++; if( pPage->intKey ){ /* pIter now points at the 64-bit integer key value, a variable length ** integer. The following block moves pIter to point at the first byte ** past the end of the key value. */ pEnd = &pIter[9]; while( (*pIter++)&0x80 && pIter<pEnd ); } testcase( nSize==pPage->maxLocal ); testcase( nSize==pPage->maxLocal+1 ); if( nSize<=pPage->maxLocal ){ nSize += (u32)(pIter - pCell); if( nSize<4 ) nSize = 4; }else{ int minLocal = pPage->minLocal; nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); testcase( nSize==pPage->maxLocal ); testcase( nSize==pPage->maxLocal+1 ); if( nSize>pPage->maxLocal ){ nSize = minLocal; } nSize += 4 + (u16)(pIter - pCell); } assert( nSize==debuginfo.nSize || CORRUPT_DB ); return (u16)nSize; } static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){ u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ u8 *pEnd; /* End mark for a varint */ #ifdef SQLITE_DEBUG /* The value returned by this function should always be the same as ** the (CellInfo.nSize) value found by doing a full parse of the ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of ** this function verifies that this invariant is not violated. */ CellInfo debuginfo; pPage->xParseCell(pPage, pCell, &debuginfo); #else UNUSED_PARAMETER(pPage); #endif assert( pPage->childPtrSize==4 ); pEnd = pIter + 9; while( (*pIter++)&0x80 && pIter<pEnd ); assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB ); return (u16)(pIter - pCell); } #ifdef SQLITE_DEBUG /* This variation on cellSizePtr() is used inside of assert() statements ** only. */ static u16 cellSize(MemPage *pPage, int iCell){ return pPage->xCellSize(pPage, findCell(pPage, iCell)); } #endif #ifndef SQLITE_OMIT_AUTOVACUUM /* ** If the cell pCell, part of page pPage contains a pointer ** to an overflow page, insert an entry into the pointer-map ** for the overflow page. */ static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ CellInfo info; if( *pRC ) return; assert( pCell!=0 ); pPage->xParseCell(pPage, pCell, &info); if( info.nLocal<info.nPayload ){ Pgno ovfl = get4byte(&pCell[info.nSize-4]); ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); } } #endif /* ** Defragment the page given. All Cells are moved to the ** end of the page and all free space is collected into one ** big FreeBlk that occurs in between the header and cell ** pointer array and the cell content area. ** ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a ** b-tree page so that there are no freeblocks or fragment bytes, all ** unused bytes are contained in the unallocated space region, and all ** cells are packed tightly at the end of the page. */ static int defragmentPage(MemPage *pPage){ int i; /* Loop counter */ int pc; /* Address of the i-th cell */ int hdr; /* Offset to the page header */ int size; /* Size of a cell */ int usableSize; /* Number of usable bytes on a page */ int cellOffset; /* Offset to the cell pointer array */ int cbrk; /* Offset to the cell content area */ int nCell; /* Number of cells on the page */ unsigned char *data; /* The page data */ unsigned char *temp; /* Temp area for cell content */ unsigned char *src; /* Source of content */ int iCellFirst; /* First allowable cell index */ int iCellLast; /* Last possible cell index */ assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( pPage->pBt!=0 ); assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); assert( pPage->nOverflow==0 ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); temp = 0; src = data = pPage->aData; hdr = pPage->hdrOffset; cellOffset = pPage->cellOffset; nCell = pPage->nCell; assert( nCell==get2byte(&data[hdr+3]) ); usableSize = pPage->pBt->usableSize; cbrk = usableSize; iCellFirst = cellOffset + 2*nCell; iCellLast = usableSize - 4; for(i=0; i<nCell; i++){ u8 *pAddr; /* The i-th cell pointer */ pAddr = &data[cellOffset + i*2]; pc = get2byte(pAddr); testcase( pc==iCellFirst ); testcase( pc==iCellLast ); /* These conditions have already been verified in btreeInitPage() ** if PRAGMA cell_size_check=ON. */ if( pc<iCellFirst || pc>iCellLast ){ return SQLITE_CORRUPT_BKPT; } assert( pc>=iCellFirst && pc<=iCellLast ); size = pPage->xCellSize(pPage, &src[pc]); cbrk -= size; if( cbrk<iCellFirst || pc+size>usableSize ){ return SQLITE_CORRUPT_BKPT; } assert( cbrk+size<=usableSize && cbrk>=iCellFirst ); testcase( cbrk+size==usableSize ); testcase( pc+size==usableSize ); put2byte(pAddr, cbrk); if( temp==0 ){ int x; if( cbrk==pc ) continue; temp = sqlite3PagerTempSpace(pPage->pBt->pPager); x = get2byte(&data[hdr+5]); memcpy(&temp[x], &data[x], (cbrk+size) - x); src = temp; } memcpy(&data[cbrk], &src[pc], size); } assert( cbrk>=iCellFirst ); put2byte(&data[hdr+5], cbrk); data[hdr+1] = 0; data[hdr+2] = 0; data[hdr+7] = 0; memset(&data[iCellFirst], 0, cbrk-iCellFirst); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); if( cbrk-iCellFirst!=pPage->nFree ){ return SQLITE_CORRUPT_BKPT; } return SQLITE_OK; } /* ** Search the free-list on page pPg for space to store a cell nByte bytes in ** size. If one can be found, return a pointer to the space and remove it ** from the free-list. ** ** If no suitable space can be found on the free-list, return NULL. ** ** This function may detect corruption within pPg. If corruption is ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned. ** ** Slots on the free list that are between 1 and 3 bytes larger than nByte ** will be ignored if adding the extra space to the fragmentation count ** causes the fragmentation count to exceed 60. */ static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ const int hdr = pPg->hdrOffset; u8 * const aData = pPg->aData; int iAddr = hdr + 1; int pc = get2byte(&aData[iAddr]); int x; int usableSize = pPg->pBt->usableSize; assert( pc>0 ); do{ int size; /* Size of the free slot */ /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of ** increasing offset. */ if( pc>usableSize-4 || pc<iAddr+4 ){ *pRc = SQLITE_CORRUPT_BKPT; return 0; } /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each ** freeblock form a big-endian integer which is the size of the freeblock ** in bytes, including the 4-byte header. */ size = get2byte(&aData[pc+2]); if( (x = size - nByte)>=0 ){ testcase( x==4 ); testcase( x==3 ); if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){ *pRc = SQLITE_CORRUPT_BKPT; return 0; }else if( x<4 ){ /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total ** number of bytes in fragments may not exceed 60. */ if( aData[hdr+7]>57 ) return 0; /* Remove the slot from the free-list. Update the number of ** fragmented bytes within the page. */ memcpy(&aData[iAddr], &aData[pc], 2); aData[hdr+7] += (u8)x; }else{ /* The slot remains on the free-list. Reduce its size to account ** for the portion used by the new allocation. */ put2byte(&aData[pc+2], x); } return &aData[pc + x]; } iAddr = pc; pc = get2byte(&aData[pc]); }while( pc ); return 0; } /* ** Allocate nByte bytes of space from within the B-Tree page passed ** as the first argument. Write into *pIdx the index into pPage->aData[] ** of the first byte of allocated space. Return either SQLITE_OK or ** an error code (usually SQLITE_CORRUPT). ** ** The caller guarantees that there is sufficient space to make the ** allocation. This routine might need to defragment in order to bring ** all the space together, however. This routine will avoid using ** the first two bytes past the cell pointer area since presumably this ** allocation is being made in order to insert a new cell, so we will ** also end up needing a new cell pointer. */ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ u8 * const data = pPage->aData; /* Local cache of pPage->aData */ int top; /* First byte of cell content area */ int rc = SQLITE_OK; /* Integer return code */ int gap; /* First byte of gap between cell pointers and cell content */ assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( pPage->pBt ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( nByte>=0 ); /* Minimum cell size is 4 */ assert( pPage->nFree>=nByte ); assert( pPage->nOverflow==0 ); assert( nByte < (int)(pPage->pBt->usableSize-8) ); assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); gap = pPage->cellOffset + 2*pPage->nCell; assert( gap<=65536 ); /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size ** and the reserved space is zero (the usual value for reserved space) ** then the cell content offset of an empty page wants to be 65536. ** However, that integer is too large to be stored in a 2-byte unsigned ** integer, so a value of 0 is used in its place. */ top = get2byte(&data[hdr+5]); assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */ if( gap>top ){ if( top==0 && pPage->pBt->usableSize==65536 ){ top = 65536; }else{ return SQLITE_CORRUPT_BKPT; } } /* If there is enough space between gap and top for one more cell pointer ** array entry offset, and if the freelist is not empty, then search the ** freelist looking for a free slot big enough to satisfy the request. */ testcase( gap+2==top ); testcase( gap+1==top ); testcase( gap==top ); if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){ u8 *pSpace = pageFindSlot(pPage, nByte, &rc); if( pSpace ){ assert( pSpace>=data && (pSpace - data)<65536 ); *pIdx = (int)(pSpace - data); return SQLITE_OK; }else if( rc ){ return rc; } } /* The request could not be fulfilled using a freelist slot. Check ** to see if defragmentation is necessary. */ testcase( gap+2+nByte==top ); if( gap+2+nByte>top ){ assert( pPage->nCell>0 || CORRUPT_DB ); rc = defragmentPage(pPage); if( rc ) return rc; top = get2byteNotZero(&data[hdr+5]); assert( gap+nByte<=top ); } /* Allocate memory from the gap in between the cell pointer array ** and the cell content area. The btreeInitPage() call has already ** validated the freelist. Given that the freelist is valid, there ** is no way that the allocation can extend off the end of the page. ** The assert() below verifies the previous sentence. */ top -= nByte; put2byte(&data[hdr+5], top); assert( top+nByte <= (int)pPage->pBt->usableSize ); *pIdx = top; return SQLITE_OK; } /* ** Return a section of the pPage->aData to the freelist. ** The first byte of the new free block is pPage->aData[iStart] ** and the size of the block is iSize bytes. ** ** Adjacent freeblocks are coalesced. ** ** Note that even though the freeblock list was checked by btreeInitPage(), ** that routine will not detect overlap between cells or freeblocks. Nor ** does it detect cells or freeblocks that encrouch into the reserved bytes ** at the end of the page. So do additional corruption checks inside this ** routine and return SQLITE_CORRUPT if any problems are found. */ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ u16 iPtr; /* Address of ptr to next freeblock */ u16 iFreeBlk; /* Address of the next freeblock */ u8 hdr; /* Page header size. 0 or 100 */ u8 nFrag = 0; /* Reduction in fragmentation */ u16 iOrigSize = iSize; /* Original value of iSize */ u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */ u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ unsigned char *data = pPage->aData; /* Page content */ assert( pPage->pBt!=0 ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( iSize>=4 ); /* Minimum cell size is 4 */ assert( iStart<=iLast ); /* Overwrite deleted information with zeros when the secure_delete ** option is enabled */ if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){ memset(&data[iStart], 0, iSize); } /* The list of freeblocks must be in ascending order. Find the ** spot on the list where iStart should be inserted. */ hdr = pPage->hdrOffset; iPtr = hdr + 1; if( data[iPtr+1]==0 && data[iPtr]==0 ){ iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */ }else{ while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){ if( iFreeBlk<iPtr+4 ){ if( iFreeBlk==0 ) break; return SQLITE_CORRUPT_BKPT; } iPtr = iFreeBlk; } if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT; assert( iFreeBlk>iPtr || iFreeBlk==0 ); /* At this point: ** iFreeBlk: First freeblock after iStart, or zero if none ** iPtr: The address of a pointer to iFreeBlk ** ** Check to see if iFreeBlk should be coalesced onto the end of iStart. */ if( iFreeBlk && iEnd+3>=iFreeBlk ){ nFrag = iFreeBlk - iEnd; if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT; iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT; iSize = iEnd - iStart; iFreeBlk = get2byte(&data[iFreeBlk]); } /* If iPtr is another freeblock (that is, if iPtr is not the freelist ** pointer in the page header) then check to see if iStart should be ** coalesced onto the end of iPtr. */ if( iPtr>hdr+1 ){ int iPtrEnd = iPtr + get2byte(&data[iPtr+2]); if( iPtrEnd+3>=iStart ){ if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT; nFrag += iStart - iPtrEnd; iSize = iEnd - iPtr; iStart = iPtr; } } if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT; data[hdr+7] -= nFrag; } if( iStart==get2byte(&data[hdr+5]) ){ /* The new freeblock is at the beginning of the cell content area, ** so just extend the cell content area rather than create another ** freelist entry */ if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT; put2byte(&data[hdr+1], iFreeBlk); put2byte(&data[hdr+5], iEnd); }else{ /* Insert the new freeblock into the freelist */ put2byte(&data[iPtr], iStart); put2byte(&data[iStart], iFreeBlk); put2byte(&data[iStart+2], iSize); } pPage->nFree += iOrigSize; return SQLITE_OK; } /* ** Decode the flags byte (the first byte of the header) for a page ** and initialize fields of the MemPage structure accordingly. ** ** Only the following combinations are supported. Anything different ** indicates a corrupt database files: ** ** PTF_ZERODATA ** PTF_ZERODATA | PTF_LEAF ** PTF_LEAFDATA | PTF_INTKEY ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF */ static int decodeFlags(MemPage *pPage, int flagByte){ BtShared *pBt; /* A copy of pPage->pBt */ assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); flagByte &= ~PTF_LEAF; pPage->childPtrSize = 4-4*pPage->leaf; pPage->xCellSize = cellSizePtr; pBt = pPage->pBt; if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an ** interior table b-tree page. */ assert( (PTF_LEAFDATA|PTF_INTKEY)==5 ); /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a ** leaf table b-tree page. */ assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 ); pPage->intKey = 1; if( pPage->leaf ){ pPage->intKeyLeaf = 1; pPage->xParseCell = btreeParseCellPtr; }else{ pPage->intKeyLeaf = 0; pPage->xCellSize = cellSizePtrNoPayload; pPage->xParseCell = btreeParseCellPtrNoPayload; } pPage->maxLocal = pBt->maxLeaf; pPage->minLocal = pBt->minLeaf; }else if( flagByte==PTF_ZERODATA ){ /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an ** interior index b-tree page. */ assert( (PTF_ZERODATA)==2 ); /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a ** leaf index b-tree page. */ assert( (PTF_ZERODATA|PTF_LEAF)==10 ); pPage->intKey = 0; pPage->intKeyLeaf = 0; pPage->xParseCell = btreeParseCellPtrIndex; pPage->maxLocal = pBt->maxLocal; pPage->minLocal = pBt->minLocal; }else{ /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is ** an error. */ return SQLITE_CORRUPT_BKPT; } pPage->max1bytePayload = pBt->max1bytePayload; return SQLITE_OK; } /* ** Initialize the auxiliary information for a disk block. ** ** Return SQLITE_OK on success. If we see that the page does ** not contain a well-formed database page, then return ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not ** guarantee that the page is well-formed. It only shows that ** we failed to detect any corruption. */ static int btreeInitPage(MemPage *pPage){ assert( pPage->pBt!=0 ); assert( pPage->pBt->db!=0 ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); if( !pPage->isInit ){ int pc; /* Address of a freeblock within pPage->aData[] */ u8 hdr; /* Offset to beginning of page header */ u8 *data; /* Equal to pPage->aData */ BtShared *pBt; /* The main btree structure */ int usableSize; /* Amount of usable space on each page */ u16 cellOffset; /* Offset from start of page to first cell pointer */ int nFree; /* Number of unused bytes on the page */ int top; /* First byte of the cell content area */ int iCellFirst; /* First allowable cell or freeblock offset */ int iCellLast; /* Last possible cell or freeblock offset */ pBt = pPage->pBt; hdr = pPage->hdrOffset; data = pPage->aData; /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating ** the b-tree page type. */ if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT; assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); pPage->maskPage = (u16)(pBt->pageSize - 1); pPage->nOverflow = 0; usableSize = pBt->usableSize; pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize; pPage->aDataEnd = &data[usableSize]; pPage->aCellIdx = &data[cellOffset]; pPage->aDataOfst = &data[pPage->childPtrSize]; /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates ** the start of the cell content area. A zero value for this integer is ** interpreted as 65536. */ top = get2byteNotZero(&data[hdr+5]); /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the ** number of cells on the page. */ pPage->nCell = get2byte(&data[hdr+3]); if( pPage->nCell>MX_CELL(pBt) ){ /* To many cells for a single page. The page must be corrupt */ return SQLITE_CORRUPT_BKPT; } testcase( pPage->nCell==MX_CELL(pBt) ); /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only ** possible for a root page of a table that contains no rows) then the ** offset to the cell content area will equal the page size minus the ** bytes of reserved space. */ assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB ); /* A malformed database page might cause us to read past the end ** of page when parsing a cell. ** ** The following block of code checks early to see if a cell extends ** past the end of a page boundary and causes SQLITE_CORRUPT to be ** returned if it does. */ iCellFirst = cellOffset + 2*pPage->nCell; iCellLast = usableSize - 4; if( pBt->db->flags & SQLITE_CellSizeCk ){ int i; /* Index into the cell pointer array */ int sz; /* Size of a cell */ if( !pPage->leaf ) iCellLast--; for(i=0; i<pPage->nCell; i++){ pc = get2byteAligned(&data[cellOffset+i*2]); testcase( pc==iCellFirst ); testcase( pc==iCellLast ); if( pc<iCellFirst || pc>iCellLast ){ return SQLITE_CORRUPT_BKPT; } sz = pPage->xCellSize(pPage, &data[pc]); testcase( pc+sz==usableSize ); if( pc+sz>usableSize ){ return SQLITE_CORRUPT_BKPT; } } if( !pPage->leaf ) iCellLast++; } /* Compute the total free space on the page ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the ** start of the first freeblock on the page, or is zero if there are no ** freeblocks. */ pc = get2byte(&data[hdr+1]); nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ if( pc>0 ){ u32 next, size; if( pc<iCellFirst ){ /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will ** always be at least one cell before the first freeblock. */ return SQLITE_CORRUPT_BKPT; } while( 1 ){ if( pc>iCellLast ){ return SQLITE_CORRUPT_BKPT; /* Freeblock off the end of the page */ } next = get2byte(&data[pc]); size = get2byte(&data[pc+2]); nFree = nFree + size; if( next<=pc+size+3 ) break; pc = next; } if( next>0 ){ return SQLITE_CORRUPT_BKPT; /* Freeblock not in ascending order */ } if( pc+size>(unsigned int)usableSize ){ return SQLITE_CORRUPT_BKPT; /* Last freeblock extends past page end */ } } /* At this point, nFree contains the sum of the offset to the start ** of the cell-content area plus the number of free bytes within ** the cell-content area. If this is greater than the usable-size ** of the page, then the page must be corrupted. This check also ** serves to verify that the offset to the start of the cell-content ** area, according to the page header, lies within the page. */ if( nFree>usableSize ){ return SQLITE_CORRUPT_BKPT; } pPage->nFree = (u16)(nFree - iCellFirst); pPage->isInit = 1; } return SQLITE_OK; } /* ** Set up a raw page so that it looks like a database page holding ** no entries. */ static void zeroPage(MemPage *pPage, int flags){ unsigned char *data = pPage->aData; BtShared *pBt = pPage->pBt; u8 hdr = pPage->hdrOffset; u16 first; assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); assert( sqlite3PagerGetData(pPage->pDbPage) == data ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( sqlite3_mutex_held(pBt->mutex) ); if( pBt->btsFlags & BTS_SECURE_DELETE ){ memset(&data[hdr], 0, pBt->usableSize - hdr); } data[hdr] = (char)flags; first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8); memset(&data[hdr+1], 0, 4); data[hdr+7] = 0; put2byte(&data[hdr+5], pBt->usableSize); pPage->nFree = (u16)(pBt->usableSize - first); decodeFlags(pPage, flags); pPage->cellOffset = first; pPage->aDataEnd = &data[pBt->usableSize]; pPage->aCellIdx = &data[first]; pPage->aDataOfst = &data[pPage->childPtrSize]; pPage->nOverflow = 0; assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); pPage->maskPage = (u16)(pBt->pageSize - 1); pPage->nCell = 0; pPage->isInit = 1; } /* ** Convert a DbPage obtained from the pager into a MemPage used by ** the btree layer. */ static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); if( pgno!=pPage->pgno ){ pPage->aData = sqlite3PagerGetData(pDbPage); pPage->pDbPage = pDbPage; pPage->pBt = pBt; pPage->pgno = pgno; pPage->hdrOffset = pgno==1 ? 100 : 0; } assert( pPage->aData==sqlite3PagerGetData(pDbPage) ); return pPage; } /* ** Get a page from the pager. Initialize the MemPage.pBt and ** MemPage.aData elements if needed. See also: btreeGetUnusedPage(). ** ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care ** about the content of the page at this time. So do not go to the disk ** to fetch the content. Just fill in the content with zeros for now. ** If in the future we call sqlite3PagerWrite() on this page, that ** means we have started to be concerned about content and the disk ** read should occur at that point. */ static int btreeGetPage( BtShared *pBt, /* The btree */ Pgno pgno, /* Number of the page to fetch */ MemPage **ppPage, /* Return the page in this parameter */ int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ ){ int rc; DbPage *pDbPage; assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); assert( sqlite3_mutex_held(pBt->mutex) ); rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); if( rc ) return rc; *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); return SQLITE_OK; } /* ** Retrieve a page from the pager cache. If the requested page is not ** already in the pager cache return NULL. Initialize the MemPage.pBt and ** MemPage.aData elements if needed. */ static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ DbPage *pDbPage; assert( sqlite3_mutex_held(pBt->mutex) ); pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); if( pDbPage ){ return btreePageFromDbPage(pDbPage, pgno, pBt); } return 0; } /* ** Return the size of the database file in pages. If there is any kind of ** error, return ((unsigned int)-1). */ static Pgno btreePagecount(BtShared *pBt){ return pBt->nPage; } SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){ assert( sqlite3BtreeHoldsMutex(p) ); assert( ((p->pBt->nPage)&0x8000000)==0 ); return btreePagecount(p->pBt); } /* ** Get a page from the pager and initialize it. ** ** If pCur!=0 then the page is being fetched as part of a moveToChild() ** call. Do additional sanity checking on the page in this case. ** And if the fetch fails, this routine must decrement pCur->iPage. ** ** The page is fetched as read-write unless pCur is not NULL and is ** a read-only cursor. ** ** If an error occurs, then *ppPage is undefined. It ** may remain unchanged, or it may be set to an invalid value. */ static int getAndInitPage( BtShared *pBt, /* The database file */ Pgno pgno, /* Number of the page to get */ MemPage **ppPage, /* Write the page pointer here */ BtCursor *pCur, /* Cursor to receive the page, or NULL */ int bReadOnly /* True for a read-only page */ ){ int rc; DbPage *pDbPage; assert( sqlite3_mutex_held(pBt->mutex) ); assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] ); assert( pCur==0 || bReadOnly==pCur->curPagerFlags ); assert( pCur==0 || pCur->iPage>0 ); if( pgno>btreePagecount(pBt) ){ rc = SQLITE_CORRUPT_BKPT; goto getAndInitPage_error; } rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); if( rc ){ goto getAndInitPage_error; } *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); if( (*ppPage)->isInit==0 ){ btreePageFromDbPage(pDbPage, pgno, pBt); rc = btreeInitPage(*ppPage); if( rc!=SQLITE_OK ){ releasePage(*ppPage); goto getAndInitPage_error; } } assert( (*ppPage)->pgno==pgno ); assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) ); /* If obtaining a child page for a cursor, we must verify that the page is ** compatible with the root page. */ if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){ rc = SQLITE_CORRUPT_BKPT; releasePage(*ppPage); goto getAndInitPage_error; } return SQLITE_OK; getAndInitPage_error: if( pCur ) pCur->iPage--; testcase( pgno==0 ); assert( pgno!=0 || rc==SQLITE_CORRUPT ); return rc; } /* ** Release a MemPage. This should be called once for each prior ** call to btreeGetPage. */ static void releasePageNotNull(MemPage *pPage){ assert( pPage->aData ); assert( pPage->pBt ); assert( pPage->pDbPage!=0 ); assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); sqlite3PagerUnrefNotNull(pPage->pDbPage); } static void releasePage(MemPage *pPage){ if( pPage ) releasePageNotNull(pPage); } /* ** Get an unused page. ** ** This works just like btreeGetPage() with the addition: ** ** * If the page is already in use for some other purpose, immediately ** release it and return an SQLITE_CURRUPT error. ** * Make sure the isInit flag is clear */ static int btreeGetUnusedPage( BtShared *pBt, /* The btree */ Pgno pgno, /* Number of the page to fetch */ MemPage **ppPage, /* Return the page in this parameter */ int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ ){ int rc = btreeGetPage(pBt, pgno, ppPage, flags); if( rc==SQLITE_OK ){ if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ releasePage(*ppPage); *ppPage = 0; return SQLITE_CORRUPT_BKPT; } (*ppPage)->isInit = 0; }else{ *ppPage = 0; } return rc; } /* ** During a rollback, when the pager reloads information into the cache ** so that the cache is restored to its original state at the start of ** the transaction, for each page restored this routine is called. ** ** This routine needs to reset the extra data section at the end of the ** page to agree with the restored data. */ static void pageReinit(DbPage *pData){ MemPage *pPage; pPage = (MemPage *)sqlite3PagerGetExtra(pData); assert( sqlite3PagerPageRefcount(pData)>0 ); if( pPage->isInit ){ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); pPage->isInit = 0; if( sqlite3PagerPageRefcount(pData)>1 ){ /* pPage might not be a btree page; it might be an overflow page ** or ptrmap page or a free page. In those cases, the following ** call to btreeInitPage() will likely return SQLITE_CORRUPT. ** But no harm is done by this. And it is very important that ** btreeInitPage() be called on every btree page so we make ** the call for every page that comes in for re-initing. */ btreeInitPage(pPage); } } } /* ** Invoke the busy handler for a btree. */ static int btreeInvokeBusyHandler(void *pArg){ BtShared *pBt = (BtShared*)pArg; assert( pBt->db ); assert( sqlite3_mutex_held(pBt->db->mutex) ); return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); } /* ** Open a database file. ** ** zFilename is the name of the database file. If zFilename is NULL ** then an ephemeral database is created. The ephemeral database might ** be exclusively in memory, or it might use a disk-based memory cache. ** Either way, the ephemeral database will be automatically deleted ** when sqlite3BtreeClose() is called. ** ** If zFilename is ":memory:" then an in-memory database is created ** that is automatically destroyed when it is closed. ** ** The "flags" parameter is a bitmask that might contain bits like ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. ** ** If the database is already opened in the same database connection ** and we are in shared cache mode, then the open will fail with an ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared ** objects in the same database connection since doing so will lead ** to problems with locking. */ SQLITE_PRIVATE int sqlite3BtreeOpen( sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ const char *zFilename, /* Name of the file containing the BTree database */ sqlite3 *db, /* Associated database handle */ Btree **ppBtree, /* Pointer to new Btree object written here */ int flags, /* Options */ int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ ){ BtShared *pBt = 0; /* Shared part of btree structure */ Btree *p; /* Handle to return */ sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ int rc = SQLITE_OK; /* Result code from this function */ u8 nReserve; /* Byte of unused space on each page */ unsigned char zDbHeader[100]; /* Database header content */ /* True if opening an ephemeral, temporary database */ const int isTempDb = zFilename==0 || zFilename[0]==0; /* Set the variable isMemdb to true for an in-memory database, or ** false for a file-based database. */ #ifdef SQLITE_OMIT_MEMORYDB const int isMemdb = 0; #else const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) || (isTempDb && sqlite3TempInMemory(db)) || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; #endif assert( db!=0 ); assert( pVfs!=0 ); assert( sqlite3_mutex_held(db->mutex) ); assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ assert( (flags & BTREE_SINGLE)==0 || isTempDb ); if( isMemdb ){ flags |= BTREE_MEMORY; } if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; } p = sqlite3MallocZero(sizeof(Btree)); if( !p ){ return SQLITE_NOMEM_BKPT; } p->inTrans = TRANS_NONE; p->db = db; #ifndef SQLITE_OMIT_SHARED_CACHE p->lock.pBtree = p; p->lock.iTable = 1; #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) /* ** If this Btree is a candidate for shared cache, try to find an ** existing BtShared object that we can share with */ if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ int nFilename = sqlite3Strlen30(zFilename)+1; int nFullPathname = pVfs->mxPathname+1; char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename)); MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) p->sharable = 1; if( !zFullPathname ){ sqlite3_free(p); return SQLITE_NOMEM_BKPT; } if( isMemdb ){ memcpy(zFullPathname, zFilename, nFilename); }else{ rc = sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname); if( rc ){ sqlite3_free(zFullPathname); sqlite3_free(p); return rc; } } #if SQLITE_THREADSAFE mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); sqlite3_mutex_enter(mutexOpen); mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); sqlite3_mutex_enter(mutexShared); #endif for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ assert( pBt->nRef>0 ); if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) && sqlite3PagerVfs(pBt->pPager)==pVfs ){ int iDb; for(iDb=db->nDb-1; iDb>=0; iDb--){ Btree *pExisting = db->aDb[iDb].pBt; if( pExisting && pExisting->pBt==pBt ){ sqlite3_mutex_leave(mutexShared); sqlite3_mutex_leave(mutexOpen); sqlite3_free(zFullPathname); sqlite3_free(p); return SQLITE_CONSTRAINT; } } p->pBt = pBt; pBt->nRef++; break; } } sqlite3_mutex_leave(mutexShared); sqlite3_free(zFullPathname); } #ifdef SQLITE_DEBUG else{ /* In debug mode, we mark all persistent databases as sharable ** even when they are not. This exercises the locking code and ** gives more opportunity for asserts(sqlite3_mutex_held()) ** statements to find locking problems. */ p->sharable = 1; } #endif } #endif if( pBt==0 ){ /* ** The following asserts make sure that structures used by the btree are ** the right size. This is to guard against size changes that result ** when compiling on a different architecture. */ assert( sizeof(i64)==8 ); assert( sizeof(u64)==8 ); assert( sizeof(u32)==4 ); assert( sizeof(u16)==2 ); assert( sizeof(Pgno)==4 ); pBt = sqlite3MallocZero( sizeof(*pBt) ); if( pBt==0 ){ rc = SQLITE_NOMEM_BKPT; goto btree_open_out; } rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, sizeof(MemPage), flags, vfsFlags, pageReinit); if( rc==SQLITE_OK ){ sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); } if( rc!=SQLITE_OK ){ goto btree_open_out; } pBt->openFlags = (u8)flags; pBt->db = db; sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); p->pBt = pBt; pBt->pCursor = 0; pBt->pPage1 = 0; if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; #ifdef SQLITE_SECURE_DELETE pBt->btsFlags |= BTS_SECURE_DELETE; #endif /* EVIDENCE-OF: R-51873-39618 The page size for a database file is ** determined by the 2-byte integer located at an offset of 16 bytes from ** the beginning of the database file. */ pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ pBt->pageSize = 0; #ifndef SQLITE_OMIT_AUTOVACUUM /* If the magic name ":memory:" will create an in-memory database, then ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a ** regular file-name. In this case the auto-vacuum applies as per normal. */ if( zFilename && !isMemdb ){ pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); } #endif nReserve = 0; }else{ /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is ** determined by the one-byte unsigned integer found at an offset of 20 ** into the database file header. */ nReserve = zDbHeader[20]; pBt->btsFlags |= BTS_PAGESIZE_FIXED; #ifndef SQLITE_OMIT_AUTOVACUUM pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); #endif } rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); if( rc ) goto btree_open_out; pBt->usableSize = pBt->pageSize - nReserve; assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) /* Add the new BtShared object to the linked list sharable BtShareds. */ pBt->nRef = 1; if( p->sharable ){ MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); if( pBt->mutex==0 ){ rc = SQLITE_NOMEM_BKPT; goto btree_open_out; } } sqlite3_mutex_enter(mutexShared); pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; sqlite3_mutex_leave(mutexShared); } #endif } #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) /* If the new Btree uses a sharable pBtShared, then link the new ** Btree into the list of all sharable Btrees for the same connection. ** The list is kept in ascending order by pBt address. */ if( p->sharable ){ int i; Btree *pSib; for(i=0; i<db->nDb; i++){ if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ while( pSib->pPrev ){ pSib = pSib->pPrev; } if( (uptr)p->pBt<(uptr)pSib->pBt ){ p->pNext = pSib; p->pPrev = 0; pSib->pPrev = p; }else{ while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){ pSib = pSib->pNext; } p->pNext = pSib->pNext; p->pPrev = pSib; if( p->pNext ){ p->pNext->pPrev = p; } pSib->pNext = p; } break; } } } #endif *ppBtree = p; btree_open_out: if( rc!=SQLITE_OK ){ if( pBt && pBt->pPager ){ sqlite3PagerClose(pBt->pPager, 0); } sqlite3_free(pBt); sqlite3_free(p); *ppBtree = 0; }else{ sqlite3_file *pFile; /* If the B-Tree was successfully opened, set the pager-cache size to the ** default value. Except, when opening on an existing shared pager-cache, ** do not change the pager-cache size. */ if( sqlite3BtreeSchema(p, 0, 0)==0 ){ sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); } pFile = sqlite3PagerFile(pBt->pPager); if( pFile->pMethods ){ sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db); } } if( mutexOpen ){ assert( sqlite3_mutex_held(mutexOpen) ); sqlite3_mutex_leave(mutexOpen); } assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 ); return rc; } /* ** Decrement the BtShared.nRef counter. When it reaches zero, ** remove the BtShared structure from the sharing list. Return ** true if the BtShared.nRef counter reaches zero and return ** false if it is still positive. */ static int removeFromSharingList(BtShared *pBt){ #ifndef SQLITE_OMIT_SHARED_CACHE MUTEX_LOGIC( sqlite3_mutex *pMaster; ) BtShared *pList; int removed = 0; assert( sqlite3_mutex_notheld(pBt->mutex) ); MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) sqlite3_mutex_enter(pMaster); pBt->nRef--; if( pBt->nRef<=0 ){ if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; }else{ pList = GLOBAL(BtShared*,sqlite3SharedCacheList); while( ALWAYS(pList) && pList->pNext!=pBt ){ pList=pList->pNext; } if( ALWAYS(pList) ){ pList->pNext = pBt->pNext; } } if( SQLITE_THREADSAFE ){ sqlite3_mutex_free(pBt->mutex); } removed = 1; } sqlite3_mutex_leave(pMaster); return removed; #else return 1; #endif } /* ** Make sure pBt->pTmpSpace points to an allocation of ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child ** pointer. */ static void allocateTempSpace(BtShared *pBt){ if( !pBt->pTmpSpace ){ pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); /* One of the uses of pBt->pTmpSpace is to format cells before ** inserting them into a leaf page (function fillInCell()). If ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes ** by the various routines that manipulate binary cells. Which ** can mean that fillInCell() only initializes the first 2 or 3 ** bytes of pTmpSpace, but that the first 4 bytes are copied from ** it into a database page. This is not actually a problem, but it ** does cause a valgrind error when the 1 or 2 bytes of unitialized ** data is passed to system call write(). So to avoid this error, ** zero the first 4 bytes of temp space here. ** ** Also: Provide four bytes of initialized space before the ** beginning of pTmpSpace as an area available to prepend the ** left-child pointer to the beginning of a cell. */ if( pBt->pTmpSpace ){ memset(pBt->pTmpSpace, 0, 8); pBt->pTmpSpace += 4; } } } /* ** Free the pBt->pTmpSpace allocation */ static void freeTempSpace(BtShared *pBt){ if( pBt->pTmpSpace ){ pBt->pTmpSpace -= 4; sqlite3PageFree(pBt->pTmpSpace); pBt->pTmpSpace = 0; } } /* ** Close an open database and invalidate all cursors. */ SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ BtShared *pBt = p->pBt; BtCursor *pCur; /* Close all cursors opened via this handle. */ assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); pCur = pBt->pCursor; while( pCur ){ BtCursor *pTmp = pCur; pCur = pCur->pNext; if( pTmp->pBtree==p ){ sqlite3BtreeCloseCursor(pTmp); } } /* Rollback any active transaction and free the handle structure. ** The call to sqlite3BtreeRollback() drops any table-locks held by ** this handle. */ sqlite3BtreeRollback(p, SQLITE_OK, 0); sqlite3BtreeLeave(p); /* If there are still other outstanding references to the shared-btree ** structure, return now. The remainder of this procedure cleans ** up the shared-btree. */ assert( p->wantToLock==0 && p->locked==0 ); if( !p->sharable || removeFromSharingList(pBt) ){ /* The pBt is no longer on the sharing list, so we can access ** it without having to hold the mutex. ** ** Clean out and delete the BtShared object. */ assert( !pBt->pCursor ); sqlite3PagerClose(pBt->pPager, p->db); if( pBt->xFreeSchema && pBt->pSchema ){ pBt->xFreeSchema(pBt->pSchema); } sqlite3DbFree(0, pBt->pSchema); freeTempSpace(pBt); sqlite3_free(pBt); } #ifndef SQLITE_OMIT_SHARED_CACHE assert( p->wantToLock==0 ); assert( p->locked==0 ); if( p->pPrev ) p->pPrev->pNext = p->pNext; if( p->pNext ) p->pNext->pPrev = p->pPrev; #endif sqlite3_free(p); return SQLITE_OK; } /* ** Change the "soft" limit on the number of pages in the cache. ** Unused and unmodified pages will be recycled when the number of ** pages in the cache exceeds this soft limit. But the size of the ** cache is allowed to grow larger than this limit if it contains ** dirty pages or pages still in active use. */ SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ BtShared *pBt = p->pBt; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); sqlite3PagerSetCachesize(pBt->pPager, mxPage); sqlite3BtreeLeave(p); return SQLITE_OK; } /* ** Change the "spill" limit on the number of pages in the cache. ** If the number of pages exceeds this limit during a write transaction, ** the pager might attempt to "spill" pages to the journal early in ** order to free up memory. ** ** The value returned is the current spill size. If zero is passed ** as an argument, no changes are made to the spill size setting, so ** using mxPage of 0 is a way to query the current spill size. */ SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){ BtShared *pBt = p->pBt; int res; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage); sqlite3BtreeLeave(p); return res; } #if SQLITE_MAX_MMAP_SIZE>0 /* ** Change the limit on the amount of the database file that may be ** memory mapped. */ SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ BtShared *pBt = p->pBt; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); sqlite3BtreeLeave(p); return SQLITE_OK; } #endif /* SQLITE_MAX_MMAP_SIZE>0 */ /* ** Change the way data is synced to disk in order to increase or decrease ** how well the database resists damage due to OS crashes and power ** failures. Level 1 is the same as asynchronous (no syncs() occur and ** there is a high probability of damage) Level 2 is the default. There ** is a very low but non-zero probability of damage. Level 3 reduces the ** probability of damage to near zero but with a write performance reduction. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags( Btree *p, /* The btree to set the safety level on */ unsigned pgFlags /* Various PAGER_* flags */ ){ BtShared *pBt = p->pBt; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); sqlite3PagerSetFlags(pBt->pPager, pgFlags); sqlite3BtreeLeave(p); return SQLITE_OK; } #endif /* ** Change the default pages size and the number of reserved bytes per page. ** Or, if the page size has already been fixed, return SQLITE_READONLY ** without changing anything. ** ** The page size must be a power of 2 between 512 and 65536. If the page ** size supplied does not meet this constraint then the page size is not ** changed. ** ** Page sizes are constrained to be a power of two so that the region ** of the database file used for locking (beginning at PENDING_BYTE, ** the first byte past the 1GB boundary, 0x40000000) needs to occur ** at the beginning of a page. ** ** If parameter nReserve is less than zero, then the number of reserved ** bytes per page is left unchanged. ** ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size ** and autovacuum mode can no longer be changed. */ SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ int rc = SQLITE_OK; BtShared *pBt = p->pBt; assert( nReserve>=-1 && nReserve<=255 ); sqlite3BtreeEnter(p); #if SQLITE_HAS_CODEC if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve; #endif if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ sqlite3BtreeLeave(p); return SQLITE_READONLY; } if( nReserve<0 ){ nReserve = pBt->pageSize - pBt->usableSize; } assert( nReserve>=0 && nReserve<=255 ); if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && ((pageSize-1)&pageSize)==0 ){ assert( (pageSize & 7)==0 ); assert( !pBt->pCursor ); pBt->pageSize = (u32)pageSize; freeTempSpace(pBt); } rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); pBt->usableSize = pBt->pageSize - (u16)nReserve; if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; sqlite3BtreeLeave(p); return rc; } /* ** Return the currently defined page size */ SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){ return p->pBt->pageSize; } /* ** This function is similar to sqlite3BtreeGetReserve(), except that it ** may only be called if it is guaranteed that the b-tree mutex is already ** held. ** ** This is useful in one special case in the backup API code where it is ** known that the shared b-tree mutex is held, but the mutex on the ** database handle that owns *p is not. In this case if sqlite3BtreeEnter() ** were to be called, it might collide with some other operation on the ** database handle that owns *p, causing undefined behavior. */ SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){ int n; assert( sqlite3_mutex_held(p->pBt->mutex) ); n = p->pBt->pageSize - p->pBt->usableSize; return n; } /* ** Return the number of bytes of space at the end of every page that ** are intentually left unused. This is the "reserved" space that is ** sometimes used by extensions. ** ** If SQLITE_HAS_MUTEX is defined then the number returned is the ** greater of the current reserved space and the maximum requested ** reserve space. */ SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){ int n; sqlite3BtreeEnter(p); n = sqlite3BtreeGetReserveNoMutex(p); #ifdef SQLITE_HAS_CODEC if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve; #endif sqlite3BtreeLeave(p); return n; } /* ** Set the maximum page count for a database if mxPage is positive. ** No changes are made if mxPage is 0 or negative. ** Regardless of the value of mxPage, return the maximum page count. */ SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ int n; sqlite3BtreeEnter(p); n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); sqlite3BtreeLeave(p); return n; } /* ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1, ** then make no changes. Always return the value of the BTS_SECURE_DELETE ** setting after the change. */ SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ int b; if( p==0 ) return 0; sqlite3BtreeEnter(p); if( newFlag>=0 ){ p->pBt->btsFlags &= ~BTS_SECURE_DELETE; if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE; } b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0; sqlite3BtreeLeave(p); return b; } /* ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it ** is disabled. The default value for the auto-vacuum property is ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. */ SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ #ifdef SQLITE_OMIT_AUTOVACUUM return SQLITE_READONLY; #else BtShared *pBt = p->pBt; int rc = SQLITE_OK; u8 av = (u8)autoVacuum; sqlite3BtreeEnter(p); if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ rc = SQLITE_READONLY; }else{ pBt->autoVacuum = av ?1:0; pBt->incrVacuum = av==2 ?1:0; } sqlite3BtreeLeave(p); return rc; #endif } /* ** Return the value of the 'auto-vacuum' property. If auto-vacuum is ** enabled 1 is returned. Otherwise 0. */ SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){ #ifdef SQLITE_OMIT_AUTOVACUUM return BTREE_AUTOVACUUM_NONE; #else int rc; sqlite3BtreeEnter(p); rc = ( (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: BTREE_AUTOVACUUM_INCR ); sqlite3BtreeLeave(p); return rc; #endif } /* ** Get a reference to pPage1 of the database file. This will ** also acquire a readlock on that file. ** ** SQLITE_OK is returned on success. If the file is not a ** well-formed database file, then SQLITE_CORRUPT is returned. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM ** is returned if we run out of memory. */ static int lockBtree(BtShared *pBt){ int rc; /* Result code from subfunctions */ MemPage *pPage1; /* Page 1 of the database file */ int nPage; /* Number of pages in the database */ int nPageFile = 0; /* Number of pages in the database file */ int nPageHeader; /* Number of pages in the database according to hdr */ assert( sqlite3_mutex_held(pBt->mutex) ); assert( pBt->pPage1==0 ); rc = sqlite3PagerSharedLock(pBt->pPager); if( rc!=SQLITE_OK ) return rc; rc = btreeGetPage(pBt, 1, &pPage1, 0); if( rc!=SQLITE_OK ) return rc; /* Do some checking to help insure the file we opened really is ** a valid database file. */ nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); sqlite3PagerPagecount(pBt->pPager, &nPageFile); if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ nPage = nPageFile; } if( nPage>0 ){ u32 pageSize; u32 usableSize; u8 *page1 = pPage1->aData; rc = SQLITE_NOTADB; /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d ** 61 74 20 33 00. */ if( memcmp(page1, zMagicHeader, 16)!=0 ){ goto page1_init_failed; } #ifdef SQLITE_OMIT_WAL if( page1[18]>1 ){ pBt->btsFlags |= BTS_READ_ONLY; } if( page1[19]>1 ){ goto page1_init_failed; } #else if( page1[18]>2 ){ pBt->btsFlags |= BTS_READ_ONLY; } if( page1[19]>2 ){ goto page1_init_failed; } /* If the write version is set to 2, this database should be accessed ** in WAL mode. If the log is not already open, open it now. Then ** return SQLITE_OK and return without populating BtShared.pPage1. ** The caller detects this and calls this function again. This is ** required as the version of page 1 currently in the page1 buffer ** may not be the latest version - there may be a newer one in the log ** file. */ if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ int isOpen = 0; rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); if( rc!=SQLITE_OK ){ goto page1_init_failed; }else{ #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS sqlite3 *db; Db *pDb; if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){ while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; } if( pDb->bSyncSet==0 && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1 ){ pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1; sqlite3PagerSetFlags(pBt->pPager, pDb->safety_level | (db->flags & PAGER_FLAGS_MASK)); } } #endif if( isOpen==0 ){ releasePage(pPage1); return SQLITE_OK; } } rc = SQLITE_NOTADB; } #endif /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload ** fractions and the leaf payload fraction values must be 64, 32, and 32. ** ** The original design allowed these amounts to vary, but as of ** version 3.6.0, we require them to be fixed. */ if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ goto page1_init_failed; } /* EVIDENCE-OF: R-51873-39618 The page size for a database file is ** determined by the 2-byte integer located at an offset of 16 bytes from ** the beginning of the database file. */ pageSize = (page1[16]<<8) | (page1[17]<<16); /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two ** between 512 and 65536 inclusive. */ if( ((pageSize-1)&pageSize)!=0 || pageSize>SQLITE_MAX_PAGE_SIZE || pageSize<=256 ){ goto page1_init_failed; } assert( (pageSize & 7)==0 ); /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte ** integer at offset 20 is the number of bytes of space at the end of ** each page to reserve for extensions. ** ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is ** determined by the one-byte unsigned integer found at an offset of 20 ** into the database file header. */ usableSize = pageSize - page1[20]; if( (u32)pageSize!=pBt->pageSize ){ /* After reading the first page of the database assuming a page size ** of BtShared.pageSize, we have discovered that the page-size is ** actually pageSize. Unlock the database, leave pBt->pPage1 at ** zero and return SQLITE_OK. The caller will call this function ** again with the correct page-size. */ releasePage(pPage1); pBt->usableSize = usableSize; pBt->pageSize = pageSize; freeTempSpace(pBt); rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, pageSize-usableSize); return rc; } if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){ rc = SQLITE_CORRUPT_BKPT; goto page1_init_failed; } /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to ** be less than 480. In other words, if the page size is 512, then the ** reserved space size cannot exceed 32. */ if( usableSize<480 ){ goto page1_init_failed; } pBt->pageSize = pageSize; pBt->usableSize = usableSize; #ifndef SQLITE_OMIT_AUTOVACUUM pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); #endif } /* maxLocal is the maximum amount of payload to store locally for ** a cell. Make sure it is small enough so that at least minFanout ** cells can will fit on one page. We assume a 10-byte page header. ** Besides the payload, the cell must store: ** 2-byte pointer to the cell ** 4-byte child pointer ** 9-byte nKey value ** 4-byte nData value ** 4-byte overflow page pointer ** So a cell consists of a 2-byte pointer, a header which is as much as ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow ** page pointer. */ pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); pBt->maxLeaf = (u16)(pBt->usableSize - 35); pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); if( pBt->maxLocal>127 ){ pBt->max1bytePayload = 127; }else{ pBt->max1bytePayload = (u8)pBt->maxLocal; } assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); pBt->pPage1 = pPage1; pBt->nPage = nPage; return SQLITE_OK; page1_init_failed: releasePage(pPage1); pBt->pPage1 = 0; return rc; } #ifndef NDEBUG /* ** Return the number of cursors open on pBt. This is for use ** in assert() expressions, so it is only compiled if NDEBUG is not ** defined. ** ** Only write cursors are counted if wrOnly is true. If wrOnly is ** false then all cursors are counted. ** ** For the purposes of this routine, a cursor is any cursor that ** is capable of reading or writing to the database. Cursors that ** have been tripped into the CURSOR_FAULT state are not counted. */ static int countValidCursors(BtShared *pBt, int wrOnly){ BtCursor *pCur; int r = 0; for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0) && pCur->eState!=CURSOR_FAULT ) r++; } return r; } #endif /* ** If there are no outstanding cursors and we are not in the middle ** of a transaction but there is a read lock on the database, then ** this routine unrefs the first page of the database file which ** has the effect of releasing the read lock. ** ** If there is a transaction in progress, this routine is a no-op. */ static void unlockBtreeIfUnused(BtShared *pBt){ assert( sqlite3_mutex_held(pBt->mutex) ); assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ MemPage *pPage1 = pBt->pPage1; assert( pPage1->aData ); assert( sqlite3PagerRefcount(pBt->pPager)==1 ); pBt->pPage1 = 0; releasePageNotNull(pPage1); } } /* ** If pBt points to an empty file then convert that empty file ** into a new empty database by initializing the first page of ** the database. */ static int newDatabase(BtShared *pBt){ MemPage *pP1; unsigned char *data; int rc; assert( sqlite3_mutex_held(pBt->mutex) ); if( pBt->nPage>0 ){ return SQLITE_OK; } pP1 = pBt->pPage1; assert( pP1!=0 ); data = pP1->aData; rc = sqlite3PagerWrite(pP1->pDbPage); if( rc ) return rc; memcpy(data, zMagicHeader, sizeof(zMagicHeader)); assert( sizeof(zMagicHeader)==16 ); data[16] = (u8)((pBt->pageSize>>8)&0xff); data[17] = (u8)((pBt->pageSize>>16)&0xff); data[18] = 1; data[19] = 1; assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); data[20] = (u8)(pBt->pageSize - pBt->usableSize); data[21] = 64; data[22] = 32; data[23] = 32; memset(&data[24], 0, 100-24); zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); pBt->btsFlags |= BTS_PAGESIZE_FIXED; #ifndef SQLITE_OMIT_AUTOVACUUM assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); put4byte(&data[36 + 4*4], pBt->autoVacuum); put4byte(&data[36 + 7*4], pBt->incrVacuum); #endif pBt->nPage = 1; data[31] = 1; return SQLITE_OK; } /* ** Initialize the first page of the database file (creating a database ** consisting of a single page and no schema objects). Return SQLITE_OK ** if successful, or an SQLite error code otherwise. */ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){ int rc; sqlite3BtreeEnter(p); p->pBt->nPage = 0; rc = newDatabase(p->pBt); sqlite3BtreeLeave(p); return rc; } /* ** Attempt to start a new transaction. A write-transaction ** is started if the second argument is nonzero, otherwise a read- ** transaction. If the second argument is 2 or more and exclusive ** transaction is started, meaning that no other process is allowed ** to access the database. A preexisting transaction may not be ** upgraded to exclusive by calling this routine a second time - the ** exclusivity flag only works for a new transaction. ** ** A write-transaction must be started before attempting any ** changes to the database. None of the following routines ** will work unless a transaction is started first: ** ** sqlite3BtreeCreateTable() ** sqlite3BtreeCreateIndex() ** sqlite3BtreeClearTable() ** sqlite3BtreeDropTable() ** sqlite3BtreeInsert() ** sqlite3BtreeDelete() ** sqlite3BtreeUpdateMeta() ** ** If an initial attempt to acquire the lock fails because of lock contention ** and the database was previously unlocked, then invoke the busy handler ** if there is one. But if there was previously a read-lock, do not ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is ** returned when there is already a read-lock in order to avoid a deadlock. ** ** Suppose there are two processes A and B. A has a read lock and B has ** a reserved lock. B tries to promote to exclusive but is blocked because ** of A's read lock. A tries to promote to reserved but is blocked by B. ** One or the other of the two processes must give way or there can be ** no progress. By returning SQLITE_BUSY and not invoking the busy callback ** when A already has a read lock, we encourage A to give up and let B ** proceed. */ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ BtShared *pBt = p->pBt; int rc = SQLITE_OK; sqlite3BtreeEnter(p); btreeIntegrity(p); /* If the btree is already in a write-transaction, or it ** is already in a read-transaction and a read-transaction ** is requested, this is a no-op. */ if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ goto trans_begun; } assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); /* Write transactions are not possible on a read-only database */ if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ rc = SQLITE_READONLY; goto trans_begun; } #ifndef SQLITE_OMIT_SHARED_CACHE { sqlite3 *pBlock = 0; /* If another database handle has already opened a write transaction ** on this shared-btree structure and a second write transaction is ** requested, return SQLITE_LOCKED. */ if( (wrflag && pBt->inTransaction==TRANS_WRITE) || (pBt->btsFlags & BTS_PENDING)!=0 ){ pBlock = pBt->pWriter->db; }else if( wrflag>1 ){ BtLock *pIter; for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ if( pIter->pBtree!=p ){ pBlock = pIter->pBtree->db; break; } } } if( pBlock ){ sqlite3ConnectionBlocked(p->db, pBlock); rc = SQLITE_LOCKED_SHAREDCACHE; goto trans_begun; } } #endif /* Any read-only or read-write transaction implies a read-lock on ** page 1. So if some other shared-cache client already has a write-lock ** on page 1, the transaction cannot be opened. */ rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); if( SQLITE_OK!=rc ) goto trans_begun; pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; do { /* Call lockBtree() until either pBt->pPage1 is populated or ** lockBtree() returns something other than SQLITE_OK. lockBtree() ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after ** reading page 1 it discovers that the page-size of the database ** file is not pBt->pageSize. In this case lockBtree() will update ** pBt->pageSize to the page-size of the file on disk. */ while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); if( rc==SQLITE_OK && wrflag ){ if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ rc = SQLITE_READONLY; }else{ rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); if( rc==SQLITE_OK ){ rc = newDatabase(pBt); } } } if( rc!=SQLITE_OK ){ unlockBtreeIfUnused(pBt); } }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && btreeInvokeBusyHandler(pBt) ); if( rc==SQLITE_OK ){ if( p->inTrans==TRANS_NONE ){ pBt->nTransaction++; #ifndef SQLITE_OMIT_SHARED_CACHE if( p->sharable ){ assert( p->lock.pBtree==p && p->lock.iTable==1 ); p->lock.eLock = READ_LOCK; p->lock.pNext = pBt->pLock; pBt->pLock = &p->lock; } #endif } p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); if( p->inTrans>pBt->inTransaction ){ pBt->inTransaction = p->inTrans; } if( wrflag ){ MemPage *pPage1 = pBt->pPage1; #ifndef SQLITE_OMIT_SHARED_CACHE assert( !pBt->pWriter ); pBt->pWriter = p; pBt->btsFlags &= ~BTS_EXCLUSIVE; if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; #endif /* If the db-size header field is incorrect (as it may be if an old ** client has been writing the database file), update it now. Doing ** this sooner rather than later means the database size can safely ** re-read the database size from page 1 if a savepoint or transaction ** rollback occurs within the transaction. */ if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ rc = sqlite3PagerWrite(pPage1->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pPage1->aData[28], pBt->nPage); } } } } trans_begun: if( rc==SQLITE_OK && wrflag ){ /* This call makes sure that the pager has the correct number of ** open savepoints. If the second parameter is greater than 0 and ** the sub-journal is not already open, then it will be opened here. */ rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint); } btreeIntegrity(p); sqlite3BtreeLeave(p); return rc; } #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Set the pointer-map entries for all children of page pPage. Also, if ** pPage contains cells that point to overflow pages, set the pointer ** map entries for the overflow pages as well. */ static int setChildPtrmaps(MemPage *pPage){ int i; /* Counter variable */ int nCell; /* Number of cells in page pPage */ int rc; /* Return code */ BtShared *pBt = pPage->pBt; Pgno pgno = pPage->pgno; assert( sqlite3_mutex_held(pPage->pBt->mutex) ); rc = btreeInitPage(pPage); if( rc!=SQLITE_OK ) return rc; nCell = pPage->nCell; for(i=0; i<nCell; i++){ u8 *pCell = findCell(pPage, i); ptrmapPutOvflPtr(pPage, pCell, &rc); if( !pPage->leaf ){ Pgno childPgno = get4byte(pCell); ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); } } if( !pPage->leaf ){ Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); } return rc; } /* ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so ** that it points to iTo. Parameter eType describes the type of pointer to ** be modified, as follows: ** ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child ** page of pPage. ** ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow ** page pointed to by one of the cells on pPage. ** ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next ** overflow page in the list. */ static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); if( eType==PTRMAP_OVERFLOW2 ){ /* The pointer is always the first 4 bytes of the page in this case. */ if( get4byte(pPage->aData)!=iFrom ){ return SQLITE_CORRUPT_BKPT; } put4byte(pPage->aData, iTo); }else{ int i; int nCell; int rc; rc = btreeInitPage(pPage); if( rc ) return rc; nCell = pPage->nCell; for(i=0; i<nCell; i++){ u8 *pCell = findCell(pPage, i); if( eType==PTRMAP_OVERFLOW1 ){ CellInfo info; pPage->xParseCell(pPage, pCell, &info); if( info.nLocal<info.nPayload ){ if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){ return SQLITE_CORRUPT_BKPT; } if( iFrom==get4byte(pCell+info.nSize-4) ){ put4byte(pCell+info.nSize-4, iTo); break; } } }else{ if( get4byte(pCell)==iFrom ){ put4byte(pCell, iTo); break; } } } if( i==nCell ){ if( eType!=PTRMAP_BTREE || get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ return SQLITE_CORRUPT_BKPT; } put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); } } return SQLITE_OK; } /* ** Move the open database page pDbPage to location iFreePage in the ** database. The pDbPage reference remains valid. ** ** The isCommit flag indicates that there is no need to remember that ** the journal needs to be sync()ed before database page pDbPage->pgno ** can be written to. The caller has already promised not to write to that ** page. */ static int relocatePage( BtShared *pBt, /* Btree */ MemPage *pDbPage, /* Open page to move */ u8 eType, /* Pointer map 'type' entry for pDbPage */ Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ Pgno iFreePage, /* The location to move pDbPage to */ int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ ){ MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ Pgno iDbPage = pDbPage->pgno; Pager *pPager = pBt->pPager; int rc; assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); assert( sqlite3_mutex_held(pBt->mutex) ); assert( pDbPage->pBt==pBt ); /* Move page iDbPage from its current location to page number iFreePage */ TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", iDbPage, iFreePage, iPtrPage, eType)); rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); if( rc!=SQLITE_OK ){ return rc; } pDbPage->pgno = iFreePage; /* If pDbPage was a btree-page, then it may have child pages and/or cells ** that point to overflow pages. The pointer map entries for all these ** pages need to be changed. ** ** If pDbPage is an overflow page, then the first 4 bytes may store a ** pointer to a subsequent overflow page. If this is the case, then ** the pointer map needs to be updated for the subsequent overflow page. */ if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ rc = setChildPtrmaps(pDbPage); if( rc!=SQLITE_OK ){ return rc; } }else{ Pgno nextOvfl = get4byte(pDbPage->aData); if( nextOvfl!=0 ){ ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc); if( rc!=SQLITE_OK ){ return rc; } } } /* Fix the database pointer on page iPtrPage that pointed at iDbPage so ** that it points at iFreePage. Also fix the pointer map entry for ** iPtrPage. */ if( eType!=PTRMAP_ROOTPAGE ){ rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); if( rc!=SQLITE_OK ){ return rc; } rc = sqlite3PagerWrite(pPtrPage->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pPtrPage); return rc; } rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); releasePage(pPtrPage); if( rc==SQLITE_OK ){ ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); } } return rc; } /* Forward declaration required by incrVacuumStep(). */ static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); /* ** Perform a single step of an incremental-vacuum. If successful, return ** SQLITE_OK. If there is no work to do (and therefore no point in ** calling this function again), return SQLITE_DONE. Or, if an error ** occurs, return some other error code. ** ** More specifically, this function attempts to re-organize the database so ** that the last page of the file currently in use is no longer in use. ** ** Parameter nFin is the number of pages that this database would contain ** were this function called until it returns SQLITE_DONE. ** ** If the bCommit parameter is non-zero, this function assumes that the ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE ** or an error. bCommit is passed true for an auto-vacuum-on-commit ** operation, or false for an incremental vacuum. */ static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ Pgno nFreeList; /* Number of pages still on the free-list */ int rc; assert( sqlite3_mutex_held(pBt->mutex) ); assert( iLastPg>nFin ); if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ u8 eType; Pgno iPtrPage; nFreeList = get4byte(&pBt->pPage1->aData[36]); if( nFreeList==0 ){ return SQLITE_DONE; } rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); if( rc!=SQLITE_OK ){ return rc; } if( eType==PTRMAP_ROOTPAGE ){ return SQLITE_CORRUPT_BKPT; } if( eType==PTRMAP_FREEPAGE ){ if( bCommit==0 ){ /* Remove the page from the files free-list. This is not required ** if bCommit is non-zero. In that case, the free-list will be ** truncated to zero after this function returns, so it doesn't ** matter if it still contains some garbage entries. */ Pgno iFreePg; MemPage *pFreePg; rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); if( rc!=SQLITE_OK ){ return rc; } assert( iFreePg==iLastPg ); releasePage(pFreePg); } } else { Pgno iFreePg; /* Index of free page to move pLastPg to */ MemPage *pLastPg; u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); if( rc!=SQLITE_OK ){ return rc; } /* If bCommit is zero, this loop runs exactly once and page pLastPg ** is swapped with the first free page pulled off the free list. ** ** On the other hand, if bCommit is greater than zero, then keep ** looping until a free-page located within the first nFin pages ** of the file is found. */ if( bCommit==0 ){ eMode = BTALLOC_LE; iNear = nFin; } do { MemPage *pFreePg; rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); if( rc!=SQLITE_OK ){ releasePage(pLastPg); return rc; } releasePage(pFreePg); }while( bCommit && iFreePg>nFin ); assert( iFreePg<iLastPg ); rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit); releasePage(pLastPg); if( rc!=SQLITE_OK ){ return rc; } } } if( bCommit==0 ){ do { iLastPg--; }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) ); pBt->bDoTruncate = 1; pBt->nPage = iLastPg; } return SQLITE_OK; } /* ** The database opened by the first argument is an auto-vacuum database ** nOrig pages in size containing nFree free pages. Return the expected ** size of the database in pages following an auto-vacuum operation. */ static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ int nEntry; /* Number of entries on one ptrmap page */ Pgno nPtrmap; /* Number of PtrMap pages to be freed */ Pgno nFin; /* Return value */ nEntry = pBt->usableSize/5; nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; nFin = nOrig - nFree - nPtrmap; if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){ nFin--; } while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){ nFin--; } return nFin; } /* ** A write-transaction must be opened before calling this function. ** It performs a single unit of work towards an incremental vacuum. ** ** If the incremental vacuum is finished after this function has run, ** SQLITE_DONE is returned. If it is not finished, but no error occurred, ** SQLITE_OK is returned. Otherwise an SQLite error code. */ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); if( !pBt->autoVacuum ){ rc = SQLITE_DONE; }else{ Pgno nOrig = btreePagecount(pBt); Pgno nFree = get4byte(&pBt->pPage1->aData[36]); Pgno nFin = finalDbSize(pBt, nOrig, nFree); if( nOrig<nFin ){ rc = SQLITE_CORRUPT_BKPT; }else if( nFree>0 ){ rc = saveAllCursors(pBt, 0, 0); if( rc==SQLITE_OK ){ invalidateAllOverflowCache(pBt); rc = incrVacuumStep(pBt, nFin, nOrig, 0); } if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); put4byte(&pBt->pPage1->aData[28], pBt->nPage); } }else{ rc = SQLITE_DONE; } } sqlite3BtreeLeave(p); return rc; } /* ** This routine is called prior to sqlite3PagerCommit when a transaction ** is committed for an auto-vacuum database. ** ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages ** the database file should be truncated to during the commit process. ** i.e. the database has been reorganized so that only the first *pnTrunc ** pages are in use. */ static int autoVacuumCommit(BtShared *pBt){ int rc = SQLITE_OK; Pager *pPager = pBt->pPager; VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); ) assert( sqlite3_mutex_held(pBt->mutex) ); invalidateAllOverflowCache(pBt); assert(pBt->autoVacuum); if( !pBt->incrVacuum ){ Pgno nFin; /* Number of pages in database after autovacuuming */ Pgno nFree; /* Number of pages on the freelist initially */ Pgno iFree; /* The next page to be freed */ Pgno nOrig; /* Database size before freeing */ nOrig = btreePagecount(pBt); if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ /* It is not possible to create a database for which the final page ** is either a pointer-map page or the pending-byte page. If one ** is encountered, this indicates corruption. */ return SQLITE_CORRUPT_BKPT; } nFree = get4byte(&pBt->pPage1->aData[36]); nFin = finalDbSize(pBt, nOrig, nFree); if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; if( nFin<nOrig ){ rc = saveAllCursors(pBt, 0, 0); } for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){ rc = incrVacuumStep(pBt, nFin, iFree, 1); } if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); put4byte(&pBt->pPage1->aData[32], 0); put4byte(&pBt->pPage1->aData[36], 0); put4byte(&pBt->pPage1->aData[28], nFin); pBt->bDoTruncate = 1; pBt->nPage = nFin; } if( rc!=SQLITE_OK ){ sqlite3PagerRollback(pPager); } } assert( nRef>=sqlite3PagerRefcount(pPager) ); return rc; } #else /* ifndef SQLITE_OMIT_AUTOVACUUM */ # define setChildPtrmaps(x) SQLITE_OK #endif /* ** This routine does the first phase of a two-phase commit. This routine ** causes a rollback journal to be created (if it does not already exist) ** and populated with enough information so that if a power loss occurs ** the database can be restored to its original state by playing back ** the journal. Then the contents of the journal are flushed out to ** the disk. After the journal is safely on oxide, the changes to the ** database are written into the database file and flushed to oxide. ** At the end of this call, the rollback journal still exists on the ** disk and we are still holding all locks, so the transaction has not ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the ** commit process. ** ** This call is a no-op if no write-transaction is currently active on pBt. ** ** Otherwise, sync the database file for the btree pBt. zMaster points to ** the name of a master journal file that should be written into the ** individual journal file, or is NULL, indicating no master journal file ** (single database transaction). ** ** When this is called, the master journal should already have been ** created, populated with this journal pointer and synced to disk. ** ** Once this is routine has returned, the only thing required to commit ** the write-transaction for this database file is to delete the journal. */ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ int rc = SQLITE_OK; if( p->inTrans==TRANS_WRITE ){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ rc = autoVacuumCommit(pBt); if( rc!=SQLITE_OK ){ sqlite3BtreeLeave(p); return rc; } } if( pBt->bDoTruncate ){ sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); } #endif rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); sqlite3BtreeLeave(p); } return rc; } /* ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() ** at the conclusion of a transaction. */ static void btreeEndTransaction(Btree *p){ BtShared *pBt = p->pBt; sqlite3 *db = p->db; assert( sqlite3BtreeHoldsMutex(p) ); #ifndef SQLITE_OMIT_AUTOVACUUM pBt->bDoTruncate = 0; #endif if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ /* If there are other active statements that belong to this database ** handle, downgrade to a read-only transaction. The other statements ** may still be reading from the database. */ downgradeAllSharedCacheTableLocks(p); p->inTrans = TRANS_READ; }else{ /* If the handle had any kind of transaction open, decrement the ** transaction count of the shared btree. If the transaction count ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() ** call below will unlock the pager. */ if( p->inTrans!=TRANS_NONE ){ clearAllSharedCacheTableLocks(p); pBt->nTransaction--; if( 0==pBt->nTransaction ){ pBt->inTransaction = TRANS_NONE; } } /* Set the current transaction state to TRANS_NONE and unlock the ** pager if this call closed the only read or write transaction. */ p->inTrans = TRANS_NONE; unlockBtreeIfUnused(pBt); } btreeIntegrity(p); } /* ** Commit the transaction currently in progress. ** ** This routine implements the second phase of a 2-phase commit. The ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() ** routine did all the work of writing information out to disk and flushing the ** contents so that they are written onto the disk platter. All this ** routine has to do is delete or truncate or zero the header in the ** the rollback journal (which causes the transaction to commit) and ** drop locks. ** ** Normally, if an error occurs while the pager layer is attempting to ** finalize the underlying journal file, this function returns an error and ** the upper layer will attempt a rollback. However, if the second argument ** is non-zero then this b-tree transaction is part of a multi-file ** transaction. In this case, the transaction has already been committed ** (by deleting a master journal file) and the caller will ignore this ** functions return code. So, even if an error occurs in the pager layer, ** reset the b-tree objects internal state to indicate that the write ** transaction has been closed. This is quite safe, as the pager will have ** transitioned to the error state. ** ** This will release the write lock on the database file. If there ** are no active cursors, it also releases the read lock. */ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ if( p->inTrans==TRANS_NONE ) return SQLITE_OK; sqlite3BtreeEnter(p); btreeIntegrity(p); /* If the handle has a write-transaction open, commit the shared-btrees ** transaction and set the shared state to TRANS_READ. */ if( p->inTrans==TRANS_WRITE ){ int rc; BtShared *pBt = p->pBt; assert( pBt->inTransaction==TRANS_WRITE ); assert( pBt->nTransaction>0 ); rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); if( rc!=SQLITE_OK && bCleanup==0 ){ sqlite3BtreeLeave(p); return rc; } p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */ pBt->inTransaction = TRANS_READ; btreeClearHasContent(pBt); } btreeEndTransaction(p); sqlite3BtreeLeave(p); return SQLITE_OK; } /* ** Do both phases of a commit. */ SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){ int rc; sqlite3BtreeEnter(p); rc = sqlite3BtreeCommitPhaseOne(p, 0); if( rc==SQLITE_OK ){ rc = sqlite3BtreeCommitPhaseTwo(p, 0); } sqlite3BtreeLeave(p); return rc; } /* ** This routine sets the state to CURSOR_FAULT and the error ** code to errCode for every cursor on any BtShared that pBtree ** references. Or if the writeOnly flag is set to 1, then only ** trip write cursors and leave read cursors unchanged. ** ** Every cursor is a candidate to be tripped, including cursors ** that belong to other database connections that happen to be ** sharing the cache with pBtree. ** ** This routine gets called when a rollback occurs. If the writeOnly ** flag is true, then only write-cursors need be tripped - read-only ** cursors save their current positions so that they may continue ** following the rollback. Or, if writeOnly is false, all cursors are ** tripped. In general, writeOnly is false if the transaction being ** rolled back modified the database schema. In this case b-tree root ** pages may be moved or deleted from the database altogether, making ** it unsafe for read cursors to continue. ** ** If the writeOnly flag is true and an error is encountered while ** saving the current position of a read-only cursor, all cursors, ** including all read-cursors are tripped. ** ** SQLITE_OK is returned if successful, or if an error occurs while ** saving a cursor position, an SQLite error code. */ SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ BtCursor *p; int rc = SQLITE_OK; assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 ); if( pBtree ){ sqlite3BtreeEnter(pBtree); for(p=pBtree->pBt->pCursor; p; p=p->pNext){ int i; if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){ if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ rc = saveCursorPosition(p); if( rc!=SQLITE_OK ){ (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); break; } } }else{ sqlite3BtreeClearCursor(p); p->eState = CURSOR_FAULT; p->skipNext = errCode; } for(i=0; i<=p->iPage; i++){ releasePage(p->apPage[i]); p->apPage[i] = 0; } } sqlite3BtreeLeave(pBtree); } return rc; } /* ** Rollback the transaction in progress. ** ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). ** Only write cursors are tripped if writeOnly is true but all cursors are ** tripped if writeOnly is false. Any attempt to use ** a tripped cursor will result in an error. ** ** This will release the write lock on the database file. If there ** are no active cursors, it also releases the read lock. */ SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ int rc; BtShared *pBt = p->pBt; MemPage *pPage1; assert( writeOnly==1 || writeOnly==0 ); assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK ); sqlite3BtreeEnter(p); if( tripCode==SQLITE_OK ){ rc = tripCode = saveAllCursors(pBt, 0, 0); if( rc ) writeOnly = 0; }else{ rc = SQLITE_OK; } if( tripCode ){ int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) ); if( rc2!=SQLITE_OK ) rc = rc2; } btreeIntegrity(p); if( p->inTrans==TRANS_WRITE ){ int rc2; assert( TRANS_WRITE==pBt->inTransaction ); rc2 = sqlite3PagerRollback(pBt->pPager); if( rc2!=SQLITE_OK ){ rc = rc2; } /* The rollback may have destroyed the pPage1->aData value. So ** call btreeGetPage() on page 1 again to make ** sure pPage1->aData is set correctly. */ if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ int nPage = get4byte(28+(u8*)pPage1->aData); testcase( nPage==0 ); if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); testcase( pBt->nPage!=nPage ); pBt->nPage = nPage; releasePage(pPage1); } assert( countValidCursors(pBt, 1)==0 ); pBt->inTransaction = TRANS_READ; btreeClearHasContent(pBt); } btreeEndTransaction(p); sqlite3BtreeLeave(p); return rc; } /* ** Start a statement subtransaction. The subtransaction can be rolled ** back independently of the main transaction. You must start a transaction ** before starting a subtransaction. The subtransaction is ended automatically ** if the main transaction commits or rolls back. ** ** Statement subtransactions are used around individual SQL statements ** that are contained within a BEGIN...COMMIT block. If a constraint ** error occurs within the statement, the effect of that one statement ** can be rolled back without having to rollback the entire transaction. ** ** A statement sub-transaction is implemented as an anonymous savepoint. The ** value passed as the second parameter is the total number of savepoints, ** including the new anonymous savepoint, open on the B-Tree. i.e. if there ** are no active savepoints and no other statement-transactions open, ** iStatement is 1. This anonymous savepoint can be released or rolled back ** using the sqlite3BtreeSavepoint() function. */ SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); assert( iStatement>0 ); assert( iStatement>p->db->nSavepoint ); assert( pBt->inTransaction==TRANS_WRITE ); /* At the pager level, a statement transaction is a savepoint with ** an index greater than all savepoints created explicitly using ** SQL statements. It is illegal to open, release or rollback any ** such savepoints while the statement transaction savepoint is active. */ rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); sqlite3BtreeLeave(p); return rc; } /* ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK ** or SAVEPOINT_RELEASE. This function either releases or rolls back the ** savepoint identified by parameter iSavepoint, depending on the value ** of op. ** ** Normally, iSavepoint is greater than or equal to zero. However, if op is ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the ** contents of the entire transaction are rolled back. This is different ** from a normal transaction rollback, as no locks are released and the ** transaction remains open. */ SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ int rc = SQLITE_OK; if( p && p->inTrans==TRANS_WRITE ){ BtShared *pBt = p->pBt; assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); sqlite3BtreeEnter(p); if( op==SAVEPOINT_ROLLBACK ){ rc = saveAllCursors(pBt, 0, 0); } if( rc==SQLITE_OK ){ rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); } if( rc==SQLITE_OK ){ if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ pBt->nPage = 0; } rc = newDatabase(pBt); pBt->nPage = get4byte(28 + pBt->pPage1->aData); /* The database size was written into the offset 28 of the header ** when the transaction started, so we know that the value at offset ** 28 is nonzero. */ assert( pBt->nPage>0 ); } sqlite3BtreeLeave(p); } return rc; } /* ** Create a new cursor for the BTree whose root is on the page ** iTable. If a read-only cursor is requested, it is assumed that ** the caller already has at least a read-only transaction open ** on the database already. If a write-cursor is requested, then ** the caller is assumed to have an open write transaction. ** ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor ** can be used for reading or for writing if other conditions for writing ** are also met. These are the conditions that must be met in order ** for writing to be allowed: ** ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR ** ** 2: Other database connections that share the same pager cache ** but which are not in the READ_UNCOMMITTED state may not have ** cursors open with wrFlag==0 on the same table. Otherwise ** the changes made by this write cursor would be visible to ** the read cursors in the other database connection. ** ** 3: The database must be writable (not on read-only media) ** ** 4: There must be an active transaction. ** ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR ** is set. If FORDELETE is set, that is a hint to the implementation that ** this cursor will only be used to seek to and delete entries of an index ** as part of a larger DELETE statement. The FORDELETE hint is not used by ** this implementation. But in a hypothetical alternative storage engine ** in which index entries are automatically deleted when corresponding table ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE ** operations on this cursor can be no-ops and all READ operations can ** return a null row (2-bytes: 0x01 0x00). ** ** No checking is done to make sure that page iTable really is the ** root page of a b-tree. If it is not, then the cursor acquired ** will not work correctly. ** ** It is assumed that the sqlite3BtreeCursorZero() has been called ** on pCur to initialize the memory space prior to invoking this routine. */ static int btreeCursor( Btree *p, /* The btree */ int iTable, /* Root page of table to open */ int wrFlag, /* 1 to write. 0 read-only */ struct KeyInfo *pKeyInfo, /* First arg to comparison function */ BtCursor *pCur /* Space for new cursor */ ){ BtShared *pBt = p->pBt; /* Shared b-tree handle */ BtCursor *pX; /* Looping over other all cursors */ assert( sqlite3BtreeHoldsMutex(p) ); assert( wrFlag==0 || wrFlag==BTREE_WRCSR || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) ); /* The following assert statements verify that if this is a sharable ** b-tree database, the connection is holding the required table locks, ** and that no other connection has any open cursor that conflicts with ** this lock. */ assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) ); assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); /* Assert that the caller has opened the required transaction. */ assert( p->inTrans>TRANS_NONE ); assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); assert( pBt->pPage1 && pBt->pPage1->aData ); assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 ); if( wrFlag ){ allocateTempSpace(pBt); if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT; } if( iTable==1 && btreePagecount(pBt)==0 ){ assert( wrFlag==0 ); iTable = 0; } /* Now that no other errors can occur, finish filling in the BtCursor ** variables and link the cursor into the BtShared list. */ pCur->pgnoRoot = (Pgno)iTable; pCur->iPage = -1; pCur->pKeyInfo = pKeyInfo; pCur->pBtree = p; pCur->pBt = pBt; pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0; pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY; /* If there are two or more cursors on the same btree, then all such ** cursors *must* have the BTCF_Multiple flag set. */ for(pX=pBt->pCursor; pX; pX=pX->pNext){ if( pX->pgnoRoot==(Pgno)iTable ){ pX->curFlags |= BTCF_Multiple; pCur->curFlags |= BTCF_Multiple; } } pCur->pNext = pBt->pCursor; pBt->pCursor = pCur; pCur->eState = CURSOR_INVALID; return SQLITE_OK; } SQLITE_PRIVATE int sqlite3BtreeCursor( Btree *p, /* The btree */ int iTable, /* Root page of table to open */ int wrFlag, /* 1 to write. 0 read-only */ struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ BtCursor *pCur /* Write new cursor here */ ){ int rc; if( iTable<1 ){ rc = SQLITE_CORRUPT_BKPT; }else{ sqlite3BtreeEnter(p); rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); sqlite3BtreeLeave(p); } return rc; } /* ** Return the size of a BtCursor object in bytes. ** ** This interfaces is needed so that users of cursors can preallocate ** sufficient storage to hold a cursor. The BtCursor object is opaque ** to users so they cannot do the sizeof() themselves - they must call ** this routine. */ SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){ return ROUND8(sizeof(BtCursor)); } /* ** Initialize memory that will be converted into a BtCursor object. ** ** The simple approach here would be to memset() the entire object ** to zero. But it turns out that the apPage[] and aiIdx[] arrays ** do not need to be zeroed and they are large, so we can save a lot ** of run-time by skipping the initialization of those elements. */ SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){ memset(p, 0, offsetof(BtCursor, iPage)); } /* ** Close a cursor. The read lock on the database file is released ** when the last cursor is closed. */ SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){ Btree *pBtree = pCur->pBtree; if( pBtree ){ int i; BtShared *pBt = pCur->pBt; sqlite3BtreeEnter(pBtree); sqlite3BtreeClearCursor(pCur); assert( pBt->pCursor!=0 ); if( pBt->pCursor==pCur ){ pBt->pCursor = pCur->pNext; }else{ BtCursor *pPrev = pBt->pCursor; do{ if( pPrev->pNext==pCur ){ pPrev->pNext = pCur->pNext; break; } pPrev = pPrev->pNext; }while( ALWAYS(pPrev) ); } for(i=0; i<=pCur->iPage; i++){ releasePage(pCur->apPage[i]); } unlockBtreeIfUnused(pBt); sqlite3_free(pCur->aOverflow); /* sqlite3_free(pCur); */ sqlite3BtreeLeave(pBtree); } return SQLITE_OK; } /* ** Make sure the BtCursor* given in the argument has a valid ** BtCursor.info structure. If it is not already valid, call ** btreeParseCell() to fill it in. ** ** BtCursor.info is a cache of the information in the current cell. ** Using this cache reduces the number of calls to btreeParseCell(). */ #ifndef NDEBUG static void assertCellInfo(BtCursor *pCur){ CellInfo info; int iPage = pCur->iPage; memset(&info, 0, sizeof(info)); btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info); assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 ); } #else #define assertCellInfo(x) #endif static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){ if( pCur->info.nSize==0 ){ int iPage = pCur->iPage; pCur->curFlags |= BTCF_ValidNKey; btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); }else{ assertCellInfo(pCur); } } #ifndef NDEBUG /* The next routine used only within assert() statements */ /* ** Return true if the given BtCursor is valid. A valid cursor is one ** that is currently pointing to a row in a (non-empty) table. ** This is a verification routine is used only within assert() statements. */ SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){ return pCur && pCur->eState==CURSOR_VALID; } #endif /* NDEBUG */ SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){ assert( pCur!=0 ); return pCur->eState==CURSOR_VALID; } /* ** Return the value of the integer key or "rowid" for a table btree. ** This routine is only valid for a cursor that is pointing into a ** ordinary table btree. If the cursor points to an index btree or ** is invalid, the result of this routine is undefined. */ SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->curIntKey ); getCellInfo(pCur); return pCur->info.nKey; } /* ** Return the number of bytes of payload for the entry that pCur is ** currently pointing to. For table btrees, this will be the amount ** of data. For index btrees, this will be the size of the key. ** ** The caller must guarantee that the cursor is pointing to a non-NULL ** valid entry. In other words, the calling procedure must guarantee ** that the cursor has Cursor.eState==CURSOR_VALID. */ SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); getCellInfo(pCur); return pCur->info.nPayload; } /* ** Given the page number of an overflow page in the database (parameter ** ovfl), this function finds the page number of the next page in the ** linked list of overflow pages. If possible, it uses the auto-vacuum ** pointer-map data instead of reading the content of page ovfl to do so. ** ** If an error occurs an SQLite error code is returned. Otherwise: ** ** The page number of the next overflow page in the linked list is ** written to *pPgnoNext. If page ovfl is the last page in its linked ** list, *pPgnoNext is set to zero. ** ** If ppPage is not NULL, and a reference to the MemPage object corresponding ** to page number pOvfl was obtained, then *ppPage is set to point to that ** reference. It is the responsibility of the caller to call releasePage() ** on *ppPage to free the reference. In no reference was obtained (because ** the pointer-map was used to obtain the value for *pPgnoNext), then ** *ppPage is set to zero. */ static int getOverflowPage( BtShared *pBt, /* The database file */ Pgno ovfl, /* Current overflow page number */ MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ Pgno *pPgnoNext /* OUT: Next overflow page number */ ){ Pgno next = 0; MemPage *pPage = 0; int rc = SQLITE_OK; assert( sqlite3_mutex_held(pBt->mutex) ); assert(pPgnoNext); #ifndef SQLITE_OMIT_AUTOVACUUM /* Try to find the next page in the overflow list using the ** autovacuum pointer-map pages. Guess that the next page in ** the overflow list is page number (ovfl+1). If that guess turns ** out to be wrong, fall back to loading the data of page ** number ovfl to determine the next page number. */ if( pBt->autoVacuum ){ Pgno pgno; Pgno iGuess = ovfl+1; u8 eType; while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ iGuess++; } if( iGuess<=btreePagecount(pBt) ){ rc = ptrmapGet(pBt, iGuess, &eType, &pgno); if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ next = iGuess; rc = SQLITE_DONE; } } } #endif assert( next==0 || rc==SQLITE_DONE ); if( rc==SQLITE_OK ){ rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); assert( rc==SQLITE_OK || pPage==0 ); if( rc==SQLITE_OK ){ next = get4byte(pPage->aData); } } *pPgnoNext = next; if( ppPage ){ *ppPage = pPage; }else{ releasePage(pPage); } return (rc==SQLITE_DONE ? SQLITE_OK : rc); } /* ** Copy data from a buffer to a page, or from a page to a buffer. ** ** pPayload is a pointer to data stored on database page pDbPage. ** If argument eOp is false, then nByte bytes of data are copied ** from pPayload to the buffer pointed at by pBuf. If eOp is true, ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes ** of data are copied from the buffer pBuf to pPayload. ** ** SQLITE_OK is returned on success, otherwise an error code. */ static int copyPayload( void *pPayload, /* Pointer to page data */ void *pBuf, /* Pointer to buffer */ int nByte, /* Number of bytes to copy */ int eOp, /* 0 -> copy from page, 1 -> copy to page */ DbPage *pDbPage /* Page containing pPayload */ ){ if( eOp ){ /* Copy data from buffer to page (a write operation) */ int rc = sqlite3PagerWrite(pDbPage); if( rc!=SQLITE_OK ){ return rc; } memcpy(pPayload, pBuf, nByte); }else{ /* Copy data from page to buffer (a read operation) */ memcpy(pBuf, pPayload, nByte); } return SQLITE_OK; } /* ** This function is used to read or overwrite payload information ** for the entry that the pCur cursor is pointing to. The eOp ** argument is interpreted as follows: ** ** 0: The operation is a read. Populate the overflow cache. ** 1: The operation is a write. Populate the overflow cache. ** ** A total of "amt" bytes are read or written beginning at "offset". ** Data is read to or from the buffer pBuf. ** ** The content being read or written might appear on the main page ** or be scattered out on multiple overflow pages. ** ** If the current cursor entry uses one or more overflow pages ** this function may allocate space for and lazily populate ** the overflow page-list cache array (BtCursor.aOverflow). ** Subsequent calls use this cache to make seeking to the supplied offset ** more efficient. ** ** Once an overflow page-list cache has been allocated, it must be ** invalidated if some other cursor writes to the same table, or if ** the cursor is moved to a different row. Additionally, in auto-vacuum ** mode, the following events may invalidate an overflow page-list cache. ** ** * An incremental vacuum, ** * A commit in auto_vacuum="full" mode, ** * Creating a table (may require moving an overflow page). */ static int accessPayload( BtCursor *pCur, /* Cursor pointing to entry to read from */ u32 offset, /* Begin reading this far into payload */ u32 amt, /* Read this many bytes */ unsigned char *pBuf, /* Write the bytes into this buffer */ int eOp /* zero to read. non-zero to write. */ ){ unsigned char *aPayload; int rc = SQLITE_OK; int iIdx = 0; MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */ BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ #ifdef SQLITE_DIRECT_OVERFLOW_READ unsigned char * const pBufStart = pBuf; /* Start of original out buffer */ #endif assert( pPage ); assert( eOp==0 || eOp==1 ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); assert( cursorHoldsMutex(pCur) ); getCellInfo(pCur); aPayload = pCur->info.pPayload; assert( offset+amt <= pCur->info.nPayload ); assert( aPayload > pPage->aData ); if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ /* Trying to read or write past the end of the data is an error. The ** conditional above is really: ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ** but is recast into its current form to avoid integer overflow problems */ return SQLITE_CORRUPT_BKPT; } /* Check if data must be read/written to/from the btree page itself. */ if( offset<pCur->info.nLocal ){ int a = amt; if( a+offset>pCur->info.nLocal ){ a = pCur->info.nLocal - offset; } rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); offset = 0; pBuf += a; amt -= a; }else{ offset -= pCur->info.nLocal; } if( rc==SQLITE_OK && amt>0 ){ const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ Pgno nextPage; nextPage = get4byte(&aPayload[pCur->info.nLocal]); /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. ** ** The aOverflow[] array is sized at one entry for each overflow page ** in the overflow chain. The page number of the first overflow page is ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array ** means "not yet known" (the cache is lazily populated). */ if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; if( nOvfl>pCur->nOvflAlloc ){ Pgno *aNew = (Pgno*)sqlite3Realloc( pCur->aOverflow, nOvfl*2*sizeof(Pgno) ); if( aNew==0 ){ return SQLITE_NOMEM_BKPT; }else{ pCur->nOvflAlloc = nOvfl*2; pCur->aOverflow = aNew; } } memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); pCur->curFlags |= BTCF_ValidOvfl; }else{ /* If the overflow page-list cache has been allocated and the ** entry for the first required overflow page is valid, skip ** directly to it. */ if( pCur->aOverflow[offset/ovflSize] ){ iIdx = (offset/ovflSize); nextPage = pCur->aOverflow[iIdx]; offset = (offset%ovflSize); } } assert( rc==SQLITE_OK && amt>0 ); while( nextPage ){ /* If required, populate the overflow page-list cache. */ assert( pCur->aOverflow[iIdx]==0 || pCur->aOverflow[iIdx]==nextPage || CORRUPT_DB ); pCur->aOverflow[iIdx] = nextPage; if( offset>=ovflSize ){ /* The only reason to read this page is to obtain the page ** number for the next page in the overflow chain. The page ** data is not required. So first try to lookup the overflow ** page-list cache, if any, then fall back to the getOverflowPage() ** function. */ assert( pCur->curFlags & BTCF_ValidOvfl ); assert( pCur->pBtree->db==pBt->db ); if( pCur->aOverflow[iIdx+1] ){ nextPage = pCur->aOverflow[iIdx+1]; }else{ rc = getOverflowPage(pBt, nextPage, 0, &nextPage); } offset -= ovflSize; }else{ /* Need to read this page properly. It contains some of the ** range of data that is being read (eOp==0) or written (eOp!=0). */ #ifdef SQLITE_DIRECT_OVERFLOW_READ sqlite3_file *fd; /* File from which to do direct overflow read */ #endif int a = amt; if( a + offset > ovflSize ){ a = ovflSize - offset; } #ifdef SQLITE_DIRECT_OVERFLOW_READ /* If all the following are true: ** ** 1) this is a read operation, and ** 2) data is required from the start of this overflow page, and ** 3) there is no open write-transaction, and ** 4) the database is file-backed, and ** 5) the page is not in the WAL file ** 6) at least 4 bytes have already been read into the output buffer ** ** then data can be read directly from the database file into the ** output buffer, bypassing the page-cache altogether. This speeds ** up loading large records that span many overflow pages. */ if( eOp==0 /* (1) */ && offset==0 /* (2) */ && pBt->inTransaction==TRANS_READ /* (3) */ && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */ && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */ && &pBuf[-4]>=pBufStart /* (6) */ ){ u8 aSave[4]; u8 *aWrite = &pBuf[-4]; assert( aWrite>=pBufStart ); /* due to (6) */ memcpy(aSave, aWrite, 4); rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); nextPage = get4byte(aWrite); memcpy(aWrite, aSave, 4); }else #endif { DbPage *pDbPage; rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, (eOp==0 ? PAGER_GET_READONLY : 0) ); if( rc==SQLITE_OK ){ aPayload = sqlite3PagerGetData(pDbPage); nextPage = get4byte(aPayload); rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); sqlite3PagerUnref(pDbPage); offset = 0; } } amt -= a; if( amt==0 ) return rc; pBuf += a; } if( rc ) break; iIdx++; } } if( rc==SQLITE_OK && amt>0 ){ return SQLITE_CORRUPT_BKPT; /* Overflow chain ends prematurely */ } return rc; } /* ** Read part of the payload for the row at which that cursor pCur is currently ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer ** begins at "offset". ** ** pCur can be pointing to either a table or an index b-tree. ** If pointing to a table btree, then the content section is read. If ** pCur is pointing to an index b-tree then the key section is read. ** ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the ** cursor might be invalid or might need to be restored before being read. ** ** Return SQLITE_OK on success or an error code if anything goes ** wrong. An error is returned if "offset+amt" is larger than ** the available payload. */ SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); } /* ** This variant of sqlite3BtreePayload() works even if the cursor has not ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read() ** interface. */ #ifndef SQLITE_OMIT_INCRBLOB static SQLITE_NOINLINE int accessPayloadChecked( BtCursor *pCur, u32 offset, u32 amt, void *pBuf ){ int rc; if ( pCur->eState==CURSOR_INVALID ){ return SQLITE_ABORT; } assert( cursorOwnsBtShared(pCur) ); rc = btreeRestoreCursorPosition(pCur); return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0); } SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ if( pCur->eState==CURSOR_VALID ){ assert( cursorOwnsBtShared(pCur) ); return accessPayload(pCur, offset, amt, pBuf, 0); }else{ return accessPayloadChecked(pCur, offset, amt, pBuf); } } #endif /* SQLITE_OMIT_INCRBLOB */ /* ** Return a pointer to payload information from the entry that the ** pCur cursor is pointing to. The pointer is to the beginning of ** the key if index btrees (pPage->intKey==0) and is the data for ** table btrees (pPage->intKey==1). The number of bytes of available ** key/data is written into *pAmt. If *pAmt==0, then the value ** returned will not be a valid pointer. ** ** This routine is an optimization. It is common for the entire key ** and data to fit on the local page and for there to be no overflow ** pages. When that is so, this routine can be used to access the ** key and data without making a copy. If the key and/or data spills ** onto overflow pages, then accessPayload() must be used to reassemble ** the key/data and copy it into a preallocated buffer. ** ** The pointer returned by this routine looks directly into the cached ** page of the database. The data might change or move the next time ** any btree routine is called. */ static const void *fetchPayload( BtCursor *pCur, /* Cursor pointing to entry to read from */ u32 *pAmt /* Write the number of available bytes here */ ){ u32 amt; assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]); assert( pCur->eState==CURSOR_VALID ); assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); assert( cursorOwnsBtShared(pCur) ); assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); assert( pCur->info.nSize>0 ); assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB ); assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB); amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload); if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal; *pAmt = amt; return (void*)pCur->info.pPayload; } /* ** For the entry that cursor pCur is point to, return as ** many bytes of the key or data as are available on the local ** b-tree page. Write the number of available bytes into *pAmt. ** ** The pointer returned is ephemeral. The key/data may move ** or be destroyed on the next call to any Btree routine, ** including calls from other threads against the same cache. ** Hence, a mutex on the BtShared should be held prior to calling ** this routine. ** ** These routines is used to get quick access to key and data ** in the common case where no overflow pages are used. */ SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){ return fetchPayload(pCur, pAmt); } /* ** Move the cursor down to a new child page. The newPgno argument is the ** page number of the child page to move to. ** ** This function returns SQLITE_CORRUPT if the page-header flags field of ** the new child page does not match the flags field of the parent (i.e. ** if an intkey page appears to be the parent of a non-intkey page, or ** vice-versa). */ static int moveToChild(BtCursor *pCur, u32 newPgno){ BtShared *pBt = pCur->pBt; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->iPage<BTCURSOR_MAX_DEPTH ); assert( pCur->iPage>=0 ); if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ return SQLITE_CORRUPT_BKPT; } pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); pCur->iPage++; pCur->aiIdx[pCur->iPage] = 0; return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage], pCur, pCur->curPagerFlags); } #if SQLITE_DEBUG /* ** Page pParent is an internal (non-leaf) tree page. This function ** asserts that page number iChild is the left-child if the iIdx'th ** cell in page pParent. Or, if iIdx is equal to the total number of ** cells in pParent, that page number iChild is the right-child of ** the page. */ static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ if( CORRUPT_DB ) return; /* The conditions tested below might not be true ** in a corrupt database */ assert( iIdx<=pParent->nCell ); if( iIdx==pParent->nCell ){ assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild ); }else{ assert( get4byte(findCell(pParent, iIdx))==iChild ); } } #else # define assertParentIndex(x,y,z) #endif /* ** Move the cursor up to the parent page. ** ** pCur->idx is set to the cell index that contains the pointer ** to the page we are coming from. If we are coming from the ** right-most child page then pCur->idx is set to one more than ** the largest cell index. */ static void moveToParent(BtCursor *pCur){ assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->iPage>0 ); assert( pCur->apPage[pCur->iPage] ); assertParentIndex( pCur->apPage[pCur->iPage-1], pCur->aiIdx[pCur->iPage-1], pCur->apPage[pCur->iPage]->pgno ); testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); releasePageNotNull(pCur->apPage[pCur->iPage--]); } /* ** Move the cursor to point to the root page of its b-tree structure. ** ** If the table has a virtual root page, then the cursor is moved to point ** to the virtual root page instead of the actual root page. A table has a ** virtual root page when the actual root page contains no cells and a ** single child page. This can only happen with the table rooted at page 1. ** ** If the b-tree structure is empty, the cursor state is set to ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first ** cell located on the root (or virtual root) page and the cursor state ** is set to CURSOR_VALID. ** ** If this function returns successfully, it may be assumed that the ** page-header flags indicate that the [virtual] root-page is the expected ** kind of b-tree page (i.e. if when opening the cursor the caller did not ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, ** indicating a table b-tree, or if the caller did specify a KeyInfo ** structure the flags byte is set to 0x02 or 0x0A, indicating an index ** b-tree). */ static int moveToRoot(BtCursor *pCur){ MemPage *pRoot; int rc = SQLITE_OK; assert( cursorOwnsBtShared(pCur) ); assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); if( pCur->eState>=CURSOR_REQUIRESEEK ){ if( pCur->eState==CURSOR_FAULT ){ assert( pCur->skipNext!=SQLITE_OK ); return pCur->skipNext; } sqlite3BtreeClearCursor(pCur); } if( pCur->iPage>=0 ){ if( pCur->iPage ){ do{ assert( pCur->apPage[pCur->iPage]!=0 ); releasePageNotNull(pCur->apPage[pCur->iPage--]); }while( pCur->iPage); goto skip_init; } }else if( pCur->pgnoRoot==0 ){ pCur->eState = CURSOR_INVALID; return SQLITE_OK; }else{ assert( pCur->iPage==(-1) ); rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0], 0, pCur->curPagerFlags); if( rc!=SQLITE_OK ){ pCur->eState = CURSOR_INVALID; return rc; } pCur->iPage = 0; pCur->curIntKey = pCur->apPage[0]->intKey; } pRoot = pCur->apPage[0]; assert( pRoot->pgno==pCur->pgnoRoot ); /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is ** NULL, the caller expects a table b-tree. If this is not the case, ** return an SQLITE_CORRUPT error. ** ** Earlier versions of SQLite assumed that this test could not fail ** if the root page was already loaded when this function was called (i.e. ** if pCur->iPage>=0). But this is not so if the database is corrupted ** in such a way that page pRoot is linked into a second b-tree table ** (or the freelist). */ assert( pRoot->intKey==1 || pRoot->intKey==0 ); if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ return SQLITE_CORRUPT_BKPT; } skip_init: pCur->aiIdx[0] = 0; pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl); pRoot = pCur->apPage[0]; if( pRoot->nCell>0 ){ pCur->eState = CURSOR_VALID; }else if( !pRoot->leaf ){ Pgno subpage; if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); pCur->eState = CURSOR_VALID; rc = moveToChild(pCur, subpage); }else{ pCur->eState = CURSOR_INVALID; } return rc; } /* ** Move the cursor down to the left-most leaf entry beneath the ** entry to which it is currently pointing. ** ** The left-most leaf is the one with the smallest key - the first ** in ascending order. */ static int moveToLeftmost(BtCursor *pCur){ Pgno pgno; int rc = SQLITE_OK; MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage])); rc = moveToChild(pCur, pgno); } return rc; } /* ** Move the cursor down to the right-most leaf entry beneath the ** page to which it is currently pointing. Notice the difference ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() ** finds the left-most entry beneath the *entry* whereas moveToRightmost() ** finds the right-most entry beneath the *page*. ** ** The right-most entry is the one with the largest key - the last ** key in ascending order. */ static int moveToRightmost(BtCursor *pCur){ Pgno pgno; int rc = SQLITE_OK; MemPage *pPage = 0; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){ pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); pCur->aiIdx[pCur->iPage] = pPage->nCell; rc = moveToChild(pCur, pgno); if( rc ) return rc; } pCur->aiIdx[pCur->iPage] = pPage->nCell-1; assert( pCur->info.nSize==0 ); assert( (pCur->curFlags & BTCF_ValidNKey)==0 ); return SQLITE_OK; } /* Move the cursor to the first entry in the table. Return SQLITE_OK ** on success. Set *pRes to 0 if the cursor actually points to something ** or set *pRes to 1 if the table is empty. */ SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ int rc; assert( cursorOwnsBtShared(pCur) ); assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); rc = moveToRoot(pCur); if( rc==SQLITE_OK ){ if( pCur->eState==CURSOR_INVALID ){ assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); *pRes = 1; }else{ assert( pCur->apPage[pCur->iPage]->nCell>0 ); *pRes = 0; rc = moveToLeftmost(pCur); } } return rc; } /* Move the cursor to the last entry in the table. Return SQLITE_OK ** on success. Set *pRes to 0 if the cursor actually points to something ** or set *pRes to 1 if the table is empty. */ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ int rc; assert( cursorOwnsBtShared(pCur) ); assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); /* If the cursor already points to the last entry, this is a no-op. */ if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){ #ifdef SQLITE_DEBUG /* This block serves to assert() that the cursor really does point ** to the last entry in the b-tree. */ int ii; for(ii=0; ii<pCur->iPage; ii++){ assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); } assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 ); assert( pCur->apPage[pCur->iPage]->leaf ); #endif return SQLITE_OK; } rc = moveToRoot(pCur); if( rc==SQLITE_OK ){ if( CURSOR_INVALID==pCur->eState ){ assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); *pRes = 1; }else{ assert( pCur->eState==CURSOR_VALID ); *pRes = 0; rc = moveToRightmost(pCur); if( rc==SQLITE_OK ){ pCur->curFlags |= BTCF_AtLast; }else{ pCur->curFlags &= ~BTCF_AtLast; } } } return rc; } /* Move the cursor so that it points to an entry near the key ** specified by pIdxKey or intKey. Return a success code. ** ** For INTKEY tables, the intKey parameter is used. pIdxKey ** must be NULL. For index tables, pIdxKey is used and intKey ** is ignored. ** ** If an exact match is not found, then the cursor is always ** left pointing at a leaf page which would hold the entry if it ** were present. The cursor might point to an entry that comes ** before or after the key. ** ** An integer is written into *pRes which is the result of ** comparing the key with the entry to which the cursor is ** pointing. The meaning of the integer written into ** *pRes is as follows: ** ** *pRes<0 The cursor is left pointing at an entry that ** is smaller than intKey/pIdxKey or if the table is empty ** and the cursor is therefore left point to nothing. ** ** *pRes==0 The cursor is left pointing at an entry that ** exactly matches intKey/pIdxKey. ** ** *pRes>0 The cursor is left pointing at an entry that ** is larger than intKey/pIdxKey. ** ** For index tables, the pIdxKey->eqSeen field is set to 1 if there ** exists an entry in the table that exactly matches pIdxKey. */ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( BtCursor *pCur, /* The cursor to be moved */ UnpackedRecord *pIdxKey, /* Unpacked index key */ i64 intKey, /* The table key */ int biasRight, /* If true, bias the search to the high end */ int *pRes /* Write search results here */ ){ int rc; RecordCompare xRecordCompare; assert( cursorOwnsBtShared(pCur) ); assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); assert( pRes ); assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) ); /* If the cursor is already positioned at the point we are trying ** to move to, then just return without doing any work */ if( pIdxKey==0 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){ if( pCur->info.nKey==intKey ){ *pRes = 0; return SQLITE_OK; } if( pCur->info.nKey<intKey ){ if( (pCur->curFlags & BTCF_AtLast)!=0 ){ *pRes = -1; return SQLITE_OK; } /* If the requested key is one more than the previous key, then ** try to get there using sqlite3BtreeNext() rather than a full ** binary search. This is an optimization only. The correct answer ** is still obtained without this ase, only a little more slowely */ if( pCur->info.nKey+1==intKey && !pCur->skipNext ){ *pRes = 0; rc = sqlite3BtreeNext(pCur, pRes); if( rc ) return rc; if( *pRes==0 ){ getCellInfo(pCur); if( pCur->info.nKey==intKey ){ return SQLITE_OK; } } } } } if( pIdxKey ){ xRecordCompare = sqlite3VdbeFindCompare(pIdxKey); pIdxKey->errCode = 0; assert( pIdxKey->default_rc==1 || pIdxKey->default_rc==0 || pIdxKey->default_rc==-1 ); }else{ xRecordCompare = 0; /* All keys are integers */ } rc = moveToRoot(pCur); if( rc ){ return rc; } assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] ); assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit ); assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 ); if( pCur->eState==CURSOR_INVALID ){ *pRes = -1; assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); return SQLITE_OK; } assert( pCur->apPage[0]->intKey==pCur->curIntKey ); assert( pCur->curIntKey || pIdxKey ); for(;;){ int lwr, upr, idx, c; Pgno chldPg; MemPage *pPage = pCur->apPage[pCur->iPage]; u8 *pCell; /* Pointer to current cell in pPage */ /* pPage->nCell must be greater than zero. If this is the root-page ** the cursor would have been INVALID above and this for(;;) loop ** not run. If this is not the root-page, then the moveToChild() routine ** would have already detected db corruption. Similarly, pPage must ** be the right kind (index or table) of b-tree page. Otherwise ** a moveToChild() or moveToRoot() call would have detected corruption. */ assert( pPage->nCell>0 ); assert( pPage->intKey==(pIdxKey==0) ); lwr = 0; upr = pPage->nCell-1; assert( biasRight==0 || biasRight==1 ); idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ pCur->aiIdx[pCur->iPage] = (u16)idx; if( xRecordCompare==0 ){ for(;;){ i64 nCellKey; pCell = findCellPastPtr(pPage, idx); if( pPage->intKeyLeaf ){ while( 0x80 <= *(pCell++) ){ if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT; } } getVarint(pCell, (u64*)&nCellKey); if( nCellKey<intKey ){ lwr = idx+1; if( lwr>upr ){ c = -1; break; } }else if( nCellKey>intKey ){ upr = idx-1; if( lwr>upr ){ c = +1; break; } }else{ assert( nCellKey==intKey ); pCur->aiIdx[pCur->iPage] = (u16)idx; if( !pPage->leaf ){ lwr = idx; goto moveto_next_layer; }else{ pCur->curFlags |= BTCF_ValidNKey; pCur->info.nKey = nCellKey; pCur->info.nSize = 0; *pRes = 0; return SQLITE_OK; } } assert( lwr+upr>=0 ); idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */ } }else{ for(;;){ int nCell; /* Size of the pCell cell in bytes */ pCell = findCellPastPtr(pPage, idx); /* The maximum supported page-size is 65536 bytes. This means that ** the maximum number of record bytes stored on an index B-Tree ** page is less than 16384 bytes and may be stored as a 2-byte ** varint. This information is used to attempt to avoid parsing ** the entire cell by checking for the cases where the record is ** stored entirely within the b-tree page by inspecting the first ** 2 bytes of the cell. */ nCell = pCell[0]; if( nCell<=pPage->max1bytePayload ){ /* This branch runs if the record-size field of the cell is a ** single byte varint and the record fits entirely on the main ** b-tree page. */ testcase( pCell+nCell+1==pPage->aDataEnd ); c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); }else if( !(pCell[1] & 0x80) && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal ){ /* The record-size field is a 2 byte varint and the record ** fits entirely on the main b-tree page. */ testcase( pCell+nCell+2==pPage->aDataEnd ); c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); }else{ /* The record flows over onto one or more overflow pages. In ** this case the whole cell needs to be parsed, a buffer allocated ** and accessPayload() used to retrieve the record into the ** buffer before VdbeRecordCompare() can be called. ** ** If the record is corrupt, the xRecordCompare routine may read ** up to two varints past the end of the buffer. An extra 18 ** bytes of padding is allocated at the end of the buffer in ** case this happens. */ void *pCellKey; u8 * const pCellBody = pCell - pPage->childPtrSize; pPage->xParseCell(pPage, pCellBody, &pCur->info); nCell = (int)pCur->info.nKey; testcase( nCell<0 ); /* True if key size is 2^32 or more */ testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */ testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */ testcase( nCell==2 ); /* Minimum legal index key size */ if( nCell<2 ){ rc = SQLITE_CORRUPT_BKPT; goto moveto_finish; } pCellKey = sqlite3Malloc( nCell+18 ); if( pCellKey==0 ){ rc = SQLITE_NOMEM_BKPT; goto moveto_finish; } pCur->aiIdx[pCur->iPage] = (u16)idx; rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); pCur->curFlags &= ~BTCF_ValidOvfl; if( rc ){ sqlite3_free(pCellKey); goto moveto_finish; } c = xRecordCompare(nCell, pCellKey, pIdxKey); sqlite3_free(pCellKey); } assert( (pIdxKey->errCode!=SQLITE_CORRUPT || c==0) && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed) ); if( c<0 ){ lwr = idx+1; }else if( c>0 ){ upr = idx-1; }else{ assert( c==0 ); *pRes = 0; rc = SQLITE_OK; pCur->aiIdx[pCur->iPage] = (u16)idx; if( pIdxKey->errCode ) rc = SQLITE_CORRUPT; goto moveto_finish; } if( lwr>upr ) break; assert( lwr+upr>=0 ); idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */ } } assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); assert( pPage->isInit ); if( pPage->leaf ){ assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); pCur->aiIdx[pCur->iPage] = (u16)idx; *pRes = c; rc = SQLITE_OK; goto moveto_finish; } moveto_next_layer: if( lwr>=pPage->nCell ){ chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); }else{ chldPg = get4byte(findCell(pPage, lwr)); } pCur->aiIdx[pCur->iPage] = (u16)lwr; rc = moveToChild(pCur, chldPg); if( rc ) break; } moveto_finish: pCur->info.nSize = 0; assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); return rc; } /* ** Return TRUE if the cursor is not pointing at an entry of the table. ** ** TRUE will be returned after a call to sqlite3BtreeNext() moves ** past the last entry in the table or sqlite3BtreePrev() moves past ** the first entry. TRUE is also returned if the table is empty. */ SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){ /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries ** have been deleted? This API will need to change to return an error code ** as well as the boolean result value. */ return (CURSOR_VALID!=pCur->eState); } /* ** Advance the cursor to the next entry in the database. If ** successful then set *pRes=0. If the cursor ** was already pointing to the last entry in the database before ** this routine was called, then set *pRes=1. ** ** The main entry point is sqlite3BtreeNext(). That routine is optimized ** for the common case of merely incrementing the cell counter BtCursor.aiIdx ** to the next cell on the current page. The (slower) btreeNext() helper ** routine is called when it is necessary to move to a different page or ** to restore the cursor. ** ** The calling function will set *pRes to 0 or 1. The initial *pRes value ** will be 1 if the cursor being stepped corresponds to an SQL index and ** if this routine could have been skipped if that SQL index had been ** a unique index. Otherwise the caller will have set *pRes to zero. ** Zero is the common case. The btree implementation is free to use the ** initial *pRes value as a hint to improve performance, but the current ** SQLite btree implementation does not. (Note that the comdb2 btree ** implementation does use this hint, however.) */ static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){ int rc; int idx; MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); assert( *pRes==0 ); if( pCur->eState!=CURSOR_VALID ){ assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); rc = restoreCursorPosition(pCur); if( rc!=SQLITE_OK ){ return rc; } if( CURSOR_INVALID==pCur->eState ){ *pRes = 1; return SQLITE_OK; } if( pCur->skipNext ){ assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); pCur->eState = CURSOR_VALID; if( pCur->skipNext>0 ){ pCur->skipNext = 0; return SQLITE_OK; } pCur->skipNext = 0; } } pPage = pCur->apPage[pCur->iPage]; idx = ++pCur->aiIdx[pCur->iPage]; assert( pPage->isInit ); /* If the database file is corrupt, it is possible for the value of idx ** to be invalid here. This can only occur if a second cursor modifies ** the page while cursor pCur is holding a reference to it. Which can ** only happen if the database is corrupt in such a way as to link the ** page into more than one b-tree structure. */ testcase( idx>pPage->nCell ); if( idx>=pPage->nCell ){ if( !pPage->leaf ){ rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); if( rc ) return rc; return moveToLeftmost(pCur); } do{ if( pCur->iPage==0 ){ *pRes = 1; pCur->eState = CURSOR_INVALID; return SQLITE_OK; } moveToParent(pCur); pPage = pCur->apPage[pCur->iPage]; }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell ); if( pPage->intKey ){ return sqlite3BtreeNext(pCur, pRes); }else{ return SQLITE_OK; } } if( pPage->leaf ){ return SQLITE_OK; }else{ return moveToLeftmost(pCur); } } SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); assert( pRes!=0 ); assert( *pRes==0 || *pRes==1 ); assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); *pRes = 0; if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes); pPage = pCur->apPage[pCur->iPage]; if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){ pCur->aiIdx[pCur->iPage]--; return btreeNext(pCur, pRes); } if( pPage->leaf ){ return SQLITE_OK; }else{ return moveToLeftmost(pCur); } } /* ** Step the cursor to the back to the previous entry in the database. If ** successful then set *pRes=0. If the cursor ** was already pointing to the first entry in the database before ** this routine was called, then set *pRes=1. ** ** The main entry point is sqlite3BtreePrevious(). That routine is optimized ** for the common case of merely decrementing the cell counter BtCursor.aiIdx ** to the previous cell on the current page. The (slower) btreePrevious() ** helper routine is called when it is necessary to move to a different page ** or to restore the cursor. ** ** The calling function will set *pRes to 0 or 1. The initial *pRes value ** will be 1 if the cursor being stepped corresponds to an SQL index and ** if this routine could have been skipped if that SQL index had been ** a unique index. Otherwise the caller will have set *pRes to zero. ** Zero is the common case. The btree implementation is free to use the ** initial *pRes value as a hint to improve performance, but the current ** SQLite btree implementation does not. (Note that the comdb2 btree ** implementation does use this hint, however.) */ static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){ int rc; MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); assert( pRes!=0 ); assert( *pRes==0 ); assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 ); assert( pCur->info.nSize==0 ); if( pCur->eState!=CURSOR_VALID ){ rc = restoreCursorPosition(pCur); if( rc!=SQLITE_OK ){ return rc; } if( CURSOR_INVALID==pCur->eState ){ *pRes = 1; return SQLITE_OK; } if( pCur->skipNext ){ assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); pCur->eState = CURSOR_VALID; if( pCur->skipNext<0 ){ pCur->skipNext = 0; return SQLITE_OK; } pCur->skipNext = 0; } } pPage = pCur->apPage[pCur->iPage]; assert( pPage->isInit ); if( !pPage->leaf ){ int idx = pCur->aiIdx[pCur->iPage]; rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); if( rc ) return rc; rc = moveToRightmost(pCur); }else{ while( pCur->aiIdx[pCur->iPage]==0 ){ if( pCur->iPage==0 ){ pCur->eState = CURSOR_INVALID; *pRes = 1; return SQLITE_OK; } moveToParent(pCur); } assert( pCur->info.nSize==0 ); assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 ); pCur->aiIdx[pCur->iPage]--; pPage = pCur->apPage[pCur->iPage]; if( pPage->intKey && !pPage->leaf ){ rc = sqlite3BtreePrevious(pCur, pRes); }else{ rc = SQLITE_OK; } } return rc; } SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ assert( cursorOwnsBtShared(pCur) ); assert( pRes!=0 ); assert( *pRes==0 || *pRes==1 ); assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); *pRes = 0; pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey); pCur->info.nSize = 0; if( pCur->eState!=CURSOR_VALID || pCur->aiIdx[pCur->iPage]==0 || pCur->apPage[pCur->iPage]->leaf==0 ){ return btreePrevious(pCur, pRes); } pCur->aiIdx[pCur->iPage]--; return SQLITE_OK; } /* ** Allocate a new page from the database file. ** ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() ** has already been called on the new page.) The new page has also ** been referenced and the calling routine is responsible for calling ** sqlite3PagerUnref() on the new page when it is done. ** ** SQLITE_OK is returned on success. Any other return value indicates ** an error. *ppPage is set to NULL in the event of an error. ** ** If the "nearby" parameter is not 0, then an effort is made to ** locate a page close to the page number "nearby". This can be used in an ** attempt to keep related pages close to each other in the database file, ** which in turn can make database access faster. ** ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists ** anywhere on the free-list, then it is guaranteed to be returned. If ** eMode is BTALLOC_LT then the page returned will be less than or equal ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there ** are no restrictions on which page is returned. */ static int allocateBtreePage( BtShared *pBt, /* The btree */ MemPage **ppPage, /* Store pointer to the allocated page here */ Pgno *pPgno, /* Store the page number here */ Pgno nearby, /* Search for a page near this one */ u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ ){ MemPage *pPage1; int rc; u32 n; /* Number of pages on the freelist */ u32 k; /* Number of leaves on the trunk of the freelist */ MemPage *pTrunk = 0; MemPage *pPrevTrunk = 0; Pgno mxPage; /* Total size of the database file */ assert( sqlite3_mutex_held(pBt->mutex) ); assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); pPage1 = pBt->pPage1; mxPage = btreePagecount(pBt); /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36 ** stores stores the total number of pages on the freelist. */ n = get4byte(&pPage1->aData[36]); testcase( n==mxPage-1 ); if( n>=mxPage ){ return SQLITE_CORRUPT_BKPT; } if( n>0 ){ /* There are pages on the freelist. Reuse one of those pages. */ Pgno iTrunk; u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ u32 nSearch = 0; /* Count of the number of search attempts */ /* If eMode==BTALLOC_EXACT and a query of the pointer-map ** shows that the page 'nearby' is somewhere on the free-list, then ** the entire-list will be searched for that page. */ #ifndef SQLITE_OMIT_AUTOVACUUM if( eMode==BTALLOC_EXACT ){ if( nearby<=mxPage ){ u8 eType; assert( nearby>0 ); assert( pBt->autoVacuum ); rc = ptrmapGet(pBt, nearby, &eType, 0); if( rc ) return rc; if( eType==PTRMAP_FREEPAGE ){ searchList = 1; } } }else if( eMode==BTALLOC_LE ){ searchList = 1; } #endif /* Decrement the free-list count by 1. Set iTrunk to the index of the ** first free-list trunk page. iPrevTrunk is initially 1. */ rc = sqlite3PagerWrite(pPage1->pDbPage); if( rc ) return rc; put4byte(&pPage1->aData[36], n-1); /* The code within this loop is run only once if the 'searchList' variable ** is not true. Otherwise, it runs once for each trunk-page on the ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) */ do { pPrevTrunk = pTrunk; if( pPrevTrunk ){ /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page ** is the page number of the next freelist trunk page in the list or ** zero if this is the last freelist trunk page. */ iTrunk = get4byte(&pPrevTrunk->aData[0]); }else{ /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32 ** stores the page number of the first page of the freelist, or zero if ** the freelist is empty. */ iTrunk = get4byte(&pPage1->aData[32]); } testcase( iTrunk==mxPage ); if( iTrunk>mxPage || nSearch++ > n ){ rc = SQLITE_CORRUPT_BKPT; }else{ rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0); } if( rc ){ pTrunk = 0; goto end_allocate_page; } assert( pTrunk!=0 ); assert( pTrunk->aData!=0 ); /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page ** is the number of leaf page pointers to follow. */ k = get4byte(&pTrunk->aData[4]); if( k==0 && !searchList ){ /* The trunk has no leaves and the list is not being searched. ** So extract the trunk page itself and use it as the newly ** allocated page */ assert( pPrevTrunk==0 ); rc = sqlite3PagerWrite(pTrunk->pDbPage); if( rc ){ goto end_allocate_page; } *pPgno = iTrunk; memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); *ppPage = pTrunk; pTrunk = 0; TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); }else if( k>(u32)(pBt->usableSize/4 - 2) ){ /* Value of k is out of range. Database corruption */ rc = SQLITE_CORRUPT_BKPT; goto end_allocate_page; #ifndef SQLITE_OMIT_AUTOVACUUM }else if( searchList && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) ){ /* The list is being searched and this trunk page is the page ** to allocate, regardless of whether it has leaves. */ *pPgno = iTrunk; *ppPage = pTrunk; searchList = 0; rc = sqlite3PagerWrite(pTrunk->pDbPage); if( rc ){ goto end_allocate_page; } if( k==0 ){ if( !pPrevTrunk ){ memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); }else{ rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); if( rc!=SQLITE_OK ){ goto end_allocate_page; } memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); } }else{ /* The trunk page is required by the caller but it contains ** pointers to free-list leaves. The first leaf becomes a trunk ** page in this case. */ MemPage *pNewTrunk; Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); if( iNewTrunk>mxPage ){ rc = SQLITE_CORRUPT_BKPT; goto end_allocate_page; } testcase( iNewTrunk==mxPage ); rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0); if( rc!=SQLITE_OK ){ goto end_allocate_page; } rc = sqlite3PagerWrite(pNewTrunk->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pNewTrunk); goto end_allocate_page; } memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); put4byte(&pNewTrunk->aData[4], k-1); memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); releasePage(pNewTrunk); if( !pPrevTrunk ){ assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); put4byte(&pPage1->aData[32], iNewTrunk); }else{ rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); if( rc ){ goto end_allocate_page; } put4byte(&pPrevTrunk->aData[0], iNewTrunk); } } pTrunk = 0; TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); #endif }else if( k>0 ){ /* Extract a leaf from the trunk */ u32 closest; Pgno iPage; unsigned char *aData = pTrunk->aData; if( nearby>0 ){ u32 i; closest = 0; if( eMode==BTALLOC_LE ){ for(i=0; i<k; i++){ iPage = get4byte(&aData[8+i*4]); if( iPage<=nearby ){ closest = i; break; } } }else{ int dist; dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby); for(i=1; i<k; i++){ int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby); if( d2<dist ){ closest = i; dist = d2; } } } }else{ closest = 0; } iPage = get4byte(&aData[8+closest*4]); testcase( iPage==mxPage ); if( iPage>mxPage ){ rc = SQLITE_CORRUPT_BKPT; goto end_allocate_page; } testcase( iPage==mxPage ); if( !searchList || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) ){ int noContent; *pPgno = iPage; TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d" ": %d more free pages\n", *pPgno, closest+1, k, pTrunk->pgno, n-1)); rc = sqlite3PagerWrite(pTrunk->pDbPage); if( rc ) goto end_allocate_page; if( closest<k-1 ){ memcpy(&aData[8+closest*4], &aData[4+k*4], 4); } put4byte(&aData[4], k-1); noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0; rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent); if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite((*ppPage)->pDbPage); if( rc!=SQLITE_OK ){ releasePage(*ppPage); *ppPage = 0; } } searchList = 0; } } releasePage(pPrevTrunk); pPrevTrunk = 0; }while( searchList ); }else{ /* There are no pages on the freelist, so append a new page to the ** database image. ** ** Normally, new pages allocated by this block can be requested from the ** pager layer with the 'no-content' flag set. This prevents the pager ** from trying to read the pages content from disk. However, if the ** current transaction has already run one or more incremental-vacuum ** steps, then the page we are about to allocate may contain content ** that is required in the event of a rollback. In this case, do ** not set the no-content flag. This causes the pager to load and journal ** the current page content before overwriting it. ** ** Note that the pager will not actually attempt to load or journal ** content for any page that really does lie past the end of the database ** file on disk. So the effects of disabling the no-content optimization ** here are confined to those pages that lie between the end of the ** database image and the end of the database file. */ int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0; rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc ) return rc; pBt->nPage++; if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ /* If *pPgno refers to a pointer-map page, allocate two new pages ** at the end of the file instead of one. The first allocated page ** becomes a new pointer-map page, the second is used by the caller. */ MemPage *pPg = 0; TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent); if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pPg->pDbPage); releasePage(pPg); } if( rc ) return rc; pBt->nPage++; if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } } #endif put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); *pPgno = pBt->nPage; assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent); if( rc ) return rc; rc = sqlite3PagerWrite((*ppPage)->pDbPage); if( rc!=SQLITE_OK ){ releasePage(*ppPage); *ppPage = 0; } TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); } assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); end_allocate_page: releasePage(pTrunk); releasePage(pPrevTrunk); assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 ); assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 ); return rc; } /* ** This function is used to add page iPage to the database file free-list. ** It is assumed that the page is not already a part of the free-list. ** ** The value passed as the second argument to this function is optional. ** If the caller happens to have a pointer to the MemPage object ** corresponding to page iPage handy, it may pass it as the second value. ** Otherwise, it may pass NULL. ** ** If a pointer to a MemPage object is passed as the second argument, ** its reference count is not altered by this function. */ static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ MemPage *pTrunk = 0; /* Free-list trunk page */ Pgno iTrunk = 0; /* Page number of free-list trunk page */ MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ MemPage *pPage; /* Page being freed. May be NULL. */ int rc; /* Return Code */ int nFree; /* Initial number of pages on free-list */ assert( sqlite3_mutex_held(pBt->mutex) ); assert( CORRUPT_DB || iPage>1 ); assert( !pMemPage || pMemPage->pgno==iPage ); if( iPage<2 ) return SQLITE_CORRUPT_BKPT; if( pMemPage ){ pPage = pMemPage; sqlite3PagerRef(pPage->pDbPage); }else{ pPage = btreePageLookup(pBt, iPage); } /* Increment the free page count on pPage1 */ rc = sqlite3PagerWrite(pPage1->pDbPage); if( rc ) goto freepage_out; nFree = get4byte(&pPage1->aData[36]); put4byte(&pPage1->aData[36], nFree+1); if( pBt->btsFlags & BTS_SECURE_DELETE ){ /* If the secure_delete option is enabled, then ** always fully overwrite deleted information with zeros. */ if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) ){ goto freepage_out; } memset(pPage->aData, 0, pPage->pBt->pageSize); } /* If the database supports auto-vacuum, write an entry in the pointer-map ** to indicate that the page is free. */ if( ISAUTOVACUUM ){ ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); if( rc ) goto freepage_out; } /* Now manipulate the actual database free-list structure. There are two ** possibilities. If the free-list is currently empty, or if the first ** trunk page in the free-list is full, then this page will become a ** new free-list trunk page. Otherwise, it will become a leaf of the ** first trunk page in the current free-list. This block tests if it ** is possible to add the page as a new free-list leaf. */ if( nFree!=0 ){ u32 nLeaf; /* Initial number of leaf cells on trunk page */ iTrunk = get4byte(&pPage1->aData[32]); rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); if( rc!=SQLITE_OK ){ goto freepage_out; } nLeaf = get4byte(&pTrunk->aData[4]); assert( pBt->usableSize>32 ); if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ rc = SQLITE_CORRUPT_BKPT; goto freepage_out; } if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ /* In this case there is room on the trunk page to insert the page ** being freed as a new leaf. ** ** Note that the trunk page is not really full until it contains ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have ** coded. But due to a coding error in versions of SQLite prior to ** 3.6.0, databases with freelist trunk pages holding more than ** usableSize/4 - 8 entries will be reported as corrupt. In order ** to maintain backwards compatibility with older versions of SQLite, ** we will continue to restrict the number of entries to usableSize/4 - 8 ** for now. At some point in the future (once everyone has upgraded ** to 3.6.0 or later) we should consider fixing the conditional above ** to read "usableSize/4-2" instead of "usableSize/4-8". ** ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still ** avoid using the last six entries in the freelist trunk page array in ** order that database files created by newer versions of SQLite can be ** read by older versions of SQLite. */ rc = sqlite3PagerWrite(pTrunk->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pTrunk->aData[4], nLeaf+1); put4byte(&pTrunk->aData[8+nLeaf*4], iPage); if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ sqlite3PagerDontWrite(pPage->pDbPage); } rc = btreeSetHasContent(pBt, iPage); } TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); goto freepage_out; } } /* If control flows to this point, then it was not possible to add the ** the page being freed as a leaf page of the first trunk in the free-list. ** Possibly because the free-list is empty, or possibly because the ** first trunk in the free-list is full. Either way, the page being freed ** will become the new first trunk page in the free-list. */ if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ goto freepage_out; } rc = sqlite3PagerWrite(pPage->pDbPage); if( rc!=SQLITE_OK ){ goto freepage_out; } put4byte(pPage->aData, iTrunk); put4byte(&pPage->aData[4], 0); put4byte(&pPage1->aData[32], iPage); TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk)); freepage_out: if( pPage ){ pPage->isInit = 0; } releasePage(pPage); releasePage(pTrunk); return rc; } static void freePage(MemPage *pPage, int *pRC){ if( (*pRC)==SQLITE_OK ){ *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); } } /* ** Free any overflow pages associated with the given Cell. Write the ** local Cell size (the number of bytes on the original page, omitting ** overflow) into *pnSize. */ static int clearCell( MemPage *pPage, /* The page that contains the Cell */ unsigned char *pCell, /* First byte of the Cell */ CellInfo *pInfo /* Size information about the cell */ ){ BtShared *pBt = pPage->pBt; Pgno ovflPgno; int rc; int nOvfl; u32 ovflPageSize; assert( sqlite3_mutex_held(pPage->pBt->mutex) ); pPage->xParseCell(pPage, pCell, pInfo); if( pInfo->nLocal==pInfo->nPayload ){ return SQLITE_OK; /* No overflow pages. Return without doing anything */ } if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){ return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */ } ovflPgno = get4byte(pCell + pInfo->nSize - 4); assert( pBt->usableSize > 4 ); ovflPageSize = pBt->usableSize - 4; nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize; assert( nOvfl>0 || (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize) ); while( nOvfl-- ){ Pgno iNext = 0; MemPage *pOvfl = 0; if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ /* 0 is not a legal page number and page 1 cannot be an ** overflow page. Therefore if ovflPgno<2 or past the end of the ** file the database must be corrupt. */ return SQLITE_CORRUPT_BKPT; } if( nOvfl ){ rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); if( rc ) return rc; } if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 ){ /* There is no reason any cursor should have an outstanding reference ** to an overflow page belonging to a cell that is being deleted/updated. ** So if there exists more than one reference to this page, then it ** must not really be an overflow page and the database must be corrupt. ** It is helpful to detect this before calling freePage2(), as ** freePage2() may zero the page contents if secure-delete mode is ** enabled. If this 'overflow' page happens to be a page that the ** caller is iterating through or using in some other way, this ** can be problematic. */ rc = SQLITE_CORRUPT_BKPT; }else{ rc = freePage2(pBt, pOvfl, ovflPgno); } if( pOvfl ){ sqlite3PagerUnref(pOvfl->pDbPage); } if( rc ) return rc; ovflPgno = iNext; } return SQLITE_OK; } /* ** Create the byte sequence used to represent a cell on page pPage ** and write that byte sequence into pCell[]. Overflow pages are ** allocated and filled in as necessary. The calling procedure ** is responsible for making sure sufficient space has been allocated ** for pCell[]. ** ** Note that pCell does not necessary need to point to the pPage->aData ** area. pCell might point to some temporary storage. The cell will ** be constructed in this temporary area then copied into pPage->aData ** later. */ static int fillInCell( MemPage *pPage, /* The page that contains the cell */ unsigned char *pCell, /* Complete text of the cell */ const BtreePayload *pX, /* Payload with which to construct the cell */ int *pnSize /* Write cell size here */ ){ int nPayload; const u8 *pSrc; int nSrc, n, rc; int spaceLeft; MemPage *pOvfl = 0; MemPage *pToRelease = 0; unsigned char *pPrior; unsigned char *pPayload; BtShared *pBt = pPage->pBt; Pgno pgnoOvfl = 0; int nHeader; assert( sqlite3_mutex_held(pPage->pBt->mutex) ); /* pPage is not necessarily writeable since pCell might be auxiliary ** buffer space that is separate from the pPage buffer area */ assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize] || sqlite3PagerIswriteable(pPage->pDbPage) ); /* Fill in the header. */ nHeader = pPage->childPtrSize; if( pPage->intKey ){ nPayload = pX->nData + pX->nZero; pSrc = pX->pData; nSrc = pX->nData; assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */ nHeader += putVarint32(&pCell[nHeader], nPayload); nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey); }else{ assert( pX->nKey<=0x7fffffff && pX->pKey!=0 ); nSrc = nPayload = (int)pX->nKey; pSrc = pX->pKey; nHeader += putVarint32(&pCell[nHeader], nPayload); } /* Fill in the payload */ if( nPayload<=pPage->maxLocal ){ n = nHeader + nPayload; testcase( n==3 ); testcase( n==4 ); if( n<4 ) n = 4; *pnSize = n; spaceLeft = nPayload; pPrior = pCell; }else{ int mn = pPage->minLocal; n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); testcase( n==pPage->maxLocal ); testcase( n==pPage->maxLocal+1 ); if( n > pPage->maxLocal ) n = mn; spaceLeft = n; *pnSize = n + nHeader + 4; pPrior = &pCell[nHeader+n]; } pPayload = &pCell[nHeader]; /* At this point variables should be set as follows: ** ** nPayload Total payload size in bytes ** pPayload Begin writing payload here ** spaceLeft Space available at pPayload. If nPayload>spaceLeft, ** that means content must spill into overflow pages. ** *pnSize Size of the local cell (not counting overflow pages) ** pPrior Where to write the pgno of the first overflow page ** ** Use a call to btreeParseCellPtr() to verify that the values above ** were computed correctly. */ #if SQLITE_DEBUG { CellInfo info; pPage->xParseCell(pPage, pCell, &info); assert( nHeader==(int)(info.pPayload - pCell) ); assert( info.nKey==pX->nKey ); assert( *pnSize == info.nSize ); assert( spaceLeft == info.nLocal ); } #endif /* Write the payload into the local Cell and any extra into overflow pages */ while( nPayload>0 ){ if( spaceLeft==0 ){ #ifndef SQLITE_OMIT_AUTOVACUUM Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ if( pBt->autoVacuum ){ do{ pgnoOvfl++; } while( PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) ); } #endif rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); #ifndef SQLITE_OMIT_AUTOVACUUM /* If the database supports auto-vacuum, and the second or subsequent ** overflow page is being allocated, add an entry to the pointer-map ** for that page now. ** ** If this is the first overflow page, then write a partial entry ** to the pointer-map. If we write nothing to this pointer-map slot, ** then the optimistic overflow chain processing in clearCell() ** may misinterpret the uninitialized values and delete the ** wrong pages from the database. */ if( pBt->autoVacuum && rc==SQLITE_OK ){ u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); if( rc ){ releasePage(pOvfl); } } #endif if( rc ){ releasePage(pToRelease); return rc; } /* If pToRelease is not zero than pPrior points into the data area ** of pToRelease. Make sure pToRelease is still writeable. */ assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); /* If pPrior is part of the data area of pPage, then make sure pPage ** is still writeable */ assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize] || sqlite3PagerIswriteable(pPage->pDbPage) ); put4byte(pPrior, pgnoOvfl); releasePage(pToRelease); pToRelease = pOvfl; pPrior = pOvfl->aData; put4byte(pPrior, 0); pPayload = &pOvfl->aData[4]; spaceLeft = pBt->usableSize - 4; } n = nPayload; if( n>spaceLeft ) n = spaceLeft; /* If pToRelease is not zero than pPayload points into the data area ** of pToRelease. Make sure pToRelease is still writeable. */ assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); /* If pPayload is part of the data area of pPage, then make sure pPage ** is still writeable */ assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize] || sqlite3PagerIswriteable(pPage->pDbPage) ); if( nSrc>0 ){ if( n>nSrc ) n = nSrc; assert( pSrc ); memcpy(pPayload, pSrc, n); }else{ memset(pPayload, 0, n); } nPayload -= n; pPayload += n; pSrc += n; nSrc -= n; spaceLeft -= n; } releasePage(pToRelease); return SQLITE_OK; } /* ** Remove the i-th cell from pPage. This routine effects pPage only. ** The cell content is not freed or deallocated. It is assumed that ** the cell content has been copied someplace else. This routine just ** removes the reference to the cell from pPage. ** ** "sz" must be the number of bytes in the cell. */ static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ u32 pc; /* Offset to cell content of cell being deleted */ u8 *data; /* pPage->aData */ u8 *ptr; /* Used to move bytes around within data[] */ int rc; /* The return code */ int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ if( *pRC ) return; assert( idx>=0 && idx<pPage->nCell ); assert( CORRUPT_DB || sz==cellSize(pPage, idx) ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); data = pPage->aData; ptr = &pPage->aCellIdx[2*idx]; pc = get2byte(ptr); hdr = pPage->hdrOffset; testcase( pc==get2byte(&data[hdr+5]) ); testcase( pc+sz==pPage->pBt->usableSize ); if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){ *pRC = SQLITE_CORRUPT_BKPT; return; } rc = freeSpace(pPage, pc, sz); if( rc ){ *pRC = rc; return; } pPage->nCell--; if( pPage->nCell==0 ){ memset(&data[hdr+1], 0, 4); data[hdr+7] = 0; put2byte(&data[hdr+5], pPage->pBt->usableSize); pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset - pPage->childPtrSize - 8; }else{ memmove(ptr, ptr+2, 2*(pPage->nCell - idx)); put2byte(&data[hdr+3], pPage->nCell); pPage->nFree += 2; } } /* ** Insert a new cell on pPage at cell index "i". pCell points to the ** content of the cell. ** ** If the cell content will fit on the page, then put it there. If it ** will not fit, then make a copy of the cell content into pTemp if ** pTemp is not null. Regardless of pTemp, allocate a new entry ** in pPage->apOvfl[] and make it point to the cell content (either ** in pTemp or the original pCell) and also record its index. ** Allocating a new entry in pPage->aCell[] implies that ** pPage->nOverflow is incremented. ** ** *pRC must be SQLITE_OK when this routine is called. */ static void insertCell( MemPage *pPage, /* Page into which we are copying */ int i, /* New cell becomes the i-th cell of the page */ u8 *pCell, /* Content of the new cell */ int sz, /* Bytes of content in pCell */ u8 *pTemp, /* Temp storage space for pCell, if needed */ Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ int *pRC /* Read and write return code from here */ ){ int idx = 0; /* Where to write new cell content in data[] */ int j; /* Loop counter */ u8 *data; /* The content of the whole page */ u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */ assert( *pRC==SQLITE_OK ); assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); assert( MX_CELL(pPage->pBt)<=10921 ); assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB ); assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); /* The cell should normally be sized correctly. However, when moving a ** malformed cell from a leaf page to an interior page, if the cell size ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size ** might be less than 8 (leaf-size + pointer) on the interior node. Hence ** the term after the || in the following assert(). */ assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) ); if( pPage->nOverflow || sz+2>pPage->nFree ){ if( pTemp ){ memcpy(pTemp, pCell, sz); pCell = pTemp; } if( iChild ){ put4byte(pCell, iChild); } j = pPage->nOverflow++; /* Comparison against ArraySize-1 since we hold back one extra slot ** as a contingency. In other words, never need more than 3 overflow ** slots but 4 are allocated, just to be safe. */ assert( j < ArraySize(pPage->apOvfl)-1 ); pPage->apOvfl[j] = pCell; pPage->aiOvfl[j] = (u16)i; /* When multiple overflows occur, they are always sequential and in ** sorted order. This invariants arise because multiple overflows can ** only occur when inserting divider cells into the parent page during ** balancing, and the dividers are adjacent and sorted. */ assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */ assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */ }else{ int rc = sqlite3PagerWrite(pPage->pDbPage); if( rc!=SQLITE_OK ){ *pRC = rc; return; } assert( sqlite3PagerIswriteable(pPage->pDbPage) ); data = pPage->aData; assert( &data[pPage->cellOffset]==pPage->aCellIdx ); rc = allocateSpace(pPage, sz, &idx); if( rc ){ *pRC = rc; return; } /* The allocateSpace() routine guarantees the following properties ** if it returns successfully */ assert( idx >= 0 ); assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB ); assert( idx+sz <= (int)pPage->pBt->usableSize ); pPage->nFree -= (u16)(2 + sz); memcpy(&data[idx], pCell, sz); if( iChild ){ put4byte(&data[idx], iChild); } pIns = pPage->aCellIdx + i*2; memmove(pIns+2, pIns, 2*(pPage->nCell - i)); put2byte(pIns, idx); pPage->nCell++; /* increment the cell count */ if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell ); #ifndef SQLITE_OMIT_AUTOVACUUM if( pPage->pBt->autoVacuum ){ /* The cell may contain a pointer to an overflow page. If so, write ** the entry for the overflow page into the pointer map. */ ptrmapPutOvflPtr(pPage, pCell, pRC); } #endif } } /* ** A CellArray object contains a cache of pointers and sizes for a ** consecutive sequence of cells that might be held on multiple pages. */ typedef struct CellArray CellArray; struct CellArray { int nCell; /* Number of cells in apCell[] */ MemPage *pRef; /* Reference page */ u8 **apCell; /* All cells begin balanced */ u16 *szCell; /* Local size of all cells in apCell[] */ }; /* ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been ** computed. */ static void populateCellCache(CellArray *p, int idx, int N){ assert( idx>=0 && idx+N<=p->nCell ); while( N>0 ){ assert( p->apCell[idx]!=0 ); if( p->szCell[idx]==0 ){ p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]); }else{ assert( CORRUPT_DB || p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) ); } idx++; N--; } } /* ** Return the size of the Nth element of the cell array */ static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){ assert( N>=0 && N<p->nCell ); assert( p->szCell[N]==0 ); p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]); return p->szCell[N]; } static u16 cachedCellSize(CellArray *p, int N){ assert( N>=0 && N<p->nCell ); if( p->szCell[N] ) return p->szCell[N]; return computeCellSize(p, N); } /* ** Array apCell[] contains pointers to nCell b-tree page cells. The ** szCell[] array contains the size in bytes of each cell. This function ** replaces the current contents of page pPg with the contents of the cell ** array. ** ** Some of the cells in apCell[] may currently be stored in pPg. This ** function works around problems caused by this by making a copy of any ** such cells before overwriting the page data. ** ** The MemPage.nFree field is invalidated by this function. It is the ** responsibility of the caller to set it correctly. */ static int rebuildPage( MemPage *pPg, /* Edit this page */ int nCell, /* Final number of cells on page */ u8 **apCell, /* Array of cells */ u16 *szCell /* Array of cell sizes */ ){ const int hdr = pPg->hdrOffset; /* Offset of header on pPg */ u8 * const aData = pPg->aData; /* Pointer to data for pPg */ const int usableSize = pPg->pBt->usableSize; u8 * const pEnd = &aData[usableSize]; int i; u8 *pCellptr = pPg->aCellIdx; u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); u8 *pData; i = get2byte(&aData[hdr+5]); memcpy(&pTmp[i], &aData[i], usableSize - i); pData = pEnd; for(i=0; i<nCell; i++){ u8 *pCell = apCell[i]; if( SQLITE_WITHIN(pCell,aData,pEnd) ){ pCell = &pTmp[pCell - aData]; } pData -= szCell[i]; put2byte(pCellptr, (pData - aData)); pCellptr += 2; if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT; memcpy(pData, pCell, szCell[i]); assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB ); testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) ); } /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ pPg->nCell = nCell; pPg->nOverflow = 0; put2byte(&aData[hdr+1], 0); put2byte(&aData[hdr+3], pPg->nCell); put2byte(&aData[hdr+5], pData - aData); aData[hdr+7] = 0x00; return SQLITE_OK; } /* ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell ** contains the size in bytes of each such cell. This function attempts to ** add the cells stored in the array to page pPg. If it cannot (because ** the page needs to be defragmented before the cells will fit), non-zero ** is returned. Otherwise, if the cells are added successfully, zero is ** returned. ** ** Argument pCellptr points to the first entry in the cell-pointer array ** (part of page pPg) to populate. After cell apCell[0] is written to the ** page body, a 16-bit offset is written to pCellptr. And so on, for each ** cell in the array. It is the responsibility of the caller to ensure ** that it is safe to overwrite this part of the cell-pointer array. ** ** When this function is called, *ppData points to the start of the ** content area on page pPg. If the size of the content area is extended, ** *ppData is updated to point to the new start of the content area ** before returning. ** ** Finally, argument pBegin points to the byte immediately following the ** end of the space required by this page for the cell-pointer area (for ** all cells - not just those inserted by the current call). If the content ** area must be extended to before this point in order to accomodate all ** cells in apCell[], then the cells do not fit and non-zero is returned. */ static int pageInsertArray( MemPage *pPg, /* Page to add cells to */ u8 *pBegin, /* End of cell-pointer array */ u8 **ppData, /* IN/OUT: Page content -area pointer */ u8 *pCellptr, /* Pointer to cell-pointer area */ int iFirst, /* Index of first cell to add */ int nCell, /* Number of cells to add to pPg */ CellArray *pCArray /* Array of cells */ ){ int i; u8 *aData = pPg->aData; u8 *pData = *ppData; int iEnd = iFirst + nCell; assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */ for(i=iFirst; i<iEnd; i++){ int sz, rc; u8 *pSlot; sz = cachedCellSize(pCArray, i); if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){ if( (pData - pBegin)<sz ) return 1; pData -= sz; pSlot = pData; } /* pSlot and pCArray->apCell[i] will never overlap on a well-formed ** database. But they might for a corrupt database. Hence use memmove() ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */ assert( (pSlot+sz)<=pCArray->apCell[i] || pSlot>=(pCArray->apCell[i]+sz) || CORRUPT_DB ); memmove(pSlot, pCArray->apCell[i], sz); put2byte(pCellptr, (pSlot - aData)); pCellptr += 2; } *ppData = pData; return 0; } /* ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell ** contains the size in bytes of each such cell. This function adds the ** space associated with each cell in the array that is currently stored ** within the body of pPg to the pPg free-list. The cell-pointers and other ** fields of the page are not updated. ** ** This function returns the total number of cells added to the free-list. */ static int pageFreeArray( MemPage *pPg, /* Page to edit */ int iFirst, /* First cell to delete */ int nCell, /* Cells to delete */ CellArray *pCArray /* Array of cells */ ){ u8 * const aData = pPg->aData; u8 * const pEnd = &aData[pPg->pBt->usableSize]; u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize]; int nRet = 0; int i; int iEnd = iFirst + nCell; u8 *pFree = 0; int szFree = 0; for(i=iFirst; i<iEnd; i++){ u8 *pCell = pCArray->apCell[i]; if( SQLITE_WITHIN(pCell, pStart, pEnd) ){ int sz; /* No need to use cachedCellSize() here. The sizes of all cells that ** are to be freed have already been computing while deciding which ** cells need freeing */ sz = pCArray->szCell[i]; assert( sz>0 ); if( pFree!=(pCell + sz) ){ if( pFree ){ assert( pFree>aData && (pFree - aData)<65536 ); freeSpace(pPg, (u16)(pFree - aData), szFree); } pFree = pCell; szFree = sz; if( pFree+sz>pEnd ) return 0; }else{ pFree = pCell; szFree += sz; } nRet++; } } if( pFree ){ assert( pFree>aData && (pFree - aData)<65536 ); freeSpace(pPg, (u16)(pFree - aData), szFree); } return nRet; } /* ** apCell[] and szCell[] contains pointers to and sizes of all cells in the ** pages being balanced. The current page, pPg, has pPg->nCell cells starting ** with apCell[iOld]. After balancing, this page should hold nNew cells ** starting at apCell[iNew]. ** ** This routine makes the necessary adjustments to pPg so that it contains ** the correct cells after being balanced. ** ** The pPg->nFree field is invalid when this function returns. It is the ** responsibility of the caller to set it correctly. */ static int editPage( MemPage *pPg, /* Edit this page */ int iOld, /* Index of first cell currently on page */ int iNew, /* Index of new first cell on page */ int nNew, /* Final number of cells on page */ CellArray *pCArray /* Array of cells and sizes */ ){ u8 * const aData = pPg->aData; const int hdr = pPg->hdrOffset; u8 *pBegin = &pPg->aCellIdx[nNew * 2]; int nCell = pPg->nCell; /* Cells stored on pPg */ u8 *pData; u8 *pCellptr; int i; int iOldEnd = iOld + pPg->nCell + pPg->nOverflow; int iNewEnd = iNew + nNew; #ifdef SQLITE_DEBUG u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); memcpy(pTmp, aData, pPg->pBt->usableSize); #endif /* Remove cells from the start and end of the page */ if( iOld<iNew ){ int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray); memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); nCell -= nShift; } if( iNewEnd < iOldEnd ){ nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); } pData = &aData[get2byteNotZero(&aData[hdr+5])]; if( pData<pBegin ) goto editpage_fail; /* Add cells to the start of the page */ if( iNew<iOld ){ int nAdd = MIN(nNew,iOld-iNew); assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB ); pCellptr = pPg->aCellIdx; memmove(&pCellptr[nAdd*2], pCellptr, nCell*2); if( pageInsertArray( pPg, pBegin, &pData, pCellptr, iNew, nAdd, pCArray ) ) goto editpage_fail; nCell += nAdd; } /* Add any overflow cells */ for(i=0; i<pPg->nOverflow; i++){ int iCell = (iOld + pPg->aiOvfl[i]) - iNew; if( iCell>=0 && iCell<nNew ){ pCellptr = &pPg->aCellIdx[iCell * 2]; memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); nCell++; if( pageInsertArray( pPg, pBegin, &pData, pCellptr, iCell+iNew, 1, pCArray ) ) goto editpage_fail; } } /* Append cells to the end of the page */ pCellptr = &pPg->aCellIdx[nCell*2]; if( pageInsertArray( pPg, pBegin, &pData, pCellptr, iNew+nCell, nNew-nCell, pCArray ) ) goto editpage_fail; pPg->nCell = nNew; pPg->nOverflow = 0; put2byte(&aData[hdr+3], pPg->nCell); put2byte(&aData[hdr+5], pData - aData); #ifdef SQLITE_DEBUG for(i=0; i<nNew && !CORRUPT_DB; i++){ u8 *pCell = pCArray->apCell[i+iNew]; int iOff = get2byteAligned(&pPg->aCellIdx[i*2]); if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){ pCell = &pTmp[pCell - aData]; } assert( 0==memcmp(pCell, &aData[iOff], pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) ); } #endif return SQLITE_OK; editpage_fail: /* Unable to edit this page. Rebuild it from scratch instead. */ populateCellCache(pCArray, iNew, nNew); return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]); } /* ** The following parameters determine how many adjacent pages get involved ** in a balancing operation. NN is the number of neighbors on either side ** of the page that participate in the balancing operation. NB is the ** total number of pages that participate, including the target page and ** NN neighbors on either side. ** ** The minimum value of NN is 1 (of course). Increasing NN above 1 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance ** in exchange for a larger degradation in INSERT and UPDATE performance. ** The value of NN appears to give the best results overall. */ #define NN 1 /* Number of neighbors on either side of pPage */ #define NB (NN*2+1) /* Total pages involved in the balance */ #ifndef SQLITE_OMIT_QUICKBALANCE /* ** This version of balance() handles the common special case where ** a new entry is being inserted on the extreme right-end of the ** tree, in other words, when the new entry will become the largest ** entry in the tree. ** ** Instead of trying to balance the 3 right-most leaf pages, just add ** a new page to the right-hand side and put the one new entry in ** that page. This leaves the right side of the tree somewhat ** unbalanced. But odds are that we will be inserting new entries ** at the end soon afterwards so the nearly empty page will quickly ** fill up. On average. ** ** pPage is the leaf page which is the right-most page in the tree. ** pParent is its parent. pPage must have a single overflow entry ** which is also the right-most entry on the page. ** ** The pSpace buffer is used to store a temporary copy of the divider ** cell that will be inserted into pParent. Such a cell consists of a 4 ** byte page number followed by a variable length integer. In other ** words, at most 13 bytes. Hence the pSpace buffer must be at ** least 13 bytes in size. */ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ BtShared *const pBt = pPage->pBt; /* B-Tree Database */ MemPage *pNew; /* Newly allocated page */ int rc; /* Return Code */ Pgno pgnoNew; /* Page number of pNew */ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( sqlite3PagerIswriteable(pParent->pDbPage) ); assert( pPage->nOverflow==1 ); /* This error condition is now caught prior to reaching this function */ if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT; /* Allocate a new page. This page will become the right-sibling of ** pPage. Make the parent page writable, so that the new divider cell ** may be inserted. If both these operations are successful, proceed. */ rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); if( rc==SQLITE_OK ){ u8 *pOut = &pSpace[4]; u8 *pCell = pPage->apOvfl[0]; u16 szCell = pPage->xCellSize(pPage, pCell); u8 *pStop; assert( sqlite3PagerIswriteable(pNew->pDbPage) ); assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); rc = rebuildPage(pNew, 1, &pCell, &szCell); if( NEVER(rc) ) return rc; pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell; /* If this is an auto-vacuum database, update the pointer map ** with entries for the new page, and any pointer from the ** cell on the page to an overflow page. If either of these ** operations fails, the return code is set, but the contents ** of the parent page are still manipulated by thh code below. ** That is Ok, at this point the parent page is guaranteed to ** be marked as dirty. Returning an error code will cause a ** rollback, undoing any changes made to the parent page. */ if( ISAUTOVACUUM ){ ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); if( szCell>pNew->minLocal ){ ptrmapPutOvflPtr(pNew, pCell, &rc); } } /* Create a divider cell to insert into pParent. The divider cell ** consists of a 4-byte page number (the page number of pPage) and ** a variable length key value (which must be the same value as the ** largest key on pPage). ** ** To find the largest key value on pPage, first find the right-most ** cell on pPage. The first two fields of this cell are the ** record-length (a variable length integer at most 32-bits in size) ** and the key value (a variable length integer, may have any value). ** The first of the while(...) loops below skips over the record-length ** field. The second while(...) loop copies the key value from the ** cell on pPage into the pSpace buffer. */ pCell = findCell(pPage, pPage->nCell-1); pStop = &pCell[9]; while( (*(pCell++)&0x80) && pCell<pStop ); pStop = &pCell[9]; while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop ); /* Insert the new divider cell into pParent. */ if( rc==SQLITE_OK ){ insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace), 0, pPage->pgno, &rc); } /* Set the right-child pointer of pParent to point to the new page. */ put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); /* Release the reference to the new page. */ releasePage(pNew); } return rc; } #endif /* SQLITE_OMIT_QUICKBALANCE */ #if 0 /* ** This function does not contribute anything to the operation of SQLite. ** it is sometimes activated temporarily while debugging code responsible ** for setting pointer-map entries. */ static int ptrmapCheckPages(MemPage **apPage, int nPage){ int i, j; for(i=0; i<nPage; i++){ Pgno n; u8 e; MemPage *pPage = apPage[i]; BtShared *pBt = pPage->pBt; assert( pPage->isInit ); for(j=0; j<pPage->nCell; j++){ CellInfo info; u8 *z; z = findCell(pPage, j); pPage->xParseCell(pPage, z, &info); if( info.nLocal<info.nPayload ){ Pgno ovfl = get4byte(&z[info.nSize-4]); ptrmapGet(pBt, ovfl, &e, &n); assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 ); } if( !pPage->leaf ){ Pgno child = get4byte(z); ptrmapGet(pBt, child, &e, &n); assert( n==pPage->pgno && e==PTRMAP_BTREE ); } } if( !pPage->leaf ){ Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]); ptrmapGet(pBt, child, &e, &n); assert( n==pPage->pgno && e==PTRMAP_BTREE ); } } return 1; } #endif /* ** This function is used to copy the contents of the b-tree node stored ** on page pFrom to page pTo. If page pFrom was not a leaf page, then ** the pointer-map entries for each child page are updated so that the ** parent page stored in the pointer map is page pTo. If pFrom contained ** any cells with overflow page pointers, then the corresponding pointer ** map entries are also updated so that the parent page is page pTo. ** ** If pFrom is currently carrying any overflow cells (entries in the ** MemPage.apOvfl[] array), they are not copied to pTo. ** ** Before returning, page pTo is reinitialized using btreeInitPage(). ** ** The performance of this function is not critical. It is only used by ** the balance_shallower() and balance_deeper() procedures, neither of ** which are called often under normal circumstances. */ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ if( (*pRC)==SQLITE_OK ){ BtShared * const pBt = pFrom->pBt; u8 * const aFrom = pFrom->aData; u8 * const aTo = pTo->aData; int const iFromHdr = pFrom->hdrOffset; int const iToHdr = ((pTo->pgno==1) ? 100 : 0); int rc; int iData; assert( pFrom->isInit ); assert( pFrom->nFree>=iToHdr ); assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize ); /* Copy the b-tree node content from page pFrom to page pTo. */ iData = get2byte(&aFrom[iFromHdr+5]); memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); /* Reinitialize page pTo so that the contents of the MemPage structure ** match the new data. The initialization of pTo can actually fail under ** fairly obscure circumstances, even though it is a copy of initialized ** page pFrom. */ pTo->isInit = 0; rc = btreeInitPage(pTo); if( rc!=SQLITE_OK ){ *pRC = rc; return; } /* If this is an auto-vacuum database, update the pointer-map entries ** for any b-tree or overflow pages that pTo now contains the pointers to. */ if( ISAUTOVACUUM ){ *pRC = setChildPtrmaps(pTo); } } } /* ** This routine redistributes cells on the iParentIdx'th child of pParent ** (hereafter "the page") and up to 2 siblings so that all pages have about the ** same amount of free space. Usually a single sibling on either side of the ** page are used in the balancing, though both siblings might come from one ** side if the page is the first or last child of its parent. If the page ** has fewer than 2 siblings (something which can only happen if the page ** is a root page or a child of a root page) then all available siblings ** participate in the balancing. ** ** The number of siblings of the page might be increased or decreased by ** one or two in an effort to keep pages nearly full but not over full. ** ** Note that when this routine is called, some of the cells on the page ** might not actually be stored in MemPage.aData[]. This can happen ** if the page is overfull. This routine ensures that all cells allocated ** to the page and its siblings fit into MemPage.aData[] before returning. ** ** In the course of balancing the page and its siblings, cells may be ** inserted into or removed from the parent page (pParent). Doing so ** may cause the parent page to become overfull or underfull. If this ** happens, it is the responsibility of the caller to invoke the correct ** balancing routine to fix this problem (see the balance() routine). ** ** If this routine fails for any reason, it might leave the database ** in a corrupted state. So if this routine fails, the database should ** be rolled back. ** ** The third argument to this function, aOvflSpace, is a pointer to a ** buffer big enough to hold one page. If while inserting cells into the parent ** page (pParent) the parent page becomes overfull, this buffer is ** used to store the parent's overflow cells. Because this function inserts ** a maximum of four divider cells into the parent page, and the maximum ** size of a cell stored within an internal node is always less than 1/4 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large ** enough for all overflow cells. ** ** If aOvflSpace is set to a null pointer, this function returns ** SQLITE_NOMEM. */ static int balance_nonroot( MemPage *pParent, /* Parent page of siblings being balanced */ int iParentIdx, /* Index of "the page" in pParent */ u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ int isRoot, /* True if pParent is a root-page */ int bBulk /* True if this call is part of a bulk load */ ){ BtShared *pBt; /* The whole database */ int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ int nNew = 0; /* Number of pages in apNew[] */ int nOld; /* Number of pages in apOld[] */ int i, j, k; /* Loop counters */ int nxDiv; /* Next divider slot in pParent->aCell[] */ int rc = SQLITE_OK; /* The return code */ u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ int usableSpace; /* Bytes in pPage beyond the header */ int pageFlags; /* Value of pPage->aData[0] */ int iSpace1 = 0; /* First unused byte of aSpace1[] */ int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ int szScratch; /* Size of scratch memory requested */ MemPage *apOld[NB]; /* pPage and up to two siblings */ MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ u8 *pRight; /* Location in parent of right-sibling pointer */ u8 *apDiv[NB-1]; /* Divider cells in pParent */ int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */ int cntOld[NB+2]; /* Old index in b.apCell[] */ int szNew[NB+2]; /* Combined size of cells placed on i-th page */ u8 *aSpace1; /* Space for copies of dividers cells */ Pgno pgno; /* Temp var to store a page number in */ u8 abDone[NB+2]; /* True after i'th new page is populated */ Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */ Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */ u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */ CellArray b; /* Parsed information on cells being balanced */ memset(abDone, 0, sizeof(abDone)); b.nCell = 0; b.apCell = 0; pBt = pParent->pBt; assert( sqlite3_mutex_held(pBt->mutex) ); assert( sqlite3PagerIswriteable(pParent->pDbPage) ); #if 0 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); #endif /* At this point pParent may have at most one overflow cell. And if ** this overflow cell is present, it must be the cell with ** index iParentIdx. This scenario comes about when this function ** is called (indirectly) from sqlite3BtreeDelete(). */ assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); if( !aOvflSpace ){ return SQLITE_NOMEM_BKPT; } /* Find the sibling pages to balance. Also locate the cells in pParent ** that divide the siblings. An attempt is made to find NN siblings on ** either side of pPage. More siblings are taken from one side, however, ** if there are fewer than NN siblings on the other side. If pParent ** has NB or fewer children then all children of pParent are taken. ** ** This loop also drops the divider cells from the parent page. This ** way, the remainder of the function does not have to deal with any ** overflow cells in the parent page, since if any existed they will ** have already been removed. */ i = pParent->nOverflow + pParent->nCell; if( i<2 ){ nxDiv = 0; }else{ assert( bBulk==0 || bBulk==1 ); if( iParentIdx==0 ){ nxDiv = 0; }else if( iParentIdx==i ){ nxDiv = i-2+bBulk; }else{ nxDiv = iParentIdx-1; } i = 2-bBulk; } nOld = i+1; if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ pRight = &pParent->aData[pParent->hdrOffset+8]; }else{ pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); } pgno = get4byte(pRight); while( 1 ){ rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0); if( rc ){ memset(apOld, 0, (i+1)*sizeof(MemPage*)); goto balance_cleanup; } nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; if( (i--)==0 ) break; if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){ apDiv[i] = pParent->apOvfl[0]; pgno = get4byte(apDiv[i]); szNew[i] = pParent->xCellSize(pParent, apDiv[i]); pParent->nOverflow = 0; }else{ apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); pgno = get4byte(apDiv[i]); szNew[i] = pParent->xCellSize(pParent, apDiv[i]); /* Drop the cell from the parent page. apDiv[i] still points to ** the cell within the parent, even though it has been dropped. ** This is safe because dropping a cell only overwrites the first ** four bytes of it, and this function does not need the first ** four bytes of the divider cell. So the pointer is safe to use ** later on. ** ** But not if we are in secure-delete mode. In secure-delete mode, ** the dropCell() routine will overwrite the entire cell with zeroes. ** In this case, temporarily copy the cell into the aOvflSpace[] ** buffer. It will be copied out again as soon as the aSpace[] buffer ** is allocated. */ if( pBt->btsFlags & BTS_SECURE_DELETE ){ int iOff; iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); if( (iOff+szNew[i])>(int)pBt->usableSize ){ rc = SQLITE_CORRUPT_BKPT; memset(apOld, 0, (i+1)*sizeof(MemPage*)); goto balance_cleanup; }else{ memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; } } dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); } } /* Make nMaxCells a multiple of 4 in order to preserve 8-byte ** alignment */ nMaxCells = (nMaxCells + 3)&~3; /* ** Allocate space for memory structures */ szScratch = nMaxCells*sizeof(u8*) /* b.apCell */ + nMaxCells*sizeof(u16) /* b.szCell */ + pBt->pageSize; /* aSpace1 */ /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer ** that is more than 6 times the database page size. */ assert( szScratch<=6*(int)pBt->pageSize ); b.apCell = sqlite3ScratchMalloc( szScratch ); if( b.apCell==0 ){ rc = SQLITE_NOMEM_BKPT; goto balance_cleanup; } b.szCell = (u16*)&b.apCell[nMaxCells]; aSpace1 = (u8*)&b.szCell[nMaxCells]; assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); /* ** Load pointers to all cells on sibling pages and the divider cells ** into the local b.apCell[] array. Make copies of the divider cells ** into space obtained from aSpace1[]. The divider cells have already ** been removed from pParent. ** ** If the siblings are on leaf pages, then the child pointers of the ** divider cells are stripped from the cells before they are copied ** into aSpace1[]. In this way, all cells in b.apCell[] are without ** child pointers. If siblings are not leaves, then all cell in ** b.apCell[] include child pointers. Either way, all cells in b.apCell[] ** are alike. ** ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. ** leafData: 1 if pPage holds key+data and pParent holds only keys. */ b.pRef = apOld[0]; leafCorrection = b.pRef->leaf*4; leafData = b.pRef->intKeyLeaf; for(i=0; i<nOld; i++){ MemPage *pOld = apOld[i]; int limit = pOld->nCell; u8 *aData = pOld->aData; u16 maskPage = pOld->maskPage; u8 *piCell = aData + pOld->cellOffset; u8 *piEnd; /* Verify that all sibling pages are of the same "type" (table-leaf, ** table-interior, index-leaf, or index-interior). */ if( pOld->aData[0]!=apOld[0]->aData[0] ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } /* Load b.apCell[] with pointers to all cells in pOld. If pOld ** constains overflow cells, include them in the b.apCell[] array ** in the correct spot. ** ** Note that when there are multiple overflow cells, it is always the ** case that they are sequential and adjacent. This invariant arises ** because multiple overflows can only occurs when inserting divider ** cells into a parent on a prior balance, and divider cells are always ** adjacent and are inserted in order. There is an assert() tagged ** with "NOTE 1" in the overflow cell insertion loop to prove this ** invariant. ** ** This must be done in advance. Once the balance starts, the cell ** offset section of the btree page will be overwritten and we will no ** long be able to find the cells if a pointer to each cell is not saved ** first. */ memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow)); if( pOld->nOverflow>0 ){ limit = pOld->aiOvfl[0]; for(j=0; j<limit; j++){ b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); piCell += 2; b.nCell++; } for(k=0; k<pOld->nOverflow; k++){ assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */ b.apCell[b.nCell] = pOld->apOvfl[k]; b.nCell++; } } piEnd = aData + pOld->cellOffset + 2*pOld->nCell; while( piCell<piEnd ){ assert( b.nCell<nMaxCells ); b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); piCell += 2; b.nCell++; } cntOld[i] = b.nCell; if( i<nOld-1 && !leafData){ u16 sz = (u16)szNew[i]; u8 *pTemp; assert( b.nCell<nMaxCells ); b.szCell[b.nCell] = sz; pTemp = &aSpace1[iSpace1]; iSpace1 += sz; assert( sz<=pBt->maxLocal+23 ); assert( iSpace1 <= (int)pBt->pageSize ); memcpy(pTemp, apDiv[i], sz); b.apCell[b.nCell] = pTemp+leafCorrection; assert( leafCorrection==0 || leafCorrection==4 ); b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection; if( !pOld->leaf ){ assert( leafCorrection==0 ); assert( pOld->hdrOffset==0 ); /* The right pointer of the child page pOld becomes the left ** pointer of the divider cell */ memcpy(b.apCell[b.nCell], &pOld->aData[8], 4); }else{ assert( leafCorrection==4 ); while( b.szCell[b.nCell]<4 ){ /* Do not allow any cells smaller than 4 bytes. If a smaller cell ** does exist, pad it with 0x00 bytes. */ assert( b.szCell[b.nCell]==3 || CORRUPT_DB ); assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB ); aSpace1[iSpace1++] = 0x00; b.szCell[b.nCell]++; } } b.nCell++; } } /* ** Figure out the number of pages needed to hold all b.nCell cells. ** Store this number in "k". Also compute szNew[] which is the total ** size of all cells on the i-th page and cntNew[] which is the index ** in b.apCell[] of the cell that divides page i from page i+1. ** cntNew[k] should equal b.nCell. ** ** Values computed by this block: ** ** k: The total number of sibling pages ** szNew[i]: Spaced used on the i-th sibling page. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to ** the right of the i-th sibling page. ** usableSpace: Number of bytes of space available on each sibling. ** */ usableSpace = pBt->usableSize - 12 + leafCorrection; for(i=0; i<nOld; i++){ MemPage *p = apOld[i]; szNew[i] = usableSpace - p->nFree; for(j=0; j<p->nOverflow; j++){ szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]); } cntNew[i] = cntOld[i]; } k = nOld; for(i=0; i<k; i++){ int sz; while( szNew[i]>usableSpace ){ if( i+1>=k ){ k = i+2; if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } szNew[k-1] = 0; cntNew[k-1] = b.nCell; } sz = 2 + cachedCellSize(&b, cntNew[i]-1); szNew[i] -= sz; if( !leafData ){ if( cntNew[i]<b.nCell ){ sz = 2 + cachedCellSize(&b, cntNew[i]); }else{ sz = 0; } } szNew[i+1] += sz; cntNew[i]--; } while( cntNew[i]<b.nCell ){ sz = 2 + cachedCellSize(&b, cntNew[i]); if( szNew[i]+sz>usableSpace ) break; szNew[i] += sz; cntNew[i]++; if( !leafData ){ if( cntNew[i]<b.nCell ){ sz = 2 + cachedCellSize(&b, cntNew[i]); }else{ sz = 0; } } szNew[i+1] -= sz; } if( cntNew[i]>=b.nCell ){ k = i+1; }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } } /* ** The packing computed by the previous block is biased toward the siblings ** on the left side (siblings with smaller keys). The left siblings are ** always nearly full, while the right-most sibling might be nearly empty. ** The next block of code attempts to adjust the packing of siblings to ** get a better balance. ** ** This adjustment is more than an optimization. The packing above might ** be so out of balance as to be illegal. For example, the right-most ** sibling might be completely empty. This adjustment is not optional. */ for(i=k-1; i>0; i--){ int szRight = szNew[i]; /* Size of sibling on the right */ int szLeft = szNew[i-1]; /* Size of sibling on the left */ int r; /* Index of right-most cell in left sibling */ int d; /* Index of first cell to the left of right sibling */ r = cntNew[i-1] - 1; d = r + 1 - leafData; (void)cachedCellSize(&b, d); do{ assert( d<nMaxCells ); assert( r<nMaxCells ); (void)cachedCellSize(&b, r); if( szRight!=0 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){ break; } szRight += b.szCell[d] + 2; szLeft -= b.szCell[r] + 2; cntNew[i-1] = r; r--; d--; }while( r>=0 ); szNew[i] = szRight; szNew[i-1] = szLeft; if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } } /* Sanity check: For a non-corrupt database file one of the follwing ** must be true: ** (1) We found one or more cells (cntNew[0])>0), or ** (2) pPage is a virtual root page. A virtual root page is when ** the real root page is page 1 and we are the only child of ** that page. */ assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB); TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n", apOld[0]->pgno, apOld[0]->nCell, nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0, nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0 )); /* ** Allocate k new pages. Reuse old pages where possible. */ pageFlags = apOld[0]->aData[0]; for(i=0; i<k; i++){ MemPage *pNew; if( i<nOld ){ pNew = apNew[i] = apOld[i]; apOld[i] = 0; rc = sqlite3PagerWrite(pNew->pDbPage); nNew++; if( rc ) goto balance_cleanup; }else{ assert( i>0 ); rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); if( rc ) goto balance_cleanup; zeroPage(pNew, pageFlags); apNew[i] = pNew; nNew++; cntOld[i] = b.nCell; /* Set the pointer-map entry for the new sibling page. */ if( ISAUTOVACUUM ){ ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); if( rc!=SQLITE_OK ){ goto balance_cleanup; } } } } /* ** Reassign page numbers so that the new pages are in ascending order. ** This helps to keep entries in the disk file in order so that a scan ** of the table is closer to a linear scan through the file. That in turn ** helps the operating system to deliver pages from the disk more rapidly. ** ** An O(n^2) insertion sort algorithm is used, but since n is never more ** than (NB+2) (a small constant), that should not be a problem. ** ** When NB==3, this one optimization makes the database about 25% faster ** for large insertions and deletions. */ for(i=0; i<nNew; i++){ aPgOrder[i] = aPgno[i] = apNew[i]->pgno; aPgFlags[i] = apNew[i]->pDbPage->flags; for(j=0; j<i; j++){ if( aPgno[j]==aPgno[i] ){ /* This branch is taken if the set of sibling pages somehow contains ** duplicate entries. This can happen if the database is corrupt. ** It would be simpler to detect this as part of the loop below, but ** we do the detection here in order to avoid populating the pager ** cache with two separate objects associated with the same ** page number. */ assert( CORRUPT_DB ); rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } } } for(i=0; i<nNew; i++){ int iBest = 0; /* aPgno[] index of page number to use */ for(j=1; j<nNew; j++){ if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j; } pgno = aPgOrder[iBest]; aPgOrder[iBest] = 0xffffffff; if( iBest!=i ){ if( iBest>i ){ sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0); } sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]); apNew[i]->pgno = pgno; } } TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) " "%d(%d nc=%d) %d(%d nc=%d)\n", apNew[0]->pgno, szNew[0], cntNew[0], nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0, nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0, nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0, nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0, nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0 )); assert( sqlite3PagerIswriteable(pParent->pDbPage) ); put4byte(pRight, apNew[nNew-1]->pgno); /* If the sibling pages are not leaves, ensure that the right-child pointer ** of the right-most new sibling page is set to the value that was ** originally in the same field of the right-most old sibling page. */ if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){ MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); } /* Make any required updates to pointer map entries associated with ** cells stored on sibling pages following the balance operation. Pointer ** map entries associated with divider cells are set by the insertCell() ** routine. The associated pointer map entries are: ** ** a) if the cell contains a reference to an overflow chain, the ** entry associated with the first page in the overflow chain, and ** ** b) if the sibling pages are not leaves, the child page associated ** with the cell. ** ** If the sibling pages are not leaves, then the pointer map entry ** associated with the right-child of each sibling may also need to be ** updated. This happens below, after the sibling pages have been ** populated, not here. */ if( ISAUTOVACUUM ){ MemPage *pNew = apNew[0]; u8 *aOld = pNew->aData; int cntOldNext = pNew->nCell + pNew->nOverflow; int usableSize = pBt->usableSize; int iNew = 0; int iOld = 0; for(i=0; i<b.nCell; i++){ u8 *pCell = b.apCell[i]; if( i==cntOldNext ){ MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld]; cntOldNext += pOld->nCell + pOld->nOverflow + !leafData; aOld = pOld->aData; } if( i==cntNew[iNew] ){ pNew = apNew[++iNew]; if( !leafData ) continue; } /* Cell pCell is destined for new sibling page pNew. Originally, it ** was either part of sibling page iOld (possibly an overflow cell), ** or else the divider cell to the left of sibling page iOld. So, ** if sibling page iOld had the same page number as pNew, and if ** pCell really was a part of sibling page iOld (not a divider or ** overflow cell), we can skip updating the pointer map entries. */ if( iOld>=nNew || pNew->pgno!=aPgno[iOld] || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize]) ){ if( !leafCorrection ){ ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc); } if( cachedCellSize(&b,i)>pNew->minLocal ){ ptrmapPutOvflPtr(pNew, pCell, &rc); } if( rc ) goto balance_cleanup; } } } /* Insert new divider cells into pParent. */ for(i=0; i<nNew-1; i++){ u8 *pCell; u8 *pTemp; int sz; MemPage *pNew = apNew[i]; j = cntNew[i]; assert( j<nMaxCells ); assert( b.apCell[j]!=0 ); pCell = b.apCell[j]; sz = b.szCell[j] + leafCorrection; pTemp = &aOvflSpace[iOvflSpace]; if( !pNew->leaf ){ memcpy(&pNew->aData[8], pCell, 4); }else if( leafData ){ /* If the tree is a leaf-data tree, and the siblings are leaves, ** then there is no divider cell in b.apCell[]. Instead, the divider ** cell consists of the integer key for the right-most cell of ** the sibling-page assembled above only. */ CellInfo info; j--; pNew->xParseCell(pNew, b.apCell[j], &info); pCell = pTemp; sz = 4 + putVarint(&pCell[4], info.nKey); pTemp = 0; }else{ pCell -= 4; /* Obscure case for non-leaf-data trees: If the cell at pCell was ** previously stored on a leaf node, and its reported size was 4 ** bytes, then it may actually be smaller than this ** (see btreeParseCellPtr(), 4 bytes is the minimum size of ** any cell). But it is important to pass the correct size to ** insertCell(), so reparse the cell now. ** ** This can only happen for b-trees used to evaluate "IN (SELECT ...)" ** and WITHOUT ROWID tables with exactly one column which is the ** primary key. */ if( b.szCell[j]==4 ){ assert(leafCorrection==4); sz = pParent->xCellSize(pParent, pCell); } } iOvflSpace += sz; assert( sz<=pBt->maxLocal+23 ); assert( iOvflSpace <= (int)pBt->pageSize ); insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc); if( rc!=SQLITE_OK ) goto balance_cleanup; assert( sqlite3PagerIswriteable(pParent->pDbPage) ); } /* Now update the actual sibling pages. The order in which they are updated ** is important, as this code needs to avoid disrupting any page from which ** cells may still to be read. In practice, this means: ** ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1]) ** then it is not safe to update page apNew[iPg] until after ** the left-hand sibling apNew[iPg-1] has been updated. ** ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1]) ** then it is not safe to update page apNew[iPg] until after ** the right-hand sibling apNew[iPg+1] has been updated. ** ** If neither of the above apply, the page is safe to update. ** ** The iPg value in the following loop starts at nNew-1 goes down ** to 0, then back up to nNew-1 again, thus making two passes over ** the pages. On the initial downward pass, only condition (1) above ** needs to be tested because (2) will always be true from the previous ** step. On the upward pass, both conditions are always true, so the ** upwards pass simply processes pages that were missed on the downward ** pass. */ for(i=1-nNew; i<nNew; i++){ int iPg = i<0 ? -i : i; assert( iPg>=0 && iPg<nNew ); if( abDone[iPg] ) continue; /* Skip pages already processed */ if( i>=0 /* On the upwards pass, or... */ || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */ ){ int iNew; int iOld; int nNewCell; /* Verify condition (1): If cells are moving left, update iPg ** only after iPg-1 has already been updated. */ assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] ); /* Verify condition (2): If cells are moving right, update iPg ** only after iPg+1 has already been updated. */ assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] ); if( iPg==0 ){ iNew = iOld = 0; nNewCell = cntNew[0]; }else{ iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell; iNew = cntNew[iPg-1] + !leafData; nNewCell = cntNew[iPg] - iNew; } rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b); if( rc ) goto balance_cleanup; abDone[iPg]++; apNew[iPg]->nFree = usableSpace-szNew[iPg]; assert( apNew[iPg]->nOverflow==0 ); assert( apNew[iPg]->nCell==nNewCell ); } } /* All pages have been processed exactly once */ assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 ); assert( nOld>0 ); assert( nNew>0 ); if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ /* The root page of the b-tree now contains no cells. The only sibling ** page is the right-child of the parent. Copy the contents of the ** child page into the parent, decreasing the overall height of the ** b-tree structure by one. This is described as the "balance-shallower" ** sub-algorithm in some documentation. ** ** If this is an auto-vacuum database, the call to copyNodeContent() ** sets all pointer-map entries corresponding to database image pages ** for which the pointer is stored within the content being copied. ** ** It is critical that the child page be defragmented before being ** copied into the parent, because if the parent is page 1 then it will ** by smaller than the child due to the database header, and so all the ** free space needs to be up front. */ assert( nNew==1 || CORRUPT_DB ); rc = defragmentPage(apNew[0]); testcase( rc!=SQLITE_OK ); assert( apNew[0]->nFree == (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) || rc!=SQLITE_OK ); copyNodeContent(apNew[0], pParent, &rc); freePage(apNew[0], &rc); }else if( ISAUTOVACUUM && !leafCorrection ){ /* Fix the pointer map entries associated with the right-child of each ** sibling page. All other pointer map entries have already been taken ** care of. */ for(i=0; i<nNew; i++){ u32 key = get4byte(&apNew[i]->aData[8]); ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc); } } assert( pParent->isInit ); TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n", nOld, nNew, b.nCell)); /* Free any old pages that were not reused as new pages. */ for(i=nNew; i<nOld; i++){ freePage(apOld[i], &rc); } #if 0 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){ /* The ptrmapCheckPages() contains assert() statements that verify that ** all pointer map pages are set correctly. This is helpful while ** debugging. This is usually disabled because a corrupt database may ** cause an assert() statement to fail. */ ptrmapCheckPages(apNew, nNew); ptrmapCheckPages(&pParent, 1); } #endif /* ** Cleanup before returning. */ balance_cleanup: sqlite3ScratchFree(b.apCell); for(i=0; i<nOld; i++){ releasePage(apOld[i]); } for(i=0; i<nNew; i++){ releasePage(apNew[i]); } return rc; } /* ** This function is called when the root page of a b-tree structure is ** overfull (has one or more overflow pages). ** ** A new child page is allocated and the contents of the current root ** page, including overflow cells, are copied into the child. The root ** page is then overwritten to make it an empty page with the right-child ** pointer pointing to the new page. ** ** Before returning, all pointer-map entries corresponding to pages ** that the new child-page now contains pointers to are updated. The ** entry corresponding to the new right-child pointer of the root ** page is also updated. ** ** If successful, *ppChild is set to contain a reference to the child ** page and SQLITE_OK is returned. In this case the caller is required ** to call releasePage() on *ppChild exactly once. If an error occurs, ** an error code is returned and *ppChild is set to 0. */ static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ int rc; /* Return value from subprocedures */ MemPage *pChild = 0; /* Pointer to a new child page */ Pgno pgnoChild = 0; /* Page number of the new child page */ BtShared *pBt = pRoot->pBt; /* The BTree */ assert( pRoot->nOverflow>0 ); assert( sqlite3_mutex_held(pBt->mutex) ); /* Make pRoot, the root page of the b-tree, writable. Allocate a new ** page that will become the new right-child of pPage. Copy the contents ** of the node stored on pRoot into the new child page. */ rc = sqlite3PagerWrite(pRoot->pDbPage); if( rc==SQLITE_OK ){ rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); copyNodeContent(pRoot, pChild, &rc); if( ISAUTOVACUUM ){ ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc); } } if( rc ){ *ppChild = 0; releasePage(pChild); return rc; } assert( sqlite3PagerIswriteable(pChild->pDbPage) ); assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); assert( pChild->nCell==pRoot->nCell ); TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); /* Copy the overflow cells from pRoot to pChild */ memcpy(pChild->aiOvfl, pRoot->aiOvfl, pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); memcpy(pChild->apOvfl, pRoot->apOvfl, pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); pChild->nOverflow = pRoot->nOverflow; /* Zero the contents of pRoot. Then install pChild as the right-child. */ zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); *ppChild = pChild; return SQLITE_OK; } /* ** The page that pCur currently points to has just been modified in ** some way. This function figures out if this modification means the ** tree needs to be balanced, and if so calls the appropriate balancing ** routine. Balancing routines are: ** ** balance_quick() ** balance_deeper() ** balance_nonroot() */ static int balance(BtCursor *pCur){ int rc = SQLITE_OK; const int nMin = pCur->pBt->usableSize * 2 / 3; u8 aBalanceQuickSpace[13]; u8 *pFree = 0; VVA_ONLY( int balance_quick_called = 0 ); VVA_ONLY( int balance_deeper_called = 0 ); do { int iPage = pCur->iPage; MemPage *pPage = pCur->apPage[iPage]; if( iPage==0 ){ if( pPage->nOverflow ){ /* The root page of the b-tree is overfull. In this case call the ** balance_deeper() function to create a new child for the root-page ** and copy the current contents of the root-page to it. The ** next iteration of the do-loop will balance the child page. */ assert( balance_deeper_called==0 ); VVA_ONLY( balance_deeper_called++ ); rc = balance_deeper(pPage, &pCur->apPage[1]); if( rc==SQLITE_OK ){ pCur->iPage = 1; pCur->aiIdx[0] = 0; pCur->aiIdx[1] = 0; assert( pCur->apPage[1]->nOverflow ); } }else{ break; } }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ break; }else{ MemPage * const pParent = pCur->apPage[iPage-1]; int const iIdx = pCur->aiIdx[iPage-1]; rc = sqlite3PagerWrite(pParent->pDbPage); if( rc==SQLITE_OK ){ #ifndef SQLITE_OMIT_QUICKBALANCE if( pPage->intKeyLeaf && pPage->nOverflow==1 && pPage->aiOvfl[0]==pPage->nCell && pParent->pgno!=1 && pParent->nCell==iIdx ){ /* Call balance_quick() to create a new sibling of pPage on which ** to store the overflow cell. balance_quick() inserts a new cell ** into pParent, which may cause pParent overflow. If this ** happens, the next iteration of the do-loop will balance pParent ** use either balance_nonroot() or balance_deeper(). Until this ** happens, the overflow cell is stored in the aBalanceQuickSpace[] ** buffer. ** ** The purpose of the following assert() is to check that only a ** single call to balance_quick() is made for each call to this ** function. If this were not verified, a subtle bug involving reuse ** of the aBalanceQuickSpace[] might sneak in. */ assert( balance_quick_called==0 ); VVA_ONLY( balance_quick_called++ ); rc = balance_quick(pParent, pPage, aBalanceQuickSpace); }else #endif { /* In this case, call balance_nonroot() to redistribute cells ** between pPage and up to 2 of its sibling pages. This involves ** modifying the contents of pParent, which may cause pParent to ** become overfull or underfull. The next iteration of the do-loop ** will balance the parent page to correct this. ** ** If the parent page becomes overfull, the overflow cell or cells ** are stored in the pSpace buffer allocated immediately below. ** A subsequent iteration of the do-loop will deal with this by ** calling balance_nonroot() (balance_deeper() may be called first, ** but it doesn't deal with overflow cells - just moves them to a ** different page). Once this subsequent call to balance_nonroot() ** has completed, it is safe to release the pSpace buffer used by ** the previous call, as the overflow cell data will have been ** copied either into the body of a database page or into the new ** pSpace buffer passed to the latter call to balance_nonroot(). */ u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints&BTREE_BULKLOAD); if( pFree ){ /* If pFree is not NULL, it points to the pSpace buffer used ** by a previous call to balance_nonroot(). Its contents are ** now stored either on real database pages or within the ** new pSpace buffer, so it may be safely freed here. */ sqlite3PageFree(pFree); } /* The pSpace buffer will be freed after the next call to ** balance_nonroot(), or just before this function returns, whichever ** comes first. */ pFree = pSpace; } } pPage->nOverflow = 0; /* The next iteration of the do-loop balances the parent page. */ releasePage(pPage); pCur->iPage--; assert( pCur->iPage>=0 ); } }while( rc==SQLITE_OK ); if( pFree ){ sqlite3PageFree(pFree); } return rc; } /* ** Insert a new record into the BTree. The content of the new record ** is described by the pX object. The pCur cursor is used only to ** define what table the record should be inserted into, and is left ** pointing at a random location. ** ** For a table btree (used for rowid tables), only the pX.nKey value of ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields ** hold the content of the row. ** ** For an index btree (used for indexes and WITHOUT ROWID tables), the ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The ** pX.pData,nData,nZero fields must be zero. ** ** If the seekResult parameter is non-zero, then a successful call to ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already ** been performed. In other words, if seekResult!=0 then the cursor ** is currently pointing to a cell that will be adjacent to the cell ** to be inserted. If seekResult<0 then pCur points to a cell that is ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell ** that is larger than (pKey,nKey). ** ** If seekResult==0, that means pCur is pointing at some unknown location. ** In that case, this routine must seek the cursor to the correct insertion ** point for (pKey,nKey) before doing the insertion. For index btrees, ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked ** key values and pX->aMem can be used instead of pX->pKey to avoid having ** to decode the key. */ SQLITE_PRIVATE int sqlite3BtreeInsert( BtCursor *pCur, /* Insert data into the table of this cursor */ const BtreePayload *pX, /* Content of the row to be inserted */ int flags, /* True if this is likely an append */ int seekResult /* Result of prior MovetoUnpacked() call */ ){ int rc; int loc = seekResult; /* -1: before desired location +1: after */ int szNew = 0; int idx; MemPage *pPage; Btree *p = pCur->pBtree; BtShared *pBt = p->pBt; unsigned char *oldCell; unsigned char *newCell = 0; assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags ); if( pCur->eState==CURSOR_FAULT ){ assert( pCur->skipNext!=SQLITE_OK ); return pCur->skipNext; } assert( cursorOwnsBtShared(pCur) ); assert( (pCur->curFlags & BTCF_WriteFlag)!=0 && pBt->inTransaction==TRANS_WRITE && (pBt->btsFlags & BTS_READ_ONLY)==0 ); assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); /* Assert that the caller has been consistent. If this cursor was opened ** expecting an index b-tree, then the caller should be inserting blob ** keys with no associated data. If the cursor was opened expecting an ** intkey table, the caller should be inserting integer keys with a ** blob of associated data. */ assert( (pX->pKey==0)==(pCur->pKeyInfo==0) ); /* Save the positions of any other cursors open on this table. ** ** In some cases, the call to btreeMoveto() below is a no-op. For ** example, when inserting data into a table with auto-generated integer ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the ** integer key to use. It then calls this function to actually insert the ** data into the intkey B-Tree. In this case btreeMoveto() recognizes ** that the cursor is already where it needs to be and returns without ** doing any work. To avoid thwarting these optimizations, it is important ** not to clear the cursor here. */ if( pCur->curFlags & BTCF_Multiple ){ rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); if( rc ) return rc; } if( pCur->pKeyInfo==0 ){ assert( pX->pKey==0 ); /* If this is an insert into a table b-tree, invalidate any incrblob ** cursors open on the row being replaced */ invalidateIncrblobCursors(p, pX->nKey, 0); /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing ** to a row with the same key as the new entry being inserted. */ assert( (flags & BTREE_SAVEPOSITION)==0 || ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) ); /* If the cursor is currently on the last row and we are appending a ** new row onto the end, set the "loc" to avoid an unnecessary ** btreeMoveto() call */ if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){ loc = 0; }else if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0 && pCur->info.nKey==pX->nKey-1 ){ loc = -1; }else if( loc==0 ){ rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc); if( rc ) return rc; } }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){ if( pX->nMem ){ UnpackedRecord r; r.pKeyInfo = pCur->pKeyInfo; r.aMem = pX->aMem; r.nField = pX->nMem; r.default_rc = 0; r.errCode = 0; r.r1 = 0; r.r2 = 0; r.eqSeen = 0; rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc); }else{ rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc); } if( rc ) return rc; } assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); pPage = pCur->apPage[pCur->iPage]; assert( pPage->intKey || pX->nKey>=0 ); assert( pPage->leaf || !pPage->intKey ); TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno, loc==0 ? "overwrite" : "new entry")); assert( pPage->isInit ); newCell = pBt->pTmpSpace; assert( newCell!=0 ); rc = fillInCell(pPage, newCell, pX, &szNew); if( rc ) goto end_insert; assert( szNew==pPage->xCellSize(pPage, newCell) ); assert( szNew <= MX_CELL_SIZE(pBt) ); idx = pCur->aiIdx[pCur->iPage]; if( loc==0 ){ CellInfo info; assert( idx<pPage->nCell ); rc = sqlite3PagerWrite(pPage->pDbPage); if( rc ){ goto end_insert; } oldCell = findCell(pPage, idx); if( !pPage->leaf ){ memcpy(newCell, oldCell, 4); } rc = clearCell(pPage, oldCell, &info); if( info.nSize==szNew && info.nLocal==info.nPayload ){ /* Overwrite the old cell with the new if they are the same size. ** We could also try to do this if the old cell is smaller, then add ** the leftover space to the free list. But experiments show that ** doing that is no faster then skipping this optimization and just ** calling dropCell() and insertCell(). */ assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */ if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT; memcpy(oldCell, newCell, szNew); return SQLITE_OK; } dropCell(pPage, idx, info.nSize, &rc); if( rc ) goto end_insert; }else if( loc<0 && pPage->nCell>0 ){ assert( pPage->leaf ); idx = ++pCur->aiIdx[pCur->iPage]; }else{ assert( pPage->leaf ); } insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); assert( pPage->nOverflow==0 || rc==SQLITE_OK ); assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); /* If no error has occurred and pPage has an overflow cell, call balance() ** to redistribute the cells within the tree. Since balance() may move ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey ** variables. ** ** Previous versions of SQLite called moveToRoot() to move the cursor ** back to the root page as balance() used to invalidate the contents ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, ** set the cursor state to "invalid". This makes common insert operations ** slightly faster. ** ** There is a subtle but important optimization here too. When inserting ** multiple records into an intkey b-tree using a single cursor (as can ** happen while processing an "INSERT INTO ... SELECT" statement), it ** is advantageous to leave the cursor pointing to the last entry in ** the b-tree if possible. If the cursor is left pointing to the last ** entry in the table, and the next row inserted has an integer key ** larger than the largest existing key, it is possible to insert the ** row without seeking the cursor. This can be a big performance boost. */ pCur->info.nSize = 0; if( pPage->nOverflow ){ assert( rc==SQLITE_OK ); pCur->curFlags &= ~(BTCF_ValidNKey); rc = balance(pCur); /* Must make sure nOverflow is reset to zero even if the balance() ** fails. Internal data structure corruption will result otherwise. ** Also, set the cursor state to invalid. This stops saveCursorPosition() ** from trying to save the current position of the cursor. */ pCur->apPage[pCur->iPage]->nOverflow = 0; pCur->eState = CURSOR_INVALID; if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){ rc = moveToRoot(pCur); if( pCur->pKeyInfo ){ assert( pCur->pKey==0 ); pCur->pKey = sqlite3Malloc( pX->nKey ); if( pCur->pKey==0 ){ rc = SQLITE_NOMEM; }else{ memcpy(pCur->pKey, pX->pKey, pX->nKey); } } pCur->eState = CURSOR_REQUIRESEEK; pCur->nKey = pX->nKey; } } assert( pCur->apPage[pCur->iPage]->nOverflow==0 ); end_insert: return rc; } /* ** Delete the entry that the cursor is pointing to. ** ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then ** the cursor is left pointing at an arbitrary location after the delete. ** But if that bit is set, then the cursor is left in a state such that ** the next call to BtreeNext() or BtreePrev() moves it to the same row ** as it would have been on if the call to BtreeDelete() had been omitted. ** ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes ** associated with a single table entry and its indexes. Only one of those ** deletes is considered the "primary" delete. The primary delete occurs ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation, ** but which might be used by alternative storage engines. */ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ Btree *p = pCur->pBtree; BtShared *pBt = p->pBt; int rc; /* Return code */ MemPage *pPage; /* Page to delete cell from */ unsigned char *pCell; /* Pointer to cell to delete */ int iCellIdx; /* Index of cell to delete */ int iCellDepth; /* Depth of node containing pCell */ CellInfo info; /* Size of the cell being deleted */ int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */ u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */ assert( cursorOwnsBtShared(pCur) ); assert( pBt->inTransaction==TRANS_WRITE ); assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); assert( pCur->curFlags & BTCF_WriteFlag ); assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); assert( !hasReadConflicts(p, pCur->pgnoRoot) ); assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); assert( pCur->eState==CURSOR_VALID ); assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 ); iCellDepth = pCur->iPage; iCellIdx = pCur->aiIdx[iCellDepth]; pPage = pCur->apPage[iCellDepth]; pCell = findCell(pPage, iCellIdx); /* If the bPreserve flag is set to true, then the cursor position must ** be preserved following this delete operation. If the current delete ** will cause a b-tree rebalance, then this is done by saving the cursor ** key and leaving the cursor in CURSOR_REQUIRESEEK state before ** returning. ** ** Or, if the current delete will not cause a rebalance, then the cursor ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately ** before or after the deleted entry. In this case set bSkipnext to true. */ if( bPreserve ){ if( !pPage->leaf || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3) ){ /* A b-tree rebalance will be required after deleting this entry. ** Save the cursor key. */ rc = saveCursorKey(pCur); if( rc ) return rc; }else{ bSkipnext = 1; } } /* If the page containing the entry to delete is not a leaf page, move ** the cursor to the largest entry in the tree that is smaller than ** the entry being deleted. This cell will replace the cell being deleted ** from the internal node. The 'previous' entry is used for this instead ** of the 'next' entry, as the previous entry is always a part of the ** sub-tree headed by the child page of the cell being deleted. This makes ** balancing the tree following the delete operation easier. */ if( !pPage->leaf ){ int notUsed = 0; rc = sqlite3BtreePrevious(pCur, &notUsed); if( rc ) return rc; } /* Save the positions of any other cursors open on this table before ** making any modifications. */ if( pCur->curFlags & BTCF_Multiple ){ rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); if( rc ) return rc; } /* If this is a delete operation to remove a row from a table b-tree, ** invalidate any incrblob cursors open on the row being deleted. */ if( pCur->pKeyInfo==0 ){ invalidateIncrblobCursors(p, pCur->info.nKey, 0); } /* Make the page containing the entry to be deleted writable. Then free any ** overflow pages associated with the entry and finally remove the cell ** itself from within the page. */ rc = sqlite3PagerWrite(pPage->pDbPage); if( rc ) return rc; rc = clearCell(pPage, pCell, &info); dropCell(pPage, iCellIdx, info.nSize, &rc); if( rc ) return rc; /* If the cell deleted was not located on a leaf page, then the cursor ** is currently pointing to the largest entry in the sub-tree headed ** by the child-page of the cell that was just deleted from an internal ** node. The cell from the leaf node needs to be moved to the internal ** node to replace the deleted cell. */ if( !pPage->leaf ){ MemPage *pLeaf = pCur->apPage[pCur->iPage]; int nCell; Pgno n = pCur->apPage[iCellDepth+1]->pgno; unsigned char *pTmp; pCell = findCell(pLeaf, pLeaf->nCell-1); if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT; nCell = pLeaf->xCellSize(pLeaf, pCell); assert( MX_CELL_SIZE(pBt) >= nCell ); pTmp = pBt->pTmpSpace; assert( pTmp!=0 ); rc = sqlite3PagerWrite(pLeaf->pDbPage); if( rc==SQLITE_OK ){ insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); } dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); if( rc ) return rc; } /* Balance the tree. If the entry deleted was located on a leaf page, ** then the cursor still points to that page. In this case the first ** call to balance() repairs the tree, and the if(...) condition is ** never true. ** ** Otherwise, if the entry deleted was on an internal node page, then ** pCur is pointing to the leaf page from which a cell was removed to ** replace the cell deleted from the internal node. This is slightly ** tricky as the leaf node may be underfull, and the internal node may ** be either under or overfull. In this case run the balancing algorithm ** on the leaf node first. If the balance proceeds far enough up the ** tree that we can be sure that any problem in the internal node has ** been corrected, so be it. Otherwise, after balancing the leaf node, ** walk the cursor up the tree to the internal node and balance it as ** well. */ rc = balance(pCur); if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ while( pCur->iPage>iCellDepth ){ releasePage(pCur->apPage[pCur->iPage--]); } rc = balance(pCur); } if( rc==SQLITE_OK ){ if( bSkipnext ){ assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) ); assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB ); assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell ); pCur->eState = CURSOR_SKIPNEXT; if( iCellIdx>=pPage->nCell ){ pCur->skipNext = -1; pCur->aiIdx[iCellDepth] = pPage->nCell-1; }else{ pCur->skipNext = 1; } }else{ rc = moveToRoot(pCur); if( bPreserve ){ pCur->eState = CURSOR_REQUIRESEEK; } } } return rc; } /* ** Create a new BTree table. Write into *piTable the page ** number for the root page of the new table. ** ** The type of type is determined by the flags parameter. Only the ** following values of flags are currently in use. Other values for ** flags might not work: ** ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys ** BTREE_ZERODATA Used for SQL indices */ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ BtShared *pBt = p->pBt; MemPage *pRoot; Pgno pgnoRoot; int rc; int ptfFlags; /* Page-type flage for the root page of new table */ assert( sqlite3BtreeHoldsMutex(p) ); assert( pBt->inTransaction==TRANS_WRITE ); assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); #ifdef SQLITE_OMIT_AUTOVACUUM rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); if( rc ){ return rc; } #else if( pBt->autoVacuum ){ Pgno pgnoMove; /* Move a page here to make room for the root-page */ MemPage *pPageMove; /* The page to move to. */ /* Creating a new table may probably require moving an existing database ** to make room for the new tables root page. In case this page turns ** out to be an overflow page, delete all overflow page-map caches ** held by open cursors. */ invalidateAllOverflowCache(pBt); /* Read the value of meta[3] from the database to determine where the ** root page of the new table should go. meta[3] is the largest root-page ** created so far, so the new root-page is (meta[3]+1). */ sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); pgnoRoot++; /* The new root-page may not be allocated on a pointer-map page, or the ** PENDING_BYTE page. */ while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ pgnoRoot++; } assert( pgnoRoot>=3 || CORRUPT_DB ); testcase( pgnoRoot<3 ); /* Allocate a page. The page that currently resides at pgnoRoot will ** be moved to the allocated page (unless the allocated page happens ** to reside at pgnoRoot). */ rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); if( rc!=SQLITE_OK ){ return rc; } if( pgnoMove!=pgnoRoot ){ /* pgnoRoot is the page that will be used for the root-page of ** the new table (assuming an error did not occur). But we were ** allocated pgnoMove. If required (i.e. if it was not allocated ** by extending the file), the current page at position pgnoMove ** is already journaled. */ u8 eType = 0; Pgno iPtrPage = 0; /* Save the positions of any open cursors. This is required in ** case they are holding a reference to an xFetch reference ** corresponding to page pgnoRoot. */ rc = saveAllCursors(pBt, 0, 0); releasePage(pPageMove); if( rc!=SQLITE_OK ){ return rc; } /* Move the page currently at pgnoRoot to pgnoMove. */ rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); if( rc!=SQLITE_OK ){ return rc; } rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ rc = SQLITE_CORRUPT_BKPT; } if( rc!=SQLITE_OK ){ releasePage(pRoot); return rc; } assert( eType!=PTRMAP_ROOTPAGE ); assert( eType!=PTRMAP_FREEPAGE ); rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); releasePage(pRoot); /* Obtain the page at pgnoRoot */ if( rc!=SQLITE_OK ){ return rc; } rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); if( rc!=SQLITE_OK ){ return rc; } rc = sqlite3PagerWrite(pRoot->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pRoot); return rc; } }else{ pRoot = pPageMove; } /* Update the pointer-map and meta-data with the new root-page number. */ ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc); if( rc ){ releasePage(pRoot); return rc; } /* When the new root page was allocated, page 1 was made writable in ** order either to increase the database filesize, or to decrement the ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. */ assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); if( NEVER(rc) ){ releasePage(pRoot); return rc; } }else{ rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); if( rc ) return rc; } #endif assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); if( createTabFlags & BTREE_INTKEY ){ ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; }else{ ptfFlags = PTF_ZERODATA | PTF_LEAF; } zeroPage(pRoot, ptfFlags); sqlite3PagerUnref(pRoot->pDbPage); assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); *piTable = (int)pgnoRoot; return SQLITE_OK; } SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ int rc; sqlite3BtreeEnter(p); rc = btreeCreateTable(p, piTable, flags); sqlite3BtreeLeave(p); return rc; } /* ** Erase the given database page and all its children. Return ** the page to the freelist. */ static int clearDatabasePage( BtShared *pBt, /* The BTree that contains the table */ Pgno pgno, /* Page number to clear */ int freePageFlag, /* Deallocate page if true */ int *pnChange /* Add number of Cells freed to this counter */ ){ MemPage *pPage; int rc; unsigned char *pCell; int i; int hdr; CellInfo info; assert( sqlite3_mutex_held(pBt->mutex) ); if( pgno>btreePagecount(pBt) ){ return SQLITE_CORRUPT_BKPT; } rc = getAndInitPage(pBt, pgno, &pPage, 0, 0); if( rc ) return rc; if( pPage->bBusy ){ rc = SQLITE_CORRUPT_BKPT; goto cleardatabasepage_out; } pPage->bBusy = 1; hdr = pPage->hdrOffset; for(i=0; i<pPage->nCell; i++){ pCell = findCell(pPage, i); if( !pPage->leaf ){ rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); if( rc ) goto cleardatabasepage_out; } rc = clearCell(pPage, pCell, &info); if( rc ) goto cleardatabasepage_out; } if( !pPage->leaf ){ rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange); if( rc ) goto cleardatabasepage_out; }else if( pnChange ){ assert( pPage->intKey || CORRUPT_DB ); testcase( !pPage->intKey ); *pnChange += pPage->nCell; } if( freePageFlag ){ freePage(pPage, &rc); }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); } cleardatabasepage_out: pPage->bBusy = 0; releasePage(pPage); return rc; } /* ** Delete all information from a single table in the database. iTable is ** the page number of the root of the table. After this routine returns, ** the root page is empty, but still exists. ** ** This routine will fail with SQLITE_LOCKED if there are any open ** read cursors on the table. Open write cursors are moved to the ** root of the table. ** ** If pnChange is not NULL, then table iTable must be an intkey table. The ** integer value pointed to by pnChange is incremented by the number of ** entries in the table. */ SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); rc = saveAllCursors(pBt, (Pgno)iTable, 0); if( SQLITE_OK==rc ){ /* Invalidate all incrblob cursors open on table iTable (assuming iTable ** is the root of a table b-tree - if it is not, the following call is ** a no-op). */ invalidateIncrblobCursors(p, 0, 1); rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); } sqlite3BtreeLeave(p); return rc; } /* ** Delete all information from the single table that pCur is open on. ** ** This routine only work for pCur on an ephemeral table. */ SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); } /* ** Erase all information in a table and add the root of the table to ** the freelist. Except, the root of the principle table (the one on ** page 1) is never added to the freelist. ** ** This routine will fail with SQLITE_LOCKED if there are any open ** cursors on the table. ** ** If AUTOVACUUM is enabled and the page at iTable is not the last ** root page in the database file, then the last root page ** in the database file is moved into the slot formerly occupied by ** iTable and that last slot formerly occupied by the last root page ** is added to the freelist instead of iTable. In this say, all ** root pages are kept at the beginning of the database file, which ** is necessary for AUTOVACUUM to work right. *piMoved is set to the ** page number that used to be the last root page in the file before ** the move. If no page gets moved, *piMoved is set to 0. ** The last root page is recorded in meta[3] and the value of ** meta[3] is updated by this procedure. */ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ int rc; MemPage *pPage = 0; BtShared *pBt = p->pBt; assert( sqlite3BtreeHoldsMutex(p) ); assert( p->inTrans==TRANS_WRITE ); assert( iTable>=2 ); rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); if( rc ) return rc; rc = sqlite3BtreeClearTable(p, iTable, 0); if( rc ){ releasePage(pPage); return rc; } *piMoved = 0; #ifdef SQLITE_OMIT_AUTOVACUUM freePage(pPage, &rc); releasePage(pPage); #else if( pBt->autoVacuum ){ Pgno maxRootPgno; sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); if( iTable==maxRootPgno ){ /* If the table being dropped is the table with the largest root-page ** number in the database, put the root page on the free list. */ freePage(pPage, &rc); releasePage(pPage); if( rc!=SQLITE_OK ){ return rc; } }else{ /* The table being dropped does not have the largest root-page ** number in the database. So move the page that does into the ** gap left by the deleted root-page. */ MemPage *pMove; releasePage(pPage); rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); if( rc!=SQLITE_OK ){ return rc; } rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); releasePage(pMove); if( rc!=SQLITE_OK ){ return rc; } pMove = 0; rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); freePage(pMove, &rc); releasePage(pMove); if( rc!=SQLITE_OK ){ return rc; } *piMoved = maxRootPgno; } /* Set the new 'max-root-page' value in the database header. This ** is the old value less one, less one more if that happens to ** be a root-page number, less one again if that is the ** PENDING_BYTE_PAGE. */ maxRootPgno--; while( maxRootPgno==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, maxRootPgno) ){ maxRootPgno--; } assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); }else{ freePage(pPage, &rc); releasePage(pPage); } #endif return rc; } SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ int rc; sqlite3BtreeEnter(p); rc = btreeDropTable(p, iTable, piMoved); sqlite3BtreeLeave(p); return rc; } /* ** This function may only be called if the b-tree connection already ** has a read or write transaction open on the database. ** ** Read the meta-information out of a database file. Meta[0] ** is the number of free pages currently in the database. Meta[1] ** through meta[15] are available for use by higher layers. Meta[0] ** is read-only, the others are read/write. ** ** The schema layer numbers meta values differently. At the schema ** layer (and the SetCookie and ReadCookie opcodes) the number of ** free pages is not visible. So Cookie[0] is the same as Meta[1]. ** ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead ** of reading the value out of the header, it instead loads the "DataVersion" ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the ** database file. It is a number computed by the pager. But its access ** pattern is the same as header meta values, and so it is convenient to ** read it from this routine. */ SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); assert( p->inTrans>TRANS_NONE ); assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) ); assert( pBt->pPage1 ); assert( idx>=0 && idx<=15 ); if( idx==BTREE_DATA_VERSION ){ *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion; }else{ *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); } /* If auto-vacuum is disabled in this build and this is an auto-vacuum ** database, mark the database as read-only. */ #ifdef SQLITE_OMIT_AUTOVACUUM if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ pBt->btsFlags |= BTS_READ_ONLY; } #endif sqlite3BtreeLeave(p); } /* ** Write meta-information back into the database. Meta[0] is ** read-only and may not be written. */ SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ BtShared *pBt = p->pBt; unsigned char *pP1; int rc; assert( idx>=1 && idx<=15 ); sqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); assert( pBt->pPage1!=0 ); pP1 = pBt->pPage1->aData; rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pP1[36 + idx*4], iMeta); #ifndef SQLITE_OMIT_AUTOVACUUM if( idx==BTREE_INCR_VACUUM ){ assert( pBt->autoVacuum || iMeta==0 ); assert( iMeta==0 || iMeta==1 ); pBt->incrVacuum = (u8)iMeta; } #endif } sqlite3BtreeLeave(p); return rc; } #ifndef SQLITE_OMIT_BTREECOUNT /* ** The first argument, pCur, is a cursor opened on some b-tree. Count the ** number of entries in the b-tree and write the result to *pnEntry. ** ** SQLITE_OK is returned if the operation is successfully executed. ** Otherwise, if an error is encountered (i.e. an IO error or database ** corruption) an SQLite error code is returned. */ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ i64 nEntry = 0; /* Value to return in *pnEntry */ int rc; /* Return code */ if( pCur->pgnoRoot==0 ){ *pnEntry = 0; return SQLITE_OK; } rc = moveToRoot(pCur); /* Unless an error occurs, the following loop runs one iteration for each ** page in the B-Tree structure (not including overflow pages). */ while( rc==SQLITE_OK ){ int iIdx; /* Index of child node in parent */ MemPage *pPage; /* Current page of the b-tree */ /* If this is a leaf page or the tree is not an int-key tree, then ** this page contains countable entries. Increment the entry counter ** accordingly. */ pPage = pCur->apPage[pCur->iPage]; if( pPage->leaf || !pPage->intKey ){ nEntry += pPage->nCell; } /* pPage is a leaf node. This loop navigates the cursor so that it ** points to the first interior cell that it points to the parent of ** the next page in the tree that has not yet been visited. The ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell ** of the page, or to the number of cells in the page if the next page ** to visit is the right-child of its parent. ** ** If all pages in the tree have been visited, return SQLITE_OK to the ** caller. */ if( pPage->leaf ){ do { if( pCur->iPage==0 ){ /* All pages of the b-tree have been visited. Return successfully. */ *pnEntry = nEntry; return moveToRoot(pCur); } moveToParent(pCur); }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell ); pCur->aiIdx[pCur->iPage]++; pPage = pCur->apPage[pCur->iPage]; } /* Descend to the child node of the cell that the cursor currently ** points at. This is the right-child if (iIdx==pPage->nCell). */ iIdx = pCur->aiIdx[pCur->iPage]; if( iIdx==pPage->nCell ){ rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); }else{ rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx))); } } /* An error has occurred. Return an error code. */ return rc; } #endif /* ** Return the pager associated with a BTree. This routine is used for ** testing and debugging only. */ SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){ return p->pBt->pPager; } #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* ** Append a message to the error message string. */ static void checkAppendMsg( IntegrityCk *pCheck, const char *zFormat, ... ){ va_list ap; if( !pCheck->mxErr ) return; pCheck->mxErr--; pCheck->nErr++; va_start(ap, zFormat); if( pCheck->errMsg.nChar ){ sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); } if( pCheck->zPfx ){ sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2); } sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap); va_end(ap); if( pCheck->errMsg.accError==STRACCUM_NOMEM ){ pCheck->mallocFailed = 1; } } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that ** corresponds to page iPg is already set. */ static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); } /* ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. */ static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); } /* ** Add 1 to the reference count for page iPage. If this is the second ** reference to the page, add an error message to pCheck->zErrMsg. ** Return 1 if there are 2 or more references to the page and 0 if ** if this is the first reference to the page. ** ** Also check that the page number is in bounds. */ static int checkRef(IntegrityCk *pCheck, Pgno iPage){ if( iPage==0 ) return 1; if( iPage>pCheck->nPage ){ checkAppendMsg(pCheck, "invalid page number %d", iPage); return 1; } if( getPageReferenced(pCheck, iPage) ){ checkAppendMsg(pCheck, "2nd reference to page %d", iPage); return 1; } setPageReferenced(pCheck, iPage); return 0; } #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Check that the entry in the pointer-map for page iChild maps to ** page iParent, pointer type ptrType. If not, append an error message ** to pCheck. */ static void checkPtrmap( IntegrityCk *pCheck, /* Integrity check context */ Pgno iChild, /* Child page number */ u8 eType, /* Expected pointer map type */ Pgno iParent /* Expected pointer map parent page number */ ){ int rc; u8 ePtrmapType; Pgno iPtrmapParent; rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1; checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild); return; } if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ checkAppendMsg(pCheck, "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", iChild, eType, iParent, ePtrmapType, iPtrmapParent); } } #endif /* ** Check the integrity of the freelist or of an overflow page list. ** Verify that the number of pages on the list is N. */ static void checkList( IntegrityCk *pCheck, /* Integrity checking context */ int isFreeList, /* True for a freelist. False for overflow page list */ int iPage, /* Page number for first page in the list */ int N /* Expected number of pages in the list */ ){ int i; int expected = N; int iFirst = iPage; while( N-- > 0 && pCheck->mxErr ){ DbPage *pOvflPage; unsigned char *pOvflData; if( iPage<1 ){ checkAppendMsg(pCheck, "%d of %d pages missing from overflow list starting at %d", N+1, expected, iFirst); break; } if( checkRef(pCheck, iPage) ) break; if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ checkAppendMsg(pCheck, "failed to get page %d", iPage); break; } pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); if( isFreeList ){ int n = get4byte(&pOvflData[4]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pCheck->pBt->autoVacuum ){ checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); } #endif if( n>(int)pCheck->pBt->usableSize/4-2 ){ checkAppendMsg(pCheck, "freelist leaf count too big on page %d", iPage); N--; }else{ for(i=0; i<n; i++){ Pgno iFreePage = get4byte(&pOvflData[8+i*4]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pCheck->pBt->autoVacuum ){ checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0); } #endif checkRef(pCheck, iFreePage); } N -= n; } } #ifndef SQLITE_OMIT_AUTOVACUUM else{ /* If this database supports auto-vacuum and iPage is not the last ** page in this overflow list, check that the pointer-map entry for ** the following page matches iPage. */ if( pCheck->pBt->autoVacuum && N>0 ){ i = get4byte(pOvflData); checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage); } } #endif iPage = get4byte(pOvflData); sqlite3PagerUnref(pOvflPage); if( isFreeList && N<(iPage!=0) ){ checkAppendMsg(pCheck, "free-page count in header is too small"); } } } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* ** An implementation of a min-heap. ** ** aHeap[0] is the number of elements on the heap. aHeap[1] is the ** root element. The daughter nodes of aHeap[N] are aHeap[N*2] ** and aHeap[N*2+1]. ** ** The heap property is this: Every node is less than or equal to both ** of its daughter nodes. A consequence of the heap property is that the ** root node aHeap[1] is always the minimum value currently in the heap. ** ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto ** the heap, preserving the heap property. The btreeHeapPull() routine ** removes the root element from the heap (the minimum value in the heap) ** and then moves other nodes around as necessary to preserve the heap ** property. ** ** This heap is used for cell overlap and coverage testing. Each u32 ** entry represents the span of a cell or freeblock on a btree page. ** The upper 16 bits are the index of the first byte of a range and the ** lower 16 bits are the index of the last byte of that range. */ static void btreeHeapInsert(u32 *aHeap, u32 x){ u32 j, i = ++aHeap[0]; aHeap[i] = x; while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){ x = aHeap[j]; aHeap[j] = aHeap[i]; aHeap[i] = x; i = j; } } static int btreeHeapPull(u32 *aHeap, u32 *pOut){ u32 j, i, x; if( (x = aHeap[0])==0 ) return 0; *pOut = aHeap[1]; aHeap[1] = aHeap[x]; aHeap[x] = 0xffffffff; aHeap[0]--; i = 1; while( (j = i*2)<=aHeap[0] ){ if( aHeap[j]>aHeap[j+1] ) j++; if( aHeap[i]<aHeap[j] ) break; x = aHeap[i]; aHeap[i] = aHeap[j]; aHeap[j] = x; i = j; } return 1; } #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* ** Do various sanity checks on a single page of a tree. Return ** the tree depth. Root pages return 0. Parents of root pages ** return 1, and so forth. ** ** These checks are done: ** ** 1. Make sure that cells and freeblocks do not overlap ** but combine to completely cover the page. ** 2. Make sure integer cell keys are in order. ** 3. Check the integrity of overflow pages. ** 4. Recursively call checkTreePage on all children. ** 5. Verify that the depth of all children is the same. */ static int checkTreePage( IntegrityCk *pCheck, /* Context for the sanity check */ int iPage, /* Page number of the page to check */ i64 *piMinKey, /* Write minimum integer primary key here */ i64 maxKey /* Error if integer primary key greater than this */ ){ MemPage *pPage = 0; /* The page being analyzed */ int i; /* Loop counter */ int rc; /* Result code from subroutine call */ int depth = -1, d2; /* Depth of a subtree */ int pgno; /* Page number */ int nFrag; /* Number of fragmented bytes on the page */ int hdr; /* Offset to the page header */ int cellStart; /* Offset to the start of the cell pointer array */ int nCell; /* Number of cells */ int doCoverageCheck = 1; /* True if cell coverage checking should be done */ int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey ** False if IPK must be strictly less than maxKey */ u8 *data; /* Page content */ u8 *pCell; /* Cell content */ u8 *pCellIdx; /* Next element of the cell pointer array */ BtShared *pBt; /* The BtShared object that owns pPage */ u32 pc; /* Address of a cell */ u32 usableSize; /* Usable size of the page */ u32 contentOffset; /* Offset to the start of the cell content area */ u32 *heap = 0; /* Min-heap used for checking cell coverage */ u32 x, prev = 0; /* Next and previous entry on the min-heap */ const char *saved_zPfx = pCheck->zPfx; int saved_v1 = pCheck->v1; int saved_v2 = pCheck->v2; u8 savedIsInit = 0; /* Check that the page exists */ pBt = pCheck->pBt; usableSize = pBt->usableSize; if( iPage==0 ) return 0; if( checkRef(pCheck, iPage) ) return 0; pCheck->zPfx = "Page %d: "; pCheck->v1 = iPage; if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ checkAppendMsg(pCheck, "unable to get the page. error code=%d", rc); goto end_of_check; } /* Clear MemPage.isInit to make sure the corruption detection code in ** btreeInitPage() is executed. */ savedIsInit = pPage->isInit; pPage->isInit = 0; if( (rc = btreeInitPage(pPage))!=0 ){ assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ checkAppendMsg(pCheck, "btreeInitPage() returns error code %d", rc); goto end_of_check; } data = pPage->aData; hdr = pPage->hdrOffset; /* Set up for cell analysis */ pCheck->zPfx = "On tree page %d cell %d: "; contentOffset = get2byteNotZero(&data[hdr+5]); assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the ** number of cells on the page. */ nCell = get2byte(&data[hdr+3]); assert( pPage->nCell==nCell ); /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page ** immediately follows the b-tree page header. */ cellStart = hdr + 12 - 4*pPage->leaf; assert( pPage->aCellIdx==&data[cellStart] ); pCellIdx = &data[cellStart + 2*(nCell-1)]; if( !pPage->leaf ){ /* Analyze the right-child page of internal pages */ pgno = get4byte(&data[hdr+8]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ pCheck->zPfx = "On page %d at right child: "; checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); } #endif depth = checkTreePage(pCheck, pgno, &maxKey, maxKey); keyCanBeEqual = 0; }else{ /* For leaf pages, the coverage check will occur in the same loop ** as the other cell checks, so initialize the heap. */ heap = pCheck->heap; heap[0] = 0; } /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte ** integer offsets to the cell contents. */ for(i=nCell-1; i>=0 && pCheck->mxErr; i--){ CellInfo info; /* Check cell size */ pCheck->v2 = i; assert( pCellIdx==&data[cellStart + i*2] ); pc = get2byteAligned(pCellIdx); pCellIdx -= 2; if( pc<contentOffset || pc>usableSize-4 ){ checkAppendMsg(pCheck, "Offset %d out of range %d..%d", pc, contentOffset, usableSize-4); doCoverageCheck = 0; continue; } pCell = &data[pc]; pPage->xParseCell(pPage, pCell, &info); if( pc+info.nSize>usableSize ){ checkAppendMsg(pCheck, "Extends off end of page"); doCoverageCheck = 0; continue; } /* Check for integer primary key out of range */ if( pPage->intKey ){ if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){ checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey); } maxKey = info.nKey; } /* Check the content overflow list */ if( info.nPayload>info.nLocal ){ int nPage; /* Number of pages on the overflow chain */ Pgno pgnoOvfl; /* First page of the overflow chain */ assert( pc + info.nSize - 4 <= usableSize ); nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4); pgnoOvfl = get4byte(&pCell[info.nSize - 4]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage); } #endif checkList(pCheck, 0, pgnoOvfl, nPage); } if( !pPage->leaf ){ /* Check sanity of left child page for internal pages */ pgno = get4byte(pCell); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); } #endif d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey); keyCanBeEqual = 0; if( d2!=depth ){ checkAppendMsg(pCheck, "Child page depth differs"); depth = d2; } }else{ /* Populate the coverage-checking heap for leaf pages */ btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1)); } } *piMinKey = maxKey; /* Check for complete coverage of the page */ pCheck->zPfx = 0; if( doCoverageCheck && pCheck->mxErr>0 ){ /* For leaf pages, the min-heap has already been initialized and the ** cells have already been inserted. But for internal pages, that has ** not yet been done, so do it now */ if( !pPage->leaf ){ heap = pCheck->heap; heap[0] = 0; for(i=nCell-1; i>=0; i--){ u32 size; pc = get2byteAligned(&data[cellStart+i*2]); size = pPage->xCellSize(pPage, &data[pc]); btreeHeapInsert(heap, (pc<<16)|(pc+size-1)); } } /* Add the freeblocks to the min-heap ** ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header ** is the offset of the first freeblock, or zero if there are no ** freeblocks on the page. */ i = get2byte(&data[hdr+1]); while( i>0 ){ int size, j; assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */ size = get2byte(&data[i+2]); assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */ btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a ** big-endian integer which is the offset in the b-tree page of the next ** freeblock in the chain, or zero if the freeblock is the last on the ** chain. */ j = get2byte(&data[i]); /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of ** increasing offset. */ assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */ assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */ i = j; } /* Analyze the min-heap looking for overlap between cells and/or ** freeblocks, and counting the number of untracked bytes in nFrag. ** ** Each min-heap entry is of the form: (start_address<<16)|end_address. ** There is an implied first entry the covers the page header, the cell ** pointer index, and the gap between the cell pointer index and the start ** of cell content. ** ** The loop below pulls entries from the min-heap in order and compares ** the start_address against the previous end_address. If there is an ** overlap, that means bytes are used multiple times. If there is a gap, ** that gap is added to the fragmentation count. */ nFrag = 0; prev = contentOffset - 1; /* Implied first min-heap entry */ while( btreeHeapPull(heap,&x) ){ if( (prev&0xffff)>=(x>>16) ){ checkAppendMsg(pCheck, "Multiple uses for byte %u of page %d", x>>16, iPage); break; }else{ nFrag += (x>>16) - (prev&0xffff) - 1; prev = x; } } nFrag += usableSize - (prev&0xffff) - 1; /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments ** is stored in the fifth field of the b-tree page header. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the ** number of fragmented free bytes within the cell content area. */ if( heap[0]==0 && nFrag!=data[hdr+7] ){ checkAppendMsg(pCheck, "Fragmentation of %d bytes reported as %d on page %d", nFrag, data[hdr+7], iPage); } } end_of_check: if( !doCoverageCheck ) pPage->isInit = savedIsInit; releasePage(pPage); pCheck->zPfx = saved_zPfx; pCheck->v1 = saved_v1; pCheck->v2 = saved_v2; return depth+1; } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* ** This routine does a complete check of the given BTree file. aRoot[] is ** an array of pages numbers were each page number is the root page of ** a table. nRoot is the number of entries in aRoot. ** ** A read-only or read-write transaction must be opened before calling ** this function. ** ** Write the number of error seen in *pnErr. Except for some memory ** allocation errors, an error message held in memory obtained from ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is ** returned. If a memory allocation error occurs, NULL is returned. */ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( Btree *p, /* The btree to be checked */ int *aRoot, /* An array of root pages numbers for individual trees */ int nRoot, /* Number of entries in aRoot[] */ int mxErr, /* Stop reporting errors after this many */ int *pnErr /* Write number of errors seen to this variable */ ){ Pgno i; IntegrityCk sCheck; BtShared *pBt = p->pBt; int savedDbFlags = pBt->db->flags; char zErr[100]; VVA_ONLY( int nRef ); sqlite3BtreeEnter(p); assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) ); assert( nRef>=0 ); sCheck.pBt = pBt; sCheck.pPager = pBt->pPager; sCheck.nPage = btreePagecount(sCheck.pBt); sCheck.mxErr = mxErr; sCheck.nErr = 0; sCheck.mallocFailed = 0; sCheck.zPfx = 0; sCheck.v1 = 0; sCheck.v2 = 0; sCheck.aPgRef = 0; sCheck.heap = 0; sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL; if( sCheck.nPage==0 ){ goto integrity_ck_cleanup; } sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); if( !sCheck.aPgRef ){ sCheck.mallocFailed = 1; goto integrity_ck_cleanup; } sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); if( sCheck.heap==0 ){ sCheck.mallocFailed = 1; goto integrity_ck_cleanup; } i = PENDING_BYTE_PAGE(pBt); if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); /* Check the integrity of the freelist */ sCheck.zPfx = "Main freelist: "; checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), get4byte(&pBt->pPage1->aData[36])); sCheck.zPfx = 0; /* Check all the tables. */ testcase( pBt->db->flags & SQLITE_CellSizeCk ); pBt->db->flags &= ~SQLITE_CellSizeCk; for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ i64 notUsed; if( aRoot[i]==0 ) continue; #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum && aRoot[i]>1 ){ checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0); } #endif checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64); } pBt->db->flags = savedDbFlags; /* Make sure every page in the file is referenced */ for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ #ifdef SQLITE_OMIT_AUTOVACUUM if( getPageReferenced(&sCheck, i)==0 ){ checkAppendMsg(&sCheck, "Page %d is never used", i); } #else /* If the database supports auto-vacuum, make sure no tables contain ** references to pointer-map pages. */ if( getPageReferenced(&sCheck, i)==0 && (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ checkAppendMsg(&sCheck, "Page %d is never used", i); } if( getPageReferenced(&sCheck, i)!=0 && (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i); } #endif } /* Clean up and report errors. */ integrity_ck_cleanup: sqlite3PageFree(sCheck.heap); sqlite3_free(sCheck.aPgRef); if( sCheck.mallocFailed ){ sqlite3StrAccumReset(&sCheck.errMsg); sCheck.nErr++; } *pnErr = sCheck.nErr; if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg); /* Make sure this analysis did not leave any unref() pages. */ assert( nRef==sqlite3PagerRefcount(pBt->pPager) ); sqlite3BtreeLeave(p); return sqlite3StrAccumFinish(&sCheck.errMsg); } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* ** Return the full pathname of the underlying database file. Return ** an empty string if the database is in-memory or a TEMP database. ** ** The pager filename is invariant as long as the pager is ** open so it is safe to access without the BtShared mutex. */ SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){ assert( p->pBt->pPager!=0 ); return sqlite3PagerFilename(p->pBt->pPager, 1); } /* ** Return the pathname of the journal file for this database. The return ** value of this routine is the same regardless of whether the journal file ** has been created or not. ** ** The pager journal filename is invariant as long as the pager is ** open so it is safe to access without the BtShared mutex. */ SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){ assert( p->pBt->pPager!=0 ); return sqlite3PagerJournalname(p->pBt->pPager); } /* ** Return non-zero if a transaction is active. */ SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){ assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); return (p && (p->inTrans==TRANS_WRITE)); } #ifndef SQLITE_OMIT_WAL /* ** Run a checkpoint on the Btree passed as the first argument. ** ** Return SQLITE_LOCKED if this or any other connection has an open ** transaction on the shared-cache the argument Btree is connected to. ** ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. */ SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ int rc = SQLITE_OK; if( p ){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); if( pBt->inTransaction!=TRANS_NONE ){ rc = SQLITE_LOCKED; }else{ rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt); } sqlite3BtreeLeave(p); } return rc; } #endif /* ** Return non-zero if a read (or write) transaction is active. */ SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){ assert( p ); assert( sqlite3_mutex_held(p->db->mutex) ); return p->inTrans!=TRANS_NONE; } SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){ assert( p ); assert( sqlite3_mutex_held(p->db->mutex) ); return p->nBackup!=0; } /* ** This function returns a pointer to a blob of memory associated with ** a single shared-btree. The memory is used by client code for its own ** purposes (for example, to store a high-level schema associated with ** the shared-btree). The btree layer manages reference counting issues. ** ** The first time this is called on a shared-btree, nBytes bytes of memory ** are allocated, zeroed, and returned to the caller. For each subsequent ** call the nBytes parameter is ignored and a pointer to the same blob ** of memory returned. ** ** If the nBytes parameter is 0 and the blob of memory has not yet been ** allocated, a null pointer is returned. If the blob has already been ** allocated, it is returned as normal. ** ** Just before the shared-btree is closed, the function passed as the ** xFree argument when the memory allocation was made is invoked on the ** blob of allocated memory. The xFree function should not call sqlite3_free() ** on the memory, the btree layer does that. */ SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); if( !pBt->pSchema && nBytes ){ pBt->pSchema = sqlite3DbMallocZero(0, nBytes); pBt->xFreeSchema = xFree; } sqlite3BtreeLeave(p); return pBt->pSchema; } /* ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared ** btree as the argument handle holds an exclusive lock on the ** sqlite_master table. Otherwise SQLITE_OK. */ SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ int rc; assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); sqlite3BtreeLeave(p); return rc; } #ifndef SQLITE_OMIT_SHARED_CACHE /* ** Obtain a lock on the table whose root page is iTab. The ** lock is a write lock if isWritelock is true or a read lock ** if it is false. */ SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ int rc = SQLITE_OK; assert( p->inTrans!=TRANS_NONE ); if( p->sharable ){ u8 lockType = READ_LOCK + isWriteLock; assert( READ_LOCK+1==WRITE_LOCK ); assert( isWriteLock==0 || isWriteLock==1 ); sqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, iTab, lockType); if( rc==SQLITE_OK ){ rc = setSharedCacheTableLock(p, iTab, lockType); } sqlite3BtreeLeave(p); } return rc; } #endif #ifndef SQLITE_OMIT_INCRBLOB /* ** Argument pCsr must be a cursor opened for writing on an ** INTKEY table currently pointing at a valid table entry. ** This function modifies the data stored as part of that entry. ** ** Only the data content may only be modified, it is not possible to ** change the length of the data stored. If this function is called with ** parameters that attempt to write past the end of the existing data, ** no modifications are made and SQLITE_CORRUPT is returned. */ SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ int rc; assert( cursorOwnsBtShared(pCsr) ); assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); assert( pCsr->curFlags & BTCF_Incrblob ); rc = restoreCursorPosition(pCsr); if( rc!=SQLITE_OK ){ return rc; } assert( pCsr->eState!=CURSOR_REQUIRESEEK ); if( pCsr->eState!=CURSOR_VALID ){ return SQLITE_ABORT; } /* Save the positions of all other cursors open on this table. This is ** required in case any of them are holding references to an xFetch ** version of the b-tree page modified by the accessPayload call below. ** ** Note that pCsr must be open on a INTKEY table and saveCursorPosition() ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence ** saveAllCursors can only return SQLITE_OK. */ VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); assert( rc==SQLITE_OK ); /* Check some assumptions: ** (a) the cursor is open for writing, ** (b) there is a read/write transaction open, ** (c) the connection holds a write-lock on the table (if required), ** (d) there are no conflicting read-locks, and ** (e) the cursor points at a valid row of an intKey table. */ if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){ return SQLITE_READONLY; } assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 && pCsr->pBt->inTransaction==TRANS_WRITE ); assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); assert( pCsr->apPage[pCsr->iPage]->intKey ); return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); } /* ** Mark this cursor as an incremental blob cursor. */ SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ pCur->curFlags |= BTCF_Incrblob; pCur->pBtree->hasIncrblobCur = 1; } #endif /* ** Set both the "read version" (single byte at byte offset 18) and ** "write version" (single byte at byte offset 19) fields in the database ** header to iVersion. */ SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ BtShared *pBt = pBtree->pBt; int rc; /* Return code */ assert( iVersion==1 || iVersion==2 ); /* If setting the version fields to 1, do not automatically open the ** WAL connection, even if the version fields are currently set to 2. */ pBt->btsFlags &= ~BTS_NO_WAL; if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; rc = sqlite3BtreeBeginTrans(pBtree, 0); if( rc==SQLITE_OK ){ u8 *aData = pBt->pPage1->aData; if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ rc = sqlite3BtreeBeginTrans(pBtree, 2); if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc==SQLITE_OK ){ aData[18] = (u8)iVersion; aData[19] = (u8)iVersion; } } } } pBt->btsFlags &= ~BTS_NO_WAL; return rc; } /* ** Return true if the cursor has a hint specified. This routine is ** only used from within assert() statements */ SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ return (pCsr->hints & mask)!=0; } /* ** Return true if the given Btree is read-only. */ SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){ return (p->pBt->btsFlags & BTS_READ_ONLY)!=0; } /* ** Return the size of the header added to each page by this module. */ SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); } #if !defined(SQLITE_OMIT_SHARED_CACHE) /* ** Return true if the Btree passed as the only argument is sharable. */ SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){ return p->sharable; } /* ** Return the number of connections to the BtShared object accessed by ** the Btree handle passed as the only argument. For private caches ** this is always 1. For shared caches it may be 1 or greater. */ SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){ testcase( p->sharable ); return p->pBt->nRef; } #endif /************** End of btree.c ***********************************************/ /************** Begin file backup.c ******************************************/ /* ** 2009 January 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation of the sqlite3_backup_XXX() ** API functions and the related features. */ /* #include "sqliteInt.h" */ /* #include "btreeInt.h" */ /* ** Structure allocated for each backup operation. */ struct sqlite3_backup { sqlite3* pDestDb; /* Destination database handle */ Btree *pDest; /* Destination b-tree file */ u32 iDestSchema; /* Original schema cookie in destination */ int bDestLocked; /* True once a write-transaction is open on pDest */ Pgno iNext; /* Page number of the next source page to copy */ sqlite3* pSrcDb; /* Source database handle */ Btree *pSrc; /* Source b-tree file */ int rc; /* Backup process error code */ /* These two variables are set by every call to backup_step(). They are ** read by calls to backup_remaining() and backup_pagecount(). */ Pgno nRemaining; /* Number of pages left to copy */ Pgno nPagecount; /* Total number of pages to copy */ int isAttached; /* True once backup has been registered with pager */ sqlite3_backup *pNext; /* Next backup associated with source pager */ }; /* ** THREAD SAFETY NOTES: ** ** Once it has been created using backup_init(), a single sqlite3_backup ** structure may be accessed via two groups of thread-safe entry points: ** ** * Via the sqlite3_backup_XXX() API function backup_step() and ** backup_finish(). Both these functions obtain the source database ** handle mutex and the mutex associated with the source BtShared ** structure, in that order. ** ** * Via the BackupUpdate() and BackupRestart() functions, which are ** invoked by the pager layer to report various state changes in ** the page cache associated with the source database. The mutex ** associated with the source database BtShared structure will always ** be held when either of these functions are invoked. ** ** The other sqlite3_backup_XXX() API functions, backup_remaining() and ** backup_pagecount() are not thread-safe functions. If they are called ** while some other thread is calling backup_step() or backup_finish(), ** the values returned may be invalid. There is no way for a call to ** BackupUpdate() or BackupRestart() to interfere with backup_remaining() ** or backup_pagecount(). ** ** Depending on the SQLite configuration, the database handles and/or ** the Btree objects may have their own mutexes that require locking. ** Non-sharable Btrees (in-memory databases for example), do not have ** associated mutexes. */ /* ** Return a pointer corresponding to database zDb (i.e. "main", "temp") ** in connection handle pDb. If such a database cannot be found, return ** a NULL pointer and write an error message to pErrorDb. ** ** If the "temp" database is requested, it may need to be opened by this ** function. If an error occurs while doing so, return 0 and write an ** error message to pErrorDb. */ static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ int i = sqlite3FindDbName(pDb, zDb); if( i==1 ){ Parse sParse; int rc = 0; memset(&sParse, 0, sizeof(sParse)); sParse.db = pDb; if( sqlite3OpenTempDatabase(&sParse) ){ sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg); rc = SQLITE_ERROR; } sqlite3DbFree(pErrorDb, sParse.zErrMsg); sqlite3ParserReset(&sParse); if( rc ){ return 0; } } if( i<0 ){ sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb); return 0; } return pDb->aDb[i].pBt; } /* ** Attempt to set the page size of the destination to match the page size ** of the source. */ static int setDestPgsz(sqlite3_backup *p){ int rc; rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0); return rc; } /* ** Check that there is no open read-transaction on the b-tree passed as the ** second argument. If there is not, return SQLITE_OK. Otherwise, if there ** is an open read-transaction, return SQLITE_ERROR and leave an error ** message in database handle db. */ static int checkReadTransaction(sqlite3 *db, Btree *p){ if( sqlite3BtreeIsInReadTrans(p) ){ sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use"); return SQLITE_ERROR; } return SQLITE_OK; } /* ** Create an sqlite3_backup process to copy the contents of zSrcDb from ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return ** a pointer to the new sqlite3_backup object. ** ** If an error occurs, NULL is returned and an error code and error message ** stored in database handle pDestDb. */ SQLITE_API sqlite3_backup *sqlite3_backup_init( sqlite3* pDestDb, /* Database to write to */ const char *zDestDb, /* Name of database within pDestDb */ sqlite3* pSrcDb, /* Database connection to read from */ const char *zSrcDb /* Name of database within pSrcDb */ ){ sqlite3_backup *p; /* Value to return */ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif /* Lock the source database handle. The destination database ** handle is not locked in this routine, but it is locked in ** sqlite3_backup_step(). The user is required to ensure that no ** other thread accesses the destination handle for the duration ** of the backup operation. Any attempt to use the destination ** database connection while a backup is in progress may cause ** a malfunction or a deadlock. */ sqlite3_mutex_enter(pSrcDb->mutex); sqlite3_mutex_enter(pDestDb->mutex); if( pSrcDb==pDestDb ){ sqlite3ErrorWithMsg( pDestDb, SQLITE_ERROR, "source and destination must be distinct" ); p = 0; }else { /* Allocate space for a new sqlite3_backup object... ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a ** call to sqlite3_backup_init() and is destroyed by a call to ** sqlite3_backup_finish(). */ p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup)); if( !p ){ sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT); } } /* If the allocation succeeded, populate the new object. */ if( p ){ p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb); p->pDest = findBtree(pDestDb, pDestDb, zDestDb); p->pDestDb = pDestDb; p->pSrcDb = pSrcDb; p->iNext = 1; p->isAttached = 0; if( 0==p->pSrc || 0==p->pDest || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK ){ /* One (or both) of the named databases did not exist or an OOM ** error was hit. Or there is a transaction open on the destination ** database. The error has already been written into the pDestDb ** handle. All that is left to do here is free the sqlite3_backup ** structure. */ sqlite3_free(p); p = 0; } } if( p ){ p->pSrc->nBackup++; } sqlite3_mutex_leave(pDestDb->mutex); sqlite3_mutex_leave(pSrcDb->mutex); return p; } /* ** Argument rc is an SQLite error code. Return true if this error is ** considered fatal if encountered during a backup operation. All errors ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. */ static int isFatalError(int rc){ return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED)); } /* ** Parameter zSrcData points to a buffer containing the data for ** page iSrcPg from the source database. Copy this data into the ** destination database. */ static int backupOnePage( sqlite3_backup *p, /* Backup handle */ Pgno iSrcPg, /* Source database page to backup */ const u8 *zSrcData, /* Source database page data */ int bUpdate /* True for an update, false otherwise */ ){ Pager * const pDestPager = sqlite3BtreePager(p->pDest); const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc); int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest); const int nCopy = MIN(nSrcPgsz, nDestPgsz); const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz; #ifdef SQLITE_HAS_CODEC /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is ** guaranteed that the shared-mutex is held by this thread, handle ** p->pSrc may not actually be the owner. */ int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc); int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest); #endif int rc = SQLITE_OK; i64 iOff; assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 ); assert( p->bDestLocked ); assert( !isFatalError(p->rc) ); assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ); assert( zSrcData ); /* Catch the case where the destination is an in-memory database and the ** page sizes of the source and destination differ. */ if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){ rc = SQLITE_READONLY; } #ifdef SQLITE_HAS_CODEC /* Backup is not possible if the page size of the destination is changing ** and a codec is in use. */ if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){ rc = SQLITE_READONLY; } /* Backup is not possible if the number of bytes of reserve space differ ** between source and destination. If there is a difference, try to ** fix the destination to agree with the source. If that is not possible, ** then the backup cannot proceed. */ if( nSrcReserve!=nDestReserve ){ u32 newPgsz = nSrcPgsz; rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve); if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY; } #endif /* This loop runs once for each destination page spanned by the source ** page. For each iteration, variable iOff is set to the byte offset ** of the destination page. */ for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){ DbPage *pDestPg = 0; Pgno iDest = (Pgno)(iOff/nDestPgsz)+1; if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue; if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0)) && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg)) ){ const u8 *zIn = &zSrcData[iOff%nSrcPgsz]; u8 *zDestData = sqlite3PagerGetData(pDestPg); u8 *zOut = &zDestData[iOff%nDestPgsz]; /* Copy the data from the source page into the destination page. ** Then clear the Btree layer MemPage.isInit flag. Both this module ** and the pager code use this trick (clearing the first byte ** of the page 'extra' space to invalidate the Btree layers ** cached parse of the page). MemPage.isInit is marked ** "MUST BE FIRST" for this purpose. */ memcpy(zOut, zIn, nCopy); ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0; if( iOff==0 && bUpdate==0 ){ sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc)); } } sqlite3PagerUnref(pDestPg); } return rc; } /* ** If pFile is currently larger than iSize bytes, then truncate it to ** exactly iSize bytes. If pFile is not larger than iSize bytes, then ** this function is a no-op. ** ** Return SQLITE_OK if everything is successful, or an SQLite error ** code if an error occurs. */ static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){ i64 iCurrent; int rc = sqlite3OsFileSize(pFile, &iCurrent); if( rc==SQLITE_OK && iCurrent>iSize ){ rc = sqlite3OsTruncate(pFile, iSize); } return rc; } /* ** Register this backup object with the associated source pager for ** callbacks when pages are changed or the cache invalidated. */ static void attachBackupObject(sqlite3_backup *p){ sqlite3_backup **pp; assert( sqlite3BtreeHoldsMutex(p->pSrc) ); pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); p->pNext = *pp; *pp = p; p->isAttached = 1; } /* ** Copy nPage pages from the source b-tree to the destination. */ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ int rc; int destMode; /* Destination journal mode */ int pgszSrc = 0; /* Source page size */ int pgszDest = 0; /* Destination page size */ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(p->pSrcDb->mutex); sqlite3BtreeEnter(p->pSrc); if( p->pDestDb ){ sqlite3_mutex_enter(p->pDestDb->mutex); } rc = p->rc; if( !isFatalError(rc) ){ Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */ Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */ int ii; /* Iterator variable */ int nSrcPage = -1; /* Size of source db in pages */ int bCloseTrans = 0; /* True if src db requires unlocking */ /* If the source pager is currently in a write-transaction, return ** SQLITE_BUSY immediately. */ if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){ rc = SQLITE_BUSY; }else{ rc = SQLITE_OK; } /* If there is no open read-transaction on the source database, open ** one now. If a transaction is opened here, then it will be closed ** before this function exits. */ if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){ rc = sqlite3BtreeBeginTrans(p->pSrc, 0); bCloseTrans = 1; } /* If the destination database has not yet been locked (i.e. if this ** is the first call to backup_step() for the current backup operation), ** try to set its page size to the same as the source database. This ** is especially important on ZipVFS systems, as in that case it is ** not possible to create a database file that uses one page size by ** writing to it with another. */ if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){ rc = SQLITE_NOMEM; } /* Lock the destination database, if it is not locked already. */ if( SQLITE_OK==rc && p->bDestLocked==0 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) ){ p->bDestLocked = 1; sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema); } /* Do not allow backup if the destination database is in WAL mode ** and the page sizes are different between source and destination */ pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); pgszDest = sqlite3BtreeGetPageSize(p->pDest); destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){ rc = SQLITE_READONLY; } /* Now that there is a read-lock on the source database, query the ** source pager for the number of pages in the database. */ nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc); assert( nSrcPage>=0 ); for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){ const Pgno iSrcPg = p->iNext; /* Source page number */ if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){ DbPage *pSrcPg; /* Source page object */ rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY); if( rc==SQLITE_OK ){ rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0); sqlite3PagerUnref(pSrcPg); } } p->iNext++; } if( rc==SQLITE_OK ){ p->nPagecount = nSrcPage; p->nRemaining = nSrcPage+1-p->iNext; if( p->iNext>(Pgno)nSrcPage ){ rc = SQLITE_DONE; }else if( !p->isAttached ){ attachBackupObject(p); } } /* Update the schema version field in the destination database. This ** is to make sure that the schema-version really does change in ** the case where the source and destination databases have the ** same schema version. */ if( rc==SQLITE_DONE ){ if( nSrcPage==0 ){ rc = sqlite3BtreeNewDb(p->pDest); nSrcPage = 1; } if( rc==SQLITE_OK || rc==SQLITE_DONE ){ rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1); } if( rc==SQLITE_OK ){ if( p->pDestDb ){ sqlite3ResetAllSchemasOfConnection(p->pDestDb); } if( destMode==PAGER_JOURNALMODE_WAL ){ rc = sqlite3BtreeSetVersion(p->pDest, 2); } } if( rc==SQLITE_OK ){ int nDestTruncate; /* Set nDestTruncate to the final number of pages in the destination ** database. The complication here is that the destination page ** size may be different to the source page size. ** ** If the source page size is smaller than the destination page size, ** round up. In this case the call to sqlite3OsTruncate() below will ** fix the size of the file. However it is important to call ** sqlite3PagerTruncateImage() here so that any pages in the ** destination file that lie beyond the nDestTruncate page mark are ** journalled by PagerCommitPhaseOne() before they are destroyed ** by the file truncation. */ assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) ); assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) ); if( pgszSrc<pgszDest ){ int ratio = pgszDest/pgszSrc; nDestTruncate = (nSrcPage+ratio-1)/ratio; if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){ nDestTruncate--; } }else{ nDestTruncate = nSrcPage * (pgszSrc/pgszDest); } assert( nDestTruncate>0 ); if( pgszSrc<pgszDest ){ /* If the source page-size is smaller than the destination page-size, ** two extra things may need to happen: ** ** * The destination may need to be truncated, and ** ** * Data stored on the pages immediately following the ** pending-byte page in the source database may need to be ** copied into the destination database. */ const i64 iSize = (i64)pgszSrc * (i64)nSrcPage; sqlite3_file * const pFile = sqlite3PagerFile(pDestPager); Pgno iPg; int nDstPage; i64 iOff; i64 iEnd; assert( pFile ); assert( nDestTruncate==0 || (i64)nDestTruncate*(i64)pgszDest >= iSize || ( nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1) && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest )); /* This block ensures that all data required to recreate the original ** database has been stored in the journal for pDestPager and the ** journal synced to disk. So at this point we may safely modify ** the database file in any way, knowing that if a power failure ** occurs, the original database will be reconstructed from the ** journal file. */ sqlite3PagerPagecount(pDestPager, &nDstPage); for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){ if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){ DbPage *pPg; rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0); if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(pPg); sqlite3PagerUnref(pPg); } } } if( rc==SQLITE_OK ){ rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1); } /* Write the extra pages and truncate the database file as required */ iEnd = MIN(PENDING_BYTE + pgszDest, iSize); for( iOff=PENDING_BYTE+pgszSrc; rc==SQLITE_OK && iOff<iEnd; iOff+=pgszSrc ){ PgHdr *pSrcPg = 0; const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1); rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0); if( rc==SQLITE_OK ){ u8 *zData = sqlite3PagerGetData(pSrcPg); rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff); } sqlite3PagerUnref(pSrcPg); } if( rc==SQLITE_OK ){ rc = backupTruncateFile(pFile, iSize); } /* Sync the database file to disk. */ if( rc==SQLITE_OK ){ rc = sqlite3PagerSync(pDestPager, 0); } }else{ sqlite3PagerTruncateImage(pDestPager, nDestTruncate); rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0); } /* Finish committing the transaction to the destination database. */ if( SQLITE_OK==rc && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0)) ){ rc = SQLITE_DONE; } } } /* If bCloseTrans is true, then this function opened a read transaction ** on the source database. Close the read transaction here. There is ** no need to check the return values of the btree methods here, as ** "committing" a read-only transaction cannot fail. */ if( bCloseTrans ){ TESTONLY( int rc2 ); TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0); TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0); assert( rc2==SQLITE_OK ); } if( rc==SQLITE_IOERR_NOMEM ){ rc = SQLITE_NOMEM_BKPT; } p->rc = rc; } if( p->pDestDb ){ sqlite3_mutex_leave(p->pDestDb->mutex); } sqlite3BtreeLeave(p->pSrc); sqlite3_mutex_leave(p->pSrcDb->mutex); return rc; } /* ** Release all resources associated with an sqlite3_backup* handle. */ SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){ sqlite3_backup **pp; /* Ptr to head of pagers backup list */ sqlite3 *pSrcDb; /* Source database connection */ int rc; /* Value to return */ /* Enter the mutexes */ if( p==0 ) return SQLITE_OK; pSrcDb = p->pSrcDb; sqlite3_mutex_enter(pSrcDb->mutex); sqlite3BtreeEnter(p->pSrc); if( p->pDestDb ){ sqlite3_mutex_enter(p->pDestDb->mutex); } /* Detach this backup from the source pager. */ if( p->pDestDb ){ p->pSrc->nBackup--; } if( p->isAttached ){ pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); while( *pp!=p ){ pp = &(*pp)->pNext; } *pp = p->pNext; } /* If a transaction is still open on the Btree, roll it back. */ sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0); /* Set the error code of the destination database handle. */ rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc; if( p->pDestDb ){ sqlite3Error(p->pDestDb, rc); /* Exit the mutexes and free the backup context structure. */ sqlite3LeaveMutexAndCloseZombie(p->pDestDb); } sqlite3BtreeLeave(p->pSrc); if( p->pDestDb ){ /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a ** call to sqlite3_backup_init() and is destroyed by a call to ** sqlite3_backup_finish(). */ sqlite3_free(p); } sqlite3LeaveMutexAndCloseZombie(pSrcDb); return rc; } /* ** Return the number of pages still to be backed up as of the most recent ** call to sqlite3_backup_step(). */ SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return p->nRemaining; } /* ** Return the total number of pages in the source database as of the most ** recent call to sqlite3_backup_step(). */ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return p->nPagecount; } /* ** This function is called after the contents of page iPage of the ** source database have been modified. If page iPage has already been ** copied into the destination database, then the data written to the ** destination is now invalidated. The destination copy of iPage needs ** to be updated with the new data before the backup operation is ** complete. ** ** It is assumed that the mutex associated with the BtShared object ** corresponding to the source database is held when this function is ** called. */ static SQLITE_NOINLINE void backupUpdate( sqlite3_backup *p, Pgno iPage, const u8 *aData ){ assert( p!=0 ); do{ assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); if( !isFatalError(p->rc) && iPage<p->iNext ){ /* The backup process p has already copied page iPage. But now it ** has been modified by a transaction on the source pager. Copy ** the new data into the backup. */ int rc; assert( p->pDestDb ); sqlite3_mutex_enter(p->pDestDb->mutex); rc = backupOnePage(p, iPage, aData, 1); sqlite3_mutex_leave(p->pDestDb->mutex); assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED ); if( rc!=SQLITE_OK ){ p->rc = rc; } } }while( (p = p->pNext)!=0 ); } SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){ if( pBackup ) backupUpdate(pBackup, iPage, aData); } /* ** Restart the backup process. This is called when the pager layer ** detects that the database has been modified by an external database ** connection. In this case there is no way of knowing which of the ** pages that have been copied into the destination database are still ** valid and which are not, so the entire process needs to be restarted. ** ** It is assumed that the mutex associated with the BtShared object ** corresponding to the source database is held when this function is ** called. */ SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){ sqlite3_backup *p; /* Iterator variable */ for(p=pBackup; p; p=p->pNext){ assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); p->iNext = 1; } } #ifndef SQLITE_OMIT_VACUUM /* ** Copy the complete content of pBtFrom into pBtTo. A transaction ** must be active for both files. ** ** The size of file pTo may be reduced by this operation. If anything ** goes wrong, the transaction on pTo is rolled back. If successful, the ** transaction is committed before returning. */ SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ int rc; sqlite3_file *pFd; /* File descriptor for database pTo */ sqlite3_backup b; sqlite3BtreeEnter(pTo); sqlite3BtreeEnter(pFrom); assert( sqlite3BtreeIsInTrans(pTo) ); pFd = sqlite3PagerFile(sqlite3BtreePager(pTo)); if( pFd->pMethods ){ i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom); rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte); if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; if( rc ) goto copy_finished; } /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set ** to 0. This is used by the implementations of sqlite3_backup_step() ** and sqlite3_backup_finish() to detect that they are being called ** from this function, not directly by the user. */ memset(&b, 0, sizeof(b)); b.pSrcDb = pFrom->db; b.pSrc = pFrom; b.pDest = pTo; b.iNext = 1; #ifdef SQLITE_HAS_CODEC sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom)); #endif /* 0x7FFFFFFF is the hard limit for the number of pages in a database ** file. By passing this as the number of pages to copy to ** sqlite3_backup_step(), we can guarantee that the copy finishes ** within a single call (unless an error occurs). The assert() statement ** checks this assumption - (p->rc) should be set to either SQLITE_DONE ** or an error code. */ sqlite3_backup_step(&b, 0x7FFFFFFF); assert( b.rc!=SQLITE_OK ); rc = sqlite3_backup_finish(&b); if( rc==SQLITE_OK ){ pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; }else{ sqlite3PagerClearCache(sqlite3BtreePager(b.pDest)); } assert( sqlite3BtreeIsInTrans(pTo)==0 ); copy_finished: sqlite3BtreeLeave(pFrom); sqlite3BtreeLeave(pTo); return rc; } #endif /* SQLITE_OMIT_VACUUM */ /************** End of backup.c **********************************************/ /************** Begin file vdbemem.c *****************************************/ /* ** 2004 May 26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code use to manipulate "Mem" structure. A "Mem" ** stores a single value in the VDBE. Mem is an opaque structure visible ** only within the VDBE. Interface routines refer to a Mem using the ** name sqlite_value */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #ifdef SQLITE_DEBUG /* ** Check invariants on a Mem object. ** ** This routine is intended for use inside of assert() statements, like ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) ); */ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){ /* If MEM_Dyn is set then Mem.xDel!=0. ** Mem.xDel is might not be initialized if MEM_Dyn is clear. */ assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 ); /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we ** ensure that if Mem.szMalloc>0 then it is safe to do ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn. ** That saves a few cycles in inner loops. */ assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 ); /* Cannot be both MEM_Int and MEM_Real at the same time */ assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) ); /* The szMalloc field holds the correct memory allocation size */ assert( p->szMalloc==0 || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) ); /* If p holds a string or blob, the Mem.z must point to exactly ** one of the following: ** ** (1) Memory in Mem.zMalloc and managed by the Mem object ** (2) Memory to be freed using Mem.xDel ** (3) An ephemeral string or blob ** (4) A static string or blob */ if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){ assert( ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) + ((p->flags&MEM_Dyn)!=0 ? 1 : 0) + ((p->flags&MEM_Ephem)!=0 ? 1 : 0) + ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1 ); } return 1; } #endif /* ** If pMem is an object with a valid string representation, this routine ** ensures the internal encoding for the string representation is ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE. ** ** If pMem is not a string object, or the encoding of the string ** representation is already stored using the requested encoding, then this ** routine is a no-op. ** ** SQLITE_OK is returned if the conversion is successful (or not required). ** SQLITE_NOMEM may be returned if a malloc() fails during conversion ** between formats. */ SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ #ifndef SQLITE_OMIT_UTF16 int rc; #endif assert( (pMem->flags&MEM_RowSet)==0 ); assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE || desiredEnc==SQLITE_UTF16BE ); if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){ return SQLITE_OK; } assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); #ifdef SQLITE_OMIT_UTF16 return SQLITE_ERROR; #else /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned, ** then the encoding of the value may not have changed. */ rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc); assert(rc==SQLITE_OK || rc==SQLITE_NOMEM); assert(rc==SQLITE_OK || pMem->enc!=desiredEnc); assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc); return rc; #endif } /* ** Make sure pMem->z points to a writable allocation of at least ** min(n,32) bytes. ** ** If the bPreserve argument is true, then copy of the content of ** pMem->z into the new allocation. pMem must be either a string or ** blob if bPreserve is true. If bPreserve is false, any prior content ** in pMem->z is discarded. */ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){ assert( sqlite3VdbeCheckMemInvariants(pMem) ); assert( (pMem->flags&MEM_RowSet)==0 ); testcase( pMem->db==0 ); /* If the bPreserve flag is set to true, then the memory cell must already ** contain a valid string or blob value. */ assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) ); testcase( bPreserve && pMem->z==0 ); assert( pMem->szMalloc==0 || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) ); if( pMem->szMalloc<n ){ if( n<32 ) n = 32; if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){ pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n); bPreserve = 0; }else{ if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc); pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n); } if( pMem->zMalloc==0 ){ sqlite3VdbeMemSetNull(pMem); pMem->z = 0; pMem->szMalloc = 0; return SQLITE_NOMEM_BKPT; }else{ pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); } } if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){ memcpy(pMem->zMalloc, pMem->z, pMem->n); } if( (pMem->flags&MEM_Dyn)!=0 ){ assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC ); pMem->xDel((void *)(pMem->z)); } pMem->z = pMem->zMalloc; pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static); return SQLITE_OK; } /* ** Change the pMem->zMalloc allocation to be at least szNew bytes. ** If pMem->zMalloc already meets or exceeds the requested size, this ** routine is a no-op. ** ** Any prior string or blob content in the pMem object may be discarded. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null ** values are preserved. ** ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM) ** if unable to complete the resizing. */ SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){ assert( szNew>0 ); assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 ); if( pMem->szMalloc<szNew ){ return sqlite3VdbeMemGrow(pMem, szNew, 0); } assert( (pMem->flags & MEM_Dyn)==0 ); pMem->z = pMem->zMalloc; pMem->flags &= (MEM_Null|MEM_Int|MEM_Real); return SQLITE_OK; } /* ** Change pMem so that its MEM_Str or MEM_Blob value is stored in ** MEM.zMalloc, where it can be safely written. ** ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails. */ SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( (pMem->flags&MEM_RowSet)==0 ); if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){ if( ExpandBlob(pMem) ) return SQLITE_NOMEM; if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){ if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){ return SQLITE_NOMEM_BKPT; } pMem->z[pMem->n] = 0; pMem->z[pMem->n+1] = 0; pMem->flags |= MEM_Term; } } pMem->flags &= ~MEM_Ephem; #ifdef SQLITE_DEBUG pMem->pScopyFrom = 0; #endif return SQLITE_OK; } /* ** If the given Mem* has a zero-filled tail, turn it into an ordinary ** blob stored in dynamically allocated space. */ #ifndef SQLITE_OMIT_INCRBLOB SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){ int nByte; assert( pMem->flags & MEM_Zero ); assert( pMem->flags&MEM_Blob ); assert( (pMem->flags&MEM_RowSet)==0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); /* Set nByte to the number of bytes required to store the expanded blob. */ nByte = pMem->n + pMem->u.nZero; if( nByte<=0 ){ nByte = 1; } if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){ return SQLITE_NOMEM_BKPT; } memset(&pMem->z[pMem->n], 0, pMem->u.nZero); pMem->n += pMem->u.nZero; pMem->flags &= ~(MEM_Zero|MEM_Term); return SQLITE_OK; } #endif /* ** It is already known that pMem contains an unterminated string. ** Add the zero terminator. */ static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){ if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){ return SQLITE_NOMEM_BKPT; } pMem->z[pMem->n] = 0; pMem->z[pMem->n+1] = 0; pMem->flags |= MEM_Term; return SQLITE_OK; } /* ** Make sure the given Mem is \u0000 terminated. */ SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) ); testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 ); if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){ return SQLITE_OK; /* Nothing to do */ }else{ return vdbeMemAddTerminator(pMem); } } /* ** Add MEM_Str to the set of representations for the given Mem. Numbers ** are converted using sqlite3_snprintf(). Converting a BLOB to a string ** is a no-op. ** ** Existing representations MEM_Int and MEM_Real are invalidated if ** bForce is true but are retained if bForce is false. ** ** A MEM_Null value will never be passed to this function. This function is ** used for converting values to text for returning to the user (i.e. via ** sqlite3_value_text()), or for ensuring that values to be used as btree ** keys are strings. In the former case a NULL pointer is returned the ** user and the latter is an internal programming error. */ SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){ int fg = pMem->flags; const int nByte = 32; assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( !(fg&MEM_Zero) ); assert( !(fg&(MEM_Str|MEM_Blob)) ); assert( fg&(MEM_Int|MEM_Real) ); assert( (pMem->flags&MEM_RowSet)==0 ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){ pMem->enc = 0; return SQLITE_NOMEM_BKPT; } /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8 ** string representation of the value. Then, if the required encoding ** is UTF-16le or UTF-16be do a translation. ** ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16. */ if( fg & MEM_Int ){ sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i); }else{ assert( fg & MEM_Real ); sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r); } pMem->n = sqlite3Strlen30(pMem->z); pMem->enc = SQLITE_UTF8; pMem->flags |= MEM_Str|MEM_Term; if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real); sqlite3VdbeChangeEncoding(pMem, enc); return SQLITE_OK; } /* ** Memory cell pMem contains the context of an aggregate function. ** This routine calls the finalize method for that function. The ** result of the aggregate is stored back into pMem. ** ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK ** otherwise. */ SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){ int rc = SQLITE_OK; if( ALWAYS(pFunc && pFunc->xFinalize) ){ sqlite3_context ctx; Mem t; assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); memset(&ctx, 0, sizeof(ctx)); memset(&t, 0, sizeof(t)); t.flags = MEM_Null; t.db = pMem->db; ctx.pOut = &t; ctx.pMem = pMem; ctx.pFunc = pFunc; pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */ assert( (pMem->flags & MEM_Dyn)==0 ); if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc); memcpy(pMem, &t, sizeof(t)); rc = ctx.isError; } return rc; } /* ** If the memory cell contains a value that must be freed by ** invoking the external callback in Mem.xDel, then this routine ** will free that value. It also sets Mem.flags to MEM_Null. ** ** This is a helper routine for sqlite3VdbeMemSetNull() and ** for sqlite3VdbeMemRelease(). Use those other routines as the ** entry point for releasing Mem resources. */ static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){ assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) ); assert( VdbeMemDynamic(p) ); if( p->flags&MEM_Agg ){ sqlite3VdbeMemFinalize(p, p->u.pDef); assert( (p->flags & MEM_Agg)==0 ); testcase( p->flags & MEM_Dyn ); } if( p->flags&MEM_Dyn ){ assert( (p->flags&MEM_RowSet)==0 ); assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 ); p->xDel((void *)p->z); }else if( p->flags&MEM_RowSet ){ sqlite3RowSetClear(p->u.pRowSet); }else if( p->flags&MEM_Frame ){ VdbeFrame *pFrame = p->u.pFrame; pFrame->pParent = pFrame->v->pDelFrame; pFrame->v->pDelFrame = pFrame; } p->flags = MEM_Null; } /* ** Release memory held by the Mem p, both external memory cleared ** by p->xDel and memory in p->zMalloc. ** ** This is a helper routine invoked by sqlite3VdbeMemRelease() in ** the unusual case where there really is memory in p that needs ** to be freed. */ static SQLITE_NOINLINE void vdbeMemClear(Mem *p){ if( VdbeMemDynamic(p) ){ vdbeMemClearExternAndSetNull(p); } if( p->szMalloc ){ sqlite3DbFree(p->db, p->zMalloc); p->szMalloc = 0; } p->z = 0; } /* ** Release any memory resources held by the Mem. Both the memory that is ** free by Mem.xDel and the Mem.zMalloc allocation are freed. ** ** Use this routine prior to clean up prior to abandoning a Mem, or to ** reset a Mem back to its minimum memory utilization. ** ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space ** prior to inserting new content into the Mem. */ SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){ assert( sqlite3VdbeCheckMemInvariants(p) ); if( VdbeMemDynamic(p) || p->szMalloc ){ vdbeMemClear(p); } } /* ** Convert a 64-bit IEEE double into a 64-bit signed integer. ** If the double is out of range of a 64-bit signed integer then ** return the closest available 64-bit signed integer. */ static i64 doubleToInt64(double r){ #ifdef SQLITE_OMIT_FLOATING_POINT /* When floating-point is omitted, double and int64 are the same thing */ return r; #else /* ** Many compilers we encounter do not define constants for the ** minimum and maximum 64-bit integers, or they define them ** inconsistently. And many do not understand the "LL" notation. ** So we define our own static constants here using nothing ** larger than a 32-bit integer constant. */ static const i64 maxInt = LARGEST_INT64; static const i64 minInt = SMALLEST_INT64; if( r<=(double)minInt ){ return minInt; }else if( r>=(double)maxInt ){ return maxInt; }else{ return (i64)r; } #endif } /* ** Return some kind of integer value which is the best we can do ** at representing the value that *pMem describes as an integer. ** If pMem is an integer, then the value is exact. If pMem is ** a floating-point then the value returned is the integer part. ** If pMem is a string or blob, then we make an attempt to convert ** it into an integer and return that. If pMem represents an ** an SQL-NULL value, return 0. ** ** If pMem represents a string value, its encoding might be changed. */ SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){ int flags; assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); flags = pMem->flags; if( flags & MEM_Int ){ return pMem->u.i; }else if( flags & MEM_Real ){ return doubleToInt64(pMem->u.r); }else if( flags & (MEM_Str|MEM_Blob) ){ i64 value = 0; assert( pMem->z || pMem->n==0 ); sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc); return value; }else{ return 0; } } /* ** Return the best representation of pMem that we can get into a ** double. If pMem is already a double or an integer, return its ** value. If it is a string or blob, try to convert it to a double. ** If it is a NULL, return 0.0. */ SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); if( pMem->flags & MEM_Real ){ return pMem->u.r; }else if( pMem->flags & MEM_Int ){ return (double)pMem->u.i; }else if( pMem->flags & (MEM_Str|MEM_Blob) ){ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ double val = (double)0; sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc); return val; }else{ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ return (double)0; } } /* ** The MEM structure is already a MEM_Real. Try to also make it a ** MEM_Int if we can. */ SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){ i64 ix; assert( pMem->flags & MEM_Real ); assert( (pMem->flags & MEM_RowSet)==0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); ix = doubleToInt64(pMem->u.r); /* Only mark the value as an integer if ** ** (1) the round-trip conversion real->int->real is a no-op, and ** (2) The integer is neither the largest nor the smallest ** possible integer (ticket #3922) ** ** The second and third terms in the following conditional enforces ** the second condition under the assumption that addition overflow causes ** values to wrap around. */ if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){ pMem->u.i = ix; MemSetTypeFlag(pMem, MEM_Int); } } /* ** Convert pMem to type integer. Invalidate any prior representations. */ SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( (pMem->flags & MEM_RowSet)==0 ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); pMem->u.i = sqlite3VdbeIntValue(pMem); MemSetTypeFlag(pMem, MEM_Int); return SQLITE_OK; } /* ** Convert pMem so that it is of type MEM_Real. ** Invalidate any prior representations. */ SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); pMem->u.r = sqlite3VdbeRealValue(pMem); MemSetTypeFlag(pMem, MEM_Real); return SQLITE_OK; } /* ** Convert pMem so that it has types MEM_Real or MEM_Int or both. ** Invalidate any prior representations. ** ** Every effort is made to force the conversion, even if the input ** is a string that does not look completely like a number. Convert ** as much of the string as we can and ignore the rest. */ SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){ assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){ MemSetTypeFlag(pMem, MEM_Int); }else{ pMem->u.r = sqlite3VdbeRealValue(pMem); MemSetTypeFlag(pMem, MEM_Real); sqlite3VdbeIntegerAffinity(pMem); } } assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 ); pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero); return SQLITE_OK; } /* ** Cast the datatype of the value in pMem according to the affinity ** "aff". Casting is different from applying affinity in that a cast ** is forced. In other words, the value is converted into the desired ** affinity even if that results in loss of data. This routine is ** used (for example) to implement the SQL "cast()" operator. */ SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){ if( pMem->flags & MEM_Null ) return; switch( aff ){ case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */ if( (pMem->flags & MEM_Blob)==0 ){ sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); assert( pMem->flags & MEM_Str || pMem->db->mallocFailed ); if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob); }else{ pMem->flags &= ~(MEM_TypeMask&~MEM_Blob); } break; } case SQLITE_AFF_NUMERIC: { sqlite3VdbeMemNumerify(pMem); break; } case SQLITE_AFF_INTEGER: { sqlite3VdbeMemIntegerify(pMem); break; } case SQLITE_AFF_REAL: { sqlite3VdbeMemRealify(pMem); break; } default: { assert( aff==SQLITE_AFF_TEXT ); assert( MEM_Str==(MEM_Blob>>3) ); pMem->flags |= (pMem->flags&MEM_Blob)>>3; sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); assert( pMem->flags & MEM_Str || pMem->db->mallocFailed ); pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero); break; } } } /* ** Initialize bulk memory to be a consistent Mem object. ** ** The minimum amount of initialization feasible is performed. */ SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){ assert( (flags & ~MEM_TypeMask)==0 ); pMem->flags = flags; pMem->db = db; pMem->szMalloc = 0; } /* ** Delete any previous value and set the value stored in *pMem to NULL. ** ** This routine calls the Mem.xDel destructor to dispose of values that ** require the destructor. But it preserves the Mem.zMalloc memory allocation. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this ** routine to invoke the destructor and deallocates Mem.zMalloc. ** ** Use this routine to reset the Mem prior to insert a new value. ** ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it. */ SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){ if( VdbeMemDynamic(pMem) ){ vdbeMemClearExternAndSetNull(pMem); }else{ pMem->flags = MEM_Null; } } SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){ sqlite3VdbeMemSetNull((Mem*)p); } /* ** Delete any previous value and set the value to be a BLOB of length ** n containing all zeros. */ SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){ sqlite3VdbeMemRelease(pMem); pMem->flags = MEM_Blob|MEM_Zero; pMem->n = 0; if( n<0 ) n = 0; pMem->u.nZero = n; pMem->enc = SQLITE_UTF8; pMem->z = 0; } /* ** The pMem is known to contain content that needs to be destroyed prior ** to a value change. So invoke the destructor, then set the value to ** a 64-bit integer. */ static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){ sqlite3VdbeMemSetNull(pMem); pMem->u.i = val; pMem->flags = MEM_Int; } /* ** Delete any previous value and set the value stored in *pMem to val, ** manifest type INTEGER. */ SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ if( VdbeMemDynamic(pMem) ){ vdbeReleaseAndSetInt64(pMem, val); }else{ pMem->u.i = val; pMem->flags = MEM_Int; } } #ifndef SQLITE_OMIT_FLOATING_POINT /* ** Delete any previous value and set the value stored in *pMem to val, ** manifest type REAL. */ SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){ sqlite3VdbeMemSetNull(pMem); if( !sqlite3IsNaN(val) ){ pMem->u.r = val; pMem->flags = MEM_Real; } } #endif /* ** Delete any previous value and set the value of pMem to be an ** empty boolean index. */ SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){ sqlite3 *db = pMem->db; assert( db!=0 ); assert( (pMem->flags & MEM_RowSet)==0 ); sqlite3VdbeMemRelease(pMem); pMem->zMalloc = sqlite3DbMallocRawNN(db, 64); if( db->mallocFailed ){ pMem->flags = MEM_Null; pMem->szMalloc = 0; }else{ assert( pMem->zMalloc ); pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc); pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc); assert( pMem->u.pRowSet!=0 ); pMem->flags = MEM_RowSet; } } /* ** Return true if the Mem object contains a TEXT or BLOB that is ** too large - whose size exceeds SQLITE_MAX_LENGTH. */ SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){ assert( p->db!=0 ); if( p->flags & (MEM_Str|MEM_Blob) ){ int n = p->n; if( p->flags & MEM_Zero ){ n += p->u.nZero; } return n>p->db->aLimit[SQLITE_LIMIT_LENGTH]; } return 0; } #ifdef SQLITE_DEBUG /* ** This routine prepares a memory cell for modification by breaking ** its link to a shallow copy and by marking any current shallow ** copies of this cell as invalid. ** ** This is used for testing and debugging only - to make sure shallow ** copies are not misused. */ SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ int i; Mem *pX; for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){ if( pX->pScopyFrom==pMem ){ pX->flags |= MEM_Undefined; pX->pScopyFrom = 0; } } pMem->pScopyFrom = 0; } #endif /* SQLITE_DEBUG */ /* ** Make an shallow copy of pFrom into pTo. Prior contents of ** pTo are freed. The pFrom->z field is not duplicated. If ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z ** and flags gets srcType (either MEM_Ephem or MEM_Static). */ static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){ vdbeMemClearExternAndSetNull(pTo); assert( !VdbeMemDynamic(pTo) ); sqlite3VdbeMemShallowCopy(pTo, pFrom, eType); } SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){ assert( (pFrom->flags & MEM_RowSet)==0 ); assert( pTo->db==pFrom->db ); if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; } memcpy(pTo, pFrom, MEMCELLSIZE); if( (pFrom->flags&MEM_Static)==0 ){ pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem); assert( srcType==MEM_Ephem || srcType==MEM_Static ); pTo->flags |= srcType; } } /* ** Make a full copy of pFrom into pTo. Prior contents of pTo are ** freed before the copy is made. */ SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ int rc = SQLITE_OK; assert( (pFrom->flags & MEM_RowSet)==0 ); if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo); memcpy(pTo, pFrom, MEMCELLSIZE); pTo->flags &= ~MEM_Dyn; if( pTo->flags&(MEM_Str|MEM_Blob) ){ if( 0==(pFrom->flags&MEM_Static) ){ pTo->flags |= MEM_Ephem; rc = sqlite3VdbeMemMakeWriteable(pTo); } } return rc; } /* ** Transfer the contents of pFrom to pTo. Any existing value in pTo is ** freed. If pFrom contains ephemeral data, a copy is made. ** ** pFrom contains an SQL NULL when this routine returns. */ SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) ); assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) ); assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db ); sqlite3VdbeMemRelease(pTo); memcpy(pTo, pFrom, sizeof(Mem)); pFrom->flags = MEM_Null; pFrom->szMalloc = 0; } /* ** Change the value of a Mem to be a string or a BLOB. ** ** The memory management strategy depends on the value of the xDel ** parameter. If the value passed is SQLITE_TRANSIENT, then the ** string is copied into a (possibly existing) buffer managed by the ** Mem structure. Otherwise, any existing buffer is freed and the ** pointer copied. ** ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH ** size limit) then no memory allocation occurs. If the string can be ** stored without allocating memory, then it is. If a memory allocation ** is required to store the string, then value of pMem is unchanged. In ** either case, SQLITE_TOOBIG is returned. */ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( Mem *pMem, /* Memory cell to set to string value */ const char *z, /* String pointer */ int n, /* Bytes in string, or negative */ u8 enc, /* Encoding of z. 0 for BLOBs */ void (*xDel)(void*) /* Destructor function */ ){ int nByte = n; /* New value for pMem->n */ int iLimit; /* Maximum allowed string or blob size */ u16 flags = 0; /* New value for pMem->flags */ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); assert( (pMem->flags & MEM_RowSet)==0 ); /* If z is a NULL pointer, set pMem to contain an SQL NULL. */ if( !z ){ sqlite3VdbeMemSetNull(pMem); return SQLITE_OK; } if( pMem->db ){ iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH]; }else{ iLimit = SQLITE_MAX_LENGTH; } flags = (enc==0?MEM_Blob:MEM_Str); if( nByte<0 ){ assert( enc!=0 ); if( enc==SQLITE_UTF8 ){ nByte = sqlite3Strlen30(z); if( nByte>iLimit ) nByte = iLimit+1; }else{ for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){} } flags |= MEM_Term; } /* The following block sets the new values of Mem.z and Mem.xDel. It ** also sets a flag in local variable "flags" to indicate the memory ** management (one of MEM_Dyn or MEM_Static). */ if( xDel==SQLITE_TRANSIENT ){ int nAlloc = nByte; if( flags&MEM_Term ){ nAlloc += (enc==SQLITE_UTF8?1:2); } if( nByte>iLimit ){ return SQLITE_TOOBIG; } testcase( nAlloc==0 ); testcase( nAlloc==31 ); testcase( nAlloc==32 ); if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){ return SQLITE_NOMEM_BKPT; } memcpy(pMem->z, z, nAlloc); }else if( xDel==SQLITE_DYNAMIC ){ sqlite3VdbeMemRelease(pMem); pMem->zMalloc = pMem->z = (char *)z; pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); }else{ sqlite3VdbeMemRelease(pMem); pMem->z = (char *)z; pMem->xDel = xDel; flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn); } pMem->n = nByte; pMem->flags = flags; pMem->enc = (enc==0 ? SQLITE_UTF8 : enc); #ifndef SQLITE_OMIT_UTF16 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){ return SQLITE_NOMEM_BKPT; } #endif if( nByte>iLimit ){ return SQLITE_TOOBIG; } return SQLITE_OK; } /* ** Move data out of a btree key or data field and into a Mem structure. ** The data is payload from the entry that pCur is currently pointing ** to. offset and amt determine what portion of the data or key to retrieve. ** The result is written into the pMem element. ** ** The pMem object must have been initialized. This routine will use ** pMem->zMalloc to hold the content from the btree, if possible. New ** pMem->zMalloc space will be allocated if necessary. The calling routine ** is responsible for making sure that the pMem object is eventually ** destroyed. ** ** If this routine fails for any reason (malloc returns NULL or unable ** to read from the disk) then the pMem is left in an inconsistent state. */ static SQLITE_NOINLINE int vdbeMemFromBtreeResize( BtCursor *pCur, /* Cursor pointing at record to retrieve. */ u32 offset, /* Offset from the start of data to return bytes from. */ u32 amt, /* Number of bytes to return. */ Mem *pMem /* OUT: Return data in this Mem structure. */ ){ int rc; pMem->flags = MEM_Null; if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){ rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z); if( rc==SQLITE_OK ){ pMem->z[amt] = 0; pMem->z[amt+1] = 0; pMem->flags = MEM_Blob|MEM_Term; pMem->n = (int)amt; }else{ sqlite3VdbeMemRelease(pMem); } } return rc; } SQLITE_PRIVATE int sqlite3VdbeMemFromBtree( BtCursor *pCur, /* Cursor pointing at record to retrieve. */ u32 offset, /* Offset from the start of data to return bytes from. */ u32 amt, /* Number of bytes to return. */ Mem *pMem /* OUT: Return data in this Mem structure. */ ){ char *zData; /* Data from the btree layer */ u32 available = 0; /* Number of bytes available on the local btree page */ int rc = SQLITE_OK; /* Return code */ assert( sqlite3BtreeCursorIsValid(pCur) ); assert( !VdbeMemDynamic(pMem) ); /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() ** that both the BtShared and database handle mutexes are held. */ assert( (pMem->flags & MEM_RowSet)==0 ); zData = (char *)sqlite3BtreePayloadFetch(pCur, &available); assert( zData!=0 ); if( offset+amt<=available ){ pMem->z = &zData[offset]; pMem->flags = MEM_Blob|MEM_Ephem; pMem->n = (int)amt; }else{ rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem); } return rc; } /* ** The pVal argument is known to be a value other than NULL. ** Convert it into a string with encoding enc and return a pointer ** to a zero-terminated version of that string. */ static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){ assert( pVal!=0 ); assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); assert( (pVal->flags & MEM_RowSet)==0 ); assert( (pVal->flags & (MEM_Null))==0 ); if( pVal->flags & (MEM_Blob|MEM_Str) ){ if( ExpandBlob(pVal) ) return 0; pVal->flags |= MEM_Str; if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){ sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED); } if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){ assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 ); if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){ return 0; } } sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */ }else{ sqlite3VdbeMemStringify(pVal, enc, 0); assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) ); } assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0 || pVal->db->mallocFailed ); if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){ return pVal->z; }else{ return 0; } } /* This function is only available internally, it is not part of the ** external API. It works in a similar way to sqlite3_value_text(), ** except the data returned is in the encoding specified by the second ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or ** SQLITE_UTF8. ** ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED. ** If that is the case, then the result must be aligned on an even byte ** boundary. */ SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){ if( !pVal ) return 0; assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); assert( (pVal->flags & MEM_RowSet)==0 ); if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){ return pVal->z; } if( pVal->flags&MEM_Null ){ return 0; } return valueToText(pVal, enc); } /* ** Create a new sqlite3_value object. */ SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){ Mem *p = sqlite3DbMallocZero(db, sizeof(*p)); if( p ){ p->flags = MEM_Null; p->db = db; } return p; } /* ** Context object passed by sqlite3Stat4ProbeSetValue() through to ** valueNew(). See comments above valueNew() for details. */ struct ValueNewStat4Ctx { Parse *pParse; Index *pIdx; UnpackedRecord **ppRec; int iVal; }; /* ** Allocate and return a pointer to a new sqlite3_value object. If ** the second argument to this function is NULL, the object is allocated ** by calling sqlite3ValueNew(). ** ** Otherwise, if the second argument is non-zero, then this function is ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not ** already been allocated, allocate the UnpackedRecord structure that ** that function will return to its caller here. Then return a pointer to ** an sqlite3_value within the UnpackedRecord.a[] array. */ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( p ){ UnpackedRecord *pRec = p->ppRec[0]; if( pRec==0 ){ Index *pIdx = p->pIdx; /* Index being probed */ int nByte; /* Bytes of space to allocate */ int i; /* Counter variable */ int nCol = pIdx->nColumn; /* Number of index columns including rowid */ nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord)); pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte); if( pRec ){ pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx); if( pRec->pKeyInfo ){ assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol ); assert( pRec->pKeyInfo->enc==ENC(db) ); pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord))); for(i=0; i<nCol; i++){ pRec->aMem[i].flags = MEM_Null; pRec->aMem[i].db = db; } }else{ sqlite3DbFree(db, pRec); pRec = 0; } } if( pRec==0 ) return 0; p->ppRec[0] = pRec; } pRec->nField = p->iVal+1; return &pRec->aMem[p->iVal]; } #else UNUSED_PARAMETER(p); #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */ return sqlite3ValueNew(db); } /* ** The expression object indicated by the second argument is guaranteed ** to be a scalar SQL function. If ** ** * all function arguments are SQL literals, ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and ** * the SQLITE_FUNC_NEEDCOLL function flag is not set, ** ** then this routine attempts to invoke the SQL function. Assuming no ** error occurs, output parameter (*ppVal) is set to point to a value ** object containing the result before returning SQLITE_OK. ** ** Affinity aff is applied to the result of the function before returning. ** If the result is a text value, the sqlite3_value object uses encoding ** enc. ** ** If the conditions above are not met, this function returns SQLITE_OK ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to ** NULL and an SQLite error code returned. */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static int valueFromFunction( sqlite3 *db, /* The database connection */ Expr *p, /* The expression to evaluate */ u8 enc, /* Encoding to use */ u8 aff, /* Affinity to use */ sqlite3_value **ppVal, /* Write the new value here */ struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */ ){ sqlite3_context ctx; /* Context object for function invocation */ sqlite3_value **apVal = 0; /* Function arguments */ int nVal = 0; /* Size of apVal[] array */ FuncDef *pFunc = 0; /* Function definition */ sqlite3_value *pVal = 0; /* New value */ int rc = SQLITE_OK; /* Return code */ ExprList *pList = 0; /* Function arguments */ int i; /* Iterator variable */ assert( pCtx!=0 ); assert( (p->flags & EP_TokenOnly)==0 ); pList = p->x.pList; if( pList ) nVal = pList->nExpr; pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0); assert( pFunc ); if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) ){ return SQLITE_OK; } if( pList ){ apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal); if( apVal==0 ){ rc = SQLITE_NOMEM_BKPT; goto value_from_function_out; } for(i=0; i<nVal; i++){ rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]); if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out; } } pVal = valueNew(db, pCtx); if( pVal==0 ){ rc = SQLITE_NOMEM_BKPT; goto value_from_function_out; } assert( pCtx->pParse->rc==SQLITE_OK ); memset(&ctx, 0, sizeof(ctx)); ctx.pOut = pVal; ctx.pFunc = pFunc; pFunc->xSFunc(&ctx, nVal, apVal); if( ctx.isError ){ rc = ctx.isError; sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal)); }else{ sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8); assert( rc==SQLITE_OK ); rc = sqlite3VdbeChangeEncoding(pVal, enc); if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){ rc = SQLITE_TOOBIG; pCtx->pParse->nErr++; } } pCtx->pParse->rc = rc; value_from_function_out: if( rc!=SQLITE_OK ){ pVal = 0; } if( apVal ){ for(i=0; i<nVal; i++){ sqlite3ValueFree(apVal[i]); } sqlite3DbFree(db, apVal); } *ppVal = pVal; return rc; } #else # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */ /* ** Extract a value from the supplied expression in the manner described ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object ** using valueNew(). ** ** If pCtx is NULL and an error occurs after the sqlite3_value object ** has been allocated, it is freed before returning. Or, if pCtx is not ** NULL, it is assumed that the caller will free any allocated object ** in all cases. */ static int valueFromExpr( sqlite3 *db, /* The database connection */ Expr *pExpr, /* The expression to evaluate */ u8 enc, /* Encoding to use */ u8 affinity, /* Affinity to use */ sqlite3_value **ppVal, /* Write the new value here */ struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */ ){ int op; char *zVal = 0; sqlite3_value *pVal = 0; int negInt = 1; const char *zNeg = ""; int rc = SQLITE_OK; assert( pExpr!=0 ); while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft; if( NEVER(op==TK_REGISTER) ) op = pExpr->op2; /* Compressed expressions only appear when parsing the DEFAULT clause ** on a table column definition, and hence only when pCtx==0. This ** check ensures that an EP_TokenOnly expression is never passed down ** into valueFromFunction(). */ assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 ); if( op==TK_CAST ){ u8 aff = sqlite3AffinityType(pExpr->u.zToken,0); rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx); testcase( rc!=SQLITE_OK ); if( *ppVal ){ sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8); sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8); } return rc; } /* Handle negative integers in a single step. This is needed in the ** case when the value is -9223372036854775808. */ if( op==TK_UMINUS && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){ pExpr = pExpr->pLeft; op = pExpr->op; negInt = -1; zNeg = "-"; } if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){ pVal = valueNew(db, pCtx); if( pVal==0 ) goto no_mem; if( ExprHasProperty(pExpr, EP_IntValue) ){ sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt); }else{ zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken); if( zVal==0 ) goto no_mem; sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC); } if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){ sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8); }else{ sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8); } if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str; if( enc!=SQLITE_UTF8 ){ rc = sqlite3VdbeChangeEncoding(pVal, enc); } }else if( op==TK_UMINUS ) { /* This branch happens for multiple negative signs. Ex: -(-5) */ if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) && pVal!=0 ){ sqlite3VdbeMemNumerify(pVal); if( pVal->flags & MEM_Real ){ pVal->u.r = -pVal->u.r; }else if( pVal->u.i==SMALLEST_INT64 ){ pVal->u.r = -(double)SMALLEST_INT64; MemSetTypeFlag(pVal, MEM_Real); }else{ pVal->u.i = -pVal->u.i; } sqlite3ValueApplyAffinity(pVal, affinity, enc); } }else if( op==TK_NULL ){ pVal = valueNew(db, pCtx); if( pVal==0 ) goto no_mem; sqlite3VdbeMemNumerify(pVal); } #ifndef SQLITE_OMIT_BLOB_LITERAL else if( op==TK_BLOB ){ int nVal; assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); assert( pExpr->u.zToken[1]=='\'' ); pVal = valueNew(db, pCtx); if( !pVal ) goto no_mem; zVal = &pExpr->u.zToken[2]; nVal = sqlite3Strlen30(zVal)-1; assert( zVal[nVal]=='\'' ); sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2, 0, SQLITE_DYNAMIC); } #endif #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 else if( op==TK_FUNCTION && pCtx!=0 ){ rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx); } #endif *ppVal = pVal; return rc; no_mem: sqlite3OomFault(db); sqlite3DbFree(db, zVal); assert( *ppVal==0 ); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( pCtx==0 ) sqlite3ValueFree(pVal); #else assert( pCtx==0 ); sqlite3ValueFree(pVal); #endif return SQLITE_NOMEM_BKPT; } /* ** Create a new sqlite3_value object, containing the value of pExpr. ** ** This only works for very simple expressions that consist of one constant ** token (i.e. "5", "5.1", "'a string'"). If the expression can ** be converted directly into a value, then the value is allocated and ** a pointer written to *ppVal. The caller is responsible for deallocating ** the value by passing it to sqlite3ValueFree() later on. If the expression ** cannot be converted to a value, then *ppVal is set to NULL. */ SQLITE_PRIVATE int sqlite3ValueFromExpr( sqlite3 *db, /* The database connection */ Expr *pExpr, /* The expression to evaluate */ u8 enc, /* Encoding to use */ u8 affinity, /* Affinity to use */ sqlite3_value **ppVal /* Write the new value here */ ){ return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0; } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** The implementation of the sqlite_record() function. This function accepts ** a single argument of any type. The return value is a formatted database ** record (a blob) containing the argument value. ** ** This is used to convert the value stored in the 'sample' column of the ** sqlite_stat3 table to the record format SQLite uses internally. */ static void recordFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const int file_format = 1; u32 iSerial; /* Serial type */ int nSerial; /* Bytes of space for iSerial as varint */ u32 nVal; /* Bytes of space required for argv[0] */ int nRet; sqlite3 *db; u8 *aRet; UNUSED_PARAMETER( argc ); iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal); nSerial = sqlite3VarintLen(iSerial); db = sqlite3_context_db_handle(context); nRet = 1 + nSerial + nVal; aRet = sqlite3DbMallocRawNN(db, nRet); if( aRet==0 ){ sqlite3_result_error_nomem(context); }else{ aRet[0] = nSerial+1; putVarint32(&aRet[1], iSerial); sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial); sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT); sqlite3DbFree(db, aRet); } } /* ** Register built-in functions used to help read ANALYZE data. */ SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){ static FuncDef aAnalyzeTableFuncs[] = { FUNCTION(sqlite_record, 1, 0, 0, recordFunc), }; sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs)); } /* ** Attempt to extract a value from pExpr and use it to construct *ppVal. ** ** If pAlloc is not NULL, then an UnpackedRecord object is created for ** pAlloc if one does not exist and the new value is added to the ** UnpackedRecord object. ** ** A value is extracted in the following cases: ** ** * (pExpr==0). In this case the value is assumed to be an SQL NULL, ** ** * The expression is a bound variable, and this is a reprepare, or ** ** * The expression is a literal value. ** ** On success, *ppVal is made to point to the extracted value. The caller ** is responsible for ensuring that the value is eventually freed. */ static int stat4ValueFromExpr( Parse *pParse, /* Parse context */ Expr *pExpr, /* The expression to extract a value from */ u8 affinity, /* Affinity to use */ struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */ sqlite3_value **ppVal /* OUT: New value object (or NULL) */ ){ int rc = SQLITE_OK; sqlite3_value *pVal = 0; sqlite3 *db = pParse->db; /* Skip over any TK_COLLATE nodes */ pExpr = sqlite3ExprSkipCollate(pExpr); if( !pExpr ){ pVal = valueNew(db, pAlloc); if( pVal ){ sqlite3VdbeMemSetNull((Mem*)pVal); } }else if( pExpr->op==TK_VARIABLE || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE) ){ Vdbe *v; int iBindVar = pExpr->iColumn; sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar); if( (v = pParse->pReprepare)!=0 ){ pVal = valueNew(db, pAlloc); if( pVal ){ rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]); if( rc==SQLITE_OK ){ sqlite3ValueApplyAffinity(pVal, affinity, ENC(db)); } pVal->db = pParse->db; } } }else{ rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc); } assert( pVal==0 || pVal->db==db ); *ppVal = pVal; return rc; } /* ** This function is used to allocate and populate UnpackedRecord ** structures intended to be compared against sample index keys stored ** in the sqlite_stat4 table. ** ** A single call to this function populates zero or more fields of the ** record starting with field iVal (fields are numbered from left to ** right starting with 0). A single field is populated if: ** ** * (pExpr==0). In this case the value is assumed to be an SQL NULL, ** ** * The expression is a bound variable, and this is a reprepare, or ** ** * The sqlite3ValueFromExpr() function is able to extract a value ** from the expression (i.e. the expression is a literal value). ** ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the ** vector components that match either of the two latter criteria listed ** above. ** ** Before any value is appended to the record, the affinity of the ** corresponding column within index pIdx is applied to it. Before ** this function returns, output parameter *pnExtract is set to the ** number of values appended to the record. ** ** When this function is called, *ppRec must either point to an object ** allocated by an earlier call to this function, or must be NULL. If it ** is NULL and a value can be successfully extracted, a new UnpackedRecord ** is allocated (and *ppRec set to point to it) before returning. ** ** Unless an error is encountered, SQLITE_OK is returned. It is not an ** error if a value cannot be extracted from pExpr. If an error does ** occur, an SQLite error code is returned. */ SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( Parse *pParse, /* Parse context */ Index *pIdx, /* Index being probed */ UnpackedRecord **ppRec, /* IN/OUT: Probe record */ Expr *pExpr, /* The expression to extract a value from */ int nElem, /* Maximum number of values to append */ int iVal, /* Array element to populate */ int *pnExtract /* OUT: Values appended to the record */ ){ int rc = SQLITE_OK; int nExtract = 0; if( pExpr==0 || pExpr->op!=TK_SELECT ){ int i; struct ValueNewStat4Ctx alloc; alloc.pParse = pParse; alloc.pIdx = pIdx; alloc.ppRec = ppRec; for(i=0; i<nElem; i++){ sqlite3_value *pVal = 0; Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0); u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i); alloc.iVal = iVal+i; rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal); if( !pVal ) break; nExtract++; } } *pnExtract = nExtract; return rc; } /* ** Attempt to extract a value from expression pExpr using the methods ** as described for sqlite3Stat4ProbeSetValue() above. ** ** If successful, set *ppVal to point to a new value object and return ** SQLITE_OK. If no value can be extracted, but no other error occurs ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error ** does occur, return an SQLite error code. The final value of *ppVal ** is undefined in this case. */ SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr( Parse *pParse, /* Parse context */ Expr *pExpr, /* The expression to extract a value from */ u8 affinity, /* Affinity to use */ sqlite3_value **ppVal /* OUT: New value object (or NULL) */ ){ return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal); } /* ** Extract the iCol-th column from the nRec-byte record in pRec. Write ** the column value into *ppVal. If *ppVal is initially NULL then a new ** sqlite3_value object is allocated. ** ** If *ppVal is initially NULL then the caller is responsible for ** ensuring that the value written into *ppVal is eventually freed. */ SQLITE_PRIVATE int sqlite3Stat4Column( sqlite3 *db, /* Database handle */ const void *pRec, /* Pointer to buffer containing record */ int nRec, /* Size of buffer pRec in bytes */ int iCol, /* Column to extract */ sqlite3_value **ppVal /* OUT: Extracted value */ ){ u32 t; /* a column type code */ int nHdr; /* Size of the header in the record */ int iHdr; /* Next unread header byte */ int iField; /* Next unread data byte */ int szField; /* Size of the current data field */ int i; /* Column index */ u8 *a = (u8*)pRec; /* Typecast byte array */ Mem *pMem = *ppVal; /* Write result into this Mem object */ assert( iCol>0 ); iHdr = getVarint32(a, nHdr); if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT; iField = nHdr; for(i=0; i<=iCol; i++){ iHdr += getVarint32(&a[iHdr], t); testcase( iHdr==nHdr ); testcase( iHdr==nHdr+1 ); if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT; szField = sqlite3VdbeSerialTypeLen(t); iField += szField; } testcase( iField==nRec ); testcase( iField==nRec+1 ); if( iField>nRec ) return SQLITE_CORRUPT_BKPT; if( pMem==0 ){ pMem = *ppVal = sqlite3ValueNew(db); if( pMem==0 ) return SQLITE_NOMEM_BKPT; } sqlite3VdbeSerialGet(&a[iField-szField], t, pMem); pMem->enc = ENC(db); return SQLITE_OK; } /* ** Unless it is NULL, the argument must be an UnpackedRecord object returned ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes ** the object. */ SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){ if( pRec ){ int i; int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField; Mem *aMem = pRec->aMem; sqlite3 *db = aMem[0].db; for(i=0; i<nCol; i++){ sqlite3VdbeMemRelease(&aMem[i]); } sqlite3KeyInfoUnref(pRec->pKeyInfo); sqlite3DbFree(db, pRec); } } #endif /* ifdef SQLITE_ENABLE_STAT4 */ /* ** Change the string value of an sqlite3_value object */ SQLITE_PRIVATE void sqlite3ValueSetStr( sqlite3_value *v, /* Value to be set */ int n, /* Length of string z */ const void *z, /* Text of the new string */ u8 enc, /* Encoding to use */ void (*xDel)(void*) /* Destructor for the string */ ){ if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel); } /* ** Free an sqlite3_value object */ SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){ if( !v ) return; sqlite3VdbeMemRelease((Mem *)v); sqlite3DbFree(((Mem*)v)->db, v); } /* ** The sqlite3ValueBytes() routine returns the number of bytes in the ** sqlite3_value object assuming that it uses the encoding "enc". ** The valueBytes() routine is a helper function. */ static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){ return valueToText(pVal, enc)!=0 ? pVal->n : 0; } SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){ Mem *p = (Mem*)pVal; assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 ); if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){ return p->n; } if( (p->flags & MEM_Blob)!=0 ){ if( p->flags & MEM_Zero ){ return p->n + p->u.nZero; }else{ return p->n; } } if( p->flags & MEM_Null ) return 0; return valueBytes(pVal, enc); } /************** End of vdbemem.c *********************************************/ /************** Begin file vdbeaux.c *****************************************/ /* ** 2003 September 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used for creating, destroying, and populating ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ /* ** Create a new virtual database engine. */ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){ sqlite3 *db = pParse->db; Vdbe *p; p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) ); if( p==0 ) return 0; memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp)); p->db = db; if( db->pVdbe ){ db->pVdbe->pPrev = p; } p->pNext = db->pVdbe; p->pPrev = 0; db->pVdbe = p; p->magic = VDBE_MAGIC_INIT; p->pParse = pParse; assert( pParse->aLabel==0 ); assert( pParse->nLabel==0 ); assert( pParse->nOpAlloc==0 ); assert( pParse->szOpAlloc==0 ); return p; } /* ** Change the error string stored in Vdbe.zErrMsg */ SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){ va_list ap; sqlite3DbFree(p->db, p->zErrMsg); va_start(ap, zFormat); p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap); va_end(ap); } /* ** Remember the SQL string for a prepared statement. */ SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){ assert( isPrepareV2==1 || isPrepareV2==0 ); if( p==0 ) return; #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG) if( !isPrepareV2 ) return; #endif assert( p->zSql==0 ); p->zSql = sqlite3DbStrNDup(p->db, z, n); p->isPrepareV2 = (u8)isPrepareV2; } /* ** Swap all content between two VDBE structures. */ SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ Vdbe tmp, *pTmp; char *zTmp; assert( pA->db==pB->db ); tmp = *pA; *pA = *pB; *pB = tmp; pTmp = pA->pNext; pA->pNext = pB->pNext; pB->pNext = pTmp; pTmp = pA->pPrev; pA->pPrev = pB->pPrev; pB->pPrev = pTmp; zTmp = pA->zSql; pA->zSql = pB->zSql; pB->zSql = zTmp; pB->isPrepareV2 = pA->isPrepareV2; } /* ** Resize the Vdbe.aOp array so that it is at least nOp elements larger ** than its current size. nOp is guaranteed to be less than or equal ** to 1024/sizeof(Op). ** ** If an out-of-memory error occurs while resizing the array, return ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain ** unchanged (this is so that any opcodes already allocated can be ** correctly deallocated along with the rest of the Vdbe). */ static int growOpArray(Vdbe *v, int nOp){ VdbeOp *pNew; Parse *p = v->pParse; /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force ** more frequent reallocs and hence provide more opportunities for ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array ** by the minimum* amount required until the size reaches 512. Normal ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current ** size of the op array or add 1KB of space, whichever is smaller. */ #ifdef SQLITE_TEST_REALLOC_STRESS int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp); #else int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op))); UNUSED_PARAMETER(nOp); #endif assert( nOp<=(1024/sizeof(Op)) ); assert( nNew>=(p->nOpAlloc+nOp) ); pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op)); if( pNew ){ p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew); p->nOpAlloc = p->szOpAlloc/sizeof(Op); v->aOp = pNew; } return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT); } #ifdef SQLITE_DEBUG /* This routine is just a convenient place to set a breakpoint that will ** fire after each opcode is inserted and displayed using ** "PRAGMA vdbe_addoptrace=on". */ static void test_addop_breakpoint(void){ static int n = 0; n++; } #endif /* ** Add a new instruction to the list of instructions current in the ** VDBE. Return the address of the new instruction. ** ** Parameters: ** ** p Pointer to the VDBE ** ** op The opcode for this instruction ** ** p1, p2, p3 Operands ** ** Use the sqlite3VdbeResolveLabel() function to fix an address and ** the sqlite3VdbeChangeP4() function to change the value of the P4 ** operand. */ static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){ assert( p->pParse->nOpAlloc<=p->nOp ); if( growOpArray(p, 1) ) return 1; assert( p->pParse->nOpAlloc>p->nOp ); return sqlite3VdbeAddOp3(p, op, p1, p2, p3); } SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ int i; VdbeOp *pOp; i = p->nOp; assert( p->magic==VDBE_MAGIC_INIT ); assert( op>=0 && op<0xff ); if( p->pParse->nOpAlloc<=i ){ return growOp3(p, op, p1, p2, p3); } p->nOp++; pOp = &p->aOp[i]; pOp->opcode = (u8)op; pOp->p5 = 0; pOp->p1 = p1; pOp->p2 = p2; pOp->p3 = p3; pOp->p4.p = 0; pOp->p4type = P4_NOTUSED; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS pOp->zComment = 0; #endif #ifdef SQLITE_DEBUG if( p->db->flags & SQLITE_VdbeAddopTrace ){ int jj, kk; Parse *pParse = p->pParse; for(jj=kk=0; jj<pParse->nColCache; jj++){ struct yColCache *x = pParse->aColCache + jj; printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn); kk++; } if( kk ) printf("\n"); sqlite3VdbePrintOp(0, i, &p->aOp[i]); test_addop_breakpoint(); } #endif #ifdef VDBE_PROFILE pOp->cycles = 0; pOp->cnt = 0; #endif #ifdef SQLITE_VDBE_COVERAGE pOp->iSrcLine = 0; #endif return i; } SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){ return sqlite3VdbeAddOp3(p, op, 0, 0, 0); } SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){ return sqlite3VdbeAddOp3(p, op, p1, 0, 0); } SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){ return sqlite3VdbeAddOp3(p, op, p1, p2, 0); } /* Generate code for an unconditional jump to instruction iDest */ SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){ return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0); } /* Generate code to cause the string zStr to be loaded into ** register iDest */ SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){ return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0); } /* ** Generate code that initializes multiple registers to string or integer ** constants. The registers begin with iDest and increase consecutively. ** One register is initialized for each characgter in zTypes[]. For each ** "s" character in zTypes[], the register is a string if the argument is ** not NULL, or OP_Null if the value is a null pointer. For each "i" character ** in zTypes[], the register is initialized to an integer. */ SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){ va_list ap; int i; char c; va_start(ap, zTypes); for(i=0; (c = zTypes[i])!=0; i++){ if( c=='s' ){ const char *z = va_arg(ap, const char*); sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0); }else{ assert( c=='i' ); sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++); } } va_end(ap); } /* ** Add an opcode that includes the p4 value as a pointer. */ SQLITE_PRIVATE int sqlite3VdbeAddOp4( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ int p2, /* The P2 operand */ int p3, /* The P3 operand */ const char *zP4, /* The P4 operand */ int p4type /* P4 operand type */ ){ int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); sqlite3VdbeChangeP4(p, addr, zP4, p4type); return addr; } /* ** Add an opcode that includes the p4 value with a P4_INT64 or ** P4_REAL type. */ SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ int p2, /* The P2 operand */ int p3, /* The P3 operand */ const u8 *zP4, /* The P4 operand */ int p4type /* P4 operand type */ ){ char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8); if( p4copy ) memcpy(p4copy, zP4, 8); return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type); } /* ** Add an OP_ParseSchema opcode. This routine is broken out from ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees ** as having been used. ** ** The zWhere string must have been obtained from sqlite3_malloc(). ** This routine will take ownership of the allocated memory. */ SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){ int j; sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC); for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j); } /* ** Add an opcode that includes the p4 value as an integer. */ SQLITE_PRIVATE int sqlite3VdbeAddOp4Int( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ int p2, /* The P2 operand */ int p3, /* The P3 operand */ int p4 /* The P4 operand as an integer */ ){ int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); if( p->db->mallocFailed==0 ){ VdbeOp *pOp = &p->aOp[addr]; pOp->p4type = P4_INT32; pOp->p4.i = p4; } return addr; } /* Insert the end of a co-routine */ SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){ sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); /* Clear the temporary register cache, thereby ensuring that each ** co-routine has its own independent set of registers, because co-routines ** might expect their registers to be preserved across an OP_Yield, and ** that could cause problems if two or more co-routines are using the same ** temporary register. */ v->pParse->nTempReg = 0; v->pParse->nRangeReg = 0; } /* ** Create a new symbolic label for an instruction that has yet to be ** coded. The symbolic label is really just a negative number. The ** label can be used as the P2 value of an operation. Later, when ** the label is resolved to a specific address, the VDBE will scan ** through its operation list and change all values of P2 which match ** the label into the resolved address. ** ** The VDBE knows that a P2 value is a label because labels are ** always negative and P2 values are suppose to be non-negative. ** Hence, a negative P2 value is a label that has yet to be resolved. ** ** Zero is returned if a malloc() fails. */ SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){ Parse *p = v->pParse; int i = p->nLabel++; assert( v->magic==VDBE_MAGIC_INIT ); if( (i & (i-1))==0 ){ p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, (i*2+1)*sizeof(p->aLabel[0])); } if( p->aLabel ){ p->aLabel[i] = -1; } return ADDR(i); } /* ** Resolve label "x" to be the address of the next instruction to ** be inserted. The parameter "x" must have been obtained from ** a prior call to sqlite3VdbeMakeLabel(). */ SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){ Parse *p = v->pParse; int j = ADDR(x); assert( v->magic==VDBE_MAGIC_INIT ); assert( j<p->nLabel ); assert( j>=0 ); if( p->aLabel ){ p->aLabel[j] = v->nOp; } } /* ** Mark the VDBE as one that can only be run one time. */ SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){ p->runOnlyOnce = 1; } /* ** Mark the VDBE as one that can only be run multiple times. */ SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){ p->runOnlyOnce = 0; } #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */ /* ** The following type and function are used to iterate through all opcodes ** in a Vdbe main program and each of the sub-programs (triggers) it may ** invoke directly or indirectly. It should be used as follows: ** ** Op *pOp; ** VdbeOpIter sIter; ** ** memset(&sIter, 0, sizeof(sIter)); ** sIter.v = v; // v is of type Vdbe* ** while( (pOp = opIterNext(&sIter)) ){ ** // Do something with pOp ** } ** sqlite3DbFree(v->db, sIter.apSub); ** */ typedef struct VdbeOpIter VdbeOpIter; struct VdbeOpIter { Vdbe *v; /* Vdbe to iterate through the opcodes of */ SubProgram **apSub; /* Array of subprograms */ int nSub; /* Number of entries in apSub */ int iAddr; /* Address of next instruction to return */ int iSub; /* 0 = main program, 1 = first sub-program etc. */ }; static Op *opIterNext(VdbeOpIter *p){ Vdbe *v = p->v; Op *pRet = 0; Op *aOp; int nOp; if( p->iSub<=p->nSub ){ if( p->iSub==0 ){ aOp = v->aOp; nOp = v->nOp; }else{ aOp = p->apSub[p->iSub-1]->aOp; nOp = p->apSub[p->iSub-1]->nOp; } assert( p->iAddr<nOp ); pRet = &aOp[p->iAddr]; p->iAddr++; if( p->iAddr==nOp ){ p->iSub++; p->iAddr = 0; } if( pRet->p4type==P4_SUBPROGRAM ){ int nByte = (p->nSub+1)*sizeof(SubProgram*); int j; for(j=0; j<p->nSub; j++){ if( p->apSub[j]==pRet->p4.pProgram ) break; } if( j==p->nSub ){ p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte); if( !p->apSub ){ pRet = 0; }else{ p->apSub[p->nSub++] = pRet->p4.pProgram; } } } } return pRet; } /* ** Check if the program stored in the VM associated with pParse may ** throw an ABORT exception (causing the statement, but not entire transaction ** to be rolled back). This condition is true if the main program or any ** sub-programs contains any of the following: ** ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort. ** * OP_Destroy ** * OP_VUpdate ** * OP_VRename ** * OP_FkCounter with P2==0 (immediate foreign key constraint) ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...) ** ** Then check that the value of Parse.mayAbort is true if an ** ABORT may be thrown, or false otherwise. Return true if it does ** match, or false otherwise. This function is intended to be used as ** part of an assert statement in the compiler. Similar to: ** ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) ); */ SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ int hasAbort = 0; int hasFkCounter = 0; int hasCreateTable = 0; int hasInitCoroutine = 0; Op *pOp; VdbeOpIter sIter; memset(&sIter, 0, sizeof(sIter)); sIter.v = v; while( (pOp = opIterNext(&sIter))!=0 ){ int opcode = pOp->opcode; if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename || ((opcode==OP_Halt || opcode==OP_HaltIfNull) && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort)) ){ hasAbort = 1; break; } if( opcode==OP_CreateTable ) hasCreateTable = 1; if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1; #ifndef SQLITE_OMIT_FOREIGN_KEY if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){ hasFkCounter = 1; } #endif } sqlite3DbFree(v->db, sIter.apSub); /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred. ** If malloc failed, then the while() loop above may not have iterated ** through all opcodes and hasAbort may be set incorrectly. Return ** true for this case to prevent the assert() in the callers frame ** from failing. */ return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter || (hasCreateTable && hasInitCoroutine) ); } #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */ /* ** This routine is called after all opcodes have been inserted. It loops ** through all the opcodes and fixes up some details. ** ** (1) For each jump instruction with a negative P2 value (a label) ** resolve the P2 value to an actual address. ** ** (2) Compute the maximum number of arguments used by any SQL function ** and store that value in *pMaxFuncArgs. ** ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately ** indicate what the prepared statement actually does. ** ** (4) Initialize the p4.xAdvance pointer on opcodes that use it. ** ** (5) Reclaim the memory allocated for storing labels. ** ** This routine will only function correctly if the mkopcodeh.tcl generator ** script numbers the opcodes correctly. Changes to this routine must be ** coordinated with changes to mkopcodeh.tcl. */ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ int nMaxArgs = *pMaxFuncArgs; Op *pOp; Parse *pParse = p->pParse; int *aLabel = pParse->aLabel; p->readOnly = 1; p->bIsReader = 0; pOp = &p->aOp[p->nOp-1]; while(1){ /* Only JUMP opcodes and the short list of special opcodes in the switch ** below need to be considered. The mkopcodeh.tcl generator script groups ** all these opcodes together near the front of the opcode list. Skip ** any opcode that does not need processing by virtual of the fact that ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization. */ if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){ /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing ** cases from this switch! */ switch( pOp->opcode ){ case OP_Transaction: { if( pOp->p2!=0 ) p->readOnly = 0; /* fall thru */ } case OP_AutoCommit: case OP_Savepoint: { p->bIsReader = 1; break; } #ifndef SQLITE_OMIT_WAL case OP_Checkpoint: #endif case OP_Vacuum: case OP_JournalMode: { p->readOnly = 0; p->bIsReader = 1; break; } #ifndef SQLITE_OMIT_VIRTUALTABLE case OP_VUpdate: { if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2; break; } case OP_VFilter: { int n; assert( (pOp - p->aOp) >= 3 ); assert( pOp[-1].opcode==OP_Integer ); n = pOp[-1].p1; if( n>nMaxArgs ) nMaxArgs = n; break; } #endif case OP_Next: case OP_NextIfOpen: case OP_SorterNext: { pOp->p4.xAdvance = sqlite3BtreeNext; pOp->p4type = P4_ADVANCE; break; } case OP_Prev: case OP_PrevIfOpen: { pOp->p4.xAdvance = sqlite3BtreePrevious; pOp->p4type = P4_ADVANCE; break; } } if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){ assert( ADDR(pOp->p2)<pParse->nLabel ); pOp->p2 = aLabel[ADDR(pOp->p2)]; } } if( pOp==p->aOp ) break; pOp--; } sqlite3DbFree(p->db, pParse->aLabel); pParse->aLabel = 0; pParse->nLabel = 0; *pMaxFuncArgs = nMaxArgs; assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) ); } /* ** Return the address of the next instruction to be inserted. */ SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){ assert( p->magic==VDBE_MAGIC_INIT ); return p->nOp; } /* ** Verify that at least N opcode slots are available in p without ** having to malloc for more space (except when compiled using ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing ** to verify that certain calls to sqlite3VdbeAddOpList() can never ** fail due to a OOM fault and hence that the return value from ** sqlite3VdbeAddOpList() will always be non-NULL. */ #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){ assert( p->nOp + N <= p->pParse->nOpAlloc ); } #endif /* ** Verify that the VM passed as the only argument does not contain ** an OP_ResultRow opcode. Fail an assert() if it does. This is used ** by code in pragma.c to ensure that the implementation of certain ** pragmas comports with the flags specified in the mkpragmatab.tcl ** script. */ #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){ int i; for(i=0; i<p->nOp; i++){ assert( p->aOp[i].opcode!=OP_ResultRow ); } } #endif /* ** This function returns a pointer to the array of opcodes associated with ** the Vdbe passed as the first argument. It is the callers responsibility ** to arrange for the returned array to be eventually freed using the ** vdbeFreeOpArray() function. ** ** Before returning, *pnOp is set to the number of entries in the returned ** array. Also, *pnMaxArg is set to the larger of its current value and ** the number of entries in the Vdbe.apArg[] array required to execute the ** returned program. */ SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){ VdbeOp *aOp = p->aOp; assert( aOp && !p->db->mallocFailed ); /* Check that sqlite3VdbeUsesBtree() was not called on this VM */ assert( DbMaskAllZero(p->btreeMask) ); resolveP2Values(p, pnMaxArg); *pnOp = p->nOp; p->aOp = 0; return aOp; } /* ** Add a whole list of operations to the operation stack. Return a ** pointer to the first operation inserted. ** ** Non-zero P2 arguments to jump instructions are automatically adjusted ** so that the jump target is relative to the first operation inserted. */ SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList( Vdbe *p, /* Add opcodes to the prepared statement */ int nOp, /* Number of opcodes to add */ VdbeOpList const *aOp, /* The opcodes to be added */ int iLineno /* Source-file line number of first opcode */ ){ int i; VdbeOp *pOut, *pFirst; assert( nOp>0 ); assert( p->magic==VDBE_MAGIC_INIT ); if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){ return 0; } pFirst = pOut = &p->aOp[p->nOp]; for(i=0; i<nOp; i++, aOp++, pOut++){ pOut->opcode = aOp->opcode; pOut->p1 = aOp->p1; pOut->p2 = aOp->p2; assert( aOp->p2>=0 ); if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){ pOut->p2 += p->nOp; } pOut->p3 = aOp->p3; pOut->p4type = P4_NOTUSED; pOut->p4.p = 0; pOut->p5 = 0; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS pOut->zComment = 0; #endif #ifdef SQLITE_VDBE_COVERAGE pOut->iSrcLine = iLineno+i; #else (void)iLineno; #endif #ifdef SQLITE_DEBUG if( p->db->flags & SQLITE_VdbeAddopTrace ){ sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]); } #endif } p->nOp += nOp; return pFirst; } #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) /* ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus(). */ SQLITE_PRIVATE void sqlite3VdbeScanStatus( Vdbe *p, /* VM to add scanstatus() to */ int addrExplain, /* Address of OP_Explain (or 0) */ int addrLoop, /* Address of loop counter */ int addrVisit, /* Address of rows visited counter */ LogEst nEst, /* Estimated number of output rows */ const char *zName /* Name of table or index being scanned */ ){ int nByte = (p->nScan+1) * sizeof(ScanStatus); ScanStatus *aNew; aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte); if( aNew ){ ScanStatus *pNew = &aNew[p->nScan++]; pNew->addrExplain = addrExplain; pNew->addrLoop = addrLoop; pNew->addrVisit = addrVisit; pNew->nEst = nEst; pNew->zName = sqlite3DbStrDup(p->db, zName); p->aScan = aNew; } } #endif /* ** Change the value of the opcode, or P1, P2, P3, or P5 operands ** for a specific instruction. */ SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){ sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode; } SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){ sqlite3VdbeGetOp(p,addr)->p1 = val; } SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){ sqlite3VdbeGetOp(p,addr)->p2 = val; } SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){ sqlite3VdbeGetOp(p,addr)->p3 = val; } SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){ assert( p->nOp>0 || p->db->mallocFailed ); if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5; } /* ** Change the P2 operand of instruction addr so that it points to ** the address of the next instruction to be coded. */ SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){ sqlite3VdbeChangeP2(p, addr, p->nOp); } /* ** If the input FuncDef structure is ephemeral, then free it. If ** the FuncDef is not ephermal, then do nothing. */ static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){ if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){ sqlite3DbFree(db, pDef); } } static void vdbeFreeOpArray(sqlite3 *, Op *, int); /* ** Delete a P4 value if necessary. */ static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){ if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); sqlite3DbFree(db, p); } static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){ freeEphemeralFunction(db, p->pFunc); sqlite3DbFree(db, p); } static void freeP4(sqlite3 *db, int p4type, void *p4){ assert( db ); switch( p4type ){ case P4_FUNCCTX: { freeP4FuncCtx(db, (sqlite3_context*)p4); break; } case P4_REAL: case P4_INT64: case P4_DYNAMIC: case P4_INTARRAY: { sqlite3DbFree(db, p4); break; } case P4_KEYINFO: { if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4); break; } #ifdef SQLITE_ENABLE_CURSOR_HINTS case P4_EXPR: { sqlite3ExprDelete(db, (Expr*)p4); break; } #endif case P4_FUNCDEF: { freeEphemeralFunction(db, (FuncDef*)p4); break; } case P4_MEM: { if( db->pnBytesFreed==0 ){ sqlite3ValueFree((sqlite3_value*)p4); }else{ freeP4Mem(db, (Mem*)p4); } break; } case P4_VTAB : { if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4); break; } } } /* ** Free the space allocated for aOp and any p4 values allocated for the ** opcodes contained within. If aOp is not NULL it is assumed to contain ** nOp entries. */ static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){ if( aOp ){ Op *pOp; for(pOp=aOp; pOp<&aOp[nOp]; pOp++){ if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p); #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS sqlite3DbFree(db, pOp->zComment); #endif } } sqlite3DbFree(db, aOp); } /* ** Link the SubProgram object passed as the second argument into the linked ** list at Vdbe.pSubProgram. This list is used to delete all sub-program ** objects when the VM is no longer required. */ SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){ p->pNext = pVdbe->pProgram; pVdbe->pProgram = p; } /* ** Change the opcode at addr into OP_Noop */ SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ VdbeOp *pOp; if( p->db->mallocFailed ) return 0; assert( addr>=0 && addr<p->nOp ); pOp = &p->aOp[addr]; freeP4(p->db, pOp->p4type, pOp->p4.p); pOp->p4type = P4_NOTUSED; pOp->p4.z = 0; pOp->opcode = OP_Noop; return 1; } /* ** If the last opcode is "op" and it is not a jump destination, ** then remove it. Return true if and only if an opcode was removed. */ SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){ if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){ return sqlite3VdbeChangeToNoop(p, p->nOp-1); }else{ return 0; } } /* ** Change the value of the P4 operand for a specific instruction. ** This routine is useful when a large program is loaded from a ** static array using sqlite3VdbeAddOpList but we want to make a ** few minor changes to the program. ** ** If n>=0 then the P4 operand is dynamic, meaning that a copy of ** the string is made into memory obtained from sqlite3_malloc(). ** A value of n==0 means copy bytes of zP4 up to and including the ** first null byte. If n>0 then copy n+1 bytes of zP4. ** ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points ** to a string or structure that is guaranteed to exist for the lifetime of ** the Vdbe. In these cases we can just copy the pointer. ** ** If addr<0 then change P4 on the most recently inserted instruction. */ static void SQLITE_NOINLINE vdbeChangeP4Full( Vdbe *p, Op *pOp, const char *zP4, int n ){ if( pOp->p4type ){ freeP4(p->db, pOp->p4type, pOp->p4.p); pOp->p4type = 0; pOp->p4.p = 0; } if( n<0 ){ sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n); }else{ if( n==0 ) n = sqlite3Strlen30(zP4); pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n); pOp->p4type = P4_DYNAMIC; } } SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ Op *pOp; sqlite3 *db; assert( p!=0 ); db = p->db; assert( p->magic==VDBE_MAGIC_INIT ); assert( p->aOp!=0 || db->mallocFailed ); if( db->mallocFailed ){ if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4); return; } assert( p->nOp>0 ); assert( addr<p->nOp ); if( addr<0 ){ addr = p->nOp - 1; } pOp = &p->aOp[addr]; if( n>=0 || pOp->p4type ){ vdbeChangeP4Full(p, pOp, zP4, n); return; } if( n==P4_INT32 ){ /* Note: this cast is safe, because the origin data point was an int ** that was cast to a (const char *). */ pOp->p4.i = SQLITE_PTR_TO_INT(zP4); pOp->p4type = P4_INT32; }else if( zP4!=0 ){ assert( n<0 ); pOp->p4.p = (void*)zP4; pOp->p4type = (signed char)n; if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4); } } /* ** Change the P4 operand of the most recently coded instruction ** to the value defined by the arguments. This is a high-speed ** version of sqlite3VdbeChangeP4(). ** ** The P4 operand must not have been previously defined. And the new ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of ** those cases. */ SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){ VdbeOp *pOp; assert( n!=P4_INT32 && n!=P4_VTAB ); assert( n<=0 ); if( p->db->mallocFailed ){ freeP4(p->db, n, pP4); }else{ assert( pP4!=0 ); assert( p->nOp>0 ); pOp = &p->aOp[p->nOp-1]; assert( pOp->p4type==P4_NOTUSED ); pOp->p4type = n; pOp->p4.p = pP4; } } /* ** Set the P4 on the most recently added opcode to the KeyInfo for the ** index given. */ SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){ Vdbe *v = pParse->pVdbe; KeyInfo *pKeyInfo; assert( v!=0 ); assert( pIdx!=0 ); pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx); if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); } #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS /* ** Change the comment on the most recently coded instruction. Or ** insert a No-op and add the comment to that new instruction. This ** makes the code easier to read during debugging. None of this happens ** in a production build. */ static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){ assert( p->nOp>0 || p->aOp==0 ); assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed ); if( p->nOp ){ assert( p->aOp ); sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment); p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap); } } SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ va_list ap; if( p ){ va_start(ap, zFormat); vdbeVComment(p, zFormat, ap); va_end(ap); } } SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){ va_list ap; if( p ){ sqlite3VdbeAddOp0(p, OP_Noop); va_start(ap, zFormat); vdbeVComment(p, zFormat, ap); va_end(ap); } } #endif /* NDEBUG */ #ifdef SQLITE_VDBE_COVERAGE /* ** Set the value if the iSrcLine field for the previously coded instruction. */ SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){ sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine; } #endif /* SQLITE_VDBE_COVERAGE */ /* ** Return the opcode for a given address. If the address is -1, then ** return the most recently inserted opcode. ** ** If a memory allocation error has occurred prior to the calling of this ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode ** is readable but not writable, though it is cast to a writable value. ** The return of a dummy opcode allows the call to continue functioning ** after an OOM fault without having to check to see if the return from ** this routine is a valid pointer. But because the dummy.opcode is 0, ** dummy will never be written to. This is verified by code inspection and ** by running with Valgrind. */ SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){ /* C89 specifies that the constant "dummy" will be initialized to all ** zeros, which is correct. MSVC generates a warning, nevertheless. */ static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */ assert( p->magic==VDBE_MAGIC_INIT ); if( addr<0 ){ addr = p->nOp - 1; } assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed ); if( p->db->mallocFailed ){ return (VdbeOp*)&dummy; }else{ return &p->aOp[addr]; } } #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) /* ** Return an integer value for one of the parameters to the opcode pOp ** determined by character c. */ static int translateP(char c, const Op *pOp){ if( c=='1' ) return pOp->p1; if( c=='2' ) return pOp->p2; if( c=='3' ) return pOp->p3; if( c=='4' ) return pOp->p4.i; return pOp->p5; } /* ** Compute a string for the "comment" field of a VDBE opcode listing. ** ** The Synopsis: field in comments in the vdbe.c source file gets converted ** to an extra string that is appended to the sqlite3OpcodeName(). In the ** absence of other comments, this synopsis becomes the comment on the opcode. ** Some translation occurs: ** ** "PX" -> "r[X]" ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x */ static int displayComment( const Op *pOp, /* The opcode to be commented */ const char *zP4, /* Previously obtained value for P4 */ char *zTemp, /* Write result here */ int nTemp /* Space available in zTemp[] */ ){ const char *zOpName; const char *zSynopsis; int nOpName; int ii, jj; char zAlt[50]; zOpName = sqlite3OpcodeName(pOp->opcode); nOpName = sqlite3Strlen30(zOpName); if( zOpName[nOpName+1] ){ int seenCom = 0; char c; zSynopsis = zOpName += nOpName + 1; if( strncmp(zSynopsis,"IF ",3)==0 ){ if( pOp->p5 & SQLITE_STOREP2 ){ sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3); }else{ sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3); } zSynopsis = zAlt; } for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){ if( c=='P' ){ c = zSynopsis[++ii]; if( c=='4' ){ sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4); }else if( c=='X' ){ sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment); seenCom = 1; }else{ int v1 = translateP(c, pOp); int v2; sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1); if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){ ii += 3; jj += sqlite3Strlen30(zTemp+jj); v2 = translateP(zSynopsis[ii], pOp); if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){ ii += 2; v2++; } if( v2>1 ){ sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1); } }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){ ii += 4; } } jj += sqlite3Strlen30(zTemp+jj); }else{ zTemp[jj++] = c; } } if( !seenCom && jj<nTemp-5 && pOp->zComment ){ sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment); jj += sqlite3Strlen30(zTemp+jj); } if( jj<nTemp ) zTemp[jj] = 0; }else if( pOp->zComment ){ sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment); jj = sqlite3Strlen30(zTemp); }else{ zTemp[0] = 0; jj = 0; } return jj; } #endif /* SQLITE_DEBUG */ #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) /* ** Translate the P4.pExpr value for an OP_CursorHint opcode into text ** that can be displayed in the P4 column of EXPLAIN output. */ static void displayP4Expr(StrAccum *p, Expr *pExpr){ const char *zOp = 0; switch( pExpr->op ){ case TK_STRING: sqlite3XPrintf(p, "%Q", pExpr->u.zToken); break; case TK_INTEGER: sqlite3XPrintf(p, "%d", pExpr->u.iValue); break; case TK_NULL: sqlite3XPrintf(p, "NULL"); break; case TK_REGISTER: { sqlite3XPrintf(p, "r[%d]", pExpr->iTable); break; } case TK_COLUMN: { if( pExpr->iColumn<0 ){ sqlite3XPrintf(p, "rowid"); }else{ sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn); } break; } case TK_LT: zOp = "LT"; break; case TK_LE: zOp = "LE"; break; case TK_GT: zOp = "GT"; break; case TK_GE: zOp = "GE"; break; case TK_NE: zOp = "NE"; break; case TK_EQ: zOp = "EQ"; break; case TK_IS: zOp = "IS"; break; case TK_ISNOT: zOp = "ISNOT"; break; case TK_AND: zOp = "AND"; break; case TK_OR: zOp = "OR"; break; case TK_PLUS: zOp = "ADD"; break; case TK_STAR: zOp = "MUL"; break; case TK_MINUS: zOp = "SUB"; break; case TK_REM: zOp = "REM"; break; case TK_BITAND: zOp = "BITAND"; break; case TK_BITOR: zOp = "BITOR"; break; case TK_SLASH: zOp = "DIV"; break; case TK_LSHIFT: zOp = "LSHIFT"; break; case TK_RSHIFT: zOp = "RSHIFT"; break; case TK_CONCAT: zOp = "CONCAT"; break; case TK_UMINUS: zOp = "MINUS"; break; case TK_UPLUS: zOp = "PLUS"; break; case TK_BITNOT: zOp = "BITNOT"; break; case TK_NOT: zOp = "NOT"; break; case TK_ISNULL: zOp = "ISNULL"; break; case TK_NOTNULL: zOp = "NOTNULL"; break; default: sqlite3XPrintf(p, "%s", "expr"); break; } if( zOp ){ sqlite3XPrintf(p, "%s(", zOp); displayP4Expr(p, pExpr->pLeft); if( pExpr->pRight ){ sqlite3StrAccumAppend(p, ",", 1); displayP4Expr(p, pExpr->pRight); } sqlite3StrAccumAppend(p, ")", 1); } } #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */ #if VDBE_DISPLAY_P4 /* ** Compute a string that describes the P4 parameter for an opcode. ** Use zTemp for any required temporary buffer space. */ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ char *zP4 = zTemp; StrAccum x; assert( nTemp>=20 ); sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0); switch( pOp->p4type ){ case P4_KEYINFO: { int j; KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; assert( pKeyInfo->aSortOrder!=0 ); sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField); for(j=0; j<pKeyInfo->nField; j++){ CollSeq *pColl = pKeyInfo->aColl[j]; const char *zColl = pColl ? pColl->zName : ""; if( strcmp(zColl, "BINARY")==0 ) zColl = "B"; sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl); } sqlite3StrAccumAppend(&x, ")", 1); break; } #ifdef SQLITE_ENABLE_CURSOR_HINTS case P4_EXPR: { displayP4Expr(&x, pOp->p4.pExpr); break; } #endif case P4_COLLSEQ: { CollSeq *pColl = pOp->p4.pColl; sqlite3XPrintf(&x, "(%.20s)", pColl->zName); break; } case P4_FUNCDEF: { FuncDef *pDef = pOp->p4.pFunc; sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg); break; } #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) case P4_FUNCCTX: { FuncDef *pDef = pOp->p4.pCtx->pFunc; sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg); break; } #endif case P4_INT64: { sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64); break; } case P4_INT32: { sqlite3XPrintf(&x, "%d", pOp->p4.i); break; } case P4_REAL: { sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal); break; } case P4_MEM: { Mem *pMem = pOp->p4.pMem; if( pMem->flags & MEM_Str ){ zP4 = pMem->z; }else if( pMem->flags & MEM_Int ){ sqlite3XPrintf(&x, "%lld", pMem->u.i); }else if( pMem->flags & MEM_Real ){ sqlite3XPrintf(&x, "%.16g", pMem->u.r); }else if( pMem->flags & MEM_Null ){ zP4 = "NULL"; }else{ assert( pMem->flags & MEM_Blob ); zP4 = "(blob)"; } break; } #ifndef SQLITE_OMIT_VIRTUALTABLE case P4_VTAB: { sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab; sqlite3XPrintf(&x, "vtab:%p", pVtab); break; } #endif case P4_INTARRAY: { int i; int *ai = pOp->p4.ai; int n = ai[0]; /* The first element of an INTARRAY is always the ** count of the number of elements to follow */ for(i=1; i<n; i++){ sqlite3XPrintf(&x, ",%d", ai[i]); } zTemp[0] = '['; sqlite3StrAccumAppend(&x, "]", 1); break; } case P4_SUBPROGRAM: { sqlite3XPrintf(&x, "program"); break; } case P4_ADVANCE: { zTemp[0] = 0; break; } case P4_TABLE: { sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName); break; } default: { zP4 = pOp->p4.z; if( zP4==0 ){ zP4 = zTemp; zTemp[0] = 0; } } } sqlite3StrAccumFinish(&x); assert( zP4!=0 ); return zP4; } #endif /* VDBE_DISPLAY_P4 */ /* ** Declare to the Vdbe that the BTree object at db->aDb[i] is used. ** ** The prepared statements need to know in advance the complete set of ** attached databases that will be use. A mask of these databases ** is maintained in p->btreeMask. The p->lockMask value is the subset of ** p->btreeMask of databases that will require a lock. */ SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){ assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 ); assert( i<(int)sizeof(p->btreeMask)*8 ); DbMaskSet(p->btreeMask, i); if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){ DbMaskSet(p->lockMask, i); } } #if !defined(SQLITE_OMIT_SHARED_CACHE) /* ** If SQLite is compiled to support shared-cache mode and to be threadsafe, ** this routine obtains the mutex associated with each BtShared structure ** that may be accessed by the VM passed as an argument. In doing so it also ** sets the BtShared.db member of each of the BtShared structures, ensuring ** that the correct busy-handler callback is invoked if required. ** ** If SQLite is not threadsafe but does support shared-cache mode, then ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables ** of all of BtShared structures accessible via the database handle ** associated with the VM. ** ** If SQLite is not threadsafe and does not support shared-cache mode, this ** function is a no-op. ** ** The p->btreeMask field is a bitmask of all btrees that the prepared ** statement p will ever use. Let N be the number of bits in p->btreeMask ** corresponding to btrees that use shared cache. Then the runtime of ** this routine is N*N. But as N is rarely more than 1, this should not ** be a problem. */ SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){ int i; sqlite3 *db; Db *aDb; int nDb; if( DbMaskAllZero(p->lockMask) ) return; /* The common case */ db = p->db; aDb = db->aDb; nDb = db->nDb; for(i=0; i<nDb; i++){ if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){ sqlite3BtreeEnter(aDb[i].pBt); } } } #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 /* ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter(). */ static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){ int i; sqlite3 *db; Db *aDb; int nDb; db = p->db; aDb = db->aDb; nDb = db->nDb; for(i=0; i<nDb; i++){ if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){ sqlite3BtreeLeave(aDb[i].pBt); } } } SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){ if( DbMaskAllZero(p->lockMask) ) return; /* The common case */ vdbeLeave(p); } #endif #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) /* ** Print a single opcode. This routine is used for debugging only. */ SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ char *zP4; char zPtr[50]; char zCom[100]; static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n"; if( pOut==0 ) pOut = stdout; zP4 = displayP4(pOp, zPtr, sizeof(zPtr)); #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS displayComment(pOp, zP4, zCom, sizeof(zCom)); #else zCom[0] = 0; #endif /* NB: The sqlite3OpcodeName() function is implemented by code created ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the ** information from the vdbe.c source text */ fprintf(pOut, zFormat1, pc, sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5, zCom ); fflush(pOut); } #endif /* ** Initialize an array of N Mem element. */ static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){ while( (N--)>0 ){ p->db = db; p->flags = flags; p->szMalloc = 0; #ifdef SQLITE_DEBUG p->pScopyFrom = 0; #endif p++; } } /* ** Release an array of N Mem elements */ static void releaseMemArray(Mem *p, int N){ if( p && N ){ Mem *pEnd = &p[N]; sqlite3 *db = p->db; if( db->pnBytesFreed ){ do{ if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); }while( (++p)<pEnd ); return; } do{ assert( (&p[1])==pEnd || p[0].db==p[1].db ); assert( sqlite3VdbeCheckMemInvariants(p) ); /* This block is really an inlined version of sqlite3VdbeMemRelease() ** that takes advantage of the fact that the memory cell value is ** being set to NULL after releasing any dynamic resources. ** ** The justification for duplicating code is that according to ** callgrind, this causes a certain test case to hit the CPU 4.7 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if ** sqlite3MemRelease() were called from here. With -O2, this jumps ** to 6.6 percent. The test case is inserting 1000 rows into a table ** with no indexes using a single prepared INSERT statement, bind() ** and reset(). Inserts are grouped into a transaction. */ testcase( p->flags & MEM_Agg ); testcase( p->flags & MEM_Dyn ); testcase( p->flags & MEM_Frame ); testcase( p->flags & MEM_RowSet ); if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){ sqlite3VdbeMemRelease(p); }else if( p->szMalloc ){ sqlite3DbFree(db, p->zMalloc); p->szMalloc = 0; } p->flags = MEM_Undefined; }while( (++p)<pEnd ); } } /* ** Delete a VdbeFrame object and its contents. VdbeFrame objects are ** allocated by the OP_Program opcode in sqlite3VdbeExec(). */ SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){ int i; Mem *aMem = VdbeFrameMem(p); VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem]; for(i=0; i<p->nChildCsr; i++){ sqlite3VdbeFreeCursor(p->v, apCsr[i]); } releaseMemArray(aMem, p->nChildMem); sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0); sqlite3DbFree(p->v->db, p); } #ifndef SQLITE_OMIT_EXPLAIN /* ** Give a listing of the program in the virtual machine. ** ** The interface is the same as sqlite3VdbeExec(). But instead of ** running the code, it invokes the callback once for each instruction. ** This feature is used to implement "EXPLAIN". ** ** When p->explain==1, each instruction is listed. When ** p->explain==2, only OP_Explain instructions are listed and these ** are shown in a different format. p->explain==2 is used to implement ** EXPLAIN QUERY PLAN. ** ** When p->explain==1, first the main program is listed, then each of ** the trigger subprograms are listed one by one. */ SQLITE_PRIVATE int sqlite3VdbeList( Vdbe *p /* The VDBE */ ){ int nRow; /* Stop when row count reaches this */ int nSub = 0; /* Number of sub-vdbes seen so far */ SubProgram **apSub = 0; /* Array of sub-vdbes */ Mem *pSub = 0; /* Memory cell hold array of subprogs */ sqlite3 *db = p->db; /* The database connection */ int i; /* Loop counter */ int rc = SQLITE_OK; /* Return code */ Mem *pMem = &p->aMem[1]; /* First Mem of result set */ assert( p->explain ); assert( p->magic==VDBE_MAGIC_RUN ); assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM ); /* Even though this opcode does not use dynamic strings for ** the result, result columns may become dynamic if the user calls ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. */ releaseMemArray(pMem, 8); p->pResultSet = 0; if( p->rc==SQLITE_NOMEM_BKPT ){ /* This happens if a malloc() inside a call to sqlite3_column_text() or ** sqlite3_column_text16() failed. */ sqlite3OomFault(db); return SQLITE_ERROR; } /* When the number of output rows reaches nRow, that means the ** listing has finished and sqlite3_step() should return SQLITE_DONE. ** nRow is the sum of the number of rows in the main program, plus ** the sum of the number of rows in all trigger subprograms encountered ** so far. The nRow value will increase as new trigger subprograms are ** encountered, but p->pc will eventually catch up to nRow. */ nRow = p->nOp; if( p->explain==1 ){ /* The first 8 memory cells are used for the result set. So we will ** commandeer the 9th cell to use as storage for an array of pointers ** to trigger subprograms. The VDBE is guaranteed to have at least 9 ** cells. */ assert( p->nMem>9 ); pSub = &p->aMem[9]; if( pSub->flags&MEM_Blob ){ /* On the first call to sqlite3_step(), pSub will hold a NULL. It is ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */ nSub = pSub->n/sizeof(Vdbe*); apSub = (SubProgram **)pSub->z; } for(i=0; i<nSub; i++){ nRow += apSub[i]->nOp; } } do{ i = p->pc++; }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain ); if( i>=nRow ){ p->rc = SQLITE_OK; rc = SQLITE_DONE; }else if( db->u1.isInterrupted ){ p->rc = SQLITE_INTERRUPT; rc = SQLITE_ERROR; sqlite3VdbeError(p, sqlite3ErrStr(p->rc)); }else{ char *zP4; Op *pOp; if( i<p->nOp ){ /* The output line number is small enough that we are still in the ** main program. */ pOp = &p->aOp[i]; }else{ /* We are currently listing subprograms. Figure out which one and ** pick up the appropriate opcode. */ int j; i -= p->nOp; for(j=0; i>=apSub[j]->nOp; j++){ i -= apSub[j]->nOp; } pOp = &apSub[j]->aOp[i]; } if( p->explain==1 ){ pMem->flags = MEM_Int; pMem->u.i = i; /* Program counter */ pMem++; pMem->flags = MEM_Static|MEM_Str|MEM_Term; pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ assert( pMem->z!=0 ); pMem->n = sqlite3Strlen30(pMem->z); pMem->enc = SQLITE_UTF8; pMem++; /* When an OP_Program opcode is encounter (the only opcode that has ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms ** kept in p->aMem[9].z to hold the new program - assuming this subprogram ** has not already been seen. */ if( pOp->p4type==P4_SUBPROGRAM ){ int nByte = (nSub+1)*sizeof(SubProgram*); int j; for(j=0; j<nSub; j++){ if( apSub[j]==pOp->p4.pProgram ) break; } if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){ apSub = (SubProgram **)pSub->z; apSub[nSub++] = pOp->p4.pProgram; pSub->flags |= MEM_Blob; pSub->n = nSub*sizeof(SubProgram*); } } } pMem->flags = MEM_Int; pMem->u.i = pOp->p1; /* P1 */ pMem++; pMem->flags = MEM_Int; pMem->u.i = pOp->p2; /* P2 */ pMem++; pMem->flags = MEM_Int; pMem->u.i = pOp->p3; /* P3 */ pMem++; if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */ assert( p->db->mallocFailed ); return SQLITE_ERROR; } pMem->flags = MEM_Str|MEM_Term; zP4 = displayP4(pOp, pMem->z, pMem->szMalloc); if( zP4!=pMem->z ){ pMem->n = 0; sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0); }else{ assert( pMem->z!=0 ); pMem->n = sqlite3Strlen30(pMem->z); pMem->enc = SQLITE_UTF8; } pMem++; if( p->explain==1 ){ if( sqlite3VdbeMemClearAndResize(pMem, 4) ){ assert( p->db->mallocFailed ); return SQLITE_ERROR; } pMem->flags = MEM_Str|MEM_Term; pMem->n = 2; sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */ pMem->enc = SQLITE_UTF8; pMem++; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS if( sqlite3VdbeMemClearAndResize(pMem, 500) ){ assert( p->db->mallocFailed ); return SQLITE_ERROR; } pMem->flags = MEM_Str|MEM_Term; pMem->n = displayComment(pOp, zP4, pMem->z, 500); pMem->enc = SQLITE_UTF8; #else pMem->flags = MEM_Null; /* Comment */ #endif } p->nResColumn = 8 - 4*(p->explain-1); p->pResultSet = &p->aMem[1]; p->rc = SQLITE_OK; rc = SQLITE_ROW; } return rc; } #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_DEBUG /* ** Print the SQL that was used to generate a VDBE program. */ SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){ const char *z = 0; if( p->zSql ){ z = p->zSql; }else if( p->nOp>=1 ){ const VdbeOp *pOp = &p->aOp[0]; if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){ z = pOp->p4.z; while( sqlite3Isspace(*z) ) z++; } } if( z ) printf("SQL: [%s]\n", z); } #endif #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) /* ** Print an IOTRACE message showing SQL content. */ SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){ int nOp = p->nOp; VdbeOp *pOp; if( sqlite3IoTrace==0 ) return; if( nOp<1 ) return; pOp = &p->aOp[0]; if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){ int i, j; char z[1000]; sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z); for(i=0; sqlite3Isspace(z[i]); i++){} for(j=0; z[i]; i++){ if( sqlite3Isspace(z[i]) ){ if( z[i-1]!=' ' ){ z[j++] = ' '; } }else{ z[j++] = z[i]; } } z[j] = 0; sqlite3IoTrace("SQL %s\n", z); } } #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */ /* An instance of this object describes bulk memory available for use ** by subcomponents of a prepared statement. Space is allocated out ** of a ReusableSpace object by the allocSpace() routine below. */ struct ReusableSpace { u8 *pSpace; /* Available memory */ int nFree; /* Bytes of available memory */ int nNeeded; /* Total bytes that could not be allocated */ }; /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf ** from the ReusableSpace object. Return a pointer to the allocated ** memory on success. If insufficient memory is available in the ** ReusableSpace object, increase the ReusableSpace.nNeeded ** value by the amount needed and return NULL. ** ** If pBuf is not initially NULL, that means that the memory has already ** been allocated by a prior call to this routine, so just return a copy ** of pBuf and leave ReusableSpace unchanged. ** ** This allocator is employed to repurpose unused slots at the end of the ** opcode array of prepared state for other memory needs of the prepared ** statement. */ static void *allocSpace( struct ReusableSpace *p, /* Bulk memory available for allocation */ void *pBuf, /* Pointer to a prior allocation */ int nByte /* Bytes of memory needed */ ){ assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) ); if( pBuf==0 ){ nByte = ROUND8(nByte); if( nByte <= p->nFree ){ p->nFree -= nByte; pBuf = &p->pSpace[p->nFree]; }else{ p->nNeeded += nByte; } } assert( EIGHT_BYTE_ALIGNMENT(pBuf) ); return pBuf; } /* ** Rewind the VDBE back to the beginning in preparation for ** running it. */ SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){ #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) int i; #endif assert( p!=0 ); assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET ); /* There should be at least one opcode. */ assert( p->nOp>0 ); /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */ p->magic = VDBE_MAGIC_RUN; #ifdef SQLITE_DEBUG for(i=0; i<p->nMem; i++){ assert( p->aMem[i].db==p->db ); } #endif p->pc = -1; p->rc = SQLITE_OK; p->errorAction = OE_Abort; p->nChange = 0; p->cacheCtr = 1; p->minWriteFileFormat = 255; p->iStatement = 0; p->nFkConstraint = 0; #ifdef VDBE_PROFILE for(i=0; i<p->nOp; i++){ p->aOp[i].cnt = 0; p->aOp[i].cycles = 0; } #endif } /* ** Prepare a virtual machine for execution for the first time after ** creating the virtual machine. This involves things such ** as allocating registers and initializing the program counter. ** After the VDBE has be prepped, it can be executed by one or more ** calls to sqlite3VdbeExec(). ** ** This function may be called exactly once on each virtual machine. ** After this routine is called the VM has been "packaged" and is ready ** to run. After this routine is called, further calls to ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects ** the Vdbe from the Parse object that helped generate it so that the ** the Vdbe becomes an independent entity and the Parse object can be ** destroyed. ** ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back ** to its initial state after it has been run. */ SQLITE_PRIVATE void sqlite3VdbeMakeReady( Vdbe *p, /* The VDBE */ Parse *pParse /* Parsing context */ ){ sqlite3 *db; /* The database connection */ int nVar; /* Number of parameters */ int nMem; /* Number of VM memory registers */ int nCursor; /* Number of cursors required */ int nArg; /* Number of arguments in subprograms */ int n; /* Loop counter */ struct ReusableSpace x; /* Reusable bulk memory */ assert( p!=0 ); assert( p->nOp>0 ); assert( pParse!=0 ); assert( p->magic==VDBE_MAGIC_INIT ); assert( pParse==p->pParse ); db = p->db; assert( db->mallocFailed==0 ); nVar = pParse->nVar; nMem = pParse->nMem; nCursor = pParse->nTab; nArg = pParse->nMaxArg; /* Each cursor uses a memory cell. The first cursor (cursor 0) can ** use aMem[0] which is not otherwise used by the VDBE program. Allocate ** space at the end of aMem[] for cursors 1 and greater. ** See also: allocateCursor(). */ nMem += nCursor; if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */ /* Figure out how much reusable memory is available at the end of the ** opcode array. This extra memory will be reallocated for other elements ** of the prepared statement. */ n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */ x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */ assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) ); x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */ assert( x.nFree>=0 ); assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) ); resolveP2Values(p, &nArg); p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort); if( pParse->explain && nMem<10 ){ nMem = 10; } p->expired = 0; /* Memory for registers, parameters, cursor, etc, is allocated in one or two ** passes. On the first pass, we try to reuse unused memory at the ** end of the opcode array. If we are unable to satisfy all memory ** requirements by reusing the opcode array tail, then the second ** pass will fill in the remainder using a fresh memory allocation. ** ** This two-pass approach that reuses as much memory as possible from ** the leftover memory at the end of the opcode array. This can significantly ** reduce the amount of memory held by a prepared statement. */ do { x.nNeeded = 0; p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem)); p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem)); p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*)); p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*)); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64)); #endif if( x.nNeeded==0 ) break; x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded); x.nFree = x.nNeeded; }while( !db->mallocFailed ); p->pVList = pParse->pVList; pParse->pVList = 0; p->explain = pParse->explain; if( db->mallocFailed ){ p->nVar = 0; p->nCursor = 0; p->nMem = 0; }else{ p->nCursor = nCursor; p->nVar = (ynVar)nVar; initMemArray(p->aVar, nVar, db, MEM_Null); p->nMem = nMem; initMemArray(p->aMem, nMem, db, MEM_Undefined); memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*)); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS memset(p->anExec, 0, p->nOp*sizeof(i64)); #endif } sqlite3VdbeRewind(p); } /* ** Close a VDBE cursor and release all the resources that cursor ** happens to hold. */ SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){ if( pCx==0 ){ return; } assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE ); switch( pCx->eCurType ){ case CURTYPE_SORTER: { sqlite3VdbeSorterClose(p->db, pCx); break; } case CURTYPE_BTREE: { if( pCx->pBtx ){ sqlite3BtreeClose(pCx->pBtx); /* The pCx->pCursor will be close automatically, if it exists, by ** the call above. */ }else{ assert( pCx->uc.pCursor!=0 ); sqlite3BtreeCloseCursor(pCx->uc.pCursor); } break; } #ifndef SQLITE_OMIT_VIRTUALTABLE case CURTYPE_VTAB: { sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur; const sqlite3_module *pModule = pVCur->pVtab->pModule; assert( pVCur->pVtab->nRef>0 ); pVCur->pVtab->nRef--; pModule->xClose(pVCur); break; } #endif } } /* ** Close all cursors in the current frame. */ static void closeCursorsInFrame(Vdbe *p){ if( p->apCsr ){ int i; for(i=0; i<p->nCursor; i++){ VdbeCursor *pC = p->apCsr[i]; if( pC ){ sqlite3VdbeFreeCursor(p, pC); p->apCsr[i] = 0; } } } } /* ** Copy the values stored in the VdbeFrame structure to its Vdbe. This ** is used, for example, when a trigger sub-program is halted to restore ** control to the main program. */ SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){ Vdbe *v = pFrame->v; closeCursorsInFrame(v); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS v->anExec = pFrame->anExec; #endif v->aOp = pFrame->aOp; v->nOp = pFrame->nOp; v->aMem = pFrame->aMem; v->nMem = pFrame->nMem; v->apCsr = pFrame->apCsr; v->nCursor = pFrame->nCursor; v->db->lastRowid = pFrame->lastRowid; v->nChange = pFrame->nChange; v->db->nChange = pFrame->nDbChange; sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0); v->pAuxData = pFrame->pAuxData; pFrame->pAuxData = 0; return pFrame->pc; } /* ** Close all cursors. ** ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory ** cell array. This is necessary as the memory cell array may contain ** pointers to VdbeFrame objects, which may in turn contain pointers to ** open cursors. */ static void closeAllCursors(Vdbe *p){ if( p->pFrame ){ VdbeFrame *pFrame; for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); sqlite3VdbeFrameRestore(pFrame); p->pFrame = 0; p->nFrame = 0; } assert( p->nFrame==0 ); closeCursorsInFrame(p); if( p->aMem ){ releaseMemArray(p->aMem, p->nMem); } while( p->pDelFrame ){ VdbeFrame *pDel = p->pDelFrame; p->pDelFrame = pDel->pParent; sqlite3VdbeFrameDelete(pDel); } /* Delete any auxdata allocations made by the VM */ if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0); assert( p->pAuxData==0 ); } /* ** Clean up the VM after a single run. */ static void Cleanup(Vdbe *p){ sqlite3 *db = p->db; #ifdef SQLITE_DEBUG /* Execute assert() statements to ensure that the Vdbe.apCsr[] and ** Vdbe.aMem[] arrays have already been cleaned up. */ int i; if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 ); if( p->aMem ){ for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined ); } #endif sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; p->pResultSet = 0; } /* ** Set the number of result columns that will be returned by this SQL ** statement. This is now set at compile time, rather than during ** execution of the vdbe program so that sqlite3_column_count() can ** be called on an SQL statement before sqlite3_step(). */ SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){ Mem *pColName; int n; sqlite3 *db = p->db; releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); sqlite3DbFree(db, p->aColName); n = nResColumn*COLNAME_N; p->nResColumn = (u16)nResColumn; p->aColName = pColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n ); if( p->aColName==0 ) return; initMemArray(p->aColName, n, p->db, MEM_Null); } /* ** Set the name of the idx'th column to be returned by the SQL statement. ** zName must be a pointer to a nul terminated string. ** ** This call must be made after a call to sqlite3VdbeSetNumCols(). ** ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed. */ SQLITE_PRIVATE int sqlite3VdbeSetColName( Vdbe *p, /* Vdbe being configured */ int idx, /* Index of column zName applies to */ int var, /* One of the COLNAME_* constants */ const char *zName, /* Pointer to buffer containing name */ void (*xDel)(void*) /* Memory management strategy for zName */ ){ int rc; Mem *pColName; assert( idx<p->nResColumn ); assert( var<COLNAME_N ); if( p->db->mallocFailed ){ assert( !zName || xDel!=SQLITE_DYNAMIC ); return SQLITE_NOMEM_BKPT; } assert( p->aColName!=0 ); pColName = &(p->aColName[idx+var*p->nResColumn]); rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel); assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 ); return rc; } /* ** A read or write transaction may or may not be active on database handle ** db. If a transaction is active, commit it. If there is a ** write-transaction spanning more than one database file, this routine ** takes care of the master journal trickery. */ static int vdbeCommit(sqlite3 *db, Vdbe *p){ int i; int nTrans = 0; /* Number of databases with an active write-transaction ** that are candidates for a two-phase commit using a ** master-journal */ int rc = SQLITE_OK; int needXcommit = 0; #ifdef SQLITE_OMIT_VIRTUALTABLE /* With this option, sqlite3VtabSync() is defined to be simply ** SQLITE_OK so p is not used. */ UNUSED_PARAMETER(p); #endif /* Before doing anything else, call the xSync() callback for any ** virtual module tables written in this transaction. This has to ** be done before determining whether a master journal file is ** required, as an xSync() callback may add an attached database ** to the transaction. */ rc = sqlite3VtabSync(db, p); /* This loop determines (a) if the commit hook should be invoked and ** (b) how many database files have open write transactions, not ** including the temp database. (b) is important because if more than ** one database file has an open write transaction, a master journal ** file is required for an atomic commit. */ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( sqlite3BtreeIsInTrans(pBt) ){ /* Whether or not a database might need a master journal depends upon ** its journal mode (among other things). This matrix determines which ** journal modes use a master journal and which do not */ static const u8 aMJNeeded[] = { /* DELETE */ 1, /* PERSIST */ 1, /* OFF */ 0, /* TRUNCATE */ 1, /* MEMORY */ 0, /* WAL */ 0 }; Pager *pPager; /* Pager associated with pBt */ needXcommit = 1; sqlite3BtreeEnter(pBt); pPager = sqlite3BtreePager(pBt); if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF && aMJNeeded[sqlite3PagerGetJournalMode(pPager)] ){ assert( i!=1 ); nTrans++; } rc = sqlite3PagerExclusiveLock(pPager); sqlite3BtreeLeave(pBt); } } if( rc!=SQLITE_OK ){ return rc; } /* If there are any write-transactions at all, invoke the commit hook */ if( needXcommit && db->xCommitCallback ){ rc = db->xCommitCallback(db->pCommitArg); if( rc ){ return SQLITE_CONSTRAINT_COMMITHOOK; } } /* The simple case - no more than one database file (not counting the ** TEMP database) has a transaction active. There is no need for the ** master-journal. ** ** If the return value of sqlite3BtreeGetFilename() is a zero length ** string, it means the main database is :memory: or a temp file. In ** that case we do not support atomic multi-file commits, so use the ** simple case then too. */ if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ rc = sqlite3BtreeCommitPhaseOne(pBt, 0); } } /* Do the commit only if all databases successfully complete phase 1. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an ** IO error while deleting or truncating a journal file. It is unlikely, ** but could happen. In this case abandon processing and return the error. */ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ rc = sqlite3BtreeCommitPhaseTwo(pBt, 0); } } if( rc==SQLITE_OK ){ sqlite3VtabCommit(db); } } /* The complex case - There is a multi-file write-transaction active. ** This requires a master journal file to ensure the transaction is ** committed atomically. */ #ifndef SQLITE_OMIT_DISKIO else{ sqlite3_vfs *pVfs = db->pVfs; char *zMaster = 0; /* File-name for the master journal */ char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt); sqlite3_file *pMaster = 0; i64 offset = 0; int res; int retryCount = 0; int nMainFile; /* Select a master journal file name */ nMainFile = sqlite3Strlen30(zMainFile); zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile); if( zMaster==0 ) return SQLITE_NOMEM_BKPT; do { u32 iRandom; if( retryCount ){ if( retryCount>100 ){ sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster); sqlite3OsDelete(pVfs, zMaster, 0); break; }else if( retryCount==1 ){ sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster); } } retryCount++; sqlite3_randomness(sizeof(iRandom), &iRandom); sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X", (iRandom>>8)&0xffffff, iRandom&0xff); /* The antipenultimate character of the master journal name must ** be "9" to avoid name collisions when using 8+3 filenames. */ assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' ); sqlite3FileSuffix3(zMainFile, zMaster); rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); }while( rc==SQLITE_OK && res ); if( rc==SQLITE_OK ){ /* Open the master journal. */ rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0 ); } if( rc!=SQLITE_OK ){ sqlite3DbFree(db, zMaster); return rc; } /* Write the name of each database file in the transaction into the new ** master journal file. If an error occurs at this point close ** and delete the master journal file. All the individual journal files ** still have 'null' as the master journal pointer, so they will roll ** back independently if a failure occurs. */ for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( sqlite3BtreeIsInTrans(pBt) ){ char const *zFile = sqlite3BtreeGetJournalname(pBt); if( zFile==0 ){ continue; /* Ignore TEMP and :memory: databases */ } assert( zFile[0]!=0 ); rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset); offset += sqlite3Strlen30(zFile)+1; if( rc!=SQLITE_OK ){ sqlite3OsCloseFree(pMaster); sqlite3OsDelete(pVfs, zMaster, 0); sqlite3DbFree(db, zMaster); return rc; } } } /* Sync the master journal file. If the IOCAP_SEQUENTIAL device ** flag is set this is not required. */ if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL) && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL)) ){ sqlite3OsCloseFree(pMaster); sqlite3OsDelete(pVfs, zMaster, 0); sqlite3DbFree(db, zMaster); return rc; } /* Sync all the db files involved in the transaction. The same call ** sets the master journal pointer in each individual journal. If ** an error occurs here, do not delete the master journal file. ** ** If the error occurs during the first call to ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the ** master journal file will be orphaned. But we cannot delete it, ** in case the master journal file name was written into the journal ** file before the failure occurred. */ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster); } } sqlite3OsCloseFree(pMaster); assert( rc!=SQLITE_BUSY ); if( rc!=SQLITE_OK ){ sqlite3DbFree(db, zMaster); return rc; } /* Delete the master journal file. This commits the transaction. After ** doing this the directory is synced again before any individual ** transaction files are deleted. */ rc = sqlite3OsDelete(pVfs, zMaster, 1); sqlite3DbFree(db, zMaster); zMaster = 0; if( rc ){ return rc; } /* All files and directories have already been synced, so the following ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and ** deleting or truncating journals. If something goes wrong while ** this is happening we don't really care. The integrity of the ** transaction is already guaranteed, but some stray 'cold' journals ** may be lying around. Returning an error code won't help matters. */ disable_simulated_io_errors(); sqlite3BeginBenignMalloc(); for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ sqlite3BtreeCommitPhaseTwo(pBt, 1); } } sqlite3EndBenignMalloc(); enable_simulated_io_errors(); sqlite3VtabCommit(db); } #endif return rc; } /* ** This routine checks that the sqlite3.nVdbeActive count variable ** matches the number of vdbe's in the list sqlite3.pVdbe that are ** currently active. An assertion fails if the two counts do not match. ** This is an internal self-check only - it is not an essential processing ** step. ** ** This is a no-op if NDEBUG is defined. */ #ifndef NDEBUG static void checkActiveVdbeCnt(sqlite3 *db){ Vdbe *p; int cnt = 0; int nWrite = 0; int nRead = 0; p = db->pVdbe; while( p ){ if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){ cnt++; if( p->readOnly==0 ) nWrite++; if( p->bIsReader ) nRead++; } p = p->pNext; } assert( cnt==db->nVdbeActive ); assert( nWrite==db->nVdbeWrite ); assert( nRead==db->nVdbeRead ); } #else #define checkActiveVdbeCnt(x) #endif /* ** If the Vdbe passed as the first argument opened a statement-transaction, ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the ** statement transaction is committed. ** ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. ** Otherwise SQLITE_OK. */ static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){ sqlite3 *const db = p->db; int rc = SQLITE_OK; int i; const int iSavepoint = p->iStatement-1; assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE); assert( db->nStatement>0 ); assert( p->iStatement==(db->nStatement+db->nSavepoint) ); for(i=0; i<db->nDb; i++){ int rc2 = SQLITE_OK; Btree *pBt = db->aDb[i].pBt; if( pBt ){ if( eOp==SAVEPOINT_ROLLBACK ){ rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint); } if( rc2==SQLITE_OK ){ rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint); } if( rc==SQLITE_OK ){ rc = rc2; } } } db->nStatement--; p->iStatement = 0; if( rc==SQLITE_OK ){ if( eOp==SAVEPOINT_ROLLBACK ){ rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint); } if( rc==SQLITE_OK ){ rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint); } } /* If the statement transaction is being rolled back, also restore the ** database handles deferred constraint counter to the value it had when ** the statement transaction was opened. */ if( eOp==SAVEPOINT_ROLLBACK ){ db->nDeferredCons = p->nStmtDefCons; db->nDeferredImmCons = p->nStmtDefImmCons; } return rc; } SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){ if( p->db->nStatement && p->iStatement ){ return vdbeCloseStatement(p, eOp); } return SQLITE_OK; } /* ** This function is called when a transaction opened by the database ** handle associated with the VM passed as an argument is about to be ** committed. If there are outstanding deferred foreign key constraint ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK. ** ** If there are outstanding FK violations and this function returns ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY ** and write an error message to it. Then return SQLITE_ERROR. */ #ifndef SQLITE_OMIT_FOREIGN_KEY SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ sqlite3 *db = p->db; if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) || (!deferred && p->nFkConstraint>0) ){ p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; p->errorAction = OE_Abort; sqlite3VdbeError(p, "FOREIGN KEY constraint failed"); return SQLITE_ERROR; } return SQLITE_OK; } #endif /* ** This routine is called the when a VDBE tries to halt. If the VDBE ** has made changes and is in autocommit mode, then commit those ** changes. If a rollback is needed, then do the rollback. ** ** This routine is the only way to move the state of a VM from ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to ** call this on a VM that is in the SQLITE_MAGIC_HALT state. ** ** Return an error code. If the commit could not complete because of ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it ** means the close did not happen and needs to be repeated. */ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ int rc; /* Used to store transient return codes */ sqlite3 *db = p->db; /* This function contains the logic that determines if a statement or ** transaction will be committed or rolled back as a result of the ** execution of this virtual machine. ** ** If any of the following errors occur: ** ** SQLITE_NOMEM ** SQLITE_IOERR ** SQLITE_FULL ** SQLITE_INTERRUPT ** ** Then the internal cache might have been left in an inconsistent ** state. We need to rollback the statement transaction, if there is ** one, or the complete transaction if there is no statement transaction. */ if( db->mallocFailed ){ p->rc = SQLITE_NOMEM_BKPT; } closeAllCursors(p); if( p->magic!=VDBE_MAGIC_RUN ){ return SQLITE_OK; } checkActiveVdbeCnt(db); /* No commit or rollback needed if the program never started or if the ** SQL statement does not read or write a database file. */ if( p->pc>=0 && p->bIsReader ){ int mrc; /* Primary error code from p->rc */ int eStatementOp = 0; int isSpecialError; /* Set to true if a 'special' error */ /* Lock all btrees used by the statement */ sqlite3VdbeEnter(p); /* Check for one of the special errors */ mrc = p->rc & 0xff; isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL; if( isSpecialError ){ /* If the query was read-only and the error code is SQLITE_INTERRUPT, ** no rollback is necessary. Otherwise, at least a savepoint ** transaction must be rolled back to restore the database to a ** consistent state. ** ** Even if the statement is read-only, it is important to perform ** a statement or transaction rollback operation. If the error ** occurred while writing to the journal, sub-journal or database ** file as part of an effort to free up cache space (see function ** pagerStress() in pager.c), the rollback is required to restore ** the pager to a consistent state. */ if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){ if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){ eStatementOp = SAVEPOINT_ROLLBACK; }else{ /* We are forced to roll back the active transaction. Before doing ** so, abort any other statements this handle currently has active. */ sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); sqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } } } /* Check for immediate foreign key violations. */ if( p->rc==SQLITE_OK ){ sqlite3VdbeCheckFk(p, 0); } /* If the auto-commit flag is set and this is the only active writer ** VM, then we do either a commit or rollback of the current transaction. ** ** Note: This block also runs if one of the special errors handled ** above has occurred. */ if( !sqlite3VtabInSync(db) && db->autoCommit && db->nVdbeWrite==(p->readOnly==0) ){ if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ rc = sqlite3VdbeCheckFk(p, 1); if( rc!=SQLITE_OK ){ if( NEVER(p->readOnly) ){ sqlite3VdbeLeave(p); return SQLITE_ERROR; } rc = SQLITE_CONSTRAINT_FOREIGNKEY; }else{ /* The auto-commit flag is true, the vdbe program was successful ** or hit an 'OR FAIL' constraint and there are no deferred foreign ** key constraints to hold up the transaction. This means a commit ** is required. */ rc = vdbeCommit(db, p); } if( rc==SQLITE_BUSY && p->readOnly ){ sqlite3VdbeLeave(p); return SQLITE_BUSY; }else if( rc!=SQLITE_OK ){ p->rc = rc; sqlite3RollbackAll(db, SQLITE_OK); p->nChange = 0; }else{ db->nDeferredCons = 0; db->nDeferredImmCons = 0; db->flags &= ~SQLITE_DeferFKs; sqlite3CommitInternalChanges(db); } }else{ sqlite3RollbackAll(db, SQLITE_OK); p->nChange = 0; } db->nStatement = 0; }else if( eStatementOp==0 ){ if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){ eStatementOp = SAVEPOINT_RELEASE; }else if( p->errorAction==OE_Abort ){ eStatementOp = SAVEPOINT_ROLLBACK; }else{ sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); sqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } } /* If eStatementOp is non-zero, then a statement transaction needs to ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to ** do so. If this operation returns an error, and the current statement ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the ** current statement error code. */ if( eStatementOp ){ rc = sqlite3VdbeCloseStatement(p, eStatementOp); if( rc ){ if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){ p->rc = rc; sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; } sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); sqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } } /* If this was an INSERT, UPDATE or DELETE and no statement transaction ** has been rolled back, update the database connection change-counter. */ if( p->changeCntOn ){ if( eStatementOp!=SAVEPOINT_ROLLBACK ){ sqlite3VdbeSetChanges(db, p->nChange); }else{ sqlite3VdbeSetChanges(db, 0); } p->nChange = 0; } /* Release the locks */ sqlite3VdbeLeave(p); } /* We have successfully halted and closed the VM. Record this fact. */ if( p->pc>=0 ){ db->nVdbeActive--; if( !p->readOnly ) db->nVdbeWrite--; if( p->bIsReader ) db->nVdbeRead--; assert( db->nVdbeActive>=db->nVdbeRead ); assert( db->nVdbeRead>=db->nVdbeWrite ); assert( db->nVdbeWrite>=0 ); } p->magic = VDBE_MAGIC_HALT; checkActiveVdbeCnt(db); if( db->mallocFailed ){ p->rc = SQLITE_NOMEM_BKPT; } /* If the auto-commit flag is set to true, then any locks that were held ** by connection db have now been released. Call sqlite3ConnectionUnlocked() ** to invoke any required unlock-notify callbacks. */ if( db->autoCommit ){ sqlite3ConnectionUnlocked(db); } assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 ); return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK); } /* ** Each VDBE holds the result of the most recent sqlite3_step() call ** in p->rc. This routine sets that result back to SQLITE_OK. */ SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){ p->rc = SQLITE_OK; } /* ** Copy the error code and error message belonging to the VDBE passed ** as the first argument to its database handle (so that they will be ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()). ** ** This function does not clear the VDBE error code or message, just ** copies them to the database handle. */ SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){ sqlite3 *db = p->db; int rc = p->rc; if( p->zErrMsg ){ db->bBenignMalloc++; sqlite3BeginBenignMalloc(); if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db); sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); sqlite3EndBenignMalloc(); db->bBenignMalloc--; db->errCode = rc; }else{ sqlite3Error(db, rc); } return rc; } #ifdef SQLITE_ENABLE_SQLLOG /* ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, ** invoke it. */ static void vdbeInvokeSqllog(Vdbe *v){ if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){ char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql); assert( v->db->init.busy==0 ); if( zExpanded ){ sqlite3GlobalConfig.xSqllog( sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1 ); sqlite3DbFree(v->db, zExpanded); } } } #else # define vdbeInvokeSqllog(x) #endif /* ** Clean up a VDBE after execution but do not delete the VDBE just yet. ** Write any error messages into *pzErrMsg. Return the result code. ** ** After this routine is run, the VDBE should be ready to be executed ** again. ** ** To look at it another way, this routine resets the state of the ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to ** VDBE_MAGIC_INIT. */ SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){ sqlite3 *db; db = p->db; /* If the VM did not run to completion or if it encountered an ** error, then it might not have been halted properly. So halt ** it now. */ sqlite3VdbeHalt(p); /* If the VDBE has be run even partially, then transfer the error code ** and error message from the VDBE into the main database structure. But ** if the VDBE has just been set to run but has not actually executed any ** instructions yet, leave the main database error information unchanged. */ if( p->pc>=0 ){ vdbeInvokeSqllog(p); sqlite3VdbeTransferError(p); sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; if( p->runOnlyOnce ) p->expired = 1; }else if( p->rc && p->expired ){ /* The expired flag was set on the VDBE before the first call ** to sqlite3_step(). For consistency (since sqlite3_step() was ** called), set the database error in this case as well. */ sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg); sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; } /* Reclaim all memory used by the VDBE */ Cleanup(p); /* Save profiling information from this VDBE run. */ #ifdef VDBE_PROFILE { FILE *out = fopen("vdbe_profile.out", "a"); if( out ){ int i; fprintf(out, "---- "); for(i=0; i<p->nOp; i++){ fprintf(out, "%02x", p->aOp[i].opcode); } fprintf(out, "\n"); if( p->zSql ){ char c, pc = 0; fprintf(out, "-- "); for(i=0; (c = p->zSql[i])!=0; i++){ if( pc=='\n' ) fprintf(out, "-- "); putc(c, out); pc = c; } if( pc!='\n' ) fprintf(out, "\n"); } for(i=0; i<p->nOp; i++){ char zHdr[100]; sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ", p->aOp[i].cnt, p->aOp[i].cycles, p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0 ); fprintf(out, "%s", zHdr); sqlite3VdbePrintOp(out, i, &p->aOp[i]); } fclose(out); } } #endif p->iCurrentTime = 0; p->magic = VDBE_MAGIC_RESET; return p->rc & db->errMask; } /* ** Clean up and delete a VDBE after execution. Return an integer which is ** the result code. Write any error message text into *pzErrMsg. */ SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){ int rc = SQLITE_OK; if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){ rc = sqlite3VdbeReset(p); assert( (rc & p->db->errMask)==rc ); } sqlite3VdbeDelete(p); return rc; } /* ** If parameter iOp is less than zero, then invoke the destructor for ** all auxiliary data pointers currently cached by the VM passed as ** the first argument. ** ** Or, if iOp is greater than or equal to zero, then the destructor is ** only invoked for those auxiliary data pointers created by the user ** function invoked by the OP_Function opcode at instruction iOp of ** VM pVdbe, and only then if: ** ** * the associated function parameter is the 32nd or later (counting ** from left to right), or ** ** * the corresponding bit in argument mask is clear (where the first ** function parameter corresponds to bit 0 etc.). */ SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){ while( *pp ){ AuxData *pAux = *pp; if( (iOp<0) || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg)))) ){ testcase( pAux->iArg==31 ); if( pAux->xDelete ){ pAux->xDelete(pAux->pAux); } *pp = pAux->pNext; sqlite3DbFree(db, pAux); }else{ pp= &pAux->pNext; } } } /* ** Free all memory associated with the Vdbe passed as the second argument, ** except for object itself, which is preserved. ** ** The difference between this function and sqlite3VdbeDelete() is that ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with ** the database connection and frees the object itself. */ SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){ SubProgram *pSub, *pNext; assert( p->db==0 || p->db==db ); releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); for(pSub=p->pProgram; pSub; pSub=pNext){ pNext = pSub->pNext; vdbeFreeOpArray(db, pSub->aOp, pSub->nOp); sqlite3DbFree(db, pSub); } if( p->magic!=VDBE_MAGIC_INIT ){ releaseMemArray(p->aVar, p->nVar); sqlite3DbFree(db, p->pVList); sqlite3DbFree(db, p->pFree); } vdbeFreeOpArray(db, p->aOp, p->nOp); sqlite3DbFree(db, p->aColName); sqlite3DbFree(db, p->zSql); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS { int i; for(i=0; i<p->nScan; i++){ sqlite3DbFree(db, p->aScan[i].zName); } sqlite3DbFree(db, p->aScan); } #endif } /* ** Delete an entire VDBE. */ SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){ sqlite3 *db; if( NEVER(p==0) ) return; db = p->db; assert( sqlite3_mutex_held(db->mutex) ); sqlite3VdbeClearObject(db, p); if( p->pPrev ){ p->pPrev->pNext = p->pNext; }else{ assert( db->pVdbe==p ); db->pVdbe = p->pNext; } if( p->pNext ){ p->pNext->pPrev = p->pPrev; } p->magic = VDBE_MAGIC_DEAD; p->db = 0; sqlite3DbFree(db, p); } /* ** The cursor "p" has a pending seek operation that has not yet been ** carried out. Seek the cursor now. If an error occurs, return ** the appropriate error code. */ static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){ int res, rc; #ifdef SQLITE_TEST extern int sqlite3_search_count; #endif assert( p->deferredMoveto ); assert( p->isTable ); assert( p->eCurType==CURTYPE_BTREE ); rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res); if( rc ) return rc; if( res!=0 ) return SQLITE_CORRUPT_BKPT; #ifdef SQLITE_TEST sqlite3_search_count++; #endif p->deferredMoveto = 0; p->cacheStatus = CACHE_STALE; return SQLITE_OK; } /* ** Something has moved cursor "p" out of place. Maybe the row it was ** pointed to was deleted out from under it. Or maybe the btree was ** rebalanced. Whatever the cause, try to restore "p" to the place it ** is supposed to be pointing. If the row was deleted out from under the ** cursor, set the cursor to point to a NULL row. */ static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){ int isDifferentRow, rc; assert( p->eCurType==CURTYPE_BTREE ); assert( p->uc.pCursor!=0 ); assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ); rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow); p->cacheStatus = CACHE_STALE; if( isDifferentRow ) p->nullRow = 1; return rc; } /* ** Check to ensure that the cursor is valid. Restore the cursor ** if need be. Return any I/O error from the restore operation. */ SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){ assert( p->eCurType==CURTYPE_BTREE ); if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ return handleMovedCursor(p); } return SQLITE_OK; } /* ** Make sure the cursor p is ready to read or write the row to which it ** was last positioned. Return an error code if an OOM fault or I/O error ** prevents us from positioning the cursor to its correct position. ** ** If a MoveTo operation is pending on the given cursor, then do that ** MoveTo now. If no move is pending, check to see if the row has been ** deleted out from under the cursor and if it has, mark the row as ** a NULL row. ** ** If the cursor is already pointing to the correct row and that row has ** not been deleted out from under the cursor, then this routine is a no-op. */ SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){ VdbeCursor *p = *pp; if( p->eCurType==CURTYPE_BTREE ){ if( p->deferredMoveto ){ int iMap; if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){ *pp = p->pAltCursor; *piCol = iMap - 1; return SQLITE_OK; } return handleDeferredMoveto(p); } if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ return handleMovedCursor(p); } } return SQLITE_OK; } /* ** The following functions: ** ** sqlite3VdbeSerialType() ** sqlite3VdbeSerialTypeLen() ** sqlite3VdbeSerialLen() ** sqlite3VdbeSerialPut() ** sqlite3VdbeSerialGet() ** ** encapsulate the code that serializes values for storage in SQLite ** data and index records. Each serialized value consists of a ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned ** integer, stored as a varint. ** ** In an SQLite index record, the serial type is stored directly before ** the blob of data that it corresponds to. In a table record, all serial ** types are stored at the start of the record, and the blobs of data at ** the end. Hence these functions allow the caller to handle the ** serial-type and data blob separately. ** ** The following table describes the various storage classes for data: ** ** serial type bytes of data type ** -------------- --------------- --------------- ** 0 0 NULL ** 1 1 signed integer ** 2 2 signed integer ** 3 3 signed integer ** 4 4 signed integer ** 5 6 signed integer ** 6 8 signed integer ** 7 8 IEEE float ** 8 0 Integer constant 0 ** 9 0 Integer constant 1 ** 10,11 reserved for expansion ** N>=12 and even (N-12)/2 BLOB ** N>=13 and odd (N-13)/2 text ** ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions ** of SQLite will not understand those serial types. */ /* ** Return the serial-type for the value stored in pMem. */ SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){ int flags = pMem->flags; u32 n; assert( pLen!=0 ); if( flags&MEM_Null ){ *pLen = 0; return 0; } if( flags&MEM_Int ){ /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ # define MAX_6BYTE ((((i64)0x00008000)<<32)-1) i64 i = pMem->u.i; u64 u; if( i<0 ){ u = ~i; }else{ u = i; } if( u<=127 ){ if( (i&1)==i && file_format>=4 ){ *pLen = 0; return 8+(u32)u; }else{ *pLen = 1; return 1; } } if( u<=32767 ){ *pLen = 2; return 2; } if( u<=8388607 ){ *pLen = 3; return 3; } if( u<=2147483647 ){ *pLen = 4; return 4; } if( u<=MAX_6BYTE ){ *pLen = 6; return 5; } *pLen = 8; return 6; } if( flags&MEM_Real ){ *pLen = 8; return 7; } assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) ); assert( pMem->n>=0 ); n = (u32)pMem->n; if( flags & MEM_Zero ){ n += pMem->u.nZero; } *pLen = n; return ((n*2) + 12 + ((flags&MEM_Str)!=0)); } /* ** The sizes for serial types less than 128 */ static const u8 sqlite3SmallTypeSizes[] = { /* 0 1 2 3 4 5 6 7 8 9 */ /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57 }; /* ** Return the length of the data corresponding to the supplied serial-type. */ SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){ if( serial_type>=128 ){ return (serial_type-12)/2; }else{ assert( serial_type<12 || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 ); return sqlite3SmallTypeSizes[serial_type]; } } SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){ assert( serial_type<128 ); return sqlite3SmallTypeSizes[serial_type]; } /* ** If we are on an architecture with mixed-endian floating ** points (ex: ARM7) then swap the lower 4 bytes with the ** upper 4 bytes. Return the result. ** ** For most architectures, this is a no-op. ** ** (later): It is reported to me that the mixed-endian problem ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems ** that early versions of GCC stored the two words of a 64-bit ** float in the wrong order. And that error has been propagated ** ever since. The blame is not necessarily with GCC, though. ** GCC might have just copying the problem from a prior compiler. ** I am also told that newer versions of GCC that follow a different ** ABI get the byte order right. ** ** Developers using SQLite on an ARM7 should compile and run their ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG ** enabled, some asserts below will ensure that the byte order of ** floating point values is correct. ** ** (2007-08-30) Frank van Vugt has studied this problem closely ** and has send his findings to the SQLite developers. Frank ** writes that some Linux kernels offer floating point hardware ** emulation that uses only 32-bit mantissas instead of a full ** 48-bits as required by the IEEE standard. (This is the ** CONFIG_FPE_FASTFPE option.) On such systems, floating point ** byte swapping becomes very complicated. To avoid problems, ** the necessary byte swapping is carried out using a 64-bit integer ** rather than a 64-bit float. Frank assures us that the code here ** works for him. We, the developers, have no way to independently ** verify this, but Frank seems to know what he is talking about ** so we trust him. */ #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT static u64 floatSwap(u64 in){ union { u64 r; u32 i[2]; } u; u32 t; u.r = in; t = u.i[0]; u.i[0] = u.i[1]; u.i[1] = t; return u.r; } # define swapMixedEndianFloat(X) X = floatSwap(X) #else # define swapMixedEndianFloat(X) #endif /* ** Write the serialized data blob for the value stored in pMem into ** buf. It is assumed that the caller has allocated sufficient space. ** Return the number of bytes written. ** ** nBuf is the amount of space left in buf[]. The caller is responsible ** for allocating enough space to buf[] to hold the entire field, exclusive ** of the pMem->u.nZero bytes for a MEM_Zero value. ** ** Return the number of bytes actually written into buf[]. The number ** of bytes in the zero-filled tail is included in the return value only ** if those bytes were zeroed in buf[]. */ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ u32 len; /* Integer and Real */ if( serial_type<=7 && serial_type>0 ){ u64 v; u32 i; if( serial_type==7 ){ assert( sizeof(v)==sizeof(pMem->u.r) ); memcpy(&v, &pMem->u.r, sizeof(v)); swapMixedEndianFloat(v); }else{ v = pMem->u.i; } len = i = sqlite3SmallTypeSizes[serial_type]; assert( i>0 ); do{ buf[--i] = (u8)(v&0xFF); v >>= 8; }while( i ); return len; } /* String or blob */ if( serial_type>=12 ){ assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0) == (int)sqlite3VdbeSerialTypeLen(serial_type) ); len = pMem->n; if( len>0 ) memcpy(buf, pMem->z, len); return len; } /* NULL or constants 0 or 1 */ return 0; } /* Input "x" is a sequence of unsigned characters that represent a ** big-endian integer. Return the equivalent native integer */ #define ONE_BYTE_INT(x) ((i8)(x)[0]) #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1]) #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2]) #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) /* ** Deserialize the data blob pointed to by buf as serial type serial_type ** and store the result in pMem. Return the number of bytes read. ** ** This function is implemented as two separate routines for performance. ** The few cases that require local variables are broken out into a separate ** routine so that in most cases the overhead of moving the stack pointer ** is avoided. */ static u32 SQLITE_NOINLINE serialGet( const unsigned char *buf, /* Buffer to deserialize from */ u32 serial_type, /* Serial type to deserialize */ Mem *pMem /* Memory cell to write value into */ ){ u64 x = FOUR_BYTE_UINT(buf); u32 y = FOUR_BYTE_UINT(buf+4); x = (x<<32) + y; if( serial_type==6 ){ /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit ** twos-complement integer. */ pMem->u.i = *(i64*)&x; pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); }else{ /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit ** floating point number. */ #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT) /* Verify that integers and floating point values use the same ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is ** defined that 64-bit floating point values really are mixed ** endian. */ static const u64 t1 = ((u64)0x3ff00000)<<32; static const double r1 = 1.0; u64 t2 = t1; swapMixedEndianFloat(t2); assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 ); #endif assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 ); swapMixedEndianFloat(x); memcpy(&pMem->u.r, &x, sizeof(x)); pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real; } return 8; } SQLITE_PRIVATE u32 sqlite3VdbeSerialGet( const unsigned char *buf, /* Buffer to deserialize from */ u32 serial_type, /* Serial type to deserialize */ Mem *pMem /* Memory cell to write value into */ ){ switch( serial_type ){ case 10: /* Reserved for future use */ case 11: /* Reserved for future use */ case 0: { /* Null */ /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */ pMem->flags = MEM_Null; break; } case 1: { /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement ** integer. */ pMem->u.i = ONE_BYTE_INT(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 1; } case 2: { /* 2-byte signed integer */ /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit ** twos-complement integer. */ pMem->u.i = TWO_BYTE_INT(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 2; } case 3: { /* 3-byte signed integer */ /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit ** twos-complement integer. */ pMem->u.i = THREE_BYTE_INT(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 3; } case 4: { /* 4-byte signed integer */ /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit ** twos-complement integer. */ pMem->u.i = FOUR_BYTE_INT(buf); #ifdef __HP_cc /* Work around a sign-extension bug in the HP compiler for HP/UX */ if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL; #endif pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 4; } case 5: { /* 6-byte signed integer */ /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit ** twos-complement integer. */ pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return 6; } case 6: /* 8-byte signed integer */ case 7: { /* IEEE floating point */ /* These use local variables, so do them in a separate routine ** to avoid having to move the frame pointer in the common case */ return serialGet(buf,serial_type,pMem); } case 8: /* Integer 0 */ case 9: { /* Integer 1 */ /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */ /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */ pMem->u.i = serial_type-8; pMem->flags = MEM_Int; return 0; } default: { /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in ** length. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and ** (N-13)/2 bytes in length. */ static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem }; pMem->z = (char *)buf; pMem->n = (serial_type-12)/2; pMem->flags = aFlag[serial_type&1]; return pMem->n; } } return 0; } /* ** This routine is used to allocate sufficient space for an UnpackedRecord ** structure large enough to be used with sqlite3VdbeRecordUnpack() if ** the first argument is a pointer to KeyInfo structure pKeyInfo. ** ** The space is either allocated using sqlite3DbMallocRaw() or from within ** the unaligned buffer passed via the second and third arguments (presumably ** stack space). If the former, then *ppFree is set to a pointer that should ** be eventually freed by the caller using sqlite3DbFree(). Or, if the ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL ** before returning. ** ** If an OOM error occurs, NULL is returned. */ SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( KeyInfo *pKeyInfo /* Description of the record */ ){ UnpackedRecord *p; /* Unpacked record to return */ int nByte; /* Number of bytes required for *p */ nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1); p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte); if( !p ) return 0; p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))]; assert( pKeyInfo->aSortOrder!=0 ); p->pKeyInfo = pKeyInfo; p->nField = pKeyInfo->nField + 1; return p; } /* ** Given the nKey-byte encoding of a record in pKey[], populate the ** UnpackedRecord structure indicated by the fourth argument with the ** contents of the decoded record. */ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( KeyInfo *pKeyInfo, /* Information about the record format */ int nKey, /* Size of the binary record */ const void *pKey, /* The binary record */ UnpackedRecord *p /* Populate this structure before returning. */ ){ const unsigned char *aKey = (const unsigned char *)pKey; int d; u32 idx; /* Offset in aKey[] to read from */ u16 u; /* Unsigned loop counter */ u32 szHdr; Mem *pMem = p->aMem; p->default_rc = 0; assert( EIGHT_BYTE_ALIGNMENT(pMem) ); idx = getVarint32(aKey, szHdr); d = szHdr; u = 0; while( idx<szHdr && d<=nKey ){ u32 serial_type; idx += getVarint32(&aKey[idx], serial_type); pMem->enc = pKeyInfo->enc; pMem->db = pKeyInfo->db; /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */ pMem->szMalloc = 0; pMem->z = 0; d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem); pMem++; if( (++u)>=p->nField ) break; } assert( u<=pKeyInfo->nField + 1 ); p->nField = u; } #if SQLITE_DEBUG /* ** This function compares two index or table record keys in the same way ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(), ** this function deserializes and compares values using the ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used ** in assert() statements to ensure that the optimized code in ** sqlite3VdbeRecordCompare() returns results with these two primitives. ** ** Return true if the result of comparison is equivalent to desiredResult. ** Return false if there is a disagreement. */ static int vdbeRecordCompareDebug( int nKey1, const void *pKey1, /* Left key */ const UnpackedRecord *pPKey2, /* Right key */ int desiredResult /* Correct answer */ ){ u32 d1; /* Offset into aKey[] of next data element */ u32 idx1; /* Offset into aKey[] of next header element */ u32 szHdr1; /* Number of bytes in header */ int i = 0; int rc = 0; const unsigned char *aKey1 = (const unsigned char *)pKey1; KeyInfo *pKeyInfo; Mem mem1; pKeyInfo = pPKey2->pKeyInfo; if( pKeyInfo->db==0 ) return 1; mem1.enc = pKeyInfo->enc; mem1.db = pKeyInfo->db; /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */ VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ /* Compilers may complain that mem1.u.i is potentially uninitialized. ** We could initialize it, as shown here, to silence those complaints. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing ** the unnecessary initialization has a measurable negative performance ** impact, since this routine is a very high runner. And so, we choose ** to ignore the compiler warnings and leave this variable uninitialized. */ /* mem1.u.i = 0; // not needed, here to silence compiler warning */ idx1 = getVarint32(aKey1, szHdr1); if( szHdr1>98307 ) return SQLITE_CORRUPT; d1 = szHdr1; assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB ); assert( pKeyInfo->aSortOrder!=0 ); assert( pKeyInfo->nField>0 ); assert( idx1<=szHdr1 || CORRUPT_DB ); do{ u32 serial_type1; /* Read the serial types for the next element in each key. */ idx1 += getVarint32( aKey1+idx1, serial_type1 ); /* Verify that there is enough key space remaining to avoid ** a buffer overread. The "d1+serial_type1+2" subexpression will ** always be greater than or equal to the amount of required key space. ** Use that approximation to avoid the more expensive call to ** sqlite3VdbeSerialTypeLen() in the common case. */ if( d1+serial_type1+2>(u32)nKey1 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 ){ break; } /* Extract the values to be compared. */ d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1); /* Do the comparison */ rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]); if( rc!=0 ){ assert( mem1.szMalloc==0 ); /* See comment below */ if( pKeyInfo->aSortOrder[i] ){ rc = -rc; /* Invert the result for DESC sort order. */ } goto debugCompareEnd; } i++; }while( idx1<szHdr1 && i<pPKey2->nField ); /* No memory allocation is ever used on mem1. Prove this using ** the following assert(). If the assert() fails, it indicates a ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */ assert( mem1.szMalloc==0 ); /* rc==0 here means that one of the keys ran out of fields and ** all the fields up to that point were equal. Return the default_rc ** value. */ rc = pPKey2->default_rc; debugCompareEnd: if( desiredResult==0 && rc==0 ) return 1; if( desiredResult<0 && rc<0 ) return 1; if( desiredResult>0 && rc>0 ) return 1; if( CORRUPT_DB ) return 1; if( pKeyInfo->db->mallocFailed ) return 1; return 0; } #endif #if SQLITE_DEBUG /* ** Count the number of fields (a.k.a. columns) in the record given by ** pKey,nKey. The verify that this count is less than or equal to the ** limit given by pKeyInfo->nField + pKeyInfo->nXField. ** ** If this constraint is not satisfied, it means that the high-speed ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will ** not work correctly. If this assert() ever fires, it probably means ** that the KeyInfo.nField or KeyInfo.nXField values were computed ** incorrectly. */ static void vdbeAssertFieldCountWithinLimits( int nKey, const void *pKey, /* The record to verify */ const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */ ){ int nField = 0; u32 szHdr; u32 idx; u32 notUsed; const unsigned char *aKey = (const unsigned char*)pKey; if( CORRUPT_DB ) return; idx = getVarint32(aKey, szHdr); assert( nKey>=0 ); assert( szHdr<=(u32)nKey ); while( idx<szHdr ){ idx += getVarint32(aKey+idx, notUsed); nField++; } assert( nField <= pKeyInfo->nField+pKeyInfo->nXField ); } #else # define vdbeAssertFieldCountWithinLimits(A,B,C) #endif /* ** Both *pMem1 and *pMem2 contain string values. Compare the two values ** using the collation sequence pColl. As usual, return a negative , zero ** or positive value if *pMem1 is less than, equal to or greater than ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);". */ static int vdbeCompareMemString( const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl, u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */ ){ if( pMem1->enc==pColl->enc ){ /* The strings are already in the correct encoding. Call the ** comparison function directly */ return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z); }else{ int rc; const void *v1, *v2; int n1, n2; Mem c1; Mem c2; sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null); sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null); sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc); n1 = v1==0 ? 0 : c1.n; v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc); n2 = v2==0 ? 0 : c2.n; rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2); if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT; sqlite3VdbeMemRelease(&c1); sqlite3VdbeMemRelease(&c2); return rc; } } /* ** The input pBlob is guaranteed to be a Blob that is not marked ** with MEM_Zero. Return true if it could be a zero-blob. */ static int isAllZero(const char *z, int n){ int i; for(i=0; i<n; i++){ if( z[i] ) return 0; } return 1; } /* ** Compare two blobs. Return negative, zero, or positive if the first ** is less than, equal to, or greater than the second, respectively. ** If one blob is a prefix of the other, then the shorter is the lessor. */ static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){ int c; int n1 = pB1->n; int n2 = pB2->n; /* It is possible to have a Blob value that has some non-zero content ** followed by zero content. But that only comes up for Blobs formed ** by the OP_MakeRecord opcode, and such Blobs never get passed into ** sqlite3MemCompare(). */ assert( (pB1->flags & MEM_Zero)==0 || n1==0 ); assert( (pB2->flags & MEM_Zero)==0 || n2==0 ); if( (pB1->flags|pB2->flags) & MEM_Zero ){ if( pB1->flags & pB2->flags & MEM_Zero ){ return pB1->u.nZero - pB2->u.nZero; }else if( pB1->flags & MEM_Zero ){ if( !isAllZero(pB2->z, pB2->n) ) return -1; return pB1->u.nZero - n2; }else{ if( !isAllZero(pB1->z, pB1->n) ) return +1; return n1 - pB2->u.nZero; } } c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1); if( c ) return c; return n1 - n2; } /* ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point ** number. Return negative, zero, or positive if the first (i64) is less than, ** equal to, or greater than the second (double). */ static int sqlite3IntFloatCompare(i64 i, double r){ if( sizeof(LONGDOUBLE_TYPE)>8 ){ LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i; if( x<r ) return -1; if( x>r ) return +1; return 0; }else{ i64 y; double s; if( r<-9223372036854775808.0 ) return +1; if( r>9223372036854775807.0 ) return -1; y = (i64)r; if( i<y ) return -1; if( i>y ){ if( y==SMALLEST_INT64 && r>0.0 ) return -1; return +1; } s = (double)i; if( s<r ) return -1; if( s>r ) return +1; return 0; } } /* ** Compare the values contained by the two memory cells, returning ** negative, zero or positive if pMem1 is less than, equal to, or greater ** than pMem2. Sorting order is NULL's first, followed by numbers (integers ** and reals) sorted numerically, followed by text ordered by the collating ** sequence pColl and finally blob's ordered by memcmp(). ** ** Two NULL values are considered equal by this function. */ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){ int f1, f2; int combined_flags; f1 = pMem1->flags; f2 = pMem2->flags; combined_flags = f1|f2; assert( (combined_flags & MEM_RowSet)==0 ); /* If one value is NULL, it is less than the other. If both values ** are NULL, return 0. */ if( combined_flags&MEM_Null ){ return (f2&MEM_Null) - (f1&MEM_Null); } /* At least one of the two values is a number */ if( combined_flags&(MEM_Int|MEM_Real) ){ if( (f1 & f2 & MEM_Int)!=0 ){ if( pMem1->u.i < pMem2->u.i ) return -1; if( pMem1->u.i > pMem2->u.i ) return +1; return 0; } if( (f1 & f2 & MEM_Real)!=0 ){ if( pMem1->u.r < pMem2->u.r ) return -1; if( pMem1->u.r > pMem2->u.r ) return +1; return 0; } if( (f1&MEM_Int)!=0 ){ if( (f2&MEM_Real)!=0 ){ return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r); }else{ return -1; } } if( (f1&MEM_Real)!=0 ){ if( (f2&MEM_Int)!=0 ){ return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r); }else{ return -1; } } return +1; } /* If one value is a string and the other is a blob, the string is less. ** If both are strings, compare using the collating functions. */ if( combined_flags&MEM_Str ){ if( (f1 & MEM_Str)==0 ){ return 1; } if( (f2 & MEM_Str)==0 ){ return -1; } assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed ); assert( pMem1->enc==SQLITE_UTF8 || pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE ); /* The collation sequence must be defined at this point, even if ** the user deletes the collation sequence after the vdbe program is ** compiled (this was not always the case). */ assert( !pColl || pColl->xCmp ); if( pColl ){ return vdbeCompareMemString(pMem1, pMem2, pColl, 0); } /* If a NULL pointer was passed as the collate function, fall through ** to the blob case and use memcmp(). */ } /* Both values must be blobs. Compare using memcmp(). */ return sqlite3BlobCompare(pMem1, pMem2); } /* ** The first argument passed to this function is a serial-type that ** corresponds to an integer - all values between 1 and 9 inclusive ** except 7. The second points to a buffer containing an integer value ** serialized according to serial_type. This function deserializes ** and returns the value. */ static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){ u32 y; assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) ); switch( serial_type ){ case 0: case 1: testcase( aKey[0]&0x80 ); return ONE_BYTE_INT(aKey); case 2: testcase( aKey[0]&0x80 ); return TWO_BYTE_INT(aKey); case 3: testcase( aKey[0]&0x80 ); return THREE_BYTE_INT(aKey); case 4: { testcase( aKey[0]&0x80 ); y = FOUR_BYTE_UINT(aKey); return (i64)*(int*)&y; } case 5: { testcase( aKey[0]&0x80 ); return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey); } case 6: { u64 x = FOUR_BYTE_UINT(aKey); testcase( aKey[0]&0x80 ); x = (x<<32) | FOUR_BYTE_UINT(aKey+4); return (i64)*(i64*)&x; } } return (serial_type - 8); } /* ** This function compares the two table rows or index records ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero ** or positive integer if key1 is less than, equal to or ** greater than key2. The {nKey1, pKey1} key must be a blob ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2 ** key must be a parsed key such as obtained from ** sqlite3VdbeParseRecord. ** ** If argument bSkip is non-zero, it is assumed that the caller has already ** determined that the first fields of the keys are equal. ** ** Key1 and Key2 do not have to contain the same number of fields. If all ** fields that appear in both keys are equal, then pPKey2->default_rc is ** returned. ** ** If database corruption is discovered, set pPKey2->errCode to ** SQLITE_CORRUPT and return 0. If an OOM error is encountered, ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db). */ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2, /* Right key */ int bSkip /* If true, skip the first field */ ){ u32 d1; /* Offset into aKey[] of next data element */ int i; /* Index of next field to compare */ u32 szHdr1; /* Size of record header in bytes */ u32 idx1; /* Offset of first type in header */ int rc = 0; /* Return value */ Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */ KeyInfo *pKeyInfo = pPKey2->pKeyInfo; const unsigned char *aKey1 = (const unsigned char *)pKey1; Mem mem1; /* If bSkip is true, then the caller has already determined that the first ** two elements in the keys are equal. Fix the various stack variables so ** that this routine begins comparing at the second field. */ if( bSkip ){ u32 s1; idx1 = 1 + getVarint32(&aKey1[1], s1); szHdr1 = aKey1[0]; d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1); i = 1; pRhs++; }else{ idx1 = getVarint32(aKey1, szHdr1); d1 = szHdr1; if( d1>(unsigned)nKey1 ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ } i = 0; } VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB ); assert( pPKey2->pKeyInfo->aSortOrder!=0 ); assert( pPKey2->pKeyInfo->nField>0 ); assert( idx1<=szHdr1 || CORRUPT_DB ); do{ u32 serial_type; /* RHS is an integer */ if( pRhs->flags & MEM_Int ){ serial_type = aKey1[idx1]; testcase( serial_type==12 ); if( serial_type>=10 ){ rc = +1; }else if( serial_type==0 ){ rc = -1; }else if( serial_type==7 ){ sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r); }else{ i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]); i64 rhs = pRhs->u.i; if( lhs<rhs ){ rc = -1; }else if( lhs>rhs ){ rc = +1; } } } /* RHS is real */ else if( pRhs->flags & MEM_Real ){ serial_type = aKey1[idx1]; if( serial_type>=10 ){ /* Serial types 12 or greater are strings and blobs (greater than ** numbers). Types 10 and 11 are currently "reserved for future ** use", so it doesn't really matter what the results of comparing ** them to numberic values are. */ rc = +1; }else if( serial_type==0 ){ rc = -1; }else{ sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); if( serial_type==7 ){ if( mem1.u.r<pRhs->u.r ){ rc = -1; }else if( mem1.u.r>pRhs->u.r ){ rc = +1; } }else{ rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r); } } } /* RHS is a string */ else if( pRhs->flags & MEM_Str ){ getVarint32(&aKey1[idx1], serial_type); testcase( serial_type==12 ); if( serial_type<12 ){ rc = -1; }else if( !(serial_type & 0x01) ){ rc = +1; }else{ mem1.n = (serial_type - 12) / 2; testcase( (d1+mem1.n)==(unsigned)nKey1 ); testcase( (d1+mem1.n+1)==(unsigned)nKey1 ); if( (d1+mem1.n) > (unsigned)nKey1 ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ }else if( pKeyInfo->aColl[i] ){ mem1.enc = pKeyInfo->enc; mem1.db = pKeyInfo->db; mem1.flags = MEM_Str; mem1.z = (char*)&aKey1[d1]; rc = vdbeCompareMemString( &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode ); }else{ int nCmp = MIN(mem1.n, pRhs->n); rc = memcmp(&aKey1[d1], pRhs->z, nCmp); if( rc==0 ) rc = mem1.n - pRhs->n; } } } /* RHS is a blob */ else if( pRhs->flags & MEM_Blob ){ assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 ); getVarint32(&aKey1[idx1], serial_type); testcase( serial_type==12 ); if( serial_type<12 || (serial_type & 0x01) ){ rc = -1; }else{ int nStr = (serial_type - 12) / 2; testcase( (d1+nStr)==(unsigned)nKey1 ); testcase( (d1+nStr+1)==(unsigned)nKey1 ); if( (d1+nStr) > (unsigned)nKey1 ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ }else if( pRhs->flags & MEM_Zero ){ if( !isAllZero((const char*)&aKey1[d1],nStr) ){ rc = 1; }else{ rc = nStr - pRhs->u.nZero; } }else{ int nCmp = MIN(nStr, pRhs->n); rc = memcmp(&aKey1[d1], pRhs->z, nCmp); if( rc==0 ) rc = nStr - pRhs->n; } } } /* RHS is null */ else{ serial_type = aKey1[idx1]; rc = (serial_type!=0); } if( rc!=0 ){ if( pKeyInfo->aSortOrder[i] ){ rc = -rc; } assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) ); assert( mem1.szMalloc==0 ); /* See comment below */ return rc; } i++; pRhs++; d1 += sqlite3VdbeSerialTypeLen(serial_type); idx1 += sqlite3VarintLen(serial_type); }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 ); /* No memory allocation is ever used on mem1. Prove this using ** the following assert(). If the assert() fails, it indicates a ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */ assert( mem1.szMalloc==0 ); /* rc==0 here means that one or both of the keys ran out of fields and ** all the fields up to that point were equal. Return the default_rc ** value. */ assert( CORRUPT_DB || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) || pKeyInfo->db->mallocFailed ); pPKey2->eqSeen = 1; return pPKey2->default_rc; } SQLITE_PRIVATE int sqlite3VdbeRecordCompare( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2 /* Right key */ ){ return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0); } /* ** This function is an optimized version of sqlite3VdbeRecordCompare() ** that (a) the first field of pPKey2 is an integer, and (b) the ** size-of-header varint at the start of (pKey1/nKey1) fits in a single ** byte (i.e. is less than 128). ** ** To avoid concerns about buffer overreads, this routine is only used ** on schemas where the maximum valid header size is 63 bytes or less. */ static int vdbeRecordCompareInt( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2 /* Right key */ ){ const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F]; int serial_type = ((const u8*)pKey1)[1]; int res; u32 y; u64 x; i64 v; i64 lhs; vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo); assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB ); switch( serial_type ){ case 1: { /* 1-byte signed integer */ lhs = ONE_BYTE_INT(aKey); testcase( lhs<0 ); break; } case 2: { /* 2-byte signed integer */ lhs = TWO_BYTE_INT(aKey); testcase( lhs<0 ); break; } case 3: { /* 3-byte signed integer */ lhs = THREE_BYTE_INT(aKey); testcase( lhs<0 ); break; } case 4: { /* 4-byte signed integer */ y = FOUR_BYTE_UINT(aKey); lhs = (i64)*(int*)&y; testcase( lhs<0 ); break; } case 5: { /* 6-byte signed integer */ lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey); testcase( lhs<0 ); break; } case 6: { /* 8-byte signed integer */ x = FOUR_BYTE_UINT(aKey); x = (x<<32) | FOUR_BYTE_UINT(aKey+4); lhs = *(i64*)&x; testcase( lhs<0 ); break; } case 8: lhs = 0; break; case 9: lhs = 1; break; /* This case could be removed without changing the results of running ** this code. Including it causes gcc to generate a faster switch ** statement (since the range of switch targets now starts at zero and ** is contiguous) but does not cause any duplicate code to be generated ** (as gcc is clever enough to combine the two like cases). Other ** compilers might be similar. */ case 0: case 7: return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); default: return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); } v = pPKey2->aMem[0].u.i; if( v>lhs ){ res = pPKey2->r1; }else if( v<lhs ){ res = pPKey2->r2; }else if( pPKey2->nField>1 ){ /* The first fields of the two keys are equal. Compare the trailing ** fields. */ res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); }else{ /* The first fields of the two keys are equal and there are no trailing ** fields. Return pPKey2->default_rc in this case. */ res = pPKey2->default_rc; pPKey2->eqSeen = 1; } assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) ); return res; } /* ** This function is an optimized version of sqlite3VdbeRecordCompare() ** that (a) the first field of pPKey2 is a string, that (b) the first field ** uses the collation sequence BINARY and (c) that the size-of-header varint ** at the start of (pKey1/nKey1) fits in a single byte. */ static int vdbeRecordCompareString( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2 /* Right key */ ){ const u8 *aKey1 = (const u8*)pKey1; int serial_type; int res; assert( pPKey2->aMem[0].flags & MEM_Str ); vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo); getVarint32(&aKey1[1], serial_type); if( serial_type<12 ){ res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */ }else if( !(serial_type & 0x01) ){ res = pPKey2->r2; /* (pKey1/nKey1) is a blob */ }else{ int nCmp; int nStr; int szHdr = aKey1[0]; nStr = (serial_type-12) / 2; if( (szHdr + nStr) > nKey1 ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ } nCmp = MIN( pPKey2->aMem[0].n, nStr ); res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp); if( res==0 ){ res = nStr - pPKey2->aMem[0].n; if( res==0 ){ if( pPKey2->nField>1 ){ res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); }else{ res = pPKey2->default_rc; pPKey2->eqSeen = 1; } }else if( res>0 ){ res = pPKey2->r2; }else{ res = pPKey2->r1; } }else if( res>0 ){ res = pPKey2->r2; }else{ res = pPKey2->r1; } } assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) || CORRUPT_DB || pPKey2->pKeyInfo->db->mallocFailed ); return res; } /* ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function ** suitable for comparing serialized records to the unpacked record passed ** as the only argument. */ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ /* varintRecordCompareInt() and varintRecordCompareString() both assume ** that the size-of-header varint that occurs at the start of each record ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt() ** also assumes that it is safe to overread a buffer by at least the ** maximum possible legal header size plus 8 bytes. Because there is ** guaranteed to be at least 74 (but not 136) bytes of padding following each ** buffer passed to varintRecordCompareInt() this makes it convenient to ** limit the size of the header to 64 bytes in cases where the first field ** is an integer. ** ** The easiest way to enforce this limit is to consider only records with ** 13 fields or less. If the first field is an integer, the maximum legal ** header size is (12*5 + 1 + 1) bytes. */ if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){ int flags = p->aMem[0].flags; if( p->pKeyInfo->aSortOrder[0] ){ p->r1 = 1; p->r2 = -1; }else{ p->r1 = -1; p->r2 = 1; } if( (flags & MEM_Int) ){ return vdbeRecordCompareInt; } testcase( flags & MEM_Real ); testcase( flags & MEM_Null ); testcase( flags & MEM_Blob ); if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){ assert( flags & MEM_Str ); return vdbeRecordCompareString; } } return sqlite3VdbeRecordCompare; } /* ** pCur points at an index entry created using the OP_MakeRecord opcode. ** Read the rowid (the last field in the record) and store it in *rowid. ** Return SQLITE_OK if everything works, or an error code otherwise. ** ** pCur might be pointing to text obtained from a corrupt database file. ** So the content cannot be trusted. Do appropriate checks on the content. */ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){ i64 nCellKey = 0; int rc; u32 szHdr; /* Size of the header */ u32 typeRowid; /* Serial type of the rowid */ u32 lenRowid; /* Size of the rowid */ Mem m, v; /* Get the size of the index entry. Only indices entries of less ** than 2GiB are support - anything large must be database corruption. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so ** this code can safely assume that nCellKey is 32-bits */ assert( sqlite3BtreeCursorIsValid(pCur) ); nCellKey = sqlite3BtreePayloadSize(pCur); assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey ); /* Read in the complete content of the index entry */ sqlite3VdbeMemInit(&m, db, 0); rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m); if( rc ){ return rc; } /* The index entry must begin with a header size */ (void)getVarint32((u8*)m.z, szHdr); testcase( szHdr==3 ); testcase( szHdr==m.n ); if( unlikely(szHdr<3 || (int)szHdr>m.n) ){ goto idx_rowid_corruption; } /* The last field of the index should be an integer - the ROWID. ** Verify that the last entry really is an integer. */ (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid); testcase( typeRowid==1 ); testcase( typeRowid==2 ); testcase( typeRowid==3 ); testcase( typeRowid==4 ); testcase( typeRowid==5 ); testcase( typeRowid==6 ); testcase( typeRowid==8 ); testcase( typeRowid==9 ); if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){ goto idx_rowid_corruption; } lenRowid = sqlite3SmallTypeSizes[typeRowid]; testcase( (u32)m.n==szHdr+lenRowid ); if( unlikely((u32)m.n<szHdr+lenRowid) ){ goto idx_rowid_corruption; } /* Fetch the integer off the end of the index record */ sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v); *rowid = v.u.i; sqlite3VdbeMemRelease(&m); return SQLITE_OK; /* Jump here if database corruption is detected after m has been ** allocated. Free the m object and return SQLITE_CORRUPT. */ idx_rowid_corruption: testcase( m.szMalloc!=0 ); sqlite3VdbeMemRelease(&m); return SQLITE_CORRUPT_BKPT; } /* ** Compare the key of the index entry that cursor pC is pointing to against ** the key string in pUnpacked. Write into *pRes a number ** that is negative, zero, or positive if pC is less than, equal to, ** or greater than pUnpacked. Return SQLITE_OK on success. ** ** pUnpacked is either created without a rowid or is truncated so that it ** omits the rowid at the end. The rowid at the end of the index entry ** is ignored as well. Hence, this routine only compares the prefixes ** of the keys prior to the final rowid, not the entire key. */ SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare( sqlite3 *db, /* Database connection */ VdbeCursor *pC, /* The cursor to compare against */ UnpackedRecord *pUnpacked, /* Unpacked version of key */ int *res /* Write the comparison result here */ ){ i64 nCellKey = 0; int rc; BtCursor *pCur; Mem m; assert( pC->eCurType==CURTYPE_BTREE ); pCur = pC->uc.pCursor; assert( sqlite3BtreeCursorIsValid(pCur) ); nCellKey = sqlite3BtreePayloadSize(pCur); /* nCellKey will always be between 0 and 0xffffffff because of the way ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ if( nCellKey<=0 || nCellKey>0x7fffffff ){ *res = 0; return SQLITE_CORRUPT_BKPT; } sqlite3VdbeMemInit(&m, db, 0); rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m); if( rc ){ return rc; } *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked); sqlite3VdbeMemRelease(&m); return SQLITE_OK; } /* ** This routine sets the value to be returned by subsequent calls to ** sqlite3_changes() on the database handle 'db'. */ SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){ assert( sqlite3_mutex_held(db->mutex) ); db->nChange = nChange; db->nTotalChange += nChange; } /* ** Set a flag in the vdbe to update the change counter when it is finalised ** or reset. */ SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){ v->changeCntOn = 1; } /* ** Mark every prepared statement associated with a database connection ** as expired. ** ** An expired statement means that recompilation of the statement is ** recommend. Statements expire when things happen that make their ** programs obsolete. Removing user-defined functions or collating ** sequences, or changing an authorization function are the types of ** things that make prepared statements obsolete. */ SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){ Vdbe *p; for(p = db->pVdbe; p; p=p->pNext){ p->expired = 1; } } /* ** Return the database associated with the Vdbe. */ SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){ return v->db; } /* ** Return a pointer to an sqlite3_value structure containing the value bound ** parameter iVar of VM v. Except, if the value is an SQL NULL, return ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_* ** constants) to the value before returning it. ** ** The returned value must be freed by the caller using sqlite3ValueFree(). */ SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){ assert( iVar>0 ); if( v ){ Mem *pMem = &v->aVar[iVar-1]; if( 0==(pMem->flags & MEM_Null) ){ sqlite3_value *pRet = sqlite3ValueNew(v->db); if( pRet ){ sqlite3VdbeMemCopy((Mem *)pRet, pMem); sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8); } return pRet; } } return 0; } /* ** Configure SQL variable iVar so that binding a new value to it signals ** to sqlite3_reoptimize() that re-preparing the statement may result ** in a better query plan. */ SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){ assert( iVar>0 ); if( iVar>32 ){ v->expmask = 0xffffffff; }else{ v->expmask |= ((u32)1 << (iVar-1)); } } #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored ** in memory obtained from sqlite3DbMalloc). */ SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){ if( pVtab->zErrMsg ){ sqlite3 *db = p->db; sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg); sqlite3_free(pVtab->zErrMsg); pVtab->zErrMsg = 0; } } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** If the second argument is not NULL, release any allocations associated ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord ** structure itself, using sqlite3DbFree(). ** ** This function is used to free UnpackedRecord structures allocated by ** the vdbeUnpackRecord() function found in vdbeapi.c. */ static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){ if( p ){ int i; for(i=0; i<nField; i++){ Mem *pMem = &p->aMem[i]; if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem); } sqlite3DbFree(db, p); } } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call, ** then cursor passed as the second argument should point to the row about ** to be update or deleted. If the application calls sqlite3_preupdate_old(), ** the required value will be read from the row the cursor points to. */ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( Vdbe *v, /* Vdbe pre-update hook is invoked by */ VdbeCursor *pCsr, /* Cursor to grab old.* values from */ int op, /* SQLITE_INSERT, UPDATE or DELETE */ const char *zDb, /* Database name */ Table *pTab, /* Modified table */ i64 iKey1, /* Initial key value */ int iReg /* Register for new.* record */ ){ sqlite3 *db = v->db; i64 iKey2; PreUpdate preupdate; const char *zTbl = pTab->zName; static const u8 fakeSortOrder = 0; assert( db->pPreUpdate==0 ); memset(&preupdate, 0, sizeof(PreUpdate)); if( HasRowid(pTab)==0 ){ iKey1 = iKey2 = 0; preupdate.pPk = sqlite3PrimaryKeyIndex(pTab); }else{ if( op==SQLITE_UPDATE ){ iKey2 = v->aMem[iReg].u.i; }else{ iKey2 = iKey1; } } assert( pCsr->nField==pTab->nCol || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1) ); preupdate.v = v; preupdate.pCsr = pCsr; preupdate.op = op; preupdate.iNewReg = iReg; preupdate.keyinfo.db = db; preupdate.keyinfo.enc = ENC(db); preupdate.keyinfo.nField = pTab->nCol; preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder; preupdate.iKey1 = iKey1; preupdate.iKey2 = iKey2; preupdate.pTab = pTab; db->pPreUpdate = &preupdate; db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2); db->pPreUpdate = 0; sqlite3DbFree(db, preupdate.aRecord); vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pUnpacked); vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pNewUnpacked); if( preupdate.aNew ){ int i; for(i=0; i<pCsr->nField; i++){ sqlite3VdbeMemRelease(&preupdate.aNew[i]); } sqlite3DbFree(db, preupdate.aNew); } } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ /************** End of vdbeaux.c *********************************************/ /************** Begin file vdbeapi.c *****************************************/ /* ** 2004 May 26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code use to implement APIs that are part of the ** VDBE. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #ifndef SQLITE_OMIT_DEPRECATED /* ** Return TRUE (non-zero) of the statement supplied as an argument needs ** to be recompiled. A statement needs to be recompiled whenever the ** execution environment changes in a way that would alter the program ** that sqlite3_prepare() generates. For example, if new functions or ** collating sequences are registered or if an authorizer function is ** added or changed. */ SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; return p==0 || p->expired; } #endif /* ** Check on a Vdbe to make sure it has not been finalized. Log ** an error and return true if it has been finalized (or is otherwise ** invalid). Return false if it is ok. */ static int vdbeSafety(Vdbe *p){ if( p->db==0 ){ sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement"); return 1; }else{ return 0; } } static int vdbeSafetyNotNull(Vdbe *p){ if( p==0 ){ sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement"); return 1; }else{ return vdbeSafety(p); } } #ifndef SQLITE_OMIT_TRACE /* ** Invoke the profile callback. This routine is only called if we already ** know that the profile callback is defined and needs to be invoked. */ static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){ sqlite3_int64 iNow; sqlite3_int64 iElapse; assert( p->startTime>0 ); assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 ); assert( db->init.busy==0 ); assert( p->zSql!=0 ); sqlite3OsCurrentTimeInt64(db->pVfs, &iNow); iElapse = (iNow - p->startTime)*1000000; if( db->xProfile ){ db->xProfile(db->pProfileArg, p->zSql, iElapse); } if( db->mTrace & SQLITE_TRACE_PROFILE ){ db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse); } p->startTime = 0; } /* ** The checkProfileCallback(DB,P) macro checks to see if a profile callback ** is needed, and it invokes the callback if it is needed. */ # define checkProfileCallback(DB,P) \ if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); } #else # define checkProfileCallback(DB,P) /*no-op*/ #endif /* ** The following routine destroys a virtual machine that is created by ** the sqlite3_compile() routine. The integer returned is an SQLITE_ ** success/failure code that describes the result of executing the virtual ** machine. ** ** This routine sets the error code and string returned by ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){ int rc; if( pStmt==0 ){ /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL ** pointer is a harmless no-op. */ rc = SQLITE_OK; }else{ Vdbe *v = (Vdbe*)pStmt; sqlite3 *db = v->db; if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT; sqlite3_mutex_enter(db->mutex); checkProfileCallback(db, v); rc = sqlite3VdbeFinalize(v); rc = sqlite3ApiExit(db, rc); sqlite3LeaveMutexAndCloseZombie(db); } return rc; } /* ** Terminate the current execution of an SQL statement and reset it ** back to its starting state so that it can be reused. A success code from ** the prior execution is returned. ** ** This routine sets the error code and string returned by ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){ int rc; if( pStmt==0 ){ rc = SQLITE_OK; }else{ Vdbe *v = (Vdbe*)pStmt; sqlite3 *db = v->db; sqlite3_mutex_enter(db->mutex); checkProfileCallback(db, v); rc = sqlite3VdbeReset(v); sqlite3VdbeRewind(v); assert( (rc & (db->errMask))==rc ); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); } return rc; } /* ** Set all the parameters in the compiled SQL statement to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){ int i; int rc = SQLITE_OK; Vdbe *p = (Vdbe*)pStmt; #if SQLITE_THREADSAFE sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex; #endif sqlite3_mutex_enter(mutex); for(i=0; i<p->nVar; i++){ sqlite3VdbeMemRelease(&p->aVar[i]); p->aVar[i].flags = MEM_Null; } if( p->isPrepareV2 && p->expmask ){ p->expired = 1; } sqlite3_mutex_leave(mutex); return rc; } /**************************** sqlite3_value_ ******************************* ** The following routines extract information from a Mem or sqlite3_value ** structure. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){ Mem *p = (Mem*)pVal; if( p->flags & (MEM_Blob|MEM_Str) ){ if( ExpandBlob(p)!=SQLITE_OK ){ assert( p->flags==MEM_Null && p->z==0 ); return 0; } p->flags |= MEM_Blob; return p->n ? p->z : 0; }else{ return sqlite3_value_text(pVal); } } SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){ return sqlite3ValueBytes(pVal, SQLITE_UTF8); } SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){ return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE); } SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){ return sqlite3VdbeRealValue((Mem*)pVal); } SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){ return (int)sqlite3VdbeIntValue((Mem*)pVal); } SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){ return sqlite3VdbeIntValue((Mem*)pVal); } SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){ Mem *pMem = (Mem*)pVal; return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0); } SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){ return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){ return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); } SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){ return sqlite3ValueText(pVal, SQLITE_UTF16BE); } SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){ return sqlite3ValueText(pVal, SQLITE_UTF16LE); } #endif /* SQLITE_OMIT_UTF16 */ /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating ** point number string BLOB NULL */ SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){ static const u8 aType[] = { SQLITE_BLOB, /* 0x00 */ SQLITE_NULL, /* 0x01 */ SQLITE_TEXT, /* 0x02 */ SQLITE_NULL, /* 0x03 */ SQLITE_INTEGER, /* 0x04 */ SQLITE_NULL, /* 0x05 */ SQLITE_INTEGER, /* 0x06 */ SQLITE_NULL, /* 0x07 */ SQLITE_FLOAT, /* 0x08 */ SQLITE_NULL, /* 0x09 */ SQLITE_FLOAT, /* 0x0a */ SQLITE_NULL, /* 0x0b */ SQLITE_INTEGER, /* 0x0c */ SQLITE_NULL, /* 0x0d */ SQLITE_INTEGER, /* 0x0e */ SQLITE_NULL, /* 0x0f */ SQLITE_BLOB, /* 0x10 */ SQLITE_NULL, /* 0x11 */ SQLITE_TEXT, /* 0x12 */ SQLITE_NULL, /* 0x13 */ SQLITE_INTEGER, /* 0x14 */ SQLITE_NULL, /* 0x15 */ SQLITE_INTEGER, /* 0x16 */ SQLITE_NULL, /* 0x17 */ SQLITE_FLOAT, /* 0x18 */ SQLITE_NULL, /* 0x19 */ SQLITE_FLOAT, /* 0x1a */ SQLITE_NULL, /* 0x1b */ SQLITE_INTEGER, /* 0x1c */ SQLITE_NULL, /* 0x1d */ SQLITE_INTEGER, /* 0x1e */ SQLITE_NULL, /* 0x1f */ }; return aType[pVal->flags&MEM_AffMask]; } /* Make a copy of an sqlite3_value object */ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){ sqlite3_value *pNew; if( pOrig==0 ) return 0; pNew = sqlite3_malloc( sizeof(*pNew) ); if( pNew==0 ) return 0; memset(pNew, 0, sizeof(*pNew)); memcpy(pNew, pOrig, MEMCELLSIZE); pNew->flags &= ~MEM_Dyn; pNew->db = 0; if( pNew->flags&(MEM_Str|MEM_Blob) ){ pNew->flags &= ~(MEM_Static|MEM_Dyn); pNew->flags |= MEM_Ephem; if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){ sqlite3ValueFree(pNew); pNew = 0; } } return pNew; } /* Destroy an sqlite3_value object previously obtained from ** sqlite3_value_dup(). */ SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){ sqlite3ValueFree(pOld); } /**************************** sqlite3_result_ ******************************* ** The following routines are used by user-defined functions to specify ** the function result. ** ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the ** result as a string or blob but if the string or blob is too large, it ** then sets the error code to SQLITE_TOOBIG ** ** The invokeValueDestructor(P,X) routine invokes destructor function X() ** on value P is not going to be used and need to be destroyed. */ static void setResultStrOrError( sqlite3_context *pCtx, /* Function context */ const char *z, /* String pointer */ int n, /* Bytes in string, or negative */ u8 enc, /* Encoding of z. 0 for BLOBs */ void (*xDel)(void*) /* Destructor function */ ){ if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){ sqlite3_result_error_toobig(pCtx); } } static int invokeValueDestructor( const void *p, /* Value to destroy */ void (*xDel)(void*), /* The destructor */ sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */ ){ assert( xDel!=SQLITE_DYNAMIC ); if( xDel==0 ){ /* noop */ }else if( xDel==SQLITE_TRANSIENT ){ /* noop */ }else{ xDel((void*)p); } if( pCtx ) sqlite3_result_error_toobig(pCtx); return SQLITE_TOOBIG; } SQLITE_API void sqlite3_result_blob( sqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( n>=0 ); assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, 0, xDel); } SQLITE_API void sqlite3_result_blob64( sqlite3_context *pCtx, const void *z, sqlite3_uint64 n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); assert( xDel!=SQLITE_DYNAMIC ); if( n>0x7fffffff ){ (void)invokeValueDestructor(z, xDel, pCtx); }else{ setResultStrOrError(pCtx, z, (int)n, 0, xDel); } } SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetDouble(pCtx->pOut, rVal); } SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_ERROR; pCtx->fErrorOrAux = 1; sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_ERROR; pCtx->fErrorOrAux = 1; sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT); } #endif SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal); } SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetInt64(pCtx->pOut, iVal); } SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetNull(pCtx->pOut); } SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){ Mem *pOut = pCtx->pOut; assert( sqlite3_mutex_held(pOut->db->mutex) ); pOut->eSubtype = eSubtype & 0xff; pOut->flags |= MEM_Subtype; } SQLITE_API void sqlite3_result_text( sqlite3_context *pCtx, const char *z, int n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel); } SQLITE_API void sqlite3_result_text64( sqlite3_context *pCtx, const char *z, sqlite3_uint64 n, void (*xDel)(void *), unsigned char enc ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); assert( xDel!=SQLITE_DYNAMIC ); if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; if( n>0x7fffffff ){ (void)invokeValueDestructor(z, xDel, pCtx); }else{ setResultStrOrError(pCtx, z, (int)n, enc, xDel); } } #ifndef SQLITE_OMIT_UTF16 SQLITE_API void sqlite3_result_text16( sqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel); } SQLITE_API void sqlite3_result_text16be( sqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel); } SQLITE_API void sqlite3_result_text16le( sqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel); } #endif /* SQLITE_OMIT_UTF16 */ SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemCopy(pCtx->pOut, pValue); } SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n); } SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){ Mem *pOut = pCtx->pOut; assert( sqlite3_mutex_held(pOut->db->mutex) ); if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){ return SQLITE_TOOBIG; } sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n); return SQLITE_OK; } SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){ pCtx->isError = errCode; pCtx->fErrorOrAux = 1; #ifdef SQLITE_DEBUG if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode; #endif if( pCtx->pOut->flags & MEM_Null ){ sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, SQLITE_UTF8, SQLITE_STATIC); } } /* Force an SQLITE_TOOBIG error. */ SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_TOOBIG; pCtx->fErrorOrAux = 1; sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, SQLITE_UTF8, SQLITE_STATIC); } /* An SQLITE_NOMEM error. */ SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){ assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); sqlite3VdbeMemSetNull(pCtx->pOut); pCtx->isError = SQLITE_NOMEM_BKPT; pCtx->fErrorOrAux = 1; sqlite3OomFault(pCtx->pOut->db); } /* ** This function is called after a transaction has been committed. It ** invokes callbacks registered with sqlite3_wal_hook() as required. */ static int doWalCallbacks(sqlite3 *db){ int rc = SQLITE_OK; #ifndef SQLITE_OMIT_WAL int i; for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ int nEntry; sqlite3BtreeEnter(pBt); nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt)); sqlite3BtreeLeave(pBt); if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){ rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry); } } } #endif return rc; } /* ** Execute the statement pStmt, either until a row of data is ready, the ** statement is completely executed or an error occurs. ** ** This routine implements the bulk of the logic behind the sqlite_step() ** API. The only thing omitted is the automatic recompile if a ** schema change has occurred. That detail is handled by the ** outer sqlite3_step() wrapper procedure. */ static int sqlite3Step(Vdbe *p){ sqlite3 *db; int rc; assert(p); if( p->magic!=VDBE_MAGIC_RUN ){ /* We used to require that sqlite3_reset() be called before retrying ** sqlite3_step() after any error or after SQLITE_DONE. But beginning ** with version 3.7.0, we changed this so that sqlite3_reset() would ** be called automatically instead of throwing the SQLITE_MISUSE error. ** This "automatic-reset" change is not technically an incompatibility, ** since any application that receives an SQLITE_MISUSE is broken by ** definition. ** ** Nevertheless, some published applications that were originally written ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE ** returns, and those were broken by the automatic-reset change. As a ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the ** legacy behavior of returning SQLITE_MISUSE for cases where the ** previous sqlite3_step() returned something other than a SQLITE_LOCKED ** or SQLITE_BUSY error. */ #ifdef SQLITE_OMIT_AUTORESET if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){ sqlite3_reset((sqlite3_stmt*)p); }else{ return SQLITE_MISUSE_BKPT; } #else sqlite3_reset((sqlite3_stmt*)p); #endif } /* Check that malloc() has not failed. If it has, return early. */ db = p->db; if( db->mallocFailed ){ p->rc = SQLITE_NOMEM; return SQLITE_NOMEM_BKPT; } if( p->pc<=0 && p->expired ){ p->rc = SQLITE_SCHEMA; rc = SQLITE_ERROR; goto end_of_step; } if( p->pc<0 ){ /* If there are no other statements currently running, then ** reset the interrupt flag. This prevents a call to sqlite3_interrupt ** from interrupting a statement that has not yet started. */ if( db->nVdbeActive==0 ){ db->u1.isInterrupted = 0; } assert( db->nVdbeWrite>0 || db->autoCommit==0 || (db->nDeferredCons==0 && db->nDeferredImmCons==0) ); #ifndef SQLITE_OMIT_TRACE if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0) && !db->init.busy && p->zSql ){ sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime); }else{ assert( p->startTime==0 ); } #endif db->nVdbeActive++; if( p->readOnly==0 ) db->nVdbeWrite++; if( p->bIsReader ) db->nVdbeRead++; p->pc = 0; } #ifdef SQLITE_DEBUG p->rcApp = SQLITE_OK; #endif #ifndef SQLITE_OMIT_EXPLAIN if( p->explain ){ rc = sqlite3VdbeList(p); }else #endif /* SQLITE_OMIT_EXPLAIN */ { db->nVdbeExec++; rc = sqlite3VdbeExec(p); db->nVdbeExec--; } #ifndef SQLITE_OMIT_TRACE /* If the statement completed successfully, invoke the profile callback */ if( rc!=SQLITE_ROW ) checkProfileCallback(db, p); #endif if( rc==SQLITE_DONE ){ assert( p->rc==SQLITE_OK ); p->rc = doWalCallbacks(db); if( p->rc!=SQLITE_OK ){ rc = SQLITE_ERROR; } } db->errCode = rc; if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){ p->rc = SQLITE_NOMEM_BKPT; } end_of_step: /* At this point local variable rc holds the value that should be ** returned if this statement was compiled using the legacy ** sqlite3_prepare() interface. According to the docs, this can only ** be one of the values in the first assert() below. Variable p->rc ** contains the value that would be returned if sqlite3_finalize() ** were called on statement p. */ assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE ); assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp ); if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ /* If this statement was prepared using sqlite3_prepare_v2(), and an ** error has occurred, then return the error code in p->rc to the ** caller. Set the error code in the database handle to the same value. */ rc = sqlite3VdbeTransferError(p); } return (rc&db->errMask); } /* ** This is the top-level implementation of sqlite3_step(). Call ** sqlite3Step() to do most of the work. If a schema error occurs, ** call sqlite3Reprepare() and try again. */ SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){ int rc = SQLITE_OK; /* Result from sqlite3Step() */ int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */ Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */ int cnt = 0; /* Counter to prevent infinite loop of reprepares */ sqlite3 *db; /* The database connection */ if( vdbeSafetyNotNull(v) ){ return SQLITE_MISUSE_BKPT; } db = v->db; sqlite3_mutex_enter(db->mutex); v->doingRerun = 0; while( (rc = sqlite3Step(v))==SQLITE_SCHEMA && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){ int savedPc = v->pc; rc2 = rc = sqlite3Reprepare(v); if( rc!=SQLITE_OK) break; sqlite3_reset(pStmt); if( savedPc>=0 ) v->doingRerun = 1; assert( v->expired==0 ); } if( rc2!=SQLITE_OK ){ /* This case occurs after failing to recompile an sql statement. ** The error message from the SQL compiler has already been loaded ** into the database handle. This block copies the error message ** from the database handle into the statement and sets the statement ** program counter to 0 to ensure that when the statement is ** finalized or reset the parser error message is available via ** sqlite3_errmsg() and sqlite3_errcode(). */ const char *zErr = (const char *)sqlite3_value_text(db->pErr); sqlite3DbFree(db, v->zErrMsg); if( !db->mallocFailed ){ v->zErrMsg = sqlite3DbStrDup(db, zErr); v->rc = rc2; } else { v->zErrMsg = 0; v->rc = rc = SQLITE_NOMEM_BKPT; } } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Extract the user data from a sqlite3_context structure and return a ** pointer to it. */ SQLITE_API void *sqlite3_user_data(sqlite3_context *p){ assert( p && p->pFunc ); return p->pFunc->pUserData; } /* ** Extract the user data from a sqlite3_context structure and return a ** pointer to it. ** ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface ** returns a copy of the pointer to the database connection (the 1st ** parameter) of the sqlite3_create_function() and ** sqlite3_create_function16() routines that originally registered the ** application defined function. */ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){ assert( p && p->pOut ); return p->pOut->db; } /* ** Return the current time for a statement. If the current time ** is requested more than once within the same run of a single prepared ** statement, the exact same time is returned for each invocation regardless ** of the amount of time that elapses between invocations. In other words, ** the time returned is always the time of the first call. */ SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){ int rc; #ifndef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime; assert( p->pVdbe!=0 ); #else sqlite3_int64 iTime = 0; sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime; #endif if( *piTime==0 ){ rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime); if( rc ) *piTime = 0; } return *piTime; } /* ** The following is the implementation of an SQL function that always ** fails with an error message stating that the function is used in the ** wrong context. The sqlite3_overload_function() API might construct ** SQL function that use this routine so that the functions will exist ** for name resolution but are actually overloaded by the xFindFunction ** method of virtual tables. */ SQLITE_PRIVATE void sqlite3InvalidFunction( sqlite3_context *context, /* The function calling context */ int NotUsed, /* Number of arguments to the function */ sqlite3_value **NotUsed2 /* Value of each argument */ ){ const char *zName = context->pFunc->zName; char *zErr; UNUSED_PARAMETER2(NotUsed, NotUsed2); zErr = sqlite3_mprintf( "unable to use function %s in the requested context", zName); sqlite3_result_error(context, zErr, -1); sqlite3_free(zErr); } /* ** Create a new aggregate context for p and return a pointer to ** its pMem->z element. */ static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){ Mem *pMem = p->pMem; assert( (pMem->flags & MEM_Agg)==0 ); if( nByte<=0 ){ sqlite3VdbeMemSetNull(pMem); pMem->z = 0; }else{ sqlite3VdbeMemClearAndResize(pMem, nByte); pMem->flags = MEM_Agg; pMem->u.pDef = p->pFunc; if( pMem->z ){ memset(pMem->z, 0, nByte); } } return (void*)pMem->z; } /* ** Allocate or return the aggregate context for a user function. A new ** context is allocated on the first call. Subsequent calls return the ** same context that was returned on prior calls. */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){ assert( p && p->pFunc && p->pFunc->xFinalize ); assert( sqlite3_mutex_held(p->pOut->db->mutex) ); testcase( nByte<0 ); if( (p->pMem->flags & MEM_Agg)==0 ){ return createAggContext(p, nByte); }else{ return (void*)p->pMem->z; } } /* ** Return the auxiliary data pointer, if any, for the iArg'th argument to ** the user-function defined by pCtx. */ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){ AuxData *pAuxData; assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); #if SQLITE_ENABLE_STAT3_OR_STAT4 if( pCtx->pVdbe==0 ) return 0; #else assert( pCtx->pVdbe!=0 ); #endif for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; } return (pAuxData ? pAuxData->pAux : 0); } /* ** Set the auxiliary data pointer and delete function, for the iArg'th ** argument to the user-function defined by pCtx. Any previous value is ** deleted by calling the delete function specified when it was set. */ SQLITE_API void sqlite3_set_auxdata( sqlite3_context *pCtx, int iArg, void *pAux, void (*xDelete)(void*) ){ AuxData *pAuxData; Vdbe *pVdbe = pCtx->pVdbe; assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); if( iArg<0 ) goto failed; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( pVdbe==0 ) goto failed; #else assert( pVdbe!=0 ); #endif for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; } if( pAuxData==0 ){ pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData)); if( !pAuxData ) goto failed; pAuxData->iOp = pCtx->iOp; pAuxData->iArg = iArg; pAuxData->pNext = pVdbe->pAuxData; pVdbe->pAuxData = pAuxData; if( pCtx->fErrorOrAux==0 ){ pCtx->isError = 0; pCtx->fErrorOrAux = 1; } }else if( pAuxData->xDelete ){ pAuxData->xDelete(pAuxData->pAux); } pAuxData->pAux = pAux; pAuxData->xDelete = xDelete; return; failed: if( xDelete ){ xDelete(pAux); } } #ifndef SQLITE_OMIT_DEPRECATED /* ** Return the number of times the Step function of an aggregate has been ** called. ** ** This function is deprecated. Do not use it for new code. It is ** provide only to avoid breaking legacy code. New aggregate function ** implementations should keep their own counts within their aggregate ** context. */ SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){ assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize ); return p->pMem->n; } #endif /* ** Return the number of columns in the result set for the statement pStmt. */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){ Vdbe *pVm = (Vdbe *)pStmt; return pVm ? pVm->nResColumn : 0; } /* ** Return the number of values available from the current row of the ** currently executing statement pStmt. */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){ Vdbe *pVm = (Vdbe *)pStmt; if( pVm==0 || pVm->pResultSet==0 ) return 0; return pVm->nResColumn; } /* ** Return a pointer to static memory containing an SQL NULL value. */ static const Mem *columnNullValue(void){ /* Even though the Mem structure contains an element ** of type i64, on certain architectures (x86) with certain compiler ** switches (-Os), gcc may align this Mem object on a 4-byte boundary ** instead of an 8-byte one. This all works fine, except that when ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s ** that a Mem structure is located on an 8-byte boundary. To prevent ** these assert()s from failing, when building with SQLITE_DEBUG defined ** using gcc, we force nullMem to be 8-byte aligned using the magical ** __attribute__((aligned(8))) macro. */ static const Mem nullMem #if defined(SQLITE_DEBUG) && defined(__GNUC__) __attribute__((aligned(8))) #endif = { /* .u = */ {0}, /* .flags = */ (u16)MEM_Null, /* .enc = */ (u8)0, /* .eSubtype = */ (u8)0, /* .n = */ (int)0, /* .z = */ (char*)0, /* .zMalloc = */ (char*)0, /* .szMalloc = */ (int)0, /* .uTemp = */ (u32)0, /* .db = */ (sqlite3*)0, /* .xDel = */ (void(*)(void*))0, #ifdef SQLITE_DEBUG /* .pScopyFrom = */ (Mem*)0, /* .pFiller = */ (void*)0, #endif }; return &nullMem; } /* ** Check to see if column iCol of the given statement is valid. If ** it is, return a pointer to the Mem for the value of that column. ** If iCol is not valid, return a pointer to a Mem which has a value ** of NULL. */ static Mem *columnMem(sqlite3_stmt *pStmt, int i){ Vdbe *pVm; Mem *pOut; pVm = (Vdbe *)pStmt; if( pVm==0 ) return (Mem*)columnNullValue(); assert( pVm->db ); sqlite3_mutex_enter(pVm->db->mutex); if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){ pOut = &pVm->pResultSet[i]; }else{ sqlite3Error(pVm->db, SQLITE_RANGE); pOut = (Mem*)columnNullValue(); } return pOut; } /* ** This function is called after invoking an sqlite3_value_XXX function on a ** column value (i.e. a value returned by evaluating an SQL expression in the ** select list of a SELECT statement) that may cause a malloc() failure. If ** malloc() has failed, the threads mallocFailed flag is cleared and the result ** code of statement pStmt set to SQLITE_NOMEM. ** ** Specifically, this is called from within: ** ** sqlite3_column_int() ** sqlite3_column_int64() ** sqlite3_column_text() ** sqlite3_column_text16() ** sqlite3_column_real() ** sqlite3_column_bytes() ** sqlite3_column_bytes16() ** sqiite3_column_blob() */ static void columnMallocFailure(sqlite3_stmt *pStmt) { /* If malloc() failed during an encoding conversion within an ** sqlite3_column_XXX API, then set the return code of the statement to ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR ** and _finalize() will return NOMEM. */ Vdbe *p = (Vdbe *)pStmt; if( p ){ assert( p->db!=0 ); assert( sqlite3_mutex_held(p->db->mutex) ); p->rc = sqlite3ApiExit(p->db, p->rc); sqlite3_mutex_leave(p->db->mutex); } } /**************************** sqlite3_column_ ******************************* ** The following routines are used to access elements of the current row ** in the result set. */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){ const void *val; val = sqlite3_value_blob( columnMem(pStmt,i) ); /* Even though there is no encoding conversion, value_blob() might ** need to call malloc() to expand the result of a zeroblob() ** expression. */ columnMallocFailure(pStmt); return val; } SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){ int val = sqlite3_value_bytes( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){ int val = sqlite3_value_bytes16( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){ double val = sqlite3_value_double( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){ int val = sqlite3_value_int( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){ sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){ const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){ Mem *pOut = columnMem(pStmt, i); if( pOut->flags&MEM_Static ){ pOut->flags &= ~MEM_Static; pOut->flags |= MEM_Ephem; } columnMallocFailure(pStmt); return (sqlite3_value *)pOut; } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){ const void *val = sqlite3_value_text16( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } #endif /* SQLITE_OMIT_UTF16 */ SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){ int iType = sqlite3_value_type( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return iType; } /* ** Convert the N-th element of pStmt->pColName[] into a string using ** xFunc() then return that string. If N is out of range, return 0. ** ** There are up to 5 names for each column. useType determines which ** name is returned. Here are the names: ** ** 0 The column name as it should be displayed for output ** 1 The datatype name for the column ** 2 The name of the database that the column derives from ** 3 The name of the table that the column derives from ** 4 The name of the table column that the result column derives from ** ** If the result is not a simple column reference (if it is an expression ** or a constant) then useTypes 2, 3, and 4 return NULL. */ static const void *columnName( sqlite3_stmt *pStmt, int N, const void *(*xFunc)(Mem*), int useType ){ const void *ret; Vdbe *p; int n; sqlite3 *db; #ifdef SQLITE_ENABLE_API_ARMOR if( pStmt==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif ret = 0; p = (Vdbe *)pStmt; db = p->db; assert( db!=0 ); n = sqlite3_column_count(pStmt); if( N<n && N>=0 ){ N += useType*n; sqlite3_mutex_enter(db->mutex); assert( db->mallocFailed==0 ); ret = xFunc(&p->aColName[N]); /* A malloc may have failed inside of the xFunc() call. If this ** is the case, clear the mallocFailed flag and return NULL. */ if( db->mallocFailed ){ sqlite3OomClear(db); ret = 0; } sqlite3_mutex_leave(db->mutex); } return ret; } /* ** Return the name of the Nth column of the result set returned by SQL ** statement pStmt. */ SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME); } #endif /* ** Constraint: If you have ENABLE_COLUMN_METADATA then you must ** not define OMIT_DECLTYPE. */ #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA) # error "Must not define both SQLITE_OMIT_DECLTYPE \ and SQLITE_ENABLE_COLUMN_METADATA" #endif #ifndef SQLITE_OMIT_DECLTYPE /* ** Return the column declaration type (if applicable) of the 'i'th column ** of the result set of SQL statement pStmt. */ SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE); } #endif /* SQLITE_OMIT_UTF16 */ #endif /* SQLITE_OMIT_DECLTYPE */ #ifdef SQLITE_ENABLE_COLUMN_METADATA /* ** Return the name of the database from which a result column derives. ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE); } #endif /* SQLITE_OMIT_UTF16 */ /* ** Return the name of the table from which a result column derives. ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE); } #endif /* SQLITE_OMIT_UTF16 */ /* ** Return the name of the table column from which a result column derives. ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN); } #ifndef SQLITE_OMIT_UTF16 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){ return columnName( pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN); } #endif /* SQLITE_OMIT_UTF16 */ #endif /* SQLITE_ENABLE_COLUMN_METADATA */ /******************************* sqlite3_bind_ *************************** ** ** Routines used to attach values to wildcards in a compiled SQL statement. */ /* ** Unbind the value bound to variable i in virtual machine p. This is the ** the same as binding a NULL value to the column. If the "i" parameter is ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK. ** ** A successful evaluation of this routine acquires the mutex on p. ** the mutex is released if any kind of error occurs. ** ** The error code stored in database p->db is overwritten with the return ** value in any case. */ static int vdbeUnbind(Vdbe *p, int i){ Mem *pVar; if( vdbeSafetyNotNull(p) ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(p->db->mutex); if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){ sqlite3Error(p->db, SQLITE_MISUSE); sqlite3_mutex_leave(p->db->mutex); sqlite3_log(SQLITE_MISUSE, "bind on a busy prepared statement: [%s]", p->zSql); return SQLITE_MISUSE_BKPT; } if( i<1 || i>p->nVar ){ sqlite3Error(p->db, SQLITE_RANGE); sqlite3_mutex_leave(p->db->mutex); return SQLITE_RANGE; } i--; pVar = &p->aVar[i]; sqlite3VdbeMemRelease(pVar); pVar->flags = MEM_Null; sqlite3Error(p->db, SQLITE_OK); /* If the bit corresponding to this variable in Vdbe.expmask is set, then ** binding a new value to this variable invalidates the current query plan. ** ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host ** parameter in the WHERE clause might influence the choice of query plan ** for a statement, then the statement will be automatically recompiled, ** as if there had been a schema change, on the first sqlite3_step() call ** following any change to the bindings of that parameter. */ if( p->isPrepareV2 && ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff) ){ p->expired = 1; } return SQLITE_OK; } /* ** Bind a text or BLOB value. */ static int bindText( sqlite3_stmt *pStmt, /* The statement to bind against */ int i, /* Index of the parameter to bind */ const void *zData, /* Pointer to the data to be bound */ int nData, /* Number of bytes of data to be bound */ void (*xDel)(void*), /* Destructor for the data */ u8 encoding /* Encoding for the data */ ){ Vdbe *p = (Vdbe *)pStmt; Mem *pVar; int rc; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ if( zData!=0 ){ pVar = &p->aVar[i-1]; rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); if( rc==SQLITE_OK && encoding!=0 ){ rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db)); } sqlite3Error(p->db, rc); rc = sqlite3ApiExit(p->db, rc); } sqlite3_mutex_leave(p->db->mutex); }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){ xDel((void*)zData); } return rc; } /* ** Bind a blob value to an SQL statement variable. */ SQLITE_API int sqlite3_bind_blob( sqlite3_stmt *pStmt, int i, const void *zData, int nData, void (*xDel)(void*) ){ #ifdef SQLITE_ENABLE_API_ARMOR if( nData<0 ) return SQLITE_MISUSE_BKPT; #endif return bindText(pStmt, i, zData, nData, xDel, 0); } SQLITE_API int sqlite3_bind_blob64( sqlite3_stmt *pStmt, int i, const void *zData, sqlite3_uint64 nData, void (*xDel)(void*) ){ assert( xDel!=SQLITE_DYNAMIC ); if( nData>0x7fffffff ){ return invokeValueDestructor(zData, xDel, 0); }else{ return bindText(pStmt, i, zData, (int)nData, xDel, 0); } } SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue); sqlite3_mutex_leave(p->db->mutex); } return rc; } SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){ return sqlite3_bind_int64(p, i, (i64)iValue); } SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue); sqlite3_mutex_leave(p->db->mutex); } return rc; } SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){ int rc; Vdbe *p = (Vdbe*)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ sqlite3_mutex_leave(p->db->mutex); } return rc; } SQLITE_API int sqlite3_bind_text( sqlite3_stmt *pStmt, int i, const char *zData, int nData, void (*xDel)(void*) ){ return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8); } SQLITE_API int sqlite3_bind_text64( sqlite3_stmt *pStmt, int i, const char *zData, sqlite3_uint64 nData, void (*xDel)(void*), unsigned char enc ){ assert( xDel!=SQLITE_DYNAMIC ); if( nData>0x7fffffff ){ return invokeValueDestructor(zData, xDel, 0); }else{ if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; return bindText(pStmt, i, zData, (int)nData, xDel, enc); } } #ifndef SQLITE_OMIT_UTF16 SQLITE_API int sqlite3_bind_text16( sqlite3_stmt *pStmt, int i, const void *zData, int nData, void (*xDel)(void*) ){ return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE); } #endif /* SQLITE_OMIT_UTF16 */ SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){ int rc; switch( sqlite3_value_type((sqlite3_value*)pValue) ){ case SQLITE_INTEGER: { rc = sqlite3_bind_int64(pStmt, i, pValue->u.i); break; } case SQLITE_FLOAT: { rc = sqlite3_bind_double(pStmt, i, pValue->u.r); break; } case SQLITE_BLOB: { if( pValue->flags & MEM_Zero ){ rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero); }else{ rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT); } break; } case SQLITE_TEXT: { rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT, pValue->enc); break; } default: { rc = sqlite3_bind_null(pStmt, i); break; } } return rc; } SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n); sqlite3_mutex_leave(p->db->mutex); } return rc; } SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){ int rc; Vdbe *p = (Vdbe *)pStmt; sqlite3_mutex_enter(p->db->mutex); if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){ rc = SQLITE_TOOBIG; }else{ assert( (n & 0x7FFFFFFF)==n ); rc = sqlite3_bind_zeroblob(pStmt, i, n); } rc = sqlite3ApiExit(p->db, rc); sqlite3_mutex_leave(p->db->mutex); return rc; } /* ** Return the number of wildcards that can be potentially bound to. ** This routine is added to support DBD::SQLite. */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; return p ? p->nVar : 0; } /* ** Return the name of a wildcard parameter. Return NULL if the index ** is out of range or if the wildcard is unnamed. ** ** The result is always UTF-8. */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){ Vdbe *p = (Vdbe*)pStmt; if( p==0 ) return 0; return sqlite3VListNumToName(p->pVList, i); } /* ** Given a wildcard parameter name, return the index of the variable ** with that name. If there is no variable with the given name, ** return 0. */ SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){ if( p==0 || zName==0 ) return 0; return sqlite3VListNameToNum(p->pVList, zName, nName); } SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){ return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName)); } /* ** Transfer all bindings from the first statement over to the second. */ SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ Vdbe *pFrom = (Vdbe*)pFromStmt; Vdbe *pTo = (Vdbe*)pToStmt; int i; assert( pTo->db==pFrom->db ); assert( pTo->nVar==pFrom->nVar ); sqlite3_mutex_enter(pTo->db->mutex); for(i=0; i<pFrom->nVar; i++){ sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); } sqlite3_mutex_leave(pTo->db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Deprecated external interface. Internal/core SQLite code ** should call sqlite3TransferBindings. ** ** It is misuse to call this routine with statements from different ** database connections. But as this is a deprecated interface, we ** will not bother to check for that condition. ** ** If the two statements contain a different number of bindings, then ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise ** SQLITE_OK is returned. */ SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ Vdbe *pFrom = (Vdbe*)pFromStmt; Vdbe *pTo = (Vdbe*)pToStmt; if( pFrom->nVar!=pTo->nVar ){ return SQLITE_ERROR; } if( pTo->isPrepareV2 && pTo->expmask ){ pTo->expired = 1; } if( pFrom->isPrepareV2 && pFrom->expmask ){ pFrom->expired = 1; } return sqlite3TransferBindings(pFromStmt, pToStmt); } #endif /* ** Return the sqlite3* database handle to which the prepared statement given ** in the argument belongs. This is the same database handle that was ** the first argument to the sqlite3_prepare() that was used to create ** the statement in the first place. */ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){ return pStmt ? ((Vdbe*)pStmt)->db : 0; } /* ** Return true if the prepared statement is guaranteed to not modify the ** database. */ SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){ return pStmt ? ((Vdbe*)pStmt)->readOnly : 1; } /* ** Return true if the prepared statement is in need of being reset. */ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){ Vdbe *v = (Vdbe*)pStmt; return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0; } /* ** Return a pointer to the next prepared statement after pStmt associated ** with database connection pDb. If pStmt is NULL, return the first ** prepared statement for the database connection. Return NULL if there ** are no more. */ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){ sqlite3_stmt *pNext; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(pDb) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(pDb->mutex); if( pStmt==0 ){ pNext = (sqlite3_stmt*)pDb->pVdbe; }else{ pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext; } sqlite3_mutex_leave(pDb->mutex); return pNext; } /* ** Return the value of a status counter for a prepared statement */ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){ Vdbe *pVdbe = (Vdbe*)pStmt; u32 v; #ifdef SQLITE_ENABLE_API_ARMOR if( !pStmt ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif v = pVdbe->aCounter[op]; if( resetFlag ) pVdbe->aCounter[op] = 0; return (int)v; } /* ** Return the SQL associated with a prepared statement */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){ Vdbe *p = (Vdbe *)pStmt; return p ? p->zSql : 0; } /* ** Return the SQL associated with a prepared statement with ** bound parameters expanded. Space to hold the returned string is ** obtained from sqlite3_malloc(). The caller is responsible for ** freeing the returned string by passing it to sqlite3_free(). ** ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of ** expanded bound parameters. */ SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){ #ifdef SQLITE_OMIT_TRACE return 0; #else char *z = 0; const char *zSql = sqlite3_sql(pStmt); if( zSql ){ Vdbe *p = (Vdbe *)pStmt; sqlite3_mutex_enter(p->db->mutex); z = sqlite3VdbeExpandSql(p, zSql); sqlite3_mutex_leave(p->db->mutex); } return z; #endif } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** Allocate and populate an UnpackedRecord structure based on the serialized ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure ** if successful, or a NULL pointer if an OOM error is encountered. */ static UnpackedRecord *vdbeUnpackRecord( KeyInfo *pKeyInfo, int nKey, const void *pKey ){ UnpackedRecord *pRet; /* Return value */ pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); if( pRet ){ memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1)); sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet); } return pRet; } /* ** This function is called from within a pre-update callback to retrieve ** a field of the row currently being updated or deleted. */ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){ PreUpdate *p = db->pPreUpdate; Mem *pMem; int rc = SQLITE_OK; /* Test that this call is being made from within an SQLITE_DELETE or ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */ if( !p || p->op==SQLITE_INSERT ){ rc = SQLITE_MISUSE_BKPT; goto preupdate_old_out; } if( p->pPk ){ iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx); } if( iIdx>=p->pCsr->nField || iIdx<0 ){ rc = SQLITE_RANGE; goto preupdate_old_out; } /* If the old.* record has not yet been loaded into memory, do so now. */ if( p->pUnpacked==0 ){ u32 nRec; u8 *aRec; nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor); aRec = sqlite3DbMallocRaw(db, nRec); if( !aRec ) goto preupdate_old_out; rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec); if( rc==SQLITE_OK ){ p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec); if( !p->pUnpacked ) rc = SQLITE_NOMEM; } if( rc!=SQLITE_OK ){ sqlite3DbFree(db, aRec); goto preupdate_old_out; } p->aRecord = aRec; } pMem = *ppValue = &p->pUnpacked->aMem[iIdx]; if( iIdx==p->pTab->iPKey ){ sqlite3VdbeMemSetInt64(pMem, p->iKey1); }else if( iIdx>=p->pUnpacked->nField ){ *ppValue = (sqlite3_value *)columnNullValue(); }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){ if( pMem->flags & MEM_Int ){ sqlite3VdbeMemRealify(pMem); } } preupdate_old_out: sqlite3Error(db, rc); return sqlite3ApiExit(db, rc); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** This function is called from within a pre-update callback to retrieve ** the number of columns in the row being updated, deleted or inserted. */ SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){ PreUpdate *p = db->pPreUpdate; return (p ? p->keyinfo.nField : 0); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** This function is designed to be called from within a pre-update callback ** only. It returns zero if the change that caused the callback was made ** immediately by a user SQL statement. Or, if the change was made by a ** trigger program, it returns the number of trigger programs currently ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a ** top-level trigger etc.). ** ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL ** or SET DEFAULT action is considered a trigger. */ SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){ PreUpdate *p = db->pPreUpdate; return (p ? p->v->nFrame : 0); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** This function is called from within a pre-update callback to retrieve ** a field of the row currently being updated or inserted. */ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){ PreUpdate *p = db->pPreUpdate; int rc = SQLITE_OK; Mem *pMem; if( !p || p->op==SQLITE_DELETE ){ rc = SQLITE_MISUSE_BKPT; goto preupdate_new_out; } if( p->pPk && p->op!=SQLITE_UPDATE ){ iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx); } if( iIdx>=p->pCsr->nField || iIdx<0 ){ rc = SQLITE_RANGE; goto preupdate_new_out; } if( p->op==SQLITE_INSERT ){ /* For an INSERT, memory cell p->iNewReg contains the serialized record ** that is being inserted. Deserialize it. */ UnpackedRecord *pUnpack = p->pNewUnpacked; if( !pUnpack ){ Mem *pData = &p->v->aMem[p->iNewReg]; rc = ExpandBlob(pData); if( rc!=SQLITE_OK ) goto preupdate_new_out; pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z); if( !pUnpack ){ rc = SQLITE_NOMEM; goto preupdate_new_out; } p->pNewUnpacked = pUnpack; } pMem = &pUnpack->aMem[iIdx]; if( iIdx==p->pTab->iPKey ){ sqlite3VdbeMemSetInt64(pMem, p->iKey2); }else if( iIdx>=pUnpack->nField ){ pMem = (sqlite3_value *)columnNullValue(); } }else{ /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required ** value. Make a copy of the cell contents and return a pointer to it. ** It is not safe to return a pointer to the memory cell itself as the ** caller may modify the value text encoding. */ assert( p->op==SQLITE_UPDATE ); if( !p->aNew ){ p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField); if( !p->aNew ){ rc = SQLITE_NOMEM; goto preupdate_new_out; } } assert( iIdx>=0 && iIdx<p->pCsr->nField ); pMem = &p->aNew[iIdx]; if( pMem->flags==0 ){ if( iIdx==p->pTab->iPKey ){ sqlite3VdbeMemSetInt64(pMem, p->iKey2); }else{ rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]); if( rc!=SQLITE_OK ) goto preupdate_new_out; } } } *ppValue = pMem; preupdate_new_out: sqlite3Error(db, rc); return sqlite3ApiExit(db, rc); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS /* ** Return status data for a single loop within query pStmt. */ SQLITE_API int sqlite3_stmt_scanstatus( sqlite3_stmt *pStmt, /* Prepared statement being queried */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Which metric to return */ void *pOut /* OUT: Write the answer here */ ){ Vdbe *p = (Vdbe*)pStmt; ScanStatus *pScan; if( idx<0 || idx>=p->nScan ) return 1; pScan = &p->aScan[idx]; switch( iScanStatusOp ){ case SQLITE_SCANSTAT_NLOOP: { *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop]; break; } case SQLITE_SCANSTAT_NVISIT: { *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit]; break; } case SQLITE_SCANSTAT_EST: { double r = 1.0; LogEst x = pScan->nEst; while( x<100 ){ x += 10; r *= 0.5; } *(double*)pOut = r*sqlite3LogEstToInt(x); break; } case SQLITE_SCANSTAT_NAME: { *(const char**)pOut = pScan->zName; break; } case SQLITE_SCANSTAT_EXPLAIN: { if( pScan->addrExplain ){ *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z; }else{ *(const char**)pOut = 0; } break; } case SQLITE_SCANSTAT_SELECTID: { if( pScan->addrExplain ){ *(int*)pOut = p->aOp[ pScan->addrExplain ].p1; }else{ *(int*)pOut = -1; } break; } default: { return 1; } } return 0; } /* ** Zero all counters associated with the sqlite3_stmt_scanstatus() data. */ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; memset(p->anExec, 0, p->nOp * sizeof(i64)); } #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */ /************** End of vdbeapi.c *********************************************/ /************** Begin file vdbetrace.c ***************************************/ /* ** 2009 November 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to insert the values of host parameters ** (aka "wildcards") into the SQL text output by sqlite3_trace(). ** ** The Vdbe parse-tree explainer is also found here. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #ifndef SQLITE_OMIT_TRACE /* ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of ** bytes in this text up to but excluding the first character in ** a host parameter. If the text contains no host parameters, return ** the total number of bytes in the text. */ static int findNextHostParameter(const char *zSql, int *pnToken){ int tokenType; int nTotal = 0; int n; *pnToken = 0; while( zSql[0] ){ n = sqlite3GetToken((u8*)zSql, &tokenType); assert( n>0 && tokenType!=TK_ILLEGAL ); if( tokenType==TK_VARIABLE ){ *pnToken = n; break; } nTotal += n; zSql += n; } return nTotal; } /* ** This function returns a pointer to a nul-terminated string in memory ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the ** string contains a copy of zRawSql but with host parameters expanded to ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, ** then the returned string holds a copy of zRawSql with "-- " prepended ** to each line of text. ** ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then ** then long strings and blobs are truncated to that many bytes. This ** can be used to prevent unreasonably large trace strings when dealing ** with large (multi-megabyte) strings and blobs. ** ** The calling function is responsible for making sure the memory returned ** is eventually freed. ** ** ALGORITHM: Scan the input string looking for host parameters in any of ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within ** string literals, quoted identifier names, and comments. For text forms, ** the host parameter index is found by scanning the prepared ** statement for the corresponding OP_Variable opcode. Once the host ** parameter index is known, locate the value in p->aVar[]. Then render ** the value as a literal in place of the host parameter name. */ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( Vdbe *p, /* The prepared statement being evaluated */ const char *zRawSql /* Raw text of the SQL statement */ ){ sqlite3 *db; /* The database connection */ int idx = 0; /* Index of a host parameter */ int nextIndex = 1; /* Index of next ? host parameter */ int n; /* Length of a token prefix */ int nToken; /* Length of the parameter token */ int i; /* Loop counter */ Mem *pVar; /* Value of a host parameter */ StrAccum out; /* Accumulate the output here */ #ifndef SQLITE_OMIT_UTF16 Mem utf8; /* Used to convert UTF16 parameters into UTF8 for display */ #endif char zBase[100]; /* Initial working space */ db = p->db; sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), db->aLimit[SQLITE_LIMIT_LENGTH]); if( db->nVdbeExec>1 ){ while( *zRawSql ){ const char *zStart = zRawSql; while( *(zRawSql++)!='\n' && *zRawSql ); sqlite3StrAccumAppend(&out, "-- ", 3); assert( (zRawSql - zStart) > 0 ); sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart)); } }else if( p->nVar==0 ){ sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql)); }else{ while( zRawSql[0] ){ n = findNextHostParameter(zRawSql, &nToken); assert( n>0 ); sqlite3StrAccumAppend(&out, zRawSql, n); zRawSql += n; assert( zRawSql[0] || nToken==0 ); if( nToken==0 ) break; if( zRawSql[0]=='?' ){ if( nToken>1 ){ assert( sqlite3Isdigit(zRawSql[1]) ); sqlite3GetInt32(&zRawSql[1], &idx); }else{ idx = nextIndex; } }else{ assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' || zRawSql[0]=='#' ); testcase( zRawSql[0]==':' ); testcase( zRawSql[0]=='$' ); testcase( zRawSql[0]=='@' ); testcase( zRawSql[0]=='#' ); idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken); assert( idx>0 ); } zRawSql += nToken; nextIndex = idx + 1; assert( idx>0 && idx<=p->nVar ); pVar = &p->aVar[idx-1]; if( pVar->flags & MEM_Null ){ sqlite3StrAccumAppend(&out, "NULL", 4); }else if( pVar->flags & MEM_Int ){ sqlite3XPrintf(&out, "%lld", pVar->u.i); }else if( pVar->flags & MEM_Real ){ sqlite3XPrintf(&out, "%!.15g", pVar->u.r); }else if( pVar->flags & MEM_Str ){ int nOut; /* Number of bytes of the string text to include in output */ #ifndef SQLITE_OMIT_UTF16 u8 enc = ENC(db); if( enc!=SQLITE_UTF8 ){ memset(&utf8, 0, sizeof(utf8)); utf8.db = db; sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC); if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){ out.accError = STRACCUM_NOMEM; out.nAlloc = 0; } pVar = &utf8; } #endif nOut = pVar->n; #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut>SQLITE_TRACE_SIZE_LIMIT ){ nOut = SQLITE_TRACE_SIZE_LIMIT; while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; } } #endif sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z); #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut<pVar->n ){ sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); } #endif #ifndef SQLITE_OMIT_UTF16 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8); #endif }else if( pVar->flags & MEM_Zero ){ sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero); }else{ int nOut; /* Number of bytes of the blob to include in output */ assert( pVar->flags & MEM_Blob ); sqlite3StrAccumAppend(&out, "x'", 2); nOut = pVar->n; #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT; #endif for(i=0; i<nOut; i++){ sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff); } sqlite3StrAccumAppend(&out, "'", 1); #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut<pVar->n ){ sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); } #endif } } } if( out.accError ) sqlite3StrAccumReset(&out); return sqlite3StrAccumFinish(&out); } #endif /* #ifndef SQLITE_OMIT_TRACE */ /************** End of vdbetrace.c *******************************************/ /************** Begin file vdbe.c ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** The code in this file implements the function that runs the ** bytecode of a prepared statement. ** ** Various scripts scan this source file in order to generate HTML ** documentation, headers files, or other derived files. The formatting ** of the code in this file is, therefore, important. See other comments ** in this file for details. If in doubt, do not deviate from existing ** commenting and indentation practices when changing or adding code. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ /* ** Invoke this macro on memory cells just prior to changing the ** value of the cell. This macro verifies that shallow copies are ** not misused. A shallow copy of a string or blob just copies a ** pointer to the string or blob, not the content. If the original ** is changed while the copy is still in use, the string or blob might ** be changed out from under the copy. This macro verifies that nothing ** like that ever happens. */ #ifdef SQLITE_DEBUG # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M) #else # define memAboutToChange(P,M) #endif /* ** The following global variable is incremented every time a cursor ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test ** procedures use this information to make sure that indices are ** working correctly. This variable has no function other than to ** help verify the correct operation of the library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_search_count = 0; #endif /* ** When this global variable is positive, it gets decremented once before ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted ** field of the sqlite3 structure is set in order to simulate an interrupt. ** ** This facility is used for testing purposes only. It does not function ** in an ordinary build. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_interrupt_count = 0; #endif /* ** The next global variable is incremented each type the OP_Sort opcode ** is executed. The test procedures use this information to make sure that ** sorting is occurring or not occurring at appropriate times. This variable ** has no function other than to help verify the correct operation of the ** library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_sort_count = 0; #endif /* ** The next global variable records the size of the largest MEM_Blob ** or MEM_Str that has been used by a VDBE opcode. The test procedures ** use this information to make sure that the zero-blob functionality ** is working correctly. This variable has no function other than to ** help verify the correct operation of the library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_max_blobsize = 0; static void updateMaxBlobsize(Mem *p){ if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ sqlite3_max_blobsize = p->n; } } #endif /* ** This macro evaluates to true if either the update hook or the preupdate ** hook are enabled for database connect DB. */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback) #else # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback) #endif /* ** The next global variable is incremented each time the OP_Found opcode ** is executed. This is used to test whether or not the foreign key ** operation implemented using OP_FkIsZero is working. This variable ** has no function other than to help verify the correct operation of the ** library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_found_count = 0; #endif /* ** Test a register to see if it exceeds the current maximum blob size. ** If it does, record the new maximum blob size. */ #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE) # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) #else # define UPDATE_MAX_BLOBSIZE(P) #endif /* ** Invoke the VDBE coverage callback, if that callback is defined. This ** feature is used for test suite validation only and does not appear an ** production builds. ** ** M is an integer, 2 or 3, that indices how many different ways the ** branch can go. It is usually 2. "I" is the direction the branch ** goes. 0 means falls through. 1 means branch is taken. 2 means the ** second alternative branch is taken. ** ** iSrcLine is the source code line (from the __LINE__ macro) that ** generated the VDBE instruction. This instrumentation assumes that all ** source code is in a single file (the amalgamation). Special values 1 ** and 2 for the iSrcLine parameter mean that this particular branch is ** always taken or never taken, respectively. */ #if !defined(SQLITE_VDBE_COVERAGE) # define VdbeBranchTaken(I,M) #else # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M) static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){ if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){ M = iSrcLine; /* Assert the truth of VdbeCoverageAlwaysTaken() and ** VdbeCoverageNeverTaken() */ assert( (M & I)==I ); }else{ if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/ sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg, iSrcLine,I,M); } } #endif /* ** Convert the given register into a string if it isn't one ** already. Return non-zero if a malloc() fails. */ #define Stringify(P, enc) \ if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \ { goto no_mem; } /* ** An ephemeral string value (signified by the MEM_Ephem flag) contains ** a pointer to a dynamically allocated string where some other entity ** is responsible for deallocating that string. Because the register ** does not control the string, it might be deleted without the register ** knowing it. ** ** This routine converts an ephemeral string into a dynamically allocated ** string that the register itself controls. In other words, it ** converts an MEM_Ephem string into a string with P.z==P.zMalloc. */ #define Deephemeralize(P) \ if( ((P)->flags&MEM_Ephem)!=0 \ && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} /* Return true if the cursor was opened using the OP_OpenSorter opcode. */ #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER) /* ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL ** if we run out of memory. */ static VdbeCursor *allocateCursor( Vdbe *p, /* The virtual machine */ int iCur, /* Index of the new VdbeCursor */ int nField, /* Number of fields in the table or index */ int iDb, /* Database the cursor belongs to, or -1 */ u8 eCurType /* Type of the new cursor */ ){ /* Find the memory cell that will be used to store the blob of memory ** required for this VdbeCursor structure. It is convenient to use a ** vdbe memory cell to manage the memory allocation required for a ** VdbeCursor structure for the following reasons: ** ** * Sometimes cursor numbers are used for a couple of different ** purposes in a vdbe program. The different uses might require ** different sized allocations. Memory cells provide growable ** allocations. ** ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can ** be freed lazily via the sqlite3_release_memory() API. This ** minimizes the number of malloc calls made by the system. ** ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from ** the top of the register space. Cursor 1 is at Mem[p->nMem-1]. ** Cursor 2 is at Mem[p->nMem-2]. And so forth. */ Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem; int nByte; VdbeCursor *pCx = 0; nByte = ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0); assert( iCur>=0 && iCur<p->nCursor ); if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/ sqlite3VdbeFreeCursor(p, p->apCsr[iCur]); p->apCsr[iCur] = 0; } if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){ p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z; memset(pCx, 0, offsetof(VdbeCursor,pAltCursor)); pCx->eCurType = eCurType; pCx->iDb = iDb; pCx->nField = nField; pCx->aOffset = &pCx->aType[nField]; if( eCurType==CURTYPE_BTREE ){ pCx->uc.pCursor = (BtCursor*) &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField]; sqlite3BtreeCursorZero(pCx->uc.pCursor); } } return pCx; } /* ** Try to convert a value into a numeric representation if we can ** do so without loss of information. In other words, if the string ** looks like a number, convert it into a number. If it does not ** look like a number, leave it alone. ** ** If the bTryForInt flag is true, then extra effort is made to give ** an integer representation. Strings that look like floating point ** values but which have no fractional component (example: '48.00') ** will have a MEM_Int representation when bTryForInt is true. ** ** If bTryForInt is false, then if the input string contains a decimal ** point or exponential notation, the result is only MEM_Real, even ** if there is an exact integer representation of the quantity. */ static void applyNumericAffinity(Mem *pRec, int bTryForInt){ double rValue; i64 iValue; u8 enc = pRec->enc; assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str ); if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return; if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){ pRec->u.i = iValue; pRec->flags |= MEM_Int; }else{ pRec->u.r = rValue; pRec->flags |= MEM_Real; if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec); } } /* ** Processing is determine by the affinity parameter: ** ** SQLITE_AFF_INTEGER: ** SQLITE_AFF_REAL: ** SQLITE_AFF_NUMERIC: ** Try to convert pRec to an integer representation or a ** floating-point representation if an integer representation ** is not possible. Note that the integer representation is ** always preferred, even if the affinity is REAL, because ** an integer representation is more space efficient on disk. ** ** SQLITE_AFF_TEXT: ** Convert pRec to a text representation. ** ** SQLITE_AFF_BLOB: ** No-op. pRec is unchanged. */ static void applyAffinity( Mem *pRec, /* The value to apply affinity to */ char affinity, /* The affinity to be applied */ u8 enc /* Use this text encoding */ ){ if( affinity>=SQLITE_AFF_NUMERIC ){ assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL || affinity==SQLITE_AFF_NUMERIC ); if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/ if( (pRec->flags & MEM_Real)==0 ){ if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1); }else{ sqlite3VdbeIntegerAffinity(pRec); } } }else if( affinity==SQLITE_AFF_TEXT ){ /* Only attempt the conversion to TEXT if there is an integer or real ** representation (blob and NULL do not get converted) but no string ** representation. It would be harmless to repeat the conversion if ** there is already a string rep, but it is pointless to waste those ** CPU cycles. */ if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/ if( (pRec->flags&(MEM_Real|MEM_Int)) ){ sqlite3VdbeMemStringify(pRec, enc, 1); } } pRec->flags &= ~(MEM_Real|MEM_Int); } } /* ** Try to convert the type of a function argument or a result column ** into a numeric representation. Use either INTEGER or REAL whichever ** is appropriate. But only do the conversion if it is possible without ** loss of information and return the revised type of the argument. */ SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){ int eType = sqlite3_value_type(pVal); if( eType==SQLITE_TEXT ){ Mem *pMem = (Mem*)pVal; applyNumericAffinity(pMem, 0); eType = sqlite3_value_type(pVal); } return eType; } /* ** Exported version of applyAffinity(). This one works on sqlite3_value*, ** not the internal Mem* type. */ SQLITE_PRIVATE void sqlite3ValueApplyAffinity( sqlite3_value *pVal, u8 affinity, u8 enc ){ applyAffinity((Mem *)pVal, affinity, enc); } /* ** pMem currently only holds a string type (or maybe a BLOB that we can ** interpret as a string if we want to). Compute its corresponding ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields ** accordingly. */ static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){ assert( (pMem->flags & (MEM_Int|MEM_Real))==0 ); assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ); if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){ return 0; } if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){ return MEM_Int; } return MEM_Real; } /* ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or ** none. ** ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags. ** But it does set pMem->u.r and pMem->u.i appropriately. */ static u16 numericType(Mem *pMem){ if( pMem->flags & (MEM_Int|MEM_Real) ){ return pMem->flags & (MEM_Int|MEM_Real); } if( pMem->flags & (MEM_Str|MEM_Blob) ){ return computeNumericType(pMem); } return 0; } #ifdef SQLITE_DEBUG /* ** Write a nice string representation of the contents of cell pMem ** into buffer zBuf, length nBuf. */ SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){ char *zCsr = zBuf; int f = pMem->flags; static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"}; if( f&MEM_Blob ){ int i; char c; if( f & MEM_Dyn ){ c = 'z'; assert( (f & (MEM_Static|MEM_Ephem))==0 ); }else if( f & MEM_Static ){ c = 't'; assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); }else if( f & MEM_Ephem ){ c = 'e'; assert( (f & (MEM_Static|MEM_Dyn))==0 ); }else{ c = 's'; } sqlite3_snprintf(100, zCsr, "%c", c); zCsr += sqlite3Strlen30(zCsr); sqlite3_snprintf(100, zCsr, "%d[", pMem->n); zCsr += sqlite3Strlen30(zCsr); for(i=0; i<16 && i<pMem->n; i++){ sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF)); zCsr += sqlite3Strlen30(zCsr); } for(i=0; i<16 && i<pMem->n; i++){ char z = pMem->z[i]; if( z<32 || z>126 ) *zCsr++ = '.'; else *zCsr++ = z; } sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]); zCsr += sqlite3Strlen30(zCsr); if( f & MEM_Zero ){ sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero); zCsr += sqlite3Strlen30(zCsr); } *zCsr = '\0'; }else if( f & MEM_Str ){ int j, k; zBuf[0] = ' '; if( f & MEM_Dyn ){ zBuf[1] = 'z'; assert( (f & (MEM_Static|MEM_Ephem))==0 ); }else if( f & MEM_Static ){ zBuf[1] = 't'; assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); }else if( f & MEM_Ephem ){ zBuf[1] = 'e'; assert( (f & (MEM_Static|MEM_Dyn))==0 ); }else{ zBuf[1] = 's'; } k = 2; sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n); k += sqlite3Strlen30(&zBuf[k]); zBuf[k++] = '['; for(j=0; j<15 && j<pMem->n; j++){ u8 c = pMem->z[j]; if( c>=0x20 && c<0x7f ){ zBuf[k++] = c; }else{ zBuf[k++] = '.'; } } zBuf[k++] = ']'; sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]); k += sqlite3Strlen30(&zBuf[k]); zBuf[k++] = 0; } } #endif #ifdef SQLITE_DEBUG /* ** Print the value of a register for tracing purposes: */ static void memTracePrint(Mem *p){ if( p->flags & MEM_Undefined ){ printf(" undefined"); }else if( p->flags & MEM_Null ){ printf(" NULL"); }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ printf(" si:%lld", p->u.i); }else if( p->flags & MEM_Int ){ printf(" i:%lld", p->u.i); #ifndef SQLITE_OMIT_FLOATING_POINT }else if( p->flags & MEM_Real ){ printf(" r:%g", p->u.r); #endif }else if( p->flags & MEM_RowSet ){ printf(" (rowset)"); }else{ char zBuf[200]; sqlite3VdbeMemPrettyPrint(p, zBuf); printf(" %s", zBuf); } if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype); } static void registerTrace(int iReg, Mem *p){ printf("REG[%d] = ", iReg); memTracePrint(p); printf("\n"); } #endif #ifdef SQLITE_DEBUG # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M) #else # define REGISTER_TRACE(R,M) #endif #ifdef VDBE_PROFILE /* ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ /************** Include hwtime.h in the middle of vdbe.c *********************/ /************** Begin file hwtime.h ******************************************/ /* ** 2008 May 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" ** counters for x86 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H /* ** The following routine only works on pentium-class (or newer) processors. ** It uses the RDTSC opcode to read the cycle count value out of the ** processor and returns that value. This can be used for high-res ** profiling. */ #if (defined(__GNUC__) || defined(_MSC_VER)) && \ (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; } #elif defined(_MSC_VER) __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX } } #endif #elif (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } #elif (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ 1: mftbu %1\n\ mftb %L0\n\ mftbu %0\n\ cmpw %0,%1\n\ bne 1b" : "=r" (retval), "=r" (junk)); return retval; } #else #error Need implementation of sqlite3Hwtime() for your platform. /* ** To compile without implementing sqlite3Hwtime() for your platform, ** you can remove the above #error and use the following ** stub function. You will lose timing support for many ** of the debugging and testing utilities, but it should at ** least compile and run. */ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif #endif /* !defined(SQLITE_HWTIME_H) */ /************** End of hwtime.h **********************************************/ /************** Continuing where we left off in vdbe.c ***********************/ #endif #ifndef NDEBUG /* ** This function is only called from within an assert() expression. It ** checks that the sqlite3.nTransaction variable is correctly set to ** the number of non-transaction savepoints currently in the ** linked list starting at sqlite3.pSavepoint. ** ** Usage: ** ** assert( checkSavepointCount(db) ); */ static int checkSavepointCount(sqlite3 *db){ int n = 0; Savepoint *p; for(p=db->pSavepoint; p; p=p->pNext) n++; assert( n==(db->nSavepoint + db->isTransactionSavepoint) ); return 1; } #endif /* ** Return the register of pOp->p2 after first preparing it to be ** overwritten with an integer value. */ static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){ sqlite3VdbeMemSetNull(pOut); pOut->flags = MEM_Int; return pOut; } static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){ Mem *pOut; assert( pOp->p2>0 ); assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); pOut = &p->aMem[pOp->p2]; memAboutToChange(p, pOut); if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/ return out2PrereleaseWithClear(pOut); }else{ pOut->flags = MEM_Int; return pOut; } } /* ** Execute as much of a VDBE program as we can. ** This is the core of sqlite3_step(). */ SQLITE_PRIVATE int sqlite3VdbeExec( Vdbe *p /* The VDBE */ ){ Op *aOp = p->aOp; /* Copy of p->aOp */ Op *pOp = aOp; /* Current operation */ #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) Op *pOrigOp; /* Value of pOp at the top of the loop */ #endif #ifdef SQLITE_DEBUG int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */ #endif int rc = SQLITE_OK; /* Value to return */ sqlite3 *db = p->db; /* The database */ u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */ u8 encoding = ENC(db); /* The database encoding */ int iCompare = 0; /* Result of last comparison */ unsigned nVmStep = 0; /* Number of virtual machine steps */ #ifndef SQLITE_OMIT_PROGRESS_CALLBACK unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */ #endif Mem *aMem = p->aMem; /* Copy of p->aMem */ Mem *pIn1 = 0; /* 1st input operand */ Mem *pIn2 = 0; /* 2nd input operand */ Mem *pIn3 = 0; /* 3rd input operand */ Mem *pOut = 0; /* Output operand */ #ifdef VDBE_PROFILE u64 start; /* CPU clock count at start of opcode */ #endif /*** INSERT STACK UNION HERE ***/ assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ sqlite3VdbeEnter(p); if( p->rc==SQLITE_NOMEM ){ /* This happens if a malloc() inside a call to sqlite3_column_text() or ** sqlite3_column_text16() failed. */ goto no_mem; } assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY ); assert( p->bIsReader || p->readOnly!=0 ); p->iCurrentTime = 0; assert( p->explain==0 ); p->pResultSet = 0; db->busyHandler.nBusy = 0; if( db->u1.isInterrupted ) goto abort_due_to_interrupt; sqlite3VdbeIOTraceSql(p); #ifndef SQLITE_OMIT_PROGRESS_CALLBACK if( db->xProgress ){ u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP]; assert( 0 < db->nProgressOps ); nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps); } #endif #ifdef SQLITE_DEBUG sqlite3BeginBenignMalloc(); if( p->pc==0 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0 ){ int i; int once = 1; sqlite3VdbePrintSql(p); if( p->db->flags & SQLITE_VdbeListing ){ printf("VDBE Program Listing:\n"); for(i=0; i<p->nOp; i++){ sqlite3VdbePrintOp(stdout, i, &aOp[i]); } } if( p->db->flags & SQLITE_VdbeEQP ){ for(i=0; i<p->nOp; i++){ if( aOp[i].opcode==OP_Explain ){ if( once ) printf("VDBE Query Plan:\n"); printf("%s\n", aOp[i].p4.z); once = 0; } } } if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n"); } sqlite3EndBenignMalloc(); #endif for(pOp=&aOp[p->pc]; 1; pOp++){ /* Errors are detected by individual opcodes, with an immediate ** jumps to abort_due_to_error. */ assert( rc==SQLITE_OK ); assert( pOp>=aOp && pOp<&aOp[p->nOp]); #ifdef VDBE_PROFILE start = sqlite3Hwtime(); #endif nVmStep++; #ifdef SQLITE_ENABLE_STMT_SCANSTATUS if( p->anExec ) p->anExec[(int)(pOp-aOp)]++; #endif /* Only allow tracing if SQLITE_DEBUG is defined. */ #ifdef SQLITE_DEBUG if( db->flags & SQLITE_VdbeTrace ){ sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp); } #endif /* Check to see if we need to simulate an interrupt. This only happens ** if we have a special test build. */ #ifdef SQLITE_TEST if( sqlite3_interrupt_count>0 ){ sqlite3_interrupt_count--; if( sqlite3_interrupt_count==0 ){ sqlite3_interrupt(db); } } #endif /* Sanity checking on other operands */ #ifdef SQLITE_DEBUG { u8 opProperty = sqlite3OpcodeProperty[pOp->opcode]; if( (opProperty & OPFLG_IN1)!=0 ){ assert( pOp->p1>0 ); assert( pOp->p1<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p1]) ); assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) ); REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]); } if( (opProperty & OPFLG_IN2)!=0 ){ assert( pOp->p2>0 ); assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p2]) ); assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) ); REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]); } if( (opProperty & OPFLG_IN3)!=0 ){ assert( pOp->p3>0 ); assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p3]) ); assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) ); REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]); } if( (opProperty & OPFLG_OUT2)!=0 ){ assert( pOp->p2>0 ); assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); memAboutToChange(p, &aMem[pOp->p2]); } if( (opProperty & OPFLG_OUT3)!=0 ){ assert( pOp->p3>0 ); assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); memAboutToChange(p, &aMem[pOp->p3]); } } #endif #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) pOrigOp = pOp; #endif switch( pOp->opcode ){ /***************************************************************************** ** What follows is a massive switch statement where each case implements a ** separate instruction in the virtual machine. If we follow the usual ** indentation conventions, each case should be indented by 6 spaces. But ** that is a lot of wasted space on the left margin. So the code within ** the switch statement will break with convention and be flush-left. Another ** big comment (similar to this one) will mark the point in the code where ** we transition back to normal indentation. ** ** The formatting of each case is important. The makefile for SQLite ** generates two C files "opcodes.h" and "opcodes.c" by scanning this ** file looking for lines that begin with "case OP_". The opcodes.h files ** will be filled with #defines that give unique integer values to each ** opcode and the opcodes.c file is filled with an array of strings where ** each string is the symbolic name for the corresponding opcode. If the ** case statement is followed by a comment of the form "/# same as ... #/" ** that comment is used to determine the particular value of the opcode. ** ** Other keywords in the comment that follows each case are used to ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[]. ** Keywords include: in1, in2, in3, out2, out3. See ** the mkopcodeh.awk script for additional information. ** ** Documentation about VDBE opcodes is generated by scanning this file ** for lines of that contain "Opcode:". That line and all subsequent ** comment lines are used in the generation of the opcode.html documentation ** file. ** ** SUMMARY: ** ** Formatting is important to scripts that scan this file. ** Do not deviate from the formatting style currently in use. ** *****************************************************************************/ /* Opcode: Goto * P2 * * * ** ** An unconditional jump to address P2. ** The next instruction executed will be ** the one at index P2 from the beginning of ** the program. ** ** The P1 parameter is not actually used by this opcode. However, it ** is sometimes set to 1 instead of 0 as a hint to the command-line shell ** that this Goto is the bottom of a loop and that the lines from P2 down ** to the current line should be indented for EXPLAIN output. */ case OP_Goto: { /* jump */ jump_to_p2_and_check_for_interrupt: pOp = &aOp[pOp->p2 - 1]; /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev, ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon ** completion. Check to see if sqlite3_interrupt() has been called ** or if the progress callback needs to be invoked. ** ** This code uses unstructured "goto" statements and does not look clean. ** But that is not due to sloppy coding habits. The code is written this ** way for performance, to avoid having to run the interrupt and progress ** checks on every opcode. This helps sqlite3_step() to run about 1.5% ** faster according to "valgrind --tool=cachegrind" */ check_for_interrupt: if( db->u1.isInterrupted ) goto abort_due_to_interrupt; #ifndef SQLITE_OMIT_PROGRESS_CALLBACK /* Call the progress callback if it is configured and the required number ** of VDBE ops have been executed (either since this invocation of ** sqlite3VdbeExec() or since last time the progress callback was called). ** If the progress callback returns non-zero, exit the virtual machine with ** a return code SQLITE_ABORT. */ if( db->xProgress!=0 && nVmStep>=nProgressLimit ){ assert( db->nProgressOps!=0 ); nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps); if( db->xProgress(db->pProgressArg) ){ rc = SQLITE_INTERRUPT; goto abort_due_to_error; } } #endif break; } /* Opcode: Gosub P1 P2 * * * ** ** Write the current address onto register P1 ** and then jump to address P2. */ case OP_Gosub: { /* jump */ assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); pIn1 = &aMem[pOp->p1]; assert( VdbeMemDynamic(pIn1)==0 ); memAboutToChange(p, pIn1); pIn1->flags = MEM_Int; pIn1->u.i = (int)(pOp-aOp); REGISTER_TRACE(pOp->p1, pIn1); /* Most jump operations do a goto to this spot in order to update ** the pOp pointer. */ jump_to_p2: pOp = &aOp[pOp->p2 - 1]; break; } /* Opcode: Return P1 * * * * ** ** Jump to the next instruction after the address in register P1. After ** the jump, register P1 becomes undefined. */ case OP_Return: { /* in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags==MEM_Int ); pOp = &aOp[pIn1->u.i]; pIn1->flags = MEM_Undefined; break; } /* Opcode: InitCoroutine P1 P2 P3 * * ** ** Set up register P1 so that it will Yield to the coroutine ** located at address P3. ** ** If P2!=0 then the coroutine implementation immediately follows ** this opcode. So jump over the coroutine implementation to ** address P2. ** ** See also: EndCoroutine */ case OP_InitCoroutine: { /* jump */ assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); assert( pOp->p2>=0 && pOp->p2<p->nOp ); assert( pOp->p3>=0 && pOp->p3<p->nOp ); pOut = &aMem[pOp->p1]; assert( !VdbeMemDynamic(pOut) ); pOut->u.i = pOp->p3 - 1; pOut->flags = MEM_Int; if( pOp->p2 ) goto jump_to_p2; break; } /* Opcode: EndCoroutine P1 * * * * ** ** The instruction at the address in register P1 is a Yield. ** Jump to the P2 parameter of that Yield. ** After the jump, register P1 becomes undefined. ** ** See also: InitCoroutine */ case OP_EndCoroutine: { /* in1 */ VdbeOp *pCaller; pIn1 = &aMem[pOp->p1]; assert( pIn1->flags==MEM_Int ); assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp ); pCaller = &aOp[pIn1->u.i]; assert( pCaller->opcode==OP_Yield ); assert( pCaller->p2>=0 && pCaller->p2<p->nOp ); pOp = &aOp[pCaller->p2 - 1]; pIn1->flags = MEM_Undefined; break; } /* Opcode: Yield P1 P2 * * * ** ** Swap the program counter with the value in register P1. This ** has the effect of yielding to a coroutine. ** ** If the coroutine that is launched by this instruction ends with ** Yield or Return then continue to the next instruction. But if ** the coroutine launched by this instruction ends with ** EndCoroutine, then jump to P2 rather than continuing with the ** next instruction. ** ** See also: InitCoroutine */ case OP_Yield: { /* in1, jump */ int pcDest; pIn1 = &aMem[pOp->p1]; assert( VdbeMemDynamic(pIn1)==0 ); pIn1->flags = MEM_Int; pcDest = (int)pIn1->u.i; pIn1->u.i = (int)(pOp - aOp); REGISTER_TRACE(pOp->p1, pIn1); pOp = &aOp[pcDest]; break; } /* Opcode: HaltIfNull P1 P2 P3 P4 P5 ** Synopsis: if r[P3]=null halt ** ** Check the value in register P3. If it is NULL then Halt using ** parameter P1, P2, and P4 as if this were a Halt instruction. If the ** value in register P3 is not NULL, then this routine is a no-op. ** The P5 parameter should be 1. */ case OP_HaltIfNull: { /* in3 */ pIn3 = &aMem[pOp->p3]; if( (pIn3->flags & MEM_Null)==0 ) break; /* Fall through into OP_Halt */ } /* Opcode: Halt P1 P2 * P4 P5 ** ** Exit immediately. All open cursors, etc are closed ** automatically. ** ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). ** For errors, it can be some other value. If P1!=0 then P2 will determine ** whether or not to rollback the current transaction. Do not rollback ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, ** then back out all changes that have occurred during this execution of the ** VDBE, but do not rollback the transaction. ** ** If P4 is not null then it is an error message string. ** ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string. ** ** 0: (no change) ** 1: NOT NULL contraint failed: P4 ** 2: UNIQUE constraint failed: P4 ** 3: CHECK constraint failed: P4 ** 4: FOREIGN KEY constraint failed: P4 ** ** If P5 is not zero and P4 is NULL, then everything after the ":" is ** omitted. ** ** There is an implied "Halt 0 0 0" instruction inserted at the very end of ** every program. So a jump past the last instruction of the program ** is the same as executing Halt. */ case OP_Halt: { VdbeFrame *pFrame; int pcx; pcx = (int)(pOp - aOp); if( pOp->p1==SQLITE_OK && p->pFrame ){ /* Halt the sub-program. Return control to the parent frame. */ pFrame = p->pFrame; p->pFrame = pFrame->pParent; p->nFrame--; sqlite3VdbeSetChanges(db, p->nChange); pcx = sqlite3VdbeFrameRestore(pFrame); if( pOp->p2==OE_Ignore ){ /* Instruction pcx is the OP_Program that invoked the sub-program ** currently being halted. If the p2 instruction of this OP_Halt ** instruction is set to OE_Ignore, then the sub-program is throwing ** an IGNORE exception. In this case jump to the address specified ** as the p2 of the calling OP_Program. */ pcx = p->aOp[pcx].p2-1; } aOp = p->aOp; aMem = p->aMem; pOp = &aOp[pcx]; break; } p->rc = pOp->p1; p->errorAction = (u8)pOp->p2; p->pc = pcx; assert( pOp->p5<=4 ); if( p->rc ){ if( pOp->p5 ){ static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK", "FOREIGN KEY" }; testcase( pOp->p5==1 ); testcase( pOp->p5==2 ); testcase( pOp->p5==3 ); testcase( pOp->p5==4 ); sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]); if( pOp->p4.z ){ p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z); } }else{ sqlite3VdbeError(p, "%s", pOp->p4.z); } sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg); } rc = sqlite3VdbeHalt(p); assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); if( rc==SQLITE_BUSY ){ p->rc = SQLITE_BUSY; }else{ assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ); assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 ); rc = p->rc ? SQLITE_ERROR : SQLITE_DONE; } goto vdbe_return; } /* Opcode: Integer P1 P2 * * * ** Synopsis: r[P2]=P1 ** ** The 32-bit integer value P1 is written into register P2. */ case OP_Integer: { /* out2 */ pOut = out2Prerelease(p, pOp); pOut->u.i = pOp->p1; break; } /* Opcode: Int64 * P2 * P4 * ** Synopsis: r[P2]=P4 ** ** P4 is a pointer to a 64-bit integer value. ** Write that value into register P2. */ case OP_Int64: { /* out2 */ pOut = out2Prerelease(p, pOp); assert( pOp->p4.pI64!=0 ); pOut->u.i = *pOp->p4.pI64; break; } #ifndef SQLITE_OMIT_FLOATING_POINT /* Opcode: Real * P2 * P4 * ** Synopsis: r[P2]=P4 ** ** P4 is a pointer to a 64-bit floating point value. ** Write that value into register P2. */ case OP_Real: { /* same as TK_FLOAT, out2 */ pOut = out2Prerelease(p, pOp); pOut->flags = MEM_Real; assert( !sqlite3IsNaN(*pOp->p4.pReal) ); pOut->u.r = *pOp->p4.pReal; break; } #endif /* Opcode: String8 * P2 * P4 * ** Synopsis: r[P2]='P4' ** ** P4 points to a nul terminated UTF-8 string. This opcode is transformed ** into a String opcode before it is executed for the first time. During ** this transformation, the length of string P4 is computed and stored ** as the P1 parameter. */ case OP_String8: { /* same as TK_STRING, out2 */ assert( pOp->p4.z!=0 ); pOut = out2Prerelease(p, pOp); pOp->opcode = OP_String; pOp->p1 = sqlite3Strlen30(pOp->p4.z); #ifndef SQLITE_OMIT_UTF16 if( encoding!=SQLITE_UTF8 ){ rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG ); if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z ); assert( VdbeMemDynamic(pOut)==0 ); pOut->szMalloc = 0; pOut->flags |= MEM_Static; if( pOp->p4type==P4_DYNAMIC ){ sqlite3DbFree(db, pOp->p4.z); } pOp->p4type = P4_DYNAMIC; pOp->p4.z = pOut->z; pOp->p1 = pOut->n; } testcase( rc==SQLITE_TOOBIG ); #endif if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } assert( rc==SQLITE_OK ); /* Fall through to the next case, OP_String */ } /* Opcode: String P1 P2 P3 P4 P5 ** Synopsis: r[P2]='P4' (len=P1) ** ** The string value P4 of length P1 (bytes) is stored in register P2. ** ** If P3 is not zero and the content of register P3 is equal to P5, then ** the datatype of the register P2 is converted to BLOB. The content is ** the same sequence of bytes, it is merely interpreted as a BLOB instead ** of a string, as if it had been CAST. In other words: ** ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB) */ case OP_String: { /* out2 */ assert( pOp->p4.z!=0 ); pOut = out2Prerelease(p, pOp); pOut->flags = MEM_Str|MEM_Static|MEM_Term; pOut->z = pOp->p4.z; pOut->n = pOp->p1; pOut->enc = encoding; UPDATE_MAX_BLOBSIZE(pOut); #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( pOp->p3>0 ){ assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); pIn3 = &aMem[pOp->p3]; assert( pIn3->flags & MEM_Int ); if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term; } #endif break; } /* Opcode: Null P1 P2 P3 * * ** Synopsis: r[P2..P3]=NULL ** ** Write a NULL into registers P2. If P3 greater than P2, then also write ** NULL into register P3 and every register in between P2 and P3. If P3 ** is less than P2 (typically P3 is zero) then only register P2 is ** set to NULL. ** ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that ** NULL values will not compare equal even if SQLITE_NULLEQ is set on ** OP_Ne or OP_Eq. */ case OP_Null: { /* out2 */ int cnt; u16 nullFlag; pOut = out2Prerelease(p, pOp); cnt = pOp->p3-pOp->p2; assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null; pOut->n = 0; while( cnt>0 ){ pOut++; memAboutToChange(p, pOut); sqlite3VdbeMemSetNull(pOut); pOut->flags = nullFlag; pOut->n = 0; cnt--; } break; } /* Opcode: SoftNull P1 * * * * ** Synopsis: r[P1]=NULL ** ** Set register P1 to have the value NULL as seen by the OP_MakeRecord ** instruction, but do not free any string or blob memory associated with ** the register, so that if the value was a string or blob that was ** previously copied using OP_SCopy, the copies will continue to be valid. */ case OP_SoftNull: { assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); pOut = &aMem[pOp->p1]; pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined; break; } /* Opcode: Blob P1 P2 * P4 * ** Synopsis: r[P2]=P4 (len=P1) ** ** P4 points to a blob of data P1 bytes long. Store this ** blob in register P2. */ case OP_Blob: { /* out2 */ assert( pOp->p1 <= SQLITE_MAX_LENGTH ); pOut = out2Prerelease(p, pOp); sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); pOut->enc = encoding; UPDATE_MAX_BLOBSIZE(pOut); break; } /* Opcode: Variable P1 P2 * P4 * ** Synopsis: r[P2]=parameter(P1,P4) ** ** Transfer the values of bound parameter P1 into register P2 ** ** If the parameter is named, then its name appears in P4. ** The P4 value is used by sqlite3_bind_parameter_name(). */ case OP_Variable: { /* out2 */ Mem *pVar; /* Value being transferred */ assert( pOp->p1>0 && pOp->p1<=p->nVar ); assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) ); pVar = &p->aVar[pOp->p1 - 1]; if( sqlite3VdbeMemTooBig(pVar) ){ goto too_big; } pOut = &aMem[pOp->p2]; sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static); UPDATE_MAX_BLOBSIZE(pOut); break; } /* Opcode: Move P1 P2 P3 * * ** Synopsis: r[P2@P3]=r[P1@P3] ** ** Move the P3 values in register P1..P1+P3-1 over into ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are ** left holding a NULL. It is an error for register ranges ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error ** for P3 to be less than 1. */ case OP_Move: { int n; /* Number of registers left to copy */ int p1; /* Register to copy from */ int p2; /* Register to copy to */ n = pOp->p3; p1 = pOp->p1; p2 = pOp->p2; assert( n>0 && p1>0 && p2>0 ); assert( p1+n<=p2 || p2+n<=p1 ); pIn1 = &aMem[p1]; pOut = &aMem[p2]; do{ assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] ); assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] ); assert( memIsValid(pIn1) ); memAboutToChange(p, pOut); sqlite3VdbeMemMove(pOut, pIn1); #ifdef SQLITE_DEBUG if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){ pOut->pScopyFrom += pOp->p2 - p1; } #endif Deephemeralize(pOut); REGISTER_TRACE(p2++, pOut); pIn1++; pOut++; }while( --n ); break; } /* Opcode: Copy P1 P2 P3 * * ** Synopsis: r[P2@P3+1]=r[P1@P3+1] ** ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3. ** ** This instruction makes a deep copy of the value. A duplicate ** is made of any string or blob constant. See also OP_SCopy. */ case OP_Copy: { int n; n = pOp->p3; pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; assert( pOut!=pIn1 ); while( 1 ){ sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); Deephemeralize(pOut); #ifdef SQLITE_DEBUG pOut->pScopyFrom = 0; #endif REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut); if( (n--)==0 ) break; pOut++; pIn1++; } break; } /* Opcode: SCopy P1 P2 * * * ** Synopsis: r[P2]=r[P1] ** ** Make a shallow copy of register P1 into register P2. ** ** This instruction makes a shallow copy of the value. If the value ** is a string or blob, then the copy is only a pointer to the ** original and hence if the original changes so will the copy. ** Worse, if the original is deallocated, the copy becomes invalid. ** Thus the program must guarantee that the original will not change ** during the lifetime of the copy. Use OP_Copy to make a complete ** copy. */ case OP_SCopy: { /* out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; assert( pOut!=pIn1 ); sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); #ifdef SQLITE_DEBUG if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1; #endif break; } /* Opcode: IntCopy P1 P2 * * * ** Synopsis: r[P2]=r[P1] ** ** Transfer the integer value held in register P1 into register P2. ** ** This is an optimized version of SCopy that works only for integer ** values. */ case OP_IntCopy: { /* out2 */ pIn1 = &aMem[pOp->p1]; assert( (pIn1->flags & MEM_Int)!=0 ); pOut = &aMem[pOp->p2]; sqlite3VdbeMemSetInt64(pOut, pIn1->u.i); break; } /* Opcode: ResultRow P1 P2 * * * ** Synopsis: output=r[P1@P2] ** ** The registers P1 through P1+P2-1 contain a single row of ** results. This opcode causes the sqlite3_step() call to terminate ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt ** structure to provide access to the r(P1)..r(P1+P2-1) values as ** the result row. */ case OP_ResultRow: { Mem *pMem; int i; assert( p->nResColumn==pOp->p2 ); assert( pOp->p1>0 ); assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); #ifndef SQLITE_OMIT_PROGRESS_CALLBACK /* Run the progress counter just before returning. */ if( db->xProgress!=0 && nVmStep>=nProgressLimit && db->xProgress(db->pProgressArg)!=0 ){ rc = SQLITE_INTERRUPT; goto abort_due_to_error; } #endif /* If this statement has violated immediate foreign key constraints, do ** not return the number of rows modified. And do not RELEASE the statement ** transaction. It needs to be rolled back. */ if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){ assert( db->flags&SQLITE_CountRows ); assert( p->usesStmtJournal ); goto abort_due_to_error; } /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then ** DML statements invoke this opcode to return the number of rows ** modified to the user. This is the only way that a VM that ** opens a statement transaction may invoke this opcode. ** ** In case this is such a statement, close any statement transaction ** opened by this VM before returning control to the user. This is to ** ensure that statement-transactions are always nested, not overlapping. ** If the open statement-transaction is not closed here, then the user ** may step another VM that opens its own statement transaction. This ** may lead to overlapping statement transactions. ** ** The statement transaction is never a top-level transaction. Hence ** the RELEASE call below can never fail. */ assert( p->iStatement==0 || db->flags&SQLITE_CountRows ); rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); assert( rc==SQLITE_OK ); /* Invalidate all ephemeral cursor row caches */ p->cacheCtr = (p->cacheCtr + 2)|1; /* Make sure the results of the current row are \000 terminated ** and have an assigned type. The results are de-ephemeralized as ** a side effect. */ pMem = p->pResultSet = &aMem[pOp->p1]; for(i=0; i<pOp->p2; i++){ assert( memIsValid(&pMem[i]) ); Deephemeralize(&pMem[i]); assert( (pMem[i].flags & MEM_Ephem)==0 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 ); sqlite3VdbeMemNulTerminate(&pMem[i]); REGISTER_TRACE(pOp->p1+i, &pMem[i]); } if( db->mallocFailed ) goto no_mem; if( db->mTrace & SQLITE_TRACE_ROW ){ db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0); } /* Return SQLITE_ROW */ p->pc = (int)(pOp - aOp) + 1; rc = SQLITE_ROW; goto vdbe_return; } /* Opcode: Concat P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]+r[P1] ** ** Add the text in register P1 onto the end of the text in ** register P2 and store the result in register P3. ** If either the P1 or P2 text are NULL then store NULL in P3. ** ** P3 = P2 || P1 ** ** It is illegal for P1 and P3 to be the same register. Sometimes, ** if P3 is the same register as P2, the implementation is able ** to avoid a memcpy(). */ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ i64 nByte; pIn1 = &aMem[pOp->p1]; pIn2 = &aMem[pOp->p2]; pOut = &aMem[pOp->p3]; assert( pIn1!=pOut ); if( (pIn1->flags | pIn2->flags) & MEM_Null ){ sqlite3VdbeMemSetNull(pOut); break; } if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem; Stringify(pIn1, encoding); Stringify(pIn2, encoding); nByte = pIn1->n + pIn2->n; if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){ goto no_mem; } MemSetTypeFlag(pOut, MEM_Str); if( pOut!=pIn2 ){ memcpy(pOut->z, pIn2->z, pIn2->n); } memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); pOut->z[nByte]=0; pOut->z[nByte+1] = 0; pOut->flags |= MEM_Term; pOut->n = (int)nByte; pOut->enc = encoding; UPDATE_MAX_BLOBSIZE(pOut); break; } /* Opcode: Add P1 P2 P3 * * ** Synopsis: r[P3]=r[P1]+r[P2] ** ** Add the value in register P1 to the value in register P2 ** and store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: Multiply P1 P2 P3 * * ** Synopsis: r[P3]=r[P1]*r[P2] ** ** ** Multiply the value in register P1 by the value in register P2 ** and store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: Subtract P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]-r[P1] ** ** Subtract the value in register P1 from the value in register P2 ** and store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: Divide P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]/r[P1] ** ** Divide the value in register P1 by the value in register P2 ** and store the result in register P3 (P3=P2/P1). If the value in ** register P1 is zero, then the result is NULL. If either input is ** NULL, the result is NULL. */ /* Opcode: Remainder P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]%r[P1] ** ** Compute the remainder after integer register P2 is divided by ** register P1 and store the result in register P3. ** If the value in register P1 is zero the result is NULL. ** If either operand is NULL, the result is NULL. */ case OP_Add: /* same as TK_PLUS, in1, in2, out3 */ case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ char bIntint; /* Started out as two integer operands */ u16 flags; /* Combined MEM_* flags from both inputs */ u16 type1; /* Numeric type of left operand */ u16 type2; /* Numeric type of right operand */ i64 iA; /* Integer value of left operand */ i64 iB; /* Integer value of right operand */ double rA; /* Real value of left operand */ double rB; /* Real value of right operand */ pIn1 = &aMem[pOp->p1]; type1 = numericType(pIn1); pIn2 = &aMem[pOp->p2]; type2 = numericType(pIn2); pOut = &aMem[pOp->p3]; flags = pIn1->flags | pIn2->flags; if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null; if( (type1 & type2 & MEM_Int)!=0 ){ iA = pIn1->u.i; iB = pIn2->u.i; bIntint = 1; switch( pOp->opcode ){ case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break; case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break; case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break; case OP_Divide: { if( iA==0 ) goto arithmetic_result_is_null; if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math; iB /= iA; break; } default: { if( iA==0 ) goto arithmetic_result_is_null; if( iA==-1 ) iA = 1; iB %= iA; break; } } pOut->u.i = iB; MemSetTypeFlag(pOut, MEM_Int); }else{ bIntint = 0; fp_math: rA = sqlite3VdbeRealValue(pIn1); rB = sqlite3VdbeRealValue(pIn2); switch( pOp->opcode ){ case OP_Add: rB += rA; break; case OP_Subtract: rB -= rA; break; case OP_Multiply: rB *= rA; break; case OP_Divide: { /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ if( rA==(double)0 ) goto arithmetic_result_is_null; rB /= rA; break; } default: { iA = (i64)rA; iB = (i64)rB; if( iA==0 ) goto arithmetic_result_is_null; if( iA==-1 ) iA = 1; rB = (double)(iB % iA); break; } } #ifdef SQLITE_OMIT_FLOATING_POINT pOut->u.i = rB; MemSetTypeFlag(pOut, MEM_Int); #else if( sqlite3IsNaN(rB) ){ goto arithmetic_result_is_null; } pOut->u.r = rB; MemSetTypeFlag(pOut, MEM_Real); if( ((type1|type2)&MEM_Real)==0 && !bIntint ){ sqlite3VdbeIntegerAffinity(pOut); } #endif } break; arithmetic_result_is_null: sqlite3VdbeMemSetNull(pOut); break; } /* Opcode: CollSeq P1 * * P4 ** ** P4 is a pointer to a CollSeq struct. If the next call to a user function ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will ** be returned. This is used by the built-in min(), max() and nullif() ** functions. ** ** If P1 is not zero, then it is a register that a subsequent min() or ** max() aggregate will set to 1 if the current row is not the minimum or ** maximum. The P1 register is initialized to 0 by this instruction. ** ** The interface used by the implementation of the aforementioned functions ** to retrieve the collation sequence set by this opcode is not available ** publicly. Only built-in functions have access to this feature. */ case OP_CollSeq: { assert( pOp->p4type==P4_COLLSEQ ); if( pOp->p1 ){ sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0); } break; } /* Opcode: Function0 P1 P2 P3 P4 P5 ** Synopsis: r[P3]=func(r[P2@P5]) ** ** Invoke a user function (P4 is a pointer to a FuncDef object that ** defines the function) with P5 arguments taken from register P2 and ** successors. The result of the function is stored in register P3. ** Register P3 must not be one of the function inputs. ** ** P1 is a 32-bit bitmask indicating whether or not each argument to the ** function was determined to be constant at compile time. If the first ** argument was constant then bit 0 of P1 is set. This is used to determine ** whether meta data associated with a user function argument using the ** sqlite3_set_auxdata() API may be safely retained until the next ** invocation of this opcode. ** ** See also: Function, AggStep, AggFinal */ /* Opcode: Function P1 P2 P3 P4 P5 ** Synopsis: r[P3]=func(r[P2@P5]) ** ** Invoke a user function (P4 is a pointer to an sqlite3_context object that ** contains a pointer to the function to be run) with P5 arguments taken ** from register P2 and successors. The result of the function is stored ** in register P3. Register P3 must not be one of the function inputs. ** ** P1 is a 32-bit bitmask indicating whether or not each argument to the ** function was determined to be constant at compile time. If the first ** argument was constant then bit 0 of P1 is set. This is used to determine ** whether meta data associated with a user function argument using the ** sqlite3_set_auxdata() API may be safely retained until the next ** invocation of this opcode. ** ** SQL functions are initially coded as OP_Function0 with P4 pointing ** to a FuncDef object. But on first evaluation, the P4 operand is ** automatically converted into an sqlite3_context object and the operation ** changed to this OP_Function opcode. In this way, the initialization of ** the sqlite3_context object occurs only once, rather than once for each ** evaluation of the function. ** ** See also: Function0, AggStep, AggFinal */ case OP_Function0: { int n; sqlite3_context *pCtx; assert( pOp->p4type==P4_FUNCDEF ); n = pOp->p5; assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n ); pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*)); if( pCtx==0 ) goto no_mem; pCtx->pOut = 0; pCtx->pFunc = pOp->p4.pFunc; pCtx->iOp = (int)(pOp - aOp); pCtx->pVdbe = p; pCtx->argc = n; pOp->p4type = P4_FUNCCTX; pOp->p4.pCtx = pCtx; pOp->opcode = OP_Function; /* Fall through into OP_Function */ } case OP_Function: { int i; sqlite3_context *pCtx; assert( pOp->p4type==P4_FUNCCTX ); pCtx = pOp->p4.pCtx; /* If this function is inside of a trigger, the register array in aMem[] ** might change from one evaluation to the next. The next block of code ** checks to see if the register array has changed, and if so it ** reinitializes the relavant parts of the sqlite3_context object */ pOut = &aMem[pOp->p3]; if( pCtx->pOut != pOut ){ pCtx->pOut = pOut; for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; } memAboutToChange(p, pCtx->pOut); #ifdef SQLITE_DEBUG for(i=0; i<pCtx->argc; i++){ assert( memIsValid(pCtx->argv[i]) ); REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); } #endif MemSetTypeFlag(pCtx->pOut, MEM_Null); pCtx->fErrorOrAux = 0; (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */ /* If the function returned an error, throw an exception */ if( pCtx->fErrorOrAux ){ if( pCtx->isError ){ sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut)); rc = pCtx->isError; } sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1); if( rc ) goto abort_due_to_error; } /* Copy the result of the function into register P3 */ if( pOut->flags & (MEM_Str|MEM_Blob) ){ sqlite3VdbeChangeEncoding(pCtx->pOut, encoding); if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big; } REGISTER_TRACE(pOp->p3, pCtx->pOut); UPDATE_MAX_BLOBSIZE(pCtx->pOut); break; } /* Opcode: BitAnd P1 P2 P3 * * ** Synopsis: r[P3]=r[P1]&r[P2] ** ** Take the bit-wise AND of the values in register P1 and P2 and ** store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: BitOr P1 P2 P3 * * ** Synopsis: r[P3]=r[P1]|r[P2] ** ** Take the bit-wise OR of the values in register P1 and P2 and ** store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: ShiftLeft P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]<<r[P1] ** ** Shift the integer value in register P2 to the left by the ** number of bits specified by the integer in register P1. ** Store the result in register P3. ** If either input is NULL, the result is NULL. */ /* Opcode: ShiftRight P1 P2 P3 * * ** Synopsis: r[P3]=r[P2]>>r[P1] ** ** Shift the integer value in register P2 to the right by the ** number of bits specified by the integer in register P1. ** Store the result in register P3. ** If either input is NULL, the result is NULL. */ case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */ case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */ case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */ case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ i64 iA; u64 uA; i64 iB; u8 op; pIn1 = &aMem[pOp->p1]; pIn2 = &aMem[pOp->p2]; pOut = &aMem[pOp->p3]; if( (pIn1->flags | pIn2->flags) & MEM_Null ){ sqlite3VdbeMemSetNull(pOut); break; } iA = sqlite3VdbeIntValue(pIn2); iB = sqlite3VdbeIntValue(pIn1); op = pOp->opcode; if( op==OP_BitAnd ){ iA &= iB; }else if( op==OP_BitOr ){ iA |= iB; }else if( iB!=0 ){ assert( op==OP_ShiftRight || op==OP_ShiftLeft ); /* If shifting by a negative amount, shift in the other direction */ if( iB<0 ){ assert( OP_ShiftRight==OP_ShiftLeft+1 ); op = 2*OP_ShiftLeft + 1 - op; iB = iB>(-64) ? -iB : 64; } if( iB>=64 ){ iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1; }else{ memcpy(&uA, &iA, sizeof(uA)); if( op==OP_ShiftLeft ){ uA <<= iB; }else{ uA >>= iB; /* Sign-extend on a right shift of a negative number */ if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB); } memcpy(&iA, &uA, sizeof(iA)); } } pOut->u.i = iA; MemSetTypeFlag(pOut, MEM_Int); break; } /* Opcode: AddImm P1 P2 * * * ** Synopsis: r[P1]=r[P1]+P2 ** ** Add the constant P2 to the value in register P1. ** The result is always an integer. ** ** To force any register to be an integer, just add 0. */ case OP_AddImm: { /* in1 */ pIn1 = &aMem[pOp->p1]; memAboutToChange(p, pIn1); sqlite3VdbeMemIntegerify(pIn1); pIn1->u.i += pOp->p2; break; } /* Opcode: MustBeInt P1 P2 * * * ** ** Force the value in register P1 to be an integer. If the value ** in P1 is not an integer and cannot be converted into an integer ** without data loss, then jump immediately to P2, or if P2==0 ** raise an SQLITE_MISMATCH exception. */ case OP_MustBeInt: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; if( (pIn1->flags & MEM_Int)==0 ){ applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2); if( (pIn1->flags & MEM_Int)==0 ){ if( pOp->p2==0 ){ rc = SQLITE_MISMATCH; goto abort_due_to_error; }else{ goto jump_to_p2; } } } MemSetTypeFlag(pIn1, MEM_Int); break; } #ifndef SQLITE_OMIT_FLOATING_POINT /* Opcode: RealAffinity P1 * * * * ** ** If register P1 holds an integer convert it to a real value. ** ** This opcode is used when extracting information from a column that ** has REAL affinity. Such column values may still be stored as ** integers, for space efficiency, but after extraction we want them ** to have only a real value. */ case OP_RealAffinity: { /* in1 */ pIn1 = &aMem[pOp->p1]; if( pIn1->flags & MEM_Int ){ sqlite3VdbeMemRealify(pIn1); } break; } #endif #ifndef SQLITE_OMIT_CAST /* Opcode: Cast P1 P2 * * * ** Synopsis: affinity(r[P1]) ** ** Force the value in register P1 to be the type defined by P2. ** ** <ul> ** <li value="97"> TEXT ** <li value="98"> BLOB ** <li value="99"> NUMERIC ** <li value="100"> INTEGER ** <li value="101"> REAL ** </ul> ** ** A NULL value is not changed by this routine. It remains NULL. */ case OP_Cast: { /* in1 */ assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL ); testcase( pOp->p2==SQLITE_AFF_TEXT ); testcase( pOp->p2==SQLITE_AFF_BLOB ); testcase( pOp->p2==SQLITE_AFF_NUMERIC ); testcase( pOp->p2==SQLITE_AFF_INTEGER ); testcase( pOp->p2==SQLITE_AFF_REAL ); pIn1 = &aMem[pOp->p1]; memAboutToChange(p, pIn1); rc = ExpandBlob(pIn1); sqlite3VdbeMemCast(pIn1, pOp->p2, encoding); UPDATE_MAX_BLOBSIZE(pIn1); if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_CAST */ /* Opcode: Eq P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]==r[P1] ** ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then ** store the result of comparison in register P2. ** ** The SQLITE_AFF_MASK portion of P5 must be an affinity character - ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made ** to coerce both inputs according to this affinity before the ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric ** affinity is used. Note that the affinity conversions are stored ** back into the input registers P1 and P3. So this opcode can cause ** persistent changes to registers P1 and P3. ** ** Once any conversions have taken place, and neither value is NULL, ** the values are compared. If both values are blobs then memcmp() is ** used to determine the results of the comparison. If both values ** are text, then the appropriate collating function specified in ** P4 is used to do the comparison. If P4 is not specified then ** memcmp() is used to compare text string. If both values are ** numeric, then a numeric comparison is used. If the two values ** are of different types, then numbers are considered less than ** strings and strings are considered less than blobs. ** ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either ** true or false and is never NULL. If both operands are NULL then the result ** of comparison is true. If either operand is NULL then the result is false. ** If neither operand is NULL the result is the same as it would be if ** the SQLITE_NULLEQ flag were omitted from P5. ** ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the ** content of r[P2] is only changed if the new value is NULL or 0 (false). ** In other words, a prior r[P2] value will not be overwritten by 1 (true). */ /* Opcode: Ne P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]!=r[P1] ** ** This works just like the Eq opcode except that the jump is taken if ** the operands in registers P1 and P3 are not equal. See the Eq opcode for ** additional information. ** ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the ** content of r[P2] is only changed if the new value is NULL or 1 (true). ** In other words, a prior r[P2] value will not be overwritten by 0 (false). */ /* Opcode: Lt P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]<r[P1] ** ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store ** the result of comparison (0 or 1 or NULL) into register P2. ** ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL ** bit is clear then fall through if either operand is NULL. ** ** The SQLITE_AFF_MASK portion of P5 must be an affinity character - ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made ** to coerce both inputs according to this affinity before the ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric ** affinity is used. Note that the affinity conversions are stored ** back into the input registers P1 and P3. So this opcode can cause ** persistent changes to registers P1 and P3. ** ** Once any conversions have taken place, and neither value is NULL, ** the values are compared. If both values are blobs then memcmp() is ** used to determine the results of the comparison. If both values ** are text, then the appropriate collating function specified in ** P4 is used to do the comparison. If P4 is not specified then ** memcmp() is used to compare text string. If both values are ** numeric, then a numeric comparison is used. If the two values ** are of different types, then numbers are considered less than ** strings and strings are considered less than blobs. */ /* Opcode: Le P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]<=r[P1] ** ** This works just like the Lt opcode except that the jump is taken if ** the content of register P3 is less than or equal to the content of ** register P1. See the Lt opcode for additional information. */ /* Opcode: Gt P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]>r[P1] ** ** This works just like the Lt opcode except that the jump is taken if ** the content of register P3 is greater than the content of ** register P1. See the Lt opcode for additional information. */ /* Opcode: Ge P1 P2 P3 P4 P5 ** Synopsis: IF r[P3]>=r[P1] ** ** This works just like the Lt opcode except that the jump is taken if ** the content of register P3 is greater than or equal to the content of ** register P1. See the Lt opcode for additional information. */ case OP_Eq: /* same as TK_EQ, jump, in1, in3 */ case OP_Ne: /* same as TK_NE, jump, in1, in3 */ case OP_Lt: /* same as TK_LT, jump, in1, in3 */ case OP_Le: /* same as TK_LE, jump, in1, in3 */ case OP_Gt: /* same as TK_GT, jump, in1, in3 */ case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ int res, res2; /* Result of the comparison of pIn1 against pIn3 */ char affinity; /* Affinity to use for comparison */ u16 flags1; /* Copy of initial value of pIn1->flags */ u16 flags3; /* Copy of initial value of pIn3->flags */ pIn1 = &aMem[pOp->p1]; pIn3 = &aMem[pOp->p3]; flags1 = pIn1->flags; flags3 = pIn3->flags; if( (flags1 | flags3)&MEM_Null ){ /* One or both operands are NULL */ if( pOp->p5 & SQLITE_NULLEQ ){ /* If SQLITE_NULLEQ is set (which will only happen if the operator is ** OP_Eq or OP_Ne) then take the jump or not depending on whether ** or not both operands are null. */ assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne ); assert( (flags1 & MEM_Cleared)==0 ); assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 ); if( (flags1&flags3&MEM_Null)!=0 && (flags3&MEM_Cleared)==0 ){ res = 0; /* Operands are equal */ }else{ res = 1; /* Operands are not equal */ } }else{ /* SQLITE_NULLEQ is clear and at least one operand is NULL, ** then the result is always NULL. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set. */ if( pOp->p5 & SQLITE_STOREP2 ){ pOut = &aMem[pOp->p2]; iCompare = 1; /* Operands are not equal */ memAboutToChange(p, pOut); MemSetTypeFlag(pOut, MEM_Null); REGISTER_TRACE(pOp->p2, pOut); }else{ VdbeBranchTaken(2,3); if( pOp->p5 & SQLITE_JUMPIFNULL ){ goto jump_to_p2; } } break; } }else{ /* Neither operand is NULL. Do a comparison. */ affinity = pOp->p5 & SQLITE_AFF_MASK; if( affinity>=SQLITE_AFF_NUMERIC ){ if( (flags1 | flags3)&MEM_Str ){ if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn1,0); testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */ flags3 = pIn3->flags; } if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn3,0); } } /* Handle the common case of integer comparison here, as an ** optimization, to avoid a call to sqlite3MemCompare() */ if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){ if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; } if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; } res = 0; goto compare_op; } }else if( affinity==SQLITE_AFF_TEXT ){ if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){ testcase( pIn1->flags & MEM_Int ); testcase( pIn1->flags & MEM_Real ); sqlite3VdbeMemStringify(pIn1, encoding, 1); testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) ); flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask); assert( pIn1!=pIn3 ); } if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){ testcase( pIn3->flags & MEM_Int ); testcase( pIn3->flags & MEM_Real ); sqlite3VdbeMemStringify(pIn3, encoding, 1); testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) ); flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask); } } assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); } compare_op: switch( pOp->opcode ){ case OP_Eq: res2 = res==0; break; case OP_Ne: res2 = res; break; case OP_Lt: res2 = res<0; break; case OP_Le: res2 = res<=0; break; case OP_Gt: res2 = res>0; break; default: res2 = res>=0; break; } /* Undo any changes made by applyAffinity() to the input registers. */ assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); pIn1->flags = flags1; assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) ); pIn3->flags = flags3; if( pOp->p5 & SQLITE_STOREP2 ){ pOut = &aMem[pOp->p2]; iCompare = res; res2 = res2!=0; /* For this path res2 must be exactly 0 or 1 */ if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){ /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1 ** and prevents OP_Ne from overwriting NULL with 0. This flag ** is only used in contexts where either: ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0) ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1) ** Therefore it is not necessary to check the content of r[P2] for ** NULL. */ assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq ); assert( res2==0 || res2==1 ); testcase( res2==0 && pOp->opcode==OP_Eq ); testcase( res2==1 && pOp->opcode==OP_Eq ); testcase( res2==0 && pOp->opcode==OP_Ne ); testcase( res2==1 && pOp->opcode==OP_Ne ); if( (pOp->opcode==OP_Eq)==res2 ) break; } memAboutToChange(p, pOut); MemSetTypeFlag(pOut, MEM_Int); pOut->u.i = res2; REGISTER_TRACE(pOp->p2, pOut); }else{ VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3); if( res2 ){ goto jump_to_p2; } } break; } /* Opcode: ElseNotEq * P2 * * * ** ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator. ** If result of an OP_Eq comparison on the same two operands ** would have be NULL or false (0), then then jump to P2. ** If the result of an OP_Eq comparison on the two previous operands ** would have been true (1), then fall through. */ case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */ assert( pOp>aOp ); assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt ); assert( pOp[-1].p5 & SQLITE_STOREP2 ); VdbeBranchTaken(iCompare!=0, 2); if( iCompare!=0 ) goto jump_to_p2; break; } /* Opcode: Permutation * * * P4 * ** ** Set the permutation used by the OP_Compare operator in the next ** instruction. The permutation is stored in the P4 operand. ** ** The permutation is only valid until the next OP_Compare that has ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should ** occur immediately prior to the OP_Compare. ** ** The first integer in the P4 integer array is the length of the array ** and does not become part of the permutation. */ case OP_Permutation: { assert( pOp->p4type==P4_INTARRAY ); assert( pOp->p4.ai ); assert( pOp[1].opcode==OP_Compare ); assert( pOp[1].p5 & OPFLAG_PERMUTE ); break; } /* Opcode: Compare P1 P2 P3 P4 P5 ** Synopsis: r[P1@P3] <-> r[P2@P3] ** ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of ** the comparison for use by the next OP_Jump instruct. ** ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is ** determined by the most recent OP_Permutation operator. If the ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential ** order. ** ** P4 is a KeyInfo structure that defines collating sequences and sort ** orders for the comparison. The permutation applies to registers ** only. The KeyInfo elements are used sequentially. ** ** The comparison is a sort comparison, so NULLs compare equal, ** NULLs are less than numbers, numbers are less than strings, ** and strings are less than blobs. */ case OP_Compare: { int n; int i; int p1; int p2; const KeyInfo *pKeyInfo; int idx; CollSeq *pColl; /* Collating sequence to use on this term */ int bRev; /* True for DESCENDING sort order */ int *aPermute; /* The permutation */ if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){ aPermute = 0; }else{ assert( pOp>aOp ); assert( pOp[-1].opcode==OP_Permutation ); assert( pOp[-1].p4type==P4_INTARRAY ); aPermute = pOp[-1].p4.ai + 1; assert( aPermute!=0 ); } n = pOp->p3; pKeyInfo = pOp->p4.pKeyInfo; assert( n>0 ); assert( pKeyInfo!=0 ); p1 = pOp->p1; p2 = pOp->p2; #if SQLITE_DEBUG if( aPermute ){ int k, mx = 0; for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k]; assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 ); assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 ); }else{ assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 ); assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 ); } #endif /* SQLITE_DEBUG */ for(i=0; i<n; i++){ idx = aPermute ? aPermute[i] : i; assert( memIsValid(&aMem[p1+idx]) ); assert( memIsValid(&aMem[p2+idx]) ); REGISTER_TRACE(p1+idx, &aMem[p1+idx]); REGISTER_TRACE(p2+idx, &aMem[p2+idx]); assert( i<pKeyInfo->nField ); pColl = pKeyInfo->aColl[i]; bRev = pKeyInfo->aSortOrder[i]; iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); if( iCompare ){ if( bRev ) iCompare = -iCompare; break; } } break; } /* Opcode: Jump P1 P2 P3 * * ** ** Jump to the instruction at address P1, P2, or P3 depending on whether ** in the most recent OP_Compare instruction the P1 vector was less than ** equal to, or greater than the P2 vector, respectively. */ case OP_Jump: { /* jump */ if( iCompare<0 ){ VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1]; }else if( iCompare==0 ){ VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1]; }else{ VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1]; } break; } /* Opcode: And P1 P2 P3 * * ** Synopsis: r[P3]=(r[P1] && r[P2]) ** ** Take the logical AND of the values in registers P1 and P2 and ** write the result into register P3. ** ** If either P1 or P2 is 0 (false) then the result is 0 even if ** the other input is NULL. A NULL and true or two NULLs give ** a NULL output. */ /* Opcode: Or P1 P2 P3 * * ** Synopsis: r[P3]=(r[P1] || r[P2]) ** ** Take the logical OR of the values in register P1 and P2 and ** store the answer in register P3. ** ** If either P1 or P2 is nonzero (true) then the result is 1 (true) ** even if the other input is NULL. A NULL and false or two NULLs ** give a NULL output. */ case OP_And: /* same as TK_AND, in1, in2, out3 */ case OP_Or: { /* same as TK_OR, in1, in2, out3 */ int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ pIn1 = &aMem[pOp->p1]; if( pIn1->flags & MEM_Null ){ v1 = 2; }else{ v1 = sqlite3VdbeIntValue(pIn1)!=0; } pIn2 = &aMem[pOp->p2]; if( pIn2->flags & MEM_Null ){ v2 = 2; }else{ v2 = sqlite3VdbeIntValue(pIn2)!=0; } if( pOp->opcode==OP_And ){ static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; v1 = and_logic[v1*3+v2]; }else{ static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 }; v1 = or_logic[v1*3+v2]; } pOut = &aMem[pOp->p3]; if( v1==2 ){ MemSetTypeFlag(pOut, MEM_Null); }else{ pOut->u.i = v1; MemSetTypeFlag(pOut, MEM_Int); } break; } /* Opcode: Not P1 P2 * * * ** Synopsis: r[P2]= !r[P1] ** ** Interpret the value in register P1 as a boolean value. Store the ** boolean complement in register P2. If the value in register P1 is ** NULL, then a NULL is stored in P2. */ case OP_Not: { /* same as TK_NOT, in1, out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; sqlite3VdbeMemSetNull(pOut); if( (pIn1->flags & MEM_Null)==0 ){ pOut->flags = MEM_Int; pOut->u.i = !sqlite3VdbeIntValue(pIn1); } break; } /* Opcode: BitNot P1 P2 * * * ** Synopsis: r[P1]= ~r[P1] ** ** Interpret the content of register P1 as an integer. Store the ** ones-complement of the P1 value into register P2. If P1 holds ** a NULL then store a NULL in P2. */ case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; sqlite3VdbeMemSetNull(pOut); if( (pIn1->flags & MEM_Null)==0 ){ pOut->flags = MEM_Int; pOut->u.i = ~sqlite3VdbeIntValue(pIn1); } break; } /* Opcode: Once P1 P2 * * * ** ** If the P1 value is equal to the P1 value on the OP_Init opcode at ** instruction 0, then jump to P2. If the two P1 values differ, then ** set the P1 value on this opcode to equal the P1 value on the OP_Init ** and fall through. */ case OP_Once: { /* jump */ assert( p->aOp[0].opcode==OP_Init ); VdbeBranchTaken(p->aOp[0].p1==pOp->p1, 2); if( p->aOp[0].p1==pOp->p1 ){ goto jump_to_p2; }else{ pOp->p1 = p->aOp[0].p1; } break; } /* Opcode: If P1 P2 P3 * * ** ** Jump to P2 if the value in register P1 is true. The value ** is considered true if it is numeric and non-zero. If the value ** in P1 is NULL then take the jump if and only if P3 is non-zero. */ /* Opcode: IfNot P1 P2 P3 * * ** ** Jump to P2 if the value in register P1 is False. The value ** is considered false if it has a numeric value of zero. If the value ** in P1 is NULL then take the jump if and only if P3 is non-zero. */ case OP_If: /* jump, in1 */ case OP_IfNot: { /* jump, in1 */ int c; pIn1 = &aMem[pOp->p1]; if( pIn1->flags & MEM_Null ){ c = pOp->p3; }else{ #ifdef SQLITE_OMIT_FLOATING_POINT c = sqlite3VdbeIntValue(pIn1)!=0; #else c = sqlite3VdbeRealValue(pIn1)!=0.0; #endif if( pOp->opcode==OP_IfNot ) c = !c; } VdbeBranchTaken(c!=0, 2); if( c ){ goto jump_to_p2; } break; } /* Opcode: IsNull P1 P2 * * * ** Synopsis: if r[P1]==NULL goto P2 ** ** Jump to P2 if the value in register P1 is NULL. */ case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ pIn1 = &aMem[pOp->p1]; VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2); if( (pIn1->flags & MEM_Null)!=0 ){ goto jump_to_p2; } break; } /* Opcode: NotNull P1 P2 * * * ** Synopsis: if r[P1]!=NULL goto P2 ** ** Jump to P2 if the value in register P1 is not NULL. */ case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ pIn1 = &aMem[pOp->p1]; VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2); if( (pIn1->flags & MEM_Null)==0 ){ goto jump_to_p2; } break; } /* Opcode: Column P1 P2 P3 P4 P5 ** Synopsis: r[P3]=PX ** ** Interpret the data that cursor P1 points to as a structure built using ** the MakeRecord instruction. (See the MakeRecord opcode for additional ** information about the format of the data.) Extract the P2-th column ** from this record. If there are less that (P2+1) ** values in the record, extract a NULL. ** ** The value extracted is stored in register P3. ** ** If the column contains fewer than P2 fields, then extract a NULL. Or, ** if the P4 argument is a P4_MEM use the value of the P4 argument as ** the result. ** ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor, ** then the cache of the cursor is reset prior to extracting the column. ** The first OP_Column against a pseudo-table after the value of the content ** register has changed should have this bit set. ** ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when ** the result is guaranteed to only be used as the argument of a length() ** or typeof() function, respectively. The loading of large blobs can be ** skipped for length() and all content loading can be skipped for typeof(). */ case OP_Column: { int p2; /* column number to retrieve */ VdbeCursor *pC; /* The VDBE cursor */ BtCursor *pCrsr; /* The BTree cursor */ u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ int len; /* The length of the serialized data for the column */ int i; /* Loop counter */ Mem *pDest; /* Where to write the extracted value */ Mem sMem; /* For storing the record being decoded */ const u8 *zData; /* Part of the record being decoded */ const u8 *zHdr; /* Next unparsed byte of the header */ const u8 *zEndHdr; /* Pointer to first byte after the header */ u32 offset; /* Offset into the data */ u64 offset64; /* 64-bit offset */ u32 avail; /* Number of bytes of available data */ u32 t; /* A type code from the record header */ Mem *pReg; /* PseudoTable input register */ pC = p->apCsr[pOp->p1]; p2 = pOp->p2; /* If the cursor cache is stale, bring it up-to-date */ rc = sqlite3VdbeCursorMoveto(&pC, &p2); if( rc ) goto abort_due_to_error; assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pDest = &aMem[pOp->p3]; memAboutToChange(p, pDest); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( pC!=0 ); assert( p2<pC->nField ); aOffset = pC->aOffset; assert( pC->eCurType!=CURTYPE_VTAB ); assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); assert( pC->eCurType!=CURTYPE_SORTER ); if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/ if( pC->nullRow ){ if( pC->eCurType==CURTYPE_PSEUDO ){ assert( pC->uc.pseudoTableReg>0 ); pReg = &aMem[pC->uc.pseudoTableReg]; assert( pReg->flags & MEM_Blob ); assert( memIsValid(pReg) ); pC->payloadSize = pC->szRow = avail = pReg->n; pC->aRow = (u8*)pReg->z; }else{ sqlite3VdbeMemSetNull(pDest); goto op_column_out; } }else{ pCrsr = pC->uc.pCursor; assert( pC->eCurType==CURTYPE_BTREE ); assert( pCrsr ); assert( sqlite3BtreeCursorIsValid(pCrsr) ); pC->payloadSize = sqlite3BtreePayloadSize(pCrsr); pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail); assert( avail<=65536 ); /* Maximum page size is 64KiB */ if( pC->payloadSize <= (u32)avail ){ pC->szRow = pC->payloadSize; }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; }else{ pC->szRow = avail; } } pC->cacheStatus = p->cacheCtr; pC->iHdrOffset = getVarint32(pC->aRow, offset); pC->nHdrParsed = 0; aOffset[0] = offset; if( avail<offset ){ /*OPTIMIZATION-IF-FALSE*/ /* pC->aRow does not have to hold the entire row, but it does at least ** need to cover the header of the record. If pC->aRow does not contain ** the complete header, then set it to zero, forcing the header to be ** dynamically allocated. */ pC->aRow = 0; pC->szRow = 0; /* Make sure a corrupt database has not given us an oversize header. ** Do this now to avoid an oversize memory allocation. ** ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte ** types use so much data space that there can only be 4096 and 32 of ** them, respectively. So the maximum header length results from a ** 3-byte type for each of the maximum of 32768 columns plus three ** extra bytes for the header length itself. 32768*3 + 3 = 98307. */ if( offset > 98307 || offset > pC->payloadSize ){ rc = SQLITE_CORRUPT_BKPT; goto abort_due_to_error; } }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/ /* The following goto is an optimization. It can be omitted and ** everything will still work. But OP_Column is measurably faster ** by skipping the subsequent conditional, which is always true. */ zData = pC->aRow; assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */ goto op_column_read_header; } } /* Make sure at least the first p2+1 entries of the header have been ** parsed and valid information is in aOffset[] and pC->aType[]. */ if( pC->nHdrParsed<=p2 ){ /* If there is more header available for parsing in the record, try ** to extract additional fields up through the p2+1-th field */ if( pC->iHdrOffset<aOffset[0] ){ /* Make sure zData points to enough of the record to cover the header. */ if( pC->aRow==0 ){ memset(&sMem, 0, sizeof(sMem)); rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem); if( rc!=SQLITE_OK ) goto abort_due_to_error; zData = (u8*)sMem.z; }else{ zData = pC->aRow; } /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */ op_column_read_header: i = pC->nHdrParsed; offset64 = aOffset[i]; zHdr = zData + pC->iHdrOffset; zEndHdr = zData + aOffset[0]; do{ if( (t = zHdr[0])<0x80 ){ zHdr++; offset64 += sqlite3VdbeOneByteSerialTypeLen(t); }else{ zHdr += sqlite3GetVarint32(zHdr, &t); offset64 += sqlite3VdbeSerialTypeLen(t); } pC->aType[i++] = t; aOffset[i] = (u32)(offset64 & 0xffffffff); }while( i<=p2 && zHdr<zEndHdr ); /* The record is corrupt if any of the following are true: ** (1) the bytes of the header extend past the declared header size ** (2) the entire header was used but not all data was used ** (3) the end of the data extends beyond the end of the record. */ if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize)) || (offset64 > pC->payloadSize) ){ if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); rc = SQLITE_CORRUPT_BKPT; goto abort_due_to_error; } pC->nHdrParsed = i; pC->iHdrOffset = (u32)(zHdr - zData); if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); }else{ t = 0; } /* If after trying to extract new entries from the header, nHdrParsed is ** still not up to p2, that means that the record has fewer than p2 ** columns. So the result will be either the default value or a NULL. */ if( pC->nHdrParsed<=p2 ){ if( pOp->p4type==P4_MEM ){ sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static); }else{ sqlite3VdbeMemSetNull(pDest); } goto op_column_out; } }else{ t = pC->aType[p2]; } /* Extract the content for the p2+1-th column. Control can only ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are ** all valid. */ assert( p2<pC->nHdrParsed ); assert( rc==SQLITE_OK ); assert( sqlite3VdbeCheckMemInvariants(pDest) ); if( VdbeMemDynamic(pDest) ){ sqlite3VdbeMemSetNull(pDest); } assert( t==pC->aType[p2] ); if( pC->szRow>=aOffset[p2+1] ){ /* This is the common case where the desired content fits on the original ** page - where the content is not on an overflow page */ zData = pC->aRow + aOffset[p2]; if( t<12 ){ sqlite3VdbeSerialGet(zData, t, pDest); }else{ /* If the column value is a string, we need a persistent value, not ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize(). */ static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term }; pDest->n = len = (t-12)/2; pDest->enc = encoding; if( pDest->szMalloc < len+2 ){ pDest->flags = MEM_Null; if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem; }else{ pDest->z = pDest->zMalloc; } memcpy(pDest->z, zData, len); pDest->z[len] = 0; pDest->z[len+1] = 0; pDest->flags = aFlag[t&1]; } }else{ pDest->enc = encoding; /* This branch happens only when content is on overflow pages */ if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)) || (len = sqlite3VdbeSerialTypeLen(t))==0 ){ /* Content is irrelevant for ** 1. the typeof() function, ** 2. the length(X) function if X is a blob, and ** 3. if the content length is zero. ** So we might as well use bogus content rather than reading ** content from disk. */ static u8 aZero[8]; /* This is the bogus content */ sqlite3VdbeSerialGet(aZero, t, pDest); }else{ rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest); if( rc!=SQLITE_OK ) goto abort_due_to_error; sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest); pDest->flags &= ~MEM_Ephem; } } op_column_out: UPDATE_MAX_BLOBSIZE(pDest); REGISTER_TRACE(pOp->p3, pDest); break; } /* Opcode: Affinity P1 P2 * P4 * ** Synopsis: affinity(r[P1@P2]) ** ** Apply affinities to a range of P2 registers starting with P1. ** ** P4 is a string that is P2 characters long. The nth character of the ** string indicates the column affinity that should be used for the nth ** memory cell in the range. */ case OP_Affinity: { const char *zAffinity; /* The affinity to be applied */ char cAff; /* A single character of affinity */ zAffinity = pOp->p4.z; assert( zAffinity!=0 ); assert( zAffinity[pOp->p2]==0 ); pIn1 = &aMem[pOp->p1]; while( (cAff = *(zAffinity++))!=0 ){ assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] ); assert( memIsValid(pIn1) ); applyAffinity(pIn1, cAff, encoding); pIn1++; } break; } /* Opcode: MakeRecord P1 P2 P3 P4 * ** Synopsis: r[P3]=mkrec(r[P1@P2]) ** ** Convert P2 registers beginning with P1 into the [record format] ** use as a data record in a database table or as a key ** in an index. The OP_Column opcode can decode the record later. ** ** P4 may be a string that is P2 characters long. The nth character of the ** string indicates the column affinity that should be used for the nth ** field of the index key. ** ** The mapping from character to affinity is given by the SQLITE_AFF_ ** macros defined in sqliteInt.h. ** ** If P4 is NULL then all index fields have the affinity BLOB. */ case OP_MakeRecord: { u8 *zNewRecord; /* A buffer to hold the data for the new record */ Mem *pRec; /* The new record */ u64 nData; /* Number of bytes of data space */ int nHdr; /* Number of bytes of header space */ i64 nByte; /* Data space required for this record */ i64 nZero; /* Number of zero bytes at the end of the record */ int nVarint; /* Number of bytes in a varint */ u32 serial_type; /* Type field */ Mem *pData0; /* First field to be combined into the record */ Mem *pLast; /* Last field of the record */ int nField; /* Number of fields in the record */ char *zAffinity; /* The affinity string for the record */ int file_format; /* File format to use for encoding */ int i; /* Space used in zNewRecord[] header */ int j; /* Space used in zNewRecord[] content */ u32 len; /* Length of a field */ /* Assuming the record contains N fields, the record format looks ** like this: ** ** ------------------------------------------------------------------------ ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | ** ------------------------------------------------------------------------ ** ** Data(0) is taken from register P1. Data(1) comes from register P1+1 ** and so forth. ** ** Each type field is a varint representing the serial type of the ** corresponding data element (see sqlite3VdbeSerialType()). The ** hdr-size field is also a varint which is the offset from the beginning ** of the record to data0. */ nData = 0; /* Number of bytes of data space */ nHdr = 0; /* Number of bytes of header space */ nZero = 0; /* Number of zero bytes at the end of the record */ nField = pOp->p1; zAffinity = pOp->p4.z; assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 ); pData0 = &aMem[nField]; nField = pOp->p2; pLast = &pData0[nField-1]; file_format = p->minWriteFileFormat; /* Identify the output register */ assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 ); pOut = &aMem[pOp->p3]; memAboutToChange(p, pOut); /* Apply the requested affinity to all inputs */ assert( pData0<=pLast ); if( zAffinity ){ pRec = pData0; do{ applyAffinity(pRec++, *(zAffinity++), encoding); assert( zAffinity[0]==0 || pRec<=pLast ); }while( zAffinity[0] ); } #ifdef SQLITE_ENABLE_NULL_TRIM /* NULLs can be safely trimmed from the end of the record, as long as ** as the schema format is 2 or more and none of the omitted columns ** have a non-NULL default value. Also, the record must be left with ** at least one field. If P5>0 then it will be one more than the ** index of the right-most column with a non-NULL default value */ if( pOp->p5 ){ while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){ pLast--; nField--; } } #endif /* Loop through the elements that will make up the record to figure ** out how much space is required for the new record. */ pRec = pLast; do{ assert( memIsValid(pRec) ); pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len); if( pRec->flags & MEM_Zero ){ if( nData ){ if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem; }else{ nZero += pRec->u.nZero; len -= pRec->u.nZero; } } nData += len; testcase( serial_type==127 ); testcase( serial_type==128 ); nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type); if( pRec==pData0 ) break; pRec--; }while(1); /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint ** which determines the total number of bytes in the header. The varint ** value is the size of the header in bytes including the size varint ** itself. */ testcase( nHdr==126 ); testcase( nHdr==127 ); if( nHdr<=126 ){ /* The common case */ nHdr += 1; }else{ /* Rare case of a really large header */ nVarint = sqlite3VarintLen(nHdr); nHdr += nVarint; if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++; } nByte = nHdr+nData; if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } /* Make sure the output register has a buffer large enough to store ** the new record. The output register (pOp->p3) is not allowed to ** be one of the input registers (because the following call to ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used). */ if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){ goto no_mem; } zNewRecord = (u8 *)pOut->z; /* Write the record */ i = putVarint32(zNewRecord, nHdr); j = nHdr; assert( pData0<=pLast ); pRec = pData0; do{ serial_type = pRec->uTemp; /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more ** additional varints, one per column. */ i += putVarint32(&zNewRecord[i], serial_type); /* serial type */ /* EVIDENCE-OF: R-64536-51728 The values for each column in the record ** immediately follow the header. */ j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */ }while( (++pRec)<=pLast ); assert( i==nHdr ); assert( j==nByte ); assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pOut->n = (int)nByte; pOut->flags = MEM_Blob; if( nZero ){ pOut->u.nZero = nZero; pOut->flags |= MEM_Zero; } pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */ REGISTER_TRACE(pOp->p3, pOut); UPDATE_MAX_BLOBSIZE(pOut); break; } /* Opcode: Count P1 P2 * * * ** Synopsis: r[P2]=count() ** ** Store the number of entries (an integer value) in the table or index ** opened by cursor P1 in register P2 */ #ifndef SQLITE_OMIT_BTREECOUNT case OP_Count: { /* out2 */ i64 nEntry; BtCursor *pCrsr; assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE ); pCrsr = p->apCsr[pOp->p1]->uc.pCursor; assert( pCrsr ); nEntry = 0; /* Not needed. Only used to silence a warning. */ rc = sqlite3BtreeCount(pCrsr, &nEntry); if( rc ) goto abort_due_to_error; pOut = out2Prerelease(p, pOp); pOut->u.i = nEntry; break; } #endif /* Opcode: Savepoint P1 * * P4 * ** ** Open, release or rollback the savepoint named by parameter P4, depending ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2. */ case OP_Savepoint: { int p1; /* Value of P1 operand */ char *zName; /* Name of savepoint */ int nName; Savepoint *pNew; Savepoint *pSavepoint; Savepoint *pTmp; int iSavepoint; int ii; p1 = pOp->p1; zName = pOp->p4.z; /* Assert that the p1 parameter is valid. Also that if there is no open ** transaction, then there cannot be any savepoints. */ assert( db->pSavepoint==0 || db->autoCommit==0 ); assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK ); assert( db->pSavepoint || db->isTransactionSavepoint==0 ); assert( checkSavepointCount(db) ); assert( p->bIsReader ); if( p1==SAVEPOINT_BEGIN ){ if( db->nVdbeWrite>0 ){ /* A new savepoint cannot be created if there are active write ** statements (i.e. open read/write incremental blob handles). */ sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress"); rc = SQLITE_BUSY; }else{ nName = sqlite3Strlen30(zName); #ifndef SQLITE_OMIT_VIRTUALTABLE /* This call is Ok even if this savepoint is actually a transaction ** savepoint (and therefore should not prompt xSavepoint()) callbacks. ** If this is a transaction savepoint being opened, it is guaranteed ** that the db->aVTrans[] array is empty. */ assert( db->autoCommit==0 || db->nVTrans==0 ); rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, db->nStatement+db->nSavepoint); if( rc!=SQLITE_OK ) goto abort_due_to_error; #endif /* Create a new savepoint structure. */ pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1); if( pNew ){ pNew->zName = (char *)&pNew[1]; memcpy(pNew->zName, zName, nName+1); /* If there is no open transaction, then mark this as a special ** "transaction savepoint". */ if( db->autoCommit ){ db->autoCommit = 0; db->isTransactionSavepoint = 1; }else{ db->nSavepoint++; } /* Link the new savepoint into the database handle's list. */ pNew->pNext = db->pSavepoint; db->pSavepoint = pNew; pNew->nDeferredCons = db->nDeferredCons; pNew->nDeferredImmCons = db->nDeferredImmCons; } } }else{ iSavepoint = 0; /* Find the named savepoint. If there is no such savepoint, then an ** an error is returned to the user. */ for( pSavepoint = db->pSavepoint; pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName); pSavepoint = pSavepoint->pNext ){ iSavepoint++; } if( !pSavepoint ){ sqlite3VdbeError(p, "no such savepoint: %s", zName); rc = SQLITE_ERROR; }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){ /* It is not possible to release (commit) a savepoint if there are ** active write statements. */ sqlite3VdbeError(p, "cannot release savepoint - " "SQL statements in progress"); rc = SQLITE_BUSY; }else{ /* Determine whether or not this is a transaction savepoint. If so, ** and this is a RELEASE command, then the current transaction ** is committed. */ int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint; if( isTransaction && p1==SAVEPOINT_RELEASE ){ if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ goto vdbe_return; } db->autoCommit = 1; if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ p->pc = (int)(pOp - aOp); db->autoCommit = 0; p->rc = rc = SQLITE_BUSY; goto vdbe_return; } db->isTransactionSavepoint = 0; rc = p->rc; }else{ int isSchemaChange; iSavepoint = db->nSavepoint - iSavepoint - 1; if( p1==SAVEPOINT_ROLLBACK ){ isSchemaChange = (db->flags & SQLITE_InternChanges)!=0; for(ii=0; ii<db->nDb; ii++){ rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT_ROLLBACK, isSchemaChange==0); if( rc!=SQLITE_OK ) goto abort_due_to_error; } }else{ isSchemaChange = 0; } for(ii=0; ii<db->nDb; ii++){ rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } } if( isSchemaChange ){ sqlite3ExpirePreparedStatements(db); sqlite3ResetAllSchemasOfConnection(db); db->flags = (db->flags | SQLITE_InternChanges); } } /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all ** savepoints nested inside of the savepoint being operated on. */ while( db->pSavepoint!=pSavepoint ){ pTmp = db->pSavepoint; db->pSavepoint = pTmp->pNext; sqlite3DbFree(db, pTmp); db->nSavepoint--; } /* If it is a RELEASE, then destroy the savepoint being operated on ** too. If it is a ROLLBACK TO, then set the number of deferred ** constraint violations present in the database to the value stored ** when the savepoint was created. */ if( p1==SAVEPOINT_RELEASE ){ assert( pSavepoint==db->pSavepoint ); db->pSavepoint = pSavepoint->pNext; sqlite3DbFree(db, pSavepoint); if( !isTransaction ){ db->nSavepoint--; } }else{ db->nDeferredCons = pSavepoint->nDeferredCons; db->nDeferredImmCons = pSavepoint->nDeferredImmCons; } if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){ rc = sqlite3VtabSavepoint(db, p1, iSavepoint); if( rc!=SQLITE_OK ) goto abort_due_to_error; } } } if( rc ) goto abort_due_to_error; break; } /* Opcode: AutoCommit P1 P2 * * * ** ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll ** back any currently active btree transactions. If there are any active ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if ** there are active writing VMs or active VMs that use shared cache. ** ** This instruction causes the VM to halt. */ case OP_AutoCommit: { int desiredAutoCommit; int iRollback; desiredAutoCommit = pOp->p1; iRollback = pOp->p2; assert( desiredAutoCommit==1 || desiredAutoCommit==0 ); assert( desiredAutoCommit==1 || iRollback==0 ); assert( db->nVdbeActive>0 ); /* At least this one VM is active */ assert( p->bIsReader ); if( desiredAutoCommit!=db->autoCommit ){ if( iRollback ){ assert( desiredAutoCommit==1 ); sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); db->autoCommit = 1; }else if( desiredAutoCommit && db->nVdbeWrite>0 ){ /* If this instruction implements a COMMIT and other VMs are writing ** return an error indicating that the other VMs must complete first. */ sqlite3VdbeError(p, "cannot commit transaction - " "SQL statements in progress"); rc = SQLITE_BUSY; goto abort_due_to_error; }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ goto vdbe_return; }else{ db->autoCommit = (u8)desiredAutoCommit; } if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ p->pc = (int)(pOp - aOp); db->autoCommit = (u8)(1-desiredAutoCommit); p->rc = rc = SQLITE_BUSY; goto vdbe_return; } assert( db->nStatement==0 ); sqlite3CloseSavepoints(db); if( p->rc==SQLITE_OK ){ rc = SQLITE_DONE; }else{ rc = SQLITE_ERROR; } goto vdbe_return; }else{ sqlite3VdbeError(p, (!desiredAutoCommit)?"cannot start a transaction within a transaction":( (iRollback)?"cannot rollback - no transaction is active": "cannot commit - no transaction is active")); rc = SQLITE_ERROR; goto abort_due_to_error; } break; } /* Opcode: Transaction P1 P2 P3 P4 P5 ** ** Begin a transaction on database P1 if a transaction is not already ** active. ** If P2 is non-zero, then a write-transaction is started, or if a ** read-transaction is already active, it is upgraded to a write-transaction. ** If P2 is zero, then a read-transaction is started. ** ** P1 is the index of the database file on which the transaction is ** started. Index 0 is the main database file and index 1 is the ** file used for temporary tables. Indices of 2 or more are used for ** attached databases. ** ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is ** true (this flag is set if the Vdbe may modify more than one row and may ** throw an ABORT exception), a statement transaction may also be opened. ** More specifically, a statement transaction is opened iff the database ** connection is currently not in autocommit mode, or if there are other ** active statements. A statement transaction allows the changes made by this ** VDBE to be rolled back after an error without having to roll back the ** entire transaction. If no error is encountered, the statement transaction ** will automatically commit when the VDBE halts. ** ** If P5!=0 then this opcode also checks the schema cookie against P3 ** and the schema generation counter against P4. ** The cookie changes its value whenever the database schema changes. ** This operation is used to detect when that the cookie has changed ** and that the current process needs to reread the schema. If the schema ** cookie in P3 differs from the schema cookie in the database header or ** if the schema generation counter in P4 differs from the current ** generation counter, then an SQLITE_SCHEMA error is raised and execution ** halts. The sqlite3_step() wrapper function might then reprepare the ** statement and rerun it from the beginning. */ case OP_Transaction: { Btree *pBt; int iMeta; int iGen; assert( p->bIsReader ); assert( p->readOnly==0 || pOp->p2==0 ); assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){ rc = SQLITE_READONLY; goto abort_due_to_error; } pBt = db->aDb[pOp->p1].pBt; if( pBt ){ rc = sqlite3BtreeBeginTrans(pBt, pOp->p2); testcase( rc==SQLITE_BUSY_SNAPSHOT ); testcase( rc==SQLITE_BUSY_RECOVERY ); if( rc!=SQLITE_OK ){ if( (rc&0xff)==SQLITE_BUSY ){ p->pc = (int)(pOp - aOp); p->rc = rc; goto vdbe_return; } goto abort_due_to_error; } if( pOp->p2 && p->usesStmtJournal && (db->autoCommit==0 || db->nVdbeRead>1) ){ assert( sqlite3BtreeIsInTrans(pBt) ); if( p->iStatement==0 ){ assert( db->nStatement>=0 && db->nSavepoint>=0 ); db->nStatement++; p->iStatement = db->nSavepoint + db->nStatement; } rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); if( rc==SQLITE_OK ){ rc = sqlite3BtreeBeginStmt(pBt, p->iStatement); } /* Store the current value of the database handles deferred constraint ** counter. If the statement transaction needs to be rolled back, ** the value of this counter needs to be restored too. */ p->nStmtDefCons = db->nDeferredCons; p->nStmtDefImmCons = db->nDeferredImmCons; } /* Gather the schema version number for checking: ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema ** version is checked to ensure that the schema has not changed since the ** SQL statement was prepared. */ sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta); iGen = db->aDb[pOp->p1].pSchema->iGeneration; }else{ iGen = iMeta = 0; } assert( pOp->p5==0 || pOp->p4type==P4_INT32 ); if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){ sqlite3DbFree(db, p->zErrMsg); p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed"); /* If the schema-cookie from the database file matches the cookie ** stored with the in-memory representation of the schema, do ** not reload the schema from the database file. ** ** If virtual-tables are in use, this is not just an optimization. ** Often, v-tables store their data in other SQLite tables, which ** are queried from within xNext() and other v-table methods using ** prepared queries. If such a query is out-of-date, we do not want to ** discard the database schema, as the user code implementing the ** v-table would have to be ready for the sqlite3_vtab structure itself ** to be invalidated whenever sqlite3_step() is called from within ** a v-table method. */ if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){ sqlite3ResetOneSchema(db, pOp->p1); } p->expired = 1; rc = SQLITE_SCHEMA; } if( rc ) goto abort_due_to_error; break; } /* Opcode: ReadCookie P1 P2 P3 * * ** ** Read cookie number P3 from database P1 and write it into register P2. ** P3==1 is the schema version. P3==2 is the database format. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is ** the main database file and P1==1 is the database file used to store ** temporary tables. ** ** There must be a read-lock on the database (either a transaction ** must be started or there must be an open cursor) before ** executing this instruction. */ case OP_ReadCookie: { /* out2 */ int iMeta; int iDb; int iCookie; assert( p->bIsReader ); iDb = pOp->p1; iCookie = pOp->p3; assert( pOp->p3<SQLITE_N_BTREE_META ); assert( iDb>=0 && iDb<db->nDb ); assert( db->aDb[iDb].pBt!=0 ); assert( DbMaskTest(p->btreeMask, iDb) ); sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta); pOut = out2Prerelease(p, pOp); pOut->u.i = iMeta; break; } /* Opcode: SetCookie P1 P2 P3 * * ** ** Write the integer value P3 into cookie number P2 of database P1. ** P2==1 is the schema version. P2==2 is the database format. ** P2==3 is the recommended pager cache ** size, and so forth. P1==0 is the main database file and P1==1 is the ** database file used to store temporary tables. ** ** A transaction must be started before executing this opcode. */ case OP_SetCookie: { Db *pDb; assert( pOp->p2<SQLITE_N_BTREE_META ); assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pDb = &db->aDb[pOp->p1]; assert( pDb->pBt!=0 ); assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); /* See note about index shifting on OP_ReadCookie */ rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3); if( pOp->p2==BTREE_SCHEMA_VERSION ){ /* When the schema cookie changes, record the new cookie internally */ pDb->pSchema->schema_cookie = pOp->p3; db->flags |= SQLITE_InternChanges; }else if( pOp->p2==BTREE_FILE_FORMAT ){ /* Record changes in the file format */ pDb->pSchema->file_format = pOp->p3; } if( pOp->p1==1 ){ /* Invalidate all prepared statements whenever the TEMP database ** schema is changed. Ticket #1644 */ sqlite3ExpirePreparedStatements(db); p->expired = 0; } if( rc ) goto abort_due_to_error; break; } /* Opcode: OpenRead P1 P2 P3 P4 P5 ** Synopsis: root=P2 iDb=P3 ** ** Open a read-only cursor for the database table whose root page is ** P2 in a database file. The database file is determined by P3. ** P3==0 means the main database, P3==1 means the database used for ** temporary tables, and P3>1 means used the corresponding attached ** database. Give the new cursor an identifier of P1. The P1 ** values need not be contiguous but all P1 values should be small integers. ** It is an error for P1 to be negative. ** ** If P5!=0 then use the content of register P2 as the root page, not ** the value of P2 itself. ** ** There will be a read lock on the database whenever there is an ** open cursor. If the database was unlocked prior to this instruction ** then a read lock is acquired as part of this instruction. A read ** lock allows other processes to read the database but prohibits ** any other process from modifying the database. The read lock is ** released when all cursors are closed. If this instruction attempts ** to get a read lock but fails, the script terminates with an ** SQLITE_BUSY error code. ** ** The P4 value may be either an integer (P4_INT32) or a pointer to ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo ** structure, then said structure defines the content and collating ** sequence of the index being opened. Otherwise, if P4 is an integer ** value, it is set to the number of columns in the table. ** ** See also: OpenWrite, ReopenIdx */ /* Opcode: ReopenIdx P1 P2 P3 P4 P5 ** Synopsis: root=P2 iDb=P3 ** ** The ReopenIdx opcode works exactly like ReadOpen except that it first ** checks to see if the cursor on P1 is already open with a root page ** number of P2 and if it is this opcode becomes a no-op. In other words, ** if the cursor is already open, do not reopen it. ** ** The ReopenIdx opcode may only be used with P5==0 and with P4 being ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as ** every other ReopenIdx or OpenRead for the same cursor number. ** ** See the OpenRead opcode documentation for additional information. */ /* Opcode: OpenWrite P1 P2 P3 P4 P5 ** Synopsis: root=P2 iDb=P3 ** ** Open a read/write cursor named P1 on the table or index whose root ** page is P2. Or if P5!=0 use the content of register P2 to find the ** root page. ** ** The P4 value may be either an integer (P4_INT32) or a pointer to ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo ** structure, then said structure defines the content and collating ** sequence of the index being opened. Otherwise, if P4 is an integer ** value, it is set to the number of columns in the table, or to the ** largest index of any column of the table that is actually used. ** ** This instruction works just like OpenRead except that it opens the cursor ** in read/write mode. For a given table, there can be one or more read-only ** cursors or a single read/write cursor but not both. ** ** See also OpenRead. */ case OP_ReopenIdx: { int nField; KeyInfo *pKeyInfo; int p2; int iDb; int wrFlag; Btree *pX; VdbeCursor *pCur; Db *pDb; assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); assert( pOp->p4type==P4_KEYINFO ); pCur = p->apCsr[pOp->p1]; if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){ assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */ goto open_cursor_set_hints; } /* If the cursor is not currently open or is open on a different ** index, then fall through into OP_OpenRead to force a reopen */ case OP_OpenRead: case OP_OpenWrite: assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); assert( p->bIsReader ); assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx || p->readOnly==0 ); if( p->expired ){ rc = SQLITE_ABORT_ROLLBACK; goto abort_due_to_error; } nField = 0; pKeyInfo = 0; p2 = pOp->p2; iDb = pOp->p3; assert( iDb>=0 && iDb<db->nDb ); assert( DbMaskTest(p->btreeMask, iDb) ); pDb = &db->aDb[iDb]; pX = pDb->pBt; assert( pX!=0 ); if( pOp->opcode==OP_OpenWrite ){ assert( OPFLAG_FORDELETE==BTREE_FORDELETE ); wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( pDb->pSchema->file_format < p->minWriteFileFormat ){ p->minWriteFileFormat = pDb->pSchema->file_format; } }else{ wrFlag = 0; } if( pOp->p5 & OPFLAG_P2ISREG ){ assert( p2>0 ); assert( p2<=(p->nMem+1 - p->nCursor) ); pIn2 = &aMem[p2]; assert( memIsValid(pIn2) ); assert( (pIn2->flags & MEM_Int)!=0 ); sqlite3VdbeMemIntegerify(pIn2); p2 = (int)pIn2->u.i; /* The p2 value always comes from a prior OP_CreateTable opcode and ** that opcode will always set the p2 value to 2 or more or else fail. ** If there were a failure, the prepared statement would have halted ** before reaching this instruction. */ assert( p2>=2 ); } if( pOp->p4type==P4_KEYINFO ){ pKeyInfo = pOp->p4.pKeyInfo; assert( pKeyInfo->enc==ENC(db) ); assert( pKeyInfo->db==db ); nField = pKeyInfo->nField+pKeyInfo->nXField; }else if( pOp->p4type==P4_INT32 ){ nField = pOp->p4.i; } assert( pOp->p1>=0 ); assert( nField>=0 ); testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */ pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE); if( pCur==0 ) goto no_mem; pCur->nullRow = 1; pCur->isOrdered = 1; pCur->pgnoRoot = p2; #ifdef SQLITE_DEBUG pCur->wrFlag = wrFlag; #endif rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor); pCur->pKeyInfo = pKeyInfo; /* Set the VdbeCursor.isTable variable. Previous versions of ** SQLite used to check if the root-page flags were sane at this point ** and report database corruption if they were not, but this check has ** since moved into the btree layer. */ pCur->isTable = pOp->p4type!=P4_KEYINFO; open_cursor_set_hints: assert( OPFLAG_BULKCSR==BTREE_BULKLOAD ); assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ ); testcase( pOp->p5 & OPFLAG_BULKCSR ); #ifdef SQLITE_ENABLE_CURSOR_HINTS testcase( pOp->p2 & OPFLAG_SEEKEQ ); #endif sqlite3BtreeCursorHintFlags(pCur->uc.pCursor, (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ))); if( rc ) goto abort_due_to_error; break; } /* Opcode: OpenEphemeral P1 P2 * P4 P5 ** Synopsis: nColumn=P2 ** ** Open a new cursor P1 to a transient table. ** The cursor is always opened read/write even if ** the main database is read-only. The ephemeral ** table is deleted automatically when the cursor is closed. ** ** P2 is the number of columns in the ephemeral table. ** The cursor points to a BTree table if P4==0 and to a BTree index ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure ** that defines the format of keys in the index. ** ** The P5 parameter can be a mask of the BTREE_* flags defined ** in btree.h. These flags control aspects of the operation of ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are ** added automatically. */ /* Opcode: OpenAutoindex P1 P2 * P4 * ** Synopsis: nColumn=P2 ** ** This opcode works the same as OP_OpenEphemeral. It has a ** different name to distinguish its use. Tables created using ** by this opcode will be used for automatically created transient ** indices in joins. */ case OP_OpenAutoindex: case OP_OpenEphemeral: { VdbeCursor *pCx; KeyInfo *pKeyInfo; static const int vfsFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TRANSIENT_DB; assert( pOp->p1>=0 ); assert( pOp->p2>=0 ); pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE); if( pCx==0 ) goto no_mem; pCx->nullRow = 1; pCx->isEphemeral = 1; rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags); if( rc==SQLITE_OK ){ rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1); } if( rc==SQLITE_OK ){ /* If a transient index is required, create it by calling ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before ** opening it. If a transient table is required, just use the ** automatically created table with root-page 1 (an BLOB_INTKEY table). */ if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){ int pgno; assert( pOp->p4type==P4_KEYINFO ); rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5); if( rc==SQLITE_OK ){ assert( pgno==MASTER_ROOT+1 ); assert( pKeyInfo->db==db ); assert( pKeyInfo->enc==ENC(db) ); rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR, pKeyInfo, pCx->uc.pCursor); } pCx->isTable = 0; }else{ rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR, 0, pCx->uc.pCursor); pCx->isTable = 1; } } if( rc ) goto abort_due_to_error; pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); break; } /* Opcode: SorterOpen P1 P2 P3 P4 * ** ** This opcode works like OP_OpenEphemeral except that it opens ** a transient index that is specifically designed to sort large ** tables using an external merge-sort algorithm. ** ** If argument P3 is non-zero, then it indicates that the sorter may ** assume that a stable sort considering the first P3 fields of each ** key is sufficient to produce the required results. */ case OP_SorterOpen: { VdbeCursor *pCx; assert( pOp->p1>=0 ); assert( pOp->p2>=0 ); pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER); if( pCx==0 ) goto no_mem; pCx->pKeyInfo = pOp->p4.pKeyInfo; assert( pCx->pKeyInfo->db==db ); assert( pCx->pKeyInfo->enc==ENC(db) ); rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx); if( rc ) goto abort_due_to_error; break; } /* Opcode: SequenceTest P1 P2 * * * ** Synopsis: if( cursor[P1].ctr++ ) pc = P2 ** ** P1 is a sorter cursor. If the sequence counter is currently zero, jump ** to P2. Regardless of whether or not the jump is taken, increment the ** the sequence value. */ case OP_SequenceTest: { VdbeCursor *pC; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); if( (pC->seqCount++)==0 ){ goto jump_to_p2; } break; } /* Opcode: OpenPseudo P1 P2 P3 * * ** Synopsis: P3 columns in r[P2] ** ** Open a new cursor that points to a fake table that contains a single ** row of data. The content of that one row is the content of memory ** register P2. In other words, cursor P1 becomes an alias for the ** MEM_Blob content contained in register P2. ** ** A pseudo-table created by this opcode is used to hold a single ** row output from the sorter so that the row can be decomposed into ** individual columns using the OP_Column opcode. The OP_Column opcode ** is the only cursor opcode that works with a pseudo-table. ** ** P3 is the number of fields in the records that will be stored by ** the pseudo-table. */ case OP_OpenPseudo: { VdbeCursor *pCx; assert( pOp->p1>=0 ); assert( pOp->p3>=0 ); pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO); if( pCx==0 ) goto no_mem; pCx->nullRow = 1; pCx->uc.pseudoTableReg = pOp->p2; pCx->isTable = 1; assert( pOp->p5==0 ); break; } /* Opcode: Close P1 * * * * ** ** Close a cursor previously opened as P1. If P1 is not ** currently open, this instruction is a no-op. */ case OP_Close: { assert( pOp->p1>=0 && pOp->p1<p->nCursor ); sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); p->apCsr[pOp->p1] = 0; break; } #ifdef SQLITE_ENABLE_COLUMN_USED_MASK /* Opcode: ColumnsUsed P1 * * P4 * ** ** This opcode (which only exists if SQLite was compiled with ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the ** table or index for cursor P1 are used. P4 is a 64-bit integer ** (P4_INT64) in which the first 63 bits are one for each of the ** first 63 columns of the table or index that are actually used ** by the cursor. The high-order bit is set if any column after ** the 64th is used. */ case OP_ColumnsUsed: { VdbeCursor *pC; pC = p->apCsr[pOp->p1]; assert( pC->eCurType==CURTYPE_BTREE ); pC->maskUsed = *(u64*)pOp->p4.pI64; break; } #endif /* Opcode: SeekGE P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as the key. If cursor P1 refers ** to an SQL index, then P3 is the first in an array of P4 registers ** that are used as an unpacked index key. ** ** Reposition cursor P1 so that it points to the smallest entry that ** is greater than or equal to the key value. If there are no records ** greater than or equal to the key and P2 is not zero, then jump to P2. ** ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this ** opcode will always land on a record that equally equals the key, or ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this ** opcode must be followed by an IdxLE opcode with the same arguments. ** The IdxLE opcode will be skipped if this opcode succeeds, but the ** IdxLE opcode will be used on subsequent loop iterations. ** ** This opcode leaves the cursor configured to move in forward order, ** from the beginning toward the end. In other words, the cursor is ** configured to use Next, not Prev. ** ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe */ /* Opcode: SeekGT P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers ** to an SQL index, then P3 is the first in an array of P4 registers ** that are used as an unpacked index key. ** ** Reposition cursor P1 so that it points to the smallest entry that ** is greater than the key value. If there are no records greater than ** the key and P2 is not zero, then jump to P2. ** ** This opcode leaves the cursor configured to move in forward order, ** from the beginning toward the end. In other words, the cursor is ** configured to use Next, not Prev. ** ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe */ /* Opcode: SeekLT P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers ** to an SQL index, then P3 is the first in an array of P4 registers ** that are used as an unpacked index key. ** ** Reposition cursor P1 so that it points to the largest entry that ** is less than the key value. If there are no records less than ** the key and P2 is not zero, then jump to P2. ** ** This opcode leaves the cursor configured to move in reverse order, ** from the end toward the beginning. In other words, the cursor is ** configured to use Prev, not Next. ** ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe */ /* Opcode: SeekLE P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), ** use the value in register P3 as a key. If cursor P1 refers ** to an SQL index, then P3 is the first in an array of P4 registers ** that are used as an unpacked index key. ** ** Reposition cursor P1 so that it points to the largest entry that ** is less than or equal to the key value. If there are no records ** less than or equal to the key and P2 is not zero, then jump to P2. ** ** This opcode leaves the cursor configured to move in reverse order, ** from the end toward the beginning. In other words, the cursor is ** configured to use Prev, not Next. ** ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this ** opcode will always land on a record that equally equals the key, or ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this ** opcode must be followed by an IdxGE opcode with the same arguments. ** The IdxGE opcode will be skipped if this opcode succeeds, but the ** IdxGE opcode will be used on subsequent loop iterations. ** ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt */ case OP_SeekLT: /* jump, in3 */ case OP_SeekLE: /* jump, in3 */ case OP_SeekGE: /* jump, in3 */ case OP_SeekGT: { /* jump, in3 */ int res; /* Comparison result */ int oc; /* Opcode */ VdbeCursor *pC; /* The cursor to seek */ UnpackedRecord r; /* The key to seek for */ int nField; /* Number of columns or fields in the key */ i64 iKey; /* The rowid we are to seek to */ int eqOnly; /* Only interested in == results */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( pOp->p2!=0 ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( OP_SeekLE == OP_SeekLT+1 ); assert( OP_SeekGE == OP_SeekLT+2 ); assert( OP_SeekGT == OP_SeekLT+3 ); assert( pC->isOrdered ); assert( pC->uc.pCursor!=0 ); oc = pOp->opcode; eqOnly = 0; pC->nullRow = 0; #ifdef SQLITE_DEBUG pC->seekOp = pOp->opcode; #endif if( pC->isTable ){ /* The BTREE_SEEK_EQ flag is only set on index cursors */ assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 || CORRUPT_DB ); /* The input value in P3 might be of any type: integer, real, string, ** blob, or NULL. But it needs to be an integer before we can do ** the seek, so convert it. */ pIn3 = &aMem[pOp->p3]; if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn3, 0); } iKey = sqlite3VdbeIntValue(pIn3); /* If the P3 value could not be converted into an integer without ** loss of information, then special processing is required... */ if( (pIn3->flags & MEM_Int)==0 ){ if( (pIn3->flags & MEM_Real)==0 ){ /* If the P3 value cannot be converted into any kind of a number, ** then the seek is not possible, so jump to P2 */ VdbeBranchTaken(1,2); goto jump_to_p2; break; } /* If the approximation iKey is larger than the actual real search ** term, substitute >= for > and < for <=. e.g. if the search term ** is 4.9 and the integer approximation 5: ** ** (x > 4.9) -> (x >= 5) ** (x <= 4.9) -> (x < 5) */ if( pIn3->u.r<(double)iKey ){ assert( OP_SeekGE==(OP_SeekGT-1) ); assert( OP_SeekLT==(OP_SeekLE-1) ); assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) ); if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--; } /* If the approximation iKey is smaller than the actual real search ** term, substitute <= for < and > for >=. */ else if( pIn3->u.r>(double)iKey ){ assert( OP_SeekLE==(OP_SeekLT+1) ); assert( OP_SeekGT==(OP_SeekGE+1) ); assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) ); if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++; } } rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res); pC->movetoTarget = iKey; /* Used by OP_Delete */ if( rc!=SQLITE_OK ){ goto abort_due_to_error; } }else{ /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and ** OP_SeekLE opcodes are allowed, and these must be immediately followed ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key. */ if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){ eqOnly = 1; assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE ); assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); assert( pOp[1].p1==pOp[0].p1 ); assert( pOp[1].p2==pOp[0].p2 ); assert( pOp[1].p3==pOp[0].p3 ); assert( pOp[1].p4.i==pOp[0].p4.i ); } nField = pOp->p4.i; assert( pOp->p4type==P4_INT32 ); assert( nField>0 ); r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)nField; /* The next line of code computes as follows, only faster: ** if( oc==OP_SeekGT || oc==OP_SeekLE ){ ** r.default_rc = -1; ** }else{ ** r.default_rc = +1; ** } */ r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1); assert( oc!=OP_SeekGT || r.default_rc==-1 ); assert( oc!=OP_SeekLE || r.default_rc==-1 ); assert( oc!=OP_SeekGE || r.default_rc==+1 ); assert( oc!=OP_SeekLT || r.default_rc==+1 ); r.aMem = &aMem[pOp->p3]; #ifdef SQLITE_DEBUG { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } #endif r.eqSeen = 0; rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } if( eqOnly && r.eqSeen==0 ){ assert( res!=0 ); goto seek_not_found; } } pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; #ifdef SQLITE_TEST sqlite3_search_count++; #endif if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT ); if( res<0 || (res==0 && oc==OP_SeekGT) ){ res = 0; rc = sqlite3BtreeNext(pC->uc.pCursor, &res); if( rc!=SQLITE_OK ) goto abort_due_to_error; }else{ res = 0; } }else{ assert( oc==OP_SeekLT || oc==OP_SeekLE ); if( res>0 || (res==0 && oc==OP_SeekLT) ){ res = 0; rc = sqlite3BtreePrevious(pC->uc.pCursor, &res); if( rc!=SQLITE_OK ) goto abort_due_to_error; }else{ /* res might be negative because the table is empty. Check to ** see if this is the case. */ res = sqlite3BtreeEof(pC->uc.pCursor); } } seek_not_found: assert( pOp->p2>0 ); VdbeBranchTaken(res!=0,2); if( res ){ goto jump_to_p2; }else if( eqOnly ){ assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */ } break; } /* Opcode: Found P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If ** P4>0 then register P3 is the first of P4 registers that form an unpacked ** record. ** ** Cursor P1 is on an index btree. If the record identified by P3 and P4 ** is a prefix of any entry in P1 then a jump is made to P2 and ** P1 is left pointing at the matching entry. ** ** This operation leaves the cursor in a state where it can be ** advanced in the forward direction. The Next instruction will work, ** but not the Prev instruction. ** ** See also: NotFound, NoConflict, NotExists. SeekGe */ /* Opcode: NotFound P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If ** P4>0 then register P3 is the first of P4 registers that form an unpacked ** record. ** ** Cursor P1 is on an index btree. If the record identified by P3 and P4 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1 ** does contain an entry whose prefix matches the P3/P4 record then control ** falls through to the next instruction and P1 is left pointing at the ** matching entry. ** ** This operation leaves the cursor in a state where it cannot be ** advanced in either direction. In other words, the Next and Prev ** opcodes do not work after this operation. ** ** See also: Found, NotExists, NoConflict */ /* Opcode: NoConflict P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If ** P4>0 then register P3 is the first of P4 registers that form an unpacked ** record. ** ** Cursor P1 is on an index btree. If the record identified by P3 and P4 ** contains any NULL value, jump immediately to P2. If all terms of the ** record are not-NULL then a check is done to determine if any row in the ** P1 index btree has a matching key prefix. If there are no matches, jump ** immediately to P2. If there is a match, fall through and leave the P1 ** cursor pointing to the matching row. ** ** This opcode is similar to OP_NotFound with the exceptions that the ** branch is always taken if any part of the search key input is NULL. ** ** This operation leaves the cursor in a state where it cannot be ** advanced in either direction. In other words, the Next and Prev ** opcodes do not work after this operation. ** ** See also: NotFound, Found, NotExists */ case OP_NoConflict: /* jump, in3 */ case OP_NotFound: /* jump, in3 */ case OP_Found: { /* jump, in3 */ int alreadyExists; int takeJump; int ii; VdbeCursor *pC; int res; UnpackedRecord *pFree; UnpackedRecord *pIdxKey; UnpackedRecord r; #ifdef SQLITE_TEST if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++; #endif assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( pOp->p4type==P4_INT32 ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); #ifdef SQLITE_DEBUG pC->seekOp = pOp->opcode; #endif pIn3 = &aMem[pOp->p3]; assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->isTable==0 ); if( pOp->p4.i>0 ){ r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)pOp->p4.i; r.aMem = pIn3; #ifdef SQLITE_DEBUG for(ii=0; ii<r.nField; ii++){ assert( memIsValid(&r.aMem[ii]) ); assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 ); if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]); } #endif pIdxKey = &r; pFree = 0; }else{ pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo); if( pIdxKey==0 ) goto no_mem; assert( pIn3->flags & MEM_Blob ); (void)ExpandBlob(pIn3); sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); } pIdxKey->default_rc = 0; takeJump = 0; if( pOp->opcode==OP_NoConflict ){ /* For the OP_NoConflict opcode, take the jump if any of the ** input fields are NULL, since any key with a NULL will not ** conflict */ for(ii=0; ii<pIdxKey->nField; ii++){ if( pIdxKey->aMem[ii].flags & MEM_Null ){ takeJump = 1; break; } } } rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res); if( pFree ) sqlite3DbFree(db, pFree); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } pC->seekResult = res; alreadyExists = (res==0); pC->nullRow = 1-alreadyExists; pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; if( pOp->opcode==OP_Found ){ VdbeBranchTaken(alreadyExists!=0,2); if( alreadyExists ) goto jump_to_p2; }else{ VdbeBranchTaken(takeJump||alreadyExists==0,2); if( takeJump || !alreadyExists ) goto jump_to_p2; } break; } /* Opcode: SeekRowid P1 P2 P3 * * ** Synopsis: intkey=r[P3] ** ** P1 is the index of a cursor open on an SQL table btree (with integer ** keys). If register P3 does not contain an integer or if P1 does not ** contain a record with rowid P3 then jump immediately to P2. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain ** a record with rowid P3 then ** leave the cursor pointing at that record and fall through to the next ** instruction. ** ** The OP_NotExists opcode performs the same operation, but with OP_NotExists ** the P3 register must be guaranteed to contain an integer value. With this ** opcode, register P3 might not contain an integer. ** ** The OP_NotFound opcode performs the same operation on index btrees ** (with arbitrary multi-value keys). ** ** This opcode leaves the cursor in a state where it cannot be advanced ** in either direction. In other words, the Next and Prev opcodes will ** not work following this opcode. ** ** See also: Found, NotFound, NoConflict, SeekRowid */ /* Opcode: NotExists P1 P2 P3 * * ** Synopsis: intkey=r[P3] ** ** P1 is the index of a cursor open on an SQL table btree (with integer ** keys). P3 is an integer rowid. If P1 does not contain a record with ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then ** leave the cursor pointing at that record and fall through to the next ** instruction. ** ** The OP_SeekRowid opcode performs the same operation but also allows the ** P3 register to contain a non-integer value, in which case the jump is ** always taken. This opcode requires that P3 always contain an integer. ** ** The OP_NotFound opcode performs the same operation on index btrees ** (with arbitrary multi-value keys). ** ** This opcode leaves the cursor in a state where it cannot be advanced ** in either direction. In other words, the Next and Prev opcodes will ** not work following this opcode. ** ** See also: Found, NotFound, NoConflict, SeekRowid */ case OP_SeekRowid: { /* jump, in3 */ VdbeCursor *pC; BtCursor *pCrsr; int res; u64 iKey; pIn3 = &aMem[pOp->p3]; if( (pIn3->flags & MEM_Int)==0 ){ applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding); if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2; } /* Fall through into OP_NotExists */ case OP_NotExists: /* jump, in3 */ pIn3 = &aMem[pOp->p3]; assert( pIn3->flags & MEM_Int ); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); #ifdef SQLITE_DEBUG pC->seekOp = 0; #endif assert( pC->isTable ); assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; assert( pCrsr!=0 ); res = 0; iKey = pIn3->u.i; rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); assert( rc==SQLITE_OK || res==0 ); pC->movetoTarget = iKey; /* Used by OP_Delete */ pC->nullRow = 0; pC->cacheStatus = CACHE_STALE; pC->deferredMoveto = 0; VdbeBranchTaken(res!=0,2); pC->seekResult = res; if( res!=0 ){ assert( rc==SQLITE_OK ); if( pOp->p2==0 ){ rc = SQLITE_CORRUPT_BKPT; }else{ goto jump_to_p2; } } if( rc ) goto abort_due_to_error; break; } /* Opcode: Sequence P1 P2 * * * ** Synopsis: r[P2]=cursor[P1].ctr++ ** ** Find the next available sequence number for cursor P1. ** Write the sequence number into register P2. ** The sequence number on the cursor is incremented after this ** instruction. */ case OP_Sequence: { /* out2 */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( p->apCsr[pOp->p1]!=0 ); assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB ); pOut = out2Prerelease(p, pOp); pOut->u.i = p->apCsr[pOp->p1]->seqCount++; break; } /* Opcode: NewRowid P1 P2 P3 * * ** Synopsis: r[P2]=rowid ** ** Get a new integer record number (a.k.a "rowid") used as the key to a table. ** The record number is not previously used as a key in the database ** table that cursor P1 points to. The new record number is written ** written to register P2. ** ** If P3>0 then P3 is a register in the root frame of this VDBE that holds ** the largest previously generated record number. No new record numbers are ** allowed to be less than this value. When this value reaches its maximum, ** an SQLITE_FULL error is generated. The P3 register is updated with the ' ** generated record number. This P3 mechanism is used to help implement the ** AUTOINCREMENT feature. */ case OP_NewRowid: { /* out2 */ i64 v; /* The new rowid */ VdbeCursor *pC; /* Cursor of table to get the new rowid */ int res; /* Result of an sqlite3BtreeLast() */ int cnt; /* Counter to limit the number of searches */ Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ VdbeFrame *pFrame; /* Root frame of VDBE */ v = 0; res = 0; pOut = out2Prerelease(p, pOp); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); { /* The next rowid or record number (different terms for the same ** thing) is obtained in a two-step algorithm. ** ** First we attempt to find the largest existing rowid and add one ** to that. But if the largest existing rowid is already the maximum ** positive integer, we have to fall through to the second ** probabilistic algorithm ** ** The second algorithm is to select a rowid at random and see if ** it already exists in the table. If it does not exist, we have ** succeeded. If the random rowid does exist, we select a new one ** and try again, up to 100 times. */ assert( pC->isTable ); #ifdef SQLITE_32BIT_ROWID # define MAX_ROWID 0x7fffffff #else /* Some compilers complain about constants of the form 0x7fffffffffffffff. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems ** to provide the constant while making all compilers happy. */ # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff ) #endif if( !pC->useRandomRowid ){ rc = sqlite3BtreeLast(pC->uc.pCursor, &res); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } if( res ){ v = 1; /* IMP: R-61914-48074 */ }else{ assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) ); v = sqlite3BtreeIntegerKey(pC->uc.pCursor); if( v>=MAX_ROWID ){ pC->useRandomRowid = 1; }else{ v++; /* IMP: R-29538-34987 */ } } } #ifndef SQLITE_OMIT_AUTOINCREMENT if( pOp->p3 ){ /* Assert that P3 is a valid memory cell. */ assert( pOp->p3>0 ); if( p->pFrame ){ for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); /* Assert that P3 is a valid memory cell. */ assert( pOp->p3<=pFrame->nMem ); pMem = &pFrame->aMem[pOp->p3]; }else{ /* Assert that P3 is a valid memory cell. */ assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); pMem = &aMem[pOp->p3]; memAboutToChange(p, pMem); } assert( memIsValid(pMem) ); REGISTER_TRACE(pOp->p3, pMem); sqlite3VdbeMemIntegerify(pMem); assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ rc = SQLITE_FULL; /* IMP: R-17817-00630 */ goto abort_due_to_error; } if( v<pMem->u.i+1 ){ v = pMem->u.i + 1; } pMem->u.i = v; } #endif if( pC->useRandomRowid ){ /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the ** largest possible integer (9223372036854775807) then the database ** engine starts picking positive candidate ROWIDs at random until ** it finds one that is not previously used. */ assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is ** an AUTOINCREMENT table. */ cnt = 0; do{ sqlite3_randomness(sizeof(v), &v); v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */ }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v, 0, &res))==SQLITE_OK) && (res==0) && (++cnt<100)); if( rc ) goto abort_due_to_error; if( res==0 ){ rc = SQLITE_FULL; /* IMP: R-38219-53002 */ goto abort_due_to_error; } assert( v>0 ); /* EV: R-40812-03570 */ } pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; } pOut->u.i = v; break; } /* Opcode: Insert P1 P2 P3 P4 P5 ** Synopsis: intkey=r[P3] data=r[P2] ** ** Write an entry into the table of cursor P1. A new entry is ** created if it doesn't already exist or the data for an existing ** entry is overwritten. The data is the value MEM_Blob stored in register ** number P2. The key is stored in register P3. The key must ** be a MEM_Int. ** ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, ** then rowid is stored for subsequent return by the ** sqlite3_last_insert_rowid() function (otherwise it is unmodified). ** ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might ** run faster by avoiding an unnecessary seek on cursor P1. However, ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior ** seeks on the cursor or if the most recent seek used a key equal to P3. ** ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an ** UPDATE operation. Otherwise (if the flag is clear) then this opcode ** is part of an INSERT operation. The difference is only important to ** the update hook. ** ** Parameter P4 may point to a Table structure, or may be NULL. If it is ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked ** following a successful insert. ** ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically ** allocated, then ownership of P2 is transferred to the pseudo-cursor ** and register P2 becomes ephemeral. If the cursor is changed, the ** value of register P2 will then change. Make sure this does not ** cause any problems.) ** ** This instruction only works on tables. The equivalent instruction ** for indices is OP_IdxInsert. */ /* Opcode: InsertInt P1 P2 P3 P4 P5 ** Synopsis: intkey=P3 data=r[P2] ** ** This works exactly like OP_Insert except that the key is the ** integer value P3, not the value of the integer stored in register P3. */ case OP_Insert: case OP_InsertInt: { Mem *pData; /* MEM cell holding data for the record to be inserted */ Mem *pKey; /* MEM cell holding key for the record */ VdbeCursor *pC; /* Cursor to table into which insert is written */ int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ const char *zDb; /* database name - used by the update hook */ Table *pTab; /* Table structure - used by update and pre-update hooks */ int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ BtreePayload x; /* Payload to be inserted */ op = 0; pData = &aMem[pOp->p2]; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( memIsValid(pData) ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable ); assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC ); REGISTER_TRACE(pOp->p2, pData); if( pOp->opcode==OP_Insert ){ pKey = &aMem[pOp->p3]; assert( pKey->flags & MEM_Int ); assert( memIsValid(pKey) ); REGISTER_TRACE(pOp->p3, pKey); x.nKey = pKey->u.i; }else{ assert( pOp->opcode==OP_InsertInt ); x.nKey = pOp->p3; } if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ assert( pC->iDb>=0 ); zDb = db->aDb[pC->iDb].zDbSName; pTab = pOp->p4.pTab; assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) ); op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); }else{ pTab = 0; /* Not needed. Silence a compiler warning. */ zDb = 0; /* Not needed. Silence a compiler warning. */ } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* Invoke the pre-update hook, if any */ if( db->xPreUpdateCallback && pOp->p4type==P4_TABLE && !(pOp->p5 & OPFLAG_ISUPDATE) ){ sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2); } if( pOp->p5 & OPFLAG_ISNOOP ) break; #endif if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey; if( pData->flags & MEM_Null ){ x.pData = 0; x.nData = 0; }else{ assert( pData->flags & (MEM_Blob|MEM_Str) ); x.pData = pData->z; x.nData = pData->n; } seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0); if( pData->flags & MEM_Zero ){ x.nZero = pData->u.nZero; }else{ x.nZero = 0; } x.pKey = 0; rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult ); pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; /* Invoke the update-hook if required. */ if( rc ) goto abort_due_to_error; if( db->xUpdateCallback && op ){ db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey); } break; } /* Opcode: Delete P1 P2 P3 P4 P5 ** ** Delete the record at which the P1 cursor is currently pointing. ** ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then ** the cursor will be left pointing at either the next or the previous ** record in the table. If it is left pointing at the next record, then ** the next Next instruction will be a no-op. As a result, in this case ** it is ok to delete a record from within a Next loop. If ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be ** left in an undefined state. ** ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this ** delete one of several associated with deleting a table row and all its ** associated index entries. Exactly one of those deletes is the "primary" ** delete. The others are all on OPFLAG_FORDELETE cursors or else are ** marked with the AUXDELETE flag. ** ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row ** change count is incremented (otherwise not). ** ** P1 must not be pseudo-table. It has to be a real table with ** multiple rows. ** ** If P4 is not NULL then it points to a Table object. In this case either ** the update or pre-update hook, or both, may be invoked. The P1 cursor must ** have been positioned using OP_NotFound prior to invoking this opcode in ** this case. Specifically, if one is configured, the pre-update hook is ** invoked if P4 is not NULL. The update-hook is invoked if one is configured, ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2. ** ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address ** of the memory cell that contains the value that the rowid of the row will ** be set to by the update. */ case OP_Delete: { VdbeCursor *pC; const char *zDb; Table *pTab; int opflags; opflags = pOp->p2; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->deferredMoveto==0 ); #ifdef SQLITE_DEBUG if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){ /* If p5 is zero, the seek operation that positioned the cursor prior to ** OP_Delete will have also set the pC->movetoTarget field to the rowid of ** the row that is being deleted */ i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor); assert( pC->movetoTarget==iKey ); } #endif /* If the update-hook or pre-update-hook will be invoked, set zDb to ** the name of the db to pass as to it. Also set local pTab to a copy ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set ** VdbeCursor.movetoTarget to the current rowid. */ if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ assert( pC->iDb>=0 ); assert( pOp->p4.pTab!=0 ); zDb = db->aDb[pC->iDb].zDbSName; pTab = pOp->p4.pTab; if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){ pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor); } }else{ zDb = 0; /* Not needed. Silence a compiler warning. */ pTab = 0; /* Not needed. Silence a compiler warning. */ } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* Invoke the pre-update-hook if required. */ if( db->xPreUpdateCallback && pOp->p4.pTab ){ assert( !(opflags & OPFLAG_ISUPDATE) || HasRowid(pTab)==0 || (aMem[pOp->p3].flags & MEM_Int) ); sqlite3VdbePreUpdateHook(p, pC, (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, zDb, pTab, pC->movetoTarget, pOp->p3 ); } if( opflags & OPFLAG_ISNOOP ) break; #endif /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 ); assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION ); assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE ); #ifdef SQLITE_DEBUG if( p->pFrame==0 ){ if( pC->isEphemeral==0 && (pOp->p5 & OPFLAG_AUXDELETE)==0 && (pC->wrFlag & OPFLAG_FORDELETE)==0 ){ nExtraDelete++; } if( pOp->p2 & OPFLAG_NCHANGE ){ nExtraDelete--; } } #endif rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5); pC->cacheStatus = CACHE_STALE; pC->seekResult = 0; if( rc ) goto abort_due_to_error; /* Invoke the update-hook if required. */ if( opflags & OPFLAG_NCHANGE ){ p->nChange++; if( db->xUpdateCallback && HasRowid(pTab) ){ db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName, pC->movetoTarget); assert( pC->iDb>=0 ); } } break; } /* Opcode: ResetCount * * * * * ** ** The value of the change counter is copied to the database handle ** change counter (returned by subsequent calls to sqlite3_changes()). ** Then the VMs internal change counter resets to 0. ** This is used by trigger programs. */ case OP_ResetCount: { sqlite3VdbeSetChanges(db, p->nChange); p->nChange = 0; break; } /* Opcode: SorterCompare P1 P2 P3 P4 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2 ** ** P1 is a sorter cursor. This instruction compares a prefix of the ** record blob in register P3 against a prefix of the entry that ** the sorter cursor currently points to. Only the first P4 fields ** of r[P3] and the sorter record are compared. ** ** If either P3 or the sorter contains a NULL in one of their significant ** fields (not counting the P4 fields at the end which are ignored) then ** the comparison is assumed to be equal. ** ** Fall through to next instruction if the two records compare equal to ** each other. Jump to P2 if they are different. */ case OP_SorterCompare: { VdbeCursor *pC; int res; int nKeyCol; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); assert( pOp->p4type==P4_INT32 ); pIn3 = &aMem[pOp->p3]; nKeyCol = pOp->p4.i; res = 0; rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res); VdbeBranchTaken(res!=0,2); if( rc ) goto abort_due_to_error; if( res ) goto jump_to_p2; break; }; /* Opcode: SorterData P1 P2 P3 * * ** Synopsis: r[P2]=data ** ** Write into register P2 the current sorter data for sorter cursor P1. ** Then clear the column header cache on cursor P3. ** ** This opcode is normally use to move a record out of the sorter and into ** a register that is the source for a pseudo-table cursor created using ** OpenPseudo. That pseudo-table cursor is the one that is identified by ** parameter P3. Clearing the P3 column cache as part of this opcode saves ** us from having to issue a separate NullRow instruction to clear that cache. */ case OP_SorterData: { VdbeCursor *pC; pOut = &aMem[pOp->p2]; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); rc = sqlite3VdbeSorterRowkey(pC, pOut); assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) ); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); if( rc ) goto abort_due_to_error; p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE; break; } /* Opcode: RowData P1 P2 P3 * * ** Synopsis: r[P2]=data ** ** Write into register P2 the complete row content for the row at ** which cursor P1 is currently pointing. ** There is no interpretation of the data. ** It is just copied onto the P2 register exactly as ** it is found in the database file. ** ** If cursor P1 is an index, then the content is the key of the row. ** If cursor P2 is a table, then the content extracted is the data. ** ** If the P1 cursor must be pointing to a valid row (not a NULL row) ** of a real table, not a pseudo-table. ** ** If P3!=0 then this opcode is allowed to make an ephermeral pointer ** into the database page. That means that the content of the output ** register will be invalidated as soon as the cursor moves - including ** moves caused by other cursors that "save" the the current cursors ** position in order that they can write to the same table. If P3==0 ** then a copy of the data is made into memory. P3!=0 is faster, but ** P3==0 is safer. ** ** If P3!=0 then the content of the P2 register is unsuitable for use ** in OP_Result and any OP_Result will invalidate the P2 register content. ** The P2 register content is invalidated by opcodes like OP_Function or ** by any use of another cursor pointing to the same table. */ case OP_RowData: { VdbeCursor *pC; BtCursor *pCrsr; u32 n; pOut = out2Prerelease(p, pOp); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( isSorter(pC)==0 ); assert( pC->nullRow==0 ); assert( pC->uc.pCursor!=0 ); pCrsr = pC->uc.pCursor; /* The OP_RowData opcodes always follow OP_NotExists or ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions ** that might invalidate the cursor. ** If this where not the case, on of the following assert()s ** would fail. Should this ever change (because of changes in the code ** generator) then the fix would be to insert a call to ** sqlite3VdbeCursorMoveto(). */ assert( pC->deferredMoveto==0 ); assert( sqlite3BtreeCursorIsValid(pCrsr) ); #if 0 /* Not required due to the previous to assert() statements */ rc = sqlite3VdbeCursorMoveto(pC); if( rc!=SQLITE_OK ) goto abort_due_to_error; #endif n = sqlite3BtreePayloadSize(pCrsr); if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } testcase( n==0 ); rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut); if( rc ) goto abort_due_to_error; if( !pOp->p3 ) Deephemeralize(pOut); UPDATE_MAX_BLOBSIZE(pOut); REGISTER_TRACE(pOp->p2, pOut); break; } /* Opcode: Rowid P1 P2 * * * ** Synopsis: r[P2]=rowid ** ** Store in register P2 an integer which is the key of the table entry that ** P1 is currently point to. ** ** P1 can be either an ordinary table or a virtual table. There used to ** be a separate OP_VRowid opcode for use with virtual tables, but this ** one opcode now works for both table types. */ case OP_Rowid: { /* out2 */ VdbeCursor *pC; i64 v; sqlite3_vtab *pVtab; const sqlite3_module *pModule; pOut = out2Prerelease(p, pOp); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); if( pC->nullRow ){ pOut->flags = MEM_Null; break; }else if( pC->deferredMoveto ){ v = pC->movetoTarget; #ifndef SQLITE_OMIT_VIRTUALTABLE }else if( pC->eCurType==CURTYPE_VTAB ){ assert( pC->uc.pVCur!=0 ); pVtab = pC->uc.pVCur->pVtab; pModule = pVtab->pModule; assert( pModule->xRowid ); rc = pModule->xRowid(pC->uc.pVCur, &v); sqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; #endif /* SQLITE_OMIT_VIRTUALTABLE */ }else{ assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); rc = sqlite3VdbeCursorRestore(pC); if( rc ) goto abort_due_to_error; if( pC->nullRow ){ pOut->flags = MEM_Null; break; } v = sqlite3BtreeIntegerKey(pC->uc.pCursor); } pOut->u.i = v; break; } /* Opcode: NullRow P1 * * * * ** ** Move the cursor P1 to a null row. Any OP_Column operations ** that occur while the cursor is on the null row will always ** write a NULL. */ case OP_NullRow: { VdbeCursor *pC; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); pC->nullRow = 1; pC->cacheStatus = CACHE_STALE; if( pC->eCurType==CURTYPE_BTREE ){ assert( pC->uc.pCursor!=0 ); sqlite3BtreeClearCursor(pC->uc.pCursor); } break; } /* Opcode: Last P1 P2 P3 * * ** ** The next use of the Rowid or Column or Prev instruction for P1 ** will refer to the last entry in the database table or index. ** If the table or index is empty and P2>0, then jump immediately to P2. ** If P2 is 0 or if the table or index is not empty, fall through ** to the following instruction. ** ** This opcode leaves the cursor configured to move in reverse order, ** from the end toward the beginning. In other words, the cursor is ** configured to use Prev, not Next. ** ** If P3 is -1, then the cursor is positioned at the end of the btree ** for the purpose of appending a new entry onto the btree. In that ** case P2 must be 0. It is assumed that the cursor is used only for ** appending and so if the cursor is valid, then the cursor must already ** be pointing at the end of the btree and so no changes are made to ** the cursor. */ case OP_Last: { /* jump */ VdbeCursor *pC; BtCursor *pCrsr; int res; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; res = 0; assert( pCrsr!=0 ); pC->seekResult = pOp->p3; #ifdef SQLITE_DEBUG pC->seekOp = OP_Last; #endif if( pOp->p3==0 || !sqlite3BtreeCursorIsValidNN(pCrsr) ){ rc = sqlite3BtreeLast(pCrsr, &res); pC->nullRow = (u8)res; pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; if( rc ) goto abort_due_to_error; if( pOp->p2>0 ){ VdbeBranchTaken(res!=0,2); if( res ) goto jump_to_p2; } }else{ assert( pOp->p2==0 ); } break; } /* Opcode: SorterSort P1 P2 * * * ** ** After all records have been inserted into the Sorter object ** identified by P1, invoke this opcode to actually do the sorting. ** Jump to P2 if there are no records to be sorted. ** ** This opcode is an alias for OP_Sort and OP_Rewind that is used ** for Sorter objects. */ /* Opcode: Sort P1 P2 * * * ** ** This opcode does exactly the same thing as OP_Rewind except that ** it increments an undocumented global variable used for testing. ** ** Sorting is accomplished by writing records into a sorting index, ** then rewinding that index and playing it back from beginning to ** end. We use the OP_Sort opcode instead of OP_Rewind to do the ** rewinding so that the global variable will be incremented and ** regression tests can determine whether or not the optimizer is ** correctly optimizing out sorts. */ case OP_SorterSort: /* jump */ case OP_Sort: { /* jump */ #ifdef SQLITE_TEST sqlite3_sort_count++; sqlite3_search_count--; #endif p->aCounter[SQLITE_STMTSTATUS_SORT]++; /* Fall through into OP_Rewind */ } /* Opcode: Rewind P1 P2 * * * ** ** The next use of the Rowid or Column or Next instruction for P1 ** will refer to the first entry in the database table or index. ** If the table or index is empty, jump immediately to P2. ** If the table or index is not empty, fall through to the following ** instruction. ** ** This opcode leaves the cursor configured to move in forward order, ** from the beginning toward the end. In other words, the cursor is ** configured to use Next, not Prev. */ case OP_Rewind: { /* jump */ VdbeCursor *pC; BtCursor *pCrsr; int res; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) ); res = 1; #ifdef SQLITE_DEBUG pC->seekOp = OP_Rewind; #endif if( isSorter(pC) ){ rc = sqlite3VdbeSorterRewind(pC, &res); }else{ assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; assert( pCrsr ); rc = sqlite3BtreeFirst(pCrsr, &res); pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; } if( rc ) goto abort_due_to_error; pC->nullRow = (u8)res; assert( pOp->p2>0 && pOp->p2<p->nOp ); VdbeBranchTaken(res!=0,2); if( res ) goto jump_to_p2; break; } /* Opcode: Next P1 P2 P3 P4 P5 ** ** Advance cursor P1 so that it points to the next key/data pair in its ** table or index. If there are no more key/value pairs then fall through ** to the following instruction. But if the cursor advance was successful, ** jump immediately to P2. ** ** The Next opcode is only valid following an SeekGT, SeekGE, or ** OP_Rewind opcode used to position the cursor. Next is not allowed ** to follow SeekLT, SeekLE, or OP_Last. ** ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have ** been opened prior to this opcode or the program will segfault. ** ** The P3 value is a hint to the btree implementation. If P3==1, that ** means P1 is an SQL index and that this instruction could have been ** omitted if that index had been unique. P3 is usually 0. P3 is ** always either 0 or 1. ** ** P4 is always of type P4_ADVANCE. The function pointer points to ** sqlite3BtreeNext(). ** ** If P5 is positive and the jump is taken, then event counter ** number P5-1 in the prepared statement is incremented. ** ** See also: Prev, NextIfOpen */ /* Opcode: NextIfOpen P1 P2 P3 P4 P5 ** ** This opcode works just like Next except that if cursor P1 is not ** open it behaves a no-op. */ /* Opcode: Prev P1 P2 P3 P4 P5 ** ** Back up cursor P1 so that it points to the previous key/data pair in its ** table or index. If there is no previous key/value pairs then fall through ** to the following instruction. But if the cursor backup was successful, ** jump immediately to P2. ** ** ** The Prev opcode is only valid following an SeekLT, SeekLE, or ** OP_Last opcode used to position the cursor. Prev is not allowed ** to follow SeekGT, SeekGE, or OP_Rewind. ** ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is ** not open then the behavior is undefined. ** ** The P3 value is a hint to the btree implementation. If P3==1, that ** means P1 is an SQL index and that this instruction could have been ** omitted if that index had been unique. P3 is usually 0. P3 is ** always either 0 or 1. ** ** P4 is always of type P4_ADVANCE. The function pointer points to ** sqlite3BtreePrevious(). ** ** If P5 is positive and the jump is taken, then event counter ** number P5-1 in the prepared statement is incremented. */ /* Opcode: PrevIfOpen P1 P2 P3 P4 P5 ** ** This opcode works just like Prev except that if cursor P1 is not ** open it behaves a no-op. */ /* Opcode: SorterNext P1 P2 * * P5 ** ** This opcode works just like OP_Next except that P1 must be a ** sorter object for which the OP_SorterSort opcode has been ** invoked. This opcode advances the cursor to the next sorted ** record, or jumps to P2 if there are no more sorted records. */ case OP_SorterNext: { /* jump */ VdbeCursor *pC; int res; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); res = 0; rc = sqlite3VdbeSorterNext(db, pC, &res); goto next_tail; case OP_PrevIfOpen: /* jump */ case OP_NextIfOpen: /* jump */ if( p->apCsr[pOp->p1]==0 ) break; /* Fall through */ case OP_Prev: /* jump */ case OP_Next: /* jump */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( pOp->p5<ArraySize(p->aCounter) ); pC = p->apCsr[pOp->p1]; res = pOp->p3; assert( pC!=0 ); assert( pC->deferredMoveto==0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( res==0 || (res==1 && pC->isTable==0) ); testcase( res==1 ); assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext ); assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious ); assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext ); assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious); /* The Next opcode is only used after SeekGT, SeekGE, and Rewind. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */ assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found); assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE || pC->seekOp==OP_Last ); rc = pOp->p4.xAdvance(pC->uc.pCursor, &res); next_tail: pC->cacheStatus = CACHE_STALE; VdbeBranchTaken(res==0,2); if( rc ) goto abort_due_to_error; if( res==0 ){ pC->nullRow = 0; p->aCounter[pOp->p5]++; #ifdef SQLITE_TEST sqlite3_search_count++; #endif goto jump_to_p2_and_check_for_interrupt; }else{ pC->nullRow = 1; } goto check_for_interrupt; } /* Opcode: IdxInsert P1 P2 P3 P4 P5 ** Synopsis: key=r[P2] ** ** Register P2 holds an SQL index key made using the ** MakeRecord instructions. This opcode writes that key ** into the index P1. Data for the entry is nil. ** ** If P4 is not zero, then it is the number of values in the unpacked ** key of reg(P2). In that case, P3 is the index of the first register ** for the unpacked key. The availability of the unpacked key can sometimes ** be an optimization. ** ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer ** that this insert is likely to be an append. ** ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear, ** then the change counter is unchanged. ** ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might ** run faster by avoiding an unnecessary seek on cursor P1. However, ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior ** seeks on the cursor or if the most recent seek used a key equivalent ** to P2. ** ** This instruction only works for indices. The equivalent instruction ** for tables is OP_Insert. */ /* Opcode: SorterInsert P1 P2 * * * ** Synopsis: key=r[P2] ** ** Register P2 holds an SQL index key made using the ** MakeRecord instructions. This opcode writes that key ** into the sorter P1. Data for the entry is nil. */ case OP_SorterInsert: /* in2 */ case OP_IdxInsert: { /* in2 */ VdbeCursor *pC; BtreePayload x; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) ); pIn2 = &aMem[pOp->p2]; assert( pIn2->flags & MEM_Blob ); if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert ); assert( pC->isTable==0 ); rc = ExpandBlob(pIn2); if( rc ) goto abort_due_to_error; if( pOp->opcode==OP_SorterInsert ){ rc = sqlite3VdbeSorterWrite(pC, pIn2); }else{ x.nKey = pIn2->n; x.pKey = pIn2->z; x.aMem = aMem + pOp->p3; x.nMem = (u16)pOp->p4.i; rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) ); assert( pC->deferredMoveto==0 ); pC->cacheStatus = CACHE_STALE; } if( rc) goto abort_due_to_error; break; } /* Opcode: IdxDelete P1 P2 P3 * * ** Synopsis: key=r[P2@P3] ** ** The content of P3 registers starting at register P2 form ** an unpacked index key. This opcode removes that entry from the ** index opened by cursor P1. */ case OP_IdxDelete: { VdbeCursor *pC; BtCursor *pCrsr; int res; UnpackedRecord r; assert( pOp->p3>0 ); assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 ); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; assert( pCrsr!=0 ); assert( pOp->p5==0 ); r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)pOp->p3; r.default_rc = 0; r.aMem = &aMem[pOp->p2]; rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); if( rc ) goto abort_due_to_error; if( res==0 ){ rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); if( rc ) goto abort_due_to_error; } assert( pC->deferredMoveto==0 ); pC->cacheStatus = CACHE_STALE; pC->seekResult = 0; break; } /* Opcode: Seek P1 * P3 P4 * ** Synopsis: Move P3 to P1.rowid ** ** P1 is an open index cursor and P3 is a cursor on the corresponding ** table. This opcode does a deferred seek of the P3 table cursor ** to the row that corresponds to the current row of P1. ** ** This is a deferred seek. Nothing actually happens until ** the cursor is used to read a record. That way, if no reads ** occur, no unnecessary I/O happens. ** ** P4 may be an array of integers (type P4_INTARRAY) containing ** one entry for each column in the P3 table. If array entry a(i) ** is non-zero, then reading column a(i)-1 from cursor P3 is ** equivalent to performing the deferred seek and then reading column i ** from P1. This information is stored in P3 and used to redirect ** reads against P3 over to P1, thus possibly avoiding the need to ** seek and read cursor P3. */ /* Opcode: IdxRowid P1 P2 * * * ** Synopsis: r[P2]=rowid ** ** Write into register P2 an integer which is the last entry in the record at ** the end of the index key pointed to by cursor P1. This integer should be ** the rowid of the table entry to which this index entry points. ** ** See also: Rowid, MakeRecord. */ case OP_Seek: case OP_IdxRowid: { /* out2 */ VdbeCursor *pC; /* The P1 index cursor */ VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */ i64 rowid; /* Rowid that P1 current points to */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->isTable==0 ); assert( pC->deferredMoveto==0 ); assert( !pC->nullRow || pOp->opcode==OP_IdxRowid ); /* The IdxRowid and Seek opcodes are combined because of the commonality ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */ rc = sqlite3VdbeCursorRestore(pC); /* sqlite3VbeCursorRestore() can only fail if the record has been deleted ** out from under the cursor. That will never happens for an IdxRowid ** or Seek opcode */ if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; if( !pC->nullRow ){ rowid = 0; /* Not needed. Only used to silence a warning. */ rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } if( pOp->opcode==OP_Seek ){ assert( pOp->p3>=0 && pOp->p3<p->nCursor ); pTabCur = p->apCsr[pOp->p3]; assert( pTabCur!=0 ); assert( pTabCur->eCurType==CURTYPE_BTREE ); assert( pTabCur->uc.pCursor!=0 ); assert( pTabCur->isTable ); pTabCur->nullRow = 0; pTabCur->movetoTarget = rowid; pTabCur->deferredMoveto = 1; assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 ); pTabCur->aAltMap = pOp->p4.ai; pTabCur->pAltCursor = pC; }else{ pOut = out2Prerelease(p, pOp); pOut->u.i = rowid; } }else{ assert( pOp->opcode==OP_IdxRowid ); sqlite3VdbeMemSetNull(&aMem[pOp->p2]); } break; } /* Opcode: IdxGE P1 P2 P3 P4 P5 ** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the PRIMARY KEY. Compare this key value against the index ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID ** fields at the end. ** ** If the P1 index entry is greater than or equal to the key value ** then jump to P2. Otherwise fall through to the next instruction. */ /* Opcode: IdxGT P1 P2 P3 P4 P5 ** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the PRIMARY KEY. Compare this key value against the index ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID ** fields at the end. ** ** If the P1 index entry is greater than the key value ** then jump to P2. Otherwise fall through to the next instruction. */ /* Opcode: IdxLT P1 P2 P3 P4 P5 ** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the PRIMARY KEY or ROWID. Compare this key value against ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or ** ROWID on the P1 index. ** ** If the P1 index entry is less than the key value then jump to P2. ** Otherwise fall through to the next instruction. */ /* Opcode: IdxLE P1 P2 P3 P4 P5 ** Synopsis: key=r[P3@P4] ** ** The P4 register values beginning with P3 form an unpacked index ** key that omits the PRIMARY KEY or ROWID. Compare this key value against ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or ** ROWID on the P1 index. ** ** If the P1 index entry is less than or equal to the key value then jump ** to P2. Otherwise fall through to the next instruction. */ case OP_IdxLE: /* jump */ case OP_IdxGT: /* jump */ case OP_IdxLT: /* jump */ case OP_IdxGE: { /* jump */ VdbeCursor *pC; int res; UnpackedRecord r; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->isOrdered ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0); assert( pC->deferredMoveto==0 ); assert( pOp->p5==0 || pOp->p5==1 ); assert( pOp->p4type==P4_INT32 ); r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)pOp->p4.i; if( pOp->opcode<OP_IdxLT ){ assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT ); r.default_rc = -1; }else{ assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT ); r.default_rc = 0; } r.aMem = &aMem[pOp->p3]; #ifdef SQLITE_DEBUG { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } #endif res = 0; /* Not needed. Only used to silence a warning. */ rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res); assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) ); if( (pOp->opcode&1)==(OP_IdxLT&1) ){ assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT ); res = -res; }else{ assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT ); res++; } VdbeBranchTaken(res>0,2); if( rc ) goto abort_due_to_error; if( res>0 ) goto jump_to_p2; break; } /* Opcode: Destroy P1 P2 P3 * * ** ** Delete an entire database table or index whose root page in the database ** file is given by P1. ** ** The table being destroyed is in the main database file if P3==0. If ** P3==1 then the table to be clear is in the auxiliary database file ** that is used to store tables create using CREATE TEMPORARY TABLE. ** ** If AUTOVACUUM is enabled then it is possible that another root page ** might be moved into the newly deleted root page in order to keep all ** root pages contiguous at the beginning of the database. The former ** value of the root page that moved - its value before the move occurred - ** is stored in register P2. If no page ** movement was required (because the table being dropped was already ** the last one in the database) then a zero is stored in register P2. ** If AUTOVACUUM is disabled then a zero is stored in register P2. ** ** See also: Clear */ case OP_Destroy: { /* out2 */ int iMoved; int iDb; assert( p->readOnly==0 ); assert( pOp->p1>1 ); pOut = out2Prerelease(p, pOp); pOut->flags = MEM_Null; if( db->nVdbeRead > db->nVDestroy+1 ){ rc = SQLITE_LOCKED; p->errorAction = OE_Abort; goto abort_due_to_error; }else{ iDb = pOp->p3; assert( DbMaskTest(p->btreeMask, iDb) ); iMoved = 0; /* Not needed. Only to silence a warning. */ rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); pOut->flags = MEM_Int; pOut->u.i = iMoved; if( rc ) goto abort_due_to_error; #ifndef SQLITE_OMIT_AUTOVACUUM if( iMoved!=0 ){ sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); /* All OP_Destroy operations occur on the same btree */ assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 ); resetSchemaOnFault = iDb+1; } #endif } break; } /* Opcode: Clear P1 P2 P3 ** ** Delete all contents of the database table or index whose root page ** in the database file is given by P1. But, unlike Destroy, do not ** remove the table or index from the database file. ** ** The table being clear is in the main database file if P2==0. If ** P2==1 then the table to be clear is in the auxiliary database file ** that is used to store tables create using CREATE TEMPORARY TABLE. ** ** If the P3 value is non-zero, then the table referred to must be an ** intkey table (an SQL table, not an index). In this case the row change ** count is incremented by the number of rows in the table being cleared. ** If P3 is greater than zero, then the value stored in register P3 is ** also incremented by the number of rows in the table being cleared. ** ** See also: Destroy */ case OP_Clear: { int nChange; nChange = 0; assert( p->readOnly==0 ); assert( DbMaskTest(p->btreeMask, pOp->p2) ); rc = sqlite3BtreeClearTable( db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0) ); if( pOp->p3 ){ p->nChange += nChange; if( pOp->p3>0 ){ assert( memIsValid(&aMem[pOp->p3]) ); memAboutToChange(p, &aMem[pOp->p3]); aMem[pOp->p3].u.i += nChange; } } if( rc ) goto abort_due_to_error; break; } /* Opcode: ResetSorter P1 * * * * ** ** Delete all contents from the ephemeral table or sorter ** that is open on cursor P1. ** ** This opcode only works for cursors used for sorting and ** opened with OP_OpenEphemeral or OP_SorterOpen. */ case OP_ResetSorter: { VdbeCursor *pC; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); if( isSorter(pC) ){ sqlite3VdbeSorterReset(db, pC->uc.pSorter); }else{ assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->isEphemeral ); rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor); if( rc ) goto abort_due_to_error; } break; } /* Opcode: CreateTable P1 P2 * * * ** Synopsis: r[P2]=root iDb=P1 ** ** Allocate a new table in the main database file if P1==0 or in the ** auxiliary database file if P1==1 or in an attached database if ** P1>1. Write the root page number of the new table into ** register P2 ** ** The difference between a table and an index is this: A table must ** have a 4-byte integer key and can have arbitrary data. An index ** has an arbitrary key but no data. ** ** See also: CreateIndex */ /* Opcode: CreateIndex P1 P2 * * * ** Synopsis: r[P2]=root iDb=P1 ** ** Allocate a new index in the main database file if P1==0 or in the ** auxiliary database file if P1==1 or in an attached database if ** P1>1. Write the root page number of the new table into ** register P2. ** ** See documentation on OP_CreateTable for additional information. */ case OP_CreateIndex: /* out2 */ case OP_CreateTable: { /* out2 */ int pgno; int flags; Db *pDb; pOut = out2Prerelease(p, pOp); pgno = 0; assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pDb = &db->aDb[pOp->p1]; assert( pDb->pBt!=0 ); if( pOp->opcode==OP_CreateTable ){ /* flags = BTREE_INTKEY; */ flags = BTREE_INTKEY; }else{ flags = BTREE_BLOBKEY; } rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags); if( rc ) goto abort_due_to_error; pOut->u.i = pgno; break; } /* Opcode: ParseSchema P1 * * P4 * ** ** Read and parse all entries from the SQLITE_MASTER table of database P1 ** that match the WHERE clause P4. ** ** This opcode invokes the parser to create a new virtual machine, ** then runs the new virtual machine. It is thus a re-entrant opcode. */ case OP_ParseSchema: { int iDb; const char *zMaster; char *zSql; InitData initData; /* Any prepared statement that invokes this opcode will hold mutexes ** on every btree. This is a prerequisite for invoking ** sqlite3InitCallback(). */ #ifdef SQLITE_DEBUG for(iDb=0; iDb<db->nDb; iDb++){ assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); } #endif iDb = pOp->p1; assert( iDb>=0 && iDb<db->nDb ); assert( DbHasProperty(db, iDb, DB_SchemaLoaded) ); /* Used to be a conditional */ { zMaster = MASTER_NAME; initData.db = db; initData.iDb = pOp->p1; initData.pzErrMsg = &p->zErrMsg; zSql = sqlite3MPrintf(db, "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid", db->aDb[iDb].zDbSName, zMaster, pOp->p4.z); if( zSql==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ assert( db->init.busy==0 ); db->init.busy = 1; initData.rc = SQLITE_OK; assert( !db->mallocFailed ); rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); if( rc==SQLITE_OK ) rc = initData.rc; sqlite3DbFree(db, zSql); db->init.busy = 0; } } if( rc ){ sqlite3ResetAllSchemasOfConnection(db); if( rc==SQLITE_NOMEM ){ goto no_mem; } goto abort_due_to_error; } break; } #if !defined(SQLITE_OMIT_ANALYZE) /* Opcode: LoadAnalysis P1 * * * * ** ** Read the sqlite_stat1 table for database P1 and load the content ** of that table into the internal index hash table. This will cause ** the analysis to be used when preparing all subsequent queries. */ case OP_LoadAnalysis: { assert( pOp->p1>=0 && pOp->p1<db->nDb ); rc = sqlite3AnalysisLoad(db, pOp->p1); if( rc ) goto abort_due_to_error; break; } #endif /* !defined(SQLITE_OMIT_ANALYZE) */ /* Opcode: DropTable P1 * * P4 * ** ** Remove the internal (in-memory) data structures that describe ** the table named P4 in database P1. This is called after a table ** is dropped from disk (using the Destroy opcode) in order to keep ** the internal representation of the ** schema consistent with what is on disk. */ case OP_DropTable: { sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); break; } /* Opcode: DropIndex P1 * * P4 * ** ** Remove the internal (in-memory) data structures that describe ** the index named P4 in database P1. This is called after an index ** is dropped from disk (using the Destroy opcode) ** in order to keep the internal representation of the ** schema consistent with what is on disk. */ case OP_DropIndex: { sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); break; } /* Opcode: DropTrigger P1 * * P4 * ** ** Remove the internal (in-memory) data structures that describe ** the trigger named P4 in database P1. This is called after a trigger ** is dropped from disk (using the Destroy opcode) in order to keep ** the internal representation of the ** schema consistent with what is on disk. */ case OP_DropTrigger: { sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); break; } #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* Opcode: IntegrityCk P1 P2 P3 P4 P5 ** ** Do an analysis of the currently open database. Store in ** register P1 the text of an error message describing any problems. ** If no problems are found, store a NULL in register P1. ** ** The register P3 contains the maximum number of allowed errors. ** At most reg(P3) errors will be reported. ** In other words, the analysis stops as soon as reg(P1) errors are ** seen. Reg(P1) is updated with the number of errors remaining. ** ** The root page numbers of all tables in the database are integers ** stored in P4_INTARRAY argument. ** ** If P5 is not zero, the check is done on the auxiliary database ** file, not the main database file. ** ** This opcode is used to implement the integrity_check pragma. */ case OP_IntegrityCk: { int nRoot; /* Number of tables to check. (Number of root pages.) */ int *aRoot; /* Array of rootpage numbers for tables to be checked */ int nErr; /* Number of errors reported */ char *z; /* Text of the error report */ Mem *pnErr; /* Register keeping track of errors remaining */ assert( p->bIsReader ); nRoot = pOp->p2; aRoot = pOp->p4.ai; assert( nRoot>0 ); assert( aRoot[nRoot]==0 ); assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pnErr = &aMem[pOp->p3]; assert( (pnErr->flags & MEM_Int)!=0 ); assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 ); pIn1 = &aMem[pOp->p1]; assert( pOp->p5<db->nDb ); assert( DbMaskTest(p->btreeMask, pOp->p5) ); z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot, (int)pnErr->u.i, &nErr); pnErr->u.i -= nErr; sqlite3VdbeMemSetNull(pIn1); if( nErr==0 ){ assert( z==0 ); }else if( z==0 ){ goto no_mem; }else{ sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free); } UPDATE_MAX_BLOBSIZE(pIn1); sqlite3VdbeChangeEncoding(pIn1, encoding); break; } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* Opcode: RowSetAdd P1 P2 * * * ** Synopsis: rowset(P1)=r[P2] ** ** Insert the integer value held by register P2 into a boolean index ** held in register P1. ** ** An assertion fails if P2 is not an integer. */ case OP_RowSetAdd: { /* in1, in2 */ pIn1 = &aMem[pOp->p1]; pIn2 = &aMem[pOp->p2]; assert( (pIn2->flags & MEM_Int)!=0 ); if( (pIn1->flags & MEM_RowSet)==0 ){ sqlite3VdbeMemSetRowSet(pIn1); if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; } sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i); break; } /* Opcode: RowSetRead P1 P2 P3 * * ** Synopsis: r[P3]=rowset(P1) ** ** Extract the smallest value from boolean index P1 and put that value into ** register P3. Or, if boolean index P1 is initially empty, leave P3 ** unchanged and jump to instruction P2. */ case OP_RowSetRead: { /* jump, in1, out3 */ i64 val; pIn1 = &aMem[pOp->p1]; if( (pIn1->flags & MEM_RowSet)==0 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0 ){ /* The boolean index is empty */ sqlite3VdbeMemSetNull(pIn1); VdbeBranchTaken(1,2); goto jump_to_p2_and_check_for_interrupt; }else{ /* A value was pulled from the index */ VdbeBranchTaken(0,2); sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); } goto check_for_interrupt; } /* Opcode: RowSetTest P1 P2 P3 P4 ** Synopsis: if r[P3] in rowset(P1) goto P2 ** ** Register P3 is assumed to hold a 64-bit integer value. If register P1 ** contains a RowSet object and that RowSet object contains ** the value held in P3, jump to register P2. Otherwise, insert the ** integer in P3 into the RowSet and continue on to the ** next opcode. ** ** The RowSet object is optimized for the case where successive sets ** of integers, where each set contains no duplicates. Each set ** of values is identified by a unique P4 value. The first set ** must have P4==0, the final set P4=-1. P4 must be either -1 or ** non-negative. For non-negative values of P4 only the lower 4 ** bits are significant. ** ** This allows optimizations: (a) when P4==0 there is no need to test ** the rowset object for P3, as it is guaranteed not to contain it, ** (b) when P4==-1 there is no need to insert the value, as it will ** never be tested for, and (c) when a value that is part of set X is ** inserted, there is no need to search to see if the same value was ** previously inserted as part of set X (only if it was previously ** inserted as part of some other set). */ case OP_RowSetTest: { /* jump, in1, in3 */ int iSet; int exists; pIn1 = &aMem[pOp->p1]; pIn3 = &aMem[pOp->p3]; iSet = pOp->p4.i; assert( pIn3->flags&MEM_Int ); /* If there is anything other than a rowset object in memory cell P1, ** delete it now and initialize P1 with an empty rowset */ if( (pIn1->flags & MEM_RowSet)==0 ){ sqlite3VdbeMemSetRowSet(pIn1); if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; } assert( pOp->p4type==P4_INT32 ); assert( iSet==-1 || iSet>=0 ); if( iSet ){ exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i); VdbeBranchTaken(exists!=0,2); if( exists ) goto jump_to_p2; } if( iSet>=0 ){ sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i); } break; } #ifndef SQLITE_OMIT_TRIGGER /* Opcode: Program P1 P2 P3 P4 P5 ** ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). ** ** P1 contains the address of the memory cell that contains the first memory ** cell in an array of values used as arguments to the sub-program. P2 ** contains the address to jump to if the sub-program throws an IGNORE ** exception using the RAISE() function. Register P3 contains the address ** of a memory cell in this (the parent) VM that is used to allocate the ** memory required by the sub-vdbe at runtime. ** ** P4 is a pointer to the VM containing the trigger program. ** ** If P5 is non-zero, then recursive program invocation is enabled. */ case OP_Program: { /* jump */ int nMem; /* Number of memory registers for sub-program */ int nByte; /* Bytes of runtime space required for sub-program */ Mem *pRt; /* Register to allocate runtime space */ Mem *pMem; /* Used to iterate through memory cells */ Mem *pEnd; /* Last memory cell in new array */ VdbeFrame *pFrame; /* New vdbe frame to execute in */ SubProgram *pProgram; /* Sub-program to execute */ void *t; /* Token identifying trigger */ pProgram = pOp->p4.pProgram; pRt = &aMem[pOp->p3]; assert( pProgram->nOp>0 ); /* If the p5 flag is clear, then recursive invocation of triggers is ** disabled for backwards compatibility (p5 is set if this sub-program ** is really a trigger, not a foreign key action, and the flag set ** and cleared by the "PRAGMA recursive_triggers" command is clear). ** ** It is recursive invocation of triggers, at the SQL level, that is ** disabled. In some cases a single trigger may generate more than one ** SubProgram (if the trigger may be executed with more than one different ** ON CONFLICT algorithm). SubProgram structures associated with a ** single trigger all have the same value for the SubProgram.token ** variable. */ if( pOp->p5 ){ t = pProgram->token; for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent); if( pFrame ) break; } if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ rc = SQLITE_ERROR; sqlite3VdbeError(p, "too many levels of trigger recursion"); goto abort_due_to_error; } /* Register pRt is used to store the memory required to save the state ** of the current program, and the memory required at runtime to execute ** the trigger program. If this trigger has been fired before, then pRt ** is already allocated. Otherwise, it must be initialized. */ if( (pRt->flags&MEM_Frame)==0 ){ /* SubProgram.nMem is set to the number of memory cells used by the ** program stored in SubProgram.aOp. As well as these, one memory ** cell is required for each cursor used by the program. Set local ** variable nMem (and later, VdbeFrame.nChildMem) to this value. */ nMem = pProgram->nMem + pProgram->nCsr; assert( nMem>0 ); if( pProgram->nCsr==0 ) nMem++; nByte = ROUND8(sizeof(VdbeFrame)) + nMem * sizeof(Mem) + pProgram->nCsr * sizeof(VdbeCursor *); pFrame = sqlite3DbMallocZero(db, nByte); if( !pFrame ){ goto no_mem; } sqlite3VdbeMemRelease(pRt); pRt->flags = MEM_Frame; pRt->u.pFrame = pFrame; pFrame->v = p; pFrame->nChildMem = nMem; pFrame->nChildCsr = pProgram->nCsr; pFrame->pc = (int)(pOp - aOp); pFrame->aMem = p->aMem; pFrame->nMem = p->nMem; pFrame->apCsr = p->apCsr; pFrame->nCursor = p->nCursor; pFrame->aOp = p->aOp; pFrame->nOp = p->nOp; pFrame->token = pProgram->token; #ifdef SQLITE_ENABLE_STMT_SCANSTATUS pFrame->anExec = p->anExec; #endif pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ pMem->flags = MEM_Undefined; pMem->db = db; } }else{ pFrame = pRt->u.pFrame; assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) ); assert( pProgram->nCsr==pFrame->nChildCsr ); assert( (int)(pOp - aOp)==pFrame->pc ); } p->nFrame++; pFrame->pParent = p->pFrame; pFrame->lastRowid = db->lastRowid; pFrame->nChange = p->nChange; pFrame->nDbChange = p->db->nChange; assert( pFrame->pAuxData==0 ); pFrame->pAuxData = p->pAuxData; p->pAuxData = 0; p->nChange = 0; p->pFrame = pFrame; p->aMem = aMem = VdbeFrameMem(pFrame); p->nMem = pFrame->nChildMem; p->nCursor = (u16)pFrame->nChildCsr; p->apCsr = (VdbeCursor **)&aMem[p->nMem]; p->aOp = aOp = pProgram->aOp; p->nOp = pProgram->nOp; #ifdef SQLITE_ENABLE_STMT_SCANSTATUS p->anExec = 0; #endif pOp = &aOp[-1]; break; } /* Opcode: Param P1 P2 * * * ** ** This opcode is only ever present in sub-programs called via the ** OP_Program instruction. Copy a value currently stored in a memory ** cell of the calling (parent) frame to cell P2 in the current frames ** address space. This is used by trigger programs to access the new.* ** and old.* values. ** ** The address of the cell in the parent frame is determined by adding ** the value of the P1 argument to the value of the P1 argument to the ** calling OP_Program instruction. */ case OP_Param: { /* out2 */ VdbeFrame *pFrame; Mem *pIn; pOut = out2Prerelease(p, pOp); pFrame = p->pFrame; pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1]; sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); break; } #endif /* #ifndef SQLITE_OMIT_TRIGGER */ #ifndef SQLITE_OMIT_FOREIGN_KEY /* Opcode: FkCounter P1 P2 * * * ** Synopsis: fkctr[P1]+=P2 ** ** Increment a "constraint counter" by P2 (P2 may be negative or positive). ** If P1 is non-zero, the database constraint counter is incremented ** (deferred foreign key constraints). Otherwise, if P1 is zero, the ** statement counter is incremented (immediate foreign key constraints). */ case OP_FkCounter: { if( db->flags & SQLITE_DeferFKs ){ db->nDeferredImmCons += pOp->p2; }else if( pOp->p1 ){ db->nDeferredCons += pOp->p2; }else{ p->nFkConstraint += pOp->p2; } break; } /* Opcode: FkIfZero P1 P2 * * * ** Synopsis: if fkctr[P1]==0 goto P2 ** ** This opcode tests if a foreign key constraint-counter is currently zero. ** If so, jump to instruction P2. Otherwise, fall through to the next ** instruction. ** ** If P1 is non-zero, then the jump is taken if the database constraint-counter ** is zero (the one that counts deferred constraint violations). If P1 is ** zero, the jump is taken if the statement constraint-counter is zero ** (immediate foreign key constraint violations). */ case OP_FkIfZero: { /* jump */ if( pOp->p1 ){ VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2); if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; }else{ VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2); if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; } break; } #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ #ifndef SQLITE_OMIT_AUTOINCREMENT /* Opcode: MemMax P1 P2 * * * ** Synopsis: r[P1]=max(r[P1],r[P2]) ** ** P1 is a register in the root frame of this VM (the root frame is ** different from the current frame if this instruction is being executed ** within a sub-program). Set the value of register P1 to the maximum of ** its current value and the value in register P2. ** ** This instruction throws an error if the memory cell is not initially ** an integer. */ case OP_MemMax: { /* in2 */ VdbeFrame *pFrame; if( p->pFrame ){ for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); pIn1 = &pFrame->aMem[pOp->p1]; }else{ pIn1 = &aMem[pOp->p1]; } assert( memIsValid(pIn1) ); sqlite3VdbeMemIntegerify(pIn1); pIn2 = &aMem[pOp->p2]; sqlite3VdbeMemIntegerify(pIn2); if( pIn1->u.i<pIn2->u.i){ pIn1->u.i = pIn2->u.i; } break; } #endif /* SQLITE_OMIT_AUTOINCREMENT */ /* Opcode: IfPos P1 P2 P3 * * ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 ** ** Register P1 must contain an integer. ** If the value of register P1 is 1 or greater, subtract P3 from the ** value in P1 and jump to P2. ** ** If the initial value of register P1 is less than 1, then the ** value is unchanged and control passes through to the next instruction. */ case OP_IfPos: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags&MEM_Int ); VdbeBranchTaken( pIn1->u.i>0, 2); if( pIn1->u.i>0 ){ pIn1->u.i -= pOp->p3; goto jump_to_p2; } break; } /* Opcode: OffsetLimit P1 P2 P3 * * ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) ** ** This opcode performs a commonly used computation associated with ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3] ** holds the offset counter. The opcode computes the combined value ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2] ** value computed is the total number of rows that will need to be ** visited in order to complete the query. ** ** If r[P3] is zero or negative, that means there is no OFFSET ** and r[P2] is set to be the value of the LIMIT, r[P1]. ** ** if r[P1] is zero or negative, that means there is no LIMIT ** and r[P2] is set to -1. ** ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3]. */ case OP_OffsetLimit: { /* in1, out2, in3 */ i64 x; pIn1 = &aMem[pOp->p1]; pIn3 = &aMem[pOp->p3]; pOut = out2Prerelease(p, pOp); assert( pIn1->flags & MEM_Int ); assert( pIn3->flags & MEM_Int ); x = pIn1->u.i; if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){ /* If the LIMIT is less than or equal to zero, loop forever. This ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then ** also loop forever. This is undocumented. In fact, one could argue ** that the loop should terminate. But assuming 1 billion iterations ** per second (far exceeding the capabilities of any current hardware) ** it would take nearly 300 years to actually reach the limit. So ** looping forever is a reasonable approximation. */ pOut->u.i = -1; }else{ pOut->u.i = x; } break; } /* Opcode: IfNotZero P1 P2 * * * ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2 ** ** Register P1 must contain an integer. If the content of register P1 is ** initially greater than zero, then decrement the value in register P1. ** If it is non-zero (negative or positive) and then also jump to P2. ** If register P1 is initially zero, leave it unchanged and fall through. */ case OP_IfNotZero: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags&MEM_Int ); VdbeBranchTaken(pIn1->u.i<0, 2); if( pIn1->u.i ){ if( pIn1->u.i>0 ) pIn1->u.i--; goto jump_to_p2; } break; } /* Opcode: DecrJumpZero P1 P2 * * * ** Synopsis: if (--r[P1])==0 goto P2 ** ** Register P1 must hold an integer. Decrement the value in P1 ** and jump to P2 if the new value is exactly zero. */ case OP_DecrJumpZero: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags&MEM_Int ); if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--; VdbeBranchTaken(pIn1->u.i==0, 2); if( pIn1->u.i==0 ) goto jump_to_p2; break; } /* Opcode: AggStep0 * P2 P3 P4 P5 ** Synopsis: accum=r[P3] step(r[P2@P5]) ** ** Execute the step function for an aggregate. The ** function has P5 arguments. P4 is a pointer to the FuncDef ** structure that specifies the function. Register P3 is the ** accumulator. ** ** The P5 arguments are taken from register P2 and its ** successors. */ /* Opcode: AggStep * P2 P3 P4 P5 ** Synopsis: accum=r[P3] step(r[P2@P5]) ** ** Execute the step function for an aggregate. The ** function has P5 arguments. P4 is a pointer to an sqlite3_context ** object that is used to run the function. Register P3 is ** as the accumulator. ** ** The P5 arguments are taken from register P2 and its ** successors. ** ** This opcode is initially coded as OP_AggStep0. On first evaluation, ** the FuncDef stored in P4 is converted into an sqlite3_context and ** the opcode is changed. In this way, the initialization of the ** sqlite3_context only happens once, instead of on each call to the ** step function. */ case OP_AggStep0: { int n; sqlite3_context *pCtx; assert( pOp->p4type==P4_FUNCDEF ); n = pOp->p5; assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n ); pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*)); if( pCtx==0 ) goto no_mem; pCtx->pMem = 0; pCtx->pFunc = pOp->p4.pFunc; pCtx->iOp = (int)(pOp - aOp); pCtx->pVdbe = p; pCtx->argc = n; pOp->p4type = P4_FUNCCTX; pOp->p4.pCtx = pCtx; pOp->opcode = OP_AggStep; /* Fall through into OP_AggStep */ } case OP_AggStep: { int i; sqlite3_context *pCtx; Mem *pMem; Mem t; assert( pOp->p4type==P4_FUNCCTX ); pCtx = pOp->p4.pCtx; pMem = &aMem[pOp->p3]; /* If this function is inside of a trigger, the register array in aMem[] ** might change from one evaluation to the next. The next block of code ** checks to see if the register array has changed, and if so it ** reinitializes the relavant parts of the sqlite3_context object */ if( pCtx->pMem != pMem ){ pCtx->pMem = pMem; for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; } #ifdef SQLITE_DEBUG for(i=0; i<pCtx->argc; i++){ assert( memIsValid(pCtx->argv[i]) ); REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); } #endif pMem->n++; sqlite3VdbeMemInit(&t, db, MEM_Null); pCtx->pOut = &t; pCtx->fErrorOrAux = 0; pCtx->skipFlag = 0; (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */ if( pCtx->fErrorOrAux ){ if( pCtx->isError ){ sqlite3VdbeError(p, "%s", sqlite3_value_text(&t)); rc = pCtx->isError; } sqlite3VdbeMemRelease(&t); if( rc ) goto abort_due_to_error; }else{ assert( t.flags==MEM_Null ); } if( pCtx->skipFlag ){ assert( pOp[-1].opcode==OP_CollSeq ); i = pOp[-1].p1; if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1); } break; } /* Opcode: AggFinal P1 P2 * P4 * ** Synopsis: accum=r[P1] N=P2 ** ** Execute the finalizer function for an aggregate. P1 is ** the memory location that is the accumulator for the aggregate. ** ** P2 is the number of arguments that the step function takes and ** P4 is a pointer to the FuncDef for this function. The P2 ** argument is not used by this opcode. It is only there to disambiguate ** functions that can take varying numbers of arguments. The ** P4 argument is only needed for the degenerate case where ** the step function was not previously called. */ case OP_AggFinal: { Mem *pMem; assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); pMem = &aMem[pOp->p1]; assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); if( rc ){ sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem)); goto abort_due_to_error; } sqlite3VdbeChangeEncoding(pMem, encoding); UPDATE_MAX_BLOBSIZE(pMem); if( sqlite3VdbeMemTooBig(pMem) ){ goto too_big; } break; } #ifndef SQLITE_OMIT_WAL /* Opcode: Checkpoint P1 P2 P3 * * ** ** Checkpoint database P1. This is a no-op if P1 is not currently in ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL, ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns ** SQLITE_BUSY or not, respectively. Write the number of pages in the ** WAL after the checkpoint into mem[P3+1] and the number of pages ** in the WAL that have been checkpointed after the checkpoint ** completes into mem[P3+2]. However on an error, mem[P3+1] and ** mem[P3+2] are initialized to -1. */ case OP_Checkpoint: { int i; /* Loop counter */ int aRes[3]; /* Results */ Mem *pMem; /* Write results here */ assert( p->readOnly==0 ); aRes[0] = 0; aRes[1] = aRes[2] = -1; assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE || pOp->p2==SQLITE_CHECKPOINT_FULL || pOp->p2==SQLITE_CHECKPOINT_RESTART || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE ); rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); if( rc ){ if( rc!=SQLITE_BUSY ) goto abort_due_to_error; rc = SQLITE_OK; aRes[0] = 1; } for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){ sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); } break; }; #endif #ifndef SQLITE_OMIT_PRAGMA /* Opcode: JournalMode P1 P2 P3 * * ** ** Change the journal mode of database P1 to P3. P3 must be one of the ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback ** modes (delete, truncate, persist, off and memory), this is a simple ** operation. No IO is required. ** ** If changing into or out of WAL mode the procedure is more complicated. ** ** Write a string containing the final journal-mode to register P2. */ case OP_JournalMode: { /* out2 */ Btree *pBt; /* Btree to change journal mode of */ Pager *pPager; /* Pager associated with pBt */ int eNew; /* New journal mode */ int eOld; /* The old journal mode */ #ifndef SQLITE_OMIT_WAL const char *zFilename; /* Name of database file for pPager */ #endif pOut = out2Prerelease(p, pOp); eNew = pOp->p3; assert( eNew==PAGER_JOURNALMODE_DELETE || eNew==PAGER_JOURNALMODE_TRUNCATE || eNew==PAGER_JOURNALMODE_PERSIST || eNew==PAGER_JOURNALMODE_OFF || eNew==PAGER_JOURNALMODE_MEMORY || eNew==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_QUERY ); assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( p->readOnly==0 ); pBt = db->aDb[pOp->p1].pBt; pPager = sqlite3BtreePager(pBt); eOld = sqlite3PagerGetJournalMode(pPager); if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld; if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; #ifndef SQLITE_OMIT_WAL zFilename = sqlite3PagerFilename(pPager, 1); /* Do not allow a transition to journal_mode=WAL for a database ** in temporary storage or if the VFS does not support shared memory */ if( eNew==PAGER_JOURNALMODE_WAL && (sqlite3Strlen30(zFilename)==0 /* Temp file */ || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */ ){ eNew = eOld; } if( (eNew!=eOld) && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL) ){ if( !db->autoCommit || db->nVdbeRead>1 ){ rc = SQLITE_ERROR; sqlite3VdbeError(p, "cannot change %s wal mode from within a transaction", (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") ); goto abort_due_to_error; }else{ if( eOld==PAGER_JOURNALMODE_WAL ){ /* If leaving WAL mode, close the log file. If successful, the call ** to PagerCloseWal() checkpoints and deletes the write-ahead-log ** file. An EXCLUSIVE lock may still be held on the database file ** after a successful return. */ rc = sqlite3PagerCloseWal(pPager, db); if( rc==SQLITE_OK ){ sqlite3PagerSetJournalMode(pPager, eNew); } }else if( eOld==PAGER_JOURNALMODE_MEMORY ){ /* Cannot transition directly from MEMORY to WAL. Use mode OFF ** as an intermediate */ sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF); } /* Open a transaction on the database file. Regardless of the journal ** mode, this transaction always uses a rollback journal. */ assert( sqlite3BtreeIsInTrans(pBt)==0 ); if( rc==SQLITE_OK ){ rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); } } } #endif /* ifndef SQLITE_OMIT_WAL */ if( rc ) eNew = eOld; eNew = sqlite3PagerSetJournalMode(pPager, eNew); pOut->flags = MEM_Str|MEM_Static|MEM_Term; pOut->z = (char *)sqlite3JournalModename(eNew); pOut->n = sqlite3Strlen30(pOut->z); pOut->enc = SQLITE_UTF8; sqlite3VdbeChangeEncoding(pOut, encoding); if( rc ) goto abort_due_to_error; break; }; #endif /* SQLITE_OMIT_PRAGMA */ #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) /* Opcode: Vacuum P1 * * * * ** ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more ** for an attached database. The "temp" database may not be vacuumed. */ case OP_Vacuum: { assert( p->readOnly==0 ); rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1); if( rc ) goto abort_due_to_error; break; } #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) /* Opcode: IncrVacuum P1 P2 * * * ** ** Perform a single step of the incremental vacuum procedure on ** the P1 database. If the vacuum has finished, jump to instruction ** P2. Otherwise, fall through to the next instruction. */ case OP_IncrVacuum: { /* jump */ Btree *pBt; assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pBt = db->aDb[pOp->p1].pBt; rc = sqlite3BtreeIncrVacuum(pBt); VdbeBranchTaken(rc==SQLITE_DONE,2); if( rc ){ if( rc!=SQLITE_DONE ) goto abort_due_to_error; rc = SQLITE_OK; goto jump_to_p2; } break; } #endif /* Opcode: Expire P1 * * * * ** ** Cause precompiled statements to expire. When an expired statement ** is executed using sqlite3_step() it will either automatically ** reprepare itself (if it was originally created using sqlite3_prepare_v2()) ** or it will fail with SQLITE_SCHEMA. ** ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, ** then only the currently executing statement is expired. */ case OP_Expire: { if( !pOp->p1 ){ sqlite3ExpirePreparedStatements(db); }else{ p->expired = 1; } break; } #ifndef SQLITE_OMIT_SHARED_CACHE /* Opcode: TableLock P1 P2 P3 P4 * ** Synopsis: iDb=P1 root=P2 write=P3 ** ** Obtain a lock on a particular table. This instruction is only used when ** the shared-cache feature is enabled. ** ** P1 is the index of the database in sqlite3.aDb[] of the database ** on which the lock is acquired. A readlock is obtained if P3==0 or ** a write lock if P3==1. ** ** P2 contains the root-page of the table to lock. ** ** P4 contains a pointer to the name of the table being locked. This is only ** used to generate an error message if the lock cannot be obtained. */ case OP_TableLock: { u8 isWriteLock = (u8)pOp->p3; if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){ int p1 = pOp->p1; assert( p1>=0 && p1<db->nDb ); assert( DbMaskTest(p->btreeMask, p1) ); assert( isWriteLock==0 || isWriteLock==1 ); rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); if( rc ){ if( (rc&0xFF)==SQLITE_LOCKED ){ const char *z = pOp->p4.z; sqlite3VdbeError(p, "database table is locked: %s", z); } goto abort_due_to_error; } } break; } #endif /* SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VBegin * * * P4 * ** ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the ** xBegin method for that table. ** ** Also, whether or not P4 is set, check that this is not being called from ** within a callback to a virtual table xSync() method. If it is, the error ** code will be set to SQLITE_LOCKED. */ case OP_VBegin: { VTable *pVTab; pVTab = pOp->p4.pVtab; rc = sqlite3VtabBegin(db, pVTab); if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab); if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VCreate P1 P2 * * * ** ** P2 is a register that holds the name of a virtual table in database ** P1. Call the xCreate method for that table. */ case OP_VCreate: { Mem sMem; /* For storing the record being decoded */ const char *zTab; /* Name of the virtual table */ memset(&sMem, 0, sizeof(sMem)); sMem.db = db; /* Because P2 is always a static string, it is impossible for the ** sqlite3VdbeMemCopy() to fail */ assert( (aMem[pOp->p2].flags & MEM_Str)!=0 ); assert( (aMem[pOp->p2].flags & MEM_Static)!=0 ); rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]); assert( rc==SQLITE_OK ); zTab = (const char*)sqlite3_value_text(&sMem); assert( zTab || db->mallocFailed ); if( zTab ){ rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg); } sqlite3VdbeMemRelease(&sMem); if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VDestroy P1 * * P4 * ** ** P4 is the name of a virtual table in database P1. Call the xDestroy method ** of that table. */ case OP_VDestroy: { db->nVDestroy++; rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); db->nVDestroy--; if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VOpen P1 * * P4 * ** ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** P1 is a cursor number. This opcode opens a cursor to the virtual ** table and stores that cursor in P1. */ case OP_VOpen: { VdbeCursor *pCur; sqlite3_vtab_cursor *pVCur; sqlite3_vtab *pVtab; const sqlite3_module *pModule; assert( p->bIsReader ); pCur = 0; pVCur = 0; pVtab = pOp->p4.pVtab->pVtab; if( pVtab==0 || NEVER(pVtab->pModule==0) ){ rc = SQLITE_LOCKED; goto abort_due_to_error; } pModule = pVtab->pModule; rc = pModule->xOpen(pVtab, &pVCur); sqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; /* Initialize sqlite3_vtab_cursor base class */ pVCur->pVtab = pVtab; /* Initialize vdbe cursor object */ pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB); if( pCur ){ pCur->uc.pVCur = pVCur; pVtab->nRef++; }else{ assert( db->mallocFailed ); pModule->xClose(pVCur); goto no_mem; } break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VFilter P1 P2 P3 P4 * ** Synopsis: iplan=r[P3] zplan='P4' ** ** P1 is a cursor opened using VOpen. P2 is an address to jump to if ** the filtered result set is empty. ** ** P4 is either NULL or a string that was generated by the xBestIndex ** method of the module. The interpretation of the P4 string is left ** to the module implementation. ** ** This opcode invokes the xFilter method on the virtual table specified ** by P1. The integer query plan parameter to xFilter is stored in register ** P3. Register P3+1 stores the argc parameter to be passed to the ** xFilter method. Registers P3+2..P3+1+argc are the argc ** additional parameters which are passed to ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter. ** ** A jump is made to P2 if the result set after filtering would be empty. */ case OP_VFilter: { /* jump */ int nArg; int iQuery; const sqlite3_module *pModule; Mem *pQuery; Mem *pArgc; sqlite3_vtab_cursor *pVCur; sqlite3_vtab *pVtab; VdbeCursor *pCur; int res; int i; Mem **apArg; pQuery = &aMem[pOp->p3]; pArgc = &pQuery[1]; pCur = p->apCsr[pOp->p1]; assert( memIsValid(pQuery) ); REGISTER_TRACE(pOp->p3, pQuery); assert( pCur->eCurType==CURTYPE_VTAB ); pVCur = pCur->uc.pVCur; pVtab = pVCur->pVtab; pModule = pVtab->pModule; /* Grab the index number and argc parameters */ assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int ); nArg = (int)pArgc->u.i; iQuery = (int)pQuery->u.i; /* Invoke the xFilter method */ res = 0; apArg = p->apArg; for(i = 0; i<nArg; i++){ apArg[i] = &pArgc[i+1]; } rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg); sqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; res = pModule->xEof(pVCur); pCur->nullRow = 0; VdbeBranchTaken(res!=0,2); if( res ) goto jump_to_p2; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VColumn P1 P2 P3 * * ** Synopsis: r[P3]=vcolumn(P2) ** ** Store the value of the P2-th column of ** the row of the virtual-table that the ** P1 cursor is pointing to into register P3. */ case OP_VColumn: { sqlite3_vtab *pVtab; const sqlite3_module *pModule; Mem *pDest; sqlite3_context sContext; VdbeCursor *pCur = p->apCsr[pOp->p1]; assert( pCur->eCurType==CURTYPE_VTAB ); assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pDest = &aMem[pOp->p3]; memAboutToChange(p, pDest); if( pCur->nullRow ){ sqlite3VdbeMemSetNull(pDest); break; } pVtab = pCur->uc.pVCur->pVtab; pModule = pVtab->pModule; assert( pModule->xColumn ); memset(&sContext, 0, sizeof(sContext)); sContext.pOut = pDest; MemSetTypeFlag(pDest, MEM_Null); rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2); sqlite3VtabImportErrmsg(p, pVtab); if( sContext.isError ){ rc = sContext.isError; } sqlite3VdbeChangeEncoding(pDest, encoding); REGISTER_TRACE(pOp->p3, pDest); UPDATE_MAX_BLOBSIZE(pDest); if( sqlite3VdbeMemTooBig(pDest) ){ goto too_big; } if( rc ) goto abort_due_to_error; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VNext P1 P2 * * * ** ** Advance virtual table P1 to the next row in its result set and ** jump to instruction P2. Or, if the virtual table has reached ** the end of its result set, then fall through to the next instruction. */ case OP_VNext: { /* jump */ sqlite3_vtab *pVtab; const sqlite3_module *pModule; int res; VdbeCursor *pCur; res = 0; pCur = p->apCsr[pOp->p1]; assert( pCur->eCurType==CURTYPE_VTAB ); if( pCur->nullRow ){ break; } pVtab = pCur->uc.pVCur->pVtab; pModule = pVtab->pModule; assert( pModule->xNext ); /* Invoke the xNext() method of the module. There is no way for the ** underlying implementation to return an error if one occurs during ** xNext(). Instead, if an error occurs, true is returned (indicating that ** data is available) and the error code returned when xColumn or ** some other method is next invoked on the save virtual table cursor. */ rc = pModule->xNext(pCur->uc.pVCur); sqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; res = pModule->xEof(pCur->uc.pVCur); VdbeBranchTaken(!res,2); if( !res ){ /* If there is data, jump to P2 */ goto jump_to_p2_and_check_for_interrupt; } goto check_for_interrupt; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VRename P1 * * P4 * ** ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** This opcode invokes the corresponding xRename method. The value ** in register P1 is passed as the zName argument to the xRename method. */ case OP_VRename: { sqlite3_vtab *pVtab; Mem *pName; pVtab = pOp->p4.pVtab->pVtab; pName = &aMem[pOp->p1]; assert( pVtab->pModule->xRename ); assert( memIsValid(pName) ); assert( p->readOnly==0 ); REGISTER_TRACE(pOp->p1, pName); assert( pName->flags & MEM_Str ); testcase( pName->enc==SQLITE_UTF8 ); testcase( pName->enc==SQLITE_UTF16BE ); testcase( pName->enc==SQLITE_UTF16LE ); rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8); if( rc ) goto abort_due_to_error; rc = pVtab->pModule->xRename(pVtab, pName->z); sqlite3VtabImportErrmsg(p, pVtab); p->expired = 0; if( rc ) goto abort_due_to_error; break; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VUpdate P1 P2 P3 P4 P5 ** Synopsis: data=r[P3@P2] ** ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** This opcode invokes the corresponding xUpdate method. P2 values ** are contiguous memory cells starting at P3 to pass to the xUpdate ** invocation. The value in register (P3+P2-1) corresponds to the ** p2th element of the argv array passed to xUpdate. ** ** The xUpdate method will do a DELETE or an INSERT or both. ** The argv[0] element (which corresponds to memory cell P3) ** is the rowid of a row to delete. If argv[0] is NULL then no ** deletion occurs. The argv[1] element is the rowid of the new ** row. This can be NULL to have the virtual table select the new ** rowid for itself. The subsequent elements in the array are ** the values of columns in the new row. ** ** If P2==1 then no insert is performed. argv[0] is the rowid of ** a row to delete. ** ** P1 is a boolean flag. If it is set to true and the xUpdate call ** is successful, then the value returned by sqlite3_last_insert_rowid() ** is set to the value of the rowid for the row just inserted. ** ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to ** apply in the case of a constraint failure on an insert or update. */ case OP_VUpdate: { sqlite3_vtab *pVtab; const sqlite3_module *pModule; int nArg; int i; sqlite_int64 rowid; Mem **apArg; Mem *pX; assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace ); assert( p->readOnly==0 ); pVtab = pOp->p4.pVtab->pVtab; if( pVtab==0 || NEVER(pVtab->pModule==0) ){ rc = SQLITE_LOCKED; goto abort_due_to_error; } pModule = pVtab->pModule; nArg = pOp->p2; assert( pOp->p4type==P4_VTAB ); if( ALWAYS(pModule->xUpdate) ){ u8 vtabOnConflict = db->vtabOnConflict; apArg = p->apArg; pX = &aMem[pOp->p3]; for(i=0; i<nArg; i++){ assert( memIsValid(pX) ); memAboutToChange(p, pX); apArg[i] = pX; pX++; } db->vtabOnConflict = pOp->p5; rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); db->vtabOnConflict = vtabOnConflict; sqlite3VtabImportErrmsg(p, pVtab); if( rc==SQLITE_OK && pOp->p1 ){ assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); db->lastRowid = rowid; } if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){ if( pOp->p5==OE_Ignore ){ rc = SQLITE_OK; }else{ p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5); } }else{ p->nChange++; } if( rc ) goto abort_due_to_error; } break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* Opcode: Pagecount P1 P2 * * * ** ** Write the current number of pages in database P1 to memory cell P2. */ case OP_Pagecount: { /* out2 */ pOut = out2Prerelease(p, pOp); pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); break; } #endif #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* Opcode: MaxPgcnt P1 P2 P3 * * ** ** Try to set the maximum page count for database P1 to the value in P3. ** Do not let the maximum page count fall below the current page count and ** do not change the maximum page count value if P3==0. ** ** Store the maximum page count after the change in register P2. */ case OP_MaxPgcnt: { /* out2 */ unsigned int newMax; Btree *pBt; pOut = out2Prerelease(p, pOp); pBt = db->aDb[pOp->p1].pBt; newMax = 0; if( pOp->p3 ){ newMax = sqlite3BtreeLastPage(pBt); if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; } pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); break; } #endif /* Opcode: Init P1 P2 * P4 * ** Synopsis: Start at P2 ** ** Programs contain a single instance of this opcode as the very first ** opcode. ** ** If tracing is enabled (by the sqlite3_trace()) interface, then ** the UTF-8 string contained in P4 is emitted on the trace callback. ** Or if P4 is blank, use the string returned by sqlite3_sql(). ** ** If P2 is not zero, jump to instruction P2. ** ** Increment the value of P1 so that OP_Once opcodes will jump the ** first time they are evaluated for this run. */ case OP_Init: { /* jump */ char *zTrace; int i; /* If the P4 argument is not NULL, then it must be an SQL comment string. ** The "--" string is broken up to prevent false-positives with srcck1.c. ** ** This assert() provides evidence for: ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that ** would have been returned by the legacy sqlite3_trace() interface by ** using the X argument when X begins with "--" and invoking ** sqlite3_expanded_sql(P) otherwise. */ assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 ); assert( pOp==p->aOp ); /* Always instruction 0 */ #ifndef SQLITE_OMIT_TRACE if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0 && !p->doingRerun && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){ #ifndef SQLITE_OMIT_DEPRECATED if( db->mTrace & SQLITE_TRACE_LEGACY ){ void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace; char *z = sqlite3VdbeExpandSql(p, zTrace); x(db->pTraceArg, z); sqlite3_free(z); }else #endif { (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace); } } #ifdef SQLITE_USE_FCNTL_TRACE zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql); if( zTrace ){ int j; for(j=0; j<db->nDb; j++){ if( DbMaskTest(p->btreeMask, j)==0 ) continue; sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace); } } #endif /* SQLITE_USE_FCNTL_TRACE */ #ifdef SQLITE_DEBUG if( (db->flags & SQLITE_SqlTrace)!=0 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){ sqlite3DebugPrintf("SQL-trace: %s\n", zTrace); } #endif /* SQLITE_DEBUG */ #endif /* SQLITE_OMIT_TRACE */ assert( pOp->p2>0 ); if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){ for(i=1; i<p->nOp; i++){ if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0; } pOp->p1 = 0; } pOp->p1++; goto jump_to_p2; } #ifdef SQLITE_ENABLE_CURSOR_HINTS /* Opcode: CursorHint P1 * * P4 * ** ** Provide a hint to cursor P1 that it only needs to return rows that ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer ** to values currently held in registers. TK_COLUMN terms in the P4 ** expression refer to columns in the b-tree to which cursor P1 is pointing. */ case OP_CursorHint: { VdbeCursor *pC; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( pOp->p4type==P4_EXPR ); pC = p->apCsr[pOp->p1]; if( pC ){ assert( pC->eCurType==CURTYPE_BTREE ); sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, pOp->p4.pExpr, aMem); } break; } #endif /* SQLITE_ENABLE_CURSOR_HINTS */ /* Opcode: Noop * * * * * ** ** Do nothing. This instruction is often useful as a jump ** destination. */ /* ** The magic Explain opcode are only inserted when explain==2 (which ** is to say when the EXPLAIN QUERY PLAN syntax is used.) ** This opcode records information from the optimizer. It is the ** the same as a no-op. This opcodesnever appears in a real VM program. */ default: { /* This is really OP_Noop and OP_Explain */ assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); break; } /***************************************************************************** ** The cases of the switch statement above this line should all be indented ** by 6 spaces. But the left-most 6 spaces have been removed to improve the ** readability. From this point on down, the normal indentation rules are ** restored. *****************************************************************************/ } #ifdef VDBE_PROFILE { u64 endTime = sqlite3Hwtime(); if( endTime>start ) pOrigOp->cycles += endTime - start; pOrigOp->cnt++; } #endif /* The following code adds nothing to the actual functionality ** of the program. It is only here for testing and debugging. ** On the other hand, it does burn CPU cycles every time through ** the evaluator loop. So we can leave it out when NDEBUG is defined. */ #ifndef NDEBUG assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] ); #ifdef SQLITE_DEBUG if( db->flags & SQLITE_VdbeTrace ){ u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode]; if( rc!=0 ) printf("rc=%d\n",rc); if( opProperty & (OPFLG_OUT2) ){ registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]); } if( opProperty & OPFLG_OUT3 ){ registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]); } } #endif /* SQLITE_DEBUG */ #endif /* NDEBUG */ } /* The end of the for(;;) loop the loops through opcodes */ /* If we reach this point, it means that execution is finished with ** an error of some kind. */ abort_due_to_error: if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT; assert( rc ); if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){ sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); } p->rc = rc; sqlite3SystemError(db, rc); testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(rc, "statement aborts at %d: [%s] %s", (int)(pOp - aOp), p->zSql, p->zErrMsg); sqlite3VdbeHalt(p); if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db); rc = SQLITE_ERROR; if( resetSchemaOnFault>0 ){ sqlite3ResetOneSchema(db, resetSchemaOnFault-1); } /* This is the only way out of this procedure. We have to ** release the mutexes on btrees that were acquired at the ** top. */ vdbe_return: testcase( nVmStep>0 ); p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep; sqlite3VdbeLeave(p); assert( rc!=SQLITE_OK || nExtraDelete==0 || sqlite3_strlike("DELETE%",p->zSql,0)!=0 ); return rc; /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH ** is encountered. */ too_big: sqlite3VdbeError(p, "string or blob too big"); rc = SQLITE_TOOBIG; goto abort_due_to_error; /* Jump to here if a malloc() fails. */ no_mem: sqlite3OomFault(db); sqlite3VdbeError(p, "out of memory"); rc = SQLITE_NOMEM_BKPT; goto abort_due_to_error; /* Jump to here if the sqlite3_interrupt() API sets the interrupt ** flag. */ abort_due_to_interrupt: assert( db->u1.isInterrupted ); rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; p->rc = rc; sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); goto abort_due_to_error; } /************** End of vdbe.c ************************************************/ /************** Begin file vdbeblob.c ****************************************/ /* ** 2007 May 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to implement incremental BLOB I/O. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #ifndef SQLITE_OMIT_INCRBLOB /* ** Valid sqlite3_blob* handles point to Incrblob structures. */ typedef struct Incrblob Incrblob; struct Incrblob { int nByte; /* Size of open blob, in bytes */ int iOffset; /* Byte offset of blob in cursor data */ u16 iCol; /* Table column this handle is open on */ BtCursor *pCsr; /* Cursor pointing at blob row */ sqlite3_stmt *pStmt; /* Statement holding cursor open */ sqlite3 *db; /* The associated database */ char *zDb; /* Database name */ Table *pTab; /* Table object */ }; /* ** This function is used by both blob_open() and blob_reopen(). It seeks ** the b-tree cursor associated with blob handle p to point to row iRow. ** If successful, SQLITE_OK is returned and subsequent calls to ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row. ** ** If an error occurs, or if the specified row does not exist or does not ** contain a value of type TEXT or BLOB in the column nominated when the ** blob handle was opened, then an error code is returned and *pzErr may ** be set to point to a buffer containing an error message. It is the ** responsibility of the caller to free the error message buffer using ** sqlite3DbFree(). ** ** If an error does occur, then the b-tree cursor is closed. All subsequent ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will ** immediately return SQLITE_ABORT. */ static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){ int rc; /* Error code */ char *zErr = 0; /* Error message */ Vdbe *v = (Vdbe *)p->pStmt; /* Set the value of register r[1] in the SQL statement to integer iRow. ** This is done directly as a performance optimization */ v->aMem[1].flags = MEM_Int; v->aMem[1].u.i = iRow; /* If the statement has been run before (and is paused at the OP_ResultRow) ** then back it up to the point where it does the OP_SeekRowid. This could ** have been down with an extra OP_Goto, but simply setting the program ** counter is faster. */ if( v->pc>3 ){ v->pc = 3; rc = sqlite3VdbeExec(v); }else{ rc = sqlite3_step(p->pStmt); } if( rc==SQLITE_ROW ){ VdbeCursor *pC = v->apCsr[0]; u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0; testcase( pC->nHdrParsed==p->iCol ); testcase( pC->nHdrParsed==p->iCol+1 ); if( type<12 ){ zErr = sqlite3MPrintf(p->db, "cannot open value of type %s", type==0?"null": type==7?"real": "integer" ); rc = SQLITE_ERROR; sqlite3_finalize(p->pStmt); p->pStmt = 0; }else{ p->iOffset = pC->aType[p->iCol + pC->nField]; p->nByte = sqlite3VdbeSerialTypeLen(type); p->pCsr = pC->uc.pCursor; sqlite3BtreeIncrblobCursor(p->pCsr); } } if( rc==SQLITE_ROW ){ rc = SQLITE_OK; }else if( p->pStmt ){ rc = sqlite3_finalize(p->pStmt); p->pStmt = 0; if( rc==SQLITE_OK ){ zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow); rc = SQLITE_ERROR; }else{ zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db)); } } assert( rc!=SQLITE_OK || zErr==0 ); assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE ); *pzErr = zErr; return rc; } /* ** Open a blob handle. */ SQLITE_API int sqlite3_blob_open( sqlite3* db, /* The database connection */ const char *zDb, /* The attached database containing the blob */ const char *zTable, /* The table containing the blob */ const char *zColumn, /* The column containing the blob */ sqlite_int64 iRow, /* The row containing the glob */ int wrFlag, /* True -> read/write access, false -> read-only */ sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ ){ int nAttempt = 0; int iCol; /* Index of zColumn in row-record */ int rc = SQLITE_OK; char *zErr = 0; Table *pTab; Parse *pParse = 0; Incrblob *pBlob = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( ppBlob==0 ){ return SQLITE_MISUSE_BKPT; } #endif *ppBlob = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zTable==0 ){ return SQLITE_MISUSE_BKPT; } #endif wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */ sqlite3_mutex_enter(db->mutex); pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob)); if( !pBlob ) goto blob_open_out; pParse = sqlite3StackAllocRaw(db, sizeof(*pParse)); if( !pParse ) goto blob_open_out; do { memset(pParse, 0, sizeof(Parse)); pParse->db = db; sqlite3DbFree(db, zErr); zErr = 0; sqlite3BtreeEnterAll(db); pTab = sqlite3LocateTable(pParse, 0, zTable, zDb); if( pTab && IsVirtual(pTab) ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable); } if( pTab && !HasRowid(pTab) ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable); } #ifndef SQLITE_OMIT_VIEW if( pTab && pTab->pSelect ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable); } #endif if( !pTab ){ if( pParse->zErrMsg ){ sqlite3DbFree(db, zErr); zErr = pParse->zErrMsg; pParse->zErrMsg = 0; } rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } pBlob->pTab = pTab; pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName; /* Now search pTab for the exact column. */ for(iCol=0; iCol<pTab->nCol; iCol++) { if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ break; } } if( iCol==pTab->nCol ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } /* If the value is being opened for writing, check that the ** column is not indexed, and that it is not part of a foreign key. */ if( wrFlag ){ const char *zFault = 0; Index *pIdx; #ifndef SQLITE_OMIT_FOREIGN_KEY if( db->flags&SQLITE_ForeignKeys ){ /* Check that the column is not part of an FK child key definition. It ** is not necessary to check if it is part of a parent key, as parent ** key columns must be indexed. The check below will pick up this ** case. */ FKey *pFKey; for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ int j; for(j=0; j<pFKey->nCol; j++){ if( pFKey->aCol[j].iFrom==iCol ){ zFault = "foreign key"; } } } } #endif for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int j; for(j=0; j<pIdx->nKeyCol; j++){ /* FIXME: Be smarter about indexes that use expressions */ if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){ zFault = "indexed"; } } } if( zFault ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault); rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } } pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse); assert( pBlob->pStmt || db->mallocFailed ); if( pBlob->pStmt ){ /* This VDBE program seeks a btree cursor to the identified ** db/table/row entry. The reason for using a vdbe program instead ** of writing code to use the b-tree layer directly is that the ** vdbe program will take advantage of the various transaction, ** locking and error handling infrastructure built into the vdbe. ** ** After seeking the cursor, the vdbe executes an OP_ResultRow. ** Code external to the Vdbe then "borrows" the b-tree cursor and ** uses it to implement the blob_read(), blob_write() and ** blob_bytes() functions. ** ** The sqlite3_blob_close() function finalizes the vdbe program, ** which closes the b-tree cursor and (possibly) commits the ** transaction. */ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList openBlob[] = { {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */ {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */ /* blobSeekToRow() will initialize r[1] to the desired rowid */ {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */ {OP_Column, 0, 0, 1}, /* 3 */ {OP_ResultRow, 1, 0, 0}, /* 4 */ {OP_Halt, 0, 0, 0}, /* 5 */ }; Vdbe *v = (Vdbe *)pBlob->pStmt; int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); VdbeOp *aOp; sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag, pTab->pSchema->schema_cookie, pTab->pSchema->iGeneration); sqlite3VdbeChangeP5(v, 1); aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn); /* Make sure a mutex is held on the table to be accessed */ sqlite3VdbeUsesBtree(v, iDb); if( db->mallocFailed==0 ){ assert( aOp!=0 ); /* Configure the OP_TableLock instruction */ #ifdef SQLITE_OMIT_SHARED_CACHE aOp[0].opcode = OP_Noop; #else aOp[0].p1 = iDb; aOp[0].p2 = pTab->tnum; aOp[0].p3 = wrFlag; sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT); } if( db->mallocFailed==0 ){ #endif /* Remove either the OP_OpenWrite or OpenRead. Set the P2 ** parameter of the other to pTab->tnum. */ if( wrFlag ) aOp[1].opcode = OP_OpenWrite; aOp[1].p2 = pTab->tnum; aOp[1].p3 = iDb; /* Configure the number of columns. Configure the cursor to ** think that the table has one more column than it really ** does. An OP_Column to retrieve this imaginary column will ** always return an SQL NULL. This is useful because it means ** we can invoke OP_Column to fill in the vdbe cursors type ** and offset cache without causing any IO. */ aOp[1].p4type = P4_INT32; aOp[1].p4.i = pTab->nCol+1; aOp[3].p2 = pTab->nCol; pParse->nVar = 0; pParse->nMem = 1; pParse->nTab = 1; sqlite3VdbeMakeReady(v, pParse); } } pBlob->iCol = iCol; pBlob->db = db; sqlite3BtreeLeaveAll(db); if( db->mallocFailed ){ goto blob_open_out; } rc = blobSeekToRow(pBlob, iRow, &zErr); } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA ); blob_open_out: if( rc==SQLITE_OK && db->mallocFailed==0 ){ *ppBlob = (sqlite3_blob *)pBlob; }else{ if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt); sqlite3DbFree(db, pBlob); } sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); sqlite3DbFree(db, zErr); sqlite3ParserReset(pParse); sqlite3StackFree(db, pParse); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Close a blob handle that was previously created using ** sqlite3_blob_open(). */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){ Incrblob *p = (Incrblob *)pBlob; int rc; sqlite3 *db; if( p ){ db = p->db; sqlite3_mutex_enter(db->mutex); rc = sqlite3_finalize(p->pStmt); sqlite3DbFree(db, p); sqlite3_mutex_leave(db->mutex); }else{ rc = SQLITE_OK; } return rc; } /* ** Perform a read or write operation on a blob */ static int blobReadWrite( sqlite3_blob *pBlob, void *z, int n, int iOffset, int (*xCall)(BtCursor*, u32, u32, void*) ){ int rc; Incrblob *p = (Incrblob *)pBlob; Vdbe *v; sqlite3 *db; if( p==0 ) return SQLITE_MISUSE_BKPT; db = p->db; sqlite3_mutex_enter(db->mutex); v = (Vdbe*)p->pStmt; if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){ /* Request is out of range. Return a transient error. */ rc = SQLITE_ERROR; }else if( v==0 ){ /* If there is no statement handle, then the blob-handle has ** already been invalidated. Return SQLITE_ABORT in this case. */ rc = SQLITE_ABORT; }else{ /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is ** returned, clean-up the statement handle. */ assert( db == v->db ); sqlite3BtreeEnterCursor(p->pCsr); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){ /* If a pre-update hook is registered and this is a write cursor, ** invoke it here. ** ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this ** operation should really be an SQLITE_UPDATE. This is probably ** incorrect, but is convenient because at this point the new.* values ** are not easily obtainable. And for the sessions module, an ** SQLITE_UPDATE where the PK columns do not change is handled in the ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually ** slightly more efficient). Since you cannot write to a PK column ** using the incremental-blob API, this works. For the sessions module ** anyhow. */ sqlite3_int64 iKey; iKey = sqlite3BtreeIntegerKey(p->pCsr); sqlite3VdbePreUpdateHook( v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1 ); } #endif rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); sqlite3BtreeLeaveCursor(p->pCsr); if( rc==SQLITE_ABORT ){ sqlite3VdbeFinalize(v); p->pStmt = 0; }else{ v->rc = rc; } } sqlite3Error(db, rc); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Read data from a blob handle. */ SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){ return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked); } /* ** Write data to a blob handle. */ SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){ return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData); } /* ** Query a blob handle for the size of the data. ** ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob ** so no mutex is required for access. */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){ Incrblob *p = (Incrblob *)pBlob; return (p && p->pStmt) ? p->nByte : 0; } /* ** Move an existing blob handle to point to a different row of the same ** database table. ** ** If an error occurs, or if the specified row does not exist or does not ** contain a blob or text value, then an error code is returned and the ** database handle error code and message set. If this happens, then all ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) ** immediately return SQLITE_ABORT. */ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ int rc; Incrblob *p = (Incrblob *)pBlob; sqlite3 *db; if( p==0 ) return SQLITE_MISUSE_BKPT; db = p->db; sqlite3_mutex_enter(db->mutex); if( p->pStmt==0 ){ /* If there is no statement handle, then the blob-handle has ** already been invalidated. Return SQLITE_ABORT in this case. */ rc = SQLITE_ABORT; }else{ char *zErr; rc = blobSeekToRow(p, iRow, &zErr); if( rc!=SQLITE_OK ){ sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); sqlite3DbFree(db, zErr); } assert( rc!=SQLITE_SCHEMA ); } rc = sqlite3ApiExit(db, rc); assert( rc==SQLITE_OK || p->pStmt==0 ); sqlite3_mutex_leave(db->mutex); return rc; } #endif /* #ifndef SQLITE_OMIT_INCRBLOB */ /************** End of vdbeblob.c ********************************************/ /************** Begin file vdbesort.c ****************************************/ /* ** 2011-07-09 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code for the VdbeSorter object, used in concert with ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements ** or by SELECT statements with ORDER BY clauses that cannot be satisfied ** using indexes and without LIMIT clauses. ** ** The VdbeSorter object implements a multi-threaded external merge sort ** algorithm that is efficient even if the number of elements being sorted ** exceeds the available memory. ** ** Here is the (internal, non-API) interface between this module and the ** rest of the SQLite system: ** ** sqlite3VdbeSorterInit() Create a new VdbeSorter object. ** ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter ** object. The row is a binary blob in the ** OP_MakeRecord format that contains both ** the ORDER BY key columns and result columns ** in the case of a SELECT w/ ORDER BY, or ** the complete record for an index entry ** in the case of a CREATE INDEX. ** ** sqlite3VdbeSorterRewind() Sort all content previously added. ** Position the read cursor on the ** first sorted element. ** ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted ** element. ** ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the ** row currently under the read cursor. ** ** sqlite3VdbeSorterCompare() Compare the binary blob for the row ** currently under the read cursor against ** another binary blob X and report if ** X is strictly less than the read cursor. ** Used to enforce uniqueness in a ** CREATE UNIQUE INDEX statement. ** ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim ** all resources. ** ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This ** is like Close() followed by Init() only ** much faster. ** ** The interfaces above must be called in a particular order. Write() can ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e. ** ** Init() ** for each record: Write() ** Rewind() ** Rowkey()/Compare() ** Next() ** Close() ** ** Algorithm: ** ** Records passed to the sorter via calls to Write() are initially held ** unsorted in main memory. Assuming the amount of memory used never exceeds ** a threshold, when Rewind() is called the set of records is sorted using ** an in-memory merge sort. In this case, no temporary files are required ** and subsequent calls to Rowkey(), Next() and Compare() read records ** directly from main memory. ** ** If the amount of space used to store records in main memory exceeds the ** threshold, then the set of records currently in memory are sorted and ** written to a temporary file in "Packed Memory Array" (PMA) format. ** A PMA created at this point is known as a "level-0 PMA". Higher levels ** of PMAs may be created by merging existing PMAs together - for example ** merging two or more level-0 PMAs together creates a level-1 PMA. ** ** The threshold for the amount of main memory to use before flushing ** records to a PMA is roughly the same as the limit configured for the ** page-cache of the main database. Specifically, the threshold is set to ** the value returned by "PRAGMA main.page_size" multipled by ** that returned by "PRAGMA main.cache_size", in bytes. ** ** If the sorter is running in single-threaded mode, then all PMAs generated ** are appended to a single temporary file. Or, if the sorter is running in ** multi-threaded mode then up to (N+1) temporary files may be opened, where ** N is the configured number of worker threads. In this case, instead of ** sorting the records and writing the PMA to a temporary file itself, the ** calling thread usually launches a worker thread to do so. Except, if ** there are already N worker threads running, the main thread does the work ** itself. ** ** The sorter is running in multi-threaded mode if (a) the library was built ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater ** than zero, and (b) worker threads have been enabled at runtime by calling ** "PRAGMA threads=N" with some value of N greater than 0. ** ** When Rewind() is called, any data remaining in memory is flushed to a ** final PMA. So at this point the data is stored in some number of sorted ** PMAs within temporary files on disk. ** ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the ** sorter is running in single-threaded mode, then these PMAs are merged ** incrementally as keys are retreived from the sorter by the VDBE. The ** MergeEngine object, described in further detail below, performs this ** merge. ** ** Or, if running in multi-threaded mode, then a background thread is ** launched to merge the existing PMAs. Once the background thread has ** merged T bytes of data into a single sorted PMA, the main thread ** begins reading keys from that PMA while the background thread proceeds ** with merging the next T bytes of data. And so on. ** ** Parameter T is set to half the value of the memory threshold used ** by Write() above to determine when to create a new PMA. ** ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when ** Rewind() is called, then a hierarchy of incremental-merges is used. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on ** disk are merged together. Then T bytes of data from the second set, and ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT ** PMAs at a time. This done is to improve locality. ** ** If running in multi-threaded mode and there are more than ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more ** than one background thread may be created. Specifically, there may be ** one background thread for each temporary file on disk, and one background ** thread to merge the output of each of the others to a single PMA for ** the main thread to read from. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ /* ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various ** messages to stderr that may be helpful in understanding the performance ** characteristics of the sorter in multi-threaded mode. */ #if 0 # define SQLITE_DEBUG_SORTER_THREADS 1 #endif /* ** Hard-coded maximum amount of data to accumulate in memory before flushing ** to a level 0 PMA. The purpose of this limit is to prevent various integer ** overflows. 512MiB. */ #define SQLITE_MAX_PMASZ (1<<29) /* ** Private objects used by the sorter */ typedef struct MergeEngine MergeEngine; /* Merge PMAs together */ typedef struct PmaReader PmaReader; /* Incrementally read one PMA */ typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */ typedef struct SorterRecord SorterRecord; /* A record being sorted */ typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */ typedef struct SorterFile SorterFile; /* Temporary file object wrapper */ typedef struct SorterList SorterList; /* In-memory list of records */ typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */ /* ** A container for a temp file handle and the current amount of data ** stored in the file. */ struct SorterFile { sqlite3_file *pFd; /* File handle */ i64 iEof; /* Bytes of data stored in pFd */ }; /* ** An in-memory list of objects to be sorted. ** ** If aMemory==0 then each object is allocated separately and the objects ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects ** are stored in the aMemory[] bulk memory, one right after the other, and ** are connected using SorterRecord.u.iNext. */ struct SorterList { SorterRecord *pList; /* Linked list of records */ u8 *aMemory; /* If non-NULL, bulk memory to hold pList */ int szPMA; /* Size of pList as PMA in bytes */ }; /* ** The MergeEngine object is used to combine two or more smaller PMAs into ** one big PMA using a merge operation. Separate PMAs all need to be ** combined into one big PMA in order to be able to step through the sorted ** records in order. ** ** The aReadr[] array contains a PmaReader object for each of the PMAs being ** merged. An aReadr[] object either points to a valid key or else is at EOF. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.) ** For the purposes of the paragraphs below, we assume that the array is ** actually N elements in size, where N is the smallest power of 2 greater ** to or equal to the number of PMAs being merged. The extra aReadr[] elements ** are treated as if they are empty (always at EOF). ** ** The aTree[] array is also N elements in size. The value of N is stored in ** the MergeEngine.nTree variable. ** ** The final (N/2) elements of aTree[] contain the results of comparing ** pairs of PMA keys together. Element i contains the result of ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the ** aTree element is set to the index of it. ** ** For the purposes of this comparison, EOF is considered greater than any ** other key value. If the keys are equal (only possible with two EOF ** values), it doesn't matter which index is stored. ** ** The (N/4) elements of aTree[] that precede the final (N/2) described ** above contains the index of the smallest of each block of 4 PmaReaders ** And so on. So that aTree[1] contains the index of the PmaReader that ** currently points to the smallest key value. aTree[0] is unused. ** ** Example: ** ** aReadr[0] -> Banana ** aReadr[1] -> Feijoa ** aReadr[2] -> Elderberry ** aReadr[3] -> Currant ** aReadr[4] -> Grapefruit ** aReadr[5] -> Apple ** aReadr[6] -> Durian ** aReadr[7] -> EOF ** ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 } ** ** The current element is "Apple" (the value of the key indicated by ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will ** be advanced to the next key in its segment. Say the next key is ** "Eggplant": ** ** aReadr[5] -> Eggplant ** ** The contents of aTree[] are updated first by comparing the new PmaReader ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian), ** so the value written into element 1 of the array is 0. As follows: ** ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 } ** ** In other words, each time we advance to the next sorter element, log2(N) ** key comparison operations are required, where N is the number of segments ** being merged (rounded up to the next power of 2). */ struct MergeEngine { int nTree; /* Used size of aTree/aReadr (power of 2) */ SortSubtask *pTask; /* Used by this thread only */ int *aTree; /* Current state of incremental merge */ PmaReader *aReadr; /* Array of PmaReaders to merge data from */ }; /* ** This object represents a single thread of control in a sort operation. ** Exactly VdbeSorter.nTask instances of this object are allocated ** as part of each VdbeSorter object. Instances are never allocated any ** other way. VdbeSorter.nTask is set to the number of worker threads allowed ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for ** single-threaded operation, there is exactly one instance of this object ** and for multi-threaded operation there are two or more instances. ** ** Essentially, this structure contains all those fields of the VdbeSorter ** structure for which each thread requires a separate instance. For example, ** each thread requries its own UnpackedRecord object to unpack records in ** as part of comparison operations. ** ** Before a background thread is launched, variable bDone is set to 0. Then, ** right before it exits, the thread itself sets bDone to 1. This is used for ** two purposes: ** ** 1. When flushing the contents of memory to a level-0 PMA on disk, to ** attempt to select a SortSubtask for which there is not already an ** active background thread (since doing so causes the main thread ** to block until it finishes). ** ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to ** block provoke debugging output. ** ** In both cases, the effects of the main thread seeing (bDone==0) even ** after the thread has finished are not dire. So we don't worry about ** memory barriers and such here. */ typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int); struct SortSubtask { SQLiteThread *pThread; /* Background thread, if any */ int bDone; /* Set if thread is finished but not joined */ VdbeSorter *pSorter; /* Sorter that owns this sub-task */ UnpackedRecord *pUnpacked; /* Space to unpack a record */ SorterList list; /* List for thread to write to a PMA */ int nPMA; /* Number of PMAs currently in file */ SorterCompare xCompare; /* Compare function to use */ SorterFile file; /* Temp file for level-0 PMAs */ SorterFile file2; /* Space for other PMAs */ }; /* ** Main sorter structure. A single instance of this is allocated for each ** sorter cursor created by the VDBE. ** ** mxKeysize: ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(), ** this variable is updated so as to be set to the size on disk of the ** largest record in the sorter. */ struct VdbeSorter { int mnPmaSize; /* Minimum PMA size, in bytes */ int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */ int mxKeysize; /* Largest serialized key seen so far */ int pgsz; /* Main database page size */ PmaReader *pReader; /* Readr data from here after Rewind() */ MergeEngine *pMerger; /* Or here, if bUseThreads==0 */ sqlite3 *db; /* Database connection */ KeyInfo *pKeyInfo; /* How to compare records */ UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */ SorterList list; /* List of in-memory records */ int iMemory; /* Offset of free space in list.aMemory */ int nMemory; /* Size of list.aMemory allocation in bytes */ u8 bUsePMA; /* True if one or more PMAs created */ u8 bUseThreads; /* True to use background threads */ u8 iPrev; /* Previous thread used to flush PMA */ u8 nTask; /* Size of aTask[] array */ u8 typeMask; SortSubtask aTask[1]; /* One or more subtasks */ }; #define SORTER_TYPE_INTEGER 0x01 #define SORTER_TYPE_TEXT 0x02 /* ** An instance of the following object is used to read records out of a ** PMA, in sorted order. The next key to be read is cached in nKey/aKey. ** aKey might point into aMap or into aBuffer. If neither of those locations ** contain a contiguous representation of the key, then aAlloc is allocated ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc. ** ** pFd==0 at EOF. */ struct PmaReader { i64 iReadOff; /* Current read offset */ i64 iEof; /* 1 byte past EOF for this PmaReader */ int nAlloc; /* Bytes of space at aAlloc */ int nKey; /* Number of bytes in key */ sqlite3_file *pFd; /* File handle we are reading from */ u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */ u8 *aKey; /* Pointer to current key */ u8 *aBuffer; /* Current read buffer */ int nBuffer; /* Size of read buffer in bytes */ u8 *aMap; /* Pointer to mapping of entire file */ IncrMerger *pIncr; /* Incremental merger */ }; /* ** Normally, a PmaReader object iterates through an existing PMA stored ** within a temp file. However, if the PmaReader.pIncr variable points to ** an object of the following type, it may be used to iterate/merge through ** multiple PMAs simultaneously. ** ** There are two types of IncrMerger object - single (bUseThread==0) and ** multi-threaded (bUseThread==1). ** ** A multi-threaded IncrMerger object uses two temporary files - aFile[0] ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in ** size. When the IncrMerger is initialized, it reads enough data from ** pMerger to populate aFile[0]. It then sets variables within the ** corresponding PmaReader object to read from that file and kicks off ** a background thread to populate aFile[1] with the next mxSz bytes of ** sorted record data from pMerger. ** ** When the PmaReader reaches the end of aFile[0], it blocks until the ** background thread has finished populating aFile[1]. It then exchanges ** the contents of the aFile[0] and aFile[1] variables within this structure, ** sets the PmaReader fields to read from the new aFile[0] and kicks off ** another background thread to populate the new aFile[1]. And so on, until ** the contents of pMerger are exhausted. ** ** A single-threaded IncrMerger does not open any temporary files of its ** own. Instead, it has exclusive access to mxSz bytes of space beginning ** at offset iStartOff of file pTask->file2. And instead of using a ** background thread to prepare data for the PmaReader, with a single ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with ** keys from pMerger by the calling thread whenever the PmaReader runs out ** of data. */ struct IncrMerger { SortSubtask *pTask; /* Task that owns this merger */ MergeEngine *pMerger; /* Merge engine thread reads data from */ i64 iStartOff; /* Offset to start writing file at */ int mxSz; /* Maximum bytes of data to store */ int bEof; /* Set to true when merge is finished */ int bUseThread; /* True to use a bg thread for this object */ SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */ }; /* ** An instance of this object is used for writing a PMA. ** ** The PMA is written one record at a time. Each record is of an arbitrary ** size. But I/O is more efficient if it occurs in page-sized blocks where ** each block is aligned on a page boundary. This object caches writes to ** the PMA so that aligned, page-size blocks are written. */ struct PmaWriter { int eFWErr; /* Non-zero if in an error state */ u8 *aBuffer; /* Pointer to write buffer */ int nBuffer; /* Size of write buffer in bytes */ int iBufStart; /* First byte of buffer to write */ int iBufEnd; /* Last byte of buffer to write */ i64 iWriteOff; /* Offset of start of buffer in file */ sqlite3_file *pFd; /* File handle to write to */ }; /* ** This object is the header on a single record while that record is being ** held in memory and prior to being written out as part of a PMA. ** ** How the linked list is connected depends on how memory is being managed ** by this module. If using a separate allocation for each in-memory record ** (VdbeSorter.list.aMemory==0), then the list is always connected using the ** SorterRecord.u.pNext pointers. ** ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0), ** then while records are being accumulated the list is linked using the ** SorterRecord.u.iNext offset. This is because the aMemory[] array may ** be sqlite3Realloc()ed while records are being accumulated. Once the VM ** has finished passing records to the sorter, or when the in-memory buffer ** is full, the list is sorted. As part of the sorting process, it is ** converted to use the SorterRecord.u.pNext pointers. See function ** vdbeSorterSort() for details. */ struct SorterRecord { int nVal; /* Size of the record in bytes */ union { SorterRecord *pNext; /* Pointer to next record in list */ int iNext; /* Offset within aMemory of next record */ } u; /* The data for the record immediately follows this header */ }; /* Return a pointer to the buffer containing the record data for SorterRecord ** object p. Should be used as if: ** ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; } */ #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1)) /* Maximum number of PMAs that a single MergeEngine can merge */ #define SORTER_MAX_MERGE_COUNT 16 static int vdbeIncrSwap(IncrMerger*); static void vdbeIncrFree(IncrMerger *); /* ** Free all memory belonging to the PmaReader object passed as the ** argument. All structure fields are set to zero before returning. */ static void vdbePmaReaderClear(PmaReader *pReadr){ sqlite3_free(pReadr->aAlloc); sqlite3_free(pReadr->aBuffer); if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); vdbeIncrFree(pReadr->pIncr); memset(pReadr, 0, sizeof(PmaReader)); } /* ** Read the next nByte bytes of data from the PMA p. ** If successful, set *ppOut to point to a buffer containing the data ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite ** error code. ** ** The buffer returned in *ppOut is only valid until the ** next call to this function. */ static int vdbePmaReadBlob( PmaReader *p, /* PmaReader from which to take the blob */ int nByte, /* Bytes of data to read */ u8 **ppOut /* OUT: Pointer to buffer containing data */ ){ int iBuf; /* Offset within buffer to read from */ int nAvail; /* Bytes of data available in buffer */ if( p->aMap ){ *ppOut = &p->aMap[p->iReadOff]; p->iReadOff += nByte; return SQLITE_OK; } assert( p->aBuffer ); /* If there is no more data to be read from the buffer, read the next ** p->nBuffer bytes of data from the file into it. Or, if there are less ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */ iBuf = p->iReadOff % p->nBuffer; if( iBuf==0 ){ int nRead; /* Bytes to read from disk */ int rc; /* sqlite3OsRead() return code */ /* Determine how many bytes of data to read. */ if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){ nRead = p->nBuffer; }else{ nRead = (int)(p->iEof - p->iReadOff); } assert( nRead>0 ); /* Readr data from the file. Return early if an error occurs. */ rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff); assert( rc!=SQLITE_IOERR_SHORT_READ ); if( rc!=SQLITE_OK ) return rc; } nAvail = p->nBuffer - iBuf; if( nByte<=nAvail ){ /* The requested data is available in the in-memory buffer. In this ** case there is no need to make a copy of the data, just return a ** pointer into the buffer to the caller. */ *ppOut = &p->aBuffer[iBuf]; p->iReadOff += nByte; }else{ /* The requested data is not all available in the in-memory buffer. ** In this case, allocate space at p->aAlloc[] to copy the requested ** range into. Then return a copy of pointer p->aAlloc to the caller. */ int nRem; /* Bytes remaining to copy */ /* Extend the p->aAlloc[] allocation if required. */ if( p->nAlloc<nByte ){ u8 *aNew; int nNew = MAX(128, p->nAlloc*2); while( nByte>nNew ) nNew = nNew*2; aNew = sqlite3Realloc(p->aAlloc, nNew); if( !aNew ) return SQLITE_NOMEM_BKPT; p->nAlloc = nNew; p->aAlloc = aNew; } /* Copy as much data as is available in the buffer into the start of ** p->aAlloc[]. */ memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail); p->iReadOff += nAvail; nRem = nByte - nAvail; /* The following loop copies up to p->nBuffer bytes per iteration into ** the p->aAlloc[] buffer. */ while( nRem>0 ){ int rc; /* vdbePmaReadBlob() return code */ int nCopy; /* Number of bytes to copy */ u8 *aNext; /* Pointer to buffer to copy data from */ nCopy = nRem; if( nRem>p->nBuffer ) nCopy = p->nBuffer; rc = vdbePmaReadBlob(p, nCopy, &aNext); if( rc!=SQLITE_OK ) return rc; assert( aNext!=p->aAlloc ); memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy); nRem -= nCopy; } *ppOut = p->aAlloc; } return SQLITE_OK; } /* ** Read a varint from the stream of data accessed by p. Set *pnOut to ** the value read. */ static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){ int iBuf; if( p->aMap ){ p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut); }else{ iBuf = p->iReadOff % p->nBuffer; if( iBuf && (p->nBuffer-iBuf)>=9 ){ p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut); }else{ u8 aVarint[16], *a; int i = 0, rc; do{ rc = vdbePmaReadBlob(p, 1, &a); if( rc ) return rc; aVarint[(i++)&0xf] = a[0]; }while( (a[0]&0x80)!=0 ); sqlite3GetVarint(aVarint, pnOut); } } return SQLITE_OK; } /* ** Attempt to memory map file pFile. If successful, set *pp to point to the ** new mapping and return SQLITE_OK. If the mapping is not attempted ** (because the file is too large or the VFS layer is configured not to use ** mmap), return SQLITE_OK and set *pp to NULL. ** ** Or, if an error occurs, return an SQLite error code. The final value of ** *pp is undefined in this case. */ static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){ int rc = SQLITE_OK; if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){ sqlite3_file *pFd = pFile->pFd; if( pFd->pMethods->iVersion>=3 ){ rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp); testcase( rc!=SQLITE_OK ); } } return rc; } /* ** Attach PmaReader pReadr to file pFile (if it is not already attached to ** that file) and seek it to offset iOff within the file. Return SQLITE_OK ** if successful, or an SQLite error code if an error occurs. */ static int vdbePmaReaderSeek( SortSubtask *pTask, /* Task context */ PmaReader *pReadr, /* Reader whose cursor is to be moved */ SorterFile *pFile, /* Sorter file to read from */ i64 iOff /* Offset in pFile */ ){ int rc = SQLITE_OK; assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 ); if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ; if( pReadr->aMap ){ sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); pReadr->aMap = 0; } pReadr->iReadOff = iOff; pReadr->iEof = pFile->iEof; pReadr->pFd = pFile->pFd; rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap); if( rc==SQLITE_OK && pReadr->aMap==0 ){ int pgsz = pTask->pSorter->pgsz; int iBuf = pReadr->iReadOff % pgsz; if( pReadr->aBuffer==0 ){ pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz); if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT; pReadr->nBuffer = pgsz; } if( rc==SQLITE_OK && iBuf ){ int nRead = pgsz - iBuf; if( (pReadr->iReadOff + nRead) > pReadr->iEof ){ nRead = (int)(pReadr->iEof - pReadr->iReadOff); } rc = sqlite3OsRead( pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff ); testcase( rc!=SQLITE_OK ); } } return rc; } /* ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if ** no error occurs, or an SQLite error code if one does. */ static int vdbePmaReaderNext(PmaReader *pReadr){ int rc = SQLITE_OK; /* Return Code */ u64 nRec = 0; /* Size of record in bytes */ if( pReadr->iReadOff>=pReadr->iEof ){ IncrMerger *pIncr = pReadr->pIncr; int bEof = 1; if( pIncr ){ rc = vdbeIncrSwap(pIncr); if( rc==SQLITE_OK && pIncr->bEof==0 ){ rc = vdbePmaReaderSeek( pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff ); bEof = 0; } } if( bEof ){ /* This is an EOF condition */ vdbePmaReaderClear(pReadr); testcase( rc!=SQLITE_OK ); return rc; } } if( rc==SQLITE_OK ){ rc = vdbePmaReadVarint(pReadr, &nRec); } if( rc==SQLITE_OK ){ pReadr->nKey = (int)nRec; rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey); testcase( rc!=SQLITE_OK ); } return rc; } /* ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile ** starting at offset iStart and ending at offset iEof-1. This function ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the ** PMA is empty). ** ** If the pnByte parameter is NULL, then it is assumed that the file ** contains a single PMA, and that that PMA omits the initial length varint. */ static int vdbePmaReaderInit( SortSubtask *pTask, /* Task context */ SorterFile *pFile, /* Sorter file to read from */ i64 iStart, /* Start offset in pFile */ PmaReader *pReadr, /* PmaReader to populate */ i64 *pnByte /* IN/OUT: Increment this value by PMA size */ ){ int rc; assert( pFile->iEof>iStart ); assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 ); assert( pReadr->aBuffer==0 ); assert( pReadr->aMap==0 ); rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart); if( rc==SQLITE_OK ){ u64 nByte = 0; /* Size of PMA in bytes */ rc = vdbePmaReadVarint(pReadr, &nByte); pReadr->iEof = pReadr->iReadOff + nByte; *pnByte += nByte; } if( rc==SQLITE_OK ){ rc = vdbePmaReaderNext(pReadr); } return rc; } /* ** A version of vdbeSorterCompare() that assumes that it has already been ** determined that the first field of key1 is equal to the first field of ** key2. */ static int vdbeSorterCompareTail( SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2 /* Right side of comparison */ ){ UnpackedRecord *r2 = pTask->pUnpacked; if( *pbKey2Cached==0 ){ sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); *pbKey2Cached = 1; } return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1); } /* ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences ** used by the comparison. Return the result of the comparison. ** ** If IN/OUT parameter *pbKey2Cached is true when this function is called, ** it is assumed that (pTask->pUnpacked) contains the unpacked version ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked ** version of key2 and *pbKey2Cached set to true before returning. ** ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set ** to SQLITE_NOMEM. */ static int vdbeSorterCompare( SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2 /* Right side of comparison */ ){ UnpackedRecord *r2 = pTask->pUnpacked; if( !*pbKey2Cached ){ sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); *pbKey2Cached = 1; } return sqlite3VdbeRecordCompare(nKey1, pKey1, r2); } /* ** A specially optimized version of vdbeSorterCompare() that assumes that ** the first field of each key is a TEXT value and that the collation ** sequence to compare them with is BINARY. */ static int vdbeSorterCompareText( SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2 /* Right side of comparison */ ){ const u8 * const p1 = (const u8 * const)pKey1; const u8 * const p2 = (const u8 * const)pKey2; const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */ const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */ int n1; int n2; int res; getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2; getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2; res = memcmp(v1, v2, MIN(n1, n2)); if( res==0 ){ res = n1 - n2; } if( res==0 ){ if( pTask->pSorter->pKeyInfo->nField>1 ){ res = vdbeSorterCompareTail( pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 ); } }else{ if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){ res = res * -1; } } return res; } /* ** A specially optimized version of vdbeSorterCompare() that assumes that ** the first field of each key is an INTEGER value. */ static int vdbeSorterCompareInt( SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ const void *pKey1, int nKey1, /* Left side of comparison */ const void *pKey2, int nKey2 /* Right side of comparison */ ){ const u8 * const p1 = (const u8 * const)pKey1; const u8 * const p2 = (const u8 * const)pKey2; const int s1 = p1[1]; /* Left hand serial type */ const int s2 = p2[1]; /* Right hand serial type */ const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */ const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */ int res; /* Return value */ assert( (s1>0 && s1<7) || s1==8 || s1==9 ); assert( (s2>0 && s2<7) || s2==8 || s2==9 ); if( s1>7 && s2>7 ){ res = s1 - s2; }else{ if( s1==s2 ){ if( (*v1 ^ *v2) & 0x80 ){ /* The two values have different signs */ res = (*v1 & 0x80) ? -1 : +1; }else{ /* The two values have the same sign. Compare using memcmp(). */ static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 }; int i; res = 0; for(i=0; i<aLen[s1]; i++){ if( (res = v1[i] - v2[i]) ) break; } } }else{ if( s2>7 ){ res = +1; }else if( s1>7 ){ res = -1; }else{ res = s1 - s2; } assert( res!=0 ); if( res>0 ){ if( *v1 & 0x80 ) res = -1; }else{ if( *v2 & 0x80 ) res = +1; } } } if( res==0 ){ if( pTask->pSorter->pKeyInfo->nField>1 ){ res = vdbeSorterCompareTail( pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 ); } }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){ res = res * -1; } return res; } /* ** Initialize the temporary index cursor just opened as a sorter cursor. ** ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField) ** to determine the number of fields that should be compared from the ** records being sorted. However, if the value passed as argument nField ** is non-zero and the sorter is able to guarantee a stable sort, nField ** is used instead. This is used when sorting records for a CREATE INDEX ** statement. In this case, keys are always delivered to the sorter in ** order of the primary key, which happens to be make up the final part ** of the records being sorted. So if the sort is stable, there is never ** any reason to compare PK fields and they can be ignored for a small ** performance boost. ** ** The sorter can guarantee a stable sort when running in single-threaded ** mode, but not in multi-threaded mode. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ SQLITE_PRIVATE int sqlite3VdbeSorterInit( sqlite3 *db, /* Database connection (for malloc()) */ int nField, /* Number of key fields in each record */ VdbeCursor *pCsr /* Cursor that holds the new sorter */ ){ int pgsz; /* Page size of main database */ int i; /* Used to iterate through aTask[] */ VdbeSorter *pSorter; /* The new sorter */ KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */ int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */ int sz; /* Size of pSorter in bytes */ int rc = SQLITE_OK; #if SQLITE_MAX_WORKER_THREADS==0 # define nWorker 0 #else int nWorker; #endif /* Initialize the upper limit on the number of worker threads */ #if SQLITE_MAX_WORKER_THREADS>0 if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){ nWorker = 0; }else{ nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS]; } #endif /* Do not allow the total number of threads (main thread + all workers) ** to exceed the maximum merge count */ #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT if( nWorker>=SORTER_MAX_MERGE_COUNT ){ nWorker = SORTER_MAX_MERGE_COUNT-1; } #endif assert( pCsr->pKeyInfo && pCsr->pBtx==0 ); assert( pCsr->eCurType==CURTYPE_SORTER ); szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*); sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask); pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo); pCsr->uc.pSorter = pSorter; if( pSorter==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz); memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo); pKeyInfo->db = 0; if( nField && nWorker==0 ){ pKeyInfo->nXField += (pKeyInfo->nField - nField); pKeyInfo->nField = nField; } pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt); pSorter->nTask = nWorker + 1; pSorter->iPrev = (u8)(nWorker - 1); pSorter->bUseThreads = (pSorter->nTask>1); pSorter->db = db; for(i=0; i<pSorter->nTask; i++){ SortSubtask *pTask = &pSorter->aTask[i]; pTask->pSorter = pSorter; } if( !sqlite3TempInMemory(db) ){ i64 mxCache; /* Cache size in bytes*/ u32 szPma = sqlite3GlobalConfig.szPma; pSorter->mnPmaSize = szPma * pgsz; mxCache = db->aDb[0].pSchema->cache_size; if( mxCache<0 ){ /* A negative cache-size value C indicates that the cache is abs(C) ** KiB in size. */ mxCache = mxCache * -1024; }else{ mxCache = mxCache * pgsz; } mxCache = MIN(mxCache, SQLITE_MAX_PMASZ); pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache); /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary ** large heap allocations. */ if( sqlite3GlobalConfig.pScratch==0 ){ assert( pSorter->iMemory==0 ); pSorter->nMemory = pgsz; pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz); if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT; } } if( (pKeyInfo->nField+pKeyInfo->nXField)<13 && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl) ){ pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT; } } return rc; } #undef nWorker /* Defined at the top of this function */ /* ** Free the list of sorted records starting at pRecord. */ static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){ SorterRecord *p; SorterRecord *pNext; for(p=pRecord; p; p=pNext){ pNext = p->u.pNext; sqlite3DbFree(db, p); } } /* ** Free all resources owned by the object indicated by argument pTask. All ** fields of *pTask are zeroed before returning. */ static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){ sqlite3DbFree(db, pTask->pUnpacked); #if SQLITE_MAX_WORKER_THREADS>0 /* pTask->list.aMemory can only be non-zero if it was handed memory ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */ if( pTask->list.aMemory ){ sqlite3_free(pTask->list.aMemory); }else #endif { assert( pTask->list.aMemory==0 ); vdbeSorterRecordFree(0, pTask->list.pList); } if( pTask->file.pFd ){ sqlite3OsCloseFree(pTask->file.pFd); } if( pTask->file2.pFd ){ sqlite3OsCloseFree(pTask->file2.pFd); } memset(pTask, 0, sizeof(SortSubtask)); } #ifdef SQLITE_DEBUG_SORTER_THREADS static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){ i64 t; int iTask = (pTask - pTask->pSorter->aTask); sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent); } static void vdbeSorterRewindDebug(const char *zEvent){ i64 t; sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t); fprintf(stderr, "%lld:X %s\n", t, zEvent); } static void vdbeSorterPopulateDebug( SortSubtask *pTask, const char *zEvent ){ i64 t; int iTask = (pTask - pTask->pSorter->aTask); sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent); } static void vdbeSorterBlockDebug( SortSubtask *pTask, int bBlocked, const char *zEvent ){ if( bBlocked ){ i64 t; sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:main %s\n", t, zEvent); } } #else # define vdbeSorterWorkDebug(x,y) # define vdbeSorterRewindDebug(y) # define vdbeSorterPopulateDebug(x,y) # define vdbeSorterBlockDebug(x,y,z) #endif #if SQLITE_MAX_WORKER_THREADS>0 /* ** Join thread pTask->thread. */ static int vdbeSorterJoinThread(SortSubtask *pTask){ int rc = SQLITE_OK; if( pTask->pThread ){ #ifdef SQLITE_DEBUG_SORTER_THREADS int bDone = pTask->bDone; #endif void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR); vdbeSorterBlockDebug(pTask, !bDone, "enter"); (void)sqlite3ThreadJoin(pTask->pThread, &pRet); vdbeSorterBlockDebug(pTask, !bDone, "exit"); rc = SQLITE_PTR_TO_INT(pRet); assert( pTask->bDone==1 ); pTask->bDone = 0; pTask->pThread = 0; } return rc; } /* ** Launch a background thread to run xTask(pIn). */ static int vdbeSorterCreateThread( SortSubtask *pTask, /* Thread will use this task object */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ ){ assert( pTask->pThread==0 && pTask->bDone==0 ); return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn); } /* ** Join all outstanding threads launched by SorterWrite() to create ** level-0 PMAs. */ static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){ int rc = rcin; int i; /* This function is always called by the main user thread. ** ** If this function is being called after SorterRewind() has been called, ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread ** is currently attempt to join one of the other threads. To avoid a race ** condition where this thread also attempts to join the same object, join ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */ for(i=pSorter->nTask-1; i>=0; i--){ SortSubtask *pTask = &pSorter->aTask[i]; int rc2 = vdbeSorterJoinThread(pTask); if( rc==SQLITE_OK ) rc = rc2; } return rc; } #else # define vdbeSorterJoinAll(x,rcin) (rcin) # define vdbeSorterJoinThread(pTask) SQLITE_OK #endif /* ** Allocate a new MergeEngine object capable of handling up to ** nReader PmaReader inputs. ** ** nReader is automatically rounded up to the next power of two. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up. */ static MergeEngine *vdbeMergeEngineNew(int nReader){ int N = 2; /* Smallest power of two >= nReader */ int nByte; /* Total bytes of space to allocate */ MergeEngine *pNew; /* Pointer to allocated object to return */ assert( nReader<=SORTER_MAX_MERGE_COUNT ); while( N<nReader ) N += N; nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader)); pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte); if( pNew ){ pNew->nTree = N; pNew->pTask = 0; pNew->aReadr = (PmaReader*)&pNew[1]; pNew->aTree = (int*)&pNew->aReadr[N]; } return pNew; } /* ** Free the MergeEngine object passed as the only argument. */ static void vdbeMergeEngineFree(MergeEngine *pMerger){ int i; if( pMerger ){ for(i=0; i<pMerger->nTree; i++){ vdbePmaReaderClear(&pMerger->aReadr[i]); } } sqlite3_free(pMerger); } /* ** Free all resources associated with the IncrMerger object indicated by ** the first argument. */ static void vdbeIncrFree(IncrMerger *pIncr){ if( pIncr ){ #if SQLITE_MAX_WORKER_THREADS>0 if( pIncr->bUseThread ){ vdbeSorterJoinThread(pIncr->pTask); if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd); if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd); } #endif vdbeMergeEngineFree(pIncr->pMerger); sqlite3_free(pIncr); } } /* ** Reset a sorting cursor back to its original empty state. */ SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){ int i; (void)vdbeSorterJoinAll(pSorter, SQLITE_OK); assert( pSorter->bUseThreads || pSorter->pReader==0 ); #if SQLITE_MAX_WORKER_THREADS>0 if( pSorter->pReader ){ vdbePmaReaderClear(pSorter->pReader); sqlite3DbFree(db, pSorter->pReader); pSorter->pReader = 0; } #endif vdbeMergeEngineFree(pSorter->pMerger); pSorter->pMerger = 0; for(i=0; i<pSorter->nTask; i++){ SortSubtask *pTask = &pSorter->aTask[i]; vdbeSortSubtaskCleanup(db, pTask); pTask->pSorter = pSorter; } if( pSorter->list.aMemory==0 ){ vdbeSorterRecordFree(0, pSorter->list.pList); } pSorter->list.pList = 0; pSorter->list.szPMA = 0; pSorter->bUsePMA = 0; pSorter->iMemory = 0; pSorter->mxKeysize = 0; sqlite3DbFree(db, pSorter->pUnpacked); pSorter->pUnpacked = 0; } /* ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines. */ SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ VdbeSorter *pSorter; assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; if( pSorter ){ sqlite3VdbeSorterReset(db, pSorter); sqlite3_free(pSorter->list.aMemory); sqlite3DbFree(db, pSorter); pCsr->uc.pSorter = 0; } } #if SQLITE_MAX_MMAP_SIZE>0 /* ** The first argument is a file-handle open on a temporary file. The file ** is guaranteed to be nByte bytes or smaller in size. This function ** attempts to extend the file to nByte bytes in size and to ensure that ** the VFS has memory mapped it. ** ** Whether or not the file does end up memory mapped of course depends on ** the specific VFS implementation. */ static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){ if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){ void *p = 0; int chunksize = 4*1024; sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize); sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte); sqlite3OsFetch(pFd, 0, (int)nByte, &p); sqlite3OsUnfetch(pFd, 0, p); } } #else # define vdbeSorterExtendFile(x,y,z) #endif /* ** Allocate space for a file-handle and open a temporary file. If successful, ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK. ** Otherwise, set *ppFd to 0 and return an SQLite error code. */ static int vdbeSorterOpenTempFile( sqlite3 *db, /* Database handle doing sort */ i64 nExtend, /* Attempt to extend file to this size */ sqlite3_file **ppFd ){ int rc; if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS; rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd, SQLITE_OPEN_TEMP_JOURNAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc ); if( rc==SQLITE_OK ){ i64 max = SQLITE_MAX_MMAP_SIZE; sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max); if( nExtend>0 ){ vdbeSorterExtendFile(db, *ppFd, nExtend); } } return rc; } /* ** If it has not already been allocated, allocate the UnpackedRecord ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or ** if no allocation was required), or SQLITE_NOMEM otherwise. */ static int vdbeSortAllocUnpacked(SortSubtask *pTask){ if( pTask->pUnpacked==0 ){ pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo); if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT; pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField; pTask->pUnpacked->errCode = 0; } return SQLITE_OK; } /* ** Merge the two sorted lists p1 and p2 into a single list. */ static SorterRecord *vdbeSorterMerge( SortSubtask *pTask, /* Calling thread context */ SorterRecord *p1, /* First list to merge */ SorterRecord *p2 /* Second list to merge */ ){ SorterRecord *pFinal = 0; SorterRecord **pp = &pFinal; int bCached = 0; assert( p1!=0 && p2!=0 ); for(;;){ int res; res = pTask->xCompare( pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal ); if( res<=0 ){ *pp = p1; pp = &p1->u.pNext; p1 = p1->u.pNext; if( p1==0 ){ *pp = p2; break; } }else{ *pp = p2; pp = &p2->u.pNext; p2 = p2->u.pNext; bCached = 0; if( p2==0 ){ *pp = p1; break; } } } return pFinal; } /* ** Return the SorterCompare function to compare values collected by the ** sorter object passed as the only argument. */ static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){ if( p->typeMask==SORTER_TYPE_INTEGER ){ return vdbeSorterCompareInt; }else if( p->typeMask==SORTER_TYPE_TEXT ){ return vdbeSorterCompareText; } return vdbeSorterCompare; } /* ** Sort the linked list of records headed at pTask->pList. Return ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if ** an error occurs. */ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ int i; SorterRecord **aSlot; SorterRecord *p; int rc; rc = vdbeSortAllocUnpacked(pTask); if( rc!=SQLITE_OK ) return rc; p = pList->pList; pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter); aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *)); if( !aSlot ){ return SQLITE_NOMEM_BKPT; } while( p ){ SorterRecord *pNext; if( pList->aMemory ){ if( (u8*)p==pList->aMemory ){ pNext = 0; }else{ assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) ); pNext = (SorterRecord*)&pList->aMemory[p->u.iNext]; } }else{ pNext = p->u.pNext; } p->u.pNext = 0; for(i=0; aSlot[i]; i++){ p = vdbeSorterMerge(pTask, p, aSlot[i]); aSlot[i] = 0; } aSlot[i] = p; p = pNext; } p = 0; for(i=0; i<64; i++){ if( aSlot[i]==0 ) continue; p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i]; } pList->pList = p; sqlite3_free(aSlot); assert( pTask->pUnpacked->errCode==SQLITE_OK || pTask->pUnpacked->errCode==SQLITE_NOMEM ); return pTask->pUnpacked->errCode; } /* ** Initialize a PMA-writer object. */ static void vdbePmaWriterInit( sqlite3_file *pFd, /* File handle to write to */ PmaWriter *p, /* Object to populate */ int nBuf, /* Buffer size */ i64 iStart /* Offset of pFd to begin writing at */ ){ memset(p, 0, sizeof(PmaWriter)); p->aBuffer = (u8*)sqlite3Malloc(nBuf); if( !p->aBuffer ){ p->eFWErr = SQLITE_NOMEM_BKPT; }else{ p->iBufEnd = p->iBufStart = (iStart % nBuf); p->iWriteOff = iStart - p->iBufStart; p->nBuffer = nBuf; p->pFd = pFd; } } /* ** Write nData bytes of data to the PMA. Return SQLITE_OK ** if successful, or an SQLite error code if an error occurs. */ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ int nRem = nData; while( nRem>0 && p->eFWErr==0 ){ int nCopy = nRem; if( nCopy>(p->nBuffer - p->iBufEnd) ){ nCopy = p->nBuffer - p->iBufEnd; } memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); p->iBufEnd += nCopy; if( p->iBufEnd==p->nBuffer ){ p->eFWErr = sqlite3OsWrite(p->pFd, &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, p->iWriteOff + p->iBufStart ); p->iBufStart = p->iBufEnd = 0; p->iWriteOff += p->nBuffer; } assert( p->iBufEnd<p->nBuffer ); nRem -= nCopy; } } /* ** Flush any buffered data to disk and clean up the PMA-writer object. ** The results of using the PMA-writer after this call are undefined. ** Return SQLITE_OK if flushing the buffered data succeeds or is not ** required. Otherwise, return an SQLite error code. ** ** Before returning, set *piEof to the offset immediately following the ** last byte written to the file. */ static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){ int rc; if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){ p->eFWErr = sqlite3OsWrite(p->pFd, &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, p->iWriteOff + p->iBufStart ); } *piEof = (p->iWriteOff + p->iBufEnd); sqlite3_free(p->aBuffer); rc = p->eFWErr; memset(p, 0, sizeof(PmaWriter)); return rc; } /* ** Write value iVal encoded as a varint to the PMA. Return ** SQLITE_OK if successful, or an SQLite error code if an error occurs. */ static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){ int nByte; u8 aByte[10]; nByte = sqlite3PutVarint(aByte, iVal); vdbePmaWriteBlob(p, aByte, nByte); } /* ** Write the current contents of in-memory linked-list pList to a level-0 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if ** successful, or an SQLite error code otherwise. ** ** The format of a PMA is: ** ** * A varint. This varint contains the total number of bytes of content ** in the PMA (not including the varint itself). ** ** * One or more records packed end-to-end in order of ascending keys. ** Each record consists of a varint followed by a blob of data (the ** key). The varint is the number of bytes in the blob of data. */ static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){ sqlite3 *db = pTask->pSorter->db; int rc = SQLITE_OK; /* Return code */ PmaWriter writer; /* Object used to write to the file */ #ifdef SQLITE_DEBUG /* Set iSz to the expected size of file pTask->file after writing the PMA. ** This is used by an assert() statement at the end of this function. */ i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof; #endif vdbeSorterWorkDebug(pTask, "enter"); memset(&writer, 0, sizeof(PmaWriter)); assert( pList->szPMA>0 ); /* If the first temporary PMA file has not been opened, open it now. */ if( pTask->file.pFd==0 ){ rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd); assert( rc!=SQLITE_OK || pTask->file.pFd ); assert( pTask->file.iEof==0 ); assert( pTask->nPMA==0 ); } /* Try to get the file to memory map */ if( rc==SQLITE_OK ){ vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9); } /* Sort the list */ if( rc==SQLITE_OK ){ rc = vdbeSorterSort(pTask, pList); } if( rc==SQLITE_OK ){ SorterRecord *p; SorterRecord *pNext = 0; vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz, pTask->file.iEof); pTask->nPMA++; vdbePmaWriteVarint(&writer, pList->szPMA); for(p=pList->pList; p; p=pNext){ pNext = p->u.pNext; vdbePmaWriteVarint(&writer, p->nVal); vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal); if( pList->aMemory==0 ) sqlite3_free(p); } pList->pList = p; rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof); } vdbeSorterWorkDebug(pTask, "exit"); assert( rc!=SQLITE_OK || pList->pList==0 ); assert( rc!=SQLITE_OK || pTask->file.iEof==iSz ); return rc; } /* ** Advance the MergeEngine to its next entry. ** Set *pbEof to true there is no next entry because ** the MergeEngine has reached the end of all its inputs. ** ** Return SQLITE_OK if successful or an error code if an error occurs. */ static int vdbeMergeEngineStep( MergeEngine *pMerger, /* The merge engine to advance to the next row */ int *pbEof /* Set TRUE at EOF. Set false for more content */ ){ int rc; int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */ SortSubtask *pTask = pMerger->pTask; /* Advance the current PmaReader */ rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]); /* Update contents of aTree[] */ if( rc==SQLITE_OK ){ int i; /* Index of aTree[] to recalculate */ PmaReader *pReadr1; /* First PmaReader to compare */ PmaReader *pReadr2; /* Second PmaReader to compare */ int bCached = 0; /* Find the first two PmaReaders to compare. The one that was just ** advanced (iPrev) and the one next to it in the array. */ pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)]; pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)]; for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){ /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */ int iRes; if( pReadr1->pFd==0 ){ iRes = +1; }else if( pReadr2->pFd==0 ){ iRes = -1; }else{ iRes = pTask->xCompare(pTask, &bCached, pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey ); } /* If pReadr1 contained the smaller value, set aTree[i] to its index. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this ** case there is no cache of pReadr2 in pTask->pUnpacked, so set ** pKey2 to point to the record belonging to pReadr2. ** ** Alternatively, if pReadr2 contains the smaller of the two values, ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare() ** was actually called above, then pTask->pUnpacked now contains ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent ** vdbeSorterCompare() from decoding pReadr2 again. ** ** If the two values were equal, then the value from the oldest ** PMA should be considered smaller. The VdbeSorter.aReadr[] array ** is sorted from oldest to newest, so pReadr1 contains older values ** than pReadr2 iff (pReadr1<pReadr2). */ if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){ pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr); pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ]; bCached = 0; }else{ if( pReadr1->pFd ) bCached = 0; pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr); pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ]; } } *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0); } return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc); } #if SQLITE_MAX_WORKER_THREADS>0 /* ** The main routine for background threads that write level-0 PMAs. */ static void *vdbeSorterFlushThread(void *pCtx){ SortSubtask *pTask = (SortSubtask*)pCtx; int rc; /* Return code */ assert( pTask->bDone==0 ); rc = vdbeSorterListToPMA(pTask, &pTask->list); pTask->bDone = 1; return SQLITE_INT_TO_PTR(rc); } #endif /* SQLITE_MAX_WORKER_THREADS>0 */ /* ** Flush the current contents of VdbeSorter.list to a new PMA, possibly ** using a background thread. */ static int vdbeSorterFlushPMA(VdbeSorter *pSorter){ #if SQLITE_MAX_WORKER_THREADS==0 pSorter->bUsePMA = 1; return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list); #else int rc = SQLITE_OK; int i; SortSubtask *pTask = 0; /* Thread context used to create new PMA */ int nWorker = (pSorter->nTask-1); /* Set the flag to indicate that at least one PMA has been written. ** Or will be, anyhow. */ pSorter->bUsePMA = 1; /* Select a sub-task to sort and flush the current list of in-memory ** records to disk. If the sorter is running in multi-threaded mode, ** round-robin between the first (pSorter->nTask-1) tasks. Except, if ** the background thread from a sub-tasks previous turn is still running, ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy, ** fall back to using the final sub-task. The first (pSorter->nTask-1) ** sub-tasks are prefered as they use background threads - the final ** sub-task uses the main thread. */ for(i=0; i<nWorker; i++){ int iTest = (pSorter->iPrev + i + 1) % nWorker; pTask = &pSorter->aTask[iTest]; if( pTask->bDone ){ rc = vdbeSorterJoinThread(pTask); } if( rc!=SQLITE_OK || pTask->pThread==0 ) break; } if( rc==SQLITE_OK ){ if( i==nWorker ){ /* Use the foreground thread for this operation */ rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list); }else{ /* Launch a background thread for this operation */ u8 *aMem = pTask->list.aMemory; void *pCtx = (void*)pTask; assert( pTask->pThread==0 && pTask->bDone==0 ); assert( pTask->list.pList==0 ); assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 ); pSorter->iPrev = (u8)(pTask - pSorter->aTask); pTask->list = pSorter->list; pSorter->list.pList = 0; pSorter->list.szPMA = 0; if( aMem ){ pSorter->list.aMemory = aMem; pSorter->nMemory = sqlite3MallocSize(aMem); }else if( pSorter->list.aMemory ){ pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory); if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT; } rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx); } } return rc; #endif /* SQLITE_MAX_WORKER_THREADS!=0 */ } /* ** Add a record to the sorter. */ SQLITE_PRIVATE int sqlite3VdbeSorterWrite( const VdbeCursor *pCsr, /* Sorter cursor */ Mem *pVal /* Memory cell containing record */ ){ VdbeSorter *pSorter; int rc = SQLITE_OK; /* Return Code */ SorterRecord *pNew; /* New list element */ int bFlush; /* True to flush contents of memory to PMA */ int nReq; /* Bytes of memory required */ int nPMA; /* Bytes of PMA space required */ int t; /* serial type of first record field */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; getVarint32((const u8*)&pVal->z[1], t); if( t>0 && t<10 && t!=7 ){ pSorter->typeMask &= SORTER_TYPE_INTEGER; }else if( t>10 && (t & 0x01) ){ pSorter->typeMask &= SORTER_TYPE_TEXT; }else{ pSorter->typeMask = 0; } assert( pSorter ); /* Figure out whether or not the current contents of memory should be ** flushed to a PMA before continuing. If so, do so. ** ** If using the single large allocation mode (pSorter->aMemory!=0), then ** flush the contents of memory to a new PMA if (a) at least one value is ** already in memory and (b) the new value will not fit in memory. ** ** Or, if using separate allocations for each record, flush the contents ** of memory to a PMA if either of the following are true: ** ** * The total memory allocated for the in-memory list is greater ** than (page-size * cache-size), or ** ** * The total memory allocated for the in-memory list is greater ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true. */ nReq = pVal->n + sizeof(SorterRecord); nPMA = pVal->n + sqlite3VarintLen(pVal->n); if( pSorter->mxPmaSize ){ if( pSorter->list.aMemory ){ bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize; }else{ bFlush = ( (pSorter->list.szPMA > pSorter->mxPmaSize) || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull()) ); } if( bFlush ){ rc = vdbeSorterFlushPMA(pSorter); pSorter->list.szPMA = 0; pSorter->iMemory = 0; assert( rc!=SQLITE_OK || pSorter->list.pList==0 ); } } pSorter->list.szPMA += nPMA; if( nPMA>pSorter->mxKeysize ){ pSorter->mxKeysize = nPMA; } if( pSorter->list.aMemory ){ int nMin = pSorter->iMemory + nReq; if( nMin>pSorter->nMemory ){ u8 *aNew; int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory; int nNew = pSorter->nMemory * 2; while( nNew < nMin ) nNew = nNew*2; if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize; if( nNew < nMin ) nNew = nMin; aNew = sqlite3Realloc(pSorter->list.aMemory, nNew); if( !aNew ) return SQLITE_NOMEM_BKPT; pSorter->list.pList = (SorterRecord*)&aNew[iListOff]; pSorter->list.aMemory = aNew; pSorter->nMemory = nNew; } pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory]; pSorter->iMemory += ROUND8(nReq); if( pSorter->list.pList ){ pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory); } }else{ pNew = (SorterRecord *)sqlite3Malloc(nReq); if( pNew==0 ){ return SQLITE_NOMEM_BKPT; } pNew->u.pNext = pSorter->list.pList; } memcpy(SRVAL(pNew), pVal->z, pVal->n); pNew->nVal = pVal->n; pSorter->list.pList = pNew; return rc; } /* ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format ** of the data stored in aFile[1] is the same as that used by regular PMAs, ** except that the number-of-bytes varint is omitted from the start. */ static int vdbeIncrPopulate(IncrMerger *pIncr){ int rc = SQLITE_OK; int rc2; i64 iStart = pIncr->iStartOff; SorterFile *pOut = &pIncr->aFile[1]; SortSubtask *pTask = pIncr->pTask; MergeEngine *pMerger = pIncr->pMerger; PmaWriter writer; assert( pIncr->bEof==0 ); vdbeSorterPopulateDebug(pTask, "enter"); vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart); while( rc==SQLITE_OK ){ int dummy; PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ]; int nKey = pReader->nKey; i64 iEof = writer.iWriteOff + writer.iBufEnd; /* Check if the output file is full or if the input has been exhausted. ** In either case exit the loop. */ if( pReader->pFd==0 ) break; if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break; /* Write the next key to the output. */ vdbePmaWriteVarint(&writer, nKey); vdbePmaWriteBlob(&writer, pReader->aKey, nKey); assert( pIncr->pMerger->pTask==pTask ); rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy); } rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof); if( rc==SQLITE_OK ) rc = rc2; vdbeSorterPopulateDebug(pTask, "exit"); return rc; } #if SQLITE_MAX_WORKER_THREADS>0 /* ** The main routine for background threads that populate aFile[1] of ** multi-threaded IncrMerger objects. */ static void *vdbeIncrPopulateThread(void *pCtx){ IncrMerger *pIncr = (IncrMerger*)pCtx; void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) ); pIncr->pTask->bDone = 1; return pRet; } /* ** Launch a background thread to populate aFile[1] of pIncr. */ static int vdbeIncrBgPopulate(IncrMerger *pIncr){ void *p = (void*)pIncr; assert( pIncr->bUseThread ); return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p); } #endif /* ** This function is called when the PmaReader corresponding to pIncr has ** finished reading the contents of aFile[0]. Its purpose is to "refill" ** aFile[0] such that the PmaReader should start rereading it from the ** beginning. ** ** For single-threaded objects, this is accomplished by literally reading ** keys from pIncr->pMerger and repopulating aFile[0]. ** ** For multi-threaded objects, all that is required is to wait until the ** background thread is finished (if it is not already) and then swap ** aFile[0] and aFile[1] in place. If the contents of pMerger have not ** been exhausted, this function also launches a new background thread ** to populate the new aFile[1]. ** ** SQLITE_OK is returned on success, or an SQLite error code otherwise. */ static int vdbeIncrSwap(IncrMerger *pIncr){ int rc = SQLITE_OK; #if SQLITE_MAX_WORKER_THREADS>0 if( pIncr->bUseThread ){ rc = vdbeSorterJoinThread(pIncr->pTask); if( rc==SQLITE_OK ){ SorterFile f0 = pIncr->aFile[0]; pIncr->aFile[0] = pIncr->aFile[1]; pIncr->aFile[1] = f0; } if( rc==SQLITE_OK ){ if( pIncr->aFile[0].iEof==pIncr->iStartOff ){ pIncr->bEof = 1; }else{ rc = vdbeIncrBgPopulate(pIncr); } } }else #endif { rc = vdbeIncrPopulate(pIncr); pIncr->aFile[0] = pIncr->aFile[1]; if( pIncr->aFile[0].iEof==pIncr->iStartOff ){ pIncr->bEof = 1; } } return rc; } /* ** Allocate and return a new IncrMerger object to read data from pMerger. ** ** If an OOM condition is encountered, return NULL. In this case free the ** pMerger argument before returning. */ static int vdbeIncrMergerNew( SortSubtask *pTask, /* The thread that will be using the new IncrMerger */ MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */ IncrMerger **ppOut /* Write the new IncrMerger here */ ){ int rc = SQLITE_OK; IncrMerger *pIncr = *ppOut = (IncrMerger*) (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr))); if( pIncr ){ pIncr->pMerger = pMerger; pIncr->pTask = pTask; pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2); pTask->file2.iEof += pIncr->mxSz; }else{ vdbeMergeEngineFree(pMerger); rc = SQLITE_NOMEM_BKPT; } return rc; } #if SQLITE_MAX_WORKER_THREADS>0 /* ** Set the "use-threads" flag on object pIncr. */ static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){ pIncr->bUseThread = 1; pIncr->pTask->file2.iEof -= pIncr->mxSz; } #endif /* SQLITE_MAX_WORKER_THREADS>0 */ /* ** Recompute pMerger->aTree[iOut] by comparing the next keys on the ** two PmaReaders that feed that entry. Neither of the PmaReaders ** are advanced. This routine merely does the comparison. */ static void vdbeMergeEngineCompare( MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */ int iOut /* Store the result in pMerger->aTree[iOut] */ ){ int i1; int i2; int iRes; PmaReader *p1; PmaReader *p2; assert( iOut<pMerger->nTree && iOut>0 ); if( iOut>=(pMerger->nTree/2) ){ i1 = (iOut - pMerger->nTree/2) * 2; i2 = i1 + 1; }else{ i1 = pMerger->aTree[iOut*2]; i2 = pMerger->aTree[iOut*2+1]; } p1 = &pMerger->aReadr[i1]; p2 = &pMerger->aReadr[i2]; if( p1->pFd==0 ){ iRes = i2; }else if( p2->pFd==0 ){ iRes = i1; }else{ SortSubtask *pTask = pMerger->pTask; int bCached = 0; int res; assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */ res = pTask->xCompare( pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey ); if( res<=0 ){ iRes = i1; }else{ iRes = i2; } } pMerger->aTree[iOut] = iRes; } /* ** Allowed values for the eMode parameter to vdbeMergeEngineInit() ** and vdbePmaReaderIncrMergeInit(). ** ** Only INCRINIT_NORMAL is valid in single-threaded builds (when ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used ** when there exists one or more separate worker threads. */ #define INCRINIT_NORMAL 0 #define INCRINIT_TASK 1 #define INCRINIT_ROOT 2 /* ** Forward reference required as the vdbeIncrMergeInit() and ** vdbePmaReaderIncrInit() routines are called mutually recursively when ** building a merge tree. */ static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode); /* ** Initialize the MergeEngine object passed as the second argument. Once this ** function returns, the first key of merged data may be read from the ** MergeEngine object in the usual fashion. ** ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge ** objects attached to the PmaReader objects that the merger reads from have ** already been populated, but that they have not yet populated aFile[0] and ** set the PmaReader objects up to read from it. In this case all that is ** required is to call vdbePmaReaderNext() on each PmaReader to point it at ** its first key. ** ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data ** to pMerger. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ static int vdbeMergeEngineInit( SortSubtask *pTask, /* Thread that will run pMerger */ MergeEngine *pMerger, /* MergeEngine to initialize */ int eMode /* One of the INCRINIT_XXX constants */ ){ int rc = SQLITE_OK; /* Return code */ int i; /* For looping over PmaReader objects */ int nTree = pMerger->nTree; /* eMode is always INCRINIT_NORMAL in single-threaded mode */ assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); /* Verify that the MergeEngine is assigned to a single thread */ assert( pMerger->pTask==0 ); pMerger->pTask = pTask; for(i=0; i<nTree; i++){ if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){ /* PmaReaders should be normally initialized in order, as if they are ** reading from the same temp file this makes for more linear file IO. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is ** in use it will block the vdbePmaReaderNext() call while it uses ** the main thread to fill its buffer. So calling PmaReaderNext() ** on this PmaReader before any of the multi-threaded PmaReaders takes ** better advantage of multi-processor hardware. */ rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]); }else{ rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL); } if( rc!=SQLITE_OK ) return rc; } for(i=pMerger->nTree-1; i>0; i--){ vdbeMergeEngineCompare(pMerger, i); } return pTask->pUnpacked->errCode; } /* ** The PmaReader passed as the first argument is guaranteed to be an ** incremental-reader (pReadr->pIncr!=0). This function serves to open ** and/or initialize the temp file related fields of the IncrMerge ** object at (pReadr->pIncr). ** ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders ** in the sub-tree headed by pReadr are also initialized. Data is then ** loaded into the buffers belonging to pReadr and it is set to point to ** the first key in its range. ** ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed ** to be a multi-threaded PmaReader and this function is being called in a ** background thread. In this case all PmaReaders in the sub-tree are ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to ** pReadr is populated. However, pReadr itself is not set up to point ** to its first key. A call to vdbePmaReaderNext() is still required to do ** that. ** ** The reason this function does not call vdbePmaReaderNext() immediately ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has ** to block on thread (pTask->thread) before accessing aFile[1]. But, since ** this entire function is being run by thread (pTask->thread), that will ** lead to the current background thread attempting to join itself. ** ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all ** child-trees have already been initialized using IncrInit(INCRINIT_TASK). ** In this case vdbePmaReaderNext() is called on all child PmaReaders and ** the current PmaReader set to point to the first key in its range. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){ int rc = SQLITE_OK; IncrMerger *pIncr = pReadr->pIncr; SortSubtask *pTask = pIncr->pTask; sqlite3 *db = pTask->pSorter->db; /* eMode is always INCRINIT_NORMAL in single-threaded mode */ assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode); /* Set up the required files for pIncr. A multi-theaded IncrMerge object ** requires two temp files to itself, whereas a single-threaded object ** only requires a region of pTask->file2. */ if( rc==SQLITE_OK ){ int mxSz = pIncr->mxSz; #if SQLITE_MAX_WORKER_THREADS>0 if( pIncr->bUseThread ){ rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd); if( rc==SQLITE_OK ){ rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd); } }else #endif /*if( !pIncr->bUseThread )*/{ if( pTask->file2.pFd==0 ){ assert( pTask->file2.iEof>0 ); rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd); pTask->file2.iEof = 0; } if( rc==SQLITE_OK ){ pIncr->aFile[1].pFd = pTask->file2.pFd; pIncr->iStartOff = pTask->file2.iEof; pTask->file2.iEof += mxSz; } } } #if SQLITE_MAX_WORKER_THREADS>0 if( rc==SQLITE_OK && pIncr->bUseThread ){ /* Use the current thread to populate aFile[1], even though this ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object, ** then this function is already running in background thread ** pIncr->pTask->thread. ** ** If this is the INCRINIT_ROOT object, then it is running in the ** main VDBE thread. But that is Ok, as that thread cannot return ** control to the VDBE or proceed with anything useful until the ** first results are ready from this merger object anyway. */ assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK ); rc = vdbeIncrPopulate(pIncr); } #endif if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){ rc = vdbePmaReaderNext(pReadr); } return rc; } #if SQLITE_MAX_WORKER_THREADS>0 /* ** The main routine for vdbePmaReaderIncrMergeInit() operations run in ** background threads. */ static void *vdbePmaReaderBgIncrInit(void *pCtx){ PmaReader *pReader = (PmaReader*)pCtx; void *pRet = SQLITE_INT_TO_PTR( vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK) ); pReader->pIncr->pTask->bDone = 1; return pRet; } #endif /* ** If the PmaReader passed as the first argument is not an incremental-reader ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to ** this routine to initialize the incremental merge. ** ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), ** then a background thread is launched to call vdbePmaReaderIncrMergeInit(). ** Or, if the IncrMerger is single threaded, the same function is called ** using the current thread. */ static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){ IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */ int rc = SQLITE_OK; /* Return code */ if( pIncr ){ #if SQLITE_MAX_WORKER_THREADS>0 assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK ); if( pIncr->bUseThread ){ void *pCtx = (void*)pReadr; rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx); }else #endif { rc = vdbePmaReaderIncrMergeInit(pReadr, eMode); } } return rc; } /* ** Allocate a new MergeEngine object to merge the contents of nPMA level-0 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut ** to NULL and return an SQLite error code. ** ** When this function is called, *piOffset is set to the offset of the ** first PMA to read from pTask->file. Assuming no error occurs, it is ** set to the offset immediately following the last byte of the last ** PMA before returning. If an error does occur, then the final value of ** *piOffset is undefined. */ static int vdbeMergeEngineLevel0( SortSubtask *pTask, /* Sorter task to read from */ int nPMA, /* Number of PMAs to read */ i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */ MergeEngine **ppOut /* OUT: New merge-engine */ ){ MergeEngine *pNew; /* Merge engine to return */ i64 iOff = *piOffset; int i; int rc = SQLITE_OK; *ppOut = pNew = vdbeMergeEngineNew(nPMA); if( pNew==0 ) rc = SQLITE_NOMEM_BKPT; for(i=0; i<nPMA && rc==SQLITE_OK; i++){ i64 nDummy = 0; PmaReader *pReadr = &pNew->aReadr[i]; rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy); iOff = pReadr->iEof; } if( rc!=SQLITE_OK ){ vdbeMergeEngineFree(pNew); *ppOut = 0; } *piOffset = iOff; return rc; } /* ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes. ** ** i.e. ** ** nPMA<=16 -> TreeDepth() == 0 ** nPMA<=256 -> TreeDepth() == 1 ** nPMA<=65536 -> TreeDepth() == 2 */ static int vdbeSorterTreeDepth(int nPMA){ int nDepth = 0; i64 nDiv = SORTER_MAX_MERGE_COUNT; while( nDiv < (i64)nPMA ){ nDiv = nDiv * SORTER_MAX_MERGE_COUNT; nDepth++; } return nDepth; } /* ** pRoot is the root of an incremental merge-tree with depth nDepth (according ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the ** tree, counting from zero. This function adds pLeaf to the tree. ** ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error ** code is returned and pLeaf is freed. */ static int vdbeSorterAddToTree( SortSubtask *pTask, /* Task context */ int nDepth, /* Depth of tree according to TreeDepth() */ int iSeq, /* Sequence number of leaf within tree */ MergeEngine *pRoot, /* Root of tree */ MergeEngine *pLeaf /* Leaf to add to tree */ ){ int rc = SQLITE_OK; int nDiv = 1; int i; MergeEngine *p = pRoot; IncrMerger *pIncr; rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr); for(i=1; i<nDepth; i++){ nDiv = nDiv * SORTER_MAX_MERGE_COUNT; } for(i=1; i<nDepth && rc==SQLITE_OK; i++){ int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT; PmaReader *pReadr = &p->aReadr[iIter]; if( pReadr->pIncr==0 ){ MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT); if( pNew==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr); } } if( rc==SQLITE_OK ){ p = pReadr->pIncr->pMerger; nDiv = nDiv / SORTER_MAX_MERGE_COUNT; } } if( rc==SQLITE_OK ){ p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr; }else{ vdbeIncrFree(pIncr); } return rc; } /* ** This function is called as part of a SorterRewind() operation on a sorter ** that has already written two or more level-0 PMAs to one or more temp ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that ** can be used to incrementally merge all PMAs on disk. ** ** If successful, SQLITE_OK is returned and *ppOut set to point to the ** MergeEngine object at the root of the tree before returning. Or, if an ** error occurs, an SQLite error code is returned and the final value ** of *ppOut is undefined. */ static int vdbeSorterMergeTreeBuild( VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */ MergeEngine **ppOut /* Write the MergeEngine here */ ){ MergeEngine *pMain = 0; int rc = SQLITE_OK; int iTask; #if SQLITE_MAX_WORKER_THREADS>0 /* If the sorter uses more than one task, then create the top-level ** MergeEngine here. This MergeEngine will read data from exactly ** one PmaReader per sub-task. */ assert( pSorter->bUseThreads || pSorter->nTask==1 ); if( pSorter->nTask>1 ){ pMain = vdbeMergeEngineNew(pSorter->nTask); if( pMain==0 ) rc = SQLITE_NOMEM_BKPT; } #endif for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){ SortSubtask *pTask = &pSorter->aTask[iTask]; assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 ); if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){ MergeEngine *pRoot = 0; /* Root node of tree for this task */ int nDepth = vdbeSorterTreeDepth(pTask->nPMA); i64 iReadOff = 0; if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){ rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot); }else{ int i; int iSeq = 0; pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT); if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT; for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){ MergeEngine *pMerger = 0; /* New level-0 PMA merger */ int nReader; /* Number of level-0 PMAs to merge */ nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT); rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger); if( rc==SQLITE_OK ){ rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger); } } } if( rc==SQLITE_OK ){ #if SQLITE_MAX_WORKER_THREADS>0 if( pMain!=0 ){ rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr); }else #endif { assert( pMain==0 ); pMain = pRoot; } }else{ vdbeMergeEngineFree(pRoot); } } } if( rc!=SQLITE_OK ){ vdbeMergeEngineFree(pMain); pMain = 0; } *ppOut = pMain; return rc; } /* ** This function is called as part of an sqlite3VdbeSorterRewind() operation ** on a sorter that has written two or more PMAs to temporary files. It sets ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader ** (for multi-threaded sorters) so that it can be used to iterate through ** all records stored in the sorter. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ static int vdbeSorterSetupMerge(VdbeSorter *pSorter){ int rc; /* Return code */ SortSubtask *pTask0 = &pSorter->aTask[0]; MergeEngine *pMain = 0; #if SQLITE_MAX_WORKER_THREADS sqlite3 *db = pTask0->pSorter->db; int i; SorterCompare xCompare = vdbeSorterGetCompare(pSorter); for(i=0; i<pSorter->nTask; i++){ pSorter->aTask[i].xCompare = xCompare; } #endif rc = vdbeSorterMergeTreeBuild(pSorter, &pMain); if( rc==SQLITE_OK ){ #if SQLITE_MAX_WORKER_THREADS assert( pSorter->bUseThreads==0 || pSorter->nTask>1 ); if( pSorter->bUseThreads ){ int iTask; PmaReader *pReadr = 0; SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1]; rc = vdbeSortAllocUnpacked(pLast); if( rc==SQLITE_OK ){ pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader)); pSorter->pReader = pReadr; if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT; } if( rc==SQLITE_OK ){ rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr); if( rc==SQLITE_OK ){ vdbeIncrMergerSetThreads(pReadr->pIncr); for(iTask=0; iTask<(pSorter->nTask-1); iTask++){ IncrMerger *pIncr; if( (pIncr = pMain->aReadr[iTask].pIncr) ){ vdbeIncrMergerSetThreads(pIncr); assert( pIncr->pTask!=pLast ); } } for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){ /* Check that: ** ** a) The incremental merge object is configured to use the ** right task, and ** b) If it is using task (nTask-1), it is configured to run ** in single-threaded mode. This is important, as the ** root merge (INCRINIT_ROOT) will be using the same task ** object. */ PmaReader *p = &pMain->aReadr[iTask]; assert( p->pIncr==0 || ( (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */ && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */ )); rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK); } } pMain = 0; } if( rc==SQLITE_OK ){ rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT); } }else #endif { rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL); pSorter->pMerger = pMain; pMain = 0; } } if( rc!=SQLITE_OK ){ vdbeMergeEngineFree(pMain); } return rc; } /* ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite, ** this function is called to prepare for iterating through the records ** in sorted order. */ SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){ VdbeSorter *pSorter; int rc = SQLITE_OK; /* Return code */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; assert( pSorter ); /* If no data has been written to disk, then do not do so now. Instead, ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly ** from the in-memory list. */ if( pSorter->bUsePMA==0 ){ if( pSorter->list.pList ){ *pbEof = 0; rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list); }else{ *pbEof = 1; } return rc; } /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() ** function flushes the contents of memory to disk, it immediately always ** creates a new list consisting of a single key immediately afterwards. ** So the list is never empty at this point. */ assert( pSorter->list.pList ); rc = vdbeSorterFlushPMA(pSorter); /* Join all threads */ rc = vdbeSorterJoinAll(pSorter, rc); vdbeSorterRewindDebug("rewind"); /* Assuming no errors have occurred, set up a merger structure to ** incrementally read and merge all remaining PMAs. */ assert( pSorter->pReader==0 ); if( rc==SQLITE_OK ){ rc = vdbeSorterSetupMerge(pSorter); *pbEof = 0; } vdbeSorterRewindDebug("rewinddone"); return rc; } /* ** Advance to the next element in the sorter. */ SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){ VdbeSorter *pSorter; int rc; /* Return code */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) ); if( pSorter->bUsePMA ){ assert( pSorter->pReader==0 || pSorter->pMerger==0 ); assert( pSorter->bUseThreads==0 || pSorter->pReader ); assert( pSorter->bUseThreads==1 || pSorter->pMerger ); #if SQLITE_MAX_WORKER_THREADS>0 if( pSorter->bUseThreads ){ rc = vdbePmaReaderNext(pSorter->pReader); *pbEof = (pSorter->pReader->pFd==0); }else #endif /*if( !pSorter->bUseThreads )*/ { assert( pSorter->pMerger!=0 ); assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) ); rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof); } }else{ SorterRecord *pFree = pSorter->list.pList; pSorter->list.pList = pFree->u.pNext; pFree->u.pNext = 0; if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree); *pbEof = !pSorter->list.pList; rc = SQLITE_OK; } return rc; } /* ** Return a pointer to a buffer owned by the sorter that contains the ** current key. */ static void *vdbeSorterRowkey( const VdbeSorter *pSorter, /* Sorter object */ int *pnKey /* OUT: Size of current key in bytes */ ){ void *pKey; if( pSorter->bUsePMA ){ PmaReader *pReader; #if SQLITE_MAX_WORKER_THREADS>0 if( pSorter->bUseThreads ){ pReader = pSorter->pReader; }else #endif /*if( !pSorter->bUseThreads )*/{ pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]]; } *pnKey = pReader->nKey; pKey = pReader->aKey; }else{ *pnKey = pSorter->list.pList->nVal; pKey = SRVAL(pSorter->list.pList); } return pKey; } /* ** Copy the current sorter key into the memory cell pOut. */ SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ VdbeSorter *pSorter; void *pKey; int nKey; /* Sorter key to copy into pOut */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; pKey = vdbeSorterRowkey(pSorter, &nKey); if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){ return SQLITE_NOMEM_BKPT; } pOut->n = nKey; MemSetTypeFlag(pOut, MEM_Blob); memcpy(pOut->z, pKey, nKey); return SQLITE_OK; } /* ** Compare the key in memory cell pVal with the key that the sorter cursor ** passed as the first argument currently points to. For the purposes of ** the comparison, ignore the rowid field at the end of each record. ** ** If the sorter cursor key contains any NULL values, consider it to be ** less than pVal. Even if pVal also contains NULL values. ** ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM). ** Otherwise, set *pRes to a negative, zero or positive value if the ** key in pVal is smaller than, equal to or larger than the current sorter ** key. ** ** This routine forms the core of the OP_SorterCompare opcode, which in ** turn is used to verify uniqueness when constructing a UNIQUE INDEX. */ SQLITE_PRIVATE int sqlite3VdbeSorterCompare( const VdbeCursor *pCsr, /* Sorter cursor */ Mem *pVal, /* Value to compare to current sorter key */ int nKeyCol, /* Compare this many columns */ int *pRes /* OUT: Result of comparison */ ){ VdbeSorter *pSorter; UnpackedRecord *r2; KeyInfo *pKeyInfo; int i; void *pKey; int nKey; /* Sorter key to compare pVal with */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; r2 = pSorter->pUnpacked; pKeyInfo = pCsr->pKeyInfo; if( r2==0 ){ r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); if( r2==0 ) return SQLITE_NOMEM_BKPT; r2->nField = nKeyCol; } assert( r2->nField==nKeyCol ); pKey = vdbeSorterRowkey(pSorter, &nKey); sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2); for(i=0; i<nKeyCol; i++){ if( r2->aMem[i].flags & MEM_Null ){ *pRes = -1; return SQLITE_OK; } } *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2); return SQLITE_OK; } /************** End of vdbesort.c ********************************************/ /************** Begin file memjournal.c **************************************/ /* ** 2008 October 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code use to implement an in-memory rollback journal. ** The in-memory rollback journal is used to journal transactions for ** ":memory:" databases and when the journal_mode=MEMORY pragma is used. ** ** Update: The in-memory journal is also used to temporarily cache ** smaller journals that are not critical for power-loss recovery. ** For example, statement journals that are not too big will be held ** entirely in memory, thus reducing the number of file I/O calls, and ** more importantly, reducing temporary file creation events. If these ** journals become too large for memory, they are spilled to disk. But ** in the common case, they are usually small and no file I/O needs to ** occur. */ /* #include "sqliteInt.h" */ /* Forward references to internal structures */ typedef struct MemJournal MemJournal; typedef struct FilePoint FilePoint; typedef struct FileChunk FileChunk; /* ** The rollback journal is composed of a linked list of these structures. ** ** The zChunk array is always at least 8 bytes in size - usually much more. ** Its actual size is stored in the MemJournal.nChunkSize variable. */ struct FileChunk { FileChunk *pNext; /* Next chunk in the journal */ u8 zChunk[8]; /* Content of this chunk */ }; /* ** By default, allocate this many bytes of memory for each FileChunk object. */ #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024 /* ** For chunk size nChunkSize, return the number of bytes that should ** be allocated for each FileChunk structure. */ #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8)) /* ** An instance of this object serves as a cursor into the rollback journal. ** The cursor can be either for reading or writing. */ struct FilePoint { sqlite3_int64 iOffset; /* Offset from the beginning of the file */ FileChunk *pChunk; /* Specific chunk into which cursor points */ }; /* ** This structure is a subclass of sqlite3_file. Each open memory-journal ** is an instance of this class. */ struct MemJournal { const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */ int nChunkSize; /* In-memory chunk-size */ int nSpill; /* Bytes of data before flushing */ int nSize; /* Bytes of data currently in memory */ FileChunk *pFirst; /* Head of in-memory chunk-list */ FilePoint endpoint; /* Pointer to the end of the file */ FilePoint readpoint; /* Pointer to the end of the last xRead() */ int flags; /* xOpen flags */ sqlite3_vfs *pVfs; /* The "real" underlying VFS */ const char *zJournal; /* Name of the journal file */ }; /* ** Read data from the in-memory journal file. This is the implementation ** of the sqlite3_vfs.xRead method. */ static int memjrnlRead( sqlite3_file *pJfd, /* The journal file from which to read */ void *zBuf, /* Put the results here */ int iAmt, /* Number of bytes to read */ sqlite_int64 iOfst /* Begin reading at this offset */ ){ MemJournal *p = (MemJournal *)pJfd; u8 *zOut = zBuf; int nRead = iAmt; int iChunkOffset; FileChunk *pChunk; #ifdef SQLITE_ENABLE_ATOMIC_WRITE if( (iAmt+iOfst)>p->endpoint.iOffset ){ return SQLITE_IOERR_SHORT_READ; } #endif assert( (iAmt+iOfst)<=p->endpoint.iOffset ); assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 ); if( p->readpoint.iOffset!=iOfst || iOfst==0 ){ sqlite3_int64 iOff = 0; for(pChunk=p->pFirst; ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst; pChunk=pChunk->pNext ){ iOff += p->nChunkSize; } }else{ pChunk = p->readpoint.pChunk; assert( pChunk!=0 ); } iChunkOffset = (int)(iOfst%p->nChunkSize); do { int iSpace = p->nChunkSize - iChunkOffset; int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset)); memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy); zOut += nCopy; nRead -= iSpace; iChunkOffset = 0; } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 ); p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0; p->readpoint.pChunk = pChunk; return SQLITE_OK; } /* ** Free the list of FileChunk structures headed at MemJournal.pFirst. */ static void memjrnlFreeChunks(MemJournal *p){ FileChunk *pIter; FileChunk *pNext; for(pIter=p->pFirst; pIter; pIter=pNext){ pNext = pIter->pNext; sqlite3_free(pIter); } p->pFirst = 0; } /* ** Flush the contents of memory to a real file on disk. */ static int memjrnlCreateFile(MemJournal *p){ int rc; sqlite3_file *pReal = (sqlite3_file*)p; MemJournal copy = *p; memset(p, 0, sizeof(MemJournal)); rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0); if( rc==SQLITE_OK ){ int nChunk = copy.nChunkSize; i64 iOff = 0; FileChunk *pIter; for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){ if( iOff + nChunk > copy.endpoint.iOffset ){ nChunk = copy.endpoint.iOffset - iOff; } rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff); if( rc ) break; iOff += nChunk; } if( rc==SQLITE_OK ){ /* No error has occurred. Free the in-memory buffers. */ memjrnlFreeChunks(&copy); } } if( rc!=SQLITE_OK ){ /* If an error occurred while creating or writing to the file, restore ** the original before returning. This way, SQLite uses the in-memory ** journal data to roll back changes made to the internal page-cache ** before this function was called. */ sqlite3OsClose(pReal); *p = copy; } return rc; } /* ** Write data to the file. */ static int memjrnlWrite( sqlite3_file *pJfd, /* The journal file into which to write */ const void *zBuf, /* Take data to be written from here */ int iAmt, /* Number of bytes to write */ sqlite_int64 iOfst /* Begin writing at this offset into the file */ ){ MemJournal *p = (MemJournal *)pJfd; int nWrite = iAmt; u8 *zWrite = (u8 *)zBuf; /* If the file should be created now, create it and write the new data ** into the file on disk. */ if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){ int rc = memjrnlCreateFile(p); if( rc==SQLITE_OK ){ rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst); } return rc; } /* If the contents of this write should be stored in memory */ else{ /* An in-memory journal file should only ever be appended to. Random ** access writes are not required. The only exception to this is when ** the in-memory journal is being used by a connection using the ** atomic-write optimization. In this case the first 28 bytes of the ** journal file may be written as part of committing the transaction. */ assert( iOfst==p->endpoint.iOffset || iOfst==0 ); #ifdef SQLITE_ENABLE_ATOMIC_WRITE if( iOfst==0 && p->pFirst ){ assert( p->nChunkSize>iAmt ); memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt); }else #else assert( iOfst>0 || p->pFirst==0 ); #endif { while( nWrite>0 ){ FileChunk *pChunk = p->endpoint.pChunk; int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize); int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset); if( iChunkOffset==0 ){ /* New chunk is required to extend the file. */ FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize)); if( !pNew ){ return SQLITE_IOERR_NOMEM_BKPT; } pNew->pNext = 0; if( pChunk ){ assert( p->pFirst ); pChunk->pNext = pNew; }else{ assert( !p->pFirst ); p->pFirst = pNew; } p->endpoint.pChunk = pNew; } memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace); zWrite += iSpace; nWrite -= iSpace; p->endpoint.iOffset += iSpace; } p->nSize = iAmt + iOfst; } } return SQLITE_OK; } /* ** Truncate the file. ** ** If the journal file is already on disk, truncate it there. Or, if it ** is still in main memory but is being truncated to zero bytes in size, ** ignore */ static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ MemJournal *p = (MemJournal *)pJfd; if( ALWAYS(size==0) ){ memjrnlFreeChunks(p); p->nSize = 0; p->endpoint.pChunk = 0; p->endpoint.iOffset = 0; p->readpoint.pChunk = 0; p->readpoint.iOffset = 0; } return SQLITE_OK; } /* ** Close the file. */ static int memjrnlClose(sqlite3_file *pJfd){ MemJournal *p = (MemJournal *)pJfd; memjrnlFreeChunks(p); return SQLITE_OK; } /* ** Sync the file. ** ** If the real file has been created, call its xSync method. Otherwise, ** syncing an in-memory journal is a no-op. */ static int memjrnlSync(sqlite3_file *pJfd, int flags){ UNUSED_PARAMETER2(pJfd, flags); return SQLITE_OK; } /* ** Query the size of the file in bytes. */ static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){ MemJournal *p = (MemJournal *)pJfd; *pSize = (sqlite_int64) p->endpoint.iOffset; return SQLITE_OK; } /* ** Table of methods for MemJournal sqlite3_file object. */ static const struct sqlite3_io_methods MemJournalMethods = { 1, /* iVersion */ memjrnlClose, /* xClose */ memjrnlRead, /* xRead */ memjrnlWrite, /* xWrite */ memjrnlTruncate, /* xTruncate */ memjrnlSync, /* xSync */ memjrnlFileSize, /* xFileSize */ 0, /* xLock */ 0, /* xUnlock */ 0, /* xCheckReservedLock */ 0, /* xFileControl */ 0, /* xSectorSize */ 0, /* xDeviceCharacteristics */ 0, /* xShmMap */ 0, /* xShmLock */ 0, /* xShmBarrier */ 0, /* xShmUnmap */ 0, /* xFetch */ 0 /* xUnfetch */ }; /* ** Open a journal file. ** ** The behaviour of the journal file depends on the value of parameter ** nSpill. If nSpill is 0, then the journal file is always create and ** accessed using the underlying VFS. If nSpill is less than zero, then ** all content is always stored in main-memory. Finally, if nSpill is a ** positive value, then the journal file is initially created in-memory ** but may be flushed to disk later on. In this case the journal file is ** flushed to disk either when it grows larger than nSpill bytes in size, ** or when sqlite3JournalCreate() is called. */ SQLITE_PRIVATE int sqlite3JournalOpen( sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */ const char *zName, /* Name of the journal file */ sqlite3_file *pJfd, /* Preallocated, blank file handle */ int flags, /* Opening flags */ int nSpill /* Bytes buffered before opening the file */ ){ MemJournal *p = (MemJournal*)pJfd; /* Zero the file-handle object. If nSpill was passed zero, initialize ** it using the sqlite3OsOpen() function of the underlying VFS. In this ** case none of the code in this module is executed as a result of calls ** made on the journal file-handle. */ memset(p, 0, sizeof(MemJournal)); if( nSpill==0 ){ return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); } if( nSpill>0 ){ p->nChunkSize = nSpill; }else{ p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk); assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) ); } p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods; p->nSpill = nSpill; p->flags = flags; p->zJournal = zName; p->pVfs = pVfs; return SQLITE_OK; } /* ** Open an in-memory journal file. */ SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){ sqlite3JournalOpen(0, 0, pJfd, 0, -1); } #ifdef SQLITE_ENABLE_ATOMIC_WRITE /* ** If the argument p points to a MemJournal structure that is not an ** in-memory-only journal file (i.e. is one that was opened with a +ve ** nSpill parameter), and the underlying file has not yet been created, ** create it now. */ SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){ int rc = SQLITE_OK; if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){ rc = memjrnlCreateFile((MemJournal*)p); } return rc; } #endif /* ** The file-handle passed as the only argument is open on a journal file. ** Return true if this "journal file" is currently stored in heap memory, ** or false otherwise. */ SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){ return p->pMethods==&MemJournalMethods; } /* ** Return the number of bytes required to store a JournalFile that uses vfs ** pVfs to create the underlying on-disk files. */ SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){ return MAX(pVfs->szOsFile, (int)sizeof(MemJournal)); } /************** End of memjournal.c ******************************************/ /************** Begin file walker.c ******************************************/ /* ** 2008 August 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used for walking the parser tree for ** an SQL statement. */ /* #include "sqliteInt.h" */ /* #include <stdlib.h> */ /* #include <string.h> */ /* ** Walk an expression tree. Invoke the callback once for each node ** of the expression, while descending. (In other words, the callback ** is invoked before visiting children.) ** ** The return value from the callback should be one of the WRC_* ** constants to specify how to proceed with the walk. ** ** WRC_Continue Continue descending down the tree. ** ** WRC_Prune Do not descend into child nodes. But allow ** the walk to continue with sibling nodes. ** ** WRC_Abort Do no more callbacks. Unwind the stack and ** return the top-level walk call. ** ** The return value from this routine is WRC_Abort to abandon the tree walk ** and WRC_Continue to continue. */ static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){ int rc; testcase( ExprHasProperty(pExpr, EP_TokenOnly) ); testcase( ExprHasProperty(pExpr, EP_Reduced) ); rc = pWalker->xExprCallback(pWalker, pExpr); if( rc || ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){ return rc & WRC_Abort; } if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; }else if( pExpr->x.pList ){ if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; } return WRC_Continue; } SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){ return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue; } /* ** Call sqlite3WalkExpr() for every expression in list p or until ** an abort request is seen. */ SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ int i; struct ExprList_item *pItem; if( p ){ for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){ if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort; } } return WRC_Continue; } /* ** Walk all expressions associated with SELECT statement p. Do ** not invoke the SELECT callback on p, but do (of course) invoke ** any expr callbacks and SELECT callbacks that come from subqueries. ** Return WRC_Abort or WRC_Continue. */ SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort; if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort; if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort; if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort; if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort; if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort; if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort; return WRC_Continue; } /* ** Walk the parse trees associated with all subqueries in the ** FROM clause of SELECT statement p. Do not invoke the select ** callback on p, but do invoke it on each FROM clause subquery ** and on any subqueries further down in the tree. Return ** WRC_Abort or WRC_Continue; */ SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ SrcList *pSrc; int i; struct SrcList_item *pItem; pSrc = p->pSrc; if( ALWAYS(pSrc) ){ for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){ return WRC_Abort; } if( pItem->fg.isTabFunc && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg) ){ return WRC_Abort; } } } return WRC_Continue; } /* ** Call sqlite3WalkExpr() for every expression in Select statement p. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and ** on the compound select chain, p->pPrior. ** ** If it is not NULL, the xSelectCallback() callback is invoked before ** the walk of the expressions and FROM clause. The xSelectCallback2() ** method, if it is not NULL, is invoked following the walk of the ** expressions and FROM clause. ** ** Return WRC_Continue under normal conditions. Return WRC_Abort if ** there is an abort request. ** ** If the Walker does not have an xSelectCallback() then this routine ** is a no-op returning WRC_Continue. */ SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){ int rc; if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){ return WRC_Continue; } rc = WRC_Continue; pWalker->walkerDepth++; while( p ){ if( pWalker->xSelectCallback ){ rc = pWalker->xSelectCallback(pWalker, p); if( rc ) break; } if( sqlite3WalkSelectExpr(pWalker, p) || sqlite3WalkSelectFrom(pWalker, p) ){ pWalker->walkerDepth--; return WRC_Abort; } if( pWalker->xSelectCallback2 ){ pWalker->xSelectCallback2(pWalker, p); } p = p->pPrior; } pWalker->walkerDepth--; return rc & WRC_Abort; } /************** End of walker.c **********************************************/ /************** Begin file resolve.c *****************************************/ /* ** 2008 August 18 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains routines used for walking the parser tree and ** resolve all identifiers by associating them with a particular ** table and column. */ /* #include "sqliteInt.h" */ /* ** Walk the expression tree pExpr and increase the aggregate function ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node. ** This needs to occur when copying a TK_AGG_FUNCTION node from an ** outer query into an inner subquery. ** ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..) ** is a helper function - a callback for the tree walker. */ static int incrAggDepth(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n; return WRC_Continue; } static void incrAggFunctionDepth(Expr *pExpr, int N){ if( N>0 ){ Walker w; memset(&w, 0, sizeof(w)); w.xExprCallback = incrAggDepth; w.u.n = N; sqlite3WalkExpr(&w, pExpr); } } /* ** Turn the pExpr expression into an alias for the iCol-th column of the ** result set in pEList. ** ** If the reference is followed by a COLLATE operator, then make sure ** the COLLATE operator is preserved. For example: ** ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase; ** ** Should be transformed into: ** ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase; ** ** The nSubquery parameter specifies how many levels of subquery the ** alias is removed from the original expression. The usual value is ** zero but it might be more if the alias is contained within a subquery ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION ** structures must be increased by the nSubquery amount. */ static void resolveAlias( Parse *pParse, /* Parsing context */ ExprList *pEList, /* A result set */ int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ Expr *pExpr, /* Transform this into an alias to the result set */ const char *zType, /* "GROUP" or "ORDER" or "" */ int nSubquery /* Number of subqueries that the label is moving */ ){ Expr *pOrig; /* The iCol-th column of the result set */ Expr *pDup; /* Copy of pOrig */ sqlite3 *db; /* The database connection */ assert( iCol>=0 && iCol<pEList->nExpr ); pOrig = pEList->a[iCol].pExpr; assert( pOrig!=0 ); db = pParse->db; pDup = sqlite3ExprDup(db, pOrig, 0); if( pDup==0 ) return; if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery); if( pExpr->op==TK_COLLATE ){ pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); } ExprSetProperty(pDup, EP_Alias); /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This ** prevents ExprDelete() from deleting the Expr structure itself, ** allowing it to be repopulated by the memcpy() on the following line. ** The pExpr->u.zToken might point into memory that will be freed by the ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to ** make a copy of the token before doing the sqlite3DbFree(). */ ExprSetProperty(pExpr, EP_Static); sqlite3ExprDelete(db, pExpr); memcpy(pExpr, pDup, sizeof(*pExpr)); if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); pExpr->flags |= EP_MemToken; } sqlite3DbFree(db, pDup); } /* ** Return TRUE if the name zCol occurs anywhere in the USING clause. ** ** Return FALSE if the USING clause is NULL or if it does not contain ** zCol. */ static int nameInUsingClause(IdList *pUsing, const char *zCol){ if( pUsing ){ int k; for(k=0; k<pUsing->nId; k++){ if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; } } return 0; } /* ** Subqueries stores the original database, table and column names for their ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN". ** Check to see if the zSpan given to this routine matches the zDb, zTab, ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will ** match anything. */ SQLITE_PRIVATE int sqlite3MatchSpanName( const char *zSpan, const char *zCol, const char *zTab, const char *zDb ){ int n; for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ return 0; } zSpan += n+1; for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ return 0; } zSpan += n+1; if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){ return 0; } return 1; } /* ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up ** that name in the set of source tables in pSrcList and make the pExpr ** expression node refer back to that source column. The following changes ** are made to pExpr: ** ** pExpr->iDb Set the index in db->aDb[] of the database X ** (even if X is implied). ** pExpr->iTable Set to the cursor number for the table obtained ** from pSrcList. ** pExpr->pTab Points to the Table structure of X.Y (even if ** X and/or Y are implied.) ** pExpr->iColumn Set to the column number within the table. ** pExpr->op Set to TK_COLUMN. ** pExpr->pLeft Any expression this points to is deleted ** pExpr->pRight Any expression this points to is deleted. ** ** The zDb variable is the name of the database (the "X"). This value may be ** NULL meaning that name is of the form Y.Z or Z. Any available database ** can be used. The zTable variable is the name of the table (the "Y"). This ** value can be NULL if zDb is also NULL. If zTable is NULL it ** means that the form of the name is Z and that columns from any table ** can be used. ** ** If the name cannot be resolved unambiguously, leave an error message ** in pParse and return WRC_Abort. Return WRC_Prune on success. */ static int lookupName( Parse *pParse, /* The parsing context */ const char *zDb, /* Name of the database containing table, or NULL */ const char *zTab, /* Name of table containing column, or NULL */ const char *zCol, /* Name of the column. */ NameContext *pNC, /* The name context used to resolve the name */ Expr *pExpr /* Make this EXPR node point to the selected column */ ){ int i, j; /* Loop counters */ int cnt = 0; /* Number of matching column names */ int cntTab = 0; /* Number of matching table names */ int nSubquery = 0; /* How many levels of subquery */ sqlite3 *db = pParse->db; /* The database connection */ struct SrcList_item *pItem; /* Use for looping over pSrcList items */ struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ NameContext *pTopNC = pNC; /* First namecontext in the list */ Schema *pSchema = 0; /* Schema of the expression */ int isTrigger = 0; /* True if resolved to a trigger column */ Table *pTab = 0; /* Table hold the row */ Column *pCol; /* A column of pTab */ assert( pNC ); /* the name context cannot be NULL. */ assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); /* Initialize the node to no-match */ pExpr->iTable = -1; pExpr->pTab = 0; ExprSetVVAProperty(pExpr, EP_NoReduce); /* Translate the schema name in zDb into a pointer to the corresponding ** schema. If not found, pSchema will remain NULL and nothing will match ** resulting in an appropriate error message toward the end of this routine */ if( zDb ){ testcase( pNC->ncFlags & NC_PartIdx ); testcase( pNC->ncFlags & NC_IsCheck ); if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ /* Silently ignore database qualifiers inside CHECK constraints and ** partial indices. Do not raise errors because that might break ** legacy and because it does not hurt anything to just ignore the ** database name. */ zDb = 0; }else{ for(i=0; i<db->nDb; i++){ assert( db->aDb[i].zDbSName ); if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ pSchema = db->aDb[i].pSchema; break; } } } } /* Start at the inner-most context and move outward until a match is found */ while( pNC && cnt==0 ){ ExprList *pEList; SrcList *pSrcList = pNC->pSrcList; if( pSrcList ){ for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ pTab = pItem->pTab; assert( pTab!=0 && pTab->zName!=0 ); assert( pTab->nCol>0 ); if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ int hit = 0; pEList = pItem->pSelect->pEList; for(j=0; j<pEList->nExpr; j++){ if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ cnt++; cntTab = 2; pMatch = pItem; pExpr->iColumn = j; hit = 1; } } if( hit || zTab==0 ) continue; } if( zDb && pTab->pSchema!=pSchema ){ continue; } if( zTab ){ const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; assert( zTabName!=0 ); if( sqlite3StrICmp(zTabName, zTab)!=0 ){ continue; } } if( 0==(cntTab++) ){ pMatch = pItem; } for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ /* If there has been exactly one prior match and this match ** is for the right-hand table of a NATURAL JOIN or is in a ** USING clause, then skip this match. */ if( cnt==1 ){ if( pItem->fg.jointype & JT_NATURAL ) continue; if( nameInUsingClause(pItem->pUsing, zCol) ) continue; } cnt++; pMatch = pItem; /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; break; } } } if( pMatch ){ pExpr->iTable = pMatch->iCursor; pExpr->pTab = pMatch->pTab; /* RIGHT JOIN not (yet) supported */ assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ ExprSetProperty(pExpr, EP_CanBeNull); } pSchema = pExpr->pTab->pSchema; } } /* if( pSrcList ) */ #ifndef SQLITE_OMIT_TRIGGER /* If we have not already resolved the name, then maybe ** it is a new.* or old.* trigger argument reference */ if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){ int op = pParse->eTriggerOp; assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ pExpr->iTable = 1; pTab = pParse->pTriggerTab; }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ pExpr->iTable = 0; pTab = pParse->pTriggerTab; }else{ pTab = 0; } if( pTab ){ int iCol; pSchema = pTab->pSchema; cntTab++; for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ if( iCol==pTab->iPKey ){ iCol = -1; } break; } } if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ /* IMP: R-51414-32910 */ iCol = -1; } if( iCol<pTab->nCol ){ cnt++; if( iCol<0 ){ pExpr->affinity = SQLITE_AFF_INTEGER; }else if( pExpr->iTable==0 ){ testcase( iCol==31 ); testcase( iCol==32 ); pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); }else{ testcase( iCol==31 ); testcase( iCol==32 ); pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); } pExpr->iColumn = (i16)iCol; pExpr->pTab = pTab; isTrigger = 1; } } } #endif /* !defined(SQLITE_OMIT_TRIGGER) */ /* ** Perhaps the name is a reference to the ROWID */ if( cnt==0 && cntTab==1 && pMatch && (pNC->ncFlags & NC_IdxExpr)==0 && sqlite3IsRowid(zCol) && VisibleRowid(pMatch->pTab) ){ cnt = 1; pExpr->iColumn = -1; pExpr->affinity = SQLITE_AFF_INTEGER; } /* ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z ** might refer to an result-set alias. This happens, for example, when ** we are resolving names in the WHERE clause of the following command: ** ** SELECT a+b AS x FROM table WHERE x<10; ** ** In cases like this, replace pExpr with a copy of the expression that ** forms the result set entry ("a+b" in the example) and return immediately. ** Note that the expression in the result set should have already been ** resolved by the time the WHERE clause is resolved. ** ** The ability to use an output result-set column in the WHERE, GROUP BY, ** or HAVING clauses, or as part of a larger expression in the ORDER BY ** clause is not standard SQL. This is a (goofy) SQLite extension, that ** is supported for backwards compatibility only. Hence, we issue a warning ** on sqlite3_log() whenever the capability is used. */ if( (pEList = pNC->pEList)!=0 && zTab==0 && cnt==0 ){ for(j=0; j<pEList->nExpr; j++){ char *zAs = pEList->a[j].zName; if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ Expr *pOrig; assert( pExpr->pLeft==0 && pExpr->pRight==0 ); assert( pExpr->x.pList==0 ); assert( pExpr->x.pSelect==0 ); pOrig = pEList->a[j].pExpr; if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); return WRC_Abort; } if( sqlite3ExprVectorSize(pOrig)!=1 ){ sqlite3ErrorMsg(pParse, "row value misused"); return WRC_Abort; } resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); cnt = 1; pMatch = 0; assert( zTab==0 && zDb==0 ); goto lookupname_end; } } } /* Advance to the next name context. The loop will exit when either ** we have a match (cnt>0) or when we run out of name contexts. */ if( cnt==0 ){ pNC = pNC->pNext; nSubquery++; } } /* ** If X and Y are NULL (in other words if only the column name Z is ** supplied) and the value of Z is enclosed in double-quotes, then ** Z is a string literal if it doesn't match any column names. In that ** case, we need to return right away and not make any changes to ** pExpr. ** ** Because no reference was made to outer contexts, the pNC->nRef ** fields are not changed in any context. */ if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){ pExpr->op = TK_STRING; pExpr->pTab = 0; return WRC_Prune; } /* ** cnt==0 means there was not match. cnt>1 means there were two or ** more matches. Either way, we have an error. */ if( cnt!=1 ){ const char *zErr; zErr = cnt==0 ? "no such column" : "ambiguous column name"; if( zDb ){ sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); }else if( zTab ){ sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); }else{ sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); } pParse->checkSchema = 1; pTopNC->nErr++; } /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the ** column number is greater than the number of bits in the bitmask ** then set the high-order bit of the bitmask. */ if( pExpr->iColumn>=0 && pMatch!=0 ){ int n = pExpr->iColumn; testcase( n==BMS-1 ); if( n>=BMS ){ n = BMS-1; } assert( pMatch->iCursor==pExpr->iTable ); pMatch->colUsed |= ((Bitmask)1)<<n; } /* Clean up and return */ sqlite3ExprDelete(db, pExpr->pLeft); pExpr->pLeft = 0; sqlite3ExprDelete(db, pExpr->pRight); pExpr->pRight = 0; pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN); lookupname_end: if( cnt==1 ){ assert( pNC!=0 ); if( !ExprHasProperty(pExpr, EP_Alias) ){ sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); } /* Increment the nRef value on all name contexts from TopNC up to ** the point where the name matched. */ for(;;){ assert( pTopNC!=0 ); pTopNC->nRef++; if( pTopNC==pNC ) break; pTopNC = pTopNC->pNext; } return WRC_Prune; } else { return WRC_Abort; } } /* ** Allocate and return a pointer to an expression to load the column iCol ** from datasource iSrc in SrcList pSrc. */ SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); if( p ){ struct SrcList_item *pItem = &pSrc->a[iSrc]; p->pTab = pItem->pTab; p->iTable = pItem->iCursor; if( p->pTab->iPKey==iCol ){ p->iColumn = -1; }else{ p->iColumn = (ynVar)iCol; testcase( iCol==BMS ); testcase( iCol==BMS-1 ); pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); } ExprSetProperty(p, EP_Resolved); } return p; } /* ** Report an error that an expression is not valid for some set of ** pNC->ncFlags values determined by validMask. */ static void notValid( Parse *pParse, /* Leave error message here */ NameContext *pNC, /* The name context */ const char *zMsg, /* Type of error */ int validMask /* Set of contexts for which prohibited */ ){ assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 ); if( (pNC->ncFlags & validMask)!=0 ){ const char *zIn = "partial index WHERE clauses"; if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions"; #ifndef SQLITE_OMIT_CHECK else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints"; #endif sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); } } /* ** Expression p should encode a floating point value between 1.0 and 0.0. ** Return 1024 times this value. Or return -1 if p is not a floating point ** value between 1.0 and 0.0. */ static int exprProbability(Expr *p){ double r = -1.0; if( p->op!=TK_FLOAT ) return -1; sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); assert( r>=0.0 ); if( r>1.0 ) return -1; return (int)(r*134217728.0); } /* ** This routine is callback for sqlite3WalkExpr(). ** ** Resolve symbolic names into TK_COLUMN operators for the current ** node in the expression tree. Return 0 to continue the search down ** the tree or 2 to abort the tree walk. ** ** This routine also does error checking and name resolution for ** function names. The operator for aggregate functions is changed ** to TK_AGG_FUNCTION. */ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ NameContext *pNC; Parse *pParse; pNC = pWalker->u.pNC; assert( pNC!=0 ); pParse = pNC->pParse; assert( pParse==pWalker->pParse ); if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune; ExprSetProperty(pExpr, EP_Resolved); #ifndef NDEBUG if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ SrcList *pSrcList = pNC->pSrcList; int i; for(i=0; i<pNC->pSrcList->nSrc; i++){ assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab); } } #endif switch( pExpr->op ){ #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) /* The special operator TK_ROW means use the rowid for the first ** column in the FROM clause. This is used by the LIMIT and ORDER BY ** clause processing on UPDATE and DELETE statements. */ case TK_ROW: { SrcList *pSrcList = pNC->pSrcList; struct SrcList_item *pItem; assert( pSrcList && pSrcList->nSrc==1 ); pItem = pSrcList->a; pExpr->op = TK_COLUMN; pExpr->pTab = pItem->pTab; pExpr->iTable = pItem->iCursor; pExpr->iColumn = -1; pExpr->affinity = SQLITE_AFF_INTEGER; break; } #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ /* A lone identifier is the name of a column. */ case TK_ID: { return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr); } /* A table name and column name: ID.ID ** Or a database, table and column: ID.ID.ID */ case TK_DOT: { const char *zColumn; const char *zTable; const char *zDb; Expr *pRight; /* if( pSrcList==0 ) break; */ notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr); pRight = pExpr->pRight; if( pRight->op==TK_ID ){ zDb = 0; zTable = pExpr->pLeft->u.zToken; zColumn = pRight->u.zToken; }else{ assert( pRight->op==TK_DOT ); zDb = pExpr->pLeft->u.zToken; zTable = pRight->pLeft->u.zToken; zColumn = pRight->pRight->u.zToken; } return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); } /* Resolve function names */ case TK_FUNCTION: { ExprList *pList = pExpr->x.pList; /* The argument list */ int n = pList ? pList->nExpr : 0; /* Number of arguments */ int no_such_func = 0; /* True if no such function exists */ int wrong_num_args = 0; /* True if wrong number of arguments */ int is_agg = 0; /* True if is an aggregate function */ int nId; /* Number of characters in function name */ const char *zId; /* The function name. */ FuncDef *pDef; /* Information about the function */ u8 enc = ENC(pParse->db); /* The database encoding */ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); zId = pExpr->u.zToken; nId = sqlite3Strlen30(zId); pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0); if( pDef==0 ){ pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0); if( pDef==0 ){ no_such_func = 1; }else{ wrong_num_args = 1; } }else{ is_agg = pDef->xFinalize!=0; if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ ExprSetProperty(pExpr, EP_Unlikely|EP_Skip); if( n==2 ){ pExpr->iTable = exprProbability(pList->a[1].pExpr); if( pExpr->iTable<0 ){ sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a " "constant between 0.0 and 1.0"); pNC->nErr++; } }else{ /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is ** equivalent to likelihood(X, 0.0625). ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is ** short-hand for likelihood(X,0.0625). ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand ** for likelihood(X,0.9375). ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent ** to likelihood(X,0.9375). */ /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */ pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120; } } #ifndef SQLITE_OMIT_AUTHORIZATION { int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); if( auth!=SQLITE_OK ){ if( auth==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized to use function: %s", pDef->zName); pNC->nErr++; } pExpr->op = TK_NULL; return WRC_Prune; } } #endif if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ /* For the purposes of the EP_ConstFunc flag, date and time ** functions and other functions that change slowly are considered ** constant because they are constant for the duration of one query */ ExprSetProperty(pExpr,EP_ConstFunc); } if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ /* Date/time functions that use 'now', and other functions like ** sqlite_version() that might change over time cannot be used ** in an index. */ notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr|NC_PartIdx); } } if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){ sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId); pNC->nErr++; is_agg = 0; }else if( no_such_func && pParse->db->init.busy==0 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION && pParse->explain==0 #endif ){ sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); pNC->nErr++; }else if( wrong_num_args ){ sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", nId, zId); pNC->nErr++; } if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg; sqlite3WalkExprList(pWalker, pList); if( is_agg ){ NameContext *pNC2 = pNC; pExpr->op = TK_AGG_FUNCTION; pExpr->op2 = 0; while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ pExpr->op2++; pNC2 = pNC2->pNext; } assert( pDef!=0 ); if( pNC2 ){ assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); } pNC->ncFlags |= NC_AllowAgg; } /* FIX ME: Compute pExpr->affinity based on the expected return ** type of the function */ return WRC_Prune; } #ifndef SQLITE_OMIT_SUBQUERY case TK_SELECT: case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); #endif case TK_IN: { testcase( pExpr->op==TK_IN ); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ int nRef = pNC->nRef; notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr); sqlite3WalkSelect(pWalker, pExpr->x.pSelect); assert( pNC->nRef>=nRef ); if( nRef!=pNC->nRef ){ ExprSetProperty(pExpr, EP_VarSelect); pNC->ncFlags |= NC_VarSelect; } } break; } case TK_VARIABLE: { notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr); break; } case TK_BETWEEN: case TK_EQ: case TK_NE: case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_IS: case TK_ISNOT: { int nLeft, nRight; if( pParse->db->mallocFailed ) break; assert( pExpr->pLeft!=0 ); nLeft = sqlite3ExprVectorSize(pExpr->pLeft); if( pExpr->op==TK_BETWEEN ){ nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr); if( nRight==nLeft ){ nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr); } }else{ assert( pExpr->pRight!=0 ); nRight = sqlite3ExprVectorSize(pExpr->pRight); } if( nLeft!=nRight ){ testcase( pExpr->op==TK_EQ ); testcase( pExpr->op==TK_NE ); testcase( pExpr->op==TK_LT ); testcase( pExpr->op==TK_LE ); testcase( pExpr->op==TK_GT ); testcase( pExpr->op==TK_GE ); testcase( pExpr->op==TK_IS ); testcase( pExpr->op==TK_ISNOT ); testcase( pExpr->op==TK_BETWEEN ); sqlite3ErrorMsg(pParse, "row value misused"); } break; } } return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; } /* ** pEList is a list of expressions which are really the result set of the ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. ** This routine checks to see if pE is a simple identifier which corresponds ** to the AS-name of one of the terms of the expression list. If it is, ** this routine return an integer between 1 and N where N is the number of ** elements in pEList, corresponding to the matching entry. If there is ** no match, or if pE is not a simple identifier, then this routine ** return 0. ** ** pEList has been resolved. pE has not. */ static int resolveAsName( Parse *pParse, /* Parsing context for error messages */ ExprList *pEList, /* List of expressions to scan */ Expr *pE /* Expression we are trying to match */ ){ int i; /* Loop counter */ UNUSED_PARAMETER(pParse); if( pE->op==TK_ID ){ char *zCol = pE->u.zToken; for(i=0; i<pEList->nExpr; i++){ char *zAs = pEList->a[i].zName; if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ return i+1; } } } return 0; } /* ** pE is a pointer to an expression which is a single term in the ** ORDER BY of a compound SELECT. The expression has not been ** name resolved. ** ** At the point this routine is called, we already know that the ** ORDER BY term is not an integer index into the result set. That ** case is handled by the calling routine. ** ** Attempt to match pE against result set columns in the left-most ** SELECT statement. Return the index i of the matching column, ** as an indication to the caller that it should sort by the i-th column. ** The left-most column is 1. In other words, the value returned is the ** same integer value that would be used in the SQL statement to indicate ** the column. ** ** If there is no match, return 0. Return -1 if an error occurs. */ static int resolveOrderByTermToExprList( Parse *pParse, /* Parsing context for error messages */ Select *pSelect, /* The SELECT statement with the ORDER BY clause */ Expr *pE /* The specific ORDER BY term */ ){ int i; /* Loop counter */ ExprList *pEList; /* The columns of the result set */ NameContext nc; /* Name context for resolving pE */ sqlite3 *db; /* Database connection */ int rc; /* Return code from subprocedures */ u8 savedSuppErr; /* Saved value of db->suppressErr */ assert( sqlite3ExprIsInteger(pE, &i)==0 ); pEList = pSelect->pEList; /* Resolve all names in the ORDER BY term expression */ memset(&nc, 0, sizeof(nc)); nc.pParse = pParse; nc.pSrcList = pSelect->pSrc; nc.pEList = pEList; nc.ncFlags = NC_AllowAgg; nc.nErr = 0; db = pParse->db; savedSuppErr = db->suppressErr; db->suppressErr = 1; rc = sqlite3ResolveExprNames(&nc, pE); db->suppressErr = savedSuppErr; if( rc ) return 0; /* Try to match the ORDER BY expression against an expression ** in the result set. Return an 1-based index of the matching ** result-set entry. */ for(i=0; i<pEList->nExpr; i++){ if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){ return i+1; } } /* If no match, return 0. */ return 0; } /* ** Generate an ORDER BY or GROUP BY term out-of-range error. */ static void resolveOutOfRangeError( Parse *pParse, /* The error context into which to write the error */ const char *zType, /* "ORDER" or "GROUP" */ int i, /* The index (1-based) of the term out of range */ int mx /* Largest permissible value of i */ ){ sqlite3ErrorMsg(pParse, "%r %s BY term out of range - should be " "between 1 and %d", i, zType, mx); } /* ** Analyze the ORDER BY clause in a compound SELECT statement. Modify ** each term of the ORDER BY clause is a constant integer between 1 ** and N where N is the number of columns in the compound SELECT. ** ** ORDER BY terms that are already an integer between 1 and N are ** unmodified. ORDER BY terms that are integers outside the range of ** 1 through N generate an error. ORDER BY terms that are expressions ** are matched against result set expressions of compound SELECT ** beginning with the left-most SELECT and working toward the right. ** At the first match, the ORDER BY expression is transformed into ** the integer column number. ** ** Return the number of errors seen. */ static int resolveCompoundOrderBy( Parse *pParse, /* Parsing context. Leave error messages here */ Select *pSelect /* The SELECT statement containing the ORDER BY */ ){ int i; ExprList *pOrderBy; ExprList *pEList; sqlite3 *db; int moreToDo = 1; pOrderBy = pSelect->pOrderBy; if( pOrderBy==0 ) return 0; db = pParse->db; #if SQLITE_MAX_COLUMN if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); return 1; } #endif for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } pSelect->pNext = 0; while( pSelect->pPrior ){ pSelect->pPrior->pNext = pSelect; pSelect = pSelect->pPrior; } while( pSelect && moreToDo ){ struct ExprList_item *pItem; moreToDo = 0; pEList = pSelect->pEList; assert( pEList!=0 ); for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ int iCol = -1; Expr *pE, *pDup; if( pItem->done ) continue; pE = sqlite3ExprSkipCollate(pItem->pExpr); if( sqlite3ExprIsInteger(pE, &iCol) ){ if( iCol<=0 || iCol>pEList->nExpr ){ resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); return 1; } }else{ iCol = resolveAsName(pParse, pEList, pE); if( iCol==0 ){ pDup = sqlite3ExprDup(db, pE, 0); if( !db->mallocFailed ){ assert(pDup); iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); } sqlite3ExprDelete(db, pDup); } } if( iCol>0 ){ /* Convert the ORDER BY term into an integer column number iCol, ** taking care to preserve the COLLATE clause if it exists */ Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); if( pNew==0 ) return 1; pNew->flags |= EP_IntValue; pNew->u.iValue = iCol; if( pItem->pExpr==pE ){ pItem->pExpr = pNew; }else{ Expr *pParent = pItem->pExpr; assert( pParent->op==TK_COLLATE ); while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft; assert( pParent->pLeft==pE ); pParent->pLeft = pNew; } sqlite3ExprDelete(db, pE); pItem->u.x.iOrderByCol = (u16)iCol; pItem->done = 1; }else{ moreToDo = 1; } } pSelect = pSelect->pNext; } for(i=0; i<pOrderBy->nExpr; i++){ if( pOrderBy->a[i].done==0 ){ sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " "column in the result set", i+1); return 1; } } return 0; } /* ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of ** the SELECT statement pSelect. If any term is reference to a ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol ** field) then convert that term into a copy of the corresponding result set ** column. ** ** If any errors are detected, add an error message to pParse and ** return non-zero. Return zero if no errors are seen. */ SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy( Parse *pParse, /* Parsing context. Leave error messages here */ Select *pSelect, /* The SELECT statement containing the clause */ ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ const char *zType /* "ORDER" or "GROUP" */ ){ int i; sqlite3 *db = pParse->db; ExprList *pEList; struct ExprList_item *pItem; if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; #if SQLITE_MAX_COLUMN if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); return 1; } #endif pEList = pSelect->pEList; assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ if( pItem->u.x.iOrderByCol ){ if( pItem->u.x.iOrderByCol>pEList->nExpr ){ resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr); return 1; } resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0); } } return 0; } /* ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. ** The Name context of the SELECT statement is pNC. zType is either ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. ** ** This routine resolves each term of the clause into an expression. ** If the order-by term is an integer I between 1 and N (where N is the ** number of columns in the result set of the SELECT) then the expression ** in the resolution is a copy of the I-th result-set expression. If ** the order-by term is an identifier that corresponds to the AS-name of ** a result-set expression, then the term resolves to a copy of the ** result-set expression. Otherwise, the expression is resolved in ** the usual way - using sqlite3ResolveExprNames(). ** ** This routine returns the number of errors. If errors occur, then ** an appropriate error message might be left in pParse. (OOM errors ** excepted.) */ static int resolveOrderGroupBy( NameContext *pNC, /* The name context of the SELECT statement */ Select *pSelect, /* The SELECT statement holding pOrderBy */ ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ const char *zType /* Either "ORDER" or "GROUP", as appropriate */ ){ int i, j; /* Loop counters */ int iCol; /* Column number */ struct ExprList_item *pItem; /* A term of the ORDER BY clause */ Parse *pParse; /* Parsing context */ int nResult; /* Number of terms in the result set */ if( pOrderBy==0 ) return 0; nResult = pSelect->pEList->nExpr; pParse = pNC->pParse; for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ Expr *pE = pItem->pExpr; Expr *pE2 = sqlite3ExprSkipCollate(pE); if( zType[0]!='G' ){ iCol = resolveAsName(pParse, pSelect->pEList, pE2); if( iCol>0 ){ /* If an AS-name match is found, mark this ORDER BY column as being ** a copy of the iCol-th result-set column. The subsequent call to ** sqlite3ResolveOrderGroupBy() will convert the expression to a ** copy of the iCol-th result-set expression. */ pItem->u.x.iOrderByCol = (u16)iCol; continue; } } if( sqlite3ExprIsInteger(pE2, &iCol) ){ /* The ORDER BY term is an integer constant. Again, set the column ** number so that sqlite3ResolveOrderGroupBy() will convert the ** order-by term to a copy of the result-set expression */ if( iCol<1 || iCol>0xffff ){ resolveOutOfRangeError(pParse, zType, i+1, nResult); return 1; } pItem->u.x.iOrderByCol = (u16)iCol; continue; } /* Otherwise, treat the ORDER BY term as an ordinary expression */ pItem->u.x.iOrderByCol = 0; if( sqlite3ResolveExprNames(pNC, pE) ){ return 1; } for(j=0; j<pSelect->pEList->nExpr; j++){ if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ pItem->u.x.iOrderByCol = j+1; } } } return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); } /* ** Resolve names in the SELECT statement p and all of its descendants. */ static int resolveSelectStep(Walker *pWalker, Select *p){ NameContext *pOuterNC; /* Context that contains this SELECT */ NameContext sNC; /* Name context of this SELECT */ int isCompound; /* True if p is a compound select */ int nCompound; /* Number of compound terms processed so far */ Parse *pParse; /* Parsing context */ int i; /* Loop counter */ ExprList *pGroupBy; /* The GROUP BY clause */ Select *pLeftmost; /* Left-most of SELECT of a compound */ sqlite3 *db; /* Database connection */ assert( p!=0 ); if( p->selFlags & SF_Resolved ){ return WRC_Prune; } pOuterNC = pWalker->u.pNC; pParse = pWalker->pParse; db = pParse->db; /* Normally sqlite3SelectExpand() will be called first and will have ** already expanded this SELECT. However, if this is a subquery within ** an expression, sqlite3ResolveExprNames() will be called without a ** prior call to sqlite3SelectExpand(). When that happens, let ** sqlite3SelectPrep() do all of the processing for this SELECT. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and ** this routine in the correct order. */ if( (p->selFlags & SF_Expanded)==0 ){ sqlite3SelectPrep(pParse, p, pOuterNC); return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; } isCompound = p->pPrior!=0; nCompound = 0; pLeftmost = p; while( p ){ assert( (p->selFlags & SF_Expanded)!=0 ); assert( (p->selFlags & SF_Resolved)==0 ); p->selFlags |= SF_Resolved; /* Resolve the expressions in the LIMIT and OFFSET clauses. These ** are not allowed to refer to any names, so pass an empty NameContext. */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; if( sqlite3ResolveExprNames(&sNC, p->pLimit) || sqlite3ResolveExprNames(&sNC, p->pOffset) ){ return WRC_Abort; } /* If the SF_Converted flags is set, then this Select object was ** was created by the convertCompoundSelectToSubquery() function. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved ** as if it were part of the sub-query, not the parent. This block ** moves the pOrderBy down to the sub-query. It will be moved back ** after the names have been resolved. */ if( p->selFlags & SF_Converted ){ Select *pSub = p->pSrc->a[0].pSelect; assert( p->pSrc->nSrc==1 && p->pOrderBy ); assert( pSub->pPrior && pSub->pOrderBy==0 ); pSub->pOrderBy = p->pOrderBy; p->pOrderBy = 0; } /* Recursively resolve names in all subqueries */ for(i=0; i<p->pSrc->nSrc; i++){ struct SrcList_item *pItem = &p->pSrc->a[i]; if( pItem->pSelect ){ NameContext *pNC; /* Used to iterate name contexts */ int nRef = 0; /* Refcount for pOuterNC and outer contexts */ const char *zSavedContext = pParse->zAuthContext; /* Count the total number of references to pOuterNC and all of its ** parent contexts. After resolving references to expressions in ** pItem->pSelect, check if this value has changed. If so, then ** SELECT statement pItem->pSelect must be correlated. Set the ** pItem->fg.isCorrelated flag if this is the case. */ for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef; if( pItem->zName ) pParse->zAuthContext = pItem->zName; sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); pParse->zAuthContext = zSavedContext; if( pParse->nErr || db->mallocFailed ) return WRC_Abort; for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef; assert( pItem->fg.isCorrelated==0 && nRef<=0 ); pItem->fg.isCorrelated = (nRef!=0); } } /* Set up the local name-context to pass to sqlite3ResolveExprNames() to ** resolve the result-set expression list. */ sNC.ncFlags = NC_AllowAgg; sNC.pSrcList = p->pSrc; sNC.pNext = pOuterNC; /* Resolve names in the result set. */ if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; /* If there are no aggregate functions in the result-set, and no GROUP BY ** expression, do not allow aggregates in any of the other expressions. */ assert( (p->selFlags & SF_Aggregate)==0 ); pGroupBy = p->pGroupBy; if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){ assert( NC_MinMaxAgg==SF_MinMaxAgg ); p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg); }else{ sNC.ncFlags &= ~NC_AllowAgg; } /* If a HAVING clause is present, then there must be a GROUP BY clause. */ if( p->pHaving && !pGroupBy ){ sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); return WRC_Abort; } /* Add the output column list to the name-context before parsing the ** other expressions in the SELECT statement. This is so that ** expressions in the WHERE clause (etc.) can refer to expressions by ** aliases in the result set. ** ** Minor point: If this is the case, then the expression will be ** re-evaluated for each reference to it. */ sNC.pEList = p->pEList; if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; /* Resolve names in table-valued-function arguments */ for(i=0; i<p->pSrc->nSrc; i++){ struct SrcList_item *pItem = &p->pSrc->a[i]; if( pItem->fg.isTabFunc && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) ){ return WRC_Abort; } } /* The ORDER BY and GROUP BY clauses may not refer to terms in ** outer queries */ sNC.pNext = 0; sNC.ncFlags |= NC_AllowAgg; /* If this is a converted compound query, move the ORDER BY clause from ** the sub-query back to the parent query. At this point each term ** within the ORDER BY clause has been transformed to an integer value. ** These integers will be replaced by copies of the corresponding result ** set expressions by the call to resolveOrderGroupBy() below. */ if( p->selFlags & SF_Converted ){ Select *pSub = p->pSrc->a[0].pSelect; p->pOrderBy = pSub->pOrderBy; pSub->pOrderBy = 0; } /* Process the ORDER BY clause for singleton SELECT statements. ** The ORDER BY clause for compounds SELECT statements is handled ** below, after all of the result-sets for all of the elements of ** the compound have been resolved. ** ** If there is an ORDER BY clause on a term of a compound-select other ** than the right-most term, then that is a syntax error. But the error ** is not detected until much later, and so we need to go ahead and ** resolve those symbols on the incorrect ORDER BY for consistency. */ if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */ && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){ return WRC_Abort; } if( db->mallocFailed ){ return WRC_Abort; } /* Resolve the GROUP BY clause. At the same time, make sure ** the GROUP BY clause does not contain aggregate functions. */ if( pGroupBy ){ struct ExprList_item *pItem; if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ return WRC_Abort; } for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " "the GROUP BY clause"); return WRC_Abort; } } } /* If this is part of a compound SELECT, check that it has the right ** number of expressions in the select list. */ if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){ sqlite3SelectWrongNumTermsError(pParse, p->pNext); return WRC_Abort; } /* Advance to the next term of the compound */ p = p->pPrior; nCompound++; } /* Resolve the ORDER BY on a compound SELECT after all terms of ** the compound have been resolved. */ if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ return WRC_Abort; } return WRC_Prune; } /* ** This routine walks an expression tree and resolves references to ** table columns and result-set columns. At the same time, do error ** checking on function usage and set a flag if any aggregate functions ** are seen. ** ** To resolve table columns references we look for nodes (or subtrees) of the ** form X.Y.Z or Y.Z or just Z where ** ** X: The name of a database. Ex: "main" or "temp" or ** the symbolic name assigned to an ATTACH-ed database. ** ** Y: The name of a table in a FROM clause. Or in a trigger ** one of the special names "old" or "new". ** ** Z: The name of a column in table Y. ** ** The node at the root of the subtree is modified as follows: ** ** Expr.op Changed to TK_COLUMN ** Expr.pTab Points to the Table object for X.Y ** Expr.iColumn The column index in X.Y. -1 for the rowid. ** Expr.iTable The VDBE cursor number for X.Y ** ** ** To resolve result-set references, look for expression nodes of the ** form Z (with no X and Y prefix) where the Z matches the right-hand ** size of an AS clause in the result-set of a SELECT. The Z expression ** is replaced by a copy of the left-hand side of the result-set expression. ** Table-name and function resolution occurs on the substituted expression ** tree. For example, in: ** ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; ** ** The "x" term of the order by is replaced by "a+b" to render: ** ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; ** ** Function calls are checked to make sure that the function is ** defined and that the correct number of arguments are specified. ** If the function is an aggregate function, then the NC_HasAgg flag is ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. ** If an expression contains aggregate functions then the EP_Agg ** property on the expression is set. ** ** An error message is left in pParse if anything is amiss. The number ** if errors is returned. */ SQLITE_PRIVATE int sqlite3ResolveExprNames( NameContext *pNC, /* Namespace to resolve expressions in. */ Expr *pExpr /* The expression to be analyzed. */ ){ u16 savedHasAgg; Walker w; if( pExpr==0 ) return 0; #if SQLITE_MAX_EXPR_DEPTH>0 { Parse *pParse = pNC->pParse; if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){ return 1; } pParse->nHeight += pExpr->nHeight; } #endif savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg); pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg); w.pParse = pNC->pParse; w.xExprCallback = resolveExprStep; w.xSelectCallback = resolveSelectStep; w.xSelectCallback2 = 0; w.walkerDepth = 0; w.eCode = 0; w.u.pNC = pNC; sqlite3WalkExpr(&w, pExpr); #if SQLITE_MAX_EXPR_DEPTH>0 pNC->pParse->nHeight -= pExpr->nHeight; #endif if( pNC->nErr>0 || w.pParse->nErr>0 ){ ExprSetProperty(pExpr, EP_Error); } if( pNC->ncFlags & NC_HasAgg ){ ExprSetProperty(pExpr, EP_Agg); } pNC->ncFlags |= savedHasAgg; return ExprHasProperty(pExpr, EP_Error); } /* ** Resolve all names for all expression in an expression list. This is ** just like sqlite3ResolveExprNames() except that it works for an expression ** list rather than a single expression. */ SQLITE_PRIVATE int sqlite3ResolveExprListNames( NameContext *pNC, /* Namespace to resolve expressions in. */ ExprList *pList /* The expression list to be analyzed. */ ){ int i; if( pList ){ for(i=0; i<pList->nExpr; i++){ if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort; } } return WRC_Continue; } /* ** Resolve all names in all expressions of a SELECT and in all ** decendents of the SELECT, including compounds off of p->pPrior, ** subqueries in expressions, and subqueries used as FROM clause ** terms. ** ** See sqlite3ResolveExprNames() for a description of the kinds of ** transformations that occur. ** ** All SELECT statements should have been expanded using ** sqlite3SelectExpand() prior to invoking this routine. */ SQLITE_PRIVATE void sqlite3ResolveSelectNames( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ NameContext *pOuterNC /* Name context for parent SELECT statement */ ){ Walker w; assert( p!=0 ); memset(&w, 0, sizeof(w)); w.xExprCallback = resolveExprStep; w.xSelectCallback = resolveSelectStep; w.pParse = pParse; w.u.pNC = pOuterNC; sqlite3WalkSelect(&w, p); } /* ** Resolve names in expressions that can only reference a single table: ** ** * CHECK constraints ** * WHERE clauses on partial indices ** ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression ** is set to -1 and the Expr.iColumn value is set to the column number. ** ** Any errors cause an error message to be set in pParse. */ SQLITE_PRIVATE void sqlite3ResolveSelfReference( Parse *pParse, /* Parsing context */ Table *pTab, /* The table being referenced */ int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */ Expr *pExpr, /* Expression to resolve. May be NULL. */ ExprList *pList /* Expression list to resolve. May be NUL. */ ){ SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ NameContext sNC; /* Name context for pParse->pNewTable */ assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr ); memset(&sNC, 0, sizeof(sNC)); memset(&sSrc, 0, sizeof(sSrc)); sSrc.nSrc = 1; sSrc.a[0].zName = pTab->zName; sSrc.a[0].pTab = pTab; sSrc.a[0].iCursor = -1; sNC.pParse = pParse; sNC.pSrcList = &sSrc; sNC.ncFlags = type; if( sqlite3ResolveExprNames(&sNC, pExpr) ) return; if( pList ) sqlite3ResolveExprListNames(&sNC, pList); } /************** End of resolve.c *********************************************/ /************** Begin file expr.c ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used for analyzing expressions and ** for generating VDBE code that evaluates expressions in SQLite. */ /* #include "sqliteInt.h" */ /* Forward declarations */ static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int); static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree); /* ** Return the affinity character for a single column of a table. */ SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){ assert( iCol<pTab->nCol ); return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER; } /* ** Return the 'affinity' of the expression pExpr if any. ** ** If pExpr is a column, a reference to a column via an 'AS' alias, ** or a sub-select with a column as the return value, then the ** affinity of that column is returned. Otherwise, 0x00 is returned, ** indicating no affinity for the expression. ** ** i.e. the WHERE clause expressions in the following statements all ** have an affinity: ** ** CREATE TABLE t1(a); ** SELECT * FROM t1 WHERE a; ** SELECT a AS b FROM t1 WHERE b; ** SELECT * FROM t1 WHERE (select a from t1); */ SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){ int op; pExpr = sqlite3ExprSkipCollate(pExpr); if( pExpr->flags & EP_Generic ) return 0; op = pExpr->op; if( op==TK_SELECT ){ assert( pExpr->flags&EP_xIsSelect ); return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); } if( op==TK_REGISTER ) op = pExpr->op2; #ifndef SQLITE_OMIT_CAST if( op==TK_CAST ){ assert( !ExprHasProperty(pExpr, EP_IntValue) ); return sqlite3AffinityType(pExpr->u.zToken, 0); } #endif if( op==TK_AGG_COLUMN || op==TK_COLUMN ){ return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn); } if( op==TK_SELECT_COLUMN ){ assert( pExpr->pLeft->flags&EP_xIsSelect ); return sqlite3ExprAffinity( pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr ); } return pExpr->affinity; } /* ** Set the collating sequence for expression pExpr to be the collating ** sequence named by pToken. Return a pointer to a new Expr node that ** implements the COLLATE operator. ** ** If a memory allocation error occurs, that fact is recorded in pParse->db ** and the pExpr parameter is returned unchanged. */ SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken( Parse *pParse, /* Parsing context */ Expr *pExpr, /* Add the "COLLATE" clause to this expression */ const Token *pCollName, /* Name of collating sequence */ int dequote /* True to dequote pCollName */ ){ if( pCollName->n>0 ){ Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); if( pNew ){ pNew->pLeft = pExpr; pNew->flags |= EP_Collate|EP_Skip; pExpr = pNew; } } return pExpr; } SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ Token s; assert( zC!=0 ); sqlite3TokenInit(&s, (char*)zC); return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); } /* ** Skip over any TK_COLLATE operators and any unlikely() ** or likelihood() function at the root of an expression. */ SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){ while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ if( ExprHasProperty(pExpr, EP_Unlikely) ){ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); assert( pExpr->x.pList->nExpr>0 ); assert( pExpr->op==TK_FUNCTION ); pExpr = pExpr->x.pList->a[0].pExpr; }else{ assert( pExpr->op==TK_COLLATE ); pExpr = pExpr->pLeft; } } return pExpr; } /* ** Return the collation sequence for the expression pExpr. If ** there is no defined collating sequence, return NULL. ** ** The collating sequence might be determined by a COLLATE operator ** or by the presence of a column with a defined collating sequence. ** COLLATE operators take first precedence. Left operands take ** precedence over right operands. */ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ sqlite3 *db = pParse->db; CollSeq *pColl = 0; Expr *p = pExpr; while( p ){ int op = p->op; if( p->flags & EP_Generic ) break; if( op==TK_CAST || op==TK_UPLUS ){ p = p->pLeft; continue; } if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){ pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); break; } if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER) && p->pTab!=0 ){ /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally ** a TK_COLUMN but was previously evaluated and cached in a register */ int j = p->iColumn; if( j>=0 ){ const char *zColl = p->pTab->aCol[j].zColl; pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); } break; } if( p->flags & EP_Collate ){ if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){ p = p->pLeft; }else{ Expr *pNext = p->pRight; /* The Expr.x union is never used at the same time as Expr.pRight */ assert( p->x.pList==0 || p->pRight==0 ); /* p->flags holds EP_Collate and p->pLeft->flags does not. And ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at ** least one EP_Collate. Thus the following two ALWAYS. */ if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){ int i; for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){ if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){ pNext = p->x.pList->a[i].pExpr; break; } } } p = pNext; } }else{ break; } } if( sqlite3CheckCollSeq(pParse, pColl) ){ pColl = 0; } return pColl; } /* ** pExpr is an operand of a comparison operator. aff2 is the ** type affinity of the other operand. This routine returns the ** type affinity that should be used for the comparison operator. */ SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){ char aff1 = sqlite3ExprAffinity(pExpr); if( aff1 && aff2 ){ /* Both sides of the comparison are columns. If one has numeric ** affinity, use that. Otherwise use no affinity. */ if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ return SQLITE_AFF_NUMERIC; }else{ return SQLITE_AFF_BLOB; } }else if( !aff1 && !aff2 ){ /* Neither side of the comparison is a column. Compare the ** results directly. */ return SQLITE_AFF_BLOB; }else{ /* One side is a column, the other is not. Use the columns affinity. */ assert( aff1==0 || aff2==0 ); return (aff1 + aff2); } } /* ** pExpr is a comparison operator. Return the type affinity that should ** be applied to both operands prior to doing the comparison. */ static char comparisonAffinity(Expr *pExpr){ char aff; assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); assert( pExpr->pLeft ); aff = sqlite3ExprAffinity(pExpr->pLeft); if( pExpr->pRight ){ aff = sqlite3CompareAffinity(pExpr->pRight, aff); }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); }else if( aff==0 ){ aff = SQLITE_AFF_BLOB; } return aff; } /* ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. ** idx_affinity is the affinity of an indexed column. Return true ** if the index with affinity idx_affinity may be used to implement ** the comparison in pExpr. */ SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ char aff = comparisonAffinity(pExpr); switch( aff ){ case SQLITE_AFF_BLOB: return 1; case SQLITE_AFF_TEXT: return idx_affinity==SQLITE_AFF_TEXT; default: return sqlite3IsNumericAffinity(idx_affinity); } } /* ** Return the P5 value that should be used for a binary comparison ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. */ static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ u8 aff = (char)sqlite3ExprAffinity(pExpr2); aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; return aff; } /* ** Return a pointer to the collation sequence that should be used by ** a binary comparison operator comparing pLeft and pRight. ** ** If the left hand expression has a collating sequence type, then it is ** used. Otherwise the collation sequence for the right hand expression ** is used, or the default (BINARY) if neither expression has a collating ** type. ** ** Argument pRight (but not pLeft) may be a null pointer. In this case, ** it is not considered. */ SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq( Parse *pParse, Expr *pLeft, Expr *pRight ){ CollSeq *pColl; assert( pLeft ); if( pLeft->flags & EP_Collate ){ pColl = sqlite3ExprCollSeq(pParse, pLeft); }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ pColl = sqlite3ExprCollSeq(pParse, pRight); }else{ pColl = sqlite3ExprCollSeq(pParse, pLeft); if( !pColl ){ pColl = sqlite3ExprCollSeq(pParse, pRight); } } return pColl; } /* ** Generate code for a comparison operator. */ static int codeCompare( Parse *pParse, /* The parsing (and code generating) context */ Expr *pLeft, /* The left operand */ Expr *pRight, /* The right operand */ int opcode, /* The comparison opcode */ int in1, int in2, /* Register holding operands */ int dest, /* Jump here if true. */ int jumpIfNull /* If true, jump if either operand is NULL */ ){ int p5; int addr; CollSeq *p4; p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, (void*)p4, P4_COLLSEQ); sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); return addr; } /* ** Return true if expression pExpr is a vector, or false otherwise. ** ** A vector is defined as any expression that results in two or more ** columns of result. Every TK_VECTOR node is an vector because the ** parser will not generate a TK_VECTOR with fewer than two entries. ** But a TK_SELECT might be either a vector or a scalar. It is only ** considered a vector if it has two or more result columns. */ SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){ return sqlite3ExprVectorSize(pExpr)>1; } /* ** If the expression passed as the only argument is of type TK_VECTOR ** return the number of expressions in the vector. Or, if the expression ** is a sub-select, return the number of columns in the sub-select. For ** any other type of expression, return 1. */ SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){ u8 op = pExpr->op; if( op==TK_REGISTER ) op = pExpr->op2; if( op==TK_VECTOR ){ return pExpr->x.pList->nExpr; }else if( op==TK_SELECT ){ return pExpr->x.pSelect->pEList->nExpr; }else{ return 1; } } #ifndef SQLITE_OMIT_SUBQUERY /* ** Return a pointer to a subexpression of pVector that is the i-th ** column of the vector (numbered starting with 0). The caller must ** ensure that i is within range. ** ** If pVector is really a scalar (and "scalar" here includes subqueries ** that return a single column!) then return pVector unmodified. ** ** pVector retains ownership of the returned subexpression. ** ** If the vector is a (SELECT ...) then the expression returned is ** just the expression for the i-th term of the result set, and may ** not be ready for evaluation because the table cursor has not yet ** been positioned. */ SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ assert( i<sqlite3ExprVectorSize(pVector) ); if( sqlite3ExprIsVector(pVector) ){ assert( pVector->op2==0 || pVector->op==TK_REGISTER ); if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){ return pVector->x.pSelect->pEList->a[i].pExpr; }else{ return pVector->x.pList->a[i].pExpr; } } return pVector; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) */ #ifndef SQLITE_OMIT_SUBQUERY /* ** Compute and return a new Expr object which when passed to ** sqlite3ExprCode() will generate all necessary code to compute ** the iField-th column of the vector expression pVector. ** ** It is ok for pVector to be a scalar (as long as iField==0). ** In that case, this routine works like sqlite3ExprDup(). ** ** The caller owns the returned Expr object and is responsible for ** ensuring that the returned value eventually gets freed. ** ** The caller retains ownership of pVector. If pVector is a TK_SELECT, ** then the returned object will reference pVector and so pVector must remain ** valid for the life of the returned object. If pVector is a TK_VECTOR ** or a scalar expression, then it can be deleted as soon as this routine ** returns. ** ** A trick to cause a TK_SELECT pVector to be deleted together with ** the returned Expr object is to attach the pVector to the pRight field ** of the returned TK_SELECT_COLUMN Expr object. */ SQLITE_PRIVATE Expr *sqlite3ExprForVectorField( Parse *pParse, /* Parsing context */ Expr *pVector, /* The vector. List of expressions or a sub-SELECT */ int iField /* Which column of the vector to return */ ){ Expr *pRet; if( pVector->op==TK_SELECT ){ assert( pVector->flags & EP_xIsSelect ); /* The TK_SELECT_COLUMN Expr node: ** ** pLeft: pVector containing TK_SELECT. Not deleted. ** pRight: not used. But recursively deleted. ** iColumn: Index of a column in pVector ** iTable: 0 or the number of columns on the LHS of an assignment ** pLeft->iTable: First in an array of register holding result, or 0 ** if the result is not yet computed. ** ** sqlite3ExprDelete() specifically skips the recursive delete of ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector ** can be attached to pRight to cause this node to take ownership of ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes ** with the same pLeft pointer to the pVector, but only one of them ** will own the pVector. */ pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0); if( pRet ){ pRet->iColumn = iField; pRet->pLeft = pVector; } assert( pRet==0 || pRet->iTable==0 ); }else{ if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr; pRet = sqlite3ExprDup(pParse->db, pVector, 0); } return pRet; } #endif /* !define(SQLITE_OMIT_SUBQUERY) */ /* ** If expression pExpr is of type TK_SELECT, generate code to evaluate ** it. Return the register in which the result is stored (or, if the ** sub-select returns more than one column, the first in an array ** of registers in which the result is stored). ** ** If pExpr is not a TK_SELECT expression, return 0. */ static int exprCodeSubselect(Parse *pParse, Expr *pExpr){ int reg = 0; #ifndef SQLITE_OMIT_SUBQUERY if( pExpr->op==TK_SELECT ){ reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0); } #endif return reg; } /* ** Argument pVector points to a vector expression - either a TK_VECTOR ** or TK_SELECT that returns more than one column. This function returns ** the register number of a register that contains the value of ** element iField of the vector. ** ** If pVector is a TK_SELECT expression, then code for it must have ** already been generated using the exprCodeSubselect() routine. In this ** case parameter regSelect should be the first in an array of registers ** containing the results of the sub-select. ** ** If pVector is of type TK_VECTOR, then code for the requested field ** is generated. In this case (*pRegFree) may be set to the number of ** a temporary register to be freed by the caller before returning. ** ** Before returning, output parameter (*ppExpr) is set to point to the ** Expr object corresponding to element iElem of the vector. */ static int exprVectorRegister( Parse *pParse, /* Parse context */ Expr *pVector, /* Vector to extract element from */ int iField, /* Field to extract from pVector */ int regSelect, /* First in array of registers */ Expr **ppExpr, /* OUT: Expression element */ int *pRegFree /* OUT: Temp register to free */ ){ u8 op = pVector->op; assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT ); if( op==TK_REGISTER ){ *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField); return pVector->iTable+iField; } if( op==TK_SELECT ){ *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr; return regSelect+iField; } *ppExpr = pVector->x.pList->a[iField].pExpr; return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); } /* ** Expression pExpr is a comparison between two vector values. Compute ** the result of the comparison (1, 0, or NULL) and write that ** result into register dest. ** ** The caller must satisfy the following preconditions: ** ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ ** otherwise: op==pExpr->op and p5==0 */ static void codeVectorCompare( Parse *pParse, /* Code generator context */ Expr *pExpr, /* The comparison operation */ int dest, /* Write results into this register */ u8 op, /* Comparison operator */ u8 p5 /* SQLITE_NULLEQ or zero */ ){ Vdbe *v = pParse->pVdbe; Expr *pLeft = pExpr->pLeft; Expr *pRight = pExpr->pRight; int nLeft = sqlite3ExprVectorSize(pLeft); int i; int regLeft = 0; int regRight = 0; u8 opx = op; int addrDone = sqlite3VdbeMakeLabel(v); if( nLeft!=sqlite3ExprVectorSize(pRight) ){ sqlite3ErrorMsg(pParse, "row value misused"); return; } assert( pExpr->op==TK_EQ || pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT || pExpr->op==TK_LT || pExpr->op==TK_GT || pExpr->op==TK_LE || pExpr->op==TK_GE ); assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ) || (pExpr->op==TK_ISNOT && op==TK_NE) ); assert( p5==0 || pExpr->op!=op ); assert( p5==SQLITE_NULLEQ || pExpr->op==op ); p5 |= SQLITE_STOREP2; if( opx==TK_LE ) opx = TK_LT; if( opx==TK_GE ) opx = TK_GT; regLeft = exprCodeSubselect(pParse, pLeft); regRight = exprCodeSubselect(pParse, pRight); for(i=0; 1 /*Loop exits by "break"*/; i++){ int regFree1 = 0, regFree2 = 0; Expr *pL, *pR; int r1, r2; assert( i>=0 && i<nLeft ); if( i>0 ) sqlite3ExprCachePush(pParse); r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1); r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2); codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); sqlite3ReleaseTempReg(pParse, regFree1); sqlite3ReleaseTempReg(pParse, regFree2); if( i>0 ) sqlite3ExprCachePop(pParse); if( i==nLeft-1 ){ break; } if( opx==TK_EQ ){ sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v); p5 |= SQLITE_KEEPNULL; }else if( opx==TK_NE ){ sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v); p5 |= SQLITE_KEEPNULL; }else{ assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE ); sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone); VdbeCoverageIf(v, op==TK_LT); VdbeCoverageIf(v, op==TK_GT); VdbeCoverageIf(v, op==TK_LE); VdbeCoverageIf(v, op==TK_GE); if( i==nLeft-2 ) opx = op; } } sqlite3VdbeResolveLabel(v, addrDone); } #if SQLITE_MAX_EXPR_DEPTH>0 /* ** Check that argument nHeight is less than or equal to the maximum ** expression depth allowed. If it is not, leave an error message in ** pParse. */ SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ int rc = SQLITE_OK; int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; if( nHeight>mxHeight ){ sqlite3ErrorMsg(pParse, "Expression tree is too large (maximum depth %d)", mxHeight ); rc = SQLITE_ERROR; } return rc; } /* The following three functions, heightOfExpr(), heightOfExprList() ** and heightOfSelect(), are used to determine the maximum height ** of any expression tree referenced by the structure passed as the ** first argument. ** ** If this maximum height is greater than the current value pointed ** to by pnHeight, the second parameter, then set *pnHeight to that ** value. */ static void heightOfExpr(Expr *p, int *pnHeight){ if( p ){ if( p->nHeight>*pnHeight ){ *pnHeight = p->nHeight; } } } static void heightOfExprList(ExprList *p, int *pnHeight){ if( p ){ int i; for(i=0; i<p->nExpr; i++){ heightOfExpr(p->a[i].pExpr, pnHeight); } } } static void heightOfSelect(Select *p, int *pnHeight){ if( p ){ heightOfExpr(p->pWhere, pnHeight); heightOfExpr(p->pHaving, pnHeight); heightOfExpr(p->pLimit, pnHeight); heightOfExpr(p->pOffset, pnHeight); heightOfExprList(p->pEList, pnHeight); heightOfExprList(p->pGroupBy, pnHeight); heightOfExprList(p->pOrderBy, pnHeight); heightOfSelect(p->pPrior, pnHeight); } } /* ** Set the Expr.nHeight variable in the structure passed as an ** argument. An expression with no children, Expr.pList or ** Expr.pSelect member has a height of 1. Any other expression ** has a height equal to the maximum height of any other ** referenced Expr plus one. ** ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags, ** if appropriate. */ static void exprSetHeight(Expr *p){ int nHeight = 0; heightOfExpr(p->pLeft, &nHeight); heightOfExpr(p->pRight, &nHeight); if( ExprHasProperty(p, EP_xIsSelect) ){ heightOfSelect(p->x.pSelect, &nHeight); }else if( p->x.pList ){ heightOfExprList(p->x.pList, &nHeight); p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); } p->nHeight = nHeight + 1; } /* ** Set the Expr.nHeight variable using the exprSetHeight() function. If ** the height is greater than the maximum allowed expression depth, ** leave an error in pParse. ** ** Also propagate all EP_Propagate flags from the Expr.x.pList into ** Expr.flags. */ SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ if( pParse->nErr ) return; exprSetHeight(p); sqlite3ExprCheckHeight(pParse, p->nHeight); } /* ** Return the maximum height of any expression tree referenced ** by the select statement passed as an argument. */ SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){ int nHeight = 0; heightOfSelect(p, &nHeight); return nHeight; } #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */ /* ** Propagate all EP_Propagate flags from the Expr.x.pList into ** Expr.flags. */ SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){ p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); } } #define exprSetHeight(y) #endif /* SQLITE_MAX_EXPR_DEPTH>0 */ /* ** This routine is the core allocator for Expr nodes. ** ** Construct a new expression node and return a pointer to it. Memory ** for this node and for the pToken argument is a single allocation ** obtained from sqlite3DbMalloc(). The calling function ** is responsible for making sure the node eventually gets freed. ** ** If dequote is true, then the token (if it exists) is dequoted. ** If dequote is false, no dequoting is performed. The deQuote ** parameter is ignored if pToken is NULL or if the token does not ** appear to be quoted. If the quotes were of the form "..." (double-quotes) ** then the EP_DblQuoted flag is set on the expression node. ** ** Special case: If op==TK_INTEGER and pToken points to a string that ** can be translated into a 32-bit integer, then the token is not ** stored in u.zToken. Instead, the integer values is written ** into u.iValue and the EP_IntValue flag is set. No extra storage ** is allocated to hold the integer text and the dequote flag is ignored. */ SQLITE_PRIVATE Expr *sqlite3ExprAlloc( sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */ int op, /* Expression opcode */ const Token *pToken, /* Token argument. Might be NULL */ int dequote /* True to dequote */ ){ Expr *pNew; int nExtra = 0; int iValue = 0; assert( db!=0 ); if( pToken ){ if( op!=TK_INTEGER || pToken->z==0 || sqlite3GetInt32(pToken->z, &iValue)==0 ){ nExtra = pToken->n+1; assert( iValue>=0 ); } } pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); if( pNew ){ memset(pNew, 0, sizeof(Expr)); pNew->op = (u8)op; pNew->iAgg = -1; if( pToken ){ if( nExtra==0 ){ pNew->flags |= EP_IntValue; pNew->u.iValue = iValue; }else{ pNew->u.zToken = (char*)&pNew[1]; assert( pToken->z!=0 || pToken->n==0 ); if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); pNew->u.zToken[pToken->n] = 0; if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted; sqlite3Dequote(pNew->u.zToken); } } } #if SQLITE_MAX_EXPR_DEPTH>0 pNew->nHeight = 1; #endif } return pNew; } /* ** Allocate a new expression node from a zero-terminated token that has ** already been dequoted. */ SQLITE_PRIVATE Expr *sqlite3Expr( sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ int op, /* Expression opcode */ const char *zToken /* Token argument. Might be NULL */ ){ Token x; x.z = zToken; x.n = zToken ? sqlite3Strlen30(zToken) : 0; return sqlite3ExprAlloc(db, op, &x, 0); } /* ** Attach subtrees pLeft and pRight to the Expr node pRoot. ** ** If pRoot==NULL that means that a memory allocation error has occurred. ** In that case, delete the subtrees pLeft and pRight. */ SQLITE_PRIVATE void sqlite3ExprAttachSubtrees( sqlite3 *db, Expr *pRoot, Expr *pLeft, Expr *pRight ){ if( pRoot==0 ){ assert( db->mallocFailed ); sqlite3ExprDelete(db, pLeft); sqlite3ExprDelete(db, pRight); }else{ if( pRight ){ pRoot->pRight = pRight; pRoot->flags |= EP_Propagate & pRight->flags; } if( pLeft ){ pRoot->pLeft = pLeft; pRoot->flags |= EP_Propagate & pLeft->flags; } exprSetHeight(pRoot); } } /* ** Allocate an Expr node which joins as many as two subtrees. ** ** One or both of the subtrees can be NULL. Return a pointer to the new ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, ** free the subtrees and return NULL. */ SQLITE_PRIVATE Expr *sqlite3PExpr( Parse *pParse, /* Parsing context */ int op, /* Expression opcode */ Expr *pLeft, /* Left operand */ Expr *pRight /* Right operand */ ){ Expr *p; if( op==TK_AND && pParse->nErr==0 ){ /* Take advantage of short-circuit false optimization for AND */ p = sqlite3ExprAnd(pParse->db, pLeft, pRight); }else{ p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)); if( p ){ memset(p, 0, sizeof(Expr)); p->op = op & TKFLG_MASK; p->iAgg = -1; } sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); } if( p ) { sqlite3ExprCheckHeight(pParse, p->nHeight); } return p; } /* ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due ** do a memory allocation failure) then delete the pSelect object. */ SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ if( pExpr ){ pExpr->x.pSelect = pSelect; ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery); sqlite3ExprSetHeightAndFlags(pParse, pExpr); }else{ assert( pParse->db->mallocFailed ); sqlite3SelectDelete(pParse->db, pSelect); } } /* ** If the expression is always either TRUE or FALSE (respectively), ** then return 1. If one cannot determine the truth value of the ** expression at compile-time return 0. ** ** This is an optimization. If is OK to return 0 here even if ** the expression really is always false or false (a false negative). ** But it is a bug to return 1 if the expression might have different ** boolean values in different circumstances (a false positive.) ** ** Note that if the expression is part of conditional for a ** LEFT JOIN, then we cannot determine at compile-time whether or not ** is it true or false, so always return 0. */ static int exprAlwaysTrue(Expr *p){ int v = 0; if( ExprHasProperty(p, EP_FromJoin) ) return 0; if( !sqlite3ExprIsInteger(p, &v) ) return 0; return v!=0; } static int exprAlwaysFalse(Expr *p){ int v = 0; if( ExprHasProperty(p, EP_FromJoin) ) return 0; if( !sqlite3ExprIsInteger(p, &v) ) return 0; return v==0; } /* ** Join two expressions using an AND operator. If either expression is ** NULL, then just return the other expression. ** ** If one side or the other of the AND is known to be false, then instead ** of returning an AND expression, just return a constant expression with ** a value of false. */ SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){ if( pLeft==0 ){ return pRight; }else if( pRight==0 ){ return pLeft; }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){ sqlite3ExprDelete(db, pLeft); sqlite3ExprDelete(db, pRight); return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0); }else{ Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0); sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight); return pNew; } } /* ** Construct a new expression node for a function with multiple ** arguments. */ SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){ Expr *pNew; sqlite3 *db = pParse->db; assert( pToken ); pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); if( pNew==0 ){ sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ return 0; } pNew->x.pList = pList; assert( !ExprHasProperty(pNew, EP_xIsSelect) ); sqlite3ExprSetHeightAndFlags(pParse, pNew); return pNew; } /* ** Assign a variable number to an expression that encodes a wildcard ** in the original SQL statement. ** ** Wildcards consisting of a single "?" are assigned the next sequential ** variable number. ** ** Wildcards of the form "?nnn" are assigned the number "nnn". We make ** sure "nnn" is not too big to avoid a denial of service attack when ** the SQL statement comes from an external source. ** ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number ** as the previous instance of the same wildcard. Or if this is the first ** instance of the wildcard, the next sequential variable number is ** assigned. */ SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ sqlite3 *db = pParse->db; const char *z; ynVar x; if( pExpr==0 ) return; assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); z = pExpr->u.zToken; assert( z!=0 ); assert( z[0]!=0 ); assert( n==sqlite3Strlen30(z) ); if( z[1]==0 ){ /* Wildcard of the form "?". Assign the next variable number */ assert( z[0]=='?' ); x = (ynVar)(++pParse->nVar); }else{ int doAdd = 0; if( z[0]=='?' ){ /* Wildcard of the form "?nnn". Convert "nnn" to an integer and ** use it as the variable number */ i64 i; int bOk; if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/ i = z[1]-'0'; /* The common case of ?N for a single digit N */ bOk = 1; }else{ bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); } testcase( i==0 ); testcase( i==1 ); testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); return; } x = (ynVar)i; if( x>pParse->nVar ){ pParse->nVar = (int)x; doAdd = 1; }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){ doAdd = 1; } }else{ /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable ** number as the prior appearance of the same name, or if the name ** has never appeared before, reuse the same variable number */ x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n); if( x==0 ){ x = (ynVar)(++pParse->nVar); doAdd = 1; } } if( doAdd ){ pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x); } } pExpr->iColumn = x; if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ sqlite3ErrorMsg(pParse, "too many SQL variables"); } } /* ** Recursively delete an expression tree. */ static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ assert( p!=0 ); /* Sanity check: Assert that the IntValue is non-negative if it exists */ assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 ); #ifdef SQLITE_DEBUG if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){ assert( p->pLeft==0 ); assert( p->pRight==0 ); assert( p->x.pSelect==0 ); } #endif if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){ /* The Expr.x union is never used at the same time as Expr.pRight */ assert( p->x.pList==0 || p->pRight==0 ); if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft); sqlite3ExprDelete(db, p->pRight); if( ExprHasProperty(p, EP_xIsSelect) ){ sqlite3SelectDelete(db, p->x.pSelect); }else{ sqlite3ExprListDelete(db, p->x.pList); } } if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken); if( !ExprHasProperty(p, EP_Static) ){ sqlite3DbFree(db, p); } } SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){ if( p ) sqlite3ExprDeleteNN(db, p); } /* ** Return the number of bytes allocated for the expression structure ** passed as the first argument. This is always one of EXPR_FULLSIZE, ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. */ static int exprStructSize(Expr *p){ if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; return EXPR_FULLSIZE; } /* ** The dupedExpr*Size() routines each return the number of bytes required ** to store a copy of an expression or expression tree. They differ in ** how much of the tree is measured. ** ** dupedExprStructSize() Size of only the Expr structure ** dupedExprNodeSize() Size of Expr + space for token ** dupedExprSize() Expr + token + subtree components ** *************************************************************************** ** ** The dupedExprStructSize() function returns two values OR-ed together: ** (1) the space required for a copy of the Expr structure only and ** (2) the EP_xxx flags that indicate what the structure size should be. ** The return values is always one of: ** ** EXPR_FULLSIZE ** EXPR_REDUCEDSIZE | EP_Reduced ** EXPR_TOKENONLYSIZE | EP_TokenOnly ** ** The size of the structure can be found by masking the return value ** of this routine with 0xfff. The flags can be found by masking the ** return value with EP_Reduced|EP_TokenOnly. ** ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size ** (unreduced) Expr objects as they or originally constructed by the parser. ** During expression analysis, extra information is computed and moved into ** later parts of teh Expr object and that extra information might get chopped ** off if the expression is reduced. Note also that it does not work to ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal ** to reduce a pristine expression tree from the parser. The implementation ** of dupedExprStructSize() contain multiple assert() statements that attempt ** to enforce this constraint. */ static int dupedExprStructSize(Expr *p, int flags){ int nSize; assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ assert( EXPR_FULLSIZE<=0xfff ); assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); if( 0==flags || p->op==TK_SELECT_COLUMN ){ nSize = EXPR_FULLSIZE; }else{ assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); assert( !ExprHasProperty(p, EP_FromJoin) ); assert( !ExprHasProperty(p, EP_MemToken) ); assert( !ExprHasProperty(p, EP_NoReduce) ); if( p->pLeft || p->x.pList ){ nSize = EXPR_REDUCEDSIZE | EP_Reduced; }else{ assert( p->pRight==0 ); nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; } } return nSize; } /* ** This function returns the space in bytes required to store the copy ** of the Expr structure and a copy of the Expr.u.zToken string (if that ** string is defined.) */ static int dupedExprNodeSize(Expr *p, int flags){ int nByte = dupedExprStructSize(p, flags) & 0xfff; if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ nByte += sqlite3Strlen30(p->u.zToken)+1; } return ROUND8(nByte); } /* ** Return the number of bytes required to create a duplicate of the ** expression passed as the first argument. The second argument is a ** mask containing EXPRDUP_XXX flags. ** ** The value returned includes space to create a copy of the Expr struct ** itself and the buffer referred to by Expr.u.zToken, if any. ** ** If the EXPRDUP_REDUCE flag is set, then the return value includes ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft ** and Expr.pRight variables (but not for any structures pointed to or ** descended from the Expr.x.pList or Expr.x.pSelect variables). */ static int dupedExprSize(Expr *p, int flags){ int nByte = 0; if( p ){ nByte = dupedExprNodeSize(p, flags); if( flags&EXPRDUP_REDUCE ){ nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags); } } return nByte; } /* ** This function is similar to sqlite3ExprDup(), except that if pzBuffer ** is not NULL then *pzBuffer is assumed to point to a buffer large enough ** to store the copy of expression p, the copies of p->u.zToken ** (if applicable), and the copies of the p->pLeft and p->pRight expressions, ** if any. Before returning, *pzBuffer is set to the first byte past the ** portion of the buffer copied into by this function. */ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ Expr *pNew; /* Value to return */ u8 *zAlloc; /* Memory space from which to build Expr object */ u32 staticFlag; /* EP_Static if space not obtained from malloc */ assert( db!=0 ); assert( p ); assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE ); assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE ); /* Figure out where to write the new Expr structure. */ if( pzBuffer ){ zAlloc = *pzBuffer; staticFlag = EP_Static; }else{ zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags)); staticFlag = 0; } pNew = (Expr *)zAlloc; if( pNew ){ /* Set nNewSize to the size allocated for the structure pointed to ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed ** by the copy of the p->u.zToken string (if any). */ const unsigned nStructSize = dupedExprStructSize(p, dupFlags); const int nNewSize = nStructSize & 0xfff; int nToken; if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ nToken = sqlite3Strlen30(p->u.zToken) + 1; }else{ nToken = 0; } if( dupFlags ){ assert( ExprHasProperty(p, EP_Reduced)==0 ); memcpy(zAlloc, p, nNewSize); }else{ u32 nSize = (u32)exprStructSize(p); memcpy(zAlloc, p, nSize); if( nSize<EXPR_FULLSIZE ){ memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize); } } /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken); pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); pNew->flags |= staticFlag; /* Copy the p->u.zToken string, if any. */ if( nToken ){ char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; memcpy(zToken, p->u.zToken, nToken); } if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){ /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ if( ExprHasProperty(p, EP_xIsSelect) ){ pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags); }else{ pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags); } } /* Fill in pNew->pLeft and pNew->pRight. */ if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){ zAlloc += dupedExprNodeSize(p, dupFlags); if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){ pNew->pLeft = p->pLeft ? exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0; pNew->pRight = p->pRight ? exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0; } if( pzBuffer ){ *pzBuffer = zAlloc; } }else{ if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ if( pNew->op==TK_SELECT_COLUMN ){ pNew->pLeft = p->pLeft; assert( p->iColumn==0 || p->pRight==0 ); assert( p->pRight==0 || p->pRight==p->pLeft ); }else{ pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); } pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); } } } return pNew; } /* ** Create and return a deep copy of the object passed as the second ** argument. If an OOM condition is encountered, NULL is returned ** and the db->mallocFailed flag set. */ #ifndef SQLITE_OMIT_CTE static With *withDup(sqlite3 *db, With *p){ With *pRet = 0; if( p ){ int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); pRet = sqlite3DbMallocZero(db, nByte); if( pRet ){ int i; pRet->nCte = p->nCte; for(i=0; i<p->nCte; i++){ pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0); pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0); pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName); } } } return pRet; } #else # define withDup(x,y) 0 #endif /* ** The following group of routines make deep copies of expressions, ** expression lists, ID lists, and select statements. The copies can ** be deleted (by being passed to their respective ...Delete() routines) ** without effecting the originals. ** ** The expression list, ID, and source lists return by sqlite3ExprListDup(), ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded ** by subsequent calls to sqlite*ListAppend() routines. ** ** Any tables that the SrcList might point to are not duplicated. ** ** The flags parameter contains a combination of the EXPRDUP_XXX flags. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a ** truncated version of the usual Expr structure that will be stored as ** part of the in-memory representation of the database schema. */ SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ assert( flags==0 || flags==EXPRDUP_REDUCE ); return p ? exprDup(db, p, flags, 0) : 0; } SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ ExprList *pNew; struct ExprList_item *pItem, *pOldItem; int i; Expr *pPriorSelectCol = 0; assert( db!=0 ); if( p==0 ) return 0; pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); if( pNew==0 ) return 0; pNew->nExpr = i = p->nExpr; if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){} pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) ); if( pItem==0 ){ sqlite3DbFree(db, pNew); return 0; } pOldItem = p->a; for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){ Expr *pOldExpr = pOldItem->pExpr; Expr *pNewExpr; pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); if( pOldExpr && pOldExpr->op==TK_SELECT_COLUMN && (pNewExpr = pItem->pExpr)!=0 ){ assert( pNewExpr->iColumn==0 || i>0 ); if( pNewExpr->iColumn==0 ){ assert( pOldExpr->pLeft==pOldExpr->pRight ); pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight; }else{ assert( i>0 ); assert( pItem[-1].pExpr!=0 ); assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 ); assert( pPriorSelectCol==pItem[-1].pExpr->pLeft ); pNewExpr->pLeft = pPriorSelectCol; } } pItem->zName = sqlite3DbStrDup(db, pOldItem->zName); pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan); pItem->sortOrder = pOldItem->sortOrder; pItem->done = 0; pItem->bSpanIsTab = pOldItem->bSpanIsTab; pItem->u = pOldItem->u; } return pNew; } /* ** If cursors, triggers, views and subqueries are all omitted from ** the build, then none of the following routines, except for ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes ** called with a NULL argument. */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ || !defined(SQLITE_OMIT_SUBQUERY) SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ SrcList *pNew; int i; int nByte; assert( db!=0 ); if( p==0 ) return 0; nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); pNew = sqlite3DbMallocRawNN(db, nByte ); if( pNew==0 ) return 0; pNew->nSrc = pNew->nAlloc = p->nSrc; for(i=0; i<p->nSrc; i++){ struct SrcList_item *pNewItem = &pNew->a[i]; struct SrcList_item *pOldItem = &p->a[i]; Table *pTab; pNewItem->pSchema = pOldItem->pSchema; pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); pNewItem->fg = pOldItem->fg; pNewItem->iCursor = pOldItem->iCursor; pNewItem->addrFillSub = pOldItem->addrFillSub; pNewItem->regReturn = pOldItem->regReturn; if( pNewItem->fg.isIndexedBy ){ pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); } pNewItem->pIBIndex = pOldItem->pIBIndex; if( pNewItem->fg.isTabFunc ){ pNewItem->u1.pFuncArg = sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); } pTab = pNewItem->pTab = pOldItem->pTab; if( pTab ){ pTab->nTabRef++; } pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); pNewItem->colUsed = pOldItem->colUsed; } return pNew; } SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ IdList *pNew; int i; assert( db!=0 ); if( p==0 ) return 0; pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); if( pNew==0 ) return 0; pNew->nId = p->nId; pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) ); if( pNew->a==0 ){ sqlite3DbFree(db, pNew); return 0; } /* Note that because the size of the allocation for p->a[] is not ** necessarily a power of two, sqlite3IdListAppend() may not be called ** on the duplicate created by this function. */ for(i=0; i<p->nId; i++){ struct IdList_item *pNewItem = &pNew->a[i]; struct IdList_item *pOldItem = &p->a[i]; pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); pNewItem->idx = pOldItem->idx; } return pNew; } SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){ Select *pRet = 0; Select *pNext = 0; Select **pp = &pRet; Select *p; assert( db!=0 ); for(p=pDup; p; p=p->pPrior){ Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) ); if( pNew==0 ) break; pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); pNew->op = p->op; pNew->pNext = pNext; pNew->pPrior = 0; pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags); pNew->iLimit = 0; pNew->iOffset = 0; pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; pNew->addrOpenEphm[0] = -1; pNew->addrOpenEphm[1] = -1; pNew->nSelectRow = p->nSelectRow; pNew->pWith = withDup(db, p->pWith); sqlite3SelectSetName(pNew, p->zSelName); *pp = pNew; pp = &pNew->pPrior; pNext = pNew; } return pRet; } #else SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ assert( p==0 ); return 0; } #endif /* ** Add a new element to the end of an expression list. If pList is ** initially NULL, then create a new expression list. ** ** If a memory allocation error occurs, the entire list is freed and ** NULL is returned. If non-NULL is returned, then it is guaranteed ** that the new entry was successfully appended. */ SQLITE_PRIVATE ExprList *sqlite3ExprListAppend( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ Expr *pExpr /* Expression to be appended. Might be NULL */ ){ sqlite3 *db = pParse->db; assert( db!=0 ); if( pList==0 ){ pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) ); if( pList==0 ){ goto no_mem; } pList->nExpr = 0; pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0])); if( pList->a==0 ) goto no_mem; }else if( (pList->nExpr & (pList->nExpr-1))==0 ){ struct ExprList_item *a; assert( pList->nExpr>0 ); a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0])); if( a==0 ){ goto no_mem; } pList->a = a; } assert( pList->a!=0 ); if( 1 ){ struct ExprList_item *pItem = &pList->a[pList->nExpr++]; memset(pItem, 0, sizeof(*pItem)); pItem->pExpr = pExpr; } return pList; no_mem: /* Avoid leaking memory if malloc has failed. */ sqlite3ExprDelete(db, pExpr); sqlite3ExprListDelete(db, pList); return 0; } /* ** pColumns and pExpr form a vector assignment which is part of the SET ** clause of an UPDATE statement. Like this: ** ** (a,b,c) = (expr1,expr2,expr3) ** Or: (a,b,c) = (SELECT x,y,z FROM ....) ** ** For each term of the vector assignment, append new entries to the ** expression list pList. In the case of a subquery on the RHS, append ** TK_SELECT_COLUMN expressions. */ SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ IdList *pColumns, /* List of names of LHS of the assignment */ Expr *pExpr /* Vector expression to be appended. Might be NULL */ ){ sqlite3 *db = pParse->db; int n; int i; int iFirst = pList ? pList->nExpr : 0; /* pColumns can only be NULL due to an OOM but an OOM will cause an ** exit prior to this routine being invoked */ if( NEVER(pColumns==0) ) goto vector_append_error; if( pExpr==0 ) goto vector_append_error; /* If the RHS is a vector, then we can immediately check to see that ** the size of the RHS and LHS match. But if the RHS is a SELECT, ** wildcards ("*") in the result set of the SELECT must be expanded before ** we can do the size check, so defer the size check until code generation. */ if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){ sqlite3ErrorMsg(pParse, "%d columns assigned %d values", pColumns->nId, n); goto vector_append_error; } for(i=0; i<pColumns->nId; i++){ Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i); pList = sqlite3ExprListAppend(pParse, pList, pSubExpr); if( pList ){ assert( pList->nExpr==iFirst+i+1 ); pList->a[pList->nExpr-1].zName = pColumns->a[i].zName; pColumns->a[i].zName = 0; } } if( pExpr->op==TK_SELECT ){ if( pList && pList->a[iFirst].pExpr ){ Expr *pFirst = pList->a[iFirst].pExpr; assert( pFirst->op==TK_SELECT_COLUMN ); /* Store the SELECT statement in pRight so it will be deleted when ** sqlite3ExprListDelete() is called */ pFirst->pRight = pExpr; pExpr = 0; /* Remember the size of the LHS in iTable so that we can check that ** the RHS and LHS sizes match during code generation. */ pFirst->iTable = pColumns->nId; } } vector_append_error: sqlite3ExprDelete(db, pExpr); sqlite3IdListDelete(db, pColumns); return pList; } /* ** Set the sort order for the last element on the given ExprList. */ SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){ if( p==0 ) return; assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 ); assert( p->nExpr>0 ); if( iSortOrder<0 ){ assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC ); return; } p->a[p->nExpr-1].sortOrder = (u8)iSortOrder; } /* ** Set the ExprList.a[].zName element of the most recently added item ** on the expression list. ** ** pList might be NULL following an OOM error. But pName should never be ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag ** is set. */ SQLITE_PRIVATE void sqlite3ExprListSetName( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to add the span. */ Token *pName, /* Name to be added */ int dequote /* True to cause the name to be dequoted */ ){ assert( pList!=0 || pParse->db->mallocFailed!=0 ); if( pList ){ struct ExprList_item *pItem; assert( pList->nExpr>0 ); pItem = &pList->a[pList->nExpr-1]; assert( pItem->zName==0 ); pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); if( dequote ) sqlite3Dequote(pItem->zName); } } /* ** Set the ExprList.a[].zSpan element of the most recently added item ** on the expression list. ** ** pList might be NULL following an OOM error. But pSpan should never be ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag ** is set. */ SQLITE_PRIVATE void sqlite3ExprListSetSpan( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to add the span. */ ExprSpan *pSpan /* The span to be added */ ){ sqlite3 *db = pParse->db; assert( pList!=0 || db->mallocFailed!=0 ); if( pList ){ struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; assert( pList->nExpr>0 ); assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr ); sqlite3DbFree(db, pItem->zSpan); pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart, (int)(pSpan->zEnd - pSpan->zStart)); } } /* ** If the expression list pEList contains more than iLimit elements, ** leave an error message in pParse. */ SQLITE_PRIVATE void sqlite3ExprListCheckLength( Parse *pParse, ExprList *pEList, const char *zObject ){ int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; testcase( pEList && pEList->nExpr==mx ); testcase( pEList && pEList->nExpr==mx+1 ); if( pEList && pEList->nExpr>mx ){ sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); } } /* ** Delete an entire expression list. */ static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){ int i; struct ExprList_item *pItem; assert( pList->a!=0 || pList->nExpr==0 ); for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ sqlite3ExprDelete(db, pItem->pExpr); sqlite3DbFree(db, pItem->zName); sqlite3DbFree(db, pItem->zSpan); } sqlite3DbFree(db, pList->a); sqlite3DbFree(db, pList); } SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ if( pList ) exprListDeleteNN(db, pList); } /* ** Return the bitwise-OR of all Expr.flags fields in the given ** ExprList. */ SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){ int i; u32 m = 0; if( pList ){ for(i=0; i<pList->nExpr; i++){ Expr *pExpr = pList->a[i].pExpr; assert( pExpr!=0 ); m |= pExpr->flags; } } return m; } /* ** These routines are Walker callbacks used to check expressions to ** see if they are "constant" for some definition of constant. The ** Walker.eCode value determines the type of "constant" we are looking ** for. ** ** These callback routines are used to implement the following: ** ** sqlite3ExprIsConstant() pWalker->eCode==1 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 ** sqlite3ExprIsTableConstant() pWalker->eCode==3 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 ** ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression ** is found to not be a constant. ** ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing ** an existing schema and 4 when processing a new statement. A bound ** parameter raises an error for new statements, but is silently converted ** to NULL for existing schemas. This allows sqlite_master tables that ** contain a bound parameter because they were generated by older versions ** of SQLite to be parsed by newer versions of SQLite without raising a ** malformed schema error. */ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ /* If pWalker->eCode is 2 then any term of the expression that comes from ** the ON or USING clauses of a left join disqualifies the expression ** from being considered constant. */ if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){ pWalker->eCode = 0; return WRC_Abort; } switch( pExpr->op ){ /* Consider functions to be constant if all their arguments are constant ** and either pWalker->eCode==4 or 5 or the function has the ** SQLITE_FUNC_CONST flag. */ case TK_FUNCTION: if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){ return WRC_Continue; }else{ pWalker->eCode = 0; return WRC_Abort; } case TK_ID: case TK_COLUMN: case TK_AGG_FUNCTION: case TK_AGG_COLUMN: testcase( pExpr->op==TK_ID ); testcase( pExpr->op==TK_COLUMN ); testcase( pExpr->op==TK_AGG_FUNCTION ); testcase( pExpr->op==TK_AGG_COLUMN ); if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ return WRC_Continue; }else{ pWalker->eCode = 0; return WRC_Abort; } case TK_VARIABLE: if( pWalker->eCode==5 ){ /* Silently convert bound parameters that appear inside of CREATE ** statements into a NULL when parsing the CREATE statement text out ** of the sqlite_master table */ pExpr->op = TK_NULL; }else if( pWalker->eCode==4 ){ /* A bound parameter in a CREATE statement that originates from ** sqlite3_prepare() causes an error */ pWalker->eCode = 0; return WRC_Abort; } /* Fall through */ default: testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */ testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */ return WRC_Continue; } } static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){ UNUSED_PARAMETER(NotUsed); pWalker->eCode = 0; return WRC_Abort; } static int exprIsConst(Expr *p, int initFlag, int iCur){ Walker w; memset(&w, 0, sizeof(w)); w.eCode = initFlag; w.xExprCallback = exprNodeIsConstant; w.xSelectCallback = selectNodeIsConstant; w.u.iCur = iCur; sqlite3WalkExpr(&w, p); return w.eCode; } /* ** Walk an expression tree. Return non-zero if the expression is constant ** and 0 if it involves variables or function calls. ** ** For the purposes of this function, a double-quoted string (ex: "abc") ** is considered a variable but a single-quoted string (ex: 'abc') is ** a constant. */ SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){ return exprIsConst(p, 1, 0); } /* ** Walk an expression tree. Return non-zero if the expression is constant ** that does no originate from the ON or USING clauses of a join. ** Return 0 if it involves variables or function calls or terms from ** an ON or USING clause. */ SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){ return exprIsConst(p, 2, 0); } /* ** Walk an expression tree. Return non-zero if the expression is constant ** for any single row of the table with cursor iCur. In other words, the ** expression must not refer to any non-deterministic function nor any ** table other than iCur. */ SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){ return exprIsConst(p, 3, iCur); } /* ** Walk an expression tree. Return non-zero if the expression is constant ** or a function call with constant arguments. Return and 0 if there ** are any variables. ** ** For the purposes of this function, a double-quoted string (ex: "abc") ** is considered a variable but a single-quoted string (ex: 'abc') is ** a constant. */ SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ assert( isInit==0 || isInit==1 ); return exprIsConst(p, 4+isInit, 0); } #ifdef SQLITE_ENABLE_CURSOR_HINTS /* ** Walk an expression tree. Return 1 if the expression contains a ** subquery of some kind. Return 0 if there are no subqueries. */ SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){ Walker w; memset(&w, 0, sizeof(w)); w.eCode = 1; w.xExprCallback = sqlite3ExprWalkNoop; w.xSelectCallback = selectNodeIsConstant; sqlite3WalkExpr(&w, p); return w.eCode==0; } #endif /* ** If the expression p codes a constant integer that is small enough ** to fit in a 32-bit integer, return 1 and put the value of the integer ** in *pValue. If the expression is not an integer or if it is too big ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. */ SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){ int rc = 0; /* If an expression is an integer literal that fits in a signed 32-bit ** integer, then the EP_IntValue flag will have already been set */ assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 || sqlite3GetInt32(p->u.zToken, &rc)==0 ); if( p->flags & EP_IntValue ){ *pValue = p->u.iValue; return 1; } switch( p->op ){ case TK_UPLUS: { rc = sqlite3ExprIsInteger(p->pLeft, pValue); break; } case TK_UMINUS: { int v; if( sqlite3ExprIsInteger(p->pLeft, &v) ){ assert( v!=(-2147483647-1) ); *pValue = -v; rc = 1; } break; } default: break; } return rc; } /* ** Return FALSE if there is no chance that the expression can be NULL. ** ** If the expression might be NULL or if the expression is too complex ** to tell return TRUE. ** ** This routine is used as an optimization, to skip OP_IsNull opcodes ** when we know that a value cannot be NULL. Hence, a false positive ** (returning TRUE when in fact the expression can never be NULL) might ** be a small performance hit but is otherwise harmless. On the other ** hand, a false negative (returning FALSE when the result could be NULL) ** will likely result in an incorrect answer. So when in doubt, return ** TRUE. */ SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){ u8 op; while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } op = p->op; if( op==TK_REGISTER ) op = p->op2; switch( op ){ case TK_INTEGER: case TK_STRING: case TK_FLOAT: case TK_BLOB: return 0; case TK_COLUMN: assert( p->pTab!=0 ); return ExprHasProperty(p, EP_CanBeNull) || (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0); default: return 1; } } /* ** Return TRUE if the given expression is a constant which would be ** unchanged by OP_Affinity with the affinity given in the second ** argument. ** ** This routine is used to determine if the OP_Affinity operation ** can be omitted. When in doubt return FALSE. A false negative ** is harmless. A false positive, however, can result in the wrong ** answer. */ SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ u8 op; if( aff==SQLITE_AFF_BLOB ) return 1; while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } op = p->op; if( op==TK_REGISTER ) op = p->op2; switch( op ){ case TK_INTEGER: { return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC; } case TK_FLOAT: { return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC; } case TK_STRING: { return aff==SQLITE_AFF_TEXT; } case TK_BLOB: { return 1; } case TK_COLUMN: { assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ return p->iColumn<0 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC); } default: { return 0; } } } /* ** Return TRUE if the given string is a row-id column name. */ SQLITE_PRIVATE int sqlite3IsRowid(const char *z){ if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; if( sqlite3StrICmp(z, "OID")==0 ) return 1; return 0; } /* ** pX is the RHS of an IN operator. If pX is a SELECT statement ** that can be simplified to a direct table access, then return ** a pointer to the SELECT statement. If pX is not a SELECT statement, ** or if the SELECT statement needs to be manifested into a transient ** table, then return NULL. */ #ifndef SQLITE_OMIT_SUBQUERY static Select *isCandidateForInOpt(Expr *pX){ Select *p; SrcList *pSrc; ExprList *pEList; Table *pTab; int i; if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */ if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */ p = pX->x.pSelect; if( p->pPrior ) return 0; /* Not a compound SELECT */ if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); return 0; /* No DISTINCT keyword and no aggregate functions */ } assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ if( p->pLimit ) return 0; /* Has no LIMIT clause */ assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */ if( p->pWhere ) return 0; /* Has no WHERE clause */ pSrc = p->pSrc; assert( pSrc!=0 ); if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ pTab = pSrc->a[0].pTab; assert( pTab!=0 ); assert( pTab->pSelect==0 ); /* FROM clause is not a view */ if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ pEList = p->pEList; assert( pEList!=0 ); /* All SELECT results must be columns. */ for(i=0; i<pEList->nExpr; i++){ Expr *pRes = pEList->a[i].pExpr; if( pRes->op!=TK_COLUMN ) return 0; assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */ } return p; } #endif /* SQLITE_OMIT_SUBQUERY */ #ifndef SQLITE_OMIT_SUBQUERY /* ** Generate code that checks the left-most column of index table iCur to see if ** it contains any NULL entries. Cause the register at regHasNull to be set ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull ** to be set to NULL if iCur contains one or more NULL values. */ static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ int addr1; sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); VdbeComment((v, "first_entry_in(%d)", iCur)); sqlite3VdbeJumpHere(v, addr1); } #endif #ifndef SQLITE_OMIT_SUBQUERY /* ** The argument is an IN operator with a list (not a subquery) on the ** right-hand side. Return TRUE if that list is constant. */ static int sqlite3InRhsIsConstant(Expr *pIn){ Expr *pLHS; int res; assert( !ExprHasProperty(pIn, EP_xIsSelect) ); pLHS = pIn->pLeft; pIn->pLeft = 0; res = sqlite3ExprIsConstant(pIn); pIn->pLeft = pLHS; return res; } #endif /* ** This function is used by the implementation of the IN (...) operator. ** The pX parameter is the expression on the RHS of the IN operator, which ** might be either a list of expressions or a subquery. ** ** The job of this routine is to find or create a b-tree object that can ** be used either to test for membership in the RHS set or to iterate through ** all members of the RHS set, skipping duplicates. ** ** A cursor is opened on the b-tree object that is the RHS of the IN operator ** and pX->iTable is set to the index of that cursor. ** ** The returned value of this function indicates the b-tree type, as follows: ** ** IN_INDEX_ROWID - The cursor was opened on a database table. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. ** IN_INDEX_EPH - The cursor was opened on a specially created and ** populated epheremal table. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be ** implemented as a sequence of comparisons. ** ** An existing b-tree might be used if the RHS expression pX is a simple ** subquery such as: ** ** SELECT <column1>, <column2>... FROM <table> ** ** If the RHS of the IN operator is a list or a more complex subquery, then ** an ephemeral table might need to be generated from the RHS and then ** pX->iTable made to point to the ephemeral table instead of an ** existing table. ** ** The inFlags parameter must contain exactly one of the bits ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a ** fast membership test. When the IN_INDEX_LOOP bit is set, the ** IN index will be used to loop over all values of the RHS of the ** IN operator. ** ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate ** through the set members) then the b-tree must not contain duplicates. ** An epheremal table must be used unless the selected columns are guaranteed ** to be unique - either because it is an INTEGER PRIMARY KEY or due to ** a UNIQUE constraint or index. ** ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used ** for fast set membership tests) then an epheremal table must ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an ** index can be found with the specified <columns> as its left-most. ** ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and ** if the RHS of the IN operator is a list (not a subquery) then this ** routine might decide that creating an ephemeral b-tree for membership ** testing is too expensive and return IN_INDEX_NOOP. In that case, the ** calling routine should implement the IN operator using a sequence ** of Eq or Ne comparison operations. ** ** When the b-tree is being used for membership tests, the calling function ** might need to know whether or not the RHS side of the IN operator ** contains a NULL. If prRhsHasNull is not a NULL pointer and ** if there is any chance that the (...) might contain a NULL value at ** runtime, then a register is allocated and the register number written ** to *prRhsHasNull. If there is no chance that the (...) contains a ** NULL value, then *prRhsHasNull is left unchanged. ** ** If a register is allocated and its location stored in *prRhsHasNull, then ** the value in that register will be NULL if the b-tree contains one or more ** NULL values, and it will be some non-NULL value if the b-tree contains no ** NULL values. ** ** If the aiMap parameter is not NULL, it must point to an array containing ** one element for each column returned by the SELECT statement on the RHS ** of the IN(...) operator. The i'th entry of the array is populated with the ** offset of the index column that matches the i'th column returned by the ** SELECT. For example, if the expression and selected index are: ** ** (?,?,?) IN (SELECT a, b, c FROM t1) ** CREATE INDEX i1 ON t1(b, c, a); ** ** then aiMap[] is populated with {2, 0, 1}. */ #ifndef SQLITE_OMIT_SUBQUERY SQLITE_PRIVATE int sqlite3FindInIndex( Parse *pParse, /* Parsing context */ Expr *pX, /* The right-hand side (RHS) of the IN operator */ u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */ int *prRhsHasNull, /* Register holding NULL status. See notes */ int *aiMap /* Mapping from Index fields to RHS fields */ ){ Select *p; /* SELECT to the right of IN operator */ int eType = 0; /* Type of RHS table. IN_INDEX_* */ int iTab = pParse->nTab++; /* Cursor of the RHS table */ int mustBeUnique; /* True if RHS must be unique */ Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ assert( pX->op==TK_IN ); mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0; /* If the RHS of this IN(...) operator is a SELECT, and if it matters ** whether or not the SELECT result contains NULL values, check whether ** or not NULL is actually possible (it may not be, for example, due ** to NOT NULL constraints in the schema). If no NULL values are possible, ** set prRhsHasNull to 0 before continuing. */ if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){ int i; ExprList *pEList = pX->x.pSelect->pEList; for(i=0; i<pEList->nExpr; i++){ if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; } if( i==pEList->nExpr ){ prRhsHasNull = 0; } } /* Check to see if an existing table or index can be used to ** satisfy the query. This is preferable to generating a new ** ephemeral table. */ if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){ sqlite3 *db = pParse->db; /* Database connection */ Table *pTab; /* Table <table>. */ i16 iDb; /* Database idx for pTab */ ExprList *pEList = p->pEList; int nExpr = pEList->nExpr; assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ pTab = p->pSrc->a[0].pTab; /* Code an OP_Transaction and OP_TableLock for <table>. */ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3CodeVerifySchema(pParse, iDb); sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); assert(v); /* sqlite3GetVdbe() has always been previously called */ if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){ /* The "x IN (SELECT rowid FROM table)" case */ int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); eType = IN_INDEX_ROWID; sqlite3VdbeJumpHere(v, iAddr); }else{ Index *pIdx; /* Iterator variable */ int affinity_ok = 1; int i; /* Check that the affinity that will be used to perform each ** comparison is the same as the affinity of each column in table ** on the RHS of the IN operator. If it not, it is not possible to ** use any index of the RHS table. */ for(i=0; i<nExpr && affinity_ok; i++){ Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); int iCol = pEList->a[i].pExpr->iColumn; char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ char cmpaff = sqlite3CompareAffinity(pLhs, idxaff); testcase( cmpaff==SQLITE_AFF_BLOB ); testcase( cmpaff==SQLITE_AFF_TEXT ); switch( cmpaff ){ case SQLITE_AFF_BLOB: break; case SQLITE_AFF_TEXT: /* sqlite3CompareAffinity() only returns TEXT if one side or the ** other has no affinity and the other side is TEXT. Hence, ** the only way for cmpaff to be TEXT is for idxaff to be TEXT ** and for the term on the LHS of the IN to have no affinity. */ assert( idxaff==SQLITE_AFF_TEXT ); break; default: affinity_ok = sqlite3IsNumericAffinity(idxaff); } } if( affinity_ok ){ /* Search for an existing index that will work for this IN operator */ for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){ Bitmask colUsed; /* Columns of the index used */ Bitmask mCol; /* Mask for the current column */ if( pIdx->nColumn<nExpr ) continue; /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute ** BITMASK(nExpr) without overflowing */ testcase( pIdx->nColumn==BMS-2 ); testcase( pIdx->nColumn==BMS-1 ); if( pIdx->nColumn>=BMS-1 ) continue; if( mustBeUnique ){ if( pIdx->nKeyCol>nExpr ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx)) ){ continue; /* This index is not unique over the IN RHS columns */ } } colUsed = 0; /* Columns of index used so far */ for(i=0; i<nExpr; i++){ Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); Expr *pRhs = pEList->a[i].pExpr; CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); int j; assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr ); for(j=0; j<nExpr; j++){ if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue; assert( pIdx->azColl[j] ); if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ continue; } break; } if( j==nExpr ) break; mCol = MASKBIT(j); if( mCol & colUsed ) break; /* Each column used only once */ colUsed |= mCol; if( aiMap ) aiMap[i] = j; } assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) ); if( colUsed==(MASKBIT(nExpr)-1) ){ /* If we reach this point, that means the index pIdx is usable */ int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); #ifndef SQLITE_OMIT_EXPLAIN sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0, sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName), P4_DYNAMIC); #endif sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; if( prRhsHasNull ){ #ifdef SQLITE_ENABLE_COLUMN_USED_MASK i64 mask = (1<<nExpr)-1; sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iTab, 0, 0, (u8*)&mask, P4_INT64); #endif *prRhsHasNull = ++pParse->nMem; if( nExpr==1 ){ sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); } } sqlite3VdbeJumpHere(v, iAddr); } } /* End loop over indexes */ } /* End if( affinity_ok ) */ } /* End if not an rowid index */ } /* End attempt to optimize using an index */ /* If no preexisting index is available for the IN clause ** and IN_INDEX_NOOP is an allowed reply ** and the RHS of the IN operator is a list, not a subquery ** and the RHS is not constant or has two or fewer terms, ** then it is not worth creating an ephemeral table to evaluate ** the IN operator so return IN_INDEX_NOOP. */ if( eType==0 && (inFlags & IN_INDEX_NOOP_OK) && !ExprHasProperty(pX, EP_xIsSelect) && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2) ){ eType = IN_INDEX_NOOP; } if( eType==0 ){ /* Could not find an existing table or index to use as the RHS b-tree. ** We will have to generate an ephemeral table to do the job. */ u32 savedNQueryLoop = pParse->nQueryLoop; int rMayHaveNull = 0; eType = IN_INDEX_EPH; if( inFlags & IN_INDEX_LOOP ){ pParse->nQueryLoop = 0; if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){ eType = IN_INDEX_ROWID; } }else if( prRhsHasNull ){ *prRhsHasNull = rMayHaveNull = ++pParse->nMem; } sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID); pParse->nQueryLoop = savedNQueryLoop; }else{ pX->iTable = iTab; } if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){ int i, n; n = sqlite3ExprVectorSize(pX->pLeft); for(i=0; i<n; i++) aiMap[i] = i; } return eType; } #endif #ifndef SQLITE_OMIT_SUBQUERY /* ** Argument pExpr is an (?, ?...) IN(...) expression. This ** function allocates and returns a nul-terminated string containing ** the affinities to be used for each column of the comparison. ** ** It is the responsibility of the caller to ensure that the returned ** string is eventually freed using sqlite3DbFree(). */ static char *exprINAffinity(Parse *pParse, Expr *pExpr){ Expr *pLeft = pExpr->pLeft; int nVal = sqlite3ExprVectorSize(pLeft); Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0; char *zRet; assert( pExpr->op==TK_IN ); zRet = sqlite3DbMallocZero(pParse->db, nVal+1); if( zRet ){ int i; for(i=0; i<nVal; i++){ Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i); char a = sqlite3ExprAffinity(pA); if( pSelect ){ zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a); }else{ zRet[i] = a; } } zRet[nVal] = '\0'; } return zRet; } #endif #ifndef SQLITE_OMIT_SUBQUERY /* ** Load the Parse object passed as the first argument with an error ** message of the form: ** ** "sub-select returns N columns - expected M" */ SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ const char *zFmt = "sub-select returns %d columns - expected %d"; sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); } #endif /* ** Expression pExpr is a vector that has been used in a context where ** it is not permitted. If pExpr is a sub-select vector, this routine ** loads the Parse object with a message of the form: ** ** "sub-select returns N columns - expected 1" ** ** Or, if it is a regular scalar vector: ** ** "row value misused" */ SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){ #ifndef SQLITE_OMIT_SUBQUERY if( pExpr->flags & EP_xIsSelect ){ sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1); }else #endif { sqlite3ErrorMsg(pParse, "row value misused"); } } /* ** Generate code for scalar subqueries used as a subquery expression, EXISTS, ** or IN operators. Examples: ** ** (SELECT a FROM b) -- subquery ** EXISTS (SELECT a FROM b) -- EXISTS subquery ** x IN (4,5,11) -- IN operator with list on right-hand side ** x IN (SELECT a FROM b) -- IN operator with subquery on the right ** ** The pExpr parameter describes the expression that contains the IN ** operator or subquery. ** ** If parameter isRowid is non-zero, then expression pExpr is guaranteed ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference ** to some integer key column of a table B-Tree. In this case, use an ** intkey B-Tree to store the set of IN(...) values instead of the usual ** (slower) variable length keys B-Tree. ** ** If rMayHaveNull is non-zero, that means that the operation is an IN ** (not a SELECT or EXISTS) and that the RHS might contains NULLs. ** All this routine does is initialize the register given by rMayHaveNull ** to NULL. Calling routines will take care of changing this register ** value to non-NULL if the RHS is NULL-free. ** ** For a SELECT or EXISTS operator, return the register that holds the ** result. For a multi-column SELECT, the result is stored in a contiguous ** array of registers and the return value is the register of the left-most ** result column. Return 0 for IN operators or if an error occurs. */ #ifndef SQLITE_OMIT_SUBQUERY SQLITE_PRIVATE int sqlite3CodeSubselect( Parse *pParse, /* Parsing context */ Expr *pExpr, /* The IN, SELECT, or EXISTS operator */ int rHasNullFlag, /* Register that records whether NULLs exist in RHS */ int isRowid /* If true, LHS of IN operator is a rowid */ ){ int jmpIfDynamic = -1; /* One-time test address */ int rReg = 0; /* Register storing resulting */ Vdbe *v = sqlite3GetVdbe(pParse); if( NEVER(v==0) ) return 0; sqlite3ExprCachePush(pParse); /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it ** is encountered if any of the following is true: ** ** * The right-hand side is a correlated subquery ** * The right-hand side is an expression list containing variables ** * We are inside a trigger ** ** If all of the above are false, then we can run this code just once ** save the results, and reuse the same result on subsequent invocations. */ if( !ExprHasProperty(pExpr, EP_VarSelect) ){ jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } #ifndef SQLITE_OMIT_EXPLAIN if( pParse->explain==2 ){ char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ", pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId ); sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); } #endif switch( pExpr->op ){ case TK_IN: { int addr; /* Address of OP_OpenEphemeral instruction */ Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */ KeyInfo *pKeyInfo = 0; /* Key information */ int nVal; /* Size of vector pLeft */ nVal = sqlite3ExprVectorSize(pLeft); assert( !isRowid || nVal==1 ); /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)' ** expression it is handled the same way. An ephemeral table is ** filled with index keys representing the results from the ** SELECT or the <exprlist>. ** ** If the 'x' expression is a column value, or the SELECT... ** statement returns a column value, then the affinity of that ** column is used to build the index keys. If both 'x' and the ** SELECT... statement are columns, then numeric affinity is used ** if either column has NUMERIC or INTEGER affinity. If neither ** 'x' nor the SELECT... statement are columns, then numeric affinity ** is used. */ pExpr->iTable = pParse->nTab++; addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, (isRowid?0:nVal)); pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ /* Case 1: expr IN (SELECT ...) ** ** Generate code to write the results of the select into the temporary ** table allocated and opened above. */ Select *pSelect = pExpr->x.pSelect; ExprList *pEList = pSelect->pEList; assert( !isRowid ); /* If the LHS and RHS of the IN operator do not match, that ** error will have been caught long before we reach this point. */ if( ALWAYS(pEList->nExpr==nVal) ){ SelectDest dest; int i; sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable); dest.zAffSdst = exprINAffinity(pParse, pExpr); assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); pSelect->iLimit = 0; testcase( pSelect->selFlags & SF_Distinct ); testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ if( sqlite3Select(pParse, pSelect, &dest) ){ sqlite3DbFree(pParse->db, dest.zAffSdst); sqlite3KeyInfoUnref(pKeyInfo); return 0; } sqlite3DbFree(pParse->db, dest.zAffSdst); assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ assert( pEList!=0 ); assert( pEList->nExpr>0 ); assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); for(i=0; i<nVal; i++){ Expr *p = sqlite3VectorFieldSubexpr(pLeft, i); pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq( pParse, p, pEList->a[i].pExpr ); } } }else if( ALWAYS(pExpr->x.pList!=0) ){ /* Case 2: expr IN (exprlist) ** ** For each expression, build an index key from the evaluation and ** store it in the temporary table. If <expr> is a column, then use ** that columns affinity when building index keys. If <expr> is not ** a column, use numeric affinity. */ char affinity; /* Affinity of the LHS of the IN */ int i; ExprList *pList = pExpr->x.pList; struct ExprList_item *pItem; int r1, r2, r3; affinity = sqlite3ExprAffinity(pLeft); if( !affinity ){ affinity = SQLITE_AFF_BLOB; } if( pKeyInfo ){ assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); } /* Loop through each expression in <exprlist>. */ r1 = sqlite3GetTempReg(pParse); r2 = sqlite3GetTempReg(pParse); if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2); for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ Expr *pE2 = pItem->pExpr; int iValToIns; /* If the expression is not constant then we will need to ** disable the test that was generated above that makes sure ** this code only executes once. Because for a non-constant ** expression we need to rerun this code each time. */ if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){ sqlite3VdbeChangeToNoop(v, jmpIfDynamic); jmpIfDynamic = -1; } /* Evaluate the expression and insert it into the temp table */ if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){ sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns); }else{ r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); if( isRowid ){ sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3); }else{ sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); sqlite3ExprCacheAffinityChange(pParse, r3, 1); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1); } } } sqlite3ReleaseTempReg(pParse, r1); sqlite3ReleaseTempReg(pParse, r2); } if( pKeyInfo ){ sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); } break; } case TK_EXISTS: case TK_SELECT: default: { /* Case 3: (SELECT ... FROM ...) ** or: EXISTS(SELECT ... FROM ...) ** ** For a SELECT, generate code to put the values for all columns of ** the first row into an array of registers and return the index of ** the first register. ** ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) ** into a register and return that register number. ** ** In both cases, the query is augmented with "LIMIT 1". Any ** preexisting limit is discarded in place of the new LIMIT 1. */ Select *pSel; /* SELECT statement to encode */ SelectDest dest; /* How to deal with SELECT result */ int nReg; /* Registers to allocate */ testcase( pExpr->op==TK_EXISTS ); testcase( pExpr->op==TK_SELECT ); assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); assert( ExprHasProperty(pExpr, EP_xIsSelect) ); pSel = pExpr->x.pSelect; nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; sqlite3SelectDestInit(&dest, 0, pParse->nMem+1); pParse->nMem += nReg; if( pExpr->op==TK_SELECT ){ dest.eDest = SRT_Mem; dest.iSdst = dest.iSDParm; dest.nSdst = nReg; sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); VdbeComment((v, "Init subquery result")); }else{ dest.eDest = SRT_Exists; sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); VdbeComment((v, "Init EXISTS result")); } sqlite3ExprDelete(pParse->db, pSel->pLimit); pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &sqlite3IntTokens[1], 0); pSel->iLimit = 0; pSel->selFlags &= ~SF_MultiValue; if( sqlite3Select(pParse, pSel, &dest) ){ return 0; } rReg = dest.iSDParm; ExprSetVVAProperty(pExpr, EP_NoReduce); break; } } if( rHasNullFlag ){ sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag); } if( jmpIfDynamic>=0 ){ sqlite3VdbeJumpHere(v, jmpIfDynamic); } sqlite3ExprCachePop(pParse); return rReg; } #endif /* SQLITE_OMIT_SUBQUERY */ #ifndef SQLITE_OMIT_SUBQUERY /* ** Expr pIn is an IN(...) expression. This function checks that the ** sub-select on the RHS of the IN() operator has the same number of ** columns as the vector on the LHS. Or, if the RHS of the IN() is not ** a sub-query, that the LHS is a vector of size 1. */ SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ int nVector = sqlite3ExprVectorSize(pIn->pLeft); if( (pIn->flags & EP_xIsSelect) ){ if( nVector!=pIn->x.pSelect->pEList->nExpr ){ sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); return 1; } }else if( nVector!=1 ){ sqlite3VectorErrorMsg(pParse, pIn->pLeft); return 1; } return 0; } #endif #ifndef SQLITE_OMIT_SUBQUERY /* ** Generate code for an IN expression. ** ** x IN (SELECT ...) ** x IN (value, value, ...) ** ** The left-hand side (LHS) is a scalar or vector expression. The ** right-hand side (RHS) is an array of zero or more scalar values, or a ** subquery. If the RHS is a subquery, the number of result columns must ** match the number of columns in the vector on the LHS. If the RHS is ** a list of values, the LHS must be a scalar. ** ** The IN operator is true if the LHS value is contained within the RHS. ** The result is false if the LHS is definitely not in the RHS. The ** result is NULL if the presence of the LHS in the RHS cannot be ** determined due to NULLs. ** ** This routine generates code that jumps to destIfFalse if the LHS is not ** contained within the RHS. If due to NULLs we cannot determine if the LHS ** is contained in the RHS then jump to destIfNull. If the LHS is contained ** within the RHS then fall through. ** ** See the separate in-operator.md documentation file in the canonical ** SQLite source tree for additional information. */ static void sqlite3ExprCodeIN( Parse *pParse, /* Parsing and code generating context */ Expr *pExpr, /* The IN expression */ int destIfFalse, /* Jump here if LHS is not contained in the RHS */ int destIfNull /* Jump here if the results are unknown due to NULLs */ ){ int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ int eType; /* Type of the RHS */ int rLhs; /* Register(s) holding the LHS values */ int rLhsOrig; /* LHS values prior to reordering by aiMap[] */ Vdbe *v; /* Statement under construction */ int *aiMap = 0; /* Map from vector field to index column */ char *zAff = 0; /* Affinity string for comparisons */ int nVector; /* Size of vectors for this IN operator */ int iDummy; /* Dummy parameter to exprCodeVector() */ Expr *pLeft; /* The LHS of the IN operator */ int i; /* loop counter */ int destStep2; /* Where to jump when NULLs seen in step 2 */ int destStep6 = 0; /* Start of code for Step 6 */ int addrTruthOp; /* Address of opcode that determines the IN is true */ int destNotNull; /* Jump here if a comparison is not true in step 6 */ int addrTop; /* Top of the step-6 loop */ pLeft = pExpr->pLeft; if( sqlite3ExprCheckIN(pParse, pExpr) ) return; zAff = exprINAffinity(pParse, pExpr); nVector = sqlite3ExprVectorSize(pExpr->pLeft); aiMap = (int*)sqlite3DbMallocZero( pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1 ); if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; /* Attempt to compute the RHS. After this step, if anything other than ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned, ** the RHS has not yet been coded. */ v = pParse->pVdbe; assert( v!=0 ); /* OOM detected prior to this routine */ VdbeNoopComment((v, "begin IN expr")); eType = sqlite3FindInIndex(pParse, pExpr, IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK, destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap); assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC ); #ifdef SQLITE_DEBUG /* Confirm that aiMap[] contains nVector integer values between 0 and ** nVector-1. */ for(i=0; i<nVector; i++){ int j, cnt; for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++; assert( cnt==1 ); } #endif /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a ** vector, then it is stored in an array of nVector registers starting ** at r1. ** ** sqlite3FindInIndex() might have reordered the fields of the LHS vector ** so that the fields are in the same order as an existing index. The ** aiMap[] array contains a mapping from the original LHS field order to ** the field order that matches the RHS index. */ sqlite3ExprCachePush(pParse); rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */ if( i==nVector ){ /* LHS fields are not reordered */ rLhs = rLhsOrig; }else{ /* Need to reorder the LHS fields according to aiMap */ rLhs = sqlite3GetTempRange(pParse, nVector); for(i=0; i<nVector; i++){ sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0); } } /* If sqlite3FindInIndex() did not find or create an index that is ** suitable for evaluating the IN operator, then evaluate using a ** sequence of comparisons. ** ** This is step (1) in the in-operator.md optimized algorithm. */ if( eType==IN_INDEX_NOOP ){ ExprList *pList = pExpr->x.pList; CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); int labelOk = sqlite3VdbeMakeLabel(v); int r2, regToFree; int regCkNull = 0; int ii; assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); if( destIfNull!=destIfFalse ){ regCkNull = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); } for(ii=0; ii<pList->nExpr; ii++){ r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree); if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); } if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){ sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2, (void*)pColl, P4_COLLSEQ); VdbeCoverageIf(v, ii<pList->nExpr-1); VdbeCoverageIf(v, ii==pList->nExpr-1); sqlite3VdbeChangeP5(v, zAff[0]); }else{ assert( destIfNull==destIfFalse ); sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2, (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); } sqlite3ReleaseTempReg(pParse, regToFree); } if( regCkNull ){ sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); sqlite3VdbeGoto(v, destIfFalse); } sqlite3VdbeResolveLabel(v, labelOk); sqlite3ReleaseTempReg(pParse, regCkNull); goto sqlite3ExprCodeIN_finished; } /* Step 2: Check to see if the LHS contains any NULL columns. If the ** LHS does contain NULLs then the result must be either FALSE or NULL. ** We will then skip the binary search of the RHS. */ if( destIfNull==destIfFalse ){ destStep2 = destIfFalse; }else{ destStep2 = destStep6 = sqlite3VdbeMakeLabel(v); } for(i=0; i<nVector; i++){ Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i); if( sqlite3ExprCanBeNull(p) ){ sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); VdbeCoverage(v); } } /* Step 3. The LHS is now known to be non-NULL. Do the binary search ** of the RHS using the LHS as a probe. If found, the result is ** true. */ if( eType==IN_INDEX_ROWID ){ /* In this case, the RHS is the ROWID of table b-tree and so we also ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 ** into a single opcode. */ sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs); VdbeCoverage(v); addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ }else{ sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); if( destIfFalse==destIfNull ){ /* Combine Step 3 and Step 5 into a single opcode */ sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, rLhs, nVector); VdbeCoverage(v); goto sqlite3ExprCodeIN_finished; } /* Ordinary Step 3, for the case where FALSE and NULL are distinct */ addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rLhs, nVector); VdbeCoverage(v); } /* Step 4. If the RHS is known to be non-NULL and we did not find ** an match on the search above, then the result must be FALSE. */ if( rRhsHasNull && nVector==1 ){ sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); VdbeCoverage(v); } /* Step 5. If we do not care about the difference between NULL and ** FALSE, then just return false. */ if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse); /* Step 6: Loop through rows of the RHS. Compare each row to the LHS. ** If any comparison is NULL, then the result is NULL. If all ** comparisons are FALSE then the final result is FALSE. ** ** For a scalar LHS, it is sufficient to check just the first row ** of the RHS. */ if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse); VdbeCoverage(v); if( nVector>1 ){ destNotNull = sqlite3VdbeMakeLabel(v); }else{ /* For nVector==1, combine steps 6 and 7 by immediately returning ** FALSE if the first comparison is not NULL */ destNotNull = destIfFalse; } for(i=0; i<nVector; i++){ Expr *p; CollSeq *pColl; int r3 = sqlite3GetTempReg(pParse); p = sqlite3VectorFieldSubexpr(pLeft, i); pColl = sqlite3ExprCollSeq(pParse, p); sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3); sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, r3); } sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); if( nVector>1 ){ sqlite3VdbeResolveLabel(v, destNotNull); sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1); VdbeCoverage(v); /* Step 7: If we reach this point, we know that the result must ** be false. */ sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); } /* Jumps here in order to return true. */ sqlite3VdbeJumpHere(v, addrTruthOp); sqlite3ExprCodeIN_finished: if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs); sqlite3ExprCachePop(pParse); VdbeComment((v, "end IN expr")); sqlite3ExprCodeIN_oom_error: sqlite3DbFree(pParse->db, aiMap); sqlite3DbFree(pParse->db, zAff); } #endif /* SQLITE_OMIT_SUBQUERY */ #ifndef SQLITE_OMIT_FLOATING_POINT /* ** Generate an instruction that will put the floating point ** value described by z[0..n-1] into register iMem. ** ** The z[] string will probably not be zero-terminated. But the ** z[n] character is guaranteed to be something that does not look ** like the continuation of the number. */ static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ if( ALWAYS(z!=0) ){ double value; sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ if( negateFlag ) value = -value; sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); } } #endif /* ** Generate an instruction that will put the integer describe by ** text z[0..n-1] into register iMem. ** ** Expr.u.zToken is always UTF8 and zero-terminated. */ static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ Vdbe *v = pParse->pVdbe; if( pExpr->flags & EP_IntValue ){ int i = pExpr->u.iValue; assert( i>=0 ); if( negFlag ) i = -i; sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); }else{ int c; i64 value; const char *z = pExpr->u.zToken; assert( z!=0 ); c = sqlite3DecOrHexToI64(z, &value); if( c==1 || (c==2 && !negFlag) || (negFlag && value==SMALLEST_INT64)){ #ifdef SQLITE_OMIT_FLOATING_POINT sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); #else #ifndef SQLITE_OMIT_HEX_INTEGER if( sqlite3_strnicmp(z,"0x",2)==0 ){ sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z); }else #endif { codeReal(v, z, negFlag, iMem); } #endif }else{ if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; } sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); } } } /* ** Erase column-cache entry number i */ static void cacheEntryClear(Parse *pParse, int i){ if( pParse->aColCache[i].tempReg ){ if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){ pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg; } } pParse->nColCache--; if( i<pParse->nColCache ){ pParse->aColCache[i] = pParse->aColCache[pParse->nColCache]; } } /* ** Record in the column cache that a particular column from a ** particular table is stored in a particular register. */ SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){ int i; int minLru; int idxLru; struct yColCache *p; /* Unless an error has occurred, register numbers are always positive. */ assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed ); assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */ /* The SQLITE_ColumnCache flag disables the column cache. This is used ** for testing only - to verify that SQLite always gets the same answer ** with and without the column cache. */ if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return; /* First replace any existing entry. ** ** Actually, the way the column cache is currently used, we are guaranteed ** that the object will never already be in cache. Verify this guarantee. */ #ifndef NDEBUG for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ assert( p->iTable!=iTab || p->iColumn!=iCol ); } #endif /* If the cache is already full, delete the least recently used entry */ if( pParse->nColCache>=SQLITE_N_COLCACHE ){ minLru = 0x7fffffff; idxLru = -1; for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ if( p->lru<minLru ){ idxLru = i; minLru = p->lru; } } p = &pParse->aColCache[idxLru]; }else{ p = &pParse->aColCache[pParse->nColCache++]; } /* Add the new entry to the end of the cache */ p->iLevel = pParse->iCacheLevel; p->iTable = iTab; p->iColumn = iCol; p->iReg = iReg; p->tempReg = 0; p->lru = pParse->iCacheCnt++; } /* ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten. ** Purge the range of registers from the column cache. */ SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){ int i = 0; while( i<pParse->nColCache ){ struct yColCache *p = &pParse->aColCache[i]; if( p->iReg >= iReg && p->iReg < iReg+nReg ){ cacheEntryClear(pParse, i); }else{ i++; } } } /* ** Remember the current column cache context. Any new entries added ** added to the column cache after this call are removed when the ** corresponding pop occurs. */ SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){ pParse->iCacheLevel++; #ifdef SQLITE_DEBUG if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ printf("PUSH to %d\n", pParse->iCacheLevel); } #endif } /* ** Remove from the column cache any entries that were added since the ** the previous sqlite3ExprCachePush operation. In other words, restore ** the cache to the state it was in prior the most recent Push. */ SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){ int i = 0; assert( pParse->iCacheLevel>=1 ); pParse->iCacheLevel--; #ifdef SQLITE_DEBUG if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ printf("POP to %d\n", pParse->iCacheLevel); } #endif while( i<pParse->nColCache ){ if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){ cacheEntryClear(pParse, i); }else{ i++; } } } /* ** When a cached column is reused, make sure that its register is ** no longer available as a temp register. ticket #3879: that same ** register might be in the cache in multiple places, so be sure to ** get them all. */ static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){ int i; struct yColCache *p; for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ if( p->iReg==iReg ){ p->tempReg = 0; } } } /* Generate code that will load into register regOut a value that is ** appropriate for the iIdxCol-th column of index pIdx. */ SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn( Parse *pParse, /* The parsing context */ Index *pIdx, /* The index whose column is to be loaded */ int iTabCur, /* Cursor pointing to a table row */ int iIdxCol, /* The column of the index to be loaded */ int regOut /* Store the index column value in this register */ ){ i16 iTabCol = pIdx->aiColumn[iIdxCol]; if( iTabCol==XN_EXPR ){ assert( pIdx->aColExpr ); assert( pIdx->aColExpr->nExpr>iIdxCol ); pParse->iSelfTab = iTabCur; sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); }else{ sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, iTabCol, regOut); } } /* ** Generate code to extract the value of the iCol-th column of a table. */ SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable( Vdbe *v, /* The VDBE under construction */ Table *pTab, /* The table containing the value */ int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ int iCol, /* Index of the column to extract */ int regOut /* Extract the value into this register */ ){ if( iCol<0 || iCol==pTab->iPKey ){ sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); }else{ int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; int x = iCol; if( !HasRowid(pTab) && !IsVirtual(pTab) ){ x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol); } sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); } if( iCol>=0 ){ sqlite3ColumnDefault(v, pTab, iCol, regOut); } } /* ** Generate code that will extract the iColumn-th column from ** table pTab and store the column value in a register. ** ** An effort is made to store the column value in register iReg. This ** is not garanteeed for GetColumn() - the result can be stored in ** any register. But the result is guaranteed to land in register iReg ** for GetColumnToReg(). ** ** There must be an open cursor to pTab in iTable when this routine ** is called. If iColumn<0 then code is generated that extracts the rowid. */ SQLITE_PRIVATE int sqlite3ExprCodeGetColumn( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Description of the table we are reading from */ int iColumn, /* Index of the table column */ int iTable, /* The cursor pointing to the table */ int iReg, /* Store results here */ u8 p5 /* P5 value for OP_Column + FLAGS */ ){ Vdbe *v = pParse->pVdbe; int i; struct yColCache *p; for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ if( p->iTable==iTable && p->iColumn==iColumn ){ p->lru = pParse->iCacheCnt++; sqlite3ExprCachePinRegister(pParse, p->iReg); return p->iReg; } } assert( v!=0 ); sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg); if( p5 ){ sqlite3VdbeChangeP5(v, p5); }else{ sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg); } return iReg; } SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Description of the table we are reading from */ int iColumn, /* Index of the table column */ int iTable, /* The cursor pointing to the table */ int iReg /* Store results here */ ){ int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0); if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg); } /* ** Clear all column cache entries. */ SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){ int i; #if SQLITE_DEBUG if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ printf("CLEAR\n"); } #endif for(i=0; i<pParse->nColCache; i++){ if( pParse->aColCache[i].tempReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){ pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg; } } pParse->nColCache = 0; } /* ** Record the fact that an affinity change has occurred on iCount ** registers starting with iStart. */ SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){ sqlite3ExprCacheRemove(pParse, iStart, iCount); } /* ** Generate code to move content from registers iFrom...iFrom+nReg-1 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. */ SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo ); sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); sqlite3ExprCacheRemove(pParse, iFrom, nReg); } #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) /* ** Return true if any register in the range iFrom..iTo (inclusive) ** is used as part of the column cache. ** ** This routine is used within assert() and testcase() macros only ** and does not appear in a normal build. */ static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){ int i; struct yColCache *p; for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ int r = p->iReg; if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/ } return 0; } #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */ /* ** Convert a scalar expression node to a TK_REGISTER referencing ** register iReg. The caller must ensure that iReg already contains ** the correct value for the expression. */ static void exprToRegister(Expr *p, int iReg){ p->op2 = p->op; p->op = TK_REGISTER; p->iTable = iReg; ExprClearProperty(p, EP_Skip); } /* ** Evaluate an expression (either a vector or a scalar expression) and store ** the result in continguous temporary registers. Return the index of ** the first register used to store the result. ** ** If the returned result register is a temporary scalar, then also write ** that register number into *piFreeable. If the returned result register ** is not a temporary or if the expression is a vector set *piFreeable ** to 0. */ static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ int iResult; int nResult = sqlite3ExprVectorSize(p); if( nResult==1 ){ iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable); }else{ *piFreeable = 0; if( p->op==TK_SELECT ){ iResult = sqlite3CodeSubselect(pParse, p, 0, 0); }else{ int i; iResult = pParse->nMem+1; pParse->nMem += nResult; for(i=0; i<nResult; i++){ sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult); } } } return iResult; } /* ** Generate code into the current Vdbe to evaluate the given ** expression. Attempt to store the results in register "target". ** Return the register where results are stored. ** ** With this routine, there is no guarantee that results will ** be stored in target. The result might be stored in some other ** register if it is convenient to do so. The calling function ** must check the return code and move the results to the desired ** register. */ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ Vdbe *v = pParse->pVdbe; /* The VM under construction */ int op; /* The opcode being coded */ int inReg = target; /* Results stored in register inReg */ int regFree1 = 0; /* If non-zero free this temporary register */ int regFree2 = 0; /* If non-zero free this temporary register */ int r1, r2; /* Various register numbers */ Expr tempX; /* Temporary expression node */ int p5 = 0; assert( target>0 && target<=pParse->nMem ); if( v==0 ){ assert( pParse->db->mallocFailed ); return 0; } if( pExpr==0 ){ op = TK_NULL; }else{ op = pExpr->op; } switch( op ){ case TK_AGG_COLUMN: { AggInfo *pAggInfo = pExpr->pAggInfo; struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; if( !pAggInfo->directMode ){ assert( pCol->iMem>0 ); return pCol->iMem; }else if( pAggInfo->useSortingIdx ){ sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, pCol->iSorterColumn, target); return target; } /* Otherwise, fall thru into the TK_COLUMN case */ } case TK_COLUMN: { int iTab = pExpr->iTable; if( iTab<0 ){ if( pParse->ckBase>0 ){ /* Generating CHECK constraints or inserting into partial index */ return pExpr->iColumn + pParse->ckBase; }else{ /* Coding an expression that is part of an index where column names ** in the index refer to the table to which the index belongs */ iTab = pParse->iSelfTab; } } return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab, pExpr->iColumn, iTab, target, pExpr->op2); } case TK_INTEGER: { codeInteger(pParse, pExpr, 0, target); return target; } #ifndef SQLITE_OMIT_FLOATING_POINT case TK_FLOAT: { assert( !ExprHasProperty(pExpr, EP_IntValue) ); codeReal(v, pExpr->u.zToken, 0, target); return target; } #endif case TK_STRING: { assert( !ExprHasProperty(pExpr, EP_IntValue) ); sqlite3VdbeLoadString(v, target, pExpr->u.zToken); return target; } case TK_NULL: { sqlite3VdbeAddOp2(v, OP_Null, 0, target); return target; } #ifndef SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: { int n; const char *z; char *zBlob; assert( !ExprHasProperty(pExpr, EP_IntValue) ); assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); assert( pExpr->u.zToken[1]=='\'' ); z = &pExpr->u.zToken[2]; n = sqlite3Strlen30(z) - 1; assert( z[n]=='\'' ); zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); return target; } #endif case TK_VARIABLE: { assert( !ExprHasProperty(pExpr, EP_IntValue) ); assert( pExpr->u.zToken!=0 ); assert( pExpr->u.zToken[0]!=0 ); sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); if( pExpr->u.zToken[1]!=0 ){ const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn); assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 ); pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */ sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC); } return target; } case TK_REGISTER: { return pExpr->iTable; } #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); if( inReg!=target ){ sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); inReg = target; } sqlite3VdbeAddOp2(v, OP_Cast, target, sqlite3AffinityType(pExpr->u.zToken, 0)); testcase( usedAsColumnCache(pParse, inReg, inReg) ); sqlite3ExprCacheAffinityChange(pParse, inReg, 1); return inReg; } #endif /* SQLITE_OMIT_CAST */ case TK_IS: case TK_ISNOT: op = (op==TK_IS) ? TK_EQ : TK_NE; p5 = SQLITE_NULLEQ; /* fall-through */ case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { Expr *pLeft = pExpr->pLeft; if( sqlite3ExprIsVector(pLeft) ){ codeVectorCompare(pParse, pExpr, target, op, p5); }else{ r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2, inReg, SQLITE_STOREP2 | p5); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); testcase( regFree1==0 ); testcase( regFree2==0 ); } break; } case TK_AND: case TK_OR: case TK_PLUS: case TK_STAR: case TK_MINUS: case TK_REM: case TK_BITAND: case TK_BITOR: case TK_SLASH: case TK_LSHIFT: case TK_RSHIFT: case TK_CONCAT: { assert( TK_AND==OP_And ); testcase( op==TK_AND ); assert( TK_OR==OP_Or ); testcase( op==TK_OR ); assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS ); assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS ); assert( TK_REM==OP_Remainder ); testcase( op==TK_REM ); assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND ); assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR ); assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH ); assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); sqlite3VdbeAddOp3(v, op, r2, r1, target); testcase( regFree1==0 ); testcase( regFree2==0 ); break; } case TK_UMINUS: { Expr *pLeft = pExpr->pLeft; assert( pLeft ); if( pLeft->op==TK_INTEGER ){ codeInteger(pParse, pLeft, 1, target); return target; #ifndef SQLITE_OMIT_FLOATING_POINT }else if( pLeft->op==TK_FLOAT ){ assert( !ExprHasProperty(pExpr, EP_IntValue) ); codeReal(v, pLeft->u.zToken, 1, target); return target; #endif }else{ tempX.op = TK_INTEGER; tempX.flags = EP_IntValue|EP_TokenOnly; tempX.u.iValue = 0; r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2); sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); testcase( regFree2==0 ); } break; } case TK_BITNOT: case TK_NOT: { assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT ); assert( TK_NOT==OP_Not ); testcase( op==TK_NOT ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); testcase( regFree1==0 ); sqlite3VdbeAddOp2(v, op, r1, inReg); break; } case TK_ISNULL: case TK_NOTNULL: { int addr; assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); sqlite3VdbeAddOp2(v, OP_Integer, 1, target); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); testcase( regFree1==0 ); addr = sqlite3VdbeAddOp1(v, op, r1); VdbeCoverageIf(v, op==TK_ISNULL); VdbeCoverageIf(v, op==TK_NOTNULL); sqlite3VdbeAddOp2(v, OP_Integer, 0, target); sqlite3VdbeJumpHere(v, addr); break; } case TK_AGG_FUNCTION: { AggInfo *pInfo = pExpr->pAggInfo; if( pInfo==0 ){ assert( !ExprHasProperty(pExpr, EP_IntValue) ); sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); }else{ return pInfo->aFunc[pExpr->iAgg].iMem; } break; } case TK_FUNCTION: { ExprList *pFarg; /* List of function arguments */ int nFarg; /* Number of function arguments */ FuncDef *pDef; /* The function definition object */ const char *zId; /* The function name */ u32 constMask = 0; /* Mask of function arguments that are constant */ int i; /* Loop counter */ sqlite3 *db = pParse->db; /* The database connection */ u8 enc = ENC(db); /* The text encoding used by this database */ CollSeq *pColl = 0; /* A collating sequence */ if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){ /* SQL functions can be expensive. So try to move constant functions ** out of the inner loop, even if that means an extra OP_Copy. */ return sqlite3ExprCodeAtInit(pParse, pExpr, -1); } assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); if( ExprHasProperty(pExpr, EP_TokenOnly) ){ pFarg = 0; }else{ pFarg = pExpr->x.pList; } nFarg = pFarg ? pFarg->nExpr : 0; assert( !ExprHasProperty(pExpr, EP_IntValue) ); zId = pExpr->u.zToken; pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0); #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION if( pDef==0 && pParse->explain ){ pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); } #endif if( pDef==0 || pDef->xFinalize!=0 ){ sqlite3ErrorMsg(pParse, "unknown function: %s()", zId); break; } /* Attempt a direct implementation of the built-in COALESCE() and ** IFNULL() functions. This avoids unnecessary evaluation of ** arguments past the first non-NULL argument. */ if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){ int endCoalesce = sqlite3VdbeMakeLabel(v); assert( nFarg>=2 ); sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); for(i=1; i<nFarg; i++){ sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce); VdbeCoverage(v); sqlite3ExprCacheRemove(pParse, target, 1); sqlite3ExprCachePush(pParse); sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target); sqlite3ExprCachePop(pParse); } sqlite3VdbeResolveLabel(v, endCoalesce); break; } /* The UNLIKELY() function is a no-op. The result is the value ** of the first argument. */ if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ assert( nFarg>=1 ); return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); } #ifdef SQLITE_DEBUG /* The AFFINITY() function evaluates to a string that describes ** the type affinity of the argument. This is used for testing of ** the SQLite type logic. */ if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){ const char *azAff[] = { "blob", "text", "numeric", "integer", "real" }; char aff; assert( nFarg==1 ); aff = sqlite3ExprAffinity(pFarg->a[0].pExpr); sqlite3VdbeLoadString(v, target, aff ? azAff[aff-SQLITE_AFF_BLOB] : "none"); return target; } #endif for(i=0; i<nFarg; i++){ if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){ testcase( i==31 ); constMask |= MASKBIT32(i); } if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); } } if( pFarg ){ if( constMask ){ r1 = pParse->nMem+1; pParse->nMem += nFarg; }else{ r1 = sqlite3GetTempRange(pParse, nFarg); } /* For length() and typeof() functions with a column argument, ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data ** loading. */ if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ u8 exprOp; assert( nFarg==1 ); assert( pFarg->a[0].pExpr!=0 ); exprOp = pFarg->a[0].pExpr->op; if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); testcase( pDef->funcFlags & OPFLAG_LENGTHARG ); pFarg->a[0].pExpr->op2 = pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG); } } sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */ sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR); sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */ }else{ r1 = 0; } #ifndef SQLITE_OMIT_VIRTUALTABLE /* Possibly overload the function if the first argument is ** a virtual table column. ** ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the ** second argument, not the first, as the argument to test to ** see if it is a column in a virtual table. This is done because ** the left operand of infix functions (the operand we want to ** control overloading) ends up as the second argument to the ** function. The expression "A glob B" is equivalent to ** "glob(B,A). We want to use the A in "A glob B" to test ** for function overloading. But we use the B term in "glob(B,A)". */ if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){ pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); }else if( nFarg>0 ){ pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); } #endif if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ if( !pColl ) pColl = db->pDfltColl; sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); } sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target, (char*)pDef, P4_FUNCDEF); sqlite3VdbeChangeP5(v, (u8)nFarg); if( nFarg && constMask==0 ){ sqlite3ReleaseTempRange(pParse, r1, nFarg); } return target; } #ifndef SQLITE_OMIT_SUBQUERY case TK_EXISTS: case TK_SELECT: { int nCol; testcase( op==TK_EXISTS ); testcase( op==TK_SELECT ); if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){ sqlite3SubselectError(pParse, nCol, 1); }else{ return sqlite3CodeSubselect(pParse, pExpr, 0, 0); } break; } case TK_SELECT_COLUMN: { int n; if( pExpr->pLeft->iTable==0 ){ pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0); } assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT ); if( pExpr->iTable && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft)) ){ sqlite3ErrorMsg(pParse, "%d columns assigned %d values", pExpr->iTable, n); } return pExpr->pLeft->iTable + pExpr->iColumn; } case TK_IN: { int destIfFalse = sqlite3VdbeMakeLabel(v); int destIfNull = sqlite3VdbeMakeLabel(v); sqlite3VdbeAddOp2(v, OP_Null, 0, target); sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); sqlite3VdbeAddOp2(v, OP_Integer, 1, target); sqlite3VdbeResolveLabel(v, destIfFalse); sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); sqlite3VdbeResolveLabel(v, destIfNull); return target; } #endif /* SQLITE_OMIT_SUBQUERY */ /* ** x BETWEEN y AND z ** ** This is equivalent to ** ** x>=y AND x<=z ** ** X is stored in pExpr->pLeft. ** Y is stored in pExpr->pList->a[0].pExpr. ** Z is stored in pExpr->pList->a[1].pExpr. */ case TK_BETWEEN: { exprCodeBetween(pParse, pExpr, target, 0, 0); return target; } case TK_SPAN: case TK_COLLATE: case TK_UPLUS: { return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); } case TK_TRIGGER: { /* If the opcode is TK_TRIGGER, then the expression is a reference ** to a column in the new.* or old.* pseudo-tables available to ** trigger programs. In this case Expr.iTable is set to 1 for the ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn ** is set to the column of the pseudo-table to read, or to -1 to ** read the rowid field. ** ** The expression is implemented using an OP_Param opcode. The p1 ** parameter is set to 0 for an old.rowid reference, or to (i+1) ** to reference another column of the old.* pseudo-table, where ** i is the index of the column. For a new.rowid reference, p1 is ** set to (n+1), where n is the number of columns in each pseudo-table. ** For a reference to any other column in the new.* pseudo-table, p1 ** is set to (n+2+i), where n and i are as defined previously. For ** example, if the table on which triggers are being fired is ** declared as: ** ** CREATE TABLE t1(a, b); ** ** Then p1 is interpreted as follows: ** ** p1==0 -> old.rowid p1==3 -> new.rowid ** p1==1 -> old.a p1==4 -> new.a ** p1==2 -> old.b p1==5 -> new.b */ Table *pTab = pExpr->pTab; int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn; assert( pExpr->iTable==0 || pExpr->iTable==1 ); assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol ); assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey ); assert( p1>=0 && p1<(pTab->nCol*2+2) ); sqlite3VdbeAddOp2(v, OP_Param, p1, target); VdbeComment((v, "%s.%s -> $%d", (pExpr->iTable ? "new" : "old"), (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName), target )); #ifndef SQLITE_OMIT_FLOATING_POINT /* If the column has REAL affinity, it may currently be stored as an ** integer. Use OP_RealAffinity to make sure it is really real. ** ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to ** floating point when extracting it from the record. */ if( pExpr->iColumn>=0 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL ){ sqlite3VdbeAddOp1(v, OP_RealAffinity, target); } #endif break; } case TK_VECTOR: { sqlite3ErrorMsg(pParse, "row value misused"); break; } /* ** Form A: ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END ** ** Form B: ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END ** ** Form A is can be transformed into the equivalent form B as follows: ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... ** WHEN x=eN THEN rN ELSE y END ** ** X (if it exists) is in pExpr->pLeft. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is ** odd. The Y is also optional. If the number of elements in x.pList ** is even, then Y is omitted and the "otherwise" result is NULL. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. ** ** The result of the expression is the Ri for the first matching Ei, ** or if there is no matching Ei, the ELSE term Y, or if there is ** no ELSE term, NULL. */ default: assert( op==TK_CASE ); { int endLabel; /* GOTO label for end of CASE stmt */ int nextCase; /* GOTO label for next WHEN clause */ int nExpr; /* 2x number of WHEN terms */ int i; /* Loop counter */ ExprList *pEList; /* List of WHEN terms */ struct ExprList_item *aListelem; /* Array of WHEN terms */ Expr opCompare; /* The X==Ei expression */ Expr *pX; /* The X expression */ Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; ) assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); assert(pExpr->x.pList->nExpr > 0); pEList = pExpr->x.pList; aListelem = pEList->a; nExpr = pEList->nExpr; endLabel = sqlite3VdbeMakeLabel(v); if( (pX = pExpr->pLeft)!=0 ){ tempX = *pX; testcase( pX->op==TK_COLUMN ); exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1)); testcase( regFree1==0 ); memset(&opCompare, 0, sizeof(opCompare)); opCompare.op = TK_EQ; opCompare.pLeft = &tempX; pTest = &opCompare; /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: ** The value in regFree1 might get SCopy-ed into the file result. ** So make sure that the regFree1 register is not reused for other ** purposes and possibly overwritten. */ regFree1 = 0; } for(i=0; i<nExpr-1; i=i+2){ sqlite3ExprCachePush(pParse); if( pX ){ assert( pTest!=0 ); opCompare.pRight = aListelem[i].pExpr; }else{ pTest = aListelem[i].pExpr; } nextCase = sqlite3VdbeMakeLabel(v); testcase( pTest->op==TK_COLUMN ); sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); sqlite3VdbeGoto(v, endLabel); sqlite3ExprCachePop(pParse); sqlite3VdbeResolveLabel(v, nextCase); } if( (nExpr&1)!=0 ){ sqlite3ExprCachePush(pParse); sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); sqlite3ExprCachePop(pParse); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, target); } assert( pParse->db->mallocFailed || pParse->nErr>0 || pParse->iCacheLevel==iCacheLevel ); sqlite3VdbeResolveLabel(v, endLabel); break; } #ifndef SQLITE_OMIT_TRIGGER case TK_RAISE: { assert( pExpr->affinity==OE_Rollback || pExpr->affinity==OE_Abort || pExpr->affinity==OE_Fail || pExpr->affinity==OE_Ignore ); if( !pParse->pTriggerTab ){ sqlite3ErrorMsg(pParse, "RAISE() may only be used within a trigger-program"); return 0; } if( pExpr->affinity==OE_Abort ){ sqlite3MayAbort(pParse); } assert( !ExprHasProperty(pExpr, EP_IntValue) ); if( pExpr->affinity==OE_Ignore ){ sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); VdbeCoverage(v); }else{ sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, pExpr->affinity, pExpr->u.zToken, 0, 0); } break; } #endif } sqlite3ReleaseTempReg(pParse, regFree1); sqlite3ReleaseTempReg(pParse, regFree2); return inReg; } /* ** Factor out the code of the given expression to initialization time. ** ** If regDest>=0 then the result is always stored in that register and the ** result is not reusable. If regDest<0 then this routine is free to ** store the value whereever it wants. The register where the expression ** is stored is returned. When regDest<0, two identical expressions will ** code to the same register. */ SQLITE_PRIVATE int sqlite3ExprCodeAtInit( Parse *pParse, /* Parsing context */ Expr *pExpr, /* The expression to code when the VDBE initializes */ int regDest /* Store the value in this register */ ){ ExprList *p; assert( ConstFactorOk(pParse) ); p = pParse->pConstExpr; if( regDest<0 && p ){ struct ExprList_item *pItem; int i; for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){ return pItem->u.iConstExprReg; } } } pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); p = sqlite3ExprListAppend(pParse, p, pExpr); if( p ){ struct ExprList_item *pItem = &p->a[p->nExpr-1]; pItem->reusable = regDest<0; if( regDest<0 ) regDest = ++pParse->nMem; pItem->u.iConstExprReg = regDest; } pParse->pConstExpr = p; return regDest; } /* ** Generate code to evaluate an expression and store the results ** into a register. Return the register number where the results ** are stored. ** ** If the register is a temporary register that can be deallocated, ** then write its number into *pReg. If the result register is not ** a temporary, then set *pReg to zero. ** ** If pExpr is a constant, then this routine might generate this ** code to fill the register in the initialization section of the ** VDBE program, in order to factor it out of the evaluation loop. */ SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ int r2; pExpr = sqlite3ExprSkipCollate(pExpr); if( ConstFactorOk(pParse) && pExpr->op!=TK_REGISTER && sqlite3ExprIsConstantNotJoin(pExpr) ){ *pReg = 0; r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1); }else{ int r1 = sqlite3GetTempReg(pParse); r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); if( r2==r1 ){ *pReg = r1; }else{ sqlite3ReleaseTempReg(pParse, r1); *pReg = 0; } } return r2; } /* ** Generate code that will evaluate expression pExpr and store the ** results in register target. The results are guaranteed to appear ** in register target. */ SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ int inReg; assert( target>0 && target<=pParse->nMem ); if( pExpr && pExpr->op==TK_REGISTER ){ sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target); }else{ inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); if( inReg!=target && pParse->pVdbe ){ sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target); } } } /* ** Make a transient copy of expression pExpr and then code it using ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode() ** except that the input expression is guaranteed to be unchanged. */ SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ sqlite3 *db = pParse->db; pExpr = sqlite3ExprDup(db, pExpr, 0); if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target); sqlite3ExprDelete(db, pExpr); } /* ** Generate code that will evaluate expression pExpr and store the ** results in register target. The results are guaranteed to appear ** in register target. If the expression is constant, then this routine ** might choose to code the expression at initialization time. */ SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){ sqlite3ExprCodeAtInit(pParse, pExpr, target); }else{ sqlite3ExprCode(pParse, pExpr, target); } } /* ** Generate code that evaluates the given expression and puts the result ** in register target. ** ** Also make a copy of the expression results into another "cache" register ** and modify the expression so that the next time it is evaluated, ** the result is a copy of the cache register. ** ** This routine is used for expressions that are used multiple ** times. They are evaluated once and the results of the expression ** are reused. */ SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ Vdbe *v = pParse->pVdbe; int iMem; assert( target>0 ); assert( pExpr->op!=TK_REGISTER ); sqlite3ExprCode(pParse, pExpr, target); iMem = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Copy, target, iMem); exprToRegister(pExpr, iMem); } /* ** Generate code that pushes the value of every element of the given ** expression list into a sequence of registers beginning at target. ** ** Return the number of elements evaluated. ** ** The SQLITE_ECEL_DUP flag prevents the arguments from being ** filled using OP_SCopy. OP_Copy must be used instead. ** ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be ** factored out into initialization code. ** ** The SQLITE_ECEL_REF flag means that expressions in the list with ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored ** in registers at srcReg, and so the value can be copied from there. */ SQLITE_PRIVATE int sqlite3ExprCodeExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* The expression list to be coded */ int target, /* Where to write results */ int srcReg, /* Source registers if SQLITE_ECEL_REF */ u8 flags /* SQLITE_ECEL_* flags */ ){ struct ExprList_item *pItem; int i, j, n; u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy; Vdbe *v = pParse->pVdbe; assert( pList!=0 ); assert( target>0 ); assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ n = pList->nExpr; if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR; for(pItem=pList->a, i=0; i<n; i++, pItem++){ Expr *pExpr = pItem->pExpr; if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){ if( flags & SQLITE_ECEL_OMITREF ){ i--; n--; }else{ sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); } }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){ sqlite3ExprCodeAtInit(pParse, pExpr, target+i); }else{ int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); if( inReg!=target+i ){ VdbeOp *pOp; if( copyOp==OP_Copy && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy && pOp->p1+pOp->p3+1==inReg && pOp->p2+pOp->p3+1==target+i ){ pOp->p3++; }else{ sqlite3VdbeAddOp2(v, copyOp, inReg, target+i); } } } } return n; } /* ** Generate code for a BETWEEN operator. ** ** x BETWEEN y AND z ** ** The above is equivalent to ** ** x>=y AND x<=z ** ** Code it as such, taking care to do the common subexpression ** elimination of x. ** ** The xJumpIf parameter determines details: ** ** NULL: Store the boolean result in reg[dest] ** sqlite3ExprIfTrue: Jump to dest if true ** sqlite3ExprIfFalse: Jump to dest if false ** ** The jumpIfNull parameter is ignored if xJumpIf is NULL. */ static void exprCodeBetween( Parse *pParse, /* Parsing and code generating context */ Expr *pExpr, /* The BETWEEN expression */ int dest, /* Jump destination or storage location */ void (*xJump)(Parse*,Expr*,int,int), /* Action to take */ int jumpIfNull /* Take the jump if the BETWEEN is NULL */ ){ Expr exprAnd; /* The AND operator in x>=y AND x<=z */ Expr compLeft; /* The x>=y term */ Expr compRight; /* The x<=z term */ Expr exprX; /* The x subexpression */ int regFree1 = 0; /* Temporary use register */ memset(&compLeft, 0, sizeof(Expr)); memset(&compRight, 0, sizeof(Expr)); memset(&exprAnd, 0, sizeof(Expr)); assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); exprX = *pExpr->pLeft; exprAnd.op = TK_AND; exprAnd.pLeft = &compLeft; exprAnd.pRight = &compRight; compLeft.op = TK_GE; compLeft.pLeft = &exprX; compLeft.pRight = pExpr->x.pList->a[0].pExpr; compRight.op = TK_LE; compRight.pLeft = &exprX; compRight.pRight = pExpr->x.pList->a[1].pExpr; exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1)); if( xJump ){ xJump(pParse, &exprAnd, dest, jumpIfNull); }else{ /* Mark the expression is being from the ON or USING clause of a join ** so that the sqlite3ExprCodeTarget() routine will not attempt to move ** it into the Parse.pConstExpr list. We should use a new bit for this, ** for clarity, but we are out of bits in the Expr.flags field so we ** have to reuse the EP_FromJoin bit. Bummer. */ exprX.flags |= EP_FromJoin; sqlite3ExprCodeTarget(pParse, &exprAnd, dest); } sqlite3ReleaseTempReg(pParse, regFree1); /* Ensure adequate test coverage */ testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); testcase( xJump==0 ); } /* ** Generate code for a boolean expression such that a jump is made ** to the label "dest" if the expression is true but execution ** continues straight thru if the expression is false. ** ** If the expression evaluates to NULL (neither true nor false), then ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. ** ** This code depends on the fact that certain token values (ex: TK_EQ) ** are the same as opcode values (ex: OP_Eq) that implement the corresponding ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in ** the make process cause these values to align. Assert()s in the code ** below verify that the numbers are aligned correctly. */ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; int regFree1 = 0; int regFree2 = 0; int r1, r2; assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ if( NEVER(pExpr==0) ) return; /* No way this can happen */ op = pExpr->op; switch( op ){ case TK_AND: { int d2 = sqlite3VdbeMakeLabel(v); testcase( jumpIfNull==0 ); sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); sqlite3ExprCachePush(pParse); sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3VdbeResolveLabel(v, d2); sqlite3ExprCachePop(pParse); break; } case TK_OR: { testcase( jumpIfNull==0 ); sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); sqlite3ExprCachePush(pParse); sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3ExprCachePop(pParse); break; } case TK_NOT: { testcase( jumpIfNull==0 ); sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); break; } case TK_IS: case TK_ISNOT: testcase( op==TK_IS ); testcase( op==TK_ISNOT ); op = (op==TK_IS) ? TK_EQ : TK_NE; jumpIfNull = SQLITE_NULLEQ; /* Fall thru */ case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; testcase( jumpIfNull==0 ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, r1, r2, dest, jumpIfNull); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); testcase( regFree1==0 ); testcase( regFree2==0 ); break; } case TK_ISNULL: case TK_NOTNULL: { assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); sqlite3VdbeAddOp2(v, op, r1, dest); VdbeCoverageIf(v, op==TK_ISNULL); VdbeCoverageIf(v, op==TK_NOTNULL); testcase( regFree1==0 ); break; } case TK_BETWEEN: { testcase( jumpIfNull==0 ); exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull); break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_IN: { int destIfFalse = sqlite3VdbeMakeLabel(v); int destIfNull = jumpIfNull ? dest : destIfFalse; sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); sqlite3VdbeGoto(v, dest); sqlite3VdbeResolveLabel(v, destIfFalse); break; } #endif default: { default_expr: if( exprAlwaysTrue(pExpr) ){ sqlite3VdbeGoto(v, dest); }else if( exprAlwaysFalse(pExpr) ){ /* No-op */ }else{ r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1); sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); VdbeCoverage(v); testcase( regFree1==0 ); testcase( jumpIfNull==0 ); } break; } } sqlite3ReleaseTempReg(pParse, regFree1); sqlite3ReleaseTempReg(pParse, regFree2); } /* ** Generate code for a boolean expression such that a jump is made ** to the label "dest" if the expression is false but execution ** continues straight thru if the expression is true. ** ** If the expression evaluates to NULL (neither true nor false) then ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull ** is 0. */ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; int regFree1 = 0; int regFree2 = 0; int r1, r2; assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ if( pExpr==0 ) return; /* The value of pExpr->op and op are related as follows: ** ** pExpr->op op ** --------- ---------- ** TK_ISNULL OP_NotNull ** TK_NOTNULL OP_IsNull ** TK_NE OP_Eq ** TK_EQ OP_Ne ** TK_GT OP_Le ** TK_LE OP_Gt ** TK_GE OP_Lt ** TK_LT OP_Ge ** ** For other values of pExpr->op, op is undefined and unused. ** The value of TK_ and OP_ constants are arranged such that we ** can compute the mapping above using the following expression. ** Assert()s verify that the computation is correct. */ op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); /* Verify correct alignment of TK_ and OP_ constants */ assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); assert( pExpr->op!=TK_NE || op==OP_Eq ); assert( pExpr->op!=TK_EQ || op==OP_Ne ); assert( pExpr->op!=TK_LT || op==OP_Ge ); assert( pExpr->op!=TK_LE || op==OP_Gt ); assert( pExpr->op!=TK_GT || op==OP_Le ); assert( pExpr->op!=TK_GE || op==OP_Lt ); switch( pExpr->op ){ case TK_AND: { testcase( jumpIfNull==0 ); sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); sqlite3ExprCachePush(pParse); sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3ExprCachePop(pParse); break; } case TK_OR: { int d2 = sqlite3VdbeMakeLabel(v); testcase( jumpIfNull==0 ); sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); sqlite3ExprCachePush(pParse); sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3VdbeResolveLabel(v, d2); sqlite3ExprCachePop(pParse); break; } case TK_NOT: { testcase( jumpIfNull==0 ); sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); break; } case TK_IS: case TK_ISNOT: testcase( pExpr->op==TK_IS ); testcase( pExpr->op==TK_ISNOT ); op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; jumpIfNull = SQLITE_NULLEQ; /* Fall thru */ case TK_LT: case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; testcase( jumpIfNull==0 ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, r1, r2, dest, jumpIfNull); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); testcase( regFree1==0 ); testcase( regFree2==0 ); break; } case TK_ISNULL: case TK_NOTNULL: { r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); sqlite3VdbeAddOp2(v, op, r1, dest); testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); testcase( regFree1==0 ); break; } case TK_BETWEEN: { testcase( jumpIfNull==0 ); exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull); break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_IN: { if( jumpIfNull ){ sqlite3ExprCodeIN(pParse, pExpr, dest, dest); }else{ int destIfNull = sqlite3VdbeMakeLabel(v); sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); sqlite3VdbeResolveLabel(v, destIfNull); } break; } #endif default: { default_expr: if( exprAlwaysFalse(pExpr) ){ sqlite3VdbeGoto(v, dest); }else if( exprAlwaysTrue(pExpr) ){ /* no-op */ }else{ r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1); sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); VdbeCoverage(v); testcase( regFree1==0 ); testcase( jumpIfNull==0 ); } break; } } sqlite3ReleaseTempReg(pParse, regFree1); sqlite3ReleaseTempReg(pParse, regFree2); } /* ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before ** code generation, and that copy is deleted after code generation. This ** ensures that the original pExpr is unchanged. */ SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ sqlite3 *db = pParse->db; Expr *pCopy = sqlite3ExprDup(db, pExpr, 0); if( db->mallocFailed==0 ){ sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); } sqlite3ExprDelete(db, pCopy); } /* ** Do a deep comparison of two expression trees. Return 0 if the two ** expressions are completely identical. Return 1 if they differ only ** by a COLLATE operator at the top level. Return 2 if there are differences ** other than the top-level COLLATE operator. ** ** If any subelement of pB has Expr.iTable==(-1) then it is allowed ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. ** ** The pA side might be using TK_REGISTER. If that is the case and pB is ** not using TK_REGISTER but is otherwise equivalent, then still return 0. ** ** Sometimes this routine will return 2 even if the two expressions ** really are equivalent. If we cannot prove that the expressions are ** identical, we return 2 just to be safe. So if this routine ** returns 2, then you do not really know for certain if the two ** expressions are the same. But if you get a 0 or 1 return, then you ** can be sure the expressions are the same. In the places where ** this routine is used, it does not hurt to get an extra 2 - that ** just might result in some slightly slower code. But returning ** an incorrect 0 or 1 could lead to a malfunction. */ SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){ u32 combinedFlags; if( pA==0 || pB==0 ){ return pB==pA ? 0 : 2; } combinedFlags = pA->flags | pB->flags; if( combinedFlags & EP_IntValue ){ if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){ return 0; } return 2; } if( pA->op!=pB->op ){ if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){ return 1; } if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){ return 1; } return 2; } if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){ if( pA->op==TK_FUNCTION ){ if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ return pA->op==TK_COLLATE ? 1 : 2; } } if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2; if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){ if( combinedFlags & EP_xIsSelect ) return 2; if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2; if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2; if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){ if( pA->iColumn!=pB->iColumn ) return 2; if( pA->iTable!=pB->iTable && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2; } } return 0; } /* ** Compare two ExprList objects. Return 0 if they are identical and ** non-zero if they differ in any way. ** ** If any subelement of pB has Expr.iTable==(-1) then it is allowed ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. ** ** This routine might return non-zero for equivalent ExprLists. The ** only consequence will be disabled optimizations. But this routine ** must never return 0 if the two ExprList objects are different, or ** a malfunction will result. ** ** Two NULL pointers are considered to be the same. But a NULL pointer ** always differs from a non-NULL pointer. */ SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ int i; if( pA==0 && pB==0 ) return 0; if( pA==0 || pB==0 ) return 1; if( pA->nExpr!=pB->nExpr ) return 1; for(i=0; i<pA->nExpr; i++){ Expr *pExprA = pA->a[i].pExpr; Expr *pExprB = pB->a[i].pExpr; if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1; if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1; } return 0; } /* ** Return true if we can prove the pE2 will always be true if pE1 is ** true. Return false if we cannot complete the proof or if pE2 might ** be false. Examples: ** ** pE1: x==5 pE2: x==5 Result: true ** pE1: x>0 pE2: x==5 Result: false ** pE1: x=21 pE2: x=21 OR y=43 Result: true ** pE1: x!=123 pE2: x IS NOT NULL Result: true ** pE1: x!=?1 pE2: x IS NOT NULL Result: true ** pE1: x IS NULL pE2: x IS NOT NULL Result: false ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false ** ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has ** Expr.iTable<0 then assume a table number given by iTab. ** ** When in doubt, return false. Returning true might give a performance ** improvement. Returning false might cause a performance reduction, but ** it will always give the correct answer and is hence always safe. */ SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){ if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){ return 1; } if( pE2->op==TK_OR && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab) || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) ) ){ return 1; } if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){ Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft); testcase( pX!=pE1->pLeft ); if( sqlite3ExprCompare(pX, pE2->pLeft, iTab)==0 ) return 1; } return 0; } /* ** An instance of the following structure is used by the tree walker ** to determine if an expression can be evaluated by reference to the ** index only, without having to do a search for the corresponding ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur ** is the cursor for the table. */ struct IdxCover { Index *pIdx; /* The index to be tested for coverage */ int iCur; /* Cursor number for the table corresponding to the index */ }; /* ** Check to see if there are references to columns in table ** pWalker->u.pIdxCover->iCur can be satisfied using the index ** pWalker->u.pIdxCover->pIdx. */ static int exprIdxCover(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_COLUMN && pExpr->iTable==pWalker->u.pIdxCover->iCur && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 ){ pWalker->eCode = 1; return WRC_Abort; } return WRC_Continue; } /* ** Determine if an index pIdx on table with cursor iCur contains will ** the expression pExpr. Return true if the index does cover the ** expression and false if the pExpr expression references table columns ** that are not found in the index pIdx. ** ** An index covering an expression means that the expression can be ** evaluated using only the index and without having to lookup the ** corresponding table entry. */ SQLITE_PRIVATE int sqlite3ExprCoveredByIndex( Expr *pExpr, /* The index to be tested */ int iCur, /* The cursor number for the corresponding table */ Index *pIdx /* The index that might be used for coverage */ ){ Walker w; struct IdxCover xcov; memset(&w, 0, sizeof(w)); xcov.iCur = iCur; xcov.pIdx = pIdx; w.xExprCallback = exprIdxCover; w.u.pIdxCover = &xcov; sqlite3WalkExpr(&w, pExpr); return !w.eCode; } /* ** An instance of the following structure is used by the tree walker ** to count references to table columns in the arguments of an ** aggregate function, in order to implement the ** sqlite3FunctionThisSrc() routine. */ struct SrcCount { SrcList *pSrc; /* One particular FROM clause in a nested query */ int nThis; /* Number of references to columns in pSrcList */ int nOther; /* Number of references to columns in other FROM clauses */ }; /* ** Count the number of references to columns. */ static int exprSrcCount(Walker *pWalker, Expr *pExpr){ /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc() ** is always called before sqlite3ExprAnalyzeAggregates() and so the ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If ** sqlite3FunctionUsesThisSrc() is used differently in the future, the ** NEVER() will need to be removed. */ if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){ int i; struct SrcCount *p = pWalker->u.pSrcCount; SrcList *pSrc = p->pSrc; int nSrc = pSrc ? pSrc->nSrc : 0; for(i=0; i<nSrc; i++){ if( pExpr->iTable==pSrc->a[i].iCursor ) break; } if( i<nSrc ){ p->nThis++; }else{ p->nOther++; } } return WRC_Continue; } /* ** Determine if any of the arguments to the pExpr Function reference ** pSrcList. Return true if they do. Also return true if the function ** has no arguments or has only constant arguments. Return false if pExpr ** references columns but not columns of tables found in pSrcList. */ SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ Walker w; struct SrcCount cnt; assert( pExpr->op==TK_AGG_FUNCTION ); memset(&w, 0, sizeof(w)); w.xExprCallback = exprSrcCount; w.u.pSrcCount = &cnt; cnt.pSrc = pSrcList; cnt.nThis = 0; cnt.nOther = 0; sqlite3WalkExprList(&w, pExpr->x.pList); return cnt.nThis>0 || cnt.nOther==0; } /* ** Add a new element to the pAggInfo->aCol[] array. Return the index of ** the new element. Return a negative number if malloc fails. */ static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ int i; pInfo->aCol = sqlite3ArrayAllocate( db, pInfo->aCol, sizeof(pInfo->aCol[0]), &pInfo->nColumn, &i ); return i; } /* ** Add a new element to the pAggInfo->aFunc[] array. Return the index of ** the new element. Return a negative number if malloc fails. */ static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ int i; pInfo->aFunc = sqlite3ArrayAllocate( db, pInfo->aFunc, sizeof(pInfo->aFunc[0]), &pInfo->nFunc, &i ); return i; } /* ** This is the xExprCallback for a tree walker. It is used to ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates ** for additional information. */ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ int i; NameContext *pNC = pWalker->u.pNC; Parse *pParse = pNC->pParse; SrcList *pSrcList = pNC->pSrcList; AggInfo *pAggInfo = pNC->pAggInfo; switch( pExpr->op ){ case TK_AGG_COLUMN: case TK_COLUMN: { testcase( pExpr->op==TK_AGG_COLUMN ); testcase( pExpr->op==TK_COLUMN ); /* Check to see if the column is in one of the tables in the FROM ** clause of the aggregate query */ if( ALWAYS(pSrcList!=0) ){ struct SrcList_item *pItem = pSrcList->a; for(i=0; i<pSrcList->nSrc; i++, pItem++){ struct AggInfo_col *pCol; assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); if( pExpr->iTable==pItem->iCursor ){ /* If we reach this point, it means that pExpr refers to a table ** that is in the FROM clause of the aggregate query. ** ** Make an entry for the column in pAggInfo->aCol[] if there ** is not an entry there already. */ int k; pCol = pAggInfo->aCol; for(k=0; k<pAggInfo->nColumn; k++, pCol++){ if( pCol->iTable==pExpr->iTable && pCol->iColumn==pExpr->iColumn ){ break; } } if( (k>=pAggInfo->nColumn) && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 ){ pCol = &pAggInfo->aCol[k]; pCol->pTab = pExpr->pTab; pCol->iTable = pExpr->iTable; pCol->iColumn = pExpr->iColumn; pCol->iMem = ++pParse->nMem; pCol->iSorterColumn = -1; pCol->pExpr = pExpr; if( pAggInfo->pGroupBy ){ int j, n; ExprList *pGB = pAggInfo->pGroupBy; struct ExprList_item *pTerm = pGB->a; n = pGB->nExpr; for(j=0; j<n; j++, pTerm++){ Expr *pE = pTerm->pExpr; if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && pE->iColumn==pExpr->iColumn ){ pCol->iSorterColumn = j; break; } } } if( pCol->iSorterColumn<0 ){ pCol->iSorterColumn = pAggInfo->nSortingColumn++; } } /* There is now an entry for pExpr in pAggInfo->aCol[] (either ** because it was there before or because we just created it). ** Convert the pExpr to be a TK_AGG_COLUMN referring to that ** pAggInfo->aCol[] entry. */ ExprSetVVAProperty(pExpr, EP_NoReduce); pExpr->pAggInfo = pAggInfo; pExpr->op = TK_AGG_COLUMN; pExpr->iAgg = (i16)k; break; } /* endif pExpr->iTable==pItem->iCursor */ } /* end loop over pSrcList */ } return WRC_Prune; } case TK_AGG_FUNCTION: { if( (pNC->ncFlags & NC_InAggFunc)==0 && pWalker->walkerDepth==pExpr->op2 ){ /* Check to see if pExpr is a duplicate of another aggregate ** function that is already in the pAggInfo structure */ struct AggInfo_func *pItem = pAggInfo->aFunc; for(i=0; i<pAggInfo->nFunc; i++, pItem++){ if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){ break; } } if( i>=pAggInfo->nFunc ){ /* pExpr is original. Make a new entry in pAggInfo->aFunc[] */ u8 enc = ENC(pParse->db); i = addAggInfoFunc(pParse->db, pAggInfo); if( i>=0 ){ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); pItem = &pAggInfo->aFunc[i]; pItem->pExpr = pExpr; pItem->iMem = ++pParse->nMem; assert( !ExprHasProperty(pExpr, EP_IntValue) ); pItem->pFunc = sqlite3FindFunction(pParse->db, pExpr->u.zToken, pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); if( pExpr->flags & EP_Distinct ){ pItem->iDistinct = pParse->nTab++; }else{ pItem->iDistinct = -1; } } } /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(pExpr, EP_NoReduce); pExpr->iAgg = (i16)i; pExpr->pAggInfo = pAggInfo; return WRC_Prune; }else{ return WRC_Continue; } } } return WRC_Continue; } static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ UNUSED_PARAMETER(pWalker); UNUSED_PARAMETER(pSelect); return WRC_Continue; } /* ** Analyze the pExpr expression looking for aggregate functions and ** for variables that need to be added to AggInfo object that pNC->pAggInfo ** points to. Additional entries are made on the AggInfo object as ** necessary. ** ** This routine should only be called after the expression has been ** analyzed by sqlite3ResolveExprNames(). */ SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ Walker w; memset(&w, 0, sizeof(w)); w.xExprCallback = analyzeAggregate; w.xSelectCallback = analyzeAggregatesInSelect; w.u.pNC = pNC; assert( pNC->pSrcList!=0 ); sqlite3WalkExpr(&w, pExpr); } /* ** Call sqlite3ExprAnalyzeAggregates() for every expression in an ** expression list. Return the number of errors. ** ** If an error is found, the analysis is cut short. */ SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ struct ExprList_item *pItem; int i; if( pList ){ for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); } } } /* ** Allocate a single new register for use to hold some intermediate result. */ SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ if( pParse->nTempReg==0 ){ return ++pParse->nMem; } return pParse->aTempReg[--pParse->nTempReg]; } /* ** Deallocate a register, making available for reuse for some other ** purpose. ** ** If a register is currently being used by the column cache, then ** the deallocation is deferred until the column cache line that uses ** the register becomes stale. */ SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){ int i; struct yColCache *p; for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ if( p->iReg==iReg ){ p->tempReg = 1; return; } } pParse->aTempReg[pParse->nTempReg++] = iReg; } } /* ** Allocate or deallocate a block of nReg consecutive registers. */ SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){ int i, n; if( nReg==1 ) return sqlite3GetTempReg(pParse); i = pParse->iRangeReg; n = pParse->nRangeReg; if( nReg<=n ){ assert( !usedAsColumnCache(pParse, i, i+n-1) ); pParse->iRangeReg += nReg; pParse->nRangeReg -= nReg; }else{ i = pParse->nMem+1; pParse->nMem += nReg; } return i; } SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ if( nReg==1 ){ sqlite3ReleaseTempReg(pParse, iReg); return; } sqlite3ExprCacheRemove(pParse, iReg, nReg); if( nReg>pParse->nRangeReg ){ pParse->nRangeReg = nReg; pParse->iRangeReg = iReg; } } /* ** Mark all temporary registers as being unavailable for reuse. */ SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){ pParse->nTempReg = 0; pParse->nRangeReg = 0; } /* ** Validate that no temporary register falls within the range of ** iFirst..iLast, inclusive. This routine is only call from within assert() ** statements. */ #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ int i; if( pParse->nRangeReg>0 && pParse->iRangeReg+pParse->nRangeReg<iLast && pParse->iRangeReg>=iFirst ){ return 0; } for(i=0; i<pParse->nTempReg; i++){ if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){ return 0; } } return 1; } #endif /* SQLITE_DEBUG */ /************** End of expr.c ************************************************/ /************** Begin file alter.c *******************************************/ /* ** 2005 February 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that used to generate VDBE code ** that implements the ALTER TABLE command. */ /* #include "sqliteInt.h" */ /* ** The code in this file only exists if we are not omitting the ** ALTER TABLE logic from the build. */ #ifndef SQLITE_OMIT_ALTERTABLE /* ** This function is used by SQL generated to implement the ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or ** CREATE INDEX command. The second is a table name. The table name in ** the CREATE TABLE or CREATE INDEX statement is replaced with the third ** argument and the result returned. Examples: ** ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') ** -> 'CREATE TABLE def(a, b, c)' ** ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') ** -> 'CREATE INDEX i ON def(a, b, c)' */ static void renameTableFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ unsigned char const *zSql = sqlite3_value_text(argv[0]); unsigned char const *zTableName = sqlite3_value_text(argv[1]); int token; Token tname; unsigned char const *zCsr = zSql; int len = 0; char *zRet; sqlite3 *db = sqlite3_context_db_handle(context); UNUSED_PARAMETER(NotUsed); /* The principle used to locate the table name in the CREATE TABLE ** statement is that the table name is the first non-space token that ** is immediately followed by a TK_LP or TK_USING token. */ if( zSql ){ do { if( !*zCsr ){ /* Ran out of input before finding an opening bracket. Return NULL. */ return; } /* Store the token that zCsr points to in tname. */ tname.z = (char*)zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = sqlite3GetToken(zCsr, &token); } while( token==TK_SPACE ); assert( len>0 ); } while( token!=TK_LP && token!=TK_USING ); zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql), zSql, zTableName, tname.z+tname.n); sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); } } /* ** This C function implements an SQL user function that is used by SQL code ** generated by the ALTER TABLE ... RENAME command to modify the definition ** of any foreign key constraints that use the table being renamed as the ** parent table. It is passed three arguments: ** ** 1) The complete text of the CREATE TABLE statement being modified, ** 2) The old name of the table being renamed, and ** 3) The new name of the table being renamed. ** ** It returns the new CREATE TABLE statement. For example: ** ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3') ** -> 'CREATE TABLE t1(a REFERENCES t3)' */ #ifndef SQLITE_OMIT_FOREIGN_KEY static void renameParentFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ sqlite3 *db = sqlite3_context_db_handle(context); char *zOutput = 0; char *zResult; unsigned char const *zInput = sqlite3_value_text(argv[0]); unsigned char const *zOld = sqlite3_value_text(argv[1]); unsigned char const *zNew = sqlite3_value_text(argv[2]); unsigned const char *z; /* Pointer to token */ int n; /* Length of token z */ int token; /* Type of token */ UNUSED_PARAMETER(NotUsed); if( zInput==0 || zOld==0 ) return; for(z=zInput; *z; z=z+n){ n = sqlite3GetToken(z, &token); if( token==TK_REFERENCES ){ char *zParent; do { z += n; n = sqlite3GetToken(z, &token); }while( token==TK_SPACE ); if( token==TK_ILLEGAL ) break; zParent = sqlite3DbStrNDup(db, (const char *)z, n); if( zParent==0 ) break; sqlite3Dequote(zParent); if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){ char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew ); sqlite3DbFree(db, zOutput); zOutput = zOut; zInput = &z[n]; } sqlite3DbFree(db, zParent); } } zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC); sqlite3DbFree(db, zOutput); } #endif #ifndef SQLITE_OMIT_TRIGGER /* This function is used by SQL generated to implement the ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER ** statement. The second is a table name. The table name in the CREATE ** TRIGGER statement is replaced with the third argument and the result ** returned. This is analagous to renameTableFunc() above, except for CREATE ** TRIGGER, not CREATE INDEX and CREATE TABLE. */ static void renameTriggerFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ unsigned char const *zSql = sqlite3_value_text(argv[0]); unsigned char const *zTableName = sqlite3_value_text(argv[1]); int token; Token tname; int dist = 3; unsigned char const *zCsr = zSql; int len = 0; char *zRet; sqlite3 *db = sqlite3_context_db_handle(context); UNUSED_PARAMETER(NotUsed); /* The principle used to locate the table name in the CREATE TRIGGER ** statement is that the table name is the first token that is immediately ** preceded by either TK_ON or TK_DOT and immediately followed by one ** of TK_WHEN, TK_BEGIN or TK_FOR. */ if( zSql ){ do { if( !*zCsr ){ /* Ran out of input before finding the table name. Return NULL. */ return; } /* Store the token that zCsr points to in tname. */ tname.z = (char*)zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = sqlite3GetToken(zCsr, &token); }while( token==TK_SPACE ); assert( len>0 ); /* Variable 'dist' stores the number of tokens read since the most ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN ** token is read and 'dist' equals 2, the condition stated above ** to be met. ** ** Note that ON cannot be a database, table or column name, so ** there is no need to worry about syntax like ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. */ dist++; if( token==TK_DOT || token==TK_ON ){ dist = 0; } } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) ); /* Variable tname now contains the token that is the old table-name ** in the CREATE TRIGGER statement. */ zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql), zSql, zTableName, tname.z+tname.n); sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); } } #endif /* !SQLITE_OMIT_TRIGGER */ /* ** Register built-in functions used to help implement ALTER TABLE */ SQLITE_PRIVATE void sqlite3AlterFunctions(void){ static FuncDef aAlterTableFuncs[] = { FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc), #ifndef SQLITE_OMIT_TRIGGER FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc), #endif #ifndef SQLITE_OMIT_FOREIGN_KEY FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc), #endif }; sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); } /* ** This function is used to create the text of expressions of the form: ** ** name=<constant1> OR name=<constant2> OR ... ** ** If argument zWhere is NULL, then a pointer string containing the text ** "name=<constant>" is returned, where <constant> is the quoted version ** of the string passed as argument zConstant. The returned buffer is ** allocated using sqlite3DbMalloc(). It is the responsibility of the ** caller to ensure that it is eventually freed. ** ** If argument zWhere is not NULL, then the string returned is ** "<where> OR name=<constant>", where <where> is the contents of zWhere. ** In this case zWhere is passed to sqlite3DbFree() before returning. ** */ static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){ char *zNew; if( !zWhere ){ zNew = sqlite3MPrintf(db, "name=%Q", zConstant); }else{ zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant); sqlite3DbFree(db, zWhere); } return zNew; } #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) /* ** Generate the text of a WHERE expression which can be used to select all ** tables that have foreign key constraints that refer to table pTab (i.e. ** constraints for which pTab is the parent table) from the sqlite_master ** table. */ static char *whereForeignKeys(Parse *pParse, Table *pTab){ FKey *p; char *zWhere = 0; for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName); } return zWhere; } #endif /* ** Generate the text of a WHERE expression which can be used to select all ** temporary triggers on table pTab from the sqlite_temp_master table. If ** table pTab has no temporary triggers, or is itself stored in the ** temporary database, NULL is returned. */ static char *whereTempTriggers(Parse *pParse, Table *pTab){ Trigger *pTrig; char *zWhere = 0; const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */ /* If the table is not located in the temp-db (in which case NULL is ** returned, loop through the tables list of triggers. For each trigger ** that is not part of the temp-db schema, add a clause to the WHERE ** expression being built up in zWhere. */ if( pTab->pSchema!=pTempSchema ){ sqlite3 *db = pParse->db; for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ if( pTrig->pSchema==pTempSchema ){ zWhere = whereOrName(db, zWhere, pTrig->zName); } } } if( zWhere ){ char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere); sqlite3DbFree(pParse->db, zWhere); zWhere = zNew; } return zWhere; } /* ** Generate code to drop and reload the internal representation of table ** pTab from the database, including triggers and temporary triggers. ** Argument zName is the name of the table in the database schema at ** the time the generated code is executed. This can be different from ** pTab->zName if this function is being called to code part of an ** "ALTER TABLE RENAME TO" statement. */ static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){ Vdbe *v; char *zWhere; int iDb; /* Index of database containing pTab */ #ifndef SQLITE_OMIT_TRIGGER Trigger *pTrig; #endif v = sqlite3GetVdbe(pParse); if( NEVER(v==0) ) return; assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); assert( iDb>=0 ); #ifndef SQLITE_OMIT_TRIGGER /* Drop any table triggers from the internal schema. */ for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); assert( iTrigDb==iDb || iTrigDb==1 ); sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0); } #endif /* Drop the table and index from the internal schema. */ sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); /* Reload the table, index and permanent trigger schemas. */ zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName); if( !zWhere ) return; sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); #ifndef SQLITE_OMIT_TRIGGER /* Now, if the table is not stored in the temp database, reload any temp ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. */ if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ sqlite3VdbeAddParseSchemaOp(v, 1, zWhere); } #endif } /* ** Parameter zName is the name of a table that is about to be altered ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). ** If the table is a system table, this function leaves an error message ** in pParse->zErr (system tables may not be altered) and returns non-zero. ** ** Or, if zName is not a system table, zero is returned. */ static int isSystemTable(Parse *pParse, const char *zName){ if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ sqlite3ErrorMsg(pParse, "table %s may not be altered", zName); return 1; } return 0; } /* ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" ** command. */ SQLITE_PRIVATE void sqlite3AlterRenameTable( Parse *pParse, /* Parser context. */ SrcList *pSrc, /* The table to rename. */ Token *pName /* The new table name. */ ){ int iDb; /* Database that contains the table */ char *zDb; /* Name of database iDb */ Table *pTab; /* Table being renamed */ char *zName = 0; /* NULL-terminated version of pName */ sqlite3 *db = pParse->db; /* Database connection */ int nTabName; /* Number of UTF-8 characters in zTabName */ const char *zTabName; /* Original name of the table */ Vdbe *v; #ifndef SQLITE_OMIT_TRIGGER char *zWhere = 0; /* Where clause to locate temp triggers */ #endif VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */ int savedDbFlags; /* Saved value of db->flags */ savedDbFlags = db->flags; if( NEVER(db->mallocFailed) ) goto exit_rename_table; assert( pSrc->nSrc==1 ); assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); if( !pTab ) goto exit_rename_table; iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); zDb = db->aDb[iDb].zDbSName; db->flags |= SQLITE_PreferBuiltin; /* Get a NULL terminated version of the new table name. */ zName = sqlite3NameFromToken(db, pName); if( !zName ) goto exit_rename_table; /* Check that a table or index named 'zName' does not already exist ** in database iDb. If so, this is an error. */ if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){ sqlite3ErrorMsg(pParse, "there is already another table or index with this name: %s", zName); goto exit_rename_table; } /* Make sure it is not a system table being altered, or a reserved name ** that the table is being renamed to. */ if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ goto exit_rename_table; } if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto exit_rename_table; } #ifndef SQLITE_OMIT_VIEW if( pTab->pSelect ){ sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); goto exit_rename_table; } #endif #ifndef SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ goto exit_rename_table; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto exit_rename_table; } if( IsVirtual(pTab) ){ pVTab = sqlite3GetVTable(db, pTab); if( pVTab->pVtab->pModule->xRename==0 ){ pVTab = 0; } } #endif /* Begin a transaction for database iDb. ** Then modify the schema cookie (since the ALTER TABLE modifies the ** schema). Open a statement transaction if the table is a virtual ** table. */ v = sqlite3GetVdbe(pParse); if( v==0 ){ goto exit_rename_table; } sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb); sqlite3ChangeCookie(pParse, iDb); /* If this is a virtual table, invoke the xRename() function if ** one is defined. The xRename() callback will modify the names ** of any resources used by the v-table implementation (including other ** SQLite tables) that are identified by the name of the virtual table. */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( pVTab ){ int i = ++pParse->nMem; sqlite3VdbeLoadString(v, i, zName); sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); sqlite3MayAbort(pParse); } #endif /* figure out how many UTF-8 characters are in zName */ zTabName = pTab->zName; nTabName = sqlite3Utf8CharLen(zTabName, -1); #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) if( db->flags&SQLITE_ForeignKeys ){ /* If foreign-key support is enabled, rewrite the CREATE TABLE ** statements corresponding to all child tables of foreign key constraints ** for which the renamed table is the parent table. */ if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){ sqlite3NestedParse(pParse, "UPDATE \"%w\".%s SET " "sql = sqlite_rename_parent(sql, %Q, %Q) " "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere); sqlite3DbFree(db, zWhere); } } #endif /* Modify the sqlite_master table to use the new table name. */ sqlite3NestedParse(pParse, "UPDATE %Q.%s SET " #ifdef SQLITE_OMIT_TRIGGER "sql = sqlite_rename_table(sql, %Q), " #else "sql = CASE " "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" "ELSE sqlite_rename_table(sql, %Q) END, " #endif "tbl_name = %Q, " "name = CASE " "WHEN type='table' THEN %Q " "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " "'sqlite_autoindex_' || %Q || substr(name,%d+18) " "ELSE name END " "WHERE tbl_name=%Q COLLATE nocase AND " "(type='table' OR type='index' OR type='trigger');", zDb, MASTER_NAME, zName, zName, zName, #ifndef SQLITE_OMIT_TRIGGER zName, #endif zName, nTabName, zTabName ); #ifndef SQLITE_OMIT_AUTOINCREMENT /* If the sqlite_sequence table exists in this database, then update ** it with the new table name. */ if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ sqlite3NestedParse(pParse, "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", zDb, zName, pTab->zName); } #endif #ifndef SQLITE_OMIT_TRIGGER /* If there are TEMP triggers on this table, modify the sqlite_temp_master ** table. Don't do this if the table being ALTERed is itself located in ** the temp database. */ if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ sqlite3NestedParse(pParse, "UPDATE sqlite_temp_master SET " "sql = sqlite_rename_trigger(sql, %Q), " "tbl_name = %Q " "WHERE %s;", zName, zName, zWhere); sqlite3DbFree(db, zWhere); } #endif #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) if( db->flags&SQLITE_ForeignKeys ){ FKey *p; for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ Table *pFrom = p->pFrom; if( pFrom!=pTab ){ reloadTableSchema(pParse, p->pFrom, pFrom->zName); } } } #endif /* Drop and reload the internal table schema. */ reloadTableSchema(pParse, pTab, zName); exit_rename_table: sqlite3SrcListDelete(db, pSrc); sqlite3DbFree(db, zName); db->flags = savedDbFlags; } /* ** This function is called after an "ALTER TABLE ... ADD" statement ** has been parsed. Argument pColDef contains the text of the new ** column definition. ** ** The Table structure pParse->pNewTable was extended to include ** the new column during parsing. */ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ Table *pNew; /* Copy of pParse->pNewTable */ Table *pTab; /* Table being altered */ int iDb; /* Database number */ const char *zDb; /* Database name */ const char *zTab; /* Table name */ char *zCol; /* Null-terminated column definition */ Column *pCol; /* The new column */ Expr *pDflt; /* Default value for the new column */ sqlite3 *db; /* The database connection; */ Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ int r1; /* Temporary registers */ db = pParse->db; if( pParse->nErr || db->mallocFailed ) return; assert( v!=0 ); pNew = pParse->pNewTable; assert( pNew ); assert( sqlite3BtreeHoldsAllMutexes(db) ); iDb = sqlite3SchemaToIndex(db, pNew->pSchema); zDb = db->aDb[iDb].zDbSName; zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ pCol = &pNew->aCol[pNew->nCol-1]; pDflt = pCol->pDflt; pTab = sqlite3FindTable(db, zTab, zDb); assert( pTab ); #ifndef SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ return; } #endif /* If the default value for the new column was specified with a ** literal NULL, then set pDflt to 0. This simplifies checking ** for an SQL NULL default below. */ assert( pDflt==0 || pDflt->op==TK_SPAN ); if( pDflt && pDflt->pLeft->op==TK_NULL ){ pDflt = 0; } /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. ** If there is a NOT NULL constraint, then the default value for the ** column must not be NULL. */ if( pCol->colFlags & COLFLAG_PRIMKEY ){ sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); return; } if( pNew->pIndex ){ sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column"); return; } if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ sqlite3ErrorMsg(pParse, "Cannot add a REFERENCES column with non-NULL default value"); return; } if( pCol->notNull && !pDflt ){ sqlite3ErrorMsg(pParse, "Cannot add a NOT NULL column with default value NULL"); return; } /* Ensure the default expression is something that sqlite3ValueFromExpr() ** can handle (i.e. not CURRENT_TIME etc.) */ if( pDflt ){ sqlite3_value *pVal = 0; int rc; rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); if( rc!=SQLITE_OK ){ assert( db->mallocFailed == 1 ); return; } if( !pVal ){ sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default"); return; } sqlite3ValueFree(pVal); } /* Modify the CREATE TABLE statement. */ zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); if( zCol ){ char *zEnd = &zCol[pColDef->n-1]; int savedDbFlags = db->flags; while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ *zEnd-- = '\0'; } db->flags |= SQLITE_PreferBuiltin; sqlite3NestedParse(pParse, "UPDATE \"%w\".%s SET " "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " "WHERE type = 'table' AND name = %Q", zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1, zTab ); sqlite3DbFree(db, zCol); db->flags = savedDbFlags; } /* Make sure the schema version is at least 3. But do not upgrade ** from less than 3 to 4, as that will corrupt any preexisting DESC ** index. */ r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); sqlite3VdbeUsesBtree(v, iDb); sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2); sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3); sqlite3ReleaseTempReg(pParse, r1); /* Reload the schema of the modified table. */ reloadTableSchema(pParse, pTab, pTab->zName); } /* ** This function is called by the parser after the table-name in ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument ** pSrc is the full-name of the table being altered. ** ** This routine makes a (partial) copy of the Table structure ** for the table being altered and sets Parse.pNewTable to point ** to it. Routines called by the parser as the column definition ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to ** the copy. The copy of the Table structure is deleted by tokenize.c ** after parsing is finished. ** ** Routine sqlite3AlterFinishAddColumn() will be called to complete ** coding the "ALTER TABLE ... ADD" statement. */ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ Table *pNew; Table *pTab; Vdbe *v; int iDb; int i; int nAlloc; sqlite3 *db = pParse->db; /* Look up the table being altered. */ assert( pParse->pNewTable==0 ); assert( sqlite3BtreeHoldsAllMutexes(db) ); if( db->mallocFailed ) goto exit_begin_add_column; pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); if( !pTab ) goto exit_begin_add_column; #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); goto exit_begin_add_column; } #endif /* Make sure this is not an attempt to ALTER a view. */ if( pTab->pSelect ){ sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); goto exit_begin_add_column; } if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ goto exit_begin_add_column; } assert( pTab->addColOffset>0 ); iDb = sqlite3SchemaToIndex(db, pTab->pSchema); /* Put a copy of the Table struct in Parse.pNewTable for the ** sqlite3AddColumn() function and friends to modify. But modify ** the name by adding an "sqlite_altertab_" prefix. By adding this ** prefix, we insure that the name will not collide with an existing ** table because user table are not allowed to have the "sqlite_" ** prefix on their name. */ pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); if( !pNew ) goto exit_begin_add_column; pParse->pNewTable = pNew; pNew->nTabRef = 1; pNew->nCol = pTab->nCol; assert( pNew->nCol>0 ); nAlloc = (((pNew->nCol-1)/8)*8)+8; assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); if( !pNew->aCol || !pNew->zName ){ assert( db->mallocFailed ); goto exit_begin_add_column; } memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); for(i=0; i<pNew->nCol; i++){ Column *pCol = &pNew->aCol[i]; pCol->zName = sqlite3DbStrDup(db, pCol->zName); pCol->zColl = 0; pCol->pDflt = 0; } pNew->pSchema = db->aDb[iDb].pSchema; pNew->addColOffset = pTab->addColOffset; pNew->nTabRef = 1; /* Begin a transaction and increment the schema cookie. */ sqlite3BeginWriteOperation(pParse, 0, iDb); v = sqlite3GetVdbe(pParse); if( !v ) goto exit_begin_add_column; sqlite3ChangeCookie(pParse, iDb); exit_begin_add_column: sqlite3SrcListDelete(db, pSrc); return; } #endif /* SQLITE_ALTER_TABLE */ /************** End of alter.c ***********************************************/ /************** Begin file analyze.c *****************************************/ /* ** 2005-07-08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code associated with the ANALYZE command. ** ** The ANALYZE command gather statistics about the content of tables ** and indices. These statistics are made available to the query planner ** to help it make better decisions about how to perform queries. ** ** The following system tables are or have been supported: ** ** CREATE TABLE sqlite_stat1(tbl, idx, stat); ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample); ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample); ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample); ** ** Additional tables might be added in future releases of SQLite. ** The sqlite_stat2 table is not created or used unless the SQLite version ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only ** created and used by SQLite versions 3.7.9 and later and with ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced ** version of sqlite_stat3 and is only available when compiled with ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is ** not possible to enable both STAT3 and STAT4 at the same time. If they ** are both enabled, then STAT4 takes precedence. ** ** For most applications, sqlite_stat1 provides all the statistics required ** for the query planner to make good choices. ** ** Format of sqlite_stat1: ** ** There is normally one row per index, with the index identified by the ** name in the idx column. The tbl column is the name of the table to ** which the index belongs. In each such row, the stat column will be ** a string consisting of a list of integers. The first integer in this ** list is the number of rows in the index. (This is the same as the ** number of rows in the table, except for partial indices.) The second ** integer is the average number of rows in the index that have the same ** value in the first column of the index. The third integer is the average ** number of rows in the index that have the same value for the first two ** columns. The N-th integer (for N>1) is the average number of rows in ** the index which have the same value for the first N-1 columns. For ** a K-column index, there will be K+1 integers in the stat column. If ** the index is unique, then the last integer will be 1. ** ** The list of integers in the stat column can optionally be followed ** by the keyword "unordered". The "unordered" keyword, if it is present, ** must be separated from the last integer by a single space. If the ** "unordered" keyword is present, then the query planner assumes that ** the index is unordered and will not use the index for a range query. ** ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat ** column contains a single integer which is the (estimated) number of ** rows in the table identified by sqlite_stat1.tbl. ** ** Format of sqlite_stat2: ** ** The sqlite_stat2 is only created and is only used if SQLite is compiled ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between ** 3.6.18 and 3.7.8. The "stat2" table contains additional information ** about the distribution of keys within an index. The index is identified by ** the "idx" column and the "tbl" column is the name of the table to which ** the index belongs. There are usually 10 rows in the sqlite_stat2 ** table for each index. ** ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9 ** inclusive are samples of the left-most key value in the index taken at ** evenly spaced points along the index. Let the number of samples be S ** (10 in the standard build) and let C be the number of rows in the index. ** Then the sampled rows are given by: ** ** rownumber = (i*C*2 + C)/(S*2) ** ** For i between 0 and S-1. Conceptually, the index space is divided into ** S uniform buckets and the samples are the middle row from each bucket. ** ** The format for sqlite_stat2 is recorded here for legacy reference. This ** version of SQLite does not support sqlite_stat2. It neither reads nor ** writes the sqlite_stat2 table. This version of SQLite only supports ** sqlite_stat3. ** ** Format for sqlite_stat3: ** ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the ** sqlite_stat4 format will be described first. Further information ** about sqlite_stat3 follows the sqlite_stat4 description. ** ** Format for sqlite_stat4: ** ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data ** to aid the query planner in choosing good indices based on the values ** that indexed columns are compared against in the WHERE clauses of ** queries. ** ** The sqlite_stat4 table contains multiple entries for each index. ** The idx column names the index and the tbl column is the table of the ** index. If the idx and tbl columns are the same, then the sample is ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the ** binary encoding of a key from the index. The nEq column is a ** list of integers. The first integer is the approximate number ** of entries in the index whose left-most column exactly matches ** the left-most column of the sample. The second integer in nEq ** is the approximate number of entries in the index where the ** first two columns match the first two columns of the sample. ** And so forth. nLt is another list of integers that show the approximate ** number of entries that are strictly less than the sample. The first ** integer in nLt contains the number of entries in the index where the ** left-most column is less than the left-most column of the sample. ** The K-th integer in the nLt entry is the number of index entries ** where the first K columns are less than the first K columns of the ** sample. The nDLt column is like nLt except that it contains the ** number of distinct entries in the index that are less than the ** sample. ** ** There can be an arbitrary number of sqlite_stat4 entries per index. ** The ANALYZE command will typically generate sqlite_stat4 tables ** that contain between 10 and 40 samples which are distributed across ** the key space, though not uniformly, and which include samples with ** large nEq values. ** ** Format for sqlite_stat3 redux: ** ** The sqlite_stat3 table is like sqlite_stat4 except that it only ** looks at the left-most column of the index. The sqlite_stat3.sample ** column contains the actual value of the left-most column instead ** of a blob encoding of the complete index key as is found in ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3 ** all contain just a single integer which is the same as the first ** integer in the equivalent columns in sqlite_stat4. */ #ifndef SQLITE_OMIT_ANALYZE /* #include "sqliteInt.h" */ #if defined(SQLITE_ENABLE_STAT4) # define IsStat4 1 # define IsStat3 0 #elif defined(SQLITE_ENABLE_STAT3) # define IsStat4 0 # define IsStat3 1 #else # define IsStat4 0 # define IsStat3 0 # undef SQLITE_STAT4_SAMPLES # define SQLITE_STAT4_SAMPLES 1 #endif #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */ /* ** This routine generates code that opens the sqlite_statN tables. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when ** appropriate compile-time options are provided. ** ** If the sqlite_statN tables do not previously exist, it is created. ** ** Argument zWhere may be a pointer to a buffer containing a table name, ** or it may be a NULL pointer. If it is not NULL, then all entries in ** the sqlite_statN tables associated with the named table are deleted. ** If zWhere==0, then code is generated to delete all stat table entries. */ static void openStatTable( Parse *pParse, /* Parsing context */ int iDb, /* The database we are looking in */ int iStatCur, /* Open the sqlite_stat1 table on this cursor */ const char *zWhere, /* Delete entries for this table or index */ const char *zWhereType /* Either "tbl" or "idx" */ ){ static const struct { const char *zName; const char *zCols; } aTable[] = { { "sqlite_stat1", "tbl,idx,stat" }, #if defined(SQLITE_ENABLE_STAT4) { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" }, { "sqlite_stat3", 0 }, #elif defined(SQLITE_ENABLE_STAT3) { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" }, { "sqlite_stat4", 0 }, #else { "sqlite_stat3", 0 }, { "sqlite_stat4", 0 }, #endif }; int i; sqlite3 *db = pParse->db; Db *pDb; Vdbe *v = sqlite3GetVdbe(pParse); int aRoot[ArraySize(aTable)]; u8 aCreateTbl[ArraySize(aTable)]; if( v==0 ) return; assert( sqlite3BtreeHoldsAllMutexes(db) ); assert( sqlite3VdbeDb(v)==db ); pDb = &db->aDb[iDb]; /* Create new statistic tables if they do not exist, or clear them ** if they do already exist. */ for(i=0; i<ArraySize(aTable); i++){ const char *zTab = aTable[i].zName; Table *pStat; if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){ if( aTable[i].zCols ){ /* The sqlite_statN table does not exist. Create it. Note that a ** side-effect of the CREATE TABLE statement is to leave the rootpage ** of the new table in register pParse->regRoot. This is important ** because the OpenWrite opcode below will be needing it. */ sqlite3NestedParse(pParse, "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols ); aRoot[i] = pParse->regRoot; aCreateTbl[i] = OPFLAG_P2ISREG; } }else{ /* The table already exists. If zWhere is not NULL, delete all entries ** associated with the table zWhere. If zWhere is NULL, delete the ** entire contents of the table. */ aRoot[i] = pStat->tnum; aCreateTbl[i] = 0; sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab); if( zWhere ){ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zDbSName, zTab, zWhereType, zWhere ); }else{ /* The sqlite_stat[134] table already exists. Delete all rows. */ sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb); } } } /* Open the sqlite_stat[134] tables for writing. */ for(i=0; aTable[i].zCols; i++){ assert( i<ArraySize(aTable) ); sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3); sqlite3VdbeChangeP5(v, aCreateTbl[i]); VdbeComment((v, aTable[i].zName)); } } /* ** Recommended number of samples for sqlite_stat4 */ #ifndef SQLITE_STAT4_SAMPLES # define SQLITE_STAT4_SAMPLES 24 #endif /* ** Three SQL functions - stat_init(), stat_push(), and stat_get() - ** share an instance of the following structure to hold their state ** information. */ typedef struct Stat4Accum Stat4Accum; typedef struct Stat4Sample Stat4Sample; struct Stat4Sample { tRowcnt *anEq; /* sqlite_stat4.nEq */ tRowcnt *anDLt; /* sqlite_stat4.nDLt */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 tRowcnt *anLt; /* sqlite_stat4.nLt */ union { i64 iRowid; /* Rowid in main table of the key */ u8 *aRowid; /* Key for WITHOUT ROWID tables */ } u; u32 nRowid; /* Sizeof aRowid[] */ u8 isPSample; /* True if a periodic sample */ int iCol; /* If !isPSample, the reason for inclusion */ u32 iHash; /* Tiebreaker hash */ #endif }; struct Stat4Accum { tRowcnt nRow; /* Number of rows in the entire table */ tRowcnt nPSample; /* How often to do a periodic sample */ int nCol; /* Number of columns in index + pk/rowid */ int nKeyCol; /* Number of index columns w/o the pk/rowid */ int mxSample; /* Maximum number of samples to accumulate */ Stat4Sample current; /* Current row as a Stat4Sample */ u32 iPrn; /* Pseudo-random number used for sampling */ Stat4Sample *aBest; /* Array of nCol best samples */ int iMin; /* Index in a[] of entry with minimum score */ int nSample; /* Current number of samples */ int iGet; /* Index of current sample accessed by stat_get() */ Stat4Sample *a; /* Array of mxSample Stat4Sample objects */ sqlite3 *db; /* Database connection, for malloc() */ }; /* Reclaim memory used by a Stat4Sample */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static void sampleClear(sqlite3 *db, Stat4Sample *p){ assert( db!=0 ); if( p->nRowid ){ sqlite3DbFree(db, p->u.aRowid); p->nRowid = 0; } } #endif /* Initialize the BLOB value of a ROWID */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){ assert( db!=0 ); if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); p->u.aRowid = sqlite3DbMallocRawNN(db, n); if( p->u.aRowid ){ p->nRowid = n; memcpy(p->u.aRowid, pData, n); }else{ p->nRowid = 0; } } #endif /* Initialize the INTEGER value of a ROWID. */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){ assert( db!=0 ); if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); p->nRowid = 0; p->u.iRowid = iRowid; } #endif /* ** Copy the contents of object (*pFrom) into (*pTo). */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ pTo->isPSample = pFrom->isPSample; pTo->iCol = pFrom->iCol; pTo->iHash = pFrom->iHash; memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); if( pFrom->nRowid ){ sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid); }else{ sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid); } } #endif /* ** Reclaim all memory of a Stat4Accum structure. */ static void stat4Destructor(void *pOld){ Stat4Accum *p = (Stat4Accum*)pOld; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int i; for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i); for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i); sampleClear(p->db, &p->current); #endif sqlite3DbFree(p->db, p); } /* ** Implementation of the stat_init(N,K,C) SQL function. The three parameters ** are: ** N: The number of columns in the index including the rowid/pk (note 1) ** K: The number of columns in the index excluding the rowid/pk. ** C: The number of rows in the index (note 2) ** ** Note 1: In the special case of the covering index that implements a ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the ** total number of columns in the table. ** ** Note 2: C is only used for STAT3 and STAT4. ** ** For indexes on ordinary rowid tables, N==K+1. But for indexes on ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the ** PRIMARY KEY of the table. The covering index that implements the ** original WITHOUT ROWID table as N==K as a special case. ** ** This routine allocates the Stat4Accum object in heap memory. The return ** value is a pointer to the Stat4Accum object. The datatype of the ** return value is BLOB, but it is really just a pointer to the Stat4Accum ** object. */ static void statInit( sqlite3_context *context, int argc, sqlite3_value **argv ){ Stat4Accum *p; int nCol; /* Number of columns in index being sampled */ int nKeyCol; /* Number of key columns */ int nColUp; /* nCol rounded up for alignment */ int n; /* Bytes of space to allocate */ sqlite3 *db; /* Database connection */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int mxSample = SQLITE_STAT4_SAMPLES; #endif /* Decode the three function arguments */ UNUSED_PARAMETER(argc); nCol = sqlite3_value_int(argv[0]); assert( nCol>0 ); nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol; nKeyCol = sqlite3_value_int(argv[1]); assert( nKeyCol<=nCol ); assert( nKeyCol>0 ); /* Allocate the space required for the Stat4Accum object */ n = sizeof(*p) + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */ + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */ + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */ + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample) #endif ; db = sqlite3_context_db_handle(context); p = sqlite3DbMallocZero(db, n); if( p==0 ){ sqlite3_result_error_nomem(context); return; } p->db = db; p->nRow = 0; p->nCol = nCol; p->nKeyCol = nKeyCol; p->current.anDLt = (tRowcnt*)&p[1]; p->current.anEq = &p->current.anDLt[nColUp]; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 { u8 *pSpace; /* Allocated space not yet assigned */ int i; /* Used to iterate through p->aSample[] */ p->iGet = -1; p->mxSample = mxSample; p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1); p->current.anLt = &p->current.anEq[nColUp]; p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]); /* Set up the Stat4Accum.a[] and aBest[] arrays */ p->a = (struct Stat4Sample*)&p->current.anLt[nColUp]; p->aBest = &p->a[mxSample]; pSpace = (u8*)(&p->a[mxSample+nCol]); for(i=0; i<(mxSample+nCol); i++){ p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); } assert( (pSpace - (u8*)p)==n ); for(i=0; i<nCol; i++){ p->aBest[i].iCol = i; } } #endif /* Return a pointer to the allocated object to the caller. Note that ** only the pointer (the 2nd parameter) matters. The size of the object ** (given by the 3rd parameter) is never used and can be any positive ** value. */ sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor); } static const FuncDef statInitFuncdef = { 2+IsStat34, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statInit, /* xSFunc */ 0, /* xFinalize */ "stat_init", /* zName */ {0} }; #ifdef SQLITE_ENABLE_STAT4 /* ** pNew and pOld are both candidate non-periodic samples selected for ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and ** considering only any trailing columns and the sample hash value, this ** function returns true if sample pNew is to be preferred over pOld. ** In other words, if we assume that the cardinalities of the selected ** column for pNew and pOld are equal, is pNew to be preferred over pOld. ** ** This function assumes that for each argument sample, the contents of ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. */ static int sampleIsBetterPost( Stat4Accum *pAccum, Stat4Sample *pNew, Stat4Sample *pOld ){ int nCol = pAccum->nCol; int i; assert( pNew->iCol==pOld->iCol ); for(i=pNew->iCol+1; i<nCol; i++){ if( pNew->anEq[i]>pOld->anEq[i] ) return 1; if( pNew->anEq[i]<pOld->anEq[i] ) return 0; } if( pNew->iHash>pOld->iHash ) return 1; return 0; } #endif #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Return true if pNew is to be preferred over pOld. ** ** This function assumes that for each argument sample, the contents of ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. */ static int sampleIsBetter( Stat4Accum *pAccum, Stat4Sample *pNew, Stat4Sample *pOld ){ tRowcnt nEqNew = pNew->anEq[pNew->iCol]; tRowcnt nEqOld = pOld->anEq[pOld->iCol]; assert( pOld->isPSample==0 && pNew->isPSample==0 ); assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) ); if( (nEqNew>nEqOld) ) return 1; #ifdef SQLITE_ENABLE_STAT4 if( nEqNew==nEqOld ){ if( pNew->iCol<pOld->iCol ) return 1; return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld)); } return 0; #else return (nEqNew==nEqOld && pNew->iHash>pOld->iHash); #endif } /* ** Copy the contents of sample *pNew into the p->a[] array. If necessary, ** remove the least desirable sample from p->a[] to make room. */ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ Stat4Sample *pSample = 0; int i; assert( IsStat4 || nEqZero==0 ); #ifdef SQLITE_ENABLE_STAT4 if( pNew->isPSample==0 ){ Stat4Sample *pUpgrade = 0; assert( pNew->anEq[pNew->iCol]>0 ); /* This sample is being added because the prefix that ends in column ** iCol occurs many times in the table. However, if we have already ** added a sample that shares this prefix, there is no need to add ** this one. Instead, upgrade the priority of the highest priority ** existing sample that shares this prefix. */ for(i=p->nSample-1; i>=0; i--){ Stat4Sample *pOld = &p->a[i]; if( pOld->anEq[pNew->iCol]==0 ){ if( pOld->isPSample ) return; assert( pOld->iCol>pNew->iCol ); assert( sampleIsBetter(p, pNew, pOld) ); if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){ pUpgrade = pOld; } } } if( pUpgrade ){ pUpgrade->iCol = pNew->iCol; pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol]; goto find_new_min; } } #endif /* If necessary, remove sample iMin to make room for the new sample. */ if( p->nSample>=p->mxSample ){ Stat4Sample *pMin = &p->a[p->iMin]; tRowcnt *anEq = pMin->anEq; tRowcnt *anLt = pMin->anLt; tRowcnt *anDLt = pMin->anDLt; sampleClear(p->db, pMin); memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1)); pSample = &p->a[p->nSample-1]; pSample->nRowid = 0; pSample->anEq = anEq; pSample->anDLt = anDLt; pSample->anLt = anLt; p->nSample = p->mxSample-1; } /* The "rows less-than" for the rowid column must be greater than that ** for the last sample in the p->a[] array. Otherwise, the samples would ** be out of order. */ #ifdef SQLITE_ENABLE_STAT4 assert( p->nSample==0 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] ); #endif /* Insert the new sample */ pSample = &p->a[p->nSample]; sampleCopy(p, pSample, pNew); p->nSample++; /* Zero the first nEqZero entries in the anEq[] array. */ memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero); #ifdef SQLITE_ENABLE_STAT4 find_new_min: #endif if( p->nSample>=p->mxSample ){ int iMin = -1; for(i=0; i<p->mxSample; i++){ if( p->a[i].isPSample ) continue; if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){ iMin = i; } } assert( iMin>=0 ); p->iMin = iMin; } } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* ** Field iChng of the index being scanned has changed. So at this point ** p->current contains a sample that reflects the previous row of the ** index. The value of anEq[iChng] and subsequent anEq[] elements are ** correct at this point. */ static void samplePushPrevious(Stat4Accum *p, int iChng){ #ifdef SQLITE_ENABLE_STAT4 int i; /* Check if any samples from the aBest[] array should be pushed ** into IndexSample.a[] at this point. */ for(i=(p->nCol-2); i>=iChng; i--){ Stat4Sample *pBest = &p->aBest[i]; pBest->anEq[i] = p->current.anEq[i]; if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){ sampleInsert(p, pBest, i); } } /* Update the anEq[] fields of any samples already collected. */ for(i=p->nSample-1; i>=0; i--){ int j; for(j=iChng; j<p->nCol; j++){ if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j]; } } #endif #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4) if( iChng==0 ){ tRowcnt nLt = p->current.anLt[0]; tRowcnt nEq = p->current.anEq[0]; /* Check if this is to be a periodic sample. If so, add it. */ if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){ p->current.isPSample = 1; sampleInsert(p, &p->current, 0); p->current.isPSample = 0; }else /* Or if it is a non-periodic sample. Add it in this case too. */ if( p->nSample<p->mxSample || sampleIsBetter(p, &p->current, &p->a[p->iMin]) ){ sampleInsert(p, &p->current, 0); } } #endif #ifndef SQLITE_ENABLE_STAT3_OR_STAT4 UNUSED_PARAMETER( p ); UNUSED_PARAMETER( iChng ); #endif } /* ** Implementation of the stat_push SQL function: stat_push(P,C,R) ** Arguments: ** ** P Pointer to the Stat4Accum object created by stat_init() ** C Index of left-most column to differ from previous row ** R Rowid for the current row. Might be a key record for ** WITHOUT ROWID tables. ** ** This SQL function always returns NULL. It's purpose it to accumulate ** statistical data and/or samples in the Stat4Accum object about the ** index being analyzed. The stat_get() SQL function will later be used to ** extract relevant information for constructing the sqlite_statN tables. ** ** The R parameter is only used for STAT3 and STAT4 */ static void statPush( sqlite3_context *context, int argc, sqlite3_value **argv ){ int i; /* The three function arguments */ Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); int iChng = sqlite3_value_int(argv[1]); UNUSED_PARAMETER( argc ); UNUSED_PARAMETER( context ); assert( p->nCol>0 ); assert( iChng<p->nCol ); if( p->nRow==0 ){ /* This is the first call to this function. Do initialization. */ for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1; }else{ /* Second and subsequent calls get processed here */ samplePushPrevious(p, iChng); /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply ** to the current row of the index. */ for(i=0; i<iChng; i++){ p->current.anEq[i]++; } for(i=iChng; i<p->nCol; i++){ p->current.anDLt[i]++; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 p->current.anLt[i] += p->current.anEq[i]; #endif p->current.anEq[i] = 1; } } p->nRow++; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){ sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2])); }else{ sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]), sqlite3_value_blob(argv[2])); } p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345; #endif #ifdef SQLITE_ENABLE_STAT4 { tRowcnt nLt = p->current.anLt[p->nCol-1]; /* Check if this is to be a periodic sample. If so, add it. */ if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){ p->current.isPSample = 1; p->current.iCol = 0; sampleInsert(p, &p->current, p->nCol-1); p->current.isPSample = 0; } /* Update the aBest[] array. */ for(i=0; i<(p->nCol-1); i++){ p->current.iCol = i; if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){ sampleCopy(p, &p->aBest[i], &p->current); } } } #endif } static const FuncDef statPushFuncdef = { 2+IsStat34, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statPush, /* xSFunc */ 0, /* xFinalize */ "stat_push", /* zName */ {0} }; #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */ #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */ #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */ #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */ #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */ /* ** Implementation of the stat_get(P,J) SQL function. This routine is ** used to query statistical information that has been gathered into ** the Stat4Accum object by prior calls to stat_push(). The P parameter ** has type BLOB but it is really just a pointer to the Stat4Accum object. ** The content to returned is determined by the parameter J ** which is one of the STAT_GET_xxxx values defined above. ** ** The stat_get(P,J) function is not available to generic SQL. It is ** inserted as part of a manually constructed bytecode program. (See ** the callStatGet() routine below.) It is guaranteed that the P ** parameter will always be a poiner to a Stat4Accum object, never a ** NULL. ** ** If neither STAT3 nor STAT4 are enabled, then J is always ** STAT_GET_STAT1 and is hence omitted and this routine becomes ** a one-parameter function, stat_get(P), that always returns the ** stat1 table entry information. */ static void statGet( sqlite3_context *context, int argc, sqlite3_value **argv ){ Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* STAT3 and STAT4 have a parameter on this routine. */ int eCall = sqlite3_value_int(argv[1]); assert( argc==2 ); assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT || eCall==STAT_GET_NDLT ); if( eCall==STAT_GET_STAT1 ) #else assert( argc==1 ); #endif { /* Return the value to store in the "stat" column of the sqlite_stat1 ** table for this index. ** ** The value is a string composed of a list of integers describing ** the index. The first integer in the list is the total number of ** entries in the index. There is one additional integer in the list ** for each indexed column. This additional integer is an estimate of ** the number of rows matched by a stabbing query on the index using ** a key with the corresponding number of fields. In other words, ** if the index is on columns (a,b) and the sqlite_stat1 value is ** "100 10 2", then SQLite estimates that: ** ** * the index contains 100 rows, ** * "WHERE a=?" matches 10 rows, and ** * "WHERE a=? AND b=?" matches 2 rows. ** ** If D is the count of distinct values and K is the total number of ** rows, then each estimate is computed as: ** ** I = (K+D-1)/D */ char *z; int i; char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 ); if( zRet==0 ){ sqlite3_result_error_nomem(context); return; } sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow); z = zRet + sqlite3Strlen30(zRet); for(i=0; i<p->nKeyCol; i++){ u64 nDistinct = p->current.anDLt[i] + 1; u64 iVal = (p->nRow + nDistinct - 1) / nDistinct; sqlite3_snprintf(24, z, " %llu", iVal); z += sqlite3Strlen30(z); assert( p->current.anEq[i] ); } assert( z[0]=='\0' && z>zRet ); sqlite3_result_text(context, zRet, -1, sqlite3_free); } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 else if( eCall==STAT_GET_ROWID ){ if( p->iGet<0 ){ samplePushPrevious(p, 0); p->iGet = 0; } if( p->iGet<p->nSample ){ Stat4Sample *pS = p->a + p->iGet; if( pS->nRowid==0 ){ sqlite3_result_int64(context, pS->u.iRowid); }else{ sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid, SQLITE_TRANSIENT); } } }else{ tRowcnt *aCnt = 0; assert( p->iGet<p->nSample ); switch( eCall ){ case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break; case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break; default: { aCnt = p->a[p->iGet].anDLt; p->iGet++; break; } } if( IsStat3 ){ sqlite3_result_int64(context, (i64)aCnt[0]); }else{ char *zRet = sqlite3MallocZero(p->nCol * 25); if( zRet==0 ){ sqlite3_result_error_nomem(context); }else{ int i; char *z = zRet; for(i=0; i<p->nCol; i++){ sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]); z += sqlite3Strlen30(z); } assert( z[0]=='\0' && z>zRet ); z[-1] = '\0'; sqlite3_result_text(context, zRet, -1, sqlite3_free); } } } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ #ifndef SQLITE_DEBUG UNUSED_PARAMETER( argc ); #endif } static const FuncDef statGetFuncdef = { 1+IsStat34, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statGet, /* xSFunc */ 0, /* xFinalize */ "stat_get", /* zName */ {0} }; static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){ assert( regOut!=regStat4 && regOut!=regStat4+1 ); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1); #elif SQLITE_DEBUG assert( iParam==STAT_GET_STAT1 ); #else UNUSED_PARAMETER( iParam ); #endif sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut, (char*)&statGetFuncdef, P4_FUNCDEF); sqlite3VdbeChangeP5(v, 1 + IsStat34); } /* ** Generate code to do an analysis of all indices associated with ** a single table. */ static void analyzeOneTable( Parse *pParse, /* Parser context */ Table *pTab, /* Table whose indices are to be analyzed */ Index *pOnlyIdx, /* If not NULL, only analyze this one index */ int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ int iMem, /* Available memory locations begin here */ int iTab /* Next available cursor */ ){ sqlite3 *db = pParse->db; /* Database handle */ Index *pIdx; /* An index to being analyzed */ int iIdxCur; /* Cursor open on index being analyzed */ int iTabCur; /* Table cursor */ Vdbe *v; /* The virtual machine being built up */ int i; /* Loop counter */ int jZeroRows = -1; /* Jump from here if number of rows is zero */ int iDb; /* Index of database containing pTab */ u8 needTableCnt = 1; /* True to count the table */ int regNewRowid = iMem++; /* Rowid for the inserted record */ int regStat4 = iMem++; /* Register to hold Stat4Accum object */ int regChng = iMem++; /* Index of changed index field */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int regRowid = iMem++; /* Rowid argument passed to stat_push() */ #endif int regTemp = iMem++; /* Temporary use register */ int regTabname = iMem++; /* Register containing table name */ int regIdxname = iMem++; /* Register containing index name */ int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */ int regPrev = iMem; /* MUST BE LAST (see below) */ pParse->nMem = MAX(pParse->nMem, iMem); v = sqlite3GetVdbe(pParse); if( v==0 || NEVER(pTab==0) ){ return; } if( pTab->tnum==0 ){ /* Do not gather statistics on views or virtual tables */ return; } if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){ /* Do not gather statistics on system tables */ return; } assert( sqlite3BtreeHoldsAllMutexes(db) ); iDb = sqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb>=0 ); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); #ifndef SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0, db->aDb[iDb].zDbSName ) ){ return; } #endif /* Establish a read-lock on the table at the shared-cache level. ** Open a read-only cursor on the table. Also allocate a cursor number ** to use for scanning indexes (iIdxCur). No index cursor is opened at ** this time though. */ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); iTabCur = iTab++; iIdxCur = iTab++; pParse->nTab = MAX(pParse->nTab, iTab); sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); sqlite3VdbeLoadString(v, regTabname, pTab->zName); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int nCol; /* Number of columns in pIdx. "N" */ int addrRewind; /* Address of "OP_Rewind iIdxCur" */ int addrNextRow; /* Address of "next_row:" */ const char *zIdxName; /* Name of the index */ int nColTest; /* Number of columns to test for changes */ if( pOnlyIdx && pOnlyIdx!=pIdx ) continue; if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0; if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){ nCol = pIdx->nKeyCol; zIdxName = pTab->zName; nColTest = nCol - 1; }else{ nCol = pIdx->nColumn; zIdxName = pIdx->zName; nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1; } /* Populate the register containing the index name. */ sqlite3VdbeLoadString(v, regIdxname, zIdxName); VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName)); /* ** Pseudo-code for loop that calls stat_push(): ** ** Rewind csr ** if eof(csr) goto end_of_scan; ** regChng = 0 ** goto chng_addr_0; ** ** next_row: ** regChng = 0 ** if( idx(0) != regPrev(0) ) goto chng_addr_0 ** regChng = 1 ** if( idx(1) != regPrev(1) ) goto chng_addr_1 ** ... ** regChng = N ** goto chng_addr_N ** ** chng_addr_0: ** regPrev(0) = idx(0) ** chng_addr_1: ** regPrev(1) = idx(1) ** ... ** ** endDistinctTest: ** regRowid = idx(rowid) ** stat_push(P, regChng, regRowid) ** Next csr ** if !eof(csr) goto next_row; ** ** end_of_scan: */ /* Make sure there are enough memory cells allocated to accommodate ** the regPrev array and a trailing rowid (the rowid slot is required ** when building a record to insert into the sample column of ** the sqlite_stat4 table. */ pParse->nMem = MAX(pParse->nMem, regPrev+nColTest); /* Open a read-only cursor on the index being analyzed. */ assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) ); sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); /* Invoke the stat_init() function. The arguments are: ** ** (1) the number of columns in the index including the rowid ** (or for a WITHOUT ROWID table, the number of PK columns), ** (2) the number of columns in the key without the rowid/pk ** (3) the number of rows in the index, ** ** ** The third argument is only used for STAT3 and STAT4 */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3); #endif sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1); sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2); sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4, (char*)&statInitFuncdef, P4_FUNCDEF); sqlite3VdbeChangeP5(v, 2+IsStat34); /* Implementation of the following: ** ** Rewind csr ** if eof(csr) goto end_of_scan; ** regChng = 0 ** goto next_push_0; ** */ addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng); addrNextRow = sqlite3VdbeCurrentAddr(v); if( nColTest>0 ){ int endDistinctTest = sqlite3VdbeMakeLabel(v); int *aGotoChng; /* Array of jump instruction addresses */ aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest); if( aGotoChng==0 ) continue; /* ** next_row: ** regChng = 0 ** if( idx(0) != regPrev(0) ) goto chng_addr_0 ** regChng = 1 ** if( idx(1) != regPrev(1) ) goto chng_addr_1 ** ... ** regChng = N ** goto endDistinctTest */ sqlite3VdbeAddOp0(v, OP_Goto); addrNextRow = sqlite3VdbeCurrentAddr(v); if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){ /* For a single-column UNIQUE index, once we have found a non-NULL ** row, we know that all the rest will be distinct, so skip ** subsequent distinctness tests. */ sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest); VdbeCoverage(v); } for(i=0; i<nColTest; i++){ char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]); sqlite3VdbeAddOp2(v, OP_Integer, i, regChng); sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp); aGotoChng[i] = sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ); sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); VdbeCoverage(v); } sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng); sqlite3VdbeGoto(v, endDistinctTest); /* ** chng_addr_0: ** regPrev(0) = idx(0) ** chng_addr_1: ** regPrev(1) = idx(1) ** ... */ sqlite3VdbeJumpHere(v, addrNextRow-1); for(i=0; i<nColTest; i++){ sqlite3VdbeJumpHere(v, aGotoChng[i]); sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i); } sqlite3VdbeResolveLabel(v, endDistinctTest); sqlite3DbFree(db, aGotoChng); } /* ** chng_addr_N: ** regRowid = idx(rowid) // STAT34 only ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only ** Next csr ** if !eof(csr) goto next_row; */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 assert( regRowid==(regStat4+2) ); if( HasRowid(pTab) ){ sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); int j, k, regKey; regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol); for(j=0; j<pPk->nKeyCol; j++){ k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); assert( k>=0 && k<pTab->nCol ); sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j); VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName)); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid); sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol); } #endif assert( regChng==(regStat4+1) ); sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp, (char*)&statPushFuncdef, P4_FUNCDEF); sqlite3VdbeChangeP5(v, 2+IsStat34); sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v); /* Add the entry to the stat1 table. */ callStatGet(v, regStat4, STAT_GET_STAT1, regStat1); assert( "BBB"[0]==SQLITE_AFF_TEXT ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); /* Add the entries to the stat3 or stat4 table. */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 { int regEq = regStat1; int regLt = regStat1+1; int regDLt = regStat1+2; int regSample = regStat1+3; int regCol = regStat1+4; int regSampleRowid = regCol + nCol; int addrNext; int addrIsNull; u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound; pParse->nMem = MAX(pParse->nMem, regCol+nCol); addrNext = sqlite3VdbeCurrentAddr(v); callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid); addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid); VdbeCoverage(v); callStatGet(v, regStat4, STAT_GET_NEQ, regEq); callStatGet(v, regStat4, STAT_GET_NLT, regLt); callStatGet(v, regStat4, STAT_GET_NDLT, regDLt); sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0); /* We know that the regSampleRowid row exists because it was read by ** the previous loop. Thus the not-found jump of seekOp will never ** be taken */ VdbeCoverageNeverTaken(v); #ifdef SQLITE_ENABLE_STAT3 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample); #else for(i=0; i<nCol; i++){ sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample); #endif sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp); sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid); sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid); sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */ sqlite3VdbeJumpHere(v, addrIsNull); } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* End of analysis */ sqlite3VdbeJumpHere(v, addrRewind); } /* Create a single sqlite_stat1 entry containing NULL as the index ** name and the row count as the content. */ if( pOnlyIdx==0 && needTableCnt ){ VdbeComment((v, "%s", pTab->zName)); sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1); jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname); assert( "BBB"[0]==SQLITE_AFF_TEXT ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3VdbeJumpHere(v, jZeroRows); } } /* ** Generate code that will cause the most recent index analysis to ** be loaded into internal hash tables where is can be used. */ static void loadAnalysis(Parse *pParse, int iDb){ Vdbe *v = sqlite3GetVdbe(pParse); if( v ){ sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb); } } /* ** Generate code that will do an analysis of an entire database */ static void analyzeDatabase(Parse *pParse, int iDb){ sqlite3 *db = pParse->db; Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */ HashElem *k; int iStatCur; int iMem; int iTab; sqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab; pParse->nTab += 3; openStatTable(pParse, iDb, iStatCur, 0, 0); iMem = pParse->nMem+1; iTab = pParse->nTab; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ Table *pTab = (Table*)sqliteHashData(k); analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab); } loadAnalysis(pParse, iDb); } /* ** Generate code that will do an analysis of a single table in ** a database. If pOnlyIdx is not NULL then it is a single index ** in pTab that should be analyzed. */ static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){ int iDb; int iStatCur; assert( pTab!=0 ); assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); sqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab; pParse->nTab += 3; if( pOnlyIdx ){ openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx"); }else{ openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl"); } analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab); loadAnalysis(pParse, iDb); } /* ** Generate code for the ANALYZE command. The parser calls this routine ** when it recognizes an ANALYZE command. ** ** ANALYZE -- 1 ** ANALYZE <database> -- 2 ** ANALYZE ?<database>.?<tablename> -- 3 ** ** Form 1 causes all indices in all attached databases to be analyzed. ** Form 2 analyzes all indices the single database named. ** Form 3 analyzes all indices associated with the named table. */ SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ sqlite3 *db = pParse->db; int iDb; int i; char *z, *zDb; Table *pTab; Index *pIdx; Token *pTableName; Vdbe *v; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ return; } assert( pName2!=0 || pName1==0 ); if( pName1==0 ){ /* Form 1: Analyze everything */ for(i=0; i<db->nDb; i++){ if( i==1 ) continue; /* Do not analyze the TEMP database */ analyzeDatabase(pParse, i); } }else if( pName2->n==0 ){ /* Form 2: Analyze the database or table named */ iDb = sqlite3FindDb(db, pName1); if( iDb>=0 ){ analyzeDatabase(pParse, iDb); }else{ z = sqlite3NameFromToken(db, pName1); if( z ){ if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){ analyzeTable(pParse, pIdx->pTable, pIdx); }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){ analyzeTable(pParse, pTab, 0); } sqlite3DbFree(db, z); } } }else{ /* Form 3: Analyze the fully qualified table name */ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName); if( iDb>=0 ){ zDb = db->aDb[iDb].zDbSName; z = sqlite3NameFromToken(db, pTableName); if( z ){ if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){ analyzeTable(pParse, pIdx->pTable, pIdx); }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){ analyzeTable(pParse, pTab, 0); } sqlite3DbFree(db, z); } } } v = sqlite3GetVdbe(pParse); if( v ) sqlite3VdbeAddOp0(v, OP_Expire); } /* ** Used to pass information from the analyzer reader through to the ** callback routine. */ typedef struct analysisInfo analysisInfo; struct analysisInfo { sqlite3 *db; const char *zDatabase; }; /* ** The first argument points to a nul-terminated string containing a ** list of space separated integers. Read the first nOut of these into ** the array aOut[]. */ static void decodeIntArray( char *zIntArray, /* String containing int array to decode */ int nOut, /* Number of slots in aOut[] */ tRowcnt *aOut, /* Store integers here */ LogEst *aLog, /* Or, if aOut==0, here */ Index *pIndex /* Handle extra flags for this index, if not NULL */ ){ char *z = zIntArray; int c; int i; tRowcnt v; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( z==0 ) z = ""; #else assert( z!=0 ); #endif for(i=0; *z && i<nOut; i++){ v = 0; while( (c=z[0])>='0' && c<='9' ){ v = v*10 + c - '0'; z++; } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( aOut ) aOut[i] = v; if( aLog ) aLog[i] = sqlite3LogEst(v); #else assert( aOut==0 ); UNUSED_PARAMETER(aOut); assert( aLog!=0 ); aLog[i] = sqlite3LogEst(v); #endif if( *z==' ' ) z++; } #ifndef SQLITE_ENABLE_STAT3_OR_STAT4 assert( pIndex!=0 ); { #else if( pIndex ){ #endif pIndex->bUnordered = 0; pIndex->noSkipScan = 0; while( z[0] ){ if( sqlite3_strglob("unordered*", z)==0 ){ pIndex->bUnordered = 1; }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){ pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3)); }else if( sqlite3_strglob("noskipscan*", z)==0 ){ pIndex->noSkipScan = 1; } #ifdef SQLITE_ENABLE_COSTMULT else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){ pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9)); } #endif while( z[0]!=0 && z[0]!=' ' ) z++; while( z[0]==' ' ) z++; } } } /* ** This callback is invoked once for each index when reading the ** sqlite_stat1 table. ** ** argv[0] = name of the table ** argv[1] = name of the index (might be NULL) ** argv[2] = results of analysis - on integer for each column ** ** Entries for which argv[1]==NULL simply record the number of rows in ** the table. */ static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ analysisInfo *pInfo = (analysisInfo*)pData; Index *pIndex; Table *pTable; const char *z; assert( argc==3 ); UNUSED_PARAMETER2(NotUsed, argc); if( argv==0 || argv[0]==0 || argv[2]==0 ){ return 0; } pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase); if( pTable==0 ){ return 0; } if( argv[1]==0 ){ pIndex = 0; }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){ pIndex = sqlite3PrimaryKeyIndex(pTable); }else{ pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase); } z = argv[2]; if( pIndex ){ tRowcnt *aiRowEst = 0; int nCol = pIndex->nKeyCol+1; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* Index.aiRowEst may already be set here if there are duplicate ** sqlite_stat1 entries for this index. In that case just clobber ** the old data with the new instead of allocating a new array. */ if( pIndex->aiRowEst==0 ){ pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol); if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db); } aiRowEst = pIndex->aiRowEst; #endif pIndex->bUnordered = 0; decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex); if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0]; }else{ Index fakeIdx; fakeIdx.szIdxRow = pTable->szTabRow; #ifdef SQLITE_ENABLE_COSTMULT fakeIdx.pTable = pTable; #endif decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx); pTable->szTabRow = fakeIdx.szIdxRow; } return 0; } /* ** If the Index.aSample variable is not NULL, delete the aSample[] array ** and its contents. */ SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( pIdx->aSample ){ int j; for(j=0; j<pIdx->nSample; j++){ IndexSample *p = &pIdx->aSample[j]; sqlite3DbFree(db, p->p); } sqlite3DbFree(db, pIdx->aSample); } if( db && db->pnBytesFreed==0 ){ pIdx->nSample = 0; pIdx->aSample = 0; } #else UNUSED_PARAMETER(db); UNUSED_PARAMETER(pIdx); #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Populate the pIdx->aAvgEq[] array based on the samples currently ** stored in pIdx->aSample[]. */ static void initAvgEq(Index *pIdx){ if( pIdx ){ IndexSample *aSample = pIdx->aSample; IndexSample *pFinal = &aSample[pIdx->nSample-1]; int iCol; int nCol = 1; if( pIdx->nSampleCol>1 ){ /* If this is stat4 data, then calculate aAvgEq[] values for all ** sample columns except the last. The last is always set to 1, as ** once the trailing PK fields are considered all index keys are ** unique. */ nCol = pIdx->nSampleCol-1; pIdx->aAvgEq[nCol] = 1; } for(iCol=0; iCol<nCol; iCol++){ int nSample = pIdx->nSample; int i; /* Used to iterate through samples */ tRowcnt sumEq = 0; /* Sum of the nEq values */ tRowcnt avgEq = 0; tRowcnt nRow; /* Number of rows in index */ i64 nSum100 = 0; /* Number of terms contributing to sumEq */ i64 nDist100; /* Number of distinct values in index */ if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){ nRow = pFinal->anLt[iCol]; nDist100 = (i64)100 * pFinal->anDLt[iCol]; nSample--; }else{ nRow = pIdx->aiRowEst[0]; nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1]; } pIdx->nRowEst0 = nRow; /* Set nSum to the number of distinct (iCol+1) field prefixes that ** occur in the stat4 table for this index. Set sumEq to the sum of ** the nEq values for column iCol for the same set (adding the value ** only once where there exist duplicate prefixes). */ for(i=0; i<nSample; i++){ if( i==(pIdx->nSample-1) || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){ sumEq += aSample[i].anEq[iCol]; nSum100 += 100; } } if( nDist100>nSum100 && sumEq<nRow ){ avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100); } if( avgEq==0 ) avgEq = 1; pIdx->aAvgEq[iCol] = avgEq; } } } /* ** Look up an index by name. Or, if the name of a WITHOUT ROWID table ** is supplied instead, find the PRIMARY KEY index for that table. */ static Index *findIndexOrPrimaryKey( sqlite3 *db, const char *zName, const char *zDb ){ Index *pIdx = sqlite3FindIndex(db, zName, zDb); if( pIdx==0 ){ Table *pTab = sqlite3FindTable(db, zName, zDb); if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab); } return pIdx; } /* ** Load the content from either the sqlite_stat4 or sqlite_stat3 table ** into the relevant Index.aSample[] arrays. ** ** Arguments zSql1 and zSql2 must point to SQL statements that return ** data equivalent to the following (statements are different for stat3, ** see the caller of this function for details): ** ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4 ** ** where %Q is replaced with the database name before the SQL is executed. */ static int loadStatTbl( sqlite3 *db, /* Database handle */ int bStat3, /* Assume single column records only */ const char *zSql1, /* SQL statement 1 (see above) */ const char *zSql2, /* SQL statement 2 (see above) */ const char *zDb /* Database name (e.g. "main") */ ){ int rc; /* Result codes from subroutines */ sqlite3_stmt *pStmt = 0; /* An SQL statement being run */ char *zSql; /* Text of the SQL statement */ Index *pPrevIdx = 0; /* Previous index in the loop */ IndexSample *pSample; /* A slot in pIdx->aSample[] */ assert( db->lookaside.bDisable ); zSql = sqlite3MPrintf(db, zSql1, zDb); if( !zSql ){ return SQLITE_NOMEM_BKPT; } rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); sqlite3DbFree(db, zSql); if( rc ) return rc; while( sqlite3_step(pStmt)==SQLITE_ROW ){ int nIdxCol = 1; /* Number of columns in stat4 records */ char *zIndex; /* Index name */ Index *pIdx; /* Pointer to the index object */ int nSample; /* Number of samples */ int nByte; /* Bytes of space required */ int i; /* Bytes of space required */ tRowcnt *pSpace; zIndex = (char *)sqlite3_column_text(pStmt, 0); if( zIndex==0 ) continue; nSample = sqlite3_column_int(pStmt, 1); pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); assert( pIdx==0 || bStat3 || pIdx->nSample==0 ); /* Index.nSample is non-zero at this point if data has already been ** loaded from the stat4 table. In this case ignore stat3 data. */ if( pIdx==0 || pIdx->nSample ) continue; if( bStat3==0 ){ assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 ); if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){ nIdxCol = pIdx->nKeyCol; }else{ nIdxCol = pIdx->nColumn; } } pIdx->nSampleCol = nIdxCol; nByte = sizeof(IndexSample) * nSample; nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample; nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */ pIdx->aSample = sqlite3DbMallocZero(db, nByte); if( pIdx->aSample==0 ){ sqlite3_finalize(pStmt); return SQLITE_NOMEM_BKPT; } pSpace = (tRowcnt*)&pIdx->aSample[nSample]; pIdx->aAvgEq = pSpace; pSpace += nIdxCol; for(i=0; i<nSample; i++){ pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol; pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol; pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol; } assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) ); } rc = sqlite3_finalize(pStmt); if( rc ) return rc; zSql = sqlite3MPrintf(db, zSql2, zDb); if( !zSql ){ return SQLITE_NOMEM_BKPT; } rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); sqlite3DbFree(db, zSql); if( rc ) return rc; while( sqlite3_step(pStmt)==SQLITE_ROW ){ char *zIndex; /* Index name */ Index *pIdx; /* Pointer to the index object */ int nCol = 1; /* Number of columns in index */ zIndex = (char *)sqlite3_column_text(pStmt, 0); if( zIndex==0 ) continue; pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); if( pIdx==0 ) continue; /* This next condition is true if data has already been loaded from ** the sqlite_stat4 table. In this case ignore stat3 data. */ nCol = pIdx->nSampleCol; if( bStat3 && nCol>1 ) continue; if( pIdx!=pPrevIdx ){ initAvgEq(pPrevIdx); pPrevIdx = pIdx; } pSample = &pIdx->aSample[pIdx->nSample]; decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0); decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0); decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0); /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer. ** This is in case the sample record is corrupted. In that case, the ** sqlite3VdbeRecordCompare() may read up to two varints past the ** end of the allocated buffer before it realizes it is dealing with ** a corrupt record. Adding the two 0x00 bytes prevents this from causing ** a buffer overread. */ pSample->n = sqlite3_column_bytes(pStmt, 4); pSample->p = sqlite3DbMallocZero(db, pSample->n + 2); if( pSample->p==0 ){ sqlite3_finalize(pStmt); return SQLITE_NOMEM_BKPT; } if( pSample->n ){ memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n); } pIdx->nSample++; } rc = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ) initAvgEq(pPrevIdx); return rc; } /* ** Load content from the sqlite_stat4 and sqlite_stat3 tables into ** the Index.aSample[] arrays of all indices. */ static int loadStat4(sqlite3 *db, const char *zDb){ int rc = SQLITE_OK; /* Result codes from subroutines */ assert( db->lookaside.bDisable ); if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){ rc = loadStatTbl(db, 0, "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4", zDb ); } if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){ rc = loadStatTbl(db, 1, "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3", zDb ); } return rc; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] ** arrays. The contents of sqlite_stat3/4 are used to populate the ** Index.aSample[] arrays. ** ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined ** during compilation and the sqlite_stat3/4 table is present, no data is ** read from it. ** ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is ** returned. However, in this case, data is read from the sqlite_stat1 ** table (if it is present) before returning. ** ** If an OOM error occurs, this function always sets db->mallocFailed. ** This means if the caller does not care about other errors, the return ** code may be ignored. */ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ analysisInfo sInfo; HashElem *i; char *zSql; int rc = SQLITE_OK; assert( iDb>=0 && iDb<db->nDb ); assert( db->aDb[iDb].pBt!=0 ); /* Clear any prior statistics */ assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); pIdx->aiRowLogEst[0] = 0; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3DeleteIndexSamples(db, pIdx); pIdx->aSample = 0; #endif } /* Load new statistics out of the sqlite_stat1 table */ sInfo.db = db; sInfo.zDatabase = db->aDb[iDb].zDbSName; if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){ zSql = sqlite3MPrintf(db, "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase); if( zSql==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); sqlite3DbFree(db, zSql); } } /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */ assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx); } /* Load the statistics from the sqlite_stat4 table. */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){ db->lookaside.bDisable++; rc = loadStat4(db, sInfo.zDatabase); db->lookaside.bDisable--; } for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); sqlite3_free(pIdx->aiRowEst); pIdx->aiRowEst = 0; } #endif if( rc==SQLITE_NOMEM ){ sqlite3OomFault(db); } return rc; } #endif /* SQLITE_OMIT_ANALYZE */ /************** End of analyze.c *********************************************/ /************** Begin file attach.c ******************************************/ /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the ATTACH and DETACH commands. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_ATTACH /* ** Resolve an expression that was part of an ATTACH or DETACH statement. This ** is slightly different from resolving a normal SQL expression, because simple ** identifiers are treated as strings, not possible column names or aliases. ** ** i.e. if the parser sees: ** ** ATTACH DATABASE abc AS def ** ** it treats the two expressions as literal strings 'abc' and 'def' instead of ** looking for columns of the same name. ** ** This only applies to the root node of pExpr, so the statement: ** ** ATTACH DATABASE abc||def AS 'db2' ** ** will fail because neither abc or def can be resolved. */ static int resolveAttachExpr(NameContext *pName, Expr *pExpr) { int rc = SQLITE_OK; if( pExpr ){ if( pExpr->op!=TK_ID ){ rc = sqlite3ResolveExprNames(pName, pExpr); }else{ pExpr->op = TK_STRING; } } return rc; } /* ** An SQL user-function registered to do the work of an ATTACH statement. The ** three arguments to the function come directly from an attach statement: ** ** ATTACH DATABASE x AS y KEY z ** ** SELECT sqlite_attach(x, y, z) ** ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the ** third argument. */ static void attachFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ int i; int rc = 0; sqlite3 *db = sqlite3_context_db_handle(context); const char *zName; const char *zFile; char *zPath = 0; char *zErr = 0; unsigned int flags; Db *aNew; char *zErrDyn = 0; sqlite3_vfs *pVfs; UNUSED_PARAMETER(NotUsed); zFile = (const char *)sqlite3_value_text(argv[0]); zName = (const char *)sqlite3_value_text(argv[1]); if( zFile==0 ) zFile = ""; if( zName==0 ) zName = ""; /* Check for the following errors: ** ** * Too many attached databases, ** * Transaction currently open ** * Specified database name already being used. */ if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){ zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", db->aLimit[SQLITE_LIMIT_ATTACHED] ); goto attach_error; } if( !db->autoCommit ){ zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction"); goto attach_error; } for(i=0; i<db->nDb; i++){ char *z = db->aDb[i].zDbSName; assert( z && zName ); if( sqlite3StrICmp(z, zName)==0 ){ zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName); goto attach_error; } } /* Allocate the new entry in the db->aDb[] array and initialize the schema ** hash tables. */ if( db->aDb==db->aDbStatic ){ aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 ); if( aNew==0 ) return; memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); }else{ aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); if( aNew==0 ) return; } db->aDb = aNew; aNew = &db->aDb[db->nDb]; memset(aNew, 0, sizeof(*aNew)); /* Open the database file. If the btree is successfully opened, use ** it to obtain the database schema. At this point the schema may ** or may not be initialized. */ flags = db->openFlags; rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr); if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); sqlite3_result_error(context, zErr, -1); sqlite3_free(zErr); return; } assert( pVfs ); flags |= SQLITE_OPEN_MAIN_DB; rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags); sqlite3_free( zPath ); db->nDb++; db->skipBtreeMutex = 0; if( rc==SQLITE_CONSTRAINT ){ rc = SQLITE_ERROR; zErrDyn = sqlite3MPrintf(db, "database is already attached"); }else if( rc==SQLITE_OK ){ Pager *pPager; aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt); if( !aNew->pSchema ){ rc = SQLITE_NOMEM_BKPT; }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){ zErrDyn = sqlite3MPrintf(db, "attached databases must use the same text encoding as main database"); rc = SQLITE_ERROR; } sqlite3BtreeEnter(aNew->pBt); pPager = sqlite3BtreePager(aNew->pBt); sqlite3PagerLockingMode(pPager, db->dfltLockMode); sqlite3BtreeSecureDelete(aNew->pBt, sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) ); #ifndef SQLITE_OMIT_PAGER_PRAGMAS sqlite3BtreeSetPagerFlags(aNew->pBt, PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK)); #endif sqlite3BtreeLeave(aNew->pBt); } aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; aNew->zDbSName = sqlite3DbStrDup(db, zName); if( rc==SQLITE_OK && aNew->zDbSName==0 ){ rc = SQLITE_NOMEM_BKPT; } #ifdef SQLITE_HAS_CODEC if( rc==SQLITE_OK ){ extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); int nKey; char *zKey; int t = sqlite3_value_type(argv[2]); switch( t ){ case SQLITE_INTEGER: case SQLITE_FLOAT: zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); rc = SQLITE_ERROR; break; case SQLITE_TEXT: case SQLITE_BLOB: nKey = sqlite3_value_bytes(argv[2]); zKey = (char *)sqlite3_value_blob(argv[2]); rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); break; case SQLITE_NULL: /* No key specified. Use the key from the main database */ sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){ rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); } break; } } #endif /* If the file was opened successfully, read the schema for the new database. ** If this fails, or if opening the file failed, then close the file and ** remove the entry from the db->aDb[] array. i.e. put everything back the way ** we found it. */ if( rc==SQLITE_OK ){ sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, &zErrDyn); sqlite3BtreeLeaveAll(db); } #ifdef SQLITE_USER_AUTHENTICATION if( rc==SQLITE_OK ){ u8 newAuth = 0; rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth); if( newAuth<db->auth.authLevel ){ rc = SQLITE_AUTH_USER; } } #endif if( rc ){ int iDb = db->nDb - 1; assert( iDb>=2 ); if( db->aDb[iDb].pBt ){ sqlite3BtreeClose(db->aDb[iDb].pBt); db->aDb[iDb].pBt = 0; db->aDb[iDb].pSchema = 0; } sqlite3ResetAllSchemasOfConnection(db); db->nDb = iDb; if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ sqlite3OomFault(db); sqlite3DbFree(db, zErrDyn); zErrDyn = sqlite3MPrintf(db, "out of memory"); }else if( zErrDyn==0 ){ zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile); } goto attach_error; } return; attach_error: /* Return an error if we get here */ if( zErrDyn ){ sqlite3_result_error(context, zErrDyn, -1); sqlite3DbFree(db, zErrDyn); } if( rc ) sqlite3_result_error_code(context, rc); } /* ** An SQL user-function registered to do the work of an DETACH statement. The ** three arguments to the function come directly from a detach statement: ** ** DETACH DATABASE x ** ** SELECT sqlite_detach(x) */ static void detachFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ const char *zName = (const char *)sqlite3_value_text(argv[0]); sqlite3 *db = sqlite3_context_db_handle(context); int i; Db *pDb = 0; char zErr[128]; UNUSED_PARAMETER(NotUsed); if( zName==0 ) zName = ""; for(i=0; i<db->nDb; i++){ pDb = &db->aDb[i]; if( pDb->pBt==0 ) continue; if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break; } if( i>=db->nDb ){ sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName); goto detach_error; } if( i<2 ){ sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName); goto detach_error; } if( !db->autoCommit ){ sqlite3_snprintf(sizeof(zErr), zErr, "cannot DETACH database within transaction"); goto detach_error; } if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){ sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName); goto detach_error; } sqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; pDb->pSchema = 0; sqlite3CollapseDatabaseArray(db); return; detach_error: sqlite3_result_error(context, zErr, -1); } /* ** This procedure generates VDBE code for a single invocation of either the ** sqlite_detach() or sqlite_attach() SQL user functions. */ static void codeAttach( Parse *pParse, /* The parser context */ int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */ FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */ Expr *pAuthArg, /* Expression to pass to authorization callback */ Expr *pFilename, /* Name of database file */ Expr *pDbname, /* Name of the database to use internally */ Expr *pKey /* Database key for encryption extension */ ){ int rc; NameContext sName; Vdbe *v; sqlite3* db = pParse->db; int regArgs; if( pParse->nErr ) goto attach_end; memset(&sName, 0, sizeof(NameContext)); sName.pParse = pParse; if( SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) || SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) || SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey)) ){ goto attach_end; } #ifndef SQLITE_OMIT_AUTHORIZATION if( pAuthArg ){ char *zAuthArg; if( pAuthArg->op==TK_STRING ){ zAuthArg = pAuthArg->u.zToken; }else{ zAuthArg = 0; } rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); if(rc!=SQLITE_OK ){ goto attach_end; } } #endif /* SQLITE_OMIT_AUTHORIZATION */ v = sqlite3GetVdbe(pParse); regArgs = sqlite3GetTempRange(pParse, 4); sqlite3ExprCode(pParse, pFilename, regArgs); sqlite3ExprCode(pParse, pDbname, regArgs+1); sqlite3ExprCode(pParse, pKey, regArgs+2); assert( v || db->mallocFailed ); if( v ){ sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3, (char *)pFunc, P4_FUNCDEF); assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg ); sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg)); /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this ** statement only). For DETACH, set it to false (expire all existing ** statements). */ sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); } attach_end: sqlite3ExprDelete(db, pFilename); sqlite3ExprDelete(db, pDbname); sqlite3ExprDelete(db, pKey); } /* ** Called by the parser to compile a DETACH statement. ** ** DETACH pDbname */ SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){ static const FuncDef detach_func = { 1, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ detachFunc, /* xSFunc */ 0, /* xFinalize */ "sqlite_detach", /* zName */ {0} }; codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname); } /* ** Called by the parser to compile an ATTACH statement. ** ** ATTACH p AS pDbname KEY pKey */ SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){ static const FuncDef attach_func = { 3, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ attachFunc, /* xSFunc */ 0, /* xFinalize */ "sqlite_attach", /* zName */ {0} }; codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey); } #endif /* SQLITE_OMIT_ATTACH */ /* ** Initialize a DbFixer structure. This routine must be called prior ** to passing the structure to one of the sqliteFixAAAA() routines below. */ SQLITE_PRIVATE void sqlite3FixInit( DbFixer *pFix, /* The fixer to be initialized */ Parse *pParse, /* Error messages will be written here */ int iDb, /* This is the database that must be used */ const char *zType, /* "view", "trigger", or "index" */ const Token *pName /* Name of the view, trigger, or index */ ){ sqlite3 *db; db = pParse->db; assert( db->nDb>iDb ); pFix->pParse = pParse; pFix->zDb = db->aDb[iDb].zDbSName; pFix->pSchema = db->aDb[iDb].pSchema; pFix->zType = zType; pFix->pName = pName; pFix->bVarOnly = (iDb==1); } /* ** The following set of routines walk through the parse tree and assign ** a specific database to all table references where the database name ** was left unspecified in the original SQL statement. The pFix structure ** must have been initialized by a prior call to sqlite3FixInit(). ** ** These routines are used to make sure that an index, trigger, or ** view in one database does not refer to objects in a different database. ** (Exception: indices, triggers, and views in the TEMP database are ** allowed to refer to anything.) If a reference is explicitly made ** to an object in a different database, an error message is added to ** pParse->zErrMsg and these routines return non-zero. If everything ** checks out, these routines return 0. */ SQLITE_PRIVATE int sqlite3FixSrcList( DbFixer *pFix, /* Context of the fixation */ SrcList *pList /* The Source list to check and modify */ ){ int i; const char *zDb; struct SrcList_item *pItem; if( NEVER(pList==0) ) return 0; zDb = pFix->zDb; for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ if( pFix->bVarOnly==0 ){ if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){ sqlite3ErrorMsg(pFix->pParse, "%s %T cannot reference objects in database %s", pFix->zType, pFix->pName, pItem->zDatabase); return 1; } sqlite3DbFree(pFix->pParse->db, pItem->zDatabase); pItem->zDatabase = 0; pItem->pSchema = pFix->pSchema; } #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1; if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1; #endif } return 0; } #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) SQLITE_PRIVATE int sqlite3FixSelect( DbFixer *pFix, /* Context of the fixation */ Select *pSelect /* The SELECT statement to be fixed to one database */ ){ while( pSelect ){ if( sqlite3FixExprList(pFix, pSelect->pEList) ){ return 1; } if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){ return 1; } if( sqlite3FixExpr(pFix, pSelect->pWhere) ){ return 1; } if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){ return 1; } if( sqlite3FixExpr(pFix, pSelect->pHaving) ){ return 1; } if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){ return 1; } if( sqlite3FixExpr(pFix, pSelect->pLimit) ){ return 1; } if( sqlite3FixExpr(pFix, pSelect->pOffset) ){ return 1; } pSelect = pSelect->pPrior; } return 0; } SQLITE_PRIVATE int sqlite3FixExpr( DbFixer *pFix, /* Context of the fixation */ Expr *pExpr /* The expression to be fixed to one database */ ){ while( pExpr ){ if( pExpr->op==TK_VARIABLE ){ if( pFix->pParse->db->init.busy ){ pExpr->op = TK_NULL; }else{ sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType); return 1; } } if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1; }else{ if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1; } if( sqlite3FixExpr(pFix, pExpr->pRight) ){ return 1; } pExpr = pExpr->pLeft; } return 0; } SQLITE_PRIVATE int sqlite3FixExprList( DbFixer *pFix, /* Context of the fixation */ ExprList *pList /* The expression to be fixed to one database */ ){ int i; struct ExprList_item *pItem; if( pList==0 ) return 0; for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){ if( sqlite3FixExpr(pFix, pItem->pExpr) ){ return 1; } } return 0; } #endif #ifndef SQLITE_OMIT_TRIGGER SQLITE_PRIVATE int sqlite3FixTriggerStep( DbFixer *pFix, /* Context of the fixation */ TriggerStep *pStep /* The trigger step be fixed to one database */ ){ while( pStep ){ if( sqlite3FixSelect(pFix, pStep->pSelect) ){ return 1; } if( sqlite3FixExpr(pFix, pStep->pWhere) ){ return 1; } if( sqlite3FixExprList(pFix, pStep->pExprList) ){ return 1; } pStep = pStep->pNext; } return 0; } #endif /************** End of attach.c **********************************************/ /************** Begin file auth.c ********************************************/ /* ** 2003 January 11 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the sqlite3_set_authorizer() ** API. This facility is an optional feature of the library. Embedded ** systems that do not need this facility may omit it by recompiling ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 */ /* #include "sqliteInt.h" */ /* ** All of the code in this file may be omitted by defining a single ** macro. */ #ifndef SQLITE_OMIT_AUTHORIZATION /* ** Set or clear the access authorization function. ** ** The access authorization function is be called during the compilation ** phase to verify that the user has read and/or write access permission on ** various fields of the database. The first argument to the auth function ** is a copy of the 3rd argument to this routine. The second argument ** to the auth function is one of these constants: ** ** SQLITE_CREATE_INDEX ** SQLITE_CREATE_TABLE ** SQLITE_CREATE_TEMP_INDEX ** SQLITE_CREATE_TEMP_TABLE ** SQLITE_CREATE_TEMP_TRIGGER ** SQLITE_CREATE_TEMP_VIEW ** SQLITE_CREATE_TRIGGER ** SQLITE_CREATE_VIEW ** SQLITE_DELETE ** SQLITE_DROP_INDEX ** SQLITE_DROP_TABLE ** SQLITE_DROP_TEMP_INDEX ** SQLITE_DROP_TEMP_TABLE ** SQLITE_DROP_TEMP_TRIGGER ** SQLITE_DROP_TEMP_VIEW ** SQLITE_DROP_TRIGGER ** SQLITE_DROP_VIEW ** SQLITE_INSERT ** SQLITE_PRAGMA ** SQLITE_READ ** SQLITE_SELECT ** SQLITE_TRANSACTION ** SQLITE_UPDATE ** ** The third and fourth arguments to the auth function are the name of ** the table and the column that are being accessed. The auth function ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY ** means that the SQL statement will never-run - the sqlite3_exec() call ** will return with an error. SQLITE_IGNORE means that the SQL statement ** should run but attempts to read the specified column will return NULL ** and attempts to write the column will be ignored. ** ** Setting the auth function to NULL disables this hook. The default ** setting of the auth function is NULL. */ SQLITE_API int sqlite3_set_authorizer( sqlite3 *db, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->xAuth = (sqlite3_xauth)xAuth; db->pAuthArg = pArg; sqlite3ExpirePreparedStatements(db); sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Write an error message into pParse->zErrMsg that explains that the ** user-supplied authorization function returned an illegal value. */ static void sqliteAuthBadReturnCode(Parse *pParse){ sqlite3ErrorMsg(pParse, "authorizer malfunction"); pParse->rc = SQLITE_ERROR; } /* ** Invoke the authorization callback for permission to read column zCol from ** table zTab in database zDb. This function assumes that an authorization ** callback has been registered (i.e. that sqlite3.xAuth is not NULL). ** ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE ** is treated as SQLITE_DENY. In this case an error is left in pParse. */ SQLITE_PRIVATE int sqlite3AuthReadCol( Parse *pParse, /* The parser context */ const char *zTab, /* Table name */ const char *zCol, /* Column name */ int iDb /* Index of containing database. */ ){ sqlite3 *db = pParse->db; /* Database handle */ char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */ int rc; /* Auth callback return code */ if( db->init.busy ) return SQLITE_OK; rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext #ifdef SQLITE_USER_AUTHENTICATION ,db->auth.zAuthUser #endif ); if( rc==SQLITE_DENY ){ if( db->nDb>2 || iDb!=0 ){ sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol); }else{ sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol); } pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ sqliteAuthBadReturnCode(pParse); } return rc; } /* ** The pExpr should be a TK_COLUMN expression. The table referred to ** is in pTabList or else it is the NEW or OLD table of a trigger. ** Check to see if it is OK to read this particular column. ** ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, ** then generate an error. */ SQLITE_PRIVATE void sqlite3AuthRead( Parse *pParse, /* The parser context */ Expr *pExpr, /* The expression to check authorization on */ Schema *pSchema, /* The schema of the expression */ SrcList *pTabList /* All table that pExpr might refer to */ ){ sqlite3 *db = pParse->db; Table *pTab = 0; /* The table being read */ const char *zCol; /* Name of the column of the table */ int iSrc; /* Index in pTabList->a[] of table being read */ int iDb; /* The index of the database the expression refers to */ int iCol; /* Index of column in table */ if( db->xAuth==0 ) return; iDb = sqlite3SchemaToIndex(pParse->db, pSchema); if( iDb<0 ){ /* An attempt to read a column out of a subquery or other ** temporary table. */ return; } assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); if( pExpr->op==TK_TRIGGER ){ pTab = pParse->pTriggerTab; }else{ assert( pTabList ); for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){ if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ pTab = pTabList->a[iSrc].pTab; break; } } } iCol = pExpr->iColumn; if( NEVER(pTab==0) ) return; if( iCol>=0 ){ assert( iCol<pTab->nCol ); zCol = pTab->aCol[iCol].zName; }else if( pTab->iPKey>=0 ){ assert( pTab->iPKey<pTab->nCol ); zCol = pTab->aCol[pTab->iPKey].zName; }else{ zCol = "ROWID"; } assert( iDb>=0 && iDb<db->nDb ); if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ pExpr->op = TK_NULL; } } /* ** Do an authorization check using the code and arguments given. Return ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY ** is returned, then the error count and error message in pParse are ** modified appropriately. */ SQLITE_PRIVATE int sqlite3AuthCheck( Parse *pParse, int code, const char *zArg1, const char *zArg2, const char *zArg3 ){ sqlite3 *db = pParse->db; int rc; /* Don't do any authorization checks if the database is initialising ** or if the parser is being invoked from within sqlite3_declare_vtab. */ if( db->init.busy || IN_DECLARE_VTAB ){ return SQLITE_OK; } if( db->xAuth==0 ){ return SQLITE_OK; } rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext #ifdef SQLITE_USER_AUTHENTICATION ,db->auth.zAuthUser #endif ); if( rc==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized"); pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ rc = SQLITE_DENY; sqliteAuthBadReturnCode(pParse); } return rc; } /* ** Push an authorization context. After this routine is called, the ** zArg3 argument to authorization callbacks will be zContext until ** popped. Or if pParse==0, this routine is a no-op. */ SQLITE_PRIVATE void sqlite3AuthContextPush( Parse *pParse, AuthContext *pContext, const char *zContext ){ assert( pParse ); pContext->pParse = pParse; pContext->zAuthContext = pParse->zAuthContext; pParse->zAuthContext = zContext; } /* ** Pop an authorization context that was previously pushed ** by sqlite3AuthContextPush */ SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){ if( pContext->pParse ){ pContext->pParse->zAuthContext = pContext->zAuthContext; pContext->pParse = 0; } } #endif /* SQLITE_OMIT_AUTHORIZATION */ /************** End of auth.c ************************************************/ /************** Begin file build.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the SQLite parser ** when syntax rules are reduced. The routines in this file handle the ** following kinds of SQL syntax: ** ** CREATE TABLE ** DROP TABLE ** CREATE INDEX ** DROP INDEX ** creating ID lists ** BEGIN TRANSACTION ** COMMIT ** ROLLBACK */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_SHARED_CACHE /* ** The TableLock structure is only used by the sqlite3TableLock() and ** codeTableLocks() functions. */ struct TableLock { int iDb; /* The database containing the table to be locked */ int iTab; /* The root page of the table to be locked */ u8 isWriteLock; /* True for write lock. False for a read lock */ const char *zLockName; /* Name of the table */ }; /* ** Record the fact that we want to lock a table at run-time. ** ** The table to be locked has root page iTab and is found in database iDb. ** A read or a write lock can be taken depending on isWritelock. ** ** This routine just records the fact that the lock is desired. The ** code to make the lock occur is generated by a later call to ** codeTableLocks() which occurs during sqlite3FinishCoding(). */ SQLITE_PRIVATE void sqlite3TableLock( Parse *pParse, /* Parsing context */ int iDb, /* Index of the database containing the table to lock */ int iTab, /* Root page number of the table to be locked */ u8 isWriteLock, /* True for a write lock */ const char *zName /* Name of the table to be locked */ ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); int i; int nBytes; TableLock *p; assert( iDb>=0 ); if( iDb==1 ) return; if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return; for(i=0; i<pToplevel->nTableLock; i++){ p = &pToplevel->aTableLock[i]; if( p->iDb==iDb && p->iTab==iTab ){ p->isWriteLock = (p->isWriteLock || isWriteLock); return; } } nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); pToplevel->aTableLock = sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); if( pToplevel->aTableLock ){ p = &pToplevel->aTableLock[pToplevel->nTableLock++]; p->iDb = iDb; p->iTab = iTab; p->isWriteLock = isWriteLock; p->zLockName = zName; }else{ pToplevel->nTableLock = 0; sqlite3OomFault(pToplevel->db); } } /* ** Code an OP_TableLock instruction for each table locked by the ** statement (configured by calls to sqlite3TableLock()). */ static void codeTableLocks(Parse *pParse){ int i; Vdbe *pVdbe; pVdbe = sqlite3GetVdbe(pParse); assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ for(i=0; i<pParse->nTableLock; i++){ TableLock *p = &pParse->aTableLock[i]; int p1 = p->iDb; sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, p->zLockName, P4_STATIC); } } #else #define codeTableLocks(x) #endif /* ** Return TRUE if the given yDbMask object is empty - if it contains no ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero() ** macros when SQLITE_MAX_ATTACHED is greater than 30. */ #if SQLITE_MAX_ATTACHED>30 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){ int i; for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0; return 1; } #endif /* ** This routine is called after a single SQL statement has been ** parsed and a VDBE program to execute that statement has been ** prepared. This routine puts the finishing touches on the ** VDBE program and resets the pParse structure for the next ** parse. ** ** Note that if an error occurred, it might be the case that ** no VDBE code was generated. */ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ sqlite3 *db; Vdbe *v; assert( pParse->pToplevel==0 ); db = pParse->db; if( pParse->nested ) return; if( db->mallocFailed || pParse->nErr ){ if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR; return; } /* Begin by generating some termination code at the end of the ** vdbe program */ v = sqlite3GetVdbe(pParse); assert( !pParse->isMultiWrite || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); if( v ){ sqlite3VdbeAddOp0(v, OP_Halt); #if SQLITE_USER_AUTHENTICATION if( pParse->nTableLock>0 && db->init.busy==0 ){ sqlite3UserAuthInit(db); if( db->auth.authLevel<UAUTH_User ){ sqlite3ErrorMsg(pParse, "user not authenticated"); pParse->rc = SQLITE_AUTH_USER; return; } } #endif /* The cookie mask contains one bit for each database file open. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are ** set for each database that is used. Generate code to start a ** transaction on each used database and to verify the schema cookie ** on each used database. */ if( db->mallocFailed==0 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) ){ int iDb, i; assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); sqlite3VdbeJumpHere(v, 0); for(iDb=0; iDb<db->nDb; iDb++){ Schema *pSchema; if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; sqlite3VdbeUsesBtree(v, iDb); pSchema = db->aDb[iDb].pSchema; sqlite3VdbeAddOp4Int(v, OP_Transaction, /* Opcode */ iDb, /* P1 */ DbMaskTest(pParse->writeMask,iDb), /* P2 */ pSchema->schema_cookie, /* P3 */ pSchema->iGeneration /* P4 */ ); if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); VdbeComment((v, "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite)); } #ifndef SQLITE_OMIT_VIRTUALTABLE for(i=0; i<pParse->nVtabLock; i++){ char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); } pParse->nVtabLock = 0; #endif /* Once all the cookies have been verified and transactions opened, ** obtain the required table-locks. This is a no-op unless the ** shared-cache feature is enabled. */ codeTableLocks(pParse); /* Initialize any AUTOINCREMENT data structures required. */ sqlite3AutoincrementBegin(pParse); /* Code constant expressions that where factored out of inner loops */ if( pParse->pConstExpr ){ ExprList *pEL = pParse->pConstExpr; pParse->okConstFactor = 0; for(i=0; i<pEL->nExpr; i++){ sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg); } } /* Finally, jump back to the beginning of the executable code. */ sqlite3VdbeGoto(v, 1); } } /* Get the VDBE program ready for execution */ if( v && pParse->nErr==0 && !db->mallocFailed ){ assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ /* A minimum of one cursor is required if autoincrement is used * See ticket [a696379c1f08866] */ if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; sqlite3VdbeMakeReady(v, pParse); pParse->rc = SQLITE_DONE; }else{ pParse->rc = SQLITE_ERROR; } } /* ** Run the parser and code generator recursively in order to generate ** code for the SQL statement given onto the end of the pParse context ** currently under construction. When the parser is run recursively ** this way, the final OP_Halt is not appended and other initialization ** and finalization steps are omitted because those are handling by the ** outermost parser. ** ** Not everything is nestable. This facility is designed to permit ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use ** care if you decide to try to use this routine for some other purposes. */ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ va_list ap; char *zSql; char *zErrMsg = 0; sqlite3 *db = pParse->db; char saveBuf[PARSE_TAIL_SZ]; if( pParse->nErr ) return; assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ va_start(ap, zFormat); zSql = sqlite3VMPrintf(db, zFormat, ap); va_end(ap); if( zSql==0 ){ return; /* A malloc must have failed */ } pParse->nested++; memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); sqlite3RunParser(pParse, zSql, &zErrMsg); sqlite3DbFree(db, zErrMsg); sqlite3DbFree(db, zSql); memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); pParse->nested--; } #if SQLITE_USER_AUTHENTICATION /* ** Return TRUE if zTable is the name of the system table that stores the ** list of users and their access credentials. */ SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){ return sqlite3_stricmp(zTable, "sqlite_user")==0; } #endif /* ** Locate the in-memory structure that describes a particular database ** table given the name of that table and (optionally) the name of the ** database containing the table. Return NULL if not found. ** ** If zDatabase is 0, all databases are searched for the table and the ** first matching table is returned. (No checking for duplicate table ** names is done.) The search order is TEMP first, then MAIN, then any ** auxiliary databases added using the ATTACH command. ** ** See also sqlite3LocateTable(). */ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ Table *p = 0; int i; /* All mutexes are required for schema access. Make sure we hold them. */ assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); #if SQLITE_USER_AUTHENTICATION /* Only the admin user is allowed to know that the sqlite_user table ** exists */ if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){ return 0; } #endif while(1){ for(i=OMIT_TEMPDB; i<db->nDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){ assert( sqlite3SchemaMutexHeld(db, j, 0) ); p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName); if( p ) return p; } } /* Not found. If the name we were looking for was temp.sqlite_master ** then change the name to sqlite_temp_master and try again. */ if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break; if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break; zName = TEMP_MASTER_NAME; } return 0; } /* ** Locate the in-memory structure that describes a particular database ** table given the name of that table and (optionally) the name of the ** database containing the table. Return NULL if not found. Also leave an ** error message in pParse->zErrMsg. ** ** The difference between this routine and sqlite3FindTable() is that this ** routine leaves an error message in pParse->zErrMsg where ** sqlite3FindTable() does not. */ SQLITE_PRIVATE Table *sqlite3LocateTable( Parse *pParse, /* context in which to report errors */ u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */ const char *zName, /* Name of the table we are looking for */ const char *zDbase /* Name of the database. Might be NULL */ ){ Table *p; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ return 0; } p = sqlite3FindTable(pParse->db, zName, zDbase); if( p==0 ){ const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; #ifndef SQLITE_OMIT_VIRTUALTABLE if( sqlite3FindDbName(pParse->db, zDbase)<1 ){ /* If zName is the not the name of a table in the schema created using ** CREATE, then check to see if it is the name of an virtual table that ** can be an eponymous virtual table. */ Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName); if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){ pMod = sqlite3PragmaVtabRegister(pParse->db, zName); } if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ return pMod->pEpoTab; } } #endif if( (flags & LOCATE_NOERR)==0 ){ if( zDbase ){ sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); }else{ sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); } pParse->checkSchema = 1; } } return p; } /* ** Locate the table identified by *p. ** ** This is a wrapper around sqlite3LocateTable(). The difference between ** sqlite3LocateTable() and this function is that this function restricts ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be ** non-NULL if it is part of a view or trigger program definition. See ** sqlite3FixSrcList() for details. */ SQLITE_PRIVATE Table *sqlite3LocateTableItem( Parse *pParse, u32 flags, struct SrcList_item *p ){ const char *zDb; assert( p->pSchema==0 || p->zDatabase==0 ); if( p->pSchema ){ int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); zDb = pParse->db->aDb[iDb].zDbSName; }else{ zDb = p->zDatabase; } return sqlite3LocateTable(pParse, flags, p->zName, zDb); } /* ** Locate the in-memory structure that describes ** a particular index given the name of that index ** and the name of the database that contains the index. ** Return NULL if not found. ** ** If zDatabase is 0, all databases are searched for the ** table and the first matching index is returned. (No checking ** for duplicate index names is done.) The search order is ** TEMP first, then MAIN, then any auxiliary databases added ** using the ATTACH command. */ SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ Index *p = 0; int i; /* All mutexes are required for schema access. Make sure we hold them. */ assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); for(i=OMIT_TEMPDB; i<db->nDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ Schema *pSchema = db->aDb[j].pSchema; assert( pSchema ); if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue; assert( sqlite3SchemaMutexHeld(db, j, 0) ); p = sqlite3HashFind(&pSchema->idxHash, zName); if( p ) break; } return p; } /* ** Reclaim the memory used by an index */ static void freeIndex(sqlite3 *db, Index *p){ #ifndef SQLITE_OMIT_ANALYZE sqlite3DeleteIndexSamples(db, p); #endif sqlite3ExprDelete(db, p->pPartIdxWhere); sqlite3ExprListDelete(db, p->aColExpr); sqlite3DbFree(db, p->zColAff); if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3_free(p->aiRowEst); #endif sqlite3DbFree(db, p); } /* ** For the index called zIdxName which is found in the database iDb, ** unlike that index from its Table then remove the index from ** the index hash table and free all memory structures associated ** with the index. */ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ Index *pIndex; Hash *pHash; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pHash = &db->aDb[iDb].pSchema->idxHash; pIndex = sqlite3HashInsert(pHash, zIdxName, 0); if( ALWAYS(pIndex) ){ if( pIndex->pTable->pIndex==pIndex ){ pIndex->pTable->pIndex = pIndex->pNext; }else{ Index *p; /* Justification of ALWAYS(); The index must be on the list of ** indices. */ p = pIndex->pTable->pIndex; while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } if( ALWAYS(p && p->pNext==pIndex) ){ p->pNext = pIndex->pNext; } } freeIndex(db, pIndex); } db->flags |= SQLITE_InternChanges; } /* ** Look through the list of open database files in db->aDb[] and if ** any have been closed, remove them from the list. Reallocate the ** db->aDb[] structure to a smaller size, if possible. ** ** Entry 0 (the "main" database) and entry 1 (the "temp" database) ** are never candidates for being collapsed. */ SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){ int i, j; for(i=j=2; i<db->nDb; i++){ struct Db *pDb = &db->aDb[i]; if( pDb->pBt==0 ){ sqlite3DbFree(db, pDb->zDbSName); pDb->zDbSName = 0; continue; } if( j<i ){ db->aDb[j] = db->aDb[i]; } j++; } db->nDb = j; if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); sqlite3DbFree(db, db->aDb); db->aDb = db->aDbStatic; } } /* ** Reset the schema for the database at index iDb. Also reset the ** TEMP schema. */ SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ Db *pDb; assert( iDb<db->nDb ); /* Case 1: Reset the single schema identified by iDb */ pDb = &db->aDb[iDb]; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); assert( pDb->pSchema!=0 ); sqlite3SchemaClear(pDb->pSchema); /* If any database other than TEMP is reset, then also reset TEMP ** since TEMP might be holding triggers that reference tables in the ** other database. */ if( iDb!=1 ){ pDb = &db->aDb[1]; assert( pDb->pSchema!=0 ); sqlite3SchemaClear(pDb->pSchema); } return; } /* ** Erase all schema information from all attached databases (including ** "main" and "temp") for a single database connection. */ SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ int i; sqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ Db *pDb = &db->aDb[i]; if( pDb->pSchema ){ sqlite3SchemaClear(pDb->pSchema); } } db->flags &= ~SQLITE_InternChanges; sqlite3VtabUnlockList(db); sqlite3BtreeLeaveAll(db); sqlite3CollapseDatabaseArray(db); } /* ** This routine is called when a commit occurs. */ SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){ db->flags &= ~SQLITE_InternChanges; } /* ** Delete memory allocated for the column names of a table or view (the ** Table.aCol[] array). */ SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ int i; Column *pCol; assert( pTable!=0 ); if( (pCol = pTable->aCol)!=0 ){ for(i=0; i<pTable->nCol; i++, pCol++){ sqlite3DbFree(db, pCol->zName); sqlite3ExprDelete(db, pCol->pDflt); sqlite3DbFree(db, pCol->zColl); } sqlite3DbFree(db, pTable->aCol); } } /* ** Remove the memory data structures associated with the given ** Table. No changes are made to disk by this routine. ** ** This routine just deletes the data structure. It does not unlink ** the table data structure from the hash table. But it does destroy ** memory structures of the indices and foreign keys associated with ** the table. ** ** The db parameter is optional. It is needed if the Table object ** contains lookaside memory. (Table objects in the schema do not use ** lookaside memory, but some ephemeral Table objects do.) Or the ** db parameter can be used with db->pnBytesFreed to measure the memory ** used by the Table object. */ static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){ Index *pIndex, *pNext; TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */ /* Record the number of outstanding lookaside allocations in schema Tables ** prior to doing any free() operations. Since schema Tables do not use ** lookaside, this number should not change. */ TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ? db->lookaside.nOut : 0 ); /* Delete all indices associated with this table. */ for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ pNext = pIndex->pNext; assert( pIndex->pSchema==pTable->pSchema || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) ); if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){ char *zName = pIndex->zName; TESTONLY ( Index *pOld = ) sqlite3HashInsert( &pIndex->pSchema->idxHash, zName, 0 ); assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); assert( pOld==pIndex || pOld==0 ); } freeIndex(db, pIndex); } /* Delete any foreign keys attached to this table. */ sqlite3FkDelete(db, pTable); /* Delete the Table structure itself. */ sqlite3DeleteColumnNames(db, pTable); sqlite3DbFree(db, pTable->zName); sqlite3DbFree(db, pTable->zColAff); sqlite3SelectDelete(db, pTable->pSelect); sqlite3ExprListDelete(db, pTable->pCheck); #ifndef SQLITE_OMIT_VIRTUALTABLE sqlite3VtabClear(db, pTable); #endif sqlite3DbFree(db, pTable); /* Verify that no lookaside memory was used by schema tables */ assert( nLookaside==0 || nLookaside==db->lookaside.nOut ); } SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ /* Do not delete the table until the reference count reaches zero. */ if( !pTable ) return; if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return; deleteTable(db, pTable); } /* ** Unlink the given table from the hash tables and the delete the ** table structure with all its indices and foreign keys. */ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ Table *p; Db *pDb; assert( db!=0 ); assert( iDb>=0 && iDb<db->nDb ); assert( zTabName ); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ pDb = &db->aDb[iDb]; p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); sqlite3DeleteTable(db, p); db->flags |= SQLITE_InternChanges; } /* ** Given a token, return a string that consists of the text of that ** token. Space to hold the returned string ** is obtained from sqliteMalloc() and must be freed by the calling ** function. ** ** Any quotation marks (ex: "name", 'name', [name], or `name`) that ** surround the body of the token are removed. ** ** Tokens are often just pointers into the original SQL text and so ** are not \000 terminated and are not persistent. The returned string ** is \000 terminated and is persistent. */ SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ char *zName; if( pName ){ zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); sqlite3Dequote(zName); }else{ zName = 0; } return zName; } /* ** Open the sqlite_master table stored in database number iDb for ** writing. The table is opened using cursor 0. */ SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){ Vdbe *v = sqlite3GetVdbe(p); sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME); sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5); if( p->nTab==0 ){ p->nTab = 1; } } /* ** Parameter zName points to a nul-terminated buffer containing the name ** of a database ("main", "temp" or the name of an attached db). This ** function returns the index of the named database in db->aDb[], or ** -1 if the named db cannot be found. */ SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){ int i = -1; /* Database number */ if( zName ){ Db *pDb; for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break; /* "main" is always an acceptable alias for the primary database ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */ if( i==0 && 0==sqlite3_stricmp("main", zName) ) break; } } return i; } /* ** The token *pName contains the name of a database (either "main" or ** "temp" or the name of an attached db). This routine returns the ** index of the named database in db->aDb[], or -1 if the named db ** does not exist. */ SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){ int i; /* Database number */ char *zName; /* Name we are searching for */ zName = sqlite3NameFromToken(db, pName); i = sqlite3FindDbName(db, zName); sqlite3DbFree(db, zName); return i; } /* The table or view or trigger name is passed to this routine via tokens ** pName1 and pName2. If the table name was fully qualified, for example: ** ** CREATE TABLE xxx.yyy (...); ** ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if ** the table name is not fully qualified, i.e.: ** ** CREATE TABLE yyy(...); ** ** Then pName1 is set to "yyy" and pName2 is "". ** ** This routine sets the *ppUnqual pointer to point at the token (pName1 or ** pName2) that stores the unqualified table name. The index of the ** database "xxx" is returned. */ SQLITE_PRIVATE int sqlite3TwoPartName( Parse *pParse, /* Parsing and code generating context */ Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ Token *pName2, /* The "yyy" in the name "xxx.yyy" */ Token **pUnqual /* Write the unqualified object name here */ ){ int iDb; /* Database holding the object */ sqlite3 *db = pParse->db; assert( pName2!=0 ); if( pName2->n>0 ){ if( db->init.busy ) { sqlite3ErrorMsg(pParse, "corrupt database"); return -1; } *pUnqual = pName2; iDb = sqlite3FindDb(db, pName1); if( iDb<0 ){ sqlite3ErrorMsg(pParse, "unknown database %T", pName1); return -1; } }else{ assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0); iDb = db->init.iDb; *pUnqual = pName1; } return iDb; } /* ** This routine is used to check if the UTF-8 string zName is a legal ** unqualified name for a new schema object (table, index, view or ** trigger). All names are legal except those that begin with the string ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace ** is reserved for internal use. */ SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){ if( !pParse->db->init.busy && pParse->nested==0 && (pParse->db->flags & SQLITE_WriteSchema)==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); return SQLITE_ERROR; } return SQLITE_OK; } /* ** Return the PRIMARY KEY index of a table */ SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){ Index *p; for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} return p; } /* ** Return the column of index pIdx that corresponds to table ** column iCol. Return -1 if not found. */ SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ int i; for(i=0; i<pIdx->nColumn; i++){ if( iCol==pIdx->aiColumn[i] ) return i; } return -1; } /* ** Begin constructing a new table representation in memory. This is ** the first of several action routines that get called in response ** to a CREATE TABLE statement. In particular, this routine is called ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp ** flag is true if the table should be stored in the auxiliary database ** file instead of in the main database file. This is normally the case ** when the "TEMP" or "TEMPORARY" keyword occurs in between ** CREATE and TABLE. ** ** The new table record is initialized and put in pParse->pNewTable. ** As more of the CREATE TABLE statement is parsed, additional action ** routines will be called to add more information to this record. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine ** is called to complete the construction of the new table record. */ SQLITE_PRIVATE void sqlite3StartTable( Parse *pParse, /* Parser context */ Token *pName1, /* First part of the name of the table or view */ Token *pName2, /* Second part of the name of the table or view */ int isTemp, /* True if this is a TEMP table */ int isView, /* True if this is a VIEW */ int isVirtual, /* True if this is a VIRTUAL table */ int noErr /* Do nothing if table already exists */ ){ Table *pTable; char *zName = 0; /* The name of the new table */ sqlite3 *db = pParse->db; Vdbe *v; int iDb; /* Database number to create the table in */ Token *pName; /* Unqualified name of the table to create */ if( db->init.busy && db->init.newTnum==1 ){ /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */ iDb = db->init.iDb; zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb)); pName = pName1; }else{ /* The common case */ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ) return; if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ /* If creating a temp table, the name may not be qualified. Unless ** the database name is "temp" anyway. */ sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); return; } if( !OMIT_TEMPDB && isTemp ) iDb = 1; zName = sqlite3NameFromToken(db, pName); } pParse->sNameToken = *pName; if( zName==0 ) return; if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto begin_table_error; } if( db->init.iDb==1 ) isTemp = 1; #ifndef SQLITE_OMIT_AUTHORIZATION assert( isTemp==0 || isTemp==1 ); assert( isView==0 || isView==1 ); { static const u8 aCode[] = { SQLITE_CREATE_TABLE, SQLITE_CREATE_TEMP_TABLE, SQLITE_CREATE_VIEW, SQLITE_CREATE_TEMP_VIEW }; char *zDb = db->aDb[iDb].zDbSName; if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ goto begin_table_error; } if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView], zName, 0, zDb) ){ goto begin_table_error; } } #endif /* Make sure the new table name does not collide with an existing ** index or table name in the same database. Issue an error message if ** it does. The exception is if the statement being parsed was passed ** to an sqlite3_declare_vtab() call. In that case only the column names ** and types will be used, so there is no need to test for namespace ** collisions. */ if( !IN_DECLARE_VTAB ){ char *zDb = db->aDb[iDb].zDbSName; if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ goto begin_table_error; } pTable = sqlite3FindTable(db, zName, zDb); if( pTable ){ if( !noErr ){ sqlite3ErrorMsg(pParse, "table %T already exists", pName); }else{ assert( !db->init.busy || CORRUPT_DB ); sqlite3CodeVerifySchema(pParse, iDb); } goto begin_table_error; } if( sqlite3FindIndex(db, zName, zDb)!=0 ){ sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); goto begin_table_error; } } pTable = sqlite3DbMallocZero(db, sizeof(Table)); if( pTable==0 ){ assert( db->mallocFailed ); pParse->rc = SQLITE_NOMEM_BKPT; pParse->nErr++; goto begin_table_error; } pTable->zName = zName; pTable->iPKey = -1; pTable->pSchema = db->aDb[iDb].pSchema; pTable->nTabRef = 1; pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); assert( pParse->pNewTable==0 ); pParse->pNewTable = pTable; /* If this is the magic sqlite_sequence table used by autoincrement, ** then record a pointer to this table in the main database structure ** so that INSERT can find the table easily. */ #ifndef SQLITE_OMIT_AUTOINCREMENT if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pTable->pSchema->pSeqTab = pTable; } #endif /* Begin generating the code that will insert the table record into ** the SQLITE_MASTER table. Note in particular that we must go ahead ** and allocate the record number for the table entry now. Before any ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause ** indices to be created and the table record must come before the ** indices. Hence, the record number for the table must be allocated ** now. */ if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ int addr1; int fileFormat; int reg1, reg2, reg3; /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */ static const char nullRow[] = { 6, 0, 0, 0, 0, 0 }; sqlite3BeginWriteOperation(pParse, 1, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( isVirtual ){ sqlite3VdbeAddOp0(v, OP_VBegin); } #endif /* If the file format and encoding in the database have not been set, ** set them now. */ reg1 = pParse->regRowid = ++pParse->nMem; reg2 = pParse->regRoot = ++pParse->nMem; reg3 = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); sqlite3VdbeUsesBtree(v, iDb); addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 1 : SQLITE_MAX_FILE_FORMAT; sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db)); sqlite3VdbeJumpHere(v, addr1); /* This just creates a place-holder record in the sqlite_master table. ** The record created does not contain anything yet. It will be replaced ** by the real entry in code generated at sqlite3EndTable(). ** ** The rowid for the new entry is left in register pParse->regRowid. ** The root page number of the new table is left in reg pParse->regRoot. ** The rowid and root page number values are needed by the code that ** sqlite3EndTable will generate. */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) if( isView || isVirtual ){ sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); }else #endif { pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); } sqlite3OpenMasterTable(pParse, iDb); sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3VdbeAddOp0(v, OP_Close); } /* Normal (non-error) return. */ return; /* If an error occurs, we jump here */ begin_table_error: sqlite3DbFree(db, zName); return; } /* Set properties of a table column based on the (magical) ** name of the column. */ #if SQLITE_ENABLE_HIDDEN_COLUMNS SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){ pCol->colFlags |= COLFLAG_HIDDEN; }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){ pTab->tabFlags |= TF_OOOHidden; } } #endif /* ** Add a new column to the table currently being constructed. ** ** The parser calls this routine once for each column declaration ** in a CREATE TABLE statement. sqlite3StartTable() gets called ** first to get things going. Then this routine is called for each ** column. */ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ Table *p; int i; char *z; char *zType; Column *pCol; sqlite3 *db = pParse->db; if( (p = pParse->pNewTable)==0 ) return; #if SQLITE_MAX_COLUMN if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); return; } #endif z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2); if( z==0 ) return; memcpy(z, pName->z, pName->n); z[pName->n] = 0; sqlite3Dequote(z); for(i=0; i<p->nCol; i++){ if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){ sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); sqlite3DbFree(db, z); return; } } if( (p->nCol & 0x7)==0 ){ Column *aNew; aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); if( aNew==0 ){ sqlite3DbFree(db, z); return; } p->aCol = aNew; } pCol = &p->aCol[p->nCol]; memset(pCol, 0, sizeof(p->aCol[0])); pCol->zName = z; sqlite3ColumnPropertiesFromName(p, pCol); if( pType->n==0 ){ /* If there is no type specified, columns have the default affinity ** 'BLOB'. */ pCol->affinity = SQLITE_AFF_BLOB; pCol->szEst = 1; }else{ zType = z + sqlite3Strlen30(z) + 1; memcpy(zType, pType->z, pType->n); zType[pType->n] = 0; sqlite3Dequote(zType); pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst); pCol->colFlags |= COLFLAG_HASTYPE; } p->nCol++; pParse->constraintName.n = 0; } /* ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has ** been seen on a column. This routine sets the notNull flag on ** the column currently under construction. */ SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){ Table *p; p = pParse->pNewTable; if( p==0 || NEVER(p->nCol<1) ) return; p->aCol[p->nCol-1].notNull = (u8)onError; } /* ** Scan the column type name zType (length nType) and return the ** associated affinity type. ** ** This routine does a case-independent search of zType for the ** substrings in the following table. If one of the substrings is ** found, the corresponding affinity is returned. If zType contains ** more than one of the substrings, entries toward the top of ** the table take priority. For example, if zType is 'BLOBINT', ** SQLITE_AFF_INTEGER is returned. ** ** Substring | Affinity ** -------------------------------- ** 'INT' | SQLITE_AFF_INTEGER ** 'CHAR' | SQLITE_AFF_TEXT ** 'CLOB' | SQLITE_AFF_TEXT ** 'TEXT' | SQLITE_AFF_TEXT ** 'BLOB' | SQLITE_AFF_BLOB ** 'REAL' | SQLITE_AFF_REAL ** 'FLOA' | SQLITE_AFF_REAL ** 'DOUB' | SQLITE_AFF_REAL ** ** If none of the substrings in the above table are found, ** SQLITE_AFF_NUMERIC is returned. */ SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){ u32 h = 0; char aff = SQLITE_AFF_NUMERIC; const char *zChar = 0; assert( zIn!=0 ); while( zIn[0] ){ h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; zIn++; if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ aff = SQLITE_AFF_TEXT; zChar = zIn; }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ aff = SQLITE_AFF_TEXT; }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ aff = SQLITE_AFF_TEXT; }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ aff = SQLITE_AFF_BLOB; if( zIn[0]=='(' ) zChar = zIn; #ifndef SQLITE_OMIT_FLOATING_POINT }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ && aff==SQLITE_AFF_NUMERIC ){ aff = SQLITE_AFF_REAL; }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ && aff==SQLITE_AFF_NUMERIC ){ aff = SQLITE_AFF_REAL; }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ && aff==SQLITE_AFF_NUMERIC ){ aff = SQLITE_AFF_REAL; #endif }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ aff = SQLITE_AFF_INTEGER; break; } } /* If pszEst is not NULL, store an estimate of the field size. The ** estimate is scaled so that the size of an integer is 1. */ if( pszEst ){ *pszEst = 1; /* default size is approx 4 bytes */ if( aff<SQLITE_AFF_NUMERIC ){ if( zChar ){ while( zChar[0] ){ if( sqlite3Isdigit(zChar[0]) ){ int v = 0; sqlite3GetInt32(zChar, &v); v = v/4 + 1; if( v>255 ) v = 255; *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ break; } zChar++; } }else{ *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ } } } return aff; } /* ** The expression is the default value for the most recently added column ** of the table currently under construction. ** ** Default value expressions must be constant. Raise an exception if this ** is not the case. ** ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. */ SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ Table *p; Column *pCol; sqlite3 *db = pParse->db; p = pParse->pNewTable; if( p!=0 ){ pCol = &(p->aCol[p->nCol-1]); if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){ sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", pCol->zName); }else{ /* A copy of pExpr is used instead of the original, as pExpr contains ** tokens that point to volatile memory. The 'span' of the expression ** is required by pragma table_info. */ Expr x; sqlite3ExprDelete(db, pCol->pDflt); memset(&x, 0, sizeof(x)); x.op = TK_SPAN; x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart, (int)(pSpan->zEnd - pSpan->zStart)); x.pLeft = pSpan->pExpr; x.flags = EP_Skip; pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); sqlite3DbFree(db, x.u.zToken); } } sqlite3ExprDelete(db, pSpan->pExpr); } /* ** Backwards Compatibility Hack: ** ** Historical versions of SQLite accepted strings as column names in ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example: ** ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim) ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC); ** ** This is goofy. But to preserve backwards compatibility we continue to ** accept it. This routine does the necessary conversion. It converts ** the expression given in its argument from a TK_STRING into a TK_ID ** if the expression is just a TK_STRING with an optional COLLATE clause. ** If the epxression is anything other than TK_STRING, the expression is ** unchanged. */ static void sqlite3StringToId(Expr *p){ if( p->op==TK_STRING ){ p->op = TK_ID; }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ p->pLeft->op = TK_ID; } } /* ** Designate the PRIMARY KEY for the table. pList is a list of names ** of columns that form the primary key. If pList is NULL, then the ** most recently added column of the table is the primary key. ** ** A table can have at most one primary key. If the table already has ** a primary key (and this is the second primary key) then create an ** error. ** ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, ** then we will try to use that column as the rowid. Set the Table.iPKey ** field of the table under construction to be the index of the ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is ** no INTEGER PRIMARY KEY. ** ** If the key is not an INTEGER PRIMARY KEY, then create a unique ** index for the key. No index is created for INTEGER PRIMARY KEYs. */ SQLITE_PRIVATE void sqlite3AddPrimaryKey( Parse *pParse, /* Parsing context */ ExprList *pList, /* List of field names to be indexed */ int onError, /* What to do with a uniqueness conflict */ int autoInc, /* True if the AUTOINCREMENT keyword is present */ int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ ){ Table *pTab = pParse->pNewTable; Column *pCol = 0; int iCol = -1, i; int nTerm; if( pTab==0 ) goto primary_key_exit; if( pTab->tabFlags & TF_HasPrimaryKey ){ sqlite3ErrorMsg(pParse, "table \"%s\" has more than one primary key", pTab->zName); goto primary_key_exit; } pTab->tabFlags |= TF_HasPrimaryKey; if( pList==0 ){ iCol = pTab->nCol - 1; pCol = &pTab->aCol[iCol]; pCol->colFlags |= COLFLAG_PRIMKEY; nTerm = 1; }else{ nTerm = pList->nExpr; for(i=0; i<nTerm; i++){ Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr); assert( pCExpr!=0 ); sqlite3StringToId(pCExpr); if( pCExpr->op==TK_ID ){ const char *zCName = pCExpr->u.zToken; for(iCol=0; iCol<pTab->nCol; iCol++){ if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ pCol = &pTab->aCol[iCol]; pCol->colFlags |= COLFLAG_PRIMKEY; break; } } } } } if( nTerm==1 && pCol && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0 && sortOrder!=SQLITE_SO_DESC ){ pTab->iPKey = iCol; pTab->keyConf = (u8)onError; assert( autoInc==0 || autoInc==1 ); pTab->tabFlags |= autoInc*TF_Autoincrement; if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; }else if( autoInc ){ #ifndef SQLITE_OMIT_AUTOINCREMENT sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " "INTEGER PRIMARY KEY"); #endif }else{ sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY); pList = 0; } primary_key_exit: sqlite3ExprListDelete(pParse->db, pList); return; } /* ** Add a new CHECK constraint to the table currently under construction. */ SQLITE_PRIVATE void sqlite3AddCheckConstraint( Parse *pParse, /* Parsing context */ Expr *pCheckExpr /* The check expression */ ){ #ifndef SQLITE_OMIT_CHECK Table *pTab = pParse->pNewTable; sqlite3 *db = pParse->db; if( pTab && !IN_DECLARE_VTAB && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) ){ pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); if( pParse->constraintName.n ){ sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); } }else #endif { sqlite3ExprDelete(pParse->db, pCheckExpr); } } /* ** Set the collation function of the most recently parsed table column ** to the CollSeq given. */ SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){ Table *p; int i; char *zColl; /* Dequoted name of collation sequence */ sqlite3 *db; if( (p = pParse->pNewTable)==0 ) return; i = p->nCol-1; db = pParse->db; zColl = sqlite3NameFromToken(db, pToken); if( !zColl ) return; if( sqlite3LocateCollSeq(pParse, zColl) ){ Index *pIdx; sqlite3DbFree(db, p->aCol[i].zColl); p->aCol[i].zColl = zColl; /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", ** then an index may have been created on this column before the ** collation type was added. Correct this if it is the case. */ for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ assert( pIdx->nKeyCol==1 ); if( pIdx->aiColumn[0]==i ){ pIdx->azColl[0] = p->aCol[i].zColl; } } }else{ sqlite3DbFree(db, zColl); } } /* ** This function returns the collation sequence for database native text ** encoding identified by the string zName, length nName. ** ** If the requested collation sequence is not available, or not available ** in the database native encoding, the collation factory is invoked to ** request it. If the collation factory does not supply such a sequence, ** and the sequence is available in another text encoding, then that is ** returned instead. ** ** If no versions of the requested collations sequence are available, or ** another error occurs, NULL is returned and an error message written into ** pParse. ** ** This routine is a wrapper around sqlite3FindCollSeq(). This routine ** invokes the collation factory if the named collation cannot be found ** and generates an error message. ** ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() */ SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ sqlite3 *db = pParse->db; u8 enc = ENC(db); u8 initbusy = db->init.busy; CollSeq *pColl; pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); if( !initbusy && (!pColl || !pColl->xCmp) ){ pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); } return pColl; } /* ** Generate code that will increment the schema cookie. ** ** The schema cookie is used to determine when the schema for the ** database changes. After each schema change, the cookie value ** changes. When a process first reads the schema it records the ** cookie. Thereafter, whenever it goes to access the database, ** it checks the cookie to make sure the schema has not changed ** since it was last read. ** ** This plan is not completely bullet-proof. It is possible for ** the schema to change multiple times and for the cookie to be ** set back to prior value. But schema changes are infrequent ** and the probability of hitting the same cookie value is only ** 1 chance in 2^32. So we're safe enough. ** ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments ** the schema-version whenever the schema changes. */ SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){ sqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, db->aDb[iDb].pSchema->schema_cookie+1); } /* ** Measure the number of characters needed to output the given ** identifier. The number returned includes any quotes used ** but does not include the null terminator. ** ** The estimate is conservative. It might be larger that what is ** really needed. */ static int identLength(const char *z){ int n; for(n=0; *z; n++, z++){ if( *z=='"' ){ n++; } } return n + 2; } /* ** The first parameter is a pointer to an output buffer. The second ** parameter is a pointer to an integer that contains the offset at ** which to write into the output buffer. This function copies the ** nul-terminated string pointed to by the third parameter, zSignedIdent, ** to the specified offset in the buffer and updates *pIdx to refer ** to the first byte after the last byte written before returning. ** ** If the string zSignedIdent consists entirely of alpha-numeric ** characters, does not begin with a digit and is not an SQL keyword, ** then it is copied to the output buffer exactly as it is. Otherwise, ** it is quoted using double-quotes. */ static void identPut(char *z, int *pIdx, char *zSignedIdent){ unsigned char *zIdent = (unsigned char*)zSignedIdent; int i, j, needQuote; i = *pIdx; for(j=0; zIdent[j]; j++){ if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; } needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID || zIdent[j]!=0 || j==0; if( needQuote ) z[i++] = '"'; for(j=0; zIdent[j]; j++){ z[i++] = zIdent[j]; if( zIdent[j]=='"' ) z[i++] = '"'; } if( needQuote ) z[i++] = '"'; z[i] = 0; *pIdx = i; } /* ** Generate a CREATE TABLE statement appropriate for the given ** table. Memory to hold the text of the statement is obtained ** from sqliteMalloc() and must be freed by the calling function. */ static char *createTableStmt(sqlite3 *db, Table *p){ int i, k, n; char *zStmt; char *zSep, *zSep2, *zEnd; Column *pCol; n = 0; for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ n += identLength(pCol->zName) + 5; } n += identLength(p->zName); if( n<50 ){ zSep = ""; zSep2 = ","; zEnd = ")"; }else{ zSep = "\n "; zSep2 = ",\n "; zEnd = "\n)"; } n += 35 + 6*p->nCol; zStmt = sqlite3DbMallocRaw(0, n); if( zStmt==0 ){ sqlite3OomFault(db); return 0; } sqlite3_snprintf(n, zStmt, "CREATE TABLE "); k = sqlite3Strlen30(zStmt); identPut(zStmt, &k, p->zName); zStmt[k++] = '('; for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ static const char * const azType[] = { /* SQLITE_AFF_BLOB */ "", /* SQLITE_AFF_TEXT */ " TEXT", /* SQLITE_AFF_NUMERIC */ " NUM", /* SQLITE_AFF_INTEGER */ " INT", /* SQLITE_AFF_REAL */ " REAL" }; int len; const char *zType; sqlite3_snprintf(n-k, &zStmt[k], zSep); k += sqlite3Strlen30(&zStmt[k]); zSep = zSep2; identPut(zStmt, &k, pCol->zName); assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); testcase( pCol->affinity==SQLITE_AFF_BLOB ); testcase( pCol->affinity==SQLITE_AFF_TEXT ); testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); testcase( pCol->affinity==SQLITE_AFF_INTEGER ); testcase( pCol->affinity==SQLITE_AFF_REAL ); zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; len = sqlite3Strlen30(zType); assert( pCol->affinity==SQLITE_AFF_BLOB || pCol->affinity==sqlite3AffinityType(zType, 0) ); memcpy(&zStmt[k], zType, len); k += len; assert( k<=n ); } sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); return zStmt; } /* ** Resize an Index object to hold N columns total. Return SQLITE_OK ** on success and SQLITE_NOMEM on an OOM error. */ static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ char *zExtra; int nByte; if( pIdx->nColumn>=N ) return SQLITE_OK; assert( pIdx->isResized==0 ); nByte = (sizeof(char*) + sizeof(i16) + 1)*N; zExtra = sqlite3DbMallocZero(db, nByte); if( zExtra==0 ) return SQLITE_NOMEM_BKPT; memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); pIdx->azColl = (const char**)zExtra; zExtra += sizeof(char*)*N; memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); pIdx->aiColumn = (i16*)zExtra; zExtra += sizeof(i16)*N; memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); pIdx->aSortOrder = (u8*)zExtra; pIdx->nColumn = N; pIdx->isResized = 1; return SQLITE_OK; } /* ** Estimate the total row width for a table. */ static void estimateTableWidth(Table *pTab){ unsigned wTable = 0; const Column *pTabCol; int i; for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ wTable += pTabCol->szEst; } if( pTab->iPKey<0 ) wTable++; pTab->szTabRow = sqlite3LogEst(wTable*4); } /* ** Estimate the average size of a row for an index. */ static void estimateIndexWidth(Index *pIdx){ unsigned wIndex = 0; int i; const Column *aCol = pIdx->pTable->aCol; for(i=0; i<pIdx->nColumn; i++){ i16 x = pIdx->aiColumn[i]; assert( x<pIdx->pTable->nCol ); wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; } pIdx->szIdxRow = sqlite3LogEst(wIndex*4); } /* Return true if value x is found any of the first nCol entries of aiCol[] */ static int hasColumn(const i16 *aiCol, int nCol, int x){ while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; return 0; } /* ** This routine runs at the end of parsing a CREATE TABLE statement that ** has a WITHOUT ROWID clause. The job of this routine is to convert both ** internal schema data structures and the generated VDBE code so that they ** are appropriate for a WITHOUT ROWID table instead of a rowid table. ** Changes include: ** ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL. ** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is ** no rowid btree for a WITHOUT ROWID. Instead, the canonical ** data storage is a covering index btree. ** (3) Bypass the creation of the sqlite_master table entry ** for the PRIMARY KEY as the primary key index is now ** identified by the sqlite_master table entry of the table itself. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the ** schema to the rootpage from the main table. ** (5) Add all table columns to the PRIMARY KEY Index object ** so that the PRIMARY KEY is a covering index. The surplus ** columns are part of KeyInfo.nXField and are not used for ** sorting or lookup or uniqueness checks. ** (6) Replace the rowid tail on all automatically generated UNIQUE ** indices with the PRIMARY KEY columns. ** ** For virtual tables, only (1) is performed. */ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ Index *pIdx; Index *pPk; int nPk; int i, j; sqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables) */ if( !db->init.imposterTable ){ for(i=0; i<pTab->nCol; i++){ if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){ pTab->aCol[i].notNull = OE_Abort; } } } /* The remaining transformations only apply to b-tree tables, not to ** virtual tables */ if( IN_DECLARE_VTAB ) return; /* Convert the OP_CreateTable opcode that would normally create the ** root-page for the table into an OP_CreateIndex opcode. The index ** created will become the PRIMARY KEY index. */ if( pParse->addrCrTab ){ assert( v ); sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex); } /* Locate the PRIMARY KEY index. Or, if this table was originally ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. */ if( pTab->iPKey>=0 ){ ExprList *pList; Token ipkToken; sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName); pList = sqlite3ExprListAppend(pParse, 0, sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); if( pList==0 ) return; pList->a[0].sortOrder = pParse->iPkSortOrder; assert( pParse->pNewTable==pTab ); sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, SQLITE_IDXTYPE_PRIMARYKEY); if( db->mallocFailed ) return; pPk = sqlite3PrimaryKeyIndex(pTab); pTab->iPKey = -1; }else{ pPk = sqlite3PrimaryKeyIndex(pTab); /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master ** table entry. This is only required if currently generating VDBE ** code for a CREATE TABLE (not when parsing one as part of reading ** a database schema). */ if( v ){ assert( db->init.busy==0 ); sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto); } /* ** Remove all redundant columns from the PRIMARY KEY. For example, change ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later ** code assumes the PRIMARY KEY contains no repeated columns. */ for(i=j=1; i<pPk->nKeyCol; i++){ if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){ pPk->nColumn--; }else{ pPk->aiColumn[j++] = pPk->aiColumn[i]; } } pPk->nKeyCol = j; } assert( pPk!=0 ); pPk->isCovering = 1; if( !db->init.imposterTable ) pPk->uniqNotNull = 1; nPk = pPk->nKeyCol; /* The root page of the PRIMARY KEY is the table root page */ pPk->tnum = pTab->tnum; /* Update the in-memory representation of all UNIQUE indices by converting ** the final rowid column into one or more columns of the PRIMARY KEY. */ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int n; if( IsPrimaryKeyIndex(pIdx) ) continue; for(i=n=0; i<nPk; i++){ if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++; } if( n==0 ){ /* This index is a superset of the primary key */ pIdx->nColumn = pIdx->nKeyCol; continue; } if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ pIdx->aiColumn[j] = pPk->aiColumn[i]; pIdx->azColl[j] = pPk->azColl[i]; j++; } } assert( pIdx->nColumn>=pIdx->nKeyCol+n ); assert( pIdx->nColumn>=j ); } /* Add all table columns to the PRIMARY KEY index */ if( nPk<pTab->nCol ){ if( resizeIndexObject(db, pPk, pTab->nCol) ) return; for(i=0, j=nPk; i<pTab->nCol; i++){ if( !hasColumn(pPk->aiColumn, j, i) ){ assert( j<pPk->nColumn ); pPk->aiColumn[j] = i; pPk->azColl[j] = sqlite3StrBINARY; j++; } } assert( pPk->nColumn==j ); assert( pTab->nCol==j ); }else{ pPk->nColumn = pTab->nCol; } } /* ** This routine is called to report the final ")" that terminates ** a CREATE TABLE statement. ** ** The table structure that other action routines have been building ** is added to the internal hash tables, assuming no errors have ** occurred. ** ** An entry for the table is made in the master table on disk, unless ** this is a temporary table or db->init.busy==1. When db->init.busy==1 ** it means we are reading the sqlite_master table because we just ** connected to the database or because the sqlite_master table has ** recently changed, so the entry for this table already exists in ** the sqlite_master table. We do not want to create it again. ** ** If the pSelect argument is not NULL, it means that this routine ** was called to create a table generated from a ** "CREATE TABLE ... AS SELECT ..." statement. The column names of ** the new table will match the result set of the SELECT. */ SQLITE_PRIVATE void sqlite3EndTable( Parse *pParse, /* Parse context */ Token *pCons, /* The ',' token after the last column defn. */ Token *pEnd, /* The ')' before options in the CREATE TABLE */ u8 tabOpts, /* Extra table options. Usually 0. */ Select *pSelect /* Select from a "CREATE ... AS SELECT" */ ){ Table *p; /* The new table */ sqlite3 *db = pParse->db; /* The database connection */ int iDb; /* Database in which the table lives */ Index *pIdx; /* An implied index of the table */ if( pEnd==0 && pSelect==0 ){ return; } assert( !db->mallocFailed ); p = pParse->pNewTable; if( p==0 ) return; assert( !db->init.busy || !pSelect ); /* If the db->init.busy is 1 it means we are reading the SQL off the ** "sqlite_master" or "sqlite_temp_master" table on the disk. ** So do not write to the disk again. Extract the root page number ** for the table from the db->init.newTnum field. (The page number ** should have been put there by the sqliteOpenCb routine.) ** ** If the root page number is 1, that means this is the sqlite_master ** table itself. So mark it read-only. */ if( db->init.busy ){ p->tnum = db->init.newTnum; if( p->tnum==1 ) p->tabFlags |= TF_Readonly; } /* Special processing for WITHOUT ROWID Tables */ if( tabOpts & TF_WithoutRowid ){ if( (p->tabFlags & TF_Autoincrement) ){ sqlite3ErrorMsg(pParse, "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); return; } if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); }else{ p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; convertToWithoutRowidTable(pParse, p); } } iDb = sqlite3SchemaToIndex(db, p->pSchema); #ifndef SQLITE_OMIT_CHECK /* Resolve names in all CHECK constraint expressions. */ if( p->pCheck ){ sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); } #endif /* !defined(SQLITE_OMIT_CHECK) */ /* Estimate the average row size for the table and for all implied indices */ estimateTableWidth(p); for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ estimateIndexWidth(pIdx); } /* If not initializing, then create a record for the new table ** in the SQLITE_MASTER table of the database. ** ** If this is a TEMPORARY table, write the entry into the auxiliary ** file instead of into the main database file. */ if( !db->init.busy ){ int n; Vdbe *v; char *zType; /* "view" or "table" */ char *zType2; /* "VIEW" or "TABLE" */ char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ v = sqlite3GetVdbe(pParse); if( NEVER(v==0) ) return; sqlite3VdbeAddOp1(v, OP_Close, 0); /* ** Initialize zType for the new view or table. */ if( p->pSelect==0 ){ /* A regular table */ zType = "table"; zType2 = "TABLE"; #ifndef SQLITE_OMIT_VIEW }else{ /* A view */ zType = "view"; zType2 = "VIEW"; #endif } /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT ** statement to populate the new table. The root-page number for the ** new table is in register pParse->regRoot. ** ** Once the SELECT has been coded by sqlite3Select(), it is in a ** suitable state to query for the column names and types to be used ** by the new table. ** ** A shared-cache write-lock is not required to write to the new table, ** as a schema-lock must have already been obtained to create it. Since ** a schema-lock excludes all other database users, the write-lock would ** be redundant. */ if( pSelect ){ SelectDest dest; /* Where the SELECT should store results */ int regYield; /* Register holding co-routine entry-point */ int addrTop; /* Top of the co-routine */ int regRec; /* A record to be insert into the new table */ int regRowid; /* Rowid of the next row to insert */ int addrInsLoop; /* Top of the loop for inserting rows */ Table *pSelTab; /* A table that describes the SELECT results */ regYield = ++pParse->nMem; regRec = ++pParse->nMem; regRowid = ++pParse->nMem; assert(pParse->nTab==1); sqlite3MayAbort(pParse); sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); pParse->nTab = 2; addrTop = sqlite3VdbeCurrentAddr(v) + 1; sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); sqlite3Select(pParse, pSelect, &dest); sqlite3VdbeEndCoroutine(v, regYield); sqlite3VdbeJumpHere(v, addrTop - 1); if( pParse->nErr ) return; pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); if( pSelTab==0 ) return; assert( p->aCol==0 ); p->nCol = pSelTab->nCol; p->aCol = pSelTab->aCol; pSelTab->nCol = 0; pSelTab->aCol = 0; sqlite3DeleteTable(db, pSelTab); addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); sqlite3TableAffinity(v, p, 0); sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); sqlite3VdbeGoto(v, addrInsLoop); sqlite3VdbeJumpHere(v, addrInsLoop); sqlite3VdbeAddOp1(v, OP_Close, 1); } /* Compute the complete text of the CREATE statement */ if( pSelect ){ zStmt = createTableStmt(db, p); }else{ Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; n = (int)(pEnd2->z - pParse->sNameToken.z); if( pEnd2->z[0]!=';' ) n += pEnd2->n; zStmt = sqlite3MPrintf(db, "CREATE %s %.*s", zType2, n, pParse->sNameToken.z ); } /* A slot for the record has already been allocated in the ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. */ sqlite3NestedParse(pParse, "UPDATE %Q.%s " "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " "WHERE rowid=#%d", db->aDb[iDb].zDbSName, MASTER_NAME, zType, p->zName, p->zName, pParse->regRoot, zStmt, pParse->regRowid ); sqlite3DbFree(db, zStmt); sqlite3ChangeCookie(pParse, iDb); #ifndef SQLITE_OMIT_AUTOINCREMENT /* Check to see if we need to create an sqlite_sequence table for ** keeping track of autoincrement keys. */ if( (p->tabFlags & TF_Autoincrement)!=0 ){ Db *pDb = &db->aDb[iDb]; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( pDb->pSchema->pSeqTab==0 ){ sqlite3NestedParse(pParse, "CREATE TABLE %Q.sqlite_sequence(name,seq)", pDb->zDbSName ); } } #endif /* Reparse everything to update our internal data structures */ sqlite3VdbeAddParseSchemaOp(v, iDb, sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); } /* Add the table to the in-memory representation of the database. */ if( db->init.busy ){ Table *pOld; Schema *pSchema = p->pSchema; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); if( pOld ){ assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ sqlite3OomFault(db); return; } pParse->pNewTable = 0; db->flags |= SQLITE_InternChanges; #ifndef SQLITE_OMIT_ALTERTABLE if( !p->pSelect ){ const char *zName = (const char *)pParse->sNameToken.z; int nName; assert( !pSelect && pCons && pEnd ); if( pCons->z==0 ){ pCons = pEnd; } nName = (int)((const char *)pCons->z - zName); p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); } #endif } } #ifndef SQLITE_OMIT_VIEW /* ** The parser calls this routine in order to create a new VIEW */ SQLITE_PRIVATE void sqlite3CreateView( Parse *pParse, /* The parsing context */ Token *pBegin, /* The CREATE token that begins the statement */ Token *pName1, /* The token that holds the name of the view */ Token *pName2, /* The token that holds the name of the view */ ExprList *pCNames, /* Optional list of view column names */ Select *pSelect, /* A SELECT statement that will become the new view */ int isTemp, /* TRUE for a TEMPORARY view */ int noErr /* Suppress error messages if VIEW already exists */ ){ Table *p; int n; const char *z; Token sEnd; DbFixer sFix; Token *pName = 0; int iDb; sqlite3 *db = pParse->db; if( pParse->nVar>0 ){ sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); goto create_view_fail; } sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); p = pParse->pNewTable; if( p==0 || pParse->nErr ) goto create_view_fail; sqlite3TwoPartName(pParse, pName1, pName2, &pName); iDb = sqlite3SchemaToIndex(db, p->pSchema); sqlite3FixInit(&sFix, pParse, iDb, "view", pName); if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; /* Make a copy of the entire SELECT statement that defines the view. ** This will force all the Expr.token.z values to be dynamically ** allocated rather than point to the input string - which means that ** they will persist after the current sqlite3_exec() call returns. */ p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); if( db->mallocFailed ) goto create_view_fail; /* Locate the end of the CREATE VIEW statement. Make sEnd point to ** the end. */ sEnd = pParse->sLastToken; assert( sEnd.z[0]!=0 ); if( sEnd.z[0]!=';' ){ sEnd.z += sEnd.n; } sEnd.n = 0; n = (int)(sEnd.z - pBegin->z); assert( n>0 ); z = pBegin->z; while( sqlite3Isspace(z[n-1]) ){ n--; } sEnd.z = &z[n-1]; sEnd.n = 1; /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ sqlite3EndTable(pParse, 0, &sEnd, 0, 0); create_view_fail: sqlite3SelectDelete(db, pSelect); sqlite3ExprListDelete(db, pCNames); return; } #endif /* SQLITE_OMIT_VIEW */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) /* ** The Table structure pTable is really a VIEW. Fill in the names of ** the columns of the view in the pTable structure. Return the number ** of errors. If an error is seen leave an error message in pParse->zErrMsg. */ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ Table *pSelTab; /* A fake table from which we get the result set */ Select *pSel; /* Copy of the SELECT that implements the view */ int nErr = 0; /* Number of errors encountered */ int n; /* Temporarily holds the number of cursors assigned */ sqlite3 *db = pParse->db; /* Database connection for malloc errors */ #ifndef SQLITE_OMIT_AUTHORIZATION sqlite3_xauth xAuth; /* Saved xAuth pointer */ #endif assert( pTable ); #ifndef SQLITE_OMIT_VIRTUALTABLE if( sqlite3VtabCallConnect(pParse, pTable) ){ return SQLITE_ERROR; } if( IsVirtual(pTable) ) return 0; #endif #ifndef SQLITE_OMIT_VIEW /* A positive nCol means the columns names for this view are ** already known. */ if( pTable->nCol>0 ) return 0; /* A negative nCol is a special marker meaning that we are currently ** trying to compute the column names. If we enter this routine with ** a negative nCol, it means two or more views form a loop, like this: ** ** CREATE VIEW one AS SELECT * FROM two; ** CREATE VIEW two AS SELECT * FROM one; ** ** Actually, the error above is now caught prior to reaching this point. ** But the following test is still important as it does come up ** in the following: ** ** CREATE TABLE main.ex1(a); ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; ** SELECT * FROM temp.ex1; */ if( pTable->nCol<0 ){ sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); return 1; } assert( pTable->nCol>=0 ); /* If we get this far, it means we need to compute the table names. ** Note that the call to sqlite3ResultSetOfSelect() will expand any ** "*" elements in the results set of the view and will assign cursors ** to the elements of the FROM clause. But we do not want these changes ** to be permanent. So the computation is done on a copy of the SELECT ** statement that defines the view. */ assert( pTable->pSelect ); pSel = sqlite3SelectDup(db, pTable->pSelect, 0); if( pSel ){ n = pParse->nTab; sqlite3SrcListAssignCursors(pParse, pSel->pSrc); pTable->nCol = -1; db->lookaside.bDisable++; #ifndef SQLITE_OMIT_AUTHORIZATION xAuth = db->xAuth; db->xAuth = 0; pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); db->xAuth = xAuth; #else pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); #endif pParse->nTab = n; if( pTable->pCheck ){ /* CREATE VIEW name(arglist) AS ... ** The names of the columns in the table are taken from ** arglist which is stored in pTable->pCheck. The pCheck field ** normally holds CHECK constraints on an ordinary table, but for ** a VIEW it holds the list of column names. */ sqlite3ColumnsFromExprList(pParse, pTable->pCheck, &pTable->nCol, &pTable->aCol); if( db->mallocFailed==0 && pParse->nErr==0 && pTable->nCol==pSel->pEList->nExpr ){ sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel); } }else if( pSelTab ){ /* CREATE VIEW name AS... without an argument list. Construct ** the column names from the SELECT statement that defines the view. */ assert( pTable->aCol==0 ); pTable->nCol = pSelTab->nCol; pTable->aCol = pSelTab->aCol; pSelTab->nCol = 0; pSelTab->aCol = 0; assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); }else{ pTable->nCol = 0; nErr++; } sqlite3DeleteTable(db, pSelTab); sqlite3SelectDelete(db, pSel); db->lookaside.bDisable--; } else { nErr++; } pTable->pSchema->schemaFlags |= DB_UnresetViews; #endif /* SQLITE_OMIT_VIEW */ return nErr; } #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ #ifndef SQLITE_OMIT_VIEW /* ** Clear the column names from every VIEW in database idx. */ static void sqliteViewResetAll(sqlite3 *db, int idx){ HashElem *i; assert( sqlite3SchemaMutexHeld(db, idx, 0) ); if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); if( pTab->pSelect ){ sqlite3DeleteColumnNames(db, pTab); pTab->aCol = 0; pTab->nCol = 0; } } DbClearProperty(db, idx, DB_UnresetViews); } #else # define sqliteViewResetAll(A,B) #endif /* SQLITE_OMIT_VIEW */ /* ** This function is called by the VDBE to adjust the internal schema ** used by SQLite when the btree layer moves a table root page. The ** root-page of a table or index in database iDb has changed from iFrom ** to iTo. ** ** Ticket #1728: The symbol table might still contain information ** on tables and/or indices that are the process of being deleted. ** If you are unlucky, one of those deleted indices or tables might ** have the same rootpage number as the real table or index that is ** being moved. So we cannot stop searching after the first match ** because the first match might be for one of the deleted indices ** or tables and not the table/index that is actually being moved. ** We must continue looping until all tables and indices with ** rootpage==iFrom have been converted to have a rootpage of iTo ** in order to be certain that we got the right one. */ #ifndef SQLITE_OMIT_AUTOVACUUM SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ HashElem *pElem; Hash *pHash; Db *pDb; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pDb = &db->aDb[iDb]; pHash = &pDb->pSchema->tblHash; for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ Table *pTab = sqliteHashData(pElem); if( pTab->tnum==iFrom ){ pTab->tnum = iTo; } } pHash = &pDb->pSchema->idxHash; for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ Index *pIdx = sqliteHashData(pElem); if( pIdx->tnum==iFrom ){ pIdx->tnum = iTo; } } } #endif /* ** Write code to erase the table with root-page iTable from database iDb. ** Also write code to modify the sqlite_master table and internal schema ** if a root-page of another table is moved by the btree-layer whilst ** erasing iTable (this can happen with an auto-vacuum database). */ static void destroyRootPage(Parse *pParse, int iTable, int iDb){ Vdbe *v = sqlite3GetVdbe(pParse); int r1 = sqlite3GetTempReg(pParse); assert( iTable>1 ); sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); sqlite3MayAbort(pParse); #ifndef SQLITE_OMIT_AUTOVACUUM /* OP_Destroy stores an in integer r1. If this integer ** is non-zero, then it is the root page number of a table moved to ** location iTable. The following code modifies the sqlite_master table to ** reflect this. ** ** The "#NNN" in the SQL is a special constant that means whatever value ** is in register NNN. See grammar rules associated with the TK_REGISTER ** token for additional information. */ sqlite3NestedParse(pParse, "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1); #endif sqlite3ReleaseTempReg(pParse, r1); } /* ** Write VDBE code to erase table pTab and all associated indices on disk. ** Code to update the sqlite_master tables and internal schema definitions ** in case a root-page belonging to another table is moved by the btree layer ** is also added (this can happen with an auto-vacuum database). */ static void destroyTable(Parse *pParse, Table *pTab){ #ifdef SQLITE_OMIT_AUTOVACUUM Index *pIdx; int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); destroyRootPage(pParse, pTab->tnum, iDb); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ destroyRootPage(pParse, pIdx->tnum, iDb); } #else /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM ** is not defined), then it is important to call OP_Destroy on the ** table and index root-pages in order, starting with the numerically ** largest root-page number. This guarantees that none of the root-pages ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the ** following were coded: ** ** OP_Destroy 4 0 ** ... ** OP_Destroy 5 0 ** ** and root page 5 happened to be the largest root-page number in the ** database, then root page 5 would be moved to page 4 by the ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit ** a free-list page. */ int iTab = pTab->tnum; int iDestroyed = 0; while( 1 ){ Index *pIdx; int iLargest = 0; if( iDestroyed==0 || iTab<iDestroyed ){ iLargest = iTab; } for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int iIdx = pIdx->tnum; assert( pIdx->pSchema==pTab->pSchema ); if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ iLargest = iIdx; } } if( iLargest==0 ){ return; }else{ int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); assert( iDb>=0 && iDb<pParse->db->nDb ); destroyRootPage(pParse, iLargest, iDb); iDestroyed = iLargest; } } #endif } /* ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) ** after a DROP INDEX or DROP TABLE command. */ static void sqlite3ClearStatTables( Parse *pParse, /* The parsing context */ int iDb, /* The database number */ const char *zType, /* "idx" or "tbl" */ const char *zName /* Name of index or table */ ){ int i; const char *zDbName = pParse->db->aDb[iDb].zDbSName; for(i=1; i<=4; i++){ char zTab[24]; sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE %s=%Q", zDbName, zTab, zType, zName ); } } } /* ** Generate code to drop a table. */ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ Vdbe *v; sqlite3 *db = pParse->db; Trigger *pTrigger; Db *pDb = &db->aDb[iDb]; v = sqlite3GetVdbe(pParse); assert( v!=0 ); sqlite3BeginWriteOperation(pParse, 1, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ sqlite3VdbeAddOp0(v, OP_VBegin); } #endif /* Drop all triggers associated with the table being dropped. Code ** is generated to remove entries from sqlite_master and/or ** sqlite_temp_master if required. */ pTrigger = sqlite3TriggerList(pParse, pTab); while( pTrigger ){ assert( pTrigger->pSchema==pTab->pSchema || pTrigger->pSchema==db->aDb[1].pSchema ); sqlite3DropTriggerPtr(pParse, pTrigger); pTrigger = pTrigger->pNext; } #ifndef SQLITE_OMIT_AUTOINCREMENT /* Remove any entries of the sqlite_sequence table associated with ** the table being dropped. This is done before the table is dropped ** at the btree level, in case the sqlite_sequence table needs to ** move as a result of the drop (can happen in auto-vacuum mode). */ if( pTab->tabFlags & TF_Autoincrement ){ sqlite3NestedParse(pParse, "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", pDb->zDbSName, pTab->zName ); } #endif /* Drop all SQLITE_MASTER table and index entries that refer to the ** table. The program name loops through the master table and deletes ** every row that refers to a table of the same name as the one being ** dropped. Triggers are handled separately because a trigger can be ** created in the temp database that refers to a table in another ** database. */ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", pDb->zDbSName, MASTER_NAME, pTab->zName); if( !isView && !IsVirtual(pTab) ){ destroyTable(pParse, pTab); } /* Remove the table entry from SQLite's internal schema and modify ** the schema cookie. */ if( IsVirtual(pTab) ){ sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); } sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); sqlite3ChangeCookie(pParse, iDb); sqliteViewResetAll(db, iDb); } /* ** This routine is called to do the work of a DROP TABLE statement. ** pName is the name of the table to be dropped. */ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ Table *pTab; Vdbe *v; sqlite3 *db = pParse->db; int iDb; if( db->mallocFailed ){ goto exit_drop_table; } assert( pParse->nErr==0 ); assert( pName->nSrc==1 ); if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; if( noErr ) db->suppressErr++; assert( isView==0 || isView==LOCATE_VIEW ); pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); if( noErr ) db->suppressErr--; if( pTab==0 ){ if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); goto exit_drop_table; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb>=0 && iDb<db->nDb ); /* If pTab is a virtual table, call ViewGetColumnNames() to ensure ** it is initialized. */ if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ goto exit_drop_table; } #ifndef SQLITE_OMIT_AUTHORIZATION { int code; const char *zTab = SCHEMA_TABLE(iDb); const char *zDb = db->aDb[iDb].zDbSName; const char *zArg2 = 0; if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ goto exit_drop_table; } if( isView ){ if( !OMIT_TEMPDB && iDb==1 ){ code = SQLITE_DROP_TEMP_VIEW; }else{ code = SQLITE_DROP_VIEW; } #ifndef SQLITE_OMIT_VIRTUALTABLE }else if( IsVirtual(pTab) ){ code = SQLITE_DROP_VTABLE; zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; #endif }else{ if( !OMIT_TEMPDB && iDb==1 ){ code = SQLITE_DROP_TEMP_TABLE; }else{ code = SQLITE_DROP_TABLE; } } if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ goto exit_drop_table; } if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ goto exit_drop_table; } } #endif if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); goto exit_drop_table; } #ifndef SQLITE_OMIT_VIEW /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used ** on a table. */ if( isView && pTab->pSelect==0 ){ sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); goto exit_drop_table; } if( !isView && pTab->pSelect ){ sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); goto exit_drop_table; } #endif /* Generate code to remove the table from the master table ** on disk. */ v = sqlite3GetVdbe(pParse); if( v ){ sqlite3BeginWriteOperation(pParse, 1, iDb); sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); sqlite3FkDropTable(pParse, pName, pTab); sqlite3CodeDropTable(pParse, pTab, iDb, isView); } exit_drop_table: sqlite3SrcListDelete(db, pName); } /* ** This routine is called to create a new foreign key on the table ** currently under construction. pFromCol determines which columns ** in the current table point to the foreign key. If pFromCol==0 then ** connect the key to the last column inserted. pTo is the name of ** the table referred to (a.k.a the "parent" table). pToCol is a list ** of tables in the parent pTo table. flags contains all ** information about the conflict resolution algorithms specified ** in the ON DELETE, ON UPDATE and ON INSERT clauses. ** ** An FKey structure is created and added to the table currently ** under construction in the pParse->pNewTable field. ** ** The foreign key is set for IMMEDIATE processing. A subsequent call ** to sqlite3DeferForeignKey() might change this to DEFERRED. */ SQLITE_PRIVATE void sqlite3CreateForeignKey( Parse *pParse, /* Parsing context */ ExprList *pFromCol, /* Columns in this table that point to other table */ Token *pTo, /* Name of the other table */ ExprList *pToCol, /* Columns in the other table */ int flags /* Conflict resolution algorithms. */ ){ sqlite3 *db = pParse->db; #ifndef SQLITE_OMIT_FOREIGN_KEY FKey *pFKey = 0; FKey *pNextTo; Table *p = pParse->pNewTable; int nByte; int i; int nCol; char *z; assert( pTo!=0 ); if( p==0 || IN_DECLARE_VTAB ) goto fk_end; if( pFromCol==0 ){ int iCol = p->nCol-1; if( NEVER(iCol<0) ) goto fk_end; if( pToCol && pToCol->nExpr!=1 ){ sqlite3ErrorMsg(pParse, "foreign key on %s" " should reference only one column of table %T", p->aCol[iCol].zName, pTo); goto fk_end; } nCol = 1; }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ sqlite3ErrorMsg(pParse, "number of columns in foreign key does not match the number of " "columns in the referenced table"); goto fk_end; }else{ nCol = pFromCol->nExpr; } nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; if( pToCol ){ for(i=0; i<pToCol->nExpr; i++){ nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; } } pFKey = sqlite3DbMallocZero(db, nByte ); if( pFKey==0 ){ goto fk_end; } pFKey->pFrom = p; pFKey->pNextFrom = p->pFKey; z = (char*)&pFKey->aCol[nCol]; pFKey->zTo = z; memcpy(z, pTo->z, pTo->n); z[pTo->n] = 0; sqlite3Dequote(z); z += pTo->n+1; pFKey->nCol = nCol; if( pFromCol==0 ){ pFKey->aCol[0].iFrom = p->nCol-1; }else{ for(i=0; i<nCol; i++){ int j; for(j=0; j<p->nCol; j++){ if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ pFKey->aCol[i].iFrom = j; break; } } if( j>=p->nCol ){ sqlite3ErrorMsg(pParse, "unknown column \"%s\" in foreign key definition", pFromCol->a[i].zName); goto fk_end; } } } if( pToCol ){ for(i=0; i<nCol; i++){ int n = sqlite3Strlen30(pToCol->a[i].zName); pFKey->aCol[i].zCol = z; memcpy(z, pToCol->a[i].zName, n); z[n] = 0; z += n+1; } } pFKey->isDeferred = 0; pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, pFKey->zTo, (void *)pFKey ); if( pNextTo==pFKey ){ sqlite3OomFault(db); goto fk_end; } if( pNextTo ){ assert( pNextTo->pPrevTo==0 ); pFKey->pNextTo = pNextTo; pNextTo->pPrevTo = pFKey; } /* Link the foreign key to the table as the last step. */ p->pFKey = pFKey; pFKey = 0; fk_end: sqlite3DbFree(db, pFKey); #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ sqlite3ExprListDelete(db, pFromCol); sqlite3ExprListDelete(db, pToCol); } /* ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED ** clause is seen as part of a foreign key definition. The isDeferred ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. ** The behavior of the most recently created foreign key is adjusted ** accordingly. */ SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ #ifndef SQLITE_OMIT_FOREIGN_KEY Table *pTab; FKey *pFKey; if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ pFKey->isDeferred = (u8)isDeferred; #endif } /* ** Generate code that will erase and refill index *pIdx. This is ** used to initialize a newly created index or to recompute the ** content of an index in response to a REINDEX command. ** ** if memRootPage is not negative, it means that the index is newly ** created. The register specified by memRootPage contains the ** root page number of the index. If memRootPage is negative, then ** the index already exists and must be cleared before being refilled and ** the root page number of the index is taken from pIndex->tnum. */ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ Table *pTab = pIndex->pTable; /* The table that is indexed */ int iTab = pParse->nTab++; /* Btree cursor used for pTab */ int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ int iSorter; /* Cursor opened by OpenSorter (if in use) */ int addr1; /* Address of top of loop */ int addr2; /* Address to jump to for next iteration */ int tnum; /* Root page of index */ int iPartIdxLabel; /* Jump to this label to skip a row */ Vdbe *v; /* Generate code into this virtual machine */ KeyInfo *pKey; /* KeyInfo for index */ int regRecord; /* Register holding assembled index record */ sqlite3 *db = pParse->db; /* The database connection */ int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); #ifndef SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, db->aDb[iDb].zDbSName ) ){ return; } #endif /* Require a write-lock on the table to perform this operation */ sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); v = sqlite3GetVdbe(pParse); if( v==0 ) return; if( memRootPage>=0 ){ tnum = memRootPage; }else{ tnum = pIndex->tnum; } pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); assert( pKey!=0 || db->mallocFailed || pParse->nErr ); /* Open the sorter cursor if we are to use one. */ iSorter = pParse->nTab++; sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) sqlite3KeyInfoRef(pKey), P4_KEYINFO); /* Open the table. Loop through all rows of the table, inserting index ** records into the sorter. */ sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); regRecord = sqlite3GetTempReg(pParse); sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, (char *)pKey, P4_KEYINFO); sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); if( IsUniqueIndex(pIndex) ){ int j2 = sqlite3VdbeCurrentAddr(v) + 3; sqlite3VdbeGoto(v, j2); addr2 = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, pIndex->nKeyCol); VdbeCoverage(v); sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); }else{ addr2 = sqlite3VdbeCurrentAddr(v); } sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1); sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); sqlite3ReleaseTempReg(pParse, regRecord); sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp1(v, OP_Close, iTab); sqlite3VdbeAddOp1(v, OP_Close, iIdx); sqlite3VdbeAddOp1(v, OP_Close, iSorter); } /* ** Allocate heap space to hold an Index object with nCol columns. ** ** Increase the allocation size to provide an extra nExtra bytes ** of 8-byte aligned space after the Index object and return a ** pointer to this extra space in *ppExtra. */ SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( sqlite3 *db, /* Database connection */ i16 nCol, /* Total number of columns in the index */ int nExtra, /* Number of bytes of extra space to alloc */ char **ppExtra /* Pointer to the "extra" space */ ){ Index *p; /* Allocated index object */ int nByte; /* Bytes of space for Index object + arrays */ nByte = ROUND8(sizeof(Index)) + /* Index structure */ ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ sizeof(i16)*nCol + /* Index.aiColumn */ sizeof(u8)*nCol); /* Index.aSortOrder */ p = sqlite3DbMallocZero(db, nByte + nExtra); if( p ){ char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; p->aSortOrder = (u8*)pExtra; p->nColumn = nCol; p->nKeyCol = nCol - 1; *ppExtra = ((char*)p) + nByte; } return p; } /* ** Create a new index for an SQL table. pName1.pName2 is the name of the index ** and pTblList is the name of the table that is to be indexed. Both will ** be NULL for a primary key or an index that is created to satisfy a ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable ** as the table to be indexed. pParse->pNewTable is a table that is ** currently being constructed by a CREATE TABLE statement. ** ** pList is a list of columns to be indexed. pList will be NULL if this ** is a primary key or unique-constraint on the most recent column added ** to the table currently under construction. */ SQLITE_PRIVATE void sqlite3CreateIndex( Parse *pParse, /* All information about this parse */ Token *pName1, /* First part of index name. May be NULL */ Token *pName2, /* Second part of index name. May be NULL */ SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ ExprList *pList, /* A list of columns to be indexed */ int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ Token *pStart, /* The CREATE token that begins this statement */ Expr *pPIWhere, /* WHERE clause for partial indices */ int sortOrder, /* Sort order of primary key when pList==NULL */ int ifNotExist, /* Omit error if index already exists */ u8 idxType /* The index type */ ){ Table *pTab = 0; /* Table to be indexed */ Index *pIndex = 0; /* The index to be created */ char *zName = 0; /* Name of the index */ int nName; /* Number of characters in zName */ int i, j; DbFixer sFix; /* For assigning database names to pTable */ int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ sqlite3 *db = pParse->db; Db *pDb; /* The specific table containing the indexed database */ int iDb; /* Index of the database that is being written */ Token *pName = 0; /* Unqualified name of the index to create */ struct ExprList_item *pListItem; /* For looping over pList */ int nExtra = 0; /* Space allocated for zExtra[] */ int nExtraCol; /* Number of extra columns needed */ char *zExtra = 0; /* Extra space after the Index object */ Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ if( db->mallocFailed || pParse->nErr>0 ){ goto exit_create_index; } if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){ goto exit_create_index; } if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ goto exit_create_index; } /* ** Find the table that is to be indexed. Return early if not found. */ if( pTblName!=0 ){ /* Use the two-part index name to determine the database ** to search for the table. 'Fix' the table name to this db ** before looking up the table. */ assert( pName1 && pName2 ); iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ) goto exit_create_index; assert( pName && pName->z ); #ifndef SQLITE_OMIT_TEMPDB /* If the index name was unqualified, check if the table ** is a temp table. If so, set the database to 1. Do not do this ** if initialising a database schema. */ if( !db->init.busy ){ pTab = sqlite3SrcListLookup(pParse, pTblName); if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ iDb = 1; } } #endif sqlite3FixInit(&sFix, pParse, iDb, "index", pName); if( sqlite3FixSrcList(&sFix, pTblName) ){ /* Because the parser constructs pTblName from a single identifier, ** sqlite3FixSrcList can never fail. */ assert(0); } pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); assert( db->mallocFailed==0 || pTab==0 ); if( pTab==0 ) goto exit_create_index; if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ sqlite3ErrorMsg(pParse, "cannot create a TEMP index on non-TEMP table \"%s\"", pTab->zName); goto exit_create_index; } if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); }else{ assert( pName==0 ); assert( pStart==0 ); pTab = pParse->pNewTable; if( !pTab ) goto exit_create_index; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); } pDb = &db->aDb[iDb]; assert( pTab!=0 ); assert( pParse->nErr==0 ); if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 && db->init.busy==0 #if SQLITE_USER_AUTHENTICATION && sqlite3UserAuthTable(pTab->zName)==0 #endif && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); goto exit_create_index; } #ifndef SQLITE_OMIT_VIEW if( pTab->pSelect ){ sqlite3ErrorMsg(pParse, "views may not be indexed"); goto exit_create_index; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); goto exit_create_index; } #endif /* ** Find the name of the index. Make sure there is not already another ** index or table with the same name. ** ** Exception: If we are reading the names of permanent indices from the ** sqlite_master table (because some other process changed the schema) and ** one of the index names collides with the name of a temporary table or ** index, then we will continue to process this index. ** ** If pName==0 it means that we are ** dealing with a primary key or UNIQUE constraint. We have to invent our ** own name. */ if( pName ){ zName = sqlite3NameFromToken(db, pName); if( zName==0 ) goto exit_create_index; assert( pName->z!=0 ); if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto exit_create_index; } if( !db->init.busy ){ if( sqlite3FindTable(db, zName, 0)!=0 ){ sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); goto exit_create_index; } } if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ if( !ifNotExist ){ sqlite3ErrorMsg(pParse, "index %s already exists", zName); }else{ assert( !db->init.busy ); sqlite3CodeVerifySchema(pParse, iDb); } goto exit_create_index; } }else{ int n; Index *pLoop; for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); if( zName==0 ){ goto exit_create_index; } /* Automatic index names generated from within sqlite3_declare_vtab() ** must have names that are distinct from normal automatic index names. ** The following statement converts "sqlite3_autoindex..." into ** "sqlite3_butoindex..." in order to make the names distinct. ** The "vtab_err.test" test demonstrates the need of this statement. */ if( IN_DECLARE_VTAB ) zName[7]++; } /* Check for authorization to create an index. */ #ifndef SQLITE_OMIT_AUTHORIZATION { const char *zDb = pDb->zDbSName; if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ goto exit_create_index; } i = SQLITE_CREATE_INDEX; if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ goto exit_create_index; } } #endif /* If pList==0, it means this routine was called to make a primary ** key out of the last column added to the table under construction. ** So create a fake list to simulate this. */ if( pList==0 ){ Token prevCol; sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName); pList = sqlite3ExprListAppend(pParse, 0, sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); if( pList==0 ) goto exit_create_index; assert( pList->nExpr==1 ); sqlite3ExprListSetSortOrder(pList, sortOrder); }else{ sqlite3ExprListCheckLength(pParse, pList, "index"); } /* Figure out how many bytes of space are required to store explicitly ** specified collation sequence names. */ for(i=0; i<pList->nExpr; i++){ Expr *pExpr = pList->a[i].pExpr; assert( pExpr!=0 ); if( pExpr->op==TK_COLLATE ){ nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); } } /* ** Allocate the index structure. */ nName = sqlite3Strlen30(zName); nExtraCol = pPk ? pPk->nKeyCol : 1; pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, nName + nExtra + 1, &zExtra); if( db->mallocFailed ){ goto exit_create_index; } assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); pIndex->zName = zExtra; zExtra += nName + 1; memcpy(pIndex->zName, zName, nName+1); pIndex->pTable = pTab; pIndex->onError = (u8)onError; pIndex->uniqNotNull = onError!=OE_None; pIndex->idxType = idxType; pIndex->pSchema = db->aDb[iDb].pSchema; pIndex->nKeyCol = pList->nExpr; if( pPIWhere ){ sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); pIndex->pPartIdxWhere = pPIWhere; pPIWhere = 0; } assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); /* Check to see if we should honor DESC requests on index columns */ if( pDb->pSchema->file_format>=4 ){ sortOrderMask = -1; /* Honor DESC */ }else{ sortOrderMask = 0; /* Ignore DESC */ } /* Analyze the list of expressions that form the terms of the index and ** report any errors. In the common case where the expression is exactly ** a table column, store that column in aiColumn[]. For general expressions, ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. ** ** TODO: Issue a warning if two or more columns of the index are identical. ** TODO: Issue a warning if the table primary key is used as part of the ** index key. */ for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ Expr *pCExpr; /* The i-th index expression */ int requestedSortOrder; /* ASC or DESC on the i-th expression */ const char *zColl; /* Collation sequence name */ sqlite3StringToId(pListItem->pExpr); sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); if( pParse->nErr ) goto exit_create_index; pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); if( pCExpr->op!=TK_COLUMN ){ if( pTab==pParse->pNewTable ){ sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " "UNIQUE constraints"); goto exit_create_index; } if( pIndex->aColExpr==0 ){ ExprList *pCopy = sqlite3ExprListDup(db, pList, 0); pIndex->aColExpr = pCopy; if( !db->mallocFailed ){ assert( pCopy!=0 ); pListItem = &pCopy->a[i]; } } j = XN_EXPR; pIndex->aiColumn[i] = XN_EXPR; pIndex->uniqNotNull = 0; }else{ j = pCExpr->iColumn; assert( j<=0x7fff ); if( j<0 ){ j = pTab->iPKey; }else if( pTab->aCol[j].notNull==0 ){ pIndex->uniqNotNull = 0; } pIndex->aiColumn[i] = (i16)j; } zColl = 0; if( pListItem->pExpr->op==TK_COLLATE ){ int nColl; zColl = pListItem->pExpr->u.zToken; nColl = sqlite3Strlen30(zColl) + 1; assert( nExtra>=nColl ); memcpy(zExtra, zColl, nColl); zColl = zExtra; zExtra += nColl; nExtra -= nColl; }else if( j>=0 ){ zColl = pTab->aCol[j].zColl; } if( !zColl ) zColl = sqlite3StrBINARY; if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ goto exit_create_index; } pIndex->azColl[i] = zColl; requestedSortOrder = pListItem->sortOrder & sortOrderMask; pIndex->aSortOrder[i] = (u8)requestedSortOrder; } /* Append the table key to the end of the index. For WITHOUT ROWID ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For ** normal tables (when pPk==0) this will be the rowid. */ if( pPk ){ for(j=0; j<pPk->nKeyCol; j++){ int x = pPk->aiColumn[j]; assert( x>=0 ); if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ pIndex->nColumn--; }else{ pIndex->aiColumn[i] = x; pIndex->azColl[i] = pPk->azColl[j]; pIndex->aSortOrder[i] = pPk->aSortOrder[j]; i++; } } assert( i==pIndex->nColumn ); }else{ pIndex->aiColumn[i] = XN_ROWID; pIndex->azColl[i] = sqlite3StrBINARY; } sqlite3DefaultRowEst(pIndex); if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); /* If this index contains every column of its table, then mark ** it as a covering index */ assert( HasRowid(pTab) || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 ); if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ pIndex->isCovering = 1; for(j=0; j<pTab->nCol; j++){ if( j==pTab->iPKey ) continue; if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue; pIndex->isCovering = 0; break; } } if( pTab==pParse->pNewTable ){ /* This routine has been called to create an automatic index as a ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or ** a PRIMARY KEY or UNIQUE clause following the column definitions. ** i.e. one of: ** ** CREATE TABLE t(x PRIMARY KEY, y); ** CREATE TABLE t(x, y, UNIQUE(x, y)); ** ** Either way, check to see if the table already has such an index. If ** so, don't bother creating this one. This only applies to ** automatically created indices. Users can do as they wish with ** explicit indices. ** ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent ** (and thus suppressing the second one) even if they have different ** sort orders. ** ** If there are different collating sequences or if the columns of ** the constraint occur in different orders, then the constraints are ** considered distinct and both result in separate indices. */ Index *pIdx; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int k; assert( IsUniqueIndex(pIdx) ); assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); assert( IsUniqueIndex(pIndex) ); if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; for(k=0; k<pIdx->nKeyCol; k++){ const char *z1; const char *z2; assert( pIdx->aiColumn[k]>=0 ); if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; z1 = pIdx->azColl[k]; z2 = pIndex->azColl[k]; if( sqlite3StrICmp(z1, z2) ) break; } if( k==pIdx->nKeyCol ){ if( pIdx->onError!=pIndex->onError ){ /* This constraint creates the same index as a previous ** constraint specified somewhere in the CREATE TABLE statement. ** However the ON CONFLICT clauses are different. If both this ** constraint and the previous equivalent constraint have explicit ** ON CONFLICT clauses this is an error. Otherwise, use the ** explicitly specified behavior for the index. */ if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ sqlite3ErrorMsg(pParse, "conflicting ON CONFLICT clauses specified", 0); } if( pIdx->onError==OE_Default ){ pIdx->onError = pIndex->onError; } } if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType; goto exit_create_index; } } } /* Link the new Index structure to its table and to the other ** in-memory database structures. */ assert( pParse->nErr==0 ); if( db->init.busy ){ Index *p; assert( !IN_DECLARE_VTAB ); assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); p = sqlite3HashInsert(&pIndex->pSchema->idxHash, pIndex->zName, pIndex); if( p ){ assert( p==pIndex ); /* Malloc must have failed */ sqlite3OomFault(db); goto exit_create_index; } db->flags |= SQLITE_InternChanges; if( pTblName!=0 ){ pIndex->tnum = db->init.newTnum; } } /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then ** emit code to allocate the index rootpage on disk and make an entry for ** the index in the sqlite_master table and populate the index with ** content. But, do not do this if we are simply reading the sqlite_master ** table to parse the schema, or if this index is the PRIMARY KEY index ** of a WITHOUT ROWID table. ** ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY ** or UNIQUE index in a CREATE TABLE statement. Since the table ** has just been created, it contains no data and the index initialization ** step can be skipped. */ else if( HasRowid(pTab) || pTblName!=0 ){ Vdbe *v; char *zStmt; int iMem = ++pParse->nMem; v = sqlite3GetVdbe(pParse); if( v==0 ) goto exit_create_index; sqlite3BeginWriteOperation(pParse, 1, iDb); /* Create the rootpage for the index using CreateIndex. But before ** doing so, code a Noop instruction and store its address in ** Index.tnum. This is required in case this index is actually a ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In ** that case the convertToWithoutRowidTable() routine will replace ** the Noop with a Goto to jump over the VDBE code generated below. */ pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop); sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); /* Gather the complete text of the CREATE INDEX statement into ** the zStmt variable */ if( pStart ){ int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; if( pName->z[n-1]==';' ) n--; /* A named index with an explicit CREATE INDEX statement */ zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", onError==OE_None ? "" : " UNIQUE", n, pName->z); }else{ /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ /* zStmt = sqlite3MPrintf(""); */ zStmt = 0; } /* Add an entry in sqlite_master for this index */ sqlite3NestedParse(pParse, "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName, pTab->zName, iMem, zStmt ); sqlite3DbFree(db, zStmt); /* Fill the index with data and reparse the schema. Code an OP_Expire ** to invalidate all pre-compiled statements. */ if( pTblName ){ sqlite3RefillIndex(pParse, pIndex, iMem); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddParseSchemaOp(v, iDb, sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); sqlite3VdbeAddOp0(v, OP_Expire); } sqlite3VdbeJumpHere(v, pIndex->tnum); } /* When adding an index to the list of indices for a table, make ** sure all indices labeled OE_Replace come after all those labeled ** OE_Ignore. This is necessary for the correct constraint check ** processing (in sqlite3GenerateConstraintChecks()) as part of ** UPDATE and INSERT statements. */ if( db->init.busy || pTblName==0 ){ if( onError!=OE_Replace || pTab->pIndex==0 || pTab->pIndex->onError==OE_Replace){ pIndex->pNext = pTab->pIndex; pTab->pIndex = pIndex; }else{ Index *pOther = pTab->pIndex; while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ pOther = pOther->pNext; } pIndex->pNext = pOther->pNext; pOther->pNext = pIndex; } pIndex = 0; } /* Clean up before exiting */ exit_create_index: if( pIndex ) freeIndex(db, pIndex); sqlite3ExprDelete(db, pPIWhere); sqlite3ExprListDelete(db, pList); sqlite3SrcListDelete(db, pTblName); sqlite3DbFree(db, zName); } /* ** Fill the Index.aiRowEst[] array with default information - information ** to be used when we have not run the ANALYZE command. ** ** aiRowEst[0] is supposed to contain the number of elements in the index. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the ** number of rows in the table that match any particular value of the ** first column of the index. aiRowEst[2] is an estimate of the number ** of rows that match any particular combination of the first 2 columns ** of the index. And so forth. It must always be the case that * ** aiRowEst[N]<=aiRowEst[N-1] ** aiRowEst[N]>=1 ** ** Apart from that, we have little to go on besides intuition as to ** how aiRowEst[] should be initialized. The numbers generated here ** are based on typical values found in actual indices. */ SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){ /* 10, 9, 8, 7, 6 */ LogEst aVal[] = { 33, 32, 30, 28, 26 }; LogEst *a = pIdx->aiRowLogEst; int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); int i; /* Set the first entry (number of rows in the index) to the estimated ** number of rows in the table, or half the number of rows in the table ** for a partial index. But do not let the estimate drop below 10. */ a[0] = pIdx->pTable->nRowLogEst; if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) ); if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) ); /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is ** 6 and each subsequent value (if any) is 5. */ memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ a[i] = 23; assert( 23==sqlite3LogEst(5) ); } assert( 0==sqlite3LogEst(1) ); if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; } /* ** This routine will drop an existing named index. This routine ** implements the DROP INDEX statement. */ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ Index *pIndex; Vdbe *v; sqlite3 *db = pParse->db; int iDb; assert( pParse->nErr==0 ); /* Never called with prior errors */ if( db->mallocFailed ){ goto exit_drop_index; } assert( pName->nSrc==1 ); if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ goto exit_drop_index; } pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); if( pIndex==0 ){ if( !ifExists ){ sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); }else{ sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); } pParse->checkSchema = 1; goto exit_drop_index; } if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ sqlite3ErrorMsg(pParse, "index associated with UNIQUE " "or PRIMARY KEY constraint cannot be dropped", 0); goto exit_drop_index; } iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); #ifndef SQLITE_OMIT_AUTHORIZATION { int code = SQLITE_DROP_INDEX; Table *pTab = pIndex->pTable; const char *zDb = db->aDb[iDb].zDbSName; const char *zTab = SCHEMA_TABLE(iDb); if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ goto exit_drop_index; } if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ goto exit_drop_index; } } #endif /* Generate code to remove the index and from the master table */ v = sqlite3GetVdbe(pParse); if( v ){ sqlite3BeginWriteOperation(pParse, 1, iDb); sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName ); sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); sqlite3ChangeCookie(pParse, iDb); destroyRootPage(pParse, pIndex->tnum, iDb); sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); } exit_drop_index: sqlite3SrcListDelete(db, pName); } /* ** pArray is a pointer to an array of objects. Each object in the ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() ** to extend the array so that there is space for a new object at the end. ** ** When this function is called, *pnEntry contains the current size of ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes ** in total). ** ** If the realloc() is successful (i.e. if no OOM condition occurs), the ** space allocated for the new object is zeroed, *pnEntry updated to ** reflect the new size of the array and a pointer to the new allocation ** returned. *pIdx is set to the index of the new array entry in this case. ** ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains ** unchanged and a copy of pArray returned. */ SQLITE_PRIVATE void *sqlite3ArrayAllocate( sqlite3 *db, /* Connection to notify of malloc failures */ void *pArray, /* Array of objects. Might be reallocated */ int szEntry, /* Size of each object in the array */ int *pnEntry, /* Number of objects currently in use */ int *pIdx /* Write the index of a new slot here */ ){ char *z; int n = *pnEntry; if( (n & (n-1))==0 ){ int sz = (n==0) ? 1 : 2*n; void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); if( pNew==0 ){ *pIdx = -1; return pArray; } pArray = pNew; } z = (char*)pArray; memset(&z[n * szEntry], 0, szEntry); *pIdx = n; ++*pnEntry; return pArray; } /* ** Append a new element to the given IdList. Create a new IdList if ** need be. ** ** A new IdList is returned, or NULL if malloc() fails. */ SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ int i; if( pList==0 ){ pList = sqlite3DbMallocZero(db, sizeof(IdList) ); if( pList==0 ) return 0; } pList->a = sqlite3ArrayAllocate( db, pList->a, sizeof(pList->a[0]), &pList->nId, &i ); if( i<0 ){ sqlite3IdListDelete(db, pList); return 0; } pList->a[i].zName = sqlite3NameFromToken(db, pToken); return pList; } /* ** Delete an IdList. */ SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ int i; if( pList==0 ) return; for(i=0; i<pList->nId; i++){ sqlite3DbFree(db, pList->a[i].zName); } sqlite3DbFree(db, pList->a); sqlite3DbFree(db, pList); } /* ** Return the index in pList of the identifier named zId. Return -1 ** if not found. */ SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){ int i; if( pList==0 ) return -1; for(i=0; i<pList->nId; i++){ if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; } return -1; } /* ** Expand the space allocated for the given SrcList object by ** creating nExtra new slots beginning at iStart. iStart is zero based. ** New slots are zeroed. ** ** For example, suppose a SrcList initially contains two entries: A,B. ** To append 3 new entries onto the end, do this: ** ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); ** ** After the call above it would contain: A, B, nil, nil, nil. ** If the iStart argument had been 1 instead of 2, then the result ** would have been: A, nil, nil, nil, B. To prepend the new slots, ** the iStart value would be 0. The result then would ** be: nil, nil, nil, A, B. ** ** If a memory allocation fails the SrcList is unchanged. The ** db->mallocFailed flag will be set to true. */ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( sqlite3 *db, /* Database connection to notify of OOM errors */ SrcList *pSrc, /* The SrcList to be enlarged */ int nExtra, /* Number of new slots to add to pSrc->a[] */ int iStart /* Index in pSrc->a[] of first new slot */ ){ int i; /* Sanity checking on calling parameters */ assert( iStart>=0 ); assert( nExtra>=1 ); assert( pSrc!=0 ); assert( iStart<=pSrc->nSrc ); /* Allocate additional space if needed */ if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ SrcList *pNew; int nAlloc = pSrc->nSrc*2+nExtra; int nGot; pNew = sqlite3DbRealloc(db, pSrc, sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); if( pNew==0 ){ assert( db->mallocFailed ); return pSrc; } pSrc = pNew; nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; pSrc->nAlloc = nGot; } /* Move existing slots that come after the newly inserted slots ** out of the way */ for(i=pSrc->nSrc-1; i>=iStart; i--){ pSrc->a[i+nExtra] = pSrc->a[i]; } pSrc->nSrc += nExtra; /* Zero the newly allocated slots */ memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); for(i=iStart; i<iStart+nExtra; i++){ pSrc->a[i].iCursor = -1; } /* Return a pointer to the enlarged SrcList */ return pSrc; } /* ** Append a new table name to the given SrcList. Create a new SrcList if ** need be. A new entry is created in the SrcList even if pTable is NULL. ** ** A SrcList is returned, or NULL if there is an OOM error. The returned ** SrcList might be the same as the SrcList that was input or it might be ** a new one. If an OOM error does occurs, then the prior value of pList ** that is input to this routine is automatically freed. ** ** If pDatabase is not null, it means that the table has an optional ** database name prefix. Like this: "database.table". The pDatabase ** points to the table name and the pTable points to the database name. ** The SrcList.a[].zName field is filled with the table name which might ** come from pTable (if pDatabase is NULL) or from pDatabase. ** SrcList.a[].zDatabase is filled with the database name from pTable, ** or with NULL if no database is specified. ** ** In other words, if call like this: ** ** sqlite3SrcListAppend(D,A,B,0); ** ** Then B is a table name and the database name is unspecified. If called ** like this: ** ** sqlite3SrcListAppend(D,A,B,C); ** ** Then C is the table name and B is the database name. If C is defined ** then so is B. In other words, we never have a case where: ** ** sqlite3SrcListAppend(D,A,0,C); ** ** Both pTable and pDatabase are assumed to be quoted. They are dequoted ** before being added to the SrcList. */ SQLITE_PRIVATE SrcList *sqlite3SrcListAppend( sqlite3 *db, /* Connection to notify of malloc failures */ SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ Token *pTable, /* Table to append */ Token *pDatabase /* Database of the table */ ){ struct SrcList_item *pItem; assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ assert( db!=0 ); if( pList==0 ){ pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) ); if( pList==0 ) return 0; pList->nAlloc = 1; pList->nSrc = 1; memset(&pList->a[0], 0, sizeof(pList->a[0])); pList->a[0].iCursor = -1; }else{ pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); } if( db->mallocFailed ){ sqlite3SrcListDelete(db, pList); return 0; } pItem = &pList->a[pList->nSrc-1]; if( pDatabase && pDatabase->z==0 ){ pDatabase = 0; } if( pDatabase ){ Token *pTemp = pDatabase; pDatabase = pTable; pTable = pTemp; } pItem->zName = sqlite3NameFromToken(db, pTable); pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); return pList; } /* ** Assign VdbeCursor index numbers to all tables in a SrcList */ SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ int i; struct SrcList_item *pItem; assert(pList || pParse->db->mallocFailed ); if( pList ){ for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ if( pItem->iCursor>=0 ) break; pItem->iCursor = pParse->nTab++; if( pItem->pSelect ){ sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); } } } } /* ** Delete an entire SrcList including all its substructure. */ SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ int i; struct SrcList_item *pItem; if( pList==0 ) return; for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ sqlite3DbFree(db, pItem->zDatabase); sqlite3DbFree(db, pItem->zName); sqlite3DbFree(db, pItem->zAlias); if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); sqlite3DeleteTable(db, pItem->pTab); sqlite3SelectDelete(db, pItem->pSelect); sqlite3ExprDelete(db, pItem->pOn); sqlite3IdListDelete(db, pItem->pUsing); } sqlite3DbFree(db, pList); } /* ** This routine is called by the parser to add a new term to the ** end of a growing FROM clause. The "p" parameter is the part of ** the FROM clause that has already been constructed. "p" is NULL ** if this is the first term of the FROM clause. pTable and pDatabase ** are the name of the table and database named in the FROM clause term. ** pDatabase is NULL if the database name qualifier is missing - the ** usual case. If the term has an alias, then pAlias points to the ** alias token. If the term is a subquery, then pSubquery is the ** SELECT statement that the subquery encodes. The pTable and ** pDatabase parameters are NULL for subqueries. The pOn and pUsing ** parameters are the content of the ON and USING clauses. ** ** Return a new SrcList which encodes is the FROM with the new ** term added. */ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm( Parse *pParse, /* Parsing context */ SrcList *p, /* The left part of the FROM clause already seen */ Token *pTable, /* Name of the table to add to the FROM clause */ Token *pDatabase, /* Name of the database containing pTable */ Token *pAlias, /* The right-hand side of the AS subexpression */ Select *pSubquery, /* A subquery used in place of a table name */ Expr *pOn, /* The ON clause of a join */ IdList *pUsing /* The USING clause of a join */ ){ struct SrcList_item *pItem; sqlite3 *db = pParse->db; if( !p && (pOn || pUsing) ){ sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", (pOn ? "ON" : "USING") ); goto append_from_error; } p = sqlite3SrcListAppend(db, p, pTable, pDatabase); if( p==0 || NEVER(p->nSrc==0) ){ goto append_from_error; } pItem = &p->a[p->nSrc-1]; assert( pAlias!=0 ); if( pAlias->n ){ pItem->zAlias = sqlite3NameFromToken(db, pAlias); } pItem->pSelect = pSubquery; pItem->pOn = pOn; pItem->pUsing = pUsing; return p; append_from_error: assert( p==0 ); sqlite3ExprDelete(db, pOn); sqlite3IdListDelete(db, pUsing); sqlite3SelectDelete(db, pSubquery); return 0; } /* ** Add an INDEXED BY or NOT INDEXED clause to the most recently added ** element of the source-list passed as the second argument. */ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ assert( pIndexedBy!=0 ); if( p && ALWAYS(p->nSrc>0) ){ struct SrcList_item *pItem = &p->a[p->nSrc-1]; assert( pItem->fg.notIndexed==0 ); assert( pItem->fg.isIndexedBy==0 ); assert( pItem->fg.isTabFunc==0 ); if( pIndexedBy->n==1 && !pIndexedBy->z ){ /* A "NOT INDEXED" clause was supplied. See parse.y ** construct "indexed_opt" for details. */ pItem->fg.notIndexed = 1; }else{ pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0); } } } /* ** Add the list of function arguments to the SrcList entry for a ** table-valued-function. */ SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ if( p ){ struct SrcList_item *pItem = &p->a[p->nSrc-1]; assert( pItem->fg.notIndexed==0 ); assert( pItem->fg.isIndexedBy==0 ); assert( pItem->fg.isTabFunc==0 ); pItem->u1.pFuncArg = pList; pItem->fg.isTabFunc = 1; }else{ sqlite3ExprListDelete(pParse->db, pList); } } /* ** When building up a FROM clause in the parser, the join operator ** is initially attached to the left operand. But the code generator ** expects the join operator to be on the right operand. This routine ** Shifts all join operators from left to right for an entire FROM ** clause. ** ** Example: Suppose the join is like this: ** ** A natural cross join B ** ** The operator is "natural cross join". The A and B operands are stored ** in p->a[0] and p->a[1], respectively. The parser initially stores the ** operator with A. This routine shifts that operator over to B. */ SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){ if( p ){ int i; for(i=p->nSrc-1; i>0; i--){ p->a[i].fg.jointype = p->a[i-1].fg.jointype; } p->a[0].fg.jointype = 0; } } /* ** Generate VDBE code for a BEGIN statement. */ SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){ sqlite3 *db; Vdbe *v; int i; assert( pParse!=0 ); db = pParse->db; assert( db!=0 ); if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ return; } v = sqlite3GetVdbe(pParse); if( !v ) return; if( type!=TK_DEFERRED ){ for(i=0; i<db->nDb; i++){ sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); sqlite3VdbeUsesBtree(v, i); } } sqlite3VdbeAddOp0(v, OP_AutoCommit); } /* ** Generate VDBE code for a COMMIT statement. */ SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){ Vdbe *v; assert( pParse!=0 ); assert( pParse->db!=0 ); if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ return; } v = sqlite3GetVdbe(pParse); if( v ){ sqlite3VdbeAddOp1(v, OP_AutoCommit, 1); } } /* ** Generate VDBE code for a ROLLBACK statement. */ SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){ Vdbe *v; assert( pParse!=0 ); assert( pParse->db!=0 ); if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ return; } v = sqlite3GetVdbe(pParse); if( v ){ sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); } } /* ** This function is called by the parser when it parses a command to create, ** release or rollback an SQL savepoint. */ SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ char *zName = sqlite3NameFromToken(pParse->db, pName); if( zName ){ Vdbe *v = sqlite3GetVdbe(pParse); #ifndef SQLITE_OMIT_AUTHORIZATION static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); #endif if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ sqlite3DbFree(pParse->db, zName); return; } sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); } } /* ** Make sure the TEMP database is open and available for use. Return ** the number of errors. Leave any error messages in the pParse structure. */ SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){ sqlite3 *db = pParse->db; if( db->aDb[1].pBt==0 && !pParse->explain ){ int rc; Btree *pBt; static const int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TEMP_DB; rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); if( rc!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, "unable to open a temporary database " "file for storing temporary tables"); pParse->rc = rc; return 1; } db->aDb[1].pBt = pBt; assert( db->aDb[1].pSchema ); if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ sqlite3OomFault(db); return 1; } } return 0; } /* ** Record the fact that the schema cookie will need to be verified ** for database iDb. The code to actually verify the schema cookie ** will occur at the end of the top-level VDBE and will be generated ** later, by sqlite3FinishCoding(). */ SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ Parse *pToplevel = sqlite3ParseToplevel(pParse); assert( iDb>=0 && iDb<pParse->db->nDb ); assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 ); assert( iDb<SQLITE_MAX_ATTACHED+2 ); assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) ); if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ DbMaskSet(pToplevel->cookieMask, iDb); if( !OMIT_TEMPDB && iDb==1 ){ sqlite3OpenTempDatabase(pToplevel); } } } /* ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each ** attached database. Otherwise, invoke it for the database named zDb only. */ SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ sqlite3 *db = pParse->db; int i; for(i=0; i<db->nDb; i++){ Db *pDb = &db->aDb[i]; if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){ sqlite3CodeVerifySchema(pParse, i); } } } /* ** Generate VDBE code that prepares for doing an operation that ** might change the database. ** ** This routine starts a new transaction if we are not already within ** a transaction. If we are already within a transaction, then a checkpoint ** is set if the setStatement parameter is true. A checkpoint should ** be set for operations that might fail (due to a constraint) part of ** the way through and which will need to undo some writes without having to ** rollback the whole transaction. For operations where all constraints ** can be checked before any changes are made to the database, it is never ** necessary to undo a write and the checkpoint should not be set. */ SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ Parse *pToplevel = sqlite3ParseToplevel(pParse); sqlite3CodeVerifySchema(pParse, iDb); DbMaskSet(pToplevel->writeMask, iDb); pToplevel->isMultiWrite |= setStatement; } /* ** Indicate that the statement currently under construction might write ** more than one entry (example: deleting one row then inserting another, ** inserting multiple rows in a table, or inserting a row and index entries.) ** If an abort occurs after some of these writes have completed, then it will ** be necessary to undo the completed writes. */ SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pToplevel->isMultiWrite = 1; } /* ** The code generator calls this routine if is discovers that it is ** possible to abort a statement prior to completion. In order to ** perform this abort without corrupting the database, we need to make ** sure that the statement is protected by a statement transaction. ** ** Technically, we only need to set the mayAbort flag if the ** isMultiWrite flag was previously set. There is a time dependency ** such that the abort must occur after the multiwrite. This makes ** some statements involving the REPLACE conflict resolution algorithm ** go a little faster. But taking advantage of this time dependency ** makes it more difficult to prove that the code is correct (in ** particular, it prevents us from writing an effective ** implementation of sqlite3AssertMayAbort()) and so we have chosen ** to take the safe route and skip the optimization. */ SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pToplevel->mayAbort = 1; } /* ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT ** error. The onError parameter determines which (if any) of the statement ** and/or current transaction is rolled back. */ SQLITE_PRIVATE void sqlite3HaltConstraint( Parse *pParse, /* Parsing context */ int errCode, /* extended error code */ int onError, /* Constraint type */ char *p4, /* Error message */ i8 p4type, /* P4_STATIC or P4_TRANSIENT */ u8 p5Errmsg /* P5_ErrMsg type */ ){ Vdbe *v = sqlite3GetVdbe(pParse); assert( (errCode&0xff)==SQLITE_CONSTRAINT ); if( onError==OE_Abort ){ sqlite3MayAbort(pParse); } sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); sqlite3VdbeChangeP5(v, p5Errmsg); } /* ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. */ SQLITE_PRIVATE void sqlite3UniqueConstraint( Parse *pParse, /* Parsing context */ int onError, /* Constraint type */ Index *pIdx /* The index that triggers the constraint */ ){ char *zErr; int j; StrAccum errMsg; Table *pTab = pIdx->pTable; sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200); if( pIdx->aColExpr ){ sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName); }else{ for(j=0; j<pIdx->nKeyCol; j++){ char *zCol; assert( pIdx->aiColumn[j]>=0 ); zCol = pTab->aCol[pIdx->aiColumn[j]].zName; if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2); sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol); } } zErr = sqlite3StrAccumFinish(&errMsg); sqlite3HaltConstraint(pParse, IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY : SQLITE_CONSTRAINT_UNIQUE, onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); } /* ** Code an OP_Halt due to non-unique rowid. */ SQLITE_PRIVATE void sqlite3RowidConstraint( Parse *pParse, /* Parsing context */ int onError, /* Conflict resolution algorithm */ Table *pTab /* The table with the non-unique rowid */ ){ char *zMsg; int rc; if( pTab->iPKey>=0 ){ zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, pTab->aCol[pTab->iPKey].zName); rc = SQLITE_CONSTRAINT_PRIMARYKEY; }else{ zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); rc = SQLITE_CONSTRAINT_ROWID; } sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, P5_ConstraintUnique); } /* ** Check to see if pIndex uses the collating sequence pColl. Return ** true if it does and false if it does not. */ #ifndef SQLITE_OMIT_REINDEX static int collationMatch(const char *zColl, Index *pIndex){ int i; assert( zColl!=0 ); for(i=0; i<pIndex->nColumn; i++){ const char *z = pIndex->azColl[i]; assert( z!=0 || pIndex->aiColumn[i]<0 ); if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ return 1; } } return 0; } #endif /* ** Recompute all indices of pTab that use the collating sequence pColl. ** If pColl==0 then recompute all indices of pTab. */ #ifndef SQLITE_OMIT_REINDEX static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ Index *pIndex; /* An index associated with pTab */ for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ if( zColl==0 || collationMatch(zColl, pIndex) ){ int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3RefillIndex(pParse, pIndex, -1); } } } #endif /* ** Recompute all indices of all tables in all databases where the ** indices use the collating sequence pColl. If pColl==0 then recompute ** all indices everywhere. */ #ifndef SQLITE_OMIT_REINDEX static void reindexDatabases(Parse *pParse, char const *zColl){ Db *pDb; /* A single database */ int iDb; /* The database index number */ sqlite3 *db = pParse->db; /* The database connection */ HashElem *k; /* For looping over tables in pDb */ Table *pTab; /* A table in the database */ assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ assert( pDb!=0 ); for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ pTab = (Table*)sqliteHashData(k); reindexTable(pParse, pTab, zColl); } } } #endif /* ** Generate code for the REINDEX command. ** ** REINDEX -- 1 ** REINDEX <collation> -- 2 ** REINDEX ?<database>.?<tablename> -- 3 ** REINDEX ?<database>.?<indexname> -- 4 ** ** Form 1 causes all indices in all attached databases to be rebuilt. ** Form 2 rebuilds all indices in all databases that use the named ** collating function. Forms 3 and 4 rebuild the named index or all ** indices associated with the named table. */ #ifndef SQLITE_OMIT_REINDEX SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ char *z; /* Name of a table or index */ const char *zDb; /* Name of the database */ Table *pTab; /* A table in the database */ Index *pIndex; /* An index associated with pTab */ int iDb; /* The database index number */ sqlite3 *db = pParse->db; /* The database connection */ Token *pObjName; /* Name of the table or index to be reindexed */ /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ return; } if( pName1==0 ){ reindexDatabases(pParse, 0); return; }else if( NEVER(pName2==0) || pName2->z==0 ){ char *zColl; assert( pName1->z ); zColl = sqlite3NameFromToken(pParse->db, pName1); if( !zColl ) return; pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); if( pColl ){ reindexDatabases(pParse, zColl); sqlite3DbFree(db, zColl); return; } sqlite3DbFree(db, zColl); } iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); if( iDb<0 ) return; z = sqlite3NameFromToken(db, pObjName); if( z==0 ) return; zDb = db->aDb[iDb].zDbSName; pTab = sqlite3FindTable(db, z, zDb); if( pTab ){ reindexTable(pParse, pTab, 0); sqlite3DbFree(db, z); return; } pIndex = sqlite3FindIndex(db, z, zDb); sqlite3DbFree(db, z); if( pIndex ){ sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3RefillIndex(pParse, pIndex, -1); return; } sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); } #endif /* ** Return a KeyInfo structure that is appropriate for the given Index. ** ** The caller should invoke sqlite3KeyInfoUnref() on the returned object ** when it has finished using it. */ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ int i; int nCol = pIdx->nColumn; int nKey = pIdx->nKeyCol; KeyInfo *pKey; if( pParse->nErr ) return 0; if( pIdx->uniqNotNull ){ pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); }else{ pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); } if( pKey ){ assert( sqlite3KeyInfoIsWriteable(pKey) ); for(i=0; i<nCol; i++){ const char *zColl = pIdx->azColl[i]; pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : sqlite3LocateCollSeq(pParse, zColl); pKey->aSortOrder[i] = pIdx->aSortOrder[i]; } if( pParse->nErr ){ sqlite3KeyInfoUnref(pKey); pKey = 0; } } return pKey; } #ifndef SQLITE_OMIT_CTE /* ** This routine is invoked once per CTE by the parser while parsing a ** WITH clause. */ SQLITE_PRIVATE With *sqlite3WithAdd( Parse *pParse, /* Parsing context */ With *pWith, /* Existing WITH clause, or NULL */ Token *pName, /* Name of the common-table */ ExprList *pArglist, /* Optional column name list for the table */ Select *pQuery /* Query used to initialize the table */ ){ sqlite3 *db = pParse->db; With *pNew; char *zName; /* Check that the CTE name is unique within this WITH clause. If ** not, store an error in the Parse structure. */ zName = sqlite3NameFromToken(pParse->db, pName); if( zName && pWith ){ int i; for(i=0; i<pWith->nCte; i++){ if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); } } } if( pWith ){ int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); pNew = sqlite3DbRealloc(db, pWith, nByte); }else{ pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); } assert( (pNew!=0 && zName!=0) || db->mallocFailed ); if( db->mallocFailed ){ sqlite3ExprListDelete(db, pArglist); sqlite3SelectDelete(db, pQuery); sqlite3DbFree(db, zName); pNew = pWith; }else{ pNew->a[pNew->nCte].pSelect = pQuery; pNew->a[pNew->nCte].pCols = pArglist; pNew->a[pNew->nCte].zName = zName; pNew->a[pNew->nCte].zCteErr = 0; pNew->nCte++; } return pNew; } /* ** Free the contents of the With object passed as the second argument. */ SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){ if( pWith ){ int i; for(i=0; i<pWith->nCte; i++){ struct Cte *pCte = &pWith->a[i]; sqlite3ExprListDelete(db, pCte->pCols); sqlite3SelectDelete(db, pCte->pSelect); sqlite3DbFree(db, pCte->zName); } sqlite3DbFree(db, pWith); } } #endif /* !defined(SQLITE_OMIT_CTE) */ /************** End of build.c ***********************************************/ /************** Begin file callback.c ****************************************/ /* ** 2005 May 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains functions used to access the internal hash tables ** of user defined functions and collation sequences. */ /* #include "sqliteInt.h" */ /* ** Invoke the 'collation needed' callback to request a collation sequence ** in the encoding enc of name zName, length nName. */ static void callCollNeeded(sqlite3 *db, int enc, const char *zName){ assert( !db->xCollNeeded || !db->xCollNeeded16 ); if( db->xCollNeeded ){ char *zExternal = sqlite3DbStrDup(db, zName); if( !zExternal ) return; db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal); sqlite3DbFree(db, zExternal); } #ifndef SQLITE_OMIT_UTF16 if( db->xCollNeeded16 ){ char const *zExternal; sqlite3_value *pTmp = sqlite3ValueNew(db); sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); if( zExternal ){ db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal); } sqlite3ValueFree(pTmp); } #endif } /* ** This routine is called if the collation factory fails to deliver a ** collation function in the best encoding but there may be other versions ** of this collation function (for other text encodings) available. Use one ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if ** possible. */ static int synthCollSeq(sqlite3 *db, CollSeq *pColl){ CollSeq *pColl2; char *z = pColl->zName; int i; static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 }; for(i=0; i<3; i++){ pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0); if( pColl2->xCmp!=0 ){ memcpy(pColl, pColl2, sizeof(CollSeq)); pColl->xDel = 0; /* Do not copy the destructor */ return SQLITE_OK; } } return SQLITE_ERROR; } /* ** This function is responsible for invoking the collation factory callback ** or substituting a collation sequence of a different encoding when the ** requested collation sequence is not available in the desired encoding. ** ** If it is not NULL, then pColl must point to the database native encoding ** collation sequence with name zName, length nName. ** ** The return value is either the collation sequence to be used in database ** db for collation type name zName, length nName, or NULL, if no collation ** sequence can be found. If no collation is found, leave an error message. ** ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq() */ SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq( Parse *pParse, /* Parsing context */ u8 enc, /* The desired encoding for the collating sequence */ CollSeq *pColl, /* Collating sequence with native encoding, or NULL */ const char *zName /* Collating sequence name */ ){ CollSeq *p; sqlite3 *db = pParse->db; p = pColl; if( !p ){ p = sqlite3FindCollSeq(db, enc, zName, 0); } if( !p || !p->xCmp ){ /* No collation sequence of this type for this encoding is registered. ** Call the collation factory to see if it can supply us with one. */ callCollNeeded(db, enc, zName); p = sqlite3FindCollSeq(db, enc, zName, 0); } if( p && !p->xCmp && synthCollSeq(db, p) ){ p = 0; } assert( !p || p->xCmp ); if( p==0 ){ sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName); } return p; } /* ** This routine is called on a collation sequence before it is used to ** check that it is defined. An undefined collation sequence exists when ** a database is loaded that contains references to collation sequences ** that have not been defined by sqlite3_create_collation() etc. ** ** If required, this routine calls the 'collation needed' callback to ** request a definition of the collating sequence. If this doesn't work, ** an equivalent collating sequence that uses a text encoding different ** from the main database is substituted, if one is available. */ SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){ if( pColl ){ const char *zName = pColl->zName; sqlite3 *db = pParse->db; CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName); if( !p ){ return SQLITE_ERROR; } assert( p==pColl ); } return SQLITE_OK; } /* ** Locate and return an entry from the db.aCollSeq hash table. If the entry ** specified by zName and nName is not found and parameter 'create' is ** true, then create a new entry. Otherwise return NULL. ** ** Each pointer stored in the sqlite3.aCollSeq hash table contains an ** array of three CollSeq structures. The first is the collation sequence ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be. ** ** Stored immediately after the three collation sequences is a copy of ** the collation sequence name. A pointer to this string is stored in ** each collation sequence structure. */ static CollSeq *findCollSeqEntry( sqlite3 *db, /* Database connection */ const char *zName, /* Name of the collating sequence */ int create /* Create a new entry if true */ ){ CollSeq *pColl; pColl = sqlite3HashFind(&db->aCollSeq, zName); if( 0==pColl && create ){ int nName = sqlite3Strlen30(zName); pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1); if( pColl ){ CollSeq *pDel = 0; pColl[0].zName = (char*)&pColl[3]; pColl[0].enc = SQLITE_UTF8; pColl[1].zName = (char*)&pColl[3]; pColl[1].enc = SQLITE_UTF16LE; pColl[2].zName = (char*)&pColl[3]; pColl[2].enc = SQLITE_UTF16BE; memcpy(pColl[0].zName, zName, nName); pColl[0].zName[nName] = 0; pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl); /* If a malloc() failure occurred in sqlite3HashInsert(), it will ** return the pColl pointer to be deleted (because it wasn't added ** to the hash table). */ assert( pDel==0 || pDel==pColl ); if( pDel!=0 ){ sqlite3OomFault(db); sqlite3DbFree(db, pDel); pColl = 0; } } } return pColl; } /* ** Parameter zName points to a UTF-8 encoded string nName bytes long. ** Return the CollSeq* pointer for the collation sequence named zName ** for the encoding 'enc' from the database 'db'. ** ** If the entry specified is not found and 'create' is true, then create a ** new entry. Otherwise return NULL. ** ** A separate function sqlite3LocateCollSeq() is a wrapper around ** this routine. sqlite3LocateCollSeq() invokes the collation factory ** if necessary and generates an error message if the collating sequence ** cannot be found. ** ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq() */ SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq( sqlite3 *db, u8 enc, const char *zName, int create ){ CollSeq *pColl; if( zName ){ pColl = findCollSeqEntry(db, zName, create); }else{ pColl = db->pDfltColl; } assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE ); if( pColl ) pColl += enc-1; return pColl; } /* During the search for the best function definition, this procedure ** is called to test how well the function passed as the first argument ** matches the request for a function with nArg arguments in a system ** that uses encoding enc. The value returned indicates how well the ** request is matched. A higher value indicates a better match. ** ** If nArg is -1 that means to only return a match (non-zero) if p->nArg ** is also -1. In other words, we are searching for a function that ** takes a variable number of arguments. ** ** If nArg is -2 that means that we are searching for any function ** regardless of the number of arguments it uses, so return a positive ** match score for any ** ** The returned value is always between 0 and 6, as follows: ** ** 0: Not a match. ** 1: UTF8/16 conversion required and function takes any number of arguments. ** 2: UTF16 byte order change required and function takes any number of args. ** 3: encoding matches and function takes any number of arguments ** 4: UTF8/16 conversion required - argument count matches exactly ** 5: UTF16 byte order conversion required - argument count matches exactly ** 6: Perfect match: encoding and argument count match exactly. ** ** If nArg==(-2) then any function with a non-null xSFunc is ** a perfect match and any function with xSFunc NULL is ** a non-match. */ #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */ static int matchQuality( FuncDef *p, /* The function we are evaluating for match quality */ int nArg, /* Desired number of arguments. (-1)==any */ u8 enc /* Desired text encoding */ ){ int match; /* nArg of -2 is a special case */ if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH; /* Wrong number of arguments means "no match" */ if( p->nArg!=nArg && p->nArg>=0 ) return 0; /* Give a better score to a function with a specific number of arguments ** than to function that accepts any number of arguments. */ if( p->nArg==nArg ){ match = 4; }else{ match = 1; } /* Bonus points if the text encoding matches */ if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){ match += 2; /* Exact encoding match */ }else if( (enc & p->funcFlags & 2)!=0 ){ match += 1; /* Both are UTF16, but with different byte orders */ } return match; } /* ** Search a FuncDefHash for a function with the given name. Return ** a pointer to the matching FuncDef if found, or 0 if there is no match. */ static FuncDef *functionSearch( int h, /* Hash of the name */ const char *zFunc /* Name of function */ ){ FuncDef *p; for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){ if( sqlite3StrICmp(p->zName, zFunc)==0 ){ return p; } } return 0; } /* ** Insert a new FuncDef into a FuncDefHash hash table. */ SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs( FuncDef *aDef, /* List of global functions to be inserted */ int nDef /* Length of the apDef[] list */ ){ int i; for(i=0; i<nDef; i++){ FuncDef *pOther; const char *zName = aDef[i].zName; int nName = sqlite3Strlen30(zName); int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ; pOther = functionSearch(h, zName); if( pOther ){ assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] ); aDef[i].pNext = pOther->pNext; pOther->pNext = &aDef[i]; }else{ aDef[i].pNext = 0; aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h]; sqlite3BuiltinFunctions.a[h] = &aDef[i]; } } } /* ** Locate a user function given a name, a number of arguments and a flag ** indicating whether the function prefers UTF-16 over UTF-8. Return a ** pointer to the FuncDef structure that defines that function, or return ** NULL if the function does not exist. ** ** If the createFlag argument is true, then a new (blank) FuncDef ** structure is created and liked into the "db" structure if a ** no matching function previously existed. ** ** If nArg is -2, then the first valid function found is returned. A ** function is valid if xSFunc is non-zero. The nArg==(-2) ** case is used to see if zName is a valid function name for some number ** of arguments. If nArg is -2, then createFlag must be 0. ** ** If createFlag is false, then a function with the required name and ** number of arguments may be returned even if the eTextRep flag does not ** match that requested. */ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( sqlite3 *db, /* An open database */ const char *zName, /* Name of the function. zero-terminated */ int nArg, /* Number of arguments. -1 means any number */ u8 enc, /* Preferred text encoding */ u8 createFlag /* Create new entry if true and does not otherwise exist */ ){ FuncDef *p; /* Iterator variable */ FuncDef *pBest = 0; /* Best match found so far */ int bestScore = 0; /* Score of best match */ int h; /* Hash value */ int nName; /* Length of the name */ assert( nArg>=(-2) ); assert( nArg>=(-1) || createFlag==0 ); nName = sqlite3Strlen30(zName); /* First search for a match amongst the application-defined functions. */ p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName); while( p ){ int score = matchQuality(p, nArg, enc); if( score>bestScore ){ pBest = p; bestScore = score; } p = p->pNext; } /* If no match is found, search the built-in functions. ** ** If the SQLITE_PreferBuiltin flag is set, then search the built-in ** functions even if a prior app-defined function was found. And give ** priority to built-in functions. ** ** Except, if createFlag is true, that means that we are trying to ** install a new function. Whatever FuncDef structure is returned it will ** have fields overwritten with new information appropriate for the ** new function. But the FuncDefs for built-in functions are read-only. ** So we must not search for built-ins when creating a new function. */ if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){ bestScore = 0; h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ; p = functionSearch(h, zName); while( p ){ int score = matchQuality(p, nArg, enc); if( score>bestScore ){ pBest = p; bestScore = score; } p = p->pNext; } } /* If the createFlag parameter is true and the search did not reveal an ** exact match for the name, number of arguments and encoding, then add a ** new entry to the hash table and return it. */ if( createFlag && bestScore<FUNC_PERFECT_MATCH && (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){ FuncDef *pOther; pBest->zName = (const char*)&pBest[1]; pBest->nArg = (u16)nArg; pBest->funcFlags = enc; memcpy((char*)&pBest[1], zName, nName+1); pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest); if( pOther==pBest ){ sqlite3DbFree(db, pBest); sqlite3OomFault(db); return 0; }else{ pBest->pNext = pOther; } } if( pBest && (pBest->xSFunc || createFlag) ){ return pBest; } return 0; } /* ** Free all resources held by the schema structure. The void* argument points ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the ** pointer itself, it just cleans up subsidiary resources (i.e. the contents ** of the schema hash tables). ** ** The Schema.cache_size variable is not cleared. */ SQLITE_PRIVATE void sqlite3SchemaClear(void *p){ Hash temp1; Hash temp2; HashElem *pElem; Schema *pSchema = (Schema *)p; temp1 = pSchema->tblHash; temp2 = pSchema->trigHash; sqlite3HashInit(&pSchema->trigHash); sqlite3HashClear(&pSchema->idxHash); for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){ sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem)); } sqlite3HashClear(&temp2); sqlite3HashInit(&pSchema->tblHash); for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){ Table *pTab = sqliteHashData(pElem); sqlite3DeleteTable(0, pTab); } sqlite3HashClear(&temp1); sqlite3HashClear(&pSchema->fkeyHash); pSchema->pSeqTab = 0; if( pSchema->schemaFlags & DB_SchemaLoaded ){ pSchema->iGeneration++; pSchema->schemaFlags &= ~DB_SchemaLoaded; } } /* ** Find and return the schema associated with a BTree. Create ** a new one if necessary. */ SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){ Schema * p; if( pBt ){ p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear); }else{ p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema)); } if( !p ){ sqlite3OomFault(db); }else if ( 0==p->file_format ){ sqlite3HashInit(&p->tblHash); sqlite3HashInit(&p->idxHash); sqlite3HashInit(&p->trigHash); sqlite3HashInit(&p->fkeyHash); p->enc = SQLITE_UTF8; } return p; } /************** End of callback.c ********************************************/ /************** Begin file delete.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** in order to generate code for DELETE FROM statements. */ /* #include "sqliteInt.h" */ /* ** While a SrcList can in general represent multiple tables and subqueries ** (as in the FROM clause of a SELECT statement) in this case it contains ** the name of a single table, as one might find in an INSERT, DELETE, ** or UPDATE statement. Look up that table in the symbol table and ** return a pointer. Set an error message and return NULL if the table ** name is not found or if any other error occurs. ** ** The following fields are initialized appropriate in pSrc: ** ** pSrc->a[0].pTab Pointer to the Table object ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one ** */ SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ struct SrcList_item *pItem = pSrc->a; Table *pTab; assert( pItem && pSrc->nSrc==1 ); pTab = sqlite3LocateTableItem(pParse, 0, pItem); sqlite3DeleteTable(pParse->db, pItem->pTab); pItem->pTab = pTab; if( pTab ){ pTab->nTabRef++; } if( sqlite3IndexedByLookup(pParse, pItem) ){ pTab = 0; } return pTab; } /* ** Check to make sure the given table is writable. If it is not ** writable, generate an error message and return 1. If it is ** writable return 0; */ SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ /* A table is not writable under the following circumstances: ** ** 1) It is a virtual table and no implementation of the xUpdate method ** has been provided, or ** 2) It is a system table (i.e. sqlite_master), this call is not ** part of a nested parse and writable_schema pragma has not ** been specified. ** ** In either case leave an error message in pParse and return non-zero. */ if( ( IsVirtual(pTab) && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ) || ( (pTab->tabFlags & TF_Readonly)!=0 && (pParse->db->flags & SQLITE_WriteSchema)==0 && pParse->nested==0 ) ){ sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); return 1; } #ifndef SQLITE_OMIT_VIEW if( !viewOk && pTab->pSelect ){ sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); return 1; } #endif return 0; } #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) /* ** Evaluate a view and store its result in an ephemeral table. The ** pWhere argument is an optional WHERE clause that restricts the ** set of rows in the view that are to be added to the ephemeral table. */ SQLITE_PRIVATE void sqlite3MaterializeView( Parse *pParse, /* Parsing context */ Table *pView, /* View definition */ Expr *pWhere, /* Optional WHERE clause to be added */ int iCur /* Cursor number for ephemeral table */ ){ SelectDest dest; Select *pSel; SrcList *pFrom; sqlite3 *db = pParse->db; int iDb = sqlite3SchemaToIndex(db, pView->pSchema); pWhere = sqlite3ExprDup(db, pWhere, 0); pFrom = sqlite3SrcListAppend(db, 0, 0, 0); if( pFrom ){ assert( pFrom->nSrc==1 ); pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName); pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName); assert( pFrom->a[0].pOn==0 ); assert( pFrom->a[0].pUsing==0 ); } pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, SF_IncludeHidden, 0, 0); sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); sqlite3Select(pParse, pSel, &dest); sqlite3SelectDelete(db, pSel); } #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) /* ** Generate an expression tree to implement the WHERE, ORDER BY, ** and LIMIT/OFFSET portion of DELETE and UPDATE statements. ** ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; ** \__________________________/ ** pLimitWhere (pInClause) */ SQLITE_PRIVATE Expr *sqlite3LimitWhere( Parse *pParse, /* The parser context */ SrcList *pSrc, /* the FROM clause -- which tables to scan */ Expr *pWhere, /* The WHERE clause. May be null */ ExprList *pOrderBy, /* The ORDER BY clause. May be null */ Expr *pLimit, /* The LIMIT clause. May be null */ Expr *pOffset, /* The OFFSET clause. May be null */ char *zStmtType /* Either DELETE or UPDATE. For err msgs. */ ){ Expr *pWhereRowid = NULL; /* WHERE rowid .. */ Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ Expr *pSelectRowid = NULL; /* SELECT rowid ... */ ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */ SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */ Select *pSelect = NULL; /* Complete SELECT tree */ /* Check that there isn't an ORDER BY without a LIMIT clause. */ if( pOrderBy && (pLimit == 0) ) { sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); goto limit_where_cleanup; } /* We only need to generate a select expression if there ** is a limit/offset term to enforce. */ if( pLimit == 0 ) { /* if pLimit is null, pOffset will always be null as well. */ assert( pOffset == 0 ); return pWhere; } /* Generate a select expression tree to enforce the limit/offset ** term for the DELETE or UPDATE statement. For example: ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 ** becomes: ** DELETE FROM table_a WHERE rowid IN ( ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 ** ); */ pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0); if( pSelectRowid == 0 ) goto limit_where_cleanup; pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid); if( pEList == 0 ) goto limit_where_cleanup; /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree ** and the SELECT subtree. */ pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0); if( pSelectSrc == 0 ) { sqlite3ExprListDelete(pParse->db, pEList); goto limit_where_cleanup; } /* generate the SELECT expression tree. */ pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0, pOrderBy,0,pLimit,pOffset); if( pSelect == 0 ) return 0; /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0); pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0; sqlite3PExprAddSelect(pParse, pInClause, pSelect); return pInClause; limit_where_cleanup: sqlite3ExprDelete(pParse->db, pWhere); sqlite3ExprListDelete(pParse->db, pOrderBy); sqlite3ExprDelete(pParse->db, pLimit); sqlite3ExprDelete(pParse->db, pOffset); return 0; } #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */ /* && !defined(SQLITE_OMIT_SUBQUERY) */ /* ** Generate code for a DELETE FROM statement. ** ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; ** \________/ \________________/ ** pTabList pWhere */ SQLITE_PRIVATE void sqlite3DeleteFrom( Parse *pParse, /* The parser context */ SrcList *pTabList, /* The table from which we should delete things */ Expr *pWhere /* The WHERE clause. May be null */ ){ Vdbe *v; /* The virtual database engine */ Table *pTab; /* The table from which records will be deleted */ int i; /* Loop counter */ WhereInfo *pWInfo; /* Information about the WHERE clause */ Index *pIdx; /* For looping over indices of the table */ int iTabCur; /* Cursor number for the table */ int iDataCur = 0; /* VDBE cursor for the canonical data source */ int iIdxCur = 0; /* Cursor number of the first index */ int nIdx; /* Number of indices */ sqlite3 *db; /* Main database structure */ AuthContext sContext; /* Authorization context */ NameContext sNC; /* Name context to resolve expressions in */ int iDb; /* Database number */ int memCnt = -1; /* Memory cell used for change counting */ int rcauth; /* Value returned by authorization callback */ int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */ int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */ Index *pPk; /* The PRIMARY KEY index on the table */ int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */ i16 nPk = 1; /* Number of columns in the PRIMARY KEY */ int iKey; /* Memory cell holding key of row to be deleted */ i16 nKey; /* Number of memory cells in the row key */ int iEphCur = 0; /* Ephemeral table holding all primary key values */ int iRowSet = 0; /* Register for rowset of rows to delete */ int addrBypass = 0; /* Address of jump over the delete logic */ int addrLoop = 0; /* Top of the delete loop */ int addrEphOpen = 0; /* Instruction to open the Ephemeral table */ int bComplex; /* True if there are triggers or FKs or ** subqueries in the WHERE clause */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True if attempting to delete from a view */ Trigger *pTrigger; /* List of table triggers, if required */ #endif memset(&sContext, 0, sizeof(sContext)); db = pParse->db; if( pParse->nErr || db->mallocFailed ){ goto delete_from_cleanup; } assert( pTabList->nSrc==1 ); /* Locate the table which we want to delete. This table has to be ** put in an SrcList structure because some of the subroutines we ** will be calling are designed to work with multiple tables and expect ** an SrcList* parameter instead of just a Table* parameter. */ pTab = sqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ) goto delete_from_cleanup; /* Figure out if we have any triggers and if the table being ** deleted from is a view */ #ifndef SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); isView = pTab->pSelect!=0; bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0); #else # define pTrigger 0 # define isView 0 #endif #ifdef SQLITE_OMIT_VIEW # undef isView # define isView 0 #endif /* If pTab is really a view, make sure it has been initialized. */ if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto delete_from_cleanup; } if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ goto delete_from_cleanup; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb<db->nDb ); rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, db->aDb[iDb].zDbSName); assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE ); if( rcauth==SQLITE_DENY ){ goto delete_from_cleanup; } assert(!isView || pTrigger); /* Assign cursor numbers to the table and all its indices. */ assert( pTabList->nSrc==1 ); iTabCur = pTabList->a[0].iCursor = pParse->nTab++; for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ pParse->nTab++; } /* Start the view context */ if( isView ){ sqlite3AuthContextPush(pParse, &sContext, pTab->zName); } /* Begin generating code. */ v = sqlite3GetVdbe(pParse); if( v==0 ){ goto delete_from_cleanup; } if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, 1, iDb); /* If we are trying to delete from a view, realize that view into ** an ephemeral table. */ #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) if( isView ){ sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur); iDataCur = iIdxCur = iTabCur; } #endif /* Resolve the column names in the WHERE clause. */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; if( sqlite3ResolveExprNames(&sNC, pWhere) ){ goto delete_from_cleanup; } /* Initialize the counter of the number of rows deleted, if ** we are counting rows. */ if( db->flags & SQLITE_CountRows ){ memCnt = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); } #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION /* Special case: A DELETE without a WHERE clause deletes everything. ** It is easier just to erase the whole table. Prior to version 3.6.5, ** this optimization caused the row change count (the value returned by ** API function sqlite3_count_changes) to be set incorrectly. */ if( rcauth==SQLITE_OK && pWhere==0 && !bComplex && !IsVirtual(pTab) #ifdef SQLITE_ENABLE_PREUPDATE_HOOK && db->xPreUpdateCallback==0 #endif ){ assert( !isView ); sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); if( HasRowid(pTab) ){ sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt, pTab->zName, P4_STATIC); } for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ assert( pIdx->pSchema==pTab->pSchema ); sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); } }else #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ { u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE; if( sNC.ncFlags & NC_VarSelect ) bComplex = 1; wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW); if( HasRowid(pTab) ){ /* For a rowid table, initialize the RowSet to an empty set */ pPk = 0; nPk = 1; iRowSet = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); }else{ /* For a WITHOUT ROWID table, create an ephemeral table used to ** hold all primary keys for rows to be deleted. */ pPk = sqlite3PrimaryKeyIndex(pTab); assert( pPk!=0 ); nPk = pPk->nKeyCol; iPk = pParse->nMem+1; pParse->nMem += nPk; iEphCur = pParse->nTab++; addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk); sqlite3VdbeSetP4KeyInfo(pParse, pPk); } /* Construct a query to find the rowid or primary key for every row ** to be deleted, based on the WHERE clause. Set variable eOnePass ** to indicate the strategy used to implement this delete: ** ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted. */ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1); if( pWInfo==0 ) goto delete_from_cleanup; eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI ); assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF ); /* Keep track of the number of rows to be deleted */ if( db->flags & SQLITE_CountRows ){ sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); } /* Extract the rowid or primary key for the current row */ if( pPk ){ for(i=0; i<nPk; i++){ assert( pPk->aiColumn[i]>=0 ); sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, pPk->aiColumn[i], iPk+i); } iKey = iPk; }else{ iKey = pParse->nMem + 1; iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0); if( iKey>pParse->nMem ) pParse->nMem = iKey; } if( eOnePass!=ONEPASS_OFF ){ /* For ONEPASS, no need to store the rowid/primary-key. There is only ** one, so just keep it in its register(s) and fall through to the ** delete code. */ nKey = nPk; /* OP_Found will use an unpacked key */ aToOpen = sqlite3DbMallocRawNN(db, nIdx+2); if( aToOpen==0 ){ sqlite3WhereEnd(pWInfo); goto delete_from_cleanup; } memset(aToOpen, 1, nIdx+1); aToOpen[nIdx+1] = 0; if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0; if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0; if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen); }else{ if( pPk ){ /* Add the PK key for this row to the temporary table */ iKey = ++pParse->nMem; nKey = 0; /* Zero tells OP_Found to use a composite key */ sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey, sqlite3IndexAffinityStr(pParse->db, pPk), nPk); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk); }else{ /* Add the rowid of the row to be deleted to the RowSet */ nKey = 1; /* OP_Seek always uses a single rowid */ sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey); } } /* If this DELETE cannot use the ONEPASS strategy, this is the ** end of the WHERE loop */ if( eOnePass!=ONEPASS_OFF ){ addrBypass = sqlite3VdbeMakeLabel(v); }else{ sqlite3WhereEnd(pWInfo); } /* Unless this is a view, open cursors for the table we are ** deleting from and all its indices. If this is a view, then the ** only effect this statement has is to fire the INSTEAD OF ** triggers. */ if( !isView ){ int iAddrOnce = 0; if( eOnePass==ONEPASS_MULTI ){ iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } testcase( IsVirtual(pTab) ); sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE, iTabCur, aToOpen, &iDataCur, &iIdxCur); assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur ); assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 ); if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce); } /* Set up a loop over the rowids/primary-keys that were found in the ** where-clause loop above. */ if( eOnePass!=ONEPASS_OFF ){ assert( nKey==nPk ); /* OP_Found will use an unpacked key */ if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){ assert( pPk!=0 || pTab->pSelect!=0 ); sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey); VdbeCoverage(v); } }else if( pPk ){ addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey); assert( nKey==0 ); /* OP_Found will use a composite key */ }else{ addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey); VdbeCoverage(v); assert( nKey==1 ); } /* Delete the row */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB); sqlite3VdbeChangeP5(v, OE_Abort); assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); sqlite3MayAbort(pParse); if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){ pParse->isMultiWrite = 0; } }else #endif { int count = (pParse->nested==0); /* True to count changes */ sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]); } /* End of the loop over all rowids/primary-keys. */ if( eOnePass!=ONEPASS_OFF ){ sqlite3VdbeResolveLabel(v, addrBypass); sqlite3WhereEnd(pWInfo); }else if( pPk ){ sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrLoop); }else{ sqlite3VdbeGoto(v, addrLoop); sqlite3VdbeJumpHere(v, addrLoop); } } /* End non-truncate path */ /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if( pParse->nested==0 && pParse->pTriggerTab==0 ){ sqlite3AutoincrementEnd(pParse); } /* Return the number of rows that were deleted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); } delete_from_cleanup: sqlite3AuthContextPop(&sContext); sqlite3SrcListDelete(db, pTabList); sqlite3ExprDelete(db, pWhere); sqlite3DbFree(db, aToOpen); return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** they may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ #ifdef isView #undef isView #endif #ifdef pTrigger #undef pTrigger #endif /* ** This routine generates VDBE code that causes a single row of a ** single table to be deleted. Both the original table entry and ** all indices are removed. ** ** Preconditions: ** ** 1. iDataCur is an open cursor on the btree that is the canonical data ** store for the table. (This will be either the table itself, ** in the case of a rowid table, or the PRIMARY KEY index in the case ** of a WITHOUT ROWID table.) ** ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number iIdxCur+i for the i-th index. ** ** 3. The primary key for the row to be deleted must be stored in a ** sequence of nPk memory cells starting at iPk. If nPk==0 that means ** that a search record formed from OP_MakeRecord is contained in the ** single memory location iPk. ** ** eMode: ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF ** then this function must seek iDataCur to the entry identified by iPk ** and nPk before reading from it. ** ** If eMode is ONEPASS_MULTI, then this call is being made as part ** of a ONEPASS delete that affects multiple rows. In this case, if ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as ** iDataCur, then its position should be preserved following the delete ** operation. Or, if iIdxNoSeek is not a valid cursor number, the ** position of iDataCur should be preserved instead. ** ** iIdxNoSeek: ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur, ** then it identifies an index cursor (from within array of cursors ** starting at iIdxCur) that already points to the index entry to be deleted. ** Except, this optimization is disabled if there are BEFORE triggers since ** the trigger body might have moved the cursor. */ SQLITE_PRIVATE void sqlite3GenerateRowDelete( Parse *pParse, /* Parsing context */ Table *pTab, /* Table containing the row to be deleted */ Trigger *pTrigger, /* List of triggers to (potentially) fire */ int iDataCur, /* Cursor from which column data is extracted */ int iIdxCur, /* First index cursor */ int iPk, /* First memory cell containing the PRIMARY KEY */ i16 nPk, /* Number of PRIMARY KEY memory cells */ u8 count, /* If non-zero, increment the row change counter */ u8 onconf, /* Default ON CONFLICT policy for triggers */ u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */ int iIdxNoSeek /* Cursor number of cursor that does not need seeking */ ){ Vdbe *v = pParse->pVdbe; /* Vdbe */ int iOld = 0; /* First register in OLD.* array */ int iLabel; /* Label resolved to end of generated code */ u8 opSeek; /* Seek opcode */ /* Vdbe is guaranteed to have been allocated by this stage. */ assert( v ); VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)", iDataCur, iIdxCur, iPk, (int)nPk)); /* Seek cursor iCur to the row to delete. If this row no longer exists ** (this can happen if a trigger program has already deleted it), do ** not attempt to delete it or fire any DELETE triggers. */ iLabel = sqlite3VdbeMakeLabel(v); opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound; if( eMode==ONEPASS_OFF ){ sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); VdbeCoverageIf(v, opSeek==OP_NotExists); VdbeCoverageIf(v, opSeek==OP_NotFound); } /* If there are any triggers to fire, allocate a range of registers to ** use for the old.* references in the triggers. */ if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ u32 mask; /* Mask of OLD.* columns in use */ int iCol; /* Iterator used while populating OLD.* */ int addrStart; /* Start of BEFORE trigger programs */ /* TODO: Could use temporary registers here. Also could attempt to ** avoid copying the contents of the rowid register. */ mask = sqlite3TriggerColmask( pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf ); mask |= sqlite3FkOldmask(pParse, pTab); iOld = pParse->nMem+1; pParse->nMem += (1 + pTab->nCol); /* Populate the OLD.* pseudo-table register array. These values will be ** used by any BEFORE and AFTER triggers that exist. */ sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld); for(iCol=0; iCol<pTab->nCol; iCol++){ testcase( mask!=0xffffffff && iCol==31 ); testcase( mask!=0xffffffff && iCol==32 ); if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1); } } /* Invoke BEFORE DELETE trigger programs. */ addrStart = sqlite3VdbeCurrentAddr(v); sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel ); /* If any BEFORE triggers were coded, then seek the cursor to the ** row to be deleted again. It may be that the BEFORE triggers moved ** the cursor or already deleted the row that the cursor was ** pointing to. ** ** Also disable the iIdxNoSeek optimization since the BEFORE trigger ** may have moved that cursor. */ if( addrStart<sqlite3VdbeCurrentAddr(v) ){ sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); VdbeCoverageIf(v, opSeek==OP_NotExists); VdbeCoverageIf(v, opSeek==OP_NotFound); testcase( iIdxNoSeek>=0 ); iIdxNoSeek = -1; } /* Do FK processing. This call checks that any FK constraints that ** refer to this table (i.e. constraints attached to other tables) ** are not violated by deleting this row. */ sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0); } /* Delete the index and table entries. Skip this step if pTab is really ** a view (in which case the only effect of the DELETE statement is to ** fire the INSTEAD OF triggers). ** ** If variable 'count' is non-zero, then this OP_Delete instruction should ** invoke the update-hook. The pre-update-hook, on the other hand should ** be invoked unless table pTab is a system table. The difference is that ** the update-hook is not invoked for rows removed by REPLACE, but the ** pre-update-hook is. */ if( pTab->pSelect==0 ){ u8 p5 = 0; sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek); sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0)); if( pParse->nested==0 ){ sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE); } if( eMode!=ONEPASS_OFF ){ sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE); } if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){ sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek); } if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION; sqlite3VdbeChangeP5(v, p5); } /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just deleted. */ sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); /* Invoke AFTER DELETE trigger programs. */ sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel ); /* Jump here if the row had already been deleted before any BEFORE ** trigger programs were invoked. Or if a trigger program throws a ** RAISE(IGNORE) exception. */ sqlite3VdbeResolveLabel(v, iLabel); VdbeModuleComment((v, "END: GenRowDel()")); } /* ** This routine generates VDBE code that causes the deletion of all ** index entries associated with a single row of a single table, pTab ** ** Preconditions: ** ** 1. A read/write cursor "iDataCur" must be open on the canonical storage ** btree for the table pTab. (This will be either the table itself ** for rowid tables or to the primary key index for WITHOUT ROWID ** tables.) ** ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex ** index is the 0-th index.) ** ** 3. The "iDataCur" cursor must be already be positioned on the row ** that is to be deleted. */ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Table containing the row to be deleted */ int iDataCur, /* Cursor of table holding data. */ int iIdxCur, /* First index cursor */ int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ int iIdxNoSeek /* Do not delete from this cursor */ ){ int i; /* Index loop counter */ int r1 = -1; /* Register holding an index key */ int iPartIdxLabel; /* Jump destination for skipping partial index entries */ Index *pIdx; /* Current index */ Index *pPrior = 0; /* Prior index */ Vdbe *v; /* The prepared statement under construction */ Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */ v = pParse->pVdbe; pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ assert( iIdxCur+i!=iDataCur || pPk==pIdx ); if( aRegIdx!=0 && aRegIdx[i]==0 ) continue; if( pIdx==pPk ) continue; if( iIdxCur+i==iIdxNoSeek ) continue; VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName)); r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, &iPartIdxLabel, pPrior, r1); sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); pPrior = pIdx; } } /* ** Generate code that will assemble an index key and stores it in register ** regOut. The key with be for index pIdx which is an index on pTab. ** iCur is the index of a cursor open on the pTab table and pointing to ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then ** iCur must be the cursor of the PRIMARY KEY index. ** ** Return a register number which is the first in a block of ** registers that holds the elements of the index key. The ** block of registers has already been deallocated by the time ** this routine returns. ** ** If *piPartIdxLabel is not NULL, fill it in with a label and jump ** to that label if pIdx is a partial index that should be skipped. ** The label should be resolved using sqlite3ResolvePartIdxLabel(). ** A partial index should be skipped if its WHERE clause evaluates ** to false or null. If pIdx is not a partial index, *piPartIdxLabel ** will be set to zero which is an empty label that is ignored by ** sqlite3ResolvePartIdxLabel(). ** ** The pPrior and regPrior parameters are used to implement a cache to ** avoid unnecessary register loads. If pPrior is not NULL, then it is ** a pointer to a different index for which an index key has just been ** computed into register regPrior. If the current pIdx index is generating ** its key into the same sequence of registers and if pPrior and pIdx share ** a column in common, then the register corresponding to that column already ** holds the correct value and the loading of that register is skipped. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK ** on a table with multiple indices, and especially with the ROWID or ** PRIMARY KEY columns of the index. */ SQLITE_PRIVATE int sqlite3GenerateIndexKey( Parse *pParse, /* Parsing context */ Index *pIdx, /* The index for which to generate a key */ int iDataCur, /* Cursor number from which to take column data */ int regOut, /* Put the new key into this register if not 0 */ int prefixOnly, /* Compute only a unique prefix of the key */ int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */ Index *pPrior, /* Previously generated index key */ int regPrior /* Register holding previous generated key */ ){ Vdbe *v = pParse->pVdbe; int j; int regBase; int nCol; if( piPartIdxLabel ){ if( pIdx->pPartIdxWhere ){ *piPartIdxLabel = sqlite3VdbeMakeLabel(v); pParse->iSelfTab = iDataCur; sqlite3ExprCachePush(pParse); sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, SQLITE_JUMPIFNULL); }else{ *piPartIdxLabel = 0; } } nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn; regBase = sqlite3GetTempRange(pParse, nCol); if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0; for(j=0; j<nCol; j++){ if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] && pPrior->aiColumn[j]!=XN_EXPR ){ /* This column was already computed by the previous index */ continue; } sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j); /* If the column affinity is REAL but the number is an integer, then it ** might be stored in the table as an integer (using a compact ** representation) then converted to REAL by an OP_RealAffinity opcode. ** But we are getting ready to store this value back into an index, where ** it should be converted by to INTEGER again. So omit the OP_RealAffinity ** opcode if it is present */ sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity); } if( regOut ){ sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut); if( pIdx->pTable->pSelect ){ const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx); sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT); } } sqlite3ReleaseTempRange(pParse, regBase, nCol); return regBase; } /* ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label ** because it was a partial index, then this routine should be called to ** resolve that label. */ SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){ if( iLabel ){ sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel); sqlite3ExprCachePop(pParse); } } /************** End of delete.c **********************************************/ /************** Begin file func.c ********************************************/ /* ** 2002 February 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C-language implementations for many of the SQL ** functions of SQLite. (Some function, and in particular the date and ** time functions, are implemented separately.) */ /* #include "sqliteInt.h" */ /* #include <stdlib.h> */ /* #include <assert.h> */ /* #include "vdbeInt.h" */ /* ** Return the collating function associated with a function. */ static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ VdbeOp *pOp; assert( context->pVdbe!=0 ); pOp = &context->pVdbe->aOp[context->iOp-1]; assert( pOp->opcode==OP_CollSeq ); assert( pOp->p4type==P4_COLLSEQ ); return pOp->p4.pColl; } /* ** Indicate that the accumulator load should be skipped on this ** iteration of the aggregate loop. */ static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ context->skipFlag = 1; } /* ** Implementation of the non-aggregate min() and max() functions */ static void minmaxFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int i; int mask; /* 0 for min() or 0xffffffff for max() */ int iBest; CollSeq *pColl; assert( argc>1 ); mask = sqlite3_user_data(context)==0 ? 0 : -1; pColl = sqlite3GetFuncCollSeq(context); assert( pColl ); assert( mask==-1 || mask==0 ); iBest = 0; if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; for(i=1; i<argc; i++){ if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return; if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){ testcase( mask==0 ); iBest = i; } } sqlite3_result_value(context, argv[iBest]); } /* ** Return the type of the argument. */ static void typeofFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ const char *z = 0; UNUSED_PARAMETER(NotUsed); switch( sqlite3_value_type(argv[0]) ){ case SQLITE_INTEGER: z = "integer"; break; case SQLITE_TEXT: z = "text"; break; case SQLITE_FLOAT: z = "real"; break; case SQLITE_BLOB: z = "blob"; break; default: z = "null"; break; } sqlite3_result_text(context, z, -1, SQLITE_STATIC); } /* ** Implementation of the length() function */ static void lengthFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int len; assert( argc==1 ); UNUSED_PARAMETER(argc); switch( sqlite3_value_type(argv[0]) ){ case SQLITE_BLOB: case SQLITE_INTEGER: case SQLITE_FLOAT: { sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); break; } case SQLITE_TEXT: { const unsigned char *z = sqlite3_value_text(argv[0]); if( z==0 ) return; len = 0; while( *z ){ len++; SQLITE_SKIP_UTF8(z); } sqlite3_result_int(context, len); break; } default: { sqlite3_result_null(context); break; } } } /* ** Implementation of the abs() function. ** ** IMP: R-23979-26855 The abs(X) function returns the absolute value of ** the numeric argument X. */ static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ assert( argc==1 ); UNUSED_PARAMETER(argc); switch( sqlite3_value_type(argv[0]) ){ case SQLITE_INTEGER: { i64 iVal = sqlite3_value_int64(argv[0]); if( iVal<0 ){ if( iVal==SMALLEST_INT64 ){ /* IMP: R-31676-45509 If X is the integer -9223372036854775808 ** then abs(X) throws an integer overflow error since there is no ** equivalent positive 64-bit two complement value. */ sqlite3_result_error(context, "integer overflow", -1); return; } iVal = -iVal; } sqlite3_result_int64(context, iVal); break; } case SQLITE_NULL: { /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ sqlite3_result_null(context); break; } default: { /* Because sqlite3_value_double() returns 0.0 if the argument is not ** something that can be converted into a number, we have: ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob ** that cannot be converted to a numeric value. */ double rVal = sqlite3_value_double(argv[0]); if( rVal<0 ) rVal = -rVal; sqlite3_result_double(context, rVal); break; } } } /* ** Implementation of the instr() function. ** ** instr(haystack,needle) finds the first occurrence of needle ** in haystack and returns the number of previous characters plus 1, ** or 0 if needle does not occur within haystack. ** ** If both haystack and needle are BLOBs, then the result is one more than ** the number of bytes in haystack prior to the first occurrence of needle, ** or 0 if needle never occurs in haystack. */ static void instrFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zHaystack; const unsigned char *zNeedle; int nHaystack; int nNeedle; int typeHaystack, typeNeedle; int N = 1; int isText; UNUSED_PARAMETER(argc); typeHaystack = sqlite3_value_type(argv[0]); typeNeedle = sqlite3_value_type(argv[1]); if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; nHaystack = sqlite3_value_bytes(argv[0]); nNeedle = sqlite3_value_bytes(argv[1]); if( nNeedle>0 ){ if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ zHaystack = sqlite3_value_blob(argv[0]); zNeedle = sqlite3_value_blob(argv[1]); assert( zNeedle!=0 ); assert( zHaystack!=0 || nHaystack==0 ); isText = 0; }else{ zHaystack = sqlite3_value_text(argv[0]); zNeedle = sqlite3_value_text(argv[1]); isText = 1; if( zHaystack==0 || zNeedle==0 ) return; } while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){ N++; do{ nHaystack--; zHaystack++; }while( isText && (zHaystack[0]&0xc0)==0x80 ); } if( nNeedle>nHaystack ) N = 0; } sqlite3_result_int(context, N); } /* ** Implementation of the printf() function. */ static void printfFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ PrintfArguments x; StrAccum str; const char *zFormat; int n; sqlite3 *db = sqlite3_context_db_handle(context); if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ x.nArg = argc-1; x.nUsed = 0; x.apArg = argv+1; sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); str.printfFlags = SQLITE_PRINTF_SQLFUNC; sqlite3XPrintf(&str, zFormat, &x); n = str.nChar; sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, SQLITE_DYNAMIC); } } /* ** Implementation of the substr() function. ** ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. ** p1 is 1-indexed. So substr(x,1,1) returns the first character ** of x. If x is text, then we actually count UTF-8 characters. ** If x is a blob, then we count bytes. ** ** If p1 is negative, then we begin abs(p1) from the end of x[]. ** ** If p2 is negative, return the p2 characters preceding p1. */ static void substrFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *z; const unsigned char *z2; int len; int p0type; i64 p1, p2; int negP2 = 0; assert( argc==3 || argc==2 ); if( sqlite3_value_type(argv[1])==SQLITE_NULL || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) ){ return; } p0type = sqlite3_value_type(argv[0]); p1 = sqlite3_value_int(argv[1]); if( p0type==SQLITE_BLOB ){ len = sqlite3_value_bytes(argv[0]); z = sqlite3_value_blob(argv[0]); if( z==0 ) return; assert( len==sqlite3_value_bytes(argv[0]) ); }else{ z = sqlite3_value_text(argv[0]); if( z==0 ) return; len = 0; if( p1<0 ){ for(z2=z; *z2; len++){ SQLITE_SKIP_UTF8(z2); } } } #ifdef SQLITE_SUBSTR_COMPATIBILITY /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as ** as substr(X,1,N) - it returns the first N characters of X. This ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8] ** from 2009-02-02 for compatibility of applications that exploited the ** old buggy behavior. */ if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */ #endif if( argc==3 ){ p2 = sqlite3_value_int(argv[2]); if( p2<0 ){ p2 = -p2; negP2 = 1; } }else{ p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; } if( p1<0 ){ p1 += len; if( p1<0 ){ p2 += p1; if( p2<0 ) p2 = 0; p1 = 0; } }else if( p1>0 ){ p1--; }else if( p2>0 ){ p2--; } if( negP2 ){ p1 -= p2; if( p1<0 ){ p2 += p1; p1 = 0; } } assert( p1>=0 && p2>=0 ); if( p0type!=SQLITE_BLOB ){ while( *z && p1 ){ SQLITE_SKIP_UTF8(z); p1--; } for(z2=z; *z2 && p2; p2--){ SQLITE_SKIP_UTF8(z2); } sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, SQLITE_UTF8); }else{ if( p1+p2>len ){ p2 = len-p1; if( p2<0 ) p2 = 0; } sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); } } /* ** Implementation of the round() function */ #ifndef SQLITE_OMIT_FLOATING_POINT static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ int n = 0; double r; char *zBuf; assert( argc==1 || argc==2 ); if( argc==2 ){ if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; n = sqlite3_value_int(argv[1]); if( n>30 ) n = 30; if( n<0 ) n = 0; } if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; r = sqlite3_value_double(argv[0]); /* If Y==0 and X will fit in a 64-bit int, ** handle the rounding directly, ** otherwise use printf. */ if( n==0 && r>=0 && r<LARGEST_INT64-1 ){ r = (double)((sqlite_int64)(r+0.5)); }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){ r = -(double)((sqlite_int64)((-r)+0.5)); }else{ zBuf = sqlite3_mprintf("%.*f",n,r); if( zBuf==0 ){ sqlite3_result_error_nomem(context); return; } sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8); sqlite3_free(zBuf); } sqlite3_result_double(context, r); } #endif /* ** Allocate nByte bytes of space using sqlite3Malloc(). If the ** allocation fails, call sqlite3_result_error_nomem() to notify ** the database handle that malloc() has failed and return NULL. ** If nByte is larger than the maximum string or blob length, then ** raise an SQLITE_TOOBIG exception and return NULL. */ static void *contextMalloc(sqlite3_context *context, i64 nByte){ char *z; sqlite3 *db = sqlite3_context_db_handle(context); assert( nByte>0 ); testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ sqlite3_result_error_toobig(context); z = 0; }else{ z = sqlite3Malloc(nByte); if( !z ){ sqlite3_result_error_nomem(context); } } return z; } /* ** Implementation of the upper() and lower() SQL functions. */ static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ char *z1; const char *z2; int i, n; UNUSED_PARAMETER(argc); z2 = (char*)sqlite3_value_text(argv[0]); n = sqlite3_value_bytes(argv[0]); /* Verify that the call to _bytes() does not invalidate the _text() pointer */ assert( z2==(char*)sqlite3_value_text(argv[0]) ); if( z2 ){ z1 = contextMalloc(context, ((i64)n)+1); if( z1 ){ for(i=0; i<n; i++){ z1[i] = (char)sqlite3Toupper(z2[i]); } sqlite3_result_text(context, z1, n, sqlite3_free); } } } static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ char *z1; const char *z2; int i, n; UNUSED_PARAMETER(argc); z2 = (char*)sqlite3_value_text(argv[0]); n = sqlite3_value_bytes(argv[0]); /* Verify that the call to _bytes() does not invalidate the _text() pointer */ assert( z2==(char*)sqlite3_value_text(argv[0]) ); if( z2 ){ z1 = contextMalloc(context, ((i64)n)+1); if( z1 ){ for(i=0; i<n; i++){ z1[i] = sqlite3Tolower(z2[i]); } sqlite3_result_text(context, z1, n, sqlite3_free); } } } /* ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented ** as VDBE code so that unused argument values do not have to be computed. ** However, we still need some kind of function implementation for this ** routines in the function table. The noopFunc macro provides this. ** noopFunc will never be called so it doesn't matter what the implementation ** is. We might as well use the "version()" function as a substitute. */ #define noopFunc versionFunc /* Substitute function - never called */ /* ** Implementation of random(). Return a random integer. */ static void randomFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ sqlite_int64 r; UNUSED_PARAMETER2(NotUsed, NotUsed2); sqlite3_randomness(sizeof(r), &r); if( r<0 ){ /* We need to prevent a random number of 0x8000000000000000 ** (or -9223372036854775808) since when you do abs() of that ** number of you get the same value back again. To do this ** in a way that is testable, mask the sign bit off of negative ** values, resulting in a positive value. Then take the ** 2s complement of that positive value. The end result can ** therefore be no less than -9223372036854775807. */ r = -(r & LARGEST_INT64); } sqlite3_result_int64(context, r); } /* ** Implementation of randomblob(N). Return a random blob ** that is N bytes long. */ static void randomBlob( sqlite3_context *context, int argc, sqlite3_value **argv ){ int n; unsigned char *p; assert( argc==1 ); UNUSED_PARAMETER(argc); n = sqlite3_value_int(argv[0]); if( n<1 ){ n = 1; } p = contextMalloc(context, n); if( p ){ sqlite3_randomness(n, p); sqlite3_result_blob(context, (char*)p, n, sqlite3_free); } } /* ** Implementation of the last_insert_rowid() SQL function. The return ** value is the same as the sqlite3_last_insert_rowid() API function. */ static void last_insert_rowid( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ sqlite3 *db = sqlite3_context_db_handle(context); UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface ** function. */ sqlite3_result_int64(context, sqlite3_last_insert_rowid(db)); } /* ** Implementation of the changes() SQL function. ** ** IMP: R-62073-11209 The changes() SQL function is a wrapper ** around the sqlite3_changes() C/C++ function and hence follows the same ** rules for counting changes. */ static void changes( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ sqlite3 *db = sqlite3_context_db_handle(context); UNUSED_PARAMETER2(NotUsed, NotUsed2); sqlite3_result_int(context, sqlite3_changes(db)); } /* ** Implementation of the total_changes() SQL function. The return value is ** the same as the sqlite3_total_changes() API function. */ static void total_changes( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ sqlite3 *db = sqlite3_context_db_handle(context); UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-52756-41993 This function is a wrapper around the ** sqlite3_total_changes() C/C++ interface. */ sqlite3_result_int(context, sqlite3_total_changes(db)); } /* ** A structure defining how to do GLOB-style comparisons. */ struct compareInfo { u8 matchAll; /* "*" or "%" */ u8 matchOne; /* "?" or "_" */ u8 matchSet; /* "[" or 0 */ u8 noCase; /* true to ignore case differences */ }; /* ** For LIKE and GLOB matching on EBCDIC machines, assume that every ** character is exactly one byte in size. Also, provde the Utf8Read() ** macro for fast reading of the next character in the common case where ** the next character is ASCII. */ #if defined(SQLITE_EBCDIC) # define sqlite3Utf8Read(A) (*((*A)++)) # define Utf8Read(A) (*(A++)) #else # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A)) #endif static const struct compareInfo globInfo = { '*', '?', '[', 0 }; /* The correct SQL-92 behavior is for the LIKE operator to ignore ** case. Thus 'a' LIKE 'A' would be true. */ static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 }; /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator ** is case sensitive causing 'a' LIKE 'A' to be false */ static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 }; /* ** Possible error returns from patternMatch() */ #define SQLITE_MATCH 0 #define SQLITE_NOMATCH 1 #define SQLITE_NOWILDCARDMATCH 2 /* ** Compare two UTF-8 strings for equality where the first string is ** a GLOB or LIKE expression. Return values: ** ** SQLITE_MATCH: Match ** SQLITE_NOMATCH: No match ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards. ** ** Globbing rules: ** ** '*' Matches any sequence of zero or more characters. ** ** '?' Matches exactly one character. ** ** [...] Matches one character from the enclosed list of ** characters. ** ** [^...] Matches one character not in the enclosed list. ** ** With the [...] and [^...] matching, a ']' character can be included ** in the list by making it the first character after '[' or '^'. A ** range of characters can be specified using '-'. Example: ** "[a-z]" matches any single lower-case letter. To match a '-', make ** it the last character in the list. ** ** Like matching rules: ** ** '%' Matches any sequence of zero or more characters ** *** '_' Matches any one character ** ** Ec Where E is the "esc" character and c is any other ** character, including '%', '_', and esc, match exactly c. ** ** The comments within this routine usually assume glob matching. ** ** This routine is usually quick, but can be N**2 in the worst case. */ static int patternCompare( const u8 *zPattern, /* The glob pattern */ const u8 *zString, /* The string to compare against the glob */ const struct compareInfo *pInfo, /* Information about how to do the compare */ u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */ ){ u32 c, c2; /* Next pattern and input string chars */ u32 matchOne = pInfo->matchOne; /* "?" or "_" */ u32 matchAll = pInfo->matchAll; /* "*" or "%" */ u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */ const u8 *zEscaped = 0; /* One past the last escaped input char */ while( (c = Utf8Read(zPattern))!=0 ){ if( c==matchAll ){ /* Match "*" */ /* Skip over multiple "*" characters in the pattern. If there ** are also "?" characters, skip those as well, but consume a ** single character of the input string for each "?" skipped */ while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){ if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ return SQLITE_NOWILDCARDMATCH; } } if( c==0 ){ return SQLITE_MATCH; /* "*" at the end of the pattern matches */ }else if( c==matchOther ){ if( pInfo->matchSet==0 ){ c = sqlite3Utf8Read(&zPattern); if( c==0 ) return SQLITE_NOWILDCARDMATCH; }else{ /* "[...]" immediately follows the "*". We have to do a slow ** recursive search in this case, but it is an unusual case. */ assert( matchOther<0x80 ); /* '[' is a single-byte character */ while( *zString ){ int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther); if( bMatch!=SQLITE_NOMATCH ) return bMatch; SQLITE_SKIP_UTF8(zString); } return SQLITE_NOWILDCARDMATCH; } } /* At this point variable c contains the first character of the ** pattern string past the "*". Search in the input string for the ** first matching character and recursively continue the match from ** that point. ** ** For a case-insensitive search, set variable cx to be the same as ** c but in the other case and search the input string for either ** c or cx. */ if( c<=0x80 ){ u32 cx; int bMatch; if( noCase ){ cx = sqlite3Toupper(c); c = sqlite3Tolower(c); }else{ cx = c; } while( (c2 = *(zString++))!=0 ){ if( c2!=c && c2!=cx ) continue; bMatch = patternCompare(zPattern,zString,pInfo,matchOther); if( bMatch!=SQLITE_NOMATCH ) return bMatch; } }else{ int bMatch; while( (c2 = Utf8Read(zString))!=0 ){ if( c2!=c ) continue; bMatch = patternCompare(zPattern,zString,pInfo,matchOther); if( bMatch!=SQLITE_NOMATCH ) return bMatch; } } return SQLITE_NOWILDCARDMATCH; } if( c==matchOther ){ if( pInfo->matchSet==0 ){ c = sqlite3Utf8Read(&zPattern); if( c==0 ) return SQLITE_NOMATCH; zEscaped = zPattern; }else{ u32 prior_c = 0; int seen = 0; int invert = 0; c = sqlite3Utf8Read(&zString); if( c==0 ) return SQLITE_NOMATCH; c2 = sqlite3Utf8Read(&zPattern); if( c2=='^' ){ invert = 1; c2 = sqlite3Utf8Read(&zPattern); } if( c2==']' ){ if( c==']' ) seen = 1; c2 = sqlite3Utf8Read(&zPattern); } while( c2 && c2!=']' ){ if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ c2 = sqlite3Utf8Read(&zPattern); if( c>=prior_c && c<=c2 ) seen = 1; prior_c = 0; }else{ if( c==c2 ){ seen = 1; } prior_c = c2; } c2 = sqlite3Utf8Read(&zPattern); } if( c2==0 || (seen ^ invert)==0 ){ return SQLITE_NOMATCH; } continue; } } c2 = Utf8Read(zString); if( c==c2 ) continue; if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ continue; } if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue; return SQLITE_NOMATCH; } return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH; } /* ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and ** non-zero if there is no match. */ SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){ return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '['); } /* ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for ** a miss - like strcmp(). */ SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc); } /* ** Count the number of times that the LIKE operator (or GLOB which is ** just a variation of LIKE) gets called. This is used for testing ** only. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_like_count = 0; #endif /* ** Implementation of the like() SQL function. This function implements ** the build-in LIKE operator. The first argument to the function is the ** pattern and the second argument is the string. So, the SQL statements: ** ** A LIKE B ** ** is implemented as like(B,A). ** ** This same function (with a different compareInfo structure) computes ** the GLOB operator. */ static void likeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zA, *zB; u32 escape; int nPat; sqlite3 *db = sqlite3_context_db_handle(context); struct compareInfo *pInfo = sqlite3_user_data(context); #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( sqlite3_value_type(argv[0])==SQLITE_BLOB || sqlite3_value_type(argv[1])==SQLITE_BLOB ){ #ifdef SQLITE_TEST sqlite3_like_count++; #endif sqlite3_result_int(context, 0); return; } #endif zB = sqlite3_value_text(argv[0]); zA = sqlite3_value_text(argv[1]); /* Limit the length of the LIKE or GLOB pattern to avoid problems ** of deep recursion and N*N behavior in patternCompare(). */ nPat = sqlite3_value_bytes(argv[0]); testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); return; } assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */ if( argc==3 ){ /* The escape character string must consist of a single UTF-8 character. ** Otherwise, return an error. */ const unsigned char *zEsc = sqlite3_value_text(argv[2]); if( zEsc==0 ) return; if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ sqlite3_result_error(context, "ESCAPE expression must be a single character", -1); return; } escape = sqlite3Utf8Read(&zEsc); }else{ escape = pInfo->matchSet; } if( zA && zB ){ #ifdef SQLITE_TEST sqlite3_like_count++; #endif sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH); } } /* ** Implementation of the NULLIF(x,y) function. The result is the first ** argument if the arguments are different. The result is NULL if the ** arguments are equal to each other. */ static void nullifFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ CollSeq *pColl = sqlite3GetFuncCollSeq(context); UNUSED_PARAMETER(NotUsed); if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ sqlite3_result_value(context, argv[0]); } } /* ** Implementation of the sqlite_version() function. The result is the version ** of the SQLite library that is running. */ static void versionFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-48699-48617 This function is an SQL wrapper around the ** sqlite3_libversion() C-interface. */ sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); } /* ** Implementation of the sqlite_source_id() function. The result is a string ** that identifies the particular version of the source code used to build ** SQLite. */ static void sourceidFunc( sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-24470-31136 This function is an SQL wrapper around the ** sqlite3_sourceid() C interface. */ sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); } /* ** Implementation of the sqlite_log() function. This is a wrapper around ** sqlite3_log(). The return value is NULL. The function exists purely for ** its side-effects. */ static void errlogFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ UNUSED_PARAMETER(argc); UNUSED_PARAMETER(context); sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); } /* ** Implementation of the sqlite_compileoption_used() function. ** The result is an integer that identifies if the compiler option ** was used to build SQLite. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS static void compileoptionusedFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zOptName; assert( argc==1 ); UNUSED_PARAMETER(argc); /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL ** function is a wrapper around the sqlite3_compileoption_used() C/C++ ** function. */ if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); } } #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ /* ** Implementation of the sqlite_compileoption_get() function. ** The result is a string that identifies the compiler options ** used to build SQLite. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS static void compileoptiongetFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int n; assert( argc==1 ); UNUSED_PARAMETER(argc); /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. */ n = sqlite3_value_int(argv[0]); sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); } #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ /* Array for converting from half-bytes (nybbles) into ASCII hex ** digits. */ static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /* ** Implementation of the QUOTE() function. This function takes a single ** argument. If the argument is numeric, the return value is the same as ** the argument. If the argument is NULL, the return value is the string ** "NULL". Otherwise, the argument is enclosed in single quotes with ** single-quote escapes. */ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ assert( argc==1 ); UNUSED_PARAMETER(argc); switch( sqlite3_value_type(argv[0]) ){ case SQLITE_FLOAT: { double r1, r2; char zBuf[50]; r1 = sqlite3_value_double(argv[0]); sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); if( r1!=r2 ){ sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); } sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); break; } case SQLITE_INTEGER: { sqlite3_result_value(context, argv[0]); break; } case SQLITE_BLOB: { char *zText = 0; char const *zBlob = sqlite3_value_blob(argv[0]); int nBlob = sqlite3_value_bytes(argv[0]); assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); if( zText ){ int i; for(i=0; i<nBlob; i++){ zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F]; zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; } zText[(nBlob*2)+2] = '\''; zText[(nBlob*2)+3] = '\0'; zText[0] = 'X'; zText[1] = '\''; sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); sqlite3_free(zText); } break; } case SQLITE_TEXT: { int i,j; u64 n; const unsigned char *zArg = sqlite3_value_text(argv[0]); char *z; if( zArg==0 ) return; for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; } z = contextMalloc(context, ((i64)i)+((i64)n)+3); if( z ){ z[0] = '\''; for(i=0, j=1; zArg[i]; i++){ z[j++] = zArg[i]; if( zArg[i]=='\'' ){ z[j++] = '\''; } } z[j++] = '\''; z[j] = 0; sqlite3_result_text(context, z, j, sqlite3_free); } break; } default: { assert( sqlite3_value_type(argv[0])==SQLITE_NULL ); sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); break; } } } /* ** The unicode() function. Return the integer unicode code-point value ** for the first character of the input string. */ static void unicodeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *z = sqlite3_value_text(argv[0]); (void)argc; if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); } /* ** The char() function takes zero or more arguments, each of which is ** an integer. It constructs a string where each character of the string ** is the unicode character for the corresponding integer argument. */ static void charFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ unsigned char *z, *zOut; int i; zOut = z = sqlite3_malloc64( argc*4+1 ); if( z==0 ){ sqlite3_result_error_nomem(context); return; } for(i=0; i<argc; i++){ sqlite3_int64 x; unsigned c; x = sqlite3_value_int64(argv[i]); if( x<0 || x>0x10ffff ) x = 0xfffd; c = (unsigned)(x & 0x1fffff); if( c<0x00080 ){ *zOut++ = (u8)(c&0xFF); }else if( c<0x00800 ){ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); *zOut++ = 0x80 + (u8)(c & 0x3F); }else if( c<0x10000 ){ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); *zOut++ = 0x80 + (u8)(c & 0x3F); }else{ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); *zOut++ = 0x80 + (u8)(c & 0x3F); } \ } sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8); } /* ** The hex() function. Interpret the argument as a blob. Return ** a hexadecimal rendering as text. */ static void hexFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int i, n; const unsigned char *pBlob; char *zHex, *z; assert( argc==1 ); UNUSED_PARAMETER(argc); pBlob = sqlite3_value_blob(argv[0]); n = sqlite3_value_bytes(argv[0]); assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ z = zHex = contextMalloc(context, ((i64)n)*2 + 1); if( zHex ){ for(i=0; i<n; i++, pBlob++){ unsigned char c = *pBlob; *(z++) = hexdigits[(c>>4)&0xf]; *(z++) = hexdigits[c&0xf]; } *z = 0; sqlite3_result_text(context, zHex, n*2, sqlite3_free); } } /* ** The zeroblob(N) function returns a zero-filled blob of size N bytes. */ static void zeroblobFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ i64 n; int rc; assert( argc==1 ); UNUSED_PARAMETER(argc); n = sqlite3_value_int64(argv[0]); if( n<0 ) n = 0; rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */ if( rc ){ sqlite3_result_error_code(context, rc); } } /* ** The replace() function. Three arguments are all strings: call ** them A, B, and C. The result is also a string which is derived ** from A by replacing every occurrence of B with C. The match ** must be exact. Collating sequences are not used. */ static void replaceFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zStr; /* The input string A */ const unsigned char *zPattern; /* The pattern string B */ const unsigned char *zRep; /* The replacement string C */ unsigned char *zOut; /* The output */ int nStr; /* Size of zStr */ int nPattern; /* Size of zPattern */ int nRep; /* Size of zRep */ i64 nOut; /* Maximum size of zOut */ int loopLimit; /* Last zStr[] that might match zPattern[] */ int i, j; /* Loop counters */ assert( argc==3 ); UNUSED_PARAMETER(argc); zStr = sqlite3_value_text(argv[0]); if( zStr==0 ) return; nStr = sqlite3_value_bytes(argv[0]); assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ zPattern = sqlite3_value_text(argv[1]); if( zPattern==0 ){ assert( sqlite3_value_type(argv[1])==SQLITE_NULL || sqlite3_context_db_handle(context)->mallocFailed ); return; } if( zPattern[0]==0 ){ assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); sqlite3_result_value(context, argv[0]); return; } nPattern = sqlite3_value_bytes(argv[1]); assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ zRep = sqlite3_value_text(argv[2]); if( zRep==0 ) return; nRep = sqlite3_value_bytes(argv[2]); assert( zRep==sqlite3_value_text(argv[2]) ); nOut = nStr + 1; assert( nOut<SQLITE_MAX_LENGTH ); zOut = contextMalloc(context, (i64)nOut); if( zOut==0 ){ return; } loopLimit = nStr - nPattern; for(i=j=0; i<=loopLimit; i++){ if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){ zOut[j++] = zStr[i]; }else{ u8 *zOld; sqlite3 *db = sqlite3_context_db_handle(context); nOut += nRep - nPattern; testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ sqlite3_result_error_toobig(context); sqlite3_free(zOut); return; } zOld = zOut; zOut = sqlite3_realloc64(zOut, (int)nOut); if( zOut==0 ){ sqlite3_result_error_nomem(context); sqlite3_free(zOld); return; } memcpy(&zOut[j], zRep, nRep); j += nRep; i += nPattern-1; } } assert( j+nStr-i+1==nOut ); memcpy(&zOut[j], &zStr[i], nStr-i); j += nStr - i; assert( j<=nOut ); zOut[j] = 0; sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); } /* ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. */ static void trimFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zIn; /* Input string */ const unsigned char *zCharSet; /* Set of characters to trim */ int nIn; /* Number of bytes in input */ int flags; /* 1: trimleft 2: trimright 3: trim */ int i; /* Loop counter */ unsigned char *aLen = 0; /* Length of each character in zCharSet */ unsigned char **azChar = 0; /* Individual characters in zCharSet */ int nChar; /* Number of characters in zCharSet */ if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ return; } zIn = sqlite3_value_text(argv[0]); if( zIn==0 ) return; nIn = sqlite3_value_bytes(argv[0]); assert( zIn==sqlite3_value_text(argv[0]) ); if( argc==1 ){ static const unsigned char lenOne[] = { 1 }; static unsigned char * const azOne[] = { (u8*)" " }; nChar = 1; aLen = (u8*)lenOne; azChar = (unsigned char **)azOne; zCharSet = 0; }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ return; }else{ const unsigned char *z; for(z=zCharSet, nChar=0; *z; nChar++){ SQLITE_SKIP_UTF8(z); } if( nChar>0 ){ azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); if( azChar==0 ){ return; } aLen = (unsigned char*)&azChar[nChar]; for(z=zCharSet, nChar=0; *z; nChar++){ azChar[nChar] = (unsigned char *)z; SQLITE_SKIP_UTF8(z); aLen[nChar] = (u8)(z - azChar[nChar]); } } } if( nChar>0 ){ flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); if( flags & 1 ){ while( nIn>0 ){ int len = 0; for(i=0; i<nChar; i++){ len = aLen[i]; if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break; } if( i>=nChar ) break; zIn += len; nIn -= len; } } if( flags & 2 ){ while( nIn>0 ){ int len = 0; for(i=0; i<nChar; i++){ len = aLen[i]; if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break; } if( i>=nChar ) break; nIn -= len; } } if( zCharSet ){ sqlite3_free(azChar); } } sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); } #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION /* ** The "unknown" function is automatically substituted in place of ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used. ** When the "sqlite3" command-line shell is built using this functionality, ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries ** involving application-defined functions to be examined in a generic ** sqlite3 shell. */ static void unknownFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ /* no-op */ } #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/ /* IMP: R-25361-16150 This function is omitted from SQLite by default. It ** is only available if the SQLITE_SOUNDEX compile-time option is used ** when SQLite is built. */ #ifdef SQLITE_SOUNDEX /* ** Compute the soundex encoding of a word. ** ** IMP: R-59782-00072 The soundex(X) function returns a string that is the ** soundex encoding of the string X. */ static void soundexFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ char zResult[8]; const u8 *zIn; int i, j; static const unsigned char iCode[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, }; assert( argc==1 ); zIn = (u8*)sqlite3_value_text(argv[0]); if( zIn==0 ) zIn = (u8*)""; for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} if( zIn[i] ){ u8 prevcode = iCode[zIn[i]&0x7f]; zResult[0] = sqlite3Toupper(zIn[i]); for(j=1; j<4 && zIn[i]; i++){ int code = iCode[zIn[i]&0x7f]; if( code>0 ){ if( code!=prevcode ){ prevcode = code; zResult[j++] = code + '0'; } }else{ prevcode = 0; } } while( j<4 ){ zResult[j++] = '0'; } zResult[j] = 0; sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); }else{ /* IMP: R-64894-50321 The string "?000" is returned if the argument ** is NULL or contains no ASCII alphabetic characters. */ sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); } } #endif /* SQLITE_SOUNDEX */ #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** A function that loads a shared-library extension then returns NULL. */ static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ const char *zFile = (const char *)sqlite3_value_text(argv[0]); const char *zProc; sqlite3 *db = sqlite3_context_db_handle(context); char *zErrMsg = 0; /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc ** flag is set. See the sqlite3_enable_load_extension() API. */ if( (db->flags & SQLITE_LoadExtFunc)==0 ){ sqlite3_result_error(context, "not authorized", -1); return; } if( argc==2 ){ zProc = (const char *)sqlite3_value_text(argv[1]); }else{ zProc = 0; } if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ sqlite3_result_error(context, zErrMsg, -1); sqlite3_free(zErrMsg); } } #endif /* ** An instance of the following structure holds the context of a ** sum() or avg() aggregate computation. */ typedef struct SumCtx SumCtx; struct SumCtx { double rSum; /* Floating point sum */ i64 iSum; /* Integer sum */ i64 cnt; /* Number of elements summed */ u8 overflow; /* True if integer overflow seen */ u8 approx; /* True if non-integer value was input to the sum */ }; /* ** Routines used to compute the sum, average, and total. ** ** The SUM() function follows the (broken) SQL standard which means ** that it returns NULL if it sums over no inputs. TOTAL returns ** 0.0 in that case. In addition, TOTAL always returns a float where ** SUM might return an integer if it never encounters a floating point ** value. TOTAL never fails, but SUM might through an exception if ** it overflows an integer. */ static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ SumCtx *p; int type; assert( argc==1 ); UNUSED_PARAMETER(argc); p = sqlite3_aggregate_context(context, sizeof(*p)); type = sqlite3_value_numeric_type(argv[0]); if( p && type!=SQLITE_NULL ){ p->cnt++; if( type==SQLITE_INTEGER ){ i64 v = sqlite3_value_int64(argv[0]); p->rSum += v; if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){ p->overflow = 1; } }else{ p->rSum += sqlite3_value_double(argv[0]); p->approx = 1; } } } static void sumFinalize(sqlite3_context *context){ SumCtx *p; p = sqlite3_aggregate_context(context, 0); if( p && p->cnt>0 ){ if( p->overflow ){ sqlite3_result_error(context,"integer overflow",-1); }else if( p->approx ){ sqlite3_result_double(context, p->rSum); }else{ sqlite3_result_int64(context, p->iSum); } } } static void avgFinalize(sqlite3_context *context){ SumCtx *p; p = sqlite3_aggregate_context(context, 0); if( p && p->cnt>0 ){ sqlite3_result_double(context, p->rSum/(double)p->cnt); } } static void totalFinalize(sqlite3_context *context){ SumCtx *p; p = sqlite3_aggregate_context(context, 0); /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ sqlite3_result_double(context, p ? p->rSum : (double)0); } /* ** The following structure keeps track of state information for the ** count() aggregate function. */ typedef struct CountCtx CountCtx; struct CountCtx { i64 n; }; /* ** Routines to implement the count() aggregate function. */ static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ CountCtx *p; p = sqlite3_aggregate_context(context, sizeof(*p)); if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ p->n++; } #ifndef SQLITE_OMIT_DEPRECATED /* The sqlite3_aggregate_count() function is deprecated. But just to make ** sure it still operates correctly, verify that its count agrees with our ** internal count when using count(*) and when the total count can be ** expressed as a 32-bit integer. */ assert( argc==1 || p==0 || p->n>0x7fffffff || p->n==sqlite3_aggregate_count(context) ); #endif } static void countFinalize(sqlite3_context *context){ CountCtx *p; p = sqlite3_aggregate_context(context, 0); sqlite3_result_int64(context, p ? p->n : 0); } /* ** Routines to implement min() and max() aggregate functions. */ static void minmaxStep( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ Mem *pArg = (Mem *)argv[0]; Mem *pBest; UNUSED_PARAMETER(NotUsed); pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); if( !pBest ) return; if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); }else if( pBest->flags ){ int max; int cmp; CollSeq *pColl = sqlite3GetFuncCollSeq(context); /* This step function is used for both the min() and max() aggregates, ** the only difference between the two being that the sense of the ** comparison is inverted. For the max() aggregate, the ** sqlite3_user_data() function returns (void *)-1. For min() it ** returns (void *)db, where db is the sqlite3* database pointer. ** Therefore the next statement sets variable 'max' to 1 for the max() ** aggregate, or 0 for min(). */ max = sqlite3_user_data(context)!=0; cmp = sqlite3MemCompare(pBest, pArg, pColl); if( (max && cmp<0) || (!max && cmp>0) ){ sqlite3VdbeMemCopy(pBest, pArg); }else{ sqlite3SkipAccumulatorLoad(context); } }else{ pBest->db = sqlite3_context_db_handle(context); sqlite3VdbeMemCopy(pBest, pArg); } } static void minMaxFinalize(sqlite3_context *context){ sqlite3_value *pRes; pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); if( pRes ){ if( pRes->flags ){ sqlite3_result_value(context, pRes); } sqlite3VdbeMemRelease(pRes); } } /* ** group_concat(EXPR, ?SEPARATOR?) */ static void groupConcatStep( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zVal; StrAccum *pAccum; const char *zSep; int nVal, nSep; assert( argc==1 || argc==2 ); if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); if( pAccum ){ sqlite3 *db = sqlite3_context_db_handle(context); int firstTerm = pAccum->mxAlloc==0; pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; if( !firstTerm ){ if( argc==2 ){ zSep = (char*)sqlite3_value_text(argv[1]); nSep = sqlite3_value_bytes(argv[1]); }else{ zSep = ","; nSep = 1; } if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep); } zVal = (char*)sqlite3_value_text(argv[0]); nVal = sqlite3_value_bytes(argv[0]); if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal); } } static void groupConcatFinalize(sqlite3_context *context){ StrAccum *pAccum; pAccum = sqlite3_aggregate_context(context, 0); if( pAccum ){ if( pAccum->accError==STRACCUM_TOOBIG ){ sqlite3_result_error_toobig(context); }else if( pAccum->accError==STRACCUM_NOMEM ){ sqlite3_result_error_nomem(context); }else{ sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, sqlite3_free); } } } /* ** This routine does per-connection function registration. Most ** of the built-in functions above are part of the global function set. ** This routine only deals with those that are not global. */ SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){ int rc = sqlite3_overload_function(db, "MATCH", 2); assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); if( rc==SQLITE_NOMEM ){ sqlite3OomFault(db); } } /* ** Set the LIKEOPT flag on the 2-argument function with the given name. */ static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){ FuncDef *pDef; pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0); if( ALWAYS(pDef) ){ pDef->funcFlags |= flagVal; } } /* ** Register the built-in LIKE and GLOB functions. The caseSensitive ** parameter determines whether or not the LIKE operator is case ** sensitive. GLOB is always case sensitive. */ SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ struct compareInfo *pInfo; if( caseSensitive ){ pInfo = (struct compareInfo*)&likeInfoAlt; }else{ pInfo = (struct compareInfo*)&likeInfoNorm; } sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0); setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE); setLikeOptFlag(db, "like", caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE); } /* ** pExpr points to an expression which implements a function. If ** it is appropriate to apply the LIKE optimization to that function ** then set aWc[0] through aWc[2] to the wildcard characters and ** return TRUE. If the function is not a LIKE-style function then ** return FALSE. ** ** *pIsNocase is set to true if uppercase and lowercase are equivalent for ** the function (default for LIKE). If the function makes the distinction ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to ** false. */ SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ FuncDef *pDef; if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList || pExpr->x.pList->nExpr!=2 ){ return 0; } assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0); if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ return 0; } /* The memcpy() statement assumes that the wildcard characters are ** the first three statements in the compareInfo structure. The ** asserts() that follow verify that assumption */ memcpy(aWc, pDef->pUserData, 3); assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; return 1; } /* ** All of the FuncDef structures in the aBuiltinFunc[] array above ** to the global function hash table. This occurs at start-time (as ** a consequence of calling sqlite3_initialize()). ** ** After this routine runs */ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ /* ** The following array holds FuncDef structures for all of the functions ** defined in this file. ** ** The array cannot be constant since changes are made to the ** FuncDef.pHash elements at start-time. The elements of this array ** are read-only after initialization is complete. ** ** For peak efficiency, put the most frequently used function last. */ static FuncDef aBuiltinFunc[] = { #ifdef SQLITE_SOUNDEX FUNCTION(soundex, 1, 0, 0, soundexFunc ), #endif #ifndef SQLITE_OMIT_LOAD_EXTENSION VFUNCTION(load_extension, 1, 0, 0, loadExt ), VFUNCTION(load_extension, 2, 0, 0, loadExt ), #endif #if SQLITE_USER_AUTHENTICATION FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ), #endif #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), #ifdef SQLITE_DEBUG FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY), #endif FUNCTION(ltrim, 1, 1, 0, trimFunc ), FUNCTION(ltrim, 2, 1, 0, trimFunc ), FUNCTION(rtrim, 1, 2, 0, trimFunc ), FUNCTION(rtrim, 2, 2, 0, trimFunc ), FUNCTION(trim, 1, 3, 0, trimFunc ), FUNCTION(trim, 2, 3, 0, trimFunc ), FUNCTION(min, -1, 0, 1, minmaxFunc ), FUNCTION(min, 0, 0, 1, 0 ), AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize, SQLITE_FUNC_MINMAX ), FUNCTION(max, -1, 1, 1, minmaxFunc ), FUNCTION(max, 0, 1, 1, 0 ), AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize, SQLITE_FUNC_MINMAX ), FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), FUNCTION(instr, 2, 0, 0, instrFunc ), FUNCTION(printf, -1, 0, 0, printfFunc ), FUNCTION(unicode, 1, 0, 0, unicodeFunc ), FUNCTION(char, -1, 0, 0, charFunc ), FUNCTION(abs, 1, 0, 0, absFunc ), #ifndef SQLITE_OMIT_FLOATING_POINT FUNCTION(round, 1, 0, 0, roundFunc ), FUNCTION(round, 2, 0, 0, roundFunc ), #endif FUNCTION(upper, 1, 0, 0, upperFunc ), FUNCTION(lower, 1, 0, 0, lowerFunc ), FUNCTION(hex, 1, 0, 0, hexFunc ), FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), VFUNCTION(random, 0, 0, 0, randomFunc ), VFUNCTION(randomblob, 1, 0, 0, randomBlob ), FUNCTION(nullif, 2, 0, 1, nullifFunc ), DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ), DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), FUNCTION(quote, 1, 0, 0, quoteFunc ), VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), VFUNCTION(changes, 0, 0, 0, changes ), VFUNCTION(total_changes, 0, 0, 0, total_changes ), FUNCTION(replace, 3, 0, 0, replaceFunc ), FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), FUNCTION(substr, 2, 0, 0, substrFunc ), FUNCTION(substr, 3, 0, 0, substrFunc ), AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ), AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ), AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ), AGGREGATE2(count, 0, 0, 0, countStep, countFinalize, SQLITE_FUNC_COUNT ), AGGREGATE(count, 1, 0, 0, countStep, countFinalize ), AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize), AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize), LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), #ifdef SQLITE_CASE_SENSITIVE_LIKE LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), #else LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE), LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE), #endif #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION FUNCTION(unknown, -1, 0, 0, unknownFunc ), #endif FUNCTION(coalesce, 1, 0, 0, 0 ), FUNCTION(coalesce, 0, 0, 0, 0 ), FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), }; #ifndef SQLITE_OMIT_ALTERTABLE sqlite3AlterFunctions(); #endif #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4) sqlite3AnalyzeFunctions(); #endif sqlite3RegisterDateTimeFunctions(); sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc)); #if 0 /* Enable to print out how the built-in functions are hashed */ { int i; FuncDef *p; for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){ printf("FUNC-HASH %02d:", i); for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){ int n = sqlite3Strlen30(p->zName); int h = p->zName[0] + n; printf(" %s(%d)", p->zName, h); } printf("\n"); } } #endif } /************** End of func.c ************************************************/ /************** Begin file fkey.c ********************************************/ /* ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used by the compiler to add foreign key ** support to compiled SQL statements. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_FOREIGN_KEY #ifndef SQLITE_OMIT_TRIGGER /* ** Deferred and Immediate FKs ** -------------------------- ** ** Foreign keys in SQLite come in two flavours: deferred and immediate. ** If an immediate foreign key constraint is violated, ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current ** statement transaction rolled back. If a ** deferred foreign key constraint is violated, no action is taken ** immediately. However if the application attempts to commit the ** transaction before fixing the constraint violation, the attempt fails. ** ** Deferred constraints are implemented using a simple counter associated ** with the database handle. The counter is set to zero each time a ** database transaction is opened. Each time a statement is executed ** that causes a foreign key violation, the counter is incremented. Each ** time a statement is executed that removes an existing violation from ** the database, the counter is decremented. When the transaction is ** committed, the commit fails if the current value of the counter is ** greater than zero. This scheme has two big drawbacks: ** ** * When a commit fails due to a deferred foreign key constraint, ** there is no way to tell which foreign constraint is not satisfied, ** or which row it is not satisfied for. ** ** * If the database contains foreign key violations when the ** transaction is opened, this may cause the mechanism to malfunction. ** ** Despite these problems, this approach is adopted as it seems simpler ** than the alternatives. ** ** INSERT operations: ** ** I.1) For each FK for which the table is the child table, search ** the parent table for a match. If none is found increment the ** constraint counter. ** ** I.2) For each FK for which the table is the parent table, ** search the child table for rows that correspond to the new ** row in the parent table. Decrement the counter for each row ** found (as the constraint is now satisfied). ** ** DELETE operations: ** ** D.1) For each FK for which the table is the child table, ** search the parent table for a row that corresponds to the ** deleted row in the child table. If such a row is not found, ** decrement the counter. ** ** D.2) For each FK for which the table is the parent table, search ** the child table for rows that correspond to the deleted row ** in the parent table. For each found increment the counter. ** ** UPDATE operations: ** ** An UPDATE command requires that all 4 steps above are taken, but only ** for FK constraints for which the affected columns are actually ** modified (values must be compared at runtime). ** ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2. ** This simplifies the implementation a bit. ** ** For the purposes of immediate FK constraints, the OR REPLACE conflict ** resolution is considered to delete rows before the new row is inserted. ** If a delete caused by OR REPLACE violates an FK constraint, an exception ** is thrown, even if the FK constraint would be satisfied after the new ** row is inserted. ** ** Immediate constraints are usually handled similarly. The only difference ** is that the counter used is stored as part of each individual statement ** object (struct Vdbe). If, after the statement has run, its immediate ** constraint counter is greater than zero, ** it returns SQLITE_CONSTRAINT_FOREIGNKEY ** and the statement transaction is rolled back. An exception is an INSERT ** statement that inserts a single row only (no triggers). In this case, ** instead of using a counter, an exception is thrown immediately if the ** INSERT violates a foreign key constraint. This is necessary as such ** an INSERT does not open a statement transaction. ** ** TODO: How should dropping a table be handled? How should renaming a ** table be handled? ** ** ** Query API Notes ** --------------- ** ** Before coding an UPDATE or DELETE row operation, the code-generator ** for those two operations needs to know whether or not the operation ** requires any FK processing and, if so, which columns of the original ** row are required by the FK processing VDBE code (i.e. if FKs were ** implemented using triggers, which of the old.* columns would be ** accessed). No information is required by the code-generator before ** coding an INSERT operation. The functions used by the UPDATE/DELETE ** generation code to query for this information are: ** ** sqlite3FkRequired() - Test to see if FK processing is required. ** sqlite3FkOldmask() - Query for the set of required old.* columns. ** ** ** Externally accessible module functions ** -------------------------------------- ** ** sqlite3FkCheck() - Check for foreign key violations. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions. ** sqlite3FkDelete() - Delete an FKey structure. */ /* ** VDBE Calling Convention ** ----------------------- ** ** Example: ** ** For the following INSERT statement: ** ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c); ** INSERT INTO t1 VALUES(1, 2, 3.1); ** ** Register (x): 2 (type integer) ** Register (x+1): 1 (type integer) ** Register (x+2): NULL (type NULL) ** Register (x+3): 3.1 (type real) */ /* ** A foreign key constraint requires that the key columns in the parent ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint. ** Given that pParent is the parent table for foreign key constraint pFKey, ** search the schema for a unique index on the parent key columns. ** ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx ** is set to point to the unique index. ** ** If the parent key consists of a single column (the foreign key constraint ** is not a composite foreign key), output variable *paiCol is set to NULL. ** Otherwise, it is set to point to an allocated array of size N, where ** N is the number of columns in the parent key. The first element of the ** array is the index of the child table column that is mapped by the FK ** constraint to the parent table column stored in the left-most column ** of index *ppIdx. The second element of the array is the index of the ** child table column that corresponds to the second left-most column of ** *ppIdx, and so on. ** ** If the required index cannot be found, either because: ** ** 1) The named parent key columns do not exist, or ** ** 2) The named parent key columns do exist, but are not subject to a ** UNIQUE or PRIMARY KEY constraint, or ** ** 3) No parent key columns were provided explicitly as part of the ** foreign key definition, and the parent table does not have a ** PRIMARY KEY, or ** ** 4) No parent key columns were provided explicitly as part of the ** foreign key definition, and the PRIMARY KEY of the parent table ** consists of a different number of columns to the child key in ** the child table. ** ** then non-zero is returned, and a "foreign key mismatch" error loaded ** into pParse. If an OOM error occurs, non-zero is returned and the ** pParse->db->mallocFailed flag is set. */ SQLITE_PRIVATE int sqlite3FkLocateIndex( Parse *pParse, /* Parse context to store any error in */ Table *pParent, /* Parent table of FK constraint pFKey */ FKey *pFKey, /* Foreign key to find index for */ Index **ppIdx, /* OUT: Unique index on parent table */ int **paiCol /* OUT: Map of index columns in pFKey */ ){ Index *pIdx = 0; /* Value to return via *ppIdx */ int *aiCol = 0; /* Value to return via *paiCol */ int nCol = pFKey->nCol; /* Number of columns in parent key */ char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */ /* The caller is responsible for zeroing output parameters. */ assert( ppIdx && *ppIdx==0 ); assert( !paiCol || *paiCol==0 ); assert( pParse ); /* If this is a non-composite (single column) foreign key, check if it ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx ** and *paiCol set to zero and return early. ** ** Otherwise, for a composite foreign key (more than one column), allocate ** space for the aiCol array (returned via output parameter *paiCol). ** Non-composite foreign keys do not require the aiCol array. */ if( nCol==1 ){ /* The FK maps to the IPK if any of the following are true: ** ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly ** mapped to the primary key of table pParent, or ** 2) The FK is explicitly mapped to a column declared as INTEGER ** PRIMARY KEY. */ if( pParent->iPKey>=0 ){ if( !zKey ) return 0; if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; } }else if( paiCol ){ assert( nCol>1 ); aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int)); if( !aiCol ) return 1; *paiCol = aiCol; } for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){ /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number ** of columns. If each indexed column corresponds to a foreign key ** column of pFKey, then this index is a winner. */ if( zKey==0 ){ /* If zKey is NULL, then this foreign key is implicitly mapped to ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be ** identified by the test. */ if( IsPrimaryKeyIndex(pIdx) ){ if( aiCol ){ int i; for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom; } break; } }else{ /* If zKey is non-NULL, then this foreign key was declared to ** map to an explicit list of columns in table pParent. Check if this ** index matches those columns. Also, check that the index uses ** the default collation sequences for each column. */ int i, j; for(i=0; i<nCol; i++){ i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */ const char *zDfltColl; /* Def. collation for column */ char *zIdxCol; /* Name of indexed column */ if( iCol<0 ) break; /* No foreign keys against expression indexes */ /* If the index uses a collation sequence that is different from ** the default collation sequence for the column, this index is ** unusable. Bail out early in this case. */ zDfltColl = pParent->aCol[iCol].zColl; if( !zDfltColl ) zDfltColl = sqlite3StrBINARY; if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break; zIdxCol = pParent->aCol[iCol].zName; for(j=0; j<nCol; j++){ if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){ if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; break; } } if( j==nCol ) break; } if( i==nCol ) break; /* pIdx is usable */ } } } if( !pIdx ){ if( !pParse->disableTriggers ){ sqlite3ErrorMsg(pParse, "foreign key mismatch - \"%w\" referencing \"%w\"", pFKey->pFrom->zName, pFKey->zTo); } sqlite3DbFree(pParse->db, aiCol); return 1; } *ppIdx = pIdx; return 0; } /* ** This function is called when a row is inserted into or deleted from the ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed ** on the child table of pFKey, this function is invoked twice for each row ** affected - once to "delete" the old row, and then again to "insert" the ** new row. ** ** Each time it is called, this function generates VDBE code to locate the ** row in the parent table that corresponds to the row being inserted into ** or deleted from the child table. If the parent row can be found, no ** special action is taken. Otherwise, if the parent row can *not* be ** found in the parent table: ** ** Operation | FK type | Action taken ** -------------------------------------------------------------------------- ** INSERT immediate Increment the "immediate constraint counter". ** ** DELETE immediate Decrement the "immediate constraint counter". ** ** INSERT deferred Increment the "deferred constraint counter". ** ** DELETE deferred Decrement the "deferred constraint counter". ** ** These operations are identified in the comment at the top of this file ** (fkey.c) as "I.1" and "D.1". */ static void fkLookupParent( Parse *pParse, /* Parse context */ int iDb, /* Index of database housing pTab */ Table *pTab, /* Parent table of FK pFKey */ Index *pIdx, /* Unique index on parent key columns in pTab */ FKey *pFKey, /* Foreign key constraint */ int *aiCol, /* Map from parent key columns to child table columns */ int regData, /* Address of array containing child table row */ int nIncr, /* Increment constraint counter by this */ int isIgnore /* If true, pretend pTab contains all NULL values */ ){ int i; /* Iterator variable */ Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */ int iCur = pParse->nTab - 1; /* Cursor number to use */ int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */ /* If nIncr is less than zero, then check at runtime if there are any ** outstanding constraints to resolve. If there are not, there is no need ** to check if deleting this row resolves any outstanding violations. ** ** Check if any of the key columns in the child table row are NULL. If ** any are, then the constraint is considered satisfied. No need to ** search for a matching row in the parent table. */ if( nIncr<0 ){ sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); VdbeCoverage(v); } for(i=0; i<pFKey->nCol; i++){ int iReg = aiCol[i] + regData + 1; sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v); } if( isIgnore==0 ){ if( pIdx==0 ){ /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY ** column of the parent table (table pTab). */ int iMustBeInt; /* Address of MustBeInt instruction */ int regTemp = sqlite3GetTempReg(pParse); /* Invoke MustBeInt to coerce the child key value to an integer (i.e. ** apply the affinity of the parent key). If this fails, then there ** is no matching parent key. Before using MustBeInt, make a copy of ** the value. Otherwise, the value inserted into the child key column ** will have INTEGER affinity applied to it, which may not be correct. */ sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp); iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0); VdbeCoverage(v); /* If the parent table is the same as the child table, and we are about ** to increment the constraint-counter (i.e. this is an INSERT operation), ** then check if the row being inserted matches itself. If so, do not ** increment the constraint-counter. */ if( pTab==pFKey->pFrom && nIncr==1 ){ sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); } sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v); sqlite3VdbeGoto(v, iOk); sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); sqlite3VdbeJumpHere(v, iMustBeInt); sqlite3ReleaseTempReg(pParse, regTemp); }else{ int nCol = pFKey->nCol; int regTemp = sqlite3GetTempRange(pParse, nCol); int regRec = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); for(i=0; i<nCol; i++){ sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i); } /* If the parent table is the same as the child table, and we are about ** to increment the constraint-counter (i.e. this is an INSERT operation), ** then check if the row being inserted matches itself. If so, do not ** increment the constraint-counter. ** ** If any of the parent-key values are NULL, then the row cannot match ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any ** of the parent-key values are NULL (at this point it is known that ** none of the child key values are). */ if( pTab==pFKey->pFrom && nIncr==1 ){ int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1; for(i=0; i<nCol; i++){ int iChild = aiCol[i]+1+regData; int iParent = pIdx->aiColumn[i]+1+regData; assert( pIdx->aiColumn[i]>=0 ); assert( aiCol[i]!=pTab->iPKey ); if( pIdx->aiColumn[i]==pTab->iPKey ){ /* The parent key is a composite key that includes the IPK column */ iParent = regData; } sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); } sqlite3VdbeGoto(v, iOk); } sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec, sqlite3IndexAffinityStr(pParse->db,pIdx), nCol); sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, regRec); sqlite3ReleaseTempRange(pParse, regTemp, nCol); } } if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs) && !pParse->pToplevel && !pParse->isMultiWrite ){ /* Special case: If this is an INSERT statement that will insert exactly ** one row into the table, raise a constraint immediately instead of ** incrementing a counter. This is necessary as the VM code is being ** generated for will not open a statement transaction. */ assert( nIncr==1 ); sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, OE_Abort, 0, P4_STATIC, P5_ConstraintFK); }else{ if( nIncr>0 && pFKey->isDeferred==0 ){ sqlite3MayAbort(pParse); } sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); } sqlite3VdbeResolveLabel(v, iOk); sqlite3VdbeAddOp1(v, OP_Close, iCur); } /* ** Return an Expr object that refers to a memory register corresponding ** to column iCol of table pTab. ** ** regBase is the first of an array of register that contains the data ** for pTab. regBase itself holds the rowid. regBase+1 holds the first ** column. regBase+2 holds the second column, and so forth. */ static Expr *exprTableRegister( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* The table whose content is at r[regBase]... */ int regBase, /* Contents of table pTab */ i16 iCol /* Which column of pTab is desired */ ){ Expr *pExpr; Column *pCol; const char *zColl; sqlite3 *db = pParse->db; pExpr = sqlite3Expr(db, TK_REGISTER, 0); if( pExpr ){ if( iCol>=0 && iCol!=pTab->iPKey ){ pCol = &pTab->aCol[iCol]; pExpr->iTable = regBase + iCol + 1; pExpr->affinity = pCol->affinity; zColl = pCol->zColl; if( zColl==0 ) zColl = db->pDfltColl->zName; pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl); }else{ pExpr->iTable = regBase; pExpr->affinity = SQLITE_AFF_INTEGER; } } return pExpr; } /* ** Return an Expr object that refers to column iCol of table pTab which ** has cursor iCur. */ static Expr *exprTableColumn( sqlite3 *db, /* The database connection */ Table *pTab, /* The table whose column is desired */ int iCursor, /* The open cursor on the table */ i16 iCol /* The column that is wanted */ ){ Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0); if( pExpr ){ pExpr->pTab = pTab; pExpr->iTable = iCursor; pExpr->iColumn = iCol; } return pExpr; } /* ** This function is called to generate code executed when a row is deleted ** from the parent table of foreign key constraint pFKey and, if pFKey is ** deferred, when a row is inserted into the same table. When generating ** code for an SQL UPDATE operation, this function may be called twice - ** once to "delete" the old row and once to "insert" the new row. ** ** Parameter nIncr is passed -1 when inserting a row (as this may decrease ** the number of FK violations in the db) or +1 when deleting one (as this ** may increase the number of FK constraint problems). ** ** The code generated by this function scans through the rows in the child ** table that correspond to the parent table row being deleted or inserted. ** For each child row found, one of the following actions is taken: ** ** Operation | FK type | Action taken ** -------------------------------------------------------------------------- ** DELETE immediate Increment the "immediate constraint counter". ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, ** throw a "FOREIGN KEY constraint failed" exception. ** ** INSERT immediate Decrement the "immediate constraint counter". ** ** DELETE deferred Increment the "deferred constraint counter". ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, ** throw a "FOREIGN KEY constraint failed" exception. ** ** INSERT deferred Decrement the "deferred constraint counter". ** ** These operations are identified in the comment at the top of this file ** (fkey.c) as "I.2" and "D.2". */ static void fkScanChildren( Parse *pParse, /* Parse context */ SrcList *pSrc, /* The child table to be scanned */ Table *pTab, /* The parent table */ Index *pIdx, /* Index on parent covering the foreign key */ FKey *pFKey, /* The foreign key linking pSrc to pTab */ int *aiCol, /* Map from pIdx cols to child table cols */ int regData, /* Parent row data starts here */ int nIncr /* Amount to increment deferred counter by */ ){ sqlite3 *db = pParse->db; /* Database handle */ int i; /* Iterator variable */ Expr *pWhere = 0; /* WHERE clause to scan with */ NameContext sNameContext; /* Context used to resolve WHERE clause */ WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ int iFkIfZero = 0; /* Address of OP_FkIfZero */ Vdbe *v = sqlite3GetVdbe(pParse); assert( pIdx==0 || pIdx->pTable==pTab ); assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol ); assert( pIdx!=0 || pFKey->nCol==1 ); assert( pIdx!=0 || HasRowid(pTab) ); if( nIncr<0 ){ iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); VdbeCoverage(v); } /* Create an Expr object representing an SQL expression like: ** ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ... ** ** The collation sequence used for the comparison should be that of ** the parent key columns. The affinity of the parent key column should ** be applied to each child key value before the comparison takes place. */ for(i=0; i<pFKey->nCol; i++){ Expr *pLeft; /* Value from parent table row */ Expr *pRight; /* Column ref to child table */ Expr *pEq; /* Expression (pLeft = pRight) */ i16 iCol; /* Index of column in child table */ const char *zCol; /* Name of column in child table */ iCol = pIdx ? pIdx->aiColumn[i] : -1; pLeft = exprTableRegister(pParse, pTab, regData, iCol); iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; assert( iCol>=0 ); zCol = pFKey->pFrom->aCol[iCol].zName; pRight = sqlite3Expr(db, TK_ID, zCol); pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight); pWhere = sqlite3ExprAnd(db, pWhere, pEq); } /* If the child table is the same as the parent table, then add terms ** to the WHERE clause that prevent this entry from being scanned. ** The added WHERE clause terms are like this: ** ** $current_rowid!=rowid ** NOT( $current_a==a AND $current_b==b AND ... ) ** ** The first form is used for rowid tables. The second form is used ** for WITHOUT ROWID tables. In the second form, the primary key is ** (a,b,...) */ if( pTab==pFKey->pFrom && nIncr>0 ){ Expr *pNe; /* Expression (pLeft != pRight) */ Expr *pLeft; /* Value from parent table row */ Expr *pRight; /* Column ref to child table */ if( HasRowid(pTab) ){ pLeft = exprTableRegister(pParse, pTab, regData, -1); pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1); pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight); }else{ Expr *pEq, *pAll = 0; Index *pPk = sqlite3PrimaryKeyIndex(pTab); assert( pIdx!=0 ); for(i=0; i<pPk->nKeyCol; i++){ i16 iCol = pIdx->aiColumn[i]; assert( iCol>=0 ); pLeft = exprTableRegister(pParse, pTab, regData, iCol); pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol); pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight); pAll = sqlite3ExprAnd(db, pAll, pEq); } pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0); } pWhere = sqlite3ExprAnd(db, pWhere, pNe); } /* Resolve the references in the WHERE clause. */ memset(&sNameContext, 0, sizeof(NameContext)); sNameContext.pSrcList = pSrc; sNameContext.pParse = pParse; sqlite3ResolveExprNames(&sNameContext, pWhere); /* Create VDBE to loop through the entries in pSrc that match the WHERE ** clause. For each row found, increment either the deferred or immediate ** foreign key constraint counter. */ pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0); sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); if( pWInfo ){ sqlite3WhereEnd(pWInfo); } /* Clean up the WHERE clause constructed above. */ sqlite3ExprDelete(db, pWhere); if( iFkIfZero ){ sqlite3VdbeJumpHere(v, iFkIfZero); } } /* ** This function returns a linked list of FKey objects (connected by ** FKey.pNextTo) holding all children of table pTab. For example, ** given the following schema: ** ** CREATE TABLE t1(a PRIMARY KEY); ** CREATE TABLE t2(b REFERENCES t1(a); ** ** Calling this function with table "t1" as an argument returns a pointer ** to the FKey structure representing the foreign key constraint on table ** "t2". Calling this function with "t2" as the argument would return a ** NULL pointer (as there are no FK constraints for which t2 is the parent ** table). */ SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){ return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName); } /* ** The second argument is a Trigger structure allocated by the ** fkActionTrigger() routine. This function deletes the Trigger structure ** and all of its sub-components. ** ** The Trigger structure or any of its sub-components may be allocated from ** the lookaside buffer belonging to database handle dbMem. */ static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ if( p ){ TriggerStep *pStep = p->step_list; sqlite3ExprDelete(dbMem, pStep->pWhere); sqlite3ExprListDelete(dbMem, pStep->pExprList); sqlite3SelectDelete(dbMem, pStep->pSelect); sqlite3ExprDelete(dbMem, p->pWhen); sqlite3DbFree(dbMem, p); } } /* ** This function is called to generate code that runs when table pTab is ** being dropped from the database. The SrcList passed as the second argument ** to this function contains a single entry guaranteed to resolve to ** table pTab. ** ** Normally, no code is required. However, if either ** ** (a) The table is the parent table of a FK constraint, or ** (b) The table is the child table of a deferred FK constraint and it is ** determined at runtime that there are outstanding deferred FK ** constraint violations in the database, ** ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping ** the table from the database. Triggers are disabled while running this ** DELETE, but foreign key actions are not. */ SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){ sqlite3 *db = pParse->db; if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){ int iSkip = 0; Vdbe *v = sqlite3GetVdbe(pParse); assert( v ); /* VDBE has already been allocated */ if( sqlite3FkReferences(pTab)==0 ){ /* Search for a deferred foreign key constraint for which this table ** is the child table. If one cannot be found, return without ** generating any VDBE code. If one can be found, then jump over ** the entire DELETE if there are no outstanding deferred constraints ** when this statement is run. */ FKey *p; for(p=pTab->pFKey; p; p=p->pNextFrom){ if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break; } if( !p ) return; iSkip = sqlite3VdbeMakeLabel(v); sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v); } pParse->disableTriggers = 1; sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0); pParse->disableTriggers = 0; /* If the DELETE has generated immediate foreign key constraint ** violations, halt the VDBE and return an error at this point, before ** any modifications to the schema are made. This is because statement ** transactions are not able to rollback schema changes. ** ** If the SQLITE_DeferFKs flag is set, then this is not required, as ** the statement transaction will not be rolled back even if FK ** constraints are violated. */ if( (db->flags & SQLITE_DeferFKs)==0 ){ sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, OE_Abort, 0, P4_STATIC, P5_ConstraintFK); } if( iSkip ){ sqlite3VdbeResolveLabel(v, iSkip); } } } /* ** The second argument points to an FKey object representing a foreign key ** for which pTab is the child table. An UPDATE statement against pTab ** is currently being processed. For each column of the table that is ** actually updated, the corresponding element in the aChange[] array ** is zero or greater (if a column is unmodified the corresponding element ** is set to -1). If the rowid column is modified by the UPDATE statement ** the bChngRowid argument is non-zero. ** ** This function returns true if any of the columns that are part of the ** child key for FK constraint *p are modified. */ static int fkChildIsModified( Table *pTab, /* Table being updated */ FKey *p, /* Foreign key for which pTab is the child */ int *aChange, /* Array indicating modified columns */ int bChngRowid /* True if rowid is modified by this update */ ){ int i; for(i=0; i<p->nCol; i++){ int iChildKey = p->aCol[i].iFrom; if( aChange[iChildKey]>=0 ) return 1; if( iChildKey==pTab->iPKey && bChngRowid ) return 1; } return 0; } /* ** The second argument points to an FKey object representing a foreign key ** for which pTab is the parent table. An UPDATE statement against pTab ** is currently being processed. For each column of the table that is ** actually updated, the corresponding element in the aChange[] array ** is zero or greater (if a column is unmodified the corresponding element ** is set to -1). If the rowid column is modified by the UPDATE statement ** the bChngRowid argument is non-zero. ** ** This function returns true if any of the columns that are part of the ** parent key for FK constraint *p are modified. */ static int fkParentIsModified( Table *pTab, FKey *p, int *aChange, int bChngRowid ){ int i; for(i=0; i<p->nCol; i++){ char *zKey = p->aCol[i].zCol; int iKey; for(iKey=0; iKey<pTab->nCol; iKey++){ if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){ Column *pCol = &pTab->aCol[iKey]; if( zKey ){ if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1; }else if( pCol->colFlags & COLFLAG_PRIMKEY ){ return 1; } } } } return 0; } /* ** Return true if the parser passed as the first argument is being ** used to code a trigger that is really a "SET NULL" action belonging ** to trigger pFKey. */ static int isSetNullAction(Parse *pParse, FKey *pFKey){ Parse *pTop = sqlite3ParseToplevel(pParse); if( pTop->pTriggerPrg ){ Trigger *p = pTop->pTriggerPrg->pTrigger; if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull) || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull) ){ return 1; } } return 0; } /* ** This function is called when inserting, deleting or updating a row of ** table pTab to generate VDBE code to perform foreign key constraint ** processing for the operation. ** ** For a DELETE operation, parameter regOld is passed the index of the ** first register in an array of (pTab->nCol+1) registers containing the ** rowid of the row being deleted, followed by each of the column values ** of the row being deleted, from left to right. Parameter regNew is passed ** zero in this case. ** ** For an INSERT operation, regOld is passed zero and regNew is passed the ** first register of an array of (pTab->nCol+1) registers containing the new ** row data. ** ** For an UPDATE operation, this function is called twice. Once before ** the original record is deleted from the table using the calling convention ** described for DELETE. Then again after the original record is deleted ** but before the new record is inserted using the INSERT convention. */ SQLITE_PRIVATE void sqlite3FkCheck( Parse *pParse, /* Parse context */ Table *pTab, /* Row is being deleted from this table */ int regOld, /* Previous row data is stored here */ int regNew, /* New row data is stored here */ int *aChange, /* Array indicating UPDATEd columns (or 0) */ int bChngRowid /* True if rowid is UPDATEd */ ){ sqlite3 *db = pParse->db; /* Database handle */ FKey *pFKey; /* Used to iterate through FKs */ int iDb; /* Index of database containing pTab */ const char *zDb; /* Name of database containing pTab */ int isIgnoreErrors = pParse->disableTriggers; /* Exactly one of regOld and regNew should be non-zero. */ assert( (regOld==0)!=(regNew==0) ); /* If foreign-keys are disabled, this function is a no-op. */ if( (db->flags&SQLITE_ForeignKeys)==0 ) return; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); zDb = db->aDb[iDb].zDbSName; /* Loop through all the foreign key constraints for which pTab is the ** child table (the table that the foreign key definition is part of). */ for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ Table *pTo; /* Parent table of foreign key pFKey */ Index *pIdx = 0; /* Index on key columns in pTo */ int *aiFree = 0; int *aiCol; int iCol; int i; int bIgnore = 0; if( aChange && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){ continue; } /* Find the parent table of this foreign key. Also find a unique index ** on the parent key columns in the parent table. If either of these ** schema items cannot be located, set an error in pParse and return ** early. */ if( pParse->disableTriggers ){ pTo = sqlite3FindTable(db, pFKey->zTo, zDb); }else{ pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); } if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){ assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) ); if( !isIgnoreErrors || db->mallocFailed ) return; if( pTo==0 ){ /* If isIgnoreErrors is true, then a table is being dropped. In this ** case SQLite runs a "DELETE FROM xxx" on the table being dropped ** before actually dropping it in order to check FK constraints. ** If the parent table of an FK constraint on the current table is ** missing, behave as if it is empty. i.e. decrement the relevant ** FK counter for each row of the current table with non-NULL keys. */ Vdbe *v = sqlite3GetVdbe(pParse); int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; for(i=0; i<pFKey->nCol; i++){ int iReg = pFKey->aCol[i].iFrom + regOld + 1; sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v); } sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1); } continue; } assert( pFKey->nCol==1 || (aiFree && pIdx) ); if( aiFree ){ aiCol = aiFree; }else{ iCol = pFKey->aCol[0].iFrom; aiCol = &iCol; } for(i=0; i<pFKey->nCol; i++){ if( aiCol[i]==pTab->iPKey ){ aiCol[i] = -1; } assert( pIdx==0 || pIdx->aiColumn[i]>=0 ); #ifndef SQLITE_OMIT_AUTHORIZATION /* Request permission to read the parent key columns. If the ** authorization callback returns SQLITE_IGNORE, behave as if any ** values read from the parent table are NULL. */ if( db->xAuth ){ int rcauth; char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName; rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb); bIgnore = (rcauth==SQLITE_IGNORE); } #endif } /* Take a shared-cache advisory read-lock on the parent table. Allocate ** a cursor to use to search the unique index on the parent key columns ** in the parent table. */ sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); pParse->nTab++; if( regOld!=0 ){ /* A row is being removed from the child table. Search for the parent. ** If the parent does not exist, removing the child row resolves an ** outstanding foreign key constraint violation. */ fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore); } if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){ /* A row is being added to the child table. If a parent row cannot ** be found, adding the child row has violated the FK constraint. ** ** If this operation is being performed as part of a trigger program ** that is actually a "SET NULL" action belonging to this very ** foreign key, then omit this scan altogether. As all child key ** values are guaranteed to be NULL, it is not possible for adding ** this row to cause an FK violation. */ fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore); } sqlite3DbFree(db, aiFree); } /* Loop through all the foreign key constraints that refer to this table. ** (the "child" constraints) */ for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ Index *pIdx = 0; /* Foreign key index for pFKey */ SrcList *pSrc; int *aiCol = 0; if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){ continue; } if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) && !pParse->pToplevel && !pParse->isMultiWrite ){ assert( regOld==0 && regNew!=0 ); /* Inserting a single row into a parent table cannot cause (or fix) ** an immediate foreign key violation. So do nothing in this case. */ continue; } if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){ if( !isIgnoreErrors || db->mallocFailed ) return; continue; } assert( aiCol || pFKey->nCol==1 ); /* Create a SrcList structure containing the child table. We need the ** child table as a SrcList for sqlite3WhereBegin() */ pSrc = sqlite3SrcListAppend(db, 0, 0, 0); if( pSrc ){ struct SrcList_item *pItem = pSrc->a; pItem->pTab = pFKey->pFrom; pItem->zName = pFKey->pFrom->zName; pItem->pTab->nTabRef++; pItem->iCursor = pParse->nTab++; if( regNew!=0 ){ fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1); } if( regOld!=0 ){ int eAction = pFKey->aAction[aChange!=0]; fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1); /* If this is a deferred FK constraint, or a CASCADE or SET NULL ** action applies, then any foreign key violations caused by ** removing the parent key will be rectified by the action trigger. ** So do not set the "may-abort" flag in this case. ** ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the ** may-abort flag will eventually be set on this statement anyway ** (when this function is called as part of processing the UPDATE ** within the action trigger). ** ** Note 2: At first glance it may seem like SQLite could simply omit ** all OP_FkCounter related scans when either CASCADE or SET NULL ** applies. The trouble starts if the CASCADE or SET NULL action ** trigger causes other triggers or action rules attached to the ** child table to fire. In these cases the fk constraint counters ** might be set incorrectly if any OP_FkCounter related scans are ** omitted. */ if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){ sqlite3MayAbort(pParse); } } pItem->zName = 0; sqlite3SrcListDelete(db, pSrc); } sqlite3DbFree(db, aiCol); } } #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x))) /* ** This function is called before generating code to update or delete a ** row contained in table pTab. */ SQLITE_PRIVATE u32 sqlite3FkOldmask( Parse *pParse, /* Parse context */ Table *pTab /* Table being modified */ ){ u32 mask = 0; if( pParse->db->flags&SQLITE_ForeignKeys ){ FKey *p; int i; for(p=pTab->pFKey; p; p=p->pNextFrom){ for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); } for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ Index *pIdx = 0; sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0); if( pIdx ){ for(i=0; i<pIdx->nKeyCol; i++){ assert( pIdx->aiColumn[i]>=0 ); mask |= COLUMN_MASK(pIdx->aiColumn[i]); } } } } return mask; } /* ** This function is called before generating code to update or delete a ** row contained in table pTab. If the operation is a DELETE, then ** parameter aChange is passed a NULL value. For an UPDATE, aChange points ** to an array of size N, where N is the number of columns in table pTab. ** If the i'th column is not modified by the UPDATE, then the corresponding ** entry in the aChange[] array is set to -1. If the column is modified, ** the value is 0 or greater. Parameter chngRowid is set to true if the ** UPDATE statement modifies the rowid fields of the table. ** ** If any foreign key processing will be required, this function returns ** true. If there is no foreign key related processing, this function ** returns false. */ SQLITE_PRIVATE int sqlite3FkRequired( Parse *pParse, /* Parse context */ Table *pTab, /* Table being modified */ int *aChange, /* Non-NULL for UPDATE operations */ int chngRowid /* True for UPDATE that affects rowid */ ){ if( pParse->db->flags&SQLITE_ForeignKeys ){ if( !aChange ){ /* A DELETE operation. Foreign key processing is required if the ** table in question is either the child or parent table for any ** foreign key constraint. */ return (sqlite3FkReferences(pTab) || pTab->pFKey); }else{ /* This is an UPDATE. Foreign key processing is only required if the ** operation modifies one or more child or parent key columns. */ FKey *p; /* Check if any child key columns are being modified. */ for(p=pTab->pFKey; p; p=p->pNextFrom){ if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1; } /* Check if any parent key columns are being modified. */ for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1; } } } return 0; } /* ** This function is called when an UPDATE or DELETE operation is being ** compiled on table pTab, which is the parent table of foreign-key pFKey. ** If the current operation is an UPDATE, then the pChanges parameter is ** passed a pointer to the list of columns being modified. If it is a ** DELETE, pChanges is passed a NULL pointer. ** ** It returns a pointer to a Trigger structure containing a trigger ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is ** returned (these actions require no special handling by the triggers ** sub-system, code for them is created by fkScanChildren()). ** ** For example, if pFKey is the foreign key and pTab is table "p" in ** the following schema: ** ** CREATE TABLE p(pk PRIMARY KEY); ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE); ** ** then the returned trigger structure is equivalent to: ** ** CREATE TRIGGER ... DELETE ON p BEGIN ** DELETE FROM c WHERE ck = old.pk; ** END; ** ** The returned pointer is cached as part of the foreign key object. It ** is eventually freed along with the rest of the foreign key object by ** sqlite3FkDelete(). */ static Trigger *fkActionTrigger( Parse *pParse, /* Parse context */ Table *pTab, /* Table being updated or deleted from */ FKey *pFKey, /* Foreign key to get action for */ ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */ ){ sqlite3 *db = pParse->db; /* Database handle */ int action; /* One of OE_None, OE_Cascade etc. */ Trigger *pTrigger; /* Trigger definition to return */ int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */ action = pFKey->aAction[iAction]; if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){ return 0; } pTrigger = pFKey->apTrigger[iAction]; if( action!=OE_None && !pTrigger ){ char const *zFrom; /* Name of child table */ int nFrom; /* Length in bytes of zFrom */ Index *pIdx = 0; /* Parent key index for this FK */ int *aiCol = 0; /* child table cols -> parent key cols */ TriggerStep *pStep = 0; /* First (only) step of trigger program */ Expr *pWhere = 0; /* WHERE clause of trigger step */ ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */ Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */ int i; /* Iterator variable */ Expr *pWhen = 0; /* WHEN clause for the trigger */ if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; assert( aiCol || pFKey->nCol==1 ); for(i=0; i<pFKey->nCol; i++){ Token tOld = { "old", 3 }; /* Literal "old" token */ Token tNew = { "new", 3 }; /* Literal "new" token */ Token tFromCol; /* Name of column in child table */ Token tToCol; /* Name of column in parent table */ int iFromCol; /* Idx of column in child table */ Expr *pEq; /* tFromCol = OLD.tToCol */ iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; assert( iFromCol>=0 ); assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) ); assert( pIdx==0 || pIdx->aiColumn[i]>=0 ); sqlite3TokenInit(&tToCol, pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName); sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName); /* Create the expression "OLD.zToCol = zFromCol". It is important ** that the "OLD.zToCol" term is on the LHS of the = operator, so ** that the affinity and collation sequence associated with the ** parent table are used for the comparison. */ pEq = sqlite3PExpr(pParse, TK_EQ, sqlite3PExpr(pParse, TK_DOT, sqlite3ExprAlloc(db, TK_ID, &tOld, 0), sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)), sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0) ); pWhere = sqlite3ExprAnd(db, pWhere, pEq); /* For ON UPDATE, construct the next term of the WHEN clause. ** The final WHEN clause will be like this: ** ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) */ if( pChanges ){ pEq = sqlite3PExpr(pParse, TK_IS, sqlite3PExpr(pParse, TK_DOT, sqlite3ExprAlloc(db, TK_ID, &tOld, 0), sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)), sqlite3PExpr(pParse, TK_DOT, sqlite3ExprAlloc(db, TK_ID, &tNew, 0), sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)) ); pWhen = sqlite3ExprAnd(db, pWhen, pEq); } if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){ Expr *pNew; if( action==OE_Cascade ){ pNew = sqlite3PExpr(pParse, TK_DOT, sqlite3ExprAlloc(db, TK_ID, &tNew, 0), sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)); }else if( action==OE_SetDflt ){ Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt; if( pDflt ){ pNew = sqlite3ExprDup(db, pDflt, 0); }else{ pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0); } }else{ pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0); } pList = sqlite3ExprListAppend(pParse, pList, pNew); sqlite3ExprListSetName(pParse, pList, &tFromCol, 0); } } sqlite3DbFree(db, aiCol); zFrom = pFKey->pFrom->zName; nFrom = sqlite3Strlen30(zFrom); if( action==OE_Restrict ){ Token tFrom; Expr *pRaise; tFrom.z = zFrom; tFrom.n = nFrom; pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed"); if( pRaise ){ pRaise->affinity = OE_Abort; } pSelect = sqlite3SelectNew(pParse, sqlite3ExprListAppend(pParse, 0, pRaise), sqlite3SrcListAppend(db, 0, &tFrom, 0), pWhere, 0, 0, 0, 0, 0, 0 ); pWhere = 0; } /* Disable lookaside memory allocation */ db->lookaside.bDisable++; pTrigger = (Trigger *)sqlite3DbMallocZero(db, sizeof(Trigger) + /* struct Trigger */ sizeof(TriggerStep) + /* Single step in trigger program */ nFrom + 1 /* Space for pStep->zTarget */ ); if( pTrigger ){ pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; pStep->zTarget = (char *)&pStep[1]; memcpy((char *)pStep->zTarget, zFrom, nFrom); pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); if( pWhen ){ pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0); pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); } } /* Re-enable the lookaside buffer, if it was disabled earlier. */ db->lookaside.bDisable--; sqlite3ExprDelete(db, pWhere); sqlite3ExprDelete(db, pWhen); sqlite3ExprListDelete(db, pList); sqlite3SelectDelete(db, pSelect); if( db->mallocFailed==1 ){ fkTriggerDelete(db, pTrigger); return 0; } assert( pStep!=0 ); switch( action ){ case OE_Restrict: pStep->op = TK_SELECT; break; case OE_Cascade: if( !pChanges ){ pStep->op = TK_DELETE; break; } default: pStep->op = TK_UPDATE; } pStep->pTrig = pTrigger; pTrigger->pSchema = pTab->pSchema; pTrigger->pTabSchema = pTab->pSchema; pFKey->apTrigger[iAction] = pTrigger; pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE); } return pTrigger; } /* ** This function is called when deleting or updating a row to implement ** any required CASCADE, SET NULL or SET DEFAULT actions. */ SQLITE_PRIVATE void sqlite3FkActions( Parse *pParse, /* Parse context */ Table *pTab, /* Table being updated or deleted from */ ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ int regOld, /* Address of array containing old row */ int *aChange, /* Array indicating UPDATEd columns (or 0) */ int bChngRowid /* True if rowid is UPDATEd */ ){ /* If foreign-key support is enabled, iterate through all FKs that ** refer to table pTab. If there is an action associated with the FK ** for this operation (either update or delete), invoke the associated ** trigger sub-program. */ if( pParse->db->flags&SQLITE_ForeignKeys ){ FKey *pFKey; /* Iterator variable */ for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){ Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges); if( pAct ){ sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0); } } } } } #endif /* ifndef SQLITE_OMIT_TRIGGER */ /* ** Free all memory associated with foreign key definitions attached to ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash ** hash table. */ SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){ FKey *pFKey; /* Iterator variable */ FKey *pNext; /* Copy of pFKey->pNextFrom */ assert( db==0 || IsVirtual(pTab) || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) ); for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ /* Remove the FK from the fkeyHash hash table. */ if( !db || db->pnBytesFreed==0 ){ if( pFKey->pPrevTo ){ pFKey->pPrevTo->pNextTo = pFKey->pNextTo; }else{ void *p = (void *)pFKey->pNextTo; const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo); sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p); } if( pFKey->pNextTo ){ pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; } } /* EV: R-30323-21917 Each foreign key constraint in SQLite is ** classified as either immediate or deferred. */ assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 ); /* Delete any triggers created to implement actions for this FK. */ #ifndef SQLITE_OMIT_TRIGGER fkTriggerDelete(db, pFKey->apTrigger[0]); fkTriggerDelete(db, pFKey->apTrigger[1]); #endif pNext = pFKey->pNextFrom; sqlite3DbFree(db, pFKey); } } #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ /************** End of fkey.c ************************************************/ /************** Begin file insert.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle INSERT statements in SQLite. */ /* #include "sqliteInt.h" */ /* ** Generate code that will ** ** (1) acquire a lock for table pTab then ** (2) open pTab as cursor iCur. ** ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index ** for that table that is actually opened. */ SQLITE_PRIVATE void sqlite3OpenTable( Parse *pParse, /* Generate code into this VDBE */ int iCur, /* The cursor number of the table */ int iDb, /* The database index in sqlite3.aDb[] */ Table *pTab, /* The table to be opened */ int opcode /* OP_OpenRead or OP_OpenWrite */ ){ Vdbe *v; assert( !IsVirtual(pTab) ); v = sqlite3GetVdbe(pParse); assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); sqlite3TableLock(pParse, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName); if( HasRowid(pTab) ){ sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol); VdbeComment((v, "%s", pTab->zName)); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pTab); assert( pPk!=0 ); assert( pPk->tnum==pTab->tnum ); sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pPk); VdbeComment((v, "%s", pTab->zName)); } } /* ** Return a pointer to the column affinity string associated with index ** pIdx. A column affinity string has one character for each column in ** the table, according to the affinity of the column: ** ** Character Column affinity ** ------------------------------ ** 'A' BLOB ** 'B' TEXT ** 'C' NUMERIC ** 'D' INTEGER ** 'F' REAL ** ** An extra 'D' is appended to the end of the string to cover the ** rowid that appears as the last column in every index. ** ** Memory for the buffer containing the column index affinity string ** is managed along with the rest of the Index structure. It will be ** released when sqlite3DeleteIndex() is called. */ SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ if( !pIdx->zColAff ){ /* The first time a column affinity string for a particular index is ** required, it is allocated and populated here. It is then stored as ** a member of the Index structure for subsequent use. ** ** The column affinity string will eventually be deleted by ** sqliteDeleteIndex() when the Index structure itself is cleaned ** up. */ int n; Table *pTab = pIdx->pTable; pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); if( !pIdx->zColAff ){ sqlite3OomFault(db); return 0; } for(n=0; n<pIdx->nColumn; n++){ i16 x = pIdx->aiColumn[n]; if( x>=0 ){ pIdx->zColAff[n] = pTab->aCol[x].affinity; }else if( x==XN_ROWID ){ pIdx->zColAff[n] = SQLITE_AFF_INTEGER; }else{ char aff; assert( x==XN_EXPR ); assert( pIdx->aColExpr!=0 ); aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); if( aff==0 ) aff = SQLITE_AFF_BLOB; pIdx->zColAff[n] = aff; } } pIdx->zColAff[n] = 0; } return pIdx->zColAff; } /* ** Compute the affinity string for table pTab, if it has not already been ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. ** ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and ** if iReg>0 then code an OP_Affinity opcode that will set the affinities ** for register iReg and following. Or if affinities exists and iReg==0, ** then just set the P4 operand of the previous opcode (which should be ** an OP_MakeRecord) to the affinity string. ** ** A column affinity string has one character per column: ** ** Character Column affinity ** ------------------------------ ** 'A' BLOB ** 'B' TEXT ** 'C' NUMERIC ** 'D' INTEGER ** 'E' REAL */ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ int i; char *zColAff = pTab->zColAff; if( zColAff==0 ){ sqlite3 *db = sqlite3VdbeDb(v); zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); if( !zColAff ){ sqlite3OomFault(db); return; } for(i=0; i<pTab->nCol; i++){ zColAff[i] = pTab->aCol[i].affinity; } do{ zColAff[i--] = 0; }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB ); pTab->zColAff = zColAff; } i = sqlite3Strlen30(zColAff); if( i ){ if( iReg ){ sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); }else{ sqlite3VdbeChangeP4(v, -1, zColAff, i); } } } /* ** Return non-zero if the table pTab in database iDb or any of its indices ** have been opened at any point in the VDBE program. This is used to see if ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can ** run without using a temporary table for the results of the SELECT. */ static int readsTable(Parse *p, int iDb, Table *pTab){ Vdbe *v = sqlite3GetVdbe(p); int i; int iEnd = sqlite3VdbeCurrentAddr(v); #ifndef SQLITE_OMIT_VIRTUALTABLE VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; #endif for(i=1; i<iEnd; i++){ VdbeOp *pOp = sqlite3VdbeGetOp(v, i); assert( pOp!=0 ); if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ Index *pIndex; int tnum = pOp->p2; if( tnum==pTab->tnum ){ return 1; } for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ if( tnum==pIndex->tnum ){ return 1; } } } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ assert( pOp->p4.pVtab!=0 ); assert( pOp->p4type==P4_VTAB ); return 1; } #endif } return 0; } #ifndef SQLITE_OMIT_AUTOINCREMENT /* ** Locate or create an AutoincInfo structure associated with table pTab ** which is in database iDb. Return the register number for the register ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT ** table. (Also return zero when doing a VACUUM since we do not want to ** update the AUTOINCREMENT counters during a VACUUM.) ** ** There is at most one AutoincInfo structure per table even if the ** same table is autoincremented multiple times due to inserts within ** triggers. A new AutoincInfo structure is created if this is the ** first use of table pTab. On 2nd and subsequent uses, the original ** AutoincInfo structure is used. ** ** Three memory locations are allocated: ** ** (1) Register to hold the name of the pTab table. ** (2) Register to hold the maximum ROWID of pTab. ** (3) Register to hold the rowid in sqlite_sequence of pTab ** ** The 2nd register is the one that is returned. That is all the ** insert routine needs to know about. */ static int autoIncBegin( Parse *pParse, /* Parsing context */ int iDb, /* Index of the database holding pTab */ Table *pTab /* The table we are writing to */ ){ int memId = 0; /* Register holding maximum rowid */ if( (pTab->tabFlags & TF_Autoincrement)!=0 && (pParse->db->flags & SQLITE_Vacuum)==0 ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); AutoincInfo *pInfo; pInfo = pToplevel->pAinc; while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } if( pInfo==0 ){ pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); if( pInfo==0 ) return 0; pInfo->pNext = pToplevel->pAinc; pToplevel->pAinc = pInfo; pInfo->pTab = pTab; pInfo->iDb = iDb; pToplevel->nMem++; /* Register to hold name of table */ pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ pToplevel->nMem++; /* Rowid in sqlite_sequence */ } memId = pInfo->regCtr; } return memId; } /* ** This routine generates code that will initialize all of the ** register used by the autoincrement tracker. */ SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){ AutoincInfo *p; /* Information about an AUTOINCREMENT */ sqlite3 *db = pParse->db; /* The database connection */ Db *pDb; /* Database only autoinc table */ int memId; /* Register holding max rowid */ Vdbe *v = pParse->pVdbe; /* VDBE under construction */ /* This routine is never called during trigger-generation. It is ** only called from the top-level */ assert( pParse->pTriggerTab==0 ); assert( sqlite3IsToplevel(pParse) ); assert( v ); /* We failed long ago if this is not so */ for(p = pParse->pAinc; p; p = p->pNext){ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList autoInc[] = { /* 0 */ {OP_Null, 0, 0, 0}, /* 1 */ {OP_Rewind, 0, 9, 0}, /* 2 */ {OP_Column, 0, 0, 0}, /* 3 */ {OP_Ne, 0, 7, 0}, /* 4 */ {OP_Rowid, 0, 0, 0}, /* 5 */ {OP_Column, 0, 1, 0}, /* 6 */ {OP_Goto, 0, 9, 0}, /* 7 */ {OP_Next, 0, 2, 0}, /* 8 */ {OP_Integer, 0, 0, 0}, /* 9 */ {OP_Close, 0, 0, 0} }; VdbeOp *aOp; pDb = &db->aDb[p->iDb]; memId = p->regCtr; assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); if( aOp==0 ) break; aOp[0].p2 = memId; aOp[0].p3 = memId+1; aOp[2].p3 = memId; aOp[3].p1 = memId-1; aOp[3].p3 = memId; aOp[3].p5 = SQLITE_JUMPIFNULL; aOp[4].p2 = memId+1; aOp[5].p3 = memId; aOp[8].p2 = memId; } } /* ** Update the maximum rowid for an autoincrement calculation. ** ** This routine should be called when the regRowid register holds a ** new rowid that is about to be inserted. If that new rowid is ** larger than the maximum rowid in the memId memory cell, then the ** memory cell is updated. */ static void autoIncStep(Parse *pParse, int memId, int regRowid){ if( memId>0 ){ sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); } } /* ** This routine generates the code needed to write autoincrement ** maximum rowid values back into the sqlite_sequence register. ** Every statement that might do an INSERT into an autoincrement ** table (either directly or through triggers) needs to call this ** routine just before the "exit" code. */ static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ AutoincInfo *p; Vdbe *v = pParse->pVdbe; sqlite3 *db = pParse->db; assert( v ); for(p = pParse->pAinc; p; p = p->pNext){ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList autoIncEnd[] = { /* 0 */ {OP_NotNull, 0, 2, 0}, /* 1 */ {OP_NewRowid, 0, 0, 0}, /* 2 */ {OP_MakeRecord, 0, 2, 0}, /* 3 */ {OP_Insert, 0, 0, 0}, /* 4 */ {OP_Close, 0, 0, 0} }; VdbeOp *aOp; Db *pDb = &db->aDb[p->iDb]; int iRec; int memId = p->regCtr; iRec = sqlite3GetTempReg(pParse); assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); if( aOp==0 ) break; aOp[0].p1 = memId+1; aOp[1].p2 = memId+1; aOp[2].p1 = memId-1; aOp[2].p3 = iRec; aOp[3].p2 = iRec; aOp[3].p3 = memId+1; aOp[3].p5 = OPFLAG_APPEND; sqlite3ReleaseTempReg(pParse, iRec); } } SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){ if( pParse->pAinc ) autoIncrementEnd(pParse); } #else /* ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines ** above are all no-ops */ # define autoIncBegin(A,B,C) (0) # define autoIncStep(A,B,C) #endif /* SQLITE_OMIT_AUTOINCREMENT */ /* Forward declaration */ static int xferOptimization( Parse *pParse, /* Parser context */ Table *pDest, /* The table we are inserting into */ Select *pSelect, /* A SELECT statement to use as the data source */ int onError, /* How to handle constraint errors */ int iDbDest /* The database of pDest */ ); /* ** This routine is called to handle SQL of the following forms: ** ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... ** insert into TABLE (IDLIST) select ** insert into TABLE (IDLIST) default values ** ** The IDLIST following the table name is always optional. If omitted, ** then a list of all (non-hidden) columns for the table is substituted. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST ** is omitted. ** ** For the pSelect parameter holds the values to be inserted for the ** first two forms shown above. A VALUES clause is really just short-hand ** for a SELECT statement that omits the FROM clause and everything else ** that follows. If the pSelect parameter is NULL, that means that the ** DEFAULT VALUES form of the INSERT statement is intended. ** ** The code generated follows one of four templates. For a simple ** insert with data coming from a single-row VALUES clause, the code executes ** once straight down through. Pseudo-code follows (we call this ** the "1st template"): ** ** open write cursor to <table> and its indices ** put VALUES clause expressions into registers ** write the resulting record into <table> ** cleanup ** ** The three remaining templates assume the statement is of the form ** ** INSERT INTO <table> SELECT ... ** ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" - ** in other words if the SELECT pulls all columns from a single table ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and ** if <table2> and <table1> are distinct tables but have identical ** schemas, including all the same indices, then a special optimization ** is invoked that copies raw records from <table2> over to <table1>. ** See the xferOptimization() function for the implementation of this ** template. This is the 2nd template. ** ** open a write cursor to <table> ** open read cursor on <table2> ** transfer all records in <table2> over to <table> ** close cursors ** foreach index on <table> ** open a write cursor on the <table> index ** open a read cursor on the corresponding <table2> index ** transfer all records from the read to the write cursors ** close cursors ** end foreach ** ** The 3rd template is for when the second template does not apply ** and the SELECT clause does not read from <table> at any time. ** The generated code follows this template: ** ** X <- A ** goto B ** A: setup for the SELECT ** loop over the rows in the SELECT ** load values into registers R..R+n ** yield X ** end loop ** cleanup after the SELECT ** end-coroutine X ** B: open write cursor to <table> and its indices ** C: yield X, at EOF goto D ** insert the select result into <table> from R..R+n ** goto C ** D: cleanup ** ** The 4th template is used if the insert statement takes its ** values from a SELECT but the data is being inserted into a table ** that is also read as part of the SELECT. In the third form, ** we have to use an intermediate table to store the results of ** the select. The template is like this: ** ** X <- A ** goto B ** A: setup for the SELECT ** loop over the tables in the SELECT ** load value into register R..R+n ** yield X ** end loop ** cleanup after the SELECT ** end co-routine R ** B: open temp table ** L: yield X, at EOF goto M ** insert row from R..R+n into temp table ** goto L ** M: open write cursor to <table> and its indices ** rewind temp table ** C: loop over rows of intermediate table ** transfer values form intermediate table into <table> ** end loop ** D: cleanup */ SQLITE_PRIVATE void sqlite3Insert( Parse *pParse, /* Parser context */ SrcList *pTabList, /* Name of table into which we are inserting */ Select *pSelect, /* A SELECT statement to use as the data source */ IdList *pColumn, /* Column names corresponding to IDLIST. */ int onError /* How to handle constraint errors */ ){ sqlite3 *db; /* The main database structure */ Table *pTab; /* The table to insert into. aka TABLE */ char *zTab; /* Name of the table into which we are inserting */ int i, j; /* Loop counters */ Vdbe *v; /* Generate code into this virtual machine */ Index *pIdx; /* For looping over indices of the table */ int nColumn; /* Number of columns in the data */ int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ int iDataCur = 0; /* VDBE cursor that is the main data repository */ int iIdxCur = 0; /* First index cursor */ int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ int endOfLoop; /* Label for the end of the insertion loop */ int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ int addrInsTop = 0; /* Jump to label "D" */ int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ SelectDest dest; /* Destination for SELECT on rhs of INSERT */ int iDb; /* Index of database holding TABLE */ u8 useTempTable = 0; /* Store SELECT results in intermediate table */ u8 appendFlag = 0; /* True if the insert is likely to be an append */ u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ u8 bIdListInOrder; /* True if IDLIST is in table order */ ExprList *pList = 0; /* List of VALUES() to be inserted */ /* Register allocations */ int regFromSelect = 0;/* Base register for data coming from SELECT */ int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ int regRowCount = 0; /* Memory cell used for the row counter */ int regIns; /* Block of regs holding rowid+data being inserted */ int regRowid; /* registers holding insert rowid */ int regData; /* register holding first column to insert */ int *aRegIdx = 0; /* One register allocated to each index */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True if attempting to insert into a view */ Trigger *pTrigger; /* List of triggers on pTab, if required */ int tmask; /* Mask of trigger times */ #endif db = pParse->db; memset(&dest, 0, sizeof(dest)); if( pParse->nErr || db->mallocFailed ){ goto insert_cleanup; } /* If the Select object is really just a simple VALUES() list with a ** single row (the common case) then keep that one row of values ** and discard the other (unused) parts of the pSelect object */ if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ pList = pSelect->pEList; pSelect->pEList = 0; sqlite3SelectDelete(db, pSelect); pSelect = 0; } /* Locate the table into which we will be inserting new information. */ assert( pTabList->nSrc==1 ); zTab = pTabList->a[0].zName; if( NEVER(zTab==0) ) goto insert_cleanup; pTab = sqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ){ goto insert_cleanup; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb<db->nDb ); if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, db->aDb[iDb].zDbSName) ){ goto insert_cleanup; } withoutRowid = !HasRowid(pTab); /* Figure out if we have any triggers and if the table being ** inserted into is a view */ #ifndef SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); isView = pTab->pSelect!=0; #else # define pTrigger 0 # define tmask 0 # define isView 0 #endif #ifdef SQLITE_OMIT_VIEW # undef isView # define isView 0 #endif assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); /* If pTab is really a view, make sure it has been initialized. ** ViewGetColumnNames() is a no-op if pTab is not a view. */ if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto insert_cleanup; } /* Cannot insert into a read-only table. */ if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ goto insert_cleanup; } /* Allocate a VDBE */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto insert_cleanup; if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); #ifndef SQLITE_OMIT_XFER_OPT /* If the statement is of the form ** ** INSERT INTO <table1> SELECT * FROM <table2>; ** ** Then special optimizations can be applied that make the transfer ** very fast and which reduce fragmentation of indices. ** ** This is the 2nd template. */ if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ assert( !pTrigger ); assert( pList==0 ); goto insert_end; } #endif /* SQLITE_OMIT_XFER_OPT */ /* If this is an AUTOINCREMENT table, look up the sequence number in the ** sqlite_sequence table and store it in memory cell regAutoinc. */ regAutoinc = autoIncBegin(pParse, iDb, pTab); /* Allocate registers for holding the rowid of the new row, ** the content of the new row, and the assembled row record. */ regRowid = regIns = pParse->nMem+1; pParse->nMem += pTab->nCol + 1; if( IsVirtual(pTab) ){ regRowid++; pParse->nMem++; } regData = regRowid+1; /* If the INSERT statement included an IDLIST term, then make sure ** all elements of the IDLIST really are columns of the table and ** remember the column indices. ** ** If the table has an INTEGER PRIMARY KEY column and that column ** is named in the IDLIST, then record in the ipkColumn variable ** the index into IDLIST of the primary key column. ipkColumn is ** the index of the primary key as it appears in IDLIST, not as ** is appears in the original table. (The index of the INTEGER ** PRIMARY KEY in the original table is pTab->iPKey.) */ bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0; if( pColumn ){ for(i=0; i<pColumn->nId; i++){ pColumn->a[i].idx = -1; } for(i=0; i<pColumn->nId; i++){ for(j=0; j<pTab->nCol; j++){ if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ pColumn->a[i].idx = j; if( i!=j ) bIdListInOrder = 0; if( j==pTab->iPKey ){ ipkColumn = i; assert( !withoutRowid ); } break; } } if( j>=pTab->nCol ){ if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ ipkColumn = i; bIdListInOrder = 0; }else{ sqlite3ErrorMsg(pParse, "table %S has no column named %s", pTabList, 0, pColumn->a[i].zName); pParse->checkSchema = 1; goto insert_cleanup; } } } } /* Figure out how many columns of data are supplied. If the data ** is coming from a SELECT statement, then generate a co-routine that ** produces a single row of the SELECT on each invocation. The ** co-routine is the common header to the 3rd and 4th templates. */ if( pSelect ){ /* Data is coming from a SELECT or from a multi-row VALUES clause. ** Generate a co-routine to run the SELECT. */ int regYield; /* Register holding co-routine entry-point */ int addrTop; /* Top of the co-routine */ int rc; /* Result code */ regYield = ++pParse->nMem; addrTop = sqlite3VdbeCurrentAddr(v) + 1; sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); dest.iSdst = bIdListInOrder ? regData : 0; dest.nSdst = pTab->nCol; rc = sqlite3Select(pParse, pSelect, &dest); regFromSelect = dest.iSdst; if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; sqlite3VdbeEndCoroutine(v, regYield); sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ assert( pSelect->pEList ); nColumn = pSelect->pEList->nExpr; /* Set useTempTable to TRUE if the result of the SELECT statement ** should be written into a temporary table (template 4). Set to ** FALSE if each output row of the SELECT can be written directly into ** the destination table (template 3). ** ** A temp table must be used if the table being updated is also one ** of the tables being read by the SELECT statement. Also use a ** temp table in the case of row triggers. */ if( pTrigger || readsTable(pParse, iDb, pTab) ){ useTempTable = 1; } if( useTempTable ){ /* Invoke the coroutine to extract information from the SELECT ** and add it to a transient table srcTab. The code generated ** here is from the 4th template: ** ** B: open temp table ** L: yield X, goto M at EOF ** insert row from R..R+n into temp table ** goto L ** M: ... */ int regRec; /* Register to hold packed record */ int regTempRowid; /* Register to hold temp table ROWID */ int addrL; /* Label "L" */ srcTab = pParse->nTab++; regRec = sqlite3GetTempReg(pParse); regTempRowid = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); sqlite3VdbeGoto(v, addrL); sqlite3VdbeJumpHere(v, addrL); sqlite3ReleaseTempReg(pParse, regRec); sqlite3ReleaseTempReg(pParse, regTempRowid); } }else{ /* This is the case if the data for the INSERT is coming from a ** single-row VALUES clause */ NameContext sNC; memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; srcTab = -1; assert( useTempTable==0 ); if( pList ){ nColumn = pList->nExpr; if( sqlite3ResolveExprListNames(&sNC, pList) ){ goto insert_cleanup; } }else{ nColumn = 0; } } /* If there is no IDLIST term but the table has an integer primary ** key, the set the ipkColumn variable to the integer primary key ** column index in the original table definition. */ if( pColumn==0 && nColumn>0 ){ ipkColumn = pTab->iPKey; } /* Make sure the number of columns in the source data matches the number ** of columns to be inserted into the table. */ for(i=0; i<pTab->nCol; i++){ nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); } if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ sqlite3ErrorMsg(pParse, "table %S has %d columns but %d values were supplied", pTabList, 0, pTab->nCol-nHidden, nColumn); goto insert_cleanup; } if( pColumn!=0 && nColumn!=pColumn->nId ){ sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); goto insert_cleanup; } /* Initialize the count of rows to be inserted */ if( db->flags & SQLITE_CountRows ){ regRowCount = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } /* If this is not a view, open the table and and all indices */ if( !isView ){ int nIdx; nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, &iDataCur, &iIdxCur); aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1)); if( aRegIdx==0 ){ goto insert_cleanup; } for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){ assert( pIdx ); aRegIdx[i] = ++pParse->nMem; pParse->nMem += pIdx->nColumn; } } /* This is the top of the main insertion loop */ if( useTempTable ){ /* This block codes the top of loop only. The complete loop is the ** following pseudocode (template 4): ** ** rewind temp table, if empty goto D ** C: loop over rows of intermediate table ** transfer values form intermediate table into <table> ** end loop ** D: ... */ addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); addrCont = sqlite3VdbeCurrentAddr(v); }else if( pSelect ){ /* This block codes the top of loop only. The complete loop is the ** following pseudocode (template 3): ** ** C: yield X, at EOF goto D ** insert the select result into <table> from R..R+n ** goto C ** D: ... */ addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); } /* Run the BEFORE and INSTEAD OF triggers, if there are any */ endOfLoop = sqlite3VdbeMakeLabel(v); if( tmask & TRIGGER_BEFORE ){ int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); /* build the NEW.* reference row. Note that if there is an INTEGER ** PRIMARY KEY into which a NULL is being inserted, that NULL will be ** translated into a unique ID for the row. But on a BEFORE trigger, ** we do not know what the unique ID will be (because the insert has ** not happened yet) so we substitute a rowid of -1 */ if( ipkColumn<0 ){ sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); }else{ int addr1; assert( !withoutRowid ); if( useTempTable ){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); }else{ assert( pSelect==0 ); /* Otherwise useTempTable is true */ sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); } addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); } /* Cannot have triggers on a virtual table. If it were possible, ** this block would have to account for hidden column. */ assert( !IsVirtual(pTab) ); /* Create the new column data */ for(i=j=0; i<pTab->nCol; i++){ if( pColumn ){ for(j=0; j<pColumn->nId; j++){ if( pColumn->a[j].idx==i ) break; } } if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){ sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); }else if( useTempTable ){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); }else{ assert( pSelect==0 ); /* Otherwise useTempTable is true */ sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); } if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++; } /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, ** do not attempt any conversions before assembling the record. ** If this is a real table, attempt conversions as required by the ** table column affinities. */ if( !isView ){ sqlite3TableAffinity(v, pTab, regCols+1); } /* Fire BEFORE or INSTEAD OF triggers */ sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, pTab, regCols-pTab->nCol-1, onError, endOfLoop); sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); } /* Compute the content of the next row to insert into a range of ** registers beginning at regIns. */ if( !isView ){ if( IsVirtual(pTab) ){ /* The row that the VUpdate opcode will delete: none */ sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); } if( ipkColumn>=0 ){ if( useTempTable ){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); }else if( pSelect ){ sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); }else{ VdbeOp *pOp; sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); pOp = sqlite3VdbeGetOp(v, -1); if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ appendFlag = 1; pOp->opcode = OP_NewRowid; pOp->p1 = iDataCur; pOp->p2 = regRowid; pOp->p3 = regAutoinc; } } /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid ** to generate a unique primary key value. */ if( !appendFlag ){ int addr1; if( !IsVirtual(pTab) ){ addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); sqlite3VdbeJumpHere(v, addr1); }else{ addr1 = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); } sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); } }else if( IsVirtual(pTab) || withoutRowid ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); }else{ sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); appendFlag = 1; } autoIncStep(pParse, regAutoinc, regRowid); /* Compute data for all columns of the new entry, beginning ** with the first column. */ nHidden = 0; for(i=0; i<pTab->nCol; i++){ int iRegStore = regRowid+1+i; if( i==pTab->iPKey ){ /* The value of the INTEGER PRIMARY KEY column is always a NULL. ** Whenever this column is read, the rowid will be substituted ** in its place. Hence, fill this column with a NULL to avoid ** taking up data space with information that will never be used. ** As there may be shallow copies of this value, make it a soft-NULL */ sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); continue; } if( pColumn==0 ){ if( IsHiddenColumn(&pTab->aCol[i]) ){ j = -1; nHidden++; }else{ j = i - nHidden; } }else{ for(j=0; j<pColumn->nId; j++){ if( pColumn->a[j].idx==i ) break; } } if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); }else if( useTempTable ){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); }else if( pSelect ){ if( regFromSelect!=regData ){ sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); } }else{ sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); } } /* Generate code to check constraints and generate index keys and ** do the insertion. */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); sqlite3MayAbort(pParse); }else #endif { int isReplace; /* Set to true if constraints may cause a replace */ int bUseSeek; /* True to use OPFLAG_SEEKRESULT */ sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0 ); sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE ** constraints or (b) there are no triggers and this table is not a ** parent table in a foreign key constraint. It is safe to set the ** flag in the second case as if any REPLACE constraint is hit, an ** OP_Delete or OP_IdxDelete instruction will be executed on each ** cursor that is disturbed. And these instructions both clear the ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT ** functionality. */ bUseSeek = (isReplace==0 || (pTrigger==0 && ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0) )); sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, regIns, aRegIdx, 0, appendFlag, bUseSeek ); } } /* Update the count of rows that are inserted */ if( (db->flags & SQLITE_CountRows)!=0 ){ sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } if( pTrigger ){ /* Code AFTER triggers */ sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, pTab, regData-2-pTab->nCol, onError, endOfLoop); } /* The bottom of the main insertion loop, if the data source ** is a SELECT statement. */ sqlite3VdbeResolveLabel(v, endOfLoop); if( useTempTable ){ sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrInsTop); sqlite3VdbeAddOp1(v, OP_Close, srcTab); }else if( pSelect ){ sqlite3VdbeGoto(v, addrCont); sqlite3VdbeJumpHere(v, addrInsTop); } insert_end: /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if( pParse->nested==0 && pParse->pTriggerTab==0 ){ sqlite3AutoincrementEnd(pParse); } /* ** Return the number of rows inserted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); } insert_cleanup: sqlite3SrcListDelete(db, pTabList); sqlite3ExprListDelete(db, pList); sqlite3SelectDelete(db, pSelect); sqlite3IdListDelete(db, pColumn); sqlite3DbFree(db, aRegIdx); } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** they may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ #ifdef isView #undef isView #endif #ifdef pTrigger #undef pTrigger #endif #ifdef tmask #undef tmask #endif /* ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged() */ #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ /* This is the Walker callback from checkConstraintUnchanged(). Set ** bit 0x01 of pWalker->eCode if ** pWalker->eCode to 0 if this expression node references any of the ** columns that are being modifed by an UPDATE statement. */ static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_COLUMN ){ assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 ); if( pExpr->iColumn>=0 ){ if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){ pWalker->eCode |= CKCNSTRNT_COLUMN; } }else{ pWalker->eCode |= CKCNSTRNT_ROWID; } } return WRC_Continue; } /* ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The ** only columns that are modified by the UPDATE are those for which ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. ** ** Return true if CHECK constraint pExpr does not use any of the ** changing columns (or the rowid if it is changing). In other words, ** return true if this CHECK constraint can be skipped when validating ** the new row in the UPDATE statement. */ static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ Walker w; memset(&w, 0, sizeof(w)); w.eCode = 0; w.xExprCallback = checkConstraintExprNode; w.u.aiCol = aiChng; sqlite3WalkExpr(&w, pExpr); if( !chngRowid ){ testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); w.eCode &= ~CKCNSTRNT_ROWID; } testcase( w.eCode==0 ); testcase( w.eCode==CKCNSTRNT_COLUMN ); testcase( w.eCode==CKCNSTRNT_ROWID ); testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); return !w.eCode; } /* ** Generate code to do constraint checks prior to an INSERT or an UPDATE ** on table pTab. ** ** The regNewData parameter is the first register in a range that contains ** the data to be inserted or the data after the update. There will be ** pTab->nCol+1 registers in this range. The first register (the one ** that regNewData points to) will contain the new rowid, or NULL in the ** case of a WITHOUT ROWID table. The second register in the range will ** contain the content of the first table column. The third register will ** contain the content of the second table column. And so forth. ** ** The regOldData parameter is similar to regNewData except that it contains ** the data prior to an UPDATE rather than afterwards. regOldData is zero ** for an INSERT. This routine can distinguish between UPDATE and INSERT by ** checking regOldData for zero. ** ** For an UPDATE, the pkChng boolean is true if the true primary key (the ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) ** might be modified by the UPDATE. If pkChng is false, then the key of ** the iDataCur content table is guaranteed to be unchanged by the UPDATE. ** ** For an INSERT, the pkChng boolean indicates whether or not the rowid ** was explicitly specified as part of the INSERT statement. If pkChng ** is zero, it means that the either rowid is computed automatically or ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, ** pkChng will only be true if the INSERT statement provides an integer ** value for either the rowid column or its INTEGER PRIMARY KEY alias. ** ** The code generated by this routine will store new index entries into ** registers identified by aRegIdx[]. No index entry is created for ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is ** the same as the order of indices on the linked list of indices ** at pTab->pIndex. ** ** The caller must have already opened writeable cursors on the main ** table and all applicable indices (that is to say, all indices for which ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor ** for the first index in the pTab->pIndex list. Cursors for other indices ** are at iIdxCur+N for the N-th element of the pTab->pIndex list. ** ** This routine also generates code to check constraints. NOT NULL, ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, ** then the appropriate action is performed. There are five possible ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. ** ** Constraint type Action What Happens ** --------------- ---------- ---------------------------------------- ** any ROLLBACK The current transaction is rolled back and ** sqlite3_step() returns immediately with a ** return code of SQLITE_CONSTRAINT. ** ** any ABORT Back out changes from the current command ** only (do not do a complete rollback) then ** cause sqlite3_step() to return immediately ** with SQLITE_CONSTRAINT. ** ** any FAIL Sqlite3_step() returns immediately with a ** return code of SQLITE_CONSTRAINT. The ** transaction is not rolled back and any ** changes to prior rows are retained. ** ** any IGNORE The attempt in insert or update the current ** row is skipped, without throwing an error. ** Processing continues with the next row. ** (There is an immediate jump to ignoreDest.) ** ** NOT NULL REPLACE The NULL value is replace by the default ** value for that column. If the default value ** is NULL, the action is the same as ABORT. ** ** UNIQUE REPLACE The other row that conflicts with the row ** being inserted is removed. ** ** CHECK REPLACE Illegal. The results in an exception. ** ** Which action to take is determined by the overrideError parameter. ** Or if overrideError==OE_Default, then the pParse->onError parameter ** is used. Or if pParse->onError==OE_Default then the onError value ** for the constraint is used. */ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( Parse *pParse, /* The parser context */ Table *pTab, /* The table being inserted or updated */ int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ int iDataCur, /* Canonical data cursor (main table or PK index) */ int iIdxCur, /* First index cursor */ int regNewData, /* First register in a range holding values to insert */ int regOldData, /* Previous content. 0 for INSERTs */ u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ u8 overrideError, /* Override onError to this if not OE_Default */ int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ int *aiChng /* column i is unchanged if aiChng[i]<0 */ ){ Vdbe *v; /* VDBE under constrution */ Index *pIdx; /* Pointer to one of the indices */ Index *pPk = 0; /* The PRIMARY KEY index */ sqlite3 *db; /* Database connection */ int i; /* loop counter */ int ix; /* Index loop counter */ int nCol; /* Number of columns */ int onError; /* Conflict resolution strategy */ int addr1; /* Address of jump instruction */ int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ int ipkTop = 0; /* Top of the rowid change constraint check */ int ipkBottom = 0; /* Bottom of the rowid change constraint check */ u8 isUpdate; /* True if this is an UPDATE operation */ u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ isUpdate = regOldData!=0; db = pParse->db; v = sqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ nCol = pTab->nCol; /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for ** normal rowid tables. nPkField is the number of key fields in the ** pPk index or 1 for a rowid table. In other words, nPkField is the ** number of fields in the true primary key of the table. */ if( HasRowid(pTab) ){ pPk = 0; nPkField = 1; }else{ pPk = sqlite3PrimaryKeyIndex(pTab); nPkField = pPk->nKeyCol; } /* Record that this module has started */ VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", iDataCur, iIdxCur, regNewData, regOldData, pkChng)); /* Test all NOT NULL constraints. */ for(i=0; i<nCol; i++){ if( i==pTab->iPKey ){ continue; /* ROWID is never NULL */ } if( aiChng && aiChng[i]<0 ){ /* Don't bother checking for NOT NULL on columns that do not change */ continue; } onError = pTab->aCol[i].notNull; if( onError==OE_None ) continue; /* This column is allowed to be NULL */ if( overrideError!=OE_Default ){ onError = overrideError; }else if( onError==OE_Default ){ onError = OE_Abort; } if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ onError = OE_Abort; } assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail || onError==OE_Ignore || onError==OE_Replace ); switch( onError ){ case OE_Abort: sqlite3MayAbort(pParse); /* Fall through */ case OE_Rollback: case OE_Fail: { char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, pTab->aCol[i].zName); sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, regNewData+1+i); sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); VdbeCoverage(v); break; } case OE_Ignore: { sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); VdbeCoverage(v); break; } default: { assert( onError==OE_Replace ); addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v); sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); sqlite3VdbeJumpHere(v, addr1); break; } } } /* Test all CHECK constraints */ #ifndef SQLITE_OMIT_CHECK if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ ExprList *pCheck = pTab->pCheck; pParse->ckBase = regNewData+1; onError = overrideError!=OE_Default ? overrideError : OE_Abort; for(i=0; i<pCheck->nExpr; i++){ int allOk; Expr *pExpr = pCheck->a[i].pExpr; if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue; allOk = sqlite3VdbeMakeLabel(v); sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); if( onError==OE_Ignore ){ sqlite3VdbeGoto(v, ignoreDest); }else{ char *zName = pCheck->a[i].zName; if( zName==0 ) zName = pTab->zName; if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, onError, zName, P4_TRANSIENT, P5_ConstraintCheck); } sqlite3VdbeResolveLabel(v, allOk); } } #endif /* !defined(SQLITE_OMIT_CHECK) */ /* If rowid is changing, make sure the new rowid does not previously ** exist in the table. */ if( pkChng && pPk==0 ){ int addrRowidOk = sqlite3VdbeMakeLabel(v); /* Figure out what action to take in case of a rowid collision */ onError = pTab->keyConf; if( overrideError!=OE_Default ){ onError = overrideError; }else if( onError==OE_Default ){ onError = OE_Abort; } if( isUpdate ){ /* pkChng!=0 does not mean that the rowid has changed, only that ** it might have changed. Skip the conflict logic below if the rowid ** is unchanged. */ sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v); } /* If the response to a rowid conflict is REPLACE but the response ** to some other UNIQUE constraint is FAIL or IGNORE, then we need ** to defer the running of the rowid conflict checking until after ** the UNIQUE constraints have run. */ if( onError==OE_Replace && overrideError!=OE_Replace ){ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); break; } } } /* Check to see if the new rowid already exists in the table. Skip ** the following conflict logic if it does not. */ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); VdbeCoverage(v); /* Generate code that deals with a rowid collision */ switch( onError ){ default: { onError = OE_Abort; /* Fall thru into the next case */ } case OE_Rollback: case OE_Abort: case OE_Fail: { sqlite3RowidConstraint(pParse, onError, pTab); break; } case OE_Replace: { /* If there are DELETE triggers on this table and the ** recursive-triggers flag is set, call GenerateRowDelete() to ** remove the conflicting row from the table. This will fire ** the triggers and remove both the table and index b-tree entries. ** ** Otherwise, if there are no triggers or the recursive-triggers ** flag is not set, but the table has one or more indexes, call ** GenerateRowIndexDelete(). This removes the index b-tree entries ** only. The table b-tree entry will be replaced by the new entry ** when it is inserted. ** ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, ** also invoke MultiWrite() to indicate that this VDBE may require ** statement rollback (if the statement is aborted after the delete ** takes place). Earlier versions called sqlite3MultiWrite() regardless, ** but being more selective here allows statements like: ** ** REPLACE INTO t(rowid) VALUES($newrowid) ** ** to run without a statement journal if there are no indexes on the ** table. */ Trigger *pTrigger = 0; if( db->flags&SQLITE_RecTriggers ){ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); } if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ sqlite3MultiWrite(pParse); sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, regNewData, 1, 0, OE_Replace, 1, -1); }else{ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( HasRowid(pTab) ){ /* This OP_Delete opcode fires the pre-update-hook only. It does ** not modify the b-tree. It is more efficient to let the coming ** OP_Insert replace the existing entry than it is to delete the ** existing entry and then insert a new one. */ sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); sqlite3VdbeAppendP4(v, pTab, P4_TABLE); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ if( pTab->pIndex ){ sqlite3MultiWrite(pParse); sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); } } seenReplace = 1; break; } case OE_Ignore: { /*assert( seenReplace==0 );*/ sqlite3VdbeGoto(v, ignoreDest); break; } } sqlite3VdbeResolveLabel(v, addrRowidOk); if( ipkTop ){ ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); sqlite3VdbeJumpHere(v, ipkTop); } } /* Test all UNIQUE constraints by creating entries for each UNIQUE ** index and making sure that duplicate entries do not already exist. ** Compute the revised record entries for indices as we go. ** ** This loop also handles the case of the PRIMARY KEY index for a ** WITHOUT ROWID table. */ for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ int regIdx; /* Range of registers hold conent for pIdx */ int regR; /* Range of registers holding conflicting PK */ int iThisCur; /* Cursor for this UNIQUE index */ int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ if( bAffinityDone==0 ){ sqlite3TableAffinity(v, pTab, regNewData+1); bAffinityDone = 1; } iThisCur = iIdxCur+ix; addrUniqueOk = sqlite3VdbeMakeLabel(v); /* Skip partial indices for which the WHERE clause is not true */ if( pIdx->pPartIdxWhere ){ sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); pParse->ckBase = regNewData+1; sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, SQLITE_JUMPIFNULL); pParse->ckBase = 0; } /* Create a record for this index entry as it should appear after ** the insert or update. Store that record in the aRegIdx[ix] register */ regIdx = aRegIdx[ix]+1; for(i=0; i<pIdx->nColumn; i++){ int iField = pIdx->aiColumn[i]; int x; if( iField==XN_EXPR ){ pParse->ckBase = regNewData+1; sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); pParse->ckBase = 0; VdbeComment((v, "%s column %d", pIdx->zName, i)); }else{ if( iField==XN_ROWID || iField==pTab->iPKey ){ x = regNewData; }else{ x = iField + regNewData + 1; } sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i); VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); } } sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); VdbeComment((v, "for %s", pIdx->zName)); /* In an UPDATE operation, if this index is the PRIMARY KEY index ** of a WITHOUT ROWID table and there has been no change the ** primary key, then no collision is possible. The collision detection ** logic below can all be skipped. */ if( isUpdate && pPk==pIdx && pkChng==0 ){ sqlite3VdbeResolveLabel(v, addrUniqueOk); continue; } /* Find out what action to take in case there is a uniqueness conflict */ onError = pIdx->onError; if( onError==OE_None ){ sqlite3VdbeResolveLabel(v, addrUniqueOk); continue; /* pIdx is not a UNIQUE index */ } if( overrideError!=OE_Default ){ onError = overrideError; }else if( onError==OE_Default ){ onError = OE_Abort; } /* Collision detection may be omitted if all of the following are true: ** (1) The conflict resolution algorithm is REPLACE ** (2) The table is a WITHOUT ROWID table ** (3) There are no secondary indexes on the table ** (4) No delete triggers need to be fired if there is a conflict ** (5) No FK constraint counters need to be updated if a conflict occurs. */ if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ && pPk==pIdx /* Condition 2 */ && onError==OE_Replace /* Condition 1 */ && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ (0==pTab->pFKey && 0==sqlite3FkReferences(pTab))) ){ sqlite3VdbeResolveLabel(v, addrUniqueOk); continue; } /* Check to see if the new index entry will be unique */ sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, regIdx, pIdx->nKeyCol); VdbeCoverage(v); /* Generate code to handle collisions */ regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); if( isUpdate || onError==OE_Replace ){ if( HasRowid(pTab) ){ sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); /* Conflict only if the rowid of the existing index entry ** is different from old-rowid */ if( isUpdate ){ sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v); } }else{ int x; /* Extract the PRIMARY KEY from the end of the index entry and ** store it in registers regR..regR+nPk-1 */ if( pIdx!=pPk ){ for(i=0; i<pPk->nKeyCol; i++){ assert( pPk->aiColumn[i]>=0 ); x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); VdbeComment((v, "%s.%s", pTab->zName, pTab->aCol[pPk->aiColumn[i]].zName)); } } if( isUpdate ){ /* If currently processing the PRIMARY KEY of a WITHOUT ROWID ** table, only conflict if the new PRIMARY KEY values are actually ** different from the old. ** ** For a UNIQUE index, only conflict if the PRIMARY KEY values ** of the matched index row are different from the original PRIMARY ** KEY values of this row before the update. */ int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; int op = OP_Ne; int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); for(i=0; i<pPk->nKeyCol; i++){ char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); x = pPk->aiColumn[i]; assert( x>=0 ); if( i==(pPk->nKeyCol-1) ){ addrJump = addrUniqueOk; op = OP_Eq; } sqlite3VdbeAddOp4(v, op, regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ ); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverageIf(v, op==OP_Eq); VdbeCoverageIf(v, op==OP_Ne); } } } } /* Generate code that executes if the new index entry is not unique */ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail || onError==OE_Ignore || onError==OE_Replace ); switch( onError ){ case OE_Rollback: case OE_Abort: case OE_Fail: { sqlite3UniqueConstraint(pParse, onError, pIdx); break; } case OE_Ignore: { sqlite3VdbeGoto(v, ignoreDest); break; } default: { Trigger *pTrigger = 0; assert( onError==OE_Replace ); sqlite3MultiWrite(pParse); if( db->flags&SQLITE_RecTriggers ){ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); } sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, regR, nPkField, 0, OE_Replace, (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); seenReplace = 1; break; } } sqlite3VdbeResolveLabel(v, addrUniqueOk); if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); } if( ipkTop ){ sqlite3VdbeGoto(v, ipkTop+1); sqlite3VdbeJumpHere(v, ipkBottom); } *pbMayReplace = seenReplace; VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); } #ifdef SQLITE_ENABLE_NULL_TRIM /* ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord) ** to be the number of columns in table pTab that must not be NULL-trimmed. ** ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero. */ SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){ u16 i; /* Records with omitted columns are only allowed for schema format ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */ if( pTab->pSchema->file_format<2 ) return; for(i=pTab->nCol; i>1 && pTab->aCol[i-1].pDflt==0; i--){} sqlite3VdbeChangeP5(v, i); } #endif /* ** This routine generates code to finish the INSERT or UPDATE operation ** that was started by a prior call to sqlite3GenerateConstraintChecks. ** A consecutive range of registers starting at regNewData contains the ** rowid and the content to be inserted. ** ** The arguments to this routine should be the same as the first six ** arguments to sqlite3GenerateConstraintChecks. */ SQLITE_PRIVATE void sqlite3CompleteInsertion( Parse *pParse, /* The parser context */ Table *pTab, /* the table into which we are inserting */ int iDataCur, /* Cursor of the canonical data source */ int iIdxCur, /* First index cursor */ int regNewData, /* Range of content */ int *aRegIdx, /* Register used by each index. 0 for unused indices */ int update_flags, /* True for UPDATE, False for INSERT */ int appendBias, /* True if this is likely to be an append */ int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ ){ Vdbe *v; /* Prepared statements under construction */ Index *pIdx; /* An index being inserted or updated */ u8 pik_flags; /* flag values passed to the btree insert */ int regData; /* Content registers (after the rowid) */ int regRec; /* Register holding assembled record for the table */ int i; /* Loop counter */ u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ assert( update_flags==0 || update_flags==OPFLAG_ISUPDATE || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION) ); v = sqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ if( aRegIdx[i]==0 ) continue; bAffinityDone = 1; if( pIdx->pPartIdxWhere ){ sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); } pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0); if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ assert( pParse->nested==0 ); pik_flags |= OPFLAG_NCHANGE; pik_flags |= (update_flags & OPFLAG_SAVEPOSITION); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( update_flags==0 ){ sqlite3VdbeAddOp4(v, OP_InsertInt, iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE ); sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); } #endif } sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], aRegIdx[i]+1, pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); sqlite3VdbeChangeP5(v, pik_flags); } if( !HasRowid(pTab) ) return; regData = regNewData + 1; regRec = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); sqlite3SetMakeRecordP5(v, pTab); if( !bAffinityDone ){ sqlite3TableAffinity(v, pTab, 0); sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); } if( pParse->nested ){ pik_flags = 0; }else{ pik_flags = OPFLAG_NCHANGE; pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID); } if( appendBias ){ pik_flags |= OPFLAG_APPEND; } if( useSeekResult ){ pik_flags |= OPFLAG_USESEEKRESULT; } sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); if( !pParse->nested ){ sqlite3VdbeAppendP4(v, pTab, P4_TABLE); } sqlite3VdbeChangeP5(v, pik_flags); } /* ** Allocate cursors for the pTab table and all its indices and generate ** code to open and initialized those cursors. ** ** The cursor for the object that contains the complete data (normally ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT ** ROWID table) is returned in *piDataCur. The first index cursor is ** returned in *piIdxCur. The number of indices is returned. ** ** Use iBase as the first cursor (either the *piDataCur for rowid tables ** or the first index for WITHOUT ROWID tables) if it is non-negative. ** If iBase is negative, then allocate the next available cursor. ** ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the ** pTab->pIndex list. ** ** If pTab is a virtual table, then this routine is a no-op and the ** *piDataCur and *piIdxCur values are left uninitialized. */ SQLITE_PRIVATE int sqlite3OpenTableAndIndices( Parse *pParse, /* Parsing context */ Table *pTab, /* Table to be opened */ int op, /* OP_OpenRead or OP_OpenWrite */ u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ int iBase, /* Use this for the table cursor, if there is one */ u8 *aToOpen, /* If not NULL: boolean for each table and index */ int *piDataCur, /* Write the database source cursor number here */ int *piIdxCur /* Write the first index cursor number here */ ){ int i; int iDb; int iDataCur; Index *pIdx; Vdbe *v; assert( op==OP_OpenRead || op==OP_OpenWrite ); assert( op==OP_OpenWrite || p5==0 ); if( IsVirtual(pTab) ){ /* This routine is a no-op for virtual tables. Leave the output ** variables *piDataCur and *piIdxCur uninitialized so that valgrind ** can detect if they are used by mistake in the caller. */ return 0; } iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); v = sqlite3GetVdbe(pParse); assert( v!=0 ); if( iBase<0 ) iBase = pParse->nTab; iDataCur = iBase++; if( piDataCur ) *piDataCur = iDataCur; if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); }else{ sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); } if( piIdxCur ) *piIdxCur = iBase; for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ int iIdxCur = iBase++; assert( pIdx->pSchema==pTab->pSchema ); if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ if( piDataCur ) *piDataCur = iIdxCur; p5 = 0; } if( aToOpen==0 || aToOpen[i+1] ){ sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); sqlite3VdbeChangeP5(v, p5); VdbeComment((v, "%s", pIdx->zName)); } } if( iBase>pParse->nTab ) pParse->nTab = iBase; return i; } #ifdef SQLITE_TEST /* ** The following global variable is incremented whenever the ** transfer optimization is used. This is used for testing ** purposes only - to make sure the transfer optimization really ** is happening when it is supposed to. */ SQLITE_API int sqlite3_xferopt_count; #endif /* SQLITE_TEST */ #ifndef SQLITE_OMIT_XFER_OPT /* ** Check to see if index pSrc is compatible as a source of data ** for index pDest in an insert transfer optimization. The rules ** for a compatible index: ** ** * The index is over the same set of columns ** * The same DESC and ASC markings occurs on all columns ** * The same onError processing (OE_Abort, OE_Ignore, etc) ** * The same collating sequence on each column ** * The index has the exact same WHERE clause */ static int xferCompatibleIndex(Index *pDest, Index *pSrc){ int i; assert( pDest && pSrc ); assert( pDest->pTable!=pSrc->pTable ); if( pDest->nKeyCol!=pSrc->nKeyCol ){ return 0; /* Different number of columns */ } if( pDest->onError!=pSrc->onError ){ return 0; /* Different conflict resolution strategies */ } for(i=0; i<pSrc->nKeyCol; i++){ if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ return 0; /* Different columns indexed */ } if( pSrc->aiColumn[i]==XN_EXPR ){ assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr, pDest->aColExpr->a[i].pExpr, -1)!=0 ){ return 0; /* Different expressions in the index */ } } if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ return 0; /* Different sort orders */ } if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ return 0; /* Different collating sequences */ } } if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ return 0; /* Different WHERE clauses */ } /* If no test above fails then the indices must be compatible */ return 1; } /* ** Attempt the transfer optimization on INSERTs of the form ** ** INSERT INTO tab1 SELECT * FROM tab2; ** ** The xfer optimization transfers raw records from tab2 over to tab1. ** Columns are not decoded and reassembled, which greatly improves ** performance. Raw index records are transferred in the same way. ** ** The xfer optimization is only attempted if tab1 and tab2 are compatible. ** There are lots of rules for determining compatibility - see comments ** embedded in the code for details. ** ** This routine returns TRUE if the optimization is guaranteed to be used. ** Sometimes the xfer optimization will only work if the destination table ** is empty - a factor that can only be determined at run-time. In that ** case, this routine generates code for the xfer optimization but also ** does a test to see if the destination table is empty and jumps over the ** xfer optimization code if the test fails. In that case, this routine ** returns FALSE so that the caller will know to go ahead and generate ** an unoptimized transfer. This routine also returns FALSE if there ** is no chance that the xfer optimization can be applied. ** ** This optimization is particularly useful at making VACUUM run faster. */ static int xferOptimization( Parse *pParse, /* Parser context */ Table *pDest, /* The table we are inserting into */ Select *pSelect, /* A SELECT statement to use as the data source */ int onError, /* How to handle constraint errors */ int iDbDest /* The database of pDest */ ){ sqlite3 *db = pParse->db; ExprList *pEList; /* The result set of the SELECT */ Table *pSrc; /* The table in the FROM clause of SELECT */ Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ struct SrcList_item *pItem; /* An element of pSelect->pSrc */ int i; /* Loop counter */ int iDbSrc; /* The database of pSrc */ int iSrc, iDest; /* Cursors from source and destination */ int addr1, addr2; /* Loop addresses */ int emptyDestTest = 0; /* Address of test for empty pDest */ int emptySrcTest = 0; /* Address of test for empty pSrc */ Vdbe *v; /* The VDBE we are building */ int regAutoinc; /* Memory register used by AUTOINC */ int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ int regData, regRowid; /* Registers holding data and rowid */ if( pSelect==0 ){ return 0; /* Must be of the form INSERT INTO ... SELECT ... */ } if( pParse->pWith || pSelect->pWith ){ /* Do not attempt to process this query if there are an WITH clauses ** attached to it. Proceeding may generate a false "no such table: xxx" ** error if pSelect reads from a CTE named "xxx". */ return 0; } if( sqlite3TriggerList(pParse, pDest) ){ return 0; /* tab1 must not have triggers */ } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pDest->tabFlags & TF_Virtual ){ return 0; /* tab1 must not be a virtual table */ } #endif if( onError==OE_Default ){ if( pDest->iPKey>=0 ) onError = pDest->keyConf; if( onError==OE_Default ) onError = OE_Abort; } assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ if( pSelect->pSrc->nSrc!=1 ){ return 0; /* FROM clause must have exactly one term */ } if( pSelect->pSrc->a[0].pSelect ){ return 0; /* FROM clause cannot contain a subquery */ } if( pSelect->pWhere ){ return 0; /* SELECT may not have a WHERE clause */ } if( pSelect->pOrderBy ){ return 0; /* SELECT may not have an ORDER BY clause */ } /* Do not need to test for a HAVING clause. If HAVING is present but ** there is no ORDER BY, we will get an error. */ if( pSelect->pGroupBy ){ return 0; /* SELECT may not have a GROUP BY clause */ } if( pSelect->pLimit ){ return 0; /* SELECT may not have a LIMIT clause */ } assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ if( pSelect->pPrior ){ return 0; /* SELECT may not be a compound query */ } if( pSelect->selFlags & SF_Distinct ){ return 0; /* SELECT may not be DISTINCT */ } pEList = pSelect->pEList; assert( pEList!=0 ); if( pEList->nExpr!=1 ){ return 0; /* The result set must have exactly one column */ } assert( pEList->a[0].pExpr ); if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ return 0; /* The result set must be the special operator "*" */ } /* At this point we have established that the statement is of the ** correct syntactic form to participate in this optimization. Now ** we have to check the semantics. */ pItem = pSelect->pSrc->a; pSrc = sqlite3LocateTableItem(pParse, 0, pItem); if( pSrc==0 ){ return 0; /* FROM clause does not contain a real table */ } if( pSrc==pDest ){ return 0; /* tab1 and tab2 may not be the same table */ } if( HasRowid(pDest)!=HasRowid(pSrc) ){ return 0; /* source and destination must both be WITHOUT ROWID or not */ } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pSrc->tabFlags & TF_Virtual ){ return 0; /* tab2 must not be a virtual table */ } #endif if( pSrc->pSelect ){ return 0; /* tab2 may not be a view */ } if( pDest->nCol!=pSrc->nCol ){ return 0; /* Number of columns must be the same in tab1 and tab2 */ } if( pDest->iPKey!=pSrc->iPKey ){ return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ } for(i=0; i<pDest->nCol; i++){ Column *pDestCol = &pDest->aCol[i]; Column *pSrcCol = &pSrc->aCol[i]; #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS if( (db->flags & SQLITE_Vacuum)==0 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN ){ return 0; /* Neither table may have __hidden__ columns */ } #endif if( pDestCol->affinity!=pSrcCol->affinity ){ return 0; /* Affinity must be the same on all columns */ } if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ return 0; /* Collating sequence must be the same on all columns */ } if( pDestCol->notNull && !pSrcCol->notNull ){ return 0; /* tab2 must be NOT NULL if tab1 is */ } /* Default values for second and subsequent columns need to match. */ if( i>0 ){ assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, pSrcCol->pDflt->u.zToken)!=0) ){ return 0; /* Default values must be the same for all columns */ } } } for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ if( IsUniqueIndex(pDestIdx) ){ destHasUniqueIdx = 1; } for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; } if( pSrcIdx==0 ){ return 0; /* pDestIdx has no corresponding index in pSrc */ } } #ifndef SQLITE_OMIT_CHECK if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ return 0; /* Tables have different CHECK constraints. Ticket #2252 */ } #endif #ifndef SQLITE_OMIT_FOREIGN_KEY /* Disallow the transfer optimization if the destination table constains ** any foreign key constraints. This is more restrictive than necessary. ** But the main beneficiary of the transfer optimization is the VACUUM ** command, and the VACUUM command disables foreign key constraints. So ** the extra complication to make this rule less restrictive is probably ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] */ if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ return 0; } #endif if( (db->flags & SQLITE_CountRows)!=0 ){ return 0; /* xfer opt does not play well with PRAGMA count_changes */ } /* If we get this far, it means that the xfer optimization is at ** least a possibility, though it might only work if the destination ** table (tab1) is initially empty. */ #ifdef SQLITE_TEST sqlite3_xferopt_count++; #endif iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); v = sqlite3GetVdbe(pParse); sqlite3CodeVerifySchema(pParse, iDbSrc); iSrc = pParse->nTab++; iDest = pParse->nTab++; regAutoinc = autoIncBegin(pParse, iDbDest, pDest); regData = sqlite3GetTempReg(pParse); regRowid = sqlite3GetTempReg(pParse); sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); assert( HasRowid(pDest) || destHasUniqueIdx ); if( (db->flags & SQLITE_Vacuum)==0 && ( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ || destHasUniqueIdx /* (2) */ || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ )){ /* In some circumstances, we are able to run the xfer optimization ** only if the destination table is initially empty. Unless the ** SQLITE_Vacuum flag is set, this block generates code to make ** that determination. If SQLITE_Vacuum is set, then the destination ** table is always empty. ** ** Conditions under which the destination must be empty: ** ** (1) There is no INTEGER PRIMARY KEY but there are indices. ** (If the destination is not initially empty, the rowid fields ** of index entries might need to change.) ** ** (2) The destination has a unique index. (The xfer optimization ** is unable to test uniqueness.) ** ** (3) onError is something other than OE_Abort and OE_Rollback. */ addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); sqlite3VdbeJumpHere(v, addr1); } if( HasRowid(pSrc) ){ u8 insFlags; sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); if( pDest->iPKey>=0 ){ addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); VdbeCoverage(v); sqlite3RowidConstraint(pParse, onError, pDest); sqlite3VdbeJumpHere(v, addr2); autoIncStep(pParse, regAutoinc, regRowid); }else if( pDest->pIndex==0 ){ addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); }else{ addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); assert( (pDest->tabFlags & TF_Autoincrement)==0 ); } sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); if( db->flags & SQLITE_Vacuum ){ sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID| OPFLAG_APPEND|OPFLAG_USESEEKRESULT; }else{ insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; } sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, (char*)pDest, P4_TABLE); sqlite3VdbeChangeP5(v, insFlags); sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); }else{ sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); } for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ u8 idxInsFlags = 0; for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; } assert( pSrcIdx ); sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); VdbeComment((v, "%s", pSrcIdx->zName)); sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); VdbeComment((v, "%s", pDestIdx->zName)); addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); if( db->flags & SQLITE_Vacuum ){ /* This INSERT command is part of a VACUUM operation, which guarantees ** that the destination table is empty. If all indexed columns use ** collation sequence BINARY, then it can also be assumed that the ** index will be populated by inserting keys in strictly sorted ** order. In this case, instead of seeking within the b-tree as part ** of every OP_IdxInsert opcode, an OP_Last is added before the ** OP_IdxInsert to seek to the point within the b-tree where each key ** should be inserted. This is faster. ** ** If any of the indexed columns use a collation sequence other than ** BINARY, this optimization is disabled. This is because the user ** might change the definition of a collation sequence and then run ** a VACUUM command. In that case keys may not be written in strictly ** sorted order. */ for(i=0; i<pSrcIdx->nColumn; i++){ const char *zColl = pSrcIdx->azColl[i]; assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0 || sqlite3StrBINARY==zColl ); if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; } if( i==pSrcIdx->nColumn ){ idxInsFlags = OPFLAG_USESEEKRESULT; sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); } } if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ idxInsFlags |= OPFLAG_NCHANGE; } sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); } if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); sqlite3ReleaseTempReg(pParse, regRowid); sqlite3ReleaseTempReg(pParse, regData); if( emptyDestTest ){ sqlite3AutoincrementEnd(pParse); sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); sqlite3VdbeJumpHere(v, emptyDestTest); sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); return 0; }else{ return 1; } } #endif /* SQLITE_OMIT_XFER_OPT */ /************** End of insert.c **********************************************/ /************** Begin file legacy.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. */ /* #include "sqliteInt.h" */ /* ** Execute SQL code. Return one of the SQLITE_ success/failure ** codes. Also write an error message into memory obtained from ** malloc() and make *pzErrMsg point to that message. ** ** If the SQL is a query, then for each row in the query result ** the xCallback() function is called. pArg becomes the first ** argument to xCallback(). If xCallback=NULL then no callback ** is invoked, even for queries. */ SQLITE_API int sqlite3_exec( sqlite3 *db, /* The database on which the SQL executes */ const char *zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ void *pArg, /* First argument to xCallback() */ char **pzErrMsg /* Write error messages here */ ){ int rc = SQLITE_OK; /* Return code */ const char *zLeftover; /* Tail of unprocessed SQL */ sqlite3_stmt *pStmt = 0; /* The current SQL statement */ char **azCols = 0; /* Names of result columns */ int callbackIsInit; /* True if callback data is initialized */ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; if( zSql==0 ) zSql = ""; sqlite3_mutex_enter(db->mutex); sqlite3Error(db, SQLITE_OK); while( rc==SQLITE_OK && zSql[0] ){ int nCol; char **azVals = 0; pStmt = 0; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); assert( rc==SQLITE_OK || pStmt==0 ); if( rc!=SQLITE_OK ){ continue; } if( !pStmt ){ /* this happens for a comment or white-space */ zSql = zLeftover; continue; } callbackIsInit = 0; nCol = sqlite3_column_count(pStmt); while( 1 ){ int i; rc = sqlite3_step(pStmt); /* Invoke the callback function if required */ if( xCallback && (SQLITE_ROW==rc || (SQLITE_DONE==rc && !callbackIsInit && db->flags&SQLITE_NullCallback)) ){ if( !callbackIsInit ){ azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); if( azCols==0 ){ goto exec_out; } for(i=0; i<nCol; i++){ azCols[i] = (char *)sqlite3_column_name(pStmt, i); /* sqlite3VdbeSetColName() installs column names as UTF8 ** strings so there is no way for sqlite3_column_name() to fail. */ assert( azCols[i]!=0 ); } callbackIsInit = 1; } if( rc==SQLITE_ROW ){ azVals = &azCols[nCol]; for(i=0; i<nCol; i++){ azVals[i] = (char *)sqlite3_column_text(pStmt, i); if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){ sqlite3OomFault(db); goto exec_out; } } } if( xCallback(pArg, nCol, azVals, azCols) ){ /* EVIDENCE-OF: R-38229-40159 If the callback function to ** sqlite3_exec() returns non-zero, then sqlite3_exec() will ** return SQLITE_ABORT. */ rc = SQLITE_ABORT; sqlite3VdbeFinalize((Vdbe *)pStmt); pStmt = 0; sqlite3Error(db, SQLITE_ABORT); goto exec_out; } } if( rc!=SQLITE_ROW ){ rc = sqlite3VdbeFinalize((Vdbe *)pStmt); pStmt = 0; zSql = zLeftover; while( sqlite3Isspace(zSql[0]) ) zSql++; break; } } sqlite3DbFree(db, azCols); azCols = 0; } exec_out: if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt); sqlite3DbFree(db, azCols); rc = sqlite3ApiExit(db, rc); if( rc!=SQLITE_OK && pzErrMsg ){ int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db)); *pzErrMsg = sqlite3Malloc(nErrMsg); if( *pzErrMsg ){ memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg); }else{ rc = SQLITE_NOMEM_BKPT; sqlite3Error(db, SQLITE_NOMEM); } }else if( pzErrMsg ){ *pzErrMsg = 0; } assert( (rc&db->errMask)==rc ); sqlite3_mutex_leave(db->mutex); return rc; } /************** End of legacy.c **********************************************/ /************** Begin file loadext.c *****************************************/ /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to dynamically load extensions into ** the SQLite library. */ #ifndef SQLITE_CORE #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ #endif /************** Include sqlite3ext.h in the middle of loadext.c **************/ /************** Begin file sqlite3ext.h **************************************/ /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the SQLite interface for use by ** shared libraries that want to be imported as extensions into ** an SQLite instance. Shared libraries that intend to be loaded ** as extensions by SQLite should #include this file instead of ** sqlite3.h. */ #ifndef SQLITE3EXT_H #define SQLITE3EXT_H /* #include "sqlite3.h" */ /* ** The following structure holds pointers to all of the SQLite API ** routines. ** ** WARNING: In order to maintain backwards compatibility, add new ** interfaces to the end of this structure only. If you insert new ** interfaces in the middle of this structure, then older different ** versions of SQLite will not be able to load each other's shared ** libraries! */ struct sqlite3_api_routines { void * (*aggregate_context)(sqlite3_context*,int nBytes); int (*aggregate_count)(sqlite3_context*); int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); int (*bind_double)(sqlite3_stmt*,int,double); int (*bind_int)(sqlite3_stmt*,int,int); int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); int (*bind_null)(sqlite3_stmt*,int); int (*bind_parameter_count)(sqlite3_stmt*); int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); const char * (*bind_parameter_name)(sqlite3_stmt*,int); int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); int (*busy_timeout)(sqlite3*,int ms); int (*changes)(sqlite3*); int (*close)(sqlite3*); int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, int eTextRep,const char*)); int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, int eTextRep,const void*)); const void * (*column_blob)(sqlite3_stmt*,int iCol); int (*column_bytes)(sqlite3_stmt*,int iCol); int (*column_bytes16)(sqlite3_stmt*,int iCol); int (*column_count)(sqlite3_stmt*pStmt); const char * (*column_database_name)(sqlite3_stmt*,int); const void * (*column_database_name16)(sqlite3_stmt*,int); const char * (*column_decltype)(sqlite3_stmt*,int i); const void * (*column_decltype16)(sqlite3_stmt*,int); double (*column_double)(sqlite3_stmt*,int iCol); int (*column_int)(sqlite3_stmt*,int iCol); sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); const char * (*column_name)(sqlite3_stmt*,int); const void * (*column_name16)(sqlite3_stmt*,int); const char * (*column_origin_name)(sqlite3_stmt*,int); const void * (*column_origin_name16)(sqlite3_stmt*,int); const char * (*column_table_name)(sqlite3_stmt*,int); const void * (*column_table_name16)(sqlite3_stmt*,int); const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); const void * (*column_text16)(sqlite3_stmt*,int iCol); int (*column_type)(sqlite3_stmt*,int iCol); sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); void * (*commit_hook)(sqlite3*,int(*)(void*),void*); int (*complete)(const char*sql); int (*complete16)(const void*sql); int (*create_collation)(sqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*)); int (*create_collation16)(sqlite3*,const void*,int,void*, int(*)(void*,int,const void*,int,const void*)); int (*create_function)(sqlite3*,const char*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*)); int (*create_function16)(sqlite3*,const void*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*)); int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); int (*data_count)(sqlite3_stmt*pStmt); sqlite3 * (*db_handle)(sqlite3_stmt*); int (*declare_vtab)(sqlite3*,const char*); int (*enable_shared_cache)(int); int (*errcode)(sqlite3*db); const char * (*errmsg)(sqlite3*); const void * (*errmsg16)(sqlite3*); int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); int (*expired)(sqlite3_stmt*); int (*finalize)(sqlite3_stmt*pStmt); void (*free)(void*); void (*free_table)(char**result); int (*get_autocommit)(sqlite3*); void * (*get_auxdata)(sqlite3_context*,int); int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); int (*global_recover)(void); void (*interruptx)(sqlite3*); sqlite_int64 (*last_insert_rowid)(sqlite3*); const char * (*libversion)(void); int (*libversion_number)(void); void *(*malloc)(int); char * (*mprintf)(const char*,...); int (*open)(const char*,sqlite3**); int (*open16)(const void*,sqlite3**); int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); void *(*realloc)(void*,int); int (*reset)(sqlite3_stmt*pStmt); void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_double)(sqlite3_context*,double); void (*result_error)(sqlite3_context*,const char*,int); void (*result_error16)(sqlite3_context*,const void*,int); void (*result_int)(sqlite3_context*,int); void (*result_int64)(sqlite3_context*,sqlite_int64); void (*result_null)(sqlite3_context*); void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_value)(sqlite3_context*,sqlite3_value*); void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, const char*,const char*),void*); void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); char * (*snprintf)(int,char*,const char*,...); int (*step)(sqlite3_stmt*); int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, char const**,char const**,int*,int*,int*); void (*thread_cleanup)(void); int (*total_changes)(sqlite3*); void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, sqlite_int64),void*); void * (*user_data)(sqlite3_context*); const void * (*value_blob)(sqlite3_value*); int (*value_bytes)(sqlite3_value*); int (*value_bytes16)(sqlite3_value*); double (*value_double)(sqlite3_value*); int (*value_int)(sqlite3_value*); sqlite_int64 (*value_int64)(sqlite3_value*); int (*value_numeric_type)(sqlite3_value*); const unsigned char * (*value_text)(sqlite3_value*); const void * (*value_text16)(sqlite3_value*); const void * (*value_text16be)(sqlite3_value*); const void * (*value_text16le)(sqlite3_value*); int (*value_type)(sqlite3_value*); char *(*vmprintf)(const char*,va_list); /* Added ??? */ int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); /* Added by 3.3.13 */ int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); int (*clear_bindings)(sqlite3_stmt*); /* Added by 3.4.1 */ int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, void (*xDestroy)(void *)); /* Added by 3.5.0 */ int (*bind_zeroblob)(sqlite3_stmt*,int,int); int (*blob_bytes)(sqlite3_blob*); int (*blob_close)(sqlite3_blob*); int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, int,sqlite3_blob**); int (*blob_read)(sqlite3_blob*,void*,int,int); int (*blob_write)(sqlite3_blob*,const void*,int,int); int (*create_collation_v2)(sqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*), void(*)(void*)); int (*file_control)(sqlite3*,const char*,int,void*); sqlite3_int64 (*memory_highwater)(int); sqlite3_int64 (*memory_used)(void); sqlite3_mutex *(*mutex_alloc)(int); void (*mutex_enter)(sqlite3_mutex*); void (*mutex_free)(sqlite3_mutex*); void (*mutex_leave)(sqlite3_mutex*); int (*mutex_try)(sqlite3_mutex*); int (*open_v2)(const char*,sqlite3**,int,const char*); int (*release_memory)(int); void (*result_error_nomem)(sqlite3_context*); void (*result_error_toobig)(sqlite3_context*); int (*sleep)(int); void (*soft_heap_limit)(int); sqlite3_vfs *(*vfs_find)(const char*); int (*vfs_register)(sqlite3_vfs*,int); int (*vfs_unregister)(sqlite3_vfs*); int (*xthreadsafe)(void); void (*result_zeroblob)(sqlite3_context*,int); void (*result_error_code)(sqlite3_context*,int); int (*test_control)(int, ...); void (*randomness)(int,void*); sqlite3 *(*context_db_handle)(sqlite3_context*); int (*extended_result_codes)(sqlite3*,int); int (*limit)(sqlite3*,int,int); sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); const char *(*sql)(sqlite3_stmt*); int (*status)(int,int*,int*,int); int (*backup_finish)(sqlite3_backup*); sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); int (*backup_pagecount)(sqlite3_backup*); int (*backup_remaining)(sqlite3_backup*); int (*backup_step)(sqlite3_backup*,int); const char *(*compileoption_get)(int); int (*compileoption_used)(const char*); int (*create_function_v2)(sqlite3*,const char*,int,int,void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*)); int (*db_config)(sqlite3*,int,...); sqlite3_mutex *(*db_mutex)(sqlite3*); int (*db_status)(sqlite3*,int,int*,int*,int); int (*extended_errcode)(sqlite3*); void (*log)(int,const char*,...); sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); const char *(*sourceid)(void); int (*stmt_status)(sqlite3_stmt*,int,int); int (*strnicmp)(const char*,const char*,int); int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); int (*wal_autocheckpoint)(sqlite3*,int); int (*wal_checkpoint)(sqlite3*,const char*); void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); int (*vtab_config)(sqlite3*,int op,...); int (*vtab_on_conflict)(sqlite3*); /* Version 3.7.16 and later */ int (*close_v2)(sqlite3*); const char *(*db_filename)(sqlite3*,const char*); int (*db_readonly)(sqlite3*,const char*); int (*db_release_memory)(sqlite3*); const char *(*errstr)(int); int (*stmt_busy)(sqlite3_stmt*); int (*stmt_readonly)(sqlite3_stmt*); int (*stricmp)(const char*,const char*); int (*uri_boolean)(const char*,const char*,int); sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); const char *(*uri_parameter)(const char*,const char*); char *(*vsnprintf)(int,char*,const char*,va_list); int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); /* Version 3.8.7 and later */ int (*auto_extension)(void(*)(void)); int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64, void(*)(void*)); int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64, void(*)(void*),unsigned char); int (*cancel_auto_extension)(void(*)(void)); int (*load_extension)(sqlite3*,const char*,const char*,char**); void *(*malloc64)(sqlite3_uint64); sqlite3_uint64 (*msize)(void*); void *(*realloc64)(void*,sqlite3_uint64); void (*reset_auto_extension)(void); void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64, void(*)(void*)); void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64, void(*)(void*), unsigned char); int (*strglob)(const char*,const char*); /* Version 3.8.11 and later */ sqlite3_value *(*value_dup)(const sqlite3_value*); void (*value_free)(sqlite3_value*); int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64); int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64); /* Version 3.9.0 and later */ unsigned int (*value_subtype)(sqlite3_value*); void (*result_subtype)(sqlite3_context*,unsigned int); /* Version 3.10.0 and later */ int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int); int (*strlike)(const char*,const char*,unsigned int); int (*db_cacheflush)(sqlite3*); /* Version 3.12.0 and later */ int (*system_errno)(sqlite3*); /* Version 3.14.0 and later */ int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); char *(*expanded_sql)(sqlite3_stmt*); }; /* ** This is the function signature used for all extension entry points. It ** is also defined in the file "loadext.c". */ typedef int (*sqlite3_loadext_entry)( sqlite3 *db, /* Handle to the database. */ char **pzErrMsg, /* Used to set error string on failure. */ const sqlite3_api_routines *pThunk /* Extension API function pointers. */ ); /* ** The following macros redefine the API routines so that they are ** redirected through the global sqlite3_api structure. ** ** This header file is also used by the loadext.c source file ** (part of the main SQLite library - not an extension) so that ** it can get access to the sqlite3_api_routines structure ** definition. But the main library does not want to redefine ** the API. So the redefinition macros are only valid if the ** SQLITE_CORE macros is undefined. */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) #define sqlite3_aggregate_context sqlite3_api->aggregate_context #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_aggregate_count sqlite3_api->aggregate_count #endif #define sqlite3_bind_blob sqlite3_api->bind_blob #define sqlite3_bind_double sqlite3_api->bind_double #define sqlite3_bind_int sqlite3_api->bind_int #define sqlite3_bind_int64 sqlite3_api->bind_int64 #define sqlite3_bind_null sqlite3_api->bind_null #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name #define sqlite3_bind_text sqlite3_api->bind_text #define sqlite3_bind_text16 sqlite3_api->bind_text16 #define sqlite3_bind_value sqlite3_api->bind_value #define sqlite3_busy_handler sqlite3_api->busy_handler #define sqlite3_busy_timeout sqlite3_api->busy_timeout #define sqlite3_changes sqlite3_api->changes #define sqlite3_close sqlite3_api->close #define sqlite3_collation_needed sqlite3_api->collation_needed #define sqlite3_collation_needed16 sqlite3_api->collation_needed16 #define sqlite3_column_blob sqlite3_api->column_blob #define sqlite3_column_bytes sqlite3_api->column_bytes #define sqlite3_column_bytes16 sqlite3_api->column_bytes16 #define sqlite3_column_count sqlite3_api->column_count #define sqlite3_column_database_name sqlite3_api->column_database_name #define sqlite3_column_database_name16 sqlite3_api->column_database_name16 #define sqlite3_column_decltype sqlite3_api->column_decltype #define sqlite3_column_decltype16 sqlite3_api->column_decltype16 #define sqlite3_column_double sqlite3_api->column_double #define sqlite3_column_int sqlite3_api->column_int #define sqlite3_column_int64 sqlite3_api->column_int64 #define sqlite3_column_name sqlite3_api->column_name #define sqlite3_column_name16 sqlite3_api->column_name16 #define sqlite3_column_origin_name sqlite3_api->column_origin_name #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 #define sqlite3_column_table_name sqlite3_api->column_table_name #define sqlite3_column_table_name16 sqlite3_api->column_table_name16 #define sqlite3_column_text sqlite3_api->column_text #define sqlite3_column_text16 sqlite3_api->column_text16 #define sqlite3_column_type sqlite3_api->column_type #define sqlite3_column_value sqlite3_api->column_value #define sqlite3_commit_hook sqlite3_api->commit_hook #define sqlite3_complete sqlite3_api->complete #define sqlite3_complete16 sqlite3_api->complete16 #define sqlite3_create_collation sqlite3_api->create_collation #define sqlite3_create_collation16 sqlite3_api->create_collation16 #define sqlite3_create_function sqlite3_api->create_function #define sqlite3_create_function16 sqlite3_api->create_function16 #define sqlite3_create_module sqlite3_api->create_module #define sqlite3_create_module_v2 sqlite3_api->create_module_v2 #define sqlite3_data_count sqlite3_api->data_count #define sqlite3_db_handle sqlite3_api->db_handle #define sqlite3_declare_vtab sqlite3_api->declare_vtab #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache #define sqlite3_errcode sqlite3_api->errcode #define sqlite3_errmsg sqlite3_api->errmsg #define sqlite3_errmsg16 sqlite3_api->errmsg16 #define sqlite3_exec sqlite3_api->exec #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_expired sqlite3_api->expired #endif #define sqlite3_finalize sqlite3_api->finalize #define sqlite3_free sqlite3_api->free #define sqlite3_free_table sqlite3_api->free_table #define sqlite3_get_autocommit sqlite3_api->get_autocommit #define sqlite3_get_auxdata sqlite3_api->get_auxdata #define sqlite3_get_table sqlite3_api->get_table #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_global_recover sqlite3_api->global_recover #endif #define sqlite3_interrupt sqlite3_api->interruptx #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid #define sqlite3_libversion sqlite3_api->libversion #define sqlite3_libversion_number sqlite3_api->libversion_number #define sqlite3_malloc sqlite3_api->malloc #define sqlite3_mprintf sqlite3_api->mprintf #define sqlite3_open sqlite3_api->open #define sqlite3_open16 sqlite3_api->open16 #define sqlite3_prepare sqlite3_api->prepare #define sqlite3_prepare16 sqlite3_api->prepare16 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 #define sqlite3_profile sqlite3_api->profile #define sqlite3_progress_handler sqlite3_api->progress_handler #define sqlite3_realloc sqlite3_api->realloc #define sqlite3_reset sqlite3_api->reset #define sqlite3_result_blob sqlite3_api->result_blob #define sqlite3_result_double sqlite3_api->result_double #define sqlite3_result_error sqlite3_api->result_error #define sqlite3_result_error16 sqlite3_api->result_error16 #define sqlite3_result_int sqlite3_api->result_int #define sqlite3_result_int64 sqlite3_api->result_int64 #define sqlite3_result_null sqlite3_api->result_null #define sqlite3_result_text sqlite3_api->result_text #define sqlite3_result_text16 sqlite3_api->result_text16 #define sqlite3_result_text16be sqlite3_api->result_text16be #define sqlite3_result_text16le sqlite3_api->result_text16le #define sqlite3_result_value sqlite3_api->result_value #define sqlite3_rollback_hook sqlite3_api->rollback_hook #define sqlite3_set_authorizer sqlite3_api->set_authorizer #define sqlite3_set_auxdata sqlite3_api->set_auxdata #define sqlite3_snprintf sqlite3_api->snprintf #define sqlite3_step sqlite3_api->step #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup #define sqlite3_total_changes sqlite3_api->total_changes #define sqlite3_trace sqlite3_api->trace #ifndef SQLITE_OMIT_DEPRECATED #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings #endif #define sqlite3_update_hook sqlite3_api->update_hook #define sqlite3_user_data sqlite3_api->user_data #define sqlite3_value_blob sqlite3_api->value_blob #define sqlite3_value_bytes sqlite3_api->value_bytes #define sqlite3_value_bytes16 sqlite3_api->value_bytes16 #define sqlite3_value_double sqlite3_api->value_double #define sqlite3_value_int sqlite3_api->value_int #define sqlite3_value_int64 sqlite3_api->value_int64 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type #define sqlite3_value_text sqlite3_api->value_text #define sqlite3_value_text16 sqlite3_api->value_text16 #define sqlite3_value_text16be sqlite3_api->value_text16be #define sqlite3_value_text16le sqlite3_api->value_text16le #define sqlite3_value_type sqlite3_api->value_type #define sqlite3_vmprintf sqlite3_api->vmprintf #define sqlite3_vsnprintf sqlite3_api->vsnprintf #define sqlite3_overload_function sqlite3_api->overload_function #define sqlite3_prepare_v2 sqlite3_api->prepare_v2 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 #define sqlite3_clear_bindings sqlite3_api->clear_bindings #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob #define sqlite3_blob_bytes sqlite3_api->blob_bytes #define sqlite3_blob_close sqlite3_api->blob_close #define sqlite3_blob_open sqlite3_api->blob_open #define sqlite3_blob_read sqlite3_api->blob_read #define sqlite3_blob_write sqlite3_api->blob_write #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 #define sqlite3_file_control sqlite3_api->file_control #define sqlite3_memory_highwater sqlite3_api->memory_highwater #define sqlite3_memory_used sqlite3_api->memory_used #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc #define sqlite3_mutex_enter sqlite3_api->mutex_enter #define sqlite3_mutex_free sqlite3_api->mutex_free #define sqlite3_mutex_leave sqlite3_api->mutex_leave #define sqlite3_mutex_try sqlite3_api->mutex_try #define sqlite3_open_v2 sqlite3_api->open_v2 #define sqlite3_release_memory sqlite3_api->release_memory #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig #define sqlite3_sleep sqlite3_api->sleep #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit #define sqlite3_vfs_find sqlite3_api->vfs_find #define sqlite3_vfs_register sqlite3_api->vfs_register #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister #define sqlite3_threadsafe sqlite3_api->xthreadsafe #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob #define sqlite3_result_error_code sqlite3_api->result_error_code #define sqlite3_test_control sqlite3_api->test_control #define sqlite3_randomness sqlite3_api->randomness #define sqlite3_context_db_handle sqlite3_api->context_db_handle #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes #define sqlite3_limit sqlite3_api->limit #define sqlite3_next_stmt sqlite3_api->next_stmt #define sqlite3_sql sqlite3_api->sql #define sqlite3_status sqlite3_api->status #define sqlite3_backup_finish sqlite3_api->backup_finish #define sqlite3_backup_init sqlite3_api->backup_init #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount #define sqlite3_backup_remaining sqlite3_api->backup_remaining #define sqlite3_backup_step sqlite3_api->backup_step #define sqlite3_compileoption_get sqlite3_api->compileoption_get #define sqlite3_compileoption_used sqlite3_api->compileoption_used #define sqlite3_create_function_v2 sqlite3_api->create_function_v2 #define sqlite3_db_config sqlite3_api->db_config #define sqlite3_db_mutex sqlite3_api->db_mutex #define sqlite3_db_status sqlite3_api->db_status #define sqlite3_extended_errcode sqlite3_api->extended_errcode #define sqlite3_log sqlite3_api->log #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 #define sqlite3_sourceid sqlite3_api->sourceid #define sqlite3_stmt_status sqlite3_api->stmt_status #define sqlite3_strnicmp sqlite3_api->strnicmp #define sqlite3_unlock_notify sqlite3_api->unlock_notify #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint #define sqlite3_wal_hook sqlite3_api->wal_hook #define sqlite3_blob_reopen sqlite3_api->blob_reopen #define sqlite3_vtab_config sqlite3_api->vtab_config #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict /* Version 3.7.16 and later */ #define sqlite3_close_v2 sqlite3_api->close_v2 #define sqlite3_db_filename sqlite3_api->db_filename #define sqlite3_db_readonly sqlite3_api->db_readonly #define sqlite3_db_release_memory sqlite3_api->db_release_memory #define sqlite3_errstr sqlite3_api->errstr #define sqlite3_stmt_busy sqlite3_api->stmt_busy #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly #define sqlite3_stricmp sqlite3_api->stricmp #define sqlite3_uri_boolean sqlite3_api->uri_boolean #define sqlite3_uri_int64 sqlite3_api->uri_int64 #define sqlite3_uri_parameter sqlite3_api->uri_parameter #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 /* Version 3.8.7 and later */ #define sqlite3_auto_extension sqlite3_api->auto_extension #define sqlite3_bind_blob64 sqlite3_api->bind_blob64 #define sqlite3_bind_text64 sqlite3_api->bind_text64 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension #define sqlite3_load_extension sqlite3_api->load_extension #define sqlite3_malloc64 sqlite3_api->malloc64 #define sqlite3_msize sqlite3_api->msize #define sqlite3_realloc64 sqlite3_api->realloc64 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension #define sqlite3_result_blob64 sqlite3_api->result_blob64 #define sqlite3_result_text64 sqlite3_api->result_text64 #define sqlite3_strglob sqlite3_api->strglob /* Version 3.8.11 and later */ #define sqlite3_value_dup sqlite3_api->value_dup #define sqlite3_value_free sqlite3_api->value_free #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64 /* Version 3.9.0 and later */ #define sqlite3_value_subtype sqlite3_api->value_subtype #define sqlite3_result_subtype sqlite3_api->result_subtype /* Version 3.10.0 and later */ #define sqlite3_status64 sqlite3_api->status64 #define sqlite3_strlike sqlite3_api->strlike #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush /* Version 3.12.0 and later */ #define sqlite3_system_errno sqlite3_api->system_errno /* Version 3.14.0 and later */ #define sqlite3_trace_v2 sqlite3_api->trace_v2 #define sqlite3_expanded_sql sqlite3_api->expanded_sql #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) /* This case when the file really is being compiled as a loadable ** extension */ # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; # define SQLITE_EXTENSION_INIT3 \ extern const sqlite3_api_routines *sqlite3_api; #else /* This case when the file is being statically linked into the ** application */ # define SQLITE_EXTENSION_INIT1 /*no-op*/ # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ # define SQLITE_EXTENSION_INIT3 /*no-op*/ #endif #endif /* SQLITE3EXT_H */ /************** End of sqlite3ext.h ******************************************/ /************** Continuing where we left off in loadext.c ********************/ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** Some API routines are omitted when various features are ** excluded from a build of SQLite. Substitute a NULL pointer ** for any missing APIs. */ #ifndef SQLITE_ENABLE_COLUMN_METADATA # define sqlite3_column_database_name 0 # define sqlite3_column_database_name16 0 # define sqlite3_column_table_name 0 # define sqlite3_column_table_name16 0 # define sqlite3_column_origin_name 0 # define sqlite3_column_origin_name16 0 #endif #ifdef SQLITE_OMIT_AUTHORIZATION # define sqlite3_set_authorizer 0 #endif #ifdef SQLITE_OMIT_UTF16 # define sqlite3_bind_text16 0 # define sqlite3_collation_needed16 0 # define sqlite3_column_decltype16 0 # define sqlite3_column_name16 0 # define sqlite3_column_text16 0 # define sqlite3_complete16 0 # define sqlite3_create_collation16 0 # define sqlite3_create_function16 0 # define sqlite3_errmsg16 0 # define sqlite3_open16 0 # define sqlite3_prepare16 0 # define sqlite3_prepare16_v2 0 # define sqlite3_result_error16 0 # define sqlite3_result_text16 0 # define sqlite3_result_text16be 0 # define sqlite3_result_text16le 0 # define sqlite3_value_text16 0 # define sqlite3_value_text16be 0 # define sqlite3_value_text16le 0 # define sqlite3_column_database_name16 0 # define sqlite3_column_table_name16 0 # define sqlite3_column_origin_name16 0 #endif #ifdef SQLITE_OMIT_COMPLETE # define sqlite3_complete 0 # define sqlite3_complete16 0 #endif #ifdef SQLITE_OMIT_DECLTYPE # define sqlite3_column_decltype16 0 # define sqlite3_column_decltype 0 #endif #ifdef SQLITE_OMIT_PROGRESS_CALLBACK # define sqlite3_progress_handler 0 #endif #ifdef SQLITE_OMIT_VIRTUALTABLE # define sqlite3_create_module 0 # define sqlite3_create_module_v2 0 # define sqlite3_declare_vtab 0 # define sqlite3_vtab_config 0 # define sqlite3_vtab_on_conflict 0 #endif #ifdef SQLITE_OMIT_SHARED_CACHE # define sqlite3_enable_shared_cache 0 #endif #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED) # define sqlite3_profile 0 # define sqlite3_trace 0 #endif #ifdef SQLITE_OMIT_GET_TABLE # define sqlite3_free_table 0 # define sqlite3_get_table 0 #endif #ifdef SQLITE_OMIT_INCRBLOB #define sqlite3_bind_zeroblob 0 #define sqlite3_blob_bytes 0 #define sqlite3_blob_close 0 #define sqlite3_blob_open 0 #define sqlite3_blob_read 0 #define sqlite3_blob_write 0 #define sqlite3_blob_reopen 0 #endif #if defined(SQLITE_OMIT_TRACE) # define sqlite3_trace_v2 0 #endif /* ** The following structure contains pointers to all SQLite API routines. ** A pointer to this structure is passed into extensions when they are ** loaded so that the extension can make calls back into the SQLite ** library. ** ** When adding new APIs, add them to the bottom of this structure ** in order to preserve backwards compatibility. ** ** Extensions that use newer APIs should first call the ** sqlite3_libversion_number() to make sure that the API they ** intend to use is supported by the library. Extensions should ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ static const sqlite3_api_routines sqlite3Apis = { sqlite3_aggregate_context, #ifndef SQLITE_OMIT_DEPRECATED sqlite3_aggregate_count, #else 0, #endif sqlite3_bind_blob, sqlite3_bind_double, sqlite3_bind_int, sqlite3_bind_int64, sqlite3_bind_null, sqlite3_bind_parameter_count, sqlite3_bind_parameter_index, sqlite3_bind_parameter_name, sqlite3_bind_text, sqlite3_bind_text16, sqlite3_bind_value, sqlite3_busy_handler, sqlite3_busy_timeout, sqlite3_changes, sqlite3_close, sqlite3_collation_needed, sqlite3_collation_needed16, sqlite3_column_blob, sqlite3_column_bytes, sqlite3_column_bytes16, sqlite3_column_count, sqlite3_column_database_name, sqlite3_column_database_name16, sqlite3_column_decltype, sqlite3_column_decltype16, sqlite3_column_double, sqlite3_column_int, sqlite3_column_int64, sqlite3_column_name, sqlite3_column_name16, sqlite3_column_origin_name, sqlite3_column_origin_name16, sqlite3_column_table_name, sqlite3_column_table_name16, sqlite3_column_text, sqlite3_column_text16, sqlite3_column_type, sqlite3_column_value, sqlite3_commit_hook, sqlite3_complete, sqlite3_complete16, sqlite3_create_collation, sqlite3_create_collation16, sqlite3_create_function, sqlite3_create_function16, sqlite3_create_module, sqlite3_data_count, sqlite3_db_handle, sqlite3_declare_vtab, sqlite3_enable_shared_cache, sqlite3_errcode, sqlite3_errmsg, sqlite3_errmsg16, sqlite3_exec, #ifndef SQLITE_OMIT_DEPRECATED sqlite3_expired, #else 0, #endif sqlite3_finalize, sqlite3_free, sqlite3_free_table, sqlite3_get_autocommit, sqlite3_get_auxdata, sqlite3_get_table, 0, /* Was sqlite3_global_recover(), but that function is deprecated */ sqlite3_interrupt, sqlite3_last_insert_rowid, sqlite3_libversion, sqlite3_libversion_number, sqlite3_malloc, sqlite3_mprintf, sqlite3_open, sqlite3_open16, sqlite3_prepare, sqlite3_prepare16, sqlite3_profile, sqlite3_progress_handler, sqlite3_realloc, sqlite3_reset, sqlite3_result_blob, sqlite3_result_double, sqlite3_result_error, sqlite3_result_error16, sqlite3_result_int, sqlite3_result_int64, sqlite3_result_null, sqlite3_result_text, sqlite3_result_text16, sqlite3_result_text16be, sqlite3_result_text16le, sqlite3_result_value, sqlite3_rollback_hook, sqlite3_set_authorizer, sqlite3_set_auxdata, sqlite3_snprintf, sqlite3_step, sqlite3_table_column_metadata, #ifndef SQLITE_OMIT_DEPRECATED sqlite3_thread_cleanup, #else 0, #endif sqlite3_total_changes, sqlite3_trace, #ifndef SQLITE_OMIT_DEPRECATED sqlite3_transfer_bindings, #else 0, #endif sqlite3_update_hook, sqlite3_user_data, sqlite3_value_blob, sqlite3_value_bytes, sqlite3_value_bytes16, sqlite3_value_double, sqlite3_value_int, sqlite3_value_int64, sqlite3_value_numeric_type, sqlite3_value_text, sqlite3_value_text16, sqlite3_value_text16be, sqlite3_value_text16le, sqlite3_value_type, sqlite3_vmprintf, /* ** The original API set ends here. All extensions can call any ** of the APIs above provided that the pointer is not NULL. But ** before calling APIs that follow, extension should check the ** sqlite3_libversion_number() to make sure they are dealing with ** a library that is new enough to support that API. ************************************************************************* */ sqlite3_overload_function, /* ** Added after 3.3.13 */ sqlite3_prepare_v2, sqlite3_prepare16_v2, sqlite3_clear_bindings, /* ** Added for 3.4.1 */ sqlite3_create_module_v2, /* ** Added for 3.5.0 */ sqlite3_bind_zeroblob, sqlite3_blob_bytes, sqlite3_blob_close, sqlite3_blob_open, sqlite3_blob_read, sqlite3_blob_write, sqlite3_create_collation_v2, sqlite3_file_control, sqlite3_memory_highwater, sqlite3_memory_used, #ifdef SQLITE_MUTEX_OMIT 0, 0, 0, 0, 0, #else sqlite3_mutex_alloc, sqlite3_mutex_enter, sqlite3_mutex_free, sqlite3_mutex_leave, sqlite3_mutex_try, #endif sqlite3_open_v2, sqlite3_release_memory, sqlite3_result_error_nomem, sqlite3_result_error_toobig, sqlite3_sleep, sqlite3_soft_heap_limit, sqlite3_vfs_find, sqlite3_vfs_register, sqlite3_vfs_unregister, /* ** Added for 3.5.8 */ sqlite3_threadsafe, sqlite3_result_zeroblob, sqlite3_result_error_code, sqlite3_test_control, sqlite3_randomness, sqlite3_context_db_handle, /* ** Added for 3.6.0 */ sqlite3_extended_result_codes, sqlite3_limit, sqlite3_next_stmt, sqlite3_sql, sqlite3_status, /* ** Added for 3.7.4 */ sqlite3_backup_finish, sqlite3_backup_init, sqlite3_backup_pagecount, sqlite3_backup_remaining, sqlite3_backup_step, #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS sqlite3_compileoption_get, sqlite3_compileoption_used, #else 0, 0, #endif sqlite3_create_function_v2, sqlite3_db_config, sqlite3_db_mutex, sqlite3_db_status, sqlite3_extended_errcode, sqlite3_log, sqlite3_soft_heap_limit64, sqlite3_sourceid, sqlite3_stmt_status, sqlite3_strnicmp, #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY sqlite3_unlock_notify, #else 0, #endif #ifndef SQLITE_OMIT_WAL sqlite3_wal_autocheckpoint, sqlite3_wal_checkpoint, sqlite3_wal_hook, #else 0, 0, 0, #endif sqlite3_blob_reopen, sqlite3_vtab_config, sqlite3_vtab_on_conflict, sqlite3_close_v2, sqlite3_db_filename, sqlite3_db_readonly, sqlite3_db_release_memory, sqlite3_errstr, sqlite3_stmt_busy, sqlite3_stmt_readonly, sqlite3_stricmp, sqlite3_uri_boolean, sqlite3_uri_int64, sqlite3_uri_parameter, sqlite3_vsnprintf, sqlite3_wal_checkpoint_v2, /* Version 3.8.7 and later */ sqlite3_auto_extension, sqlite3_bind_blob64, sqlite3_bind_text64, sqlite3_cancel_auto_extension, sqlite3_load_extension, sqlite3_malloc64, sqlite3_msize, sqlite3_realloc64, sqlite3_reset_auto_extension, sqlite3_result_blob64, sqlite3_result_text64, sqlite3_strglob, /* Version 3.8.11 and later */ (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup, sqlite3_value_free, sqlite3_result_zeroblob64, sqlite3_bind_zeroblob64, /* Version 3.9.0 and later */ sqlite3_value_subtype, sqlite3_result_subtype, /* Version 3.10.0 and later */ sqlite3_status64, sqlite3_strlike, sqlite3_db_cacheflush, /* Version 3.12.0 and later */ sqlite3_system_errno, /* Version 3.14.0 and later */ sqlite3_trace_v2, sqlite3_expanded_sql }; /* ** Attempt to load an SQLite extension library contained in the file ** zFile. The entry point is zProc. zProc may be 0 in which case a ** default entry point name (sqlite3_extension_init) is used. Use ** of the default name is recommended. ** ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. ** ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with ** error message text. The calling function should free this memory ** by calling sqlite3DbFree(db, ). */ static int sqlite3LoadExtension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ){ sqlite3_vfs *pVfs = db->pVfs; void *handle; sqlite3_loadext_entry xInit; char *zErrmsg = 0; const char *zEntry; char *zAltEntry = 0; void **aHandle; u64 nMsg = 300 + sqlite3Strlen30(zFile); int ii; int rc; /* Shared library endings to try if zFile cannot be loaded as written */ static const char *azEndings[] = { #if SQLITE_OS_WIN "dll" #elif defined(__APPLE__) "dylib" #else "so" #endif }; if( pzErrMsg ) *pzErrMsg = 0; /* Ticket #1863. To avoid a creating security problems for older ** applications that relink against newer versions of SQLite, the ** ability to run load_extension is turned off by default. One ** must call either sqlite3_enable_load_extension(db) or ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0) ** to turn on extension loading. */ if( (db->flags & SQLITE_LoadExtension)==0 ){ if( pzErrMsg ){ *pzErrMsg = sqlite3_mprintf("not authorized"); } return SQLITE_ERROR; } zEntry = zProc ? zProc : "sqlite3_extension_init"; handle = sqlite3OsDlOpen(pVfs, zFile); #if SQLITE_OS_UNIX || SQLITE_OS_WIN for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){ char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]); if( zAltFile==0 ) return SQLITE_NOMEM_BKPT; handle = sqlite3OsDlOpen(pVfs, zAltFile); sqlite3_free(zAltFile); } #endif if( handle==0 ){ if( pzErrMsg ){ *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg); if( zErrmsg ){ sqlite3_snprintf(nMsg, zErrmsg, "unable to open shared library [%s]", zFile); sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); } } return SQLITE_ERROR; } xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); /* If no entry point was specified and the default legacy ** entry point name "sqlite3_extension_init" was not found, then ** construct an entry point name "sqlite3_X_init" where the X is ** replaced by the lowercase value of every ASCII alphabetic ** character in the filename after the last "/" upto the first ".", ** and eliding the first three characters if they are "lib". ** Examples: ** ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init */ if( xInit==0 && zProc==0 ){ int iFile, iEntry, c; int ncFile = sqlite3Strlen30(zFile); zAltEntry = sqlite3_malloc64(ncFile+30); if( zAltEntry==0 ){ sqlite3OsDlClose(pVfs, handle); return SQLITE_NOMEM_BKPT; } memcpy(zAltEntry, "sqlite3_", 8); for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){} iFile++; if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){ if( sqlite3Isalpha(c) ){ zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; } } memcpy(zAltEntry+iEntry, "_init", 6); zEntry = zAltEntry; xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); } if( xInit==0 ){ if( pzErrMsg ){ nMsg += sqlite3Strlen30(zEntry); *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg); if( zErrmsg ){ sqlite3_snprintf(nMsg, zErrmsg, "no entry point [%s] in shared library [%s]", zEntry, zFile); sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); } } sqlite3OsDlClose(pVfs, handle); sqlite3_free(zAltEntry); return SQLITE_ERROR; } sqlite3_free(zAltEntry); rc = xInit(db, &zErrmsg, &sqlite3Apis); if( rc ){ if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK; if( pzErrMsg ){ *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); } sqlite3_free(zErrmsg); sqlite3OsDlClose(pVfs, handle); return SQLITE_ERROR; } /* Append the new shared library handle to the db->aExtension array. */ aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1)); if( aHandle==0 ){ return SQLITE_NOMEM_BKPT; } if( db->nExtension>0 ){ memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension); } sqlite3DbFree(db, db->aExtension); db->aExtension = aHandle; db->aExtension[db->nExtension++] = handle; return SQLITE_OK; } SQLITE_API int sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ){ int rc; sqlite3_mutex_enter(db->mutex); rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Call this routine when the database connection is closing in order ** to clean up loaded extensions */ SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){ int i; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nExtension; i++){ sqlite3OsDlClose(db->pVfs, db->aExtension[i]); } sqlite3DbFree(db, db->aExtension); } /* ** Enable or disable extension loading. Extension loading is disabled by ** default so as not to open security holes in older applications. */ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){ sqlite3_mutex_enter(db->mutex); if( onoff ){ db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc; }else{ db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc); } sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */ /* ** The following object holds the list of automatically loaded ** extensions. ** ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER ** mutex must be held while accessing this list. */ typedef struct sqlite3AutoExtList sqlite3AutoExtList; static SQLITE_WSD struct sqlite3AutoExtList { u32 nExt; /* Number of entries in aExt[] */ void (**aExt)(void); /* Pointers to the extension init functions */ } sqlite3Autoext = { 0, 0 }; /* The "wsdAutoext" macro will resolve to the autoextension ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Autoext" state vector declared above. */ #ifdef SQLITE_OMIT_WSD # define wsdAutoextInit \ sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) # define wsdAutoext x[0] #else # define wsdAutoextInit # define wsdAutoext sqlite3Autoext #endif /* ** Register a statically linked extension that is automatically ** loaded by every new database connection. */ SQLITE_API int sqlite3_auto_extension( void (*xInit)(void) ){ int rc = SQLITE_OK; #ifndef SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc ){ return rc; }else #endif { u32 i; #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif wsdAutoextInit; sqlite3_mutex_enter(mutex); for(i=0; i<wsdAutoext.nExt; i++){ if( wsdAutoext.aExt[i]==xInit ) break; } if( i==wsdAutoext.nExt ){ u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]); void (**aNew)(void); aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte); if( aNew==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ wsdAutoext.aExt = aNew; wsdAutoext.aExt[wsdAutoext.nExt] = xInit; wsdAutoext.nExt++; } } sqlite3_mutex_leave(mutex); assert( (rc&0xff)==rc ); return rc; } } /* ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the ** set of routines that is invoked for each new database connection, if it ** is currently on the list. If xInit is not on the list, then this ** routine is a no-op. ** ** Return 1 if xInit was found on the list and removed. Return 0 if xInit ** was not on the list. */ SQLITE_API int sqlite3_cancel_auto_extension( void (*xInit)(void) ){ #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif int i; int n = 0; wsdAutoextInit; sqlite3_mutex_enter(mutex); for(i=(int)wsdAutoext.nExt-1; i>=0; i--){ if( wsdAutoext.aExt[i]==xInit ){ wsdAutoext.nExt--; wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt]; n++; break; } } sqlite3_mutex_leave(mutex); return n; } /* ** Reset the automatic extension loading mechanism. */ SQLITE_API void sqlite3_reset_auto_extension(void){ #ifndef SQLITE_OMIT_AUTOINIT if( sqlite3_initialize()==SQLITE_OK ) #endif { #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif wsdAutoextInit; sqlite3_mutex_enter(mutex); sqlite3_free(wsdAutoext.aExt); wsdAutoext.aExt = 0; wsdAutoext.nExt = 0; sqlite3_mutex_leave(mutex); } } /* ** Load all automatic extensions. ** ** If anything goes wrong, set an error in the database connection. */ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){ u32 i; int go = 1; int rc; sqlite3_loadext_entry xInit; wsdAutoextInit; if( wsdAutoext.nExt==0 ){ /* Common case: early out without every having to acquire a mutex */ return; } for(i=0; go; i++){ char *zErrmsg; #if SQLITE_THREADSAFE sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif #ifdef SQLITE_OMIT_LOAD_EXTENSION const sqlite3_api_routines *pThunk = 0; #else const sqlite3_api_routines *pThunk = &sqlite3Apis; #endif sqlite3_mutex_enter(mutex); if( i>=wsdAutoext.nExt ){ xInit = 0; go = 0; }else{ xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i]; } sqlite3_mutex_leave(mutex); zErrmsg = 0; if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){ sqlite3ErrorWithMsg(db, rc, "automatic extension loading failed: %s", zErrmsg); go = 0; } sqlite3_free(zErrmsg); } } /************** End of loadext.c *********************************************/ /************** Begin file pragma.c ******************************************/ /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the PRAGMA command. */ /* #include "sqliteInt.h" */ #if !defined(SQLITE_ENABLE_LOCKING_STYLE) # if defined(__APPLE__) # define SQLITE_ENABLE_LOCKING_STYLE 1 # else # define SQLITE_ENABLE_LOCKING_STYLE 0 # endif #endif /*************************************************************************** ** The "pragma.h" include file is an automatically generated file that ** that includes the PragType_XXXX macro definitions and the aPragmaName[] ** object. This ensures that the aPragmaName[] table is arranged in ** lexicographical order to facility a binary search of the pragma name. ** Do not edit pragma.h directly. Edit and rerun the script in at ** ../tool/mkpragmatab.tcl. */ /************** Include pragma.h in the middle of pragma.c *******************/ /************** Begin file pragma.h ******************************************/ /* DO NOT EDIT! ** This file is automatically generated by the script at ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit ** that script and rerun it. */ /* The various pragma types */ #define PragTyp_HEADER_VALUE 0 #define PragTyp_AUTO_VACUUM 1 #define PragTyp_FLAG 2 #define PragTyp_BUSY_TIMEOUT 3 #define PragTyp_CACHE_SIZE 4 #define PragTyp_CACHE_SPILL 5 #define PragTyp_CASE_SENSITIVE_LIKE 6 #define PragTyp_COLLATION_LIST 7 #define PragTyp_COMPILE_OPTIONS 8 #define PragTyp_DATA_STORE_DIRECTORY 9 #define PragTyp_DATABASE_LIST 10 #define PragTyp_DEFAULT_CACHE_SIZE 11 #define PragTyp_ENCODING 12 #define PragTyp_FOREIGN_KEY_CHECK 13 #define PragTyp_FOREIGN_KEY_LIST 14 #define PragTyp_INCREMENTAL_VACUUM 15 #define PragTyp_INDEX_INFO 16 #define PragTyp_INDEX_LIST 17 #define PragTyp_INTEGRITY_CHECK 18 #define PragTyp_JOURNAL_MODE 19 #define PragTyp_JOURNAL_SIZE_LIMIT 20 #define PragTyp_LOCK_PROXY_FILE 21 #define PragTyp_LOCKING_MODE 22 #define PragTyp_PAGE_COUNT 23 #define PragTyp_MMAP_SIZE 24 #define PragTyp_PAGE_SIZE 25 #define PragTyp_SECURE_DELETE 26 #define PragTyp_SHRINK_MEMORY 27 #define PragTyp_SOFT_HEAP_LIMIT 28 #define PragTyp_STATS 29 #define PragTyp_SYNCHRONOUS 30 #define PragTyp_TABLE_INFO 31 #define PragTyp_TEMP_STORE 32 #define PragTyp_TEMP_STORE_DIRECTORY 33 #define PragTyp_THREADS 34 #define PragTyp_WAL_AUTOCHECKPOINT 35 #define PragTyp_WAL_CHECKPOINT 36 #define PragTyp_ACTIVATE_EXTENSIONS 37 #define PragTyp_HEXKEY 38 #define PragTyp_KEY 39 #define PragTyp_REKEY 40 #define PragTyp_LOCK_STATUS 41 #define PragTyp_PARSER_TRACE 42 /* Property flags associated with various pragma. */ #define PragFlg_NeedSchema 0x01 /* Force schema load before running */ #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */ #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */ #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */ #define PragFlg_Result0 0x10 /* Acts as query when no argument */ #define PragFlg_Result1 0x20 /* Acts as query when has one argument */ #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */ #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */ /* Names of columns for pragmas that return multi-column result ** or that return single-column results where the name of the ** result column is different from the name of the pragma */ static const char *const pragCName[] = { /* 0 */ "cache_size", /* Used by: default_cache_size */ /* 1 */ "cid", /* Used by: table_info */ /* 2 */ "name", /* 3 */ "type", /* 4 */ "notnull", /* 5 */ "dflt_value", /* 6 */ "pk", /* 7 */ "table", /* Used by: stats */ /* 8 */ "index", /* 9 */ "width", /* 10 */ "height", /* 11 */ "seqno", /* Used by: index_info */ /* 12 */ "cid", /* 13 */ "name", /* 14 */ "seqno", /* Used by: index_xinfo */ /* 15 */ "cid", /* 16 */ "name", /* 17 */ "desc", /* 18 */ "coll", /* 19 */ "key", /* 20 */ "seq", /* Used by: index_list */ /* 21 */ "name", /* 22 */ "unique", /* 23 */ "origin", /* 24 */ "partial", /* 25 */ "seq", /* Used by: database_list */ /* 26 */ "name", /* 27 */ "file", /* 28 */ "seq", /* Used by: collation_list */ /* 29 */ "name", /* 30 */ "id", /* Used by: foreign_key_list */ /* 31 */ "seq", /* 32 */ "table", /* 33 */ "from", /* 34 */ "to", /* 35 */ "on_update", /* 36 */ "on_delete", /* 37 */ "match", /* 38 */ "table", /* Used by: foreign_key_check */ /* 39 */ "rowid", /* 40 */ "parent", /* 41 */ "fkid", /* 42 */ "busy", /* Used by: wal_checkpoint */ /* 43 */ "log", /* 44 */ "checkpointed", /* 45 */ "timeout", /* Used by: busy_timeout */ /* 46 */ "database", /* Used by: lock_status */ /* 47 */ "status", }; /* Definitions of all built-in pragmas */ typedef struct PragmaName { const char *const zName; /* Name of pragma */ u8 ePragTyp; /* PragTyp_XXX value */ u8 mPragFlg; /* Zero or more PragFlg_XXX values */ u8 iPragCName; /* Start of column names in pragCName[] */ u8 nPragCName; /* Num of col names. 0 means use pragma name */ u32 iArg; /* Extra argument */ } PragmaName; static const PragmaName aPragmaName[] = { #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) {/* zName: */ "activate_extensions", /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS, /* ePragFlg: */ 0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) {/* zName: */ "application_id", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ BTREE_APPLICATION_ID }, #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) {/* zName: */ "auto_vacuum", /* ePragTyp: */ PragTyp_AUTO_VACUUM, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX) {/* zName: */ "automatic_index", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_AutoIndex }, #endif #endif {/* zName: */ "busy_timeout", /* ePragTyp: */ PragTyp_BUSY_TIMEOUT, /* ePragFlg: */ PragFlg_Result0, /* ColNames: */ 45, 1, /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) {/* zName: */ "cache_size", /* ePragTyp: */ PragTyp_CACHE_SIZE, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "cache_spill", /* ePragTyp: */ PragTyp_CACHE_SPILL, /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif {/* zName: */ "case_sensitive_like", /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE, /* ePragFlg: */ PragFlg_NoColumns, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "cell_size_check", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_CellSizeCk }, #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "checkpoint_fullfsync", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_CkptFullFSync }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) {/* zName: */ "collation_list", /* ePragTyp: */ PragTyp_COLLATION_LIST, /* ePragFlg: */ PragFlg_Result0, /* ColNames: */ 28, 2, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) {/* zName: */ "compile_options", /* ePragTyp: */ PragTyp_COMPILE_OPTIONS, /* ePragFlg: */ PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "count_changes", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_CountRows }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN {/* zName: */ "data_store_directory", /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY, /* ePragFlg: */ PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) {/* zName: */ "data_version", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ BTREE_DATA_VERSION }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) {/* zName: */ "database_list", /* ePragTyp: */ PragTyp_DATABASE_LIST, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0, /* ColNames: */ 25, 3, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) {/* zName: */ "default_cache_size", /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, /* ColNames: */ 0, 1, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) {/* zName: */ "defer_foreign_keys", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_DeferFKs }, #endif #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "empty_result_callbacks", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_NullCallback }, #endif #if !defined(SQLITE_OMIT_UTF16) {/* zName: */ "encoding", /* ePragTyp: */ PragTyp_ENCODING, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) {/* zName: */ "foreign_key_check", /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK, /* ePragFlg: */ PragFlg_NeedSchema, /* ColNames: */ 38, 4, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FOREIGN_KEY) {/* zName: */ "foreign_key_list", /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, /* ColNames: */ 30, 8, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) {/* zName: */ "foreign_keys", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_ForeignKeys }, #endif #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) {/* zName: */ "freelist_count", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ BTREE_FREE_PAGE_COUNT }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "full_column_names", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_FullColNames }, {/* zName: */ "fullfsync", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_FullFSync }, #endif #if defined(SQLITE_HAS_CODEC) {/* zName: */ "hexkey", /* ePragTyp: */ PragTyp_HEXKEY, /* ePragFlg: */ 0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "hexrekey", /* ePragTyp: */ PragTyp_HEXKEY, /* ePragFlg: */ 0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_CHECK) {/* zName: */ "ignore_check_constraints", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_IgnoreChecks }, #endif #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) {/* zName: */ "incremental_vacuum", /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) {/* zName: */ "index_info", /* ePragTyp: */ PragTyp_INDEX_INFO, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, /* ColNames: */ 11, 3, /* iArg: */ 0 }, {/* zName: */ "index_list", /* ePragTyp: */ PragTyp_INDEX_LIST, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, /* ColNames: */ 20, 5, /* iArg: */ 0 }, {/* zName: */ "index_xinfo", /* ePragTyp: */ PragTyp_INDEX_INFO, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, /* ColNames: */ 14, 6, /* iArg: */ 1 }, #endif #if !defined(SQLITE_OMIT_INTEGRITY_CHECK) {/* zName: */ "integrity_check", /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, /* ePragFlg: */ PragFlg_NeedSchema, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) {/* zName: */ "journal_mode", /* ePragTyp: */ PragTyp_JOURNAL_MODE, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "journal_size_limit", /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT, /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if defined(SQLITE_HAS_CODEC) {/* zName: */ "key", /* ePragTyp: */ PragTyp_KEY, /* ePragFlg: */ 0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "legacy_file_format", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_LegacyFileFmt }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE {/* zName: */ "lock_proxy_file", /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE, /* ePragFlg: */ PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) {/* zName: */ "lock_status", /* ePragTyp: */ PragTyp_LOCK_STATUS, /* ePragFlg: */ PragFlg_Result0, /* ColNames: */ 46, 2, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) {/* zName: */ "locking_mode", /* ePragTyp: */ PragTyp_LOCKING_MODE, /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "max_page_count", /* ePragTyp: */ PragTyp_PAGE_COUNT, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "mmap_size", /* ePragTyp: */ PragTyp_MMAP_SIZE, /* ePragFlg: */ 0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "page_count", /* ePragTyp: */ PragTyp_PAGE_COUNT, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "page_size", /* ePragTyp: */ PragTyp_PAGE_SIZE, /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE) {/* zName: */ "parser_trace", /* ePragTyp: */ PragTyp_PARSER_TRACE, /* ePragFlg: */ 0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "query_only", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_QueryOnly }, #endif #if !defined(SQLITE_OMIT_INTEGRITY_CHECK) {/* zName: */ "quick_check", /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, /* ePragFlg: */ PragFlg_NeedSchema, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "read_uncommitted", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_ReadUncommitted }, {/* zName: */ "recursive_triggers", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_RecTriggers }, #endif #if defined(SQLITE_HAS_CODEC) {/* zName: */ "rekey", /* ePragTyp: */ PragTyp_REKEY, /* ePragFlg: */ 0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "reverse_unordered_selects", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_ReverseOrder }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) {/* zName: */ "schema_version", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ BTREE_SCHEMA_VERSION }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) {/* zName: */ "secure_delete", /* ePragTyp: */ PragTyp_SECURE_DELETE, /* ePragFlg: */ PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "short_column_names", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_ShortColNames }, #endif {/* zName: */ "shrink_memory", /* ePragTyp: */ PragTyp_SHRINK_MEMORY, /* ePragFlg: */ PragFlg_NoColumns, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "soft_heap_limit", /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT, /* ePragFlg: */ PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if defined(SQLITE_DEBUG) {/* zName: */ "sql_trace", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_SqlTrace }, #endif #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) {/* zName: */ "stats", /* ePragTyp: */ PragTyp_STATS, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, /* ColNames: */ 7, 4, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) {/* zName: */ "synchronous", /* ePragTyp: */ PragTyp_SYNCHRONOUS, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) {/* zName: */ "table_info", /* ePragTyp: */ PragTyp_TABLE_INFO, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, /* ColNames: */ 1, 6, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) {/* zName: */ "temp_store", /* ePragTyp: */ PragTyp_TEMP_STORE, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "temp_store_directory", /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY, /* ePragFlg: */ PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #endif {/* zName: */ "threads", /* ePragTyp: */ PragTyp_THREADS, /* ePragFlg: */ PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) {/* zName: */ "user_version", /* ePragTyp: */ PragTyp_HEADER_VALUE, /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, /* ColNames: */ 0, 0, /* iArg: */ BTREE_USER_VERSION }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if defined(SQLITE_DEBUG) {/* zName: */ "vdbe_addoptrace", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_VdbeAddopTrace }, {/* zName: */ "vdbe_debug", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace }, {/* zName: */ "vdbe_eqp", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_VdbeEQP }, {/* zName: */ "vdbe_listing", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_VdbeListing }, {/* zName: */ "vdbe_trace", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_VdbeTrace }, #endif #endif #if !defined(SQLITE_OMIT_WAL) {/* zName: */ "wal_autocheckpoint", /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT, /* ePragFlg: */ 0, /* ColNames: */ 0, 0, /* iArg: */ 0 }, {/* zName: */ "wal_checkpoint", /* ePragTyp: */ PragTyp_WAL_CHECKPOINT, /* ePragFlg: */ PragFlg_NeedSchema, /* ColNames: */ 42, 3, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) {/* zName: */ "writable_schema", /* ePragTyp: */ PragTyp_FLAG, /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, /* ColNames: */ 0, 0, /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode }, #endif }; /* Number of pragmas: 60 on by default, 73 total. */ /************** End of pragma.h **********************************************/ /************** Continuing where we left off in pragma.c *********************/ /* ** Interpret the given string as a safety level. Return 0 for OFF, ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or ** unrecognized string argument. The FULL and EXTRA option is disallowed ** if the omitFull parameter it 1. ** ** Note that the values returned are one less that the values that ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done ** to support legacy SQL code. The safety level used to be boolean ** and older scripts may have used numbers 0 for OFF and 1 for ON. */ static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){ /* 123456789 123456789 123 */ static const char zText[] = "onoffalseyestruextrafull"; static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20}; static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4}; static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2}; /* on no off false yes true extra full */ int i, n; if( sqlite3Isdigit(*z) ){ return (u8)sqlite3Atoi(z); } n = sqlite3Strlen30(z); for(i=0; i<ArraySize(iLength); i++){ if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 && (!omitFull || iValue[i]<=1) ){ return iValue[i]; } } return dflt; } /* ** Interpret the given string as a boolean value. */ SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){ return getSafetyLevel(z,1,dflt)!=0; } /* The sqlite3GetBoolean() function is used by other modules but the ** remainder of this file is specific to PRAGMA processing. So omit ** the rest of the file if PRAGMAs are omitted from the build. */ #if !defined(SQLITE_OMIT_PRAGMA) /* ** Interpret the given string as a locking mode value. */ static int getLockingMode(const char *z){ if( z ){ if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE; if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL; } return PAGER_LOCKINGMODE_QUERY; } #ifndef SQLITE_OMIT_AUTOVACUUM /* ** Interpret the given string as an auto-vacuum mode value. ** ** The following strings, "none", "full" and "incremental" are ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively. */ static int getAutoVacuum(const char *z){ int i; if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE; if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL; if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR; i = sqlite3Atoi(z); return (u8)((i>=0&&i<=2)?i:0); } #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** Interpret the given string as a temp db location. Return 1 for file ** backed temporary databases, 2 for the Red-Black tree in memory database ** and 0 to use the compile-time default. */ static int getTempStore(const char *z){ if( z[0]>='0' && z[0]<='2' ){ return z[0] - '0'; }else if( sqlite3StrICmp(z, "file")==0 ){ return 1; }else if( sqlite3StrICmp(z, "memory")==0 ){ return 2; }else{ return 0; } } #endif /* SQLITE_PAGER_PRAGMAS */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** Invalidate temp storage, either when the temp storage is changed ** from default, or when 'file' and the temp_store_directory has changed */ static int invalidateTempStorage(Parse *pParse){ sqlite3 *db = pParse->db; if( db->aDb[1].pBt!=0 ){ if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ sqlite3ErrorMsg(pParse, "temporary storage cannot be changed " "from within a transaction"); return SQLITE_ERROR; } sqlite3BtreeClose(db->aDb[1].pBt); db->aDb[1].pBt = 0; sqlite3ResetAllSchemasOfConnection(db); } return SQLITE_OK; } #endif /* SQLITE_PAGER_PRAGMAS */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** If the TEMP database is open, close it and mark the database schema ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE ** or DEFAULT_TEMP_STORE pragmas. */ static int changeTempStorage(Parse *pParse, const char *zStorageType){ int ts = getTempStore(zStorageType); sqlite3 *db = pParse->db; if( db->temp_store==ts ) return SQLITE_OK; if( invalidateTempStorage( pParse ) != SQLITE_OK ){ return SQLITE_ERROR; } db->temp_store = (u8)ts; return SQLITE_OK; } #endif /* SQLITE_PAGER_PRAGMAS */ /* ** Set result column names for a pragma. */ static void setPragmaResultColumnNames( Vdbe *v, /* The query under construction */ const PragmaName *pPragma /* The pragma */ ){ u8 n = pPragma->nPragCName; sqlite3VdbeSetNumCols(v, n==0 ? 1 : n); if( n==0 ){ sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC); }else{ int i, j; for(i=0, j=pPragma->iPragCName; i<n; i++, j++){ sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC); } } } /* ** Generate code to return a single integer value. */ static void returnSingleInt(Vdbe *v, i64 value){ sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } /* ** Generate code to return a single text value. */ static void returnSingleText( Vdbe *v, /* Prepared statement under construction */ const char *zValue /* Value to be returned */ ){ if( zValue ){ sqlite3VdbeLoadString(v, 1, (const char*)zValue); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } } /* ** Set the safety_level and pager flags for pager iDb. Or if iDb<0 ** set these values for all pagers. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS static void setAllPagerFlags(sqlite3 *db){ if( db->autoCommit ){ Db *pDb = db->aDb; int n = db->nDb; assert( SQLITE_FullFSync==PAGER_FULLFSYNC ); assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC ); assert( SQLITE_CacheSpill==PAGER_CACHESPILL ); assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL) == PAGER_FLAGS_MASK ); assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level ); while( (n--) > 0 ){ if( pDb->pBt ){ sqlite3BtreeSetPagerFlags(pDb->pBt, pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) ); } pDb++; } } } #else # define setAllPagerFlags(X) /* no-op */ #endif /* ** Return a human-readable name for a constraint resolution action. */ #ifndef SQLITE_OMIT_FOREIGN_KEY static const char *actionName(u8 action){ const char *zName; switch( action ){ case OE_SetNull: zName = "SET NULL"; break; case OE_SetDflt: zName = "SET DEFAULT"; break; case OE_Cascade: zName = "CASCADE"; break; case OE_Restrict: zName = "RESTRICT"; break; default: zName = "NO ACTION"; assert( action==OE_None ); break; } return zName; } #endif /* ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants ** defined in pager.h. This function returns the associated lowercase ** journal-mode name. */ SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){ static char * const azModeName[] = { "delete", "persist", "off", "truncate", "memory" #ifndef SQLITE_OMIT_WAL , "wal" #endif }; assert( PAGER_JOURNALMODE_DELETE==0 ); assert( PAGER_JOURNALMODE_PERSIST==1 ); assert( PAGER_JOURNALMODE_OFF==2 ); assert( PAGER_JOURNALMODE_TRUNCATE==3 ); assert( PAGER_JOURNALMODE_MEMORY==4 ); assert( PAGER_JOURNALMODE_WAL==5 ); assert( eMode>=0 && eMode<=ArraySize(azModeName) ); if( eMode==ArraySize(azModeName) ) return 0; return azModeName[eMode]; } /* ** Locate a pragma in the aPragmaName[] array. */ static const PragmaName *pragmaLocate(const char *zName){ int upr, lwr, mid = 0, rc; lwr = 0; upr = ArraySize(aPragmaName)-1; while( lwr<=upr ){ mid = (lwr+upr)/2; rc = sqlite3_stricmp(zName, aPragmaName[mid].zName); if( rc==0 ) break; if( rc<0 ){ upr = mid - 1; }else{ lwr = mid + 1; } } return lwr>upr ? 0 : &aPragmaName[mid]; } /* ** Process a pragma statement. ** ** Pragmas are of this form: ** ** PRAGMA [schema.]id [= value] ** ** The identifier might also be a string. The value is a string, and ** identifier, or a number. If minusFlag is true, then the value is ** a number that was preceded by a minus sign. ** ** If the left side is "database.id" then pId1 is the database name ** and pId2 is the id. If the left side is just "id" then pId1 is the ** id and pId2 is any empty string. */ SQLITE_PRIVATE void sqlite3Pragma( Parse *pParse, Token *pId1, /* First part of [schema.]id field */ Token *pId2, /* Second part of [schema.]id field, or NULL */ Token *pValue, /* Token for <value>, or NULL */ int minusFlag /* True if a '-' sign preceded <value> */ ){ char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */ char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */ const char *zDb = 0; /* The database name */ Token *pId; /* Pointer to <id> token */ char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */ int iDb; /* Database index for <database> */ int rc; /* return value form SQLITE_FCNTL_PRAGMA */ sqlite3 *db = pParse->db; /* The database connection */ Db *pDb; /* The specific database being pragmaed */ Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */ const PragmaName *pPragma; /* The pragma */ if( v==0 ) return; sqlite3VdbeRunOnlyOnce(v); pParse->nMem = 2; /* Interpret the [schema.] part of the pragma statement. iDb is the ** index of the database this pragma is being applied to in db.aDb[]. */ iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); if( iDb<0 ) return; pDb = &db->aDb[iDb]; /* If the temp database has been explicitly named as part of the ** pragma, make sure it is open. */ if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ return; } zLeft = sqlite3NameFromToken(db, pId); if( !zLeft ) return; if( minusFlag ){ zRight = sqlite3MPrintf(db, "-%T", pValue); }else{ zRight = sqlite3NameFromToken(db, pValue); } assert( pId2 ); zDb = pId2->n>0 ? pDb->zDbSName : 0; if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ goto pragma_out; } /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS ** connection. If it returns SQLITE_OK, then assume that the VFS ** handled the pragma and generate a no-op prepared statement. ** ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed, ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file ** object corresponding to the database file to which the pragma ** statement refers. ** ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA ** file control is an array of pointers to strings (char**) in which the ** second element of the array is the name of the pragma and the third ** element is the argument to the pragma or NULL if the pragma has no ** argument. */ aFcntl[0] = 0; aFcntl[1] = zLeft; aFcntl[2] = zRight; aFcntl[3] = 0; db->busyHandler.nBusy = 0; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); if( rc==SQLITE_OK ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT); returnSingleText(v, aFcntl[0]); sqlite3_free(aFcntl[0]); goto pragma_out; } if( rc!=SQLITE_NOTFOUND ){ if( aFcntl[0] ){ sqlite3ErrorMsg(pParse, "%s", aFcntl[0]); sqlite3_free(aFcntl[0]); } pParse->nErr++; pParse->rc = rc; goto pragma_out; } /* Locate the pragma in the lookup table */ pPragma = pragmaLocate(zLeft); if( pPragma==0 ) goto pragma_out; /* Make sure the database schema is loaded if the pragma requires that */ if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){ if( sqlite3ReadSchema(pParse) ) goto pragma_out; } /* Register the result column names for pragmas that return results */ if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0) ){ setPragmaResultColumnNames(v, pPragma); } /* Jump to the appropriate pragma handler */ switch( pPragma->ePragTyp ){ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) /* ** PRAGMA [schema.]default_cache_size ** PRAGMA [schema.]default_cache_size=N ** ** The first form reports the current persistent setting for the ** page cache size. The value returned is the maximum number of ** pages in the page cache. The second form sets both the current ** page cache size value and the persistent page cache size value ** stored in the database file. ** ** Older versions of SQLite would set the default cache size to a ** negative number to indicate synchronous=OFF. These days, synchronous ** is always on by default regardless of the sign of the default cache ** size. But continue to take the absolute value of the default cache ** size of historical compatibility. */ case PragTyp_DEFAULT_CACHE_SIZE: { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList getCacheSize[] = { { OP_Transaction, 0, 0, 0}, /* 0 */ { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */ { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 2, 0}, { OP_Subtract, 1, 2, 1}, { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 1, 0}, /* 6 */ { OP_Noop, 0, 0, 0}, { OP_ResultRow, 1, 1, 0}, }; VdbeOp *aOp; sqlite3VdbeUsesBtree(v, iDb); if( !zRight ){ pParse->nMem += 2; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE; }else{ int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) /* ** PRAGMA [schema.]page_size ** PRAGMA [schema.]page_size=N ** ** The first form reports the current setting for the ** database page size in bytes. The second form sets the ** database page size value. The value can only be set if ** the database has not yet been created. */ case PragTyp_PAGE_SIZE: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; returnSingleInt(v, size); }else{ /* Malloc may fail when setting the page-size, as there is an internal ** buffer that the pager module resizes using sqlite3_realloc(). */ db->nextPagesize = sqlite3Atoi(zRight); if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ sqlite3OomFault(db); } } break; } /* ** PRAGMA [schema.]secure_delete ** PRAGMA [schema.]secure_delete=ON/OFF ** ** The first form reports the current setting for the ** secure_delete flag. The second form changes the secure_delete ** flag setting and reports thenew value. */ case PragTyp_SECURE_DELETE: { Btree *pBt = pDb->pBt; int b = -1; assert( pBt!=0 ); if( zRight ){ b = sqlite3GetBoolean(zRight, 0); } if( pId2->n==0 && b>=0 ){ int ii; for(ii=0; ii<db->nDb; ii++){ sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); } } b = sqlite3BtreeSecureDelete(pBt, b); returnSingleInt(v, b); break; } /* ** PRAGMA [schema.]max_page_count ** PRAGMA [schema.]max_page_count=N ** ** The first form reports the current setting for the ** maximum number of pages in the database file. The ** second form attempts to change this setting. Both ** forms return the current setting. ** ** The absolute value of N is used. This is undocumented and might ** change. The only purpose is to provide an easy way to test ** the sqlite3AbsInt32() function. ** ** PRAGMA [schema.]page_count ** ** Return the number of pages in the specified database. */ case PragTyp_PAGE_COUNT: { int iReg; sqlite3CodeVerifySchema(pParse, iDb); iReg = ++pParse->nMem; if( sqlite3Tolower(zLeft[0])=='p' ){ sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); }else{ sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3AbsInt32(sqlite3Atoi(zRight))); } sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); break; } /* ** PRAGMA [schema.]locking_mode ** PRAGMA [schema.]locking_mode = (normal|exclusive) */ case PragTyp_LOCKING_MODE: { const char *zRet = "normal"; int eMode = getLockingMode(zRight); if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ /* Simple "PRAGMA locking_mode;" statement. This is a query for ** the current default locking mode (which may be different to ** the locking-mode of the main database). */ eMode = db->dfltLockMode; }else{ Pager *pPager; if( pId2->n==0 ){ /* This indicates that no database name was specified as part ** of the PRAGMA command. In this case the locking-mode must be ** set on all attached databases, as well as the main db file. ** ** Also, the sqlite3.dfltLockMode variable is set so that ** any subsequently attached databases also use the specified ** locking mode. */ int ii; assert(pDb==&db->aDb[0]); for(ii=2; ii<db->nDb; ii++){ pPager = sqlite3BtreePager(db->aDb[ii].pBt); sqlite3PagerLockingMode(pPager, eMode); } db->dfltLockMode = (u8)eMode; } pPager = sqlite3BtreePager(pDb->pBt); eMode = sqlite3PagerLockingMode(pPager, eMode); } assert( eMode==PAGER_LOCKINGMODE_NORMAL || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ zRet = "exclusive"; } returnSingleText(v, zRet); break; } /* ** PRAGMA [schema.]journal_mode ** PRAGMA [schema.]journal_mode = ** (delete|persist|off|truncate|memory|wal|off) */ case PragTyp_JOURNAL_MODE: { int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ int ii; /* Loop counter */ if( zRight==0 ){ /* If there is no "=MODE" part of the pragma, do a query for the ** current mode */ eMode = PAGER_JOURNALMODE_QUERY; }else{ const char *zMode; int n = sqlite3Strlen30(zRight); for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; } if( !zMode ){ /* If the "=MODE" part does not match any known journal mode, ** then do a query */ eMode = PAGER_JOURNALMODE_QUERY; } } if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ iDb = 0; pId2->n = 1; } for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3VdbeUsesBtree(v, ii); sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); } } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); break; } /* ** PRAGMA [schema.]journal_size_limit ** PRAGMA [schema.]journal_size_limit=N ** ** Get or set the size limit on rollback journal files. */ case PragTyp_JOURNAL_SIZE_LIMIT: { Pager *pPager = sqlite3BtreePager(pDb->pBt); i64 iLimit = -2; if( zRight ){ sqlite3DecOrHexToI64(zRight, &iLimit); if( iLimit<-1 ) iLimit = -1; } iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); returnSingleInt(v, iLimit); break; } #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ /* ** PRAGMA [schema.]auto_vacuum ** PRAGMA [schema.]auto_vacuum=N ** ** Get or set the value of the database 'auto-vacuum' parameter. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL */ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_AUTO_VACUUM: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt)); }else{ int eAuto = getAutoVacuum(zRight); assert( eAuto>=0 && eAuto<=2 ); db->nextAutovac = (u8)eAuto; /* Call SetAutoVacuum() to set initialize the internal auto and ** incr-vacuum flags. This is required in case this connection ** creates the database file. It is important that it is created ** as an auto-vacuum capable db. */ rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ /* When setting the auto_vacuum mode to either "full" or ** "incremental", write the value of meta[6] in the database ** file. Before writing to meta[6], check that meta[3] indicates ** that this really is an auto-vacuum capable database. */ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList setMeta6[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, { OP_If, 1, 0, 0}, /* 2 */ { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */ }; VdbeOp *aOp; int iAddr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[2].p2 = iAddr+4; aOp[4].p1 = iDb; aOp[4].p3 = eAuto - 1; sqlite3VdbeUsesBtree(v, iDb); } } break; } #endif /* ** PRAGMA [schema.]incremental_vacuum(N) ** ** Do N steps of incremental vacuuming on a database. */ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_INCREMENTAL_VACUUM: { int iLimit, addr; if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ iLimit = 0x7fffffff; } sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); sqlite3VdbeAddOp1(v, OP_ResultRow, 1); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr); break; } #endif #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** PRAGMA [schema.]cache_size ** PRAGMA [schema.]cache_size=N ** ** The first form reports the current local setting for the ** page cache size. The second form sets the local ** page cache size value. If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. */ case PragTyp_CACHE_SIZE: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, pDb->pSchema->cache_size); }else{ int size = sqlite3Atoi(zRight); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } /* ** PRAGMA [schema.]cache_spill ** PRAGMA cache_spill=BOOLEAN ** PRAGMA [schema.]cache_spill=N ** ** The first form reports the current local setting for the ** page cache spill size. The second form turns cache spill on ** or off. When turnning cache spill on, the size is set to the ** current cache_size. The third form sets a spill size that ** may be different form the cache size. ** If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. ** ** If the number of cache_spill pages is less then the number of ** cache_size pages, no spilling occurs until the page count exceeds ** the number of cache_size pages. ** ** The cache_spill=BOOLEAN setting applies to all attached schemas, ** not just the schema specified. */ case PragTyp_CACHE_SPILL: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, (db->flags & SQLITE_CacheSpill)==0 ? 0 : sqlite3BtreeSetSpillSize(pDb->pBt,0)); }else{ int size = 1; if( sqlite3GetInt32(zRight, &size) ){ sqlite3BtreeSetSpillSize(pDb->pBt, size); } if( sqlite3GetBoolean(zRight, size!=0) ){ db->flags |= SQLITE_CacheSpill; }else{ db->flags &= ~SQLITE_CacheSpill; } setAllPagerFlags(db); } break; } /* ** PRAGMA [schema.]mmap_size(N) ** ** Used to set mapping size limit. The mapping size limit is ** used to limit the aggregate size of all memory mapped regions of the ** database file. If this parameter is set to zero, then memory mapping ** is not used at all. If N is negative, then the default memory map ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. ** The parameter N is measured in bytes. ** ** This value is advisory. The underlying VFS is free to memory map ** as little or as much as it wants. Except, if N is set to 0 then the ** upper layers will never invoke the xFetch interfaces to the VFS. */ case PragTyp_MMAP_SIZE: { sqlite3_int64 sz; #if SQLITE_MAX_MMAP_SIZE>0 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( zRight ){ int ii; sqlite3DecOrHexToI64(zRight, &sz); if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; if( pId2->n==0 ) db->szMmap = sz; for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); } } } sz = -1; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); #else sz = 0; rc = SQLITE_OK; #endif if( rc==SQLITE_OK ){ returnSingleInt(v, sz); }else if( rc!=SQLITE_NOTFOUND ){ pParse->nErr++; pParse->rc = rc; } break; } /* ** PRAGMA temp_store ** PRAGMA temp_store = "default"|"memory"|"file" ** ** Return or set the local value of the temp_store flag. Changing ** the local value does not make changes to the disk file and the default ** value will be restored the next time the database is opened. ** ** Note that it is possible for the library compile-time options to ** override this setting */ case PragTyp_TEMP_STORE: { if( !zRight ){ returnSingleInt(v, db->temp_store); }else{ changeTempStorage(pParse, zRight); } break; } /* ** PRAGMA temp_store_directory ** PRAGMA temp_store_directory = ""|"directory_name" ** ** Return or set the local value of the temp_store_directory flag. Changing ** the value sets a specific directory to be used for temporary files. ** Setting to a null string reverts to the default temporary directory search. ** If temporary directory is changed, then invalidateTempStorage. ** */ case PragTyp_TEMP_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, sqlite3_temp_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, "not a writable directory"); goto pragma_out; } } if( SQLITE_TEMP_STORE==0 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) || (SQLITE_TEMP_STORE==2 && db->temp_store==1) ){ invalidateTempStorage(pParse); } sqlite3_free(sqlite3_temp_directory); if( zRight[0] ){ sqlite3_temp_directory = sqlite3_mprintf("%s", zRight); }else{ sqlite3_temp_directory = 0; } #endif /* SQLITE_OMIT_WSD */ } break; } #if SQLITE_OS_WIN /* ** PRAGMA data_store_directory ** PRAGMA data_store_directory = ""|"directory_name" ** ** Return or set the local value of the data_store_directory flag. Changing ** the value sets a specific directory to be used for database files that ** were specified with a relative pathname. Setting to a null string reverts ** to the default database directory, which for database files specified with ** a relative path will probably be based on the current directory for the ** process. Database file specified with an absolute path are not impacted ** by this setting, regardless of its value. ** */ case PragTyp_DATA_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, sqlite3_data_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, "not a writable directory"); goto pragma_out; } } sqlite3_free(sqlite3_data_directory); if( zRight[0] ){ sqlite3_data_directory = sqlite3_mprintf("%s", zRight); }else{ sqlite3_data_directory = 0; } #endif /* SQLITE_OMIT_WSD */ } break; } #endif #if SQLITE_ENABLE_LOCKING_STYLE /* ** PRAGMA [schema.]lock_proxy_file ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path" ** ** Return or set the value of the lock_proxy_file flag. Changing ** the value sets a specific file to be used for database access locks. ** */ case PragTyp_LOCK_PROXY_FILE: { if( !zRight ){ Pager *pPager = sqlite3BtreePager(pDb->pBt); char *proxy_file_path = NULL; sqlite3_file *pFile = sqlite3PagerFile(pPager); sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, &proxy_file_path); returnSingleText(v, proxy_file_path); }else{ Pager *pPager = sqlite3BtreePager(pDb->pBt); sqlite3_file *pFile = sqlite3PagerFile(pPager); int res; if( zRight[0] ){ res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, zRight); } else { res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, NULL); } if( res!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, "failed to set lock proxy file"); goto pragma_out; } } break; } #endif /* SQLITE_ENABLE_LOCKING_STYLE */ /* ** PRAGMA [schema.]synchronous ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA ** ** Return or set the local value of the synchronous flag. Changing ** the local value does not make changes to the disk file and the ** default value will be restored the next time the database is ** opened. */ case PragTyp_SYNCHRONOUS: { if( !zRight ){ returnSingleInt(v, pDb->safety_level-1); }else{ if( !db->autoCommit ){ sqlite3ErrorMsg(pParse, "Safety level may not be changed inside a transaction"); }else{ int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; if( iLevel==0 ) iLevel = 1; pDb->safety_level = iLevel; pDb->bSyncSet = 1; setAllPagerFlags(db); } } break; } #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ #ifndef SQLITE_OMIT_FLAG_PRAGMAS case PragTyp_FLAG: { if( zRight==0 ){ setPragmaResultColumnNames(v, pPragma); returnSingleInt(v, (db->flags & pPragma->iArg)!=0 ); }else{ int mask = pPragma->iArg; /* Mask of bits to set or clear. */ if( db->autoCommit==0 ){ /* Foreign key support may not be enabled or disabled while not ** in auto-commit mode. */ mask &= ~(SQLITE_ForeignKeys); } #if SQLITE_USER_AUTHENTICATION if( db->auth.authLevel==UAUTH_User ){ /* Do not allow non-admin users to modify the schema arbitrarily */ mask &= ~(SQLITE_WriteSchema); } #endif if( sqlite3GetBoolean(zRight, 0) ){ db->flags |= mask; }else{ db->flags &= ~mask; if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; } /* Many of the flag-pragmas modify the code generated by the SQL ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. */ sqlite3VdbeAddOp0(v, OP_Expire); setAllPagerFlags(db); } break; } #endif /* SQLITE_OMIT_FLAG_PRAGMAS */ #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS /* ** PRAGMA table_info(<table>) ** ** Return a single row for each column of the named table. The columns of ** the returned data set are: ** ** cid: Column id (numbered from left to right, starting at 0) ** name: Column name ** type: Column declaration type. ** notnull: True if 'NOT NULL' is part of column declaration ** dflt_value: The default value for the column, if any. */ case PragTyp_TABLE_INFO: if( zRight ){ Table *pTab; pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab ){ int i, k; int nHidden = 0; Column *pCol; Index *pPk = sqlite3PrimaryKeyIndex(pTab); pParse->nMem = 6; sqlite3CodeVerifySchema(pParse, iDb); sqlite3ViewGetColumnNames(pParse, pTab); for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ if( IsHiddenColumn(pCol) ){ nHidden++; continue; } if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ k = 0; }else if( pPk==0 ){ k = 1; }else{ for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){} } assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN ); sqlite3VdbeMultiLoad(v, 1, "issisi", i-nHidden, pCol->zName, sqlite3ColumnType(pCol,""), pCol->notNull ? 1 : 0, pCol->pDflt ? pCol->pDflt->u.zToken : 0, k); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6); } } } break; case PragTyp_STATS: { Index *pIdx; HashElem *i; pParse->nMem = 4; sqlite3CodeVerifySchema(pParse, iDb); for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); sqlite3VdbeMultiLoad(v, 1, "ssii", pTab->zName, 0, pTab->szTabRow, pTab->nRowLogEst); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ sqlite3VdbeMultiLoad(v, 2, "sii", pIdx->zName, pIdx->szIdxRow, pIdx->aiRowLogEst[0]); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); } } } break; case PragTyp_INDEX_INFO: if( zRight ){ Index *pIdx; Table *pTab; pIdx = sqlite3FindIndex(db, zRight, zDb); if( pIdx ){ int i; int mx; if( pPragma->iArg ){ /* PRAGMA index_xinfo (newer version with more rows and columns) */ mx = pIdx->nColumn; pParse->nMem = 6; }else{ /* PRAGMA index_info (legacy version) */ mx = pIdx->nKeyCol; pParse->nMem = 3; } pTab = pIdx->pTable; sqlite3CodeVerifySchema(pParse, iDb); assert( pParse->nMem<=pPragma->nPragCName ); for(i=0; i<mx; i++){ i16 cnum = pIdx->aiColumn[i]; sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum, cnum<0 ? 0 : pTab->aCol[cnum].zName); if( pPragma->iArg ){ sqlite3VdbeMultiLoad(v, 4, "isi", pIdx->aSortOrder[i], pIdx->azColl[i], i<pIdx->nKeyCol); } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); } } } break; case PragTyp_INDEX_LIST: if( zRight ){ Index *pIdx; Table *pTab; int i; pTab = sqlite3FindTable(db, zRight, zDb); if( pTab ){ pParse->nMem = 5; sqlite3CodeVerifySchema(pParse, iDb); for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ const char *azOrigin[] = { "c", "u", "pk" }; sqlite3VdbeMultiLoad(v, 1, "isisi", i, pIdx->zName, IsUniqueIndex(pIdx), azOrigin[pIdx->idxType], pIdx->pPartIdxWhere!=0); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); } } } break; case PragTyp_DATABASE_LIST: { int i; pParse->nMem = 3; for(i=0; i<db->nDb; i++){ if( db->aDb[i].pBt==0 ) continue; assert( db->aDb[i].zDbSName!=0 ); sqlite3VdbeMultiLoad(v, 1, "iss", i, db->aDb[i].zDbSName, sqlite3BtreeGetFilename(db->aDb[i].pBt)); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } } break; case PragTyp_COLLATION_LIST: { int i = 0; HashElem *p; pParse->nMem = 2; for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ CollSeq *pColl = (CollSeq *)sqliteHashData(p); sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); } } break; #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ #ifndef SQLITE_OMIT_FOREIGN_KEY case PragTyp_FOREIGN_KEY_LIST: if( zRight ){ FKey *pFK; Table *pTab; pTab = sqlite3FindTable(db, zRight, zDb); if( pTab ){ pFK = pTab->pFKey; if( pFK ){ int i = 0; pParse->nMem = 8; sqlite3CodeVerifySchema(pParse, iDb); while(pFK){ int j; for(j=0; j<pFK->nCol; j++){ sqlite3VdbeMultiLoad(v, 1, "iissssss", i, j, pFK->zTo, pTab->aCol[pFK->aCol[j].iFrom].zName, pFK->aCol[j].zCol, actionName(pFK->aAction[1]), /* ON UPDATE */ actionName(pFK->aAction[0]), /* ON DELETE */ "NONE"); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8); } ++i; pFK = pFK->pNextFrom; } } } } break; #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ #ifndef SQLITE_OMIT_FOREIGN_KEY #ifndef SQLITE_OMIT_TRIGGER case PragTyp_FOREIGN_KEY_CHECK: { FKey *pFK; /* A foreign key constraint */ Table *pTab; /* Child table contain "REFERENCES" keyword */ Table *pParent; /* Parent table that child points to */ Index *pIdx; /* Index in the parent table */ int i; /* Loop counter: Foreign key number for pTab */ int j; /* Loop counter: Field of the foreign key */ HashElem *k; /* Loop counter: Next table in schema */ int x; /* result variable */ int regResult; /* 3 registers to hold a result row */ int regKey; /* Register to hold key for checking the FK */ int regRow; /* Registers to hold a row from pTab */ int addrTop; /* Top of a loop checking foreign keys */ int addrOk; /* Jump here if the key is OK */ int *aiCols; /* child to parent column mapping */ regResult = pParse->nMem+1; pParse->nMem += 4; regKey = ++pParse->nMem; regRow = ++pParse->nMem; sqlite3CodeVerifySchema(pParse, iDb); k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); while( k ){ if( zRight ){ pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); k = 0; }else{ pTab = (Table*)sqliteHashData(k); k = sqliteHashNext(k); } if( pTab==0 || pTab->pFKey==0 ) continue; sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead); sqlite3VdbeLoadString(v, regResult, pTab->zName); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); if( pParent==0 ) continue; pIdx = 0; sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName); x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); if( x==0 ){ if( pIdx==0 ){ sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead); }else{ sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); } }else{ k = 0; break; } } assert( pParse->nErr>0 || pFK==0 ); if( pFK ) break; if( pParse->nTab<i ) pParse->nTab = i; addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); pIdx = 0; aiCols = 0; if( pParent ){ x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); assert( x==0 ); } addrOk = sqlite3VdbeMakeLabel(v); if( pParent && pIdx==0 ){ int iKey = pFK->aCol[0].iFrom; assert( iKey>=0 && iKey<pTab->nCol ); if( iKey!=pTab->iPKey ){ sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow); sqlite3ColumnDefault(v, pTab, iKey, regRow); sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v); }else{ sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow); } sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v); sqlite3VdbeGoto(v, addrOk); sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); }else{ for(j=0; j<pFK->nCol; j++){ sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j); sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); } if( pParent ){ sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, sqlite3IndexAffinityStr(db,pIdx), pFK->nCol); sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); VdbeCoverage(v); } } sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1); sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); sqlite3VdbeResolveLabel(v, addrOk); sqlite3DbFree(db, aiCols); } sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrTop); } } break; #endif /* !defined(SQLITE_OMIT_TRIGGER) */ #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ #ifndef NDEBUG case PragTyp_PARSER_TRACE: { if( zRight ){ if( sqlite3GetBoolean(zRight, 0) ){ sqlite3ParserTrace(stdout, "parser: "); }else{ sqlite3ParserTrace(0, 0); } } } break; #endif /* Reinstall the LIKE and GLOB functions. The variant of LIKE ** used will be case sensitive or not depending on the RHS. */ case PragTyp_CASE_SENSITIVE_LIKE: { if( zRight ){ sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); } } break; #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 #endif #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* Pragma "quick_check" is reduced version of ** integrity_check designed to detect most database corruption ** without most of the overhead of a full integrity-check. */ case PragTyp_INTEGRITY_CHECK: { int i, j, addr, mxErr; int isQuick = (sqlite3Tolower(zLeft[0])=='q'); /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check", ** then iDb is set to the index of the database identified by <db>. ** In this case, the integrity of database iDb only is verified by ** the VDBE created below. ** ** Otherwise, if the command was simply "PRAGMA integrity_check" (or ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb ** to -1 here, to indicate that the VDBE should verify the integrity ** of all attached databases. */ assert( iDb>=0 ); assert( iDb==0 || pId2->z ); if( pId2->z==0 ) iDb = -1; /* Initialize the VDBE program */ pParse->nMem = 6; /* Set the maximum error count */ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; if( zRight ){ sqlite3GetInt32(zRight, &mxErr); if( mxErr<=0 ){ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */ /* Do an integrity check on each database file */ for(i=0; i<db->nDb; i++){ HashElem *x; Hash *pTbls; int *aRoot; int cnt = 0; int mxIdx = 0; int nIdx; if( OMIT_TEMPDB && i==1 ) continue; if( iDb>=0 && i!=iDb ) continue; sqlite3CodeVerifySchema(pParse, i); addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */ VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); /* Do an integrity check of the B-Tree ** ** Begin by finding the root pages numbers ** for all tables and indices in the database. */ assert( sqlite3SchemaMutexHeld(db, i, 0) ); pTbls = &db->aDb[i].pSchema->tblHash; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; if( HasRowid(pTab) ) cnt++; for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } if( nIdx>mxIdx ) mxIdx = nIdx; } aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); if( aRoot==0 ) break; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ aRoot[cnt++] = pIdx->tnum; } } aRoot[cnt] = 0; /* Make sure sufficient number of registers have been allocated */ pParse->nMem = MAX( pParse->nMem, 8+mxIdx ); /* Do the b-tree integrity checks */ sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); sqlite3VdbeChangeP5(v, (u8)i); addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName), P4_DYNAMIC); sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2); sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1); sqlite3VdbeJumpHere(v, addr); /* Make sure all the indices are constructed correctly. */ for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx, *pPk; Index *pPrior = 0; int loopTop; int iDataCur, iIdxCur; int r1 = -1; if( pTab->pIndex==0 ) continue; pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */ VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); sqlite3ExprCacheClear(pParse); sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, 1, 0, &iDataCur, &iIdxCur); sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */ } assert( pParse->nMem>=8+j ); assert( sqlite3NoTempsInRange(pParse,1,7+j) ); sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); /* Verify that all NOT NULL columns really are NOT NULL */ for(j=0; j<pTab->nCol; j++){ char *zErr; int jmp2, jmp3; if( j==pTab->iPKey ) continue; if( pTab->aCol[j].notNull==0 ) continue; sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName, pTab->aCol[j].zName); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v); sqlite3VdbeAddOp0(v, OP_Halt); sqlite3VdbeJumpHere(v, jmp2); sqlite3VdbeJumpHere(v, jmp3); } /* Validate index entries for the current row */ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int jmp2, jmp3, jmp4, jmp5; int ckUniq = sqlite3VdbeMakeLabel(v); if( pPk==pIdx ) continue; r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, pPrior, r1); pPrior = pIdx; sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */ /* Verify that an index entry exists for the current table row */ jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, pIdx->nColumn); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ sqlite3VdbeLoadString(v, 3, "row "); sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); sqlite3VdbeLoadString(v, 4, " missing from index "); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v); sqlite3VdbeAddOp0(v, OP_Halt); sqlite3VdbeJumpHere(v, jmp2); /* For UNIQUE indexes, verify that only one entry exists with the ** current key. The entry is unique if (1) any column is NULL ** or (2) the next entry has a different key */ if( IsUniqueIndex(pIdx) ){ int uniqOk = sqlite3VdbeMakeLabel(v); int jmp6; int kk; for(kk=0; kk<pIdx->nKeyCol; kk++){ int iCol = pIdx->aiColumn[kk]; assert( iCol!=XN_ROWID && iCol<pTab->nCol ); if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); VdbeCoverage(v); } jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); sqlite3VdbeGoto(v, uniqOk); sqlite3VdbeJumpHere(v, jmp6); sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, pIdx->nKeyCol); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ sqlite3VdbeLoadString(v, 3, "non-unique entry in index "); sqlite3VdbeGoto(v, jmp5); sqlite3VdbeResolveLabel(v, uniqOk); } sqlite3VdbeJumpHere(v, jmp4); sqlite3ResolvePartIdxLabel(pParse, jmp3); } sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); sqlite3VdbeJumpHere(v, loopTop-1); #ifndef SQLITE_OMIT_BTREECOUNT sqlite3VdbeLoadString(v, 2, "wrong # of entries in index "); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ if( pPk==pIdx ) continue; addr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); sqlite3VdbeLoadString(v, 3, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7); sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1); } #endif /* SQLITE_OMIT_BTREECOUNT */ } } { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList endCode[] = { { OP_AddImm, 1, 0, 0}, /* 0 */ { OP_If, 1, 4, 0}, /* 1 */ { OP_String8, 0, 3, 0}, /* 2 */ { OP_ResultRow, 3, 1, 0}, /* 3 */ }; VdbeOp *aOp; aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); if( aOp ){ aOp[0].p2 = -mxErr; aOp[2].p4type = P4_STATIC; aOp[2].p4.z = "ok"; } } } break; #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ #ifndef SQLITE_OMIT_UTF16 /* ** PRAGMA encoding ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" ** ** In its first form, this pragma returns the encoding of the main ** database. If the database is not initialized, it is initialized now. ** ** The second form of this pragma is a no-op if the main database file ** has not already been initialized. In this case it sets the default ** encoding that will be used for the main database file if a new file ** is created. If an existing main database file is opened, then the ** default text encoding for the existing database is used. ** ** In all cases new databases created using the ATTACH command are ** created to use the same default text encoding as the main database. If ** the main database has not been initialized and/or created when ATTACH ** is executed, this is done before the ATTACH operation. ** ** In the second form this pragma sets the text encoding to be used in ** new database files created using this database handle. It is only ** useful if invoked immediately after the main database i */ case PragTyp_ENCODING: { static const struct EncName { char *zName; u8 enc; } encnames[] = { { "UTF8", SQLITE_UTF8 }, { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */ { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */ { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */ { "UTF16le", SQLITE_UTF16LE }, { "UTF16be", SQLITE_UTF16BE }, { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */ { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */ { 0, 0 } }; const struct EncName *pEnc; if( !zRight ){ /* "PRAGMA encoding" */ if( sqlite3ReadSchema(pParse) ) goto pragma_out; assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); returnSingleText(v, encnames[ENC(pParse->db)].zName); }else{ /* "PRAGMA encoding = XXX" */ /* Only change the value of sqlite.enc if the database handle is not ** initialized. If the main database exists, the new sqlite.enc value ** will be overwritten when the schema is next loaded. If it does not ** already exists, it will be created to use the new encoding value. */ if( !(DbHasProperty(db, 0, DB_SchemaLoaded)) || DbHasProperty(db, 0, DB_Empty) ){ for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ SCHEMA_ENC(db) = ENC(db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; break; } } if( !pEnc->zName ){ sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); } } } } break; #endif /* SQLITE_OMIT_UTF16 */ #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS /* ** PRAGMA [schema.]schema_version ** PRAGMA [schema.]schema_version = <integer> ** ** PRAGMA [schema.]user_version ** PRAGMA [schema.]user_version = <integer> ** ** PRAGMA [schema.]freelist_count ** ** PRAGMA [schema.]data_version ** ** PRAGMA [schema.]application_id ** PRAGMA [schema.]application_id = <integer> ** ** The pragma's schema_version and user_version are used to set or get ** the value of the schema-version and user-version, respectively. Both ** the schema-version and the user-version are 32-bit signed integers ** stored in the database header. ** ** The schema-cookie is usually only manipulated internally by SQLite. It ** is incremented by SQLite whenever the database schema is modified (by ** creating or dropping a table or index). The schema version is used by ** SQLite each time a query is executed to ensure that the internal cache ** of the schema used when compiling the SQL query matches the schema of ** the database against which the compiled query is actually executed. ** Subverting this mechanism by using "PRAGMA schema_version" to modify ** the schema-version is potentially dangerous and may lead to program ** crashes or database corruption. Use with caution! ** ** The user-version is not used internally by SQLite. It may be used by ** applications for any purpose. */ case PragTyp_HEADER_VALUE: { int iCookie = pPragma->iArg; /* Which cookie to read or write */ sqlite3VdbeUsesBtree(v, iDb); if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){ /* Write the specified cookie value */ static const VdbeOpList setCookie[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ { OP_SetCookie, 0, 0, 0}, /* 1 */ }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p2 = iCookie; aOp[1].p3 = sqlite3Atoi(zRight); }else{ /* Read the specified cookie value */ static const VdbeOpList readCookie[] = { { OP_Transaction, 0, 0, 0}, /* 0 */ { OP_ReadCookie, 0, 1, 0}, /* 1 */ { OP_ResultRow, 1, 1, 0} }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p3 = iCookie; sqlite3VdbeReusable(v); } } break; #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* ** PRAGMA compile_options ** ** Return the names of all compile-time options used in this build, ** one option per row. */ case PragTyp_COMPILE_OPTIONS: { int i = 0; const char *zOpt; pParse->nMem = 1; while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ sqlite3VdbeLoadString(v, 1, zOpt); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } sqlite3VdbeReusable(v); } break; #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ #ifndef SQLITE_OMIT_WAL /* ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate ** ** Checkpoint the database. */ case PragTyp_WAL_CHECKPOINT: { int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); int eMode = SQLITE_CHECKPOINT_PASSIVE; if( zRight ){ if( sqlite3StrICmp(zRight, "full")==0 ){ eMode = SQLITE_CHECKPOINT_FULL; }else if( sqlite3StrICmp(zRight, "restart")==0 ){ eMode = SQLITE_CHECKPOINT_RESTART; }else if( sqlite3StrICmp(zRight, "truncate")==0 ){ eMode = SQLITE_CHECKPOINT_TRUNCATE; } } pParse->nMem = 3; sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } break; /* ** PRAGMA wal_autocheckpoint ** PRAGMA wal_autocheckpoint = N ** ** Configure a database connection to automatically checkpoint a database ** after accumulating N frames in the log. Or query for the current value ** of N. */ case PragTyp_WAL_AUTOCHECKPOINT: { if( zRight ){ sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); } returnSingleInt(v, db->xWalCallback==sqlite3WalDefaultHook ? SQLITE_PTR_TO_INT(db->pWalArg) : 0); } break; #endif /* ** PRAGMA shrink_memory ** ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database ** connection on which it is invoked to free up as much memory as it ** can, by calling sqlite3_db_release_memory(). */ case PragTyp_SHRINK_MEMORY: { sqlite3_db_release_memory(db); break; } /* ** PRAGMA busy_timeout ** PRAGMA busy_timeout = N ** ** Call sqlite3_busy_timeout(db, N). Return the current timeout value ** if one is set. If no busy handler or a different busy handler is set ** then 0 is returned. Setting the busy_timeout to 0 or negative ** disables the timeout. */ /*case PragTyp_BUSY_TIMEOUT*/ default: { assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); if( zRight ){ sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); } returnSingleInt(v, db->busyTimeout); break; } /* ** PRAGMA soft_heap_limit ** PRAGMA soft_heap_limit = N ** ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the ** sqlite3_soft_heap_limit64() interface with the argument N, if N is ** specified and is a non-negative integer. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always ** returns the same integer that would be returned by the ** sqlite3_soft_heap_limit64(-1) C-language function. */ case PragTyp_SOFT_HEAP_LIMIT: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ sqlite3_soft_heap_limit64(N); } returnSingleInt(v, sqlite3_soft_heap_limit64(-1)); break; } /* ** PRAGMA threads ** PRAGMA threads = N ** ** Configure the maximum number of worker threads. Return the new ** maximum, which might be less than requested. */ case PragTyp_THREADS: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK && N>=0 ){ sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); } returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); break; } #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* ** Report the current state of file logs for all databases */ case PragTyp_LOCK_STATUS: { static const char *const azLockName[] = { "unlocked", "shared", "reserved", "pending", "exclusive" }; int i; pParse->nMem = 2; for(i=0; i<db->nDb; i++){ Btree *pBt; const char *zState = "unknown"; int j; if( db->aDb[i].zDbSName==0 ) continue; pBt = db->aDb[i].pBt; if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ zState = "closed"; }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ zState = azLockName[j]; } sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); } break; } #endif #ifdef SQLITE_HAS_CODEC case PragTyp_KEY: { if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); break; } case PragTyp_REKEY: { if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); break; } case PragTyp_HEXKEY: { if( zRight ){ u8 iByte; int i; char zKey[40]; for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){ iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]); if( (i&1)!=0 ) zKey[i/2] = iByte; } if( (zLeft[3] & 0xf)==0xb ){ sqlite3_key_v2(db, zDb, zKey, i/2); }else{ sqlite3_rekey_v2(db, zDb, zKey, i/2); } } break; } #endif #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){ #ifdef SQLITE_HAS_CODEC if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){ sqlite3_activate_see(&zRight[4]); } #endif #ifdef SQLITE_ENABLE_CEROD if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ sqlite3_activate_cerod(&zRight[6]); } #endif } break; #endif } /* End of the PRAGMA switch */ /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only ** purpose is to execute assert() statements to verify that if the ** PragFlg_NoColumns1 flag is set and the caller specified an argument ** to the PRAGMA, the implementation has not added any OP_ResultRow ** instructions to the VM. */ if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){ sqlite3VdbeVerifyNoResultRow(v); } pragma_out: sqlite3DbFree(db, zLeft); sqlite3DbFree(db, zRight); } #ifndef SQLITE_OMIT_VIRTUALTABLE /***************************************************************************** ** Implementation of an eponymous virtual table that runs a pragma. ** */ typedef struct PragmaVtab PragmaVtab; typedef struct PragmaVtabCursor PragmaVtabCursor; struct PragmaVtab { sqlite3_vtab base; /* Base class. Must be first */ sqlite3 *db; /* The database connection to which it belongs */ const PragmaName *pName; /* Name of the pragma */ u8 nHidden; /* Number of hidden columns */ u8 iHidden; /* Index of the first hidden column */ }; struct PragmaVtabCursor { sqlite3_vtab_cursor base; /* Base class. Must be first */ sqlite3_stmt *pPragma; /* The pragma statement to run */ sqlite_int64 iRowid; /* Current rowid */ char *azArg[2]; /* Value of the argument and schema */ }; /* ** Pragma virtual table module xConnect method. */ static int pragmaVtabConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ const PragmaName *pPragma = (const PragmaName*)pAux; PragmaVtab *pTab = 0; int rc; int i, j; char cSep = '('; StrAccum acc; char zBuf[200]; UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x"); for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){ sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]); cSep = ','; } if( i==0 ){ sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName); cSep = ','; i++; } j = 0; if( pPragma->mPragFlg & PragFlg_Result1 ){ sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN"); j++; } if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){ sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN"); j++; } sqlite3StrAccumAppend(&acc, ")", 1); sqlite3StrAccumFinish(&acc); assert( strlen(zBuf) < sizeof(zBuf)-1 ); rc = sqlite3_declare_vtab(db, zBuf); if( rc==SQLITE_OK ){ pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab)); if( pTab==0 ){ rc = SQLITE_NOMEM; }else{ memset(pTab, 0, sizeof(PragmaVtab)); pTab->pName = pPragma; pTab->db = db; pTab->iHidden = i; pTab->nHidden = j; } }else{ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } *ppVtab = (sqlite3_vtab*)pTab; return rc; } /* ** Pragma virtual table module xDisconnect method. */ static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){ PragmaVtab *pTab = (PragmaVtab*)pVtab; sqlite3_free(pTab); return SQLITE_OK; } /* Figure out the best index to use to search a pragma virtual table. ** ** There are not really any index choices. But we want to encourage the ** query planner to give == constraints on as many hidden parameters as ** possible, and especially on the first hidden parameter. So return a ** high cost if hidden parameters are unconstrained. */ static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ PragmaVtab *pTab = (PragmaVtab*)tab; const struct sqlite3_index_constraint *pConstraint; int i, j; int seen[2]; pIdxInfo->estimatedCost = (double)1; if( pTab->nHidden==0 ){ return SQLITE_OK; } pConstraint = pIdxInfo->aConstraint; seen[0] = 0; seen[1] = 0; for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ if( pConstraint->usable==0 ) continue; if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; if( pConstraint->iColumn < pTab->iHidden ) continue; j = pConstraint->iColumn - pTab->iHidden; assert( j < 2 ); seen[j] = i+1; } if( seen[0]==0 ){ pIdxInfo->estimatedCost = (double)2147483647; pIdxInfo->estimatedRows = 2147483647; return SQLITE_OK; } j = seen[0]-1; pIdxInfo->aConstraintUsage[j].argvIndex = 1; pIdxInfo->aConstraintUsage[j].omit = 1; if( seen[1]==0 ) return SQLITE_OK; pIdxInfo->estimatedCost = (double)20; pIdxInfo->estimatedRows = 20; j = seen[1]-1; pIdxInfo->aConstraintUsage[j].argvIndex = 2; pIdxInfo->aConstraintUsage[j].omit = 1; return SQLITE_OK; } /* Create a new cursor for the pragma virtual table */ static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){ PragmaVtabCursor *pCsr; pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr)); if( pCsr==0 ) return SQLITE_NOMEM; memset(pCsr, 0, sizeof(PragmaVtabCursor)); pCsr->base.pVtab = pVtab; *ppCursor = &pCsr->base; return SQLITE_OK; } /* Clear all content from pragma virtual table cursor. */ static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){ int i; sqlite3_finalize(pCsr->pPragma); pCsr->pPragma = 0; for(i=0; i<ArraySize(pCsr->azArg); i++){ sqlite3_free(pCsr->azArg[i]); pCsr->azArg[i] = 0; } } /* Close a pragma virtual table cursor */ static int pragmaVtabClose(sqlite3_vtab_cursor *cur){ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur; pragmaVtabCursorClear(pCsr); sqlite3_free(pCsr); return SQLITE_OK; } /* Advance the pragma virtual table cursor to the next row */ static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; int rc = SQLITE_OK; /* Increment the xRowid value */ pCsr->iRowid++; assert( pCsr->pPragma ); if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){ rc = sqlite3_finalize(pCsr->pPragma); pCsr->pPragma = 0; pragmaVtabCursorClear(pCsr); } return rc; } /* ** Pragma virtual table module xFilter method. */ static int pragmaVtabFilter( sqlite3_vtab_cursor *pVtabCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab); int rc; int i, j; StrAccum acc; char *zSql; UNUSED_PARAMETER(idxNum); UNUSED_PARAMETER(idxStr); pragmaVtabCursorClear(pCsr); j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1; for(i=0; i<argc; i++, j++){ assert( j<ArraySize(pCsr->azArg) ); pCsr->azArg[j] = sqlite3_mprintf("%s", sqlite3_value_text(argv[i])); if( pCsr->azArg[j]==0 ){ return SQLITE_NOMEM; } } sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]); sqlite3StrAccumAppendAll(&acc, "PRAGMA "); if( pCsr->azArg[1] ){ sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]); } sqlite3StrAccumAppendAll(&acc, pTab->pName->zName); if( pCsr->azArg[0] ){ sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]); } zSql = sqlite3StrAccumFinish(&acc); if( zSql==0 ) return SQLITE_NOMEM; rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0); sqlite3_free(zSql); if( rc!=SQLITE_OK ){ pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); return rc; } return pragmaVtabNext(pVtabCursor); } /* ** Pragma virtual table module xEof method. */ static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; return (pCsr->pPragma==0); } /* The xColumn method simply returns the corresponding column from ** the PRAGMA. */ static int pragmaVtabColumn( sqlite3_vtab_cursor *pVtabCursor, sqlite3_context *ctx, int i ){ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab); if( i<pTab->iHidden ){ sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i)); }else{ sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT); } return SQLITE_OK; } /* ** Pragma virtual table module xRowid method. */ static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){ PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; *p = pCsr->iRowid; return SQLITE_OK; } /* The pragma virtual table object */ static const sqlite3_module pragmaVtabModule = { 0, /* iVersion */ 0, /* xCreate - create a table */ pragmaVtabConnect, /* xConnect - connect to an existing table */ pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */ pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */ 0, /* xDestroy - Drop a table */ pragmaVtabOpen, /* xOpen - open a cursor */ pragmaVtabClose, /* xClose - close a cursor */ pragmaVtabFilter, /* xFilter - configure scan constraints */ pragmaVtabNext, /* xNext - advance a cursor */ pragmaVtabEof, /* xEof */ pragmaVtabColumn, /* xColumn - read data */ pragmaVtabRowid, /* xRowid - read data */ 0, /* xUpdate - write data */ 0, /* xBegin - begin transaction */ 0, /* xSync - sync transaction */ 0, /* xCommit - commit transaction */ 0, /* xRollback - rollback transaction */ 0, /* xFindFunction - function overloading */ 0, /* xRename - rename the table */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; /* ** Check to see if zTabName is really the name of a pragma. If it is, ** then register an eponymous virtual table for that pragma and return ** a pointer to the Module object for the new virtual table. */ SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){ const PragmaName *pName; assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 ); pName = pragmaLocate(zName+7); if( pName==0 ) return 0; if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0; assert( sqlite3HashFind(&db->aModule, zName)==0 ); return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0); } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #endif /* SQLITE_OMIT_PRAGMA */ /************** End of pragma.c **********************************************/ /************** Begin file prepare.c *****************************************/ /* ** 2005 May 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation of the sqlite3_prepare() ** interface, and routines that contribute to loading the database schema ** from disk. */ /* #include "sqliteInt.h" */ /* ** Fill the InitData structure with an error message that indicates ** that the database is corrupt. */ static void corruptSchema( InitData *pData, /* Initialization context */ const char *zObj, /* Object being parsed at the point of error */ const char *zExtra /* Error information */ ){ sqlite3 *db = pData->db; if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){ char *z; if( zObj==0 ) zObj = "?"; z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj); if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra); sqlite3DbFree(db, *pData->pzErrMsg); *pData->pzErrMsg = z; } pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT; } /* ** This is the callback routine for the code that initializes the ** database. See sqlite3Init() below for additional information. ** This routine is also called from the OP_ParseSchema opcode of the VDBE. ** ** Each callback contains the following information: ** ** argv[0] = name of thing being created ** argv[1] = root page number for table or index. 0 for trigger or view. ** argv[2] = SQL text for the CREATE statement. ** */ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){ InitData *pData = (InitData*)pInit; sqlite3 *db = pData->db; int iDb = pData->iDb; assert( argc==3 ); UNUSED_PARAMETER2(NotUsed, argc); assert( sqlite3_mutex_held(db->mutex) ); DbClearProperty(db, iDb, DB_Empty); if( db->mallocFailed ){ corruptSchema(pData, argv[0], 0); return 1; } assert( iDb>=0 && iDb<db->nDb ); if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ if( argv[1]==0 ){ corruptSchema(pData, argv[0], 0); }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){ /* Call the parser to process a CREATE TABLE, INDEX or VIEW. ** But because db->init.busy is set to 1, no VDBE code is generated ** or executed. All the parser does is build the internal data ** structures that describe the table, index, or view. */ int rc; u8 saved_iDb = db->init.iDb; sqlite3_stmt *pStmt; TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ assert( db->init.busy ); db->init.iDb = iDb; db->init.newTnum = sqlite3Atoi(argv[1]); db->init.orphanTrigger = 0; TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0); rc = db->errCode; assert( (rc&0xFF)==(rcp&0xFF) ); db->init.iDb = saved_iDb; assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 ); if( SQLITE_OK!=rc ){ if( db->init.orphanTrigger ){ assert( iDb==1 ); }else{ pData->rc = rc; if( rc==SQLITE_NOMEM ){ sqlite3OomFault(db); }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){ corruptSchema(pData, argv[0], sqlite3_errmsg(db)); } } } sqlite3_finalize(pStmt); }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){ corruptSchema(pData, argv[0], 0); }else{ /* If the SQL column is blank it means this is an index that ** was created to be the PRIMARY KEY or to fulfill a UNIQUE ** constraint for a CREATE TABLE. The index should have already ** been created when we processed the CREATE TABLE. All we have ** to do here is record the root page number for that index. */ Index *pIndex; pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName); if( pIndex==0 ){ /* This can occur if there exists an index on a TEMP table which ** has the same name as another index on a permanent index. Since ** the permanent table is hidden by the TEMP table, we can also ** safely ignore the index on the permanent table. */ /* Do Nothing */; }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){ corruptSchema(pData, argv[0], "invalid rootpage"); } } return 0; } /* ** Attempt to read the database schema and initialize internal ** data structures for a single database file. The index of the ** database file is given by iDb. iDb==0 is used for the main ** database. iDb==1 should never be used. iDb>=2 is used for ** auxiliary databases. Return one of the SQLITE_ error codes to ** indicate success or failure. */ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ int rc; int i; #ifndef SQLITE_OMIT_DEPRECATED int size; #endif Db *pDb; char const *azArg[4]; int meta[5]; InitData initData; const char *zMasterName; int openedTransaction = 0; assert( iDb>=0 && iDb<db->nDb ); assert( db->aDb[iDb].pSchema ); assert( sqlite3_mutex_held(db->mutex) ); assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); /* Construct the in-memory representation schema tables (sqlite_master or ** sqlite_temp_master) by invoking the parser directly. The appropriate ** table name will be inserted automatically by the parser so we can just ** use the abbreviation "x" here. The parser will also automatically tag ** the schema table as read-only. */ azArg[0] = zMasterName = SCHEMA_TABLE(iDb); azArg[1] = "1"; azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text," "rootpage integer,sql text)"; azArg[3] = 0; initData.db = db; initData.iDb = iDb; initData.rc = SQLITE_OK; initData.pzErrMsg = pzErrMsg; sqlite3InitCallback(&initData, 3, (char **)azArg, 0); if( initData.rc ){ rc = initData.rc; goto error_out; } /* Create a cursor to hold the database open */ pDb = &db->aDb[iDb]; if( pDb->pBt==0 ){ if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){ DbSetProperty(db, 1, DB_SchemaLoaded); } return SQLITE_OK; } /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed before this function returns. */ sqlite3BtreeEnter(pDb->pBt); if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){ rc = sqlite3BtreeBeginTrans(pDb->pBt, 0); if( rc!=SQLITE_OK ){ sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc)); goto initone_error_out; } openedTransaction = 1; } /* Get the database meta information. ** ** Meta values are as follows: ** meta[0] Schema cookie. Changes with each schema change. ** meta[1] File format of schema layer. ** meta[2] Size of the page cache. ** meta[3] Largest rootpage (auto/incr_vacuum mode) ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE ** meta[5] User version ** meta[6] Incremental vacuum mode ** meta[7] unused ** meta[8] unused ** meta[9] unused ** ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to ** the possible values of meta[4]. */ for(i=0; i<ArraySize(meta); i++){ sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]); } pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1]; /* If opening a non-empty database, check the text encoding. For the ** main database, set sqlite3.enc to the encoding of the main database. ** For an attached db, it is an error if the encoding is not the same ** as sqlite3.enc. */ if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */ if( iDb==0 ){ #ifndef SQLITE_OMIT_UTF16 u8 encoding; /* If opening the main database, set ENC(db). */ encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3; if( encoding==0 ) encoding = SQLITE_UTF8; ENC(db) = encoding; #else ENC(db) = SQLITE_UTF8; #endif }else{ /* If opening an attached database, the encoding much match ENC(db) */ if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){ sqlite3SetString(pzErrMsg, db, "attached databases must use the same" " text encoding as main database"); rc = SQLITE_ERROR; goto initone_error_out; } } }else{ DbSetProperty(db, iDb, DB_Empty); } pDb->pSchema->enc = ENC(db); if( pDb->pSchema->cache_size==0 ){ #ifndef SQLITE_OMIT_DEPRECATED size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]); if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } pDb->pSchema->cache_size = size; #else pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE; #endif sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } /* ** file_format==1 Version 3.0.0. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants */ pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1]; if( pDb->pSchema->file_format==0 ){ pDb->pSchema->file_format = 1; } if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){ sqlite3SetString(pzErrMsg, db, "unsupported file format"); rc = SQLITE_ERROR; goto initone_error_out; } /* Ticket #2804: When we open a database in the newer file format, ** clear the legacy_file_format pragma flag so that a VACUUM will ** not downgrade the database and thus invalidate any descending ** indices that the user might have created. */ if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){ db->flags &= ~SQLITE_LegacyFileFmt; } /* Read the schema information out of the schema tables */ assert( db->init.busy ); { char *zSql; zSql = sqlite3MPrintf(db, "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid", db->aDb[iDb].zDbSName, zMasterName); #ifndef SQLITE_OMIT_AUTHORIZATION { sqlite3_xauth xAuth; xAuth = db->xAuth; db->xAuth = 0; #endif rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); #ifndef SQLITE_OMIT_AUTHORIZATION db->xAuth = xAuth; } #endif if( rc==SQLITE_OK ) rc = initData.rc; sqlite3DbFree(db, zSql); #ifndef SQLITE_OMIT_ANALYZE if( rc==SQLITE_OK ){ sqlite3AnalysisLoad(db, iDb); } #endif } if( db->mallocFailed ){ rc = SQLITE_NOMEM_BKPT; sqlite3ResetAllSchemasOfConnection(db); } if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){ /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider ** the schema loaded, even if errors occurred. In this situation the ** current sqlite3_prepare() operation will fail, but the following one ** will attempt to compile the supplied statement against whatever subset ** of the schema was loaded before the error occurred. The primary ** purpose of this is to allow access to the sqlite_master table ** even when its contents have been corrupted. */ DbSetProperty(db, iDb, DB_SchemaLoaded); rc = SQLITE_OK; } /* Jump here for an error that occurs after successfully allocating ** curMain and calling sqlite3BtreeEnter(). For an error that occurs ** before that point, jump to error_out. */ initone_error_out: if( openedTransaction ){ sqlite3BtreeCommit(pDb->pBt); } sqlite3BtreeLeave(pDb->pBt); error_out: if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ sqlite3OomFault(db); } return rc; } /* ** Initialize all database files - the main database file, the file ** used to store temporary tables, and any additional database files ** created using ATTACH statements. Return a success code. If an ** error occurs, write an error message into *pzErrMsg. ** ** After a database is initialized, the DB_SchemaLoaded bit is set ** bit is set in the flags field of the Db structure. If the database ** file was of zero-length, then the DB_Empty flag is also set. */ SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){ int i, rc; int commit_internal = !(db->flags&SQLITE_InternChanges); assert( sqlite3_mutex_held(db->mutex) ); assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) ); assert( db->init.busy==0 ); rc = SQLITE_OK; db->init.busy = 1; ENC(db) = SCHEMA_ENC(db); for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue; rc = sqlite3InitOne(db, i, pzErrMsg); if( rc ){ sqlite3ResetOneSchema(db, i); } } /* Once all the other databases have been initialized, load the schema ** for the TEMP database. This is loaded last, as the TEMP database ** schema may contain references to objects in other databases. */ #ifndef SQLITE_OMIT_TEMPDB assert( db->nDb>1 ); if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){ rc = sqlite3InitOne(db, 1, pzErrMsg); if( rc ){ sqlite3ResetOneSchema(db, 1); } } #endif db->init.busy = 0; if( rc==SQLITE_OK && commit_internal ){ sqlite3CommitInternalChanges(db); } return rc; } /* ** This routine is a no-op if the database schema is already initialized. ** Otherwise, the schema is loaded. An error code is returned. */ SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){ int rc = SQLITE_OK; sqlite3 *db = pParse->db; assert( sqlite3_mutex_held(db->mutex) ); if( !db->init.busy ){ rc = sqlite3Init(db, &pParse->zErrMsg); } if( rc!=SQLITE_OK ){ pParse->rc = rc; pParse->nErr++; } return rc; } /* ** Check schema cookies in all databases. If any cookie is out ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies ** make no changes to pParse->rc. */ static void schemaIsValid(Parse *pParse){ sqlite3 *db = pParse->db; int iDb; int rc; int cookie; assert( pParse->checkSchema ); assert( sqlite3_mutex_held(db->mutex) ); for(iDb=0; iDb<db->nDb; iDb++){ int openedTransaction = 0; /* True if a transaction is opened */ Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */ if( pBt==0 ) continue; /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed immediately after reading the meta-value. */ if( !sqlite3BtreeIsInReadTrans(pBt) ){ rc = sqlite3BtreeBeginTrans(pBt, 0); if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ sqlite3OomFault(db); } if( rc!=SQLITE_OK ) return; openedTransaction = 1; } /* Read the schema cookie from the database. If it does not match the ** value stored as part of the in-memory schema representation, ** set Parse.rc to SQLITE_SCHEMA. */ sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){ sqlite3ResetOneSchema(db, iDb); pParse->rc = SQLITE_SCHEMA; } /* Close the transaction, if one was opened. */ if( openedTransaction ){ sqlite3BtreeCommit(pBt); } } } /* ** Convert a schema pointer into the iDb index that indicates ** which database file in db->aDb[] the schema refers to. ** ** If the same database is attached more than once, the first ** attached database is returned. */ SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ int i = -1000000; /* If pSchema is NULL, then return -1000000. This happens when code in ** expr.c is trying to resolve a reference to a transient table (i.e. one ** created by a sub-select). In this case the return value of this ** function should never be used. ** ** We return -1000000 instead of the more usual -1 simply because using ** -1000000 as the incorrect index into db->aDb[] is much ** more likely to cause a segfault than -1 (of course there are assert() ** statements too, but it never hurts to play the odds). */ assert( sqlite3_mutex_held(db->mutex) ); if( pSchema ){ for(i=0; ALWAYS(i<db->nDb); i++){ if( db->aDb[i].pSchema==pSchema ){ break; } } assert( i>=0 && i<db->nDb ); } return i; } /* ** Free all memory allocations in the pParse object */ SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){ if( pParse ){ sqlite3 *db = pParse->db; sqlite3DbFree(db, pParse->aLabel); sqlite3ExprListDelete(db, pParse->pConstExpr); if( db ){ assert( db->lookaside.bDisable >= pParse->disableLookaside ); db->lookaside.bDisable -= pParse->disableLookaside; } pParse->disableLookaside = 0; } } /* ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe *pReprepare, /* VM being reprepared */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ char *zErrMsg = 0; /* Error message */ int rc = SQLITE_OK; /* Result code */ int i; /* Loop counter */ Parse sParse; /* Parsing context */ memset(&sParse, 0, PARSE_HDR_SZ); memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ); sParse.pReprepare = pReprepare; assert( ppStmt && *ppStmt==0 ); /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */ assert( sqlite3_mutex_held(db->mutex) ); /* Check to verify that it is possible to get a read lock on all ** database schemas. The inability to get a read lock indicates that ** some other database connection is holding a write-lock, which in ** turn means that the other connection has made uncommitted changes ** to the schema. ** ** Were we to proceed and prepare the statement against the uncommitted ** schema changes and if those schema changes are subsequently rolled ** back and different changes are made in their place, then when this ** prepared statement goes to run the schema cookie would fail to detect ** the schema change. Disaster would follow. ** ** This thread is currently holding mutexes on all Btrees (because ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it ** is not possible for another thread to start a new schema change ** while this routine is running. Hence, we do not need to hold ** locks on the schema, we just need to make sure nobody else is ** holding them. ** ** Note that setting READ_UNCOMMITTED overrides most lock detection, ** but it does *not* override schema lock detection, so this all still ** works even if READ_UNCOMMITTED is set. */ for(i=0; i<db->nDb; i++) { Btree *pBt = db->aDb[i].pBt; if( pBt ){ assert( sqlite3BtreeHoldsMutex(pBt) ); rc = sqlite3BtreeSchemaLocked(pBt); if( rc ){ const char *zDb = db->aDb[i].zDbSName; sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb); testcase( db->flags & SQLITE_ReadUncommitted ); goto end_prepare; } } } sqlite3VtabUnlockList(db); sParse.db = db; if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){ char *zSqlCopy; int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; testcase( nBytes==mxLen ); testcase( nBytes==mxLen+1 ); if( nBytes>mxLen ){ sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long"); rc = sqlite3ApiExit(db, SQLITE_TOOBIG); goto end_prepare; } zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); if( zSqlCopy ){ sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg); sParse.zTail = &zSql[sParse.zTail-zSqlCopy]; sqlite3DbFree(db, zSqlCopy); }else{ sParse.zTail = &zSql[nBytes]; } }else{ sqlite3RunParser(&sParse, zSql, &zErrMsg); } assert( 0==sParse.nQueryLoop ); if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK; if( sParse.checkSchema ){ schemaIsValid(&sParse); } if( db->mallocFailed ){ sParse.rc = SQLITE_NOMEM_BKPT; } if( pzTail ){ *pzTail = sParse.zTail; } rc = sParse.rc; #ifndef SQLITE_OMIT_EXPLAIN if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){ static const char * const azColName[] = { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", "selectid", "order", "from", "detail" }; int iFirst, mx; if( sParse.explain==2 ){ sqlite3VdbeSetNumCols(sParse.pVdbe, 4); iFirst = 8; mx = 12; }else{ sqlite3VdbeSetNumCols(sParse.pVdbe, 8); iFirst = 0; mx = 8; } for(i=iFirst; i<mx; i++){ sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME, azColName[i], SQLITE_STATIC); } } #endif if( db->init.busy==0 ){ Vdbe *pVdbe = sParse.pVdbe; sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag); } if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){ sqlite3VdbeFinalize(sParse.pVdbe); assert(!(*ppStmt)); }else{ *ppStmt = (sqlite3_stmt*)sParse.pVdbe; } if( zErrMsg ){ sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg); sqlite3DbFree(db, zErrMsg); }else{ sqlite3Error(db, rc); } /* Delete any TriggerPrg structures allocated while parsing this statement. */ while( sParse.pTriggerPrg ){ TriggerPrg *pT = sParse.pTriggerPrg; sParse.pTriggerPrg = pT->pNext; sqlite3DbFree(db, pT); } end_prepare: sqlite3ParserReset(&sParse); rc = sqlite3ApiExit(db, rc); assert( (rc&db->errMask)==rc ); return rc; } static int sqlite3LockAndPrepare( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe *pOld, /* VM being reprepared */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; #ifdef SQLITE_ENABLE_API_ARMOR if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; #endif *ppStmt = 0; if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); if( rc==SQLITE_SCHEMA ){ sqlite3_finalize(*ppStmt); rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); } sqlite3BtreeLeaveAll(db); sqlite3_mutex_leave(db->mutex); assert( rc==SQLITE_OK || *ppStmt==0 ); return rc; } /* ** Rerun the compilation of a statement after a schema change. ** ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, ** if the statement cannot be recompiled because another connection has ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error ** occurs, return SQLITE_SCHEMA. */ SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){ int rc; sqlite3_stmt *pNew; const char *zSql; sqlite3 *db; assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); zSql = sqlite3_sql((sqlite3_stmt *)p); assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ db = sqlite3VdbeDb(p); assert( sqlite3_mutex_held(db->mutex) ); rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0); if( rc ){ if( rc==SQLITE_NOMEM ){ sqlite3OomFault(db); } assert( pNew==0 ); return rc; }else{ assert( pNew!=0 ); } sqlite3VdbeSwap((Vdbe*)pNew, p); sqlite3TransferBindings(pNew, (sqlite3_stmt*)p); sqlite3VdbeResetStepResult((Vdbe*)pNew); sqlite3VdbeFinalize((Vdbe*)pNew); return SQLITE_OK; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } SQLITE_API int sqlite3_prepare_v2( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } #ifndef SQLITE_OMIT_UTF16 /* ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare16( sqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ /* This function currently works by first transforming the UTF-16 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The ** tricky bit is figuring out the pointer to return in *pzTail. */ char *zSql8; const char *zTail8 = 0; int rc = SQLITE_OK; #ifdef SQLITE_ENABLE_API_ARMOR if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; #endif *ppStmt = 0; if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ return SQLITE_MISUSE_BKPT; } if( nBytes>=0 ){ int sz; const char *z = (const char*)zSql; for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){} nBytes = sz; } sqlite3_mutex_enter(db->mutex); zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); if( zSql8 ){ rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8); } if( zTail8 && pzTail ){ /* If sqlite3_prepare returns a tail pointer, we calculate the ** equivalent pointer into the UTF-16 string by counting the unicode ** characters between zSql8 and zTail8, and then returning a pointer ** the same number of characters into the UTF-16 string. */ int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); } sqlite3DbFree(db, zSql8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ SQLITE_API int sqlite3_prepare16( sqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } SQLITE_API int sqlite3_prepare16_v2( sqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } #endif /* SQLITE_OMIT_UTF16 */ /************** End of prepare.c *********************************************/ /************** Begin file select.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle SELECT statements in SQLite. */ /* #include "sqliteInt.h" */ /* ** Trace output macros */ #if SELECTTRACE_ENABLED /***/ int sqlite3SelectTrace = 0; # define SELECTTRACE(K,P,S,X) \ if(sqlite3SelectTrace&(K)) \ sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\ (S)->zSelName,(S)),\ sqlite3DebugPrintf X #else # define SELECTTRACE(K,P,S,X) #endif /* ** An instance of the following object is used to record information about ** how to process the DISTINCT keyword, to simplify passing that information ** into the selectInnerLoop() routine. */ typedef struct DistinctCtx DistinctCtx; struct DistinctCtx { u8 isTnct; /* True if the DISTINCT keyword is present */ u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ int tabTnct; /* Ephemeral table used for DISTINCT processing */ int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ }; /* ** An instance of the following object is used to record information about ** the ORDER BY (or GROUP BY) clause of query is being coded. */ typedef struct SortCtx SortCtx; struct SortCtx { ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ int nOBSat; /* Number of ORDER BY terms satisfied by indices */ int iECursor; /* Cursor number for the sorter */ int regReturn; /* Register holding block-output return address */ int labelBkOut; /* Start label for the block-output subroutine */ int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ int labelDone; /* Jump here when done, ex: LIMIT reached */ u8 sortFlags; /* Zero or more SORTFLAG_* bits */ u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */ }; #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ /* ** Delete all the content of a Select structure. Deallocate the structure ** itself only if bFree is true. */ static void clearSelect(sqlite3 *db, Select *p, int bFree){ while( p ){ Select *pPrior = p->pPrior; sqlite3ExprListDelete(db, p->pEList); sqlite3SrcListDelete(db, p->pSrc); sqlite3ExprDelete(db, p->pWhere); sqlite3ExprListDelete(db, p->pGroupBy); sqlite3ExprDelete(db, p->pHaving); sqlite3ExprListDelete(db, p->pOrderBy); sqlite3ExprDelete(db, p->pLimit); sqlite3ExprDelete(db, p->pOffset); if( p->pWith ) sqlite3WithDelete(db, p->pWith); if( bFree ) sqlite3DbFree(db, p); p = pPrior; bFree = 1; } } /* ** Initialize a SelectDest structure. */ SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ pDest->eDest = (u8)eDest; pDest->iSDParm = iParm; pDest->zAffSdst = 0; pDest->iSdst = 0; pDest->nSdst = 0; } /* ** Allocate a new Select structure and return a pointer to that ** structure. */ SQLITE_PRIVATE Select *sqlite3SelectNew( Parse *pParse, /* Parsing context */ ExprList *pEList, /* which columns to include in the result */ SrcList *pSrc, /* the FROM clause -- which tables to scan */ Expr *pWhere, /* the WHERE clause */ ExprList *pGroupBy, /* the GROUP BY clause */ Expr *pHaving, /* the HAVING clause */ ExprList *pOrderBy, /* the ORDER BY clause */ u32 selFlags, /* Flag parameters, such as SF_Distinct */ Expr *pLimit, /* LIMIT value. NULL means not used */ Expr *pOffset /* OFFSET value. NULL means no offset */ ){ Select *pNew; Select standin; sqlite3 *db = pParse->db; pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); if( pNew==0 ){ assert( db->mallocFailed ); pNew = &standin; } if( pEList==0 ){ pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0)); } pNew->pEList = pEList; pNew->op = TK_SELECT; pNew->selFlags = selFlags; pNew->iLimit = 0; pNew->iOffset = 0; #if SELECTTRACE_ENABLED pNew->zSelName[0] = 0; #endif pNew->addrOpenEphm[0] = -1; pNew->addrOpenEphm[1] = -1; pNew->nSelectRow = 0; if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc)); pNew->pSrc = pSrc; pNew->pWhere = pWhere; pNew->pGroupBy = pGroupBy; pNew->pHaving = pHaving; pNew->pOrderBy = pOrderBy; pNew->pPrior = 0; pNew->pNext = 0; pNew->pLimit = pLimit; pNew->pOffset = pOffset; pNew->pWith = 0; assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 ); if( db->mallocFailed ) { clearSelect(db, pNew, pNew!=&standin); pNew = 0; }else{ assert( pNew->pSrc!=0 || pParse->nErr>0 ); } assert( pNew!=&standin ); return pNew; } #if SELECTTRACE_ENABLED /* ** Set the name of a Select object */ SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){ if( p && zName ){ sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName); } } #endif /* ** Delete the given Select structure and all of its substructures. */ SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){ if( p ) clearSelect(db, p, 1); } /* ** Return a pointer to the right-most SELECT statement in a compound. */ static Select *findRightmost(Select *p){ while( p->pNext ) p = p->pNext; return p; } /* ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the ** type of join. Return an integer constant that expresses that type ** in terms of the following bit values: ** ** JT_INNER ** JT_CROSS ** JT_OUTER ** JT_NATURAL ** JT_LEFT ** JT_RIGHT ** ** A full outer join is the combination of JT_LEFT and JT_RIGHT. ** ** If an illegal or unsupported join type is seen, then still return ** a join type, but put an error in the pParse structure. */ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ int jointype = 0; Token *apAll[3]; Token *p; /* 0123456789 123456789 123456789 123 */ static const char zKeyText[] = "naturaleftouterightfullinnercross"; static const struct { u8 i; /* Beginning of keyword text in zKeyText[] */ u8 nChar; /* Length of the keyword in characters */ u8 code; /* Join type mask */ } aKeyword[] = { /* natural */ { 0, 7, JT_NATURAL }, /* left */ { 6, 4, JT_LEFT|JT_OUTER }, /* outer */ { 10, 5, JT_OUTER }, /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, /* inner */ { 23, 5, JT_INNER }, /* cross */ { 28, 5, JT_INNER|JT_CROSS }, }; int i, j; apAll[0] = pA; apAll[1] = pB; apAll[2] = pC; for(i=0; i<3 && apAll[i]; i++){ p = apAll[i]; for(j=0; j<ArraySize(aKeyword); j++){ if( p->n==aKeyword[j].nChar && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ jointype |= aKeyword[j].code; break; } } testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); if( j>=ArraySize(aKeyword) ){ jointype |= JT_ERROR; break; } } if( (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || (jointype & JT_ERROR)!=0 ){ const char *zSp = " "; assert( pB!=0 ); if( pC==0 ){ zSp++; } sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " "%T %T%s%T", pA, pB, zSp, pC); jointype = JT_INNER; }else if( (jointype & JT_OUTER)!=0 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ sqlite3ErrorMsg(pParse, "RIGHT and FULL OUTER JOINs are not currently supported"); jointype = JT_INNER; } return jointype; } /* ** Return the index of a column in a table. Return -1 if the column ** is not contained in the table. */ static int columnIndex(Table *pTab, const char *zCol){ int i; for(i=0; i<pTab->nCol; i++){ if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; } return -1; } /* ** Search the first N tables in pSrc, from left to right, looking for a ** table that has a column named zCol. ** ** When found, set *piTab and *piCol to the table index and column index ** of the matching column and return TRUE. ** ** If not found, return FALSE. */ static int tableAndColumnIndex( SrcList *pSrc, /* Array of tables to search */ int N, /* Number of tables in pSrc->a[] to search */ const char *zCol, /* Name of the column we are looking for */ int *piTab, /* Write index of pSrc->a[] here */ int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ ){ int i; /* For looping over tables in pSrc */ int iCol; /* Index of column matching zCol */ assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ for(i=0; i<N; i++){ iCol = columnIndex(pSrc->a[i].pTab, zCol); if( iCol>=0 ){ if( piTab ){ *piTab = i; *piCol = iCol; } return 1; } } return 0; } /* ** This function is used to add terms implied by JOIN syntax to the ** WHERE clause expression of a SELECT statement. The new term, which ** is ANDed with the existing WHERE clause, is of the form: ** ** (tab1.col1 = tab2.col2) ** ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is ** column iColRight of tab2. */ static void addWhereTerm( Parse *pParse, /* Parsing context */ SrcList *pSrc, /* List of tables in FROM clause */ int iLeft, /* Index of first table to join in pSrc */ int iColLeft, /* Index of column in first table */ int iRight, /* Index of second table in pSrc */ int iColRight, /* Index of column in second table */ int isOuterJoin, /* True if this is an OUTER join */ Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ ){ sqlite3 *db = pParse->db; Expr *pE1; Expr *pE2; Expr *pEq; assert( iLeft<iRight ); assert( pSrc->nSrc>iRight ); assert( pSrc->a[iLeft].pTab ); assert( pSrc->a[iRight].pTab ); pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); if( pEq && isOuterJoin ){ ExprSetProperty(pEq, EP_FromJoin); assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(pEq, EP_NoReduce); pEq->iRightJoinTable = (i16)pE2->iTable; } *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); } /* ** Set the EP_FromJoin property on all terms of the given expression. ** And set the Expr.iRightJoinTable to iTable for every term in the ** expression. ** ** The EP_FromJoin property is used on terms of an expression to tell ** the LEFT OUTER JOIN processing logic that this term is part of the ** join restriction specified in the ON or USING clause and not a part ** of the more general WHERE clause. These terms are moved over to the ** WHERE clause during join processing but we need to remember that they ** originated in the ON or USING clause. ** ** The Expr.iRightJoinTable tells the WHERE clause processing that the ** expression depends on table iRightJoinTable even if that table is not ** explicitly mentioned in the expression. That information is needed ** for cases like this: ** ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 ** ** The where clause needs to defer the handling of the t1.x=5 ** term until after the t2 loop of the join. In that way, a ** NULL t2 row will be inserted whenever t1.x!=5. If we do not ** defer the handling of t1.x=5, it will be processed immediately ** after the t1 loop and rows with t1.x!=5 will never appear in ** the output, which is incorrect. */ static void setJoinExpr(Expr *p, int iTable){ while( p ){ ExprSetProperty(p, EP_FromJoin); assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(p, EP_NoReduce); p->iRightJoinTable = (i16)iTable; if( p->op==TK_FUNCTION && p->x.pList ){ int i; for(i=0; i<p->x.pList->nExpr; i++){ setJoinExpr(p->x.pList->a[i].pExpr, iTable); } } setJoinExpr(p->pLeft, iTable); p = p->pRight; } } /* ** This routine processes the join information for a SELECT statement. ** ON and USING clauses are converted into extra terms of the WHERE clause. ** NATURAL joins also create extra WHERE clause terms. ** ** The terms of a FROM clause are contained in the Select.pSrc structure. ** The left most table is the first entry in Select.pSrc. The right-most ** table is the last entry. The join operator is held in the entry to ** the left. Thus entry 0 contains the join operator for the join between ** entries 0 and 1. Any ON or USING clauses associated with the join are ** also attached to the left entry. ** ** This routine returns the number of errors encountered. */ static int sqliteProcessJoin(Parse *pParse, Select *p){ SrcList *pSrc; /* All tables in the FROM clause */ int i, j; /* Loop counters */ struct SrcList_item *pLeft; /* Left table being joined */ struct SrcList_item *pRight; /* Right table being joined */ pSrc = p->pSrc; pLeft = &pSrc->a[0]; pRight = &pLeft[1]; for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ Table *pLeftTab = pLeft->pTab; Table *pRightTab = pRight->pTab; int isOuter; if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; isOuter = (pRight->fg.jointype & JT_OUTER)!=0; /* When the NATURAL keyword is present, add WHERE clause terms for ** every column that the two tables have in common. */ if( pRight->fg.jointype & JT_NATURAL ){ if( pRight->pOn || pRight->pUsing ){ sqlite3ErrorMsg(pParse, "a NATURAL join may not have " "an ON or USING clause", 0); return 1; } for(j=0; j<pRightTab->nCol; j++){ char *zName; /* Name of column in the right table */ int iLeft; /* Matching left table */ int iLeftCol; /* Matching column in the left table */ zName = pRightTab->aCol[j].zName; if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, isOuter, &p->pWhere); } } } /* Disallow both ON and USING clauses in the same join */ if( pRight->pOn && pRight->pUsing ){ sqlite3ErrorMsg(pParse, "cannot have both ON and USING " "clauses in the same join"); return 1; } /* Add the ON clause to the end of the WHERE clause, connected by ** an AND operator. */ if( pRight->pOn ){ if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); pRight->pOn = 0; } /* Create extra terms on the WHERE clause for each column named ** in the USING clause. Example: If the two tables to be joined are ** A and B and the USING clause names X, Y, and Z, then add this ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z ** Report an error if any column mentioned in the USING clause is ** not contained in both tables to be joined. */ if( pRight->pUsing ){ IdList *pList = pRight->pUsing; for(j=0; j<pList->nId; j++){ char *zName; /* Name of the term in the USING clause */ int iLeft; /* Table on the left with matching column name */ int iLeftCol; /* Column number of matching column on the left */ int iRightCol; /* Column number of matching column on the right */ zName = pList->a[j].zName; iRightCol = columnIndex(pRightTab, zName); if( iRightCol<0 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ sqlite3ErrorMsg(pParse, "cannot join using column %s - column " "not present in both tables", zName); return 1; } addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, isOuter, &p->pWhere); } } } return 0; } /* Forward reference */ static KeyInfo *keyInfoFromExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* Form the KeyInfo object from this ExprList */ int iStart, /* Begin with this column of pList */ int nExtra /* Add this many extra columns to the end */ ); /* ** Generate code that will push the record in registers regData ** through regData+nData-1 onto the sorter. */ static void pushOntoSorter( Parse *pParse, /* Parser context */ SortCtx *pSort, /* Information about the ORDER BY clause */ Select *pSelect, /* The whole SELECT statement */ int regData, /* First register holding data to be sorted */ int regOrigData, /* First register holding data before packing */ int nData, /* Number of elements in the data array */ int nPrefixReg /* No. of reg prior to regData available for use */ ){ Vdbe *v = pParse->pVdbe; /* Stmt under construction */ int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ int regBase; /* Regs for sorter record */ int regRecord = ++pParse->nMem; /* Assembled sorter record */ int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ int op; /* Opcode to add sorter record to sorter */ int iLimit; /* LIMIT counter */ assert( bSeq==0 || bSeq==1 ); assert( nData==1 || regData==regOrigData || regOrigData==0 ); if( nPrefixReg ){ assert( nPrefixReg==nExpr+bSeq ); regBase = regData - nExpr - bSeq; }else{ regBase = pParse->nMem + 1; pParse->nMem += nBase; } assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; pSort->labelDone = sqlite3VdbeMakeLabel(v); sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); if( bSeq ){ sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); } if( nPrefixReg==0 && nData>0 ){ sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); if( nOBSat>0 ){ int regPrevKey; /* The first nOBSat columns of the previous row */ int addrFirst; /* Address of the OP_IfNot opcode */ int addrJmp; /* Address of the OP_Jump opcode */ VdbeOp *pOp; /* Opcode that opens the sorter */ int nKey; /* Number of sorting key columns, including OP_Sequence */ KeyInfo *pKI; /* Original KeyInfo on the sorter table */ regPrevKey = pParse->nMem+1; pParse->nMem += pSort->nOBSat; nKey = nExpr - pSort->nOBSat + bSeq; if( bSeq ){ addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); }else{ addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); } VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); if( pParse->db->mallocFailed ) return; pOp->p2 = nKey + nData; pKI = pOp->p4.pKeyInfo; memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */ sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); testcase( pKI->nXField>2 ); pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, pKI->nXField-1); addrJmp = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); pSort->labelBkOut = sqlite3VdbeMakeLabel(v); pSort->regReturn = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); if( iLimit ){ sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); VdbeCoverage(v); } sqlite3VdbeJumpHere(v, addrFirst); sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); sqlite3VdbeJumpHere(v, addrJmp); } if( pSort->sortFlags & SORTFLAG_UseSorter ){ op = OP_SorterInsert; }else{ op = OP_IdxInsert; } sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, regBase+nOBSat, nBase-nOBSat); if( iLimit ){ int addr; int r1 = 0; /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit ** register is initialized with value of LIMIT+OFFSET.) After the sorter ** fills up, delete the least entry in the sorter after each insert. ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */ addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v); sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); if( pSort->bOrderedInnerLoop ){ r1 = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1); VdbeComment((v, "seq")); } sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); if( pSort->bOrderedInnerLoop ){ /* If the inner loop is driven by an index such that values from ** the same iteration of the inner loop are in sorted order, then ** immediately jump to the next iteration of an inner loop if the ** entry from the current iteration does not fit into the top ** LIMIT+OFFSET entries of the sorter. */ int iBrk = sqlite3VdbeCurrentAddr(v) + 2; sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1); sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); VdbeCoverage(v); } sqlite3VdbeJumpHere(v, addr); } } /* ** Add code to implement the OFFSET */ static void codeOffset( Vdbe *v, /* Generate code into this VM */ int iOffset, /* Register holding the offset counter */ int iContinue /* Jump here to skip the current record */ ){ if( iOffset>0 ){ sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); VdbeComment((v, "OFFSET")); } } /* ** Add code that will check to make sure the N registers starting at iMem ** form a distinct entry. iTab is a sorting index that holds previously ** seen combinations of the N values. A new entry is made in iTab ** if the current N values are new. ** ** A jump to addrRepeat is made and the N+1 values are popped from the ** stack if the top N elements are not distinct. */ static void codeDistinct( Parse *pParse, /* Parsing and code generating context */ int iTab, /* A sorting index used to test for distinctness */ int addrRepeat, /* Jump to here if not distinct */ int N, /* Number of elements */ int iMem /* First element */ ){ Vdbe *v; int r1; v = pParse->pVdbe; r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); sqlite3ReleaseTempReg(pParse, r1); } /* ** This routine generates the code for the inside of the inner loop ** of a SELECT. ** ** If srcTab is negative, then the pEList expressions ** are evaluated in order to get the data for this row. If srcTab is ** zero or more, then data is pulled from srcTab and pEList is used only ** to get the number of columns and the collation sequence for each column. */ static void selectInnerLoop( Parse *pParse, /* The parser context */ Select *p, /* The complete select statement being coded */ ExprList *pEList, /* List of values being extracted */ int srcTab, /* Pull data from this table */ SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ SelectDest *pDest, /* How to dispose of the results */ int iContinue, /* Jump here to continue with next row */ int iBreak /* Jump here to break out of the inner loop */ ){ Vdbe *v = pParse->pVdbe; int i; int hasDistinct; /* True if the DISTINCT keyword is present */ int eDest = pDest->eDest; /* How to dispose of results */ int iParm = pDest->iSDParm; /* First argument to disposal method */ int nResultCol; /* Number of result columns */ int nPrefixReg = 0; /* Number of extra registers before regResult */ /* Usually, regResult is the first cell in an array of memory cells ** containing the current result row. In this case regOrig is set to the ** same value. However, if the results are being sent to the sorter, the ** values for any expressions that are also part of the sort-key are omitted ** from this array. In this case regOrig is set to zero. */ int regResult; /* Start of memory holding current results */ int regOrig; /* Start of memory holding full result (or 0) */ assert( v ); assert( pEList!=0 ); hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; if( pSort && pSort->pOrderBy==0 ) pSort = 0; if( pSort==0 && !hasDistinct ){ assert( iContinue!=0 ); codeOffset(v, p->iOffset, iContinue); } /* Pull the requested columns. */ nResultCol = pEList->nExpr; if( pDest->iSdst==0 ){ if( pSort ){ nPrefixReg = pSort->pOrderBy->nExpr; if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; pParse->nMem += nPrefixReg; } pDest->iSdst = pParse->nMem+1; pParse->nMem += nResultCol; }else if( pDest->iSdst+nResultCol > pParse->nMem ){ /* This is an error condition that can result, for example, when a SELECT ** on the right-hand side of an INSERT contains more result columns than ** there are columns in the table on the left. The error will be caught ** and reported later. But we need to make sure enough memory is allocated ** to avoid other spurious errors in the meantime. */ pParse->nMem += nResultCol; } pDest->nSdst = nResultCol; regOrig = regResult = pDest->iSdst; if( srcTab>=0 ){ for(i=0; i<nResultCol; i++){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); VdbeComment((v, "%s", pEList->a[i].zName)); } }else if( eDest!=SRT_Exists ){ /* If the destination is an EXISTS(...) expression, the actual ** values returned by the SELECT are not required. */ u8 ecelFlags; if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ ecelFlags = SQLITE_ECEL_DUP; }else{ ecelFlags = 0; } if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ /* For each expression in pEList that is a copy of an expression in ** the ORDER BY clause (pSort->pOrderBy), set the associated ** iOrderByCol value to one more than the index of the ORDER BY ** expression within the sort-key that pushOntoSorter() will generate. ** This allows the pEList field to be omitted from the sorted record, ** saving space and CPU cycles. */ ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ int j; if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; } } regOrig = 0; assert( eDest==SRT_Set || eDest==SRT_Mem || eDest==SRT_Coroutine || eDest==SRT_Output ); } nResultCol = sqlite3ExprCodeExprList(pParse,pEList,regResult,0,ecelFlags); } /* If the DISTINCT keyword was present on the SELECT statement ** and this row has been seen before, then do not make this row ** part of the result. */ if( hasDistinct ){ switch( pDistinct->eTnctType ){ case WHERE_DISTINCT_ORDERED: { VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ int iJump; /* Jump destination */ int regPrev; /* Previous row content */ /* Allocate space for the previous row */ regPrev = pParse->nMem+1; pParse->nMem += nResultCol; /* Change the OP_OpenEphemeral coded earlier to an OP_Null ** sets the MEM_Cleared bit on the first register of the ** previous value. This will cause the OP_Ne below to always ** fail on the first iteration of the loop even if the first ** row is all NULLs. */ sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); pOp->opcode = OP_Null; pOp->p1 = 1; pOp->p2 = regPrev; iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; for(i=0; i<nResultCol; i++){ CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr); if( i<nResultCol-1 ){ sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); VdbeCoverage(v); }else{ sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); VdbeCoverage(v); } sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); } assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); break; } case WHERE_DISTINCT_UNIQUE: { sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); break; } default: { assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult); break; } } if( pSort==0 ){ codeOffset(v, p->iOffset, iContinue); } } switch( eDest ){ /* In this mode, write each query result to the key of the temporary ** table iParm. */ #ifndef SQLITE_OMIT_COMPOUND_SELECT case SRT_Union: { int r1; r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); sqlite3ReleaseTempReg(pParse, r1); break; } /* Construct a record from the query result, but instead of ** saving that record, use it as a key to delete elements from ** the temporary table iParm. */ case SRT_Except: { sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); break; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ /* Store the result as data using a unique key. */ case SRT_Fifo: case SRT_DistFifo: case SRT_Table: case SRT_EphemTab: { int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); testcase( eDest==SRT_Table ); testcase( eDest==SRT_EphemTab ); testcase( eDest==SRT_Fifo ); testcase( eDest==SRT_DistFifo ); sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); #ifndef SQLITE_OMIT_CTE if( eDest==SRT_DistFifo ){ /* If the destination is DistFifo, then cursor (iParm+1) is open ** on an ephemeral index. If the current row is already present ** in the index, do not write it to the output. If not, add the ** current row to the index and proceed with writing it to the ** output table as well. */ int addr = sqlite3VdbeCurrentAddr(v) + 4; sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); assert( pSort==0 ); } #endif if( pSort ){ pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg); }else{ int r2 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3ReleaseTempReg(pParse, r2); } sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); break; } #ifndef SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)" construct, ** then there should be a single item on the stack. Write this ** item into the set table with bogus data. */ case SRT_Set: { if( pSort ){ /* At first glance you would think we could optimize out the ** ORDER BY in this case since the order of entries in the set ** does not matter. But there might be a LIMIT clause, in which ** case the order does matter */ pushOntoSorter( pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else{ int r1 = sqlite3GetTempReg(pParse); assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, r1, pDest->zAffSdst, nResultCol); sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); sqlite3ReleaseTempReg(pParse, r1); } break; } /* If any row exist in the result set, record that fact and abort. */ case SRT_Exists: { sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); /* The LIMIT clause will terminate the loop for us */ break; } /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell or array of ** memory cells and break out of the scan loop. */ case SRT_Mem: { if( pSort ){ assert( nResultCol<=pDest->nSdst ); pushOntoSorter( pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else{ assert( nResultCol==pDest->nSdst ); assert( regResult==iParm ); /* The LIMIT clause will jump out of the loop for us */ } break; } #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ case SRT_Coroutine: /* Send data to a co-routine */ case SRT_Output: { /* Return the results */ testcase( eDest==SRT_Coroutine ); testcase( eDest==SRT_Output ); if( pSort ){ pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else if( eDest==SRT_Coroutine ){ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); }else{ sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); } break; } #ifndef SQLITE_OMIT_CTE /* Write the results into a priority queue that is order according to ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an ** index with pSO->nExpr+2 columns. Build a key using pSO for the first ** pSO->nExpr columns, then make sure all keys are unique by adding a ** final OP_Sequence column. The last column is the record as a blob. */ case SRT_DistQueue: case SRT_Queue: { int nKey; int r1, r2, r3; int addrTest = 0; ExprList *pSO; pSO = pDest->pOrderBy; assert( pSO ); nKey = pSO->nExpr; r1 = sqlite3GetTempReg(pParse); r2 = sqlite3GetTempRange(pParse, nKey+2); r3 = r2+nKey+1; if( eDest==SRT_DistQueue ){ /* If the destination is DistQueue, then cursor (iParm+1) is open ** on a second ephemeral index that holds all values every previously ** added to the queue. */ addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, regResult, nResultCol); VdbeCoverage(v); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); if( eDest==SRT_DistQueue ){ sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); } for(i=0; i<nKey; i++){ sqlite3VdbeAddOp2(v, OP_SCopy, regResult + pSO->a[i].u.x.iOrderByCol - 1, r2+i); } sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); sqlite3ReleaseTempReg(pParse, r1); sqlite3ReleaseTempRange(pParse, r2, nKey+2); break; } #endif /* SQLITE_OMIT_CTE */ #if !defined(SQLITE_OMIT_TRIGGER) /* Discard the results. This is used for SELECT statements inside ** the body of a TRIGGER. The purpose of such selects is to call ** user-defined functions that have side effects. We do not care ** about the actual results of the select. */ default: { assert( eDest==SRT_Discard ); break; } #endif } /* Jump to the end of the loop if the LIMIT is reached. Except, if ** there is a sorter, in which case the sorter has already limited ** the output for us. */ if( pSort==0 && p->iLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); } } /* ** Allocate a KeyInfo object sufficient for an index of N key columns and ** X extra columns. */ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ int nExtra = (N+X)*(sizeof(CollSeq*)+1); KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); if( p ){ p->aSortOrder = (u8*)&p->aColl[N+X]; p->nField = (u16)N; p->nXField = (u16)X; p->enc = ENC(db); p->db = db; p->nRef = 1; memset(&p[1], 0, nExtra); }else{ sqlite3OomFault(db); } return p; } /* ** Deallocate a KeyInfo object */ SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){ if( p ){ assert( p->nRef>0 ); p->nRef--; if( p->nRef==0 ) sqlite3DbFree(p->db, p); } } /* ** Make a new pointer to a KeyInfo object */ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ if( p ){ assert( p->nRef>0 ); p->nRef++; } return p; } #ifdef SQLITE_DEBUG /* ** Return TRUE if a KeyInfo object can be change. The KeyInfo object ** can only be changed if this is just a single reference to the object. ** ** This routine is used only inside of assert() statements. */ SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } #endif /* SQLITE_DEBUG */ /* ** Given an expression list, generate a KeyInfo structure that records ** the collating sequence for each expression in that expression list. ** ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting ** KeyInfo structure is appropriate for initializing a virtual index to ** implement that clause. If the ExprList is the result set of a SELECT ** then the KeyInfo structure is appropriate for initializing a virtual ** index to implement a DISTINCT test. ** ** Space to hold the KeyInfo structure is obtained from malloc. The calling ** function is responsible for seeing that this structure is eventually ** freed. */ static KeyInfo *keyInfoFromExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* Form the KeyInfo object from this ExprList */ int iStart, /* Begin with this column of pList */ int nExtra /* Add this many extra columns to the end */ ){ int nExpr; KeyInfo *pInfo; struct ExprList_item *pItem; sqlite3 *db = pParse->db; int i; nExpr = pList->nExpr; pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); if( pInfo ){ assert( sqlite3KeyInfoIsWriteable(pInfo) ); for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ CollSeq *pColl; pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); if( !pColl ) pColl = db->pDfltColl; pInfo->aColl[i-iStart] = pColl; pInfo->aSortOrder[i-iStart] = pItem->sortOrder; } } return pInfo; } /* ** Name of the connection operator, used for error messages. */ static const char *selectOpName(int id){ char *z; switch( id ){ case TK_ALL: z = "UNION ALL"; break; case TK_INTERSECT: z = "INTERSECT"; break; case TK_EXCEPT: z = "EXCEPT"; break; default: z = "UNION"; break; } return z; } #ifndef SQLITE_OMIT_EXPLAIN /* ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function ** is a no-op. Otherwise, it adds a single row of output to the EQP result, ** where the caption is of the form: ** ** "USE TEMP B-TREE FOR xxx" ** ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which ** is determined by the zUsage argument. */ static void explainTempTable(Parse *pParse, const char *zUsage){ if( pParse->explain==2 ){ Vdbe *v = pParse->pVdbe; char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); } } /* ** Assign expression b to lvalue a. A second, no-op, version of this macro ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code ** in sqlite3Select() to assign values to structure member variables that ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the ** code with #ifndef directives. */ # define explainSetInteger(a, b) a = b #else /* No-op versions of the explainXXX() functions and macros. */ # define explainTempTable(y,z) # define explainSetInteger(y,z) #endif #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) /* ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function ** is a no-op. Otherwise, it adds a single row of output to the EQP result, ** where the caption is of one of the two forms: ** ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" ** ** where iSub1 and iSub2 are the integers passed as the corresponding ** function parameters, and op is the text representation of the parameter ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is ** false, or the second form if it is true. */ static void explainComposite( Parse *pParse, /* Parse context */ int op, /* One of TK_UNION, TK_EXCEPT etc. */ int iSub1, /* Subquery id 1 */ int iSub2, /* Subquery id 2 */ int bUseTmp /* True if a temp table was used */ ){ assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); if( pParse->explain==2 ){ Vdbe *v = pParse->pVdbe; char *zMsg = sqlite3MPrintf( pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) ); sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); } } #else /* No-op versions of the explainXXX() functions and macros. */ # define explainComposite(v,w,x,y,z) #endif /* ** If the inner loop was generated using a non-null pOrderBy argument, ** then the results were placed in a sorter. After the loop is terminated ** we need to run the sorter and output the results. The following ** routine generates the code needed to do that. */ static void generateSortTail( Parse *pParse, /* Parsing context */ Select *p, /* The SELECT statement */ SortCtx *pSort, /* Information on the ORDER BY clause */ int nColumn, /* Number of columns of data */ SelectDest *pDest /* Write the sorted results here */ ){ Vdbe *v = pParse->pVdbe; /* The prepared statement */ int addrBreak = pSort->labelDone; /* Jump here to exit loop */ int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ int addr; int addrOnce = 0; int iTab; ExprList *pOrderBy = pSort->pOrderBy; int eDest = pDest->eDest; int iParm = pDest->iSDParm; int regRow; int regRowid; int iCol; int nKey; int iSortTab; /* Sorter cursor to read from */ int nSortData; /* Trailing values to read from sorter */ int i; int bSeq; /* True if sorter record includes seq. no. */ struct ExprList_item *aOutEx = p->pEList->a; assert( addrBreak<0 ); if( pSort->labelBkOut ){ sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); sqlite3VdbeGoto(v, addrBreak); sqlite3VdbeResolveLabel(v, pSort->labelBkOut); } iTab = pSort->iECursor; if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ regRowid = 0; regRow = pDest->iSdst; nSortData = nColumn; }else{ regRowid = sqlite3GetTempReg(pParse); regRow = sqlite3GetTempRange(pParse, nColumn); nSortData = nColumn; } nKey = pOrderBy->nExpr - pSort->nOBSat; if( pSort->sortFlags & SORTFLAG_UseSorter ){ int regSortOut = ++pParse->nMem; iSortTab = pParse->nTab++; if( pSort->labelBkOut ){ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData); if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); VdbeCoverage(v); codeOffset(v, p->iOffset, addrContinue); sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); bSeq = 0; }else{ addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); codeOffset(v, p->iOffset, addrContinue); iSortTab = iTab; bSeq = 1; } for(i=0, iCol=nKey+bSeq; i<nSortData; i++){ int iRead; if( aOutEx[i].u.x.iOrderByCol ){ iRead = aOutEx[i].u.x.iOrderByCol-1; }else{ iRead = iCol++; } sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan)); } switch( eDest ){ case SRT_Table: case SRT_EphemTab: { sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); break; } #ifndef SQLITE_OMIT_SUBQUERY case SRT_Set: { assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, pDest->zAffSdst, nColumn); sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); break; } case SRT_Mem: { /* The LIMIT clause will terminate the loop for us */ break; } #endif default: { assert( eDest==SRT_Output || eDest==SRT_Coroutine ); testcase( eDest==SRT_Output ); testcase( eDest==SRT_Coroutine ); if( eDest==SRT_Output ){ sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); }else{ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); } break; } } if( regRowid ){ if( eDest==SRT_Set ){ sqlite3ReleaseTempRange(pParse, regRow, nColumn); }else{ sqlite3ReleaseTempReg(pParse, regRow); } sqlite3ReleaseTempReg(pParse, regRowid); } /* The bottom of the loop */ sqlite3VdbeResolveLabel(v, addrContinue); if( pSort->sortFlags & SORTFLAG_UseSorter ){ sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); }else{ sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); } if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); sqlite3VdbeResolveLabel(v, addrBreak); } /* ** Return a pointer to a string containing the 'declaration type' of the ** expression pExpr. The string may be treated as static by the caller. ** ** Also try to estimate the size of the returned value and return that ** result in *pEstWidth. ** ** The declaration type is the exact datatype definition extracted from the ** original CREATE TABLE statement if the expression is a column. The ** declaration type for a ROWID field is INTEGER. Exactly when an expression ** is considered a column can be complex in the presence of subqueries. The ** result-set expression in all of the following SELECT statements is ** considered a column by this function. ** ** SELECT col FROM tbl; ** SELECT (SELECT col FROM tbl; ** SELECT (SELECT col FROM tbl); ** SELECT abc FROM (SELECT col AS abc FROM tbl); ** ** The declaration type for any expression other than a column is NULL. ** ** This routine has either 3 or 6 parameters depending on whether or not ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. */ #ifdef SQLITE_ENABLE_COLUMN_METADATA # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F) #endif static const char *columnTypeImpl( NameContext *pNC, Expr *pExpr, #ifdef SQLITE_ENABLE_COLUMN_METADATA const char **pzOrigDb, const char **pzOrigTab, const char **pzOrigCol, #endif u8 *pEstWidth ){ char const *zType = 0; int j; u8 estWidth = 1; #ifdef SQLITE_ENABLE_COLUMN_METADATA char const *zOrigDb = 0; char const *zOrigTab = 0; char const *zOrigCol = 0; #endif assert( pExpr!=0 ); assert( pNC->pSrcList!=0 ); switch( pExpr->op ){ case TK_AGG_COLUMN: case TK_COLUMN: { /* The expression is a column. Locate the table the column is being ** extracted from in NameContext.pSrcList. This table may be real ** database table or a subquery. */ Table *pTab = 0; /* Table structure column is extracted from */ Select *pS = 0; /* Select the column is extracted from */ int iCol = pExpr->iColumn; /* Index of column in pTab */ testcase( pExpr->op==TK_AGG_COLUMN ); testcase( pExpr->op==TK_COLUMN ); while( pNC && !pTab ){ SrcList *pTabList = pNC->pSrcList; for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); if( j<pTabList->nSrc ){ pTab = pTabList->a[j].pTab; pS = pTabList->a[j].pSelect; }else{ pNC = pNC->pNext; } } if( pTab==0 ){ /* At one time, code such as "SELECT new.x" within a trigger would ** cause this condition to run. Since then, we have restructured how ** trigger code is generated and so this condition is no longer ** possible. However, it can still be true for statements like ** the following: ** ** CREATE TABLE t1(col INTEGER); ** SELECT (SELECT t1.col) FROM FROM t1; ** ** when columnType() is called on the expression "t1.col" in the ** sub-select. In this case, set the column type to NULL, even ** though it should really be "INTEGER". ** ** This is not a problem, as the column type of "t1.col" is never ** used. When columnType() is called on the expression ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT ** branch below. */ break; } assert( pTab && pExpr->pTab==pTab ); if( pS ){ /* The "table" is actually a sub-select or a view in the FROM clause ** of the SELECT statement. Return the declaration type and origin ** data for the result-set column of the sub-select. */ if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ /* If iCol is less than zero, then the expression requests the ** rowid of the sub-select or view. This expression is legal (see ** test case misc2.2.2) - it always evaluates to NULL. ** ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been ** caught already by name resolution. */ NameContext sNC; Expr *p = pS->pEList->a[iCol].pExpr; sNC.pSrcList = pS->pSrc; sNC.pNext = pNC; sNC.pParse = pNC->pParse; zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); } }else if( pTab->pSchema ){ /* A real table */ assert( !pS ); if( iCol<0 ) iCol = pTab->iPKey; assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); #ifdef SQLITE_ENABLE_COLUMN_METADATA if( iCol<0 ){ zType = "INTEGER"; zOrigCol = "rowid"; }else{ zOrigCol = pTab->aCol[iCol].zName; zType = sqlite3ColumnType(&pTab->aCol[iCol],0); estWidth = pTab->aCol[iCol].szEst; } zOrigTab = pTab->zName; if( pNC->pParse ){ int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; } #else if( iCol<0 ){ zType = "INTEGER"; }else{ zType = sqlite3ColumnType(&pTab->aCol[iCol],0); estWidth = pTab->aCol[iCol].szEst; } #endif } break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_SELECT: { /* The expression is a sub-select. Return the declaration type and ** origin info for the single column in the result set of the SELECT ** statement. */ NameContext sNC; Select *pS = pExpr->x.pSelect; Expr *p = pS->pEList->a[0].pExpr; assert( ExprHasProperty(pExpr, EP_xIsSelect) ); sNC.pSrcList = pS->pSrc; sNC.pNext = pNC; sNC.pParse = pNC->pParse; zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); break; } #endif } #ifdef SQLITE_ENABLE_COLUMN_METADATA if( pzOrigDb ){ assert( pzOrigTab && pzOrigCol ); *pzOrigDb = zOrigDb; *pzOrigTab = zOrigTab; *pzOrigCol = zOrigCol; } #endif if( pEstWidth ) *pEstWidth = estWidth; return zType; } /* ** Generate code that will tell the VDBE the declaration types of columns ** in the result set. */ static void generateColumnTypes( Parse *pParse, /* Parser context */ SrcList *pTabList, /* List of tables */ ExprList *pEList /* Expressions defining the result set */ ){ #ifndef SQLITE_OMIT_DECLTYPE Vdbe *v = pParse->pVdbe; int i; NameContext sNC; sNC.pSrcList = pTabList; sNC.pParse = pParse; for(i=0; i<pEList->nExpr; i++){ Expr *p = pEList->a[i].pExpr; const char *zType; #ifdef SQLITE_ENABLE_COLUMN_METADATA const char *zOrigDb = 0; const char *zOrigTab = 0; const char *zOrigCol = 0; zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0); /* The vdbe must make its own copy of the column-type and other ** column specific strings, in case the schema is reset before this ** virtual machine is deleted. */ sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); #else zType = columnType(&sNC, p, 0, 0, 0, 0); #endif sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); } #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ } /* ** Generate code that will tell the VDBE the names of columns ** in the result set. This information is used to provide the ** azCol[] values in the callback. */ static void generateColumnNames( Parse *pParse, /* Parser context */ SrcList *pTabList, /* List of tables */ ExprList *pEList /* Expressions defining the result set */ ){ Vdbe *v = pParse->pVdbe; int i, j; sqlite3 *db = pParse->db; int fullNames, shortNames; #ifndef SQLITE_OMIT_EXPLAIN /* If this is an EXPLAIN, skip this step */ if( pParse->explain ){ return; } #endif if( pParse->colNamesSet || db->mallocFailed ) return; assert( v!=0 ); assert( pTabList!=0 ); pParse->colNamesSet = 1; fullNames = (db->flags & SQLITE_FullColNames)!=0; shortNames = (db->flags & SQLITE_ShortColNames)!=0; sqlite3VdbeSetNumCols(v, pEList->nExpr); for(i=0; i<pEList->nExpr; i++){ Expr *p; p = pEList->a[i].pExpr; if( NEVER(p==0) ) continue; if( pEList->a[i].zName ){ char *zName = pEList->a[i].zName; sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){ Table *pTab; char *zCol; int iCol = p->iColumn; for(j=0; ALWAYS(j<pTabList->nSrc); j++){ if( pTabList->a[j].iCursor==p->iTable ) break; } assert( j<pTabList->nSrc ); pTab = pTabList->a[j].pTab; if( iCol<0 ) iCol = pTab->iPKey; assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); if( iCol<0 ){ zCol = "rowid"; }else{ zCol = pTab->aCol[iCol].zName; } if( !shortNames && !fullNames ){ sqlite3VdbeSetColName(v, i, COLNAME_NAME, sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); }else if( fullNames ){ char *zName = 0; zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); }else{ sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); } }else{ const char *z = pEList->a[i].zSpan; z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); } } generateColumnTypes(pParse, pTabList, pEList); } /* ** Given an expression list (which is really the list of expressions ** that form the result set of a SELECT statement) compute appropriate ** column names for a table that would hold the expression list. ** ** All column names will be unique. ** ** Only the column names are computed. Column.zType, Column.zColl, ** and other fields of Column are zeroed. ** ** Return SQLITE_OK on success. If a memory allocation error occurs, ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. */ SQLITE_PRIVATE int sqlite3ColumnsFromExprList( Parse *pParse, /* Parsing context */ ExprList *pEList, /* Expr list from which to derive column names */ i16 *pnCol, /* Write the number of columns here */ Column **paCol /* Write the new column list here */ ){ sqlite3 *db = pParse->db; /* Database connection */ int i, j; /* Loop counters */ u32 cnt; /* Index added to make the name unique */ Column *aCol, *pCol; /* For looping over result columns */ int nCol; /* Number of columns in the result set */ Expr *p; /* Expression for a single result column */ char *zName; /* Column name */ int nName; /* Size of name in zName[] */ Hash ht; /* Hash table of column names */ sqlite3HashInit(&ht); if( pEList ){ nCol = pEList->nExpr; aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); testcase( aCol==0 ); }else{ nCol = 0; aCol = 0; } assert( nCol==(i16)nCol ); *pnCol = nCol; *paCol = aCol; for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ /* Get an appropriate name for the column */ p = sqlite3ExprSkipCollate(pEList->a[i].pExpr); if( (zName = pEList->a[i].zName)!=0 ){ /* If the column contains an "AS <name>" phrase, use <name> as the name */ }else{ Expr *pColExpr = p; /* The expression that is the result column name */ Table *pTab; /* Table associated with this expression */ while( pColExpr->op==TK_DOT ){ pColExpr = pColExpr->pRight; assert( pColExpr!=0 ); } if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ /* For columns use the column name name */ int iCol = pColExpr->iColumn; pTab = pColExpr->pTab; if( iCol<0 ) iCol = pTab->iPKey; zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; }else if( pColExpr->op==TK_ID ){ assert( !ExprHasProperty(pColExpr, EP_IntValue) ); zName = pColExpr->u.zToken; }else{ /* Use the original text of the column expression as its name */ zName = pEList->a[i].zSpan; } } zName = sqlite3MPrintf(db, "%s", zName); /* Make sure the column name is unique. If the name is not unique, ** append an integer to the name so that it becomes unique. */ cnt = 0; while( zName && sqlite3HashFind(&ht, zName)!=0 ){ nName = sqlite3Strlen30(zName); if( nName>0 ){ for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} if( zName[j]==':' ) nName = j; } zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); } pCol->zName = zName; sqlite3ColumnPropertiesFromName(0, pCol); if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ sqlite3OomFault(db); } } sqlite3HashClear(&ht); if( db->mallocFailed ){ for(j=0; j<i; j++){ sqlite3DbFree(db, aCol[j].zName); } sqlite3DbFree(db, aCol); *paCol = 0; *pnCol = 0; return SQLITE_NOMEM_BKPT; } return SQLITE_OK; } /* ** Add type and collation information to a column list based on ** a SELECT statement. ** ** The column list presumably came from selectColumnNamesFromExprList(). ** The column list has only names, not types or collations. This ** routine goes through and adds the types and collations. ** ** This routine requires that all identifiers in the SELECT ** statement be resolved. */ SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation( Parse *pParse, /* Parsing contexts */ Table *pTab, /* Add column type information to this table */ Select *pSelect /* SELECT used to determine types and collations */ ){ sqlite3 *db = pParse->db; NameContext sNC; Column *pCol; CollSeq *pColl; int i; Expr *p; struct ExprList_item *a; u64 szAll = 0; assert( pSelect!=0 ); assert( (pSelect->selFlags & SF_Resolved)!=0 ); assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); if( db->mallocFailed ) return; memset(&sNC, 0, sizeof(sNC)); sNC.pSrcList = pSelect->pSrc; a = pSelect->pEList->a; for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ const char *zType; int n, m; p = a[i].pExpr; zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst); szAll += pCol->szEst; pCol->affinity = sqlite3ExprAffinity(p); if( zType && (m = sqlite3Strlen30(zType))>0 ){ n = sqlite3Strlen30(pCol->zName); pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); if( pCol->zName ){ memcpy(&pCol->zName[n+1], zType, m+1); pCol->colFlags |= COLFLAG_HASTYPE; } } if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB; pColl = sqlite3ExprCollSeq(pParse, p); if( pColl && pCol->zColl==0 ){ pCol->zColl = sqlite3DbStrDup(db, pColl->zName); } } pTab->szTabRow = sqlite3LogEst(szAll*4); } /* ** Given a SELECT statement, generate a Table structure that describes ** the result set of that SELECT. */ SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ Table *pTab; sqlite3 *db = pParse->db; int savedFlags; savedFlags = db->flags; db->flags &= ~SQLITE_FullColNames; db->flags |= SQLITE_ShortColNames; sqlite3SelectPrep(pParse, pSelect, 0); if( pParse->nErr ) return 0; while( pSelect->pPrior ) pSelect = pSelect->pPrior; db->flags = savedFlags; pTab = sqlite3DbMallocZero(db, sizeof(Table) ); if( pTab==0 ){ return 0; } /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside ** is disabled */ assert( db->lookaside.bDisable ); pTab->nTabRef = 1; pTab->zName = 0; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect); pTab->iPKey = -1; if( db->mallocFailed ){ sqlite3DeleteTable(db, pTab); return 0; } return pTab; } /* ** Get a VDBE for the given parser context. Create a new one if necessary. ** If an error occurs, return NULL and leave a message in pParse. */ static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){ Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse); if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1); if( pParse->pToplevel==0 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) ){ pParse->okConstFactor = 1; } return v; } SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){ Vdbe *v = pParse->pVdbe; return v ? v : allocVdbe(pParse); } /* ** Compute the iLimit and iOffset fields of the SELECT based on the ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions ** that appear in the original SQL statement after the LIMIT and OFFSET ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset ** are the integer memory register numbers for counters used to compute ** the limit and offset. If there is no limit and/or offset, then ** iLimit and iOffset are negative. ** ** This routine changes the values of iLimit and iOffset only if ** a limit or offset is defined by pLimit and pOffset. iLimit and ** iOffset should have been preset to appropriate default values (zero) ** prior to calling this routine. ** ** The iOffset register (if it exists) is initialized to the value ** of the OFFSET. The iLimit register is initialized to LIMIT. Register ** iOffset+1 is initialized to LIMIT+OFFSET. ** ** Only if pLimit!=0 or pOffset!=0 do the limit registers get ** redefined. The UNION ALL operator uses this property to force ** the reuse of the same limit and offset registers across multiple ** SELECT statements. */ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ Vdbe *v = 0; int iLimit = 0; int iOffset; int n; if( p->iLimit ) return; /* ** "LIMIT -1" always shows all rows. There is some ** controversy about what the correct behavior should be. ** The current implementation interprets "LIMIT 0" to mean ** no rows. */ sqlite3ExprCacheClear(pParse); assert( p->pOffset==0 || p->pLimit!=0 ); if( p->pLimit ){ p->iLimit = iLimit = ++pParse->nMem; v = sqlite3GetVdbe(pParse); assert( v!=0 ); if( sqlite3ExprIsInteger(p->pLimit, &n) ){ sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); VdbeComment((v, "LIMIT counter")); if( n==0 ){ sqlite3VdbeGoto(v, iBreak); }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ p->nSelectRow = sqlite3LogEst((u64)n); p->selFlags |= SF_FixedLimit; } }else{ sqlite3ExprCode(pParse, p->pLimit, iLimit); sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); VdbeComment((v, "LIMIT counter")); sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); } if( p->pOffset ){ p->iOffset = iOffset = ++pParse->nMem; pParse->nMem++; /* Allocate an extra register for limit+offset */ sqlite3ExprCode(pParse, p->pOffset, iOffset); sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); VdbeComment((v, "OFFSET counter")); sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); VdbeComment((v, "LIMIT+OFFSET")); } } } #ifndef SQLITE_OMIT_COMPOUND_SELECT /* ** Return the appropriate collating sequence for the iCol-th column of ** the result set for the compound-select statement "p". Return NULL if ** the column has no default collating sequence. ** ** The collating sequence for the compound select is taken from the ** left-most term of the select that has a collating sequence. */ static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ CollSeq *pRet; if( p->pPrior ){ pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); }else{ pRet = 0; } assert( iCol>=0 ); /* iCol must be less than p->pEList->nExpr. Otherwise an error would ** have been thrown during name resolution and we would not have gotten ** this far */ if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); } return pRet; } /* ** The select statement passed as the second parameter is a compound SELECT ** with an ORDER BY clause. This function allocates and returns a KeyInfo ** structure suitable for implementing the ORDER BY. ** ** Space to hold the KeyInfo structure is obtained from malloc. The calling ** function is responsible for ensuring that this structure is eventually ** freed. */ static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ ExprList *pOrderBy = p->pOrderBy; int nOrderBy = p->pOrderBy->nExpr; sqlite3 *db = pParse->db; KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); if( pRet ){ int i; for(i=0; i<nOrderBy; i++){ struct ExprList_item *pItem = &pOrderBy->a[i]; Expr *pTerm = pItem->pExpr; CollSeq *pColl; if( pTerm->flags & EP_Collate ){ pColl = sqlite3ExprCollSeq(pParse, pTerm); }else{ pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); if( pColl==0 ) pColl = db->pDfltColl; pOrderBy->a[i].pExpr = sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); } assert( sqlite3KeyInfoIsWriteable(pRet) ); pRet->aColl[i] = pColl; pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder; } } return pRet; } #ifndef SQLITE_OMIT_CTE /* ** This routine generates VDBE code to compute the content of a WITH RECURSIVE ** query of the form: ** ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) ** \___________/ \_______________/ ** p->pPrior p ** ** ** There is exactly one reference to the recursive-table in the FROM clause ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. ** ** The setup-query runs once to generate an initial set of rows that go ** into a Queue table. Rows are extracted from the Queue table one by ** one. Each row extracted from Queue is output to pDest. Then the single ** extracted row (now in the iCurrent table) becomes the content of the ** recursive-table for a recursive-query run. The output of the recursive-query ** is added back into the Queue table. Then another row is extracted from Queue ** and the iteration continues until the Queue table is empty. ** ** If the compound query operator is UNION then no duplicate rows are ever ** inserted into the Queue table. The iDistinct table keeps a copy of all rows ** that have ever been inserted into Queue and causes duplicates to be ** discarded. If the operator is UNION ALL, then duplicates are allowed. ** ** If the query has an ORDER BY, then entries in the Queue table are kept in ** ORDER BY order and the first entry is extracted for each cycle. Without ** an ORDER BY, the Queue table is just a FIFO. ** ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows ** have been output to pDest. A LIMIT of zero means to output no rows and a ** negative LIMIT means to output all rows. If there is also an OFFSET clause ** with a positive value, then the first OFFSET outputs are discarded rather ** than being sent to pDest. The LIMIT count does not begin until after OFFSET ** rows have been skipped. */ static void generateWithRecursiveQuery( Parse *pParse, /* Parsing context */ Select *p, /* The recursive SELECT to be coded */ SelectDest *pDest /* What to do with query results */ ){ SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ Select *pSetup = p->pPrior; /* The setup query */ int addrTop; /* Top of the loop */ int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ int iCurrent = 0; /* The Current table */ int regCurrent; /* Register holding Current table */ int iQueue; /* The Queue table */ int iDistinct = 0; /* To ensure unique results if UNION */ int eDest = SRT_Fifo; /* How to write to Queue */ SelectDest destQueue; /* SelectDest targetting the Queue table */ int i; /* Loop counter */ int rc; /* Result code */ ExprList *pOrderBy; /* The ORDER BY clause */ Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */ int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ /* Obtain authorization to do a recursive query */ if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; /* Process the LIMIT and OFFSET clauses, if they exist */ addrBreak = sqlite3VdbeMakeLabel(v); p->nSelectRow = 320; /* 4 billion rows */ computeLimitRegisters(pParse, p, addrBreak); pLimit = p->pLimit; pOffset = p->pOffset; regLimit = p->iLimit; regOffset = p->iOffset; p->pLimit = p->pOffset = 0; p->iLimit = p->iOffset = 0; pOrderBy = p->pOrderBy; /* Locate the cursor number of the Current table */ for(i=0; ALWAYS(i<pSrc->nSrc); i++){ if( pSrc->a[i].fg.isRecursive ){ iCurrent = pSrc->a[i].iCursor; break; } } /* Allocate cursors numbers for Queue and Distinct. The cursor number for ** the Distinct table must be exactly one greater than Queue in order ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ iQueue = pParse->nTab++; if( p->op==TK_UNION ){ eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; iDistinct = pParse->nTab++; }else{ eDest = pOrderBy ? SRT_Queue : SRT_Fifo; } sqlite3SelectDestInit(&destQueue, eDest, iQueue); /* Allocate cursors for Current, Queue, and Distinct. */ regCurrent = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); if( pOrderBy ){ KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, (char*)pKeyInfo, P4_KEYINFO); destQueue.pOrderBy = pOrderBy; }else{ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); } VdbeComment((v, "Queue table")); if( iDistinct ){ p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); p->selFlags |= SF_UsesEphemeral; } /* Detach the ORDER BY clause from the compound SELECT */ p->pOrderBy = 0; /* Store the results of the setup-query in Queue. */ pSetup->pNext = 0; rc = sqlite3Select(pParse, pSetup, &destQueue); pSetup->pNext = p; if( rc ) goto end_of_recursive_query; /* Find the next row in the Queue and output that row */ addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); /* Transfer the next row in Queue over to Current */ sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ if( pOrderBy ){ sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); }else{ sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); } sqlite3VdbeAddOp1(v, OP_Delete, iQueue); /* Output the single row in Current */ addrCont = sqlite3VdbeMakeLabel(v); codeOffset(v, regOffset, addrCont); selectInnerLoop(pParse, p, p->pEList, iCurrent, 0, 0, pDest, addrCont, addrBreak); if( regLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); VdbeCoverage(v); } sqlite3VdbeResolveLabel(v, addrCont); /* Execute the recursive SELECT taking the single row in Current as ** the value for the recursive-table. Store the results in the Queue. */ if( p->selFlags & SF_Aggregate ){ sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); }else{ p->pPrior = 0; sqlite3Select(pParse, p, &destQueue); assert( p->pPrior==0 ); p->pPrior = pSetup; } /* Keep running the loop until the Queue is empty */ sqlite3VdbeGoto(v, addrTop); sqlite3VdbeResolveLabel(v, addrBreak); end_of_recursive_query: sqlite3ExprListDelete(pParse->db, p->pOrderBy); p->pOrderBy = pOrderBy; p->pLimit = pLimit; p->pOffset = pOffset; return; } #endif /* SQLITE_OMIT_CTE */ /* Forward references */ static int multiSelectOrderBy( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ); /* ** Handle the special case of a compound-select that originates from a ** VALUES clause. By handling this as a special case, we avoid deep ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT ** on a VALUES clause. ** ** Because the Select object originates from a VALUES clause: ** (1) It has no LIMIT or OFFSET ** (2) All terms are UNION ALL ** (3) There is no ORDER BY clause */ static int multiSelectValues( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ Select *pPrior; int nRow = 1; int rc = 0; assert( p->selFlags & SF_MultiValue ); do{ assert( p->selFlags & SF_Values ); assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); assert( p->pLimit==0 ); assert( p->pOffset==0 ); assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); if( p->pPrior==0 ) break; assert( p->pPrior->pNext==p ); p = p->pPrior; nRow++; }while(1); while( p ){ pPrior = p->pPrior; p->pPrior = 0; rc = sqlite3Select(pParse, p, pDest); p->pPrior = pPrior; if( rc ) break; p->nSelectRow = nRow; p = p->pNext; } return rc; } /* ** This routine is called to process a compound query form from ** two or more separate queries using UNION, UNION ALL, EXCEPT, or ** INTERSECT ** ** "p" points to the right-most of the two queries. the query on the ** left is p->pPrior. The left query could also be a compound query ** in which case this routine will be called recursively. ** ** The results of the total query are to be written into a destination ** of type eDest with parameter iParm. ** ** Example 1: Consider a three-way compound SQL statement. ** ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 ** ** This statement is parsed up as follows: ** ** SELECT c FROM t3 ** | ** `-----> SELECT b FROM t2 ** | ** `------> SELECT a FROM t1 ** ** The arrows in the diagram above represent the Select.pPrior pointer. ** So if this routine is called with p equal to the t3 query, then ** pPrior will be the t2 query. p->op will be TK_UNION in this case. ** ** Notice that because of the way SQLite parses compound SELECTs, the ** individual selects always group from left to right. */ static int multiSelect( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ int rc = SQLITE_OK; /* Success code from a subroutine */ Select *pPrior; /* Another SELECT immediately to our left */ Vdbe *v; /* Generate code to this VDBE */ SelectDest dest; /* Alternative data destination */ Select *pDelete = 0; /* Chain of simple selects to delete */ sqlite3 *db; /* Database connection */ #ifndef SQLITE_OMIT_EXPLAIN int iSub1 = 0; /* EQP id of left-hand query */ int iSub2 = 0; /* EQP id of right-hand query */ #endif /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. */ assert( p && p->pPrior ); /* Calling function guarantees this much */ assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); db = pParse->db; pPrior = p->pPrior; dest = *pDest; if( pPrior->pOrderBy ){ sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", selectOpName(p->op)); rc = 1; goto multi_select_end; } if( pPrior->pLimit ){ sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", selectOpName(p->op)); rc = 1; goto multi_select_end; } v = sqlite3GetVdbe(pParse); assert( v!=0 ); /* The VDBE already created by calling function */ /* Create the destination temporary table if necessary */ if( dest.eDest==SRT_EphemTab ){ assert( p->pEList ); sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); dest.eDest = SRT_Table; } /* Special handling for a compound-select that originates as a VALUES clause. */ if( p->selFlags & SF_MultiValue ){ rc = multiSelectValues(pParse, p, &dest); goto multi_select_end; } /* Make sure all SELECTs in the statement have the same number of elements ** in their result sets. */ assert( p->pEList && pPrior->pEList ); assert( p->pEList->nExpr==pPrior->pEList->nExpr ); #ifndef SQLITE_OMIT_CTE if( p->selFlags & SF_Recursive ){ generateWithRecursiveQuery(pParse, p, &dest); }else #endif /* Compound SELECTs that have an ORDER BY clause are handled separately. */ if( p->pOrderBy ){ return multiSelectOrderBy(pParse, p, pDest); }else /* Generate code for the left and right SELECT statements. */ switch( p->op ){ case TK_ALL: { int addr = 0; int nLimit; assert( !pPrior->pLimit ); pPrior->iLimit = p->iLimit; pPrior->iOffset = p->iOffset; pPrior->pLimit = p->pLimit; pPrior->pOffset = p->pOffset; explainSetInteger(iSub1, pParse->iNextSelectId); rc = sqlite3Select(pParse, pPrior, &dest); p->pLimit = 0; p->pOffset = 0; if( rc ){ goto multi_select_end; } p->pPrior = 0; p->iLimit = pPrior->iLimit; p->iOffset = pPrior->iOffset; if( p->iLimit ){ addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); VdbeComment((v, "Jump ahead if LIMIT reached")); if( p->iOffset ){ sqlite3VdbeAddOp3(v, OP_OffsetLimit, p->iLimit, p->iOffset+1, p->iOffset); } } explainSetInteger(iSub2, pParse->iNextSelectId); rc = sqlite3Select(pParse, p, &dest); testcase( rc!=SQLITE_OK ); pDelete = p->pPrior; p->pPrior = pPrior; p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); if( pPrior->pLimit && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) ){ p->nSelectRow = sqlite3LogEst((u64)nLimit); } if( addr ){ sqlite3VdbeJumpHere(v, addr); } break; } case TK_EXCEPT: case TK_UNION: { int unionTab; /* Cursor number of the temporary table holding result */ u8 op = 0; /* One of the SRT_ operations to apply to self */ int priorOp; /* The SRT_ operation to apply to prior selects */ Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ int addr; SelectDest uniondest; testcase( p->op==TK_EXCEPT ); testcase( p->op==TK_UNION ); priorOp = SRT_Union; if( dest.eDest==priorOp ){ /* We can reuse a temporary table generated by a SELECT to our ** right. */ assert( p->pLimit==0 ); /* Not allowed on leftward elements */ assert( p->pOffset==0 ); /* Not allowed on leftward elements */ unionTab = dest.iSDParm; }else{ /* We will need to create our own temporary table to hold the ** intermediate results. */ unionTab = pParse->nTab++; assert( p->pOrderBy==0 ); addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); } /* Code the SELECT statements to our left */ assert( !pPrior->pOrderBy ); sqlite3SelectDestInit(&uniondest, priorOp, unionTab); explainSetInteger(iSub1, pParse->iNextSelectId); rc = sqlite3Select(pParse, pPrior, &uniondest); if( rc ){ goto multi_select_end; } /* Code the current SELECT statement */ if( p->op==TK_EXCEPT ){ op = SRT_Except; }else{ assert( p->op==TK_UNION ); op = SRT_Union; } p->pPrior = 0; pLimit = p->pLimit; p->pLimit = 0; pOffset = p->pOffset; p->pOffset = 0; uniondest.eDest = op; explainSetInteger(iSub2, pParse->iNextSelectId); rc = sqlite3Select(pParse, p, &uniondest); testcase( rc!=SQLITE_OK ); /* Query flattening in sqlite3Select() might refill p->pOrderBy. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ sqlite3ExprListDelete(db, p->pOrderBy); pDelete = p->pPrior; p->pPrior = pPrior; p->pOrderBy = 0; if( p->op==TK_UNION ){ p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } sqlite3ExprDelete(db, p->pLimit); p->pLimit = pLimit; p->pOffset = pOffset; p->iLimit = 0; p->iOffset = 0; /* Convert the data in the temporary table into whatever form ** it is that we currently need. */ assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); if( dest.eDest!=priorOp ){ int iCont, iBreak, iStart; assert( p->pEList ); if( dest.eDest==SRT_Output ){ Select *pFirst = p; while( pFirst->pPrior ) pFirst = pFirst->pPrior; generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); } iBreak = sqlite3VdbeMakeLabel(v); iCont = sqlite3VdbeMakeLabel(v); computeLimitRegisters(pParse, p, iBreak); sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); iStart = sqlite3VdbeCurrentAddr(v); selectInnerLoop(pParse, p, p->pEList, unionTab, 0, 0, &dest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); sqlite3VdbeResolveLabel(v, iBreak); sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); } break; } default: assert( p->op==TK_INTERSECT ); { int tab1, tab2; int iCont, iBreak, iStart; Expr *pLimit, *pOffset; int addr; SelectDest intersectdest; int r1; /* INTERSECT is different from the others since it requires ** two temporary tables. Hence it has its own case. Begin ** by allocating the tables we will need. */ tab1 = pParse->nTab++; tab2 = pParse->nTab++; assert( p->pOrderBy==0 ); addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); /* Code the SELECTs to our left into temporary table "tab1". */ sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); explainSetInteger(iSub1, pParse->iNextSelectId); rc = sqlite3Select(pParse, pPrior, &intersectdest); if( rc ){ goto multi_select_end; } /* Code the current SELECT into temporary table "tab2" */ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); assert( p->addrOpenEphm[1] == -1 ); p->addrOpenEphm[1] = addr; p->pPrior = 0; pLimit = p->pLimit; p->pLimit = 0; pOffset = p->pOffset; p->pOffset = 0; intersectdest.iSDParm = tab2; explainSetInteger(iSub2, pParse->iNextSelectId); rc = sqlite3Select(pParse, p, &intersectdest); testcase( rc!=SQLITE_OK ); pDelete = p->pPrior; p->pPrior = pPrior; if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; sqlite3ExprDelete(db, p->pLimit); p->pLimit = pLimit; p->pOffset = pOffset; /* Generate code to take the intersection of the two temporary ** tables. */ assert( p->pEList ); if( dest.eDest==SRT_Output ){ Select *pFirst = p; while( pFirst->pPrior ) pFirst = pFirst->pPrior; generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); } iBreak = sqlite3VdbeMakeLabel(v); iCont = sqlite3VdbeMakeLabel(v); computeLimitRegisters(pParse, p, iBreak); sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); r1 = sqlite3GetTempReg(pParse); iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, r1); selectInnerLoop(pParse, p, p->pEList, tab1, 0, 0, &dest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); sqlite3VdbeResolveLabel(v, iBreak); sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); break; } } explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); /* Compute collating sequences used by ** temporary tables needed to implement the compound select. ** Attach the KeyInfo structure to all temporary tables. ** ** This section is run by the right-most SELECT statement only. ** SELECT statements to the left always skip this part. The right-most ** SELECT might also skip this part if it has no ORDER BY clause and ** no temp tables are required. */ if( p->selFlags & SF_UsesEphemeral ){ int i; /* Loop counter */ KeyInfo *pKeyInfo; /* Collating sequence for the result set */ Select *pLoop; /* For looping through SELECT statements */ CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ int nCol; /* Number of columns in result set */ assert( p->pNext==0 ); nCol = p->pEList->nExpr; pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); if( !pKeyInfo ){ rc = SQLITE_NOMEM_BKPT; goto multi_select_end; } for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ *apColl = multiSelectCollSeq(pParse, p, i); if( 0==*apColl ){ *apColl = db->pDfltColl; } } for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ for(i=0; i<2; i++){ int addr = pLoop->addrOpenEphm[i]; if( addr<0 ){ /* If [0] is unused then [1] is also unused. So we can ** always safely abort as soon as the first unused slot is found */ assert( pLoop->addrOpenEphm[1]<0 ); break; } sqlite3VdbeChangeP2(v, addr, nCol); sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); pLoop->addrOpenEphm[i] = -1; } } sqlite3KeyInfoUnref(pKeyInfo); } multi_select_end: pDest->iSdst = dest.iSdst; pDest->nSdst = dest.nSdst; sqlite3SelectDelete(db, pDelete); return rc; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ /* ** Error message for when two or more terms of a compound select have different ** size result sets. */ SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ if( p->selFlags & SF_Values ){ sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); }else{ sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" " do not have the same number of result columns", selectOpName(p->op)); } } /* ** Code an output subroutine for a coroutine implementation of a ** SELECT statment. ** ** The data to be output is contained in pIn->iSdst. There are ** pIn->nSdst columns to be output. pDest is where the output should ** be sent. ** ** regReturn is the number of the register holding the subroutine ** return address. ** ** If regPrev>0 then it is the first register in a vector that ** records the previous output. mem[regPrev] is a flag that is false ** if there has been no previous output. If regPrev>0 then code is ** generated to suppress duplicates. pKeyInfo is used for comparing ** keys. ** ** If the LIMIT found in p->iLimit is reached, jump immediately to ** iBreak. */ static int generateOutputSubroutine( Parse *pParse, /* Parsing context */ Select *p, /* The SELECT statement */ SelectDest *pIn, /* Coroutine supplying data */ SelectDest *pDest, /* Where to send the data */ int regReturn, /* The return address register */ int regPrev, /* Previous result register. No uniqueness if 0 */ KeyInfo *pKeyInfo, /* For comparing with previous entry */ int iBreak /* Jump here if we hit the LIMIT */ ){ Vdbe *v = pParse->pVdbe; int iContinue; int addr; addr = sqlite3VdbeCurrentAddr(v); iContinue = sqlite3VdbeMakeLabel(v); /* Suppress duplicates for UNION, EXCEPT, and INTERSECT */ if( regPrev ){ int addr1, addr2; addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); } if( pParse->db->mallocFailed ) return 0; /* Suppress the first OFFSET entries if there is an OFFSET clause */ codeOffset(v, p->iOffset, iContinue); assert( pDest->eDest!=SRT_Exists ); assert( pDest->eDest!=SRT_Table ); switch( pDest->eDest ){ /* Store the result as data using a unique key. */ case SRT_EphemTab: { int r1 = sqlite3GetTempReg(pParse); int r2 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3ReleaseTempReg(pParse, r2); sqlite3ReleaseTempReg(pParse, r1); break; } #ifndef SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)". */ case SRT_Set: { int r1; testcase( pIn->nSdst>1 ); r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1, pDest->zAffSdst, pIn->nSdst); sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, pIn->iSdst, pIn->nSdst); sqlite3ReleaseTempReg(pParse, r1); break; } /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell and break out ** of the scan loop. */ case SRT_Mem: { assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 ); sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); /* The LIMIT clause will jump out of the loop for us */ break; } #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ /* The results are stored in a sequence of registers ** starting at pDest->iSdst. Then the co-routine yields. */ case SRT_Coroutine: { if( pDest->iSdst==0 ){ pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); pDest->nSdst = pIn->nSdst; } sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); break; } /* If none of the above, then the result destination must be ** SRT_Output. This routine is never called with any other ** destination other than the ones handled above or SRT_Output. ** ** For SRT_Output, results are stored in a sequence of registers. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to ** return the next row of result. */ default: { assert( pDest->eDest==SRT_Output ); sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); break; } } /* Jump to the end of the loop if the LIMIT is reached. */ if( p->iLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); } /* Generate the subroutine return */ sqlite3VdbeResolveLabel(v, iContinue); sqlite3VdbeAddOp1(v, OP_Return, regReturn); return addr; } /* ** Alternative compound select code generator for cases when there ** is an ORDER BY clause. ** ** We assume a query of the following form: ** ** <selectA> <operator> <selectB> ORDER BY <orderbylist> ** ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea ** is to code both <selectA> and <selectB> with the ORDER BY clause as ** co-routines. Then run the co-routines in parallel and merge the results ** into the output. In addition to the two coroutines (called selectA and ** selectB) there are 7 subroutines: ** ** outA: Move the output of the selectA coroutine into the output ** of the compound query. ** ** outB: Move the output of the selectB coroutine into the output ** of the compound query. (Only generated for UNION and ** UNION ALL. EXCEPT and INSERTSECT never output a row that ** appears only in B.) ** ** AltB: Called when there is data from both coroutines and A<B. ** ** AeqB: Called when there is data from both coroutines and A==B. ** ** AgtB: Called when there is data from both coroutines and A>B. ** ** EofA: Called when data is exhausted from selectA. ** ** EofB: Called when data is exhausted from selectB. ** ** The implementation of the latter five subroutines depend on which ** <operator> is used: ** ** ** UNION ALL UNION EXCEPT INTERSECT ** ------------- ----------------- -------------- ----------------- ** AltB: outA, nextA outA, nextA outA, nextA nextA ** ** AeqB: outA, nextA nextA nextA outA, nextA ** ** AgtB: outB, nextB outB, nextB nextB nextB ** ** EofA: outB, nextB outB, nextB halt halt ** ** EofB: outA, nextA outA, nextA outA, nextA halt ** ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA ** causes an immediate jump to EofA and an EOF on B following nextB causes ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or ** following nextX causes a jump to the end of the select processing. ** ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled ** within the output subroutine. The regPrev register set holds the previously ** output value. A comparison is made against this value and the output ** is skipped if the next results would be the same as the previous. ** ** The implementation plan is to implement the two coroutines and seven ** subroutines first, then put the control logic at the bottom. Like this: ** ** goto Init ** coA: coroutine for left query (A) ** coB: coroutine for right query (B) ** outA: output one row of A ** outB: output one row of B (UNION and UNION ALL only) ** EofA: ... ** EofB: ... ** AltB: ... ** AeqB: ... ** AgtB: ... ** Init: initialize coroutine registers ** yield coA ** if eof(A) goto EofA ** yield coB ** if eof(B) goto EofB ** Cmpr: Compare A, B ** Jump AltB, AeqB, AgtB ** End: ... ** ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not ** actually called using Gosub and they do not Return. EofA and EofB loop ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, ** and AgtB jump to either L2 or to one of EofA or EofB. */ #ifndef SQLITE_OMIT_COMPOUND_SELECT static int multiSelectOrderBy( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ int i, j; /* Loop counters */ Select *pPrior; /* Another SELECT immediately to our left */ Vdbe *v; /* Generate code to this VDBE */ SelectDest destA; /* Destination for coroutine A */ SelectDest destB; /* Destination for coroutine B */ int regAddrA; /* Address register for select-A coroutine */ int regAddrB; /* Address register for select-B coroutine */ int addrSelectA; /* Address of the select-A coroutine */ int addrSelectB; /* Address of the select-B coroutine */ int regOutA; /* Address register for the output-A subroutine */ int regOutB; /* Address register for the output-B subroutine */ int addrOutA; /* Address of the output-A subroutine */ int addrOutB = 0; /* Address of the output-B subroutine */ int addrEofA; /* Address of the select-A-exhausted subroutine */ int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ int addrEofB; /* Address of the select-B-exhausted subroutine */ int addrAltB; /* Address of the A<B subroutine */ int addrAeqB; /* Address of the A==B subroutine */ int addrAgtB; /* Address of the A>B subroutine */ int regLimitA; /* Limit register for select-A */ int regLimitB; /* Limit register for select-A */ int regPrev; /* A range of registers to hold previous output */ int savedLimit; /* Saved value of p->iLimit */ int savedOffset; /* Saved value of p->iOffset */ int labelCmpr; /* Label for the start of the merge algorithm */ int labelEnd; /* Label for the end of the overall SELECT stmt */ int addr1; /* Jump instructions that get retargetted */ int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ KeyInfo *pKeyMerge; /* Comparison information for merging rows */ sqlite3 *db; /* Database connection */ ExprList *pOrderBy; /* The ORDER BY clause */ int nOrderBy; /* Number of terms in the ORDER BY clause */ int *aPermute; /* Mapping from ORDER BY terms to result set columns */ #ifndef SQLITE_OMIT_EXPLAIN int iSub1; /* EQP id of left-hand query */ int iSub2; /* EQP id of right-hand query */ #endif assert( p->pOrderBy!=0 ); assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ db = pParse->db; v = pParse->pVdbe; assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ labelEnd = sqlite3VdbeMakeLabel(v); labelCmpr = sqlite3VdbeMakeLabel(v); /* Patch up the ORDER BY clause */ op = p->op; pPrior = p->pPrior; assert( pPrior->pOrderBy==0 ); pOrderBy = p->pOrderBy; assert( pOrderBy ); nOrderBy = pOrderBy->nExpr; /* For operators other than UNION ALL we have to make sure that ** the ORDER BY clause covers every term of the result set. Add ** terms to the ORDER BY clause as necessary. */ if( op!=TK_ALL ){ for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ struct ExprList_item *pItem; for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ assert( pItem->u.x.iOrderByCol>0 ); if( pItem->u.x.iOrderByCol==i ) break; } if( j==nOrderBy ){ Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); if( pNew==0 ) return SQLITE_NOMEM_BKPT; pNew->flags |= EP_IntValue; pNew->u.iValue = i; pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; } } } /* Compute the comparison permutation and keyinfo that is used with ** the permutation used to determine if the next ** row of results comes from selectA or selectB. Also add explicit ** collations to the ORDER BY clause terms so that when the subqueries ** to the right and the left are evaluated, they use the correct ** collation. */ aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); if( aPermute ){ struct ExprList_item *pItem; aPermute[0] = nOrderBy; for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ assert( pItem->u.x.iOrderByCol>0 ); assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); aPermute[i] = pItem->u.x.iOrderByCol - 1; } pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); }else{ pKeyMerge = 0; } /* Reattach the ORDER BY clause to the query. */ p->pOrderBy = pOrderBy; pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); /* Allocate a range of temporary registers and the KeyInfo needed ** for the logic that removes duplicate result rows when the ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). */ if( op==TK_ALL ){ regPrev = 0; }else{ int nExpr = p->pEList->nExpr; assert( nOrderBy>=nExpr || db->mallocFailed ); regPrev = pParse->nMem+1; pParse->nMem += nExpr+1; sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); if( pKeyDup ){ assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); for(i=0; i<nExpr; i++){ pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); pKeyDup->aSortOrder[i] = 0; } } } /* Separate the left and the right query from one another */ p->pPrior = 0; pPrior->pNext = 0; sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); if( pPrior->pPrior==0 ){ sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); } /* Compute the limit registers */ computeLimitRegisters(pParse, p, labelEnd); if( p->iLimit && op==TK_ALL ){ regLimitA = ++pParse->nMem; regLimitB = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, regLimitA); sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); }else{ regLimitA = regLimitB = 0; } sqlite3ExprDelete(db, p->pLimit); p->pLimit = 0; sqlite3ExprDelete(db, p->pOffset); p->pOffset = 0; regAddrA = ++pParse->nMem; regAddrB = ++pParse->nMem; regOutA = ++pParse->nMem; regOutB = ++pParse->nMem; sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); /* Generate a coroutine to evaluate the SELECT statement to the ** left of the compound operator - the "A" select. */ addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); VdbeComment((v, "left SELECT")); pPrior->iLimit = regLimitA; explainSetInteger(iSub1, pParse->iNextSelectId); sqlite3Select(pParse, pPrior, &destA); sqlite3VdbeEndCoroutine(v, regAddrA); sqlite3VdbeJumpHere(v, addr1); /* Generate a coroutine to evaluate the SELECT statement on ** the right - the "B" select */ addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); VdbeComment((v, "right SELECT")); savedLimit = p->iLimit; savedOffset = p->iOffset; p->iLimit = regLimitB; p->iOffset = 0; explainSetInteger(iSub2, pParse->iNextSelectId); sqlite3Select(pParse, p, &destB); p->iLimit = savedLimit; p->iOffset = savedOffset; sqlite3VdbeEndCoroutine(v, regAddrB); /* Generate a subroutine that outputs the current row of the A ** select as the next output row of the compound select. */ VdbeNoopComment((v, "Output routine for A")); addrOutA = generateOutputSubroutine(pParse, p, &destA, pDest, regOutA, regPrev, pKeyDup, labelEnd); /* Generate a subroutine that outputs the current row of the B ** select as the next output row of the compound select. */ if( op==TK_ALL || op==TK_UNION ){ VdbeNoopComment((v, "Output routine for B")); addrOutB = generateOutputSubroutine(pParse, p, &destB, pDest, regOutB, regPrev, pKeyDup, labelEnd); } sqlite3KeyInfoUnref(pKeyDup); /* Generate a subroutine to run when the results from select A ** are exhausted and only data in select B remains. */ if( op==TK_EXCEPT || op==TK_INTERSECT ){ addrEofA_noB = addrEofA = labelEnd; }else{ VdbeNoopComment((v, "eof-A subroutine")); addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); VdbeCoverage(v); sqlite3VdbeGoto(v, addrEofA); p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } /* Generate a subroutine to run when the results from select B ** are exhausted and only data in select A remains. */ if( op==TK_INTERSECT ){ addrEofB = addrEofA; if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; }else{ VdbeNoopComment((v, "eof-B subroutine")); addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); sqlite3VdbeGoto(v, addrEofB); } /* Generate code to handle the case of A<B */ VdbeNoopComment((v, "A-lt-B subroutine")); addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); sqlite3VdbeGoto(v, labelCmpr); /* Generate code to handle the case of A==B */ if( op==TK_ALL ){ addrAeqB = addrAltB; }else if( op==TK_INTERSECT ){ addrAeqB = addrAltB; addrAltB++; }else{ VdbeNoopComment((v, "A-eq-B subroutine")); addrAeqB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); sqlite3VdbeGoto(v, labelCmpr); } /* Generate code to handle the case of A>B */ VdbeNoopComment((v, "A-gt-B subroutine")); addrAgtB = sqlite3VdbeCurrentAddr(v); if( op==TK_ALL || op==TK_UNION ){ sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); } sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); sqlite3VdbeGoto(v, labelCmpr); /* This code runs once to initialize everything. */ sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); /* Implement the main merge loop */ sqlite3VdbeResolveLabel(v, labelCmpr); sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, (char*)pKeyMerge, P4_KEYINFO); sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); /* Jump to the this point in order to terminate the query. */ sqlite3VdbeResolveLabel(v, labelEnd); /* Set the number of output columns */ if( pDest->eDest==SRT_Output ){ Select *pFirst = pPrior; while( pFirst->pPrior ) pFirst = pFirst->pPrior; generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); } /* Reassembly the compound query so that it will be freed correctly ** by the calling function */ if( p->pPrior ){ sqlite3SelectDelete(db, p->pPrior); } p->pPrior = pPrior; pPrior->pNext = p; /*** TBD: Insert subroutine calls to close cursors on incomplete **** subqueries ****/ explainComposite(pParse, p->op, iSub1, iSub2, 0); return pParse->nErr!=0; } #endif #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* Forward Declarations */ static void substExprList(Parse*, ExprList*, int, ExprList*); static void substSelect(Parse*, Select *, int, ExprList*, int); /* ** Scan through the expression pExpr. Replace every reference to ** a column in table number iTable with a copy of the iColumn-th ** entry in pEList. (But leave references to the ROWID column ** unchanged.) ** ** This routine is part of the flattening procedure. A subquery ** whose result set is defined by pEList appears as entry in the ** FROM clause of a SELECT such that the VDBE cursor assigned to that ** FORM clause entry is iTable. This routine make the necessary ** changes to pExpr so that it refers directly to the source table ** of the subquery rather the result set of the subquery. */ static Expr *substExpr( Parse *pParse, /* Report errors here */ Expr *pExpr, /* Expr in which substitution occurs */ int iTable, /* Table to be substituted */ ExprList *pEList /* Substitute expressions */ ){ sqlite3 *db = pParse->db; if( pExpr==0 ) return 0; if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ if( pExpr->iColumn<0 ){ pExpr->op = TK_NULL; }else{ Expr *pNew; Expr *pCopy = pEList->a[pExpr->iColumn].pExpr; assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); assert( pExpr->pLeft==0 && pExpr->pRight==0 ); if( sqlite3ExprIsVector(pCopy) ){ sqlite3VectorErrorMsg(pParse, pCopy); }else{ pNew = sqlite3ExprDup(db, pCopy, 0); if( pNew && (pExpr->flags & EP_FromJoin) ){ pNew->iRightJoinTable = pExpr->iRightJoinTable; pNew->flags |= EP_FromJoin; } sqlite3ExprDelete(db, pExpr); pExpr = pNew; } } }else{ pExpr->pLeft = substExpr(pParse, pExpr->pLeft, iTable, pEList); pExpr->pRight = substExpr(pParse, pExpr->pRight, iTable, pEList); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ substSelect(pParse, pExpr->x.pSelect, iTable, pEList, 1); }else{ substExprList(pParse, pExpr->x.pList, iTable, pEList); } } return pExpr; } static void substExprList( Parse *pParse, /* Report errors here */ ExprList *pList, /* List to scan and in which to make substitutes */ int iTable, /* Table to be substituted */ ExprList *pEList /* Substitute values */ ){ int i; if( pList==0 ) return; for(i=0; i<pList->nExpr; i++){ pList->a[i].pExpr = substExpr(pParse, pList->a[i].pExpr, iTable, pEList); } } static void substSelect( Parse *pParse, /* Report errors here */ Select *p, /* SELECT statement in which to make substitutions */ int iTable, /* Table to be replaced */ ExprList *pEList, /* Substitute values */ int doPrior /* Do substitutes on p->pPrior too */ ){ SrcList *pSrc; struct SrcList_item *pItem; int i; if( !p ) return; do{ substExprList(pParse, p->pEList, iTable, pEList); substExprList(pParse, p->pGroupBy, iTable, pEList); substExprList(pParse, p->pOrderBy, iTable, pEList); p->pHaving = substExpr(pParse, p->pHaving, iTable, pEList); p->pWhere = substExpr(pParse, p->pWhere, iTable, pEList); pSrc = p->pSrc; assert( pSrc!=0 ); for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ substSelect(pParse, pItem->pSelect, iTable, pEList, 1); if( pItem->fg.isTabFunc ){ substExprList(pParse, pItem->u1.pFuncArg, iTable, pEList); } } }while( doPrior && (p = p->pPrior)!=0 ); } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* ** This routine attempts to flatten subqueries as a performance optimization. ** This routine returns 1 if it makes changes and 0 if no flattening occurs. ** ** To understand the concept of flattening, consider the following ** query: ** ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 ** ** The default way of implementing this query is to execute the ** subquery first and store the results in a temporary table, then ** run the outer query on that temporary table. This requires two ** passes over the data. Furthermore, because the temporary table ** has no indices, the WHERE clause on the outer query cannot be ** optimized. ** ** This routine attempts to rewrite queries such as the above into ** a single flat select, like this: ** ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 ** ** The code generated for this simplification gives the same result ** but only has to scan the data once. And because indices might ** exist on the table t1, a complete scan of the data might be ** avoided. ** ** Flattening is only attempted if all of the following are true: ** ** (1) The subquery and the outer query do not both use aggregates. ** ** (2) The subquery is not an aggregate or (2a) the outer query is not a join ** and (2b) the outer query does not use subqueries other than the one ** FROM-clause subquery that is a candidate for flattening. (2b is ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.) ** ** (3) The subquery is not the right operand of a left outer join ** (Originally ticket #306. Strengthened by ticket #3300) ** ** (4) The subquery is not DISTINCT. ** ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT ** sub-queries that were excluded from this optimization. Restriction ** (4) has since been expanded to exclude all DISTINCT subqueries. ** ** (6) The subquery does not use aggregates or the outer query is not ** DISTINCT. ** ** (7) The subquery has a FROM clause. TODO: For subqueries without ** A FROM clause, consider adding a FROM close with the special ** table sqlite_once that consists of a single row containing a ** single NULL. ** ** (8) The subquery does not use LIMIT or the outer query is not a join. ** ** (9) The subquery does not use LIMIT or the outer query does not use ** aggregates. ** ** (**) Restriction (10) was removed from the code on 2005-02-05 but we ** accidently carried the comment forward until 2014-09-15. Original ** text: "The subquery does not use aggregates or the outer query ** does not use LIMIT." ** ** (11) The subquery and the outer query do not both have ORDER BY clauses. ** ** (**) Not implemented. Subsumed into restriction (3). Was previously ** a separate restriction deriving from ticket #350. ** ** (13) The subquery and outer query do not both use LIMIT. ** ** (14) The subquery does not use OFFSET. ** ** (15) The outer query is not part of a compound select or the ** subquery does not have a LIMIT clause. ** (See ticket #2339 and ticket [02a8e81d44]). ** ** (16) The outer query is not an aggregate or the subquery does ** not contain ORDER BY. (Ticket #2942) This used to not matter ** until we introduced the group_concat() function. ** ** (17) The sub-query is not a compound select, or it is a UNION ALL ** compound clause made up entirely of non-aggregate queries, and ** the parent query: ** ** * is not itself part of a compound select, ** * is not an aggregate or DISTINCT query, and ** * is not a join ** ** The parent and sub-query may contain WHERE clauses. Subject to ** rules (11), (13) and (14), they may also contain ORDER BY, ** LIMIT and OFFSET clauses. The subquery cannot use any compound ** operator other than UNION ALL because all the other compound ** operators have an implied DISTINCT which is disallowed by ** restriction (4). ** ** Also, each component of the sub-query must return the same number ** of result columns. This is actually a requirement for any compound ** SELECT statement, but all the code here does is make sure that no ** such (illegal) sub-query is flattened. The caller will detect the ** syntax error and return a detailed message. ** ** (18) If the sub-query is a compound select, then all terms of the ** ORDER by clause of the parent must be simple references to ** columns of the sub-query. ** ** (19) The subquery does not use LIMIT or the outer query does not ** have a WHERE clause. ** ** (20) If the sub-query is a compound select, then it must not use ** an ORDER BY clause. Ticket #3773. We could relax this constraint ** somewhat by saying that the terms of the ORDER BY clause must ** appear as unmodified result columns in the outer query. But we ** have other optimizations in mind to deal with that case. ** ** (21) The subquery does not use LIMIT or the outer query is not ** DISTINCT. (See ticket [752e1646fc]). ** ** (22) The subquery is not a recursive CTE. ** ** (23) The parent is not a recursive CTE, or the sub-query is not a ** compound query. This restriction is because transforming the ** parent to a compound query confuses the code that handles ** recursive queries in multiSelect(). ** ** (24) The subquery is not an aggregate that uses the built-in min() or ** or max() functions. (Without this restriction, a query like: ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily ** return the value X for which Y was maximal.) ** ** ** In this routine, the "p" parameter is a pointer to the outer query. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. ** ** If flattening is not attempted, this routine is a no-op and returns 0. ** If flattening is attempted this routine returns 1. ** ** All of the expression analysis must occur on both the outer query and ** the subquery before this routine runs. */ static int flattenSubquery( Parse *pParse, /* Parsing context */ Select *p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ int isAgg, /* True if outer SELECT uses aggregate functions */ int subqueryIsAgg /* True if the subquery uses aggregate functions */ ){ const char *zSavedAuthContext = pParse->zAuthContext; Select *pParent; /* Current UNION ALL term of the other query */ Select *pSub; /* The inner query or "subquery" */ Select *pSub1; /* Pointer to the rightmost select in sub-query */ SrcList *pSrc; /* The FROM clause of the outer query */ SrcList *pSubSrc; /* The FROM clause of the subquery */ ExprList *pList; /* The result set of the outer query */ int iParent; /* VDBE cursor number of the pSub result set temp table */ int i; /* Loop counter */ Expr *pWhere; /* The WHERE clause */ struct SrcList_item *pSubitem; /* The subquery */ sqlite3 *db = pParse->db; /* Check to see if flattening is permitted. Return 0 if not. */ assert( p!=0 ); assert( p->pPrior==0 ); /* Unable to flatten compound queries */ if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; pSrc = p->pSrc; assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); pSubitem = &pSrc->a[iFrom]; iParent = pSubitem->iCursor; pSub = pSubitem->pSelect; assert( pSub!=0 ); if( subqueryIsAgg ){ if( isAgg ) return 0; /* Restriction (1) */ if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */ if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery)) || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0 || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0 ){ return 0; /* Restriction (2b) */ } } pSubSrc = pSub->pSrc; assert( pSubSrc ); /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET ** because they could be computed at compile-time. But when LIMIT and OFFSET ** became arbitrary expressions, we were forced to add restrictions (13) ** and (14). */ if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ if( pSub->pOffset ) return 0; /* Restriction (14) */ if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ return 0; /* Restriction (15) */ } if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ return 0; /* Restrictions (8)(9) */ } if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ return 0; /* Restriction (6) */ } if( p->pOrderBy && pSub->pOrderBy ){ return 0; /* Restriction (11) */ } if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ return 0; /* Restriction (21) */ } testcase( pSub->selFlags & SF_Recursive ); testcase( pSub->selFlags & SF_MinMaxAgg ); if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){ return 0; /* Restrictions (22) and (24) */ } if( (p->selFlags & SF_Recursive) && pSub->pPrior ){ return 0; /* Restriction (23) */ } /* OBSOLETE COMMENT 1: ** Restriction 3: If the subquery is a join, make sure the subquery is ** not used as the right operand of an outer join. Examples of why this ** is not allowed: ** ** t1 LEFT OUTER JOIN (t2 JOIN t3) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) JOIN t3 ** ** which is not at all the same thing. ** ** OBSOLETE COMMENT 2: ** Restriction 12: If the subquery is the right operand of a left outer ** join, make sure the subquery has no WHERE clause. ** An examples of why this is not allowed: ** ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 ** ** But the t2.x>0 test will always fail on a NULL row of t2, which ** effectively converts the OUTER JOIN into an INNER JOIN. ** ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: ** Ticket #3300 shows that flattening the right term of a LEFT JOIN ** is fraught with danger. Best to avoid the whole thing. If the ** subquery is the right term of a LEFT JOIN, then do not flatten. */ if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ return 0; } /* Restriction 17: If the sub-query is a compound SELECT, then it must ** use only the UNION ALL operator. And none of the simple select queries ** that make up the compound SELECT are allowed to be aggregate or distinct ** queries. */ if( pSub->pPrior ){ if( pSub->pOrderBy ){ return 0; /* Restriction 20 */ } if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ return 0; } for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); assert( pSub->pSrc!=0 ); assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 || (pSub1->pPrior && pSub1->op!=TK_ALL) || pSub1->pSrc->nSrc<1 ){ return 0; } testcase( pSub1->pSrc->nSrc>1 ); } /* Restriction 18. */ if( p->pOrderBy ){ int ii; for(ii=0; ii<p->pOrderBy->nExpr; ii++){ if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; } } } /***** If we reach this point, flattening is permitted. *****/ SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n", pSub->zSelName, pSub, iFrom)); /* Authorize the subquery */ pParse->zAuthContext = pSubitem->zName; TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); testcase( i==SQLITE_DENY ); pParse->zAuthContext = zSavedAuthContext; /* If the sub-query is a compound SELECT statement, then (by restrictions ** 17 and 18 above) it must be a UNION ALL and the parent query must ** be of the form: ** ** SELECT <expr-list> FROM (<sub-query>) <where-clause> ** ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or ** OFFSET clauses and joins them to the left-hand-side of the original ** using UNION ALL operators. In this case N is the number of simple ** select statements in the compound sub-query. ** ** Example: ** ** SELECT a+1 FROM ( ** SELECT x FROM tab ** UNION ALL ** SELECT y FROM tab ** UNION ALL ** SELECT abs(z*2) FROM tab2 ** ) WHERE a!=5 ORDER BY 1 ** ** Transformed into: ** ** SELECT x+1 FROM tab WHERE x+1!=5 ** UNION ALL ** SELECT y+1 FROM tab WHERE y+1!=5 ** UNION ALL ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 ** ORDER BY 1 ** ** We call this the "compound-subquery flattening". */ for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ Select *pNew; ExprList *pOrderBy = p->pOrderBy; Expr *pLimit = p->pLimit; Expr *pOffset = p->pOffset; Select *pPrior = p->pPrior; p->pOrderBy = 0; p->pSrc = 0; p->pPrior = 0; p->pLimit = 0; p->pOffset = 0; pNew = sqlite3SelectDup(db, p, 0); sqlite3SelectSetName(pNew, pSub->zSelName); p->pOffset = pOffset; p->pLimit = pLimit; p->pOrderBy = pOrderBy; p->pSrc = pSrc; p->op = TK_ALL; if( pNew==0 ){ p->pPrior = pPrior; }else{ pNew->pPrior = pPrior; if( pPrior ) pPrior->pNext = pNew; pNew->pNext = p; p->pPrior = pNew; SELECTTRACE(2,pParse,p, ("compound-subquery flattener creates %s.%p as peer\n", pNew->zSelName, pNew)); } if( db->mallocFailed ) return 1; } /* Begin flattening the iFrom-th entry of the FROM clause ** in the outer query. */ pSub = pSub1 = pSubitem->pSelect; /* Delete the transient table structure associated with the ** subquery */ sqlite3DbFree(db, pSubitem->zDatabase); sqlite3DbFree(db, pSubitem->zName); sqlite3DbFree(db, pSubitem->zAlias); pSubitem->zDatabase = 0; pSubitem->zName = 0; pSubitem->zAlias = 0; pSubitem->pSelect = 0; /* Defer deleting the Table object associated with the ** subquery until code generation is ** complete, since there may still exist Expr.pTab entries that ** refer to the subquery even after flattening. Ticket #3346. ** ** pSubitem->pTab is always non-NULL by test restrictions and tests above. */ if( ALWAYS(pSubitem->pTab!=0) ){ Table *pTabToDel = pSubitem->pTab; if( pTabToDel->nTabRef==1 ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pTabToDel->pNextZombie = pToplevel->pZombieTab; pToplevel->pZombieTab = pTabToDel; }else{ pTabToDel->nTabRef--; } pSubitem->pTab = 0; } /* The following loop runs once for each term in a compound-subquery ** flattening (as described above). If we are doing a different kind ** of flattening - a flattening other than a compound-subquery flattening - ** then this loop only runs once. ** ** This loop moves all of the FROM elements of the subquery into the ** the FROM clause of the outer query. Before doing this, remember ** the cursor number for the original outer query FROM element in ** iParent. The iParent cursor will never be used. Subsequent code ** will scan expressions looking for iParent references and replace ** those references with expressions that resolve to the subquery FROM ** elements we are now copying in. */ for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ int nSubSrc; u8 jointype = 0; pSubSrc = pSub->pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent->pSrc; /* FROM clause of the outer query */ if( pSrc ){ assert( pParent==p ); /* First time through the loop */ jointype = pSubitem->fg.jointype; }else{ assert( pParent!=p ); /* 2nd and subsequent times through the loop */ pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); if( pSrc==0 ){ assert( db->mallocFailed ); break; } } /* The subquery uses a single slot of the FROM clause of the outer ** query. If the subquery has more than one element in its FROM clause, ** then expand the outer query to make space for it to hold all elements ** of the subquery. ** ** Example: ** ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; ** ** The outer query has 3 slots in its FROM clause. One slot of the ** outer query (the middle slot) is used by the subquery. The next ** block of code will expand the outer query FROM clause to 4 slots. ** The middle slot is expanded to two slots in order to make space ** for the two elements in the FROM clause of the subquery. */ if( nSubSrc>1 ){ pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); if( db->mallocFailed ){ break; } } /* Transfer the FROM clause terms from the subquery into the ** outer query. */ for(i=0; i<nSubSrc; i++){ sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); pSrc->a[i+iFrom] = pSubSrc->a[i]; memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } pSrc->a[iFrom].fg.jointype = jointype; /* Now begin substituting subquery result set expressions for ** references to the iParent in the outer query. ** ** Example: ** ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; ** \ \_____________ subquery __________/ / ** \_____________________ outer query ______________________________/ ** ** We look at every expression in the outer query and every place we see ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". */ pList = pParent->pEList; for(i=0; i<pList->nExpr; i++){ if( pList->a[i].zName==0 ){ char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); sqlite3Dequote(zName); pList->a[i].zName = zName; } } if( pSub->pOrderBy ){ /* At this point, any non-zero iOrderByCol values indicate that the ** ORDER BY column expression is identical to the iOrderByCol'th ** expression returned by SELECT statement pSub. Since these values ** do not necessarily correspond to columns in SELECT statement pParent, ** zero them before transfering the ORDER BY clause. ** ** Not doing this may cause an error if a subsequent call to this ** function attempts to flatten a compound sub-query into pParent ** (the only way this can happen is if the compound sub-query is ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ ExprList *pOrderBy = pSub->pOrderBy; for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } assert( pParent->pOrderBy==0 ); assert( pSub->pPrior==0 ); pParent->pOrderBy = pOrderBy; pSub->pOrderBy = 0; } pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); if( subqueryIsAgg ){ assert( pParent->pHaving==0 ); pParent->pHaving = pParent->pWhere; pParent->pWhere = pWhere; pParent->pHaving = sqlite3ExprAnd(db, sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving ); assert( pParent->pGroupBy==0 ); pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); }else{ pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere); } substSelect(pParse, pParent, iParent, pSub->pEList, 0); /* The flattened query is distinct if either the inner or the ** outer query is distinct. */ pParent->selFlags |= pSub->selFlags & SF_Distinct; /* ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; ** ** One is tempted to try to add a and b to combine the limits. But this ** does not work if either limit is negative. */ if( pSub->pLimit ){ pParent->pLimit = pSub->pLimit; pSub->pLimit = 0; } } /* Finially, delete what is left of the subquery and return ** success. */ sqlite3SelectDelete(db, pSub1); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,("After flattening:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif return 1; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* ** Make copies of relevant WHERE clause terms of the outer query into ** the WHERE clause of subquery. Example: ** ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; ** ** Transformed into: ** ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) ** WHERE x=5 AND y=10; ** ** The hope is that the terms added to the inner query will make it more ** efficient. ** ** Do not attempt this optimization if: ** ** (1) The inner query is an aggregate. (In that case, we'd really want ** to copy the outer WHERE-clause terms onto the HAVING clause of the ** inner query. But they probably won't help there so do not bother.) ** ** (2) The inner query is the recursive part of a common table expression. ** ** (3) The inner query has a LIMIT clause (since the changes to the WHERE ** close would change the meaning of the LIMIT). ** ** (4) The inner query is the right operand of a LEFT JOIN. (The caller ** enforces this restriction since this routine does not have enough ** information to know.) ** ** (5) The WHERE clause expression originates in the ON or USING clause ** of a LEFT JOIN. ** ** Return 0 if no changes are made and non-zero if one or more WHERE clause ** terms are duplicated into the subquery. */ static int pushDownWhereTerms( Parse *pParse, /* Parse context (for malloc() and error reporting) */ Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ Expr *pWhere, /* The WHERE clause of the outer query */ int iCursor /* Cursor number of the subquery */ ){ Expr *pNew; int nChng = 0; Select *pX; /* For looping over compound SELECTs in pSubq */ if( pWhere==0 ) return 0; for(pX=pSubq; pX; pX=pX->pPrior){ if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){ testcase( pX->selFlags & SF_Aggregate ); testcase( pX->selFlags & SF_Recursive ); testcase( pX!=pSubq ); return 0; /* restrictions (1) and (2) */ } } if( pSubq->pLimit!=0 ){ return 0; /* restriction (3) */ } while( pWhere->op==TK_AND ){ nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor); pWhere = pWhere->pLeft; } if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */ if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ nChng++; while( pSubq ){ pNew = sqlite3ExprDup(pParse->db, pWhere, 0); pNew = substExpr(pParse, pNew, iCursor, pSubq->pEList); pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew); pSubq = pSubq->pPrior; } } return nChng; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ /* ** Based on the contents of the AggInfo structure indicated by the first ** argument, this function checks if the following are true: ** ** * the query contains just a single aggregate function, ** * the aggregate function is either min() or max(), and ** * the argument to the aggregate function is a column value. ** ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX ** is returned as appropriate. Also, *ppMinMax is set to point to the ** list of arguments passed to the aggregate before returning. ** ** Or, if the conditions above are not met, *ppMinMax is set to 0 and ** WHERE_ORDERBY_NORMAL is returned. */ static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ *ppMinMax = 0; if( pAggInfo->nFunc==1 ){ Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ assert( pExpr->op==TK_AGG_FUNCTION ); if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ const char *zFunc = pExpr->u.zToken; if( sqlite3StrICmp(zFunc, "min")==0 ){ eRet = WHERE_ORDERBY_MIN; *ppMinMax = pEList; }else if( sqlite3StrICmp(zFunc, "max")==0 ){ eRet = WHERE_ORDERBY_MAX; *ppMinMax = pEList; } } } assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); return eRet; } /* ** The select statement passed as the first argument is an aggregate query. ** The second argument is the associated aggregate-info object. This ** function tests if the SELECT is of the form: ** ** SELECT count(*) FROM <tbl> ** ** where table is a database table, not a sub-select or view. If the query ** does match this pattern, then a pointer to the Table object representing ** <tbl> is returned. Otherwise, 0 is returned. */ static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ Table *pTab; Expr *pExpr; assert( !p->pGroupBy ); if( p->pWhere || p->pEList->nExpr!=1 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect ){ return 0; } pTab = p->pSrc->a[0].pTab; pExpr = p->pEList->a[0].pExpr; assert( pTab && !pTab->pSelect && pExpr ); if( IsVirtual(pTab) ) return 0; if( pExpr->op!=TK_AGG_FUNCTION ) return 0; if( NEVER(pAggInfo->nFunc==0) ) return 0; if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; if( pExpr->flags&EP_Distinct ) return 0; return pTab; } /* ** If the source-list item passed as an argument was augmented with an ** INDEXED BY clause, then try to locate the specified index. If there ** was such a clause and the named index cannot be found, return ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate ** pFrom->pIndex and return SQLITE_OK. */ SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ if( pFrom->pTab && pFrom->fg.isIndexedBy ){ Table *pTab = pFrom->pTab; char *zIndexedBy = pFrom->u1.zIndexedBy; Index *pIdx; for(pIdx=pTab->pIndex; pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); pIdx=pIdx->pNext ); if( !pIdx ){ sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); pParse->checkSchema = 1; return SQLITE_ERROR; } pFrom->pIBIndex = pIdx; } return SQLITE_OK; } /* ** Detect compound SELECT statements that use an ORDER BY clause with ** an alternative collating sequence. ** ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... ** ** These are rewritten as a subquery: ** ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) ** ORDER BY ... COLLATE ... ** ** This transformation is necessary because the multiSelectOrderBy() routine ** above that generates the code for a compound SELECT with an ORDER BY clause ** uses a merge algorithm that requires the same collating sequence on the ** result columns as on the ORDER BY clause. See ticket ** http://www.sqlite.org/src/info/6709574d2a ** ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. ** The UNION ALL operator works fine with multiSelectOrderBy() even when ** there are COLLATE terms in the ORDER BY. */ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ int i; Select *pNew; Select *pX; sqlite3 *db; struct ExprList_item *a; SrcList *pNewSrc; Parse *pParse; Token dummy; if( p->pPrior==0 ) return WRC_Continue; if( p->pOrderBy==0 ) return WRC_Continue; for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} if( pX==0 ) return WRC_Continue; a = p->pOrderBy->a; for(i=p->pOrderBy->nExpr-1; i>=0; i--){ if( a[i].pExpr->flags & EP_Collate ) break; } if( i<0 ) return WRC_Continue; /* If we reach this point, that means the transformation is required. */ pParse = pWalker->pParse; db = pParse->db; pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); if( pNew==0 ) return WRC_Abort; memset(&dummy, 0, sizeof(dummy)); pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); if( pNewSrc==0 ) return WRC_Abort; *pNew = *p; p->pSrc = pNewSrc; p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); p->op = TK_SELECT; p->pWhere = 0; pNew->pGroupBy = 0; pNew->pHaving = 0; pNew->pOrderBy = 0; p->pPrior = 0; p->pNext = 0; p->pWith = 0; p->selFlags &= ~SF_Compound; assert( (p->selFlags & SF_Converted)==0 ); p->selFlags |= SF_Converted; assert( pNew->pPrior!=0 ); pNew->pPrior->pNext = pNew; pNew->pLimit = 0; pNew->pOffset = 0; return WRC_Continue; } /* ** Check to see if the FROM clause term pFrom has table-valued function ** arguments. If it does, leave an error message in pParse and return ** non-zero, since pFrom is not allowed to be a table-valued function. */ static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ if( pFrom->fg.isTabFunc ){ sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); return 1; } return 0; } #ifndef SQLITE_OMIT_CTE /* ** Argument pWith (which may be NULL) points to a linked list of nested ** WITH contexts, from inner to outermost. If the table identified by ** FROM clause element pItem is really a common-table-expression (CTE) ** then return a pointer to the CTE definition for that table. Otherwise ** return NULL. ** ** If a non-NULL value is returned, set *ppContext to point to the With ** object that the returned CTE belongs to. */ static struct Cte *searchWith( With *pWith, /* Current innermost WITH clause */ struct SrcList_item *pItem, /* FROM clause element to resolve */ With **ppContext /* OUT: WITH clause return value belongs to */ ){ const char *zName; if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ With *p; for(p=pWith; p; p=p->pOuter){ int i; for(i=0; i<p->nCte; i++){ if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ *ppContext = p; return &p->a[i]; } } } } return 0; } /* The code generator maintains a stack of active WITH clauses ** with the inner-most WITH clause being at the top of the stack. ** ** This routine pushes the WITH clause passed as the second argument ** onto the top of the stack. If argument bFree is true, then this ** WITH clause will never be popped from the stack. In this case it ** should be freed along with the Parse object. In other cases, when ** bFree==0, the With object will be freed along with the SELECT ** statement with which it is associated. */ SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); if( pWith ){ assert( pParse->pWith!=pWith ); pWith->pOuter = pParse->pWith; pParse->pWith = pWith; if( bFree ) pParse->pWithToFree = pWith; } } /* ** This function checks if argument pFrom refers to a CTE declared by ** a WITH clause on the stack currently maintained by the parser. And, ** if currently processing a CTE expression, if it is a recursive ** reference to the current CTE. ** ** If pFrom falls into either of the two categories above, pFrom->pTab ** and other fields are populated accordingly. The caller should check ** (pFrom->pTab!=0) to determine whether or not a successful match ** was found. ** ** Whether or not a match is found, SQLITE_OK is returned if no error ** occurs. If an error does occur, an error message is stored in the ** parser and some error code other than SQLITE_OK returned. */ static int withExpand( Walker *pWalker, struct SrcList_item *pFrom ){ Parse *pParse = pWalker->pParse; sqlite3 *db = pParse->db; struct Cte *pCte; /* Matched CTE (or NULL if no match) */ With *pWith; /* WITH clause that pCte belongs to */ assert( pFrom->pTab==0 ); pCte = searchWith(pParse->pWith, pFrom, &pWith); if( pCte ){ Table *pTab; ExprList *pEList; Select *pSel; Select *pLeft; /* Left-most SELECT statement */ int bMayRecursive; /* True if compound joined by UNION [ALL] */ With *pSavedWith; /* Initial value of pParse->pWith */ /* If pCte->zCteErr is non-NULL at this point, then this is an illegal ** recursive reference to CTE pCte. Leave an error in pParse and return ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. ** In this case, proceed. */ if( pCte->zCteErr ){ sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); return SQLITE_ERROR; } if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; assert( pFrom->pTab==0 ); pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return WRC_Abort; pTab->nTabRef = 1; pTab->zName = sqlite3DbStrDup(db, pCte->zName); pTab->iPKey = -1; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; assert( pFrom->pSelect ); /* Check if this is a recursive CTE. */ pSel = pFrom->pSelect; bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); if( bMayRecursive ){ int i; SrcList *pSrc = pFrom->pSelect->pSrc; for(i=0; i<pSrc->nSrc; i++){ struct SrcList_item *pItem = &pSrc->a[i]; if( pItem->zDatabase==0 && pItem->zName!=0 && 0==sqlite3StrICmp(pItem->zName, pCte->zName) ){ pItem->pTab = pTab; pItem->fg.isRecursive = 1; pTab->nTabRef++; pSel->selFlags |= SF_Recursive; } } } /* Only one recursive reference is permitted. */ if( pTab->nTabRef>2 ){ sqlite3ErrorMsg( pParse, "multiple references to recursive table: %s", pCte->zName ); return SQLITE_ERROR; } assert( pTab->nTabRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); pCte->zCteErr = "circular reference: %s"; pSavedWith = pParse->pWith; pParse->pWith = pWith; if( bMayRecursive ){ Select *pPrior = pSel->pPrior; assert( pPrior->pWith==0 ); pPrior->pWith = pSel->pWith; sqlite3WalkSelect(pWalker, pPrior); pPrior->pWith = 0; }else{ sqlite3WalkSelect(pWalker, pSel); } pParse->pWith = pWith; for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); pEList = pLeft->pEList; if( pCte->pCols ){ if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", pCte->zName, pEList->nExpr, pCte->pCols->nExpr ); pParse->pWith = pSavedWith; return SQLITE_ERROR; } pEList = pCte->pCols; } sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); if( bMayRecursive ){ if( pSel->selFlags & SF_Recursive ){ pCte->zCteErr = "multiple recursive references: %s"; }else{ pCte->zCteErr = "recursive reference in a subquery: %s"; } sqlite3WalkSelect(pWalker, pSel); } pCte->zCteErr = 0; pParse->pWith = pSavedWith; } return SQLITE_OK; } #endif #ifndef SQLITE_OMIT_CTE /* ** If the SELECT passed as the second argument has an associated WITH ** clause, pop it from the stack stored as part of the Parse object. ** ** This function is used as the xSelectCallback2() callback by ** sqlite3SelectExpand() when walking a SELECT tree to resolve table ** names and other FROM clause elements. */ static void selectPopWith(Walker *pWalker, Select *p){ Parse *pParse = pWalker->pParse; if( pParse->pWith && p->pPrior==0 ){ With *pWith = findRightmost(p)->pWith; if( pWith!=0 ){ assert( pParse->pWith==pWith ); pParse->pWith = pWith->pOuter; } } } #else #define selectPopWith 0 #endif /* ** This routine is a Walker callback for "expanding" a SELECT statement. ** "Expanding" means to do the following: ** ** (1) Make sure VDBE cursor numbers have been assigned to every ** element of the FROM clause. ** ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that ** defines FROM clause. When views appear in the FROM clause, ** fill pTabList->a[].pSelect with a copy of the SELECT statement ** that implements the view. A copy is made of the view's SELECT ** statement so that we can freely modify or delete that statement ** without worrying about messing up the persistent representation ** of the view. ** ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword ** on joins and the ON and USING clause of joins. ** ** (4) Scan the list of columns in the result set (pEList) looking ** for instances of the "*" operator or the TABLE.* operator. ** If found, expand each "*" to be every column in every table ** and TABLE.* to be every column in TABLE. ** */ static int selectExpander(Walker *pWalker, Select *p){ Parse *pParse = pWalker->pParse; int i, j, k; SrcList *pTabList; ExprList *pEList; struct SrcList_item *pFrom; sqlite3 *db = pParse->db; Expr *pE, *pRight, *pExpr; u16 selFlags = p->selFlags; p->selFlags |= SF_Expanded; if( db->mallocFailed ){ return WRC_Abort; } if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ return WRC_Prune; } pTabList = p->pSrc; pEList = p->pEList; if( p->pWith ){ sqlite3WithPush(pParse, p->pWith, 0); } /* Make sure cursor numbers have been assigned to all entries in ** the FROM clause of the SELECT statement. */ sqlite3SrcListAssignCursors(pParse, pTabList); /* Look up every table named in the FROM clause of the select. If ** an entry of the FROM clause is a subquery instead of a table or view, ** then create a transient table structure to describe the subquery. */ for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ Table *pTab; assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); if( pFrom->fg.isRecursive ) continue; assert( pFrom->pTab==0 ); #ifndef SQLITE_OMIT_CTE if( withExpand(pWalker, pFrom) ) return WRC_Abort; if( pFrom->pTab ) {} else #endif if( pFrom->zName==0 ){ #ifndef SQLITE_OMIT_SUBQUERY Select *pSel = pFrom->pSelect; /* A sub-query in the FROM clause of a SELECT */ assert( pSel!=0 ); assert( pFrom->pTab==0 ); if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return WRC_Abort; pTab->nTabRef = 1; pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); while( pSel->pPrior ){ pSel = pSel->pPrior; } sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); pTab->iPKey = -1; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); pTab->tabFlags |= TF_Ephemeral; #endif }else{ /* An ordinary table or view name in the FROM clause */ assert( pFrom->pTab==0 ); pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); if( pTab==0 ) return WRC_Abort; if( pTab->nTabRef>=0xffff ){ sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", pTab->zName); pFrom->pTab = 0; return WRC_Abort; } pTab->nTabRef++; if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ return WRC_Abort; } #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) if( IsVirtual(pTab) || pTab->pSelect ){ i16 nCol; if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; assert( pFrom->pSelect==0 ); pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); sqlite3SelectSetName(pFrom->pSelect, pTab->zName); nCol = pTab->nCol; pTab->nCol = -1; sqlite3WalkSelect(pWalker, pFrom->pSelect); pTab->nCol = nCol; } #endif } /* Locate the index named by the INDEXED BY clause, if any. */ if( sqlite3IndexedByLookup(pParse, pFrom) ){ return WRC_Abort; } } /* Process NATURAL keywords, and ON and USING clauses of joins. */ if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ return WRC_Abort; } /* For every "*" that occurs in the column list, insert the names of ** all columns in all tables. And for every TABLE.* insert the names ** of all columns in TABLE. The parser inserted a special expression ** with the TK_ASTERISK operator for each "*" that it found in the column ** list. The following code just has to locate the TK_ASTERISK ** expressions and expand each one to the list of all columns in ** all tables. ** ** The first loop just checks to see if there are any "*" operators ** that need expanding. */ for(k=0; k<pEList->nExpr; k++){ pE = pEList->a[k].pExpr; if( pE->op==TK_ASTERISK ) break; assert( pE->op!=TK_DOT || pE->pRight!=0 ); assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; } if( k<pEList->nExpr ){ /* ** If we get here it means the result set contains one or more "*" ** operators that need to be expanded. Loop through each expression ** in the result set and expand them one by one. */ struct ExprList_item *a = pEList->a; ExprList *pNew = 0; int flags = pParse->db->flags; int longNames = (flags & SQLITE_FullColNames)!=0 && (flags & SQLITE_ShortColNames)==0; for(k=0; k<pEList->nExpr; k++){ pE = a[k].pExpr; pRight = pE->pRight; assert( pE->op!=TK_DOT || pRight!=0 ); if( pE->op!=TK_ASTERISK && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) ){ /* This particular expression does not need to be expanded. */ pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); if( pNew ){ pNew->a[pNew->nExpr-1].zName = a[k].zName; pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; a[k].zName = 0; a[k].zSpan = 0; } a[k].pExpr = 0; }else{ /* This expression is a "*" or a "TABLE.*" and needs to be ** expanded. */ int tableSeen = 0; /* Set to 1 when TABLE matches */ char *zTName = 0; /* text of name of TABLE */ if( pE->op==TK_DOT ){ assert( pE->pLeft!=0 ); assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); zTName = pE->pLeft->u.zToken; } for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ Table *pTab = pFrom->pTab; Select *pSub = pFrom->pSelect; char *zTabName = pFrom->zAlias; const char *zSchemaName = 0; int iDb; if( zTabName==0 ){ zTabName = pTab->zName; } if( db->mallocFailed ) break; if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ pSub = 0; if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ continue; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; } for(j=0; j<pTab->nCol; j++){ char *zName = pTab->aCol[j].zName; char *zColname; /* The computed column name */ char *zToFree; /* Malloced string that needs to be freed */ Token sColname; /* Computed column name as a token */ assert( zName ); if( zTName && pSub && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 ){ continue; } /* If a column is marked as 'hidden', omit it from the expanded ** result-set list unless the SELECT has the SF_IncludeHidden ** bit set. */ if( (p->selFlags & SF_IncludeHidden)==0 && IsHiddenColumn(&pTab->aCol[j]) ){ continue; } tableSeen = 1; if( i>0 && zTName==0 ){ if( (pFrom->fg.jointype & JT_NATURAL)!=0 && tableAndColumnIndex(pTabList, i, zName, 0, 0) ){ /* In a NATURAL join, omit the join columns from the ** table to the right of the join */ continue; } if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ /* In a join with a USING clause, omit columns in the ** using clause from the table on the right. */ continue; } } pRight = sqlite3Expr(db, TK_ID, zName); zColname = zName; zToFree = 0; if( longNames || pTabList->nSrc>1 ){ Expr *pLeft; pLeft = sqlite3Expr(db, TK_ID, zTabName); pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); if( zSchemaName ){ pLeft = sqlite3Expr(db, TK_ID, zSchemaName); pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); } if( longNames ){ zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); zToFree = zColname; } }else{ pExpr = pRight; } pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); sqlite3TokenInit(&sColname, zColname); sqlite3ExprListSetName(pParse, pNew, &sColname, 0); if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; if( pSub ){ pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); testcase( pX->zSpan==0 ); }else{ pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", zSchemaName, zTabName, zColname); testcase( pX->zSpan==0 ); } pX->bSpanIsTab = 1; } sqlite3DbFree(db, zToFree); } } if( !tableSeen ){ if( zTName ){ sqlite3ErrorMsg(pParse, "no such table: %s", zTName); }else{ sqlite3ErrorMsg(pParse, "no tables specified"); } } } } sqlite3ExprListDelete(db, pEList); p->pEList = pNew; } #if SQLITE_MAX_COLUMN if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many columns in result set"); return WRC_Abort; } #endif return WRC_Continue; } /* ** No-op routine for the parse-tree walker. ** ** When this routine is the Walker.xExprCallback then expression trees ** are walked without any actions being taken at each node. Presumably, ** when this routine is used for Walker.xExprCallback then ** Walker.xSelectCallback is set to do something useful for every ** subquery in the parser tree. */ SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return WRC_Continue; } /* ** This routine "expands" a SELECT statement and all of its subqueries. ** For additional information on what it means to "expand" a SELECT ** statement, see the comment on the selectExpand worker callback above. ** ** Expanding a SELECT statement is the first step in processing a ** SELECT statement. The SELECT statement must be expanded before ** name resolution is performed. ** ** If anything goes wrong, an error message is written into pParse. ** The calling function can detect the problem by looking at pParse->nErr ** and/or pParse->db->mallocFailed. */ static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ Walker w; memset(&w, 0, sizeof(w)); w.xExprCallback = sqlite3ExprWalkNoop; w.pParse = pParse; if( pParse->hasCompound ){ w.xSelectCallback = convertCompoundSelectToSubquery; sqlite3WalkSelect(&w, pSelect); } w.xSelectCallback = selectExpander; w.xSelectCallback2 = selectPopWith; sqlite3WalkSelect(&w, pSelect); } #ifndef SQLITE_OMIT_SUBQUERY /* ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() ** interface. ** ** For each FROM-clause subquery, add Column.zType and Column.zColl ** information to the Table structure that represents the result set ** of that subquery. ** ** The Table structure that represents the result set was constructed ** by selectExpander() but the type and collation information was omitted ** at that point because identifiers had not yet been resolved. This ** routine is called after identifier resolution. */ static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ Parse *pParse; int i; SrcList *pTabList; struct SrcList_item *pFrom; assert( p->selFlags & SF_Resolved ); assert( (p->selFlags & SF_HasTypeInfo)==0 ); p->selFlags |= SF_HasTypeInfo; pParse = pWalker->pParse; pTabList = p->pSrc; for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ Table *pTab = pFrom->pTab; assert( pTab!=0 ); if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ /* A sub-query in the FROM clause of a SELECT */ Select *pSel = pFrom->pSelect; if( pSel ){ while( pSel->pPrior ) pSel = pSel->pPrior; sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel); } } } } #endif /* ** This routine adds datatype and collating sequence information to ** the Table structures of all FROM-clause subqueries in a ** SELECT statement. ** ** Use this routine after name resolution. */ static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ #ifndef SQLITE_OMIT_SUBQUERY Walker w; memset(&w, 0, sizeof(w)); w.xSelectCallback2 = selectAddSubqueryTypeInfo; w.xExprCallback = sqlite3ExprWalkNoop; w.pParse = pParse; sqlite3WalkSelect(&w, pSelect); #endif } /* ** This routine sets up a SELECT statement for processing. The ** following is accomplished: ** ** * VDBE Cursor numbers are assigned to all FROM-clause terms. ** * Ephemeral Table objects are created for all FROM-clause subqueries. ** * ON and USING clauses are shifted into WHERE statements ** * Wildcards "*" and "TABLE.*" in result sets are expanded. ** * Identifiers in expression are matched to tables. ** ** This routine acts recursively on all subqueries within the SELECT. */ SQLITE_PRIVATE void sqlite3SelectPrep( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ NameContext *pOuterNC /* Name context for container */ ){ sqlite3 *db; if( NEVER(p==0) ) return; db = pParse->db; if( db->mallocFailed ) return; if( p->selFlags & SF_HasTypeInfo ) return; sqlite3SelectExpand(pParse, p); if( pParse->nErr || db->mallocFailed ) return; sqlite3ResolveSelectNames(pParse, p, pOuterNC); if( pParse->nErr || db->mallocFailed ) return; sqlite3SelectAddTypeInfo(pParse, p); } /* ** Reset the aggregate accumulator. ** ** The aggregate accumulator is a set of memory cells that hold ** intermediate results while calculating an aggregate. This ** routine generates code that stores NULLs in all of those memory ** cells. */ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; struct AggInfo_func *pFunc; int nReg = pAggInfo->nFunc + pAggInfo->nColumn; if( nReg==0 ) return; #ifdef SQLITE_DEBUG /* Verify that all AggInfo registers are within the range specified by ** AggInfo.mnReg..AggInfo.mxReg */ assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); for(i=0; i<pAggInfo->nColumn; i++){ assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); } for(i=0; i<pAggInfo->nFunc; i++){ assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); } #endif sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ if( pFunc->iDistinct>=0 ){ Expr *pE = pFunc->pExpr; assert( !ExprHasProperty(pE, EP_xIsSelect) ); if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " "argument"); pFunc->iDistinct = -1; }else{ KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0); sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO); } } } } /* ** Invoke the OP_AggFinalize opcode for every aggregate function ** in the AggInfo structure. */ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; struct AggInfo_func *pF; for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ ExprList *pList = pF->pExpr->x.pList; assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); } } /* ** Update the accumulator memory cells for an aggregate based on ** the current cursor position. */ static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; int regHit = 0; int addrHitTest = 0; struct AggInfo_func *pF; struct AggInfo_col *pC; pAggInfo->directMode = 1; for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ int nArg; int addrNext = 0; int regAgg; ExprList *pList = pF->pExpr->x.pList; assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); if( pList ){ nArg = pList->nExpr; regAgg = sqlite3GetTempRange(pParse, nArg); sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); }else{ nArg = 0; regAgg = 0; } if( pF->iDistinct>=0 ){ addrNext = sqlite3VdbeMakeLabel(v); testcase( nArg==0 ); /* Error condition */ testcase( nArg>1 ); /* Also an error */ codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); } if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ CollSeq *pColl = 0; struct ExprList_item *pItem; int j; assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); } if( !pColl ){ pColl = pParse->db->pDfltColl; } if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); } sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem); sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); sqlite3VdbeChangeP5(v, (u8)nArg); sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); sqlite3ReleaseTempRange(pParse, regAgg, nArg); if( addrNext ){ sqlite3VdbeResolveLabel(v, addrNext); sqlite3ExprCacheClear(pParse); } } /* Before populating the accumulator registers, clear the column cache. ** Otherwise, if any of the required column values are already present ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value ** to pC->iMem. But by the time the value is used, the original register ** may have been used, invalidating the underlying buffer holding the ** text or blob value. See ticket [883034dcb5]. ** ** Another solution would be to change the OP_SCopy used to copy cached ** values to an OP_Copy. */ if( regHit ){ addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); } sqlite3ExprCacheClear(pParse); for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); } pAggInfo->directMode = 0; sqlite3ExprCacheClear(pParse); if( addrHitTest ){ sqlite3VdbeJumpHere(v, addrHitTest); } } /* ** Add a single OP_Explain instruction to the VDBE to explain a simple ** count(*) query ("SELECT count(*) FROM pTab"). */ #ifndef SQLITE_OMIT_EXPLAIN static void explainSimpleCount( Parse *pParse, /* Parse context */ Table *pTab, /* Table being queried */ Index *pIdx /* Index used to optimize scan, or NULL */ ){ if( pParse->explain==2 ){ int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", pTab->zName, bCover ? " USING COVERING INDEX " : "", bCover ? pIdx->zName : "" ); sqlite3VdbeAddOp4( pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC ); } } #else # define explainSimpleCount(a,b,c) #endif /* ** Generate code for the SELECT statement given in the p argument. ** ** The results are returned according to the SelectDest structure. ** See comments in sqliteInt.h for further information. ** ** This routine returns the number of errors. If any errors are ** encountered, then an appropriate error message is left in ** pParse->zErrMsg. ** ** This routine does NOT free the Select structure passed in. The ** calling function needs to do that. */ SQLITE_PRIVATE int sqlite3Select( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ SelectDest *pDest /* What to do with the query results */ ){ int i, j; /* Loop counters */ WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ Vdbe *v; /* The virtual machine under construction */ int isAgg; /* True for select lists like "count(*)" */ ExprList *pEList = 0; /* List of columns to extract. */ SrcList *pTabList; /* List of tables to select from */ Expr *pWhere; /* The WHERE clause. May be NULL */ ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ Expr *pHaving; /* The HAVING clause. May be NULL */ int rc = 1; /* Value to return from this function */ DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ SortCtx sSort; /* Info on how to code the ORDER BY clause */ AggInfo sAggInfo; /* Information used by aggregate queries */ int iEnd; /* Address of the end of the query */ sqlite3 *db; /* The database connection */ #ifndef SQLITE_OMIT_EXPLAIN int iRestoreSelectId = pParse->iSelectId; pParse->iSelectId = pParse->iNextSelectId++; #endif db = pParse->db; if( p==0 || db->mallocFailed || pParse->nErr ){ return 1; } if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; memset(&sAggInfo, 0, sizeof(sAggInfo)); #if SELECTTRACE_ENABLED pParse->nSelectIndent++; SELECTTRACE(1,pParse,p, ("begin processing:\n")); if( sqlite3SelectTrace & 0x100 ){ sqlite3TreeViewSelect(0, p, 0); } #endif assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); if( IgnorableOrderby(pDest) ){ assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); /* If ORDER BY makes no difference in the output then neither does ** DISTINCT so it can be removed too. */ sqlite3ExprListDelete(db, p->pOrderBy); p->pOrderBy = 0; p->selFlags &= ~SF_Distinct; } sqlite3SelectPrep(pParse, p, 0); memset(&sSort, 0, sizeof(sSort)); sSort.pOrderBy = p->pOrderBy; pTabList = p->pSrc; if( pParse->nErr || db->mallocFailed ){ goto select_end; } assert( p->pEList!=0 ); isAgg = (p->selFlags & SF_Aggregate)!=0; #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p, ("after name resolution:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif /* Try to flatten subqueries in the FROM clause up into the main query */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ struct SrcList_item *pItem = &pTabList->a[i]; Select *pSub = pItem->pSelect; int isAggSub; Table *pTab = pItem->pTab; if( pSub==0 ) continue; /* Catch mismatch in the declared columns of a view and the number of ** columns in the SELECT on the RHS */ if( pTab->nCol!=pSub->pEList->nExpr ){ sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", pTab->nCol, pTab->zName, pSub->pEList->nExpr); goto select_end; } isAggSub = (pSub->selFlags & SF_Aggregate)!=0; if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ /* This subquery can be absorbed into its parent. */ if( isAggSub ){ isAgg = 1; p->selFlags |= SF_Aggregate; } i = -1; } pTabList = p->pSrc; if( db->mallocFailed ) goto select_end; if( !IgnorableOrderby(pDest) ){ sSort.pOrderBy = p->pOrderBy; } } #endif /* Get a pointer the VDBE under construction, allocating a new VDBE if one ** does not already exist */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto select_end; #ifndef SQLITE_OMIT_COMPOUND_SELECT /* Handle compound SELECT statements using the separate multiSelect() ** procedure. */ if( p->pPrior ){ rc = multiSelect(pParse, p, pDest); explainSetInteger(pParse->iSelectId, iRestoreSelectId); #if SELECTTRACE_ENABLED SELECTTRACE(1,pParse,p,("end compound-select processing\n")); pParse->nSelectIndent--; #endif return rc; } #endif /* Generate code for all sub-queries in the FROM clause */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) for(i=0; i<pTabList->nSrc; i++){ struct SrcList_item *pItem = &pTabList->a[i]; SelectDest dest; Select *pSub = pItem->pSelect; if( pSub==0 ) continue; /* Sometimes the code for a subquery will be generated more than ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, ** for example. In that case, do not regenerate the code to manifest ** a view or the co-routine to implement a view. The first instance ** is sufficient, though the subroutine to manifest the view does need ** to be invoked again. */ if( pItem->addrFillSub ){ if( pItem->fg.viaCoroutine==0 ){ sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); } continue; } /* Increment Parse.nHeight by the height of the largest expression ** tree referred to by this, the parent select. The child select ** may contain expression trees of at most ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit ** more conservative than necessary, but much easier than enforcing ** an exact limit. */ pParse->nHeight += sqlite3SelectExprHeight(p); /* Make copies of constant WHERE-clause terms in the outer query down ** inside the subquery. This can help the subquery to run more efficiently. */ if( (pItem->fg.jointype & JT_OUTER)==0 && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor) ){ #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif } /* Generate code to implement the subquery ** ** The subquery is implemented as a co-routine if all of these are true: ** (1) The subquery is guaranteed to be the outer loop (so that it ** does not need to be computed more than once) ** (2) The ALL keyword after SELECT is omitted. (Applications are ** allowed to say "SELECT ALL" instead of just "SELECT" to disable ** the use of co-routines.) ** (3) Co-routines are not disabled using sqlite3_test_control() ** with SQLITE_TESTCTRL_OPTIMIZATIONS. ** ** TODO: Are there other reasons beside (1) to use a co-routine ** implementation? */ if( i==0 && (pTabList->nSrc==1 || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ && (p->selFlags & SF_All)==0 /* (2) */ && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */ ){ /* Implement a co-routine that will return a single row of the result ** set on each invocation. */ int addrTop = sqlite3VdbeCurrentAddr(v)+1; pItem->regReturn = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); VdbeComment((v, "%s", pItem->pTab->zName)); pItem->addrFillSub = addrTop; sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); sqlite3Select(pParse, pSub, &dest); pItem->pTab->nRowLogEst = pSub->nSelectRow; pItem->fg.viaCoroutine = 1; pItem->regResult = dest.iSdst; sqlite3VdbeEndCoroutine(v, pItem->regReturn); sqlite3VdbeJumpHere(v, addrTop-1); sqlite3ClearTempRegCache(pParse); }else{ /* Generate a subroutine that will fill an ephemeral table with ** the content of this subquery. pItem->addrFillSub will point ** to the address of the generated subroutine. pItem->regReturn ** is a register allocated to hold the subroutine return address */ int topAddr; int onceAddr = 0; int retAddr; assert( pItem->addrFillSub==0 ); pItem->regReturn = ++pParse->nMem; topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); pItem->addrFillSub = topAddr+1; if( pItem->fg.isCorrelated==0 ){ /* If the subquery is not correlated and if we are not inside of ** a trigger, then we only need to compute the value of the subquery ** once. */ onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); }else{ VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); } sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); sqlite3Select(pParse, pSub, &dest); pItem->pTab->nRowLogEst = pSub->nSelectRow; if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); VdbeComment((v, "end %s", pItem->pTab->zName)); sqlite3VdbeChangeP1(v, topAddr, retAddr); sqlite3ClearTempRegCache(pParse); } if( db->mallocFailed ) goto select_end; pParse->nHeight -= sqlite3SelectExprHeight(p); } #endif /* Various elements of the SELECT copied into local variables for ** convenience */ pEList = p->pEList; pWhere = p->pWhere; pGroupBy = p->pGroupBy; pHaving = p->pHaving; sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and ** if the select-list is the same as the ORDER BY list, then this query ** can be rewritten as a GROUP BY. In other words, this: ** ** SELECT DISTINCT xyz FROM ... ORDER BY xyz ** ** is transformed to: ** ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz ** ** The second form is preferred as a single index (or temp-table) may be ** used for both the ORDER BY and DISTINCT processing. As originally ** written the query must use a temp-table for at least one of the ORDER ** BY and DISTINCT, and an index or separate temp-table for the other. */ if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 ){ p->selFlags &= ~SF_Distinct; pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); /* Notice that even thought SF_Distinct has been cleared from p->selFlags, ** the sDistinct.isTnct is still set. Hence, isTnct represents the ** original setting of the SF_Distinct flag, not the current setting */ assert( sDistinct.isTnct ); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif } /* If there is an ORDER BY clause, then create an ephemeral index to ** do the sorting. But this sorting ephemeral index might end up ** being unused if the data can be extracted in pre-sorted order. ** If that is the case, then the OP_OpenEphemeral instruction will be ** changed to an OP_Noop once we figure out that the sorting index is ** not needed. The sSort.addrSortIndex variable is used to facilitate ** that change. */ if( sSort.pOrderBy ){ KeyInfo *pKeyInfo; pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr); sSort.iECursor = pParse->nTab++; sSort.addrSortIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, (char*)pKeyInfo, P4_KEYINFO ); }else{ sSort.addrSortIndex = -1; } /* If the output is destined for a temporary table, open that table. */ if( pDest->eDest==SRT_EphemTab ){ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); } /* Set the limiter. */ iEnd = sqlite3VdbeMakeLabel(v); if( (p->selFlags & SF_FixedLimit)==0 ){ p->nSelectRow = 320; /* 4 billion rows */ } computeLimitRegisters(pParse, p, iEnd); if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); sSort.sortFlags |= SORTFLAG_UseSorter; } /* Open an ephemeral index to use for the distinct set. */ if( p->selFlags & SF_Distinct ){ sDistinct.tabTnct = pParse->nTab++; sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sDistinct.tabTnct, 0, 0, (char*)keyInfoFromExprList(pParse, p->pEList,0,0), P4_KEYINFO); sqlite3VdbeChangeP5(v, BTREE_UNORDERED); sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; }else{ sDistinct.eTnctType = WHERE_DISTINCT_NOOP; } if( !isAgg && pGroupBy==0 ){ /* No aggregate functions and no GROUP BY clause */ u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); assert( WHERE_USE_LIMIT==SF_FixedLimit ); wctrlFlags |= p->selFlags & SF_FixedLimit; /* Begin the database scan. */ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, p->pEList, wctrlFlags, p->nSelectRow); if( pWInfo==0 ) goto select_end; if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); } if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); } if( sSort.pOrderBy ){ sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo); if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ sSort.pOrderBy = 0; } } /* If sorting index that was created by a prior OP_OpenEphemeral ** instruction ended up not being needed, then change the OP_OpenEphemeral ** into an OP_Noop. */ if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); } /* Use the standard inner loop. */ selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest, sqlite3WhereContinueLabel(pWInfo), sqlite3WhereBreakLabel(pWInfo)); /* End the database scan loop. */ sqlite3WhereEnd(pWInfo); }else{ /* This case when there exist aggregate functions or a GROUP BY clause ** or both */ NameContext sNC; /* Name context for processing aggregate information */ int iAMem; /* First Mem address for storing current GROUP BY */ int iBMem; /* First Mem address for previous GROUP BY */ int iUseFlag; /* Mem address holding flag indicating that at least ** one row of the input to the aggregator has been ** processed */ int iAbortFlag; /* Mem address which causes query abort if positive */ int groupBySort; /* Rows come from source in GROUP BY order */ int addrEnd; /* End of processing for this SELECT */ int sortPTab = 0; /* Pseudotable used to decode sorting results */ int sortOut = 0; /* Output register from the sorter */ int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ /* Remove any and all aliases between the result set and the ** GROUP BY clause. */ if( pGroupBy ){ int k; /* Loop counter */ struct ExprList_item *pItem; /* For looping over expression in a list */ for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ pItem->u.x.iAlias = 0; } for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ pItem->u.x.iAlias = 0; } assert( 66==sqlite3LogEst(100) ); if( p->nSelectRow>66 ) p->nSelectRow = 66; }else{ assert( 0==sqlite3LogEst(1) ); p->nSelectRow = 0; } /* If there is both a GROUP BY and an ORDER BY clause and they are ** identical, then it may be possible to disable the ORDER BY clause ** on the grounds that the GROUP BY will cause elements to come out ** in the correct order. It also may not - the GROUP BY might use a ** database index that causes rows to be grouped together as required ** but not actually sorted. Either way, record the fact that the ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp ** variable. */ if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ orderByGrp = 1; } /* Create a label to jump to when we want to abort the query */ addrEnd = sqlite3VdbeMakeLabel(v); /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the ** SELECT statement. */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; sNC.pAggInfo = &sAggInfo; sAggInfo.mnReg = pParse->nMem+1; sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; sAggInfo.pGroupBy = pGroupBy; sqlite3ExprAnalyzeAggList(&sNC, pEList); sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); if( pHaving ){ sqlite3ExprAnalyzeAggregates(&sNC, pHaving); } sAggInfo.nAccumulator = sAggInfo.nColumn; for(i=0; i<sAggInfo.nFunc; i++){ assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); sNC.ncFlags |= NC_InAggFunc; sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); sNC.ncFlags &= ~NC_InAggFunc; } sAggInfo.mxReg = pParse->nMem; if( db->mallocFailed ) goto select_end; /* Processing for aggregates with GROUP BY is very different and ** much more complex than aggregates without a GROUP BY. */ if( pGroupBy ){ KeyInfo *pKeyInfo; /* Keying information for the group by clause */ int addr1; /* A-vs-B comparision jump */ int addrOutputRow; /* Start of subroutine that outputs a result row */ int regOutputRow; /* Return address register for output subroutine */ int addrSetAbort; /* Set the abort flag and return */ int addrTopOfLoop; /* Top of the input loop */ int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ int addrReset; /* Subroutine for resetting the accumulator */ int regReset; /* Return address register for reset subroutine */ /* If there is a GROUP BY clause we might need a sorting index to ** implement it. Allocate that sorting index now. If it turns out ** that we do not need it after all, the OP_SorterOpen instruction ** will be converted into a Noop. */ sAggInfo.sortingIdx = pParse->nTab++; pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn); addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 0, (char*)pKeyInfo, P4_KEYINFO); /* Initialize memory locations used by GROUP BY aggregate processing */ iUseFlag = ++pParse->nMem; iAbortFlag = ++pParse->nMem; regOutputRow = ++pParse->nMem; addrOutputRow = sqlite3VdbeMakeLabel(v); regReset = ++pParse->nMem; addrReset = sqlite3VdbeMakeLabel(v); iAMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; iBMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); VdbeComment((v, "clear abort flag")); sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); VdbeComment((v, "indicate accumulator empty")); sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); /* Begin a loop that will extract all source rows in GROUP BY order. ** This might involve two separate loops with an OP_Sort in between, or ** it might be a single loop that uses an index to extract information ** in the right order to begin with. */ sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 ); if( pWInfo==0 ) goto select_end; if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ /* The optimizer is able to deliver rows in group by order so ** we do not have to sort. The OP_OpenEphemeral table will be ** cancelled later because we still need to use the pKeyInfo */ groupBySort = 0; }else{ /* Rows are coming out in undetermined order. We have to push ** each row into a sorting index, terminate the first loop, ** then loop over the sorting index in order to get the output ** in sorted order */ int regBase; int regRecord; int nCol; int nGroupBy; explainTempTable(pParse, (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? "DISTINCT" : "GROUP BY"); groupBySort = 1; nGroupBy = pGroupBy->nExpr; nCol = nGroupBy; j = nGroupBy; for(i=0; i<sAggInfo.nColumn; i++){ if( sAggInfo.aCol[i].iSorterColumn>=j ){ nCol++; j++; } } regBase = sqlite3GetTempRange(pParse, nCol); sqlite3ExprCacheClear(pParse); sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); j = nGroupBy; for(i=0; i<sAggInfo.nColumn; i++){ struct AggInfo_col *pCol = &sAggInfo.aCol[i]; if( pCol->iSorterColumn>=j ){ int r1 = j + regBase; sqlite3ExprCodeGetColumnToReg(pParse, pCol->pTab, pCol->iColumn, pCol->iTable, r1); j++; } } regRecord = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); sqlite3ReleaseTempReg(pParse, regRecord); sqlite3ReleaseTempRange(pParse, regBase, nCol); sqlite3WhereEnd(pWInfo); sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; sortOut = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); sAggInfo.useSortingIdx = 1; sqlite3ExprCacheClear(pParse); } /* If the index or temporary table used by the GROUP BY sort ** will naturally deliver rows in the order required by the ORDER BY ** clause, cancel the ephemeral table open coded earlier. ** ** This is an optimization - the correct answer should result regardless. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to ** disable this optimization for testing purposes. */ if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) && (groupBySort || sqlite3WhereIsSorted(pWInfo)) ){ sSort.pOrderBy = 0; sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); } /* Evaluate the current GROUP BY terms and store in b0, b1, b2... ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) ** Then compare the current GROUP BY terms against the GROUP BY terms ** from the previous row currently stored in a0, a1, a2... */ addrTopOfLoop = sqlite3VdbeCurrentAddr(v); sqlite3ExprCacheClear(pParse); if( groupBySort ){ sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut, sortPTab); } for(j=0; j<pGroupBy->nExpr; j++){ if( groupBySort ){ sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); }else{ sAggInfo.directMode = 1; sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); } } sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); addr1 = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); /* Generate code that runs whenever the GROUP BY changes. ** Changes in the GROUP BY are detected by the previous code ** block. If there were no changes, this block is skipped. ** ** This code copies current group by terms in b0,b1,b2,... ** over to a0,a1,a2. It then calls the output subroutine ** and resets the aggregate accumulator registers in preparation ** for the next GROUP BY batch. */ sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); VdbeComment((v, "output one row")); sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); VdbeComment((v, "check abort flag")); sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); VdbeComment((v, "reset accumulator")); /* Update the aggregate accumulators based on the content of ** the current row */ sqlite3VdbeJumpHere(v, addr1); updateAccumulator(pParse, &sAggInfo); sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); VdbeComment((v, "indicate data in accumulator")); /* End of the loop */ if( groupBySort ){ sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); VdbeCoverage(v); }else{ sqlite3WhereEnd(pWInfo); sqlite3VdbeChangeToNoop(v, addrSortingIdx); } /* Output the final row of result */ sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); VdbeComment((v, "output final row")); /* Jump over the subroutines */ sqlite3VdbeGoto(v, addrEnd); /* Generate a subroutine that outputs a single row of the result ** set. This subroutine first looks at the iUseFlag. If iUseFlag ** is less than or equal to zero, the subroutine is a no-op. If ** the processing calls for the query to abort, this subroutine ** increments the iAbortFlag memory location before returning in ** order to signal the caller to abort. */ addrSetAbort = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); VdbeComment((v, "set abort flag")); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); sqlite3VdbeResolveLabel(v, addrOutputRow); addrOutputRow = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v); VdbeComment((v, "Groupby result generator entry point")); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); finalizeAggFunctions(pParse, &sAggInfo); sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); selectInnerLoop(pParse, p, p->pEList, -1, &sSort, &sDistinct, pDest, addrOutputRow+1, addrSetAbort); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); VdbeComment((v, "end groupby result generator")); /* Generate a subroutine that will reset the group-by accumulator */ sqlite3VdbeResolveLabel(v, addrReset); resetAccumulator(pParse, &sAggInfo); sqlite3VdbeAddOp1(v, OP_Return, regReset); } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ else { ExprList *pDel = 0; #ifndef SQLITE_OMIT_BTREECOUNT Table *pTab; if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ /* If isSimpleCount() returns a pointer to a Table structure, then ** the SQL statement is of the form: ** ** SELECT count(*) FROM <tbl> ** ** where the Table structure returned represents table <tbl>. ** ** This statement is so common that it is optimized specially. The ** OP_Count instruction is executed either on the intkey table that ** contains the data for table <tbl> or on one of its indexes. It ** is better to execute the op on an index, as indexes are almost ** always spread across less pages than their corresponding tables. */ const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ Index *pIdx; /* Iterator variable */ KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ Index *pBest = 0; /* Best index found so far */ int iRoot = pTab->tnum; /* Root page of scanned b-tree */ sqlite3CodeVerifySchema(pParse, iDb); sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); /* Search for the index that has the lowest scan cost. ** ** (2011-04-15) Do not do a full scan of an unordered index. ** ** (2013-10-03) Do not count the entries in a partial index. ** ** In practice the KeyInfo structure will not be used. It is only ** passed to keep OP_OpenRead happy. */ if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->bUnordered==0 && pIdx->szIdxRow<pTab->szTabRow && pIdx->pPartIdxWhere==0 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) ){ pBest = pIdx; } } if( pBest ){ iRoot = pBest->tnum; pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); } /* Open a read-only cursor, execute the OP_Count, close the cursor. */ sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); if( pKeyInfo ){ sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); } sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); sqlite3VdbeAddOp1(v, OP_Close, iCsr); explainSimpleCount(pParse, pTab, pBest); }else #endif /* SQLITE_OMIT_BTREECOUNT */ { /* Check if the query is of one of the following forms: ** ** SELECT min(x) FROM ... ** SELECT max(x) FROM ... ** ** If it is, then ask the code in where.c to attempt to sort results ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. ** If where.c is able to produce results sorted in this order, then ** add vdbe code to break out of the processing loop after the ** first iteration (since the first iteration of the loop is ** guaranteed to operate on the row with the minimum or maximum ** value of x, the only row required). ** ** A special flag must be passed to sqlite3WhereBegin() to slightly ** modify behavior as follows: ** ** + If the query is a "SELECT min(x)", then the loop coded by ** where.c should not iterate over any values with a NULL value ** for x. ** ** + The optimizer code in where.c (the thing that decides which ** index or indices to use) should place a different priority on ** satisfying the 'ORDER BY' clause than it does in other cases. ** Refer to code and comments in where.c for details. */ ExprList *pMinMax = 0; u8 flag = WHERE_ORDERBY_NORMAL; assert( p->pGroupBy==0 ); assert( flag==0 ); if( p->pHaving==0 ){ flag = minMaxQuery(&sAggInfo, &pMinMax); } assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); if( flag ){ pMinMax = sqlite3ExprListDup(db, pMinMax, 0); pDel = pMinMax; assert( db->mallocFailed || pMinMax!=0 ); if( !db->mallocFailed ){ pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; pMinMax->a[0].pExpr->op = TK_COLUMN; } } /* This case runs if the aggregate has no GROUP BY clause. The ** processing is much simpler since there is only a single row ** of output. */ resetAccumulator(pParse, &sAggInfo); pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0); if( pWInfo==0 ){ sqlite3ExprListDelete(db, pDel); goto select_end; } updateAccumulator(pParse, &sAggInfo); assert( pMinMax==0 || pMinMax->nExpr==1 ); if( sqlite3WhereIsOrdered(pWInfo)>0 ){ sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); VdbeComment((v, "%s() by index", (flag==WHERE_ORDERBY_MIN?"min":"max"))); } sqlite3WhereEnd(pWInfo); finalizeAggFunctions(pParse, &sAggInfo); } sSort.pOrderBy = 0; sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, pDest, addrEnd, addrEnd); sqlite3ExprListDelete(db, pDel); } sqlite3VdbeResolveLabel(v, addrEnd); } /* endif aggregate query */ if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ explainTempTable(pParse, "DISTINCT"); } /* If there is an ORDER BY clause, then we need to sort the results ** and send them to the callback one by one. */ if( sSort.pOrderBy ){ explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); } /* Jump here to skip this query */ sqlite3VdbeResolveLabel(v, iEnd); /* The SELECT has been coded. If there is an error in the Parse structure, ** set the return code to 1. Otherwise 0. */ rc = (pParse->nErr>0); /* Control jumps to here if an error is encountered above, or upon ** successful coding of the SELECT. */ select_end: explainSetInteger(pParse->iSelectId, iRestoreSelectId); /* Identify column names if results of the SELECT are to be output. */ if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ generateColumnNames(pParse, pTabList, pEList); } sqlite3DbFree(db, sAggInfo.aCol); sqlite3DbFree(db, sAggInfo.aFunc); #if SELECTTRACE_ENABLED SELECTTRACE(1,pParse,p,("end processing\n")); pParse->nSelectIndent--; #endif return rc; } /************** End of select.c **********************************************/ /************** Begin file table.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the sqlite3_get_table() and sqlite3_free_table() ** interface routines. These are just wrappers around the main ** interface routine of sqlite3_exec(). ** ** These routines are in a separate files so that they will not be linked ** if they are not used. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_GET_TABLE /* ** This structure is used to pass data from sqlite3_get_table() through ** to the callback function is uses to build the result. */ typedef struct TabResult { char **azResult; /* Accumulated output */ char *zErrMsg; /* Error message text, if an error occurs */ u32 nAlloc; /* Slots allocated for azResult[] */ u32 nRow; /* Number of rows in the result */ u32 nColumn; /* Number of columns in the result */ u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */ int rc; /* Return code from sqlite3_exec() */ } TabResult; /* ** This routine is called once for each row in the result table. Its job ** is to fill in the TabResult structure appropriately, allocating new ** memory as necessary. */ static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ TabResult *p = (TabResult*)pArg; /* Result accumulator */ int need; /* Slots needed in p->azResult[] */ int i; /* Loop counter */ char *z; /* A single column of result */ /* Make sure there is enough space in p->azResult to hold everything ** we need to remember from this invocation of the callback. */ if( p->nRow==0 && argv!=0 ){ need = nCol*2; }else{ need = nCol; } if( p->nData + need > p->nAlloc ){ char **azNew; p->nAlloc = p->nAlloc*2 + need; azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc ); if( azNew==0 ) goto malloc_failed; p->azResult = azNew; } /* If this is the first row, then generate an extra row containing ** the names of all columns. */ if( p->nRow==0 ){ p->nColumn = nCol; for(i=0; i<nCol; i++){ z = sqlite3_mprintf("%s", colv[i]); if( z==0 ) goto malloc_failed; p->azResult[p->nData++] = z; } }else if( (int)p->nColumn!=nCol ){ sqlite3_free(p->zErrMsg); p->zErrMsg = sqlite3_mprintf( "sqlite3_get_table() called with two or more incompatible queries" ); p->rc = SQLITE_ERROR; return 1; } /* Copy over the row data */ if( argv!=0 ){ for(i=0; i<nCol; i++){ if( argv[i]==0 ){ z = 0; }else{ int n = sqlite3Strlen30(argv[i])+1; z = sqlite3_malloc64( n ); if( z==0 ) goto malloc_failed; memcpy(z, argv[i], n); } p->azResult[p->nData++] = z; } p->nRow++; } return 0; malloc_failed: p->rc = SQLITE_NOMEM_BKPT; return 1; } /* ** Query the database. But instead of invoking a callback for each row, ** malloc() for space to hold the result and return the entire results ** at the conclusion of the call. ** ** The result that is written to ***pazResult is held in memory obtained ** from malloc(). But the caller cannot free this memory directly. ** Instead, the entire table should be passed to sqlite3_free_table() when ** the calling procedure is finished using it. */ SQLITE_API int sqlite3_get_table( sqlite3 *db, /* The database on which the SQL executes */ const char *zSql, /* The SQL to be executed */ char ***pazResult, /* Write the result table here */ int *pnRow, /* Write the number of rows in the result here */ int *pnColumn, /* Write the number of columns of result here */ char **pzErrMsg /* Write error messages here */ ){ int rc; TabResult res; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT; #endif *pazResult = 0; if( pnColumn ) *pnColumn = 0; if( pnRow ) *pnRow = 0; if( pzErrMsg ) *pzErrMsg = 0; res.zErrMsg = 0; res.nRow = 0; res.nColumn = 0; res.nData = 1; res.nAlloc = 20; res.rc = SQLITE_OK; res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc ); if( res.azResult==0 ){ db->errCode = SQLITE_NOMEM; return SQLITE_NOMEM_BKPT; } res.azResult[0] = 0; rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg); assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); res.azResult[0] = SQLITE_INT_TO_PTR(res.nData); if( (rc&0xff)==SQLITE_ABORT ){ sqlite3_free_table(&res.azResult[1]); if( res.zErrMsg ){ if( pzErrMsg ){ sqlite3_free(*pzErrMsg); *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); } sqlite3_free(res.zErrMsg); } db->errCode = res.rc; /* Assume 32-bit assignment is atomic */ return res.rc; } sqlite3_free(res.zErrMsg); if( rc!=SQLITE_OK ){ sqlite3_free_table(&res.azResult[1]); return rc; } if( res.nAlloc>res.nData ){ char **azNew; azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData ); if( azNew==0 ){ sqlite3_free_table(&res.azResult[1]); db->errCode = SQLITE_NOMEM; return SQLITE_NOMEM_BKPT; } res.azResult = azNew; } *pazResult = &res.azResult[1]; if( pnColumn ) *pnColumn = res.nColumn; if( pnRow ) *pnRow = res.nRow; return rc; } /* ** This routine frees the space the sqlite3_get_table() malloced. */ SQLITE_API void sqlite3_free_table( char **azResult /* Result returned from sqlite3_get_table() */ ){ if( azResult ){ int i, n; azResult--; assert( azResult!=0 ); n = SQLITE_PTR_TO_INT(azResult[0]); for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); } sqlite3_free(azResult); } } #endif /* SQLITE_OMIT_GET_TABLE */ /************** End of table.c ***********************************************/ /************** Begin file trigger.c *****************************************/ /* ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation for TRIGGERs */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_TRIGGER /* ** Delete a linked list of TriggerStep structures. */ SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){ while( pTriggerStep ){ TriggerStep * pTmp = pTriggerStep; pTriggerStep = pTriggerStep->pNext; sqlite3ExprDelete(db, pTmp->pWhere); sqlite3ExprListDelete(db, pTmp->pExprList); sqlite3SelectDelete(db, pTmp->pSelect); sqlite3IdListDelete(db, pTmp->pIdList); sqlite3DbFree(db, pTmp); } } /* ** Given table pTab, return a list of all the triggers attached to ** the table. The list is connected by Trigger.pNext pointers. ** ** All of the triggers on pTab that are in the same database as pTab ** are already attached to pTab->pTrigger. But there might be additional ** triggers on pTab in the TEMP schema. This routine prepends all ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list ** and returns the combined list. ** ** To state it another way: This routine returns a list of all triggers ** that fire off of pTab. The list will include any TEMP triggers on ** pTab as well as the triggers lised in pTab->pTrigger. */ SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ Schema * const pTmpSchema = pParse->db->aDb[1].pSchema; Trigger *pList = 0; /* List of triggers to return */ if( pParse->disableTriggers ){ return 0; } if( pTmpSchema!=pTab->pSchema ){ HashElem *p; assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) ); for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){ Trigger *pTrig = (Trigger *)sqliteHashData(p); if( pTrig->pTabSchema==pTab->pSchema && 0==sqlite3StrICmp(pTrig->table, pTab->zName) ){ pTrig->pNext = (pList ? pList : pTab->pTrigger); pList = pTrig; } } } return (pList ? pList : pTab->pTrigger); } /* ** This is called by the parser when it sees a CREATE TRIGGER statement ** up to the point of the BEGIN before the trigger actions. A Trigger ** structure is generated based on the information available and stored ** in pParse->pNewTrigger. After the trigger actions have been parsed, the ** sqlite3FinishTrigger() function is called to complete the trigger ** construction process. */ SQLITE_PRIVATE void sqlite3BeginTrigger( Parse *pParse, /* The parse context of the CREATE TRIGGER statement */ Token *pName1, /* The name of the trigger */ Token *pName2, /* The name of the trigger */ int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */ int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */ IdList *pColumns, /* column list if this is an UPDATE OF trigger */ SrcList *pTableName,/* The name of the table/view the trigger applies to */ Expr *pWhen, /* WHEN clause */ int isTemp, /* True if the TEMPORARY keyword is present */ int noErr /* Suppress errors if the trigger already exists */ ){ Trigger *pTrigger = 0; /* The new trigger */ Table *pTab; /* Table that the trigger fires off of */ char *zName = 0; /* Name of the trigger */ sqlite3 *db = pParse->db; /* The database connection */ int iDb; /* The database to store the trigger in */ Token *pName; /* The unqualified db name */ DbFixer sFix; /* State vector for the DB fixer */ assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */ assert( pName2!=0 ); assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE ); assert( op>0 && op<0xff ); if( isTemp ){ /* If TEMP was specified, then the trigger name may not be qualified. */ if( pName2->n>0 ){ sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name"); goto trigger_cleanup; } iDb = 1; pName = pName1; }else{ /* Figure out the db that the trigger will be created in */ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ){ goto trigger_cleanup; } } if( !pTableName || db->mallocFailed ){ goto trigger_cleanup; } /* A long-standing parser bug is that this syntax was allowed: ** ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab .... ** ^^^^^^^^ ** ** To maintain backwards compatibility, ignore the database ** name on pTableName if we are reparsing out of SQLITE_MASTER. */ if( db->init.busy && iDb!=1 ){ sqlite3DbFree(db, pTableName->a[0].zDatabase); pTableName->a[0].zDatabase = 0; } /* If the trigger name was unqualified, and the table is a temp table, ** then set iDb to 1 to create the trigger in the temporary database. ** If sqlite3SrcListLookup() returns 0, indicating the table does not ** exist, the error is caught by the block below. */ pTab = sqlite3SrcListLookup(pParse, pTableName); if( db->init.busy==0 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ iDb = 1; } /* Ensure the table name matches database name and that the table exists */ if( db->mallocFailed ) goto trigger_cleanup; assert( pTableName->nSrc==1 ); sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName); if( sqlite3FixSrcList(&sFix, pTableName) ){ goto trigger_cleanup; } pTab = sqlite3SrcListLookup(pParse, pTableName); if( !pTab ){ /* The table does not exist. */ if( db->init.iDb==1 ){ /* Ticket #3810. ** Normally, whenever a table is dropped, all associated triggers are ** dropped too. But if a TEMP trigger is created on a non-TEMP table ** and the table is dropped by a different database connection, the ** trigger is not visible to the database connection that does the ** drop so the trigger cannot be dropped. This results in an ** "orphaned trigger" - a trigger whose associated table is missing. */ db->init.orphanTrigger = 1; } goto trigger_cleanup; } if( IsVirtual(pTab) ){ sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables"); goto trigger_cleanup; } /* Check that the trigger name is not reserved and that no trigger of the ** specified name exists */ zName = sqlite3NameFromToken(db, pName); if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto trigger_cleanup; } assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){ if( !noErr ){ sqlite3ErrorMsg(pParse, "trigger %T already exists", pName); }else{ assert( !db->init.busy ); sqlite3CodeVerifySchema(pParse, iDb); } goto trigger_cleanup; } /* Do not create a trigger on a system table */ if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ sqlite3ErrorMsg(pParse, "cannot create trigger on system table"); goto trigger_cleanup; } /* INSTEAD of triggers are only for views and views only support INSTEAD ** of triggers. */ if( pTab->pSelect && tr_tm!=TK_INSTEAD ){ sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0); goto trigger_cleanup; } if( !pTab->pSelect && tr_tm==TK_INSTEAD ){ sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF" " trigger on table: %S", pTableName, 0); goto trigger_cleanup; } #ifndef SQLITE_OMIT_AUTHORIZATION { int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); int code = SQLITE_CREATE_TRIGGER; const char *zDb = db->aDb[iTabDb].zDbSName; const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb; if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER; if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){ goto trigger_cleanup; } if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){ goto trigger_cleanup; } } #endif /* INSTEAD OF triggers can only appear on views and BEFORE triggers ** cannot appear on views. So we might as well translate every ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code ** elsewhere. */ if (tr_tm == TK_INSTEAD){ tr_tm = TK_BEFORE; } /* Build the Trigger object */ pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger)); if( pTrigger==0 ) goto trigger_cleanup; pTrigger->zName = zName; zName = 0; pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName); pTrigger->pSchema = db->aDb[iDb].pSchema; pTrigger->pTabSchema = pTab->pSchema; pTrigger->op = (u8)op; pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER; pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); pTrigger->pColumns = sqlite3IdListDup(db, pColumns); assert( pParse->pNewTrigger==0 ); pParse->pNewTrigger = pTrigger; trigger_cleanup: sqlite3DbFree(db, zName); sqlite3SrcListDelete(db, pTableName); sqlite3IdListDelete(db, pColumns); sqlite3ExprDelete(db, pWhen); if( !pParse->pNewTrigger ){ sqlite3DeleteTrigger(db, pTrigger); }else{ assert( pParse->pNewTrigger==pTrigger ); } } /* ** This routine is called after all of the trigger actions have been parsed ** in order to complete the process of building the trigger. */ SQLITE_PRIVATE void sqlite3FinishTrigger( Parse *pParse, /* Parser context */ TriggerStep *pStepList, /* The triggered program */ Token *pAll /* Token that describes the complete CREATE TRIGGER */ ){ Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */ char *zName; /* Name of trigger */ sqlite3 *db = pParse->db; /* The database */ DbFixer sFix; /* Fixer object */ int iDb; /* Database containing the trigger */ Token nameToken; /* Trigger name for error reporting */ pParse->pNewTrigger = 0; if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup; zName = pTrig->zName; iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); pTrig->step_list = pStepList; while( pStepList ){ pStepList->pTrig = pTrig; pStepList = pStepList->pNext; } sqlite3TokenInit(&nameToken, pTrig->zName); sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken); if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) || sqlite3FixExpr(&sFix, pTrig->pWhen) ){ goto triggerfinish_cleanup; } /* if we are not initializing, ** build the sqlite_master entry */ if( !db->init.busy ){ Vdbe *v; char *z; /* Make an entry in the sqlite_master table */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto triggerfinish_cleanup; sqlite3BeginWriteOperation(pParse, 0, iDb); z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); sqlite3NestedParse(pParse, "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", db->aDb[iDb].zDbSName, MASTER_NAME, zName, pTrig->table, z); sqlite3DbFree(db, z); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddParseSchemaOp(v, iDb, sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName)); } if( db->init.busy ){ Trigger *pLink = pTrig; Hash *pHash = &db->aDb[iDb].pSchema->trigHash; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pTrig = sqlite3HashInsert(pHash, zName, pTrig); if( pTrig ){ sqlite3OomFault(db); }else if( pLink->pSchema==pLink->pTabSchema ){ Table *pTab; pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table); assert( pTab!=0 ); pLink->pNext = pTab->pTrigger; pTab->pTrigger = pLink; } } triggerfinish_cleanup: sqlite3DeleteTrigger(db, pTrig); assert( !pParse->pNewTrigger ); sqlite3DeleteTriggerStep(db, pStepList); } /* ** Turn a SELECT statement (that the pSelect parameter points to) into ** a trigger step. Return a pointer to a TriggerStep structure. ** ** The parser calls this routine when it finds a SELECT statement in ** body of a TRIGGER. */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){ TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); if( pTriggerStep==0 ) { sqlite3SelectDelete(db, pSelect); return 0; } pTriggerStep->op = TK_SELECT; pTriggerStep->pSelect = pSelect; pTriggerStep->orconf = OE_Default; return pTriggerStep; } /* ** Allocate space to hold a new trigger step. The allocated space ** holds both the TriggerStep object and the TriggerStep.target.z string. ** ** If an OOM error occurs, NULL is returned and db->mallocFailed is set. */ static TriggerStep *triggerStepAllocate( sqlite3 *db, /* Database connection */ u8 op, /* Trigger opcode */ Token *pName /* The target name */ ){ TriggerStep *pTriggerStep; pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1); if( pTriggerStep ){ char *z = (char*)&pTriggerStep[1]; memcpy(z, pName->z, pName->n); sqlite3Dequote(z); pTriggerStep->zTarget = z; pTriggerStep->op = op; } return pTriggerStep; } /* ** Build a trigger step out of an INSERT statement. Return a pointer ** to the new trigger step. ** ** The parser calls this routine when it sees an INSERT inside the ** body of a trigger. */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( sqlite3 *db, /* The database connection */ Token *pTableName, /* Name of the table into which we insert */ IdList *pColumn, /* List of columns in pTableName to insert into */ Select *pSelect, /* A SELECT statement that supplies values */ u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ ){ TriggerStep *pTriggerStep; assert(pSelect != 0 || db->mallocFailed); pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName); if( pTriggerStep ){ pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); pTriggerStep->pIdList = pColumn; pTriggerStep->orconf = orconf; }else{ sqlite3IdListDelete(db, pColumn); } sqlite3SelectDelete(db, pSelect); return pTriggerStep; } /* ** Construct a trigger step that implements an UPDATE statement and return ** a pointer to that trigger step. The parser calls this routine when it ** sees an UPDATE statement inside the body of a CREATE TRIGGER. */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( sqlite3 *db, /* The database connection */ Token *pTableName, /* Name of the table to be updated */ ExprList *pEList, /* The SET clause: list of column and new values */ Expr *pWhere, /* The WHERE clause */ u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */ ){ TriggerStep *pTriggerStep; pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName); if( pTriggerStep ){ pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); pTriggerStep->orconf = orconf; } sqlite3ExprListDelete(db, pEList); sqlite3ExprDelete(db, pWhere); return pTriggerStep; } /* ** Construct a trigger step that implements a DELETE statement and return ** a pointer to that trigger step. The parser calls this routine when it ** sees a DELETE statement inside the body of a CREATE TRIGGER. */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep( sqlite3 *db, /* Database connection */ Token *pTableName, /* The table from which rows are deleted */ Expr *pWhere /* The WHERE clause */ ){ TriggerStep *pTriggerStep; pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName); if( pTriggerStep ){ pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); pTriggerStep->orconf = OE_Default; } sqlite3ExprDelete(db, pWhere); return pTriggerStep; } /* ** Recursively delete a Trigger structure */ SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){ if( pTrigger==0 ) return; sqlite3DeleteTriggerStep(db, pTrigger->step_list); sqlite3DbFree(db, pTrigger->zName); sqlite3DbFree(db, pTrigger->table); sqlite3ExprDelete(db, pTrigger->pWhen); sqlite3IdListDelete(db, pTrigger->pColumns); sqlite3DbFree(db, pTrigger); } /* ** This function is called to drop a trigger from the database schema. ** ** This may be called directly from the parser and therefore identifies ** the trigger by name. The sqlite3DropTriggerPtr() routine does the ** same job as this routine except it takes a pointer to the trigger ** instead of the trigger name. **/ SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){ Trigger *pTrigger = 0; int i; const char *zDb; const char *zName; sqlite3 *db = pParse->db; if( db->mallocFailed ) goto drop_trigger_cleanup; if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ goto drop_trigger_cleanup; } assert( pName->nSrc==1 ); zDb = pName->a[0].zDatabase; zName = pName->a[0].zName; assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); for(i=OMIT_TEMPDB; i<db->nDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue; assert( sqlite3SchemaMutexHeld(db, j, 0) ); pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName); if( pTrigger ) break; } if( !pTrigger ){ if( !noErr ){ sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0); }else{ sqlite3CodeVerifyNamedSchema(pParse, zDb); } pParse->checkSchema = 1; goto drop_trigger_cleanup; } sqlite3DropTriggerPtr(pParse, pTrigger); drop_trigger_cleanup: sqlite3SrcListDelete(db, pName); } /* ** Return a pointer to the Table structure for the table that a trigger ** is set on. */ static Table *tableOfTrigger(Trigger *pTrigger){ return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table); } /* ** Drop a trigger given a pointer to that trigger. */ SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ Table *pTable; Vdbe *v; sqlite3 *db = pParse->db; int iDb; iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema); assert( iDb>=0 && iDb<db->nDb ); pTable = tableOfTrigger(pTrigger); assert( pTable ); assert( pTable->pSchema==pTrigger->pSchema || iDb==1 ); #ifndef SQLITE_OMIT_AUTHORIZATION { int code = SQLITE_DROP_TRIGGER; const char *zDb = db->aDb[iDb].zDbSName; const char *zTab = SCHEMA_TABLE(iDb); if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER; if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) || sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ return; } } #endif /* Generate code to destroy the database record of the trigger. */ assert( pTable!=0 ); if( (v = sqlite3GetVdbe(pParse))!=0 ){ sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'", db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName ); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0); } } /* ** Remove a trigger from the hash tables of the sqlite* pointer. */ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){ Trigger *pTrigger; Hash *pHash; assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pHash = &(db->aDb[iDb].pSchema->trigHash); pTrigger = sqlite3HashInsert(pHash, zName, 0); if( ALWAYS(pTrigger) ){ if( pTrigger->pSchema==pTrigger->pTabSchema ){ Table *pTab = tableOfTrigger(pTrigger); Trigger **pp; for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext)); *pp = (*pp)->pNext; } sqlite3DeleteTrigger(db, pTrigger); db->flags |= SQLITE_InternChanges; } } /* ** pEList is the SET clause of an UPDATE statement. Each entry ** in pEList is of the format <id>=<expr>. If any of the entries ** in pEList have an <id> which matches an identifier in pIdList, ** then return TRUE. If pIdList==NULL, then it is considered a ** wildcard that matches anything. Likewise if pEList==NULL then ** it matches anything so always return true. Return false only ** if there is no match. */ static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){ int e; if( pIdList==0 || NEVER(pEList==0) ) return 1; for(e=0; e<pEList->nExpr; e++){ if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1; } return 0; } /* ** Return a list of all triggers on table pTab if there exists at least ** one trigger that must be fired when an operation of type 'op' is ** performed on the table, and, if that operation is an UPDATE, if at ** least one of the columns in pChanges is being modified. */ SQLITE_PRIVATE Trigger *sqlite3TriggersExist( Parse *pParse, /* Parse context */ Table *pTab, /* The table the contains the triggers */ int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */ ExprList *pChanges, /* Columns that change in an UPDATE statement */ int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ ){ int mask = 0; Trigger *pList = 0; Trigger *p; if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){ pList = sqlite3TriggerList(pParse, pTab); } assert( pList==0 || IsVirtual(pTab)==0 ); for(p=pList; p; p=p->pNext){ if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){ mask |= p->tr_tm; } } if( pMask ){ *pMask = mask; } return (mask ? pList : 0); } /* ** Convert the pStep->zTarget string into a SrcList and return a pointer ** to that SrcList. ** ** This routine adds a specific database name, if needed, to the target when ** forming the SrcList. This prevents a trigger in one database from ** referring to a target in another database. An exception is when the ** trigger is in TEMP in which case it can refer to any other database it ** wants. */ static SrcList *targetSrcList( Parse *pParse, /* The parsing context */ TriggerStep *pStep /* The trigger containing the target token */ ){ sqlite3 *db = pParse->db; int iDb; /* Index of the database to use */ SrcList *pSrc; /* SrcList to be returned */ pSrc = sqlite3SrcListAppend(db, 0, 0, 0); if( pSrc ){ assert( pSrc->nSrc>0 ); pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget); iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema); if( iDb==0 || iDb>=2 ){ const char *zDb; assert( iDb<db->nDb ); zDb = db->aDb[iDb].zDbSName; pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb); } } return pSrc; } /* ** Generate VDBE code for the statements inside the body of a single ** trigger. */ static int codeTriggerProgram( Parse *pParse, /* The parser context */ TriggerStep *pStepList, /* List of statements inside the trigger body */ int orconf /* Conflict algorithm. (OE_Abort, etc) */ ){ TriggerStep *pStep; Vdbe *v = pParse->pVdbe; sqlite3 *db = pParse->db; assert( pParse->pTriggerTab && pParse->pToplevel ); assert( pStepList ); assert( v!=0 ); for(pStep=pStepList; pStep; pStep=pStep->pNext){ /* Figure out the ON CONFLICT policy that will be used for this step ** of the trigger program. If the statement that caused this trigger ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use ** the ON CONFLICT policy that was specified as part of the trigger ** step statement. Example: ** ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN; ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b); ** END; ** ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy */ pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf; assert( pParse->okConstFactor==0 ); switch( pStep->op ){ case TK_UPDATE: { sqlite3Update(pParse, targetSrcList(pParse, pStep), sqlite3ExprListDup(db, pStep->pExprList, 0), sqlite3ExprDup(db, pStep->pWhere, 0), pParse->eOrconf ); break; } case TK_INSERT: { sqlite3Insert(pParse, targetSrcList(pParse, pStep), sqlite3SelectDup(db, pStep->pSelect, 0), sqlite3IdListDup(db, pStep->pIdList), pParse->eOrconf ); break; } case TK_DELETE: { sqlite3DeleteFrom(pParse, targetSrcList(pParse, pStep), sqlite3ExprDup(db, pStep->pWhere, 0) ); break; } default: assert( pStep->op==TK_SELECT ); { SelectDest sDest; Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0); sqlite3SelectDestInit(&sDest, SRT_Discard, 0); sqlite3Select(pParse, pSelect, &sDest); sqlite3SelectDelete(db, pSelect); break; } } if( pStep->op!=TK_SELECT ){ sqlite3VdbeAddOp0(v, OP_ResetCount); } } return 0; } #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS /* ** This function is used to add VdbeComment() annotations to a VDBE ** program. It is not used in production code, only for debugging. */ static const char *onErrorText(int onError){ switch( onError ){ case OE_Abort: return "abort"; case OE_Rollback: return "rollback"; case OE_Fail: return "fail"; case OE_Replace: return "replace"; case OE_Ignore: return "ignore"; case OE_Default: return "default"; } return "n/a"; } #endif /* ** Parse context structure pFrom has just been used to create a sub-vdbe ** (trigger program). If an error has occurred, transfer error information ** from pFrom to pTo. */ static void transferParseError(Parse *pTo, Parse *pFrom){ assert( pFrom->zErrMsg==0 || pFrom->nErr ); assert( pTo->zErrMsg==0 || pTo->nErr ); if( pTo->nErr==0 ){ pTo->zErrMsg = pFrom->zErrMsg; pTo->nErr = pFrom->nErr; pTo->rc = pFrom->rc; }else{ sqlite3DbFree(pFrom->db, pFrom->zErrMsg); } } /* ** Create and populate a new TriggerPrg object with a sub-program ** implementing trigger pTrigger with ON CONFLICT policy orconf. */ static TriggerPrg *codeRowTrigger( Parse *pParse, /* Current parse context */ Trigger *pTrigger, /* Trigger to code */ Table *pTab, /* The table pTrigger is attached to */ int orconf /* ON CONFLICT policy to code trigger program with */ ){ Parse *pTop = sqlite3ParseToplevel(pParse); sqlite3 *db = pParse->db; /* Database handle */ TriggerPrg *pPrg; /* Value to return */ Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */ Vdbe *v; /* Temporary VM */ NameContext sNC; /* Name context for sub-vdbe */ SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */ Parse *pSubParse; /* Parse context for sub-vdbe */ int iEndTrigger = 0; /* Label to jump to if WHEN is false */ assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); assert( pTop->pVdbe ); /* Allocate the TriggerPrg and SubProgram objects. To ensure that they ** are freed if an error occurs, link them into the Parse.pTriggerPrg ** list of the top-level Parse object sooner rather than later. */ pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg)); if( !pPrg ) return 0; pPrg->pNext = pTop->pTriggerPrg; pTop->pTriggerPrg = pPrg; pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram)); if( !pProgram ) return 0; sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram); pPrg->pTrigger = pTrigger; pPrg->orconf = orconf; pPrg->aColmask[0] = 0xffffffff; pPrg->aColmask[1] = 0xffffffff; /* Allocate and populate a new Parse context to use for coding the ** trigger sub-program. */ pSubParse = sqlite3StackAllocZero(db, sizeof(Parse)); if( !pSubParse ) return 0; memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pSubParse; pSubParse->db = db; pSubParse->pTriggerTab = pTab; pSubParse->pToplevel = pTop; pSubParse->zAuthContext = pTrigger->zName; pSubParse->eTriggerOp = pTrigger->op; pSubParse->nQueryLoop = pParse->nQueryLoop; v = sqlite3GetVdbe(pSubParse); if( v ){ VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", pTrigger->zName, onErrorText(orconf), (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"), (pTrigger->op==TK_UPDATE ? "UPDATE" : ""), (pTrigger->op==TK_INSERT ? "INSERT" : ""), (pTrigger->op==TK_DELETE ? "DELETE" : ""), pTab->zName )); #ifndef SQLITE_OMIT_TRACE sqlite3VdbeChangeP4(v, -1, sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC ); #endif /* If one was specified, code the WHEN clause. If it evaluates to false ** (or NULL) the sub-vdbe is immediately halted by jumping to the ** OP_Halt inserted at the end of the program. */ if( pTrigger->pWhen ){ pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0); if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) && db->mallocFailed==0 ){ iEndTrigger = sqlite3VdbeMakeLabel(v); sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL); } sqlite3ExprDelete(db, pWhen); } /* Code the trigger program into the sub-vdbe. */ codeTriggerProgram(pSubParse, pTrigger->step_list, orconf); /* Insert an OP_Halt at the end of the sub-program. */ if( iEndTrigger ){ sqlite3VdbeResolveLabel(v, iEndTrigger); } sqlite3VdbeAddOp0(v, OP_Halt); VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf))); transferParseError(pParse, pSubParse); if( db->mallocFailed==0 ){ pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg); } pProgram->nMem = pSubParse->nMem; pProgram->nCsr = pSubParse->nTab; pProgram->token = (void *)pTrigger; pPrg->aColmask[0] = pSubParse->oldmask; pPrg->aColmask[1] = pSubParse->newmask; sqlite3VdbeDelete(v); } assert( !pSubParse->pAinc && !pSubParse->pZombieTab ); assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg ); sqlite3ParserReset(pSubParse); sqlite3StackFree(db, pSubParse); return pPrg; } /* ** Return a pointer to a TriggerPrg object containing the sub-program for ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such ** TriggerPrg object exists, a new object is allocated and populated before ** being returned. */ static TriggerPrg *getRowTrigger( Parse *pParse, /* Current parse context */ Trigger *pTrigger, /* Trigger to code */ Table *pTab, /* The table trigger pTrigger is attached to */ int orconf /* ON CONFLICT algorithm. */ ){ Parse *pRoot = sqlite3ParseToplevel(pParse); TriggerPrg *pPrg; assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); /* It may be that this trigger has already been coded (or is in the ** process of being coded). If this is the case, then an entry with ** a matching TriggerPrg.pTrigger field will be present somewhere ** in the Parse.pTriggerPrg list. Search for such an entry. */ for(pPrg=pRoot->pTriggerPrg; pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); pPrg=pPrg->pNext ); /* If an existing TriggerPrg could not be located, create a new one. */ if( !pPrg ){ pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf); } return pPrg; } /* ** Generate code for the trigger program associated with trigger p on ** table pTab. The reg, orconf and ignoreJump parameters passed to this ** function are the same as those described in the header function for ** sqlite3CodeRowTrigger() */ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( Parse *pParse, /* Parse context */ Trigger *p, /* Trigger to code */ Table *pTab, /* The table to code triggers from */ int reg, /* Reg array containing OLD.* and NEW.* values */ int orconf, /* ON CONFLICT policy */ int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ ){ Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */ TriggerPrg *pPrg; pPrg = getRowTrigger(pParse, p, pTab, orconf); assert( pPrg || pParse->nErr || pParse->db->mallocFailed ); /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program ** is a pointer to the sub-vdbe containing the trigger program. */ if( pPrg ){ int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers)); sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem, (const char *)pPrg->pProgram, P4_SUBPROGRAM); VdbeComment( (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf))); /* Set the P5 operand of the OP_Program instruction to non-zero if ** recursive invocation of this trigger program is disallowed. Recursive ** invocation is disallowed if (a) the sub-program is really a trigger, ** not a foreign key action, and (b) the flag to enable recursive triggers ** is clear. */ sqlite3VdbeChangeP5(v, (u8)bRecursive); } } /* ** This is called to code the required FOR EACH ROW triggers for an operation ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE) ** is given by the op parameter. The tr_tm parameter determines whether the ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then ** parameter pChanges is passed the list of columns being modified. ** ** If there are no triggers that fire at the specified time for the specified ** operation on pTab, this function is a no-op. ** ** The reg argument is the address of the first in an array of registers ** that contain the values substituted for the new.* and old.* references ** in the trigger program. If N is the number of columns in table pTab ** (a copy of pTab->nCol), then registers are populated as follows: ** ** Register Contains ** ------------------------------------------------------ ** reg+0 OLD.rowid ** reg+1 OLD.* value of left-most column of pTab ** ... ... ** reg+N OLD.* value of right-most column of pTab ** reg+N+1 NEW.rowid ** reg+N+2 OLD.* value of left-most column of pTab ** ... ... ** reg+N+N+1 NEW.* value of right-most column of pTab ** ** For ON DELETE triggers, the registers containing the NEW.* values will ** never be accessed by the trigger program, so they are not allocated or ** populated by the caller (there is no data to populate them with anyway). ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers ** are never accessed, and so are not allocated by the caller. So, for an ** ON INSERT trigger, the value passed to this function as parameter reg ** is not a readable register, although registers (reg+N) through ** (reg+N+N+1) are. ** ** Parameter orconf is the default conflict resolution algorithm for the ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump ** is the instruction that control should jump to if a trigger program ** raises an IGNORE exception. */ SQLITE_PRIVATE void sqlite3CodeRowTrigger( Parse *pParse, /* Parse context */ Trigger *pTrigger, /* List of triggers on table pTab */ int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */ ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ Table *pTab, /* The table to code triggers from */ int reg, /* The first in an array of registers (see above) */ int orconf, /* ON CONFLICT policy */ int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ ){ Trigger *p; /* Used to iterate through pTrigger list */ assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE ); assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER ); assert( (op==TK_UPDATE)==(pChanges!=0) ); for(p=pTrigger; p; p=p->pNext){ /* Sanity checking: The schema for the trigger and for the table are ** always defined. The trigger must be in the same schema as the table ** or else it must be a TEMP trigger. */ assert( p->pSchema!=0 ); assert( p->pTabSchema!=0 ); assert( p->pSchema==p->pTabSchema || p->pSchema==pParse->db->aDb[1].pSchema ); /* Determine whether we should code this trigger */ if( p->op==op && p->tr_tm==tr_tm && checkColumnOverlap(p->pColumns, pChanges) ){ sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump); } } } /* ** Triggers may access values stored in the old.* or new.* pseudo-table. ** This function returns a 32-bit bitmask indicating which columns of the ** old.* or new.* tables actually are used by triggers. This information ** may be used by the caller, for example, to avoid having to load the entire ** old.* record into memory when executing an UPDATE or DELETE command. ** ** Bit 0 of the returned mask is set if the left-most column of the ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if ** the second leftmost column value is required, and so on. If there ** are more than 32 columns in the table, and at least one of the columns ** with an index greater than 32 may be accessed, 0xffffffff is returned. ** ** It is not possible to determine if the old.rowid or new.rowid column is ** accessed by triggers. The caller must always assume that it is. ** ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned ** applies to the old.* table. If 1, the new.* table. ** ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only ** included in the returned mask if the TRIGGER_BEFORE bit is set in the ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm. */ SQLITE_PRIVATE u32 sqlite3TriggerColmask( Parse *pParse, /* Parse context */ Trigger *pTrigger, /* List of triggers on table pTab */ ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */ int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ Table *pTab, /* The table to code triggers from */ int orconf /* Default ON CONFLICT policy for trigger steps */ ){ const int op = pChanges ? TK_UPDATE : TK_DELETE; u32 mask = 0; Trigger *p; assert( isNew==1 || isNew==0 ); for(p=pTrigger; p; p=p->pNext){ if( p->op==op && (tr_tm&p->tr_tm) && checkColumnOverlap(p->pColumns,pChanges) ){ TriggerPrg *pPrg; pPrg = getRowTrigger(pParse, p, pTab, orconf); if( pPrg ){ mask |= pPrg->aColmask[isNew]; } } } return mask; } #endif /* !defined(SQLITE_OMIT_TRIGGER) */ /************** End of trigger.c *********************************************/ /************** Begin file update.c ******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle UPDATE statements. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Forward declaration */ static void updateVirtualTable( Parse *pParse, /* The parsing context */ SrcList *pSrc, /* The virtual table to be modified */ Table *pTab, /* The virtual table */ ExprList *pChanges, /* The columns to change in the UPDATE statement */ Expr *pRowidExpr, /* Expression used to recompute the rowid */ int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ Expr *pWhere, /* WHERE clause of the UPDATE statement */ int onError /* ON CONFLICT strategy */ ); #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* ** The most recently coded instruction was an OP_Column to retrieve the ** i-th column of table pTab. This routine sets the P4 parameter of the ** OP_Column to the default value, if any. ** ** The default value of a column is specified by a DEFAULT clause in the ** column definition. This was either supplied by the user when the table ** was created, or added later to the table definition by an ALTER TABLE ** command. If the latter, then the row-records in the table btree on disk ** may not contain a value for the column and the default value, taken ** from the P4 parameter of the OP_Column instruction, is returned instead. ** If the former, then all row-records are guaranteed to include a value ** for the column and the P4 value is not required. ** ** Column definitions created by an ALTER TABLE command may only have ** literal default values specified: a number, null or a string. (If a more ** complicated default expression value was provided, it is evaluated ** when the ALTER TABLE is executed and one of the literal values written ** into the sqlite_master table.) ** ** Therefore, the P4 parameter is only required if the default value for ** the column is a literal number, string or null. The sqlite3ValueFromExpr() ** function is capable of transforming these types of expressions into ** sqlite3_value objects. ** ** If parameter iReg is not negative, code an OP_RealAffinity instruction ** on register iReg. This is used when an equivalent integer value is ** stored in place of an 8-byte floating point value in order to save ** space. */ SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ assert( pTab!=0 ); if( !pTab->pSelect ){ sqlite3_value *pValue = 0; u8 enc = ENC(sqlite3VdbeDb(v)); Column *pCol = &pTab->aCol[i]; VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); assert( i<pTab->nCol ); sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, pCol->affinity, &pValue); if( pValue ){ sqlite3VdbeAppendP4(v, pValue, P4_MEM); } } #ifndef SQLITE_OMIT_FLOATING_POINT if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); } #endif } /* ** Process an UPDATE statement. ** ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL; ** \_______/ \________/ \______/ \________________/ * onError pTabList pChanges pWhere */ SQLITE_PRIVATE void sqlite3Update( Parse *pParse, /* The parser context */ SrcList *pTabList, /* The table in which we should change things */ ExprList *pChanges, /* Things to be changed */ Expr *pWhere, /* The WHERE clause. May be null */ int onError /* How to handle constraint errors */ ){ int i, j; /* Loop counters */ Table *pTab; /* The table to be updated */ int addrTop = 0; /* VDBE instruction address of the start of the loop */ WhereInfo *pWInfo; /* Information about the WHERE clause */ Vdbe *v; /* The virtual database engine */ Index *pIdx; /* For looping over indices */ Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */ int nIdx; /* Number of indices that need updating */ int iBaseCur; /* Base cursor number */ int iDataCur; /* Cursor for the canonical data btree */ int iIdxCur; /* Cursor for the first index */ sqlite3 *db; /* The database structure */ int *aRegIdx = 0; /* First register in array assigned to each index */ int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the ** an expression for the i-th column of the table. ** aXRef[i]==-1 if the i-th column is not changed. */ u8 *aToOpen; /* 1 for tables and indices to be opened */ u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */ u8 chngRowid; /* Rowid changed in a normal table */ u8 chngKey; /* Either chngPk or chngRowid */ Expr *pRowidExpr = 0; /* Expression defining the new record number */ AuthContext sContext; /* The authorization context */ NameContext sNC; /* The name-context to resolve expressions in */ int iDb; /* Database containing the table being updated */ int eOnePass; /* ONEPASS_XXX value from where.c */ int hasFK; /* True if foreign key processing is required */ int labelBreak; /* Jump here to break out of UPDATE loop */ int labelContinue; /* Jump here to continue next step of UPDATE loop */ int flags; /* Flags for sqlite3WhereBegin() */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True when updating a view (INSTEAD OF trigger) */ Trigger *pTrigger; /* List of triggers on pTab, if required */ int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ #endif int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ int iEph = 0; /* Ephemeral table holding all primary key values */ int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */ int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ int addrOpen = 0; /* Address of OP_OpenEphemeral */ int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */ i16 nPk = 0; /* Number of components of the PRIMARY KEY */ int bReplace = 0; /* True if REPLACE conflict resolution might happen */ /* Register Allocations */ int regRowCount = 0; /* A count of rows changed */ int regOldRowid = 0; /* The old rowid */ int regNewRowid = 0; /* The new rowid */ int regNew = 0; /* Content of the NEW.* table in triggers */ int regOld = 0; /* Content of OLD.* table in triggers */ int regRowSet = 0; /* Rowset of rows to be updated */ int regKey = 0; /* composite PRIMARY KEY value */ memset(&sContext, 0, sizeof(sContext)); db = pParse->db; if( pParse->nErr || db->mallocFailed ){ goto update_cleanup; } assert( pTabList->nSrc==1 ); /* Locate the table which we want to update. */ pTab = sqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ) goto update_cleanup; iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); /* Figure out if we have any triggers and if the table being ** updated is a view. */ #ifndef SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask); isView = pTab->pSelect!=0; assert( pTrigger || tmask==0 ); #else # define pTrigger 0 # define isView 0 # define tmask 0 #endif #ifdef SQLITE_OMIT_VIEW # undef isView # define isView 0 #endif if( sqlite3ViewGetColumnNames(pParse, pTab) ){ goto update_cleanup; } if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ goto update_cleanup; } /* Allocate a cursors for the main database table and for all indices. ** The index cursors might not be used, but if they are used they ** need to occur right after the database cursor. So go ahead and ** allocate enough space, just in case. */ pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++; iIdxCur = iDataCur+1; pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){ iDataCur = pParse->nTab; pTabList->a[0].iCursor = iDataCur; } pParse->nTab++; } /* Allocate space for aXRef[], aRegIdx[], and aToOpen[]. ** Initialize aXRef[] and aToOpen[] to their default values. */ aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 ); if( aXRef==0 ) goto update_cleanup; aRegIdx = aXRef+pTab->nCol; aToOpen = (u8*)(aRegIdx+nIdx); memset(aToOpen, 1, nIdx+1); aToOpen[nIdx+1] = 0; for(i=0; i<pTab->nCol; i++) aXRef[i] = -1; /* Initialize the name-context */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; /* Resolve the column names in all the expressions of the ** of the UPDATE statement. Also find the column index ** for each column to be updated in the pChanges array. For each ** column to be updated, make sure we have authorization to change ** that column. */ chngRowid = chngPk = 0; for(i=0; i<pChanges->nExpr; i++){ if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ goto update_cleanup; } for(j=0; j<pTab->nCol; j++){ if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){ if( j==pTab->iPKey ){ chngRowid = 1; pRowidExpr = pChanges->a[i].pExpr; }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ chngPk = 1; } aXRef[j] = i; break; } } if( j>=pTab->nCol ){ if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){ j = -1; chngRowid = 1; pRowidExpr = pChanges->a[i].pExpr; }else{ sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName); pParse->checkSchema = 1; goto update_cleanup; } } #ifndef SQLITE_OMIT_AUTHORIZATION { int rc; rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName, j<0 ? "ROWID" : pTab->aCol[j].zName, db->aDb[iDb].zDbSName); if( rc==SQLITE_DENY ){ goto update_cleanup; }else if( rc==SQLITE_IGNORE ){ aXRef[j] = -1; } } #endif } assert( (chngRowid & chngPk)==0 ); assert( chngRowid==0 || chngRowid==1 ); assert( chngPk==0 || chngPk==1 ); chngKey = chngRowid + chngPk; /* The SET expressions are not actually used inside the WHERE loop. ** So reset the colUsed mask. Unless this is a virtual table. In that ** case, set all bits of the colUsed mask (to ensure that the virtual ** table implementation makes all columns available). */ pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0; hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey); /* There is one entry in the aRegIdx[] array for each index on the table ** being updated. Fill in aRegIdx[] with a register number that will hold ** the key for accessing each index. ** ** FIXME: Be smarter about omitting indexes that use expressions. */ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int reg; if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){ reg = ++pParse->nMem; pParse->nMem += pIdx->nColumn; }else{ reg = 0; for(i=0; i<pIdx->nKeyCol; i++){ i16 iIdxCol = pIdx->aiColumn[i]; if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){ reg = ++pParse->nMem; pParse->nMem += pIdx->nColumn; if( (onError==OE_Replace) || (onError==OE_Default && pIdx->onError==OE_Replace) ){ bReplace = 1; } break; } } } if( reg==0 ) aToOpen[j+1] = 0; aRegIdx[j] = reg; } if( bReplace ){ /* If REPLACE conflict resolution might be invoked, open cursors on all ** indexes in case they are needed to delete records. */ memset(aToOpen, 1, nIdx+1); } /* Begin generating code. */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto update_cleanup; if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, 1, iDb); /* Allocate required registers. */ if( !IsVirtual(pTab) ){ regRowSet = ++pParse->nMem; regOldRowid = regNewRowid = ++pParse->nMem; if( chngPk || pTrigger || hasFK ){ regOld = pParse->nMem + 1; pParse->nMem += pTab->nCol; } if( chngKey || pTrigger || hasFK ){ regNewRowid = ++pParse->nMem; } regNew = pParse->nMem + 1; pParse->nMem += pTab->nCol; } /* Start the view context. */ if( isView ){ sqlite3AuthContextPush(pParse, &sContext, pTab->zName); } /* If we are trying to update a view, realize that view into ** an ephemeral table. */ #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) if( isView ){ sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur); } #endif /* Resolve the column names in all the expressions in the ** WHERE clause. */ if( sqlite3ResolveExprNames(&sNC, pWhere) ){ goto update_cleanup; } #ifndef SQLITE_OMIT_VIRTUALTABLE /* Virtual tables must be handled separately */ if( IsVirtual(pTab) ){ updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, pWhere, onError); goto update_cleanup; } #endif /* Initialize the count of updated rows */ if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){ regRowCount = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } if( HasRowid(pTab) ){ sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); }else{ assert( pPk!=0 ); nPk = pPk->nKeyCol; iPk = pParse->nMem+1; pParse->nMem += nPk; regKey = ++pParse->nMem; iEph = pParse->nTab++; sqlite3VdbeAddOp2(v, OP_Null, 0, iPk); addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk); sqlite3VdbeSetP4KeyInfo(pParse, pPk); } /* Begin the database scan. ** ** Do not consider a single-pass strategy for a multi-row update if ** there are any triggers or foreign keys to process, or rows may ** be deleted as a result of REPLACE conflict handling. Any of these ** things might disturb a cursor being used to scan through the table ** or index, causing a single-pass approach to malfunction. */ flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE; if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){ flags |= WHERE_ONEPASS_MULTIROW; } pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur); if( pWInfo==0 ) goto update_cleanup; /* A one-pass strategy that might update more than one row may not ** be used if any column of the index used for the scan is being ** updated. Otherwise, if there is an index on "b", statements like ** the following could create an infinite loop: ** ** UPDATE t1 SET b=b+1 WHERE b>? ** ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI ** strategy that uses an index for which one or more columns are being ** updated. */ eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); if( eOnePass==ONEPASS_MULTI ){ int iCur = aiCurOnePass[1]; if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){ eOnePass = ONEPASS_OFF; } assert( iCur!=iDataCur || !HasRowid(pTab) ); } if( HasRowid(pTab) ){ /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF ** mode, write the rowid into the FIFO. In either of the one-pass modes, ** leave it in register regOldRowid. */ sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid); if( eOnePass==ONEPASS_OFF ){ sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); } }else{ /* Read the PK of the current row into an array of registers. In ** ONEPASS_OFF mode, serialize the array into a record and store it in ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table ** is not required) and leave the PK fields in the array of registers. */ for(i=0; i<nPk; i++){ assert( pPk->aiColumn[i]>=0 ); sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i); } if( eOnePass ){ sqlite3VdbeChangeToNoop(v, addrOpen); nKey = nPk; regKey = iPk; }else{ sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey, sqlite3IndexAffinityStr(db, pPk), nPk); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk); } } if( eOnePass!=ONEPASS_MULTI ){ sqlite3WhereEnd(pWInfo); } labelBreak = sqlite3VdbeMakeLabel(v); if( !isView ){ int addrOnce = 0; /* Open every index that needs updating. */ if( eOnePass!=ONEPASS_OFF ){ if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0; if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0; } if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen, 0, 0); if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); } /* Top of the update loop */ if( eOnePass!=ONEPASS_OFF ){ if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){ assert( pPk ); sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey); VdbeCoverageNeverTaken(v); } if( eOnePass==ONEPASS_SINGLE ){ labelContinue = labelBreak; }else{ labelContinue = sqlite3VdbeMakeLabel(v); } sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak); VdbeCoverageIf(v, pPk==0); VdbeCoverageIf(v, pPk!=0); }else if( pPk ){ labelContinue = sqlite3VdbeMakeLabel(v); sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v); addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey); sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0); VdbeCoverage(v); }else{ labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak, regOldRowid); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); VdbeCoverage(v); } /* If the record number will change, set register regNewRowid to ** contain the new value. If the record number is not being modified, ** then regNewRowid is the same register as regOldRowid, which is ** already populated. */ assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid ); if( chngRowid ){ sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v); } /* Compute the old pre-UPDATE content of the row being changed, if that ** information is needed */ if( chngPk || hasFK || pTrigger ){ u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); oldmask |= sqlite3TriggerColmask(pParse, pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError ); for(i=0; i<pTab->nCol; i++){ if( oldmask==0xffffffff || (i<32 && (oldmask & MASKBIT32(i))!=0) || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){ testcase( oldmask!=0xffffffff && i==31 ); sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i); } } if( chngRowid==0 && pPk==0 ){ sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid); } } /* Populate the array of registers beginning at regNew with the new ** row data. This array is used to check constants, create the new ** table and index records, and as the values for any new.* references ** made by triggers. ** ** If there are one or more BEFORE triggers, then do not populate the ** registers associated with columns that are (a) not modified by ** this UPDATE statement and (b) not accessed by new.* references. The ** values for registers not modified by the UPDATE must be reloaded from ** the database after the BEFORE triggers are fired anyway (as the trigger ** may have modified them). So not loading those that are not going to ** be used eliminates some redundant opcodes. */ newmask = sqlite3TriggerColmask( pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError ); for(i=0; i<pTab->nCol; i++){ if( i==pTab->iPKey ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i); }else{ j = aXRef[i]; if( j>=0 ){ sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i); }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){ /* This branch loads the value of a column that will not be changed ** into a register. This is done if there are no BEFORE triggers, or ** if there are one or more BEFORE triggers that use this value via ** a new.* reference in a trigger program. */ testcase( i==31 ); testcase( i==32 ); sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i); } } } /* Fire any BEFORE UPDATE triggers. This happens before constraints are ** verified. One could argue that this is wrong. */ if( tmask&TRIGGER_BEFORE ){ sqlite3TableAffinity(v, pTab, regNew); sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue); /* The row-trigger may have deleted the row being updated. In this ** case, jump to the next row. No updates or AFTER triggers are ** required. This behavior - what happens when the row being updated ** is deleted or renamed by a BEFORE trigger - is left undefined in the ** documentation. */ if( pPk ){ sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey); VdbeCoverage(v); }else{ sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); VdbeCoverage(v); } /* If it did not delete it, the row-trigger may still have modified ** some of the columns of the row being updated. Load the values for ** all columns not modified by the update statement into their ** registers in case this has happened. */ for(i=0; i<pTab->nCol; i++){ if( aXRef[i]<0 && i!=pTab->iPKey ){ sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i); } } } if( !isView ){ int addr1 = 0; /* Address of jump instruction */ /* Do constraint checks. */ assert( regOldRowid>0 ); sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace, aXRef); /* Do FK constraint checks. */ if( hasFK ){ sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey); } /* Delete the index entries associated with the current record. */ if( bReplace || chngKey ){ if( pPk ){ addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey); }else{ addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid); } VdbeCoverageNeverTaken(v); } sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1); /* If changing the rowid value, or if there are foreign key constraints ** to process, delete the old record. Otherwise, add a noop OP_Delete ** to invoke the pre-update hook. ** ** That (regNew==regnewRowid+1) is true is also important for the ** pre-update hook. If the caller invokes preupdate_new(), the returned ** value is copied from memory cell (regNewRowid+1+iCol), where iCol ** is the column index supplied by the user. */ assert( regNew==regNewRowid+1 ); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK sqlite3VdbeAddOp3(v, OP_Delete, iDataCur, OPFLAG_ISUPDATE | ((hasFK || chngKey) ? 0 : OPFLAG_ISNOOP), regNewRowid ); if( eOnePass==ONEPASS_MULTI ){ assert( hasFK==0 && chngKey==0 ); sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); } if( !pParse->nested ){ sqlite3VdbeAppendP4(v, pTab, P4_TABLE); } #else if( hasFK || chngKey ){ sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0); } #endif if( bReplace || chngKey ){ sqlite3VdbeJumpHere(v, addr1); } if( hasFK ){ sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey); } /* Insert the new index entries and the new record. */ sqlite3CompleteInsertion( pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0), 0, 0 ); /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just updated. */ if( hasFK ){ sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey); } } /* Increment the row counter */ if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){ sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue); /* Repeat the above with the next record to be updated, until ** all record selected by the WHERE clause have been updated. */ if( eOnePass==ONEPASS_SINGLE ){ /* Nothing to do at end-of-loop for a single-pass */ }else if( eOnePass==ONEPASS_MULTI ){ sqlite3VdbeResolveLabel(v, labelContinue); sqlite3WhereEnd(pWInfo); }else if( pPk ){ sqlite3VdbeResolveLabel(v, labelContinue); sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v); }else{ sqlite3VdbeGoto(v, labelContinue); } sqlite3VdbeResolveLabel(v, labelBreak); /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if( pParse->nested==0 && pParse->pTriggerTab==0 ){ sqlite3AutoincrementEnd(pParse); } /* ** Return the number of rows that were changed. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){ sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); } update_cleanup: sqlite3AuthContextPop(&sContext); sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */ sqlite3SrcListDelete(db, pTabList); sqlite3ExprListDelete(db, pChanges); sqlite3ExprDelete(db, pWhere); return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** they may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ #ifdef isView #undef isView #endif #ifdef pTrigger #undef pTrigger #endif #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Generate code for an UPDATE of a virtual table. ** ** There are two possible strategies - the default and the special ** "onepass" strategy. Onepass is only used if the virtual table ** implementation indicates that pWhere may match at most one row. ** ** The default strategy is to create an ephemeral table that contains ** for each row to be changed: ** ** (A) The original rowid of that row. ** (B) The revised rowid for the row. ** (C) The content of every column in the row. ** ** Then loop through the contents of this ephemeral table executing a ** VUpdate for each row. When finished, drop the ephemeral table. ** ** The "onepass" strategy does not use an ephemeral table. Instead, it ** stores the same values (A, B and C above) in a register array and ** makes a single invocation of VUpdate. */ static void updateVirtualTable( Parse *pParse, /* The parsing context */ SrcList *pSrc, /* The virtual table to be modified */ Table *pTab, /* The virtual table */ ExprList *pChanges, /* The columns to change in the UPDATE statement */ Expr *pRowid, /* Expression used to recompute the rowid */ int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ Expr *pWhere, /* WHERE clause of the UPDATE statement */ int onError /* ON CONFLICT strategy */ ){ Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */ int ephemTab; /* Table holding the result of the SELECT */ int i; /* Loop counter */ sqlite3 *db = pParse->db; /* Database connection */ const char *pVTab = (const char*)sqlite3GetVTable(db, pTab); WhereInfo *pWInfo; int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */ int regArg; /* First register in VUpdate arg array */ int regRec; /* Register in which to assemble record */ int regRowid; /* Register for ephem table rowid */ int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */ int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */ int bOnePass; /* True to use onepass strategy */ int addr; /* Address of OP_OpenEphemeral */ /* Allocate nArg registers to martial the arguments to VUpdate. Then ** create and open the ephemeral table in which the records created from ** these arguments will be temporarily stored. */ assert( v ); ephemTab = pParse->nTab++; addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg); regArg = pParse->nMem + 1; pParse->nMem += nArg; regRec = ++pParse->nMem; regRowid = ++pParse->nMem; /* Start scanning the virtual table */ pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0); if( pWInfo==0 ) return; /* Populate the argument registers. */ sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg); if( pRowid ){ sqlite3ExprCode(pParse, pRowid, regArg+1); }else{ sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1); } for(i=0; i<pTab->nCol; i++){ if( aXRef[i]>=0 ){ sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i); }else{ sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i); } } bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy); if( bOnePass ){ /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded ** above. Also, if this is a top-level parse (not a trigger), clear the ** multi-write flag so that the VM does not open a statement journal */ sqlite3VdbeChangeToNoop(v, addr); if( sqlite3IsToplevel(pParse) ){ pParse->isMultiWrite = 0; } }else{ /* Create a record from the argument register contents and insert it into ** the ephemeral table. */ sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec); sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid); sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid); } if( bOnePass==0 ){ /* End the virtual table scan */ sqlite3WhereEnd(pWInfo); /* Begin scannning through the ephemeral table. */ addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v); /* Extract arguments from the current row of the ephemeral table and ** invoke the VUpdate method. */ for(i=0; i<nArg; i++){ sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i); } } sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB); sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); sqlite3MayAbort(pParse); /* End of the ephemeral table scan. Or, if using the onepass strategy, ** jump to here if the scan visited zero rows. */ if( bOnePass==0 ){ sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr); sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); }else{ sqlite3WhereEnd(pWInfo); } } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /************** End of update.c **********************************************/ /************** Begin file vacuum.c ******************************************/ /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the VACUUM command. ** ** Most of the code in this file may be omitted by defining the ** SQLITE_OMIT_VACUUM macro. */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) /* ** Execute zSql on database db. ** ** If zSql returns rows, then each row will have exactly one ** column. (This will only happen if zSql begins with "SELECT".) ** Take each row of result and call execSql() again recursively. ** ** The execSqlF() routine does the same thing, except it accepts ** a format string as its third argument */ static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ sqlite3_stmt *pStmt; int rc; /* printf("SQL: [%s]\n", zSql); fflush(stdout); */ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0); assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 ); if( zSubSql ){ assert( zSubSql[0]!='S' ); rc = execSql(db, pzErrMsg, zSubSql); if( rc!=SQLITE_OK ) break; } } assert( rc!=SQLITE_ROW ); if( rc==SQLITE_DONE ) rc = SQLITE_OK; if( rc ){ sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); } (void)sqlite3_finalize(pStmt); return rc; } static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){ char *z; va_list ap; int rc; va_start(ap, zSql); z = sqlite3VMPrintf(db, zSql, ap); va_end(ap); if( z==0 ) return SQLITE_NOMEM; rc = execSql(db, pzErrMsg, z); sqlite3DbFree(db, z); return rc; } /* ** The VACUUM command is used to clean up the database, ** collapse free space, etc. It is modelled after the VACUUM command ** in PostgreSQL. The VACUUM command works as follows: ** ** (1) Create a new transient database file ** (2) Copy all content from the database being vacuumed into ** the new transient database file ** (3) Copy content from the transient database back into the ** original database. ** ** The transient database requires temporary disk space approximately ** equal to the size of the original database. The copy operation of ** step (3) requires additional temporary disk space approximately equal ** to the size of the original database for the rollback journal. ** Hence, temporary disk space that is approximately 2x the size of the ** original database is required. Every page of the database is written ** approximately 3 times: Once for step (2) and twice for step (3). ** Two writes per page are required in step (3) because the original ** database content must be written into the rollback journal prior to ** overwriting the database with the vacuumed content. ** ** Only 1x temporary space and only 1x writes would be required if ** the copy of step (3) were replaced by deleting the original database ** and renaming the transient database as the original. But that will ** not work if other processes are attached to the original database. ** And a power loss in between deleting the original and renaming the ** transient would cause the database file to appear to be deleted ** following reboot. */ SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){ Vdbe *v = sqlite3GetVdbe(pParse); int iDb = pNm ? sqlite3TwoPartName(pParse, pNm, pNm, &pNm) : 0; if( v && (iDb>=2 || iDb==0) ){ sqlite3VdbeAddOp1(v, OP_Vacuum, iDb); sqlite3VdbeUsesBtree(v, iDb); } return; } /* ** This routine implements the OP_Vacuum opcode of the VDBE. */ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ int rc = SQLITE_OK; /* Return code from service routines */ Btree *pMain; /* The database being vacuumed */ Btree *pTemp; /* The temporary database we vacuum into */ int saved_flags; /* Saved value of the db->flags */ int saved_nChange; /* Saved value of db->nChange */ int saved_nTotalChange; /* Saved value of db->nTotalChange */ u8 saved_mTrace; /* Saved trace settings */ Db *pDb = 0; /* Database to detach at end of vacuum */ int isMemDb; /* True if vacuuming a :memory: database */ int nRes; /* Bytes of reserved space at the end of each page */ int nDb; /* Number of attached databases */ const char *zDbMain; /* Schema name of database to vacuum */ if( !db->autoCommit ){ sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); return SQLITE_ERROR; } if( db->nVdbeActive>1 ){ sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); return SQLITE_ERROR; } /* Save the current value of the database flags so that it can be ** restored before returning. Then set the writable-schema flag, and ** disable CHECK and foreign key constraints. */ saved_flags = db->flags; saved_nChange = db->nChange; saved_nTotalChange = db->nTotalChange; saved_mTrace = db->mTrace; db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin | SQLITE_Vacuum); db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows); db->mTrace = 0; zDbMain = db->aDb[iDb].zDbSName; pMain = db->aDb[iDb].pBt; isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain)); /* Attach the temporary database as 'vacuum_db'. The synchronous pragma ** can be set to 'off' for this file, as it is not recovered if a crash ** occurs anyway. The integrity of the database is maintained by a ** (possibly synchronous) transaction opened on the main database before ** sqlite3BtreeCopyFile() is called. ** ** An optimisation would be to use a non-journaled pager. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but ** that actually made the VACUUM run slower. Very little journalling ** actually occurs when doing a vacuum since the vacuum_db is initially ** empty. Only the journal header is written. Apparently it takes more ** time to parse and run the PRAGMA to turn journalling off than it does ** to write the journal header file. */ nDb = db->nDb; rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db"); if( rc!=SQLITE_OK ) goto end_of_vacuum; assert( (db->nDb-1)==nDb ); pDb = &db->aDb[nDb]; assert( strcmp(pDb->zDbSName,"vacuum_db")==0 ); pTemp = pDb->pBt; /* The call to execSql() to attach the temp database has left the file ** locked (as there was more than one active statement when the transaction ** to read the schema was concluded. Unlock it here so that this doesn't ** cause problems for the call to BtreeSetPageSize() below. */ sqlite3BtreeCommit(pTemp); nRes = sqlite3BtreeGetOptimalReserve(pMain); /* A VACUUM cannot change the pagesize of an encrypted database. */ #ifdef SQLITE_HAS_CODEC if( db->nextPagesize ){ extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); int nKey; char *zKey; sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); if( nKey ) db->nextPagesize = 0; } #endif sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size); sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0)); sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL); /* Begin a transaction and take an exclusive lock on the main database ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below, ** to ensure that we do not try to change the page-size on a WAL database. */ rc = execSql(db, pzErrMsg, "BEGIN"); if( rc!=SQLITE_OK ) goto end_of_vacuum; rc = sqlite3BtreeBeginTrans(pMain, 2); if( rc!=SQLITE_OK ) goto end_of_vacuum; /* Do not attempt to change the page size for a WAL database */ if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain)) ==PAGER_JOURNALMODE_WAL ){ db->nextPagesize = 0; } if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0) || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0)) || NEVER(db->mallocFailed) ){ rc = SQLITE_NOMEM_BKPT; goto end_of_vacuum; } #ifndef SQLITE_OMIT_AUTOVACUUM sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : sqlite3BtreeGetAutoVacuum(pMain)); #endif /* Query the schema of the main database. Create a mirror schema ** in the temporary database. */ db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */ rc = execSqlF(db, pzErrMsg, "SELECT sql FROM \"%w\".sqlite_master" " WHERE type='table'AND name<>'sqlite_sequence'" " AND coalesce(rootpage,1)>0", zDbMain ); if( rc!=SQLITE_OK ) goto end_of_vacuum; rc = execSqlF(db, pzErrMsg, "SELECT sql FROM \"%w\".sqlite_master" " WHERE type='index' AND length(sql)>10", zDbMain ); if( rc!=SQLITE_OK ) goto end_of_vacuum; db->init.iDb = 0; /* Loop through the tables in the main database. For each, do ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy ** the contents to the temporary database. */ rc = execSqlF(db, pzErrMsg, "SELECT'INSERT INTO vacuum_db.'||quote(name)" "||' SELECT*FROM\"%w\".'||quote(name)" "FROM vacuum_db.sqlite_master " "WHERE type='table'AND coalesce(rootpage,1)>0", zDbMain ); assert( (db->flags & SQLITE_Vacuum)!=0 ); db->flags &= ~SQLITE_Vacuum; if( rc!=SQLITE_OK ) goto end_of_vacuum; /* Copy the triggers, views, and virtual tables from the main database ** over to the temporary database. None of these objects has any ** associated storage, so all we have to do is copy their entries ** from the SQLITE_MASTER table. */ rc = execSqlF(db, pzErrMsg, "INSERT INTO vacuum_db.sqlite_master" " SELECT*FROM \"%w\".sqlite_master" " WHERE type IN('view','trigger')" " OR(type='table'AND rootpage=0)", zDbMain ); if( rc ) goto end_of_vacuum; /* At this point, there is a write transaction open on both the ** vacuum database and the main database. Assuming no error occurs, ** both transactions are closed by this block - the main database ** transaction by sqlite3BtreeCopyFile() and the other by an explicit ** call to sqlite3BtreeCommit(). */ { u32 meta; int i; /* This array determines which meta meta values are preserved in the ** vacuum. Even entries are the meta value number and odd entries ** are an increment to apply to the meta value after the vacuum. ** The increment is used to increase the schema cookie so that other ** connections to the same database will know to reread the schema. */ static const unsigned char aCopy[] = { BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */ BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */ BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */ BTREE_USER_VERSION, 0, /* Preserve the user version */ BTREE_APPLICATION_ID, 0, /* Preserve the application id */ }; assert( 1==sqlite3BtreeIsInTrans(pTemp) ); assert( 1==sqlite3BtreeIsInTrans(pMain) ); /* Copy Btree meta values */ for(i=0; i<ArraySize(aCopy); i+=2){ /* GetMeta() and UpdateMeta() cannot fail in this context because ** we already have page 1 loaded into cache and marked dirty. */ sqlite3BtreeGetMeta(pMain, aCopy[i], &meta); rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]); if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum; } rc = sqlite3BtreeCopyFile(pMain, pTemp); if( rc!=SQLITE_OK ) goto end_of_vacuum; rc = sqlite3BtreeCommit(pTemp); if( rc!=SQLITE_OK ) goto end_of_vacuum; #ifndef SQLITE_OMIT_AUTOVACUUM sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp)); #endif } assert( rc==SQLITE_OK ); rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1); end_of_vacuum: /* Restore the original value of db->flags */ db->init.iDb = 0; db->flags = saved_flags; db->nChange = saved_nChange; db->nTotalChange = saved_nTotalChange; db->mTrace = saved_mTrace; sqlite3BtreeSetPageSize(pMain, -1, -1, 1); /* Currently there is an SQL level transaction open on the vacuum ** database. No locks are held on any other files (since the main file ** was committed at the btree level). So it safe to end the transaction ** by manually setting the autoCommit flag to true and detaching the ** vacuum database. The vacuum_db journal file is deleted when the pager ** is closed by the DETACH. */ db->autoCommit = 1; if( pDb ){ sqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; pDb->pSchema = 0; } /* This both clears the schemas and reduces the size of the db->aDb[] ** array. */ sqlite3ResetAllSchemasOfConnection(db); return rc; } #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */ /************** End of vacuum.c **********************************************/ /************** Begin file vtab.c ********************************************/ /* ** 2006 June 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to help implement virtual tables. */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* #include "sqliteInt.h" */ /* ** Before a virtual table xCreate() or xConnect() method is invoked, the ** sqlite3.pVtabCtx member variable is set to point to an instance of ** this struct allocated on the stack. It is used by the implementation of ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which ** are invoked only from within xCreate and xConnect methods. */ struct VtabCtx { VTable *pVTable; /* The virtual table being constructed */ Table *pTab; /* The Table object to which the virtual table belongs */ VtabCtx *pPrior; /* Parent context (if any) */ int bDeclared; /* True after sqlite3_declare_vtab() is called */ }; /* ** Construct and install a Module object for a virtual table. When this ** routine is called, it is guaranteed that all appropriate locks are held ** and the module is not already part of the connection. */ SQLITE_PRIVATE Module *sqlite3VtabCreateModule( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux, /* Context pointer for xCreate/xConnect */ void (*xDestroy)(void *) /* Module destructor function */ ){ Module *pMod; int nName = sqlite3Strlen30(zName); pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1); if( pMod ){ Module *pDel; char *zCopy = (char *)(&pMod[1]); memcpy(zCopy, zName, nName+1); pMod->zName = zCopy; pMod->pModule = pModule; pMod->pAux = pAux; pMod->xDestroy = xDestroy; pMod->pEpoTab = 0; pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod); assert( pDel==0 || pDel==pMod ); if( pDel ){ sqlite3OomFault(db); sqlite3DbFree(db, pDel); pMod = 0; } } return pMod; } /* ** The actual function that does the work of creating a new module. ** This function implements the sqlite3_create_module() and ** sqlite3_create_module_v2() interfaces. */ static int createModule( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux, /* Context pointer for xCreate/xConnect */ void (*xDestroy)(void *) /* Module destructor function */ ){ int rc = SQLITE_OK; sqlite3_mutex_enter(db->mutex); if( sqlite3HashFind(&db->aModule, zName) ){ rc = SQLITE_MISUSE_BKPT; }else{ (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy); } rc = sqlite3ApiExit(db, rc); if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux); sqlite3_mutex_leave(db->mutex); return rc; } /* ** External API function used to create a new virtual-table module. */ SQLITE_API int sqlite3_create_module( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux /* Context pointer for xCreate/xConnect */ ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif return createModule(db, zName, pModule, pAux, 0); } /* ** External API function used to create a new virtual-table module. */ SQLITE_API int sqlite3_create_module_v2( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux, /* Context pointer for xCreate/xConnect */ void (*xDestroy)(void *) /* Module destructor function */ ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif return createModule(db, zName, pModule, pAux, xDestroy); } /* ** Lock the virtual table so that it cannot be disconnected. ** Locks nest. Every lock should have a corresponding unlock. ** If an unlock is omitted, resources leaks will occur. ** ** If a disconnect is attempted while a virtual table is locked, ** the disconnect is deferred until all locks have been removed. */ SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){ pVTab->nRef++; } /* ** pTab is a pointer to a Table structure representing a virtual-table. ** Return a pointer to the VTable object used by connection db to access ** this virtual-table, if one has been created, or NULL otherwise. */ SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){ VTable *pVtab; assert( IsVirtual(pTab) ); for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext); return pVtab; } /* ** Decrement the ref-count on a virtual table object. When the ref-count ** reaches zero, call the xDisconnect() method to delete the object. */ SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){ sqlite3 *db = pVTab->db; assert( db ); assert( pVTab->nRef>0 ); assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE ); pVTab->nRef--; if( pVTab->nRef==0 ){ sqlite3_vtab *p = pVTab->pVtab; if( p ){ p->pModule->xDisconnect(p); } sqlite3DbFree(db, pVTab); } } /* ** Table p is a virtual table. This function moves all elements in the ** p->pVTable list to the sqlite3.pDisconnect lists of their associated ** database connections to be disconnected at the next opportunity. ** Except, if argument db is not NULL, then the entry associated with ** connection db is left in the p->pVTable list. */ static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){ VTable *pRet = 0; VTable *pVTable = p->pVTable; p->pVTable = 0; /* Assert that the mutex (if any) associated with the BtShared database ** that contains table p is held by the caller. See header comments ** above function sqlite3VtabUnlockList() for an explanation of why ** this makes it safe to access the sqlite3.pDisconnect list of any ** database connection that may have an entry in the p->pVTable list. */ assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); while( pVTable ){ sqlite3 *db2 = pVTable->db; VTable *pNext = pVTable->pNext; assert( db2 ); if( db2==db ){ pRet = pVTable; p->pVTable = pRet; pRet->pNext = 0; }else{ pVTable->pNext = db2->pDisconnect; db2->pDisconnect = pVTable; } pVTable = pNext; } assert( !db || pRet ); return pRet; } /* ** Table *p is a virtual table. This function removes the VTable object ** for table *p associated with database connection db from the linked ** list in p->pVTab. It also decrements the VTable ref count. This is ** used when closing database connection db to free all of its VTable ** objects without disturbing the rest of the Schema object (which may ** be being used by other shared-cache connections). */ SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){ VTable **ppVTab; assert( IsVirtual(p) ); assert( sqlite3BtreeHoldsAllMutexes(db) ); assert( sqlite3_mutex_held(db->mutex) ); for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){ if( (*ppVTab)->db==db ){ VTable *pVTab = *ppVTab; *ppVTab = pVTab->pNext; sqlite3VtabUnlock(pVTab); break; } } } /* ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list. ** ** This function may only be called when the mutexes associated with all ** shared b-tree databases opened using connection db are held by the ** caller. This is done to protect the sqlite3.pDisconnect list. The ** sqlite3.pDisconnect list is accessed only as follows: ** ** 1) By this function. In this case, all BtShared mutexes and the mutex ** associated with the database handle itself must be held. ** ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to ** the sqlite3.pDisconnect list. In this case either the BtShared mutex ** associated with the database the virtual table is stored in is held ** or, if the virtual table is stored in a non-sharable database, then ** the database handle mutex is held. ** ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously ** by multiple threads. It is thread-safe. */ SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){ VTable *p = db->pDisconnect; db->pDisconnect = 0; assert( sqlite3BtreeHoldsAllMutexes(db) ); assert( sqlite3_mutex_held(db->mutex) ); if( p ){ sqlite3ExpirePreparedStatements(db); do { VTable *pNext = p->pNext; sqlite3VtabUnlock(p); p = pNext; }while( p ); } } /* ** Clear any and all virtual-table information from the Table record. ** This routine is called, for example, just before deleting the Table ** record. ** ** Since it is a virtual-table, the Table structure contains a pointer ** to the head of a linked list of VTable structures. Each VTable ** structure is associated with a single sqlite3* user of the schema. ** The reference count of the VTable structure associated with database ** connection db is decremented immediately (which may lead to the ** structure being xDisconnected and free). Any other VTable structures ** in the list are moved to the sqlite3.pDisconnect list of the associated ** database connection. */ SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){ if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p); if( p->azModuleArg ){ int i; for(i=0; i<p->nModuleArg; i++){ if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]); } sqlite3DbFree(db, p->azModuleArg); } } /* ** Add a new module argument to pTable->azModuleArg[]. ** The string is not copied - the pointer is stored. The ** string will be freed automatically when the table is ** deleted. */ static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ int nBytes = sizeof(char *)*(2+pTable->nModuleArg); char **azModuleArg; azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); if( azModuleArg==0 ){ sqlite3DbFree(db, zArg); }else{ int i = pTable->nModuleArg++; azModuleArg[i] = zArg; azModuleArg[i+1] = 0; pTable->azModuleArg = azModuleArg; } } /* ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE ** statement. The module name has been parsed, but the optional list ** of parameters that follow the module name are still pending. */ SQLITE_PRIVATE void sqlite3VtabBeginParse( Parse *pParse, /* Parsing context */ Token *pName1, /* Name of new table, or database name */ Token *pName2, /* Name of new table or NULL */ Token *pModuleName, /* Name of the module for the virtual table */ int ifNotExists /* No error if the table already exists */ ){ int iDb; /* The database the table is being created in */ Table *pTable; /* The new virtual table */ sqlite3 *db; /* Database connection */ sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists); pTable = pParse->pNewTable; if( pTable==0 ) return; assert( 0==pTable->pIndex ); db = pParse->db; iDb = sqlite3SchemaToIndex(db, pTable->pSchema); assert( iDb>=0 ); pTable->tabFlags |= TF_Virtual; pTable->nModuleArg = 0; addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName)); addModuleArgument(db, pTable, 0); addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName)); assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0) || (pParse->sNameToken.z==pName1->z && pName2->z==0) ); pParse->sNameToken.n = (int)( &pModuleName->z[pModuleName->n] - pParse->sNameToken.z ); #ifndef SQLITE_OMIT_AUTHORIZATION /* Creating a virtual table invokes the authorization callback twice. ** The first invocation, to obtain permission to INSERT a row into the ** sqlite_master table, has already been made by sqlite3StartTable(). ** The second call, to obtain permission to create the table, is made now. */ if( pTable->azModuleArg ){ sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName); } #endif } /* ** This routine takes the module argument that has been accumulating ** in pParse->zArg[] and appends it to the list of arguments on the ** virtual table currently under construction in pParse->pTable. */ static void addArgumentToVtab(Parse *pParse){ if( pParse->sArg.z && pParse->pNewTable ){ const char *z = (const char*)pParse->sArg.z; int n = pParse->sArg.n; sqlite3 *db = pParse->db; addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); } } /* ** The parser calls this routine after the CREATE VIRTUAL TABLE statement ** has been completely parsed. */ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ Table *pTab = pParse->pNewTable; /* The table being constructed */ sqlite3 *db = pParse->db; /* The database connection */ if( pTab==0 ) return; addArgumentToVtab(pParse); pParse->sArg.z = 0; if( pTab->nModuleArg<1 ) return; /* If the CREATE VIRTUAL TABLE statement is being entered for the ** first time (in other words if the virtual table is actually being ** created now instead of just being read out of sqlite_master) then ** do additional initialization work and store the statement text ** in the sqlite_master table. */ if( !db->init.busy ){ char *zStmt; char *zWhere; int iDb; int iReg; Vdbe *v; /* Compute the complete text of the CREATE VIRTUAL TABLE statement */ if( pEnd ){ pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n; } zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken); /* A slot for the record has already been allocated in the ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. ** ** The VM register number pParse->regRowid holds the rowid of an ** entry in the sqlite_master table tht was created for this vtab ** by sqlite3StartTable(). */ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3NestedParse(pParse, "UPDATE %Q.%s " "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " "WHERE rowid=#%d", db->aDb[iDb].zDbSName, MASTER_NAME, pTab->zName, pTab->zName, zStmt, pParse->regRowid ); sqlite3DbFree(db, zStmt); v = sqlite3GetVdbe(pParse); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddOp0(v, OP_Expire); zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName); sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); iReg = ++pParse->nMem; sqlite3VdbeLoadString(v, iReg, pTab->zName); sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg); } /* If we are rereading the sqlite_master table create the in-memory ** record of the table. The xConnect() method is not called until ** the first time the virtual table is used in an SQL statement. This ** allows a schema that contains virtual tables to be loaded before ** the required virtual table implementations are registered. */ else { Table *pOld; Schema *pSchema = pTab->pSchema; const char *zName = pTab->zName; assert( sqlite3SchemaMutexHeld(db, 0, pSchema) ); pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab); if( pOld ){ sqlite3OomFault(db); assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */ return; } pParse->pNewTable = 0; } } /* ** The parser calls this routine when it sees the first token ** of an argument to the module name in a CREATE VIRTUAL TABLE statement. */ SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){ addArgumentToVtab(pParse); pParse->sArg.z = 0; pParse->sArg.n = 0; } /* ** The parser calls this routine for each token after the first token ** in an argument to the module name in a CREATE VIRTUAL TABLE statement. */ SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){ Token *pArg = &pParse->sArg; if( pArg->z==0 ){ pArg->z = p->z; pArg->n = p->n; }else{ assert(pArg->z <= p->z); pArg->n = (int)(&p->z[p->n] - pArg->z); } } /* ** Invoke a virtual table constructor (either xCreate or xConnect). The ** pointer to the function to invoke is passed as the fourth parameter ** to this procedure. */ static int vtabCallConstructor( sqlite3 *db, Table *pTab, Module *pMod, int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**), char **pzErr ){ VtabCtx sCtx; VTable *pVTable; int rc; const char *const*azArg = (const char *const*)pTab->azModuleArg; int nArg = pTab->nModuleArg; char *zErr = 0; char *zModuleName; int iDb; VtabCtx *pCtx; /* Check that the virtual-table is not already being initialized */ for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){ if( pCtx->pTab==pTab ){ *pzErr = sqlite3MPrintf(db, "vtable constructor called recursively: %s", pTab->zName ); return SQLITE_LOCKED; } } zModuleName = sqlite3MPrintf(db, "%s", pTab->zName); if( !zModuleName ){ return SQLITE_NOMEM_BKPT; } pVTable = sqlite3DbMallocZero(db, sizeof(VTable)); if( !pVTable ){ sqlite3DbFree(db, zModuleName); return SQLITE_NOMEM_BKPT; } pVTable->db = db; pVTable->pMod = pMod; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); pTab->azModuleArg[1] = db->aDb[iDb].zDbSName; /* Invoke the virtual table constructor */ assert( &db->pVtabCtx ); assert( xConstruct ); sCtx.pTab = pTab; sCtx.pVTable = pVTable; sCtx.pPrior = db->pVtabCtx; sCtx.bDeclared = 0; db->pVtabCtx = &sCtx; rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr); db->pVtabCtx = sCtx.pPrior; if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); assert( sCtx.pTab==pTab ); if( SQLITE_OK!=rc ){ if( zErr==0 ){ *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName); }else { *pzErr = sqlite3MPrintf(db, "%s", zErr); sqlite3_free(zErr); } sqlite3DbFree(db, pVTable); }else if( ALWAYS(pVTable->pVtab) ){ /* Justification of ALWAYS(): A correct vtab constructor must allocate ** the sqlite3_vtab object if successful. */ memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0])); pVTable->pVtab->pModule = pMod->pModule; pVTable->nRef = 1; if( sCtx.bDeclared==0 ){ const char *zFormat = "vtable constructor did not declare schema: %s"; *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName); sqlite3VtabUnlock(pVTable); rc = SQLITE_ERROR; }else{ int iCol; u8 oooHidden = 0; /* If everything went according to plan, link the new VTable structure ** into the linked list headed by pTab->pVTable. Then loop through the ** columns of the table to see if any of them contain the token "hidden". ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from ** the type string. */ pVTable->pNext = pTab->pVTable; pTab->pVTable = pVTable; for(iCol=0; iCol<pTab->nCol; iCol++){ char *zType = sqlite3ColumnType(&pTab->aCol[iCol], ""); int nType; int i = 0; nType = sqlite3Strlen30(zType); for(i=0; i<nType; i++){ if( 0==sqlite3StrNICmp("hidden", &zType[i], 6) && (i==0 || zType[i-1]==' ') && (zType[i+6]=='\0' || zType[i+6]==' ') ){ break; } } if( i<nType ){ int j; int nDel = 6 + (zType[i+6] ? 1 : 0); for(j=i; (j+nDel)<=nType; j++){ zType[j] = zType[j+nDel]; } if( zType[i]=='\0' && i>0 ){ assert(zType[i-1]==' '); zType[i-1] = '\0'; } pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN; oooHidden = TF_OOOHidden; }else{ pTab->tabFlags |= oooHidden; } } } } sqlite3DbFree(db, zModuleName); return rc; } /* ** This function is invoked by the parser to call the xConnect() method ** of the virtual table pTab. If an error occurs, an error code is returned ** and an error left in pParse. ** ** This call is a no-op if table pTab is not a virtual table. */ SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){ sqlite3 *db = pParse->db; const char *zMod; Module *pMod; int rc; assert( pTab ); if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){ return SQLITE_OK; } /* Locate the required virtual table module */ zMod = pTab->azModuleArg[0]; pMod = (Module*)sqlite3HashFind(&db->aModule, zMod); if( !pMod ){ const char *zModule = pTab->azModuleArg[0]; sqlite3ErrorMsg(pParse, "no such module: %s", zModule); rc = SQLITE_ERROR; }else{ char *zErr = 0; rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr); if( rc!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, "%s", zErr); } sqlite3DbFree(db, zErr); } return rc; } /* ** Grow the db->aVTrans[] array so that there is room for at least one ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise. */ static int growVTrans(sqlite3 *db){ const int ARRAY_INCR = 5; /* Grow the sqlite3.aVTrans array if required */ if( (db->nVTrans%ARRAY_INCR)==0 ){ VTable **aVTrans; int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR); aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes); if( !aVTrans ){ return SQLITE_NOMEM_BKPT; } memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR); db->aVTrans = aVTrans; } return SQLITE_OK; } /* ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should ** have already been reserved using growVTrans(). */ static void addToVTrans(sqlite3 *db, VTable *pVTab){ /* Add pVtab to the end of sqlite3.aVTrans */ db->aVTrans[db->nVTrans++] = pVTab; sqlite3VtabLock(pVTab); } /* ** This function is invoked by the vdbe to call the xCreate method ** of the virtual table named zTab in database iDb. ** ** If an error occurs, *pzErr is set to point to an English language ** description of the error and an SQLITE_XXX error code is returned. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr. */ SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){ int rc = SQLITE_OK; Table *pTab; Module *pMod; const char *zMod; pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable ); /* Locate the required virtual table module */ zMod = pTab->azModuleArg[0]; pMod = (Module*)sqlite3HashFind(&db->aModule, zMod); /* If the module has been registered and includes a Create method, ** invoke it now. If the module has not been registered, return an ** error. Otherwise, do nothing. */ if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){ *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod); rc = SQLITE_ERROR; }else{ rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr); } /* Justification of ALWAYS(): The xConstructor method is required to ** create a valid sqlite3_vtab if it returns SQLITE_OK. */ if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){ rc = growVTrans(db); if( rc==SQLITE_OK ){ addToVTrans(db, sqlite3GetVTable(db, pTab)); } } return rc; } /* ** This function is used to set the schema of a virtual table. It is only ** valid to call this function from within the xCreate() or xConnect() of a ** virtual table module. */ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){ VtabCtx *pCtx; Parse *pParse; int rc = SQLITE_OK; Table *pTab; char *zErr = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); pCtx = db->pVtabCtx; if( !pCtx || pCtx->bDeclared ){ sqlite3Error(db, SQLITE_MISUSE); sqlite3_mutex_leave(db->mutex); return SQLITE_MISUSE_BKPT; } pTab = pCtx->pTab; assert( (pTab->tabFlags & TF_Virtual)!=0 ); pParse = sqlite3StackAllocZero(db, sizeof(*pParse)); if( pParse==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ pParse->declareVtab = 1; pParse->db = db; pParse->nQueryLoop = 1; if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) && pParse->pNewTable && !db->mallocFailed && !pParse->pNewTable->pSelect && (pParse->pNewTable->tabFlags & TF_Virtual)==0 ){ if( !pTab->aCol ){ Table *pNew = pParse->pNewTable; Index *pIdx; pTab->aCol = pNew->aCol; pTab->nCol = pNew->nCol; pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid); pNew->nCol = 0; pNew->aCol = 0; assert( pTab->pIndex==0 ); if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){ rc = SQLITE_ERROR; } pIdx = pNew->pIndex; if( pIdx ){ assert( pIdx->pNext==0 ); pTab->pIndex = pIdx; pNew->pIndex = 0; pIdx->pTable = pTab; } } pCtx->bDeclared = 1; }else{ sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr); sqlite3DbFree(db, zErr); rc = SQLITE_ERROR; } pParse->declareVtab = 0; if( pParse->pVdbe ){ sqlite3VdbeFinalize(pParse->pVdbe); } sqlite3DeleteTable(db, pParse->pNewTable); sqlite3ParserReset(pParse); sqlite3StackFree(db, pParse); } assert( (rc&0xff)==rc ); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** This function is invoked by the vdbe to call the xDestroy method ** of the virtual table named zTab in database iDb. This occurs ** when a DROP TABLE is mentioned. ** ** This call is a no-op if zTab is not a virtual table. */ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){ int rc = SQLITE_OK; Table *pTab; pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){ VTable *p; int (*xDestroy)(sqlite3_vtab *); for(p=pTab->pVTable; p; p=p->pNext){ assert( p->pVtab ); if( p->pVtab->nRef>0 ){ return SQLITE_LOCKED; } } p = vtabDisconnectAll(db, pTab); xDestroy = p->pMod->pModule->xDestroy; assert( xDestroy!=0 ); /* Checked before the virtual table is created */ rc = xDestroy(p->pVtab); /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */ if( rc==SQLITE_OK ){ assert( pTab->pVTable==p && p->pNext==0 ); p->pVtab = 0; pTab->pVTable = 0; sqlite3VtabUnlock(p); } } return rc; } /* ** This function invokes either the xRollback or xCommit method ** of each of the virtual tables in the sqlite3.aVTrans array. The method ** called is identified by the second argument, "offset", which is ** the offset of the method to call in the sqlite3_module structure. ** ** The array is cleared after invoking the callbacks. */ static void callFinaliser(sqlite3 *db, int offset){ int i; if( db->aVTrans ){ VTable **aVTrans = db->aVTrans; db->aVTrans = 0; for(i=0; i<db->nVTrans; i++){ VTable *pVTab = aVTrans[i]; sqlite3_vtab *p = pVTab->pVtab; if( p ){ int (*x)(sqlite3_vtab *); x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset); if( x ) x(p); } pVTab->iSavepoint = 0; sqlite3VtabUnlock(pVTab); } sqlite3DbFree(db, aVTrans); db->nVTrans = 0; } } /* ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans ** array. Return the error code for the first error that occurs, or ** SQLITE_OK if all xSync operations are successful. ** ** If an error message is available, leave it in p->zErrMsg. */ SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){ int i; int rc = SQLITE_OK; VTable **aVTrans = db->aVTrans; db->aVTrans = 0; for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){ int (*x)(sqlite3_vtab *); sqlite3_vtab *pVtab = aVTrans[i]->pVtab; if( pVtab && (x = pVtab->pModule->xSync)!=0 ){ rc = x(pVtab); sqlite3VtabImportErrmsg(p, pVtab); } } db->aVTrans = aVTrans; return rc; } /* ** Invoke the xRollback method of all virtual tables in the ** sqlite3.aVTrans array. Then clear the array itself. */ SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){ callFinaliser(db, offsetof(sqlite3_module,xRollback)); return SQLITE_OK; } /* ** Invoke the xCommit method of all virtual tables in the ** sqlite3.aVTrans array. Then clear the array itself. */ SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){ callFinaliser(db, offsetof(sqlite3_module,xCommit)); return SQLITE_OK; } /* ** If the virtual table pVtab supports the transaction interface ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is ** not currently open, invoke the xBegin method now. ** ** If the xBegin call is successful, place the sqlite3_vtab pointer ** in the sqlite3.aVTrans array. */ SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){ int rc = SQLITE_OK; const sqlite3_module *pModule; /* Special case: If db->aVTrans is NULL and db->nVTrans is greater ** than zero, then this function is being called from within a ** virtual module xSync() callback. It is illegal to write to ** virtual module tables in this case, so return SQLITE_LOCKED. */ if( sqlite3VtabInSync(db) ){ return SQLITE_LOCKED; } if( !pVTab ){ return SQLITE_OK; } pModule = pVTab->pVtab->pModule; if( pModule->xBegin ){ int i; /* If pVtab is already in the aVTrans array, return early */ for(i=0; i<db->nVTrans; i++){ if( db->aVTrans[i]==pVTab ){ return SQLITE_OK; } } /* Invoke the xBegin method. If successful, add the vtab to the ** sqlite3.aVTrans[] array. */ rc = growVTrans(db); if( rc==SQLITE_OK ){ rc = pModule->xBegin(pVTab->pVtab); if( rc==SQLITE_OK ){ int iSvpt = db->nStatement + db->nSavepoint; addToVTrans(db, pVTab); if( iSvpt && pModule->xSavepoint ){ pVTab->iSavepoint = iSvpt; rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1); } } } } return rc; } /* ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all ** virtual tables that currently have an open transaction. Pass iSavepoint ** as the second argument to the virtual table method invoked. ** ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with ** an open transaction is invoked. ** ** If any virtual table method returns an error code other than SQLITE_OK, ** processing is abandoned and the error returned to the caller of this ** function immediately. If all calls to virtual table methods are successful, ** SQLITE_OK is returned. */ SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ int rc = SQLITE_OK; assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN ); assert( iSavepoint>=-1 ); if( db->aVTrans ){ int i; for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){ VTable *pVTab = db->aVTrans[i]; const sqlite3_module *pMod = pVTab->pMod->pModule; if( pVTab->pVtab && pMod->iVersion>=2 ){ int (*xMethod)(sqlite3_vtab *, int); switch( op ){ case SAVEPOINT_BEGIN: xMethod = pMod->xSavepoint; pVTab->iSavepoint = iSavepoint+1; break; case SAVEPOINT_ROLLBACK: xMethod = pMod->xRollbackTo; break; default: xMethod = pMod->xRelease; break; } if( xMethod && pVTab->iSavepoint>iSavepoint ){ rc = xMethod(pVTab->pVtab, iSavepoint); } } } } return rc; } /* ** The first parameter (pDef) is a function implementation. The ** second parameter (pExpr) is the first argument to this function. ** If pExpr is a column in a virtual table, then let the virtual ** table implementation have an opportunity to overload the function. ** ** This routine is used to allow virtual table implementations to ** overload MATCH, LIKE, GLOB, and REGEXP operators. ** ** Return either the pDef argument (indicating no change) or a ** new FuncDef structure that is marked as ephemeral using the ** SQLITE_FUNC_EPHEM flag. */ SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction( sqlite3 *db, /* Database connection for reporting malloc problems */ FuncDef *pDef, /* Function to possibly overload */ int nArg, /* Number of arguments to the function */ Expr *pExpr /* First argument to the function */ ){ Table *pTab; sqlite3_vtab *pVtab; sqlite3_module *pMod; void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0; void *pArg = 0; FuncDef *pNew; int rc = 0; char *zLowerName; unsigned char *z; /* Check to see the left operand is a column in a virtual table */ if( NEVER(pExpr==0) ) return pDef; if( pExpr->op!=TK_COLUMN ) return pDef; pTab = pExpr->pTab; if( NEVER(pTab==0) ) return pDef; if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef; pVtab = sqlite3GetVTable(db, pTab)->pVtab; assert( pVtab!=0 ); assert( pVtab->pModule!=0 ); pMod = (sqlite3_module *)pVtab->pModule; if( pMod->xFindFunction==0 ) return pDef; /* Call the xFindFunction method on the virtual table implementation ** to see if the implementation wants to overload this function */ zLowerName = sqlite3DbStrDup(db, pDef->zName); if( zLowerName ){ for(z=(unsigned char*)zLowerName; *z; z++){ *z = sqlite3UpperToLower[*z]; } rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg); sqlite3DbFree(db, zLowerName); } if( rc==0 ){ return pDef; } /* Create a new ephemeral function definition for the overloaded ** function */ pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + sqlite3Strlen30(pDef->zName) + 1); if( pNew==0 ){ return pDef; } *pNew = *pDef; pNew->zName = (const char*)&pNew[1]; memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1); pNew->xSFunc = xSFunc; pNew->pUserData = pArg; pNew->funcFlags |= SQLITE_FUNC_EPHEM; return pNew; } /* ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[] ** array so that an OP_VBegin will get generated for it. Add pTab to the ** array if it is missing. If pTab is already in the array, this routine ** is a no-op. */ SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ Parse *pToplevel = sqlite3ParseToplevel(pParse); int i, n; Table **apVtabLock; assert( IsVirtual(pTab) ); for(i=0; i<pToplevel->nVtabLock; i++){ if( pTab==pToplevel->apVtabLock[i] ) return; } n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]); apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n); if( apVtabLock ){ pToplevel->apVtabLock = apVtabLock; pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab; }else{ sqlite3OomFault(pToplevel->db); } } /* ** Check to see if virtual table module pMod can be have an eponymous ** virtual table instance. If it can, create one if one does not already ** exist. Return non-zero if the eponymous virtual table instance exists ** when this routine returns, and return zero if it does not exist. ** ** An eponymous virtual table instance is one that is named after its ** module, and more importantly, does not require a CREATE VIRTUAL TABLE ** statement in order to come into existance. Eponymous virtual table ** instances always exist. They cannot be DROP-ed. ** ** Any virtual table module for which xConnect and xCreate are the same ** method can have an eponymous virtual table instance. */ SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){ const sqlite3_module *pModule = pMod->pModule; Table *pTab; char *zErr = 0; int rc; sqlite3 *db = pParse->db; if( pMod->pEpoTab ) return 1; if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0; pTab = sqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return 0; pTab->zName = sqlite3DbStrDup(db, pMod->zName); if( pTab->zName==0 ){ sqlite3DbFree(db, pTab); return 0; } pMod->pEpoTab = pTab; pTab->nTabRef = 1; pTab->pSchema = db->aDb[0].pSchema; pTab->tabFlags |= TF_Virtual; pTab->nModuleArg = 0; pTab->iPKey = -1; addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName)); addModuleArgument(db, pTab, 0); addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName)); rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr); if( rc ){ sqlite3ErrorMsg(pParse, "%s", zErr); sqlite3DbFree(db, zErr); sqlite3VtabEponymousTableClear(db, pMod); return 0; } return 1; } /* ** Erase the eponymous virtual table instance associated with ** virtual table module pMod, if it exists. */ SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){ Table *pTab = pMod->pEpoTab; if( pTab!=0 ){ /* Mark the table as Ephemeral prior to deleting it, so that the ** sqlite3DeleteTable() routine will know that it is not stored in ** the schema. */ pTab->tabFlags |= TF_Ephemeral; sqlite3DeleteTable(db, pTab); pMod->pEpoTab = 0; } } /* ** Return the ON CONFLICT resolution mode in effect for the virtual ** table update operation currently in progress. ** ** The results of this routine are undefined unless it is called from ** within an xUpdate method. */ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){ static const unsigned char aMap[] = { SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE }; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 ); assert( OE_Ignore==4 && OE_Replace==5 ); assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 ); return (int)aMap[db->vtabOnConflict-1]; } /* ** Call from within the xCreate() or xConnect() methods to provide ** the SQLite core with additional information about the behavior ** of the virtual table being implemented. */ SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){ va_list ap; int rc = SQLITE_OK; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); va_start(ap, op); switch( op ){ case SQLITE_VTAB_CONSTRAINT_SUPPORT: { VtabCtx *p = db->pVtabCtx; if( !p ){ rc = SQLITE_MISUSE_BKPT; }else{ assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 ); p->pVTable->bConstraint = (u8)va_arg(ap, int); } break; } default: rc = SQLITE_MISUSE_BKPT; break; } va_end(ap); if( rc!=SQLITE_OK ) sqlite3Error(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /************** End of vtab.c ************************************************/ /************** Begin file wherecode.c ***************************************/ /* ** 2015-06-06 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This module contains C code that generates VDBE code used to process ** the WHERE clause of SQL statements. ** ** This file was split off from where.c on 2015-06-06 in order to reduce the ** size of where.c and make it easier to edit. This file contains the routines ** that actually generate the bulk of the WHERE loop code. The original where.c ** file retains the code that does query planning and analysis. */ /* #include "sqliteInt.h" */ /************** Include whereInt.h in the middle of wherecode.c **************/ /************** Begin file whereInt.h ****************************************/ /* ** 2013-11-12 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains structure and macro definitions for the query ** planner logic in "where.c". These definitions are broken out into ** a separate source file for easier editing. */ /* ** Trace output macros */ #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) /***/ int sqlite3WhereTrace; #endif #if defined(SQLITE_DEBUG) \ && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE)) # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X # define WHERETRACE_ENABLED 1 #else # define WHERETRACE(K,X) #endif /* Forward references */ typedef struct WhereClause WhereClause; typedef struct WhereMaskSet WhereMaskSet; typedef struct WhereOrInfo WhereOrInfo; typedef struct WhereAndInfo WhereAndInfo; typedef struct WhereLevel WhereLevel; typedef struct WhereLoop WhereLoop; typedef struct WherePath WherePath; typedef struct WhereTerm WhereTerm; typedef struct WhereLoopBuilder WhereLoopBuilder; typedef struct WhereScan WhereScan; typedef struct WhereOrCost WhereOrCost; typedef struct WhereOrSet WhereOrSet; /* ** This object contains information needed to implement a single nested ** loop in WHERE clause. ** ** Contrast this object with WhereLoop. This object describes the ** implementation of the loop. WhereLoop describes the algorithm. ** This object contains a pointer to the WhereLoop algorithm as one of ** its elements. ** ** The WhereInfo object contains a single instance of this object for ** each term in the FROM clause (which is to say, for each of the ** nested loops as implemented). The order of WhereLevel objects determines ** the loop nested order, with WhereInfo.a[0] being the outer loop and ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop. */ struct WhereLevel { int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */ int iTabCur; /* The VDBE cursor used to access the table */ int iIdxCur; /* The VDBE cursor used to access pIdx */ int addrBrk; /* Jump here to break out of the loop */ int addrNxt; /* Jump here to start the next IN combination */ int addrSkip; /* Jump here for next iteration of skip-scan */ int addrCont; /* Jump here to continue with the next loop cycle */ int addrFirst; /* First instruction of interior of the loop */ int addrBody; /* Beginning of the body of this loop */ #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */ int addrLikeRep; /* LIKE range processing address */ #endif u8 iFrom; /* Which entry in the FROM clause */ u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */ int p1, p2; /* Operands of the opcode used to ends the loop */ union { /* Information that depends on pWLoop->wsFlags */ struct { int nIn; /* Number of entries in aInLoop[] */ struct InLoop { int iCur; /* The VDBE cursor used by this IN operator */ int addrInTop; /* Top of the IN loop */ u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */ } *aInLoop; /* Information about each nested IN operator */ } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */ Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */ } u; struct WhereLoop *pWLoop; /* The selected WhereLoop object */ Bitmask notReady; /* FROM entries not usable at this level */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS int addrVisit; /* Address at which row is visited */ #endif }; /* ** Each instance of this object represents an algorithm for evaluating one ** term of a join. Every term of the FROM clause will have at least ** one corresponding WhereLoop object (unless INDEXED BY constraints ** prevent a query solution - which is an error) and many terms of the ** FROM clause will have multiple WhereLoop objects, each describing a ** potential way of implementing that FROM-clause term, together with ** dependencies and cost estimates for using the chosen algorithm. ** ** Query planning consists of building up a collection of these WhereLoop ** objects, then computing a particular sequence of WhereLoop objects, with ** one WhereLoop object per FROM clause term, that satisfy all dependencies ** and that minimize the overall cost. */ struct WhereLoop { Bitmask prereq; /* Bitmask of other loops that must run first */ Bitmask maskSelf; /* Bitmask identifying table iTab */ #ifdef SQLITE_DEBUG char cId; /* Symbolic ID of this loop for debugging use */ #endif u8 iTab; /* Position in FROM clause of table for this loop */ u8 iSortIdx; /* Sorting index number. 0==None */ LogEst rSetup; /* One-time setup cost (ex: create transient index) */ LogEst rRun; /* Cost of running each loop */ LogEst nOut; /* Estimated number of output rows */ union { struct { /* Information for internal btree tables */ u16 nEq; /* Number of equality constraints */ u16 nBtm; /* Size of BTM vector */ u16 nTop; /* Size of TOP vector */ Index *pIndex; /* Index used, or NULL */ } btree; struct { /* Information for virtual tables */ int idxNum; /* Index number */ u8 needFree; /* True if sqlite3_free(idxStr) is needed */ i8 isOrdered; /* True if satisfies ORDER BY */ u16 omitMask; /* Terms that may be omitted */ char *idxStr; /* Index identifier string */ } vtab; } u; u32 wsFlags; /* WHERE_* flags describing the plan */ u16 nLTerm; /* Number of entries in aLTerm[] */ u16 nSkip; /* Number of NULL aLTerm[] entries */ /**** whereLoopXfer() copies fields above ***********************/ # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot) u16 nLSlot; /* Number of slots allocated for aLTerm[] */ WhereTerm **aLTerm; /* WhereTerms used */ WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */ WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */ }; /* This object holds the prerequisites and the cost of running a ** subquery on one operand of an OR operator in the WHERE clause. ** See WhereOrSet for additional information */ struct WhereOrCost { Bitmask prereq; /* Prerequisites */ LogEst rRun; /* Cost of running this subquery */ LogEst nOut; /* Number of outputs for this subquery */ }; /* The WhereOrSet object holds a set of possible WhereOrCosts that ** correspond to the subquery(s) of OR-clause processing. Only the ** best N_OR_COST elements are retained. */ #define N_OR_COST 3 struct WhereOrSet { u16 n; /* Number of valid a[] entries */ WhereOrCost a[N_OR_COST]; /* Set of best costs */ }; /* ** Each instance of this object holds a sequence of WhereLoop objects ** that implement some or all of a query plan. ** ** Think of each WhereLoop object as a node in a graph with arcs ** showing dependencies and costs for travelling between nodes. (That is ** not a completely accurate description because WhereLoop costs are a ** vector, not a scalar, and because dependencies are many-to-one, not ** one-to-one as are graph nodes. But it is a useful visualization aid.) ** Then a WherePath object is a path through the graph that visits some ** or all of the WhereLoop objects once. ** ** The "solver" works by creating the N best WherePath objects of length ** 1. Then using those as a basis to compute the N best WherePath objects ** of length 2. And so forth until the length of WherePaths equals the ** number of nodes in the FROM clause. The best (lowest cost) WherePath ** at the end is the chosen query plan. */ struct WherePath { Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */ Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */ LogEst nRow; /* Estimated number of rows generated by this path */ LogEst rCost; /* Total cost of this path */ LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */ i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */ WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */ }; /* ** The query generator uses an array of instances of this structure to ** help it analyze the subexpressions of the WHERE clause. Each WHERE ** clause subexpression is separated from the others by AND operators, ** usually, or sometimes subexpressions separated by OR. ** ** All WhereTerms are collected into a single WhereClause structure. ** The following identity holds: ** ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm ** ** When a term is of the form: ** ** X <op> <expr> ** ** where X is a column name and <op> is one of certain operators, ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the ** cursor number and column number for X. WhereTerm.eOperator records ** the <op> using a bitmask encoding defined by WO_xxx below. The ** use of a bitmask encoding for the operator allows us to search ** quickly for terms that match any of several different operators. ** ** A WhereTerm might also be two or more subterms connected by OR: ** ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR .... ** ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR ** and the WhereTerm.u.pOrInfo field points to auxiliary information that ** is collected about the OR clause. ** ** If a term in the WHERE clause does not match either of the two previous ** categories, then eOperator==0. The WhereTerm.pExpr field is still set ** to the original subexpression content and wtFlags is set up appropriately ** but no other fields in the WhereTerm object are meaningful. ** ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers, ** but they do so indirectly. A single WhereMaskSet structure translates ** cursor number into bits and the translated bit is stored in the prereq ** fields. The translation is used in order to maximize the number of ** bits that will fit in a Bitmask. The VDBE cursor numbers might be ** spread out over the non-negative integers. For example, the cursor ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet ** translates these sparse cursor numbers into consecutive integers ** beginning with 0 in order to make the best possible use of the available ** bits in the Bitmask. So, in the example above, the cursor numbers ** would be mapped into integers 0 through 7. ** ** The number of terms in a join is limited by the number of bits ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite ** is only able to process joins with 64 or fewer tables. */ struct WhereTerm { Expr *pExpr; /* Pointer to the subexpression that is this term */ WhereClause *pWC; /* The clause this term is part of */ LogEst truthProb; /* Probability of truth for this expression */ u16 wtFlags; /* TERM_xxx bit flags. See below */ u16 eOperator; /* A WO_xx value describing <op> */ u8 nChild; /* Number of children that must disable us */ u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */ int iParent; /* Disable pWC->a[iParent] when this term disabled */ int leftCursor; /* Cursor number of X in "X <op> <expr>" */ int iField; /* Field in (?,?,?) IN (SELECT...) vector */ union { int leftColumn; /* Column number of X in "X <op> <expr>" */ WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */ WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */ } u; Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */ Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */ }; /* ** Allowed values of WhereTerm.wtFlags */ #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */ #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */ #define TERM_CODED 0x04 /* This term is already coded */ #define TERM_COPIED 0x08 /* Has a child */ #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */ #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */ #define TERM_OR_OK 0x40 /* Used during OR-clause processing */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */ #else # define TERM_VNULL 0x00 /* Disabled if not using stat3 */ #endif #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */ #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */ #define TERM_LIKE 0x400 /* The original LIKE operator */ #define TERM_IS 0x800 /* Term.pExpr is an IS operator */ /* ** An instance of the WhereScan object is used as an iterator for locating ** terms in the WHERE clause that are useful to the query planner. */ struct WhereScan { WhereClause *pOrigWC; /* Original, innermost WhereClause */ WhereClause *pWC; /* WhereClause currently being scanned */ const char *zCollName; /* Required collating sequence, if not NULL */ Expr *pIdxExpr; /* Search for this index expression */ char idxaff; /* Must match this affinity, if zCollName!=NULL */ unsigned char nEquiv; /* Number of entries in aEquiv[] */ unsigned char iEquiv; /* Next unused slot in aEquiv[] */ u32 opMask; /* Acceptable operators */ int k; /* Resume scanning at this->pWC->a[this->k] */ int aiCur[11]; /* Cursors in the equivalence class */ i16 aiColumn[11]; /* Corresponding column number in the eq-class */ }; /* ** An instance of the following structure holds all information about a ** WHERE clause. Mostly this is a container for one or more WhereTerms. ** ** Explanation of pOuter: For a WHERE clause of the form ** ** a AND ((b AND c) OR (d AND e)) AND f ** ** There are separate WhereClause objects for the whole clause and for ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the ** subclauses points to the WhereClause object for the whole clause. */ struct WhereClause { WhereInfo *pWInfo; /* WHERE clause processing context */ WhereClause *pOuter; /* Outer conjunction */ u8 op; /* Split operator. TK_AND or TK_OR */ int nTerm; /* Number of terms */ int nSlot; /* Number of entries in a[] */ WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */ #if defined(SQLITE_SMALL_STACK) WhereTerm aStatic[1]; /* Initial static space for a[] */ #else WhereTerm aStatic[8]; /* Initial static space for a[] */ #endif }; /* ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to ** a dynamically allocated instance of the following structure. */ struct WhereOrInfo { WhereClause wc; /* Decomposition into subterms */ Bitmask indexable; /* Bitmask of all indexable tables in the clause */ }; /* ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to ** a dynamically allocated instance of the following structure. */ struct WhereAndInfo { WhereClause wc; /* The subexpression broken out */ }; /* ** An instance of the following structure keeps track of a mapping ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm. ** ** The VDBE cursor numbers are small integers contained in ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE ** clause, the cursor numbers might not begin with 0 and they might ** contain gaps in the numbering sequence. But we want to make maximum ** use of the bits in our bitmasks. This structure provides a mapping ** from the sparse cursor numbers into consecutive integers beginning ** with 0. ** ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A. ** ** For example, if the WHERE clause expression used these VDBE ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure ** would map those cursor numbers into bits 0 through 5. ** ** Note that the mapping is not necessarily ordered. In the example ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0, ** 57->5, 73->4. Or one of 719 other combinations might be used. It ** does not really matter. What is important is that sparse cursor ** numbers all get mapped into bit numbers that begin with 0 and contain ** no gaps. */ struct WhereMaskSet { int n; /* Number of assigned cursor values */ int ix[BMS]; /* Cursor assigned to each bit */ }; /* ** Initialize a WhereMaskSet object */ #define initMaskSet(P) (P)->n=0 /* ** This object is a convenience wrapper holding all information needed ** to construct WhereLoop objects for a particular query. */ struct WhereLoopBuilder { WhereInfo *pWInfo; /* Information about this WHERE */ WhereClause *pWC; /* WHERE clause terms */ ExprList *pOrderBy; /* ORDER BY clause */ WhereLoop *pNew; /* Template WhereLoop */ WhereOrSet *pOrSet; /* Record best loops here, if not NULL */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 UnpackedRecord *pRec; /* Probe for stat4 (if required) */ int nRecValid; /* Number of valid fields currently in pRec */ #endif }; /* ** The WHERE clause processing routine has two halves. The ** first part does the start of the WHERE loop and the second ** half does the tail of the WHERE loop. An instance of ** this structure is returned by the first half and passed ** into the second half to give some continuity. ** ** An instance of this object holds the complete state of the query ** planner. */ struct WhereInfo { Parse *pParse; /* Parsing and code generating context */ SrcList *pTabList; /* List of tables in the join */ ExprList *pOrderBy; /* The ORDER BY clause or NULL */ ExprList *pDistinctSet; /* DISTINCT over all these values */ LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */ int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */ int iContinue; /* Jump here to continue with next record */ int iBreak; /* Jump here to break out of the loop */ int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */ u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */ u8 nLevel; /* Number of nested loop */ i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */ u8 sorted; /* True if really sorted (not just grouped) */ u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */ u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */ u8 eDistinct; /* One of the WHERE_DISTINCT_* values */ u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */ int iTop; /* The very beginning of the WHERE loop */ WhereLoop *pLoops; /* List of all WhereLoop objects */ Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ LogEst nRowOut; /* Estimated number of output rows */ WhereClause sWC; /* Decomposition of the WHERE clause */ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ WhereLevel a[1]; /* Information about each nest loop in WHERE */ }; /* ** Private interfaces - callable only by other where.c routines. ** ** where.c: */ SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int); #ifdef WHERETRACE_ENABLED SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC); #endif SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( WhereClause *pWC, /* The WHERE clause to be searched */ int iCur, /* Cursor number of LHS */ int iColumn, /* Column number of LHS */ Bitmask notReady, /* RHS must not overlap with this mask */ u32 op, /* Mask of WO_xx values describing operator */ Index *pIdx /* Must be compatible with this index, if not NULL */ ); /* wherecode.c: */ #ifndef SQLITE_OMIT_EXPLAIN SQLITE_PRIVATE int sqlite3WhereExplainOneScan( Parse *pParse, /* Parse context */ SrcList *pTabList, /* Table list this loop refers to */ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ int iLevel, /* Value for "level" column of output */ int iFrom, /* Value for "from" column of output */ u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ ); #else # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0 #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS SQLITE_PRIVATE void sqlite3WhereAddScanStatus( Vdbe *v, /* Vdbe to add scanstatus entry to */ SrcList *pSrclist, /* FROM clause pLvl reads data from */ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ int addrExplain /* Address of OP_Explain (or 0) */ ); #else # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d) #endif SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( WhereInfo *pWInfo, /* Complete information about the WHERE clause */ int iLevel, /* Which level of pWInfo->a[] should be coded */ Bitmask notReady /* Which tables are currently available */ ); /* whereexpr.c: */ SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*); SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*); SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8); SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*); SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*); SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*); SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*); /* ** Bitmasks for the operators on WhereTerm objects. These are all ** operators that are of interest to the query planner. An ** OR-ed combination of these values can be used when searching for ** particular WhereTerms within a WhereClause. ** ** Value constraints: ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE ** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH */ #define WO_IN 0x0001 #define WO_EQ 0x0002 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ)) #define WO_LE (WO_EQ<<(TK_LE-TK_EQ)) #define WO_GT (WO_EQ<<(TK_GT-TK_EQ)) #define WO_GE (WO_EQ<<(TK_GE-TK_EQ)) #define WO_MATCH 0x0040 #define WO_IS 0x0080 #define WO_ISNULL 0x0100 #define WO_OR 0x0200 /* Two or more OR-connected terms */ #define WO_AND 0x0400 /* Two or more AND-connected terms */ #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */ #define WO_NOOP 0x1000 /* This term does not restrict search space */ #define WO_ALL 0x1fff /* Mask of all possible WO_* values */ #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */ /* ** These are definitions of bits in the WhereLoop.wsFlags field. ** The particular combination of bits in each WhereLoop help to ** determine the algorithm that WhereLoop represents. */ #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */ #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */ #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */ #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */ #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */ #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */ #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */ #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */ #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */ #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */ #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */ #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */ #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */ #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */ #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */ #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */ #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */ #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/ #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */ /************** End of whereInt.h ********************************************/ /************** Continuing where we left off in wherecode.c ******************/ #ifndef SQLITE_OMIT_EXPLAIN /* ** Return the name of the i-th column of the pIdx index. */ static const char *explainIndexColumnName(Index *pIdx, int i){ i = pIdx->aiColumn[i]; if( i==XN_EXPR ) return "<expr>"; if( i==XN_ROWID ) return "rowid"; return pIdx->pTable->aCol[i].zName; } /* ** This routine is a helper for explainIndexRange() below ** ** pStr holds the text of an expression that we are building up one term ** at a time. This routine adds a new term to the end of the expression. ** Terms are separated by AND so add the "AND" text for second and subsequent ** terms only. */ static void explainAppendTerm( StrAccum *pStr, /* The text expression being built */ Index *pIdx, /* Index to read column names from */ int nTerm, /* Number of terms */ int iTerm, /* Zero-based index of first term. */ int bAnd, /* Non-zero to append " AND " */ const char *zOp /* Name of the operator */ ){ int i; assert( nTerm>=1 ); if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5); if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); for(i=0; i<nTerm; i++){ if( i ) sqlite3StrAccumAppend(pStr, ",", 1); sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i)); } if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1); sqlite3StrAccumAppend(pStr, zOp, 1); if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); for(i=0; i<nTerm; i++){ if( i ) sqlite3StrAccumAppend(pStr, ",", 1); sqlite3StrAccumAppend(pStr, "?", 1); } if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1); } /* ** Argument pLevel describes a strategy for scanning table pTab. This ** function appends text to pStr that describes the subset of table ** rows scanned by the strategy in the form of an SQL expression. ** ** For example, if the query: ** ** SELECT * FROM t1 WHERE a=1 AND b>2; ** ** is run and there is an index on (a, b), then this function returns a ** string similar to: ** ** "a=? AND b>?" */ static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ Index *pIndex = pLoop->u.btree.pIndex; u16 nEq = pLoop->u.btree.nEq; u16 nSkip = pLoop->nSkip; int i, j; if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; sqlite3StrAccumAppend(pStr, " (", 2); for(i=0; i<nEq; i++){ const char *z = explainIndexColumnName(pIndex, i); if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5); sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); } j = i; if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">"); i = 1; } if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); } sqlite3StrAccumAppend(pStr, ")", 1); } /* ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode ** is added to the output to describe the table scan strategy in pLevel. ** ** If an OP_Explain opcode is added to the VM, its address is returned. ** Otherwise, if no OP_Explain is coded, zero is returned. */ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( Parse *pParse, /* Parse context */ SrcList *pTabList, /* Table list this loop refers to */ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ int iLevel, /* Value for "level" column of output */ int iFrom, /* Value for "from" column of output */ u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ ){ int ret = 0; #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) if( pParse->explain==2 ) #endif { struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; Vdbe *v = pParse->pVdbe; /* VM being constructed */ sqlite3 *db = pParse->db; /* Database handle */ int iId = pParse->iSelectId; /* Select id (left-most output column) */ int isSearch; /* True for a SEARCH. False for SCAN. */ WhereLoop *pLoop; /* The controlling WhereLoop object */ u32 flags; /* Flags that describe this loop */ char *zMsg; /* Text to add to EQP output */ StrAccum str; /* EQP output string */ char zBuf[100]; /* Initial space for EQP output string */ pLoop = pLevel->pWLoop; flags = pLoop->wsFlags; if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); if( pItem->pSelect ){ sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId); }else{ sqlite3XPrintf(&str, " TABLE %s", pItem->zName); } if( pItem->zAlias ){ sqlite3XPrintf(&str, " AS %s", pItem->zAlias); } if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ const char *zFmt = 0; Index *pIdx; assert( pLoop->u.btree.pIndex!=0 ); pIdx = pLoop->u.btree.pIndex; assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ if( isSearch ){ zFmt = "PRIMARY KEY"; } }else if( flags & WHERE_PARTIALIDX ){ zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; }else if( flags & WHERE_AUTO_INDEX ){ zFmt = "AUTOMATIC COVERING INDEX"; }else if( flags & WHERE_IDX_ONLY ){ zFmt = "COVERING INDEX %s"; }else{ zFmt = "INDEX %s"; } if( zFmt ){ sqlite3StrAccumAppend(&str, " USING ", 7); sqlite3XPrintf(&str, zFmt, pIdx->zName); explainIndexRange(&str, pLoop); } }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ const char *zRangeOp; if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ zRangeOp = "="; }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ zRangeOp = ">? AND rowid<"; }else if( flags&WHERE_BTM_LIMIT ){ zRangeOp = ">"; }else{ assert( flags&WHERE_TOP_LIMIT); zRangeOp = "<"; } sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); } #ifndef SQLITE_OMIT_VIRTUALTABLE else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s", pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); } #endif #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS if( pLoop->nOut>=10 ){ sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); }else{ sqlite3StrAccumAppend(&str, " (~1 row)", 9); } #endif zMsg = sqlite3StrAccumFinish(&str); ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC); } return ret; } #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS /* ** Configure the VM passed as the first argument with an ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to ** implement level pLvl. Argument pSrclist is a pointer to the FROM ** clause that the scan reads data from. ** ** If argument addrExplain is not 0, it must be the address of an ** OP_Explain instruction that describes the same loop. */ SQLITE_PRIVATE void sqlite3WhereAddScanStatus( Vdbe *v, /* Vdbe to add scanstatus entry to */ SrcList *pSrclist, /* FROM clause pLvl reads data from */ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ int addrExplain /* Address of OP_Explain (or 0) */ ){ const char *zObj = 0; WhereLoop *pLoop = pLvl->pWLoop; if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ zObj = pLoop->u.btree.pIndex->zName; }else{ zObj = pSrclist->a[pLvl->iFrom].zName; } sqlite3VdbeScanStatus( v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj ); } #endif /* ** Disable a term in the WHERE clause. Except, do not disable the term ** if it controls a LEFT OUTER JOIN and it did not originate in the ON ** or USING clause of that join. ** ** Consider the term t2.z='ok' in the following queries: ** ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' ** ** The t2.z='ok' is disabled in the in (2) because it originates ** in the ON clause. The term is disabled in (3) because it is not part ** of a LEFT OUTER JOIN. In (1), the term is not disabled. ** ** Disabling a term causes that term to not be tested in the inner loop ** of the join. Disabling is an optimization. When terms are satisfied ** by indices, we disable them to prevent redundant tests in the inner ** loop. We would get the correct results if nothing were ever disabled, ** but joins might run a little slower. The trick is to disable as much ** as we can without disabling too much. If we disabled in (1), we'd get ** the wrong answer. See ticket #813. ** ** If all the children of a term are disabled, then that term is also ** automatically disabled. In this way, terms get disabled if derived ** virtual terms are tested first. For example: ** ** x GLOB 'abc*' AND x>='abc' AND x<'acd' ** \___________/ \______/ \_____/ ** parent child1 child2 ** ** Only the parent term was in the original WHERE clause. The child1 ** and child2 terms were added by the LIKE optimization. If both of ** the virtual child terms are valid, then testing of the parent can be ** skipped. ** ** Usually the parent term is marked as TERM_CODED. But if the parent ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. ** The TERM_LIKECOND marking indicates that the term should be coded inside ** a conditional such that is only evaluated on the second pass of a ** LIKE-optimization loop, when scanning BLOBs instead of strings. */ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ int nLoop = 0; while( ALWAYS(pTerm!=0) && (pTerm->wtFlags & TERM_CODED)==0 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) && (pLevel->notReady & pTerm->prereqAll)==0 ){ if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ pTerm->wtFlags |= TERM_LIKECOND; }else{ pTerm->wtFlags |= TERM_CODED; } if( pTerm->iParent<0 ) break; pTerm = &pTerm->pWC->a[pTerm->iParent]; pTerm->nChild--; if( pTerm->nChild!=0 ) break; nLoop++; } } /* ** Code an OP_Affinity opcode to apply the column affinity string zAff ** to the n registers starting at base. ** ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the ** beginning and end of zAff are ignored. If all entries in zAff are ** SQLITE_AFF_BLOB, then no code gets generated. ** ** This routine makes its own copy of zAff so that the caller is free ** to modify zAff after this routine returns. */ static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ Vdbe *v = pParse->pVdbe; if( zAff==0 ){ assert( pParse->db->mallocFailed ); return; } assert( v!=0 ); /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning ** and end of the affinity string. */ while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){ n--; base++; zAff++; } while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){ n--; } /* Code the OP_Affinity opcode if there is anything left to do. */ if( n>0 ){ sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); sqlite3ExprCacheAffinityChange(pParse, base, n); } } /* ** Expression pRight, which is the RHS of a comparison operation, is ** either a vector of n elements or, if n==1, a scalar expression. ** Before the comparison operation, affinity zAff is to be applied ** to the pRight values. This function modifies characters within the ** affinity string to SQLITE_AFF_BLOB if either: ** ** * the comparison will be performed with no affinity, or ** * the affinity change in zAff is guaranteed not to change the value. */ static void updateRangeAffinityStr( Expr *pRight, /* RHS of comparison */ int n, /* Number of vector elements in comparison */ char *zAff /* Affinity string to modify */ ){ int i; for(i=0; i<n; i++){ Expr *p = sqlite3VectorFieldSubexpr(pRight, i); if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB || sqlite3ExprNeedsNoAffinityChange(p, zAff[i]) ){ zAff[i] = SQLITE_AFF_BLOB; } } } /* ** Generate code for a single equality term of the WHERE clause. An equality ** term can be either X=expr or X IN (...). pTerm is the term to be ** coded. ** ** The current value for the constraint is left in a register, the index ** of which is returned. An attempt is made store the result in iTarget but ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the ** constraint is a TK_EQ or TK_IS, then the current value might be left in ** some other register and it is the caller's responsibility to compensate. ** ** For a constraint of the form X=expr, the expression is evaluated in ** straight-line code. For constraints of the form X IN (...) ** this routine sets up a loop that will iterate over all values of X. */ static int codeEqualityTerm( Parse *pParse, /* The parsing context */ WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ WhereLevel *pLevel, /* The level of the FROM clause we are working on */ int iEq, /* Index of the equality term within this level */ int bRev, /* True for reverse-order IN operations */ int iTarget /* Attempt to leave results in this register */ ){ Expr *pX = pTerm->pExpr; Vdbe *v = pParse->pVdbe; int iReg; /* Register holding results */ assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); assert( iTarget>0 ); if( pX->op==TK_EQ || pX->op==TK_IS ){ iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); }else if( pX->op==TK_ISNULL ){ iReg = iTarget; sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); #ifndef SQLITE_OMIT_SUBQUERY }else{ int eType = IN_INDEX_NOOP; int iTab; struct InLoop *pIn; WhereLoop *pLoop = pLevel->pWLoop; int i; int nEq = 0; int *aiMap = 0; if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 && pLoop->u.btree.pIndex->aSortOrder[iEq] ){ testcase( iEq==0 ); testcase( bRev ); bRev = !bRev; } assert( pX->op==TK_IN ); iReg = iTarget; for(i=0; i<iEq; i++){ if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ disableTerm(pLevel, pTerm); return iTarget; } } for(i=iEq;i<pLoop->nLTerm; i++){ if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++; } if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0); }else{ Select *pSelect = pX->x.pSelect; sqlite3 *db = pParse->db; u16 savedDbOptFlags = db->dbOptFlags; ExprList *pOrigRhs = pSelect->pEList; ExprList *pOrigLhs = pX->pLeft->x.pList; ExprList *pRhs = 0; /* New Select.pEList for RHS */ ExprList *pLhs = 0; /* New pX->pLeft vector */ for(i=iEq;i<pLoop->nLTerm; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ int iField = pLoop->aLTerm[i]->iField - 1; Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0); Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0); pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs); pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs); } } if( !db->mallocFailed ){ Expr *pLeft = pX->pLeft; if( pSelect->pOrderBy ){ /* If the SELECT statement has an ORDER BY clause, zero the ** iOrderByCol variables. These are set to non-zero when an ** ORDER BY term exactly matches one of the terms of the ** result-set. Since the result-set of the SELECT statement may ** have been modified or reordered, these variables are no longer ** set correctly. Since setting them is just an optimization, ** it's easiest just to zero them here. */ ExprList *pOrderBy = pSelect->pOrderBy; for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } } /* Take care here not to generate a TK_VECTOR containing only a ** single value. Since the parser never creates such a vector, some ** of the subroutines do not handle this case. */ if( pLhs->nExpr==1 ){ pX->pLeft = pLhs->a[0].pExpr; }else{ pLeft->x.pList = pLhs; aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq); testcase( aiMap==0 ); } pSelect->pEList = pRhs; db->dbOptFlags |= SQLITE_QueryFlattener; eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap); db->dbOptFlags = savedDbOptFlags; testcase( aiMap!=0 && aiMap[0]!=0 ); pSelect->pEList = pOrigRhs; pLeft->x.pList = pOrigLhs; pX->pLeft = pLeft; } sqlite3ExprListDelete(pParse->db, pLhs); sqlite3ExprListDelete(pParse->db, pRhs); } if( eType==IN_INDEX_INDEX_DESC ){ testcase( bRev ); bRev = !bRev; } iTab = pX->iTable; sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); VdbeCoverageIf(v, bRev); VdbeCoverageIf(v, !bRev); assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); pLoop->wsFlags |= WHERE_IN_ABLE; if( pLevel->u.in.nIn==0 ){ pLevel->addrNxt = sqlite3VdbeMakeLabel(v); } i = pLevel->u.in.nIn; pLevel->u.in.nIn += nEq; pLevel->u.in.aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); pIn = pLevel->u.in.aInLoop; if( pIn ){ int iMap = 0; /* Index in aiMap[] */ pIn += i; for(i=iEq;i<pLoop->nLTerm; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ int iOut = iReg + i - iEq; if( eType==IN_INDEX_ROWID ){ testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */ pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); }else{ int iCol = aiMap ? aiMap[iMap++] : 0; pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); } sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); if( i==iEq ){ pIn->iCur = iTab; pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; }else{ pIn->eEndLoopOp = OP_Noop; } pIn++; } } }else{ pLevel->u.in.nIn = 0; } sqlite3DbFree(pParse->db, aiMap); #endif } disableTerm(pLevel, pTerm); return iReg; } /* ** Generate code that will evaluate all == and IN constraints for an ** index scan. ** ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 ** The index has as many as three equality constraints, but in this ** example, the third "c" value is an inequality. So only two ** constraints are coded. This routine will generate code to evaluate ** a==5 and b IN (1,2,3). The current values for a and b will be stored ** in consecutive registers and the index of the first register is returned. ** ** In the example above nEq==2. But this subroutine works for any value ** of nEq including 0. If nEq==0, this routine is nearly a no-op. ** The only thing it does is allocate the pLevel->iMem memory cell and ** compute the affinity string. ** ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that ** occurs after the nEq quality constraints. ** ** This routine allocates a range of nEq+nExtraReg memory cells and returns ** the index of the first memory cell in that range. The code that ** calls this routine will use that memory range to store keys for ** start and termination conditions of the loop. ** key value of the loop. If one or more IN operators appear, then ** this routine allocates an additional nEq memory cells for internal ** use. ** ** Before returning, *pzAff is set to point to a buffer containing a ** copy of the column affinity string of the index allocated using ** sqlite3DbMalloc(). Except, entries in the copy of the string associated ** with equality constraints that use BLOB or NONE affinity are set to ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: ** ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; ** ** In the example above, the index on t1(a) has TEXT affinity. But since ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, ** no conversion should be attempted before using a t2.b value as part of ** a key to search the index. Hence the first byte in the returned affinity ** string in this example would be set to SQLITE_AFF_BLOB. */ static int codeAllEqualityTerms( Parse *pParse, /* Parsing context */ WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ int bRev, /* Reverse the order of IN operators */ int nExtraReg, /* Number of extra registers to allocate */ char **pzAff /* OUT: Set to point to affinity string */ ){ u16 nEq; /* The number of == or IN constraints to code */ u16 nSkip; /* Number of left-most columns to skip */ Vdbe *v = pParse->pVdbe; /* The vm under construction */ Index *pIdx; /* The index being used for this loop */ WhereTerm *pTerm; /* A single constraint term */ WhereLoop *pLoop; /* The WhereLoop object */ int j; /* Loop counter */ int regBase; /* Base register */ int nReg; /* Number of registers to allocate */ char *zAff; /* Affinity string to return */ /* This module is only called on query plans that use an index. */ pLoop = pLevel->pWLoop; assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); nEq = pLoop->u.btree.nEq; nSkip = pLoop->nSkip; pIdx = pLoop->u.btree.pIndex; assert( pIdx!=0 ); /* Figure out how many memory cells we will need then allocate them. */ regBase = pParse->nMem + 1; nReg = pLoop->u.btree.nEq + nExtraReg; pParse->nMem += nReg; zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); assert( zAff!=0 || pParse->db->mallocFailed ); if( nSkip ){ int iIdxCur = pLevel->iIdxCur; sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); j = sqlite3VdbeAddOp0(v, OP_Goto); pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), iIdxCur, 0, regBase, nSkip); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); sqlite3VdbeJumpHere(v, j); for(j=0; j<nSkip; j++){ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); testcase( pIdx->aiColumn[j]==XN_EXPR ); VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); } } /* Evaluate the equality constraints */ assert( zAff==0 || (int)strlen(zAff)>=nEq ); for(j=nSkip; j<nEq; j++){ int r1; pTerm = pLoop->aLTerm[j]; assert( pTerm!=0 ); /* The following testcase is true for indices with redundant columns. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); testcase( pTerm->wtFlags & TERM_VIRTUAL ); r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); if( r1!=regBase+j ){ if( nReg==1 ){ sqlite3ReleaseTempReg(pParse, regBase); regBase = r1; }else{ sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); } } if( pTerm->eOperator & WO_IN ){ if( pTerm->pExpr->flags & EP_xIsSelect ){ /* No affinity ever needs to be (or should be) applied to a value ** from the RHS of an "? IN (SELECT ...)" expression. The ** sqlite3FindInIndex() routine has already ensured that the ** affinity of the comparison has been applied to the value. */ if( zAff ) zAff[j] = SQLITE_AFF_BLOB; } }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ Expr *pRight = pTerm->pExpr->pRight; if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); VdbeCoverage(v); } if( zAff ){ if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ zAff[j] = SQLITE_AFF_BLOB; } if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ zAff[j] = SQLITE_AFF_BLOB; } } } } *pzAff = zAff; return regBase; } #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS /* ** If the most recently coded instruction is a constant range constraint ** (a string literal) that originated from the LIKE optimization, then ** set P3 and P5 on the OP_String opcode so that the string will be cast ** to a BLOB at appropriate times. ** ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range ** expression: "x>='ABC' AND x<'abd'". But this requires that the range ** scan loop run twice, once for strings and a second time for BLOBs. ** The OP_String opcodes on the second pass convert the upper and lower ** bound string constants to blobs. This routine makes the necessary changes ** to the OP_String opcodes for that to happen. ** ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then ** only the one pass through the string space is required, so this routine ** becomes a no-op. */ static void whereLikeOptimizationStringFixup( Vdbe *v, /* prepared statement under construction */ WhereLevel *pLevel, /* The loop that contains the LIKE operator */ WhereTerm *pTerm /* The upper or lower bound just coded */ ){ if( pTerm->wtFlags & TERM_LIKEOPT ){ VdbeOp *pOp; assert( pLevel->iLikeRepCntr>0 ); pOp = sqlite3VdbeGetOp(v, -1); assert( pOp!=0 ); assert( pOp->opcode==OP_String8 || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ } } #else # define whereLikeOptimizationStringFixup(A,B,C) #endif #ifdef SQLITE_ENABLE_CURSOR_HINTS /* ** Information is passed from codeCursorHint() down to individual nodes of ** the expression tree (by sqlite3WalkExpr()) using an instance of this ** structure. */ struct CCurHint { int iTabCur; /* Cursor for the main table */ int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ Index *pIdx; /* The index used to access the table */ }; /* ** This function is called for every node of an expression that is a candidate ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference ** the table CCurHint.iTabCur, verify that the same column can be ** accessed through the index. If it cannot, then set pWalker->eCode to 1. */ static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ struct CCurHint *pHint = pWalker->u.pCCurHint; assert( pHint->pIdx!=0 ); if( pExpr->op==TK_COLUMN && pExpr->iTable==pHint->iTabCur && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0 ){ pWalker->eCode = 1; } return WRC_Continue; } /* ** Test whether or not expression pExpr, which was part of a WHERE clause, ** should be included in the cursor-hint for a table that is on the rhs ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the ** expression is not suitable. ** ** An expression is unsuitable if it might evaluate to non NULL even if ** a TK_COLUMN node that does affect the value of the expression is set ** to NULL. For example: ** ** col IS NULL ** col IS NOT NULL ** coalesce(col, 1) ** CASE WHEN col THEN 0 ELSE 1 END */ static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_IS || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE ){ pWalker->eCode = 1; }else if( pExpr->op==TK_FUNCTION ){ int d1; char d2[3]; if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ pWalker->eCode = 1; } } return WRC_Continue; } /* ** This function is called on every node of an expression tree used as an ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN ** that accesses any table other than the one identified by ** CCurHint.iTabCur, then do the following: ** ** 1) allocate a register and code an OP_Column instruction to read ** the specified column into the new register, and ** ** 2) transform the expression node to a TK_REGISTER node that reads ** from the newly populated register. ** ** Also, if the node is a TK_COLUMN that does access the table idenified ** by pCCurHint.iTabCur, and an index is being used (which we will ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into ** an access of the index rather than the original table. */ static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ int rc = WRC_Continue; struct CCurHint *pHint = pWalker->u.pCCurHint; if( pExpr->op==TK_COLUMN ){ if( pExpr->iTable!=pHint->iTabCur ){ Vdbe *v = pWalker->pParse->pVdbe; int reg = ++pWalker->pParse->nMem; /* Register for column value */ sqlite3ExprCodeGetColumnOfTable( v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg ); pExpr->op = TK_REGISTER; pExpr->iTable = reg; }else if( pHint->pIdx!=0 ){ pExpr->iTable = pHint->iIdxCur; pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn); assert( pExpr->iColumn>=0 ); } }else if( pExpr->op==TK_AGG_FUNCTION ){ /* An aggregate function in the WHERE clause of a query means this must ** be a correlated sub-query, and expression pExpr is an aggregate from ** the parent context. Do not walk the function arguments in this case. ** ** todo: It should be possible to replace this node with a TK_REGISTER ** expression, as the result of the expression must be stored in a ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ rc = WRC_Prune; } return rc; } /* ** Insert an OP_CursorHint instruction if it is appropriate to do so. */ static void codeCursorHint( struct SrcList_item *pTabItem, /* FROM clause item */ WhereInfo *pWInfo, /* The where clause */ WhereLevel *pLevel, /* Which loop to provide hints for */ WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ ){ Parse *pParse = pWInfo->pParse; sqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; Expr *pExpr = 0; WhereLoop *pLoop = pLevel->pWLoop; int iCur; WhereClause *pWC; WhereTerm *pTerm; int i, j; struct CCurHint sHint; Walker sWalker; if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; iCur = pLevel->iTabCur; assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); sHint.iTabCur = iCur; sHint.iIdxCur = pLevel->iIdxCur; sHint.pIdx = pLoop->u.btree.pIndex; memset(&sWalker, 0, sizeof(sWalker)); sWalker.pParse = pParse; sWalker.u.pCCurHint = &sHint; pWC = &pWInfo->sWC; for(i=0; i<pWC->nTerm; i++){ pTerm = &pWC->a[i]; if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( pTerm->prereqAll & pLevel->notReady ) continue; /* Any terms specified as part of the ON(...) clause for any LEFT ** JOIN for which the current table is not the rhs are omitted ** from the cursor-hint. ** ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms ** that were specified as part of the WHERE clause must be excluded. ** This is to address the following: ** ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; ** ** Say there is a single row in t2 that matches (t1.a=t2.b), but its ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is ** pushed down to the cursor, this row is filtered out, causing ** SQLite to synthesize a row of NULL values. Which does match the ** WHERE clause, and so the query returns a row. Which is incorrect. ** ** For the same reason, WHERE terms such as: ** ** WHERE 1 = (t2.c IS NULL) ** ** are also excluded. See codeCursorHintIsOrFunction() for details. */ if( pTabItem->fg.jointype & JT_LEFT ){ Expr *pExpr = pTerm->pExpr; if( !ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable!=pTabItem->iCursor ){ sWalker.eCode = 0; sWalker.xExprCallback = codeCursorHintIsOrFunction; sqlite3WalkExpr(&sWalker, pTerm->pExpr); if( sWalker.eCode ) continue; } }else{ if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; } /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize ** the cursor. These terms are not needed as hints for a pure range ** scan (that has no == terms) so omit them. */ if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){} if( j<pLoop->nLTerm ) continue; } /* No subqueries or non-deterministic functions allowed */ if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; /* For an index scan, make sure referenced columns are actually in ** the index. */ if( sHint.pIdx!=0 ){ sWalker.eCode = 0; sWalker.xExprCallback = codeCursorHintCheckExpr; sqlite3WalkExpr(&sWalker, pTerm->pExpr); if( sWalker.eCode ) continue; } /* If we survive all prior tests, that means this term is worth hinting */ pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); } if( pExpr!=0 ){ sWalker.xExprCallback = codeCursorHintFixExpr; sqlite3WalkExpr(&sWalker, pExpr); sqlite3VdbeAddOp4(v, OP_CursorHint, (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, (const char*)pExpr, P4_EXPR); } } #else # define codeCursorHint(A,B,C,D) /* No-op */ #endif /* SQLITE_ENABLE_CURSOR_HINTS */ /* ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains ** a rowid value just read from cursor iIdxCur, open on index pIdx. This ** function generates code to do a deferred seek of cursor iCur to the ** rowid stored in register iRowid. ** ** Normally, this is just: ** ** OP_Seek $iCur $iRowid ** ** However, if the scan currently being coded is a branch of an OR-loop and ** the statement currently being coded is a SELECT, then P3 of the OP_Seek ** is set to iIdxCur and P4 is set to point to an array of integers ** containing one entry for each column of the table cursor iCur is open ** on. For each table column, if the column is the i'th column of the ** index, then the corresponding array entry is set to (i+1). If the column ** does not appear in the index at all, the array entry is set to 0. */ static void codeDeferredSeek( WhereInfo *pWInfo, /* Where clause context */ Index *pIdx, /* Index scan is using */ int iCur, /* Cursor for IPK b-tree */ int iIdxCur /* Index cursor */ ){ Parse *pParse = pWInfo->pParse; /* Parse context */ Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ assert( iIdxCur>0 ); assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur); if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) ){ int i; Table *pTab = pIdx->pTable; int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); if( ai ){ ai[0] = pTab->nCol; for(i=0; i<pIdx->nColumn-1; i++){ assert( pIdx->aiColumn[i]<pTab->nCol ); if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1; } sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); } } } /* ** If the expression passed as the second argument is a vector, generate ** code to write the first nReg elements of the vector into an array ** of registers starting with iReg. ** ** If the expression is not a vector, then nReg must be passed 1. In ** this case, generate code to evaluate the expression and leave the ** result in register iReg. */ static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ assert( nReg>0 ); if( sqlite3ExprIsVector(p) ){ #ifndef SQLITE_OMIT_SUBQUERY if( (p->flags & EP_xIsSelect) ){ Vdbe *v = pParse->pVdbe; int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0); sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); }else #endif { int i; ExprList *pList = p->x.pList; assert( nReg<=pList->nExpr ); for(i=0; i<nReg; i++){ sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); } } }else{ assert( nReg==1 ); sqlite3ExprCode(pParse, p, iReg); } } /* ** Generate code for the start of the iLevel-th loop in the WHERE clause ** implementation described by pWInfo. */ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( WhereInfo *pWInfo, /* Complete information about the WHERE clause */ int iLevel, /* Which level of pWInfo->a[] should be coded */ Bitmask notReady /* Which tables are currently available */ ){ int j, k; /* Loop counters */ int iCur; /* The VDBE cursor for the table */ int addrNxt; /* Where to jump to continue with the next IN case */ int omitTable; /* True if we use the index only */ int bRev; /* True if we need to scan in reverse order */ WhereLevel *pLevel; /* The where level to be coded */ WhereLoop *pLoop; /* The WhereLoop object being coded */ WhereClause *pWC; /* Decomposition of the entire WHERE clause */ WhereTerm *pTerm; /* A WHERE clause term */ Parse *pParse; /* Parsing context */ sqlite3 *db; /* Database connection */ Vdbe *v; /* The prepared stmt under constructions */ struct SrcList_item *pTabItem; /* FROM clause term being coded */ int addrBrk; /* Jump here to break out of the loop */ int addrCont; /* Jump here to continue with next cycle */ int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ int iReleaseReg = 0; /* Temp register to free before returning */ pParse = pWInfo->pParse; v = pParse->pVdbe; pWC = &pWInfo->sWC; db = pParse->db; pLevel = &pWInfo->a[iLevel]; pLoop = pLevel->pWLoop; pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; iCur = pTabItem->iCursor; pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); bRev = (pWInfo->revMask>>iLevel)&1; omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); /* Create labels for the "break" and "continue" instructions ** for the current loop. Jump to addrBrk to break out of a loop. ** Jump to cont to go immediately to the next iteration of the ** loop. ** ** When there is an IN operator, we also have a "addrNxt" label that ** means to continue with the next IN value combination. When ** there are no IN operators in the constraints, the "addrNxt" label ** is the same as "addrBrk". */ addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); /* If this is the right table of a LEFT OUTER JOIN, allocate and ** initialize a memory cell that records if this table matches any ** row of the left table of the join. */ if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ pLevel->iLeftJoin = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); VdbeComment((v, "init LEFT JOIN no-match flag")); } /* Special case of a FROM clause subquery implemented as a co-routine */ if( pTabItem->fg.viaCoroutine ){ int regYield = pTabItem->regReturn; sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); VdbeCoverage(v); VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); pLevel->op = OP_Goto; }else #ifndef SQLITE_OMIT_VIRTUALTABLE if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ /* Case 1: The table is a virtual-table. Use the VFilter and VNext ** to access the data. */ int iReg; /* P3 Value for OP_VFilter */ int addrNotFound; int nConstraint = pLoop->nLTerm; int iIn; /* Counter for IN constraints */ sqlite3ExprCachePush(pParse); iReg = sqlite3GetTempRange(pParse, nConstraint+2); addrNotFound = pLevel->addrBrk; for(j=0; j<nConstraint; j++){ int iTarget = iReg+j+2; pTerm = pLoop->aLTerm[j]; if( NEVER(pTerm==0) ) continue; if( pTerm->eOperator & WO_IN ){ codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); addrNotFound = pLevel->addrNxt; }else{ Expr *pRight = pTerm->pExpr->pRight; codeExprOrVector(pParse, pRight, iTarget, 1); } } sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pLoop->u.vtab.idxStr, pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC); VdbeCoverage(v); pLoop->u.vtab.needFree = 0; pLevel->p1 = iCur; pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; pLevel->p2 = sqlite3VdbeCurrentAddr(v); iIn = pLevel->u.in.nIn; for(j=nConstraint-1; j>=0; j--){ pTerm = pLoop->aLTerm[j]; if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ disableTerm(pLevel, pTerm); }else if( (pTerm->eOperator & WO_IN)!=0 ){ Expr *pCompare; /* The comparison operator */ Expr *pRight; /* RHS of the comparison */ VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ /* Reload the constraint value into reg[iReg+j+2]. The same value ** was loaded into the same register prior to the OP_VFilter, but ** the xFilter implementation might have changed the datatype or ** encoding of the value in the register, so it *must* be reloaded. */ assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); if( !db->mallocFailed ){ assert( iIn>0 ); pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop); assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); testcase( pOp->opcode==OP_Rowid ); sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); } /* Generate code that will continue to the next row if ** the IN constraint is not satisfied */ pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0); assert( pCompare!=0 || db->mallocFailed ); if( pCompare ){ pCompare->pLeft = pTerm->pExpr->pLeft; pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); if( pRight ){ pRight->iTable = iReg+j+2; sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); } pCompare->pLeft = 0; sqlite3ExprDelete(db, pCompare); } } } /* These registers need to be preserved in case there is an IN operator ** loop. So we could deallocate the registers here (and potentially ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems ** simpler and safer to simply not reuse the registers. ** ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); */ sqlite3ExprCachePop(pParse); }else #endif /* SQLITE_OMIT_VIRTUALTABLE */ if( (pLoop->wsFlags & WHERE_IPK)!=0 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 ){ /* Case 2: We can directly reference a single row using an ** equality comparison against the ROWID field. Or ** we reference multiple rows using a "rowid IN (...)" ** construct. */ assert( pLoop->u.btree.nEq==1 ); pTerm = pLoop->aLTerm[0]; assert( pTerm!=0 ); assert( pTerm->pExpr!=0 ); assert( omitTable==0 ); testcase( pTerm->wtFlags & TERM_VIRTUAL ); iReleaseReg = ++pParse->nMem; iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); addrNxt = pLevel->addrNxt; sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); VdbeCoverage(v); sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); VdbeComment((v, "pk")); pLevel->op = OP_Noop; }else if( (pLoop->wsFlags & WHERE_IPK)!=0 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 ){ /* Case 3: We have an inequality comparison against the ROWID field. */ int testOp = OP_Noop; int start; int memEndValue = 0; WhereTerm *pStart, *pEnd; assert( omitTable==0 ); j = 0; pStart = pEnd = 0; if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; assert( pStart!=0 || pEnd!=0 ); if( bRev ){ pTerm = pStart; pStart = pEnd; pEnd = pTerm; } codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); if( pStart ){ Expr *pX; /* The expression that defines the start bound */ int r1, rTemp; /* Registers for holding the start boundary */ int op; /* Cursor seek operation */ /* The following constant maps TK_xx codes into corresponding ** seek opcodes. It depends on a particular ordering of TK_xx */ const u8 aMoveOp[] = { /* TK_GT */ OP_SeekGT, /* TK_LE */ OP_SeekLE, /* TK_LT */ OP_SeekLT, /* TK_GE */ OP_SeekGE }; assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ assert( (pStart->wtFlags & TERM_VNULL)==0 ); testcase( pStart->wtFlags & TERM_VIRTUAL ); pX = pStart->pExpr; assert( pX!=0 ); testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ if( sqlite3ExprIsVector(pX->pRight) ){ r1 = rTemp = sqlite3GetTempReg(pParse); codeExprOrVector(pParse, pX->pRight, r1, 1); op = aMoveOp[(pX->op - TK_GT) | 0x0001]; }else{ r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); disableTerm(pLevel, pStart); op = aMoveOp[(pX->op - TK_GT)]; } sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); VdbeComment((v, "pk")); VdbeCoverageIf(v, pX->op==TK_GT); VdbeCoverageIf(v, pX->op==TK_LE); VdbeCoverageIf(v, pX->op==TK_LT); VdbeCoverageIf(v, pX->op==TK_GE); sqlite3ExprCacheAffinityChange(pParse, r1, 1); sqlite3ReleaseTempReg(pParse, rTemp); }else{ sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); } if( pEnd ){ Expr *pX; pX = pEnd->pExpr; assert( pX!=0 ); assert( (pEnd->wtFlags & TERM_VNULL)==0 ); testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ testcase( pEnd->wtFlags & TERM_VIRTUAL ); memEndValue = ++pParse->nMem; codeExprOrVector(pParse, pX->pRight, memEndValue, 1); if( 0==sqlite3ExprIsVector(pX->pRight) && (pX->op==TK_LT || pX->op==TK_GT) ){ testOp = bRev ? OP_Le : OP_Ge; }else{ testOp = bRev ? OP_Lt : OP_Gt; } if( 0==sqlite3ExprIsVector(pX->pRight) ){ disableTerm(pLevel, pEnd); } } start = sqlite3VdbeCurrentAddr(v); pLevel->op = bRev ? OP_Prev : OP_Next; pLevel->p1 = iCur; pLevel->p2 = start; assert( pLevel->p5==0 ); if( testOp!=OP_Noop ){ iRowidReg = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); VdbeCoverageIf(v, testOp==OP_Le); VdbeCoverageIf(v, testOp==OP_Lt); VdbeCoverageIf(v, testOp==OP_Ge); VdbeCoverageIf(v, testOp==OP_Gt); sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); } }else if( pLoop->wsFlags & WHERE_INDEXED ){ /* Case 4: A scan using an index. ** ** The WHERE clause may contain zero or more equality ** terms ("==" or "IN" operators) that refer to the N ** left-most columns of the index. It may also contain ** inequality constraints (>, <, >= or <=) on the indexed ** column that immediately follows the N equalities. Only ** the right-most column can be an inequality - the rest must ** use the "==" and "IN" operators. For example, if the ** index is on (x,y,z), then the following clauses are all ** optimized: ** ** x=5 ** x=5 AND y=10 ** x=5 AND y<10 ** x=5 AND y>5 AND y<10 ** x=5 AND y=5 AND z<=10 ** ** The z<10 term of the following cannot be used, only ** the x=5 term: ** ** x=5 AND z<10 ** ** N may be zero if there are inequality constraints. ** If there are no inequality constraints, then N is at ** least one. ** ** This case is also used when there are no WHERE clause ** constraints but an index is selected anyway, in order ** to force the output order to conform to an ORDER BY. */ static const u8 aStartOp[] = { 0, 0, OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ OP_Last, /* 3: (!start_constraints && startEq && bRev) */ OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ }; static const u8 aEndOp[] = { OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ }; u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ int regBase; /* Base register holding constraint values */ WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ int startEq; /* True if range start uses ==, >= or <= */ int endEq; /* True if range end uses ==, >= or <= */ int start_constraints; /* Start of range is constrained */ int nConstraint; /* Number of constraint terms */ Index *pIdx; /* The index we will be using */ int iIdxCur; /* The VDBE cursor for the index */ int nExtraReg = 0; /* Number of extra registers needed */ int op; /* Instruction opcode */ char *zStartAff; /* Affinity for start of range constraint */ char *zEndAff = 0; /* Affinity for end of range constraint */ u8 bSeekPastNull = 0; /* True to seek past initial nulls */ u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ pIdx = pLoop->u.btree.pIndex; iIdxCur = pLevel->iIdxCur; assert( nEq>=pLoop->nSkip ); /* If this loop satisfies a sort order (pOrderBy) request that ** was passed to this function to implement a "SELECT min(x) ..." ** query, then the caller will only allow the loop to run for ** a single iteration. This means that the first row returned ** should not have a NULL value stored in 'x'. If column 'x' is ** the first one after the nEq equality constraints in the index, ** this requires some special handling. */ assert( pWInfo->pOrderBy==0 || pWInfo->pOrderBy->nExpr==1 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 && pWInfo->nOBSat>0 && (pIdx->nKeyCol>nEq) ){ assert( pLoop->nSkip==0 ); bSeekPastNull = 1; nExtraReg = 1; } /* Find any inequality constraint terms for the start and end ** of the range. */ j = nEq; if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ pRangeStart = pLoop->aLTerm[j++]; nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); /* Like optimization range constraints always occur in pairs */ assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); } if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ pRangeEnd = pLoop->aLTerm[j++]; nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ assert( pRangeStart!=0 ); /* LIKE opt constraints */ assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ pLevel->iLikeRepCntr = (u32)++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); VdbeComment((v, "LIKE loop counter")); pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); /* iLikeRepCntr actually stores 2x the counter register number. The ** bottom bit indicates whether the search order is ASC or DESC. */ testcase( bRev ); testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); assert( (bRev & ~1)==0 ); pLevel->iLikeRepCntr <<=1; pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); } #endif if( pRangeStart==0 ){ j = pIdx->aiColumn[nEq]; if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){ bSeekPastNull = 1; } } } assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); /* If we are doing a reverse order scan on an ascending index, or ** a forward order scan on a descending index, interchange the ** start and end terms (pRangeStart and pRangeEnd). */ if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) || (bRev && pIdx->nKeyCol==nEq) ){ SWAP(WhereTerm *, pRangeEnd, pRangeStart); SWAP(u8, bSeekPastNull, bStopAtNull); SWAP(u8, nBtm, nTop); } /* Generate code to evaluate all constraint terms using == or IN ** and store the values of those terms in an array of registers ** starting at regBase. */ codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); if( zStartAff && nTop ){ zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); } addrNxt = pLevel->addrNxt; testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); start_constraints = pRangeStart || nEq>0; /* Seek the index cursor to the start of the range. */ nConstraint = nEq; if( pRangeStart ){ Expr *pRight = pRangeStart->pExpr->pRight; codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); if( (pRangeStart->wtFlags & TERM_VNULL)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); VdbeCoverage(v); } if( zStartAff ){ updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]); } nConstraint += nBtm; testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); if( sqlite3ExprIsVector(pRight)==0 ){ disableTerm(pLevel, pRangeStart); }else{ startEq = 1; } bSeekPastNull = 0; }else if( bSeekPastNull ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); nConstraint++; startEq = 0; start_constraints = 1; } codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ /* The skip-scan logic inside the call to codeAllEqualityConstraints() ** above has already left the cursor sitting on the correct row, ** so no further seeking is needed */ }else{ op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; assert( op!=0 ); sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); VdbeCoverage(v); VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); } /* Load the value for the inequality constraint at the end of the ** range (if any). */ nConstraint = nEq; if( pRangeEnd ){ Expr *pRight = pRangeEnd->pExpr->pRight; sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); codeExprOrVector(pParse, pRight, regBase+nEq, nTop); whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); if( (pRangeEnd->wtFlags & TERM_VNULL)==0 && sqlite3ExprCanBeNull(pRight) ){ sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); VdbeCoverage(v); } if( zEndAff ){ updateRangeAffinityStr(pRight, nTop, zEndAff); codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff); }else{ assert( pParse->db->mallocFailed ); } nConstraint += nTop; testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); if( sqlite3ExprIsVector(pRight)==0 ){ disableTerm(pLevel, pRangeEnd); }else{ endEq = 1; } }else if( bStopAtNull ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); endEq = 0; nConstraint++; } sqlite3DbFree(db, zStartAff); sqlite3DbFree(db, zEndAff); /* Top of the loop body */ pLevel->p2 = sqlite3VdbeCurrentAddr(v); /* Check if the index cursor is past the end of the range. */ if( nConstraint ){ op = aEndOp[bRev*2 + endEq]; sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); } /* Seek the table cursor, if required */ if( omitTable ){ /* pIdx is a covering index. No need to access the main table. */ }else if( HasRowid(pIdx->pTable) ){ if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || ( (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE) && (pWInfo->eOnePass==ONEPASS_SINGLE) )){ iRowidReg = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); VdbeCoverage(v); }else{ codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); } }else if( iCur!=iIdxCur ){ Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); for(j=0; j<pPk->nKeyCol; j++){ k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); } sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, iRowidReg, pPk->nKeyCol); VdbeCoverage(v); } /* Record the instruction used to terminate the loop. */ if( pLoop->wsFlags & WHERE_ONEROW ){ pLevel->op = OP_Noop; }else if( bRev ){ pLevel->op = OP_Prev; }else{ pLevel->op = OP_Next; } pLevel->p1 = iIdxCur; pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; }else{ assert( pLevel->p5==0 ); } }else #ifndef SQLITE_OMIT_OR_OPTIMIZATION if( pLoop->wsFlags & WHERE_MULTI_OR ){ /* Case 5: Two or more separately indexed terms connected by OR ** ** Example: ** ** CREATE TABLE t1(a,b,c,d); ** CREATE INDEX i1 ON t1(a); ** CREATE INDEX i2 ON t1(b); ** CREATE INDEX i3 ON t1(c); ** ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) ** ** In the example, there are three indexed terms connected by OR. ** The top of the loop looks like this: ** ** Null 1 # Zero the rowset in reg 1 ** ** Then, for each indexed term, the following. The arguments to ** RowSetTest are such that the rowid of the current row is inserted ** into the RowSet. If it is already present, control skips the ** Gosub opcode and jumps straight to the code generated by WhereEnd(). ** ** sqlite3WhereBegin(<term>) ** RowSetTest # Insert rowid into rowset ** Gosub 2 A ** sqlite3WhereEnd() ** ** Following the above, code to terminate the loop. Label A, the target ** of the Gosub above, jumps to the instruction right after the Goto. ** ** Null 1 # Zero the rowset in reg 1 ** Goto B # The loop is finished. ** ** A: <loop body> # Return data, whatever. ** ** Return 2 # Jump back to the Gosub ** ** B: <after the loop> ** ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then ** use an ephemeral index instead of a RowSet to record the primary ** keys of the rows we have already seen. ** */ WhereClause *pOrWc; /* The OR-clause broken out into subterms */ SrcList *pOrTab; /* Shortened table list or OR-clause generation */ Index *pCov = 0; /* Potential covering index (or NULL) */ int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ int regRowset = 0; /* Register for RowSet object */ int regRowid = 0; /* Register holding rowid */ int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ int iRetInit; /* Address of regReturn init */ int untestedTerms = 0; /* Some terms not completely tested */ int ii; /* Loop counter */ u16 wctrlFlags; /* Flags for sub-WHERE clause */ Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ Table *pTab = pTabItem->pTab; pTerm = pLoop->aLTerm[0]; assert( pTerm!=0 ); assert( pTerm->eOperator & WO_OR ); assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); pOrWc = &pTerm->u.pOrInfo->wc; pLevel->op = OP_Return; pLevel->p1 = regReturn; /* Set up a new SrcList in pOrTab containing the table being scanned ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). */ if( pWInfo->nLevel>1 ){ int nNotReady; /* The number of notReady tables */ struct SrcList_item *origSrc; /* Original list of tables */ nNotReady = pWInfo->nLevel - iLevel - 1; pOrTab = sqlite3StackAllocRaw(db, sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); if( pOrTab==0 ) return notReady; pOrTab->nAlloc = (u8)(nNotReady + 1); pOrTab->nSrc = pOrTab->nAlloc; memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); origSrc = pWInfo->pTabList->a; for(k=1; k<=nNotReady; k++){ memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); } }else{ pOrTab = pWInfo->pTabList; } /* Initialize the rowset register to contain NULL. An SQL NULL is ** equivalent to an empty rowset. Or, create an ephemeral index ** capable of holding primary keys in the case of a WITHOUT ROWID. ** ** Also initialize regReturn to contain the address of the instruction ** immediately following the OP_Return at the bottom of the loop. This ** is required in a few obscure LEFT JOIN cases where control jumps ** over the top of the loop into the body of it. In this case the ** correct response for the end-of-loop code (the OP_Return) is to ** fall through to the next instruction, just as an OP_Next does if ** called on an uninitialized cursor. */ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ if( HasRowid(pTab) ){ regRowset = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pTab); regRowset = pParse->nTab++; sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); sqlite3VdbeSetP4KeyInfo(pParse, pPk); } regRowid = ++pParse->nMem; } iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y ** Then for every term xN, evaluate as the subexpression: xN AND z ** That way, terms in y that are factored into the disjunction will ** be picked up by the recursive calls to sqlite3WhereBegin() below. ** ** Actually, each subexpression is converted to "xN AND w" where w is ** the "interesting" terms of z - terms that did not originate in the ** ON or USING clause of a LEFT JOIN, and terms that are usable as ** indices. ** ** This optimization also only applies if the (x1 OR x2 OR ...) term ** is not contained in the ON clause of a LEFT JOIN. ** See ticket http://www.sqlite.org/src/info/f2369304e4 */ if( pWC->nTerm>1 ){ int iTerm; for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ Expr *pExpr = pWC->a[iTerm].pExpr; if( &pWC->a[iTerm] == pTerm ) continue; if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); pExpr = sqlite3ExprDup(db, pExpr, 0); pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); } if( pAndExpr ){ pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr); } } /* Run a separate WHERE clause for each term of the OR clause. After ** eliminating duplicates from other WHERE clauses, the action for each ** sub-WHERE clause is to to invoke the main loop body as a subroutine. */ wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); for(ii=0; ii<pOrWc->nTerm; ii++){ WhereTerm *pOrTerm = &pOrWc->a[ii]; if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ WhereInfo *pSubWInfo; /* Info for single OR-term scan */ Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ int jmp1 = 0; /* Address of jump operation */ if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ pAndExpr->pLeft = pOrExpr; pOrExpr = pAndExpr; } /* Loop through table entries that match term pOrTerm. */ WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, wctrlFlags, iCovCur); assert( pSubWInfo || pParse->nErr || db->mallocFailed ); if( pSubWInfo ){ WhereLoop *pSubLoop; int addrExplain = sqlite3WhereExplainOneScan( pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 ); sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); /* This is the sub-WHERE clause body. First skip over ** duplicate rows from prior sub-WHERE clauses, and record the ** rowid (or PRIMARY KEY) for the current row so that the same ** row will be skipped in subsequent sub-WHERE clauses. */ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ int r; int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); if( HasRowid(pTab) ){ r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet); VdbeCoverage(v); }else{ Index *pPk = sqlite3PrimaryKeyIndex(pTab); int nPk = pPk->nKeyCol; int iPk; /* Read the PK into an array of temp registers. */ r = sqlite3GetTempRange(pParse, nPk); for(iPk=0; iPk<nPk; iPk++){ int iCol = pPk->aiColumn[iPk]; sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk); } /* Check if the temp table already contains this key. If so, ** the row has already been included in the result set and ** can be ignored (by jumping past the Gosub below). Otherwise, ** insert the key into the temp table and proceed with processing ** the row. ** ** Use some of the same optimizations as OP_RowSetTest: If iSet ** is zero, assume that the key cannot already be present in ** the temp table. And if iSet is -1, assume that there is no ** need to insert the key into the temp table, as it will never ** be tested for. */ if( iSet ){ jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); VdbeCoverage(v); } if( iSet>=0 ){ sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid, r, nPk); if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); } /* Release the array of temp registers */ sqlite3ReleaseTempRange(pParse, r, nPk); } } /* Invoke the main loop body as a subroutine */ sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); /* Jump here (skipping the main loop body subroutine) if the ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); /* The pSubWInfo->untestedTerms flag means that this OR term ** contained one or more AND term from a notReady table. The ** terms from the notReady table could not be tested and will ** need to be tested later. */ if( pSubWInfo->untestedTerms ) untestedTerms = 1; /* If all of the OR-connected terms are optimized using the same ** index, and the index is opened using the same cursor number ** by each call to sqlite3WhereBegin() made by this loop, it may ** be possible to use that index as a covering index. ** ** If the call to sqlite3WhereBegin() above resulted in a scan that ** uses an index, and this is either the first OR-connected term ** processed or the index is the same as that used by all previous ** terms, set pCov to the candidate covering index. Otherwise, set ** pCov to NULL to indicate that no candidate covering index will ** be available. */ pSubLoop = pSubWInfo->a[0].pWLoop; assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 && (ii==0 || pSubLoop->u.btree.pIndex==pCov) && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) ){ assert( pSubWInfo->a[0].iIdxCur==iCovCur ); pCov = pSubLoop->u.btree.pIndex; }else{ pCov = 0; } /* Finish the loop through table entries that match term pOrTerm. */ sqlite3WhereEnd(pSubWInfo); } } } pLevel->u.pCovidx = pCov; if( pCov ) pLevel->iIdxCur = iCovCur; if( pAndExpr ){ pAndExpr->pLeft = 0; sqlite3ExprDelete(db, pAndExpr); } sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); sqlite3VdbeGoto(v, pLevel->addrBrk); sqlite3VdbeResolveLabel(v, iLoopBody); if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); if( !untestedTerms ) disableTerm(pLevel, pTerm); }else #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ { /* Case 6: There is no usable index. We must do a complete ** scan of the entire table. */ static const u8 aStep[] = { OP_Next, OP_Prev }; static const u8 aStart[] = { OP_Rewind, OP_Last }; assert( bRev==0 || bRev==1 ); if( pTabItem->fg.isRecursive ){ /* Tables marked isRecursive have only a single row that is stored in ** a pseudo-cursor. No need to Rewind or Next such cursors. */ pLevel->op = OP_Noop; }else{ codeCursorHint(pTabItem, pWInfo, pLevel, 0); pLevel->op = aStep[bRev]; pLevel->p1 = iCur; pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; } } #ifdef SQLITE_ENABLE_STMT_SCANSTATUS pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); #endif /* Insert code to test every subexpression that can be completely ** computed using the current set of tables. */ for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ Expr *pE; int skipLikeAddr = 0; testcase( pTerm->wtFlags & TERM_VIRTUAL ); testcase( pTerm->wtFlags & TERM_CODED ); if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ testcase( pWInfo->untestedTerms==0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); pWInfo->untestedTerms = 1; continue; } pE = pTerm->pExpr; assert( pE!=0 ); if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ continue; } if( pTerm->wtFlags & TERM_LIKECOND ){ /* If the TERM_LIKECOND flag is set, that means that the range search ** is sufficient to guarantee that the LIKE operator is true, so we ** can skip the call to the like(A,B) function. But this only works ** for strings. So do not skip the call to the function on the pass ** that compares BLOBs. */ #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS continue; #else u32 x = pLevel->iLikeRepCntr; assert( x>0 ); skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1)); VdbeCoverage(v); #endif } sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); pTerm->wtFlags |= TERM_CODED; } /* Insert code to test for implied constraints based on transitivity ** of the "==" operator. ** ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" ** and we are coding the t1 loop and the t2 loop has not yet coded, ** then we cannot use the "t1.a=t2.b" constraint, but we can code ** the implied "t1.a=123" constraint. */ for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ Expr *pE, sEAlt; WhereTerm *pAlt; if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; if( pTerm->leftCursor!=iCur ) continue; if( pLevel->iLeftJoin ) continue; pE = pTerm->pExpr; assert( !ExprHasProperty(pE, EP_FromJoin) ); assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN|WO_IS, 0); if( pAlt==0 ) continue; if( pAlt->wtFlags & (TERM_CODED) ) continue; testcase( pAlt->eOperator & WO_EQ ); testcase( pAlt->eOperator & WO_IS ); testcase( pAlt->eOperator & WO_IN ); VdbeModuleComment((v, "begin transitive constraint")); sEAlt = *pAlt->pExpr; sEAlt.pLeft = pE->pLeft; sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); } /* For a LEFT OUTER JOIN, generate code that will record the fact that ** at least one row of the right table has matched the left table. */ if( pLevel->iLeftJoin ){ pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); VdbeComment((v, "record LEFT JOIN hit")); sqlite3ExprCacheClear(pParse); for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ testcase( pTerm->wtFlags & TERM_VIRTUAL ); testcase( pTerm->wtFlags & TERM_CODED ); if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ assert( pWInfo->untestedTerms ); continue; } assert( pTerm->pExpr ); sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); pTerm->wtFlags |= TERM_CODED; } } return pLevel->notReady; } /************** End of wherecode.c *******************************************/ /************** Begin file whereexpr.c ***************************************/ /* ** 2015-06-08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This module contains C code that generates VDBE code used to process ** the WHERE clause of SQL statements. ** ** This file was originally part of where.c but was split out to improve ** readability and editabiliity. This file contains utility routines for ** analyzing Expr objects in the WHERE clause. */ /* #include "sqliteInt.h" */ /* #include "whereInt.h" */ /* Forward declarations */ static void exprAnalyze(SrcList*, WhereClause*, int); /* ** Deallocate all memory associated with a WhereOrInfo object. */ static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ sqlite3WhereClauseClear(&p->wc); sqlite3DbFree(db, p); } /* ** Deallocate all memory associated with a WhereAndInfo object. */ static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ sqlite3WhereClauseClear(&p->wc); sqlite3DbFree(db, p); } /* ** Add a single new WhereTerm entry to the WhereClause object pWC. ** The new WhereTerm object is constructed from Expr p and with wtFlags. ** The index in pWC->a[] of the new WhereTerm is returned on success. ** 0 is returned if the new WhereTerm could not be added due to a memory ** allocation error. The memory allocation failure will be recorded in ** the db->mallocFailed flag so that higher-level functions can detect it. ** ** This routine will increase the size of the pWC->a[] array as necessary. ** ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility ** for freeing the expression p is assumed by the WhereClause object pWC. ** This is true even if this routine fails to allocate a new WhereTerm. ** ** WARNING: This routine might reallocate the space used to store ** WhereTerms. All pointers to WhereTerms should be invalidated after ** calling this routine. Such pointers may be reinitialized by referencing ** the pWC->a[] array. */ static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){ WhereTerm *pTerm; int idx; testcase( wtFlags & TERM_VIRTUAL ); if( pWC->nTerm>=pWC->nSlot ){ WhereTerm *pOld = pWC->a; sqlite3 *db = pWC->pWInfo->pParse->db; pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); if( pWC->a==0 ){ if( wtFlags & TERM_DYNAMIC ){ sqlite3ExprDelete(db, p); } pWC->a = pOld; return 0; } memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); if( pOld!=pWC->aStatic ){ sqlite3DbFree(db, pOld); } pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); } pTerm = &pWC->a[idx = pWC->nTerm++]; if( p && ExprHasProperty(p, EP_Unlikely) ){ pTerm->truthProb = sqlite3LogEst(p->iTable) - 270; }else{ pTerm->truthProb = 1; } pTerm->pExpr = sqlite3ExprSkipCollate(p); pTerm->wtFlags = wtFlags; pTerm->pWC = pWC; pTerm->iParent = -1; memset(&pTerm->eOperator, 0, sizeof(WhereTerm) - offsetof(WhereTerm,eOperator)); return idx; } /* ** Return TRUE if the given operator is one of the operators that is ** allowed for an indexable WHERE clause term. The allowed operators are ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL" */ static int allowedOp(int op){ assert( TK_GT>TK_EQ && TK_GT<TK_GE ); assert( TK_LT>TK_EQ && TK_LT<TK_GE ); assert( TK_LE>TK_EQ && TK_LE<TK_GE ); assert( TK_GE==TK_EQ+4 ); return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS; } /* ** Commute a comparison operator. Expressions of the form "X op Y" ** are converted into "Y op X". ** ** If left/right precedence rules come into play when determining the ** collating sequence, then COLLATE operators are adjusted to ensure ** that the collating sequence does not change. For example: ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on ** the left hand side of a comparison overrides any collation sequence ** attached to the right. For the same reason the EP_Collate flag ** is not commuted. */ static void exprCommute(Parse *pParse, Expr *pExpr){ u16 expRight = (pExpr->pRight->flags & EP_Collate); u16 expLeft = (pExpr->pLeft->flags & EP_Collate); assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); if( expRight==expLeft ){ /* Either X and Y both have COLLATE operator or neither do */ if( expRight ){ /* Both X and Y have COLLATE operators. Make sure X is always ** used by clearing the EP_Collate flag from Y. */ pExpr->pRight->flags &= ~EP_Collate; }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){ /* Neither X nor Y have COLLATE operators, but X has a non-default ** collating sequence. So add the EP_Collate marker on X to cause ** it to be searched first. */ pExpr->pLeft->flags |= EP_Collate; } } SWAP(Expr*,pExpr->pRight,pExpr->pLeft); if( pExpr->op>=TK_GT ){ assert( TK_LT==TK_GT+2 ); assert( TK_GE==TK_LE+2 ); assert( TK_GT>TK_EQ ); assert( TK_GT<TK_LE ); assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE ); pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; } } /* ** Translate from TK_xx operator to WO_xx bitmask. */ static u16 operatorMask(int op){ u16 c; assert( allowedOp(op) ); if( op==TK_IN ){ c = WO_IN; }else if( op==TK_ISNULL ){ c = WO_ISNULL; }else if( op==TK_IS ){ c = WO_IS; }else{ assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff ); c = (u16)(WO_EQ<<(op-TK_EQ)); } assert( op!=TK_ISNULL || c==WO_ISNULL ); assert( op!=TK_IN || c==WO_IN ); assert( op!=TK_EQ || c==WO_EQ ); assert( op!=TK_LT || c==WO_LT ); assert( op!=TK_LE || c==WO_LE ); assert( op!=TK_GT || c==WO_GT ); assert( op!=TK_GE || c==WO_GE ); assert( op!=TK_IS || c==WO_IS ); return c; } #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION /* ** Check to see if the given expression is a LIKE or GLOB operator that ** can be optimized using inequality constraints. Return TRUE if it is ** so and false if not. ** ** In order for the operator to be optimizible, the RHS must be a string ** literal that does not begin with a wildcard. The LHS must be a column ** that may only be NULL, a string, or a BLOB, never a number. (This means ** that virtual tables cannot participate in the LIKE optimization.) The ** collating sequence for the column on the LHS must be appropriate for ** the operator. */ static int isLikeOrGlob( Parse *pParse, /* Parsing and code generating context */ Expr *pExpr, /* Test this expression */ Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */ int *pisComplete, /* True if the only wildcard is % in the last character */ int *pnoCase /* True if uppercase is equivalent to lowercase */ ){ const char *z = 0; /* String on RHS of LIKE operator */ Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ ExprList *pList; /* List of operands to the LIKE operator */ int c; /* One character in z[] */ int cnt; /* Number of non-wildcard prefix characters */ char wc[3]; /* Wildcard characters */ sqlite3 *db = pParse->db; /* Database connection */ sqlite3_value *pVal = 0; int op; /* Opcode of pRight */ int rc; /* Result code to return */ if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){ return 0; } #ifdef SQLITE_EBCDIC if( *pnoCase ) return 0; #endif pList = pExpr->x.pList; pLeft = pList->a[1].pExpr; if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT || IsVirtual(pLeft->pTab) /* Value might be numeric */ ){ /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must ** be the name of an indexed column with TEXT affinity. */ return 0; } assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */ pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr); op = pRight->op; if( op==TK_VARIABLE ){ Vdbe *pReprepare = pParse->pReprepare; int iCol = pRight->iColumn; pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB); if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ z = (char *)sqlite3_value_text(pVal); } sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); }else if( op==TK_STRING ){ z = pRight->u.zToken; } if( z ){ cnt = 0; while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; } if( cnt!=0 && 255!=(u8)z[cnt-1] ){ Expr *pPrefix; *pisComplete = c==wc[0] && z[cnt+1]==0; pPrefix = sqlite3Expr(db, TK_STRING, z); if( pPrefix ) pPrefix->u.zToken[cnt] = 0; *ppPrefix = pPrefix; if( op==TK_VARIABLE ){ Vdbe *v = pParse->pVdbe; sqlite3VdbeSetVarmask(v, pRight->iColumn); if( *pisComplete && pRight->u.zToken[1] ){ /* If the rhs of the LIKE expression is a variable, and the current ** value of the variable means there is no need to invoke the LIKE ** function, then no OP_Variable will be added to the program. ** This causes problems for the sqlite3_bind_parameter_name() ** API. To work around them, add a dummy OP_Variable here. */ int r1 = sqlite3GetTempReg(pParse); sqlite3ExprCodeTarget(pParse, pRight, r1); sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); sqlite3ReleaseTempReg(pParse, r1); } } }else{ z = 0; } } rc = (z!=0); sqlite3ValueFree(pVal); return rc; } #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Check to see if the given expression is of the form ** ** column OP expr ** ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a ** column of a virtual table. ** ** If it is then return TRUE. If not, return FALSE. */ static int isMatchOfColumn( Expr *pExpr, /* Test this expression */ unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */ ){ static const struct Op2 { const char *zOp; unsigned char eOp2; } aOp[] = { { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } }; ExprList *pList; Expr *pCol; /* Column reference */ int i; if( pExpr->op!=TK_FUNCTION ){ return 0; } pList = pExpr->x.pList; if( pList==0 || pList->nExpr!=2 ){ return 0; } pCol = pList->a[1].pExpr; if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){ return 0; } for(i=0; i<ArraySize(aOp); i++){ if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){ *peOp2 = aOp[i].eOp2; return 1; } } return 0; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* ** If the pBase expression originated in the ON or USING clause of ** a join, then transfer the appropriate markings over to derived. */ static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ if( pDerived ){ pDerived->flags |= pBase->flags & EP_FromJoin; pDerived->iRightJoinTable = pBase->iRightJoinTable; } } /* ** Mark term iChild as being a child of term iParent */ static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){ pWC->a[iChild].iParent = iParent; pWC->a[iChild].truthProb = pWC->a[iParent].truthProb; pWC->a[iParent].nChild++; } /* ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not ** a conjunction, then return just pTerm when N==0. If N is exceeds ** the number of available subterms, return NULL. */ static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){ if( pTerm->eOperator!=WO_AND ){ return N==0 ? pTerm : 0; } if( N<pTerm->u.pAndInfo->wc.nTerm ){ return &pTerm->u.pAndInfo->wc.a[N]; } return 0; } /* ** Subterms pOne and pTwo are contained within WHERE clause pWC. The ** two subterms are in disjunction - they are OR-ed together. ** ** If these two terms are both of the form: "A op B" with the same ** A and B values but different operators and if the operators are ** compatible (if one is = and the other is <, for example) then ** add a new virtual AND term to pWC that is the combination of the ** two. ** ** Some examples: ** ** x<y OR x=y --> x<=y ** x=y OR x=y --> x=y ** x<=y OR x<y --> x<=y ** ** The following is NOT generated: ** ** x<y OR x>y --> x!=y */ static void whereCombineDisjuncts( SrcList *pSrc, /* the FROM clause */ WhereClause *pWC, /* The complete WHERE clause */ WhereTerm *pOne, /* First disjunct */ WhereTerm *pTwo /* Second disjunct */ ){ u16 eOp = pOne->eOperator | pTwo->eOperator; sqlite3 *db; /* Database connection (for malloc) */ Expr *pNew; /* New virtual expression */ int op; /* Operator for the combined expression */ int idxNew; /* Index in pWC of the next virtual term */ if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return; assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 ); assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 ); if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return; /* If we reach this point, it means the two subterms can be combined */ if( (eOp & (eOp-1))!=0 ){ if( eOp & (WO_LT|WO_LE) ){ eOp = WO_LE; }else{ assert( eOp & (WO_GT|WO_GE) ); eOp = WO_GE; } } db = pWC->pWInfo->pParse->db; pNew = sqlite3ExprDup(db, pOne->pExpr, 0); if( pNew==0 ) return; for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); } pNew->op = op; idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); exprAnalyze(pSrc, pWC, idxNew); } #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) /* ** Analyze a term that consists of two or more OR-connected ** subterms. So in: ** ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) ** ^^^^^^^^^^^^^^^^^^^^ ** ** This routine analyzes terms such as the middle term in the above example. ** A WhereOrTerm object is computed and attached to the term under ** analysis, regardless of the outcome of the analysis. Hence: ** ** WhereTerm.wtFlags |= TERM_ORINFO ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object ** ** The term being analyzed must have two or more of OR-connected subterms. ** A single subterm might be a set of AND-connected sub-subterms. ** Examples of terms under analysis: ** ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 ** (B) x=expr1 OR expr2=x OR x=expr3 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) ** (F) x>A OR (x=A AND y>=B) ** ** CASE 1: ** ** If all subterms are of the form T.C=expr for some single column of C and ** a single table T (as shown in example B above) then create a new virtual ** term that is an equivalent IN expression. In other words, if the term ** being analyzed is: ** ** x = expr1 OR expr2 = x OR x = expr3 ** ** then create a new virtual term like this: ** ** x IN (expr1,expr2,expr3) ** ** CASE 2: ** ** If there are exactly two disjuncts and one side has x>A and the other side ** has x=A (for the same x and A) then add a new virtual conjunct term to the ** WHERE clause of the form "x>=A". Example: ** ** x>A OR (x=A AND y>B) adds: x>=A ** ** The added conjunct can sometimes be helpful in query planning. ** ** CASE 3: ** ** If all subterms are indexable by a single table T, then set ** ** WhereTerm.eOperator = WO_OR ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T ** ** A subterm is "indexable" if it is of the form ** "T.C <op> <expr>" where C is any column of table T and ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". ** A subterm is also indexable if it is an AND of two or more ** subsubterms at least one of which is indexable. Indexable AND ** subterms have their eOperator set to WO_AND and they have ** u.pAndInfo set to a dynamically allocated WhereAndTerm object. ** ** From another point of view, "indexable" means that the subterm could ** potentially be used with an index if an appropriate index exists. ** This analysis does not consider whether or not the index exists; that ** is decided elsewhere. This analysis only looks at whether subterms ** appropriate for indexing exist. ** ** All examples A through E above satisfy case 3. But if a term ** also satisfies case 1 (such as B) we know that the optimizer will ** always prefer case 1, so in that case we pretend that case 3 is not ** satisfied. ** ** It might be the case that multiple tables are indexable. For example, ** (E) above is indexable on tables P, Q, and R. ** ** Terms that satisfy case 3 are candidates for lookup by using ** separate indices to find rowids for each subterm and composing ** the union of all rowids using a RowSet object. This is similar ** to "bitmap indices" in other database engines. ** ** OTHERWISE: ** ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to ** zero. This term is not useful for search. */ static void exprAnalyzeOrTerm( SrcList *pSrc, /* the FROM clause */ WhereClause *pWC, /* the complete WHERE clause */ int idxTerm /* Index of the OR-term to be analyzed */ ){ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ Parse *pParse = pWInfo->pParse; /* Parser context */ sqlite3 *db = pParse->db; /* Database connection */ WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ Expr *pExpr = pTerm->pExpr; /* The expression of the term */ int i; /* Loop counters */ WhereClause *pOrWc; /* Breakup of pTerm into subterms */ WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ Bitmask chngToIN; /* Tables that might satisfy case 1 */ Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ /* ** Break the OR clause into its separate subterms. The subterms are ** stored in a WhereClause structure containing within the WhereOrInfo ** object that is attached to the original OR clause term. */ assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); assert( pExpr->op==TK_OR ); pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); if( pOrInfo==0 ) return; pTerm->wtFlags |= TERM_ORINFO; pOrWc = &pOrInfo->wc; memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic)); sqlite3WhereClauseInit(pOrWc, pWInfo); sqlite3WhereSplit(pOrWc, pExpr, TK_OR); sqlite3WhereExprAnalyze(pSrc, pOrWc); if( db->mallocFailed ) return; assert( pOrWc->nTerm>=2 ); /* ** Compute the set of tables that might satisfy cases 1 or 3. */ indexable = ~(Bitmask)0; chngToIN = ~(Bitmask)0; for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ WhereAndInfo *pAndInfo; assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); chngToIN = 0; pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo)); if( pAndInfo ){ WhereClause *pAndWC; WhereTerm *pAndTerm; int j; Bitmask b = 0; pOrTerm->u.pAndInfo = pAndInfo; pOrTerm->wtFlags |= TERM_ANDINFO; pOrTerm->eOperator = WO_AND; pAndWC = &pAndInfo->wc; memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic)); sqlite3WhereClauseInit(pAndWC, pWC->pWInfo); sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND); sqlite3WhereExprAnalyze(pSrc, pAndWC); pAndWC->pOuter = pWC; if( !db->mallocFailed ){ for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){ assert( pAndTerm->pExpr ); if( allowedOp(pAndTerm->pExpr->op) || pAndTerm->eOperator==WO_MATCH ){ b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); } } } indexable &= b; } }else if( pOrTerm->wtFlags & TERM_COPIED ){ /* Skip this term for now. We revisit it when we process the ** corresponding TERM_VIRTUAL term */ }else{ Bitmask b; b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); if( pOrTerm->wtFlags & TERM_VIRTUAL ){ WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor); } indexable &= b; if( (pOrTerm->eOperator & WO_EQ)==0 ){ chngToIN = 0; }else{ chngToIN &= b; } } } /* ** Record the set of tables that satisfy case 3. The set might be ** empty. */ pOrInfo->indexable = indexable; pTerm->eOperator = indexable==0 ? 0 : WO_OR; /* For a two-way OR, attempt to implementation case 2. */ if( indexable && pOrWc->nTerm==2 ){ int iOne = 0; WhereTerm *pOne; while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){ int iTwo = 0; WhereTerm *pTwo; while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){ whereCombineDisjuncts(pSrc, pWC, pOne, pTwo); } } } /* ** chngToIN holds a set of tables that *might* satisfy case 1. But ** we have to do some additional checking to see if case 1 really ** is satisfied. ** ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means ** that there is no possibility of transforming the OR clause into an ** IN operator because one or more terms in the OR clause contain ** something other than == on a column in the single table. The 1-bit ** case means that every term of the OR clause is of the form ** "table.column=expr" for some single table. The one bit that is set ** will correspond to the common table. We still need to check to make ** sure the same column is used on all terms. The 2-bit case is when ** the all terms are of the form "table1.column=table2.column". It ** might be possible to form an IN operator with either table1.column ** or table2.column as the LHS if either is common to every term of ** the OR clause. ** ** Note that terms of the form "table.column1=table.column2" (the ** same table on both sizes of the ==) cannot be optimized. */ if( chngToIN ){ int okToChngToIN = 0; /* True if the conversion to IN is valid */ int iColumn = -1; /* Column index on lhs of IN operator */ int iCursor = -1; /* Table cursor common to all terms */ int j = 0; /* Loop counter */ /* Search for a table and column that appears on one side or the ** other of the == operator in every subterm. That table and column ** will be recorded in iCursor and iColumn. There might not be any ** such table and column. Set okToChngToIN if an appropriate table ** and column is found but leave okToChngToIN false if not found. */ for(j=0; j<2 && !okToChngToIN; j++){ pOrTerm = pOrWc->a; for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ assert( pOrTerm->eOperator & WO_EQ ); pOrTerm->wtFlags &= ~TERM_OR_OK; if( pOrTerm->leftCursor==iCursor ){ /* This is the 2-bit case and we are on the second iteration and ** current term is from the first iteration. So skip this term. */ assert( j==1 ); continue; } if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){ /* This term must be of the form t1.a==t2.b where t2 is in the ** chngToIN set but t1 is not. This term will be either preceded ** or follwed by an inverted copy (t2.b==t1.a). Skip this term ** and use its inversion. */ testcase( pOrTerm->wtFlags & TERM_COPIED ); testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); continue; } iColumn = pOrTerm->u.leftColumn; iCursor = pOrTerm->leftCursor; break; } if( i<0 ){ /* No candidate table+column was found. This can only occur ** on the second iteration */ assert( j==1 ); assert( IsPowerOfTwo(chngToIN) ); assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) ); break; } testcase( j==1 ); /* We have found a candidate table and column. Check to see if that ** table and column is common to every term in the OR clause */ okToChngToIN = 1; for(; i>=0 && okToChngToIN; i--, pOrTerm++){ assert( pOrTerm->eOperator & WO_EQ ); if( pOrTerm->leftCursor!=iCursor ){ pOrTerm->wtFlags &= ~TERM_OR_OK; }else if( pOrTerm->u.leftColumn!=iColumn ){ okToChngToIN = 0; }else{ int affLeft, affRight; /* If the right-hand side is also a column, then the affinities ** of both right and left sides must be such that no type ** conversions are required on the right. (Ticket #2249) */ affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); if( affRight!=0 && affRight!=affLeft ){ okToChngToIN = 0; }else{ pOrTerm->wtFlags |= TERM_OR_OK; } } } } /* At this point, okToChngToIN is true if original pTerm satisfies ** case 1. In that case, construct a new virtual term that is ** pTerm converted into an IN operator. */ if( okToChngToIN ){ Expr *pDup; /* A transient duplicate expression */ ExprList *pList = 0; /* The RHS of the IN operator */ Expr *pLeft = 0; /* The LHS of the IN operator */ Expr *pNew; /* The complete IN operator */ for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; assert( pOrTerm->eOperator & WO_EQ ); assert( pOrTerm->leftCursor==iCursor ); assert( pOrTerm->u.leftColumn==iColumn ); pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); pLeft = pOrTerm->pExpr->pLeft; } assert( pLeft!=0 ); pDup = sqlite3ExprDup(db, pLeft, 0); pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0); if( pNew ){ int idxNew; transferJoinMarkings(pNew, pExpr); assert( !ExprHasProperty(pNew, EP_xIsSelect) ); pNew->x.pList = pList; idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); exprAnalyze(pSrc, pWC, idxNew); pTerm = &pWC->a[idxTerm]; markTermAsChild(pWC, idxNew, idxTerm); }else{ sqlite3ExprListDelete(db, pList); } pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */ } } } #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ /* ** We already know that pExpr is a binary operator where both operands are ** column references. This routine checks to see if pExpr is an equivalence ** relation: ** 1. The SQLITE_Transitive optimization must be enabled ** 2. Must be either an == or an IS operator ** 3. Not originating in the ON clause of an OUTER JOIN ** 4. The affinities of A and B must be compatible ** 5a. Both operands use the same collating sequence OR ** 5b. The overall collating sequence is BINARY ** If this routine returns TRUE, that means that the RHS can be substituted ** for the LHS anyplace else in the WHERE clause where the LHS column occurs. ** This is an optimization. No harm comes from returning 0. But if 1 is ** returned when it should not be, then incorrect answers might result. */ static int termIsEquivalence(Parse *pParse, Expr *pExpr){ char aff1, aff2; CollSeq *pColl; const char *zColl1, *zColl2; if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0; aff1 = sqlite3ExprAffinity(pExpr->pLeft); aff2 = sqlite3ExprAffinity(pExpr->pRight); if( aff1!=aff2 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2)) ){ return 0; } pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight); if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1; pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); zColl1 = pColl ? pColl->zName : 0; pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight); zColl2 = pColl ? pColl->zName : 0; return sqlite3_stricmp(zColl1, zColl2)==0; } /* ** Recursively walk the expressions of a SELECT statement and generate ** a bitmask indicating which tables are used in that expression ** tree. */ static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ Bitmask mask = 0; while( pS ){ SrcList *pSrc = pS->pSrc; mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList); mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy); mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy); mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere); mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving); if( ALWAYS(pSrc!=0) ){ int i; for(i=0; i<pSrc->nSrc; i++){ mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect); mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn); } } pS = pS->pPrior; } return mask; } /* ** Expression pExpr is one operand of a comparison operator that might ** be useful for indexing. This routine checks to see if pExpr appears ** in any index. Return TRUE (1) if pExpr is an indexed term and return ** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor ** number of the table that is indexed and *piColumn to the column number ** of the column that is indexed, or XN_EXPR (-2) if an expression is being ** indexed. ** ** If pExpr is a TK_COLUMN column reference, then this routine always returns ** true even if that particular column is not indexed, because the column ** might be added to an automatic index later. */ static int exprMightBeIndexed( SrcList *pFrom, /* The FROM clause */ int op, /* The specific comparison operator */ Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ Expr *pExpr, /* An operand of a comparison operator */ int *piCur, /* Write the referenced table cursor number here */ int *piColumn /* Write the referenced table column number here */ ){ Index *pIdx; int i; int iCur; /* If this expression is a vector to the left or right of a ** inequality constraint (>, <, >= or <=), perform the processing ** on the first element of the vector. */ assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE ); assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE ); assert( op<=TK_GE ); if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){ pExpr = pExpr->x.pList->a[0].pExpr; } if( pExpr->op==TK_COLUMN ){ *piCur = pExpr->iTable; *piColumn = pExpr->iColumn; return 1; } if( mPrereq==0 ) return 0; /* No table references */ if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */ for(i=0; mPrereq>1; i++, mPrereq>>=1){} iCur = pFrom->a[i].iCursor; for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->aColExpr==0 ) continue; for(i=0; i<pIdx->nKeyCol; i++){ if( pIdx->aiColumn[i]!=XN_EXPR ) continue; if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){ *piCur = iCur; *piColumn = XN_EXPR; return 1; } } } return 0; } /* ** The input to this routine is an WhereTerm structure with only the ** "pExpr" field filled in. The job of this routine is to analyze the ** subexpression and populate all the other fields of the WhereTerm ** structure. ** ** If the expression is of the form "<expr> <op> X" it gets commuted ** to the standard form of "X <op> <expr>". ** ** If the expression is of the form "X <op> Y" where both X and Y are ** columns, then the original expression is unchanged and a new virtual ** term of the form "Y <op> X" is added to the WHERE clause and ** analyzed separately. The original term is marked with TERM_COPIED ** and the new term is marked with TERM_DYNAMIC (because it's pExpr ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it ** is a commuted copy of a prior term.) The original term has nChild=1 ** and the copy has idxParent set to the index of the original term. */ static void exprAnalyze( SrcList *pSrc, /* the FROM clause */ WhereClause *pWC, /* the WHERE clause */ int idxTerm /* Index of the term to be analyzed */ ){ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ WhereTerm *pTerm; /* The term to be analyzed */ WhereMaskSet *pMaskSet; /* Set of table index masks */ Expr *pExpr; /* The expression to be analyzed */ Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ Bitmask prereqAll; /* Prerequesites of pExpr */ Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ int noCase = 0; /* uppercase equivalent to lowercase */ int op; /* Top-level operator. pExpr->op */ Parse *pParse = pWInfo->pParse; /* Parsing context */ sqlite3 *db = pParse->db; /* Database connection */ unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */ int nLeft; /* Number of elements on left side vector */ if( db->mallocFailed ){ return; } pTerm = &pWC->a[idxTerm]; pMaskSet = &pWInfo->sMaskSet; pExpr = pTerm->pExpr; assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); op = pExpr->op; if( op==TK_IN ){ assert( pExpr->pRight==0 ); if( sqlite3ExprCheckIN(pParse, pExpr) ) return; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect); }else{ pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList); } }else if( op==TK_ISNULL ){ pTerm->prereqRight = 0; }else{ pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight); } prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr); if( ExprHasProperty(pExpr, EP_FromJoin) ){ Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable); prereqAll |= x; extraRight = x-1; /* ON clause terms may not be used with an index ** on left table of a LEFT JOIN. Ticket #3015 */ if( (prereqAll>>1)>=x ){ sqlite3ErrorMsg(pParse, "ON clause references tables to its right"); return; } } pTerm->prereqAll = prereqAll; pTerm->leftCursor = -1; pTerm->iParent = -1; pTerm->eOperator = 0; if( allowedOp(op) ){ int iCur, iColumn; Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; if( pTerm->iField>0 ){ assert( op==TK_IN ); assert( pLeft->op==TK_VECTOR ); pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr; } if( exprMightBeIndexed(pSrc, op, prereqLeft, pLeft, &iCur, &iColumn) ){ pTerm->leftCursor = iCur; pTerm->u.leftColumn = iColumn; pTerm->eOperator = operatorMask(op) & opMask; } if( op==TK_IS ) pTerm->wtFlags |= TERM_IS; if( pRight && exprMightBeIndexed(pSrc, op, pTerm->prereqRight, pRight, &iCur,&iColumn) ){ WhereTerm *pNew; Expr *pDup; u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ assert( pTerm->iField==0 ); if( pTerm->leftCursor>=0 ){ int idxNew; pDup = sqlite3ExprDup(db, pExpr, 0); if( db->mallocFailed ){ sqlite3ExprDelete(db, pDup); return; } idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); if( idxNew==0 ) return; pNew = &pWC->a[idxNew]; markTermAsChild(pWC, idxNew, idxTerm); if( op==TK_IS ) pNew->wtFlags |= TERM_IS; pTerm = &pWC->a[idxTerm]; pTerm->wtFlags |= TERM_COPIED; if( termIsEquivalence(pParse, pDup) ){ pTerm->eOperator |= WO_EQUIV; eExtraOp = WO_EQUIV; } }else{ pDup = pExpr; pNew = pTerm; } exprCommute(pParse, pDup); pNew->leftCursor = iCur; pNew->u.leftColumn = iColumn; testcase( (prereqLeft | extraRight) != prereqLeft ); pNew->prereqRight = prereqLeft | extraRight; pNew->prereqAll = prereqAll; pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask; } } #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION /* If a term is the BETWEEN operator, create two new virtual terms ** that define the range that the BETWEEN implements. For example: ** ** a BETWEEN b AND c ** ** is converted into: ** ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) ** ** The two new terms are added onto the end of the WhereClause object. ** The new terms are "dynamic" and are children of the original BETWEEN ** term. That means that if the BETWEEN term is coded, the children are ** skipped. Or, if the children are satisfied by an index, the original ** BETWEEN term is skipped. */ else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ ExprList *pList = pExpr->x.pList; int i; static const u8 ops[] = {TK_GE, TK_LE}; assert( pList!=0 ); assert( pList->nExpr==2 ); for(i=0; i<2; i++){ Expr *pNewExpr; int idxNew; pNewExpr = sqlite3PExpr(pParse, ops[i], sqlite3ExprDup(db, pExpr->pLeft, 0), sqlite3ExprDup(db, pList->a[i].pExpr, 0)); transferJoinMarkings(pNewExpr, pExpr); idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); exprAnalyze(pSrc, pWC, idxNew); pTerm = &pWC->a[idxTerm]; markTermAsChild(pWC, idxNew, idxTerm); } } #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) /* Analyze a term that is composed of two or more subterms connected by ** an OR operator. */ else if( pExpr->op==TK_OR ){ assert( pWC->op==TK_AND ); exprAnalyzeOrTerm(pSrc, pWC, idxTerm); pTerm = &pWC->a[idxTerm]; } #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION /* Add constraints to reduce the search space on a LIKE or GLOB ** operator. ** ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints ** ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%' ** ** The last character of the prefix "abc" is incremented to form the ** termination condition "abd". If case is not significant (the default ** for LIKE) then the lower-bound is made all uppercase and the upper- ** bound is made all lowercase so that the bounds also work when comparing ** BLOBs. */ if( pWC->op==TK_AND && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) ){ Expr *pLeft; /* LHS of LIKE/GLOB operator */ Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ Expr *pNewExpr1; Expr *pNewExpr2; int idxNew1; int idxNew2; const char *zCollSeqName; /* Name of collating sequence */ const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC; pLeft = pExpr->x.pList->a[1].pExpr; pStr2 = sqlite3ExprDup(db, pStr1, 0); /* Convert the lower bound to upper-case and the upper bound to ** lower-case (upper-case is less than lower-case in ASCII) so that ** the range constraints also work for BLOBs */ if( noCase && !pParse->db->mallocFailed ){ int i; char c; pTerm->wtFlags |= TERM_LIKE; for(i=0; (c = pStr1->u.zToken[i])!=0; i++){ pStr1->u.zToken[i] = sqlite3Toupper(c); pStr2->u.zToken[i] = sqlite3Tolower(c); } } if( !db->mallocFailed ){ u8 c, *pC; /* Last character before the first wildcard */ pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; c = *pC; if( noCase ){ /* The point is to increment the last character before the first ** wildcard. But if we increment '@', that will push it into the ** alphabetic range where case conversions will mess up the ** inequality. To avoid this, make sure to also run the full ** LIKE on all candidate expressions by clearing the isComplete flag */ if( c=='A'-1 ) isComplete = 0; c = sqlite3UpperToLower[c]; } *pC = c + 1; } zCollSeqName = noCase ? "NOCASE" : "BINARY"; pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName), pStr1); transferJoinMarkings(pNewExpr1, pExpr); idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags); testcase( idxNew1==0 ); exprAnalyze(pSrc, pWC, idxNew1); pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), pStr2); transferJoinMarkings(pNewExpr2, pExpr); idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags); testcase( idxNew2==0 ); exprAnalyze(pSrc, pWC, idxNew2); pTerm = &pWC->a[idxTerm]; if( isComplete ){ markTermAsChild(pWC, idxNew1, idxTerm); markTermAsChild(pWC, idxNew2, idxTerm); } } #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Add a WO_MATCH auxiliary term to the constraint set if the ** current expression is of the form: column MATCH expr. ** This information is used by the xBestIndex methods of ** virtual tables. The native query optimizer does not attempt ** to do anything with MATCH functions. */ if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){ int idxNew; Expr *pRight, *pLeft; WhereTerm *pNewTerm; Bitmask prereqColumn, prereqExpr; pRight = pExpr->x.pList->a[0].pExpr; pLeft = pExpr->x.pList->a[1].pExpr; prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight); prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft); if( (prereqExpr & prereqColumn)==0 ){ Expr *pNewExpr; pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 0, sqlite3ExprDup(db, pRight, 0)); idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); pNewTerm = &pWC->a[idxNew]; pNewTerm->prereqRight = prereqExpr; pNewTerm->leftCursor = pLeft->iTable; pNewTerm->u.leftColumn = pLeft->iColumn; pNewTerm->eOperator = WO_MATCH; pNewTerm->eMatchOp = eOp2; markTermAsChild(pWC, idxNew, idxTerm); pTerm = &pWC->a[idxTerm]; pTerm->wtFlags |= TERM_COPIED; pNewTerm->prereqAll = pTerm->prereqAll; } } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create ** new terms for each component comparison - "a = ?" and "b = ?". The ** new terms completely replace the original vector comparison, which is ** no longer used. ** ** This is only required if at least one side of the comparison operation ** is not a sub-select. */ if( pWC->op==TK_AND && (pExpr->op==TK_EQ || pExpr->op==TK_IS) && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 || (pExpr->pRight->flags & EP_xIsSelect)==0) ){ int i; for(i=0; i<nLeft; i++){ int idxNew; Expr *pNew; Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i); Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i); pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight); transferJoinMarkings(pNew, pExpr); idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC); exprAnalyze(pSrc, pWC, idxNew); } pTerm = &pWC->a[idxTerm]; pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */ pTerm->eOperator = 0; } /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create ** a virtual term for each vector component. The expression object ** used by each such virtual term is pExpr (the full vector IN(...) ** expression). The WhereTerm.iField variable identifies the index within ** the vector on the LHS that the virtual term represents. ** ** This only works if the RHS is a simple SELECT, not a compound */ if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0 && pExpr->pLeft->op==TK_VECTOR && pExpr->x.pSelect->pPrior==0 ){ int i; for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){ int idxNew; idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL); pWC->a[idxNew].iField = i+1; exprAnalyze(pSrc, pWC, idxNew); markTermAsChild(pWC, idxNew, idxTerm); } } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* When sqlite_stat3 histogram data is available an operator of the ** form "x IS NOT NULL" can sometimes be evaluated more efficiently ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a ** virtual term of that form. ** ** Note that the virtual term must be tagged with TERM_VNULL. */ if( pExpr->op==TK_NOTNULL && pExpr->pLeft->op==TK_COLUMN && pExpr->pLeft->iColumn>=0 && OptimizationEnabled(db, SQLITE_Stat34) ){ Expr *pNewExpr; Expr *pLeft = pExpr->pLeft; int idxNew; WhereTerm *pNewTerm; pNewExpr = sqlite3PExpr(pParse, TK_GT, sqlite3ExprDup(db, pLeft, 0), sqlite3ExprAlloc(db, TK_NULL, 0, 0)); idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); if( idxNew ){ pNewTerm = &pWC->a[idxNew]; pNewTerm->prereqRight = 0; pNewTerm->leftCursor = pLeft->iTable; pNewTerm->u.leftColumn = pLeft->iColumn; pNewTerm->eOperator = WO_GT; markTermAsChild(pWC, idxNew, idxTerm); pTerm = &pWC->a[idxTerm]; pTerm->wtFlags |= TERM_COPIED; pNewTerm->prereqAll = pTerm->prereqAll; } } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* Prevent ON clause terms of a LEFT JOIN from being used to drive ** an index for tables to the left of the join. */ testcase( pTerm!=&pWC->a[idxTerm] ); pTerm = &pWC->a[idxTerm]; pTerm->prereqRight |= extraRight; } /*************************************************************************** ** Routines with file scope above. Interface to the rest of the where.c ** subsystem follows. ***************************************************************************/ /* ** This routine identifies subexpressions in the WHERE clause where ** each subexpression is separated by the AND operator or some other ** operator specified in the op parameter. The WhereClause structure ** is filled with pointers to subexpressions. For example: ** ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) ** \________/ \_______________/ \________________/ ** slot[0] slot[1] slot[2] ** ** The original WHERE clause in pExpr is unaltered. All this routine ** does is make slot[] entries point to substructure within pExpr. ** ** In the previous sentence and in the diagram, "slot[]" refers to ** the WhereClause.a[] array. The slot[] array grows as needed to contain ** all terms of the WHERE clause. */ SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ Expr *pE2 = sqlite3ExprSkipCollate(pExpr); pWC->op = op; if( pE2==0 ) return; if( pE2->op!=op ){ whereClauseInsert(pWC, pExpr, 0); }else{ sqlite3WhereSplit(pWC, pE2->pLeft, op); sqlite3WhereSplit(pWC, pE2->pRight, op); } } /* ** Initialize a preallocated WhereClause structure. */ SQLITE_PRIVATE void sqlite3WhereClauseInit( WhereClause *pWC, /* The WhereClause to be initialized */ WhereInfo *pWInfo /* The WHERE processing context */ ){ pWC->pWInfo = pWInfo; pWC->pOuter = 0; pWC->nTerm = 0; pWC->nSlot = ArraySize(pWC->aStatic); pWC->a = pWC->aStatic; } /* ** Deallocate a WhereClause structure. The WhereClause structure ** itself is not freed. This routine is the inverse of ** sqlite3WhereClauseInit(). */ SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){ int i; WhereTerm *a; sqlite3 *db = pWC->pWInfo->pParse->db; for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ if( a->wtFlags & TERM_DYNAMIC ){ sqlite3ExprDelete(db, a->pExpr); } if( a->wtFlags & TERM_ORINFO ){ whereOrInfoDelete(db, a->u.pOrInfo); }else if( a->wtFlags & TERM_ANDINFO ){ whereAndInfoDelete(db, a->u.pAndInfo); } } if( pWC->a!=pWC->aStatic ){ sqlite3DbFree(db, pWC->a); } } /* ** These routines walk (recursively) an expression tree and generate ** a bitmask indicating which tables are used in that expression ** tree. */ SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ Bitmask mask; if( p==0 ) return 0; if( p->op==TK_COLUMN ){ mask = sqlite3WhereGetMask(pMaskSet, p->iTable); return mask; } assert( !ExprHasProperty(p, EP_TokenOnly) ); mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0; if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft); if( ExprHasProperty(p, EP_xIsSelect) ){ mask |= exprSelectUsage(pMaskSet, p->x.pSelect); }else if( p->x.pList ){ mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList); } return mask; } SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){ int i; Bitmask mask = 0; if( pList ){ for(i=0; i<pList->nExpr; i++){ mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr); } } return mask; } /* ** Call exprAnalyze on all terms in a WHERE clause. ** ** Note that exprAnalyze() might add new virtual terms onto the ** end of the WHERE clause. We do not want to analyze these new ** virtual terms, so start analyzing at the end and work forward ** so that the added virtual terms are never processed. */ SQLITE_PRIVATE void sqlite3WhereExprAnalyze( SrcList *pTabList, /* the FROM clause */ WhereClause *pWC /* the WHERE clause to be analyzed */ ){ int i; for(i=pWC->nTerm-1; i>=0; i--){ exprAnalyze(pTabList, pWC, i); } } /* ** For table-valued-functions, transform the function arguments into ** new WHERE clause terms. ** ** Each function argument translates into an equality constraint against ** a HIDDEN column in the table. */ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( Parse *pParse, /* Parsing context */ struct SrcList_item *pItem, /* The FROM clause term to process */ WhereClause *pWC /* Xfer function arguments to here */ ){ Table *pTab; int j, k; ExprList *pArgs; Expr *pColRef; Expr *pTerm; if( pItem->fg.isTabFunc==0 ) return; pTab = pItem->pTab; assert( pTab!=0 ); pArgs = pItem->u1.pFuncArg; if( pArgs==0 ) return; for(j=k=0; j<pArgs->nExpr; j++){ while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;} if( k>=pTab->nCol ){ sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d", pTab->zName, j); return; } pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); if( pColRef==0 ) return; pColRef->iTable = pItem->iCursor; pColRef->iColumn = k++; pColRef->pTab = pTab; pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0)); whereClauseInsert(pWC, pTerm, TERM_DYNAMIC); } } /************** End of whereexpr.c *******************************************/ /************** Begin file where.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This module contains C code that generates VDBE code used to process ** the WHERE clause of SQL statements. This module is responsible for ** generating the code that loops through a table looking for applicable ** rows. Indices are selected and used to speed the search when doing ** so is applicable. Because this module is responsible for selecting ** indices, you might also think of this module as the "query optimizer". */ /* #include "sqliteInt.h" */ /* #include "whereInt.h" */ /* Forward declaration of methods */ static int whereLoopResize(sqlite3*, WhereLoop*, int); /* Test variable that can be set to enable WHERE tracing */ #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) /***/ int sqlite3WhereTrace = 0; #endif /* ** Return the estimated number of output rows from a WHERE clause */ SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ return pWInfo->nRowOut; } /* ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this ** WHERE clause returns outputs for DISTINCT processing. */ SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ return pWInfo->eDistinct; } /* ** Return TRUE if the WHERE clause returns rows in ORDER BY order. ** Return FALSE if the output needs to be sorted. */ SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ return pWInfo->nOBSat; } /* ** Return TRUE if the innermost loop of the WHERE clause implementation ** returns rows in ORDER BY order for complete run of the inner loop. ** ** Across multiple iterations of outer loops, the output rows need not be ** sorted. As long as rows are sorted for just the innermost loop, this ** routine can return TRUE. */ SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){ return pWInfo->bOrderedInnerLoop; } /* ** Return the VDBE address or label to jump to in order to continue ** immediately with the next row of a WHERE clause. */ SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ assert( pWInfo->iContinue!=0 ); return pWInfo->iContinue; } /* ** Return the VDBE address or label to jump to in order to break ** out of a WHERE loop. */ SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ return pWInfo->iBreak; } /* ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to ** operate directly on the rowis returned by a WHERE clause. Return ** ONEPASS_SINGLE (1) if the statement can operation directly because only ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass ** optimization can be used on multiple ** ** If the ONEPASS optimization is used (if this routine returns true) ** then also write the indices of open cursors used by ONEPASS ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data ** table and iaCur[1] gets the cursor used by an auxiliary index. ** Either value may be -1, indicating that cursor is not used. ** Any cursors returned will have been opened for writing. ** ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is ** unable to use the ONEPASS optimization. */ SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); #ifdef WHERETRACE_ENABLED if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ sqlite3DebugPrintf("%s cursors: %d %d\n", pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI", aiCur[0], aiCur[1]); } #endif return pWInfo->eOnePass; } /* ** Move the content of pSrc into pDest */ static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ pDest->n = pSrc->n; memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); } /* ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet. ** ** The new entry might overwrite an existing entry, or it might be ** appended, or it might be discarded. Do whatever is the right thing ** so that pSet keeps the N_OR_COST best entries seen so far. */ static int whereOrInsert( WhereOrSet *pSet, /* The WhereOrSet to be updated */ Bitmask prereq, /* Prerequisites of the new entry */ LogEst rRun, /* Run-cost of the new entry */ LogEst nOut /* Number of outputs for the new entry */ ){ u16 i; WhereOrCost *p; for(i=pSet->n, p=pSet->a; i>0; i--, p++){ if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){ goto whereOrInsert_done; } if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){ return 0; } } if( pSet->n<N_OR_COST ){ p = &pSet->a[pSet->n++]; p->nOut = nOut; }else{ p = pSet->a; for(i=1; i<pSet->n; i++){ if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i; } if( p->rRun<=rRun ) return 0; } whereOrInsert_done: p->prereq = prereq; p->rRun = rRun; if( p->nOut>nOut ) p->nOut = nOut; return 1; } /* ** Return the bitmask for the given cursor number. Return 0 if ** iCursor is not in the set. */ SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ int i; assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); for(i=0; i<pMaskSet->n; i++){ if( pMaskSet->ix[i]==iCursor ){ return MASKBIT(i); } } return 0; } /* ** Create a new mask for cursor iCursor. ** ** There is one cursor per table in the FROM clause. The number of ** tables in the FROM clause is limited by a test early in the ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] ** array will never overflow. */ static void createMask(WhereMaskSet *pMaskSet, int iCursor){ assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); pMaskSet->ix[pMaskSet->n++] = iCursor; } /* ** Advance to the next WhereTerm that matches according to the criteria ** established when the pScan object was initialized by whereScanInit(). ** Return NULL if there are no more matching WhereTerms. */ static WhereTerm *whereScanNext(WhereScan *pScan){ int iCur; /* The cursor on the LHS of the term */ i16 iColumn; /* The column on the LHS of the term. -1 for IPK */ Expr *pX; /* An expression being tested */ WhereClause *pWC; /* Shorthand for pScan->pWC */ WhereTerm *pTerm; /* The term being tested */ int k = pScan->k; /* Where to start scanning */ assert( pScan->iEquiv<=pScan->nEquiv ); pWC = pScan->pWC; while(1){ iColumn = pScan->aiColumn[pScan->iEquiv-1]; iCur = pScan->aiCur[pScan->iEquiv-1]; assert( pWC!=0 ); do{ for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){ if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn && (iColumn!=XN_EXPR || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0) && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin)) ){ if( (pTerm->eOperator & WO_EQUIV)!=0 && pScan->nEquiv<ArraySize(pScan->aiCur) && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN ){ int j; for(j=0; j<pScan->nEquiv; j++){ if( pScan->aiCur[j]==pX->iTable && pScan->aiColumn[j]==pX->iColumn ){ break; } } if( j==pScan->nEquiv ){ pScan->aiCur[j] = pX->iTable; pScan->aiColumn[j] = pX->iColumn; pScan->nEquiv++; } } if( (pTerm->eOperator & pScan->opMask)!=0 ){ /* Verify the affinity and collating sequence match */ if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ CollSeq *pColl; Parse *pParse = pWC->pWInfo->pParse; pX = pTerm->pExpr; if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ continue; } assert(pX->pLeft); pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); if( pColl==0 ) pColl = pParse->db->pDfltColl; if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ continue; } } if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN && pX->iTable==pScan->aiCur[0] && pX->iColumn==pScan->aiColumn[0] ){ testcase( pTerm->eOperator & WO_IS ); continue; } pScan->pWC = pWC; pScan->k = k+1; return pTerm; } } } pWC = pWC->pOuter; k = 0; }while( pWC!=0 ); if( pScan->iEquiv>=pScan->nEquiv ) break; pWC = pScan->pOrigWC; k = 0; pScan->iEquiv++; } return 0; } /* ** Initialize a WHERE clause scanner object. Return a pointer to the ** first match. Return NULL if there are no matches. ** ** The scanner will be searching the WHERE clause pWC. It will look ** for terms of the form "X <op> <expr>" where X is column iColumn of table ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx ** must be one of the indexes of table iCur. ** ** The <op> must be one of the operators described by opMask. ** ** If the search is for X and the WHERE clause contains terms of the ** form X=Y then this routine might also return terms of the form ** "Y <op> <expr>". The number of levels of transitivity is limited, ** but is enough to handle most commonly occurring SQL statements. ** ** If X is not the INTEGER PRIMARY KEY then X must be compatible with ** index pIdx. */ static WhereTerm *whereScanInit( WhereScan *pScan, /* The WhereScan object being initialized */ WhereClause *pWC, /* The WHERE clause to be scanned */ int iCur, /* Cursor to scan for */ int iColumn, /* Column to scan for */ u32 opMask, /* Operator(s) to scan for */ Index *pIdx /* Must be compatible with this index */ ){ pScan->pOrigWC = pWC; pScan->pWC = pWC; pScan->pIdxExpr = 0; pScan->idxaff = 0; pScan->zCollName = 0; if( pIdx ){ int j = iColumn; iColumn = pIdx->aiColumn[j]; if( iColumn==XN_EXPR ){ pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; pScan->zCollName = pIdx->azColl[j]; }else if( iColumn==pIdx->pTable->iPKey ){ iColumn = XN_ROWID; }else if( iColumn>=0 ){ pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; pScan->zCollName = pIdx->azColl[j]; } }else if( iColumn==XN_EXPR ){ return 0; } pScan->opMask = opMask; pScan->k = 0; pScan->aiCur[0] = iCur; pScan->aiColumn[0] = iColumn; pScan->nEquiv = 1; pScan->iEquiv = 1; return whereScanNext(pScan); } /* ** Search for a term in the WHERE clause that is of the form "X <op> <expr>" ** where X is a reference to the iColumn of table iCur or of index pIdx ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by ** the op parameter. Return a pointer to the term. Return 0 if not found. ** ** If pIdx!=0 then it must be one of the indexes of table iCur. ** Search for terms matching the iColumn-th column of pIdx ** rather than the iColumn-th column of table iCur. ** ** The term returned might by Y=<expr> if there is another constraint in ** the WHERE clause that specifies that X=Y. Any such constraints will be ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10 ** other equivalent values. Hence a search for X will return <expr> if X=A1 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>. ** ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>" ** then try for the one with no dependencies on <expr> - in other words where ** <expr> is a constant expression of some kind. Only return entries of ** the form "X <op> Y" where Y is a column in another table if no terms of ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS ** exist, try to return a term that does not use WO_EQUIV. */ SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( WhereClause *pWC, /* The WHERE clause to be searched */ int iCur, /* Cursor number of LHS */ int iColumn, /* Column number of LHS */ Bitmask notReady, /* RHS must not overlap with this mask */ u32 op, /* Mask of WO_xx values describing operator */ Index *pIdx /* Must be compatible with this index, if not NULL */ ){ WhereTerm *pResult = 0; WhereTerm *p; WhereScan scan; p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); op &= WO_EQ|WO_IS; while( p ){ if( (p->prereqRight & notReady)==0 ){ if( p->prereqRight==0 && (p->eOperator&op)!=0 ){ testcase( p->eOperator & WO_IS ); return p; } if( pResult==0 ) pResult = p; } p = whereScanNext(&scan); } return pResult; } /* ** This function searches pList for an entry that matches the iCol-th column ** of index pIdx. ** ** If such an expression is found, its index in pList->a[] is returned. If ** no expression is found, -1 is returned. */ static int findIndexCol( Parse *pParse, /* Parse context */ ExprList *pList, /* Expression list to search */ int iBase, /* Cursor for table associated with pIdx */ Index *pIdx, /* Index to match column of */ int iCol /* Column of index to match */ ){ int i; const char *zColl = pIdx->azColl[iCol]; for(i=0; i<pList->nExpr; i++){ Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr); if( p->op==TK_COLUMN && p->iColumn==pIdx->aiColumn[iCol] && p->iTable==iBase ){ CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){ return i; } } } return -1; } /* ** Return TRUE if the iCol-th column of index pIdx is NOT NULL */ static int indexColumnNotNull(Index *pIdx, int iCol){ int j; assert( pIdx!=0 ); assert( iCol>=0 && iCol<pIdx->nColumn ); j = pIdx->aiColumn[iCol]; if( j>=0 ){ return pIdx->pTable->aCol[j].notNull; }else if( j==(-1) ){ return 1; }else{ assert( j==(-2) ); return 0; /* Assume an indexed expression can always yield a NULL */ } } /* ** Return true if the DISTINCT expression-list passed as the third argument ** is redundant. ** ** A DISTINCT list is redundant if any subset of the columns in the ** DISTINCT list are collectively unique and individually non-null. */ static int isDistinctRedundant( Parse *pParse, /* Parsing context */ SrcList *pTabList, /* The FROM clause */ WhereClause *pWC, /* The WHERE clause */ ExprList *pDistinct /* The result set that needs to be DISTINCT */ ){ Table *pTab; Index *pIdx; int i; int iBase; /* If there is more than one table or sub-select in the FROM clause of ** this query, then it will not be possible to show that the DISTINCT ** clause is redundant. */ if( pTabList->nSrc!=1 ) return 0; iBase = pTabList->a[0].iCursor; pTab = pTabList->a[0].pTab; /* If any of the expressions is an IPK column on table iBase, then return ** true. Note: The (p->iTable==iBase) part of this test may be false if the ** current SELECT is a correlated sub-query. */ for(i=0; i<pDistinct->nExpr; i++){ Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr); if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1; } /* Loop through all indices on the table, checking each to see if it makes ** the DISTINCT qualifier redundant. It does so if: ** ** 1. The index is itself UNIQUE, and ** ** 2. All of the columns in the index are either part of the pDistinct ** list, or else the WHERE clause contains a term of the form "col=X", ** where X is a constant value. The collation sequences of the ** comparison and select-list expressions must match those of the index. ** ** 3. All of those index columns for which the WHERE clause does not ** contain a "col=X" term are subject to a NOT NULL constraint. */ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( !IsUniqueIndex(pIdx) ) continue; for(i=0; i<pIdx->nKeyCol; i++){ if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){ if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break; if( indexColumnNotNull(pIdx, i)==0 ) break; } } if( i==pIdx->nKeyCol ){ /* This index implies that the DISTINCT qualifier is redundant. */ return 1; } } return 0; } /* ** Estimate the logarithm of the input value to base 2. */ static LogEst estLog(LogEst N){ return N<=10 ? 0 : sqlite3LogEst(N) - 33; } /* ** Convert OP_Column opcodes to OP_Copy in previously generated code. ** ** This routine runs over generated VDBE code and translates OP_Column ** opcodes into OP_Copy when the table is being accessed via co-routine ** instead of via table lookup. ** ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero, ** then each OP_Rowid is transformed into an instruction to increment the ** value stored in its output register. */ static void translateColumnToCopy( Vdbe *v, /* The VDBE containing code to translate */ int iStart, /* Translate from this opcode to the end */ int iTabCur, /* OP_Column/OP_Rowid references to this table */ int iRegister, /* The first column is in this register */ int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */ ){ VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart); int iEnd = sqlite3VdbeCurrentAddr(v); for(; iStart<iEnd; iStart++, pOp++){ if( pOp->p1!=iTabCur ) continue; if( pOp->opcode==OP_Column ){ pOp->opcode = OP_Copy; pOp->p1 = pOp->p2 + iRegister; pOp->p2 = pOp->p3; pOp->p3 = 0; }else if( pOp->opcode==OP_Rowid ){ if( bIncrRowid ){ /* Increment the value stored in the P2 operand of the OP_Rowid. */ pOp->opcode = OP_AddImm; pOp->p1 = pOp->p2; pOp->p2 = 1; }else{ pOp->opcode = OP_Null; pOp->p1 = 0; pOp->p3 = 0; } } } } /* ** Two routines for printing the content of an sqlite3_index_info ** structure. Used for testing and debugging only. If neither ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines ** are no-ops. */ #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ int i; if( !sqlite3WhereTrace ) return; for(i=0; i<p->nConstraint; i++){ sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", i, p->aConstraint[i].iColumn, p->aConstraint[i].iTermOffset, p->aConstraint[i].op, p->aConstraint[i].usable); } for(i=0; i<p->nOrderBy; i++){ sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", i, p->aOrderBy[i].iColumn, p->aOrderBy[i].desc); } } static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ int i; if( !sqlite3WhereTrace ) return; for(i=0; i<p->nConstraint; i++){ sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", i, p->aConstraintUsage[i].argvIndex, p->aConstraintUsage[i].omit); } sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); } #else #define TRACE_IDX_INPUTS(A) #define TRACE_IDX_OUTPUTS(A) #endif #ifndef SQLITE_OMIT_AUTOMATIC_INDEX /* ** Return TRUE if the WHERE clause term pTerm is of a form where it ** could be used with an index to access pSrc, assuming an appropriate ** index existed. */ static int termCanDriveIndex( WhereTerm *pTerm, /* WHERE clause term to check */ struct SrcList_item *pSrc, /* Table we are trying to access */ Bitmask notReady /* Tables in outer loops of the join */ ){ char aff; if( pTerm->leftCursor!=pSrc->iCursor ) return 0; if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0; if( (pTerm->prereqRight & notReady)!=0 ) return 0; if( pTerm->u.leftColumn<0 ) return 0; aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; testcase( pTerm->pExpr->op==TK_IS ); return 1; } #endif #ifndef SQLITE_OMIT_AUTOMATIC_INDEX /* ** Generate code to construct the Index object for an automatic index ** and to set up the WhereLevel object pLevel so that the code generator ** makes use of the automatic index. */ static void constructAutomaticIndex( Parse *pParse, /* The parsing context */ WhereClause *pWC, /* The WHERE clause */ struct SrcList_item *pSrc, /* The FROM clause term to get the next index */ Bitmask notReady, /* Mask of cursors that are not available */ WhereLevel *pLevel /* Write new index here */ ){ int nKeyCol; /* Number of columns in the constructed index */ WhereTerm *pTerm; /* A single term of the WHERE clause */ WhereTerm *pWCEnd; /* End of pWC->a[] */ Index *pIdx; /* Object describing the transient index */ Vdbe *v; /* Prepared statement under construction */ int addrInit; /* Address of the initialization bypass jump */ Table *pTable; /* The table being indexed */ int addrTop; /* Top of the index fill loop */ int regRecord; /* Register holding an index record */ int n; /* Column counter */ int i; /* Loop counter */ int mxBitCol; /* Maximum column in pSrc->colUsed */ CollSeq *pColl; /* Collating sequence to on a column */ WhereLoop *pLoop; /* The Loop object */ char *zNotUsed; /* Extra space on the end of pIdx */ Bitmask idxCols; /* Bitmap of columns used for indexing */ Bitmask extraCols; /* Bitmap of additional columns */ u8 sentWarning = 0; /* True if a warnning has been issued */ Expr *pPartial = 0; /* Partial Index Expression */ int iContinue = 0; /* Jump here to skip excluded rows */ struct SrcList_item *pTabItem; /* FROM clause term being indexed */ int addrCounter = 0; /* Address where integer counter is initialized */ int regBase; /* Array of registers where record is assembled */ /* Generate code to skip over the creation and initialization of the ** transient index on 2nd and subsequent iterations of the loop. */ v = pParse->pVdbe; assert( v!=0 ); addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); /* Count the number of columns that will be added to the index ** and used to match WHERE clause constraints */ nKeyCol = 0; pTable = pSrc->pTab; pWCEnd = &pWC->a[pWC->nTerm]; pLoop = pLevel->pWLoop; idxCols = 0; for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ Expr *pExpr = pTerm->pExpr; assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */ || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */ || pLoop->prereq!=0 ); /* table of a LEFT JOIN */ if( pLoop->prereq==0 && (pTerm->wtFlags & TERM_VIRTUAL)==0 && !ExprHasProperty(pExpr, EP_FromJoin) && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){ pPartial = sqlite3ExprAnd(pParse->db, pPartial, sqlite3ExprDup(pParse->db, pExpr, 0)); } if( termCanDriveIndex(pTerm, pSrc, notReady) ){ int iCol = pTerm->u.leftColumn; Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); testcase( iCol==BMS ); testcase( iCol==BMS-1 ); if( !sentWarning ){ sqlite3_log(SQLITE_WARNING_AUTOINDEX, "automatic index on %s(%s)", pTable->zName, pTable->aCol[iCol].zName); sentWarning = 1; } if( (idxCols & cMask)==0 ){ if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){ goto end_auto_index_create; } pLoop->aLTerm[nKeyCol++] = pTerm; idxCols |= cMask; } } } assert( nKeyCol>0 ); pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED | WHERE_AUTO_INDEX; /* Count the number of additional columns needed to create a ** covering index. A "covering index" is an index that contains all ** columns that are needed by the query. With a covering index, the ** original table never needs to be accessed. Automatic indices must ** be a covering index because the index will not be updated if the ** original table changes and the index and table cannot both be used ** if they go out of sync. */ extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); mxBitCol = MIN(BMS-1,pTable->nCol); testcase( pTable->nCol==BMS-1 ); testcase( pTable->nCol==BMS-2 ); for(i=0; i<mxBitCol; i++){ if( extraCols & MASKBIT(i) ) nKeyCol++; } if( pSrc->colUsed & MASKBIT(BMS-1) ){ nKeyCol += pTable->nCol - BMS + 1; } /* Construct the Index object to describe this index */ pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); if( pIdx==0 ) goto end_auto_index_create; pLoop->u.btree.pIndex = pIdx; pIdx->zName = "auto-index"; pIdx->pTable = pTable; n = 0; idxCols = 0; for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ if( termCanDriveIndex(pTerm, pSrc, notReady) ){ int iCol = pTerm->u.leftColumn; Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); testcase( iCol==BMS-1 ); testcase( iCol==BMS ); if( (idxCols & cMask)==0 ){ Expr *pX = pTerm->pExpr; idxCols |= cMask; pIdx->aiColumn[n] = pTerm->u.leftColumn; pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; n++; } } } assert( (u32)n==pLoop->u.btree.nEq ); /* Add additional columns needed to make the automatic index into ** a covering index */ for(i=0; i<mxBitCol; i++){ if( extraCols & MASKBIT(i) ){ pIdx->aiColumn[n] = i; pIdx->azColl[n] = sqlite3StrBINARY; n++; } } if( pSrc->colUsed & MASKBIT(BMS-1) ){ for(i=BMS-1; i<pTable->nCol; i++){ pIdx->aiColumn[n] = i; pIdx->azColl[n] = sqlite3StrBINARY; n++; } } assert( n==nKeyCol ); pIdx->aiColumn[n] = XN_ROWID; pIdx->azColl[n] = sqlite3StrBINARY; /* Create the automatic index */ assert( pLevel->iIdxCur>=0 ); pLevel->iIdxCur = pParse->nTab++; sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "for %s", pTable->zName)); /* Fill the automatic index with content */ sqlite3ExprCachePush(pParse); pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom]; if( pTabItem->fg.viaCoroutine ){ int regYield = pTabItem->regReturn; addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0); sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield); VdbeCoverage(v); VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); }else{ addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); } if( pPartial ){ iContinue = sqlite3VdbeMakeLabel(v); sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL); pLoop->wsFlags |= WHERE_PARTIALIDX; } regRecord = sqlite3GetTempReg(pParse); regBase = sqlite3GenerateIndexKey( pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 ); sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue); if( pTabItem->fg.viaCoroutine ){ sqlite3VdbeChangeP2(v, addrCounter, regBase+n); translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1); sqlite3VdbeGoto(v, addrTop); pTabItem->fg.viaCoroutine = 0; }else{ sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); } sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); sqlite3VdbeJumpHere(v, addrTop); sqlite3ReleaseTempReg(pParse, regRecord); sqlite3ExprCachePop(pParse); /* Jump here when skipping the initialization */ sqlite3VdbeJumpHere(v, addrInit); end_auto_index_create: sqlite3ExprDelete(pParse->db, pPartial); } #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Allocate and populate an sqlite3_index_info structure. It is the ** responsibility of the caller to eventually release the structure ** by passing the pointer returned by this function to sqlite3_free(). */ static sqlite3_index_info *allocateIndexInfo( Parse *pParse, WhereClause *pWC, Bitmask mUnusable, /* Ignore terms with these prereqs */ struct SrcList_item *pSrc, ExprList *pOrderBy, u16 *pmNoOmit /* Mask of terms not to omit */ ){ int i, j; int nTerm; struct sqlite3_index_constraint *pIdxCons; struct sqlite3_index_orderby *pIdxOrderBy; struct sqlite3_index_constraint_usage *pUsage; WhereTerm *pTerm; int nOrderBy; sqlite3_index_info *pIdxInfo; u16 mNoOmit = 0; /* Count the number of possible WHERE clause constraints referring ** to this virtual table */ for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ if( pTerm->leftCursor != pSrc->iCursor ) continue; if( pTerm->prereqRight & mUnusable ) continue; assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); testcase( pTerm->eOperator & WO_IN ); testcase( pTerm->eOperator & WO_ISNULL ); testcase( pTerm->eOperator & WO_IS ); testcase( pTerm->eOperator & WO_ALL ); if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue; if( pTerm->wtFlags & TERM_VNULL ) continue; assert( pTerm->u.leftColumn>=(-1) ); nTerm++; } /* If the ORDER BY clause contains only columns in the current ** virtual table then allocate space for the aOrderBy part of ** the sqlite3_index_info structure. */ nOrderBy = 0; if( pOrderBy ){ int n = pOrderBy->nExpr; for(i=0; i<n; i++){ Expr *pExpr = pOrderBy->a[i].pExpr; if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; } if( i==n){ nOrderBy = n; } } /* Allocate the sqlite3_index_info structure */ pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm + sizeof(*pIdxOrderBy)*nOrderBy ); if( pIdxInfo==0 ){ sqlite3ErrorMsg(pParse, "out of memory"); return 0; } /* Initialize the structure. The sqlite3_index_info structure contains ** many fields that are declared "const" to prevent xBestIndex from ** changing them. We have to do some funky casting in order to ** initialize those fields. */ pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; *(int*)&pIdxInfo->nConstraint = nTerm; *(int*)&pIdxInfo->nOrderBy = nOrderBy; *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = pUsage; for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ u8 op; if( pTerm->leftCursor != pSrc->iCursor ) continue; if( pTerm->prereqRight & mUnusable ) continue; assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); testcase( pTerm->eOperator & WO_IN ); testcase( pTerm->eOperator & WO_IS ); testcase( pTerm->eOperator & WO_ISNULL ); testcase( pTerm->eOperator & WO_ALL ); if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue; if( pTerm->wtFlags & TERM_VNULL ) continue; assert( pTerm->u.leftColumn>=(-1) ); pIdxCons[j].iColumn = pTerm->u.leftColumn; pIdxCons[j].iTermOffset = i; op = (u8)pTerm->eOperator & WO_ALL; if( op==WO_IN ) op = WO_EQ; if( op==WO_MATCH ){ op = pTerm->eMatchOp; } pIdxCons[j].op = op; /* The direct assignment in the previous line is possible only because ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The ** following asserts verify this fact. */ assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) ); if( op & (WO_LT|WO_LE|WO_GT|WO_GE) && sqlite3ExprIsVector(pTerm->pExpr->pRight) ){ if( i<16 ) mNoOmit |= (1 << i); if( op==WO_LT ) pIdxCons[j].op = WO_LE; if( op==WO_GT ) pIdxCons[j].op = WO_GE; } j++; } for(i=0; i<nOrderBy; i++){ Expr *pExpr = pOrderBy->a[i].pExpr; pIdxOrderBy[i].iColumn = pExpr->iColumn; pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; } *pmNoOmit = mNoOmit; return pIdxInfo; } /* ** The table object reference passed as the second argument to this function ** must represent a virtual table. This function invokes the xBestIndex() ** method of the virtual table with the sqlite3_index_info object that ** comes in as the 3rd argument to this function. ** ** If an error occurs, pParse is populated with an error message and a ** non-zero value is returned. Otherwise, 0 is returned and the output ** part of the sqlite3_index_info structure is left populated. ** ** Whether or not an error is returned, it is the responsibility of the ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates ** that this is required. */ static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; int rc; TRACE_IDX_INPUTS(p); rc = pVtab->pModule->xBestIndex(pVtab, p); TRACE_IDX_OUTPUTS(p); if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM ){ sqlite3OomFault(pParse->db); }else if( !pVtab->zErrMsg ){ sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); }else{ sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); } } sqlite3_free(pVtab->zErrMsg); pVtab->zErrMsg = 0; #if 0 /* This error is now caught by the caller. ** Search for "xBestIndex malfunction" below */ for(i=0; i<p->nConstraint; i++){ if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ sqlite3ErrorMsg(pParse, "table %s: xBestIndex returned an invalid plan", pTab->zName); } } #endif return pParse->nErr; } #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Estimate the location of a particular key among all keys in an ** index. Store the results in aStat as follows: ** ** aStat[0] Est. number of rows less than pRec ** aStat[1] Est. number of rows equal to pRec ** ** Return the index of the sample that is the smallest sample that ** is greater than or equal to pRec. Note that this index is not an index ** into the aSample[] array - it is an index into a virtual set of samples ** based on the contents of aSample[] and the number of fields in record ** pRec. */ static int whereKeyStats( Parse *pParse, /* Database connection */ Index *pIdx, /* Index to consider domain of */ UnpackedRecord *pRec, /* Vector of values to consider */ int roundUp, /* Round up if true. Round down if false */ tRowcnt *aStat /* OUT: stats written here */ ){ IndexSample *aSample = pIdx->aSample; int iCol; /* Index of required stats in anEq[] etc. */ int i; /* Index of first sample >= pRec */ int iSample; /* Smallest sample larger than or equal to pRec */ int iMin = 0; /* Smallest sample not yet tested */ int iTest; /* Next sample to test */ int res; /* Result of comparison operation */ int nField; /* Number of fields in pRec */ tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */ #ifndef SQLITE_DEBUG UNUSED_PARAMETER( pParse ); #endif assert( pRec!=0 ); assert( pIdx->nSample>0 ); assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol ); /* Do a binary search to find the first sample greater than or equal ** to pRec. If pRec contains a single field, the set of samples to search ** is simply the aSample[] array. If the samples in aSample[] contain more ** than one fields, all fields following the first are ignored. ** ** If pRec contains N fields, where N is more than one, then as well as the ** samples in aSample[] (truncated to N fields), the search also has to ** consider prefixes of those samples. For example, if the set of samples ** in aSample is: ** ** aSample[0] = (a, 5) ** aSample[1] = (a, 10) ** aSample[2] = (b, 5) ** aSample[3] = (c, 100) ** aSample[4] = (c, 105) ** ** Then the search space should ideally be the samples above and the ** unique prefixes [a], [b] and [c]. But since that is hard to organize, ** the code actually searches this set: ** ** 0: (a) ** 1: (a, 5) ** 2: (a, 10) ** 3: (a, 10) ** 4: (b) ** 5: (b, 5) ** 6: (c) ** 7: (c, 100) ** 8: (c, 105) ** 9: (c, 105) ** ** For each sample in the aSample[] array, N samples are present in the ** effective sample array. In the above, samples 0 and 1 are based on ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc. ** ** Often, sample i of each block of N effective samples has (i+1) fields. ** Except, each sample may be extended to ensure that it is greater than or ** equal to the previous sample in the array. For example, in the above, ** sample 2 is the first sample of a block of N samples, so at first it ** appears that it should be 1 field in size. However, that would make it ** smaller than sample 1, so the binary search would not work. As a result, ** it is extended to two fields. The duplicates that this creates do not ** cause any problems. */ nField = pRec->nField; iCol = 0; iSample = pIdx->nSample * nField; do{ int iSamp; /* Index in aSample[] of test sample */ int n; /* Number of fields in test sample */ iTest = (iMin+iSample)/2; iSamp = iTest / nField; if( iSamp>0 ){ /* The proposed effective sample is a prefix of sample aSample[iSamp]. ** Specifically, the shortest prefix of at least (1 + iTest%nField) ** fields that is greater than the previous effective sample. */ for(n=(iTest % nField) + 1; n<nField; n++){ if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break; } }else{ n = iTest + 1; } pRec->nField = n; res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec); if( res<0 ){ iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1]; iMin = iTest+1; }else if( res==0 && n<nField ){ iLower = aSample[iSamp].anLt[n-1]; iMin = iTest+1; res = -1; }else{ iSample = iTest; iCol = n-1; } }while( res && iMin<iSample ); i = iSample / nField; #ifdef SQLITE_DEBUG /* The following assert statements check that the binary search code ** above found the right answer. This block serves no purpose other ** than to invoke the asserts. */ if( pParse->db->mallocFailed==0 ){ if( res==0 ){ /* If (res==0) is true, then pRec must be equal to sample i. */ assert( i<pIdx->nSample ); assert( iCol==nField-1 ); pRec->nField = nField; assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) || pParse->db->mallocFailed ); }else{ /* Unless i==pIdx->nSample, indicating that pRec is larger than ** all samples in the aSample[] array, pRec must be smaller than the ** (iCol+1) field prefix of sample i. */ assert( i<=pIdx->nSample && i>=0 ); pRec->nField = iCol+1; assert( i==pIdx->nSample || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 || pParse->db->mallocFailed ); /* if i==0 and iCol==0, then record pRec is smaller than all samples ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must ** be greater than or equal to the (iCol) field prefix of sample i. ** If (i>0), then pRec must also be greater than sample (i-1). */ if( iCol>0 ){ pRec->nField = iCol; assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0 || pParse->db->mallocFailed ); } if( i>0 ){ pRec->nField = nField; assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 || pParse->db->mallocFailed ); } } } #endif /* ifdef SQLITE_DEBUG */ if( res==0 ){ /* Record pRec is equal to sample i */ assert( iCol==nField-1 ); aStat[0] = aSample[i].anLt[iCol]; aStat[1] = aSample[i].anEq[iCol]; }else{ /* At this point, the (iCol+1) field prefix of aSample[i] is the first ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec ** is larger than all samples in the array. */ tRowcnt iUpper, iGap; if( i>=pIdx->nSample ){ iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]); }else{ iUpper = aSample[i].anLt[iCol]; } if( iLower>=iUpper ){ iGap = 0; }else{ iGap = iUpper - iLower; } if( roundUp ){ iGap = (iGap*2)/3; }else{ iGap = iGap/3; } aStat[0] = iLower + iGap; aStat[1] = pIdx->aAvgEq[iCol]; } /* Restore the pRec->nField value before returning. */ pRec->nField = nField; return i; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* ** If it is not NULL, pTerm is a term that provides an upper or lower ** bound on a range scan. Without considering pTerm, it is estimated ** that the scan will visit nNew rows. This function returns the number ** estimated to be visited after taking pTerm into account. ** ** If the user explicitly specified a likelihood() value for this term, ** then the return value is the likelihood multiplied by the number of ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term ** has a likelihood of 0.50, and any other term a likelihood of 0.25. */ static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ LogEst nRet = nNew; if( pTerm ){ if( pTerm->truthProb<=0 ){ nRet += pTerm->truthProb; }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ nRet -= 20; assert( 20==sqlite3LogEst(4) ); } } return nRet; } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Return the affinity for a single column of an index. */ SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){ assert( iCol>=0 && iCol<pIdx->nColumn ); if( !pIdx->zColAff ){ if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB; } return pIdx->zColAff[iCol]; } #endif #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** This function is called to estimate the number of rows visited by a ** range-scan on a skip-scan index. For example: ** ** CREATE INDEX i1 ON t1(a, b, c); ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?; ** ** Value pLoop->nOut is currently set to the estimated number of rows ** visited for scanning (a=? AND b=?). This function reduces that estimate ** by some factor to account for the (c BETWEEN ? AND ?) expression based ** on the stat4 data for the index. this scan will be peformed multiple ** times (once for each (a,b) combination that matches a=?) is dealt with ** by the caller. ** ** It does this by scanning through all stat4 samples, comparing values ** extracted from pLower and pUpper with the corresponding column in each ** sample. If L and U are the number of samples found to be less than or ** equal to the values extracted from pLower and pUpper respectively, and ** N is the total number of samples, the pLoop->nOut value is adjusted ** as follows: ** ** nOut = nOut * ( min(U - L, 1) / N ) ** ** If pLower is NULL, or a value cannot be extracted from the term, L is ** set to zero. If pUpper is NULL, or a value cannot be extracted from it, ** U is set to N. ** ** Normally, this function sets *pbDone to 1 before returning. However, ** if no value can be extracted from either pLower or pUpper (and so the ** estimate of the number of rows delivered remains unchanged), *pbDone ** is left as is. ** ** If an error occurs, an SQLite error code is returned. Otherwise, ** SQLITE_OK. */ static int whereRangeSkipScanEst( Parse *pParse, /* Parsing & code generating context */ WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ WhereLoop *pLoop, /* Update the .nOut value of this loop */ int *pbDone /* Set to true if at least one expr. value extracted */ ){ Index *p = pLoop->u.btree.pIndex; int nEq = pLoop->u.btree.nEq; sqlite3 *db = pParse->db; int nLower = -1; int nUpper = p->nSample+1; int rc = SQLITE_OK; u8 aff = sqlite3IndexColumnAffinity(db, p, nEq); CollSeq *pColl; sqlite3_value *p1 = 0; /* Value extracted from pLower */ sqlite3_value *p2 = 0; /* Value extracted from pUpper */ sqlite3_value *pVal = 0; /* Value extracted from record */ pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); if( pLower ){ rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); nLower = 0; } if( pUpper && rc==SQLITE_OK ){ rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); nUpper = p2 ? 0 : p->nSample; } if( p1 || p2 ){ int i; int nDiff; for(i=0; rc==SQLITE_OK && i<p->nSample; i++){ rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); if( rc==SQLITE_OK && p1 ){ int res = sqlite3MemCompare(p1, pVal, pColl); if( res>=0 ) nLower++; } if( rc==SQLITE_OK && p2 ){ int res = sqlite3MemCompare(p2, pVal, pColl); if( res>=0 ) nUpper++; } } nDiff = (nUpper - nLower); if( nDiff<=0 ) nDiff = 1; /* If there is both an upper and lower bound specified, and the ** comparisons indicate that they are close together, use the fallback ** method (assume that the scan visits 1/64 of the rows) for estimating ** the number of rows visited. Otherwise, estimate the number of rows ** using the method described in the header comment for this function. */ if( nDiff!=1 || pUpper==0 || pLower==0 ){ int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff)); pLoop->nOut -= nAdjust; *pbDone = 1; WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n", nLower, nUpper, nAdjust*-1, pLoop->nOut)); } }else{ assert( *pbDone==0 ); } sqlite3ValueFree(p1); sqlite3ValueFree(p2); sqlite3ValueFree(pVal); return rc; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ /* ** This function is used to estimate the number of rows that will be visited ** by scanning an index for a range of values. The range may have an upper ** bound, a lower bound, or both. The WHERE clause terms that set the upper ** and lower bounds are represented by pLower and pUpper respectively. For ** example, assuming that index p is on t1(a): ** ** ... FROM t1 WHERE a > ? AND a < ? ... ** |_____| |_____| ** | | ** pLower pUpper ** ** If either of the upper or lower bound is not present, then NULL is passed in ** place of the corresponding WhereTerm. ** ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index ** column subject to the range constraint. Or, equivalently, the number of ** equality constraints optimized by the proposed index scan. For example, ** assuming index p is on t1(a, b), and the SQL query is: ** ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... ** ** then nEq is set to 1 (as the range restricted column, b, is the second ** left-most column of the index). Or, if the query is: ** ** ... FROM t1 WHERE a > ? AND a < ? ... ** ** then nEq is set to 0. ** ** When this function is called, *pnOut is set to the sqlite3LogEst() of the ** number of rows that the index scan is expected to visit without ** considering the range constraints. If nEq is 0, then *pnOut is the number of ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) ** to account for the range constraints pLower and pUpper. ** ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be ** used, a single range inequality reduces the search space by a factor of 4. ** and a pair of constraints (x>? AND x<?) reduces the expected number of ** rows visited by a factor of 64. */ static int whereRangeScanEst( Parse *pParse, /* Parsing & code generating context */ WhereLoopBuilder *pBuilder, WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ ){ int rc = SQLITE_OK; int nOut = pLoop->nOut; LogEst nNew; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 Index *p = pLoop->u.btree.pIndex; int nEq = pLoop->u.btree.nEq; if( p->nSample>0 && nEq<p->nSampleCol ){ if( nEq==pBuilder->nRecValid ){ UnpackedRecord *pRec = pBuilder->pRec; tRowcnt a[2]; int nBtm = pLoop->u.btree.nBtm; int nTop = pLoop->u.btree.nTop; /* Variable iLower will be set to the estimate of the number of rows in ** the index that are less than the lower bound of the range query. The ** lower bound being the concatenation of $P and $L, where $P is the ** key-prefix formed by the nEq values matched against the nEq left-most ** columns of the index, and $L is the value in pLower. ** ** Or, if pLower is NULL or $L cannot be extracted from it (because it ** is not a simple variable or literal value), the lower bound of the ** range is $P. Due to a quirk in the way whereKeyStats() works, even ** if $L is available, whereKeyStats() is called for both ($P) and ** ($P:$L) and the larger of the two returned values is used. ** ** Similarly, iUpper is to be set to the estimate of the number of rows ** less than the upper bound of the range query. Where the upper bound ** is either ($P) or ($P:$U). Again, even if $U is available, both values ** of iUpper are requested of whereKeyStats() and the smaller used. ** ** The number of rows between the two bounds is then just iUpper-iLower. */ tRowcnt iLower; /* Rows less than the lower bound */ tRowcnt iUpper; /* Rows less than the upper bound */ int iLwrIdx = -2; /* aSample[] for the lower bound */ int iUprIdx = -1; /* aSample[] for the upper bound */ if( pRec ){ testcase( pRec->nField!=pBuilder->nRecValid ); pRec->nField = pBuilder->nRecValid; } /* Determine iLower and iUpper using ($P) only. */ if( nEq==0 ){ iLower = 0; iUpper = p->nRowEst0; }else{ /* Note: this call could be optimized away - since the same values must ** have been requested when testing key $P in whereEqualScanEst(). */ whereKeyStats(pParse, p, pRec, 0, a); iLower = a[0]; iUpper = a[0] + a[1]; } assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 ); assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); assert( p->aSortOrder!=0 ); if( p->aSortOrder[nEq] ){ /* The roles of pLower and pUpper are swapped for a DESC index */ SWAP(WhereTerm*, pLower, pUpper); SWAP(int, nBtm, nTop); } /* If possible, improve on the iLower estimate using ($P:$L). */ if( pLower ){ int n; /* Values extracted from pExpr */ Expr *pExpr = pLower->pExpr->pRight; rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n); if( rc==SQLITE_OK && n ){ tRowcnt iNew; u16 mask = WO_GT|WO_LE; if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a); iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0); if( iNew>iLower ) iLower = iNew; nOut--; pLower = 0; } } /* If possible, improve on the iUpper estimate using ($P:$U). */ if( pUpper ){ int n; /* Values extracted from pExpr */ Expr *pExpr = pUpper->pExpr->pRight; rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n); if( rc==SQLITE_OK && n ){ tRowcnt iNew; u16 mask = WO_GT|WO_LE; if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); iUprIdx = whereKeyStats(pParse, p, pRec, 1, a); iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0); if( iNew<iUpper ) iUpper = iNew; nOut--; pUpper = 0; } } pBuilder->pRec = pRec; if( rc==SQLITE_OK ){ if( iUpper>iLower ){ nNew = sqlite3LogEst(iUpper - iLower); /* TUNING: If both iUpper and iLower are derived from the same ** sample, then assume they are 4x more selective. This brings ** the estimated selectivity more in line with what it would be ** if estimated without the use of STAT3/4 tables. */ if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) ); }else{ nNew = 10; assert( 10==sqlite3LogEst(2) ); } if( nNew<nOut ){ nOut = nNew; } WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n", (u32)iLower, (u32)iUpper, nOut)); } }else{ int bDone = 0; rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone); if( bDone ) return rc; } } #else UNUSED_PARAMETER(pParse); UNUSED_PARAMETER(pBuilder); assert( pLower || pUpper ); #endif assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 ); nNew = whereRangeAdjust(pLower, nOut); nNew = whereRangeAdjust(pUpper, nNew); /* TUNING: If there is both an upper and lower limit and neither limit ** has an application-defined likelihood(), assume the range is ** reduced by an additional 75%. This means that, by default, an open-ended ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to ** match 1/64 of the index. */ if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){ nNew -= 20; } nOut -= (pLower!=0) + (pUpper!=0); if( nNew<10 ) nNew = 10; if( nNew<nOut ) nOut = nNew; #if defined(WHERETRACE_ENABLED) if( pLoop->nOut>nOut ){ WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n", pLoop->nOut, nOut)); } #endif pLoop->nOut = (LogEst)nOut; return rc; } #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Estimate the number of rows that will be returned based on ** an equality constraint x=VALUE and where that VALUE occurs in ** the histogram data. This only works when x is the left-most ** column of an index and sqlite_stat3 histogram data is available ** for that index. When pExpr==NULL that means the constraint is ** "x IS NULL" instead of "x=VALUE". ** ** Write the estimated row count into *pnRow and return SQLITE_OK. ** If unable to make an estimate, leave *pnRow unchanged and return ** non-zero. ** ** This routine can fail if it is unable to load a collating sequence ** required for string comparison, or if unable to allocate memory ** for a UTF conversion required for comparison. The error is stored ** in the pParse structure. */ static int whereEqualScanEst( Parse *pParse, /* Parsing & code generating context */ WhereLoopBuilder *pBuilder, Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ tRowcnt *pnRow /* Write the revised row estimate here */ ){ Index *p = pBuilder->pNew->u.btree.pIndex; int nEq = pBuilder->pNew->u.btree.nEq; UnpackedRecord *pRec = pBuilder->pRec; int rc; /* Subfunction return code */ tRowcnt a[2]; /* Statistics */ int bOk; assert( nEq>=1 ); assert( nEq<=p->nColumn ); assert( p->aSample!=0 ); assert( p->nSample>0 ); assert( pBuilder->nRecValid<nEq ); /* If values are not available for all fields of the index to the left ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */ if( pBuilder->nRecValid<(nEq-1) ){ return SQLITE_NOTFOUND; } /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() ** below would return the same value. */ if( nEq>=p->nColumn ){ *pnRow = 1; return SQLITE_OK; } rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk); pBuilder->pRec = pRec; if( rc!=SQLITE_OK ) return rc; if( bOk==0 ) return SQLITE_NOTFOUND; pBuilder->nRecValid = nEq; whereKeyStats(pParse, p, pRec, 0, a); WHERETRACE(0x10,("equality scan regions %s(%d): %d\n", p->zName, nEq-1, (int)a[1])); *pnRow = a[1]; return rc; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 /* ** Estimate the number of rows that will be returned based on ** an IN constraint where the right-hand side of the IN operator ** is a list of values. Example: ** ** WHERE x IN (1,2,3,4) ** ** Write the estimated row count into *pnRow and return SQLITE_OK. ** If unable to make an estimate, leave *pnRow unchanged and return ** non-zero. ** ** This routine can fail if it is unable to load a collating sequence ** required for string comparison, or if unable to allocate memory ** for a UTF conversion required for comparison. The error is stored ** in the pParse structure. */ static int whereInScanEst( Parse *pParse, /* Parsing & code generating context */ WhereLoopBuilder *pBuilder, ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */ tRowcnt *pnRow /* Write the revised row estimate here */ ){ Index *p = pBuilder->pNew->u.btree.pIndex; i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]); int nRecValid = pBuilder->nRecValid; int rc = SQLITE_OK; /* Subfunction return code */ tRowcnt nEst; /* Number of rows for a single term */ tRowcnt nRowEst = 0; /* New estimate of the number of rows */ int i; /* Loop counter */ assert( p->aSample!=0 ); for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){ nEst = nRow0; rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst); nRowEst += nEst; pBuilder->nRecValid = nRecValid; } if( rc==SQLITE_OK ){ if( nRowEst > nRow0 ) nRowEst = nRow0; *pnRow = nRowEst; WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst)); } assert( pBuilder->nRecValid==nRecValid ); return rc; } #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ #ifdef WHERETRACE_ENABLED /* ** Print the content of a WhereTerm object */ static void whereTermPrint(WhereTerm *pTerm, int iTerm){ if( pTerm==0 ){ sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); }else{ char zType[4]; char zLeft[50]; memcpy(zType, "...", 4); if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; if( pTerm->eOperator & WO_SINGLE ){ sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}", pTerm->leftCursor, pTerm->u.leftColumn); }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){ sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", pTerm->u.pOrInfo->indexable); }else{ sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); } sqlite3DebugPrintf( "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x", iTerm, pTerm, zType, zLeft, pTerm->truthProb, pTerm->eOperator, pTerm->wtFlags); if( pTerm->iField ){ sqlite3DebugPrintf(" iField=%d\n", pTerm->iField); }else{ sqlite3DebugPrintf("\n"); } sqlite3TreeViewExpr(0, pTerm->pExpr, 0); } } #endif #ifdef WHERETRACE_ENABLED /* ** Show the complete content of a WhereClause */ SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){ int i; for(i=0; i<pWC->nTerm; i++){ whereTermPrint(&pWC->a[i], i); } } #endif #ifdef WHERETRACE_ENABLED /* ** Print a WhereLoop object for debugging purposes */ static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){ WhereInfo *pWInfo = pWC->pWInfo; int nb = 1+(pWInfo->pTabList->nSrc+3)/4; struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab; Table *pTab = pItem->pTab; Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1; sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, p->iTab, nb, p->maskSelf, nb, p->prereq & mAll); sqlite3DebugPrintf(" %12s", pItem->zAlias ? pItem->zAlias : pTab->zName); if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ const char *zName; if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){ if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ int i = sqlite3Strlen30(zName) - 1; while( zName[i]!='_' ) i--; zName += i; } sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); }else{ sqlite3DebugPrintf("%20s",""); } }else{ char *z; if( p->u.vtab.idxStr ){ z = sqlite3_mprintf("(%d,\"%s\",%x)", p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); }else{ z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); } sqlite3DebugPrintf(" %-19s", z); sqlite3_free(z); } if( p->wsFlags & WHERE_SKIPSCAN ){ sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); }else{ sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); } sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ int i; for(i=0; i<p->nLTerm; i++){ whereTermPrint(p->aLTerm[i], i); } } } #endif /* ** Convert bulk memory into a valid WhereLoop that can be passed ** to whereLoopClear harmlessly. */ static void whereLoopInit(WhereLoop *p){ p->aLTerm = p->aLTermSpace; p->nLTerm = 0; p->nLSlot = ArraySize(p->aLTermSpace); p->wsFlags = 0; } /* ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. */ static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ sqlite3_free(p->u.vtab.idxStr); p->u.vtab.needFree = 0; p->u.vtab.idxStr = 0; }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ sqlite3DbFree(db, p->u.btree.pIndex->zColAff); sqlite3DbFree(db, p->u.btree.pIndex); p->u.btree.pIndex = 0; } } } /* ** Deallocate internal memory used by a WhereLoop object */ static void whereLoopClear(sqlite3 *db, WhereLoop *p){ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); whereLoopClearUnion(db, p); whereLoopInit(p); } /* ** Increase the memory allocation for pLoop->aLTerm[] to be at least n. */ static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ WhereTerm **paNew; if( p->nLSlot>=n ) return SQLITE_OK; n = (n+7)&~7; paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); if( paNew==0 ) return SQLITE_NOMEM_BKPT; memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); p->aLTerm = paNew; p->nLSlot = n; return SQLITE_OK; } /* ** Transfer content from the second pLoop into the first. */ static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ whereLoopClearUnion(db, pTo); if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ memset(&pTo->u, 0, sizeof(pTo->u)); return SQLITE_NOMEM_BKPT; } memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ pFrom->u.vtab.needFree = 0; }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ pFrom->u.btree.pIndex = 0; } return SQLITE_OK; } /* ** Delete a WhereLoop object */ static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ whereLoopClear(db, p); sqlite3DbFree(db, p); } /* ** Free a WhereInfo structure */ static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ if( ALWAYS(pWInfo) ){ int i; for(i=0; i<pWInfo->nLevel; i++){ WhereLevel *pLevel = &pWInfo->a[i]; if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){ sqlite3DbFree(db, pLevel->u.in.aInLoop); } } sqlite3WhereClauseClear(&pWInfo->sWC); while( pWInfo->pLoops ){ WhereLoop *p = pWInfo->pLoops; pWInfo->pLoops = p->pNextLoop; whereLoopDelete(db, p); } sqlite3DbFree(db, pWInfo); } } /* ** Return TRUE if all of the following are true: ** ** (1) X has the same or lower cost that Y ** (2) X is a proper subset of Y ** (3) X skips at least as many columns as Y ** ** By "proper subset" we mean that X uses fewer WHERE clause terms ** than Y and that every WHERE clause term used by X is also used ** by Y. ** ** If X is a proper subset of Y then Y is a better choice and ought ** to have a lower cost. This routine returns TRUE when that cost ** relationship is inverted and needs to be adjusted. The third rule ** was added because if X uses skip-scan less than Y it still might ** deserve a lower cost even if it is a proper subset of Y. */ static int whereLoopCheaperProperSubset( const WhereLoop *pX, /* First WhereLoop to compare */ const WhereLoop *pY /* Compare against this WhereLoop */ ){ int i, j; if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){ return 0; /* X is not a subset of Y */ } if( pY->nSkip > pX->nSkip ) return 0; if( pX->rRun >= pY->rRun ){ if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */ if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */ } for(i=pX->nLTerm-1; i>=0; i--){ if( pX->aLTerm[i]==0 ) continue; for(j=pY->nLTerm-1; j>=0; j--){ if( pY->aLTerm[j]==pX->aLTerm[i] ) break; } if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ } return 1; /* All conditions meet */ } /* ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so ** that: ** ** (1) pTemplate costs less than any other WhereLoops that are a proper ** subset of pTemplate ** ** (2) pTemplate costs more than any other WhereLoops for which pTemplate ** is a proper subset. ** ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer ** WHERE clause terms than Y and that every WHERE clause term used by X is ** also used by Y. */ static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; for(; p; p=p->pNextLoop){ if( p->iTab!=pTemplate->iTab ) continue; if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; if( whereLoopCheaperProperSubset(p, pTemplate) ){ /* Adjust pTemplate cost downward so that it is cheaper than its ** subset p. */ WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1)); pTemplate->rRun = p->rRun; pTemplate->nOut = p->nOut - 1; }else if( whereLoopCheaperProperSubset(pTemplate, p) ){ /* Adjust pTemplate cost upward so that it is costlier than p since ** pTemplate is a proper subset of p */ WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1)); pTemplate->rRun = p->rRun; pTemplate->nOut = p->nOut + 1; } } } /* ** Search the list of WhereLoops in *ppPrev looking for one that can be ** supplanted by pTemplate. ** ** Return NULL if the WhereLoop list contains an entry that can supplant ** pTemplate, in other words if pTemplate does not belong on the list. ** ** If pX is a WhereLoop that pTemplate can supplant, then return the ** link that points to pX. ** ** If pTemplate cannot supplant any existing element of the list but needs ** to be added to the list, then return a pointer to the tail of the list. */ static WhereLoop **whereLoopFindLesser( WhereLoop **ppPrev, const WhereLoop *pTemplate ){ WhereLoop *p; for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){ if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ /* If either the iTab or iSortIdx values for two WhereLoop are different ** then those WhereLoops need to be considered separately. Neither is ** a candidate to replace the other. */ continue; } /* In the current implementation, the rSetup value is either zero ** or the cost of building an automatic index (NlogN) and the NlogN ** is the same for compatible WhereLoops. */ assert( p->rSetup==0 || pTemplate->rSetup==0 || p->rSetup==pTemplate->rSetup ); /* whereLoopAddBtree() always generates and inserts the automatic index ** case first. Hence compatible candidate WhereLoops never have a larger ** rSetup. Call this SETUP-INVARIANT */ assert( p->rSetup>=pTemplate->rSetup ); /* Any loop using an appliation-defined index (or PRIMARY KEY or ** UNIQUE constraint) with one or more == constraints is better ** than an automatic index. Unless it is a skip-scan. */ if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && (pTemplate->nSkip)==0 && (pTemplate->wsFlags & WHERE_INDEXED)!=0 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0 && (p->prereq & pTemplate->prereq)==pTemplate->prereq ){ break; } /* If existing WhereLoop p is better than pTemplate, pTemplate can be ** discarded. WhereLoop p is better if: ** (1) p has no more dependencies than pTemplate, and ** (2) p has an equal or lower cost than pTemplate */ if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */ && p->rSetup<=pTemplate->rSetup /* (2a) */ && p->rRun<=pTemplate->rRun /* (2b) */ && p->nOut<=pTemplate->nOut /* (2c) */ ){ return 0; /* Discard pTemplate */ } /* If pTemplate is always better than p, then cause p to be overwritten ** with pTemplate. pTemplate is better than p if: ** (1) pTemplate has no more dependences than p, and ** (2) pTemplate has an equal or lower cost than p. */ if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */ && p->rRun>=pTemplate->rRun /* (2a) */ && p->nOut>=pTemplate->nOut /* (2b) */ ){ assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ break; /* Cause p to be overwritten by pTemplate */ } } return ppPrev; } /* ** Insert or replace a WhereLoop entry using the template supplied. ** ** An existing WhereLoop entry might be overwritten if the new template ** is better and has fewer dependencies. Or the template will be ignored ** and no insert will occur if an existing WhereLoop is faster and has ** fewer dependencies than the template. Otherwise a new WhereLoop is ** added based on the template. ** ** If pBuilder->pOrSet is not NULL then we care about only the ** prerequisites and rRun and nOut costs of the N best loops. That ** information is gathered in the pBuilder->pOrSet object. This special ** processing mode is used only for OR clause processing. ** ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we ** still might overwrite similar loops with the new template if the ** new template is better. Loops may be overwritten if the following ** conditions are met: ** ** (1) They have the same iTab. ** (2) They have the same iSortIdx. ** (3) The template has same or fewer dependencies than the current loop ** (4) The template has the same or lower cost than the current loop */ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ WhereLoop **ppPrev, *p; WhereInfo *pWInfo = pBuilder->pWInfo; sqlite3 *db = pWInfo->pParse->db; int rc; /* If pBuilder->pOrSet is defined, then only keep track of the costs ** and prereqs. */ if( pBuilder->pOrSet!=0 ){ if( pTemplate->nLTerm ){ #if WHERETRACE_ENABLED u16 n = pBuilder->pOrSet->n; int x = #endif whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, pTemplate->nOut); #if WHERETRACE_ENABLED /* 0x8 */ if( sqlite3WhereTrace & 0x8 ){ sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); whereLoopPrint(pTemplate, pBuilder->pWC); } #endif } return SQLITE_OK; } /* Look for an existing WhereLoop to replace with pTemplate */ whereLoopAdjustCost(pWInfo->pLoops, pTemplate); ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); if( ppPrev==0 ){ /* There already exists a WhereLoop on the list that is better ** than pTemplate, so just ignore pTemplate */ #if WHERETRACE_ENABLED /* 0x8 */ if( sqlite3WhereTrace & 0x8 ){ sqlite3DebugPrintf(" skip: "); whereLoopPrint(pTemplate, pBuilder->pWC); } #endif return SQLITE_OK; }else{ p = *ppPrev; } /* If we reach this point it means that either p[] should be overwritten ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new ** WhereLoop and insert it. */ #if WHERETRACE_ENABLED /* 0x8 */ if( sqlite3WhereTrace & 0x8 ){ if( p!=0 ){ sqlite3DebugPrintf("replace: "); whereLoopPrint(p, pBuilder->pWC); } sqlite3DebugPrintf(" add: "); whereLoopPrint(pTemplate, pBuilder->pWC); } #endif if( p==0 ){ /* Allocate a new WhereLoop to add to the end of the list */ *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop)); if( p==0 ) return SQLITE_NOMEM_BKPT; whereLoopInit(p); p->pNextLoop = 0; }else{ /* We will be overwriting WhereLoop p[]. But before we do, first ** go through the rest of the list and delete any other entries besides ** p[] that are also supplated by pTemplate */ WhereLoop **ppTail = &p->pNextLoop; WhereLoop *pToDel; while( *ppTail ){ ppTail = whereLoopFindLesser(ppTail, pTemplate); if( ppTail==0 ) break; pToDel = *ppTail; if( pToDel==0 ) break; *ppTail = pToDel->pNextLoop; #if WHERETRACE_ENABLED /* 0x8 */ if( sqlite3WhereTrace & 0x8 ){ sqlite3DebugPrintf(" delete: "); whereLoopPrint(pToDel, pBuilder->pWC); } #endif whereLoopDelete(db, pToDel); } } rc = whereLoopXfer(db, p, pTemplate); if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ Index *pIndex = p->u.btree.pIndex; if( pIndex && pIndex->tnum==0 ){ p->u.btree.pIndex = 0; } } return rc; } /* ** Adjust the WhereLoop.nOut value downward to account for terms of the ** WHERE clause that reference the loop but which are not used by an ** index. * ** For every WHERE clause term that is not used by the index ** and which has a truth probability assigned by one of the likelihood(), ** likely(), or unlikely() SQL functions, reduce the estimated number ** of output rows by the probability specified. ** ** TUNING: For every WHERE clause term that is not used by the index ** and which does not have an assigned truth probability, heuristics ** described below are used to try to estimate the truth probability. ** TODO --> Perhaps this is something that could be improved by better ** table statistics. ** ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75% ** value corresponds to -1 in LogEst notation, so this means decrement ** the WhereLoop.nOut field for every such WHERE clause term. ** ** Heuristic 2: If there exists one or more WHERE clause terms of the ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the ** final output row estimate is no greater than 1/4 of the total number ** of rows in the table. In other words, assume that x==EXPR will filter ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the ** "x" column is boolean or else -1 or 0 or 1 is a common default value ** on the "x" column and so in that case only cap the output row estimate ** at 1/2 instead of 1/4. */ static void whereLoopOutputAdjust( WhereClause *pWC, /* The WHERE clause */ WhereLoop *pLoop, /* The loop to adjust downward */ LogEst nRow /* Number of rows in the entire table */ ){ WhereTerm *pTerm, *pX; Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); int i, j, k; LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */ assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; if( (pTerm->prereqAll & notAllowed)!=0 ) continue; for(j=pLoop->nLTerm-1; j>=0; j--){ pX = pLoop->aLTerm[j]; if( pX==0 ) continue; if( pX==pTerm ) break; if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; } if( j<0 ){ if( pTerm->truthProb<=0 ){ /* If a truth probability is specified using the likelihood() hints, ** then use the probability provided by the application. */ pLoop->nOut += pTerm->truthProb; }else{ /* In the absence of explicit truth probabilities, use heuristics to ** guess a reasonable truth probability. */ pLoop->nOut--; if( pTerm->eOperator&(WO_EQ|WO_IS) ){ Expr *pRight = pTerm->pExpr->pRight; testcase( pTerm->pExpr->op==TK_IS ); if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){ k = 10; }else{ k = 20; } if( iReduce<k ) iReduce = k; } } } } if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce; } /* ** Term pTerm is a vector range comparison operation. The first comparison ** in the vector can be optimized using column nEq of the index. This ** function returns the total number of vector elements that can be used ** as part of the range comparison. ** ** For example, if the query is: ** ** WHERE a = ? AND (b, c, d) > (?, ?, ?) ** ** and the index: ** ** CREATE INDEX ... ON (a, b, c, d, e) ** ** then this function would be invoked with nEq=1. The value returned in ** this case is 3. */ static int whereRangeVectorLen( Parse *pParse, /* Parsing context */ int iCur, /* Cursor open on pIdx */ Index *pIdx, /* The index to be used for a inequality constraint */ int nEq, /* Number of prior equality constraints on same index */ WhereTerm *pTerm /* The vector inequality constraint */ ){ int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft); int i; nCmp = MIN(nCmp, (pIdx->nColumn - nEq)); for(i=1; i<nCmp; i++){ /* Test if comparison i of pTerm is compatible with column (i+nEq) ** of the index. If not, exit the loop. */ char aff; /* Comparison affinity */ char idxaff = 0; /* Indexed columns affinity */ CollSeq *pColl; /* Comparison collation sequence */ Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr; Expr *pRhs = pTerm->pExpr->pRight; if( pRhs->flags & EP_xIsSelect ){ pRhs = pRhs->x.pSelect->pEList->a[i].pExpr; }else{ pRhs = pRhs->x.pList->a[i].pExpr; } /* Check that the LHS of the comparison is a column reference to ** the right column of the right source table. And that the sort ** order of the index column is the same as the sort order of the ** leftmost index column. */ if( pLhs->op!=TK_COLUMN || pLhs->iTable!=iCur || pLhs->iColumn!=pIdx->aiColumn[i+nEq] || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq] ){ break; } testcase( pLhs->iColumn==XN_ROWID ); aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs)); idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); if( aff!=idxaff ) break; pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); if( pColl==0 ) break; if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; } return i; } /* ** Adjust the cost C by the costMult facter T. This only occurs if ** compiled with -DSQLITE_ENABLE_COSTMULT */ #ifdef SQLITE_ENABLE_COSTMULT # define ApplyCostMultiplier(C,T) C += T #else # define ApplyCostMultiplier(C,T) #endif /* ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the ** index pIndex. Try to match one more. ** ** When this function is called, pBuilder->pNew->nOut contains the ** number of rows expected to be visited by filtering using the nEq ** terms only. If it is modified, this value is restored before this ** function returns. ** ** If pProbe->tnum==0, that means pIndex is a fake index used for the ** INTEGER PRIMARY KEY. */ static int whereLoopAddBtreeIndex( WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ struct SrcList_item *pSrc, /* FROM clause term being analyzed */ Index *pProbe, /* An index on pSrc */ LogEst nInMul /* log(Number of iterations due to IN) */ ){ WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ Parse *pParse = pWInfo->pParse; /* Parsing context */ sqlite3 *db = pParse->db; /* Database connection malloc context */ WhereLoop *pNew; /* Template WhereLoop under construction */ WhereTerm *pTerm; /* A WhereTerm under consideration */ int opMask; /* Valid operators for constraints */ WhereScan scan; /* Iterator for WHERE terms */ Bitmask saved_prereq; /* Original value of pNew->prereq */ u16 saved_nLTerm; /* Original value of pNew->nLTerm */ u16 saved_nEq; /* Original value of pNew->u.btree.nEq */ u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */ u16 saved_nTop; /* Original value of pNew->u.btree.nTop */ u16 saved_nSkip; /* Original value of pNew->nSkip */ u32 saved_wsFlags; /* Original value of pNew->wsFlags */ LogEst saved_nOut; /* Original value of pNew->nOut */ int rc = SQLITE_OK; /* Return code */ LogEst rSize; /* Number of rows in the table */ LogEst rLogSize; /* Logarithm of table size */ WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ pNew = pBuilder->pNew; if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n", pProbe->zName, pNew->u.btree.nEq)); assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); if( pNew->wsFlags & WHERE_BTM_LIMIT ){ opMask = WO_LT|WO_LE; }else{ assert( pNew->u.btree.nBtm==0 ); opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS; } if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); assert( pNew->u.btree.nEq<pProbe->nColumn ); saved_nEq = pNew->u.btree.nEq; saved_nBtm = pNew->u.btree.nBtm; saved_nTop = pNew->u.btree.nTop; saved_nSkip = pNew->nSkip; saved_nLTerm = pNew->nLTerm; saved_wsFlags = pNew->wsFlags; saved_prereq = pNew->prereq; saved_nOut = pNew->nOut; pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq, opMask, pProbe); pNew->rSetup = 0; rSize = pProbe->aiRowLogEst[0]; rLogSize = estLog(rSize); for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ LogEst rCostIdx; LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ int nIn = 0; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 int nRecValid = pBuilder->nRecValid; #endif if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) && indexColumnNotNull(pProbe, saved_nEq) ){ continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ } if( pTerm->prereqRight & pNew->maskSelf ) continue; /* Do not allow the upper bound of a LIKE optimization range constraint ** to mix with a lower range bound from some other source */ if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue; /* Do not allow IS constraints from the WHERE clause to be used by the ** right table of a LEFT JOIN. Only constraints in the ON clause are ** allowed */ if( (pSrc->fg.jointype & JT_LEFT)!=0 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) && (eOp & (WO_IS|WO_ISNULL))!=0 ){ testcase( eOp & WO_IS ); testcase( eOp & WO_ISNULL ); continue; } pNew->wsFlags = saved_wsFlags; pNew->u.btree.nEq = saved_nEq; pNew->u.btree.nBtm = saved_nBtm; pNew->u.btree.nTop = saved_nTop; pNew->nLTerm = saved_nLTerm; if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ pNew->aLTerm[pNew->nLTerm++] = pTerm; pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; assert( nInMul==0 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 ); if( eOp & WO_IN ){ Expr *pExpr = pTerm->pExpr; pNew->wsFlags |= WHERE_COLUMN_IN; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ int i; nIn = 46; assert( 46==sqlite3LogEst(25) ); /* The expression may actually be of the form (x, y) IN (SELECT...). ** In this case there is a separate term for each of (x) and (y). ** However, the nIn multiplier should only be applied once, not once ** for each such term. The following loop checks that pTerm is the ** first such term in use, and sets nIn back to 0 if it is not. */ for(i=0; i<pNew->nLTerm-1; i++){ if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0; } }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ /* "x IN (value, value, ...)" */ nIn = sqlite3LogEst(pExpr->x.pList->nExpr); assert( nIn>0 ); /* RHS always has 2 or more terms... The parser ** changes "x IN (?)" into "x=?". */ } }else if( eOp & (WO_EQ|WO_IS) ){ int iCol = pProbe->aiColumn[saved_nEq]; pNew->wsFlags |= WHERE_COLUMN_EQ; assert( saved_nEq==pNew->u.btree.nEq ); if( iCol==XN_ROWID || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1) ){ if( iCol>=0 && pProbe->uniqNotNull==0 ){ pNew->wsFlags |= WHERE_UNQ_WANTED; }else{ pNew->wsFlags |= WHERE_ONEROW; } } }else if( eOp & WO_ISNULL ){ pNew->wsFlags |= WHERE_COLUMN_NULL; }else if( eOp & (WO_GT|WO_GE) ){ testcase( eOp & WO_GT ); testcase( eOp & WO_GE ); pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; pNew->u.btree.nBtm = whereRangeVectorLen( pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm ); pBtm = pTerm; pTop = 0; if( pTerm->wtFlags & TERM_LIKEOPT ){ /* Range contraints that come from the LIKE optimization are ** always used in pairs. */ pTop = &pTerm[1]; assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm ); assert( pTop->wtFlags & TERM_LIKEOPT ); assert( pTop->eOperator==WO_LT ); if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ pNew->aLTerm[pNew->nLTerm++] = pTop; pNew->wsFlags |= WHERE_TOP_LIMIT; pNew->u.btree.nTop = 1; } }else{ assert( eOp & (WO_LT|WO_LE) ); testcase( eOp & WO_LT ); testcase( eOp & WO_LE ); pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; pNew->u.btree.nTop = whereRangeVectorLen( pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm ); pTop = pTerm; pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? pNew->aLTerm[pNew->nLTerm-2] : 0; } /* At this point pNew->nOut is set to the number of rows expected to ** be visited by the index scan before considering term pTerm, or the ** values of nIn and nInMul. In other words, assuming that all ** "x IN(...)" terms are replaced with "x = ?". This block updates ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ assert( pNew->nOut==saved_nOut ); if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4 ** data, using some other estimate. */ whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); }else{ int nEq = ++pNew->u.btree.nEq; assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) ); assert( pNew->nOut==saved_nOut ); if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){ assert( (eOp & WO_IN) || nIn==0 ); testcase( eOp & WO_IN ); pNew->nOut += pTerm->truthProb; pNew->nOut -= nIn; }else{ #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 tRowcnt nOut = 0; if( nInMul==0 && pProbe->nSample && pNew->u.btree.nEq<=pProbe->nSampleCol && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) ){ Expr *pExpr = pTerm->pExpr; if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){ testcase( eOp & WO_EQ ); testcase( eOp & WO_IS ); testcase( eOp & WO_ISNULL ); rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); }else{ rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); } if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ if( nOut ){ pNew->nOut = sqlite3LogEst(nOut); if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; pNew->nOut -= nIn; } } if( nOut==0 ) #endif { pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]); if( eOp & WO_ISNULL ){ /* TUNING: If there is no likelihood() value, assume that a ** "col IS NULL" expression matches twice as many rows ** as (col=?). */ pNew->nOut += 10; } } } } /* Set rCostIdx to the cost of visiting selected rows in index. Add ** it to pNew->rRun, which is currently set to the cost of the index ** seek only. Then, if this is a non-covering index, add the cost of ** visiting the rows in the main table. */ rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow; pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx); if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); } ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult); nOutUnadjusted = pNew->nOut; pNew->rRun += nInMul + nIn; pNew->nOut += nInMul + nIn; whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize); rc = whereLoopInsert(pBuilder, pNew); if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ pNew->nOut = saved_nOut; }else{ pNew->nOut = nOutUnadjusted; } if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 && pNew->u.btree.nEq<pProbe->nColumn ){ whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); } pNew->nOut = saved_nOut; #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 pBuilder->nRecValid = nRecValid; #endif } pNew->prereq = saved_prereq; pNew->u.btree.nEq = saved_nEq; pNew->u.btree.nBtm = saved_nBtm; pNew->u.btree.nTop = saved_nTop; pNew->nSkip = saved_nSkip; pNew->wsFlags = saved_wsFlags; pNew->nOut = saved_nOut; pNew->nLTerm = saved_nLTerm; /* Consider using a skip-scan if there are no WHERE clause constraints ** available for the left-most terms of the index, and if the average ** number of repeats in the left-most terms is at least 18. ** ** The magic number 18 is selected on the basis that scanning 17 rows ** is almost always quicker than an index seek (even though if the index ** contains fewer than 2^17 rows we assume otherwise in other parts of ** the code). And, even if it is not, it should not be too much slower. ** On the other hand, the extra seeks could end up being significantly ** more expensive. */ assert( 42==sqlite3LogEst(18) ); if( saved_nEq==saved_nSkip && saved_nEq+1<pProbe->nKeyCol && pProbe->noSkipScan==0 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK ){ LogEst nIter; pNew->u.btree.nEq++; pNew->nSkip++; pNew->aLTerm[pNew->nLTerm++] = 0; pNew->wsFlags |= WHERE_SKIPSCAN; nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1]; pNew->nOut -= nIter; /* TUNING: Because uncertainties in the estimates for skip-scan queries, ** add a 1.375 fudge factor to make skip-scan slightly less likely. */ nIter += 5; whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul); pNew->nOut = saved_nOut; pNew->u.btree.nEq = saved_nEq; pNew->nSkip = saved_nSkip; pNew->wsFlags = saved_wsFlags; } WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n", pProbe->zName, saved_nEq, rc)); return rc; } /* ** Return True if it is possible that pIndex might be useful in ** implementing the ORDER BY clause in pBuilder. ** ** Return False if pBuilder does not contain an ORDER BY clause or ** if there is no way for pIndex to be useful in implementing that ** ORDER BY clause. */ static int indexMightHelpWithOrderBy( WhereLoopBuilder *pBuilder, Index *pIndex, int iCursor ){ ExprList *pOB; ExprList *aColExpr; int ii, jj; if( pIndex->bUnordered ) return 0; if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; for(ii=0; ii<pOB->nExpr; ii++){ Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){ if( pExpr->iColumn<0 ) return 1; for(jj=0; jj<pIndex->nKeyCol; jj++){ if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; } }else if( (aColExpr = pIndex->aColExpr)!=0 ){ for(jj=0; jj<pIndex->nKeyCol; jj++){ if( pIndex->aiColumn[jj]!=XN_EXPR ) continue; if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){ return 1; } } } } return 0; } /* ** Return a bitmask where 1s indicate that the corresponding column of ** the table is used by an index. Only the first 63 columns are considered. */ static Bitmask columnsInIndex(Index *pIdx){ Bitmask m = 0; int j; for(j=pIdx->nColumn-1; j>=0; j--){ int x = pIdx->aiColumn[j]; if( x>=0 ){ testcase( x==BMS-1 ); testcase( x==BMS-2 ); if( x<BMS-1 ) m |= MASKBIT(x); } } return m; } /* Check to see if a partial index with pPartIndexWhere can be used ** in the current query. Return true if it can be and false if not. */ static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){ int i; WhereTerm *pTerm; while( pWhere->op==TK_AND ){ if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0; pWhere = pWhere->pRight; } for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ Expr *pExpr = pTerm->pExpr; if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab) && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) ){ return 1; } } return 0; } /* ** Add all WhereLoop objects for a single table of the join where the table ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be ** a b-tree table, not a virtual table. ** ** The costs (WhereLoop.rRun) of the b-tree loops added by this function ** are calculated as follows: ** ** For a full scan, assuming the table (or index) contains nRow rows: ** ** cost = nRow * 3.0 // full-table scan ** cost = nRow * K // scan of covering index ** cost = nRow * (K+3.0) // scan of non-covering index ** ** where K is a value between 1.1 and 3.0 set based on the relative ** estimated average size of the index and table records. ** ** For an index scan, where nVisit is the number of index rows visited ** by the scan, and nSeek is the number of seek operations required on ** the index b-tree: ** ** cost = nSeek * (log(nRow) + K * nVisit) // covering index ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index ** ** Normally, nSeek is 1. nSeek values greater than 1 come about if the ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans. ** ** The estimated values (nRow, nVisit, nSeek) often contain a large amount ** of uncertainty. For this reason, scoring is designed to pick plans that ** "do the least harm" if the estimates are inaccurate. For example, a ** log(nRow) factor is omitted from a non-covering index scan in order to ** bias the scoring in favor of using an index, since the worst-case ** performance of using an index is far better than the worst-case performance ** of a full table scan. */ static int whereLoopAddBtree( WhereLoopBuilder *pBuilder, /* WHERE clause information */ Bitmask mPrereq /* Extra prerequesites for using this table */ ){ WhereInfo *pWInfo; /* WHERE analysis context */ Index *pProbe; /* An index we are evaluating */ Index sPk; /* A fake index object for the primary key */ LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */ i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */ SrcList *pTabList; /* The FROM clause */ struct SrcList_item *pSrc; /* The FROM clause btree term to add */ WhereLoop *pNew; /* Template WhereLoop object */ int rc = SQLITE_OK; /* Return code */ int iSortIdx = 1; /* Index number */ int b; /* A boolean value */ LogEst rSize; /* number of rows in the table */ LogEst rLogSize; /* Logarithm of the number of rows in the table */ WhereClause *pWC; /* The parsed WHERE clause */ Table *pTab; /* Table being queried */ pNew = pBuilder->pNew; pWInfo = pBuilder->pWInfo; pTabList = pWInfo->pTabList; pSrc = pTabList->a + pNew->iTab; pTab = pSrc->pTab; pWC = pBuilder->pWC; assert( !IsVirtual(pSrc->pTab) ); if( pSrc->pIBIndex ){ /* An INDEXED BY clause specifies a particular index to use */ pProbe = pSrc->pIBIndex; }else if( !HasRowid(pTab) ){ pProbe = pTab->pIndex; }else{ /* There is no INDEXED BY clause. Create a fake Index object in local ** variable sPk to represent the rowid primary key index. Make this ** fake index the first in a chain of Index objects with all of the real ** indices to follow */ Index *pFirst; /* First of real indices on the table */ memset(&sPk, 0, sizeof(Index)); sPk.nKeyCol = 1; sPk.nColumn = 1; sPk.aiColumn = &aiColumnPk; sPk.aiRowLogEst = aiRowEstPk; sPk.onError = OE_Replace; sPk.pTable = pTab; sPk.szIdxRow = pTab->szTabRow; aiRowEstPk[0] = pTab->nRowLogEst; aiRowEstPk[1] = 0; pFirst = pSrc->pTab->pIndex; if( pSrc->fg.notIndexed==0 ){ /* The real indices of the table are only considered if the ** NOT INDEXED qualifier is omitted from the FROM clause */ sPk.pNext = pFirst; } pProbe = &sPk; } rSize = pTab->nRowLogEst; rLogSize = estLog(rSize); #ifndef SQLITE_OMIT_AUTOMATIC_INDEX /* Automatic indexes */ if( !pBuilder->pOrSet /* Not part of an OR optimization */ && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */ && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */ && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */ && !pSrc->fg.isCorrelated /* Not a correlated subquery */ && !pSrc->fg.isRecursive /* Not a recursive common table expression. */ ){ /* Generate auto-index WhereLoops */ WhereTerm *pTerm; WhereTerm *pWCEnd = pWC->a + pWC->nTerm; for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){ if( pTerm->prereqRight & pNew->maskSelf ) continue; if( termCanDriveIndex(pTerm, pSrc, 0) ){ pNew->u.btree.nEq = 1; pNew->nSkip = 0; pNew->u.btree.pIndex = 0; pNew->nLTerm = 1; pNew->aLTerm[0] = pTerm; /* TUNING: One-time cost for computing the automatic index is ** estimated to be X*N*log2(N) where N is the number of rows in ** the table being indexed and where X is 7 (LogEst=28) for normal ** tables or 1.375 (LogEst=4) for views and subqueries. The value ** of X is smaller for views and subqueries so that the query planner ** will be more aggressive about generating automatic indexes for ** those objects, since there is no opportunity to add schema ** indexes on subqueries and views. */ pNew->rSetup = rLogSize + rSize + 4; if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){ pNew->rSetup += 24; } ApplyCostMultiplier(pNew->rSetup, pTab->costMult); if( pNew->rSetup<0 ) pNew->rSetup = 0; /* TUNING: Each index lookup yields 20 rows in the table. This ** is more than the usual guess of 10 rows, since we have no way ** of knowing how selective the index will ultimately be. It would ** not be unreasonable to make this value much larger. */ pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); pNew->wsFlags = WHERE_AUTO_INDEX; pNew->prereq = mPrereq | pTerm->prereqRight; rc = whereLoopInsert(pBuilder, pNew); } } } #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ /* Loop over all indices */ for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ if( pProbe->pPartIdxWhere!=0 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){ testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ continue; /* Partial index inappropriate for this query */ } rSize = pProbe->aiRowLogEst[0]; pNew->u.btree.nEq = 0; pNew->u.btree.nBtm = 0; pNew->u.btree.nTop = 0; pNew->nSkip = 0; pNew->nLTerm = 0; pNew->iSortIdx = 0; pNew->rSetup = 0; pNew->prereq = mPrereq; pNew->nOut = rSize; pNew->u.btree.pIndex = pProbe; b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); if( pProbe->tnum<=0 ){ /* Integer primary key index */ pNew->wsFlags = WHERE_IPK; /* Full table scan */ pNew->iSortIdx = b ? iSortIdx : 0; /* TUNING: Cost of full table scan is (N*3.0). */ pNew->rRun = rSize + 16; ApplyCostMultiplier(pNew->rRun, pTab->costMult); whereLoopOutputAdjust(pWC, pNew, rSize); rc = whereLoopInsert(pBuilder, pNew); pNew->nOut = rSize; if( rc ) break; }else{ Bitmask m; if( pProbe->isCovering ){ pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; m = 0; }else{ m = pSrc->colUsed & ~columnsInIndex(pProbe); pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; } /* Full scan via index */ if( b || !HasRowid(pTab) || pProbe->pPartIdxWhere!=0 || ( m==0 && pProbe->bUnordered==0 && (pProbe->szIdxRow<pTab->szTabRow) && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 && sqlite3GlobalConfig.bUseCis && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) ) ){ pNew->iSortIdx = b ? iSortIdx : 0; /* The cost of visiting the index rows is N*K, where K is ** between 1.1 and 3.0, depending on the relative sizes of the ** index and table rows. */ pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow; if( m!=0 ){ /* If this is a non-covering index scan, add in the cost of ** doing table lookups. The cost will be 3x the number of ** lookups. Take into account WHERE clause terms that can be ** satisfied using just the index, and that do not require a ** table lookup. */ LogEst nLookup = rSize + 16; /* Base cost: N*3 */ int ii; int iCur = pSrc->iCursor; WhereClause *pWC2 = &pWInfo->sWC; for(ii=0; ii<pWC2->nTerm; ii++){ WhereTerm *pTerm = &pWC2->a[ii]; if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){ break; } /* pTerm can be evaluated using just the index. So reduce ** the expected number of table lookups accordingly */ if( pTerm->truthProb<=0 ){ nLookup += pTerm->truthProb; }else{ nLookup--; if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19; } } pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup); } ApplyCostMultiplier(pNew->rRun, pTab->costMult); whereLoopOutputAdjust(pWC, pNew, rSize); rc = whereLoopInsert(pBuilder, pNew); pNew->nOut = rSize; if( rc ) break; } } rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 sqlite3Stat4ProbeFree(pBuilder->pRec); pBuilder->nRecValid = 0; pBuilder->pRec = 0; #endif /* If there was an INDEXED BY clause, then only that one index is ** considered. */ if( pSrc->pIBIndex ) break; } return rc; } #ifndef SQLITE_OMIT_VIRTUALTABLE /* ** Argument pIdxInfo is already populated with all constraints that may ** be used by the virtual table identified by pBuilder->pNew->iTab. This ** function marks a subset of those constraints usable, invokes the ** xBestIndex method and adds the returned plan to pBuilder. ** ** A constraint is marked usable if: ** ** * Argument mUsable indicates that its prerequisites are available, and ** ** * It is not one of the operators specified in the mExclude mask passed ** as the fourth argument (which in practice is either WO_IN or 0). ** ** Argument mPrereq is a mask of tables that must be scanned before the ** virtual table in question. These are added to the plans prerequisites ** before it is added to pBuilder. ** ** Output parameter *pbIn is set to true if the plan added to pBuilder ** uses one or more WO_IN terms, or false otherwise. */ static int whereLoopAddVirtualOne( WhereLoopBuilder *pBuilder, Bitmask mPrereq, /* Mask of tables that must be used. */ Bitmask mUsable, /* Mask of usable tables */ u16 mExclude, /* Exclude terms using these operators */ sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */ u16 mNoOmit, /* Do not omit these constraints */ int *pbIn /* OUT: True if plan uses an IN(...) op */ ){ WhereClause *pWC = pBuilder->pWC; struct sqlite3_index_constraint *pIdxCons; struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage; int i; int mxTerm; int rc = SQLITE_OK; WhereLoop *pNew = pBuilder->pNew; Parse *pParse = pBuilder->pWInfo->pParse; struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab]; int nConstraint = pIdxInfo->nConstraint; assert( (mUsable & mPrereq)==mPrereq ); *pbIn = 0; pNew->prereq = mPrereq; /* Set the usable flag on the subset of constraints identified by ** arguments mUsable and mExclude. */ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; for(i=0; i<nConstraint; i++, pIdxCons++){ WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset]; pIdxCons->usable = 0; if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight && (pTerm->eOperator & mExclude)==0 ){ pIdxCons->usable = 1; } } /* Initialize the output fields of the sqlite3_index_info structure */ memset(pUsage, 0, sizeof(pUsage[0])*nConstraint); assert( pIdxInfo->needToFreeIdxStr==0 ); pIdxInfo->idxStr = 0; pIdxInfo->idxNum = 0; pIdxInfo->orderByConsumed = 0; pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; pIdxInfo->estimatedRows = 25; pIdxInfo->idxFlags = 0; pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed; /* Invoke the virtual table xBestIndex() method */ rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo); if( rc ) return rc; mxTerm = -1; assert( pNew->nLSlot>=nConstraint ); for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0; pNew->u.vtab.omitMask = 0; pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; for(i=0; i<nConstraint; i++, pIdxCons++){ int iTerm; if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){ WhereTerm *pTerm; int j = pIdxCons->iTermOffset; if( iTerm>=nConstraint || j<0 || j>=pWC->nTerm || pNew->aLTerm[iTerm]!=0 || pIdxCons->usable==0 ){ rc = SQLITE_ERROR; sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); return rc; } testcase( iTerm==nConstraint-1 ); testcase( j==0 ); testcase( j==pWC->nTerm-1 ); pTerm = &pWC->a[j]; pNew->prereq |= pTerm->prereqRight; assert( iTerm<pNew->nLSlot ); pNew->aLTerm[iTerm] = pTerm; if( iTerm>mxTerm ) mxTerm = iTerm; testcase( iTerm==15 ); testcase( iTerm==16 ); if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm; if( (pTerm->eOperator & WO_IN)!=0 ){ /* A virtual table that is constrained by an IN clause may not ** consume the ORDER BY clause because (1) the order of IN terms ** is not necessarily related to the order of output terms and ** (2) Multiple outputs from a single IN value will not merge ** together. */ pIdxInfo->orderByConsumed = 0; pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE; *pbIn = 1; assert( (mExclude & WO_IN)==0 ); } } } pNew->u.vtab.omitMask &= ~mNoOmit; pNew->nLTerm = mxTerm+1; assert( pNew->nLTerm<=pNew->nLSlot ); pNew->u.vtab.idxNum = pIdxInfo->idxNum; pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; pIdxInfo->needToFreeIdxStr = 0; pNew->u.vtab.idxStr = pIdxInfo->idxStr; pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? pIdxInfo->nOrderBy : 0); pNew->rSetup = 0; pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated ** that the scan will visit at most one row. Clear it otherwise. */ if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){ pNew->wsFlags |= WHERE_ONEROW; }else{ pNew->wsFlags &= ~WHERE_ONEROW; } rc = whereLoopInsert(pBuilder, pNew); if( pNew->u.vtab.needFree ){ sqlite3_free(pNew->u.vtab.idxStr); pNew->u.vtab.needFree = 0; } WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n", *pbIn, (sqlite3_uint64)mPrereq, (sqlite3_uint64)(pNew->prereq & ~mPrereq))); return rc; } /* ** Add all WhereLoop objects for a table of the join identified by ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. ** ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause ** entries that occur before the virtual table in the FROM clause and are ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the ** mUnusable mask contains all FROM clause entries that occur after the ** virtual table and are separated from it by at least one LEFT or ** CROSS JOIN. ** ** For example, if the query were: ** ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6; ** ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6). ** ** All the tables in mPrereq must be scanned before the current virtual ** table. So any terms for which all prerequisites are satisfied by ** mPrereq may be specified as "usable" in all calls to xBestIndex. ** Conversely, all tables in mUnusable must be scanned after the current ** virtual table, so any terms for which the prerequisites overlap with ** mUnusable should always be configured as "not-usable" for xBestIndex. */ static int whereLoopAddVirtual( WhereLoopBuilder *pBuilder, /* WHERE clause information */ Bitmask mPrereq, /* Tables that must be scanned before this one */ Bitmask mUnusable /* Tables that must be scanned after this one */ ){ int rc = SQLITE_OK; /* Return code */ WhereInfo *pWInfo; /* WHERE analysis context */ Parse *pParse; /* The parsing context */ WhereClause *pWC; /* The WHERE clause */ struct SrcList_item *pSrc; /* The FROM clause term to search */ sqlite3_index_info *p; /* Object to pass to xBestIndex() */ int nConstraint; /* Number of constraints in p */ int bIn; /* True if plan uses IN(...) operator */ WhereLoop *pNew; Bitmask mBest; /* Tables used by best possible plan */ u16 mNoOmit; assert( (mPrereq & mUnusable)==0 ); pWInfo = pBuilder->pWInfo; pParse = pWInfo->pParse; pWC = pBuilder->pWC; pNew = pBuilder->pNew; pSrc = &pWInfo->pTabList->a[pNew->iTab]; assert( IsVirtual(pSrc->pTab) ); p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, &mNoOmit); if( p==0 ) return SQLITE_NOMEM_BKPT; pNew->rSetup = 0; pNew->wsFlags = WHERE_VIRTUALTABLE; pNew->nLTerm = 0; pNew->u.vtab.needFree = 0; nConstraint = p->nConstraint; if( whereLoopResize(pParse->db, pNew, nConstraint) ){ sqlite3DbFree(pParse->db, p); return SQLITE_NOMEM_BKPT; } /* First call xBestIndex() with all constraints usable. */ WHERETRACE(0x40, (" VirtualOne: all usable\n")); rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn); /* If the call to xBestIndex() with all terms enabled produced a plan ** that does not require any source tables (IOW: a plan with mBest==0), ** then there is no point in making any further calls to xBestIndex() ** since they will all return the same result (if the xBestIndex() ** implementation is sane). */ if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){ int seenZero = 0; /* True if a plan with no prereqs seen */ int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */ Bitmask mPrev = 0; Bitmask mBestNoIn = 0; /* If the plan produced by the earlier call uses an IN(...) term, call ** xBestIndex again, this time with IN(...) terms disabled. */ if( bIn ){ WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n")); rc = whereLoopAddVirtualOne( pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn); assert( bIn==0 ); mBestNoIn = pNew->prereq & ~mPrereq; if( mBestNoIn==0 ){ seenZero = 1; seenZeroNoIN = 1; } } /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) ** in the set of terms that apply to the current virtual table. */ while( rc==SQLITE_OK ){ int i; Bitmask mNext = ALLBITS; assert( mNext>0 ); for(i=0; i<nConstraint; i++){ Bitmask mThis = ( pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq ); if( mThis>mPrev && mThis<mNext ) mNext = mThis; } mPrev = mNext; if( mNext==ALLBITS ) break; if( mNext==mBest || mNext==mBestNoIn ) continue; WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n", (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext)); rc = whereLoopAddVirtualOne( pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn); if( pNew->prereq==mPrereq ){ seenZero = 1; if( bIn==0 ) seenZeroNoIN = 1; } } /* If the calls to xBestIndex() in the above loop did not find a plan ** that requires no source tables at all (i.e. one guaranteed to be ** usable), make a call here with all source tables disabled */ if( rc==SQLITE_OK && seenZero==0 ){ WHERETRACE(0x40, (" VirtualOne: all disabled\n")); rc = whereLoopAddVirtualOne( pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn); if( bIn==0 ) seenZeroNoIN = 1; } /* If the calls to xBestIndex() have so far failed to find a plan ** that requires no source tables at all and does not use an IN(...) ** operator, make a final call to obtain one here. */ if( rc==SQLITE_OK && seenZeroNoIN==0 ){ WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n")); rc = whereLoopAddVirtualOne( pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn); } } if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr); sqlite3DbFree(pParse->db, p); return rc; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* ** Add WhereLoop entries to handle OR terms. This works for either ** btrees or virtual tables. */ static int whereLoopAddOr( WhereLoopBuilder *pBuilder, Bitmask mPrereq, Bitmask mUnusable ){ WhereInfo *pWInfo = pBuilder->pWInfo; WhereClause *pWC; WhereLoop *pNew; WhereTerm *pTerm, *pWCEnd; int rc = SQLITE_OK; int iCur; WhereClause tempWC; WhereLoopBuilder sSubBuild; WhereOrSet sSum, sCur; struct SrcList_item *pItem; pWC = pBuilder->pWC; pWCEnd = pWC->a + pWC->nTerm; pNew = pBuilder->pNew; memset(&sSum, 0, sizeof(sSum)); pItem = pWInfo->pTabList->a + pNew->iTab; iCur = pItem->iCursor; for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){ if( (pTerm->eOperator & WO_OR)!=0 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 ){ WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; WhereTerm *pOrTerm; int once = 1; int i, j; sSubBuild = *pBuilder; sSubBuild.pOrderBy = 0; sSubBuild.pOrSet = &sCur; WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm)); for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){ if( (pOrTerm->eOperator & WO_AND)!=0 ){ sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; }else if( pOrTerm->leftCursor==iCur ){ tempWC.pWInfo = pWC->pWInfo; tempWC.pOuter = pWC; tempWC.op = TK_AND; tempWC.nTerm = 1; tempWC.a = pOrTerm; sSubBuild.pWC = &tempWC; }else{ continue; } sCur.n = 0; #ifdef WHERETRACE_ENABLED WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); if( sqlite3WhereTrace & 0x400 ){ sqlite3WhereClausePrint(sSubBuild.pWC); } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pItem->pTab) ){ rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable); }else #endif { rc = whereLoopAddBtree(&sSubBuild, mPrereq); } if( rc==SQLITE_OK ){ rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable); } assert( rc==SQLITE_OK || sCur.n==0 ); if( sCur.n==0 ){ sSum.n = 0; break; }else if( once ){ whereOrMove(&sSum, &sCur); once = 0; }else{ WhereOrSet sPrev; whereOrMove(&sPrev, &sSum); sSum.n = 0; for(i=0; i<sPrev.n; i++){ for(j=0; j<sCur.n; j++){ whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq, sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun), sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut)); } } } } pNew->nLTerm = 1; pNew->aLTerm[0] = pTerm; pNew->wsFlags = WHERE_MULTI_OR; pNew->rSetup = 0; pNew->iSortIdx = 0; memset(&pNew->u, 0, sizeof(pNew->u)); for(i=0; rc==SQLITE_OK && i<sSum.n; i++){ /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs ** of all sub-scans required by the OR-scan. However, due to rounding ** errors, it may be that the cost of the OR-scan is equal to its ** most expensive sub-scan. Add the smallest possible penalty ** (equivalent to multiplying the cost by 1.07) to ensure that ** this does not happen. Otherwise, for WHERE clauses such as the ** following where there is an index on "y": ** ** WHERE likelihood(x=?, 0.99) OR y=? ** ** the planner may elect to "OR" together a full-table scan and an ** index lookup. And other similarly odd results. */ pNew->rRun = sSum.a[i].rRun + 1; pNew->nOut = sSum.a[i].nOut; pNew->prereq = sSum.a[i].prereq; rc = whereLoopInsert(pBuilder, pNew); } WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm)); } } return rc; } /* ** Add all WhereLoop objects for all tables */ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ WhereInfo *pWInfo = pBuilder->pWInfo; Bitmask mPrereq = 0; Bitmask mPrior = 0; int iTab; SrcList *pTabList = pWInfo->pTabList; struct SrcList_item *pItem; struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel]; sqlite3 *db = pWInfo->pParse->db; int rc = SQLITE_OK; WhereLoop *pNew; u8 priorJointype = 0; /* Loop over the tables in the join, from left to right */ pNew = pBuilder->pNew; whereLoopInit(pNew); for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){ Bitmask mUnusable = 0; pNew->iTab = iTab; pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){ /* This condition is true when pItem is the FROM clause term on the ** right-hand-side of a LEFT or CROSS JOIN. */ mPrereq = mPrior; } priorJointype = pItem->fg.jointype; #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pItem->pTab) ){ struct SrcList_item *p; for(p=&pItem[1]; p<pEnd; p++){ if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){ mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); } } rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable); }else #endif /* SQLITE_OMIT_VIRTUALTABLE */ { rc = whereLoopAddBtree(pBuilder, mPrereq); } if( rc==SQLITE_OK ){ rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable); } mPrior |= pNew->maskSelf; if( rc || db->mallocFailed ) break; } whereLoopClear(db, pNew); return rc; } /* ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th ** parameters) to see if it outputs rows in the requested ORDER BY ** (or GROUP BY) without requiring a separate sort operation. Return N: ** ** N>0: N terms of the ORDER BY clause are satisfied ** N==0: No terms of the ORDER BY clause are satisfied ** N<0: Unknown yet how many terms of ORDER BY might be satisfied. ** ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as ** strict. With GROUP BY and DISTINCT the only requirement is that ** equivalent rows appear immediately adjacent to one another. GROUP BY ** and DISTINCT do not require rows to appear in any particular order as long ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT ** the pOrderBy terms can be matched in any order. With ORDER BY, the ** pOrderBy terms must be matched in strict left-to-right order. */ static i8 wherePathSatisfiesOrderBy( WhereInfo *pWInfo, /* The WHERE clause */ ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ WherePath *pPath, /* The WherePath to check */ u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */ u16 nLoop, /* Number of entries in pPath->aLoop[] */ WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ ){ u8 revSet; /* True if rev is known */ u8 rev; /* Composite sort order */ u8 revIdx; /* Index sort order */ u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ u16 eqOpMask; /* Allowed equality operators */ u16 nKeyCol; /* Number of key columns in pIndex */ u16 nColumn; /* Total number of ordered columns in the index */ u16 nOrderBy; /* Number terms in the ORDER BY clause */ int iLoop; /* Index of WhereLoop in pPath being processed */ int i, j; /* Loop counters */ int iCur; /* Cursor number for current WhereLoop */ int iColumn; /* A column number within table iCur */ WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ WhereTerm *pTerm; /* A single term of the WHERE clause */ Expr *pOBExpr; /* An expression from the ORDER BY clause */ CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ Index *pIndex; /* The index associated with pLoop */ sqlite3 *db = pWInfo->pParse->db; /* Database connection */ Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ Bitmask obDone; /* Mask of all ORDER BY terms */ Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ Bitmask ready; /* Mask of inner loops */ /* ** We say the WhereLoop is "one-row" if it generates no more than one ** row of output. A WhereLoop is one-row if all of the following are true: ** (a) All index columns match with WHERE_COLUMN_EQ. ** (b) The index is unique ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. ** ** We say the WhereLoop is "order-distinct" if the set of columns from ** that WhereLoop that are in the ORDER BY clause are different for every ** row of the WhereLoop. Every one-row WhereLoop is automatically ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause ** is not order-distinct. To be order-distinct is not quite the same as being ** UNIQUE since a UNIQUE column or index can have multiple rows that ** are NULL and NULL values are equivalent for the purpose of order-distinct. ** To be order-distinct, the columns must be UNIQUE and NOT NULL. ** ** The rowid for a table is always UNIQUE and NOT NULL so whenever the ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is ** automatically order-distinct. */ assert( pOrderBy!=0 ); if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; nOrderBy = pOrderBy->nExpr; testcase( nOrderBy==BMS-1 ); if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ isOrderDistinct = 1; obDone = MASKBIT(nOrderBy)-1; orderDistinctMask = 0; ready = 0; eqOpMask = WO_EQ | WO_IS | WO_ISNULL; if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN; for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){ if( iLoop>0 ) ready |= pLoop->maskSelf; if( iLoop<nLoop ){ pLoop = pPath->aLoop[iLoop]; if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue; }else{ pLoop = pLast; } if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ if( pLoop->u.vtab.isOrdered ) obSat = obDone; break; } iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; /* Mark off any ORDER BY term X that is a column in the table of ** the current loop for which there is term in the WHERE ** clause of the form X IS NULL or X=? that reference only outer ** loops. */ for(i=0; i<nOrderBy; i++){ if( MASKBIT(i) & obSat ) continue; pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); if( pOBExpr->op!=TK_COLUMN ) continue; if( pOBExpr->iTable!=iCur ) continue; pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, ~ready, eqOpMask, 0); if( pTerm==0 ) continue; if( pTerm->eOperator==WO_IN ){ /* IN terms are only valid for sorting in the ORDER BY LIMIT ** optimization, and then only if they are actually used ** by the query plan */ assert( wctrlFlags & WHERE_ORDERBY_LIMIT ); for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){} if( j>=pLoop->nLTerm ) continue; } if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){ const char *z1, *z2; pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); if( !pColl ) pColl = db->pDfltColl; z1 = pColl->zName; pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); if( !pColl ) pColl = db->pDfltColl; z2 = pColl->zName; if( sqlite3StrICmp(z1, z2)!=0 ) continue; testcase( pTerm->pExpr->op==TK_IS ); } obSat |= MASKBIT(i); } if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ if( pLoop->wsFlags & WHERE_IPK ){ pIndex = 0; nKeyCol = 0; nColumn = 1; }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ return 0; }else{ nKeyCol = pIndex->nKeyCol; nColumn = pIndex->nColumn; assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); assert( pIndex->aiColumn[nColumn-1]==XN_ROWID || !HasRowid(pIndex->pTable)); isOrderDistinct = IsUniqueIndex(pIndex); } /* Loop through all columns of the index and deal with the ones ** that are not constrained by == or IN. */ rev = revSet = 0; distinctColumns = 0; for(j=0; j<nColumn; j++){ u8 bOnce = 1; /* True to run the ORDER BY search loop */ assert( j>=pLoop->u.btree.nEq || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip) ); if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){ u16 eOp = pLoop->aLTerm[j]->eOperator; /* Skip over == and IS and ISNULL terms. (Also skip IN terms when ** doing WHERE_ORDERBY_LIMIT processing). ** ** If the current term is a column of an ((?,?) IN (SELECT...)) ** expression for which the SELECT returns more than one column, ** check that it is the only column used by this loop. Otherwise, ** if it is one of two or more, none of the columns can be ** considered to match an ORDER BY term. */ if( (eOp & eqOpMask)!=0 ){ if( eOp & WO_ISNULL ){ testcase( isOrderDistinct ); isOrderDistinct = 0; } continue; }else if( ALWAYS(eOp & WO_IN) ){ /* ALWAYS() justification: eOp is an equality operator due to the ** j<pLoop->u.btree.nEq constraint above. Any equality other ** than WO_IN is captured by the previous "if". So this one ** always has to be WO_IN. */ Expr *pX = pLoop->aLTerm[j]->pExpr; for(i=j+1; i<pLoop->u.btree.nEq; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ assert( (pLoop->aLTerm[i]->eOperator & WO_IN) ); bOnce = 0; break; } } } } /* Get the column number in the table (iColumn) and sort order ** (revIdx) for the j-th column of the index. */ if( pIndex ){ iColumn = pIndex->aiColumn[j]; revIdx = pIndex->aSortOrder[j]; if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; }else{ iColumn = XN_ROWID; revIdx = 0; } /* An unconstrained column that might be NULL means that this ** WhereLoop is not well-ordered */ if( isOrderDistinct && iColumn>=0 && j>=pLoop->u.btree.nEq && pIndex->pTable->aCol[iColumn].notNull==0 ){ isOrderDistinct = 0; } /* Find the ORDER BY term that corresponds to the j-th column ** of the index and mark that ORDER BY term off */ isMatch = 0; for(i=0; bOnce && i<nOrderBy; i++){ if( MASKBIT(i) & obSat ) continue; pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); testcase( wctrlFlags & WHERE_GROUPBY ); testcase( wctrlFlags & WHERE_DISTINCTBY ); if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; if( iColumn>=(-1) ){ if( pOBExpr->op!=TK_COLUMN ) continue; if( pOBExpr->iTable!=iCur ) continue; if( pOBExpr->iColumn!=iColumn ) continue; }else{ if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){ continue; } } if( iColumn>=0 ){ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); if( !pColl ) pColl = db->pDfltColl; if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; } isMatch = 1; break; } if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){ /* Make sure the sort order is compatible in an ORDER BY clause. ** Sort order is irrelevant for a GROUP BY clause. */ if( revSet ){ if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0; }else{ rev = revIdx ^ pOrderBy->a[i].sortOrder; if( rev ) *pRevMask |= MASKBIT(iLoop); revSet = 1; } } if( isMatch ){ if( iColumn==XN_ROWID ){ testcase( distinctColumns==0 ); distinctColumns = 1; } obSat |= MASKBIT(i); }else{ /* No match found */ if( j==0 || j<nKeyCol ){ testcase( isOrderDistinct!=0 ); isOrderDistinct = 0; } break; } } /* end Loop over all index columns */ if( distinctColumns ){ testcase( isOrderDistinct==0 ); isOrderDistinct = 1; } } /* end-if not one-row */ /* Mark off any other ORDER BY terms that reference pLoop */ if( isOrderDistinct ){ orderDistinctMask |= pLoop->maskSelf; for(i=0; i<nOrderBy; i++){ Expr *p; Bitmask mTerm; if( MASKBIT(i) & obSat ) continue; p = pOrderBy->a[i].pExpr; mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p); if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; if( (mTerm&~orderDistinctMask)==0 ){ obSat |= MASKBIT(i); } } } } /* End the loop over all WhereLoops from outer-most down to inner-most */ if( obSat==obDone ) return (i8)nOrderBy; if( !isOrderDistinct ){ for(i=nOrderBy-1; i>0; i--){ Bitmask m = MASKBIT(i) - 1; if( (obSat&m)==m ) return i; } return 0; } return -1; } /* ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(), ** the planner assumes that the specified pOrderBy list is actually a GROUP ** BY clause - and so any order that groups rows as required satisfies the ** request. ** ** Normally, in this case it is not possible for the caller to determine ** whether or not the rows are really being delivered in sorted order, or ** just in some other order that provides the required grouping. However, ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then ** this function may be called on the returned WhereInfo object. It returns ** true if the rows really will be sorted in the specified order, or false ** otherwise. ** ** For example, assuming: ** ** CREATE INDEX i1 ON t1(x, Y); ** ** then ** ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0 */ SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){ assert( pWInfo->wctrlFlags & WHERE_GROUPBY ); assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP ); return pWInfo->sorted; } #ifdef WHERETRACE_ENABLED /* For debugging use only: */ static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ static char zName[65]; int i; for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; } if( pLast ) zName[i++] = pLast->cId; zName[i] = 0; return zName; } #endif /* ** Return the cost of sorting nRow rows, assuming that the keys have ** nOrderby columns and that the first nSorted columns are already in ** order. */ static LogEst whereSortingCost( WhereInfo *pWInfo, LogEst nRow, int nOrderBy, int nSorted ){ /* TUNING: Estimated cost of a full external sort, where N is ** the number of rows to sort is: ** ** cost = (3.0 * N * log(N)). ** ** Or, if the order-by clause has X terms but only the last Y ** terms are out of order, then block-sorting will reduce the ** sorting cost to: ** ** cost = (3.0 * N * log(N)) * (Y/X) ** ** The (Y/X) term is implemented using stack variable rScale ** below. */ LogEst rScale, rSortCost; assert( nOrderBy>0 && 66==sqlite3LogEst(100) ); rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66; rSortCost = nRow + rScale + 16; /* Multiple by log(M) where M is the number of output rows. ** Use the LIMIT for M if it is smaller */ if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){ nRow = pWInfo->iLimit; } rSortCost += estLog(nRow); return rSortCost; } /* ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine ** attempts to find the lowest cost path that visits each WhereLoop ** once. This path is then loaded into the pWInfo->a[].pWLoop fields. ** ** Assume that the total number of output rows that will need to be sorted ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting ** costs if nRowEst==0. ** ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation ** error occurs. */ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ int mxChoice; /* Maximum number of simultaneous paths tracked */ int nLoop; /* Number of terms in the join */ Parse *pParse; /* Parsing context */ sqlite3 *db; /* The database connection */ int iLoop; /* Loop counter over the terms of the join */ int ii, jj; /* Loop counters */ int mxI = 0; /* Index of next entry to replace */ int nOrderBy; /* Number of ORDER BY clause terms */ LogEst mxCost = 0; /* Maximum cost of a set of paths */ LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */ int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ WherePath *aFrom; /* All nFrom paths at the previous level */ WherePath *aTo; /* The nTo best paths at the current level */ WherePath *pFrom; /* An element of aFrom[] that we are working on */ WherePath *pTo; /* An element of aTo[] that we are working on */ WhereLoop *pWLoop; /* One of the WhereLoop objects */ WhereLoop **pX; /* Used to divy up the pSpace memory */ LogEst *aSortCost = 0; /* Sorting and partial sorting costs */ char *pSpace; /* Temporary memory used by this routine */ int nSpace; /* Bytes of space allocated at pSpace */ pParse = pWInfo->pParse; db = pParse->db; nLoop = pWInfo->nLevel; /* TUNING: For simple queries, only the best path is tracked. ** For 2-way joins, the 5 best paths are followed. ** For joins of 3 or more tables, track the 10 best paths */ mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10); assert( nLoop<=pWInfo->pTabList->nSrc ); WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst)); /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this ** case the purpose of this call is to estimate the number of rows returned ** by the overall query. Once this estimate has been obtained, the caller ** will invoke this function a second time, passing the estimate as the ** nRowEst parameter. */ if( pWInfo->pOrderBy==0 || nRowEst==0 ){ nOrderBy = 0; }else{ nOrderBy = pWInfo->pOrderBy->nExpr; } /* Allocate and initialize space for aTo, aFrom and aSortCost[] */ nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; nSpace += sizeof(LogEst) * nOrderBy; pSpace = sqlite3DbMallocRawNN(db, nSpace); if( pSpace==0 ) return SQLITE_NOMEM_BKPT; aTo = (WherePath*)pSpace; aFrom = aTo+mxChoice; memset(aFrom, 0, sizeof(aFrom[0])); pX = (WhereLoop**)(aFrom+mxChoice); for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ pFrom->aLoop = pX; } if( nOrderBy ){ /* If there is an ORDER BY clause and it is not being ignored, set up ** space for the aSortCost[] array. Each element of the aSortCost array ** is either zero - meaning it has not yet been initialized - or the ** cost of sorting nRowEst rows of data where the first X terms of ** the ORDER BY clause are already in order, where X is the array ** index. */ aSortCost = (LogEst*)pX; memset(aSortCost, 0, sizeof(LogEst) * nOrderBy); } assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] ); assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX ); /* Seed the search with a single WherePath containing zero WhereLoops. ** ** TUNING: Do not let the number of iterations go above 28. If the cost ** of computing an automatic index is not paid back within the first 28 ** rows, then do not use the automatic index. */ aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) ); nFrom = 1; assert( aFrom[0].isOrdered==0 ); if( nOrderBy ){ /* If nLoop is zero, then there are no FROM terms in the query. Since ** in this case the query may return a maximum of one row, the results ** are already in the requested order. Set isOrdered to nOrderBy to ** indicate this. Or, if nLoop is greater than zero, set isOrdered to ** -1, indicating that the result set may or may not be ordered, ** depending on the loops added to the current plan. */ aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy; } /* Compute successively longer WherePaths using the previous generation ** of WherePaths as the basis for the next. Keep track of the mxChoice ** best paths at each generation */ for(iLoop=0; iLoop<nLoop; iLoop++){ nTo = 0; for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){ for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ LogEst nOut; /* Rows visited by (pFrom+pWLoop) */ LogEst rCost; /* Cost of path (pFrom+pWLoop) */ LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */ i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */ Bitmask maskNew; /* Mask of src visited by (..) */ Bitmask revMask = 0; /* Mask of rev-order loops for (..) */ if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){ /* Do not use an automatic index if the this loop is expected ** to run less than 2 times. */ assert( 10==sqlite3LogEst(2) ); continue; } /* At this point, pWLoop is a candidate to be the next loop. ** Compute its cost */ rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted); nOut = pFrom->nRow + pWLoop->nOut; maskNew = pFrom->maskLoop | pWLoop->maskSelf; if( isOrdered<0 ){ isOrdered = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, iLoop, pWLoop, &revMask); }else{ revMask = pFrom->revLoop; } if( isOrdered>=0 && isOrdered<nOrderBy ){ if( aSortCost[isOrdered]==0 ){ aSortCost[isOrdered] = whereSortingCost( pWInfo, nRowEst, nOrderBy, isOrdered ); } rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]); WHERETRACE(0x002, ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n", aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, rUnsorted, rCost)); }else{ rCost = rUnsorted; } /* Check to see if pWLoop should be added to the set of ** mxChoice best-so-far paths. ** ** First look for an existing path among best-so-far paths ** that covers the same set of loops and has the same isOrdered ** setting as the current path candidate. ** ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range ** of legal values for isOrdered, -1..64. */ for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){ if( pTo->maskLoop==maskNew && ((pTo->isOrdered^isOrdered)&0x80)==0 ){ testcase( jj==nTo-1 ); break; } } if( jj>=nTo ){ /* None of the existing best-so-far paths match the candidate. */ if( nTo>=mxChoice && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted)) ){ /* The current candidate is no better than any of the mxChoice ** paths currently in the best-so-far buffer. So discard ** this candidate as not viable. */ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n", wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, isOrdered>=0 ? isOrdered+'0' : '?'); } #endif continue; } /* If we reach this points it means that the new candidate path ** needs to be added to the set of best-so-far paths. */ if( nTo<mxChoice ){ /* Increase the size of the aTo set by one */ jj = nTo++; }else{ /* New path replaces the prior worst to keep count below mxChoice */ jj = mxI; } pTo = &aTo[jj]; #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n", wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, isOrdered>=0 ? isOrdered+'0' : '?'); } #endif }else{ /* Control reaches here if best-so-far path pTo=aTo[jj] covers the ** same set of loops and has the sam isOrdered setting as the ** candidate path. Check to see if the candidate should replace ** pTo or if the candidate should be skipped */ if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf( "Skip %s cost=%-3d,%3d order=%c", wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, isOrdered>=0 ? isOrdered+'0' : '?'); sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); } #endif /* Discard the candidate path from further consideration */ testcase( pTo->rCost==rCost ); continue; } testcase( pTo->rCost==rCost+1 ); /* Control reaches here if the candidate path is better than the ** pTo path. Replace pTo with the candidate. */ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf( "Update %s cost=%-3d,%3d order=%c", wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, isOrdered>=0 ? isOrdered+'0' : '?'); sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); } #endif } /* pWLoop is a winner. Add it to the set of best so far */ pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; pTo->revLoop = revMask; pTo->nRow = nOut; pTo->rCost = rCost; pTo->rUnsorted = rUnsorted; pTo->isOrdered = isOrdered; memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); pTo->aLoop[iLoop] = pWLoop; if( nTo>=mxChoice ){ mxI = 0; mxCost = aTo[0].rCost; mxUnsorted = aTo[0].nRow; for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){ if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) ){ mxCost = pTo->rCost; mxUnsorted = pTo->rUnsorted; mxI = jj; } } } } } #ifdef WHERETRACE_ENABLED /* >=2 */ if( sqlite3WhereTrace & 0x02 ){ sqlite3DebugPrintf("---- after round %d ----\n", iLoop); for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){ sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); if( pTo->isOrdered>0 ){ sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); }else{ sqlite3DebugPrintf("\n"); } } } #endif /* Swap the roles of aFrom and aTo for the next generation */ pFrom = aTo; aTo = aFrom; aFrom = pFrom; nFrom = nTo; } if( nFrom==0 ){ sqlite3ErrorMsg(pParse, "no query solution"); sqlite3DbFree(db, pSpace); return SQLITE_ERROR; } /* Find the lowest cost path. pFrom will be left pointing to that path */ pFrom = aFrom; for(ii=1; ii<nFrom; ii++){ if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; } assert( pWInfo->nLevel==nLoop ); /* Load the lowest cost path into pWInfo */ for(iLoop=0; iLoop<nLoop; iLoop++){ WhereLevel *pLevel = pWInfo->a + iLoop; pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; pLevel->iFrom = pWLoop->iTab; pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; } if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP && nRowEst ){ Bitmask notUsed; int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom, WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed); if( rc==pWInfo->pDistinctSet->nExpr ){ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; } } if( pWInfo->pOrderBy ){ if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; } }else{ pWInfo->nOBSat = pFrom->isOrdered; pWInfo->revMask = pFrom->revLoop; if( pWInfo->nOBSat<=0 ){ pWInfo->nOBSat = 0; if( nLoop>0 ){ u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags; if( (wsFlags & WHERE_ONEROW)==0 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN) ){ Bitmask m = 0; int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m); testcase( wsFlags & WHERE_IPK ); testcase( wsFlags & WHERE_COLUMN_IN ); if( rc==pWInfo->pOrderBy->nExpr ){ pWInfo->bOrderedInnerLoop = 1; pWInfo->revMask = m; } } } } } if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0 ){ Bitmask revMask = 0; int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask ); assert( pWInfo->sorted==0 ); if( nOrder==pWInfo->pOrderBy->nExpr ){ pWInfo->sorted = 1; pWInfo->revMask = revMask; } } } pWInfo->nRowOut = pFrom->nRow; /* Free temporary memory and return success */ sqlite3DbFree(db, pSpace); return SQLITE_OK; } /* ** Most queries use only a single table (they are not joins) and have ** simple == constraints against indexed fields. This routine attempts ** to plan those simple cases using much less ceremony than the ** general-purpose query planner, and thereby yield faster sqlite3_prepare() ** times for the common case. ** ** Return non-zero on success, if this query can be handled by this ** no-frills query planner. Return zero if this query needs the ** general-purpose query planner. */ static int whereShortCut(WhereLoopBuilder *pBuilder){ WhereInfo *pWInfo; struct SrcList_item *pItem; WhereClause *pWC; WhereTerm *pTerm; WhereLoop *pLoop; int iCur; int j; Table *pTab; Index *pIdx; pWInfo = pBuilder->pWInfo; if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0; assert( pWInfo->pTabList->nSrc>=1 ); pItem = pWInfo->pTabList->a; pTab = pItem->pTab; if( IsVirtual(pTab) ) return 0; if( pItem->fg.isIndexedBy ) return 0; iCur = pItem->iCursor; pWC = &pWInfo->sWC; pLoop = pBuilder->pNew; pLoop->wsFlags = 0; pLoop->nSkip = 0; pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0); if( pTerm ){ testcase( pTerm->eOperator & WO_IS ); pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; pLoop->aLTerm[0] = pTerm; pLoop->nLTerm = 1; pLoop->u.btree.nEq = 1; /* TUNING: Cost of a rowid lookup is 10 */ pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ }else{ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int opMask; assert( pLoop->aLTermSpace==pLoop->aLTerm ); if( !IsUniqueIndex(pIdx) || pIdx->pPartIdxWhere!=0 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) ) continue; opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ; for(j=0; j<pIdx->nKeyCol; j++){ pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx); if( pTerm==0 ) break; testcase( pTerm->eOperator & WO_IS ); pLoop->aLTerm[j] = pTerm; } if( j!=pIdx->nKeyCol ) continue; pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ pLoop->wsFlags |= WHERE_IDX_ONLY; } pLoop->nLTerm = j; pLoop->u.btree.nEq = j; pLoop->u.btree.pIndex = pIdx; /* TUNING: Cost of a unique index lookup is 15 */ pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ break; } } if( pLoop->wsFlags ){ pLoop->nOut = (LogEst)1; pWInfo->a[0].pWLoop = pLoop; pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); pWInfo->a[0].iTabCur = iCur; pWInfo->nRowOut = 1; if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; } #ifdef SQLITE_DEBUG pLoop->cId = '0'; #endif return 1; } return 0; } /* ** Generate the beginning of the loop used for WHERE clause processing. ** The return value is a pointer to an opaque structure that contains ** information needed to terminate the loop. Later, the calling routine ** should invoke sqlite3WhereEnd() with the return value of this function ** in order to complete the WHERE clause processing. ** ** If an error occurs, this routine returns NULL. ** ** The basic idea is to do a nested loop, one loop for each table in ** the FROM clause of a select. (INSERT and UPDATE statements are the ** same as a SELECT with only a single table in the FROM clause.) For ** example, if the SQL is this: ** ** SELECT * FROM t1, t2, t3 WHERE ...; ** ** Then the code generated is conceptually like the following: ** ** foreach row1 in t1 do \ Code generated ** foreach row2 in t2 do |-- by sqlite3WhereBegin() ** foreach row3 in t3 do / ** ... ** end \ Code generated ** end |-- by sqlite3WhereEnd() ** end / ** ** Note that the loops might not be nested in the order in which they ** appear in the FROM clause if a different order is better able to make ** use of indices. Note also that when the IN operator appears in ** the WHERE clause, it might result in additional nested loops for ** scanning through all values on the right-hand side of the IN. ** ** There are Btree cursors associated with each table. t1 uses cursor ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. ** And so forth. This routine generates code to open those VDBE cursors ** and sqlite3WhereEnd() generates the code to close them. ** ** The code that sqlite3WhereBegin() generates leaves the cursors named ** in pTabList pointing at their appropriate entries. The [...] code ** can use OP_Column and OP_Rowid opcodes on these cursors to extract ** data from the various tables of the loop. ** ** If the WHERE clause is empty, the foreach loops must each scan their ** entire tables. Thus a three-way join is an O(N^3) operation. But if ** the tables have indices and there are terms in the WHERE clause that ** refer to those indices, a complete table scan can be avoided and the ** code will run much faster. Most of the work of this routine is checking ** to see if there are indices that can be used to speed up the loop. ** ** Terms of the WHERE clause are also used to limit which rows actually ** make it to the "..." in the middle of the loop. After each "foreach", ** terms of the WHERE clause that use only terms in that loop and outer ** loops are evaluated and if false a jump is made around all subsequent ** inner loops (or around the "..." if the test occurs within the inner- ** most loop) ** ** OUTER JOINS ** ** An outer join of tables t1 and t2 is conceptally coded as follows: ** ** foreach row1 in t1 do ** flag = 0 ** foreach row2 in t2 do ** start: ** ... ** flag = 1 ** end ** if flag==0 then ** move the row2 cursor to a null row ** goto start ** fi ** end ** ** ORDER BY CLAUSE PROCESSING ** ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement ** if there is one. If there is no ORDER BY clause or if this routine ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. ** ** The iIdxCur parameter is the cursor number of an index. If ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index ** to use for OR clause processing. The WHERE clause should use this ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is ** the first cursor in an array of cursors for all indices. iIdxCur should ** be used to compute the appropriate cursor depending on which index is ** used. */ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( Parse *pParse, /* The parser context */ SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ Expr *pWhere, /* The WHERE clause */ ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */ ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */ u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */ int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number ** If WHERE_USE_LIMIT, then the limit amount */ ){ int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ int nTabList; /* Number of elements in pTabList */ WhereInfo *pWInfo; /* Will become the return value of this function */ Vdbe *v = pParse->pVdbe; /* The virtual database engine */ Bitmask notReady; /* Cursors that are not yet positioned */ WhereLoopBuilder sWLB; /* The WhereLoop builder */ WhereMaskSet *pMaskSet; /* The expression mask set */ WhereLevel *pLevel; /* A single level in pWInfo->a[] */ WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ int ii; /* Loop counter */ sqlite3 *db; /* Database connection */ int rc; /* Return code */ u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */ assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || ( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 )); /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */ assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 || (wctrlFlags & WHERE_USE_LIMIT)==0 ); /* Variable initialization */ db = pParse->db; memset(&sWLB, 0, sizeof(sWLB)); /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0; sWLB.pOrderBy = pOrderBy; /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ wctrlFlags &= ~WHERE_WANT_DISTINCT; } /* The number of tables in the FROM clause is limited by the number of ** bits in a Bitmask */ testcase( pTabList->nSrc==BMS ); if( pTabList->nSrc>BMS ){ sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); return 0; } /* This function normally generates a nested loop for all tables in ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should ** only generate code for the first table in pTabList and assume that ** any cursors associated with subsequent tables are uninitialized. */ nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc; /* Allocate and initialize the WhereInfo structure that will become the ** return value. A single allocation is used to store the WhereInfo ** struct, the contents of WhereInfo.a[], the WhereClause structure ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte ** field (type Bitmask) it must be aligned on an 8-byte boundary on ** some architectures. Hence the ROUND8() below. */ nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); if( db->mallocFailed ){ sqlite3DbFree(db, pWInfo); pWInfo = 0; goto whereBeginError; } pWInfo->pParse = pParse; pWInfo->pTabList = pTabList; pWInfo->pOrderBy = pOrderBy; pWInfo->pDistinctSet = pDistinctSet; pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; pWInfo->nLevel = nTabList; pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v); pWInfo->wctrlFlags = wctrlFlags; pWInfo->iLimit = iAuxArg; pWInfo->savedNQueryLoop = pParse->nQueryLoop; memset(&pWInfo->nOBSat, 0, offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat)); memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel)); assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */ pMaskSet = &pWInfo->sMaskSet; sWLB.pWInfo = pWInfo; sWLB.pWC = &pWInfo->sWC; sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); whereLoopInit(sWLB.pNew); #ifdef SQLITE_DEBUG sWLB.pNew->cId = '*'; #endif /* Split the WHERE clause into separate subexpressions where each ** subexpression is separated by an AND operator. */ initMaskSet(pMaskSet); sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo); sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND); /* Special case: a WHERE clause that is constant. Evaluate the ** expression and either jump over all of the code or fall thru. */ for(ii=0; ii<sWLB.pWC->nTerm; ii++){ if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){ sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL); sWLB.pWC->a[ii].wtFlags |= TERM_CODED; } } /* Special case: No FROM clause */ if( nTabList==0 ){ if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; if( wctrlFlags & WHERE_WANT_DISTINCT ){ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; } } /* Assign a bit from the bitmask to every term in the FROM clause. ** ** The N-th term of the FROM clause is assigned a bitmask of 1<<N. ** ** The rule of the previous sentence ensures thta if X is the bitmask for ** a table T, then X-1 is the bitmask for all other tables to the left of T. ** Knowing the bitmask for all tables to the left of a left join is ** important. Ticket #3015. ** ** Note that bitmasks are created for all pTabList->nSrc tables in ** pTabList, not just the first nTabList tables. nTabList is normally ** equal to pTabList->nSrc but might be shortened to 1 if the ** WHERE_OR_SUBCLAUSE flag is set. */ for(ii=0; ii<pTabList->nSrc; ii++){ createMask(pMaskSet, pTabList->a[ii].iCursor); sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); } #ifdef SQLITE_DEBUG for(ii=0; ii<pTabList->nSrc; ii++){ Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor); assert( m==MASKBIT(ii) ); } #endif /* Analyze all of the subexpressions. */ sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); if( db->mallocFailed ) goto whereBeginError; if( wctrlFlags & WHERE_WANT_DISTINCT ){ if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){ /* The DISTINCT marking is pointless. Ignore it. */ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; }else if( pOrderBy==0 ){ /* Try to ORDER BY the result set to make distinct processing easier */ pWInfo->wctrlFlags |= WHERE_DISTINCTBY; pWInfo->pOrderBy = pDistinctSet; } } /* Construct the WhereLoop objects */ #if defined(WHERETRACE_ENABLED) if( sqlite3WhereTrace & 0xffff ){ sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags); if( wctrlFlags & WHERE_USE_LIMIT ){ sqlite3DebugPrintf(", limit: %d", iAuxArg); } sqlite3DebugPrintf(")\n"); } if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ sqlite3WhereClausePrint(sWLB.pWC); } #endif if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ rc = whereLoopAddAll(&sWLB); if( rc ) goto whereBeginError; #ifdef WHERETRACE_ENABLED if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ WhereLoop *p; int i; static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ p->cId = zLabel[i%sizeof(zLabel)]; whereLoopPrint(p, sWLB.pWC); } } #endif wherePathSolver(pWInfo, 0); if( db->mallocFailed ) goto whereBeginError; if( pWInfo->pOrderBy ){ wherePathSolver(pWInfo, pWInfo->nRowOut+1); if( db->mallocFailed ) goto whereBeginError; } } if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ pWInfo->revMask = ALLBITS; } if( pParse->nErr || NEVER(db->mallocFailed) ){ goto whereBeginError; } #ifdef WHERETRACE_ENABLED if( sqlite3WhereTrace ){ sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); if( pWInfo->nOBSat>0 ){ sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); } switch( pWInfo->eDistinct ){ case WHERE_DISTINCT_UNIQUE: { sqlite3DebugPrintf(" DISTINCT=unique"); break; } case WHERE_DISTINCT_ORDERED: { sqlite3DebugPrintf(" DISTINCT=ordered"); break; } case WHERE_DISTINCT_UNORDERED: { sqlite3DebugPrintf(" DISTINCT=unordered"); break; } } sqlite3DebugPrintf("\n"); for(ii=0; ii<pWInfo->nLevel; ii++){ whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); } } #endif /* Attempt to omit tables from the join that do not effect the result */ if( pWInfo->nLevel>=2 && pDistinctSet!=0 && OptimizationEnabled(db, SQLITE_OmitNoopJoin) ){ Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet); if( sWLB.pOrderBy ){ tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy); } while( pWInfo->nLevel>=2 ){ WhereTerm *pTerm, *pEnd; pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break; if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 && (pLoop->wsFlags & WHERE_ONEROW)==0 ){ break; } if( (tabUsed & pLoop->maskSelf)!=0 ) break; pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ if( (pTerm->prereqAll & pLoop->maskSelf)!=0 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) ){ break; } } if( pTerm<pEnd ) break; WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId)); pWInfo->nLevel--; nTabList--; } } WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; /* If the caller is an UPDATE or DELETE statement that is requesting ** to use a one-pass algorithm, determine if this is appropriate. */ assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){ int wsFlags = pWInfo->a[0].pWLoop->wsFlags; int bOnerow = (wsFlags & WHERE_ONEROW)!=0; if( bOnerow || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0 && 0==(wsFlags & WHERE_VIRTUALTABLE)) ){ pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI; if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){ if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){ bFordelete = OPFLAG_FORDELETE; } pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY); } } } /* Open all tables in the pTabList and any indices selected for ** searching those tables. */ for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){ Table *pTab; /* Table to open */ int iDb; /* Index of database containing table/index */ struct SrcList_item *pTabItem; pTabItem = &pTabList->a[pLevel->iFrom]; pTab = pTabItem->pTab; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); pLoop = pLevel->pWLoop; if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ /* Do nothing */ }else #ifndef SQLITE_OMIT_VIRTUALTABLE if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); int iCur = pTabItem->iCursor; sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); }else if( IsVirtual(pTab) ){ /* noop */ }else #endif if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ int op = OP_OpenRead; if( pWInfo->eOnePass!=ONEPASS_OFF ){ op = OP_OpenWrite; pWInfo->aiCurOnePass[0] = pTabItem->iCursor; }; sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); assert( pTabItem->iCursor==pLevel->iTabCur ); testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 ); testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS ); if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){ Bitmask b = pTabItem->colUsed; int n = 0; for(; b; b=b>>1, n++){} sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32); assert( n<=pTab->nCol ); } #ifdef SQLITE_ENABLE_CURSOR_HINTS if( pLoop->u.btree.pIndex!=0 ){ sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete); }else #endif { sqlite3VdbeChangeP5(v, bFordelete); } #ifdef SQLITE_ENABLE_COLUMN_USED_MASK sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0, (const u8*)&pTabItem->colUsed, P4_INT64); #endif }else{ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); } if( pLoop->wsFlags & WHERE_INDEXED ){ Index *pIx = pLoop->u.btree.pIndex; int iIndexCur; int op = OP_OpenRead; /* iAuxArg is always set if to a positive value if ONEPASS is possible */ assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){ /* This is one term of an OR-optimization using the PRIMARY KEY of a ** WITHOUT ROWID table. No need for a separate index */ iIndexCur = pLevel->iTabCur; op = 0; }else if( pWInfo->eOnePass!=ONEPASS_OFF ){ Index *pJ = pTabItem->pTab->pIndex; iIndexCur = iAuxArg; assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); while( ALWAYS(pJ) && pJ!=pIx ){ iIndexCur++; pJ = pJ->pNext; } op = OP_OpenWrite; pWInfo->aiCurOnePass[1] = iIndexCur; }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){ iIndexCur = iAuxArg; op = OP_ReopenIdx; }else{ iIndexCur = pParse->nTab++; } pLevel->iIdxCur = iIndexCur; assert( pIx->pSchema==pTab->pSchema ); assert( iIndexCur>=0 ); if( op ){ sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); sqlite3VdbeSetP4KeyInfo(pParse, pIx); if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ){ sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */ } VdbeComment((v, "%s", pIx->zName)); #ifdef SQLITE_ENABLE_COLUMN_USED_MASK { u64 colUsed = 0; int ii, jj; for(ii=0; ii<pIx->nColumn; ii++){ jj = pIx->aiColumn[ii]; if( jj<0 ) continue; if( jj>63 ) jj = 63; if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue; colUsed |= ((u64)1)<<(ii<63 ? ii : 63); } sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0, (u8*)&colUsed, P4_INT64); } #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */ } } if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); } pWInfo->iTop = sqlite3VdbeCurrentAddr(v); if( db->mallocFailed ) goto whereBeginError; /* Generate the code to do the search. Each iteration of the for ** loop below generates code for a single nested loop of the VM ** program. */ notReady = ~(Bitmask)0; for(ii=0; ii<nTabList; ii++){ int addrExplain; int wsFlags; pLevel = &pWInfo->a[ii]; wsFlags = pLevel->pWLoop->wsFlags; #ifndef SQLITE_OMIT_AUTOMATIC_INDEX if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ constructAutomaticIndex(pParse, &pWInfo->sWC, &pTabList->a[pLevel->iFrom], notReady, pLevel); if( db->mallocFailed ) goto whereBeginError; } #endif addrExplain = sqlite3WhereExplainOneScan( pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags ); pLevel->addrBody = sqlite3VdbeCurrentAddr(v); notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady); pWInfo->iContinue = pLevel->addrCont; if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){ sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); } } /* Done. */ VdbeModuleComment((v, "Begin WHERE-core")); return pWInfo; /* Jump here if malloc fails */ whereBeginError: if( pWInfo ){ pParse->nQueryLoop = pWInfo->savedNQueryLoop; whereInfoFree(db, pWInfo); } return 0; } /* ** Generate the end of the WHERE loop. See comments on ** sqlite3WhereBegin() for additional information. */ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ Parse *pParse = pWInfo->pParse; Vdbe *v = pParse->pVdbe; int i; WhereLevel *pLevel; WhereLoop *pLoop; SrcList *pTabList = pWInfo->pTabList; sqlite3 *db = pParse->db; /* Generate loop termination code. */ VdbeModuleComment((v, "End WHERE-core")); sqlite3ExprCacheClear(pParse); for(i=pWInfo->nLevel-1; i>=0; i--){ int addr; pLevel = &pWInfo->a[i]; pLoop = pLevel->pWLoop; sqlite3VdbeResolveLabel(v, pLevel->addrCont); if( pLevel->op!=OP_Noop ){ sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); sqlite3VdbeChangeP5(v, pLevel->p5); VdbeCoverage(v); VdbeCoverageIf(v, pLevel->op==OP_Next); VdbeCoverageIf(v, pLevel->op==OP_Prev); VdbeCoverageIf(v, pLevel->op==OP_VNext); } if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ struct InLoop *pIn; int j; sqlite3VdbeResolveLabel(v, pLevel->addrNxt); for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ sqlite3VdbeJumpHere(v, pIn->addrInTop+1); if( pIn->eEndLoopOp!=OP_Noop ){ sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); VdbeCoverage(v); VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen); VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen); } sqlite3VdbeJumpHere(v, pIn->addrInTop-1); } } sqlite3VdbeResolveLabel(v, pLevel->addrBrk); if( pLevel->addrSkip ){ sqlite3VdbeGoto(v, pLevel->addrSkip); VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); sqlite3VdbeJumpHere(v, pLevel->addrSkip); sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); } #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( pLevel->addrLikeRep ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1), pLevel->addrLikeRep); VdbeCoverage(v); } #endif if( pLevel->iLeftJoin ){ int ws = pLoop->wsFlags; addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 ); if( (ws & WHERE_IDX_ONLY)==0 ){ sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); } if( (ws & WHERE_INDEXED) || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) ){ sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); } if( pLevel->op==OP_Return ){ sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); }else{ sqlite3VdbeGoto(v, pLevel->addrFirst); } sqlite3VdbeJumpHere(v, addr); } VdbeModuleComment((v, "End WHERE-loop%d: %s", i, pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); } /* The "break" point is here, just past the end of the outer loop. ** Set it. */ sqlite3VdbeResolveLabel(v, pWInfo->iBreak); assert( pWInfo->nLevel<=pTabList->nSrc ); for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){ int k, last; VdbeOp *pOp; Index *pIdx = 0; struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; Table *pTab = pTabItem->pTab; assert( pTab!=0 ); pLoop = pLevel->pWLoop; /* For a co-routine, change all OP_Column references to the table of ** the co-routine into OP_Copy of result contained in a register. ** OP_Rowid becomes OP_Null. */ if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){ translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur, pTabItem->regResult, 0); continue; } /* If this scan uses an index, make VDBE code substitutions to read data ** from the index instead of from the table where possible. In some cases ** this optimization prevents the table from ever being read, which can ** yield a significant performance boost. ** ** Calls to the code generator in between sqlite3WhereBegin and ** sqlite3WhereEnd will have created code that references the table ** directly. This loop scans all that code looking for opcodes ** that reference the table and converts them into opcodes that ** reference the index. */ if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ pIdx = pLoop->u.btree.pIndex; }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ pIdx = pLevel->u.pCovidx; } if( pIdx && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable)) && !db->mallocFailed ){ last = sqlite3VdbeCurrentAddr(v); k = pLevel->addrBody; pOp = sqlite3VdbeGetOp(v, k); for(; k<last; k++, pOp++){ if( pOp->p1!=pLevel->iTabCur ) continue; if( pOp->opcode==OP_Column ){ int x = pOp->p2; assert( pIdx->pTable==pTab ); if( !HasRowid(pTab) ){ Index *pPk = sqlite3PrimaryKeyIndex(pTab); x = pPk->aiColumn[x]; assert( x>=0 ); } x = sqlite3ColumnOfIndex(pIdx, x); if( x>=0 ){ pOp->p2 = x; pOp->p1 = pLevel->iIdxCur; } assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 || pWInfo->eOnePass ); }else if( pOp->opcode==OP_Rowid ){ pOp->p1 = pLevel->iIdxCur; pOp->opcode = OP_IdxRowid; } } } } /* Final cleanup */ pParse->nQueryLoop = pWInfo->savedNQueryLoop; whereInfoFree(db, pWInfo); return; } /************** End of where.c ***********************************************/ /************** Begin file parse.c *******************************************/ /* ** 2000-05-29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Driver template for the LEMON parser generator. ** ** The "lemon" program processes an LALR(1) input grammar file, then uses ** this template to construct a parser. The "lemon" program inserts text ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the ** interstitial "-" characters) contained in this template is changed into ** the value of the %name directive from the grammar. Otherwise, the content ** of this template is copied straight through into the generate parser ** source file. ** ** The following is the concatenation of all %include directives from the ** input grammar file: */ /* #include <stdio.h> */ /************ Begin %include sections from the grammar ************************/ /* #include "sqliteInt.h" */ /* ** Disable all error recovery processing in the parser push-down ** automaton. */ #define YYNOERRORRECOVERY 1 /* ** Make yytestcase() the same as testcase() */ #define yytestcase(X) testcase(X) /* ** Indicate that sqlite3ParserFree() will never be called with a null ** pointer. */ #define YYPARSEFREENEVERNULL 1 /* ** In the amalgamation, the parse.c file generated by lemon and the ** tokenize.c file are concatenated. In that case, sqlite3RunParser() ** has access to the the size of the yyParser object and so the parser ** engine can be allocated from stack. In that case, only the ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be ** omitted. */ #ifdef SQLITE_AMALGAMATION # define sqlite3Parser_ENGINEALWAYSONSTACK 1 #endif /* ** Alternative datatype for the argument to the malloc() routine passed ** into sqlite3ParserAlloc(). The default is size_t. */ #define YYMALLOCARGTYPE u64 /* ** An instance of this structure holds information about the ** LIMIT clause of a SELECT statement. */ struct LimitVal { Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */ Expr *pOffset; /* The OFFSET expression. NULL if there is none */ }; /* ** An instance of the following structure describes the event of a ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT, ** TK_DELETE, or TK_INSTEAD. If the event is of the form ** ** UPDATE ON (a,b,c) ** ** Then the "b" IdList records the list "a,b,c". */ struct TrigEvent { int a; IdList * b; }; /* ** Disable lookaside memory allocation for objects that might be ** shared across database connections. */ static void disableLookaside(Parse *pParse){ pParse->disableLookaside++; pParse->db->lookaside.bDisable++; } /* ** For a compound SELECT statement, make sure p->pPrior->pNext==p for ** all elements in the list. And make sure list length does not exceed ** SQLITE_LIMIT_COMPOUND_SELECT. */ static void parserDoubleLinkSelect(Parse *pParse, Select *p){ if( p->pPrior ){ Select *pNext = 0, *pLoop; int mxSelect, cnt = 0; for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){ pLoop->pNext = pNext; pLoop->selFlags |= SF_Compound; } if( (p->selFlags & SF_MultiValue)==0 && (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 && cnt>mxSelect ){ sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); } } } /* This is a utility routine used to set the ExprSpan.zStart and ** ExprSpan.zEnd values of pOut so that the span covers the complete ** range of text beginning with pStart and going to the end of pEnd. */ static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){ pOut->zStart = pStart->z; pOut->zEnd = &pEnd->z[pEnd->n]; } /* Construct a new Expr object from a single identifier. Use the ** new Expr to populate pOut. Set the span of pOut to be the identifier ** that created the expression. */ static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){ Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1); if( p ){ memset(p, 0, sizeof(Expr)); p->op = (u8)op; p->flags = EP_Leaf; p->iAgg = -1; p->u.zToken = (char*)&p[1]; memcpy(p->u.zToken, t.z, t.n); p->u.zToken[t.n] = 0; if( sqlite3Isquote(p->u.zToken[0]) ){ if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted; sqlite3Dequote(p->u.zToken); } #if SQLITE_MAX_EXPR_DEPTH>0 p->nHeight = 1; #endif } pOut->pExpr = p; pOut->zStart = t.z; pOut->zEnd = &t.z[t.n]; } /* This routine constructs a binary expression node out of two ExprSpan ** objects and uses the result to populate a new ExprSpan object. */ static void spanBinaryExpr( Parse *pParse, /* The parsing context. Errors accumulate here */ int op, /* The binary operation */ ExprSpan *pLeft, /* The left operand, and output */ ExprSpan *pRight /* The right operand */ ){ pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr); pLeft->zEnd = pRight->zEnd; } /* If doNot is true, then add a TK_NOT Expr-node wrapper around the ** outside of *ppExpr. */ static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){ if( doNot ){ pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0); } } /* Construct an expression node for a unary postfix operator */ static void spanUnaryPostfix( Parse *pParse, /* Parsing context to record errors */ int op, /* The operator */ ExprSpan *pOperand, /* The operand, and output */ Token *pPostOp /* The operand token for setting the span */ ){ pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0); pOperand->zEnd = &pPostOp->z[pPostOp->n]; } /* A routine to convert a binary TK_IS or TK_ISNOT expression into a ** unary TK_ISNULL or TK_NOTNULL expression. */ static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){ sqlite3 *db = pParse->db; if( pA && pY && pY->op==TK_NULL ){ pA->op = (u8)op; sqlite3ExprDelete(db, pA->pRight); pA->pRight = 0; } } /* Construct an expression node for a unary prefix operator */ static void spanUnaryPrefix( ExprSpan *pOut, /* Write the new expression node here */ Parse *pParse, /* Parsing context to record errors */ int op, /* The operator */ ExprSpan *pOperand, /* The operand */ Token *pPreOp /* The operand token for setting the span */ ){ pOut->zStart = pPreOp->z; pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0); pOut->zEnd = pOperand->zEnd; } /* Add a single new term to an ExprList that is used to store a ** list of identifiers. Report an error if the ID list contains ** a COLLATE clause or an ASC or DESC keyword, except ignore the ** error while parsing a legacy schema. */ static ExprList *parserAddExprIdListTerm( Parse *pParse, ExprList *pPrior, Token *pIdToken, int hasCollate, int sortOrder ){ ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0); if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED) && pParse->db->init.busy==0 ){ sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"", pIdToken->n, pIdToken->z); } sqlite3ExprListSetName(pParse, p, pIdToken, 1); return p; } /**************** End of %include directives **********************************/ /* These constants specify the various numeric values for terminal symbols ** in a format understandable to "makeheaders". This section is blank unless ** "lemon" is run with the "-m" command-line option. ***************** Begin makeheaders token definitions *************************/ /**************** End makeheaders token definitions ***************************/ /* The next sections is a series of control #defines. ** various aspects of the generated parser. ** YYCODETYPE is the data type used to store the integer codes ** that represent terminal and non-terminal symbols. ** "unsigned char" is used if there are fewer than ** 256 symbols. Larger types otherwise. ** YYNOCODE is a number of type YYCODETYPE that is not used for ** any terminal or nonterminal symbol. ** YYFALLBACK If defined, this indicates that one or more tokens ** (also known as: "terminal symbols") have fall-back ** values which should be used if the original symbol ** would not parse. This permits keywords to sometimes ** be used as identifiers, for example. ** YYACTIONTYPE is the data type used for "action codes" - numbers ** that indicate what to do in response to the next ** token. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal ** symbols. Background: A "minor type" is a semantic ** value associated with a terminal or non-terminal ** symbols. For example, for an "ID" terminal symbol, ** the minor type might be the name of the identifier. ** Each non-terminal can have a different minor type. ** Terminal symbols all have the same minor type, though. ** This macros defines the minor type for terminal ** symbols. ** YYMINORTYPE is the data type used for all minor types. ** This is typically a union of many types, one of ** which is sqlite3ParserTOKENTYPE. The entry in the union ** for terminal symbols is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. If ** zero the stack is dynamically sized using realloc() ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YY_MAX_SHIFT Maximum value for shift actions ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions ** YY_MIN_REDUCE Maximum value for reduce actions ** YY_ERROR_ACTION The yy_action[] code for syntax error ** YY_ACCEPT_ACTION The yy_action[] code for accept ** YY_NO_ACTION The yy_action[] code for no-op */ #ifndef INTERFACE # define INTERFACE 1 #endif /************* Begin control #defines *****************************************/ #define YYCODETYPE unsigned char #define YYNOCODE 252 #define YYACTIONTYPE unsigned short int #define YYWILDCARD 96 #define sqlite3ParserTOKENTYPE Token typedef union { int yyinit; sqlite3ParserTOKENTYPE yy0; Expr* yy72; TriggerStep* yy145; ExprList* yy148; SrcList* yy185; ExprSpan yy190; int yy194; Select* yy243; IdList* yy254; With* yy285; struct TrigEvent yy332; struct LimitVal yy354; struct {int value; int mask;} yy497; } YYMINORTYPE; #ifndef YYSTACKDEPTH #define YYSTACKDEPTH 100 #endif #define sqlite3ParserARG_SDECL Parse *pParse; #define sqlite3ParserARG_PDECL ,Parse *pParse #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse #define sqlite3ParserARG_STORE yypParser->pParse = pParse #define YYFALLBACK 1 #define YYNSTATE 456 #define YYNRULE 332 #define YY_MAX_SHIFT 455 #define YY_MIN_SHIFTREDUCE 668 #define YY_MAX_SHIFTREDUCE 999 #define YY_MIN_REDUCE 1000 #define YY_MAX_REDUCE 1331 #define YY_ERROR_ACTION 1332 #define YY_ACCEPT_ACTION 1333 #define YY_NO_ACTION 1334 /************* End control #defines *******************************************/ /* Define the yytestcase() macro to be a no-op if is not already defined ** otherwise. ** ** Applications can choose to define yytestcase() in the %include section ** to a macro that can assist in verifying code coverage. For production ** code the yytestcase() macro should be turned off. But it is useful ** for testing. */ #ifndef yytestcase # define yytestcase(X) #endif /* Next are the tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE. ** ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE ** and YY_MAX_REDUCE ** ** N == YY_ERROR_ACTION A syntax error has occurred. ** ** N == YY_ACCEPT_ACTION The parser accepts its input. ** ** N == YY_NO_ACTION No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as either: ** ** (A) N = yy_action[ yy_shift_ofst[S] + X ] ** (B) N = yy_default[S] ** ** The (A) formula is preferred. The B formula is used instead if: ** (1) The yy_shift_ofst[S]+X value is out of range, or ** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or ** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT. ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X. ** Hence only tests (1) and (2) need to be evaluated.) ** ** The formulas above are for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. ** *********** Begin parsing tables **********************************************/ #define YY_ACTTAB_COUNT (1567) static const YYACTIONTYPE yy_action[] = { /* 0 */ 325, 832, 351, 825, 5, 203, 203, 819, 99, 100, /* 10 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98, /* 20 */ 98, 98, 98, 301, 96, 96, 96, 96, 95, 95, /* 30 */ 94, 94, 94, 93, 351, 325, 977, 977, 824, 824, /* 40 */ 826, 947, 354, 99, 100, 90, 842, 842, 854, 857, /* 50 */ 846, 846, 97, 97, 98, 98, 98, 98, 338, 96, /* 60 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351, /* 70 */ 95, 95, 94, 94, 94, 93, 351, 791, 977, 977, /* 80 */ 325, 94, 94, 94, 93, 351, 792, 75, 99, 100, /* 90 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98, /* 100 */ 98, 98, 98, 450, 96, 96, 96, 96, 95, 95, /* 110 */ 94, 94, 94, 93, 351, 1333, 155, 155, 2, 325, /* 120 */ 275, 146, 132, 52, 52, 93, 351, 99, 100, 90, /* 130 */ 842, 842, 854, 857, 846, 846, 97, 97, 98, 98, /* 140 */ 98, 98, 101, 96, 96, 96, 96, 95, 95, 94, /* 150 */ 94, 94, 93, 351, 958, 958, 325, 268, 428, 413, /* 160 */ 411, 61, 752, 752, 99, 100, 90, 842, 842, 854, /* 170 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 60, /* 180 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 190 */ 351, 325, 270, 329, 273, 277, 959, 960, 250, 99, /* 200 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, /* 210 */ 98, 98, 98, 98, 301, 96, 96, 96, 96, 95, /* 220 */ 95, 94, 94, 94, 93, 351, 325, 938, 1326, 698, /* 230 */ 706, 1326, 242, 412, 99, 100, 90, 842, 842, 854, /* 240 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 347, /* 250 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 260 */ 351, 325, 938, 1327, 384, 699, 1327, 381, 379, 99, /* 270 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, /* 280 */ 98, 98, 98, 98, 701, 96, 96, 96, 96, 95, /* 290 */ 95, 94, 94, 94, 93, 351, 325, 92, 89, 178, /* 300 */ 833, 936, 373, 700, 99, 100, 90, 842, 842, 854, /* 310 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 375, /* 320 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 330 */ 351, 325, 1276, 947, 354, 818, 936, 739, 739, 99, /* 340 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, /* 350 */ 98, 98, 98, 98, 230, 96, 96, 96, 96, 95, /* 360 */ 95, 94, 94, 94, 93, 351, 325, 969, 227, 92, /* 370 */ 89, 178, 373, 300, 99, 100, 90, 842, 842, 854, /* 380 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 921, /* 390 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 400 */ 351, 325, 449, 447, 447, 447, 147, 737, 737, 99, /* 410 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, /* 420 */ 98, 98, 98, 98, 296, 96, 96, 96, 96, 95, /* 430 */ 95, 94, 94, 94, 93, 351, 325, 419, 231, 958, /* 440 */ 958, 158, 25, 422, 99, 100, 90, 842, 842, 854, /* 450 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 450, /* 460 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 470 */ 351, 443, 224, 224, 420, 958, 958, 962, 325, 52, /* 480 */ 52, 959, 960, 176, 415, 78, 99, 100, 90, 842, /* 490 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98, /* 500 */ 98, 379, 96, 96, 96, 96, 95, 95, 94, 94, /* 510 */ 94, 93, 351, 325, 428, 418, 298, 959, 960, 962, /* 520 */ 81, 99, 88, 90, 842, 842, 854, 857, 846, 846, /* 530 */ 97, 97, 98, 98, 98, 98, 717, 96, 96, 96, /* 540 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 843, /* 550 */ 843, 855, 858, 996, 318, 343, 379, 100, 90, 842, /* 560 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98, /* 570 */ 98, 450, 96, 96, 96, 96, 95, 95, 94, 94, /* 580 */ 94, 93, 351, 325, 350, 350, 350, 260, 377, 340, /* 590 */ 929, 52, 52, 90, 842, 842, 854, 857, 846, 846, /* 600 */ 97, 97, 98, 98, 98, 98, 361, 96, 96, 96, /* 610 */ 96, 95, 95, 94, 94, 94, 93, 351, 86, 445, /* 620 */ 847, 3, 1203, 361, 360, 378, 344, 813, 958, 958, /* 630 */ 1300, 86, 445, 729, 3, 212, 169, 287, 405, 282, /* 640 */ 404, 199, 232, 450, 300, 760, 83, 84, 280, 245, /* 650 */ 262, 365, 251, 85, 352, 352, 92, 89, 178, 83, /* 660 */ 84, 242, 412, 52, 52, 448, 85, 352, 352, 246, /* 670 */ 959, 960, 194, 455, 670, 402, 399, 398, 448, 243, /* 680 */ 221, 114, 434, 776, 361, 450, 397, 268, 747, 224, /* 690 */ 224, 132, 132, 198, 832, 434, 452, 451, 428, 427, /* 700 */ 819, 415, 734, 713, 132, 52, 52, 832, 268, 452, /* 710 */ 451, 734, 194, 819, 363, 402, 399, 398, 450, 1271, /* 720 */ 1271, 23, 958, 958, 86, 445, 397, 3, 228, 429, /* 730 */ 895, 824, 824, 826, 827, 19, 203, 720, 52, 52, /* 740 */ 428, 408, 439, 249, 824, 824, 826, 827, 19, 229, /* 750 */ 403, 153, 83, 84, 761, 177, 241, 450, 721, 85, /* 760 */ 352, 352, 120, 157, 959, 960, 58, 977, 409, 355, /* 770 */ 330, 448, 268, 428, 430, 320, 790, 32, 32, 86, /* 780 */ 445, 776, 3, 341, 98, 98, 98, 98, 434, 96, /* 790 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351, /* 800 */ 832, 120, 452, 451, 813, 887, 819, 83, 84, 977, /* 810 */ 813, 132, 410, 920, 85, 352, 352, 132, 407, 789, /* 820 */ 958, 958, 92, 89, 178, 917, 448, 262, 370, 261, /* 830 */ 82, 914, 80, 262, 370, 261, 776, 824, 824, 826, /* 840 */ 827, 19, 934, 434, 96, 96, 96, 96, 95, 95, /* 850 */ 94, 94, 94, 93, 351, 832, 74, 452, 451, 958, /* 860 */ 958, 819, 959, 960, 120, 92, 89, 178, 945, 2, /* 870 */ 918, 965, 268, 1, 976, 76, 445, 762, 3, 708, /* 880 */ 901, 901, 387, 958, 958, 757, 919, 371, 740, 778, /* 890 */ 756, 257, 824, 824, 826, 827, 19, 417, 741, 450, /* 900 */ 24, 959, 960, 83, 84, 369, 958, 958, 177, 226, /* 910 */ 85, 352, 352, 885, 315, 314, 313, 215, 311, 10, /* 920 */ 10, 683, 448, 349, 348, 959, 960, 909, 777, 157, /* 930 */ 120, 958, 958, 337, 776, 416, 711, 310, 450, 434, /* 940 */ 450, 321, 450, 791, 103, 200, 175, 450, 959, 960, /* 950 */ 908, 832, 792, 452, 451, 9, 9, 819, 10, 10, /* 960 */ 52, 52, 51, 51, 180, 716, 248, 10, 10, 171, /* 970 */ 170, 167, 339, 959, 960, 247, 984, 702, 702, 450, /* 980 */ 715, 233, 686, 982, 889, 983, 182, 914, 824, 824, /* 990 */ 826, 827, 19, 183, 256, 423, 132, 181, 394, 10, /* 1000 */ 10, 889, 891, 749, 958, 958, 917, 268, 985, 198, /* 1010 */ 985, 349, 348, 425, 415, 299, 817, 832, 326, 825, /* 1020 */ 120, 332, 133, 819, 268, 98, 98, 98, 98, 91, /* 1030 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, /* 1040 */ 351, 157, 810, 371, 382, 359, 959, 960, 358, 268, /* 1050 */ 450, 918, 368, 324, 824, 824, 826, 450, 709, 450, /* 1060 */ 264, 380, 889, 450, 877, 746, 253, 919, 255, 433, /* 1070 */ 36, 36, 234, 450, 234, 120, 269, 37, 37, 12, /* 1080 */ 12, 334, 272, 27, 27, 450, 330, 118, 450, 162, /* 1090 */ 742, 280, 450, 38, 38, 450, 985, 356, 985, 450, /* 1100 */ 709, 1210, 450, 132, 450, 39, 39, 450, 40, 40, /* 1110 */ 450, 362, 41, 41, 450, 42, 42, 450, 254, 28, /* 1120 */ 28, 450, 29, 29, 31, 31, 450, 43, 43, 450, /* 1130 */ 44, 44, 450, 714, 45, 45, 450, 11, 11, 767, /* 1140 */ 450, 46, 46, 450, 268, 450, 105, 105, 450, 47, /* 1150 */ 47, 450, 48, 48, 450, 237, 33, 33, 450, 172, /* 1160 */ 49, 49, 450, 50, 50, 34, 34, 274, 122, 122, /* 1170 */ 450, 123, 123, 450, 124, 124, 450, 898, 56, 56, /* 1180 */ 450, 897, 35, 35, 450, 267, 450, 817, 450, 817, /* 1190 */ 106, 106, 450, 53, 53, 385, 107, 107, 450, 817, /* 1200 */ 108, 108, 817, 450, 104, 104, 121, 121, 119, 119, /* 1210 */ 450, 117, 112, 112, 450, 276, 450, 225, 111, 111, /* 1220 */ 450, 730, 450, 109, 109, 450, 673, 674, 675, 912, /* 1230 */ 110, 110, 317, 998, 55, 55, 57, 57, 692, 331, /* 1240 */ 54, 54, 26, 26, 696, 30, 30, 317, 937, 197, /* 1250 */ 196, 195, 335, 281, 336, 446, 331, 745, 689, 436, /* 1260 */ 440, 444, 120, 72, 386, 223, 175, 345, 757, 933, /* 1270 */ 20, 286, 319, 756, 815, 372, 374, 202, 202, 202, /* 1280 */ 263, 395, 285, 74, 208, 21, 696, 719, 718, 884, /* 1290 */ 120, 120, 120, 120, 120, 754, 278, 828, 77, 74, /* 1300 */ 726, 727, 785, 783, 880, 202, 999, 208, 894, 893, /* 1310 */ 894, 893, 694, 816, 763, 116, 774, 1290, 431, 432, /* 1320 */ 302, 999, 390, 303, 823, 697, 691, 680, 159, 289, /* 1330 */ 679, 884, 681, 952, 291, 218, 293, 7, 316, 828, /* 1340 */ 173, 805, 259, 364, 252, 911, 376, 713, 295, 435, /* 1350 */ 308, 168, 955, 993, 135, 400, 990, 284, 882, 881, /* 1360 */ 205, 928, 926, 59, 333, 62, 144, 156, 130, 72, /* 1370 */ 802, 366, 367, 393, 137, 185, 189, 160, 139, 383, /* 1380 */ 67, 896, 140, 141, 142, 148, 389, 812, 775, 266, /* 1390 */ 219, 190, 154, 391, 913, 876, 271, 406, 191, 322, /* 1400 */ 682, 733, 192, 342, 732, 724, 731, 711, 723, 421, /* 1410 */ 705, 71, 323, 6, 204, 771, 288, 79, 297, 346, /* 1420 */ 772, 704, 290, 283, 703, 770, 292, 294, 967, 239, /* 1430 */ 769, 102, 862, 438, 426, 240, 424, 442, 73, 213, /* 1440 */ 688, 238, 22, 453, 953, 214, 217, 216, 454, 677, /* 1450 */ 676, 671, 753, 125, 115, 235, 126, 669, 353, 166, /* 1460 */ 127, 244, 179, 357, 306, 304, 305, 307, 113, 892, /* 1470 */ 327, 890, 811, 328, 134, 128, 136, 138, 743, 258, /* 1480 */ 907, 184, 143, 129, 910, 186, 63, 64, 145, 187, /* 1490 */ 906, 65, 8, 66, 13, 188, 202, 899, 265, 149, /* 1500 */ 987, 388, 150, 685, 161, 392, 285, 193, 279, 396, /* 1510 */ 151, 401, 68, 14, 15, 722, 69, 236, 831, 131, /* 1520 */ 830, 860, 70, 751, 16, 414, 755, 4, 174, 220, /* 1530 */ 222, 784, 201, 152, 779, 77, 74, 17, 18, 875, /* 1540 */ 861, 859, 916, 864, 915, 207, 206, 942, 163, 437, /* 1550 */ 948, 943, 164, 209, 1002, 441, 863, 165, 210, 829, /* 1560 */ 695, 87, 312, 211, 1292, 1291, 309, }; static const YYCODETYPE yy_lookahead[] = { /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28, /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48, /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133, /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33, /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 187, 43, /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97, /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28, /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48, /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19, /* 120 */ 16, 22, 92, 172, 173, 52, 53, 27, 28, 29, /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49, /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208, /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32, /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79, /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 190 */ 53, 19, 88, 157, 90, 23, 97, 98, 193, 27, /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47, /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172, /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32, /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187, /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 260 */ 53, 19, 22, 23, 228, 23, 26, 231, 152, 27, /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, /* 280 */ 38, 39, 40, 41, 172, 43, 44, 45, 46, 47, /* 290 */ 48, 49, 50, 51, 52, 53, 19, 221, 222, 223, /* 300 */ 23, 96, 152, 172, 27, 28, 29, 30, 31, 32, /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152, /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 330 */ 53, 19, 0, 1, 2, 23, 96, 190, 191, 27, /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, /* 350 */ 38, 39, 40, 41, 238, 43, 44, 45, 46, 47, /* 360 */ 48, 49, 50, 51, 52, 53, 19, 185, 218, 221, /* 370 */ 222, 223, 152, 152, 27, 28, 29, 30, 31, 32, /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 241, /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 400 */ 53, 19, 152, 168, 169, 170, 22, 190, 191, 27, /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47, /* 430 */ 48, 49, 50, 51, 52, 53, 19, 19, 218, 55, /* 440 */ 56, 24, 22, 152, 27, 28, 29, 30, 31, 32, /* 450 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152, /* 460 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 470 */ 53, 250, 194, 195, 56, 55, 56, 55, 19, 172, /* 480 */ 173, 97, 98, 152, 206, 138, 27, 28, 29, 30, /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 500 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50, /* 510 */ 51, 52, 53, 19, 207, 208, 152, 97, 98, 97, /* 520 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35, /* 530 */ 36, 37, 38, 39, 40, 41, 181, 43, 44, 45, /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 30, /* 550 */ 31, 32, 33, 247, 248, 19, 152, 28, 29, 30, /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50, /* 580 */ 51, 52, 53, 19, 168, 169, 170, 238, 19, 53, /* 590 */ 152, 172, 173, 29, 30, 31, 32, 33, 34, 35, /* 600 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45, /* 610 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 20, /* 620 */ 101, 22, 23, 169, 170, 56, 207, 85, 55, 56, /* 630 */ 23, 19, 20, 26, 22, 99, 100, 101, 102, 103, /* 640 */ 104, 105, 238, 152, 152, 210, 47, 48, 112, 152, /* 650 */ 108, 109, 110, 54, 55, 56, 221, 222, 223, 47, /* 660 */ 48, 119, 120, 172, 173, 66, 54, 55, 56, 152, /* 670 */ 97, 98, 99, 148, 149, 102, 103, 104, 66, 154, /* 680 */ 23, 156, 83, 26, 230, 152, 113, 152, 163, 194, /* 690 */ 195, 92, 92, 30, 95, 83, 97, 98, 207, 208, /* 700 */ 101, 206, 179, 180, 92, 172, 173, 95, 152, 97, /* 710 */ 98, 188, 99, 101, 219, 102, 103, 104, 152, 119, /* 720 */ 120, 196, 55, 56, 19, 20, 113, 22, 193, 163, /* 730 */ 11, 132, 133, 134, 135, 136, 24, 65, 172, 173, /* 740 */ 207, 208, 250, 152, 132, 133, 134, 135, 136, 193, /* 750 */ 78, 84, 47, 48, 49, 98, 199, 152, 86, 54, /* 760 */ 55, 56, 196, 152, 97, 98, 209, 55, 163, 244, /* 770 */ 107, 66, 152, 207, 208, 164, 175, 172, 173, 19, /* 780 */ 20, 124, 22, 111, 38, 39, 40, 41, 83, 43, /* 790 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, /* 800 */ 95, 196, 97, 98, 85, 152, 101, 47, 48, 97, /* 810 */ 85, 92, 207, 193, 54, 55, 56, 92, 49, 175, /* 820 */ 55, 56, 221, 222, 223, 12, 66, 108, 109, 110, /* 830 */ 137, 163, 139, 108, 109, 110, 26, 132, 133, 134, /* 840 */ 135, 136, 152, 83, 43, 44, 45, 46, 47, 48, /* 850 */ 49, 50, 51, 52, 53, 95, 26, 97, 98, 55, /* 860 */ 56, 101, 97, 98, 196, 221, 222, 223, 146, 147, /* 870 */ 57, 171, 152, 22, 26, 19, 20, 49, 22, 179, /* 880 */ 108, 109, 110, 55, 56, 116, 73, 219, 75, 124, /* 890 */ 121, 152, 132, 133, 134, 135, 136, 163, 85, 152, /* 900 */ 232, 97, 98, 47, 48, 237, 55, 56, 98, 5, /* 910 */ 54, 55, 56, 193, 10, 11, 12, 13, 14, 172, /* 920 */ 173, 17, 66, 47, 48, 97, 98, 152, 124, 152, /* 930 */ 196, 55, 56, 186, 124, 152, 106, 160, 152, 83, /* 940 */ 152, 164, 152, 61, 22, 211, 212, 152, 97, 98, /* 950 */ 152, 95, 70, 97, 98, 172, 173, 101, 172, 173, /* 960 */ 172, 173, 172, 173, 60, 181, 62, 172, 173, 47, /* 970 */ 48, 123, 186, 97, 98, 71, 100, 55, 56, 152, /* 980 */ 181, 186, 21, 107, 152, 109, 82, 163, 132, 133, /* 990 */ 134, 135, 136, 89, 16, 207, 92, 93, 19, 172, /* 1000 */ 173, 169, 170, 195, 55, 56, 12, 152, 132, 30, /* 1010 */ 134, 47, 48, 186, 206, 225, 152, 95, 114, 97, /* 1020 */ 196, 245, 246, 101, 152, 38, 39, 40, 41, 42, /* 1030 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, /* 1040 */ 53, 152, 163, 219, 152, 141, 97, 98, 193, 152, /* 1050 */ 152, 57, 91, 164, 132, 133, 134, 152, 55, 152, /* 1060 */ 152, 237, 230, 152, 103, 193, 88, 73, 90, 75, /* 1070 */ 172, 173, 183, 152, 185, 196, 152, 172, 173, 172, /* 1080 */ 173, 217, 152, 172, 173, 152, 107, 22, 152, 24, /* 1090 */ 193, 112, 152, 172, 173, 152, 132, 242, 134, 152, /* 1100 */ 97, 140, 152, 92, 152, 172, 173, 152, 172, 173, /* 1110 */ 152, 100, 172, 173, 152, 172, 173, 152, 140, 172, /* 1120 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152, /* 1130 */ 172, 173, 152, 152, 172, 173, 152, 172, 173, 213, /* 1140 */ 152, 172, 173, 152, 152, 152, 172, 173, 152, 172, /* 1150 */ 173, 152, 172, 173, 152, 210, 172, 173, 152, 26, /* 1160 */ 172, 173, 152, 172, 173, 172, 173, 152, 172, 173, /* 1170 */ 152, 172, 173, 152, 172, 173, 152, 59, 172, 173, /* 1180 */ 152, 63, 172, 173, 152, 193, 152, 152, 152, 152, /* 1190 */ 172, 173, 152, 172, 173, 77, 172, 173, 152, 152, /* 1200 */ 172, 173, 152, 152, 172, 173, 172, 173, 172, 173, /* 1210 */ 152, 22, 172, 173, 152, 152, 152, 22, 172, 173, /* 1220 */ 152, 152, 152, 172, 173, 152, 7, 8, 9, 163, /* 1230 */ 172, 173, 22, 23, 172, 173, 172, 173, 166, 167, /* 1240 */ 172, 173, 172, 173, 55, 172, 173, 22, 23, 108, /* 1250 */ 109, 110, 217, 152, 217, 166, 167, 163, 163, 163, /* 1260 */ 163, 163, 196, 130, 217, 211, 212, 217, 116, 23, /* 1270 */ 22, 101, 26, 121, 23, 23, 23, 26, 26, 26, /* 1280 */ 23, 23, 112, 26, 26, 37, 97, 100, 101, 55, /* 1290 */ 196, 196, 196, 196, 196, 23, 23, 55, 26, 26, /* 1300 */ 7, 8, 23, 152, 23, 26, 96, 26, 132, 132, /* 1310 */ 134, 134, 23, 152, 152, 26, 152, 122, 152, 191, /* 1320 */ 152, 96, 234, 152, 152, 152, 152, 152, 197, 210, /* 1330 */ 152, 97, 152, 152, 210, 233, 210, 198, 150, 97, /* 1340 */ 184, 201, 239, 214, 214, 201, 239, 180, 214, 227, /* 1350 */ 200, 198, 155, 67, 243, 176, 69, 175, 175, 175, /* 1360 */ 122, 159, 159, 240, 159, 240, 22, 220, 27, 130, /* 1370 */ 201, 18, 159, 18, 189, 158, 158, 220, 192, 159, /* 1380 */ 137, 236, 192, 192, 192, 189, 74, 189, 159, 235, /* 1390 */ 159, 158, 22, 177, 201, 201, 159, 107, 158, 177, /* 1400 */ 159, 174, 158, 76, 174, 182, 174, 106, 182, 125, /* 1410 */ 174, 107, 177, 22, 159, 216, 215, 137, 159, 53, /* 1420 */ 216, 176, 215, 174, 174, 216, 215, 215, 174, 229, /* 1430 */ 216, 129, 224, 177, 126, 229, 127, 177, 128, 25, /* 1440 */ 162, 226, 26, 161, 13, 153, 6, 153, 151, 151, /* 1450 */ 151, 151, 205, 165, 178, 178, 165, 4, 3, 22, /* 1460 */ 165, 142, 15, 94, 202, 204, 203, 201, 16, 23, /* 1470 */ 249, 23, 120, 249, 246, 111, 131, 123, 20, 16, /* 1480 */ 1, 125, 123, 111, 56, 64, 37, 37, 131, 122, /* 1490 */ 1, 37, 5, 37, 22, 107, 26, 80, 140, 80, /* 1500 */ 87, 72, 107, 20, 24, 19, 112, 105, 23, 79, /* 1510 */ 22, 79, 22, 22, 22, 58, 22, 79, 23, 68, /* 1520 */ 23, 23, 26, 116, 22, 26, 23, 22, 122, 23, /* 1530 */ 23, 56, 64, 22, 124, 26, 26, 64, 64, 23, /* 1540 */ 23, 23, 23, 11, 23, 22, 26, 23, 22, 24, /* 1550 */ 1, 23, 22, 26, 251, 24, 23, 22, 122, 23, /* 1560 */ 23, 22, 15, 122, 122, 122, 23, }; #define YY_SHIFT_USE_DFLT (1567) #define YY_SHIFT_COUNT (455) #define YY_SHIFT_MIN (-94) #define YY_SHIFT_MAX (1549) static const short yy_shift_ofst[] = { /* 0 */ 40, 599, 904, 612, 760, 760, 760, 760, 725, -19, /* 10 */ 16, 16, 100, 760, 760, 760, 760, 760, 760, 760, /* 20 */ 876, 876, 573, 542, 719, 600, 61, 137, 172, 207, /* 30 */ 242, 277, 312, 347, 382, 417, 459, 459, 459, 459, /* 40 */ 459, 459, 459, 459, 459, 459, 459, 459, 459, 459, /* 50 */ 459, 459, 459, 494, 459, 529, 564, 564, 705, 760, /* 60 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, /* 70 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, /* 80 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, /* 90 */ 856, 760, 760, 760, 760, 760, 760, 760, 760, 760, /* 100 */ 760, 760, 760, 760, 987, 746, 746, 746, 746, 746, /* 110 */ 801, 23, 32, 949, 961, 979, 964, 964, 949, 73, /* 120 */ 113, -51, 1567, 1567, 1567, 536, 536, 536, 99, 99, /* 130 */ 813, 813, 667, 205, 240, 949, 949, 949, 949, 949, /* 140 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949, /* 150 */ 949, 949, 949, 949, 949, 332, 1011, 422, 422, 113, /* 160 */ 30, 30, 30, 30, 30, 30, 1567, 1567, 1567, 922, /* 170 */ -94, -94, 384, 613, 828, 420, 765, 804, 851, 949, /* 180 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949, /* 190 */ 949, 949, 949, 949, 949, 672, 672, 672, 949, 949, /* 200 */ 657, 949, 949, 949, -18, 949, 949, 994, 949, 949, /* 210 */ 949, 949, 949, 949, 949, 949, 949, 949, 772, 1118, /* 220 */ 712, 712, 712, 810, 45, 769, 1219, 1133, 418, 418, /* 230 */ 569, 1133, 569, 830, 607, 663, 882, 418, 693, 882, /* 240 */ 882, 848, 1152, 1065, 1286, 1238, 1238, 1287, 1287, 1238, /* 250 */ 1344, 1341, 1239, 1353, 1353, 1353, 1353, 1238, 1355, 1239, /* 260 */ 1344, 1341, 1341, 1239, 1238, 1355, 1243, 1312, 1238, 1238, /* 270 */ 1355, 1370, 1238, 1355, 1238, 1355, 1370, 1290, 1290, 1290, /* 280 */ 1327, 1370, 1290, 1301, 1290, 1327, 1290, 1290, 1284, 1304, /* 290 */ 1284, 1304, 1284, 1304, 1284, 1304, 1238, 1391, 1238, 1280, /* 300 */ 1370, 1366, 1366, 1370, 1302, 1308, 1310, 1309, 1239, 1414, /* 310 */ 1416, 1431, 1431, 1440, 1440, 1440, 1440, 1567, 1567, 1567, /* 320 */ 1567, 1567, 1567, 1567, 1567, 519, 978, 1210, 1225, 104, /* 330 */ 1141, 1189, 1246, 1248, 1251, 1252, 1253, 1257, 1258, 1273, /* 340 */ 1003, 1187, 1293, 1170, 1272, 1279, 1234, 1281, 1176, 1177, /* 350 */ 1289, 1242, 1195, 1453, 1455, 1437, 1319, 1447, 1369, 1452, /* 360 */ 1446, 1448, 1352, 1345, 1364, 1354, 1458, 1356, 1463, 1479, /* 370 */ 1359, 1357, 1449, 1450, 1454, 1456, 1372, 1428, 1421, 1367, /* 380 */ 1489, 1487, 1472, 1388, 1358, 1417, 1470, 1419, 1413, 1429, /* 390 */ 1395, 1480, 1483, 1486, 1394, 1402, 1488, 1430, 1490, 1491, /* 400 */ 1485, 1492, 1432, 1457, 1494, 1438, 1451, 1495, 1497, 1498, /* 410 */ 1496, 1407, 1502, 1503, 1505, 1499, 1406, 1506, 1507, 1475, /* 420 */ 1468, 1511, 1410, 1509, 1473, 1510, 1474, 1516, 1509, 1517, /* 430 */ 1518, 1519, 1520, 1521, 1523, 1532, 1524, 1526, 1525, 1527, /* 440 */ 1528, 1530, 1531, 1527, 1533, 1535, 1536, 1537, 1539, 1436, /* 450 */ 1441, 1442, 1443, 1543, 1547, 1549, }; #define YY_REDUCE_USE_DFLT (-130) #define YY_REDUCE_COUNT (324) #define YY_REDUCE_MIN (-129) #define YY_REDUCE_MAX (1300) static const short yy_reduce_ofst[] = { /* 0 */ -29, 566, 525, 605, -49, 307, 491, 533, 668, 435, /* 10 */ 601, 644, 148, 747, 786, 795, 419, 788, 827, 790, /* 20 */ 454, 832, 889, 495, 824, 734, 76, 76, 76, 76, /* 30 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, /* 40 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, /* 50 */ 76, 76, 76, 76, 76, 76, 76, 76, 783, 898, /* 60 */ 905, 907, 911, 921, 933, 936, 940, 943, 947, 950, /* 70 */ 952, 955, 958, 962, 965, 969, 974, 977, 980, 984, /* 80 */ 988, 991, 993, 996, 999, 1002, 1006, 1010, 1018, 1021, /* 90 */ 1024, 1028, 1032, 1034, 1036, 1040, 1046, 1051, 1058, 1062, /* 100 */ 1064, 1068, 1070, 1073, 76, 76, 76, 76, 76, 76, /* 110 */ 76, 76, 76, 855, 36, 523, 235, 416, 777, 76, /* 120 */ 278, 76, 76, 76, 76, 700, 700, 700, 150, 220, /* 130 */ 147, 217, 221, 306, 306, 611, 5, 535, 556, 620, /* 140 */ 720, 872, 897, 116, 864, 349, 1035, 1037, 404, 1047, /* 150 */ 992, -129, 1050, 492, 62, 722, 879, 1072, 1089, 808, /* 160 */ 1066, 1094, 1095, 1096, 1097, 1098, 776, 1054, 557, 57, /* 170 */ 112, 131, 167, 182, 250, 272, 291, 331, 364, 438, /* 180 */ 497, 517, 591, 653, 690, 739, 775, 798, 892, 908, /* 190 */ 924, 930, 1015, 1063, 1069, 355, 784, 799, 981, 1101, /* 200 */ 926, 1151, 1161, 1162, 945, 1164, 1166, 1128, 1168, 1171, /* 210 */ 1172, 250, 1173, 1174, 1175, 1178, 1180, 1181, 1088, 1102, /* 220 */ 1119, 1124, 1126, 926, 1131, 1139, 1188, 1140, 1129, 1130, /* 230 */ 1103, 1144, 1107, 1179, 1156, 1167, 1182, 1134, 1122, 1183, /* 240 */ 1184, 1150, 1153, 1197, 1111, 1202, 1203, 1123, 1125, 1205, /* 250 */ 1147, 1185, 1169, 1186, 1190, 1191, 1192, 1213, 1217, 1193, /* 260 */ 1157, 1196, 1198, 1194, 1220, 1218, 1145, 1154, 1229, 1231, /* 270 */ 1233, 1216, 1237, 1240, 1241, 1244, 1222, 1227, 1230, 1232, /* 280 */ 1223, 1235, 1236, 1245, 1249, 1226, 1250, 1254, 1199, 1201, /* 290 */ 1204, 1207, 1209, 1211, 1214, 1212, 1255, 1208, 1259, 1215, /* 300 */ 1256, 1200, 1206, 1260, 1247, 1261, 1263, 1262, 1266, 1278, /* 310 */ 1282, 1292, 1294, 1297, 1298, 1299, 1300, 1221, 1224, 1228, /* 320 */ 1288, 1291, 1276, 1277, 1295, }; static const YYACTIONTYPE yy_default[] = { /* 0 */ 1281, 1271, 1271, 1271, 1203, 1203, 1203, 1203, 1271, 1096, /* 10 */ 1125, 1125, 1255, 1332, 1332, 1332, 1332, 1332, 1332, 1202, /* 20 */ 1332, 1332, 1332, 1332, 1271, 1100, 1131, 1332, 1332, 1332, /* 30 */ 1332, 1204, 1205, 1332, 1332, 1332, 1254, 1256, 1141, 1140, /* 40 */ 1139, 1138, 1237, 1112, 1136, 1129, 1133, 1204, 1198, 1199, /* 50 */ 1197, 1201, 1205, 1332, 1132, 1167, 1182, 1166, 1332, 1332, /* 60 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 70 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 80 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 90 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 100 */ 1332, 1332, 1332, 1332, 1176, 1181, 1188, 1180, 1177, 1169, /* 110 */ 1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172, /* 120 */ 1332, 1173, 1185, 1184, 1183, 1262, 1289, 1288, 1332, 1332, /* 130 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 140 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 150 */ 1332, 1332, 1332, 1332, 1332, 1281, 1271, 1025, 1025, 1332, /* 160 */ 1271, 1271, 1271, 1271, 1271, 1271, 1267, 1100, 1091, 1332, /* 170 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 180 */ 1259, 1257, 1332, 1218, 1332, 1332, 1332, 1332, 1332, 1332, /* 190 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 200 */ 1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332, /* 210 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1283, 1332, 1232, /* 220 */ 1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114, /* 230 */ 1321, 1135, 1321, 1042, 1303, 1039, 1125, 1114, 1200, 1125, /* 240 */ 1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105, /* 250 */ 1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135, /* 260 */ 1146, 1070, 1070, 1135, 1105, 1016, 1236, 1318, 1105, 1105, /* 270 */ 1016, 1211, 1105, 1016, 1105, 1016, 1211, 1068, 1068, 1068, /* 280 */ 1057, 1211, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113, /* 290 */ 1118, 1113, 1118, 1113, 1118, 1113, 1105, 1206, 1105, 1332, /* 300 */ 1211, 1215, 1215, 1211, 1130, 1119, 1128, 1126, 1135, 1022, /* 310 */ 1060, 1286, 1286, 1282, 1282, 1282, 1282, 1329, 1329, 1267, /* 320 */ 1298, 1298, 1044, 1044, 1298, 1332, 1332, 1332, 1332, 1332, /* 330 */ 1332, 1293, 1332, 1220, 1332, 1332, 1332, 1332, 1332, 1332, /* 340 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 350 */ 1332, 1332, 1152, 1332, 1000, 1264, 1332, 1332, 1263, 1332, /* 360 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 370 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320, /* 380 */ 1332, 1332, 1332, 1332, 1332, 1332, 1235, 1234, 1332, 1332, /* 390 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 400 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, /* 410 */ 1332, 1082, 1332, 1332, 1332, 1307, 1332, 1332, 1332, 1332, /* 420 */ 1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332, /* 430 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1273, /* 440 */ 1332, 1332, 1332, 1272, 1332, 1332, 1332, 1332, 1332, 1154, /* 450 */ 1332, 1153, 1157, 1332, 1010, 1332, }; /********** End of lemon-generated parsing tables *****************************/ /* The next table maps tokens (terminal symbols) into fallback tokens. ** If a construct like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammar, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. ** ** This feature can be used, for example, to cause some keywords in a language ** to revert to identifiers if they keyword does not apply in the context where ** it appears. */ #ifdef YYFALLBACK static const YYCODETYPE yyFallback[] = { 0, /* $ => nothing */ 0, /* SEMI => nothing */ 55, /* EXPLAIN => ID */ 55, /* QUERY => ID */ 55, /* PLAN => ID */ 55, /* BEGIN => ID */ 0, /* TRANSACTION => nothing */ 55, /* DEFERRED => ID */ 55, /* IMMEDIATE => ID */ 55, /* EXCLUSIVE => ID */ 0, /* COMMIT => nothing */ 55, /* END => ID */ 55, /* ROLLBACK => ID */ 55, /* SAVEPOINT => ID */ 55, /* RELEASE => ID */ 0, /* TO => nothing */ 0, /* TABLE => nothing */ 0, /* CREATE => nothing */ 55, /* IF => ID */ 0, /* NOT => nothing */ 0, /* EXISTS => nothing */ 55, /* TEMP => ID */ 0, /* LP => nothing */ 0, /* RP => nothing */ 0, /* AS => nothing */ 55, /* WITHOUT => ID */ 0, /* COMMA => nothing */ 0, /* OR => nothing */ 0, /* AND => nothing */ 0, /* IS => nothing */ 55, /* MATCH => ID */ 55, /* LIKE_KW => ID */ 0, /* BETWEEN => nothing */ 0, /* IN => nothing */ 0, /* ISNULL => nothing */ 0, /* NOTNULL => nothing */ 0, /* NE => nothing */ 0, /* EQ => nothing */ 0, /* GT => nothing */ 0, /* LE => nothing */ 0, /* LT => nothing */ 0, /* GE => nothing */ 0, /* ESCAPE => nothing */ 0, /* BITAND => nothing */ 0, /* BITOR => nothing */ 0, /* LSHIFT => nothing */ 0, /* RSHIFT => nothing */ 0, /* PLUS => nothing */ 0, /* MINUS => nothing */ 0, /* STAR => nothing */ 0, /* SLASH => nothing */ 0, /* REM => nothing */ 0, /* CONCAT => nothing */ 0, /* COLLATE => nothing */ 0, /* BITNOT => nothing */ 0, /* ID => nothing */ 0, /* INDEXED => nothing */ 55, /* ABORT => ID */ 55, /* ACTION => ID */ 55, /* AFTER => ID */ 55, /* ANALYZE => ID */ 55, /* ASC => ID */ 55, /* ATTACH => ID */ 55, /* BEFORE => ID */ 55, /* BY => ID */ 55, /* CASCADE => ID */ 55, /* CAST => ID */ 55, /* COLUMNKW => ID */ 55, /* CONFLICT => ID */ 55, /* DATABASE => ID */ 55, /* DESC => ID */ 55, /* DETACH => ID */ 55, /* EACH => ID */ 55, /* FAIL => ID */ 55, /* FOR => ID */ 55, /* IGNORE => ID */ 55, /* INITIALLY => ID */ 55, /* INSTEAD => ID */ 55, /* NO => ID */ 55, /* KEY => ID */ 55, /* OF => ID */ 55, /* OFFSET => ID */ 55, /* PRAGMA => ID */ 55, /* RAISE => ID */ 55, /* RECURSIVE => ID */ 55, /* REPLACE => ID */ 55, /* RESTRICT => ID */ 55, /* ROW => ID */ 55, /* TRIGGER => ID */ 55, /* VACUUM => ID */ 55, /* VIEW => ID */ 55, /* VIRTUAL => ID */ 55, /* WITH => ID */ 55, /* REINDEX => ID */ 55, /* RENAME => ID */ 55, /* CTIME_KW => ID */ }; #endif /* YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. ** ** After the "shift" half of a SHIFTREDUCE action, the stateno field ** actually contains the reduce action for the second half of the ** SHIFTREDUCE. */ struct yyStackEntry { YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */ YYCODETYPE major; /* The major token value. This is the code ** number for the token at this stack level */ YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct yyParser { yyStackEntry *yytos; /* Pointer to top element of the stack */ #ifdef YYTRACKMAXSTACKDEPTH int yyhwm; /* High-water mark of the stack */ #endif #ifndef YYNOERRORRECOVERY int yyerrcnt; /* Shifts left before out of the error */ #endif sqlite3ParserARG_SDECL /* A place to hold %extra_argument */ #if YYSTACKDEPTH<=0 int yystksz; /* Current side of the stack */ yyStackEntry *yystack; /* The parser's stack */ yyStackEntry yystk0; /* First stack entry */ #else yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ #endif }; typedef struct yyParser yyParser; #ifndef NDEBUG /* #include <stdio.h> */ static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: ** <ul> ** <li> A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. ** <li> A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. ** </ul> ** ** Outputs: ** None. */ SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; else if( yyTracePrompt==0 ) yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *const yyTokenName[] = { "$", "SEMI", "EXPLAIN", "QUERY", "PLAN", "BEGIN", "TRANSACTION", "DEFERRED", "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END", "ROLLBACK", "SAVEPOINT", "RELEASE", "TO", "TABLE", "CREATE", "IF", "NOT", "EXISTS", "TEMP", "LP", "RP", "AS", "WITHOUT", "COMMA", "OR", "AND", "IS", "MATCH", "LIKE_KW", "BETWEEN", "IN", "ISNULL", "NOTNULL", "NE", "EQ", "GT", "LE", "LT", "GE", "ESCAPE", "BITAND", "BITOR", "LSHIFT", "RSHIFT", "PLUS", "MINUS", "STAR", "SLASH", "REM", "CONCAT", "COLLATE", "BITNOT", "ID", "INDEXED", "ABORT", "ACTION", "AFTER", "ANALYZE", "ASC", "ATTACH", "BEFORE", "BY", "CASCADE", "CAST", "COLUMNKW", "CONFLICT", "DATABASE", "DESC", "DETACH", "EACH", "FAIL", "FOR", "IGNORE", "INITIALLY", "INSTEAD", "NO", "KEY", "OF", "OFFSET", "PRAGMA", "RAISE", "RECURSIVE", "REPLACE", "RESTRICT", "ROW", "TRIGGER", "VACUUM", "VIEW", "VIRTUAL", "WITH", "REINDEX", "RENAME", "CTIME_KW", "ANY", "STRING", "JOIN_KW", "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY", "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR", "ON", "INSERT", "DELETE", "UPDATE", "SET", "DEFERRABLE", "FOREIGN", "DROP", "UNION", "ALL", "EXCEPT", "INTERSECT", "SELECT", "VALUES", "DISTINCT", "DOT", "FROM", "JOIN", "USING", "ORDER", "GROUP", "HAVING", "LIMIT", "WHERE", "INTO", "FLOAT", "BLOB", "INTEGER", "VARIABLE", "CASE", "WHEN", "THEN", "ELSE", "INDEX", "ALTER", "ADD", "error", "input", "cmdlist", "ecmd", "explain", "cmdx", "cmd", "transtype", "trans_opt", "nm", "savepoint_opt", "create_table", "create_table_args", "createkw", "temp", "ifnotexists", "dbnm", "columnlist", "conslist_opt", "table_options", "select", "columnname", "carglist", "typetoken", "typename", "signed", "plus_num", "minus_num", "ccons", "term", "expr", "onconf", "sortorder", "autoinc", "eidlist_opt", "refargs", "defer_subclause", "refarg", "refact", "init_deferred_pred_opt", "conslist", "tconscomma", "tcons", "sortlist", "eidlist", "defer_subclause_opt", "orconf", "resolvetype", "raisetype", "ifexists", "fullname", "selectnowith", "oneselect", "with", "multiselect_op", "distinct", "selcollist", "from", "where_opt", "groupby_opt", "having_opt", "orderby_opt", "limit_opt", "values", "nexprlist", "exprlist", "sclp", "as", "seltablist", "stl_prefix", "joinop", "indexed_opt", "on_opt", "using_opt", "idlist", "setlist", "insert_cmd", "idlist_opt", "likeop", "between_op", "in_op", "paren_exprlist", "case_operand", "case_exprlist", "case_else", "uniqueflag", "collate", "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause", "when_clause", "trigger_cmd", "trnm", "tridxby", "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken", "lp", "anylist", "wqlist", }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *const yyRuleName[] = { /* 0 */ "explain ::= EXPLAIN", /* 1 */ "explain ::= EXPLAIN QUERY PLAN", /* 2 */ "cmdx ::= cmd", /* 3 */ "cmd ::= BEGIN transtype trans_opt", /* 4 */ "transtype ::=", /* 5 */ "transtype ::= DEFERRED", /* 6 */ "transtype ::= IMMEDIATE", /* 7 */ "transtype ::= EXCLUSIVE", /* 8 */ "cmd ::= COMMIT trans_opt", /* 9 */ "cmd ::= END trans_opt", /* 10 */ "cmd ::= ROLLBACK trans_opt", /* 11 */ "cmd ::= SAVEPOINT nm", /* 12 */ "cmd ::= RELEASE savepoint_opt nm", /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", /* 15 */ "createkw ::= CREATE", /* 16 */ "ifnotexists ::=", /* 17 */ "ifnotexists ::= IF NOT EXISTS", /* 18 */ "temp ::= TEMP", /* 19 */ "temp ::=", /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options", /* 21 */ "create_table_args ::= AS select", /* 22 */ "table_options ::=", /* 23 */ "table_options ::= WITHOUT nm", /* 24 */ "columnname ::= nm typetoken", /* 25 */ "typetoken ::=", /* 26 */ "typetoken ::= typename LP signed RP", /* 27 */ "typetoken ::= typename LP signed COMMA signed RP", /* 28 */ "typename ::= typename ID|STRING", /* 29 */ "ccons ::= CONSTRAINT nm", /* 30 */ "ccons ::= DEFAULT term", /* 31 */ "ccons ::= DEFAULT LP expr RP", /* 32 */ "ccons ::= DEFAULT PLUS term", /* 33 */ "ccons ::= DEFAULT MINUS term", /* 34 */ "ccons ::= DEFAULT ID|INDEXED", /* 35 */ "ccons ::= NOT NULL onconf", /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", /* 37 */ "ccons ::= UNIQUE onconf", /* 38 */ "ccons ::= CHECK LP expr RP", /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs", /* 40 */ "ccons ::= defer_subclause", /* 41 */ "ccons ::= COLLATE ID|STRING", /* 42 */ "autoinc ::=", /* 43 */ "autoinc ::= AUTOINCR", /* 44 */ "refargs ::=", /* 45 */ "refargs ::= refargs refarg", /* 46 */ "refarg ::= MATCH nm", /* 47 */ "refarg ::= ON INSERT refact", /* 48 */ "refarg ::= ON DELETE refact", /* 49 */ "refarg ::= ON UPDATE refact", /* 50 */ "refact ::= SET NULL", /* 51 */ "refact ::= SET DEFAULT", /* 52 */ "refact ::= CASCADE", /* 53 */ "refact ::= RESTRICT", /* 54 */ "refact ::= NO ACTION", /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", /* 57 */ "init_deferred_pred_opt ::=", /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", /* 60 */ "conslist_opt ::=", /* 61 */ "tconscomma ::= COMMA", /* 62 */ "tcons ::= CONSTRAINT nm", /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf", /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf", /* 65 */ "tcons ::= CHECK LP expr RP onconf", /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt", /* 67 */ "defer_subclause_opt ::=", /* 68 */ "onconf ::=", /* 69 */ "onconf ::= ON CONFLICT resolvetype", /* 70 */ "orconf ::=", /* 71 */ "orconf ::= OR resolvetype", /* 72 */ "resolvetype ::= IGNORE", /* 73 */ "resolvetype ::= REPLACE", /* 74 */ "cmd ::= DROP TABLE ifexists fullname", /* 75 */ "ifexists ::= IF EXISTS", /* 76 */ "ifexists ::=", /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select", /* 78 */ "cmd ::= DROP VIEW ifexists fullname", /* 79 */ "cmd ::= select", /* 80 */ "select ::= with selectnowith", /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect", /* 82 */ "multiselect_op ::= UNION", /* 83 */ "multiselect_op ::= UNION ALL", /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT", /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", /* 86 */ "values ::= VALUES LP nexprlist RP", /* 87 */ "values ::= values COMMA LP exprlist RP", /* 88 */ "distinct ::= DISTINCT", /* 89 */ "distinct ::= ALL", /* 90 */ "distinct ::=", /* 91 */ "sclp ::=", /* 92 */ "selcollist ::= sclp expr as", /* 93 */ "selcollist ::= sclp STAR", /* 94 */ "selcollist ::= sclp nm DOT STAR", /* 95 */ "as ::= AS nm", /* 96 */ "as ::=", /* 97 */ "from ::=", /* 98 */ "from ::= FROM seltablist", /* 99 */ "stl_prefix ::= seltablist joinop", /* 100 */ "stl_prefix ::=", /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt", /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", /* 105 */ "dbnm ::=", /* 106 */ "dbnm ::= DOT nm", /* 107 */ "fullname ::= nm dbnm", /* 108 */ "joinop ::= COMMA|JOIN", /* 109 */ "joinop ::= JOIN_KW JOIN", /* 110 */ "joinop ::= JOIN_KW nm JOIN", /* 111 */ "joinop ::= JOIN_KW nm nm JOIN", /* 112 */ "on_opt ::= ON expr", /* 113 */ "on_opt ::=", /* 114 */ "indexed_opt ::=", /* 115 */ "indexed_opt ::= INDEXED BY nm", /* 116 */ "indexed_opt ::= NOT INDEXED", /* 117 */ "using_opt ::= USING LP idlist RP", /* 118 */ "using_opt ::=", /* 119 */ "orderby_opt ::=", /* 120 */ "orderby_opt ::= ORDER BY sortlist", /* 121 */ "sortlist ::= sortlist COMMA expr sortorder", /* 122 */ "sortlist ::= expr sortorder", /* 123 */ "sortorder ::= ASC", /* 124 */ "sortorder ::= DESC", /* 125 */ "sortorder ::=", /* 126 */ "groupby_opt ::=", /* 127 */ "groupby_opt ::= GROUP BY nexprlist", /* 128 */ "having_opt ::=", /* 129 */ "having_opt ::= HAVING expr", /* 130 */ "limit_opt ::=", /* 131 */ "limit_opt ::= LIMIT expr", /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr", /* 133 */ "limit_opt ::= LIMIT expr COMMA expr", /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt", /* 135 */ "where_opt ::=", /* 136 */ "where_opt ::= WHERE expr", /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt", /* 138 */ "setlist ::= setlist COMMA nm EQ expr", /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr", /* 140 */ "setlist ::= nm EQ expr", /* 141 */ "setlist ::= LP idlist RP EQ expr", /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select", /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES", /* 144 */ "insert_cmd ::= INSERT orconf", /* 145 */ "insert_cmd ::= REPLACE", /* 146 */ "idlist_opt ::=", /* 147 */ "idlist_opt ::= LP idlist RP", /* 148 */ "idlist ::= idlist COMMA nm", /* 149 */ "idlist ::= nm", /* 150 */ "expr ::= LP expr RP", /* 151 */ "term ::= NULL", /* 152 */ "expr ::= ID|INDEXED", /* 153 */ "expr ::= JOIN_KW", /* 154 */ "expr ::= nm DOT nm", /* 155 */ "expr ::= nm DOT nm DOT nm", /* 156 */ "term ::= FLOAT|BLOB", /* 157 */ "term ::= STRING", /* 158 */ "term ::= INTEGER", /* 159 */ "expr ::= VARIABLE", /* 160 */ "expr ::= expr COLLATE ID|STRING", /* 161 */ "expr ::= CAST LP expr AS typetoken RP", /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP", /* 163 */ "expr ::= ID|INDEXED LP STAR RP", /* 164 */ "term ::= CTIME_KW", /* 165 */ "expr ::= LP nexprlist COMMA expr RP", /* 166 */ "expr ::= expr AND expr", /* 167 */ "expr ::= expr OR expr", /* 168 */ "expr ::= expr LT|GT|GE|LE expr", /* 169 */ "expr ::= expr EQ|NE expr", /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", /* 171 */ "expr ::= expr PLUS|MINUS expr", /* 172 */ "expr ::= expr STAR|SLASH|REM expr", /* 173 */ "expr ::= expr CONCAT expr", /* 174 */ "likeop ::= LIKE_KW|MATCH", /* 175 */ "likeop ::= NOT LIKE_KW|MATCH", /* 176 */ "expr ::= expr likeop expr", /* 177 */ "expr ::= expr likeop expr ESCAPE expr", /* 178 */ "expr ::= expr ISNULL|NOTNULL", /* 179 */ "expr ::= expr NOT NULL", /* 180 */ "expr ::= expr IS expr", /* 181 */ "expr ::= expr IS NOT expr", /* 182 */ "expr ::= NOT expr", /* 183 */ "expr ::= BITNOT expr", /* 184 */ "expr ::= MINUS expr", /* 185 */ "expr ::= PLUS expr", /* 186 */ "between_op ::= BETWEEN", /* 187 */ "between_op ::= NOT BETWEEN", /* 188 */ "expr ::= expr between_op expr AND expr", /* 189 */ "in_op ::= IN", /* 190 */ "in_op ::= NOT IN", /* 191 */ "expr ::= expr in_op LP exprlist RP", /* 192 */ "expr ::= LP select RP", /* 193 */ "expr ::= expr in_op LP select RP", /* 194 */ "expr ::= expr in_op nm dbnm paren_exprlist", /* 195 */ "expr ::= EXISTS LP select RP", /* 196 */ "expr ::= CASE case_operand case_exprlist case_else END", /* 197 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", /* 198 */ "case_exprlist ::= WHEN expr THEN expr", /* 199 */ "case_else ::= ELSE expr", /* 200 */ "case_else ::=", /* 201 */ "case_operand ::= expr", /* 202 */ "case_operand ::=", /* 203 */ "exprlist ::=", /* 204 */ "nexprlist ::= nexprlist COMMA expr", /* 205 */ "nexprlist ::= expr", /* 206 */ "paren_exprlist ::=", /* 207 */ "paren_exprlist ::= LP exprlist RP", /* 208 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt", /* 209 */ "uniqueflag ::= UNIQUE", /* 210 */ "uniqueflag ::=", /* 211 */ "eidlist_opt ::=", /* 212 */ "eidlist_opt ::= LP eidlist RP", /* 213 */ "eidlist ::= eidlist COMMA nm collate sortorder", /* 214 */ "eidlist ::= nm collate sortorder", /* 215 */ "collate ::=", /* 216 */ "collate ::= COLLATE ID|STRING", /* 217 */ "cmd ::= DROP INDEX ifexists fullname", /* 218 */ "cmd ::= VACUUM", /* 219 */ "cmd ::= VACUUM nm", /* 220 */ "cmd ::= PRAGMA nm dbnm", /* 221 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", /* 222 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", /* 223 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", /* 224 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", /* 225 */ "plus_num ::= PLUS INTEGER|FLOAT", /* 226 */ "minus_num ::= MINUS INTEGER|FLOAT", /* 227 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", /* 228 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", /* 229 */ "trigger_time ::= BEFORE", /* 230 */ "trigger_time ::= AFTER", /* 231 */ "trigger_time ::= INSTEAD OF", /* 232 */ "trigger_time ::=", /* 233 */ "trigger_event ::= DELETE|INSERT", /* 234 */ "trigger_event ::= UPDATE", /* 235 */ "trigger_event ::= UPDATE OF idlist", /* 236 */ "when_clause ::=", /* 237 */ "when_clause ::= WHEN expr", /* 238 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", /* 239 */ "trigger_cmd_list ::= trigger_cmd SEMI", /* 240 */ "trnm ::= nm DOT nm", /* 241 */ "tridxby ::= INDEXED BY nm", /* 242 */ "tridxby ::= NOT INDEXED", /* 243 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt", /* 244 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select", /* 245 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt", /* 246 */ "trigger_cmd ::= select", /* 247 */ "expr ::= RAISE LP IGNORE RP", /* 248 */ "expr ::= RAISE LP raisetype COMMA nm RP", /* 249 */ "raisetype ::= ROLLBACK", /* 250 */ "raisetype ::= ABORT", /* 251 */ "raisetype ::= FAIL", /* 252 */ "cmd ::= DROP TRIGGER ifexists fullname", /* 253 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", /* 254 */ "cmd ::= DETACH database_kw_opt expr", /* 255 */ "key_opt ::=", /* 256 */ "key_opt ::= KEY expr", /* 257 */ "cmd ::= REINDEX", /* 258 */ "cmd ::= REINDEX nm dbnm", /* 259 */ "cmd ::= ANALYZE", /* 260 */ "cmd ::= ANALYZE nm dbnm", /* 261 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", /* 262 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist", /* 263 */ "add_column_fullname ::= fullname", /* 264 */ "cmd ::= create_vtab", /* 265 */ "cmd ::= create_vtab LP vtabarglist RP", /* 266 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", /* 267 */ "vtabarg ::=", /* 268 */ "vtabargtoken ::= ANY", /* 269 */ "vtabargtoken ::= lp anylist RP", /* 270 */ "lp ::= LP", /* 271 */ "with ::=", /* 272 */ "with ::= WITH wqlist", /* 273 */ "with ::= WITH RECURSIVE wqlist", /* 274 */ "wqlist ::= nm eidlist_opt AS LP select RP", /* 275 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP", /* 276 */ "input ::= cmdlist", /* 277 */ "cmdlist ::= cmdlist ecmd", /* 278 */ "cmdlist ::= ecmd", /* 279 */ "ecmd ::= SEMI", /* 280 */ "ecmd ::= explain cmdx SEMI", /* 281 */ "explain ::=", /* 282 */ "trans_opt ::=", /* 283 */ "trans_opt ::= TRANSACTION", /* 284 */ "trans_opt ::= TRANSACTION nm", /* 285 */ "savepoint_opt ::= SAVEPOINT", /* 286 */ "savepoint_opt ::=", /* 287 */ "cmd ::= create_table create_table_args", /* 288 */ "columnlist ::= columnlist COMMA columnname carglist", /* 289 */ "columnlist ::= columnname carglist", /* 290 */ "nm ::= ID|INDEXED", /* 291 */ "nm ::= STRING", /* 292 */ "nm ::= JOIN_KW", /* 293 */ "typetoken ::= typename", /* 294 */ "typename ::= ID|STRING", /* 295 */ "signed ::= plus_num", /* 296 */ "signed ::= minus_num", /* 297 */ "carglist ::= carglist ccons", /* 298 */ "carglist ::=", /* 299 */ "ccons ::= NULL onconf", /* 300 */ "conslist_opt ::= COMMA conslist", /* 301 */ "conslist ::= conslist tconscomma tcons", /* 302 */ "conslist ::= tcons", /* 303 */ "tconscomma ::=", /* 304 */ "defer_subclause_opt ::= defer_subclause", /* 305 */ "resolvetype ::= raisetype", /* 306 */ "selectnowith ::= oneselect", /* 307 */ "oneselect ::= values", /* 308 */ "sclp ::= selcollist COMMA", /* 309 */ "as ::= ID|STRING", /* 310 */ "expr ::= term", /* 311 */ "exprlist ::= nexprlist", /* 312 */ "nmnum ::= plus_num", /* 313 */ "nmnum ::= nm", /* 314 */ "nmnum ::= ON", /* 315 */ "nmnum ::= DELETE", /* 316 */ "nmnum ::= DEFAULT", /* 317 */ "plus_num ::= INTEGER|FLOAT", /* 318 */ "foreach_clause ::=", /* 319 */ "foreach_clause ::= FOR EACH ROW", /* 320 */ "trnm ::= nm", /* 321 */ "tridxby ::=", /* 322 */ "database_kw_opt ::= DATABASE", /* 323 */ "database_kw_opt ::=", /* 324 */ "kwcolumn_opt ::=", /* 325 */ "kwcolumn_opt ::= COLUMNKW", /* 326 */ "vtabarglist ::= vtabarg", /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg", /* 328 */ "vtabarg ::= vtabarg vtabargtoken", /* 329 */ "anylist ::=", /* 330 */ "anylist ::= anylist LP anylist RP", /* 331 */ "anylist ::= anylist ANY", }; #endif /* NDEBUG */ #if YYSTACKDEPTH<=0 /* ** Try to increase the size of the parser stack. Return the number ** of errors. Return 0 on success. */ static int yyGrowStack(yyParser *p){ int newSize; int idx; yyStackEntry *pNew; newSize = p->yystksz*2 + 100; idx = p->yytos ? (int)(p->yytos - p->yystack) : 0; if( p->yystack==&p->yystk0 ){ pNew = malloc(newSize*sizeof(pNew[0])); if( pNew ) pNew[0] = p->yystk0; }else{ pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); } if( pNew ){ p->yystack = pNew; p->yytos = &p->yystack[idx]; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n", yyTracePrompt, p->yystksz, newSize); } #endif p->yystksz = newSize; } return pNew==0; } #endif /* Datatype of the argument to the memory allocated passed as the ** second argument to sqlite3ParserAlloc() below. This can be changed by ** putting an appropriate #define in the %include section of the input ** grammar. */ #ifndef YYMALLOCARGTYPE # define YYMALLOCARGTYPE size_t #endif /* Initialize a new parser that has already been allocated. */ SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){ yyParser *pParser = (yyParser*)yypParser; #ifdef YYTRACKMAXSTACKDEPTH pParser->yyhwm = 0; #endif #if YYSTACKDEPTH<=0 pParser->yytos = NULL; pParser->yystack = NULL; pParser->yystksz = 0; if( yyGrowStack(pParser) ){ pParser->yystack = &pParser->yystk0; pParser->yystksz = 1; } #endif #ifndef YYNOERRORRECOVERY pParser->yyerrcnt = -1; #endif pParser->yytos = pParser->yystack; pParser->yystack[0].stateno = 0; pParser->yystack[0].major = 0; } #ifndef sqlite3Parser_ENGINEALWAYSONSTACK /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to sqlite3Parser and sqlite3ParserFree. */ SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) ); if( pParser ) sqlite3ParserInit(pParser); return pParser; } #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */ /* The following function deletes the "minor type" or semantic value ** associated with a symbol. The symbol can be either a terminal ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is ** a pointer to the value to be deleted. The code used to do the ** deletions is derived from the %destructor and/or %token_destructor ** directives of the input grammar. */ static void yy_destructor( yyParser *yypParser, /* The parser */ YYCODETYPE yymajor, /* Type code for object to destroy */ YYMINORTYPE *yypminor /* The object to be destroyed */ ){ sqlite3ParserARG_FETCH; switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are *not* used ** inside the C code. */ /********* Begin destructor definitions ***************************************/ case 163: /* select */ case 194: /* selectnowith */ case 195: /* oneselect */ case 206: /* values */ { sqlite3SelectDelete(pParse->db, (yypminor->yy243)); } break; case 172: /* term */ case 173: /* expr */ { sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr); } break; case 177: /* eidlist_opt */ case 186: /* sortlist */ case 187: /* eidlist */ case 199: /* selcollist */ case 202: /* groupby_opt */ case 204: /* orderby_opt */ case 207: /* nexprlist */ case 208: /* exprlist */ case 209: /* sclp */ case 218: /* setlist */ case 224: /* paren_exprlist */ case 226: /* case_exprlist */ { sqlite3ExprListDelete(pParse->db, (yypminor->yy148)); } break; case 193: /* fullname */ case 200: /* from */ case 211: /* seltablist */ case 212: /* stl_prefix */ { sqlite3SrcListDelete(pParse->db, (yypminor->yy185)); } break; case 196: /* with */ case 250: /* wqlist */ { sqlite3WithDelete(pParse->db, (yypminor->yy285)); } break; case 201: /* where_opt */ case 203: /* having_opt */ case 215: /* on_opt */ case 225: /* case_operand */ case 227: /* case_else */ case 236: /* when_clause */ case 241: /* key_opt */ { sqlite3ExprDelete(pParse->db, (yypminor->yy72)); } break; case 216: /* using_opt */ case 217: /* idlist */ case 220: /* idlist_opt */ { sqlite3IdListDelete(pParse->db, (yypminor->yy254)); } break; case 232: /* trigger_cmd_list */ case 237: /* trigger_cmd */ { sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145)); } break; case 234: /* trigger_event */ { sqlite3IdListDelete(pParse->db, (yypminor->yy332).b); } break; /********* End destructor definitions *****************************************/ default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. */ static void yy_pop_parser_stack(yyParser *pParser){ yyStackEntry *yytos; assert( pParser->yytos!=0 ); assert( pParser->yytos > pParser->yystack ); yytos = pParser->yytos--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sPopping %s\n", yyTracePrompt, yyTokenName[yytos->major]); } #endif yy_destructor(pParser, yytos->major, &yytos->minor); } /* ** Clear all secondary memory allocations from the parser */ SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){ yyParser *pParser = (yyParser*)p; while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser); #if YYSTACKDEPTH<=0 if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack); #endif } #ifndef sqlite3Parser_ENGINEALWAYSONSTACK /* ** Deallocate and destroy a parser. Destructors are called for ** all stack elements before shutting the parser down. ** ** If the YYPARSEFREENEVERNULL macro exists (for example because it ** is defined in a %include section of the input grammar) then it is ** assumed that the input pointer is never NULL. */ SQLITE_PRIVATE void sqlite3ParserFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ #ifndef YYPARSEFREENEVERNULL if( p==0 ) return; #endif sqlite3ParserFinalize(p); (*freeProc)(p); } #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */ /* ** Return the peak depth of the stack for a parser. */ #ifdef YYTRACKMAXSTACKDEPTH SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){ yyParser *pParser = (yyParser*)p; return pParser->yyhwm; } #endif /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. */ static unsigned int yy_find_shift_action( yyParser *pParser, /* The parser */ YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yytos->stateno; if( stateno>=YY_MIN_REDUCE ) return stateno; assert( stateno <= YY_SHIFT_COUNT ); do{ i = yy_shift_ofst[stateno]; assert( iLookAhead!=YYNOCODE ); i += iLookAhead; if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ #ifdef YYFALLBACK YYCODETYPE iFallback; /* Fallback token */ if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) && (iFallback = yyFallback[iLookAhead])!=0 ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */ iLookAhead = iFallback; continue; } #endif #ifdef YYWILDCARD { int j = i - iLookAhead + YYWILDCARD; if( #if YY_SHIFT_MIN+YYWILDCARD<0 j>=0 && #endif #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT j<YY_ACTTAB_COUNT && #endif yy_lookahead[j]==YYWILDCARD && iLookAhead>0 ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); } #endif /* NDEBUG */ return yy_action[j]; } } #endif /* YYWILDCARD */ return yy_default[stateno]; }else{ return yy_action[i]; } }while(1); } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. */ static int yy_find_reduce_action( int stateno, /* Current state number */ YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; #ifdef YYERRORSYMBOL if( stateno>YY_REDUCE_COUNT ){ return yy_default[stateno]; } #else assert( stateno<=YY_REDUCE_COUNT ); #endif i = yy_reduce_ofst[stateno]; assert( i!=YY_REDUCE_USE_DFLT ); assert( iLookAhead!=YYNOCODE ); i += iLookAhead; #ifdef YYERRORSYMBOL if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; } #else assert( i>=0 && i<YY_ACTTAB_COUNT ); assert( yy_lookahead[i]==iLookAhead ); #endif return yy_action[i]; } /* ** The following routine is called if the stack overflows. */ static void yyStackOverflow(yyParser *yypParser){ sqlite3ParserARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); } #endif while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ /******** Begin %stack_overflow code ******************************************/ sqlite3ErrorMsg(pParse, "parser stack overflow"); /******** End %stack_overflow code ********************************************/ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ } /* ** Print tracing information for a SHIFT action */ #ifndef NDEBUG static void yyTraceShift(yyParser *yypParser, int yyNewState){ if( yyTraceFILE ){ if( yyNewState<YYNSTATE ){ fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n", yyTracePrompt,yyTokenName[yypParser->yytos->major], yyNewState); }else{ fprintf(yyTraceFILE,"%sShift '%s'\n", yyTracePrompt,yyTokenName[yypParser->yytos->major]); } } } #else # define yyTraceShift(X,Y) #endif /* ** Perform a shift action. */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yytos++; #ifdef YYTRACKMAXSTACKDEPTH if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){ yypParser->yyhwm++; assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) ); } #endif #if YYSTACKDEPTH>0 if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){ yypParser->yytos--; yyStackOverflow(yypParser); return; } #else if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){ if( yyGrowStack(yypParser) ){ yypParser->yytos--; yyStackOverflow(yypParser); return; } } #endif if( yyNewState > YY_MAX_SHIFT ){ yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; } yytos = yypParser->yytos; yytos->stateno = (YYACTIONTYPE)yyNewState; yytos->major = (YYCODETYPE)yyMajor; yytos->minor.yy0 = yyMinor; yyTraceShift(yypParser, yyNewState); } /* The following table contains information about every rule that ** is used during the reduce. */ static const struct { YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } yyRuleInfo[] = { { 147, 1 }, { 147, 3 }, { 148, 1 }, { 149, 3 }, { 150, 0 }, { 150, 1 }, { 150, 1 }, { 150, 1 }, { 149, 2 }, { 149, 2 }, { 149, 2 }, { 149, 2 }, { 149, 3 }, { 149, 5 }, { 154, 6 }, { 156, 1 }, { 158, 0 }, { 158, 3 }, { 157, 1 }, { 157, 0 }, { 155, 5 }, { 155, 2 }, { 162, 0 }, { 162, 2 }, { 164, 2 }, { 166, 0 }, { 166, 4 }, { 166, 6 }, { 167, 2 }, { 171, 2 }, { 171, 2 }, { 171, 4 }, { 171, 3 }, { 171, 3 }, { 171, 2 }, { 171, 3 }, { 171, 5 }, { 171, 2 }, { 171, 4 }, { 171, 4 }, { 171, 1 }, { 171, 2 }, { 176, 0 }, { 176, 1 }, { 178, 0 }, { 178, 2 }, { 180, 2 }, { 180, 3 }, { 180, 3 }, { 180, 3 }, { 181, 2 }, { 181, 2 }, { 181, 1 }, { 181, 1 }, { 181, 2 }, { 179, 3 }, { 179, 2 }, { 182, 0 }, { 182, 2 }, { 182, 2 }, { 161, 0 }, { 184, 1 }, { 185, 2 }, { 185, 7 }, { 185, 5 }, { 185, 5 }, { 185, 10 }, { 188, 0 }, { 174, 0 }, { 174, 3 }, { 189, 0 }, { 189, 2 }, { 190, 1 }, { 190, 1 }, { 149, 4 }, { 192, 2 }, { 192, 0 }, { 149, 9 }, { 149, 4 }, { 149, 1 }, { 163, 2 }, { 194, 3 }, { 197, 1 }, { 197, 2 }, { 197, 1 }, { 195, 9 }, { 206, 4 }, { 206, 5 }, { 198, 1 }, { 198, 1 }, { 198, 0 }, { 209, 0 }, { 199, 3 }, { 199, 2 }, { 199, 4 }, { 210, 2 }, { 210, 0 }, { 200, 0 }, { 200, 2 }, { 212, 2 }, { 212, 0 }, { 211, 7 }, { 211, 9 }, { 211, 7 }, { 211, 7 }, { 159, 0 }, { 159, 2 }, { 193, 2 }, { 213, 1 }, { 213, 2 }, { 213, 3 }, { 213, 4 }, { 215, 2 }, { 215, 0 }, { 214, 0 }, { 214, 3 }, { 214, 2 }, { 216, 4 }, { 216, 0 }, { 204, 0 }, { 204, 3 }, { 186, 4 }, { 186, 2 }, { 175, 1 }, { 175, 1 }, { 175, 0 }, { 202, 0 }, { 202, 3 }, { 203, 0 }, { 203, 2 }, { 205, 0 }, { 205, 2 }, { 205, 4 }, { 205, 4 }, { 149, 6 }, { 201, 0 }, { 201, 2 }, { 149, 8 }, { 218, 5 }, { 218, 7 }, { 218, 3 }, { 218, 5 }, { 149, 6 }, { 149, 7 }, { 219, 2 }, { 219, 1 }, { 220, 0 }, { 220, 3 }, { 217, 3 }, { 217, 1 }, { 173, 3 }, { 172, 1 }, { 173, 1 }, { 173, 1 }, { 173, 3 }, { 173, 5 }, { 172, 1 }, { 172, 1 }, { 172, 1 }, { 173, 1 }, { 173, 3 }, { 173, 6 }, { 173, 5 }, { 173, 4 }, { 172, 1 }, { 173, 5 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 173, 3 }, { 221, 1 }, { 221, 2 }, { 173, 3 }, { 173, 5 }, { 173, 2 }, { 173, 3 }, { 173, 3 }, { 173, 4 }, { 173, 2 }, { 173, 2 }, { 173, 2 }, { 173, 2 }, { 222, 1 }, { 222, 2 }, { 173, 5 }, { 223, 1 }, { 223, 2 }, { 173, 5 }, { 173, 3 }, { 173, 5 }, { 173, 5 }, { 173, 4 }, { 173, 5 }, { 226, 5 }, { 226, 4 }, { 227, 2 }, { 227, 0 }, { 225, 1 }, { 225, 0 }, { 208, 0 }, { 207, 3 }, { 207, 1 }, { 224, 0 }, { 224, 3 }, { 149, 12 }, { 228, 1 }, { 228, 0 }, { 177, 0 }, { 177, 3 }, { 187, 5 }, { 187, 3 }, { 229, 0 }, { 229, 2 }, { 149, 4 }, { 149, 1 }, { 149, 2 }, { 149, 3 }, { 149, 5 }, { 149, 6 }, { 149, 5 }, { 149, 6 }, { 169, 2 }, { 170, 2 }, { 149, 5 }, { 231, 11 }, { 233, 1 }, { 233, 1 }, { 233, 2 }, { 233, 0 }, { 234, 1 }, { 234, 1 }, { 234, 3 }, { 236, 0 }, { 236, 2 }, { 232, 3 }, { 232, 2 }, { 238, 3 }, { 239, 3 }, { 239, 2 }, { 237, 7 }, { 237, 5 }, { 237, 5 }, { 237, 1 }, { 173, 4 }, { 173, 6 }, { 191, 1 }, { 191, 1 }, { 191, 1 }, { 149, 4 }, { 149, 6 }, { 149, 3 }, { 241, 0 }, { 241, 2 }, { 149, 1 }, { 149, 3 }, { 149, 1 }, { 149, 3 }, { 149, 6 }, { 149, 7 }, { 242, 1 }, { 149, 1 }, { 149, 4 }, { 244, 8 }, { 246, 0 }, { 247, 1 }, { 247, 3 }, { 248, 1 }, { 196, 0 }, { 196, 2 }, { 196, 3 }, { 250, 6 }, { 250, 8 }, { 144, 1 }, { 145, 2 }, { 145, 1 }, { 146, 1 }, { 146, 3 }, { 147, 0 }, { 151, 0 }, { 151, 1 }, { 151, 2 }, { 153, 1 }, { 153, 0 }, { 149, 2 }, { 160, 4 }, { 160, 2 }, { 152, 1 }, { 152, 1 }, { 152, 1 }, { 166, 1 }, { 167, 1 }, { 168, 1 }, { 168, 1 }, { 165, 2 }, { 165, 0 }, { 171, 2 }, { 161, 2 }, { 183, 3 }, { 183, 1 }, { 184, 0 }, { 188, 1 }, { 190, 1 }, { 194, 1 }, { 195, 1 }, { 209, 2 }, { 210, 1 }, { 173, 1 }, { 208, 1 }, { 230, 1 }, { 230, 1 }, { 230, 1 }, { 230, 1 }, { 230, 1 }, { 169, 1 }, { 235, 0 }, { 235, 3 }, { 238, 1 }, { 239, 0 }, { 240, 1 }, { 240, 0 }, { 243, 0 }, { 243, 1 }, { 245, 1 }, { 245, 3 }, { 246, 2 }, { 249, 0 }, { 249, 4 }, { 249, 2 }, }; static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser *yypParser, /* The parser */ unsigned int yyruleno /* Number of the rule by which to reduce */ ){ int yygoto; /* The next state */ int yyact; /* The next action */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ sqlite3ParserARG_FETCH; yymsp = yypParser->yytos; #ifndef NDEBUG if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ yysize = yyRuleInfo[yyruleno].nrhs; fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt, yyRuleName[yyruleno], yymsp[-yysize].stateno); } #endif /* NDEBUG */ /* Check that the stack is large enough to grow by a single entry ** if the RHS of the rule is empty. This ensures that there is room ** enough on the stack to push the LHS value */ if( yyRuleInfo[yyruleno].nrhs==0 ){ #ifdef YYTRACKMAXSTACKDEPTH if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){ yypParser->yyhwm++; assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack)); } #endif #if YYSTACKDEPTH>0 if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){ yyStackOverflow(yypParser); return; } #else if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){ if( yyGrowStack(yypParser) ){ yyStackOverflow(yypParser); return; } yymsp = yypParser->yytos; } #endif } switch( yyruleno ){ /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** #line <lineno> <grammarfile> ** { ... } // User supplied code ** #line <lineno> <thisfile> ** break; */ /********** Begin reduce actions **********************************************/ YYMINORTYPE yylhsminor; case 0: /* explain ::= EXPLAIN */ { pParse->explain = 1; } break; case 1: /* explain ::= EXPLAIN QUERY PLAN */ { pParse->explain = 2; } break; case 2: /* cmdx ::= cmd */ { sqlite3FinishCoding(pParse); } break; case 3: /* cmd ::= BEGIN transtype trans_opt */ {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);} break; case 4: /* transtype ::= */ {yymsp[1].minor.yy194 = TK_DEFERRED;} break; case 5: /* transtype ::= DEFERRED */ case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6); case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7); {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/} break; case 8: /* cmd ::= COMMIT trans_opt */ case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9); {sqlite3CommitTransaction(pParse);} break; case 10: /* cmd ::= ROLLBACK trans_opt */ {sqlite3RollbackTransaction(pParse);} break; case 11: /* cmd ::= SAVEPOINT nm */ { sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0); } break; case 12: /* cmd ::= RELEASE savepoint_opt nm */ { sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0); } break; case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ { sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0); } break; case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ { sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194); } break; case 15: /* createkw ::= CREATE */ {disableLookaside(pParse);} break; case 16: /* ifnotexists ::= */ case 19: /* temp ::= */ yytestcase(yyruleno==19); case 22: /* table_options ::= */ yytestcase(yyruleno==22); case 42: /* autoinc ::= */ yytestcase(yyruleno==42); case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57); case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67); case 76: /* ifexists ::= */ yytestcase(yyruleno==76); case 90: /* distinct ::= */ yytestcase(yyruleno==90); case 215: /* collate ::= */ yytestcase(yyruleno==215); {yymsp[1].minor.yy194 = 0;} break; case 17: /* ifnotexists ::= IF NOT EXISTS */ {yymsp[-2].minor.yy194 = 1;} break; case 18: /* temp ::= TEMP */ case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43); {yymsp[0].minor.yy194 = 1;} break; case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */ { sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0); } break; case 21: /* create_table_args ::= AS select */ { sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243); sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); } break; case 23: /* table_options ::= WITHOUT nm */ { if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){ yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid; }else{ yymsp[-1].minor.yy194 = 0; sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z); } } break; case 24: /* columnname ::= nm typetoken */ {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);} break; case 25: /* typetoken ::= */ case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60); case 96: /* as ::= */ yytestcase(yyruleno==96); {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;} break; case 26: /* typetoken ::= typename LP signed RP */ { yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z); } break; case 27: /* typetoken ::= typename LP signed COMMA signed RP */ { yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z); } break; case 28: /* typename ::= typename ID|STRING */ {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);} break; case 29: /* ccons ::= CONSTRAINT nm */ case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62); {pParse->constraintName = yymsp[0].minor.yy0;} break; case 30: /* ccons ::= DEFAULT term */ case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32); {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);} break; case 31: /* ccons ::= DEFAULT LP expr RP */ {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);} break; case 33: /* ccons ::= DEFAULT MINUS term */ { ExprSpan v; v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0); v.zStart = yymsp[-1].minor.yy0.z; v.zEnd = yymsp[0].minor.yy190.zEnd; sqlite3AddDefaultValue(pParse,&v); } break; case 34: /* ccons ::= DEFAULT ID|INDEXED */ { ExprSpan v; spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0); sqlite3AddDefaultValue(pParse,&v); } break; case 35: /* ccons ::= NOT NULL onconf */ {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);} break; case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);} break; case 37: /* ccons ::= UNIQUE onconf */ {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0, SQLITE_IDXTYPE_UNIQUE);} break; case 38: /* ccons ::= CHECK LP expr RP */ {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);} break; case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */ {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);} break; case 40: /* ccons ::= defer_subclause */ {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);} break; case 41: /* ccons ::= COLLATE ID|STRING */ {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} break; case 44: /* refargs ::= */ { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */} break; case 45: /* refargs ::= refargs refarg */ { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; } break; case 46: /* refarg ::= MATCH nm */ { yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; } break; case 47: /* refarg ::= ON INSERT refact */ { yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; } break; case 48: /* refarg ::= ON DELETE refact */ { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; } break; case 49: /* refarg ::= ON UPDATE refact */ { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; } break; case 50: /* refact ::= SET NULL */ { yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */} break; case 51: /* refact ::= SET DEFAULT */ { yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */} break; case 52: /* refact ::= CASCADE */ { yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */} break; case 53: /* refact ::= RESTRICT */ { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */} break; case 54: /* refact ::= NO ACTION */ { yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */} break; case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ {yymsp[-2].minor.yy194 = 0;} break; case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71); case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144); {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;} break; case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75); case 187: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==187); case 190: /* in_op ::= NOT IN */ yytestcase(yyruleno==190); case 216: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==216); {yymsp[-1].minor.yy194 = 1;} break; case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ {yymsp[-1].minor.yy194 = 0;} break; case 61: /* tconscomma ::= COMMA */ {pParse->constraintName.n = 0;} break; case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);} break; case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */ {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0, SQLITE_IDXTYPE_UNIQUE);} break; case 65: /* tcons ::= CHECK LP expr RP onconf */ {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);} break; case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ { sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194); sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194); } break; case 68: /* onconf ::= */ case 70: /* orconf ::= */ yytestcase(yyruleno==70); {yymsp[1].minor.yy194 = OE_Default;} break; case 69: /* onconf ::= ON CONFLICT resolvetype */ {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;} break; case 72: /* resolvetype ::= IGNORE */ {yymsp[0].minor.yy194 = OE_Ignore;} break; case 73: /* resolvetype ::= REPLACE */ case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145); {yymsp[0].minor.yy194 = OE_Replace;} break; case 74: /* cmd ::= DROP TABLE ifexists fullname */ { sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194); } break; case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ { sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194); } break; case 78: /* cmd ::= DROP VIEW ifexists fullname */ { sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194); } break; case 79: /* cmd ::= select */ { SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0}; sqlite3Select(pParse, yymsp[0].minor.yy243, &dest); sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); } break; case 80: /* select ::= with selectnowith */ { Select *p = yymsp[0].minor.yy243; if( p ){ p->pWith = yymsp[-1].minor.yy285; parserDoubleLinkSelect(pParse, p); }else{ sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285); } yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/ } break; case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */ { Select *pRhs = yymsp[0].minor.yy243; Select *pLhs = yymsp[-2].minor.yy243; if( pRhs && pRhs->pPrior ){ SrcList *pFrom; Token x; x.n = 0; parserDoubleLinkSelect(pParse, pRhs); pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0); pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0); } if( pRhs ){ pRhs->op = (u8)yymsp[-1].minor.yy194; pRhs->pPrior = pLhs; if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue; pRhs->selFlags &= ~SF_MultiValue; if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1; }else{ sqlite3SelectDelete(pParse->db, pLhs); } yymsp[-2].minor.yy243 = pRhs; } break; case 82: /* multiselect_op ::= UNION */ case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84); {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/} break; case 83: /* multiselect_op ::= UNION ALL */ {yymsp[-1].minor.yy194 = TK_ALL;} break; case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ { #if SELECTTRACE_ENABLED Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/ #endif yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset); #if SELECTTRACE_ENABLED /* Populate the Select.zSelName[] string that is used to help with ** query planner debugging, to differentiate between multiple Select ** objects in a complex query. ** ** If the SELECT keyword is immediately followed by a C-style comment ** then extract the first few alphanumeric characters from within that ** comment to be the zSelName value. Otherwise, the label is #N where ** is an integer that is incremented with each SELECT statement seen. */ if( yymsp[-8].minor.yy243!=0 ){ const char *z = s.z+6; int i; sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d", ++pParse->nSelect); while( z[0]==' ' ) z++; if( z[0]=='/' && z[1]=='*' ){ z += 2; while( z[0]==' ' ) z++; for(i=0; sqlite3Isalnum(z[i]); i++){} sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z); } } #endif /* SELECTRACE_ENABLED */ } break; case 86: /* values ::= VALUES LP nexprlist RP */ { yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0); } break; case 87: /* values ::= values COMMA LP exprlist RP */ { Select *pRight, *pLeft = yymsp[-4].minor.yy243; pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0); if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue; if( pRight ){ pRight->op = TK_ALL; pRight->pPrior = pLeft; yymsp[-4].minor.yy243 = pRight; }else{ yymsp[-4].minor.yy243 = pLeft; } } break; case 88: /* distinct ::= DISTINCT */ {yymsp[0].minor.yy194 = SF_Distinct;} break; case 89: /* distinct ::= ALL */ {yymsp[0].minor.yy194 = SF_All;} break; case 91: /* sclp ::= */ case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119); case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126); case 203: /* exprlist ::= */ yytestcase(yyruleno==203); case 206: /* paren_exprlist ::= */ yytestcase(yyruleno==206); case 211: /* eidlist_opt ::= */ yytestcase(yyruleno==211); {yymsp[1].minor.yy148 = 0;} break; case 92: /* selcollist ::= sclp expr as */ { yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr); if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1); sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190); } break; case 93: /* selcollist ::= sclp STAR */ { Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0); yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p); } break; case 94: /* selcollist ::= sclp nm DOT STAR */ { Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0); Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot); } break; case 95: /* as ::= AS nm */ case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106); case 225: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==225); case 226: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==226); {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;} break; case 97: /* from ::= */ {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));} break; case 98: /* from ::= FROM seltablist */ { yymsp[-1].minor.yy185 = yymsp[0].minor.yy185; sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185); } break; case 99: /* stl_prefix ::= seltablist joinop */ { if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194; } break; case 100: /* stl_prefix ::= */ {yymsp[1].minor.yy185 = 0;} break; case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ { yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0); } break; case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ { yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148); } break; case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ { yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); } break; case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ { if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){ yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185; }else if( yymsp[-4].minor.yy185->nSrc==1 ){ yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); if( yymsp[-6].minor.yy185 ){ struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1]; struct SrcList_item *pOld = yymsp[-4].minor.yy185->a; pNew->zName = pOld->zName; pNew->zDatabase = pOld->zDatabase; pNew->pSelect = pOld->pSelect; pOld->zName = pOld->zDatabase = 0; pOld->pSelect = 0; } sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185); }else{ Select *pSubquery; sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185); pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0); yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); } } break; case 105: /* dbnm ::= */ case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114); {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;} break; case 107: /* fullname ::= nm dbnm */ {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/} break; case 108: /* joinop ::= COMMA|JOIN */ { yymsp[0].minor.yy194 = JT_INNER; } break; case 109: /* joinop ::= JOIN_KW JOIN */ {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/} break; case 110: /* joinop ::= JOIN_KW nm JOIN */ {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/} break; case 111: /* joinop ::= JOIN_KW nm nm JOIN */ {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/} break; case 112: /* on_opt ::= ON expr */ case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129); case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136); case 199: /* case_else ::= ELSE expr */ yytestcase(yyruleno==199); {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;} break; case 113: /* on_opt ::= */ case 128: /* having_opt ::= */ yytestcase(yyruleno==128); case 135: /* where_opt ::= */ yytestcase(yyruleno==135); case 200: /* case_else ::= */ yytestcase(yyruleno==200); case 202: /* case_operand ::= */ yytestcase(yyruleno==202); {yymsp[1].minor.yy72 = 0;} break; case 115: /* indexed_opt ::= INDEXED BY nm */ {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;} break; case 116: /* indexed_opt ::= NOT INDEXED */ {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;} break; case 117: /* using_opt ::= USING LP idlist RP */ {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;} break; case 118: /* using_opt ::= */ case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146); {yymsp[1].minor.yy254 = 0;} break; case 120: /* orderby_opt ::= ORDER BY sortlist */ case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127); {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;} break; case 121: /* sortlist ::= sortlist COMMA expr sortorder */ { yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr); sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194); } break; case 122: /* sortlist ::= expr sortorder */ { yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/ sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194); } break; case 123: /* sortorder ::= ASC */ {yymsp[0].minor.yy194 = SQLITE_SO_ASC;} break; case 124: /* sortorder ::= DESC */ {yymsp[0].minor.yy194 = SQLITE_SO_DESC;} break; case 125: /* sortorder ::= */ {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;} break; case 130: /* limit_opt ::= */ {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;} break; case 131: /* limit_opt ::= LIMIT expr */ {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;} break; case 132: /* limit_opt ::= LIMIT expr OFFSET expr */ {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;} break; case 133: /* limit_opt ::= LIMIT expr COMMA expr */ {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;} break; case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */ { sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0); sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72); } break; case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */ { sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1); sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0); sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list"); sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194); } break; case 138: /* setlist ::= setlist COMMA nm EQ expr */ { yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1); } break; case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */ { yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); } break; case 140: /* setlist ::= nm EQ expr */ { yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr); sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1); } yymsp[-2].minor.yy148 = yylhsminor.yy148; break; case 141: /* setlist ::= LP idlist RP EQ expr */ { yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); } break; case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */ { sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194); } break; case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */ { sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1); sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194); } break; case 147: /* idlist_opt ::= LP idlist RP */ {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;} break; case 148: /* idlist ::= idlist COMMA nm */ {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);} break; case 149: /* idlist ::= nm */ {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/} break; case 150: /* expr ::= LP expr RP */ {spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;} break; case 151: /* term ::= NULL */ case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156); case 157: /* term ::= STRING */ yytestcase(yyruleno==157); {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/} break; case 152: /* expr ::= ID|INDEXED */ case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153); {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/} break; case 154: /* expr ::= nm DOT nm */ { Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2); } break; case 155: /* expr ::= nm DOT nm DOT nm */ { Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1); Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3); spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4); } break; case 158: /* term ::= INTEGER */ { yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1); yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z; yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n; if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf; } yymsp[0].minor.yy190 = yylhsminor.yy190; break; case 159: /* expr ::= VARIABLE */ { if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){ u32 n = yymsp[0].minor.yy0.n; spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0); sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n); }else{ /* When doing a nested parse, one can include terms in an expression ** that look like this: #1 #2 ... These terms refer to registers ** in the virtual machine. #N is the N-th register. */ Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/ assert( t.n>=2 ); spanSet(&yymsp[0].minor.yy190, &t, &t); if( pParse->nested==0 ){ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t); yymsp[0].minor.yy190.pExpr = 0; }else{ yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0); if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable); } } } break; case 160: /* expr ::= expr COLLATE ID|STRING */ { yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1); yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; } break; case 161: /* expr ::= CAST LP expr AS typetoken RP */ { spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1); sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0); } break; case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */ { if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0); } yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0); spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){ yylhsminor.yy190.pExpr->flags |= EP_Distinct; } } yymsp[-4].minor.yy190 = yylhsminor.yy190; break; case 163: /* expr ::= ID|INDEXED LP STAR RP */ { yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0); spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); } yymsp[-3].minor.yy190 = yylhsminor.yy190; break; case 164: /* term ::= CTIME_KW */ { yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0); spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0); } yymsp[0].minor.yy190 = yylhsminor.yy190; break; case 165: /* expr ::= LP nexprlist COMMA expr RP */ { ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr); yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0); if( yylhsminor.yy190.pExpr ){ yylhsminor.yy190.pExpr->x.pList = pList; spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0); }else{ sqlite3ExprListDelete(pParse->db, pList); } } yymsp[-4].minor.yy190 = yylhsminor.yy190; break; case 166: /* expr ::= expr AND expr */ case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167); case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168); case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169); case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170); case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171); case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172); case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173); {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);} break; case 174: /* likeop ::= LIKE_KW|MATCH */ {yymsp[0].minor.yy0=yymsp[0].minor.yy0;/*A-overwrites-X*/} break; case 175: /* likeop ::= NOT LIKE_KW|MATCH */ {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/} break; case 176: /* expr ::= expr likeop expr */ { ExprList *pList; int bNot = yymsp[-1].minor.yy0.n & 0x80000000; yymsp[-1].minor.yy0.n &= 0x7fffffff; pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr); pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr); yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0); exprNot(pParse, bNot, &yymsp[-2].minor.yy190); yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc; } break; case 177: /* expr ::= expr likeop expr ESCAPE expr */ { ExprList *pList; int bNot = yymsp[-3].minor.yy0.n & 0x80000000; yymsp[-3].minor.yy0.n &= 0x7fffffff; pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr); pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0); exprNot(pParse, bNot, &yymsp[-4].minor.yy190); yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc; } break; case 178: /* expr ::= expr ISNULL|NOTNULL */ {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);} break; case 179: /* expr ::= expr NOT NULL */ {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);} break; case 180: /* expr ::= expr IS expr */ { spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190); binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL); } break; case 181: /* expr ::= expr IS NOT expr */ { spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190); binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL); } break; case 182: /* expr ::= NOT expr */ case 183: /* expr ::= BITNOT expr */ yytestcase(yyruleno==183); {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} break; case 184: /* expr ::= MINUS expr */ {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} break; case 185: /* expr ::= PLUS expr */ {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} break; case 186: /* between_op ::= BETWEEN */ case 189: /* in_op ::= IN */ yytestcase(yyruleno==189); {yymsp[0].minor.yy194 = 0;} break; case 188: /* expr ::= expr between_op expr AND expr */ { ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0); if( yymsp[-4].minor.yy190.pExpr ){ yymsp[-4].minor.yy190.pExpr->x.pList = pList; }else{ sqlite3ExprListDelete(pParse->db, pList); } exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; } break; case 191: /* expr ::= expr in_op LP exprlist RP */ { if( yymsp[-1].minor.yy148==0 ){ /* Expressions of the form ** ** expr1 IN () ** expr1 NOT IN () ** ** simplify to constants 0 (false) and 1 (true), respectively, ** regardless of the value of expr1. */ sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr); yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1); }else if( yymsp[-1].minor.yy148->nExpr==1 ){ /* Expressions of the form: ** ** expr1 IN (?1) ** expr1 NOT IN (?2) ** ** with exactly one value on the RHS can be simplified to something ** like this: ** ** expr1 == ?1 ** expr1 <> ?2 ** ** But, the RHS of the == or <> is marked with the EP_Generic flag ** so that it may not contribute to the computation of comparison ** affinity or the collating sequence to use for comparison. Otherwise, ** the semantics would be subtly different from IN or NOT IN. */ Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr; yymsp[-1].minor.yy148->a[0].pExpr = 0; sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); /* pRHS cannot be NULL because a malloc error would have been detected ** before now and control would have never reached this point */ if( ALWAYS(pRHS) ){ pRHS->flags &= ~EP_Collate; pRHS->flags |= EP_Generic; } yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS); }else{ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); if( yymsp[-4].minor.yy190.pExpr ){ yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148; sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); }else{ sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); } exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); } yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; } break; case 192: /* expr ::= LP select RP */ { spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0); sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243); } break; case 193: /* expr ::= expr in_op LP select RP */ { yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243); exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; } break; case 194: /* expr ::= expr in_op nm dbnm paren_exprlist */ { SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0); if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148); yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect); exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n]; } break; case 195: /* expr ::= EXISTS LP select RP */ { Expr *p; spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0); sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243); } break; case 196: /* expr ::= CASE case_operand case_exprlist case_else END */ { spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/ yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0); if( yymsp[-4].minor.yy190.pExpr ){ yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148; sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); }else{ sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148); sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72); } } break; case 197: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ { yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr); yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); } break; case 198: /* case_exprlist ::= WHEN expr THEN expr */ { yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr); } break; case 201: /* case_operand ::= expr */ {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/} break; case 204: /* nexprlist ::= nexprlist COMMA expr */ {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);} break; case 205: /* nexprlist ::= expr */ {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/} break; case 207: /* paren_exprlist ::= LP exprlist RP */ case 212: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==212); {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;} break; case 208: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ { sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194, &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF); } break; case 209: /* uniqueflag ::= UNIQUE */ case 250: /* raisetype ::= ABORT */ yytestcase(yyruleno==250); {yymsp[0].minor.yy194 = OE_Abort;} break; case 210: /* uniqueflag ::= */ {yymsp[1].minor.yy194 = OE_None;} break; case 213: /* eidlist ::= eidlist COMMA nm collate sortorder */ { yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); } break; case 214: /* eidlist ::= nm collate sortorder */ { yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/ } break; case 217: /* cmd ::= DROP INDEX ifexists fullname */ {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);} break; case 218: /* cmd ::= VACUUM */ {sqlite3Vacuum(pParse,0);} break; case 219: /* cmd ::= VACUUM nm */ {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);} break; case 220: /* cmd ::= PRAGMA nm dbnm */ {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} break; case 221: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} break; case 222: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} break; case 223: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);} break; case 224: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);} break; case 227: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ { Token all; all.z = yymsp[-3].minor.yy0.z; all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all); } break; case 228: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ { sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194); yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/ } break; case 229: /* trigger_time ::= BEFORE */ { yymsp[0].minor.yy194 = TK_BEFORE; } break; case 230: /* trigger_time ::= AFTER */ { yymsp[0].minor.yy194 = TK_AFTER; } break; case 231: /* trigger_time ::= INSTEAD OF */ { yymsp[-1].minor.yy194 = TK_INSTEAD;} break; case 232: /* trigger_time ::= */ { yymsp[1].minor.yy194 = TK_BEFORE; } break; case 233: /* trigger_event ::= DELETE|INSERT */ case 234: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==234); {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;} break; case 235: /* trigger_event ::= UPDATE OF idlist */ {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;} break; case 236: /* when_clause ::= */ case 255: /* key_opt ::= */ yytestcase(yyruleno==255); { yymsp[1].minor.yy72 = 0; } break; case 237: /* when_clause ::= WHEN expr */ case 256: /* key_opt ::= KEY expr */ yytestcase(yyruleno==256); { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; } break; case 238: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ { assert( yymsp[-2].minor.yy145!=0 ); yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145; yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145; } break; case 239: /* trigger_cmd_list ::= trigger_cmd SEMI */ { assert( yymsp[-1].minor.yy145!=0 ); yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145; } break; case 240: /* trnm ::= nm DOT nm */ { yymsp[-2].minor.yy0 = yymsp[0].minor.yy0; sqlite3ErrorMsg(pParse, "qualified table names are not allowed on INSERT, UPDATE, and DELETE " "statements within triggers"); } break; case 241: /* tridxby ::= INDEXED BY nm */ { sqlite3ErrorMsg(pParse, "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " "within triggers"); } break; case 242: /* tridxby ::= NOT INDEXED */ { sqlite3ErrorMsg(pParse, "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " "within triggers"); } break; case 243: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);} break; case 244: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */ {yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/} break; case 245: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);} break; case 246: /* trigger_cmd ::= select */ {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/} break; case 247: /* expr ::= RAISE LP IGNORE RP */ { spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0); if( yymsp[-3].minor.yy190.pExpr ){ yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore; } } break; case 248: /* expr ::= RAISE LP raisetype COMMA nm RP */ { spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); if( yymsp[-5].minor.yy190.pExpr ) { yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194; } } break; case 249: /* raisetype ::= ROLLBACK */ {yymsp[0].minor.yy194 = OE_Rollback;} break; case 251: /* raisetype ::= FAIL */ {yymsp[0].minor.yy194 = OE_Fail;} break; case 252: /* cmd ::= DROP TRIGGER ifexists fullname */ { sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194); } break; case 253: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ { sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72); } break; case 254: /* cmd ::= DETACH database_kw_opt expr */ { sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr); } break; case 257: /* cmd ::= REINDEX */ {sqlite3Reindex(pParse, 0, 0);} break; case 258: /* cmd ::= REINDEX nm dbnm */ {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} break; case 259: /* cmd ::= ANALYZE */ {sqlite3Analyze(pParse, 0, 0);} break; case 260: /* cmd ::= ANALYZE nm dbnm */ {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} break; case 261: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ { sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0); } break; case 262: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ { yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n; sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0); } break; case 263: /* add_column_fullname ::= fullname */ { disableLookaside(pParse); sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185); } break; case 264: /* cmd ::= create_vtab */ {sqlite3VtabFinishParse(pParse,0);} break; case 265: /* cmd ::= create_vtab LP vtabarglist RP */ {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} break; case 266: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ { sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194); } break; case 267: /* vtabarg ::= */ {sqlite3VtabArgInit(pParse);} break; case 268: /* vtabargtoken ::= ANY */ case 269: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==269); case 270: /* lp ::= LP */ yytestcase(yyruleno==270); {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} break; case 271: /* with ::= */ {yymsp[1].minor.yy285 = 0;} break; case 272: /* with ::= WITH wqlist */ { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; } break; case 273: /* with ::= WITH RECURSIVE wqlist */ { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; } break; case 274: /* wqlist ::= nm eidlist_opt AS LP select RP */ { yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/ } break; case 275: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ { yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); } break; default: /* (276) input ::= cmdlist */ yytestcase(yyruleno==276); /* (277) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==277); /* (278) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=278); /* (279) ecmd ::= SEMI */ yytestcase(yyruleno==279); /* (280) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==280); /* (281) explain ::= */ yytestcase(yyruleno==281); /* (282) trans_opt ::= */ yytestcase(yyruleno==282); /* (283) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==283); /* (284) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==284); /* (285) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==285); /* (286) savepoint_opt ::= */ yytestcase(yyruleno==286); /* (287) cmd ::= create_table create_table_args */ yytestcase(yyruleno==287); /* (288) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==288); /* (289) columnlist ::= columnname carglist */ yytestcase(yyruleno==289); /* (290) nm ::= ID|INDEXED */ yytestcase(yyruleno==290); /* (291) nm ::= STRING */ yytestcase(yyruleno==291); /* (292) nm ::= JOIN_KW */ yytestcase(yyruleno==292); /* (293) typetoken ::= typename */ yytestcase(yyruleno==293); /* (294) typename ::= ID|STRING */ yytestcase(yyruleno==294); /* (295) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=295); /* (296) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=296); /* (297) carglist ::= carglist ccons */ yytestcase(yyruleno==297); /* (298) carglist ::= */ yytestcase(yyruleno==298); /* (299) ccons ::= NULL onconf */ yytestcase(yyruleno==299); /* (300) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==300); /* (301) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==301); /* (302) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=302); /* (303) tconscomma ::= */ yytestcase(yyruleno==303); /* (304) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=304); /* (305) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=305); /* (306) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=306); /* (307) oneselect ::= values */ yytestcase(yyruleno==307); /* (308) sclp ::= selcollist COMMA */ yytestcase(yyruleno==308); /* (309) as ::= ID|STRING */ yytestcase(yyruleno==309); /* (310) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=310); /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311); /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312); /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313); /* (314) nmnum ::= ON */ yytestcase(yyruleno==314); /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315); /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316); /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317); /* (318) foreach_clause ::= */ yytestcase(yyruleno==318); /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319); /* (320) trnm ::= nm */ yytestcase(yyruleno==320); /* (321) tridxby ::= */ yytestcase(yyruleno==321); /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322); /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323); /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324); /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325); /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326); /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327); /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328); /* (329) anylist ::= */ yytestcase(yyruleno==329); /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330); /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331); break; /********** End reduce actions ************************************************/ }; assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) ); yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); if( yyact <= YY_MAX_SHIFTREDUCE ){ if( yyact>YY_MAX_SHIFT ){ yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; } yymsp -= yysize-1; yypParser->yytos = yymsp; yymsp->stateno = (YYACTIONTYPE)yyact; yymsp->major = (YYCODETYPE)yygoto; yyTraceShift(yypParser, yyact); }else{ assert( yyact == YY_ACCEPT_ACTION ); yypParser->yytos -= yysize; yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ #ifndef YYNOERRORRECOVERY static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ sqlite3ParserARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ /************ Begin %parse_failure code ***************************************/ /************ End %parse_failure code *****************************************/ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } #endif /* YYNOERRORRECOVERY */ /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */ ){ sqlite3ParserARG_FETCH; #define TOKEN yyminor /************ Begin %syntax_error code ****************************************/ UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); /************ End %syntax_error code ******************************************/ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser *yypParser /* The parser */ ){ sqlite3ParserARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt = -1; #endif assert( yypParser->yytos==yypParser->yystack ); /* Here code is inserted which will be executed whenever the ** parser accepts */ /*********** Begin %parse_accept code *****************************************/ /*********** End %parse_accept code *******************************************/ sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "sqlite3ParserAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: ** <ul> ** <li> A pointer to the parser (an opaque structure.) ** <li> The major token number. ** <li> The minor token number. ** <li> An option argument of a grammar-specified type. ** </ul> ** ** Outputs: ** None. */ SQLITE_PRIVATE void sqlite3Parser( void *yyp, /* The parser */ int yymajor, /* The major token code number */ sqlite3ParserTOKENTYPE yyminor /* The value for the token */ sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; unsigned int yyact; /* The parser action. */ #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) int yyendofinput; /* True if we are at the end of input */ #endif #ifdef YYERRORSYMBOL int yyerrorhit = 0; /* True if yymajor has invoked an error */ #endif yyParser *yypParser; /* The parser */ yypParser = (yyParser*)yyp; assert( yypParser->yytos!=0 ); #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) yyendofinput = (yymajor==0); #endif sqlite3ParserARG_STORE; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]); } #endif do{ yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); if( yyact <= YY_MAX_SHIFTREDUCE ){ yy_shift(yypParser,yyact,yymajor,yyminor); #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt--; #endif yymajor = YYNOCODE; }else if( yyact <= YY_MAX_REDUCE ){ yy_reduce(yypParser,yyact-YY_MIN_REDUCE); }else{ assert( yyact == YY_ERROR_ACTION ); yyminorunion.yy0 = yyminor; #ifdef YYERRORSYMBOL int yymx; #endif #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif #ifdef YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser->yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminor); } yymx = yypParser->yytos->major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser->yytos >= yypParser->yystack && yymx != YYERRORSYMBOL && (yyact = yy_find_reduce_action( yypParser->yytos->stateno, YYERRORSYMBOL)) >= YY_MIN_REDUCE ){ yy_pop_parser_stack(yypParser); } if( yypParser->yytos < yypParser->yystack || yymajor==0 ){ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); yy_parse_failed(yypParser); #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt = -1; #endif yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor); } } yypParser->yyerrcnt = 3; yyerrorhit = 1; #elif defined(YYNOERRORRECOVERY) /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to ** do any kind of error recovery. Instead, simply invoke the syntax ** error routine and continue going as if nothing had happened. ** ** Applications can set this macro (for example inside %include) if ** they intend to abandon the parse upon the first syntax error seen. */ yy_syntax_error(yypParser,yymajor, yyminor); yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); yymajor = YYNOCODE; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( yypParser->yyerrcnt<=0 ){ yy_syntax_error(yypParser,yymajor, yyminor); } yypParser->yyerrcnt = 3; yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); if( yyendofinput ){ yy_parse_failed(yypParser); #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt = -1; #endif } yymajor = YYNOCODE; #endif } }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack ); #ifndef NDEBUG if( yyTraceFILE ){ yyStackEntry *i; char cDiv = '['; fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt); for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){ fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]); cDiv = ' '; } fprintf(yyTraceFILE,"]\n"); } #endif return; } /************** End of parse.c ***********************************************/ /************** Begin file tokenize.c ****************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that splits an SQL input string up into ** individual tokens and sends those tokens one-by-one over to the ** parser for analysis. */ /* #include "sqliteInt.h" */ /* #include <stdlib.h> */ /* Character classes for tokenizing ** ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented ** using a lookup table, whereas a switch() directly on c uses a binary search. ** The lookup table is much faster. To maximize speed, and to ensure that ** a lookup table is used, all of the classes need to be small integers and ** all of them need to be used within the switch. */ #define CC_X 0 /* The letter 'x', or start of BLOB literal */ #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */ #define CC_ID 2 /* unicode characters usable in IDs */ #define CC_DIGIT 3 /* Digits */ #define CC_DOLLAR 4 /* '$' */ #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */ #define CC_VARNUM 6 /* '?'. Numeric SQL variables */ #define CC_SPACE 7 /* Space characters */ #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */ #define CC_QUOTE2 9 /* '['. [...] style quoted ids */ #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */ #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */ #define CC_LT 12 /* '<'. Part of < or <= or <> */ #define CC_GT 13 /* '>'. Part of > or >= */ #define CC_EQ 14 /* '='. Part of = or == */ #define CC_BANG 15 /* '!'. Part of != */ #define CC_SLASH 16 /* '/'. / or c-style comment */ #define CC_LP 17 /* '(' */ #define CC_RP 18 /* ')' */ #define CC_SEMI 19 /* ';' */ #define CC_PLUS 20 /* '+' */ #define CC_STAR 21 /* '*' */ #define CC_PERCENT 22 /* '%' */ #define CC_COMMA 23 /* ',' */ #define CC_AND 24 /* '&' */ #define CC_TILDA 25 /* '~' */ #define CC_DOT 26 /* '.' */ #define CC_ILLEGAL 27 /* Illegal character */ static const unsigned char aiClass[] = { #ifdef SQLITE_ASCII /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27, /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16, /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6, /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1, /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27, /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 #endif #ifdef SQLITE_EBCDIC /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27, /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10, /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27, /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6, /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8, /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27, /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27, #endif }; /* ** The charMap() macro maps alphabetic characters (only) into their ** lower-case ASCII equivalent. On ASCII machines, this is just ** an upper-to-lower case map. On EBCDIC machines we also need ** to adjust the encoding. The mapping is only valid for alphabetics ** which are the only characters for which this feature is used. ** ** Used by keywordhash.h */ #ifdef SQLITE_ASCII # define charMap(X) sqlite3UpperToLower[(unsigned char)X] #endif #ifdef SQLITE_EBCDIC # define charMap(X) ebcdicToAscii[(unsigned char)X] const unsigned char ebcdicToAscii[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ }; #endif /* ** The sqlite3KeywordCode function looks up an identifier to determine if ** it is a keyword. If it is a keyword, the token code of that keyword is ** returned. If the input is not a keyword, TK_ID is returned. ** ** The implementation of this routine was generated by a program, ** mkkeywordhash.c, located in the tool subdirectory of the distribution. ** The output of the mkkeywordhash.c program is written into a file ** named keywordhash.h and then included into this source file by ** the #include below. */ /************** Include keywordhash.h in the middle of tokenize.c ************/ /************** Begin file keywordhash.h *************************************/ /***** This file contains automatically generated code ****** ** ** The code in this file has been automatically generated by ** ** sqlite/tool/mkkeywordhash.c ** ** The code in this file implements a function that determines whether ** or not a given identifier is really an SQL keyword. The same thing ** might be implemented more directly using a hand-written hash table. ** But by using this automatically generated code, the size of the code ** is substantially reduced. This is important for embedded applications ** on platforms with limited memory. */ /* Hash score: 182 */ static int keywordCode(const char *z, int n, int *pType){ /* zText[] encodes 834 bytes of keywords in 554 bytes */ /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */ /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */ /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */ /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */ /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */ /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */ /* VACUUMVIEWINITIALLY */ static const char zText[553] = { 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E', 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S', 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A', 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E', 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A', 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A', 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A', 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J', 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L', 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E', 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H', 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E', 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E', 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M', 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R', 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A', 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D', 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O', 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T', 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R', 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M', 'V','I','E','W','I','N','I','T','I','A','L','L','Y', }; static const unsigned char aHash[127] = { 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0, 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0, 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71, 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44, 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25, 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0, 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14, 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113, 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0, 29, 0, 86, 63, 64, 0, 20, 61, 0, 56, }; static const unsigned char aNext[124] = { 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50, 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38, 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0, 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34, 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8, 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37, 73, 83, 0, 35, 68, 0, 0, }; static const unsigned char aLen[124] = { 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7, 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8, 3, 5, 5, 6, 4, 9, 3, }; static const unsigned short int aOffset[124] = { 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192, 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246, 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318, 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380, 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459, 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513, 521, 524, 529, 534, 540, 544, 549, }; static const unsigned char aCode[124] = { TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP, TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH, TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, }; int i, j; const char *zKW; if( n>=2 ){ i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127; for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){ if( aLen[i]!=n ) continue; j = 0; zKW = &zText[aOffset[i]]; #ifdef SQLITE_ASCII while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; } #endif #ifdef SQLITE_EBCDIC while( j<n && toupper(z[j])==zKW[j] ){ j++; } #endif if( j<n ) continue; testcase( i==0 ); /* REINDEX */ testcase( i==1 ); /* INDEXED */ testcase( i==2 ); /* INDEX */ testcase( i==3 ); /* DESC */ testcase( i==4 ); /* ESCAPE */ testcase( i==5 ); /* EACH */ testcase( i==6 ); /* CHECK */ testcase( i==7 ); /* KEY */ testcase( i==8 ); /* BEFORE */ testcase( i==9 ); /* FOREIGN */ testcase( i==10 ); /* FOR */ testcase( i==11 ); /* IGNORE */ testcase( i==12 ); /* REGEXP */ testcase( i==13 ); /* EXPLAIN */ testcase( i==14 ); /* INSTEAD */ testcase( i==15 ); /* ADD */ testcase( i==16 ); /* DATABASE */ testcase( i==17 ); /* AS */ testcase( i==18 ); /* SELECT */ testcase( i==19 ); /* TABLE */ testcase( i==20 ); /* LEFT */ testcase( i==21 ); /* THEN */ testcase( i==22 ); /* END */ testcase( i==23 ); /* DEFERRABLE */ testcase( i==24 ); /* ELSE */ testcase( i==25 ); /* EXCEPT */ testcase( i==26 ); /* TRANSACTION */ testcase( i==27 ); /* ACTION */ testcase( i==28 ); /* ON */ testcase( i==29 ); /* NATURAL */ testcase( i==30 ); /* ALTER */ testcase( i==31 ); /* RAISE */ testcase( i==32 ); /* EXCLUSIVE */ testcase( i==33 ); /* EXISTS */ testcase( i==34 ); /* SAVEPOINT */ testcase( i==35 ); /* INTERSECT */ testcase( i==36 ); /* TRIGGER */ testcase( i==37 ); /* REFERENCES */ testcase( i==38 ); /* CONSTRAINT */ testcase( i==39 ); /* INTO */ testcase( i==40 ); /* OFFSET */ testcase( i==41 ); /* OF */ testcase( i==42 ); /* SET */ testcase( i==43 ); /* TEMPORARY */ testcase( i==44 ); /* TEMP */ testcase( i==45 ); /* OR */ testcase( i==46 ); /* UNIQUE */ testcase( i==47 ); /* QUERY */ testcase( i==48 ); /* WITHOUT */ testcase( i==49 ); /* WITH */ testcase( i==50 ); /* OUTER */ testcase( i==51 ); /* RELEASE */ testcase( i==52 ); /* ATTACH */ testcase( i==53 ); /* HAVING */ testcase( i==54 ); /* GROUP */ testcase( i==55 ); /* UPDATE */ testcase( i==56 ); /* BEGIN */ testcase( i==57 ); /* INNER */ testcase( i==58 ); /* RECURSIVE */ testcase( i==59 ); /* BETWEEN */ testcase( i==60 ); /* NOTNULL */ testcase( i==61 ); /* NOT */ testcase( i==62 ); /* NO */ testcase( i==63 ); /* NULL */ testcase( i==64 ); /* LIKE */ testcase( i==65 ); /* CASCADE */ testcase( i==66 ); /* ASC */ testcase( i==67 ); /* DELETE */ testcase( i==68 ); /* CASE */ testcase( i==69 ); /* COLLATE */ testcase( i==70 ); /* CREATE */ testcase( i==71 ); /* CURRENT_DATE */ testcase( i==72 ); /* DETACH */ testcase( i==73 ); /* IMMEDIATE */ testcase( i==74 ); /* JOIN */ testcase( i==75 ); /* INSERT */ testcase( i==76 ); /* MATCH */ testcase( i==77 ); /* PLAN */ testcase( i==78 ); /* ANALYZE */ testcase( i==79 ); /* PRAGMA */ testcase( i==80 ); /* ABORT */ testcase( i==81 ); /* VALUES */ testcase( i==82 ); /* VIRTUAL */ testcase( i==83 ); /* LIMIT */ testcase( i==84 ); /* WHEN */ testcase( i==85 ); /* WHERE */ testcase( i==86 ); /* RENAME */ testcase( i==87 ); /* AFTER */ testcase( i==88 ); /* REPLACE */ testcase( i==89 ); /* AND */ testcase( i==90 ); /* DEFAULT */ testcase( i==91 ); /* AUTOINCREMENT */ testcase( i==92 ); /* TO */ testcase( i==93 ); /* IN */ testcase( i==94 ); /* CAST */ testcase( i==95 ); /* COLUMN */ testcase( i==96 ); /* COMMIT */ testcase( i==97 ); /* CONFLICT */ testcase( i==98 ); /* CROSS */ testcase( i==99 ); /* CURRENT_TIMESTAMP */ testcase( i==100 ); /* CURRENT_TIME */ testcase( i==101 ); /* PRIMARY */ testcase( i==102 ); /* DEFERRED */ testcase( i==103 ); /* DISTINCT */ testcase( i==104 ); /* IS */ testcase( i==105 ); /* DROP */ testcase( i==106 ); /* FAIL */ testcase( i==107 ); /* FROM */ testcase( i==108 ); /* FULL */ testcase( i==109 ); /* GLOB */ testcase( i==110 ); /* BY */ testcase( i==111 ); /* IF */ testcase( i==112 ); /* ISNULL */ testcase( i==113 ); /* ORDER */ testcase( i==114 ); /* RESTRICT */ testcase( i==115 ); /* RIGHT */ testcase( i==116 ); /* ROLLBACK */ testcase( i==117 ); /* ROW */ testcase( i==118 ); /* UNION */ testcase( i==119 ); /* USING */ testcase( i==120 ); /* VACUUM */ testcase( i==121 ); /* VIEW */ testcase( i==122 ); /* INITIALLY */ testcase( i==123 ); /* ALL */ *pType = aCode[i]; break; } } return n; } SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){ int id = TK_ID; keywordCode((char*)z, n, &id); return id; } #define SQLITE_N_KEYWORD 124 /************** End of keywordhash.h *****************************************/ /************** Continuing where we left off in tokenize.c *******************/ /* ** If X is a character that can be used in an identifier then ** IdChar(X) will be true. Otherwise it is false. ** ** For ASCII, any character with the high-order bit set is ** allowed in an identifier. For 7-bit characters, ** sqlite3IsIdChar[X] must be 1. ** ** For EBCDIC, the rules are more complex but have the same ** end result. ** ** Ticket #1066. the SQL standard does not allow '$' in the ** middle of identifiers. But many SQL implementations do. ** SQLite will allow '$' in identifiers for compatibility. ** But the feature is undocumented. */ #ifdef SQLITE_ASCII #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) #endif #ifdef SQLITE_EBCDIC SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = { /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ }; #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) #endif /* Make the IdChar function accessible from ctime.c */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); } #endif /* ** Return the length (in bytes) of the token that begins at z[0]. ** Store the token type in *tokenType before returning. */ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ int i, c; switch( aiClass[*z] ){ /* Switch on the character-class of the first byte ** of the token. See the comment on the CC_ defines ** above. */ case CC_SPACE: { testcase( z[0]==' ' ); testcase( z[0]=='\t' ); testcase( z[0]=='\n' ); testcase( z[0]=='\f' ); testcase( z[0]=='\r' ); for(i=1; sqlite3Isspace(z[i]); i++){} *tokenType = TK_SPACE; return i; } case CC_MINUS: { if( z[1]=='-' ){ for(i=2; (c=z[i])!=0 && c!='\n'; i++){} *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } *tokenType = TK_MINUS; return 1; } case CC_LP: { *tokenType = TK_LP; return 1; } case CC_RP: { *tokenType = TK_RP; return 1; } case CC_SEMI: { *tokenType = TK_SEMI; return 1; } case CC_PLUS: { *tokenType = TK_PLUS; return 1; } case CC_STAR: { *tokenType = TK_STAR; return 1; } case CC_SLASH: { if( z[1]!='*' || z[2]==0 ){ *tokenType = TK_SLASH; return 1; } for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){} if( c ) i++; *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } case CC_PERCENT: { *tokenType = TK_REM; return 1; } case CC_EQ: { *tokenType = TK_EQ; return 1 + (z[1]=='='); } case CC_LT: { if( (c=z[1])=='=' ){ *tokenType = TK_LE; return 2; }else if( c=='>' ){ *tokenType = TK_NE; return 2; }else if( c=='<' ){ *tokenType = TK_LSHIFT; return 2; }else{ *tokenType = TK_LT; return 1; } } case CC_GT: { if( (c=z[1])=='=' ){ *tokenType = TK_GE; return 2; }else if( c=='>' ){ *tokenType = TK_RSHIFT; return 2; }else{ *tokenType = TK_GT; return 1; } } case CC_BANG: { if( z[1]!='=' ){ *tokenType = TK_ILLEGAL; return 1; }else{ *tokenType = TK_NE; return 2; } } case CC_PIPE: { if( z[1]!='|' ){ *tokenType = TK_BITOR; return 1; }else{ *tokenType = TK_CONCAT; return 2; } } case CC_COMMA: { *tokenType = TK_COMMA; return 1; } case CC_AND: { *tokenType = TK_BITAND; return 1; } case CC_TILDA: { *tokenType = TK_BITNOT; return 1; } case CC_QUOTE: { int delim = z[0]; testcase( delim=='`' ); testcase( delim=='\'' ); testcase( delim=='"' ); for(i=1; (c=z[i])!=0; i++){ if( c==delim ){ if( z[i+1]==delim ){ i++; }else{ break; } } } if( c=='\'' ){ *tokenType = TK_STRING; return i+1; }else if( c!=0 ){ *tokenType = TK_ID; return i+1; }else{ *tokenType = TK_ILLEGAL; return i; } } case CC_DOT: { #ifndef SQLITE_OMIT_FLOATING_POINT if( !sqlite3Isdigit(z[1]) ) #endif { *tokenType = TK_DOT; return 1; } /* If the next character is a digit, this is a floating point ** number that begins with ".". Fall thru into the next case */ } case CC_DIGIT: { testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' ); testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' ); testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' ); testcase( z[0]=='9' ); *tokenType = TK_INTEGER; #ifndef SQLITE_OMIT_HEX_INTEGER if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){ for(i=3; sqlite3Isxdigit(z[i]); i++){} return i; } #endif for(i=0; sqlite3Isdigit(z[i]); i++){} #ifndef SQLITE_OMIT_FLOATING_POINT if( z[i]=='.' ){ i++; while( sqlite3Isdigit(z[i]) ){ i++; } *tokenType = TK_FLOAT; } if( (z[i]=='e' || z[i]=='E') && ( sqlite3Isdigit(z[i+1]) || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2])) ) ){ i += 2; while( sqlite3Isdigit(z[i]) ){ i++; } *tokenType = TK_FLOAT; } #endif while( IdChar(z[i]) ){ *tokenType = TK_ILLEGAL; i++; } return i; } case CC_QUOTE2: { for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} *tokenType = c==']' ? TK_ID : TK_ILLEGAL; return i; } case CC_VARNUM: { *tokenType = TK_VARIABLE; for(i=1; sqlite3Isdigit(z[i]); i++){} return i; } case CC_DOLLAR: case CC_VARALPHA: { int n = 0; testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' ); testcase( z[0]=='#' ); *tokenType = TK_VARIABLE; for(i=1; (c=z[i])!=0; i++){ if( IdChar(c) ){ n++; #ifndef SQLITE_OMIT_TCL_VARIABLE }else if( c=='(' && n>0 ){ do{ i++; }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' ); if( c==')' ){ i++; }else{ *tokenType = TK_ILLEGAL; } break; }else if( c==':' && z[i+1]==':' ){ i++; #endif }else{ break; } } if( n==0 ) *tokenType = TK_ILLEGAL; return i; } case CC_KYWD: { for(i=1; aiClass[z[i]]<=CC_KYWD; i++){} if( IdChar(z[i]) ){ /* This token started out using characters that can appear in keywords, ** but z[i] is a character not allowed within keywords, so this must ** be an identifier instead */ i++; break; } *tokenType = TK_ID; return keywordCode((char*)z, i, tokenType); } case CC_X: { #ifndef SQLITE_OMIT_BLOB_LITERAL testcase( z[0]=='x' ); testcase( z[0]=='X' ); if( z[1]=='\'' ){ *tokenType = TK_BLOB; for(i=2; sqlite3Isxdigit(z[i]); i++){} if( z[i]!='\'' || i%2 ){ *tokenType = TK_ILLEGAL; while( z[i] && z[i]!='\'' ){ i++; } } if( z[i] ) i++; return i; } #endif /* If it is not a BLOB literal, then it must be an ID, since no ** SQL keywords start with the letter 'x'. Fall through */ } case CC_ID: { i = 1; break; } default: { *tokenType = TK_ILLEGAL; return 1; } } while( IdChar(z[i]) ){ i++; } *tokenType = TK_ID; return i; } /* ** Run the parser on the given SQL string. The parser structure is ** passed in. An SQLITE_ status code is returned. If an error occurs ** then an and attempt is made to write an error message into ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that ** error message. */ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ int nErr = 0; /* Number of errors encountered */ int i; /* Loop counter */ void *pEngine; /* The LEMON-generated LALR(1) parser */ int tokenType; /* type of the next token */ int lastTokenParsed = -1; /* type of the previous token */ sqlite3 *db = pParse->db; /* The database connection */ int mxSqlLen; /* Max length of an SQL string */ #ifdef sqlite3Parser_ENGINEALWAYSONSTACK unsigned char zSpace[sizeof(yyParser)]; /* Space for parser engine object */ #endif assert( zSql!=0 ); mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; if( db->nVdbeActive==0 ){ db->u1.isInterrupted = 0; } pParse->rc = SQLITE_OK; pParse->zTail = zSql; i = 0; assert( pzErrMsg!=0 ); /* sqlite3ParserTrace(stdout, "parser: "); */ #ifdef sqlite3Parser_ENGINEALWAYSONSTACK pEngine = zSpace; sqlite3ParserInit(pEngine); #else pEngine = sqlite3ParserAlloc(sqlite3Malloc); if( pEngine==0 ){ sqlite3OomFault(db); return SQLITE_NOMEM_BKPT; } #endif assert( pParse->pNewTable==0 ); assert( pParse->pNewTrigger==0 ); assert( pParse->nVar==0 ); assert( pParse->pVList==0 ); while( 1 ){ assert( i>=0 ); if( zSql[i]!=0 ){ pParse->sLastToken.z = &zSql[i]; pParse->sLastToken.n = sqlite3GetToken((u8*)&zSql[i],&tokenType); i += pParse->sLastToken.n; if( i>mxSqlLen ){ pParse->rc = SQLITE_TOOBIG; break; } }else{ /* Upon reaching the end of input, call the parser two more times ** with tokens TK_SEMI and 0, in that order. */ if( lastTokenParsed==TK_SEMI ){ tokenType = 0; }else if( lastTokenParsed==0 ){ break; }else{ tokenType = TK_SEMI; } } if( tokenType>=TK_SPACE ){ assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL ); if( db->u1.isInterrupted ){ pParse->rc = SQLITE_INTERRUPT; break; } if( tokenType==TK_ILLEGAL ){ sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"", &pParse->sLastToken); break; } }else{ sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse); lastTokenParsed = tokenType; if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break; } } assert( nErr==0 ); pParse->zTail = &zSql[i]; #ifdef YYTRACKMAXSTACKDEPTH sqlite3_mutex_enter(sqlite3MallocMutex()); sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK, sqlite3ParserStackPeak(pEngine) ); sqlite3_mutex_leave(sqlite3MallocMutex()); #endif /* YYDEBUG */ #ifdef sqlite3Parser_ENGINEALWAYSONSTACK sqlite3ParserFinalize(pEngine); #else sqlite3ParserFree(pEngine, sqlite3_free); #endif if( db->mallocFailed ){ pParse->rc = SQLITE_NOMEM_BKPT; } if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){ pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc)); } assert( pzErrMsg!=0 ); if( pParse->zErrMsg ){ *pzErrMsg = pParse->zErrMsg; sqlite3_log(pParse->rc, "%s", *pzErrMsg); pParse->zErrMsg = 0; nErr++; } if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ sqlite3VdbeDelete(pParse->pVdbe); pParse->pVdbe = 0; } #ifndef SQLITE_OMIT_SHARED_CACHE if( pParse->nested==0 ){ sqlite3DbFree(db, pParse->aTableLock); pParse->aTableLock = 0; pParse->nTableLock = 0; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE sqlite3_free(pParse->apVtabLock); #endif if( !IN_DECLARE_VTAB ){ /* If the pParse->declareVtab flag is set, do not delete any table ** structure built up in pParse->pNewTable. The calling code (see vtab.c) ** will take responsibility for freeing the Table structure. */ sqlite3DeleteTable(db, pParse->pNewTable); } if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree); sqlite3DeleteTrigger(db, pParse->pNewTrigger); sqlite3DbFree(db, pParse->pVList); while( pParse->pAinc ){ AutoincInfo *p = pParse->pAinc; pParse->pAinc = p->pNext; sqlite3DbFree(db, p); } while( pParse->pZombieTab ){ Table *p = pParse->pZombieTab; pParse->pZombieTab = p->pNextZombie; sqlite3DeleteTable(db, p); } assert( nErr==0 || pParse->rc!=SQLITE_OK ); return nErr; } /************** End of tokenize.c ********************************************/ /************** Begin file complete.c ****************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that implements the sqlite3_complete() API. ** This code used to be part of the tokenizer.c source file. But by ** separating it out, the code will be automatically omitted from ** static links that do not use it. */ /* #include "sqliteInt.h" */ #ifndef SQLITE_OMIT_COMPLETE /* ** This is defined in tokenize.c. We just have to import the definition. */ #ifndef SQLITE_AMALGAMATION #ifdef SQLITE_ASCII #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) #endif #ifdef SQLITE_EBCDIC SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) #endif #endif /* SQLITE_AMALGAMATION */ /* ** Token types used by the sqlite3_complete() routine. See the header ** comments on that procedure for additional information. */ #define tkSEMI 0 #define tkWS 1 #define tkOTHER 2 #ifndef SQLITE_OMIT_TRIGGER #define tkEXPLAIN 3 #define tkCREATE 4 #define tkTEMP 5 #define tkTRIGGER 6 #define tkEND 7 #endif /* ** Return TRUE if the given SQL string ends in a semicolon. ** ** Special handling is require for CREATE TRIGGER statements. ** Whenever the CREATE TRIGGER keywords are seen, the statement ** must end with ";END;". ** ** This implementation uses a state machine with 8 states: ** ** (0) INVALID We have not yet seen a non-whitespace character. ** ** (1) START At the beginning or end of an SQL statement. This routine ** returns 1 if it ends in the START state and 0 if it ends ** in any other state. ** ** (2) NORMAL We are in the middle of statement which ends with a single ** semicolon. ** ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of ** a statement. ** ** (4) CREATE The keyword CREATE has been seen at the beginning of a ** statement, possibly preceded by EXPLAIN and/or followed by ** TEMP or TEMPORARY ** ** (5) TRIGGER We are in the middle of a trigger definition that must be ** ended by a semicolon, the keyword END, and another semicolon. ** ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at ** the end of a trigger definition. ** ** (7) END We've seen the ";END" of the ";END;" that occurs at the end ** of a trigger definition. ** ** Transitions between states above are determined by tokens extracted ** from the input. The following tokens are significant: ** ** (0) tkSEMI A semicolon. ** (1) tkWS Whitespace. ** (2) tkOTHER Any other SQL token. ** (3) tkEXPLAIN The "explain" keyword. ** (4) tkCREATE The "create" keyword. ** (5) tkTEMP The "temp" or "temporary" keyword. ** (6) tkTRIGGER The "trigger" keyword. ** (7) tkEND The "end" keyword. ** ** Whitespace never causes a state transition and is always ignored. ** This means that a SQL string of all whitespace is invalid. ** ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ SQLITE_API int sqlite3_complete(const char *zSql){ u8 state = 0; /* Current state, using numbers defined in header comment */ u8 token; /* Value of the next token */ #ifndef SQLITE_OMIT_TRIGGER /* A complex statement machine used to detect the end of a CREATE TRIGGER ** statement. This is the normal case. */ static const u8 trans[8][8] = { /* Token: */ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, }, /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, }, /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, }, /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, }, /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, }, /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, }, /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, }, /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, }, }; #else /* If triggers are not supported by this compile then the statement machine ** used to detect the end of a statement is much simpler */ static const u8 trans[3][3] = { /* Token: */ /* State: ** SEMI WS OTHER */ /* 0 INVALID: */ { 1, 0, 2, }, /* 1 START: */ { 1, 1, 2, }, /* 2 NORMAL: */ { 1, 2, 2, }, }; #endif /* SQLITE_OMIT_TRIGGER */ #ifdef SQLITE_ENABLE_API_ARMOR if( zSql==0 ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif while( *zSql ){ switch( *zSql ){ case ';': { /* A semicolon */ token = tkSEMI; break; } case ' ': case '\r': case '\t': case '\n': case '\f': { /* White space is ignored */ token = tkWS; break; } case '/': { /* C-style comments */ if( zSql[1]!='*' ){ token = tkOTHER; break; } zSql += 2; while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; } if( zSql[0]==0 ) return 0; zSql++; token = tkWS; break; } case '-': { /* SQL-style comments from "--" to end of line */ if( zSql[1]!='-' ){ token = tkOTHER; break; } while( *zSql && *zSql!='\n' ){ zSql++; } if( *zSql==0 ) return state==1; token = tkWS; break; } case '[': { /* Microsoft-style identifiers in [...] */ zSql++; while( *zSql && *zSql!=']' ){ zSql++; } if( *zSql==0 ) return 0; token = tkOTHER; break; } case '`': /* Grave-accent quoted symbols used by MySQL */ case '"': /* single- and double-quoted strings */ case '\'': { int c = *zSql; zSql++; while( *zSql && *zSql!=c ){ zSql++; } if( *zSql==0 ) return 0; token = tkOTHER; break; } default: { #ifdef SQLITE_EBCDIC unsigned char c; #endif if( IdChar((u8)*zSql) ){ /* Keywords and unquoted identifiers */ int nId; for(nId=1; IdChar(zSql[nId]); nId++){} #ifdef SQLITE_OMIT_TRIGGER token = tkOTHER; #else switch( *zSql ){ case 'c': case 'C': { if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){ token = tkCREATE; }else{ token = tkOTHER; } break; } case 't': case 'T': { if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){ token = tkTRIGGER; }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){ token = tkTEMP; }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){ token = tkTEMP; }else{ token = tkOTHER; } break; } case 'e': case 'E': { if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){ token = tkEND; }else #ifndef SQLITE_OMIT_EXPLAIN if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){ token = tkEXPLAIN; }else #endif { token = tkOTHER; } break; } default: { token = tkOTHER; break; } } #endif /* SQLITE_OMIT_TRIGGER */ zSql += nId-1; }else{ /* Operators and special symbols */ token = tkOTHER; } break; } } state = trans[state][token]; zSql++; } return state==1; } #ifndef SQLITE_OMIT_UTF16 /* ** This routine is the same as the sqlite3_complete() routine described ** above, except that the parameter is required to be UTF-16 encoded, not ** UTF-8. */ SQLITE_API int sqlite3_complete16(const void *zSql){ sqlite3_value *pVal; char const *zSql8; int rc; #ifndef SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc ) return rc; #endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ rc = sqlite3_complete(zSql8); }else{ rc = SQLITE_NOMEM_BKPT; } sqlite3ValueFree(pVal); return rc & 0xff; } #endif /* SQLITE_OMIT_UTF16 */ #endif /* SQLITE_OMIT_COMPLETE */ /************** End of complete.c ********************************************/ /************** Begin file main.c ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. */ /* #include "sqliteInt.h" */ #ifdef SQLITE_ENABLE_FTS3 /************** Include fts3.h in the middle of main.c ***********************/ /************** Begin file fts3.h ********************************************/ /* ** 2006 Oct 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file is used by programs that want to link against the ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. */ /* #include "sqlite3.h" */ #if 0 extern "C" { #endif /* __cplusplus */ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db); #if 0 } /* extern "C" */ #endif /* __cplusplus */ /************** End of fts3.h ************************************************/ /************** Continuing where we left off in main.c ***********************/ #endif #ifdef SQLITE_ENABLE_RTREE /************** Include rtree.h in the middle of main.c **********************/ /************** Begin file rtree.h *******************************************/ /* ** 2008 May 26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file is used by programs that want to link against the ** RTREE library. All it does is declare the sqlite3RtreeInit() interface. */ /* #include "sqlite3.h" */ #if 0 extern "C" { #endif /* __cplusplus */ SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); #if 0 } /* extern "C" */ #endif /* __cplusplus */ /************** End of rtree.h ***********************************************/ /************** Continuing where we left off in main.c ***********************/ #endif #ifdef SQLITE_ENABLE_ICU /************** Include sqliteicu.h in the middle of main.c ******************/ /************** Begin file sqliteicu.h ***************************************/ /* ** 2008 May 26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file is used by programs that want to link against the ** ICU extension. All it does is declare the sqlite3IcuInit() interface. */ /* #include "sqlite3.h" */ #if 0 extern "C" { #endif /* __cplusplus */ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db); #if 0 } /* extern "C" */ #endif /* __cplusplus */ /************** End of sqliteicu.h *******************************************/ /************** Continuing where we left off in main.c ***********************/ #endif #ifdef SQLITE_ENABLE_JSON1 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*); #endif #ifdef SQLITE_ENABLE_FTS5 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*); #endif #ifndef SQLITE_AMALGAMATION /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant ** contains the text of SQLITE_VERSION macro. */ SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; #endif /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns ** a pointer to the to the sqlite3_version[] string constant. */ SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; } /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a ** pointer to a string constant whose value is the same as the ** SQLITE_SOURCE_ID C preprocessor macro. */ SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function ** returns an integer equal to SQLITE_VERSION_NUMBER. */ SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns ** zero if and only if SQLite was compiled with mutexing code omitted due to ** the SQLITE_THREADSAFE compile-time option being set to 0. */ SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } /* ** When compiling the test fixture or with debugging enabled (on Win32), ** this variable being set to non-zero will cause OSTRACE macros to emit ** extra diagnostic information. */ #ifdef SQLITE_HAVE_OS_TRACE # ifndef SQLITE_DEBUG_OS_TRACE # define SQLITE_DEBUG_OS_TRACE 0 # endif int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; #endif #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) /* ** If the following function pointer is not NULL and if ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing ** I/O active are written using this function. These messages ** are intended for debugging activity only. */ SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0; #endif /* ** If the following global variable points to a string which is the ** name of a directory, then that directory will be used to store ** temporary files. ** ** See also the "PRAGMA temp_store_directory" SQL command. */ SQLITE_API char *sqlite3_temp_directory = 0; /* ** If the following global variable points to a string which is the ** name of a directory, then that directory will be used to store ** all database files specified with a relative pathname. ** ** See also the "PRAGMA data_store_directory" SQL command. */ SQLITE_API char *sqlite3_data_directory = 0; /* ** Initialize SQLite. ** ** This routine must be called to initialize the memory allocation, ** VFS, and mutex subsystems prior to doing any serious work with ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT ** this routine will be called automatically by key routines such as ** sqlite3_open(). ** ** This routine is a no-op except on its very first call for the process, ** or for the first call after a call to sqlite3_shutdown. ** ** The first thread to call this routine runs the initialization to ** completion. If subsequent threads call this routine before the first ** thread has finished the initialization process, then the subsequent ** threads must block until the first thread finishes with the initialization. ** ** The first thread might call this routine recursively. Recursive ** calls to this routine should not block, of course. Otherwise the ** initialization process would never complete. ** ** Let X be the first thread to enter this routine. Let Y be some other ** thread. Then while the initial invocation of this routine by X is ** incomplete, it is required that: ** ** * Calls to this routine from Y must block until the outer-most ** call by X completes. ** ** * Recursive calls to this routine from thread X return immediately ** without blocking. */ SQLITE_API int sqlite3_initialize(void){ MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ int rc; /* Result code */ #ifdef SQLITE_EXTRA_INIT int bRunExtraInit = 0; /* Extra initialization needed */ #endif #ifdef SQLITE_OMIT_WSD rc = sqlite3_wsd_init(4096, 24); if( rc!=SQLITE_OK ){ return rc; } #endif /* If the following assert() fails on some obscure processor/compiler ** combination, the work-around is to set the correct pointer ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */ assert( SQLITE_PTRSIZE==sizeof(char*) ); /* If SQLite is already completely initialized, then this call ** to sqlite3_initialize() should be a no-op. But the initialization ** must be complete. So isInit must not be set until the very end ** of this routine. */ if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; /* Make sure the mutex subsystem is initialized. If unable to ** initialize the mutex subsystem, return early with the error. ** If the system is so sick that we are unable to allocate a mutex, ** there is not much SQLite is going to be able to do. ** ** The mutex subsystem must take care of serializing its own ** initialization. */ rc = sqlite3MutexInit(); if( rc ) return rc; /* Initialize the malloc() system and the recursive pInitMutex mutex. ** This operation is protected by the STATIC_MASTER mutex. Note that ** MutexAlloc() is called for a static mutex prior to initializing the ** malloc subsystem - this implies that the allocation of a static ** mutex must not require support from the malloc subsystem. */ MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) sqlite3_mutex_enter(pMaster); sqlite3GlobalConfig.isMutexInit = 1; if( !sqlite3GlobalConfig.isMallocInit ){ rc = sqlite3MallocInit(); } if( rc==SQLITE_OK ){ sqlite3GlobalConfig.isMallocInit = 1; if( !sqlite3GlobalConfig.pInitMutex ){ sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ rc = SQLITE_NOMEM_BKPT; } } } if( rc==SQLITE_OK ){ sqlite3GlobalConfig.nRefInitMutex++; } sqlite3_mutex_leave(pMaster); /* If rc is not SQLITE_OK at this point, then either the malloc ** subsystem could not be initialized or the system failed to allocate ** the pInitMutex mutex. Return an error in either case. */ if( rc!=SQLITE_OK ){ return rc; } /* Do the rest of the initialization under the recursive mutex so ** that we will be able to handle recursive calls into ** sqlite3_initialize(). The recursive calls normally come through ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other ** recursive calls might also be possible. ** ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls ** to the xInit method, so the xInit method need not be threadsafe. ** ** The following mutex is what serializes access to the appdef pcache xInit ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the ** call to sqlite3PcacheInitialize(). */ sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ sqlite3GlobalConfig.inProgress = 1; #ifdef SQLITE_ENABLE_SQLLOG { extern void sqlite3_init_sqllog(void); sqlite3_init_sqllog(); } #endif memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions)); sqlite3RegisterBuiltinFunctions(); if( sqlite3GlobalConfig.isPCacheInit==0 ){ rc = sqlite3PcacheInitialize(); } if( rc==SQLITE_OK ){ sqlite3GlobalConfig.isPCacheInit = 1; rc = sqlite3OsInit(); } if( rc==SQLITE_OK ){ sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); sqlite3GlobalConfig.isInit = 1; #ifdef SQLITE_EXTRA_INIT bRunExtraInit = 1; #endif } sqlite3GlobalConfig.inProgress = 0; } sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); /* Go back under the static mutex and clean up the recursive ** mutex to prevent a resource leak. */ sqlite3_mutex_enter(pMaster); sqlite3GlobalConfig.nRefInitMutex--; if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ assert( sqlite3GlobalConfig.nRefInitMutex==0 ); sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); sqlite3GlobalConfig.pInitMutex = 0; } sqlite3_mutex_leave(pMaster); /* The following is just a sanity check to make sure SQLite has ** been compiled correctly. It is important to run this code, but ** we don't want to run it too often and soak up CPU cycles for no ** reason. So we run it once during initialization. */ #ifndef NDEBUG #ifndef SQLITE_OMIT_FLOATING_POINT /* This section of code's only "output" is via assert() statements. */ if ( rc==SQLITE_OK ){ u64 x = (((u64)1)<<63)-1; double y; assert(sizeof(x)==8); assert(sizeof(x)==sizeof(y)); memcpy(&y, &x, 8); assert( sqlite3IsNaN(y) ); } #endif #endif /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT ** compile-time option. */ #ifdef SQLITE_EXTRA_INIT if( bRunExtraInit ){ int SQLITE_EXTRA_INIT(const char*); rc = SQLITE_EXTRA_INIT(0); } #endif return rc; } /* ** Undo the effects of sqlite3_initialize(). Must not be called while ** there are outstanding database connections or memory allocations or ** while any part of SQLite is otherwise in use in any thread. This ** routine is not threadsafe. But it is safe to invoke this routine ** on when SQLite is already shut down. If SQLite is already shut down ** when this routine is invoked, then this routine is a harmless no-op. */ SQLITE_API int sqlite3_shutdown(void){ #ifdef SQLITE_OMIT_WSD int rc = sqlite3_wsd_init(4096, 24); if( rc!=SQLITE_OK ){ return rc; } #endif if( sqlite3GlobalConfig.isInit ){ #ifdef SQLITE_EXTRA_SHUTDOWN void SQLITE_EXTRA_SHUTDOWN(void); SQLITE_EXTRA_SHUTDOWN(); #endif sqlite3_os_end(); sqlite3_reset_auto_extension(); sqlite3GlobalConfig.isInit = 0; } if( sqlite3GlobalConfig.isPCacheInit ){ sqlite3PcacheShutdown(); sqlite3GlobalConfig.isPCacheInit = 0; } if( sqlite3GlobalConfig.isMallocInit ){ sqlite3MallocEnd(); sqlite3GlobalConfig.isMallocInit = 0; #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES /* The heap subsystem has now been shutdown and these values are supposed ** to be NULL or point to memory that was obtained from sqlite3_malloc(), ** which would rely on that heap subsystem; therefore, make sure these ** values cannot refer to heap memory that was just invalidated when the ** heap subsystem was shutdown. This is only done if the current call to ** this function resulted in the heap subsystem actually being shutdown. */ sqlite3_data_directory = 0; sqlite3_temp_directory = 0; #endif } if( sqlite3GlobalConfig.isMutexInit ){ sqlite3MutexEnd(); sqlite3GlobalConfig.isMutexInit = 0; } return SQLITE_OK; } /* ** This API allows applications to modify the global configuration of ** the SQLite library at run-time. ** ** This routine should only be called when there are no outstanding ** database connections or memory allocations. This routine is not ** threadsafe. Failure to heed these warnings can lead to unpredictable ** behavior. */ SQLITE_API int sqlite3_config(int op, ...){ va_list ap; int rc = SQLITE_OK; /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while ** the SQLite library is in use. */ if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; va_start(ap, op); switch( op ){ /* Mutex configuration options are only available in a threadsafe ** compile. */ #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */ case SQLITE_CONFIG_SINGLETHREAD: { /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to ** Single-thread. */ sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */ sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */ case SQLITE_CONFIG_MULTITHREAD: { /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to ** Multi-thread. */ sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */ case SQLITE_CONFIG_SERIALIZED: { /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to ** Serialized. */ sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */ break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */ case SQLITE_CONFIG_MUTEX: { /* Specify an alternative mutex implementation */ sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */ case SQLITE_CONFIG_GETMUTEX: { /* Retrieve the current mutex implementation */ *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; break; } #endif case SQLITE_CONFIG_MALLOC: { /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a ** single argument which is a pointer to an instance of the ** sqlite3_mem_methods structure. The argument specifies alternative ** low-level memory allocation routines to be used in place of the memory ** allocation routines built into SQLite. */ sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); break; } case SQLITE_CONFIG_GETMALLOC: { /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a ** single argument which is a pointer to an instance of the ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is ** filled with the currently defined memory allocation routines. */ if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; break; } case SQLITE_CONFIG_MEMSTATUS: { /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes ** single argument of type int, interpreted as a boolean, which enables ** or disables the collection of memory allocation statistics. */ sqlite3GlobalConfig.bMemstat = va_arg(ap, int); break; } case SQLITE_CONFIG_SCRATCH: { /* EVIDENCE-OF: R-08404-60887 There are three arguments to ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from ** which the scratch allocations will be drawn, the size of each scratch ** allocation (sz), and the maximum number of scratch allocations (N). */ sqlite3GlobalConfig.pScratch = va_arg(ap, void*); sqlite3GlobalConfig.szScratch = va_arg(ap, int); sqlite3GlobalConfig.nScratch = va_arg(ap, int); break; } case SQLITE_CONFIG_PAGECACHE: { /* EVIDENCE-OF: R-18761-36601 There are three arguments to ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem), ** the size of each page cache line (sz), and the number of cache lines ** (N). */ sqlite3GlobalConfig.pPage = va_arg(ap, void*); sqlite3GlobalConfig.szPage = va_arg(ap, int); sqlite3GlobalConfig.nPage = va_arg(ap, int); break; } case SQLITE_CONFIG_PCACHE_HDRSZ: { /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes ** a single parameter which is a pointer to an integer and writes into ** that integer the number of extra bytes per page required for each page ** in SQLITE_CONFIG_PAGECACHE. */ *va_arg(ap, int*) = sqlite3HeaderSizeBtree() + sqlite3HeaderSizePcache() + sqlite3HeaderSizePcache1(); break; } case SQLITE_CONFIG_PCACHE: { /* no-op */ break; } case SQLITE_CONFIG_GETPCACHE: { /* now an error */ rc = SQLITE_ERROR; break; } case SQLITE_CONFIG_PCACHE2: { /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a ** single argument which is a pointer to an sqlite3_pcache_methods2 ** object. This object specifies the interface to a custom page cache ** implementation. */ sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); break; } case SQLITE_CONFIG_GETPCACHE2: { /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a ** single argument which is a pointer to an sqlite3_pcache_methods2 ** object. SQLite copies of the current page cache implementation into ** that object. */ if( sqlite3GlobalConfig.pcache2.xInit==0 ){ sqlite3PCacheSetDefault(); } *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; break; } /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */ #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) case SQLITE_CONFIG_HEAP: { /* EVIDENCE-OF: R-19854-42126 There are three arguments to ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the ** number of bytes in the memory buffer, and the minimum allocation size. */ sqlite3GlobalConfig.pHeap = va_arg(ap, void*); sqlite3GlobalConfig.nHeap = va_arg(ap, int); sqlite3GlobalConfig.mnReq = va_arg(ap, int); if( sqlite3GlobalConfig.mnReq<1 ){ sqlite3GlobalConfig.mnReq = 1; }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ /* cap min request size at 2^12 */ sqlite3GlobalConfig.mnReq = (1<<12); } if( sqlite3GlobalConfig.pHeap==0 ){ /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer) ** is NULL, then SQLite reverts to using its default memory allocator ** (the system malloc() implementation), undoing any prior invocation of ** SQLITE_CONFIG_MALLOC. ** ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to ** revert to its default implementation when sqlite3_initialize() is run */ memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); }else{ /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the ** alternative memory allocator is engaged to handle all of SQLites ** memory allocation needs. */ #ifdef SQLITE_ENABLE_MEMSYS3 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); #endif #ifdef SQLITE_ENABLE_MEMSYS5 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); #endif } break; } #endif case SQLITE_CONFIG_LOOKASIDE: { sqlite3GlobalConfig.szLookaside = va_arg(ap, int); sqlite3GlobalConfig.nLookaside = va_arg(ap, int); break; } /* Record a pointer to the logger function and its first argument. ** The default is NULL. Logging is disabled if the function pointer is ** NULL. */ case SQLITE_CONFIG_LOG: { /* MSVC is picky about pulling func ptrs from va lists. ** http://support.microsoft.com/kb/47961 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); */ typedef void(*LOGFUNC_t)(void*,int,const char*); sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); break; } /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames ** can be changed at start-time using the ** sqlite3_config(SQLITE_CONFIG_URI,1) or ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. */ case SQLITE_CONFIG_URI: { /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single ** argument of type int. If non-zero, then URI handling is globally ** enabled. If the parameter is zero, then URI handling is globally ** disabled. */ sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); break; } case SQLITE_CONFIG_COVERING_INDEX_SCAN: { /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN ** option takes a single integer argument which is interpreted as a ** boolean in order to enable or disable the use of covering indices for ** full table scans in the query optimizer. */ sqlite3GlobalConfig.bUseCis = va_arg(ap, int); break; } #ifdef SQLITE_ENABLE_SQLLOG case SQLITE_CONFIG_SQLLOG: { typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); break; } #endif case SQLITE_CONFIG_MMAP_SIZE: { /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit ** integer (sqlite3_int64) values that are the default mmap size limit ** (the default setting for PRAGMA mmap_size) and the maximum allowed ** mmap size limit. */ sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); /* EVIDENCE-OF: R-53367-43190 If either argument to this option is ** negative, then that argument is changed to its compile-time default. ** ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be ** silently truncated if necessary so that it does not exceed the ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE ** compile-time option. */ if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ mxMmap = SQLITE_MAX_MMAP_SIZE; } if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; if( szMmap>mxMmap) szMmap = mxMmap; sqlite3GlobalConfig.mxMmap = mxMmap; sqlite3GlobalConfig.szMmap = szMmap; break; } #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */ case SQLITE_CONFIG_WIN32_HEAPSIZE: { /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit ** unsigned integer value that specifies the maximum size of the created ** heap. */ sqlite3GlobalConfig.nHeap = va_arg(ap, int); break; } #endif case SQLITE_CONFIG_PMASZ: { sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int); break; } case SQLITE_CONFIG_STMTJRNL_SPILL: { sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int); break; } default: { rc = SQLITE_ERROR; break; } } va_end(ap); return rc; } /* ** Set up the lookaside buffers for a database connection. ** Return SQLITE_OK on success. ** If lookaside is already active, return SQLITE_BUSY. ** ** The sz parameter is the number of bytes in each lookaside slot. ** The cnt parameter is the number of slots. If pStart is NULL the ** space for the lookaside memory is obtained from sqlite3_malloc(). ** If pStart is not NULL then it is sz*cnt bytes of memory to use for ** the lookaside memory. */ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ #ifndef SQLITE_OMIT_LOOKASIDE void *pStart; if( db->lookaside.nOut ){ return SQLITE_BUSY; } /* Free any existing lookaside buffer for this handle before ** allocating a new one so we don't have to have space for ** both at the same time. */ if( db->lookaside.bMalloced ){ sqlite3_free(db->lookaside.pStart); } /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger ** than a pointer to be useful. */ sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; if( cnt<0 ) cnt = 0; if( sz==0 || cnt==0 ){ sz = 0; pStart = 0; }else if( pBuf==0 ){ sqlite3BeginBenignMalloc(); pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ sqlite3EndBenignMalloc(); if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; }else{ pStart = pBuf; } db->lookaside.pStart = pStart; db->lookaside.pFree = 0; db->lookaside.sz = (u16)sz; if( pStart ){ int i; LookasideSlot *p; assert( sz > (int)sizeof(LookasideSlot*) ); p = (LookasideSlot*)pStart; for(i=cnt-1; i>=0; i--){ p->pNext = db->lookaside.pFree; db->lookaside.pFree = p; p = (LookasideSlot*)&((u8*)p)[sz]; } db->lookaside.pEnd = p; db->lookaside.bDisable = 0; db->lookaside.bMalloced = pBuf==0 ?1:0; }else{ db->lookaside.pStart = db; db->lookaside.pEnd = db; db->lookaside.bDisable = 1; db->lookaside.bMalloced = 0; } #endif /* SQLITE_OMIT_LOOKASIDE */ return SQLITE_OK; } /* ** Return the mutex associated with a database connection. */ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->mutex; } /* ** Free up as much memory as we can from the given database ** connection. */ SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){ int i; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ Pager *pPager = sqlite3BtreePager(pBt); sqlite3PagerShrink(pPager); } } sqlite3BtreeLeaveAll(db); sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Flush any dirty pages in the pager-cache for any attached database ** to disk. */ SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){ int i; int rc = SQLITE_OK; int bSeenBusy = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt && sqlite3BtreeIsInTrans(pBt) ){ Pager *pPager = sqlite3BtreePager(pBt); rc = sqlite3PagerFlush(pPager); if( rc==SQLITE_BUSY ){ bSeenBusy = 1; rc = SQLITE_OK; } } } sqlite3BtreeLeaveAll(db); sqlite3_mutex_leave(db->mutex); return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc); } /* ** Configuration settings for an individual database connection */ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ va_list ap; int rc; va_start(ap, op); switch( op ){ case SQLITE_DBCONFIG_MAINDBNAME: { db->aDb[0].zDbSName = va_arg(ap,char*); rc = SQLITE_OK; break; } case SQLITE_DBCONFIG_LOOKASIDE: { void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ rc = setupLookaside(db, pBuf, sz, cnt); break; } default: { static const struct { int op; /* The opcode */ u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ } aFlagOp[] = { { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer }, { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension }, { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose }, }; unsigned int i; rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ for(i=0; i<ArraySize(aFlagOp); i++){ if( aFlagOp[i].op==op ){ int onoff = va_arg(ap, int); int *pRes = va_arg(ap, int*); int oldFlags = db->flags; if( onoff>0 ){ db->flags |= aFlagOp[i].mask; }else if( onoff==0 ){ db->flags &= ~aFlagOp[i].mask; } if( oldFlags!=db->flags ){ sqlite3ExpirePreparedStatements(db); } if( pRes ){ *pRes = (db->flags & aFlagOp[i].mask)!=0; } rc = SQLITE_OK; break; } } break; } } va_end(ap); return rc; } /* ** Return true if the buffer z[0..n-1] contains all spaces. */ static int allSpaces(const char *z, int n){ while( n>0 && z[n-1]==' ' ){ n--; } return n==0; } /* ** This is the default collating function named "BINARY" which is always ** available. ** ** If the padFlag argument is not NULL then space padding at the end ** of strings is ignored. This implements the RTRIM collation. */ static int binCollFunc( void *padFlag, int nKey1, const void *pKey1, int nKey2, const void *pKey2 ){ int rc, n; n = nKey1<nKey2 ? nKey1 : nKey2; /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares ** strings byte by byte using the memcmp() function from the standard C ** library. */ rc = memcmp(pKey1, pKey2, n); if( rc==0 ){ if( padFlag && allSpaces(((char*)pKey1)+n, nKey1-n) && allSpaces(((char*)pKey2)+n, nKey2-n) ){ /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra ** spaces at the end of either string do not change the result. In other ** words, strings will compare equal to one another as long as they ** differ only in the number of spaces at the end. */ }else{ rc = nKey1 - nKey2; } } return rc; } /* ** Another built-in collating sequence: NOCASE. ** ** This collating sequence is intended to be used for "case independent ** comparison". SQLite's knowledge of upper and lower case equivalents ** extends only to the 26 characters used in the English language. ** ** At the moment there is only a UTF-8 implementation. */ static int nocaseCollatingFunc( void *NotUsed, int nKey1, const void *pKey1, int nKey2, const void *pKey2 ){ int r = sqlite3StrNICmp( (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2); UNUSED_PARAMETER(NotUsed); if( 0==r ){ r = nKey1-nKey2; } return r; } /* ** Return the ROWID of the most recent insert */ SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->lastRowid; } /* ** Return the number of changes in the most recent call to sqlite3_exec(). */ SQLITE_API int sqlite3_changes(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->nChange; } /* ** Return the number of changes since the database handle was opened. */ SQLITE_API int sqlite3_total_changes(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->nTotalChange; } /* ** Close all open savepoints. This function only manipulates fields of the ** database handle object, it does not close any savepoints that may be open ** at the b-tree/pager level. */ SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){ while( db->pSavepoint ){ Savepoint *pTmp = db->pSavepoint; db->pSavepoint = pTmp->pNext; sqlite3DbFree(db, pTmp); } db->nSavepoint = 0; db->nStatement = 0; db->isTransactionSavepoint = 0; } /* ** Invoke the destructor function associated with FuncDef p, if any. Except, ** if this is not the last copy of the function, do not invoke it. Multiple ** copies of a single function are created when create_function() is called ** with SQLITE_ANY as the encoding. */ static void functionDestroy(sqlite3 *db, FuncDef *p){ FuncDestructor *pDestructor = p->u.pDestructor; if( pDestructor ){ pDestructor->nRef--; if( pDestructor->nRef==0 ){ pDestructor->xDestroy(pDestructor->pUserData); sqlite3DbFree(db, pDestructor); } } } /* ** Disconnect all sqlite3_vtab objects that belong to database connection ** db. This is called when db is being closed. */ static void disconnectAllVtab(sqlite3 *db){ #ifndef SQLITE_OMIT_VIRTUALTABLE int i; HashElem *p; sqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ Schema *pSchema = db->aDb[i].pSchema; if( db->aDb[i].pSchema ){ for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ Table *pTab = (Table *)sqliteHashData(p); if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); } } } for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){ Module *pMod = (Module *)sqliteHashData(p); if( pMod->pEpoTab ){ sqlite3VtabDisconnect(db, pMod->pEpoTab); } } sqlite3VtabUnlockList(db); sqlite3BtreeLeaveAll(db); #else UNUSED_PARAMETER(db); #endif } /* ** Return TRUE if database connection db has unfinalized prepared ** statements or unfinished sqlite3_backup objects. */ static int connectionIsBusy(sqlite3 *db){ int j; assert( sqlite3_mutex_held(db->mutex) ); if( db->pVdbe ) return 1; for(j=0; j<db->nDb; j++){ Btree *pBt = db->aDb[j].pBt; if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; } return 0; } /* ** Close an existing SQLite database */ static int sqlite3Close(sqlite3 *db, int forceZombie){ if( !db ){ /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ return SQLITE_OK; } if( !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(db->mutex); if( db->mTrace & SQLITE_TRACE_CLOSE ){ db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0); } /* Force xDisconnect calls on all virtual tables */ disconnectAllVtab(db); /* If a transaction is open, the disconnectAllVtab() call above ** will not have called the xDisconnect() method on any virtual ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() ** call will do so. We need to do this before the check for active ** SQL statements below, as the v-table implementation may be storing ** some prepared statements internally. */ sqlite3VtabRollback(db); /* Legacy behavior (sqlite3_close() behavior) is to return ** SQLITE_BUSY if the connection can not be closed immediately. */ if( !forceZombie && connectionIsBusy(db) ){ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " "statements or unfinished backups"); sqlite3_mutex_leave(db->mutex); return SQLITE_BUSY; } #ifdef SQLITE_ENABLE_SQLLOG if( sqlite3GlobalConfig.xSqllog ){ /* Closing the handle. Fourth parameter is passed the value 2. */ sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); } #endif /* Convert the connection into a zombie and then close it. */ db->magic = SQLITE_MAGIC_ZOMBIE; sqlite3LeaveMutexAndCloseZombie(db); return SQLITE_OK; } /* ** Two variations on the public interface for closing a database ** connection. The sqlite3_close() version returns SQLITE_BUSY and ** leaves the connection option if there are unfinalized prepared ** statements or unfinished sqlite3_backups. The sqlite3_close_v2() ** version forces the connection to become a zombie if there are ** unclosed resources, and arranges for deallocation when the last ** prepare statement or sqlite3_backup closes. */ SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } /* ** Close the mutex on database connection db. ** ** Furthermore, if database connection db is a zombie (meaning that there ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and ** every sqlite3_stmt has now been finalized and every sqlite3_backup has ** finished, then free all resources. */ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ HashElem *i; /* Hash table iterator */ int j; /* If there are outstanding sqlite3_stmt or sqlite3_backup objects ** or if the connection has not yet been closed by sqlite3_close_v2(), ** then just leave the mutex and return. */ if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ sqlite3_mutex_leave(db->mutex); return; } /* If we reach this point, it means that the database connection has ** closed all sqlite3_stmt and sqlite3_backup objects and has been ** passed to sqlite3_close (meaning that it is a zombie). Therefore, ** go ahead and free all resources. */ /* If a transaction is open, roll it back. This also ensures that if ** any database schemas have been modified by an uncommitted transaction ** they are reset. And that the required b-tree mutex is held to make ** the pager rollback and schema reset an atomic operation. */ sqlite3RollbackAll(db, SQLITE_OK); /* Free any outstanding Savepoint structures. */ sqlite3CloseSavepoints(db); /* Close all database connections */ for(j=0; j<db->nDb; j++){ struct Db *pDb = &db->aDb[j]; if( pDb->pBt ){ sqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; if( j!=1 ){ pDb->pSchema = 0; } } } /* Clear the TEMP schema separately and last */ if( db->aDb[1].pSchema ){ sqlite3SchemaClear(db->aDb[1].pSchema); } sqlite3VtabUnlockList(db); /* Free up the array of auxiliary databases */ sqlite3CollapseDatabaseArray(db); assert( db->nDb<=2 ); assert( db->aDb==db->aDbStatic ); /* Tell the code in notify.c that the connection no longer holds any ** locks and does not require any further unlock-notify callbacks. */ sqlite3ConnectionClosed(db); for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){ FuncDef *pNext, *p; p = sqliteHashData(i); do{ functionDestroy(db, p); pNext = p->pNext; sqlite3DbFree(db, p); p = pNext; }while( p ); } sqlite3HashClear(&db->aFunc); for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ CollSeq *pColl = (CollSeq *)sqliteHashData(i); /* Invoke any destructors registered for collation sequence user data. */ for(j=0; j<3; j++){ if( pColl[j].xDel ){ pColl[j].xDel(pColl[j].pUser); } } sqlite3DbFree(db, pColl); } sqlite3HashClear(&db->aCollSeq); #ifndef SQLITE_OMIT_VIRTUALTABLE for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ Module *pMod = (Module *)sqliteHashData(i); if( pMod->xDestroy ){ pMod->xDestroy(pMod->pAux); } sqlite3VtabEponymousTableClear(db, pMod); sqlite3DbFree(db, pMod); } sqlite3HashClear(&db->aModule); #endif sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ sqlite3ValueFree(db->pErr); sqlite3CloseExtensions(db); #if SQLITE_USER_AUTHENTICATION sqlite3_free(db->auth.zAuthUser); sqlite3_free(db->auth.zAuthPW); #endif db->magic = SQLITE_MAGIC_ERROR; /* The temp-database schema is allocated differently from the other schema ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). ** So it needs to be freed here. Todo: Why not roll the temp schema into ** the same sqliteMalloc() as the one that allocates the database ** structure? */ sqlite3DbFree(db, db->aDb[1].pSchema); sqlite3_mutex_leave(db->mutex); db->magic = SQLITE_MAGIC_CLOSED; sqlite3_mutex_free(db->mutex); assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ if( db->lookaside.bMalloced ){ sqlite3_free(db->lookaside.pStart); } sqlite3_free(db); } /* ** Rollback all database files. If tripCode is not SQLITE_OK, then ** any write cursors are invalidated ("tripped" - as in "tripping a circuit ** breaker") and made to return tripCode if there are any further ** attempts to use that cursor. Read cursors remain open and valid ** but are "saved" in case the table pages are moved around. */ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){ int i; int inTrans = 0; int schemaChange; assert( sqlite3_mutex_held(db->mutex) ); sqlite3BeginBenignMalloc(); /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). ** This is important in case the transaction being rolled back has ** modified the database schema. If the b-tree mutexes are not taken ** here, then another shared-cache connection might sneak in between ** the database rollback and schema reset, which can cause false ** corruption reports in some cases. */ sqlite3BtreeEnterAll(db); schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0; for(i=0; i<db->nDb; i++){ Btree *p = db->aDb[i].pBt; if( p ){ if( sqlite3BtreeIsInTrans(p) ){ inTrans = 1; } sqlite3BtreeRollback(p, tripCode, !schemaChange); } } sqlite3VtabRollback(db); sqlite3EndBenignMalloc(); if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){ sqlite3ExpirePreparedStatements(db); sqlite3ResetAllSchemasOfConnection(db); } sqlite3BtreeLeaveAll(db); /* Any deferred constraint violations have now been resolved. */ db->nDeferredCons = 0; db->nDeferredImmCons = 0; db->flags &= ~SQLITE_DeferFKs; /* If one has been configured, invoke the rollback-hook callback */ if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ db->xRollbackCallback(db->pRollbackArg); } } /* ** Return a static string containing the name corresponding to the error code ** specified in the argument. */ #if defined(SQLITE_NEED_ERR_NAME) SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ const char *zName = 0; int i, origRc = rc; for(i=0; i<2 && zName==0; i++, rc &= 0xff){ switch( rc ){ case SQLITE_OK: zName = "SQLITE_OK"; break; case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; case SQLITE_PERM: zName = "SQLITE_PERM"; break; case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break; case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; case SQLITE_IOERR_CHECKRESERVEDLOCK: zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; case SQLITE_FULL: zName = "SQLITE_FULL"; break; case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; case SQLITE_CONSTRAINT_FOREIGNKEY: zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; case SQLITE_CONSTRAINT_PRIMARYKEY: zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; case SQLITE_CONSTRAINT_COMMITHOOK: zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; case SQLITE_CONSTRAINT_FUNCTION: zName = "SQLITE_CONSTRAINT_FUNCTION"; break; case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break; case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; case SQLITE_ROW: zName = "SQLITE_ROW"; break; case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; case SQLITE_NOTICE_RECOVER_ROLLBACK: zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; case SQLITE_DONE: zName = "SQLITE_DONE"; break; } } if( zName==0 ){ static char zBuf[50]; sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); zName = zBuf; } return zName; } #endif /* ** Return a static string that describes the kind of error specified in the ** argument. */ SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ static const char* const aMsg[] = { /* SQLITE_OK */ "not an error", /* SQLITE_ERROR */ "SQL logic error or missing database", /* SQLITE_INTERNAL */ 0, /* SQLITE_PERM */ "access permission denied", /* SQLITE_ABORT */ "callback requested query abort", /* SQLITE_BUSY */ "database is locked", /* SQLITE_LOCKED */ "database table is locked", /* SQLITE_NOMEM */ "out of memory", /* SQLITE_READONLY */ "attempt to write a readonly database", /* SQLITE_INTERRUPT */ "interrupted", /* SQLITE_IOERR */ "disk I/O error", /* SQLITE_CORRUPT */ "database disk image is malformed", /* SQLITE_NOTFOUND */ "unknown operation", /* SQLITE_FULL */ "database or disk is full", /* SQLITE_CANTOPEN */ "unable to open database file", /* SQLITE_PROTOCOL */ "locking protocol", /* SQLITE_EMPTY */ "table contains no data", /* SQLITE_SCHEMA */ "database schema has changed", /* SQLITE_TOOBIG */ "string or blob too big", /* SQLITE_CONSTRAINT */ "constraint failed", /* SQLITE_MISMATCH */ "datatype mismatch", /* SQLITE_MISUSE */ "library routine called out of sequence", /* SQLITE_NOLFS */ "large file support is disabled", /* SQLITE_AUTH */ "authorization denied", /* SQLITE_FORMAT */ "auxiliary database format error", /* SQLITE_RANGE */ "bind or column index out of range", /* SQLITE_NOTADB */ "file is encrypted or is not a database", }; const char *zErr = "unknown error"; switch( rc ){ case SQLITE_ABORT_ROLLBACK: { zErr = "abort due to ROLLBACK"; break; } default: { rc &= 0xff; if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){ zErr = aMsg[rc]; } break; } } return zErr; } /* ** This routine implements a busy callback that sleeps and tries ** again until a timeout value is reached. The timeout value is ** an integer number of milliseconds passed in as the first ** argument. */ static int sqliteDefaultBusyCallback( void *ptr, /* Database connection */ int count /* Number of times table has been busy */ ){ #if SQLITE_OS_WIN || HAVE_USLEEP static const u8 delays[] = { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; static const u8 totals[] = { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; # define NDELAY ArraySize(delays) sqlite3 *db = (sqlite3 *)ptr; int timeout = db->busyTimeout; int delay, prior; assert( count>=0 ); if( count < NDELAY ){ delay = delays[count]; prior = totals[count]; }else{ delay = delays[NDELAY-1]; prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); } if( prior + delay > timeout ){ delay = timeout - prior; if( delay<=0 ) return 0; } sqlite3OsSleep(db->pVfs, delay*1000); return 1; #else sqlite3 *db = (sqlite3 *)ptr; int timeout = ((sqlite3 *)ptr)->busyTimeout; if( (count+1)*1000 > timeout ){ return 0; } sqlite3OsSleep(db->pVfs, 1000000); return 1; #endif } /* ** Invoke the given busy handler. ** ** This routine is called when an operation failed with a lock. ** If this routine returns non-zero, the lock is retried. If it ** returns 0, the operation aborts with an SQLITE_BUSY error. */ SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ int rc; if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; rc = p->xFunc(p->pArg, p->nBusy); if( rc==0 ){ p->nBusy = -1; }else{ p->nBusy++; } return rc; } /* ** This routine sets the busy callback for an Sqlite database to the ** given callback function with the given argument. */ SQLITE_API int sqlite3_busy_handler( sqlite3 *db, int (*xBusy)(void*,int), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->busyHandler.xFunc = xBusy; db->busyHandler.pArg = pArg; db->busyHandler.nBusy = 0; db->busyTimeout = 0; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_PROGRESS_CALLBACK /* ** This routine sets the progress callback for an Sqlite database to the ** given callback function with the given argument. The progress callback will ** be invoked every nOps opcodes. */ SQLITE_API void sqlite3_progress_handler( sqlite3 *db, int nOps, int (*xProgress)(void*), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return; } #endif sqlite3_mutex_enter(db->mutex); if( nOps>0 ){ db->xProgress = xProgress; db->nProgressOps = (unsigned)nOps; db->pProgressArg = pArg; }else{ db->xProgress = 0; db->nProgressOps = 0; db->pProgressArg = 0; } sqlite3_mutex_leave(db->mutex); } #endif /* ** This routine installs a default busy handler that waits for the ** specified number of milliseconds before returning 0. */ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif if( ms>0 ){ sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); db->busyTimeout = ms; }else{ sqlite3_busy_handler(db, 0, 0); } return SQLITE_OK; } /* ** Cause any pending operation to stop at its earliest opportunity. */ SQLITE_API void sqlite3_interrupt(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){ (void)SQLITE_MISUSE_BKPT; return; } #endif db->u1.isInterrupted = 1; } /* ** This function is exactly the same as sqlite3_create_function(), except ** that it is designed to be called by internal code. The difference is ** that if a malloc() fails in sqlite3_create_function(), an error code ** is returned and the mallocFailed flag cleared. */ SQLITE_PRIVATE int sqlite3CreateFunc( sqlite3 *db, const char *zFunctionName, int nArg, int enc, void *pUserData, void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), void (*xStep)(sqlite3_context*,int,sqlite3_value **), void (*xFinal)(sqlite3_context*), FuncDestructor *pDestructor ){ FuncDef *p; int nName; int extraFlags; assert( sqlite3_mutex_held(db->mutex) ); if( zFunctionName==0 || (xSFunc && (xFinal || xStep)) || (!xSFunc && (xFinal && !xStep)) || (!xSFunc && (!xFinal && xStep)) || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || (255<(nName = sqlite3Strlen30( zFunctionName))) ){ return SQLITE_MISUSE_BKPT; } assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); extraFlags = enc & SQLITE_DETERMINISTIC; enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); #ifndef SQLITE_OMIT_UTF16 /* If SQLITE_UTF16 is specified as the encoding type, transform this ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. ** ** If SQLITE_ANY is specified, add three versions of the function ** to the hash table. */ if( enc==SQLITE_UTF16 ){ enc = SQLITE_UTF16NATIVE; }else if( enc==SQLITE_ANY ){ int rc; rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags, pUserData, xSFunc, xStep, xFinal, pDestructor); if( rc==SQLITE_OK ){ rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags, pUserData, xSFunc, xStep, xFinal, pDestructor); } if( rc!=SQLITE_OK ){ return rc; } enc = SQLITE_UTF16BE; } #else enc = SQLITE_UTF8; #endif /* Check if an existing function is being overridden or deleted. If so, ** and there are active VMs, then return SQLITE_BUSY. If a function ** is being overridden/deleted but there are no active VMs, allow the ** operation to continue but invalidate all precompiled statements. */ p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0); if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){ if( db->nVdbeActive ){ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to delete/modify user-function due to active statements"); assert( !db->mallocFailed ); return SQLITE_BUSY; }else{ sqlite3ExpirePreparedStatements(db); } } p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1); assert(p || db->mallocFailed); if( !p ){ return SQLITE_NOMEM_BKPT; } /* If an older version of the function with a configured destructor is ** being replaced invoke the destructor function here. */ functionDestroy(db, p); if( pDestructor ){ pDestructor->nRef++; } p->u.pDestructor = pDestructor; p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags; testcase( p->funcFlags & SQLITE_DETERMINISTIC ); p->xSFunc = xSFunc ? xSFunc : xStep; p->xFinalize = xFinal; p->pUserData = pUserData; p->nArg = (u16)nArg; return SQLITE_OK; } /* ** Create new user functions. */ SQLITE_API int sqlite3_create_function( sqlite3 *db, const char *zFunc, int nArg, int enc, void *p, void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), void (*xStep)(sqlite3_context*,int,sqlite3_value **), void (*xFinal)(sqlite3_context*) ){ return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, 0); } SQLITE_API int sqlite3_create_function_v2( sqlite3 *db, const char *zFunc, int nArg, int enc, void *p, void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), void (*xStep)(sqlite3_context*,int,sqlite3_value **), void (*xFinal)(sqlite3_context*), void (*xDestroy)(void *) ){ int rc = SQLITE_ERROR; FuncDestructor *pArg = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( xDestroy ){ pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); if( !pArg ){ xDestroy(p); goto out; } pArg->xDestroy = xDestroy; pArg->pUserData = p; } rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg); if( pArg && pArg->nRef==0 ){ assert( rc!=SQLITE_OK ); xDestroy(p); sqlite3DbFree(db, pArg); } out: rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #ifndef SQLITE_OMIT_UTF16 SQLITE_API int sqlite3_create_function16( sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *p, void (*xSFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ){ int rc; char *zFunc8; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0); sqlite3DbFree(db, zFunc8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #endif /* ** Declare that a function has been overloaded by a virtual table. ** ** If the function already exists as a regular global function, then ** this routine is a no-op. If the function does not exist, then create ** a new one that always throws a run-time error. ** ** When virtual tables intend to provide an overloaded function, they ** should call this routine to make sure the global function exists. ** A global function must exist in order for name resolution to work ** properly. */ SQLITE_API int sqlite3_overload_function( sqlite3 *db, const char *zName, int nArg ){ int rc = SQLITE_OK; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){ rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, 0, sqlite3InvalidFunction, 0, 0, 0); } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #ifndef SQLITE_OMIT_TRACE /* ** Register a trace function. The pArg from the previously registered trace ** is returned. ** ** A NULL trace function means that no tracing is executes. A non-NULL ** trace is a pointer to a function that is invoked at the start of each ** SQL statement. */ #ifndef SQLITE_OMIT_DEPRECATED SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pOld = db->pTraceArg; db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0; db->xTrace = (int(*)(u32,void*,void*,void*))xTrace; db->pTraceArg = pArg; sqlite3_mutex_leave(db->mutex); return pOld; } #endif /* SQLITE_OMIT_DEPRECATED */ /* Register a trace callback using the version-2 interface. */ SQLITE_API int sqlite3_trace_v2( sqlite3 *db, /* Trace this connection */ unsigned mTrace, /* Mask of events to be traced */ int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */ void *pArg /* Context */ ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( mTrace==0 ) xTrace = 0; if( xTrace==0 ) mTrace = 0; db->mTrace = mTrace; db->xTrace = xTrace; db->pTraceArg = pArg; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Register a profile function. The pArg from the previously registered ** profile function is returned. ** ** A NULL profile function means that no profiling is executes. A non-NULL ** profile is a pointer to a function that is invoked at the conclusion of ** each SQL statement that is run. */ SQLITE_API void *sqlite3_profile( sqlite3 *db, void (*xProfile)(void*,const char*,sqlite_uint64), void *pArg ){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pOld = db->pProfileArg; db->xProfile = xProfile; db->pProfileArg = pArg; sqlite3_mutex_leave(db->mutex); return pOld; } #endif /* SQLITE_OMIT_DEPRECATED */ #endif /* SQLITE_OMIT_TRACE */ /* ** Register a function to be invoked when a transaction commits. ** If the invoked function returns non-zero, then the commit becomes a ** rollback. */ SQLITE_API void *sqlite3_commit_hook( sqlite3 *db, /* Attach the hook to this database */ int (*xCallback)(void*), /* Function to invoke on each commit */ void *pArg /* Argument to the function */ ){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pOld = db->pCommitArg; db->xCommitCallback = xCallback; db->pCommitArg = pArg; sqlite3_mutex_leave(db->mutex); return pOld; } /* ** Register a callback to be invoked each time a row is updated, ** inserted or deleted using this database connection. */ SQLITE_API void *sqlite3_update_hook( sqlite3 *db, /* Attach the hook to this database */ void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), void *pArg /* Argument to the function */ ){ void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pRet = db->pUpdateArg; db->xUpdateCallback = xCallback; db->pUpdateArg = pArg; sqlite3_mutex_leave(db->mutex); return pRet; } /* ** Register a callback to be invoked each time a transaction is rolled ** back by this database connection. */ SQLITE_API void *sqlite3_rollback_hook( sqlite3 *db, /* Attach the hook to this database */ void (*xCallback)(void*), /* Callback function */ void *pArg /* Argument to the function */ ){ void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pRet = db->pRollbackArg; db->xRollbackCallback = xCallback; db->pRollbackArg = pArg; sqlite3_mutex_leave(db->mutex); return pRet; } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** Register a callback to be invoked each time a row is updated, ** inserted or deleted using this database connection. */ SQLITE_API void *sqlite3_preupdate_hook( sqlite3 *db, /* Attach the hook to this database */ void(*xCallback)( /* Callback function */ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64), void *pArg /* First callback argument */ ){ void *pRet; sqlite3_mutex_enter(db->mutex); pRet = db->pPreUpdateArg; db->xPreUpdateCallback = xCallback; db->pPreUpdateArg = pArg; sqlite3_mutex_leave(db->mutex); return pRet; } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifndef SQLITE_OMIT_WAL /* ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file ** is greater than sqlite3.pWalArg cast to an integer (the value configured by ** wal_autocheckpoint()). */ SQLITE_PRIVATE int sqlite3WalDefaultHook( void *pClientData, /* Argument */ sqlite3 *db, /* Connection */ const char *zDb, /* Database */ int nFrame /* Size of WAL */ ){ if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ sqlite3BeginBenignMalloc(); sqlite3_wal_checkpoint(db, zDb); sqlite3EndBenignMalloc(); } return SQLITE_OK; } #endif /* SQLITE_OMIT_WAL */ /* ** Configure an sqlite3_wal_hook() callback to automatically checkpoint ** a database after committing a transaction if there are nFrame or ** more frames in the log file. Passing zero or a negative value as the ** nFrame parameter disables automatic checkpoints entirely. ** ** The callback registered by this function replaces any existing callback ** registered using sqlite3_wal_hook(). Likewise, registering a callback ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism ** configured by this function. */ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ #ifdef SQLITE_OMIT_WAL UNUSED_PARAMETER(db); UNUSED_PARAMETER(nFrame); #else #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif if( nFrame>0 ){ sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); }else{ sqlite3_wal_hook(db, 0, 0); } #endif return SQLITE_OK; } /* ** Register a callback to be invoked each time a transaction is written ** into the write-ahead-log by this database connection. */ SQLITE_API void *sqlite3_wal_hook( sqlite3 *db, /* Attach the hook to this db handle */ int(*xCallback)(void *, sqlite3*, const char*, int), void *pArg /* First argument passed to xCallback() */ ){ #ifndef SQLITE_OMIT_WAL void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif sqlite3_mutex_enter(db->mutex); pRet = db->pWalArg; db->xWalCallback = xCallback; db->pWalArg = pArg; sqlite3_mutex_leave(db->mutex); return pRet; #else return 0; #endif } /* ** Checkpoint database zDb. */ SQLITE_API int sqlite3_wal_checkpoint_v2( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ int *pnCkpt /* OUT: Total number of frames checkpointed */ ){ #ifdef SQLITE_OMIT_WAL return SQLITE_OK; #else int rc; /* Return code */ int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif /* Initialize the output variables to -1 in case an error occurs. */ if( pnLog ) *pnLog = -1; if( pnCkpt ) *pnCkpt = -1; assert( SQLITE_CHECKPOINT_PASSIVE==0 ); assert( SQLITE_CHECKPOINT_FULL==1 ); assert( SQLITE_CHECKPOINT_RESTART==2 ); assert( SQLITE_CHECKPOINT_TRUNCATE==3 ); if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){ /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint ** mode: */ return SQLITE_MISUSE; } sqlite3_mutex_enter(db->mutex); if( zDb && zDb[0] ){ iDb = sqlite3FindDbName(db, zDb); } if( iDb<0 ){ rc = SQLITE_ERROR; sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); }else{ db->busyHandler.nBusy = 0; rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); sqlite3Error(db, rc); } rc = sqlite3ApiExit(db, rc); /* If there are no active statements, clear the interrupt flag at this ** point. */ if( db->nVdbeActive==0 ){ db->u1.isInterrupted = 0; } sqlite3_mutex_leave(db->mutex); return rc; #endif } /* ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points ** to contains a zero-length string, all attached databases are ** checkpointed. */ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */ return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0); } #ifndef SQLITE_OMIT_WAL /* ** Run a checkpoint on database iDb. This is a no-op if database iDb is ** not currently open in WAL mode. ** ** If a transaction is open on the database being checkpointed, this ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If ** an error occurs while running the checkpoint, an SQLite error code is ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. ** ** The mutex on database handle db should be held by the caller. The mutex ** associated with the specific b-tree being checkpointed is taken by ** this function while the checkpoint is running. ** ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are ** checkpointed. If an error is encountered it is returned immediately - ** no attempt is made to checkpoint any remaining databases. ** ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. */ SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ int rc = SQLITE_OK; /* Return code */ int i; /* Used to iterate through attached dbs */ int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ assert( sqlite3_mutex_held(db->mutex) ); assert( !pnLog || *pnLog==-1 ); assert( !pnCkpt || *pnCkpt==-1 ); for(i=0; i<db->nDb && rc==SQLITE_OK; i++){ if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); pnLog = 0; pnCkpt = 0; if( rc==SQLITE_BUSY ){ bBusy = 1; rc = SQLITE_OK; } } } return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; } #endif /* SQLITE_OMIT_WAL */ /* ** This function returns true if main-memory should be used instead of ** a temporary file for transient pager files and statement journals. ** The value returned depends on the value of db->temp_store (runtime ** parameter) and the compile time value of SQLITE_TEMP_STORE. The ** following table describes the relationship between these two values ** and this functions return value. ** ** SQLITE_TEMP_STORE db->temp_store Location of temporary database ** ----------------- -------------- ------------------------------ ** 0 any file (return 0) ** 1 1 file (return 0) ** 1 2 memory (return 1) ** 1 0 file (return 0) ** 2 1 file (return 0) ** 2 2 memory (return 1) ** 2 0 memory (return 1) ** 3 any memory (return 1) */ SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){ #if SQLITE_TEMP_STORE==1 return ( db->temp_store==2 ); #endif #if SQLITE_TEMP_STORE==2 return ( db->temp_store!=1 ); #endif #if SQLITE_TEMP_STORE==3 UNUSED_PARAMETER(db); return 1; #endif #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 UNUSED_PARAMETER(db); return 0; #endif } /* ** Return UTF-8 encoded English language explanation of the most recent ** error. */ SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ const char *z; if( !db ){ return sqlite3ErrStr(SQLITE_NOMEM_BKPT); } if( !sqlite3SafetyCheckSickOrOk(db) ){ return sqlite3ErrStr(SQLITE_MISUSE_BKPT); } sqlite3_mutex_enter(db->mutex); if( db->mallocFailed ){ z = sqlite3ErrStr(SQLITE_NOMEM_BKPT); }else{ testcase( db->pErr==0 ); z = (char*)sqlite3_value_text(db->pErr); assert( !db->mallocFailed ); if( z==0 ){ z = sqlite3ErrStr(db->errCode); } } sqlite3_mutex_leave(db->mutex); return z; } #ifndef SQLITE_OMIT_UTF16 /* ** Return UTF-16 encoded English language explanation of the most recent ** error. */ SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ static const u16 outOfMem[] = { 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 }; static const u16 misuse[] = { 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 'c', 'a', 'l', 'l', 'e', 'd', ' ', 'o', 'u', 't', ' ', 'o', 'f', ' ', 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 }; const void *z; if( !db ){ return (void *)outOfMem; } if( !sqlite3SafetyCheckSickOrOk(db) ){ return (void *)misuse; } sqlite3_mutex_enter(db->mutex); if( db->mallocFailed ){ z = (void *)outOfMem; }else{ z = sqlite3_value_text16(db->pErr); if( z==0 ){ sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode)); z = sqlite3_value_text16(db->pErr); } /* A malloc() may have failed within the call to sqlite3_value_text16() ** above. If this is the case, then the db->mallocFailed flag needs to ** be cleared before returning. Do this directly, instead of via ** sqlite3ApiExit(), to avoid setting the database handle error message. */ sqlite3OomClear(db); } sqlite3_mutex_leave(db->mutex); return z; } #endif /* SQLITE_OMIT_UTF16 */ /* ** Return the most recent error code generated by an SQLite routine. If NULL is ** passed to this function, we assume a malloc() failed during sqlite3_open(). */ SQLITE_API int sqlite3_errcode(sqlite3 *db){ if( db && !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } if( !db || db->mallocFailed ){ return SQLITE_NOMEM_BKPT; } return db->errCode & db->errMask; } SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){ if( db && !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } if( !db || db->mallocFailed ){ return SQLITE_NOMEM_BKPT; } return db->errCode; } SQLITE_API int sqlite3_system_errno(sqlite3 *db){ return db ? db->iSysErrno : 0; } /* ** Return a string that describes the kind of error specified in the ** argument. For now, this simply calls the internal sqlite3ErrStr() ** function. */ SQLITE_API const char *sqlite3_errstr(int rc){ return sqlite3ErrStr(rc); } /* ** Create a new collating function for database "db". The name is zName ** and the encoding is enc. */ static int createCollation( sqlite3* db, const char *zName, u8 enc, void* pCtx, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDel)(void*) ){ CollSeq *pColl; int enc2; assert( sqlite3_mutex_held(db->mutex) ); /* If SQLITE_UTF16 is specified as the encoding type, transform this ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. */ enc2 = enc; testcase( enc2==SQLITE_UTF16 ); testcase( enc2==SQLITE_UTF16_ALIGNED ); if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ enc2 = SQLITE_UTF16NATIVE; } if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){ return SQLITE_MISUSE_BKPT; } /* Check if this call is removing or replacing an existing collation ** sequence. If so, and there are active VMs, return busy. If there ** are no active VMs, invalidate any pre-compiled statements. */ pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); if( pColl && pColl->xCmp ){ if( db->nVdbeActive ){ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to delete/modify collation sequence due to active statements"); return SQLITE_BUSY; } sqlite3ExpirePreparedStatements(db); /* If collation sequence pColl was created directly by a call to ** sqlite3_create_collation, and not generated by synthCollSeq(), ** then any copies made by synthCollSeq() need to be invalidated. ** Also, collation destructor - CollSeq.xDel() - function may need ** to be called. */ if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName); int j; for(j=0; j<3; j++){ CollSeq *p = &aColl[j]; if( p->enc==pColl->enc ){ if( p->xDel ){ p->xDel(p->pUser); } p->xCmp = 0; } } } } pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); if( pColl==0 ) return SQLITE_NOMEM_BKPT; pColl->xCmp = xCompare; pColl->pUser = pCtx; pColl->xDel = xDel; pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); sqlite3Error(db, SQLITE_OK); return SQLITE_OK; } /* ** This array defines hard upper bounds on limit values. The ** initializer must be kept in sync with the SQLITE_LIMIT_* ** #defines in sqlite3.h. */ static const int aHardLimit[] = { SQLITE_MAX_LENGTH, SQLITE_MAX_SQL_LENGTH, SQLITE_MAX_COLUMN, SQLITE_MAX_EXPR_DEPTH, SQLITE_MAX_COMPOUND_SELECT, SQLITE_MAX_VDBE_OP, SQLITE_MAX_FUNCTION_ARG, SQLITE_MAX_ATTACHED, SQLITE_MAX_LIKE_PATTERN_LENGTH, SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */ SQLITE_MAX_TRIGGER_DEPTH, SQLITE_MAX_WORKER_THREADS, }; /* ** Make sure the hard limits are set to reasonable values */ #if SQLITE_MAX_LENGTH<100 # error SQLITE_MAX_LENGTH must be at least 100 #endif #if SQLITE_MAX_SQL_LENGTH<100 # error SQLITE_MAX_SQL_LENGTH must be at least 100 #endif #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH #endif #if SQLITE_MAX_COMPOUND_SELECT<2 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2 #endif #if SQLITE_MAX_VDBE_OP<40 # error SQLITE_MAX_VDBE_OP must be at least 40 #endif #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127 #endif #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125 # error SQLITE_MAX_ATTACHED must be between 0 and 125 #endif #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 #endif #if SQLITE_MAX_COLUMN>32767 # error SQLITE_MAX_COLUMN must not exceed 32767 #endif #if SQLITE_MAX_TRIGGER_DEPTH<1 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 #endif #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50 #endif /* ** Change the value of a limit. Report the old value. ** If an invalid limit index is supplied, report -1. ** Make no changes but still report the old value if the ** new limit is negative. ** ** A new lower limit does not shrink existing constructs. ** It merely prevents new constructs that exceed the limit ** from forming. */ SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ int oldLimit; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return -1; } #endif /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME ** there is a hard upper bound set at compile-time by a C preprocessor ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to ** "_MAX_".) */ assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== SQLITE_MAX_LIKE_PATTERN_LENGTH ); assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS ); assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) ); if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ return -1; } oldLimit = db->aLimit[limitId]; if( newLimit>=0 ){ /* IMP: R-52476-28732 */ if( newLimit>aHardLimit[limitId] ){ newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ } db->aLimit[limitId] = newLimit; } return oldLimit; /* IMP: R-53341-35419 */ } /* ** This function is used to parse both URIs and non-URI filenames passed by the ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database ** URIs specified as part of ATTACH statements. ** ** The first argument to this function is the name of the VFS to use (or ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" ** query parameter. The second argument contains the URI (or non-URI filename) ** itself. When this function is called the *pFlags variable should contain ** the default flags to open the database handle with. The value stored in ** *pFlags may be updated before returning if the URI filename contains ** "cache=xxx" or "mode=xxx" query parameters. ** ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to ** the VFS that should be used to open the database file. *pzFile is set to ** point to a buffer containing the name of the file to open. It is the ** responsibility of the caller to eventually call sqlite3_free() to release ** this buffer. ** ** If an error occurs, then an SQLite error code is returned and *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to eventually release ** this buffer by calling sqlite3_free(). */ SQLITE_PRIVATE int sqlite3ParseUri( const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ const char *zUri, /* Nul-terminated URI to parse */ unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ sqlite3_vfs **ppVfs, /* OUT: VFS to use */ char **pzFile, /* OUT: Filename component of URI */ char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ ){ int rc = SQLITE_OK; unsigned int flags = *pFlags; const char *zVfs = zDefaultVfs; char *zFile; char c; int nUri = sqlite3Strlen30(zUri); assert( *pzErrMsg==0 ); if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */ || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */ && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */ ){ char *zOpt; int eState; /* Parser state when parsing URI */ int iIn; /* Input character index */ int iOut = 0; /* Output character index */ u64 nByte = nUri+2; /* Bytes of space to allocate */ /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen ** method that there may be extra parameters following the file-name. */ flags |= SQLITE_OPEN_URI; for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&'); zFile = sqlite3_malloc64(nByte); if( !zFile ) return SQLITE_NOMEM_BKPT; iIn = 5; #ifdef SQLITE_ALLOW_URI_AUTHORITY if( strncmp(zUri+5, "///", 3)==0 ){ iIn = 7; /* The following condition causes URIs with five leading / characters ** like file://///host/path to be converted into UNCs like //host/path. ** The correct URI for that UNC has only two or four leading / characters ** file://host/path or file:////host/path. But 5 leading slashes is a ** common error, we are told, so we handle it as a special case. */ if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; } }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){ iIn = 16; } #else /* Discard the scheme and authority segments of the URI. */ if( zUri[5]=='/' && zUri[6]=='/' ){ iIn = 7; while( zUri[iIn] && zUri[iIn]!='/' ) iIn++; if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){ *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", iIn-7, &zUri[7]); rc = SQLITE_ERROR; goto parse_uri_out; } } #endif /* Copy the filename and any query parameters into the zFile buffer. ** Decode %HH escape codes along the way. ** ** Within this loop, variable eState may be set to 0, 1 or 2, depending ** on the parsing context. As follows: ** ** 0: Parsing file-name. ** 1: Parsing name section of a name=value query parameter. ** 2: Parsing value section of a name=value query parameter. */ eState = 0; while( (c = zUri[iIn])!=0 && c!='#' ){ iIn++; if( c=='%' && sqlite3Isxdigit(zUri[iIn]) && sqlite3Isxdigit(zUri[iIn+1]) ){ int octet = (sqlite3HexToInt(zUri[iIn++]) << 4); octet += sqlite3HexToInt(zUri[iIn++]); assert( octet>=0 && octet<256 ); if( octet==0 ){ #ifndef SQLITE_ENABLE_URI_00_ERROR /* This branch is taken when "%00" appears within the URI. In this ** case we ignore all text in the remainder of the path, name or ** value currently being parsed. So ignore the current character ** and skip to the next "?", "=" or "&", as appropriate. */ while( (c = zUri[iIn])!=0 && c!='#' && (eState!=0 || c!='?') && (eState!=1 || (c!='=' && c!='&')) && (eState!=2 || c!='&') ){ iIn++; } continue; #else /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */ *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri"); rc = SQLITE_ERROR; goto parse_uri_out; #endif } c = octet; }else if( eState==1 && (c=='&' || c=='=') ){ if( zFile[iOut-1]==0 ){ /* An empty option name. Ignore this option altogether. */ while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; continue; } if( c=='&' ){ zFile[iOut++] = '\0'; }else{ eState = 2; } c = 0; }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ c = 0; eState = 1; } zFile[iOut++] = c; } if( eState==1 ) zFile[iOut++] = '\0'; zFile[iOut++] = '\0'; zFile[iOut++] = '\0'; /* Check if there were any options specified that should be interpreted ** here. Options that are interpreted here include "vfs" and those that ** correspond to flags that may be passed to the sqlite3_open_v2() ** method. */ zOpt = &zFile[sqlite3Strlen30(zFile)+1]; while( zOpt[0] ){ int nOpt = sqlite3Strlen30(zOpt); char *zVal = &zOpt[nOpt+1]; int nVal = sqlite3Strlen30(zVal); if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ zVfs = zVal; }else{ struct OpenMode { const char *z; int mode; } *aMode = 0; char *zModeType = 0; int mask = 0; int limit = 0; if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ static struct OpenMode aCacheMode[] = { { "shared", SQLITE_OPEN_SHAREDCACHE }, { "private", SQLITE_OPEN_PRIVATECACHE }, { 0, 0 } }; mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; aMode = aCacheMode; limit = mask; zModeType = "cache"; } if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ static struct OpenMode aOpenMode[] = { { "ro", SQLITE_OPEN_READONLY }, { "rw", SQLITE_OPEN_READWRITE }, { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, { "memory", SQLITE_OPEN_MEMORY }, { 0, 0 } }; mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; aMode = aOpenMode; limit = mask & flags; zModeType = "access"; } if( aMode ){ int i; int mode = 0; for(i=0; aMode[i].z; i++){ const char *z = aMode[i].z; if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ mode = aMode[i].mode; break; } } if( mode==0 ){ *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); rc = SQLITE_ERROR; goto parse_uri_out; } if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", zModeType, zVal); rc = SQLITE_PERM; goto parse_uri_out; } flags = (flags & ~mask) | mode; } } zOpt = &zVal[nVal+1]; } }else{ zFile = sqlite3_malloc64(nUri+2); if( !zFile ) return SQLITE_NOMEM_BKPT; if( nUri ){ memcpy(zFile, zUri, nUri); } zFile[nUri] = '\0'; zFile[nUri+1] = '\0'; flags &= ~SQLITE_OPEN_URI; } *ppVfs = sqlite3_vfs_find(zVfs); if( *ppVfs==0 ){ *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); rc = SQLITE_ERROR; } parse_uri_out: if( rc!=SQLITE_OK ){ sqlite3_free(zFile); zFile = 0; } *pFlags = flags; *pzFile = zFile; return rc; } /* ** This routine does the work of opening a database on behalf of ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" ** is UTF-8 encoded. */ static int openDatabase( const char *zFilename, /* Database filename UTF-8 encoded */ sqlite3 **ppDb, /* OUT: Returned database handle */ unsigned int flags, /* Operational flags */ const char *zVfs /* Name of the VFS to use */ ){ sqlite3 *db; /* Store allocated handle here */ int rc; /* Return code */ int isThreadsafe; /* True for threadsafe connections */ char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ #ifdef SQLITE_ENABLE_API_ARMOR if( ppDb==0 ) return SQLITE_MISUSE_BKPT; #endif *ppDb = 0; #ifndef SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc ) return rc; #endif /* Only allow sensible combinations of bits in the flags argument. ** Throw an error if any non-sense combination is used. If we ** do not block illegal combinations here, it could trigger ** assert() statements in deeper layers. Sensible combinations ** are: ** ** 1: SQLITE_OPEN_READONLY ** 2: SQLITE_OPEN_READWRITE ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE */ assert( SQLITE_OPEN_READONLY == 0x01 ); assert( SQLITE_OPEN_READWRITE == 0x02 ); assert( SQLITE_OPEN_CREATE == 0x04 ); testcase( (1<<(flags&7))==0x02 ); /* READONLY */ testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ if( ((1<<(flags&7)) & 0x46)==0 ){ return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */ } if( sqlite3GlobalConfig.bCoreMutex==0 ){ isThreadsafe = 0; }else if( flags & SQLITE_OPEN_NOMUTEX ){ isThreadsafe = 0; }else if( flags & SQLITE_OPEN_FULLMUTEX ){ isThreadsafe = 1; }else{ isThreadsafe = sqlite3GlobalConfig.bFullMutex; } if( flags & SQLITE_OPEN_PRIVATECACHE ){ flags &= ~SQLITE_OPEN_SHAREDCACHE; }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ flags |= SQLITE_OPEN_SHAREDCACHE; } /* Remove harmful bits from the flags parameter ** ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were ** dealt with in the previous code block. Besides these, the only ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask ** off all other flags. */ flags &= ~( SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_TRANSIENT_DB | SQLITE_OPEN_MAIN_JOURNAL | SQLITE_OPEN_TEMP_JOURNAL | SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_MASTER_JOURNAL | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_WAL ); /* Allocate the sqlite data structure */ db = sqlite3MallocZero( sizeof(sqlite3) ); if( db==0 ) goto opendb_out; if( isThreadsafe ){ db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); if( db->mutex==0 ){ sqlite3_free(db); db = 0; goto opendb_out; } } sqlite3_mutex_enter(db->mutex); db->errMask = 0xff; db->nDb = 2; db->magic = SQLITE_MAGIC_BUSY; db->aDb = db->aDbStatic; assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; db->autoCommit = 1; db->nextAutovac = -1; db->szMmap = sqlite3GlobalConfig.szMmap; db->nextPagesize = 0; db->nMaxSorterMmap = 0x7FFFFFFF; db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX | SQLITE_AutoIndex #endif #if SQLITE_DEFAULT_CKPTFULLFSYNC | SQLITE_CkptFullFSync #endif #if SQLITE_DEFAULT_FILE_FORMAT<4 | SQLITE_LegacyFileFmt #endif #ifdef SQLITE_ENABLE_LOAD_EXTENSION | SQLITE_LoadExtension #endif #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS | SQLITE_RecTriggers #endif #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS | SQLITE_ForeignKeys #endif #if defined(SQLITE_REVERSE_UNORDERED_SELECTS) | SQLITE_ReverseOrder #endif #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) | SQLITE_CellSizeCk #endif #if defined(SQLITE_ENABLE_FTS3_TOKENIZER) | SQLITE_Fts3Tokenizer #endif ; sqlite3HashInit(&db->aCollSeq); #ifndef SQLITE_OMIT_VIRTUALTABLE sqlite3HashInit(&db->aModule); #endif /* Add the default collation sequence BINARY. BINARY works for both UTF-8 ** and UTF-16, so add a version for each to avoid any unnecessary ** conversions. The only error that can occur here is a malloc() failure. ** ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating ** functions: */ createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0); createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0); createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0); createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); if( db->mallocFailed ){ goto opendb_out; } /* EVIDENCE-OF: R-08308-17224 The default collating function for all ** strings is BINARY. */ db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0); assert( db->pDfltColl!=0 ); /* Parse the filename/URI argument. */ db->openFlags = flags; rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); sqlite3_free(zErrMsg); goto opendb_out; } /* Open the backend database driver */ rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, flags | SQLITE_OPEN_MAIN_DB); if( rc!=SQLITE_OK ){ if( rc==SQLITE_IOERR_NOMEM ){ rc = SQLITE_NOMEM_BKPT; } sqlite3Error(db, rc); goto opendb_out; } sqlite3BtreeEnter(db->aDb[0].pBt); db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db); sqlite3BtreeLeave(db->aDb[0].pBt); db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); /* The default safety_level for the main database is FULL; for the temp ** database it is OFF. This matches the pager layer defaults. */ db->aDb[0].zDbSName = "main"; db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; db->aDb[1].zDbSName = "temp"; db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF; db->magic = SQLITE_MAGIC_OPEN; if( db->mallocFailed ){ goto opendb_out; } /* Register all built-in functions, but do not attempt to read the ** database schema yet. This is delayed until the first time the database ** is accessed. */ sqlite3Error(db, SQLITE_OK); sqlite3RegisterPerConnectionBuiltinFunctions(db); rc = sqlite3_errcode(db); #ifdef SQLITE_ENABLE_FTS5 /* Register any built-in FTS5 module before loading the automatic ** extensions. This allows automatic extensions to register FTS5 ** tokenizers and auxiliary functions. */ if( !db->mallocFailed && rc==SQLITE_OK ){ rc = sqlite3Fts5Init(db); } #endif /* Load automatic extensions - extensions that have been registered ** using the sqlite3_automatic_extension() API. */ if( rc==SQLITE_OK ){ sqlite3AutoLoadExtensions(db); rc = sqlite3_errcode(db); if( rc!=SQLITE_OK ){ goto opendb_out; } } #ifdef SQLITE_ENABLE_FTS1 if( !db->mallocFailed ){ extern int sqlite3Fts1Init(sqlite3*); rc = sqlite3Fts1Init(db); } #endif #ifdef SQLITE_ENABLE_FTS2 if( !db->mallocFailed && rc==SQLITE_OK ){ extern int sqlite3Fts2Init(sqlite3*); rc = sqlite3Fts2Init(db); } #endif #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */ if( !db->mallocFailed && rc==SQLITE_OK ){ rc = sqlite3Fts3Init(db); } #endif #ifdef SQLITE_ENABLE_ICU if( !db->mallocFailed && rc==SQLITE_OK ){ rc = sqlite3IcuInit(db); } #endif #ifdef SQLITE_ENABLE_RTREE if( !db->mallocFailed && rc==SQLITE_OK){ rc = sqlite3RtreeInit(db); } #endif #ifdef SQLITE_ENABLE_DBSTAT_VTAB if( !db->mallocFailed && rc==SQLITE_OK){ rc = sqlite3DbstatRegister(db); } #endif #ifdef SQLITE_ENABLE_JSON1 if( !db->mallocFailed && rc==SQLITE_OK){ rc = sqlite3Json1Init(db); } #endif /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking ** mode. Doing nothing at all also makes NORMAL the default. */ #ifdef SQLITE_DEFAULT_LOCKING_MODE db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), SQLITE_DEFAULT_LOCKING_MODE); #endif if( rc ) sqlite3Error(db, rc); /* Enable the lookaside-malloc subsystem */ setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, sqlite3GlobalConfig.nLookaside); sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); opendb_out: if( db ){ assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 ); sqlite3_mutex_leave(db->mutex); } rc = sqlite3_errcode(db); assert( db!=0 || rc==SQLITE_NOMEM ); if( rc==SQLITE_NOMEM ){ sqlite3_close(db); db = 0; }else if( rc!=SQLITE_OK ){ db->magic = SQLITE_MAGIC_SICK; } *ppDb = db; #ifdef SQLITE_ENABLE_SQLLOG if( sqlite3GlobalConfig.xSqllog ){ /* Opening a db handle. Fourth parameter is passed 0. */ void *pArg = sqlite3GlobalConfig.pSqllogArg; sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); } #endif #if defined(SQLITE_HAS_CODEC) if( rc==SQLITE_OK ){ const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey"); if( zHexKey && zHexKey[0] ){ u8 iByte; int i; char zKey[40]; for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){ iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]); if( (i&1)!=0 ) zKey[i/2] = iByte; } sqlite3_key_v2(db, 0, zKey, i/2); } } #endif sqlite3_free(zOpen); return rc & 0xff; } /* ** Open a new database handle. */ SQLITE_API int sqlite3_open( const char *zFilename, sqlite3 **ppDb ){ return openDatabase(zFilename, ppDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); } SQLITE_API int sqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ){ return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); } #ifndef SQLITE_OMIT_UTF16 /* ** Open a new database handle. */ SQLITE_API int sqlite3_open16( const void *zFilename, sqlite3 **ppDb ){ char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ sqlite3_value *pVal; int rc; #ifdef SQLITE_ENABLE_API_ARMOR if( ppDb==0 ) return SQLITE_MISUSE_BKPT; #endif *ppDb = 0; #ifndef SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc ) return rc; #endif if( zFilename==0 ) zFilename = "\000\000"; pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zFilename8 ){ rc = openDatabase(zFilename8, ppDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); assert( *ppDb || rc==SQLITE_NOMEM ); if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE; } }else{ rc = SQLITE_NOMEM_BKPT; } sqlite3ValueFree(pVal); return rc & 0xff; } #endif /* SQLITE_OMIT_UTF16 */ /* ** Register a new collation sequence with the database handle db. */ SQLITE_API int sqlite3_create_collation( sqlite3* db, const char *zName, int enc, void* pCtx, int(*xCompare)(void*,int,const void*,int,const void*) ){ return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0); } /* ** Register a new collation sequence with the database handle db. */ SQLITE_API int sqlite3_create_collation_v2( sqlite3* db, const char *zName, int enc, void* pCtx, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDel)(void*) ){ int rc; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #ifndef SQLITE_OMIT_UTF16 /* ** Register a new collation sequence with the database handle db. */ SQLITE_API int sqlite3_create_collation16( sqlite3* db, const void *zName, int enc, void* pCtx, int(*xCompare)(void*,int,const void*,int,const void*) ){ int rc = SQLITE_OK; char *zName8; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); if( zName8 ){ rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); sqlite3DbFree(db, zName8); } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } #endif /* SQLITE_OMIT_UTF16 */ /* ** Register a collation sequence factory callback with the database handle ** db. Replace any previously installed collation sequence factory. */ SQLITE_API int sqlite3_collation_needed( sqlite3 *db, void *pCollNeededArg, void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->xCollNeeded = xCollNeeded; db->xCollNeeded16 = 0; db->pCollNeededArg = pCollNeededArg; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_UTF16 /* ** Register a collation sequence factory callback with the database handle ** db. Replace any previously installed collation sequence factory. */ SQLITE_API int sqlite3_collation_needed16( sqlite3 *db, void *pCollNeededArg, void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->xCollNeeded = 0; db->xCollNeeded16 = xCollNeeded16; db->pCollNeededArg = pCollNeededArg; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #endif /* SQLITE_OMIT_UTF16 */ #ifndef SQLITE_OMIT_DEPRECATED /* ** This function is now an anachronism. It used to be used to recover from a ** malloc() failure, but SQLite now does this automatically. */ SQLITE_API int sqlite3_global_recover(void){ return SQLITE_OK; } #endif /* ** Test to see whether or not the database connection is in autocommit ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on ** by default. Autocommit is disabled by a BEGIN statement and reenabled ** by the next COMMIT or ROLLBACK. */ SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif return db->autoCommit; } /* ** The following routines are substitutes for constants SQLITE_CORRUPT, ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error ** constants. They serve two purposes: ** ** 1. Serve as a convenient place to set a breakpoint in a debugger ** to detect when version error conditions occurs. ** ** 2. Invoke sqlite3_log() to provide the source code location where ** a low-level error is first detected. */ static int reportError(int iErr, int lineno, const char *zType){ sqlite3_log(iErr, "%s at line %d of [%.10s]", zType, lineno, 20+sqlite3_sourceid()); return iErr; } SQLITE_PRIVATE int sqlite3CorruptError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_CORRUPT, lineno, "database corruption"); } SQLITE_PRIVATE int sqlite3MisuseError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_MISUSE, lineno, "misuse"); } SQLITE_PRIVATE int sqlite3CantopenError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_CANTOPEN, lineno, "cannot open file"); } #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3NomemError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_NOMEM, lineno, "OOM"); } SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){ testcase( sqlite3GlobalConfig.xLog!=0 ); return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error"); } #endif #ifndef SQLITE_OMIT_DEPRECATED /* ** This is a convenience routine that makes sure that all thread-specific ** data for this thread has been deallocated. ** ** SQLite no longer uses thread-specific data so this routine is now a ** no-op. It is retained for historical compatibility. */ SQLITE_API void sqlite3_thread_cleanup(void){ } #endif /* ** Return meta information about a specific column of a database table. ** See comment in sqlite3.h (sqlite.h.in) for details. */ SQLITE_API int sqlite3_table_column_metadata( sqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ char const **pzDataType, /* OUTPUT: Declared data type */ char const **pzCollSeq, /* OUTPUT: Collation sequence name */ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ int *pAutoinc /* OUTPUT: True if column is auto-increment */ ){ int rc; char *zErrMsg = 0; Table *pTab = 0; Column *pCol = 0; int iCol = 0; char const *zDataType = 0; char const *zCollSeq = 0; int notnull = 0; int primarykey = 0; int autoinc = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){ return SQLITE_MISUSE_BKPT; } #endif /* Ensure the database schema has been loaded */ sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, &zErrMsg); if( SQLITE_OK!=rc ){ goto error_out; } /* Locate the table in question */ pTab = sqlite3FindTable(db, zTableName, zDbName); if( !pTab || pTab->pSelect ){ pTab = 0; goto error_out; } /* Find the column for which info is requested */ if( zColumnName==0 ){ /* Query for existance of table only */ }else{ for(iCol=0; iCol<pTab->nCol; iCol++){ pCol = &pTab->aCol[iCol]; if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ break; } } if( iCol==pTab->nCol ){ if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){ iCol = pTab->iPKey; pCol = iCol>=0 ? &pTab->aCol[iCol] : 0; }else{ pTab = 0; goto error_out; } } } /* The following block stores the meta information that will be returned ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey ** and autoinc. At this point there are two possibilities: ** ** 1. The specified column name was rowid", "oid" or "_rowid_" ** and there is no explicitly declared IPK column. ** ** 2. The table is not a view and the column name identified an ** explicitly declared column. Copy meta information from *pCol. */ if( pCol ){ zDataType = sqlite3ColumnType(pCol,0); zCollSeq = pCol->zColl; notnull = pCol->notNull!=0; primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; }else{ zDataType = "INTEGER"; primarykey = 1; } if( !zCollSeq ){ zCollSeq = sqlite3StrBINARY; } error_out: sqlite3BtreeLeaveAll(db); /* Whether the function call succeeded or failed, set the output parameters ** to whatever their local counterparts contain. If an error did occur, ** this has the effect of zeroing all output parameters. */ if( pzDataType ) *pzDataType = zDataType; if( pzCollSeq ) *pzCollSeq = zCollSeq; if( pNotNull ) *pNotNull = notnull; if( pPrimaryKey ) *pPrimaryKey = primarykey; if( pAutoinc ) *pAutoinc = autoinc; if( SQLITE_OK==rc && !pTab ){ sqlite3DbFree(db, zErrMsg); zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, zColumnName); rc = SQLITE_ERROR; } sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); sqlite3DbFree(db, zErrMsg); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Sleep for a little while. Return the amount of time slept. */ SQLITE_API int sqlite3_sleep(int ms){ sqlite3_vfs *pVfs; int rc; pVfs = sqlite3_vfs_find(0); if( pVfs==0 ) return 0; /* This function works in milliseconds, but the underlying OsSleep() ** API uses microseconds. Hence the 1000's. */ rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); return rc; } /* ** Enable or disable the extended result codes. */ SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); db->errMask = onoff ? 0xffffffff : 0xff; sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Invoke the xFileControl method on a particular database. */ SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ int rc = SQLITE_ERROR; Btree *pBtree; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif sqlite3_mutex_enter(db->mutex); pBtree = sqlite3DbNameToBtree(db, zDbName); if( pBtree ){ Pager *pPager; sqlite3_file *fd; sqlite3BtreeEnter(pBtree); pPager = sqlite3BtreePager(pBtree); assert( pPager!=0 ); fd = sqlite3PagerFile(pPager); assert( fd!=0 ); if( op==SQLITE_FCNTL_FILE_POINTER ){ *(sqlite3_file**)pArg = fd; rc = SQLITE_OK; }else if( op==SQLITE_FCNTL_VFS_POINTER ){ *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager); rc = SQLITE_OK; }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){ *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager); rc = SQLITE_OK; }else if( fd->pMethods ){ rc = sqlite3OsFileControl(fd, op, pArg); }else{ rc = SQLITE_NOTFOUND; } sqlite3BtreeLeave(pBtree); } sqlite3_mutex_leave(db->mutex); return rc; } /* ** Interface to the testing logic. */ SQLITE_API int sqlite3_test_control(int op, ...){ int rc = 0; #ifdef SQLITE_UNTESTABLE UNUSED_PARAMETER(op); #else va_list ap; va_start(ap, op); switch( op ){ /* ** Save the current state of the PRNG. */ case SQLITE_TESTCTRL_PRNG_SAVE: { sqlite3PrngSaveState(); break; } /* ** Restore the state of the PRNG to the last state saved using ** PRNG_SAVE. If PRNG_SAVE has never before been called, then ** this verb acts like PRNG_RESET. */ case SQLITE_TESTCTRL_PRNG_RESTORE: { sqlite3PrngRestoreState(); break; } /* ** Reset the PRNG back to its uninitialized state. The next call ** to sqlite3_randomness() will reseed the PRNG using a single call ** to the xRandomness method of the default VFS. */ case SQLITE_TESTCTRL_PRNG_RESET: { sqlite3_randomness(0,0); break; } /* ** sqlite3_test_control(BITVEC_TEST, size, program) ** ** Run a test against a Bitvec object of size. The program argument ** is an array of integers that defines the test. Return -1 on a ** memory allocation error, 0 on success, or non-zero for an error. ** See the sqlite3BitvecBuiltinTest() for additional information. */ case SQLITE_TESTCTRL_BITVEC_TEST: { int sz = va_arg(ap, int); int *aProg = va_arg(ap, int*); rc = sqlite3BitvecBuiltinTest(sz, aProg); break; } /* ** sqlite3_test_control(FAULT_INSTALL, xCallback) ** ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called, ** if xCallback is not NULL. ** ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0) ** is called immediately after installing the new callback and the return ** value from sqlite3FaultSim(0) becomes the return from ** sqlite3_test_control(). */ case SQLITE_TESTCTRL_FAULT_INSTALL: { /* MSVC is picky about pulling func ptrs from va lists. ** http://support.microsoft.com/kb/47961 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); */ typedef int(*TESTCALLBACKFUNC_t)(int); sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); rc = sqlite3FaultSim(0); break; } /* ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) ** ** Register hooks to call to indicate which malloc() failures ** are benign. */ case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { typedef void (*void_function)(void); void_function xBenignBegin; void_function xBenignEnd; xBenignBegin = va_arg(ap, void_function); xBenignEnd = va_arg(ap, void_function); sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) ** ** Set the PENDING byte to the value in the argument, if X>0. ** Make no changes if X==0. Return the value of the pending byte ** as it existing before this routine was called. ** ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in ** an incompatible database file format. Changing the PENDING byte ** while any database connection is open results in undefined and ** deleterious behavior. */ case SQLITE_TESTCTRL_PENDING_BYTE: { rc = PENDING_BYTE; #ifndef SQLITE_OMIT_WSD { unsigned int newVal = va_arg(ap, unsigned int); if( newVal ) sqlite3PendingByte = newVal; } #endif break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) ** ** This action provides a run-time test to see whether or not ** assert() was enabled at compile-time. If X is true and assert() ** is enabled, then the return value is true. If X is true and ** assert() is disabled, then the return value is zero. If X is ** false and assert() is enabled, then the assertion fires and the ** process aborts. If X is false and assert() is disabled, then the ** return value is zero. */ case SQLITE_TESTCTRL_ASSERT: { volatile int x = 0; assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 ); rc = x; break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) ** ** This action provides a run-time test to see how the ALWAYS and ** NEVER macros were defined at compile-time. ** ** The return value is ALWAYS(X). ** ** The recommended test is X==2. If the return value is 2, that means ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the ** default setting. If the return value is 1, then ALWAYS() is either ** hard-coded to true or else it asserts if its argument is false. ** The first behavior (hard-coded to true) is the case if ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second ** behavior (assert if the argument to ALWAYS() is false) is the case if ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. ** ** The run-time test procedure might look something like this: ** ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ ** // ALWAYS() and NEVER() are no-op pass-through macros ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. ** }else{ ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. ** } */ case SQLITE_TESTCTRL_ALWAYS: { int x = va_arg(ap,int); rc = ALWAYS(x); break; } /* ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); ** ** The integer returned reveals the byte-order of the computer on which ** SQLite is running: ** ** 1 big-endian, determined at run-time ** 10 little-endian, determined at run-time ** 432101 big-endian, determined at compile-time ** 123410 little-endian, determined at compile-time */ case SQLITE_TESTCTRL_BYTEORDER: { rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN; break; } /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) ** ** Set the nReserve size to N for the main database on the database ** connection db. */ case SQLITE_TESTCTRL_RESERVE: { sqlite3 *db = va_arg(ap, sqlite3*); int x = va_arg(ap,int); sqlite3_mutex_enter(db->mutex); sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); sqlite3_mutex_leave(db->mutex); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) ** ** Enable or disable various optimizations for testing purposes. The ** argument N is a bitmask of optimizations to be disabled. For normal ** operation N should be 0. The idea is that a test program (like the ** SQL Logic Test or SLT test module) can run the same SQL multiple times ** with various optimizations disabled to verify that the same answer ** is obtained in every case. */ case SQLITE_TESTCTRL_OPTIMIZATIONS: { sqlite3 *db = va_arg(ap, sqlite3*); db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); break; } #ifdef SQLITE_N_KEYWORD /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) ** ** If zWord is a keyword recognized by the parser, then return the ** number of keywords. Or if zWord is not a keyword, return 0. ** ** This test feature is only available in the amalgamation since ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite ** is built using separate source files. */ case SQLITE_TESTCTRL_ISKEYWORD: { const char *zWord = va_arg(ap, const char*); int n = sqlite3Strlen30(zWord); rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; break; } #endif /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); ** ** Pass pFree into sqlite3ScratchFree(). ** If sz>0 then allocate a scratch buffer into pNew. */ case SQLITE_TESTCTRL_SCRATCHMALLOC: { void *pFree, **ppNew; int sz; sz = va_arg(ap, int); ppNew = va_arg(ap, void**); pFree = va_arg(ap, void*); if( sz ) *ppNew = sqlite3ScratchMalloc(sz); sqlite3ScratchFree(pFree); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); ** ** If parameter onoff is non-zero, configure the wrappers so that all ** subsequent calls to localtime() and variants fail. If onoff is zero, ** undo this setting. */ case SQLITE_TESTCTRL_LOCALTIME_FAULT: { sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); ** ** Set or clear a flag that indicates that the database file is always well- ** formed and never corrupt. This flag is clear by default, indicating that ** database files might have arbitrary corruption. Setting the flag during ** testing causes certain assert() statements in the code to be activated ** that demonstrat invariants on well-formed database files. */ case SQLITE_TESTCTRL_NEVER_CORRUPT: { sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); break; } /* Set the threshold at which OP_Once counters reset back to zero. ** By default this is 0x7ffffffe (over 2 billion), but that value is ** too big to test in a reasonable amount of time, so this control is ** provided to set a small and easily reachable reset value. */ case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: { sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); ** ** Set the VDBE coverage callback function to xCallback with context ** pointer ptr. */ case SQLITE_TESTCTRL_VDBE_COVERAGE: { #ifdef SQLITE_VDBE_COVERAGE typedef void (*branch_callback)(void*,int,u8,u8); sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); #endif break; } /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ case SQLITE_TESTCTRL_SORTER_MMAP: { sqlite3 *db = va_arg(ap, sqlite3*); db->nMaxSorterMmap = va_arg(ap, int); break; } /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT); ** ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if ** not. */ case SQLITE_TESTCTRL_ISINIT: { if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; break; } /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); ** ** This test control is used to create imposter tables. "db" is a pointer ** to the database connection. dbName is the database name (ex: "main" or ** "temp") which will receive the imposter. "onOff" turns imposter mode on ** or off. "tnum" is the root page of the b-tree to which the imposter ** table should connect. ** ** Enable imposter mode only when the schema has already been parsed. Then ** run a single CREATE TABLE statement to construct the imposter table in ** the parsed schema. Then turn imposter mode back off again. ** ** If onOff==0 and tnum>0 then reset the schema for all databases, causing ** the schema to be reparsed the next time it is needed. This has the ** effect of erasing all imposter tables. */ case SQLITE_TESTCTRL_IMPOSTER: { sqlite3 *db = va_arg(ap, sqlite3*); sqlite3_mutex_enter(db->mutex); db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*)); db->init.busy = db->init.imposterTable = va_arg(ap,int); db->init.newTnum = va_arg(ap,int); if( db->init.busy==0 && db->init.newTnum>0 ){ sqlite3ResetAllSchemasOfConnection(db); } sqlite3_mutex_leave(db->mutex); break; } } va_end(ap); #endif /* SQLITE_UNTESTABLE */ return rc; } /* ** This is a utility routine, useful to VFS implementations, that checks ** to see if a database file was a URI that contained a specific query ** parameter, and if so obtains the value of the query parameter. ** ** The zFilename argument is the filename pointer passed into the xOpen() ** method of a VFS implementation. The zParam argument is the name of the ** query parameter we seek. This routine returns the value of the zParam ** parameter if it exists. If the parameter does not exist, this routine ** returns a NULL pointer. */ SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ if( zFilename==0 || zParam==0 ) return 0; zFilename += sqlite3Strlen30(zFilename) + 1; while( zFilename[0] ){ int x = strcmp(zFilename, zParam); zFilename += sqlite3Strlen30(zFilename) + 1; if( x==0 ) return zFilename; zFilename += sqlite3Strlen30(zFilename) + 1; } return 0; } /* ** Return a boolean value for a query parameter. */ SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ const char *z = sqlite3_uri_parameter(zFilename, zParam); bDflt = bDflt!=0; return z ? sqlite3GetBoolean(z, bDflt) : bDflt; } /* ** Return a 64-bit integer value for a query parameter. */ SQLITE_API sqlite3_int64 sqlite3_uri_int64( const char *zFilename, /* Filename as passed to xOpen */ const char *zParam, /* URI parameter sought */ sqlite3_int64 bDflt /* return if parameter is missing */ ){ const char *z = sqlite3_uri_parameter(zFilename, zParam); sqlite3_int64 v; if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){ bDflt = v; } return bDflt; } /* ** Return the Btree pointer identified by zDbName. Return NULL if not found. */ SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0; return iDb<0 ? 0 : db->aDb[iDb].pBt; } /* ** Return the filename of the database associated with a database ** connection. */ SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ Btree *pBt; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif pBt = sqlite3DbNameToBtree(db, zDbName); return pBt ? sqlite3BtreeGetFilename(pBt) : 0; } /* ** Return 1 if database is read-only or 0 if read/write. Return -1 if ** no such database exists. */ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ Btree *pBt; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return -1; } #endif pBt = sqlite3DbNameToBtree(db, zDbName); return pBt ? sqlite3BtreeIsReadonly(pBt) : -1; } #ifdef SQLITE_ENABLE_SNAPSHOT /* ** Obtain a snapshot handle for the snapshot of database zDb currently ** being read by handle db. */ SQLITE_API int sqlite3_snapshot_get( sqlite3 *db, const char *zDb, sqlite3_snapshot **ppSnapshot ){ int rc = SQLITE_ERROR; #ifndef SQLITE_OMIT_WAL #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( db->autoCommit==0 ){ int iDb = sqlite3FindDbName(db, zDb); if( iDb==0 || iDb>1 ){ Btree *pBt = db->aDb[iDb].pBt; if( 0==sqlite3BtreeIsInTrans(pBt) ){ rc = sqlite3BtreeBeginTrans(pBt, 0); if( rc==SQLITE_OK ){ rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot); } } } } sqlite3_mutex_leave(db->mutex); #endif /* SQLITE_OMIT_WAL */ return rc; } /* ** Open a read-transaction on the snapshot idendified by pSnapshot. */ SQLITE_API int sqlite3_snapshot_open( sqlite3 *db, const char *zDb, sqlite3_snapshot *pSnapshot ){ int rc = SQLITE_ERROR; #ifndef SQLITE_OMIT_WAL #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); if( db->autoCommit==0 ){ int iDb; iDb = sqlite3FindDbName(db, zDb); if( iDb==0 || iDb>1 ){ Btree *pBt = db->aDb[iDb].pBt; if( 0==sqlite3BtreeIsInReadTrans(pBt) ){ rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot); if( rc==SQLITE_OK ){ rc = sqlite3BtreeBeginTrans(pBt, 0); sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0); } } } } sqlite3_mutex_leave(db->mutex); #endif /* SQLITE_OMIT_WAL */ return rc; } /* ** Recover as many snapshots as possible from the wal file associated with ** schema zDb of database db. */ SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){ int rc = SQLITE_ERROR; int iDb; #ifndef SQLITE_OMIT_WAL #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); iDb = sqlite3FindDbName(db, zDb); if( iDb==0 || iDb>1 ){ Btree *pBt = db->aDb[iDb].pBt; if( 0==sqlite3BtreeIsInReadTrans(pBt) ){ rc = sqlite3BtreeBeginTrans(pBt, 0); if( rc==SQLITE_OK ){ rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt)); sqlite3BtreeCommit(pBt); } } } sqlite3_mutex_leave(db->mutex); #endif /* SQLITE_OMIT_WAL */ return rc; } /* ** Free a snapshot handle obtained from sqlite3_snapshot_get(). */ SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){ sqlite3_free(pSnapshot); } #endif /* SQLITE_ENABLE_SNAPSHOT */ /************** End of main.c ************************************************/ /************** Begin file notify.c ******************************************/ /* ** 2009 March 3 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the implementation of the sqlite3_unlock_notify() ** API method and its associated functionality. */ /* #include "sqliteInt.h" */ /* #include "btreeInt.h" */ /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY /* ** Public interfaces: ** ** sqlite3ConnectionBlocked() ** sqlite3ConnectionUnlocked() ** sqlite3ConnectionClosed() ** sqlite3_unlock_notify() */ #define assertMutexHeld() \ assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) /* ** Head of a linked list of all sqlite3 objects created by this process ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection ** is not NULL. This variable may only accessed while the STATIC_MASTER ** mutex is held. */ static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; #ifndef NDEBUG /* ** This function is a complex assert() that verifies the following ** properties of the blocked connections list: ** ** 1) Each entry in the list has a non-NULL value for either ** pUnlockConnection or pBlockingConnection, or both. ** ** 2) All entries in the list that share a common value for ** xUnlockNotify are grouped together. ** ** 3) If the argument db is not NULL, then none of the entries in the ** blocked connections list have pUnlockConnection or pBlockingConnection ** set to db. This is used when closing connection db. */ static void checkListProperties(sqlite3 *db){ sqlite3 *p; for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ int seen = 0; sqlite3 *p2; /* Verify property (1) */ assert( p->pUnlockConnection || p->pBlockingConnection ); /* Verify property (2) */ for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); assert( db==0 || p->pUnlockConnection!=db ); assert( db==0 || p->pBlockingConnection!=db ); } } } #else # define checkListProperties(x) #endif /* ** Remove connection db from the blocked connections list. If connection ** db is not currently a part of the list, this function is a no-op. */ static void removeFromBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ if( *pp==db ){ *pp = (*pp)->pNextBlocked; break; } } } /* ** Add connection db to the blocked connections list. It is assumed ** that it is not already a part of the list. */ static void addToBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for( pp=&sqlite3BlockedList; *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; pp=&(*pp)->pNextBlocked ); db->pNextBlocked = *pp; *pp = db; } /* ** Obtain the STATIC_MASTER mutex. */ static void enterMutex(void){ sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); checkListProperties(0); } /* ** Release the STATIC_MASTER mutex. */ static void leaveMutex(void){ assertMutexHeld(); checkListProperties(0); sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); } /* ** Register an unlock-notify callback. ** ** This is called after connection "db" has attempted some operation ** but has received an SQLITE_LOCKED error because another connection ** (call it pOther) in the same process was busy using the same shared ** cache. pOther is found by looking at db->pBlockingConnection. ** ** If there is no blocking connection, the callback is invoked immediately, ** before this routine returns. ** ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate ** a deadlock. ** ** Otherwise, make arrangements to invoke xNotify when pOther drops ** its locks. ** ** Each call to this routine overrides any prior callbacks registered ** on the same "db". If xNotify==0 then any prior callbacks are immediately ** cancelled. */ SQLITE_API int sqlite3_unlock_notify( sqlite3 *db, void (*xNotify)(void **, int), void *pArg ){ int rc = SQLITE_OK; sqlite3_mutex_enter(db->mutex); enterMutex(); if( xNotify==0 ){ removeFromBlockedList(db); db->pBlockingConnection = 0; db->pUnlockConnection = 0; db->xUnlockNotify = 0; db->pUnlockArg = 0; }else if( 0==db->pBlockingConnection ){ /* The blocking transaction has been concluded. Or there never was a ** blocking transaction. In either case, invoke the notify callback ** immediately. */ xNotify(&pArg, 1); }else{ sqlite3 *p; for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} if( p ){ rc = SQLITE_LOCKED; /* Deadlock detected. */ }else{ db->pUnlockConnection = db->pBlockingConnection; db->xUnlockNotify = xNotify; db->pUnlockArg = pArg; removeFromBlockedList(db); addToBlockedList(db); } } leaveMutex(); assert( !db->mallocFailed ); sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0)); sqlite3_mutex_leave(db->mutex); return rc; } /* ** This function is called while stepping or preparing a statement ** associated with connection db. The operation will return SQLITE_LOCKED ** to the user because it requires a lock that will not be available ** until connection pBlocker concludes its current transaction. */ SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ enterMutex(); if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ addToBlockedList(db); } db->pBlockingConnection = pBlocker; leaveMutex(); } /* ** This function is called when ** the transaction opened by database db has just finished. Locks held ** by database connection db have been released. ** ** This function loops through each entry in the blocked connections ** list and does the following: ** ** 1) If the sqlite3.pBlockingConnection member of a list entry is ** set to db, then set pBlockingConnection=0. ** ** 2) If the sqlite3.pUnlockConnection member of a list entry is ** set to db, then invoke the configured unlock-notify callback and ** set pUnlockConnection=0. ** ** 3) If the two steps above mean that pBlockingConnection==0 and ** pUnlockConnection==0, remove the entry from the blocked connections ** list. */ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ int nArg = 0; /* Number of entries in aArg[] */ sqlite3 **pp; /* Iterator variable */ void **aArg; /* Arguments to the unlock callback */ void **aDyn = 0; /* Dynamically allocated space for aArg[] */ void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ aArg = aStatic; enterMutex(); /* Enter STATIC_MASTER mutex */ /* This loop runs once for each entry in the blocked-connections list. */ for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ sqlite3 *p = *pp; /* Step 1. */ if( p->pBlockingConnection==db ){ p->pBlockingConnection = 0; } /* Step 2. */ if( p->pUnlockConnection==db ){ assert( p->xUnlockNotify ); if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ xUnlockNotify(aArg, nArg); nArg = 0; } sqlite3BeginBenignMalloc(); assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); if( (!aDyn && nArg==(int)ArraySize(aStatic)) || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*))) ){ /* The aArg[] array needs to grow. */ void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); if( pNew ){ memcpy(pNew, aArg, nArg*sizeof(void *)); sqlite3_free(aDyn); aDyn = aArg = pNew; }else{ /* This occurs when the array of context pointers that need to ** be passed to the unlock-notify callback is larger than the ** aStatic[] array allocated on the stack and the attempt to ** allocate a larger array from the heap has failed. ** ** This is a difficult situation to handle. Returning an error ** code to the caller is insufficient, as even if an error code ** is returned the transaction on connection db will still be ** closed and the unlock-notify callbacks on blocked connections ** will go unissued. This might cause the application to wait ** indefinitely for an unlock-notify callback that will never ** arrive. ** ** Instead, invoke the unlock-notify callback with the context ** array already accumulated. We can then clear the array and ** begin accumulating any further context pointers without ** requiring any dynamic allocation. This is sub-optimal because ** it means that instead of one callback with a large array of ** context pointers the application will receive two or more ** callbacks with smaller arrays of context pointers, which will ** reduce the applications ability to prioritize multiple ** connections. But it is the best that can be done under the ** circumstances. */ xUnlockNotify(aArg, nArg); nArg = 0; } } sqlite3EndBenignMalloc(); aArg[nArg++] = p->pUnlockArg; xUnlockNotify = p->xUnlockNotify; p->pUnlockConnection = 0; p->xUnlockNotify = 0; p->pUnlockArg = 0; } /* Step 3. */ if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ /* Remove connection p from the blocked connections list. */ *pp = p->pNextBlocked; p->pNextBlocked = 0; }else{ pp = &p->pNextBlocked; } } if( nArg!=0 ){ xUnlockNotify(aArg, nArg); } sqlite3_free(aDyn); leaveMutex(); /* Leave STATIC_MASTER mutex */ } /* ** This is called when the database connection passed as an argument is ** being closed. The connection is removed from the blocked list. */ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ sqlite3ConnectionUnlocked(db); enterMutex(); removeFromBlockedList(db); checkListProperties(db); leaveMutex(); } #endif /************** End of notify.c **********************************************/ /************** Begin file fts3.c ********************************************/ /* ** 2006 Oct 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This is an SQLite module implementing full-text search. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* The full-text index is stored in a series of b+tree (-like) ** structures called segments which map terms to doclists. The ** structures are like b+trees in layout, but are constructed from the ** bottom up in optimal fashion and are not updatable. Since trees ** are built from the bottom up, things will be described from the ** bottom up. ** ** **** Varints **** ** The basic unit of encoding is a variable-length integer called a ** varint. We encode variable-length integers in little-endian order ** using seven bits * per byte as follows: ** ** KEY: ** A = 0xxxxxxx 7 bits of data and one flag bit ** B = 1xxxxxxx 7 bits of data and one flag bit ** ** 7 bits - A ** 14 bits - BA ** 21 bits - BBA ** and so on. ** ** This is similar in concept to how sqlite encodes "varints" but ** the encoding is not the same. SQLite varints are big-endian ** are are limited to 9 bytes in length whereas FTS3 varints are ** little-endian and can be up to 10 bytes in length (in theory). ** ** Example encodings: ** ** 1: 0x01 ** 127: 0x7f ** 128: 0x81 0x00 ** ** **** Document lists **** ** A doclist (document list) holds a docid-sorted list of hits for a ** given term. Doclists hold docids and associated token positions. ** A docid is the unique integer identifier for a single document. ** A position is the index of a word within the document. The first ** word of the document has a position of 0. ** ** FTS3 used to optionally store character offsets using a compile-time ** option. But that functionality is no longer supported. ** ** A doclist is stored like this: ** ** array { ** varint docid; (delta from previous doclist) ** array { (position list for column 0) ** varint position; (2 more than the delta from previous position) ** } ** array { ** varint POS_COLUMN; (marks start of position list for new column) ** varint column; (index of new column) ** array { ** varint position; (2 more than the delta from previous position) ** } ** } ** varint POS_END; (marks end of positions for this document. ** } ** ** Here, array { X } means zero or more occurrences of X, adjacent in ** memory. A "position" is an index of a token in the token stream ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur ** in the same logical place as the position element, and act as sentinals ** ending a position list array. POS_END is 0. POS_COLUMN is 1. ** The positions numbers are not stored literally but rather as two more ** than the difference from the prior position, or the just the position plus ** 2 for the first position. Example: ** ** label: A B C D E F G H I J K ** value: 123 5 9 1 1 14 35 0 234 72 0 ** ** The 123 value is the first docid. For column zero in this document ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1 ** at D signals the start of a new column; the 1 at E indicates that the ** new column is column number 1. There are two positions at 12 and 45 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The ** 234 at I is the delta to next docid (357). It has one position 70 ** (72-2) and then terminates with the 0 at K. ** ** A "position-list" is the list of positions for multiple columns for ** a single docid. A "column-list" is the set of positions for a single ** column. Hence, a position-list consists of one or more column-lists, ** a document record consists of a docid followed by a position-list and ** a doclist consists of one or more document records. ** ** A bare doclist omits the position information, becoming an ** array of varint-encoded docids. ** **** Segment leaf nodes **** ** Segment leaf nodes store terms and doclists, ordered by term. Leaf ** nodes are written using LeafWriter, and read using LeafReader (to ** iterate through a single leaf node's data) and LeavesReader (to ** iterate through a segment's entire leaf layer). Leaf nodes have ** the format: ** ** varint iHeight; (height from leaf level, always 0) ** varint nTerm; (length of first term) ** char pTerm[nTerm]; (content of first term) ** varint nDoclist; (length of term's associated doclist) ** char pDoclist[nDoclist]; (content of doclist) ** array { ** (further terms are delta-encoded) ** varint nPrefix; (length of prefix shared with previous term) ** varint nSuffix; (length of unshared suffix) ** char pTermSuffix[nSuffix];(unshared suffix of next term) ** varint nDoclist; (length of term's associated doclist) ** char pDoclist[nDoclist]; (content of doclist) ** } ** ** Here, array { X } means zero or more occurrences of X, adjacent in ** memory. ** ** Leaf nodes are broken into blocks which are stored contiguously in ** the %_segments table in sorted order. This means that when the end ** of a node is reached, the next term is in the node with the next ** greater node id. ** ** New data is spilled to a new leaf node when the current node ** exceeds LEAF_MAX bytes (default 2048). New data which itself is ** larger than STANDALONE_MIN (default 1024) is placed in a standalone ** node (a leaf node with a single term and doclist). The goal of ** these settings is to pack together groups of small doclists while ** making it efficient to directly access large doclists. The ** assumption is that large doclists represent terms which are more ** likely to be query targets. ** ** TODO(shess) It may be useful for blocking decisions to be more ** dynamic. For instance, it may make more sense to have a 2.5k leaf ** node rather than splitting into 2k and .5k nodes. My intuition is ** that this might extend through 2x or 4x the pagesize. ** ** **** Segment interior nodes **** ** Segment interior nodes store blockids for subtree nodes and terms ** to describe what data is stored by the each subtree. Interior ** nodes are written using InteriorWriter, and read using ** InteriorReader. InteriorWriters are created as needed when ** SegmentWriter creates new leaf nodes, or when an interior node ** itself grows too big and must be split. The format of interior ** nodes: ** ** varint iHeight; (height from leaf level, always >0) ** varint iBlockid; (block id of node's leftmost subtree) ** optional { ** varint nTerm; (length of first term) ** char pTerm[nTerm]; (content of first term) ** array { ** (further terms are delta-encoded) ** varint nPrefix; (length of shared prefix with previous term) ** varint nSuffix; (length of unshared suffix) ** char pTermSuffix[nSuffix]; (unshared suffix of next term) ** } ** } ** ** Here, optional { X } means an optional element, while array { X } ** means zero or more occurrences of X, adjacent in memory. ** ** An interior node encodes n terms separating n+1 subtrees. The ** subtree blocks are contiguous, so only the first subtree's blockid ** is encoded. The subtree at iBlockid will contain all terms less ** than the first term encoded (or all terms if no term is encoded). ** Otherwise, for terms greater than or equal to pTerm[i] but less ** than pTerm[i+1], the subtree for that term will be rooted at ** iBlockid+i. Interior nodes only store enough term data to ** distinguish adjacent children (if the rightmost term of the left ** child is "something", and the leftmost term of the right child is ** "wicked", only "w" is stored). ** ** New data is spilled to a new interior node at the same height when ** the current node exceeds INTERIOR_MAX bytes (default 2048). ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing ** interior nodes and making the tree too skinny. The interior nodes ** at a given height are naturally tracked by interior nodes at ** height+1, and so on. ** ** **** Segment directory **** ** The segment directory in table %_segdir stores meta-information for ** merging and deleting segments, and also the root node of the ** segment's tree. ** ** The root node is the top node of the segment's tree after encoding ** the entire segment, restricted to ROOT_MAX bytes (default 1024). ** This could be either a leaf node or an interior node. If the top ** node requires more than ROOT_MAX bytes, it is flushed to %_segments ** and a new root interior node is generated (which should always fit ** within ROOT_MAX because it only needs space for 2 varints, the ** height and the blockid of the previous root). ** ** The meta-information in the segment directory is: ** level - segment level (see below) ** idx - index within level ** - (level,idx uniquely identify a segment) ** start_block - first leaf node ** leaves_end_block - last leaf node ** end_block - last block (including interior nodes) ** root - contents of root node ** ** If the root node is a leaf node, then start_block, ** leaves_end_block, and end_block are all 0. ** ** **** Segment merging **** ** To amortize update costs, segments are grouped into levels and ** merged in batches. Each increase in level represents exponentially ** more documents. ** ** New documents (actually, document updates) are tokenized and ** written individually (using LeafWriter) to a level 0 segment, with ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all ** level 0 segments are merged into a single level 1 segment. Level 1 ** is populated like level 0, and eventually MERGE_COUNT level 1 ** segments are merged to a single level 2 segment (representing ** MERGE_COUNT^2 updates), and so on. ** ** A segment merge traverses all segments at a given level in ** parallel, performing a straightforward sorted merge. Since segment ** leaf nodes are written in to the %_segments table in order, this ** merge traverses the underlying sqlite disk structures efficiently. ** After the merge, all segment blocks from the merged level are ** deleted. ** ** MERGE_COUNT controls how often we merge segments. 16 seems to be ** somewhat of a sweet spot for insertion performance. 32 and 64 show ** very similar performance numbers to 16 on insertion, though they're ** a tiny bit slower (perhaps due to more overhead in merge-time ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than ** 16, 2 about 66% slower than 16. ** ** At query time, high MERGE_COUNT increases the number of segments ** which need to be scanned and merged. For instance, with 100k docs ** inserted: ** ** MERGE_COUNT segments ** 16 25 ** 8 12 ** 4 10 ** 2 6 ** ** This appears to have only a moderate impact on queries for very ** frequent terms (which are somewhat dominated by segment merge ** costs), and infrequent and non-existent terms still seem to be fast ** even with many segments. ** ** TODO(shess) That said, it would be nice to have a better query-side ** argument for MERGE_COUNT of 16. Also, it is possible/likely that ** optimizations to things like doclist merging will swing the sweet ** spot around. ** ** ** **** Handling of deletions and updates **** ** Since we're using a segmented structure, with no docid-oriented ** index into the term index, we clearly cannot simply update the term ** index when a document is deleted or updated. For deletions, we ** write an empty doclist (varint(docid) varint(POS_END)), for updates ** we simply write the new doclist. Segment merges overwrite older ** data for a particular docid with newer data, so deletes or updates ** will eventually overtake the earlier data and knock it out. The ** query logic likewise merges doclists so that newer data knocks out ** older data. */ /************** Include fts3Int.h in the middle of fts3.c ********************/ /************** Begin file fts3Int.h *****************************************/ /* ** 2009 Nov 12 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ #ifndef _FTSINT_H #define _FTSINT_H #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif /* FTS3/FTS4 require virtual tables */ #ifdef SQLITE_OMIT_VIRTUALTABLE # undef SQLITE_ENABLE_FTS3 # undef SQLITE_ENABLE_FTS4 #endif /* ** FTS4 is really an extension for FTS3. It is enabled using the ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3. */ #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) # define SQLITE_ENABLE_FTS3 #endif #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* If not building as part of the core, include sqlite3ext.h. */ #ifndef SQLITE_CORE /* # include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT3 #endif /* #include "sqlite3.h" */ /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/ /************** Begin file fts3_tokenizer.h **********************************/ /* ** 2006 July 10 ** ** The author disclaims copyright to this source code. ** ************************************************************************* ** Defines the interface to tokenizers used by fulltext-search. There ** are three basic components: ** ** sqlite3_tokenizer_module is a singleton defining the tokenizer ** interface functions. This is essentially the class structure for ** tokenizers. ** ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps ** including customization information defined at creation time. ** ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate ** tokens from a particular input. */ #ifndef _FTS3_TOKENIZER_H_ #define _FTS3_TOKENIZER_H_ /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. ** If tokenizers are to be allowed to call sqlite3_*() functions, then ** we will need a way to register the API consistently. */ /* #include "sqlite3.h" */ /* ** Structures used by the tokenizer interface. When a new tokenizer ** implementation is registered, the caller provides a pointer to ** an sqlite3_tokenizer_module containing pointers to the callback ** functions that make up an implementation. ** ** When an fts3 table is created, it passes any arguments passed to ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer ** implementation. The xCreate() function in turn returns an ** sqlite3_tokenizer structure representing the specific tokenizer to ** be used for the fts3 table (customized by the tokenizer clause arguments). ** ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() ** method is called. It returns an sqlite3_tokenizer_cursor object ** that may be used to tokenize a specific input buffer based on ** the tokenization rules supplied by a specific sqlite3_tokenizer ** object. */ typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; typedef struct sqlite3_tokenizer sqlite3_tokenizer; typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; struct sqlite3_tokenizer_module { /* ** Structure version. Should always be set to 0 or 1. */ int iVersion; /* ** Create a new tokenizer. The values in the argv[] array are the ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL ** TABLE statement that created the fts3 table. For example, if ** the following SQL is executed: ** ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2) ** ** then argc is set to 2, and the argv[] array contains pointers ** to the strings "arg1" and "arg2". ** ** This method should return either SQLITE_OK (0), or an SQLite error ** code. If SQLITE_OK is returned, then *ppTokenizer should be set ** to point at the newly created tokenizer structure. The generic ** sqlite3_tokenizer.pModule variable should not be initialized by ** this callback. The caller will do so. */ int (*xCreate)( int argc, /* Size of argv array */ const char *const*argv, /* Tokenizer argument strings */ sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ ); /* ** Destroy an existing tokenizer. The fts3 module calls this method ** exactly once for each successful call to xCreate(). */ int (*xDestroy)(sqlite3_tokenizer *pTokenizer); /* ** Create a tokenizer cursor to tokenize an input buffer. The caller ** is responsible for ensuring that the input buffer remains valid ** until the cursor is closed (using the xClose() method). */ int (*xOpen)( sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ const char *pInput, int nBytes, /* Input buffer */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ ); /* ** Destroy an existing tokenizer cursor. The fts3 module calls this ** method exactly once for each successful call to xOpen(). */ int (*xClose)(sqlite3_tokenizer_cursor *pCursor); /* ** Retrieve the next token from the tokenizer cursor pCursor. This ** method should either return SQLITE_OK and set the values of the ** "OUT" variables identified below, or SQLITE_DONE to indicate that ** the end of the buffer has been reached, or an SQLite error code. ** ** *ppToken should be set to point at a buffer containing the ** normalized version of the token (i.e. after any case-folding and/or ** stemming has been performed). *pnBytes should be set to the length ** of this buffer in bytes. The input text that generated the token is ** identified by the byte offsets returned in *piStartOffset and ** *piEndOffset. *piStartOffset should be set to the index of the first ** byte of the token in the input buffer. *piEndOffset should be set ** to the index of the first byte just past the end of the token in ** the input buffer. ** ** The buffer *ppToken is set to point at is managed by the tokenizer ** implementation. It is only required to be valid until the next call ** to xNext() or xClose(). */ /* TODO(shess) current implementation requires pInput to be ** nul-terminated. This should either be fixed, or pInput/nBytes ** should be converted to zInput. */ int (*xNext)( sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ int *piStartOffset, /* OUT: Byte offset of token in input buffer */ int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ int *piPosition /* OUT: Number of tokens returned before this one */ ); /*********************************************************************** ** Methods below this point are only available if iVersion>=1. */ /* ** Configure the language id of a tokenizer cursor. */ int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid); }; struct sqlite3_tokenizer { const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ /* Tokenizer implementations will typically add additional fields */ }; struct sqlite3_tokenizer_cursor { sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ /* Tokenizer implementations will typically add additional fields */ }; int fts3_global_term_cnt(int iTerm, int iCol); int fts3_term_cnt(int iTerm, int iCol); #endif /* _FTS3_TOKENIZER_H_ */ /************** End of fts3_tokenizer.h **************************************/ /************** Continuing where we left off in fts3Int.h ********************/ /************** Include fts3_hash.h in the middle of fts3Int.h ***************/ /************** Begin file fts3_hash.h ***************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for the generic hash-table implementation ** used in SQLite. We've modified it slightly to serve as a standalone ** hash table implementation for the full-text indexing module. ** */ #ifndef _FTS3_HASH_H_ #define _FTS3_HASH_H_ /* Forward declarations of structures. */ typedef struct Fts3Hash Fts3Hash; typedef struct Fts3HashElem Fts3HashElem; /* A complete hash table is an instance of the following structure. ** The internals of this structure are intended to be opaque -- client ** code should not attempt to access or modify the fields of this structure ** directly. Change this structure only by using the routines below. ** However, many of the "procedures" and "functions" for modifying and ** accessing this structure are really macros, so we can't really make ** this structure opaque. */ struct Fts3Hash { char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ char copyKey; /* True if copy of key made on insert */ int count; /* Number of entries in this table */ Fts3HashElem *first; /* The first element of the array */ int htsize; /* Number of buckets in the hash table */ struct _fts3ht { /* the hash table */ int count; /* Number of entries with this hash */ Fts3HashElem *chain; /* Pointer to first entry with this hash */ } *ht; }; /* Each element in the hash table is an instance of the following ** structure. All elements are stored on a single doubly-linked list. ** ** Again, this structure is intended to be opaque, but it can't really ** be opaque because it is used by macros. */ struct Fts3HashElem { Fts3HashElem *next, *prev; /* Next and previous elements in the table */ void *data; /* Data associated with this element */ void *pKey; int nKey; /* Key associated with this element */ }; /* ** There are 2 different modes of operation for a hash table: ** ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long ** (including the null-terminator, if any). Case ** is respected in comparisons. ** ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long. ** memcmp() is used to compare keys. ** ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1. */ #define FTS3_HASH_STRING 1 #define FTS3_HASH_BINARY 2 /* ** Access routines. To delete, insert a NULL pointer. */ SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey); SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData); SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey); SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*); SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int); /* ** Shorthand for the functions above */ #define fts3HashInit sqlite3Fts3HashInit #define fts3HashInsert sqlite3Fts3HashInsert #define fts3HashFind sqlite3Fts3HashFind #define fts3HashClear sqlite3Fts3HashClear #define fts3HashFindElem sqlite3Fts3HashFindElem /* ** Macros for looping over all elements of a hash table. The idiom is ** like this: ** ** Fts3Hash h; ** Fts3HashElem *p; ** ... ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){ ** SomeStructure *pData = fts3HashData(p); ** // do something with pData ** } */ #define fts3HashFirst(H) ((H)->first) #define fts3HashNext(E) ((E)->next) #define fts3HashData(E) ((E)->data) #define fts3HashKey(E) ((E)->pKey) #define fts3HashKeysize(E) ((E)->nKey) /* ** Number of entries in a hash table */ #define fts3HashCount(H) ((H)->count) #endif /* _FTS3_HASH_H_ */ /************** End of fts3_hash.h *******************************************/ /************** Continuing where we left off in fts3Int.h ********************/ /* ** This constant determines the maximum depth of an FTS expression tree ** that the library will create and use. FTS uses recursion to perform ** various operations on the query tree, so the disadvantage of a large ** limit is that it may allow very large queries to use large amounts ** of stack space (perhaps causing a stack overflow). */ #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH # define SQLITE_FTS3_MAX_EXPR_DEPTH 12 #endif /* ** This constant controls how often segments are merged. Once there are ** FTS3_MERGE_COUNT segments of level N, they are merged into a single ** segment of level N+1. */ #define FTS3_MERGE_COUNT 16 /* ** This is the maximum amount of data (in bytes) to store in the ** Fts3Table.pendingTerms hash table. Normally, the hash table is ** populated as documents are inserted/updated/deleted in a transaction ** and used to create a new segment when the transaction is committed. ** However if this limit is reached midway through a transaction, a new ** segment is created and the hash table cleared immediately. */ #define FTS3_MAX_PENDING_DATA (1*1024*1024) /* ** Macro to return the number of elements in an array. SQLite has a ** similar macro called ArraySize(). Use a different name to avoid ** a collision when building an amalgamation with built-in FTS3. */ #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0]))) #ifndef MIN # define MIN(x,y) ((x)<(y)?(x):(y)) #endif #ifndef MAX # define MAX(x,y) ((x)>(y)?(x):(y)) #endif /* ** Maximum length of a varint encoded integer. The varint format is different ** from that used by SQLite, so the maximum length is 10, not 9. */ #define FTS3_VARINT_MAX 10 /* ** FTS4 virtual tables may maintain multiple indexes - one index of all terms ** in the document set and zero or more prefix indexes. All indexes are stored ** as one or more b+-trees in the %_segments and %_segdir tables. ** ** It is possible to determine which index a b+-tree belongs to based on the ** value stored in the "%_segdir.level" column. Given this value L, the index ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with ** level values between 0 and 1023 (inclusive) belong to index 0, all levels ** between 1024 and 2047 to index 1, and so on. ** ** It is considered impossible for an index to use more than 1024 levels. In ** theory though this may happen, but only after at least ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables. */ #define FTS3_SEGDIR_MAXLEVEL 1024 #define FTS3_SEGDIR_MAXLEVEL_STR "1024" /* ** The testcase() macro is only used by the amalgamation. If undefined, ** make it a no-op. */ #ifndef testcase # define testcase(X) #endif /* ** Terminator values for position-lists and column-lists. */ #define POS_COLUMN (1) /* Column-list terminator */ #define POS_END (0) /* Position-list terminator */ /* ** This section provides definitions to allow the ** FTS3 extension to be compiled outside of the ** amalgamation. */ #ifndef SQLITE_AMALGAMATION /* ** Macros indicating that conditional expressions are always true or ** false. */ #ifdef SQLITE_COVERAGE_TEST # define ALWAYS(x) (1) # define NEVER(X) (0) #elif defined(SQLITE_DEBUG) # define ALWAYS(x) sqlite3Fts3Always((x)!=0) # define NEVER(x) sqlite3Fts3Never((x)!=0) SQLITE_PRIVATE int sqlite3Fts3Always(int b); SQLITE_PRIVATE int sqlite3Fts3Never(int b); #else # define ALWAYS(x) (x) # define NEVER(x) (x) #endif /* ** Internal types used by SQLite. */ typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */ typedef short int i16; /* 2-byte (or larger) signed integer */ typedef unsigned int u32; /* 4-byte unsigned integer */ typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */ typedef sqlite3_int64 i64; /* 8-byte signed integer */ /* ** Macro used to suppress compiler warnings for unused parameters. */ #define UNUSED_PARAMETER(x) (void)(x) /* ** Activate assert() only if SQLITE_TEST is enabled. */ #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif /* ** The TESTONLY macro is used to enclose variable declarations or ** other bits of code that are needed to support the arguments ** within testcase() and assert() macros. */ #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) # define TESTONLY(X) X #else # define TESTONLY(X) #endif #endif /* SQLITE_AMALGAMATION */ #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3Fts3Corrupt(void); # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt() #else # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB #endif typedef struct Fts3Table Fts3Table; typedef struct Fts3Cursor Fts3Cursor; typedef struct Fts3Expr Fts3Expr; typedef struct Fts3Phrase Fts3Phrase; typedef struct Fts3PhraseToken Fts3PhraseToken; typedef struct Fts3Doclist Fts3Doclist; typedef struct Fts3SegFilter Fts3SegFilter; typedef struct Fts3DeferredToken Fts3DeferredToken; typedef struct Fts3SegReader Fts3SegReader; typedef struct Fts3MultiSegReader Fts3MultiSegReader; typedef struct MatchinfoBuffer MatchinfoBuffer; /* ** A connection to a fulltext index is an instance of the following ** structure. The xCreate and xConnect methods create an instance ** of this structure and xDestroy and xDisconnect free that instance. ** All other methods receive a pointer to the structure as one of their ** arguments. */ struct Fts3Table { sqlite3_vtab base; /* Base class used by SQLite core */ sqlite3 *db; /* The database connection */ const char *zDb; /* logical database name */ const char *zName; /* virtual table name */ int nColumn; /* number of named columns in virtual table */ char **azColumn; /* column names. malloced */ u8 *abNotindexed; /* True for 'notindexed' columns */ sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ char *zContentTbl; /* content=xxx option, or NULL */ char *zLanguageid; /* languageid=xxx option, or NULL */ int nAutoincrmerge; /* Value configured by 'automerge' */ u32 nLeafAdd; /* Number of leaf blocks added this trans */ /* Precompiled statements used by the implementation. Each of these ** statements is run and reset within a single virtual table API call. */ sqlite3_stmt *aStmt[40]; sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */ char *zReadExprlist; char *zWriteExprlist; int nNodeSize; /* Soft limit for node size */ u8 bFts4; /* True for FTS4, false for FTS3 */ u8 bHasStat; /* True if %_stat table exists (2==unknown) */ u8 bHasDocsize; /* True if %_docsize table exists */ u8 bDescIdx; /* True if doclists are in reverse order */ u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */ int nPgsz; /* Page size for host database */ char *zSegmentsTbl; /* Name of %_segments table */ sqlite3_blob *pSegments; /* Blob handle open on %_segments table */ /* ** The following array of hash tables is used to buffer pending index ** updates during transactions. All pending updates buffered at any one ** time must share a common language-id (see the FTS4 langid= feature). ** The current language id is stored in variable iPrevLangid. ** ** A single FTS4 table may have multiple full-text indexes. For each index ** there is an entry in the aIndex[] array. Index 0 is an index of all the ** terms that appear in the document set. Each subsequent index in aIndex[] ** is an index of prefixes of a specific length. ** ** Variable nPendingData contains an estimate the memory consumed by the ** pending data structures, including hash table overhead, but not including ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash ** tables are flushed to disk. Variable iPrevDocid is the docid of the most ** recently inserted record. */ int nIndex; /* Size of aIndex[] */ struct Fts3Index { int nPrefix; /* Prefix length (0 for main terms index) */ Fts3Hash hPending; /* Pending terms table for this index */ } *aIndex; int nMaxPendingData; /* Max pending data before flush to disk */ int nPendingData; /* Current bytes of pending data */ sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */ int iPrevLangid; /* Langid of recently inserted document */ int bPrevDelete; /* True if last operation was a delete */ #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) /* State variables used for validating that the transaction control ** methods of the virtual table are called at appropriate times. These ** values do not contribute to FTS functionality; they are used for ** verifying the operation of the SQLite core. */ int inTransaction; /* True after xBegin but before xCommit/xRollback */ int mxSavepoint; /* Largest valid xSavepoint integer */ #endif #ifdef SQLITE_TEST /* True to disable the incremental doclist optimization. This is controled ** by special insert command 'test-no-incr-doclist'. */ int bNoIncrDoclist; #endif }; /* ** When the core wants to read from the virtual table, it creates a ** virtual table cursor (an instance of the following structure) using ** the xOpen method. Cursors are destroyed using the xClose method. */ struct Fts3Cursor { sqlite3_vtab_cursor base; /* Base class used by SQLite core */ i16 eSearch; /* Search strategy (see below) */ u8 isEof; /* True if at End Of Results */ u8 isRequireSeek; /* True if must seek pStmt to %_content row */ u8 bSeekStmt; /* True if pStmt is a seek */ sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ Fts3Expr *pExpr; /* Parsed MATCH query string */ int iLangid; /* Language being queried for */ int nPhrase; /* Number of matchable phrases in query */ Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */ sqlite3_int64 iPrevId; /* Previous id read from aDoclist */ char *pNextId; /* Pointer into the body of aDoclist */ char *aDoclist; /* List of docids for full-text queries */ int nDoclist; /* Size of buffer at aDoclist */ u8 bDesc; /* True to sort in descending order */ int eEvalmode; /* An FTS3_EVAL_XX constant */ int nRowAvg; /* Average size of database rows, in pages */ sqlite3_int64 nDoc; /* Documents in table */ i64 iMinDocid; /* Minimum docid to return */ i64 iMaxDocid; /* Maximum docid to return */ int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */ MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */ }; #define FTS3_EVAL_FILTER 0 #define FTS3_EVAL_NEXT 1 #define FTS3_EVAL_MATCHINFO 2 /* ** The Fts3Cursor.eSearch member is always set to one of the following. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index ** of the column to be searched. For example, in ** ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d); ** SELECT docid FROM ex1 WHERE b MATCH 'one two three'; ** ** Because the LHS of the MATCH operator is 2nd column "b", ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a, ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1" ** indicating that all columns should be searched, ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4. */ #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */ #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */ #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */ /* ** The lower 16-bits of the sqlite3_index_info.idxNum value set by ** the xBestIndex() method contains the Fts3Cursor.eSearch value described ** above. The upper 16-bits contain a combination of the following ** bits, used to describe extra constraints on full-text searches. */ #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */ #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */ #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */ struct Fts3Doclist { char *aAll; /* Array containing doclist (or NULL) */ int nAll; /* Size of a[] in bytes */ char *pNextDocid; /* Pointer to next docid */ sqlite3_int64 iDocid; /* Current docid (if pList!=0) */ int bFreeList; /* True if pList should be sqlite3_free()d */ char *pList; /* Pointer to position list following iDocid */ int nList; /* Length of position list */ }; /* ** A "phrase" is a sequence of one or more tokens that must match in ** sequence. A single token is the base case and the most common case. ** For a sequence of tokens contained in double-quotes (i.e. "one two three") ** nToken will be the number of tokens in the string. */ struct Fts3PhraseToken { char *z; /* Text of the token */ int n; /* Number of bytes in buffer z */ int isPrefix; /* True if token ends with a "*" character */ int bFirst; /* True if token must appear at position 0 */ /* Variables above this point are populated when the expression is ** parsed (by code in fts3_expr.c). Below this point the variables are ** used when evaluating the expression. */ Fts3DeferredToken *pDeferred; /* Deferred token object for this token */ Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */ }; struct Fts3Phrase { /* Cache of doclist for this phrase. */ Fts3Doclist doclist; int bIncr; /* True if doclist is loaded incrementally */ int iDoclistToken; /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an ** OR condition. */ char *pOrPoslist; i64 iOrDocid; /* Variables below this point are populated by fts3_expr.c when parsing ** a MATCH expression. Everything above is part of the evaluation phase. */ int nToken; /* Number of tokens in the phrase */ int iColumn; /* Index of column this phrase must match */ Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */ }; /* ** A tree of these objects forms the RHS of a MATCH operator. ** ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist ** points to a malloced buffer, size nDoclist bytes, containing the results ** of this phrase query in FTS3 doclist format. As usual, the initial ** "Length" field found in doclists stored on disk is omitted from this ** buffer. ** ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global ** matchinfo data. If it is not NULL, it points to an array of size nCol*3, ** where nCol is the number of columns in the queried FTS table. The array ** is populated as follows: ** ** aMI[iCol*3 + 0] = Undefined ** aMI[iCol*3 + 1] = Number of occurrences ** aMI[iCol*3 + 2] = Number of rows containing at least one instance ** ** The aMI array is allocated using sqlite3_malloc(). It should be freed ** when the expression node is. */ struct Fts3Expr { int eType; /* One of the FTSQUERY_XXX values defined below */ int nNear; /* Valid if eType==FTSQUERY_NEAR */ Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */ Fts3Expr *pLeft; /* Left operand */ Fts3Expr *pRight; /* Right operand */ Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */ /* The following are used by the fts3_eval.c module. */ sqlite3_int64 iDocid; /* Current docid */ u8 bEof; /* True this expression is at EOF already */ u8 bStart; /* True if iDocid is valid */ u8 bDeferred; /* True if this expression is entirely deferred */ /* The following are used by the fts3_snippet.c module. */ int iPhrase; /* Index of this phrase in matchinfo() results */ u32 *aMI; /* See above */ }; /* ** Candidate values for Fts3Query.eType. Note that the order of the first ** four values is in order of precedence when parsing expressions. For ** example, the following: ** ** "a OR b AND c NOT d NEAR e" ** ** is equivalent to: ** ** "a OR (b AND (c NOT (d NEAR e)))" */ #define FTSQUERY_NEAR 1 #define FTSQUERY_NOT 2 #define FTSQUERY_AND 3 #define FTSQUERY_OR 4 #define FTSQUERY_PHRASE 5 /* fts3_write.c */ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*); SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *); SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *); SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *); SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64, sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**); SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( Fts3Table*,int,const char*,int,int,Fts3SegReader**); SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *); SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **); SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*); SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **); SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **); #ifndef SQLITE_DISABLE_FTS4_DEFERRED SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *); SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int); SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *); SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *); SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *); #else # define sqlite3Fts3FreeDeferredTokens(x) # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK # define sqlite3Fts3FreeDeferredDoclists(x) # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK #endif SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *); SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *); /* Special values interpreted by sqlite3SegReaderCursor() */ #define FTS3_SEGCURSOR_PENDING -1 #define FTS3_SEGCURSOR_ALL -2 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*); SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *); SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *); SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, int, int, int, const char *, int, int, int, Fts3MultiSegReader *); /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */ #define FTS3_SEGMENT_REQUIRE_POS 0x00000001 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004 #define FTS3_SEGMENT_PREFIX 0x00000008 #define FTS3_SEGMENT_SCAN 0x00000010 #define FTS3_SEGMENT_FIRST 0x00000020 /* Type passed as 4th argument to SegmentReaderIterate() */ struct Fts3SegFilter { const char *zTerm; int nTerm; int iCol; int flags; }; struct Fts3MultiSegReader { /* Used internally by sqlite3Fts3SegReaderXXX() calls */ Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */ int nSegment; /* Size of apSegment array */ int nAdvance; /* How many seg-readers to advance */ Fts3SegFilter *pFilter; /* Pointer to filter object */ char *aBuffer; /* Buffer to merge doclists in */ int nBuffer; /* Allocated size of aBuffer[] in bytes */ int iColFilter; /* If >=0, filter for this column */ int bRestart; /* Used by fts3.c only. */ int nCost; /* Cost of running iterator */ int bLookup; /* True if a lookup of a single entry. */ /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */ char *zTerm; /* Pointer to term buffer */ int nTerm; /* Size of zTerm in bytes */ char *aDoclist; /* Pointer to doclist buffer */ int nDoclist; /* Size of aDoclist[] in bytes */ }; SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int); #define fts3GetVarint32(p, piVal) ( \ (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \ ) /* fts3.c */ SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...); SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64); SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *); SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *); SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64); SQLITE_PRIVATE void sqlite3Fts3Dequote(char *); SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*); SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *); SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *); SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*); SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc); /* fts3_tokenizer.c */ SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *); SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *); SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, sqlite3_tokenizer **, char ** ); SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char); /* fts3_snippet.c */ SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*); SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *, const char *, const char *, int, int ); SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *); SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p); /* fts3_expr.c */ SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int, char **, int, int, int, const char *, int, Fts3Expr **, char ** ); SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *); #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db); SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db); #endif SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int, sqlite3_tokenizer_cursor ** ); /* fts3_aux.c */ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db); SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *); SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( Fts3Table*, Fts3MultiSegReader*, int, const char*, int); SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *); SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *); SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr); /* fts3_tokenize_vtab.c */ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *); /* fts3_unicode2.c (functions generated by parsing unicode text files) */ #ifndef SQLITE_DISABLE_FTS3_UNICODE SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int); SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int); SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int); #endif #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */ #endif /* _FTSINT_H */ /************** End of fts3Int.h *********************************************/ /************** Continuing where we left off in fts3.c ***********************/ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) # define SQLITE_CORE 1 #endif /* #include <assert.h> */ /* #include <stdlib.h> */ /* #include <stddef.h> */ /* #include <stdio.h> */ /* #include <string.h> */ /* #include <stdarg.h> */ /* #include "fts3.h" */ #ifndef SQLITE_CORE /* # include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #endif static int fts3EvalNext(Fts3Cursor *pCsr); static int fts3EvalStart(Fts3Cursor *pCsr); static int fts3TermSegReaderCursor( Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **); #ifndef SQLITE_AMALGAMATION # if defined(SQLITE_DEBUG) SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; } SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; } # endif #endif /* ** Write a 64-bit variable-length integer to memory starting at p[0]. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes. ** The number of bytes written is returned. */ SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ unsigned char *q = (unsigned char *) p; sqlite_uint64 vu = v; do{ *q++ = (unsigned char) ((vu & 0x7f) | 0x80); vu >>= 7; }while( vu!=0 ); q[-1] &= 0x7f; /* turn off high bit in final byte */ assert( q - (unsigned char *)p <= FTS3_VARINT_MAX ); return (int) (q - (unsigned char *)p); } #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \ v = (v & mask1) | ( (*ptr++) << shift ); \ if( (v & mask2)==0 ){ var = v; return ret; } #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \ v = (*ptr++); \ if( (v & mask2)==0 ){ var = v; return ret; } /* ** Read a 64-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read, or 0 on error. ** The value is stored in *v. */ SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){ const char *pStart = p; u32 a; u64 b; int shift; GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1); GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2); GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3); GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4); b = (a & 0x0FFFFFFF ); for(shift=28; shift<=63; shift+=7){ u64 c = *p++; b += (c&0x7F) << shift; if( (c & 0x80)==0 ) break; } *v = b; return (int)(p - pStart); } /* ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a ** 32-bit integer before it is returned. */ SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){ u32 a; #ifndef fts3GetVarint32 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1); #else a = (*p++); assert( a & 0x80 ); #endif GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2); GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3); GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4); a = (a & 0x0FFFFFFF ); *pi = (int)(a | ((u32)(*p & 0x0F) << 28)); return 5; } /* ** Return the number of bytes required to encode v as a varint */ SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){ int i = 0; do{ i++; v >>= 7; }while( v!=0 ); return i; } /* ** Convert an SQL-style quoted string into a normal string by removing ** the quote characters. The conversion is done in-place. If the ** input does not begin with a quote character, then this routine ** is a no-op. ** ** Examples: ** ** "abc" becomes abc ** 'xyz' becomes xyz ** [pqr] becomes pqr ** `mno` becomes mno ** */ SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){ char quote; /* Quote character (if any ) */ quote = z[0]; if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ int iIn = 1; /* Index of next byte to read from input */ int iOut = 0; /* Index of next byte to write to output */ /* If the first byte was a '[', then the close-quote character is a ']' */ if( quote=='[' ) quote = ']'; while( z[iIn] ){ if( z[iIn]==quote ){ if( z[iIn+1]!=quote ) break; z[iOut++] = quote; iIn += 2; }else{ z[iOut++] = z[iIn++]; } } z[iOut] = '\0'; } } /* ** Read a single varint from the doclist at *pp and advance *pp to point ** to the first byte past the end of the varint. Add the value of the varint ** to *pVal. */ static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ sqlite3_int64 iVal; *pp += sqlite3Fts3GetVarint(*pp, &iVal); *pVal += iVal; } /* ** When this function is called, *pp points to the first byte following a ** varint that is part of a doclist (or position-list, or any other list ** of varints). This function moves *pp to point to the start of that varint, ** and sets *pVal by the varint value. ** ** Argument pStart points to the first byte of the doclist that the ** varint is part of. */ static void fts3GetReverseVarint( char **pp, char *pStart, sqlite3_int64 *pVal ){ sqlite3_int64 iVal; char *p; /* Pointer p now points at the first byte past the varint we are ** interested in. So, unless the doclist is corrupt, the 0x80 bit is ** clear on character p[-1]. */ for(p = (*pp)-2; p>=pStart && *p&0x80; p--); p++; *pp = p; sqlite3Fts3GetVarint(p, &iVal); *pVal = iVal; } /* ** The xDisconnect() virtual table method. */ static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table *)pVtab; int i; assert( p->nPendingData==0 ); assert( p->pSegments==0 ); /* Free any prepared statements held */ sqlite3_finalize(p->pSeekStmt); for(i=0; i<SizeofArray(p->aStmt); i++){ sqlite3_finalize(p->aStmt[i]); } sqlite3_free(p->zSegmentsTbl); sqlite3_free(p->zReadExprlist); sqlite3_free(p->zWriteExprlist); sqlite3_free(p->zContentTbl); sqlite3_free(p->zLanguageid); /* Invoke the tokenizer destructor to free the tokenizer. */ p->pTokenizer->pModule->xDestroy(p->pTokenizer); sqlite3_free(p); return SQLITE_OK; } /* ** Write an error message into *pzErr */ SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){ va_list ap; sqlite3_free(*pzErr); va_start(ap, zFormat); *pzErr = sqlite3_vmprintf(zFormat, ap); va_end(ap); } /* ** Construct one or more SQL statements from the format string given ** and then evaluate those statements. The success code is written ** into *pRc. ** ** If *pRc is initially non-zero then this routine is a no-op. */ static void fts3DbExec( int *pRc, /* Success code */ sqlite3 *db, /* Database in which to run SQL */ const char *zFormat, /* Format string for SQL */ ... /* Arguments to the format string */ ){ va_list ap; char *zSql; if( *pRc ) return; va_start(ap, zFormat); zSql = sqlite3_vmprintf(zFormat, ap); va_end(ap); if( zSql==0 ){ *pRc = SQLITE_NOMEM; }else{ *pRc = sqlite3_exec(db, zSql, 0, 0, 0); sqlite3_free(zSql); } } /* ** The xDestroy() virtual table method. */ static int fts3DestroyMethod(sqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table *)pVtab; int rc = SQLITE_OK; /* Return code */ const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */ sqlite3 *db = p->db; /* Database handle */ /* Drop the shadow tables */ if( p->zContentTbl==0 ){ fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName); } fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName); fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName); fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName); fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName); /* If everything has worked, invoke fts3DisconnectMethod() to free the ** memory associated with the Fts3Table structure and return SQLITE_OK. ** Otherwise, return an SQLite error code. */ return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc); } /* ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table ** passed as the first argument. This is done as part of the xConnect() ** and xCreate() methods. ** ** If *pRc is non-zero when this function is called, it is a no-op. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc ** before returning. */ static void fts3DeclareVtab(int *pRc, Fts3Table *p){ if( *pRc==SQLITE_OK ){ int i; /* Iterator variable */ int rc; /* Return code */ char *zSql; /* SQL statement passed to declare_vtab() */ char *zCols; /* List of user defined columns */ const char *zLanguageid; zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid"); sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); /* Create a list of user columns for the virtual table */ zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]); for(i=1; zCols && i<p->nColumn; i++){ zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); } /* Create the whole "CREATE TABLE" statement to pass to SQLite */ zSql = sqlite3_mprintf( "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", zCols, p->zName, zLanguageid ); if( !zCols || !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_declare_vtab(p->db, zSql); } sqlite3_free(zSql); sqlite3_free(zCols); *pRc = rc; } } /* ** Create the %_stat table if it does not already exist. */ SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ fts3DbExec(pRc, p->db, "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'" "(id INTEGER PRIMARY KEY, value BLOB);", p->zDb, p->zName ); if( (*pRc)==SQLITE_OK ) p->bHasStat = 1; } /* ** Create the backing store tables (%_content, %_segments and %_segdir) ** required by the FTS3 table passed as the only argument. This is done ** as part of the vtab xCreate() method. ** ** If the p->bHasDocsize boolean is true (indicating that this is an ** FTS4 table, not an FTS3 table) then also create the %_docsize and ** %_stat tables required by FTS4. */ static int fts3CreateTables(Fts3Table *p){ int rc = SQLITE_OK; /* Return code */ int i; /* Iterator variable */ sqlite3 *db = p->db; /* The database connection */ if( p->zContentTbl==0 ){ const char *zLanguageid = p->zLanguageid; char *zContentCols; /* Columns of %_content table */ /* Create a list of user columns for the content table */ zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY"); for(i=0; zContentCols && i<p->nColumn; i++){ char *z = p->azColumn[i]; zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); } if( zLanguageid && zContentCols ){ zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid); } if( zContentCols==0 ) rc = SQLITE_NOMEM; /* Create the content table */ fts3DbExec(&rc, db, "CREATE TABLE %Q.'%q_content'(%s)", p->zDb, p->zName, zContentCols ); sqlite3_free(zContentCols); } /* Create other tables */ fts3DbExec(&rc, db, "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);", p->zDb, p->zName ); fts3DbExec(&rc, db, "CREATE TABLE %Q.'%q_segdir'(" "level INTEGER," "idx INTEGER," "start_block INTEGER," "leaves_end_block INTEGER," "end_block INTEGER," "root BLOB," "PRIMARY KEY(level, idx)" ");", p->zDb, p->zName ); if( p->bHasDocsize ){ fts3DbExec(&rc, db, "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);", p->zDb, p->zName ); } assert( p->bHasStat==p->bFts4 ); if( p->bHasStat ){ sqlite3Fts3CreateStatTable(&rc, p); } return rc; } /* ** Store the current database page-size in bytes in p->nPgsz. ** ** If *pRc is non-zero when this function is called, it is a no-op. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc ** before returning. */ static void fts3DatabasePageSize(int *pRc, Fts3Table *p){ if( *pRc==SQLITE_OK ){ int rc; /* Return code */ char *zSql; /* SQL text "PRAGMA %Q.page_size" */ sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_step(pStmt); p->nPgsz = sqlite3_column_int(pStmt, 0); rc = sqlite3_finalize(pStmt); }else if( rc==SQLITE_AUTH ){ p->nPgsz = 1024; rc = SQLITE_OK; } } assert( p->nPgsz>0 || rc!=SQLITE_OK ); sqlite3_free(zSql); *pRc = rc; } } /* ** "Special" FTS4 arguments are column specifications of the following form: ** ** <key> = <value> ** ** There may not be whitespace surrounding the "=" character. The <value> ** term may be quoted, but the <key> may not. */ static int fts3IsSpecialColumn( const char *z, int *pnKey, char **pzValue ){ char *zValue; const char *zCsr = z; while( *zCsr!='=' ){ if( *zCsr=='\0' ) return 0; zCsr++; } *pnKey = (int)(zCsr-z); zValue = sqlite3_mprintf("%s", &zCsr[1]); if( zValue ){ sqlite3Fts3Dequote(zValue); } *pzValue = zValue; return 1; } /* ** Append the output of a printf() style formatting to an existing string. */ static void fts3Appendf( int *pRc, /* IN/OUT: Error code */ char **pz, /* IN/OUT: Pointer to string buffer */ const char *zFormat, /* Printf format string to append */ ... /* Arguments for printf format string */ ){ if( *pRc==SQLITE_OK ){ va_list ap; char *z; va_start(ap, zFormat); z = sqlite3_vmprintf(zFormat, ap); va_end(ap); if( z && *pz ){ char *z2 = sqlite3_mprintf("%s%s", *pz, z); sqlite3_free(z); z = z2; } if( z==0 ) *pRc = SQLITE_NOMEM; sqlite3_free(*pz); *pz = z; } } /* ** Return a copy of input string zInput enclosed in double-quotes (") and ** with all double quote characters escaped. For example: ** ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\"" ** ** The pointer returned points to memory obtained from sqlite3_malloc(). It ** is the callers responsibility to call sqlite3_free() to release this ** memory. */ static char *fts3QuoteId(char const *zInput){ int nRet; char *zRet; nRet = 2 + (int)strlen(zInput)*2 + 1; zRet = sqlite3_malloc(nRet); if( zRet ){ int i; char *z = zRet; *(z++) = '"'; for(i=0; zInput[i]; i++){ if( zInput[i]=='"' ) *(z++) = '"'; *(z++) = zInput[i]; } *(z++) = '"'; *(z++) = '\0'; } return zRet; } /* ** Return a list of comma separated SQL expressions and a FROM clause that ** could be used in a SELECT statement such as the following: ** ** SELECT <list of expressions> FROM %_content AS x ... ** ** to return the docid, followed by each column of text data in order ** from left to write. If parameter zFunc is not NULL, then instead of ** being returned directly each column of text data is passed to an SQL ** function named zFunc first. For example, if zFunc is "unzip" and the ** table has the three user-defined columns "a", "b", and "c", the following ** string is returned: ** ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x" ** ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It ** is the responsibility of the caller to eventually free it. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and ** a NULL pointer is returned). Otherwise, if an OOM error is encountered ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If ** no error occurs, *pRc is left unmodified. */ static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ char *zRet = 0; char *zFree = 0; char *zFunction; int i; if( p->zContentTbl==0 ){ if( !zFunc ){ zFunction = ""; }else{ zFree = zFunction = fts3QuoteId(zFunc); } fts3Appendf(pRc, &zRet, "docid"); for(i=0; i<p->nColumn; i++){ fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]); } if( p->zLanguageid ){ fts3Appendf(pRc, &zRet, ", x.%Q", "langid"); } sqlite3_free(zFree); }else{ fts3Appendf(pRc, &zRet, "rowid"); for(i=0; i<p->nColumn; i++){ fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]); } if( p->zLanguageid ){ fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid); } } fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", p->zDb, (p->zContentTbl ? p->zContentTbl : p->zName), (p->zContentTbl ? "" : "_content") ); return zRet; } /* ** Return a list of N comma separated question marks, where N is the number ** of columns in the %_content table (one for the docid plus one for each ** user-defined text column). ** ** If argument zFunc is not NULL, then all but the first question mark ** is preceded by zFunc and an open bracket, and followed by a closed ** bracket. For example, if zFunc is "zip" and the FTS3 table has three ** user-defined text columns, the following string is returned: ** ** "?, zip(?), zip(?), zip(?)" ** ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It ** is the responsibility of the caller to eventually free it. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and ** a NULL pointer is returned). Otherwise, if an OOM error is encountered ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If ** no error occurs, *pRc is left unmodified. */ static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){ char *zRet = 0; char *zFree = 0; char *zFunction; int i; if( !zFunc ){ zFunction = ""; }else{ zFree = zFunction = fts3QuoteId(zFunc); } fts3Appendf(pRc, &zRet, "?"); for(i=0; i<p->nColumn; i++){ fts3Appendf(pRc, &zRet, ",%s(?)", zFunction); } if( p->zLanguageid ){ fts3Appendf(pRc, &zRet, ", ?"); } sqlite3_free(zFree); return zRet; } /* ** This function interprets the string at (*pp) as a non-negative integer ** value. It reads the integer and sets *pnOut to the value read, then ** sets *pp to point to the byte immediately following the last byte of ** the integer value. ** ** Only decimal digits ('0'..'9') may be part of an integer value. ** ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and ** the output value undefined. Otherwise SQLITE_OK is returned. ** ** This function is used when parsing the "prefix=" FTS4 parameter. */ static int fts3GobbleInt(const char **pp, int *pnOut){ const int MAX_NPREFIX = 10000000; const char *p; /* Iterator pointer */ int nInt = 0; /* Output value */ for(p=*pp; p[0]>='0' && p[0]<='9'; p++){ nInt = nInt * 10 + (p[0] - '0'); if( nInt>MAX_NPREFIX ){ nInt = 0; break; } } if( p==*pp ) return SQLITE_ERROR; *pnOut = nInt; *pp = p; return SQLITE_OK; } /* ** This function is called to allocate an array of Fts3Index structures ** representing the indexes maintained by the current FTS table. FTS tables ** always maintain the main "terms" index, but may also maintain one or ** more "prefix" indexes, depending on the value of the "prefix=" parameter ** (if any) specified as part of the CREATE VIRTUAL TABLE statement. ** ** Argument zParam is passed the value of the "prefix=" option if one was ** specified, or NULL otherwise. ** ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to ** the allocated array. *pnIndex is set to the number of elements in the ** array. If an error does occur, an SQLite error code is returned. ** ** Regardless of whether or not an error is returned, it is the responsibility ** of the caller to call sqlite3_free() on the output array to free it. */ static int fts3PrefixParameter( const char *zParam, /* ABC in prefix=ABC parameter to parse */ int *pnIndex, /* OUT: size of *apIndex[] array */ struct Fts3Index **apIndex /* OUT: Array of indexes for this table */ ){ struct Fts3Index *aIndex; /* Allocated array */ int nIndex = 1; /* Number of entries in array */ if( zParam && zParam[0] ){ const char *p; nIndex++; for(p=zParam; *p; p++){ if( *p==',' ) nIndex++; } } aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex); *apIndex = aIndex; if( !aIndex ){ return SQLITE_NOMEM; } memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex); if( zParam ){ const char *p = zParam; int i; for(i=1; i<nIndex; i++){ int nPrefix = 0; if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR; assert( nPrefix>=0 ); if( nPrefix==0 ){ nIndex--; i--; }else{ aIndex[i].nPrefix = nPrefix; } p++; } } *pnIndex = nIndex; return SQLITE_OK; } /* ** This function is called when initializing an FTS4 table that uses the ** content=xxx option. It determines the number of and names of the columns ** of the new FTS4 table. ** ** The third argument passed to this function is the value passed to the ** config=xxx option (i.e. "xxx"). This function queries the database for ** a table of that name. If found, the output variables are populated ** as follows: ** ** *pnCol: Set to the number of columns table xxx has, ** ** *pnStr: Set to the total amount of space required to store a copy ** of each columns name, including the nul-terminator. ** ** *pazCol: Set to point to an array of *pnCol strings. Each string is ** the name of the corresponding column in table xxx. The array ** and its contents are allocated using a single allocation. It ** is the responsibility of the caller to free this allocation ** by eventually passing the *pazCol value to sqlite3_free(). ** ** If the table cannot be found, an error code is returned and the output ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is ** returned (and the output variables are undefined). */ static int fts3ContentColumns( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */ const char *zTbl, /* Name of content table */ const char ***pazCol, /* OUT: Malloc'd array of column names */ int *pnCol, /* OUT: Size of array *pazCol */ int *pnStr, /* OUT: Bytes of string content */ char **pzErr /* OUT: error message */ ){ int rc = SQLITE_OK; /* Return code */ char *zSql; /* "SELECT *" statement on zTbl */ sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */ zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl); if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db)); } } sqlite3_free(zSql); if( rc==SQLITE_OK ){ const char **azCol; /* Output array */ int nStr = 0; /* Size of all column names (incl. 0x00) */ int nCol; /* Number of table columns */ int i; /* Used to iterate through columns */ /* Loop through the returned columns. Set nStr to the number of bytes of ** space required to store a copy of each column name, including the ** nul-terminator byte. */ nCol = sqlite3_column_count(pStmt); for(i=0; i<nCol; i++){ const char *zCol = sqlite3_column_name(pStmt, i); nStr += (int)strlen(zCol) + 1; } /* Allocate and populate the array to return. */ azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr); if( azCol==0 ){ rc = SQLITE_NOMEM; }else{ char *p = (char *)&azCol[nCol]; for(i=0; i<nCol; i++){ const char *zCol = sqlite3_column_name(pStmt, i); int n = (int)strlen(zCol)+1; memcpy(p, zCol, n); azCol[i] = p; p += n; } } sqlite3_finalize(pStmt); /* Set the output variables. */ *pnCol = nCol; *pnStr = nStr; *pazCol = azCol; } return rc; } /* ** This function is the implementation of both the xConnect and xCreate ** methods of the FTS3 virtual table. ** ** The argv[] array contains the following: ** ** argv[0] -> module name ("fts3" or "fts4") ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> "column name" and other module argument fields. */ static int fts3InitVtab( int isCreate, /* True for xCreate, false for xConnect */ sqlite3 *db, /* The SQLite database connection */ void *pAux, /* Hash table containing tokenizers */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ char **pzErr /* Write any error message here */ ){ Fts3Hash *pHash = (Fts3Hash *)pAux; Fts3Table *p = 0; /* Pointer to allocated vtab */ int rc = SQLITE_OK; /* Return code */ int i; /* Iterator variable */ int nByte; /* Size of allocation used for *p */ int iCol; /* Column index */ int nString = 0; /* Bytes required to hold all column names */ int nCol = 0; /* Number of columns in the FTS table */ char *zCsr; /* Space for holding column names */ int nDb; /* Bytes required to hold database name */ int nName; /* Bytes required to hold table name */ int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */ const char **aCol; /* Array of column names */ sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ int nIndex = 0; /* Size of aIndex[] array */ struct Fts3Index *aIndex = 0; /* Array of indexes for this table */ /* The results of parsing supported FTS4 key=value options: */ int bNoDocsize = 0; /* True to omit %_docsize table */ int bDescIdx = 0; /* True to store descending indexes */ char *zPrefix = 0; /* Prefix parameter value (or NULL) */ char *zCompress = 0; /* compress=? parameter (or NULL) */ char *zUncompress = 0; /* uncompress=? parameter (or NULL) */ char *zContent = 0; /* content=? parameter (or NULL) */ char *zLanguageid = 0; /* languageid=? parameter (or NULL) */ char **azNotindexed = 0; /* The set of notindexed= columns */ int nNotindexed = 0; /* Size of azNotindexed[] array */ assert( strlen(argv[0])==4 ); assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) ); nDb = (int)strlen(argv[1]) + 1; nName = (int)strlen(argv[2]) + 1; nByte = sizeof(const char *) * (argc-2); aCol = (const char **)sqlite3_malloc(nByte); if( aCol ){ memset((void*)aCol, 0, nByte); azNotindexed = (char **)sqlite3_malloc(nByte); } if( azNotindexed ){ memset(azNotindexed, 0, nByte); } if( !aCol || !azNotindexed ){ rc = SQLITE_NOMEM; goto fts3_init_out; } /* Loop through all of the arguments passed by the user to the FTS3/4 ** module (i.e. all the column names and special arguments). This loop ** does the following: ** ** + Figures out the number of columns the FTSX table will have, and ** the number of bytes of space that must be allocated to store copies ** of the column names. ** ** + If there is a tokenizer specification included in the arguments, ** initializes the tokenizer pTokenizer. */ for(i=3; rc==SQLITE_OK && i<argc; i++){ char const *z = argv[i]; int nKey; char *zVal; /* Check if this is a tokenizer specification */ if( !pTokenizer && strlen(z)>8 && 0==sqlite3_strnicmp(z, "tokenize", 8) && 0==sqlite3Fts3IsIdChar(z[8]) ){ rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); } /* Check if it is an FTS4 special argument. */ else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){ struct Fts4Option { const char *zOpt; int nOpt; } aFts4Opt[] = { { "matchinfo", 9 }, /* 0 -> MATCHINFO */ { "prefix", 6 }, /* 1 -> PREFIX */ { "compress", 8 }, /* 2 -> COMPRESS */ { "uncompress", 10 }, /* 3 -> UNCOMPRESS */ { "order", 5 }, /* 4 -> ORDER */ { "content", 7 }, /* 5 -> CONTENT */ { "languageid", 10 }, /* 6 -> LANGUAGEID */ { "notindexed", 10 } /* 7 -> NOTINDEXED */ }; int iOpt; if( !zVal ){ rc = SQLITE_NOMEM; }else{ for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){ struct Fts4Option *pOp = &aFts4Opt[iOpt]; if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){ break; } } if( iOpt==SizeofArray(aFts4Opt) ){ sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z); rc = SQLITE_ERROR; }else{ switch( iOpt ){ case 0: /* MATCHINFO */ if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){ sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal); rc = SQLITE_ERROR; } bNoDocsize = 1; break; case 1: /* PREFIX */ sqlite3_free(zPrefix); zPrefix = zVal; zVal = 0; break; case 2: /* COMPRESS */ sqlite3_free(zCompress); zCompress = zVal; zVal = 0; break; case 3: /* UNCOMPRESS */ sqlite3_free(zUncompress); zUncompress = zVal; zVal = 0; break; case 4: /* ORDER */ if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) ){ sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal); rc = SQLITE_ERROR; } bDescIdx = (zVal[0]=='d' || zVal[0]=='D'); break; case 5: /* CONTENT */ sqlite3_free(zContent); zContent = zVal; zVal = 0; break; case 6: /* LANGUAGEID */ assert( iOpt==6 ); sqlite3_free(zLanguageid); zLanguageid = zVal; zVal = 0; break; case 7: /* NOTINDEXED */ azNotindexed[nNotindexed++] = zVal; zVal = 0; break; } } sqlite3_free(zVal); } } /* Otherwise, the argument is a column name. */ else { nString += (int)(strlen(z) + 1); aCol[nCol++] = z; } } /* If a content=xxx option was specified, the following: ** ** 1. Ignore any compress= and uncompress= options. ** ** 2. If no column names were specified as part of the CREATE VIRTUAL ** TABLE statement, use all columns from the content table. */ if( rc==SQLITE_OK && zContent ){ sqlite3_free(zCompress); sqlite3_free(zUncompress); zCompress = 0; zUncompress = 0; if( nCol==0 ){ sqlite3_free((void*)aCol); aCol = 0; rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr); /* If a languageid= option was specified, remove the language id ** column from the aCol[] array. */ if( rc==SQLITE_OK && zLanguageid ){ int j; for(j=0; j<nCol; j++){ if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){ int k; for(k=j; k<nCol; k++) aCol[k] = aCol[k+1]; nCol--; break; } } } } } if( rc!=SQLITE_OK ) goto fts3_init_out; if( nCol==0 ){ assert( nString==0 ); aCol[0] = "content"; nString = 8; nCol = 1; } if( pTokenizer==0 ){ rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr); if( rc!=SQLITE_OK ) goto fts3_init_out; } assert( pTokenizer ); rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex); if( rc==SQLITE_ERROR ){ assert( zPrefix ); sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix); } if( rc!=SQLITE_OK ) goto fts3_init_out; /* Allocate and populate the Fts3Table structure. */ nByte = sizeof(Fts3Table) + /* Fts3Table */ nCol * sizeof(char *) + /* azColumn */ nIndex * sizeof(struct Fts3Index) + /* aIndex */ nCol * sizeof(u8) + /* abNotindexed */ nName + /* zName */ nDb + /* zDb */ nString; /* Space for azColumn strings */ p = (Fts3Table*)sqlite3_malloc(nByte); if( p==0 ){ rc = SQLITE_NOMEM; goto fts3_init_out; } memset(p, 0, nByte); p->db = db; p->nColumn = nCol; p->nPendingData = 0; p->azColumn = (char **)&p[1]; p->pTokenizer = pTokenizer; p->nMaxPendingData = FTS3_MAX_PENDING_DATA; p->bHasDocsize = (isFts4 && bNoDocsize==0); p->bHasStat = (u8)isFts4; p->bFts4 = (u8)isFts4; p->bDescIdx = (u8)bDescIdx; p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */ p->zContentTbl = zContent; p->zLanguageid = zLanguageid; zContent = 0; zLanguageid = 0; TESTONLY( p->inTransaction = -1 ); TESTONLY( p->mxSavepoint = -1 ); p->aIndex = (struct Fts3Index *)&p->azColumn[nCol]; memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex); p->nIndex = nIndex; for(i=0; i<nIndex; i++){ fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1); } p->abNotindexed = (u8 *)&p->aIndex[nIndex]; /* Fill in the zName and zDb fields of the vtab structure. */ zCsr = (char *)&p->abNotindexed[nCol]; p->zName = zCsr; memcpy(zCsr, argv[2], nName); zCsr += nName; p->zDb = zCsr; memcpy(zCsr, argv[1], nDb); zCsr += nDb; /* Fill in the azColumn array */ for(iCol=0; iCol<nCol; iCol++){ char *z; int n = 0; z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n); memcpy(zCsr, z, n); zCsr[n] = '\0'; sqlite3Fts3Dequote(zCsr); p->azColumn[iCol] = zCsr; zCsr += n+1; assert( zCsr <= &((char *)p)[nByte] ); } /* Fill in the abNotindexed array */ for(iCol=0; iCol<nCol; iCol++){ int n = (int)strlen(p->azColumn[iCol]); for(i=0; i<nNotindexed; i++){ char *zNot = azNotindexed[i]; if( zNot && n==(int)strlen(zNot) && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){ p->abNotindexed[iCol] = 1; sqlite3_free(zNot); azNotindexed[i] = 0; } } } for(i=0; i<nNotindexed; i++){ if( azNotindexed[i] ){ sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]); rc = SQLITE_ERROR; } } if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){ char const *zMiss = (zCompress==0 ? "compress" : "uncompress"); rc = SQLITE_ERROR; sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss); } p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc); p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc); if( rc!=SQLITE_OK ) goto fts3_init_out; /* If this is an xCreate call, create the underlying tables in the ** database. TODO: For xConnect(), it could verify that said tables exist. */ if( isCreate ){ rc = fts3CreateTables(p); } /* Check to see if a legacy fts3 table has been "upgraded" by the ** addition of a %_stat table so that it can use incremental merge. */ if( !isFts4 && !isCreate ){ p->bHasStat = 2; } /* Figure out the page-size for the database. This is required in order to ** estimate the cost of loading large doclists from the database. */ fts3DatabasePageSize(&rc, p); p->nNodeSize = p->nPgsz-35; /* Declare the table schema to SQLite. */ fts3DeclareVtab(&rc, p); fts3_init_out: sqlite3_free(zPrefix); sqlite3_free(aIndex); sqlite3_free(zCompress); sqlite3_free(zUncompress); sqlite3_free(zContent); sqlite3_free(zLanguageid); for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]); sqlite3_free((void *)aCol); sqlite3_free((void *)azNotindexed); if( rc!=SQLITE_OK ){ if( p ){ fts3DisconnectMethod((sqlite3_vtab *)p); }else if( pTokenizer ){ pTokenizer->pModule->xDestroy(pTokenizer); } }else{ assert( p->pSegments==0 ); *ppVTab = &p->base; } return rc; } /* ** The xConnect() and xCreate() methods for the virtual table. All the ** work is done in function fts3InitVtab(). */ static int fts3ConnectMethod( sqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); } static int fts3CreateMethod( sqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); } /* ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this ** extension is currently being used by a version of SQLite too old to ** support estimatedRows. In that case this function is a no-op. */ static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ #if SQLITE_VERSION_NUMBER>=3008002 if( sqlite3_libversion_number()>=3008002 ){ pIdxInfo->estimatedRows = nRow; } #endif } /* ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this ** extension is currently being used by a version of SQLite too old to ** support index-info flags. In that case this function is a no-op. */ static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){ #if SQLITE_VERSION_NUMBER>=3008012 if( sqlite3_libversion_number()>=3008012 ){ pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE; } #endif } /* ** Implementation of the xBestIndex method for FTS3 tables. There ** are three possible strategies, in order of preference: ** ** 1. Direct lookup by rowid or docid. ** 2. Full-text search using a MATCH operator on a non-docid column. ** 3. Linear scan of %_content table. */ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ Fts3Table *p = (Fts3Table *)pVTab; int i; /* Iterator variable */ int iCons = -1; /* Index of constraint to use */ int iLangidCons = -1; /* Index of langid=x constraint, if present */ int iDocidGe = -1; /* Index of docid>=x constraint, if present */ int iDocidLe = -1; /* Index of docid<=x constraint, if present */ int iIdx; /* By default use a full table scan. This is an expensive option, ** so search through the constraints to see if a more efficient ** strategy is possible. */ pInfo->idxNum = FTS3_FULLSCAN_SEARCH; pInfo->estimatedCost = 5000000; for(i=0; i<pInfo->nConstraint; i++){ int bDocid; /* True if this constraint is on docid */ struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; if( pCons->usable==0 ){ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ /* There exists an unusable MATCH constraint. This means that if ** the planner does elect to use the results of this call as part ** of the overall query plan the user will see an "unable to use ** function MATCH in the requested context" error. To discourage ** this, return a very high cost here. */ pInfo->idxNum = FTS3_FULLSCAN_SEARCH; pInfo->estimatedCost = 1e50; fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50); return SQLITE_OK; } continue; } bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1); /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */ if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){ pInfo->idxNum = FTS3_DOCID_SEARCH; pInfo->estimatedCost = 1.0; iCons = i; } /* A MATCH constraint. Use a full-text search. ** ** If there is more than one MATCH constraint available, use the first ** one encountered. If there is both a MATCH constraint and a direct ** rowid/docid lookup, prefer the MATCH strategy. This is done even ** though the rowid/docid lookup is faster than a MATCH query, selecting ** it would lead to an "unable to use function MATCH in the requested ** context" error. */ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn ){ pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn; pInfo->estimatedCost = 2.0; iCons = i; } /* Equality constraint on the langid column */ if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && pCons->iColumn==p->nColumn + 2 ){ iLangidCons = i; } if( bDocid ){ switch( pCons->op ){ case SQLITE_INDEX_CONSTRAINT_GE: case SQLITE_INDEX_CONSTRAINT_GT: iDocidGe = i; break; case SQLITE_INDEX_CONSTRAINT_LE: case SQLITE_INDEX_CONSTRAINT_LT: iDocidLe = i; break; } } } /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */ if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo); iIdx = 1; if( iCons>=0 ){ pInfo->aConstraintUsage[iCons].argvIndex = iIdx++; pInfo->aConstraintUsage[iCons].omit = 1; } if( iLangidCons>=0 ){ pInfo->idxNum |= FTS3_HAVE_LANGID; pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++; } if( iDocidGe>=0 ){ pInfo->idxNum |= FTS3_HAVE_DOCID_GE; pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++; } if( iDocidLe>=0 ){ pInfo->idxNum |= FTS3_HAVE_DOCID_LE; pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++; } /* Regardless of the strategy selected, FTS can deliver rows in rowid (or ** docid) order. Both ascending and descending are possible. */ if( pInfo->nOrderBy==1 ){ struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){ if( pOrder->desc ){ pInfo->idxStr = "DESC"; }else{ pInfo->idxStr = "ASC"; } pInfo->orderByConsumed = 1; } } assert( p->pSegments==0 ); return SQLITE_OK; } /* ** Implementation of xOpen method. */ static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ sqlite3_vtab_cursor *pCsr; /* Allocated cursor */ UNUSED_PARAMETER(pVTab); /* Allocate a buffer large enough for an Fts3Cursor structure. If the ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, ** if the allocation fails, return SQLITE_NOMEM. */ *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor)); if( !pCsr ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(Fts3Cursor)); return SQLITE_OK; } /* ** Finalize the statement handle at pCsr->pStmt. ** ** Or, if that statement handle is one created by fts3CursorSeekStmt(), ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement ** pointer there instead of finalizing it. */ static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){ if( pCsr->bSeekStmt ){ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; if( p->pSeekStmt==0 ){ p->pSeekStmt = pCsr->pStmt; sqlite3_reset(pCsr->pStmt); pCsr->pStmt = 0; } pCsr->bSeekStmt = 0; } sqlite3_finalize(pCsr->pStmt); } /* ** Close the cursor. For additional information see the documentation ** on the xClose method of the virtual table interface. */ static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); fts3CursorFinalizeStmt(pCsr); sqlite3Fts3ExprFree(pCsr->pExpr); sqlite3Fts3FreeDeferredTokens(pCsr); sqlite3_free(pCsr->aDoclist); sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); sqlite3_free(pCsr); return SQLITE_OK; } /* ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then ** compose and prepare an SQL statement of the form: ** ** "SELECT <columns> FROM %_content WHERE rowid = ?" ** ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to ** it. If an error occurs, return an SQLite error code. */ static int fts3CursorSeekStmt(Fts3Cursor *pCsr){ int rc = SQLITE_OK; if( pCsr->pStmt==0 ){ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; char *zSql; if( p->pSeekStmt ){ pCsr->pStmt = p->pSeekStmt; p->pSeekStmt = 0; }else{ zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); if( !zSql ) return SQLITE_NOMEM; rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); sqlite3_free(zSql); } if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1; } return rc; } /* ** Position the pCsr->pStmt statement so that it is on the row ** of the %_content table that contains the last match. Return ** SQLITE_OK on success. */ static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ int rc = SQLITE_OK; if( pCsr->isRequireSeek ){ rc = fts3CursorSeekStmt(pCsr); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); pCsr->isRequireSeek = 0; if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ return SQLITE_OK; }else{ rc = sqlite3_reset(pCsr->pStmt); if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){ /* If no row was found and no error has occurred, then the %_content ** table is missing a row that is present in the full-text index. ** The data structures are corrupt. */ rc = FTS_CORRUPT_VTAB; pCsr->isEof = 1; } } } } if( rc!=SQLITE_OK && pContext ){ sqlite3_result_error_code(pContext, rc); } return rc; } /* ** This function is used to process a single interior node when searching ** a b-tree for a term or term prefix. The node data is passed to this ** function via the zNode/nNode parameters. The term to search for is ** passed in zTerm/nTerm. ** ** If piFirst is not NULL, then this function sets *piFirst to the blockid ** of the child node that heads the sub-tree that may contain the term. ** ** If piLast is not NULL, then *piLast is set to the right-most child node ** that heads a sub-tree that may contain a term for which zTerm/nTerm is ** a prefix. ** ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK. */ static int fts3ScanInteriorNode( const char *zTerm, /* Term to select leaves for */ int nTerm, /* Size of term zTerm in bytes */ const char *zNode, /* Buffer containing segment interior node */ int nNode, /* Size of buffer at zNode */ sqlite3_int64 *piFirst, /* OUT: Selected child node */ sqlite3_int64 *piLast /* OUT: Selected child node */ ){ int rc = SQLITE_OK; /* Return code */ const char *zCsr = zNode; /* Cursor to iterate through node */ const char *zEnd = &zCsr[nNode];/* End of interior node buffer */ char *zBuffer = 0; /* Buffer to load terms into */ int nAlloc = 0; /* Size of allocated buffer */ int isFirstTerm = 1; /* True when processing first term on page */ sqlite3_int64 iChild; /* Block id of child node to descend to */ /* Skip over the 'height' varint that occurs at the start of every ** interior node. Then load the blockid of the left-child of the b-tree ** node into variable iChild. ** ** Even if the data structure on disk is corrupted, this (reading two ** varints from the buffer) does not risk an overread. If zNode is a ** root node, then the buffer comes from a SELECT statement. SQLite does ** not make this guarantee explicitly, but in practice there are always ** either more than 20 bytes of allocated space following the nNode bytes of ** contents, or two zero bytes. Or, if the node is read from the %_segments ** table, then there are always 20 bytes of zeroed padding following the ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details). */ zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); if( zCsr>zEnd ){ return FTS_CORRUPT_VTAB; } while( zCsr<zEnd && (piFirst || piLast) ){ int cmp; /* memcmp() result */ int nSuffix; /* Size of term suffix */ int nPrefix = 0; /* Size of term prefix */ int nBuffer; /* Total term size */ /* Load the next term on the node into zBuffer. Use realloc() to expand ** the size of zBuffer if required. */ if( !isFirstTerm ){ zCsr += fts3GetVarint32(zCsr, &nPrefix); } isFirstTerm = 0; zCsr += fts3GetVarint32(zCsr, &nSuffix); if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){ rc = FTS_CORRUPT_VTAB; goto finish_scan; } if( nPrefix+nSuffix>nAlloc ){ char *zNew; nAlloc = (nPrefix+nSuffix) * 2; zNew = (char *)sqlite3_realloc(zBuffer, nAlloc); if( !zNew ){ rc = SQLITE_NOMEM; goto finish_scan; } zBuffer = zNew; } assert( zBuffer ); memcpy(&zBuffer[nPrefix], zCsr, nSuffix); nBuffer = nPrefix + nSuffix; zCsr += nSuffix; /* Compare the term we are searching for with the term just loaded from ** the interior node. If the specified term is greater than or equal ** to the term from the interior node, then all terms on the sub-tree ** headed by node iChild are smaller than zTerm. No need to search ** iChild. ** ** If the interior node term is larger than the specified term, then ** the tree headed by iChild may contain the specified term. */ cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer)); if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){ *piFirst = iChild; piFirst = 0; } if( piLast && cmp<0 ){ *piLast = iChild; piLast = 0; } iChild++; }; if( piFirst ) *piFirst = iChild; if( piLast ) *piLast = iChild; finish_scan: sqlite3_free(zBuffer); return rc; } /* ** The buffer pointed to by argument zNode (size nNode bytes) contains an ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes) ** contains a term. This function searches the sub-tree headed by the zNode ** node for the range of leaf nodes that may contain the specified term ** or terms for which the specified term is a prefix. ** ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the ** left-most leaf node in the tree that may contain the specified term. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the ** right-most leaf node that may contain a term for which the specified ** term is a prefix. ** ** It is possible that the range of returned leaf nodes does not contain ** the specified term or any terms for which it is a prefix. However, if the ** segment does contain any such terms, they are stored within the identified ** range. Because this function only inspects interior segment nodes (and ** never loads leaf nodes into memory), it is not possible to be sure. ** ** If an error occurs, an error code other than SQLITE_OK is returned. */ static int fts3SelectLeaf( Fts3Table *p, /* Virtual table handle */ const char *zTerm, /* Term to select leaves for */ int nTerm, /* Size of term zTerm in bytes */ const char *zNode, /* Buffer containing segment interior node */ int nNode, /* Size of buffer at zNode */ sqlite3_int64 *piLeaf, /* Selected leaf node */ sqlite3_int64 *piLeaf2 /* Selected leaf node */ ){ int rc = SQLITE_OK; /* Return code */ int iHeight; /* Height of this node in tree */ assert( piLeaf || piLeaf2 ); fts3GetVarint32(zNode, &iHeight); rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); if( rc==SQLITE_OK && iHeight>1 ){ char *zBlob = 0; /* Blob read from %_segments table */ int nBlob = 0; /* Size of zBlob in bytes */ if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); if( rc==SQLITE_OK ){ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); } sqlite3_free(zBlob); piLeaf = 0; zBlob = 0; } if( rc==SQLITE_OK ){ rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); } if( rc==SQLITE_OK ){ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); } sqlite3_free(zBlob); } return rc; } /* ** This function is used to create delta-encoded serialized lists of FTS3 ** varints. Each call to this function appends a single varint to a list. */ static void fts3PutDeltaVarint( char **pp, /* IN/OUT: Output pointer */ sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ sqlite3_int64 iVal /* Write this value to the list */ ){ assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); *piPrev = iVal; } /* ** When this function is called, *ppPoslist is assumed to point to the ** start of a position-list. After it returns, *ppPoslist points to the ** first byte after the position-list. ** ** A position list is list of positions (delta encoded) and columns for ** a single document record of a doclist. So, in other words, this ** routine advances *ppPoslist so that it points to the next docid in ** the doclist, or to the first byte past the end of the doclist. ** ** If pp is not NULL, then the contents of the position list are copied ** to *pp. *pp is set to point to the first byte past the last byte copied ** before this function returns. */ static void fts3PoslistCopy(char **pp, char **ppPoslist){ char *pEnd = *ppPoslist; char c = 0; /* The end of a position list is marked by a zero encoded as an FTS3 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail ** of some other, multi-byte, value. ** ** The following while-loop moves pEnd to point to the first byte that is not ** immediately preceded by a byte with the 0x80 bit set. Then increments ** pEnd once more so that it points to the byte immediately following the ** last byte in the position-list. */ while( *pEnd | c ){ c = *pEnd++ & 0x80; testcase( c!=0 && (*pEnd)==0 ); } pEnd++; /* Advance past the POS_END terminator byte */ if( pp ){ int n = (int)(pEnd - *ppPoslist); char *p = *pp; memcpy(p, *ppPoslist, n); p += n; *pp = p; } *ppPoslist = pEnd; } /* ** When this function is called, *ppPoslist is assumed to point to the ** start of a column-list. After it returns, *ppPoslist points to the ** to the terminator (POS_COLUMN or POS_END) byte of the column-list. ** ** A column-list is list of delta-encoded positions for a single column ** within a single document within a doclist. ** ** The column-list is terminated either by a POS_COLUMN varint (1) or ** a POS_END varint (0). This routine leaves *ppPoslist pointing to ** the POS_COLUMN or POS_END that terminates the column-list. ** ** If pp is not NULL, then the contents of the column-list are copied ** to *pp. *pp is set to point to the first byte past the last byte copied ** before this function returns. The POS_COLUMN or POS_END terminator ** is not copied into *pp. */ static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ char *pEnd = *ppPoslist; char c = 0; /* A column-list is terminated by either a 0x01 or 0x00 byte that is ** not part of a multi-byte varint. */ while( 0xFE & (*pEnd | c) ){ c = *pEnd++ & 0x80; testcase( c!=0 && ((*pEnd)&0xfe)==0 ); } if( pp ){ int n = (int)(pEnd - *ppPoslist); char *p = *pp; memcpy(p, *ppPoslist, n); p += n; *pp = p; } *ppPoslist = pEnd; } /* ** Value used to signify the end of an position-list. This is safe because ** it is not possible to have a document with 2^31 terms. */ #define POSITION_LIST_END 0x7fffffff /* ** This function is used to help parse position-lists. When this function is ** called, *pp may point to the start of the next varint in the position-list ** being parsed, or it may point to 1 byte past the end of the position-list ** (in which case **pp will be a terminator bytes POS_END (0) or ** (1)). ** ** If *pp points past the end of the current position-list, set *pi to ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp, ** increment the current value of *pi by the value read, and set *pp to ** point to the next value before returning. ** ** Before calling this routine *pi must be initialized to the value of ** the previous position, or zero if we are reading the first position ** in the position-list. Because positions are delta-encoded, the value ** of the previous position is needed in order to compute the value of ** the next position. */ static void fts3ReadNextPos( char **pp, /* IN/OUT: Pointer into position-list buffer */ sqlite3_int64 *pi /* IN/OUT: Value read from position-list */ ){ if( (**pp)&0xFE ){ fts3GetDeltaVarint(pp, pi); *pi -= 2; }else{ *pi = POSITION_LIST_END; } } /* ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by ** the value of iCol encoded as a varint to *pp. This will start a new ** column list. ** ** Set *pp to point to the byte just after the last byte written before ** returning (do not modify it if iCol==0). Return the total number of bytes ** written (0 if iCol==0). */ static int fts3PutColNumber(char **pp, int iCol){ int n = 0; /* Number of bytes written */ if( iCol ){ char *p = *pp; /* Output pointer */ n = 1 + sqlite3Fts3PutVarint(&p[1], iCol); *p = 0x01; *pp = &p[n]; } return n; } /* ** Compute the union of two position lists. The output written ** into *pp contains all positions of both *pp1 and *pp2 in sorted ** order and with any duplicates removed. All pointers are ** updated appropriately. The caller is responsible for insuring ** that there is enough space in *pp to hold the complete output. */ static void fts3PoslistMerge( char **pp, /* Output buffer */ char **pp1, /* Left input list */ char **pp2 /* Right input list */ ){ char *p = *pp; char *p1 = *pp1; char *p2 = *pp2; while( *p1 || *p2 ){ int iCol1; /* The current column index in pp1 */ int iCol2; /* The current column index in pp2 */ if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1); else if( *p1==POS_END ) iCol1 = POSITION_LIST_END; else iCol1 = 0; if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2); else if( *p2==POS_END ) iCol2 = POSITION_LIST_END; else iCol2 = 0; if( iCol1==iCol2 ){ sqlite3_int64 i1 = 0; /* Last position from pp1 */ sqlite3_int64 i2 = 0; /* Last position from pp2 */ sqlite3_int64 iPrev = 0; int n = fts3PutColNumber(&p, iCol1); p1 += n; p2 += n; /* At this point, both p1 and p2 point to the start of column-lists ** for the same column (the column with index iCol1 and iCol2). ** A column-list is a list of non-negative delta-encoded varints, each ** incremented by 2 before being stored. Each list is terminated by a ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists ** and writes the results to buffer p. p is left pointing to the byte ** after the list written. No terminator (POS_END or POS_COLUMN) is ** written to the output. */ fts3GetDeltaVarint(&p1, &i1); fts3GetDeltaVarint(&p2, &i2); do { fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); iPrev -= 2; if( i1==i2 ){ fts3ReadNextPos(&p1, &i1); fts3ReadNextPos(&p2, &i2); }else if( i1<i2 ){ fts3ReadNextPos(&p1, &i1); }else{ fts3ReadNextPos(&p2, &i2); } }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END ); }else if( iCol1<iCol2 ){ p1 += fts3PutColNumber(&p, iCol1); fts3ColumnlistCopy(&p, &p1); }else{ p2 += fts3PutColNumber(&p, iCol2); fts3ColumnlistCopy(&p, &p2); } } *p++ = POS_END; *pp = p; *pp1 = p1 + 1; *pp2 = p2 + 1; } /* ** This function is used to merge two position lists into one. When it is ** called, *pp1 and *pp2 must both point to position lists. A position-list is ** the part of a doclist that follows each document id. For example, if a row ** contains: ** ** 'a b c'|'x y z'|'a b b a' ** ** Then the position list for this row for token 'b' would consist of: ** ** 0x02 0x01 0x02 0x03 0x03 0x00 ** ** When this function returns, both *pp1 and *pp2 are left pointing to the ** byte following the 0x00 terminator of their respective position lists. ** ** If isSaveLeft is 0, an entry is added to the output position list for ** each position in *pp2 for which there exists one or more positions in ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e. ** when the *pp1 token appears before the *pp2 token, but not more than nToken ** slots before it. ** ** e.g. nToken==1 searches for adjacent positions. */ static int fts3PoslistPhraseMerge( char **pp, /* IN/OUT: Preallocated output buffer */ int nToken, /* Maximum difference in token positions */ int isSaveLeft, /* Save the left position */ int isExact, /* If *pp1 is exactly nTokens before *pp2 */ char **pp1, /* IN/OUT: Left input list */ char **pp2 /* IN/OUT: Right input list */ ){ char *p = *pp; char *p1 = *pp1; char *p2 = *pp2; int iCol1 = 0; int iCol2 = 0; /* Never set both isSaveLeft and isExact for the same invocation. */ assert( isSaveLeft==0 || isExact==0 ); assert( p!=0 && *p1!=0 && *p2!=0 ); if( *p1==POS_COLUMN ){ p1++; p1 += fts3GetVarint32(p1, &iCol1); } if( *p2==POS_COLUMN ){ p2++; p2 += fts3GetVarint32(p2, &iCol2); } while( 1 ){ if( iCol1==iCol2 ){ char *pSave = p; sqlite3_int64 iPrev = 0; sqlite3_int64 iPos1 = 0; sqlite3_int64 iPos2 = 0; if( iCol1 ){ *p++ = POS_COLUMN; p += sqlite3Fts3PutVarint(p, iCol1); } assert( *p1!=POS_END && *p1!=POS_COLUMN ); assert( *p2!=POS_END && *p2!=POS_COLUMN ); fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; while( 1 ){ if( iPos2==iPos1+nToken || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) ){ sqlite3_int64 iSave; iSave = isSaveLeft ? iPos1 : iPos2; fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2; pSave = 0; assert( p ); } if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){ if( (*p2&0xFE)==0 ) break; fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; }else{ if( (*p1&0xFE)==0 ) break; fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; } } if( pSave ){ assert( pp && p ); p = pSave; } fts3ColumnlistCopy(0, &p1); fts3ColumnlistCopy(0, &p2); assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 ); if( 0==*p1 || 0==*p2 ) break; p1++; p1 += fts3GetVarint32(p1, &iCol1); p2++; p2 += fts3GetVarint32(p2, &iCol2); } /* Advance pointer p1 or p2 (whichever corresponds to the smaller of ** iCol1 and iCol2) so that it points to either the 0x00 that marks the ** end of the position list, or the 0x01 that precedes the next ** column-number in the position list. */ else if( iCol1<iCol2 ){ fts3ColumnlistCopy(0, &p1); if( 0==*p1 ) break; p1++; p1 += fts3GetVarint32(p1, &iCol1); }else{ fts3ColumnlistCopy(0, &p2); if( 0==*p2 ) break; p2++; p2 += fts3GetVarint32(p2, &iCol2); } } fts3PoslistCopy(0, &p2); fts3PoslistCopy(0, &p1); *pp1 = p1; *pp2 = p2; if( *pp==p ){ return 0; } *p++ = 0x00; *pp = p; return 1; } /* ** Merge two position-lists as required by the NEAR operator. The argument ** position lists correspond to the left and right phrases of an expression ** like: ** ** "phrase 1" NEAR "phrase number 2" ** ** Position list *pp1 corresponds to the left-hand side of the NEAR ** expression and *pp2 to the right. As usual, the indexes in the position ** lists are the offsets of the last token in each phrase (tokens "1" and "2" ** in the example above). ** ** The output position list - written to *pp - is a copy of *pp2 with those ** entries that are not sufficiently NEAR entries in *pp1 removed. */ static int fts3PoslistNearMerge( char **pp, /* Output buffer */ char *aTmp, /* Temporary buffer space */ int nRight, /* Maximum difference in token positions */ int nLeft, /* Maximum difference in token positions */ char **pp1, /* IN/OUT: Left input list */ char **pp2 /* IN/OUT: Right input list */ ){ char *p1 = *pp1; char *p2 = *pp2; char *pTmp1 = aTmp; char *pTmp2; char *aTmp2; int res = 1; fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2); aTmp2 = pTmp2 = pTmp1; *pp1 = p1; *pp2 = p2; fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1); if( pTmp1!=aTmp && pTmp2!=aTmp2 ){ fts3PoslistMerge(pp, &aTmp, &aTmp2); }else if( pTmp1!=aTmp ){ fts3PoslistCopy(pp, &aTmp); }else if( pTmp2!=aTmp2 ){ fts3PoslistCopy(pp, &aTmp2); }else{ res = 0; } return res; } /* ** An instance of this function is used to merge together the (potentially ** large number of) doclists for each term that matches a prefix query. ** See function fts3TermSelectMerge() for details. */ typedef struct TermSelect TermSelect; struct TermSelect { char *aaOutput[16]; /* Malloc'd output buffers */ int anOutput[16]; /* Size each output buffer in bytes */ }; /* ** This function is used to read a single varint from a buffer. Parameter ** pEnd points 1 byte past the end of the buffer. When this function is ** called, if *pp points to pEnd or greater, then the end of the buffer ** has been reached. In this case *pp is set to 0 and the function returns. ** ** If *pp does not point to or past pEnd, then a single varint is read ** from *pp. *pp is then set to point 1 byte past the end of the read varint. ** ** If bDescIdx is false, the value read is added to *pVal before returning. ** If it is true, the value read is subtracted from *pVal before this ** function returns. */ static void fts3GetDeltaVarint3( char **pp, /* IN/OUT: Point to read varint from */ char *pEnd, /* End of buffer */ int bDescIdx, /* True if docids are descending */ sqlite3_int64 *pVal /* IN/OUT: Integer value */ ){ if( *pp>=pEnd ){ *pp = 0; }else{ sqlite3_int64 iVal; *pp += sqlite3Fts3GetVarint(*pp, &iVal); if( bDescIdx ){ *pVal -= iVal; }else{ *pVal += iVal; } } } /* ** This function is used to write a single varint to a buffer. The varint ** is written to *pp. Before returning, *pp is set to point 1 byte past the ** end of the value written. ** ** If *pbFirst is zero when this function is called, the value written to ** the buffer is that of parameter iVal. ** ** If *pbFirst is non-zero when this function is called, then the value ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal) ** (if bDescIdx is non-zero). ** ** Before returning, this function always sets *pbFirst to 1 and *piPrev ** to the value of parameter iVal. */ static void fts3PutDeltaVarint3( char **pp, /* IN/OUT: Output pointer */ int bDescIdx, /* True for descending docids */ sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ int *pbFirst, /* IN/OUT: True after first int written */ sqlite3_int64 iVal /* Write this value to the list */ ){ sqlite3_int64 iWrite; if( bDescIdx==0 || *pbFirst==0 ){ iWrite = iVal - *piPrev; }else{ iWrite = *piPrev - iVal; } assert( *pbFirst || *piPrev==0 ); assert( *pbFirst==0 || iWrite>0 ); *pp += sqlite3Fts3PutVarint(*pp, iWrite); *piPrev = iVal; *pbFirst = 1; } /* ** This macro is used by various functions that merge doclists. The two ** arguments are 64-bit docid values. If the value of the stack variable ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). ** Otherwise, (i2-i1). ** ** Using this makes it easier to write code that can merge doclists that are ** sorted in either ascending or descending order. */ #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2)) /* ** This function does an "OR" merge of two doclists (output contains all ** positions contained in either argument doclist). If the docids in the ** input doclists are sorted in ascending order, parameter bDescDoclist ** should be false. If they are sorted in ascending order, it should be ** passed a non-zero value. ** ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer ** containing the output doclist and SQLITE_OK is returned. In this case ** *pnOut is set to the number of bytes in the output doclist. ** ** If an error occurs, an SQLite error code is returned. The output values ** are undefined in this case. */ static int fts3DoclistOrMerge( int bDescDoclist, /* True if arguments are desc */ char *a1, int n1, /* First doclist */ char *a2, int n2, /* Second doclist */ char **paOut, int *pnOut /* OUT: Malloc'd doclist */ ){ sqlite3_int64 i1 = 0; sqlite3_int64 i2 = 0; sqlite3_int64 iPrev = 0; char *pEnd1 = &a1[n1]; char *pEnd2 = &a2[n2]; char *p1 = a1; char *p2 = a2; char *p; char *aOut; int bFirstOut = 0; *paOut = 0; *pnOut = 0; /* Allocate space for the output. Both the input and output doclists ** are delta encoded. If they are in ascending order (bDescDoclist==0), ** then the first docid in each list is simply encoded as a varint. For ** each subsequent docid, the varint stored is the difference between the ** current and previous docid (a positive number - since the list is in ** ascending order). ** ** The first docid written to the output is therefore encoded using the ** same number of bytes as it is in whichever of the input lists it is ** read from. And each subsequent docid read from the same input list ** consumes either the same or less bytes as it did in the input (since ** the difference between it and the previous value in the output must ** be a positive value less than or equal to the delta value read from ** the input list). The same argument applies to all but the first docid ** read from the 'other' list. And to the contents of all position lists ** that will be copied and merged from the input to the output. ** ** However, if the first docid copied to the output is a negative number, ** then the encoding of the first docid from the 'other' input list may ** be larger in the output than it was in the input (since the delta value ** may be a larger positive integer than the actual docid). ** ** The space required to store the output is therefore the sum of the ** sizes of the two inputs, plus enough space for exactly one of the input ** docids to grow. ** ** A symetric argument may be made if the doclists are in descending ** order. */ aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1); if( !aOut ) return SQLITE_NOMEM; p = aOut; fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); while( p1 || p2 ){ sqlite3_int64 iDiff = DOCID_CMP(i1, i2); if( p2 && p1 && iDiff==0 ){ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); fts3PoslistMerge(&p, &p1, &p2); fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); }else if( !p2 || (p1 && iDiff<0) ){ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); fts3PoslistCopy(&p, &p1); fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); }else{ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2); fts3PoslistCopy(&p, &p2); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); } } *paOut = aOut; *pnOut = (int)(p-aOut); assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 ); return SQLITE_OK; } /* ** This function does a "phrase" merge of two doclists. In a phrase merge, ** the output contains a copy of each position from the right-hand input ** doclist for which there is a position in the left-hand input doclist ** exactly nDist tokens before it. ** ** If the docids in the input doclists are sorted in ascending order, ** parameter bDescDoclist should be false. If they are sorted in ascending ** order, it should be passed a non-zero value. ** ** The right-hand input doclist is overwritten by this function. */ static int fts3DoclistPhraseMerge( int bDescDoclist, /* True if arguments are desc */ int nDist, /* Distance from left to right (1=adjacent) */ char *aLeft, int nLeft, /* Left doclist */ char **paRight, int *pnRight /* IN/OUT: Right/output doclist */ ){ sqlite3_int64 i1 = 0; sqlite3_int64 i2 = 0; sqlite3_int64 iPrev = 0; char *aRight = *paRight; char *pEnd1 = &aLeft[nLeft]; char *pEnd2 = &aRight[*pnRight]; char *p1 = aLeft; char *p2 = aRight; char *p; int bFirstOut = 0; char *aOut; assert( nDist>0 ); if( bDescDoclist ){ aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX); if( aOut==0 ) return SQLITE_NOMEM; }else{ aOut = aRight; } p = aOut; fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); while( p1 && p2 ){ sqlite3_int64 iDiff = DOCID_CMP(i1, i2); if( iDiff==0 ){ char *pSave = p; sqlite3_int64 iPrevSave = iPrev; int bFirstOutSave = bFirstOut; fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){ p = pSave; iPrev = iPrevSave; bFirstOut = bFirstOutSave; } fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); }else if( iDiff<0 ){ fts3PoslistCopy(0, &p1); fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); }else{ fts3PoslistCopy(0, &p2); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); } } *pnRight = (int)(p - aOut); if( bDescDoclist ){ sqlite3_free(aRight); *paRight = aOut; } return SQLITE_OK; } /* ** Argument pList points to a position list nList bytes in size. This ** function checks to see if the position list contains any entries for ** a token in position 0 (of any column). If so, it writes argument iDelta ** to the output buffer pOut, followed by a position list consisting only ** of the entries from pList at position 0, and terminated by an 0x00 byte. ** The value returned is the number of bytes written to pOut (if any). */ SQLITE_PRIVATE int sqlite3Fts3FirstFilter( sqlite3_int64 iDelta, /* Varint that may be written to pOut */ char *pList, /* Position list (no 0x00 term) */ int nList, /* Size of pList in bytes */ char *pOut /* Write output here */ ){ int nOut = 0; int bWritten = 0; /* True once iDelta has been written */ char *p = pList; char *pEnd = &pList[nList]; if( *p!=0x01 ){ if( *p==0x02 ){ nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); pOut[nOut++] = 0x02; bWritten = 1; } fts3ColumnlistCopy(0, &p); } while( p<pEnd && *p==0x01 ){ sqlite3_int64 iCol; p++; p += sqlite3Fts3GetVarint(p, &iCol); if( *p==0x02 ){ if( bWritten==0 ){ nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); bWritten = 1; } pOut[nOut++] = 0x01; nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol); pOut[nOut++] = 0x02; } fts3ColumnlistCopy(0, &p); } if( bWritten ){ pOut[nOut++] = 0x00; } return nOut; } /* ** Merge all doclists in the TermSelect.aaOutput[] array into a single ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all ** other doclists (except the aaOutput[0] one) and return SQLITE_OK. ** ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is ** the responsibility of the caller to free any doclists left in the ** TermSelect.aaOutput[] array. */ static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){ char *aOut = 0; int nOut = 0; int i; /* Loop through the doclists in the aaOutput[] array. Merge them all ** into a single doclist. */ for(i=0; i<SizeofArray(pTS->aaOutput); i++){ if( pTS->aaOutput[i] ){ if( !aOut ){ aOut = pTS->aaOutput[i]; nOut = pTS->anOutput[i]; pTS->aaOutput[i] = 0; }else{ int nNew; char *aNew; int rc = fts3DoclistOrMerge(p->bDescIdx, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew ); if( rc!=SQLITE_OK ){ sqlite3_free(aOut); return rc; } sqlite3_free(pTS->aaOutput[i]); sqlite3_free(aOut); pTS->aaOutput[i] = 0; aOut = aNew; nOut = nNew; } } } pTS->aaOutput[0] = aOut; pTS->anOutput[0] = nOut; return SQLITE_OK; } /* ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed ** as the first argument. The merge is an "OR" merge (see function ** fts3DoclistOrMerge() for details). ** ** This function is called with the doclist for each term that matches ** a queried prefix. It merges all these doclists into one, the doclist ** for the specified prefix. Since there can be a very large number of ** doclists to merge, the merging is done pair-wise using the TermSelect ** object. ** ** This function returns SQLITE_OK if the merge is successful, or an ** SQLite error code (SQLITE_NOMEM) if an error occurs. */ static int fts3TermSelectMerge( Fts3Table *p, /* FTS table handle */ TermSelect *pTS, /* TermSelect object to merge into */ char *aDoclist, /* Pointer to doclist */ int nDoclist /* Size of aDoclist in bytes */ ){ if( pTS->aaOutput[0]==0 ){ /* If this is the first term selected, copy the doclist to the output ** buffer using memcpy(). ** ** Add FTS3_VARINT_MAX bytes of unused space to the end of the ** allocation. This is so as to ensure that the buffer is big enough ** to hold the current doclist AND'd with any other doclist. If the ** doclists are stored in order=ASC order, this padding would not be ** required (since the size of [doclistA AND doclistB] is always less ** than or equal to the size of [doclistA] in that case). But this is ** not true for order=DESC. For example, a doclist containing (1, -1) ** may be smaller than (-1), as in the first example the -1 may be stored ** as a single-byte delta, whereas in the second it must be stored as a ** FTS3_VARINT_MAX byte varint. ** ** Similar padding is added in the fts3DoclistOrMerge() function. */ pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1); pTS->anOutput[0] = nDoclist; if( pTS->aaOutput[0] ){ memcpy(pTS->aaOutput[0], aDoclist, nDoclist); }else{ return SQLITE_NOMEM; } }else{ char *aMerge = aDoclist; int nMerge = nDoclist; int iOut; for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){ if( pTS->aaOutput[iOut]==0 ){ assert( iOut>0 ); pTS->aaOutput[iOut] = aMerge; pTS->anOutput[iOut] = nMerge; break; }else{ char *aNew; int nNew; int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew ); if( rc!=SQLITE_OK ){ if( aMerge!=aDoclist ) sqlite3_free(aMerge); return rc; } if( aMerge!=aDoclist ) sqlite3_free(aMerge); sqlite3_free(pTS->aaOutput[iOut]); pTS->aaOutput[iOut] = 0; aMerge = aNew; nMerge = nNew; if( (iOut+1)==SizeofArray(pTS->aaOutput) ){ pTS->aaOutput[iOut] = aMerge; pTS->anOutput[iOut] = nMerge; } } } } return SQLITE_OK; } /* ** Append SegReader object pNew to the end of the pCsr->apSegment[] array. */ static int fts3SegReaderCursorAppend( Fts3MultiSegReader *pCsr, Fts3SegReader *pNew ){ if( (pCsr->nSegment%16)==0 ){ Fts3SegReader **apNew; int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte); if( !apNew ){ sqlite3Fts3SegReaderFree(pNew); return SQLITE_NOMEM; } pCsr->apSegment = apNew; } pCsr->apSegment[pCsr->nSegment++] = pNew; return SQLITE_OK; } /* ** Add seg-reader objects to the Fts3MultiSegReader object passed as the ** 8th argument. ** ** This function returns SQLITE_OK if successful, or an SQLite error code ** otherwise. */ static int fts3SegReaderCursor( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language id */ int iIndex, /* Index to search (from 0 to p->nIndex-1) */ int iLevel, /* Level of segments to scan */ const char *zTerm, /* Term to query for */ int nTerm, /* Size of zTerm in bytes */ int isPrefix, /* True for a prefix search */ int isScan, /* True to scan from zTerm to EOF */ Fts3MultiSegReader *pCsr /* Cursor object to populate */ ){ int rc = SQLITE_OK; /* Error code */ sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */ int rc2; /* Result of sqlite3_reset() */ /* If iLevel is less than 0 and this is not a scan, include a seg-reader ** for the pending-terms. If this is a scan, then this call must be being ** made by an fts4aux module, not an FTS table. In this case calling ** Fts3SegReaderPending might segfault, as the data structures used by ** fts4aux are not completely populated. So it's easiest to filter these ** calls out here. */ if( iLevel<0 && p->aIndex ){ Fts3SegReader *pSeg = 0; rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg); if( rc==SQLITE_OK && pSeg ){ rc = fts3SegReaderCursorAppend(pCsr, pSeg); } } if( iLevel!=FTS3_SEGCURSOR_PENDING ){ if( rc==SQLITE_OK ){ rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt); } while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ Fts3SegReader *pSeg = 0; /* Read the values returned by the SELECT into local variables. */ sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1); sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2); sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3); int nRoot = sqlite3_column_bytes(pStmt, 4); char const *zRoot = sqlite3_column_blob(pStmt, 4); /* If zTerm is not NULL, and this segment is not stored entirely on its ** root node, the range of leaves scanned can be reduced. Do this. */ if( iStartBlock && zTerm ){ sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi); if( rc!=SQLITE_OK ) goto finished; if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock; } rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, (isPrefix==0 && isScan==0), iStartBlock, iLeavesEndBlock, iEndBlock, zRoot, nRoot, &pSeg ); if( rc!=SQLITE_OK ) goto finished; rc = fts3SegReaderCursorAppend(pCsr, pSeg); } } finished: rc2 = sqlite3_reset(pStmt); if( rc==SQLITE_DONE ) rc = rc2; return rc; } /* ** Set up a cursor object for iterating through a full-text index or a ** single level therein. */ SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language-id to search */ int iIndex, /* Index to search (from 0 to p->nIndex-1) */ int iLevel, /* Level of segments to scan */ const char *zTerm, /* Term to query for */ int nTerm, /* Size of zTerm in bytes */ int isPrefix, /* True for a prefix search */ int isScan, /* True to scan from zTerm to EOF */ Fts3MultiSegReader *pCsr /* Cursor object to populate */ ){ assert( iIndex>=0 && iIndex<p->nIndex ); assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel==FTS3_SEGCURSOR_PENDING || iLevel>=0 ); assert( iLevel<FTS3_SEGDIR_MAXLEVEL ); assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 ); assert( isPrefix==0 || isScan==0 ); memset(pCsr, 0, sizeof(Fts3MultiSegReader)); return fts3SegReaderCursor( p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr ); } /* ** In addition to its current configuration, have the Fts3MultiSegReader ** passed as the 4th argument also scan the doclist for term zTerm/nTerm. ** ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. */ static int fts3SegReaderCursorAddZero( Fts3Table *p, /* FTS virtual table handle */ int iLangid, const char *zTerm, /* Term to scan doclist of */ int nTerm, /* Number of bytes in zTerm */ Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */ ){ return fts3SegReaderCursor(p, iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr ); } /* ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or, ** if isPrefix is true, to scan the doclist for all terms for which ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return ** an SQLite error code. ** ** It is the responsibility of the caller to free this object by eventually ** passing it to fts3SegReaderCursorFree() ** ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. ** Output parameter *ppSegcsr is set to 0 if an error occurs. */ static int fts3TermSegReaderCursor( Fts3Cursor *pCsr, /* Virtual table cursor handle */ const char *zTerm, /* Term to query for */ int nTerm, /* Size of zTerm in bytes */ int isPrefix, /* True for a prefix search */ Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */ ){ Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */ int rc = SQLITE_NOMEM; /* Return code */ pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader)); if( pSegcsr ){ int i; int bFound = 0; /* True once an index has been found */ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; if( isPrefix ){ for(i=1; bFound==0 && i<p->nIndex; i++){ if( p->aIndex[i].nPrefix==nTerm ){ bFound = 1; rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr ); pSegcsr->bLookup = 1; } } for(i=1; bFound==0 && i<p->nIndex; i++){ if( p->aIndex[i].nPrefix==nTerm+1 ){ bFound = 1; rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr ); if( rc==SQLITE_OK ){ rc = fts3SegReaderCursorAddZero( p, pCsr->iLangid, zTerm, nTerm, pSegcsr ); } } } } if( bFound==0 ){ rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr ); pSegcsr->bLookup = !isPrefix; } } *ppSegcsr = pSegcsr; return rc; } /* ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor(). */ static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){ sqlite3Fts3SegReaderFinish(pSegcsr); sqlite3_free(pSegcsr); } /* ** This function retrieves the doclist for the specified term (or term ** prefix) from the database. */ static int fts3TermSelect( Fts3Table *p, /* Virtual table handle */ Fts3PhraseToken *pTok, /* Token to query for */ int iColumn, /* Column to query (or -ve for all columns) */ int *pnOut, /* OUT: Size of buffer at *ppOut */ char **ppOut /* OUT: Malloced result buffer */ ){ int rc; /* Return code */ Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */ TermSelect tsc; /* Object for pair-wise doclist merging */ Fts3SegFilter filter; /* Segment term filter configuration */ pSegcsr = pTok->pSegcsr; memset(&tsc, 0, sizeof(TermSelect)); filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0) | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0) | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0); filter.iCol = iColumn; filter.zTerm = pTok->z; filter.nTerm = pTok->n; rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter); while( SQLITE_OK==rc && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) ){ rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist); } if( rc==SQLITE_OK ){ rc = fts3TermSelectFinishMerge(p, &tsc); } if( rc==SQLITE_OK ){ *ppOut = tsc.aaOutput[0]; *pnOut = tsc.anOutput[0]; }else{ int i; for(i=0; i<SizeofArray(tsc.aaOutput); i++){ sqlite3_free(tsc.aaOutput[i]); } } fts3SegReaderCursorFree(pSegcsr); pTok->pSegcsr = 0; return rc; } /* ** This function counts the total number of docids in the doclist stored ** in buffer aList[], size nList bytes. ** ** If the isPoslist argument is true, then it is assumed that the doclist ** contains a position-list following each docid. Otherwise, it is assumed ** that the doclist is simply a list of docids stored as delta encoded ** varints. */ static int fts3DoclistCountDocids(char *aList, int nList){ int nDoc = 0; /* Return value */ if( aList ){ char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */ char *p = aList; /* Cursor */ while( p<aEnd ){ nDoc++; while( (*p++)&0x80 ); /* Skip docid varint */ fts3PoslistCopy(0, &p); /* Skip over position list */ } } return nDoc; } /* ** Advance the cursor to the next row in the %_content table that ** matches the search criteria. For a MATCH search, this will be ** the next row that matches. For a full-table scan, this will be ** simply the next row in the %_content table. For a docid lookup, ** this routine simply sets the EOF flag. ** ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned ** even if we reach end-of-file. The fts3EofMethod() will be called ** subsequently to determine whether or not an EOF was hit. */ static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){ int rc; Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){ if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ pCsr->isEof = 1; rc = sqlite3_reset(pCsr->pStmt); }else{ pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0); rc = SQLITE_OK; } }else{ rc = fts3EvalNext((Fts3Cursor *)pCursor); } assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); return rc; } /* ** The following are copied from sqliteInt.h. ** ** Constants for the largest and smallest possible 64-bit signed integers. ** These macros are designed to work correctly on both 32-bit and 64-bit ** compilers. */ #ifndef SQLITE_AMALGAMATION # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) #endif /* ** If the numeric type of argument pVal is "integer", then return it ** converted to a 64-bit signed integer. Otherwise, return a copy of ** the second parameter, iDefault. */ static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){ if( pVal ){ int eType = sqlite3_value_numeric_type(pVal); if( eType==SQLITE_INTEGER ){ return sqlite3_value_int64(pVal); } } return iDefault; } /* ** This is the xFilter interface for the virtual table. See ** the virtual table xFilter method documentation for additional ** information. ** ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against ** the %_content table. ** ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry ** in the %_content table. ** ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The ** column on the left-hand side of the MATCH operator is column ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand ** side of the MATCH operator. */ static int fts3FilterMethod( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ sqlite3_value **apVal /* Arguments for the indexing scheme */ ){ int rc = SQLITE_OK; char *zSql; /* SQL statement used to access %_content */ int eSearch; Fts3Table *p = (Fts3Table *)pCursor->pVtab; Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */ sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */ sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */ sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */ int iIdx; UNUSED_PARAMETER(idxStr); UNUSED_PARAMETER(nVal); eSearch = (idxNum & 0x0000FFFF); assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) ); assert( p->pSegments==0 ); /* Collect arguments into local variables */ iIdx = 0; if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++]; if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++]; if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++]; if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++]; assert( iIdx==nVal ); /* In case the cursor has been used before, clear it now. */ fts3CursorFinalizeStmt(pCsr); sqlite3_free(pCsr->aDoclist); sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); sqlite3Fts3ExprFree(pCsr->pExpr); memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor)); /* Set the lower and upper bounds on docids to return */ pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64); pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64); if( idxStr ){ pCsr->bDesc = (idxStr[0]=='D'); }else{ pCsr->bDesc = p->bDescIdx; } pCsr->eSearch = (i16)eSearch; if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){ int iCol = eSearch-FTS3_FULLTEXT_SEARCH; const char *zQuery = (const char *)sqlite3_value_text(pCons); if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){ return SQLITE_NOMEM; } pCsr->iLangid = 0; if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid); assert( p->base.zErrMsg==0 ); rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid, p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, &p->base.zErrMsg ); if( rc!=SQLITE_OK ){ return rc; } rc = fts3EvalStart(pCsr); sqlite3Fts3SegmentsClose(p); if( rc!=SQLITE_OK ) return rc; pCsr->pNextId = pCsr->aDoclist; pCsr->iPrevId = 0; } /* Compile a SELECT statement for this cursor. For a full-table-scan, the ** statement loops through all rows of the %_content table. For a ** full-text query or docid lookup, the statement retrieves a single ** row by docid. */ if( eSearch==FTS3_FULLSCAN_SEARCH ){ if( pDocidGe || pDocidLe ){ zSql = sqlite3_mprintf( "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s", p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid, (pCsr->bDesc ? "DESC" : "ASC") ); }else{ zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC") ); } if( zSql ){ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); sqlite3_free(zSql); }else{ rc = SQLITE_NOMEM; } }else if( eSearch==FTS3_DOCID_SEARCH ){ rc = fts3CursorSeekStmt(pCsr); if( rc==SQLITE_OK ){ rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons); } } if( rc!=SQLITE_OK ) return rc; return fts3NextMethod(pCursor); } /* ** This is the xEof method of the virtual table. SQLite calls this ** routine to find out if it has reached the end of a result set. */ static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ return ((Fts3Cursor *)pCursor)->isEof; } /* ** This is the xRowid method. The SQLite core calls this routine to ** retrieve the rowid for the current row of the result set. fts3 ** exposes %_content.docid as the rowid for the virtual table. The ** rowid should be written to *pRowid. */ static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; *pRowid = pCsr->iPrevId; return SQLITE_OK; } /* ** This is the xColumn method, called by SQLite to request a value from ** the row that the supplied cursor currently points to. ** ** If: ** ** (iCol < p->nColumn) -> The value of the iCol'th user column. ** (iCol == p->nColumn) -> Magic column with the same name as the table. ** (iCol == p->nColumn+1) -> Docid column ** (iCol == p->nColumn+2) -> Langid column */ static int fts3ColumnMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ int rc = SQLITE_OK; /* Return Code */ Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; Fts3Table *p = (Fts3Table *)pCursor->pVtab; /* The column value supplied by SQLite must be in range. */ assert( iCol>=0 && iCol<=p->nColumn+2 ); if( iCol==p->nColumn+1 ){ /* This call is a request for the "docid" column. Since "docid" is an ** alias for "rowid", use the xRowid() method to obtain the value. */ sqlite3_result_int64(pCtx, pCsr->iPrevId); }else if( iCol==p->nColumn ){ /* The extra column whose name is the same as the table. ** Return a blob which is a pointer to the cursor. */ sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT); }else if( iCol==p->nColumn+2 && pCsr->pExpr ){ sqlite3_result_int64(pCtx, pCsr->iLangid); }else{ /* The requested column is either a user column (one that contains ** indexed data), or the language-id column. */ rc = fts3CursorSeek(0, pCsr); if( rc==SQLITE_OK ){ if( iCol==p->nColumn+2 ){ int iLangid = 0; if( p->zLanguageid ){ iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1); } sqlite3_result_int(pCtx, iLangid); }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){ sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); } } } assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); return rc; } /* ** This function is the implementation of the xUpdate callback used by ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be ** inserted, updated or deleted. */ static int fts3UpdateMethod( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Size of argument array */ sqlite3_value **apVal, /* Array of arguments */ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ ){ return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); } /* ** Implementation of xSync() method. Flush the contents of the pending-terms ** hash-table to the database. */ static int fts3SyncMethod(sqlite3_vtab *pVtab){ /* Following an incremental-merge operation, assuming that the input ** segments are not completely consumed (the usual case), they are updated ** in place to remove the entries that have already been merged. This ** involves updating the leaf block that contains the smallest unmerged ** entry and each block (if any) between the leaf and the root node. So ** if the height of the input segment b-trees is N, and input segments ** are merged eight at a time, updating the input segments at the end ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually ** small - often between 0 and 2. So the overhead of the incremental ** merge is somewhere between 8 and 24 blocks. To avoid this overhead ** dwarfing the actual productive work accomplished, the incremental merge ** is only attempted if it will write at least 64 leaf blocks. Hence ** nMinMerge. ** ** Of course, updating the input segments also involves deleting a bunch ** of blocks from the segments table. But this is not considered overhead ** as it would also be required by a crisis-merge that used the same input ** segments. */ const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */ Fts3Table *p = (Fts3Table*)pVtab; int rc = sqlite3Fts3PendingTermsFlush(p); if( rc==SQLITE_OK && p->nLeafAdd>(nMinMerge/16) && p->nAutoincrmerge && p->nAutoincrmerge!=0xff ){ int mxLevel = 0; /* Maximum relative level value in db */ int A; /* Incr-merge parameter A */ rc = sqlite3Fts3MaxLevel(p, &mxLevel); assert( rc==SQLITE_OK || mxLevel==0 ); A = p->nLeafAdd * mxLevel; A += (A/2); if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge); } sqlite3Fts3SegmentsClose(p); return rc; } /* ** If it is currently unknown whether or not the FTS table has an %_stat ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code ** if an error occurs. */ static int fts3SetHasStat(Fts3Table *p){ int rc = SQLITE_OK; if( p->bHasStat==2 ){ const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'"; char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName); if( zSql ){ sqlite3_stmt *pStmt = 0; rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); if( rc==SQLITE_OK ){ int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW); rc = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ) p->bHasStat = (u8)bHasStat; } sqlite3_free(zSql); }else{ rc = SQLITE_NOMEM; } } return rc; } /* ** Implementation of xBegin() method. */ static int fts3BeginMethod(sqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table*)pVtab; UNUSED_PARAMETER(pVtab); assert( p->pSegments==0 ); assert( p->nPendingData==0 ); assert( p->inTransaction!=1 ); TESTONLY( p->inTransaction = 1 ); TESTONLY( p->mxSavepoint = -1; ); p->nLeafAdd = 0; return fts3SetHasStat(p); } /* ** Implementation of xCommit() method. This is a no-op. The contents of ** the pending-terms hash-table have already been flushed into the database ** by fts3SyncMethod(). */ static int fts3CommitMethod(sqlite3_vtab *pVtab){ TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); UNUSED_PARAMETER(pVtab); assert( p->nPendingData==0 ); assert( p->inTransaction!=0 ); assert( p->pSegments==0 ); TESTONLY( p->inTransaction = 0 ); TESTONLY( p->mxSavepoint = -1; ); return SQLITE_OK; } /* ** Implementation of xRollback(). Discard the contents of the pending-terms ** hash-table. Any changes made to the database are reverted by SQLite. */ static int fts3RollbackMethod(sqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table*)pVtab; sqlite3Fts3PendingTermsClear(p); assert( p->inTransaction!=0 ); TESTONLY( p->inTransaction = 0 ); TESTONLY( p->mxSavepoint = -1; ); return SQLITE_OK; } /* ** When called, *ppPoslist must point to the byte immediately following the ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function ** moves *ppPoslist so that it instead points to the first byte of the ** same position list. */ static void fts3ReversePoslist(char *pStart, char **ppPoslist){ char *p = &(*ppPoslist)[-2]; char c = 0; /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */ while( p>pStart && (c=*p--)==0 ); /* Search backwards for a varint with value zero (the end of the previous ** poslist). This is an 0x00 byte preceded by some byte that does not ** have the 0x80 bit set. */ while( p>pStart && (*p & 0x80) | c ){ c = *p--; } assert( p==pStart || c==0 ); /* At this point p points to that preceding byte without the 0x80 bit ** set. So to find the start of the poslist, skip forward 2 bytes then ** over a varint. ** ** Normally. The other case is that p==pStart and the poslist to return ** is the first in the doclist. In this case do not skip forward 2 bytes. ** The second part of the if condition (c==0 && *ppPoslist>&p[2]) ** is required for cases where the first byte of a doclist and the ** doclist is empty. For example, if the first docid is 10, a doclist ** that begins with: ** ** 0x0A 0x00 <next docid delta varint> */ if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; } while( *p++&0x80 ); *ppPoslist = p; } /* ** Helper function used by the implementation of the overloaded snippet(), ** offsets() and optimize() SQL functions. ** ** If the value passed as the third argument is a blob of size ** sizeof(Fts3Cursor*), then the blob contents are copied to the ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error ** message is written to context pContext and SQLITE_ERROR returned. The ** string passed via zFunc is used as part of the error message. */ static int fts3FunctionArg( sqlite3_context *pContext, /* SQL function call context */ const char *zFunc, /* Function name */ sqlite3_value *pVal, /* argv[0] passed to function */ Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ ){ Fts3Cursor *pRet; if( sqlite3_value_type(pVal)!=SQLITE_BLOB || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *) ){ char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc); sqlite3_result_error(pContext, zErr, -1); sqlite3_free(zErr); return SQLITE_ERROR; } memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *)); *ppCsr = pRet; return SQLITE_OK; } /* ** Implementation of the snippet() function for FTS3 */ static void fts3SnippetFunc( sqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of apVal[] array */ sqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ const char *zStart = "<b>"; const char *zEnd = "</b>"; const char *zEllipsis = "<b>...</b>"; int iCol = -1; int nToken = 15; /* Default number of tokens in snippet */ /* There must be at least one argument passed to this function (otherwise ** the non-overloaded version would have been called instead of this one). */ assert( nVal>=1 ); if( nVal>6 ){ sqlite3_result_error(pContext, "wrong number of arguments to function snippet()", -1); return; } if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; switch( nVal ){ case 6: nToken = sqlite3_value_int(apVal[5]); case 5: iCol = sqlite3_value_int(apVal[4]); case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); case 2: zStart = (const char*)sqlite3_value_text(apVal[1]); } if( !zEllipsis || !zEnd || !zStart ){ sqlite3_result_error_nomem(pContext); }else if( nToken==0 ){ sqlite3_result_text(pContext, "", -1, SQLITE_STATIC); }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); } } /* ** Implementation of the offsets() function for FTS3 */ static void fts3OffsetsFunc( sqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ sqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ UNUSED_PARAMETER(nVal); assert( nVal==1 ); if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return; assert( pCsr ); if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ sqlite3Fts3Offsets(pContext, pCsr); } } /* ** Implementation of the special optimize() function for FTS3. This ** function merges all segments in the database to a single segment. ** Example usage is: ** ** SELECT optimize(t) FROM t LIMIT 1; ** ** where 't' is the name of an FTS3 table. */ static void fts3OptimizeFunc( sqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ sqlite3_value **apVal /* Array of arguments */ ){ int rc; /* Return code */ Fts3Table *p; /* Virtual table handle */ Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */ UNUSED_PARAMETER(nVal); assert( nVal==1 ); if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return; p = (Fts3Table *)pCursor->base.pVtab; assert( p ); rc = sqlite3Fts3Optimize(p); switch( rc ){ case SQLITE_OK: sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); break; case SQLITE_DONE: sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); break; default: sqlite3_result_error_code(pContext, rc); break; } } /* ** Implementation of the matchinfo() function for FTS3 */ static void fts3MatchinfoFunc( sqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ sqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ assert( nVal==1 || nVal==2 ); if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){ const char *zArg = 0; if( nVal>1 ){ zArg = (const char *)sqlite3_value_text(apVal[1]); } sqlite3Fts3Matchinfo(pContext, pCsr, zArg); } } /* ** This routine implements the xFindFunction method for the FTS3 ** virtual table. */ static int fts3FindFunctionMethod( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ void **ppArg /* Unused */ ){ struct Overloaded { const char *zName; void (*xFunc)(sqlite3_context*,int,sqlite3_value**); } aOverload[] = { { "snippet", fts3SnippetFunc }, { "offsets", fts3OffsetsFunc }, { "optimize", fts3OptimizeFunc }, { "matchinfo", fts3MatchinfoFunc }, }; int i; /* Iterator variable */ UNUSED_PARAMETER(pVtab); UNUSED_PARAMETER(nArg); UNUSED_PARAMETER(ppArg); for(i=0; i<SizeofArray(aOverload); i++){ if( strcmp(zName, aOverload[i].zName)==0 ){ *pxFunc = aOverload[i].xFunc; return 1; } } /* No function of the specified name was found. Return 0. */ return 0; } /* ** Implementation of FTS3 xRename method. Rename an fts3 table. */ static int fts3RenameMethod( sqlite3_vtab *pVtab, /* Virtual table handle */ const char *zName /* New name of table */ ){ Fts3Table *p = (Fts3Table *)pVtab; sqlite3 *db = p->db; /* Database connection */ int rc; /* Return Code */ /* At this point it must be known if the %_stat table exists or not. ** So bHasStat may not be 2. */ rc = fts3SetHasStat(p); /* As it happens, the pending terms table is always empty here. This is ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction ** always opens a savepoint transaction. And the xSavepoint() method ** flushes the pending terms table. But leave the (no-op) call to ** PendingTermsFlush() in in case that changes. */ assert( p->nPendingData==0 ); if( rc==SQLITE_OK ){ rc = sqlite3Fts3PendingTermsFlush(p); } if( p->zContentTbl==0 ){ fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';", p->zDb, p->zName, zName ); } if( p->bHasDocsize ){ fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';", p->zDb, p->zName, zName ); } if( p->bHasStat ){ fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';", p->zDb, p->zName, zName ); } fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';", p->zDb, p->zName, zName ); fts3DbExec(&rc, db, "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';", p->zDb, p->zName, zName ); return rc; } /* ** The xSavepoint() method. ** ** Flush the contents of the pending-terms table to disk. */ static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ int rc = SQLITE_OK; UNUSED_PARAMETER(iSavepoint); assert( ((Fts3Table *)pVtab)->inTransaction ); assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint ); TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint ); if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){ rc = fts3SyncMethod(pVtab); } return rc; } /* ** The xRelease() method. ** ** This is a no-op. */ static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); UNUSED_PARAMETER(iSavepoint); UNUSED_PARAMETER(pVtab); assert( p->inTransaction ); assert( p->mxSavepoint >= iSavepoint ); TESTONLY( p->mxSavepoint = iSavepoint-1 ); return SQLITE_OK; } /* ** The xRollbackTo() method. ** ** Discard the contents of the pending terms table. */ static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ Fts3Table *p = (Fts3Table*)pVtab; UNUSED_PARAMETER(iSavepoint); assert( p->inTransaction ); assert( p->mxSavepoint >= iSavepoint ); TESTONLY( p->mxSavepoint = iSavepoint ); sqlite3Fts3PendingTermsClear(p); return SQLITE_OK; } static const sqlite3_module fts3Module = { /* iVersion */ 2, /* xCreate */ fts3CreateMethod, /* xConnect */ fts3ConnectMethod, /* xBestIndex */ fts3BestIndexMethod, /* xDisconnect */ fts3DisconnectMethod, /* xDestroy */ fts3DestroyMethod, /* xOpen */ fts3OpenMethod, /* xClose */ fts3CloseMethod, /* xFilter */ fts3FilterMethod, /* xNext */ fts3NextMethod, /* xEof */ fts3EofMethod, /* xColumn */ fts3ColumnMethod, /* xRowid */ fts3RowidMethod, /* xUpdate */ fts3UpdateMethod, /* xBegin */ fts3BeginMethod, /* xSync */ fts3SyncMethod, /* xCommit */ fts3CommitMethod, /* xRollback */ fts3RollbackMethod, /* xFindFunction */ fts3FindFunctionMethod, /* xRename */ fts3RenameMethod, /* xSavepoint */ fts3SavepointMethod, /* xRelease */ fts3ReleaseMethod, /* xRollbackTo */ fts3RollbackToMethod, }; /* ** This function is registered as the module destructor (called when an ** FTS3 enabled database connection is closed). It frees the memory ** allocated for the tokenizer hash table. */ static void hashDestroy(void *p){ Fts3Hash *pHash = (Fts3Hash *)p; sqlite3Fts3HashClear(pHash); sqlite3_free(pHash); } /* ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c ** respectively. The following three forward declarations are for functions ** declared in these files used to retrieve the respective implementations. ** ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed ** to by the argument to point to the "simple" tokenizer implementation. ** And so on. */ SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); #ifndef SQLITE_DISABLE_FTS3_UNICODE SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule); #endif #ifdef SQLITE_ENABLE_ICU SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); #endif /* ** Initialize the fts3 extension. If this extension is built as part ** of the sqlite library, then this function is called directly by ** SQLite. If fts3 is built as a dynamically loadable extension, this ** function is called by the sqlite3_extension_init() entry point. */ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ int rc = SQLITE_OK; Fts3Hash *pHash = 0; const sqlite3_tokenizer_module *pSimple = 0; const sqlite3_tokenizer_module *pPorter = 0; #ifndef SQLITE_DISABLE_FTS3_UNICODE const sqlite3_tokenizer_module *pUnicode = 0; #endif #ifdef SQLITE_ENABLE_ICU const sqlite3_tokenizer_module *pIcu = 0; sqlite3Fts3IcuTokenizerModule(&pIcu); #endif #ifndef SQLITE_DISABLE_FTS3_UNICODE sqlite3Fts3UnicodeTokenizer(&pUnicode); #endif #ifdef SQLITE_TEST rc = sqlite3Fts3InitTerm(db); if( rc!=SQLITE_OK ) return rc; #endif rc = sqlite3Fts3InitAux(db); if( rc!=SQLITE_OK ) return rc; sqlite3Fts3SimpleTokenizerModule(&pSimple); sqlite3Fts3PorterTokenizerModule(&pPorter); /* Allocate and initialize the hash-table used to store tokenizers. */ pHash = sqlite3_malloc(sizeof(Fts3Hash)); if( !pHash ){ rc = SQLITE_NOMEM; }else{ sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); } /* Load the built-in tokenizers into the hash table */ if( rc==SQLITE_OK ){ if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple) || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) #ifndef SQLITE_DISABLE_FTS3_UNICODE || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) #endif #ifdef SQLITE_ENABLE_ICU || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu)) #endif ){ rc = SQLITE_NOMEM; } } #ifdef SQLITE_TEST if( rc==SQLITE_OK ){ rc = sqlite3Fts3ExprInitTestInterface(db); } #endif /* Create the virtual table wrapper around the hash-table and overload ** the two scalar functions. If this is successful, register the ** module with sqlite. */ if( SQLITE_OK==rc && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1)) ){ rc = sqlite3_create_module_v2( db, "fts3", &fts3Module, (void *)pHash, hashDestroy ); if( rc==SQLITE_OK ){ rc = sqlite3_create_module_v2( db, "fts4", &fts3Module, (void *)pHash, 0 ); } if( rc==SQLITE_OK ){ rc = sqlite3Fts3InitTok(db, (void *)pHash); } return rc; } /* An error has occurred. Delete the hash table and return the error code. */ assert( rc!=SQLITE_OK ); if( pHash ){ sqlite3Fts3HashClear(pHash); sqlite3_free(pHash); } return rc; } /* ** Allocate an Fts3MultiSegReader for each token in the expression headed ** by pExpr. ** ** An Fts3SegReader object is a cursor that can seek or scan a range of ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple ** Fts3SegReader objects internally to provide an interface to seek or scan ** within the union of all segments of a b-tree. Hence the name. ** ** If the allocated Fts3MultiSegReader just seeks to a single entry in a ** segment b-tree (if the term is not a prefix or it is a prefix for which ** there exists prefix b-tree of the right length) then it may be traversed ** and merged incrementally. Otherwise, it has to be merged into an in-memory ** doclist and then traversed. */ static void fts3EvalAllocateReaders( Fts3Cursor *pCsr, /* FTS cursor handle */ Fts3Expr *pExpr, /* Allocate readers for this expression */ int *pnToken, /* OUT: Total number of tokens in phrase. */ int *pnOr, /* OUT: Total number of OR nodes in expr. */ int *pRc /* IN/OUT: Error code */ ){ if( pExpr && SQLITE_OK==*pRc ){ if( pExpr->eType==FTSQUERY_PHRASE ){ int i; int nToken = pExpr->pPhrase->nToken; *pnToken += nToken; for(i=0; i<nToken; i++){ Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i]; int rc = fts3TermSegReaderCursor(pCsr, pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr ); if( rc!=SQLITE_OK ){ *pRc = rc; return; } } assert( pExpr->pPhrase->iDoclistToken==0 ); pExpr->pPhrase->iDoclistToken = -1; }else{ *pnOr += (pExpr->eType==FTSQUERY_OR); fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc); fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc); } } } /* ** Arguments pList/nList contain the doclist for token iToken of phrase p. ** It is merged into the main doclist stored in p->doclist.aAll/nAll. ** ** This function assumes that pList points to a buffer allocated using ** sqlite3_malloc(). This function takes responsibility for eventually ** freeing the buffer. ** ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs. */ static int fts3EvalPhraseMergeToken( Fts3Table *pTab, /* FTS Table pointer */ Fts3Phrase *p, /* Phrase to merge pList/nList into */ int iToken, /* Token pList/nList corresponds to */ char *pList, /* Pointer to doclist */ int nList /* Number of bytes in pList */ ){ int rc = SQLITE_OK; assert( iToken!=p->iDoclistToken ); if( pList==0 ){ sqlite3_free(p->doclist.aAll); p->doclist.aAll = 0; p->doclist.nAll = 0; } else if( p->iDoclistToken<0 ){ p->doclist.aAll = pList; p->doclist.nAll = nList; } else if( p->doclist.aAll==0 ){ sqlite3_free(pList); } else { char *pLeft; char *pRight; int nLeft; int nRight; int nDiff; if( p->iDoclistToken<iToken ){ pLeft = p->doclist.aAll; nLeft = p->doclist.nAll; pRight = pList; nRight = nList; nDiff = iToken - p->iDoclistToken; }else{ pRight = p->doclist.aAll; nRight = p->doclist.nAll; pLeft = pList; nLeft = nList; nDiff = p->iDoclistToken - iToken; } rc = fts3DoclistPhraseMerge( pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight ); sqlite3_free(pLeft); p->doclist.aAll = pRight; p->doclist.nAll = nRight; } if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken; return rc; } /* ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist ** does not take deferred tokens into account. ** ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. */ static int fts3EvalPhraseLoad( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Phrase *p /* Phrase object */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int iToken; int rc = SQLITE_OK; for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){ Fts3PhraseToken *pToken = &p->aToken[iToken]; assert( pToken->pDeferred==0 || pToken->pSegcsr==0 ); if( pToken->pSegcsr ){ int nThis = 0; char *pThis = 0; rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis); if( rc==SQLITE_OK ){ rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis); } } assert( pToken->pSegcsr==0 ); } return rc; } /* ** This function is called on each phrase after the position lists for ** any deferred tokens have been loaded into memory. It updates the phrases ** current position list to include only those positions that are really ** instances of the phrase (after considering deferred tokens). If this ** means that the phrase does not appear in the current row, doclist.pList ** and doclist.nList are both zeroed. ** ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. */ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ int iToken; /* Used to iterate through phrase tokens */ char *aPoslist = 0; /* Position list for deferred tokens */ int nPoslist = 0; /* Number of bytes in aPoslist */ int iPrev = -1; /* Token number of previous deferred token */ assert( pPhrase->doclist.bFreeList==0 ); for(iToken=0; iToken<pPhrase->nToken; iToken++){ Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; Fts3DeferredToken *pDeferred = pToken->pDeferred; if( pDeferred ){ char *pList; int nList; int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList); if( rc!=SQLITE_OK ) return rc; if( pList==0 ){ sqlite3_free(aPoslist); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; return SQLITE_OK; }else if( aPoslist==0 ){ aPoslist = pList; nPoslist = nList; }else{ char *aOut = pList; char *p1 = aPoslist; char *p2 = aOut; assert( iPrev>=0 ); fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2); sqlite3_free(aPoslist); aPoslist = pList; nPoslist = (int)(aOut - aPoslist); if( nPoslist==0 ){ sqlite3_free(aPoslist); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; return SQLITE_OK; } } iPrev = iToken; } } if( iPrev>=0 ){ int nMaxUndeferred = pPhrase->iDoclistToken; if( nMaxUndeferred<0 ){ pPhrase->doclist.pList = aPoslist; pPhrase->doclist.nList = nPoslist; pPhrase->doclist.iDocid = pCsr->iPrevId; pPhrase->doclist.bFreeList = 1; }else{ int nDistance; char *p1; char *p2; char *aOut; if( nMaxUndeferred>iPrev ){ p1 = aPoslist; p2 = pPhrase->doclist.pList; nDistance = nMaxUndeferred - iPrev; }else{ p1 = pPhrase->doclist.pList; p2 = aPoslist; nDistance = iPrev - nMaxUndeferred; } aOut = (char *)sqlite3_malloc(nPoslist+8); if( !aOut ){ sqlite3_free(aPoslist); return SQLITE_NOMEM; } pPhrase->doclist.pList = aOut; if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){ pPhrase->doclist.bFreeList = 1; pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList); }else{ sqlite3_free(aOut); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; } sqlite3_free(aPoslist); } } return SQLITE_OK; } /* ** Maximum number of tokens a phrase may have to be considered for the ** incremental doclists strategy. */ #define MAX_INCR_PHRASE_TOKENS 4 /* ** This function is called for each Fts3Phrase in a full-text query ** expression to initialize the mechanism for returning rows. Once this ** function has been called successfully on an Fts3Phrase, it may be ** used with fts3EvalPhraseNext() to iterate through the matching docids. ** ** If parameter bOptOk is true, then the phrase may (or may not) use the ** incremental loading strategy. Otherwise, the entire doclist is loaded into ** memory within this call. ** ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. */ static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; /* Error code */ int i; /* Determine if doclists may be loaded from disk incrementally. This is ** possible if the bOptOk argument is true, the FTS doclists will be ** scanned in forward order, and the phrase consists of ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first" ** tokens or prefix tokens that cannot use a prefix-index. */ int bHaveIncr = 0; int bIncrOk = (bOptOk && pCsr->bDesc==pTab->bDescIdx && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 #ifdef SQLITE_TEST && pTab->bNoIncrDoclist==0 #endif ); for(i=0; bIncrOk==1 && i<p->nToken; i++){ Fts3PhraseToken *pToken = &p->aToken[i]; if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){ bIncrOk = 0; } if( pToken->pSegcsr ) bHaveIncr = 1; } if( bIncrOk && bHaveIncr ){ /* Use the incremental approach. */ int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn); for(i=0; rc==SQLITE_OK && i<p->nToken; i++){ Fts3PhraseToken *pToken = &p->aToken[i]; Fts3MultiSegReader *pSegcsr = pToken->pSegcsr; if( pSegcsr ){ rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); } } p->bIncr = 1; }else{ /* Load the full doclist for the phrase into memory. */ rc = fts3EvalPhraseLoad(pCsr, p); p->bIncr = 0; } assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr ); return rc; } /* ** This function is used to iterate backwards (from the end to start) ** through doclists. It is used by this module to iterate through phrase ** doclists in reverse and by the fts3_write.c module to iterate through ** pending-terms lists when writing to databases with "order=desc". ** ** The doclist may be sorted in ascending (parameter bDescIdx==0) or ** descending (parameter bDescIdx==1) order of docid. Regardless, this ** function iterates from the end of the doclist to the beginning. */ SQLITE_PRIVATE void sqlite3Fts3DoclistPrev( int bDescIdx, /* True if the doclist is desc */ char *aDoclist, /* Pointer to entire doclist */ int nDoclist, /* Length of aDoclist in bytes */ char **ppIter, /* IN/OUT: Iterator pointer */ sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ int *pnList, /* OUT: List length pointer */ u8 *pbEof /* OUT: End-of-file flag */ ){ char *p = *ppIter; assert( nDoclist>0 ); assert( *pbEof==0 ); assert( p || *piDocid==0 ); assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) ); if( p==0 ){ sqlite3_int64 iDocid = 0; char *pNext = 0; char *pDocid = aDoclist; char *pEnd = &aDoclist[nDoclist]; int iMul = 1; while( pDocid<pEnd ){ sqlite3_int64 iDelta; pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta); iDocid += (iMul * iDelta); pNext = pDocid; fts3PoslistCopy(0, &pDocid); while( pDocid<pEnd && *pDocid==0 ) pDocid++; iMul = (bDescIdx ? -1 : 1); } *pnList = (int)(pEnd - pNext); *ppIter = pNext; *piDocid = iDocid; }else{ int iMul = (bDescIdx ? -1 : 1); sqlite3_int64 iDelta; fts3GetReverseVarint(&p, aDoclist, &iDelta); *piDocid -= (iMul * iDelta); if( p==aDoclist ){ *pbEof = 1; }else{ char *pSave = p; fts3ReversePoslist(aDoclist, &p); *pnList = (int)(pSave - p); } *ppIter = p; } } /* ** Iterate forwards through a doclist. */ SQLITE_PRIVATE void sqlite3Fts3DoclistNext( int bDescIdx, /* True if the doclist is desc */ char *aDoclist, /* Pointer to entire doclist */ int nDoclist, /* Length of aDoclist in bytes */ char **ppIter, /* IN/OUT: Iterator pointer */ sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ u8 *pbEof /* OUT: End-of-file flag */ ){ char *p = *ppIter; assert( nDoclist>0 ); assert( *pbEof==0 ); assert( p || *piDocid==0 ); assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) ); if( p==0 ){ p = aDoclist; p += sqlite3Fts3GetVarint(p, piDocid); }else{ fts3PoslistCopy(0, &p); while( p<&aDoclist[nDoclist] && *p==0 ) p++; if( p>=&aDoclist[nDoclist] ){ *pbEof = 1; }else{ sqlite3_int64 iVar; p += sqlite3Fts3GetVarint(p, &iVar); *piDocid += ((bDescIdx ? -1 : 1) * iVar); } } *ppIter = p; } /* ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof ** to true if EOF is reached. */ static void fts3EvalDlPhraseNext( Fts3Table *pTab, Fts3Doclist *pDL, u8 *pbEof ){ char *pIter; /* Used to iterate through aAll */ char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */ if( pDL->pNextDocid ){ pIter = pDL->pNextDocid; }else{ pIter = pDL->aAll; } if( pIter>=pEnd ){ /* We have already reached the end of this doclist. EOF. */ *pbEof = 1; }else{ sqlite3_int64 iDelta; pIter += sqlite3Fts3GetVarint(pIter, &iDelta); if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){ pDL->iDocid += iDelta; }else{ pDL->iDocid -= iDelta; } pDL->pList = pIter; fts3PoslistCopy(0, &pIter); pDL->nList = (int)(pIter - pDL->pList); /* pIter now points just past the 0x00 that terminates the position- ** list for document pDL->iDocid. However, if this position-list was ** edited in place by fts3EvalNearTrim(), then pIter may not actually ** point to the start of the next docid value. The following line deals ** with this case by advancing pIter past the zero-padding added by ** fts3EvalNearTrim(). */ while( pIter<pEnd && *pIter==0 ) pIter++; pDL->pNextDocid = pIter; assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter ); *pbEof = 0; } } /* ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext(). */ typedef struct TokenDoclist TokenDoclist; struct TokenDoclist { int bIgnore; sqlite3_int64 iDocid; char *pList; int nList; }; /* ** Token pToken is an incrementally loaded token that is part of a ** multi-token phrase. Advance it to the next matching document in the ** database and populate output variable *p with the details of the new ** entry. Or, if the iterator has reached EOF, set *pbEof to true. ** ** If an error occurs, return an SQLite error code. Otherwise, return ** SQLITE_OK. */ static int incrPhraseTokenNext( Fts3Table *pTab, /* Virtual table handle */ Fts3Phrase *pPhrase, /* Phrase to advance token of */ int iToken, /* Specific token to advance */ TokenDoclist *p, /* OUT: Docid and doclist for new entry */ u8 *pbEof /* OUT: True if iterator is at EOF */ ){ int rc = SQLITE_OK; if( pPhrase->iDoclistToken==iToken ){ assert( p->bIgnore==0 ); assert( pPhrase->aToken[iToken].pSegcsr==0 ); fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof); p->pList = pPhrase->doclist.pList; p->nList = pPhrase->doclist.nList; p->iDocid = pPhrase->doclist.iDocid; }else{ Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; assert( pToken->pDeferred==0 ); assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 ); if( pToken->pSegcsr ){ assert( p->bIgnore==0 ); rc = sqlite3Fts3MsrIncrNext( pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList ); if( p->pList==0 ) *pbEof = 1; }else{ p->bIgnore = 1; } } return rc; } /* ** The phrase iterator passed as the second argument: ** ** * features at least one token that uses an incremental doclist, and ** ** * does not contain any deferred tokens. ** ** Advance it to the next matching documnent in the database and populate ** the Fts3Doclist.pList and nList fields. ** ** If there is no "next" entry and no error occurs, then *pbEof is set to ** 1 before returning. Otherwise, if no error occurs and the iterator is ** successfully advanced, *pbEof is set to 0. ** ** If an error occurs, return an SQLite error code. Otherwise, return ** SQLITE_OK. */ static int fts3EvalIncrPhraseNext( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Phrase *p, /* Phrase object to advance to next docid */ u8 *pbEof /* OUT: Set to 1 if EOF */ ){ int rc = SQLITE_OK; Fts3Doclist *pDL = &p->doclist; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; u8 bEof = 0; /* This is only called if it is guaranteed that the phrase has at least ** one incremental token. In which case the bIncr flag is set. */ assert( p->bIncr==1 ); if( p->nToken==1 && p->bIncr ){ rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, &pDL->iDocid, &pDL->pList, &pDL->nList ); if( pDL->pList==0 ) bEof = 1; }else{ int bDescDoclist = pCsr->bDesc; struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS]; memset(a, 0, sizeof(a)); assert( p->nToken<=MAX_INCR_PHRASE_TOKENS ); assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS ); while( bEof==0 ){ int bMaxSet = 0; sqlite3_int64 iMax = 0; /* Largest docid for all iterators */ int i; /* Used to iterate through tokens */ /* Advance the iterator for each token in the phrase once. */ for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){ rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){ iMax = a[i].iDocid; bMaxSet = 1; } } assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) ); assert( rc!=SQLITE_OK || bMaxSet ); /* Keep advancing iterators until they all point to the same document */ for(i=0; i<p->nToken; i++){ while( rc==SQLITE_OK && bEof==0 && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 ){ rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); if( DOCID_CMP(a[i].iDocid, iMax)>0 ){ iMax = a[i].iDocid; i = 0; } } } /* Check if the current entries really are a phrase match */ if( bEof==0 ){ int nList = 0; int nByte = a[p->nToken-1].nList; char *aDoclist = sqlite3_malloc(nByte+1); if( !aDoclist ) return SQLITE_NOMEM; memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); for(i=0; i<(p->nToken-1); i++){ if( a[i].bIgnore==0 ){ char *pL = a[i].pList; char *pR = aDoclist; char *pOut = aDoclist; int nDist = p->nToken-1-i; int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR); if( res==0 ) break; nList = (int)(pOut - aDoclist); } } if( i==(p->nToken-1) ){ pDL->iDocid = iMax; pDL->pList = aDoclist; pDL->nList = nList; pDL->bFreeList = 1; break; } sqlite3_free(aDoclist); } } } *pbEof = bEof; return rc; } /* ** Attempt to move the phrase iterator to point to the next matching docid. ** If an error occurs, return an SQLite error code. Otherwise, return ** SQLITE_OK. ** ** If there is no "next" entry and no error occurs, then *pbEof is set to ** 1 before returning. Otherwise, if no error occurs and the iterator is ** successfully advanced, *pbEof is set to 0. */ static int fts3EvalPhraseNext( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Phrase *p, /* Phrase object to advance to next docid */ u8 *pbEof /* OUT: Set to 1 if EOF */ ){ int rc = SQLITE_OK; Fts3Doclist *pDL = &p->doclist; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; if( p->bIncr ){ rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof); }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){ sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof ); pDL->pList = pDL->pNextDocid; }else{ fts3EvalDlPhraseNext(pTab, pDL, pbEof); } return rc; } /* ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the ** expression. Also the Fts3Expr.bDeferred variable is set to true for any ** expressions for which all descendent tokens are deferred. ** ** If parameter bOptOk is zero, then it is guaranteed that the ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for ** each phrase in the expression (subject to deferred token processing). ** Or, if bOptOk is non-zero, then one or more tokens within the expression ** may be loaded incrementally, meaning doclist.aAll/nAll is not available. ** ** If an error occurs within this function, *pRc is set to an SQLite error ** code before returning. */ static void fts3EvalStartReaders( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Expr *pExpr, /* Expression to initialize phrases in */ int *pRc /* IN/OUT: Error code */ ){ if( pExpr && SQLITE_OK==*pRc ){ if( pExpr->eType==FTSQUERY_PHRASE ){ int nToken = pExpr->pPhrase->nToken; if( nToken ){ int i; for(i=0; i<nToken; i++){ if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break; } pExpr->bDeferred = (i==nToken); } *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase); }else{ fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc); fts3EvalStartReaders(pCsr, pExpr->pRight, pRc); pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred); } } } /* ** An array of the following structures is assembled as part of the process ** of selecting tokens to defer before the query starts executing (as part ** of the xFilter() method). There is one element in the array for each ** token in the FTS expression. ** ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong ** to phrases that are connected only by AND and NEAR operators (not OR or ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered ** separately. The root of a tokens AND/NEAR cluster is stored in ** Fts3TokenAndCost.pRoot. */ typedef struct Fts3TokenAndCost Fts3TokenAndCost; struct Fts3TokenAndCost { Fts3Phrase *pPhrase; /* The phrase the token belongs to */ int iToken; /* Position of token in phrase */ Fts3PhraseToken *pToken; /* The token itself */ Fts3Expr *pRoot; /* Root of NEAR/AND cluster */ int nOvfl; /* Number of overflow pages to load doclist */ int iCol; /* The column the token must match */ }; /* ** This function is used to populate an allocated Fts3TokenAndCost array. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** Otherwise, if an error occurs during execution, *pRc is set to an ** SQLite error code. */ static void fts3EvalTokenCosts( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */ Fts3Expr *pExpr, /* Expression to consider */ Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */ Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */ int *pRc /* IN/OUT: Error code */ ){ if( *pRc==SQLITE_OK ){ if( pExpr->eType==FTSQUERY_PHRASE ){ Fts3Phrase *pPhrase = pExpr->pPhrase; int i; for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){ Fts3TokenAndCost *pTC = (*ppTC)++; pTC->pPhrase = pPhrase; pTC->iToken = i; pTC->pRoot = pRoot; pTC->pToken = &pPhrase->aToken[i]; pTC->iCol = pPhrase->iColumn; *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl); } }else if( pExpr->eType!=FTSQUERY_NOT ){ assert( pExpr->eType==FTSQUERY_OR || pExpr->eType==FTSQUERY_AND || pExpr->eType==FTSQUERY_NEAR ); assert( pExpr->pLeft && pExpr->pRight ); if( pExpr->eType==FTSQUERY_OR ){ pRoot = pExpr->pLeft; **ppOr = pRoot; (*ppOr)++; } fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc); if( pExpr->eType==FTSQUERY_OR ){ pRoot = pExpr->pRight; **ppOr = pRoot; (*ppOr)++; } fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc); } } } /* ** Determine the average document (row) size in pages. If successful, ** write this value to *pnPage and return SQLITE_OK. Otherwise, return ** an SQLite error code. ** ** The average document size in pages is calculated by first calculating ** determining the average size in bytes, B. If B is less than the amount ** of data that will fit on a single leaf page of an intkey table in ** this database, then the average docsize is 1. Otherwise, it is 1 plus ** the number of overflow pages consumed by a record B bytes in size. */ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ if( pCsr->nRowAvg==0 ){ /* The average document size, which is required to calculate the cost ** of each doclist, has not yet been determined. Read the required ** data from the %_stat table to calculate it. ** ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 ** varints, where nCol is the number of columns in the FTS3 table. ** The first varint is the number of documents currently stored in ** the table. The following nCol varints contain the total amount of ** data stored in all rows of each column of the table, from left ** to right. */ int rc; Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; sqlite3_stmt *pStmt; sqlite3_int64 nDoc = 0; sqlite3_int64 nByte = 0; const char *pEnd; const char *a; rc = sqlite3Fts3SelectDoctotal(p, &pStmt); if( rc!=SQLITE_OK ) return rc; a = sqlite3_column_blob(pStmt, 0); assert( a ); pEnd = &a[sqlite3_column_bytes(pStmt, 0)]; a += sqlite3Fts3GetVarint(a, &nDoc); while( a<pEnd ){ a += sqlite3Fts3GetVarint(a, &nByte); } if( nDoc==0 || nByte==0 ){ sqlite3_reset(pStmt); return FTS_CORRUPT_VTAB; } pCsr->nDoc = nDoc; pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz); assert( pCsr->nRowAvg>0 ); rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ) return rc; } *pnPage = pCsr->nRowAvg; return SQLITE_OK; } /* ** This function is called to select the tokens (if any) that will be ** deferred. The array aTC[] has already been populated when this is ** called. ** ** This function is called once for each AND/NEAR cluster in the ** expression. Each invocation determines which tokens to defer within ** the cluster with root node pRoot. See comments above the definition ** of struct Fts3TokenAndCost for more details. ** ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken() ** called on each token to defer. Otherwise, an SQLite error code is ** returned. */ static int fts3EvalSelectDeferred( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Expr *pRoot, /* Consider tokens with this root node */ Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */ int nTC /* Number of entries in aTC[] */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int nDocSize = 0; /* Number of pages per doc loaded */ int rc = SQLITE_OK; /* Return code */ int ii; /* Iterator variable for various purposes */ int nOvfl = 0; /* Total overflow pages used by doclists */ int nToken = 0; /* Total number of tokens in cluster */ int nMinEst = 0; /* The minimum count for any phrase so far. */ int nLoad4 = 1; /* (Phrases that will be loaded)^4. */ /* Tokens are never deferred for FTS tables created using the content=xxx ** option. The reason being that it is not guaranteed that the content ** table actually contains the same data as the index. To prevent this from ** causing any problems, the deferred token optimization is completely ** disabled for content=xxx tables. */ if( pTab->zContentTbl ){ return SQLITE_OK; } /* Count the tokens in this AND/NEAR cluster. If none of the doclists ** associated with the tokens spill onto overflow pages, or if there is ** only 1 token, exit early. No tokens to defer in this case. */ for(ii=0; ii<nTC; ii++){ if( aTC[ii].pRoot==pRoot ){ nOvfl += aTC[ii].nOvfl; nToken++; } } if( nOvfl==0 || nToken<2 ) return SQLITE_OK; /* Obtain the average docsize (in pages). */ rc = fts3EvalAverageDocsize(pCsr, &nDocSize); assert( rc!=SQLITE_OK || nDocSize>0 ); /* Iterate through all tokens in this AND/NEAR cluster, in ascending order ** of the number of overflow pages that will be loaded by the pager layer ** to retrieve the entire doclist for the token from the full-text index. ** Load the doclists for tokens that are either: ** ** a. The cheapest token in the entire query (i.e. the one visited by the ** first iteration of this loop), or ** ** b. Part of a multi-token phrase. ** ** After each token doclist is loaded, merge it with the others from the ** same phrase and count the number of documents that the merged doclist ** contains. Set variable "nMinEst" to the smallest number of documents in ** any phrase doclist for which 1 or more token doclists have been loaded. ** Let nOther be the number of other phrases for which it is certain that ** one or more tokens will not be deferred. ** ** Then, for each token, defer it if loading the doclist would result in ** loading N or more overflow pages into memory, where N is computed as: ** ** (nMinEst + 4^nOther - 1) / (4^nOther) */ for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){ int iTC; /* Used to iterate through aTC[] array. */ Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */ /* Set pTC to point to the cheapest remaining token. */ for(iTC=0; iTC<nTC; iTC++){ if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) ){ pTC = &aTC[iTC]; } } assert( pTC ); if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){ /* The number of overflow pages to load for this (and therefore all ** subsequent) tokens is greater than the estimated number of pages ** that will be loaded if all subsequent tokens are deferred. */ Fts3PhraseToken *pToken = pTC->pToken; rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol); fts3SegReaderCursorFree(pToken->pSegcsr); pToken->pSegcsr = 0; }else{ /* Set nLoad4 to the value of (4^nOther) for the next iteration of the ** for-loop. Except, limit the value to 2^24 to prevent it from ** overflowing the 32-bit integer it is stored in. */ if( ii<12 ) nLoad4 = nLoad4*4; if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){ /* Either this is the cheapest token in the entire query, or it is ** part of a multi-token phrase. Either way, the entire doclist will ** (eventually) be loaded into memory. It may as well be now. */ Fts3PhraseToken *pToken = pTC->pToken; int nList = 0; char *pList = 0; rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList); assert( rc==SQLITE_OK || pList==0 ); if( rc==SQLITE_OK ){ rc = fts3EvalPhraseMergeToken( pTab, pTC->pPhrase, pTC->iToken,pList,nList ); } if( rc==SQLITE_OK ){ int nCount; nCount = fts3DoclistCountDocids( pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll ); if( ii==0 || nCount<nMinEst ) nMinEst = nCount; } } } pTC->pToken = 0; } return rc; } /* ** This function is called from within the xFilter method. It initializes ** the full-text query currently stored in pCsr->pExpr. To iterate through ** the results of a query, the caller does: ** ** fts3EvalStart(pCsr); ** while( 1 ){ ** fts3EvalNext(pCsr); ** if( pCsr->bEof ) break; ** ... return row pCsr->iPrevId to the caller ... ** } */ static int fts3EvalStart(Fts3Cursor *pCsr){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; int nToken = 0; int nOr = 0; /* Allocate a MultiSegReader for each token in the expression. */ fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc); /* Determine which, if any, tokens in the expression should be deferred. */ #ifndef SQLITE_DISABLE_FTS4_DEFERRED if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){ Fts3TokenAndCost *aTC; Fts3Expr **apOr; aTC = (Fts3TokenAndCost *)sqlite3_malloc( sizeof(Fts3TokenAndCost) * nToken + sizeof(Fts3Expr *) * nOr * 2 ); apOr = (Fts3Expr **)&aTC[nToken]; if( !aTC ){ rc = SQLITE_NOMEM; }else{ int ii; Fts3TokenAndCost *pTC = aTC; Fts3Expr **ppOr = apOr; fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc); nToken = (int)(pTC-aTC); nOr = (int)(ppOr-apOr); if( rc==SQLITE_OK ){ rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken); for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){ rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken); } } sqlite3_free(aTC); } } #endif fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc); return rc; } /* ** Invalidate the current position list for phrase pPhrase. */ static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){ if( pPhrase->doclist.bFreeList ){ sqlite3_free(pPhrase->doclist.pList); } pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; pPhrase->doclist.bFreeList = 0; } /* ** This function is called to edit the position list associated with ** the phrase object passed as the fifth argument according to a NEAR ** condition. For example: ** ** abc NEAR/5 "def ghi" ** ** Parameter nNear is passed the NEAR distance of the expression (5 in ** the example above). When this function is called, *paPoslist points to ** the position list, and *pnToken is the number of phrase tokens in, the ** phrase on the other side of the NEAR operator to pPhrase. For example, ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to ** the position list associated with phrase "abc". ** ** All positions in the pPhrase position list that are not sufficiently ** close to a position in the *paPoslist position list are removed. If this ** leaves 0 positions, zero is returned. Otherwise, non-zero. ** ** Before returning, *paPoslist is set to point to the position lsit ** associated with pPhrase. And *pnToken is set to the number of tokens in ** pPhrase. */ static int fts3EvalNearTrim( int nNear, /* NEAR distance. As in "NEAR/nNear". */ char *aTmp, /* Temporary space to use */ char **paPoslist, /* IN/OUT: Position list */ int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */ Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */ ){ int nParam1 = nNear + pPhrase->nToken; int nParam2 = nNear + *pnToken; int nNew; char *p2; char *pOut; int res; assert( pPhrase->doclist.pList ); p2 = pOut = pPhrase->doclist.pList; res = fts3PoslistNearMerge( &pOut, aTmp, nParam1, nParam2, paPoslist, &p2 ); if( res ){ nNew = (int)(pOut - pPhrase->doclist.pList) - 1; assert( pPhrase->doclist.pList[nNew]=='\0' ); assert( nNew<=pPhrase->doclist.nList && nNew>0 ); memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew); pPhrase->doclist.nList = nNew; *paPoslist = pPhrase->doclist.pList; *pnToken = pPhrase->nToken; } return res; } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is called. ** Otherwise, it advances the expression passed as the second argument to ** point to the next matching row in the database. Expressions iterate through ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero, ** or descending if it is non-zero. ** ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if ** successful, the following variables in pExpr are set: ** ** Fts3Expr.bEof (non-zero if EOF - there is no next row) ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row) ** ** If the expression is of type FTSQUERY_PHRASE, and the expression is not ** at EOF, then the following variables are populated with the position list ** for the phrase for the visited row: ** ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes) ** FTs3Expr.pPhrase->doclist.pList (pointer to position list) ** ** It says above that this function advances the expression to the next ** matching row. This is usually true, but there are the following exceptions: ** ** 1. Deferred tokens are not taken into account. If a phrase consists ** entirely of deferred tokens, it is assumed to match every row in ** the db. In this case the position-list is not populated at all. ** ** Or, if a phrase contains one or more deferred tokens and one or ** more non-deferred tokens, then the expression is advanced to the ** next possible match, considering only non-deferred tokens. In other ** words, if the phrase is "A B C", and "B" is deferred, the expression ** is advanced to the next row that contains an instance of "A * C", ** where "*" may match any single token. The position list in this case ** is populated as for "A * C" before returning. ** ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is ** advanced to point to the next row that matches "x AND y". ** ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is ** really a match, taking into account deferred tokens and NEAR operators. */ static void fts3EvalNextRow( Fts3Cursor *pCsr, /* FTS Cursor handle */ Fts3Expr *pExpr, /* Expr. to advance to next matching row */ int *pRc /* IN/OUT: Error code */ ){ if( *pRc==SQLITE_OK ){ int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */ assert( pExpr->bEof==0 ); pExpr->bStart = 1; switch( pExpr->eType ){ case FTSQUERY_NEAR: case FTSQUERY_AND: { Fts3Expr *pLeft = pExpr->pLeft; Fts3Expr *pRight = pExpr->pRight; assert( !pLeft->bDeferred || !pRight->bDeferred ); if( pLeft->bDeferred ){ /* LHS is entirely deferred. So we assume it matches every row. ** Advance the RHS iterator to find the next row visited. */ fts3EvalNextRow(pCsr, pRight, pRc); pExpr->iDocid = pRight->iDocid; pExpr->bEof = pRight->bEof; }else if( pRight->bDeferred ){ /* RHS is entirely deferred. So we assume it matches every row. ** Advance the LHS iterator to find the next row visited. */ fts3EvalNextRow(pCsr, pLeft, pRc); pExpr->iDocid = pLeft->iDocid; pExpr->bEof = pLeft->bEof; }else{ /* Neither the RHS or LHS are deferred. */ fts3EvalNextRow(pCsr, pLeft, pRc); fts3EvalNextRow(pCsr, pRight, pRc); while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){ sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid); if( iDiff==0 ) break; if( iDiff<0 ){ fts3EvalNextRow(pCsr, pLeft, pRc); }else{ fts3EvalNextRow(pCsr, pRight, pRc); } } pExpr->iDocid = pLeft->iDocid; pExpr->bEof = (pLeft->bEof || pRight->bEof); if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){ if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){ Fts3Doclist *pDl = &pRight->pPhrase->doclist; while( *pRc==SQLITE_OK && pRight->bEof==0 ){ memset(pDl->pList, 0, pDl->nList); fts3EvalNextRow(pCsr, pRight, pRc); } } if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){ Fts3Doclist *pDl = &pLeft->pPhrase->doclist; while( *pRc==SQLITE_OK && pLeft->bEof==0 ){ memset(pDl->pList, 0, pDl->nList); fts3EvalNextRow(pCsr, pLeft, pRc); } } } } break; } case FTSQUERY_OR: { Fts3Expr *pLeft = pExpr->pLeft; Fts3Expr *pRight = pExpr->pRight; sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid ); assert( pRight->bStart || pLeft->iDocid==pRight->iDocid ); if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ fts3EvalNextRow(pCsr, pLeft, pRc); }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){ fts3EvalNextRow(pCsr, pRight, pRc); }else{ fts3EvalNextRow(pCsr, pLeft, pRc); fts3EvalNextRow(pCsr, pRight, pRc); } pExpr->bEof = (pLeft->bEof && pRight->bEof); iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ pExpr->iDocid = pLeft->iDocid; }else{ pExpr->iDocid = pRight->iDocid; } break; } case FTSQUERY_NOT: { Fts3Expr *pLeft = pExpr->pLeft; Fts3Expr *pRight = pExpr->pRight; if( pRight->bStart==0 ){ fts3EvalNextRow(pCsr, pRight, pRc); assert( *pRc!=SQLITE_OK || pRight->bStart ); } fts3EvalNextRow(pCsr, pLeft, pRc); if( pLeft->bEof==0 ){ while( !*pRc && !pRight->bEof && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 ){ fts3EvalNextRow(pCsr, pRight, pRc); } } pExpr->iDocid = pLeft->iDocid; pExpr->bEof = pLeft->bEof; break; } default: { Fts3Phrase *pPhrase = pExpr->pPhrase; fts3EvalInvalidatePoslist(pPhrase); *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof); pExpr->iDocid = pPhrase->doclist.iDocid; break; } } } } /* ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR ** cluster, then this function returns 1 immediately. ** ** Otherwise, it checks if the current row really does match the NEAR ** expression, using the data currently stored in the position lists ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. ** ** If the current row is a match, the position list associated with each ** phrase in the NEAR expression is edited in place to contain only those ** phrase instances sufficiently close to their peers to satisfy all NEAR ** constraints. In this case it returns 1. If the NEAR expression does not ** match the current row, 0 is returned. The position lists may or may not ** be edited if 0 is returned. */ static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){ int res = 1; /* The following block runs if pExpr is the root of a NEAR query. ** For example, the query: ** ** "w" NEAR "x" NEAR "y" NEAR "z" ** ** which is represented in tree form as: ** ** | ** +--NEAR--+ <-- root of NEAR query ** | | ** +--NEAR--+ "z" ** | | ** +--NEAR--+ "y" ** | | ** "w" "x" ** ** The right-hand child of a NEAR node is always a phrase. The ** left-hand child may be either a phrase or a NEAR node. There are ** no exceptions to this - it's the way the parser in fts3_expr.c works. */ if( *pRc==SQLITE_OK && pExpr->eType==FTSQUERY_NEAR && pExpr->bEof==0 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) ){ Fts3Expr *p; int nTmp = 0; /* Bytes of temp space */ char *aTmp; /* Temp space for PoslistNearMerge() */ /* Allocate temporary working space. */ for(p=pExpr; p->pLeft; p=p->pLeft){ nTmp += p->pRight->pPhrase->doclist.nList; } nTmp += p->pPhrase->doclist.nList; if( nTmp==0 ){ res = 0; }else{ aTmp = sqlite3_malloc(nTmp*2); if( !aTmp ){ *pRc = SQLITE_NOMEM; res = 0; }else{ char *aPoslist = p->pPhrase->doclist.pList; int nToken = p->pPhrase->nToken; for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){ Fts3Phrase *pPhrase = p->pRight->pPhrase; int nNear = p->nNear; res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); } aPoslist = pExpr->pRight->pPhrase->doclist.pList; nToken = pExpr->pRight->pPhrase->nToken; for(p=pExpr->pLeft; p && res; p=p->pLeft){ int nNear; Fts3Phrase *pPhrase; assert( p->pParent && p->pParent->pLeft==p ); nNear = p->pParent->nNear; pPhrase = ( p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase ); res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); } } sqlite3_free(aTmp); } } return res; } /* ** This function is a helper function for sqlite3Fts3EvalTestDeferred(). ** Assuming no error occurs or has occurred, It returns non-zero if the ** expression passed as the second argument matches the row that pCsr ** currently points to, or zero if it does not. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** If an error occurs during execution of this function, *pRc is set to ** the appropriate SQLite error code. In this case the returned value is ** undefined. */ static int fts3EvalTestExpr( Fts3Cursor *pCsr, /* FTS cursor handle */ Fts3Expr *pExpr, /* Expr to test. May or may not be root. */ int *pRc /* IN/OUT: Error code */ ){ int bHit = 1; /* Return value */ if( *pRc==SQLITE_OK ){ switch( pExpr->eType ){ case FTSQUERY_NEAR: case FTSQUERY_AND: bHit = ( fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) && fts3EvalNearTest(pExpr, pRc) ); /* If the NEAR expression does not match any rows, zero the doclist for ** all phrases involved in the NEAR. This is because the snippet(), ** offsets() and matchinfo() functions are not supposed to recognize ** any instances of phrases that are part of unmatched NEAR queries. ** For example if this expression: ** ** ... MATCH 'a OR (b NEAR c)' ** ** is matched against a row containing: ** ** 'a b d e' ** ** then any snippet() should ony highlight the "a" term, not the "b" ** (as "b" is part of a non-matching NEAR clause). */ if( bHit==0 && pExpr->eType==FTSQUERY_NEAR && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) ){ Fts3Expr *p; for(p=pExpr; p->pPhrase==0; p=p->pLeft){ if( p->pRight->iDocid==pCsr->iPrevId ){ fts3EvalInvalidatePoslist(p->pRight->pPhrase); } } if( p->iDocid==pCsr->iPrevId ){ fts3EvalInvalidatePoslist(p->pPhrase); } } break; case FTSQUERY_OR: { int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc); int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc); bHit = bHit1 || bHit2; break; } case FTSQUERY_NOT: bHit = ( fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) ); break; default: { #ifndef SQLITE_DISABLE_FTS4_DEFERRED if( pCsr->pDeferred && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred) ){ Fts3Phrase *pPhrase = pExpr->pPhrase; assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 ); if( pExpr->bDeferred ){ fts3EvalInvalidatePoslist(pPhrase); } *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase); bHit = (pPhrase->doclist.pList!=0); pExpr->iDocid = pCsr->iPrevId; }else #endif { bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId); } break; } } } return bHit; } /* ** This function is called as the second part of each xNext operation when ** iterating through the results of a full-text query. At this point the ** cursor points to a row that matches the query expression, with the ** following caveats: ** ** * Up until this point, "NEAR" operators in the expression have been ** treated as "AND". ** ** * Deferred tokens have not yet been considered. ** ** If *pRc is not SQLITE_OK when this function is called, it immediately ** returns 0. Otherwise, it tests whether or not after considering NEAR ** operators and deferred tokens the current row is still a match for the ** expression. It returns 1 if both of the following are true: ** ** 1. *pRc is SQLITE_OK when this function returns, and ** ** 2. After scanning the current FTS table row for the deferred tokens, ** it is determined that the row does *not* match the query. ** ** Or, if no error occurs and it seems the current row does match the FTS ** query, return 0. */ SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){ int rc = *pRc; int bMiss = 0; if( rc==SQLITE_OK ){ /* If there are one or more deferred tokens, load the current row into ** memory and scan it to determine the position list for each deferred ** token. Then, see if this row is really a match, considering deferred ** tokens and NEAR operators (neither of which were taken into account ** earlier, by fts3EvalNextRow()). */ if( pCsr->pDeferred ){ rc = fts3CursorSeek(0, pCsr); if( rc==SQLITE_OK ){ rc = sqlite3Fts3CacheDeferredDoclists(pCsr); } } bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc)); /* Free the position-lists accumulated for each deferred token above. */ sqlite3Fts3FreeDeferredDoclists(pCsr); *pRc = rc; } return (rc==SQLITE_OK && bMiss); } /* ** Advance to the next document that matches the FTS expression in ** Fts3Cursor.pExpr. */ static int fts3EvalNext(Fts3Cursor *pCsr){ int rc = SQLITE_OK; /* Return Code */ Fts3Expr *pExpr = pCsr->pExpr; assert( pCsr->isEof==0 ); if( pExpr==0 ){ pCsr->isEof = 1; }else{ do { if( pCsr->isRequireSeek==0 ){ sqlite3_reset(pCsr->pStmt); } assert( sqlite3_data_count(pCsr->pStmt)==0 ); fts3EvalNextRow(pCsr, pExpr, &rc); pCsr->isEof = pExpr->bEof; pCsr->isRequireSeek = 1; pCsr->isMatchinfoNeeded = 1; pCsr->iPrevId = pExpr->iDocid; }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) ); } /* Check if the cursor is past the end of the docid range specified ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */ if( rc==SQLITE_OK && ( (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid) || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid) )){ pCsr->isEof = 1; } return rc; } /* ** Restart interation for expression pExpr so that the next call to ** fts3EvalNext() visits the first row. Do not allow incremental ** loading or merging of phrase doclists for this iteration. ** ** If *pRc is other than SQLITE_OK when this function is called, it is ** a no-op. If an error occurs within this function, *pRc is set to an ** SQLite error code before returning. */ static void fts3EvalRestart( Fts3Cursor *pCsr, Fts3Expr *pExpr, int *pRc ){ if( pExpr && *pRc==SQLITE_OK ){ Fts3Phrase *pPhrase = pExpr->pPhrase; if( pPhrase ){ fts3EvalInvalidatePoslist(pPhrase); if( pPhrase->bIncr ){ int i; for(i=0; i<pPhrase->nToken; i++){ Fts3PhraseToken *pToken = &pPhrase->aToken[i]; assert( pToken->pDeferred==0 ); if( pToken->pSegcsr ){ sqlite3Fts3MsrIncrRestart(pToken->pSegcsr); } } *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase); } pPhrase->doclist.pNextDocid = 0; pPhrase->doclist.iDocid = 0; pPhrase->pOrPoslist = 0; } pExpr->iDocid = 0; pExpr->bEof = 0; pExpr->bStart = 0; fts3EvalRestart(pCsr, pExpr->pLeft, pRc); fts3EvalRestart(pCsr, pExpr->pRight, pRc); } } /* ** After allocating the Fts3Expr.aMI[] array for each phrase in the ** expression rooted at pExpr, the cursor iterates through all rows matched ** by pExpr, calling this function for each row. This function increments ** the values in Fts3Expr.aMI[] according to the position-list currently ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase ** expression nodes. */ static void fts3EvalUpdateCounts(Fts3Expr *pExpr){ if( pExpr ){ Fts3Phrase *pPhrase = pExpr->pPhrase; if( pPhrase && pPhrase->doclist.pList ){ int iCol = 0; char *p = pPhrase->doclist.pList; assert( *p ); while( 1 ){ u8 c = 0; int iCnt = 0; while( 0xFE & (*p | c) ){ if( (c&0x80)==0 ) iCnt++; c = *p++ & 0x80; } /* aMI[iCol*3 + 1] = Number of occurrences ** aMI[iCol*3 + 2] = Number of rows containing at least one instance */ pExpr->aMI[iCol*3 + 1] += iCnt; pExpr->aMI[iCol*3 + 2] += (iCnt>0); if( *p==0x00 ) break; p++; p += fts3GetVarint32(p, &iCol); } } fts3EvalUpdateCounts(pExpr->pLeft); fts3EvalUpdateCounts(pExpr->pRight); } } /* ** Expression pExpr must be of type FTSQUERY_PHRASE. ** ** If it is not already allocated and populated, this function allocates and ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part ** of a NEAR expression, then it also allocates and populates the same array ** for all other phrases that are part of the NEAR expression. ** ** SQLITE_OK is returned if the aMI[] array is successfully allocated and ** populated. Otherwise, if an error occurs, an SQLite error code is returned. */ static int fts3EvalGatherStats( Fts3Cursor *pCsr, /* Cursor object */ Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */ ){ int rc = SQLITE_OK; /* Return code */ assert( pExpr->eType==FTSQUERY_PHRASE ); if( pExpr->aMI==0 ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; Fts3Expr *pRoot; /* Root of NEAR expression */ Fts3Expr *p; /* Iterator used for several purposes */ sqlite3_int64 iPrevId = pCsr->iPrevId; sqlite3_int64 iDocid; u8 bEof; /* Find the root of the NEAR expression */ pRoot = pExpr; while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){ pRoot = pRoot->pParent; } iDocid = pRoot->iDocid; bEof = pRoot->bEof; assert( pRoot->bStart ); /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */ for(p=pRoot; p; p=p->pLeft){ Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight); assert( pE->aMI==0 ); pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32)); if( !pE->aMI ) return SQLITE_NOMEM; memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32)); } fts3EvalRestart(pCsr, pRoot, &rc); while( pCsr->isEof==0 && rc==SQLITE_OK ){ do { /* Ensure the %_content statement is reset. */ if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt); assert( sqlite3_data_count(pCsr->pStmt)==0 ); /* Advance to the next document */ fts3EvalNextRow(pCsr, pRoot, &rc); pCsr->isEof = pRoot->bEof; pCsr->isRequireSeek = 1; pCsr->isMatchinfoNeeded = 1; pCsr->iPrevId = pRoot->iDocid; }while( pCsr->isEof==0 && pRoot->eType==FTSQUERY_NEAR && sqlite3Fts3EvalTestDeferred(pCsr, &rc) ); if( rc==SQLITE_OK && pCsr->isEof==0 ){ fts3EvalUpdateCounts(pRoot); } } pCsr->isEof = 0; pCsr->iPrevId = iPrevId; if( bEof ){ pRoot->bEof = bEof; }else{ /* Caution: pRoot may iterate through docids in ascending or descending ** order. For this reason, even though it seems more defensive, the ** do loop can not be written: ** ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK ); */ fts3EvalRestart(pCsr, pRoot, &rc); do { fts3EvalNextRow(pCsr, pRoot, &rc); assert( pRoot->bEof==0 ); }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK ); } } return rc; } /* ** This function is used by the matchinfo() module to query a phrase ** expression node for the following information: ** ** 1. The total number of occurrences of the phrase in each column of ** the FTS table (considering all rows), and ** ** 2. For each column, the number of rows in the table for which the ** column contains at least one instance of the phrase. ** ** If no error occurs, SQLITE_OK is returned and the values for each column ** written into the array aiOut as follows: ** ** aiOut[iCol*3 + 1] = Number of occurrences ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance ** ** Caveats: ** ** * If a phrase consists entirely of deferred tokens, then all output ** values are set to the number of documents in the table. In other ** words we assume that very common tokens occur exactly once in each ** column of each row of the table. ** ** * If a phrase contains some deferred tokens (and some non-deferred ** tokens), count the potential occurrence identified by considering ** the non-deferred tokens instead of actual phrase occurrences. ** ** * If the phrase is part of a NEAR expression, then only phrase instances ** that meet the NEAR constraint are included in the counts. */ SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats( Fts3Cursor *pCsr, /* FTS cursor handle */ Fts3Expr *pExpr, /* Phrase expression */ u32 *aiOut /* Array to write results into (see above) */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; int iCol; if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){ assert( pCsr->nDoc>0 ); for(iCol=0; iCol<pTab->nColumn; iCol++){ aiOut[iCol*3 + 1] = (u32)pCsr->nDoc; aiOut[iCol*3 + 2] = (u32)pCsr->nDoc; } }else{ rc = fts3EvalGatherStats(pCsr, pExpr); if( rc==SQLITE_OK ){ assert( pExpr->aMI ); for(iCol=0; iCol<pTab->nColumn; iCol++){ aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1]; aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2]; } } } return rc; } /* ** The expression pExpr passed as the second argument to this function ** must be of type FTSQUERY_PHRASE. ** ** The returned value is either NULL or a pointer to a buffer containing ** a position-list indicating the occurrences of the phrase in column iCol ** of the current row. ** ** More specifically, the returned buffer contains 1 varint for each ** occurrence of the phrase in the column, stored using the normal (delta+2) ** compression and is terminated by either an 0x01 or 0x00 byte. For example, ** if the requested column contains "a b X c d X X" and the position-list ** for 'X' is requested, the buffer returned may contain: ** ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00 ** ** This function works regardless of whether or not the phrase is deferred, ** incremental, or neither. */ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( Fts3Cursor *pCsr, /* FTS3 cursor object */ Fts3Expr *pExpr, /* Phrase to return doclist for */ int iCol, /* Column to return position list for */ char **ppOut /* OUT: Pointer to position list */ ){ Fts3Phrase *pPhrase = pExpr->pPhrase; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; char *pIter; int iThis; sqlite3_int64 iDocid; /* If this phrase is applies specifically to some column other than ** column iCol, return a NULL pointer. */ *ppOut = 0; assert( iCol>=0 && iCol<pTab->nColumn ); if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){ return SQLITE_OK; } iDocid = pExpr->iDocid; pIter = pPhrase->doclist.pList; if( iDocid!=pCsr->iPrevId || pExpr->bEof ){ int rc = SQLITE_OK; int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */ int bOr = 0; u8 bTreeEof = 0; Fts3Expr *p; /* Used to iterate from pExpr to root */ Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */ int bMatch; /* Check if this phrase descends from an OR expression node. If not, ** return NULL. Otherwise, the entry that corresponds to docid ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the ** tree that the node is part of has been marked as EOF, but the node ** itself is not EOF, then it may point to an earlier entry. */ pNear = pExpr; for(p=pExpr->pParent; p; p=p->pParent){ if( p->eType==FTSQUERY_OR ) bOr = 1; if( p->eType==FTSQUERY_NEAR ) pNear = p; if( p->bEof ) bTreeEof = 1; } if( bOr==0 ) return SQLITE_OK; /* This is the descendent of an OR node. In this case we cannot use ** an incremental phrase. Load the entire doclist for the phrase ** into memory in this case. */ if( pPhrase->bIncr ){ int bEofSave = pNear->bEof; fts3EvalRestart(pCsr, pNear, &rc); while( rc==SQLITE_OK && !pNear->bEof ){ fts3EvalNextRow(pCsr, pNear, &rc); if( bEofSave==0 && pNear->iDocid==iDocid ) break; } assert( rc!=SQLITE_OK || pPhrase->bIncr==0 ); } if( bTreeEof ){ while( rc==SQLITE_OK && !pNear->bEof ){ fts3EvalNextRow(pCsr, pNear, &rc); } } if( rc!=SQLITE_OK ) return rc; bMatch = 1; for(p=pNear; p; p=p->pLeft){ u8 bEof = 0; Fts3Expr *pTest = p; Fts3Phrase *pPh; assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE ); if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight; assert( pTest->eType==FTSQUERY_PHRASE ); pPh = pTest->pPhrase; pIter = pPh->pOrPoslist; iDocid = pPh->iOrDocid; if( pCsr->bDesc==bDescDoclist ){ bEof = !pPh->doclist.nAll || (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll)); while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){ sqlite3Fts3DoclistNext( bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, &pIter, &iDocid, &bEof ); } }else{ bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll); while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){ int dummy; sqlite3Fts3DoclistPrev( bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, &pIter, &iDocid, &dummy, &bEof ); } } pPh->pOrPoslist = pIter; pPh->iOrDocid = iDocid; if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0; } if( bMatch ){ pIter = pPhrase->pOrPoslist; }else{ pIter = 0; } } if( pIter==0 ) return SQLITE_OK; if( *pIter==0x01 ){ pIter++; pIter += fts3GetVarint32(pIter, &iThis); }else{ iThis = 0; } while( iThis<iCol ){ fts3ColumnlistCopy(0, &pIter); if( *pIter==0x00 ) return SQLITE_OK; pIter++; pIter += fts3GetVarint32(pIter, &iThis); } if( *pIter==0x00 ){ pIter = 0; } *ppOut = ((iCol==iThis)?pIter:0); return SQLITE_OK; } /* ** Free all components of the Fts3Phrase structure that were allocated by ** the eval module. Specifically, this means to free: ** ** * the contents of pPhrase->doclist, and ** * any Fts3MultiSegReader objects held by phrase tokens. */ SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ if( pPhrase ){ int i; sqlite3_free(pPhrase->doclist.aAll); fts3EvalInvalidatePoslist(pPhrase); memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist)); for(i=0; i<pPhrase->nToken; i++){ fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr); pPhrase->aToken[i].pSegcsr = 0; } } } /* ** Return SQLITE_CORRUPT_VTAB. */ #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3Fts3Corrupt(){ return SQLITE_CORRUPT_VTAB; } #endif #if !SQLITE_CORE /* ** Initialize API pointer table, if required. */ #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_fts3_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) return sqlite3Fts3Init(db); } #endif #endif /************** End of fts3.c ************************************************/ /************** Begin file fts3_aux.c ****************************************/ /* ** 2011 Jan 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <string.h> */ /* #include <assert.h> */ typedef struct Fts3auxTable Fts3auxTable; typedef struct Fts3auxCursor Fts3auxCursor; struct Fts3auxTable { sqlite3_vtab base; /* Base class used by SQLite core */ Fts3Table *pFts3Tab; }; struct Fts3auxCursor { sqlite3_vtab_cursor base; /* Base class used by SQLite core */ Fts3MultiSegReader csr; /* Must be right after "base" */ Fts3SegFilter filter; char *zStop; int nStop; /* Byte-length of string zStop */ int iLangid; /* Language id to query */ int isEof; /* True if cursor is at EOF */ sqlite3_int64 iRowid; /* Current rowid */ int iCol; /* Current value of 'col' column */ int nStat; /* Size of aStat[] array */ struct Fts3auxColstats { sqlite3_int64 nDoc; /* 'documents' values for current csr row */ sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */ } *aStat; }; /* ** Schema of the terms table. */ #define FTS3_AUX_SCHEMA \ "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)" /* ** This function does all the work for both the xConnect and xCreate methods. ** These tables have no persistent representation of their own, so xConnect ** and xCreate are identical operations. */ static int fts3auxConnectMethod( sqlite3 *db, /* Database connection */ void *pUnused, /* Unused */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ char const *zDb; /* Name of database (e.g. "main") */ char const *zFts3; /* Name of fts3 table */ int nDb; /* Result of strlen(zDb) */ int nFts3; /* Result of strlen(zFts3) */ int nByte; /* Bytes of space to allocate here */ int rc; /* value returned by declare_vtab() */ Fts3auxTable *p; /* Virtual table object to return */ UNUSED_PARAMETER(pUnused); /* The user should invoke this in one of two forms: ** ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table); ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table); */ if( argc!=4 && argc!=5 ) goto bad_args; zDb = argv[1]; nDb = (int)strlen(zDb); if( argc==5 ){ if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){ zDb = argv[3]; nDb = (int)strlen(zDb); zFts3 = argv[4]; }else{ goto bad_args; } }else{ zFts3 = argv[3]; } nFts3 = (int)strlen(zFts3); rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA); if( rc!=SQLITE_OK ) return rc; nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2; p = (Fts3auxTable *)sqlite3_malloc(nByte); if( !p ) return SQLITE_NOMEM; memset(p, 0, nByte); p->pFts3Tab = (Fts3Table *)&p[1]; p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1]; p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1]; p->pFts3Tab->db = db; p->pFts3Tab->nIndex = 1; memcpy((char *)p->pFts3Tab->zDb, zDb, nDb); memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3); sqlite3Fts3Dequote((char *)p->pFts3Tab->zName); *ppVtab = (sqlite3_vtab *)p; return SQLITE_OK; bad_args: sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor"); return SQLITE_ERROR; } /* ** This function does the work for both the xDisconnect and xDestroy methods. ** These tables have no persistent representation of their own, so xDisconnect ** and xDestroy are identical operations. */ static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){ Fts3auxTable *p = (Fts3auxTable *)pVtab; Fts3Table *pFts3 = p->pFts3Tab; int i; /* Free any prepared statements held */ for(i=0; i<SizeofArray(pFts3->aStmt); i++){ sqlite3_finalize(pFts3->aStmt[i]); } sqlite3_free(pFts3->zSegmentsTbl); sqlite3_free(p); return SQLITE_OK; } #define FTS4AUX_EQ_CONSTRAINT 1 #define FTS4AUX_GE_CONSTRAINT 2 #define FTS4AUX_LE_CONSTRAINT 4 /* ** xBestIndex - Analyze a WHERE and ORDER BY clause. */ static int fts3auxBestIndexMethod( sqlite3_vtab *pVTab, sqlite3_index_info *pInfo ){ int i; int iEq = -1; int iGe = -1; int iLe = -1; int iLangid = -1; int iNext = 1; /* Next free argvIndex value */ UNUSED_PARAMETER(pVTab); /* This vtab delivers always results in "ORDER BY term ASC" order. */ if( pInfo->nOrderBy==1 && pInfo->aOrderBy[0].iColumn==0 && pInfo->aOrderBy[0].desc==0 ){ pInfo->orderByConsumed = 1; } /* Search for equality and range constraints on the "term" column. ** And equality constraints on the hidden "languageid" column. */ for(i=0; i<pInfo->nConstraint; i++){ if( pInfo->aConstraint[i].usable ){ int op = pInfo->aConstraint[i].op; int iCol = pInfo->aConstraint[i].iColumn; if( iCol==0 ){ if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i; if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i; if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i; if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i; if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i; } if( iCol==4 ){ if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i; } } } if( iEq>=0 ){ pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT; pInfo->aConstraintUsage[iEq].argvIndex = iNext++; pInfo->estimatedCost = 5; }else{ pInfo->idxNum = 0; pInfo->estimatedCost = 20000; if( iGe>=0 ){ pInfo->idxNum += FTS4AUX_GE_CONSTRAINT; pInfo->aConstraintUsage[iGe].argvIndex = iNext++; pInfo->estimatedCost /= 2; } if( iLe>=0 ){ pInfo->idxNum += FTS4AUX_LE_CONSTRAINT; pInfo->aConstraintUsage[iLe].argvIndex = iNext++; pInfo->estimatedCost /= 2; } } if( iLangid>=0 ){ pInfo->aConstraintUsage[iLangid].argvIndex = iNext++; pInfo->estimatedCost--; } return SQLITE_OK; } /* ** xOpen - Open a cursor. */ static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ Fts3auxCursor *pCsr; /* Pointer to cursor object to return */ UNUSED_PARAMETER(pVTab); pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor)); if( !pCsr ) return SQLITE_NOMEM; memset(pCsr, 0, sizeof(Fts3auxCursor)); *ppCsr = (sqlite3_vtab_cursor *)pCsr; return SQLITE_OK; } /* ** xClose - Close a cursor. */ static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){ Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; sqlite3Fts3SegmentsClose(pFts3); sqlite3Fts3SegReaderFinish(&pCsr->csr); sqlite3_free((void *)pCsr->filter.zTerm); sqlite3_free(pCsr->zStop); sqlite3_free(pCsr->aStat); sqlite3_free(pCsr); return SQLITE_OK; } static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){ if( nSize>pCsr->nStat ){ struct Fts3auxColstats *aNew; aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, sizeof(struct Fts3auxColstats) * nSize ); if( aNew==0 ) return SQLITE_NOMEM; memset(&aNew[pCsr->nStat], 0, sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat) ); pCsr->aStat = aNew; pCsr->nStat = nSize; } return SQLITE_OK; } /* ** xNext - Advance the cursor to the next row, if any. */ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; int rc; /* Increment our pretend rowid value. */ pCsr->iRowid++; for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){ if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK; } rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr); if( rc==SQLITE_ROW ){ int i = 0; int nDoclist = pCsr->csr.nDoclist; char *aDoclist = pCsr->csr.aDoclist; int iCol; int eState = 0; if( pCsr->zStop ){ int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm; int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n); if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){ pCsr->isEof = 1; return SQLITE_OK; } } if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM; memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat); iCol = 0; while( i<nDoclist ){ sqlite3_int64 v = 0; i += sqlite3Fts3GetVarint(&aDoclist[i], &v); switch( eState ){ /* State 0. In this state the integer just read was a docid. */ case 0: pCsr->aStat[0].nDoc++; eState = 1; iCol = 0; break; /* State 1. In this state we are expecting either a 1, indicating ** that the following integer will be a column number, or the ** start of a position list for column 0. ** ** The only difference between state 1 and state 2 is that if the ** integer encountered in state 1 is not 0 or 1, then we need to ** increment the column 0 "nDoc" count for this term. */ case 1: assert( iCol==0 ); if( v>1 ){ pCsr->aStat[1].nDoc++; } eState = 2; /* fall through */ case 2: if( v==0 ){ /* 0x00. Next integer will be a docid. */ eState = 0; }else if( v==1 ){ /* 0x01. Next integer will be a column number. */ eState = 3; }else{ /* 2 or greater. A position. */ pCsr->aStat[iCol+1].nOcc++; pCsr->aStat[0].nOcc++; } break; /* State 3. The integer just read is a column number. */ default: assert( eState==3 ); iCol = (int)v; if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM; pCsr->aStat[iCol+1].nDoc++; eState = 2; break; } } pCsr->iCol = 0; rc = SQLITE_OK; }else{ pCsr->isEof = 1; } return rc; } /* ** xFilter - Initialize a cursor to point at the start of its data. */ static int fts3auxFilterMethod( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ sqlite3_value **apVal /* Arguments for the indexing scheme */ ){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; int rc; int isScan = 0; int iLangVal = 0; /* Language id to query */ int iEq = -1; /* Index of term=? value in apVal */ int iGe = -1; /* Index of term>=? value in apVal */ int iLe = -1; /* Index of term<=? value in apVal */ int iLangid = -1; /* Index of languageid=? value in apVal */ int iNext = 0; UNUSED_PARAMETER(nVal); UNUSED_PARAMETER(idxStr); assert( idxStr==0 ); assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ); if( idxNum==FTS4AUX_EQ_CONSTRAINT ){ iEq = iNext++; }else{ isScan = 1; if( idxNum & FTS4AUX_GE_CONSTRAINT ){ iGe = iNext++; } if( idxNum & FTS4AUX_LE_CONSTRAINT ){ iLe = iNext++; } } if( iNext<nVal ){ iLangid = iNext++; } /* In case this cursor is being reused, close and zero it. */ testcase(pCsr->filter.zTerm); sqlite3Fts3SegReaderFinish(&pCsr->csr); sqlite3_free((void *)pCsr->filter.zTerm); sqlite3_free(pCsr->aStat); memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr); pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN; if( iEq>=0 || iGe>=0 ){ const unsigned char *zStr = sqlite3_value_text(apVal[0]); assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) ); if( zStr ){ pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr); pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]); if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM; } } if( iLe>=0 ){ pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe])); pCsr->nStop = sqlite3_value_bytes(apVal[iLe]); if( pCsr->zStop==0 ) return SQLITE_NOMEM; } if( iLangid>=0 ){ iLangVal = sqlite3_value_int(apVal[iLangid]); /* If the user specified a negative value for the languageid, use zero ** instead. This works, as the "languageid=?" constraint will also ** be tested by the VDBE layer. The test will always be false (since ** this module will not return a row with a negative languageid), and ** so the overall query will return zero rows. */ if( iLangVal<0 ) iLangVal = 0; } pCsr->iLangid = iLangVal; rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL, pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr ); if( rc==SQLITE_OK ){ rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter); } if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor); return rc; } /* ** xEof - Return true if the cursor is at EOF, or false otherwise. */ static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; return pCsr->isEof; } /* ** xColumn - Return a column value. */ static int fts3auxColumnMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts3auxCursor *p = (Fts3auxCursor *)pCursor; assert( p->isEof==0 ); switch( iCol ){ case 0: /* term */ sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT); break; case 1: /* col */ if( p->iCol ){ sqlite3_result_int(pCtx, p->iCol-1); }else{ sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC); } break; case 2: /* documents */ sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc); break; case 3: /* occurrences */ sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc); break; default: /* languageid */ assert( iCol==4 ); sqlite3_result_int(pCtx, p->iLangid); break; } return SQLITE_OK; } /* ** xRowid - Return the current rowid for the cursor. */ static int fts3auxRowidMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite_int64 *pRowid /* OUT: Rowid value */ ){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; *pRowid = pCsr->iRowid; return SQLITE_OK; } /* ** Register the fts3aux module with database connection db. Return SQLITE_OK ** if successful or an error code if sqlite3_create_module() fails. */ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){ static const sqlite3_module fts3aux_module = { 0, /* iVersion */ fts3auxConnectMethod, /* xCreate */ fts3auxConnectMethod, /* xConnect */ fts3auxBestIndexMethod, /* xBestIndex */ fts3auxDisconnectMethod, /* xDisconnect */ fts3auxDisconnectMethod, /* xDestroy */ fts3auxOpenMethod, /* xOpen */ fts3auxCloseMethod, /* xClose */ fts3auxFilterMethod, /* xFilter */ fts3auxNextMethod, /* xNext */ fts3auxEofMethod, /* xEof */ fts3auxColumnMethod, /* xColumn */ fts3auxRowidMethod, /* xRowid */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindFunction */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; int rc; /* Return code */ rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0); return rc; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_aux.c ********************************************/ /************** Begin file fts3_expr.c ***************************************/ /* ** 2008 Nov 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This module contains code that implements a parser for fts3 query strings ** (the right-hand argument to the MATCH operator). Because the supported ** syntax is relatively simple, the whole tokenizer/parser system is ** hand-coded. */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* ** By default, this module parses the legacy syntax that has been ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS ** is defined, then it uses the new syntax. The differences between ** the new and the old syntaxes are: ** ** a) The new syntax supports parenthesis. The old does not. ** ** b) The new syntax supports the AND and NOT operators. The old does not. ** ** c) The old syntax supports the "-" token qualifier. This is not ** supported by the new syntax (it is replaced by the NOT operator). ** ** d) When using the old syntax, the OR operator has a greater precedence ** than an implicit AND. When using the new, both implicity and explicit ** AND operators have a higher precedence than OR. ** ** If compiled with SQLITE_TEST defined, then this module exports the ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable ** to zero causes the module to use the old syntax. If it is set to ** non-zero the new syntax is activated. This is so both syntaxes can ** be tested using a single build of testfixture. ** ** The following describes the syntax supported by the fts3 MATCH ** operator in a similar format to that used by the lemon parser ** generator. This module does not use actually lemon, it uses a ** custom parser. ** ** query ::= andexpr (OR andexpr)*. ** ** andexpr ::= notexpr (AND? notexpr)*. ** ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*. ** notexpr ::= LP query RP. ** ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*. ** ** distance_opt ::= . ** distance_opt ::= / INTEGER. ** ** phrase ::= TOKEN. ** phrase ::= COLUMN:TOKEN. ** phrase ::= "TOKEN TOKEN TOKEN...". */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_fts3_enable_parentheses = 0; #else # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS # define sqlite3_fts3_enable_parentheses 1 # else # define sqlite3_fts3_enable_parentheses 0 # endif #endif /* ** Default span for NEAR operators. */ #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10 /* #include <string.h> */ /* #include <assert.h> */ /* ** isNot: ** This variable is used by function getNextNode(). When getNextNode() is ** called, it sets ParseContext.isNot to true if the 'next node' is a ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to ** zero. */ typedef struct ParseContext ParseContext; struct ParseContext { sqlite3_tokenizer *pTokenizer; /* Tokenizer module */ int iLangid; /* Language id used with tokenizer */ const char **azCol; /* Array of column names for fts3 table */ int bFts4; /* True to allow FTS4-only syntax */ int nCol; /* Number of entries in azCol[] */ int iDefaultCol; /* Default column to query */ int isNot; /* True if getNextNode() sees a unary - */ sqlite3_context *pCtx; /* Write error message here */ int nNest; /* Number of nested brackets */ }; /* ** This function is equivalent to the standard isspace() function. ** ** The standard isspace() can be awkward to use safely, because although it ** is defined to accept an argument of type int, its behavior when passed ** an integer that falls outside of the range of the unsigned char type ** is undefined (and sometimes, "undefined" means segfault). This wrapper ** is defined to accept an argument of type char, and always returns 0 for ** any values that fall outside of the range of the unsigned char type (i.e. ** negative values). */ static int fts3isspace(char c){ return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; } /* ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful, ** zero the memory before returning a pointer to it. If unsuccessful, ** return NULL. */ static void *fts3MallocZero(int nByte){ void *pRet = sqlite3_malloc(nByte); if( pRet ) memset(pRet, 0, nByte); return pRet; } SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer( sqlite3_tokenizer *pTokenizer, int iLangid, const char *z, int n, sqlite3_tokenizer_cursor **ppCsr ){ sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; sqlite3_tokenizer_cursor *pCsr = 0; int rc; rc = pModule->xOpen(pTokenizer, z, n, &pCsr); assert( rc==SQLITE_OK || pCsr==0 ); if( rc==SQLITE_OK ){ pCsr->pTokenizer = pTokenizer; if( pModule->iVersion>=1 ){ rc = pModule->xLanguageid(pCsr, iLangid); if( rc!=SQLITE_OK ){ pModule->xClose(pCsr); pCsr = 0; } } } *ppCsr = pCsr; return rc; } /* ** Function getNextNode(), which is called by fts3ExprParse(), may itself ** call fts3ExprParse(). So this forward declaration is required. */ static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); /* ** Extract the next token from buffer z (length n) using the tokenizer ** and other information (column names etc.) in pParse. Create an Fts3Expr ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this ** single token and set *ppExpr to point to it. If the end of the buffer is ** reached before a token is found, set *ppExpr to zero. It is the ** responsibility of the caller to eventually deallocate the allocated ** Fts3Expr structure (if any) by passing it to sqlite3_free(). ** ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation ** fails. */ static int getNextToken( ParseContext *pParse, /* fts3 query parse context */ int iCol, /* Value for Fts3Phrase.iColumn */ const char *z, int n, /* Input string */ Fts3Expr **ppExpr, /* OUT: expression */ int *pnConsumed /* OUT: Number of bytes consumed */ ){ sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; int rc; sqlite3_tokenizer_cursor *pCursor; Fts3Expr *pRet = 0; int i = 0; /* Set variable i to the maximum number of bytes of input to tokenize. */ for(i=0; i<n; i++){ if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break; if( z[i]=='"' ) break; } *pnConsumed = i; rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor); if( rc==SQLITE_OK ){ const char *zToken; int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0; int nByte; /* total space to allocate */ rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition); if( rc==SQLITE_OK ){ nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken; pRet = (Fts3Expr *)fts3MallocZero(nByte); if( !pRet ){ rc = SQLITE_NOMEM; }else{ pRet->eType = FTSQUERY_PHRASE; pRet->pPhrase = (Fts3Phrase *)&pRet[1]; pRet->pPhrase->nToken = 1; pRet->pPhrase->iColumn = iCol; pRet->pPhrase->aToken[0].n = nToken; pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1]; memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken); if( iEnd<n && z[iEnd]=='*' ){ pRet->pPhrase->aToken[0].isPrefix = 1; iEnd++; } while( 1 ){ if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){ pParse->isNot = 1; iStart--; }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){ pRet->pPhrase->aToken[0].bFirst = 1; iStart--; }else{ break; } } } *pnConsumed = iEnd; }else if( i && rc==SQLITE_DONE ){ rc = SQLITE_OK; } pModule->xClose(pCursor); } *ppExpr = pRet; return rc; } /* ** Enlarge a memory allocation. If an out-of-memory allocation occurs, ** then free the old allocation. */ static void *fts3ReallocOrFree(void *pOrig, int nNew){ void *pRet = sqlite3_realloc(pOrig, nNew); if( !pRet ){ sqlite3_free(pOrig); } return pRet; } /* ** Buffer zInput, length nInput, contains the contents of a quoted string ** that appeared as part of an fts3 query expression. Neither quote character ** is included in the buffer. This function attempts to tokenize the entire ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE ** containing the results. ** ** If successful, SQLITE_OK is returned and *ppExpr set to point at the ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set ** to 0. */ static int getNextString( ParseContext *pParse, /* fts3 query parse context */ const char *zInput, int nInput, /* Input string */ Fts3Expr **ppExpr /* OUT: expression */ ){ sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; int rc; Fts3Expr *p = 0; sqlite3_tokenizer_cursor *pCursor = 0; char *zTemp = 0; int nTemp = 0; const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase); int nToken = 0; /* The final Fts3Expr data structure, including the Fts3Phrase, ** Fts3PhraseToken structures token buffers are all stored as a single ** allocation so that the expression can be freed with a single call to ** sqlite3_free(). Setting this up requires a two pass approach. ** ** The first pass, in the block below, uses a tokenizer cursor to iterate ** through the tokens in the expression. This pass uses fts3ReallocOrFree() ** to assemble data in two dynamic buffers: ** ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase ** structure, followed by the array of Fts3PhraseToken ** structures. This pass only populates the Fts3PhraseToken array. ** ** Buffer zTemp: Contains copies of all tokens. ** ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below, ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase ** structures. */ rc = sqlite3Fts3OpenTokenizer( pTokenizer, pParse->iLangid, zInput, nInput, &pCursor); if( rc==SQLITE_OK ){ int ii; for(ii=0; rc==SQLITE_OK; ii++){ const char *zByte; int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0; rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos); if( rc==SQLITE_OK ){ Fts3PhraseToken *pToken; p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken)); if( !p ) goto no_mem; zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte); if( !zTemp ) goto no_mem; assert( nToken==ii ); pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii]; memset(pToken, 0, sizeof(Fts3PhraseToken)); memcpy(&zTemp[nTemp], zByte, nByte); nTemp += nByte; pToken->n = nByte; pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*'); pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^'); nToken = ii+1; } } pModule->xClose(pCursor); pCursor = 0; } if( rc==SQLITE_DONE ){ int jj; char *zBuf = 0; p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp); if( !p ) goto no_mem; memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p); p->eType = FTSQUERY_PHRASE; p->pPhrase = (Fts3Phrase *)&p[1]; p->pPhrase->iColumn = pParse->iDefaultCol; p->pPhrase->nToken = nToken; zBuf = (char *)&p->pPhrase->aToken[nToken]; if( zTemp ){ memcpy(zBuf, zTemp, nTemp); sqlite3_free(zTemp); }else{ assert( nTemp==0 ); } for(jj=0; jj<p->pPhrase->nToken; jj++){ p->pPhrase->aToken[jj].z = zBuf; zBuf += p->pPhrase->aToken[jj].n; } rc = SQLITE_OK; } *ppExpr = p; return rc; no_mem: if( pCursor ){ pModule->xClose(pCursor); } sqlite3_free(zTemp); sqlite3_free(p); *ppExpr = 0; return SQLITE_NOMEM; } /* ** The output variable *ppExpr is populated with an allocated Fts3Expr ** structure, or set to 0 if the end of the input buffer is reached. ** ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered. ** If SQLITE_ERROR is returned, pContext is populated with an error message. */ static int getNextNode( ParseContext *pParse, /* fts3 query parse context */ const char *z, int n, /* Input string */ Fts3Expr **ppExpr, /* OUT: expression */ int *pnConsumed /* OUT: Number of bytes consumed */ ){ static const struct Fts3Keyword { char *z; /* Keyword text */ unsigned char n; /* Length of the keyword */ unsigned char parenOnly; /* Only valid in paren mode */ unsigned char eType; /* Keyword code */ } aKeyword[] = { { "OR" , 2, 0, FTSQUERY_OR }, { "AND", 3, 1, FTSQUERY_AND }, { "NOT", 3, 1, FTSQUERY_NOT }, { "NEAR", 4, 0, FTSQUERY_NEAR } }; int ii; int iCol; int iColLen; int rc; Fts3Expr *pRet = 0; const char *zInput = z; int nInput = n; pParse->isNot = 0; /* Skip over any whitespace before checking for a keyword, an open or ** close bracket, or a quoted string. */ while( nInput>0 && fts3isspace(*zInput) ){ nInput--; zInput++; } if( nInput==0 ){ return SQLITE_DONE; } /* See if we are dealing with a keyword. */ for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){ const struct Fts3Keyword *pKey = &aKeyword[ii]; if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){ continue; } if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){ int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM; int nKey = pKey->n; char cNext; /* If this is a "NEAR" keyword, check for an explicit nearness. */ if( pKey->eType==FTSQUERY_NEAR ){ assert( nKey==4 ); if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){ nNear = 0; for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){ nNear = nNear * 10 + (zInput[nKey] - '0'); } } } /* At this point this is probably a keyword. But for that to be true, ** the next byte must contain either whitespace, an open or close ** parenthesis, a quote character, or EOF. */ cNext = zInput[nKey]; if( fts3isspace(cNext) || cNext=='"' || cNext=='(' || cNext==')' || cNext==0 ){ pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr)); if( !pRet ){ return SQLITE_NOMEM; } pRet->eType = pKey->eType; pRet->nNear = nNear; *ppExpr = pRet; *pnConsumed = (int)((zInput - z) + nKey); return SQLITE_OK; } /* Turns out that wasn't a keyword after all. This happens if the ** user has supplied a token such as "ORacle". Continue. */ } } /* See if we are dealing with a quoted phrase. If this is the case, then ** search for the closing quote and pass the whole string to getNextString() ** for processing. This is easy to do, as fts3 has no syntax for escaping ** a quote character embedded in a string. */ if( *zInput=='"' ){ for(ii=1; ii<nInput && zInput[ii]!='"'; ii++); *pnConsumed = (int)((zInput - z) + ii + 1); if( ii==nInput ){ return SQLITE_ERROR; } return getNextString(pParse, &zInput[1], ii-1, ppExpr); } if( sqlite3_fts3_enable_parentheses ){ if( *zInput=='(' ){ int nConsumed = 0; pParse->nNest++; rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed); if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; } *pnConsumed = (int)(zInput - z) + 1 + nConsumed; return rc; }else if( *zInput==')' ){ pParse->nNest--; *pnConsumed = (int)((zInput - z) + 1); *ppExpr = 0; return SQLITE_DONE; } } /* If control flows to this point, this must be a regular token, or ** the end of the input. Read a regular token using the sqlite3_tokenizer ** interface. Before doing so, figure out if there is an explicit ** column specifier for the token. ** ** TODO: Strangely, it is not possible to associate a column specifier ** with a quoted phrase, only with a single token. Not sure if this was ** an implementation artifact or an intentional decision when fts3 was ** first implemented. Whichever it was, this module duplicates the ** limitation. */ iCol = pParse->iDefaultCol; iColLen = 0; for(ii=0; ii<pParse->nCol; ii++){ const char *zStr = pParse->azCol[ii]; int nStr = (int)strlen(zStr); if( nInput>nStr && zInput[nStr]==':' && sqlite3_strnicmp(zStr, zInput, nStr)==0 ){ iCol = ii; iColLen = (int)((zInput - z) + nStr + 1); break; } } rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed); *pnConsumed += iColLen; return rc; } /* ** The argument is an Fts3Expr structure for a binary operator (any type ** except an FTSQUERY_PHRASE). Return an integer value representing the ** precedence of the operator. Lower values have a higher precedence (i.e. ** group more tightly). For example, in the C language, the == operator ** groups more tightly than ||, and would therefore have a higher precedence. ** ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS ** is defined), the order of the operators in precedence from highest to ** lowest is: ** ** NEAR ** NOT ** AND (including implicit ANDs) ** OR ** ** Note that when using the old query syntax, the OR operator has a higher ** precedence than the AND operator. */ static int opPrecedence(Fts3Expr *p){ assert( p->eType!=FTSQUERY_PHRASE ); if( sqlite3_fts3_enable_parentheses ){ return p->eType; }else if( p->eType==FTSQUERY_NEAR ){ return 1; }else if( p->eType==FTSQUERY_OR ){ return 2; } assert( p->eType==FTSQUERY_AND ); return 3; } /* ** Argument ppHead contains a pointer to the current head of a query ** expression tree being parsed. pPrev is the expression node most recently ** inserted into the tree. This function adds pNew, which is always a binary ** operator node, into the expression tree based on the relative precedence ** of pNew and the existing nodes of the tree. This may result in the head ** of the tree changing, in which case *ppHead is set to the new root node. */ static void insertBinaryOperator( Fts3Expr **ppHead, /* Pointer to the root node of a tree */ Fts3Expr *pPrev, /* Node most recently inserted into the tree */ Fts3Expr *pNew /* New binary node to insert into expression tree */ ){ Fts3Expr *pSplit = pPrev; while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){ pSplit = pSplit->pParent; } if( pSplit->pParent ){ assert( pSplit->pParent->pRight==pSplit ); pSplit->pParent->pRight = pNew; pNew->pParent = pSplit->pParent; }else{ *ppHead = pNew; } pNew->pLeft = pSplit; pSplit->pParent = pNew; } /* ** Parse the fts3 query expression found in buffer z, length n. This function ** returns either when the end of the buffer is reached or an unmatched ** closing bracket - ')' - is encountered. ** ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the ** parsed form of the expression and *pnConsumed is set to the number of ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM ** (out of memory error) or SQLITE_ERROR (parse error) is returned. */ static int fts3ExprParse( ParseContext *pParse, /* fts3 query parse context */ const char *z, int n, /* Text of MATCH query */ Fts3Expr **ppExpr, /* OUT: Parsed query structure */ int *pnConsumed /* OUT: Number of bytes consumed */ ){ Fts3Expr *pRet = 0; Fts3Expr *pPrev = 0; Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */ int nIn = n; const char *zIn = z; int rc = SQLITE_OK; int isRequirePhrase = 1; while( rc==SQLITE_OK ){ Fts3Expr *p = 0; int nByte = 0; rc = getNextNode(pParse, zIn, nIn, &p, &nByte); assert( nByte>0 || (rc!=SQLITE_OK && p==0) ); if( rc==SQLITE_OK ){ if( p ){ int isPhrase; if( !sqlite3_fts3_enable_parentheses && p->eType==FTSQUERY_PHRASE && pParse->isNot ){ /* Create an implicit NOT operator. */ Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr)); if( !pNot ){ sqlite3Fts3ExprFree(p); rc = SQLITE_NOMEM; goto exprparse_out; } pNot->eType = FTSQUERY_NOT; pNot->pRight = p; p->pParent = pNot; if( pNotBranch ){ pNot->pLeft = pNotBranch; pNotBranch->pParent = pNot; } pNotBranch = pNot; p = pPrev; }else{ int eType = p->eType; isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft); /* The isRequirePhrase variable is set to true if a phrase or ** an expression contained in parenthesis is required. If a ** binary operator (AND, OR, NOT or NEAR) is encounted when ** isRequirePhrase is set, this is a syntax error. */ if( !isPhrase && isRequirePhrase ){ sqlite3Fts3ExprFree(p); rc = SQLITE_ERROR; goto exprparse_out; } if( isPhrase && !isRequirePhrase ){ /* Insert an implicit AND operator. */ Fts3Expr *pAnd; assert( pRet && pPrev ); pAnd = fts3MallocZero(sizeof(Fts3Expr)); if( !pAnd ){ sqlite3Fts3ExprFree(p); rc = SQLITE_NOMEM; goto exprparse_out; } pAnd->eType = FTSQUERY_AND; insertBinaryOperator(&pRet, pPrev, pAnd); pPrev = pAnd; } /* This test catches attempts to make either operand of a NEAR ** operator something other than a phrase. For example, either of ** the following: ** ** (bracketed expression) NEAR phrase ** phrase NEAR (bracketed expression) ** ** Return an error in either case. */ if( pPrev && ( (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE) || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR) )){ sqlite3Fts3ExprFree(p); rc = SQLITE_ERROR; goto exprparse_out; } if( isPhrase ){ if( pRet ){ assert( pPrev && pPrev->pLeft && pPrev->pRight==0 ); pPrev->pRight = p; p->pParent = pPrev; }else{ pRet = p; } }else{ insertBinaryOperator(&pRet, pPrev, p); } isRequirePhrase = !isPhrase; } pPrev = p; } assert( nByte>0 ); } assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) ); nIn -= nByte; zIn += nByte; } if( rc==SQLITE_DONE && pRet && isRequirePhrase ){ rc = SQLITE_ERROR; } if( rc==SQLITE_DONE ){ rc = SQLITE_OK; if( !sqlite3_fts3_enable_parentheses && pNotBranch ){ if( !pRet ){ rc = SQLITE_ERROR; }else{ Fts3Expr *pIter = pNotBranch; while( pIter->pLeft ){ pIter = pIter->pLeft; } pIter->pLeft = pRet; pRet->pParent = pIter; pRet = pNotBranch; } } } *pnConsumed = n - nIn; exprparse_out: if( rc!=SQLITE_OK ){ sqlite3Fts3ExprFree(pRet); sqlite3Fts3ExprFree(pNotBranch); pRet = 0; } *ppExpr = pRet; return rc; } /* ** Return SQLITE_ERROR if the maximum depth of the expression tree passed ** as the only argument is more than nMaxDepth. */ static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){ int rc = SQLITE_OK; if( p ){ if( nMaxDepth<0 ){ rc = SQLITE_TOOBIG; }else{ rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1); if( rc==SQLITE_OK ){ rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1); } } } return rc; } /* ** This function attempts to transform the expression tree at (*pp) to ** an equivalent but more balanced form. The tree is modified in place. ** If successful, SQLITE_OK is returned and (*pp) set to point to the ** new root expression node. ** ** nMaxDepth is the maximum allowable depth of the balanced sub-tree. ** ** Otherwise, if an error occurs, an SQLite error code is returned and ** expression (*pp) freed. */ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ int rc = SQLITE_OK; /* Return code */ Fts3Expr *pRoot = *pp; /* Initial root node */ Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */ int eType = pRoot->eType; /* Type of node in this tree */ if( nMaxDepth==0 ){ rc = SQLITE_ERROR; } if( rc==SQLITE_OK ){ if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){ Fts3Expr **apLeaf; apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth); if( 0==apLeaf ){ rc = SQLITE_NOMEM; }else{ memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth); } if( rc==SQLITE_OK ){ int i; Fts3Expr *p; /* Set $p to point to the left-most leaf in the tree of eType nodes. */ for(p=pRoot; p->eType==eType; p=p->pLeft){ assert( p->pParent==0 || p->pParent->pLeft==p ); assert( p->pLeft && p->pRight ); } /* This loop runs once for each leaf in the tree of eType nodes. */ while( 1 ){ int iLvl; Fts3Expr *pParent = p->pParent; /* Current parent of p */ assert( pParent==0 || pParent->pLeft==p ); p->pParent = 0; if( pParent ){ pParent->pLeft = 0; }else{ pRoot = 0; } rc = fts3ExprBalance(&p, nMaxDepth-1); if( rc!=SQLITE_OK ) break; for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){ if( apLeaf[iLvl]==0 ){ apLeaf[iLvl] = p; p = 0; }else{ assert( pFree ); pFree->pLeft = apLeaf[iLvl]; pFree->pRight = p; pFree->pLeft->pParent = pFree; pFree->pRight->pParent = pFree; p = pFree; pFree = pFree->pParent; p->pParent = 0; apLeaf[iLvl] = 0; } } if( p ){ sqlite3Fts3ExprFree(p); rc = SQLITE_TOOBIG; break; } /* If that was the last leaf node, break out of the loop */ if( pParent==0 ) break; /* Set $p to point to the next leaf in the tree of eType nodes */ for(p=pParent->pRight; p->eType==eType; p=p->pLeft); /* Remove pParent from the original tree. */ assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent ); pParent->pRight->pParent = pParent->pParent; if( pParent->pParent ){ pParent->pParent->pLeft = pParent->pRight; }else{ assert( pParent==pRoot ); pRoot = pParent->pRight; } /* Link pParent into the free node list. It will be used as an ** internal node of the new tree. */ pParent->pParent = pFree; pFree = pParent; } if( rc==SQLITE_OK ){ p = 0; for(i=0; i<nMaxDepth; i++){ if( apLeaf[i] ){ if( p==0 ){ p = apLeaf[i]; p->pParent = 0; }else{ assert( pFree!=0 ); pFree->pRight = p; pFree->pLeft = apLeaf[i]; pFree->pLeft->pParent = pFree; pFree->pRight->pParent = pFree; p = pFree; pFree = pFree->pParent; p->pParent = 0; } } } pRoot = p; }else{ /* An error occurred. Delete the contents of the apLeaf[] array ** and pFree list. Everything else is cleaned up by the call to ** sqlite3Fts3ExprFree(pRoot) below. */ Fts3Expr *pDel; for(i=0; i<nMaxDepth; i++){ sqlite3Fts3ExprFree(apLeaf[i]); } while( (pDel=pFree)!=0 ){ pFree = pDel->pParent; sqlite3_free(pDel); } } assert( pFree==0 ); sqlite3_free( apLeaf ); } }else if( eType==FTSQUERY_NOT ){ Fts3Expr *pLeft = pRoot->pLeft; Fts3Expr *pRight = pRoot->pRight; pRoot->pLeft = 0; pRoot->pRight = 0; pLeft->pParent = 0; pRight->pParent = 0; rc = fts3ExprBalance(&pLeft, nMaxDepth-1); if( rc==SQLITE_OK ){ rc = fts3ExprBalance(&pRight, nMaxDepth-1); } if( rc!=SQLITE_OK ){ sqlite3Fts3ExprFree(pRight); sqlite3Fts3ExprFree(pLeft); }else{ assert( pLeft && pRight ); pRoot->pLeft = pLeft; pLeft->pParent = pRoot; pRoot->pRight = pRight; pRight->pParent = pRoot; } } } if( rc!=SQLITE_OK ){ sqlite3Fts3ExprFree(pRoot); pRoot = 0; } *pp = pRoot; return rc; } /* ** This function is similar to sqlite3Fts3ExprParse(), with the following ** differences: ** ** 1. It does not do expression rebalancing. ** 2. It does not check that the expression does not exceed the ** maximum allowable depth. ** 3. Even if it fails, *ppExpr may still be set to point to an ** expression tree. It should be deleted using sqlite3Fts3ExprFree() ** in this case. */ static int fts3ExprParseUnbalanced( sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ int iLangid, /* Language id for tokenizer */ char **azCol, /* Array of column names for fts3 table */ int bFts4, /* True to allow FTS4-only syntax */ int nCol, /* Number of entries in azCol[] */ int iDefaultCol, /* Default column to query */ const char *z, int n, /* Text of MATCH query */ Fts3Expr **ppExpr /* OUT: Parsed query structure */ ){ int nParsed; int rc; ParseContext sParse; memset(&sParse, 0, sizeof(ParseContext)); sParse.pTokenizer = pTokenizer; sParse.iLangid = iLangid; sParse.azCol = (const char **)azCol; sParse.nCol = nCol; sParse.iDefaultCol = iDefaultCol; sParse.bFts4 = bFts4; if( z==0 ){ *ppExpr = 0; return SQLITE_OK; } if( n<0 ){ n = (int)strlen(z); } rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed); assert( rc==SQLITE_OK || *ppExpr==0 ); /* Check for mismatched parenthesis */ if( rc==SQLITE_OK && sParse.nNest ){ rc = SQLITE_ERROR; } return rc; } /* ** Parameters z and n contain a pointer to and length of a buffer containing ** an fts3 query expression, respectively. This function attempts to parse the ** query expression and create a tree of Fts3Expr structures representing the ** parsed expression. If successful, *ppExpr is set to point to the head ** of the parsed expression tree and SQLITE_OK is returned. If an error ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse ** error) is returned and *ppExpr is set to 0. ** ** If parameter n is a negative number, then z is assumed to point to a ** nul-terminated string and the length is determined using strlen(). ** ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to ** use to normalize query tokens while parsing the expression. The azCol[] ** array, which is assumed to contain nCol entries, should contain the names ** of each column in the target fts3 table, in order from left to right. ** Column names must be nul-terminated strings. ** ** The iDefaultCol parameter should be passed the index of the table column ** that appears on the left-hand-side of the MATCH operator (the default ** column to match against for tokens for which a column name is not explicitly ** specified as part of the query string), or -1 if tokens may by default ** match any table column. */ SQLITE_PRIVATE int sqlite3Fts3ExprParse( sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ int iLangid, /* Language id for tokenizer */ char **azCol, /* Array of column names for fts3 table */ int bFts4, /* True to allow FTS4-only syntax */ int nCol, /* Number of entries in azCol[] */ int iDefaultCol, /* Default column to query */ const char *z, int n, /* Text of MATCH query */ Fts3Expr **ppExpr, /* OUT: Parsed query structure */ char **pzErr /* OUT: Error message (sqlite3_malloc) */ ){ int rc = fts3ExprParseUnbalanced( pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr ); /* Rebalance the expression. And check that its depth does not exceed ** SQLITE_FTS3_MAX_EXPR_DEPTH. */ if( rc==SQLITE_OK && *ppExpr ){ rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); if( rc==SQLITE_OK ){ rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); } } if( rc!=SQLITE_OK ){ sqlite3Fts3ExprFree(*ppExpr); *ppExpr = 0; if( rc==SQLITE_TOOBIG ){ sqlite3Fts3ErrMsg(pzErr, "FTS expression tree is too large (maximum depth %d)", SQLITE_FTS3_MAX_EXPR_DEPTH ); rc = SQLITE_ERROR; }else if( rc==SQLITE_ERROR ){ sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z); } } return rc; } /* ** Free a single node of an expression tree. */ static void fts3FreeExprNode(Fts3Expr *p){ assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 ); sqlite3Fts3EvalPhraseCleanup(p->pPhrase); sqlite3_free(p->aMI); sqlite3_free(p); } /* ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse(). ** ** This function would be simpler if it recursively called itself. But ** that would mean passing a sufficiently large expression to ExprParse() ** could cause a stack overflow. */ SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){ Fts3Expr *p; assert( pDel==0 || pDel->pParent==0 ); for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){ assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft ); } while( p ){ Fts3Expr *pParent = p->pParent; fts3FreeExprNode(p); if( pParent && p==pParent->pLeft && pParent->pRight ){ p = pParent->pRight; while( p && (p->pLeft || p->pRight) ){ assert( p==p->pParent->pRight || p==p->pParent->pLeft ); p = (p->pLeft ? p->pLeft : p->pRight); } }else{ p = pParent; } } } /**************************************************************************** ***************************************************************************** ** Everything after this point is just test code. */ #ifdef SQLITE_TEST /* #include <stdio.h> */ /* ** Function to query the hash-table of tokenizers (see README.tokenizers). */ static int queryTestTokenizer( sqlite3 *db, const char *zName, const sqlite3_tokenizer_module **pp ){ int rc; sqlite3_stmt *pStmt; const char zSql[] = "SELECT fts3_tokenizer(?)"; *pp = 0; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ return rc; } sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); if( SQLITE_ROW==sqlite3_step(pStmt) ){ if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); } } return sqlite3_finalize(pStmt); } /* ** Return a pointer to a buffer containing a text representation of the ** expression passed as the first argument. The buffer is obtained from ** sqlite3_malloc(). It is the responsibility of the caller to use ** sqlite3_free() to release the memory. If an OOM condition is encountered, ** NULL is returned. ** ** If the second argument is not NULL, then its contents are prepended to ** the returned expression text and then freed using sqlite3_free(). */ static char *exprToString(Fts3Expr *pExpr, char *zBuf){ if( pExpr==0 ){ return sqlite3_mprintf(""); } switch( pExpr->eType ){ case FTSQUERY_PHRASE: { Fts3Phrase *pPhrase = pExpr->pPhrase; int i; zBuf = sqlite3_mprintf( "%zPHRASE %d 0", zBuf, pPhrase->iColumn); for(i=0; zBuf && i<pPhrase->nToken; i++){ zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, pPhrase->aToken[i].n, pPhrase->aToken[i].z, (pPhrase->aToken[i].isPrefix?"+":"") ); } return zBuf; } case FTSQUERY_NEAR: zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear); break; case FTSQUERY_NOT: zBuf = sqlite3_mprintf("%zNOT ", zBuf); break; case FTSQUERY_AND: zBuf = sqlite3_mprintf("%zAND ", zBuf); break; case FTSQUERY_OR: zBuf = sqlite3_mprintf("%zOR ", zBuf); break; } if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf); if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf); if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf); if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf); if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf); return zBuf; } /* ** This is the implementation of a scalar SQL function used to test the ** expression parser. It should be called as follows: ** ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...); ** ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used ** to parse the query expression (see README.tokenizers). The second argument ** is the query expression to parse. Each subsequent argument is the name ** of a column of the fts3 table that the query expression may refer to. ** For example: ** ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2'); */ static void fts3ExprTest( sqlite3_context *context, int argc, sqlite3_value **argv ){ sqlite3_tokenizer_module const *pModule = 0; sqlite3_tokenizer *pTokenizer = 0; int rc; char **azCol = 0; const char *zExpr; int nExpr; int nCol; int ii; Fts3Expr *pExpr; char *zBuf = 0; sqlite3 *db = sqlite3_context_db_handle(context); if( argc<3 ){ sqlite3_result_error(context, "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1 ); return; } rc = queryTestTokenizer(db, (const char *)sqlite3_value_text(argv[0]), &pModule); if( rc==SQLITE_NOMEM ){ sqlite3_result_error_nomem(context); goto exprtest_out; }else if( !pModule ){ sqlite3_result_error(context, "No such tokenizer module", -1); goto exprtest_out; } rc = pModule->xCreate(0, 0, &pTokenizer); assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); if( rc==SQLITE_NOMEM ){ sqlite3_result_error_nomem(context); goto exprtest_out; } pTokenizer->pModule = pModule; zExpr = (const char *)sqlite3_value_text(argv[1]); nExpr = sqlite3_value_bytes(argv[1]); nCol = argc-2; azCol = (char **)sqlite3_malloc(nCol*sizeof(char *)); if( !azCol ){ sqlite3_result_error_nomem(context); goto exprtest_out; } for(ii=0; ii<nCol; ii++){ azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]); } if( sqlite3_user_data(context) ){ char *zDummy = 0; rc = sqlite3Fts3ExprParse( pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy ); assert( rc==SQLITE_OK || pExpr==0 ); sqlite3_free(zDummy); }else{ rc = fts3ExprParseUnbalanced( pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr ); } if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){ sqlite3Fts3ExprFree(pExpr); sqlite3_result_error(context, "Error parsing expression", -1); }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){ sqlite3_result_error_nomem(context); }else{ sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); sqlite3_free(zBuf); } sqlite3Fts3ExprFree(pExpr); exprtest_out: if( pModule && pTokenizer ){ rc = pModule->xDestroy(pTokenizer); } sqlite3_free(azCol); } /* ** Register the query expression parser test function fts3_exprtest() ** with database connection db. */ SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){ int rc = sqlite3_create_function( db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0 ); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0 ); } return rc; } #endif #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_expr.c *******************************************/ /************** Begin file fts3_hash.c ***************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of generic hash-tables used in SQLite. ** We've modified it slightly to serve as a standalone hash table ** implementation for the full-text indexing module. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <assert.h> */ /* #include <stdlib.h> */ /* #include <string.h> */ /* #include "fts3_hash.h" */ /* ** Malloc and Free functions */ static void *fts3HashMalloc(int n){ void *p = sqlite3_malloc(n); if( p ){ memset(p, 0, n); } return p; } static void fts3HashFree(void *p){ sqlite3_free(p); } /* Turn bulk memory into a hash table object by initializing the ** fields of the Hash structure. ** ** "pNew" is a pointer to the hash table that is to be initialized. ** keyClass is one of the constants ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass ** determines what kind of key the hash table will use. "copyKey" is ** true if the hash table should make its own private copy of keys and ** false if it should just use the supplied pointer. */ SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){ assert( pNew!=0 ); assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY ); pNew->keyClass = keyClass; pNew->copyKey = copyKey; pNew->first = 0; pNew->count = 0; pNew->htsize = 0; pNew->ht = 0; } /* Remove all entries from a hash table. Reclaim all memory. ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){ Fts3HashElem *elem; /* For looping over all elements of the table */ assert( pH!=0 ); elem = pH->first; pH->first = 0; fts3HashFree(pH->ht); pH->ht = 0; pH->htsize = 0; while( elem ){ Fts3HashElem *next_elem = elem->next; if( pH->copyKey && elem->pKey ){ fts3HashFree(elem->pKey); } fts3HashFree(elem); elem = next_elem; } pH->count = 0; } /* ** Hash and comparison functions when the mode is FTS3_HASH_STRING */ static int fts3StrHash(const void *pKey, int nKey){ const char *z = (const char *)pKey; unsigned h = 0; if( nKey<=0 ) nKey = (int) strlen(z); while( nKey > 0 ){ h = (h<<3) ^ h ^ *z++; nKey--; } return (int)(h & 0x7fffffff); } static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){ if( n1!=n2 ) return 1; return strncmp((const char*)pKey1,(const char*)pKey2,n1); } /* ** Hash and comparison functions when the mode is FTS3_HASH_BINARY */ static int fts3BinHash(const void *pKey, int nKey){ int h = 0; const char *z = (const char *)pKey; while( nKey-- > 0 ){ h = (h<<3) ^ h ^ *(z++); } return h & 0x7fffffff; } static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){ if( n1!=n2 ) return 1; return memcmp(pKey1,pKey2,n1); } /* ** Return a pointer to the appropriate hash function given the key class. ** ** The C syntax in this function definition may be unfamilar to some ** programmers, so we provide the following additional explanation: ** ** The name of the function is "ftsHashFunction". The function takes a ** single parameter "keyClass". The return value of ftsHashFunction() ** is a pointer to another function. Specifically, the return value ** of ftsHashFunction() is a pointer to a function that takes two parameters ** with types "const void*" and "int" and returns an "int". */ static int (*ftsHashFunction(int keyClass))(const void*,int){ if( keyClass==FTS3_HASH_STRING ){ return &fts3StrHash; }else{ assert( keyClass==FTS3_HASH_BINARY ); return &fts3BinHash; } } /* ** Return a pointer to the appropriate hash function given the key class. ** ** For help in interpreted the obscure C code in the function definition, ** see the header comment on the previous function. */ static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){ if( keyClass==FTS3_HASH_STRING ){ return &fts3StrCompare; }else{ assert( keyClass==FTS3_HASH_BINARY ); return &fts3BinCompare; } } /* Link an element into the hash table */ static void fts3HashInsertElement( Fts3Hash *pH, /* The complete hash table */ struct _fts3ht *pEntry, /* The entry into which pNew is inserted */ Fts3HashElem *pNew /* The element to be inserted */ ){ Fts3HashElem *pHead; /* First element already in pEntry */ pHead = pEntry->chain; if( pHead ){ pNew->next = pHead; pNew->prev = pHead->prev; if( pHead->prev ){ pHead->prev->next = pNew; } else { pH->first = pNew; } pHead->prev = pNew; }else{ pNew->next = pH->first; if( pH->first ){ pH->first->prev = pNew; } pNew->prev = 0; pH->first = pNew; } pEntry->count++; pEntry->chain = pNew; } /* Resize the hash table so that it cantains "new_size" buckets. ** "new_size" must be a power of 2. The hash table might fail ** to resize if sqliteMalloc() fails. ** ** Return non-zero if a memory allocation error occurs. */ static int fts3Rehash(Fts3Hash *pH, int new_size){ struct _fts3ht *new_ht; /* The new hash table */ Fts3HashElem *elem, *next_elem; /* For looping over existing elements */ int (*xHash)(const void*,int); /* The hash function */ assert( (new_size & (new_size-1))==0 ); new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) ); if( new_ht==0 ) return 1; fts3HashFree(pH->ht); pH->ht = new_ht; pH->htsize = new_size; xHash = ftsHashFunction(pH->keyClass); for(elem=pH->first, pH->first=0; elem; elem = next_elem){ int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); next_elem = elem->next; fts3HashInsertElement(pH, &new_ht[h], elem); } return 0; } /* This function (for internal use only) locates an element in an ** hash table that matches the given key. The hash for this key has ** already been computed and is passed as the 4th parameter. */ static Fts3HashElem *fts3FindElementByHash( const Fts3Hash *pH, /* The pH to be searched */ const void *pKey, /* The key we are searching for */ int nKey, int h /* The hash for this key. */ ){ Fts3HashElem *elem; /* Used to loop thru the element list */ int count; /* Number of elements left to test */ int (*xCompare)(const void*,int,const void*,int); /* comparison function */ if( pH->ht ){ struct _fts3ht *pEntry = &pH->ht[h]; elem = pEntry->chain; count = pEntry->count; xCompare = ftsCompareFunction(pH->keyClass); while( count-- && elem ){ if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ return elem; } elem = elem->next; } } return 0; } /* Remove a single entry from the hash table given a pointer to that ** element and a hash on the element's key. */ static void fts3RemoveElementByHash( Fts3Hash *pH, /* The pH containing "elem" */ Fts3HashElem* elem, /* The element to be removed from the pH */ int h /* Hash value for the element */ ){ struct _fts3ht *pEntry; if( elem->prev ){ elem->prev->next = elem->next; }else{ pH->first = elem->next; } if( elem->next ){ elem->next->prev = elem->prev; } pEntry = &pH->ht[h]; if( pEntry->chain==elem ){ pEntry->chain = elem->next; } pEntry->count--; if( pEntry->count<=0 ){ pEntry->chain = 0; } if( pH->copyKey && elem->pKey ){ fts3HashFree(elem->pKey); } fts3HashFree( elem ); pH->count--; if( pH->count<=0 ){ assert( pH->first==0 ); assert( pH->count==0 ); fts3HashClear(pH); } } SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem( const Fts3Hash *pH, const void *pKey, int nKey ){ int h; /* A hash on key */ int (*xHash)(const void*,int); /* The hash function */ if( pH==0 || pH->ht==0 ) return 0; xHash = ftsHashFunction(pH->keyClass); assert( xHash!=0 ); h = (*xHash)(pKey,nKey); assert( (pH->htsize & (pH->htsize-1))==0 ); return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1)); } /* ** Attempt to locate an element of the hash table pH with a key ** that matches pKey,nKey. Return the data for this element if it is ** found, or NULL if there is no match. */ SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){ Fts3HashElem *pElem; /* The element that matches key (if any) */ pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey); return pElem ? pElem->data : 0; } /* Insert an element into the hash table pH. The key is pKey,nKey ** and the data is "data". ** ** If no element exists with a matching key, then a new ** element is created. A copy of the key is made if the copyKey ** flag is set. NULL is returned. ** ** If another element already exists with the same key, then the ** new data replaces the old data and the old data is returned. ** The key is not copied in this instance. If a malloc fails, then ** the new data is returned and the hash table is unchanged. ** ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ SQLITE_PRIVATE void *sqlite3Fts3HashInsert( Fts3Hash *pH, /* The hash table to insert into */ const void *pKey, /* The key */ int nKey, /* Number of bytes in the key */ void *data /* The data */ ){ int hraw; /* Raw hash value of the key */ int h; /* the hash of the key modulo hash table size */ Fts3HashElem *elem; /* Used to loop thru the element list */ Fts3HashElem *new_elem; /* New element added to the pH */ int (*xHash)(const void*,int); /* The hash function */ assert( pH!=0 ); xHash = ftsHashFunction(pH->keyClass); assert( xHash!=0 ); hraw = (*xHash)(pKey, nKey); assert( (pH->htsize & (pH->htsize-1))==0 ); h = hraw & (pH->htsize-1); elem = fts3FindElementByHash(pH,pKey,nKey,h); if( elem ){ void *old_data = elem->data; if( data==0 ){ fts3RemoveElementByHash(pH,elem,h); }else{ elem->data = data; } return old_data; } if( data==0 ) return 0; if( (pH->htsize==0 && fts3Rehash(pH,8)) || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2)) ){ pH->count = 0; return data; } assert( pH->htsize>0 ); new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) ); if( new_elem==0 ) return data; if( pH->copyKey && pKey!=0 ){ new_elem->pKey = fts3HashMalloc( nKey ); if( new_elem->pKey==0 ){ fts3HashFree(new_elem); return data; } memcpy((void*)new_elem->pKey, pKey, nKey); }else{ new_elem->pKey = (void*)pKey; } new_elem->nKey = nKey; pH->count++; assert( pH->htsize>0 ); assert( (pH->htsize & (pH->htsize-1))==0 ); h = hraw & (pH->htsize-1); fts3HashInsertElement(pH, &pH->ht[h], new_elem); new_elem->data = data; return 0; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_hash.c *******************************************/ /************** Begin file fts3_porter.c *************************************/ /* ** 2006 September 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Implementation of the full-text-search tokenizer that implements ** a Porter stemmer. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <assert.h> */ /* #include <stdlib.h> */ /* #include <stdio.h> */ /* #include <string.h> */ /* #include "fts3_tokenizer.h" */ /* ** Class derived from sqlite3_tokenizer */ typedef struct porter_tokenizer { sqlite3_tokenizer base; /* Base class */ } porter_tokenizer; /* ** Class derived from sqlite3_tokenizer_cursor */ typedef struct porter_tokenizer_cursor { sqlite3_tokenizer_cursor base; const char *zInput; /* input we are tokenizing */ int nInput; /* size of the input */ int iOffset; /* current position in zInput */ int iToken; /* index of next token to be returned */ char *zToken; /* storage for current token */ int nAllocated; /* space allocated to zToken buffer */ } porter_tokenizer_cursor; /* ** Create a new tokenizer instance. */ static int porterCreate( int argc, const char * const *argv, sqlite3_tokenizer **ppTokenizer ){ porter_tokenizer *t; UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t)); if( t==NULL ) return SQLITE_NOMEM; memset(t, 0, sizeof(*t)); *ppTokenizer = &t->base; return SQLITE_OK; } /* ** Destroy a tokenizer */ static int porterDestroy(sqlite3_tokenizer *pTokenizer){ sqlite3_free(pTokenizer); return SQLITE_OK; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is zInput[0..nInput-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int porterOpen( sqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *zInput, int nInput, /* String to be tokenized */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ porter_tokenizer_cursor *c; UNUSED_PARAMETER(pTokenizer); c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); if( c==NULL ) return SQLITE_NOMEM; c->zInput = zInput; if( zInput==0 ){ c->nInput = 0; }else if( nInput<0 ){ c->nInput = (int)strlen(zInput); }else{ c->nInput = nInput; } c->iOffset = 0; /* start tokenizing at the beginning */ c->iToken = 0; c->zToken = NULL; /* no space allocated, yet. */ c->nAllocated = 0; *ppCursor = &c->base; return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to ** porterOpen() above. */ static int porterClose(sqlite3_tokenizer_cursor *pCursor){ porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; sqlite3_free(c->zToken); sqlite3_free(c); return SQLITE_OK; } /* ** Vowel or consonant */ static const char cType[] = { 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 2, 1 }; /* ** isConsonant() and isVowel() determine if their first character in ** the string they point to is a consonant or a vowel, according ** to Porter ruls. ** ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'. ** 'Y' is a consonant unless it follows another consonant, ** in which case it is a vowel. ** ** In these routine, the letters are in reverse order. So the 'y' rule ** is that 'y' is a consonant unless it is followed by another ** consonent. */ static int isVowel(const char*); static int isConsonant(const char *z){ int j; char x = *z; if( x==0 ) return 0; assert( x>='a' && x<='z' ); j = cType[x-'a']; if( j<2 ) return j; return z[1]==0 || isVowel(z + 1); } static int isVowel(const char *z){ int j; char x = *z; if( x==0 ) return 0; assert( x>='a' && x<='z' ); j = cType[x-'a']; if( j<2 ) return 1-j; return isConsonant(z + 1); } /* ** Let any sequence of one or more vowels be represented by V and let ** C be sequence of one or more consonants. Then every word can be ** represented as: ** ** [C] (VC){m} [V] ** ** In prose: A word is an optional consonant followed by zero or ** vowel-consonant pairs followed by an optional vowel. "m" is the ** number of vowel consonant pairs. This routine computes the value ** of m for the first i bytes of a word. ** ** Return true if the m-value for z is 1 or more. In other words, ** return true if z contains at least one vowel that is followed ** by a consonant. ** ** In this routine z[] is in reverse order. So we are really looking ** for an instance of a consonant followed by a vowel. */ static int m_gt_0(const char *z){ while( isVowel(z) ){ z++; } if( *z==0 ) return 0; while( isConsonant(z) ){ z++; } return *z!=0; } /* Like mgt0 above except we are looking for a value of m which is ** exactly 1 */ static int m_eq_1(const char *z){ while( isVowel(z) ){ z++; } if( *z==0 ) return 0; while( isConsonant(z) ){ z++; } if( *z==0 ) return 0; while( isVowel(z) ){ z++; } if( *z==0 ) return 1; while( isConsonant(z) ){ z++; } return *z==0; } /* Like mgt0 above except we are looking for a value of m>1 instead ** or m>0 */ static int m_gt_1(const char *z){ while( isVowel(z) ){ z++; } if( *z==0 ) return 0; while( isConsonant(z) ){ z++; } if( *z==0 ) return 0; while( isVowel(z) ){ z++; } if( *z==0 ) return 0; while( isConsonant(z) ){ z++; } return *z!=0; } /* ** Return TRUE if there is a vowel anywhere within z[0..n-1] */ static int hasVowel(const char *z){ while( isConsonant(z) ){ z++; } return *z!=0; } /* ** Return TRUE if the word ends in a double consonant. ** ** The text is reversed here. So we are really looking at ** the first two characters of z[]. */ static int doubleConsonant(const char *z){ return isConsonant(z) && z[0]==z[1]; } /* ** Return TRUE if the word ends with three letters which ** are consonant-vowel-consonent and where the final consonant ** is not 'w', 'x', or 'y'. ** ** The word is reversed here. So we are really checking the ** first three letters and the first one cannot be in [wxy]. */ static int star_oh(const char *z){ return isConsonant(z) && z[0]!='w' && z[0]!='x' && z[0]!='y' && isVowel(z+1) && isConsonant(z+2); } /* ** If the word ends with zFrom and xCond() is true for the stem ** of the word that preceeds the zFrom ending, then change the ** ending to zTo. ** ** The input word *pz and zFrom are both in reverse order. zTo ** is in normal order. ** ** Return TRUE if zFrom matches. Return FALSE if zFrom does not ** match. Not that TRUE is returned even if xCond() fails and ** no substitution occurs. */ static int stem( char **pz, /* The word being stemmed (Reversed) */ const char *zFrom, /* If the ending matches this... (Reversed) */ const char *zTo, /* ... change the ending to this (not reversed) */ int (*xCond)(const char*) /* Condition that must be true */ ){ char *z = *pz; while( *zFrom && *zFrom==*z ){ z++; zFrom++; } if( *zFrom!=0 ) return 0; if( xCond && !xCond(z) ) return 1; while( *zTo ){ *(--z) = *(zTo++); } *pz = z; return 1; } /* ** This is the fallback stemmer used when the porter stemmer is ** inappropriate. The input word is copied into the output with ** US-ASCII case folding. If the input word is too long (more ** than 20 bytes if it contains no digits or more than 6 bytes if ** it contains digits) then word is truncated to 20 or 6 bytes ** by taking 10 or 3 bytes from the beginning and end. */ static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){ int i, mx, j; int hasDigit = 0; for(i=0; i<nIn; i++){ char c = zIn[i]; if( c>='A' && c<='Z' ){ zOut[i] = c - 'A' + 'a'; }else{ if( c>='0' && c<='9' ) hasDigit = 1; zOut[i] = c; } } mx = hasDigit ? 3 : 10; if( nIn>mx*2 ){ for(j=mx, i=nIn-mx; i<nIn; i++, j++){ zOut[j] = zOut[i]; } i = j; } zOut[i] = 0; *pnOut = i; } /* ** Stem the input word zIn[0..nIn-1]. Store the output in zOut. ** zOut is at least big enough to hold nIn bytes. Write the actual ** size of the output word (exclusive of the '\0' terminator) into *pnOut. ** ** Any upper-case characters in the US-ASCII character set ([A-Z]) ** are converted to lower case. Upper-case UTF characters are ** unchanged. ** ** Words that are longer than about 20 bytes are stemmed by retaining ** a few bytes from the beginning and the end of the word. If the ** word contains digits, 3 bytes are taken from the beginning and ** 3 bytes from the end. For long words without digits, 10 bytes ** are taken from each end. US-ASCII case folding still applies. ** ** If the input word contains not digits but does characters not ** in [a-zA-Z] then no stemming is attempted and this routine just ** copies the input into the input into the output with US-ASCII ** case folding. ** ** Stemming never increases the length of the word. So there is ** no chance of overflowing the zOut buffer. */ static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){ int i, j; char zReverse[28]; char *z, *z2; if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){ /* The word is too big or too small for the porter stemmer. ** Fallback to the copy stemmer */ copy_stemmer(zIn, nIn, zOut, pnOut); return; } for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){ char c = zIn[i]; if( c>='A' && c<='Z' ){ zReverse[j] = c + 'a' - 'A'; }else if( c>='a' && c<='z' ){ zReverse[j] = c; }else{ /* The use of a character not in [a-zA-Z] means that we fallback ** to the copy stemmer */ copy_stemmer(zIn, nIn, zOut, pnOut); return; } } memset(&zReverse[sizeof(zReverse)-5], 0, 5); z = &zReverse[j+1]; /* Step 1a */ if( z[0]=='s' ){ if( !stem(&z, "sess", "ss", 0) && !stem(&z, "sei", "i", 0) && !stem(&z, "ss", "ss", 0) ){ z++; } } /* Step 1b */ z2 = z; if( stem(&z, "dee", "ee", m_gt_0) ){ /* Do nothing. The work was all in the test */ }else if( (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel)) && z!=z2 ){ if( stem(&z, "ta", "ate", 0) || stem(&z, "lb", "ble", 0) || stem(&z, "zi", "ize", 0) ){ /* Do nothing. The work was all in the test */ }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){ z++; }else if( m_eq_1(z) && star_oh(z) ){ *(--z) = 'e'; } } /* Step 1c */ if( z[0]=='y' && hasVowel(z+1) ){ z[0] = 'i'; } /* Step 2 */ switch( z[1] ){ case 'a': if( !stem(&z, "lanoita", "ate", m_gt_0) ){ stem(&z, "lanoit", "tion", m_gt_0); } break; case 'c': if( !stem(&z, "icne", "ence", m_gt_0) ){ stem(&z, "icna", "ance", m_gt_0); } break; case 'e': stem(&z, "rezi", "ize", m_gt_0); break; case 'g': stem(&z, "igol", "log", m_gt_0); break; case 'l': if( !stem(&z, "ilb", "ble", m_gt_0) && !stem(&z, "illa", "al", m_gt_0) && !stem(&z, "iltne", "ent", m_gt_0) && !stem(&z, "ile", "e", m_gt_0) ){ stem(&z, "ilsuo", "ous", m_gt_0); } break; case 'o': if( !stem(&z, "noitazi", "ize", m_gt_0) && !stem(&z, "noita", "ate", m_gt_0) ){ stem(&z, "rota", "ate", m_gt_0); } break; case 's': if( !stem(&z, "msila", "al", m_gt_0) && !stem(&z, "ssenevi", "ive", m_gt_0) && !stem(&z, "ssenluf", "ful", m_gt_0) ){ stem(&z, "ssensuo", "ous", m_gt_0); } break; case 't': if( !stem(&z, "itila", "al", m_gt_0) && !stem(&z, "itivi", "ive", m_gt_0) ){ stem(&z, "itilib", "ble", m_gt_0); } break; } /* Step 3 */ switch( z[0] ){ case 'e': if( !stem(&z, "etaci", "ic", m_gt_0) && !stem(&z, "evita", "", m_gt_0) ){ stem(&z, "ezila", "al", m_gt_0); } break; case 'i': stem(&z, "itici", "ic", m_gt_0); break; case 'l': if( !stem(&z, "laci", "ic", m_gt_0) ){ stem(&z, "luf", "", m_gt_0); } break; case 's': stem(&z, "ssen", "", m_gt_0); break; } /* Step 4 */ switch( z[1] ){ case 'a': if( z[0]=='l' && m_gt_1(z+2) ){ z += 2; } break; case 'c': if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){ z += 4; } break; case 'e': if( z[0]=='r' && m_gt_1(z+2) ){ z += 2; } break; case 'i': if( z[0]=='c' && m_gt_1(z+2) ){ z += 2; } break; case 'l': if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){ z += 4; } break; case 'n': if( z[0]=='t' ){ if( z[2]=='a' ){ if( m_gt_1(z+3) ){ z += 3; } }else if( z[2]=='e' ){ if( !stem(&z, "tneme", "", m_gt_1) && !stem(&z, "tnem", "", m_gt_1) ){ stem(&z, "tne", "", m_gt_1); } } } break; case 'o': if( z[0]=='u' ){ if( m_gt_1(z+2) ){ z += 2; } }else if( z[3]=='s' || z[3]=='t' ){ stem(&z, "noi", "", m_gt_1); } break; case 's': if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){ z += 3; } break; case 't': if( !stem(&z, "eta", "", m_gt_1) ){ stem(&z, "iti", "", m_gt_1); } break; case 'u': if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){ z += 3; } break; case 'v': case 'z': if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){ z += 3; } break; } /* Step 5a */ if( z[0]=='e' ){ if( m_gt_1(z+1) ){ z++; }else if( m_eq_1(z+1) && !star_oh(z+1) ){ z++; } } /* Step 5b */ if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){ z++; } /* z[] is now the stemmed word in reverse order. Flip it back ** around into forward order and return. */ *pnOut = i = (int)strlen(z); zOut[i] = 0; while( *z ){ zOut[--i] = *(z++); } } /* ** Characters that can be part of a token. We assume any character ** whose value is greater than 0x80 (any UTF character) can be ** part of a token. In other words, delimiters all must have ** values of 0x7f or lower. */ static const char porterIdChar[] = { /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ }; #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30])) /* ** Extract the next token from a tokenization cursor. The cursor must ** have been opened by a prior call to porterOpen(). */ static int porterNext( sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ const char **pzToken, /* OUT: *pzToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ int *piEndOffset, /* OUT: Ending offset of token */ int *piPosition /* OUT: Position integer of token */ ){ porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; const char *z = c->zInput; while( c->iOffset<c->nInput ){ int iStartOffset, ch; /* Scan past delimiter characters */ while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){ c->iOffset++; } /* Count non-delimiter characters. */ iStartOffset = c->iOffset; while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){ c->iOffset++; } if( c->iOffset>iStartOffset ){ int n = c->iOffset-iStartOffset; if( n>c->nAllocated ){ char *pNew; c->nAllocated = n+20; pNew = sqlite3_realloc(c->zToken, c->nAllocated); if( !pNew ) return SQLITE_NOMEM; c->zToken = pNew; } porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes); *pzToken = c->zToken; *piStartOffset = iStartOffset; *piEndOffset = c->iOffset; *piPosition = c->iToken++; return SQLITE_OK; } } return SQLITE_DONE; } /* ** The set of routines that implement the porter-stemmer tokenizer */ static const sqlite3_tokenizer_module porterTokenizerModule = { 0, porterCreate, porterDestroy, porterOpen, porterClose, porterNext, 0 }; /* ** Allocate a new porter tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &porterTokenizerModule; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_porter.c *****************************************/ /************** Begin file fts3_tokenizer.c **********************************/ /* ** 2007 June 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This is part of an SQLite module implementing full-text search. ** This particular file implements the generic tokenizer interface. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <assert.h> */ /* #include <string.h> */ /* ** Return true if the two-argument version of fts3_tokenizer() ** has been activated via a prior call to sqlite3_db_config(db, ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0); */ static int fts3TokenizerEnabled(sqlite3_context *context){ sqlite3 *db = sqlite3_context_db_handle(context); int isEnabled = 0; sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled); return isEnabled; } /* ** Implementation of the SQL scalar function for accessing the underlying ** hash table. This function may be called as follows: ** ** SELECT <function-name>(<key-name>); ** SELECT <function-name>(<key-name>, <pointer>); ** ** where <function-name> is the name passed as the second argument ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer'). ** ** If the <pointer> argument is specified, it must be a blob value ** containing a pointer to be stored as the hash data corresponding ** to the string <key-name>. If <pointer> is not specified, then ** the string <key-name> must already exist in the has table. Otherwise, ** an error is returned. ** ** Whether or not the <pointer> argument is specified, the value returned ** is a blob containing the pointer stored as the hash data corresponding ** to string <key-name> (after the hash-table is updated, if applicable). */ static void fts3TokenizerFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ Fts3Hash *pHash; void *pPtr = 0; const unsigned char *zName; int nName; assert( argc==1 || argc==2 ); pHash = (Fts3Hash *)sqlite3_user_data(context); zName = sqlite3_value_text(argv[0]); nName = sqlite3_value_bytes(argv[0])+1; if( argc==2 ){ if( fts3TokenizerEnabled(context) ){ void *pOld; int n = sqlite3_value_bytes(argv[1]); if( zName==0 || n!=sizeof(pPtr) ){ sqlite3_result_error(context, "argument type mismatch", -1); return; } pPtr = *(void **)sqlite3_value_blob(argv[1]); pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr); if( pOld==pPtr ){ sqlite3_result_error(context, "out of memory", -1); } }else{ sqlite3_result_error(context, "fts3tokenize disabled", -1); return; } }else{ if( zName ){ pPtr = sqlite3Fts3HashFind(pHash, zName, nName); } if( !pPtr ){ char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); sqlite3_result_error(context, zErr, -1); sqlite3_free(zErr); return; } } sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); } SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){ static const char isFtsIdChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ }; return (c&0x80 || isFtsIdChar[(int)(c)]); } SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){ const char *z1; const char *z2 = 0; /* Find the start of the next token. */ z1 = zStr; while( z2==0 ){ char c = *z1; switch( c ){ case '\0': return 0; /* No more tokens here */ case '\'': case '"': case '`': { z2 = z1; while( *++z2 && (*z2!=c || *++z2==c) ); break; } case '[': z2 = &z1[1]; while( *z2 && z2[0]!=']' ) z2++; if( *z2 ) z2++; break; default: if( sqlite3Fts3IsIdChar(*z1) ){ z2 = &z1[1]; while( sqlite3Fts3IsIdChar(*z2) ) z2++; }else{ z1++; } } } *pn = (int)(z2-z1); return z1; } SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( Fts3Hash *pHash, /* Tokenizer hash table */ const char *zArg, /* Tokenizer name */ sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */ char **pzErr /* OUT: Set to malloced error message */ ){ int rc; char *z = (char *)zArg; int n = 0; char *zCopy; char *zEnd; /* Pointer to nul-term of zCopy */ sqlite3_tokenizer_module *m; zCopy = sqlite3_mprintf("%s", zArg); if( !zCopy ) return SQLITE_NOMEM; zEnd = &zCopy[strlen(zCopy)]; z = (char *)sqlite3Fts3NextToken(zCopy, &n); if( z==0 ){ assert( n==0 ); z = zCopy; } z[n] = '\0'; sqlite3Fts3Dequote(z); m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1); if( !m ){ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z); rc = SQLITE_ERROR; }else{ char const **aArg = 0; int iArg = 0; z = &z[n+1]; while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){ int nNew = sizeof(char *)*(iArg+1); char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew); if( !aNew ){ sqlite3_free(zCopy); sqlite3_free((void *)aArg); return SQLITE_NOMEM; } aArg = aNew; aArg[iArg++] = z; z[n] = '\0'; sqlite3Fts3Dequote(z); z = &z[n+1]; } rc = m->xCreate(iArg, aArg, ppTok); assert( rc!=SQLITE_OK || *ppTok ); if( rc!=SQLITE_OK ){ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer"); }else{ (*ppTok)->pModule = m; } sqlite3_free((void *)aArg); } sqlite3_free(zCopy); return rc; } #ifdef SQLITE_TEST #if defined(INCLUDE_SQLITE_TCL_H) # include "sqlite_tcl.h" #else # include "tcl.h" #endif /* #include <string.h> */ /* ** Implementation of a special SQL scalar function for testing tokenizers ** designed to be used in concert with the Tcl testing framework. This ** function must be called with two or more arguments: ** ** SELECT <function-name>(<key-name>, ..., <input-string>); ** ** where <function-name> is the name passed as the second argument ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer') ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test'). ** ** The return value is a string that may be interpreted as a Tcl ** list. For each token in the <input-string>, three elements are ** added to the returned list. The first is the token position, the ** second is the token text (folded, stemmed, etc.) and the third is the ** substring of <input-string> associated with the token. For example, ** using the built-in "simple" tokenizer: ** ** SELECT fts_tokenizer_test('simple', 'I don't see how'); ** ** will return the string: ** ** "{0 i I 1 dont don't 2 see see 3 how how}" ** */ static void testFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ Fts3Hash *pHash; sqlite3_tokenizer_module *p; sqlite3_tokenizer *pTokenizer = 0; sqlite3_tokenizer_cursor *pCsr = 0; const char *zErr = 0; const char *zName; int nName; const char *zInput; int nInput; const char *azArg[64]; const char *zToken; int nToken = 0; int iStart = 0; int iEnd = 0; int iPos = 0; int i; Tcl_Obj *pRet; if( argc<2 ){ sqlite3_result_error(context, "insufficient arguments", -1); return; } nName = sqlite3_value_bytes(argv[0]); zName = (const char *)sqlite3_value_text(argv[0]); nInput = sqlite3_value_bytes(argv[argc-1]); zInput = (const char *)sqlite3_value_text(argv[argc-1]); pHash = (Fts3Hash *)sqlite3_user_data(context); p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); if( !p ){ char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName); sqlite3_result_error(context, zErr2, -1); sqlite3_free(zErr2); return; } pRet = Tcl_NewObj(); Tcl_IncrRefCount(pRet); for(i=1; i<argc-1; i++){ azArg[i-1] = (const char *)sqlite3_value_text(argv[i]); } if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){ zErr = "error in xCreate()"; goto finish; } pTokenizer->pModule = p; if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){ zErr = "error in xOpen()"; goto finish; } while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){ Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos)); Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); zToken = &zInput[iStart]; nToken = iEnd-iStart; Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); } if( SQLITE_OK!=p->xClose(pCsr) ){ zErr = "error in xClose()"; goto finish; } if( SQLITE_OK!=p->xDestroy(pTokenizer) ){ zErr = "error in xDestroy()"; goto finish; } finish: if( zErr ){ sqlite3_result_error(context, zErr, -1); }else{ sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); } Tcl_DecrRefCount(pRet); } static int registerTokenizer( sqlite3 *db, char *zName, const sqlite3_tokenizer_module *p ){ int rc; sqlite3_stmt *pStmt; const char zSql[] = "SELECT fts3_tokenizer(?, ?)"; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ return rc; } sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); sqlite3_step(pStmt); return sqlite3_finalize(pStmt); } static int queryTokenizer( sqlite3 *db, char *zName, const sqlite3_tokenizer_module **pp ){ int rc; sqlite3_stmt *pStmt; const char zSql[] = "SELECT fts3_tokenizer(?)"; *pp = 0; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ return rc; } sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); if( SQLITE_ROW==sqlite3_step(pStmt) ){ if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); } } return sqlite3_finalize(pStmt); } SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); /* ** Implementation of the scalar function fts3_tokenizer_internal_test(). ** This function is used for testing only, it is not included in the ** build unless SQLITE_TEST is defined. ** ** The purpose of this is to test that the fts3_tokenizer() function ** can be used as designed by the C-code in the queryTokenizer and ** registerTokenizer() functions above. These two functions are repeated ** in the README.tokenizer file as an example, so it is important to ** test them. ** ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar ** function with no arguments. An assert() will fail if a problem is ** detected. i.e.: ** ** SELECT fts3_tokenizer_internal_test(); ** */ static void intTestFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ int rc; const sqlite3_tokenizer_module *p1; const sqlite3_tokenizer_module *p2; sqlite3 *db = (sqlite3 *)sqlite3_user_data(context); UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); /* Test the query function */ sqlite3Fts3SimpleTokenizerModule(&p1); rc = queryTokenizer(db, "simple", &p2); assert( rc==SQLITE_OK ); assert( p1==p2 ); rc = queryTokenizer(db, "nosuchtokenizer", &p2); assert( rc==SQLITE_ERROR ); assert( p2==0 ); assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") ); /* Test the storage function */ if( fts3TokenizerEnabled(context) ){ rc = registerTokenizer(db, "nosuchtokenizer", p1); assert( rc==SQLITE_OK ); rc = queryTokenizer(db, "nosuchtokenizer", &p2); assert( rc==SQLITE_OK ); assert( p2==p1 ); } sqlite3_result_text(context, "ok", -1, SQLITE_STATIC); } #endif /* ** Set up SQL objects in database db used to access the contents of ** the hash table pointed to by argument pHash. The hash table must ** been initialized to use string keys, and to take a private copy ** of the key when a value is inserted. i.e. by a call similar to: ** ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); ** ** This function adds a scalar function (see header comment above ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is ** defined at compilation time, a temporary virtual table (see header ** comment above struct HashTableVtab) to the database schema. Both ** provide read/write access to the contents of *pHash. ** ** The third argument to this function, zName, is used as the name ** of both the scalar and, if created, the virtual table. */ SQLITE_PRIVATE int sqlite3Fts3InitHashTable( sqlite3 *db, Fts3Hash *pHash, const char *zName ){ int rc = SQLITE_OK; void *p = (void *)pHash; const int any = SQLITE_ANY; #ifdef SQLITE_TEST char *zTest = 0; char *zTest2 = 0; void *pdb = (void *)db; zTest = sqlite3_mprintf("%s_test", zName); zTest2 = sqlite3_mprintf("%s_internal_test", zName); if( !zTest || !zTest2 ){ rc = SQLITE_NOMEM; } #endif if( SQLITE_OK==rc ){ rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0); } if( SQLITE_OK==rc ){ rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0); } #ifdef SQLITE_TEST if( SQLITE_OK==rc ){ rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0); } if( SQLITE_OK==rc ){ rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0); } #endif #ifdef SQLITE_TEST sqlite3_free(zTest); sqlite3_free(zTest2); #endif return rc; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_tokenizer.c **************************************/ /************** Begin file fts3_tokenizer1.c *********************************/ /* ** 2006 Oct 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Implementation of the "simple" full-text-search tokenizer. */ /* ** The code in this file is only compiled if: ** ** * The FTS3 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <assert.h> */ /* #include <stdlib.h> */ /* #include <stdio.h> */ /* #include <string.h> */ /* #include "fts3_tokenizer.h" */ typedef struct simple_tokenizer { sqlite3_tokenizer base; char delim[128]; /* flag ASCII delimiters */ } simple_tokenizer; typedef struct simple_tokenizer_cursor { sqlite3_tokenizer_cursor base; const char *pInput; /* input we are tokenizing */ int nBytes; /* size of the input */ int iOffset; /* current position in pInput */ int iToken; /* index of next token to be returned */ char *pToken; /* storage for current token */ int nTokenAllocated; /* space allocated to zToken buffer */ } simple_tokenizer_cursor; static int simpleDelim(simple_tokenizer *t, unsigned char c){ return c<0x80 && t->delim[c]; } static int fts3_isalnum(int x){ return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z'); } /* ** Create a new tokenizer instance. */ static int simpleCreate( int argc, const char * const *argv, sqlite3_tokenizer **ppTokenizer ){ simple_tokenizer *t; t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t)); if( t==NULL ) return SQLITE_NOMEM; memset(t, 0, sizeof(*t)); /* TODO(shess) Delimiters need to remain the same from run to run, ** else we need to reindex. One solution would be a meta-table to ** track such information in the database, then we'd only want this ** information on the initial create. */ if( argc>1 ){ int i, n = (int)strlen(argv[1]); for(i=0; i<n; i++){ unsigned char ch = argv[1][i]; /* We explicitly don't support UTF-8 delimiters for now. */ if( ch>=0x80 ){ sqlite3_free(t); return SQLITE_ERROR; } t->delim[ch] = 1; } } else { /* Mark non-alphanumeric ASCII characters as delimiters */ int i; for(i=1; i<0x80; i++){ t->delim[i] = !fts3_isalnum(i) ? -1 : 0; } } *ppTokenizer = &t->base; return SQLITE_OK; } /* ** Destroy a tokenizer */ static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ sqlite3_free(pTokenizer); return SQLITE_OK; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is pInput[0..nBytes-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int simpleOpen( sqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *pInput, int nBytes, /* String to be tokenized */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ simple_tokenizer_cursor *c; UNUSED_PARAMETER(pTokenizer); c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); if( c==NULL ) return SQLITE_NOMEM; c->pInput = pInput; if( pInput==0 ){ c->nBytes = 0; }else if( nBytes<0 ){ c->nBytes = (int)strlen(pInput); }else{ c->nBytes = nBytes; } c->iOffset = 0; /* start tokenizing at the beginning */ c->iToken = 0; c->pToken = NULL; /* no space allocated, yet. */ c->nTokenAllocated = 0; *ppCursor = &c->base; return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to ** simpleOpen() above. */ static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; sqlite3_free(c->pToken); sqlite3_free(c); return SQLITE_OK; } /* ** Extract the next token from a tokenization cursor. The cursor must ** have been opened by a prior call to simpleOpen(). */ static int simpleNext( sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ const char **ppToken, /* OUT: *ppToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ int *piEndOffset, /* OUT: Ending offset of token */ int *piPosition /* OUT: Position integer of token */ ){ simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer; unsigned char *p = (unsigned char *)c->pInput; while( c->iOffset<c->nBytes ){ int iStartOffset; /* Scan past delimiter characters */ while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){ c->iOffset++; } /* Count non-delimiter characters. */ iStartOffset = c->iOffset; while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){ c->iOffset++; } if( c->iOffset>iStartOffset ){ int i, n = c->iOffset-iStartOffset; if( n>c->nTokenAllocated ){ char *pNew; c->nTokenAllocated = n+20; pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated); if( !pNew ) return SQLITE_NOMEM; c->pToken = pNew; } for(i=0; i<n; i++){ /* TODO(shess) This needs expansion to handle UTF-8 ** case-insensitivity. */ unsigned char ch = p[iStartOffset+i]; c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch); } *ppToken = c->pToken; *pnBytes = n; *piStartOffset = iStartOffset; *piEndOffset = c->iOffset; *piPosition = c->iToken++; return SQLITE_OK; } } return SQLITE_DONE; } /* ** The set of routines that implement the simple tokenizer */ static const sqlite3_tokenizer_module simpleTokenizerModule = { 0, simpleCreate, simpleDestroy, simpleOpen, simpleClose, simpleNext, 0, }; /* ** Allocate a new simple tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &simpleTokenizerModule; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_tokenizer1.c *************************************/ /************** Begin file fts3_tokenize_vtab.c ******************************/ /* ** 2013 Apr 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code for the "fts3tokenize" virtual table module. ** An fts3tokenize virtual table is created as follows: ** ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize( ** <tokenizer-name>, <arg-1>, ... ** ); ** ** The table created has the following schema: ** ** CREATE TABLE <tbl>(input, token, start, end, position) ** ** When queried, the query must include a WHERE clause of type: ** ** input = <string> ** ** The virtual table module tokenizes this <string>, using the FTS3 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE ** statement and returns one row for each token in the result. With ** fields set as follows: ** ** input: Always set to a copy of <string> ** token: A token from the input. ** start: Byte offset of the token within the input <string>. ** end: Byte offset of the byte immediately following the end of the ** token within the input string. ** pos: Token offset of token within input. ** */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <string.h> */ /* #include <assert.h> */ typedef struct Fts3tokTable Fts3tokTable; typedef struct Fts3tokCursor Fts3tokCursor; /* ** Virtual table structure. */ struct Fts3tokTable { sqlite3_vtab base; /* Base class used by SQLite core */ const sqlite3_tokenizer_module *pMod; sqlite3_tokenizer *pTok; }; /* ** Virtual table cursor structure. */ struct Fts3tokCursor { sqlite3_vtab_cursor base; /* Base class used by SQLite core */ char *zInput; /* Input string */ sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */ int iRowid; /* Current 'rowid' value */ const char *zToken; /* Current 'token' value */ int nToken; /* Size of zToken in bytes */ int iStart; /* Current 'start' value */ int iEnd; /* Current 'end' value */ int iPos; /* Current 'pos' value */ }; /* ** Query FTS for the tokenizer implementation named zName. */ static int fts3tokQueryTokenizer( Fts3Hash *pHash, const char *zName, const sqlite3_tokenizer_module **pp, char **pzErr ){ sqlite3_tokenizer_module *p; int nName = (int)strlen(zName); p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); if( !p ){ sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName); return SQLITE_ERROR; } *pp = p; return SQLITE_OK; } /* ** The second argument, argv[], is an array of pointers to nul-terminated ** strings. This function makes a copy of the array and strings into a ** single block of memory. It then dequotes any of the strings that appear ** to be quoted. ** ** If successful, output parameter *pazDequote is set to point at the ** array of dequoted strings and SQLITE_OK is returned. The caller is ** responsible for eventually calling sqlite3_free() to free the array ** in this case. Or, if an error occurs, an SQLite error code is returned. ** The final value of *pazDequote is undefined in this case. */ static int fts3tokDequoteArray( int argc, /* Number of elements in argv[] */ const char * const *argv, /* Input array */ char ***pazDequote /* Output array */ ){ int rc = SQLITE_OK; /* Return code */ if( argc==0 ){ *pazDequote = 0; }else{ int i; int nByte = 0; char **azDequote; for(i=0; i<argc; i++){ nByte += (int)(strlen(argv[i]) + 1); } *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte); if( azDequote==0 ){ rc = SQLITE_NOMEM; }else{ char *pSpace = (char *)&azDequote[argc]; for(i=0; i<argc; i++){ int n = (int)strlen(argv[i]); azDequote[i] = pSpace; memcpy(pSpace, argv[i], n+1); sqlite3Fts3Dequote(pSpace); pSpace += (n+1); } } } return rc; } /* ** Schema of the tokenizer table. */ #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)" /* ** This function does all the work for both the xConnect and xCreate methods. ** These tables have no persistent representation of their own, so xConnect ** and xCreate are identical operations. ** ** argv[0]: module name ** argv[1]: database name ** argv[2]: table name ** argv[3]: first argument (tokenizer name) */ static int fts3tokConnectMethod( sqlite3 *db, /* Database connection */ void *pHash, /* Hash table of tokenizers */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ Fts3tokTable *pTab = 0; const sqlite3_tokenizer_module *pMod = 0; sqlite3_tokenizer *pTok = 0; int rc; char **azDequote = 0; int nDequote; rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA); if( rc!=SQLITE_OK ) return rc; nDequote = argc-3; rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote); if( rc==SQLITE_OK ){ const char *zModule; if( nDequote<1 ){ zModule = "simple"; }else{ zModule = azDequote[0]; } rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr); } assert( (rc==SQLITE_OK)==(pMod!=0) ); if( rc==SQLITE_OK ){ const char * const *azArg = (const char * const *)&azDequote[1]; rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok); } if( rc==SQLITE_OK ){ pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable)); if( pTab==0 ){ rc = SQLITE_NOMEM; } } if( rc==SQLITE_OK ){ memset(pTab, 0, sizeof(Fts3tokTable)); pTab->pMod = pMod; pTab->pTok = pTok; *ppVtab = &pTab->base; }else{ if( pTok ){ pMod->xDestroy(pTok); } } sqlite3_free(azDequote); return rc; } /* ** This function does the work for both the xDisconnect and xDestroy methods. ** These tables have no persistent representation of their own, so xDisconnect ** and xDestroy are identical operations. */ static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){ Fts3tokTable *pTab = (Fts3tokTable *)pVtab; pTab->pMod->xDestroy(pTab->pTok); sqlite3_free(pTab); return SQLITE_OK; } /* ** xBestIndex - Analyze a WHERE and ORDER BY clause. */ static int fts3tokBestIndexMethod( sqlite3_vtab *pVTab, sqlite3_index_info *pInfo ){ int i; UNUSED_PARAMETER(pVTab); for(i=0; i<pInfo->nConstraint; i++){ if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ ){ pInfo->idxNum = 1; pInfo->aConstraintUsage[i].argvIndex = 1; pInfo->aConstraintUsage[i].omit = 1; pInfo->estimatedCost = 1; return SQLITE_OK; } } pInfo->idxNum = 0; assert( pInfo->estimatedCost>1000000.0 ); return SQLITE_OK; } /* ** xOpen - Open a cursor. */ static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ Fts3tokCursor *pCsr; UNUSED_PARAMETER(pVTab); pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor)); if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(Fts3tokCursor)); *ppCsr = (sqlite3_vtab_cursor *)pCsr; return SQLITE_OK; } /* ** Reset the tokenizer cursor passed as the only argument. As if it had ** just been returned by fts3tokOpenMethod(). */ static void fts3tokResetCursor(Fts3tokCursor *pCsr){ if( pCsr->pCsr ){ Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab); pTab->pMod->xClose(pCsr->pCsr); pCsr->pCsr = 0; } sqlite3_free(pCsr->zInput); pCsr->zInput = 0; pCsr->zToken = 0; pCsr->nToken = 0; pCsr->iStart = 0; pCsr->iEnd = 0; pCsr->iPos = 0; pCsr->iRowid = 0; } /* ** xClose - Close a cursor. */ static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; fts3tokResetCursor(pCsr); sqlite3_free(pCsr); return SQLITE_OK; } /* ** xNext - Advance the cursor to the next row, if any. */ static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); int rc; /* Return code */ pCsr->iRowid++; rc = pTab->pMod->xNext(pCsr->pCsr, &pCsr->zToken, &pCsr->nToken, &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos ); if( rc!=SQLITE_OK ){ fts3tokResetCursor(pCsr); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } return rc; } /* ** xFilter - Initialize a cursor to point at the start of its data. */ static int fts3tokFilterMethod( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ sqlite3_value **apVal /* Arguments for the indexing scheme */ ){ int rc = SQLITE_ERROR; Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); UNUSED_PARAMETER(idxStr); UNUSED_PARAMETER(nVal); fts3tokResetCursor(pCsr); if( idxNum==1 ){ const char *zByte = (const char *)sqlite3_value_text(apVal[0]); int nByte = sqlite3_value_bytes(apVal[0]); pCsr->zInput = sqlite3_malloc(nByte+1); if( pCsr->zInput==0 ){ rc = SQLITE_NOMEM; }else{ memcpy(pCsr->zInput, zByte, nByte); pCsr->zInput[nByte] = 0; rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr); if( rc==SQLITE_OK ){ pCsr->pCsr->pTokenizer = pTab->pTok; } } } if( rc!=SQLITE_OK ) return rc; return fts3tokNextMethod(pCursor); } /* ** xEof - Return true if the cursor is at EOF, or false otherwise. */ static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; return (pCsr->zToken==0); } /* ** xColumn - Return a column value. */ static int fts3tokColumnMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; /* CREATE TABLE x(input, token, start, end, position) */ switch( iCol ){ case 0: sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT); break; case 1: sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT); break; case 2: sqlite3_result_int(pCtx, pCsr->iStart); break; case 3: sqlite3_result_int(pCtx, pCsr->iEnd); break; default: assert( iCol==4 ); sqlite3_result_int(pCtx, pCsr->iPos); break; } return SQLITE_OK; } /* ** xRowid - Return the current rowid for the cursor. */ static int fts3tokRowidMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite_int64 *pRowid /* OUT: Rowid value */ ){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; *pRowid = (sqlite3_int64)pCsr->iRowid; return SQLITE_OK; } /* ** Register the fts3tok module with database connection db. Return SQLITE_OK ** if successful or an error code if sqlite3_create_module() fails. */ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){ static const sqlite3_module fts3tok_module = { 0, /* iVersion */ fts3tokConnectMethod, /* xCreate */ fts3tokConnectMethod, /* xConnect */ fts3tokBestIndexMethod, /* xBestIndex */ fts3tokDisconnectMethod, /* xDisconnect */ fts3tokDisconnectMethod, /* xDestroy */ fts3tokOpenMethod, /* xOpen */ fts3tokCloseMethod, /* xClose */ fts3tokFilterMethod, /* xFilter */ fts3tokNextMethod, /* xNext */ fts3tokEofMethod, /* xEof */ fts3tokColumnMethod, /* xColumn */ fts3tokRowidMethod, /* xRowid */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindFunction */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; int rc; /* Return code */ rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash); return rc; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_tokenize_vtab.c **********************************/ /************** Begin file fts3_write.c **************************************/ /* ** 2009 Oct 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file is part of the SQLite FTS3 extension module. Specifically, ** this file contains code to insert, update and delete rows from FTS3 ** tables. It also contains code to merge FTS3 b-tree segments. Some ** of the sub-routines used to merge segments are also used by the query ** code in fts3.c. */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <string.h> */ /* #include <assert.h> */ /* #include <stdlib.h> */ #define FTS_MAX_APPENDABLE_HEIGHT 16 /* ** When full-text index nodes are loaded from disk, the buffer that they ** are loaded into has the following number of bytes of padding at the end ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer ** of 920 bytes is allocated for it. ** ** This means that if we have a pointer into a buffer containing node data, ** it is always safe to read up to two varints from it without risking an ** overread, even if the node data is corrupted. */ #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2) /* ** Under certain circumstances, b-tree nodes (doclists) can be loaded into ** memory incrementally instead of all at once. This can be a big performance ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext() ** method before retrieving all query results (as may happen, for example, ** if a query has a LIMIT clause). ** ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes. ** The code is written so that the hard lower-limit for each of these values ** is 1. Clearly such small values would be inefficient, but can be useful ** for testing purposes. ** ** If this module is built with SQLITE_TEST defined, these constants may ** be overridden at runtime for testing purposes. File fts3_test.c contains ** a Tcl interface to read and write the values. */ #ifdef SQLITE_TEST int test_fts3_node_chunksize = (4*1024); int test_fts3_node_chunk_threshold = (4*1024)*4; # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold #else # define FTS3_NODE_CHUNKSIZE (4*1024) # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4) #endif /* ** The two values that may be meaningfully bound to the :1 parameter in ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT. */ #define FTS_STAT_DOCTOTAL 0 #define FTS_STAT_INCRMERGEHINT 1 #define FTS_STAT_AUTOINCRMERGE 2 /* ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic ** and incremental merge operation that takes place. This is used for ** debugging FTS only, it should not usually be turned on in production ** systems. */ #ifdef FTS3_LOG_MERGES static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){ sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel); } #else #define fts3LogMerge(x, y) #endif typedef struct PendingList PendingList; typedef struct SegmentNode SegmentNode; typedef struct SegmentWriter SegmentWriter; /* ** An instance of the following data structure is used to build doclists ** incrementally. See function fts3PendingListAppend() for details. */ struct PendingList { int nData; char *aData; int nSpace; sqlite3_int64 iLastDocid; sqlite3_int64 iLastCol; sqlite3_int64 iLastPos; }; /* ** Each cursor has a (possibly empty) linked list of the following objects. */ struct Fts3DeferredToken { Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */ int iCol; /* Column token must occur in */ Fts3DeferredToken *pNext; /* Next in list of deferred tokens */ PendingList *pList; /* Doclist is assembled here */ }; /* ** An instance of this structure is used to iterate through the terms on ** a contiguous set of segment b-tree leaf nodes. Although the details of ** this structure are only manipulated by code in this file, opaque handles ** of type Fts3SegReader* are also used by code in fts3.c to iterate through ** terms when querying the full-text index. See functions: ** ** sqlite3Fts3SegReaderNew() ** sqlite3Fts3SegReaderFree() ** sqlite3Fts3SegReaderIterate() ** ** Methods used to manipulate Fts3SegReader structures: ** ** fts3SegReaderNext() ** fts3SegReaderFirstDocid() ** fts3SegReaderNextDocid() */ struct Fts3SegReader { int iIdx; /* Index within level, or 0x7FFFFFFF for PT */ u8 bLookup; /* True for a lookup only */ u8 rootOnly; /* True for a root-only reader */ sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */ sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */ sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */ sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */ char *aNode; /* Pointer to node data (or NULL) */ int nNode; /* Size of buffer at aNode (or 0) */ int nPopulate; /* If >0, bytes of buffer aNode[] loaded */ sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */ Fts3HashElem **ppNextElem; /* Variables set by fts3SegReaderNext(). These may be read directly ** by the caller. They are valid from the time SegmentReaderNew() returns ** until SegmentReaderNext() returns something other than SQLITE_OK ** (i.e. SQLITE_DONE). */ int nTerm; /* Number of bytes in current term */ char *zTerm; /* Pointer to current term */ int nTermAlloc; /* Allocated size of zTerm buffer */ char *aDoclist; /* Pointer to doclist of current entry */ int nDoclist; /* Size of doclist in current entry */ /* The following variables are used by fts3SegReaderNextDocid() to iterate ** through the current doclist (aDoclist/nDoclist). */ char *pOffsetList; int nOffsetList; /* For descending pending seg-readers only */ sqlite3_int64 iDocid; }; #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0) #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0) /* ** An instance of this structure is used to create a segment b-tree in the ** database. The internal details of this type are only accessed by the ** following functions: ** ** fts3SegWriterAdd() ** fts3SegWriterFlush() ** fts3SegWriterFree() */ struct SegmentWriter { SegmentNode *pTree; /* Pointer to interior tree structure */ sqlite3_int64 iFirst; /* First slot in %_segments written */ sqlite3_int64 iFree; /* Next free slot in %_segments */ char *zTerm; /* Pointer to previous term buffer */ int nTerm; /* Number of bytes in zTerm */ int nMalloc; /* Size of malloc'd buffer at zMalloc */ char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ int nSize; /* Size of allocation at aData */ int nData; /* Bytes of data in aData */ char *aData; /* Pointer to block from malloc() */ i64 nLeafData; /* Number of bytes of leaf data written */ }; /* ** Type SegmentNode is used by the following three functions to create ** the interior part of the segment b+-tree structures (everything except ** the leaf nodes). These functions and type are only ever used by code ** within the fts3SegWriterXXX() family of functions described above. ** ** fts3NodeAddTerm() ** fts3NodeWrite() ** fts3NodeFree() ** ** When a b+tree is written to the database (either as a result of a merge ** or the pending-terms table being flushed), leaves are written into the ** database file as soon as they are completely populated. The interior of ** the tree is assembled in memory and written out only once all leaves have ** been populated and stored. This is Ok, as the b+-tree fanout is usually ** very large, meaning that the interior of the tree consumes relatively ** little memory. */ struct SegmentNode { SegmentNode *pParent; /* Parent node (or NULL for root node) */ SegmentNode *pRight; /* Pointer to right-sibling */ SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */ int nEntry; /* Number of terms written to node so far */ char *zTerm; /* Pointer to previous term buffer */ int nTerm; /* Number of bytes in zTerm */ int nMalloc; /* Size of malloc'd buffer at zMalloc */ char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ int nData; /* Bytes of valid data so far */ char *aData; /* Node data */ }; /* ** Valid values for the second argument to fts3SqlStmt(). */ #define SQL_DELETE_CONTENT 0 #define SQL_IS_EMPTY 1 #define SQL_DELETE_ALL_CONTENT 2 #define SQL_DELETE_ALL_SEGMENTS 3 #define SQL_DELETE_ALL_SEGDIR 4 #define SQL_DELETE_ALL_DOCSIZE 5 #define SQL_DELETE_ALL_STAT 6 #define SQL_SELECT_CONTENT_BY_ROWID 7 #define SQL_NEXT_SEGMENT_INDEX 8 #define SQL_INSERT_SEGMENTS 9 #define SQL_NEXT_SEGMENTS_ID 10 #define SQL_INSERT_SEGDIR 11 #define SQL_SELECT_LEVEL 12 #define SQL_SELECT_LEVEL_RANGE 13 #define SQL_SELECT_LEVEL_COUNT 14 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15 #define SQL_DELETE_SEGDIR_LEVEL 16 #define SQL_DELETE_SEGMENTS_RANGE 17 #define SQL_CONTENT_INSERT 18 #define SQL_DELETE_DOCSIZE 19 #define SQL_REPLACE_DOCSIZE 20 #define SQL_SELECT_DOCSIZE 21 #define SQL_SELECT_STAT 22 #define SQL_REPLACE_STAT 23 #define SQL_SELECT_ALL_PREFIX_LEVEL 24 #define SQL_DELETE_ALL_TERMS_SEGDIR 25 #define SQL_DELETE_SEGDIR_RANGE 26 #define SQL_SELECT_ALL_LANGID 27 #define SQL_FIND_MERGE_LEVEL 28 #define SQL_MAX_LEAF_NODE_ESTIMATE 29 #define SQL_DELETE_SEGDIR_ENTRY 30 #define SQL_SHIFT_SEGDIR_ENTRY 31 #define SQL_SELECT_SEGDIR 32 #define SQL_CHOMP_SEGDIR 33 #define SQL_SEGMENT_IS_APPENDABLE 34 #define SQL_SELECT_INDEXES 35 #define SQL_SELECT_MXLEVEL 36 #define SQL_SELECT_LEVEL_RANGE2 37 #define SQL_UPDATE_LEVEL_IDX 38 #define SQL_UPDATE_LEVEL 39 /* ** This function is used to obtain an SQLite prepared statement handle ** for the statement identified by the second argument. If successful, ** *pp is set to the requested statement handle and SQLITE_OK returned. ** Otherwise, an SQLite error code is returned and *pp is set to 0. ** ** If argument apVal is not NULL, then it must point to an array with ** at least as many entries as the requested statement has bound ** parameters. The values are bound to the statements parameters before ** returning. */ static int fts3SqlStmt( Fts3Table *p, /* Virtual table handle */ int eStmt, /* One of the SQL_XXX constants above */ sqlite3_stmt **pp, /* OUT: Statement handle */ sqlite3_value **apVal /* Values to bind to statement */ ){ const char *azSql[] = { /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?", /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)", /* 2 */ "DELETE FROM %Q.'%q_content'", /* 3 */ "DELETE FROM %Q.'%q_segments'", /* 4 */ "DELETE FROM %Q.'%q_segdir'", /* 5 */ "DELETE FROM %Q.'%q_docsize'", /* 6 */ "DELETE FROM %Q.'%q_stat'", /* 7 */ "SELECT %s WHERE rowid=?", /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1", /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)", /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)", /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)", /* Return segments in order from oldest to newest.*/ /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root " "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC", /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root " "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?" "ORDER BY level DESC, idx ASC", /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?", /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?", /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?", /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)", /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?", /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?", /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?", /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)", /* 24 */ "", /* 25 */ "", /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'", /* This statement is used to determine which level to read the input from ** when performing an incremental merge. It returns the absolute level number ** of the oldest level in the db that contains at least ? segments. Or, ** if no level in the FTS index contains more than ? segments, the statement ** returns zero rows. */ /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' " " GROUP BY level HAVING cnt>=?" " ORDER BY (level %% 1024) ASC LIMIT 1", /* Estimate the upper limit on the number of leaf nodes in a new segment ** created by merging the oldest :2 segments from absolute level :1. See ** function sqlite3Fts3Incrmerge() for details. */ /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) " " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?", /* SQL_DELETE_SEGDIR_ENTRY ** Delete the %_segdir entry on absolute level :1 with index :2. */ /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", /* SQL_SHIFT_SEGDIR_ENTRY ** Modify the idx value for the segment with idx=:3 on absolute level :2 ** to :1. */ /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?", /* SQL_SELECT_SEGDIR ** Read a single entry from the %_segdir table. The entry from absolute ** level :1 with index value :2. */ /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root " "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", /* SQL_CHOMP_SEGDIR ** Update the start_block (:1) and root (:2) fields of the %_segdir ** entry located on absolute level :3 with index :4. */ /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?" "WHERE level = ? AND idx = ?", /* SQL_SEGMENT_IS_APPENDABLE ** Return a single row if the segment with end_block=? is appendable. Or ** no rows otherwise. */ /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL", /* SQL_SELECT_INDEXES ** Return the list of valid segment indexes for absolute level ? */ /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC", /* SQL_SELECT_MXLEVEL ** Return the largest relative level in the FTS index or indexes. */ /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'", /* Return segments in order from oldest to newest.*/ /* 37 */ "SELECT level, idx, end_block " "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? " "ORDER BY level DESC, idx ASC", /* Update statements used while promoting segments */ /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? " "WHERE level=? AND idx=?", /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1" }; int rc = SQLITE_OK; sqlite3_stmt *pStmt; assert( SizeofArray(azSql)==SizeofArray(p->aStmt) ); assert( eStmt<SizeofArray(azSql) && eStmt>=0 ); pStmt = p->aStmt[eStmt]; if( !pStmt ){ char *zSql; if( eStmt==SQL_CONTENT_INSERT ){ zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist); }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){ zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist); }else{ zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName); } if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL); sqlite3_free(zSql); assert( rc==SQLITE_OK || pStmt==0 ); p->aStmt[eStmt] = pStmt; } } if( apVal ){ int i; int nParam = sqlite3_bind_parameter_count(pStmt); for(i=0; rc==SQLITE_OK && i<nParam; i++){ rc = sqlite3_bind_value(pStmt, i+1, apVal[i]); } } *pp = pStmt; return rc; } static int fts3SelectDocsize( Fts3Table *pTab, /* FTS3 table handle */ sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */ sqlite3_stmt **ppStmt /* OUT: Statement handle */ ){ sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */ int rc; /* Return code */ rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, iDocid); rc = sqlite3_step(pStmt); if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){ rc = sqlite3_reset(pStmt); if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB; pStmt = 0; }else{ rc = SQLITE_OK; } } *ppStmt = pStmt; return rc; } SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal( Fts3Table *pTab, /* Fts3 table handle */ sqlite3_stmt **ppStmt /* OUT: Statement handle */ ){ sqlite3_stmt *pStmt = 0; int rc; rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); if( sqlite3_step(pStmt)!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){ rc = sqlite3_reset(pStmt); if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB; pStmt = 0; } } *ppStmt = pStmt; return rc; } SQLITE_PRIVATE int sqlite3Fts3SelectDocsize( Fts3Table *pTab, /* Fts3 table handle */ sqlite3_int64 iDocid, /* Docid to read size data for */ sqlite3_stmt **ppStmt /* OUT: Statement handle */ ){ return fts3SelectDocsize(pTab, iDocid, ppStmt); } /* ** Similar to fts3SqlStmt(). Except, after binding the parameters in ** array apVal[] to the SQL statement identified by eStmt, the statement ** is executed. ** ** Returns SQLITE_OK if the statement is successfully executed, or an ** SQLite error code otherwise. */ static void fts3SqlExec( int *pRC, /* Result code */ Fts3Table *p, /* The FTS3 table */ int eStmt, /* Index of statement to evaluate */ sqlite3_value **apVal /* Parameters to bind */ ){ sqlite3_stmt *pStmt; int rc; if( *pRC ) return; rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); if( rc==SQLITE_OK ){ sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); } *pRC = rc; } /* ** This function ensures that the caller has obtained an exclusive ** shared-cache table-lock on the %_segdir table. This is required before ** writing data to the fts3 table. If this lock is not acquired first, then ** the caller may end up attempting to take this lock as part of committing ** a transaction, causing SQLite to return SQLITE_LOCKED or ** LOCKED_SHAREDCACHEto a COMMIT command. ** ** It is best to avoid this because if FTS3 returns any error when ** committing a transaction, the whole transaction will be rolled back. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. ** It can still happen if the user locks the underlying tables directly ** instead of accessing them via FTS. */ static int fts3Writelock(Fts3Table *p){ int rc = SQLITE_OK; if( p->nPendingData==0 ){ sqlite3_stmt *pStmt; rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_null(pStmt, 1); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); } } return rc; } /* ** FTS maintains a separate indexes for each language-id (a 32-bit integer). ** Within each language id, a separate index is maintained to store the ** document terms, and each configured prefix size (configured the FTS ** "prefix=" option). And each index consists of multiple levels ("relative ** levels"). ** ** All three of these values (the language id, the specific index and the ** level within the index) are encoded in 64-bit integer values stored ** in the %_segdir table on disk. This function is used to convert three ** separate component values into the single 64-bit integer value that ** can be used to query the %_segdir table. ** ** Specifically, each language-id/index combination is allocated 1024 ** 64-bit integer level values ("absolute levels"). The main terms index ** for language-id 0 is allocate values 0-1023. The first prefix index ** (if any) for language-id 0 is allocated values 1024-2047. And so on. ** Language 1 indexes are allocated immediately following language 0. ** ** So, for a system with nPrefix prefix indexes configured, the block of ** absolute levels that corresponds to language-id iLangid and index ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024). */ static sqlite3_int64 getAbsoluteLevel( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language id */ int iIndex, /* Index in p->aIndex[] */ int iLevel /* Level of segments */ ){ sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */ assert( iLangid>=0 ); assert( p->nIndex>0 ); assert( iIndex>=0 && iIndex<p->nIndex ); iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL; return iBase + iLevel; } /* ** Set *ppStmt to a statement handle that may be used to iterate through ** all rows in the %_segdir table, from oldest to newest. If successful, ** return SQLITE_OK. If an error occurs while preparing the statement, ** return an SQLite error code. ** ** There is only ever one instance of this SQL statement compiled for ** each FTS3 table. ** ** The statement returns the following columns from the %_segdir table: ** ** 0: idx ** 1: start_block ** 2: leaves_end_block ** 3: end_block ** 4: root */ SQLITE_PRIVATE int sqlite3Fts3AllSegdirs( Fts3Table *p, /* FTS3 table */ int iLangid, /* Language being queried */ int iIndex, /* Index for p->aIndex[] */ int iLevel, /* Level to select (relative level) */ sqlite3_stmt **ppStmt /* OUT: Compiled statement */ ){ int rc; sqlite3_stmt *pStmt = 0; assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 ); assert( iLevel<FTS3_SEGDIR_MAXLEVEL ); assert( iIndex>=0 && iIndex<p->nIndex ); if( iLevel<0 ){ /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); sqlite3_bind_int64(pStmt, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); } }else{ /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel)); } } *ppStmt = pStmt; return rc; } /* ** Append a single varint to a PendingList buffer. SQLITE_OK is returned ** if successful, or an SQLite error code otherwise. ** ** This function also serves to allocate the PendingList structure itself. ** For example, to create a new PendingList structure containing two ** varints: ** ** PendingList *p = 0; ** fts3PendingListAppendVarint(&p, 1); ** fts3PendingListAppendVarint(&p, 2); */ static int fts3PendingListAppendVarint( PendingList **pp, /* IN/OUT: Pointer to PendingList struct */ sqlite3_int64 i /* Value to append to data */ ){ PendingList *p = *pp; /* Allocate or grow the PendingList as required. */ if( !p ){ p = sqlite3_malloc(sizeof(*p) + 100); if( !p ){ return SQLITE_NOMEM; } p->nSpace = 100; p->aData = (char *)&p[1]; p->nData = 0; } else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){ int nNew = p->nSpace * 2; p = sqlite3_realloc(p, sizeof(*p) + nNew); if( !p ){ sqlite3_free(*pp); *pp = 0; return SQLITE_NOMEM; } p->nSpace = nNew; p->aData = (char *)&p[1]; } /* Append the new serialized varint to the end of the list. */ p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i); p->aData[p->nData] = '\0'; *pp = p; return SQLITE_OK; } /* ** Add a docid/column/position entry to a PendingList structure. Non-zero ** is returned if the structure is sqlite3_realloced as part of adding ** the entry. Otherwise, zero. ** ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning. ** Zero is always returned in this case. Otherwise, if no OOM error occurs, ** it is set to SQLITE_OK. */ static int fts3PendingListAppend( PendingList **pp, /* IN/OUT: PendingList structure */ sqlite3_int64 iDocid, /* Docid for entry to add */ sqlite3_int64 iCol, /* Column for entry to add */ sqlite3_int64 iPos, /* Position of term for entry to add */ int *pRc /* OUT: Return code */ ){ PendingList *p = *pp; int rc = SQLITE_OK; assert( !p || p->iLastDocid<=iDocid ); if( !p || p->iLastDocid!=iDocid ){ sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0); if( p ){ assert( p->nData<p->nSpace ); assert( p->aData[p->nData]==0 ); p->nData++; } if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){ goto pendinglistappend_out; } p->iLastCol = -1; p->iLastPos = 0; p->iLastDocid = iDocid; } if( iCol>0 && p->iLastCol!=iCol ){ if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1)) || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol)) ){ goto pendinglistappend_out; } p->iLastCol = iCol; p->iLastPos = 0; } if( iCol>=0 ){ assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) ); rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos); if( rc==SQLITE_OK ){ p->iLastPos = iPos; } } pendinglistappend_out: *pRc = rc; if( p!=*pp ){ *pp = p; return 1; } return 0; } /* ** Free a PendingList object allocated by fts3PendingListAppend(). */ static void fts3PendingListDelete(PendingList *pList){ sqlite3_free(pList); } /* ** Add an entry to one of the pending-terms hash tables. */ static int fts3PendingTermsAddOne( Fts3Table *p, int iCol, int iPos, Fts3Hash *pHash, /* Pending terms hash table to add entry to */ const char *zToken, int nToken ){ PendingList *pList; int rc = SQLITE_OK; pList = (PendingList *)fts3HashFind(pHash, zToken, nToken); if( pList ){ p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem)); } if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){ if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){ /* Malloc failed while inserting the new entry. This can only ** happen if there was no previous entry for this token. */ assert( 0==fts3HashFind(pHash, zToken, nToken) ); sqlite3_free(pList); rc = SQLITE_NOMEM; } } if( rc==SQLITE_OK ){ p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem)); } return rc; } /* ** Tokenize the nul-terminated string zText and add all tokens to the ** pending-terms hash-table. The docid used is that currently stored in ** p->iPrevDocid, and the column is specified by argument iCol. ** ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. */ static int fts3PendingTermsAdd( Fts3Table *p, /* Table into which text will be inserted */ int iLangid, /* Language id to use */ const char *zText, /* Text of document to be inserted */ int iCol, /* Column into which text is being inserted */ u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */ ){ int rc; int iStart = 0; int iEnd = 0; int iPos = 0; int nWord = 0; char const *zToken; int nToken = 0; sqlite3_tokenizer *pTokenizer = p->pTokenizer; sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; sqlite3_tokenizer_cursor *pCsr; int (*xNext)(sqlite3_tokenizer_cursor *pCursor, const char**,int*,int*,int*,int*); assert( pTokenizer && pModule ); /* If the user has inserted a NULL value, this function may be called with ** zText==0. In this case, add zero token entries to the hash table and ** return early. */ if( zText==0 ){ *pnWord = 0; return SQLITE_OK; } rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr); if( rc!=SQLITE_OK ){ return rc; } xNext = pModule->xNext; while( SQLITE_OK==rc && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos)) ){ int i; if( iPos>=nWord ) nWord = iPos+1; /* Positions cannot be negative; we use -1 as a terminator internally. ** Tokens must have a non-zero length. */ if( iPos<0 || !zToken || nToken<=0 ){ rc = SQLITE_ERROR; break; } /* Add the term to the terms index */ rc = fts3PendingTermsAddOne( p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken ); /* Add the term to each of the prefix indexes that it is not too ** short for. */ for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){ struct Fts3Index *pIndex = &p->aIndex[i]; if( nToken<pIndex->nPrefix ) continue; rc = fts3PendingTermsAddOne( p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix ); } } pModule->xClose(pCsr); *pnWord += nWord; return (rc==SQLITE_DONE ? SQLITE_OK : rc); } /* ** Calling this function indicates that subsequent calls to ** fts3PendingTermsAdd() are to add term/position-list pairs for the ** contents of the document with docid iDocid. */ static int fts3PendingTermsDocid( Fts3Table *p, /* Full-text table handle */ int bDelete, /* True if this op is a delete */ int iLangid, /* Language id of row being written */ sqlite_int64 iDocid /* Docid of row being written */ ){ assert( iLangid>=0 ); assert( bDelete==1 || bDelete==0 ); /* TODO(shess) Explore whether partially flushing the buffer on ** forced-flush would provide better performance. I suspect that if ** we ordered the doclists by size and flushed the largest until the ** buffer was half empty, that would let the less frequent terms ** generate longer doclists. */ if( iDocid<p->iPrevDocid || (iDocid==p->iPrevDocid && p->bPrevDelete==0) || p->iPrevLangid!=iLangid || p->nPendingData>p->nMaxPendingData ){ int rc = sqlite3Fts3PendingTermsFlush(p); if( rc!=SQLITE_OK ) return rc; } p->iPrevDocid = iDocid; p->iPrevLangid = iLangid; p->bPrevDelete = bDelete; return SQLITE_OK; } /* ** Discard the contents of the pending-terms hash tables. */ SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){ int i; for(i=0; i<p->nIndex; i++){ Fts3HashElem *pElem; Fts3Hash *pHash = &p->aIndex[i].hPending; for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){ PendingList *pList = (PendingList *)fts3HashData(pElem); fts3PendingListDelete(pList); } fts3HashClear(pHash); } p->nPendingData = 0; } /* ** This function is called by the xUpdate() method as part of an INSERT ** operation. It adds entries for each term in the new record to the ** pendingTerms hash table. ** ** Argument apVal is the same as the similarly named argument passed to ** fts3InsertData(). Parameter iDocid is the docid of the new row. */ static int fts3InsertTerms( Fts3Table *p, int iLangid, sqlite3_value **apVal, u32 *aSz ){ int i; /* Iterator variable */ for(i=2; i<p->nColumn+2; i++){ int iCol = i-2; if( p->abNotindexed[iCol]==0 ){ const char *zText = (const char *)sqlite3_value_text(apVal[i]); int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]); if( rc!=SQLITE_OK ){ return rc; } aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]); } } return SQLITE_OK; } /* ** This function is called by the xUpdate() method for an INSERT operation. ** The apVal parameter is passed a copy of the apVal argument passed by ** SQLite to the xUpdate() method. i.e: ** ** apVal[0] Not used for INSERT. ** apVal[1] rowid ** apVal[2] Left-most user-defined column ** ... ** apVal[p->nColumn+1] Right-most user-defined column ** apVal[p->nColumn+2] Hidden column with same name as table ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid) ** apVal[p->nColumn+4] Hidden languageid column */ static int fts3InsertData( Fts3Table *p, /* Full-text table */ sqlite3_value **apVal, /* Array of values to insert */ sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */ ){ int rc; /* Return code */ sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */ if( p->zContentTbl ){ sqlite3_value *pRowid = apVal[p->nColumn+3]; if( sqlite3_value_type(pRowid)==SQLITE_NULL ){ pRowid = apVal[1]; } if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){ return SQLITE_CONSTRAINT; } *piDocid = sqlite3_value_int64(pRowid); return SQLITE_OK; } /* Locate the statement handle used to insert data into the %_content ** table. The SQL for this statement is: ** ** INSERT INTO %_content VALUES(?, ?, ?, ...) ** ** The statement features N '?' variables, where N is the number of user ** defined columns in the FTS3 table, plus one for the docid field. */ rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]); if( rc==SQLITE_OK && p->zLanguageid ){ rc = sqlite3_bind_int( pContentInsert, p->nColumn+2, sqlite3_value_int(apVal[p->nColumn+4]) ); } if( rc!=SQLITE_OK ) return rc; /* There is a quirk here. The users INSERT statement may have specified ** a value for the "rowid" field, for the "docid" field, or for both. ** Which is a problem, since "rowid" and "docid" are aliases for the ** same value. For example: ** ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2); ** ** In FTS3, this is an error. It is an error to specify non-NULL values ** for both docid and some other rowid alias. */ if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){ if( SQLITE_NULL==sqlite3_value_type(apVal[0]) && SQLITE_NULL!=sqlite3_value_type(apVal[1]) ){ /* A rowid/docid conflict. */ return SQLITE_ERROR; } rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]); if( rc!=SQLITE_OK ) return rc; } /* Execute the statement to insert the record. Set *piDocid to the ** new docid value. */ sqlite3_step(pContentInsert); rc = sqlite3_reset(pContentInsert); *piDocid = sqlite3_last_insert_rowid(p->db); return rc; } /* ** Remove all data from the FTS3 table. Clear the hash table containing ** pending terms. */ static int fts3DeleteAll(Fts3Table *p, int bContent){ int rc = SQLITE_OK; /* Return code */ /* Discard the contents of the pending-terms hash table. */ sqlite3Fts3PendingTermsClear(p); /* Delete everything from the shadow tables. Except, leave %_content as ** is if bContent is false. */ assert( p->zContentTbl==0 || bContent==0 ); if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0); fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0); fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0); if( p->bHasDocsize ){ fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0); } if( p->bHasStat ){ fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0); } return rc; } /* ** */ static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){ int iLangid = 0; if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1); return iLangid; } /* ** The first element in the apVal[] array is assumed to contain the docid ** (an integer) of a row about to be deleted. Remove all terms from the ** full-text index. */ static void fts3DeleteTerms( int *pRC, /* Result code */ Fts3Table *p, /* The FTS table to delete from */ sqlite3_value *pRowid, /* The docid to be deleted */ u32 *aSz, /* Sizes of deleted document written here */ int *pbFound /* OUT: Set to true if row really does exist */ ){ int rc; sqlite3_stmt *pSelect; assert( *pbFound==0 ); if( *pRC ) return; rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pSelect) ){ int i; int iLangid = langidFromSelect(p, pSelect); i64 iDocid = sqlite3_column_int64(pSelect, 0); rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid); for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){ int iCol = i-1; if( p->abNotindexed[iCol]==0 ){ const char *zText = (const char *)sqlite3_column_text(pSelect, i); rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]); aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i); } } if( rc!=SQLITE_OK ){ sqlite3_reset(pSelect); *pRC = rc; return; } *pbFound = 1; } rc = sqlite3_reset(pSelect); }else{ sqlite3_reset(pSelect); } *pRC = rc; } /* ** Forward declaration to account for the circular dependency between ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx(). */ static int fts3SegmentMerge(Fts3Table *, int, int, int); /* ** This function allocates a new level iLevel index in the segdir table. ** Usually, indexes are allocated within a level sequentially starting ** with 0, so the allocated index is one greater than the value returned ** by: ** ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel ** ** However, if there are already FTS3_MERGE_COUNT indexes at the requested ** level, they are merged into a single level (iLevel+1) segment and the ** allocated index is 0. ** ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK ** returned. Otherwise, an SQLite error code is returned. */ static int fts3AllocateSegdirIdx( Fts3Table *p, int iLangid, /* Language id */ int iIndex, /* Index for p->aIndex */ int iLevel, int *piIdx ){ int rc; /* Return Code */ sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */ int iNext = 0; /* Result of query pNextIdx */ assert( iLangid>=0 ); assert( p->nIndex>=1 ); /* Set variable iNext to the next available segdir index at level iLevel. */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64( pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) ); if( SQLITE_ROW==sqlite3_step(pNextIdx) ){ iNext = sqlite3_column_int(pNextIdx, 0); } rc = sqlite3_reset(pNextIdx); } if( rc==SQLITE_OK ){ /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already ** full, merge all segments in level iLevel into a single iLevel+1 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise, ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext. */ if( iNext>=FTS3_MERGE_COUNT ){ fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel)); rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel); *piIdx = 0; }else{ *piIdx = iNext; } } return rc; } /* ** The %_segments table is declared as follows: ** ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB) ** ** This function reads data from a single row of the %_segments table. The ** specific row is identified by the iBlockid parameter. If paBlob is not ** NULL, then a buffer is allocated using sqlite3_malloc() and populated ** with the contents of the blob stored in the "block" column of the ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set ** to the size of the blob in bytes before returning. ** ** If an error occurs, or the table does not contain the specified row, ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If ** paBlob is non-NULL, then it is the responsibility of the caller to ** eventually free the returned buffer. ** ** This function may leave an open sqlite3_blob* handle in the ** Fts3Table.pSegments variable. This handle is reused by subsequent calls ** to this function. The handle may be closed by calling the ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy ** performance improvement, but the blob handle should always be closed ** before control is returned to the user (to prevent a lock being held ** on the database file for longer than necessary). Thus, any virtual table ** method (xFilter etc.) that may directly or indirectly call this function ** must call sqlite3Fts3SegmentsClose() before returning. */ SQLITE_PRIVATE int sqlite3Fts3ReadBlock( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */ char **paBlob, /* OUT: Blob data in malloc'd buffer */ int *pnBlob, /* OUT: Size of blob data */ int *pnLoad /* OUT: Bytes actually loaded */ ){ int rc; /* Return code */ /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */ assert( pnBlob ); if( p->pSegments ){ rc = sqlite3_blob_reopen(p->pSegments, iBlockid); }else{ if( 0==p->zSegmentsTbl ){ p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName); if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM; } rc = sqlite3_blob_open( p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments ); } if( rc==SQLITE_OK ){ int nByte = sqlite3_blob_bytes(p->pSegments); *pnBlob = nByte; if( paBlob ){ char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING); if( !aByte ){ rc = SQLITE_NOMEM; }else{ if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){ nByte = FTS3_NODE_CHUNKSIZE; *pnLoad = nByte; } rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0); memset(&aByte[nByte], 0, FTS3_NODE_PADDING); if( rc!=SQLITE_OK ){ sqlite3_free(aByte); aByte = 0; } } *paBlob = aByte; } } return rc; } /* ** Close the blob handle at p->pSegments, if it is open. See comments above ** the sqlite3Fts3ReadBlock() function for details. */ SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){ sqlite3_blob_close(p->pSegments); p->pSegments = 0; } static int fts3SegReaderIncrRead(Fts3SegReader *pReader){ int nRead; /* Number of bytes to read */ int rc; /* Return code */ nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE); rc = sqlite3_blob_read( pReader->pBlob, &pReader->aNode[pReader->nPopulate], nRead, pReader->nPopulate ); if( rc==SQLITE_OK ){ pReader->nPopulate += nRead; memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING); if( pReader->nPopulate==pReader->nNode ){ sqlite3_blob_close(pReader->pBlob); pReader->pBlob = 0; pReader->nPopulate = 0; } } return rc; } static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){ int rc = SQLITE_OK; assert( !pReader->pBlob || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode]) ); while( pReader->pBlob && rc==SQLITE_OK && (pFrom - pReader->aNode + nByte)>pReader->nPopulate ){ rc = fts3SegReaderIncrRead(pReader); } return rc; } /* ** Set an Fts3SegReader cursor to point at EOF. */ static void fts3SegReaderSetEof(Fts3SegReader *pSeg){ if( !fts3SegReaderIsRootOnly(pSeg) ){ sqlite3_free(pSeg->aNode); sqlite3_blob_close(pSeg->pBlob); pSeg->pBlob = 0; } pSeg->aNode = 0; } /* ** Move the iterator passed as the first argument to the next term in the ** segment. If successful, SQLITE_OK is returned. If there is no next term, ** SQLITE_DONE. Otherwise, an SQLite error code. */ static int fts3SegReaderNext( Fts3Table *p, Fts3SegReader *pReader, int bIncr ){ int rc; /* Return code of various sub-routines */ char *pNext; /* Cursor variable */ int nPrefix; /* Number of bytes in term prefix */ int nSuffix; /* Number of bytes in term suffix */ if( !pReader->aDoclist ){ pNext = pReader->aNode; }else{ pNext = &pReader->aDoclist[pReader->nDoclist]; } if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){ if( fts3SegReaderIsPending(pReader) ){ Fts3HashElem *pElem = *(pReader->ppNextElem); sqlite3_free(pReader->aNode); pReader->aNode = 0; if( pElem ){ char *aCopy; PendingList *pList = (PendingList *)fts3HashData(pElem); int nCopy = pList->nData+1; pReader->zTerm = (char *)fts3HashKey(pElem); pReader->nTerm = fts3HashKeysize(pElem); aCopy = (char*)sqlite3_malloc(nCopy); if( !aCopy ) return SQLITE_NOMEM; memcpy(aCopy, pList->aData, nCopy); pReader->nNode = pReader->nDoclist = nCopy; pReader->aNode = pReader->aDoclist = aCopy; pReader->ppNextElem++; assert( pReader->aNode ); } return SQLITE_OK; } fts3SegReaderSetEof(pReader); /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf ** blocks have already been traversed. */ assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock ); if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){ return SQLITE_OK; } rc = sqlite3Fts3ReadBlock( p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, (bIncr ? &pReader->nPopulate : 0) ); if( rc!=SQLITE_OK ) return rc; assert( pReader->pBlob==0 ); if( bIncr && pReader->nPopulate<pReader->nNode ){ pReader->pBlob = p->pSegments; p->pSegments = 0; } pNext = pReader->aNode; } assert( !fts3SegReaderIsPending(pReader) ); rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2); if( rc!=SQLITE_OK ) return rc; /* Because of the FTS3_NODE_PADDING bytes of padding, the following is ** safe (no risk of overread) even if the node data is corrupted. */ pNext += fts3GetVarint32(pNext, &nPrefix); pNext += fts3GetVarint32(pNext, &nSuffix); if( nPrefix<0 || nSuffix<=0 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] ){ return FTS_CORRUPT_VTAB; } if( nPrefix+nSuffix>pReader->nTermAlloc ){ int nNew = (nPrefix+nSuffix)*2; char *zNew = sqlite3_realloc(pReader->zTerm, nNew); if( !zNew ){ return SQLITE_NOMEM; } pReader->zTerm = zNew; pReader->nTermAlloc = nNew; } rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX); if( rc!=SQLITE_OK ) return rc; memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix); pReader->nTerm = nPrefix+nSuffix; pNext += nSuffix; pNext += fts3GetVarint32(pNext, &pReader->nDoclist); pReader->aDoclist = pNext; pReader->pOffsetList = 0; /* Check that the doclist does not appear to extend past the end of the ** b-tree node. And that the final byte of the doclist is 0x00. If either ** of these statements is untrue, then the data structure is corrupt. */ if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1]) ){ return FTS_CORRUPT_VTAB; } return SQLITE_OK; } /* ** Set the SegReader to point to the first docid in the doclist associated ** with the current term. */ static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){ int rc = SQLITE_OK; assert( pReader->aDoclist ); assert( !pReader->pOffsetList ); if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ u8 bEof = 0; pReader->iDocid = 0; pReader->nOffsetList = 0; sqlite3Fts3DoclistPrev(0, pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, &pReader->iDocid, &pReader->nOffsetList, &bEof ); }else{ rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX); if( rc==SQLITE_OK ){ int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid); pReader->pOffsetList = &pReader->aDoclist[n]; } } return rc; } /* ** Advance the SegReader to point to the next docid in the doclist ** associated with the current term. ** ** If arguments ppOffsetList and pnOffsetList are not NULL, then ** *ppOffsetList is set to point to the first column-offset list ** in the doclist entry (i.e. immediately past the docid varint). ** *pnOffsetList is set to the length of the set of column-offset ** lists, not including the nul-terminator byte. For example: */ static int fts3SegReaderNextDocid( Fts3Table *pTab, Fts3SegReader *pReader, /* Reader to advance to next docid */ char **ppOffsetList, /* OUT: Pointer to current position-list */ int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */ ){ int rc = SQLITE_OK; char *p = pReader->pOffsetList; char c = 0; assert( p ); if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ /* A pending-terms seg-reader for an FTS4 table that uses order=desc. ** Pending-terms doclists are always built up in ascending order, so ** we have to iterate through them backwards here. */ u8 bEof = 0; if( ppOffsetList ){ *ppOffsetList = pReader->pOffsetList; *pnOffsetList = pReader->nOffsetList - 1; } sqlite3Fts3DoclistPrev(0, pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid, &pReader->nOffsetList, &bEof ); if( bEof ){ pReader->pOffsetList = 0; }else{ pReader->pOffsetList = p; } }else{ char *pEnd = &pReader->aDoclist[pReader->nDoclist]; /* Pointer p currently points at the first byte of an offset list. The ** following block advances it to point one byte past the end of ** the same offset list. */ while( 1 ){ /* The following line of code (and the "p++" below the while() loop) is ** normally all that is required to move pointer p to the desired ** position. The exception is if this node is being loaded from disk ** incrementally and pointer "p" now points to the first byte past ** the populated part of pReader->aNode[]. */ while( *p | c ) c = *p++ & 0x80; assert( *p==0 ); if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break; rc = fts3SegReaderIncrRead(pReader); if( rc!=SQLITE_OK ) return rc; } p++; /* If required, populate the output variables with a pointer to and the ** size of the previous offset-list. */ if( ppOffsetList ){ *ppOffsetList = pReader->pOffsetList; *pnOffsetList = (int)(p - pReader->pOffsetList - 1); } /* List may have been edited in place by fts3EvalNearTrim() */ while( p<pEnd && *p==0 ) p++; /* If there are no more entries in the doclist, set pOffsetList to ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and ** Fts3SegReader.pOffsetList to point to the next offset list before ** returning. */ if( p>=pEnd ){ pReader->pOffsetList = 0; }else{ rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX); if( rc==SQLITE_OK ){ sqlite3_int64 iDelta; pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta); if( pTab->bDescIdx ){ pReader->iDocid -= iDelta; }else{ pReader->iDocid += iDelta; } } } } return SQLITE_OK; } SQLITE_PRIVATE int sqlite3Fts3MsrOvfl( Fts3Cursor *pCsr, Fts3MultiSegReader *pMsr, int *pnOvfl ){ Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; int nOvfl = 0; int ii; int rc = SQLITE_OK; int pgsz = p->nPgsz; assert( p->bFts4 ); assert( pgsz>0 ); for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){ Fts3SegReader *pReader = pMsr->apSegment[ii]; if( !fts3SegReaderIsPending(pReader) && !fts3SegReaderIsRootOnly(pReader) ){ sqlite3_int64 jj; for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){ int nBlob; rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0); if( rc!=SQLITE_OK ) break; if( (nBlob+35)>pgsz ){ nOvfl += (nBlob + 34)/pgsz; } } } } *pnOvfl = nOvfl; return rc; } /* ** Free all allocations associated with the iterator passed as the ** second argument. */ SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){ if( pReader ){ if( !fts3SegReaderIsPending(pReader) ){ sqlite3_free(pReader->zTerm); } if( !fts3SegReaderIsRootOnly(pReader) ){ sqlite3_free(pReader->aNode); } sqlite3_blob_close(pReader->pBlob); } sqlite3_free(pReader); } /* ** Allocate a new SegReader object. */ SQLITE_PRIVATE int sqlite3Fts3SegReaderNew( int iAge, /* Segment "age". */ int bLookup, /* True for a lookup only */ sqlite3_int64 iStartLeaf, /* First leaf to traverse */ sqlite3_int64 iEndLeaf, /* Final leaf to traverse */ sqlite3_int64 iEndBlock, /* Final block of segment */ const char *zRoot, /* Buffer containing root node */ int nRoot, /* Size of buffer containing root node */ Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */ ){ Fts3SegReader *pReader; /* Newly allocated SegReader object */ int nExtra = 0; /* Bytes to allocate segment root node */ assert( iStartLeaf<=iEndLeaf ); if( iStartLeaf==0 ){ nExtra = nRoot + FTS3_NODE_PADDING; } pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra); if( !pReader ){ return SQLITE_NOMEM; } memset(pReader, 0, sizeof(Fts3SegReader)); pReader->iIdx = iAge; pReader->bLookup = bLookup!=0; pReader->iStartBlock = iStartLeaf; pReader->iLeafEndBlock = iEndLeaf; pReader->iEndBlock = iEndBlock; if( nExtra ){ /* The entire segment is stored in the root node. */ pReader->aNode = (char *)&pReader[1]; pReader->rootOnly = 1; pReader->nNode = nRoot; memcpy(pReader->aNode, zRoot, nRoot); memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING); }else{ pReader->iCurrentBlock = iStartLeaf-1; } *ppReader = pReader; return SQLITE_OK; } /* ** This is a comparison function used as a qsort() callback when sorting ** an array of pending terms by term. This occurs as part of flushing ** the contents of the pending-terms hash table to the database. */ static int SQLITE_CDECL fts3CompareElemByTerm( const void *lhs, const void *rhs ){ char *z1 = fts3HashKey(*(Fts3HashElem **)lhs); char *z2 = fts3HashKey(*(Fts3HashElem **)rhs); int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs); int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs); int n = (n1<n2 ? n1 : n2); int c = memcmp(z1, z2, n); if( c==0 ){ c = n1 - n2; } return c; } /* ** This function is used to allocate an Fts3SegReader that iterates through ** a subset of the terms stored in the Fts3Table.pendingTerms array. ** ** If the isPrefixIter parameter is zero, then the returned SegReader iterates ** through each term in the pending-terms table. Or, if isPrefixIter is ** non-zero, it iterates through each term and its prefixes. For example, if ** the pending terms hash table contains the terms "sqlite", "mysql" and ** "firebird", then the iterator visits the following 'terms' (in the order ** shown): ** ** f fi fir fire fireb firebi firebir firebird ** m my mys mysq mysql ** s sq sql sqli sqlit sqlite ** ** Whereas if isPrefixIter is zero, the terms visited are: ** ** firebird mysql sqlite */ SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( Fts3Table *p, /* Virtual table handle */ int iIndex, /* Index for p->aIndex */ const char *zTerm, /* Term to search for */ int nTerm, /* Size of buffer zTerm */ int bPrefix, /* True for a prefix iterator */ Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */ ){ Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */ Fts3HashElem *pE; /* Iterator variable */ Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */ int nElem = 0; /* Size of array at aElem */ int rc = SQLITE_OK; /* Return Code */ Fts3Hash *pHash; pHash = &p->aIndex[iIndex].hPending; if( bPrefix ){ int nAlloc = 0; /* Size of allocated array at aElem */ for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){ char *zKey = (char *)fts3HashKey(pE); int nKey = fts3HashKeysize(pE); if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){ if( nElem==nAlloc ){ Fts3HashElem **aElem2; nAlloc += 16; aElem2 = (Fts3HashElem **)sqlite3_realloc( aElem, nAlloc*sizeof(Fts3HashElem *) ); if( !aElem2 ){ rc = SQLITE_NOMEM; nElem = 0; break; } aElem = aElem2; } aElem[nElem++] = pE; } } /* If more than one term matches the prefix, sort the Fts3HashElem ** objects in term order using qsort(). This uses the same comparison ** callback as is used when flushing terms to disk. */ if( nElem>1 ){ qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm); } }else{ /* The query is a simple term lookup that matches at most one term in ** the index. All that is required is a straight hash-lookup. ** ** Because the stack address of pE may be accessed via the aElem pointer ** below, the "Fts3HashElem *pE" must be declared so that it is valid ** within this entire function, not just this "else{...}" block. */ pE = fts3HashFindElem(pHash, zTerm, nTerm); if( pE ){ aElem = &pE; nElem = 1; } } if( nElem>0 ){ int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); pReader = (Fts3SegReader *)sqlite3_malloc(nByte); if( !pReader ){ rc = SQLITE_NOMEM; }else{ memset(pReader, 0, nByte); pReader->iIdx = 0x7FFFFFFF; pReader->ppNextElem = (Fts3HashElem **)&pReader[1]; memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *)); } } if( bPrefix ){ sqlite3_free(aElem); } *ppReader = pReader; return rc; } /* ** Compare the entries pointed to by two Fts3SegReader structures. ** Comparison is as follows: ** ** 1) EOF is greater than not EOF. ** ** 2) The current terms (if any) are compared using memcmp(). If one ** term is a prefix of another, the longer term is considered the ** larger. ** ** 3) By segment age. An older segment is considered larger. */ static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ int rc; if( pLhs->aNode && pRhs->aNode ){ int rc2 = pLhs->nTerm - pRhs->nTerm; if( rc2<0 ){ rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm); }else{ rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm); } if( rc==0 ){ rc = rc2; } }else{ rc = (pLhs->aNode==0) - (pRhs->aNode==0); } if( rc==0 ){ rc = pRhs->iIdx - pLhs->iIdx; } assert( rc!=0 ); return rc; } /* ** A different comparison function for SegReader structures. In this ** version, it is assumed that each SegReader points to an entry in ** a doclist for identical terms. Comparison is made as follows: ** ** 1) EOF (end of doclist in this case) is greater than not EOF. ** ** 2) By current docid. ** ** 3) By segment age. An older segment is considered larger. */ static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); if( rc==0 ){ if( pLhs->iDocid==pRhs->iDocid ){ rc = pRhs->iIdx - pLhs->iIdx; }else{ rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1; } } assert( pLhs->aNode && pRhs->aNode ); return rc; } static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); if( rc==0 ){ if( pLhs->iDocid==pRhs->iDocid ){ rc = pRhs->iIdx - pLhs->iIdx; }else{ rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1; } } assert( pLhs->aNode && pRhs->aNode ); return rc; } /* ** Compare the term that the Fts3SegReader object passed as the first argument ** points to with the term specified by arguments zTerm and nTerm. ** ** If the pSeg iterator is already at EOF, return 0. Otherwise, return ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are ** equal, or +ve if the pSeg term is greater than zTerm/nTerm. */ static int fts3SegReaderTermCmp( Fts3SegReader *pSeg, /* Segment reader object */ const char *zTerm, /* Term to compare to */ int nTerm /* Size of term zTerm in bytes */ ){ int res = 0; if( pSeg->aNode ){ if( pSeg->nTerm>nTerm ){ res = memcmp(pSeg->zTerm, zTerm, nTerm); }else{ res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm); } if( res==0 ){ res = pSeg->nTerm-nTerm; } } return res; } /* ** Argument apSegment is an array of nSegment elements. It is known that ** the final (nSegment-nSuspect) members are already in sorted order ** (according to the comparison function provided). This function shuffles ** the array around until all entries are in sorted order. */ static void fts3SegReaderSort( Fts3SegReader **apSegment, /* Array to sort entries of */ int nSegment, /* Size of apSegment array */ int nSuspect, /* Unsorted entry count */ int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */ ){ int i; /* Iterator variable */ assert( nSuspect<=nSegment ); if( nSuspect==nSegment ) nSuspect--; for(i=nSuspect-1; i>=0; i--){ int j; for(j=i; j<(nSegment-1); j++){ Fts3SegReader *pTmp; if( xCmp(apSegment[j], apSegment[j+1])<0 ) break; pTmp = apSegment[j+1]; apSegment[j+1] = apSegment[j]; apSegment[j] = pTmp; } } #ifndef NDEBUG /* Check that the list really is sorted now. */ for(i=0; i<(nSuspect-1); i++){ assert( xCmp(apSegment[i], apSegment[i+1])<0 ); } #endif } /* ** Insert a record into the %_segments table. */ static int fts3WriteSegment( Fts3Table *p, /* Virtual table handle */ sqlite3_int64 iBlock, /* Block id for new block */ char *z, /* Pointer to buffer containing block data */ int n /* Size of buffer z in bytes */ ){ sqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, iBlock); sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); } return rc; } /* ** Find the largest relative level number in the table. If successful, set ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs, ** set *pnMax to zero and return an SQLite error code. */ SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){ int rc; int mxLevel = 0; sqlite3_stmt *pStmt = 0; rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pStmt) ){ mxLevel = sqlite3_column_int(pStmt, 0); } rc = sqlite3_reset(pStmt); } *pnMax = mxLevel; return rc; } /* ** Insert a record into the %_segdir table. */ static int fts3WriteSegdir( Fts3Table *p, /* Virtual table handle */ sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */ int iIdx, /* Value for "idx" field */ sqlite3_int64 iStartBlock, /* Value for "start_block" field */ sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */ sqlite3_int64 iEndBlock, /* Value for "end_block" field */ sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */ char *zRoot, /* Blob value for "root" field */ int nRoot /* Number of bytes in buffer zRoot */ ){ sqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pStmt, 1, iLevel); sqlite3_bind_int(pStmt, 2, iIdx); sqlite3_bind_int64(pStmt, 3, iStartBlock); sqlite3_bind_int64(pStmt, 4, iLeafEndBlock); if( nLeafData==0 ){ sqlite3_bind_int64(pStmt, 5, iEndBlock); }else{ char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData); if( !zEnd ) return SQLITE_NOMEM; sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free); } sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); } return rc; } /* ** Return the size of the common prefix (if any) shared by zPrev and ** zNext, in bytes. For example, ** ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0 */ static int fts3PrefixCompress( const char *zPrev, /* Buffer containing previous term */ int nPrev, /* Size of buffer zPrev in bytes */ const char *zNext, /* Buffer containing next term */ int nNext /* Size of buffer zNext in bytes */ ){ int n; UNUSED_PARAMETER(nNext); for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++); return n; } /* ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger ** (according to memcmp) than the previous term. */ static int fts3NodeAddTerm( Fts3Table *p, /* Virtual table handle */ SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */ int isCopyTerm, /* True if zTerm/nTerm is transient */ const char *zTerm, /* Pointer to buffer containing term */ int nTerm /* Size of term in bytes */ ){ SegmentNode *pTree = *ppTree; int rc; SegmentNode *pNew; /* First try to append the term to the current node. Return early if ** this is possible. */ if( pTree ){ int nData = pTree->nData; /* Current size of node in bytes */ int nReq = nData; /* Required space after adding zTerm */ int nPrefix; /* Number of bytes of prefix compression */ int nSuffix; /* Suffix length */ nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm); nSuffix = nTerm-nPrefix; nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix; if( nReq<=p->nNodeSize || !pTree->zTerm ){ if( nReq>p->nNodeSize ){ /* An unusual case: this is the first term to be added to the node ** and the static node buffer (p->nNodeSize bytes) is not large ** enough. Use a separately malloced buffer instead This wastes ** p->nNodeSize bytes, but since this scenario only comes about when ** the database contain two terms that share a prefix of almost 2KB, ** this is not expected to be a serious problem. */ assert( pTree->aData==(char *)&pTree[1] ); pTree->aData = (char *)sqlite3_malloc(nReq); if( !pTree->aData ){ return SQLITE_NOMEM; } } if( pTree->zTerm ){ /* There is no prefix-length field for first term in a node */ nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix); } nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix); memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix); pTree->nData = nData + nSuffix; pTree->nEntry++; if( isCopyTerm ){ if( pTree->nMalloc<nTerm ){ char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2); if( !zNew ){ return SQLITE_NOMEM; } pTree->nMalloc = nTerm*2; pTree->zMalloc = zNew; } pTree->zTerm = pTree->zMalloc; memcpy(pTree->zTerm, zTerm, nTerm); pTree->nTerm = nTerm; }else{ pTree->zTerm = (char *)zTerm; pTree->nTerm = nTerm; } return SQLITE_OK; } } /* If control flows to here, it was not possible to append zTerm to the ** current node. Create a new node (a right-sibling of the current node). ** If this is the first node in the tree, the term is added to it. ** ** Otherwise, the term is not added to the new node, it is left empty for ** now. Instead, the term is inserted into the parent of pTree. If pTree ** has no parent, one is created here. */ pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize); if( !pNew ){ return SQLITE_NOMEM; } memset(pNew, 0, sizeof(SegmentNode)); pNew->nData = 1 + FTS3_VARINT_MAX; pNew->aData = (char *)&pNew[1]; if( pTree ){ SegmentNode *pParent = pTree->pParent; rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm); if( pTree->pParent==0 ){ pTree->pParent = pParent; } pTree->pRight = pNew; pNew->pLeftmost = pTree->pLeftmost; pNew->pParent = pParent; pNew->zMalloc = pTree->zMalloc; pNew->nMalloc = pTree->nMalloc; pTree->zMalloc = 0; }else{ pNew->pLeftmost = pNew; rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); } *ppTree = pNew; return rc; } /* ** Helper function for fts3NodeWrite(). */ static int fts3TreeFinishNode( SegmentNode *pTree, int iHeight, sqlite3_int64 iLeftChild ){ int nStart; assert( iHeight>=1 && iHeight<128 ); nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild); pTree->aData[nStart] = (char)iHeight; sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild); return nStart; } /* ** Write the buffer for the segment node pTree and all of its peers to the ** database. Then call this function recursively to write the parent of ** pTree and its peers to the database. ** ** Except, if pTree is a root node, do not write it to the database. Instead, ** set output variables *paRoot and *pnRoot to contain the root node. ** ** If successful, SQLITE_OK is returned and output variable *piLast is ** set to the largest blockid written to the database (or zero if no ** blocks were written to the db). Otherwise, an SQLite error code is ** returned. */ static int fts3NodeWrite( Fts3Table *p, /* Virtual table handle */ SegmentNode *pTree, /* SegmentNode handle */ int iHeight, /* Height of this node in tree */ sqlite3_int64 iLeaf, /* Block id of first leaf node */ sqlite3_int64 iFree, /* Block id of next free slot in %_segments */ sqlite3_int64 *piLast, /* OUT: Block id of last entry written */ char **paRoot, /* OUT: Data for root node */ int *pnRoot /* OUT: Size of root node in bytes */ ){ int rc = SQLITE_OK; if( !pTree->pParent ){ /* Root node of the tree. */ int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf); *piLast = iFree-1; *pnRoot = pTree->nData - nStart; *paRoot = &pTree->aData[nStart]; }else{ SegmentNode *pIter; sqlite3_int64 iNextFree = iFree; sqlite3_int64 iNextLeaf = iLeaf; for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){ int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf); int nWrite = pIter->nData - nStart; rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite); iNextFree++; iNextLeaf += (pIter->nEntry+1); } if( rc==SQLITE_OK ){ assert( iNextLeaf==iFree ); rc = fts3NodeWrite( p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot ); } } return rc; } /* ** Free all memory allocations associated with the tree pTree. */ static void fts3NodeFree(SegmentNode *pTree){ if( pTree ){ SegmentNode *p = pTree->pLeftmost; fts3NodeFree(p->pParent); while( p ){ SegmentNode *pRight = p->pRight; if( p->aData!=(char *)&p[1] ){ sqlite3_free(p->aData); } assert( pRight==0 || p->zMalloc==0 ); sqlite3_free(p->zMalloc); sqlite3_free(p); p = pRight; } } } /* ** Add a term to the segment being constructed by the SegmentWriter object ** *ppWriter. When adding the first term to a segment, *ppWriter should ** be passed NULL. This function will allocate a new SegmentWriter object ** and return it via the input/output variable *ppWriter in this case. ** ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. */ static int fts3SegWriterAdd( Fts3Table *p, /* Virtual table handle */ SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */ int isCopyTerm, /* True if buffer zTerm must be copied */ const char *zTerm, /* Pointer to buffer containing term */ int nTerm, /* Size of term in bytes */ const char *aDoclist, /* Pointer to buffer containing doclist */ int nDoclist /* Size of doclist in bytes */ ){ int nPrefix; /* Size of term prefix in bytes */ int nSuffix; /* Size of term suffix in bytes */ int nReq; /* Number of bytes required on leaf page */ int nData; SegmentWriter *pWriter = *ppWriter; if( !pWriter ){ int rc; sqlite3_stmt *pStmt; /* Allocate the SegmentWriter structure */ pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter)); if( !pWriter ) return SQLITE_NOMEM; memset(pWriter, 0, sizeof(SegmentWriter)); *ppWriter = pWriter; /* Allocate a buffer in which to accumulate data */ pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize); if( !pWriter->aData ) return SQLITE_NOMEM; pWriter->nSize = p->nNodeSize; /* Find the next free blockid in the %_segments table */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; if( SQLITE_ROW==sqlite3_step(pStmt) ){ pWriter->iFree = sqlite3_column_int64(pStmt, 0); pWriter->iFirst = pWriter->iFree; } rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ) return rc; } nData = pWriter->nData; nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm); nSuffix = nTerm-nPrefix; /* Figure out how many bytes are required by this new entry */ nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */ sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */ nSuffix + /* Term suffix */ sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ nDoclist; /* Doclist data */ if( nData>0 && nData+nReq>p->nNodeSize ){ int rc; /* The current leaf node is full. Write it out to the database. */ rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData); if( rc!=SQLITE_OK ) return rc; p->nLeafAdd++; /* Add the current term to the interior node tree. The term added to ** the interior tree must: ** ** a) be greater than the largest term on the leaf node just written ** to the database (still available in pWriter->zTerm), and ** ** b) be less than or equal to the term about to be added to the new ** leaf node (zTerm/nTerm). ** ** In other words, it must be the prefix of zTerm 1 byte longer than ** the common prefix (if any) of zTerm and pWriter->zTerm. */ assert( nPrefix<nTerm ); rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1); if( rc!=SQLITE_OK ) return rc; nData = 0; pWriter->nTerm = 0; nPrefix = 0; nSuffix = nTerm; nReq = 1 + /* varint containing prefix size */ sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */ nTerm + /* Term suffix */ sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ nDoclist; /* Doclist data */ } /* Increase the total number of bytes written to account for the new entry. */ pWriter->nLeafData += nReq; /* If the buffer currently allocated is too small for this entry, realloc ** the buffer to make it large enough. */ if( nReq>pWriter->nSize ){ char *aNew = sqlite3_realloc(pWriter->aData, nReq); if( !aNew ) return SQLITE_NOMEM; pWriter->aData = aNew; pWriter->nSize = nReq; } assert( nData+nReq<=pWriter->nSize ); /* Append the prefix-compressed term and doclist to the buffer. */ nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); nData += nSuffix; nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); memcpy(&pWriter->aData[nData], aDoclist, nDoclist); pWriter->nData = nData + nDoclist; /* Save the current term so that it can be used to prefix-compress the next. ** If the isCopyTerm parameter is true, then the buffer pointed to by ** zTerm is transient, so take a copy of the term data. Otherwise, just ** store a copy of the pointer. */ if( isCopyTerm ){ if( nTerm>pWriter->nMalloc ){ char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2); if( !zNew ){ return SQLITE_NOMEM; } pWriter->nMalloc = nTerm*2; pWriter->zMalloc = zNew; pWriter->zTerm = zNew; } assert( pWriter->zTerm==pWriter->zMalloc ); memcpy(pWriter->zTerm, zTerm, nTerm); }else{ pWriter->zTerm = (char *)zTerm; } pWriter->nTerm = nTerm; return SQLITE_OK; } /* ** Flush all data associated with the SegmentWriter object pWriter to the ** database. This function must be called after all terms have been added ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is ** returned. Otherwise, an SQLite error code. */ static int fts3SegWriterFlush( Fts3Table *p, /* Virtual table handle */ SegmentWriter *pWriter, /* SegmentWriter to flush to the db */ sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */ int iIdx /* Value for 'idx' column of %_segdir */ ){ int rc; /* Return code */ if( pWriter->pTree ){ sqlite3_int64 iLast = 0; /* Largest block id written to database */ sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */ char *zRoot = NULL; /* Pointer to buffer containing root node */ int nRoot = 0; /* Size of buffer zRoot */ iLastLeaf = pWriter->iFree; rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData); if( rc==SQLITE_OK ){ rc = fts3NodeWrite(p, pWriter->pTree, 1, pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot); } if( rc==SQLITE_OK ){ rc = fts3WriteSegdir(p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot); } }else{ /* The entire tree fits on the root node. Write it to the segdir table. */ rc = fts3WriteSegdir(p, iLevel, iIdx, 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData); } p->nLeafAdd++; return rc; } /* ** Release all memory held by the SegmentWriter object passed as the ** first argument. */ static void fts3SegWriterFree(SegmentWriter *pWriter){ if( pWriter ){ sqlite3_free(pWriter->aData); sqlite3_free(pWriter->zMalloc); fts3NodeFree(pWriter->pTree); sqlite3_free(pWriter); } } /* ** The first value in the apVal[] array is assumed to contain an integer. ** This function tests if there exist any documents with docid values that ** are different from that integer. i.e. if deleting the document with docid ** pRowid would mean the FTS3 table were empty. ** ** If successful, *pisEmpty is set to true if the table is empty except for ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an ** error occurs, an SQLite error code is returned. */ static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){ sqlite3_stmt *pStmt; int rc; if( p->zContentTbl ){ /* If using the content=xxx option, assume the table is never empty */ *pisEmpty = 0; rc = SQLITE_OK; }else{ rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pStmt) ){ *pisEmpty = sqlite3_column_int(pStmt, 0); } rc = sqlite3_reset(pStmt); } } return rc; } /* ** Set *pnMax to the largest segment level in the database for the index ** iIndex. ** ** Segment levels are stored in the 'level' column of the %_segdir table. ** ** Return SQLITE_OK if successful, or an SQLite error code if not. */ static int fts3SegmentMaxLevel( Fts3Table *p, int iLangid, int iIndex, sqlite3_int64 *pnMax ){ sqlite3_stmt *pStmt; int rc; assert( iIndex>=0 && iIndex<p->nIndex ); /* Set pStmt to the compiled version of: ** ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? ** ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); sqlite3_bind_int64(pStmt, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); if( SQLITE_ROW==sqlite3_step(pStmt) ){ *pnMax = sqlite3_column_int64(pStmt, 0); } return sqlite3_reset(pStmt); } /* ** iAbsLevel is an absolute level that may be assumed to exist within ** the database. This function checks if it is the largest level number ** within its index. Assuming no error occurs, *pbMax is set to 1 if ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK ** is returned. If an error occurs, an error code is returned and the ** final value of *pbMax is undefined. */ static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){ /* Set pStmt to the compiled version of: ** ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? ** ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). */ sqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; sqlite3_bind_int64(pStmt, 1, iAbsLevel+1); sqlite3_bind_int64(pStmt, 2, ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL ); *pbMax = 0; if( SQLITE_ROW==sqlite3_step(pStmt) ){ *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL; } return sqlite3_reset(pStmt); } /* ** Delete all entries in the %_segments table associated with the segment ** opened with seg-reader pSeg. This function does not affect the contents ** of the %_segdir table. */ static int fts3DeleteSegment( Fts3Table *p, /* FTS table handle */ Fts3SegReader *pSeg /* Segment to delete */ ){ int rc = SQLITE_OK; /* Return code */ if( pSeg->iStartBlock ){ sqlite3_stmt *pDelete; /* SQL statement to delete rows */ rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock); sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock); sqlite3_step(pDelete); rc = sqlite3_reset(pDelete); } } return rc; } /* ** This function is used after merging multiple segments into a single large ** segment to delete the old, now redundant, segment b-trees. Specifically, ** it: ** ** 1) Deletes all %_segments entries for the segments associated with ** each of the SegReader objects in the array passed as the third ** argument, and ** ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir ** entries regardless of level if (iLevel<0). ** ** SQLITE_OK is returned if successful, otherwise an SQLite error code. */ static int fts3DeleteSegdir( Fts3Table *p, /* Virtual table handle */ int iLangid, /* Language id */ int iIndex, /* Index for p->aIndex */ int iLevel, /* Level of %_segdir entries to delete */ Fts3SegReader **apSegment, /* Array of SegReader objects */ int nReader /* Size of array apSegment */ ){ int rc = SQLITE_OK; /* Return Code */ int i; /* Iterator variable */ sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */ for(i=0; rc==SQLITE_OK && i<nReader; i++){ rc = fts3DeleteSegment(p, apSegment[i]); } if( rc!=SQLITE_OK ){ return rc; } assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL ); if( iLevel==FTS3_SEGCURSOR_ALL ){ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); sqlite3_bind_int64(pDelete, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); } }else{ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64( pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) ); } } if( rc==SQLITE_OK ){ sqlite3_step(pDelete); rc = sqlite3_reset(pDelete); } return rc; } /* ** When this function is called, buffer *ppList (size *pnList bytes) contains ** a position list that may (or may not) feature multiple columns. This ** function adjusts the pointer *ppList and the length *pnList so that they ** identify the subset of the position list that corresponds to column iCol. ** ** If there are no entries in the input position list for column iCol, then ** *pnList is set to zero before returning. ** ** If parameter bZero is non-zero, then any part of the input list following ** the end of the output list is zeroed before returning. */ static void fts3ColumnFilter( int iCol, /* Column to filter on */ int bZero, /* Zero out anything following *ppList */ char **ppList, /* IN/OUT: Pointer to position list */ int *pnList /* IN/OUT: Size of buffer *ppList in bytes */ ){ char *pList = *ppList; int nList = *pnList; char *pEnd = &pList[nList]; int iCurrent = 0; char *p = pList; assert( iCol>=0 ); while( 1 ){ char c = 0; while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80; if( iCol==iCurrent ){ nList = (int)(p - pList); break; } nList -= (int)(p - pList); pList = p; if( nList==0 ){ break; } p = &pList[1]; p += fts3GetVarint32(p, &iCurrent); } if( bZero && &pList[nList]!=pEnd ){ memset(&pList[nList], 0, pEnd - &pList[nList]); } *ppList = pList; *pnList = nList; } /* ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any ** existing data). Grow the buffer if required. ** ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered ** trying to resize the buffer, return SQLITE_NOMEM. */ static int fts3MsrBufferData( Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ char *pList, int nList ){ if( nList>pMsr->nBuffer ){ char *pNew; pMsr->nBuffer = nList*2; pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); if( !pNew ) return SQLITE_NOMEM; pMsr->aBuffer = pNew; } memcpy(pMsr->aBuffer, pList, nList); return SQLITE_OK; } SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ sqlite3_int64 *piDocid, /* OUT: Docid value */ char **paPoslist, /* OUT: Pointer to position list */ int *pnPoslist /* OUT: Size of position list in bytes */ ){ int nMerge = pMsr->nAdvance; Fts3SegReader **apSegment = pMsr->apSegment; int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp ); if( nMerge==0 ){ *paPoslist = 0; return SQLITE_OK; } while( 1 ){ Fts3SegReader *pSeg; pSeg = pMsr->apSegment[0]; if( pSeg->pOffsetList==0 ){ *paPoslist = 0; break; }else{ int rc; char *pList; int nList; int j; sqlite3_int64 iDocid = apSegment[0]->iDocid; rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); j = 1; while( rc==SQLITE_OK && j<nMerge && apSegment[j]->pOffsetList && apSegment[j]->iDocid==iDocid ){ rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0); j++; } if( rc!=SQLITE_OK ) return rc; fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp); if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){ rc = fts3MsrBufferData(pMsr, pList, nList+1); if( rc!=SQLITE_OK ) return rc; assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 ); pList = pMsr->aBuffer; } if( pMsr->iColFilter>=0 ){ fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList); } if( nList>0 ){ *paPoslist = pList; *piDocid = iDocid; *pnPoslist = nList; break; } } } return SQLITE_OK; } static int fts3SegReaderStart( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr, /* Cursor object */ const char *zTerm, /* Term searched for (or NULL) */ int nTerm /* Length of zTerm in bytes */ ){ int i; int nSeg = pCsr->nSegment; /* If the Fts3SegFilter defines a specific term (or term prefix) to search ** for, then advance each segment iterator until it points to a term of ** equal or greater value than the specified term. This prevents many ** unnecessary merge/sort operations for the case where single segment ** b-tree leaf nodes contain more than one term. */ for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){ int res = 0; Fts3SegReader *pSeg = pCsr->apSegment[i]; do { int rc = fts3SegReaderNext(p, pSeg, 0); if( rc!=SQLITE_OK ) return rc; }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 ); if( pSeg->bLookup && res!=0 ){ fts3SegReaderSetEof(pSeg); } } fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp); return SQLITE_OK; } SQLITE_PRIVATE int sqlite3Fts3SegReaderStart( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr, /* Cursor object */ Fts3SegFilter *pFilter /* Restrictions on range of iteration */ ){ pCsr->pFilter = pFilter; return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm); } SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr, /* Cursor object */ int iCol, /* Column to match on. */ const char *zTerm, /* Term to iterate through a doclist for */ int nTerm /* Number of bytes in zTerm */ ){ int i; int rc; int nSegment = pCsr->nSegment; int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp ); assert( pCsr->pFilter==0 ); assert( zTerm && nTerm>0 ); /* Advance each segment iterator until it points to the term zTerm/nTerm. */ rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm); if( rc!=SQLITE_OK ) return rc; /* Determine how many of the segments actually point to zTerm/nTerm. */ for(i=0; i<nSegment; i++){ Fts3SegReader *pSeg = pCsr->apSegment[i]; if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){ break; } } pCsr->nAdvance = i; /* Advance each of the segments to point to the first docid. */ for(i=0; i<pCsr->nAdvance; i++){ rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]); if( rc!=SQLITE_OK ) return rc; } fts3SegReaderSort(pCsr->apSegment, i, i, xCmp); assert( iCol<0 || iCol<p->nColumn ); pCsr->iColFilter = iCol; return SQLITE_OK; } /* ** This function is called on a MultiSegReader that has been started using ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also ** have been made. Calling this function puts the MultiSegReader in such ** a state that if the next two calls are: ** ** sqlite3Fts3SegReaderStart() ** sqlite3Fts3SegReaderStep() ** ** then the entire doclist for the term is available in ** MultiSegReader.aDoclist/nDoclist. */ SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){ int i; /* Used to iterate through segment-readers */ assert( pCsr->zTerm==0 ); assert( pCsr->nTerm==0 ); assert( pCsr->aDoclist==0 ); assert( pCsr->nDoclist==0 ); pCsr->nAdvance = 0; pCsr->bRestart = 1; for(i=0; i<pCsr->nSegment; i++){ pCsr->apSegment[i]->pOffsetList = 0; pCsr->apSegment[i]->nOffsetList = 0; pCsr->apSegment[i]->iDocid = 0; } return SQLITE_OK; } SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr /* Cursor object */ ){ int rc = SQLITE_OK; int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY); int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS); int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER); int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX); int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN); int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST); Fts3SegReader **apSegment = pCsr->apSegment; int nSegment = pCsr->nSegment; Fts3SegFilter *pFilter = pCsr->pFilter; int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp ); if( pCsr->nSegment==0 ) return SQLITE_OK; do { int nMerge; int i; /* Advance the first pCsr->nAdvance entries in the apSegment[] array ** forward. Then sort the list in order of current term again. */ for(i=0; i<pCsr->nAdvance; i++){ Fts3SegReader *pSeg = apSegment[i]; if( pSeg->bLookup ){ fts3SegReaderSetEof(pSeg); }else{ rc = fts3SegReaderNext(p, pSeg, 0); } if( rc!=SQLITE_OK ) return rc; } fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp); pCsr->nAdvance = 0; /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */ assert( rc==SQLITE_OK ); if( apSegment[0]->aNode==0 ) break; pCsr->nTerm = apSegment[0]->nTerm; pCsr->zTerm = apSegment[0]->zTerm; /* If this is a prefix-search, and if the term that apSegment[0] points ** to does not share a suffix with pFilter->zTerm/nTerm, then all ** required callbacks have been made. In this case exit early. ** ** Similarly, if this is a search for an exact match, and the first term ** of segment apSegment[0] is not a match, exit early. */ if( pFilter->zTerm && !isScan ){ if( pCsr->nTerm<pFilter->nTerm || (!isPrefix && pCsr->nTerm>pFilter->nTerm) || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) ){ break; } } nMerge = 1; while( nMerge<nSegment && apSegment[nMerge]->aNode && apSegment[nMerge]->nTerm==pCsr->nTerm && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm) ){ nMerge++; } assert( isIgnoreEmpty || (isRequirePos && !isColFilter) ); if( nMerge==1 && !isIgnoreEmpty && !isFirst && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0) ){ pCsr->nDoclist = apSegment[0]->nDoclist; if( fts3SegReaderIsPending(apSegment[0]) ){ rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist); pCsr->aDoclist = pCsr->aBuffer; }else{ pCsr->aDoclist = apSegment[0]->aDoclist; } if( rc==SQLITE_OK ) rc = SQLITE_ROW; }else{ int nDoclist = 0; /* Size of doclist */ sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */ /* The current term of the first nMerge entries in the array ** of Fts3SegReader objects is the same. The doclists must be merged ** and a single term returned with the merged doclist. */ for(i=0; i<nMerge; i++){ fts3SegReaderFirstDocid(p, apSegment[i]); } fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp); while( apSegment[0]->pOffsetList ){ int j; /* Number of segments that share a docid */ char *pList = 0; int nList = 0; int nByte; sqlite3_int64 iDocid = apSegment[0]->iDocid; fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); j = 1; while( j<nMerge && apSegment[j]->pOffsetList && apSegment[j]->iDocid==iDocid ){ fts3SegReaderNextDocid(p, apSegment[j], 0, 0); j++; } if( isColFilter ){ fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList); } if( !isIgnoreEmpty || nList>0 ){ /* Calculate the 'docid' delta value to write into the merged ** doclist. */ sqlite3_int64 iDelta; if( p->bDescIdx && nDoclist>0 ){ iDelta = iPrev - iDocid; }else{ iDelta = iDocid - iPrev; } assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) ); assert( nDoclist>0 || iDelta==iDocid ); nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0); if( nDoclist+nByte>pCsr->nBuffer ){ char *aNew; pCsr->nBuffer = (nDoclist+nByte)*2; aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer); if( !aNew ){ return SQLITE_NOMEM; } pCsr->aBuffer = aNew; } if( isFirst ){ char *a = &pCsr->aBuffer[nDoclist]; int nWrite; nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a); if( nWrite ){ iPrev = iDocid; nDoclist += nWrite; } }else{ nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta); iPrev = iDocid; if( isRequirePos ){ memcpy(&pCsr->aBuffer[nDoclist], pList, nList); nDoclist += nList; pCsr->aBuffer[nDoclist++] = '\0'; } } } fts3SegReaderSort(apSegment, nMerge, j, xCmp); } if( nDoclist>0 ){ pCsr->aDoclist = pCsr->aBuffer; pCsr->nDoclist = nDoclist; rc = SQLITE_ROW; } } pCsr->nAdvance = nMerge; }while( rc==SQLITE_OK ); return rc; } SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish( Fts3MultiSegReader *pCsr /* Cursor object */ ){ if( pCsr ){ int i; for(i=0; i<pCsr->nSegment; i++){ sqlite3Fts3SegReaderFree(pCsr->apSegment[i]); } sqlite3_free(pCsr->apSegment); sqlite3_free(pCsr->aBuffer); pCsr->nSegment = 0; pCsr->apSegment = 0; pCsr->aBuffer = 0; } } /* ** Decode the "end_block" field, selected by column iCol of the SELECT ** statement passed as the first argument. ** ** The "end_block" field may contain either an integer, or a text field ** containing the text representation of two non-negative integers separated ** by one or more space (0x20) characters. In the first case, set *piEndBlock ** to the integer value and *pnByte to zero before returning. In the second, ** set *piEndBlock to the first value and *pnByte to the second. */ static void fts3ReadEndBlockField( sqlite3_stmt *pStmt, int iCol, i64 *piEndBlock, i64 *pnByte ){ const unsigned char *zText = sqlite3_column_text(pStmt, iCol); if( zText ){ int i; int iMul = 1; i64 iVal = 0; for(i=0; zText[i]>='0' && zText[i]<='9'; i++){ iVal = iVal*10 + (zText[i] - '0'); } *piEndBlock = iVal; while( zText[i]==' ' ) i++; iVal = 0; if( zText[i]=='-' ){ i++; iMul = -1; } for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){ iVal = iVal*10 + (zText[i] - '0'); } *pnByte = (iVal * (i64)iMul); } } /* ** A segment of size nByte bytes has just been written to absolute level ** iAbsLevel. Promote any segments that should be promoted as a result. */ static int fts3PromoteSegments( Fts3Table *p, /* FTS table handle */ sqlite3_int64 iAbsLevel, /* Absolute level just updated */ sqlite3_int64 nByte /* Size of new segment at iAbsLevel */ ){ int rc = SQLITE_OK; sqlite3_stmt *pRange; rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0); if( rc==SQLITE_OK ){ int bOk = 0; i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1; i64 nLimit = (nByte*3)/2; /* Loop through all entries in the %_segdir table corresponding to ** segments in this index on levels greater than iAbsLevel. If there is ** at least one such segment, and it is possible to determine that all ** such segments are smaller than nLimit bytes in size, they will be ** promoted to level iAbsLevel. */ sqlite3_bind_int64(pRange, 1, iAbsLevel+1); sqlite3_bind_int64(pRange, 2, iLast); while( SQLITE_ROW==sqlite3_step(pRange) ){ i64 nSize = 0, dummy; fts3ReadEndBlockField(pRange, 2, &dummy, &nSize); if( nSize<=0 || nSize>nLimit ){ /* If nSize==0, then the %_segdir.end_block field does not not ** contain a size value. This happens if it was written by an ** old version of FTS. In this case it is not possible to determine ** the size of the segment, and so segment promotion does not ** take place. */ bOk = 0; break; } bOk = 1; } rc = sqlite3_reset(pRange); if( bOk ){ int iIdx = 0; sqlite3_stmt *pUpdate1 = 0; sqlite3_stmt *pUpdate2 = 0; if( rc==SQLITE_OK ){ rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0); } if( rc==SQLITE_OK ){ rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0); } if( rc==SQLITE_OK ){ /* Loop through all %_segdir entries for segments in this index with ** levels equal to or greater than iAbsLevel. As each entry is visited, ** updated it to set (level = -1) and (idx = N), where N is 0 for the ** oldest segment in the range, 1 for the next oldest, and so on. ** ** In other words, move all segments being promoted to level -1, ** setting the "idx" fields as appropriate to keep them in the same ** order. The contents of level -1 (which is never used, except ** transiently here), will be moved back to level iAbsLevel below. */ sqlite3_bind_int64(pRange, 1, iAbsLevel); while( SQLITE_ROW==sqlite3_step(pRange) ){ sqlite3_bind_int(pUpdate1, 1, iIdx++); sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0)); sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1)); sqlite3_step(pUpdate1); rc = sqlite3_reset(pUpdate1); if( rc!=SQLITE_OK ){ sqlite3_reset(pRange); break; } } } if( rc==SQLITE_OK ){ rc = sqlite3_reset(pRange); } /* Move level -1 to level iAbsLevel */ if( rc==SQLITE_OK ){ sqlite3_bind_int64(pUpdate2, 1, iAbsLevel); sqlite3_step(pUpdate2); rc = sqlite3_reset(pUpdate2); } } } return rc; } /* ** Merge all level iLevel segments in the database into a single ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a ** single segment with a level equal to the numerically largest level ** currently present in the database. ** ** If this function is called with iLevel<0, but there is only one ** segment in the database, SQLITE_DONE is returned immediately. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, ** an SQLite error code is returned. */ static int fts3SegmentMerge( Fts3Table *p, int iLangid, /* Language id to merge */ int iIndex, /* Index in p->aIndex[] to merge */ int iLevel /* Level to merge */ ){ int rc; /* Return code */ int iIdx = 0; /* Index of new segment */ sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */ SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */ Fts3SegFilter filter; /* Segment term filter condition */ Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */ int bIgnoreEmpty = 0; /* True to ignore empty segments */ i64 iMaxLevel = 0; /* Max level number for this index/langid */ assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel==FTS3_SEGCURSOR_PENDING || iLevel>=0 ); assert( iLevel<FTS3_SEGDIR_MAXLEVEL ); assert( iIndex>=0 && iIndex<p->nIndex ); rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr); if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished; if( iLevel!=FTS3_SEGCURSOR_PENDING ){ rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel); if( rc!=SQLITE_OK ) goto finished; } if( iLevel==FTS3_SEGCURSOR_ALL ){ /* This call is to merge all segments in the database to a single ** segment. The level of the new segment is equal to the numerically ** greatest segment level currently present in the database for this ** index. The idx of the new segment is always 0. */ if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){ rc = SQLITE_DONE; goto finished; } iNewLevel = iMaxLevel; bIgnoreEmpty = 1; }else{ /* This call is to merge all segments at level iLevel. find the next ** available segment index at level iLevel+1. The call to ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to ** a single iLevel+2 segment if necessary. */ assert( FTS3_SEGCURSOR_PENDING==-1 ); iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1); rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx); bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel); } if( rc!=SQLITE_OK ) goto finished; assert( csr.nSegment>0 ); assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) ); assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) ); memset(&filter, 0, sizeof(Fts3SegFilter)); filter.flags = FTS3_SEGMENT_REQUIRE_POS; filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0); rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); while( SQLITE_OK==rc ){ rc = sqlite3Fts3SegReaderStep(p, &csr); if( rc!=SQLITE_ROW ) break; rc = fts3SegWriterAdd(p, &pWriter, 1, csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist); } if( rc!=SQLITE_OK ) goto finished; assert( pWriter || bIgnoreEmpty ); if( iLevel!=FTS3_SEGCURSOR_PENDING ){ rc = fts3DeleteSegdir( p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment ); if( rc!=SQLITE_OK ) goto finished; } if( pWriter ){ rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx); if( rc==SQLITE_OK ){ if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){ rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData); } } } finished: fts3SegWriterFree(pWriter); sqlite3Fts3SegReaderFinish(&csr); return rc; } /* ** Flush the contents of pendingTerms to level 0 segments. */ SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){ int rc = SQLITE_OK; int i; for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){ rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } sqlite3Fts3PendingTermsClear(p); /* Determine the auto-incr-merge setting if unknown. If enabled, ** estimate the number of leaf blocks of content to be written */ if( rc==SQLITE_OK && p->bHasStat && p->nAutoincrmerge==0xff && p->nLeafAdd>0 ){ sqlite3_stmt *pStmt = 0; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); rc = sqlite3_step(pStmt); if( rc==SQLITE_ROW ){ p->nAutoincrmerge = sqlite3_column_int(pStmt, 0); if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8; }else if( rc==SQLITE_DONE ){ p->nAutoincrmerge = 0; } rc = sqlite3_reset(pStmt); } } return rc; } /* ** Encode N integers as varints into a blob. */ static void fts3EncodeIntArray( int N, /* The number of integers to encode */ u32 *a, /* The integer values */ char *zBuf, /* Write the BLOB here */ int *pNBuf /* Write number of bytes if zBuf[] used here */ ){ int i, j; for(i=j=0; i<N; i++){ j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]); } *pNBuf = j; } /* ** Decode a blob of varints into N integers */ static void fts3DecodeIntArray( int N, /* The number of integers to decode */ u32 *a, /* Write the integer values */ const char *zBuf, /* The BLOB containing the varints */ int nBuf /* size of the BLOB */ ){ int i, j; UNUSED_PARAMETER(nBuf); for(i=j=0; i<N; i++){ sqlite3_int64 x; j += sqlite3Fts3GetVarint(&zBuf[j], &x); assert(j<=nBuf); a[i] = (u32)(x & 0xffffffff); } } /* ** Insert the sizes (in tokens) for each column of the document ** with docid equal to p->iPrevDocid. The sizes are encoded as ** a blob of varints. */ static void fts3InsertDocsize( int *pRC, /* Result code */ Fts3Table *p, /* Table into which to insert */ u32 *aSz /* Sizes of each column, in tokens */ ){ char *pBlob; /* The BLOB encoding of the document size */ int nBlob; /* Number of bytes in the BLOB */ sqlite3_stmt *pStmt; /* Statement used to insert the encoding */ int rc; /* Result code from subfunctions */ if( *pRC ) return; pBlob = sqlite3_malloc( 10*p->nColumn ); if( pBlob==0 ){ *pRC = SQLITE_NOMEM; return; } fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob); rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0); if( rc ){ sqlite3_free(pBlob); *pRC = rc; return; } sqlite3_bind_int64(pStmt, 1, p->iPrevDocid); sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free); sqlite3_step(pStmt); *pRC = sqlite3_reset(pStmt); } /* ** Record 0 of the %_stat table contains a blob consisting of N varints, ** where N is the number of user defined columns in the fts3 table plus ** two. If nCol is the number of user defined columns, then values of the ** varints are set as follows: ** ** Varint 0: Total number of rows in the table. ** ** Varint 1..nCol: For each column, the total number of tokens stored in ** the column for all rows of the table. ** ** Varint 1+nCol: The total size, in bytes, of all text values in all ** columns of all rows of the table. ** */ static void fts3UpdateDocTotals( int *pRC, /* The result code */ Fts3Table *p, /* Table being updated */ u32 *aSzIns, /* Size increases */ u32 *aSzDel, /* Size decreases */ int nChng /* Change in the number of documents */ ){ char *pBlob; /* Storage for BLOB written into %_stat */ int nBlob; /* Size of BLOB written into %_stat */ u32 *a; /* Array of integers that becomes the BLOB */ sqlite3_stmt *pStmt; /* Statement for reading and writing */ int i; /* Loop counter */ int rc; /* Result code from subfunctions */ const int nStat = p->nColumn+2; if( *pRC ) return; a = sqlite3_malloc( (sizeof(u32)+10)*nStat ); if( a==0 ){ *pRC = SQLITE_NOMEM; return; } pBlob = (char*)&a[nStat]; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); if( rc ){ sqlite3_free(a); *pRC = rc; return; } sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); if( sqlite3_step(pStmt)==SQLITE_ROW ){ fts3DecodeIntArray(nStat, a, sqlite3_column_blob(pStmt, 0), sqlite3_column_bytes(pStmt, 0)); }else{ memset(a, 0, sizeof(u32)*(nStat) ); } rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ){ sqlite3_free(a); *pRC = rc; return; } if( nChng<0 && a[0]<(u32)(-nChng) ){ a[0] = 0; }else{ a[0] += nChng; } for(i=0; i<p->nColumn+1; i++){ u32 x = a[i+1]; if( x+aSzIns[i] < aSzDel[i] ){ x = 0; }else{ x = x + aSzIns[i] - aSzDel[i]; } a[i+1] = x; } fts3EncodeIntArray(nStat, a, pBlob, &nBlob); rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); if( rc ){ sqlite3_free(a); *pRC = rc; return; } sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC); sqlite3_step(pStmt); *pRC = sqlite3_reset(pStmt); sqlite3_free(a); } /* ** Merge the entire database so that there is one segment for each ** iIndex/iLangid combination. */ static int fts3DoOptimize(Fts3Table *p, int bReturnDone){ int bSeenDone = 0; int rc; sqlite3_stmt *pAllLangid = 0; rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); if( rc==SQLITE_OK ){ int rc2; sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); sqlite3_bind_int(pAllLangid, 2, p->nIndex); while( sqlite3_step(pAllLangid)==SQLITE_ROW ){ int i; int iLangid = sqlite3_column_int(pAllLangid, 0); for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){ rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL); if( rc==SQLITE_DONE ){ bSeenDone = 1; rc = SQLITE_OK; } } } rc2 = sqlite3_reset(pAllLangid); if( rc==SQLITE_OK ) rc = rc2; } sqlite3Fts3SegmentsClose(p); sqlite3Fts3PendingTermsClear(p); return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc; } /* ** This function is called when the user executes the following statement: ** ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild'); ** ** The entire FTS index is discarded and rebuilt. If the table is one ** created using the content=xxx option, then the new index is based on ** the current contents of the xxx table. Otherwise, it is rebuilt based ** on the contents of the %_content table. */ static int fts3DoRebuild(Fts3Table *p){ int rc; /* Return Code */ rc = fts3DeleteAll(p, 0); if( rc==SQLITE_OK ){ u32 *aSz = 0; u32 *aSzIns = 0; u32 *aSzDel = 0; sqlite3_stmt *pStmt = 0; int nEntry = 0; /* Compose and prepare an SQL statement to loop through the content table */ char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); } if( rc==SQLITE_OK ){ int nByte = sizeof(u32) * (p->nColumn+1)*3; aSz = (u32 *)sqlite3_malloc(nByte); if( aSz==0 ){ rc = SQLITE_NOMEM; }else{ memset(aSz, 0, nByte); aSzIns = &aSz[p->nColumn+1]; aSzDel = &aSzIns[p->nColumn+1]; } } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ int iCol; int iLangid = langidFromSelect(p, pStmt); rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0)); memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1)); for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){ if( p->abNotindexed[iCol]==0 ){ const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1); rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]); aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1); } } if( p->bHasDocsize ){ fts3InsertDocsize(&rc, p, aSz); } if( rc!=SQLITE_OK ){ sqlite3_finalize(pStmt); pStmt = 0; }else{ nEntry++; for(iCol=0; iCol<=p->nColumn; iCol++){ aSzIns[iCol] += aSz[iCol]; } } } if( p->bFts4 ){ fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry); } sqlite3_free(aSz); if( pStmt ){ int rc2 = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ){ rc = rc2; } } } return rc; } /* ** This function opens a cursor used to read the input data for an ** incremental merge operation. Specifically, it opens a cursor to scan ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute ** level iAbsLevel. */ static int fts3IncrmergeCsr( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level to open */ int nSeg, /* Number of segments to merge */ Fts3MultiSegReader *pCsr /* Cursor object to populate */ ){ int rc; /* Return Code */ sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */ int nByte; /* Bytes allocated at pCsr->apSegment[] */ /* Allocate space for the Fts3MultiSegReader.aCsr[] array */ memset(pCsr, 0, sizeof(*pCsr)); nByte = sizeof(Fts3SegReader *) * nSeg; pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte); if( pCsr->apSegment==0 ){ rc = SQLITE_NOMEM; }else{ memset(pCsr->apSegment, 0, nByte); rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); } if( rc==SQLITE_OK ){ int i; int rc2; sqlite3_bind_int64(pStmt, 1, iAbsLevel); assert( pCsr->nSegment==0 ); for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){ rc = sqlite3Fts3SegReaderNew(i, 0, sqlite3_column_int64(pStmt, 1), /* segdir.start_block */ sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */ sqlite3_column_int64(pStmt, 3), /* segdir.end_block */ sqlite3_column_blob(pStmt, 4), /* segdir.root */ sqlite3_column_bytes(pStmt, 4), /* segdir.root */ &pCsr->apSegment[i] ); pCsr->nSegment++; } rc2 = sqlite3_reset(pStmt); if( rc==SQLITE_OK ) rc = rc2; } return rc; } typedef struct IncrmergeWriter IncrmergeWriter; typedef struct NodeWriter NodeWriter; typedef struct Blob Blob; typedef struct NodeReader NodeReader; /* ** An instance of the following structure is used as a dynamic buffer ** to build up nodes or other blobs of data in. ** ** The function blobGrowBuffer() is used to extend the allocation. */ struct Blob { char *a; /* Pointer to allocation */ int n; /* Number of valid bytes of data in a[] */ int nAlloc; /* Allocated size of a[] (nAlloc>=n) */ }; /* ** This structure is used to build up buffers containing segment b-tree ** nodes (blocks). */ struct NodeWriter { sqlite3_int64 iBlock; /* Current block id */ Blob key; /* Last key written to the current block */ Blob block; /* Current block image */ }; /* ** An object of this type contains the state required to create or append ** to an appendable b-tree segment. */ struct IncrmergeWriter { int nLeafEst; /* Space allocated for leaf blocks */ int nWork; /* Number of leaf pages flushed */ sqlite3_int64 iAbsLevel; /* Absolute level of input segments */ int iIdx; /* Index of *output* segment in iAbsLevel+1 */ sqlite3_int64 iStart; /* Block number of first allocated block */ sqlite3_int64 iEnd; /* Block number of last allocated block */ sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */ u8 bNoLeafData; /* If true, store 0 for segment size */ NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT]; }; /* ** An object of the following type is used to read data from a single ** FTS segment node. See the following functions: ** ** nodeReaderInit() ** nodeReaderNext() ** nodeReaderRelease() */ struct NodeReader { const char *aNode; int nNode; int iOff; /* Current offset within aNode[] */ /* Output variables. Containing the current node entry. */ sqlite3_int64 iChild; /* Pointer to child node */ Blob term; /* Current term */ const char *aDoclist; /* Pointer to doclist */ int nDoclist; /* Size of doclist in bytes */ }; /* ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** Otherwise, if the allocation at pBlob->a is not already at least nMin ** bytes in size, extend (realloc) it to be so. ** ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc ** to reflect the new size of the pBlob->a[] buffer. */ static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){ if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){ int nAlloc = nMin; char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc); if( a ){ pBlob->nAlloc = nAlloc; pBlob->a = a; }else{ *pRc = SQLITE_NOMEM; } } } /* ** Attempt to advance the node-reader object passed as the first argument to ** the next entry on the node. ** ** Return an error code if an error occurs (SQLITE_NOMEM is possible). ** Otherwise return SQLITE_OK. If there is no next entry on the node ** (e.g. because the current entry is the last) set NodeReader->aNode to ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output ** variables for the new entry. */ static int nodeReaderNext(NodeReader *p){ int bFirst = (p->term.n==0); /* True for first term on the node */ int nPrefix = 0; /* Bytes to copy from previous term */ int nSuffix = 0; /* Bytes to append to the prefix */ int rc = SQLITE_OK; /* Return code */ assert( p->aNode ); if( p->iChild && bFirst==0 ) p->iChild++; if( p->iOff>=p->nNode ){ /* EOF */ p->aNode = 0; }else{ if( bFirst==0 ){ p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix); } p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix); blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc); if( rc==SQLITE_OK ){ memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix); p->term.n = nPrefix+nSuffix; p->iOff += nSuffix; if( p->iChild==0 ){ p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist); p->aDoclist = &p->aNode[p->iOff]; p->iOff += p->nDoclist; } } } assert( p->iOff<=p->nNode ); return rc; } /* ** Release all dynamic resources held by node-reader object *p. */ static void nodeReaderRelease(NodeReader *p){ sqlite3_free(p->term.a); } /* ** Initialize a node-reader object to read the node in buffer aNode/nNode. ** ** If successful, SQLITE_OK is returned and the NodeReader object set to ** point to the first entry on the node (if any). Otherwise, an SQLite ** error code is returned. */ static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){ memset(p, 0, sizeof(NodeReader)); p->aNode = aNode; p->nNode = nNode; /* Figure out if this is a leaf or an internal node. */ if( p->aNode[0] ){ /* An internal node. */ p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild); }else{ p->iOff = 1; } return nodeReaderNext(p); } /* ** This function is called while writing an FTS segment each time a leaf o ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed ** to be greater than the largest key on the node just written, but smaller ** than or equal to the first key that will be written to the next leaf ** node. ** ** The block id of the leaf node just written to disk may be found in ** (pWriter->aNodeWriter[0].iBlock) when this function is called. */ static int fts3IncrmergePush( Fts3Table *p, /* Fts3 table handle */ IncrmergeWriter *pWriter, /* Writer object */ const char *zTerm, /* Term to write to internal node */ int nTerm /* Bytes at zTerm */ ){ sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock; int iLayer; assert( nTerm>0 ); for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){ sqlite3_int64 iNextPtr = 0; NodeWriter *pNode = &pWriter->aNodeWriter[iLayer]; int rc = SQLITE_OK; int nPrefix; int nSuffix; int nSpace; /* Figure out how much space the key will consume if it is written to ** the current node of layer iLayer. Due to the prefix compression, ** the space required changes depending on which node the key is to ** be added to. */ nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm); nSuffix = nTerm - nPrefix; nSpace = sqlite3Fts3VarintLen(nPrefix); nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ /* If the current node of layer iLayer contains zero keys, or if adding ** the key to it will not cause it to grow to larger than nNodeSize ** bytes in size, write the key here. */ Blob *pBlk = &pNode->block; if( pBlk->n==0 ){ blobGrowBuffer(pBlk, p->nNodeSize, &rc); if( rc==SQLITE_OK ){ pBlk->a[0] = (char)iLayer; pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr); } } blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc); blobGrowBuffer(&pNode->key, nTerm, &rc); if( rc==SQLITE_OK ){ if( pNode->key.n ){ pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix); } pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix); memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix); pBlk->n += nSuffix; memcpy(pNode->key.a, zTerm, nTerm); pNode->key.n = nTerm; } }else{ /* Otherwise, flush the current node of layer iLayer to disk. ** Then allocate a new, empty sibling node. The key will be written ** into the parent of this node. */ rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); assert( pNode->block.nAlloc>=p->nNodeSize ); pNode->block.a[0] = (char)iLayer; pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1); iNextPtr = pNode->iBlock; pNode->iBlock++; pNode->key.n = 0; } if( rc!=SQLITE_OK || iNextPtr==0 ) return rc; iPtr = iNextPtr; } assert( 0 ); return 0; } /* ** Append a term and (optionally) doclist to the FTS segment node currently ** stored in blob *pNode. The node need not contain any terms, but the ** header must be written before this function is called. ** ** A node header is a single 0x00 byte for a leaf node, or a height varint ** followed by the left-hand-child varint for an internal node. ** ** The term to be appended is passed via arguments zTerm/nTerm. For a ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal ** node, both aDoclist and nDoclist must be passed 0. ** ** If the size of the value in blob pPrev is zero, then this is the first ** term written to the node. Otherwise, pPrev contains a copy of the ** previous term. Before this function returns, it is updated to contain a ** copy of zTerm/nTerm. ** ** It is assumed that the buffer associated with pNode is already large ** enough to accommodate the new entry. The buffer associated with pPrev ** is extended by this function if requrired. ** ** If an error (i.e. OOM condition) occurs, an SQLite error code is ** returned. Otherwise, SQLITE_OK. */ static int fts3AppendToNode( Blob *pNode, /* Current node image to append to */ Blob *pPrev, /* Buffer containing previous term written */ const char *zTerm, /* New term to write */ int nTerm, /* Size of zTerm in bytes */ const char *aDoclist, /* Doclist (or NULL) to write */ int nDoclist /* Size of aDoclist in bytes */ ){ int rc = SQLITE_OK; /* Return code */ int bFirst = (pPrev->n==0); /* True if this is the first term written */ int nPrefix; /* Size of term prefix in bytes */ int nSuffix; /* Size of term suffix in bytes */ /* Node must have already been started. There must be a doclist for a ** leaf node, and there must not be a doclist for an internal node. */ assert( pNode->n>0 ); assert( (pNode->a[0]=='\0')==(aDoclist!=0) ); blobGrowBuffer(pPrev, nTerm, &rc); if( rc!=SQLITE_OK ) return rc; nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm); nSuffix = nTerm - nPrefix; memcpy(pPrev->a, zTerm, nTerm); pPrev->n = nTerm; if( bFirst==0 ){ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix); } pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix); memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix); pNode->n += nSuffix; if( aDoclist ){ pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist); memcpy(&pNode->a[pNode->n], aDoclist, nDoclist); pNode->n += nDoclist; } assert( pNode->n<=pNode->nAlloc ); return SQLITE_OK; } /* ** Append the current term and doclist pointed to by cursor pCsr to the ** appendable b-tree segment opened for writing by pWriter. ** ** Return SQLITE_OK if successful, or an SQLite error code otherwise. */ static int fts3IncrmergeAppend( Fts3Table *p, /* Fts3 table handle */ IncrmergeWriter *pWriter, /* Writer object */ Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */ ){ const char *zTerm = pCsr->zTerm; int nTerm = pCsr->nTerm; const char *aDoclist = pCsr->aDoclist; int nDoclist = pCsr->nDoclist; int rc = SQLITE_OK; /* Return code */ int nSpace; /* Total space in bytes required on leaf */ int nPrefix; /* Size of prefix shared with previous term */ int nSuffix; /* Size of suffix (nTerm - nPrefix) */ NodeWriter *pLeaf; /* Object used to write leaf nodes */ pLeaf = &pWriter->aNodeWriter[0]; nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm); nSuffix = nTerm - nPrefix; nSpace = sqlite3Fts3VarintLen(nPrefix); nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; /* If the current block is not empty, and if adding this term/doclist ** to the current block would make it larger than Fts3Table.nNodeSize ** bytes, write this block out to the database. */ if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){ rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n); pWriter->nWork++; /* Add the current term to the parent node. The term added to the ** parent must: ** ** a) be greater than the largest term on the leaf node just written ** to the database (still available in pLeaf->key), and ** ** b) be less than or equal to the term about to be added to the new ** leaf node (zTerm/nTerm). ** ** In other words, it must be the prefix of zTerm 1 byte longer than ** the common prefix (if any) of zTerm and pWriter->zTerm. */ if( rc==SQLITE_OK ){ rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1); } /* Advance to the next output block */ pLeaf->iBlock++; pLeaf->key.n = 0; pLeaf->block.n = 0; nSuffix = nTerm; nSpace = 1; nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; } pWriter->nLeafData += nSpace; blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc); if( rc==SQLITE_OK ){ if( pLeaf->block.n==0 ){ pLeaf->block.n = 1; pLeaf->block.a[0] = '\0'; } rc = fts3AppendToNode( &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist ); } return rc; } /* ** This function is called to release all dynamic resources held by the ** merge-writer object pWriter, and if no error has occurred, to flush ** all outstanding node buffers held by pWriter to disk. ** ** If *pRc is not SQLITE_OK when this function is called, then no attempt ** is made to write any data to disk. Instead, this function serves only ** to release outstanding resources. ** ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while ** flushing buffers to disk, *pRc is set to an SQLite error code before ** returning. */ static void fts3IncrmergeRelease( Fts3Table *p, /* FTS3 table handle */ IncrmergeWriter *pWriter, /* Merge-writer object */ int *pRc /* IN/OUT: Error code */ ){ int i; /* Used to iterate through non-root layers */ int iRoot; /* Index of root in pWriter->aNodeWriter */ NodeWriter *pRoot; /* NodeWriter for root node */ int rc = *pRc; /* Error code */ /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment ** root node. If the segment fits entirely on a single leaf node, iRoot ** will be set to 0. If the root node is the parent of the leaves, iRoot ** will be 1. And so on. */ for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){ NodeWriter *pNode = &pWriter->aNodeWriter[iRoot]; if( pNode->block.n>0 ) break; assert( *pRc || pNode->block.nAlloc==0 ); assert( *pRc || pNode->key.nAlloc==0 ); sqlite3_free(pNode->block.a); sqlite3_free(pNode->key.a); } /* Empty output segment. This is a no-op. */ if( iRoot<0 ) return; /* The entire output segment fits on a single node. Normally, this means ** the node would be stored as a blob in the "root" column of the %_segdir ** table. However, this is not permitted in this case. The problem is that ** space has already been reserved in the %_segments table, and so the ** start_block and end_block fields of the %_segdir table must be populated. ** And, by design or by accident, released versions of FTS cannot handle ** segments that fit entirely on the root node with start_block!=0. ** ** Instead, create a synthetic root node that contains nothing but a ** pointer to the single content node. So that the segment consists of a ** single leaf and a single interior (root) node. ** ** Todo: Better might be to defer allocating space in the %_segments ** table until we are sure it is needed. */ if( iRoot==0 ){ Blob *pBlock = &pWriter->aNodeWriter[1].block; blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc); if( rc==SQLITE_OK ){ pBlock->a[0] = 0x01; pBlock->n = 1 + sqlite3Fts3PutVarint( &pBlock->a[1], pWriter->aNodeWriter[0].iBlock ); } iRoot = 1; } pRoot = &pWriter->aNodeWriter[iRoot]; /* Flush all currently outstanding nodes to disk. */ for(i=0; i<iRoot; i++){ NodeWriter *pNode = &pWriter->aNodeWriter[i]; if( pNode->block.n>0 && rc==SQLITE_OK ){ rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); } sqlite3_free(pNode->block.a); sqlite3_free(pNode->key.a); } /* Write the %_segdir record. */ if( rc==SQLITE_OK ){ rc = fts3WriteSegdir(p, pWriter->iAbsLevel+1, /* level */ pWriter->iIdx, /* idx */ pWriter->iStart, /* start_block */ pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */ pWriter->iEnd, /* end_block */ (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */ pRoot->block.a, pRoot->block.n /* root */ ); } sqlite3_free(pRoot->block.a); sqlite3_free(pRoot->key.a); *pRc = rc; } /* ** Compare the term in buffer zLhs (size in bytes nLhs) with that in ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of ** the other, it is considered to be smaller than the other. ** ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve ** if it is greater. */ static int fts3TermCmp( const char *zLhs, int nLhs, /* LHS of comparison */ const char *zRhs, int nRhs /* RHS of comparison */ ){ int nCmp = MIN(nLhs, nRhs); int res; res = memcmp(zLhs, zRhs, nCmp); if( res==0 ) res = nLhs - nRhs; return res; } /* ** Query to see if the entry in the %_segments table with blockid iEnd is ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before ** returning. Otherwise, set *pbRes to 0. ** ** Or, if an error occurs while querying the database, return an SQLite ** error code. The final value of *pbRes is undefined in this case. ** ** This is used to test if a segment is an "appendable" segment. If it ** is, then a NULL entry has been inserted into the %_segments table ** with blockid %_segdir.end_block. */ static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){ int bRes = 0; /* Result to set *pbRes to */ sqlite3_stmt *pCheck = 0; /* Statement to query database with */ int rc; /* Return code */ rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pCheck, 1, iEnd); if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1; rc = sqlite3_reset(pCheck); } *pbRes = bRes; return rc; } /* ** This function is called when initializing an incremental-merge operation. ** It checks if the existing segment with index value iIdx at absolute level ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the ** merge-writer object *pWriter is initialized to write to it. ** ** An existing segment can be appended to by an incremental merge if: ** ** * It was initially created as an appendable segment (with all required ** space pre-allocated), and ** ** * The first key read from the input (arguments zKey and nKey) is ** greater than the largest key currently stored in the potential ** output segment. */ static int fts3IncrmergeLoad( Fts3Table *p, /* Fts3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ int iIdx, /* Index of candidate output segment */ const char *zKey, /* First key to write */ int nKey, /* Number of bytes in nKey */ IncrmergeWriter *pWriter /* Populate this object */ ){ int rc; /* Return code */ sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0); if( rc==SQLITE_OK ){ sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */ sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */ sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */ const char *aRoot = 0; /* Pointer to %_segdir.root buffer */ int nRoot = 0; /* Size of aRoot[] in bytes */ int rc2; /* Return code from sqlite3_reset() */ int bAppendable = 0; /* Set to true if segment is appendable */ /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */ sqlite3_bind_int64(pSelect, 1, iAbsLevel+1); sqlite3_bind_int(pSelect, 2, iIdx); if( sqlite3_step(pSelect)==SQLITE_ROW ){ iStart = sqlite3_column_int64(pSelect, 1); iLeafEnd = sqlite3_column_int64(pSelect, 2); fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData); if( pWriter->nLeafData<0 ){ pWriter->nLeafData = pWriter->nLeafData * -1; } pWriter->bNoLeafData = (pWriter->nLeafData==0); nRoot = sqlite3_column_bytes(pSelect, 4); aRoot = sqlite3_column_blob(pSelect, 4); }else{ return sqlite3_reset(pSelect); } /* Check for the zero-length marker in the %_segments table */ rc = fts3IsAppendable(p, iEnd, &bAppendable); /* Check that zKey/nKey is larger than the largest key the candidate */ if( rc==SQLITE_OK && bAppendable ){ char *aLeaf = 0; int nLeaf = 0; rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0); if( rc==SQLITE_OK ){ NodeReader reader; for(rc = nodeReaderInit(&reader, aLeaf, nLeaf); rc==SQLITE_OK && reader.aNode; rc = nodeReaderNext(&reader) ){ assert( reader.aNode ); } if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){ bAppendable = 0; } nodeReaderRelease(&reader); } sqlite3_free(aLeaf); } if( rc==SQLITE_OK && bAppendable ){ /* It is possible to append to this segment. Set up the IncrmergeWriter ** object to do so. */ int i; int nHeight = (int)aRoot[0]; NodeWriter *pNode; pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT; pWriter->iStart = iStart; pWriter->iEnd = iEnd; pWriter->iAbsLevel = iAbsLevel; pWriter->iIdx = iIdx; for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){ pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; } pNode = &pWriter->aNodeWriter[nHeight]; pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight; blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc); if( rc==SQLITE_OK ){ memcpy(pNode->block.a, aRoot, nRoot); pNode->block.n = nRoot; } for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){ NodeReader reader; pNode = &pWriter->aNodeWriter[i]; rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n); while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader); blobGrowBuffer(&pNode->key, reader.term.n, &rc); if( rc==SQLITE_OK ){ memcpy(pNode->key.a, reader.term.a, reader.term.n); pNode->key.n = reader.term.n; if( i>0 ){ char *aBlock = 0; int nBlock = 0; pNode = &pWriter->aNodeWriter[i-1]; pNode->iBlock = reader.iChild; rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0); blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc); if( rc==SQLITE_OK ){ memcpy(pNode->block.a, aBlock, nBlock); pNode->block.n = nBlock; } sqlite3_free(aBlock); } } nodeReaderRelease(&reader); } } rc2 = sqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } return rc; } /* ** Determine the largest segment index value that exists within absolute ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus ** one before returning SQLITE_OK. Or, if there are no segments at all ** within level iAbsLevel, set *piIdx to zero. ** ** If an error occurs, return an SQLite error code. The final value of ** *piIdx is undefined in this case. */ static int fts3IncrmergeOutputIdx( Fts3Table *p, /* FTS Table handle */ sqlite3_int64 iAbsLevel, /* Absolute index of input segments */ int *piIdx /* OUT: Next free index at iAbsLevel+1 */ ){ int rc; sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1); sqlite3_step(pOutputIdx); *piIdx = sqlite3_column_int(pOutputIdx, 0); rc = sqlite3_reset(pOutputIdx); } return rc; } /* ** Allocate an appendable output segment on absolute level iAbsLevel+1 ** with idx value iIdx. ** ** In the %_segdir table, a segment is defined by the values in three ** columns: ** ** start_block ** leaves_end_block ** end_block ** ** When an appendable segment is allocated, it is estimated that the ** maximum number of leaf blocks that may be required is the sum of the ** number of leaf blocks consumed by the input segments, plus the number ** of input segments, multiplied by two. This value is stored in stack ** variable nLeafEst. ** ** A total of 16*nLeafEst blocks are allocated when an appendable segment ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous ** array of leaf nodes starts at the first block allocated. The array ** of interior nodes that are parents of the leaf nodes start at block ** (start_block + (1 + end_block - start_block) / 16). And so on. ** ** In the actual code below, the value "16" is replaced with the ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT. */ static int fts3IncrmergeWriter( Fts3Table *p, /* Fts3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ int iIdx, /* Index of new output segment */ Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */ IncrmergeWriter *pWriter /* Populate this object */ ){ int rc; /* Return Code */ int i; /* Iterator variable */ int nLeafEst = 0; /* Blocks allocated for leaf nodes */ sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */ sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */ /* Calculate nLeafEst. */ rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pLeafEst, 1, iAbsLevel); sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment); if( SQLITE_ROW==sqlite3_step(pLeafEst) ){ nLeafEst = sqlite3_column_int(pLeafEst, 0); } rc = sqlite3_reset(pLeafEst); } if( rc!=SQLITE_OK ) return rc; /* Calculate the first block to use in the output segment */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){ pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0); pWriter->iEnd = pWriter->iStart - 1; pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT; } rc = sqlite3_reset(pFirstBlock); } if( rc!=SQLITE_OK ) return rc; /* Insert the marker in the %_segments table to make sure nobody tries ** to steal the space just allocated. This is also used to identify ** appendable segments. */ rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0); if( rc!=SQLITE_OK ) return rc; pWriter->iAbsLevel = iAbsLevel; pWriter->nLeafEst = nLeafEst; pWriter->iIdx = iIdx; /* Set up the array of NodeWriter objects */ for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){ pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; } return SQLITE_OK; } /* ** Remove an entry from the %_segdir table. This involves running the ** following two statements: ** ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx ** ** The DELETE statement removes the specific %_segdir level. The UPDATE ** statement ensures that the remaining segments have contiguously allocated ** idx values. */ static int fts3RemoveSegdirEntry( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level to delete from */ int iIdx /* Index of %_segdir entry to delete */ ){ int rc; /* Return code */ sqlite3_stmt *pDelete = 0; /* DELETE statement */ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDelete, 1, iAbsLevel); sqlite3_bind_int(pDelete, 2, iIdx); sqlite3_step(pDelete); rc = sqlite3_reset(pDelete); } return rc; } /* ** One or more segments have just been removed from absolute level iAbsLevel. ** Update the 'idx' values of the remaining segments in the level so that ** the idx values are a contiguous sequence starting from 0. */ static int fts3RepackSegdirLevel( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iAbsLevel /* Absolute level to repack */ ){ int rc; /* Return code */ int *aIdx = 0; /* Array of remaining idx values */ int nIdx = 0; /* Valid entries in aIdx[] */ int nAlloc = 0; /* Allocated size of aIdx[] */ int i; /* Iterator variable */ sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */ sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */ rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0); if( rc==SQLITE_OK ){ int rc2; sqlite3_bind_int64(pSelect, 1, iAbsLevel); while( SQLITE_ROW==sqlite3_step(pSelect) ){ if( nIdx>=nAlloc ){ int *aNew; nAlloc += 16; aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int)); if( !aNew ){ rc = SQLITE_NOMEM; break; } aIdx = aNew; } aIdx[nIdx++] = sqlite3_column_int(pSelect, 0); } rc2 = sqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } if( rc==SQLITE_OK ){ rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0); } if( rc==SQLITE_OK ){ sqlite3_bind_int64(pUpdate, 2, iAbsLevel); } assert( p->bIgnoreSavepoint==0 ); p->bIgnoreSavepoint = 1; for(i=0; rc==SQLITE_OK && i<nIdx; i++){ if( aIdx[i]!=i ){ sqlite3_bind_int(pUpdate, 3, aIdx[i]); sqlite3_bind_int(pUpdate, 1, i); sqlite3_step(pUpdate); rc = sqlite3_reset(pUpdate); } } p->bIgnoreSavepoint = 0; sqlite3_free(aIdx); return rc; } static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){ pNode->a[0] = (char)iHeight; if( iChild ){ assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) ); pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild); }else{ assert( pNode->nAlloc>=1 ); pNode->n = 1; } } /* ** The first two arguments are a pointer to and the size of a segment b-tree ** node. The node may be a leaf or an internal node. ** ** This function creates a new node image in blob object *pNew by copying ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes) ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode. */ static int fts3TruncateNode( const char *aNode, /* Current node image */ int nNode, /* Size of aNode in bytes */ Blob *pNew, /* OUT: Write new node image here */ const char *zTerm, /* Omit all terms smaller than this */ int nTerm, /* Size of zTerm in bytes */ sqlite3_int64 *piBlock /* OUT: Block number in next layer down */ ){ NodeReader reader; /* Reader object */ Blob prev = {0, 0, 0}; /* Previous term written to new node */ int rc = SQLITE_OK; /* Return code */ int bLeaf = aNode[0]=='\0'; /* True for a leaf node */ /* Allocate required output space */ blobGrowBuffer(pNew, nNode, &rc); if( rc!=SQLITE_OK ) return rc; pNew->n = 0; /* Populate new node buffer */ for(rc = nodeReaderInit(&reader, aNode, nNode); rc==SQLITE_OK && reader.aNode; rc = nodeReaderNext(&reader) ){ if( pNew->n==0 ){ int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm); if( res<0 || (bLeaf==0 && res==0) ) continue; fts3StartNode(pNew, (int)aNode[0], reader.iChild); *piBlock = reader.iChild; } rc = fts3AppendToNode( pNew, &prev, reader.term.a, reader.term.n, reader.aDoclist, reader.nDoclist ); if( rc!=SQLITE_OK ) break; } if( pNew->n==0 ){ fts3StartNode(pNew, (int)aNode[0], reader.iChild); *piBlock = reader.iChild; } assert( pNew->n<=pNew->nAlloc ); nodeReaderRelease(&reader); sqlite3_free(prev.a); return rc; } /* ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute ** level iAbsLevel. This may involve deleting entries from the %_segments ** table, and modifying existing entries in both the %_segments and %_segdir ** tables. ** ** SQLITE_OK is returned if the segment is updated successfully. Or an ** SQLite error code otherwise. */ static int fts3TruncateSegment( Fts3Table *p, /* FTS3 table handle */ sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */ int iIdx, /* Index within level of segment to modify */ const char *zTerm, /* Remove terms smaller than this */ int nTerm /* Number of bytes in buffer zTerm */ ){ int rc = SQLITE_OK; /* Return code */ Blob root = {0,0,0}; /* New root page image */ Blob block = {0,0,0}; /* Buffer used for any other block */ sqlite3_int64 iBlock = 0; /* Block id */ sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */ sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */ sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0); if( rc==SQLITE_OK ){ int rc2; /* sqlite3_reset() return code */ sqlite3_bind_int64(pFetch, 1, iAbsLevel); sqlite3_bind_int(pFetch, 2, iIdx); if( SQLITE_ROW==sqlite3_step(pFetch) ){ const char *aRoot = sqlite3_column_blob(pFetch, 4); int nRoot = sqlite3_column_bytes(pFetch, 4); iOldStart = sqlite3_column_int64(pFetch, 1); rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock); } rc2 = sqlite3_reset(pFetch); if( rc==SQLITE_OK ) rc = rc2; } while( rc==SQLITE_OK && iBlock ){ char *aBlock = 0; int nBlock = 0; iNewStart = iBlock; rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0); if( rc==SQLITE_OK ){ rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock); } if( rc==SQLITE_OK ){ rc = fts3WriteSegment(p, iNewStart, block.a, block.n); } sqlite3_free(aBlock); } /* Variable iNewStart now contains the first valid leaf node. */ if( rc==SQLITE_OK && iNewStart ){ sqlite3_stmt *pDel = 0; rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDel, 1, iOldStart); sqlite3_bind_int64(pDel, 2, iNewStart-1); sqlite3_step(pDel); rc = sqlite3_reset(pDel); } } if( rc==SQLITE_OK ){ sqlite3_stmt *pChomp = 0; rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pChomp, 1, iNewStart); sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC); sqlite3_bind_int64(pChomp, 3, iAbsLevel); sqlite3_bind_int(pChomp, 4, iIdx); sqlite3_step(pChomp); rc = sqlite3_reset(pChomp); } } sqlite3_free(root.a); sqlite3_free(block.a); return rc; } /* ** This function is called after an incrmental-merge operation has run to ** merge (or partially merge) two or more segments from absolute level ** iAbsLevel. ** ** Each input segment is either removed from the db completely (if all of ** its data was copied to the output segment by the incrmerge operation) ** or modified in place so that it no longer contains those entries that ** have been duplicated in the output segment. */ static int fts3IncrmergeChomp( Fts3Table *p, /* FTS table handle */ sqlite3_int64 iAbsLevel, /* Absolute level containing segments */ Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */ int *pnRem /* Number of segments not deleted */ ){ int i; int nRem = 0; int rc = SQLITE_OK; for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){ Fts3SegReader *pSeg = 0; int j; /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding ** somewhere in the pCsr->apSegment[] array. */ for(j=0; ALWAYS(j<pCsr->nSegment); j++){ pSeg = pCsr->apSegment[j]; if( pSeg->iIdx==i ) break; } assert( j<pCsr->nSegment && pSeg->iIdx==i ); if( pSeg->aNode==0 ){ /* Seg-reader is at EOF. Remove the entire input segment. */ rc = fts3DeleteSegment(p, pSeg); if( rc==SQLITE_OK ){ rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx); } *pnRem = 0; }else{ /* The incremental merge did not copy all the data from this ** segment to the upper level. The segment is modified in place ** so that it contains no keys smaller than zTerm/nTerm. */ const char *zTerm = pSeg->zTerm; int nTerm = pSeg->nTerm; rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm); nRem++; } } if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){ rc = fts3RepackSegdirLevel(p, iAbsLevel); } *pnRem = nRem; return rc; } /* ** Store an incr-merge hint in the database. */ static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){ sqlite3_stmt *pReplace = 0; int rc; /* Return code */ rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT); sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC); sqlite3_step(pReplace); rc = sqlite3_reset(pReplace); } return rc; } /* ** Load an incr-merge hint from the database. The incr-merge hint, if one ** exists, is stored in the rowid==1 row of the %_stat table. ** ** If successful, populate blob *pHint with the value read from the %_stat ** table and return SQLITE_OK. Otherwise, if an error occurs, return an ** SQLite error code. */ static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){ sqlite3_stmt *pSelect = 0; int rc; pHint->n = 0; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0); if( rc==SQLITE_OK ){ int rc2; sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT); if( SQLITE_ROW==sqlite3_step(pSelect) ){ const char *aHint = sqlite3_column_blob(pSelect, 0); int nHint = sqlite3_column_bytes(pSelect, 0); if( aHint ){ blobGrowBuffer(pHint, nHint, &rc); if( rc==SQLITE_OK ){ memcpy(pHint->a, aHint, nHint); pHint->n = nHint; } } } rc2 = sqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } return rc; } /* ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry ** consists of two varints, the absolute level number of the input segments ** and the number of input segments. ** ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs, ** set *pRc to an SQLite error code before returning. */ static void fts3IncrmergeHintPush( Blob *pHint, /* Hint blob to append to */ i64 iAbsLevel, /* First varint to store in hint */ int nInput, /* Second varint to store in hint */ int *pRc /* IN/OUT: Error code */ ){ blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc); if( *pRc==SQLITE_OK ){ pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel); pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput); } } /* ** Read the last entry (most recently pushed) from the hint blob *pHint ** and then remove the entry. Write the two values read to *piAbsLevel and ** *pnInput before returning. ** ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB. */ static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){ const int nHint = pHint->n; int i; i = pHint->n-2; while( i>0 && (pHint->a[i-1] & 0x80) ) i--; while( i>0 && (pHint->a[i-1] & 0x80) ) i--; pHint->n = i; i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel); i += fts3GetVarint32(&pHint->a[i], pnInput); if( i!=nHint ) return FTS_CORRUPT_VTAB; return SQLITE_OK; } /* ** Attempt an incremental merge that writes nMerge leaf blocks. ** ** Incremental merges happen nMin segments at a time. The segments ** to be merged are the nMin oldest segments (the ones with the smallest ** values for the _segdir.idx field) in the highest level that contains ** at least nMin segments. Multiple merges might occur in an attempt to ** write the quota of nMerge leaf blocks. */ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ int rc; /* Return code */ int nRem = nMerge; /* Number of leaf pages yet to be written */ Fts3MultiSegReader *pCsr; /* Cursor used to read input data */ Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */ IncrmergeWriter *pWriter; /* Writer object */ int nSeg = 0; /* Number of input segments */ sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */ Blob hint = {0, 0, 0}; /* Hint read from %_stat table */ int bDirtyHint = 0; /* True if blob 'hint' has been modified */ /* Allocate space for the cursor, filter and writer objects */ const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter); pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc); if( !pWriter ) return SQLITE_NOMEM; pFilter = (Fts3SegFilter *)&pWriter[1]; pCsr = (Fts3MultiSegReader *)&pFilter[1]; rc = fts3IncrmergeHintLoad(p, &hint); while( rc==SQLITE_OK && nRem>0 ){ const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex; sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */ int bUseHint = 0; /* True if attempting to append */ int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */ /* Search the %_segdir table for the absolute level with the smallest ** relative level number that contains at least nMin segments, if any. ** If one is found, set iAbsLevel to the absolute level number and ** nSeg to nMin. If no level with at least nMin segments can be found, ** set nSeg to -1. */ rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0); sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin)); if( sqlite3_step(pFindLevel)==SQLITE_ROW ){ iAbsLevel = sqlite3_column_int64(pFindLevel, 0); nSeg = sqlite3_column_int(pFindLevel, 1); assert( nSeg>=2 ); }else{ nSeg = -1; } rc = sqlite3_reset(pFindLevel); /* If the hint read from the %_stat table is not empty, check if the ** last entry in it specifies a relative level smaller than or equal ** to the level identified by the block above (if any). If so, this ** iteration of the loop will work on merging at the hinted level. */ if( rc==SQLITE_OK && hint.n ){ int nHint = hint.n; sqlite3_int64 iHintAbsLevel = 0; /* Hint level */ int nHintSeg = 0; /* Hint number of segments */ rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg); if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){ iAbsLevel = iHintAbsLevel; nSeg = nHintSeg; bUseHint = 1; bDirtyHint = 1; }else{ /* This undoes the effect of the HintPop() above - so that no entry ** is removed from the hint blob. */ hint.n = nHint; } } /* If nSeg is less that zero, then there is no level with at least ** nMin segments and no hint in the %_stat table. No work to do. ** Exit early in this case. */ if( nSeg<0 ) break; /* Open a cursor to iterate through the contents of the oldest nSeg ** indexes of absolute level iAbsLevel. If this cursor is opened using ** the 'hint' parameters, it is possible that there are less than nSeg ** segments available in level iAbsLevel. In this case, no work is ** done on iAbsLevel - fall through to the next iteration of the loop ** to start work on some other level. */ memset(pWriter, 0, nAlloc); pFilter->flags = FTS3_SEGMENT_REQUIRE_POS; if( rc==SQLITE_OK ){ rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx); assert( bUseHint==1 || bUseHint==0 ); if( iIdx==0 || (bUseHint && iIdx==1) ){ int bIgnore = 0; rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore); if( bIgnore ){ pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY; } } } if( rc==SQLITE_OK ){ rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr); } if( SQLITE_OK==rc && pCsr->nSegment==nSeg && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter)) && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr)) ){ if( bUseHint && iIdx>0 ){ const char *zKey = pCsr->zTerm; int nKey = pCsr->nTerm; rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter); }else{ rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter); } if( rc==SQLITE_OK && pWriter->nLeafEst ){ fts3LogMerge(nSeg, iAbsLevel); do { rc = fts3IncrmergeAppend(p, pWriter, pCsr); if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr); if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK; }while( rc==SQLITE_ROW ); /* Update or delete the input segments */ if( rc==SQLITE_OK ){ nRem -= (1 + pWriter->nWork); rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg); if( nSeg!=0 ){ bDirtyHint = 1; fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc); } } } if( nSeg!=0 ){ pWriter->nLeafData = pWriter->nLeafData * -1; } fts3IncrmergeRelease(p, pWriter, &rc); if( nSeg==0 && pWriter->bNoLeafData==0 ){ fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData); } } sqlite3Fts3SegReaderFinish(pCsr); } /* Write the hint values into the %_stat table for the next incr-merger */ if( bDirtyHint && rc==SQLITE_OK ){ rc = fts3IncrmergeHintStore(p, &hint); } sqlite3_free(pWriter); sqlite3_free(hint.a); return rc; } /* ** Convert the text beginning at *pz into an integer and return ** its value. Advance *pz to point to the first character past ** the integer. */ static int fts3Getint(const char **pz){ const char *z = *pz; int i = 0; while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0'; *pz = z; return i; } /* ** Process statements of the form: ** ** INSERT INTO table(table) VALUES('merge=A,B'); ** ** A and B are integers that decode to be the number of leaf pages ** written for the merge, and the minimum number of segments on a level ** before it will be selected for a merge, respectively. */ static int fts3DoIncrmerge( Fts3Table *p, /* FTS3 table handle */ const char *zParam /* Nul-terminated string containing "A,B" */ ){ int rc; int nMin = (FTS3_MERGE_COUNT / 2); int nMerge = 0; const char *z = zParam; /* Read the first integer value */ nMerge = fts3Getint(&z); /* If the first integer value is followed by a ',', read the second ** integer value. */ if( z[0]==',' && z[1]!='\0' ){ z++; nMin = fts3Getint(&z); } if( z[0]!='\0' || nMin<2 ){ rc = SQLITE_ERROR; }else{ rc = SQLITE_OK; if( !p->bHasStat ){ assert( p->bFts4==0 ); sqlite3Fts3CreateStatTable(&rc, p); } if( rc==SQLITE_OK ){ rc = sqlite3Fts3Incrmerge(p, nMerge, nMin); } sqlite3Fts3SegmentsClose(p); } return rc; } /* ** Process statements of the form: ** ** INSERT INTO table(table) VALUES('automerge=X'); ** ** where X is an integer. X==0 means to turn automerge off. X!=0 means ** turn it on. The setting is persistent. */ static int fts3DoAutoincrmerge( Fts3Table *p, /* FTS3 table handle */ const char *zParam /* Nul-terminated string containing boolean */ ){ int rc = SQLITE_OK; sqlite3_stmt *pStmt = 0; p->nAutoincrmerge = fts3Getint(&zParam); if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){ p->nAutoincrmerge = 8; } if( !p->bHasStat ){ assert( p->bFts4==0 ); sqlite3Fts3CreateStatTable(&rc, p); if( rc ) return rc; } rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); if( rc ) return rc; sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); return rc; } /* ** Return a 64-bit checksum for the FTS index entry specified by the ** arguments to this function. */ static u64 fts3ChecksumEntry( const char *zTerm, /* Pointer to buffer containing term */ int nTerm, /* Size of zTerm in bytes */ int iLangid, /* Language id for current row */ int iIndex, /* Index (0..Fts3Table.nIndex-1) */ i64 iDocid, /* Docid for current row. */ int iCol, /* Column number */ int iPos /* Position */ ){ int i; u64 ret = (u64)iDocid; ret += (ret<<3) + iLangid; ret += (ret<<3) + iIndex; ret += (ret<<3) + iCol; ret += (ret<<3) + iPos; for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i]; return ret; } /* ** Return a checksum of all entries in the FTS index that correspond to ** language id iLangid. The checksum is calculated by XORing the checksums ** of each individual entry (see fts3ChecksumEntry()) together. ** ** If successful, the checksum value is returned and *pRc set to SQLITE_OK. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The ** return value is undefined in this case. */ static u64 fts3ChecksumIndex( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language id to return cksum for */ int iIndex, /* Index to cksum (0..p->nIndex-1) */ int *pRc /* OUT: Return code */ ){ Fts3SegFilter filter; Fts3MultiSegReader csr; int rc; u64 cksum = 0; assert( *pRc==SQLITE_OK ); memset(&filter, 0, sizeof(filter)); memset(&csr, 0, sizeof(csr)); filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; filter.flags |= FTS3_SEGMENT_SCAN; rc = sqlite3Fts3SegReaderCursor( p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr ); if( rc==SQLITE_OK ){ rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); } if( rc==SQLITE_OK ){ while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){ char *pCsr = csr.aDoclist; char *pEnd = &pCsr[csr.nDoclist]; i64 iDocid = 0; i64 iCol = 0; i64 iPos = 0; pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); while( pCsr<pEnd ){ i64 iVal = 0; pCsr += sqlite3Fts3GetVarint(pCsr, &iVal); if( pCsr<pEnd ){ if( iVal==0 || iVal==1 ){ iCol = 0; iPos = 0; if( iVal ){ pCsr += sqlite3Fts3GetVarint(pCsr, &iCol); }else{ pCsr += sqlite3Fts3GetVarint(pCsr, &iVal); iDocid += iVal; } }else{ iPos += (iVal - 2); cksum = cksum ^ fts3ChecksumEntry( csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid, (int)iCol, (int)iPos ); } } } } } sqlite3Fts3SegReaderFinish(&csr); *pRc = rc; return cksum; } /* ** Check if the contents of the FTS index match the current contents of the ** content table. If no error occurs and the contents do match, set *pbOk ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk ** to false before returning. ** ** If an error occurs (e.g. an OOM or IO error), return an SQLite error ** code. The final value of *pbOk is undefined in this case. */ static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){ int rc = SQLITE_OK; /* Return code */ u64 cksum1 = 0; /* Checksum based on FTS index contents */ u64 cksum2 = 0; /* Checksum based on %_content contents */ sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */ /* This block calculates the checksum according to the FTS index. */ rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); if( rc==SQLITE_OK ){ int rc2; sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); sqlite3_bind_int(pAllLangid, 2, p->nIndex); while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){ int iLangid = sqlite3_column_int(pAllLangid, 0); int i; for(i=0; i<p->nIndex; i++){ cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc); } } rc2 = sqlite3_reset(pAllLangid); if( rc==SQLITE_OK ) rc = rc2; } /* This block calculates the checksum according to the %_content table */ if( rc==SQLITE_OK ){ sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule; sqlite3_stmt *pStmt = 0; char *zSql; zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); if( !zSql ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ i64 iDocid = sqlite3_column_int64(pStmt, 0); int iLang = langidFromSelect(p, pStmt); int iCol; for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){ if( p->abNotindexed[iCol]==0 ){ const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1); int nText = sqlite3_column_bytes(pStmt, iCol+1); sqlite3_tokenizer_cursor *pT = 0; rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT); while( rc==SQLITE_OK ){ char const *zToken; /* Buffer containing token */ int nToken = 0; /* Number of bytes in token */ int iDum1 = 0, iDum2 = 0; /* Dummy variables */ int iPos = 0; /* Position of token in zText */ rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos); if( rc==SQLITE_OK ){ int i; cksum2 = cksum2 ^ fts3ChecksumEntry( zToken, nToken, iLang, 0, iDocid, iCol, iPos ); for(i=1; i<p->nIndex; i++){ if( p->aIndex[i].nPrefix<=nToken ){ cksum2 = cksum2 ^ fts3ChecksumEntry( zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos ); } } } } if( pT ) pModule->xClose(pT); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } } } sqlite3_finalize(pStmt); } *pbOk = (cksum1==cksum2); return rc; } /* ** Run the integrity-check. If no error occurs and the current contents of ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB. ** ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite ** error code. ** ** The integrity-check works as follows. For each token and indexed token ** prefix in the document set, a 64-bit checksum is calculated (by code ** in fts3ChecksumEntry()) based on the following: ** ** + The index number (0 for the main index, 1 for the first prefix ** index etc.), ** + The token (or token prefix) text itself, ** + The language-id of the row it appears in, ** + The docid of the row it appears in, ** + The column it appears in, and ** + The tokens position within that column. ** ** The checksums for all entries in the index are XORed together to create ** a single checksum for the entire index. ** ** The integrity-check code calculates the same checksum in two ways: ** ** 1. By scanning the contents of the FTS index, and ** 2. By scanning and tokenizing the content table. ** ** If the two checksums are identical, the integrity-check is deemed to have ** passed. */ static int fts3DoIntegrityCheck( Fts3Table *p /* FTS3 table handle */ ){ int rc; int bOk = 0; rc = fts3IntegrityCheck(p, &bOk); if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB; return rc; } /* ** Handle a 'special' INSERT of the form: ** ** "INSERT INTO tbl(tbl) VALUES(<expr>)" ** ** Argument pVal contains the result of <expr>. Currently the only ** meaningful value to insert is the text 'optimize'. */ static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ int rc; /* Return Code */ const char *zVal = (const char *)sqlite3_value_text(pVal); int nVal = sqlite3_value_bytes(pVal); if( !zVal ){ return SQLITE_NOMEM; }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){ rc = fts3DoOptimize(p, 0); }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){ rc = fts3DoRebuild(p); }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){ rc = fts3DoIntegrityCheck(p); }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){ rc = fts3DoIncrmerge(p, &zVal[6]); }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){ rc = fts3DoAutoincrmerge(p, &zVal[10]); #ifdef SQLITE_TEST }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ p->nNodeSize = atoi(&zVal[9]); rc = SQLITE_OK; }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ p->nMaxPendingData = atoi(&zVal[11]); rc = SQLITE_OK; }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){ p->bNoIncrDoclist = atoi(&zVal[21]); rc = SQLITE_OK; #endif }else{ rc = SQLITE_ERROR; } return rc; } #ifndef SQLITE_DISABLE_FTS4_DEFERRED /* ** Delete all cached deferred doclists. Deferred doclists are cached ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function. */ SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){ Fts3DeferredToken *pDef; for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){ fts3PendingListDelete(pDef->pList); pDef->pList = 0; } } /* ** Free all entries in the pCsr->pDeffered list. Entries are added to ** this list using sqlite3Fts3DeferToken(). */ SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){ Fts3DeferredToken *pDef; Fts3DeferredToken *pNext; for(pDef=pCsr->pDeferred; pDef; pDef=pNext){ pNext = pDef->pNext; fts3PendingListDelete(pDef->pList); sqlite3_free(pDef); } pCsr->pDeferred = 0; } /* ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list ** based on the row that pCsr currently points to. ** ** A deferred-doclist is like any other doclist with position information ** included, except that it only contains entries for a single row of the ** table, not for all rows. */ SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){ int rc = SQLITE_OK; /* Return code */ if( pCsr->pDeferred ){ int i; /* Used to iterate through table columns */ sqlite3_int64 iDocid; /* Docid of the row pCsr points to */ Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; sqlite3_tokenizer *pT = p->pTokenizer; sqlite3_tokenizer_module const *pModule = pT->pModule; assert( pCsr->isRequireSeek==0 ); iDocid = sqlite3_column_int64(pCsr->pStmt, 0); for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){ if( p->abNotindexed[i]==0 ){ const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1); sqlite3_tokenizer_cursor *pTC = 0; rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC); while( rc==SQLITE_OK ){ char const *zToken; /* Buffer containing token */ int nToken = 0; /* Number of bytes in token */ int iDum1 = 0, iDum2 = 0; /* Dummy variables */ int iPos = 0; /* Position of token in zText */ rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos); for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ Fts3PhraseToken *pPT = pDef->pToken; if( (pDef->iCol>=p->nColumn || pDef->iCol==i) && (pPT->bFirst==0 || iPos==0) && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken)) && (0==memcmp(zToken, pPT->z, pPT->n)) ){ fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc); } } } if( pTC ) pModule->xClose(pTC); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } } for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ if( pDef->pList ){ rc = fts3PendingListAppendVarint(&pDef->pList, 0); } } } return rc; } SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList( Fts3DeferredToken *p, char **ppData, int *pnData ){ char *pRet; int nSkip; sqlite3_int64 dummy; *ppData = 0; *pnData = 0; if( p->pList==0 ){ return SQLITE_OK; } pRet = (char *)sqlite3_malloc(p->pList->nData); if( !pRet ) return SQLITE_NOMEM; nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy); *pnData = p->pList->nData - nSkip; *ppData = pRet; memcpy(pRet, &p->pList->aData[nSkip], *pnData); return SQLITE_OK; } /* ** Add an entry for token pToken to the pCsr->pDeferred list. */ SQLITE_PRIVATE int sqlite3Fts3DeferToken( Fts3Cursor *pCsr, /* Fts3 table cursor */ Fts3PhraseToken *pToken, /* Token to defer */ int iCol /* Column that token must appear in (or -1) */ ){ Fts3DeferredToken *pDeferred; pDeferred = sqlite3_malloc(sizeof(*pDeferred)); if( !pDeferred ){ return SQLITE_NOMEM; } memset(pDeferred, 0, sizeof(*pDeferred)); pDeferred->pToken = pToken; pDeferred->pNext = pCsr->pDeferred; pDeferred->iCol = iCol; pCsr->pDeferred = pDeferred; assert( pToken->pDeferred==0 ); pToken->pDeferred = pDeferred; return SQLITE_OK; } #endif /* ** SQLite value pRowid contains the rowid of a row that may or may not be ** present in the FTS3 table. If it is, delete it and adjust the contents ** of subsiduary data structures accordingly. */ static int fts3DeleteByRowid( Fts3Table *p, sqlite3_value *pRowid, int *pnChng, /* IN/OUT: Decrement if row is deleted */ u32 *aSzDel ){ int rc = SQLITE_OK; /* Return code */ int bFound = 0; /* True if *pRowid really is in the table */ fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound); if( bFound && rc==SQLITE_OK ){ int isEmpty = 0; /* Deleting *pRowid leaves the table empty */ rc = fts3IsEmpty(p, pRowid, &isEmpty); if( rc==SQLITE_OK ){ if( isEmpty ){ /* Deleting this row means the whole table is empty. In this case ** delete the contents of all three tables and throw away any ** data in the pendingTerms hash table. */ rc = fts3DeleteAll(p, 1); *pnChng = 0; memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2); }else{ *pnChng = *pnChng - 1; if( p->zContentTbl==0 ){ fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid); } if( p->bHasDocsize ){ fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid); } } } } return rc; } /* ** This function does the work for the xUpdate method of FTS3 virtual ** tables. The schema of the virtual table being: ** ** CREATE TABLE <table name>( ** <user columns>, ** <table name> HIDDEN, ** docid HIDDEN, ** <langid> HIDDEN ** ); ** ** */ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( sqlite3_vtab *pVtab, /* FTS3 vtab object */ int nArg, /* Size of argument array */ sqlite3_value **apVal, /* Array of arguments */ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ ){ Fts3Table *p = (Fts3Table *)pVtab; int rc = SQLITE_OK; /* Return Code */ int isRemove = 0; /* True for an UPDATE or DELETE */ u32 *aSzIns = 0; /* Sizes of inserted documents */ u32 *aSzDel = 0; /* Sizes of deleted documents */ int nChng = 0; /* Net change in number of documents */ int bInsertDone = 0; /* At this point it must be known if the %_stat table exists or not. ** So bHasStat may not be 2. */ assert( p->bHasStat==0 || p->bHasStat==1 ); assert( p->pSegments==0 ); assert( nArg==1 /* DELETE operations */ || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */ ); /* Check for a "special" INSERT operation. One of the form: ** ** INSERT INTO xyz(xyz) VALUES('command'); */ if( nArg>1 && sqlite3_value_type(apVal[0])==SQLITE_NULL && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){ rc = fts3SpecialInsert(p, apVal[p->nColumn+2]); goto update_out; } if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){ rc = SQLITE_CONSTRAINT; goto update_out; } /* Allocate space to hold the change in document sizes */ aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 ); if( aSzDel==0 ){ rc = SQLITE_NOMEM; goto update_out; } aSzIns = &aSzDel[p->nColumn+1]; memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2); rc = fts3Writelock(p); if( rc!=SQLITE_OK ) goto update_out; /* If this is an INSERT operation, or an UPDATE that modifies the rowid ** value, then this operation requires constraint handling. ** ** If the on-conflict mode is REPLACE, this means that the existing row ** should be deleted from the database before inserting the new row. Or, ** if the on-conflict mode is other than REPLACE, then this method must ** detect the conflict and return SQLITE_CONSTRAINT before beginning to ** modify the database file. */ if( nArg>1 && p->zContentTbl==0 ){ /* Find the value object that holds the new rowid value. */ sqlite3_value *pNewRowid = apVal[3+p->nColumn]; if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){ pNewRowid = apVal[1]; } if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( sqlite3_value_type(apVal[0])==SQLITE_NULL || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid) )){ /* The new rowid is not NULL (in this case the rowid will be ** automatically assigned and there is no chance of a conflict), and ** the statement is either an INSERT or an UPDATE that modifies the ** rowid column. So if the conflict mode is REPLACE, then delete any ** existing row with rowid=pNewRowid. ** ** Or, if the conflict mode is not REPLACE, insert the new record into ** the %_content table. If we hit the duplicate rowid constraint (or any ** other error) while doing so, return immediately. ** ** This branch may also run if pNewRowid contains a value that cannot ** be losslessly converted to an integer. In this case, the eventual ** call to fts3InsertData() (either just below or further on in this ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is ** invoked, it will delete zero rows (since no row will have ** docid=$pNewRowid if $pNewRowid is not an integer value). */ if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){ rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel); }else{ rc = fts3InsertData(p, apVal, pRowid); bInsertDone = 1; } } } if( rc!=SQLITE_OK ){ goto update_out; } /* If this is a DELETE or UPDATE operation, remove the old record. */ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER ); rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel); isRemove = 1; } /* If this is an INSERT or UPDATE operation, insert the new record. */ if( nArg>1 && rc==SQLITE_OK ){ int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]); if( bInsertDone==0 ){ rc = fts3InsertData(p, apVal, pRowid); if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){ rc = FTS_CORRUPT_VTAB; } } if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){ rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid); } if( rc==SQLITE_OK ){ assert( p->iPrevDocid==*pRowid ); rc = fts3InsertTerms(p, iLangid, apVal, aSzIns); } if( p->bHasDocsize ){ fts3InsertDocsize(&rc, p, aSzIns); } nChng++; } if( p->bFts4 ){ fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng); } update_out: sqlite3_free(aSzDel); sqlite3Fts3SegmentsClose(p); return rc; } /* ** Flush any data in the pending-terms hash table to disk. If successful, ** merge all segments in the database (including the new segment, if ** there was any data to flush) into a single segment. */ SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){ int rc; rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0); if( rc==SQLITE_OK ){ rc = fts3DoOptimize(p, 1); if( rc==SQLITE_OK || rc==SQLITE_DONE ){ int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); if( rc2!=SQLITE_OK ) rc = rc2; }else{ sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0); sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); } } sqlite3Fts3SegmentsClose(p); return rc; } #endif /************** End of fts3_write.c ******************************************/ /************** Begin file fts3_snippet.c ************************************/ /* ** 2009 Oct 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <string.h> */ /* #include <assert.h> */ /* ** Characters that may appear in the second argument to matchinfo(). */ #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */ #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */ #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */ #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */ #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */ #define FTS3_MATCHINFO_LCS 's' /* nCol values */ #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */ #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */ #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */ /* ** The default value for the second argument to matchinfo(). */ #define FTS3_MATCHINFO_DEFAULT "pcx" /* ** Used as an fts3ExprIterate() context when loading phrase doclists to ** Fts3Expr.aDoclist[]/nDoclist. */ typedef struct LoadDoclistCtx LoadDoclistCtx; struct LoadDoclistCtx { Fts3Cursor *pCsr; /* FTS3 Cursor */ int nPhrase; /* Number of phrases seen so far */ int nToken; /* Number of tokens seen so far */ }; /* ** The following types are used as part of the implementation of the ** fts3BestSnippet() routine. */ typedef struct SnippetIter SnippetIter; typedef struct SnippetPhrase SnippetPhrase; typedef struct SnippetFragment SnippetFragment; struct SnippetIter { Fts3Cursor *pCsr; /* Cursor snippet is being generated from */ int iCol; /* Extract snippet from this column */ int nSnippet; /* Requested snippet length (in tokens) */ int nPhrase; /* Number of phrases in query */ SnippetPhrase *aPhrase; /* Array of size nPhrase */ int iCurrent; /* First token of current snippet */ }; struct SnippetPhrase { int nToken; /* Number of tokens in phrase */ char *pList; /* Pointer to start of phrase position list */ int iHead; /* Next value in position list */ char *pHead; /* Position list data following iHead */ int iTail; /* Next value in trailing position list */ char *pTail; /* Position list data following iTail */ }; struct SnippetFragment { int iCol; /* Column snippet is extracted from */ int iPos; /* Index of first token in snippet */ u64 covered; /* Mask of query phrases covered */ u64 hlmask; /* Mask of snippet terms to highlight */ }; /* ** This type is used as an fts3ExprIterate() context object while ** accumulating the data returned by the matchinfo() function. */ typedef struct MatchInfo MatchInfo; struct MatchInfo { Fts3Cursor *pCursor; /* FTS3 Cursor */ int nCol; /* Number of columns in table */ int nPhrase; /* Number of matchable phrases in query */ sqlite3_int64 nDoc; /* Number of docs in database */ char flag; u32 *aMatchinfo; /* Pre-allocated buffer */ }; /* ** An instance of this structure is used to manage a pair of buffers, each ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below ** for details. */ struct MatchinfoBuffer { u8 aRef[3]; int nElem; int bGlobal; /* Set if global data is loaded */ char *zMatchinfo; u32 aMatchinfo[1]; }; /* ** The snippet() and offsets() functions both return text values. An instance ** of the following structure is used to accumulate those values while the ** functions are running. See fts3StringAppend() for details. */ typedef struct StrBuffer StrBuffer; struct StrBuffer { char *z; /* Pointer to buffer containing string */ int n; /* Length of z in bytes (excl. nul-term) */ int nAlloc; /* Allocated size of buffer z in bytes */ }; /************************************************************************* ** Start of MatchinfoBuffer code. */ /* ** Allocate a two-slot MatchinfoBuffer object. */ static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){ MatchinfoBuffer *pRet; int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer); int nStr = (int)strlen(zMatchinfo); pRet = sqlite3_malloc(nByte + nStr+1); if( pRet ){ memset(pRet, 0, nByte); pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet; pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1); pRet->nElem = nElem; pRet->zMatchinfo = ((char*)pRet) + nByte; memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1); pRet->aRef[0] = 1; } return pRet; } static void fts3MIBufferFree(void *p){ MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]); assert( (u32*)p==&pBuf->aMatchinfo[1] || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] ); if( (u32*)p==&pBuf->aMatchinfo[1] ){ pBuf->aRef[1] = 0; }else{ pBuf->aRef[2] = 0; } if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){ sqlite3_free(pBuf); } } static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ void (*xRet)(void*) = 0; u32 *aOut = 0; if( p->aRef[1]==0 ){ p->aRef[1] = 1; aOut = &p->aMatchinfo[1]; xRet = fts3MIBufferFree; } else if( p->aRef[2]==0 ){ p->aRef[2] = 1; aOut = &p->aMatchinfo[p->nElem+2]; xRet = fts3MIBufferFree; }else{ aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32)); if( aOut ){ xRet = sqlite3_free; if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32)); } } *paOut = aOut; return xRet; } static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){ p->bGlobal = 1; memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32)); } /* ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew() */ SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){ if( p ){ assert( p->aRef[0]==1 ); p->aRef[0] = 0; if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){ sqlite3_free(p); } } } /* ** End of MatchinfoBuffer code. *************************************************************************/ /* ** This function is used to help iterate through a position-list. A position ** list is a list of unique integers, sorted from smallest to largest. Each ** element of the list is represented by an FTS3 varint that takes the value ** of the difference between the current element and the previous one plus ** two. For example, to store the position-list: ** ** 4 9 113 ** ** the three varints: ** ** 6 7 106 ** ** are encoded. ** ** When this function is called, *pp points to the start of an element of ** the list. *piPos contains the value of the previous entry in the list. ** After it returns, *piPos contains the value of the next element of the ** list and *pp is advanced to the following varint. */ static void fts3GetDeltaPosition(char **pp, int *piPos){ int iVal; *pp += fts3GetVarint32(*pp, &iVal); *piPos += (iVal-2); } /* ** Helper function for fts3ExprIterate() (see below). */ static int fts3ExprIterate2( Fts3Expr *pExpr, /* Expression to iterate phrases of */ int *piPhrase, /* Pointer to phrase counter */ int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ void *pCtx /* Second argument to pass to callback */ ){ int rc; /* Return code */ int eType = pExpr->eType; /* Type of expression node pExpr */ if( eType!=FTSQUERY_PHRASE ){ assert( pExpr->pLeft && pExpr->pRight ); rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx); if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){ rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx); } }else{ rc = x(pExpr, *piPhrase, pCtx); (*piPhrase)++; } return rc; } /* ** Iterate through all phrase nodes in an FTS3 query, except those that ** are part of a sub-tree that is the right-hand-side of a NOT operator. ** For each phrase node found, the supplied callback function is invoked. ** ** If the callback function returns anything other than SQLITE_OK, ** the iteration is abandoned and the error code returned immediately. ** Otherwise, SQLITE_OK is returned after a callback has been made for ** all eligible phrase nodes. */ static int fts3ExprIterate( Fts3Expr *pExpr, /* Expression to iterate phrases of */ int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ void *pCtx /* Second argument to pass to callback */ ){ int iPhrase = 0; /* Variable used as the phrase counter */ return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx); } /* ** This is an fts3ExprIterate() callback used while loading the doclists ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also ** fts3ExprLoadDoclists(). */ static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ int rc = SQLITE_OK; Fts3Phrase *pPhrase = pExpr->pPhrase; LoadDoclistCtx *p = (LoadDoclistCtx *)ctx; UNUSED_PARAMETER(iPhrase); p->nPhrase++; p->nToken += pPhrase->nToken; return rc; } /* ** Load the doclists for each phrase in the query associated with FTS3 cursor ** pCsr. ** ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable ** phrases in the expression (all phrases except those directly or ** indirectly descended from the right-hand-side of a NOT operator). If ** pnToken is not NULL, then it is set to the number of tokens in all ** matchable phrases of the expression. */ static int fts3ExprLoadDoclists( Fts3Cursor *pCsr, /* Fts3 cursor for current query */ int *pnPhrase, /* OUT: Number of phrases in query */ int *pnToken /* OUT: Number of tokens in query */ ){ int rc; /* Return Code */ LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */ sCtx.pCsr = pCsr; rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx); if( pnPhrase ) *pnPhrase = sCtx.nPhrase; if( pnToken ) *pnToken = sCtx.nToken; return rc; } static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ (*(int *)ctx)++; pExpr->iPhrase = iPhrase; return SQLITE_OK; } static int fts3ExprPhraseCount(Fts3Expr *pExpr){ int nPhrase = 0; (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase); return nPhrase; } /* ** Advance the position list iterator specified by the first two ** arguments so that it points to the first element with a value greater ** than or equal to parameter iNext. */ static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){ char *pIter = *ppIter; if( pIter ){ int iIter = *piIter; while( iIter<iNext ){ if( 0==(*pIter & 0xFE) ){ iIter = -1; pIter = 0; break; } fts3GetDeltaPosition(&pIter, &iIter); } *piIter = iIter; *ppIter = pIter; } } /* ** Advance the snippet iterator to the next candidate snippet. */ static int fts3SnippetNextCandidate(SnippetIter *pIter){ int i; /* Loop counter */ if( pIter->iCurrent<0 ){ /* The SnippetIter object has just been initialized. The first snippet ** candidate always starts at offset 0 (even if this candidate has a ** score of 0.0). */ pIter->iCurrent = 0; /* Advance the 'head' iterator of each phrase to the first offset that ** is greater than or equal to (iNext+nSnippet). */ for(i=0; i<pIter->nPhrase; i++){ SnippetPhrase *pPhrase = &pIter->aPhrase[i]; fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet); } }else{ int iStart; int iEnd = 0x7FFFFFFF; for(i=0; i<pIter->nPhrase; i++){ SnippetPhrase *pPhrase = &pIter->aPhrase[i]; if( pPhrase->pHead && pPhrase->iHead<iEnd ){ iEnd = pPhrase->iHead; } } if( iEnd==0x7FFFFFFF ){ return 1; } pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1; for(i=0; i<pIter->nPhrase; i++){ SnippetPhrase *pPhrase = &pIter->aPhrase[i]; fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1); fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart); } } return 0; } /* ** Retrieve information about the current candidate snippet of snippet ** iterator pIter. */ static void fts3SnippetDetails( SnippetIter *pIter, /* Snippet iterator */ u64 mCovered, /* Bitmask of phrases already covered */ int *piToken, /* OUT: First token of proposed snippet */ int *piScore, /* OUT: "Score" for this snippet */ u64 *pmCover, /* OUT: Bitmask of phrases covered */ u64 *pmHighlight /* OUT: Bitmask of terms to highlight */ ){ int iStart = pIter->iCurrent; /* First token of snippet */ int iScore = 0; /* Score of this snippet */ int i; /* Loop counter */ u64 mCover = 0; /* Mask of phrases covered by this snippet */ u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */ for(i=0; i<pIter->nPhrase; i++){ SnippetPhrase *pPhrase = &pIter->aPhrase[i]; if( pPhrase->pTail ){ char *pCsr = pPhrase->pTail; int iCsr = pPhrase->iTail; while( iCsr<(iStart+pIter->nSnippet) ){ int j; u64 mPhrase = (u64)1 << i; u64 mPos = (u64)1 << (iCsr - iStart); assert( iCsr>=iStart ); if( (mCover|mCovered)&mPhrase ){ iScore++; }else{ iScore += 1000; } mCover |= mPhrase; for(j=0; j<pPhrase->nToken; j++){ mHighlight |= (mPos>>j); } if( 0==(*pCsr & 0x0FE) ) break; fts3GetDeltaPosition(&pCsr, &iCsr); } } } /* Set the output variables before returning. */ *piToken = iStart; *piScore = iScore; *pmCover = mCover; *pmHighlight = mHighlight; } /* ** This function is an fts3ExprIterate() callback used by fts3BestSnippet(). ** Each invocation populates an element of the SnippetIter.aPhrase[] array. */ static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){ SnippetIter *p = (SnippetIter *)ctx; SnippetPhrase *pPhrase = &p->aPhrase[iPhrase]; char *pCsr; int rc; pPhrase->nToken = pExpr->pPhrase->nToken; rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr); assert( rc==SQLITE_OK || pCsr==0 ); if( pCsr ){ int iFirst = 0; pPhrase->pList = pCsr; fts3GetDeltaPosition(&pCsr, &iFirst); assert( iFirst>=0 ); pPhrase->pHead = pCsr; pPhrase->pTail = pCsr; pPhrase->iHead = iFirst; pPhrase->iTail = iFirst; }else{ assert( rc!=SQLITE_OK || ( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 )); } return rc; } /* ** Select the fragment of text consisting of nFragment contiguous tokens ** from column iCol that represent the "best" snippet. The best snippet ** is the snippet with the highest score, where scores are calculated ** by adding: ** ** (a) +1 point for each occurrence of a matchable phrase in the snippet. ** ** (b) +1000 points for the first occurrence of each matchable phrase in ** the snippet for which the corresponding mCovered bit is not set. ** ** The selected snippet parameters are stored in structure *pFragment before ** returning. The score of the selected snippet is stored in *piScore ** before returning. */ static int fts3BestSnippet( int nSnippet, /* Desired snippet length */ Fts3Cursor *pCsr, /* Cursor to create snippet for */ int iCol, /* Index of column to create snippet from */ u64 mCovered, /* Mask of phrases already covered */ u64 *pmSeen, /* IN/OUT: Mask of phrases seen */ SnippetFragment *pFragment, /* OUT: Best snippet found */ int *piScore /* OUT: Score of snippet pFragment */ ){ int rc; /* Return Code */ int nList; /* Number of phrases in expression */ SnippetIter sIter; /* Iterates through snippet candidates */ int nByte; /* Number of bytes of space to allocate */ int iBestScore = -1; /* Best snippet score found so far */ int i; /* Loop counter */ memset(&sIter, 0, sizeof(sIter)); /* Iterate through the phrases in the expression to count them. The same ** callback makes sure the doclists are loaded for each phrase. */ rc = fts3ExprLoadDoclists(pCsr, &nList, 0); if( rc!=SQLITE_OK ){ return rc; } /* Now that it is known how many phrases there are, allocate and zero ** the required space using malloc(). */ nByte = sizeof(SnippetPhrase) * nList; sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte); if( !sIter.aPhrase ){ return SQLITE_NOMEM; } memset(sIter.aPhrase, 0, nByte); /* Initialize the contents of the SnippetIter object. Then iterate through ** the set of phrases in the expression to populate the aPhrase[] array. */ sIter.pCsr = pCsr; sIter.iCol = iCol; sIter.nSnippet = nSnippet; sIter.nPhrase = nList; sIter.iCurrent = -1; rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter); if( rc==SQLITE_OK ){ /* Set the *pmSeen output variable. */ for(i=0; i<nList; i++){ if( sIter.aPhrase[i].pHead ){ *pmSeen |= (u64)1 << i; } } /* Loop through all candidate snippets. Store the best snippet in ** *pFragment. Store its associated 'score' in iBestScore. */ pFragment->iCol = iCol; while( !fts3SnippetNextCandidate(&sIter) ){ int iPos; int iScore; u64 mCover; u64 mHighlite; fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite); assert( iScore>=0 ); if( iScore>iBestScore ){ pFragment->iPos = iPos; pFragment->hlmask = mHighlite; pFragment->covered = mCover; iBestScore = iScore; } } *piScore = iBestScore; } sqlite3_free(sIter.aPhrase); return rc; } /* ** Append a string to the string-buffer passed as the first argument. ** ** If nAppend is negative, then the length of the string zAppend is ** determined using strlen(). */ static int fts3StringAppend( StrBuffer *pStr, /* Buffer to append to */ const char *zAppend, /* Pointer to data to append to buffer */ int nAppend /* Size of zAppend in bytes (or -1) */ ){ if( nAppend<0 ){ nAppend = (int)strlen(zAppend); } /* If there is insufficient space allocated at StrBuffer.z, use realloc() ** to grow the buffer until so that it is big enough to accomadate the ** appended data. */ if( pStr->n+nAppend+1>=pStr->nAlloc ){ int nAlloc = pStr->nAlloc+nAppend+100; char *zNew = sqlite3_realloc(pStr->z, nAlloc); if( !zNew ){ return SQLITE_NOMEM; } pStr->z = zNew; pStr->nAlloc = nAlloc; } assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) ); /* Append the data to the string buffer. */ memcpy(&pStr->z[pStr->n], zAppend, nAppend); pStr->n += nAppend; pStr->z[pStr->n] = '\0'; return SQLITE_OK; } /* ** The fts3BestSnippet() function often selects snippets that end with a ** query term. That is, the final term of the snippet is always a term ** that requires highlighting. For example, if 'X' is a highlighted term ** and '.' is a non-highlighted term, BestSnippet() may select: ** ** ........X.....X ** ** This function "shifts" the beginning of the snippet forward in the ** document so that there are approximately the same number of ** non-highlighted terms to the right of the final highlighted term as there ** are to the left of the first highlighted term. For example, to this: ** ** ....X.....X.... ** ** This is done as part of extracting the snippet text, not when selecting ** the snippet. Snippet selection is done based on doclists only, so there ** is no way for fts3BestSnippet() to know whether or not the document ** actually contains terms that follow the final highlighted term. */ static int fts3SnippetShift( Fts3Table *pTab, /* FTS3 table snippet comes from */ int iLangid, /* Language id to use in tokenizing */ int nSnippet, /* Number of tokens desired for snippet */ const char *zDoc, /* Document text to extract snippet from */ int nDoc, /* Size of buffer zDoc in bytes */ int *piPos, /* IN/OUT: First token of snippet */ u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */ ){ u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */ if( hlmask ){ int nLeft; /* Tokens to the left of first highlight */ int nRight; /* Tokens to the right of last highlight */ int nDesired; /* Ideal number of tokens to shift forward */ for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++); for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++); nDesired = (nLeft-nRight)/2; /* Ideally, the start of the snippet should be pushed forward in the ** document nDesired tokens. This block checks if there are actually ** nDesired tokens to the right of the snippet. If so, *piPos and ** *pHlMask are updated to shift the snippet nDesired tokens to the ** right. Otherwise, the snippet is shifted by the number of tokens ** available. */ if( nDesired>0 ){ int nShift; /* Number of tokens to shift snippet by */ int iCurrent = 0; /* Token counter */ int rc; /* Return Code */ sqlite3_tokenizer_module *pMod; sqlite3_tokenizer_cursor *pC; pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired) ** or more tokens in zDoc/nDoc. */ rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC); if( rc!=SQLITE_OK ){ return rc; } while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){ const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0; rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent); } pMod->xClose(pC); if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; } nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet; assert( nShift<=nDesired ); if( nShift>0 ){ *piPos += nShift; *pHlmask = hlmask >> nShift; } } } return SQLITE_OK; } /* ** Extract the snippet text for fragment pFragment from cursor pCsr and ** append it to string buffer pOut. */ static int fts3SnippetText( Fts3Cursor *pCsr, /* FTS3 Cursor */ SnippetFragment *pFragment, /* Snippet to extract */ int iFragment, /* Fragment number */ int isLast, /* True for final fragment in snippet */ int nSnippet, /* Number of tokens in extracted snippet */ const char *zOpen, /* String inserted before highlighted term */ const char *zClose, /* String inserted after highlighted term */ const char *zEllipsis, /* String inserted between snippets */ StrBuffer *pOut /* Write output here */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc; /* Return code */ const char *zDoc; /* Document text to extract snippet from */ int nDoc; /* Size of zDoc in bytes */ int iCurrent = 0; /* Current token number of document */ int iEnd = 0; /* Byte offset of end of current token */ int isShiftDone = 0; /* True after snippet is shifted */ int iPos = pFragment->iPos; /* First token of snippet */ u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */ int iCol = pFragment->iCol+1; /* Query column to extract text from */ sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */ sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */ zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol); if( zDoc==0 ){ if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){ return SQLITE_NOMEM; } return SQLITE_OK; } nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol); /* Open a token cursor on the document. */ pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC); if( rc!=SQLITE_OK ){ return rc; } while( rc==SQLITE_OK ){ const char *ZDUMMY; /* Dummy argument used with tokenizer */ int DUMMY1 = -1; /* Dummy argument used with tokenizer */ int iBegin = 0; /* Offset in zDoc of start of token */ int iFin = 0; /* Offset in zDoc of end of token */ int isHighlight = 0; /* True for highlighted terms */ /* Variable DUMMY1 is initialized to a negative value above. Elsewhere ** in the FTS code the variable that the third argument to xNext points to ** is initialized to zero before the first (*but not necessarily ** subsequent*) call to xNext(). This is done for a particular application ** that needs to know whether or not the tokenizer is being used for ** snippet generation or for some other purpose. ** ** Extreme care is required when writing code to depend on this ** initialization. It is not a documented part of the tokenizer interface. ** If a tokenizer is used directly by any code outside of FTS, this ** convention might not be respected. */ rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent); if( rc!=SQLITE_OK ){ if( rc==SQLITE_DONE ){ /* Special case - the last token of the snippet is also the last token ** of the column. Append any punctuation that occurred between the end ** of the previous token and the end of the document to the output. ** Then break out of the loop. */ rc = fts3StringAppend(pOut, &zDoc[iEnd], -1); } break; } if( iCurrent<iPos ){ continue; } if( !isShiftDone ){ int n = nDoc - iBegin; rc = fts3SnippetShift( pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask ); isShiftDone = 1; /* Now that the shift has been done, check if the initial "..." are ** required. They are required if (a) this is not the first fragment, ** or (b) this fragment does not begin at position 0 of its column. */ if( rc==SQLITE_OK ){ if( iPos>0 || iFragment>0 ){ rc = fts3StringAppend(pOut, zEllipsis, -1); }else if( iBegin ){ rc = fts3StringAppend(pOut, zDoc, iBegin); } } if( rc!=SQLITE_OK || iCurrent<iPos ) continue; } if( iCurrent>=(iPos+nSnippet) ){ if( isLast ){ rc = fts3StringAppend(pOut, zEllipsis, -1); } break; } /* Set isHighlight to true if this term should be highlighted. */ isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0; if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd); if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1); if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin); if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1); iEnd = iFin; } pMod->xClose(pC); return rc; } /* ** This function is used to count the entries in a column-list (a ** delta-encoded list of term offsets within a single column of a single ** row). When this function is called, *ppCollist should point to the ** beginning of the first varint in the column-list (the varint that ** contains the position of the first matching term in the column data). ** Before returning, *ppCollist is set to point to the first byte after ** the last varint in the column-list (either the 0x00 signifying the end ** of the position-list, or the 0x01 that precedes the column number of ** the next column in the position-list). ** ** The number of elements in the column-list is returned. */ static int fts3ColumnlistCount(char **ppCollist){ char *pEnd = *ppCollist; char c = 0; int nEntry = 0; /* A column-list is terminated by either a 0x01 or 0x00. */ while( 0xFE & (*pEnd | c) ){ c = *pEnd++ & 0x80; if( !c ) nEntry++; } *ppCollist = pEnd; return nEntry; } /* ** This function gathers 'y' or 'b' data for a single phrase. */ static void fts3ExprLHits( Fts3Expr *pExpr, /* Phrase expression node */ MatchInfo *p /* Matchinfo context */ ){ Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab; int iStart; Fts3Phrase *pPhrase = pExpr->pPhrase; char *pIter = pPhrase->doclist.pList; int iCol = 0; assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS ); if( p->flag==FTS3_MATCHINFO_LHITS ){ iStart = pExpr->iPhrase * p->nCol; }else{ iStart = pExpr->iPhrase * ((p->nCol + 31) / 32); } while( 1 ){ int nHit = fts3ColumnlistCount(&pIter); if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){ if( p->flag==FTS3_MATCHINFO_LHITS ){ p->aMatchinfo[iStart + iCol] = (u32)nHit; }else if( nHit ){ p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F)); } } assert( *pIter==0x00 || *pIter==0x01 ); if( *pIter!=0x01 ) break; pIter++; pIter += fts3GetVarint32(pIter, &iCol); } } /* ** Gather the results for matchinfo directives 'y' and 'b'. */ static void fts3ExprLHitGather( Fts3Expr *pExpr, MatchInfo *p ){ assert( (pExpr->pLeft==0)==(pExpr->pRight==0) ); if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){ if( pExpr->pLeft ){ fts3ExprLHitGather(pExpr->pLeft, p); fts3ExprLHitGather(pExpr->pRight, p); }else{ fts3ExprLHits(pExpr, p); } } } /* ** fts3ExprIterate() callback used to collect the "global" matchinfo stats ** for a single query. ** ** fts3ExprIterate() callback to load the 'global' elements of a ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements ** of the matchinfo array that are constant for all rows returned by the ** current query. ** ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This ** function populates Matchinfo.aMatchinfo[] as follows: ** ** for(iCol=0; iCol<nCol; iCol++){ ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X; ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y; ** } ** ** where X is the number of matches for phrase iPhrase is column iCol of all ** rows of the table. Y is the number of rows for which column iCol contains ** at least one instance of phrase iPhrase. ** ** If the phrase pExpr consists entirely of deferred tokens, then all X and ** Y values are set to nDoc, where nDoc is the number of documents in the ** file system. This is done because the full-text index doclist is required ** to calculate these values properly, and the full-text index doclist is ** not available for deferred tokens. */ static int fts3ExprGlobalHitsCb( Fts3Expr *pExpr, /* Phrase expression node */ int iPhrase, /* Phrase number (numbered from zero) */ void *pCtx /* Pointer to MatchInfo structure */ ){ MatchInfo *p = (MatchInfo *)pCtx; return sqlite3Fts3EvalPhraseStats( p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol] ); } /* ** fts3ExprIterate() callback used to collect the "local" part of the ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the ** array that are different for each row returned by the query. */ static int fts3ExprLocalHitsCb( Fts3Expr *pExpr, /* Phrase expression node */ int iPhrase, /* Phrase number */ void *pCtx /* Pointer to MatchInfo structure */ ){ int rc = SQLITE_OK; MatchInfo *p = (MatchInfo *)pCtx; int iStart = iPhrase * p->nCol * 3; int i; for(i=0; i<p->nCol && rc==SQLITE_OK; i++){ char *pCsr; rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr); if( pCsr ){ p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr); }else{ p->aMatchinfo[iStart+i*3] = 0; } } return rc; } static int fts3MatchinfoCheck( Fts3Table *pTab, char cArg, char **pzErr ){ if( (cArg==FTS3_MATCHINFO_NPHRASE) || (cArg==FTS3_MATCHINFO_NCOL) || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4) || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4) || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize) || (cArg==FTS3_MATCHINFO_LCS) || (cArg==FTS3_MATCHINFO_HITS) || (cArg==FTS3_MATCHINFO_LHITS) || (cArg==FTS3_MATCHINFO_LHITS_BM) ){ return SQLITE_OK; } sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg); return SQLITE_ERROR; } static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ int nVal; /* Number of integers output by cArg */ switch( cArg ){ case FTS3_MATCHINFO_NDOC: case FTS3_MATCHINFO_NPHRASE: case FTS3_MATCHINFO_NCOL: nVal = 1; break; case FTS3_MATCHINFO_AVGLENGTH: case FTS3_MATCHINFO_LENGTH: case FTS3_MATCHINFO_LCS: nVal = pInfo->nCol; break; case FTS3_MATCHINFO_LHITS: nVal = pInfo->nCol * pInfo->nPhrase; break; case FTS3_MATCHINFO_LHITS_BM: nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32); break; default: assert( cArg==FTS3_MATCHINFO_HITS ); nVal = pInfo->nCol * pInfo->nPhrase * 3; break; } return nVal; } static int fts3MatchinfoSelectDoctotal( Fts3Table *pTab, sqlite3_stmt **ppStmt, sqlite3_int64 *pnDoc, const char **paLen ){ sqlite3_stmt *pStmt; const char *a; sqlite3_int64 nDoc; if( !*ppStmt ){ int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt); if( rc!=SQLITE_OK ) return rc; } pStmt = *ppStmt; assert( sqlite3_data_count(pStmt)==1 ); a = sqlite3_column_blob(pStmt, 0); a += sqlite3Fts3GetVarint(a, &nDoc); if( nDoc==0 ) return FTS_CORRUPT_VTAB; *pnDoc = (u32)nDoc; if( paLen ) *paLen = a; return SQLITE_OK; } /* ** An instance of the following structure is used to store state while ** iterating through a multi-column position-list corresponding to the ** hits for a single phrase on a single row in order to calculate the ** values for a matchinfo() FTS3_MATCHINFO_LCS request. */ typedef struct LcsIterator LcsIterator; struct LcsIterator { Fts3Expr *pExpr; /* Pointer to phrase expression */ int iPosOffset; /* Tokens count up to end of this phrase */ char *pRead; /* Cursor used to iterate through aDoclist */ int iPos; /* Current position */ }; /* ** If LcsIterator.iCol is set to the following value, the iterator has ** finished iterating through all offsets for all columns. */ #define LCS_ITERATOR_FINISHED 0x7FFFFFFF; static int fts3MatchinfoLcsCb( Fts3Expr *pExpr, /* Phrase expression node */ int iPhrase, /* Phrase number (numbered from zero) */ void *pCtx /* Pointer to MatchInfo structure */ ){ LcsIterator *aIter = (LcsIterator *)pCtx; aIter[iPhrase].pExpr = pExpr; return SQLITE_OK; } /* ** Advance the iterator passed as an argument to the next position. Return ** 1 if the iterator is at EOF or if it now points to the start of the ** position list for the next column. */ static int fts3LcsIteratorAdvance(LcsIterator *pIter){ char *pRead = pIter->pRead; sqlite3_int64 iRead; int rc = 0; pRead += sqlite3Fts3GetVarint(pRead, &iRead); if( iRead==0 || iRead==1 ){ pRead = 0; rc = 1; }else{ pIter->iPos += (int)(iRead-2); } pIter->pRead = pRead; return rc; } /* ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. ** ** If the call is successful, the longest-common-substring lengths for each ** column are written into the first nCol elements of the pInfo->aMatchinfo[] ** array before returning. SQLITE_OK is returned in this case. ** ** Otherwise, if an error occurs, an SQLite error code is returned and the ** data written to the first nCol elements of pInfo->aMatchinfo[] is ** undefined. */ static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ LcsIterator *aIter; int i; int iCol; int nToken = 0; /* Allocate and populate the array of LcsIterator objects. The array ** contains one element for each matchable phrase in the query. **/ aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase); if( !aIter ) return SQLITE_NOMEM; memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase); (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter); for(i=0; i<pInfo->nPhrase; i++){ LcsIterator *pIter = &aIter[i]; nToken -= pIter->pExpr->pPhrase->nToken; pIter->iPosOffset = nToken; } for(iCol=0; iCol<pInfo->nCol; iCol++){ int nLcs = 0; /* LCS value for this column */ int nLive = 0; /* Number of iterators in aIter not at EOF */ for(i=0; i<pInfo->nPhrase; i++){ int rc; LcsIterator *pIt = &aIter[i]; rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); if( rc!=SQLITE_OK ) return rc; if( pIt->pRead ){ pIt->iPos = pIt->iPosOffset; fts3LcsIteratorAdvance(&aIter[i]); nLive++; } } while( nLive>0 ){ LcsIterator *pAdv = 0; /* The iterator to advance by one position */ int nThisLcs = 0; /* LCS for the current iterator positions */ for(i=0; i<pInfo->nPhrase; i++){ LcsIterator *pIter = &aIter[i]; if( pIter->pRead==0 ){ /* This iterator is already at EOF for this column. */ nThisLcs = 0; }else{ if( pAdv==0 || pIter->iPos<pAdv->iPos ){ pAdv = pIter; } if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){ nThisLcs++; }else{ nThisLcs = 1; } if( nThisLcs>nLcs ) nLcs = nThisLcs; } } if( fts3LcsIteratorAdvance(pAdv) ) nLive--; } pInfo->aMatchinfo[iCol] = nLcs; } sqlite3_free(aIter); return SQLITE_OK; } /* ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to ** be returned by the matchinfo() function. Argument zArg contains the ** format string passed as the second argument to matchinfo (or the ** default value "pcx" if no second argument was specified). The format ** string has already been validated and the pInfo->aMatchinfo[] array ** is guaranteed to be large enough for the output. ** ** If bGlobal is true, then populate all fields of the matchinfo() output. ** If it is false, then assume that those fields that do not change between ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS) ** have already been populated. ** ** Return SQLITE_OK if successful, or an SQLite error code if an error ** occurs. If a value other than SQLITE_OK is returned, the state the ** pInfo->aMatchinfo[] buffer is left in is undefined. */ static int fts3MatchinfoValues( Fts3Cursor *pCsr, /* FTS3 cursor object */ int bGlobal, /* True to grab the global stats */ MatchInfo *pInfo, /* Matchinfo context object */ const char *zArg /* Matchinfo format string */ ){ int rc = SQLITE_OK; int i; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; sqlite3_stmt *pSelect = 0; for(i=0; rc==SQLITE_OK && zArg[i]; i++){ pInfo->flag = zArg[i]; switch( zArg[i] ){ case FTS3_MATCHINFO_NPHRASE: if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase; break; case FTS3_MATCHINFO_NCOL: if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol; break; case FTS3_MATCHINFO_NDOC: if( bGlobal ){ sqlite3_int64 nDoc = 0; rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0); pInfo->aMatchinfo[0] = (u32)nDoc; } break; case FTS3_MATCHINFO_AVGLENGTH: if( bGlobal ){ sqlite3_int64 nDoc; /* Number of rows in table */ const char *a; /* Aggregate column length array */ rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a); if( rc==SQLITE_OK ){ int iCol; for(iCol=0; iCol<pInfo->nCol; iCol++){ u32 iVal; sqlite3_int64 nToken; a += sqlite3Fts3GetVarint(a, &nToken); iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc); pInfo->aMatchinfo[iCol] = iVal; } } } break; case FTS3_MATCHINFO_LENGTH: { sqlite3_stmt *pSelectDocsize = 0; rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize); if( rc==SQLITE_OK ){ int iCol; const char *a = sqlite3_column_blob(pSelectDocsize, 0); for(iCol=0; iCol<pInfo->nCol; iCol++){ sqlite3_int64 nToken; a += sqlite3Fts3GetVarint(a, &nToken); pInfo->aMatchinfo[iCol] = (u32)nToken; } } sqlite3_reset(pSelectDocsize); break; } case FTS3_MATCHINFO_LCS: rc = fts3ExprLoadDoclists(pCsr, 0, 0); if( rc==SQLITE_OK ){ rc = fts3MatchinfoLcs(pCsr, pInfo); } break; case FTS3_MATCHINFO_LHITS_BM: case FTS3_MATCHINFO_LHITS: { int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); memset(pInfo->aMatchinfo, 0, nZero); fts3ExprLHitGather(pCsr->pExpr, pInfo); break; } default: { Fts3Expr *pExpr; assert( zArg[i]==FTS3_MATCHINFO_HITS ); pExpr = pCsr->pExpr; rc = fts3ExprLoadDoclists(pCsr, 0, 0); if( rc!=SQLITE_OK ) break; if( bGlobal ){ if( pCsr->pDeferred ){ rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0); if( rc!=SQLITE_OK ) break; } rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo); sqlite3Fts3EvalTestDeferred(pCsr, &rc); if( rc!=SQLITE_OK ) break; } (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo); break; } } pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]); } sqlite3_reset(pSelect); return rc; } /* ** Populate pCsr->aMatchinfo[] with data for the current row. The ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32). */ static void fts3GetMatchinfo( sqlite3_context *pCtx, /* Return results here */ Fts3Cursor *pCsr, /* FTS3 Cursor object */ const char *zArg /* Second argument to matchinfo() function */ ){ MatchInfo sInfo; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; int bGlobal = 0; /* Collect 'global' stats as well as local */ u32 *aOut = 0; void (*xDestroyOut)(void*) = 0; memset(&sInfo, 0, sizeof(MatchInfo)); sInfo.pCursor = pCsr; sInfo.nCol = pTab->nColumn; /* If there is cached matchinfo() data, but the format string for the ** cache does not match the format string for this request, discard ** the cached data. */ if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){ sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); pCsr->pMIBuffer = 0; } /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the ** matchinfo function has been called for this query. In this case ** allocate the array used to accumulate the matchinfo data and ** initialize those elements that are constant for every row. */ if( pCsr->pMIBuffer==0 ){ int nMatchinfo = 0; /* Number of u32 elements in match-info */ int i; /* Used to iterate through zArg */ /* Determine the number of phrases in the query */ pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr); sInfo.nPhrase = pCsr->nPhrase; /* Determine the number of integers in the buffer returned by this call. */ for(i=0; zArg[i]; i++){ char *zErr = 0; if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){ sqlite3_result_error(pCtx, zErr, -1); sqlite3_free(zErr); return; } nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]); } /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */ pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg); if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM; pCsr->isMatchinfoNeeded = 1; bGlobal = 1; } if( rc==SQLITE_OK ){ xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut); if( xDestroyOut==0 ){ rc = SQLITE_NOMEM; } } if( rc==SQLITE_OK ){ sInfo.aMatchinfo = aOut; sInfo.nPhrase = pCsr->nPhrase; rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg); if( bGlobal ){ fts3MIBufferSetGlobal(pCsr->pMIBuffer); } } if( rc!=SQLITE_OK ){ sqlite3_result_error_code(pCtx, rc); if( xDestroyOut ) xDestroyOut(aOut); }else{ int n = pCsr->pMIBuffer->nElem * sizeof(u32); sqlite3_result_blob(pCtx, aOut, n, xDestroyOut); } } /* ** Implementation of snippet() function. */ SQLITE_PRIVATE void sqlite3Fts3Snippet( sqlite3_context *pCtx, /* SQLite function call context */ Fts3Cursor *pCsr, /* Cursor object */ const char *zStart, /* Snippet start text - "<b>" */ const char *zEnd, /* Snippet end text - "</b>" */ const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */ int iCol, /* Extract snippet from this column */ int nToken /* Approximate number of tokens in snippet */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; int i; StrBuffer res = {0, 0, 0}; /* The returned text includes up to four fragments of text extracted from ** the data in the current row. The first iteration of the for(...) loop ** below attempts to locate a single fragment of text nToken tokens in ** size that contains at least one instance of all phrases in the query ** expression that appear in the current row. If such a fragment of text ** cannot be found, the second iteration of the loop attempts to locate ** a pair of fragments, and so on. */ int nSnippet = 0; /* Number of fragments in this snippet */ SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */ int nFToken = -1; /* Number of tokens in each fragment */ if( !pCsr->pExpr ){ sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); return; } for(nSnippet=1; 1; nSnippet++){ int iSnip; /* Loop counter 0..nSnippet-1 */ u64 mCovered = 0; /* Bitmask of phrases covered by snippet */ u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */ if( nToken>=0 ){ nFToken = (nToken+nSnippet-1) / nSnippet; }else{ nFToken = -1 * nToken; } for(iSnip=0; iSnip<nSnippet; iSnip++){ int iBestScore = -1; /* Best score of columns checked so far */ int iRead; /* Used to iterate through columns */ SnippetFragment *pFragment = &aSnippet[iSnip]; memset(pFragment, 0, sizeof(*pFragment)); /* Loop through all columns of the table being considered for snippets. ** If the iCol argument to this function was negative, this means all ** columns of the FTS3 table. Otherwise, only column iCol is considered. */ for(iRead=0; iRead<pTab->nColumn; iRead++){ SnippetFragment sF = {0, 0, 0, 0}; int iS = 0; if( iCol>=0 && iRead!=iCol ) continue; /* Find the best snippet of nFToken tokens in column iRead. */ rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS); if( rc!=SQLITE_OK ){ goto snippet_out; } if( iS>iBestScore ){ *pFragment = sF; iBestScore = iS; } } mCovered |= pFragment->covered; } /* If all query phrases seen by fts3BestSnippet() are present in at least ** one of the nSnippet snippet fragments, break out of the loop. */ assert( (mCovered&mSeen)==mCovered ); if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break; } assert( nFToken>0 ); for(i=0; i<nSnippet && rc==SQLITE_OK; i++){ rc = fts3SnippetText(pCsr, &aSnippet[i], i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res ); } snippet_out: sqlite3Fts3SegmentsClose(pTab); if( rc!=SQLITE_OK ){ sqlite3_result_error_code(pCtx, rc); sqlite3_free(res.z); }else{ sqlite3_result_text(pCtx, res.z, -1, sqlite3_free); } } typedef struct TermOffset TermOffset; typedef struct TermOffsetCtx TermOffsetCtx; struct TermOffset { char *pList; /* Position-list */ int iPos; /* Position just read from pList */ int iOff; /* Offset of this term from read positions */ }; struct TermOffsetCtx { Fts3Cursor *pCsr; int iCol; /* Column of table to populate aTerm for */ int iTerm; sqlite3_int64 iDocid; TermOffset *aTerm; }; /* ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets(). */ static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){ TermOffsetCtx *p = (TermOffsetCtx *)ctx; int nTerm; /* Number of tokens in phrase */ int iTerm; /* For looping through nTerm phrase terms */ char *pList; /* Pointer to position list for phrase */ int iPos = 0; /* First position in position-list */ int rc; UNUSED_PARAMETER(iPhrase); rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList); nTerm = pExpr->pPhrase->nToken; if( pList ){ fts3GetDeltaPosition(&pList, &iPos); assert( iPos>=0 ); } for(iTerm=0; iTerm<nTerm; iTerm++){ TermOffset *pT = &p->aTerm[p->iTerm++]; pT->iOff = nTerm-iTerm-1; pT->pList = pList; pT->iPos = iPos; } return rc; } /* ** Implementation of offsets() function. */ SQLITE_PRIVATE void sqlite3Fts3Offsets( sqlite3_context *pCtx, /* SQLite function call context */ Fts3Cursor *pCsr /* Cursor object */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule; int rc; /* Return Code */ int nToken; /* Number of tokens in query */ int iCol; /* Column currently being processed */ StrBuffer res = {0, 0, 0}; /* Result string */ TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */ if( !pCsr->pExpr ){ sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); return; } memset(&sCtx, 0, sizeof(sCtx)); assert( pCsr->isRequireSeek==0 ); /* Count the number of terms in the query */ rc = fts3ExprLoadDoclists(pCsr, 0, &nToken); if( rc!=SQLITE_OK ) goto offsets_out; /* Allocate the array of TermOffset iterators. */ sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken); if( 0==sCtx.aTerm ){ rc = SQLITE_NOMEM; goto offsets_out; } sCtx.iDocid = pCsr->iPrevId; sCtx.pCsr = pCsr; /* Loop through the table columns, appending offset information to ** string-buffer res for each column. */ for(iCol=0; iCol<pTab->nColumn; iCol++){ sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */ const char *ZDUMMY; /* Dummy argument used with xNext() */ int NDUMMY = 0; /* Dummy argument used with xNext() */ int iStart = 0; int iEnd = 0; int iCurrent = 0; const char *zDoc; int nDoc; /* Initialize the contents of sCtx.aTerm[] for column iCol. There is ** no way that this operation can fail, so the return code from ** fts3ExprIterate() can be discarded. */ sCtx.iCol = iCol; sCtx.iTerm = 0; (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx); /* Retreive the text stored in column iCol. If an SQL NULL is stored ** in column iCol, jump immediately to the next iteration of the loop. ** If an OOM occurs while retrieving the data (this can happen if SQLite ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM ** to the caller. */ zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1); nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1); if( zDoc==0 ){ if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){ continue; } rc = SQLITE_NOMEM; goto offsets_out; } /* Initialize a tokenizer iterator to iterate through column iCol. */ rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc, nDoc, &pC ); if( rc!=SQLITE_OK ) goto offsets_out; rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); while( rc==SQLITE_OK ){ int i; /* Used to loop through terms */ int iMinPos = 0x7FFFFFFF; /* Position of next token */ TermOffset *pTerm = 0; /* TermOffset associated with next token */ for(i=0; i<nToken; i++){ TermOffset *pT = &sCtx.aTerm[i]; if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){ iMinPos = pT->iPos-pT->iOff; pTerm = pT; } } if( !pTerm ){ /* All offsets for this column have been gathered. */ rc = SQLITE_DONE; }else{ assert( iCurrent<=iMinPos ); if( 0==(0xFE&*pTerm->pList) ){ pTerm->pList = 0; }else{ fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos); } while( rc==SQLITE_OK && iCurrent<iMinPos ){ rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); } if( rc==SQLITE_OK ){ char aBuffer[64]; sqlite3_snprintf(sizeof(aBuffer), aBuffer, "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart ); rc = fts3StringAppend(&res, aBuffer, -1); }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){ rc = FTS_CORRUPT_VTAB; } } } if( rc==SQLITE_DONE ){ rc = SQLITE_OK; } pMod->xClose(pC); if( rc!=SQLITE_OK ) goto offsets_out; } offsets_out: sqlite3_free(sCtx.aTerm); assert( rc!=SQLITE_DONE ); sqlite3Fts3SegmentsClose(pTab); if( rc!=SQLITE_OK ){ sqlite3_result_error_code(pCtx, rc); sqlite3_free(res.z); }else{ sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free); } return; } /* ** Implementation of matchinfo() function. */ SQLITE_PRIVATE void sqlite3Fts3Matchinfo( sqlite3_context *pContext, /* Function call context */ Fts3Cursor *pCsr, /* FTS3 table cursor */ const char *zArg /* Second arg to matchinfo() function */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; const char *zFormat; if( zArg ){ zFormat = zArg; }else{ zFormat = FTS3_MATCHINFO_DEFAULT; } if( !pCsr->pExpr ){ sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC); return; }else{ /* Retrieve matchinfo() data. */ fts3GetMatchinfo(pContext, pCsr, zFormat); sqlite3Fts3SegmentsClose(pTab); } } #endif /************** End of fts3_snippet.c ****************************************/ /************** Begin file fts3_unicode.c ************************************/ /* ** 2012 May 24 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Implementation of the "unicode" full-text-search tokenizer. */ #ifndef SQLITE_DISABLE_FTS3_UNICODE /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) /* #include <assert.h> */ /* #include <stdlib.h> */ /* #include <stdio.h> */ /* #include <string.h> */ /* #include "fts3_tokenizer.h" */ /* ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied ** from the sqlite3 source file utf.c. If this file is compiled as part ** of the amalgamation, they are not required. */ #ifndef SQLITE_AMALGAMATION static const unsigned char sqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = sqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ if( c<0x80 \ || (c&0xFFFFF800)==0xD800 \ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } #define WRITE_UTF8(zOut, c) { \ if( c<0x00080 ){ \ *zOut++ = (u8)(c&0xFF); \ } \ else if( c<0x00800 ){ \ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ else if( c<0x10000 ){ \ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ }else{ \ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ } #endif /* ifndef SQLITE_AMALGAMATION */ typedef struct unicode_tokenizer unicode_tokenizer; typedef struct unicode_cursor unicode_cursor; struct unicode_tokenizer { sqlite3_tokenizer base; int bRemoveDiacritic; int nException; int *aiException; }; struct unicode_cursor { sqlite3_tokenizer_cursor base; const unsigned char *aInput; /* Input text being tokenized */ int nInput; /* Size of aInput[] in bytes */ int iOff; /* Current offset within aInput[] */ int iToken; /* Index of next token to be returned */ char *zToken; /* storage for current token */ int nAlloc; /* space allocated at zToken */ }; /* ** Destroy a tokenizer allocated by unicodeCreate(). */ static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){ if( pTokenizer ){ unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer; sqlite3_free(p->aiException); sqlite3_free(p); } return SQLITE_OK; } /* ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE ** statement has specified that the tokenizer for this table shall consider ** all characters in string zIn/nIn to be separators (if bAlnum==0) or ** token characters (if bAlnum==1). ** ** For each codepoint in the zIn/nIn string, this function checks if the ** sqlite3FtsUnicodeIsalnum() function already returns the desired result. ** If so, no action is taken. Otherwise, the codepoint is added to the ** unicode_tokenizer.aiException[] array. For the purposes of tokenization, ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all ** codepoints in the aiException[] array. ** ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic() ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored. ** It is not possible to change the behavior of the tokenizer with respect ** to these codepoints. */ static int unicodeAddExceptions( unicode_tokenizer *p, /* Tokenizer to add exceptions to */ int bAlnum, /* Replace Isalnum() return value with this */ const char *zIn, /* Array of characters to make exceptions */ int nIn /* Length of z in bytes */ ){ const unsigned char *z = (const unsigned char *)zIn; const unsigned char *zTerm = &z[nIn]; int iCode; int nEntry = 0; assert( bAlnum==0 || bAlnum==1 ); while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum && sqlite3FtsUnicodeIsdiacritic(iCode)==0 ){ nEntry++; } } if( nEntry ){ int *aNew; /* New aiException[] array */ int nNew; /* Number of valid entries in array aNew[] */ aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int)); if( aNew==0 ) return SQLITE_NOMEM; nNew = p->nException; z = (const unsigned char *)zIn; while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum && sqlite3FtsUnicodeIsdiacritic(iCode)==0 ){ int i, j; for(i=0; i<nNew && aNew[i]<iCode; i++); for(j=nNew; j>i; j--) aNew[j] = aNew[j-1]; aNew[i] = iCode; nNew++; } } p->aiException = aNew; p->nException = nNew; } return SQLITE_OK; } /* ** Return true if the p->aiException[] array contains the value iCode. */ static int unicodeIsException(unicode_tokenizer *p, int iCode){ if( p->nException>0 ){ int *a = p->aiException; int iLo = 0; int iHi = p->nException-1; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( iCode==a[iTest] ){ return 1; }else if( iCode>a[iTest] ){ iLo = iTest+1; }else{ iHi = iTest-1; } } } return 0; } /* ** Return true if, for the purposes of tokenization, codepoint iCode is ** considered a token character (not a separator). */ static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){ assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode); } /* ** Create a new tokenizer instance. */ static int unicodeCreate( int nArg, /* Size of array argv[] */ const char * const *azArg, /* Tokenizer creation arguments */ sqlite3_tokenizer **pp /* OUT: New tokenizer handle */ ){ unicode_tokenizer *pNew; /* New tokenizer object */ int i; int rc = SQLITE_OK; pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer)); if( pNew==NULL ) return SQLITE_NOMEM; memset(pNew, 0, sizeof(unicode_tokenizer)); pNew->bRemoveDiacritic = 1; for(i=0; rc==SQLITE_OK && i<nArg; i++){ const char *z = azArg[i]; int n = (int)strlen(z); if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){ pNew->bRemoveDiacritic = 1; } else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){ pNew->bRemoveDiacritic = 0; } else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){ rc = unicodeAddExceptions(pNew, 1, &z[11], n-11); } else if( n>=11 && memcmp("separators=", z, 11)==0 ){ rc = unicodeAddExceptions(pNew, 0, &z[11], n-11); } else{ /* Unrecognized argument */ rc = SQLITE_ERROR; } } if( rc!=SQLITE_OK ){ unicodeDestroy((sqlite3_tokenizer *)pNew); pNew = 0; } *pp = (sqlite3_tokenizer *)pNew; return rc; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is pInput[0..nBytes-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int unicodeOpen( sqlite3_tokenizer *p, /* The tokenizer */ const char *aInput, /* Input string */ int nInput, /* Size of string aInput in bytes */ sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */ ){ unicode_cursor *pCsr; pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor)); if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(unicode_cursor)); pCsr->aInput = (const unsigned char *)aInput; if( aInput==0 ){ pCsr->nInput = 0; }else if( nInput<0 ){ pCsr->nInput = (int)strlen(aInput); }else{ pCsr->nInput = nInput; } *pp = &pCsr->base; UNUSED_PARAMETER(p); return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to ** simpleOpen() above. */ static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){ unicode_cursor *pCsr = (unicode_cursor *) pCursor; sqlite3_free(pCsr->zToken); sqlite3_free(pCsr); return SQLITE_OK; } /* ** Extract the next token from a tokenization cursor. The cursor must ** have been opened by a prior call to simpleOpen(). */ static int unicodeNext( sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */ const char **paToken, /* OUT: Token text */ int *pnToken, /* OUT: Number of bytes at *paToken */ int *piStart, /* OUT: Starting offset of token */ int *piEnd, /* OUT: Ending offset of token */ int *piPos /* OUT: Position integer of token */ ){ unicode_cursor *pCsr = (unicode_cursor *)pC; unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer); int iCode = 0; char *zOut; const unsigned char *z = &pCsr->aInput[pCsr->iOff]; const unsigned char *zStart = z; const unsigned char *zEnd; const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput]; /* Scan past any delimiter characters before the start of the next token. ** Return SQLITE_DONE early if this takes us all the way to the end of ** the input. */ while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); if( unicodeIsAlnum(p, iCode) ) break; zStart = z; } if( zStart>=zTerm ) return SQLITE_DONE; zOut = pCsr->zToken; do { int iOut; /* Grow the output buffer if required. */ if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){ char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64); if( !zNew ) return SQLITE_NOMEM; zOut = &zNew[zOut - pCsr->zToken]; pCsr->zToken = zNew; pCsr->nAlloc += 64; } /* Write the folded case of the last character read to the output */ zEnd = z; iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic); if( iOut ){ WRITE_UTF8(zOut, iOut); } /* If the cursor is not at EOF, read the next character */ if( z>=zTerm ) break; READ_UTF8(z, zTerm, iCode); }while( unicodeIsAlnum(p, iCode) || sqlite3FtsUnicodeIsdiacritic(iCode) ); /* Set the output variables and return. */ pCsr->iOff = (int)(z - pCsr->aInput); *paToken = pCsr->zToken; *pnToken = (int)(zOut - pCsr->zToken); *piStart = (int)(zStart - pCsr->aInput); *piEnd = (int)(zEnd - pCsr->aInput); *piPos = pCsr->iToken++; return SQLITE_OK; } /* ** Set *ppModule to a pointer to the sqlite3_tokenizer_module ** structure for the unicode tokenizer. */ SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){ static const sqlite3_tokenizer_module module = { 0, unicodeCreate, unicodeDestroy, unicodeOpen, unicodeClose, unicodeNext, 0, }; *ppModule = &module; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */ /************** End of fts3_unicode.c ****************************************/ /************** Begin file fts3_unicode2.c ***********************************/ /* ** 2012 May 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** */ /* ** DO NOT EDIT THIS MACHINE GENERATED FILE. */ #ifndef SQLITE_DISABLE_FTS3_UNICODE #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) /* #include <assert.h> */ /* ** Return true if the argument corresponds to a unicode codepoint ** classified as either a letter or a number. Otherwise false. ** ** The results are undefined if the value passed to this function ** is less than zero. */ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){ /* Each unsigned integer in the following array corresponds to a contiguous ** range of unicode codepoints that are not either letters or numbers (i.e. ** codepoints for which this function should return 0). ** ** The most significant 22 bits in each 32-bit value contain the first ** codepoint in the range. The least significant 10 bits are used to store ** the size of the range (always at least 1). In other words, the value ** ((C<<22) + N) represents a range of N codepoints starting with codepoint ** C. It is not possible to represent a range larger than 1023 codepoints ** using this format. */ static const unsigned int aEntry[] = { 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07, 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01, 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401, 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01, 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01, 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802, 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F, 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401, 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804, 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403, 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812, 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001, 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802, 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805, 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401, 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03, 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807, 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001, 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01, 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804, 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001, 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802, 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01, 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06, 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007, 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006, 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417, 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14, 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07, 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01, 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001, 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802, 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F, 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002, 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802, 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006, 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D, 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802, 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027, 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403, 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805, 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04, 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401, 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005, 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B, 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A, 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001, 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59, 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807, 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01, 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E, 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100, 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10, 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402, 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804, 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012, 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004, 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002, 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803, 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07, 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02, 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060, 0x380400F0, }; static const unsigned int aAscii[4] = { 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001, }; if( c<128 ){ return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 ); }else if( c<(1<<22) ){ unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; int iRes = 0; int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; int iLo = 0; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( key >= aEntry[iTest] ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( aEntry[0]<key ); assert( key>=aEntry[iRes] ); return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF))); } return 1; } /* ** If the argument is a codepoint corresponding to a lowercase letter ** in the ASCII range with a diacritic added, return the codepoint ** of the ASCII letter only. For example, if passed 235 - "LATIN ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER ** E"). The resuls of passing a codepoint that corresponds to an ** uppercase letter are undefined. */ static int remove_diacritic(int c){ unsigned short aDia[] = { 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995, 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286, 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732, 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336, 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928, 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504, 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62924, 63050, 63082, 63274, 63390, }; char aChar[] = { '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c', 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r', 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o', 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r', 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h', 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't', 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a', 'e', 'i', 'o', 'u', 'y', }; unsigned int key = (((unsigned int)c)<<3) | 0x00000007; int iRes = 0; int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1; int iLo = 0; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( key >= aDia[iTest] ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( key>=aDia[iRes] ); return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]); } /* ** Return true if the argument interpreted as a unicode codepoint ** is a diacritical modifier character. */ SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){ unsigned int mask0 = 0x08029FDF; unsigned int mask1 = 0x000361F8; if( c<768 || c>817 ) return 0; return (c < 768+32) ? (mask0 & (1 << (c-768))) : (mask1 & (1 << (c-768-32))); } /* ** Interpret the argument as a unicode codepoint. If the codepoint ** is an upper case character that has a lower case equivalent, ** return the codepoint corresponding to the lower case version. ** Otherwise, return a copy of the argument. ** ** The results are undefined if the value passed to this function ** is less than zero. */ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ /* Each entry in the following array defines a rule for folding a range ** of codepoints to lower case. The rule applies to a range of nRange ** codepoints starting at codepoint iCode. ** ** If the least significant bit in flags is clear, then the rule applies ** to all nRange codepoints (i.e. all nRange codepoints are upper case and ** need to be folded). Or, if it is set, then the rule only applies to ** every second codepoint in the range, starting with codepoint C. ** ** The 7 most significant bits in flags are an index into the aiOff[] ** array. If a specific codepoint C does require folding, then its lower ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF). ** ** The contents of this array are generated by parsing the CaseFolding.txt ** file distributed as part of the "Unicode Character Database". See ** http://www.unicode.org for details. */ static const struct TableEntry { unsigned short iCode; unsigned char flags; unsigned char nRange; } aEntry[] = { {65, 14, 26}, {181, 64, 1}, {192, 14, 23}, {216, 14, 7}, {256, 1, 48}, {306, 1, 6}, {313, 1, 16}, {330, 1, 46}, {376, 116, 1}, {377, 1, 6}, {383, 104, 1}, {385, 50, 1}, {386, 1, 4}, {390, 44, 1}, {391, 0, 1}, {393, 42, 2}, {395, 0, 1}, {398, 32, 1}, {399, 38, 1}, {400, 40, 1}, {401, 0, 1}, {403, 42, 1}, {404, 46, 1}, {406, 52, 1}, {407, 48, 1}, {408, 0, 1}, {412, 52, 1}, {413, 54, 1}, {415, 56, 1}, {416, 1, 6}, {422, 60, 1}, {423, 0, 1}, {425, 60, 1}, {428, 0, 1}, {430, 60, 1}, {431, 0, 1}, {433, 58, 2}, {435, 1, 4}, {439, 62, 1}, {440, 0, 1}, {444, 0, 1}, {452, 2, 1}, {453, 0, 1}, {455, 2, 1}, {456, 0, 1}, {458, 2, 1}, {459, 1, 18}, {478, 1, 18}, {497, 2, 1}, {498, 1, 4}, {502, 122, 1}, {503, 134, 1}, {504, 1, 40}, {544, 110, 1}, {546, 1, 18}, {570, 70, 1}, {571, 0, 1}, {573, 108, 1}, {574, 68, 1}, {577, 0, 1}, {579, 106, 1}, {580, 28, 1}, {581, 30, 1}, {582, 1, 10}, {837, 36, 1}, {880, 1, 4}, {886, 0, 1}, {902, 18, 1}, {904, 16, 3}, {908, 26, 1}, {910, 24, 2}, {913, 14, 17}, {931, 14, 9}, {962, 0, 1}, {975, 4, 1}, {976, 140, 1}, {977, 142, 1}, {981, 146, 1}, {982, 144, 1}, {984, 1, 24}, {1008, 136, 1}, {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1}, {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1}, {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32}, {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1}, {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38}, {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1}, {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1}, {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6}, {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6}, {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8}, {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2}, {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1}, {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2}, {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2}, {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2}, {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1}, {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16}, {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47}, {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1}, {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1}, {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1}, {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2}, {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1}, {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14}, {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1}, {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1}, {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1}, {65313, 14, 26}, }; static const unsigned short aiOff[] = { 1, 2, 8, 15, 16, 26, 28, 32, 37, 38, 40, 48, 63, 64, 69, 71, 79, 80, 116, 202, 203, 205, 206, 207, 209, 210, 211, 213, 214, 217, 218, 219, 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721, 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 65514, 65521, 65527, 65528, 65529, }; int ret = c; assert( c>=0 ); assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 ); if( c<128 ){ if( c>='A' && c<='Z' ) ret = c + ('a' - 'A'); }else if( c<65536 ){ int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; int iLo = 0; int iRes = -1; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; int cmp = (c - aEntry[iTest].iCode); if( cmp>=0 ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( iRes<0 || c>=aEntry[iRes].iCode ); if( iRes>=0 ){ const struct TableEntry *p = &aEntry[iRes]; if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; assert( ret>0 ); } } if( bRemoveDiacritic ) ret = remove_diacritic(ret); } else if( c>=66560 && c<66600 ){ ret = c + 40; } return ret; } #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */ #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */ /************** End of fts3_unicode2.c ***************************************/ /************** Begin file rtree.c *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code for implementations of the r-tree and r*-tree ** algorithms packaged as an SQLite virtual table module. */ /* ** Database Format of R-Tree Tables ** -------------------------------- ** ** The data structure for a single virtual r-tree table is stored in three ** native SQLite tables declared as follows. In each case, the '%' character ** in the table name is replaced with the user-supplied name of the r-tree ** table. ** ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB) ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER) ** ** The data for each node of the r-tree structure is stored in the %_node ** table. For each node that is not the root node of the r-tree, there is ** an entry in the %_parent table associating the node with its parent. ** And for each row of data in the table, there is an entry in the %_rowid ** table that maps from the entries rowid to the id of the node that it ** is stored on. ** ** The root node of an r-tree always exists, even if the r-tree table is ** empty. The nodeno of the root node is always 1. All other nodes in the ** table must be the same size as the root node. The content of each node ** is formatted as follows: ** ** 1. If the node is the root node (node 1), then the first 2 bytes ** of the node contain the tree depth as a big-endian integer. ** For non-root nodes, the first 2 bytes are left unused. ** ** 2. The next 2 bytes contain the number of entries currently ** stored in the node. ** ** 3. The remainder of the node contains the node entries. Each entry ** consists of a single 8-byte integer followed by an even number ** of 4-byte coordinates. For leaf nodes the integer is the rowid ** of a record. For internal nodes it is the node number of a ** child page. */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE) #ifndef SQLITE_CORE /* #include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #else /* #include "sqlite3.h" */ #endif /* #include <string.h> */ /* #include <assert.h> */ /* #include <stdio.h> */ #ifndef SQLITE_AMALGAMATION #include "sqlite3rtree.h" typedef sqlite3_int64 i64; typedef sqlite3_uint64 u64; typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; #endif /* The following macro is used to suppress compiler warnings. */ #ifndef UNUSED_PARAMETER # define UNUSED_PARAMETER(x) (void)(x) #endif typedef struct Rtree Rtree; typedef struct RtreeCursor RtreeCursor; typedef struct RtreeNode RtreeNode; typedef struct RtreeCell RtreeCell; typedef struct RtreeConstraint RtreeConstraint; typedef struct RtreeMatchArg RtreeMatchArg; typedef struct RtreeGeomCallback RtreeGeomCallback; typedef union RtreeCoord RtreeCoord; typedef struct RtreeSearchPoint RtreeSearchPoint; /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ #define RTREE_MAX_DIMENSIONS 5 /* Size of hash table Rtree.aHash. This hash table is not expected to ** ever contain very many entries, so a fixed number of buckets is ** used. */ #define HASHSIZE 97 /* The xBestIndex method of this virtual table requires an estimate of ** the number of rows in the virtual table to calculate the costs of ** various strategies. If possible, this estimate is loaded from the ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum). ** Otherwise, if no sqlite_stat1 entry is available, use ** RTREE_DEFAULT_ROWEST. */ #define RTREE_DEFAULT_ROWEST 1048576 #define RTREE_MIN_ROWEST 100 /* ** An rtree virtual-table object. */ struct Rtree { sqlite3_vtab base; /* Base class. Must be first */ sqlite3 *db; /* Host database connection */ int iNodeSize; /* Size in bytes of each node in the node table */ u8 nDim; /* Number of dimensions */ u8 nDim2; /* Twice the number of dimensions */ u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */ u8 nBytesPerCell; /* Bytes consumed per cell */ u8 inWrTrans; /* True if inside write transaction */ int iDepth; /* Current depth of the r-tree structure */ char *zDb; /* Name of database containing r-tree table */ char *zName; /* Name of r-tree table */ u32 nBusy; /* Current number of users of this structure */ i64 nRowEst; /* Estimated number of rows in this table */ u32 nCursor; /* Number of open cursors */ /* List of nodes removed during a CondenseTree operation. List is ** linked together via the pointer normally used for hash chains - ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree ** headed by the node (leaf nodes have RtreeNode.iNode==0). */ RtreeNode *pDeleted; int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ /* Blob I/O on xxx_node */ sqlite3_blob *pNodeBlob; /* Statements to read/write/delete a record from xxx_node */ sqlite3_stmt *pWriteNode; sqlite3_stmt *pDeleteNode; /* Statements to read/write/delete a record from xxx_rowid */ sqlite3_stmt *pReadRowid; sqlite3_stmt *pWriteRowid; sqlite3_stmt *pDeleteRowid; /* Statements to read/write/delete a record from xxx_parent */ sqlite3_stmt *pReadParent; sqlite3_stmt *pWriteParent; sqlite3_stmt *pDeleteParent; RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ }; /* Possible values for Rtree.eCoordType: */ #define RTREE_COORD_REAL32 0 #define RTREE_COORD_INT32 1 /* ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will ** only deal with integer coordinates. No floating point operations ** will be done. */ #ifdef SQLITE_RTREE_INT_ONLY typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */ typedef int RtreeValue; /* Low accuracy coordinate */ # define RTREE_ZERO 0 #else typedef double RtreeDValue; /* High accuracy coordinate */ typedef float RtreeValue; /* Low accuracy coordinate */ # define RTREE_ZERO 0.0 #endif /* ** When doing a search of an r-tree, instances of the following structure ** record intermediate results from the tree walk. ** ** The id is always a node-id. For iLevel>=1 the id is the node-id of ** the node that the RtreeSearchPoint represents. When iLevel==0, however, ** the id is of the parent node and the cell that RtreeSearchPoint ** represents is the iCell-th entry in the parent node. */ struct RtreeSearchPoint { RtreeDValue rScore; /* The score for this node. Smallest goes first. */ sqlite3_int64 id; /* Node ID */ u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */ u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */ u8 iCell; /* Cell index within the node */ }; /* ** The minimum number of cells allowed for a node is a third of the ** maximum. In Gutman's notation: ** ** m = M/3 ** ** If an R*-tree "Reinsert" operation is required, the same number of ** cells are removed from the overfull node and reinserted into the tree. */ #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3) #define RTREE_REINSERT(p) RTREE_MINCELLS(p) #define RTREE_MAXCELLS 51 /* ** The smallest possible node-size is (512-64)==448 bytes. And the largest ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates). ** Therefore all non-root nodes must contain at least 3 entries. Since ** 2^40 is greater than 2^64, an r-tree structure always has a depth of ** 40 or less. */ #define RTREE_MAX_DEPTH 40 /* ** Number of entries in the cursor RtreeNode cache. The first entry is ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining ** entries cache the RtreeNode for the first elements of the priority queue. */ #define RTREE_CACHE_SZ 5 /* ** An rtree cursor object. */ struct RtreeCursor { sqlite3_vtab_cursor base; /* Base class. Must be first */ u8 atEOF; /* True if at end of search */ u8 bPoint; /* True if sPoint is valid */ int iStrategy; /* Copy of idxNum search parameter */ int nConstraint; /* Number of entries in aConstraint */ RtreeConstraint *aConstraint; /* Search constraints. */ int nPointAlloc; /* Number of slots allocated for aPoint[] */ int nPoint; /* Number of slots used in aPoint[] */ int mxLevel; /* iLevel value for root of the tree */ RtreeSearchPoint *aPoint; /* Priority queue for search points */ RtreeSearchPoint sPoint; /* Cached next search point */ RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */ u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */ }; /* Return the Rtree of a RtreeCursor */ #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab)) /* ** A coordinate can be either a floating point number or a integer. All ** coordinates within a single R-Tree are always of the same time. */ union RtreeCoord { RtreeValue f; /* Floating point value */ int i; /* Integer value */ u32 u; /* Unsigned for byte-order conversions */ }; /* ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord ** formatted as a RtreeDValue (double or int64). This macro assumes that local ** variable pRtree points to the Rtree structure associated with the ** RtreeCoord. */ #ifdef SQLITE_RTREE_INT_ONLY # define DCOORD(coord) ((RtreeDValue)coord.i) #else # define DCOORD(coord) ( \ (pRtree->eCoordType==RTREE_COORD_REAL32) ? \ ((double)coord.f) : \ ((double)coord.i) \ ) #endif /* ** A search constraint. */ struct RtreeConstraint { int iCoord; /* Index of constrained coordinate */ int op; /* Constraining operation */ union { RtreeDValue rValue; /* Constraint value. */ int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*); int (*xQueryFunc)(sqlite3_rtree_query_info*); } u; sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */ }; /* Possible values for RtreeConstraint.op */ #define RTREE_EQ 0x41 /* A */ #define RTREE_LE 0x42 /* B */ #define RTREE_LT 0x43 /* C */ #define RTREE_GE 0x44 /* D */ #define RTREE_GT 0x45 /* E */ #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */ #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */ /* ** An rtree structure node. */ struct RtreeNode { RtreeNode *pParent; /* Parent node */ i64 iNode; /* The node number */ int nRef; /* Number of references to this node */ int isDirty; /* True if the node needs to be written to disk */ u8 *zData; /* Content of the node, as should be on disk */ RtreeNode *pNext; /* Next node in this hash collision chain */ }; /* Return the number of cells in a node */ #define NCELL(pNode) readInt16(&(pNode)->zData[2]) /* ** A single cell from a node, deserialized */ struct RtreeCell { i64 iRowid; /* Node or entry ID */ RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */ }; /* ** This object becomes the sqlite3_user_data() for the SQL functions ** that are created by sqlite3_rtree_geometry_callback() and ** sqlite3_rtree_query_callback() and which appear on the right of MATCH ** operators in order to constrain a search. ** ** xGeom and xQueryFunc are the callback functions. Exactly one of ** xGeom and xQueryFunc fields is non-NULL, depending on whether the ** SQL function was created using sqlite3_rtree_geometry_callback() or ** sqlite3_rtree_query_callback(). ** ** This object is deleted automatically by the destructor mechanism in ** sqlite3_create_function_v2(). */ struct RtreeGeomCallback { int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); int (*xQueryFunc)(sqlite3_rtree_query_info*); void (*xDestructor)(void*); void *pContext; }; /* ** Value for the first field of every RtreeMatchArg object. The MATCH ** operator tests that the first field of a blob operand matches this ** value to avoid operating on invalid blobs (which could cause a segfault). */ #define RTREE_GEOMETRY_MAGIC 0x891245AB /* ** An instance of this structure (in the form of a BLOB) is returned by ** the SQL functions that sqlite3_rtree_geometry_callback() and ** sqlite3_rtree_query_callback() create, and is read as the right-hand ** operand to the MATCH operator of an R-Tree. */ struct RtreeMatchArg { u32 magic; /* Always RTREE_GEOMETRY_MAGIC */ RtreeGeomCallback cb; /* Info about the callback functions */ int nParam; /* Number of parameters to the SQL function */ sqlite3_value **apSqlParam; /* Original SQL parameter values */ RtreeDValue aParam[1]; /* Values for parameters to the SQL function */ }; #ifndef MAX # define MAX(x,y) ((x) < (y) ? (y) : (x)) #endif #ifndef MIN # define MIN(x,y) ((x) > (y) ? (y) : (x)) #endif /* What version of GCC is being used. 0 means GCC is not being used */ #ifndef GCC_VERSION #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) #else # define GCC_VERSION 0 #endif #endif /* What version of CLANG is being used. 0 means CLANG is not being used */ #ifndef CLANG_VERSION #if defined(__clang__) && !defined(_WIN32) && !defined(SQLITE_DISABLE_INTRINSIC) # define CLANG_VERSION \ (__clang_major__*1000000+__clang_minor__*1000+__clang_patchlevel__) #else # define CLANG_VERSION 0 #endif #endif /* The testcase() macro should already be defined in the amalgamation. If ** it is not, make it a no-op. */ #ifndef SQLITE_AMALGAMATION # define testcase(X) #endif /* ** Macros to determine whether the machine is big or little endian, ** and whether or not that determination is run-time or compile-time. ** ** For best performance, an attempt is made to guess at the byte-order ** using C-preprocessor macros. If that is unsuccessful, or if ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined ** at run-time. */ #ifndef SQLITE_BYTEORDER #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ defined(__arm__) # define SQLITE_BYTEORDER 1234 #elif defined(sparc) || defined(__ppc__) # define SQLITE_BYTEORDER 4321 #else # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */ #endif #endif /* What version of MSVC is being used. 0 means MSVC is not being used */ #ifndef MSVC_VERSION #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) # define MSVC_VERSION _MSC_VER #else # define MSVC_VERSION 0 #endif #endif /* ** Functions to deserialize a 16 bit integer, 32 bit real number and ** 64 bit integer. The deserialized value is returned. */ static int readInt16(u8 *p){ return (p[0]<<8) + p[1]; } static void readCoord(u8 *p, RtreeCoord *pCoord){ assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */ #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 pCoord->u = _byteswap_ulong(*(u32*)p); #elif SQLITE_BYTEORDER==1234 && (GCC_VERSION>=4003000 || CLANG_VERSION>=3000000) pCoord->u = __builtin_bswap32(*(u32*)p); #elif SQLITE_BYTEORDER==4321 pCoord->u = *(u32*)p; #else pCoord->u = ( (((u32)p[0]) << 24) + (((u32)p[1]) << 16) + (((u32)p[2]) << 8) + (((u32)p[3]) << 0) ); #endif } static i64 readInt64(u8 *p){ #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u64 x; memcpy(&x, p, 8); return (i64)_byteswap_uint64(x); #elif SQLITE_BYTEORDER==1234 && (GCC_VERSION>=4003000 || CLANG_VERSION>=3000000) u64 x; memcpy(&x, p, 8); return (i64)__builtin_bswap64(x); #elif SQLITE_BYTEORDER==4321 i64 x; memcpy(&x, p, 8); return x; #else return ( (((i64)p[0]) << 56) + (((i64)p[1]) << 48) + (((i64)p[2]) << 40) + (((i64)p[3]) << 32) + (((i64)p[4]) << 24) + (((i64)p[5]) << 16) + (((i64)p[6]) << 8) + (((i64)p[7]) << 0) ); #endif } /* ** Functions to serialize a 16 bit integer, 32 bit real number and ** 64 bit integer. The value returned is the number of bytes written ** to the argument buffer (always 2, 4 and 8 respectively). */ static void writeInt16(u8 *p, int i){ p[0] = (i>> 8)&0xFF; p[1] = (i>> 0)&0xFF; } static int writeCoord(u8 *p, RtreeCoord *pCoord){ u32 i; assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */ assert( sizeof(RtreeCoord)==4 ); assert( sizeof(u32)==4 ); #if SQLITE_BYTEORDER==1234 && (GCC_VERSION>=4003000 || CLANG_VERSION>=3000000) i = __builtin_bswap32(pCoord->u); memcpy(p, &i, 4); #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 i = _byteswap_ulong(pCoord->u); memcpy(p, &i, 4); #elif SQLITE_BYTEORDER==4321 i = pCoord->u; memcpy(p, &i, 4); #else i = pCoord->u; p[0] = (i>>24)&0xFF; p[1] = (i>>16)&0xFF; p[2] = (i>> 8)&0xFF; p[3] = (i>> 0)&0xFF; #endif return 4; } static int writeInt64(u8 *p, i64 i){ #if SQLITE_BYTEORDER==1234 && (GCC_VERSION>=4003000 || CLANG_VERSION>=3000000) i = (i64)__builtin_bswap64((u64)i); memcpy(p, &i, 8); #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 i = (i64)_byteswap_uint64((u64)i); memcpy(p, &i, 8); #elif SQLITE_BYTEORDER==4321 memcpy(p, &i, 8); #else p[0] = (i>>56)&0xFF; p[1] = (i>>48)&0xFF; p[2] = (i>>40)&0xFF; p[3] = (i>>32)&0xFF; p[4] = (i>>24)&0xFF; p[5] = (i>>16)&0xFF; p[6] = (i>> 8)&0xFF; p[7] = (i>> 0)&0xFF; #endif return 8; } /* ** Increment the reference count of node p. */ static void nodeReference(RtreeNode *p){ if( p ){ p->nRef++; } } /* ** Clear the content of node p (set all bytes to 0x00). */ static void nodeZero(Rtree *pRtree, RtreeNode *p){ memset(&p->zData[2], 0, pRtree->iNodeSize-2); p->isDirty = 1; } /* ** Given a node number iNode, return the corresponding key to use ** in the Rtree.aHash table. */ static int nodeHash(i64 iNode){ return iNode % HASHSIZE; } /* ** Search the node hash table for node iNode. If found, return a pointer ** to it. Otherwise, return 0. */ static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){ RtreeNode *p; for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext); return p; } /* ** Add node pNode to the node hash table. */ static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){ int iHash; assert( pNode->pNext==0 ); iHash = nodeHash(pNode->iNode); pNode->pNext = pRtree->aHash[iHash]; pRtree->aHash[iHash] = pNode; } /* ** Remove node pNode from the node hash table. */ static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ RtreeNode **pp; if( pNode->iNode!=0 ){ pp = &pRtree->aHash[nodeHash(pNode->iNode)]; for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); } *pp = pNode->pNext; pNode->pNext = 0; } } /* ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0), ** indicating that node has not yet been assigned a node number. It is ** assigned a node number when nodeWrite() is called to write the ** node contents out to the database. */ static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){ RtreeNode *pNode; pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); if( pNode ){ memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize); pNode->zData = (u8 *)&pNode[1]; pNode->nRef = 1; pNode->pParent = pParent; pNode->isDirty = 1; nodeReference(pParent); } return pNode; } /* ** Clear the Rtree.pNodeBlob object */ static void nodeBlobReset(Rtree *pRtree){ if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){ sqlite3_blob *pBlob = pRtree->pNodeBlob; pRtree->pNodeBlob = 0; sqlite3_blob_close(pBlob); } } /* ** Obtain a reference to an r-tree node. */ static int nodeAcquire( Rtree *pRtree, /* R-tree structure */ i64 iNode, /* Node number to load */ RtreeNode *pParent, /* Either the parent node or NULL */ RtreeNode **ppNode /* OUT: Acquired node */ ){ int rc = SQLITE_OK; RtreeNode *pNode = 0; /* Check if the requested node is already in the hash table. If so, ** increase its reference count and return it. */ if( (pNode = nodeHashLookup(pRtree, iNode)) ){ assert( !pParent || !pNode->pParent || pNode->pParent==pParent ); if( pParent && !pNode->pParent ){ nodeReference(pParent); pNode->pParent = pParent; } pNode->nRef++; *ppNode = pNode; return SQLITE_OK; } if( pRtree->pNodeBlob ){ sqlite3_blob *pBlob = pRtree->pNodeBlob; pRtree->pNodeBlob = 0; rc = sqlite3_blob_reopen(pBlob, iNode); pRtree->pNodeBlob = pBlob; if( rc ){ nodeBlobReset(pRtree); if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM; } } if( pRtree->pNodeBlob==0 ){ char *zTab = sqlite3_mprintf("%s_node", pRtree->zName); if( zTab==0 ) return SQLITE_NOMEM; rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0, &pRtree->pNodeBlob); sqlite3_free(zTab); } if( rc ){ nodeBlobReset(pRtree); *ppNode = 0; /* If unable to open an sqlite3_blob on the desired row, that can only ** be because the shadow tables hold erroneous data. */ if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB; }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){ pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize); if( !pNode ){ rc = SQLITE_NOMEM; }else{ pNode->pParent = pParent; pNode->zData = (u8 *)&pNode[1]; pNode->nRef = 1; pNode->iNode = iNode; pNode->isDirty = 0; pNode->pNext = 0; rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData, pRtree->iNodeSize, 0); nodeReference(pParent); } } /* If the root node was just loaded, set pRtree->iDepth to the height ** of the r-tree structure. A height of zero means all data is stored on ** the root node. A height of one means the children of the root node ** are the leaves, and so on. If the depth as specified on the root node ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt. */ if( pNode && iNode==1 ){ pRtree->iDepth = readInt16(pNode->zData); if( pRtree->iDepth>RTREE_MAX_DEPTH ){ rc = SQLITE_CORRUPT_VTAB; } } /* If no error has occurred so far, check if the "number of entries" ** field on the node is too large. If so, set the return code to ** SQLITE_CORRUPT_VTAB. */ if( pNode && rc==SQLITE_OK ){ if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){ rc = SQLITE_CORRUPT_VTAB; } } if( rc==SQLITE_OK ){ if( pNode!=0 ){ nodeHashInsert(pRtree, pNode); }else{ rc = SQLITE_CORRUPT_VTAB; } *ppNode = pNode; }else{ sqlite3_free(pNode); *ppNode = 0; } return rc; } /* ** Overwrite cell iCell of node pNode with the contents of pCell. */ static void nodeOverwriteCell( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* The node into which the cell is to be written */ RtreeCell *pCell, /* The cell to write */ int iCell /* Index into pNode into which pCell is written */ ){ int ii; u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; p += writeInt64(p, pCell->iRowid); for(ii=0; ii<pRtree->nDim2; ii++){ p += writeCoord(p, &pCell->aCoord[ii]); } pNode->isDirty = 1; } /* ** Remove the cell with index iCell from node pNode. */ static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){ u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; u8 *pSrc = &pDst[pRtree->nBytesPerCell]; int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell; memmove(pDst, pSrc, nByte); writeInt16(&pNode->zData[2], NCELL(pNode)-1); pNode->isDirty = 1; } /* ** Insert the contents of cell pCell into node pNode. If the insert ** is successful, return SQLITE_OK. ** ** If there is not enough free space in pNode, return SQLITE_FULL. */ static int nodeInsertCell( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* Write new cell into this node */ RtreeCell *pCell /* The cell to be inserted */ ){ int nCell; /* Current number of cells in pNode */ int nMaxCell; /* Maximum number of cells for pNode */ nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell; nCell = NCELL(pNode); assert( nCell<=nMaxCell ); if( nCell<nMaxCell ){ nodeOverwriteCell(pRtree, pNode, pCell, nCell); writeInt16(&pNode->zData[2], nCell+1); pNode->isDirty = 1; } return (nCell==nMaxCell); } /* ** If the node is dirty, write it out to the database. */ static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){ int rc = SQLITE_OK; if( pNode->isDirty ){ sqlite3_stmt *p = pRtree->pWriteNode; if( pNode->iNode ){ sqlite3_bind_int64(p, 1, pNode->iNode); }else{ sqlite3_bind_null(p, 1); } sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); sqlite3_step(p); pNode->isDirty = 0; rc = sqlite3_reset(p); if( pNode->iNode==0 && rc==SQLITE_OK ){ pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); nodeHashInsert(pRtree, pNode); } } return rc; } /* ** Release a reference to a node. If the node is dirty and the reference ** count drops to zero, the node data is written to the database. */ static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){ int rc = SQLITE_OK; if( pNode ){ assert( pNode->nRef>0 ); pNode->nRef--; if( pNode->nRef==0 ){ if( pNode->iNode==1 ){ pRtree->iDepth = -1; } if( pNode->pParent ){ rc = nodeRelease(pRtree, pNode->pParent); } if( rc==SQLITE_OK ){ rc = nodeWrite(pRtree, pNode); } nodeHashDelete(pRtree, pNode); sqlite3_free(pNode); } } return rc; } /* ** Return the 64-bit integer value associated with cell iCell of ** node pNode. If pNode is a leaf node, this is a rowid. If it is ** an internal node, then the 64-bit integer is a child page number. */ static i64 nodeGetRowid( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* The node from which to extract the ID */ int iCell /* The cell index from which to extract the ID */ ){ assert( iCell<NCELL(pNode) ); return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]); } /* ** Return coordinate iCoord from cell iCell in node pNode. */ static void nodeGetCoord( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* The node from which to extract a coordinate */ int iCell, /* The index of the cell within the node */ int iCoord, /* Which coordinate to extract */ RtreeCoord *pCoord /* OUT: Space to write result to */ ){ readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord); } /* ** Deserialize cell iCell of node pNode. Populate the structure pointed ** to by pCell with the results. */ static void nodeGetCell( Rtree *pRtree, /* The overall R-Tree */ RtreeNode *pNode, /* The node containing the cell to be read */ int iCell, /* Index of the cell within the node */ RtreeCell *pCell /* OUT: Write the cell contents here */ ){ u8 *pData; RtreeCoord *pCoord; int ii = 0; pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell); pCoord = pCell->aCoord; do{ readCoord(pData, &pCoord[ii]); readCoord(pData+4, &pCoord[ii+1]); pData += 8; ii += 2; }while( ii<pRtree->nDim2 ); } /* Forward declaration for the function that does the work of ** the virtual table module xCreate() and xConnect() methods. */ static int rtreeInit( sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int ); /* ** Rtree virtual table module xCreate method. */ static int rtreeCreate( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1); } /* ** Rtree virtual table module xConnect method. */ static int rtreeConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0); } /* ** Increment the r-tree reference count. */ static void rtreeReference(Rtree *pRtree){ pRtree->nBusy++; } /* ** Decrement the r-tree reference count. When the reference count reaches ** zero the structure is deleted. */ static void rtreeRelease(Rtree *pRtree){ pRtree->nBusy--; if( pRtree->nBusy==0 ){ pRtree->inWrTrans = 0; pRtree->nCursor = 0; nodeBlobReset(pRtree); sqlite3_finalize(pRtree->pWriteNode); sqlite3_finalize(pRtree->pDeleteNode); sqlite3_finalize(pRtree->pReadRowid); sqlite3_finalize(pRtree->pWriteRowid); sqlite3_finalize(pRtree->pDeleteRowid); sqlite3_finalize(pRtree->pReadParent); sqlite3_finalize(pRtree->pWriteParent); sqlite3_finalize(pRtree->pDeleteParent); sqlite3_free(pRtree); } } /* ** Rtree virtual table module xDisconnect method. */ static int rtreeDisconnect(sqlite3_vtab *pVtab){ rtreeRelease((Rtree *)pVtab); return SQLITE_OK; } /* ** Rtree virtual table module xDestroy method. */ static int rtreeDestroy(sqlite3_vtab *pVtab){ Rtree *pRtree = (Rtree *)pVtab; int rc; char *zCreate = sqlite3_mprintf( "DROP TABLE '%q'.'%q_node';" "DROP TABLE '%q'.'%q_rowid';" "DROP TABLE '%q'.'%q_parent';", pRtree->zDb, pRtree->zName, pRtree->zDb, pRtree->zName, pRtree->zDb, pRtree->zName ); if( !zCreate ){ rc = SQLITE_NOMEM; }else{ nodeBlobReset(pRtree); rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); sqlite3_free(zCreate); } if( rc==SQLITE_OK ){ rtreeRelease(pRtree); } return rc; } /* ** Rtree virtual table module xOpen method. */ static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ int rc = SQLITE_NOMEM; Rtree *pRtree = (Rtree *)pVTab; RtreeCursor *pCsr; pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor)); if( pCsr ){ memset(pCsr, 0, sizeof(RtreeCursor)); pCsr->base.pVtab = pVTab; rc = SQLITE_OK; pRtree->nCursor++; } *ppCursor = (sqlite3_vtab_cursor *)pCsr; return rc; } /* ** Free the RtreeCursor.aConstraint[] array and its contents. */ static void freeCursorConstraints(RtreeCursor *pCsr){ if( pCsr->aConstraint ){ int i; /* Used to iterate through constraint array */ for(i=0; i<pCsr->nConstraint; i++){ sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo; if( pInfo ){ if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser); sqlite3_free(pInfo); } } sqlite3_free(pCsr->aConstraint); pCsr->aConstraint = 0; } } /* ** Rtree virtual table module xClose method. */ static int rtreeClose(sqlite3_vtab_cursor *cur){ Rtree *pRtree = (Rtree *)(cur->pVtab); int ii; RtreeCursor *pCsr = (RtreeCursor *)cur; assert( pRtree->nCursor>0 ); freeCursorConstraints(pCsr); sqlite3_free(pCsr->aPoint); for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]); sqlite3_free(pCsr); pRtree->nCursor--; nodeBlobReset(pRtree); return SQLITE_OK; } /* ** Rtree virtual table module xEof method. ** ** Return non-zero if the cursor does not currently point to a valid ** record (i.e if the scan has finished), or zero otherwise. */ static int rtreeEof(sqlite3_vtab_cursor *cur){ RtreeCursor *pCsr = (RtreeCursor *)cur; return pCsr->atEOF; } /* ** Convert raw bits from the on-disk RTree record into a coordinate value. ** The on-disk format is big-endian and needs to be converted for little- ** endian platforms. The on-disk record stores integer coordinates if ** eInt is true and it stores 32-bit floating point records if eInt is ** false. a[] is the four bytes of the on-disk record to be decoded. ** Store the results in "r". ** ** There are five versions of this macro. The last one is generic. The ** other four are various architectures-specific optimizations. */ #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ c.u = _byteswap_ulong(*(u32*)a); \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #elif SQLITE_BYTEORDER==1234 && (GCC_VERSION>=4003000 || CLANG_VERSION>=3000000) #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ c.u = __builtin_bswap32(*(u32*)a); \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #elif SQLITE_BYTEORDER==1234 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ memcpy(&c.u,a,4); \ c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \ ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #elif SQLITE_BYTEORDER==4321 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ memcpy(&c.u,a,4); \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #else #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \ +((u32)a[2]<<8) + a[3]; \ r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ } #endif /* ** Check the RTree node or entry given by pCellData and p against the MATCH ** constraint pConstraint. */ static int rtreeCallbackConstraint( RtreeConstraint *pConstraint, /* The constraint to test */ int eInt, /* True if RTree holding integer coordinates */ u8 *pCellData, /* Raw cell content */ RtreeSearchPoint *pSearch, /* Container of this cell */ sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */ int *peWithin /* OUT: visibility of the cell */ ){ sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */ int nCoord = pInfo->nCoord; /* No. of coordinates */ int rc; /* Callback return code */ RtreeCoord c; /* Translator union */ sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */ assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY ); assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 ); if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){ pInfo->iRowid = readInt64(pCellData); } pCellData += 8; #ifndef SQLITE_RTREE_INT_ONLY if( eInt==0 ){ switch( nCoord ){ case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f; readCoord(pCellData+32, &c); aCoord[8] = c.f; case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f; readCoord(pCellData+24, &c); aCoord[6] = c.f; case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f; readCoord(pCellData+16, &c); aCoord[4] = c.f; case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f; readCoord(pCellData+8, &c); aCoord[2] = c.f; default: readCoord(pCellData+4, &c); aCoord[1] = c.f; readCoord(pCellData, &c); aCoord[0] = c.f; } }else #endif { switch( nCoord ){ case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i; readCoord(pCellData+32, &c); aCoord[8] = c.i; case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i; readCoord(pCellData+24, &c); aCoord[6] = c.i; case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i; readCoord(pCellData+16, &c); aCoord[4] = c.i; case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i; readCoord(pCellData+8, &c); aCoord[2] = c.i; default: readCoord(pCellData+4, &c); aCoord[1] = c.i; readCoord(pCellData, &c); aCoord[0] = c.i; } } if( pConstraint->op==RTREE_MATCH ){ int eWithin = 0; rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo, nCoord, aCoord, &eWithin); if( eWithin==0 ) *peWithin = NOT_WITHIN; *prScore = RTREE_ZERO; }else{ pInfo->aCoord = aCoord; pInfo->iLevel = pSearch->iLevel - 1; pInfo->rScore = pInfo->rParentScore = pSearch->rScore; pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin; rc = pConstraint->u.xQueryFunc(pInfo); if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin; if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){ *prScore = pInfo->rScore; } } return rc; } /* ** Check the internal RTree node given by pCellData against constraint p. ** If this constraint cannot be satisfied by any child within the node, ** set *peWithin to NOT_WITHIN. */ static void rtreeNonleafConstraint( RtreeConstraint *p, /* The constraint to test */ int eInt, /* True if RTree holds integer coordinates */ u8 *pCellData, /* Raw cell content as appears on disk */ int *peWithin /* Adjust downward, as appropriate */ ){ sqlite3_rtree_dbl val; /* Coordinate value convert to a double */ /* p->iCoord might point to either a lower or upper bound coordinate ** in a coordinate pair. But make pCellData point to the lower bound. */ pCellData += 8 + 4*(p->iCoord&0xfe); assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE || p->op==RTREE_GT || p->op==RTREE_EQ ); assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ switch( p->op ){ case RTREE_LE: case RTREE_LT: case RTREE_EQ: RTREE_DECODE_COORD(eInt, pCellData, val); /* val now holds the lower bound of the coordinate pair */ if( p->u.rValue>=val ) return; if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */ /* Fall through for the RTREE_EQ case */ default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */ pCellData += 4; RTREE_DECODE_COORD(eInt, pCellData, val); /* val now holds the upper bound of the coordinate pair */ if( p->u.rValue<=val ) return; } *peWithin = NOT_WITHIN; } /* ** Check the leaf RTree cell given by pCellData against constraint p. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN. ** If the constraint is satisfied, leave *peWithin unchanged. ** ** The constraint is of the form: xN op $val ** ** The op is given by p->op. The xN is p->iCoord-th coordinate in ** pCellData. $val is given by p->u.rValue. */ static void rtreeLeafConstraint( RtreeConstraint *p, /* The constraint to test */ int eInt, /* True if RTree holds integer coordinates */ u8 *pCellData, /* Raw cell content as appears on disk */ int *peWithin /* Adjust downward, as appropriate */ ){ RtreeDValue xN; /* Coordinate value converted to a double */ assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE || p->op==RTREE_GT || p->op==RTREE_EQ ); pCellData += 8 + p->iCoord*4; assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ RTREE_DECODE_COORD(eInt, pCellData, xN); switch( p->op ){ case RTREE_LE: if( xN <= p->u.rValue ) return; break; case RTREE_LT: if( xN < p->u.rValue ) return; break; case RTREE_GE: if( xN >= p->u.rValue ) return; break; case RTREE_GT: if( xN > p->u.rValue ) return; break; default: if( xN == p->u.rValue ) return; break; } *peWithin = NOT_WITHIN; } /* ** One of the cells in node pNode is guaranteed to have a 64-bit ** integer value equal to iRowid. Return the index of this cell. */ static int nodeRowidIndex( Rtree *pRtree, RtreeNode *pNode, i64 iRowid, int *piIndex ){ int ii; int nCell = NCELL(pNode); assert( nCell<200 ); for(ii=0; ii<nCell; ii++){ if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){ *piIndex = ii; return SQLITE_OK; } } return SQLITE_CORRUPT_VTAB; } /* ** Return the index of the cell containing a pointer to node pNode ** in its parent. If pNode is the root node, return -1. */ static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){ RtreeNode *pParent = pNode->pParent; if( pParent ){ return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex); } *piIndex = -1; return SQLITE_OK; } /* ** Compare two search points. Return negative, zero, or positive if the first ** is less than, equal to, or greater than the second. ** ** The rScore is the primary key. Smaller rScore values come first. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller ** iLevel values coming first. In this way, if rScore is the same for all ** SearchPoints, then iLevel becomes the deciding factor and the result ** is a depth-first search, which is the desired default behavior. */ static int rtreeSearchPointCompare( const RtreeSearchPoint *pA, const RtreeSearchPoint *pB ){ if( pA->rScore<pB->rScore ) return -1; if( pA->rScore>pB->rScore ) return +1; if( pA->iLevel<pB->iLevel ) return -1; if( pA->iLevel>pB->iLevel ) return +1; return 0; } /* ** Interchange two search points in a cursor. */ static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){ RtreeSearchPoint t = p->aPoint[i]; assert( i<j ); p->aPoint[i] = p->aPoint[j]; p->aPoint[j] = t; i++; j++; if( i<RTREE_CACHE_SZ ){ if( j>=RTREE_CACHE_SZ ){ nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]); p->aNode[i] = 0; }else{ RtreeNode *pTemp = p->aNode[i]; p->aNode[i] = p->aNode[j]; p->aNode[j] = pTemp; } } } /* ** Return the search point with the lowest current score. */ static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){ return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0; } /* ** Get the RtreeNode for the search point with the lowest score. */ static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){ sqlite3_int64 id; int ii = 1 - pCur->bPoint; assert( ii==0 || ii==1 ); assert( pCur->bPoint || pCur->nPoint ); if( pCur->aNode[ii]==0 ){ assert( pRC!=0 ); id = ii ? pCur->aPoint[0].id : pCur->sPoint.id; *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]); } return pCur->aNode[ii]; } /* ** Push a new element onto the priority queue */ static RtreeSearchPoint *rtreeEnqueue( RtreeCursor *pCur, /* The cursor */ RtreeDValue rScore, /* Score for the new search point */ u8 iLevel /* Level for the new search point */ ){ int i, j; RtreeSearchPoint *pNew; if( pCur->nPoint>=pCur->nPointAlloc ){ int nNew = pCur->nPointAlloc*2 + 8; pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0])); if( pNew==0 ) return 0; pCur->aPoint = pNew; pCur->nPointAlloc = nNew; } i = pCur->nPoint++; pNew = pCur->aPoint + i; pNew->rScore = rScore; pNew->iLevel = iLevel; assert( iLevel<=RTREE_MAX_DEPTH ); while( i>0 ){ RtreeSearchPoint *pParent; j = (i-1)/2; pParent = pCur->aPoint + j; if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break; rtreeSearchPointSwap(pCur, j, i); i = j; pNew = pParent; } return pNew; } /* ** Allocate a new RtreeSearchPoint and return a pointer to it. Return ** NULL if malloc fails. */ static RtreeSearchPoint *rtreeSearchPointNew( RtreeCursor *pCur, /* The cursor */ RtreeDValue rScore, /* Score for the new search point */ u8 iLevel /* Level for the new search point */ ){ RtreeSearchPoint *pNew, *pFirst; pFirst = rtreeSearchPointFirst(pCur); pCur->anQueue[iLevel]++; if( pFirst==0 || pFirst->rScore>rScore || (pFirst->rScore==rScore && pFirst->iLevel>iLevel) ){ if( pCur->bPoint ){ int ii; pNew = rtreeEnqueue(pCur, rScore, iLevel); if( pNew==0 ) return 0; ii = (int)(pNew - pCur->aPoint) + 1; if( ii<RTREE_CACHE_SZ ){ assert( pCur->aNode[ii]==0 ); pCur->aNode[ii] = pCur->aNode[0]; }else{ nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]); } pCur->aNode[0] = 0; *pNew = pCur->sPoint; } pCur->sPoint.rScore = rScore; pCur->sPoint.iLevel = iLevel; pCur->bPoint = 1; return &pCur->sPoint; }else{ return rtreeEnqueue(pCur, rScore, iLevel); } } #if 0 /* Tracing routines for the RtreeSearchPoint queue */ static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){ if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); } printf(" %d.%05lld.%02d %g %d", p->iLevel, p->id, p->iCell, p->rScore, p->eWithin ); idx++; if( idx<RTREE_CACHE_SZ ){ printf(" %p\n", pCur->aNode[idx]); }else{ printf("\n"); } } static void traceQueue(RtreeCursor *pCur, const char *zPrefix){ int ii; printf("=== %9s ", zPrefix); if( pCur->bPoint ){ tracePoint(&pCur->sPoint, -1, pCur); } for(ii=0; ii<pCur->nPoint; ii++){ if( ii>0 || pCur->bPoint ) printf(" "); tracePoint(&pCur->aPoint[ii], ii, pCur); } } # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B) #else # define RTREE_QUEUE_TRACE(A,B) /* no-op */ #endif /* Remove the search point with the lowest current score. */ static void rtreeSearchPointPop(RtreeCursor *p){ int i, j, k, n; i = 1 - p->bPoint; assert( i==0 || i==1 ); if( p->aNode[i] ){ nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]); p->aNode[i] = 0; } if( p->bPoint ){ p->anQueue[p->sPoint.iLevel]--; p->bPoint = 0; }else if( p->nPoint ){ p->anQueue[p->aPoint[0].iLevel]--; n = --p->nPoint; p->aPoint[0] = p->aPoint[n]; if( n<RTREE_CACHE_SZ-1 ){ p->aNode[1] = p->aNode[n+1]; p->aNode[n+1] = 0; } i = 0; while( (j = i*2+1)<n ){ k = j+1; if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){ if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){ rtreeSearchPointSwap(p, i, k); i = k; }else{ break; } }else{ if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){ rtreeSearchPointSwap(p, i, j); i = j; }else{ break; } } } } } /* ** Continue the search on cursor pCur until the front of the queue ** contains an entry suitable for returning as a result-set row, ** or until the RtreeSearchPoint queue is empty, indicating that the ** query has completed. */ static int rtreeStepToLeaf(RtreeCursor *pCur){ RtreeSearchPoint *p; Rtree *pRtree = RTREE_OF_CURSOR(pCur); RtreeNode *pNode; int eWithin; int rc = SQLITE_OK; int nCell; int nConstraint = pCur->nConstraint; int ii; int eInt; RtreeSearchPoint x; eInt = pRtree->eCoordType==RTREE_COORD_INT32; while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){ pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc); if( rc ) return rc; nCell = NCELL(pNode); assert( nCell<200 ); while( p->iCell<nCell ){ sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1; u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell); eWithin = FULLY_WITHIN; for(ii=0; ii<nConstraint; ii++){ RtreeConstraint *pConstraint = pCur->aConstraint + ii; if( pConstraint->op>=RTREE_MATCH ){ rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p, &rScore, &eWithin); if( rc ) return rc; }else if( p->iLevel==1 ){ rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin); }else{ rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin); } if( eWithin==NOT_WITHIN ) break; } p->iCell++; if( eWithin==NOT_WITHIN ) continue; x.iLevel = p->iLevel - 1; if( x.iLevel ){ x.id = readInt64(pCellData); x.iCell = 0; }else{ x.id = p->id; x.iCell = p->iCell - 1; } if( p->iCell>=nCell ){ RTREE_QUEUE_TRACE(pCur, "POP-S:"); rtreeSearchPointPop(pCur); } if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO; p = rtreeSearchPointNew(pCur, rScore, x.iLevel); if( p==0 ) return SQLITE_NOMEM; p->eWithin = (u8)eWithin; p->id = x.id; p->iCell = x.iCell; RTREE_QUEUE_TRACE(pCur, "PUSH-S:"); break; } if( p->iCell>=nCell ){ RTREE_QUEUE_TRACE(pCur, "POP-Se:"); rtreeSearchPointPop(pCur); } } pCur->atEOF = p==0; return SQLITE_OK; } /* ** Rtree virtual table module xNext method. */ static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; int rc = SQLITE_OK; /* Move to the next entry that matches the configured constraints. */ RTREE_QUEUE_TRACE(pCsr, "POP-Nx:"); rtreeSearchPointPop(pCsr); rc = rtreeStepToLeaf(pCsr); return rc; } /* ** Rtree virtual table module xRowid method. */ static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); int rc = SQLITE_OK; RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); if( rc==SQLITE_OK && p ){ *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell); } return rc; } /* ** Rtree virtual table module xColumn method. */ static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ Rtree *pRtree = (Rtree *)cur->pVtab; RtreeCursor *pCsr = (RtreeCursor *)cur; RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); RtreeCoord c; int rc = SQLITE_OK; RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); if( rc ) return rc; if( p==0 ) return SQLITE_OK; if( i==0 ){ sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell)); }else{ nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c); #ifndef SQLITE_RTREE_INT_ONLY if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ sqlite3_result_double(ctx, c.f); }else #endif { assert( pRtree->eCoordType==RTREE_COORD_INT32 ); sqlite3_result_int(ctx, c.i); } } return SQLITE_OK; } /* ** Use nodeAcquire() to obtain the leaf node containing the record with ** rowid iRowid. If successful, set *ppLeaf to point to the node and ** return SQLITE_OK. If there is no such record in the table, set ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf ** to zero and return an SQLite error code. */ static int findLeafNode( Rtree *pRtree, /* RTree to search */ i64 iRowid, /* The rowid searching for */ RtreeNode **ppLeaf, /* Write the node here */ sqlite3_int64 *piNode /* Write the node-id here */ ){ int rc; *ppLeaf = 0; sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); if( piNode ) *piNode = iNode; rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); sqlite3_reset(pRtree->pReadRowid); }else{ rc = sqlite3_reset(pRtree->pReadRowid); } return rc; } /* ** This function is called to configure the RtreeConstraint object passed ** as the second argument for a MATCH constraint. The value passed as the ** first argument to this function is the right-hand operand to the MATCH ** operator. */ static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ RtreeMatchArg *pBlob; /* BLOB returned by geometry function */ sqlite3_rtree_query_info *pInfo; /* Callback information */ int nBlob; /* Size of the geometry function blob */ int nExpected; /* Expected size of the BLOB */ /* Check that value is actually a blob. */ if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR; /* Check that the blob is roughly the right size. */ nBlob = sqlite3_value_bytes(pValue); if( nBlob<(int)sizeof(RtreeMatchArg) ){ return SQLITE_ERROR; } pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob ); if( !pInfo ) return SQLITE_NOMEM; memset(pInfo, 0, sizeof(*pInfo)); pBlob = (RtreeMatchArg*)&pInfo[1]; memcpy(pBlob, sqlite3_value_blob(pValue), nBlob); nExpected = (int)(sizeof(RtreeMatchArg) + pBlob->nParam*sizeof(sqlite3_value*) + (pBlob->nParam-1)*sizeof(RtreeDValue)); if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){ sqlite3_free(pInfo); return SQLITE_ERROR; } pInfo->pContext = pBlob->cb.pContext; pInfo->nParam = pBlob->nParam; pInfo->aParam = pBlob->aParam; pInfo->apSqlParam = pBlob->apSqlParam; if( pBlob->cb.xGeom ){ pCons->u.xGeom = pBlob->cb.xGeom; }else{ pCons->op = RTREE_QUERY; pCons->u.xQueryFunc = pBlob->cb.xQueryFunc; } pCons->pInfo = pInfo; return SQLITE_OK; } /* ** Rtree virtual table module xFilter method. */ static int rtreeFilter( sqlite3_vtab_cursor *pVtabCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; RtreeNode *pRoot = 0; int ii; int rc = SQLITE_OK; int iCell = 0; rtreeReference(pRtree); /* Reset the cursor to the same state as rtreeOpen() leaves it in. */ freeCursorConstraints(pCsr); sqlite3_free(pCsr->aPoint); memset(pCsr, 0, sizeof(RtreeCursor)); pCsr->base.pVtab = (sqlite3_vtab*)pRtree; pCsr->iStrategy = idxNum; if( idxNum==1 ){ /* Special case - lookup by rowid. */ RtreeNode *pLeaf; /* Leaf on which the required cell resides */ RtreeSearchPoint *p; /* Search point for the leaf */ i64 iRowid = sqlite3_value_int64(argv[0]); i64 iNode = 0; rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); if( rc==SQLITE_OK && pLeaf!=0 ){ p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0); assert( p!=0 ); /* Always returns pCsr->sPoint */ pCsr->aNode[0] = pLeaf; p->id = iNode; p->eWithin = PARTLY_WITHIN; rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell); p->iCell = (u8)iCell; RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:"); }else{ pCsr->atEOF = 1; } }else{ /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array ** with the configured constraints. */ rc = nodeAcquire(pRtree, 1, 0, &pRoot); if( rc==SQLITE_OK && argc>0 ){ pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc); pCsr->nConstraint = argc; if( !pCsr->aConstraint ){ rc = SQLITE_NOMEM; }else{ memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc); memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1)); assert( (idxStr==0 && argc==0) || (idxStr && (int)strlen(idxStr)==argc*2) ); for(ii=0; ii<argc; ii++){ RtreeConstraint *p = &pCsr->aConstraint[ii]; p->op = idxStr[ii*2]; p->iCoord = idxStr[ii*2+1]-'0'; if( p->op>=RTREE_MATCH ){ /* A MATCH operator. The right-hand-side must be a blob that ** can be cast into an RtreeMatchArg object. One created using ** an sqlite3_rtree_geometry_callback() SQL user function. */ rc = deserializeGeometry(argv[ii], p); if( rc!=SQLITE_OK ){ break; } p->pInfo->nCoord = pRtree->nDim2; p->pInfo->anQueue = pCsr->anQueue; p->pInfo->mxLevel = pRtree->iDepth + 1; }else{ #ifdef SQLITE_RTREE_INT_ONLY p->u.rValue = sqlite3_value_int64(argv[ii]); #else p->u.rValue = sqlite3_value_double(argv[ii]); #endif } } } } if( rc==SQLITE_OK ){ RtreeSearchPoint *pNew; pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1)); if( pNew==0 ) return SQLITE_NOMEM; pNew->id = 1; pNew->iCell = 0; pNew->eWithin = PARTLY_WITHIN; assert( pCsr->bPoint==1 ); pCsr->aNode[0] = pRoot; pRoot = 0; RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:"); rc = rtreeStepToLeaf(pCsr); } } nodeRelease(pRtree, pRoot); rtreeRelease(pRtree); return rc; } /* ** Rtree virtual table module xBestIndex method. There are three ** table scan strategies to choose from (in order from most to ** least desirable): ** ** idxNum idxStr Strategy ** ------------------------------------------------ ** 1 Unused Direct lookup by rowid. ** 2 See below R-tree query or full-table scan. ** ------------------------------------------------ ** ** If strategy 1 is used, then idxStr is not meaningful. If strategy ** 2 is used, idxStr is formatted to contain 2 bytes for each ** constraint used. The first two bytes of idxStr correspond to ** the constraint in sqlite3_index_info.aConstraintUsage[] with ** (argvIndex==1) etc. ** ** The first of each pair of bytes in idxStr identifies the constraint ** operator as follows: ** ** Operator Byte Value ** ---------------------- ** = 0x41 ('A') ** <= 0x42 ('B') ** < 0x43 ('C') ** >= 0x44 ('D') ** > 0x45 ('E') ** MATCH 0x46 ('F') ** ---------------------- ** ** The second of each pair of bytes identifies the coordinate column ** to which the constraint applies. The leftmost coordinate column ** is 'a', the second from the left 'b' etc. */ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ Rtree *pRtree = (Rtree*)tab; int rc = SQLITE_OK; int ii; int bMatch = 0; /* True if there exists a MATCH constraint */ i64 nRow; /* Estimated rows returned by this scan */ int iIdx = 0; char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; memset(zIdxStr, 0, sizeof(zIdxStr)); /* Check if there exists a MATCH constraint - even an unusable one. If there ** is, do not consider the lookup-by-rowid plan as using such a plan would ** require the VDBE to evaluate the MATCH constraint, which is not currently ** possible. */ for(ii=0; ii<pIdxInfo->nConstraint; ii++){ if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){ bMatch = 1; } } assert( pIdxInfo->idxStr==0 ); for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){ struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; if( bMatch==0 && p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ /* We have an equality constraint on the rowid. Use strategy 1. */ int jj; for(jj=0; jj<ii; jj++){ pIdxInfo->aConstraintUsage[jj].argvIndex = 0; pIdxInfo->aConstraintUsage[jj].omit = 0; } pIdxInfo->idxNum = 1; pIdxInfo->aConstraintUsage[ii].argvIndex = 1; pIdxInfo->aConstraintUsage[jj].omit = 1; /* This strategy involves a two rowid lookups on an B-Tree structures ** and then a linear search of an R-Tree node. This should be ** considered almost as quick as a direct rowid lookup (for which ** sqlite uses an internal cost of 0.0). It is expected to return ** a single row. */ pIdxInfo->estimatedCost = 30.0; pIdxInfo->estimatedRows = 1; return SQLITE_OK; } if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){ u8 op; switch( p->op ){ case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; default: assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH ); op = RTREE_MATCH; break; } zIdxStr[iIdx++] = op; zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0'); pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); pIdxInfo->aConstraintUsage[ii].omit = 1; } } pIdxInfo->idxNum = 2; pIdxInfo->needToFreeIdxStr = 1; if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ return SQLITE_NOMEM; } nRow = pRtree->nRowEst >> (iIdx/2); pIdxInfo->estimatedCost = (double)6.0 * (double)nRow; pIdxInfo->estimatedRows = nRow; return rc; } /* ** Return the N-dimensional volumn of the cell stored in *p. */ static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ RtreeDValue area = (RtreeDValue)1; assert( pRtree->nDim>=1 && pRtree->nDim<=5 ); #ifndef SQLITE_RTREE_INT_ONLY if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ switch( pRtree->nDim ){ case 5: area = p->aCoord[9].f - p->aCoord[8].f; case 4: area *= p->aCoord[7].f - p->aCoord[6].f; case 3: area *= p->aCoord[5].f - p->aCoord[4].f; case 2: area *= p->aCoord[3].f - p->aCoord[2].f; default: area *= p->aCoord[1].f - p->aCoord[0].f; } }else #endif { switch( pRtree->nDim ){ case 5: area = p->aCoord[9].i - p->aCoord[8].i; case 4: area *= p->aCoord[7].i - p->aCoord[6].i; case 3: area *= p->aCoord[5].i - p->aCoord[4].i; case 2: area *= p->aCoord[3].i - p->aCoord[2].i; default: area *= p->aCoord[1].i - p->aCoord[0].i; } } return area; } /* ** Return the margin length of cell p. The margin length is the sum ** of the objects size in each dimension. */ static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){ RtreeDValue margin = 0; int ii = pRtree->nDim2 - 2; do{ margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); ii -= 2; }while( ii>=0 ); return margin; } /* ** Store the union of cells p1 and p2 in p1. */ static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ int ii = 0; if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ do{ p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); ii += 2; }while( ii<pRtree->nDim2 ); }else{ do{ p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); ii += 2; }while( ii<pRtree->nDim2 ); } } /* ** Return true if the area covered by p2 is a subset of the area covered ** by p1. False otherwise. */ static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ int ii; int isInt = (pRtree->eCoordType==RTREE_COORD_INT32); for(ii=0; ii<pRtree->nDim2; ii+=2){ RtreeCoord *a1 = &p1->aCoord[ii]; RtreeCoord *a2 = &p2->aCoord[ii]; if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) ){ return 0; } } return 1; } /* ** Return the amount cell p would grow by if it were unioned with pCell. */ static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ RtreeDValue area; RtreeCell cell; memcpy(&cell, p, sizeof(RtreeCell)); area = cellArea(pRtree, &cell); cellUnion(pRtree, &cell, pCell); return (cellArea(pRtree, &cell)-area); } static RtreeDValue cellOverlap( Rtree *pRtree, RtreeCell *p, RtreeCell *aCell, int nCell ){ int ii; RtreeDValue overlap = RTREE_ZERO; for(ii=0; ii<nCell; ii++){ int jj; RtreeDValue o = (RtreeDValue)1; for(jj=0; jj<pRtree->nDim2; jj+=2){ RtreeDValue x1, x2; x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); if( x2<x1 ){ o = (RtreeDValue)0; break; }else{ o = o * (x2-x1); } } overlap += o; } return overlap; } /* ** This function implements the ChooseLeaf algorithm from Gutman[84]. ** ChooseSubTree in r*tree terminology. */ static int ChooseLeaf( Rtree *pRtree, /* Rtree table */ RtreeCell *pCell, /* Cell to insert into rtree */ int iHeight, /* Height of sub-tree rooted at pCell */ RtreeNode **ppLeaf /* OUT: Selected leaf page */ ){ int rc; int ii; RtreeNode *pNode; rc = nodeAcquire(pRtree, 1, 0, &pNode); for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){ int iCell; sqlite3_int64 iBest = 0; RtreeDValue fMinGrowth = RTREE_ZERO; RtreeDValue fMinArea = RTREE_ZERO; int nCell = NCELL(pNode); RtreeCell cell; RtreeNode *pChild; RtreeCell *aCell = 0; /* Select the child node which will be enlarged the least if pCell ** is inserted into it. Resolve ties by choosing the entry with ** the smallest area. */ for(iCell=0; iCell<nCell; iCell++){ int bBest = 0; RtreeDValue growth; RtreeDValue area; nodeGetCell(pRtree, pNode, iCell, &cell); growth = cellGrowth(pRtree, &cell, pCell); area = cellArea(pRtree, &cell); if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){ bBest = 1; } if( bBest ){ fMinGrowth = growth; fMinArea = area; iBest = cell.iRowid; } } sqlite3_free(aCell); rc = nodeAcquire(pRtree, iBest, pNode, &pChild); nodeRelease(pRtree, pNode); pNode = pChild; } *ppLeaf = pNode; return rc; } /* ** A cell with the same content as pCell has just been inserted into ** the node pNode. This function updates the bounding box cells in ** all ancestor elements. */ static int AdjustTree( Rtree *pRtree, /* Rtree table */ RtreeNode *pNode, /* Adjust ancestry of this node. */ RtreeCell *pCell /* This cell was just inserted */ ){ RtreeNode *p = pNode; while( p->pParent ){ RtreeNode *pParent = p->pParent; RtreeCell cell; int iCell; if( nodeParentIndex(pRtree, p, &iCell) ){ return SQLITE_CORRUPT_VTAB; } nodeGetCell(pRtree, pParent, iCell, &cell); if( !cellContains(pRtree, &cell, pCell) ){ cellUnion(pRtree, &cell, pCell); nodeOverwriteCell(pRtree, pParent, &cell, iCell); } p = pParent; } return SQLITE_OK; } /* ** Write mapping (iRowid->iNode) to the <rtree>_rowid table. */ static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); sqlite3_step(pRtree->pWriteRowid); return sqlite3_reset(pRtree->pWriteRowid); } /* ** Write mapping (iNode->iPar) to the <rtree>_parent table. */ static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); sqlite3_step(pRtree->pWriteParent); return sqlite3_reset(pRtree->pWriteParent); } static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); /* ** Arguments aIdx, aDistance and aSpare all point to arrays of size ** nIdx. The aIdx array contains the set of integers from 0 to ** (nIdx-1) in no particular order. This function sorts the values ** in aIdx according to the indexed values in aDistance. For ** example, assuming the inputs: ** ** aIdx = { 0, 1, 2, 3 } ** aDistance = { 5.0, 2.0, 7.0, 6.0 } ** ** this function sets the aIdx array to contain: ** ** aIdx = { 0, 1, 2, 3 } ** ** The aSpare array is used as temporary working space by the ** sorting algorithm. */ static void SortByDistance( int *aIdx, int nIdx, RtreeDValue *aDistance, int *aSpare ){ if( nIdx>1 ){ int iLeft = 0; int iRight = 0; int nLeft = nIdx/2; int nRight = nIdx-nLeft; int *aLeft = aIdx; int *aRight = &aIdx[nLeft]; SortByDistance(aLeft, nLeft, aDistance, aSpare); SortByDistance(aRight, nRight, aDistance, aSpare); memcpy(aSpare, aLeft, sizeof(int)*nLeft); aLeft = aSpare; while( iLeft<nLeft || iRight<nRight ){ if( iLeft==nLeft ){ aIdx[iLeft+iRight] = aRight[iRight]; iRight++; }else if( iRight==nRight ){ aIdx[iLeft+iRight] = aLeft[iLeft]; iLeft++; }else{ RtreeDValue fLeft = aDistance[aLeft[iLeft]]; RtreeDValue fRight = aDistance[aRight[iRight]]; if( fLeft<fRight ){ aIdx[iLeft+iRight] = aLeft[iLeft]; iLeft++; }else{ aIdx[iLeft+iRight] = aRight[iRight]; iRight++; } } } #if 0 /* Check that the sort worked */ { int jj; for(jj=1; jj<nIdx; jj++){ RtreeDValue left = aDistance[aIdx[jj-1]]; RtreeDValue right = aDistance[aIdx[jj]]; assert( left<=right ); } } #endif } } /* ** Arguments aIdx, aCell and aSpare all point to arrays of size ** nIdx. The aIdx array contains the set of integers from 0 to ** (nIdx-1) in no particular order. This function sorts the values ** in aIdx according to dimension iDim of the cells in aCell. The ** minimum value of dimension iDim is considered first, the ** maximum used to break ties. ** ** The aSpare array is used as temporary working space by the ** sorting algorithm. */ static void SortByDimension( Rtree *pRtree, int *aIdx, int nIdx, int iDim, RtreeCell *aCell, int *aSpare ){ if( nIdx>1 ){ int iLeft = 0; int iRight = 0; int nLeft = nIdx/2; int nRight = nIdx-nLeft; int *aLeft = aIdx; int *aRight = &aIdx[nLeft]; SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare); SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare); memcpy(aSpare, aLeft, sizeof(int)*nLeft); aLeft = aSpare; while( iLeft<nLeft || iRight<nRight ){ RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]); RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]); RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]); RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]); if( (iLeft!=nLeft) && ((iRight==nRight) || (xleft1<xright1) || (xleft1==xright1 && xleft2<xright2) )){ aIdx[iLeft+iRight] = aLeft[iLeft]; iLeft++; }else{ aIdx[iLeft+iRight] = aRight[iRight]; iRight++; } } #if 0 /* Check that the sort worked */ { int jj; for(jj=1; jj<nIdx; jj++){ RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2]; RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1]; RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2]; RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1]; assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) ); } } #endif } } /* ** Implementation of the R*-tree variant of SplitNode from Beckman[1990]. */ static int splitNodeStartree( Rtree *pRtree, RtreeCell *aCell, int nCell, RtreeNode *pLeft, RtreeNode *pRight, RtreeCell *pBboxLeft, RtreeCell *pBboxRight ){ int **aaSorted; int *aSpare; int ii; int iBestDim = 0; int iBestSplit = 0; RtreeDValue fBestMargin = RTREE_ZERO; int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int)); aaSorted = (int **)sqlite3_malloc(nByte); if( !aaSorted ){ return SQLITE_NOMEM; } aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell]; memset(aaSorted, 0, nByte); for(ii=0; ii<pRtree->nDim; ii++){ int jj; aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell]; for(jj=0; jj<nCell; jj++){ aaSorted[ii][jj] = jj; } SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare); } for(ii=0; ii<pRtree->nDim; ii++){ RtreeDValue margin = RTREE_ZERO; RtreeDValue fBestOverlap = RTREE_ZERO; RtreeDValue fBestArea = RTREE_ZERO; int iBestLeft = 0; int nLeft; for( nLeft=RTREE_MINCELLS(pRtree); nLeft<=(nCell-RTREE_MINCELLS(pRtree)); nLeft++ ){ RtreeCell left; RtreeCell right; int kk; RtreeDValue overlap; RtreeDValue area; memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell)); memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell)); for(kk=1; kk<(nCell-1); kk++){ if( kk<nLeft ){ cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]); }else{ cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]); } } margin += cellMargin(pRtree, &left); margin += cellMargin(pRtree, &right); overlap = cellOverlap(pRtree, &left, &right, 1); area = cellArea(pRtree, &left) + cellArea(pRtree, &right); if( (nLeft==RTREE_MINCELLS(pRtree)) || (overlap<fBestOverlap) || (overlap==fBestOverlap && area<fBestArea) ){ iBestLeft = nLeft; fBestOverlap = overlap; fBestArea = area; } } if( ii==0 || margin<fBestMargin ){ iBestDim = ii; fBestMargin = margin; iBestSplit = iBestLeft; } } memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell)); memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell)); for(ii=0; ii<nCell; ii++){ RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight; RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight; RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]]; nodeInsertCell(pRtree, pTarget, pCell); cellUnion(pRtree, pBbox, pCell); } sqlite3_free(aaSorted); return SQLITE_OK; } static int updateMapping( Rtree *pRtree, i64 iRowid, RtreeNode *pNode, int iHeight ){ int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64); xSetMapping = ((iHeight==0)?rowidWrite:parentWrite); if( iHeight>0 ){ RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); if( pChild ){ nodeRelease(pRtree, pChild->pParent); nodeReference(pNode); pChild->pParent = pNode; } } return xSetMapping(pRtree, iRowid, pNode->iNode); } static int SplitNode( Rtree *pRtree, RtreeNode *pNode, RtreeCell *pCell, int iHeight ){ int i; int newCellIsRight = 0; int rc = SQLITE_OK; int nCell = NCELL(pNode); RtreeCell *aCell; int *aiUsed; RtreeNode *pLeft = 0; RtreeNode *pRight = 0; RtreeCell leftbbox; RtreeCell rightbbox; /* Allocate an array and populate it with a copy of pCell and ** all cells from node pLeft. Then zero the original node. */ aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); if( !aCell ){ rc = SQLITE_NOMEM; goto splitnode_out; } aiUsed = (int *)&aCell[nCell+1]; memset(aiUsed, 0, sizeof(int)*(nCell+1)); for(i=0; i<nCell; i++){ nodeGetCell(pRtree, pNode, i, &aCell[i]); } nodeZero(pRtree, pNode); memcpy(&aCell[nCell], pCell, sizeof(RtreeCell)); nCell++; if( pNode->iNode==1 ){ pRight = nodeNew(pRtree, pNode); pLeft = nodeNew(pRtree, pNode); pRtree->iDepth++; pNode->isDirty = 1; writeInt16(pNode->zData, pRtree->iDepth); }else{ pLeft = pNode; pRight = nodeNew(pRtree, pLeft->pParent); nodeReference(pLeft); } if( !pLeft || !pRight ){ rc = SQLITE_NOMEM; goto splitnode_out; } memset(pLeft->zData, 0, pRtree->iNodeSize); memset(pRight->zData, 0, pRtree->iNodeSize); rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox); if( rc!=SQLITE_OK ){ goto splitnode_out; } /* Ensure both child nodes have node numbers assigned to them by calling ** nodeWrite(). Node pRight always needs a node number, as it was created ** by nodeNew() above. But node pLeft sometimes already has a node number. ** In this case avoid the all to nodeWrite(). */ if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)) || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) ){ goto splitnode_out; } rightbbox.iRowid = pRight->iNode; leftbbox.iRowid = pLeft->iNode; if( pNode->iNode==1 ){ rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); if( rc!=SQLITE_OK ){ goto splitnode_out; } }else{ RtreeNode *pParent = pLeft->pParent; int iCell; rc = nodeParentIndex(pRtree, pLeft, &iCell); if( rc==SQLITE_OK ){ nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); rc = AdjustTree(pRtree, pParent, &leftbbox); } if( rc!=SQLITE_OK ){ goto splitnode_out; } } if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ goto splitnode_out; } for(i=0; i<NCELL(pRight); i++){ i64 iRowid = nodeGetRowid(pRtree, pRight, i); rc = updateMapping(pRtree, iRowid, pRight, iHeight); if( iRowid==pCell->iRowid ){ newCellIsRight = 1; } if( rc!=SQLITE_OK ){ goto splitnode_out; } } if( pNode->iNode==1 ){ for(i=0; i<NCELL(pLeft); i++){ i64 iRowid = nodeGetRowid(pRtree, pLeft, i); rc = updateMapping(pRtree, iRowid, pLeft, iHeight); if( rc!=SQLITE_OK ){ goto splitnode_out; } } }else if( newCellIsRight==0 ){ rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight); } if( rc==SQLITE_OK ){ rc = nodeRelease(pRtree, pRight); pRight = 0; } if( rc==SQLITE_OK ){ rc = nodeRelease(pRtree, pLeft); pLeft = 0; } splitnode_out: nodeRelease(pRtree, pRight); nodeRelease(pRtree, pLeft); sqlite3_free(aCell); return rc; } /* ** If node pLeaf is not the root of the r-tree and its pParent pointer is ** still NULL, load all ancestor nodes of pLeaf into memory and populate ** the pLeaf->pParent chain all the way up to the root node. ** ** This operation is required when a row is deleted (or updated - an update ** is implemented as a delete followed by an insert). SQLite provides the ** rowid of the row to delete, which can be used to find the leaf on which ** the entry resides (argument pLeaf). Once the leaf is located, this ** function is called to determine its ancestry. */ static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ int rc = SQLITE_OK; RtreeNode *pChild = pLeaf; while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){ int rc2 = SQLITE_OK; /* sqlite3_reset() return code */ sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode); rc = sqlite3_step(pRtree->pReadParent); if( rc==SQLITE_ROW ){ RtreeNode *pTest; /* Used to test for reference loops */ i64 iNode; /* Node number of parent node */ /* Before setting pChild->pParent, test that we are not creating a ** loop of references (as we would if, say, pChild==pParent). We don't ** want to do this as it leads to a memory leak when trying to delete ** the referenced counted node structures. */ iNode = sqlite3_column_int64(pRtree->pReadParent, 0); for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent); if( !pTest ){ rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent); } } rc = sqlite3_reset(pRtree->pReadParent); if( rc==SQLITE_OK ) rc = rc2; if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB; pChild = pChild->pParent; } return rc; } static int deleteCell(Rtree *, RtreeNode *, int, int); static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ int rc; int rc2; RtreeNode *pParent = 0; int iCell; assert( pNode->nRef==1 ); /* Remove the entry in the parent cell. */ rc = nodeParentIndex(pRtree, pNode, &iCell); if( rc==SQLITE_OK ){ pParent = pNode->pParent; pNode->pParent = 0; rc = deleteCell(pRtree, pParent, iCell, iHeight+1); } rc2 = nodeRelease(pRtree, pParent); if( rc==SQLITE_OK ){ rc = rc2; } if( rc!=SQLITE_OK ){ return rc; } /* Remove the xxx_node entry. */ sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); sqlite3_step(pRtree->pDeleteNode); if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ return rc; } /* Remove the xxx_parent entry. */ sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); sqlite3_step(pRtree->pDeleteParent); if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ return rc; } /* Remove the node from the in-memory hash table and link it into ** the Rtree.pDeleted list. Its contents will be re-inserted later on. */ nodeHashDelete(pRtree, pNode); pNode->iNode = iHeight; pNode->pNext = pRtree->pDeleted; pNode->nRef++; pRtree->pDeleted = pNode; return SQLITE_OK; } static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){ RtreeNode *pParent = pNode->pParent; int rc = SQLITE_OK; if( pParent ){ int ii; int nCell = NCELL(pNode); RtreeCell box; /* Bounding box for pNode */ nodeGetCell(pRtree, pNode, 0, &box); for(ii=1; ii<nCell; ii++){ RtreeCell cell; nodeGetCell(pRtree, pNode, ii, &cell); cellUnion(pRtree, &box, &cell); } box.iRowid = pNode->iNode; rc = nodeParentIndex(pRtree, pNode, &ii); if( rc==SQLITE_OK ){ nodeOverwriteCell(pRtree, pParent, &box, ii); rc = fixBoundingBox(pRtree, pParent); } } return rc; } /* ** Delete the cell at index iCell of node pNode. After removing the ** cell, adjust the r-tree data structure if required. */ static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){ RtreeNode *pParent; int rc; if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){ return rc; } /* Remove the cell from the node. This call just moves bytes around ** the in-memory node image, so it cannot fail. */ nodeDeleteCell(pRtree, pNode, iCell); /* If the node is not the tree root and now has less than the minimum ** number of cells, remove it from the tree. Otherwise, update the ** cell in the parent node so that it tightly contains the updated ** node. */ pParent = pNode->pParent; assert( pParent || pNode->iNode==1 ); if( pParent ){ if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){ rc = removeNode(pRtree, pNode, iHeight); }else{ rc = fixBoundingBox(pRtree, pNode); } } return rc; } static int Reinsert( Rtree *pRtree, RtreeNode *pNode, RtreeCell *pCell, int iHeight ){ int *aOrder; int *aSpare; RtreeCell *aCell; RtreeDValue *aDistance; int nCell; RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS]; int iDim; int ii; int rc = SQLITE_OK; int n; memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS); nCell = NCELL(pNode)+1; n = (nCell+1)&(~1); /* Allocate the buffers used by this operation. The allocation is ** relinquished before this function returns. */ aCell = (RtreeCell *)sqlite3_malloc(n * ( sizeof(RtreeCell) + /* aCell array */ sizeof(int) + /* aOrder array */ sizeof(int) + /* aSpare array */ sizeof(RtreeDValue) /* aDistance array */ )); if( !aCell ){ return SQLITE_NOMEM; } aOrder = (int *)&aCell[n]; aSpare = (int *)&aOrder[n]; aDistance = (RtreeDValue *)&aSpare[n]; for(ii=0; ii<nCell; ii++){ if( ii==(nCell-1) ){ memcpy(&aCell[ii], pCell, sizeof(RtreeCell)); }else{ nodeGetCell(pRtree, pNode, ii, &aCell[ii]); } aOrder[ii] = ii; for(iDim=0; iDim<pRtree->nDim; iDim++){ aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]); aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]); } } for(iDim=0; iDim<pRtree->nDim; iDim++){ aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2)); } for(ii=0; ii<nCell; ii++){ aDistance[ii] = RTREE_ZERO; for(iDim=0; iDim<pRtree->nDim; iDim++){ RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - DCOORD(aCell[ii].aCoord[iDim*2])); aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]); } } SortByDistance(aOrder, nCell, aDistance, aSpare); nodeZero(pRtree, pNode); for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){ RtreeCell *p = &aCell[aOrder[ii]]; nodeInsertCell(pRtree, pNode, p); if( p->iRowid==pCell->iRowid ){ if( iHeight==0 ){ rc = rowidWrite(pRtree, p->iRowid, pNode->iNode); }else{ rc = parentWrite(pRtree, p->iRowid, pNode->iNode); } } } if( rc==SQLITE_OK ){ rc = fixBoundingBox(pRtree, pNode); } for(; rc==SQLITE_OK && ii<nCell; ii++){ /* Find a node to store this cell in. pNode->iNode currently contains ** the height of the sub-tree headed by the cell. */ RtreeNode *pInsert; RtreeCell *p = &aCell[aOrder[ii]]; rc = ChooseLeaf(pRtree, p, iHeight, &pInsert); if( rc==SQLITE_OK ){ int rc2; rc = rtreeInsertCell(pRtree, pInsert, p, iHeight); rc2 = nodeRelease(pRtree, pInsert); if( rc==SQLITE_OK ){ rc = rc2; } } } sqlite3_free(aCell); return rc; } /* ** Insert cell pCell into node pNode. Node pNode is the head of a ** subtree iHeight high (leaf nodes have iHeight==0). */ static int rtreeInsertCell( Rtree *pRtree, RtreeNode *pNode, RtreeCell *pCell, int iHeight ){ int rc = SQLITE_OK; if( iHeight>0 ){ RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid); if( pChild ){ nodeRelease(pRtree, pChild->pParent); nodeReference(pNode); pChild->pParent = pNode; } } if( nodeInsertCell(pRtree, pNode, pCell) ){ if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){ rc = SplitNode(pRtree, pNode, pCell, iHeight); }else{ pRtree->iReinsertHeight = iHeight; rc = Reinsert(pRtree, pNode, pCell, iHeight); } }else{ rc = AdjustTree(pRtree, pNode, pCell); if( rc==SQLITE_OK ){ if( iHeight==0 ){ rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); }else{ rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode); } } } return rc; } static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ int ii; int rc = SQLITE_OK; int nCell = NCELL(pNode); for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){ RtreeNode *pInsert; RtreeCell cell; nodeGetCell(pRtree, pNode, ii, &cell); /* Find a node to store this cell in. pNode->iNode currently contains ** the height of the sub-tree headed by the cell. */ rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert); if( rc==SQLITE_OK ){ int rc2; rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode); rc2 = nodeRelease(pRtree, pInsert); if( rc==SQLITE_OK ){ rc = rc2; } } } return rc; } /* ** Select a currently unused rowid for a new r-tree record. */ static int newRowid(Rtree *pRtree, i64 *piRowid){ int rc; sqlite3_bind_null(pRtree->pWriteRowid, 1); sqlite3_bind_null(pRtree->pWriteRowid, 2); sqlite3_step(pRtree->pWriteRowid); rc = sqlite3_reset(pRtree->pWriteRowid); *piRowid = sqlite3_last_insert_rowid(pRtree->db); return rc; } /* ** Remove the entry with rowid=iDelete from the r-tree structure. */ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ int rc; /* Return code */ RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */ int iCell; /* Index of iDelete cell in pLeaf */ RtreeNode *pRoot; /* Root node of rtree structure */ /* Obtain a reference to the root node to initialize Rtree.iDepth */ rc = nodeAcquire(pRtree, 1, 0, &pRoot); /* Obtain a reference to the leaf node that contains the entry ** about to be deleted. */ if( rc==SQLITE_OK ){ rc = findLeafNode(pRtree, iDelete, &pLeaf, 0); } /* Delete the cell in question from the leaf node. */ if( rc==SQLITE_OK ){ int rc2; rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell); if( rc==SQLITE_OK ){ rc = deleteCell(pRtree, pLeaf, iCell, 0); } rc2 = nodeRelease(pRtree, pLeaf); if( rc==SQLITE_OK ){ rc = rc2; } } /* Delete the corresponding entry in the <rtree>_rowid table. */ if( rc==SQLITE_OK ){ sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); sqlite3_step(pRtree->pDeleteRowid); rc = sqlite3_reset(pRtree->pDeleteRowid); } /* Check if the root node now has exactly one child. If so, remove ** it, schedule the contents of the child for reinsertion and ** reduce the tree height by one. ** ** This is equivalent to copying the contents of the child into ** the root node (the operation that Gutman's paper says to perform ** in this scenario). */ if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){ int rc2; RtreeNode *pChild; i64 iChild = nodeGetRowid(pRtree, pRoot, 0); rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); if( rc==SQLITE_OK ){ rc = removeNode(pRtree, pChild, pRtree->iDepth-1); } rc2 = nodeRelease(pRtree, pChild); if( rc==SQLITE_OK ) rc = rc2; if( rc==SQLITE_OK ){ pRtree->iDepth--; writeInt16(pRoot->zData, pRtree->iDepth); pRoot->isDirty = 1; } } /* Re-insert the contents of any underfull nodes removed from the tree. */ for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){ if( rc==SQLITE_OK ){ rc = reinsertNodeContent(pRtree, pLeaf); } pRtree->pDeleted = pLeaf->pNext; sqlite3_free(pLeaf); } /* Release the reference to the root node. */ if( rc==SQLITE_OK ){ rc = nodeRelease(pRtree, pRoot); }else{ nodeRelease(pRtree, pRoot); } return rc; } /* ** Rounding constants for float->double conversion. */ #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */ #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */ #if !defined(SQLITE_RTREE_INT_ONLY) /* ** Convert an sqlite3_value into an RtreeValue (presumably a float) ** while taking care to round toward negative or positive, respectively. */ static RtreeValue rtreeValueDown(sqlite3_value *v){ double d = sqlite3_value_double(v); float f = (float)d; if( f>d ){ f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS)); } return f; } static RtreeValue rtreeValueUp(sqlite3_value *v){ double d = sqlite3_value_double(v); float f = (float)d; if( f<d ){ f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY)); } return f; } #endif /* !defined(SQLITE_RTREE_INT_ONLY) */ /* ** A constraint has failed while inserting a row into an rtree table. ** Assuming no OOM error occurs, this function sets the error message ** (at pRtree->base.zErrMsg) to an appropriate value and returns ** SQLITE_CONSTRAINT. ** ** Parameter iCol is the index of the leftmost column involved in the ** constraint failure. If it is 0, then the constraint that failed is ** the unique constraint on the id column. Otherwise, it is the rtree ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed. ** ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT. */ static int rtreeConstraintError(Rtree *pRtree, int iCol){ sqlite3_stmt *pStmt = 0; char *zSql; int rc; assert( iCol==0 || iCol%2 ); zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName); if( zSql ){ rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0); }else{ rc = SQLITE_NOMEM; } sqlite3_free(zSql); if( rc==SQLITE_OK ){ if( iCol==0 ){ const char *zCol = sqlite3_column_name(pStmt, 0); pRtree->base.zErrMsg = sqlite3_mprintf( "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol ); }else{ const char *zCol1 = sqlite3_column_name(pStmt, iCol); const char *zCol2 = sqlite3_column_name(pStmt, iCol+1); pRtree->base.zErrMsg = sqlite3_mprintf( "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2 ); } } sqlite3_finalize(pStmt); return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc); } /* ** The xUpdate method for rtree module virtual tables. */ static int rtreeUpdate( sqlite3_vtab *pVtab, int nData, sqlite3_value **azData, sqlite_int64 *pRowid ){ Rtree *pRtree = (Rtree *)pVtab; int rc = SQLITE_OK; RtreeCell cell; /* New cell to insert if nData>1 */ int bHaveRowid = 0; /* Set to 1 after new rowid is determined */ rtreeReference(pRtree); assert(nData>=1); cell.iRowid = 0; /* Used only to suppress a compiler warning */ /* Constraint handling. A write operation on an r-tree table may return ** SQLITE_CONSTRAINT for two reasons: ** ** 1. A duplicate rowid value, or ** 2. The supplied data violates the "x2>=x1" constraint. ** ** In the first case, if the conflict-handling mode is REPLACE, then ** the conflicting row can be removed before proceeding. In the second ** case, SQLITE_CONSTRAINT must be returned regardless of the ** conflict-handling mode specified by the user. */ if( nData>1 ){ int ii; /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. ** ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared ** with "column" that are interpreted as table constraints. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5)); ** This problem was discovered after years of use, so we silently ignore ** these kinds of misdeclared tables to avoid breaking any legacy. */ assert( nData<=(pRtree->nDim2 + 3) ); #ifndef SQLITE_RTREE_INT_ONLY if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ for(ii=0; ii<nData-4; ii+=2){ cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]); cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]); if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){ rc = rtreeConstraintError(pRtree, ii+1); goto constraint; } } }else #endif { for(ii=0; ii<nData-4; ii+=2){ cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]); cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]); if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){ rc = rtreeConstraintError(pRtree, ii+1); goto constraint; } } } /* If a rowid value was supplied, check if it is already present in ** the table. If so, the constraint has failed. */ if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){ cell.iRowid = sqlite3_value_int64(azData[2]); if( sqlite3_value_type(azData[0])==SQLITE_NULL || sqlite3_value_int64(azData[0])!=cell.iRowid ){ int steprc; sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); steprc = sqlite3_step(pRtree->pReadRowid); rc = sqlite3_reset(pRtree->pReadRowid); if( SQLITE_ROW==steprc ){ if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ rc = rtreeDeleteRowid(pRtree, cell.iRowid); }else{ rc = rtreeConstraintError(pRtree, 0); goto constraint; } } } bHaveRowid = 1; } } /* If azData[0] is not an SQL NULL value, it is the rowid of a ** record to delete from the r-tree table. The following block does ** just that. */ if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){ rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0])); } /* If the azData[] array contains more than one element, elements ** (azData[2]..azData[argc-1]) contain a new record to insert into ** the r-tree structure. */ if( rc==SQLITE_OK && nData>1 ){ /* Insert the new record into the r-tree */ RtreeNode *pLeaf = 0; /* Figure out the rowid of the new row. */ if( bHaveRowid==0 ){ rc = newRowid(pRtree, &cell.iRowid); } *pRowid = cell.iRowid; if( rc==SQLITE_OK ){ rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); } if( rc==SQLITE_OK ){ int rc2; pRtree->iReinsertHeight = -1; rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); rc2 = nodeRelease(pRtree, pLeaf); if( rc==SQLITE_OK ){ rc = rc2; } } } constraint: rtreeRelease(pRtree); return rc; } /* ** Called when a transaction starts. */ static int rtreeBeginTransaction(sqlite3_vtab *pVtab){ Rtree *pRtree = (Rtree *)pVtab; assert( pRtree->inWrTrans==0 ); pRtree->inWrTrans++; return SQLITE_OK; } /* ** Called when a transaction completes (either by COMMIT or ROLLBACK). ** The sqlite3_blob object should be released at this point. */ static int rtreeEndTransaction(sqlite3_vtab *pVtab){ Rtree *pRtree = (Rtree *)pVtab; pRtree->inWrTrans = 0; nodeBlobReset(pRtree); return SQLITE_OK; } /* ** The xRename method for rtree module virtual tables. */ static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ Rtree *pRtree = (Rtree *)pVtab; int rc = SQLITE_NOMEM; char *zSql = sqlite3_mprintf( "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" , pRtree->zDb, pRtree->zName, zNewName , pRtree->zDb, pRtree->zName, zNewName , pRtree->zDb, pRtree->zName, zNewName ); if( zSql ){ rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); sqlite3_free(zSql); } return rc; } /* ** This function populates the pRtree->nRowEst variable with an estimate ** of the number of rows in the virtual table. If possible, this is based ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST. */ static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){ const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'"; char *zSql; sqlite3_stmt *p; int rc; i64 nRow = 0; rc = sqlite3_table_column_metadata( db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0 ); if( rc!=SQLITE_OK ){ pRtree->nRowEst = RTREE_DEFAULT_ROWEST; return rc==SQLITE_ERROR ? SQLITE_OK : rc; } zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0); if( rc==SQLITE_OK ){ if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0); rc = sqlite3_finalize(p); }else if( rc!=SQLITE_NOMEM ){ rc = SQLITE_OK; } if( rc==SQLITE_OK ){ if( nRow==0 ){ pRtree->nRowEst = RTREE_DEFAULT_ROWEST; }else{ pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST); } } sqlite3_free(zSql); } return rc; } static sqlite3_module rtreeModule = { 0, /* iVersion */ rtreeCreate, /* xCreate - create a table */ rtreeConnect, /* xConnect - connect to an existing table */ rtreeBestIndex, /* xBestIndex - Determine search strategy */ rtreeDisconnect, /* xDisconnect - Disconnect from a table */ rtreeDestroy, /* xDestroy - Drop a table */ rtreeOpen, /* xOpen - open a cursor */ rtreeClose, /* xClose - close a cursor */ rtreeFilter, /* xFilter - configure scan constraints */ rtreeNext, /* xNext - advance a cursor */ rtreeEof, /* xEof */ rtreeColumn, /* xColumn - read data */ rtreeRowid, /* xRowid - read data */ rtreeUpdate, /* xUpdate - write data */ rtreeBeginTransaction, /* xBegin - begin transaction */ rtreeEndTransaction, /* xSync - sync transaction */ rtreeEndTransaction, /* xCommit - commit transaction */ rtreeEndTransaction, /* xRollback - rollback transaction */ 0, /* xFindFunction - function overloading */ rtreeRename, /* xRename - rename the table */ 0, /* xSavepoint */ 0, /* xRelease */ 0, /* xRollbackTo */ }; static int rtreeSqlInit( Rtree *pRtree, sqlite3 *db, const char *zDb, const char *zPrefix, int isCreate ){ int rc = SQLITE_OK; #define N_STATEMENT 8 static const char *azSql[N_STATEMENT] = { /* Write the xxx_node table */ "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)", "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1", /* Read and write the xxx_rowid table */ "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1", "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)", "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1", /* Read and write the xxx_parent table */ "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1", "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)", "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1" }; sqlite3_stmt **appStmt[N_STATEMENT]; int i; pRtree->db = db; if( isCreate ){ char *zCreate = sqlite3_mprintf( "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);" "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);" "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY," " parentnode INTEGER);" "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))", zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize ); if( !zCreate ){ return SQLITE_NOMEM; } rc = sqlite3_exec(db, zCreate, 0, 0, 0); sqlite3_free(zCreate); if( rc!=SQLITE_OK ){ return rc; } } appStmt[0] = &pRtree->pWriteNode; appStmt[1] = &pRtree->pDeleteNode; appStmt[2] = &pRtree->pReadRowid; appStmt[3] = &pRtree->pWriteRowid; appStmt[4] = &pRtree->pDeleteRowid; appStmt[5] = &pRtree->pReadParent; appStmt[6] = &pRtree->pWriteParent; appStmt[7] = &pRtree->pDeleteParent; rc = rtreeQueryStat1(db, pRtree); for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){ char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix); if( zSql ){ rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); }else{ rc = SQLITE_NOMEM; } sqlite3_free(zSql); } return rc; } /* ** The second argument to this function contains the text of an SQL statement ** that returns a single integer value. The statement is compiled and executed ** using database connection db. If successful, the integer value returned ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error ** code is returned and the value of *piVal after returning is not defined. */ static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){ int rc = SQLITE_NOMEM; if( zSql ){ sqlite3_stmt *pStmt = 0; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pStmt) ){ *piVal = sqlite3_column_int(pStmt, 0); } rc = sqlite3_finalize(pStmt); } } return rc; } /* ** This function is called from within the xConnect() or xCreate() method to ** determine the node-size used by the rtree table being created or connected ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned. ** Otherwise, an SQLite error code is returned. ** ** If this function is being called as part of an xConnect(), then the rtree ** table already exists. In this case the node-size is determined by inspecting ** the root node of the tree. ** ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. ** This ensures that each node is stored on a single database page. If the ** database page-size is so large that more than RTREE_MAXCELLS entries ** would fit in a single node, use a smaller node-size. */ static int getNodeSize( sqlite3 *db, /* Database handle */ Rtree *pRtree, /* Rtree handle */ int isCreate, /* True for xCreate, false for xConnect */ char **pzErr /* OUT: Error message, if any */ ){ int rc; char *zSql; if( isCreate ){ int iPageSize = 0; zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); rc = getIntFromStmt(db, zSql, &iPageSize); if( rc==SQLITE_OK ){ pRtree->iNodeSize = iPageSize-64; if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){ pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; } }else{ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } }else{ zSql = sqlite3_mprintf( "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1", pRtree->zDb, pRtree->zName ); rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize); if( rc!=SQLITE_OK ){ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } } sqlite3_free(zSql); return rc; } /* ** This function is the implementation of both the xConnect and xCreate ** methods of the r-tree virtual table. ** ** argv[0] -> module name ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> column names... */ static int rtreeInit( sqlite3 *db, /* Database connection */ void *pAux, /* One of the RTREE_COORD_* constants */ int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ sqlite3_vtab **ppVtab, /* OUT: New virtual table */ char **pzErr, /* OUT: Error message, if any */ int isCreate /* True for xCreate, false for xConnect */ ){ int rc = SQLITE_OK; Rtree *pRtree; int nDb; /* Length of string argv[1] */ int nName; /* Length of string argv[2] */ int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32); const char *aErrMsg[] = { 0, /* 0 */ "Wrong number of columns for an rtree table", /* 1 */ "Too few columns for an rtree table", /* 2 */ "Too many columns for an rtree table" /* 3 */ }; int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2; if( aErrMsg[iErr] ){ *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); return SQLITE_ERROR; } sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); /* Allocate the sqlite3_vtab structure */ nDb = (int)strlen(argv[1]); nName = (int)strlen(argv[2]); pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2); if( !pRtree ){ return SQLITE_NOMEM; } memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); pRtree->nBusy = 1; pRtree->base.pModule = &rtreeModule; pRtree->zDb = (char *)&pRtree[1]; pRtree->zName = &pRtree->zDb[nDb+1]; pRtree->nDim = (u8)((argc-4)/2); pRtree->nDim2 = pRtree->nDim*2; pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; pRtree->eCoordType = (u8)eCoordType; memcpy(pRtree->zDb, argv[1], nDb); memcpy(pRtree->zName, argv[2], nName); /* Figure out the node size to use. */ rc = getNodeSize(db, pRtree, isCreate, pzErr); /* Create/Connect to the underlying relational database schema. If ** that is successful, call sqlite3_declare_vtab() to configure ** the r-tree table schema. */ if( rc==SQLITE_OK ){ if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); }else{ char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]); char *zTmp; int ii; for(ii=4; zSql && ii<argc; ii++){ zTmp = zSql; zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]); sqlite3_free(zTmp); } if( zSql ){ zTmp = zSql; zSql = sqlite3_mprintf("%s);", zTmp); sqlite3_free(zTmp); } if( !zSql ){ rc = SQLITE_NOMEM; }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){ *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } sqlite3_free(zSql); } } if( rc==SQLITE_OK ){ *ppVtab = (sqlite3_vtab *)pRtree; }else{ assert( *ppVtab==0 ); assert( pRtree->nBusy==1 ); rtreeRelease(pRtree); } return rc; } /* ** Implementation of a scalar function that decodes r-tree nodes to ** human readable strings. This can be used for debugging and analysis. ** ** The scalar function takes two arguments: (1) the number of dimensions ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing ** an r-tree node. For a two-dimensional r-tree structure called "rt", to ** deserialize all nodes, a statement like: ** ** SELECT rtreenode(2, data) FROM rt_node; ** ** The human readable string takes the form of a Tcl list with one ** entry for each cell in the r-tree node. Each entry is itself a ** list, containing the 8-byte rowid/pageno followed by the ** <num-dimension>*2 coordinates. */ static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ char *zText = 0; RtreeNode node; Rtree tree; int ii; UNUSED_PARAMETER(nArg); memset(&node, 0, sizeof(RtreeNode)); memset(&tree, 0, sizeof(Rtree)); tree.nDim = (u8)sqlite3_value_int(apArg[0]); tree.nDim2 = tree.nDim*2; tree.nBytesPerCell = 8 + 8 * tree.nDim; node.zData = (u8 *)sqlite3_value_blob(apArg[1]); for(ii=0; ii<NCELL(&node); ii++){ char zCell[512]; int nCell = 0; RtreeCell cell; int jj; nodeGetCell(&tree, &node, ii, &cell); sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid); nCell = (int)strlen(zCell); for(jj=0; jj<tree.nDim2; jj++){ #ifndef SQLITE_RTREE_INT_ONLY sqlite3_snprintf(512-nCell,&zCell[nCell], " %g", (double)cell.aCoord[jj].f); #else sqlite3_snprintf(512-nCell,&zCell[nCell], " %d", cell.aCoord[jj].i); #endif nCell = (int)strlen(zCell); } if( zText ){ char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell); sqlite3_free(zText); zText = zTextNew; }else{ zText = sqlite3_mprintf("{%s}", zCell); } } sqlite3_result_text(ctx, zText, -1, sqlite3_free); } /* This routine implements an SQL function that returns the "depth" parameter ** from the front of a blob that is an r-tree node. For example: ** ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1; ** ** The depth value is 0 for all nodes other than the root node, and the root ** node always has nodeno=1, so the example above is the primary use for this ** routine. This routine is intended for testing and analysis only. */ static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ UNUSED_PARAMETER(nArg); if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB || sqlite3_value_bytes(apArg[0])<2 ){ sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); }else{ u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]); sqlite3_result_int(ctx, readInt16(zBlob)); } } /* ** Register the r-tree module with database handle db. This creates the ** virtual table module "rtree" and the debugging/analysis scalar ** function "rtreenode". */ SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){ const int utf8 = SQLITE_UTF8; int rc; rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0); } if( rc==SQLITE_OK ){ #ifdef SQLITE_RTREE_INT_ONLY void *c = (void *)RTREE_COORD_INT32; #else void *c = (void *)RTREE_COORD_REAL32; #endif rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0); } if( rc==SQLITE_OK ){ void *c = (void *)RTREE_COORD_INT32; rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0); } return rc; } /* ** This routine deletes the RtreeGeomCallback object that was attached ** one of the SQL functions create by sqlite3_rtree_geometry_callback() ** or sqlite3_rtree_query_callback(). In other words, this routine is the ** destructor for an RtreeGeomCallback objecct. This routine is called when ** the corresponding SQL function is deleted. */ static void rtreeFreeCallback(void *p){ RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p; if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext); sqlite3_free(p); } /* ** This routine frees the BLOB that is returned by geomCallback(). */ static void rtreeMatchArgFree(void *pArg){ int i; RtreeMatchArg *p = (RtreeMatchArg*)pArg; for(i=0; i<p->nParam; i++){ sqlite3_value_free(p->apSqlParam[i]); } sqlite3_free(p); } /* ** Each call to sqlite3_rtree_geometry_callback() or ** sqlite3_rtree_query_callback() creates an ordinary SQLite ** scalar function that is implemented by this routine. ** ** All this function does is construct an RtreeMatchArg object that ** contains the geometry-checking callback routines and a list of ** parameters to this function, then return that RtreeMatchArg object ** as a BLOB. ** ** The R-Tree MATCH operator will read the returned BLOB, deserialize ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure ** out which elements of the R-Tree should be returned by the query. */ static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx); RtreeMatchArg *pBlob; int nBlob; int memErr = 0; nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue) + nArg*sizeof(sqlite3_value*); pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob); if( !pBlob ){ sqlite3_result_error_nomem(ctx); }else{ int i; pBlob->magic = RTREE_GEOMETRY_MAGIC; pBlob->cb = pGeomCtx[0]; pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg]; pBlob->nParam = nArg; for(i=0; i<nArg; i++){ pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]); if( pBlob->apSqlParam[i]==0 ) memErr = 1; #ifdef SQLITE_RTREE_INT_ONLY pBlob->aParam[i] = sqlite3_value_int64(aArg[i]); #else pBlob->aParam[i] = sqlite3_value_double(aArg[i]); #endif } if( memErr ){ sqlite3_result_error_nomem(ctx); rtreeMatchArgFree(pBlob); }else{ sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree); } } } /* ** Register a new geometry function for use with the r-tree MATCH operator. */ SQLITE_API int sqlite3_rtree_geometry_callback( sqlite3 *db, /* Register SQL function on this connection */ const char *zGeom, /* Name of the new SQL function */ int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */ void *pContext /* Extra data associated with the callback */ ){ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ /* Allocate and populate the context object. */ pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); if( !pGeomCtx ) return SQLITE_NOMEM; pGeomCtx->xGeom = xGeom; pGeomCtx->xQueryFunc = 0; pGeomCtx->xDestructor = 0; pGeomCtx->pContext = pContext; return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback ); } /* ** Register a new 2nd-generation geometry function for use with the ** r-tree MATCH operator. */ SQLITE_API int sqlite3_rtree_query_callback( sqlite3 *db, /* Register SQL function on this connection */ const char *zQueryFunc, /* Name of new SQL function */ int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */ void *pContext, /* Extra data passed into the callback */ void (*xDestructor)(void*) /* Destructor for the extra data */ ){ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ /* Allocate and populate the context object. */ pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); if( !pGeomCtx ) return SQLITE_NOMEM; pGeomCtx->xGeom = 0; pGeomCtx->xQueryFunc = xQueryFunc; pGeomCtx->xDestructor = xDestructor; pGeomCtx->pContext = pContext; return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback ); } #if !SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_rtree_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) return sqlite3RtreeInit(db); } #endif #endif /************** End of rtree.c ***********************************************/ /************** Begin file icu.c *********************************************/ /* ** 2007 May 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $ ** ** This file implements an integration between the ICU library ** ("International Components for Unicode", an open-source library ** for handling unicode data) and SQLite. The integration uses ** ICU to provide the following to SQLite: ** ** * An implementation of the SQL regexp() function (and hence REGEXP ** operator) using the ICU uregex_XX() APIs. ** ** * Implementations of the SQL scalar upper() and lower() functions ** for case mapping. ** ** * Integration of ICU and SQLite collation sequences. ** ** * An implementation of the LIKE operator that uses ICU to ** provide case-independent matching. */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) /* Include ICU headers */ #include <unicode/utypes.h> #include <unicode/uregex.h> #include <unicode/ustring.h> #include <unicode/ucol.h> /* #include <assert.h> */ #ifndef SQLITE_CORE /* #include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #else /* #include "sqlite3.h" */ #endif /* ** Maximum length (in bytes) of the pattern in a LIKE or GLOB ** operator. */ #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 #endif /* ** Version of sqlite3_free() that is always a function, never a macro. */ static void xFree(void *p){ sqlite3_free(p); } /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. It is copied here from SQLite source ** code file utf8.c. */ static const unsigned char icuUtf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; #define SQLITE_ICU_READ_UTF8(zIn, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = icuUtf8Trans1[c-0xc0]; \ while( (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ } #define SQLITE_ICU_SKIP_UTF8(zIn) \ assert( *zIn ); \ if( *(zIn++)>=0xc0 ){ \ while( (*zIn & 0xc0)==0x80 ){zIn++;} \ } /* ** Compare two UTF-8 strings for equality where the first string is ** a "LIKE" expression. Return true (1) if they are the same and ** false (0) if they are different. */ static int icuLikeCompare( const uint8_t *zPattern, /* LIKE pattern */ const uint8_t *zString, /* The UTF-8 string to compare against */ const UChar32 uEsc /* The escape character */ ){ static const int MATCH_ONE = (UChar32)'_'; static const int MATCH_ALL = (UChar32)'%'; int prevEscape = 0; /* True if the previous character was uEsc */ while( 1 ){ /* Read (and consume) the next character from the input pattern. */ UChar32 uPattern; SQLITE_ICU_READ_UTF8(zPattern, uPattern); if( uPattern==0 ) break; /* There are now 4 possibilities: ** ** 1. uPattern is an unescaped match-all character "%", ** 2. uPattern is an unescaped match-one character "_", ** 3. uPattern is an unescaped escape character, or ** 4. uPattern is to be handled as an ordinary character */ if( !prevEscape && uPattern==MATCH_ALL ){ /* Case 1. */ uint8_t c; /* Skip any MATCH_ALL or MATCH_ONE characters that follow a ** MATCH_ALL. For each MATCH_ONE, skip one character in the ** test string. */ while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){ if( c==MATCH_ONE ){ if( *zString==0 ) return 0; SQLITE_ICU_SKIP_UTF8(zString); } zPattern++; } if( *zPattern==0 ) return 1; while( *zString ){ if( icuLikeCompare(zPattern, zString, uEsc) ){ return 1; } SQLITE_ICU_SKIP_UTF8(zString); } return 0; }else if( !prevEscape && uPattern==MATCH_ONE ){ /* Case 2. */ if( *zString==0 ) return 0; SQLITE_ICU_SKIP_UTF8(zString); }else if( !prevEscape && uPattern==uEsc){ /* Case 3. */ prevEscape = 1; }else{ /* Case 4. */ UChar32 uString; SQLITE_ICU_READ_UTF8(zString, uString); uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT); uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT); if( uString!=uPattern ){ return 0; } prevEscape = 0; } } return *zString==0; } /* ** Implementation of the like() SQL function. This function implements ** the build-in LIKE operator. The first argument to the function is the ** pattern and the second argument is the string. So, the SQL statements: ** ** A LIKE B ** ** is implemented as like(B, A). If there is an escape character E, ** ** A LIKE B ESCAPE E ** ** is mapped to like(B, A, E). */ static void icuLikeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zA = sqlite3_value_text(argv[0]); const unsigned char *zB = sqlite3_value_text(argv[1]); UChar32 uEsc = 0; /* Limit the length of the LIKE or GLOB pattern to avoid problems ** of deep recursion and N*N behavior in patternCompare(). */ if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); return; } if( argc==3 ){ /* The escape character string must consist of a single UTF-8 character. ** Otherwise, return an error. */ int nE= sqlite3_value_bytes(argv[2]); const unsigned char *zE = sqlite3_value_text(argv[2]); int i = 0; if( zE==0 ) return; U8_NEXT(zE, i, nE, uEsc); if( i!=nE){ sqlite3_result_error(context, "ESCAPE expression must be a single character", -1); return; } } if( zA && zB ){ sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc)); } } /* ** This function is called when an ICU function called from within ** the implementation of an SQL scalar function returns an error. ** ** The scalar function context passed as the first argument is ** loaded with an error message based on the following two args. */ static void icuFunctionError( sqlite3_context *pCtx, /* SQLite scalar function context */ const char *zName, /* Name of ICU function that failed */ UErrorCode e /* Error code returned by ICU function */ ){ char zBuf[128]; sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e)); zBuf[127] = '\0'; sqlite3_result_error(pCtx, zBuf, -1); } /* ** Function to delete compiled regexp objects. Registered as ** a destructor function with sqlite3_set_auxdata(). */ static void icuRegexpDelete(void *p){ URegularExpression *pExpr = (URegularExpression *)p; uregex_close(pExpr); } /* ** Implementation of SQLite REGEXP operator. This scalar function takes ** two arguments. The first is a regular expression pattern to compile ** the second is a string to match against that pattern. If either ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result ** is 1 if the string matches the pattern, or 0 otherwise. ** ** SQLite maps the regexp() function to the regexp() operator such ** that the following two are equivalent: ** ** zString REGEXP zPattern ** regexp(zPattern, zString) ** ** Uses the following ICU regexp APIs: ** ** uregex_open() ** uregex_matches() ** uregex_close() */ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ UErrorCode status = U_ZERO_ERROR; URegularExpression *pExpr; UBool res; const UChar *zString = sqlite3_value_text16(apArg[1]); (void)nArg; /* Unused parameter */ /* If the left hand side of the regexp operator is NULL, ** then the result is also NULL. */ if( !zString ){ return; } pExpr = sqlite3_get_auxdata(p, 0); if( !pExpr ){ const UChar *zPattern = sqlite3_value_text16(apArg[0]); if( !zPattern ){ return; } pExpr = uregex_open(zPattern, -1, 0, 0, &status); if( U_SUCCESS(status) ){ sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete); }else{ assert(!pExpr); icuFunctionError(p, "uregex_open", status); return; } } /* Configure the text that the regular expression operates on. */ uregex_setText(pExpr, zString, -1, &status); if( !U_SUCCESS(status) ){ icuFunctionError(p, "uregex_setText", status); return; } /* Attempt the match */ res = uregex_matches(pExpr, 0, &status); if( !U_SUCCESS(status) ){ icuFunctionError(p, "uregex_matches", status); return; } /* Set the text that the regular expression operates on to a NULL ** pointer. This is not really necessary, but it is tidier than ** leaving the regular expression object configured with an invalid ** pointer after this function returns. */ uregex_setText(pExpr, 0, 0, &status); /* Return 1 or 0. */ sqlite3_result_int(p, res ? 1 : 0); } /* ** Implementations of scalar functions for case mapping - upper() and ** lower(). Function upper() converts its input to upper-case (ABC). ** Function lower() converts to lower-case (abc). ** ** ICU provides two types of case mapping, "general" case mapping and ** "language specific". Refer to ICU documentation for the differences ** between the two. ** ** To utilise "general" case mapping, the upper() or lower() scalar ** functions are invoked with one argument: ** ** upper('ABC') -> 'abc' ** lower('abc') -> 'ABC' ** ** To access ICU "language specific" case mapping, upper() or lower() ** should be invoked with two arguments. The second argument is the name ** of the locale to use. Passing an empty string ("") or SQL NULL value ** as the second argument is the same as invoking the 1 argument version ** of upper() or lower(). ** ** lower('I', 'en_us') -> 'i' ** lower('I', 'tr_tr') -> '\u131' (small dotless i) ** ** http://www.icu-project.org/userguide/posix.html#case_mappings */ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ const UChar *zInput; /* Pointer to input string */ UChar *zOutput = 0; /* Pointer to output buffer */ int nInput; /* Size of utf-16 input string in bytes */ int nOut; /* Size of output buffer in bytes */ int cnt; int bToUpper; /* True for toupper(), false for tolower() */ UErrorCode status; const char *zLocale = 0; assert(nArg==1 || nArg==2); bToUpper = (sqlite3_user_data(p)!=0); if( nArg==2 ){ zLocale = (const char *)sqlite3_value_text(apArg[1]); } zInput = sqlite3_value_text16(apArg[0]); if( !zInput ){ return; } nOut = nInput = sqlite3_value_bytes16(apArg[0]); if( nOut==0 ){ sqlite3_result_text16(p, "", 0, SQLITE_STATIC); return; } for(cnt=0; cnt<2; cnt++){ UChar *zNew = sqlite3_realloc(zOutput, nOut); if( zNew==0 ){ sqlite3_free(zOutput); sqlite3_result_error_nomem(p); return; } zOutput = zNew; status = U_ZERO_ERROR; if( bToUpper ){ nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); }else{ nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); } if( U_SUCCESS(status) ){ sqlite3_result_text16(p, zOutput, nOut, xFree); }else if( status==U_BUFFER_OVERFLOW_ERROR ){ assert( cnt==0 ); continue; }else{ icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status); } return; } assert( 0 ); /* Unreachable */ } /* ** Collation sequence destructor function. The pCtx argument points to ** a UCollator structure previously allocated using ucol_open(). */ static void icuCollationDel(void *pCtx){ UCollator *p = (UCollator *)pCtx; ucol_close(p); } /* ** Collation sequence comparison function. The pCtx argument points to ** a UCollator structure previously allocated using ucol_open(). */ static int icuCollationColl( void *pCtx, int nLeft, const void *zLeft, int nRight, const void *zRight ){ UCollationResult res; UCollator *p = (UCollator *)pCtx; res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2); switch( res ){ case UCOL_LESS: return -1; case UCOL_GREATER: return +1; case UCOL_EQUAL: return 0; } assert(!"Unexpected return value from ucol_strcoll()"); return 0; } /* ** Implementation of the scalar function icu_load_collation(). ** ** This scalar function is used to add ICU collation based collation ** types to an SQLite database connection. It is intended to be called ** as follows: ** ** SELECT icu_load_collation(<locale>, <collation-name>); ** ** Where <locale> is a string containing an ICU locale identifier (i.e. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the ** collation sequence to create. */ static void icuLoadCollation( sqlite3_context *p, int nArg, sqlite3_value **apArg ){ sqlite3 *db = (sqlite3 *)sqlite3_user_data(p); UErrorCode status = U_ZERO_ERROR; const char *zLocale; /* Locale identifier - (eg. "jp_JP") */ const char *zName; /* SQL Collation sequence name (eg. "japanese") */ UCollator *pUCollator; /* ICU library collation object */ int rc; /* Return code from sqlite3_create_collation_x() */ assert(nArg==2); (void)nArg; /* Unused parameter */ zLocale = (const char *)sqlite3_value_text(apArg[0]); zName = (const char *)sqlite3_value_text(apArg[1]); if( !zLocale || !zName ){ return; } pUCollator = ucol_open(zLocale, &status); if( !U_SUCCESS(status) ){ icuFunctionError(p, "ucol_open", status); return; } assert(p); rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, icuCollationColl, icuCollationDel ); if( rc!=SQLITE_OK ){ ucol_close(pUCollator); sqlite3_result_error(p, "Error registering collation function", -1); } } /* ** Register the ICU extension functions with database db. */ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){ static const struct IcuScalar { const char *zName; /* Function name */ unsigned char nArg; /* Number of arguments */ unsigned short enc; /* Optimal text encoding */ unsigned char iContext; /* sqlite3_user_data() context */ void (*xFunc)(sqlite3_context*,int,sqlite3_value**); } scalars[] = { {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation}, {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc}, {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16}, {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16}, {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16}, {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16}, {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc}, {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc}, }; int rc = SQLITE_OK; int i; for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){ const struct IcuScalar *p = &scalars[i]; rc = sqlite3_create_function( db, p->zName, p->nArg, p->enc, p->iContext ? (void*)db : (void*)0, p->xFunc, 0, 0 ); } return rc; } #if !SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_icu_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) return sqlite3IcuInit(db); } #endif #endif /************** End of icu.c *************************************************/ /************** Begin file fts3_icu.c ****************************************/ /* ** 2007 June 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements a tokenizer for fts3 based on the ICU library. */ /* #include "fts3Int.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) #ifdef SQLITE_ENABLE_ICU /* #include <assert.h> */ /* #include <string.h> */ /* #include "fts3_tokenizer.h" */ #include <unicode/ubrk.h> /* #include <unicode/ucol.h> */ /* #include <unicode/ustring.h> */ #include <unicode/utf16.h> typedef struct IcuTokenizer IcuTokenizer; typedef struct IcuCursor IcuCursor; struct IcuTokenizer { sqlite3_tokenizer base; char *zLocale; }; struct IcuCursor { sqlite3_tokenizer_cursor base; UBreakIterator *pIter; /* ICU break-iterator object */ int nChar; /* Number of UChar elements in pInput */ UChar *aChar; /* Copy of input using utf-16 encoding */ int *aOffset; /* Offsets of each character in utf-8 input */ int nBuffer; char *zBuffer; int iToken; }; /* ** Create a new tokenizer instance. */ static int icuCreate( int argc, /* Number of entries in argv[] */ const char * const *argv, /* Tokenizer creation arguments */ sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ ){ IcuTokenizer *p; int n = 0; if( argc>0 ){ n = strlen(argv[0])+1; } p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n); if( !p ){ return SQLITE_NOMEM; } memset(p, 0, sizeof(IcuTokenizer)); if( n ){ p->zLocale = (char *)&p[1]; memcpy(p->zLocale, argv[0], n); } *ppTokenizer = (sqlite3_tokenizer *)p; return SQLITE_OK; } /* ** Destroy a tokenizer */ static int icuDestroy(sqlite3_tokenizer *pTokenizer){ IcuTokenizer *p = (IcuTokenizer *)pTokenizer; sqlite3_free(p); return SQLITE_OK; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is pInput[0..nBytes-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int icuOpen( sqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *zInput, /* Input string */ int nInput, /* Length of zInput in bytes */ sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ IcuTokenizer *p = (IcuTokenizer *)pTokenizer; IcuCursor *pCsr; const int32_t opt = U_FOLD_CASE_DEFAULT; UErrorCode status = U_ZERO_ERROR; int nChar; UChar32 c; int iInput = 0; int iOut = 0; *ppCursor = 0; if( zInput==0 ){ nInput = 0; zInput = ""; }else if( nInput<0 ){ nInput = strlen(zInput); } nChar = nInput+1; pCsr = (IcuCursor *)sqlite3_malloc( sizeof(IcuCursor) + /* IcuCursor */ ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */ (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */ ); if( !pCsr ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(IcuCursor)); pCsr->aChar = (UChar *)&pCsr[1]; pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3]; pCsr->aOffset[iOut] = iInput; U8_NEXT(zInput, iInput, nInput, c); while( c>0 ){ int isError = 0; c = u_foldCase(c, opt); U16_APPEND(pCsr->aChar, iOut, nChar, c, isError); if( isError ){ sqlite3_free(pCsr); return SQLITE_ERROR; } pCsr->aOffset[iOut] = iInput; if( iInput<nInput ){ U8_NEXT(zInput, iInput, nInput, c); }else{ c = 0; } } pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status); if( !U_SUCCESS(status) ){ sqlite3_free(pCsr); return SQLITE_ERROR; } pCsr->nChar = iOut; ubrk_first(pCsr->pIter); *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to icuOpen(). */ static int icuClose(sqlite3_tokenizer_cursor *pCursor){ IcuCursor *pCsr = (IcuCursor *)pCursor; ubrk_close(pCsr->pIter); sqlite3_free(pCsr->zBuffer); sqlite3_free(pCsr); return SQLITE_OK; } /* ** Extract the next token from a tokenization cursor. */ static int icuNext( sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ const char **ppToken, /* OUT: *ppToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ int *piEndOffset, /* OUT: Ending offset of token */ int *piPosition /* OUT: Position integer of token */ ){ IcuCursor *pCsr = (IcuCursor *)pCursor; int iStart = 0; int iEnd = 0; int nByte = 0; while( iStart==iEnd ){ UChar32 c; iStart = ubrk_current(pCsr->pIter); iEnd = ubrk_next(pCsr->pIter); if( iEnd==UBRK_DONE ){ return SQLITE_DONE; } while( iStart<iEnd ){ int iWhite = iStart; U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c); if( u_isspace(c) ){ iStart = iWhite; }else{ break; } } assert(iStart<=iEnd); } do { UErrorCode status = U_ZERO_ERROR; if( nByte ){ char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte); if( !zNew ){ return SQLITE_NOMEM; } pCsr->zBuffer = zNew; pCsr->nBuffer = nByte; } u_strToUTF8( pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */ &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */ &status /* Output success/failure */ ); } while( nByte>pCsr->nBuffer ); *ppToken = pCsr->zBuffer; *pnBytes = nByte; *piStartOffset = pCsr->aOffset[iStart]; *piEndOffset = pCsr->aOffset[iEnd]; *piPosition = pCsr->iToken++; return SQLITE_OK; } /* ** The set of routines that implement the simple tokenizer */ static const sqlite3_tokenizer_module icuTokenizerModule = { 0, /* iVersion */ icuCreate, /* xCreate */ icuDestroy, /* xCreate */ icuOpen, /* xOpen */ icuClose, /* xClose */ icuNext, /* xNext */ 0, /* xLanguageid */ }; /* ** Set *ppModule to point at the implementation of the ICU tokenizer. */ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &icuTokenizerModule; } #endif /* defined(SQLITE_ENABLE_ICU) */ #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_icu.c ********************************************/ /************** Begin file sqlite3rbu.c **************************************/ /* ** 2014 August 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** ** OVERVIEW ** ** The RBU extension requires that the RBU update be packaged as an ** SQLite database. The tables it expects to find are described in ** sqlite3rbu.h. Essentially, for each table xyz in the target database ** that the user wishes to write to, a corresponding data_xyz table is ** created in the RBU database and populated with one row for each row to ** update, insert or delete from the target table. ** ** The update proceeds in three stages: ** ** 1) The database is updated. The modified database pages are written ** to a *-oal file. A *-oal file is just like a *-wal file, except ** that it is named "<database>-oal" instead of "<database>-wal". ** Because regular SQLite clients do not look for file named ** "<database>-oal", they go on using the original database in ** rollback mode while the *-oal file is being generated. ** ** During this stage RBU does not update the database by writing ** directly to the target tables. Instead it creates "imposter" ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses ** to update each b-tree individually. All updates required by each ** b-tree are completed before moving on to the next, and all ** updates are done in sorted key order. ** ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal" ** location using a call to rename(2). Before doing this the RBU ** module takes an EXCLUSIVE lock on the database file, ensuring ** that there are no other active readers. ** ** Once the EXCLUSIVE lock is released, any other database readers ** detect the new *-wal file and read the database in wal mode. At ** this point they see the new version of the database - including ** the updates made as part of the RBU update. ** ** 3) The new *-wal file is checkpointed. This proceeds in the same way ** as a regular database checkpoint, except that a single frame is ** checkpointed each time sqlite3rbu_step() is called. If the RBU ** handle is closed before the entire *-wal file is checkpointed, ** the checkpoint progress is saved in the RBU database and the ** checkpoint can be resumed by another RBU client at some point in ** the future. ** ** POTENTIAL PROBLEMS ** ** The rename() call might not be portable. And RBU is not currently ** syncing the directory after renaming the file. ** ** When state is saved, any commit to the *-oal file and the commit to ** the RBU update database are not atomic. So if the power fails at the ** wrong moment they might get out of sync. As the main database will be ** committed before the RBU update database this will likely either just ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE ** constraint violations). ** ** If some client does modify the target database mid RBU update, or some ** other error occurs, the RBU extension will keep throwing errors. It's ** not really clear how to get out of this state. The system could just ** by delete the RBU update database and *-oal file and have the device ** download the update again and start over. ** ** At present, for an UPDATE, both the new.* and old.* records are ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all ** fields are collected. This means we're probably writing a lot more ** data to disk when saving the state of an ongoing update to the RBU ** update database than is strictly necessary. ** */ /* #include <assert.h> */ /* #include <string.h> */ /* #include <stdio.h> */ /* #include "sqlite3.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/ /************** Begin file sqlite3rbu.h **************************************/ /* ** 2014 August 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the public interface for the RBU extension. */ /* ** SUMMARY ** ** Writing a transaction containing a large number of operations on ** b-tree indexes that are collectively larger than the available cache ** memory can be very inefficient. ** ** The problem is that in order to update a b-tree, the leaf page (at least) ** containing the entry being inserted or deleted must be modified. If the ** working set of leaves is larger than the available cache memory, then a ** single leaf that is modified more than once as part of the transaction ** may be loaded from or written to the persistent media multiple times. ** Additionally, because the index updates are likely to be applied in ** random order, access to pages within the database is also likely to be in ** random order, which is itself quite inefficient. ** ** One way to improve the situation is to sort the operations on each index ** by index key before applying them to the b-tree. This leads to an IO ** pattern that resembles a single linear scan through the index b-tree, ** and all but guarantees each modified leaf page is loaded and stored ** exactly once. SQLite uses this trick to improve the performance of ** CREATE INDEX commands. This extension allows it to be used to improve ** the performance of large transactions on existing databases. ** ** Additionally, this extension allows the work involved in writing the ** large transaction to be broken down into sub-transactions performed ** sequentially by separate processes. This is useful if the system cannot ** guarantee that a single update process will run for long enough to apply ** the entire update, for example because the update is being applied on a ** mobile device that is frequently rebooted. Even after the writer process ** has committed one or more sub-transactions, other database clients continue ** to read from the original database snapshot. In other words, partially ** applied transactions are not visible to other clients. ** ** "RBU" stands for "Resumable Bulk Update". As in a large database update ** transmitted via a wireless network to a mobile device. A transaction ** applied using this extension is hence refered to as an "RBU update". ** ** ** LIMITATIONS ** ** An "RBU update" transaction is subject to the following limitations: ** ** * The transaction must consist of INSERT, UPDATE and DELETE operations ** only. ** ** * INSERT statements may not use any default values. ** ** * UPDATE and DELETE statements must identify their target rows by ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY ** KEY fields may not be updated or deleted. If the table being written ** has no PRIMARY KEY, affected rows must be identified by rowid. ** ** * UPDATE statements may not modify PRIMARY KEY columns. ** ** * No triggers will be fired. ** ** * No foreign key violations are detected or reported. ** ** * CHECK constraints are not enforced. ** ** * No constraint handling mode except for "OR ROLLBACK" is supported. ** ** ** PREPARATION ** ** An "RBU update" is stored as a separate SQLite database. A database ** containing an RBU update is an "RBU database". For each table in the ** target database to be updated, the RBU database should contain a table ** named "data_<target name>" containing the same set of columns as the ** target table, and one more - "rbu_control". The data_% table should ** have no PRIMARY KEY or UNIQUE constraints, but each column should have ** the same type as the corresponding column in the target database. ** The "rbu_control" column should have no type at all. For example, if ** the target database contains: ** ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE); ** ** Then the RBU database should contain: ** ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control); ** ** The order of the columns in the data_% table does not matter. ** ** Instead of a regular table, the RBU database may also contain virtual ** tables or view named using the data_<target> naming scheme. ** ** Instead of the plain data_<target> naming scheme, RBU database tables ** may also be named data<integer>_<target>, where <integer> is any sequence ** of zero or more numeric characters (0-9). This can be significant because ** tables within the RBU database are always processed in order sorted by ** name. By judicious selection of the <integer> portion of the names ** of the RBU tables the user can therefore control the order in which they ** are processed. This can be useful, for example, to ensure that "external ** content" FTS4 tables are updated before their underlying content tables. ** ** If the target database table is a virtual table or a table that has no ** PRIMARY KEY declaration, the data_% table must also contain a column ** named "rbu_rowid". This column is mapped to the tables implicit primary ** key column - "rowid". Virtual tables for which the "rowid" column does ** not function like a primary key value cannot be updated using RBU. For ** example, if the target db contains either of the following: ** ** CREATE VIRTUAL TABLE x1 USING fts3(a, b); ** CREATE TABLE x1(a, b) ** ** then the RBU database should contain: ** ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control); ** ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the ** target table must be present in the input table. For virtual tables, ** hidden columns are optional - they are updated by RBU if present in ** the input table, or not otherwise. For example, to write to an fts4 ** table with a hidden languageid column such as: ** ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid'); ** ** Either of the following input table schemas may be used: ** ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control); ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control); ** ** For each row to INSERT into the target database as part of the RBU ** update, the corresponding data_% table should contain a single record ** with the "rbu_control" column set to contain integer value 0. The ** other columns should be set to the values that make up the new record ** to insert. ** ** If the target database table has an INTEGER PRIMARY KEY, it is not ** possible to insert a NULL value into the IPK column. Attempting to ** do so results in an SQLITE_MISMATCH error. ** ** For each row to DELETE from the target database as part of the RBU ** update, the corresponding data_% table should contain a single record ** with the "rbu_control" column set to contain integer value 1. The ** real primary key values of the row to delete should be stored in the ** corresponding columns of the data_% table. The values stored in the ** other columns are not used. ** ** For each row to UPDATE from the target database as part of the RBU ** update, the corresponding data_% table should contain a single record ** with the "rbu_control" column set to contain a value of type text. ** The real primary key values identifying the row to update should be ** stored in the corresponding columns of the data_% table row, as should ** the new values of all columns being update. The text value in the ** "rbu_control" column must contain the same number of characters as ** there are columns in the target database table, and must consist entirely ** of 'x' and '.' characters (or in some special cases 'd' - see below). For ** each column that is being updated, the corresponding character is set to ** 'x'. For those that remain as they are, the corresponding character of the ** rbu_control value should be set to '.'. For example, given the tables ** above, the update statement: ** ** UPDATE t1 SET c = 'usa' WHERE a = 4; ** ** is represented by the data_t1 row created by: ** ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x'); ** ** Instead of an 'x' character, characters of the rbu_control value specified ** for UPDATEs may also be set to 'd'. In this case, instead of updating the ** target table with the value stored in the corresponding data_% column, the ** user-defined SQL function "rbu_delta()" is invoked and the result stored in ** the target table column. rbu_delta() is invoked with two arguments - the ** original value currently stored in the target table column and the ** value specified in the data_xxx table. ** ** For example, this row: ** ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d'); ** ** is similar to an UPDATE statement such as: ** ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4; ** ** Finally, if an 'f' character appears in place of a 'd' or 's' in an ** ota_control string, the contents of the data_xxx table column is assumed ** to be a "fossil delta" - a patch to be applied to a blob value in the ** format used by the fossil source-code management system. In this case ** the existing value within the target database table must be of type BLOB. ** It is replaced by the result of applying the specified fossil delta to ** itself. ** ** If the target database table is a virtual table or a table with no PRIMARY ** KEY, the rbu_control value should not include a character corresponding ** to the rbu_rowid value. For example, this: ** ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) ** VALUES(NULL, 'usa', 12, '.x'); ** ** causes a result similar to: ** ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12; ** ** The data_xxx tables themselves should have no PRIMARY KEY declarations. ** However, RBU is more efficient if reading the rows in from each data_xxx ** table in "rowid" order is roughly the same as reading them sorted by ** the PRIMARY KEY of the corresponding target database table. In other ** words, rows should be sorted using the destination table PRIMARY KEY ** fields before they are inserted into the data_xxx tables. ** ** USAGE ** ** The API declared below allows an application to apply an RBU update ** stored on disk to an existing target database. Essentially, the ** application: ** ** 1) Opens an RBU handle using the sqlite3rbu_open() function. ** ** 2) Registers any required virtual table modules with the database ** handle returned by sqlite3rbu_db(). Also, if required, register ** the rbu_delta() implementation. ** ** 3) Calls the sqlite3rbu_step() function one or more times on ** the new handle. Each call to sqlite3rbu_step() performs a single ** b-tree operation, so thousands of calls may be required to apply ** a complete update. ** ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If ** sqlite3rbu_step() has been called enough times to completely ** apply the update to the target database, then the RBU database ** is marked as fully applied. Otherwise, the state of the RBU ** update application is saved in the RBU database for later ** resumption. ** ** See comments below for more detail on APIs. ** ** If an update is only partially applied to the target database by the ** time sqlite3rbu_close() is called, various state information is saved ** within the RBU database. This allows subsequent processes to automatically ** resume the RBU update from where it left off. ** ** To remove all RBU extension state information, returning an RBU database ** to its original contents, it is sufficient to drop all tables that begin ** with the prefix "rbu_" ** ** DATABASE LOCKING ** ** An RBU update may not be applied to a database in WAL mode. Attempting ** to do so is an error (SQLITE_ERROR). ** ** While an RBU handle is open, a SHARED lock may be held on the target ** database file. This means it is possible for other clients to read the ** database, but not to write it. ** ** If an RBU update is started and then suspended before it is completed, ** then an external client writes to the database, then attempting to resume ** the suspended RBU update is also an error (SQLITE_BUSY). */ #ifndef _SQLITE3RBU_H #define _SQLITE3RBU_H /* #include "sqlite3.h" ** Required for error code definitions ** */ #if 0 extern "C" { #endif typedef struct sqlite3rbu sqlite3rbu; /* ** Open an RBU handle. ** ** Argument zTarget is the path to the target database. Argument zRbu is ** the path to the RBU database. Each call to this function must be matched ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget ** or zRbu begin with "file:", it will be interpreted as an SQLite ** database URI, not a regular file name. ** ** If the zState argument is passed a NULL value, the RBU extension stores ** the current state of the update (how many rows have been updated, which ** indexes are yet to be updated etc.) within the RBU database itself. This ** can be convenient, as it means that the RBU application does not need to ** organize removing a separate state file after the update is concluded. ** Or, if zState is non-NULL, it must be a path to a database file in which ** the RBU extension can store the state of the update. ** ** When resuming an RBU update, the zState argument must be passed the same ** value as when the RBU update was started. ** ** Once the RBU update is finished, the RBU extension does not ** automatically remove any zState database file, even if it created it. ** ** By default, RBU uses the default VFS to access the files on disk. To ** use a VFS other than the default, an SQLite "file:" URI containing a ** "vfs=..." option may be passed as the zTarget option. ** ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of ** SQLite's built-in VFSs, including the multiplexor VFS. However it does ** not work out of the box with zipvfs. Refer to the comment describing ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs. */ SQLITE_API sqlite3rbu *sqlite3rbu_open( const char *zTarget, const char *zRbu, const char *zState ); /* ** Open an RBU handle to perform an RBU vacuum on database file zTarget. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except ** that it can be suspended and resumed like an RBU update. ** ** The second argument to this function identifies a database in which ** to store the state of the RBU vacuum operation if it is suspended. The ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum ** operation, the state database should either not exist or be empty ** (contain no tables). If an RBU vacuum is suspended by calling ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has ** returned SQLITE_DONE, the vacuum state is stored in the state database. ** The vacuum can be resumed by calling this function to open a new RBU ** handle specifying the same target and state databases. ** ** If the second argument passed to this function is NULL, then the ** name of the state database is "<database>-vacuum", where <database> ** is the name of the target database file. In this case, on UNIX, if the ** state database is not already present in the file-system, it is created ** with the same permissions as the target db is made. ** ** This function does not delete the state database after an RBU vacuum ** is completed, even if it created it. However, if the call to ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents ** of the state tables within the state database are zeroed. This way, ** the next call to sqlite3rbu_vacuum() opens a handle that starts a ** new RBU vacuum operation. ** ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment ** describing the sqlite3rbu_create_vfs() API function below for ** a description of the complications associated with using RBU with ** zipvfs databases. */ SQLITE_API sqlite3rbu *sqlite3rbu_vacuum( const char *zTarget, const char *zState ); /* ** Internally, each RBU connection uses a separate SQLite database ** connection to access the target and rbu update databases. This ** API allows the application direct access to these database handles. ** ** The first argument passed to this function must be a valid, open, RBU ** handle. The second argument should be passed zero to access the target ** database handle, or non-zero to access the rbu update database handle. ** Accessing the underlying database handles may be useful in the ** following scenarios: ** ** * If any target tables are virtual tables, it may be necessary to ** call sqlite3_create_module() on the target database handle to ** register the required virtual table implementations. ** ** * If the data_xxx tables in the RBU source database are virtual ** tables, the application may need to call sqlite3_create_module() on ** the rbu update db handle to any required virtual table ** implementations. ** ** * If the application uses the "rbu_delta()" feature described above, ** it must use sqlite3_create_function() or similar to register the ** rbu_delta() implementation with the target database handle. ** ** If an error has occurred, either while opening or stepping the RBU object, ** this function may return NULL. The error code and message may be collected ** when sqlite3rbu_close() is called. ** ** Database handles returned by this function remain valid until the next ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db(). */ SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu); /* ** Do some work towards applying the RBU update to the target db. ** ** Return SQLITE_DONE if the update has been completely applied, or ** SQLITE_OK if no error occurs but there remains work to do to apply ** the RBU update. If an error does occur, some other error code is ** returned. ** ** Once a call to sqlite3rbu_step() has returned a value other than ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops ** that immediately return the same value. */ SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu); /* ** Force RBU to save its state to disk. ** ** If a power failure or application crash occurs during an update, following ** system recovery RBU may resume the update from the point at which the state ** was last saved. In other words, from the most recent successful call to ** sqlite3rbu_close() or this function. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu); /* ** Close an RBU handle. ** ** If the RBU update has been completely applied, mark the RBU database ** as fully applied. Otherwise, assuming no error has occurred, save the ** current state of the RBU update appliation to the RBU database. ** ** If an error has already occurred as part of an sqlite3rbu_step() ** or sqlite3rbu_open() call, or if one occurs within this function, an ** SQLite error code is returned. Additionally, *pzErrmsg may be set to ** point to a buffer containing a utf-8 formatted English language error ** message. It is the responsibility of the caller to eventually free any ** such buffer using sqlite3_free(). ** ** Otherwise, if no error occurs, this function returns SQLITE_OK if the ** update has been partially applied, or SQLITE_DONE if it has been ** completely applied. */ SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg); /* ** Return the total number of key-value operations (inserts, deletes or ** updates) that have been performed on the target database since the ** current RBU update was started. */ SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu); /* ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) ** progress indications for the two stages of an RBU update. This API may ** be useful for driving GUI progress indicators and similar. ** ** An RBU update is divided into two stages: ** ** * Stage 1, in which changes are accumulated in an oal/wal file, and ** * Stage 2, in which the contents of the wal file are copied into the ** main database. ** ** The update is visible to non-RBU clients during stage 2. During stage 1 ** non-RBU reader clients may see the original database. ** ** If this API is called during stage 2 of the update, output variable ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo) ** to a value between 0 and 10000 to indicate the permyriadage progress of ** stage 2. A value of 5000 indicates that stage 2 is half finished, ** 9000 indicates that it is 90% finished, and so on. ** ** If this API is called during stage 1 of the update, output variable ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The ** value to which (*pnOne) is set depends on whether or not the RBU ** database contains an "rbu_count" table. The rbu_count table, if it ** exists, must contain the same columns as the following: ** ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID; ** ** There must be one row in the table for each source (data_xxx) table within ** the RBU database. The 'tbl' column should contain the name of the source ** table. The 'cnt' column should contain the number of rows within the ** source table. ** ** If the rbu_count table is present and populated correctly and this ** API is called during stage 1, the *pnOne output variable is set to the ** permyriadage progress of the same stage. If the rbu_count table does ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count ** table exists but is not correctly populated, the value of the *pnOne ** output variable during stage 1 is undefined. */ SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo); /* ** Obtain an indication as to the current stage of an RBU update or vacuum. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants ** defined in this file. Return values should be interpreted as follows: ** ** SQLITE_RBU_STATE_OAL: ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step() ** may either add further data to the *-oal file, or compute data that will ** be added by a subsequent call. ** ** SQLITE_RBU_STATE_MOVE: ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step() ** will move the *-oal file to the equivalent *-wal path. If the current ** operation is an RBU update, then the updated version of the database ** file will become visible to ordinary SQLite clients following the next ** call to sqlite3rbu_step(). ** ** SQLITE_RBU_STATE_CHECKPOINT: ** RBU is currently performing an incremental checkpoint. The next call to ** sqlite3rbu_step() will copy a page of data from the *-wal file into ** the target database file. ** ** SQLITE_RBU_STATE_DONE: ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step() ** will immediately return SQLITE_DONE. ** ** SQLITE_RBU_STATE_ERROR: ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will ** immediately return the SQLite error code associated with the error. */ #define SQLITE_RBU_STATE_OAL 1 #define SQLITE_RBU_STATE_MOVE 2 #define SQLITE_RBU_STATE_CHECKPOINT 3 #define SQLITE_RBU_STATE_DONE 4 #define SQLITE_RBU_STATE_ERROR 5 SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu); /* ** Create an RBU VFS named zName that accesses the underlying file-system ** via existing VFS zParent. Or, if the zParent parameter is passed NULL, ** then the new RBU VFS uses the default system VFS to access the file-system. ** The new object is registered as a non-default VFS with SQLite before ** returning. ** ** Part of the RBU implementation uses a custom VFS object. Usually, this ** object is created and deleted automatically by RBU. ** ** The exception is for applications that also use zipvfs. In this case, ** the custom VFS must be explicitly created by the user before the RBU ** handle is opened. The RBU VFS should be installed so that the zipvfs ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use ** (for example multiplexor) to access the file-system. For example, ** to assemble an RBU enabled VFS stack that uses both zipvfs and ** multiplexor (error checking omitted): ** ** // Create a VFS named "multiplex" (not the default). ** sqlite3_multiplex_initialize(0, 0); ** ** // Create an rbu VFS named "rbu" that uses multiplexor. If the ** // second argument were replaced with NULL, the "rbu" VFS would ** // access the file-system via the system default VFS, bypassing the ** // multiplexor. ** sqlite3rbu_create_vfs("rbu", "multiplex"); ** ** // Create a zipvfs VFS named "zipvfs" that uses rbu. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector); ** ** // Make zipvfs the default VFS. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1); ** ** Because the default VFS created above includes a RBU functionality, it ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack ** that does not include the RBU layer results in an error. ** ** The overhead of adding the "rbu" VFS to the system is negligible for ** non-RBU users. There is no harm in an application accessing the ** file-system via "rbu" all the time, even if it only uses RBU functionality ** occasionally. */ SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent); /* ** Deregister and destroy an RBU vfs created by an earlier call to ** sqlite3rbu_create_vfs(). ** ** VFS objects are not reference counted. If a VFS object is destroyed ** before all database handles that use it have been closed, the results ** are undefined. */ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); #if 0 } /* end of the 'extern "C"' block */ #endif #endif /* _SQLITE3RBU_H */ /************** End of sqlite3rbu.h ******************************************/ /************** Continuing where we left off in sqlite3rbu.c *****************/ #if defined(_WIN32_WCE) /* #include "windows.h" */ #endif /* Maximum number of prepared UPDATE statements held by this module */ #define SQLITE_RBU_UPDATE_CACHESIZE 16 /* ** Swap two objects of type TYPE. */ #if !defined(SQLITE_AMALGAMATION) # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} #endif /* ** The rbu_state table is used to save the state of a partially applied ** update so that it can be resumed later. The table consists of integer ** keys mapped to values as follows: ** ** RBU_STATE_STAGE: ** May be set to integer values 1, 2, 4 or 5. As follows: ** 1: the *-rbu file is currently under construction. ** 2: the *-rbu file has been constructed, but not yet moved ** to the *-wal path. ** 4: the checkpoint is underway. ** 5: the rbu update has been checkpointed. ** ** RBU_STATE_TBL: ** Only valid if STAGE==1. The target database name of the table ** currently being written. ** ** RBU_STATE_IDX: ** Only valid if STAGE==1. The target database name of the index ** currently being written, or NULL if the main table is currently being ** updated. ** ** RBU_STATE_ROW: ** Only valid if STAGE==1. Number of rows already processed for the current ** table/index. ** ** RBU_STATE_PROGRESS: ** Trbul number of sqlite3rbu_step() calls made so far as part of this ** rbu update. ** ** RBU_STATE_CKPT: ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index ** header created by recovering the *-wal file. This is used to detect ** cases when another client appends frames to the *-wal file in the ** middle of an incremental checkpoint (an incremental checkpoint cannot ** be continued if this happens). ** ** RBU_STATE_COOKIE: ** Valid if STAGE==1. The current change-counter cookie value in the ** target db file. ** ** RBU_STATE_OALSZ: ** Valid if STAGE==1. The size in bytes of the *-oal file. */ #define RBU_STATE_STAGE 1 #define RBU_STATE_TBL 2 #define RBU_STATE_IDX 3 #define RBU_STATE_ROW 4 #define RBU_STATE_PROGRESS 5 #define RBU_STATE_CKPT 6 #define RBU_STATE_COOKIE 7 #define RBU_STATE_OALSZ 8 #define RBU_STATE_PHASEONESTEP 9 #define RBU_STAGE_OAL 1 #define RBU_STAGE_MOVE 2 #define RBU_STAGE_CAPTURE 3 #define RBU_STAGE_CKPT 4 #define RBU_STAGE_DONE 5 #define RBU_CREATE_STATE \ "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)" typedef struct RbuFrame RbuFrame; typedef struct RbuObjIter RbuObjIter; typedef struct RbuState RbuState; typedef struct rbu_vfs rbu_vfs; typedef struct rbu_file rbu_file; typedef struct RbuUpdateStmt RbuUpdateStmt; #if !defined(SQLITE_AMALGAMATION) typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; typedef sqlite3_int64 i64; #endif /* ** These values must match the values defined in wal.c for the equivalent ** locks. These are not magic numbers as they are part of the SQLite file ** format. */ #define WAL_LOCK_WRITE 0 #define WAL_LOCK_CKPT 1 #define WAL_LOCK_READ0 3 #define SQLITE_FCNTL_RBUCNT 5149216 /* ** A structure to store values read from the rbu_state table in memory. */ struct RbuState { int eStage; char *zTbl; char *zIdx; i64 iWalCksum; int nRow; i64 nProgress; u32 iCookie; i64 iOalSz; i64 nPhaseOneStep; }; struct RbuUpdateStmt { char *zMask; /* Copy of update mask used with pUpdate */ sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */ RbuUpdateStmt *pNext; }; /* ** An iterator of this type is used to iterate through all objects in ** the target database that require updating. For each such table, the ** iterator visits, in order: ** ** * the table itself, ** * each index of the table (zero or more points to visit), and ** * a special "cleanup table" state. ** ** abIndexed: ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise, ** it points to an array of flags nTblCol elements in size. The flag is ** set for each column that is either a part of the PK or a part of an ** index. Or clear otherwise. ** */ struct RbuObjIter { sqlite3_stmt *pTblIter; /* Iterate through tables */ sqlite3_stmt *pIdxIter; /* Index iterator */ int nTblCol; /* Size of azTblCol[] array */ char **azTblCol; /* Array of unquoted target column names */ char **azTblType; /* Array of target column types */ int *aiSrcOrder; /* src table col -> target table col */ u8 *abTblPk; /* Array of flags, set on target PK columns */ u8 *abNotNull; /* Array of flags, set on NOT NULL columns */ u8 *abIndexed; /* Array of flags, set on indexed & PK cols */ int eType; /* Table type - an RBU_PK_XXX value */ /* Output variables. zTbl==0 implies EOF. */ int bCleanup; /* True in "cleanup" state */ const char *zTbl; /* Name of target db table */ const char *zDataTbl; /* Name of rbu db table (or null) */ const char *zIdx; /* Name of target db index (or null) */ int iTnum; /* Root page of current object */ int iPkTnum; /* If eType==EXTERNAL, root of PK index */ int bUnique; /* Current index is unique */ int nIndex; /* Number of aux. indexes on table zTbl */ /* Statements created by rbuObjIterPrepareAll() */ int nCol; /* Number of columns in current object */ sqlite3_stmt *pSelect; /* Source data */ sqlite3_stmt *pInsert; /* Statement for INSERT operations */ sqlite3_stmt *pDelete; /* Statement for DELETE ops */ sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */ /* Last UPDATE used (for PK b-tree updates only), or NULL. */ RbuUpdateStmt *pRbuUpdate; }; /* ** Values for RbuObjIter.eType ** ** 0: Table does not exist (error) ** 1: Table has an implicit rowid. ** 2: Table has an explicit IPK column. ** 3: Table has an external PK index. ** 4: Table is WITHOUT ROWID. ** 5: Table is a virtual table. */ #define RBU_PK_NOTABLE 0 #define RBU_PK_NONE 1 #define RBU_PK_IPK 2 #define RBU_PK_EXTERNAL 3 #define RBU_PK_WITHOUT_ROWID 4 #define RBU_PK_VTAB 5 /* ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs ** one of the following operations. */ #define RBU_INSERT 1 /* Insert on a main table b-tree */ #define RBU_DELETE 2 /* Delete a row from a main table b-tree */ #define RBU_REPLACE 3 /* Delete and then insert a row */ #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */ #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */ #define RBU_UPDATE 6 /* Update a row in a main table b-tree */ /* ** A single step of an incremental checkpoint - frame iWalFrame of the wal ** file should be copied to page iDbPage of the database file. */ struct RbuFrame { u32 iDbPage; u32 iWalFrame; }; /* ** RBU handle. ** ** nPhaseOneStep: ** If the RBU database contains an rbu_count table, this value is set to ** a running estimate of the number of b-tree operations required to ** finish populating the *-oal file. This allows the sqlite3_bp_progress() ** API to calculate the permyriadage progress of populating the *-oal file ** using the formula: ** ** permyriadage = (10000 * nProgress) / nPhaseOneStep ** ** nPhaseOneStep is initialized to the sum of: ** ** nRow * (nIndex + 1) ** ** for all source tables in the RBU database, where nRow is the number ** of rows in the source table and nIndex the number of indexes on the ** corresponding target database table. ** ** This estimate is accurate if the RBU update consists entirely of ** INSERT operations. However, it is inaccurate if: ** ** * the RBU update contains any UPDATE operations. If the PK specified ** for an UPDATE operation does not exist in the target table, then ** no b-tree operations are required on index b-trees. Or if the ** specified PK does exist, then (nIndex*2) such operations are ** required (one delete and one insert on each index b-tree). ** ** * the RBU update contains any DELETE operations for which the specified ** PK does not exist. In this case no operations are required on index ** b-trees. ** ** * the RBU update contains REPLACE operations. These are similar to ** UPDATE operations. ** ** nPhaseOneStep is updated to account for the conditions above during the ** first pass of each source table. The updated nPhaseOneStep value is ** stored in the rbu_state table if the RBU update is suspended. */ struct sqlite3rbu { int eStage; /* Value of RBU_STATE_STAGE field */ sqlite3 *dbMain; /* target database handle */ sqlite3 *dbRbu; /* rbu database handle */ char *zTarget; /* Path to target db */ char *zRbu; /* Path to rbu db */ char *zState; /* Path to state db (or NULL if zRbu) */ char zStateDb[5]; /* Db name for state ("stat" or "main") */ int rc; /* Value returned by last rbu_step() call */ char *zErrmsg; /* Error message if rc!=SQLITE_OK */ int nStep; /* Rows processed for current object */ int nProgress; /* Rows processed for all objects */ RbuObjIter objiter; /* Iterator for skipping through tbl/idx */ const char *zVfsName; /* Name of automatically created rbu vfs */ rbu_file *pTargetFd; /* File handle open on target db */ i64 iOalSz; i64 nPhaseOneStep; /* The following state variables are used as part of the incremental ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding ** function rbuSetupCheckpoint() for details. */ u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */ u32 mLock; int nFrame; /* Entries in aFrame[] array */ int nFrameAlloc; /* Allocated size of aFrame[] array */ RbuFrame *aFrame; int pgsz; u8 *aBuf; i64 iWalCksum; /* Used in RBU vacuum mode only */ int nRbu; /* Number of RBU VFS in the stack */ rbu_file *pRbuFd; /* Fd for main db of dbRbu */ }; /* ** An rbu VFS is implemented using an instance of this structure. */ struct rbu_vfs { sqlite3_vfs base; /* rbu VFS shim methods */ sqlite3_vfs *pRealVfs; /* Underlying VFS */ sqlite3_mutex *mutex; /* Mutex to protect pMain */ rbu_file *pMain; /* Linked list of main db files */ }; /* ** Each file opened by an rbu VFS is represented by an instance of ** the following structure. */ struct rbu_file { sqlite3_file base; /* sqlite3_file methods */ sqlite3_file *pReal; /* Underlying file handle */ rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */ sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */ int openFlags; /* Flags this file was opened with */ u32 iCookie; /* Cookie value for main db files */ u8 iWriteVer; /* "write-version" value for main db files */ u8 bNolock; /* True to fail EXCLUSIVE locks */ int nShm; /* Number of entries in apShm[] array */ char **apShm; /* Array of mmap'd *-shm regions */ char *zDel; /* Delete this when closing file */ const char *zWal; /* Wal filename for this main db file */ rbu_file *pWalFd; /* Wal file descriptor for this main db */ rbu_file *pMainNext; /* Next MAIN_DB file */ }; /* ** True for an RBU vacuum handle, or false otherwise. */ #define rbuIsVacuum(p) ((p)->zTarget==0) /************************************************************************* ** The following three functions, found below: ** ** rbuDeltaGetInt() ** rbuDeltaChecksum() ** rbuDeltaApply() ** ** are lifted from the fossil source code (http://fossil-scm.org). They ** are used to implement the scalar SQL function rbu_fossil_delta(). */ /* ** Read bytes from *pz and convert them into a positive integer. When ** finished, leave *pz pointing to the first character past the end of ** the integer. The *pLen parameter holds the length of the string ** in *pz and is decremented once for each character in the integer. */ static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){ static const signed char zValue[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1, }; unsigned int v = 0; int c; unsigned char *z = (unsigned char*)*pz; unsigned char *zStart = z; while( (c = zValue[0x7f&*(z++)])>=0 ){ v = (v<<6) + c; } z--; *pLen -= z - zStart; *pz = (char*)z; return v; } /* ** Compute a 32-bit checksum on the N-byte buffer. Return the result. */ static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){ const unsigned char *z = (const unsigned char *)zIn; unsigned sum0 = 0; unsigned sum1 = 0; unsigned sum2 = 0; unsigned sum3 = 0; while(N >= 16){ sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]); sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]); sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]); sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]); z += 16; N -= 16; } while(N >= 4){ sum0 += z[0]; sum1 += z[1]; sum2 += z[2]; sum3 += z[3]; z += 4; N -= 4; } sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24); switch(N){ case 3: sum3 += (z[2] << 8); case 2: sum3 += (z[1] << 16); case 1: sum3 += (z[0] << 24); default: ; } return sum3; } /* ** Apply a delta. ** ** The output buffer should be big enough to hold the whole output ** file and a NUL terminator at the end. The delta_output_size() ** routine will determine this size for you. ** ** The delta string should be null-terminated. But the delta string ** may contain embedded NUL characters (if the input and output are ** binary files) so we also have to pass in the length of the delta in ** the lenDelta parameter. ** ** This function returns the size of the output file in bytes (excluding ** the final NUL terminator character). Except, if the delta string is ** malformed or intended for use with a source file other than zSrc, ** then this routine returns -1. ** ** Refer to the delta_create() documentation above for a description ** of the delta file format. */ static int rbuDeltaApply( const char *zSrc, /* The source or pattern file */ int lenSrc, /* Length of the source file */ const char *zDelta, /* Delta to apply to the pattern */ int lenDelta, /* Length of the delta */ char *zOut /* Write the output into this preallocated buffer */ ){ unsigned int limit; unsigned int total = 0; #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST char *zOrigOut = zOut; #endif limit = rbuDeltaGetInt(&zDelta, &lenDelta); if( *zDelta!='\n' ){ /* ERROR: size integer not terminated by "\n" */ return -1; } zDelta++; lenDelta--; while( *zDelta && lenDelta>0 ){ unsigned int cnt, ofst; cnt = rbuDeltaGetInt(&zDelta, &lenDelta); switch( zDelta[0] ){ case '@': { zDelta++; lenDelta--; ofst = rbuDeltaGetInt(&zDelta, &lenDelta); if( lenDelta>0 && zDelta[0]!=',' ){ /* ERROR: copy command not terminated by ',' */ return -1; } zDelta++; lenDelta--; total += cnt; if( total>limit ){ /* ERROR: copy exceeds output file size */ return -1; } if( (int)(ofst+cnt) > lenSrc ){ /* ERROR: copy extends past end of input */ return -1; } memcpy(zOut, &zSrc[ofst], cnt); zOut += cnt; break; } case ':': { zDelta++; lenDelta--; total += cnt; if( total>limit ){ /* ERROR: insert command gives an output larger than predicted */ return -1; } if( (int)cnt>lenDelta ){ /* ERROR: insert count exceeds size of delta */ return -1; } memcpy(zOut, zDelta, cnt); zOut += cnt; zDelta += cnt; lenDelta -= cnt; break; } case ';': { zDelta++; lenDelta--; zOut[0] = 0; #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){ /* ERROR: bad checksum */ return -1; } #endif if( total!=limit ){ /* ERROR: generated size does not match predicted size */ return -1; } return total; } default: { /* ERROR: unknown delta operator */ return -1; } } } /* ERROR: unterminated delta */ return -1; } static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){ int size; size = rbuDeltaGetInt(&zDelta, &lenDelta); if( *zDelta!='\n' ){ /* ERROR: size integer not terminated by "\n" */ return -1; } return size; } /* ** End of code taken from fossil. *************************************************************************/ /* ** Implementation of SQL scalar function rbu_fossil_delta(). ** ** This function applies a fossil delta patch to a blob. Exactly two ** arguments must be passed to this function. The first is the blob to ** patch and the second the patch to apply. If no error occurs, this ** function returns the patched blob. */ static void rbuFossilDeltaFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *aDelta; int nDelta; const char *aOrig; int nOrig; int nOut; int nOut2; char *aOut; assert( argc==2 ); nOrig = sqlite3_value_bytes(argv[0]); aOrig = (const char*)sqlite3_value_blob(argv[0]); nDelta = sqlite3_value_bytes(argv[1]); aDelta = (const char*)sqlite3_value_blob(argv[1]); /* Figure out the size of the output */ nOut = rbuDeltaOutputSize(aDelta, nDelta); if( nOut<0 ){ sqlite3_result_error(context, "corrupt fossil delta", -1); return; } aOut = sqlite3_malloc(nOut+1); if( aOut==0 ){ sqlite3_result_error_nomem(context); }else{ nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut); if( nOut2!=nOut ){ sqlite3_result_error(context, "corrupt fossil delta", -1); }else{ sqlite3_result_blob(context, aOut, nOut, sqlite3_free); } } } /* ** Prepare the SQL statement in buffer zSql against database handle db. ** If successful, set *ppStmt to point to the new statement and return ** SQLITE_OK. ** ** Otherwise, if an error does occur, set *ppStmt to NULL and return ** an SQLite error code. Additionally, set output variable *pzErrmsg to ** point to a buffer containing an error message. It is the responsibility ** of the caller to (eventually) free this buffer using sqlite3_free(). */ static int prepareAndCollectError( sqlite3 *db, sqlite3_stmt **ppStmt, char **pzErrmsg, const char *zSql ){ int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); if( rc!=SQLITE_OK ){ *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); *ppStmt = 0; } return rc; } /* ** Reset the SQL statement passed as the first argument. Return a copy ** of the value returned by sqlite3_reset(). ** ** If an error has occurred, then set *pzErrmsg to point to a buffer ** containing an error message. It is the responsibility of the caller ** to eventually free this buffer using sqlite3_free(). */ static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){ int rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ){ *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt))); } return rc; } /* ** Unless it is NULL, argument zSql points to a buffer allocated using ** sqlite3_malloc containing an SQL statement. This function prepares the SQL ** statement against database db and frees the buffer. If statement ** compilation is successful, *ppStmt is set to point to the new statement ** handle and SQLITE_OK is returned. ** ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code ** returned. In this case, *pzErrmsg may also be set to point to an error ** message. It is the responsibility of the caller to free this error message ** buffer using sqlite3_free(). ** ** If argument zSql is NULL, this function assumes that an OOM has occurred. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL. */ static int prepareFreeAndCollectError( sqlite3 *db, sqlite3_stmt **ppStmt, char **pzErrmsg, char *zSql ){ int rc; assert( *pzErrmsg==0 ); if( zSql==0 ){ rc = SQLITE_NOMEM; *ppStmt = 0; }else{ rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql); sqlite3_free(zSql); } return rc; } /* ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated ** by an earlier call to rbuObjIterCacheTableInfo(). */ static void rbuObjIterFreeCols(RbuObjIter *pIter){ int i; for(i=0; i<pIter->nTblCol; i++){ sqlite3_free(pIter->azTblCol[i]); sqlite3_free(pIter->azTblType[i]); } sqlite3_free(pIter->azTblCol); pIter->azTblCol = 0; pIter->azTblType = 0; pIter->aiSrcOrder = 0; pIter->abTblPk = 0; pIter->abNotNull = 0; pIter->nTblCol = 0; pIter->eType = 0; /* Invalid value */ } /* ** Finalize all statements and free all allocations that are specific to ** the current object (table/index pair). */ static void rbuObjIterClearStatements(RbuObjIter *pIter){ RbuUpdateStmt *pUp; sqlite3_finalize(pIter->pSelect); sqlite3_finalize(pIter->pInsert); sqlite3_finalize(pIter->pDelete); sqlite3_finalize(pIter->pTmpInsert); pUp = pIter->pRbuUpdate; while( pUp ){ RbuUpdateStmt *pTmp = pUp->pNext; sqlite3_finalize(pUp->pUpdate); sqlite3_free(pUp); pUp = pTmp; } pIter->pSelect = 0; pIter->pInsert = 0; pIter->pDelete = 0; pIter->pRbuUpdate = 0; pIter->pTmpInsert = 0; pIter->nCol = 0; } /* ** Clean up any resources allocated as part of the iterator object passed ** as the only argument. */ static void rbuObjIterFinalize(RbuObjIter *pIter){ rbuObjIterClearStatements(pIter); sqlite3_finalize(pIter->pTblIter); sqlite3_finalize(pIter->pIdxIter); rbuObjIterFreeCols(pIter); memset(pIter, 0, sizeof(RbuObjIter)); } /* ** Advance the iterator to the next position. ** ** If no error occurs, SQLITE_OK is returned and the iterator is left ** pointing to the next entry. Otherwise, an error code and message is ** left in the RBU handle passed as the first argument. A copy of the ** error code is returned. */ static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){ int rc = p->rc; if( rc==SQLITE_OK ){ /* Free any SQLite statements used while processing the previous object */ rbuObjIterClearStatements(pIter); if( pIter->zIdx==0 ){ rc = sqlite3_exec(p->dbMain, "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;" "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;" "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;" "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;" , 0, 0, &p->zErrmsg ); } if( rc==SQLITE_OK ){ if( pIter->bCleanup ){ rbuObjIterFreeCols(pIter); pIter->bCleanup = 0; rc = sqlite3_step(pIter->pTblIter); if( rc!=SQLITE_ROW ){ rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg); pIter->zTbl = 0; }else{ pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0); pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1); rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM; } }else{ if( pIter->zIdx==0 ){ sqlite3_stmt *pIdx = pIter->pIdxIter; rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC); } if( rc==SQLITE_OK ){ rc = sqlite3_step(pIter->pIdxIter); if( rc!=SQLITE_ROW ){ rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg); pIter->bCleanup = 1; pIter->zIdx = 0; }else{ pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0); pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1); pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2); rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM; } } } } } if( rc!=SQLITE_OK ){ rbuObjIterFinalize(pIter); p->rc = rc; } return rc; } /* ** The implementation of the rbu_target_name() SQL function. This function ** accepts one or two arguments. The first argument is the name of a table - ** the name of a table in the RBU database. The second, if it is present, is 1 ** for a view or 0 for a table. ** ** For a non-vacuum RBU handle, if the table name matches the pattern: ** ** data[0-9]_<name> ** ** where <name> is any sequence of 1 or more characters, <name> is returned. ** Otherwise, if the only argument does not match the above pattern, an SQL ** NULL is returned. ** ** "data_t1" -> "t1" ** "data0123_t2" -> "t2" ** "dataAB_t3" -> NULL ** ** For an rbu vacuum handle, a copy of the first argument is returned if ** the second argument is either missing or 0 (not a view). */ static void rbuTargetNameFunc( sqlite3_context *pCtx, int argc, sqlite3_value **argv ){ sqlite3rbu *p = sqlite3_user_data(pCtx); const char *zIn; assert( argc==1 || argc==2 ); zIn = (const char*)sqlite3_value_text(argv[0]); if( zIn ){ if( rbuIsVacuum(p) ){ if( argc==1 || 0==sqlite3_value_int(argv[1]) ){ sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC); } }else{ if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){ int i; for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++); if( zIn[i]=='_' && zIn[i+1] ){ sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC); } } } } } /* ** Initialize the iterator structure passed as the second argument. ** ** If no error occurs, SQLITE_OK is returned and the iterator is left ** pointing to the first entry. Otherwise, an error code and message is ** left in the RBU handle passed as the first argument. A copy of the ** error code is returned. */ static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){ int rc; memset(pIter, 0, sizeof(RbuObjIter)); rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, sqlite3_mprintf( "SELECT rbu_target_name(name, type='view') AS target, name " "FROM sqlite_master " "WHERE type IN ('table', 'view') AND target IS NOT NULL " " %s " "ORDER BY name" , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : "")); if( rc==SQLITE_OK ){ rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg, "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' " " FROM main.sqlite_master " " WHERE type='index' AND tbl_name = ?" ); } pIter->bCleanup = 1; p->rc = rc; return rbuObjIterNext(p, pIter); } /* ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs, ** an error code is stored in the RBU handle passed as the first argument. ** ** If an error has already occurred (p->rc is already set to something other ** than SQLITE_OK), then this function returns NULL without modifying the ** stored error code. In this case it still calls sqlite3_free() on any ** printf() parameters associated with %z conversions. */ static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){ char *zSql = 0; va_list ap; va_start(ap, zFmt); zSql = sqlite3_vmprintf(zFmt, ap); if( p->rc==SQLITE_OK ){ if( zSql==0 ) p->rc = SQLITE_NOMEM; }else{ sqlite3_free(zSql); zSql = 0; } va_end(ap); return zSql; } /* ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing ** arguments are the usual subsitution values. This function performs ** the printf() style substitutions and executes the result as an SQL ** statement on the RBU handles database. ** ** If an error occurs, an error code and error message is stored in the ** RBU handle. If an error has already occurred when this function is ** called, it is a no-op. */ static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){ va_list ap; char *zSql; va_start(ap, zFmt); zSql = sqlite3_vmprintf(zFmt, ap); if( p->rc==SQLITE_OK ){ if( zSql==0 ){ p->rc = SQLITE_NOMEM; }else{ p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg); } } sqlite3_free(zSql); va_end(ap); return p->rc; } /* ** Attempt to allocate and return a pointer to a zeroed block of nByte ** bytes. ** ** If an error (i.e. an OOM condition) occurs, return NULL and leave an ** error code in the rbu handle passed as the first argument. Or, if an ** error has already occurred when this function is called, return NULL ** immediately without attempting the allocation or modifying the stored ** error code. */ static void *rbuMalloc(sqlite3rbu *p, int nByte){ void *pRet = 0; if( p->rc==SQLITE_OK ){ assert( nByte>0 ); pRet = sqlite3_malloc64(nByte); if( pRet==0 ){ p->rc = SQLITE_NOMEM; }else{ memset(pRet, 0, nByte); } } return pRet; } /* ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that ** there is room for at least nCol elements. If an OOM occurs, store an ** error code in the RBU handle passed as the first argument. */ static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){ int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol; char **azNew; azNew = (char**)rbuMalloc(p, nByte); if( azNew ){ pIter->azTblCol = azNew; pIter->azTblType = &azNew[nCol]; pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol]; pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol]; pIter->abNotNull = (u8*)&pIter->abTblPk[nCol]; pIter->abIndexed = (u8*)&pIter->abNotNull[nCol]; } } /* ** The first argument must be a nul-terminated string. This function ** returns a copy of the string in memory obtained from sqlite3_malloc(). ** It is the responsibility of the caller to eventually free this memory ** using sqlite3_free(). ** ** If an OOM condition is encountered when attempting to allocate memory, ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise, ** if the allocation succeeds, (*pRc) is left unchanged. */ static char *rbuStrndup(const char *zStr, int *pRc){ char *zRet = 0; assert( *pRc==SQLITE_OK ); if( zStr ){ size_t nCopy = strlen(zStr) + 1; zRet = (char*)sqlite3_malloc64(nCopy); if( zRet ){ memcpy(zRet, zStr, nCopy); }else{ *pRc = SQLITE_NOMEM; } } return zRet; } /* ** Finalize the statement passed as the second argument. ** ** If the sqlite3_finalize() call indicates that an error occurs, and the ** rbu handle error code is not already set, set the error code and error ** message accordingly. */ static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){ sqlite3 *db = sqlite3_db_handle(pStmt); int rc = sqlite3_finalize(pStmt); if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ p->rc = rc; p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); } } /* Determine the type of a table. ** ** peType is of type (int*), a pointer to an output parameter of type ** (int). This call sets the output parameter as follows, depending ** on the type of the table specified by parameters dbName and zTbl. ** ** RBU_PK_NOTABLE: No such table. ** RBU_PK_NONE: Table has an implicit rowid. ** RBU_PK_IPK: Table has an explicit IPK column. ** RBU_PK_EXTERNAL: Table has an external PK index. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID. ** RBU_PK_VTAB: Table is a virtual table. ** ** Argument *piPk is also of type (int*), and also points to an output ** parameter. Unless the table has an external primary key index ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or, ** if the table does have an external primary key index, then *piPk ** is set to the root page number of the primary key index before ** returning. ** ** ALGORITHM: ** ** if( no entry exists in sqlite_master ){ ** return RBU_PK_NOTABLE ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){ ** return RBU_PK_VTAB ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){ ** if( the index that is the pk exists in sqlite_master ){ ** *piPK = rootpage of that index. ** return RBU_PK_EXTERNAL ** }else{ ** return RBU_PK_WITHOUT_ROWID ** } ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){ ** return RBU_PK_IPK ** }else{ ** return RBU_PK_NONE ** } */ static void rbuTableType( sqlite3rbu *p, const char *zTab, int *peType, int *piTnum, int *piPk ){ /* ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q) ** 1) PRAGMA index_list = ? ** 2) SELECT count(*) FROM sqlite_master where name=%Q ** 3) PRAGMA table_info = ? */ sqlite3_stmt *aStmt[4] = {0, 0, 0, 0}; *peType = RBU_PK_NOTABLE; *piPk = 0; assert( p->rc==SQLITE_OK ); p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, sqlite3_mprintf( "SELECT (sql LIKE 'create virtual%%'), rootpage" " FROM sqlite_master" " WHERE name=%Q", zTab )); if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){ /* Either an error, or no such table. */ goto rbuTableType_end; } if( sqlite3_column_int(aStmt[0], 0) ){ *peType = RBU_PK_VTAB; /* virtual table */ goto rbuTableType_end; } *piTnum = sqlite3_column_int(aStmt[0], 1); p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, sqlite3_mprintf("PRAGMA index_list=%Q",zTab) ); if( p->rc ) goto rbuTableType_end; while( sqlite3_step(aStmt[1])==SQLITE_ROW ){ const u8 *zOrig = sqlite3_column_text(aStmt[1], 3); const u8 *zIdx = sqlite3_column_text(aStmt[1], 1); if( zOrig && zIdx && zOrig[0]=='p' ){ p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, sqlite3_mprintf( "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx )); if( p->rc==SQLITE_OK ){ if( sqlite3_step(aStmt[2])==SQLITE_ROW ){ *piPk = sqlite3_column_int(aStmt[2], 0); *peType = RBU_PK_EXTERNAL; }else{ *peType = RBU_PK_WITHOUT_ROWID; } } goto rbuTableType_end; } } p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, sqlite3_mprintf("PRAGMA table_info=%Q",zTab) ); if( p->rc==SQLITE_OK ){ while( sqlite3_step(aStmt[3])==SQLITE_ROW ){ if( sqlite3_column_int(aStmt[3],5)>0 ){ *peType = RBU_PK_IPK; /* explicit IPK column */ goto rbuTableType_end; } } *peType = RBU_PK_NONE; } rbuTableType_end: { unsigned int i; for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){ rbuFinalize(p, aStmt[i]); } } } /* ** This is a helper function for rbuObjIterCacheTableInfo(). It populates ** the pIter->abIndexed[] array. */ static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){ sqlite3_stmt *pList = 0; int bIndex = 0; if( p->rc==SQLITE_OK ){ memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol); p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) ); } pIter->nIndex = 0; while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){ const char *zIdx = (const char*)sqlite3_column_text(pList, 1); sqlite3_stmt *pXInfo = 0; if( zIdx==0 ) break; p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ int iCid = sqlite3_column_int(pXInfo, 1); if( iCid>=0 ) pIter->abIndexed[iCid] = 1; } rbuFinalize(p, pXInfo); bIndex = 1; pIter->nIndex++; } if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ /* "PRAGMA index_list" includes the main PK b-tree */ pIter->nIndex--; } rbuFinalize(p, pList); if( bIndex==0 ) pIter->abIndexed = 0; } /* ** If they are not already populated, populate the pIter->azTblCol[], ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to ** the table (not index) that the iterator currently points to. ** ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If ** an error does occur, an error code and error message are also left in ** the RBU handle. */ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ if( pIter->azTblCol==0 ){ sqlite3_stmt *pStmt = 0; int nCol = 0; int i; /* for() loop iterator variable */ int bRbuRowid = 0; /* If input table has column "rbu_rowid" */ int iOrder = 0; int iTnum = 0; /* Figure out the type of table this step will deal with. */ assert( pIter->eType==0 ); rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum); if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl); } if( p->rc ) return p->rc; if( pIter->zIdx==0 ) pIter->iTnum = iTnum; assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID || pIter->eType==RBU_PK_VTAB ); /* Populate the azTblCol[] and nTblCol variables based on the columns ** of the input table. Ignore any input table columns that begin with ** "rbu_". */ p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl) ); if( p->rc==SQLITE_OK ){ nCol = sqlite3_column_count(pStmt); rbuAllocateIterArrays(p, pIter, nCol); } for(i=0; p->rc==SQLITE_OK && i<nCol; i++){ const char *zName = (const char*)sqlite3_column_name(pStmt, i); if( sqlite3_strnicmp("rbu_", zName, 4) ){ char *zCopy = rbuStrndup(zName, &p->rc); pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol; pIter->azTblCol[pIter->nTblCol++] = zCopy; } else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){ bRbuRowid = 1; } } sqlite3_finalize(pStmt); pStmt = 0; if( p->rc==SQLITE_OK && rbuIsVacuum(p)==0 && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf( "table %q %s rbu_rowid column", pIter->zDataTbl, (bRbuRowid ? "may not have" : "requires") ); } /* Check that all non-HIDDEN columns in the destination table are also ** present in the input table. Populate the abTblPk[], azTblType[] and ** aiTblOrder[] arrays at the same time. */ if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl) ); } while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ const char *zName = (const char*)sqlite3_column_text(pStmt, 1); if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */ for(i=iOrder; i<pIter->nTblCol; i++){ if( 0==strcmp(zName, pIter->azTblCol[i]) ) break; } if( i==pIter->nTblCol ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("column missing from %q: %s", pIter->zDataTbl, zName ); }else{ int iPk = sqlite3_column_int(pStmt, 5); int bNotNull = sqlite3_column_int(pStmt, 3); const char *zType = (const char*)sqlite3_column_text(pStmt, 2); if( i!=iOrder ){ SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]); SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]); } pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc); pIter->abTblPk[iOrder] = (iPk!=0); pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0); iOrder++; } } rbuFinalize(p, pStmt); rbuObjIterCacheIndexedCols(p, pIter); assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 ); assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 ); } return p->rc; } /* ** This function constructs and returns a pointer to a nul-terminated ** string containing some SQL clause or list based on one or more of the ** column names currently stored in the pIter->azTblCol[] array. */ static char *rbuObjIterGetCollist( sqlite3rbu *p, /* RBU object */ RbuObjIter *pIter /* Object iterator for column names */ ){ char *zList = 0; const char *zSep = ""; int i; for(i=0; i<pIter->nTblCol; i++){ const char *z = pIter->azTblCol[i]; zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z); zSep = ", "; } return zList; } /* ** This function is used to create a SELECT list (the list of SQL ** expressions that follows a SELECT keyword) for a SELECT statement ** used to read from an data_xxx or rbu_tmp_xxx table while updating the ** index object currently indicated by the iterator object passed as the ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used ** to obtain the required information. ** ** If the index is of the following form: ** ** CREATE INDEX i1 ON t1(c, b COLLATE nocase); ** ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column ** "ipk", the returned string is: ** ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'" ** ** As well as the returned string, three other malloc'd strings are ** returned via output parameters. As follows: ** ** pzImposterCols: ... ** pzImposterPk: ... ** pzWhere: ... */ static char *rbuObjIterGetIndexCols( sqlite3rbu *p, /* RBU object */ RbuObjIter *pIter, /* Object iterator for column names */ char **pzImposterCols, /* OUT: Columns for imposter table */ char **pzImposterPk, /* OUT: Imposter PK clause */ char **pzWhere, /* OUT: WHERE clause */ int *pnBind /* OUT: Trbul number of columns */ ){ int rc = p->rc; /* Error code */ int rc2; /* sqlite3_finalize() return code */ char *zRet = 0; /* String to return */ char *zImpCols = 0; /* String to return via *pzImposterCols */ char *zImpPK = 0; /* String to return via *pzImposterPK */ char *zWhere = 0; /* String to return via *pzWhere */ int nBind = 0; /* Value to return via *pnBind */ const char *zCom = ""; /* Set to ", " later on */ const char *zAnd = ""; /* Set to " AND " later on */ sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */ if( rc==SQLITE_OK ){ assert( p->zErrmsg==0 ); rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) ); } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ int iCid = sqlite3_column_int(pXInfo, 1); int bDesc = sqlite3_column_int(pXInfo, 3); const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); const char *zCol; const char *zType; if( iCid<0 ){ /* An integer primary key. If the table has an explicit IPK, use ** its name. Otherwise, use "rbu_rowid". */ if( pIter->eType==RBU_PK_IPK ){ int i; for(i=0; pIter->abTblPk[i]==0; i++); assert( i<pIter->nTblCol ); zCol = pIter->azTblCol[i]; }else if( rbuIsVacuum(p) ){ zCol = "_rowid_"; }else{ zCol = "rbu_rowid"; } zType = "INTEGER"; }else{ zCol = pIter->azTblCol[iCid]; zType = pIter->azTblType[iCid]; } zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate); if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){ const char *zOrder = (bDesc ? " DESC" : ""); zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", zImpPK, zCom, nBind, zCol, zOrder ); } zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", zImpCols, zCom, nBind, zCol, zType, zCollate ); zWhere = sqlite3_mprintf( "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol ); if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM; zCom = ", "; zAnd = " AND "; nBind++; } rc2 = sqlite3_finalize(pXInfo); if( rc==SQLITE_OK ) rc = rc2; if( rc!=SQLITE_OK ){ sqlite3_free(zRet); sqlite3_free(zImpCols); sqlite3_free(zImpPK); sqlite3_free(zWhere); zRet = 0; zImpCols = 0; zImpPK = 0; zWhere = 0; p->rc = rc; } *pzImposterCols = zImpCols; *pzImposterPk = zImpPK; *pzWhere = zWhere; *pnBind = nBind; return zRet; } /* ** Assuming the current table columns are "a", "b" and "c", and the zObj ** paramter is passed "old", return a string of the form: ** ** "old.a, old.b, old.b" ** ** With the column names escaped. ** ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append ** the text ", old._rowid_" to the returned value. */ static char *rbuObjIterGetOldlist( sqlite3rbu *p, RbuObjIter *pIter, const char *zObj ){ char *zList = 0; if( p->rc==SQLITE_OK && pIter->abIndexed ){ const char *zS = ""; int i; for(i=0; i<pIter->nTblCol; i++){ if( pIter->abIndexed[i] ){ const char *zCol = pIter->azTblCol[i]; zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol); }else{ zList = sqlite3_mprintf("%z%sNULL", zList, zS); } zS = ", "; if( zList==0 ){ p->rc = SQLITE_NOMEM; break; } } /* For a table with implicit rowids, append "old._rowid_" to the list. */ if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj); } } return zList; } /* ** Return an expression that can be used in a WHERE clause to match the ** primary key of the current table. For example, if the table is: ** ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c)); ** ** Return the string: ** ** "b = ?1 AND c = ?2" */ static char *rbuObjIterGetWhere( sqlite3rbu *p, RbuObjIter *pIter ){ char *zList = 0; if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){ zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1); }else if( pIter->eType==RBU_PK_EXTERNAL ){ const char *zSep = ""; int i; for(i=0; i<pIter->nTblCol; i++){ if( pIter->abTblPk[i] ){ zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1); zSep = " AND "; } } zList = rbuMPrintf(p, "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList ); }else{ const char *zSep = ""; int i; for(i=0; i<pIter->nTblCol; i++){ if( pIter->abTblPk[i] ){ const char *zCol = pIter->azTblCol[i]; zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1); zSep = " AND "; } } } return zList; } /* ** The SELECT statement iterating through the keys for the current object ** (p->objiter.pSelect) currently points to a valid row. However, there ** is something wrong with the rbu_control value in the rbu_control value ** stored in the (p->nCol+1)'th column. Set the error code and error message ** of the RBU handle to something reflecting this. */ static void rbuBadControlError(sqlite3rbu *p){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("invalid rbu_control value"); } /* ** Return a nul-terminated string containing the comma separated list of ** assignments that should be included following the "SET" keyword of ** an UPDATE statement used to update the table object that the iterator ** passed as the second argument currently points to if the rbu_control ** column of the data_xxx table entry is set to zMask. ** ** The memory for the returned string is obtained from sqlite3_malloc(). ** It is the responsibility of the caller to eventually free it using ** sqlite3_free(). ** ** If an OOM error is encountered when allocating space for the new ** string, an error code is left in the rbu handle passed as the first ** argument and NULL is returned. Or, if an error has already occurred ** when this function is called, NULL is returned immediately, without ** attempting the allocation or modifying the stored error code. */ static char *rbuObjIterGetSetlist( sqlite3rbu *p, RbuObjIter *pIter, const char *zMask ){ char *zList = 0; if( p->rc==SQLITE_OK ){ int i; if( (int)strlen(zMask)!=pIter->nTblCol ){ rbuBadControlError(p); }else{ const char *zSep = ""; for(i=0; i<pIter->nTblCol; i++){ char c = zMask[pIter->aiSrcOrder[i]]; if( c=='x' ){ zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, pIter->azTblCol[i], i+1 ); zSep = ", "; } else if( c=='d' ){ zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 ); zSep = ", "; } else if( c=='f' ){ zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 ); zSep = ", "; } } } } return zList; } /* ** Return a nul-terminated string consisting of nByte comma separated ** "?" expressions. For example, if nByte is 3, return a pointer to ** a buffer containing the string "?,?,?". ** ** The memory for the returned string is obtained from sqlite3_malloc(). ** It is the responsibility of the caller to eventually free it using ** sqlite3_free(). ** ** If an OOM error is encountered when allocating space for the new ** string, an error code is left in the rbu handle passed as the first ** argument and NULL is returned. Or, if an error has already occurred ** when this function is called, NULL is returned immediately, without ** attempting the allocation or modifying the stored error code. */ static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){ char *zRet = 0; int nByte = nBind*2 + 1; zRet = (char*)rbuMalloc(p, nByte); if( zRet ){ int i; for(i=0; i<nBind; i++){ zRet[i*2] = '?'; zRet[i*2+1] = (i+1==nBind) ? '\0' : ','; } } return zRet; } /* ** The iterator currently points to a table (not index) of type ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY ** declaration for the corresponding imposter table. For example, ** if the iterator points to a table created as: ** ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID ** ** this function returns: ** ** PRIMARY KEY("b", "a" DESC) */ static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){ char *z = 0; assert( pIter->zIdx==0 ); if( p->rc==SQLITE_OK ){ const char *zSep = "PRIMARY KEY("; sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */ sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */ p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) ); while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){ const char *zOrig = (const char*)sqlite3_column_text(pXList,3); if( zOrig && strcmp(zOrig, "pk")==0 ){ const char *zIdx = (const char*)sqlite3_column_text(pXList,1); if( zIdx ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); } break; } } rbuFinalize(p, pXList); while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ if( sqlite3_column_int(pXInfo, 5) ){ /* int iCid = sqlite3_column_int(pXInfo, 0); */ const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2); const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : ""; z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc); zSep = ", "; } } z = rbuMPrintf(p, "%z)", z); rbuFinalize(p, pXInfo); } return z; } /* ** This function creates the second imposter table used when writing to ** a table b-tree where the table has an external primary key. If the ** iterator passed as the second argument does not currently point to ** a table (not index) with an external primary key, this function is a ** no-op. ** ** Assuming the iterator does point to a table with an external PK, this ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2" ** used to access that PK index. For example, if the target table is ** declared as follows: ** ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c)); ** ** then the imposter table schema is: ** ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID; ** */ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){ int tnum = pIter->iPkTnum; /* Root page of PK index */ sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */ const char *zIdx = 0; /* Name of PK index */ sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */ const char *zComma = ""; char *zCols = 0; /* Used to build up list of table cols */ char *zPk = 0; /* Used to build up table PK declaration */ /* Figure out the name of the primary key index for the current table. ** This is needed for the argument to "PRAGMA index_xinfo". Set ** zIdx to point to a nul-terminated string containing this name. */ p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, "SELECT name FROM sqlite_master WHERE rootpage = ?" ); if( p->rc==SQLITE_OK ){ sqlite3_bind_int(pQuery, 1, tnum); if( SQLITE_ROW==sqlite3_step(pQuery) ){ zIdx = (const char*)sqlite3_column_text(pQuery, 0); } } if( zIdx ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); } rbuFinalize(p, pQuery); while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ int bKey = sqlite3_column_int(pXInfo, 5); if( bKey ){ int iCid = sqlite3_column_int(pXInfo, 1); int bDesc = sqlite3_column_int(pXInfo, 3); const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma, iCid, pIter->azTblType[iCid], zCollate ); zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":""); zComma = ", "; } } zCols = rbuMPrintf(p, "%z, id INTEGER", zCols); rbuFinalize(p, pXInfo); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", zCols, zPk ); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); } } /* ** If an error has already occurred when this function is called, it ** immediately returns zero (without doing any work). Or, if an error ** occurs during the execution of this function, it sets the error code ** in the sqlite3rbu object indicated by the first argument and returns ** zero. ** ** The iterator passed as the second argument is guaranteed to point to ** a table (not an index) when this function is called. This function ** attempts to create any imposter table required to write to the main ** table b-tree of the table before returning. Non-zero is returned if ** an imposter table are created, or zero otherwise. ** ** An imposter table is required in all cases except RBU_PK_VTAB. Only ** virtual tables are written to directly. The imposter table has the ** same schema as the actual target table (less any UNIQUE constraints). ** More precisely, the "same schema" means the same columns, types, ** collation sequences. For tables that do not have an external PRIMARY ** KEY, it also means the same PRIMARY KEY declaration. */ static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){ int tnum = pIter->iTnum; const char *zComma = ""; char *zSql = 0; int iCol; sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){ const char *zPk = ""; const char *zCol = pIter->azTblCol[iCol]; const char *zColl = 0; p->rc = sqlite3_table_column_metadata( p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0 ); if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){ /* If the target table column is an "INTEGER PRIMARY KEY", add ** "PRIMARY KEY" to the imposter table column declaration. */ zPk = "PRIMARY KEY "; } zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s", zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl, (pIter->abNotNull[iCol] ? " NOT NULL" : "") ); zComma = ", "; } if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ char *zPk = rbuWithoutRowidPK(p, pIter); if( zPk ){ zSql = rbuMPrintf(p, "%z, %z", zSql, zPk); } } sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", pIter->zTbl, zSql, (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "") ); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); } } /* ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table. ** Specifically a statement of the form: ** ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...); ** ** The number of bound variables is equal to the number of columns in ** the target table, plus one (for the rbu_control column), plus one more ** (for the rbu_rowid column) if the target table is an implicit IPK or ** virtual table. */ static void rbuObjIterPrepareTmpInsert( sqlite3rbu *p, RbuObjIter *pIter, const char *zCollist, const char *zRbuRowid ){ int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE); char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid); if( zBind ){ assert( pIter->pTmpInsert==0 ); p->rc = prepareFreeAndCollectError( p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf( "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind )); } } static void rbuTmpInsertFunc( sqlite3_context *pCtx, int nVal, sqlite3_value **apVal ){ sqlite3rbu *p = sqlite3_user_data(pCtx); int rc = SQLITE_OK; int i; assert( sqlite3_value_int(apVal[0])!=0 || p->objiter.eType==RBU_PK_EXTERNAL || p->objiter.eType==RBU_PK_NONE ); if( sqlite3_value_int(apVal[0])!=0 ){ p->nPhaseOneStep += p->objiter.nIndex; } for(i=0; rc==SQLITE_OK && i<nVal; i++){ rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]); } if( rc==SQLITE_OK ){ sqlite3_step(p->objiter.pTmpInsert); rc = sqlite3_reset(p->objiter.pTmpInsert); } if( rc!=SQLITE_OK ){ sqlite3_result_error_code(pCtx, rc); } } /* ** Ensure that the SQLite statement handles required to update the ** target database object currently indicated by the iterator passed ** as the second argument are available. */ static int rbuObjIterPrepareAll( sqlite3rbu *p, RbuObjIter *pIter, int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */ ){ assert( pIter->bCleanup==0 ); if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){ const int tnum = pIter->iTnum; char *zCollist = 0; /* List of indexed columns */ char **pz = &p->zErrmsg; const char *zIdx = pIter->zIdx; char *zLimit = 0; if( nOffset ){ zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset); if( !zLimit ) p->rc = SQLITE_NOMEM; } if( zIdx ){ const char *zTbl = pIter->zTbl; char *zImposterCols = 0; /* Columns for imposter table */ char *zImposterPK = 0; /* Primary key declaration for imposter */ char *zWhere = 0; /* WHERE clause on PK columns */ char *zBind = 0; int nBind = 0; assert( pIter->eType!=RBU_PK_VTAB ); zCollist = rbuObjIterGetIndexCols( p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind ); zBind = rbuObjIterGetBindlist(p, nBind); /* Create the imposter table used to write to this index. */ sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID", zTbl, zImposterCols, zImposterPK ); sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); /* Create the statement to insert index entries */ pIter->nCol = nBind; if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError( p->dbMain, &pIter->pInsert, &p->zErrmsg, sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind) ); } /* And to delete index entries */ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError( p->dbMain, &pIter->pDelete, &p->zErrmsg, sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere) ); } /* Create the SELECT statement to read keys in sorted order */ if( p->rc==SQLITE_OK ){ char *zSql; if( rbuIsVacuum(p) ){ zSql = sqlite3_mprintf( "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s", zCollist, pIter->zDataTbl, zCollist, zLimit ); }else if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ zSql = sqlite3_mprintf( "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s", zCollist, p->zStateDb, pIter->zDataTbl, zCollist, zLimit ); }else{ zSql = sqlite3_mprintf( "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' " "UNION ALL " "SELECT %s, rbu_control FROM '%q' " "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 " "ORDER BY %s%s", zCollist, p->zStateDb, pIter->zDataTbl, zCollist, pIter->zDataTbl, zCollist, zLimit ); } p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql); } sqlite3_free(zImposterCols); sqlite3_free(zImposterPK); sqlite3_free(zWhere); sqlite3_free(zBind); }else{ int bRbuRowid = (pIter->eType==RBU_PK_VTAB) ||(pIter->eType==RBU_PK_NONE) ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)); const char *zTbl = pIter->zTbl; /* Table this step applies to */ const char *zWrite; /* Imposter table name */ char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid); char *zWhere = rbuObjIterGetWhere(p, pIter); char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old"); char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new"); zCollist = rbuObjIterGetCollist(p, pIter); pIter->nCol = pIter->nTblCol; /* Create the imposter table or tables (if required). */ rbuCreateImposterTable(p, pIter); rbuCreateImposterTable2(p, pIter); zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_"); /* Create the INSERT statement to write to the target PK b-tree */ if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz, sqlite3_mprintf( "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings ) ); } /* Create the DELETE statement to write to the target PK b-tree. ** Because it only performs INSERT operations, this is not required for ** an rbu vacuum handle. */ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz, sqlite3_mprintf( "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere ) ); } if( rbuIsVacuum(p)==0 && pIter->abIndexed ){ const char *zRbuRowid = ""; if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ zRbuRowid = ", rbu_rowid"; } /* Create the rbu_tmp_xxx table and the triggers to populate it. */ rbuMPrintfExec(p, p->dbRbu, "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS " "SELECT *%s FROM '%q' WHERE 0;" , p->zStateDb, pIter->zDataTbl , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "") , pIter->zDataTbl ); rbuMPrintfExec(p, p->dbMain, "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" " "BEGIN " " SELECT rbu_tmp_insert(3, %s);" "END;" "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" " "BEGIN " " SELECT rbu_tmp_insert(3, %s);" "END;" "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" " "BEGIN " " SELECT rbu_tmp_insert(4, %s);" "END;", zWrite, zTbl, zOldlist, zWrite, zTbl, zOldlist, zWrite, zTbl, zNewlist ); if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ rbuMPrintfExec(p, p->dbMain, "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" " "BEGIN " " SELECT rbu_tmp_insert(0, %s);" "END;", zWrite, zTbl, zNewlist ); } rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid); } /* Create the SELECT statement to read keys from data_xxx */ if( p->rc==SQLITE_OK ){ const char *zRbuRowid = ""; if( bRbuRowid ){ zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid"; } p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, sqlite3_mprintf( "SELECT %s,%s rbu_control%s FROM '%q'%s", zCollist, (rbuIsVacuum(p) ? "0 AS " : ""), zRbuRowid, pIter->zDataTbl, zLimit ) ); } sqlite3_free(zWhere); sqlite3_free(zOldlist); sqlite3_free(zNewlist); sqlite3_free(zBindings); } sqlite3_free(zCollist); sqlite3_free(zLimit); } return p->rc; } /* ** Set output variable *ppStmt to point to an UPDATE statement that may ** be used to update the imposter table for the main table b-tree of the ** table object that pIter currently points to, assuming that the ** rbu_control column of the data_xyz table contains zMask. ** ** If the zMask string does not specify any columns to update, then this ** is not an error. Output variable *ppStmt is set to NULL in this case. */ static int rbuGetUpdateStmt( sqlite3rbu *p, /* RBU handle */ RbuObjIter *pIter, /* Object iterator */ const char *zMask, /* rbu_control value ('x.x.') */ sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */ ){ RbuUpdateStmt **pp; RbuUpdateStmt *pUp = 0; int nUp = 0; /* In case an error occurs */ *ppStmt = 0; /* Search for an existing statement. If one is found, shift it to the front ** of the LRU queue and return immediately. Otherwise, leave nUp pointing ** to the number of statements currently in the cache and pUp to the ** last object in the list. */ for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){ pUp = *pp; if( strcmp(pUp->zMask, zMask)==0 ){ *pp = pUp->pNext; pUp->pNext = pIter->pRbuUpdate; pIter->pRbuUpdate = pUp; *ppStmt = pUp->pUpdate; return SQLITE_OK; } nUp++; } assert( pUp==0 || pUp->pNext==0 ); if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){ for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext)); *pp = 0; sqlite3_finalize(pUp->pUpdate); pUp->pUpdate = 0; }else{ pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1); } if( pUp ){ char *zWhere = rbuObjIterGetWhere(p, pIter); char *zSet = rbuObjIterGetSetlist(p, pIter, zMask); char *zUpdate = 0; pUp->zMask = (char*)&pUp[1]; memcpy(pUp->zMask, zMask, pIter->nTblCol); pUp->pNext = pIter->pRbuUpdate; pIter->pRbuUpdate = pUp; if( zSet ){ const char *zPrefix = ""; if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_"; zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", zPrefix, pIter->zTbl, zSet, zWhere ); p->rc = prepareFreeAndCollectError( p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate ); *ppStmt = pUp->pUpdate; } sqlite3_free(zWhere); sqlite3_free(zSet); } return p->rc; } static sqlite3 *rbuOpenDbhandle( sqlite3rbu *p, const char *zName, int bUseVfs ){ sqlite3 *db = 0; if( p->rc==SQLITE_OK ){ const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI; p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0); if( p->rc ){ p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); sqlite3_close(db); db = 0; } } return db; } /* ** Free an RbuState object allocated by rbuLoadState(). */ static void rbuFreeState(RbuState *p){ if( p ){ sqlite3_free(p->zTbl); sqlite3_free(p->zIdx); sqlite3_free(p); } } /* ** Allocate an RbuState object and load the contents of the rbu_state ** table into it. Return a pointer to the new object. It is the ** responsibility of the caller to eventually free the object using ** sqlite3_free(). ** ** If an error occurs, leave an error code and message in the rbu handle ** and return NULL. */ static RbuState *rbuLoadState(sqlite3rbu *p){ RbuState *pRet = 0; sqlite3_stmt *pStmt = 0; int rc; int rc2; pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState)); if( pRet==0 ) return 0; rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb) ); while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ switch( sqlite3_column_int(pStmt, 0) ){ case RBU_STATE_STAGE: pRet->eStage = sqlite3_column_int(pStmt, 1); if( pRet->eStage!=RBU_STAGE_OAL && pRet->eStage!=RBU_STAGE_MOVE && pRet->eStage!=RBU_STAGE_CKPT ){ p->rc = SQLITE_CORRUPT; } break; case RBU_STATE_TBL: pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); break; case RBU_STATE_IDX: pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); break; case RBU_STATE_ROW: pRet->nRow = sqlite3_column_int(pStmt, 1); break; case RBU_STATE_PROGRESS: pRet->nProgress = sqlite3_column_int64(pStmt, 1); break; case RBU_STATE_CKPT: pRet->iWalCksum = sqlite3_column_int64(pStmt, 1); break; case RBU_STATE_COOKIE: pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1); break; case RBU_STATE_OALSZ: pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1); break; case RBU_STATE_PHASEONESTEP: pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1); break; default: rc = SQLITE_CORRUPT; break; } } rc2 = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ) rc = rc2; p->rc = rc; return pRet; } /* ** Open the database handle and attach the RBU database as "rbu". If an ** error occurs, leave an error code and message in the RBU handle. */ static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){ assert( p->rc || (p->dbMain==0 && p->dbRbu==0) ); assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 ); /* Open the RBU database */ p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1); if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); if( p->zState==0 ){ const char *zFile = sqlite3_db_filename(p->dbRbu, "main"); p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile); } } /* If using separate RBU and state databases, attach the state database to ** the RBU db handle now. */ if( p->zState ){ rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState); memcpy(p->zStateDb, "stat", 4); }else{ memcpy(p->zStateDb, "main", 4); } #if 0 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0); } #endif /* If it has not already been created, create the rbu_state table */ rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb); #if 0 if( rbuIsVacuum(p) ){ if( p->rc==SQLITE_OK ){ int rc2; int bOk = 0; sqlite3_stmt *pCnt = 0; p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg, "SELECT count(*) FROM stat.sqlite_master" ); if( p->rc==SQLITE_OK && sqlite3_step(pCnt)==SQLITE_ROW && 1==sqlite3_column_int(pCnt, 0) ){ bOk = 1; } rc2 = sqlite3_finalize(pCnt); if( p->rc==SQLITE_OK ) p->rc = rc2; if( p->rc==SQLITE_OK && bOk==0 ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("invalid state database"); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); } } } #endif if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ int bOpen = 0; int rc; p->nRbu = 0; p->pRbuFd = 0; rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); if( rc!=SQLITE_NOTFOUND ) p->rc = rc; if( p->eStage>=RBU_STAGE_MOVE ){ bOpen = 1; }else{ RbuState *pState = rbuLoadState(p); if( pState ){ bOpen = (pState->eStage>=RBU_STAGE_MOVE); rbuFreeState(pState); } } if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1); } p->eStage = 0; if( p->rc==SQLITE_OK && p->dbMain==0 ){ if( !rbuIsVacuum(p) ){ p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1); }else if( p->pRbuFd->pWalFd ){ if( pbRetry ){ p->pRbuFd->bNolock = 0; sqlite3_close(p->dbRbu); sqlite3_close(p->dbMain); p->dbMain = 0; p->dbRbu = 0; *pbRetry = 1; return; } p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database"); }else{ char *zTarget; char *zExtra = 0; if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){ zExtra = &p->zRbu[5]; while( *zExtra ){ if( *zExtra++=='?' ) break; } if( *zExtra=='\0' ) zExtra = 0; } zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s", sqlite3_db_filename(p->dbRbu, "main"), (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra) ); if( zTarget==0 ){ p->rc = SQLITE_NOMEM; return; } p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1); sqlite3_free(zTarget); } } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_create_function(p->dbMain, "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_create_function(p->dbMain, "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_create_function(p->dbRbu, "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); } rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master"); /* Mark the database file just opened as an RBU target database. If ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use. ** This is an error. */ if( p->rc==SQLITE_OK ){ p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); } if( p->rc==SQLITE_NOTFOUND ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("rbu vfs not found"); } } /* ** This routine is a copy of the sqlite3FileSuffix3() routine from the core. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined. ** ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than ** three characters, then shorten the suffix on z[] to be the last three ** characters of the original suffix. ** ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always ** do the suffix shortening regardless of URI parameter. ** ** Examples: ** ** test.db-journal => test.nal ** test.db-wal => test.wal ** test.db-shm => test.shm ** test.db-mj7f3319fa => test.9fa */ static void rbuFileSuffix3(const char *zBase, char *z){ #ifdef SQLITE_ENABLE_8_3_NAMES #if SQLITE_ENABLE_8_3_NAMES<2 if( sqlite3_uri_boolean(zBase, "8_3_names", 0) ) #endif { int i, sz; sz = (int)strlen(z)&0xffffff; for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4); } #endif } /* ** Return the current wal-index header checksum for the target database ** as a 64-bit integer. ** ** The checksum is store in the first page of xShmMap memory as an 8-byte ** blob starting at byte offset 40. */ static i64 rbuShmChecksum(sqlite3rbu *p){ i64 iRet = 0; if( p->rc==SQLITE_OK ){ sqlite3_file *pDb = p->pTargetFd->pReal; u32 volatile *ptr; p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr); if( p->rc==SQLITE_OK ){ iRet = ((i64)ptr[10] << 32) + ptr[11]; } } return iRet; } /* ** This function is called as part of initializing or reinitializing an ** incremental checkpoint. ** ** It populates the sqlite3rbu.aFrame[] array with the set of ** (wal frame -> db page) copy operations required to checkpoint the ** current wal file, and obtains the set of shm locks required to safely ** perform the copy operations directly on the file-system. ** ** If argument pState is not NULL, then the incremental checkpoint is ** being resumed. In this case, if the checksum of the wal-index-header ** following recovery is not the same as the checksum saved in the RbuState ** object, then the rbu handle is set to DONE state. This occurs if some ** other client appends a transaction to the wal file in the middle of ** an incremental checkpoint. */ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ /* If pState is NULL, then the wal file may not have been opened and ** recovered. Running a read-statement here to ensure that doing so ** does not interfere with the "capture" process below. */ if( pState==0 ){ p->eStage = 0; if( p->rc==SQLITE_OK ){ p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0); } } /* Assuming no error has occurred, run a "restart" checkpoint with the ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following ** special behaviour in the rbu VFS: ** ** * If the exclusive shm WRITER or READ0 lock cannot be obtained, ** the checkpoint fails with SQLITE_BUSY (normally SQLite would ** proceed with running a passive checkpoint instead of failing). ** ** * Attempts to read from the *-wal file or write to the database file ** do not perform any IO. Instead, the frame/page combinations that ** would be read/written are recorded in the sqlite3rbu.aFrame[] ** array. ** ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, ** READ0 and CHECKPOINT locks taken as part of the checkpoint are ** no-ops. These locks will not be released until the connection ** is closed. ** ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL ** error. ** ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[] ** array populated with a set of (frame -> page) mappings. Because the ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy ** data from the wal file into the database file according to the ** contents of aFrame[]. */ if( p->rc==SQLITE_OK ){ int rc2; p->eStage = RBU_STAGE_CAPTURE; rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0); if( rc2!=SQLITE_INTERNAL ) p->rc = rc2; } if( p->rc==SQLITE_OK && p->nFrame>0 ){ p->eStage = RBU_STAGE_CKPT; p->nStep = (pState ? pState->nRow : 0); p->aBuf = rbuMalloc(p, p->pgsz); p->iWalCksum = rbuShmChecksum(p); } if( p->rc==SQLITE_OK ){ if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){ p->rc = SQLITE_DONE; p->eStage = RBU_STAGE_DONE; } } } /* ** Called when iAmt bytes are read from offset iOff of the wal file while ** the rbu object is in capture mode. Record the frame number of the frame ** being read in the aFrame[] array. */ static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){ const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0); u32 iFrame; if( pRbu->mLock!=mReq ){ pRbu->rc = SQLITE_BUSY; return SQLITE_INTERNAL; } pRbu->pgsz = iAmt; if( pRbu->nFrame==pRbu->nFrameAlloc ){ int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2; RbuFrame *aNew; aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame)); if( aNew==0 ) return SQLITE_NOMEM; pRbu->aFrame = aNew; pRbu->nFrameAlloc = nNew; } iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1; if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame; pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame; pRbu->aFrame[pRbu->nFrame].iDbPage = 0; pRbu->nFrame++; return SQLITE_OK; } /* ** Called when a page of data is written to offset iOff of the database ** file while the rbu handle is in capture mode. Record the page number ** of the page being written in the aFrame[] array. */ static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){ pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1; return SQLITE_OK; } /* ** This is called as part of an incremental checkpoint operation. Copy ** a single frame of data from the wal file into the database file, as ** indicated by the RbuFrame object. */ static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){ sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal; sqlite3_file *pDb = p->pTargetFd->pReal; i64 iOff; assert( p->rc==SQLITE_OK ); iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24; p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff); if( p->rc ) return; iOff = (i64)(pFrame->iDbPage-1) * p->pgsz; p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff); } /* ** Take an EXCLUSIVE lock on the database file. */ static void rbuLockDatabase(sqlite3rbu *p){ sqlite3_file *pReal = p->pTargetFd->pReal; assert( p->rc==SQLITE_OK ); p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED); if( p->rc==SQLITE_OK ){ p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE); } } #if defined(_WIN32_WCE) static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){ int nChar; LPWSTR zWideFilename; nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0); if( nChar==0 ){ return 0; } zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) ); if( zWideFilename==0 ){ return 0; } memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0])); nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar); if( nChar==0 ){ sqlite3_free(zWideFilename); zWideFilename = 0; } return zWideFilename; } #endif /* ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock ** on the database file. This proc moves the *-oal file to the *-wal path, ** then reopens the database file (this time in vanilla, non-oal, WAL mode). ** If an error occurs, leave an error code and error message in the rbu ** handle. */ static void rbuMoveOalFile(sqlite3rbu *p){ const char *zBase = sqlite3_db_filename(p->dbMain, "main"); const char *zMove = zBase; char *zOal; char *zWal; if( rbuIsVacuum(p) ){ zMove = sqlite3_db_filename(p->dbRbu, "main"); } zOal = sqlite3_mprintf("%s-oal", zMove); zWal = sqlite3_mprintf("%s-wal", zMove); assert( p->eStage==RBU_STAGE_MOVE ); assert( p->rc==SQLITE_OK && p->zErrmsg==0 ); if( zWal==0 || zOal==0 ){ p->rc = SQLITE_NOMEM; }else{ /* Move the *-oal file to *-wal. At this point connection p->db is ** holding a SHARED lock on the target database file (because it is ** in WAL mode). So no other connection may be writing the db. ** ** In order to ensure that there are no database readers, an EXCLUSIVE ** lock is obtained here before the *-oal is moved to *-wal. */ rbuLockDatabase(p); if( p->rc==SQLITE_OK ){ rbuFileSuffix3(zBase, zWal); rbuFileSuffix3(zBase, zOal); /* Re-open the databases. */ rbuObjIterFinalize(&p->objiter); sqlite3_close(p->dbRbu); sqlite3_close(p->dbMain); p->dbMain = 0; p->dbRbu = 0; #if defined(_WIN32_WCE) { LPWSTR zWideOal; LPWSTR zWideWal; zWideOal = rbuWinUtf8ToUnicode(zOal); if( zWideOal ){ zWideWal = rbuWinUtf8ToUnicode(zWal); if( zWideWal ){ if( MoveFileW(zWideOal, zWideWal) ){ p->rc = SQLITE_OK; }else{ p->rc = SQLITE_IOERR; } sqlite3_free(zWideWal); }else{ p->rc = SQLITE_IOERR_NOMEM; } sqlite3_free(zWideOal); }else{ p->rc = SQLITE_IOERR_NOMEM; } } #else p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK; #endif if( p->rc==SQLITE_OK ){ rbuOpenDatabase(p, 0); rbuSetupCheckpoint(p, 0); } } } sqlite3_free(zWal); sqlite3_free(zOal); } /* ** The SELECT statement iterating through the keys for the current object ** (p->objiter.pSelect) currently points to a valid row. This function ** determines the type of operation requested by this row and returns ** one of the following values to indicate the result: ** ** * RBU_INSERT ** * RBU_DELETE ** * RBU_IDX_DELETE ** * RBU_UPDATE ** ** If RBU_UPDATE is returned, then output variable *pzMask is set to ** point to the text value indicating the columns to update. ** ** If the rbu_control field contains an invalid value, an error code and ** message are left in the RBU handle and zero returned. */ static int rbuStepType(sqlite3rbu *p, const char **pzMask){ int iCol = p->objiter.nCol; /* Index of rbu_control column */ int res = 0; /* Return value */ switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){ case SQLITE_INTEGER: { int iVal = sqlite3_column_int(p->objiter.pSelect, iCol); switch( iVal ){ case 0: res = RBU_INSERT; break; case 1: res = RBU_DELETE; break; case 2: res = RBU_REPLACE; break; case 3: res = RBU_IDX_DELETE; break; case 4: res = RBU_IDX_INSERT; break; } break; } case SQLITE_TEXT: { const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol); if( z==0 ){ p->rc = SQLITE_NOMEM; }else{ *pzMask = (const char*)z; } res = RBU_UPDATE; break; } default: break; } if( res==0 ){ rbuBadControlError(p); } return res; } #ifdef SQLITE_DEBUG /* ** Assert that column iCol of statement pStmt is named zName. */ static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){ const char *zCol = sqlite3_column_name(pStmt, iCol); assert( 0==sqlite3_stricmp(zName, zCol) ); } #else # define assertColumnName(x,y,z) #endif /* ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or ** RBU_IDX_DELETE. This function performs the work of a single ** sqlite3rbu_step() call for the type of operation specified by eType. */ static void rbuStepOneOp(sqlite3rbu *p, int eType){ RbuObjIter *pIter = &p->objiter; sqlite3_value *pVal; sqlite3_stmt *pWriter; int i; assert( p->rc==SQLITE_OK ); assert( eType!=RBU_DELETE || pIter->zIdx==0 ); assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE || eType==RBU_INSERT || eType==RBU_IDX_INSERT ); /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE ** statement below does actually delete a row, nPhaseOneStep will be ** incremented by the same amount when SQL function rbu_tmp_insert() ** is invoked by the trigger. */ if( eType==RBU_DELETE ){ p->nPhaseOneStep -= p->objiter.nIndex; } if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){ pWriter = pIter->pDelete; }else{ pWriter = pIter->pInsert; } for(i=0; i<pIter->nCol; i++){ /* If this is an INSERT into a table b-tree and the table has an ** explicit INTEGER PRIMARY KEY, check that this is not an attempt ** to write a NULL into the IPK column. That is not permitted. */ if( eType==RBU_INSERT && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i] && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL ){ p->rc = SQLITE_MISMATCH; p->zErrmsg = sqlite3_mprintf("datatype mismatch"); return; } if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){ continue; } pVal = sqlite3_column_value(pIter->pSelect, i); p->rc = sqlite3_bind_value(pWriter, i+1, pVal); if( p->rc ) return; } if( pIter->zIdx==0 ){ if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)) ){ /* For a virtual table, or a table with no primary key, the ** SELECT statement is: ** ** SELECT <cols>, rbu_control, rbu_rowid FROM .... ** ** Hence column_value(pIter->nCol+1). */ assertColumnName(pIter->pSelect, pIter->nCol+1, rbuIsVacuum(p) ? "rowid" : "rbu_rowid" ); pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1); p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal); } } if( p->rc==SQLITE_OK ){ sqlite3_step(pWriter); p->rc = resetAndCollectError(pWriter, &p->zErrmsg); } } /* ** This function does the work for an sqlite3rbu_step() call. ** ** The object-iterator (p->objiter) currently points to a valid object, ** and the input cursor (p->objiter.pSelect) currently points to a valid ** input row. Perform whatever processing is required and return. ** ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code ** and message is left in the RBU handle and a copy of the error code ** returned. */ static int rbuStep(sqlite3rbu *p){ RbuObjIter *pIter = &p->objiter; const char *zMask = 0; int eType = rbuStepType(p, &zMask); if( eType ){ assert( eType==RBU_INSERT || eType==RBU_DELETE || eType==RBU_REPLACE || eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT || eType==RBU_UPDATE ); assert( eType!=RBU_UPDATE || pIter->zIdx==0 ); if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){ rbuBadControlError(p); } else if( eType==RBU_REPLACE ){ if( pIter->zIdx==0 ){ p->nPhaseOneStep += p->objiter.nIndex; rbuStepOneOp(p, RBU_DELETE); } if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT); } else if( eType!=RBU_UPDATE ){ rbuStepOneOp(p, eType); } else{ sqlite3_value *pVal; sqlite3_stmt *pUpdate = 0; assert( eType==RBU_UPDATE ); p->nPhaseOneStep -= p->objiter.nIndex; rbuGetUpdateStmt(p, pIter, zMask, &pUpdate); if( pUpdate ){ int i; for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){ char c = zMask[pIter->aiSrcOrder[i]]; pVal = sqlite3_column_value(pIter->pSelect, i); if( pIter->abTblPk[i] || c!='.' ){ p->rc = sqlite3_bind_value(pUpdate, i+1, pVal); } } if( p->rc==SQLITE_OK && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) ){ /* Bind the rbu_rowid value to column _rowid_ */ assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid"); pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1); p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal); } if( p->rc==SQLITE_OK ){ sqlite3_step(pUpdate); p->rc = resetAndCollectError(pUpdate, &p->zErrmsg); } } } } return p->rc; } /* ** Increment the schema cookie of the main database opened by p->dbMain. ** ** Or, if this is an RBU vacuum, set the schema cookie of the main db ** opened by p->dbMain to one more than the schema cookie of the main ** db opened by p->dbRbu. */ static void rbuIncrSchemaCookie(sqlite3rbu *p){ if( p->rc==SQLITE_OK ){ sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain); int iCookie = 1000000; sqlite3_stmt *pStmt; p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg, "PRAGMA schema_version" ); if( p->rc==SQLITE_OK ){ /* Coverage: it may be that this sqlite3_step() cannot fail. There ** is already a transaction open, so the prepared statement cannot ** throw an SQLITE_SCHEMA exception. The only database page the ** statement reads is page 1, which is guaranteed to be in the cache. ** And no memory allocations are required. */ if( SQLITE_ROW==sqlite3_step(pStmt) ){ iCookie = sqlite3_column_int(pStmt, 0); } rbuFinalize(p, pStmt); } if( p->rc==SQLITE_OK ){ rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1); } } } /* ** Update the contents of the rbu_state table within the rbu database. The ** value stored in the RBU_STATE_STAGE column is eStage. All other values ** are determined by inspecting the rbu handle passed as the first argument. */ static void rbuSaveState(sqlite3rbu *p, int eStage){ if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){ sqlite3_stmt *pInsert = 0; rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd); int rc; assert( p->zErrmsg==0 ); rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg, sqlite3_mprintf( "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES " "(%d, %d), " "(%d, %Q), " "(%d, %Q), " "(%d, %d), " "(%d, %d), " "(%d, %lld), " "(%d, %lld), " "(%d, %lld), " "(%d, %lld) ", p->zStateDb, RBU_STATE_STAGE, eStage, RBU_STATE_TBL, p->objiter.zTbl, RBU_STATE_IDX, p->objiter.zIdx, RBU_STATE_ROW, p->nStep, RBU_STATE_PROGRESS, p->nProgress, RBU_STATE_CKPT, p->iWalCksum, RBU_STATE_COOKIE, (i64)pFd->iCookie, RBU_STATE_OALSZ, p->iOalSz, RBU_STATE_PHASEONESTEP, p->nPhaseOneStep ) ); assert( pInsert==0 || rc==SQLITE_OK ); if( rc==SQLITE_OK ){ sqlite3_step(pInsert); rc = sqlite3_finalize(pInsert); } if( rc!=SQLITE_OK ) p->rc = rc; } } /* ** The second argument passed to this function is the name of a PRAGMA ** setting - "page_size", "auto_vacuum", "user_version" or "application_id". ** This function executes the following on sqlite3rbu.dbRbu: ** ** "PRAGMA main.$zPragma" ** ** where $zPragma is the string passed as the second argument, then ** on sqlite3rbu.dbMain: ** ** "PRAGMA main.$zPragma = $val" ** ** where $val is the value returned by the first PRAGMA invocation. ** ** In short, it copies the value of the specified PRAGMA setting from ** dbRbu to dbMain. */ static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){ if( p->rc==SQLITE_OK ){ sqlite3_stmt *pPragma = 0; p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg, sqlite3_mprintf("PRAGMA main.%s", zPragma) ); if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){ p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d", zPragma, sqlite3_column_int(pPragma, 0) ); } rbuFinalize(p, pPragma); } } /* ** The RBU handle passed as the only argument has just been opened and ** the state database is empty. If this RBU handle was opened for an ** RBU vacuum operation, create the schema in the target db. */ static void rbuCreateTargetSchema(sqlite3rbu *p){ sqlite3_stmt *pSql = 0; sqlite3_stmt *pInsert = 0; assert( rbuIsVacuum(p) ); p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg); if( p->rc==SQLITE_OK ){ p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0" " AND name!='sqlite_sequence' " " ORDER BY type DESC" ); } while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){ const char *zSql = (const char*)sqlite3_column_text(pSql, 0); p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg); } rbuFinalize(p, pSql); if( p->rc!=SQLITE_OK ) return; if( p->rc==SQLITE_OK ){ p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL" ); } if( p->rc==SQLITE_OK ){ p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg, "INSERT INTO sqlite_master VALUES(?,?,?,?,?)" ); } while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){ int i; for(i=0; i<5; i++){ sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i)); } sqlite3_step(pInsert); p->rc = sqlite3_reset(pInsert); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg); } rbuFinalize(p, pSql); rbuFinalize(p, pInsert); } /* ** Step the RBU object. */ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){ if( p ){ switch( p->eStage ){ case RBU_STAGE_OAL: { RbuObjIter *pIter = &p->objiter; /* If this is an RBU vacuum operation and the state table was empty ** when this handle was opened, create the target database schema. */ if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){ rbuCreateTargetSchema(p); rbuCopyPragma(p, "user_version"); rbuCopyPragma(p, "application_id"); } while( p->rc==SQLITE_OK && pIter->zTbl ){ if( pIter->bCleanup ){ /* Clean up the rbu_tmp_xxx table for the previous table. It ** cannot be dropped as there are currently active SQL statements. ** But the contents can be deleted. */ if( rbuIsVacuum(p)==0 && pIter->abIndexed ){ rbuMPrintfExec(p, p->dbRbu, "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl ); } }else{ rbuObjIterPrepareAll(p, pIter, 0); /* Advance to the next row to process. */ if( p->rc==SQLITE_OK ){ int rc = sqlite3_step(pIter->pSelect); if( rc==SQLITE_ROW ){ p->nProgress++; p->nStep++; return rbuStep(p); } p->rc = sqlite3_reset(pIter->pSelect); p->nStep = 0; } } rbuObjIterNext(p, pIter); } if( p->rc==SQLITE_OK ){ assert( pIter->zTbl==0 ); rbuSaveState(p, RBU_STAGE_MOVE); rbuIncrSchemaCookie(p); if( p->rc==SQLITE_OK ){ p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg); } if( p->rc==SQLITE_OK ){ p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg); } p->eStage = RBU_STAGE_MOVE; } break; } case RBU_STAGE_MOVE: { if( p->rc==SQLITE_OK ){ rbuMoveOalFile(p); p->nProgress++; } break; } case RBU_STAGE_CKPT: { if( p->rc==SQLITE_OK ){ if( p->nStep>=p->nFrame ){ sqlite3_file *pDb = p->pTargetFd->pReal; /* Sync the db file */ p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL); /* Update nBackfill */ if( p->rc==SQLITE_OK ){ void volatile *ptr; p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr); if( p->rc==SQLITE_OK ){ ((u32 volatile*)ptr)[24] = p->iMaxFrame; } } if( p->rc==SQLITE_OK ){ p->eStage = RBU_STAGE_DONE; p->rc = SQLITE_DONE; } }else{ RbuFrame *pFrame = &p->aFrame[p->nStep]; rbuCheckpointFrame(p, pFrame); p->nStep++; } p->nProgress++; } break; } default: break; } return p->rc; }else{ return SQLITE_NOMEM; } } /* ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero ** otherwise. Either or both argument may be NULL. Two NULL values are ** considered equal, and NULL is considered distinct from all other values. */ static int rbuStrCompare(const char *z1, const char *z2){ if( z1==0 && z2==0 ) return 0; if( z1==0 || z2==0 ) return 1; return (sqlite3_stricmp(z1, z2)!=0); } /* ** This function is called as part of sqlite3rbu_open() when initializing ** an rbu handle in OAL stage. If the rbu update has not started (i.e. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges ** things so that the next call to sqlite3rbu_step() continues on from ** where the previous rbu handle left off. ** ** If an error occurs, an error code and error message are left in the ** rbu handle passed as the first argument. */ static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){ assert( p->rc==SQLITE_OK ); if( pState->zTbl ){ RbuObjIter *pIter = &p->objiter; int rc = SQLITE_OK; while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup || rbuStrCompare(pIter->zIdx, pState->zIdx) || rbuStrCompare(pIter->zTbl, pState->zTbl) )){ rc = rbuObjIterNext(p, pIter); } if( rc==SQLITE_OK && !pIter->zTbl ){ rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error"); } if( rc==SQLITE_OK ){ p->nStep = pState->nRow; rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep); } p->rc = rc; } } /* ** If there is a "*-oal" file in the file-system corresponding to the ** target database in the file-system, delete it. If an error occurs, ** leave an error code and error message in the rbu handle. */ static void rbuDeleteOalFile(sqlite3rbu *p){ char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget); if( zOal ){ sqlite3_vfs *pVfs = sqlite3_vfs_find(0); assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 ); pVfs->xDelete(pVfs, zOal, 0); sqlite3_free(zOal); } } /* ** Allocate a private rbu VFS for the rbu handle passed as the only ** argument. This VFS will be used unless the call to sqlite3rbu_open() ** specified a URI with a vfs=? option in place of a target database ** file name. */ static void rbuCreateVfs(sqlite3rbu *p){ int rnd; char zRnd[64]; assert( p->rc==SQLITE_OK ); sqlite3_randomness(sizeof(int), (void*)&rnd); sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd); p->rc = sqlite3rbu_create_vfs(zRnd, 0); if( p->rc==SQLITE_OK ){ sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd); assert( pVfs ); p->zVfsName = pVfs->zName; } } /* ** Destroy the private VFS created for the rbu handle passed as the only ** argument by an earlier call to rbuCreateVfs(). */ static void rbuDeleteVfs(sqlite3rbu *p){ if( p->zVfsName ){ sqlite3rbu_destroy_vfs(p->zVfsName); p->zVfsName = 0; } } /* ** This user-defined SQL function is invoked with a single argument - the ** name of a table expected to appear in the target database. It returns ** the number of auxilliary indexes on the table. */ static void rbuIndexCntFunc( sqlite3_context *pCtx, int nVal, sqlite3_value **apVal ){ sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx); sqlite3_stmt *pStmt = 0; char *zErrmsg = 0; int rc; assert( nVal==1 ); rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg, sqlite3_mprintf("SELECT count(*) FROM sqlite_master " "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0])) ); if( rc!=SQLITE_OK ){ sqlite3_result_error(pCtx, zErrmsg, -1); }else{ int nIndex = 0; if( SQLITE_ROW==sqlite3_step(pStmt) ){ nIndex = sqlite3_column_int(pStmt, 0); } rc = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ){ sqlite3_result_int(pCtx, nIndex); }else{ sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1); } } sqlite3_free(zErrmsg); } /* ** If the RBU database contains the rbu_count table, use it to initialize ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table ** is assumed to contain the same columns as: ** ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID; ** ** There should be one row in the table for each data_xxx table in the ** database. The 'tbl' column should contain the name of a data_xxx table, ** and the cnt column the number of rows it contains. ** ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt ** for all rows in the rbu_count table, where nIndex is the number of ** indexes on the corresponding target database table. */ static void rbuInitPhaseOneSteps(sqlite3rbu *p){ if( p->rc==SQLITE_OK ){ sqlite3_stmt *pStmt = 0; int bExists = 0; /* True if rbu_count exists */ p->nPhaseOneStep = -1; p->rc = sqlite3_create_function(p->dbRbu, "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0 ); /* Check for the rbu_count table. If it does not exist, or if an error ** occurs, nPhaseOneStep will be left set to -1. */ if( p->rc==SQLITE_OK ){ p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'" ); } if( p->rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pStmt) ){ bExists = 1; } p->rc = sqlite3_finalize(pStmt); } if( p->rc==SQLITE_OK && bExists ){ p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))" "FROM rbu_count" ); if( p->rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pStmt) ){ p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0); } p->rc = sqlite3_finalize(pStmt); } } } } static sqlite3rbu *openRbuHandle( const char *zTarget, const char *zRbu, const char *zState ){ sqlite3rbu *p; size_t nTarget = zTarget ? strlen(zTarget) : 0; size_t nRbu = strlen(zRbu); size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1; p = (sqlite3rbu*)sqlite3_malloc64(nByte); if( p ){ RbuState *pState = 0; /* Create the custom VFS. */ memset(p, 0, sizeof(sqlite3rbu)); rbuCreateVfs(p); /* Open the target, RBU and state databases */ if( p->rc==SQLITE_OK ){ char *pCsr = (char*)&p[1]; int bRetry = 0; if( zTarget ){ p->zTarget = pCsr; memcpy(p->zTarget, zTarget, nTarget+1); pCsr += nTarget+1; } p->zRbu = pCsr; memcpy(p->zRbu, zRbu, nRbu+1); pCsr += nRbu+1; if( zState ){ p->zState = rbuMPrintf(p, "%s", zState); } /* If the first attempt to open the database file fails and the bRetry ** flag it set, this means that the db was not opened because it seemed ** to be a wal-mode db. But, this may have happened due to an earlier ** RBU vacuum operation leaving an old wal file in the directory. ** If this is the case, it will have been checkpointed and deleted ** when the handle was closed and a second attempt to open the ** database may succeed. */ rbuOpenDatabase(p, &bRetry); if( bRetry ){ rbuOpenDatabase(p, 0); } } if( p->rc==SQLITE_OK ){ pState = rbuLoadState(p); assert( pState || p->rc!=SQLITE_OK ); if( p->rc==SQLITE_OK ){ if( pState->eStage==0 ){ rbuDeleteOalFile(p); rbuInitPhaseOneSteps(p); p->eStage = RBU_STAGE_OAL; }else{ p->eStage = pState->eStage; p->nPhaseOneStep = pState->nPhaseOneStep; } p->nProgress = pState->nProgress; p->iOalSz = pState->iOalSz; } } assert( p->rc!=SQLITE_OK || p->eStage!=0 ); if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){ if( p->eStage==RBU_STAGE_OAL ){ p->rc = SQLITE_ERROR; p->zErrmsg = sqlite3_mprintf("cannot update wal mode database"); }else if( p->eStage==RBU_STAGE_MOVE ){ p->eStage = RBU_STAGE_CKPT; p->nStep = 0; } } if( p->rc==SQLITE_OK && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE) && pState->eStage!=0 ){ rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd); if( pFd->iCookie!=pState->iCookie ){ /* At this point (pTargetFd->iCookie) contains the value of the ** change-counter cookie (the thing that gets incremented when a ** transaction is committed in rollback mode) currently stored on ** page 1 of the database file. */ p->rc = SQLITE_BUSY; p->zErrmsg = sqlite3_mprintf("database modified during rbu %s", (rbuIsVacuum(p) ? "vacuum" : "update") ); } } if( p->rc==SQLITE_OK ){ if( p->eStage==RBU_STAGE_OAL ){ sqlite3 *db = p->dbMain; p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg); /* Point the object iterator at the first object */ if( p->rc==SQLITE_OK ){ p->rc = rbuObjIterFirst(p, &p->objiter); } /* If the RBU database contains no data_xxx tables, declare the RBU ** update finished. */ if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){ p->rc = SQLITE_DONE; p->eStage = RBU_STAGE_DONE; }else{ if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){ rbuCopyPragma(p, "page_size"); rbuCopyPragma(p, "auto_vacuum"); } /* Open transactions both databases. The *-oal file is opened or ** created at this point. */ if( p->rc==SQLITE_OK ){ p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg); } /* Check if the main database is a zipvfs db. If it is, set the upper ** level pager to use "journal_mode=off". This prevents it from ** generating a large journal using a temp file. */ if( p->rc==SQLITE_OK ){ int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0); if( frc==SQLITE_OK ){ p->rc = sqlite3_exec( db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg); } } if( p->rc==SQLITE_OK ){ rbuSetupOal(p, pState); } } }else if( p->eStage==RBU_STAGE_MOVE ){ /* no-op */ }else if( p->eStage==RBU_STAGE_CKPT ){ rbuSetupCheckpoint(p, pState); }else if( p->eStage==RBU_STAGE_DONE ){ p->rc = SQLITE_DONE; }else{ p->rc = SQLITE_CORRUPT; } } rbuFreeState(pState); } return p; } /* ** Allocate and return an RBU handle with all fields zeroed except for the ** error code, which is set to SQLITE_MISUSE. */ static sqlite3rbu *rbuMisuseError(void){ sqlite3rbu *pRet; pRet = sqlite3_malloc64(sizeof(sqlite3rbu)); if( pRet ){ memset(pRet, 0, sizeof(sqlite3rbu)); pRet->rc = SQLITE_MISUSE; } return pRet; } /* ** Open and return a new RBU handle. */ SQLITE_API sqlite3rbu *sqlite3rbu_open( const char *zTarget, const char *zRbu, const char *zState ){ if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); } /* TODO: Check that zTarget and zRbu are non-NULL */ return openRbuHandle(zTarget, zRbu, zState); } /* ** Open a handle to begin or resume an RBU VACUUM operation. */ SQLITE_API sqlite3rbu *sqlite3rbu_vacuum( const char *zTarget, const char *zState ){ if( zTarget==0 ){ return rbuMisuseError(); } /* TODO: Check that both arguments are non-NULL */ return openRbuHandle(0, zTarget, zState); } /* ** Return the database handle used by pRbu. */ SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){ sqlite3 *db = 0; if( pRbu ){ db = (bRbu ? pRbu->dbRbu : pRbu->dbMain); } return db; } /* ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT, ** then edit any error message string so as to remove all occurrences of ** the pattern "rbu_imp_[0-9]*". */ static void rbuEditErrmsg(sqlite3rbu *p){ if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){ unsigned int i; size_t nErrmsg = strlen(p->zErrmsg); for(i=0; i<(nErrmsg-8); i++){ if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){ int nDel = 8; while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++; memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel); nErrmsg -= nDel; } } } } /* ** Close the RBU handle. */ SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){ int rc; if( p ){ /* Commit the transaction to the *-oal file. */ if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){ p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg); } rbuSaveState(p, p->eStage); if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){ p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg); } /* Close any open statement handles. */ rbuObjIterFinalize(&p->objiter); /* If this is an RBU vacuum handle and the vacuum has either finished ** successfully or encountered an error, delete the contents of the ** state table. This causes the next call to sqlite3rbu_vacuum() ** specifying the current target and state databases to start a new ** vacuum from scratch. */ if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){ int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0); if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2; } /* Close the open database handle and VFS object. */ sqlite3_close(p->dbRbu); sqlite3_close(p->dbMain); rbuDeleteVfs(p); sqlite3_free(p->aBuf); sqlite3_free(p->aFrame); rbuEditErrmsg(p); rc = p->rc; *pzErrmsg = p->zErrmsg; sqlite3_free(p->zState); sqlite3_free(p); }else{ rc = SQLITE_NOMEM; *pzErrmsg = 0; } return rc; } /* ** Return the total number of key-value operations (inserts, deletes or ** updates) that have been performed on the target database since the ** current RBU update was started. */ SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){ return pRbu->nProgress; } /* ** Return permyriadage progress indications for the two main stages of ** an RBU update. */ SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){ const int MAX_PROGRESS = 10000; switch( p->eStage ){ case RBU_STAGE_OAL: if( p->nPhaseOneStep>0 ){ *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep); }else{ *pnOne = -1; } *pnTwo = 0; break; case RBU_STAGE_MOVE: *pnOne = MAX_PROGRESS; *pnTwo = 0; break; case RBU_STAGE_CKPT: *pnOne = MAX_PROGRESS; *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame); break; case RBU_STAGE_DONE: *pnOne = MAX_PROGRESS; *pnTwo = MAX_PROGRESS; break; default: assert( 0 ); } } /* ** Return the current state of the RBU vacuum or update operation. */ SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){ int aRes[] = { 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE, 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE }; assert( RBU_STAGE_OAL==1 ); assert( RBU_STAGE_MOVE==2 ); assert( RBU_STAGE_CKPT==4 ); assert( RBU_STAGE_DONE==5 ); assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL ); assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE ); assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT ); assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE ); if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){ return SQLITE_RBU_STATE_ERROR; }else{ assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE ); assert( p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE || p->eStage==RBU_STAGE_CKPT || p->eStage==RBU_STAGE_DONE ); return aRes[p->eStage]; } } SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){ int rc = p->rc; if( rc==SQLITE_DONE ) return SQLITE_OK; assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE ); if( p->eStage==RBU_STAGE_OAL ){ assert( rc!=SQLITE_DONE ); if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0); } p->rc = rc; rbuSaveState(p, p->eStage); rc = p->rc; if( p->eStage==RBU_STAGE_OAL ){ assert( rc!=SQLITE_DONE ); if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0); if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0); } p->rc = rc; return rc; } /************************************************************************** ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour ** of a standard VFS in the following ways: ** ** 1. Whenever the first page of a main database file is read or ** written, the value of the change-counter cookie is stored in ** rbu_file.iCookie. Similarly, the value of the "write-version" ** database header field is stored in rbu_file.iWriteVer. This ensures ** that the values are always trustworthy within an open transaction. ** ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd) ** member variable of the associated database file descriptor is set ** to point to the new file. A mutex protected linked list of all main ** db fds opened using a particular RBU VFS is maintained at ** rbu_vfs.pMain to facilitate this. ** ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file ** object can be marked as the target database of an RBU update. This ** turns on the following extra special behaviour: ** ** 3a. If xAccess() is called to check if there exists a *-wal file ** associated with an RBU target database currently in RBU_STAGE_OAL ** stage (preparing the *-oal file), the following special handling ** applies: ** ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU ** target database may not be in wal mode already. ** ** * if the *-wal file does not exist, set the output parameter to ** non-zero (to tell SQLite that it does exist) anyway. ** ** Then, when xOpen() is called to open the *-wal file associated with ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal ** file, the rbu vfs opens the corresponding *-oal file instead. ** ** 3b. The *-shm pages returned by xShmMap() for a target db file in ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls ** are no-ops on target database files in RBU_STAGE_OAL mode. This is ** because assert() statements in some VFS implementations fail if ** xShmLock() is called before xShmMap(). ** ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it ** fails with an SQLITE_BUSY error. This is to stop RBU connections ** from automatically checkpointing a *-wal (or *-oal) file from within ** sqlite3_close(). ** ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and ** all xWrite() calls on the target database file perform no IO. ** Instead the frame and page numbers that would be read and written ** are recorded. Additionally, successful attempts to obtain exclusive ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target ** database file are recorded. xShmLock() calls to unlock the same ** locks are no-ops (so that once obtained, these locks are never ** relinquished). Finally, calls to xSync() on the target database ** file fail with SQLITE_INTERNAL errors. */ static void rbuUnlockShm(rbu_file *p){ if( p->pRbu ){ int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock; int i; for(i=0; i<SQLITE_SHM_NLOCK;i++){ if( (1<<i) & p->pRbu->mLock ){ xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE); } } p->pRbu->mLock = 0; } } /* ** Close an rbu file. */ static int rbuVfsClose(sqlite3_file *pFile){ rbu_file *p = (rbu_file*)pFile; int rc; int i; /* Free the contents of the apShm[] array. And the array itself. */ for(i=0; i<p->nShm; i++){ sqlite3_free(p->apShm[i]); } sqlite3_free(p->apShm); p->apShm = 0; sqlite3_free(p->zDel); if( p->openFlags & SQLITE_OPEN_MAIN_DB ){ rbu_file **pp; sqlite3_mutex_enter(p->pRbuVfs->mutex); for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext)); *pp = p->pMainNext; sqlite3_mutex_leave(p->pRbuVfs->mutex); rbuUnlockShm(p); p->pReal->pMethods->xShmUnmap(p->pReal, 0); } /* Close the underlying file handle */ rc = p->pReal->pMethods->xClose(p->pReal); return rc; } /* ** Read and return an unsigned 32-bit big-endian integer from the buffer ** passed as the only argument. */ static u32 rbuGetU32(u8 *aBuf){ return ((u32)aBuf[0] << 24) + ((u32)aBuf[1] << 16) + ((u32)aBuf[2] << 8) + ((u32)aBuf[3]); } /* ** Write an unsigned 32-bit value in big-endian format to the supplied ** buffer. */ static void rbuPutU32(u8 *aBuf, u32 iVal){ aBuf[0] = (iVal >> 24) & 0xFF; aBuf[1] = (iVal >> 16) & 0xFF; aBuf[2] = (iVal >> 8) & 0xFF; aBuf[3] = (iVal >> 0) & 0xFF; } static void rbuPutU16(u8 *aBuf, u16 iVal){ aBuf[0] = (iVal >> 8) & 0xFF; aBuf[1] = (iVal >> 0) & 0xFF; } /* ** Read data from an rbuVfs-file. */ static int rbuVfsRead( sqlite3_file *pFile, void *zBuf, int iAmt, sqlite_int64 iOfst ){ rbu_file *p = (rbu_file*)pFile; sqlite3rbu *pRbu = p->pRbu; int rc; if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){ assert( p->openFlags & SQLITE_OPEN_WAL ); rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt); }else{ if( pRbu && pRbu->eStage==RBU_STAGE_OAL && (p->openFlags & SQLITE_OPEN_WAL) && iOfst>=pRbu->iOalSz ){ rc = SQLITE_OK; memset(zBuf, 0, iAmt); }else{ rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); #if 1 /* If this is being called to read the first page of the target ** database as part of an rbu vacuum operation, synthesize the ** contents of the first page if it does not yet exist. Otherwise, ** SQLite will not check for a *-wal file. */ if( pRbu && rbuIsVacuum(pRbu) && rc==SQLITE_IOERR_SHORT_READ && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) && pRbu->rc==SQLITE_OK ){ sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd; rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst); if( rc==SQLITE_OK ){ u8 *aBuf = (u8*)zBuf; u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0; rbuPutU32(&aBuf[52], iRoot); /* largest root page number */ rbuPutU32(&aBuf[36], 0); /* number of free pages */ rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */ rbuPutU32(&aBuf[28], 1); /* size of db file in pages */ rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */ if( iAmt>100 ){ memset(&aBuf[100], 0, iAmt-100); rbuPutU16(&aBuf[105], iAmt & 0xFFFF); aBuf[100] = 0x0D; } } } #endif } if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){ /* These look like magic numbers. But they are stable, as they are part ** of the definition of the SQLite file format, which may not change. */ u8 *pBuf = (u8*)zBuf; p->iCookie = rbuGetU32(&pBuf[24]); p->iWriteVer = pBuf[19]; } } return rc; } /* ** Write data to an rbuVfs-file. */ static int rbuVfsWrite( sqlite3_file *pFile, const void *zBuf, int iAmt, sqlite_int64 iOfst ){ rbu_file *p = (rbu_file*)pFile; sqlite3rbu *pRbu = p->pRbu; int rc; if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){ assert( p->openFlags & SQLITE_OPEN_MAIN_DB ); rc = rbuCaptureDbWrite(p->pRbu, iOfst); }else{ if( pRbu && pRbu->eStage==RBU_STAGE_OAL && (p->openFlags & SQLITE_OPEN_WAL) && iOfst>=pRbu->iOalSz ){ pRbu->iOalSz = iAmt + iOfst; } rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst); if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){ /* These look like magic numbers. But they are stable, as they are part ** of the definition of the SQLite file format, which may not change. */ u8 *pBuf = (u8*)zBuf; p->iCookie = rbuGetU32(&pBuf[24]); p->iWriteVer = pBuf[19]; } } return rc; } /* ** Truncate an rbuVfs-file. */ static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){ rbu_file *p = (rbu_file*)pFile; return p->pReal->pMethods->xTruncate(p->pReal, size); } /* ** Sync an rbuVfs-file. */ static int rbuVfsSync(sqlite3_file *pFile, int flags){ rbu_file *p = (rbu_file *)pFile; if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){ if( p->openFlags & SQLITE_OPEN_MAIN_DB ){ return SQLITE_INTERNAL; } return SQLITE_OK; } return p->pReal->pMethods->xSync(p->pReal, flags); } /* ** Return the current file-size of an rbuVfs-file. */ static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ rbu_file *p = (rbu_file *)pFile; int rc; rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); /* If this is an RBU vacuum operation and this is the target database, ** pretend that it has at least one page. Otherwise, SQLite will not ** check for the existance of a *-wal file. rbuVfsRead() contains ** similar logic. */ if( rc==SQLITE_OK && *pSize==0 && p->pRbu && rbuIsVacuum(p->pRbu) && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){ *pSize = 1024; } return rc; } /* ** Lock an rbuVfs-file. */ static int rbuVfsLock(sqlite3_file *pFile, int eLock){ rbu_file *p = (rbu_file*)pFile; sqlite3rbu *pRbu = p->pRbu; int rc = SQLITE_OK; assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); if( eLock==SQLITE_LOCK_EXCLUSIVE && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE)) ){ /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this ** prevents it from checkpointing the database from sqlite3_close(). */ rc = SQLITE_BUSY; }else{ rc = p->pReal->pMethods->xLock(p->pReal, eLock); } return rc; } /* ** Unlock an rbuVfs-file. */ static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){ rbu_file *p = (rbu_file *)pFile; return p->pReal->pMethods->xUnlock(p->pReal, eLock); } /* ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file. */ static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){ rbu_file *p = (rbu_file *)pFile; return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); } /* ** File control method. For custom operations on an rbuVfs-file. */ static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){ rbu_file *p = (rbu_file *)pFile; int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl; int rc; assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL) ); if( op==SQLITE_FCNTL_RBU ){ sqlite3rbu *pRbu = (sqlite3rbu*)pArg; /* First try to find another RBU vfs lower down in the vfs stack. If ** one is found, this vfs will operate in pass-through mode. The lower ** level vfs will do the special RBU handling. */ rc = xControl(p->pReal, op, pArg); if( rc==SQLITE_NOTFOUND ){ /* Now search for a zipvfs instance lower down in the VFS stack. If ** one is found, this is an error. */ void *dummy = 0; rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy); if( rc==SQLITE_OK ){ rc = SQLITE_ERROR; pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error"); }else if( rc==SQLITE_NOTFOUND ){ pRbu->pTargetFd = p; p->pRbu = pRbu; if( p->pWalFd ) p->pWalFd->pRbu = pRbu; rc = SQLITE_OK; } } return rc; } else if( op==SQLITE_FCNTL_RBUCNT ){ sqlite3rbu *pRbu = (sqlite3rbu*)pArg; pRbu->nRbu++; pRbu->pRbuFd = p; p->bNolock = 1; } rc = xControl(p->pReal, op, pArg); if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){ rbu_vfs *pRbuVfs = p->pRbuVfs; char *zIn = *(char**)pArg; char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn); *(char**)pArg = zOut; if( zOut==0 ) rc = SQLITE_NOMEM; } return rc; } /* ** Return the sector-size in bytes for an rbuVfs-file. */ static int rbuVfsSectorSize(sqlite3_file *pFile){ rbu_file *p = (rbu_file *)pFile; return p->pReal->pMethods->xSectorSize(p->pReal); } /* ** Return the device characteristic flags supported by an rbuVfs-file. */ static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){ rbu_file *p = (rbu_file *)pFile; return p->pReal->pMethods->xDeviceCharacteristics(p->pReal); } /* ** Take or release a shared-memory lock. */ static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ rbu_file *p = (rbu_file*)pFile; sqlite3rbu *pRbu = p->pRbu; int rc = SQLITE_OK; #ifdef SQLITE_AMALGAMATION assert( WAL_CKPT_LOCK==1 ); #endif assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){ /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from ** taking this lock also prevents any checkpoints from occurring. ** todo: really, it's not clear why this might occur, as ** wal_autocheckpoint ought to be turned off. */ if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY; }else{ int bCapture = 0; if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE) && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0) ){ bCapture = 1; } if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){ rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags); if( bCapture && rc==SQLITE_OK ){ pRbu->mLock |= (1 << ofst); } } } return rc; } /* ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file. */ static int rbuVfsShmMap( sqlite3_file *pFile, int iRegion, int szRegion, int isWrite, void volatile **pp ){ rbu_file *p = (rbu_file*)pFile; int rc = SQLITE_OK; int eStage = (p->pRbu ? p->pRbu->eStage : 0); /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space ** instead of a file on disk. */ assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){ if( iRegion<=p->nShm ){ int nByte = (iRegion+1) * sizeof(char*); char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte); if( apNew==0 ){ rc = SQLITE_NOMEM; }else{ memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm)); p->apShm = apNew; p->nShm = iRegion+1; } } if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){ char *pNew = (char*)sqlite3_malloc64(szRegion); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ memset(pNew, 0, szRegion); p->apShm[iRegion] = pNew; } } if( rc==SQLITE_OK ){ *pp = p->apShm[iRegion]; }else{ *pp = 0; } }else{ assert( p->apShm==0 ); rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp); } return rc; } /* ** Memory barrier. */ static void rbuVfsShmBarrier(sqlite3_file *pFile){ rbu_file *p = (rbu_file *)pFile; p->pReal->pMethods->xShmBarrier(p->pReal); } /* ** The xShmUnmap method. */ static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){ rbu_file *p = (rbu_file*)pFile; int rc = SQLITE_OK; int eStage = (p->pRbu ? p->pRbu->eStage : 0); assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){ /* no-op */ }else{ /* Release the checkpointer and writer locks */ rbuUnlockShm(p); rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag); } return rc; } /* ** Given that zWal points to a buffer containing a wal file name passed to ** either the xOpen() or xAccess() VFS method, return a pointer to the ** file-handle opened by the same database connection on the corresponding ** database file. */ static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){ rbu_file *pDb; sqlite3_mutex_enter(pRbuVfs->mutex); for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){} sqlite3_mutex_leave(pRbuVfs->mutex); return pDb; } /* ** A main database named zName has just been opened. The following ** function returns a pointer to a buffer owned by SQLite that contains ** the name of the *-wal file this db connection will use. SQLite ** happens to pass a pointer to this buffer when using xAccess() ** or xOpen() to operate on the *-wal file. */ static const char *rbuMainToWal(const char *zName, int flags){ int n = (int)strlen(zName); const char *z = &zName[n]; if( flags & SQLITE_OPEN_URI ){ int odd = 0; while( 1 ){ if( z[0]==0 ){ odd = 1 - odd; if( odd && z[1]==0 ) break; } z++; } z += 2; }else{ while( *z==0 ) z++; } z += (n + 8 + 1); return z; } /* ** Open an rbu file handle. */ static int rbuVfsOpen( sqlite3_vfs *pVfs, const char *zName, sqlite3_file *pFile, int flags, int *pOutFlags ){ static sqlite3_io_methods rbuvfs_io_methods = { 2, /* iVersion */ rbuVfsClose, /* xClose */ rbuVfsRead, /* xRead */ rbuVfsWrite, /* xWrite */ rbuVfsTruncate, /* xTruncate */ rbuVfsSync, /* xSync */ rbuVfsFileSize, /* xFileSize */ rbuVfsLock, /* xLock */ rbuVfsUnlock, /* xUnlock */ rbuVfsCheckReservedLock, /* xCheckReservedLock */ rbuVfsFileControl, /* xFileControl */ rbuVfsSectorSize, /* xSectorSize */ rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */ rbuVfsShmMap, /* xShmMap */ rbuVfsShmLock, /* xShmLock */ rbuVfsShmBarrier, /* xShmBarrier */ rbuVfsShmUnmap, /* xShmUnmap */ 0, 0 /* xFetch, xUnfetch */ }; rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs; sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs; rbu_file *pFd = (rbu_file *)pFile; int rc = SQLITE_OK; const char *zOpen = zName; int oflags = flags; memset(pFd, 0, sizeof(rbu_file)); pFd->pReal = (sqlite3_file*)&pFd[1]; pFd->pRbuVfs = pRbuVfs; pFd->openFlags = flags; if( zName ){ if( flags & SQLITE_OPEN_MAIN_DB ){ /* A main database has just been opened. The following block sets ** (pFd->zWal) to point to a buffer owned by SQLite that contains ** the name of the *-wal file this db connection will use. SQLite ** happens to pass a pointer to this buffer when using xAccess() ** or xOpen() to operate on the *-wal file. */ pFd->zWal = rbuMainToWal(zName, flags); } else if( flags & SQLITE_OPEN_WAL ){ rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName); if( pDb ){ if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){ /* This call is to open a *-wal file. Intead, open the *-oal. This ** code ensures that the string passed to xOpen() is terminated by a ** pair of '\0' bytes in case the VFS attempts to extract a URI ** parameter from it. */ const char *zBase = zName; size_t nCopy; char *zCopy; if( rbuIsVacuum(pDb->pRbu) ){ zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main"); zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI); } nCopy = strlen(zBase); zCopy = sqlite3_malloc64(nCopy+2); if( zCopy ){ memcpy(zCopy, zBase, nCopy); zCopy[nCopy-3] = 'o'; zCopy[nCopy] = '\0'; zCopy[nCopy+1] = '\0'; zOpen = (const char*)(pFd->zDel = zCopy); }else{ rc = SQLITE_NOMEM; } pFd->pRbu = pDb->pRbu; } pDb->pWalFd = pFd; } } } if( oflags & SQLITE_OPEN_MAIN_DB && sqlite3_uri_boolean(zName, "rbu_memory", 0) ){ assert( oflags & SQLITE_OPEN_MAIN_DB ); oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; zOpen = 0; } if( rc==SQLITE_OK ){ rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags); } if( pFd->pReal->pMethods ){ /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods ** pointer and, if the file is a main database file, link it into the ** mutex protected linked list of all such files. */ pFile->pMethods = &rbuvfs_io_methods; if( flags & SQLITE_OPEN_MAIN_DB ){ sqlite3_mutex_enter(pRbuVfs->mutex); pFd->pMainNext = pRbuVfs->pMain; pRbuVfs->pMain = pFd; sqlite3_mutex_leave(pRbuVfs->mutex); } }else{ sqlite3_free(pFd->zDel); } return rc; } /* ** Delete the file located at zPath. */ static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xDelete(pRealVfs, zPath, dirSync); } /* ** Test for access permissions. Return true if the requested permission ** is available, or false otherwise. */ static int rbuVfsAccess( sqlite3_vfs *pVfs, const char *zPath, int flags, int *pResOut ){ rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs; sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs; int rc; rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut); /* If this call is to check if a *-wal file associated with an RBU target ** database connection exists, and the RBU update is in RBU_STAGE_OAL, ** the following special handling is activated: ** ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This ** ensures that the RBU extension never tries to update a database ** in wal mode, even if the first page of the database file has ** been damaged. ** ** b) if the *-wal file does not exist, claim that it does anyway, ** causing SQLite to call xOpen() to open it. This call will also ** be intercepted (see the rbuVfsOpen() function) and the *-oal ** file opened instead. */ if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){ rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath); if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){ if( *pResOut ){ rc = SQLITE_CANTOPEN; }else{ *pResOut = 1; } } } return rc; } /* ** Populate buffer zOut with the full canonical pathname corresponding ** to the pathname in zPath. zOut is guaranteed to point to a buffer ** of at least (DEVSYM_MAX_PATHNAME+1) bytes. */ static int rbuVfsFullPathname( sqlite3_vfs *pVfs, const char *zPath, int nOut, char *zOut ){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut); } #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** Open the dynamic library located at zPath and return a handle. */ static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xDlOpen(pRealVfs, zPath); } /* ** Populate the buffer zErrMsg (size nByte bytes) with a human readable ** utf-8 string describing the most recent error encountered associated ** with dynamic libraries. */ static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; pRealVfs->xDlError(pRealVfs, nByte, zErrMsg); } /* ** Return a pointer to the symbol zSymbol in the dynamic library pHandle. */ static void (*rbuVfsDlSym( sqlite3_vfs *pVfs, void *pArg, const char *zSym ))(void){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xDlSym(pRealVfs, pArg, zSym); } /* ** Close the dynamic library handle pHandle. */ static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; pRealVfs->xDlClose(pRealVfs, pHandle); } #endif /* SQLITE_OMIT_LOAD_EXTENSION */ /* ** Populate the buffer pointed to by zBufOut with nByte bytes of ** random data. */ static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut); } /* ** Sleep for nMicro microseconds. Return the number of microseconds ** actually slept. */ static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xSleep(pRealVfs, nMicro); } /* ** Return the current time as a Julian Day number in *pTimeOut. */ static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xCurrentTime(pRealVfs, pTimeOut); } /* ** No-op. */ static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){ return 0; } /* ** Deregister and destroy an RBU vfs created by an earlier call to ** sqlite3rbu_create_vfs(). */ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){ sqlite3_vfs *pVfs = sqlite3_vfs_find(zName); if( pVfs && pVfs->xOpen==rbuVfsOpen ){ sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex); sqlite3_vfs_unregister(pVfs); sqlite3_free(pVfs); } } /* ** Create an RBU VFS named zName that accesses the underlying file-system ** via existing VFS zParent. The new object is registered as a non-default ** VFS with SQLite before returning. */ SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){ /* Template for VFS */ static sqlite3_vfs vfs_template = { 1, /* iVersion */ 0, /* szOsFile */ 0, /* mxPathname */ 0, /* pNext */ 0, /* zName */ 0, /* pAppData */ rbuVfsOpen, /* xOpen */ rbuVfsDelete, /* xDelete */ rbuVfsAccess, /* xAccess */ rbuVfsFullPathname, /* xFullPathname */ #ifndef SQLITE_OMIT_LOAD_EXTENSION rbuVfsDlOpen, /* xDlOpen */ rbuVfsDlError, /* xDlError */ rbuVfsDlSym, /* xDlSym */ rbuVfsDlClose, /* xDlClose */ #else 0, 0, 0, 0, #endif rbuVfsRandomness, /* xRandomness */ rbuVfsSleep, /* xSleep */ rbuVfsCurrentTime, /* xCurrentTime */ rbuVfsGetLastError, /* xGetLastError */ 0, /* xCurrentTimeInt64 (version 2) */ 0, 0, 0 /* Unimplemented version 3 methods */ }; rbu_vfs *pNew = 0; /* Newly allocated VFS */ int rc = SQLITE_OK; size_t nName; size_t nByte; nName = strlen(zName); nByte = sizeof(rbu_vfs) + nName + 1; pNew = (rbu_vfs*)sqlite3_malloc64(nByte); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ sqlite3_vfs *pParent; /* Parent VFS */ memset(pNew, 0, nByte); pParent = sqlite3_vfs_find(zParent); if( pParent==0 ){ rc = SQLITE_NOTFOUND; }else{ char *zSpace; memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs)); pNew->base.mxPathname = pParent->mxPathname; pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile; pNew->pRealVfs = pParent; pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]); memcpy(zSpace, zName, nName); /* Allocate the mutex and register the new VFS (not as the default) */ pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); if( pNew->mutex==0 ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_vfs_register(&pNew->base, 0); } } if( rc!=SQLITE_OK ){ sqlite3_mutex_free(pNew->mutex); sqlite3_free(pNew); } } return rc; } /**************************************************************************/ #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */ /************** End of sqlite3rbu.c ******************************************/ /************** Begin file dbstat.c ******************************************/ /* ** 2010 July 12 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains an implementation of the "dbstat" virtual table. ** ** The dbstat virtual table is used to extract low-level formatting ** information from an SQLite database in order to implement the ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script ** for an example implementation. ** ** Additional information is available on the "dbstat.html" page of the ** official SQLite documentation. */ /* #include "sqliteInt.h" ** Requires access to internal data structures ** */ #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \ && !defined(SQLITE_OMIT_VIRTUALTABLE) /* ** Page paths: ** ** The value of the 'path' column describes the path taken from the ** root-node of the b-tree structure to each page. The value of the ** root-node path is '/'. ** ** The value of the path for the left-most child page of the root of ** a b-tree is '/000/'. (Btrees store content ordered from left to right ** so the pages to the left have smaller keys than the pages to the right.) ** The next to left-most child of the root page is ** '/001', and so on, each sibling page identified by a 3-digit hex ** value. The children of the 451st left-most sibling have paths such ** as '/1c2/000/, '/1c2/001/' etc. ** ** Overflow pages are specified by appending a '+' character and a ** six-digit hexadecimal value to the path to the cell they are linked ** from. For example, the three overflow pages in a chain linked from ** the left-most cell of the 450th child of the root page are identified ** by the paths: ** ** '/1c2/000+000000' // First page in overflow chain ** '/1c2/000+000001' // Second page in overflow chain ** '/1c2/000+000002' // Third page in overflow chain ** ** If the paths are sorted using the BINARY collation sequence, then ** the overflow pages associated with a cell will appear earlier in the ** sort-order than its child page: ** ** '/1c2/000/' // Left-most child of 451st child of root */ #define VTAB_SCHEMA \ "CREATE TABLE xx( " \ " name TEXT, /* Name of table or index */" \ " path TEXT, /* Path to page from root */" \ " pageno INTEGER, /* Page number */" \ " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \ " ncell INTEGER, /* Cells on page (0 for overflow) */" \ " payload INTEGER, /* Bytes of payload on this page */" \ " unused INTEGER, /* Bytes of unused space on this page */" \ " mx_payload INTEGER, /* Largest payload size of all cells */" \ " pgoffset INTEGER, /* Offset of page in file */" \ " pgsize INTEGER, /* Size of the page */" \ " schema TEXT HIDDEN /* Database schema being analyzed */" \ ");" typedef struct StatTable StatTable; typedef struct StatCursor StatCursor; typedef struct StatPage StatPage; typedef struct StatCell StatCell; struct StatCell { int nLocal; /* Bytes of local payload */ u32 iChildPg; /* Child node (or 0 if this is a leaf) */ int nOvfl; /* Entries in aOvfl[] */ u32 *aOvfl; /* Array of overflow page numbers */ int nLastOvfl; /* Bytes of payload on final overflow page */ int iOvfl; /* Iterates through aOvfl[] */ }; struct StatPage { u32 iPgno; DbPage *pPg; int iCell; char *zPath; /* Path to this page */ /* Variables populated by statDecodePage(): */ u8 flags; /* Copy of flags byte */ int nCell; /* Number of cells on page */ int nUnused; /* Number of unused bytes on page */ StatCell *aCell; /* Array of parsed cells */ u32 iRightChildPg; /* Right-child page number (or 0) */ int nMxPayload; /* Largest payload of any cell on this page */ }; struct StatCursor { sqlite3_vtab_cursor base; sqlite3_stmt *pStmt; /* Iterates through set of root pages */ int isEof; /* After pStmt has returned SQLITE_DONE */ int iDb; /* Schema used for this query */ StatPage aPage[32]; int iPage; /* Current entry in aPage[] */ /* Values to return. */ char *zName; /* Value of 'name' column */ char *zPath; /* Value of 'path' column */ u32 iPageno; /* Value of 'pageno' column */ char *zPagetype; /* Value of 'pagetype' column */ int nCell; /* Value of 'ncell' column */ int nPayload; /* Value of 'payload' column */ int nUnused; /* Value of 'unused' column */ int nMxPayload; /* Value of 'mx_payload' column */ i64 iOffset; /* Value of 'pgOffset' column */ int szPage; /* Value of 'pgSize' column */ }; struct StatTable { sqlite3_vtab base; sqlite3 *db; int iDb; /* Index of database to analyze */ }; #ifndef get2byte # define get2byte(x) ((x)[0]<<8 | (x)[1]) #endif /* ** Connect to or create a statvfs virtual table. */ static int statConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ StatTable *pTab = 0; int rc = SQLITE_OK; int iDb; if( argc>=4 ){ Token nm; sqlite3TokenInit(&nm, (char*)argv[3]); iDb = sqlite3FindDb(db, &nm); if( iDb<0 ){ *pzErr = sqlite3_mprintf("no such database: %s", argv[3]); return SQLITE_ERROR; } }else{ iDb = 0; } rc = sqlite3_declare_vtab(db, VTAB_SCHEMA); if( rc==SQLITE_OK ){ pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable)); if( pTab==0 ) rc = SQLITE_NOMEM_BKPT; } assert( rc==SQLITE_OK || pTab==0 ); if( rc==SQLITE_OK ){ memset(pTab, 0, sizeof(StatTable)); pTab->db = db; pTab->iDb = iDb; } *ppVtab = (sqlite3_vtab*)pTab; return rc; } /* ** Disconnect from or destroy a statvfs virtual table. */ static int statDisconnect(sqlite3_vtab *pVtab){ sqlite3_free(pVtab); return SQLITE_OK; } /* ** There is no "best-index". This virtual table always does a linear ** scan. However, a schema=? constraint should cause this table to ** operate on a different database schema, so check for it. ** ** idxNum is normally 0, but will be 1 if a schema=? constraint exists. */ static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ int i; pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */ /* Look for a valid schema=? constraint. If found, change the idxNum to ** 1 and request the value of that constraint be sent to xFilter. And ** lower the cost estimate to encourage the constrained version to be ** used. */ for(i=0; i<pIdxInfo->nConstraint; i++){ if( pIdxInfo->aConstraint[i].usable==0 ) continue; if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue; pIdxInfo->idxNum = 1; pIdxInfo->estimatedCost = 1.0; pIdxInfo->aConstraintUsage[i].argvIndex = 1; pIdxInfo->aConstraintUsage[i].omit = 1; break; } /* Records are always returned in ascending order of (name, path). ** If this will satisfy the client, set the orderByConsumed flag so that ** SQLite does not do an external sort. */ if( ( pIdxInfo->nOrderBy==1 && pIdxInfo->aOrderBy[0].iColumn==0 && pIdxInfo->aOrderBy[0].desc==0 ) || ( pIdxInfo->nOrderBy==2 && pIdxInfo->aOrderBy[0].iColumn==0 && pIdxInfo->aOrderBy[0].desc==0 && pIdxInfo->aOrderBy[1].iColumn==1 && pIdxInfo->aOrderBy[1].desc==0 ) ){ pIdxInfo->orderByConsumed = 1; } return SQLITE_OK; } /* ** Open a new statvfs cursor. */ static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ StatTable *pTab = (StatTable *)pVTab; StatCursor *pCsr; pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor)); if( pCsr==0 ){ return SQLITE_NOMEM_BKPT; }else{ memset(pCsr, 0, sizeof(StatCursor)); pCsr->base.pVtab = pVTab; pCsr->iDb = pTab->iDb; } *ppCursor = (sqlite3_vtab_cursor *)pCsr; return SQLITE_OK; } static void statClearPage(StatPage *p){ int i; if( p->aCell ){ for(i=0; i<p->nCell; i++){ sqlite3_free(p->aCell[i].aOvfl); } sqlite3_free(p->aCell); } sqlite3PagerUnref(p->pPg); sqlite3_free(p->zPath); memset(p, 0, sizeof(StatPage)); } static void statResetCsr(StatCursor *pCsr){ int i; sqlite3_reset(pCsr->pStmt); for(i=0; i<ArraySize(pCsr->aPage); i++){ statClearPage(&pCsr->aPage[i]); } pCsr->iPage = 0; sqlite3_free(pCsr->zPath); pCsr->zPath = 0; pCsr->isEof = 0; } /* ** Close a statvfs cursor. */ static int statClose(sqlite3_vtab_cursor *pCursor){ StatCursor *pCsr = (StatCursor *)pCursor; statResetCsr(pCsr); sqlite3_finalize(pCsr->pStmt); sqlite3_free(pCsr); return SQLITE_OK; } static void getLocalPayload( int nUsable, /* Usable bytes per page */ u8 flags, /* Page flags */ int nTotal, /* Total record (payload) size */ int *pnLocal /* OUT: Bytes stored locally */ ){ int nLocal; int nMinLocal; int nMaxLocal; if( flags==0x0D ){ /* Table leaf node */ nMinLocal = (nUsable - 12) * 32 / 255 - 23; nMaxLocal = nUsable - 35; }else{ /* Index interior and leaf nodes */ nMinLocal = (nUsable - 12) * 32 / 255 - 23; nMaxLocal = (nUsable - 12) * 64 / 255 - 23; } nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4); if( nLocal>nMaxLocal ) nLocal = nMinLocal; *pnLocal = nLocal; } static int statDecodePage(Btree *pBt, StatPage *p){ int nUnused; int iOff; int nHdr; int isLeaf; int szPage; u8 *aData = sqlite3PagerGetData(p->pPg); u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0]; p->flags = aHdr[0]; p->nCell = get2byte(&aHdr[3]); p->nMxPayload = 0; isLeaf = (p->flags==0x0A || p->flags==0x0D); nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100; nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell; nUnused += (int)aHdr[7]; iOff = get2byte(&aHdr[1]); while( iOff ){ nUnused += get2byte(&aData[iOff+2]); iOff = get2byte(&aData[iOff]); } p->nUnused = nUnused; p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]); szPage = sqlite3BtreeGetPageSize(pBt); if( p->nCell ){ int i; /* Used to iterate through cells */ int nUsable; /* Usable bytes per page */ sqlite3BtreeEnter(pBt); nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt); sqlite3BtreeLeave(pBt); p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell)); if( p->aCell==0 ) return SQLITE_NOMEM_BKPT; memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell)); for(i=0; i<p->nCell; i++){ StatCell *pCell = &p->aCell[i]; iOff = get2byte(&aData[nHdr+i*2]); if( !isLeaf ){ pCell->iChildPg = sqlite3Get4byte(&aData[iOff]); iOff += 4; } if( p->flags==0x05 ){ /* A table interior node. nPayload==0. */ }else{ u32 nPayload; /* Bytes of payload total (local+overflow) */ int nLocal; /* Bytes of payload stored locally */ iOff += getVarint32(&aData[iOff], nPayload); if( p->flags==0x0D ){ u64 dummy; iOff += sqlite3GetVarint(&aData[iOff], &dummy); } if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload; getLocalPayload(nUsable, p->flags, nPayload, &nLocal); pCell->nLocal = nLocal; assert( nLocal>=0 ); assert( nPayload>=(u32)nLocal ); assert( nLocal<=(nUsable-35) ); if( nPayload>(u32)nLocal ){ int j; int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4); pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4); pCell->nOvfl = nOvfl; pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl); if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT; pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]); for(j=1; j<nOvfl; j++){ int rc; u32 iPrev = pCell->aOvfl[j-1]; DbPage *pPg = 0; rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0); if( rc!=SQLITE_OK ){ assert( pPg==0 ); return rc; } pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg)); sqlite3PagerUnref(pPg); } } } } } return SQLITE_OK; } /* ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on ** the current value of pCsr->iPageno. */ static void statSizeAndOffset(StatCursor *pCsr){ StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab; Btree *pBt = pTab->db->aDb[pTab->iDb].pBt; Pager *pPager = sqlite3BtreePager(pBt); sqlite3_file *fd; sqlite3_int64 x[2]; /* The default page size and offset */ pCsr->szPage = sqlite3BtreeGetPageSize(pBt); pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1); /* If connected to a ZIPVFS backend, override the page size and ** offset with actual values obtained from ZIPVFS. */ fd = sqlite3PagerFile(pPager); x[0] = pCsr->iPageno; if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){ pCsr->iOffset = x[0]; pCsr->szPage = (int)x[1]; } } /* ** Move a statvfs cursor to the next entry in the file. */ static int statNext(sqlite3_vtab_cursor *pCursor){ int rc; int nPayload; char *z; StatCursor *pCsr = (StatCursor *)pCursor; StatTable *pTab = (StatTable *)pCursor->pVtab; Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt; Pager *pPager = sqlite3BtreePager(pBt); sqlite3_free(pCsr->zPath); pCsr->zPath = 0; statNextRestart: if( pCsr->aPage[0].pPg==0 ){ rc = sqlite3_step(pCsr->pStmt); if( rc==SQLITE_ROW ){ int nPage; u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1); sqlite3PagerPagecount(pPager, &nPage); if( nPage==0 ){ pCsr->isEof = 1; return sqlite3_reset(pCsr->pStmt); } rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0); pCsr->aPage[0].iPgno = iRoot; pCsr->aPage[0].iCell = 0; pCsr->aPage[0].zPath = z = sqlite3_mprintf("/"); pCsr->iPage = 0; if( z==0 ) rc = SQLITE_NOMEM_BKPT; }else{ pCsr->isEof = 1; return sqlite3_reset(pCsr->pStmt); } }else{ /* Page p itself has already been visited. */ StatPage *p = &pCsr->aPage[pCsr->iPage]; while( p->iCell<p->nCell ){ StatCell *pCell = &p->aCell[p->iCell]; if( pCell->iOvfl<pCell->nOvfl ){ int nUsable; sqlite3BtreeEnter(pBt); nUsable = sqlite3BtreeGetPageSize(pBt) - sqlite3BtreeGetReserveNoMutex(pBt); sqlite3BtreeLeave(pBt); pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); pCsr->iPageno = pCell->aOvfl[pCell->iOvfl]; pCsr->zPagetype = "overflow"; pCsr->nCell = 0; pCsr->nMxPayload = 0; pCsr->zPath = z = sqlite3_mprintf( "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl ); if( pCell->iOvfl<pCell->nOvfl-1 ){ pCsr->nUnused = 0; pCsr->nPayload = nUsable - 4; }else{ pCsr->nPayload = pCell->nLastOvfl; pCsr->nUnused = nUsable - 4 - pCsr->nPayload; } pCell->iOvfl++; statSizeAndOffset(pCsr); return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK; } if( p->iRightChildPg ) break; p->iCell++; } if( !p->iRightChildPg || p->iCell>p->nCell ){ statClearPage(p); if( pCsr->iPage==0 ) return statNext(pCursor); pCsr->iPage--; goto statNextRestart; /* Tail recursion */ } pCsr->iPage++; assert( p==&pCsr->aPage[pCsr->iPage-1] ); if( p->iCell==p->nCell ){ p[1].iPgno = p->iRightChildPg; }else{ p[1].iPgno = p->aCell[p->iCell].iChildPg; } rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0); p[1].iCell = 0; p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell); p->iCell++; if( z==0 ) rc = SQLITE_NOMEM_BKPT; } /* Populate the StatCursor fields with the values to be returned ** by the xColumn() and xRowid() methods. */ if( rc==SQLITE_OK ){ int i; StatPage *p = &pCsr->aPage[pCsr->iPage]; pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); pCsr->iPageno = p->iPgno; rc = statDecodePage(pBt, p); if( rc==SQLITE_OK ){ statSizeAndOffset(pCsr); switch( p->flags ){ case 0x05: /* table internal */ case 0x02: /* index internal */ pCsr->zPagetype = "internal"; break; case 0x0D: /* table leaf */ case 0x0A: /* index leaf */ pCsr->zPagetype = "leaf"; break; default: pCsr->zPagetype = "corrupted"; break; } pCsr->nCell = p->nCell; pCsr->nUnused = p->nUnused; pCsr->nMxPayload = p->nMxPayload; pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath); if( z==0 ) rc = SQLITE_NOMEM_BKPT; nPayload = 0; for(i=0; i<p->nCell; i++){ nPayload += p->aCell[i].nLocal; } pCsr->nPayload = nPayload; } } return rc; } static int statEof(sqlite3_vtab_cursor *pCursor){ StatCursor *pCsr = (StatCursor *)pCursor; return pCsr->isEof; } static int statFilter( sqlite3_vtab_cursor *pCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ StatCursor *pCsr = (StatCursor *)pCursor; StatTable *pTab = (StatTable*)(pCursor->pVtab); char *zSql; int rc = SQLITE_OK; char *zMaster; if( idxNum==1 ){ const char *zDbase = (const char*)sqlite3_value_text(argv[0]); pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase); if( pCsr->iDb<0 ){ sqlite3_free(pCursor->pVtab->zErrMsg); pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase); return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT; } }else{ pCsr->iDb = pTab->iDb; } statResetCsr(pCsr); sqlite3_finalize(pCsr->pStmt); pCsr->pStmt = 0; zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master"; zSql = sqlite3_mprintf( "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type" " UNION ALL " "SELECT name, rootpage, type" " FROM \"%w\".%s WHERE rootpage!=0" " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster); if( zSql==0 ){ return SQLITE_NOMEM_BKPT; }else{ rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0); sqlite3_free(zSql); } if( rc==SQLITE_OK ){ rc = statNext(pCursor); } return rc; } static int statColumn( sqlite3_vtab_cursor *pCursor, sqlite3_context *ctx, int i ){ StatCursor *pCsr = (StatCursor *)pCursor; switch( i ){ case 0: /* name */ sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT); break; case 1: /* path */ sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT); break; case 2: /* pageno */ sqlite3_result_int64(ctx, pCsr->iPageno); break; case 3: /* pagetype */ sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC); break; case 4: /* ncell */ sqlite3_result_int(ctx, pCsr->nCell); break; case 5: /* payload */ sqlite3_result_int(ctx, pCsr->nPayload); break; case 6: /* unused */ sqlite3_result_int(ctx, pCsr->nUnused); break; case 7: /* mx_payload */ sqlite3_result_int(ctx, pCsr->nMxPayload); break; case 8: /* pgoffset */ sqlite3_result_int64(ctx, pCsr->iOffset); break; case 9: /* pgsize */ sqlite3_result_int(ctx, pCsr->szPage); break; default: { /* schema */ sqlite3 *db = sqlite3_context_db_handle(ctx); int iDb = pCsr->iDb; sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC); break; } } return SQLITE_OK; } static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ StatCursor *pCsr = (StatCursor *)pCursor; *pRowid = pCsr->iPageno; return SQLITE_OK; } /* ** Invoke this routine to register the "dbstat" virtual table module */ SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ static sqlite3_module dbstat_module = { 0, /* iVersion */ statConnect, /* xCreate */ statConnect, /* xConnect */ statBestIndex, /* xBestIndex */ statDisconnect, /* xDisconnect */ statDisconnect, /* xDestroy */ statOpen, /* xOpen - open a cursor */ statClose, /* xClose - close a cursor */ statFilter, /* xFilter - configure scan constraints */ statNext, /* xNext - advance a cursor */ statEof, /* xEof - check for end of scan */ statColumn, /* xColumn - read data */ statRowid, /* xRowid - read data */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindMethod */ 0, /* xRename */ }; return sqlite3_create_module(db, "dbstat", &dbstat_module, 0); } #elif defined(SQLITE_ENABLE_DBSTAT_VTAB) SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; } #endif /* SQLITE_ENABLE_DBSTAT_VTAB */ /************** End of dbstat.c **********************************************/ /************** Begin file sqlite3session.c **********************************/ #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK) /* #include "sqlite3session.h" */ /* #include <assert.h> */ /* #include <string.h> */ #ifndef SQLITE_AMALGAMATION /* # include "sqliteInt.h" */ /* # include "vdbeInt.h" */ #endif typedef struct SessionTable SessionTable; typedef struct SessionChange SessionChange; typedef struct SessionBuffer SessionBuffer; typedef struct SessionInput SessionInput; /* ** Minimum chunk size used by streaming versions of functions. */ #ifndef SESSIONS_STRM_CHUNK_SIZE # ifdef SQLITE_TEST # define SESSIONS_STRM_CHUNK_SIZE 64 # else # define SESSIONS_STRM_CHUNK_SIZE 1024 # endif #endif typedef struct SessionHook SessionHook; struct SessionHook { void *pCtx; int (*xOld)(void*,int,sqlite3_value**); int (*xNew)(void*,int,sqlite3_value**); int (*xCount)(void*); int (*xDepth)(void*); }; /* ** Session handle structure. */ struct sqlite3_session { sqlite3 *db; /* Database handle session is attached to */ char *zDb; /* Name of database session is attached to */ int bEnable; /* True if currently recording */ int bIndirect; /* True if all changes are indirect */ int bAutoAttach; /* True to auto-attach tables */ int rc; /* Non-zero if an error has occurred */ void *pFilterCtx; /* First argument to pass to xTableFilter */ int (*xTableFilter)(void *pCtx, const char *zTab); sqlite3_session *pNext; /* Next session object on same db. */ SessionTable *pTable; /* List of attached tables */ SessionHook hook; /* APIs to grab new and old data with */ }; /* ** Instances of this structure are used to build strings or binary records. */ struct SessionBuffer { u8 *aBuf; /* Pointer to changeset buffer */ int nBuf; /* Size of buffer aBuf */ int nAlloc; /* Size of allocation containing aBuf */ }; /* ** An object of this type is used internally as an abstraction for ** input data. Input data may be supplied either as a single large buffer ** (e.g. sqlite3changeset_start()) or using a stream function (e.g. ** sqlite3changeset_start_strm()). */ struct SessionInput { int bNoDiscard; /* If true, discard no data */ int iCurrent; /* Offset in aData[] of current change */ int iNext; /* Offset in aData[] of next change */ u8 *aData; /* Pointer to buffer containing changeset */ int nData; /* Number of bytes in aData */ SessionBuffer buf; /* Current read buffer */ int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */ void *pIn; /* First argument to xInput */ int bEof; /* Set to true after xInput finished */ }; /* ** Structure for changeset iterators. */ struct sqlite3_changeset_iter { SessionInput in; /* Input buffer or stream */ SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */ int bPatchset; /* True if this is a patchset */ int rc; /* Iterator error code */ sqlite3_stmt *pConflict; /* Points to conflicting row, if any */ char *zTab; /* Current table */ int nCol; /* Number of columns in zTab */ int op; /* Current operation */ int bIndirect; /* True if current change was indirect */ u8 *abPK; /* Primary key array */ sqlite3_value **apValue; /* old.* and new.* values */ }; /* ** Each session object maintains a set of the following structures, one ** for each table the session object is monitoring. The structures are ** stored in a linked list starting at sqlite3_session.pTable. ** ** The keys of the SessionTable.aChange[] hash table are all rows that have ** been modified in any way since the session object was attached to the ** table. ** ** The data associated with each hash-table entry is a structure containing ** a subset of the initial values that the modified row contained at the ** start of the session. Or no initial values if the row was inserted. */ struct SessionTable { SessionTable *pNext; char *zName; /* Local name of table */ int nCol; /* Number of columns in table zName */ const char **azCol; /* Column names */ u8 *abPK; /* Array of primary key flags */ int nEntry; /* Total number of entries in hash table */ int nChange; /* Size of apChange[] array */ SessionChange **apChange; /* Hash table buckets */ }; /* ** RECORD FORMAT: ** ** The following record format is similar to (but not compatible with) that ** used in SQLite database files. This format is used as part of the ** change-set binary format, and so must be architecture independent. ** ** Unlike the SQLite database record format, each field is self-contained - ** there is no separation of header and data. Each field begins with a ** single byte describing its type, as follows: ** ** 0x00: Undefined value. ** 0x01: Integer value. ** 0x02: Real value. ** 0x03: Text value. ** 0x04: Blob value. ** 0x05: SQL NULL value. ** ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT ** and so on in sqlite3.h. For undefined and NULL values, the field consists ** only of the single type byte. For other types of values, the type byte ** is followed by: ** ** Text values: ** A varint containing the number of bytes in the value (encoded using ** UTF-8). Followed by a buffer containing the UTF-8 representation ** of the text value. There is no nul terminator. ** ** Blob values: ** A varint containing the number of bytes in the value, followed by ** a buffer containing the value itself. ** ** Integer values: ** An 8-byte big-endian integer value. ** ** Real values: ** An 8-byte big-endian IEEE 754-2008 real value. ** ** Varint values are encoded in the same way as varints in the SQLite ** record format. ** ** CHANGESET FORMAT: ** ** A changeset is a collection of DELETE, UPDATE and INSERT operations on ** one or more tables. Operations on a single table are grouped together, ** but may occur in any order (i.e. deletes, updates and inserts are all ** mixed together). ** ** Each group of changes begins with a table header: ** ** 1 byte: Constant 0x54 (capital 'T') ** Varint: Number of columns in the table. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated. ** ** Followed by one or more changes to the table. ** ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09). ** 1 byte: The "indirect-change" flag. ** old.* record: (delete and update only) ** new.* record: (insert and update only) ** ** The "old.*" and "new.*" records, if present, are N field records in the ** format described above under "RECORD FORMAT", where N is the number of ** columns in the table. The i'th field of each record is associated with ** the i'th column of the table, counting from left to right in the order ** in which columns were declared in the CREATE TABLE statement. ** ** The new.* record that is part of each INSERT change contains the values ** that make up the new row. Similarly, the old.* record that is part of each ** DELETE change contains the values that made up the row that was deleted ** from the database. In the changeset format, the records that are part ** of INSERT or DELETE changes never contain any undefined (type byte 0x00) ** fields. ** ** Within the old.* record associated with an UPDATE change, all fields ** associated with table columns that are not PRIMARY KEY columns and are ** not modified by the UPDATE change are set to "undefined". Other fields ** are set to the values that made up the row before the UPDATE that the ** change records took place. Within the new.* record, fields associated ** with table columns modified by the UPDATE change contain the new ** values. Fields associated with table columns that are not modified ** are set to "undefined". ** ** PATCHSET FORMAT: ** ** A patchset is also a collection of changes. It is similar to a changeset, ** but leaves undefined those fields that are not useful if no conflict ** resolution is required when applying the changeset. ** ** Each group of changes begins with a table header: ** ** 1 byte: Constant 0x50 (capital 'P') ** Varint: Number of columns in the table. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated. ** ** Followed by one or more changes to the table. ** ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09). ** 1 byte: The "indirect-change" flag. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE, ** full record for INSERT). ** ** As in the changeset format, each field of the single record that is part ** of a patchset change is associated with the correspondingly positioned ** table column, counting from left to right within the CREATE TABLE ** statement. ** ** For a DELETE change, all fields within the record except those associated ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields ** contain the values identifying the row to delete. ** ** For an UPDATE change, all fields except those associated with PRIMARY KEY ** columns and columns that are modified by the UPDATE are set to "undefined". ** PRIMARY KEY fields contain the values identifying the table row to update, ** and fields associated with modified columns contain the new column values. ** ** The records associated with INSERT changes are in the same format as for ** changesets. It is not possible for a record associated with an INSERT ** change to contain a field set to "undefined". */ /* ** For each row modified during a session, there exists a single instance of ** this structure stored in a SessionTable.aChange[] hash table. */ struct SessionChange { int op; /* One of UPDATE, DELETE, INSERT */ int bIndirect; /* True if this change is "indirect" */ int nRecord; /* Number of bytes in buffer aRecord[] */ u8 *aRecord; /* Buffer containing old.* record */ SessionChange *pNext; /* For hash-table collisions */ }; /* ** Write a varint with value iVal into the buffer at aBuf. Return the ** number of bytes written. */ static int sessionVarintPut(u8 *aBuf, int iVal){ return putVarint32(aBuf, iVal); } /* ** Return the number of bytes required to store value iVal as a varint. */ static int sessionVarintLen(int iVal){ return sqlite3VarintLen(iVal); } /* ** Read a varint value from aBuf[] into *piVal. Return the number of ** bytes read. */ static int sessionVarintGet(u8 *aBuf, int *piVal){ return getVarint32(aBuf, *piVal); } /* Load an unaligned and unsigned 32-bit integer */ #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) /* ** Read a 64-bit big-endian integer value from buffer aRec[]. Return ** the value read. */ static sqlite3_int64 sessionGetI64(u8 *aRec){ u64 x = SESSION_UINT32(aRec); u32 y = SESSION_UINT32(aRec+4); x = (x<<32) + y; return (sqlite3_int64)x; } /* ** Write a 64-bit big-endian integer value to the buffer aBuf[]. */ static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){ aBuf[0] = (i>>56) & 0xFF; aBuf[1] = (i>>48) & 0xFF; aBuf[2] = (i>>40) & 0xFF; aBuf[3] = (i>>32) & 0xFF; aBuf[4] = (i>>24) & 0xFF; aBuf[5] = (i>>16) & 0xFF; aBuf[6] = (i>> 8) & 0xFF; aBuf[7] = (i>> 0) & 0xFF; } /* ** This function is used to serialize the contents of value pValue (see ** comment titled "RECORD FORMAT" above). ** ** If it is non-NULL, the serialized form of the value is written to ** buffer aBuf. *pnWrite is set to the number of bytes written before ** returning. Or, if aBuf is NULL, the only thing this function does is ** set *pnWrite. ** ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs ** within a call to sqlite3_value_text() (may fail if the db is utf-16)) ** SQLITE_NOMEM is returned. */ static int sessionSerializeValue( u8 *aBuf, /* If non-NULL, write serialized value here */ sqlite3_value *pValue, /* Value to serialize */ int *pnWrite /* IN/OUT: Increment by bytes written */ ){ int nByte; /* Size of serialized value in bytes */ if( pValue ){ int eType; /* Value type (SQLITE_NULL, TEXT etc.) */ eType = sqlite3_value_type(pValue); if( aBuf ) aBuf[0] = eType; switch( eType ){ case SQLITE_NULL: nByte = 1; break; case SQLITE_INTEGER: case SQLITE_FLOAT: if( aBuf ){ /* TODO: SQLite does something special to deal with mixed-endian ** floating point values (e.g. ARM7). This code probably should ** too. */ u64 i; if( eType==SQLITE_INTEGER ){ i = (u64)sqlite3_value_int64(pValue); }else{ double r; assert( sizeof(double)==8 && sizeof(u64)==8 ); r = sqlite3_value_double(pValue); memcpy(&i, &r, 8); } sessionPutI64(&aBuf[1], i); } nByte = 9; break; default: { u8 *z; int n; int nVarint; assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); if( eType==SQLITE_TEXT ){ z = (u8 *)sqlite3_value_text(pValue); }else{ z = (u8 *)sqlite3_value_blob(pValue); } n = sqlite3_value_bytes(pValue); if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM; nVarint = sessionVarintLen(n); if( aBuf ){ sessionVarintPut(&aBuf[1], n); if( n ) memcpy(&aBuf[nVarint + 1], z, n); } nByte = 1 + nVarint + n; break; } } }else{ nByte = 1; if( aBuf ) aBuf[0] = '\0'; } if( pnWrite ) *pnWrite += nByte; return SQLITE_OK; } /* ** This macro is used to calculate hash key values for data structures. In ** order to use this macro, the entire data structure must be represented ** as a series of unsigned integers. In order to calculate a hash-key value ** for a data structure represented as three such integers, the macro may ** then be used as follows: ** ** int hash_key_value; ** hash_key_value = HASH_APPEND(0, <value 1>); ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>); ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>); ** ** In practice, the data structures this macro is used for are the primary ** key values of modified rows. */ #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add) /* ** Append the hash of the 64-bit integer passed as the second argument to the ** hash-key value passed as the first. Return the new hash-key value. */ static unsigned int sessionHashAppendI64(unsigned int h, i64 i){ h = HASH_APPEND(h, i & 0xFFFFFFFF); return HASH_APPEND(h, (i>>32)&0xFFFFFFFF); } /* ** Append the hash of the blob passed via the second and third arguments to ** the hash-key value passed as the first. Return the new hash-key value. */ static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){ int i; for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]); return h; } /* ** Append the hash of the data type passed as the second argument to the ** hash-key value passed as the first. Return the new hash-key value. */ static unsigned int sessionHashAppendType(unsigned int h, int eType){ return HASH_APPEND(h, eType); } /* ** This function may only be called from within a pre-update callback. ** It calculates a hash based on the primary key values of the old.* or ** new.* row currently available and, assuming no error occurs, writes it to ** *piHash before returning. If the primary key contains one or more NULL ** values, *pbNullPK is set to true before returning. ** ** If an error occurs, an SQLite error code is returned and the final values ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned ** and the output variables are set as described above. */ static int sessionPreupdateHash( sqlite3_session *pSession, /* Session object that owns pTab */ SessionTable *pTab, /* Session table handle */ int bNew, /* True to hash the new.* PK */ int *piHash, /* OUT: Hash value */ int *pbNullPK /* OUT: True if there are NULL values in PK */ ){ unsigned int h = 0; /* Hash value to return */ int i; /* Used to iterate through columns */ assert( *pbNullPK==0 ); assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) ); for(i=0; i<pTab->nCol; i++){ if( pTab->abPK[i] ){ int rc; int eType; sqlite3_value *pVal; if( bNew ){ rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal); }else{ rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal); } if( rc!=SQLITE_OK ) return rc; eType = sqlite3_value_type(pVal); h = sessionHashAppendType(h, eType); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ i64 iVal; if( eType==SQLITE_INTEGER ){ iVal = sqlite3_value_int64(pVal); }else{ double rVal = sqlite3_value_double(pVal); assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); memcpy(&iVal, &rVal, 8); } h = sessionHashAppendI64(h, iVal); }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ const u8 *z; int n; if( eType==SQLITE_TEXT ){ z = (const u8 *)sqlite3_value_text(pVal); }else{ z = (const u8 *)sqlite3_value_blob(pVal); } n = sqlite3_value_bytes(pVal); if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM; h = sessionHashAppendBlob(h, n, z); }else{ assert( eType==SQLITE_NULL ); *pbNullPK = 1; } } } *piHash = (h % pTab->nChange); return SQLITE_OK; } /* ** The buffer that the argument points to contains a serialized SQL value. ** Return the number of bytes of space occupied by the value (including ** the type byte). */ static int sessionSerialLen(u8 *a){ int e = *a; int n; if( e==0 ) return 1; if( e==SQLITE_NULL ) return 1; if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9; return sessionVarintGet(&a[1], &n) + 1 + n; } /* ** Based on the primary key values stored in change aRecord, calculate a ** hash key. Assume the has table has nBucket buckets. The hash keys ** calculated by this function are compatible with those calculated by ** sessionPreupdateHash(). ** ** The bPkOnly argument is non-zero if the record at aRecord[] is from ** a patchset DELETE. In this case the non-PK fields are omitted entirely. */ static unsigned int sessionChangeHash( SessionTable *pTab, /* Table handle */ int bPkOnly, /* Record consists of PK fields only */ u8 *aRecord, /* Change record */ int nBucket /* Assume this many buckets in hash table */ ){ unsigned int h = 0; /* Value to return */ int i; /* Used to iterate through columns */ u8 *a = aRecord; /* Used to iterate through change record */ for(i=0; i<pTab->nCol; i++){ int eType = *a; int isPK = pTab->abPK[i]; if( bPkOnly && isPK==0 ) continue; /* It is not possible for eType to be SQLITE_NULL here. The session ** module does not record changes for rows with NULL values stored in ** primary key columns. */ assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT || eType==SQLITE_TEXT || eType==SQLITE_BLOB || eType==SQLITE_NULL || eType==0 ); assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) ); if( isPK ){ a++; h = sessionHashAppendType(h, eType); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ h = sessionHashAppendI64(h, sessionGetI64(a)); a += 8; }else{ int n; a += sessionVarintGet(a, &n); h = sessionHashAppendBlob(h, n, a); a += n; } }else{ a += sessionSerialLen(a); } } return (h % nBucket); } /* ** Arguments aLeft and aRight are pointers to change records for table pTab. ** This function returns true if the two records apply to the same row (i.e. ** have the same values stored in the primary key columns), or false ** otherwise. */ static int sessionChangeEqual( SessionTable *pTab, /* Table used for PK definition */ int bLeftPkOnly, /* True if aLeft[] contains PK fields only */ u8 *aLeft, /* Change record */ int bRightPkOnly, /* True if aRight[] contains PK fields only */ u8 *aRight /* Change record */ ){ u8 *a1 = aLeft; /* Cursor to iterate through aLeft */ u8 *a2 = aRight; /* Cursor to iterate through aRight */ int iCol; /* Used to iterate through table columns */ for(iCol=0; iCol<pTab->nCol; iCol++){ if( pTab->abPK[iCol] ){ int n1 = sessionSerialLen(a1); int n2 = sessionSerialLen(a2); if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){ return 0; } a1 += n1; a2 += n2; }else{ if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1); if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2); } } return 1; } /* ** Arguments aLeft and aRight both point to buffers containing change ** records with nCol columns. This function "merges" the two records into ** a single records which is written to the buffer at *paOut. *paOut is ** then set to point to one byte after the last byte written before ** returning. ** ** The merging of records is done as follows: For each column, if the ** aRight record contains a value for the column, copy the value from ** their. Otherwise, if aLeft contains a value, copy it. If neither ** record contains a value for a given column, then neither does the ** output record. */ static void sessionMergeRecord( u8 **paOut, int nCol, u8 *aLeft, u8 *aRight ){ u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */ u8 *a2 = aRight; /* Cursor used to iterate through aRight */ u8 *aOut = *paOut; /* Output cursor */ int iCol; /* Used to iterate from 0 to nCol */ for(iCol=0; iCol<nCol; iCol++){ int n1 = sessionSerialLen(a1); int n2 = sessionSerialLen(a2); if( *a2 ){ memcpy(aOut, a2, n2); aOut += n2; }else{ memcpy(aOut, a1, n1); aOut += n1; } a1 += n1; a2 += n2; } *paOut = aOut; } /* ** This is a helper function used by sessionMergeUpdate(). ** ** When this function is called, both *paOne and *paTwo point to a value ** within a change record. Before it returns, both have been advanced so ** as to point to the next value in the record. ** ** If, when this function is called, *paTwo points to a valid value (i.e. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo ** pointer is returned and *pnVal is set to the number of bytes in the ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal ** set to the number of bytes in the value at *paOne. If *paOne points ** to the "no value" placeholder, *pnVal is set to 1. In other words: ** ** if( *paTwo is valid ) return *paTwo; ** return *paOne; ** */ static u8 *sessionMergeValue( u8 **paOne, /* IN/OUT: Left-hand buffer pointer */ u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */ int *pnVal /* OUT: Bytes in returned value */ ){ u8 *a1 = *paOne; u8 *a2 = *paTwo; u8 *pRet = 0; int n1; assert( a1 ); if( a2 ){ int n2 = sessionSerialLen(a2); if( *a2 ){ *pnVal = n2; pRet = a2; } *paTwo = &a2[n2]; } n1 = sessionSerialLen(a1); if( pRet==0 ){ *pnVal = n1; pRet = a1; } *paOne = &a1[n1]; return pRet; } /* ** This function is used by changeset_concat() to merge two UPDATE changes ** on the same row. */ static int sessionMergeUpdate( u8 **paOut, /* IN/OUT: Pointer to output buffer */ SessionTable *pTab, /* Table change pertains to */ int bPatchset, /* True if records are patchset records */ u8 *aOldRecord1, /* old.* record for first change */ u8 *aOldRecord2, /* old.* record for second change */ u8 *aNewRecord1, /* new.* record for first change */ u8 *aNewRecord2 /* new.* record for second change */ ){ u8 *aOld1 = aOldRecord1; u8 *aOld2 = aOldRecord2; u8 *aNew1 = aNewRecord1; u8 *aNew2 = aNewRecord2; u8 *aOut = *paOut; int i; if( bPatchset==0 ){ int bRequired = 0; assert( aOldRecord1 && aNewRecord1 ); /* Write the old.* vector first. */ for(i=0; i<pTab->nCol; i++){ int nOld; u8 *aOld; int nNew; u8 *aNew; aOld = sessionMergeValue(&aOld1, &aOld2, &nOld); aNew = sessionMergeValue(&aNew1, &aNew2, &nNew); if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){ if( pTab->abPK[i]==0 ) bRequired = 1; memcpy(aOut, aOld, nOld); aOut += nOld; }else{ *(aOut++) = '\0'; } } if( !bRequired ) return 0; } /* Write the new.* vector */ aOld1 = aOldRecord1; aOld2 = aOldRecord2; aNew1 = aNewRecord1; aNew2 = aNewRecord2; for(i=0; i<pTab->nCol; i++){ int nOld; u8 *aOld; int nNew; u8 *aNew; aOld = sessionMergeValue(&aOld1, &aOld2, &nOld); aNew = sessionMergeValue(&aNew1, &aNew2, &nNew); if( bPatchset==0 && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew))) ){ *(aOut++) = '\0'; }else{ memcpy(aOut, aNew, nNew); aOut += nNew; } } *paOut = aOut; return 1; } /* ** This function is only called from within a pre-update-hook callback. ** It determines if the current pre-update-hook change affects the same row ** as the change stored in argument pChange. If so, it returns true. Otherwise ** if the pre-update-hook does not affect the same row as pChange, it returns ** false. */ static int sessionPreupdateEqual( sqlite3_session *pSession, /* Session object that owns SessionTable */ SessionTable *pTab, /* Table associated with change */ SessionChange *pChange, /* Change to compare to */ int op /* Current pre-update operation */ ){ int iCol; /* Used to iterate through columns */ u8 *a = pChange->aRecord; /* Cursor used to scan change record */ assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); for(iCol=0; iCol<pTab->nCol; iCol++){ if( !pTab->abPK[iCol] ){ a += sessionSerialLen(a); }else{ sqlite3_value *pVal; /* Value returned by preupdate_new/old */ int rc; /* Error code from preupdate_new/old */ int eType = *a++; /* Type of value from change record */ /* The following calls to preupdate_new() and preupdate_old() can not ** fail. This is because they cache their return values, and by the ** time control flows to here they have already been called once from ** within sessionPreupdateHash(). The first two asserts below verify ** this (that the method has already been called). */ if( op==SQLITE_INSERT ){ /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */ rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal); }else{ /* assert( db->pPreUpdate->pUnpacked ); */ rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal); } assert( rc==SQLITE_OK ); if( sqlite3_value_type(pVal)!=eType ) return 0; /* A SessionChange object never has a NULL value in a PK column */ assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT || eType==SQLITE_BLOB || eType==SQLITE_TEXT ); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ i64 iVal = sessionGetI64(a); a += 8; if( eType==SQLITE_INTEGER ){ if( sqlite3_value_int64(pVal)!=iVal ) return 0; }else{ double rVal; assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); memcpy(&rVal, &iVal, 8); if( sqlite3_value_double(pVal)!=rVal ) return 0; } }else{ int n; const u8 *z; a += sessionVarintGet(a, &n); if( sqlite3_value_bytes(pVal)!=n ) return 0; if( eType==SQLITE_TEXT ){ z = sqlite3_value_text(pVal); }else{ z = sqlite3_value_blob(pVal); } if( memcmp(a, z, n) ) return 0; a += n; break; } } } return 1; } /* ** If required, grow the hash table used to store changes on table pTab ** (part of the session pSession). If a fatal OOM error occurs, set the ** session object to failed and return SQLITE_ERROR. Otherwise, return ** SQLITE_OK. ** ** It is possible that a non-fatal OOM error occurs in this function. In ** that case the hash-table does not grow, but SQLITE_OK is returned anyway. ** Growing the hash table in this case is a performance optimization only, ** it is not required for correct operation. */ static int sessionGrowHash(int bPatchset, SessionTable *pTab){ if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){ int i; SessionChange **apNew; int nNew = (pTab->nChange ? pTab->nChange : 128) * 2; apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew); if( apNew==0 ){ if( pTab->nChange==0 ){ return SQLITE_ERROR; } return SQLITE_OK; } memset(apNew, 0, sizeof(SessionChange *) * nNew); for(i=0; i<pTab->nChange; i++){ SessionChange *p; SessionChange *pNext; for(p=pTab->apChange[i]; p; p=pNext){ int bPkOnly = (p->op==SQLITE_DELETE && bPatchset); int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew); pNext = p->pNext; p->pNext = apNew[iHash]; apNew[iHash] = p; } } sqlite3_free(pTab->apChange); pTab->nChange = nNew; pTab->apChange = apNew; } return SQLITE_OK; } /* ** This function queries the database for the names of the columns of table ** zThis, in schema zDb. It is expected that the table has nCol columns. If ** not, SQLITE_SCHEMA is returned and none of the output variables are ** populated. ** ** Otherwise, if they are not NULL, variable *pnCol is set to the number ** of columns in the database table and variable *pzTab is set to point to a ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to ** point to an array of pointers to column names. And *pabPK (again, if not ** NULL) is set to point to an array of booleans - true if the corresponding ** column is part of the primary key. ** ** For example, if the table is declared as: ** ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z)); ** ** Then the four output variables are populated as follows: ** ** *pnCol = 4 ** *pzTab = "tbl1" ** *pazCol = {"w", "x", "y", "z"} ** *pabPK = {1, 0, 0, 1} ** ** All returned buffers are part of the same single allocation, which must ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then ** pointer *pazCol should be freed to release all memory. Otherwise, pointer ** *pabPK. It is illegal for both pazCol and pabPK to be NULL. */ static int sessionTableInfo( sqlite3 *db, /* Database connection */ const char *zDb, /* Name of attached database (e.g. "main") */ const char *zThis, /* Table name */ int *pnCol, /* OUT: number of columns */ const char **pzTab, /* OUT: Copy of zThis */ const char ***pazCol, /* OUT: Array of column names for table */ u8 **pabPK /* OUT: Array of booleans - true for PK col */ ){ char *zPragma; sqlite3_stmt *pStmt; int rc; int nByte; int nDbCol = 0; int nThis; int i; u8 *pAlloc = 0; char **azCol = 0; u8 *abPK = 0; assert( pazCol && pabPK ); nThis = sqlite3Strlen30(zThis); zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis); if( !zPragma ) return SQLITE_NOMEM; rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0); sqlite3_free(zPragma); if( rc!=SQLITE_OK ) return rc; nByte = nThis + 1; while( SQLITE_ROW==sqlite3_step(pStmt) ){ nByte += sqlite3_column_bytes(pStmt, 1); nDbCol++; } rc = sqlite3_reset(pStmt); if( rc==SQLITE_OK ){ nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1); pAlloc = sqlite3_malloc(nByte); if( pAlloc==0 ){ rc = SQLITE_NOMEM; } } if( rc==SQLITE_OK ){ azCol = (char **)pAlloc; pAlloc = (u8 *)&azCol[nDbCol]; abPK = (u8 *)pAlloc; pAlloc = &abPK[nDbCol]; if( pzTab ){ memcpy(pAlloc, zThis, nThis+1); *pzTab = (char *)pAlloc; pAlloc += nThis+1; } i = 0; while( SQLITE_ROW==sqlite3_step(pStmt) ){ int nName = sqlite3_column_bytes(pStmt, 1); const unsigned char *zName = sqlite3_column_text(pStmt, 1); if( zName==0 ) break; memcpy(pAlloc, zName, nName+1); azCol[i] = (char *)pAlloc; pAlloc += nName+1; abPK[i] = sqlite3_column_int(pStmt, 5); i++; } rc = sqlite3_reset(pStmt); } /* If successful, populate the output variables. Otherwise, zero them and ** free any allocation made. An error code will be returned in this case. */ if( rc==SQLITE_OK ){ *pazCol = (const char **)azCol; *pabPK = abPK; *pnCol = nDbCol; }else{ *pazCol = 0; *pabPK = 0; *pnCol = 0; if( pzTab ) *pzTab = 0; sqlite3_free(azCol); } sqlite3_finalize(pStmt); return rc; } /* ** This function is only called from within a pre-update handler for a ** write to table pTab, part of session pSession. If this is the first ** write to this table, initalize the SessionTable.nCol, azCol[] and ** abPK[] arrays accordingly. ** ** If an error occurs, an error code is stored in sqlite3_session.rc and ** non-zero returned. Or, if no error occurs but the table has no primary ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to ** indicate that updates on this table should be ignored. SessionTable.abPK ** is set to NULL in this case. */ static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){ if( pTab->nCol==0 ){ u8 *abPK; assert( pTab->azCol==0 || pTab->abPK==0 ); pSession->rc = sessionTableInfo(pSession->db, pSession->zDb, pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK ); if( pSession->rc==SQLITE_OK ){ int i; for(i=0; i<pTab->nCol; i++){ if( abPK[i] ){ pTab->abPK = abPK; break; } } } } return (pSession->rc || pTab->abPK==0); } /* ** This function is only called from with a pre-update-hook reporting a ** change on table pTab (attached to session pSession). The type of change ** (UPDATE, INSERT, DELETE) is specified by the first argument. ** ** Unless one is already present or an error occurs, an entry is added ** to the changed-rows hash table associated with table pTab. */ static void sessionPreupdateOneChange( int op, /* One of SQLITE_UPDATE, INSERT, DELETE */ sqlite3_session *pSession, /* Session object pTab is attached to */ SessionTable *pTab /* Table that change applies to */ ){ int iHash; int bNull = 0; int rc = SQLITE_OK; if( pSession->rc ) return; /* Load table details if required */ if( sessionInitTable(pSession, pTab) ) return; /* Check the number of columns in this xPreUpdate call matches the ** number of columns in the table. */ if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){ pSession->rc = SQLITE_SCHEMA; return; } /* Grow the hash table if required */ if( sessionGrowHash(0, pTab) ){ pSession->rc = SQLITE_NOMEM; return; } /* Calculate the hash-key for this change. If the primary key of the row ** includes a NULL value, exit early. Such changes are ignored by the ** session module. */ rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull); if( rc!=SQLITE_OK ) goto error_out; if( bNull==0 ){ /* Search the hash table for an existing record for this row. */ SessionChange *pC; for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){ if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break; } if( pC==0 ){ /* Create a new change object containing all the old values (if ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK ** values (if this is an INSERT). */ SessionChange *pChange; /* New change object */ int nByte; /* Number of bytes to allocate */ int i; /* Used to iterate through columns */ assert( rc==SQLITE_OK ); pTab->nEntry++; /* Figure out how large an allocation is required */ nByte = sizeof(SessionChange); for(i=0; i<pTab->nCol; i++){ sqlite3_value *p = 0; if( op!=SQLITE_INSERT ){ TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p); assert( trc==SQLITE_OK ); }else if( pTab->abPK[i] ){ TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p); assert( trc==SQLITE_OK ); } /* This may fail if SQLite value p contains a utf-16 string that must ** be converted to utf-8 and an OOM error occurs while doing so. */ rc = sessionSerializeValue(0, p, &nByte); if( rc!=SQLITE_OK ) goto error_out; } /* Allocate the change object */ pChange = (SessionChange *)sqlite3_malloc(nByte); if( !pChange ){ rc = SQLITE_NOMEM; goto error_out; }else{ memset(pChange, 0, sizeof(SessionChange)); pChange->aRecord = (u8 *)&pChange[1]; } /* Populate the change object. None of the preupdate_old(), ** preupdate_new() or SerializeValue() calls below may fail as all ** required values and encodings have already been cached in memory. ** It is not possible for an OOM to occur in this block. */ nByte = 0; for(i=0; i<pTab->nCol; i++){ sqlite3_value *p = 0; if( op!=SQLITE_INSERT ){ pSession->hook.xOld(pSession->hook.pCtx, i, &p); }else if( pTab->abPK[i] ){ pSession->hook.xNew(pSession->hook.pCtx, i, &p); } sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte); } /* Add the change to the hash-table */ if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){ pChange->bIndirect = 1; } pChange->nRecord = nByte; pChange->op = op; pChange->pNext = pTab->apChange[iHash]; pTab->apChange[iHash] = pChange; }else if( pC->bIndirect ){ /* If the existing change is considered "indirect", but this current ** change is "direct", mark the change object as direct. */ if( pSession->hook.xDepth(pSession->hook.pCtx)==0 && pSession->bIndirect==0 ){ pC->bIndirect = 0; } } } /* If an error has occurred, mark the session object as failed. */ error_out: if( rc!=SQLITE_OK ){ pSession->rc = rc; } } static int sessionFindTable( sqlite3_session *pSession, const char *zName, SessionTable **ppTab ){ int rc = SQLITE_OK; int nName = sqlite3Strlen30(zName); SessionTable *pRet; /* Search for an existing table */ for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){ if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break; } if( pRet==0 && pSession->bAutoAttach ){ /* If there is a table-filter configured, invoke it. If it returns 0, ** do not automatically add the new table. */ if( pSession->xTableFilter==0 || pSession->xTableFilter(pSession->pFilterCtx, zName) ){ rc = sqlite3session_attach(pSession, zName); if( rc==SQLITE_OK ){ for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext); assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ); } } } assert( rc==SQLITE_OK || pRet==0 ); *ppTab = pRet; return rc; } /* ** The 'pre-update' hook registered by this module with SQLite databases. */ static void xPreUpdate( void *pCtx, /* Copy of third arg to preupdate_hook() */ sqlite3 *db, /* Database handle */ int op, /* SQLITE_UPDATE, DELETE or INSERT */ char const *zDb, /* Database name */ char const *zName, /* Table name */ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ ){ sqlite3_session *pSession; int nDb = sqlite3Strlen30(zDb); assert( sqlite3_mutex_held(db->mutex) ); for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){ SessionTable *pTab; /* If this session is attached to a different database ("main", "temp" ** etc.), or if it is not currently enabled, there is nothing to do. Skip ** to the next session object attached to this database. */ if( pSession->bEnable==0 ) continue; if( pSession->rc ) continue; if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue; pSession->rc = sessionFindTable(pSession, zName, &pTab); if( pTab ){ assert( pSession->rc==SQLITE_OK ); sessionPreupdateOneChange(op, pSession, pTab); if( op==SQLITE_UPDATE ){ sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab); } } } } /* ** The pre-update hook implementations. */ static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){ return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal); } static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){ return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal); } static int sessionPreupdateCount(void *pCtx){ return sqlite3_preupdate_count((sqlite3*)pCtx); } static int sessionPreupdateDepth(void *pCtx){ return sqlite3_preupdate_depth((sqlite3*)pCtx); } /* ** Install the pre-update hooks on the session object passed as the only ** argument. */ static void sessionPreupdateHooks( sqlite3_session *pSession ){ pSession->hook.pCtx = (void*)pSession->db; pSession->hook.xOld = sessionPreupdateOld; pSession->hook.xNew = sessionPreupdateNew; pSession->hook.xCount = sessionPreupdateCount; pSession->hook.xDepth = sessionPreupdateDepth; } typedef struct SessionDiffCtx SessionDiffCtx; struct SessionDiffCtx { sqlite3_stmt *pStmt; int nOldOff; }; /* ** The diff hook implementations. */ static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){ SessionDiffCtx *p = (SessionDiffCtx*)pCtx; *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff); return SQLITE_OK; } static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){ SessionDiffCtx *p = (SessionDiffCtx*)pCtx; *ppVal = sqlite3_column_value(p->pStmt, iVal); return SQLITE_OK; } static int sessionDiffCount(void *pCtx){ SessionDiffCtx *p = (SessionDiffCtx*)pCtx; return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt); } static int sessionDiffDepth(void *pCtx){ return 0; } /* ** Install the diff hooks on the session object passed as the only ** argument. */ static void sessionDiffHooks( sqlite3_session *pSession, SessionDiffCtx *pDiffCtx ){ pSession->hook.pCtx = (void*)pDiffCtx; pSession->hook.xOld = sessionDiffOld; pSession->hook.xNew = sessionDiffNew; pSession->hook.xCount = sessionDiffCount; pSession->hook.xDepth = sessionDiffDepth; } static char *sessionExprComparePK( int nCol, const char *zDb1, const char *zDb2, const char *zTab, const char **azCol, u8 *abPK ){ int i; const char *zSep = ""; char *zRet = 0; for(i=0; i<nCol; i++){ if( abPK[i] ){ zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"", zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i] ); zSep = " AND "; if( zRet==0 ) break; } } return zRet; } static char *sessionExprCompareOther( int nCol, const char *zDb1, const char *zDb2, const char *zTab, const char **azCol, u8 *abPK ){ int i; const char *zSep = ""; char *zRet = 0; int bHave = 0; for(i=0; i<nCol; i++){ if( abPK[i]==0 ){ bHave = 1; zRet = sqlite3_mprintf( "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"", zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i] ); zSep = " OR "; if( zRet==0 ) break; } } if( bHave==0 ){ assert( zRet==0 ); zRet = sqlite3_mprintf("0"); } return zRet; } static char *sessionSelectFindNew( int nCol, const char *zDb1, /* Pick rows in this db only */ const char *zDb2, /* But not in this one */ const char *zTbl, /* Table name */ const char *zExpr ){ char *zRet = sqlite3_mprintf( "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS (" " SELECT 1 FROM \"%w\".\"%w\" WHERE %s" ")", zDb1, zTbl, zDb2, zTbl, zExpr ); return zRet; } static int sessionDiffFindNew( int op, sqlite3_session *pSession, SessionTable *pTab, const char *zDb1, const char *zDb2, char *zExpr ){ int rc = SQLITE_OK; char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr); if( zStmt==0 ){ rc = SQLITE_NOMEM; }else{ sqlite3_stmt *pStmt; rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); if( rc==SQLITE_OK ){ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; pDiffCtx->pStmt = pStmt; pDiffCtx->nOldOff = 0; while( SQLITE_ROW==sqlite3_step(pStmt) ){ sessionPreupdateOneChange(op, pSession, pTab); } rc = sqlite3_finalize(pStmt); } sqlite3_free(zStmt); } return rc; } static int sessionDiffFindModified( sqlite3_session *pSession, SessionTable *pTab, const char *zFrom, const char *zExpr ){ int rc = SQLITE_OK; char *zExpr2 = sessionExprCompareOther(pTab->nCol, pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK ); if( zExpr2==0 ){ rc = SQLITE_NOMEM; }else{ char *zStmt = sqlite3_mprintf( "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)", pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2 ); if( zStmt==0 ){ rc = SQLITE_NOMEM; }else{ sqlite3_stmt *pStmt; rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); if( rc==SQLITE_OK ){ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; pDiffCtx->pStmt = pStmt; pDiffCtx->nOldOff = pTab->nCol; while( SQLITE_ROW==sqlite3_step(pStmt) ){ sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab); } rc = sqlite3_finalize(pStmt); } sqlite3_free(zStmt); } } return rc; } SQLITE_API int sqlite3session_diff( sqlite3_session *pSession, const char *zFrom, const char *zTbl, char **pzErrMsg ){ const char *zDb = pSession->zDb; int rc = pSession->rc; SessionDiffCtx d; memset(&d, 0, sizeof(d)); sessionDiffHooks(pSession, &d); sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); if( pzErrMsg ) *pzErrMsg = 0; if( rc==SQLITE_OK ){ char *zExpr = 0; sqlite3 *db = pSession->db; SessionTable *pTo; /* Table zTbl */ /* Locate and if necessary initialize the target table object */ rc = sessionFindTable(pSession, zTbl, &pTo); if( pTo==0 ) goto diff_out; if( sessionInitTable(pSession, pTo) ){ rc = pSession->rc; goto diff_out; } /* Check the table schemas match */ if( rc==SQLITE_OK ){ int bHasPk = 0; int bMismatch = 0; int nCol; /* Columns in zFrom.zTbl */ u8 *abPK; const char **azCol = 0; rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK); if( rc==SQLITE_OK ){ if( pTo->nCol!=nCol ){ bMismatch = 1; }else{ int i; for(i=0; i<nCol; i++){ if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1; if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1; if( abPK[i] ) bHasPk = 1; } } } sqlite3_free((char*)azCol); if( bMismatch ){ *pzErrMsg = sqlite3_mprintf("table schemas do not match"); rc = SQLITE_SCHEMA; } if( bHasPk==0 ){ /* Ignore tables with no primary keys */ goto diff_out; } } if( rc==SQLITE_OK ){ zExpr = sessionExprComparePK(pTo->nCol, zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK ); } /* Find new rows */ if( rc==SQLITE_OK ){ rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr); } /* Find old rows */ if( rc==SQLITE_OK ){ rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr); } /* Find modified rows */ if( rc==SQLITE_OK ){ rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr); } sqlite3_free(zExpr); } diff_out: sessionPreupdateHooks(pSession); sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); return rc; } /* ** Create a session object. This session object will record changes to ** database zDb attached to connection db. */ SQLITE_API int sqlite3session_create( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ sqlite3_session **ppSession /* OUT: New session object */ ){ sqlite3_session *pNew; /* Newly allocated session object */ sqlite3_session *pOld; /* Session object already attached to db */ int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */ /* Zero the output value in case an error occurs. */ *ppSession = 0; /* Allocate and populate the new session object. */ pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1); if( !pNew ) return SQLITE_NOMEM; memset(pNew, 0, sizeof(sqlite3_session)); pNew->db = db; pNew->zDb = (char *)&pNew[1]; pNew->bEnable = 1; memcpy(pNew->zDb, zDb, nDb+1); sessionPreupdateHooks(pNew); /* Add the new session object to the linked list of session objects ** attached to database handle $db. Do this under the cover of the db ** handle mutex. */ sqlite3_mutex_enter(sqlite3_db_mutex(db)); pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew); pNew->pNext = pOld; sqlite3_mutex_leave(sqlite3_db_mutex(db)); *ppSession = pNew; return SQLITE_OK; } /* ** Free the list of table objects passed as the first argument. The contents ** of the changed-rows hash tables are also deleted. */ static void sessionDeleteTable(SessionTable *pList){ SessionTable *pNext; SessionTable *pTab; for(pTab=pList; pTab; pTab=pNext){ int i; pNext = pTab->pNext; for(i=0; i<pTab->nChange; i++){ SessionChange *p; SessionChange *pNextChange; for(p=pTab->apChange[i]; p; p=pNextChange){ pNextChange = p->pNext; sqlite3_free(p); } } sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */ sqlite3_free(pTab->apChange); sqlite3_free(pTab); } } /* ** Delete a session object previously allocated using sqlite3session_create(). */ SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){ sqlite3 *db = pSession->db; sqlite3_session *pHead; sqlite3_session **pp; /* Unlink the session from the linked list of sessions attached to the ** database handle. Hold the db mutex while doing so. */ sqlite3_mutex_enter(sqlite3_db_mutex(db)); pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0); for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){ if( (*pp)==pSession ){ *pp = (*pp)->pNext; if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead); break; } } sqlite3_mutex_leave(sqlite3_db_mutex(db)); /* Delete all attached table objects. And the contents of their ** associated hash-tables. */ sessionDeleteTable(pSession->pTable); /* Free the session object itself. */ sqlite3_free(pSession); } /* ** Set a table filter on a Session Object. */ SQLITE_API void sqlite3session_table_filter( sqlite3_session *pSession, int(*xFilter)(void*, const char*), void *pCtx /* First argument passed to xFilter */ ){ pSession->bAutoAttach = 1; pSession->pFilterCtx = pCtx; pSession->xTableFilter = xFilter; } /* ** Attach a table to a session. All subsequent changes made to the table ** while the session object is enabled will be recorded. ** ** Only tables that have a PRIMARY KEY defined may be attached. It does ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) ** or not. */ SQLITE_API int sqlite3session_attach( sqlite3_session *pSession, /* Session object */ const char *zName /* Table name */ ){ int rc = SQLITE_OK; sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); if( !zName ){ pSession->bAutoAttach = 1; }else{ SessionTable *pTab; /* New table object (if required) */ int nName; /* Number of bytes in string zName */ /* First search for an existing entry. If one is found, this call is ** a no-op. Return early. */ nName = sqlite3Strlen30(zName); for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){ if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break; } if( !pTab ){ /* Allocate new SessionTable object. */ pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1); if( !pTab ){ rc = SQLITE_NOMEM; }else{ /* Populate the new SessionTable object and link it into the list. ** The new object must be linked onto the end of the list, not ** simply added to the start of it in order to ensure that tables ** appear in the correct order when a changeset or patchset is ** eventually generated. */ SessionTable **ppTab; memset(pTab, 0, sizeof(SessionTable)); pTab->zName = (char *)&pTab[1]; memcpy(pTab->zName, zName, nName+1); for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext); *ppTab = pTab; } } } sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); return rc; } /* ** Ensure that there is room in the buffer to append nByte bytes of data. ** If not, use sqlite3_realloc() to grow the buffer so that there is. ** ** If successful, return zero. Otherwise, if an OOM condition is encountered, ** set *pRc to SQLITE_NOMEM and return non-zero. */ static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){ if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){ u8 *aNew; int nNew = p->nAlloc ? p->nAlloc : 128; do { nNew = nNew*2; }while( nNew<(p->nBuf+nByte) ); aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew); if( 0==aNew ){ *pRc = SQLITE_NOMEM; }else{ p->aBuf = aNew; p->nAlloc = nNew; } } return (*pRc!=SQLITE_OK); } /* ** Append the value passed as the second argument to the buffer passed ** as the first. ** ** This function is a no-op if *pRc is non-zero when it is called. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code ** before returning. */ static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){ int rc = *pRc; if( rc==SQLITE_OK ){ int nByte = 0; rc = sessionSerializeValue(0, pVal, &nByte); sessionBufferGrow(p, nByte, &rc); if( rc==SQLITE_OK ){ rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0); p->nBuf += nByte; }else{ *pRc = rc; } } } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append a single byte to the buffer. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){ if( 0==sessionBufferGrow(p, 1, pRc) ){ p->aBuf[p->nBuf++] = v; } } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append a single varint to the buffer. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){ if( 0==sessionBufferGrow(p, 9, pRc) ){ p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v); } } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append a blob of data to the buffer. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ static void sessionAppendBlob( SessionBuffer *p, const u8 *aBlob, int nBlob, int *pRc ){ if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){ memcpy(&p->aBuf[p->nBuf], aBlob, nBlob); p->nBuf += nBlob; } } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append a string to the buffer. All bytes in the string ** up to (but not including) the nul-terminator are written to the buffer. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ static void sessionAppendStr( SessionBuffer *p, const char *zStr, int *pRc ){ int nStr = sqlite3Strlen30(zStr); if( 0==sessionBufferGrow(p, nStr, pRc) ){ memcpy(&p->aBuf[p->nBuf], zStr, nStr); p->nBuf += nStr; } } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append the string representation of integer iVal ** to the buffer. No nul-terminator is written. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ static void sessionAppendInteger( SessionBuffer *p, /* Buffer to append to */ int iVal, /* Value to write the string rep. of */ int *pRc /* IN/OUT: Error code */ ){ char aBuf[24]; sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal); sessionAppendStr(p, aBuf, pRc); } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append the string zStr enclosed in quotes (") and ** with any embedded quote characters escaped to the buffer. No ** nul-terminator byte is written. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ static void sessionAppendIdent( SessionBuffer *p, /* Buffer to a append to */ const char *zStr, /* String to quote, escape and append */ int *pRc /* IN/OUT: Error code */ ){ int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1; if( 0==sessionBufferGrow(p, nStr, pRc) ){ char *zOut = (char *)&p->aBuf[p->nBuf]; const char *zIn = zStr; *zOut++ = '"'; while( *zIn ){ if( *zIn=='"' ) *zOut++ = '"'; *zOut++ = *(zIn++); } *zOut++ = '"'; p->nBuf = (int)((u8 *)zOut - p->aBuf); } } /* ** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwse, it appends the serialized version of the value stored ** in column iCol of the row that SQL statement pStmt currently points ** to to the buffer. */ static void sessionAppendCol( SessionBuffer *p, /* Buffer to append to */ sqlite3_stmt *pStmt, /* Handle pointing to row containing value */ int iCol, /* Column to read value from */ int *pRc /* IN/OUT: Error code */ ){ if( *pRc==SQLITE_OK ){ int eType = sqlite3_column_type(pStmt, iCol); sessionAppendByte(p, (u8)eType, pRc); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ sqlite3_int64 i; u8 aBuf[8]; if( eType==SQLITE_INTEGER ){ i = sqlite3_column_int64(pStmt, iCol); }else{ double r = sqlite3_column_double(pStmt, iCol); memcpy(&i, &r, 8); } sessionPutI64(aBuf, i); sessionAppendBlob(p, aBuf, 8, pRc); } if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){ u8 *z; int nByte; if( eType==SQLITE_BLOB ){ z = (u8 *)sqlite3_column_blob(pStmt, iCol); }else{ z = (u8 *)sqlite3_column_text(pStmt, iCol); } nByte = sqlite3_column_bytes(pStmt, iCol); if( z || (eType==SQLITE_BLOB && nByte==0) ){ sessionAppendVarint(p, nByte, pRc); sessionAppendBlob(p, z, nByte, pRc); }else{ *pRc = SQLITE_NOMEM; } } } } /* ** ** This function appends an update change to the buffer (see the comments ** under "CHANGESET FORMAT" at the top of the file). An update change ** consists of: ** ** 1 byte: SQLITE_UPDATE (0x17) ** n bytes: old.* record (see RECORD FORMAT) ** m bytes: new.* record (see RECORD FORMAT) ** ** The SessionChange object passed as the third argument contains the ** values that were stored in the row when the session began (the old.* ** values). The statement handle passed as the second argument points ** at the current version of the row (the new.* values). ** ** If all of the old.* values are equal to their corresponding new.* value ** (i.e. nothing has changed), then no data at all is appended to the buffer. ** ** Otherwise, the old.* record contains all primary key values and the ** original values of any fields that have been modified. The new.* record ** contains the new values of only those fields that have been modified. */ static int sessionAppendUpdate( SessionBuffer *pBuf, /* Buffer to append to */ int bPatchset, /* True for "patchset", 0 for "changeset" */ sqlite3_stmt *pStmt, /* Statement handle pointing at new row */ SessionChange *p, /* Object containing old values */ u8 *abPK /* Boolean array - true for PK columns */ ){ int rc = SQLITE_OK; SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */ int bNoop = 1; /* Set to zero if any values are modified */ int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */ int i; /* Used to iterate through columns */ u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */ sessionAppendByte(pBuf, SQLITE_UPDATE, &rc); sessionAppendByte(pBuf, p->bIndirect, &rc); for(i=0; i<sqlite3_column_count(pStmt); i++){ int bChanged = 0; int nAdvance; int eType = *pCsr; switch( eType ){ case SQLITE_NULL: nAdvance = 1; if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){ bChanged = 1; } break; case SQLITE_FLOAT: case SQLITE_INTEGER: { nAdvance = 9; if( eType==sqlite3_column_type(pStmt, i) ){ sqlite3_int64 iVal = sessionGetI64(&pCsr[1]); if( eType==SQLITE_INTEGER ){ if( iVal==sqlite3_column_int64(pStmt, i) ) break; }else{ double dVal; memcpy(&dVal, &iVal, 8); if( dVal==sqlite3_column_double(pStmt, i) ) break; } } bChanged = 1; break; } default: { int n; int nHdr = 1 + sessionVarintGet(&pCsr[1], &n); assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); nAdvance = nHdr + n; if( eType==sqlite3_column_type(pStmt, i) && n==sqlite3_column_bytes(pStmt, i) && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n)) ){ break; } bChanged = 1; } } /* If at least one field has been modified, this is not a no-op. */ if( bChanged ) bNoop = 0; /* Add a field to the old.* record. This is omitted if this modules is ** currently generating a patchset. */ if( bPatchset==0 ){ if( bChanged || abPK[i] ){ sessionAppendBlob(pBuf, pCsr, nAdvance, &rc); }else{ sessionAppendByte(pBuf, 0, &rc); } } /* Add a field to the new.* record. Or the only record if currently ** generating a patchset. */ if( bChanged || (bPatchset && abPK[i]) ){ sessionAppendCol(&buf2, pStmt, i, &rc); }else{ sessionAppendByte(&buf2, 0, &rc); } pCsr += nAdvance; } if( bNoop ){ pBuf->nBuf = nRewind; }else{ sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc); } sqlite3_free(buf2.aBuf); return rc; } /* ** Append a DELETE change to the buffer passed as the first argument. Use ** the changeset format if argument bPatchset is zero, or the patchset ** format otherwise. */ static int sessionAppendDelete( SessionBuffer *pBuf, /* Buffer to append to */ int bPatchset, /* True for "patchset", 0 for "changeset" */ SessionChange *p, /* Object containing old values */ int nCol, /* Number of columns in table */ u8 *abPK /* Boolean array - true for PK columns */ ){ int rc = SQLITE_OK; sessionAppendByte(pBuf, SQLITE_DELETE, &rc); sessionAppendByte(pBuf, p->bIndirect, &rc); if( bPatchset==0 ){ sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc); }else{ int i; u8 *a = p->aRecord; for(i=0; i<nCol; i++){ u8 *pStart = a; int eType = *a++; switch( eType ){ case 0: case SQLITE_NULL: assert( abPK[i]==0 ); break; case SQLITE_FLOAT: case SQLITE_INTEGER: a += 8; break; default: { int n; a += sessionVarintGet(a, &n); a += n; break; } } if( abPK[i] ){ sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc); } } assert( (a - p->aRecord)==p->nRecord ); } return rc; } /* ** Formulate and prepare a SELECT statement to retrieve a row from table ** zTab in database zDb based on its primary key. i.e. ** ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ... */ static int sessionSelectStmt( sqlite3 *db, /* Database handle */ const char *zDb, /* Database name */ const char *zTab, /* Table name */ int nCol, /* Number of columns in table */ const char **azCol, /* Names of table columns */ u8 *abPK, /* PRIMARY KEY array */ sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */ ){ int rc = SQLITE_OK; int i; const char *zSep = ""; SessionBuffer buf = {0, 0, 0}; sessionAppendStr(&buf, "SELECT * FROM ", &rc); sessionAppendIdent(&buf, zDb, &rc); sessionAppendStr(&buf, ".", &rc); sessionAppendIdent(&buf, zTab, &rc); sessionAppendStr(&buf, " WHERE ", &rc); for(i=0; i<nCol; i++){ if( abPK[i] ){ sessionAppendStr(&buf, zSep, &rc); sessionAppendIdent(&buf, azCol[i], &rc); sessionAppendStr(&buf, " = ?", &rc); sessionAppendInteger(&buf, i+1, &rc); zSep = " AND "; } } if( rc==SQLITE_OK ){ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0); } sqlite3_free(buf.aBuf); return rc; } /* ** Bind the PRIMARY KEY values from the change passed in argument pChange ** to the SELECT statement passed as the first argument. The SELECT statement ** is as prepared by function sessionSelectStmt(). ** ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite ** error code (e.g. SQLITE_NOMEM) otherwise. */ static int sessionSelectBind( sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */ int nCol, /* Number of columns in table */ u8 *abPK, /* PRIMARY KEY array */ SessionChange *pChange /* Change structure */ ){ int i; int rc = SQLITE_OK; u8 *a = pChange->aRecord; for(i=0; i<nCol && rc==SQLITE_OK; i++){ int eType = *a++; switch( eType ){ case 0: case SQLITE_NULL: assert( abPK[i]==0 ); break; case SQLITE_INTEGER: { if( abPK[i] ){ i64 iVal = sessionGetI64(a); rc = sqlite3_bind_int64(pSelect, i+1, iVal); } a += 8; break; } case SQLITE_FLOAT: { if( abPK[i] ){ double rVal; i64 iVal = sessionGetI64(a); memcpy(&rVal, &iVal, 8); rc = sqlite3_bind_double(pSelect, i+1, rVal); } a += 8; break; } case SQLITE_TEXT: { int n; a += sessionVarintGet(a, &n); if( abPK[i] ){ rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT); } a += n; break; } default: { int n; assert( eType==SQLITE_BLOB ); a += sessionVarintGet(a, &n); if( abPK[i] ){ rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT); } a += n; break; } } } return rc; } /* ** This function is a no-op if *pRc is set to other than SQLITE_OK when it ** is called. Otherwise, append a serialized table header (part of the binary ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an ** SQLite error code before returning. */ static void sessionAppendTableHdr( SessionBuffer *pBuf, /* Append header to this buffer */ int bPatchset, /* Use the patchset format if true */ SessionTable *pTab, /* Table object to append header for */ int *pRc /* IN/OUT: Error code */ ){ /* Write a table header */ sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc); sessionAppendVarint(pBuf, pTab->nCol, pRc); sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc); sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc); } /* ** Generate either a changeset (if argument bPatchset is zero) or a patchset ** (if it is non-zero) based on the current contents of the session object ** passed as the first argument. ** ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error ** occurs, an SQLite error code is returned and both output variables set ** to 0. */ static int sessionGenerateChangeset( sqlite3_session *pSession, /* Session object */ int bPatchset, /* True for patchset, false for changeset */ int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut, /* First argument for xOutput */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ){ sqlite3 *db = pSession->db; /* Source database handle */ SessionTable *pTab; /* Used to iterate through attached tables */ SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */ int rc; /* Return code */ assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) ); /* Zero the output variables in case an error occurs. If this session ** object is already in the error state (sqlite3_session.rc != SQLITE_OK), ** this call will be a no-op. */ if( xOutput==0 ){ *pnChangeset = 0; *ppChangeset = 0; } if( pSession->rc ) return pSession->rc; rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0); if( rc!=SQLITE_OK ) return rc; sqlite3_mutex_enter(sqlite3_db_mutex(db)); for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){ if( pTab->nEntry ){ const char *zName = pTab->zName; int nCol; /* Number of columns in table */ u8 *abPK; /* Primary key array */ const char **azCol = 0; /* Table columns */ int i; /* Used to iterate through hash buckets */ sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */ int nRewind = buf.nBuf; /* Initial size of write buffer */ int nNoop; /* Size of buffer after writing tbl header */ /* Check the table schema is still Ok. */ rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK); if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){ rc = SQLITE_SCHEMA; } /* Write a table header */ sessionAppendTableHdr(&buf, bPatchset, pTab, &rc); /* Build and compile a statement to execute: */ if( rc==SQLITE_OK ){ rc = sessionSelectStmt( db, pSession->zDb, zName, nCol, azCol, abPK, &pSel); } nNoop = buf.nBuf; for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){ SessionChange *p; /* Used to iterate through changes */ for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){ rc = sessionSelectBind(pSel, nCol, abPK, p); if( rc!=SQLITE_OK ) continue; if( sqlite3_step(pSel)==SQLITE_ROW ){ if( p->op==SQLITE_INSERT ){ int iCol; sessionAppendByte(&buf, SQLITE_INSERT, &rc); sessionAppendByte(&buf, p->bIndirect, &rc); for(iCol=0; iCol<nCol; iCol++){ sessionAppendCol(&buf, pSel, iCol, &rc); } }else{ rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK); } }else if( p->op!=SQLITE_INSERT ){ rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK); } if( rc==SQLITE_OK ){ rc = sqlite3_reset(pSel); } /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass ** its contents to the xOutput() callback. */ if( xOutput && rc==SQLITE_OK && buf.nBuf>nNoop && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE ){ rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf); nNoop = -1; buf.nBuf = 0; } } } sqlite3_finalize(pSel); if( buf.nBuf==nNoop ){ buf.nBuf = nRewind; } sqlite3_free((char*)azCol); /* cast works around VC++ bug */ } } if( rc==SQLITE_OK ){ if( xOutput==0 ){ *pnChangeset = buf.nBuf; *ppChangeset = buf.aBuf; buf.aBuf = 0; }else if( buf.nBuf>0 ){ rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf); } } sqlite3_free(buf.aBuf); sqlite3_exec(db, "RELEASE changeset", 0, 0, 0); sqlite3_mutex_leave(sqlite3_db_mutex(db)); return rc; } /* ** Obtain a changeset object containing all changes recorded by the ** session object passed as the first argument. ** ** It is the responsibility of the caller to eventually free the buffer ** using sqlite3_free(). */ SQLITE_API int sqlite3session_changeset( sqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ){ return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset); } /* ** Streaming version of sqlite3session_changeset(). */ SQLITE_API int sqlite3session_changeset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0); } /* ** Streaming version of sqlite3session_patchset(). */ SQLITE_API int sqlite3session_patchset_strm( sqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0); } /* ** Obtain a patchset object containing all changes recorded by the ** session object passed as the first argument. ** ** It is the responsibility of the caller to eventually free the buffer ** using sqlite3_free(). */ SQLITE_API int sqlite3session_patchset( sqlite3_session *pSession, /* Session object */ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ void **ppPatchset /* OUT: Buffer containing changeset */ ){ return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset); } /* ** Enable or disable the session object passed as the first argument. */ SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){ int ret; sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); if( bEnable>=0 ){ pSession->bEnable = bEnable; } ret = pSession->bEnable; sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); return ret; } /* ** Enable or disable the session object passed as the first argument. */ SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){ int ret; sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); if( bIndirect>=0 ){ pSession->bIndirect = bIndirect; } ret = pSession->bIndirect; sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); return ret; } /* ** Return true if there have been no changes to monitored tables recorded ** by the session object passed as the only argument. */ SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){ int ret = 0; SessionTable *pTab; sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){ ret = (pTab->nEntry>0); } sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); return (ret==0); } /* ** Do the work for either sqlite3changeset_start() or start_strm(). */ static int sessionChangesetStart( sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int nChangeset, /* Size of buffer pChangeset in bytes */ void *pChangeset /* Pointer to buffer containing changeset */ ){ sqlite3_changeset_iter *pRet; /* Iterator to return */ int nByte; /* Number of bytes to allocate for iterator */ assert( xInput==0 || (pChangeset==0 && nChangeset==0) ); /* Zero the output variable in case an error occurs. */ *pp = 0; /* Allocate and initialize the iterator structure. */ nByte = sizeof(sqlite3_changeset_iter); pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte); if( !pRet ) return SQLITE_NOMEM; memset(pRet, 0, sizeof(sqlite3_changeset_iter)); pRet->in.aData = (u8 *)pChangeset; pRet->in.nData = nChangeset; pRet->in.xInput = xInput; pRet->in.pIn = pIn; pRet->in.bEof = (xInput ? 0 : 1); /* Populate the output variable and return success. */ *pp = pRet; return SQLITE_OK; } /* ** Create an iterator used to iterate through the contents of a changeset. */ SQLITE_API int sqlite3changeset_start( sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ int nChangeset, /* Size of buffer pChangeset in bytes */ void *pChangeset /* Pointer to buffer containing changeset */ ){ return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset); } /* ** Streaming version of sqlite3changeset_start(). */ SQLITE_API int sqlite3changeset_start_strm( sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ){ return sessionChangesetStart(pp, xInput, pIn, 0, 0); } /* ** If the SessionInput object passed as the only argument is a streaming ** object and the buffer is full, discard some data to free up space. */ static void sessionDiscardData(SessionInput *pIn){ if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){ int nMove = pIn->buf.nBuf - pIn->iNext; assert( nMove>=0 ); if( nMove>0 ){ memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove); } pIn->buf.nBuf -= pIn->iNext; pIn->iNext = 0; pIn->nData = pIn->buf.nBuf; } } /* ** Ensure that there are at least nByte bytes available in the buffer. Or, ** if there are not nByte bytes remaining in the input, that all available ** data is in the buffer. ** ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise. */ static int sessionInputBuffer(SessionInput *pIn, int nByte){ int rc = SQLITE_OK; if( pIn->xInput ){ while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){ int nNew = SESSIONS_STRM_CHUNK_SIZE; if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn); if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){ rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew); if( nNew==0 ){ pIn->bEof = 1; }else{ pIn->buf.nBuf += nNew; } } pIn->aData = pIn->buf.aBuf; pIn->nData = pIn->buf.nBuf; } } return rc; } /* ** When this function is called, *ppRec points to the start of a record ** that contains nCol values. This function advances the pointer *ppRec ** until it points to the byte immediately following that record. */ static void sessionSkipRecord( u8 **ppRec, /* IN/OUT: Record pointer */ int nCol /* Number of values in record */ ){ u8 *aRec = *ppRec; int i; for(i=0; i<nCol; i++){ int eType = *aRec++; if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ int nByte; aRec += sessionVarintGet((u8*)aRec, &nByte); aRec += nByte; }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ aRec += 8; } } *ppRec = aRec; } /* ** This function sets the value of the sqlite3_value object passed as the ** first argument to a copy of the string or blob held in the aData[] ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM ** error occurs. */ static int sessionValueSetStr( sqlite3_value *pVal, /* Set the value of this object */ u8 *aData, /* Buffer containing string or blob data */ int nData, /* Size of buffer aData[] in bytes */ u8 enc /* String encoding (0 for blobs) */ ){ /* In theory this code could just pass SQLITE_TRANSIENT as the final ** argument to sqlite3ValueSetStr() and have the copy created ** automatically. But doing so makes it difficult to detect any OOM ** error. Hence the code to create the copy externally. */ u8 *aCopy = sqlite3_malloc(nData+1); if( aCopy==0 ) return SQLITE_NOMEM; memcpy(aCopy, aData, nData); sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free); return SQLITE_OK; } /* ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT" ** for details. ** ** When this function is called, *paChange points to the start of the record ** to deserialize. Assuming no error occurs, *paChange is set to point to ** one byte after the end of the same record before this function returns. ** If the argument abPK is NULL, then the record contains nCol values. Or, ** if abPK is other than NULL, then the record contains only the PK fields ** (in other words, it is a patchset DELETE record). ** ** If successful, each element of the apOut[] array (allocated by the caller) ** is set to point to an sqlite3_value object containing the value read ** from the corresponding position in the record. If that value is not ** included in the record (i.e. because the record is part of an UPDATE change ** and the field was not modified), the corresponding element of apOut[] is ** set to NULL. ** ** It is the responsibility of the caller to free all sqlite_value structures ** using sqlite3_free(). ** ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. ** The apOut[] array may have been partially populated in this case. */ static int sessionReadRecord( SessionInput *pIn, /* Input data */ int nCol, /* Number of values in record */ u8 *abPK, /* Array of primary key flags, or NULL */ sqlite3_value **apOut /* Write values to this array */ ){ int i; /* Used to iterate through columns */ int rc = SQLITE_OK; for(i=0; i<nCol && rc==SQLITE_OK; i++){ int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */ if( abPK && abPK[i]==0 ) continue; rc = sessionInputBuffer(pIn, 9); if( rc==SQLITE_OK ){ eType = pIn->aData[pIn->iNext++]; } assert( apOut[i]==0 ); if( eType ){ apOut[i] = sqlite3ValueNew(0); if( !apOut[i] ) rc = SQLITE_NOMEM; } if( rc==SQLITE_OK ){ u8 *aVal = &pIn->aData[pIn->iNext]; if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ int nByte; pIn->iNext += sessionVarintGet(aVal, &nByte); rc = sessionInputBuffer(pIn, nByte); if( rc==SQLITE_OK ){ u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0); rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc); } pIn->iNext += nByte; } if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ sqlite3_int64 v = sessionGetI64(aVal); if( eType==SQLITE_INTEGER ){ sqlite3VdbeMemSetInt64(apOut[i], v); }else{ double d; memcpy(&d, &v, 8); sqlite3VdbeMemSetDouble(apOut[i], d); } pIn->iNext += 8; } } } return rc; } /* ** The input pointer currently points to the second byte of a table-header. ** Specifically, to the following: ** ** + number of columns in table (varint) ** + array of PK flags (1 byte per column), ** + table name (nul terminated). ** ** This function ensures that all of the above is present in the input ** buffer (i.e. that it can be accessed without any calls to xInput()). ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. ** The input pointer is not moved. */ static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){ int rc = SQLITE_OK; int nCol = 0; int nRead = 0; rc = sessionInputBuffer(pIn, 9); if( rc==SQLITE_OK ){ nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol); rc = sessionInputBuffer(pIn, nRead+nCol+100); nRead += nCol; } while( rc==SQLITE_OK ){ while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){ nRead++; } if( (pIn->iNext + nRead)<pIn->nData ) break; rc = sessionInputBuffer(pIn, nRead + 100); } *pnByte = nRead+1; return rc; } /* ** The input pointer currently points to the first byte of the first field ** of a record consisting of nCol columns. This function ensures the entire ** record is buffered. It does not move the input pointer. ** ** If successful, SQLITE_OK is returned and *pnByte is set to the size of ** the record in bytes. Otherwise, an SQLite error code is returned. The ** final value of *pnByte is undefined in this case. */ static int sessionChangesetBufferRecord( SessionInput *pIn, /* Input data */ int nCol, /* Number of columns in record */ int *pnByte /* OUT: Size of record in bytes */ ){ int rc = SQLITE_OK; int nByte = 0; int i; for(i=0; rc==SQLITE_OK && i<nCol; i++){ int eType; rc = sessionInputBuffer(pIn, nByte + 10); if( rc==SQLITE_OK ){ eType = pIn->aData[pIn->iNext + nByte++]; if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ int n; nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n); nByte += n; rc = sessionInputBuffer(pIn, nByte); }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ nByte += 8; } } } *pnByte = nByte; return rc; } /* ** The input pointer currently points to the second byte of a table-header. ** Specifically, to the following: ** ** + number of columns in table (varint) ** + array of PK flags (1 byte per column), ** + table name (nul terminated). ** ** This function decodes the table-header and populates the p->nCol, ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is ** also allocated or resized according to the new value of p->nCol. The ** input pointer is left pointing to the byte following the table header. ** ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code ** is returned and the final values of the various fields enumerated above ** are undefined. */ static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ int rc; int nCopy; assert( p->rc==SQLITE_OK ); rc = sessionChangesetBufferTblhdr(&p->in, &nCopy); if( rc==SQLITE_OK ){ int nByte; int nVarint; nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol); nCopy -= nVarint; p->in.iNext += nVarint; nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy; p->tblhdr.nBuf = 0; sessionBufferGrow(&p->tblhdr, nByte, &rc); } if( rc==SQLITE_OK ){ int iPK = sizeof(sqlite3_value*)*p->nCol*2; memset(p->tblhdr.aBuf, 0, iPK); memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy); p->in.iNext += nCopy; } p->apValue = (sqlite3_value**)p->tblhdr.aBuf; p->abPK = (u8*)&p->apValue[p->nCol*2]; p->zTab = (char*)&p->abPK[p->nCol]; return (p->rc = rc); } /* ** Advance the changeset iterator to the next change. ** ** If both paRec and pnRec are NULL, then this function works like the public ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the ** sqlite3changeset_new() and old() APIs may be used to query for values. ** ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change ** record is written to *paRec before returning and the number of bytes in ** the record to *pnRec. ** ** Either way, this function returns SQLITE_ROW if the iterator is ** successfully advanced to the next change in the changeset, an SQLite ** error code if an error occurs, or SQLITE_DONE if there are no further ** changes in the changeset. */ static int sessionChangesetNext( sqlite3_changeset_iter *p, /* Changeset iterator */ u8 **paRec, /* If non-NULL, store record pointer here */ int *pnRec /* If non-NULL, store size of record here */ ){ int i; u8 op; assert( (paRec==0 && pnRec==0) || (paRec && pnRec) ); /* If the iterator is in the error-state, return immediately. */ if( p->rc!=SQLITE_OK ) return p->rc; /* Free the current contents of p->apValue[], if any. */ if( p->apValue ){ for(i=0; i<p->nCol*2; i++){ sqlite3ValueFree(p->apValue[i]); } memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2); } /* Make sure the buffer contains at least 10 bytes of input data, or all ** remaining data if there are less than 10 bytes available. This is ** sufficient either for the 'T' or 'P' byte and the varint that follows ** it, or for the two single byte values otherwise. */ p->rc = sessionInputBuffer(&p->in, 2); if( p->rc!=SQLITE_OK ) return p->rc; /* If the iterator is already at the end of the changeset, return DONE. */ if( p->in.iNext>=p->in.nData ){ return SQLITE_DONE; } sessionDiscardData(&p->in); p->in.iCurrent = p->in.iNext; op = p->in.aData[p->in.iNext++]; if( op=='T' || op=='P' ){ p->bPatchset = (op=='P'); if( sessionChangesetReadTblhdr(p) ) return p->rc; if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc; p->in.iCurrent = p->in.iNext; op = p->in.aData[p->in.iNext++]; } p->op = op; p->bIndirect = p->in.aData[p->in.iNext++]; if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){ return (p->rc = SQLITE_CORRUPT_BKPT); } if( paRec ){ int nVal; /* Number of values to buffer */ if( p->bPatchset==0 && op==SQLITE_UPDATE ){ nVal = p->nCol * 2; }else if( p->bPatchset && op==SQLITE_DELETE ){ nVal = 0; for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++; }else{ nVal = p->nCol; } p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec); if( p->rc!=SQLITE_OK ) return p->rc; *paRec = &p->in.aData[p->in.iNext]; p->in.iNext += *pnRec; }else{ /* If this is an UPDATE or DELETE, read the old.* record. */ if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){ u8 *abPK = p->bPatchset ? p->abPK : 0; p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue); if( p->rc!=SQLITE_OK ) return p->rc; } /* If this is an INSERT or UPDATE, read the new.* record. */ if( p->op!=SQLITE_DELETE ){ p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]); if( p->rc!=SQLITE_OK ) return p->rc; } if( p->bPatchset && p->op==SQLITE_UPDATE ){ /* If this is an UPDATE that is part of a patchset, then all PK and ** modified fields are present in the new.* record. The old.* record ** is currently completely empty. This block shifts the PK fields from ** new.* to old.*, to accommodate the code that reads these arrays. */ for(i=0; i<p->nCol; i++){ assert( p->apValue[i]==0 ); assert( p->abPK[i]==0 || p->apValue[i+p->nCol] ); if( p->abPK[i] ){ p->apValue[i] = p->apValue[i+p->nCol]; p->apValue[i+p->nCol] = 0; } } } } return SQLITE_ROW; } /* ** Advance an iterator created by sqlite3changeset_start() to the next ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE ** or SQLITE_CORRUPT. ** ** This function may not be called on iterators passed to a conflict handler ** callback by changeset_apply(). */ SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){ return sessionChangesetNext(p, 0, 0); } /* ** The following function extracts information on the current change ** from a changeset iterator. It may only be called after changeset_next() ** has returned SQLITE_ROW. */ SQLITE_API int sqlite3changeset_op( sqlite3_changeset_iter *pIter, /* Iterator handle */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ int *pbIndirect /* OUT: True if change is indirect */ ){ *pOp = pIter->op; *pnCol = pIter->nCol; *pzTab = pIter->zTab; if( pbIndirect ) *pbIndirect = pIter->bIndirect; return SQLITE_OK; } /* ** Return information regarding the PRIMARY KEY and number of columns in ** the database table affected by the change that pIter currently points ** to. This function may only be called after changeset_next() returns ** SQLITE_ROW. */ SQLITE_API int sqlite3changeset_pk( sqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ){ *pabPK = pIter->abPK; if( pnCol ) *pnCol = pIter->nCol; return SQLITE_OK; } /* ** This function may only be called while the iterator is pointing to an ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()). ** Otherwise, SQLITE_MISUSE is returned. ** ** It sets *ppValue to point to an sqlite3_value structure containing the ** iVal'th value in the old.* record. Or, if that particular value is not ** included in the record (because the change is an UPDATE and the field ** was not modified and is not a PK column), set *ppValue to NULL. ** ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is ** not modified. Otherwise, SQLITE_OK. */ SQLITE_API int sqlite3changeset_old( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Index of old.* value to retrieve */ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ){ if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){ return SQLITE_MISUSE; } if( iVal<0 || iVal>=pIter->nCol ){ return SQLITE_RANGE; } *ppValue = pIter->apValue[iVal]; return SQLITE_OK; } /* ** This function may only be called while the iterator is pointing to an ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()). ** Otherwise, SQLITE_MISUSE is returned. ** ** It sets *ppValue to point to an sqlite3_value structure containing the ** iVal'th value in the new.* record. Or, if that particular value is not ** included in the record (because the change is an UPDATE and the field ** was not modified), set *ppValue to NULL. ** ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is ** not modified. Otherwise, SQLITE_OK. */ SQLITE_API int sqlite3changeset_new( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Index of new.* value to retrieve */ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ){ if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){ return SQLITE_MISUSE; } if( iVal<0 || iVal>=pIter->nCol ){ return SQLITE_RANGE; } *ppValue = pIter->apValue[pIter->nCol+iVal]; return SQLITE_OK; } /* ** The following two macros are used internally. They are similar to the ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that ** they omit all error checking and return a pointer to the requested value. */ #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)] #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)] /* ** This function may only be called with a changeset iterator that has been ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned. ** ** If successful, *ppValue is set to point to an sqlite3_value structure ** containing the iVal'th value of the conflicting record. ** ** If value iVal is out-of-range or some other error occurs, an SQLite error ** code is returned. Otherwise, SQLITE_OK. */ SQLITE_API int sqlite3changeset_conflict( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Index of conflict record value to fetch */ sqlite3_value **ppValue /* OUT: Value from conflicting row */ ){ if( !pIter->pConflict ){ return SQLITE_MISUSE; } if( iVal<0 || iVal>=pIter->nCol ){ return SQLITE_RANGE; } *ppValue = sqlite3_column_value(pIter->pConflict, iVal); return SQLITE_OK; } /* ** This function may only be called with an iterator passed to an ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case ** it sets the output variable to the total number of known foreign key ** violations in the destination database and returns SQLITE_OK. ** ** In all other cases this function returns SQLITE_MISUSE. */ SQLITE_API int sqlite3changeset_fk_conflicts( sqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ){ if( pIter->pConflict || pIter->apValue ){ return SQLITE_MISUSE; } *pnOut = pIter->nCol; return SQLITE_OK; } /* ** Finalize an iterator allocated with sqlite3changeset_start(). ** ** This function may not be called on iterators passed to a conflict handler ** callback by changeset_apply(). */ SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){ int rc = SQLITE_OK; if( p ){ int i; /* Used to iterate through p->apValue[] */ rc = p->rc; if( p->apValue ){ for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]); } sqlite3_free(p->tblhdr.aBuf); sqlite3_free(p->in.buf.aBuf); sqlite3_free(p); } return rc; } static int sessionChangesetInvert( SessionInput *pInput, /* Input changeset */ int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut, int *pnInverted, /* OUT: Number of bytes in output changeset */ void **ppInverted /* OUT: Inverse of pChangeset */ ){ int rc = SQLITE_OK; /* Return value */ SessionBuffer sOut; /* Output buffer */ int nCol = 0; /* Number of cols in current table */ u8 *abPK = 0; /* PK array for current table */ sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */ SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */ /* Initialize the output buffer */ memset(&sOut, 0, sizeof(SessionBuffer)); /* Zero the output variables in case an error occurs. */ if( ppInverted ){ *ppInverted = 0; *pnInverted = 0; } while( 1 ){ u8 eType; /* Test for EOF. */ if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert; if( pInput->iNext>=pInput->nData ) break; eType = pInput->aData[pInput->iNext]; switch( eType ){ case 'T': { /* A 'table' record consists of: ** ** * A constant 'T' character, ** * Number of columns in said table (a varint), ** * An array of nCol bytes (sPK), ** * A nul-terminated table name. */ int nByte; int nVar; pInput->iNext++; if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){ goto finished_invert; } nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol); sPK.nBuf = 0; sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc); sessionAppendByte(&sOut, eType, &rc); sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc); if( rc ) goto finished_invert; pInput->iNext += nByte; sqlite3_free(apVal); apVal = 0; abPK = sPK.aBuf; break; } case SQLITE_INSERT: case SQLITE_DELETE: { int nByte; int bIndirect = pInput->aData[pInput->iNext+1]; int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE); pInput->iNext += 2; assert( rc==SQLITE_OK ); rc = sessionChangesetBufferRecord(pInput, nCol, &nByte); sessionAppendByte(&sOut, eType2, &rc); sessionAppendByte(&sOut, bIndirect, &rc); sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc); pInput->iNext += nByte; if( rc ) goto finished_invert; break; } case SQLITE_UPDATE: { int iCol; if( 0==apVal ){ apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2); if( 0==apVal ){ rc = SQLITE_NOMEM; goto finished_invert; } memset(apVal, 0, sizeof(apVal[0])*nCol*2); } /* Write the header for the new UPDATE change. Same as the original. */ sessionAppendByte(&sOut, eType, &rc); sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc); /* Read the old.* and new.* records for the update change. */ pInput->iNext += 2; rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]); if( rc==SQLITE_OK ){ rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]); } /* Write the new old.* record. Consists of the PK columns from the ** original old.* record, and the other values from the original ** new.* record. */ for(iCol=0; iCol<nCol; iCol++){ sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)]; sessionAppendValue(&sOut, pVal, &rc); } /* Write the new new.* record. Consists of a copy of all values ** from the original old.* record, except for the PK columns, which ** are set to "undefined". */ for(iCol=0; iCol<nCol; iCol++){ sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]); sessionAppendValue(&sOut, pVal, &rc); } for(iCol=0; iCol<nCol*2; iCol++){ sqlite3ValueFree(apVal[iCol]); } memset(apVal, 0, sizeof(apVal[0])*nCol*2); if( rc!=SQLITE_OK ){ goto finished_invert; } break; } default: rc = SQLITE_CORRUPT_BKPT; goto finished_invert; } assert( rc==SQLITE_OK ); if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); sOut.nBuf = 0; if( rc!=SQLITE_OK ) goto finished_invert; } } assert( rc==SQLITE_OK ); if( pnInverted ){ *pnInverted = sOut.nBuf; *ppInverted = sOut.aBuf; sOut.aBuf = 0; }else if( sOut.nBuf>0 ){ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); } finished_invert: sqlite3_free(sOut.aBuf); sqlite3_free(apVal); sqlite3_free(sPK.aBuf); return rc; } /* ** Invert a changeset object. */ SQLITE_API int sqlite3changeset_invert( int nChangeset, /* Number of bytes in input */ const void *pChangeset, /* Input changeset */ int *pnInverted, /* OUT: Number of bytes in output changeset */ void **ppInverted /* OUT: Inverse of pChangeset */ ){ SessionInput sInput; /* Set up the input stream */ memset(&sInput, 0, sizeof(SessionInput)); sInput.nData = nChangeset; sInput.aData = (u8*)pChangeset; return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted); } /* ** Streaming version of sqlite3changeset_invert(). */ SQLITE_API int sqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ SessionInput sInput; int rc; /* Set up the input stream */ memset(&sInput, 0, sizeof(SessionInput)); sInput.xInput = xInput; sInput.pIn = pIn; rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0); sqlite3_free(sInput.buf.aBuf); return rc; } typedef struct SessionApplyCtx SessionApplyCtx; struct SessionApplyCtx { sqlite3 *db; sqlite3_stmt *pDelete; /* DELETE statement */ sqlite3_stmt *pUpdate; /* UPDATE statement */ sqlite3_stmt *pInsert; /* INSERT statement */ sqlite3_stmt *pSelect; /* SELECT statement */ int nCol; /* Size of azCol[] and abPK[] arrays */ const char **azCol; /* Array of column names */ u8 *abPK; /* Boolean array - true if column is in PK */ int bDeferConstraints; /* True to defer constraints */ SessionBuffer constraints; /* Deferred constraints are stored here */ }; /* ** Formulate a statement to DELETE a row from database db. Assuming a table ** structure like this: ** ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c)); ** ** The DELETE statement looks like this: ** ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4) ** ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require ** matching b and d values, or 1 otherwise. The second case comes up if the ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE. ** ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left ** pointing to the prepared version of the SQL statement. */ static int sessionDeleteRow( sqlite3 *db, /* Database handle */ const char *zTab, /* Table name */ SessionApplyCtx *p /* Session changeset-apply context */ ){ int i; const char *zSep = ""; int rc = SQLITE_OK; SessionBuffer buf = {0, 0, 0}; int nPk = 0; sessionAppendStr(&buf, "DELETE FROM ", &rc); sessionAppendIdent(&buf, zTab, &rc); sessionAppendStr(&buf, " WHERE ", &rc); for(i=0; i<p->nCol; i++){ if( p->abPK[i] ){ nPk++; sessionAppendStr(&buf, zSep, &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); sessionAppendStr(&buf, " = ?", &rc); sessionAppendInteger(&buf, i+1, &rc); zSep = " AND "; } } if( nPk<p->nCol ){ sessionAppendStr(&buf, " AND (?", &rc); sessionAppendInteger(&buf, p->nCol+1, &rc); sessionAppendStr(&buf, " OR ", &rc); zSep = ""; for(i=0; i<p->nCol; i++){ if( !p->abPK[i] ){ sessionAppendStr(&buf, zSep, &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); sessionAppendStr(&buf, " IS ?", &rc); sessionAppendInteger(&buf, i+1, &rc); zSep = "AND "; } } sessionAppendStr(&buf, ")", &rc); } if( rc==SQLITE_OK ){ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0); } sqlite3_free(buf.aBuf); return rc; } /* ** Formulate and prepare a statement to UPDATE a row from database db. ** Assuming a table structure like this: ** ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c)); ** ** The UPDATE statement looks like this: ** ** UPDATE x SET ** a = CASE WHEN ?2 THEN ?3 ELSE a END, ** b = CASE WHEN ?5 THEN ?6 ELSE b END, ** c = CASE WHEN ?8 THEN ?9 ELSE c END, ** d = CASE WHEN ?11 THEN ?12 ELSE d END ** WHERE a = ?1 AND c = ?7 AND (?13 OR ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND ** ) ** ** For each column in the table, there are three variables to bind: ** ** ?(i*3+1) The old.* value of the column, if any. ** ?(i*3+2) A boolean flag indicating that the value is being modified. ** ?(i*3+3) The new.* value of the column, if any. ** ** Also, a boolean flag that, if set to true, causes the statement to update ** a row even if the non-PK values do not match. This is required if the ** conflict-handler is invoked with CHANGESET_DATA and returns ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)". ** ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left ** pointing to the prepared version of the SQL statement. */ static int sessionUpdateRow( sqlite3 *db, /* Database handle */ const char *zTab, /* Table name */ SessionApplyCtx *p /* Session changeset-apply context */ ){ int rc = SQLITE_OK; int i; const char *zSep = ""; SessionBuffer buf = {0, 0, 0}; /* Append "UPDATE tbl SET " */ sessionAppendStr(&buf, "UPDATE ", &rc); sessionAppendIdent(&buf, zTab, &rc); sessionAppendStr(&buf, " SET ", &rc); /* Append the assignments */ for(i=0; i<p->nCol; i++){ sessionAppendStr(&buf, zSep, &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); sessionAppendStr(&buf, " = CASE WHEN ?", &rc); sessionAppendInteger(&buf, i*3+2, &rc); sessionAppendStr(&buf, " THEN ?", &rc); sessionAppendInteger(&buf, i*3+3, &rc); sessionAppendStr(&buf, " ELSE ", &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); sessionAppendStr(&buf, " END", &rc); zSep = ", "; } /* Append the PK part of the WHERE clause */ sessionAppendStr(&buf, " WHERE ", &rc); for(i=0; i<p->nCol; i++){ if( p->abPK[i] ){ sessionAppendIdent(&buf, p->azCol[i], &rc); sessionAppendStr(&buf, " = ?", &rc); sessionAppendInteger(&buf, i*3+1, &rc); sessionAppendStr(&buf, " AND ", &rc); } } /* Append the non-PK part of the WHERE clause */ sessionAppendStr(&buf, " (?", &rc); sessionAppendInteger(&buf, p->nCol*3+1, &rc); sessionAppendStr(&buf, " OR 1", &rc); for(i=0; i<p->nCol; i++){ if( !p->abPK[i] ){ sessionAppendStr(&buf, " AND (?", &rc); sessionAppendInteger(&buf, i*3+2, &rc); sessionAppendStr(&buf, "=0 OR ", &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); sessionAppendStr(&buf, " IS ?", &rc); sessionAppendInteger(&buf, i*3+1, &rc); sessionAppendStr(&buf, ")", &rc); } } sessionAppendStr(&buf, ")", &rc); if( rc==SQLITE_OK ){ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0); } sqlite3_free(buf.aBuf); return rc; } /* ** Formulate and prepare an SQL statement to query table zTab by primary ** key. Assuming the following table structure: ** ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c)); ** ** The SELECT statement looks like this: ** ** SELECT * FROM x WHERE a = ?1 AND c = ?3 ** ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left ** pointing to the prepared version of the SQL statement. */ static int sessionSelectRow( sqlite3 *db, /* Database handle */ const char *zTab, /* Table name */ SessionApplyCtx *p /* Session changeset-apply context */ ){ return sessionSelectStmt( db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect); } /* ** Formulate and prepare an INSERT statement to add a record to table zTab. ** For example: ** ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...); ** ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left ** pointing to the prepared version of the SQL statement. */ static int sessionInsertRow( sqlite3 *db, /* Database handle */ const char *zTab, /* Table name */ SessionApplyCtx *p /* Session changeset-apply context */ ){ int rc = SQLITE_OK; int i; SessionBuffer buf = {0, 0, 0}; sessionAppendStr(&buf, "INSERT INTO main.", &rc); sessionAppendIdent(&buf, zTab, &rc); sessionAppendStr(&buf, "(", &rc); for(i=0; i<p->nCol; i++){ if( i!=0 ) sessionAppendStr(&buf, ", ", &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); } sessionAppendStr(&buf, ") VALUES(?", &rc); for(i=1; i<p->nCol; i++){ sessionAppendStr(&buf, ", ?", &rc); } sessionAppendStr(&buf, ")", &rc); if( rc==SQLITE_OK ){ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0); } sqlite3_free(buf.aBuf); return rc; } /* ** A wrapper around sqlite3_bind_value() that detects an extra problem. ** See comments in the body of this function for details. */ static int sessionBindValue( sqlite3_stmt *pStmt, /* Statement to bind value to */ int i, /* Parameter number to bind to */ sqlite3_value *pVal /* Value to bind */ ){ int eType = sqlite3_value_type(pVal); /* COVERAGE: The (pVal->z==0) branch is never true using current versions ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either ** the (pVal->z) variable remains as it was or the type of the value is ** set to SQLITE_NULL. */ if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){ /* This condition occurs when an earlier OOM in a call to ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */ return SQLITE_NOMEM; } return sqlite3_bind_value(pStmt, i, pVal); } /* ** Iterator pIter must point to an SQLITE_INSERT entry. This function ** transfers new.* values from the current iterator entry to statement ** pStmt. The table being inserted into has nCol columns. ** ** New.* value $i from the iterator is bound to variable ($i+1) of ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1) ** are transfered to the statement. Otherwise, if abPK is not NULL, it points ** to an array nCol elements in size. In this case only those values for ** which abPK[$i] is true are read from the iterator and bound to the ** statement. ** ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK. */ static int sessionBindRow( sqlite3_changeset_iter *pIter, /* Iterator to read values from */ int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **), int nCol, /* Number of columns */ u8 *abPK, /* If not NULL, bind only if true */ sqlite3_stmt *pStmt /* Bind values to this statement */ ){ int i; int rc = SQLITE_OK; /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the ** argument iterator points to a suitable entry. Make sure that xValue ** is one of these to guarantee that it is safe to ignore the return ** in the code below. */ assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new ); for(i=0; rc==SQLITE_OK && i<nCol; i++){ if( !abPK || abPK[i] ){ sqlite3_value *pVal; (void)xValue(pIter, i, &pVal); rc = sessionBindValue(pStmt, i+1, pVal); } } return rc; } /* ** SQL statement pSelect is as generated by the sessionSelectRow() function. ** This function binds the primary key values from the change that changeset ** iterator pIter points to to the SELECT and attempts to seek to the table ** entry. If a row is found, the SELECT statement left pointing at the row ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error ** has occured, the statement is reset and SQLITE_OK is returned. If an ** error occurs, the statement is reset and an SQLite error code is returned. ** ** If this function returns SQLITE_ROW, the caller must eventually reset() ** statement pSelect. If any other value is returned, the statement does ** not require a reset(). ** ** If the iterator currently points to an INSERT record, bind values from the ** new.* record to the SELECT statement. Or, if it points to a DELETE or ** UPDATE, bind values from the old.* record. */ static int sessionSeekToRow( sqlite3 *db, /* Database handle */ sqlite3_changeset_iter *pIter, /* Changeset iterator */ u8 *abPK, /* Primary key flags array */ sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */ ){ int rc; /* Return code */ int nCol; /* Number of columns in table */ int op; /* Changset operation (SQLITE_UPDATE etc.) */ const char *zDummy; /* Unused */ sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); rc = sessionBindRow(pIter, op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old, nCol, abPK, pSelect ); if( rc==SQLITE_OK ){ rc = sqlite3_step(pSelect); if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect); } return rc; } /* ** Invoke the conflict handler for the change that the changeset iterator ** currently points to. ** ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT. ** If argument pbReplace is NULL, then the type of conflict handler invoked ** depends solely on eType, as follows: ** ** eType value Value passed to xConflict ** ------------------------------------------------- ** CHANGESET_DATA CHANGESET_NOTFOUND ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT ** ** Or, if pbReplace is not NULL, then an attempt is made to find an existing ** record with the same primary key as the record about to be deleted, updated ** or inserted. If such a record can be found, it is available to the conflict ** handler as the "conflicting" record. In this case the type of conflict ** handler invoked is as follows: ** ** eType value PK Record found? Value passed to xConflict ** ---------------------------------------------------------------- ** CHANGESET_DATA Yes CHANGESET_DATA ** CHANGESET_DATA No CHANGESET_NOTFOUND ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT ** ** If pbReplace is not NULL, and a record with a matching PK is found, and ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace ** is set to non-zero before returning SQLITE_OK. ** ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is ** returned. Or, if the conflict handler returns an invalid value, ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT, ** this function returns SQLITE_OK. */ static int sessionConflictHandler( int eType, /* Either CHANGESET_DATA or CONFLICT */ SessionApplyCtx *p, /* changeset_apply() context */ sqlite3_changeset_iter *pIter, /* Changeset iterator */ int(*xConflict)(void *, int, sqlite3_changeset_iter*), void *pCtx, /* First argument for conflict handler */ int *pbReplace /* OUT: Set to true if PK row is found */ ){ int res = 0; /* Value returned by conflict handler */ int rc; int nCol; int op; const char *zDummy; sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA ); assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT ); assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND ); /* Bind the new.* PRIMARY KEY values to the SELECT statement. */ if( pbReplace ){ rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect); }else{ rc = SQLITE_OK; } if( rc==SQLITE_ROW ){ /* There exists another row with the new.* primary key. */ pIter->pConflict = p->pSelect; res = xConflict(pCtx, eType, pIter); pIter->pConflict = 0; rc = sqlite3_reset(p->pSelect); }else if( rc==SQLITE_OK ){ if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){ /* Instead of invoking the conflict handler, append the change blob ** to the SessionApplyCtx.constraints buffer. */ u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent]; int nBlob = pIter->in.iNext - pIter->in.iCurrent; sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc); res = SQLITE_CHANGESET_OMIT; }else{ /* No other row with the new.* primary key. */ res = xConflict(pCtx, eType+1, pIter); if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE; } } if( rc==SQLITE_OK ){ switch( res ){ case SQLITE_CHANGESET_REPLACE: assert( pbReplace ); *pbReplace = 1; break; case SQLITE_CHANGESET_OMIT: break; case SQLITE_CHANGESET_ABORT: rc = SQLITE_ABORT; break; default: rc = SQLITE_MISUSE; break; } } return rc; } /* ** Attempt to apply the change that the iterator passed as the first argument ** currently points to to the database. If a conflict is encountered, invoke ** the conflict handler callback. ** ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If ** one is encountered, update or delete the row with the matching primary key ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs, ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry ** to true before returning. In this case the caller will invoke this function ** again, this time with pbRetry set to NULL. ** ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true ** before retrying. In this case the caller attempts to remove the conflicting ** row before invoking this function again, this time with pbReplace set ** to NULL. ** ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is ** returned. */ static int sessionApplyOneOp( sqlite3_changeset_iter *pIter, /* Changeset iterator */ SessionApplyCtx *p, /* changeset_apply() context */ int(*xConflict)(void *, int, sqlite3_changeset_iter *), void *pCtx, /* First argument for the conflict handler */ int *pbReplace, /* OUT: True to remove PK row and retry */ int *pbRetry /* OUT: True to retry. */ ){ const char *zDummy; int op; int nCol; int rc = SQLITE_OK; assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect ); assert( p->azCol && p->abPK ); assert( !pbReplace || *pbReplace==0 ); sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); if( op==SQLITE_DELETE ){ /* Bind values to the DELETE statement. If conflict handling is required, ** bind values for all columns and set bound variable (nCol+1) to true. ** Or, if conflict handling is not required, bind just the PK column ** values and, if it exists, set (nCol+1) to false. Conflict handling ** is not required if: ** ** * this is a patchset, or ** * (pbRetry==0), or ** * all columns of the table are PK columns (in this case there is ** no (nCol+1) variable to bind to). */ u8 *abPK = (pIter->bPatchset ? p->abPK : 0); rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete); if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){ rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK)); } if( rc!=SQLITE_OK ) return rc; sqlite3_step(p->pDelete); rc = sqlite3_reset(p->pDelete); if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ rc = sessionConflictHandler( SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry ); }else if( (rc&0xff)==SQLITE_CONSTRAINT ){ rc = sessionConflictHandler( SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0 ); } }else if( op==SQLITE_UPDATE ){ int i; /* Bind values to the UPDATE statement. */ for(i=0; rc==SQLITE_OK && i<nCol; i++){ sqlite3_value *pOld = sessionChangesetOld(pIter, i); sqlite3_value *pNew = sessionChangesetNew(pIter, i); sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew); if( pOld ){ rc = sessionBindValue(p->pUpdate, i*3+1, pOld); } if( rc==SQLITE_OK && pNew ){ rc = sessionBindValue(p->pUpdate, i*3+3, pNew); } } if( rc==SQLITE_OK ){ sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset); } if( rc!=SQLITE_OK ) return rc; /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict, ** the result will be SQLITE_OK with 0 rows modified. */ sqlite3_step(p->pUpdate); rc = sqlite3_reset(p->pUpdate); if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ /* A NOTFOUND or DATA error. Search the table to see if it contains ** a row with a matching primary key. If so, this is a DATA conflict. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */ rc = sessionConflictHandler( SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry ); }else if( (rc&0xff)==SQLITE_CONSTRAINT ){ /* This is always a CONSTRAINT conflict. */ rc = sessionConflictHandler( SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0 ); } }else{ assert( op==SQLITE_INSERT ); rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert); if( rc!=SQLITE_OK ) return rc; sqlite3_step(p->pInsert); rc = sqlite3_reset(p->pInsert); if( (rc&0xff)==SQLITE_CONSTRAINT ){ rc = sessionConflictHandler( SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace ); } } return rc; } /* ** Attempt to apply the change that the iterator passed as the first argument ** currently points to to the database. If a conflict is encountered, invoke ** the conflict handler callback. ** ** The difference between this function and sessionApplyOne() is that this ** function handles the case where the conflict-handler is invoked and ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be ** retried in some manner. */ static int sessionApplyOneWithRetry( sqlite3 *db, /* Apply change to "main" db of this handle */ sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */ SessionApplyCtx *pApply, /* Apply context */ int(*xConflict)(void*, int, sqlite3_changeset_iter*), void *pCtx /* First argument passed to xConflict */ ){ int bReplace = 0; int bRetry = 0; int rc; rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry); assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) ); /* If the bRetry flag is set, the change has not been applied due to an ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and ** a row with the correct PK is present in the db, but one or more other ** fields do not contain the expected values) and the conflict handler ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation, ** but pass NULL as the final argument so that sessionApplyOneOp() ignores ** the SQLITE_CHANGESET_DATA problem. */ if( bRetry ){ assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE ); rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); } /* If the bReplace flag is set, the change is an INSERT that has not ** been performed because the database already contains a row with the ** specified primary key and the conflict handler returned ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row ** before reattempting the INSERT. */ else if( bReplace ){ assert( pIter->op==SQLITE_INSERT ); rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0); if( rc==SQLITE_OK ){ rc = sessionBindRow(pIter, sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete); sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1); } if( rc==SQLITE_OK ){ sqlite3_step(pApply->pDelete); rc = sqlite3_reset(pApply->pDelete); } if( rc==SQLITE_OK ){ rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); } if( rc==SQLITE_OK ){ rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0); } } return rc; } /* ** Retry the changes accumulated in the pApply->constraints buffer. */ static int sessionRetryConstraints( sqlite3 *db, int bPatchset, const char *zTab, SessionApplyCtx *pApply, int(*xConflict)(void*, int, sqlite3_changeset_iter*), void *pCtx /* First argument passed to xConflict */ ){ int rc = SQLITE_OK; while( pApply->constraints.nBuf ){ sqlite3_changeset_iter *pIter2 = 0; SessionBuffer cons = pApply->constraints; memset(&pApply->constraints, 0, sizeof(SessionBuffer)); rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf); if( rc==SQLITE_OK ){ int nByte = 2*pApply->nCol*sizeof(sqlite3_value*); int rc2; pIter2->bPatchset = bPatchset; pIter2->zTab = (char*)zTab; pIter2->nCol = pApply->nCol; pIter2->abPK = pApply->abPK; sessionBufferGrow(&pIter2->tblhdr, nByte, &rc); pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf; if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte); while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){ rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx); } rc2 = sqlite3changeset_finalize(pIter2); if( rc==SQLITE_OK ) rc = rc2; } assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 ); sqlite3_free(cons.aBuf); if( rc!=SQLITE_OK ) break; if( pApply->constraints.nBuf>=cons.nBuf ){ /* No progress was made on the last round. */ pApply->bDeferConstraints = 0; } } return rc; } /* ** Argument pIter is a changeset iterator that has been initialized, but ** not yet passed to sqlite3changeset_next(). This function applies the ** changeset to the main database attached to handle "db". The supplied ** conflict handler callback is invoked to resolve any conflicts encountered ** while applying the change. */ static int sessionChangesetApply( sqlite3 *db, /* Apply change to "main" db of this handle */ sqlite3_changeset_iter *pIter, /* Changeset to apply */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of fifth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ){ int schemaMismatch = 0; int rc; /* Return code */ const char *zTab = 0; /* Name of current table */ int nTab = 0; /* Result of sqlite3Strlen30(zTab) */ SessionApplyCtx sApply; /* changeset_apply() context object */ int bPatchset; assert( xConflict!=0 ); pIter->in.bNoDiscard = 1; memset(&sApply, 0, sizeof(sApply)); sqlite3_mutex_enter(sqlite3_db_mutex(db)); rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0); if( rc==SQLITE_OK ){ rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0); } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){ int nCol; int op; const char *zNew; sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0); if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){ u8 *abPK; rc = sessionRetryConstraints( db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx ); if( rc!=SQLITE_OK ) break; sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ sqlite3_finalize(sApply.pDelete); sqlite3_finalize(sApply.pUpdate); sqlite3_finalize(sApply.pInsert); sqlite3_finalize(sApply.pSelect); memset(&sApply, 0, sizeof(sApply)); sApply.db = db; sApply.bDeferConstraints = 1; /* If an xFilter() callback was specified, invoke it now. If the ** xFilter callback returns zero, skip this table. If it returns ** non-zero, proceed. */ schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew))); if( schemaMismatch ){ zTab = sqlite3_mprintf("%s", zNew); if( zTab==0 ){ rc = SQLITE_NOMEM; break; } nTab = (int)strlen(zTab); sApply.azCol = (const char **)zTab; }else{ int nMinCol = 0; int i; sqlite3changeset_pk(pIter, &abPK, 0); rc = sessionTableInfo( db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK ); if( rc!=SQLITE_OK ) break; for(i=0; i<sApply.nCol; i++){ if( sApply.abPK[i] ) nMinCol = i+1; } if( sApply.nCol==0 ){ schemaMismatch = 1; sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): no such table: %s", zTab ); } else if( sApply.nCol<nCol ){ schemaMismatch = 1; sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): table %s has %d columns, " "expected %d or more", zTab, sApply.nCol, nCol ); } else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){ schemaMismatch = 1; sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): " "primary key mismatch for table %s", zTab ); } else{ sApply.nCol = nCol; if((rc = sessionSelectRow(db, zTab, &sApply)) || (rc = sessionUpdateRow(db, zTab, &sApply)) || (rc = sessionDeleteRow(db, zTab, &sApply)) || (rc = sessionInsertRow(db, zTab, &sApply)) ){ break; } } nTab = sqlite3Strlen30(zTab); } } /* If there is a schema mismatch on the current table, proceed to the ** next change. A log message has already been issued. */ if( schemaMismatch ) continue; rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx); } bPatchset = pIter->bPatchset; if( rc==SQLITE_OK ){ rc = sqlite3changeset_finalize(pIter); }else{ sqlite3changeset_finalize(pIter); } if( rc==SQLITE_OK ){ rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx); } if( rc==SQLITE_OK ){ int nFk, notUsed; sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0); if( nFk!=0 ){ int res = SQLITE_CHANGESET_ABORT; sqlite3_changeset_iter sIter; memset(&sIter, 0, sizeof(sIter)); sIter.nCol = nFk; res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter); if( res!=SQLITE_CHANGESET_OMIT ){ rc = SQLITE_CONSTRAINT; } } } sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0); if( rc==SQLITE_OK ){ rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); }else{ sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0); sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); } sqlite3_finalize(sApply.pInsert); sqlite3_finalize(sApply.pDelete); sqlite3_finalize(sApply.pUpdate); sqlite3_finalize(sApply.pSelect); sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ sqlite3_free((char*)sApply.constraints.aBuf); sqlite3_mutex_leave(sqlite3_db_mutex(db)); return rc; } /* ** Apply the changeset passed via pChangeset/nChangeset to the main database ** attached to handle "db". Invoke the supplied conflict handler callback ** to resolve any conflicts encountered while applying the change. */ SQLITE_API int sqlite3changeset_apply( sqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of fifth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ){ sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset); if( rc==SQLITE_OK ){ rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx); } return rc; } /* ** Apply the changeset passed via xInput/pIn to the main database ** attached to handle "db". Invoke the supplied conflict handler callback ** to resolve any conflicts encountered while applying the change. */ SQLITE_API int sqlite3changeset_apply_strm( sqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ){ sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn); if( rc==SQLITE_OK ){ rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx); } return rc; } /* ** sqlite3_changegroup handle. */ struct sqlite3_changegroup { int rc; /* Error code */ int bPatch; /* True to accumulate patchsets */ SessionTable *pList; /* List of tables in current patch */ }; /* ** This function is called to merge two changes to the same row together as ** part of an sqlite3changeset_concat() operation. A new change object is ** allocated and a pointer to it stored in *ppNew. */ static int sessionChangeMerge( SessionTable *pTab, /* Table structure */ int bPatchset, /* True for patchsets */ SessionChange *pExist, /* Existing change */ int op2, /* Second change operation */ int bIndirect, /* True if second change is indirect */ u8 *aRec, /* Second change record */ int nRec, /* Number of bytes in aRec */ SessionChange **ppNew /* OUT: Merged change */ ){ SessionChange *pNew = 0; if( !pExist ){ pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec); if( !pNew ){ return SQLITE_NOMEM; } memset(pNew, 0, sizeof(SessionChange)); pNew->op = op2; pNew->bIndirect = bIndirect; pNew->nRecord = nRec; pNew->aRecord = (u8*)&pNew[1]; memcpy(pNew->aRecord, aRec, nRec); }else{ int op1 = pExist->op; /* ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2. ** op1=INSERT, op2=UPDATE -> INSERT. ** op1=INSERT, op2=DELETE -> (none) ** ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2. ** op1=UPDATE, op2=UPDATE -> UPDATE. ** op1=UPDATE, op2=DELETE -> DELETE. ** ** op1=DELETE, op2=INSERT -> UPDATE. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2. */ if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT) || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT) || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE) || (op1==SQLITE_DELETE && op2==SQLITE_DELETE) ){ pNew = pExist; }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){ sqlite3_free(pExist); assert( pNew==0 ); }else{ u8 *aExist = pExist->aRecord; int nByte; u8 *aCsr; /* Allocate a new SessionChange object. Ensure that the aRecord[] ** buffer of the new object is large enough to hold any record that ** may be generated by combining the input records. */ nByte = sizeof(SessionChange) + pExist->nRecord + nRec; pNew = (SessionChange *)sqlite3_malloc(nByte); if( !pNew ){ sqlite3_free(pExist); return SQLITE_NOMEM; } memset(pNew, 0, sizeof(SessionChange)); pNew->bIndirect = (bIndirect && pExist->bIndirect); aCsr = pNew->aRecord = (u8 *)&pNew[1]; if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */ u8 *a1 = aRec; assert( op2==SQLITE_UPDATE ); pNew->op = SQLITE_INSERT; if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol); sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1); }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */ assert( op2==SQLITE_INSERT ); pNew->op = SQLITE_UPDATE; if( bPatchset ){ memcpy(aCsr, aRec, nRec); aCsr += nRec; }else{ if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){ sqlite3_free(pNew); pNew = 0; } } }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */ u8 *a1 = aExist; u8 *a2 = aRec; assert( op1==SQLITE_UPDATE ); if( bPatchset==0 ){ sessionSkipRecord(&a1, pTab->nCol); sessionSkipRecord(&a2, pTab->nCol); } pNew->op = SQLITE_UPDATE; if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){ sqlite3_free(pNew); pNew = 0; } }else{ /* UPDATE + DELETE */ assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE ); pNew->op = SQLITE_DELETE; if( bPatchset ){ memcpy(aCsr, aRec, nRec); aCsr += nRec; }else{ sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist); } } if( pNew ){ pNew->nRecord = (int)(aCsr - pNew->aRecord); } sqlite3_free(pExist); } } *ppNew = pNew; return SQLITE_OK; } /* ** Add all changes in the changeset traversed by the iterator passed as ** the first argument to the changegroup hash tables. */ static int sessionChangesetToHash( sqlite3_changeset_iter *pIter, /* Iterator to read from */ sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */ ){ u8 *aRec; int nRec; int rc = SQLITE_OK; SessionTable *pTab = 0; while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){ const char *zNew; int nCol; int op; int iHash; int bIndirect; SessionChange *pChange; SessionChange *pExist = 0; SessionChange **pp; if( pGrp->pList==0 ){ pGrp->bPatch = pIter->bPatchset; }else if( pIter->bPatchset!=pGrp->bPatch ){ rc = SQLITE_ERROR; break; } sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect); if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){ /* Search the list for a matching table */ int nNew = (int)strlen(zNew); u8 *abPK; sqlite3changeset_pk(pIter, &abPK, 0); for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){ if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break; } if( !pTab ){ SessionTable **ppTab; pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1); if( !pTab ){ rc = SQLITE_NOMEM; break; } memset(pTab, 0, sizeof(SessionTable)); pTab->nCol = nCol; pTab->abPK = (u8*)&pTab[1]; memcpy(pTab->abPK, abPK, nCol); pTab->zName = (char*)&pTab->abPK[nCol]; memcpy(pTab->zName, zNew, nNew+1); /* The new object must be linked on to the end of the list, not ** simply added to the start of it. This is to ensure that the ** tables within the output of sqlite3changegroup_output() are in ** the right order. */ for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext); *ppTab = pTab; }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){ rc = SQLITE_SCHEMA; break; } } if( sessionGrowHash(pIter->bPatchset, pTab) ){ rc = SQLITE_NOMEM; break; } iHash = sessionChangeHash( pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange ); /* Search for existing entry. If found, remove it from the hash table. ** Code below may link it back in. */ for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){ int bPkOnly1 = 0; int bPkOnly2 = 0; if( pIter->bPatchset ){ bPkOnly1 = (*pp)->op==SQLITE_DELETE; bPkOnly2 = op==SQLITE_DELETE; } if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){ pExist = *pp; *pp = (*pp)->pNext; pTab->nEntry--; break; } } rc = sessionChangeMerge(pTab, pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange ); if( rc ) break; if( pChange ){ pChange->pNext = pTab->apChange[iHash]; pTab->apChange[iHash] = pChange; pTab->nEntry++; } } if( rc==SQLITE_OK ) rc = pIter->rc; return rc; } /* ** Serialize a changeset (or patchset) based on all changesets (or patchsets) ** added to the changegroup object passed as the first argument. ** ** If xOutput is not NULL, then the changeset/patchset is returned to the ** user via one or more calls to xOutput, as with the other streaming ** interfaces. ** ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a ** buffer containing the output changeset before this function returns. In ** this case (*pnOut) is set to the size of the output buffer in bytes. It ** is the responsibility of the caller to free the output buffer using ** sqlite3_free() when it is no longer required. ** ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut) ** are both set to 0 before returning. */ static int sessionChangegroupOutput( sqlite3_changegroup *pGrp, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut, int *pnOut, void **ppOut ){ int rc = SQLITE_OK; SessionBuffer buf = {0, 0, 0}; SessionTable *pTab; assert( xOutput==0 || (ppOut==0 && pnOut==0) ); /* Create the serialized output changeset based on the contents of the ** hash tables attached to the SessionTable objects in list p->pList. */ for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){ int i; if( pTab->nEntry==0 ) continue; sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc); for(i=0; i<pTab->nChange; i++){ SessionChange *p; for(p=pTab->apChange[i]; p; p=p->pNext){ sessionAppendByte(&buf, p->op, &rc); sessionAppendByte(&buf, p->bIndirect, &rc); sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc); } } if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){ rc = xOutput(pOut, buf.aBuf, buf.nBuf); buf.nBuf = 0; } } if( rc==SQLITE_OK ){ if( xOutput ){ if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf); }else{ *ppOut = buf.aBuf; *pnOut = buf.nBuf; buf.aBuf = 0; } } sqlite3_free(buf.aBuf); return rc; } /* ** Allocate a new, empty, sqlite3_changegroup. */ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){ int rc = SQLITE_OK; /* Return code */ sqlite3_changegroup *p; /* New object */ p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup)); if( p==0 ){ rc = SQLITE_NOMEM; }else{ memset(p, 0, sizeof(sqlite3_changegroup)); } *pp = p; return rc; } /* ** Add the changeset currently stored in buffer pData, size nData bytes, ** to changeset-group p. */ SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){ sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ int rc; /* Return code */ rc = sqlite3changeset_start(&pIter, nData, pData); if( rc==SQLITE_OK ){ rc = sessionChangesetToHash(pIter, pGrp); } sqlite3changeset_finalize(pIter); return rc; } /* ** Obtain a buffer containing a changeset representing the concatenation ** of all changesets added to the group so far. */ SQLITE_API int sqlite3changegroup_output( sqlite3_changegroup *pGrp, int *pnData, void **ppData ){ return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData); } /* ** Streaming versions of changegroup_add(). */ SQLITE_API int sqlite3changegroup_add_strm( sqlite3_changegroup *pGrp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ){ sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ int rc; /* Return code */ rc = sqlite3changeset_start_strm(&pIter, xInput, pIn); if( rc==SQLITE_OK ){ rc = sessionChangesetToHash(pIter, pGrp); } sqlite3changeset_finalize(pIter); return rc; } /* ** Streaming versions of changegroup_output(). */ SQLITE_API int sqlite3changegroup_output_strm( sqlite3_changegroup *pGrp, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0); } /* ** Delete a changegroup object. */ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){ if( pGrp ){ sessionDeleteTable(pGrp->pList); sqlite3_free(pGrp); } } /* ** Combine two changesets together. */ SQLITE_API int sqlite3changeset_concat( int nLeft, /* Number of bytes in lhs input */ void *pLeft, /* Lhs input changeset */ int nRight /* Number of bytes in rhs input */, void *pRight, /* Rhs input changeset */ int *pnOut, /* OUT: Number of bytes in output changeset */ void **ppOut /* OUT: changeset (left <concat> right) */ ){ sqlite3_changegroup *pGrp; int rc; rc = sqlite3changegroup_new(&pGrp); if( rc==SQLITE_OK ){ rc = sqlite3changegroup_add(pGrp, nLeft, pLeft); } if( rc==SQLITE_OK ){ rc = sqlite3changegroup_add(pGrp, nRight, pRight); } if( rc==SQLITE_OK ){ rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); } sqlite3changegroup_delete(pGrp); return rc; } /* ** Streaming version of sqlite3changeset_concat(). */ SQLITE_API int sqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), void *pInB, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ sqlite3_changegroup *pGrp; int rc; rc = sqlite3changegroup_new(&pGrp); if( rc==SQLITE_OK ){ rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA); } if( rc==SQLITE_OK ){ rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB); } if( rc==SQLITE_OK ){ rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut); } sqlite3changegroup_delete(pGrp); return rc; } #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */ /************** End of sqlite3session.c **************************************/ /************** Begin file json1.c *******************************************/ /* ** 2015-08-12 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This SQLite extension implements JSON functions. The interface is ** modeled after MySQL JSON functions: ** ** https://dev.mysql.com/doc/refman/5.7/en/json.html ** ** For the time being, all JSON is stored as pure text. (We might add ** a JSONB type in the future which stores a binary encoding of JSON in ** a BLOB, but there is no support for JSONB in the current implementation. ** This implementation parses JSON text at 250 MB/s, so it is hard to see ** how JSONB might improve on that.) */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) #if !defined(SQLITEINT_H) /* #include "sqlite3ext.h" */ #endif SQLITE_EXTENSION_INIT1 /* #include <assert.h> */ /* #include <string.h> */ /* #include <stdlib.h> */ /* #include <stdarg.h> */ /* Mark a function parameter as unused, to suppress nuisance compiler ** warnings. */ #ifndef UNUSED_PARAM # define UNUSED_PARAM(X) (void)(X) #endif #ifndef LARGEST_INT64 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) #endif /* ** Versions of isspace(), isalnum() and isdigit() to which it is safe ** to pass signed char values. */ #ifdef sqlite3Isdigit /* Use the SQLite core versions if this routine is part of the ** SQLite amalgamation */ # define safe_isdigit(x) sqlite3Isdigit(x) # define safe_isalnum(x) sqlite3Isalnum(x) # define safe_isxdigit(x) sqlite3Isxdigit(x) #else /* Use the standard library for separate compilation */ #include <ctype.h> /* amalgamator: keep */ # define safe_isdigit(x) isdigit((unsigned char)(x)) # define safe_isalnum(x) isalnum((unsigned char)(x)) # define safe_isxdigit(x) isxdigit((unsigned char)(x)) #endif /* ** Growing our own isspace() routine this way is twice as fast as ** the library isspace() function, resulting in a 7% overall performance ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os). */ static const char jsonIsSpace[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; #define safe_isspace(x) (jsonIsSpace[(unsigned char)x]) #ifndef SQLITE_AMALGAMATION /* Unsigned integer types. These are already defined in the sqliteInt.h, ** but the definitions need to be repeated for separate compilation. */ typedef sqlite3_uint64 u64; typedef unsigned int u32; typedef unsigned char u8; #endif /* Objects */ typedef struct JsonString JsonString; typedef struct JsonNode JsonNode; typedef struct JsonParse JsonParse; /* An instance of this object represents a JSON string ** under construction. Really, this is a generic string accumulator ** that can be and is used to create strings other than JSON. */ struct JsonString { sqlite3_context *pCtx; /* Function context - put error messages here */ char *zBuf; /* Append JSON content here */ u64 nAlloc; /* Bytes of storage available in zBuf[] */ u64 nUsed; /* Bytes of zBuf[] currently used */ u8 bStatic; /* True if zBuf is static space */ u8 bErr; /* True if an error has been encountered */ char zSpace[100]; /* Initial static space */ }; /* JSON type values */ #define JSON_NULL 0 #define JSON_TRUE 1 #define JSON_FALSE 2 #define JSON_INT 3 #define JSON_REAL 4 #define JSON_STRING 5 #define JSON_ARRAY 6 #define JSON_OBJECT 7 /* The "subtype" set for JSON values */ #define JSON_SUBTYPE 74 /* Ascii for "J" */ /* ** Names of the various JSON types: */ static const char * const jsonType[] = { "null", "true", "false", "integer", "real", "text", "array", "object" }; /* Bit values for the JsonNode.jnFlag field */ #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */ #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */ #define JNODE_REMOVE 0x04 /* Do not output */ #define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */ #define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */ #define JNODE_LABEL 0x20 /* Is a label of an object */ /* A single node of parsed JSON */ struct JsonNode { u8 eType; /* One of the JSON_ type values */ u8 jnFlags; /* JNODE flags */ u8 iVal; /* Replacement value when JNODE_REPLACE */ u32 n; /* Bytes of content, or number of sub-nodes */ union { const char *zJContent; /* Content for INT, REAL, and STRING */ u32 iAppend; /* More terms for ARRAY and OBJECT */ u32 iKey; /* Key for ARRAY objects in json_tree() */ } u; }; /* A completely parsed JSON string */ struct JsonParse { u32 nNode; /* Number of slots of aNode[] used */ u32 nAlloc; /* Number of slots of aNode[] allocated */ JsonNode *aNode; /* Array of nodes containing the parse */ const char *zJson; /* Original JSON string */ u32 *aUp; /* Index of parent of each node */ u8 oom; /* Set to true if out of memory */ u8 nErr; /* Number of errors seen */ }; /************************************************************************** ** Utility routines for dealing with JsonString objects **************************************************************************/ /* Set the JsonString object to an empty string */ static void jsonZero(JsonString *p){ p->zBuf = p->zSpace; p->nAlloc = sizeof(p->zSpace); p->nUsed = 0; p->bStatic = 1; } /* Initialize the JsonString object */ static void jsonInit(JsonString *p, sqlite3_context *pCtx){ p->pCtx = pCtx; p->bErr = 0; jsonZero(p); } /* Free all allocated memory and reset the JsonString object back to its ** initial state. */ static void jsonReset(JsonString *p){ if( !p->bStatic ) sqlite3_free(p->zBuf); jsonZero(p); } /* Report an out-of-memory (OOM) condition */ static void jsonOom(JsonString *p){ p->bErr = 1; sqlite3_result_error_nomem(p->pCtx); jsonReset(p); } /* Enlarge pJson->zBuf so that it can hold at least N more bytes. ** Return zero on success. Return non-zero on an OOM error */ static int jsonGrow(JsonString *p, u32 N){ u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10; char *zNew; if( p->bStatic ){ if( p->bErr ) return 1; zNew = sqlite3_malloc64(nTotal); if( zNew==0 ){ jsonOom(p); return SQLITE_NOMEM; } memcpy(zNew, p->zBuf, (size_t)p->nUsed); p->zBuf = zNew; p->bStatic = 0; }else{ zNew = sqlite3_realloc64(p->zBuf, nTotal); if( zNew==0 ){ jsonOom(p); return SQLITE_NOMEM; } p->zBuf = zNew; } p->nAlloc = nTotal; return SQLITE_OK; } /* Append N bytes from zIn onto the end of the JsonString string. */ static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){ if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return; memcpy(p->zBuf+p->nUsed, zIn, N); p->nUsed += N; } /* Append formatted text (not to exceed N bytes) to the JsonString. */ static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){ va_list ap; if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return; va_start(ap, zFormat); sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap); va_end(ap); p->nUsed += (int)strlen(p->zBuf+p->nUsed); } /* Append a single character */ static void jsonAppendChar(JsonString *p, char c){ if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return; p->zBuf[p->nUsed++] = c; } /* Append a comma separator to the output buffer, if the previous ** character is not '[' or '{'. */ static void jsonAppendSeparator(JsonString *p){ char c; if( p->nUsed==0 ) return; c = p->zBuf[p->nUsed-1]; if( c!='[' && c!='{' ) jsonAppendChar(p, ','); } /* Append the N-byte string in zIn to the end of the JsonString string ** under construction. Enclose the string in "..." and escape ** any double-quotes or backslash characters contained within the ** string. */ static void jsonAppendString(JsonString *p, const char *zIn, u32 N){ u32 i; if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return; p->zBuf[p->nUsed++] = '"'; for(i=0; i<N; i++){ unsigned char c = ((unsigned const char*)zIn)[i]; if( c=='"' || c=='\\' ){ json_simple_escape: if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return; p->zBuf[p->nUsed++] = '\\'; }else if( c<=0x1f ){ static const char aSpecial[] = { 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assert( sizeof(aSpecial)==32 ); assert( aSpecial['\b']=='b' ); assert( aSpecial['\f']=='f' ); assert( aSpecial['\n']=='n' ); assert( aSpecial['\r']=='r' ); assert( aSpecial['\t']=='t' ); if( aSpecial[c] ){ c = aSpecial[c]; goto json_simple_escape; } if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return; p->zBuf[p->nUsed++] = '\\'; p->zBuf[p->nUsed++] = 'u'; p->zBuf[p->nUsed++] = '0'; p->zBuf[p->nUsed++] = '0'; p->zBuf[p->nUsed++] = '0' + (c>>4); c = "0123456789abcdef"[c&0xf]; } p->zBuf[p->nUsed++] = c; } p->zBuf[p->nUsed++] = '"'; assert( p->nUsed<p->nAlloc ); } /* ** Append a function parameter value to the JSON string under ** construction. */ static void jsonAppendValue( JsonString *p, /* Append to this JSON string */ sqlite3_value *pValue /* Value to append */ ){ switch( sqlite3_value_type(pValue) ){ case SQLITE_NULL: { jsonAppendRaw(p, "null", 4); break; } case SQLITE_INTEGER: case SQLITE_FLOAT: { const char *z = (const char*)sqlite3_value_text(pValue); u32 n = (u32)sqlite3_value_bytes(pValue); jsonAppendRaw(p, z, n); break; } case SQLITE_TEXT: { const char *z = (const char*)sqlite3_value_text(pValue); u32 n = (u32)sqlite3_value_bytes(pValue); if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){ jsonAppendRaw(p, z, n); }else{ jsonAppendString(p, z, n); } break; } default: { if( p->bErr==0 ){ sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1); p->bErr = 2; jsonReset(p); } break; } } } /* Make the JSON in p the result of the SQL function. */ static void jsonResult(JsonString *p){ if( p->bErr==0 ){ sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, p->bStatic ? SQLITE_TRANSIENT : sqlite3_free, SQLITE_UTF8); jsonZero(p); } assert( p->bStatic ); } /************************************************************************** ** Utility routines for dealing with JsonNode and JsonParse objects **************************************************************************/ /* ** Return the number of consecutive JsonNode slots need to represent ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and ** OBJECT types, the number might be larger. ** ** Appended elements are not counted. The value returned is the number ** by which the JsonNode counter should increment in order to go to the ** next peer value. */ static u32 jsonNodeSize(JsonNode *pNode){ return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1; } /* ** Reclaim all memory allocated by a JsonParse object. But do not ** delete the JsonParse object itself. */ static void jsonParseReset(JsonParse *pParse){ sqlite3_free(pParse->aNode); pParse->aNode = 0; pParse->nNode = 0; pParse->nAlloc = 0; sqlite3_free(pParse->aUp); pParse->aUp = 0; } /* ** Convert the JsonNode pNode into a pure JSON string and ** append to pOut. Subsubstructure is also included. Return ** the number of JsonNode objects that are encoded. */ static void jsonRenderNode( JsonNode *pNode, /* The node to render */ JsonString *pOut, /* Write JSON here */ sqlite3_value **aReplace /* Replacement values */ ){ switch( pNode->eType ){ default: { assert( pNode->eType==JSON_NULL ); jsonAppendRaw(pOut, "null", 4); break; } case JSON_TRUE: { jsonAppendRaw(pOut, "true", 4); break; } case JSON_FALSE: { jsonAppendRaw(pOut, "false", 5); break; } case JSON_STRING: { if( pNode->jnFlags & JNODE_RAW ){ jsonAppendString(pOut, pNode->u.zJContent, pNode->n); break; } /* Fall through into the next case */ } case JSON_REAL: case JSON_INT: { jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n); break; } case JSON_ARRAY: { u32 j = 1; jsonAppendChar(pOut, '['); for(;;){ while( j<=pNode->n ){ if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){ if( pNode[j].jnFlags & JNODE_REPLACE ){ jsonAppendSeparator(pOut); jsonAppendValue(pOut, aReplace[pNode[j].iVal]); } }else{ jsonAppendSeparator(pOut); jsonRenderNode(&pNode[j], pOut, aReplace); } j += jsonNodeSize(&pNode[j]); } if( (pNode->jnFlags & JNODE_APPEND)==0 ) break; pNode = &pNode[pNode->u.iAppend]; j = 1; } jsonAppendChar(pOut, ']'); break; } case JSON_OBJECT: { u32 j = 1; jsonAppendChar(pOut, '{'); for(;;){ while( j<=pNode->n ){ if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){ jsonAppendSeparator(pOut); jsonRenderNode(&pNode[j], pOut, aReplace); jsonAppendChar(pOut, ':'); if( pNode[j+1].jnFlags & JNODE_REPLACE ){ jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]); }else{ jsonRenderNode(&pNode[j+1], pOut, aReplace); } } j += 1 + jsonNodeSize(&pNode[j+1]); } if( (pNode->jnFlags & JNODE_APPEND)==0 ) break; pNode = &pNode[pNode->u.iAppend]; j = 1; } jsonAppendChar(pOut, '}'); break; } } } /* ** Return a JsonNode and all its descendents as a JSON string. */ static void jsonReturnJson( JsonNode *pNode, /* Node to return */ sqlite3_context *pCtx, /* Return value for this function */ sqlite3_value **aReplace /* Array of replacement values */ ){ JsonString s; jsonInit(&s, pCtx); jsonRenderNode(pNode, &s, aReplace); jsonResult(&s); sqlite3_result_subtype(pCtx, JSON_SUBTYPE); } /* ** Make the JsonNode the return value of the function. */ static void jsonReturn( JsonNode *pNode, /* Node to return */ sqlite3_context *pCtx, /* Return value for this function */ sqlite3_value **aReplace /* Array of replacement values */ ){ switch( pNode->eType ){ default: { assert( pNode->eType==JSON_NULL ); sqlite3_result_null(pCtx); break; } case JSON_TRUE: { sqlite3_result_int(pCtx, 1); break; } case JSON_FALSE: { sqlite3_result_int(pCtx, 0); break; } case JSON_INT: { sqlite3_int64 i = 0; const char *z = pNode->u.zJContent; if( z[0]=='-' ){ z++; } while( z[0]>='0' && z[0]<='9' ){ unsigned v = *(z++) - '0'; if( i>=LARGEST_INT64/10 ){ if( i>LARGEST_INT64/10 ) goto int_as_real; if( z[0]>='0' && z[0]<='9' ) goto int_as_real; if( v==9 ) goto int_as_real; if( v==8 ){ if( pNode->u.zJContent[0]=='-' ){ sqlite3_result_int64(pCtx, SMALLEST_INT64); goto int_done; }else{ goto int_as_real; } } } i = i*10 + v; } if( pNode->u.zJContent[0]=='-' ){ i = -i; } sqlite3_result_int64(pCtx, i); int_done: break; int_as_real: /* fall through to real */; } case JSON_REAL: { double r; #ifdef SQLITE_AMALGAMATION const char *z = pNode->u.zJContent; sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8); #else r = strtod(pNode->u.zJContent, 0); #endif sqlite3_result_double(pCtx, r); break; } case JSON_STRING: { #if 0 /* Never happens because JNODE_RAW is only set by json_set(), ** json_insert() and json_replace() and those routines do not ** call jsonReturn() */ if( pNode->jnFlags & JNODE_RAW ){ sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n, SQLITE_TRANSIENT); }else #endif assert( (pNode->jnFlags & JNODE_RAW)==0 ); if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){ /* JSON formatted without any backslash-escapes */ sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2, SQLITE_TRANSIENT); }else{ /* Translate JSON formatted string into raw text */ u32 i; u32 n = pNode->n; const char *z = pNode->u.zJContent; char *zOut; u32 j; zOut = sqlite3_malloc( n+1 ); if( zOut==0 ){ sqlite3_result_error_nomem(pCtx); break; } for(i=1, j=0; i<n-1; i++){ char c = z[i]; if( c!='\\' ){ zOut[j++] = c; }else{ c = z[++i]; if( c=='u' ){ u32 v = 0, k; for(k=0; k<4; i++, k++){ assert( i<n-2 ); c = z[i+1]; assert( safe_isxdigit(c) ); if( c<='9' ) v = v*16 + c - '0'; else if( c<='F' ) v = v*16 + c - 'A' + 10; else v = v*16 + c - 'a' + 10; } if( v==0 ) break; if( v<=0x7f ){ zOut[j++] = (char)v; }else if( v<=0x7ff ){ zOut[j++] = (char)(0xc0 | (v>>6)); zOut[j++] = 0x80 | (v&0x3f); }else{ zOut[j++] = (char)(0xe0 | (v>>12)); zOut[j++] = 0x80 | ((v>>6)&0x3f); zOut[j++] = 0x80 | (v&0x3f); } }else{ if( c=='b' ){ c = '\b'; }else if( c=='f' ){ c = '\f'; }else if( c=='n' ){ c = '\n'; }else if( c=='r' ){ c = '\r'; }else if( c=='t' ){ c = '\t'; } zOut[j++] = c; } } } zOut[j] = 0; sqlite3_result_text(pCtx, zOut, j, sqlite3_free); } break; } case JSON_ARRAY: case JSON_OBJECT: { jsonReturnJson(pNode, pCtx, aReplace); break; } } } /* Forward reference */ static int jsonParseAddNode(JsonParse*,u32,u32,const char*); /* ** A macro to hint to the compiler that a function should not be ** inlined. */ #if defined(__GNUC__) # define JSON_NOINLINE __attribute__((noinline)) #elif defined(_MSC_VER) && _MSC_VER>=1310 # define JSON_NOINLINE __declspec(noinline) #else # define JSON_NOINLINE #endif static JSON_NOINLINE int jsonParseAddNodeExpand( JsonParse *pParse, /* Append the node to this object */ u32 eType, /* Node type */ u32 n, /* Content size or sub-node count */ const char *zContent /* Content */ ){ u32 nNew; JsonNode *pNew; assert( pParse->nNode>=pParse->nAlloc ); if( pParse->oom ) return -1; nNew = pParse->nAlloc*2 + 10; pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew); if( pNew==0 ){ pParse->oom = 1; return -1; } pParse->nAlloc = nNew; pParse->aNode = pNew; assert( pParse->nNode<pParse->nAlloc ); return jsonParseAddNode(pParse, eType, n, zContent); } /* ** Create a new JsonNode instance based on the arguments and append that ** instance to the JsonParse. Return the index in pParse->aNode[] of the ** new node, or -1 if a memory allocation fails. */ static int jsonParseAddNode( JsonParse *pParse, /* Append the node to this object */ u32 eType, /* Node type */ u32 n, /* Content size or sub-node count */ const char *zContent /* Content */ ){ JsonNode *p; if( pParse->nNode>=pParse->nAlloc ){ return jsonParseAddNodeExpand(pParse, eType, n, zContent); } p = &pParse->aNode[pParse->nNode]; p->eType = (u8)eType; p->jnFlags = 0; p->iVal = 0; p->n = n; p->u.zJContent = zContent; return pParse->nNode++; } /* ** Return true if z[] begins with 4 (or more) hexadecimal digits */ static int jsonIs4Hex(const char *z){ int i; for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0; return 1; } /* ** Parse a single JSON value which begins at pParse->zJson[i]. Return the ** index of the first character past the end of the value parsed. ** ** Return negative for a syntax error. Special cases: return -2 if the ** first non-whitespace character is '}' and return -3 if the first ** non-whitespace character is ']'. */ static int jsonParseValue(JsonParse *pParse, u32 i){ char c; u32 j; int iThis; int x; JsonNode *pNode; while( safe_isspace(pParse->zJson[i]) ){ i++; } if( (c = pParse->zJson[i])=='{' ){ /* Parse object */ iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0); if( iThis<0 ) return -1; for(j=i+1;;j++){ while( safe_isspace(pParse->zJson[j]) ){ j++; } x = jsonParseValue(pParse, j); if( x<0 ){ if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1; return -1; } if( pParse->oom ) return -1; pNode = &pParse->aNode[pParse->nNode-1]; if( pNode->eType!=JSON_STRING ) return -1; pNode->jnFlags |= JNODE_LABEL; j = x; while( safe_isspace(pParse->zJson[j]) ){ j++; } if( pParse->zJson[j]!=':' ) return -1; j++; x = jsonParseValue(pParse, j); if( x<0 ) return -1; j = x; while( safe_isspace(pParse->zJson[j]) ){ j++; } c = pParse->zJson[j]; if( c==',' ) continue; if( c!='}' ) return -1; break; } pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1; return j+1; }else if( c=='[' ){ /* Parse array */ iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0); if( iThis<0 ) return -1; for(j=i+1;;j++){ while( safe_isspace(pParse->zJson[j]) ){ j++; } x = jsonParseValue(pParse, j); if( x<0 ){ if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1; return -1; } j = x; while( safe_isspace(pParse->zJson[j]) ){ j++; } c = pParse->zJson[j]; if( c==',' ) continue; if( c!=']' ) return -1; break; } pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1; return j+1; }else if( c=='"' ){ /* Parse string */ u8 jnFlags = 0; j = i+1; for(;;){ c = pParse->zJson[j]; if( c==0 ) return -1; if( c=='\\' ){ c = pParse->zJson[++j]; if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f' || c=='n' || c=='r' || c=='t' || (c=='u' && jsonIs4Hex(pParse->zJson+j+1)) ){ jnFlags = JNODE_ESCAPE; }else{ return -1; } }else if( c=='"' ){ break; } j++; } jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]); if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags; return j+1; }else if( c=='n' && strncmp(pParse->zJson+i,"null",4)==0 && !safe_isalnum(pParse->zJson[i+4]) ){ jsonParseAddNode(pParse, JSON_NULL, 0, 0); return i+4; }else if( c=='t' && strncmp(pParse->zJson+i,"true",4)==0 && !safe_isalnum(pParse->zJson[i+4]) ){ jsonParseAddNode(pParse, JSON_TRUE, 0, 0); return i+4; }else if( c=='f' && strncmp(pParse->zJson+i,"false",5)==0 && !safe_isalnum(pParse->zJson[i+5]) ){ jsonParseAddNode(pParse, JSON_FALSE, 0, 0); return i+5; }else if( c=='-' || (c>='0' && c<='9') ){ /* Parse number */ u8 seenDP = 0; u8 seenE = 0; j = i+1; for(;; j++){ c = pParse->zJson[j]; if( c>='0' && c<='9' ) continue; if( c=='.' ){ if( pParse->zJson[j-1]=='-' ) return -1; if( seenDP ) return -1; seenDP = 1; continue; } if( c=='e' || c=='E' ){ if( pParse->zJson[j-1]<'0' ) return -1; if( seenE ) return -1; seenDP = seenE = 1; c = pParse->zJson[j+1]; if( c=='+' || c=='-' ){ j++; c = pParse->zJson[j+1]; } if( c<'0' || c>'9' ) return -1; continue; } break; } if( pParse->zJson[j-1]<'0' ) return -1; jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT, j - i, &pParse->zJson[i]); return j; }else if( c=='}' ){ return -2; /* End of {...} */ }else if( c==']' ){ return -3; /* End of [...] */ }else if( c==0 ){ return 0; /* End of file */ }else{ return -1; /* Syntax error */ } } /* ** Parse a complete JSON string. Return 0 on success or non-zero if there ** are any errors. If an error occurs, free all memory associated with ** pParse. ** ** pParse is uninitialized when this routine is called. */ static int jsonParse( JsonParse *pParse, /* Initialize and fill this JsonParse object */ sqlite3_context *pCtx, /* Report errors here */ const char *zJson /* Input JSON text to be parsed */ ){ int i; memset(pParse, 0, sizeof(*pParse)); if( zJson==0 ) return 1; pParse->zJson = zJson; i = jsonParseValue(pParse, 0); if( pParse->oom ) i = -1; if( i>0 ){ while( safe_isspace(zJson[i]) ) i++; if( zJson[i] ) i = -1; } if( i<=0 ){ if( pCtx!=0 ){ if( pParse->oom ){ sqlite3_result_error_nomem(pCtx); }else{ sqlite3_result_error(pCtx, "malformed JSON", -1); } } jsonParseReset(pParse); return 1; } return 0; } /* Mark node i of pParse as being a child of iParent. Call recursively ** to fill in all the descendants of node i. */ static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){ JsonNode *pNode = &pParse->aNode[i]; u32 j; pParse->aUp[i] = iParent; switch( pNode->eType ){ case JSON_ARRAY: { for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){ jsonParseFillInParentage(pParse, i+j, i); } break; } case JSON_OBJECT: { for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){ pParse->aUp[i+j] = i; jsonParseFillInParentage(pParse, i+j+1, i); } break; } default: { break; } } } /* ** Compute the parentage of all nodes in a completed parse. */ static int jsonParseFindParents(JsonParse *pParse){ u32 *aUp; assert( pParse->aUp==0 ); aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode ); if( aUp==0 ){ pParse->oom = 1; return SQLITE_NOMEM; } jsonParseFillInParentage(pParse, 0, 0); return SQLITE_OK; } /* ** Compare the OBJECT label at pNode against zKey,nKey. Return true on ** a match. */ static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){ if( pNode->jnFlags & JNODE_RAW ){ if( pNode->n!=nKey ) return 0; return strncmp(pNode->u.zJContent, zKey, nKey)==0; }else{ if( pNode->n!=nKey+2 ) return 0; return strncmp(pNode->u.zJContent+1, zKey, nKey)==0; } } /* forward declaration */ static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**); /* ** Search along zPath to find the node specified. Return a pointer ** to that node, or NULL if zPath is malformed or if there is no such ** node. ** ** If pApnd!=0, then try to append new nodes to complete zPath if it is ** possible to do so and if no existing node corresponds to zPath. If ** new nodes are appended *pApnd is set to 1. */ static JsonNode *jsonLookupStep( JsonParse *pParse, /* The JSON to search */ u32 iRoot, /* Begin the search at this node */ const char *zPath, /* The path to search */ int *pApnd, /* Append nodes to complete path if not NULL */ const char **pzErr /* Make *pzErr point to any syntax error in zPath */ ){ u32 i, j, nKey; const char *zKey; JsonNode *pRoot = &pParse->aNode[iRoot]; if( zPath[0]==0 ) return pRoot; if( zPath[0]=='.' ){ if( pRoot->eType!=JSON_OBJECT ) return 0; zPath++; if( zPath[0]=='"' ){ zKey = zPath + 1; for(i=1; zPath[i] && zPath[i]!='"'; i++){} nKey = i-1; if( zPath[i] ){ i++; }else{ *pzErr = zPath; return 0; } }else{ zKey = zPath; for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){} nKey = i; } if( nKey==0 ){ *pzErr = zPath; return 0; } j = 1; for(;;){ while( j<=pRoot->n ){ if( jsonLabelCompare(pRoot+j, zKey, nKey) ){ return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr); } j++; j += jsonNodeSize(&pRoot[j]); } if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break; iRoot += pRoot->u.iAppend; pRoot = &pParse->aNode[iRoot]; j = 1; } if( pApnd ){ u32 iStart, iLabel; JsonNode *pNode; iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0); iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath); zPath += i; pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr); if( pParse->oom ) return 0; if( pNode ){ pRoot = &pParse->aNode[iRoot]; pRoot->u.iAppend = iStart - iRoot; pRoot->jnFlags |= JNODE_APPEND; pParse->aNode[iLabel].jnFlags |= JNODE_RAW; } return pNode; } }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){ if( pRoot->eType!=JSON_ARRAY ) return 0; i = 0; j = 1; while( safe_isdigit(zPath[j]) ){ i = i*10 + zPath[j] - '0'; j++; } if( zPath[j]!=']' ){ *pzErr = zPath; return 0; } zPath += j + 1; j = 1; for(;;){ while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){ if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--; j += jsonNodeSize(&pRoot[j]); } if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break; iRoot += pRoot->u.iAppend; pRoot = &pParse->aNode[iRoot]; j = 1; } if( j<=pRoot->n ){ return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr); } if( i==0 && pApnd ){ u32 iStart; JsonNode *pNode; iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0); pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr); if( pParse->oom ) return 0; if( pNode ){ pRoot = &pParse->aNode[iRoot]; pRoot->u.iAppend = iStart - iRoot; pRoot->jnFlags |= JNODE_APPEND; } return pNode; } }else{ *pzErr = zPath; } return 0; } /* ** Append content to pParse that will complete zPath. Return a pointer ** to the inserted node, or return NULL if the append fails. */ static JsonNode *jsonLookupAppend( JsonParse *pParse, /* Append content to the JSON parse */ const char *zPath, /* Description of content to append */ int *pApnd, /* Set this flag to 1 */ const char **pzErr /* Make this point to any syntax error */ ){ *pApnd = 1; if( zPath[0]==0 ){ jsonParseAddNode(pParse, JSON_NULL, 0, 0); return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1]; } if( zPath[0]=='.' ){ jsonParseAddNode(pParse, JSON_OBJECT, 0, 0); }else if( strncmp(zPath,"[0]",3)==0 ){ jsonParseAddNode(pParse, JSON_ARRAY, 0, 0); }else{ return 0; } if( pParse->oom ) return 0; return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr); } /* ** Return the text of a syntax error message on a JSON path. Space is ** obtained from sqlite3_malloc(). */ static char *jsonPathSyntaxError(const char *zErr){ return sqlite3_mprintf("JSON path error near '%q'", zErr); } /* ** Do a node lookup using zPath. Return a pointer to the node on success. ** Return NULL if not found or if there is an error. ** ** On an error, write an error message into pCtx and increment the ** pParse->nErr counter. ** ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if ** nodes are appended. */ static JsonNode *jsonLookup( JsonParse *pParse, /* The JSON to search */ const char *zPath, /* The path to search */ int *pApnd, /* Append nodes to complete path if not NULL */ sqlite3_context *pCtx /* Report errors here, if not NULL */ ){ const char *zErr = 0; JsonNode *pNode = 0; char *zMsg; if( zPath==0 ) return 0; if( zPath[0]!='$' ){ zErr = zPath; goto lookup_err; } zPath++; pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr); if( zErr==0 ) return pNode; lookup_err: pParse->nErr++; assert( zErr!=0 && pCtx!=0 ); zMsg = jsonPathSyntaxError(zErr); if( zMsg ){ sqlite3_result_error(pCtx, zMsg, -1); sqlite3_free(zMsg); }else{ sqlite3_result_error_nomem(pCtx); } return 0; } /* ** Report the wrong number of arguments for json_insert(), json_replace() ** or json_set(). */ static void jsonWrongNumArgs( sqlite3_context *pCtx, const char *zFuncName ){ char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments", zFuncName); sqlite3_result_error(pCtx, zMsg, -1); sqlite3_free(zMsg); } /**************************************************************************** ** SQL functions used for testing and debugging ****************************************************************************/ #ifdef SQLITE_DEBUG /* ** The json_parse(JSON) function returns a string which describes ** a parse of the JSON provided. Or it returns NULL if JSON is not ** well-formed. */ static void jsonParseFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonString s; /* Output string - not real JSON */ JsonParse x; /* The parse */ u32 i; assert( argc==1 ); if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; jsonParseFindParents(&x); jsonInit(&s, ctx); for(i=0; i<x.nNode; i++){ const char *zType; if( x.aNode[i].jnFlags & JNODE_LABEL ){ assert( x.aNode[i].eType==JSON_STRING ); zType = "label"; }else{ zType = jsonType[x.aNode[i].eType]; } jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d", i, zType, x.aNode[i].n, x.aUp[i]); if( x.aNode[i].u.zJContent!=0 ){ jsonAppendRaw(&s, " ", 1); jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n); } jsonAppendRaw(&s, "\n", 1); } jsonParseReset(&x); jsonResult(&s); } /* ** The json_test1(JSON) function return true (1) if the input is JSON ** text generated by another json function. It returns (0) if the input ** is not known to be JSON. */ static void jsonTest1Func( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ UNUSED_PARAM(argc); sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE); } #endif /* SQLITE_DEBUG */ /**************************************************************************** ** Scalar SQL function implementations ****************************************************************************/ /* ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value ** corresponding to the SQL value input. Mostly this means putting ** double-quotes around strings and returning the unquoted string "null" ** when given a NULL input. */ static void jsonQuoteFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonString jx; UNUSED_PARAM(argc); jsonInit(&jx, ctx); jsonAppendValue(&jx, argv[0]); jsonResult(&jx); sqlite3_result_subtype(ctx, JSON_SUBTYPE); } /* ** Implementation of the json_array(VALUE,...) function. Return a JSON ** array that contains all values given in arguments. Or if any argument ** is a BLOB, throw an error. */ static void jsonArrayFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ int i; JsonString jx; jsonInit(&jx, ctx); jsonAppendChar(&jx, '['); for(i=0; i<argc; i++){ jsonAppendSeparator(&jx); jsonAppendValue(&jx, argv[i]); } jsonAppendChar(&jx, ']'); jsonResult(&jx); sqlite3_result_subtype(ctx, JSON_SUBTYPE); } /* ** json_array_length(JSON) ** json_array_length(JSON, PATH) ** ** Return the number of elements in the top-level JSON array. ** Return 0 if the input is not a well-formed JSON array. */ static void jsonArrayLengthFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonParse x; /* The parse */ sqlite3_int64 n = 0; u32 i; JsonNode *pNode; if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; assert( x.nNode ); if( argc==2 ){ const char *zPath = (const char*)sqlite3_value_text(argv[1]); pNode = jsonLookup(&x, zPath, 0, ctx); }else{ pNode = x.aNode; } if( pNode==0 ){ x.nErr = 1; }else if( pNode->eType==JSON_ARRAY ){ assert( (pNode->jnFlags & JNODE_APPEND)==0 ); for(i=1; i<=pNode->n; n++){ i += jsonNodeSize(&pNode[i]); } } if( x.nErr==0 ) sqlite3_result_int64(ctx, n); jsonParseReset(&x); } /* ** json_extract(JSON, PATH, ...) ** ** Return the element described by PATH. Return NULL if there is no ** PATH element. If there are multiple PATHs, then return a JSON array ** with the result from each path. Throw an error if the JSON or any PATH ** is malformed. */ static void jsonExtractFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonParse x; /* The parse */ JsonNode *pNode; const char *zPath; JsonString jx; int i; if( argc<2 ) return; if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; jsonInit(&jx, ctx); jsonAppendChar(&jx, '['); for(i=1; i<argc; i++){ zPath = (const char*)sqlite3_value_text(argv[i]); pNode = jsonLookup(&x, zPath, 0, ctx); if( x.nErr ) break; if( argc>2 ){ jsonAppendSeparator(&jx); if( pNode ){ jsonRenderNode(pNode, &jx, 0); }else{ jsonAppendRaw(&jx, "null", 4); } }else if( pNode ){ jsonReturn(pNode, ctx, 0); } } if( argc>2 && i==argc ){ jsonAppendChar(&jx, ']'); jsonResult(&jx); sqlite3_result_subtype(ctx, JSON_SUBTYPE); } jsonReset(&jx); jsonParseReset(&x); } /* ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON ** object that contains all name/value given in arguments. Or if any name ** is not a string or if any value is a BLOB, throw an error. */ static void jsonObjectFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ int i; JsonString jx; const char *z; u32 n; if( argc&1 ){ sqlite3_result_error(ctx, "json_object() requires an even number " "of arguments", -1); return; } jsonInit(&jx, ctx); jsonAppendChar(&jx, '{'); for(i=0; i<argc; i+=2){ if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){ sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1); jsonReset(&jx); return; } jsonAppendSeparator(&jx); z = (const char*)sqlite3_value_text(argv[i]); n = (u32)sqlite3_value_bytes(argv[i]); jsonAppendString(&jx, z, n); jsonAppendChar(&jx, ':'); jsonAppendValue(&jx, argv[i+1]); } jsonAppendChar(&jx, '}'); jsonResult(&jx); sqlite3_result_subtype(ctx, JSON_SUBTYPE); } /* ** json_remove(JSON, PATH, ...) ** ** Remove the named elements from JSON and return the result. malformed ** JSON or PATH arguments result in an error. */ static void jsonRemoveFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonParse x; /* The parse */ JsonNode *pNode; const char *zPath; u32 i; if( argc<1 ) return; if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; assert( x.nNode ); for(i=1; i<(u32)argc; i++){ zPath = (const char*)sqlite3_value_text(argv[i]); if( zPath==0 ) goto remove_done; pNode = jsonLookup(&x, zPath, 0, ctx); if( x.nErr ) goto remove_done; if( pNode ) pNode->jnFlags |= JNODE_REMOVE; } if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){ jsonReturnJson(x.aNode, ctx, 0); } remove_done: jsonParseReset(&x); } /* ** json_replace(JSON, PATH, VALUE, ...) ** ** Replace the value at PATH with VALUE. If PATH does not already exist, ** this routine is a no-op. If JSON or PATH is malformed, throw an error. */ static void jsonReplaceFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonParse x; /* The parse */ JsonNode *pNode; const char *zPath; u32 i; if( argc<1 ) return; if( (argc&1)==0 ) { jsonWrongNumArgs(ctx, "replace"); return; } if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; assert( x.nNode ); for(i=1; i<(u32)argc; i+=2){ zPath = (const char*)sqlite3_value_text(argv[i]); pNode = jsonLookup(&x, zPath, 0, ctx); if( x.nErr ) goto replace_err; if( pNode ){ pNode->jnFlags |= (u8)JNODE_REPLACE; pNode->iVal = (u8)(i+1); } } if( x.aNode[0].jnFlags & JNODE_REPLACE ){ sqlite3_result_value(ctx, argv[x.aNode[0].iVal]); }else{ jsonReturnJson(x.aNode, ctx, argv); } replace_err: jsonParseReset(&x); } /* ** json_set(JSON, PATH, VALUE, ...) ** ** Set the value at PATH to VALUE. Create the PATH if it does not already ** exist. Overwrite existing values that do exist. ** If JSON or PATH is malformed, throw an error. ** ** json_insert(JSON, PATH, VALUE, ...) ** ** Create PATH and initialize it to VALUE. If PATH already exists, this ** routine is a no-op. If JSON or PATH is malformed, throw an error. */ static void jsonSetFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonParse x; /* The parse */ JsonNode *pNode; const char *zPath; u32 i; int bApnd; int bIsSet = *(int*)sqlite3_user_data(ctx); if( argc<1 ) return; if( (argc&1)==0 ) { jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert"); return; } if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; assert( x.nNode ); for(i=1; i<(u32)argc; i+=2){ zPath = (const char*)sqlite3_value_text(argv[i]); bApnd = 0; pNode = jsonLookup(&x, zPath, &bApnd, ctx); if( x.oom ){ sqlite3_result_error_nomem(ctx); goto jsonSetDone; }else if( x.nErr ){ goto jsonSetDone; }else if( pNode && (bApnd || bIsSet) ){ pNode->jnFlags |= (u8)JNODE_REPLACE; pNode->iVal = (u8)(i+1); } } if( x.aNode[0].jnFlags & JNODE_REPLACE ){ sqlite3_result_value(ctx, argv[x.aNode[0].iVal]); }else{ jsonReturnJson(x.aNode, ctx, argv); } jsonSetDone: jsonParseReset(&x); } /* ** json_type(JSON) ** json_type(JSON, PATH) ** ** Return the top-level "type" of a JSON string. Throw an error if ** either the JSON or PATH inputs are not well-formed. */ static void jsonTypeFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonParse x; /* The parse */ const char *zPath; JsonNode *pNode; if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; assert( x.nNode ); if( argc==2 ){ zPath = (const char*)sqlite3_value_text(argv[1]); pNode = jsonLookup(&x, zPath, 0, ctx); }else{ pNode = x.aNode; } if( pNode ){ sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC); } jsonParseReset(&x); } /* ** json_valid(JSON) ** ** Return 1 if JSON is a well-formed JSON string according to RFC-7159. ** Return 0 otherwise. */ static void jsonValidFunc( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonParse x; /* The parse */ int rc = 0; UNUSED_PARAM(argc); if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){ rc = 1; } jsonParseReset(&x); sqlite3_result_int(ctx, rc); } /**************************************************************************** ** Aggregate SQL function implementations ****************************************************************************/ /* ** json_group_array(VALUE) ** ** Return a JSON array composed of all values in the aggregate. */ static void jsonArrayStep( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonString *pStr; UNUSED_PARAM(argc); pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); if( pStr ){ if( pStr->zBuf==0 ){ jsonInit(pStr, ctx); jsonAppendChar(pStr, '['); }else{ jsonAppendChar(pStr, ','); pStr->pCtx = ctx; } jsonAppendValue(pStr, argv[0]); } } static void jsonArrayFinal(sqlite3_context *ctx){ JsonString *pStr; pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); if( pStr ){ pStr->pCtx = ctx; jsonAppendChar(pStr, ']'); if( pStr->bErr ){ if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx); assert( pStr->bStatic ); }else{ sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed, pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free); pStr->bStatic = 1; } }else{ sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC); } sqlite3_result_subtype(ctx, JSON_SUBTYPE); } /* ** json_group_obj(NAME,VALUE) ** ** Return a JSON object composed of all names and values in the aggregate. */ static void jsonObjectStep( sqlite3_context *ctx, int argc, sqlite3_value **argv ){ JsonString *pStr; const char *z; u32 n; UNUSED_PARAM(argc); pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); if( pStr ){ if( pStr->zBuf==0 ){ jsonInit(pStr, ctx); jsonAppendChar(pStr, '{'); }else{ jsonAppendChar(pStr, ','); pStr->pCtx = ctx; } z = (const char*)sqlite3_value_text(argv[0]); n = (u32)sqlite3_value_bytes(argv[0]); jsonAppendString(pStr, z, n); jsonAppendChar(pStr, ':'); jsonAppendValue(pStr, argv[1]); } } static void jsonObjectFinal(sqlite3_context *ctx){ JsonString *pStr; pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); if( pStr ){ jsonAppendChar(pStr, '}'); if( pStr->bErr ){ if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx); assert( pStr->bStatic ); }else{ sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed, pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free); pStr->bStatic = 1; } }else{ sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC); } sqlite3_result_subtype(ctx, JSON_SUBTYPE); } #ifndef SQLITE_OMIT_VIRTUALTABLE /**************************************************************************** ** The json_each virtual table ****************************************************************************/ typedef struct JsonEachCursor JsonEachCursor; struct JsonEachCursor { sqlite3_vtab_cursor base; /* Base class - must be first */ u32 iRowid; /* The rowid */ u32 iBegin; /* The first node of the scan */ u32 i; /* Index in sParse.aNode[] of current row */ u32 iEnd; /* EOF when i equals or exceeds this value */ u8 eType; /* Type of top-level element */ u8 bRecursive; /* True for json_tree(). False for json_each() */ char *zJson; /* Input JSON */ char *zRoot; /* Path by which to filter zJson */ JsonParse sParse; /* Parse of the input JSON */ }; /* Constructor for the json_each virtual table */ static int jsonEachConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ sqlite3_vtab *pNew; int rc; /* Column numbers */ #define JEACH_KEY 0 #define JEACH_VALUE 1 #define JEACH_TYPE 2 #define JEACH_ATOM 3 #define JEACH_ID 4 #define JEACH_PARENT 5 #define JEACH_FULLKEY 6 #define JEACH_PATH 7 #define JEACH_JSON 8 #define JEACH_ROOT 9 UNUSED_PARAM(pzErr); UNUSED_PARAM(argv); UNUSED_PARAM(argc); UNUSED_PARAM(pAux); rc = sqlite3_declare_vtab(db, "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path," "json HIDDEN,root HIDDEN)"); if( rc==SQLITE_OK ){ pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) ); if( pNew==0 ) return SQLITE_NOMEM; memset(pNew, 0, sizeof(*pNew)); } return rc; } /* destructor for json_each virtual table */ static int jsonEachDisconnect(sqlite3_vtab *pVtab){ sqlite3_free(pVtab); return SQLITE_OK; } /* constructor for a JsonEachCursor object for json_each(). */ static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ JsonEachCursor *pCur; UNUSED_PARAM(p); pCur = sqlite3_malloc( sizeof(*pCur) ); if( pCur==0 ) return SQLITE_NOMEM; memset(pCur, 0, sizeof(*pCur)); *ppCursor = &pCur->base; return SQLITE_OK; } /* constructor for a JsonEachCursor object for json_tree(). */ static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ int rc = jsonEachOpenEach(p, ppCursor); if( rc==SQLITE_OK ){ JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor; pCur->bRecursive = 1; } return rc; } /* Reset a JsonEachCursor back to its original state. Free any memory ** held. */ static void jsonEachCursorReset(JsonEachCursor *p){ sqlite3_free(p->zJson); sqlite3_free(p->zRoot); jsonParseReset(&p->sParse); p->iRowid = 0; p->i = 0; p->iEnd = 0; p->eType = 0; p->zJson = 0; p->zRoot = 0; } /* Destructor for a jsonEachCursor object */ static int jsonEachClose(sqlite3_vtab_cursor *cur){ JsonEachCursor *p = (JsonEachCursor*)cur; jsonEachCursorReset(p); sqlite3_free(cur); return SQLITE_OK; } /* Return TRUE if the jsonEachCursor object has been advanced off the end ** of the JSON object */ static int jsonEachEof(sqlite3_vtab_cursor *cur){ JsonEachCursor *p = (JsonEachCursor*)cur; return p->i >= p->iEnd; } /* Advance the cursor to the next element for json_tree() */ static int jsonEachNext(sqlite3_vtab_cursor *cur){ JsonEachCursor *p = (JsonEachCursor*)cur; if( p->bRecursive ){ if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++; p->i++; p->iRowid++; if( p->i<p->iEnd ){ u32 iUp = p->sParse.aUp[p->i]; JsonNode *pUp = &p->sParse.aNode[iUp]; p->eType = pUp->eType; if( pUp->eType==JSON_ARRAY ){ if( iUp==p->i-1 ){ pUp->u.iKey = 0; }else{ pUp->u.iKey++; } } } }else{ switch( p->eType ){ case JSON_ARRAY: { p->i += jsonNodeSize(&p->sParse.aNode[p->i]); p->iRowid++; break; } case JSON_OBJECT: { p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]); p->iRowid++; break; } default: { p->i = p->iEnd; break; } } } return SQLITE_OK; } /* Append the name of the path for element i to pStr */ static void jsonEachComputePath( JsonEachCursor *p, /* The cursor */ JsonString *pStr, /* Write the path here */ u32 i /* Path to this element */ ){ JsonNode *pNode, *pUp; u32 iUp; if( i==0 ){ jsonAppendChar(pStr, '$'); return; } iUp = p->sParse.aUp[i]; jsonEachComputePath(p, pStr, iUp); pNode = &p->sParse.aNode[i]; pUp = &p->sParse.aNode[iUp]; if( pUp->eType==JSON_ARRAY ){ jsonPrintf(30, pStr, "[%d]", pUp->u.iKey); }else{ assert( pUp->eType==JSON_OBJECT ); if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--; assert( pNode->eType==JSON_STRING ); assert( pNode->jnFlags & JNODE_LABEL ); jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1); } } /* Return the value of a column */ static int jsonEachColumn( sqlite3_vtab_cursor *cur, /* The cursor */ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ int i /* Which column to return */ ){ JsonEachCursor *p = (JsonEachCursor*)cur; JsonNode *pThis = &p->sParse.aNode[p->i]; switch( i ){ case JEACH_KEY: { if( p->i==0 ) break; if( p->eType==JSON_OBJECT ){ jsonReturn(pThis, ctx, 0); }else if( p->eType==JSON_ARRAY ){ u32 iKey; if( p->bRecursive ){ if( p->iRowid==0 ) break; iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey; }else{ iKey = p->iRowid; } sqlite3_result_int64(ctx, (sqlite3_int64)iKey); } break; } case JEACH_VALUE: { if( pThis->jnFlags & JNODE_LABEL ) pThis++; jsonReturn(pThis, ctx, 0); break; } case JEACH_TYPE: { if( pThis->jnFlags & JNODE_LABEL ) pThis++; sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC); break; } case JEACH_ATOM: { if( pThis->jnFlags & JNODE_LABEL ) pThis++; if( pThis->eType>=JSON_ARRAY ) break; jsonReturn(pThis, ctx, 0); break; } case JEACH_ID: { sqlite3_result_int64(ctx, (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0)); break; } case JEACH_PARENT: { if( p->i>p->iBegin && p->bRecursive ){ sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]); } break; } case JEACH_FULLKEY: { JsonString x; jsonInit(&x, ctx); if( p->bRecursive ){ jsonEachComputePath(p, &x, p->i); }else{ if( p->zRoot ){ jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot)); }else{ jsonAppendChar(&x, '$'); } if( p->eType==JSON_ARRAY ){ jsonPrintf(30, &x, "[%d]", p->iRowid); }else{ jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1); } } jsonResult(&x); break; } case JEACH_PATH: { if( p->bRecursive ){ JsonString x; jsonInit(&x, ctx); jsonEachComputePath(p, &x, p->sParse.aUp[p->i]); jsonResult(&x); break; } /* For json_each() path and root are the same so fall through ** into the root case */ } default: { const char *zRoot = p->zRoot; if( zRoot==0 ) zRoot = "$"; sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC); break; } case JEACH_JSON: { assert( i==JEACH_JSON ); sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC); break; } } return SQLITE_OK; } /* Return the current rowid value */ static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ JsonEachCursor *p = (JsonEachCursor*)cur; *pRowid = p->iRowid; return SQLITE_OK; } /* The query strategy is to look for an equality constraint on the json ** column. Without such a constraint, the table cannot operate. idxNum is ** 1 if the constraint is found, 3 if the constraint and zRoot are found, ** and 0 otherwise. */ static int jsonEachBestIndex( sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo ){ int i; int jsonIdx = -1; int rootIdx = -1; const struct sqlite3_index_constraint *pConstraint; UNUSED_PARAM(tab); pConstraint = pIdxInfo->aConstraint; for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ if( pConstraint->usable==0 ) continue; if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; switch( pConstraint->iColumn ){ case JEACH_JSON: jsonIdx = i; break; case JEACH_ROOT: rootIdx = i; break; default: /* no-op */ break; } } if( jsonIdx<0 ){ pIdxInfo->idxNum = 0; pIdxInfo->estimatedCost = 1e99; }else{ pIdxInfo->estimatedCost = 1.0; pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1; pIdxInfo->aConstraintUsage[jsonIdx].omit = 1; if( rootIdx<0 ){ pIdxInfo->idxNum = 1; }else{ pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2; pIdxInfo->aConstraintUsage[rootIdx].omit = 1; pIdxInfo->idxNum = 3; } } return SQLITE_OK; } /* Start a search on a new JSON string */ static int jsonEachFilter( sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ JsonEachCursor *p = (JsonEachCursor*)cur; const char *z; const char *zRoot = 0; sqlite3_int64 n; UNUSED_PARAM(idxStr); UNUSED_PARAM(argc); jsonEachCursorReset(p); if( idxNum==0 ) return SQLITE_OK; z = (const char*)sqlite3_value_text(argv[0]); if( z==0 ) return SQLITE_OK; n = sqlite3_value_bytes(argv[0]); p->zJson = sqlite3_malloc64( n+1 ); if( p->zJson==0 ) return SQLITE_NOMEM; memcpy(p->zJson, z, (size_t)n+1); if( jsonParse(&p->sParse, 0, p->zJson) ){ int rc = SQLITE_NOMEM; if( p->sParse.oom==0 ){ sqlite3_free(cur->pVtab->zErrMsg); cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON"); if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR; } jsonEachCursorReset(p); return rc; }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){ jsonEachCursorReset(p); return SQLITE_NOMEM; }else{ JsonNode *pNode = 0; if( idxNum==3 ){ const char *zErr = 0; zRoot = (const char*)sqlite3_value_text(argv[1]); if( zRoot==0 ) return SQLITE_OK; n = sqlite3_value_bytes(argv[1]); p->zRoot = sqlite3_malloc64( n+1 ); if( p->zRoot==0 ) return SQLITE_NOMEM; memcpy(p->zRoot, zRoot, (size_t)n+1); if( zRoot[0]!='$' ){ zErr = zRoot; }else{ pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr); } if( zErr ){ sqlite3_free(cur->pVtab->zErrMsg); cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr); jsonEachCursorReset(p); return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; }else if( pNode==0 ){ return SQLITE_OK; } }else{ pNode = p->sParse.aNode; } p->iBegin = p->i = (int)(pNode - p->sParse.aNode); p->eType = pNode->eType; if( p->eType>=JSON_ARRAY ){ pNode->u.iKey = 0; p->iEnd = p->i + pNode->n + 1; if( p->bRecursive ){ p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType; if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){ p->i--; } }else{ p->i++; } }else{ p->iEnd = p->i+1; } } return SQLITE_OK; } /* The methods of the json_each virtual table */ static sqlite3_module jsonEachModule = { 0, /* iVersion */ 0, /* xCreate */ jsonEachConnect, /* xConnect */ jsonEachBestIndex, /* xBestIndex */ jsonEachDisconnect, /* xDisconnect */ 0, /* xDestroy */ jsonEachOpenEach, /* xOpen - open a cursor */ jsonEachClose, /* xClose - close a cursor */ jsonEachFilter, /* xFilter - configure scan constraints */ jsonEachNext, /* xNext - advance a cursor */ jsonEachEof, /* xEof - check for end of scan */ jsonEachColumn, /* xColumn - read data */ jsonEachRowid, /* xRowid - read data */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindMethod */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; /* The methods of the json_tree virtual table. */ static sqlite3_module jsonTreeModule = { 0, /* iVersion */ 0, /* xCreate */ jsonEachConnect, /* xConnect */ jsonEachBestIndex, /* xBestIndex */ jsonEachDisconnect, /* xDisconnect */ 0, /* xDestroy */ jsonEachOpenTree, /* xOpen - open a cursor */ jsonEachClose, /* xClose - close a cursor */ jsonEachFilter, /* xFilter - configure scan constraints */ jsonEachNext, /* xNext - advance a cursor */ jsonEachEof, /* xEof - check for end of scan */ jsonEachColumn, /* xColumn - read data */ jsonEachRowid, /* xRowid - read data */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindMethod */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0 /* xRollbackTo */ }; #endif /* SQLITE_OMIT_VIRTUALTABLE */ /**************************************************************************** ** The following routines are the only publically visible identifiers in this ** file. Call the following routines in order to register the various SQL ** functions and the virtual table implemented by this file. ****************************************************************************/ SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){ int rc = SQLITE_OK; unsigned int i; static const struct { const char *zName; int nArg; int flag; void (*xFunc)(sqlite3_context*,int,sqlite3_value**); } aFunc[] = { { "json", 1, 0, jsonRemoveFunc }, { "json_array", -1, 0, jsonArrayFunc }, { "json_array_length", 1, 0, jsonArrayLengthFunc }, { "json_array_length", 2, 0, jsonArrayLengthFunc }, { "json_extract", -1, 0, jsonExtractFunc }, { "json_insert", -1, 0, jsonSetFunc }, { "json_object", -1, 0, jsonObjectFunc }, { "json_quote", 1, 0, jsonQuoteFunc }, { "json_remove", -1, 0, jsonRemoveFunc }, { "json_replace", -1, 0, jsonReplaceFunc }, { "json_set", -1, 1, jsonSetFunc }, { "json_type", 1, 0, jsonTypeFunc }, { "json_type", 2, 0, jsonTypeFunc }, { "json_valid", 1, 0, jsonValidFunc }, #if SQLITE_DEBUG /* DEBUG and TESTING functions */ { "json_parse", 1, 0, jsonParseFunc }, { "json_test1", 1, 0, jsonTest1Func }, #endif }; static const struct { const char *zName; int nArg; void (*xStep)(sqlite3_context*,int,sqlite3_value**); void (*xFinal)(sqlite3_context*); } aAgg[] = { { "json_group_array", 1, jsonArrayStep, jsonArrayFinal }, { "json_group_object", 2, jsonObjectStep, jsonObjectFinal }, }; #ifndef SQLITE_OMIT_VIRTUALTABLE static const struct { const char *zName; sqlite3_module *pModule; } aMod[] = { { "json_each", &jsonEachModule }, { "json_tree", &jsonTreeModule }, }; #endif for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){ rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, SQLITE_UTF8 | SQLITE_DETERMINISTIC, (void*)&aFunc[i].flag, aFunc[i].xFunc, 0, 0); } for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){ rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg, SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0, 0, aAgg[i].xStep, aAgg[i].xFinal); } #ifndef SQLITE_OMIT_VIRTUALTABLE for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){ rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0); } #endif return rc; } #ifndef SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_json_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return sqlite3Json1Init(db); } #endif #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */ /************** End of json1.c ***********************************************/ /************** Begin file fts5.c ********************************************/ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif #if defined(NDEBUG) && defined(SQLITE_DEBUG) # undef NDEBUG #endif /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Interfaces to extend FTS5. Using the interfaces defined in this file, ** FTS5 may be extended with: ** ** * custom tokenizers, and ** * custom auxiliary functions. */ #ifndef _FTS5_H #define _FTS5_H /* #include "sqlite3.h" */ #if 0 extern "C" { #endif /************************************************************************* ** CUSTOM AUXILIARY FUNCTIONS ** ** Virtual table implementations may overload SQL functions by implementing ** the sqlite3_module.xFindFunction() method. */ typedef struct Fts5ExtensionApi Fts5ExtensionApi; typedef struct Fts5Context Fts5Context; typedef struct Fts5PhraseIter Fts5PhraseIter; typedef void (*fts5_extension_function)( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ sqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ sqlite3_value **apVal /* Array of trailing arguments */ ); struct Fts5PhraseIter { const unsigned char *a; const unsigned char *b; }; /* ** EXTENSION API FUNCTIONS ** ** xUserData(pFts): ** Return a copy of the context pointer the extension function was ** registered with. ** ** xColumnTotalSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the FTS5 table. Or, if iCol is ** non-negative but less than the number of columns in the table, return ** the total number of tokens in column iCol, considering all rows in ** the FTS5 table. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** xColumnCount(pFts): ** Return the number of columns in the table. ** ** xColumnSize(pFts, iCol, pnToken): ** If parameter iCol is less than zero, set output variable *pnToken ** to the total number of tokens in the current row. Or, if iCol is ** non-negative but less than the number of columns in the table, set ** *pnToken to the number of tokens in column iCol of the current row. ** ** If parameter iCol is greater than or equal to the number of columns ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. ** an OOM condition or IO error), an appropriate SQLite error code is ** returned. ** ** This function may be quite inefficient if used with an FTS5 table ** created with the "columnsize=0" option. ** ** xColumnText: ** This function attempts to retrieve the text of column iCol of the ** current document. If successful, (*pz) is set to point to a buffer ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise, ** if an error occurs, an SQLite error code is returned and the final values ** of (*pz) and (*pn) are undefined. ** ** xPhraseCount: ** Returns the number of phrases in the current query expression. ** ** xPhraseSize: ** Returns the number of tokens in phrase iPhrase of the query. Phrases ** are numbered starting from zero. ** ** xInstCount: ** Set *pnInst to the total number of occurrences of all phrases within ** the query within the current row. Return SQLITE_OK if successful, or ** an error code (i.e. SQLITE_NOMEM) if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always returns 0. ** ** xInst: ** Query for the details of phrase match iIdx within the current row. ** Phrase matches are numbered starting from zero, so the iIdx argument ** should be greater than or equal to zero and smaller than the value ** output by xInstCount(). ** ** Usually, output parameter *piPhrase is set to the phrase number, *piCol ** to the column in which it occurs and *piOff the token offset of the ** first token of the phrase. The exception is if the table was created ** with the offsets=0 option specified. In this case *piOff is always ** set to -1. ** ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) ** if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. ** ** xRowid: ** Returns the rowid of the current row. ** ** xTokenize: ** Tokenize text using the tokenizer belonging to the FTS5 table. ** ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback): ** This API function is used to query the FTS table for phrase iPhrase ** of the current query. Specifically, a query equivalent to: ** ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid ** ** with $p set to a phrase equivalent to the phrase iPhrase of the ** current query is executed. Any column filter that applies to ** phrase iPhrase of the current query is included in $p. For each ** row visited, the callback function passed as the fourth argument ** is invoked. The context and API objects passed to the callback ** function may be used to access the properties of each matched row. ** Invoking Api.xUserData() returns a copy of the pointer passed as ** the third argument to pUserData. ** ** If the callback function returns any value other than SQLITE_OK, the ** query is abandoned and the xQueryPhrase function returns immediately. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK. ** Otherwise, the error code is propagated upwards. ** ** If the query runs to completion without incident, SQLITE_OK is returned. ** Or, if some error occurs before the query completes or is aborted by ** the callback, an SQLite error code is returned. ** ** ** xSetAuxdata(pFts5, pAux, xDelete) ** ** Save the pointer passed as the second argument as the extension functions ** "auxiliary data". The pointer may then be retrieved by the current or any ** future invocation of the same fts5 extension function made as part of ** of the same MATCH query using the xGetAuxdata() API. ** ** Each extension function is allocated a single auxiliary data slot for ** each FTS query (MATCH expression). If the extension function is invoked ** more than once for a single FTS query, then all invocations share a ** single auxiliary data context. ** ** If there is already an auxiliary data pointer when this function is ** invoked, then it is replaced by the new pointer. If an xDelete callback ** was specified along with the original pointer, it is invoked at this ** point. ** ** The xDelete callback, if one is specified, is also invoked on the ** auxiliary data pointer after the FTS5 query has finished. ** ** If an error (e.g. an OOM condition) occurs within this function, an ** the auxiliary data is set to NULL and an error code returned. If the ** xDelete parameter was not NULL, it is invoked on the auxiliary data ** pointer before returning. ** ** ** xGetAuxdata(pFts5, bClear) ** ** Returns the current auxiliary data pointer for the fts5 extension ** function. See the xSetAuxdata() method for details. ** ** If the bClear argument is non-zero, then the auxiliary data is cleared ** (set to NULL) before this function returns. In this case the xDelete, ** if any, is not invoked. ** ** ** xRowCount(pFts5, pnRow) ** ** This function is used to retrieve the total number of rows in the table. ** In other words, the same value that would be returned by: ** ** SELECT count(*) FROM ftstable; ** ** xPhraseFirst() ** This function is used, along with type Fts5PhraseIter and the xPhraseNext ** method, to iterate through all instances of a single query phrase within ** the current row. This is the same information as is accessible via the ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient ** to use, this API may be faster under some circumstances. To iterate ** through instances of phrase iPhrase, use the following code: ** ** Fts5PhraseIter iter; ** int iCol, iOff; ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff); ** iCol>=0; ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff) ** ){ ** // An instance of phrase iPhrase at offset iOff of column iCol ** } ** ** The Fts5PhraseIter structure is defined above. Applications should not ** modify this structure directly - it should only be used as shown above ** with the xPhraseFirst() and xPhraseNext() API methods (and by ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below). ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. If the FTS5 table is created ** with either "detail=none" or "detail=column" and "content=" option ** (i.e. if it is a contentless table), then this API always iterates ** through an empty set (all calls to xPhraseFirst() set iCol to -1). ** ** xPhraseNext() ** See xPhraseFirst above. ** ** xPhraseFirstColumn() ** This function and xPhraseNextColumn() are similar to the xPhraseFirst() ** and xPhraseNext() APIs described above. The difference is that instead ** of iterating through all instances of a phrase in the current row, these ** APIs are used to iterate through the set of columns in the current row ** that contain one or more instances of a specified phrase. For example: ** ** Fts5PhraseIter iter; ** int iCol; ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol); ** iCol>=0; ** pApi->xPhraseNextColumn(pFts, &iter, &iCol) ** ){ ** // Column iCol contains at least one instance of phrase iPhrase ** } ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" option. If the FTS5 table is created with either ** "detail=none" "content=" option (i.e. if it is a contentless table), ** then this API always iterates through an empty set (all calls to ** xPhraseFirstColumn() set iCol to -1). ** ** The information accessed using this API and its companion ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext ** (or xInst/xInstCount). The chief advantage of this API is that it is ** significantly more efficient than those alternatives when used with ** "detail=column" tables. ** ** xPhraseNextColumn() ** See xPhraseFirstColumn above. */ struct Fts5ExtensionApi { int iVersion; /* Currently always set to 3 */ void *(*xUserData)(Fts5Context*); int (*xColumnCount)(Fts5Context*); int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); int (*xTokenize)(Fts5Context*, const char *pText, int nText, /* Text to tokenize */ void *pCtx, /* Context passed to xToken() */ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ); int (*xPhraseCount)(Fts5Context*); int (*xPhraseSize)(Fts5Context*, int iPhrase); int (*xInstCount)(Fts5Context*, int *pnInst); int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); sqlite3_int64 (*xRowid)(Fts5Context*); int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData, int(*)(const Fts5ExtensionApi*,Fts5Context*,void*) ); int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*)); void *(*xGetAuxdata)(Fts5Context*, int bClear); int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*); void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff); int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*); void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol); }; /* ** CUSTOM AUXILIARY FUNCTIONS *************************************************************************/ /************************************************************************* ** CUSTOM TOKENIZERS ** ** Applications may also register custom tokenizer types. A tokenizer ** is registered by providing fts5 with a populated instance of the ** following structure. All structure methods must be defined, setting ** any member of the fts5_tokenizer struct to NULL leads to undefined ** behaviour. The structure methods are expected to function as follows: ** ** xCreate: ** This function is used to allocate and initialize a tokenizer instance. ** A tokenizer instance is required to actually tokenize text. ** ** The first argument passed to this function is a copy of the (void*) ** pointer provided by the application when the fts5_tokenizer object ** was registered with FTS5 (the third argument to xCreateTokenizer()). ** The second and third arguments are an array of nul-terminated strings ** containing the tokenizer arguments, if any, specified following the ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used ** to create the FTS5 table. ** ** The final argument is an output variable. If successful, (*ppOut) ** should be set to point to the new tokenizer handle and SQLITE_OK ** returned. If an error occurs, some value other than SQLITE_OK should ** be returned. In this case, fts5 assumes that the final value of *ppOut ** is undefined. ** ** xDelete: ** This function is invoked to delete a tokenizer handle previously ** allocated using xCreate(). Fts5 guarantees that this function will ** be invoked exactly once for each successful call to xCreate(). ** ** xTokenize: ** This function is expected to tokenize the nText byte string indicated ** by argument pText. pText may or may not be nul-terminated. The first ** argument passed to this function is a pointer to an Fts5Tokenizer object ** returned by an earlier call to xCreate(). ** ** The second argument indicates the reason that FTS5 is requesting ** tokenization of the supplied text. This is always one of the following ** four values: ** ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into ** or removed from the FTS table. The tokenizer is being invoked to ** determine the set of tokens to add to (or delete from) the ** FTS index. ** ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed ** against the FTS index. The tokenizer is being called to tokenize ** a bareword or quoted string specified as part of the query. ** ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is ** followed by a "*" character, indicating that the last token ** returned by the tokenizer will be treated as a token prefix. ** ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to ** satisfy an fts5_api.xTokenize() request made by an auxiliary ** function. Or an fts5_api.xColumnSize() request made by the same ** on a columnsize=0 database. ** </ul> ** ** For each token in the input string, the supplied callback xToken() must ** be invoked. The first argument to it should be a copy of the pointer ** passed as the second argument to xTokenize(). The third and fourth ** arguments are a pointer to a buffer containing the token text, and the ** size of the token in bytes. The 4th and 5th arguments are the byte offsets ** of the first byte of and first byte immediately following the text from ** which the token is derived within the input. ** ** The second argument passed to the xToken() callback ("tflags") should ** normally be set to 0. The exception is if the tokenizer supports ** synonyms. In this case see the discussion below for details. ** ** FTS5 assumes the xToken() callback is invoked for each token in the ** order that they occur within the input text. ** ** If an xToken() callback returns any value other than SQLITE_OK, then ** the tokenization should be abandoned and the xTokenize() method should ** immediately return a copy of the xToken() return value. Or, if the ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally, ** if an error occurs with the xTokenize() implementation itself, it ** may abandon the tokenization and return any error code other than ** SQLITE_OK or SQLITE_DONE. ** ** SYNONYM SUPPORT ** ** Custom tokenizers may also support synonyms. Consider a case in which a ** user wishes to query for a phrase such as "first place". Using the ** built-in tokenizers, the FTS5 query 'first + place' will match instances ** of "first place" within the document set, but not alternative forms ** such as "1st place". In some applications, it would be better to match ** all instances of "first place" or "1st place" regardless of which form ** the user specified in the MATCH query text. ** ** There are several ways to approach this in FTS5: ** ** <ol><li> By mapping all synonyms to a single token. In this case, the ** In the above example, this means that the tokenizer returns the ** same token for inputs "first" and "1st". Say that token is in ** fact "first", so that when the user inserts the document "I won ** 1st place" entries are added to the index for tokens "i", "won", ** "first" and "place". If the user then queries for '1st + place', ** the tokenizer substitutes "first" for "1st" and the query works ** as expected. ** ** <li> By adding multiple synonyms for a single term to the FTS index. ** In this case, when tokenizing query text, the tokenizer may ** provide multiple synonyms for a single term within the document. ** FTS5 then queries the index for each synonym individually. For ** example, faced with the query: ** ** <codeblock> ** ... MATCH 'first place'</codeblock> ** ** the tokenizer offers both "1st" and "first" as synonyms for the ** first token in the MATCH query and FTS5 effectively runs a query ** similar to: ** ** <codeblock> ** ... MATCH '(first OR 1st) place'</codeblock> ** ** except that, for the purposes of auxiliary functions, the query ** still appears to contain just two phrases - "(first OR 1st)" ** being treated as a single phrase. ** ** <li> By adding multiple synonyms for a single term to the FTS index. ** Using this method, when tokenizing document text, the tokenizer ** provides multiple synonyms for each token. So that when a ** document such as "I won first place" is tokenized, entries are ** added to the FTS index for "i", "won", "first", "1st" and ** "place". ** ** This way, even if the tokenizer does not provide synonyms ** when tokenizing query text (it should not - to do would be ** inefficient), it doesn't matter if the user queries for ** 'first + place' or '1st + place', as there are entires in the ** FTS index corresponding to both forms of the first token. ** </ol> ** ** Whether it is parsing document or query text, any call to xToken that ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit ** is considered to supply a synonym for the previous token. For example, ** when parsing the document "I won first place", a tokenizer that supports ** synonyms would call xToken() 5 times, as follows: ** ** <codeblock> ** xToken(pCtx, 0, "i", 1, 0, 1); ** xToken(pCtx, 0, "won", 3, 2, 5); ** xToken(pCtx, 0, "first", 5, 6, 11); ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11); ** xToken(pCtx, 0, "place", 5, 12, 17); **</codeblock> ** ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time ** xToken() is called. Multiple synonyms may be specified for a single token ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. ** There is no limit to the number of synonyms that may be provided for a ** single token. ** ** In many cases, method (1) above is the best approach. It does not add ** extra data to the FTS index or require FTS5 to query for multiple terms, ** so it is efficient in terms of disk space and query speed. However, it ** does not support prefix queries very well. If, as suggested above, the ** token "first" is subsituted for "1st" by the tokenizer, then the query: ** ** <codeblock> ** ... MATCH '1s*'</codeblock> ** ** will not match documents that contain the token "1st" (as the tokenizer ** will probably not map "1s" to any prefix of "first"). ** ** For full prefix support, method (3) may be preferred. In this case, ** because the index contains entries for both "first" and "1st", prefix ** queries such as 'fi*' or '1s*' will match correctly. However, because ** extra entries are added to the FTS index, this method uses more space ** within the database. ** ** Method (2) offers a midpoint between (1) and (3). Using this method, ** a query such as '1s*' will match documents that contain the literal ** token "1st", but not "first" (assuming the tokenizer is not able to ** provide synonyms for prefixes). However, a non-prefix query like '1st' ** will match against "1st" and "first". This method does not require ** extra disk space, as no extra entries are added to the FTS index. ** On the other hand, it may require more CPU cycles to run MATCH queries, ** as separate queries of the FTS index are required for each synonym. ** ** When using methods (2) or (3), it is important that the tokenizer only ** provide synonyms when tokenizing document text (method (2)) or query ** text (method (3)), not both. Doing so will not cause any errors, but is ** inefficient. */ typedef struct Fts5Tokenizer Fts5Tokenizer; typedef struct fts5_tokenizer fts5_tokenizer; struct fts5_tokenizer { int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); void (*xDelete)(Fts5Tokenizer*); int (*xTokenize)(Fts5Tokenizer*, void *pCtx, int flags, /* Mask of FTS5_TOKENIZE_* flags */ const char *pText, int nText, int (*xToken)( void *pCtx, /* Copy of 2nd argument to xTokenize() */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Pointer to buffer containing token */ int nToken, /* Size of token in bytes */ int iStart, /* Byte offset of token within input text */ int iEnd /* Byte offset of end of token within input text */ ) ); }; /* Flags that may be passed as the third argument to xTokenize() */ #define FTS5_TOKENIZE_QUERY 0x0001 #define FTS5_TOKENIZE_PREFIX 0x0002 #define FTS5_TOKENIZE_DOCUMENT 0x0004 #define FTS5_TOKENIZE_AUX 0x0008 /* Flags that may be passed by the tokenizer implementation back to FTS5 ** as the third argument to the supplied xToken callback. */ #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */ /* ** END OF CUSTOM TOKENIZERS *************************************************************************/ /************************************************************************* ** FTS5 EXTENSION REGISTRATION API */ typedef struct fts5_api fts5_api; struct fts5_api { int iVersion; /* Currently always set to 2 */ /* Create a new tokenizer */ int (*xCreateTokenizer)( fts5_api *pApi, const char *zName, void *pContext, fts5_tokenizer *pTokenizer, void (*xDestroy)(void*) ); /* Find an existing tokenizer */ int (*xFindTokenizer)( fts5_api *pApi, const char *zName, void **ppContext, fts5_tokenizer *pTokenizer ); /* Create a new auxiliary function */ int (*xCreateFunction)( fts5_api *pApi, const char *zName, void *pContext, fts5_extension_function xFunction, void (*xDestroy)(void*) ); }; /* ** END OF REGISTRATION API *************************************************************************/ #if 0 } /* end of the 'extern "C"' block */ #endif #endif /* _FTS5_H */ /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ #ifndef _FTS5INT_H #define _FTS5INT_H /* #include "fts5.h" */ /* #include "sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 /* #include <string.h> */ /* #include <assert.h> */ #ifndef SQLITE_AMALGAMATION typedef unsigned char u8; typedef unsigned int u32; typedef unsigned short u16; typedef short i16; typedef sqlite3_int64 i64; typedef sqlite3_uint64 u64; #define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0]))) #define testcase(x) #define ALWAYS(x) 1 #define NEVER(x) 0 #define MIN(x,y) (((x) < (y)) ? (x) : (y)) #define MAX(x,y) (((x) > (y)) ? (x) : (y)) /* ** Constants for the largest and smallest possible 64-bit signed integers. */ # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) #endif /* Truncate very long tokens to this many bytes. Hard limit is ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset ** field that occurs at the start of each leaf page (see fts5_index.c). */ #define FTS5_MAX_TOKEN_SIZE 32768 /* ** Maximum number of prefix indexes on single FTS5 table. This must be ** less than 32. If it is set to anything large than that, an #error ** directive in fts5_index.c will cause the build to fail. */ #define FTS5_MAX_PREFIX_INDEXES 31 #define FTS5_DEFAULT_NEARDIST 10 #define FTS5_DEFAULT_RANK "bm25" /* Name of rank and rowid columns */ #define FTS5_RANK_NAME "rank" #define FTS5_ROWID_NAME "rowid" #ifdef SQLITE_DEBUG # define FTS5_CORRUPT sqlite3Fts5Corrupt() static int sqlite3Fts5Corrupt(void); #else # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB #endif /* ** The assert_nc() macro is similar to the assert() macro, except that it ** is used for assert() conditions that are true only if it can be ** guranteed that the database is not corrupt. */ #ifdef SQLITE_DEBUG SQLITE_API extern int sqlite3_fts5_may_be_corrupt; # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x)) #else # define assert_nc(x) assert(x) #endif /* Mark a function parameter as unused, to suppress nuisance compiler ** warnings. */ #ifndef UNUSED_PARAM # define UNUSED_PARAM(X) (void)(X) #endif #ifndef UNUSED_PARAM2 # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y) #endif typedef struct Fts5Global Fts5Global; typedef struct Fts5Colset Fts5Colset; /* If a NEAR() clump or phrase may only match a specific set of columns, ** then an object of the following type is used to record the set of columns. ** Each entry in the aiCol[] array is a column that may be matched. ** ** This object is used by fts5_expr.c and fts5_index.c. */ struct Fts5Colset { int nCol; int aiCol[1]; }; /************************************************************************** ** Interface to code in fts5_config.c. fts5_config.c contains contains code ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement. */ typedef struct Fts5Config Fts5Config; /* ** An instance of the following structure encodes all information that can ** be gleaned from the CREATE VIRTUAL TABLE statement. ** ** And all information loaded from the %_config table. ** ** nAutomerge: ** The minimum number of segments that an auto-merge operation should ** attempt to merge together. A value of 1 sets the object to use the ** compile time default. Zero disables auto-merge altogether. ** ** zContent: ** ** zContentRowid: ** The value of the content_rowid= option, if one was specified. Or ** the string "rowid" otherwise. This text is not quoted - if it is ** used as part of an SQL statement it needs to be quoted appropriately. ** ** zContentExprlist: ** ** pzErrmsg: ** This exists in order to allow the fts5_index.c module to return a ** decent error message if it encounters a file-format version it does ** not understand. ** ** bColumnsize: ** True if the %_docsize table is created. ** ** bPrefixIndex: ** This is only used for debugging. If set to false, any prefix indexes ** are ignored. This value is configured using: ** ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex); ** */ struct Fts5Config { sqlite3 *db; /* Database handle */ char *zDb; /* Database holding FTS index (e.g. "main") */ char *zName; /* Name of FTS index */ int nCol; /* Number of columns */ char **azCol; /* Column names */ u8 *abUnindexed; /* True for unindexed columns */ int nPrefix; /* Number of prefix indexes */ int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */ int eContent; /* An FTS5_CONTENT value */ char *zContent; /* content table */ char *zContentRowid; /* "content_rowid=" option value */ int bColumnsize; /* "columnsize=" option value (dflt==1) */ int eDetail; /* FTS5_DETAIL_XXX value */ char *zContentExprlist; Fts5Tokenizer *pTok; fts5_tokenizer *pTokApi; /* Values loaded from the %_config table */ int iCookie; /* Incremented when %_config is modified */ int pgsz; /* Approximate page size used in %_data */ int nAutomerge; /* 'automerge' setting */ int nCrisisMerge; /* Maximum allowed segments per level */ int nUsermerge; /* 'usermerge' setting */ int nHashSize; /* Bytes of memory for in-memory hash */ char *zRank; /* Name of rank function */ char *zRankArgs; /* Arguments to rank function */ /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */ char **pzErrmsg; #ifdef SQLITE_DEBUG int bPrefixIndex; /* True to use prefix-indexes */ #endif }; /* Current expected value of %_config table 'version' field */ #define FTS5_CURRENT_VERSION 4 #define FTS5_CONTENT_NORMAL 0 #define FTS5_CONTENT_NONE 1 #define FTS5_CONTENT_EXTERNAL 2 #define FTS5_DETAIL_FULL 0 #define FTS5_DETAIL_NONE 1 #define FTS5_DETAIL_COLUMNS 2 static int sqlite3Fts5ConfigParse( Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char** ); static void sqlite3Fts5ConfigFree(Fts5Config*); static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig); static int sqlite3Fts5Tokenize( Fts5Config *pConfig, /* FTS5 Configuration object */ int flags, /* FTS5_TOKENIZE_* flags */ const char *pText, int nText, /* Text to tokenize */ void *pCtx, /* Context passed to xToken() */ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ); static void sqlite3Fts5Dequote(char *z); /* Load the contents of the %_config table */ static int sqlite3Fts5ConfigLoad(Fts5Config*, int); /* Set the value of a single config attribute */ static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*); static int sqlite3Fts5ConfigParseRank(const char*, char**, char**); /* ** End of interface to code in fts5_config.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_buffer.c. */ /* ** Buffer object for the incremental building of string data. */ typedef struct Fts5Buffer Fts5Buffer; struct Fts5Buffer { u8 *p; int n; int nSpace; }; static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32); static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64); static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*); static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*); static void sqlite3Fts5BufferFree(Fts5Buffer*); static void sqlite3Fts5BufferZero(Fts5Buffer*); static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*); static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...); static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...); #define fts5BufferZero(x) sqlite3Fts5BufferZero(x) #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c) #define fts5BufferFree(a) sqlite3Fts5BufferFree(a) #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d) #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d) #define fts5BufferGrow(pRc,pBuf,nn) ( \ (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \ sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \ ) /* Write and decode big-endian 32-bit integer values */ static void sqlite3Fts5Put32(u8*, int); static int sqlite3Fts5Get32(const u8*); #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32) #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF) typedef struct Fts5PoslistReader Fts5PoslistReader; struct Fts5PoslistReader { /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */ const u8 *a; /* Position list to iterate through */ int n; /* Size of buffer at a[] in bytes */ int i; /* Current offset in a[] */ u8 bFlag; /* For client use (any custom purpose) */ /* Output variables */ u8 bEof; /* Set to true at EOF */ i64 iPos; /* (iCol<<32) + iPos */ }; static int sqlite3Fts5PoslistReaderInit( const u8 *a, int n, /* Poslist buffer to iterate through */ Fts5PoslistReader *pIter /* Iterator object to initialize */ ); static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*); typedef struct Fts5PoslistWriter Fts5PoslistWriter; struct Fts5PoslistWriter { i64 iPrev; }; static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64); static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64); static int sqlite3Fts5PoslistNext64( const u8 *a, int n, /* Buffer containing poslist */ int *pi, /* IN/OUT: Offset within a[] */ i64 *piOff /* IN/OUT: Current offset */ ); /* Malloc utility */ static void *sqlite3Fts5MallocZero(int *pRc, int nByte); static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn); /* Character set tests (like isspace(), isalpha() etc.) */ static int sqlite3Fts5IsBareword(char t); /* Bucket of terms object used by the integrity-check in offsets=0 mode. */ typedef struct Fts5Termset Fts5Termset; static int sqlite3Fts5TermsetNew(Fts5Termset**); static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent); static void sqlite3Fts5TermsetFree(Fts5Termset*); /* ** End of interface to code in fts5_buffer.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_index.c. fts5_index.c contains contains code ** to access the data stored in the %_data table. */ typedef struct Fts5Index Fts5Index; typedef struct Fts5IndexIter Fts5IndexIter; struct Fts5IndexIter { i64 iRowid; const u8 *pData; int nData; u8 bEof; }; #define sqlite3Fts5IterEof(x) ((x)->bEof) /* ** Values used as part of the flags argument passed to IndexQuery(). */ #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */ #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */ #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */ #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */ /* The following are used internally by the fts5_index.c module. They are ** defined here only to make it easier to avoid clashes with the flags ** above. */ #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010 #define FTS5INDEX_QUERY_NOOUTPUT 0x0020 /* ** Create/destroy an Fts5Index object. */ static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**); static int sqlite3Fts5IndexClose(Fts5Index *p); /* ** Return a simple checksum value based on the arguments. */ static u64 sqlite3Fts5IndexEntryCksum( i64 iRowid, int iCol, int iPos, int iIdx, const char *pTerm, int nTerm ); /* ** Argument p points to a buffer containing utf-8 text that is n bytes in ** size. Return the number of bytes in the nChar character prefix of the ** buffer, or 0 if there are less than nChar characters in total. */ static int sqlite3Fts5IndexCharlenToBytelen( const char *p, int nByte, int nChar ); /* ** Open a new iterator to iterate though all rowids that match the ** specified token or token prefix. */ static int sqlite3Fts5IndexQuery( Fts5Index *p, /* FTS index to query */ const char *pToken, int nToken, /* Token (or prefix) to query for */ int flags, /* Mask of FTS5INDEX_QUERY_X flags */ Fts5Colset *pColset, /* Match these columns only */ Fts5IndexIter **ppIter /* OUT: New iterator object */ ); /* ** The various operations on open token or token prefix iterators opened ** using sqlite3Fts5IndexQuery(). */ static int sqlite3Fts5IterNext(Fts5IndexIter*); static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch); /* ** Close an iterator opened by sqlite3Fts5IndexQuery(). */ static void sqlite3Fts5IterClose(Fts5IndexIter*); /* ** This interface is used by the fts5vocab module. */ static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*); static int sqlite3Fts5IterNextScan(Fts5IndexIter*); /* ** Insert or remove data to or from the index. Each time a document is ** added to or removed from the index, this function is called one or more ** times. ** ** For an insert, it must be called once for each token in the new document. ** If the operation is a delete, it must be called (at least) once for each ** unique token in the document with an iCol value less than zero. The iPos ** argument is ignored for a delete. */ static int sqlite3Fts5IndexWrite( Fts5Index *p, /* Index to write to */ int iCol, /* Column token appears in (-ve -> delete) */ int iPos, /* Position of token within column */ const char *pToken, int nToken /* Token to add or remove to or from index */ ); /* ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to ** document iDocid. */ static int sqlite3Fts5IndexBeginWrite( Fts5Index *p, /* Index to write to */ int bDelete, /* True if current operation is a delete */ i64 iDocid /* Docid to add or remove data from */ ); /* ** Flush any data stored in the in-memory hash tables to the database. ** If the bCommit flag is true, also close any open blob handles. */ static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit); /* ** Discard any data stored in the in-memory hash tables. Do not write it ** to the database. Additionally, assume that the contents of the %_data ** table may have changed on disk. So any in-memory caches of %_data ** records must be invalidated. */ static int sqlite3Fts5IndexRollback(Fts5Index *p); /* ** Get or set the "averages" values. */ static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize); static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int); /* ** Functions called by the storage module as part of integrity-check. */ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum); /* ** Called during virtual module initialization to register UDF ** fts5_decode() with SQLite */ static int sqlite3Fts5IndexInit(sqlite3*); static int sqlite3Fts5IndexSetCookie(Fts5Index*, int); /* ** Return the total number of entries read from the %_data table by ** this connection since it was created. */ static int sqlite3Fts5IndexReads(Fts5Index *p); static int sqlite3Fts5IndexReinit(Fts5Index *p); static int sqlite3Fts5IndexOptimize(Fts5Index *p); static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge); static int sqlite3Fts5IndexReset(Fts5Index *p); static int sqlite3Fts5IndexLoadConfig(Fts5Index *p); /* ** End of interface to code in fts5_index.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_varint.c. */ static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v); static int sqlite3Fts5GetVarintLen(u32 iVal); static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*); static int sqlite3Fts5PutVarint(unsigned char *p, u64 v); #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b) #define fts5GetVarint sqlite3Fts5GetVarint #define fts5FastGetVarint32(a, iOff, nVal) { \ nVal = (a)[iOff++]; \ if( nVal & 0x80 ){ \ iOff--; \ iOff += fts5GetVarint32(&(a)[iOff], nVal); \ } \ } /* ** End of interface to code in fts5_varint.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5.c. */ static int sqlite3Fts5GetTokenizer( Fts5Global*, const char **azArg, int nArg, Fts5Tokenizer**, fts5_tokenizer**, char **pzErr ); static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **); /* ** End of interface to code in fts5.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_hash.c. */ typedef struct Fts5Hash Fts5Hash; /* ** Create a hash table, free a hash table. */ static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize); static void sqlite3Fts5HashFree(Fts5Hash*); static int sqlite3Fts5HashWrite( Fts5Hash*, i64 iRowid, /* Rowid for this entry */ int iCol, /* Column token appears in (-ve -> delete) */ int iPos, /* Position of token within column */ char bByte, const char *pToken, int nToken /* Token to add or remove to or from index */ ); /* ** Empty (but do not delete) a hash table. */ static void sqlite3Fts5HashClear(Fts5Hash*); static int sqlite3Fts5HashQuery( Fts5Hash*, /* Hash table to query */ const char *pTerm, int nTerm, /* Query term */ const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */ int *pnDoclist /* OUT: Size of doclist in bytes */ ); static int sqlite3Fts5HashScanInit( Fts5Hash*, /* Hash table to query */ const char *pTerm, int nTerm /* Query prefix */ ); static void sqlite3Fts5HashScanNext(Fts5Hash*); static int sqlite3Fts5HashScanEof(Fts5Hash*); static void sqlite3Fts5HashScanEntry(Fts5Hash *, const char **pzTerm, /* OUT: term (nul-terminated) */ const u8 **ppDoclist, /* OUT: pointer to doclist */ int *pnDoclist /* OUT: size of doclist in bytes */ ); /* ** End of interface to code in fts5_hash.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_storage.c. fts5_storage.c contains contains ** code to access the data stored in the %_content and %_docsize tables. */ #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */ #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */ #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */ typedef struct Fts5Storage Fts5Storage; static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**); static int sqlite3Fts5StorageClose(Fts5Storage *p); static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName); static int sqlite3Fts5DropAll(Fts5Config*); static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **); static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**); static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*); static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64); static int sqlite3Fts5StorageIntegrity(Fts5Storage *p); static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**); static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*); static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol); static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg); static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow); static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit); static int sqlite3Fts5StorageRollback(Fts5Storage *p); static int sqlite3Fts5StorageConfigValue( Fts5Storage *p, const char*, sqlite3_value*, int ); static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p); static int sqlite3Fts5StorageRebuild(Fts5Storage *p); static int sqlite3Fts5StorageOptimize(Fts5Storage *p); static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge); static int sqlite3Fts5StorageReset(Fts5Storage *p); /* ** End of interface to code in fts5_storage.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_expr.c. */ typedef struct Fts5Expr Fts5Expr; typedef struct Fts5ExprNode Fts5ExprNode; typedef struct Fts5Parse Fts5Parse; typedef struct Fts5Token Fts5Token; typedef struct Fts5ExprPhrase Fts5ExprPhrase; typedef struct Fts5ExprNearset Fts5ExprNearset; struct Fts5Token { const char *p; /* Token text (not NULL terminated) */ int n; /* Size of buffer p in bytes */ }; /* Parse a MATCH expression. */ static int sqlite3Fts5ExprNew( Fts5Config *pConfig, const char *zExpr, Fts5Expr **ppNew, char **pzErr ); /* ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc); ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr); ** rc = sqlite3Fts5ExprNext(pExpr) ** ){ ** // The document with rowid iRowid matches the expression! ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr); ** } */ static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc); static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax); static int sqlite3Fts5ExprEof(Fts5Expr*); static i64 sqlite3Fts5ExprRowid(Fts5Expr*); static void sqlite3Fts5ExprFree(Fts5Expr*); /* Called during startup to register a UDF with SQLite */ static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*); static int sqlite3Fts5ExprPhraseCount(Fts5Expr*); static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase); static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **); typedef struct Fts5PoslistPopulator Fts5PoslistPopulator; static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int); static int sqlite3Fts5ExprPopulatePoslists( Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int ); static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64); static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**); static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *); /******************************************* ** The fts5_expr.c API above this point is used by the other hand-written ** C code in this module. The interfaces below this point are called by ** the parser code in fts5parse.y. */ static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...); static Fts5ExprNode *sqlite3Fts5ParseNode( Fts5Parse *pParse, int eType, Fts5ExprNode *pLeft, Fts5ExprNode *pRight, Fts5ExprNearset *pNear ); static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( Fts5Parse *pParse, Fts5ExprNode *pLeft, Fts5ExprNode *pRight ); static Fts5ExprPhrase *sqlite3Fts5ParseTerm( Fts5Parse *pParse, Fts5ExprPhrase *pPhrase, Fts5Token *pToken, int bPrefix ); static Fts5ExprNearset *sqlite3Fts5ParseNearset( Fts5Parse*, Fts5ExprNearset*, Fts5ExprPhrase* ); static Fts5Colset *sqlite3Fts5ParseColset( Fts5Parse*, Fts5Colset*, Fts5Token * ); static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*); static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*); static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*); static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*); static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*); static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*); static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p); static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*); /* ** End of interface to code in fts5_expr.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_aux.c. */ static int sqlite3Fts5AuxInit(fts5_api*); /* ** End of interface to code in fts5_aux.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_tokenizer.c. */ static int sqlite3Fts5TokenizerInit(fts5_api*); /* ** End of interface to code in fts5_tokenizer.c. **************************************************************************/ /************************************************************************** ** Interface to code in fts5_vocab.c. */ static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*); /* ** End of interface to code in fts5_vocab.c. **************************************************************************/ /************************************************************************** ** Interface to automatically generated code in fts5_unicode2.c. */ static int sqlite3Fts5UnicodeIsalnum(int c); static int sqlite3Fts5UnicodeIsdiacritic(int c); static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); /* ** End of interface to code in fts5_unicode2.c. **************************************************************************/ #endif #define FTS5_OR 1 #define FTS5_AND 2 #define FTS5_NOT 3 #define FTS5_TERM 4 #define FTS5_COLON 5 #define FTS5_LP 6 #define FTS5_RP 7 #define FTS5_MINUS 8 #define FTS5_LCP 9 #define FTS5_RCP 10 #define FTS5_STRING 11 #define FTS5_COMMA 12 #define FTS5_PLUS 13 #define FTS5_STAR 14 /* ** 2000-05-29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Driver template for the LEMON parser generator. ** ** The "lemon" program processes an LALR(1) input grammar file, then uses ** this template to construct a parser. The "lemon" program inserts text ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the ** interstitial "-" characters) contained in this template is changed into ** the value of the %name directive from the grammar. Otherwise, the content ** of this template is copied straight through into the generate parser ** source file. ** ** The following is the concatenation of all %include directives from the ** input grammar file: */ /* #include <stdio.h> */ /************ Begin %include sections from the grammar ************************/ /* #include "fts5Int.h" */ /* #include "fts5parse.h" */ /* ** Disable all error recovery processing in the parser push-down ** automaton. */ #define fts5YYNOERRORRECOVERY 1 /* ** Make fts5yytestcase() the same as testcase() */ #define fts5yytestcase(X) testcase(X) /* ** Indicate that sqlite3ParserFree() will never be called with a null ** pointer. */ #define fts5YYPARSEFREENOTNULL 1 /* ** Alternative datatype for the argument to the malloc() routine passed ** into sqlite3ParserAlloc(). The default is size_t. */ #define fts5YYMALLOCARGTYPE u64 /**************** End of %include directives **********************************/ /* These constants specify the various numeric values for terminal symbols ** in a format understandable to "makeheaders". This section is blank unless ** "lemon" is run with the "-m" command-line option. ***************** Begin makeheaders token definitions *************************/ /**************** End makeheaders token definitions ***************************/ /* The next sections is a series of control #defines. ** various aspects of the generated parser. ** fts5YYCODETYPE is the data type used to store the integer codes ** that represent terminal and non-terminal symbols. ** "unsigned char" is used if there are fewer than ** 256 symbols. Larger types otherwise. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for ** any terminal or nonterminal symbol. ** fts5YYFALLBACK If defined, this indicates that one or more tokens ** (also known as: "terminal symbols") have fall-back ** values which should be used if the original symbol ** would not parse. This permits keywords to sometimes ** be used as identifiers, for example. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers ** that indicate what to do in response to the next ** token. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal ** symbols. Background: A "minor type" is a semantic ** value associated with a terminal or non-terminal ** symbols. For example, for an "ID" terminal symbol, ** the minor type might be the name of the identifier. ** Each non-terminal can have a different minor type. ** Terminal symbols all have the same minor type, though. ** This macros defines the minor type for terminal ** symbols. ** fts5YYMINORTYPE is the data type used for all minor types. ** This is typically a union of many types, one of ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union ** for terminal symbols is called "fts5yy0". ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If ** zero the stack is dynamically sized using realloc() ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser ** fts5YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. ** fts5YYNSTATE the combined number of states. ** fts5YYNRULE the number of rules in the grammar ** fts5YY_MAX_SHIFT Maximum value for shift actions ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions ** fts5YY_MIN_REDUCE Maximum value for reduce actions ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op */ #ifndef INTERFACE # define INTERFACE 1 #endif /************* Begin control #defines *****************************************/ #define fts5YYCODETYPE unsigned char #define fts5YYNOCODE 28 #define fts5YYACTIONTYPE unsigned char #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token typedef union { int fts5yyinit; sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0; int fts5yy4; Fts5Colset* fts5yy11; Fts5ExprNode* fts5yy24; Fts5ExprNearset* fts5yy46; Fts5ExprPhrase* fts5yy53; } fts5YYMINORTYPE; #ifndef fts5YYSTACKDEPTH #define fts5YYSTACKDEPTH 100 #endif #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse; #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse #define fts5YYNSTATE 29 #define fts5YYNRULE 26 #define fts5YY_MAX_SHIFT 28 #define fts5YY_MIN_SHIFTREDUCE 45 #define fts5YY_MAX_SHIFTREDUCE 70 #define fts5YY_MIN_REDUCE 71 #define fts5YY_MAX_REDUCE 96 #define fts5YY_ERROR_ACTION 97 #define fts5YY_ACCEPT_ACTION 98 #define fts5YY_NO_ACTION 99 /************* End control #defines *******************************************/ /* Define the fts5yytestcase() macro to be a no-op if is not already defined ** otherwise. ** ** Applications can choose to define fts5yytestcase() in the %include section ** to a macro that can assist in verifying code coverage. For production ** code the fts5yytestcase() macro should be turned off. But it is useful ** for testing. */ #ifndef fts5yytestcase # define fts5yytestcase(X) #endif /* Next are the tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE. ** ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE ** and fts5YY_MAX_REDUCE ** ** N == fts5YY_ERROR_ACTION A syntax error has occurred. ** ** N == fts5YY_ACCEPT_ACTION The parser accepts its input. ** ** N == fts5YY_NO_ACTION No such action. Denotes unused ** slots in the fts5yy_action[] table. ** ** The action table is constructed as a single large table named fts5yy_action[]. ** Given state S and lookahead X, the action is computed as either: ** ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ] ** (B) N = fts5yy_default[S] ** ** The (A) formula is preferred. The B formula is used instead if: ** (1) The fts5yy_shift_ofst[S]+X value is out of range, or ** (2) fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or ** (3) fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT. ** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that ** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X. ** Hence only tests (1) and (2) need to be evaluated.) ** ** The formulas above are for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of ** fts5YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** fts5yy_action[] A single table containing all actions. ** fts5yy_lookahead[] A table containing the lookahead for each entry in ** fts5yy_action. Used to detect hash collisions. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for ** shifting terminals. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for ** shifting non-terminals after a reduce. ** fts5yy_default[] Default action for each state. ** *********** Begin parsing tables **********************************************/ #define fts5YY_ACTTAB_COUNT (85) static const fts5YYACTIONTYPE fts5yy_action[] = { /* 0 */ 98, 16, 51, 5, 53, 27, 83, 7, 26, 15, /* 10 */ 51, 5, 53, 27, 13, 69, 26, 48, 51, 5, /* 20 */ 53, 27, 19, 11, 26, 9, 20, 51, 5, 53, /* 30 */ 27, 13, 22, 26, 28, 51, 5, 53, 27, 68, /* 40 */ 1, 26, 19, 11, 17, 9, 52, 10, 53, 27, /* 50 */ 23, 24, 26, 54, 3, 4, 2, 26, 6, 21, /* 60 */ 49, 71, 3, 4, 2, 7, 56, 59, 55, 59, /* 70 */ 4, 2, 12, 69, 58, 60, 18, 67, 62, 69, /* 80 */ 25, 66, 8, 14, 2, }; static const fts5YYCODETYPE fts5yy_lookahead[] = { /* 0 */ 16, 17, 18, 19, 20, 21, 5, 6, 24, 17, /* 10 */ 18, 19, 20, 21, 11, 14, 24, 17, 18, 19, /* 20 */ 20, 21, 8, 9, 24, 11, 17, 18, 19, 20, /* 30 */ 21, 11, 12, 24, 17, 18, 19, 20, 21, 26, /* 40 */ 6, 24, 8, 9, 22, 11, 18, 11, 20, 21, /* 50 */ 24, 25, 24, 20, 1, 2, 3, 24, 23, 24, /* 60 */ 7, 0, 1, 2, 3, 6, 10, 11, 10, 11, /* 70 */ 2, 3, 9, 14, 11, 11, 22, 26, 7, 14, /* 80 */ 13, 11, 5, 11, 3, }; #define fts5YY_SHIFT_USE_DFLT (85) #define fts5YY_SHIFT_COUNT (28) #define fts5YY_SHIFT_MIN (0) #define fts5YY_SHIFT_MAX (81) static const unsigned char fts5yy_shift_ofst[] = { /* 0 */ 34, 34, 34, 34, 34, 14, 20, 3, 36, 1, /* 10 */ 59, 64, 64, 65, 65, 53, 61, 56, 58, 63, /* 20 */ 68, 67, 70, 67, 71, 72, 67, 77, 81, }; #define fts5YY_REDUCE_USE_DFLT (-17) #define fts5YY_REDUCE_COUNT (14) #define fts5YY_REDUCE_MIN (-16) #define fts5YY_REDUCE_MAX (54) static const signed char fts5yy_reduce_ofst[] = { /* 0 */ -16, -8, 0, 9, 17, 28, 26, 35, 33, 13, /* 10 */ 13, 22, 54, 13, 51, }; static const fts5YYACTIONTYPE fts5yy_default[] = { /* 0 */ 97, 97, 97, 97, 97, 76, 91, 97, 97, 96, /* 10 */ 96, 97, 97, 96, 96, 97, 97, 97, 97, 97, /* 20 */ 73, 89, 97, 90, 97, 97, 87, 97, 72, }; /********** End of lemon-generated parsing tables *****************************/ /* The next table maps tokens (terminal symbols) into fallback tokens. ** If a construct like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammar, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. ** ** This feature can be used, for example, to cause some keywords in a language ** to revert to identifiers if they keyword does not apply in the context where ** it appears. */ #ifdef fts5YYFALLBACK static const fts5YYCODETYPE fts5yyFallback[] = { }; #endif /* fts5YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. ** ** After the "shift" half of a SHIFTREDUCE action, the stateno field ** actually contains the reduce action for the second half of the ** SHIFTREDUCE. */ struct fts5yyStackEntry { fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */ fts5YYCODETYPE major; /* The major token value. This is the code ** number for the token at this stack level */ fts5YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct fts5yyStackEntry fts5yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct fts5yyParser { fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */ #ifdef fts5YYTRACKMAXSTACKDEPTH int fts5yyhwm; /* High-water mark of the stack */ #endif #ifndef fts5YYNOERRORRECOVERY int fts5yyerrcnt; /* Shifts left before out of the error */ #endif sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */ #if fts5YYSTACKDEPTH<=0 int fts5yystksz; /* Current side of the stack */ fts5yyStackEntry *fts5yystack; /* The parser's stack */ fts5yyStackEntry fts5yystk0; /* First stack entry */ #else fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */ #endif }; typedef struct fts5yyParser fts5yyParser; #ifndef NDEBUG /* #include <stdio.h> */ static FILE *fts5yyTraceFILE = 0; static char *fts5yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: ** <ul> ** <li> A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. ** <li> A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. ** </ul> ** ** Outputs: ** None. */ static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){ fts5yyTraceFILE = TraceFILE; fts5yyTracePrompt = zTracePrompt; if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0; else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *const fts5yyTokenName[] = { "$", "OR", "AND", "NOT", "TERM", "COLON", "LP", "RP", "MINUS", "LCP", "RCP", "STRING", "COMMA", "PLUS", "STAR", "error", "input", "expr", "cnearset", "exprlist", "nearset", "colset", "colsetlist", "nearphrases", "phrase", "neardist_opt", "star_opt", }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *const fts5yyRuleName[] = { /* 0 */ "input ::= expr", /* 1 */ "expr ::= expr AND expr", /* 2 */ "expr ::= expr OR expr", /* 3 */ "expr ::= expr NOT expr", /* 4 */ "expr ::= LP expr RP", /* 5 */ "expr ::= exprlist", /* 6 */ "exprlist ::= cnearset", /* 7 */ "exprlist ::= exprlist cnearset", /* 8 */ "cnearset ::= nearset", /* 9 */ "cnearset ::= colset COLON nearset", /* 10 */ "colset ::= MINUS LCP colsetlist RCP", /* 11 */ "colset ::= LCP colsetlist RCP", /* 12 */ "colset ::= STRING", /* 13 */ "colset ::= MINUS STRING", /* 14 */ "colsetlist ::= colsetlist STRING", /* 15 */ "colsetlist ::= STRING", /* 16 */ "nearset ::= phrase", /* 17 */ "nearset ::= STRING LP nearphrases neardist_opt RP", /* 18 */ "nearphrases ::= phrase", /* 19 */ "nearphrases ::= nearphrases phrase", /* 20 */ "neardist_opt ::=", /* 21 */ "neardist_opt ::= COMMA STRING", /* 22 */ "phrase ::= phrase PLUS STRING star_opt", /* 23 */ "phrase ::= STRING star_opt", /* 24 */ "star_opt ::= STAR", /* 25 */ "star_opt ::=", }; #endif /* NDEBUG */ #if fts5YYSTACKDEPTH<=0 /* ** Try to increase the size of the parser stack. Return the number ** of errors. Return 0 on success. */ static int fts5yyGrowStack(fts5yyParser *p){ int newSize; int idx; fts5yyStackEntry *pNew; newSize = p->fts5yystksz*2 + 100; idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0; if( p->fts5yystack==&p->fts5yystk0 ){ pNew = malloc(newSize*sizeof(pNew[0])); if( pNew ) pNew[0] = p->fts5yystk0; }else{ pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0])); } if( pNew ){ p->fts5yystack = pNew; p->fts5yytos = &p->fts5yystack[idx]; #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n", fts5yyTracePrompt, p->fts5yystksz, newSize); } #endif p->fts5yystksz = newSize; } return pNew==0; } #endif /* Datatype of the argument to the memory allocated passed as the ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by ** putting an appropriate #define in the %include section of the input ** grammar. */ #ifndef fts5YYMALLOCARGTYPE # define fts5YYMALLOCARGTYPE size_t #endif /* Initialize a new parser that has already been allocated. */ static void sqlite3Fts5ParserInit(void *fts5yypParser){ fts5yyParser *pParser = (fts5yyParser*)fts5yypParser; #ifdef fts5YYTRACKMAXSTACKDEPTH pParser->fts5yyhwm = 0; #endif #if fts5YYSTACKDEPTH<=0 pParser->fts5yytos = NULL; pParser->fts5yystack = NULL; pParser->fts5yystksz = 0; if( fts5yyGrowStack(pParser) ){ pParser->fts5yystack = &pParser->fts5yystk0; pParser->fts5yystksz = 1; } #endif #ifndef fts5YYNOERRORRECOVERY pParser->fts5yyerrcnt = -1; #endif pParser->fts5yytos = pParser->fts5yystack; pParser->fts5yystack[0].stateno = 0; pParser->fts5yystack[0].major = 0; } #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree. */ static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){ fts5yyParser *pParser; pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) ); if( pParser ) sqlite3Fts5ParserInit(pParser); return pParser; } #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */ /* The following function deletes the "minor type" or semantic value ** associated with a symbol. The symbol can be either a terminal ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is ** a pointer to the value to be deleted. The code used to do the ** deletions is derived from the %destructor and/or %token_destructor ** directives of the input grammar. */ static void fts5yy_destructor( fts5yyParser *fts5yypParser, /* The parser */ fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */ fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */ ){ sqlite3Fts5ParserARG_FETCH; switch( fts5yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are *not* used ** inside the C code. */ /********* Begin destructor definitions ***************************************/ case 16: /* input */ { (void)pParse; } break; case 17: /* expr */ case 18: /* cnearset */ case 19: /* exprlist */ { sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24)); } break; case 20: /* nearset */ case 23: /* nearphrases */ { sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46)); } break; case 21: /* colset */ case 22: /* colsetlist */ { sqlite3_free((fts5yypminor->fts5yy11)); } break; case 24: /* phrase */ { sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53)); } break; /********* End destructor definitions *****************************************/ default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. */ static void fts5yy_pop_parser_stack(fts5yyParser *pParser){ fts5yyStackEntry *fts5yytos; assert( pParser->fts5yytos!=0 ); assert( pParser->fts5yytos > pParser->fts5yystack ); fts5yytos = pParser->fts5yytos--; #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sPopping %s\n", fts5yyTracePrompt, fts5yyTokenName[fts5yytos->major]); } #endif fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor); } /* ** Clear all secondary memory allocations from the parser */ static void sqlite3Fts5ParserFinalize(void *p){ fts5yyParser *pParser = (fts5yyParser*)p; while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser); #if fts5YYSTACKDEPTH<=0 if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack); #endif } #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK /* ** Deallocate and destroy a parser. Destructors are called for ** all stack elements before shutting the parser down. ** ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it ** is defined in a %include section of the input grammar) then it is ** assumed that the input pointer is never NULL. */ static void sqlite3Fts5ParserFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ #ifndef fts5YYPARSEFREENEVERNULL if( p==0 ) return; #endif sqlite3Fts5ParserFinalize(p); (*freeProc)(p); } #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */ /* ** Return the peak depth of the stack for a parser. */ #ifdef fts5YYTRACKMAXSTACKDEPTH static int sqlite3Fts5ParserStackPeak(void *p){ fts5yyParser *pParser = (fts5yyParser*)p; return pParser->fts5yyhwm; } #endif /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. */ static unsigned int fts5yy_find_shift_action( fts5yyParser *pParser, /* The parser */ fts5YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->fts5yytos->stateno; if( stateno>=fts5YY_MIN_REDUCE ) return stateno; assert( stateno <= fts5YY_SHIFT_COUNT ); do{ i = fts5yy_shift_ofst[stateno]; assert( iLookAhead!=fts5YYNOCODE ); i += iLookAhead; if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){ #ifdef fts5YYFALLBACK fts5YYCODETYPE iFallback; /* Fallback token */ if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0]) && (iFallback = fts5yyFallback[iLookAhead])!=0 ){ #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n", fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]); } #endif assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */ iLookAhead = iFallback; continue; } #endif #ifdef fts5YYWILDCARD { int j = i - iLookAhead + fts5YYWILDCARD; if( #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0 j>=0 && #endif #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT j<fts5YY_ACTTAB_COUNT && #endif fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0 ){ #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n", fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[fts5YYWILDCARD]); } #endif /* NDEBUG */ return fts5yy_action[j]; } } #endif /* fts5YYWILDCARD */ return fts5yy_default[stateno]; }else{ return fts5yy_action[i]; } }while(1); } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. */ static int fts5yy_find_reduce_action( int stateno, /* Current state number */ fts5YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; #ifdef fts5YYERRORSYMBOL if( stateno>fts5YY_REDUCE_COUNT ){ return fts5yy_default[stateno]; } #else assert( stateno<=fts5YY_REDUCE_COUNT ); #endif i = fts5yy_reduce_ofst[stateno]; assert( i!=fts5YY_REDUCE_USE_DFLT ); assert( iLookAhead!=fts5YYNOCODE ); i += iLookAhead; #ifdef fts5YYERRORSYMBOL if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){ return fts5yy_default[stateno]; } #else assert( i>=0 && i<fts5YY_ACTTAB_COUNT ); assert( fts5yy_lookahead[i]==iLookAhead ); #endif return fts5yy_action[i]; } /* ** The following routine is called if the stack overflows. */ static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){ sqlite3Fts5ParserARG_FETCH; #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt); } #endif while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ /******** Begin %stack_overflow code ******************************************/ sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow"); /******** End %stack_overflow code ********************************************/ sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ } /* ** Print tracing information for a SHIFT action */ #ifndef NDEBUG static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){ if( fts5yyTraceFILE ){ if( fts5yyNewState<fts5YYNSTATE ){ fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n", fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major], fts5yyNewState); }else{ fprintf(fts5yyTraceFILE,"%sShift '%s'\n", fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]); } } } #else # define fts5yyTraceShift(X,Y) #endif /* ** Perform a shift action. */ static void fts5yy_shift( fts5yyParser *fts5yypParser, /* The parser to be shifted */ int fts5yyNewState, /* The new state to shift in */ int fts5yyMajor, /* The major token to shift in */ sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */ ){ fts5yyStackEntry *fts5yytos; fts5yypParser->fts5yytos++; #ifdef fts5YYTRACKMAXSTACKDEPTH if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){ fts5yypParser->fts5yyhwm++; assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) ); } #endif #if fts5YYSTACKDEPTH>0 if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){ fts5yypParser->fts5yytos--; fts5yyStackOverflow(fts5yypParser); return; } #else if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){ if( fts5yyGrowStack(fts5yypParser) ){ fts5yypParser->fts5yytos--; fts5yyStackOverflow(fts5yypParser); return; } } #endif if( fts5yyNewState > fts5YY_MAX_SHIFT ){ fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE; } fts5yytos = fts5yypParser->fts5yytos; fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState; fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor; fts5yytos->minor.fts5yy0 = fts5yyMinor; fts5yyTraceShift(fts5yypParser, fts5yyNewState); } /* The following table contains information about every rule that ** is used during the reduce. */ static const struct { fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } fts5yyRuleInfo[] = { { 16, 1 }, { 17, 3 }, { 17, 3 }, { 17, 3 }, { 17, 3 }, { 17, 1 }, { 19, 1 }, { 19, 2 }, { 18, 1 }, { 18, 3 }, { 21, 4 }, { 21, 3 }, { 21, 1 }, { 21, 2 }, { 22, 2 }, { 22, 1 }, { 20, 1 }, { 20, 5 }, { 23, 1 }, { 23, 2 }, { 25, 0 }, { 25, 2 }, { 24, 4 }, { 24, 2 }, { 26, 1 }, { 26, 0 }, }; static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void fts5yy_reduce( fts5yyParser *fts5yypParser, /* The parser */ unsigned int fts5yyruleno /* Number of the rule by which to reduce */ ){ int fts5yygoto; /* The next state */ int fts5yyact; /* The next action */ fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */ int fts5yysize; /* Amount to pop the stack */ sqlite3Fts5ParserARG_FETCH; fts5yymsp = fts5yypParser->fts5yytos; #ifndef NDEBUG if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){ fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs; fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt, fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno); } #endif /* NDEBUG */ /* Check that the stack is large enough to grow by a single entry ** if the RHS of the rule is empty. This ensures that there is room ** enough on the stack to push the LHS value */ if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){ #ifdef fts5YYTRACKMAXSTACKDEPTH if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){ fts5yypParser->fts5yyhwm++; assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)); } #endif #if fts5YYSTACKDEPTH>0 if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){ fts5yyStackOverflow(fts5yypParser); return; } #else if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){ if( fts5yyGrowStack(fts5yypParser) ){ fts5yyStackOverflow(fts5yypParser); return; } fts5yymsp = fts5yypParser->fts5yytos; } #endif } switch( fts5yyruleno ){ /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** #line <lineno> <grammarfile> ** { ... } // User supplied code ** #line <lineno> <thisfile> ** break; */ /********** Begin reduce actions **********************************************/ fts5YYMINORTYPE fts5yylhsminor; case 0: /* input ::= expr */ { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); } break; case 1: /* expr ::= expr AND expr */ { fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); } fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; case 2: /* expr ::= expr OR expr */ { fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); } fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; case 3: /* expr ::= expr NOT expr */ { fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); } fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; case 4: /* expr ::= LP expr RP */ {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;} break; case 5: /* expr ::= exprlist */ case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6); {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;} fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; case 7: /* exprlist ::= exprlist cnearset */ { fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24); } fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; case 8: /* cnearset ::= nearset */ { fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); } fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; case 9: /* cnearset ::= colset COLON nearset */ { sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy46, fts5yymsp[-2].minor.fts5yy11); fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); } fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; case 10: /* colset ::= MINUS LCP colsetlist RCP */ { fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11); } break; case 11: /* colset ::= LCP colsetlist RCP */ { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; } break; case 12: /* colset ::= STRING */ { fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); } fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11; break; case 13: /* colset ::= MINUS STRING */ { fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11); } break; case 14: /* colsetlist ::= colsetlist STRING */ { fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); } fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11; break; case 15: /* colsetlist ::= STRING */ { fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); } fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11; break; case 16: /* nearset ::= phrase */ { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); } fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; case 17: /* nearset ::= STRING LP nearphrases neardist_opt RP */ { sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0); sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0); fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46; } fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; case 18: /* nearphrases ::= phrase */ { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); } fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; case 19: /* nearphrases ::= nearphrases phrase */ { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53); } fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; case 20: /* neardist_opt ::= */ { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; } break; case 21: /* neardist_opt ::= COMMA STRING */ { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; } break; case 22: /* phrase ::= phrase PLUS STRING star_opt */ { fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4); } fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53; break; case 23: /* phrase ::= STRING star_opt */ { fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4); } fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53; break; case 24: /* star_opt ::= STAR */ { fts5yymsp[0].minor.fts5yy4 = 1; } break; case 25: /* star_opt ::= */ { fts5yymsp[1].minor.fts5yy4 = 0; } break; default: break; /********** End reduce actions ************************************************/ }; assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) ); fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs; fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs; fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto); if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){ if( fts5yyact>fts5YY_MAX_SHIFT ){ fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE; } fts5yymsp -= fts5yysize-1; fts5yypParser->fts5yytos = fts5yymsp; fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact; fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto; fts5yyTraceShift(fts5yypParser, fts5yyact); }else{ assert( fts5yyact == fts5YY_ACCEPT_ACTION ); fts5yypParser->fts5yytos -= fts5yysize; fts5yy_accept(fts5yypParser); } } /* ** The following code executes when the parse fails */ #ifndef fts5YYNOERRORRECOVERY static void fts5yy_parse_failed( fts5yyParser *fts5yypParser /* The parser */ ){ sqlite3Fts5ParserARG_FETCH; #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt); } #endif while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ /************ Begin %parse_failure code ***************************************/ /************ End %parse_failure code *****************************************/ sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } #endif /* fts5YYNOERRORRECOVERY */ /* ** The following code executes when a syntax error first occurs. */ static void fts5yy_syntax_error( fts5yyParser *fts5yypParser, /* The parser */ int fts5yymajor, /* The major type of the error token */ sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */ ){ sqlite3Fts5ParserARG_FETCH; #define FTS5TOKEN fts5yyminor /************ Begin %syntax_error code ****************************************/ UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */ sqlite3Fts5ParseError( pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p ); /************ End %syntax_error code ******************************************/ sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void fts5yy_accept( fts5yyParser *fts5yypParser /* The parser */ ){ sqlite3Fts5ParserARG_FETCH; #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt); } #endif #ifndef fts5YYNOERRORRECOVERY fts5yypParser->fts5yyerrcnt = -1; #endif assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack ); /* Here code is inserted which will be executed whenever the ** parser accepts */ /*********** Begin %parse_accept code *****************************************/ /*********** End %parse_accept code *******************************************/ sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: ** <ul> ** <li> A pointer to the parser (an opaque structure.) ** <li> The major token number. ** <li> The minor token number. ** <li> An option argument of a grammar-specified type. ** </ul> ** ** Outputs: ** None. */ static void sqlite3Fts5Parser( void *fts5yyp, /* The parser */ int fts5yymajor, /* The major token code number */ sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */ sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */ ){ fts5YYMINORTYPE fts5yyminorunion; unsigned int fts5yyact; /* The parser action. */ #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY) int fts5yyendofinput; /* True if we are at the end of input */ #endif #ifdef fts5YYERRORSYMBOL int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */ #endif fts5yyParser *fts5yypParser; /* The parser */ fts5yypParser = (fts5yyParser*)fts5yyp; assert( fts5yypParser->fts5yytos!=0 ); #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY) fts5yyendofinput = (fts5yymajor==0); #endif sqlite3Fts5ParserARG_STORE; #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]); } #endif do{ fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor); if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){ fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor); #ifndef fts5YYNOERRORRECOVERY fts5yypParser->fts5yyerrcnt--; #endif fts5yymajor = fts5YYNOCODE; }else if( fts5yyact <= fts5YY_MAX_REDUCE ){ fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE); }else{ assert( fts5yyact == fts5YY_ERROR_ACTION ); fts5yyminorunion.fts5yy0 = fts5yyminor; #ifdef fts5YYERRORSYMBOL int fts5yymx; #endif #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt); } #endif #ifdef fts5YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( fts5yypParser->fts5yyerrcnt<0 ){ fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor); } fts5yymx = fts5yypParser->fts5yytos->major; if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){ #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n", fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]); } #endif fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion); fts5yymajor = fts5YYNOCODE; }else{ while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack && fts5yymx != fts5YYERRORSYMBOL && (fts5yyact = fts5yy_find_reduce_action( fts5yypParser->fts5yytos->stateno, fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE ){ fts5yy_pop_parser_stack(fts5yypParser); } if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){ fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion); fts5yy_parse_failed(fts5yypParser); #ifndef fts5YYNOERRORRECOVERY fts5yypParser->fts5yyerrcnt = -1; #endif fts5yymajor = fts5YYNOCODE; }else if( fts5yymx!=fts5YYERRORSYMBOL ){ fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor); } } fts5yypParser->fts5yyerrcnt = 3; fts5yyerrorhit = 1; #elif defined(fts5YYNOERRORRECOVERY) /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to ** do any kind of error recovery. Instead, simply invoke the syntax ** error routine and continue going as if nothing had happened. ** ** Applications can set this macro (for example inside %include) if ** they intend to abandon the parse upon the first syntax error seen. */ fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor); fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion); fts5yymajor = fts5YYNOCODE; #else /* fts5YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( fts5yypParser->fts5yyerrcnt<=0 ){ fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor); } fts5yypParser->fts5yyerrcnt = 3; fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion); if( fts5yyendofinput ){ fts5yy_parse_failed(fts5yypParser); #ifndef fts5YYNOERRORRECOVERY fts5yypParser->fts5yyerrcnt = -1; #endif } fts5yymajor = fts5YYNOCODE; #endif } }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ); #ifndef NDEBUG if( fts5yyTraceFILE ){ fts5yyStackEntry *i; char cDiv = '['; fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt); for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){ fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]); cDiv = ' '; } fprintf(fts5yyTraceFILE,"]\n"); } #endif return; } /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** */ /* #include "fts5Int.h" */ #include <math.h> /* amalgamator: keep */ /* ** Object used to iterate through all "coalesced phrase instances" in ** a single column of the current row. If the phrase instances in the ** column being considered do not overlap, this object simply iterates ** through them. Or, if they do overlap (share one or more tokens in ** common), each set of overlapping instances is treated as a single ** match. See documentation for the highlight() auxiliary function for ** details. ** ** Usage is: ** ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter); ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter); ** rc = fts5CInstIterNext(&iter) ** ){ ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd); ** } ** */ typedef struct CInstIter CInstIter; struct CInstIter { const Fts5ExtensionApi *pApi; /* API offered by current FTS version */ Fts5Context *pFts; /* First arg to pass to pApi functions */ int iCol; /* Column to search */ int iInst; /* Next phrase instance index */ int nInst; /* Total number of phrase instances */ /* Output variables */ int iStart; /* First token in coalesced phrase instance */ int iEnd; /* Last token in coalesced phrase instance */ }; /* ** Advance the iterator to the next coalesced phrase instance. Return ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. */ static int fts5CInstIterNext(CInstIter *pIter){ int rc = SQLITE_OK; pIter->iStart = -1; pIter->iEnd = -1; while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){ int ip; int ic; int io; rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io); if( rc==SQLITE_OK ){ if( ic==pIter->iCol ){ int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip); if( pIter->iStart<0 ){ pIter->iStart = io; pIter->iEnd = iEnd; }else if( io<=pIter->iEnd ){ if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd; }else{ break; } } pIter->iInst++; } } return rc; } /* ** Initialize the iterator object indicated by the final parameter to ** iterate through coalesced phrase instances in column iCol. */ static int fts5CInstIterInit( const Fts5ExtensionApi *pApi, Fts5Context *pFts, int iCol, CInstIter *pIter ){ int rc; memset(pIter, 0, sizeof(CInstIter)); pIter->pApi = pApi; pIter->pFts = pFts; pIter->iCol = iCol; rc = pApi->xInstCount(pFts, &pIter->nInst); if( rc==SQLITE_OK ){ rc = fts5CInstIterNext(pIter); } return rc; } /************************************************************************* ** Start of highlight() implementation. */ typedef struct HighlightContext HighlightContext; struct HighlightContext { CInstIter iter; /* Coalesced Instance Iterator */ int iPos; /* Current token offset in zIn[] */ int iRangeStart; /* First token to include */ int iRangeEnd; /* If non-zero, last token to include */ const char *zOpen; /* Opening highlight */ const char *zClose; /* Closing highlight */ const char *zIn; /* Input text */ int nIn; /* Size of input text in bytes */ int iOff; /* Current offset within zIn[] */ char *zOut; /* Output value */ }; /* ** Append text to the HighlightContext output string - p->zOut. Argument ** z points to a buffer containing n bytes of text to append. If n is ** negative, everything up until the first '\0' is appended to the output. ** ** If *pRc is set to any value other than SQLITE_OK when this function is ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered, ** *pRc is set to an error code before returning. */ static void fts5HighlightAppend( int *pRc, HighlightContext *p, const char *z, int n ){ if( *pRc==SQLITE_OK ){ if( n<0 ) n = (int)strlen(z); p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z); if( p->zOut==0 ) *pRc = SQLITE_NOMEM; } } /* ** Tokenizer callback used by implementation of highlight() function. */ static int fts5HighlightCb( void *pContext, /* Pointer to HighlightContext object */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Buffer containing token */ int nToken, /* Size of token in bytes */ int iStartOff, /* Start offset of token */ int iEndOff /* End offset of token */ ){ HighlightContext *p = (HighlightContext*)pContext; int rc = SQLITE_OK; int iPos; UNUSED_PARAM2(pToken, nToken); if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK; iPos = p->iPos++; if( p->iRangeEnd>0 ){ if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK; if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff; } if( iPos==p->iter.iStart ){ fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff); fts5HighlightAppend(&rc, p, p->zOpen, -1); p->iOff = iStartOff; } if( iPos==p->iter.iEnd ){ if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){ fts5HighlightAppend(&rc, p, p->zOpen, -1); } fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff); fts5HighlightAppend(&rc, p, p->zClose, -1); p->iOff = iEndOff; if( rc==SQLITE_OK ){ rc = fts5CInstIterNext(&p->iter); } } if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){ fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff); p->iOff = iEndOff; if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){ fts5HighlightAppend(&rc, p, p->zClose, -1); } } return rc; } /* ** Implementation of highlight() function. */ static void fts5HighlightFunction( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ sqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ sqlite3_value **apVal /* Array of trailing arguments */ ){ HighlightContext ctx; int rc; int iCol; if( nVal!=3 ){ const char *zErr = "wrong number of arguments to function highlight()"; sqlite3_result_error(pCtx, zErr, -1); return; } iCol = sqlite3_value_int(apVal[0]); memset(&ctx, 0, sizeof(HighlightContext)); ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]); ctx.zClose = (const char*)sqlite3_value_text(apVal[2]); rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn); if( ctx.zIn ){ if( rc==SQLITE_OK ){ rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter); } if( rc==SQLITE_OK ){ rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb); } fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff); if( rc==SQLITE_OK ){ sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT); } sqlite3_free(ctx.zOut); } if( rc!=SQLITE_OK ){ sqlite3_result_error_code(pCtx, rc); } } /* ** End of highlight() implementation. **************************************************************************/ /* ** Context object passed to the fts5SentenceFinderCb() function. */ typedef struct Fts5SFinder Fts5SFinder; struct Fts5SFinder { int iPos; /* Current token position */ int nFirstAlloc; /* Allocated size of aFirst[] */ int nFirst; /* Number of entries in aFirst[] */ int *aFirst; /* Array of first token in each sentence */ const char *zDoc; /* Document being tokenized */ }; /* ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an ** error occurs. */ static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){ if( p->nFirstAlloc==p->nFirst ){ int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64; int *aNew; aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int)); if( aNew==0 ) return SQLITE_NOMEM; p->aFirst = aNew; p->nFirstAlloc = nNew; } p->aFirst[p->nFirst++] = iAdd; return SQLITE_OK; } /* ** This function is an xTokenize() callback used by the auxiliary snippet() ** function. Its job is to identify tokens that are the first in a sentence. ** For each such token, an entry is added to the SFinder.aFirst[] array. */ static int fts5SentenceFinderCb( void *pContext, /* Pointer to HighlightContext object */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Buffer containing token */ int nToken, /* Size of token in bytes */ int iStartOff, /* Start offset of token */ int iEndOff /* End offset of token */ ){ int rc = SQLITE_OK; UNUSED_PARAM2(pToken, nToken); UNUSED_PARAM(iEndOff); if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){ Fts5SFinder *p = (Fts5SFinder*)pContext; if( p->iPos>0 ){ int i; char c = 0; for(i=iStartOff-1; i>=0; i--){ c = p->zDoc[i]; if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break; } if( i!=iStartOff-1 && (c=='.' || c==':') ){ rc = fts5SentenceFinderAdd(p, p->iPos); } }else{ rc = fts5SentenceFinderAdd(p, 0); } p->iPos++; } return rc; } static int fts5SnippetScore( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ int nDocsize, /* Size of column in tokens */ unsigned char *aSeen, /* Array with one element per query phrase */ int iCol, /* Column to score */ int iPos, /* Starting offset to score */ int nToken, /* Max tokens per snippet */ int *pnScore, /* OUT: Score */ int *piPos /* OUT: Adjusted offset */ ){ int rc; int i; int ip = 0; int ic = 0; int iOff = 0; int iFirst = -1; int nInst; int nScore = 0; int iLast = 0; rc = pApi->xInstCount(pFts, &nInst); for(i=0; i<nInst && rc==SQLITE_OK; i++){ rc = pApi->xInst(pFts, i, &ip, &ic, &iOff); if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){ nScore += (aSeen[ip] ? 1 : 1000); aSeen[ip] = 1; if( iFirst<0 ) iFirst = iOff; iLast = iOff + pApi->xPhraseSize(pFts, ip); } } *pnScore = nScore; if( piPos ){ int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2; if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken; if( iAdj<0 ) iAdj = 0; *piPos = iAdj; } return rc; } /* ** Implementation of snippet() function. */ static void fts5SnippetFunction( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ sqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ sqlite3_value **apVal /* Array of trailing arguments */ ){ HighlightContext ctx; int rc = SQLITE_OK; /* Return code */ int iCol; /* 1st argument to snippet() */ const char *zEllips; /* 4th argument to snippet() */ int nToken; /* 5th argument to snippet() */ int nInst = 0; /* Number of instance matches this row */ int i; /* Used to iterate through instances */ int nPhrase; /* Number of phrases in query */ unsigned char *aSeen; /* Array of "seen instance" flags */ int iBestCol; /* Column containing best snippet */ int iBestStart = 0; /* First token of best snippet */ int nBestScore = 0; /* Score of best snippet */ int nColSize = 0; /* Total size of iBestCol in tokens */ Fts5SFinder sFinder; /* Used to find the beginnings of sentences */ int nCol; if( nVal!=5 ){ const char *zErr = "wrong number of arguments to function snippet()"; sqlite3_result_error(pCtx, zErr, -1); return; } nCol = pApi->xColumnCount(pFts); memset(&ctx, 0, sizeof(HighlightContext)); iCol = sqlite3_value_int(apVal[0]); ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]); ctx.zClose = (const char*)sqlite3_value_text(apVal[2]); zEllips = (const char*)sqlite3_value_text(apVal[3]); nToken = sqlite3_value_int(apVal[4]); iBestCol = (iCol>=0 ? iCol : 0); nPhrase = pApi->xPhraseCount(pFts); aSeen = sqlite3_malloc(nPhrase); if( aSeen==0 ){ rc = SQLITE_NOMEM; } if( rc==SQLITE_OK ){ rc = pApi->xInstCount(pFts, &nInst); } memset(&sFinder, 0, sizeof(Fts5SFinder)); for(i=0; i<nCol; i++){ if( iCol<0 || iCol==i ){ int nDoc; int nDocsize; int ii; sFinder.iPos = 0; sFinder.nFirst = 0; rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc); if( rc!=SQLITE_OK ) break; rc = pApi->xTokenize(pFts, sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb ); if( rc!=SQLITE_OK ) break; rc = pApi->xColumnSize(pFts, i, &nDocsize); if( rc!=SQLITE_OK ) break; for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){ int ip, ic, io; int iAdj; int nScore; int jj; rc = pApi->xInst(pFts, ii, &ip, &ic, &io); if( ic!=i || rc!=SQLITE_OK ) continue; memset(aSeen, 0, nPhrase); rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, io, nToken, &nScore, &iAdj ); if( rc==SQLITE_OK && nScore>nBestScore ){ nBestScore = nScore; iBestCol = i; iBestStart = iAdj; nColSize = nDocsize; } if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){ for(jj=0; jj<(sFinder.nFirst-1); jj++){ if( sFinder.aFirst[jj+1]>io ) break; } if( sFinder.aFirst[jj]<io ){ memset(aSeen, 0, nPhrase); rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, sFinder.aFirst[jj], nToken, &nScore, 0 ); nScore += (sFinder.aFirst[jj]==0 ? 120 : 100); if( rc==SQLITE_OK && nScore>nBestScore ){ nBestScore = nScore; iBestCol = i; iBestStart = sFinder.aFirst[jj]; nColSize = nDocsize; } } } } } } if( rc==SQLITE_OK ){ rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn); } if( rc==SQLITE_OK && nColSize==0 ){ rc = pApi->xColumnSize(pFts, iBestCol, &nColSize); } if( ctx.zIn ){ if( rc==SQLITE_OK ){ rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter); } ctx.iRangeStart = iBestStart; ctx.iRangeEnd = iBestStart + nToken - 1; if( iBestStart>0 ){ fts5HighlightAppend(&rc, &ctx, zEllips, -1); } /* Advance iterator ctx.iter so that it points to the first coalesced ** phrase instance at or following position iBestStart. */ while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){ rc = fts5CInstIterNext(&ctx.iter); } if( rc==SQLITE_OK ){ rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb); } if( ctx.iRangeEnd>=(nColSize-1) ){ fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff); }else{ fts5HighlightAppend(&rc, &ctx, zEllips, -1); } } if( rc==SQLITE_OK ){ sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT); }else{ sqlite3_result_error_code(pCtx, rc); } sqlite3_free(ctx.zOut); sqlite3_free(aSeen); sqlite3_free(sFinder.aFirst); } /************************************************************************/ /* ** The first time the bm25() function is called for a query, an instance ** of the following structure is allocated and populated. */ typedef struct Fts5Bm25Data Fts5Bm25Data; struct Fts5Bm25Data { int nPhrase; /* Number of phrases in query */ double avgdl; /* Average number of tokens in each row */ double *aIDF; /* IDF for each phrase */ double *aFreq; /* Array used to calculate phrase freq. */ }; /* ** Callback used by fts5Bm25GetData() to count the number of rows in the ** table matched by each individual phrase within the query. */ static int fts5CountCb( const Fts5ExtensionApi *pApi, Fts5Context *pFts, void *pUserData /* Pointer to sqlite3_int64 variable */ ){ sqlite3_int64 *pn = (sqlite3_int64*)pUserData; UNUSED_PARAM2(pApi, pFts); (*pn)++; return SQLITE_OK; } /* ** Set *ppData to point to the Fts5Bm25Data object for the current query. ** If the object has not already been allocated, allocate and populate it ** now. */ static int fts5Bm25GetData( const Fts5ExtensionApi *pApi, Fts5Context *pFts, Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */ ){ int rc = SQLITE_OK; /* Return code */ Fts5Bm25Data *p; /* Object to return */ p = pApi->xGetAuxdata(pFts, 0); if( p==0 ){ int nPhrase; /* Number of phrases in query */ sqlite3_int64 nRow = 0; /* Number of rows in table */ sqlite3_int64 nToken = 0; /* Number of tokens in table */ int nByte; /* Bytes of space to allocate */ int i; /* Allocate the Fts5Bm25Data object */ nPhrase = pApi->xPhraseCount(pFts); nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double); p = (Fts5Bm25Data*)sqlite3_malloc(nByte); if( p==0 ){ rc = SQLITE_NOMEM; }else{ memset(p, 0, nByte); p->nPhrase = nPhrase; p->aIDF = (double*)&p[1]; p->aFreq = &p->aIDF[nPhrase]; } /* Calculate the average document length for this FTS5 table */ if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow); if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken); if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow; /* Calculate an IDF for each phrase in the query */ for(i=0; rc==SQLITE_OK && i<nPhrase; i++){ sqlite3_int64 nHit = 0; rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb); if( rc==SQLITE_OK ){ /* Calculate the IDF (Inverse Document Frequency) for phrase i. ** This is done using the standard BM25 formula as found on wikipedia: ** ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) ) ** ** where "N" is the total number of documents in the set and nHit ** is the number that contain at least one instance of the phrase ** under consideration. ** ** The problem with this is that if (N < 2*nHit), the IDF is ** negative. Which is undesirable. So the mimimum allowable IDF is ** (1e-6) - roughly the same as a term that appears in just over ** half of set of 5,000,000 documents. */ double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) ); if( idf<=0.0 ) idf = 1e-6; p->aIDF[i] = idf; } } if( rc!=SQLITE_OK ){ sqlite3_free(p); }else{ rc = pApi->xSetAuxdata(pFts, p, sqlite3_free); } if( rc!=SQLITE_OK ) p = 0; } *ppData = p; return rc; } /* ** Implementation of bm25() function. */ static void fts5Bm25Function( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ sqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ sqlite3_value **apVal /* Array of trailing arguments */ ){ const double k1 = 1.2; /* Constant "k1" from BM25 formula */ const double b = 0.75; /* Constant "b" from BM25 formula */ int rc = SQLITE_OK; /* Error code */ double score = 0.0; /* SQL function return value */ Fts5Bm25Data *pData; /* Values allocated/calculated once only */ int i; /* Iterator variable */ int nInst = 0; /* Value returned by xInstCount() */ double D = 0.0; /* Total number of tokens in row */ double *aFreq = 0; /* Array of phrase freq. for current row */ /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation) ** for each phrase in the query for the current row. */ rc = fts5Bm25GetData(pApi, pFts, &pData); if( rc==SQLITE_OK ){ aFreq = pData->aFreq; memset(aFreq, 0, sizeof(double) * pData->nPhrase); rc = pApi->xInstCount(pFts, &nInst); } for(i=0; rc==SQLITE_OK && i<nInst; i++){ int ip; int ic; int io; rc = pApi->xInst(pFts, i, &ip, &ic, &io); if( rc==SQLITE_OK ){ double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0; aFreq[ip] += w; } } /* Figure out the total size of the current row in tokens. */ if( rc==SQLITE_OK ){ int nTok; rc = pApi->xColumnSize(pFts, -1, &nTok); D = (double)nTok; } /* Determine the BM25 score for the current row. */ for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){ score += pData->aIDF[i] * ( ( aFreq[i] * (k1 + 1.0) ) / ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) ) ); } /* If no error has occurred, return the calculated score. Otherwise, ** throw an SQL exception. */ if( rc==SQLITE_OK ){ sqlite3_result_double(pCtx, -1.0 * score); }else{ sqlite3_result_error_code(pCtx, rc); } } static int sqlite3Fts5AuxInit(fts5_api *pApi){ struct Builtin { const char *zFunc; /* Function name (nul-terminated) */ void *pUserData; /* User-data pointer */ fts5_extension_function xFunc;/* Callback function */ void (*xDestroy)(void*); /* Destructor function */ } aBuiltin [] = { { "snippet", 0, fts5SnippetFunction, 0 }, { "highlight", 0, fts5HighlightFunction, 0 }, { "bm25", 0, fts5Bm25Function, 0 }, }; int rc = SQLITE_OK; /* Return code */ int i; /* To iterate through builtin functions */ for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){ rc = pApi->xCreateFunction(pApi, aBuiltin[i].zFunc, aBuiltin[i].pUserData, aBuiltin[i].xFunc, aBuiltin[i].xDestroy ); } return rc; } /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** */ /* #include "fts5Int.h" */ static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){ if( (u32)pBuf->nSpace<nByte ){ u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64; u8 *pNew; while( nNew<nByte ){ nNew = nNew * 2; } pNew = sqlite3_realloc(pBuf->p, nNew); if( pNew==0 ){ *pRc = SQLITE_NOMEM; return 1; }else{ pBuf->nSpace = nNew; pBuf->p = pNew; } } return 0; } /* ** Encode value iVal as an SQLite varint and append it to the buffer object ** pBuf. If an OOM error occurs, set the error code in p. */ static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){ if( fts5BufferGrow(pRc, pBuf, 9) ) return; pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal); } static void sqlite3Fts5Put32(u8 *aBuf, int iVal){ aBuf[0] = (iVal>>24) & 0x00FF; aBuf[1] = (iVal>>16) & 0x00FF; aBuf[2] = (iVal>> 8) & 0x00FF; aBuf[3] = (iVal>> 0) & 0x00FF; } static int sqlite3Fts5Get32(const u8 *aBuf){ return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3]; } /* ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set ** the error code in p. If an error has already occurred when this function ** is called, it is a no-op. */ static void sqlite3Fts5BufferAppendBlob( int *pRc, Fts5Buffer *pBuf, u32 nData, const u8 *pData ){ assert_nc( *pRc || nData>=0 ); if( fts5BufferGrow(pRc, pBuf, nData) ) return; memcpy(&pBuf->p[pBuf->n], pData, nData); pBuf->n += nData; } /* ** Append the nul-terminated string zStr to the buffer pBuf. This function ** ensures that the byte following the buffer data is set to 0x00, even ** though this byte is not included in the pBuf->n count. */ static void sqlite3Fts5BufferAppendString( int *pRc, Fts5Buffer *pBuf, const char *zStr ){ int nStr = (int)strlen(zStr); sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr); pBuf->n--; } /* ** Argument zFmt is a printf() style format string. This function performs ** the printf() style processing, then appends the results to buffer pBuf. ** ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte ** following the buffer data is set to 0x00, even though this byte is not ** included in the pBuf->n count. */ static void sqlite3Fts5BufferAppendPrintf( int *pRc, Fts5Buffer *pBuf, char *zFmt, ... ){ if( *pRc==SQLITE_OK ){ char *zTmp; va_list ap; va_start(ap, zFmt); zTmp = sqlite3_vmprintf(zFmt, ap); va_end(ap); if( zTmp==0 ){ *pRc = SQLITE_NOMEM; }else{ sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp); sqlite3_free(zTmp); } } } static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){ char *zRet = 0; if( *pRc==SQLITE_OK ){ va_list ap; va_start(ap, zFmt); zRet = sqlite3_vmprintf(zFmt, ap); va_end(ap); if( zRet==0 ){ *pRc = SQLITE_NOMEM; } } return zRet; } /* ** Free any buffer allocated by pBuf. Zero the structure before returning. */ static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){ sqlite3_free(pBuf->p); memset(pBuf, 0, sizeof(Fts5Buffer)); } /* ** Zero the contents of the buffer object. But do not free the associated ** memory allocation. */ static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){ pBuf->n = 0; } /* ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an ** the error code in p. If an error has already occurred when this function ** is called, it is a no-op. */ static void sqlite3Fts5BufferSet( int *pRc, Fts5Buffer *pBuf, int nData, const u8 *pData ){ pBuf->n = 0; sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData); } static int sqlite3Fts5PoslistNext64( const u8 *a, int n, /* Buffer containing poslist */ int *pi, /* IN/OUT: Offset within a[] */ i64 *piOff /* IN/OUT: Current offset */ ){ int i = *pi; if( i>=n ){ /* EOF */ *piOff = -1; return 1; }else{ i64 iOff = *piOff; int iVal; fts5FastGetVarint32(a, i, iVal); if( iVal==1 ){ fts5FastGetVarint32(a, i, iVal); iOff = ((i64)iVal) << 32; fts5FastGetVarint32(a, i, iVal); } *piOff = iOff + (iVal-2); *pi = i; return 0; } } /* ** Advance the iterator object passed as the only argument. Return true ** if the iterator reaches EOF, or false otherwise. */ static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){ if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){ pIter->bEof = 1; } return pIter->bEof; } static int sqlite3Fts5PoslistReaderInit( const u8 *a, int n, /* Poslist buffer to iterate through */ Fts5PoslistReader *pIter /* Iterator object to initialize */ ){ memset(pIter, 0, sizeof(*pIter)); pIter->a = a; pIter->n = n; sqlite3Fts5PoslistReaderNext(pIter); return pIter->bEof; } /* ** Append position iPos to the position list being accumulated in buffer ** pBuf, which must be already be large enough to hold the new data. ** The previous position written to this list is *piPrev. *piPrev is set ** to iPos before returning. */ static void sqlite3Fts5PoslistSafeAppend( Fts5Buffer *pBuf, i64 *piPrev, i64 iPos ){ static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32; if( (iPos & colmask) != (*piPrev & colmask) ){ pBuf->p[pBuf->n++] = 1; pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32)); *piPrev = (iPos & colmask); } pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2); *piPrev = iPos; } static int sqlite3Fts5PoslistWriterAppend( Fts5Buffer *pBuf, Fts5PoslistWriter *pWriter, i64 iPos ){ int rc = 0; /* Initialized only to suppress erroneous warning from Clang */ if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc; sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos); return SQLITE_OK; } static void *sqlite3Fts5MallocZero(int *pRc, int nByte){ void *pRet = 0; if( *pRc==SQLITE_OK ){ pRet = sqlite3_malloc(nByte); if( pRet==0 && nByte>0 ){ *pRc = SQLITE_NOMEM; }else{ memset(pRet, 0, nByte); } } return pRet; } /* ** Return a nul-terminated copy of the string indicated by pIn. If nIn ** is non-negative, then it is the length of the string in bytes. Otherwise, ** the length of the string is determined using strlen(). ** ** It is the responsibility of the caller to eventually free the returned ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned. */ static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){ char *zRet = 0; if( *pRc==SQLITE_OK ){ if( nIn<0 ){ nIn = (int)strlen(pIn); } zRet = (char*)sqlite3_malloc(nIn+1); if( zRet ){ memcpy(zRet, pIn, nIn); zRet[nIn] = '\0'; }else{ *pRc = SQLITE_NOMEM; } } return zRet; } /* ** Return true if character 't' may be part of an FTS5 bareword, or false ** otherwise. Characters that may be part of barewords: ** ** * All non-ASCII characters, ** * The 52 upper and lower case ASCII characters, and ** * The 10 integer ASCII characters. ** * The underscore character "_" (0x5F). ** * The unicode "subsitute" character (0x1A). */ static int sqlite3Fts5IsBareword(char t){ u8 aBareword[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */ }; return (t & 0x80) || aBareword[(int)t]; } /************************************************************************* */ typedef struct Fts5TermsetEntry Fts5TermsetEntry; struct Fts5TermsetEntry { char *pTerm; int nTerm; int iIdx; /* Index (main or aPrefix[] entry) */ Fts5TermsetEntry *pNext; }; struct Fts5Termset { Fts5TermsetEntry *apHash[512]; }; static int sqlite3Fts5TermsetNew(Fts5Termset **pp){ int rc = SQLITE_OK; *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset)); return rc; } static int sqlite3Fts5TermsetAdd( Fts5Termset *p, int iIdx, const char *pTerm, int nTerm, int *pbPresent ){ int rc = SQLITE_OK; *pbPresent = 0; if( p ){ int i; u32 hash = 13; Fts5TermsetEntry *pEntry; /* Calculate a hash value for this term. This is the same hash checksum ** used by the fts5_hash.c module. This is not important for correct ** operation of the module, but is necessary to ensure that some tests ** designed to produce hash table collisions really do work. */ for(i=nTerm-1; i>=0; i--){ hash = (hash << 3) ^ hash ^ pTerm[i]; } hash = (hash << 3) ^ hash ^ iIdx; hash = hash % ArraySize(p->apHash); for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){ if( pEntry->iIdx==iIdx && pEntry->nTerm==nTerm && memcmp(pEntry->pTerm, pTerm, nTerm)==0 ){ *pbPresent = 1; break; } } if( pEntry==0 ){ pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm); if( pEntry ){ pEntry->pTerm = (char*)&pEntry[1]; pEntry->nTerm = nTerm; pEntry->iIdx = iIdx; memcpy(pEntry->pTerm, pTerm, nTerm); pEntry->pNext = p->apHash[hash]; p->apHash[hash] = pEntry; } } } return rc; } static void sqlite3Fts5TermsetFree(Fts5Termset *p){ if( p ){ u32 i; for(i=0; i<ArraySize(p->apHash); i++){ Fts5TermsetEntry *pEntry = p->apHash[i]; while( pEntry ){ Fts5TermsetEntry *pDel = pEntry; pEntry = pEntry->pNext; sqlite3_free(pDel); } } sqlite3_free(p); } } /* ** 2014 Jun 09 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This is an SQLite module implementing full-text search. */ /* #include "fts5Int.h" */ #define FTS5_DEFAULT_PAGE_SIZE 4050 #define FTS5_DEFAULT_AUTOMERGE 4 #define FTS5_DEFAULT_USERMERGE 4 #define FTS5_DEFAULT_CRISISMERGE 16 #define FTS5_DEFAULT_HASHSIZE (1024*1024) /* Maximum allowed page size */ #define FTS5_MAX_PAGE_SIZE (128*1024) static int fts5_iswhitespace(char x){ return (x==' '); } static int fts5_isopenquote(char x){ return (x=='"' || x=='\'' || x=='[' || x=='`'); } /* ** Argument pIn points to a character that is part of a nul-terminated ** string. Return a pointer to the first character following *pIn in ** the string that is not a white-space character. */ static const char *fts5ConfigSkipWhitespace(const char *pIn){ const char *p = pIn; if( p ){ while( fts5_iswhitespace(*p) ){ p++; } } return p; } /* ** Argument pIn points to a character that is part of a nul-terminated ** string. Return a pointer to the first character following *pIn in ** the string that is not a "bareword" character. */ static const char *fts5ConfigSkipBareword(const char *pIn){ const char *p = pIn; while ( sqlite3Fts5IsBareword(*p) ) p++; if( p==pIn ) p = 0; return p; } static int fts5_isdigit(char a){ return (a>='0' && a<='9'); } static const char *fts5ConfigSkipLiteral(const char *pIn){ const char *p = pIn; switch( *p ){ case 'n': case 'N': if( sqlite3_strnicmp("null", p, 4)==0 ){ p = &p[4]; }else{ p = 0; } break; case 'x': case 'X': p++; if( *p=='\'' ){ p++; while( (*p>='a' && *p<='f') || (*p>='A' && *p<='F') || (*p>='0' && *p<='9') ){ p++; } if( *p=='\'' && 0==((p-pIn)%2) ){ p++; }else{ p = 0; } }else{ p = 0; } break; case '\'': p++; while( p ){ if( *p=='\'' ){ p++; if( *p!='\'' ) break; } p++; if( *p==0 ) p = 0; } break; default: /* maybe a number */ if( *p=='+' || *p=='-' ) p++; while( fts5_isdigit(*p) ) p++; /* At this point, if the literal was an integer, the parse is ** finished. Or, if it is a floating point value, it may continue ** with either a decimal point or an 'E' character. */ if( *p=='.' && fts5_isdigit(p[1]) ){ p += 2; while( fts5_isdigit(*p) ) p++; } if( p==pIn ) p = 0; break; } return p; } /* ** The first character of the string pointed to by argument z is guaranteed ** to be an open-quote character (see function fts5_isopenquote()). ** ** This function searches for the corresponding close-quote character within ** the string and, if found, dequotes the string in place and adds a new ** nul-terminator byte. ** ** If the close-quote is found, the value returned is the byte offset of ** the character immediately following it. Or, if the close-quote is not ** found, -1 is returned. If -1 is returned, the buffer is left in an ** undefined state. */ static int fts5Dequote(char *z){ char q; int iIn = 1; int iOut = 0; q = z[0]; /* Set stack variable q to the close-quote character */ assert( q=='[' || q=='\'' || q=='"' || q=='`' ); if( q=='[' ) q = ']'; while( ALWAYS(z[iIn]) ){ if( z[iIn]==q ){ if( z[iIn+1]!=q ){ /* Character iIn was the close quote. */ iIn++; break; }else{ /* Character iIn and iIn+1 form an escaped quote character. Skip ** the input cursor past both and copy a single quote character ** to the output buffer. */ iIn += 2; z[iOut++] = q; } }else{ z[iOut++] = z[iIn++]; } } z[iOut] = '\0'; return iIn; } /* ** Convert an SQL-style quoted string into a normal string by removing ** the quote characters. The conversion is done in-place. If the ** input does not begin with a quote character, then this routine ** is a no-op. ** ** Examples: ** ** "abc" becomes abc ** 'xyz' becomes xyz ** [pqr] becomes pqr ** `mno` becomes mno */ static void sqlite3Fts5Dequote(char *z){ char quote; /* Quote character (if any ) */ assert( 0==fts5_iswhitespace(z[0]) ); quote = z[0]; if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ fts5Dequote(z); } } struct Fts5Enum { const char *zName; int eVal; }; typedef struct Fts5Enum Fts5Enum; static int fts5ConfigSetEnum( const Fts5Enum *aEnum, const char *zEnum, int *peVal ){ int nEnum = (int)strlen(zEnum); int i; int iVal = -1; for(i=0; aEnum[i].zName; i++){ if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){ if( iVal>=0 ) return SQLITE_ERROR; iVal = aEnum[i].eVal; } } *peVal = iVal; return iVal<0 ? SQLITE_ERROR : SQLITE_OK; } /* ** Parse a "special" CREATE VIRTUAL TABLE directive and update ** configuration object pConfig as appropriate. ** ** If successful, object pConfig is updated and SQLITE_OK returned. If ** an error occurs, an SQLite error code is returned and an error message ** may be left in *pzErr. It is the responsibility of the caller to ** eventually free any such error message using sqlite3_free(). */ static int fts5ConfigParseSpecial( Fts5Global *pGlobal, Fts5Config *pConfig, /* Configuration object to update */ const char *zCmd, /* Special command to parse */ const char *zArg, /* Argument to parse */ char **pzErr /* OUT: Error message */ ){ int rc = SQLITE_OK; int nCmd = (int)strlen(zCmd); if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){ const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES; const char *p; int bFirst = 1; if( pConfig->aPrefix==0 ){ pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte); if( rc ) return rc; } p = zArg; while( 1 ){ int nPre = 0; while( p[0]==' ' ) p++; if( bFirst==0 && p[0]==',' ){ p++; while( p[0]==' ' ) p++; }else if( p[0]=='\0' ){ break; } if( p[0]<'0' || p[0]>'9' ){ *pzErr = sqlite3_mprintf("malformed prefix=... directive"); rc = SQLITE_ERROR; break; } if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){ *pzErr = sqlite3_mprintf( "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES ); rc = SQLITE_ERROR; break; } while( p[0]>='0' && p[0]<='9' && nPre<1000 ){ nPre = nPre*10 + (p[0] - '0'); p++; } if( nPre<=0 || nPre>=1000 ){ *pzErr = sqlite3_mprintf("prefix length out of range (max 999)"); rc = SQLITE_ERROR; break; } pConfig->aPrefix[pConfig->nPrefix] = nPre; pConfig->nPrefix++; bFirst = 0; } assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES ); return rc; } if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){ const char *p = (const char*)zArg; int nArg = (int)strlen(zArg) + 1; char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg); char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2); char *pSpace = pDel; if( azArg && pSpace ){ if( pConfig->pTok ){ *pzErr = sqlite3_mprintf("multiple tokenize=... directives"); rc = SQLITE_ERROR; }else{ for(nArg=0; p && *p; nArg++){ const char *p2 = fts5ConfigSkipWhitespace(p); if( *p2=='\'' ){ p = fts5ConfigSkipLiteral(p2); }else{ p = fts5ConfigSkipBareword(p2); } if( p ){ memcpy(pSpace, p2, p-p2); azArg[nArg] = pSpace; sqlite3Fts5Dequote(pSpace); pSpace += (p - p2) + 1; p = fts5ConfigSkipWhitespace(p); } } if( p==0 ){ *pzErr = sqlite3_mprintf("parse error in tokenize directive"); rc = SQLITE_ERROR; }else{ rc = sqlite3Fts5GetTokenizer(pGlobal, (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi, pzErr ); } } } sqlite3_free(azArg); sqlite3_free(pDel); return rc; } if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){ if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){ *pzErr = sqlite3_mprintf("multiple content=... directives"); rc = SQLITE_ERROR; }else{ if( zArg[0] ){ pConfig->eContent = FTS5_CONTENT_EXTERNAL; pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg); }else{ pConfig->eContent = FTS5_CONTENT_NONE; } } return rc; } if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){ if( pConfig->zContentRowid ){ *pzErr = sqlite3_mprintf("multiple content_rowid=... directives"); rc = SQLITE_ERROR; }else{ pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1); } return rc; } if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){ if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){ *pzErr = sqlite3_mprintf("malformed columnsize=... directive"); rc = SQLITE_ERROR; }else{ pConfig->bColumnsize = (zArg[0]=='1'); } return rc; } if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){ const Fts5Enum aDetail[] = { { "none", FTS5_DETAIL_NONE }, { "full", FTS5_DETAIL_FULL }, { "columns", FTS5_DETAIL_COLUMNS }, { 0, 0 } }; if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){ *pzErr = sqlite3_mprintf("malformed detail=... directive"); } return rc; } *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd); return SQLITE_ERROR; } /* ** Allocate an instance of the default tokenizer ("simple") at ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error ** code if an error occurs. */ static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){ assert( pConfig->pTok==0 && pConfig->pTokApi==0 ); return sqlite3Fts5GetTokenizer( pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0 ); } /* ** Gobble up the first bareword or quoted word from the input buffer zIn. ** Return a pointer to the character immediately following the last in ** the gobbled word if successful, or a NULL pointer otherwise (failed ** to find close-quote character). ** ** Before returning, set pzOut to point to a new buffer containing a ** nul-terminated, dequoted copy of the gobbled word. If the word was ** quoted, *pbQuoted is also set to 1 before returning. ** ** If *pRc is other than SQLITE_OK when this function is called, it is ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not* ** set if a parse error (failed to find close quote) occurs. */ static const char *fts5ConfigGobbleWord( int *pRc, /* IN/OUT: Error code */ const char *zIn, /* Buffer to gobble string/bareword from */ char **pzOut, /* OUT: malloc'd buffer containing str/bw */ int *pbQuoted /* OUT: Set to true if dequoting required */ ){ const char *zRet = 0; int nIn = (int)strlen(zIn); char *zOut = sqlite3_malloc(nIn+1); assert( *pRc==SQLITE_OK ); *pbQuoted = 0; *pzOut = 0; if( zOut==0 ){ *pRc = SQLITE_NOMEM; }else{ memcpy(zOut, zIn, nIn+1); if( fts5_isopenquote(zOut[0]) ){ int ii = fts5Dequote(zOut); zRet = &zIn[ii]; *pbQuoted = 1; }else{ zRet = fts5ConfigSkipBareword(zIn); if( zRet ){ zOut[zRet-zIn] = '\0'; } } } if( zRet==0 ){ sqlite3_free(zOut); }else{ *pzOut = zOut; } return zRet; } static int fts5ConfigParseColumn( Fts5Config *p, char *zCol, char *zArg, char **pzErr ){ int rc = SQLITE_OK; if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME) || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME) ){ *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol); rc = SQLITE_ERROR; }else if( zArg ){ if( 0==sqlite3_stricmp(zArg, "unindexed") ){ p->abUnindexed[p->nCol] = 1; }else{ *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg); rc = SQLITE_ERROR; } } p->azCol[p->nCol++] = zCol; return rc; } /* ** Populate the Fts5Config.zContentExprlist string. */ static int fts5ConfigMakeExprlist(Fts5Config *p){ int i; int rc = SQLITE_OK; Fts5Buffer buf = {0, 0, 0}; sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid); if( p->eContent!=FTS5_CONTENT_NONE ){ for(i=0; i<p->nCol; i++){ if( p->eContent==FTS5_CONTENT_EXTERNAL ){ sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]); }else{ sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i); } } } assert( p->zContentExprlist==0 ); p->zContentExprlist = (char*)buf.p; return rc; } /* ** Arguments nArg/azArg contain the string arguments passed to the xCreate ** or xConnect method of the virtual table. This function attempts to ** allocate an instance of Fts5Config containing the results of parsing ** those arguments. ** ** If successful, SQLITE_OK is returned and *ppOut is set to point to the ** new Fts5Config object. If an error occurs, an SQLite error code is ** returned, *ppOut is set to NULL and an error message may be left in ** *pzErr. It is the responsibility of the caller to eventually free any ** such error message using sqlite3_free(). */ static int sqlite3Fts5ConfigParse( Fts5Global *pGlobal, sqlite3 *db, int nArg, /* Number of arguments */ const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */ Fts5Config **ppOut, /* OUT: Results of parse */ char **pzErr /* OUT: Error message */ ){ int rc = SQLITE_OK; /* Return code */ Fts5Config *pRet; /* New object to return */ int i; int nByte; *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config)); if( pRet==0 ) return SQLITE_NOMEM; memset(pRet, 0, sizeof(Fts5Config)); pRet->db = db; pRet->iCookie = -1; nByte = nArg * (sizeof(char*) + sizeof(u8)); pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte); pRet->abUnindexed = (u8*)&pRet->azCol[nArg]; pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1); pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1); pRet->bColumnsize = 1; pRet->eDetail = FTS5_DETAIL_FULL; #ifdef SQLITE_DEBUG pRet->bPrefixIndex = 1; #endif if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){ *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName); rc = SQLITE_ERROR; } for(i=3; rc==SQLITE_OK && i<nArg; i++){ const char *zOrig = azArg[i]; const char *z; char *zOne = 0; char *zTwo = 0; int bOption = 0; int bMustBeCol = 0; z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol); z = fts5ConfigSkipWhitespace(z); if( z && *z=='=' ){ bOption = 1; z++; if( bMustBeCol ) z = 0; } z = fts5ConfigSkipWhitespace(z); if( z && z[0] ){ int bDummy; z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy); if( z && z[0] ) z = 0; } if( rc==SQLITE_OK ){ if( z==0 ){ *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig); rc = SQLITE_ERROR; }else{ if( bOption ){ rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr); }else{ rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr); zOne = 0; } } } sqlite3_free(zOne); sqlite3_free(zTwo); } /* If a tokenizer= option was successfully parsed, the tokenizer has ** already been allocated. Otherwise, allocate an instance of the default ** tokenizer (unicode61) now. */ if( rc==SQLITE_OK && pRet->pTok==0 ){ rc = fts5ConfigDefaultTokenizer(pGlobal, pRet); } /* If no zContent option was specified, fill in the default values. */ if( rc==SQLITE_OK && pRet->zContent==0 ){ const char *zTail = 0; assert( pRet->eContent==FTS5_CONTENT_NORMAL || pRet->eContent==FTS5_CONTENT_NONE ); if( pRet->eContent==FTS5_CONTENT_NORMAL ){ zTail = "content"; }else if( pRet->bColumnsize ){ zTail = "docsize"; } if( zTail ){ pRet->zContent = sqlite3Fts5Mprintf( &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail ); } } if( rc==SQLITE_OK && pRet->zContentRowid==0 ){ pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1); } /* Formulate the zContentExprlist text */ if( rc==SQLITE_OK ){ rc = fts5ConfigMakeExprlist(pRet); } if( rc!=SQLITE_OK ){ sqlite3Fts5ConfigFree(pRet); *ppOut = 0; } return rc; } /* ** Free the configuration object passed as the only argument. */ static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){ if( pConfig ){ int i; if( pConfig->pTok ){ pConfig->pTokApi->xDelete(pConfig->pTok); } sqlite3_free(pConfig->zDb); sqlite3_free(pConfig->zName); for(i=0; i<pConfig->nCol; i++){ sqlite3_free(pConfig->azCol[i]); } sqlite3_free(pConfig->azCol); sqlite3_free(pConfig->aPrefix); sqlite3_free(pConfig->zRank); sqlite3_free(pConfig->zRankArgs); sqlite3_free(pConfig->zContent); sqlite3_free(pConfig->zContentRowid); sqlite3_free(pConfig->zContentExprlist); sqlite3_free(pConfig); } } /* ** Call sqlite3_declare_vtab() based on the contents of the configuration ** object passed as the only argument. Return SQLITE_OK if successful, or ** an SQLite error code if an error occurs. */ static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){ int i; int rc = SQLITE_OK; char *zSql; zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x("); for(i=0; zSql && i<pConfig->nCol; i++){ const char *zSep = (i==0?"":", "); zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]); } zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)", zSql, pConfig->zName, FTS5_RANK_NAME ); assert( zSql || rc==SQLITE_NOMEM ); if( zSql ){ rc = sqlite3_declare_vtab(pConfig->db, zSql); sqlite3_free(zSql); } return rc; } /* ** Tokenize the text passed via the second and third arguments. ** ** The callback is invoked once for each token in the input text. The ** arguments passed to it are, in order: ** ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize() ** const char *pToken // Pointer to buffer containing token ** int nToken // Size of token in bytes ** int iStart // Byte offset of start of token within input text ** int iEnd // Byte offset of end of token within input text ** int iPos // Position of token in input (first token is 0) ** ** If the callback returns a non-zero value the tokenization is abandoned ** and no further callbacks are issued. ** ** This function returns SQLITE_OK if successful or an SQLite error code ** if an error occurs. If the tokenization was abandoned early because ** the callback returned SQLITE_DONE, this is not an error and this function ** still returns SQLITE_OK. Or, if the tokenization was abandoned early ** because the callback returned another non-zero value, it is assumed ** to be an SQLite error code and returned to the caller. */ static int sqlite3Fts5Tokenize( Fts5Config *pConfig, /* FTS5 Configuration object */ int flags, /* FTS5_TOKENIZE_* flags */ const char *pText, int nText, /* Text to tokenize */ void *pCtx, /* Context passed to xToken() */ int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ){ if( pText==0 ) return SQLITE_OK; return pConfig->pTokApi->xTokenize( pConfig->pTok, pCtx, flags, pText, nText, xToken ); } /* ** Argument pIn points to the first character in what is expected to be ** a comma-separated list of SQL literals followed by a ')' character. ** If it actually is this, return a pointer to the ')'. Otherwise, return ** NULL to indicate a parse error. */ static const char *fts5ConfigSkipArgs(const char *pIn){ const char *p = pIn; while( 1 ){ p = fts5ConfigSkipWhitespace(p); p = fts5ConfigSkipLiteral(p); p = fts5ConfigSkipWhitespace(p); if( p==0 || *p==')' ) break; if( *p!=',' ){ p = 0; break; } p++; } return p; } /* ** Parameter zIn contains a rank() function specification. The format of ** this is: ** ** + Bareword (function name) ** + Open parenthesis - "(" ** + Zero or more SQL literals in a comma separated list ** + Close parenthesis - ")" */ static int sqlite3Fts5ConfigParseRank( const char *zIn, /* Input string */ char **pzRank, /* OUT: Rank function name */ char **pzRankArgs /* OUT: Rank function arguments */ ){ const char *p = zIn; const char *pRank; char *zRank = 0; char *zRankArgs = 0; int rc = SQLITE_OK; *pzRank = 0; *pzRankArgs = 0; if( p==0 ){ rc = SQLITE_ERROR; }else{ p = fts5ConfigSkipWhitespace(p); pRank = p; p = fts5ConfigSkipBareword(p); if( p ){ zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank); if( zRank ) memcpy(zRank, pRank, p-pRank); }else{ rc = SQLITE_ERROR; } if( rc==SQLITE_OK ){ p = fts5ConfigSkipWhitespace(p); if( *p!='(' ) rc = SQLITE_ERROR; p++; } if( rc==SQLITE_OK ){ const char *pArgs; p = fts5ConfigSkipWhitespace(p); pArgs = p; if( *p!=')' ){ p = fts5ConfigSkipArgs(p); if( p==0 ){ rc = SQLITE_ERROR; }else{ zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs); if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs); } } } } if( rc!=SQLITE_OK ){ sqlite3_free(zRank); assert( zRankArgs==0 ); }else{ *pzRank = zRank; *pzRankArgs = zRankArgs; } return rc; } static int sqlite3Fts5ConfigSetValue( Fts5Config *pConfig, const char *zKey, sqlite3_value *pVal, int *pbBadkey ){ int rc = SQLITE_OK; if( 0==sqlite3_stricmp(zKey, "pgsz") ){ int pgsz = 0; if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ pgsz = sqlite3_value_int(pVal); } if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){ *pbBadkey = 1; }else{ pConfig->pgsz = pgsz; } } else if( 0==sqlite3_stricmp(zKey, "hashsize") ){ int nHashSize = -1; if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ nHashSize = sqlite3_value_int(pVal); } if( nHashSize<=0 ){ *pbBadkey = 1; }else{ pConfig->nHashSize = nHashSize; } } else if( 0==sqlite3_stricmp(zKey, "automerge") ){ int nAutomerge = -1; if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ nAutomerge = sqlite3_value_int(pVal); } if( nAutomerge<0 || nAutomerge>64 ){ *pbBadkey = 1; }else{ if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE; pConfig->nAutomerge = nAutomerge; } } else if( 0==sqlite3_stricmp(zKey, "usermerge") ){ int nUsermerge = -1; if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ nUsermerge = sqlite3_value_int(pVal); } if( nUsermerge<2 || nUsermerge>16 ){ *pbBadkey = 1; }else{ pConfig->nUsermerge = nUsermerge; } } else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){ int nCrisisMerge = -1; if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ nCrisisMerge = sqlite3_value_int(pVal); } if( nCrisisMerge<0 ){ *pbBadkey = 1; }else{ if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE; pConfig->nCrisisMerge = nCrisisMerge; } } else if( 0==sqlite3_stricmp(zKey, "rank") ){ const char *zIn = (const char*)sqlite3_value_text(pVal); char *zRank; char *zRankArgs; rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs); if( rc==SQLITE_OK ){ sqlite3_free(pConfig->zRank); sqlite3_free(pConfig->zRankArgs); pConfig->zRank = zRank; pConfig->zRankArgs = zRankArgs; }else if( rc==SQLITE_ERROR ){ rc = SQLITE_OK; *pbBadkey = 1; } }else{ *pbBadkey = 1; } return rc; } /* ** Load the contents of the %_config table into memory. */ static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){ const char *zSelect = "SELECT k, v FROM %Q.'%q_config'"; char *zSql; sqlite3_stmt *p = 0; int rc = SQLITE_OK; int iVersion = 0; /* Set default values */ pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE; pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE; pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE; pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE; pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE; zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName); if( zSql ){ rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0); sqlite3_free(zSql); } assert( rc==SQLITE_OK || p==0 ); if( rc==SQLITE_OK ){ while( SQLITE_ROW==sqlite3_step(p) ){ const char *zK = (const char*)sqlite3_column_text(p, 0); sqlite3_value *pVal = sqlite3_column_value(p, 1); if( 0==sqlite3_stricmp(zK, "version") ){ iVersion = sqlite3_value_int(pVal); }else{ int bDummy = 0; sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy); } } rc = sqlite3_finalize(p); } if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){ rc = SQLITE_ERROR; if( pConfig->pzErrmsg ){ assert( 0==*pConfig->pzErrmsg ); *pConfig->pzErrmsg = sqlite3_mprintf( "invalid fts5 file format (found %d, expected %d) - run 'rebuild'", iVersion, FTS5_CURRENT_VERSION ); } } if( rc==SQLITE_OK ){ pConfig->iCookie = iCookie; } return rc; } /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ /* #include "fts5Int.h" */ /* #include "fts5parse.h" */ /* ** All token types in the generated fts5parse.h file are greater than 0. */ #define FTS5_EOF 0 #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) typedef struct Fts5ExprTerm Fts5ExprTerm; /* ** Functions generated by lemon from fts5parse.y. */ static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64)); static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*)); static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*); #ifndef NDEBUG /* #include <stdio.h> */ static void sqlite3Fts5ParserTrace(FILE*, char*); #endif struct Fts5Expr { Fts5Index *pIndex; Fts5Config *pConfig; Fts5ExprNode *pRoot; int bDesc; /* Iterate in descending rowid order */ int nPhrase; /* Number of phrases in expression */ Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */ }; /* ** eType: ** Expression node type. Always one of: ** ** FTS5_AND (nChild, apChild valid) ** FTS5_OR (nChild, apChild valid) ** FTS5_NOT (nChild, apChild valid) ** FTS5_STRING (pNear valid) ** FTS5_TERM (pNear valid) */ struct Fts5ExprNode { int eType; /* Node type */ int bEof; /* True at EOF */ int bNomatch; /* True if entry is not a match */ /* Next method for this node. */ int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64); i64 iRowid; /* Current rowid */ Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */ /* Child nodes. For a NOT node, this array always contains 2 entries. For ** AND or OR nodes, it contains 2 or more entries. */ int nChild; /* Number of child nodes */ Fts5ExprNode *apChild[1]; /* Array of child nodes */ }; #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING) /* ** Invoke the xNext method of an Fts5ExprNode object. This macro should be ** used as if it has the same signature as the xNext() methods themselves. */ #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d)) /* ** An instance of the following structure represents a single search term ** or term prefix. */ struct Fts5ExprTerm { int bPrefix; /* True for a prefix term */ char *zTerm; /* nul-terminated term */ Fts5IndexIter *pIter; /* Iterator for this term */ Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */ }; /* ** A phrase. One or more terms that must appear in a contiguous sequence ** within a document for it to match. */ struct Fts5ExprPhrase { Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */ Fts5Buffer poslist; /* Current position list */ int nTerm; /* Number of entries in aTerm[] */ Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */ }; /* ** One or more phrases that must appear within a certain token distance of ** each other within each matching document. */ struct Fts5ExprNearset { int nNear; /* NEAR parameter */ Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */ int nPhrase; /* Number of entries in aPhrase[] array */ Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */ }; /* ** Parse context. */ struct Fts5Parse { Fts5Config *pConfig; char *zErr; int rc; int nPhrase; /* Size of apPhrase array */ Fts5ExprPhrase **apPhrase; /* Array of all phrases */ Fts5ExprNode *pExpr; /* Result of a successful parse */ }; static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); if( pParse->rc==SQLITE_OK ){ pParse->zErr = sqlite3_vmprintf(zFmt, ap); pParse->rc = SQLITE_ERROR; } va_end(ap); } static int fts5ExprIsspace(char t){ return t==' ' || t=='\t' || t=='\n' || t=='\r'; } /* ** Read the first token from the nul-terminated string at *pz. */ static int fts5ExprGetToken( Fts5Parse *pParse, const char **pz, /* IN/OUT: Pointer into buffer */ Fts5Token *pToken ){ const char *z = *pz; int tok; /* Skip past any whitespace */ while( fts5ExprIsspace(*z) ) z++; pToken->p = z; pToken->n = 1; switch( *z ){ case '(': tok = FTS5_LP; break; case ')': tok = FTS5_RP; break; case '{': tok = FTS5_LCP; break; case '}': tok = FTS5_RCP; break; case ':': tok = FTS5_COLON; break; case ',': tok = FTS5_COMMA; break; case '+': tok = FTS5_PLUS; break; case '*': tok = FTS5_STAR; break; case '-': tok = FTS5_MINUS; break; case '\0': tok = FTS5_EOF; break; case '"': { const char *z2; tok = FTS5_STRING; for(z2=&z[1]; 1; z2++){ if( z2[0]=='"' ){ z2++; if( z2[0]!='"' ) break; } if( z2[0]=='\0' ){ sqlite3Fts5ParseError(pParse, "unterminated string"); return FTS5_EOF; } } pToken->n = (z2 - z); break; } default: { const char *z2; if( sqlite3Fts5IsBareword(z[0])==0 ){ sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z); return FTS5_EOF; } tok = FTS5_STRING; for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++); pToken->n = (z2 - z); if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR; if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT; if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND; break; } } *pz = &pToken->p[pToken->n]; return tok; } static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); } static void fts5ParseFree(void *p){ sqlite3_free(p); } static int sqlite3Fts5ExprNew( Fts5Config *pConfig, /* FTS5 Configuration */ const char *zExpr, /* Expression text */ Fts5Expr **ppNew, char **pzErr ){ Fts5Parse sParse; Fts5Token token; const char *z = zExpr; int t; /* Next token type */ void *pEngine; Fts5Expr *pNew; *ppNew = 0; *pzErr = 0; memset(&sParse, 0, sizeof(sParse)); pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc); if( pEngine==0 ){ return SQLITE_NOMEM; } sParse.pConfig = pConfig; do { t = fts5ExprGetToken(&sParse, &z, &token); sqlite3Fts5Parser(pEngine, t, token, &sParse); }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF ); sqlite3Fts5ParserFree(pEngine, fts5ParseFree); assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 ); if( sParse.rc==SQLITE_OK ){ *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr)); if( pNew==0 ){ sParse.rc = SQLITE_NOMEM; sqlite3Fts5ParseNodeFree(sParse.pExpr); }else{ if( !sParse.pExpr ){ const int nByte = sizeof(Fts5ExprNode); pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte); if( pNew->pRoot ){ pNew->pRoot->bEof = 1; } }else{ pNew->pRoot = sParse.pExpr; } pNew->pIndex = 0; pNew->pConfig = pConfig; pNew->apExprPhrase = sParse.apPhrase; pNew->nPhrase = sParse.nPhrase; sParse.apPhrase = 0; } }else{ sqlite3Fts5ParseNodeFree(sParse.pExpr); } sqlite3_free(sParse.apPhrase); *pzErr = sParse.zErr; return sParse.rc; } /* ** Free the expression node object passed as the only argument. */ static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){ if( p ){ int i; for(i=0; i<p->nChild; i++){ sqlite3Fts5ParseNodeFree(p->apChild[i]); } sqlite3Fts5ParseNearsetFree(p->pNear); sqlite3_free(p); } } /* ** Free the expression object passed as the only argument. */ static void sqlite3Fts5ExprFree(Fts5Expr *p){ if( p ){ sqlite3Fts5ParseNodeFree(p->pRoot); sqlite3_free(p->apExprPhrase); sqlite3_free(p); } } /* ** Argument pTerm must be a synonym iterator. Return the current rowid ** that it points to. */ static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){ i64 iRet = 0; int bRetValid = 0; Fts5ExprTerm *p; assert( pTerm->pSynonym ); assert( bDesc==0 || bDesc==1 ); for(p=pTerm; p; p=p->pSynonym){ if( 0==sqlite3Fts5IterEof(p->pIter) ){ i64 iRowid = p->pIter->iRowid; if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){ iRet = iRowid; bRetValid = 1; } } } if( pbEof && bRetValid==0 ) *pbEof = 1; return iRet; } /* ** Argument pTerm must be a synonym iterator. */ static int fts5ExprSynonymList( Fts5ExprTerm *pTerm, i64 iRowid, Fts5Buffer *pBuf, /* Use this buffer for space if required */ u8 **pa, int *pn ){ Fts5PoslistReader aStatic[4]; Fts5PoslistReader *aIter = aStatic; int nIter = 0; int nAlloc = 4; int rc = SQLITE_OK; Fts5ExprTerm *p; assert( pTerm->pSynonym ); for(p=pTerm; p; p=p->pSynonym){ Fts5IndexIter *pIter = p->pIter; if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){ if( pIter->nData==0 ) continue; if( nIter==nAlloc ){ int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2; Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte); if( aNew==0 ){ rc = SQLITE_NOMEM; goto synonym_poslist_out; } memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter); nAlloc = nAlloc*2; if( aIter!=aStatic ) sqlite3_free(aIter); aIter = aNew; } sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]); assert( aIter[nIter].bEof==0 ); nIter++; } } if( nIter==1 ){ *pa = (u8*)aIter[0].a; *pn = aIter[0].n; }else{ Fts5PoslistWriter writer = {0}; i64 iPrev = -1; fts5BufferZero(pBuf); while( 1 ){ int i; i64 iMin = FTS5_LARGEST_INT64; for(i=0; i<nIter; i++){ if( aIter[i].bEof==0 ){ if( aIter[i].iPos==iPrev ){ if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue; } if( aIter[i].iPos<iMin ){ iMin = aIter[i].iPos; } } } if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break; rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin); iPrev = iMin; } if( rc==SQLITE_OK ){ *pa = pBuf->p; *pn = pBuf->n; } } synonym_poslist_out: if( aIter!=aStatic ) sqlite3_free(aIter); return rc; } /* ** All individual term iterators in pPhrase are guaranteed to be valid and ** pointing to the same rowid when this function is called. This function ** checks if the current rowid really is a match, and if so populates ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch ** is set to true if this is really a match, or false otherwise. ** ** SQLITE_OK is returned if an error occurs, or an SQLite error code ** otherwise. It is not considered an error code if the current rowid is ** not a match. */ static int fts5ExprPhraseIsMatch( Fts5ExprNode *pNode, /* Node pPhrase belongs to */ Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */ int *pbMatch /* OUT: Set to true if really a match */ ){ Fts5PoslistWriter writer = {0}; Fts5PoslistReader aStatic[4]; Fts5PoslistReader *aIter = aStatic; int i; int rc = SQLITE_OK; fts5BufferZero(&pPhrase->poslist); /* If the aStatic[] array is not large enough, allocate a large array ** using sqlite3_malloc(). This approach could be improved upon. */ if( pPhrase->nTerm>ArraySize(aStatic) ){ int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm; aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte); if( !aIter ) return SQLITE_NOMEM; } memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm); /* Initialize a term iterator for each term in the phrase */ for(i=0; i<pPhrase->nTerm; i++){ Fts5ExprTerm *pTerm = &pPhrase->aTerm[i]; int n = 0; int bFlag = 0; u8 *a = 0; if( pTerm->pSynonym ){ Fts5Buffer buf = {0, 0, 0}; rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n); if( rc ){ sqlite3_free(a); goto ismatch_out; } if( a==buf.p ) bFlag = 1; }else{ a = (u8*)pTerm->pIter->pData; n = pTerm->pIter->nData; } sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]); aIter[i].bFlag = (u8)bFlag; if( aIter[i].bEof ) goto ismatch_out; } while( 1 ){ int bMatch; i64 iPos = aIter[0].iPos; do { bMatch = 1; for(i=0; i<pPhrase->nTerm; i++){ Fts5PoslistReader *pPos = &aIter[i]; i64 iAdj = iPos + i; if( pPos->iPos!=iAdj ){ bMatch = 0; while( pPos->iPos<iAdj ){ if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out; } if( pPos->iPos>iAdj ) iPos = pPos->iPos-i; } } }while( bMatch==0 ); /* Append position iPos to the output */ rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos); if( rc!=SQLITE_OK ) goto ismatch_out; for(i=0; i<pPhrase->nTerm; i++){ if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out; } } ismatch_out: *pbMatch = (pPhrase->poslist.n>0); for(i=0; i<pPhrase->nTerm; i++){ if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a); } if( aIter!=aStatic ) sqlite3_free(aIter); return rc; } typedef struct Fts5LookaheadReader Fts5LookaheadReader; struct Fts5LookaheadReader { const u8 *a; /* Buffer containing position list */ int n; /* Size of buffer a[] in bytes */ int i; /* Current offset in position list */ i64 iPos; /* Current position */ i64 iLookahead; /* Next position */ }; #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62) static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){ p->iPos = p->iLookahead; if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){ p->iLookahead = FTS5_LOOKAHEAD_EOF; } return (p->iPos==FTS5_LOOKAHEAD_EOF); } static int fts5LookaheadReaderInit( const u8 *a, int n, /* Buffer to read position list from */ Fts5LookaheadReader *p /* Iterator object to initialize */ ){ memset(p, 0, sizeof(Fts5LookaheadReader)); p->a = a; p->n = n; fts5LookaheadReaderNext(p); return fts5LookaheadReaderNext(p); } typedef struct Fts5NearTrimmer Fts5NearTrimmer; struct Fts5NearTrimmer { Fts5LookaheadReader reader; /* Input iterator */ Fts5PoslistWriter writer; /* Writer context */ Fts5Buffer *pOut; /* Output poslist */ }; /* ** The near-set object passed as the first argument contains more than ** one phrase. All phrases currently point to the same row. The ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function ** tests if the current row contains instances of each phrase sufficiently ** close together to meet the NEAR constraint. Non-zero is returned if it ** does, or zero otherwise. ** ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM) ** occurs within this function (*pRc) is set accordingly before returning. ** The return value is undefined in both these cases. ** ** If no error occurs and non-zero (a match) is returned, the position-list ** of each phrase object is edited to contain only those entries that ** meet the constraint before returning. */ static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){ Fts5NearTrimmer aStatic[4]; Fts5NearTrimmer *a = aStatic; Fts5ExprPhrase **apPhrase = pNear->apPhrase; int i; int rc = *pRc; int bMatch; assert( pNear->nPhrase>1 ); /* If the aStatic[] array is not large enough, allocate a large array ** using sqlite3_malloc(). This approach could be improved upon. */ if( pNear->nPhrase>ArraySize(aStatic) ){ int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase; a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte); }else{ memset(aStatic, 0, sizeof(aStatic)); } if( rc!=SQLITE_OK ){ *pRc = rc; return 0; } /* Initialize a lookahead iterator for each phrase. After passing the ** buffer and buffer size to the lookaside-reader init function, zero ** the phrase poslist buffer. The new poslist for the phrase (containing ** the same entries as the original with some entries removed on account ** of the NEAR constraint) is written over the original even as it is ** being read. This is safe as the entries for the new poslist are a ** subset of the old, so it is not possible for data yet to be read to ** be overwritten. */ for(i=0; i<pNear->nPhrase; i++){ Fts5Buffer *pPoslist = &apPhrase[i]->poslist; fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader); pPoslist->n = 0; a[i].pOut = pPoslist; } while( 1 ){ int iAdv; i64 iMin; i64 iMax; /* This block advances the phrase iterators until they point to a set of ** entries that together comprise a match. */ iMax = a[0].reader.iPos; do { bMatch = 1; for(i=0; i<pNear->nPhrase; i++){ Fts5LookaheadReader *pPos = &a[i].reader; iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear; if( pPos->iPos<iMin || pPos->iPos>iMax ){ bMatch = 0; while( pPos->iPos<iMin ){ if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out; } if( pPos->iPos>iMax ) iMax = pPos->iPos; } } }while( bMatch==0 ); /* Add an entry to each output position list */ for(i=0; i<pNear->nPhrase; i++){ i64 iPos = a[i].reader.iPos; Fts5PoslistWriter *pWriter = &a[i].writer; if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){ sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos); } } iAdv = 0; iMin = a[0].reader.iLookahead; for(i=0; i<pNear->nPhrase; i++){ if( a[i].reader.iLookahead < iMin ){ iMin = a[i].reader.iLookahead; iAdv = i; } } if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out; } ismatch_out: { int bRet = a[0].pOut->n>0; *pRc = rc; if( a!=aStatic ) sqlite3_free(a); return bRet; } } /* ** Advance iterator pIter until it points to a value equal to or laster ** than the initial value of *piLast. If this means the iterator points ** to a value laster than *piLast, update *piLast to the new lastest value. ** ** If the iterator reaches EOF, set *pbEof to true before returning. If ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc ** are set, return a non-zero value. Otherwise, return zero. */ static int fts5ExprAdvanceto( Fts5IndexIter *pIter, /* Iterator to advance */ int bDesc, /* True if iterator is "rowid DESC" */ i64 *piLast, /* IN/OUT: Lastest rowid seen so far */ int *pRc, /* OUT: Error code */ int *pbEof /* OUT: Set to true if EOF */ ){ i64 iLast = *piLast; i64 iRowid; iRowid = pIter->iRowid; if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){ int rc = sqlite3Fts5IterNextFrom(pIter, iLast); if( rc || sqlite3Fts5IterEof(pIter) ){ *pRc = rc; *pbEof = 1; return 1; } iRowid = pIter->iRowid; assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) ); } *piLast = iRowid; return 0; } static int fts5ExprSynonymAdvanceto( Fts5ExprTerm *pTerm, /* Term iterator to advance */ int bDesc, /* True if iterator is "rowid DESC" */ i64 *piLast, /* IN/OUT: Lastest rowid seen so far */ int *pRc /* OUT: Error code */ ){ int rc = SQLITE_OK; i64 iLast = *piLast; Fts5ExprTerm *p; int bEof = 0; for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){ if( sqlite3Fts5IterEof(p->pIter)==0 ){ i64 iRowid = p->pIter->iRowid; if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){ rc = sqlite3Fts5IterNextFrom(p->pIter, iLast); } } } if( rc!=SQLITE_OK ){ *pRc = rc; bEof = 1; }else{ *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof); } return bEof; } static int fts5ExprNearTest( int *pRc, Fts5Expr *pExpr, /* Expression that pNear is a part of */ Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */ ){ Fts5ExprNearset *pNear = pNode->pNear; int rc = *pRc; if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){ Fts5ExprTerm *pTerm; Fts5ExprPhrase *pPhrase = pNear->apPhrase[0]; pPhrase->poslist.n = 0; for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){ Fts5IndexIter *pIter = pTerm->pIter; if( sqlite3Fts5IterEof(pIter)==0 ){ if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){ pPhrase->poslist.n = 1; } } } return pPhrase->poslist.n; }else{ int i; /* Check that each phrase in the nearset matches the current row. ** Populate the pPhrase->poslist buffers at the same time. If any ** phrase is not a match, break out of the loop early. */ for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i]; if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){ int bMatch = 0; rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch); if( bMatch==0 ) break; }else{ Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter; fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData); } } *pRc = rc; if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){ return 1; } return 0; } } /* ** Initialize all term iterators in the pNear object. If any term is found ** to match no documents at all, return immediately without initializing any ** further iterators. ** ** If an error occurs, return an SQLite error code. Otherwise, return ** SQLITE_OK. It is not considered an error if some term matches zero ** documents. */ static int fts5ExprNearInitAll( Fts5Expr *pExpr, Fts5ExprNode *pNode ){ Fts5ExprNearset *pNear = pNode->pNear; int i; assert( pNode->bNomatch==0 ); for(i=0; i<pNear->nPhrase; i++){ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i]; if( pPhrase->nTerm==0 ){ pNode->bEof = 1; return SQLITE_OK; }else{ int j; for(j=0; j<pPhrase->nTerm; j++){ Fts5ExprTerm *pTerm = &pPhrase->aTerm[j]; Fts5ExprTerm *p; int bHit = 0; for(p=pTerm; p; p=p->pSynonym){ int rc; if( p->pIter ){ sqlite3Fts5IterClose(p->pIter); p->pIter = 0; } rc = sqlite3Fts5IndexQuery( pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm), (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) | (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0), pNear->pColset, &p->pIter ); assert( (rc==SQLITE_OK)==(p->pIter!=0) ); if( rc!=SQLITE_OK ) return rc; if( 0==sqlite3Fts5IterEof(p->pIter) ){ bHit = 1; } } if( bHit==0 ){ pNode->bEof = 1; return SQLITE_OK; } } } } pNode->bEof = 0; return SQLITE_OK; } /* ** If pExpr is an ASC iterator, this function returns a value with the ** same sign as: ** ** (iLhs - iRhs) ** ** Otherwise, if this is a DESC iterator, the opposite is returned: ** ** (iRhs - iLhs) */ static int fts5RowidCmp( Fts5Expr *pExpr, i64 iLhs, i64 iRhs ){ assert( pExpr->bDesc==0 || pExpr->bDesc==1 ); if( pExpr->bDesc==0 ){ if( iLhs<iRhs ) return -1; return (iLhs > iRhs); }else{ if( iLhs>iRhs ) return -1; return (iLhs < iRhs); } } static void fts5ExprSetEof(Fts5ExprNode *pNode){ int i; pNode->bEof = 1; pNode->bNomatch = 0; for(i=0; i<pNode->nChild; i++){ fts5ExprSetEof(pNode->apChild[i]); } } static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){ if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){ Fts5ExprNearset *pNear = pNode->pNear; int i; for(i=0; i<pNear->nPhrase; i++){ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i]; pPhrase->poslist.n = 0; } }else{ int i; for(i=0; i<pNode->nChild; i++){ fts5ExprNodeZeroPoslist(pNode->apChild[i]); } } } /* ** Compare the values currently indicated by the two nodes as follows: ** ** res = (*p1) - (*p2) ** ** Nodes that point to values that come later in the iteration order are ** considered to be larger. Nodes at EOF are the largest of all. ** ** This means that if the iteration order is ASC, then numerically larger ** rowids are considered larger. Or if it is the default DESC, numerically ** smaller rowids are larger. */ static int fts5NodeCompare( Fts5Expr *pExpr, Fts5ExprNode *p1, Fts5ExprNode *p2 ){ if( p2->bEof ) return -1; if( p1->bEof ) return +1; return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid); } /* ** All individual term iterators in pNear are guaranteed to be valid when ** this function is called. This function checks if all term iterators ** point to the same rowid, and if not, advances them until they do. ** If an EOF is reached before this happens, *pbEof is set to true before ** returning. ** ** SQLITE_OK is returned if an error occurs, or an SQLite error code ** otherwise. It is not considered an error code if an iterator reaches ** EOF. */ static int fts5ExprNodeTest_STRING( Fts5Expr *pExpr, /* Expression pPhrase belongs to */ Fts5ExprNode *pNode ){ Fts5ExprNearset *pNear = pNode->pNear; Fts5ExprPhrase *pLeft = pNear->apPhrase[0]; int rc = SQLITE_OK; i64 iLast; /* Lastest rowid any iterator points to */ int i, j; /* Phrase and token index, respectively */ int bMatch; /* True if all terms are at the same rowid */ const int bDesc = pExpr->bDesc; /* Check that this node should not be FTS5_TERM */ assert( pNear->nPhrase>1 || pNear->apPhrase[0]->nTerm>1 || pNear->apPhrase[0]->aTerm[0].pSynonym ); /* Initialize iLast, the "lastest" rowid any iterator points to. If the ** iterator skips through rowids in the default ascending order, this means ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it ** means the minimum rowid. */ if( pLeft->aTerm[0].pSynonym ){ iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0); }else{ iLast = pLeft->aTerm[0].pIter->iRowid; } do { bMatch = 1; for(i=0; i<pNear->nPhrase; i++){ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i]; for(j=0; j<pPhrase->nTerm; j++){ Fts5ExprTerm *pTerm = &pPhrase->aTerm[j]; if( pTerm->pSynonym ){ i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0); if( iRowid==iLast ) continue; bMatch = 0; if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){ pNode->bNomatch = 0; pNode->bEof = 1; return rc; } }else{ Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter; if( pIter->iRowid==iLast || pIter->bEof ) continue; bMatch = 0; if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){ return rc; } } } } }while( bMatch==0 ); pNode->iRowid = iLast; pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK); assert( pNode->bEof==0 || pNode->bNomatch==0 ); return rc; } /* ** Advance the first term iterator in the first phrase of pNear. Set output ** variable *pbEof to true if it reaches EOF or if an error occurs. ** ** Return SQLITE_OK if successful, or an SQLite error code if an error ** occurs. */ static int fts5ExprNodeNext_STRING( Fts5Expr *pExpr, /* Expression pPhrase belongs to */ Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */ int bFromValid, i64 iFrom ){ Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0]; int rc = SQLITE_OK; pNode->bNomatch = 0; if( pTerm->pSynonym ){ int bEof = 1; Fts5ExprTerm *p; /* Find the firstest rowid any synonym points to. */ i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0); /* Advance each iterator that currently points to iRowid. Or, if iFrom ** is valid - each iterator that points to a rowid before iFrom. */ for(p=pTerm; p; p=p->pSynonym){ if( sqlite3Fts5IterEof(p->pIter)==0 ){ i64 ii = p->pIter->iRowid; if( ii==iRowid || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc) ){ if( bFromValid ){ rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom); }else{ rc = sqlite3Fts5IterNext(p->pIter); } if( rc!=SQLITE_OK ) break; if( sqlite3Fts5IterEof(p->pIter)==0 ){ bEof = 0; } }else{ bEof = 0; } } } /* Set the EOF flag if either all synonym iterators are at EOF or an ** error has occurred. */ pNode->bEof = (rc || bEof); }else{ Fts5IndexIter *pIter = pTerm->pIter; assert( Fts5NodeIsString(pNode) ); if( bFromValid ){ rc = sqlite3Fts5IterNextFrom(pIter, iFrom); }else{ rc = sqlite3Fts5IterNext(pIter); } pNode->bEof = (rc || sqlite3Fts5IterEof(pIter)); } if( pNode->bEof==0 ){ assert( rc==SQLITE_OK ); rc = fts5ExprNodeTest_STRING(pExpr, pNode); } return rc; } static int fts5ExprNodeTest_TERM( Fts5Expr *pExpr, /* Expression that pNear is a part of */ Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */ ){ /* As this "NEAR" object is actually a single phrase that consists ** of a single term only, grab pointers into the poslist managed by the ** fts5_index.c iterator object. This is much faster than synthesizing ** a new poslist the way we have to for more complicated phrase or NEAR ** expressions. */ Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0]; Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter; assert( pNode->eType==FTS5_TERM ); assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 ); assert( pPhrase->aTerm[0].pSynonym==0 ); pPhrase->poslist.n = pIter->nData; if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){ pPhrase->poslist.p = (u8*)pIter->pData; } pNode->iRowid = pIter->iRowid; pNode->bNomatch = (pPhrase->poslist.n==0); return SQLITE_OK; } /* ** xNext() method for a node of type FTS5_TERM. */ static int fts5ExprNodeNext_TERM( Fts5Expr *pExpr, Fts5ExprNode *pNode, int bFromValid, i64 iFrom ){ int rc; Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter; assert( pNode->bEof==0 ); if( bFromValid ){ rc = sqlite3Fts5IterNextFrom(pIter, iFrom); }else{ rc = sqlite3Fts5IterNext(pIter); } if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){ rc = fts5ExprNodeTest_TERM(pExpr, pNode); }else{ pNode->bEof = 1; pNode->bNomatch = 0; } return rc; } static void fts5ExprNodeTest_OR( Fts5Expr *pExpr, /* Expression of which pNode is a part */ Fts5ExprNode *pNode /* Expression node to test */ ){ Fts5ExprNode *pNext = pNode->apChild[0]; int i; for(i=1; i<pNode->nChild; i++){ Fts5ExprNode *pChild = pNode->apChild[i]; int cmp = fts5NodeCompare(pExpr, pNext, pChild); if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){ pNext = pChild; } } pNode->iRowid = pNext->iRowid; pNode->bEof = pNext->bEof; pNode->bNomatch = pNext->bNomatch; } static int fts5ExprNodeNext_OR( Fts5Expr *pExpr, Fts5ExprNode *pNode, int bFromValid, i64 iFrom ){ int i; i64 iLast = pNode->iRowid; for(i=0; i<pNode->nChild; i++){ Fts5ExprNode *p1 = pNode->apChild[i]; assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 ); if( p1->bEof==0 ){ if( (p1->iRowid==iLast) || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0) ){ int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom); if( rc!=SQLITE_OK ) return rc; } } } fts5ExprNodeTest_OR(pExpr, pNode); return SQLITE_OK; } /* ** Argument pNode is an FTS5_AND node. */ static int fts5ExprNodeTest_AND( Fts5Expr *pExpr, /* Expression pPhrase belongs to */ Fts5ExprNode *pAnd /* FTS5_AND node to advance */ ){ int iChild; i64 iLast = pAnd->iRowid; int rc = SQLITE_OK; int bMatch; assert( pAnd->bEof==0 ); do { pAnd->bNomatch = 0; bMatch = 1; for(iChild=0; iChild<pAnd->nChild; iChild++){ Fts5ExprNode *pChild = pAnd->apChild[iChild]; int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid); if( cmp>0 ){ /* Advance pChild until it points to iLast or laster */ rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast); if( rc!=SQLITE_OK ) return rc; } /* If the child node is now at EOF, so is the parent AND node. Otherwise, ** the child node is guaranteed to have advanced at least as far as ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the ** new lastest rowid seen so far. */ assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 ); if( pChild->bEof ){ fts5ExprSetEof(pAnd); bMatch = 1; break; }else if( iLast!=pChild->iRowid ){ bMatch = 0; iLast = pChild->iRowid; } if( pChild->bNomatch ){ pAnd->bNomatch = 1; } } }while( bMatch==0 ); if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){ fts5ExprNodeZeroPoslist(pAnd); } pAnd->iRowid = iLast; return SQLITE_OK; } static int fts5ExprNodeNext_AND( Fts5Expr *pExpr, Fts5ExprNode *pNode, int bFromValid, i64 iFrom ){ int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom); if( rc==SQLITE_OK ){ rc = fts5ExprNodeTest_AND(pExpr, pNode); } return rc; } static int fts5ExprNodeTest_NOT( Fts5Expr *pExpr, /* Expression pPhrase belongs to */ Fts5ExprNode *pNode /* FTS5_NOT node to advance */ ){ int rc = SQLITE_OK; Fts5ExprNode *p1 = pNode->apChild[0]; Fts5ExprNode *p2 = pNode->apChild[1]; assert( pNode->nChild==2 ); while( rc==SQLITE_OK && p1->bEof==0 ){ int cmp = fts5NodeCompare(pExpr, p1, p2); if( cmp>0 ){ rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid); cmp = fts5NodeCompare(pExpr, p1, p2); } assert( rc!=SQLITE_OK || cmp<=0 ); if( cmp || p2->bNomatch ) break; rc = fts5ExprNodeNext(pExpr, p1, 0, 0); } pNode->bEof = p1->bEof; pNode->bNomatch = p1->bNomatch; pNode->iRowid = p1->iRowid; if( p1->bEof ){ fts5ExprNodeZeroPoslist(p2); } return rc; } static int fts5ExprNodeNext_NOT( Fts5Expr *pExpr, Fts5ExprNode *pNode, int bFromValid, i64 iFrom ){ int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom); if( rc==SQLITE_OK ){ rc = fts5ExprNodeTest_NOT(pExpr, pNode); } return rc; } /* ** If pNode currently points to a match, this function returns SQLITE_OK ** without modifying it. Otherwise, pNode is advanced until it does point ** to a match or EOF is reached. */ static int fts5ExprNodeTest( Fts5Expr *pExpr, /* Expression of which pNode is a part */ Fts5ExprNode *pNode /* Expression node to test */ ){ int rc = SQLITE_OK; if( pNode->bEof==0 ){ switch( pNode->eType ){ case FTS5_STRING: { rc = fts5ExprNodeTest_STRING(pExpr, pNode); break; } case FTS5_TERM: { rc = fts5ExprNodeTest_TERM(pExpr, pNode); break; } case FTS5_AND: { rc = fts5ExprNodeTest_AND(pExpr, pNode); break; } case FTS5_OR: { fts5ExprNodeTest_OR(pExpr, pNode); break; } default: assert( pNode->eType==FTS5_NOT ); { rc = fts5ExprNodeTest_NOT(pExpr, pNode); break; } } } return rc; } /* ** Set node pNode, which is part of expression pExpr, to point to the first ** match. If there are no matches, set the Node.bEof flag to indicate EOF. ** ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise. ** It is not an error if there are no matches. */ static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){ int rc = SQLITE_OK; pNode->bEof = 0; pNode->bNomatch = 0; if( Fts5NodeIsString(pNode) ){ /* Initialize all term iterators in the NEAR object. */ rc = fts5ExprNearInitAll(pExpr, pNode); }else if( pNode->xNext==0 ){ pNode->bEof = 1; }else{ int i; int nEof = 0; for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){ Fts5ExprNode *pChild = pNode->apChild[i]; rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]); assert( pChild->bEof==0 || pChild->bEof==1 ); nEof += pChild->bEof; } pNode->iRowid = pNode->apChild[0]->iRowid; switch( pNode->eType ){ case FTS5_AND: if( nEof>0 ) fts5ExprSetEof(pNode); break; case FTS5_OR: if( pNode->nChild==nEof ) fts5ExprSetEof(pNode); break; default: assert( pNode->eType==FTS5_NOT ); pNode->bEof = pNode->apChild[0]->bEof; break; } } if( rc==SQLITE_OK ){ rc = fts5ExprNodeTest(pExpr, pNode); } return rc; } /* ** Begin iterating through the set of documents in index pIdx matched by ** the MATCH expression passed as the first argument. If the "bDesc" ** parameter is passed a non-zero value, iteration is in descending rowid ** order. Or, if it is zero, in ascending order. ** ** If iterating in ascending rowid order (bDesc==0), the first document ** visited is that with the smallest rowid that is larger than or equal ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1), ** then the first document visited must have a rowid smaller than or ** equal to iFirst. ** ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It ** is not considered an error if the query does not match any documents. */ static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){ Fts5ExprNode *pRoot = p->pRoot; int rc; /* Return code */ p->pIndex = pIdx; p->bDesc = bDesc; rc = fts5ExprNodeFirst(p, pRoot); /* If not at EOF but the current rowid occurs earlier than iFirst in ** the iteration order, move to document iFirst or later. */ if( rc==SQLITE_OK && 0==pRoot->bEof && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){ rc = fts5ExprNodeNext(p, pRoot, 1, iFirst); } /* If the iterator is not at a real match, skip forward until it is. */ while( pRoot->bNomatch ){ assert( pRoot->bEof==0 && rc==SQLITE_OK ); rc = fts5ExprNodeNext(p, pRoot, 0, 0); } return rc; } /* ** Move to the next document ** ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It ** is not considered an error if the query does not match any documents. */ static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){ int rc; Fts5ExprNode *pRoot = p->pRoot; assert( pRoot->bEof==0 && pRoot->bNomatch==0 ); do { rc = fts5ExprNodeNext(p, pRoot, 0, 0); assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) ); }while( pRoot->bNomatch ); if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){ pRoot->bEof = 1; } return rc; } static int sqlite3Fts5ExprEof(Fts5Expr *p){ return p->pRoot->bEof; } static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){ return p->pRoot->iRowid; } static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){ int rc = SQLITE_OK; *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n); return rc; } /* ** Free the phrase object passed as the only argument. */ static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){ if( pPhrase ){ int i; for(i=0; i<pPhrase->nTerm; i++){ Fts5ExprTerm *pSyn; Fts5ExprTerm *pNext; Fts5ExprTerm *pTerm = &pPhrase->aTerm[i]; sqlite3_free(pTerm->zTerm); sqlite3Fts5IterClose(pTerm->pIter); for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){ pNext = pSyn->pSynonym; sqlite3Fts5IterClose(pSyn->pIter); fts5BufferFree((Fts5Buffer*)&pSyn[1]); sqlite3_free(pSyn); } } if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist); sqlite3_free(pPhrase); } } /* ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is ** appended to it and the results returned. ** ** If an OOM error occurs, both the pNear and pPhrase objects are freed and ** NULL returned. */ static Fts5ExprNearset *sqlite3Fts5ParseNearset( Fts5Parse *pParse, /* Parse context */ Fts5ExprNearset *pNear, /* Existing nearset, or NULL */ Fts5ExprPhrase *pPhrase /* Recently parsed phrase */ ){ const int SZALLOC = 8; Fts5ExprNearset *pRet = 0; if( pParse->rc==SQLITE_OK ){ if( pPhrase==0 ){ return pNear; } if( pNear==0 ){ int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*); pRet = sqlite3_malloc(nByte); if( pRet==0 ){ pParse->rc = SQLITE_NOMEM; }else{ memset(pRet, 0, nByte); } }else if( (pNear->nPhrase % SZALLOC)==0 ){ int nNew = pNear->nPhrase + SZALLOC; int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*); pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte); if( pRet==0 ){ pParse->rc = SQLITE_NOMEM; } }else{ pRet = pNear; } } if( pRet==0 ){ assert( pParse->rc!=SQLITE_OK ); sqlite3Fts5ParseNearsetFree(pNear); sqlite3Fts5ParsePhraseFree(pPhrase); }else{ if( pRet->nPhrase>0 ){ Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1]; assert( pLast==pParse->apPhrase[pParse->nPhrase-2] ); if( pPhrase->nTerm==0 ){ fts5ExprPhraseFree(pPhrase); pRet->nPhrase--; pParse->nPhrase--; pPhrase = pLast; }else if( pLast->nTerm==0 ){ fts5ExprPhraseFree(pLast); pParse->apPhrase[pParse->nPhrase-2] = pPhrase; pParse->nPhrase--; pRet->nPhrase--; } } pRet->apPhrase[pRet->nPhrase++] = pPhrase; } return pRet; } typedef struct TokenCtx TokenCtx; struct TokenCtx { Fts5ExprPhrase *pPhrase; int rc; }; /* ** Callback for tokenizing terms used by ParseTerm(). */ static int fts5ParseTokenize( void *pContext, /* Pointer to Fts5InsertCtx object */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Buffer containing token */ int nToken, /* Size of token in bytes */ int iUnused1, /* Start offset of token */ int iUnused2 /* End offset of token */ ){ int rc = SQLITE_OK; const int SZALLOC = 8; TokenCtx *pCtx = (TokenCtx*)pContext; Fts5ExprPhrase *pPhrase = pCtx->pPhrase; UNUSED_PARAM2(iUnused1, iUnused2); /* If an error has already occurred, this is a no-op */ if( pCtx->rc!=SQLITE_OK ) return pCtx->rc; if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE; if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){ Fts5ExprTerm *pSyn; int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1; pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte); if( pSyn==0 ){ rc = SQLITE_NOMEM; }else{ memset(pSyn, 0, nByte); pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer); memcpy(pSyn->zTerm, pToken, nToken); pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym; pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn; } }else{ Fts5ExprTerm *pTerm; if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){ Fts5ExprPhrase *pNew; int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0); pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase, sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew ); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase)); pCtx->pPhrase = pPhrase = pNew; pNew->nTerm = nNew - SZALLOC; } } if( rc==SQLITE_OK ){ pTerm = &pPhrase->aTerm[pPhrase->nTerm++]; memset(pTerm, 0, sizeof(Fts5ExprTerm)); pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken); } } pCtx->rc = rc; return rc; } /* ** Free the phrase object passed as the only argument. */ static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){ fts5ExprPhraseFree(pPhrase); } /* ** Free the phrase object passed as the second argument. */ static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){ if( pNear ){ int i; for(i=0; i<pNear->nPhrase; i++){ fts5ExprPhraseFree(pNear->apPhrase[i]); } sqlite3_free(pNear->pColset); sqlite3_free(pNear); } } static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){ assert( pParse->pExpr==0 ); pParse->pExpr = p; } /* ** This function is called by the parser to process a string token. The ** string may or may not be quoted. In any case it is tokenized and a ** phrase object consisting of all tokens returned. */ static Fts5ExprPhrase *sqlite3Fts5ParseTerm( Fts5Parse *pParse, /* Parse context */ Fts5ExprPhrase *pAppend, /* Phrase to append to */ Fts5Token *pToken, /* String to tokenize */ int bPrefix /* True if there is a trailing "*" */ ){ Fts5Config *pConfig = pParse->pConfig; TokenCtx sCtx; /* Context object passed to callback */ int rc; /* Tokenize return code */ char *z = 0; memset(&sCtx, 0, sizeof(TokenCtx)); sCtx.pPhrase = pAppend; rc = fts5ParseStringFromToken(pToken, &z); if( rc==SQLITE_OK ){ int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0); int n; sqlite3Fts5Dequote(z); n = (int)strlen(z); rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize); } sqlite3_free(z); if( rc || (rc = sCtx.rc) ){ pParse->rc = rc; fts5ExprPhraseFree(sCtx.pPhrase); sCtx.pPhrase = 0; }else{ if( pAppend==0 ){ if( (pParse->nPhrase % 8)==0 ){ int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8); Fts5ExprPhrase **apNew; apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte); if( apNew==0 ){ pParse->rc = SQLITE_NOMEM; fts5ExprPhraseFree(sCtx.pPhrase); return 0; } pParse->apPhrase = apNew; } pParse->nPhrase++; } if( sCtx.pPhrase==0 ){ /* This happens when parsing a token or quoted phrase that contains ** no token characters at all. (e.g ... MATCH '""'). */ sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase)); }else if( sCtx.pPhrase->nTerm ){ sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix; } pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase; } return sCtx.pPhrase; } /* ** Create a new FTS5 expression by cloning phrase iPhrase of the ** expression passed as the second argument. */ static int sqlite3Fts5ExprClonePhrase( Fts5Expr *pExpr, int iPhrase, Fts5Expr **ppNew ){ int rc = SQLITE_OK; /* Return code */ Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */ Fts5Expr *pNew = 0; /* Expression to return via *ppNew */ TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */ pOrig = pExpr->apExprPhrase[iPhrase]; pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr)); if( rc==SQLITE_OK ){ pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase*)); } if( rc==SQLITE_OK ){ pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprNode)); } if( rc==SQLITE_OK ){ pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*)); } if( rc==SQLITE_OK ){ Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset; if( pColsetOrig ){ int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int); Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte); if( pColset ){ memcpy(pColset, pColsetOrig, nByte); } pNew->pRoot->pNear->pColset = pColset; } } if( pOrig->nTerm ){ int i; /* Used to iterate through phrase terms */ for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){ int tflags = 0; Fts5ExprTerm *p; for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){ const char *zTerm = p->zTerm; rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm), 0, 0); tflags = FTS5_TOKEN_COLOCATED; } if( rc==SQLITE_OK ){ sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix; } } }else{ /* This happens when parsing a token or quoted phrase that contains ** no token characters at all. (e.g ... MATCH '""'). */ sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase)); } if( rc==SQLITE_OK ){ /* All the allocations succeeded. Put the expression object together. */ pNew->pIndex = pExpr->pIndex; pNew->pConfig = pExpr->pConfig; pNew->nPhrase = 1; pNew->apExprPhrase[0] = sCtx.pPhrase; pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase; pNew->pRoot->pNear->nPhrase = 1; sCtx.pPhrase->pNode = pNew->pRoot; if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){ pNew->pRoot->eType = FTS5_TERM; pNew->pRoot->xNext = fts5ExprNodeNext_TERM; }else{ pNew->pRoot->eType = FTS5_STRING; pNew->pRoot->xNext = fts5ExprNodeNext_STRING; } }else{ sqlite3Fts5ExprFree(pNew); fts5ExprPhraseFree(sCtx.pPhrase); pNew = 0; } *ppNew = pNew; return rc; } /* ** Token pTok has appeared in a MATCH expression where the NEAR operator ** is expected. If token pTok does not contain "NEAR", store an error ** in the pParse object. */ static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){ if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){ sqlite3Fts5ParseError( pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p ); } } static void sqlite3Fts5ParseSetDistance( Fts5Parse *pParse, Fts5ExprNearset *pNear, Fts5Token *p ){ if( pNear ){ int nNear = 0; int i; if( p->n ){ for(i=0; i<p->n; i++){ char c = (char)p->p[i]; if( c<'0' || c>'9' ){ sqlite3Fts5ParseError( pParse, "expected integer, got \"%.*s\"", p->n, p->p ); return; } nNear = nNear * 10 + (p->p[i] - '0'); } }else{ nNear = FTS5_DEFAULT_NEARDIST; } pNear->nNear = nNear; } } /* ** The second argument passed to this function may be NULL, or it may be ** an existing Fts5Colset object. This function returns a pointer to ** a new colset object containing the contents of (p) with new value column ** number iCol appended. ** ** If an OOM error occurs, store an error code in pParse and return NULL. ** The old colset object (if any) is not freed in this case. */ static Fts5Colset *fts5ParseColset( Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */ Fts5Colset *p, /* Existing colset object */ int iCol /* New column to add to colset object */ ){ int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */ Fts5Colset *pNew; /* New colset object to return */ assert( pParse->rc==SQLITE_OK ); assert( iCol>=0 && iCol<pParse->pConfig->nCol ); pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol); if( pNew==0 ){ pParse->rc = SQLITE_NOMEM; }else{ int *aiCol = pNew->aiCol; int i, j; for(i=0; i<nCol; i++){ if( aiCol[i]==iCol ) return pNew; if( aiCol[i]>iCol ) break; } for(j=nCol; j>i; j--){ aiCol[j] = aiCol[j-1]; } aiCol[i] = iCol; pNew->nCol = nCol+1; #ifndef NDEBUG /* Check that the array is in order and contains no duplicate entries. */ for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] ); #endif } return pNew; } /* ** Allocate and return an Fts5Colset object specifying the inverse of ** the colset passed as the second argument. Free the colset passed ** as the second argument before returning. */ static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){ Fts5Colset *pRet; int nCol = pParse->pConfig->nCol; pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5Colset) + sizeof(int)*nCol ); if( pRet ){ int i; int iOld = 0; for(i=0; i<nCol; i++){ if( iOld>=p->nCol || p->aiCol[iOld]!=i ){ pRet->aiCol[pRet->nCol++] = i; }else{ iOld++; } } } sqlite3_free(p); return pRet; } static Fts5Colset *sqlite3Fts5ParseColset( Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */ Fts5Colset *pColset, /* Existing colset object */ Fts5Token *p ){ Fts5Colset *pRet = 0; int iCol; char *z; /* Dequoted copy of token p */ z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n); if( pParse->rc==SQLITE_OK ){ Fts5Config *pConfig = pParse->pConfig; sqlite3Fts5Dequote(z); for(iCol=0; iCol<pConfig->nCol; iCol++){ if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break; } if( iCol==pConfig->nCol ){ sqlite3Fts5ParseError(pParse, "no such column: %s", z); }else{ pRet = fts5ParseColset(pParse, pColset, iCol); } sqlite3_free(z); } if( pRet==0 ){ assert( pParse->rc!=SQLITE_OK ); sqlite3_free(pColset); } return pRet; } static void sqlite3Fts5ParseSetColset( Fts5Parse *pParse, Fts5ExprNearset *pNear, Fts5Colset *pColset ){ if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){ pParse->rc = SQLITE_ERROR; pParse->zErr = sqlite3_mprintf( "fts5: column queries are not supported (detail=none)" ); sqlite3_free(pColset); return; } if( pNear ){ pNear->pColset = pColset; }else{ sqlite3_free(pColset); } } static void fts5ExprAssignXNext(Fts5ExprNode *pNode){ switch( pNode->eType ){ case FTS5_STRING: { Fts5ExprNearset *pNear = pNode->pNear; if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1 && pNear->apPhrase[0]->aTerm[0].pSynonym==0 ){ pNode->eType = FTS5_TERM; pNode->xNext = fts5ExprNodeNext_TERM; }else{ pNode->xNext = fts5ExprNodeNext_STRING; } break; }; case FTS5_OR: { pNode->xNext = fts5ExprNodeNext_OR; break; }; case FTS5_AND: { pNode->xNext = fts5ExprNodeNext_AND; break; }; default: assert( pNode->eType==FTS5_NOT ); { pNode->xNext = fts5ExprNodeNext_NOT; break; }; } } static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){ if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){ int nByte = sizeof(Fts5ExprNode*) * pSub->nChild; memcpy(&p->apChild[p->nChild], pSub->apChild, nByte); p->nChild += pSub->nChild; sqlite3_free(pSub); }else{ p->apChild[p->nChild++] = pSub; } } /* ** Allocate and return a new expression object. If anything goes wrong (i.e. ** OOM error), leave an error code in pParse and return NULL. */ static Fts5ExprNode *sqlite3Fts5ParseNode( Fts5Parse *pParse, /* Parse context */ int eType, /* FTS5_STRING, AND, OR or NOT */ Fts5ExprNode *pLeft, /* Left hand child expression */ Fts5ExprNode *pRight, /* Right hand child expression */ Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */ ){ Fts5ExprNode *pRet = 0; if( pParse->rc==SQLITE_OK ){ int nChild = 0; /* Number of children of returned node */ int nByte; /* Bytes of space to allocate for this node */ assert( (eType!=FTS5_STRING && !pNear) || (eType==FTS5_STRING && !pLeft && !pRight) ); if( eType==FTS5_STRING && pNear==0 ) return 0; if( eType!=FTS5_STRING && pLeft==0 ) return pRight; if( eType!=FTS5_STRING && pRight==0 ) return pLeft; if( eType==FTS5_NOT ){ nChild = 2; }else if( eType==FTS5_AND || eType==FTS5_OR ){ nChild = 2; if( pLeft->eType==eType ) nChild += pLeft->nChild-1; if( pRight->eType==eType ) nChild += pRight->nChild-1; } nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1); pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte); if( pRet ){ pRet->eType = eType; pRet->pNear = pNear; fts5ExprAssignXNext(pRet); if( eType==FTS5_STRING ){ int iPhrase; for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){ pNear->apPhrase[iPhrase]->pNode = pRet; if( pNear->apPhrase[iPhrase]->nTerm==0 ){ pRet->xNext = 0; pRet->eType = FTS5_EOF; } } if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1) ){ assert( pParse->rc==SQLITE_OK ); pParse->rc = SQLITE_ERROR; assert( pParse->zErr==0 ); pParse->zErr = sqlite3_mprintf( "fts5: %s queries are not supported (detail!=full)", pNear->nPhrase==1 ? "phrase": "NEAR" ); sqlite3_free(pRet); pRet = 0; } }else{ fts5ExprAddChildren(pRet, pLeft); fts5ExprAddChildren(pRet, pRight); } } } if( pRet==0 ){ assert( pParse->rc!=SQLITE_OK ); sqlite3Fts5ParseNodeFree(pLeft); sqlite3Fts5ParseNodeFree(pRight); sqlite3Fts5ParseNearsetFree(pNear); } return pRet; } static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( Fts5Parse *pParse, /* Parse context */ Fts5ExprNode *pLeft, /* Left hand child expression */ Fts5ExprNode *pRight /* Right hand child expression */ ){ Fts5ExprNode *pRet = 0; Fts5ExprNode *pPrev; if( pParse->rc ){ sqlite3Fts5ParseNodeFree(pLeft); sqlite3Fts5ParseNodeFree(pRight); }else{ assert( pLeft->eType==FTS5_STRING || pLeft->eType==FTS5_TERM || pLeft->eType==FTS5_EOF || pLeft->eType==FTS5_AND ); assert( pRight->eType==FTS5_STRING || pRight->eType==FTS5_TERM || pRight->eType==FTS5_EOF ); if( pLeft->eType==FTS5_AND ){ pPrev = pLeft->apChild[pLeft->nChild-1]; }else{ pPrev = pLeft; } assert( pPrev->eType==FTS5_STRING || pPrev->eType==FTS5_TERM || pPrev->eType==FTS5_EOF ); if( pRight->eType==FTS5_EOF ){ assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] ); sqlite3Fts5ParseNodeFree(pRight); pRet = pLeft; pParse->nPhrase--; } else if( pPrev->eType==FTS5_EOF ){ Fts5ExprPhrase **ap; if( pPrev==pLeft ){ pRet = pRight; }else{ pLeft->apChild[pLeft->nChild-1] = pRight; pRet = pLeft; } ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase]; assert( ap[0]==pPrev->pNear->apPhrase[0] ); memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase); pParse->nPhrase--; sqlite3Fts5ParseNodeFree(pPrev); } else{ pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0); } } return pRet; } static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){ int nByte = 0; Fts5ExprTerm *p; char *zQuoted; /* Determine the maximum amount of space required. */ for(p=pTerm; p; p=p->pSynonym){ nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2; } zQuoted = sqlite3_malloc(nByte); if( zQuoted ){ int i = 0; for(p=pTerm; p; p=p->pSynonym){ char *zIn = p->zTerm; zQuoted[i++] = '"'; while( *zIn ){ if( *zIn=='"' ) zQuoted[i++] = '"'; zQuoted[i++] = *zIn++; } zQuoted[i++] = '"'; if( p->pSynonym ) zQuoted[i++] = '|'; } if( pTerm->bPrefix ){ zQuoted[i++] = ' '; zQuoted[i++] = '*'; } zQuoted[i++] = '\0'; } return zQuoted; } static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){ char *zNew; va_list ap; va_start(ap, zFmt); zNew = sqlite3_vmprintf(zFmt, ap); va_end(ap); if( zApp && zNew ){ char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew); sqlite3_free(zNew); zNew = zNew2; } sqlite3_free(zApp); return zNew; } /* ** Compose a tcl-readable representation of expression pExpr. Return a ** pointer to a buffer containing that representation. It is the ** responsibility of the caller to at some point free the buffer using ** sqlite3_free(). */ static char *fts5ExprPrintTcl( Fts5Config *pConfig, const char *zNearsetCmd, Fts5ExprNode *pExpr ){ char *zRet = 0; if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){ Fts5ExprNearset *pNear = pExpr->pNear; int i; int iTerm; zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd); if( zRet==0 ) return 0; if( pNear->pColset ){ int *aiCol = pNear->pColset->aiCol; int nCol = pNear->pColset->nCol; if( nCol==1 ){ zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]); }else{ zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]); for(i=1; i<pNear->pColset->nCol; i++){ zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]); } zRet = fts5PrintfAppend(zRet, "} "); } if( zRet==0 ) return 0; } if( pNear->nPhrase>1 ){ zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear); if( zRet==0 ) return 0; } zRet = fts5PrintfAppend(zRet, "--"); if( zRet==0 ) return 0; for(i=0; i<pNear->nPhrase; i++){ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i]; zRet = fts5PrintfAppend(zRet, " {"); for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){ char *zTerm = pPhrase->aTerm[iTerm].zTerm; zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm); if( pPhrase->aTerm[iTerm].bPrefix ){ zRet = fts5PrintfAppend(zRet, "*"); } } if( zRet ) zRet = fts5PrintfAppend(zRet, "}"); if( zRet==0 ) return 0; } }else{ char const *zOp = 0; int i; switch( pExpr->eType ){ case FTS5_AND: zOp = "AND"; break; case FTS5_NOT: zOp = "NOT"; break; default: assert( pExpr->eType==FTS5_OR ); zOp = "OR"; break; } zRet = sqlite3_mprintf("%s", zOp); for(i=0; zRet && i<pExpr->nChild; i++){ char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]); if( !z ){ sqlite3_free(zRet); zRet = 0; }else{ zRet = fts5PrintfAppend(zRet, " [%z]", z); } } } return zRet; } static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){ char *zRet = 0; if( pExpr->eType==0 ){ return sqlite3_mprintf("\"\""); }else if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){ Fts5ExprNearset *pNear = pExpr->pNear; int i; int iTerm; if( pNear->pColset ){ int iCol = pNear->pColset->aiCol[0]; zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]); if( zRet==0 ) return 0; } if( pNear->nPhrase>1 ){ zRet = fts5PrintfAppend(zRet, "NEAR("); if( zRet==0 ) return 0; } for(i=0; i<pNear->nPhrase; i++){ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i]; if( i!=0 ){ zRet = fts5PrintfAppend(zRet, " "); if( zRet==0 ) return 0; } for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){ char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]); if( zTerm ){ zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm); sqlite3_free(zTerm); } if( zTerm==0 || zRet==0 ){ sqlite3_free(zRet); return 0; } } } if( pNear->nPhrase>1 ){ zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear); if( zRet==0 ) return 0; } }else{ char const *zOp = 0; int i; switch( pExpr->eType ){ case FTS5_AND: zOp = " AND "; break; case FTS5_NOT: zOp = " NOT "; break; default: assert( pExpr->eType==FTS5_OR ); zOp = " OR "; break; } for(i=0; i<pExpr->nChild; i++){ char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]); if( z==0 ){ sqlite3_free(zRet); zRet = 0; }else{ int e = pExpr->apChild[i]->eType; int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF); zRet = fts5PrintfAppend(zRet, "%s%s%z%s", (i==0 ? "" : zOp), (b?"(":""), z, (b?")":"") ); } if( zRet==0 ) break; } } return zRet; } /* ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0) ** and fts5_expr_tcl() (bTcl!=0). */ static void fts5ExprFunction( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ sqlite3_value **apVal, /* Function arguments */ int bTcl ){ Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx); sqlite3 *db = sqlite3_context_db_handle(pCtx); const char *zExpr = 0; char *zErr = 0; Fts5Expr *pExpr = 0; int rc; int i; const char **azConfig; /* Array of arguments for Fts5Config */ const char *zNearsetCmd = "nearset"; int nConfig; /* Size of azConfig[] */ Fts5Config *pConfig = 0; int iArg = 1; if( nArg<1 ){ zErr = sqlite3_mprintf("wrong number of arguments to function %s", bTcl ? "fts5_expr_tcl" : "fts5_expr" ); sqlite3_result_error(pCtx, zErr, -1); sqlite3_free(zErr); return; } if( bTcl && nArg>1 ){ zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]); iArg = 2; } nConfig = 3 + (nArg-iArg); azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig); if( azConfig==0 ){ sqlite3_result_error_nomem(pCtx); return; } azConfig[0] = 0; azConfig[1] = "main"; azConfig[2] = "tbl"; for(i=3; iArg<nArg; iArg++){ azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]); } zExpr = (const char*)sqlite3_value_text(apVal[0]); rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr); if( rc==SQLITE_OK ){ rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr); } if( rc==SQLITE_OK ){ char *zText; if( pExpr->pRoot->xNext==0 ){ zText = sqlite3_mprintf(""); }else if( bTcl ){ zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot); }else{ zText = fts5ExprPrint(pConfig, pExpr->pRoot); } if( zText==0 ){ rc = SQLITE_NOMEM; }else{ sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT); sqlite3_free(zText); } } if( rc!=SQLITE_OK ){ if( zErr ){ sqlite3_result_error(pCtx, zErr, -1); sqlite3_free(zErr); }else{ sqlite3_result_error_code(pCtx, rc); } } sqlite3_free((void *)azConfig); sqlite3Fts5ConfigFree(pConfig); sqlite3Fts5ExprFree(pExpr); } static void fts5ExprFunctionHr( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ sqlite3_value **apVal /* Function arguments */ ){ fts5ExprFunction(pCtx, nArg, apVal, 0); } static void fts5ExprFunctionTcl( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ sqlite3_value **apVal /* Function arguments */ ){ fts5ExprFunction(pCtx, nArg, apVal, 1); } /* ** The implementation of an SQLite user-defined-function that accepts a ** single integer as an argument. If the integer is an alpha-numeric ** unicode code point, 1 is returned. Otherwise 0. */ static void fts5ExprIsAlnum( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ sqlite3_value **apVal /* Function arguments */ ){ int iCode; if( nArg!=1 ){ sqlite3_result_error(pCtx, "wrong number of arguments to function fts5_isalnum", -1 ); return; } iCode = sqlite3_value_int(apVal[0]); sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode)); } static void fts5ExprFold( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ sqlite3_value **apVal /* Function arguments */ ){ if( nArg!=1 && nArg!=2 ){ sqlite3_result_error(pCtx, "wrong number of arguments to function fts5_fold", -1 ); }else{ int iCode; int bRemoveDiacritics = 0; iCode = sqlite3_value_int(apVal[0]); if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]); sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics)); } } /* ** This is called during initialization to register the fts5_expr() scalar ** UDF with the SQLite handle passed as the only argument. */ static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){ struct Fts5ExprFunc { const char *z; void (*x)(sqlite3_context*,int,sqlite3_value**); } aFunc[] = { { "fts5_expr", fts5ExprFunctionHr }, { "fts5_expr_tcl", fts5ExprFunctionTcl }, { "fts5_isalnum", fts5ExprIsAlnum }, { "fts5_fold", fts5ExprFold }, }; int i; int rc = SQLITE_OK; void *pCtx = (void*)pGlobal; for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){ struct Fts5ExprFunc *p = &aFunc[i]; rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0); } /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */ #ifndef NDEBUG (void)sqlite3Fts5ParserTrace; #endif return rc; } /* ** Return the number of phrases in expression pExpr. */ static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){ return (pExpr ? pExpr->nPhrase : 0); } /* ** Return the number of terms in the iPhrase'th phrase in pExpr. */ static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){ if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0; return pExpr->apExprPhrase[iPhrase]->nTerm; } /* ** This function is used to access the current position list for phrase ** iPhrase. */ static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){ int nRet; Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase]; Fts5ExprNode *pNode = pPhrase->pNode; if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){ *pa = pPhrase->poslist.p; nRet = pPhrase->poslist.n; }else{ *pa = 0; nRet = 0; } return nRet; } struct Fts5PoslistPopulator { Fts5PoslistWriter writer; int bOk; /* True if ok to populate */ int bMiss; }; static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){ Fts5PoslistPopulator *pRet; pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase); if( pRet ){ int i; memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase); for(i=0; i<pExpr->nPhrase; i++){ Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist; Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode; assert( pExpr->apExprPhrase[i]->nTerm==1 ); if( bLive && (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof) ){ pRet[i].bMiss = 1; }else{ pBuf->n = 0; } } } return pRet; } struct Fts5ExprCtx { Fts5Expr *pExpr; Fts5PoslistPopulator *aPopulator; i64 iOff; }; typedef struct Fts5ExprCtx Fts5ExprCtx; /* ** TODO: Make this more efficient! */ static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){ int i; for(i=0; i<pColset->nCol; i++){ if( pColset->aiCol[i]==iCol ) return 1; } return 0; } static int fts5ExprPopulatePoslistsCb( void *pCtx, /* Copy of 2nd argument to xTokenize() */ int tflags, /* Mask of FTS5_TOKEN_* flags */ const char *pToken, /* Pointer to buffer containing token */ int nToken, /* Size of token in bytes */ int iUnused1, /* Byte offset of token within input text */ int iUnused2 /* Byte offset of end of token within input text */ ){ Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx; Fts5Expr *pExpr = p->pExpr; int i; UNUSED_PARAM2(iUnused1, iUnused2); if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE; if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++; for(i=0; i<pExpr->nPhrase; i++){ Fts5ExprTerm *pTerm; if( p->aPopulator[i].bOk==0 ) continue; for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){ int nTerm = (int)strlen(pTerm->zTerm); if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix)) && memcmp(pTerm->zTerm, pToken, nTerm)==0 ){ int rc = sqlite3Fts5PoslistWriterAppend( &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff ); if( rc ) return rc; break; } } } return SQLITE_OK; } static int sqlite3Fts5ExprPopulatePoslists( Fts5Config *pConfig, Fts5Expr *pExpr, Fts5PoslistPopulator *aPopulator, int iCol, const char *z, int n ){ int i; Fts5ExprCtx sCtx; sCtx.pExpr = pExpr; sCtx.aPopulator = aPopulator; sCtx.iOff = (((i64)iCol) << 32) - 1; for(i=0; i<pExpr->nPhrase; i++){ Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode; Fts5Colset *pColset = pNode->pNear->pColset; if( (pColset && 0==fts5ExprColsetTest(pColset, iCol)) || aPopulator[i].bMiss ){ aPopulator[i].bOk = 0; }else{ aPopulator[i].bOk = 1; } } return sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb ); } static void fts5ExprClearPoslists(Fts5ExprNode *pNode){ if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){ pNode->pNear->apPhrase[0]->poslist.n = 0; }else{ int i; for(i=0; i<pNode->nChild; i++){ fts5ExprClearPoslists(pNode->apChild[i]); } } } static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){ pNode->iRowid = iRowid; pNode->bEof = 0; switch( pNode->eType ){ case FTS5_TERM: case FTS5_STRING: return (pNode->pNear->apPhrase[0]->poslist.n>0); case FTS5_AND: { int i; for(i=0; i<pNode->nChild; i++){ if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){ fts5ExprClearPoslists(pNode); return 0; } } break; } case FTS5_OR: { int i; int bRet = 0; for(i=0; i<pNode->nChild; i++){ if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){ bRet = 1; } } return bRet; } default: { assert( pNode->eType==FTS5_NOT ); if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid) || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid) ){ fts5ExprClearPoslists(pNode); return 0; } break; } } return 1; } static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){ fts5ExprCheckPoslists(pExpr->pRoot, iRowid); } /* ** This function is only called for detail=columns tables. */ static int sqlite3Fts5ExprPhraseCollist( Fts5Expr *pExpr, int iPhrase, const u8 **ppCollist, int *pnCollist ){ Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase]; Fts5ExprNode *pNode = pPhrase->pNode; int rc = SQLITE_OK; assert( iPhrase>=0 && iPhrase<pExpr->nPhrase ); assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS ); if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid && pPhrase->poslist.n>0 ){ Fts5ExprTerm *pTerm = &pPhrase->aTerm[0]; if( pTerm->pSynonym ){ Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1]; rc = fts5ExprSynonymList( pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist ); }else{ *ppCollist = pPhrase->aTerm[0].pIter->pData; *pnCollist = pPhrase->aTerm[0].pIter->nData; } }else{ *ppCollist = 0; *pnCollist = 0; } return rc; } /* ** 2014 August 11 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ /* #include "fts5Int.h" */ typedef struct Fts5HashEntry Fts5HashEntry; /* ** This file contains the implementation of an in-memory hash table used ** to accumuluate "term -> doclist" content before it is flused to a level-0 ** segment. */ struct Fts5Hash { int eDetail; /* Copy of Fts5Config.eDetail */ int *pnByte; /* Pointer to bytes counter */ int nEntry; /* Number of entries currently in hash */ int nSlot; /* Size of aSlot[] array */ Fts5HashEntry *pScan; /* Current ordered scan item */ Fts5HashEntry **aSlot; /* Array of hash slots */ }; /* ** Each entry in the hash table is represented by an object of the ** following type. Each object, its key (zKey[]) and its current data ** are stored in a single memory allocation. The position list data ** immediately follows the key data in memory. ** ** The data that follows the key is in a similar, but not identical format ** to the doclist data stored in the database. It is: ** ** * Rowid, as a varint ** * Position list, without 0x00 terminator. ** * Size of previous position list and rowid, as a 4 byte ** big-endian integer. ** ** iRowidOff: ** Offset of last rowid written to data area. Relative to first byte of ** structure. ** ** nData: ** Bytes of data written since iRowidOff. */ struct Fts5HashEntry { Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */ Fts5HashEntry *pScanNext; /* Next entry in sorted order */ int nAlloc; /* Total size of allocation */ int iSzPoslist; /* Offset of space for 4-byte poslist size */ int nData; /* Total bytes of data (incl. structure) */ int nKey; /* Length of zKey[] in bytes */ u8 bDel; /* Set delete-flag @ iSzPoslist */ u8 bContent; /* Set content-flag (detail=none mode) */ i16 iCol; /* Column of last value written */ int iPos; /* Position of last value written */ i64 iRowid; /* Rowid of last value written */ char zKey[8]; /* Nul-terminated entry key */ }; /* ** Size of Fts5HashEntry without the zKey[] array. */ #define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8) /* ** Allocate a new hash table. */ static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){ int rc = SQLITE_OK; Fts5Hash *pNew; *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash)); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ int nByte; memset(pNew, 0, sizeof(Fts5Hash)); pNew->pnByte = pnByte; pNew->eDetail = pConfig->eDetail; pNew->nSlot = 1024; nByte = sizeof(Fts5HashEntry*) * pNew->nSlot; pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte); if( pNew->aSlot==0 ){ sqlite3_free(pNew); *ppNew = 0; rc = SQLITE_NOMEM; }else{ memset(pNew->aSlot, 0, nByte); } } return rc; } /* ** Free a hash table object. */ static void sqlite3Fts5HashFree(Fts5Hash *pHash){ if( pHash ){ sqlite3Fts5HashClear(pHash); sqlite3_free(pHash->aSlot); sqlite3_free(pHash); } } /* ** Empty (but do not delete) a hash table. */ static void sqlite3Fts5HashClear(Fts5Hash *pHash){ int i; for(i=0; i<pHash->nSlot; i++){ Fts5HashEntry *pNext; Fts5HashEntry *pSlot; for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){ pNext = pSlot->pHashNext; sqlite3_free(pSlot); } } memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*)); pHash->nEntry = 0; } static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){ int i; unsigned int h = 13; for(i=n-1; i>=0; i--){ h = (h << 3) ^ h ^ p[i]; } return (h % nSlot); } static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){ int i; unsigned int h = 13; for(i=n-1; i>=0; i--){ h = (h << 3) ^ h ^ p[i]; } h = (h << 3) ^ h ^ b; return (h % nSlot); } /* ** Resize the hash table by doubling the number of slots. */ static int fts5HashResize(Fts5Hash *pHash){ int nNew = pHash->nSlot*2; int i; Fts5HashEntry **apNew; Fts5HashEntry **apOld = pHash->aSlot; apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*)); if( !apNew ) return SQLITE_NOMEM; memset(apNew, 0, nNew*sizeof(Fts5HashEntry*)); for(i=0; i<pHash->nSlot; i++){ while( apOld[i] ){ int iHash; Fts5HashEntry *p = apOld[i]; apOld[i] = p->pHashNext; iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey)); p->pHashNext = apNew[iHash]; apNew[iHash] = p; } } sqlite3_free(apOld); pHash->nSlot = nNew; pHash->aSlot = apNew; return SQLITE_OK; } static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){ if( p->iSzPoslist ){ u8 *pPtr = (u8*)p; if( pHash->eDetail==FTS5_DETAIL_NONE ){ assert( p->nData==p->iSzPoslist ); if( p->bDel ){ pPtr[p->nData++] = 0x00; if( p->bContent ){ pPtr[p->nData++] = 0x00; } } }else{ int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */ int nPos = nSz*2 + p->bDel; /* Value of nPos field */ assert( p->bDel==0 || p->bDel==1 ); if( nPos<=127 ){ pPtr[p->iSzPoslist] = (u8)nPos; }else{ int nByte = sqlite3Fts5GetVarintLen((u32)nPos); memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz); sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos); p->nData += (nByte-1); } } p->iSzPoslist = 0; p->bDel = 0; p->bContent = 0; } } /* ** Add an entry to the in-memory hash table. The key is the concatenation ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos). ** ** (bByte || pToken) -> (iRowid,iCol,iPos) ** ** Or, if iCol is negative, then the value is a delete marker. */ static int sqlite3Fts5HashWrite( Fts5Hash *pHash, i64 iRowid, /* Rowid for this entry */ int iCol, /* Column token appears in (-ve -> delete) */ int iPos, /* Position of token within column */ char bByte, /* First byte of token */ const char *pToken, int nToken /* Token to add or remove to or from index */ ){ unsigned int iHash; Fts5HashEntry *p; u8 *pPtr; int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */ int bNew; /* If non-delete entry should be written */ bNew = (pHash->eDetail==FTS5_DETAIL_FULL); /* Attempt to locate an existing hash entry */ iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken); for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){ if( p->zKey[0]==bByte && p->nKey==nToken && memcmp(&p->zKey[1], pToken, nToken)==0 ){ break; } } /* If an existing hash entry cannot be found, create a new one. */ if( p==0 ){ /* Figure out how much space to allocate */ int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64; if( nByte<128 ) nByte = 128; /* Grow the Fts5Hash.aSlot[] array if necessary. */ if( (pHash->nEntry*2)>=pHash->nSlot ){ int rc = fts5HashResize(pHash); if( rc!=SQLITE_OK ) return rc; iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken); } /* Allocate new Fts5HashEntry and add it to the hash table. */ p = (Fts5HashEntry*)sqlite3_malloc(nByte); if( !p ) return SQLITE_NOMEM; memset(p, 0, FTS5_HASHENTRYSIZE); p->nAlloc = nByte; p->zKey[0] = bByte; memcpy(&p->zKey[1], pToken, nToken); assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) ); p->nKey = nToken; p->zKey[nToken+1] = '\0'; p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE; p->pHashNext = pHash->aSlot[iHash]; pHash->aSlot[iHash] = p; pHash->nEntry++; /* Add the first rowid field to the hash-entry */ p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid); p->iRowid = iRowid; p->iSzPoslist = p->nData; if( pHash->eDetail!=FTS5_DETAIL_NONE ){ p->nData += 1; p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1); } nIncr += p->nData; }else{ /* Appending to an existing hash-entry. Check that there is enough ** space to append the largest possible new entry. Worst case scenario ** is: ** ** + 9 bytes for a new rowid, ** + 4 byte reserved for the "poslist size" varint. ** + 1 byte for a "new column" byte, ** + 3 bytes for a new column number (16-bit max) as a varint, ** + 5 bytes for the new position offset (32-bit max). */ if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){ int nNew = p->nAlloc * 2; Fts5HashEntry *pNew; Fts5HashEntry **pp; pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew); if( pNew==0 ) return SQLITE_NOMEM; pNew->nAlloc = nNew; for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext); *pp = pNew; p = pNew; } nIncr -= p->nData; } assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) ); pPtr = (u8*)p; /* If this is a new rowid, append the 4-byte size field for the previous ** entry, and the new rowid for this entry. */ if( iRowid!=p->iRowid ){ fts5HashAddPoslistSize(pHash, p); p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid); p->iRowid = iRowid; bNew = 1; p->iSzPoslist = p->nData; if( pHash->eDetail!=FTS5_DETAIL_NONE ){ p->nData += 1; p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1); p->iPos = 0; } } if( iCol>=0 ){ if( pHash->eDetail==FTS5_DETAIL_NONE ){ p->bContent = 1; }else{ /* Append a new column value, if necessary */ assert( iCol>=p->iCol ); if( iCol!=p->iCol ){ if( pHash->eDetail==FTS5_DETAIL_FULL ){ pPtr[p->nData++] = 0x01; p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol); p->iCol = (i16)iCol; p->iPos = 0; }else{ bNew = 1; p->iCol = (i16)(iPos = iCol); } } /* Append the new position offset, if necessary */ if( bNew ){ p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2); p->iPos = iPos; } } }else{ /* This is a delete. Set the delete flag. */ p->bDel = 1; } nIncr += p->nData; *pHash->pnByte += nIncr; return SQLITE_OK; } /* ** Arguments pLeft and pRight point to linked-lists of hash-entry objects, ** each sorted in key order. This function merges the two lists into a ** single list and returns a pointer to its first element. */ static Fts5HashEntry *fts5HashEntryMerge( Fts5HashEntry *pLeft, Fts5HashEntry *pRight ){ Fts5HashEntry *p1 = pLeft; Fts5HashEntry *p2 = pRight; Fts5HashEntry *pRet = 0; Fts5HashEntry **ppOut = &pRet; while( p1 || p2 ){ if( p1==0 ){ *ppOut = p2; p2 = 0; }else if( p2==0 ){ *ppOut = p1; p1 = 0; }else{ int i = 0; while( p1->zKey[i]==p2->zKey[i] ) i++; if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){ /* p2 is smaller */ *ppOut = p2; ppOut = &p2->pScanNext; p2 = p2->pScanNext; }else{ /* p1 is smaller */ *ppOut = p1; ppOut = &p1->pScanNext; p1 = p1->pScanNext; } *ppOut = 0; } } return pRet; } /* ** Extract all tokens from hash table iHash and link them into a list ** in sorted order. The hash table is cleared before returning. It is ** the responsibility of the caller to free the elements of the returned ** list. */ static int fts5HashEntrySort( Fts5Hash *pHash, const char *pTerm, int nTerm, /* Query prefix, if any */ Fts5HashEntry **ppSorted ){ const int nMergeSlot = 32; Fts5HashEntry **ap; Fts5HashEntry *pList; int iSlot; int i; *ppSorted = 0; ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot); if( !ap ) return SQLITE_NOMEM; memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot); for(iSlot=0; iSlot<pHash->nSlot; iSlot++){ Fts5HashEntry *pIter; for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){ if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){ Fts5HashEntry *pEntry = pIter; pEntry->pScanNext = 0; for(i=0; ap[i]; i++){ pEntry = fts5HashEntryMerge(pEntry, ap[i]); ap[i] = 0; } ap[i] = pEntry; } } } pList = 0; for(i=0; i<nMergeSlot; i++){ pList = fts5HashEntryMerge(pList, ap[i]); } pHash->nEntry = 0; sqlite3_free(ap); *ppSorted = pList; return SQLITE_OK; } /* ** Query the hash table for a doclist associated with term pTerm/nTerm. */ static int sqlite3Fts5HashQuery( Fts5Hash *pHash, /* Hash table to query */ const char *pTerm, int nTerm, /* Query term */ const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */ int *pnDoclist /* OUT: Size of doclist in bytes */ ){ unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm); Fts5HashEntry *p; for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){ if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break; } if( p ){ fts5HashAddPoslistSize(pHash, p); *ppDoclist = (const u8*)&p->zKey[nTerm+1]; *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1); }else{ *ppDoclist = 0; *pnDoclist = 0; } return SQLITE_OK; } static int sqlite3Fts5HashScanInit( Fts5Hash *p, /* Hash table to query */ const char *pTerm, int nTerm /* Query prefix */ ){ return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan); } static void sqlite3Fts5HashScanNext(Fts5Hash *p){ assert( !sqlite3Fts5HashScanEof(p) ); p->pScan = p->pScan->pScanNext; } static int sqlite3Fts5HashScanEof(Fts5Hash *p){ return (p->pScan==0); } static void sqlite3Fts5HashScanEntry( Fts5Hash *pHash, const char **pzTerm, /* OUT: term (nul-terminated) */ const u8 **ppDoclist, /* OUT: pointer to doclist */ int *pnDoclist /* OUT: size of doclist in bytes */ ){ Fts5HashEntry *p; if( (p = pHash->pScan) ){ int nTerm = (int)strlen(p->zKey); fts5HashAddPoslistSize(pHash, p); *pzTerm = p->zKey; *ppDoclist = (const u8*)&p->zKey[nTerm+1]; *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1); }else{ *pzTerm = 0; *ppDoclist = 0; *pnDoclist = 0; } } /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Low level access to the FTS index stored in the database file. The ** routines in this file file implement all read and write access to the ** %_data table. Other parts of the system access this functionality via ** the interface defined in fts5Int.h. */ /* #include "fts5Int.h" */ /* ** Overview: ** ** The %_data table contains all the FTS indexes for an FTS5 virtual table. ** As well as the main term index, there may be up to 31 prefix indexes. ** The format is similar to FTS3/4, except that: ** ** * all segment b-tree leaf data is stored in fixed size page records ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is ** taken to ensure it is possible to iterate in either direction through ** the entries in a doclist, or to seek to a specific entry within a ** doclist, without loading it into memory. ** ** * large doclists that span many pages have associated "doclist index" ** records that contain a copy of the first rowid on each page spanned by ** the doclist. This is used to speed up seek operations, and merges of ** large doclists with very small doclists. ** ** * extra fields in the "structure record" record the state of ongoing ** incremental merge operations. ** */ #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */ #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */ #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */ #define FTS5_MAIN_PREFIX '0' #if FTS5_MAX_PREFIX_INDEXES > 31 # error "FTS5_MAX_PREFIX_INDEXES is too large" #endif /* ** Details: ** ** The %_data table managed by this module, ** ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB); ** ** , contains the following 5 types of records. See the comments surrounding ** the FTS5_*_ROWID macros below for a description of how %_data rowids are ** assigned to each fo them. ** ** 1. Structure Records: ** ** The set of segments that make up an index - the index structure - are ** recorded in a single record within the %_data table. The record consists ** of a single 32-bit configuration cookie value followed by a list of ** SQLite varints. If the FTS table features more than one index (because ** there are one or more prefix indexes), it is guaranteed that all share ** the same cookie value. ** ** Immediately following the configuration cookie, the record begins with ** three varints: ** ** + number of levels, ** + total number of segments on all levels, ** + value of write counter. ** ** Then, for each level from 0 to nMax: ** ** + number of input segments in ongoing merge. ** + total number of segments in level. ** + for each segment from oldest to newest: ** + segment id (always > 0) ** + first leaf page number (often 1, always greater than 0) ** + final leaf page number ** ** 2. The Averages Record: ** ** A single record within the %_data table. The data is a list of varints. ** The first value is the number of rows in the index. Then, for each column ** from left to right, the total number of tokens in the column for all ** rows of the table. ** ** 3. Segment leaves: ** ** TERM/DOCLIST FORMAT: ** ** Most of each segment leaf is taken up by term/doclist data. The ** general format of term/doclist, starting with the first term ** on the leaf page, is: ** ** varint : size of first term ** blob: first term data ** doclist: first doclist ** zero-or-more { ** varint: number of bytes in common with previous term ** varint: number of bytes of new term data (nNew) ** blob: nNew bytes of new term data ** doclist: next doclist ** } ** ** doclist format: ** ** varint: first rowid ** poslist: first poslist ** zero-or-more { ** varint: rowid delta (always > 0) ** poslist: next poslist ** } ** ** poslist format: ** ** varint: size of poslist in bytes multiplied by 2, not including ** this field. Plus 1 if this entry carries the "delete" flag. ** collist: collist for column 0 ** zero-or-more { ** 0x01 byte ** varint: column number (I) ** collist: collist for column I ** } ** ** collist format: ** ** varint: first offset + 2 ** zero-or-more { ** varint: offset delta + 2 ** } ** ** PAGE FORMAT ** ** Each leaf page begins with a 4-byte header containing 2 16-bit ** unsigned integer fields in big-endian format. They are: ** ** * The byte offset of the first rowid on the page, if it exists ** and occurs before the first term (otherwise 0). ** ** * The byte offset of the start of the page footer. If the page ** footer is 0 bytes in size, then this field is the same as the ** size of the leaf page in bytes. ** ** The page footer consists of a single varint for each term located ** on the page. Each varint is the byte offset of the current term ** within the page, delta-compressed against the previous value. In ** other words, the first varint in the footer is the byte offset of ** the first term, the second is the byte offset of the second less that ** of the first, and so on. ** ** The term/doclist format described above is accurate if the entire ** term/doclist data fits on a single leaf page. If this is not the case, ** the format is changed in two ways: ** ** + if the first rowid on a page occurs before the first term, it ** is stored as a literal value: ** ** varint: first rowid ** ** + the first term on each page is stored in the same way as the ** very first term of the segment: ** ** varint : size of first term ** blob: first term data ** ** 5. Segment doclist indexes: ** ** Doclist indexes are themselves b-trees, however they usually consist of ** a single leaf record only. The format of each doclist index leaf page ** is: ** ** * Flags byte. Bits are: ** 0x01: Clear if leaf is also the root page, otherwise set. ** ** * Page number of fts index leaf page. As a varint. ** ** * First rowid on page indicated by previous field. As a varint. ** ** * A list of varints, one for each subsequent termless page. A ** positive delta if the termless page contains at least one rowid, ** or an 0x00 byte otherwise. ** ** Internal doclist index nodes are: ** ** * Flags byte. Bits are: ** 0x01: Clear for root page, otherwise set. ** ** * Page number of first child page. As a varint. ** ** * Copy of first rowid on page indicated by previous field. As a varint. ** ** * A list of delta-encoded varints - the first rowid on each subsequent ** child page. ** */ /* ** Rowids for the averages and structure records in the %_data table. */ #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */ #define FTS5_STRUCTURE_ROWID 10 /* The structure record */ /* ** Macros determining the rowids used by segment leaves and dlidx leaves ** and nodes. All nodes and leaves are stored in the %_data table with large ** positive rowids. ** ** Each segment has a unique non-zero 16-bit id. ** ** The rowid for each segment leaf is found by passing the segment id and ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered ** sequentially starting from 1. */ #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */ #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */ #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */ #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */ #define fts5_dri(segid, dlidx, height, pgno) ( \ ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \ ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \ ((i64)(height) << (FTS5_DATA_PAGE_B)) + \ ((i64)(pgno)) \ ) #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno) #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno) /* ** Maximum segments permitted in a single index */ #define FTS5_MAX_SEGMENT 2000 #ifdef SQLITE_DEBUG static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; } #endif /* ** Each time a blob is read from the %_data table, it is padded with this ** many zero bytes. This makes it easier to decode the various record formats ** without overreading if the records are corrupt. */ #define FTS5_DATA_ZERO_PADDING 8 #define FTS5_DATA_PADDING 20 typedef struct Fts5Data Fts5Data; typedef struct Fts5DlidxIter Fts5DlidxIter; typedef struct Fts5DlidxLvl Fts5DlidxLvl; typedef struct Fts5DlidxWriter Fts5DlidxWriter; typedef struct Fts5Iter Fts5Iter; typedef struct Fts5PageWriter Fts5PageWriter; typedef struct Fts5SegIter Fts5SegIter; typedef struct Fts5DoclistIter Fts5DoclistIter; typedef struct Fts5SegWriter Fts5SegWriter; typedef struct Fts5Structure Fts5Structure; typedef struct Fts5StructureLevel Fts5StructureLevel; typedef struct Fts5StructureSegment Fts5StructureSegment; struct Fts5Data { u8 *p; /* Pointer to buffer containing record */ int nn; /* Size of record in bytes */ int szLeaf; /* Size of leaf without page-index */ }; /* ** One object per %_data table. */ struct Fts5Index { Fts5Config *pConfig; /* Virtual table configuration */ char *zDataTbl; /* Name of %_data table */ int nWorkUnit; /* Leaf pages in a "unit" of work */ /* ** Variables related to the accumulation of tokens and doclists within the ** in-memory hash tables before they are flushed to disk. */ Fts5Hash *pHash; /* Hash table for in-memory data */ int nPendingData; /* Current bytes of pending data */ i64 iWriteRowid; /* Rowid for current doc being written */ int bDelete; /* Current write is a delete */ /* Error state. */ int rc; /* Current error code */ /* State used by the fts5DataXXX() functions. */ sqlite3_blob *pReader; /* RO incr-blob open on %_data table */ sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */ sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */ sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */ sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */ sqlite3_stmt *pIdxSelect; int nRead; /* Total number of blocks read */ sqlite3_stmt *pDataVersion; i64 iStructVersion; /* data_version when pStruct read */ Fts5Structure *pStruct; /* Current db structure (or NULL) */ }; struct Fts5DoclistIter { u8 *aEof; /* Pointer to 1 byte past end of doclist */ /* Output variables. aPoslist==0 at EOF */ i64 iRowid; u8 *aPoslist; int nPoslist; int nSize; }; /* ** The contents of the "structure" record for each index are represented ** using an Fts5Structure record in memory. Which uses instances of the ** other Fts5StructureXXX types as components. */ struct Fts5StructureSegment { int iSegid; /* Segment id */ int pgnoFirst; /* First leaf page number in segment */ int pgnoLast; /* Last leaf page number in segment */ }; struct Fts5StructureLevel { int nMerge; /* Number of segments in incr-merge */ int nSeg; /* Total number of segments on level */ Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */ }; struct Fts5Structure { int nRef; /* Object reference count */ u64 nWriteCounter; /* Total leaves written to level 0 */ int nSegment; /* Total segments in this structure */ int nLevel; /* Number of levels in this index */ Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */ }; /* ** An object of type Fts5SegWriter is used to write to segments. */ struct Fts5PageWriter { int pgno; /* Page number for this page */ int iPrevPgidx; /* Previous value written into pgidx */ Fts5Buffer buf; /* Buffer containing leaf data */ Fts5Buffer pgidx; /* Buffer containing page-index */ Fts5Buffer term; /* Buffer containing previous term on page */ }; struct Fts5DlidxWriter { int pgno; /* Page number for this page */ int bPrevValid; /* True if iPrev is valid */ i64 iPrev; /* Previous rowid value written to page */ Fts5Buffer buf; /* Buffer containing page data */ }; struct Fts5SegWriter { int iSegid; /* Segid to write to */ Fts5PageWriter writer; /* PageWriter object */ i64 iPrevRowid; /* Previous rowid written to current leaf */ u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */ u8 bFirstRowidInPage; /* True if next rowid is first in page */ /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */ u8 bFirstTermInPage; /* True if next term will be first in leaf */ int nLeafWritten; /* Number of leaf pages written */ int nEmpty; /* Number of contiguous term-less nodes */ int nDlidx; /* Allocated size of aDlidx[] array */ Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */ /* Values to insert into the %_idx table */ Fts5Buffer btterm; /* Next term to insert into %_idx table */ int iBtPage; /* Page number corresponding to btterm */ }; typedef struct Fts5CResult Fts5CResult; struct Fts5CResult { u16 iFirst; /* aSeg[] index of firstest iterator */ u8 bTermEq; /* True if the terms are equal */ }; /* ** Object for iterating through a single segment, visiting each term/rowid ** pair in the segment. ** ** pSeg: ** The segment to iterate through. ** ** iLeafPgno: ** Current leaf page number within segment. ** ** iLeafOffset: ** Byte offset within the current leaf that is the first byte of the ** position list data (one byte passed the position-list size field). ** rowid field of the current entry. Usually this is the size field of the ** position list data. The exception is if the rowid for the current entry ** is the last thing on the leaf page. ** ** pLeaf: ** Buffer containing current leaf page data. Set to NULL at EOF. ** ** iTermLeafPgno, iTermLeafOffset: ** Leaf page number containing the last term read from the segment. And ** the offset immediately following the term data. ** ** flags: ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows: ** ** FTS5_SEGITER_ONETERM: ** If set, set the iterator to point to EOF after the current doclist ** has been exhausted. Do not proceed to the next term in the segment. ** ** FTS5_SEGITER_REVERSE: ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If ** it is set, iterate through rowid in descending order instead of the ** default ascending order. ** ** iRowidOffset/nRowidOffset/aRowidOffset: ** These are used if the FTS5_SEGITER_REVERSE flag is set. ** ** For each rowid on the page corresponding to the current term, the ** corresponding aRowidOffset[] entry is set to the byte offset of the ** start of the "position-list-size" field within the page. ** ** iTermIdx: ** Index of current term on iTermLeafPgno. */ struct Fts5SegIter { Fts5StructureSegment *pSeg; /* Segment to iterate through */ int flags; /* Mask of configuration flags */ int iLeafPgno; /* Current leaf page number */ Fts5Data *pLeaf; /* Current leaf data */ Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */ int iLeafOffset; /* Byte offset within current leaf */ /* Next method */ void (*xNext)(Fts5Index*, Fts5SegIter*, int*); /* The page and offset from which the current term was read. The offset ** is the offset of the first rowid in the current doclist. */ int iTermLeafPgno; int iTermLeafOffset; int iPgidxOff; /* Next offset in pgidx */ int iEndofDoclist; /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */ int iRowidOffset; /* Current entry in aRowidOffset[] */ int nRowidOffset; /* Allocated size of aRowidOffset[] array */ int *aRowidOffset; /* Array of offset to rowid fields */ Fts5DlidxIter *pDlidx; /* If there is a doclist-index */ /* Variables populated based on current entry. */ Fts5Buffer term; /* Current term */ i64 iRowid; /* Current rowid */ int nPos; /* Number of bytes in current position list */ u8 bDel; /* True if the delete flag is set */ }; /* ** Argument is a pointer to an Fts5Data structure that contains a ** leaf page. */ #define ASSERT_SZLEAF_OK(x) assert( \ (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \ ) #define FTS5_SEGITER_ONETERM 0x01 #define FTS5_SEGITER_REVERSE 0x02 /* ** Argument is a pointer to an Fts5Data structure that contains a leaf ** page. This macro evaluates to true if the leaf contains no terms, or ** false if it contains at least one term. */ #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn) #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2])) #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p)) /* ** Object for iterating through the merged results of one or more segments, ** visiting each term/rowid pair in the merged data. ** ** nSeg is always a power of two greater than or equal to the number of ** segments that this object is merging data from. Both the aSeg[] and ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded ** with zeroed objects - these are handled as if they were iterators opened ** on empty segments. ** ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the ** comparison in this context is the index of the iterator that currently ** points to the smaller term/rowid combination. Iterators at EOF are ** considered to be greater than all other iterators. ** ** aFirst[1] contains the index in aSeg[] of the iterator that points to ** the smallest key overall. aFirst[0] is unused. ** ** poslist: ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered. ** There is no way to tell if this is populated or not. */ struct Fts5Iter { Fts5IndexIter base; /* Base class containing output vars */ Fts5Index *pIndex; /* Index that owns this iterator */ Fts5Structure *pStruct; /* Database structure for this iterator */ Fts5Buffer poslist; /* Buffer containing current poslist */ Fts5Colset *pColset; /* Restrict matches to these columns */ /* Invoked to set output variables. */ void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*); int nSeg; /* Size of aSeg[] array */ int bRev; /* True to iterate in reverse order */ u8 bSkipEmpty; /* True to skip deleted entries */ i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */ Fts5CResult *aFirst; /* Current merge state (see above) */ Fts5SegIter aSeg[1]; /* Array of segment iterators */ }; /* ** An instance of the following type is used to iterate through the contents ** of a doclist-index record. ** ** pData: ** Record containing the doclist-index data. ** ** bEof: ** Set to true once iterator has reached EOF. ** ** iOff: ** Set to the current offset within record pData. */ struct Fts5DlidxLvl { Fts5Data *pData; /* Data for current page of this level */ int iOff; /* Current offset into pData */ int bEof; /* At EOF already */ int iFirstOff; /* Used by reverse iterators */ /* Output variables */ int iLeafPgno; /* Page number of current leaf page */ i64 iRowid; /* First rowid on leaf iLeafPgno */ }; struct Fts5DlidxIter { int nLvl; int iSegid; Fts5DlidxLvl aLvl[1]; }; static void fts5PutU16(u8 *aOut, u16 iVal){ aOut[0] = (iVal>>8); aOut[1] = (iVal&0xFF); } static u16 fts5GetU16(const u8 *aIn){ return ((u16)aIn[0] << 8) + aIn[1]; } /* ** Allocate and return a buffer at least nByte bytes in size. ** ** If an OOM error is encountered, return NULL and set the error code in ** the Fts5Index handle passed as the first argument. */ static void *fts5IdxMalloc(Fts5Index *p, int nByte){ return sqlite3Fts5MallocZero(&p->rc, nByte); } /* ** Compare the contents of the pLeft buffer with the pRight/nRight blob. ** ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or ** +ve if pRight is smaller than pLeft. In other words: ** ** res = *pLeft - *pRight */ #ifdef SQLITE_DEBUG static int fts5BufferCompareBlob( Fts5Buffer *pLeft, /* Left hand side of comparison */ const u8 *pRight, int nRight /* Right hand side of comparison */ ){ int nCmp = MIN(pLeft->n, nRight); int res = memcmp(pLeft->p, pRight, nCmp); return (res==0 ? (pLeft->n - nRight) : res); } #endif /* ** Compare the contents of the two buffers using memcmp(). If one buffer ** is a prefix of the other, it is considered the lesser. ** ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or ** +ve if pRight is smaller than pLeft. In other words: ** ** res = *pLeft - *pRight */ static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){ int nCmp = MIN(pLeft->n, pRight->n); int res = memcmp(pLeft->p, pRight->p, nCmp); return (res==0 ? (pLeft->n - pRight->n) : res); } static int fts5LeafFirstTermOff(Fts5Data *pLeaf){ int ret; fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret); return ret; } /* ** Close the read-only blob handle, if it is open. */ static void fts5CloseReader(Fts5Index *p){ if( p->pReader ){ sqlite3_blob *pReader = p->pReader; p->pReader = 0; sqlite3_blob_close(pReader); } } /* ** Retrieve a record from the %_data table. ** ** If an error occurs, NULL is returned and an error left in the ** Fts5Index object. */ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ Fts5Data *pRet = 0; if( p->rc==SQLITE_OK ){ int rc = SQLITE_OK; if( p->pReader ){ /* This call may return SQLITE_ABORT if there has been a savepoint ** rollback since it was last used. In this case a new blob handle ** is required. */ sqlite3_blob *pBlob = p->pReader; p->pReader = 0; rc = sqlite3_blob_reopen(pBlob, iRowid); assert( p->pReader==0 ); p->pReader = pBlob; if( rc!=SQLITE_OK ){ fts5CloseReader(p); } if( rc==SQLITE_ABORT ) rc = SQLITE_OK; } /* If the blob handle is not open at this point, open it and seek ** to the requested entry. */ if( p->pReader==0 && rc==SQLITE_OK ){ Fts5Config *pConfig = p->pConfig; rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader ); } /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead. ** All the reasons those functions might return SQLITE_ERROR - missing ** table, missing row, non-blob/text in block column - indicate ** backing store corruption. */ if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT; if( rc==SQLITE_OK ){ u8 *aOut = 0; /* Read blob data into this buffer */ int nByte = sqlite3_blob_bytes(p->pReader); int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING; pRet = (Fts5Data*)sqlite3_malloc(nAlloc); if( pRet ){ pRet->nn = nByte; aOut = pRet->p = (u8*)&pRet[1]; }else{ rc = SQLITE_NOMEM; } if( rc==SQLITE_OK ){ rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0); } if( rc!=SQLITE_OK ){ sqlite3_free(pRet); pRet = 0; }else{ /* TODO1: Fix this */ pRet->szLeaf = fts5GetU16(&pRet->p[2]); } } p->rc = rc; p->nRead++; } assert( (pRet==0)==(p->rc!=SQLITE_OK) ); return pRet; } /* ** Release a reference to data record returned by an earlier call to ** fts5DataRead(). */ static void fts5DataRelease(Fts5Data *pData){ sqlite3_free(pData); } static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){ Fts5Data *pRet = fts5DataRead(p, iRowid); if( pRet ){ if( pRet->szLeaf>pRet->nn ){ p->rc = FTS5_CORRUPT; fts5DataRelease(pRet); pRet = 0; } } return pRet; } static int fts5IndexPrepareStmt( Fts5Index *p, sqlite3_stmt **ppStmt, char *zSql ){ if( p->rc==SQLITE_OK ){ if( zSql ){ p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0); }else{ p->rc = SQLITE_NOMEM; } } sqlite3_free(zSql); return p->rc; } /* ** INSERT OR REPLACE a record into the %_data table. */ static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){ if( p->rc!=SQLITE_OK ) return; if( p->pWriter==0 ){ Fts5Config *pConfig = p->pConfig; fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf( "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)", pConfig->zDb, pConfig->zName )); if( p->rc ) return; } sqlite3_bind_int64(p->pWriter, 1, iRowid); sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC); sqlite3_step(p->pWriter); p->rc = sqlite3_reset(p->pWriter); } /* ** Execute the following SQL: ** ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast */ static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){ if( p->rc!=SQLITE_OK ) return; if( p->pDeleter==0 ){ int rc; Fts5Config *pConfig = p->pConfig; char *zSql = sqlite3_mprintf( "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?", pConfig->zDb, pConfig->zName ); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0); sqlite3_free(zSql); } if( rc!=SQLITE_OK ){ p->rc = rc; return; } } sqlite3_bind_int64(p->pDeleter, 1, iFirst); sqlite3_bind_int64(p->pDeleter, 2, iLast); sqlite3_step(p->pDeleter); p->rc = sqlite3_reset(p->pDeleter); } /* ** Remove all records associated with segment iSegid. */ static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){ i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0); i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1; fts5DataDelete(p, iFirst, iLast); if( p->pIdxDeleter==0 ){ Fts5Config *pConfig = p->pConfig; fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf( "DELETE FROM '%q'.'%q_idx' WHERE segid=?", pConfig->zDb, pConfig->zName )); } if( p->rc==SQLITE_OK ){ sqlite3_bind_int(p->pIdxDeleter, 1, iSegid); sqlite3_step(p->pIdxDeleter); p->rc = sqlite3_reset(p->pIdxDeleter); } } /* ** Release a reference to an Fts5Structure object returned by an earlier ** call to fts5StructureRead() or fts5StructureDecode(). */ static void fts5StructureRelease(Fts5Structure *pStruct){ if( pStruct && 0>=(--pStruct->nRef) ){ int i; assert( pStruct->nRef==0 ); for(i=0; i<pStruct->nLevel; i++){ sqlite3_free(pStruct->aLevel[i].aSeg); } sqlite3_free(pStruct); } } static void fts5StructureRef(Fts5Structure *pStruct){ pStruct->nRef++; } /* ** Deserialize and return the structure record currently stored in serialized ** form within buffer pData/nData. ** ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array ** are over-allocated by one slot. This allows the structure contents ** to be more easily edited. ** ** If an error occurs, *ppOut is set to NULL and an SQLite error code ** returned. Otherwise, *ppOut is set to point to the new object and ** SQLITE_OK returned. */ static int fts5StructureDecode( const u8 *pData, /* Buffer containing serialized structure */ int nData, /* Size of buffer pData in bytes */ int *piCookie, /* Configuration cookie value */ Fts5Structure **ppOut /* OUT: Deserialized object */ ){ int rc = SQLITE_OK; int i = 0; int iLvl; int nLevel = 0; int nSegment = 0; int nByte; /* Bytes of space to allocate at pRet */ Fts5Structure *pRet = 0; /* Structure object to return */ /* Grab the cookie value */ if( piCookie ) *piCookie = sqlite3Fts5Get32(pData); i = 4; /* Read the total number of levels and segments from the start of the ** structure record. */ i += fts5GetVarint32(&pData[i], nLevel); i += fts5GetVarint32(&pData[i], nSegment); nByte = ( sizeof(Fts5Structure) + /* Main structure */ sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */ ); pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte); if( pRet ){ pRet->nRef = 1; pRet->nLevel = nLevel; pRet->nSegment = nSegment; i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter); for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){ Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl]; int nTotal = 0; int iSeg; if( i>=nData ){ rc = FTS5_CORRUPT; }else{ i += fts5GetVarint32(&pData[i], pLvl->nMerge); i += fts5GetVarint32(&pData[i], nTotal); assert( nTotal>=pLvl->nMerge ); pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc, nTotal * sizeof(Fts5StructureSegment) ); } if( rc==SQLITE_OK ){ pLvl->nSeg = nTotal; for(iSeg=0; iSeg<nTotal; iSeg++){ if( i>=nData ){ rc = FTS5_CORRUPT; break; } i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid); i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst); i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast); } } } if( rc!=SQLITE_OK ){ fts5StructureRelease(pRet); pRet = 0; } } *ppOut = pRet; return rc; } /* ** */ static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){ if( *pRc==SQLITE_OK ){ Fts5Structure *pStruct = *ppStruct; int nLevel = pStruct->nLevel; int nByte = ( sizeof(Fts5Structure) + /* Main structure */ sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */ ); pStruct = sqlite3_realloc(pStruct, nByte); if( pStruct ){ memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel)); pStruct->nLevel++; *ppStruct = pStruct; }else{ *pRc = SQLITE_NOMEM; } } } /* ** Extend level iLvl so that there is room for at least nExtra more ** segments. */ static void fts5StructureExtendLevel( int *pRc, Fts5Structure *pStruct, int iLvl, int nExtra, int bInsert ){ if( *pRc==SQLITE_OK ){ Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl]; Fts5StructureSegment *aNew; int nByte; nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment); aNew = sqlite3_realloc(pLvl->aSeg, nByte); if( aNew ){ if( bInsert==0 ){ memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra); }else{ int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment); memmove(&aNew[nExtra], aNew, nMove); memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra); } pLvl->aSeg = aNew; }else{ *pRc = SQLITE_NOMEM; } } } static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){ Fts5Structure *pRet = 0; Fts5Config *pConfig = p->pConfig; int iCookie; /* Configuration cookie */ Fts5Data *pData; pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID); if( p->rc==SQLITE_OK ){ /* TODO: Do we need this if the leaf-index is appended? Probably... */ memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING); p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet); if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){ p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie); } fts5DataRelease(pData); if( p->rc!=SQLITE_OK ){ fts5StructureRelease(pRet); pRet = 0; } } return pRet; } static i64 fts5IndexDataVersion(Fts5Index *p){ i64 iVersion = 0; if( p->rc==SQLITE_OK ){ if( p->pDataVersion==0 ){ p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion, sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb) ); if( p->rc ) return 0; } if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){ iVersion = sqlite3_column_int64(p->pDataVersion, 0); } p->rc = sqlite3_reset(p->pDataVersion); } return iVersion; } /* ** Read, deserialize and return the structure record. ** ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array ** are over-allocated as described for function fts5StructureDecode() ** above. ** ** If an error occurs, NULL is returned and an error code left in the ** Fts5Index handle. If an error has already occurred when this function ** is called, it is a no-op. */ static Fts5Structure *fts5StructureRead(Fts5Index *p){ if( p->pStruct==0 ){ p->iStructVersion = fts5IndexDataVersion(p); if( p->rc==SQLITE_OK ){ p->pStruct = fts5StructureReadUncached(p); } } #if 0 else{ Fts5Structure *pTest = fts5StructureReadUncached(p); if( pTest ){ int i, j; assert_nc( p->pStruct->nSegment==pTest->nSegment ); assert_nc( p->pStruct->nLevel==pTest->nLevel ); for(i=0; i<pTest->nLevel; i++){ assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge ); assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg ); for(j=0; j<pTest->aLevel[i].nSeg; j++){ Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j]; Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j]; assert_nc( p1->iSegid==p2->iSegid ); assert_nc( p1->pgnoFirst==p2->pgnoFirst ); assert_nc( p1->pgnoLast==p2->pgnoLast ); } } fts5StructureRelease(pTest); } } #endif if( p->rc!=SQLITE_OK ) return 0; assert( p->iStructVersion!=0 ); assert( p->pStruct!=0 ); fts5StructureRef(p->pStruct); return p->pStruct; } static void fts5StructureInvalidate(Fts5Index *p){ if( p->pStruct ){ fts5StructureRelease(p->pStruct); p->pStruct = 0; } } /* ** Return the total number of segments in index structure pStruct. This ** function is only ever used as part of assert() conditions. */ #ifdef SQLITE_DEBUG static int fts5StructureCountSegments(Fts5Structure *pStruct){ int nSegment = 0; /* Total number of segments */ if( pStruct ){ int iLvl; /* Used to iterate through levels */ for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){ nSegment += pStruct->aLevel[iLvl].nSeg; } } return nSegment; } #endif #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \ assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \ memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \ (pBuf)->n += nBlob; \ } #define fts5BufferSafeAppendVarint(pBuf, iVal) { \ (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \ assert( (pBuf)->nSpace>=(pBuf)->n ); \ } /* ** Serialize and store the "structure" record. ** ** If an error occurs, leave an error code in the Fts5Index object. If an ** error has already occurred, this function is a no-op. */ static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){ if( p->rc==SQLITE_OK ){ Fts5Buffer buf; /* Buffer to serialize record into */ int iLvl; /* Used to iterate through levels */ int iCookie; /* Cookie value to store */ assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) ); memset(&buf, 0, sizeof(Fts5Buffer)); /* Append the current configuration cookie */ iCookie = p->pConfig->iCookie; if( iCookie<0 ) iCookie = 0; if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){ sqlite3Fts5Put32(buf.p, iCookie); buf.n = 4; fts5BufferSafeAppendVarint(&buf, pStruct->nLevel); fts5BufferSafeAppendVarint(&buf, pStruct->nSegment); fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter); } for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){ int iSeg; /* Used to iterate through segments */ Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl]; fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge); fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg); assert( pLvl->nMerge<=pLvl->nSeg ); for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){ fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid); fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst); fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast); } } fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n); fts5BufferFree(&buf); } } #if 0 static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*); static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){ int rc = SQLITE_OK; Fts5Buffer buf; memset(&buf, 0, sizeof(buf)); fts5DebugStructure(&rc, &buf, pStruct); fprintf(stdout, "%s: %s\n", zCaption, buf.p); fflush(stdout); fts5BufferFree(&buf); } #else # define fts5PrintStructure(x,y) #endif static int fts5SegmentSize(Fts5StructureSegment *pSeg){ return 1 + pSeg->pgnoLast - pSeg->pgnoFirst; } /* ** Return a copy of index structure pStruct. Except, promote as many ** segments as possible to level iPromote. If an OOM occurs, NULL is ** returned. */ static void fts5StructurePromoteTo( Fts5Index *p, int iPromote, int szPromote, Fts5Structure *pStruct ){ int il, is; Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote]; if( pOut->nMerge==0 ){ for(il=iPromote+1; il<pStruct->nLevel; il++){ Fts5StructureLevel *pLvl = &pStruct->aLevel[il]; if( pLvl->nMerge ) return; for(is=pLvl->nSeg-1; is>=0; is--){ int sz = fts5SegmentSize(&pLvl->aSeg[is]); if( sz>szPromote ) return; fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1); if( p->rc ) return; memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment)); pOut->nSeg++; pLvl->nSeg--; } } } } /* ** A new segment has just been written to level iLvl of index structure ** pStruct. This function determines if any segments should be promoted ** as a result. Segments are promoted in two scenarios: ** ** a) If the segment just written is smaller than one or more segments ** within the previous populated level, it is promoted to the previous ** populated level. ** ** b) If the segment just written is larger than the newest segment on ** the next populated level, then that segment, and any other adjacent ** segments that are also smaller than the one just written, are ** promoted. ** ** If one or more segments are promoted, the structure object is updated ** to reflect this. */ static void fts5StructurePromote( Fts5Index *p, /* FTS5 backend object */ int iLvl, /* Index level just updated */ Fts5Structure *pStruct /* Index structure */ ){ if( p->rc==SQLITE_OK ){ int iTst; int iPromote = -1; int szPromote = 0; /* Promote anything this size or smaller */ Fts5StructureSegment *pSeg; /* Segment just written */ int szSeg; /* Size of segment just written */ int nSeg = pStruct->aLevel[iLvl].nSeg; if( nSeg==0 ) return; pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1]; szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst); /* Check for condition (a) */ for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--); if( iTst>=0 ){ int i; int szMax = 0; Fts5StructureLevel *pTst = &pStruct->aLevel[iTst]; assert( pTst->nMerge==0 ); for(i=0; i<pTst->nSeg; i++){ int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1; if( sz>szMax ) szMax = sz; } if( szMax>=szSeg ){ /* Condition (a) is true. Promote the newest segment on level ** iLvl to level iTst. */ iPromote = iTst; szPromote = szMax; } } /* If condition (a) is not met, assume (b) is true. StructurePromoteTo() ** is a no-op if it is not. */ if( iPromote<0 ){ iPromote = iLvl; szPromote = szSeg; } fts5StructurePromoteTo(p, iPromote, szPromote, pStruct); } } /* ** Advance the iterator passed as the only argument. If the end of the ** doclist-index page is reached, return non-zero. */ static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){ Fts5Data *pData = pLvl->pData; if( pLvl->iOff==0 ){ assert( pLvl->bEof==0 ); pLvl->iOff = 1; pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno); pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid); pLvl->iFirstOff = pLvl->iOff; }else{ int iOff; for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){ if( pData->p[iOff] ) break; } if( iOff<pData->nn ){ i64 iVal; pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1; iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal); pLvl->iRowid += iVal; pLvl->iOff = iOff; }else{ pLvl->bEof = 1; } } return pLvl->bEof; } /* ** Advance the iterator passed as the only argument. */ static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){ Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl]; assert( iLvl<pIter->nLvl ); if( fts5DlidxLvlNext(pLvl) ){ if( (iLvl+1) < pIter->nLvl ){ fts5DlidxIterNextR(p, pIter, iLvl+1); if( pLvl[1].bEof==0 ){ fts5DataRelease(pLvl->pData); memset(pLvl, 0, sizeof(Fts5DlidxLvl)); pLvl->pData = fts5DataRead(p, FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno) ); if( pLvl->pData ) fts5DlidxLvlNext(pLvl); } } } return pIter->aLvl[0].bEof; } static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){ return fts5DlidxIterNextR(p, pIter, 0); } /* ** The iterator passed as the first argument has the following fields set ** as follows. This function sets up the rest of the iterator so that it ** points to the first rowid in the doclist-index. ** ** pData: ** pointer to doclist-index record, ** ** When this function is called pIter->iLeafPgno is the page number the ** doclist is associated with (the one featuring the term). */ static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){ int i; for(i=0; i<pIter->nLvl; i++){ fts5DlidxLvlNext(&pIter->aLvl[i]); } return pIter->aLvl[0].bEof; } static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){ return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof; } static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){ int i; /* Advance each level to the last entry on the last page */ for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){ Fts5DlidxLvl *pLvl = &pIter->aLvl[i]; while( fts5DlidxLvlNext(pLvl)==0 ); pLvl->bEof = 0; if( i>0 ){ Fts5DlidxLvl *pChild = &pLvl[-1]; fts5DataRelease(pChild->pData); memset(pChild, 0, sizeof(Fts5DlidxLvl)); pChild->pData = fts5DataRead(p, FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno) ); } } } /* ** Move the iterator passed as the only argument to the previous entry. */ static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){ int iOff = pLvl->iOff; assert( pLvl->bEof==0 ); if( iOff<=pLvl->iFirstOff ){ pLvl->bEof = 1; }else{ u8 *a = pLvl->pData->p; i64 iVal; int iLimit; int ii; int nZero = 0; /* Currently iOff points to the first byte of a varint. This block ** decrements iOff until it points to the first byte of the previous ** varint. Taking care not to read any memory locations that occur ** before the buffer in memory. */ iLimit = (iOff>9 ? iOff-9 : 0); for(iOff--; iOff>iLimit; iOff--){ if( (a[iOff-1] & 0x80)==0 ) break; } fts5GetVarint(&a[iOff], (u64*)&iVal); pLvl->iRowid -= iVal; pLvl->iLeafPgno--; /* Skip backwards past any 0x00 varints. */ for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){ nZero++; } if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){ /* The byte immediately before the last 0x00 byte has the 0x80 bit ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80 ** bytes before a[ii]. */ int bZero = 0; /* True if last 0x00 counts */ if( (ii-8)>=pLvl->iFirstOff ){ int j; for(j=1; j<=8 && (a[ii-j] & 0x80); j++); bZero = (j>8); } if( bZero==0 ) nZero--; } pLvl->iLeafPgno -= nZero; pLvl->iOff = iOff - nZero; } return pLvl->bEof; } static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){ Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl]; assert( iLvl<pIter->nLvl ); if( fts5DlidxLvlPrev(pLvl) ){ if( (iLvl+1) < pIter->nLvl ){ fts5DlidxIterPrevR(p, pIter, iLvl+1); if( pLvl[1].bEof==0 ){ fts5DataRelease(pLvl->pData); memset(pLvl, 0, sizeof(Fts5DlidxLvl)); pLvl->pData = fts5DataRead(p, FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno) ); if( pLvl->pData ){ while( fts5DlidxLvlNext(pLvl)==0 ); pLvl->bEof = 0; } } } } return pIter->aLvl[0].bEof; } static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){ return fts5DlidxIterPrevR(p, pIter, 0); } /* ** Free a doclist-index iterator object allocated by fts5DlidxIterInit(). */ static void fts5DlidxIterFree(Fts5DlidxIter *pIter){ if( pIter ){ int i; for(i=0; i<pIter->nLvl; i++){ fts5DataRelease(pIter->aLvl[i].pData); } sqlite3_free(pIter); } } static Fts5DlidxIter *fts5DlidxIterInit( Fts5Index *p, /* Fts5 Backend to iterate within */ int bRev, /* True for ORDER BY ASC */ int iSegid, /* Segment id */ int iLeafPg /* Leaf page number to load dlidx for */ ){ Fts5DlidxIter *pIter = 0; int i; int bDone = 0; for(i=0; p->rc==SQLITE_OK && bDone==0; i++){ int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl); Fts5DlidxIter *pNew; pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte); if( pNew==0 ){ p->rc = SQLITE_NOMEM; }else{ i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg); Fts5DlidxLvl *pLvl = &pNew->aLvl[i]; pIter = pNew; memset(pLvl, 0, sizeof(Fts5DlidxLvl)); pLvl->pData = fts5DataRead(p, iRowid); if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){ bDone = 1; } pIter->nLvl = i+1; } } if( p->rc==SQLITE_OK ){ pIter->iSegid = iSegid; if( bRev==0 ){ fts5DlidxIterFirst(pIter); }else{ fts5DlidxIterLast(p, pIter); } } if( p->rc!=SQLITE_OK ){ fts5DlidxIterFree(pIter); pIter = 0; } return pIter; } static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){ return pIter->aLvl[0].iRowid; } static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){ return pIter->aLvl[0].iLeafPgno; } /* ** Load the next leaf page into the segment iterator. */ static void fts5SegIterNextPage( Fts5Index *p, /* FTS5 backend object */ Fts5SegIter *pIter /* Iterator to advance to next page */ ){ Fts5Data *pLeaf; Fts5StructureSegment *pSeg = pIter->pSeg; fts5DataRelease(pIter->pLeaf); pIter->iLeafPgno++; if( pIter->pNextLeaf ){ pIter->pLeaf = pIter->pNextLeaf; pIter->pNextLeaf = 0; }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){ pIter->pLeaf = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno) ); }else{ pIter->pLeaf = 0; } pLeaf = pIter->pLeaf; if( pLeaf ){ pIter->iPgidxOff = pLeaf->szLeaf; if( fts5LeafIsTermless(pLeaf) ){ pIter->iEndofDoclist = pLeaf->nn+1; }else{ pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff], pIter->iEndofDoclist ); } } } /* ** Argument p points to a buffer containing a varint to be interpreted as a ** position list size field. Read the varint and return the number of bytes ** read. Before returning, set *pnSz to the number of bytes in the position ** list, and *pbDel to true if the delete flag is set, or false otherwise. */ static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){ int nSz; int n = 0; fts5FastGetVarint32(p, n, nSz); assert_nc( nSz>=0 ); *pnSz = nSz/2; *pbDel = nSz & 0x0001; return n; } /* ** Fts5SegIter.iLeafOffset currently points to the first byte of a ** position-list size field. Read the value of the field and store it ** in the following variables: ** ** Fts5SegIter.nPos ** Fts5SegIter.bDel ** ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the ** position list content (if any). */ static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){ if( p->rc==SQLITE_OK ){ int iOff = pIter->iLeafOffset; /* Offset to read at */ ASSERT_SZLEAF_OK(pIter->pLeaf); if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){ int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf); pIter->bDel = 0; pIter->nPos = 1; if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){ pIter->bDel = 1; iOff++; if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){ pIter->nPos = 1; iOff++; }else{ pIter->nPos = 0; } } }else{ int nSz; fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz); pIter->bDel = (nSz & 0x0001); pIter->nPos = nSz>>1; assert_nc( pIter->nPos>=0 ); } pIter->iLeafOffset = iOff; } } static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){ u8 *a = pIter->pLeaf->p; /* Buffer to read data from */ int iOff = pIter->iLeafOffset; ASSERT_SZLEAF_OK(pIter->pLeaf); if( iOff>=pIter->pLeaf->szLeaf ){ fts5SegIterNextPage(p, pIter); if( pIter->pLeaf==0 ){ if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT; return; } iOff = 4; a = pIter->pLeaf->p; } iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid); pIter->iLeafOffset = iOff; } /* ** Fts5SegIter.iLeafOffset currently points to the first byte of the ** "nSuffix" field of a term. Function parameter nKeep contains the value ** of the "nPrefix" field (if there was one - it is passed 0 if this is ** the first term in the segment). ** ** This function populates: ** ** Fts5SegIter.term ** Fts5SegIter.rowid ** ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of ** the first position list. The position list belonging to document ** (Fts5SegIter.iRowid). */ static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){ u8 *a = pIter->pLeaf->p; /* Buffer to read data from */ int iOff = pIter->iLeafOffset; /* Offset to read at */ int nNew; /* Bytes of new data */ iOff += fts5GetVarint32(&a[iOff], nNew); if( iOff+nNew>pIter->pLeaf->nn ){ p->rc = FTS5_CORRUPT; return; } pIter->term.n = nKeep; fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]); iOff += nNew; pIter->iTermLeafOffset = iOff; pIter->iTermLeafPgno = pIter->iLeafPgno; pIter->iLeafOffset = iOff; if( pIter->iPgidxOff>=pIter->pLeaf->nn ){ pIter->iEndofDoclist = pIter->pLeaf->nn+1; }else{ int nExtra; pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra); pIter->iEndofDoclist += nExtra; } fts5SegIterLoadRowid(p, pIter); } static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*); static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*); static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*); static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){ if( pIter->flags & FTS5_SEGITER_REVERSE ){ pIter->xNext = fts5SegIterNext_Reverse; }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){ pIter->xNext = fts5SegIterNext_None; }else{ pIter->xNext = fts5SegIterNext; } } /* ** Initialize the iterator object pIter to iterate through the entries in ** segment pSeg. The iterator is left pointing to the first entry when ** this function returns. ** ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If ** an error has already occurred when this function is called, it is a no-op. */ static void fts5SegIterInit( Fts5Index *p, /* FTS index object */ Fts5StructureSegment *pSeg, /* Description of segment */ Fts5SegIter *pIter /* Object to populate */ ){ if( pSeg->pgnoFirst==0 ){ /* This happens if the segment is being used as an input to an incremental ** merge and all data has already been "trimmed". See function ** fts5TrimSegments() for details. In this case leave the iterator empty. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is ** at EOF already. */ assert( pIter->pLeaf==0 ); return; } if( p->rc==SQLITE_OK ){ memset(pIter, 0, sizeof(*pIter)); fts5SegIterSetNext(p, pIter); pIter->pSeg = pSeg; pIter->iLeafPgno = pSeg->pgnoFirst-1; fts5SegIterNextPage(p, pIter); } if( p->rc==SQLITE_OK ){ pIter->iLeafOffset = 4; assert_nc( pIter->pLeaf->nn>4 ); assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 ); pIter->iPgidxOff = pIter->pLeaf->szLeaf+1; fts5SegIterLoadTerm(p, pIter, 0); fts5SegIterLoadNPos(p, pIter); } } /* ** This function is only ever called on iterators created by calls to ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set. ** ** The iterator is in an unusual state when this function is called: the ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of ** the position-list size field for the first relevant rowid on the page. ** Fts5SegIter.rowid is set, but nPos and bDel are not. ** ** This function advances the iterator so that it points to the last ** relevant rowid on the page and, if necessary, initializes the ** aRowidOffset[] and iRowidOffset variables. At this point the iterator ** is in its regular state - Fts5SegIter.iLeafOffset points to the first ** byte of the position list content associated with said rowid. */ static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){ int eDetail = p->pConfig->eDetail; int n = pIter->pLeaf->szLeaf; int i = pIter->iLeafOffset; u8 *a = pIter->pLeaf->p; int iRowidOffset = 0; if( n>pIter->iEndofDoclist ){ n = pIter->iEndofDoclist; } ASSERT_SZLEAF_OK(pIter->pLeaf); while( 1 ){ i64 iDelta = 0; if( eDetail==FTS5_DETAIL_NONE ){ /* todo */ if( i<n && a[i]==0 ){ i++; if( i<n && a[i]==0 ) i++; } }else{ int nPos; int bDummy; i += fts5GetPoslistSize(&a[i], &nPos, &bDummy); i += nPos; } if( i>=n ) break; i += fts5GetVarint(&a[i], (u64*)&iDelta); pIter->iRowid += iDelta; /* If necessary, grow the pIter->aRowidOffset[] array. */ if( iRowidOffset>=pIter->nRowidOffset ){ int nNew = pIter->nRowidOffset + 8; int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int)); if( aNew==0 ){ p->rc = SQLITE_NOMEM; break; } pIter->aRowidOffset = aNew; pIter->nRowidOffset = nNew; } pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset; pIter->iLeafOffset = i; } pIter->iRowidOffset = iRowidOffset; fts5SegIterLoadNPos(p, pIter); } /* ** */ static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){ assert( pIter->flags & FTS5_SEGITER_REVERSE ); assert( pIter->flags & FTS5_SEGITER_ONETERM ); fts5DataRelease(pIter->pLeaf); pIter->pLeaf = 0; while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){ Fts5Data *pNew; pIter->iLeafPgno--; pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID( pIter->pSeg->iSegid, pIter->iLeafPgno )); if( pNew ){ /* iTermLeafOffset may be equal to szLeaf if the term is the last ** thing on the page - i.e. the first rowid is on the following page. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */ if( pIter->iLeafPgno==pIter->iTermLeafPgno ){ assert( pIter->pLeaf==0 ); if( pIter->iTermLeafOffset<pNew->szLeaf ){ pIter->pLeaf = pNew; pIter->iLeafOffset = pIter->iTermLeafOffset; } }else{ int iRowidOff; iRowidOff = fts5LeafFirstRowidOff(pNew); if( iRowidOff ){ pIter->pLeaf = pNew; pIter->iLeafOffset = iRowidOff; } } if( pIter->pLeaf ){ u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset]; pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid); break; }else{ fts5DataRelease(pNew); } } } if( pIter->pLeaf ){ pIter->iEndofDoclist = pIter->pLeaf->nn+1; fts5SegIterReverseInitPage(p, pIter); } } /* ** Return true if the iterator passed as the second argument currently ** points to a delete marker. A delete marker is an entry with a 0 byte ** position-list. */ static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){ Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst]; return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0); } /* ** Advance iterator pIter to the next entry. ** ** This version of fts5SegIterNext() is only used by reverse iterators. */ static void fts5SegIterNext_Reverse( Fts5Index *p, /* FTS5 backend object */ Fts5SegIter *pIter, /* Iterator to advance */ int *pbUnused /* Unused */ ){ assert( pIter->flags & FTS5_SEGITER_REVERSE ); assert( pIter->pNextLeaf==0 ); UNUSED_PARAM(pbUnused); if( pIter->iRowidOffset>0 ){ u8 *a = pIter->pLeaf->p; int iOff; i64 iDelta; pIter->iRowidOffset--; pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset]; fts5SegIterLoadNPos(p, pIter); iOff = pIter->iLeafOffset; if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){ iOff += pIter->nPos; } fts5GetVarint(&a[iOff], (u64*)&iDelta); pIter->iRowid -= iDelta; }else{ fts5SegIterReverseNewPage(p, pIter); } } /* ** Advance iterator pIter to the next entry. ** ** This version of fts5SegIterNext() is only used if detail=none and the ** iterator is not a reverse direction iterator. */ static void fts5SegIterNext_None( Fts5Index *p, /* FTS5 backend object */ Fts5SegIter *pIter, /* Iterator to advance */ int *pbNewTerm /* OUT: Set for new term */ ){ int iOff; assert( p->rc==SQLITE_OK ); assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 ); assert( p->pConfig->eDetail==FTS5_DETAIL_NONE ); ASSERT_SZLEAF_OK(pIter->pLeaf); iOff = pIter->iLeafOffset; /* Next entry is on the next page */ if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){ fts5SegIterNextPage(p, pIter); if( p->rc || pIter->pLeaf==0 ) return; pIter->iRowid = 0; iOff = 4; } if( iOff<pIter->iEndofDoclist ){ /* Next entry is on the current page */ i64 iDelta; iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta); pIter->iLeafOffset = iOff; pIter->iRowid += iDelta; }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){ if( pIter->pSeg ){ int nKeep = 0; if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){ iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep); } pIter->iLeafOffset = iOff; fts5SegIterLoadTerm(p, pIter, nKeep); }else{ const u8 *pList = 0; const char *zTerm = 0; int nList; sqlite3Fts5HashScanNext(p->pHash); sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList); if( pList==0 ) goto next_none_eof; pIter->pLeaf->p = (u8*)pList; pIter->pLeaf->nn = nList; pIter->pLeaf->szLeaf = nList; pIter->iEndofDoclist = nList; sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm); pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid); } if( pbNewTerm ) *pbNewTerm = 1; }else{ goto next_none_eof; } fts5SegIterLoadNPos(p, pIter); return; next_none_eof: fts5DataRelease(pIter->pLeaf); pIter->pLeaf = 0; } /* ** Advance iterator pIter to the next entry. ** ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It ** is not considered an error if the iterator reaches EOF. If an error has ** already occurred when this function is called, it is a no-op. */ static void fts5SegIterNext( Fts5Index *p, /* FTS5 backend object */ Fts5SegIter *pIter, /* Iterator to advance */ int *pbNewTerm /* OUT: Set for new term */ ){ Fts5Data *pLeaf = pIter->pLeaf; int iOff; int bNewTerm = 0; int nKeep = 0; u8 *a; int n; assert( pbNewTerm==0 || *pbNewTerm==0 ); assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE ); /* Search for the end of the position list within the current page. */ a = pLeaf->p; n = pLeaf->szLeaf; ASSERT_SZLEAF_OK(pLeaf); iOff = pIter->iLeafOffset + pIter->nPos; if( iOff<n ){ /* The next entry is on the current page. */ assert_nc( iOff<=pIter->iEndofDoclist ); if( iOff>=pIter->iEndofDoclist ){ bNewTerm = 1; if( iOff!=fts5LeafFirstTermOff(pLeaf) ){ iOff += fts5GetVarint32(&a[iOff], nKeep); } }else{ u64 iDelta; iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta); pIter->iRowid += iDelta; assert_nc( iDelta>0 ); } pIter->iLeafOffset = iOff; }else if( pIter->pSeg==0 ){ const u8 *pList = 0; const char *zTerm = 0; int nList = 0; assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm ); if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){ sqlite3Fts5HashScanNext(p->pHash); sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList); } if( pList==0 ){ fts5DataRelease(pIter->pLeaf); pIter->pLeaf = 0; }else{ pIter->pLeaf->p = (u8*)pList; pIter->pLeaf->nn = nList; pIter->pLeaf->szLeaf = nList; pIter->iEndofDoclist = nList+1; sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm), (u8*)zTerm); pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid); *pbNewTerm = 1; } }else{ iOff = 0; /* Next entry is not on the current page */ while( iOff==0 ){ fts5SegIterNextPage(p, pIter); pLeaf = pIter->pLeaf; if( pLeaf==0 ) break; ASSERT_SZLEAF_OK(pLeaf); if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){ iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid); pIter->iLeafOffset = iOff; if( pLeaf->nn>pLeaf->szLeaf ){ pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32( &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist ); } } else if( pLeaf->nn>pLeaf->szLeaf ){ pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32( &pLeaf->p[pLeaf->szLeaf], iOff ); pIter->iLeafOffset = iOff; pIter->iEndofDoclist = iOff; bNewTerm = 1; } assert_nc( iOff<pLeaf->szLeaf ); if( iOff>pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; return; } } } /* Check if the iterator is now at EOF. If so, return early. */ if( pIter->pLeaf ){ if( bNewTerm ){ if( pIter->flags & FTS5_SEGITER_ONETERM ){ fts5DataRelease(pIter->pLeaf); pIter->pLeaf = 0; }else{ fts5SegIterLoadTerm(p, pIter, nKeep); fts5SegIterLoadNPos(p, pIter); if( pbNewTerm ) *pbNewTerm = 1; } }else{ /* The following could be done by calling fts5SegIterLoadNPos(). But ** this block is particularly performance critical, so equivalent ** code is inlined. ** ** Later: Switched back to fts5SegIterLoadNPos() because it supports ** detail=none mode. Not ideal. */ int nSz; assert( p->rc==SQLITE_OK ); assert( pIter->iLeafOffset<=pIter->pLeaf->nn ); fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz); pIter->bDel = (nSz & 0x0001); pIter->nPos = nSz>>1; assert_nc( pIter->nPos>=0 ); } } } #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; } #define fts5IndexSkipVarint(a, iOff) { \ int iEnd = iOff+9; \ while( (a[iOff++] & 0x80) && iOff<iEnd ); \ } /* ** Iterator pIter currently points to the first rowid in a doclist. This ** function sets the iterator up so that iterates in reverse order through ** the doclist. */ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){ Fts5DlidxIter *pDlidx = pIter->pDlidx; Fts5Data *pLast = 0; int pgnoLast = 0; if( pDlidx ){ int iSegid = pIter->pSeg->iSegid; pgnoLast = fts5DlidxIterPgno(pDlidx); pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast)); }else{ Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */ /* Currently, Fts5SegIter.iLeafOffset points to the first byte of ** position-list content for the current rowid. Back it up so that it ** points to the start of the position-list size field. */ int iPoslist; if( pIter->iTermLeafPgno==pIter->iLeafPgno ){ iPoslist = pIter->iTermLeafOffset; }else{ iPoslist = 4; } fts5IndexSkipVarint(pLeaf->p, iPoslist); pIter->iLeafOffset = iPoslist; /* If this condition is true then the largest rowid for the current ** term may not be stored on the current page. So search forward to ** see where said rowid really is. */ if( pIter->iEndofDoclist>=pLeaf->szLeaf ){ int pgno; Fts5StructureSegment *pSeg = pIter->pSeg; /* The last rowid in the doclist may not be on the current page. Search ** forward to find the page containing the last rowid. */ for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){ i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno); Fts5Data *pNew = fts5DataRead(p, iAbs); if( pNew ){ int iRowid, bTermless; iRowid = fts5LeafFirstRowidOff(pNew); bTermless = fts5LeafIsTermless(pNew); if( iRowid ){ SWAPVAL(Fts5Data*, pNew, pLast); pgnoLast = pgno; } fts5DataRelease(pNew); if( bTermless==0 ) break; } } } } /* If pLast is NULL at this point, then the last rowid for this doclist ** lies on the page currently indicated by the iterator. In this case ** pIter->iLeafOffset is already set to point to the position-list size ** field associated with the first relevant rowid on the page. ** ** Or, if pLast is non-NULL, then it is the page that contains the last ** rowid. In this case configure the iterator so that it points to the ** first rowid on this page. */ if( pLast ){ int iOff; fts5DataRelease(pIter->pLeaf); pIter->pLeaf = pLast; pIter->iLeafPgno = pgnoLast; iOff = fts5LeafFirstRowidOff(pLast); iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid); pIter->iLeafOffset = iOff; if( fts5LeafIsTermless(pLast) ){ pIter->iEndofDoclist = pLast->nn+1; }else{ pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast); } } fts5SegIterReverseInitPage(p, pIter); } /* ** Iterator pIter currently points to the first rowid of a doclist. ** There is a doclist-index associated with the final term on the current ** page. If the current term is the last term on the page, load the ** doclist-index from disk and initialize an iterator at (pIter->pDlidx). */ static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){ int iSeg = pIter->pSeg->iSegid; int bRev = (pIter->flags & FTS5_SEGITER_REVERSE); Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */ assert( pIter->flags & FTS5_SEGITER_ONETERM ); assert( pIter->pDlidx==0 ); /* Check if the current doclist ends on this page. If it does, return ** early without loading the doclist-index (as it belongs to a different ** term. */ if( pIter->iTermLeafPgno==pIter->iLeafPgno && pIter->iEndofDoclist<pLeaf->szLeaf ){ return; } pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno); } /* ** The iterator object passed as the second argument currently contains ** no valid values except for the Fts5SegIter.pLeaf member variable. This ** function searches the leaf page for a term matching (pTerm/nTerm). ** ** If the specified term is found on the page, then the iterator is left ** pointing to it. If argument bGe is zero and the term is not found, ** the iterator is left pointing at EOF. ** ** If bGe is non-zero and the specified term is not found, then the ** iterator is left pointing to the smallest term in the segment that ** is larger than the specified term, even if this term is not on the ** current page. */ static void fts5LeafSeek( Fts5Index *p, /* Leave any error code here */ int bGe, /* True for a >= search */ Fts5SegIter *pIter, /* Iterator to seek */ const u8 *pTerm, int nTerm /* Term to search for */ ){ int iOff; const u8 *a = pIter->pLeaf->p; int szLeaf = pIter->pLeaf->szLeaf; int n = pIter->pLeaf->nn; int nMatch = 0; int nKeep = 0; int nNew = 0; int iTermOff; int iPgidx; /* Current offset in pgidx */ int bEndOfPage = 0; assert( p->rc==SQLITE_OK ); iPgidx = szLeaf; iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff); iOff = iTermOff; if( iOff>n ){ p->rc = FTS5_CORRUPT; return; } while( 1 ){ /* Figure out how many new bytes are in this term */ fts5FastGetVarint32(a, iOff, nNew); if( nKeep<nMatch ){ goto search_failed; } assert( nKeep>=nMatch ); if( nKeep==nMatch ){ int nCmp; int i; nCmp = MIN(nNew, nTerm-nMatch); for(i=0; i<nCmp; i++){ if( a[iOff+i]!=pTerm[nMatch+i] ) break; } nMatch += i; if( nTerm==nMatch ){ if( i==nNew ){ goto search_success; }else{ goto search_failed; } }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){ goto search_failed; } } if( iPgidx>=n ){ bEndOfPage = 1; break; } iPgidx += fts5GetVarint32(&a[iPgidx], nKeep); iTermOff += nKeep; iOff = iTermOff; if( iOff>=n ){ p->rc = FTS5_CORRUPT; return; } /* Read the nKeep field of the next term. */ fts5FastGetVarint32(a, iOff, nKeep); } search_failed: if( bGe==0 ){ fts5DataRelease(pIter->pLeaf); pIter->pLeaf = 0; return; }else if( bEndOfPage ){ do { fts5SegIterNextPage(p, pIter); if( pIter->pLeaf==0 ) return; a = pIter->pLeaf->p; if( fts5LeafIsTermless(pIter->pLeaf)==0 ){ iPgidx = pIter->pLeaf->szLeaf; iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff); if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; }else{ nKeep = 0; iTermOff = iOff; n = pIter->pLeaf->nn; iOff += fts5GetVarint32(&a[iOff], nNew); break; } } }while( 1 ); } search_success: pIter->iLeafOffset = iOff + nNew; pIter->iTermLeafOffset = pIter->iLeafOffset; pIter->iTermLeafPgno = pIter->iLeafPgno; fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm); fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]); if( iPgidx>=n ){ pIter->iEndofDoclist = pIter->pLeaf->nn+1; }else{ int nExtra; iPgidx += fts5GetVarint32(&a[iPgidx], nExtra); pIter->iEndofDoclist = iTermOff + nExtra; } pIter->iPgidxOff = iPgidx; fts5SegIterLoadRowid(p, pIter); fts5SegIterLoadNPos(p, pIter); } static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){ if( p->pIdxSelect==0 ){ Fts5Config *pConfig = p->pConfig; fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf( "SELECT pgno FROM '%q'.'%q_idx' WHERE " "segid=? AND term<=? ORDER BY term DESC LIMIT 1", pConfig->zDb, pConfig->zName )); } return p->pIdxSelect; } /* ** Initialize the object pIter to point to term pTerm/nTerm within segment ** pSeg. If there is no such term in the index, the iterator is set to EOF. ** ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If ** an error has already occurred when this function is called, it is a no-op. */ static void fts5SegIterSeekInit( Fts5Index *p, /* FTS5 backend */ const u8 *pTerm, int nTerm, /* Term to seek to */ int flags, /* Mask of FTS5INDEX_XXX flags */ Fts5StructureSegment *pSeg, /* Description of segment */ Fts5SegIter *pIter /* Object to populate */ ){ int iPg = 1; int bGe = (flags & FTS5INDEX_QUERY_SCAN); int bDlidx = 0; /* True if there is a doclist-index */ sqlite3_stmt *pIdxSelect = 0; assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 ); assert( pTerm && nTerm ); memset(pIter, 0, sizeof(*pIter)); pIter->pSeg = pSeg; /* This block sets stack variable iPg to the leaf page number that may ** contain term (pTerm/nTerm), if it is present in the segment. */ pIdxSelect = fts5IdxSelectStmt(p); if( p->rc ) return; sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid); sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC); if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){ i64 val = sqlite3_column_int(pIdxSelect, 0); iPg = (int)(val>>1); bDlidx = (val & 0x0001); } p->rc = sqlite3_reset(pIdxSelect); if( iPg<pSeg->pgnoFirst ){ iPg = pSeg->pgnoFirst; bDlidx = 0; } pIter->iLeafPgno = iPg - 1; fts5SegIterNextPage(p, pIter); if( pIter->pLeaf ){ fts5LeafSeek(p, bGe, pIter, pTerm, nTerm); } if( p->rc==SQLITE_OK && bGe==0 ){ pIter->flags |= FTS5_SEGITER_ONETERM; if( pIter->pLeaf ){ if( flags & FTS5INDEX_QUERY_DESC ){ pIter->flags |= FTS5_SEGITER_REVERSE; } if( bDlidx ){ fts5SegIterLoadDlidx(p, pIter); } if( flags & FTS5INDEX_QUERY_DESC ){ fts5SegIterReverse(p, pIter); } } } fts5SegIterSetNext(p, pIter); /* Either: ** ** 1) an error has occurred, or ** 2) the iterator points to EOF, or ** 3) the iterator points to an entry with term (pTerm/nTerm), or ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points ** to an entry with a term greater than or equal to (pTerm/nTerm). */ assert( p->rc!=SQLITE_OK /* 1 */ || pIter->pLeaf==0 /* 2 */ || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */ || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */ ); } /* ** Initialize the object pIter to point to term pTerm/nTerm within the ** in-memory hash table. If there is no such term in the hash-table, the ** iterator is set to EOF. ** ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If ** an error has already occurred when this function is called, it is a no-op. */ static void fts5SegIterHashInit( Fts5Index *p, /* FTS5 backend */ const u8 *pTerm, int nTerm, /* Term to seek to */ int flags, /* Mask of FTS5INDEX_XXX flags */ Fts5SegIter *pIter /* Object to populate */ ){ const u8 *pList = 0; int nList = 0; const u8 *z = 0; int n = 0; assert( p->pHash ); assert( p->rc==SQLITE_OK ); if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){ p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm); sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList); n = (z ? (int)strlen((const char*)z) : 0); }else{ pIter->flags |= FTS5_SEGITER_ONETERM; sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList); z = pTerm; n = nTerm; } if( pList ){ Fts5Data *pLeaf; sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z); pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data)); if( pLeaf==0 ) return; pLeaf->p = (u8*)pList; pLeaf->nn = pLeaf->szLeaf = nList; pIter->pLeaf = pLeaf; pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid); pIter->iEndofDoclist = pLeaf->nn; if( flags & FTS5INDEX_QUERY_DESC ){ pIter->flags |= FTS5_SEGITER_REVERSE; fts5SegIterReverseInitPage(p, pIter); }else{ fts5SegIterLoadNPos(p, pIter); } } fts5SegIterSetNext(p, pIter); } /* ** Zero the iterator passed as the only argument. */ static void fts5SegIterClear(Fts5SegIter *pIter){ fts5BufferFree(&pIter->term); fts5DataRelease(pIter->pLeaf); fts5DataRelease(pIter->pNextLeaf); fts5DlidxIterFree(pIter->pDlidx); sqlite3_free(pIter->aRowidOffset); memset(pIter, 0, sizeof(Fts5SegIter)); } #ifdef SQLITE_DEBUG /* ** This function is used as part of the big assert() procedure implemented by ** fts5AssertMultiIterSetup(). It ensures that the result currently stored ** in *pRes is the correct result of comparing the current positions of the ** two iterators. */ static void fts5AssertComparisonResult( Fts5Iter *pIter, Fts5SegIter *p1, Fts5SegIter *p2, Fts5CResult *pRes ){ int i1 = p1 - pIter->aSeg; int i2 = p2 - pIter->aSeg; if( p1->pLeaf || p2->pLeaf ){ if( p1->pLeaf==0 ){ assert( pRes->iFirst==i2 ); }else if( p2->pLeaf==0 ){ assert( pRes->iFirst==i1 ); }else{ int nMin = MIN(p1->term.n, p2->term.n); int res = memcmp(p1->term.p, p2->term.p, nMin); if( res==0 ) res = p1->term.n - p2->term.n; if( res==0 ){ assert( pRes->bTermEq==1 ); assert( p1->iRowid!=p2->iRowid ); res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1; }else{ assert( pRes->bTermEq==0 ); } if( res<0 ){ assert( pRes->iFirst==i1 ); }else{ assert( pRes->iFirst==i2 ); } } } } /* ** This function is a no-op unless SQLITE_DEBUG is defined when this module ** is compiled. In that case, this function is essentially an assert() ** statement used to verify that the contents of the pIter->aFirst[] array ** are correct. */ static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){ if( p->rc==SQLITE_OK ){ Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ]; int i; assert( (pFirst->pLeaf==0)==pIter->base.bEof ); /* Check that pIter->iSwitchRowid is set correctly. */ for(i=0; i<pIter->nSeg; i++){ Fts5SegIter *p1 = &pIter->aSeg[i]; assert( p1==pFirst || p1->pLeaf==0 || fts5BufferCompare(&pFirst->term, &p1->term) || p1->iRowid==pIter->iSwitchRowid || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev ); } for(i=0; i<pIter->nSeg; i+=2){ Fts5SegIter *p1 = &pIter->aSeg[i]; Fts5SegIter *p2 = &pIter->aSeg[i+1]; Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2]; fts5AssertComparisonResult(pIter, p1, p2, pRes); } for(i=1; i<(pIter->nSeg / 2); i+=2){ Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ]; Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ]; Fts5CResult *pRes = &pIter->aFirst[i]; fts5AssertComparisonResult(pIter, p1, p2, pRes); } } } #else # define fts5AssertMultiIterSetup(x,y) #endif /* ** Do the comparison necessary to populate pIter->aFirst[iOut]. ** ** If the returned value is non-zero, then it is the index of an entry ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing ** to a key that is a duplicate of another, higher priority, ** segment-iterator in the pSeg->aSeg[] array. */ static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){ int i1; /* Index of left-hand Fts5SegIter */ int i2; /* Index of right-hand Fts5SegIter */ int iRes; Fts5SegIter *p1; /* Left-hand Fts5SegIter */ Fts5SegIter *p2; /* Right-hand Fts5SegIter */ Fts5CResult *pRes = &pIter->aFirst[iOut]; assert( iOut<pIter->nSeg && iOut>0 ); assert( pIter->bRev==0 || pIter->bRev==1 ); if( iOut>=(pIter->nSeg/2) ){ i1 = (iOut - pIter->nSeg/2) * 2; i2 = i1 + 1; }else{ i1 = pIter->aFirst[iOut*2].iFirst; i2 = pIter->aFirst[iOut*2+1].iFirst; } p1 = &pIter->aSeg[i1]; p2 = &pIter->aSeg[i2]; pRes->bTermEq = 0; if( p1->pLeaf==0 ){ /* If p1 is at EOF */ iRes = i2; }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */ iRes = i1; }else{ int res = fts5BufferCompare(&p1->term, &p2->term); if( res==0 ){ assert( i2>i1 ); assert( i2!=0 ); pRes->bTermEq = 1; if( p1->iRowid==p2->iRowid ){ p1->bDel = p2->bDel; return i2; } res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1; } assert( res!=0 ); if( res<0 ){ iRes = i1; }else{ iRes = i2; } } pRes->iFirst = (u16)iRes; return 0; } /* ** Move the seg-iter so that it points to the first rowid on page iLeafPgno. ** It is an error if leaf iLeafPgno does not exist or contains no rowids. */ static void fts5SegIterGotoPage( Fts5Index *p, /* FTS5 backend object */ Fts5SegIter *pIter, /* Iterator to advance */ int iLeafPgno ){ assert( iLeafPgno>pIter->iLeafPgno ); if( iLeafPgno>pIter->pSeg->pgnoLast ){ p->rc = FTS5_CORRUPT; }else{ fts5DataRelease(pIter->pNextLeaf); pIter->pNextLeaf = 0; pIter->iLeafPgno = iLeafPgno-1; fts5SegIterNextPage(p, pIter); assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno ); if( p->rc==SQLITE_OK ){ int iOff; u8 *a = pIter->pLeaf->p; int n = pIter->pLeaf->szLeaf; iOff = fts5LeafFirstRowidOff(pIter->pLeaf); if( iOff<4 || iOff>=n ){ p->rc = FTS5_CORRUPT; }else{ iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid); pIter->iLeafOffset = iOff; fts5SegIterLoadNPos(p, pIter); } } } } /* ** Advance the iterator passed as the second argument until it is at or ** past rowid iFrom. Regardless of the value of iFrom, the iterator is ** always advanced at least once. */ static void fts5SegIterNextFrom( Fts5Index *p, /* FTS5 backend object */ Fts5SegIter *pIter, /* Iterator to advance */ i64 iMatch /* Advance iterator at least this far */ ){ int bRev = (pIter->flags & FTS5_SEGITER_REVERSE); Fts5DlidxIter *pDlidx = pIter->pDlidx; int iLeafPgno = pIter->iLeafPgno; int bMove = 1; assert( pIter->flags & FTS5_SEGITER_ONETERM ); assert( pIter->pDlidx ); assert( pIter->pLeaf ); if( bRev==0 ){ while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){ iLeafPgno = fts5DlidxIterPgno(pDlidx); fts5DlidxIterNext(p, pDlidx); } assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc ); if( iLeafPgno>pIter->iLeafPgno ){ fts5SegIterGotoPage(p, pIter, iLeafPgno); bMove = 0; } }else{ assert( pIter->pNextLeaf==0 ); assert( iMatch<pIter->iRowid ); while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){ fts5DlidxIterPrev(p, pDlidx); } iLeafPgno = fts5DlidxIterPgno(pDlidx); assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno ); if( iLeafPgno<pIter->iLeafPgno ){ pIter->iLeafPgno = iLeafPgno+1; fts5SegIterReverseNewPage(p, pIter); bMove = 0; } } do{ if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0); if( pIter->pLeaf==0 ) break; if( bRev==0 && pIter->iRowid>=iMatch ) break; if( bRev!=0 && pIter->iRowid<=iMatch ) break; bMove = 1; }while( p->rc==SQLITE_OK ); } /* ** Free the iterator object passed as the second argument. */ static void fts5MultiIterFree(Fts5Iter *pIter){ if( pIter ){ int i; for(i=0; i<pIter->nSeg; i++){ fts5SegIterClear(&pIter->aSeg[i]); } fts5StructureRelease(pIter->pStruct); fts5BufferFree(&pIter->poslist); sqlite3_free(pIter); } } static void fts5MultiIterAdvanced( Fts5Index *p, /* FTS5 backend to iterate within */ Fts5Iter *pIter, /* Iterator to update aFirst[] array for */ int iChanged, /* Index of sub-iterator just advanced */ int iMinset /* Minimum entry in aFirst[] to set */ ){ int i; for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){ int iEq; if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){ Fts5SegIter *pSeg = &pIter->aSeg[iEq]; assert( p->rc==SQLITE_OK ); pSeg->xNext(p, pSeg, 0); i = pIter->nSeg + iEq; } } } /* ** Sub-iterator iChanged of iterator pIter has just been advanced. It still ** points to the same term though - just a different rowid. This function ** attempts to update the contents of the pIter->aFirst[] accordingly. ** If it does so successfully, 0 is returned. Otherwise 1. ** ** If non-zero is returned, the caller should call fts5MultiIterAdvanced() ** on the iterator instead. That function does the same as this one, except ** that it deals with more complicated cases as well. */ static int fts5MultiIterAdvanceRowid( Fts5Iter *pIter, /* Iterator to update aFirst[] array for */ int iChanged, /* Index of sub-iterator just advanced */ Fts5SegIter **ppFirst ){ Fts5SegIter *pNew = &pIter->aSeg[iChanged]; if( pNew->iRowid==pIter->iSwitchRowid || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev ){ int i; Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001]; pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64; for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){ Fts5CResult *pRes = &pIter->aFirst[i]; assert( pNew->pLeaf ); assert( pRes->bTermEq==0 || pOther->pLeaf ); if( pRes->bTermEq ){ if( pNew->iRowid==pOther->iRowid ){ return 1; }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){ pIter->iSwitchRowid = pOther->iRowid; pNew = pOther; }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){ pIter->iSwitchRowid = pOther->iRowid; } } pRes->iFirst = (u16)(pNew - pIter->aSeg); if( i==1 ) break; pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ]; } } *ppFirst = pNew; return 0; } /* ** Set the pIter->bEof variable based on the state of the sub-iterators. */ static void fts5MultiIterSetEof(Fts5Iter *pIter){ Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ]; pIter->base.bEof = pSeg->pLeaf==0; pIter->iSwitchRowid = pSeg->iRowid; } /* ** Move the iterator to the next entry. ** ** If an error occurs, an error code is left in Fts5Index.rc. It is not ** considered an error if the iterator reaches EOF, or if it is already at ** EOF when this function is called. */ static void fts5MultiIterNext( Fts5Index *p, Fts5Iter *pIter, int bFrom, /* True if argument iFrom is valid */ i64 iFrom /* Advance at least as far as this */ ){ int bUseFrom = bFrom; assert( pIter->base.bEof==0 ); while( p->rc==SQLITE_OK ){ int iFirst = pIter->aFirst[1].iFirst; int bNewTerm = 0; Fts5SegIter *pSeg = &pIter->aSeg[iFirst]; assert( p->rc==SQLITE_OK ); if( bUseFrom && pSeg->pDlidx ){ fts5SegIterNextFrom(p, pSeg, iFrom); }else{ pSeg->xNext(p, pSeg, &bNewTerm); } if( pSeg->pLeaf==0 || bNewTerm || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg) ){ fts5MultiIterAdvanced(p, pIter, iFirst, 1); fts5MultiIterSetEof(pIter); pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst]; if( pSeg->pLeaf==0 ) return; } fts5AssertMultiIterSetup(p, pIter); assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf ); if( pIter->bSkipEmpty==0 || pSeg->nPos ){ pIter->xSetOutputs(pIter, pSeg); return; } bUseFrom = 0; } } static void fts5MultiIterNext2( Fts5Index *p, Fts5Iter *pIter, int *pbNewTerm /* OUT: True if *might* be new term */ ){ assert( pIter->bSkipEmpty ); if( p->rc==SQLITE_OK ){ do { int iFirst = pIter->aFirst[1].iFirst; Fts5SegIter *pSeg = &pIter->aSeg[iFirst]; int bNewTerm = 0; assert( p->rc==SQLITE_OK ); pSeg->xNext(p, pSeg, &bNewTerm); if( pSeg->pLeaf==0 || bNewTerm || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg) ){ fts5MultiIterAdvanced(p, pIter, iFirst, 1); fts5MultiIterSetEof(pIter); *pbNewTerm = 1; }else{ *pbNewTerm = 0; } fts5AssertMultiIterSetup(p, pIter); }while( fts5MultiIterIsEmpty(p, pIter) ); } } static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){ UNUSED_PARAM2(pUnused1, pUnused2); } static Fts5Iter *fts5MultiIterAlloc( Fts5Index *p, /* FTS5 backend to iterate within */ int nSeg ){ Fts5Iter *pNew; int nSlot; /* Power of two >= nSeg */ for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2); pNew = fts5IdxMalloc(p, sizeof(Fts5Iter) + /* pNew */ sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */ sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */ ); if( pNew ){ pNew->nSeg = nSlot; pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot]; pNew->pIndex = p; pNew->xSetOutputs = fts5IterSetOutputs_Noop; } return pNew; } static void fts5PoslistCallback( Fts5Index *pUnused, void *pContext, const u8 *pChunk, int nChunk ){ UNUSED_PARAM(pUnused); assert_nc( nChunk>=0 ); if( nChunk>0 ){ fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk); } } typedef struct PoslistCallbackCtx PoslistCallbackCtx; struct PoslistCallbackCtx { Fts5Buffer *pBuf; /* Append to this buffer */ Fts5Colset *pColset; /* Restrict matches to this column */ int eState; /* See above */ }; typedef struct PoslistOffsetsCtx PoslistOffsetsCtx; struct PoslistOffsetsCtx { Fts5Buffer *pBuf; /* Append to this buffer */ Fts5Colset *pColset; /* Restrict matches to this column */ int iRead; int iWrite; }; /* ** TODO: Make this more efficient! */ static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){ int i; for(i=0; i<pColset->nCol; i++){ if( pColset->aiCol[i]==iCol ) return 1; } return 0; } static void fts5PoslistOffsetsCallback( Fts5Index *pUnused, void *pContext, const u8 *pChunk, int nChunk ){ PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext; UNUSED_PARAM(pUnused); assert_nc( nChunk>=0 ); if( nChunk>0 ){ int i = 0; while( i<nChunk ){ int iVal; i += fts5GetVarint32(&pChunk[i], iVal); iVal += pCtx->iRead - 2; pCtx->iRead = iVal; if( fts5IndexColsetTest(pCtx->pColset, iVal) ){ fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite); pCtx->iWrite = iVal; } } } } static void fts5PoslistFilterCallback( Fts5Index *pUnused, void *pContext, const u8 *pChunk, int nChunk ){ PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext; UNUSED_PARAM(pUnused); assert_nc( nChunk>=0 ); if( nChunk>0 ){ /* Search through to find the first varint with value 1. This is the ** start of the next columns hits. */ int i = 0; int iStart = 0; if( pCtx->eState==2 ){ int iCol; fts5FastGetVarint32(pChunk, i, iCol); if( fts5IndexColsetTest(pCtx->pColset, iCol) ){ pCtx->eState = 1; fts5BufferSafeAppendVarint(pCtx->pBuf, 1); }else{ pCtx->eState = 0; } } do { while( i<nChunk && pChunk[i]!=0x01 ){ while( pChunk[i] & 0x80 ) i++; i++; } if( pCtx->eState ){ fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart); } if( i<nChunk ){ int iCol; iStart = i; i++; if( i>=nChunk ){ pCtx->eState = 2; }else{ fts5FastGetVarint32(pChunk, i, iCol); pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol); if( pCtx->eState ){ fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart); iStart = i; } } } }while( i<nChunk ); } } static void fts5ChunkIterate( Fts5Index *p, /* Index object */ Fts5SegIter *pSeg, /* Poslist of this iterator */ void *pCtx, /* Context pointer for xChunk callback */ void (*xChunk)(Fts5Index*, void*, const u8*, int) ){ int nRem = pSeg->nPos; /* Number of bytes still to come */ Fts5Data *pData = 0; u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset]; int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset); int pgno = pSeg->iLeafPgno; int pgnoSave = 0; /* This function does notmwork with detail=none databases. */ assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE ); if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){ pgnoSave = pgno+1; } while( 1 ){ xChunk(p, pCtx, pChunk, nChunk); nRem -= nChunk; fts5DataRelease(pData); if( nRem<=0 ){ break; }else{ pgno++; pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno)); if( pData==0 ) break; pChunk = &pData->p[4]; nChunk = MIN(nRem, pData->szLeaf - 4); if( pgno==pgnoSave ){ assert( pSeg->pNextLeaf==0 ); pSeg->pNextLeaf = pData; pData = 0; } } } } /* ** Iterator pIter currently points to a valid entry (not EOF). This ** function appends the position list data for the current entry to ** buffer pBuf. It does not make a copy of the position-list size ** field. */ static void fts5SegiterPoslist( Fts5Index *p, Fts5SegIter *pSeg, Fts5Colset *pColset, Fts5Buffer *pBuf ){ if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){ if( pColset==0 ){ fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback); }else{ if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){ PoslistCallbackCtx sCtx; sCtx.pBuf = pBuf; sCtx.pColset = pColset; sCtx.eState = fts5IndexColsetTest(pColset, 0); assert( sCtx.eState==0 || sCtx.eState==1 ); fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback); }else{ PoslistOffsetsCtx sCtx; memset(&sCtx, 0, sizeof(sCtx)); sCtx.pBuf = pBuf; sCtx.pColset = pColset; fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback); } } } } /* ** IN/OUT parameter (*pa) points to a position list n bytes in size. If ** the position list contains entries for column iCol, then (*pa) is set ** to point to the sub-position-list for that column and the number of ** bytes in it returned. Or, if the argument position list does not ** contain any entries for column iCol, return 0. */ static int fts5IndexExtractCol( const u8 **pa, /* IN/OUT: Pointer to poslist */ int n, /* IN: Size of poslist in bytes */ int iCol /* Column to extract from poslist */ ){ int iCurrent = 0; /* Anything before the first 0x01 is col 0 */ const u8 *p = *pa; const u8 *pEnd = &p[n]; /* One byte past end of position list */ while( iCol>iCurrent ){ /* Advance pointer p until it points to pEnd or an 0x01 byte that is ** not part of a varint. Note that it is not possible for a negative ** or extremely large varint to occur within an uncorrupted position ** list. So the last byte of each varint may be assumed to have a clear ** 0x80 bit. */ while( *p!=0x01 ){ while( *p++ & 0x80 ); if( p>=pEnd ) return 0; } *pa = p++; iCurrent = *p++; if( iCurrent & 0x80 ){ p--; p += fts5GetVarint32(p, iCurrent); } } if( iCol!=iCurrent ) return 0; /* Advance pointer p until it points to pEnd or an 0x01 byte that is ** not part of a varint */ while( p<pEnd && *p!=0x01 ){ while( *p++ & 0x80 ); } return p - (*pa); } static int fts5IndexExtractColset ( Fts5Colset *pColset, /* Colset to filter on */ const u8 *pPos, int nPos, /* Position list */ Fts5Buffer *pBuf /* Output buffer */ ){ int rc = SQLITE_OK; int i; fts5BufferZero(pBuf); for(i=0; i<pColset->nCol; i++){ const u8 *pSub = pPos; int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]); if( nSub ){ fts5BufferAppendBlob(&rc, pBuf, nSub, pSub); } } return rc; } /* ** xSetOutputs callback used by detail=none tables. */ static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){ assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE ); pIter->base.iRowid = pSeg->iRowid; pIter->base.nData = pSeg->nPos; } /* ** xSetOutputs callback used by detail=full and detail=col tables when no ** column filters are specified. */ static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){ pIter->base.iRowid = pSeg->iRowid; pIter->base.nData = pSeg->nPos; assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE ); assert( pIter->pColset==0 ); if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){ /* All data is stored on the current page. Populate the output ** variables to point into the body of the page object. */ pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset]; }else{ /* The data is distributed over two or more pages. Copy it into the ** Fts5Iter.poslist buffer and then set the output pointer to point ** to this buffer. */ fts5BufferZero(&pIter->poslist); fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist); pIter->base.pData = pIter->poslist.p; } } /* ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match ** against no columns at all). */ static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){ UNUSED_PARAM(pSeg); pIter->base.nData = 0; } /* ** xSetOutputs callback used by detail=col when there is a column filter ** and there are 100 or more columns. Also called as a fallback from ** fts5IterSetOutputs_Col100 if the column-list spans more than one page. */ static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){ fts5BufferZero(&pIter->poslist); fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist); pIter->base.iRowid = pSeg->iRowid; pIter->base.pData = pIter->poslist.p; pIter->base.nData = pIter->poslist.n; } /* ** xSetOutputs callback used when: ** ** * detail=col, ** * there is a column filter, and ** * the table contains 100 or fewer columns. ** ** The last point is to ensure all column numbers are stored as ** single-byte varints. */ static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){ assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS ); assert( pIter->pColset ); if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){ fts5IterSetOutputs_Col(pIter, pSeg); }else{ u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset]; u8 *pEnd = (u8*)&a[pSeg->nPos]; int iPrev = 0; int *aiCol = pIter->pColset->aiCol; int *aiColEnd = &aiCol[pIter->pColset->nCol]; u8 *aOut = pIter->poslist.p; int iPrevOut = 0; pIter->base.iRowid = pSeg->iRowid; while( a<pEnd ){ iPrev += (int)a++[0] - 2; while( *aiCol<iPrev ){ aiCol++; if( aiCol==aiColEnd ) goto setoutputs_col_out; } if( *aiCol==iPrev ){ *aOut++ = (u8)((iPrev - iPrevOut) + 2); iPrevOut = iPrev; } } setoutputs_col_out: pIter->base.pData = pIter->poslist.p; pIter->base.nData = aOut - pIter->poslist.p; } } /* ** xSetOutputs callback used by detail=full when there is a column filter. */ static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){ Fts5Colset *pColset = pIter->pColset; pIter->base.iRowid = pSeg->iRowid; assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL ); assert( pColset ); if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){ /* All data is stored on the current page. Populate the output ** variables to point into the body of the page object. */ const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset]; if( pColset->nCol==1 ){ pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]); pIter->base.pData = a; }else{ fts5BufferZero(&pIter->poslist); fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist); pIter->base.pData = pIter->poslist.p; pIter->base.nData = pIter->poslist.n; } }else{ /* The data is distributed over two or more pages. Copy it into the ** Fts5Iter.poslist buffer and then set the output pointer to point ** to this buffer. */ fts5BufferZero(&pIter->poslist); fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist); pIter->base.pData = pIter->poslist.p; pIter->base.nData = pIter->poslist.n; } } static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){ if( *pRc==SQLITE_OK ){ Fts5Config *pConfig = pIter->pIndex->pConfig; if( pConfig->eDetail==FTS5_DETAIL_NONE ){ pIter->xSetOutputs = fts5IterSetOutputs_None; } else if( pIter->pColset==0 ){ pIter->xSetOutputs = fts5IterSetOutputs_Nocolset; } else if( pIter->pColset->nCol==0 ){ pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset; } else if( pConfig->eDetail==FTS5_DETAIL_FULL ){ pIter->xSetOutputs = fts5IterSetOutputs_Full; } else{ assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS ); if( pConfig->nCol<=100 ){ pIter->xSetOutputs = fts5IterSetOutputs_Col100; sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol); }else{ pIter->xSetOutputs = fts5IterSetOutputs_Col; } } } } /* ** Allocate a new Fts5Iter object. ** ** The new object will be used to iterate through data in structure pStruct. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel ** is zero or greater, data from the first nSegment segments on level iLevel ** is merged. ** ** The iterator initially points to the first term/rowid entry in the ** iterated data. */ static void fts5MultiIterNew( Fts5Index *p, /* FTS5 backend to iterate within */ Fts5Structure *pStruct, /* Structure of specific index */ int flags, /* FTS5INDEX_QUERY_XXX flags */ Fts5Colset *pColset, /* Colset to filter on (or NULL) */ const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */ int iLevel, /* Level to iterate (-1 for all) */ int nSegment, /* Number of segments to merge (iLevel>=0) */ Fts5Iter **ppOut /* New object */ ){ int nSeg = 0; /* Number of segment-iters in use */ int iIter = 0; /* */ int iSeg; /* Used to iterate through segments */ Fts5StructureLevel *pLvl; Fts5Iter *pNew; assert( (pTerm==0 && nTerm==0) || iLevel<0 ); /* Allocate space for the new multi-seg-iterator. */ if( p->rc==SQLITE_OK ){ if( iLevel<0 ){ assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) ); nSeg = pStruct->nSegment; nSeg += (p->pHash ? 1 : 0); }else{ nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment); } } *ppOut = pNew = fts5MultiIterAlloc(p, nSeg); if( pNew==0 ) return; pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC)); pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY)); pNew->pStruct = pStruct; pNew->pColset = pColset; fts5StructureRef(pStruct); if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){ fts5IterSetOutputCb(&p->rc, pNew); } /* Initialize each of the component segment iterators. */ if( p->rc==SQLITE_OK ){ if( iLevel<0 ){ Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel]; if( p->pHash ){ /* Add a segment iterator for the current contents of the hash table. */ Fts5SegIter *pIter = &pNew->aSeg[iIter++]; fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter); } for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){ for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){ Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg]; Fts5SegIter *pIter = &pNew->aSeg[iIter++]; if( pTerm==0 ){ fts5SegIterInit(p, pSeg, pIter); }else{ fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter); } } } }else{ pLvl = &pStruct->aLevel[iLevel]; for(iSeg=nSeg-1; iSeg>=0; iSeg--){ fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]); } } assert( iIter==nSeg ); } /* If the above was successful, each component iterators now points ** to the first entry in its segment. In this case initialize the ** aFirst[] array. Or, if an error has occurred, free the iterator ** object and set the output variable to NULL. */ if( p->rc==SQLITE_OK ){ for(iIter=pNew->nSeg-1; iIter>0; iIter--){ int iEq; if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){ Fts5SegIter *pSeg = &pNew->aSeg[iEq]; if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0); fts5MultiIterAdvanced(p, pNew, iEq, iIter); } } fts5MultiIterSetEof(pNew); fts5AssertMultiIterSetup(p, pNew); if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){ fts5MultiIterNext(p, pNew, 0, 0); }else if( pNew->base.bEof==0 ){ Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst]; pNew->xSetOutputs(pNew, pSeg); } }else{ fts5MultiIterFree(pNew); *ppOut = 0; } } /* ** Create an Fts5Iter that iterates through the doclist provided ** as the second argument. */ static void fts5MultiIterNew2( Fts5Index *p, /* FTS5 backend to iterate within */ Fts5Data *pData, /* Doclist to iterate through */ int bDesc, /* True for descending rowid order */ Fts5Iter **ppOut /* New object */ ){ Fts5Iter *pNew; pNew = fts5MultiIterAlloc(p, 2); if( pNew ){ Fts5SegIter *pIter = &pNew->aSeg[1]; pIter->flags = FTS5_SEGITER_ONETERM; if( pData->szLeaf>0 ){ pIter->pLeaf = pData; pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid); pIter->iEndofDoclist = pData->nn; pNew->aFirst[1].iFirst = 1; if( bDesc ){ pNew->bRev = 1; pIter->flags |= FTS5_SEGITER_REVERSE; fts5SegIterReverseInitPage(p, pIter); }else{ fts5SegIterLoadNPos(p, pIter); } pData = 0; }else{ pNew->base.bEof = 1; } fts5SegIterSetNext(p, pIter); *ppOut = pNew; } fts5DataRelease(pData); } /* ** Return true if the iterator is at EOF or if an error has occurred. ** False otherwise. */ static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){ assert( p->rc || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof ); return (p->rc || pIter->base.bEof); } /* ** Return the rowid of the entry that the iterator currently points ** to. If the iterator points to EOF when this function is called the ** results are undefined. */ static i64 fts5MultiIterRowid(Fts5Iter *pIter){ assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf ); return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid; } /* ** Move the iterator to the next entry at or following iMatch. */ static void fts5MultiIterNextFrom( Fts5Index *p, Fts5Iter *pIter, i64 iMatch ){ while( 1 ){ i64 iRowid; fts5MultiIterNext(p, pIter, 1, iMatch); if( fts5MultiIterEof(p, pIter) ) break; iRowid = fts5MultiIterRowid(pIter); if( pIter->bRev==0 && iRowid>=iMatch ) break; if( pIter->bRev!=0 && iRowid<=iMatch ) break; } } /* ** Return a pointer to a buffer containing the term associated with the ** entry that the iterator currently points to. */ static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){ Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ]; *pn = p->term.n; return p->term.p; } /* ** Allocate a new segment-id for the structure pStruct. The new segment ** id must be between 1 and 65335 inclusive, and must not be used by ** any currently existing segment. If a free segment id cannot be found, ** SQLITE_FULL is returned. ** ** If an error has already occurred, this function is a no-op. 0 is ** returned in this case. */ static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){ int iSegid = 0; if( p->rc==SQLITE_OK ){ if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){ p->rc = SQLITE_FULL; }else{ /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following ** array is 63 elements, or 252 bytes, in size. */ u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32]; int iLvl, iSeg; int i; u32 mask; memset(aUsed, 0, sizeof(aUsed)); for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){ int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid; if( iId<=FTS5_MAX_SEGMENT ){ aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32); } } } for(i=0; aUsed[i]==0xFFFFFFFF; i++); mask = aUsed[i]; for(iSegid=0; mask & (1 << iSegid); iSegid++); iSegid += 1 + i*32; #ifdef SQLITE_DEBUG for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){ assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid ); } } assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT ); { sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p); if( p->rc==SQLITE_OK ){ u8 aBlob[2] = {0xff, 0xff}; sqlite3_bind_int(pIdxSelect, 1, iSegid); sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC); assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW ); p->rc = sqlite3_reset(pIdxSelect); } } #endif } } return iSegid; } /* ** Discard all data currently cached in the hash-tables. */ static void fts5IndexDiscardData(Fts5Index *p){ assert( p->pHash || p->nPendingData==0 ); if( p->pHash ){ sqlite3Fts5HashClear(p->pHash); p->nPendingData = 0; } } /* ** Return the size of the prefix, in bytes, that buffer ** (pNew/<length-unknown>) shares with buffer (pOld/nOld). ** ** Buffer (pNew/<length-unknown>) is guaranteed to be greater ** than buffer (pOld/nOld). */ static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){ int i; for(i=0; i<nOld; i++){ if( pOld[i]!=pNew[i] ) break; } return i; } static void fts5WriteDlidxClear( Fts5Index *p, Fts5SegWriter *pWriter, int bFlush /* If true, write dlidx to disk */ ){ int i; assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) ); for(i=0; i<pWriter->nDlidx; i++){ Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i]; if( pDlidx->buf.n==0 ) break; if( bFlush ){ assert( pDlidx->pgno!=0 ); fts5DataWrite(p, FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno), pDlidx->buf.p, pDlidx->buf.n ); } sqlite3Fts5BufferZero(&pDlidx->buf); pDlidx->bPrevValid = 0; } } /* ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size. ** Any new array elements are zeroed before returning. */ static int fts5WriteDlidxGrow( Fts5Index *p, Fts5SegWriter *pWriter, int nLvl ){ if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){ Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc( pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl ); if( aDlidx==0 ){ p->rc = SQLITE_NOMEM; }else{ int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx); memset(&aDlidx[pWriter->nDlidx], 0, nByte); pWriter->aDlidx = aDlidx; pWriter->nDlidx = nLvl; } } return p->rc; } /* ** If the current doclist-index accumulating in pWriter->aDlidx[] is large ** enough, flush it to disk and return 1. Otherwise discard it and return ** zero. */ static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){ int bFlag = 0; /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written ** to the database, also write the doclist-index to disk. */ if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){ bFlag = 1; } fts5WriteDlidxClear(p, pWriter, bFlag); pWriter->nEmpty = 0; return bFlag; } /* ** This function is called whenever processing of the doclist for the ** last term on leaf page (pWriter->iBtPage) is completed. ** ** The doclist-index for that term is currently stored in-memory within the ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function ** writes it out to disk. Or, if it is too small to bother with, discards ** it. ** ** Fts5SegWriter.btterm currently contains the first term on page iBtPage. */ static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){ int bFlag; assert( pWriter->iBtPage || pWriter->nEmpty==0 ); if( pWriter->iBtPage==0 ) return; bFlag = fts5WriteFlushDlidx(p, pWriter); if( p->rc==SQLITE_OK ){ const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:""); /* The following was already done in fts5WriteInit(): */ /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */ sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC); sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1)); sqlite3_step(p->pIdxWriter); p->rc = sqlite3_reset(p->pIdxWriter); } pWriter->iBtPage = 0; } /* ** This is called once for each leaf page except the first that contains ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that ** is larger than all terms written to earlier leaves, and equal to or ** smaller than the first term on the new leaf. ** ** If an error occurs, an error code is left in Fts5Index.rc. If an error ** has already occurred when this function is called, it is a no-op. */ static void fts5WriteBtreeTerm( Fts5Index *p, /* FTS5 backend object */ Fts5SegWriter *pWriter, /* Writer object */ int nTerm, const u8 *pTerm /* First term on new page */ ){ fts5WriteFlushBtree(p, pWriter); fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm); pWriter->iBtPage = pWriter->writer.pgno; } /* ** This function is called when flushing a leaf page that contains no ** terms at all to disk. */ static void fts5WriteBtreeNoTerm( Fts5Index *p, /* FTS5 backend object */ Fts5SegWriter *pWriter /* Writer object */ ){ /* If there were no rowids on the leaf page either and the doclist-index ** has already been started, append an 0x00 byte to it. */ if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){ Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0]; assert( pDlidx->bPrevValid ); sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0); } /* Increment the "number of sequential leaves without a term" counter. */ pWriter->nEmpty++; } static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){ i64 iRowid; int iOff; iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid); fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid); return iRowid; } /* ** Rowid iRowid has just been appended to the current leaf page. It is the ** first on the page. This function appends an appropriate entry to the current ** doclist-index. */ static void fts5WriteDlidxAppend( Fts5Index *p, Fts5SegWriter *pWriter, i64 iRowid ){ int i; int bDone = 0; for(i=0; p->rc==SQLITE_OK && bDone==0; i++){ i64 iVal; Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i]; if( pDlidx->buf.n>=p->pConfig->pgsz ){ /* The current doclist-index page is full. Write it to disk and push ** a copy of iRowid (which will become the first rowid on the next ** doclist-index leaf page) up into the next level of the b-tree ** hierarchy. If the node being flushed is currently the root node, ** also push its first rowid upwards. */ pDlidx->buf.p[0] = 0x01; /* Not the root node */ fts5DataWrite(p, FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno), pDlidx->buf.p, pDlidx->buf.n ); fts5WriteDlidxGrow(p, pWriter, i+2); pDlidx = &pWriter->aDlidx[i]; if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){ i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf); /* This was the root node. Push its first rowid up to the new root. */ pDlidx[1].pgno = pDlidx->pgno; sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0); sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno); sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst); pDlidx[1].bPrevValid = 1; pDlidx[1].iPrev = iFirst; } sqlite3Fts5BufferZero(&pDlidx->buf); pDlidx->bPrevValid = 0; pDlidx->pgno++; }else{ bDone = 1; } if( pDlidx->bPrevValid ){ iVal = iRowid - pDlidx->iPrev; }else{ i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno); assert( pDlidx->buf.n==0 ); sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone); sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno); iVal = iRowid; } sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal); pDlidx->bPrevValid = 1; pDlidx->iPrev = iRowid; } } static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){ static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 }; Fts5PageWriter *pPage = &pWriter->writer; i64 iRowid; static int nCall = 0; nCall++; assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) ); /* Set the szLeaf header field. */ assert( 0==fts5GetU16(&pPage->buf.p[2]) ); fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n); if( pWriter->bFirstTermInPage ){ /* No term was written to this page. */ assert( pPage->pgidx.n==0 ); fts5WriteBtreeNoTerm(p, pWriter); }else{ /* Append the pgidx to the page buffer. Set the szLeaf header field. */ fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p); } /* Write the page out to disk */ iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno); fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n); /* Initialize the next page. */ fts5BufferZero(&pPage->buf); fts5BufferZero(&pPage->pgidx); fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero); pPage->iPrevPgidx = 0; pPage->pgno++; /* Increase the leaves written counter */ pWriter->nLeafWritten++; /* The new leaf holds no terms or rowids */ pWriter->bFirstTermInPage = 1; pWriter->bFirstRowidInPage = 1; } /* ** Append term pTerm/nTerm to the segment being written by the writer passed ** as the second argument. ** ** If an error occurs, set the Fts5Index.rc error code. If an error has ** already occurred, this function is a no-op. */ static void fts5WriteAppendTerm( Fts5Index *p, Fts5SegWriter *pWriter, int nTerm, const u8 *pTerm ){ int nPrefix; /* Bytes of prefix compression for term */ Fts5PageWriter *pPage = &pWriter->writer; Fts5Buffer *pPgidx = &pWriter->writer.pgidx; assert( p->rc==SQLITE_OK ); assert( pPage->buf.n>=4 ); assert( pPage->buf.n>4 || pWriter->bFirstTermInPage ); /* If the current leaf page is full, flush it to disk. */ if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){ if( pPage->buf.n>4 ){ fts5WriteFlushLeaf(p, pWriter); } fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING); } /* TODO1: Updating pgidx here. */ pPgidx->n += sqlite3Fts5PutVarint( &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx ); pPage->iPrevPgidx = pPage->buf.n; #if 0 fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n); pPgidx->n += 2; #endif if( pWriter->bFirstTermInPage ){ nPrefix = 0; if( pPage->pgno!=1 ){ /* This is the first term on a leaf that is not the leftmost leaf in ** the segment b-tree. In this case it is necessary to add a term to ** the b-tree hierarchy that is (a) larger than the largest term ** already written to the segment and (b) smaller than or equal to ** this term. In other words, a prefix of (pTerm/nTerm) that is one ** byte longer than the longest prefix (pTerm/nTerm) shares with the ** previous term. ** ** Usually, the previous term is available in pPage->term. The exception ** is if this is the first term written in an incremental-merge step. ** In this case the previous term is not available, so just write a ** copy of (pTerm/nTerm) into the parent node. This is slightly ** inefficient, but still correct. */ int n = nTerm; if( pPage->term.n ){ n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm); } fts5WriteBtreeTerm(p, pWriter, n, pTerm); pPage = &pWriter->writer; } }else{ nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm); fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix); } /* Append the number of bytes of new data, then the term data itself ** to the page. */ fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix); fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]); /* Update the Fts5PageWriter.term field. */ fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm); pWriter->bFirstTermInPage = 0; pWriter->bFirstRowidInPage = 0; pWriter->bFirstRowidInDoclist = 1; assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) ); pWriter->aDlidx[0].pgno = pPage->pgno; } /* ** Append a rowid and position-list size field to the writers output. */ static void fts5WriteAppendRowid( Fts5Index *p, Fts5SegWriter *pWriter, i64 iRowid ){ if( p->rc==SQLITE_OK ){ Fts5PageWriter *pPage = &pWriter->writer; if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){ fts5WriteFlushLeaf(p, pWriter); } /* If this is to be the first rowid written to the page, set the ** rowid-pointer in the page-header. Also append a value to the dlidx ** buffer, in case a doclist-index is required. */ if( pWriter->bFirstRowidInPage ){ fts5PutU16(pPage->buf.p, (u16)pPage->buf.n); fts5WriteDlidxAppend(p, pWriter, iRowid); } /* Write the rowid. */ if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){ fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid); }else{ assert( p->rc || iRowid>pWriter->iPrevRowid ); fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid); } pWriter->iPrevRowid = iRowid; pWriter->bFirstRowidInDoclist = 0; pWriter->bFirstRowidInPage = 0; } } static void fts5WriteAppendPoslistData( Fts5Index *p, Fts5SegWriter *pWriter, const u8 *aData, int nData ){ Fts5PageWriter *pPage = &pWriter->writer; const u8 *a = aData; int n = nData; assert( p->pConfig->pgsz>0 ); while( p->rc==SQLITE_OK && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz ){ int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n; int nCopy = 0; while( nCopy<nReq ){ i64 dummy; nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy); } fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a); a += nCopy; n -= nCopy; fts5WriteFlushLeaf(p, pWriter); } if( n>0 ){ fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a); } } /* ** Flush any data cached by the writer object to the database. Free any ** allocations associated with the writer. */ static void fts5WriteFinish( Fts5Index *p, Fts5SegWriter *pWriter, /* Writer object */ int *pnLeaf /* OUT: Number of leaf pages in b-tree */ ){ int i; Fts5PageWriter *pLeaf = &pWriter->writer; if( p->rc==SQLITE_OK ){ assert( pLeaf->pgno>=1 ); if( pLeaf->buf.n>4 ){ fts5WriteFlushLeaf(p, pWriter); } *pnLeaf = pLeaf->pgno-1; if( pLeaf->pgno>1 ){ fts5WriteFlushBtree(p, pWriter); } } fts5BufferFree(&pLeaf->term); fts5BufferFree(&pLeaf->buf); fts5BufferFree(&pLeaf->pgidx); fts5BufferFree(&pWriter->btterm); for(i=0; i<pWriter->nDlidx; i++){ sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf); } sqlite3_free(pWriter->aDlidx); } static void fts5WriteInit( Fts5Index *p, Fts5SegWriter *pWriter, int iSegid ){ const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING; memset(pWriter, 0, sizeof(Fts5SegWriter)); pWriter->iSegid = iSegid; fts5WriteDlidxGrow(p, pWriter, 1); pWriter->writer.pgno = 1; pWriter->bFirstTermInPage = 1; pWriter->iBtPage = 1; assert( pWriter->writer.buf.n==0 ); assert( pWriter->writer.pgidx.n==0 ); /* Grow the two buffers to pgsz + padding bytes in size. */ sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer); sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer); if( p->pIdxWriter==0 ){ Fts5Config *pConfig = p->pConfig; fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf( "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)", pConfig->zDb, pConfig->zName )); } if( p->rc==SQLITE_OK ){ /* Initialize the 4-byte leaf-page header to 0x00. */ memset(pWriter->writer.buf.p, 0, 4); pWriter->writer.buf.n = 4; /* Bind the current output segment id to the index-writer. This is an ** optimization over binding the same value over and over as rows are ** inserted into %_idx by the current writer. */ sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); } } /* ** Iterator pIter was used to iterate through the input segments of on an ** incremental merge operation. This function is called if the incremental ** merge step has finished but the input has not been completely exhausted. */ static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){ int i; Fts5Buffer buf; memset(&buf, 0, sizeof(Fts5Buffer)); for(i=0; i<pIter->nSeg; i++){ Fts5SegIter *pSeg = &pIter->aSeg[i]; if( pSeg->pSeg==0 ){ /* no-op */ }else if( pSeg->pLeaf==0 ){ /* All keys from this input segment have been transfered to the output. ** Set both the first and last page-numbers to 0 to indicate that the ** segment is now empty. */ pSeg->pSeg->pgnoLast = 0; pSeg->pSeg->pgnoFirst = 0; }else{ int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */ i64 iLeafRowid; Fts5Data *pData; int iId = pSeg->pSeg->iSegid; u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00}; iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno); pData = fts5DataRead(p, iLeafRowid); if( pData ){ fts5BufferZero(&buf); fts5BufferGrow(&p->rc, &buf, pData->nn); fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr); fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n); fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p); fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]); if( p->rc==SQLITE_OK ){ /* Set the szLeaf field */ fts5PutU16(&buf.p[2], (u16)buf.n); } /* Set up the new page-index array */ fts5BufferAppendVarint(&p->rc, &buf, 4); if( pSeg->iLeafPgno==pSeg->iTermLeafPgno && pSeg->iEndofDoclist<pData->szLeaf ){ int nDiff = pData->szLeaf - pSeg->iEndofDoclist; fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4); fts5BufferAppendBlob(&p->rc, &buf, pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff] ); } fts5DataRelease(pData); pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno; fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid); fts5DataWrite(p, iLeafRowid, buf.p, buf.n); } } } fts5BufferFree(&buf); } static void fts5MergeChunkCallback( Fts5Index *p, void *pCtx, const u8 *pChunk, int nChunk ){ Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx; fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk); } /* ** */ static void fts5IndexMergeLevel( Fts5Index *p, /* FTS5 backend object */ Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */ int iLvl, /* Level to read input from */ int *pnRem /* Write up to this many output leaves */ ){ Fts5Structure *pStruct = *ppStruct; Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl]; Fts5StructureLevel *pLvlOut; Fts5Iter *pIter = 0; /* Iterator to read input data */ int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */ int nInput; /* Number of input segments */ Fts5SegWriter writer; /* Writer object */ Fts5StructureSegment *pSeg; /* Output segment */ Fts5Buffer term; int bOldest; /* True if the output segment is the oldest */ int eDetail = p->pConfig->eDetail; const int flags = FTS5INDEX_QUERY_NOOUTPUT; assert( iLvl<pStruct->nLevel ); assert( pLvl->nMerge<=pLvl->nSeg ); memset(&writer, 0, sizeof(Fts5SegWriter)); memset(&term, 0, sizeof(Fts5Buffer)); if( pLvl->nMerge ){ pLvlOut = &pStruct->aLevel[iLvl+1]; assert( pLvlOut->nSeg>0 ); nInput = pLvl->nMerge; pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1]; fts5WriteInit(p, &writer, pSeg->iSegid); writer.writer.pgno = pSeg->pgnoLast+1; writer.iBtPage = 0; }else{ int iSegid = fts5AllocateSegid(p, pStruct); /* Extend the Fts5Structure object as required to ensure the output ** segment exists. */ if( iLvl==pStruct->nLevel-1 ){ fts5StructureAddLevel(&p->rc, ppStruct); pStruct = *ppStruct; } fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0); if( p->rc ) return; pLvl = &pStruct->aLevel[iLvl]; pLvlOut = &pStruct->aLevel[iLvl+1]; fts5WriteInit(p, &writer, iSegid); /* Add the new segment to the output level */ pSeg = &pLvlOut->aSeg[pLvlOut->nSeg]; pLvlOut->nSeg++; pSeg->pgnoFirst = 1; pSeg->iSegid = iSegid; pStruct->nSegment++; /* Read input from all segments in the input level */ nInput = pLvl->nSeg; } bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2); assert( iLvl>=0 ); for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter); fts5MultiIterEof(p, pIter)==0; fts5MultiIterNext(p, pIter, 0, 0) ){ Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ]; int nPos; /* position-list size field value */ int nTerm; const u8 *pTerm; /* Check for key annihilation. */ if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue; pTerm = fts5MultiIterTerm(pIter, &nTerm); if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){ if( pnRem && writer.nLeafWritten>nRem ){ break; } /* This is a new term. Append a term to the output segment. */ fts5WriteAppendTerm(p, &writer, nTerm, pTerm); fts5BufferSet(&p->rc, &term, nTerm, pTerm); } /* Append the rowid to the output */ /* WRITEPOSLISTSIZE */ fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter)); if( eDetail==FTS5_DETAIL_NONE ){ if( pSegIter->bDel ){ fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0); if( pSegIter->nPos>0 ){ fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0); } } }else{ /* Append the position-list data to the output */ nPos = pSegIter->nPos*2 + pSegIter->bDel; fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos); fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback); } } /* Flush the last leaf page to disk. Set the output segment b-tree height ** and last leaf page number at the same time. */ fts5WriteFinish(p, &writer, &pSeg->pgnoLast); if( fts5MultiIterEof(p, pIter) ){ int i; /* Remove the redundant segments from the %_data table */ for(i=0; i<nInput; i++){ fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid); } /* Remove the redundant segments from the input level */ if( pLvl->nSeg!=nInput ){ int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment); memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove); } pStruct->nSegment -= nInput; pLvl->nSeg -= nInput; pLvl->nMerge = 0; if( pSeg->pgnoLast==0 ){ pLvlOut->nSeg--; pStruct->nSegment--; } }else{ assert( pSeg->pgnoLast>0 ); fts5TrimSegments(p, pIter); pLvl->nMerge = nInput; } fts5MultiIterFree(pIter); fts5BufferFree(&term); if( pnRem ) *pnRem -= writer.nLeafWritten; } /* ** Do up to nPg pages of automerge work on the index. ** ** Return true if any changes were actually made, or false otherwise. */ static int fts5IndexMerge( Fts5Index *p, /* FTS5 backend object */ Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */ int nPg, /* Pages of work to do */ int nMin /* Minimum number of segments to merge */ ){ int nRem = nPg; int bRet = 0; Fts5Structure *pStruct = *ppStruct; while( nRem>0 && p->rc==SQLITE_OK ){ int iLvl; /* To iterate through levels */ int iBestLvl = 0; /* Level offering the most input segments */ int nBest = 0; /* Number of input segments on best level */ /* Set iBestLvl to the level to read input segments from. */ assert( pStruct->nLevel>0 ); for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){ Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl]; if( pLvl->nMerge ){ if( pLvl->nMerge>nBest ){ iBestLvl = iLvl; nBest = pLvl->nMerge; } break; } if( pLvl->nSeg>nBest ){ nBest = pLvl->nSeg; iBestLvl = iLvl; } } /* If nBest is still 0, then the index must be empty. */ #ifdef SQLITE_DEBUG for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){ assert( pStruct->aLevel[iLvl].nSeg==0 ); } #endif if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){ break; } bRet = 1; fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem); if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){ fts5StructurePromote(p, iBestLvl+1, pStruct); } } *ppStruct = pStruct; return bRet; } /* ** A total of nLeaf leaf pages of data has just been flushed to a level-0 ** segment. This function updates the write-counter accordingly and, if ** necessary, performs incremental merge work. ** ** If an error occurs, set the Fts5Index.rc error code. If an error has ** already occurred, this function is a no-op. */ static void fts5IndexAutomerge( Fts5Index *p, /* FTS5 backend object */ Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */ int nLeaf /* Number of output leaves just written */ ){ if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){ Fts5Structure *pStruct = *ppStruct; u64 nWrite; /* Initial value of write-counter */ int nWork; /* Number of work-quanta to perform */ int nRem; /* Number of leaf pages left to write */ /* Update the write-counter. While doing so, set nWork. */ nWrite = pStruct->nWriteCounter; nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit)); pStruct->nWriteCounter += nLeaf; nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel); fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge); } } static void fts5IndexCrisismerge( Fts5Index *p, /* FTS5 backend object */ Fts5Structure **ppStruct /* IN/OUT: Current structure of index */ ){ const int nCrisis = p->pConfig->nCrisisMerge; Fts5Structure *pStruct = *ppStruct; int iLvl = 0; assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 ); while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){ fts5IndexMergeLevel(p, &pStruct, iLvl, 0); assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) ); fts5StructurePromote(p, iLvl+1, pStruct); iLvl++; } *ppStruct = pStruct; } static int fts5IndexReturn(Fts5Index *p){ int rc = p->rc; p->rc = SQLITE_OK; return rc; } typedef struct Fts5FlushCtx Fts5FlushCtx; struct Fts5FlushCtx { Fts5Index *pIdx; Fts5SegWriter writer; }; /* ** Buffer aBuf[] contains a list of varints, all small enough to fit ** in a 32-bit integer. Return the size of the largest prefix of this ** list nMax bytes or less in size. */ static int fts5PoslistPrefix(const u8 *aBuf, int nMax){ int ret; u32 dummy; ret = fts5GetVarint32(aBuf, dummy); if( ret<nMax ){ while( 1 ){ int i = fts5GetVarint32(&aBuf[ret], dummy); if( (ret + i) > nMax ) break; ret += i; } } return ret; } /* ** Flush the contents of in-memory hash table iHash to a new level-0 ** segment on disk. Also update the corresponding structure record. ** ** If an error occurs, set the Fts5Index.rc error code. If an error has ** already occurred, this function is a no-op. */ static void fts5FlushOneHash(Fts5Index *p){ Fts5Hash *pHash = p->pHash; Fts5Structure *pStruct; int iSegid; int pgnoLast = 0; /* Last leaf page number in segment */ /* Obtain a reference to the index structure and allocate a new segment-id ** for the new level-0 segment. */ pStruct = fts5StructureRead(p); iSegid = fts5AllocateSegid(p, pStruct); fts5StructureInvalidate(p); if( iSegid ){ const int pgsz = p->pConfig->pgsz; int eDetail = p->pConfig->eDetail; Fts5StructureSegment *pSeg; /* New segment within pStruct */ Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */ Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */ Fts5SegWriter writer; fts5WriteInit(p, &writer, iSegid); pBuf = &writer.writer.buf; pPgidx = &writer.writer.pgidx; /* fts5WriteInit() should have initialized the buffers to (most likely) ** the maximum space required. */ assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) ); assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) ); /* Begin scanning through hash table entries. This loop runs once for each ** term/doclist currently stored within the hash table. */ if( p->rc==SQLITE_OK ){ p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0); } while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){ const char *zTerm; /* Buffer containing term */ const u8 *pDoclist; /* Pointer to doclist for this term */ int nDoclist; /* Size of doclist in bytes */ /* Write the term for this entry to disk. */ sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist); fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm); assert( writer.bFirstRowidInPage==0 ); if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){ /* The entire doclist will fit on the current leaf. */ fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist); }else{ i64 iRowid = 0; i64 iDelta = 0; int iOff = 0; /* The entire doclist will not fit on this leaf. The following ** loop iterates through the poslists that make up the current ** doclist. */ while( p->rc==SQLITE_OK && iOff<nDoclist ){ iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta); iRowid += iDelta; if( writer.bFirstRowidInPage ){ fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */ pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid); writer.bFirstRowidInPage = 0; fts5WriteDlidxAppend(p, &writer, iRowid); }else{ pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta); } assert( pBuf->n<=pBuf->nSpace ); if( eDetail==FTS5_DETAIL_NONE ){ if( iOff<nDoclist && pDoclist[iOff]==0 ){ pBuf->p[pBuf->n++] = 0; iOff++; if( iOff<nDoclist && pDoclist[iOff]==0 ){ pBuf->p[pBuf->n++] = 0; iOff++; } } if( (pBuf->n + pPgidx->n)>=pgsz ){ fts5WriteFlushLeaf(p, &writer); } }else{ int bDummy; int nPos; int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy); nCopy += nPos; if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){ /* The entire poslist will fit on the current leaf. So copy ** it in one go. */ fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy); }else{ /* The entire poslist will not fit on this leaf. So it needs ** to be broken into sections. The only qualification being ** that each varint must be stored contiguously. */ const u8 *pPoslist = &pDoclist[iOff]; int iPos = 0; while( p->rc==SQLITE_OK ){ int nSpace = pgsz - pBuf->n - pPgidx->n; int n = 0; if( (nCopy - iPos)<=nSpace ){ n = nCopy - iPos; }else{ n = fts5PoslistPrefix(&pPoslist[iPos], nSpace); } assert( n>0 ); fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n); iPos += n; if( (pBuf->n + pPgidx->n)>=pgsz ){ fts5WriteFlushLeaf(p, &writer); } if( iPos>=nCopy ) break; } } iOff += nCopy; } } } /* TODO2: Doclist terminator written here. */ /* pBuf->p[pBuf->n++] = '\0'; */ assert( pBuf->n<=pBuf->nSpace ); sqlite3Fts5HashScanNext(pHash); } sqlite3Fts5HashClear(pHash); fts5WriteFinish(p, &writer, &pgnoLast); /* Update the Fts5Structure. It is written back to the database by the ** fts5StructureRelease() call below. */ if( pStruct->nLevel==0 ){ fts5StructureAddLevel(&p->rc, &pStruct); } fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0); if( p->rc==SQLITE_OK ){ pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ]; pSeg->iSegid = iSegid; pSeg->pgnoFirst = 1; pSeg->pgnoLast = pgnoLast; pStruct->nSegment++; } fts5StructurePromote(p, 0, pStruct); } fts5IndexAutomerge(p, &pStruct, pgnoLast); fts5IndexCrisismerge(p, &pStruct); fts5StructureWrite(p, pStruct); fts5StructureRelease(pStruct); } /* ** Flush any data stored in the in-memory hash tables to the database. */ static void fts5IndexFlush(Fts5Index *p){ /* Unless it is empty, flush the hash table to disk */ if( p->nPendingData ){ assert( p->pHash ); p->nPendingData = 0; fts5FlushOneHash(p); } } static Fts5Structure *fts5IndexOptimizeStruct( Fts5Index *p, Fts5Structure *pStruct ){ Fts5Structure *pNew = 0; int nByte = sizeof(Fts5Structure); int nSeg = pStruct->nSegment; int i; /* Figure out if this structure requires optimization. A structure does ** not require optimization if either: ** ** + it consists of fewer than two segments, or ** + all segments are on the same level, or ** + all segments except one are currently inputs to a merge operation. ** ** In the first case, return NULL. In the second, increment the ref-count ** on *pStruct and return a copy of the pointer to it. */ if( nSeg<2 ) return 0; for(i=0; i<pStruct->nLevel; i++){ int nThis = pStruct->aLevel[i].nSeg; if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){ fts5StructureRef(pStruct); return pStruct; } assert( pStruct->aLevel[i].nMerge<=nThis ); } nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel); pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte); if( pNew ){ Fts5StructureLevel *pLvl; nByte = nSeg * sizeof(Fts5StructureSegment); pNew->nLevel = pStruct->nLevel+1; pNew->nRef = 1; pNew->nWriteCounter = pStruct->nWriteCounter; pLvl = &pNew->aLevel[pStruct->nLevel]; pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte); if( pLvl->aSeg ){ int iLvl, iSeg; int iSegOut = 0; /* Iterate through all segments, from oldest to newest. Add them to ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest ** segment in the data structure. */ for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){ pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg]; iSegOut++; } } pNew->nSegment = pLvl->nSeg = nSeg; }else{ sqlite3_free(pNew); pNew = 0; } } return pNew; } static int sqlite3Fts5IndexOptimize(Fts5Index *p){ Fts5Structure *pStruct; Fts5Structure *pNew = 0; assert( p->rc==SQLITE_OK ); fts5IndexFlush(p); pStruct = fts5StructureRead(p); fts5StructureInvalidate(p); if( pStruct ){ pNew = fts5IndexOptimizeStruct(p, pStruct); } fts5StructureRelease(pStruct); assert( pNew==0 || pNew->nSegment>0 ); if( pNew ){ int iLvl; for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){} while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){ int nRem = FTS5_OPT_WORK_UNIT; fts5IndexMergeLevel(p, &pNew, iLvl, &nRem); } fts5StructureWrite(p, pNew); fts5StructureRelease(pNew); } return fts5IndexReturn(p); } /* ** This is called to implement the special "VALUES('merge', $nMerge)" ** INSERT command. */ static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){ Fts5Structure *pStruct = fts5StructureRead(p); if( pStruct ){ int nMin = p->pConfig->nUsermerge; fts5StructureInvalidate(p); if( nMerge<0 ){ Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct); fts5StructureRelease(pStruct); pStruct = pNew; nMin = 2; nMerge = nMerge*-1; } if( pStruct && pStruct->nLevel ){ if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){ fts5StructureWrite(p, pStruct); } } fts5StructureRelease(pStruct); } return fts5IndexReturn(p); } static void fts5AppendRowid( Fts5Index *p, i64 iDelta, Fts5Iter *pUnused, Fts5Buffer *pBuf ){ UNUSED_PARAM(pUnused); fts5BufferAppendVarint(&p->rc, pBuf, iDelta); } static void fts5AppendPoslist( Fts5Index *p, i64 iDelta, Fts5Iter *pMulti, Fts5Buffer *pBuf ){ int nData = pMulti->base.nData; assert( nData>0 ); if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){ fts5BufferSafeAppendVarint(pBuf, iDelta); fts5BufferSafeAppendVarint(pBuf, nData*2); fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData); } } static void fts5DoclistIterNext(Fts5DoclistIter *pIter){ u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist; assert( pIter->aPoslist ); if( p>=pIter->aEof ){ pIter->aPoslist = 0; }else{ i64 iDelta; p += fts5GetVarint(p, (u64*)&iDelta); pIter->iRowid += iDelta; /* Read position list size */ if( p[0] & 0x80 ){ int nPos; pIter->nSize = fts5GetVarint32(p, nPos); pIter->nPoslist = (nPos>>1); }else{ pIter->nPoslist = ((int)(p[0])) >> 1; pIter->nSize = 1; } pIter->aPoslist = p; } } static void fts5DoclistIterInit( Fts5Buffer *pBuf, Fts5DoclistIter *pIter ){ memset(pIter, 0, sizeof(*pIter)); pIter->aPoslist = pBuf->p; pIter->aEof = &pBuf->p[pBuf->n]; fts5DoclistIterNext(pIter); } #if 0 /* ** Append a doclist to buffer pBuf. ** ** This function assumes that space within the buffer has already been ** allocated. */ static void fts5MergeAppendDocid( Fts5Buffer *pBuf, /* Buffer to write to */ i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */ i64 iRowid /* Rowid to append */ ){ assert( pBuf->n!=0 || (*piLastRowid)==0 ); fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid); *piLastRowid = iRowid; } #endif #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \ assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \ fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \ (iLastRowid) = (iRowid); \ } /* ** Swap the contents of buffer *p1 with that of *p2. */ static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){ Fts5Buffer tmp = *p1; *p1 = *p2; *p2 = tmp; } static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){ int i = *piOff; if( i>=pBuf->n ){ *piOff = -1; }else{ u64 iVal; *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal); *piRowid += iVal; } } /* ** This is the equivalent of fts5MergePrefixLists() for detail=none mode. ** In this case the buffers consist of a delta-encoded list of rowids only. */ static void fts5MergeRowidLists( Fts5Index *p, /* FTS5 backend object */ Fts5Buffer *p1, /* First list to merge */ Fts5Buffer *p2 /* Second list to merge */ ){ int i1 = 0; int i2 = 0; i64 iRowid1 = 0; i64 iRowid2 = 0; i64 iOut = 0; Fts5Buffer out; memset(&out, 0, sizeof(out)); sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n); if( p->rc ) return; fts5NextRowid(p1, &i1, &iRowid1); fts5NextRowid(p2, &i2, &iRowid2); while( i1>=0 || i2>=0 ){ if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){ assert( iOut==0 || iRowid1>iOut ); fts5BufferSafeAppendVarint(&out, iRowid1 - iOut); iOut = iRowid1; fts5NextRowid(p1, &i1, &iRowid1); }else{ assert( iOut==0 || iRowid2>iOut ); fts5BufferSafeAppendVarint(&out, iRowid2 - iOut); iOut = iRowid2; if( i1>=0 && iRowid1==iRowid2 ){ fts5NextRowid(p1, &i1, &iRowid1); } fts5NextRowid(p2, &i2, &iRowid2); } } fts5BufferSwap(&out, p1); fts5BufferFree(&out); } /* ** Buffers p1 and p2 contain doclists. This function merges the content ** of the two doclists together and sets buffer p1 to the result before ** returning. ** ** If an error occurs, an error code is left in p->rc. If an error has ** already occurred, this function is a no-op. */ static void fts5MergePrefixLists( Fts5Index *p, /* FTS5 backend object */ Fts5Buffer *p1, /* First list to merge */ Fts5Buffer *p2 /* Second list to merge */ ){ if( p2->n ){ i64 iLastRowid = 0; Fts5DoclistIter i1; Fts5DoclistIter i2; Fts5Buffer out = {0, 0, 0}; Fts5Buffer tmp = {0, 0, 0}; if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return; fts5DoclistIterInit(p1, &i1); fts5DoclistIterInit(p2, &i2); while( 1 ){ if( i1.iRowid<i2.iRowid ){ /* Copy entry from i1 */ fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid); fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize); fts5DoclistIterNext(&i1); if( i1.aPoslist==0 ) break; } else if( i2.iRowid!=i1.iRowid ){ /* Copy entry from i2 */ fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid); fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize); fts5DoclistIterNext(&i2); if( i2.aPoslist==0 ) break; } else{ /* Merge the two position lists. */ i64 iPos1 = 0; i64 iPos2 = 0; int iOff1 = 0; int iOff2 = 0; u8 *a1 = &i1.aPoslist[i1.nSize]; u8 *a2 = &i2.aPoslist[i2.nSize]; i64 iPrev = 0; Fts5PoslistWriter writer; memset(&writer, 0, sizeof(writer)); fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid); fts5BufferZero(&tmp); sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist); if( p->rc ) break; sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); assert( iPos1>=0 && iPos2>=0 ); if( iPos1<iPos2 ){ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); }else{ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); } if( iPos1>=0 && iPos2>=0 ){ while( 1 ){ if( iPos1<iPos2 ){ if( iPos1!=iPrev ){ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); } sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); if( iPos1<0 ) break; }else{ assert( iPos2!=iPrev ); sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); if( iPos2<0 ) break; } } } if( iPos1>=0 ){ if( iPos1!=iPrev ){ sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); } fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1); }else{ assert( iPos2>=0 && iPos2!=iPrev ); sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2); } /* WRITEPOSLISTSIZE */ fts5BufferSafeAppendVarint(&out, tmp.n * 2); fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n); fts5DoclistIterNext(&i1); fts5DoclistIterNext(&i2); if( i1.aPoslist==0 || i2.aPoslist==0 ) break; } } if( i1.aPoslist ){ fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid); fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist); } else if( i2.aPoslist ){ fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid); fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist); } fts5BufferSet(&p->rc, p1, out.n, out.p); fts5BufferFree(&tmp); fts5BufferFree(&out); } } static void fts5SetupPrefixIter( Fts5Index *p, /* Index to read from */ int bDesc, /* True for "ORDER BY rowid DESC" */ const u8 *pToken, /* Buffer containing prefix to match */ int nToken, /* Size of buffer pToken in bytes */ Fts5Colset *pColset, /* Restrict matches to these columns */ Fts5Iter **ppIter /* OUT: New iterator */ ){ Fts5Structure *pStruct; Fts5Buffer *aBuf; const int nBuf = 32; void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*); void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*); if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){ xMerge = fts5MergeRowidLists; xAppend = fts5AppendRowid; }else{ xMerge = fts5MergePrefixLists; xAppend = fts5AppendPoslist; } aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf); pStruct = fts5StructureRead(p); if( aBuf && pStruct ){ const int flags = FTS5INDEX_QUERY_SCAN | FTS5INDEX_QUERY_SKIPEMPTY | FTS5INDEX_QUERY_NOOUTPUT; int i; i64 iLastRowid = 0; Fts5Iter *p1 = 0; /* Iterator used to gather data from index */ Fts5Data *pData; Fts5Buffer doclist; int bNewTerm = 1; memset(&doclist, 0, sizeof(doclist)); fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1); fts5IterSetOutputCb(&p->rc, p1); for( /* no-op */ ; fts5MultiIterEof(p, p1)==0; fts5MultiIterNext2(p, p1, &bNewTerm) ){ Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ]; int nTerm = pSeg->term.n; const u8 *pTerm = pSeg->term.p; p1->xSetOutputs(p1, pSeg); assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 ); if( bNewTerm ){ if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break; } if( p1->base.nData==0 ) continue; if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){ for(i=0; p->rc==SQLITE_OK && doclist.n; i++){ assert( i<nBuf ); if( aBuf[i].n==0 ){ fts5BufferSwap(&doclist, &aBuf[i]); fts5BufferZero(&doclist); }else{ xMerge(p, &doclist, &aBuf[i]); fts5BufferZero(&aBuf[i]); } } iLastRowid = 0; } xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist); iLastRowid = p1->base.iRowid; } for(i=0; i<nBuf; i++){ if( p->rc==SQLITE_OK ){ xMerge(p, &doclist, &aBuf[i]); } fts5BufferFree(&aBuf[i]); } fts5MultiIterFree(p1); pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n); if( pData ){ pData->p = (u8*)&pData[1]; pData->nn = pData->szLeaf = doclist.n; memcpy(pData->p, doclist.p, doclist.n); fts5MultiIterNew2(p, pData, bDesc, ppIter); } fts5BufferFree(&doclist); } fts5StructureRelease(pStruct); sqlite3_free(aBuf); } /* ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain ** to the document with rowid iRowid. */ static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){ assert( p->rc==SQLITE_OK ); /* Allocate the hash table if it has not already been allocated */ if( p->pHash==0 ){ p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData); } /* Flush the hash table to disk if required */ if( iRowid<p->iWriteRowid || (iRowid==p->iWriteRowid && p->bDelete==0) || (p->nPendingData > p->pConfig->nHashSize) ){ fts5IndexFlush(p); } p->iWriteRowid = iRowid; p->bDelete = bDelete; return fts5IndexReturn(p); } /* ** Commit data to disk. */ static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){ assert( p->rc==SQLITE_OK ); fts5IndexFlush(p); if( bCommit ) fts5CloseReader(p); return fts5IndexReturn(p); } /* ** Discard any data stored in the in-memory hash tables. Do not write it ** to the database. Additionally, assume that the contents of the %_data ** table may have changed on disk. So any in-memory caches of %_data ** records must be invalidated. */ static int sqlite3Fts5IndexRollback(Fts5Index *p){ fts5CloseReader(p); fts5IndexDiscardData(p); fts5StructureInvalidate(p); /* assert( p->rc==SQLITE_OK ); */ return SQLITE_OK; } /* ** The %_data table is completely empty when this function is called. This ** function populates it with the initial structure objects for each index, ** and the initial version of the "averages" record (a zero-byte blob). */ static int sqlite3Fts5IndexReinit(Fts5Index *p){ Fts5Structure s; fts5StructureInvalidate(p); memset(&s, 0, sizeof(Fts5Structure)); fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0); fts5StructureWrite(p, &s); return fts5IndexReturn(p); } /* ** Open a new Fts5Index handle. If the bCreate argument is true, create ** and initialize the underlying %_data table. ** ** If successful, set *pp to point to the new object and return SQLITE_OK. ** Otherwise, set *pp to NULL and return an SQLite error code. */ static int sqlite3Fts5IndexOpen( Fts5Config *pConfig, int bCreate, Fts5Index **pp, char **pzErr ){ int rc = SQLITE_OK; Fts5Index *p; /* New object */ *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index)); if( rc==SQLITE_OK ){ p->pConfig = pConfig; p->nWorkUnit = FTS5_WORK_UNIT; p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName); if( p->zDataTbl && bCreate ){ rc = sqlite3Fts5CreateTable( pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr ); if( rc==SQLITE_OK ){ rc = sqlite3Fts5CreateTable(pConfig, "idx", "segid, term, pgno, PRIMARY KEY(segid, term)", 1, pzErr ); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5IndexReinit(p); } } } assert( rc!=SQLITE_OK || p->rc==SQLITE_OK ); if( rc ){ sqlite3Fts5IndexClose(p); *pp = 0; } return rc; } /* ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen(). */ static int sqlite3Fts5IndexClose(Fts5Index *p){ int rc = SQLITE_OK; if( p ){ assert( p->pReader==0 ); fts5StructureInvalidate(p); sqlite3_finalize(p->pWriter); sqlite3_finalize(p->pDeleter); sqlite3_finalize(p->pIdxWriter); sqlite3_finalize(p->pIdxDeleter); sqlite3_finalize(p->pIdxSelect); sqlite3_finalize(p->pDataVersion); sqlite3Fts5HashFree(p->pHash); sqlite3_free(p->zDataTbl); sqlite3_free(p); } return rc; } /* ** Argument p points to a buffer containing utf-8 text that is n bytes in ** size. Return the number of bytes in the nChar character prefix of the ** buffer, or 0 if there are less than nChar characters in total. */ static int sqlite3Fts5IndexCharlenToBytelen( const char *p, int nByte, int nChar ){ int n = 0; int i; for(i=0; i<nChar; i++){ if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */ if( (unsigned char)p[n++]>=0xc0 ){ while( (p[n] & 0xc0)==0x80 ) n++; } } return n; } /* ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of ** unicode characters in the string. */ static int fts5IndexCharlen(const char *pIn, int nIn){ int nChar = 0; int i = 0; while( i<nIn ){ if( (unsigned char)pIn[i++]>=0xc0 ){ while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++; } nChar++; } return nChar; } /* ** Insert or remove data to or from the index. Each time a document is ** added to or removed from the index, this function is called one or more ** times. ** ** For an insert, it must be called once for each token in the new document. ** If the operation is a delete, it must be called (at least) once for each ** unique token in the document with an iCol value less than zero. The iPos ** argument is ignored for a delete. */ static int sqlite3Fts5IndexWrite( Fts5Index *p, /* Index to write to */ int iCol, /* Column token appears in (-ve -> delete) */ int iPos, /* Position of token within column */ const char *pToken, int nToken /* Token to add or remove to or from index */ ){ int i; /* Used to iterate through indexes */ int rc = SQLITE_OK; /* Return code */ Fts5Config *pConfig = p->pConfig; assert( p->rc==SQLITE_OK ); assert( (iCol<0)==p->bDelete ); /* Add the entry to the main terms index. */ rc = sqlite3Fts5HashWrite( p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken ); for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){ const int nChar = pConfig->aPrefix[i]; int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar); if( nByte ){ rc = sqlite3Fts5HashWrite(p->pHash, p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken, nByte ); } } return rc; } /* ** Open a new iterator to iterate though all rowid that match the ** specified token or token prefix. */ static int sqlite3Fts5IndexQuery( Fts5Index *p, /* FTS index to query */ const char *pToken, int nToken, /* Token (or prefix) to query for */ int flags, /* Mask of FTS5INDEX_QUERY_X flags */ Fts5Colset *pColset, /* Match these columns only */ Fts5IndexIter **ppIter /* OUT: New iterator object */ ){ Fts5Config *pConfig = p->pConfig; Fts5Iter *pRet = 0; Fts5Buffer buf = {0, 0, 0}; /* If the QUERY_SCAN flag is set, all other flags must be clear. */ assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN ); if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){ int iIdx = 0; /* Index to search */ memcpy(&buf.p[1], pToken, nToken); /* Figure out which index to search and set iIdx accordingly. If this ** is a prefix query for which there is no prefix index, set iIdx to ** greater than pConfig->nPrefix to indicate that the query will be ** satisfied by scanning multiple terms in the main index. ** ** If the QUERY_TEST_NOIDX flag was specified, then this must be a ** prefix-query. Instead of using a prefix-index (if one exists), ** evaluate the prefix query using the main FTS index. This is used ** for internal sanity checking by the integrity-check in debug ** mode only. */ #ifdef SQLITE_DEBUG if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){ assert( flags & FTS5INDEX_QUERY_PREFIX ); iIdx = 1+pConfig->nPrefix; }else #endif if( flags & FTS5INDEX_QUERY_PREFIX ){ int nChar = fts5IndexCharlen(pToken, nToken); for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){ if( pConfig->aPrefix[iIdx-1]==nChar ) break; } } if( iIdx<=pConfig->nPrefix ){ /* Straight index lookup */ Fts5Structure *pStruct = fts5StructureRead(p); buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx); if( pStruct ){ fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY, pColset, buf.p, nToken+1, -1, 0, &pRet ); fts5StructureRelease(pStruct); } }else{ /* Scan multiple terms in the main index */ int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0; buf.p[0] = FTS5_MAIN_PREFIX; fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet); assert( p->rc!=SQLITE_OK || pRet->pColset==0 ); fts5IterSetOutputCb(&p->rc, pRet); if( p->rc==SQLITE_OK ){ Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst]; if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg); } } if( p->rc ){ sqlite3Fts5IterClose(&pRet->base); pRet = 0; fts5CloseReader(p); } *ppIter = &pRet->base; sqlite3Fts5BufferFree(&buf); } return fts5IndexReturn(p); } /* ** Return true if the iterator passed as the only argument is at EOF. */ /* ** Move to the next matching rowid. */ static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; assert( pIter->pIndex->rc==SQLITE_OK ); fts5MultiIterNext(pIter->pIndex, pIter, 0, 0); return fts5IndexReturn(pIter->pIndex); } /* ** Move to the next matching term/rowid. Used by the fts5vocab module. */ static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; Fts5Index *p = pIter->pIndex; assert( pIter->pIndex->rc==SQLITE_OK ); fts5MultiIterNext(p, pIter, 0, 0); if( p->rc==SQLITE_OK ){ Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ]; if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){ fts5DataRelease(pSeg->pLeaf); pSeg->pLeaf = 0; pIter->base.bEof = 1; } } return fts5IndexReturn(pIter->pIndex); } /* ** Move to the next matching rowid that occurs at or after iMatch. The ** definition of "at or after" depends on whether this iterator iterates ** in ascending or descending rowid order. */ static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch); return fts5IndexReturn(pIter->pIndex); } /* ** Return the current term. */ static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){ int n; const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n); *pn = n-1; return &z[1]; } /* ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery(). */ static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){ if( pIndexIter ){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; Fts5Index *pIndex = pIter->pIndex; fts5MultiIterFree(pIter); fts5CloseReader(pIndex); } } /* ** Read and decode the "averages" record from the database. ** ** Parameter anSize must point to an array of size nCol, where nCol is ** the number of user defined columns in the FTS table. */ static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){ int nCol = p->pConfig->nCol; Fts5Data *pData; *pnRow = 0; memset(anSize, 0, sizeof(i64) * nCol); pData = fts5DataRead(p, FTS5_AVERAGES_ROWID); if( p->rc==SQLITE_OK && pData->nn ){ int i = 0; int iCol; i += fts5GetVarint(&pData->p[i], (u64*)pnRow); for(iCol=0; i<pData->nn && iCol<nCol; iCol++){ i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]); } } fts5DataRelease(pData); return fts5IndexReturn(p); } /* ** Replace the current "averages" record with the contents of the buffer ** supplied as the second argument. */ static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){ assert( p->rc==SQLITE_OK ); fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData); return fts5IndexReturn(p); } /* ** Return the total number of blocks this module has read from the %_data ** table since it was created. */ static int sqlite3Fts5IndexReads(Fts5Index *p){ return p->nRead; } /* ** Set the 32-bit cookie value stored at the start of all structure ** records to the value passed as the second argument. ** ** Return SQLITE_OK if successful, or an SQLite error code if an error ** occurs. */ static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){ int rc; /* Return code */ Fts5Config *pConfig = p->pConfig; /* Configuration object */ u8 aCookie[4]; /* Binary representation of iNew */ sqlite3_blob *pBlob = 0; assert( p->rc==SQLITE_OK ); sqlite3Fts5Put32(aCookie, iNew); rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, "block", FTS5_STRUCTURE_ROWID, 1, &pBlob ); if( rc==SQLITE_OK ){ sqlite3_blob_write(pBlob, aCookie, 4, 0); rc = sqlite3_blob_close(pBlob); } return rc; } static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){ Fts5Structure *pStruct; pStruct = fts5StructureRead(p); fts5StructureRelease(pStruct); return fts5IndexReturn(p); } /************************************************************************* ************************************************************************** ** Below this point is the implementation of the integrity-check ** functionality. */ /* ** Return a simple checksum value based on the arguments. */ static u64 sqlite3Fts5IndexEntryCksum( i64 iRowid, int iCol, int iPos, int iIdx, const char *pTerm, int nTerm ){ int i; u64 ret = iRowid; ret += (ret<<3) + iCol; ret += (ret<<3) + iPos; if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx); for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i]; return ret; } #ifdef SQLITE_DEBUG /* ** This function is purely an internal test. It does not contribute to ** FTS functionality, or even the integrity-check, in any way. ** ** Instead, it tests that the same set of pgno/rowid combinations are ** visited regardless of whether the doclist-index identified by parameters ** iSegid/iLeaf is iterated in forwards or reverse order. */ static void fts5TestDlidxReverse( Fts5Index *p, int iSegid, /* Segment id to load from */ int iLeaf /* Load doclist-index for this leaf */ ){ Fts5DlidxIter *pDlidx = 0; u64 cksum1 = 13; u64 cksum2 = 13; for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf); fts5DlidxIterEof(p, pDlidx)==0; fts5DlidxIterNext(p, pDlidx) ){ i64 iRowid = fts5DlidxIterRowid(pDlidx); int pgno = fts5DlidxIterPgno(pDlidx); assert( pgno>iLeaf ); cksum1 += iRowid + ((i64)pgno<<32); } fts5DlidxIterFree(pDlidx); pDlidx = 0; for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf); fts5DlidxIterEof(p, pDlidx)==0; fts5DlidxIterPrev(p, pDlidx) ){ i64 iRowid = fts5DlidxIterRowid(pDlidx); int pgno = fts5DlidxIterPgno(pDlidx); assert( fts5DlidxIterPgno(pDlidx)>iLeaf ); cksum2 += iRowid + ((i64)pgno<<32); } fts5DlidxIterFree(pDlidx); pDlidx = 0; if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT; } static int fts5QueryCksum( Fts5Index *p, /* Fts5 index object */ int iIdx, const char *z, /* Index key to query for */ int n, /* Size of index key in bytes */ int flags, /* Flags for Fts5IndexQuery */ u64 *pCksum /* IN/OUT: Checksum value */ ){ int eDetail = p->pConfig->eDetail; u64 cksum = *pCksum; Fts5IndexIter *pIter = 0; int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter); while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){ i64 rowid = pIter->iRowid; if( eDetail==FTS5_DETAIL_NONE ){ cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n); }else{ Fts5PoslistReader sReader; for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader); sReader.bEof==0; sqlite3Fts5PoslistReaderNext(&sReader) ){ int iCol = FTS5_POS2COLUMN(sReader.iPos); int iOff = FTS5_POS2OFFSET(sReader.iPos); cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n); } } if( rc==SQLITE_OK ){ rc = sqlite3Fts5IterNext(pIter); } } sqlite3Fts5IterClose(pIter); *pCksum = cksum; return rc; } /* ** This function is also purely an internal test. It does not contribute to ** FTS functionality, or even the integrity-check, in any way. */ static void fts5TestTerm( Fts5Index *p, Fts5Buffer *pPrev, /* Previous term */ const char *z, int n, /* Possibly new term to test */ u64 expected, u64 *pCksum ){ int rc = p->rc; if( pPrev->n==0 ){ fts5BufferSet(&rc, pPrev, n, (const u8*)z); }else if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){ u64 cksum3 = *pCksum; const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */ int nTerm = pPrev->n-1; /* Size of zTerm in bytes */ int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX); int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX); u64 ck1 = 0; u64 ck2 = 0; /* Check that the results returned for ASC and DESC queries are ** the same. If not, call this corruption. */ rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1); if( rc==SQLITE_OK ){ int f = flags|FTS5INDEX_QUERY_DESC; rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2); } if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT; /* If this is a prefix query, check that the results returned if the ** the index is disabled are the same. In both ASC and DESC order. ** ** This check may only be performed if the hash table is empty. This ** is because the hash table only supports a single scan query at ** a time, and the multi-iter loop from which this function is called ** is already performing such a scan. */ if( p->nPendingData==0 ){ if( iIdx>0 && rc==SQLITE_OK ){ int f = flags|FTS5INDEX_QUERY_TEST_NOIDX; ck2 = 0; rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2); if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT; } if( iIdx>0 && rc==SQLITE_OK ){ int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC; ck2 = 0; rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2); if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT; } } cksum3 ^= ck1; fts5BufferSet(&rc, pPrev, n, (const u8*)z); if( rc==SQLITE_OK && cksum3!=expected ){ rc = FTS5_CORRUPT; } *pCksum = cksum3; } p->rc = rc; } #else # define fts5TestDlidxReverse(x,y,z) # define fts5TestTerm(u,v,w,x,y,z) #endif /* ** Check that: ** ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and ** contain zero terms. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and ** contain zero rowids. */ static void fts5IndexIntegrityCheckEmpty( Fts5Index *p, Fts5StructureSegment *pSeg, /* Segment to check internal consistency */ int iFirst, int iNoRowid, int iLast ){ int i; /* Now check that the iter.nEmpty leaves following the current leaf ** (a) exist and (b) contain no terms. */ for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){ Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i)); if( pLeaf ){ if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT; if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT; } fts5DataRelease(pLeaf); } } static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){ int iTermOff = 0; int ii; Fts5Buffer buf1 = {0,0,0}; Fts5Buffer buf2 = {0,0,0}; ii = pLeaf->szLeaf; while( ii<pLeaf->nn && p->rc==SQLITE_OK ){ int res; int iOff; int nIncr; ii += fts5GetVarint32(&pLeaf->p[ii], nIncr); iTermOff += nIncr; iOff = iTermOff; if( iOff>=pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; }else if( iTermOff==nIncr ){ int nByte; iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte); if( (iOff+nByte)>pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; }else{ fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]); } }else{ int nKeep, nByte; iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep); iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte); if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; }else{ buf1.n = nKeep; fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]); } if( p->rc==SQLITE_OK ){ res = fts5BufferCompare(&buf1, &buf2); if( res<=0 ) p->rc = FTS5_CORRUPT; } } fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p); } fts5BufferFree(&buf1); fts5BufferFree(&buf2); } static void fts5IndexIntegrityCheckSegment( Fts5Index *p, /* FTS5 backend object */ Fts5StructureSegment *pSeg /* Segment to check internal consistency */ ){ Fts5Config *pConfig = p->pConfig; sqlite3_stmt *pStmt = 0; int rc2; int iIdxPrevLeaf = pSeg->pgnoFirst-1; int iDlidxPrevLeaf = pSeg->pgnoLast; if( pSeg->pgnoFirst==0 ) return; fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf( "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d", pConfig->zDb, pConfig->zName, pSeg->iSegid )); /* Iterate through the b-tree hierarchy. */ while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ i64 iRow; /* Rowid for this leaf */ Fts5Data *pLeaf; /* Data for this leaf */ int nIdxTerm = sqlite3_column_bytes(pStmt, 1); const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1); int iIdxLeaf = sqlite3_column_int(pStmt, 2); int bIdxDlidx = sqlite3_column_int(pStmt, 3); /* If the leaf in question has already been trimmed from the segment, ** ignore this b-tree entry. Otherwise, load it into memory. */ if( iIdxLeaf<pSeg->pgnoFirst ) continue; iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf); pLeaf = fts5LeafRead(p, iRow); if( pLeaf==0 ) break; /* Check that the leaf contains at least one term, and that it is equal ** to or larger than the split-key in zIdxTerm. Also check that if there ** is also a rowid pointer within the leaf page header, it points to a ** location before the term. */ if( pLeaf->nn<=pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; }else{ int iOff; /* Offset of first term on leaf */ int iRowidOff; /* Offset of first rowid on leaf */ int nTerm; /* Size of term on leaf in bytes */ int res; /* Comparison of term and split-key */ iOff = fts5LeafFirstTermOff(pLeaf); iRowidOff = fts5LeafFirstRowidOff(pLeaf); if( iRowidOff>=iOff ){ p->rc = FTS5_CORRUPT; }else{ iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm); res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm)); if( res==0 ) res = nTerm - nIdxTerm; if( res<0 ) p->rc = FTS5_CORRUPT; } fts5IntegrityCheckPgidx(p, pLeaf); } fts5DataRelease(pLeaf); if( p->rc ) break; /* Now check that the iter.nEmpty leaves following the current leaf ** (a) exist and (b) contain no terms. */ fts5IndexIntegrityCheckEmpty( p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1 ); if( p->rc ) break; /* If there is a doclist-index, check that it looks right. */ if( bIdxDlidx ){ Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */ int iPrevLeaf = iIdxLeaf; int iSegid = pSeg->iSegid; int iPg = 0; i64 iKey; for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf); fts5DlidxIterEof(p, pDlidx)==0; fts5DlidxIterNext(p, pDlidx) ){ /* Check any rowid-less pages that occur before the current leaf. */ for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){ iKey = FTS5_SEGMENT_ROWID(iSegid, iPg); pLeaf = fts5DataRead(p, iKey); if( pLeaf ){ if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT; fts5DataRelease(pLeaf); } } iPrevLeaf = fts5DlidxIterPgno(pDlidx); /* Check that the leaf page indicated by the iterator really does ** contain the rowid suggested by the same. */ iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf); pLeaf = fts5DataRead(p, iKey); if( pLeaf ){ i64 iRowid; int iRowidOff = fts5LeafFirstRowidOff(pLeaf); ASSERT_SZLEAF_OK(pLeaf); if( iRowidOff>=pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; }else{ fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid); if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT; } fts5DataRelease(pLeaf); } } iDlidxPrevLeaf = iPg; fts5DlidxIterFree(pDlidx); fts5TestDlidxReverse(p, iSegid, iIdxLeaf); }else{ iDlidxPrevLeaf = pSeg->pgnoLast; /* TODO: Check there is no doclist index */ } iIdxPrevLeaf = iIdxLeaf; } rc2 = sqlite3_finalize(pStmt); if( p->rc==SQLITE_OK ) p->rc = rc2; /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */ #if 0 if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){ p->rc = FTS5_CORRUPT; } #endif } /* ** Run internal checks to ensure that the FTS index (a) is internally ** consistent and (b) contains entries for which the XOR of the checksums ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum. ** ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the ** checksum does not match. Return SQLITE_OK if all checks pass without ** error, or some other SQLite error code if another error (e.g. OOM) ** occurs. */ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){ int eDetail = p->pConfig->eDetail; u64 cksum2 = 0; /* Checksum based on contents of indexes */ Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */ Fts5Iter *pIter; /* Used to iterate through entire index */ Fts5Structure *pStruct; /* Index structure */ #ifdef SQLITE_DEBUG /* Used by extra internal tests only run if NDEBUG is not defined */ u64 cksum3 = 0; /* Checksum based on contents of indexes */ Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */ #endif const int flags = FTS5INDEX_QUERY_NOOUTPUT; /* Load the FTS index structure */ pStruct = fts5StructureRead(p); /* Check that the internal nodes of each segment match the leaves */ if( pStruct ){ int iLvl, iSeg; for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){ Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg]; fts5IndexIntegrityCheckSegment(p, pSeg); } } } /* The cksum argument passed to this function is a checksum calculated ** based on all expected entries in the FTS index (including prefix index ** entries). This block checks that a checksum calculated based on the ** actual contents of FTS index is identical. ** ** Two versions of the same checksum are calculated. The first (stack ** variable cksum2) based on entries extracted from the full-text index ** while doing a linear scan of each individual index in turn. ** ** As each term visited by the linear scans, a separate query for the ** same term is performed. cksum3 is calculated based on the entries ** extracted by these queries. */ for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter); fts5MultiIterEof(p, pIter)==0; fts5MultiIterNext(p, pIter, 0, 0) ){ int n; /* Size of term in bytes */ i64 iPos = 0; /* Position read from poslist */ int iOff = 0; /* Offset within poslist */ i64 iRowid = fts5MultiIterRowid(pIter); char *z = (char*)fts5MultiIterTerm(pIter, &n); /* If this is a new term, query for it. Update cksum3 with the results. */ fts5TestTerm(p, &term, z, n, cksum2, &cksum3); if( eDetail==FTS5_DETAIL_NONE ){ if( 0==fts5MultiIterIsEmpty(p, pIter) ){ cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n); } }else{ poslist.n = 0; fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist); while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){ int iCol = FTS5_POS2COLUMN(iPos); int iTokOff = FTS5_POS2OFFSET(iPos); cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n); } } } fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3); fts5MultiIterFree(pIter); if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT; fts5StructureRelease(pStruct); #ifdef SQLITE_DEBUG fts5BufferFree(&term); #endif fts5BufferFree(&poslist); return fts5IndexReturn(p); } /************************************************************************* ************************************************************************** ** Below this point is the implementation of the fts5_decode() scalar ** function only. */ /* ** Decode a segment-data rowid from the %_data table. This function is ** the opposite of macro FTS5_SEGMENT_ROWID(). */ static void fts5DecodeRowid( i64 iRowid, /* Rowid from %_data table */ int *piSegid, /* OUT: Segment id */ int *pbDlidx, /* OUT: Dlidx flag */ int *piHeight, /* OUT: Height */ int *piPgno /* OUT: Page number */ ){ *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1)); iRowid >>= FTS5_DATA_PAGE_B; *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1)); iRowid >>= FTS5_DATA_HEIGHT_B; *pbDlidx = (int)(iRowid & 0x0001); iRowid >>= FTS5_DATA_DLI_B; *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1)); } static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){ int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */ fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno); if( iSegid==0 ){ if( iKey==FTS5_AVERAGES_ROWID ){ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} "); }else{ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}"); } } else{ sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}", bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno ); } } static void fts5DebugStructure( int *pRc, /* IN/OUT: error code */ Fts5Buffer *pBuf, Fts5Structure *p ){ int iLvl, iSeg; /* Iterate through levels, segments */ for(iLvl=0; iLvl<p->nLevel; iLvl++){ Fts5StructureLevel *pLvl = &p->aLevel[iLvl]; sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg ); for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){ Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg]; sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}", pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast ); } sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}"); } } /* ** This is part of the fts5_decode() debugging aid. ** ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This ** function appends a human-readable representation of the same object ** to the buffer passed as the second argument. */ static void fts5DecodeStructure( int *pRc, /* IN/OUT: error code */ Fts5Buffer *pBuf, const u8 *pBlob, int nBlob ){ int rc; /* Return code */ Fts5Structure *p = 0; /* Decoded structure object */ rc = fts5StructureDecode(pBlob, nBlob, 0, &p); if( rc!=SQLITE_OK ){ *pRc = rc; return; } fts5DebugStructure(pRc, pBuf, p); fts5StructureRelease(p); } /* ** This is part of the fts5_decode() debugging aid. ** ** Arguments pBlob/nBlob contain an "averages" record. This function ** appends a human-readable representation of record to the buffer passed ** as the second argument. */ static void fts5DecodeAverages( int *pRc, /* IN/OUT: error code */ Fts5Buffer *pBuf, const u8 *pBlob, int nBlob ){ int i = 0; const char *zSpace = ""; while( i<nBlob ){ u64 iVal; i += sqlite3Fts5GetVarint(&pBlob[i], &iVal); sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal); zSpace = " "; } } /* ** Buffer (a/n) is assumed to contain a list of serialized varints. Read ** each varint and append its string representation to buffer pBuf. Return ** after either the input buffer is exhausted or a 0 value is read. ** ** The return value is the number of bytes read from the input buffer. */ static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){ int iOff = 0; while( iOff<n ){ int iVal; iOff += fts5GetVarint32(&a[iOff], iVal); sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal); } return iOff; } /* ** The start of buffer (a/n) contains the start of a doclist. The doclist ** may or may not finish within the buffer. This function appends a text ** representation of the part of the doclist that is present to buffer ** pBuf. ** ** The return value is the number of bytes read from the input buffer. */ static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){ i64 iDocid = 0; int iOff = 0; if( n>0 ){ iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid); sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid); } while( iOff<n ){ int nPos; int bDel; iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel); sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":""); iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos)); if( iOff<n ){ i64 iDelta; iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta); iDocid += iDelta; sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid); } } return iOff; } /* ** This function is part of the fts5_decode() debugging function. It is ** only ever used with detail=none tables. ** ** Buffer (pData/nData) contains a doclist in the format used by detail=none ** tables. This function appends a human-readable version of that list to ** buffer pBuf. ** ** If *pRc is other than SQLITE_OK when this function is called, it is a ** no-op. If an OOM or other error occurs within this function, *pRc is ** set to an SQLite error code before returning. The final state of buffer ** pBuf is undefined in this case. */ static void fts5DecodeRowidList( int *pRc, /* IN/OUT: Error code */ Fts5Buffer *pBuf, /* Buffer to append text to */ const u8 *pData, int nData /* Data to decode list-of-rowids from */ ){ int i = 0; i64 iRowid = 0; while( i<nData ){ const char *zApp = ""; u64 iVal; i += sqlite3Fts5GetVarint(&pData[i], &iVal); iRowid += iVal; if( i<nData && pData[i]==0x00 ){ i++; if( i<nData && pData[i]==0x00 ){ i++; zApp = "+"; }else{ zApp = "*"; } } sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp); } } /* ** The implementation of user-defined scalar function fts5_decode(). */ static void fts5DecodeFunction( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args (always 2) */ sqlite3_value **apVal /* Function arguments */ ){ i64 iRowid; /* Rowid for record being decoded */ int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */ const u8 *aBlob; int n; /* Record to decode */ u8 *a = 0; Fts5Buffer s; /* Build up text to return here */ int rc = SQLITE_OK; /* Return code */ int nSpace = 0; int eDetailNone = (sqlite3_user_data(pCtx)!=0); assert( nArg==2 ); UNUSED_PARAM(nArg); memset(&s, 0, sizeof(Fts5Buffer)); iRowid = sqlite3_value_int64(apVal[0]); /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[] ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents ** buffer overreads even if the record is corrupt. */ n = sqlite3_value_bytes(apVal[1]); aBlob = sqlite3_value_blob(apVal[1]); nSpace = n + FTS5_DATA_ZERO_PADDING; a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace); if( a==0 ) goto decode_out; memcpy(a, aBlob, n); fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno); fts5DebugRowid(&rc, &s, iRowid); if( bDlidx ){ Fts5Data dlidx; Fts5DlidxLvl lvl; dlidx.p = a; dlidx.nn = n; memset(&lvl, 0, sizeof(Fts5DlidxLvl)); lvl.pData = &dlidx; lvl.iLeafPgno = iPgno; for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){ sqlite3Fts5BufferAppendPrintf(&rc, &s, " %d(%lld)", lvl.iLeafPgno, lvl.iRowid ); } }else if( iSegid==0 ){ if( iRowid==FTS5_AVERAGES_ROWID ){ fts5DecodeAverages(&rc, &s, a, n); }else{ fts5DecodeStructure(&rc, &s, a, n); } }else if( eDetailNone ){ Fts5Buffer term; /* Current term read from page */ int szLeaf; int iPgidxOff = szLeaf = fts5GetU16(&a[2]); int iTermOff; int nKeep = 0; int iOff; memset(&term, 0, sizeof(Fts5Buffer)); /* Decode any entries that occur before the first term. */ if( szLeaf<n ){ iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff); }else{ iTermOff = szLeaf; } fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4); iOff = iTermOff; while( iOff<szLeaf ){ int nAppend; /* Read the term data for the next term*/ iOff += fts5GetVarint32(&a[iOff], nAppend); term.n = nKeep; fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]); sqlite3Fts5BufferAppendPrintf( &rc, &s, " term=%.*s", term.n, (const char*)term.p ); iOff += nAppend; /* Figure out where the doclist for this term ends */ if( iPgidxOff<n ){ int nIncr; iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr); iTermOff += nIncr; }else{ iTermOff = szLeaf; } fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff); iOff = iTermOff; if( iOff<szLeaf ){ iOff += fts5GetVarint32(&a[iOff], nKeep); } } fts5BufferFree(&term); }else{ Fts5Buffer term; /* Current term read from page */ int szLeaf; /* Offset of pgidx in a[] */ int iPgidxOff; int iPgidxPrev = 0; /* Previous value read from pgidx */ int iTermOff = 0; int iRowidOff = 0; int iOff; int nDoclist; memset(&term, 0, sizeof(Fts5Buffer)); if( n<4 ){ sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt"); goto decode_out; }else{ iRowidOff = fts5GetU16(&a[0]); iPgidxOff = szLeaf = fts5GetU16(&a[2]); if( iPgidxOff<n ){ fts5GetVarint32(&a[iPgidxOff], iTermOff); } } /* Decode the position list tail at the start of the page */ if( iRowidOff!=0 ){ iOff = iRowidOff; }else if( iTermOff!=0 ){ iOff = iTermOff; }else{ iOff = szLeaf; } fts5DecodePoslist(&rc, &s, &a[4], iOff-4); /* Decode any more doclist data that appears on the page before the ** first term. */ nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff; fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist); while( iPgidxOff<n ){ int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */ int nByte; /* Bytes of data */ int iEnd; iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte); iPgidxPrev += nByte; iOff = iPgidxPrev; if( iPgidxOff<n ){ fts5GetVarint32(&a[iPgidxOff], nByte); iEnd = iPgidxPrev + nByte; }else{ iEnd = szLeaf; } if( bFirst==0 ){ iOff += fts5GetVarint32(&a[iOff], nByte); term.n = nByte; } iOff += fts5GetVarint32(&a[iOff], nByte); fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]); iOff += nByte; sqlite3Fts5BufferAppendPrintf( &rc, &s, " term=%.*s", term.n, (const char*)term.p ); iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff); } fts5BufferFree(&term); } decode_out: sqlite3_free(a); if( rc==SQLITE_OK ){ sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT); }else{ sqlite3_result_error_code(pCtx, rc); } fts5BufferFree(&s); } /* ** The implementation of user-defined scalar function fts5_rowid(). */ static void fts5RowidFunction( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args (always 2) */ sqlite3_value **apVal /* Function arguments */ ){ const char *zArg; if( nArg==0 ){ sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1); }else{ zArg = (const char*)sqlite3_value_text(apVal[0]); if( 0==sqlite3_stricmp(zArg, "segment") ){ i64 iRowid; int segid, pgno; if( nArg!=3 ){ sqlite3_result_error(pCtx, "should be: fts5_rowid('segment', segid, pgno))", -1 ); }else{ segid = sqlite3_value_int(apVal[1]); pgno = sqlite3_value_int(apVal[2]); iRowid = FTS5_SEGMENT_ROWID(segid, pgno); sqlite3_result_int64(pCtx, iRowid); } }else{ sqlite3_result_error(pCtx, "first arg to fts5_rowid() must be 'segment'" , -1 ); } } } /* ** This is called as part of registering the FTS5 module with database ** connection db. It registers several user-defined scalar functions useful ** with FTS5. ** ** If successful, SQLITE_OK is returned. If an error occurs, some other ** SQLite error code is returned instead. */ static int sqlite3Fts5IndexInit(sqlite3 *db){ int rc = sqlite3_create_function( db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0 ); if( rc==SQLITE_OK ){ rc = sqlite3_create_function( db, "fts5_decode_none", 2, SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0 ); } if( rc==SQLITE_OK ){ rc = sqlite3_create_function( db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0 ); } return rc; } static int sqlite3Fts5IndexReset(Fts5Index *p){ assert( p->pStruct==0 || p->iStructVersion!=0 ); if( fts5IndexDataVersion(p)!=p->iStructVersion ){ fts5StructureInvalidate(p); } return fts5IndexReturn(p); } /* ** 2014 Jun 09 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This is an SQLite module implementing full-text search. */ /* #include "fts5Int.h" */ /* ** This variable is set to false when running tests for which the on disk ** structures should not be corrupt. Otherwise, true. If it is false, extra ** assert() conditions in the fts5 code are activated - conditions that are ** only true if it is guaranteed that the fts5 database is not corrupt. */ SQLITE_API int sqlite3_fts5_may_be_corrupt = 1; typedef struct Fts5Auxdata Fts5Auxdata; typedef struct Fts5Auxiliary Fts5Auxiliary; typedef struct Fts5Cursor Fts5Cursor; typedef struct Fts5Sorter Fts5Sorter; typedef struct Fts5Table Fts5Table; typedef struct Fts5TokenizerModule Fts5TokenizerModule; /* ** NOTES ON TRANSACTIONS: ** ** SQLite invokes the following virtual table methods as transactions are ** opened and closed by the user: ** ** xBegin(): Start of a new transaction. ** xSync(): Initial part of two-phase commit. ** xCommit(): Final part of two-phase commit. ** xRollback(): Rollback the transaction. ** ** Anything that is required as part of a commit that may fail is performed ** in the xSync() callback. Current versions of SQLite ignore any errors ** returned by xCommit(). ** ** And as sub-transactions are opened/closed: ** ** xSavepoint(int S): Open savepoint S. ** xRelease(int S): Commit and close savepoint S. ** xRollbackTo(int S): Rollback to start of savepoint S. ** ** During a write-transaction the fts5_index.c module may cache some data ** in-memory. It is flushed to disk whenever xSync(), xRelease() or ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo() ** is called. ** ** Additionally, if SQLITE_DEBUG is defined, an instance of the following ** structure is used to record the current transaction state. This information ** is not required, but it is used in the assert() statements executed by ** function fts5CheckTransactionState() (see below). */ struct Fts5TransactionState { int eState; /* 0==closed, 1==open, 2==synced */ int iSavepoint; /* Number of open savepoints (0 -> none) */ }; /* ** A single object of this type is allocated when the FTS5 module is ** registered with a database handle. It is used to store pointers to ** all registered FTS5 extensions - tokenizers and auxiliary functions. */ struct Fts5Global { fts5_api api; /* User visible part of object (see fts5.h) */ sqlite3 *db; /* Associated database connection */ i64 iNextId; /* Used to allocate unique cursor ids */ Fts5Auxiliary *pAux; /* First in list of all aux. functions */ Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */ Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */ Fts5Cursor *pCsr; /* First in list of all open cursors */ }; /* ** Each auxiliary function registered with the FTS5 module is represented ** by an object of the following type. All such objects are stored as part ** of the Fts5Global.pAux list. */ struct Fts5Auxiliary { Fts5Global *pGlobal; /* Global context for this function */ char *zFunc; /* Function name (nul-terminated) */ void *pUserData; /* User-data pointer */ fts5_extension_function xFunc; /* Callback function */ void (*xDestroy)(void*); /* Destructor function */ Fts5Auxiliary *pNext; /* Next registered auxiliary function */ }; /* ** Each tokenizer module registered with the FTS5 module is represented ** by an object of the following type. All such objects are stored as part ** of the Fts5Global.pTok list. */ struct Fts5TokenizerModule { char *zName; /* Name of tokenizer */ void *pUserData; /* User pointer passed to xCreate() */ fts5_tokenizer x; /* Tokenizer functions */ void (*xDestroy)(void*); /* Destructor function */ Fts5TokenizerModule *pNext; /* Next registered tokenizer module */ }; /* ** Virtual-table object. */ struct Fts5Table { sqlite3_vtab base; /* Base class used by SQLite core */ Fts5Config *pConfig; /* Virtual table configuration */ Fts5Index *pIndex; /* Full-text index */ Fts5Storage *pStorage; /* Document store */ Fts5Global *pGlobal; /* Global (connection wide) data */ Fts5Cursor *pSortCsr; /* Sort data from this cursor */ #ifdef SQLITE_DEBUG struct Fts5TransactionState ts; #endif }; struct Fts5MatchPhrase { Fts5Buffer *pPoslist; /* Pointer to current poslist */ int nTerm; /* Size of phrase in terms */ }; /* ** pStmt: ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank; ** ** aIdx[]: ** There is one entry in the aIdx[] array for each phrase in the query, ** the value of which is the offset within aPoslist[] following the last ** byte of the position list for the corresponding phrase. */ struct Fts5Sorter { sqlite3_stmt *pStmt; i64 iRowid; /* Current rowid */ const u8 *aPoslist; /* Position lists for current row */ int nIdx; /* Number of entries in aIdx[] */ int aIdx[1]; /* Offsets into aPoslist for current row */ }; /* ** Virtual-table cursor object. ** ** iSpecial: ** If this is a 'special' query (refer to function fts5SpecialMatch()), ** then this variable contains the result of the query. ** ** iFirstRowid, iLastRowid: ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the ** cursor iterates in ascending order of rowids, iFirstRowid is the lower ** limit of rowids to return, and iLastRowid the upper. In other words, the ** WHERE clause in the user's query might have been: ** ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid ** ** If the cursor iterates in descending order of rowid, iFirstRowid ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid ** the lower. */ struct Fts5Cursor { sqlite3_vtab_cursor base; /* Base class used by SQLite core */ Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */ int *aColumnSize; /* Values for xColumnSize() */ i64 iCsrId; /* Cursor id */ /* Zero from this point onwards on cursor reset */ int ePlan; /* FTS5_PLAN_XXX value */ int bDesc; /* True for "ORDER BY rowid DESC" queries */ i64 iFirstRowid; /* Return no rowids earlier than this */ i64 iLastRowid; /* Return no rowids later than this */ sqlite3_stmt *pStmt; /* Statement used to read %_content */ Fts5Expr *pExpr; /* Expression for MATCH queries */ Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */ int csrflags; /* Mask of cursor flags (see below) */ i64 iSpecial; /* Result of special query */ /* "rank" function. Populated on demand from vtab.xColumn(). */ char *zRank; /* Custom rank function */ char *zRankArgs; /* Custom rank function args */ Fts5Auxiliary *pRank; /* Rank callback (or NULL) */ int nRankArg; /* Number of trailing arguments for rank() */ sqlite3_value **apRankArg; /* Array of trailing arguments */ sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */ /* Auxiliary data storage */ Fts5Auxiliary *pAux; /* Currently executing extension function */ Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */ /* Cache used by auxiliary functions xInst() and xInstCount() */ Fts5PoslistReader *aInstIter; /* One for each phrase */ int nInstAlloc; /* Size of aInst[] array (entries / 3) */ int nInstCount; /* Number of phrase instances */ int *aInst; /* 3 integers per phrase instance */ }; /* ** Bits that make up the "idxNum" parameter passed indirectly by ** xBestIndex() to xFilter(). */ #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */ #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */ #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */ #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */ #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */ #define FTS5_BI_ORDER_RANK 0x0020 #define FTS5_BI_ORDER_ROWID 0x0040 #define FTS5_BI_ORDER_DESC 0x0080 /* ** Values for Fts5Cursor.csrflags */ #define FTS5CSR_EOF 0x01 #define FTS5CSR_REQUIRE_CONTENT 0x02 #define FTS5CSR_REQUIRE_DOCSIZE 0x04 #define FTS5CSR_REQUIRE_INST 0x08 #define FTS5CSR_FREE_ZRANK 0x10 #define FTS5CSR_REQUIRE_RESEEK 0x20 #define FTS5CSR_REQUIRE_POSLIST 0x40 #define BitFlagAllTest(x,y) (((x) & (y))==(y)) #define BitFlagTest(x,y) (((x) & (y))!=0) /* ** Macros to Set(), Clear() and Test() cursor flags. */ #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag)) #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag)) #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag)) struct Fts5Auxdata { Fts5Auxiliary *pAux; /* Extension to which this belongs */ void *pPtr; /* Pointer value */ void(*xDelete)(void*); /* Destructor */ Fts5Auxdata *pNext; /* Next object in linked list */ }; #ifdef SQLITE_DEBUG #define FTS5_BEGIN 1 #define FTS5_SYNC 2 #define FTS5_COMMIT 3 #define FTS5_ROLLBACK 4 #define FTS5_SAVEPOINT 5 #define FTS5_RELEASE 6 #define FTS5_ROLLBACKTO 7 static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){ switch( op ){ case FTS5_BEGIN: assert( p->ts.eState==0 ); p->ts.eState = 1; p->ts.iSavepoint = -1; break; case FTS5_SYNC: assert( p->ts.eState==1 ); p->ts.eState = 2; break; case FTS5_COMMIT: assert( p->ts.eState==2 ); p->ts.eState = 0; break; case FTS5_ROLLBACK: assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 ); p->ts.eState = 0; break; case FTS5_SAVEPOINT: assert( p->ts.eState==1 ); assert( iSavepoint>=0 ); assert( iSavepoint>p->ts.iSavepoint ); p->ts.iSavepoint = iSavepoint; break; case FTS5_RELEASE: assert( p->ts.eState==1 ); assert( iSavepoint>=0 ); assert( iSavepoint<=p->ts.iSavepoint ); p->ts.iSavepoint = iSavepoint-1; break; case FTS5_ROLLBACKTO: assert( p->ts.eState==1 ); assert( iSavepoint>=0 ); assert( iSavepoint<=p->ts.iSavepoint ); p->ts.iSavepoint = iSavepoint; break; } } #else # define fts5CheckTransactionState(x,y,z) #endif /* ** Return true if pTab is a contentless table. */ static int fts5IsContentless(Fts5Table *pTab){ return pTab->pConfig->eContent==FTS5_CONTENT_NONE; } /* ** Delete a virtual table handle allocated by fts5InitVtab(). */ static void fts5FreeVtab(Fts5Table *pTab){ if( pTab ){ sqlite3Fts5IndexClose(pTab->pIndex); sqlite3Fts5StorageClose(pTab->pStorage); sqlite3Fts5ConfigFree(pTab->pConfig); sqlite3_free(pTab); } } /* ** The xDisconnect() virtual table method. */ static int fts5DisconnectMethod(sqlite3_vtab *pVtab){ fts5FreeVtab((Fts5Table*)pVtab); return SQLITE_OK; } /* ** The xDestroy() virtual table method. */ static int fts5DestroyMethod(sqlite3_vtab *pVtab){ Fts5Table *pTab = (Fts5Table*)pVtab; int rc = sqlite3Fts5DropAll(pTab->pConfig); if( rc==SQLITE_OK ){ fts5FreeVtab((Fts5Table*)pVtab); } return rc; } /* ** This function is the implementation of both the xConnect and xCreate ** methods of the FTS3 virtual table. ** ** The argv[] array contains the following: ** ** argv[0] -> module name ("fts5") ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> "column name" and other module argument fields. */ static int fts5InitVtab( int bCreate, /* True for xCreate, false for xConnect */ sqlite3 *db, /* The SQLite database connection */ void *pAux, /* Hash table containing tokenizers */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ char **pzErr /* Write any error message here */ ){ Fts5Global *pGlobal = (Fts5Global*)pAux; const char **azConfig = (const char**)argv; int rc = SQLITE_OK; /* Return code */ Fts5Config *pConfig = 0; /* Results of parsing argc/argv */ Fts5Table *pTab = 0; /* New virtual table object */ /* Allocate the new vtab object and parse the configuration */ pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table)); if( rc==SQLITE_OK ){ rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr); assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 ); } if( rc==SQLITE_OK ){ pTab->pConfig = pConfig; pTab->pGlobal = pGlobal; } /* Open the index sub-system */ if( rc==SQLITE_OK ){ rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr); } /* Open the storage sub-system */ if( rc==SQLITE_OK ){ rc = sqlite3Fts5StorageOpen( pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr ); } /* Call sqlite3_declare_vtab() */ if( rc==SQLITE_OK ){ rc = sqlite3Fts5ConfigDeclareVtab(pConfig); } /* Load the initial configuration */ if( rc==SQLITE_OK ){ assert( pConfig->pzErrmsg==0 ); pConfig->pzErrmsg = pzErr; rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex); sqlite3Fts5IndexRollback(pTab->pIndex); pConfig->pzErrmsg = 0; } if( rc!=SQLITE_OK ){ fts5FreeVtab(pTab); pTab = 0; }else if( bCreate ){ fts5CheckTransactionState(pTab, FTS5_BEGIN, 0); } *ppVTab = (sqlite3_vtab*)pTab; return rc; } /* ** The xConnect() and xCreate() methods for the virtual table. All the ** work is done in function fts5InitVtab(). */ static int fts5ConnectMethod( sqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); } static int fts5CreateMethod( sqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); } /* ** The different query plans. */ #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */ #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */ #define FTS5_PLAN_SPECIAL 3 /* An internal query */ #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */ #define FTS5_PLAN_SCAN 5 /* No usable constraint */ #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */ /* ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this ** extension is currently being used by a version of SQLite too old to ** support index-info flags. In that case this function is a no-op. */ static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){ #if SQLITE_VERSION_NUMBER>=3008012 #ifndef SQLITE_CORE if( sqlite3_libversion_number()>=3008012 ) #endif { pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE; } #endif } /* ** Implementation of the xBestIndex method for FTS5 tables. Within the ** WHERE constraint, it searches for the following: ** ** 1. A MATCH constraint against the special column. ** 2. A MATCH constraint against the "rank" column. ** 3. An == constraint against the rowid column. ** 4. A < or <= constraint against the rowid column. ** 5. A > or >= constraint against the rowid column. ** ** Within the ORDER BY, either: ** ** 5. ORDER BY rank [ASC|DESC] ** 6. ORDER BY rowid [ASC|DESC] ** ** Costs are assigned as follows: ** ** a) If an unusable MATCH operator is present in the WHERE clause, the ** cost is unconditionally set to 1e50 (a really big number). ** ** a) If a MATCH operator is present, the cost depends on the other ** constraints also present. As follows: ** ** * No other constraints: cost=1000.0 ** * One rowid range constraint: cost=750.0 ** * Both rowid range constraints: cost=500.0 ** * An == rowid constraint: cost=100.0 ** ** b) Otherwise, if there is no MATCH: ** ** * No other constraints: cost=1000000.0 ** * One rowid range constraint: cost=750000.0 ** * Both rowid range constraints: cost=250000.0 ** * An == rowid constraint: cost=10.0 ** ** Costs are not modified by the ORDER BY clause. */ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ Fts5Table *pTab = (Fts5Table*)pVTab; Fts5Config *pConfig = pTab->pConfig; int idxFlags = 0; /* Parameter passed through to xFilter() */ int bHasMatch; int iNext; int i; struct Constraint { int op; /* Mask against sqlite3_index_constraint.op */ int fts5op; /* FTS5 mask for idxFlags */ int iCol; /* 0==rowid, 1==tbl, 2==rank */ int omit; /* True to omit this if found */ int iConsIndex; /* Index in pInfo->aConstraint[] */ } aConstraint[] = { {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_MATCH, 1, 1, -1}, {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_RANK, 2, 1, -1}, {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1}, {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE, FTS5_BI_ROWID_LE, 0, 0, -1}, {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE, FTS5_BI_ROWID_GE, 0, 0, -1}, }; int aColMap[3]; aColMap[0] = -1; aColMap[1] = pConfig->nCol; aColMap[2] = pConfig->nCol+1; /* Set idxFlags flags for all WHERE clause terms that will be used. */ for(i=0; i<pInfo->nConstraint; i++){ struct sqlite3_index_constraint *p = &pInfo->aConstraint[i]; int j; for(j=0; j<ArraySize(aConstraint); j++){ struct Constraint *pC = &aConstraint[j]; if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){ if( p->usable ){ pC->iConsIndex = i; idxFlags |= pC->fts5op; }else if( j==0 ){ /* As there exists an unusable MATCH constraint this is an ** unusable plan. Set a prohibitively high cost. */ pInfo->estimatedCost = 1e50; return SQLITE_OK; } } } } /* Set idxFlags flags for the ORDER BY clause */ if( pInfo->nOrderBy==1 ){ int iSort = pInfo->aOrderBy[0].iColumn; if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){ idxFlags |= FTS5_BI_ORDER_RANK; }else if( iSort==-1 ){ idxFlags |= FTS5_BI_ORDER_ROWID; } if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){ pInfo->orderByConsumed = 1; if( pInfo->aOrderBy[0].desc ){ idxFlags |= FTS5_BI_ORDER_DESC; } } } /* Calculate the estimated cost based on the flags set in idxFlags. */ bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH); if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){ pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0; if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo); }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){ pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0; }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){ pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0; }else{ pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0; } /* Assign argvIndex values to each constraint in use. */ iNext = 1; for(i=0; i<ArraySize(aConstraint); i++){ struct Constraint *pC = &aConstraint[i]; if( pC->iConsIndex>=0 ){ pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++; pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit; } } pInfo->idxNum = idxFlags; return SQLITE_OK; } static int fts5NewTransaction(Fts5Table *pTab){ Fts5Cursor *pCsr; for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){ if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK; } return sqlite3Fts5StorageReset(pTab->pStorage); } /* ** Implementation of xOpen method. */ static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ Fts5Table *pTab = (Fts5Table*)pVTab; Fts5Config *pConfig = pTab->pConfig; Fts5Cursor *pCsr = 0; /* New cursor object */ int nByte; /* Bytes of space to allocate */ int rc; /* Return code */ rc = fts5NewTransaction(pTab); if( rc==SQLITE_OK ){ nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int); pCsr = (Fts5Cursor*)sqlite3_malloc(nByte); if( pCsr ){ Fts5Global *pGlobal = pTab->pGlobal; memset(pCsr, 0, nByte); pCsr->aColumnSize = (int*)&pCsr[1]; pCsr->pNext = pGlobal->pCsr; pGlobal->pCsr = pCsr; pCsr->iCsrId = ++pGlobal->iNextId; }else{ rc = SQLITE_NOMEM; } } *ppCsr = (sqlite3_vtab_cursor*)pCsr; return rc; } static int fts5StmtType(Fts5Cursor *pCsr){ if( pCsr->ePlan==FTS5_PLAN_SCAN ){ return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC; } return FTS5_STMT_LOOKUP; } /* ** This function is called after the cursor passed as the only argument ** is moved to point at a different row. It clears all cached data ** specific to the previous row stored by the cursor object. */ static void fts5CsrNewrow(Fts5Cursor *pCsr){ CsrFlagSet(pCsr, FTS5CSR_REQUIRE_CONTENT | FTS5CSR_REQUIRE_DOCSIZE | FTS5CSR_REQUIRE_INST | FTS5CSR_REQUIRE_POSLIST ); } static void fts5FreeCursorComponents(Fts5Cursor *pCsr){ Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); Fts5Auxdata *pData; Fts5Auxdata *pNext; sqlite3_free(pCsr->aInstIter); sqlite3_free(pCsr->aInst); if( pCsr->pStmt ){ int eStmt = fts5StmtType(pCsr); sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt); } if( pCsr->pSorter ){ Fts5Sorter *pSorter = pCsr->pSorter; sqlite3_finalize(pSorter->pStmt); sqlite3_free(pSorter); } if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){ sqlite3Fts5ExprFree(pCsr->pExpr); } for(pData=pCsr->pAuxdata; pData; pData=pNext){ pNext = pData->pNext; if( pData->xDelete ) pData->xDelete(pData->pPtr); sqlite3_free(pData); } sqlite3_finalize(pCsr->pRankArgStmt); sqlite3_free(pCsr->apRankArg); if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){ sqlite3_free(pCsr->zRank); sqlite3_free(pCsr->zRankArgs); } memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr)); } /* ** Close the cursor. For additional information see the documentation ** on the xClose method of the virtual table interface. */ static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){ if( pCursor ){ Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab); Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; Fts5Cursor **pp; fts5FreeCursorComponents(pCsr); /* Remove the cursor from the Fts5Global.pCsr list */ for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext); *pp = pCsr->pNext; sqlite3_free(pCsr); } return SQLITE_OK; } static int fts5SorterNext(Fts5Cursor *pCsr){ Fts5Sorter *pSorter = pCsr->pSorter; int rc; rc = sqlite3_step(pSorter->pStmt); if( rc==SQLITE_DONE ){ rc = SQLITE_OK; CsrFlagSet(pCsr, FTS5CSR_EOF); }else if( rc==SQLITE_ROW ){ const u8 *a; const u8 *aBlob; int nBlob; int i; int iOff = 0; rc = SQLITE_OK; pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0); nBlob = sqlite3_column_bytes(pSorter->pStmt, 1); aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1); /* nBlob==0 in detail=none mode. */ if( nBlob>0 ){ for(i=0; i<(pSorter->nIdx-1); i++){ int iVal; a += fts5GetVarint32(a, iVal); iOff += iVal; pSorter->aIdx[i] = iOff; } pSorter->aIdx[i] = &aBlob[nBlob] - a; pSorter->aPoslist = a; } fts5CsrNewrow(pCsr); } return rc; } /* ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors ** open on table pTab. */ static void fts5TripCursors(Fts5Table *pTab){ Fts5Cursor *pCsr; for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){ if( pCsr->ePlan==FTS5_PLAN_MATCH && pCsr->base.pVtab==(sqlite3_vtab*)pTab ){ CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK); } } } /* ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first ** argument, close and reopen all Fts5IndexIter iterators that the cursor ** is using. Then attempt to move the cursor to a rowid equal to or laster ** (in the cursors sort order - ASC or DESC) than the current rowid. ** ** If the new rowid is not equal to the old, set output parameter *pbSkip ** to 1 before returning. Otherwise, leave it unchanged. ** ** Return SQLITE_OK if successful or if no reseek was required, or an ** error code if an error occurred. */ static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){ int rc = SQLITE_OK; assert( *pbSkip==0 ); if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){ Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); int bDesc = pCsr->bDesc; i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr); rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc); if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){ *pbSkip = 1; } CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK); fts5CsrNewrow(pCsr); if( sqlite3Fts5ExprEof(pCsr->pExpr) ){ CsrFlagSet(pCsr, FTS5CSR_EOF); *pbSkip = 1; } } return rc; } /* ** Advance the cursor to the next row in the table that matches the ** search criteria. ** ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned ** even if we reach end-of-file. The fts5EofMethod() will be called ** subsequently to determine whether or not an EOF was hit. */ static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; int rc; assert( (pCsr->ePlan<3)== (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE) ); assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) ); if( pCsr->ePlan<3 ){ int bSkip = 0; if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc; rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid); CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr)); fts5CsrNewrow(pCsr); }else{ switch( pCsr->ePlan ){ case FTS5_PLAN_SPECIAL: { CsrFlagSet(pCsr, FTS5CSR_EOF); rc = SQLITE_OK; break; } case FTS5_PLAN_SORTED_MATCH: { rc = fts5SorterNext(pCsr); break; } default: rc = sqlite3_step(pCsr->pStmt); if( rc!=SQLITE_ROW ){ CsrFlagSet(pCsr, FTS5CSR_EOF); rc = sqlite3_reset(pCsr->pStmt); }else{ rc = SQLITE_OK; } break; } } return rc; } static int fts5PrepareStatement( sqlite3_stmt **ppStmt, Fts5Config *pConfig, const char *zFmt, ... ){ sqlite3_stmt *pRet = 0; int rc; char *zSql; va_list ap; va_start(ap, zFmt); zSql = sqlite3_vmprintf(zFmt, ap); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0); if( rc!=SQLITE_OK ){ *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db)); } sqlite3_free(zSql); } va_end(ap); *ppStmt = pRet; return rc; } static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){ Fts5Config *pConfig = pTab->pConfig; Fts5Sorter *pSorter; int nPhrase; int nByte; int rc; const char *zRank = pCsr->zRank; const char *zRankArgs = pCsr->zRankArgs; nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr); nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1); pSorter = (Fts5Sorter*)sqlite3_malloc(nByte); if( pSorter==0 ) return SQLITE_NOMEM; memset(pSorter, 0, nByte); pSorter->nIdx = nPhrase; /* TODO: It would be better to have some system for reusing statement ** handles here, rather than preparing a new one for each query. But that ** is not possible as SQLite reference counts the virtual table objects. ** And since the statement required here reads from this very virtual ** table, saving it creates a circular reference. ** ** If SQLite a built-in statement cache, this wouldn't be a problem. */ rc = fts5PrepareStatement(&pSorter->pStmt, pConfig, "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s", pConfig->zDb, pConfig->zName, zRank, pConfig->zName, (zRankArgs ? ", " : ""), (zRankArgs ? zRankArgs : ""), bDesc ? "DESC" : "ASC" ); pCsr->pSorter = pSorter; if( rc==SQLITE_OK ){ assert( pTab->pSortCsr==0 ); pTab->pSortCsr = pCsr; rc = fts5SorterNext(pCsr); pTab->pSortCsr = 0; } if( rc!=SQLITE_OK ){ sqlite3_finalize(pSorter->pStmt); sqlite3_free(pSorter); pCsr->pSorter = 0; } return rc; } static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){ int rc; Fts5Expr *pExpr = pCsr->pExpr; rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc); if( sqlite3Fts5ExprEof(pExpr) ){ CsrFlagSet(pCsr, FTS5CSR_EOF); } fts5CsrNewrow(pCsr); return rc; } /* ** Process a "special" query. A special query is identified as one with a ** MATCH expression that begins with a '*' character. The remainder of ** the text passed to the MATCH operator are used as the special query ** parameters. */ static int fts5SpecialMatch( Fts5Table *pTab, Fts5Cursor *pCsr, const char *zQuery ){ int rc = SQLITE_OK; /* Return code */ const char *z = zQuery; /* Special query text */ int n; /* Number of bytes in text at z */ while( z[0]==' ' ) z++; for(n=0; z[n] && z[n]!=' '; n++); assert( pTab->base.zErrMsg==0 ); pCsr->ePlan = FTS5_PLAN_SPECIAL; if( 0==sqlite3_strnicmp("reads", z, n) ){ pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex); } else if( 0==sqlite3_strnicmp("id", z, n) ){ pCsr->iSpecial = pCsr->iCsrId; } else{ /* An unrecognized directive. Return an error message. */ pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z); rc = SQLITE_ERROR; } return rc; } /* ** Search for an auxiliary function named zName that can be used with table ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary ** structure. Otherwise, if no such function exists, return NULL. */ static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){ Fts5Auxiliary *pAux; for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){ if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux; } /* No function of the specified name was found. Return 0. */ return 0; } static int fts5FindRankFunction(Fts5Cursor *pCsr){ Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); Fts5Config *pConfig = pTab->pConfig; int rc = SQLITE_OK; Fts5Auxiliary *pAux = 0; const char *zRank = pCsr->zRank; const char *zRankArgs = pCsr->zRankArgs; if( zRankArgs ){ char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs); if( zSql ){ sqlite3_stmt *pStmt = 0; rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 ); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pStmt) ){ int nByte; pCsr->nRankArg = sqlite3_column_count(pStmt); nByte = sizeof(sqlite3_value*)*pCsr->nRankArg; pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte); if( rc==SQLITE_OK ){ int i; for(i=0; i<pCsr->nRankArg; i++){ pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i); } } pCsr->pRankArgStmt = pStmt; }else{ rc = sqlite3_finalize(pStmt); assert( rc!=SQLITE_OK ); } } } } if( rc==SQLITE_OK ){ pAux = fts5FindAuxiliary(pTab, zRank); if( pAux==0 ){ assert( pTab->base.zErrMsg==0 ); pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank); rc = SQLITE_ERROR; } } pCsr->pRank = pAux; return rc; } static int fts5CursorParseRank( Fts5Config *pConfig, Fts5Cursor *pCsr, sqlite3_value *pRank ){ int rc = SQLITE_OK; if( pRank ){ const char *z = (const char*)sqlite3_value_text(pRank); char *zRank = 0; char *zRankArgs = 0; if( z==0 ){ if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR; }else{ rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs); } if( rc==SQLITE_OK ){ pCsr->zRank = zRank; pCsr->zRankArgs = zRankArgs; CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK); }else if( rc==SQLITE_ERROR ){ pCsr->base.pVtab->zErrMsg = sqlite3_mprintf( "parse error in rank function: %s", z ); } }else{ if( pConfig->zRank ){ pCsr->zRank = (char*)pConfig->zRank; pCsr->zRankArgs = (char*)pConfig->zRankArgs; }else{ pCsr->zRank = (char*)FTS5_DEFAULT_RANK; pCsr->zRankArgs = 0; } } return rc; } static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){ if( pVal ){ int eType = sqlite3_value_numeric_type(pVal); if( eType==SQLITE_INTEGER ){ return sqlite3_value_int64(pVal); } } return iDefault; } /* ** This is the xFilter interface for the virtual table. See ** the virtual table xFilter method documentation for additional ** information. ** ** There are three possible query strategies: ** ** 1. Full-text search using a MATCH operator. ** 2. A by-rowid lookup. ** 3. A full-table scan. */ static int fts5FilterMethod( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *zUnused, /* Unused */ int nVal, /* Number of elements in apVal */ sqlite3_value **apVal /* Arguments for the indexing scheme */ ){ Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab); Fts5Config *pConfig = pTab->pConfig; Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; int rc = SQLITE_OK; /* Error code */ int iVal = 0; /* Counter for apVal[] */ int bDesc; /* True if ORDER BY [rank|rowid] DESC */ int bOrderByRank; /* True if ORDER BY rank */ sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */ sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */ sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */ sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */ sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */ char **pzErrmsg = pConfig->pzErrmsg; UNUSED_PARAM(zUnused); UNUSED_PARAM(nVal); if( pCsr->ePlan ){ fts5FreeCursorComponents(pCsr); memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr)); } assert( pCsr->pStmt==0 ); assert( pCsr->pExpr==0 ); assert( pCsr->csrflags==0 ); assert( pCsr->pRank==0 ); assert( pCsr->zRank==0 ); assert( pCsr->zRankArgs==0 ); assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg ); pConfig->pzErrmsg = &pTab->base.zErrMsg; /* Decode the arguments passed through to this function. ** ** Note: The following set of if(...) statements must be in the same ** order as the corresponding entries in the struct at the top of ** fts5BestIndexMethod(). */ if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++]; if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++]; if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++]; if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++]; if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++]; assert( iVal==nVal ); bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0); pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0); /* Set the cursor upper and lower rowid limits. Only some strategies ** actually use them. This is ok, as the xBestIndex() method leaves the ** sqlite3_index_constraint.omit flag clear for range constraints ** on the rowid field. */ if( pRowidEq ){ pRowidLe = pRowidGe = pRowidEq; } if( bDesc ){ pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64); pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64); }else{ pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64); pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64); } if( pTab->pSortCsr ){ /* If pSortCsr is non-NULL, then this call is being made as part of ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will ** return results to the user for this query. The current cursor ** (pCursor) is used to execute the query issued by function ** fts5CursorFirstSorted() above. */ assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 ); assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 ); assert( pCsr->iLastRowid==LARGEST_INT64 ); assert( pCsr->iFirstRowid==SMALLEST_INT64 ); pCsr->ePlan = FTS5_PLAN_SOURCE; pCsr->pExpr = pTab->pSortCsr->pExpr; rc = fts5CursorFirst(pTab, pCsr, bDesc); }else if( pMatch ){ const char *zExpr = (const char*)sqlite3_value_text(apVal[0]); if( zExpr==0 ) zExpr = ""; rc = fts5CursorParseRank(pConfig, pCsr, pRank); if( rc==SQLITE_OK ){ if( zExpr[0]=='*' ){ /* The user has issued a query of the form "MATCH '*...'". This ** indicates that the MATCH expression is not a full text query, ** but a request for an internal parameter. */ rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]); }else{ char **pzErr = &pTab->base.zErrMsg; rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr); if( rc==SQLITE_OK ){ if( bOrderByRank ){ pCsr->ePlan = FTS5_PLAN_SORTED_MATCH; rc = fts5CursorFirstSorted(pTab, pCsr, bDesc); }else{ pCsr->ePlan = FTS5_PLAN_MATCH; rc = fts5CursorFirst(pTab, pCsr, bDesc); } } } } }else if( pConfig->zContent==0 ){ *pConfig->pzErrmsg = sqlite3_mprintf( "%s: table does not support scanning", pConfig->zName ); rc = SQLITE_ERROR; }else{ /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup ** by rowid (ePlan==FTS5_PLAN_ROWID). */ pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN); rc = sqlite3Fts5StorageStmt( pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg ); if( rc==SQLITE_OK ){ if( pCsr->ePlan==FTS5_PLAN_ROWID ){ sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]); }else{ sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid); sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid); } rc = fts5NextMethod(pCursor); } } pConfig->pzErrmsg = pzErrmsg; return rc; } /* ** This is the xEof method of the virtual table. SQLite calls this ** routine to find out if it has reached the end of a result set. */ static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0); } /* ** Return the rowid that the cursor currently points to. */ static i64 fts5CursorRowid(Fts5Cursor *pCsr){ assert( pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE ); if( pCsr->pSorter ){ return pCsr->pSorter->iRowid; }else{ return sqlite3Fts5ExprRowid(pCsr->pExpr); } } /* ** This is the xRowid method. The SQLite core calls this routine to ** retrieve the rowid for the current row of the result set. fts5 ** exposes %_content.rowid as the rowid for the virtual table. The ** rowid should be written to *pRowid. */ static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; int ePlan = pCsr->ePlan; assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 ); switch( ePlan ){ case FTS5_PLAN_SPECIAL: *pRowid = 0; break; case FTS5_PLAN_SOURCE: case FTS5_PLAN_MATCH: case FTS5_PLAN_SORTED_MATCH: *pRowid = fts5CursorRowid(pCsr); break; default: *pRowid = sqlite3_column_int64(pCsr->pStmt, 0); break; } return SQLITE_OK; } /* ** If the cursor requires seeking (bSeekRequired flag is set), seek it. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise. ** ** If argument bErrormsg is true and an error occurs, an error message may ** be left in sqlite3_vtab.zErrMsg. */ static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){ int rc = SQLITE_OK; /* If the cursor does not yet have a statement handle, obtain one now. */ if( pCsr->pStmt==0 ){ Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); int eStmt = fts5StmtType(pCsr); rc = sqlite3Fts5StorageStmt( pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0) ); assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 ); assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ); } if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){ assert( pCsr->pExpr ); sqlite3_reset(pCsr->pStmt); sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr)); rc = sqlite3_step(pCsr->pStmt); if( rc==SQLITE_ROW ){ rc = SQLITE_OK; CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT); }else{ rc = sqlite3_reset(pCsr->pStmt); if( rc==SQLITE_OK ){ rc = FTS5_CORRUPT; } } } return rc; } static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){ va_list ap; /* ... printf arguments */ va_start(ap, zFormat); assert( p->base.zErrMsg==0 ); p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap); va_end(ap); } /* ** This function is called to handle an FTS INSERT command. In other words, ** an INSERT statement of the form: ** ** INSERT INTO fts(fts) VALUES($pCmd) ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal) ** ** Argument pVal is the value assigned to column "fts" by the INSERT ** statement. This function returns SQLITE_OK if successful, or an SQLite ** error code if an error occurs. ** ** The commands implemented by this function are documented in the "Special ** INSERT Directives" section of the documentation. It should be updated if ** more commands are added to this function. */ static int fts5SpecialInsert( Fts5Table *pTab, /* Fts5 table object */ const char *zCmd, /* Text inserted into table-name column */ sqlite3_value *pVal /* Value inserted into rank column */ ){ Fts5Config *pConfig = pTab->pConfig; int rc = SQLITE_OK; int bError = 0; if( 0==sqlite3_stricmp("delete-all", zCmd) ){ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){ fts5SetVtabError(pTab, "'delete-all' may only be used with a " "contentless or external content fts5 table" ); rc = SQLITE_ERROR; }else{ rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage); } }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){ if( pConfig->eContent==FTS5_CONTENT_NONE ){ fts5SetVtabError(pTab, "'rebuild' may not be used with a contentless fts5 table" ); rc = SQLITE_ERROR; }else{ rc = sqlite3Fts5StorageRebuild(pTab->pStorage); } }else if( 0==sqlite3_stricmp("optimize", zCmd) ){ rc = sqlite3Fts5StorageOptimize(pTab->pStorage); }else if( 0==sqlite3_stricmp("merge", zCmd) ){ int nMerge = sqlite3_value_int(pVal); rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge); }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){ rc = sqlite3Fts5StorageIntegrity(pTab->pStorage); #ifdef SQLITE_DEBUG }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){ pConfig->bPrefixIndex = sqlite3_value_int(pVal); #endif }else{ rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex); if( rc==SQLITE_OK ){ rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError); } if( rc==SQLITE_OK ){ if( bError ){ rc = SQLITE_ERROR; }else{ rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0); } } } return rc; } static int fts5SpecialDelete( Fts5Table *pTab, sqlite3_value **apVal ){ int rc = SQLITE_OK; int eType1 = sqlite3_value_type(apVal[1]); if( eType1==SQLITE_INTEGER ){ sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]); rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]); } return rc; } static void fts5StorageInsert( int *pRc, Fts5Table *pTab, sqlite3_value **apVal, i64 *piRowid ){ int rc = *pRc; if( rc==SQLITE_OK ){ rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid); } *pRc = rc; } /* ** This function is the implementation of the xUpdate callback used by ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be ** inserted, updated or deleted. ** ** A delete specifies a single argument - the rowid of the row to remove. ** ** Update and insert operations pass: ** ** 1. The "old" rowid, or NULL. ** 2. The "new" rowid. ** 3. Values for each of the nCol matchable columns. ** 4. Values for the two hidden columns (<tablename> and "rank"). */ static int fts5UpdateMethod( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Size of argument array */ sqlite3_value **apVal, /* Array of arguments */ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ ){ Fts5Table *pTab = (Fts5Table*)pVtab; Fts5Config *pConfig = pTab->pConfig; int eType0; /* value_type() of apVal[0] */ int rc = SQLITE_OK; /* Return code */ /* A transaction must be open when this is called. */ assert( pTab->ts.eState==1 ); assert( pVtab->zErrMsg==0 ); assert( nArg==1 || nArg==(2+pConfig->nCol+2) ); assert( nArg==1 || sqlite3_value_type(apVal[1])==SQLITE_INTEGER || sqlite3_value_type(apVal[1])==SQLITE_NULL ); assert( pTab->pConfig->pzErrmsg==0 ); pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg; /* Put any active cursors into REQUIRE_SEEK state. */ fts5TripCursors(pTab); eType0 = sqlite3_value_type(apVal[0]); if( eType0==SQLITE_NULL && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL ){ /* A "special" INSERT op. These are handled separately. */ const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]); if( pConfig->eContent!=FTS5_CONTENT_NORMAL && 0==sqlite3_stricmp("delete", z) ){ rc = fts5SpecialDelete(pTab, apVal); }else{ rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]); } }else{ /* A regular INSERT, UPDATE or DELETE statement. The trick here is that ** any conflict on the rowid value must be detected before any ** modifications are made to the database file. There are 4 cases: ** ** 1) DELETE ** 2) UPDATE (rowid not modified) ** 3) UPDATE (rowid modified) ** 4) INSERT ** ** Cases 3 and 4 may violate the rowid constraint. */ int eConflict = SQLITE_ABORT; if( pConfig->eContent==FTS5_CONTENT_NORMAL ){ eConflict = sqlite3_vtab_on_conflict(pConfig->db); } assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL ); assert( nArg!=1 || eType0==SQLITE_INTEGER ); /* Filter out attempts to run UPDATE or DELETE on contentless tables. ** This is not suported. */ if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){ pTab->base.zErrMsg = sqlite3_mprintf( "cannot %s contentless fts5 table: %s", (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName ); rc = SQLITE_ERROR; } /* DELETE */ else if( nArg==1 ){ i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0); } /* INSERT */ else if( eType0!=SQLITE_INTEGER ){ /* If this is a REPLACE, first remove the current entry (if any) */ if( eConflict==SQLITE_REPLACE && sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){ i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0); } fts5StorageInsert(&rc, pTab, apVal, pRowid); } /* UPDATE */ else{ i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */ i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */ if( iOld!=iNew ){ if( eConflict==SQLITE_REPLACE ){ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); if( rc==SQLITE_OK ){ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0); } fts5StorageInsert(&rc, pTab, apVal, pRowid); }else{ rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid); if( rc==SQLITE_OK ){ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid); } } }else{ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); fts5StorageInsert(&rc, pTab, apVal, pRowid); } } } pTab->pConfig->pzErrmsg = 0; return rc; } /* ** Implementation of xSync() method. */ static int fts5SyncMethod(sqlite3_vtab *pVtab){ int rc; Fts5Table *pTab = (Fts5Table*)pVtab; fts5CheckTransactionState(pTab, FTS5_SYNC, 0); pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg; fts5TripCursors(pTab); rc = sqlite3Fts5StorageSync(pTab->pStorage, 1); pTab->pConfig->pzErrmsg = 0; return rc; } /* ** Implementation of xBegin() method. */ static int fts5BeginMethod(sqlite3_vtab *pVtab){ fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0); fts5NewTransaction((Fts5Table*)pVtab); return SQLITE_OK; } /* ** Implementation of xCommit() method. This is a no-op. The contents of ** the pending-terms hash-table have already been flushed into the database ** by fts5SyncMethod(). */ static int fts5CommitMethod(sqlite3_vtab *pVtab){ UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */ fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0); return SQLITE_OK; } /* ** Implementation of xRollback(). Discard the contents of the pending-terms ** hash-table. Any changes made to the database are reverted by SQLite. */ static int fts5RollbackMethod(sqlite3_vtab *pVtab){ int rc; Fts5Table *pTab = (Fts5Table*)pVtab; fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0); rc = sqlite3Fts5StorageRollback(pTab->pStorage); return rc; } static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*); static void *fts5ApiUserData(Fts5Context *pCtx){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; return pCsr->pAux->pUserData; } static int fts5ApiColumnCount(Fts5Context *pCtx){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol; } static int fts5ApiColumnTotalSize( Fts5Context *pCtx, int iCol, sqlite3_int64 *pnToken ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken); } static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow); } static int fts5ApiTokenize( Fts5Context *pCtx, const char *pText, int nText, void *pUserData, int (*xToken)(void*, int, const char*, int, int, int) ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); return sqlite3Fts5Tokenize( pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken ); } static int fts5ApiPhraseCount(Fts5Context *pCtx){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; return sqlite3Fts5ExprPhraseCount(pCsr->pExpr); } static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase); } static int fts5ApiColumnText( Fts5Context *pCtx, int iCol, const char **pz, int *pn ){ int rc = SQLITE_OK; Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){ *pz = 0; *pn = 0; }else{ rc = fts5SeekCursor(pCsr, 0); if( rc==SQLITE_OK ){ *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1); *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1); } } return rc; } static int fts5CsrPoslist( Fts5Cursor *pCsr, int iPhrase, const u8 **pa, int *pn ){ Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig; int rc = SQLITE_OK; int bLive = (pCsr->pSorter==0); if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){ if( pConfig->eDetail!=FTS5_DETAIL_FULL ){ Fts5PoslistPopulator *aPopulator; int i; aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive); if( aPopulator==0 ) rc = SQLITE_NOMEM; for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){ int n; const char *z; rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n); if( rc==SQLITE_OK ){ rc = sqlite3Fts5ExprPopulatePoslists( pConfig, pCsr->pExpr, aPopulator, i, z, n ); } } sqlite3_free(aPopulator); if( pCsr->pSorter ){ sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid); } } CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST); } if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){ Fts5Sorter *pSorter = pCsr->pSorter; int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]); *pn = pSorter->aIdx[iPhrase] - i1; *pa = &pSorter->aPoslist[i1]; }else{ *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa); } return rc; } /* ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated ** correctly for the current view. Return SQLITE_OK if successful, or an ** SQLite error code otherwise. */ static int fts5CacheInstArray(Fts5Cursor *pCsr){ int rc = SQLITE_OK; Fts5PoslistReader *aIter; /* One iterator for each phrase */ int nIter; /* Number of iterators/phrases */ nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr); if( pCsr->aInstIter==0 ){ int nByte = sizeof(Fts5PoslistReader) * nIter; pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte); } aIter = pCsr->aInstIter; if( aIter ){ int nInst = 0; /* Number instances seen so far */ int i; /* Initialize all iterators */ for(i=0; i<nIter && rc==SQLITE_OK; i++){ const u8 *a; int n; rc = fts5CsrPoslist(pCsr, i, &a, &n); if( rc==SQLITE_OK ){ sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]); } } if( rc==SQLITE_OK ){ while( 1 ){ int *aInst; int iBest = -1; for(i=0; i<nIter; i++){ if( (aIter[i].bEof==0) && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos) ){ iBest = i; } } if( iBest<0 ) break; nInst++; if( nInst>=pCsr->nInstAlloc ){ pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32; aInst = (int*)sqlite3_realloc( pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3 ); if( aInst ){ pCsr->aInst = aInst; }else{ rc = SQLITE_NOMEM; break; } } aInst = &pCsr->aInst[3 * (nInst-1)]; aInst[0] = iBest; aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos); aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos); sqlite3Fts5PoslistReaderNext(&aIter[iBest]); } } pCsr->nInstCount = nInst; CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST); } return rc; } static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; int rc = SQLITE_OK; if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){ *pnInst = pCsr->nInstCount; } return rc; } static int fts5ApiInst( Fts5Context *pCtx, int iIdx, int *piPhrase, int *piCol, int *piOff ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; int rc = SQLITE_OK; if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){ if( iIdx<0 || iIdx>=pCsr->nInstCount ){ rc = SQLITE_RANGE; #if 0 }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){ *piPhrase = pCsr->aInst[iIdx*3]; *piCol = pCsr->aInst[iIdx*3 + 2]; *piOff = -1; #endif }else{ *piPhrase = pCsr->aInst[iIdx*3]; *piCol = pCsr->aInst[iIdx*3 + 1]; *piOff = pCsr->aInst[iIdx*3 + 2]; } } return rc; } static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){ return fts5CursorRowid((Fts5Cursor*)pCtx); } static int fts5ColumnSizeCb( void *pContext, /* Pointer to int */ int tflags, const char *pUnused, /* Buffer containing token */ int nUnused, /* Size of token in bytes */ int iUnused1, /* Start offset of token */ int iUnused2 /* End offset of token */ ){ int *pCnt = (int*)pContext; UNUSED_PARAM2(pUnused, nUnused); UNUSED_PARAM2(iUnused1, iUnused2); if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){ (*pCnt)++; } return SQLITE_OK; } static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); Fts5Config *pConfig = pTab->pConfig; int rc = SQLITE_OK; if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){ if( pConfig->bColumnsize ){ i64 iRowid = fts5CursorRowid(pCsr); rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize); }else if( pConfig->zContent==0 ){ int i; for(i=0; i<pConfig->nCol; i++){ if( pConfig->abUnindexed[i]==0 ){ pCsr->aColumnSize[i] = -1; } } }else{ int i; for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){ if( pConfig->abUnindexed[i]==0 ){ const char *z; int n; void *p = (void*)(&pCsr->aColumnSize[i]); pCsr->aColumnSize[i] = 0; rc = fts5ApiColumnText(pCtx, i, &z, &n); if( rc==SQLITE_OK ){ rc = sqlite3Fts5Tokenize( pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb ); } } } } CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE); } if( iCol<0 ){ int i; *pnToken = 0; for(i=0; i<pConfig->nCol; i++){ *pnToken += pCsr->aColumnSize[i]; } }else if( iCol<pConfig->nCol ){ *pnToken = pCsr->aColumnSize[iCol]; }else{ *pnToken = 0; rc = SQLITE_RANGE; } return rc; } /* ** Implementation of the xSetAuxdata() method. */ static int fts5ApiSetAuxdata( Fts5Context *pCtx, /* Fts5 context */ void *pPtr, /* Pointer to save as auxdata */ void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */ ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Auxdata *pData; /* Search through the cursors list of Fts5Auxdata objects for one that ** corresponds to the currently executing auxiliary function. */ for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){ if( pData->pAux==pCsr->pAux ) break; } if( pData ){ if( pData->xDelete ){ pData->xDelete(pData->pPtr); } }else{ int rc = SQLITE_OK; pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata)); if( pData==0 ){ if( xDelete ) xDelete(pPtr); return rc; } pData->pAux = pCsr->pAux; pData->pNext = pCsr->pAuxdata; pCsr->pAuxdata = pData; } pData->xDelete = xDelete; pData->pPtr = pPtr; return SQLITE_OK; } static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Auxdata *pData; void *pRet = 0; for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){ if( pData->pAux==pCsr->pAux ) break; } if( pData ){ pRet = pData->pPtr; if( bClear ){ pData->pPtr = 0; pData->xDelete = 0; } } return pRet; } static void fts5ApiPhraseNext( Fts5Context *pUnused, Fts5PhraseIter *pIter, int *piCol, int *piOff ){ UNUSED_PARAM(pUnused); if( pIter->a>=pIter->b ){ *piCol = -1; *piOff = -1; }else{ int iVal; pIter->a += fts5GetVarint32(pIter->a, iVal); if( iVal==1 ){ pIter->a += fts5GetVarint32(pIter->a, iVal); *piCol = iVal; *piOff = 0; pIter->a += fts5GetVarint32(pIter->a, iVal); } *piOff += (iVal-2); } } static int fts5ApiPhraseFirst( Fts5Context *pCtx, int iPhrase, Fts5PhraseIter *pIter, int *piCol, int *piOff ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; int n; int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n); if( rc==SQLITE_OK ){ pIter->b = &pIter->a[n]; *piCol = 0; *piOff = 0; fts5ApiPhraseNext(pCtx, pIter, piCol, piOff); } return rc; } static void fts5ApiPhraseNextColumn( Fts5Context *pCtx, Fts5PhraseIter *pIter, int *piCol ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig; if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ if( pIter->a>=pIter->b ){ *piCol = -1; }else{ int iIncr; pIter->a += fts5GetVarint32(&pIter->a[0], iIncr); *piCol += (iIncr-2); } }else{ while( 1 ){ int dummy; if( pIter->a>=pIter->b ){ *piCol = -1; return; } if( pIter->a[0]==0x01 ) break; pIter->a += fts5GetVarint32(pIter->a, dummy); } pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol); } } static int fts5ApiPhraseFirstColumn( Fts5Context *pCtx, int iPhrase, Fts5PhraseIter *pIter, int *piCol ){ int rc = SQLITE_OK; Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig; if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ Fts5Sorter *pSorter = pCsr->pSorter; int n; if( pSorter ){ int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]); n = pSorter->aIdx[iPhrase] - i1; pIter->a = &pSorter->aPoslist[i1]; }else{ rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n); } if( rc==SQLITE_OK ){ pIter->b = &pIter->a[n]; *piCol = 0; fts5ApiPhraseNextColumn(pCtx, pIter, piCol); } }else{ int n; rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n); if( rc==SQLITE_OK ){ pIter->b = &pIter->a[n]; if( n<=0 ){ *piCol = -1; }else if( pIter->a[0]==0x01 ){ pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol); }else{ *piCol = 0; } } } return rc; } static int fts5ApiQueryPhrase(Fts5Context*, int, void*, int(*)(const Fts5ExtensionApi*, Fts5Context*, void*) ); static const Fts5ExtensionApi sFts5Api = { 2, /* iVersion */ fts5ApiUserData, fts5ApiColumnCount, fts5ApiRowCount, fts5ApiColumnTotalSize, fts5ApiTokenize, fts5ApiPhraseCount, fts5ApiPhraseSize, fts5ApiInstCount, fts5ApiInst, fts5ApiRowid, fts5ApiColumnText, fts5ApiColumnSize, fts5ApiQueryPhrase, fts5ApiSetAuxdata, fts5ApiGetAuxdata, fts5ApiPhraseFirst, fts5ApiPhraseNext, fts5ApiPhraseFirstColumn, fts5ApiPhraseNextColumn, }; /* ** Implementation of API function xQueryPhrase(). */ static int fts5ApiQueryPhrase( Fts5Context *pCtx, int iPhrase, void *pUserData, int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*) ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); int rc; Fts5Cursor *pNew = 0; rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew); if( rc==SQLITE_OK ){ pNew->ePlan = FTS5_PLAN_MATCH; pNew->iFirstRowid = SMALLEST_INT64; pNew->iLastRowid = LARGEST_INT64; pNew->base.pVtab = (sqlite3_vtab*)pTab; rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr); } if( rc==SQLITE_OK ){ for(rc = fts5CursorFirst(pTab, pNew, 0); rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0; rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew) ){ rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData); if( rc!=SQLITE_OK ){ if( rc==SQLITE_DONE ) rc = SQLITE_OK; break; } } } fts5CloseMethod((sqlite3_vtab_cursor*)pNew); return rc; } static void fts5ApiInvoke( Fts5Auxiliary *pAux, Fts5Cursor *pCsr, sqlite3_context *context, int argc, sqlite3_value **argv ){ assert( pCsr->pAux==0 ); pCsr->pAux = pAux; pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv); pCsr->pAux = 0; } static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){ Fts5Cursor *pCsr; for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){ if( pCsr->iCsrId==iCsrId ) break; } return pCsr; } static void fts5ApiCallback( sqlite3_context *context, int argc, sqlite3_value **argv ){ Fts5Auxiliary *pAux; Fts5Cursor *pCsr; i64 iCsrId; assert( argc>=1 ); pAux = (Fts5Auxiliary*)sqlite3_user_data(context); iCsrId = sqlite3_value_int64(argv[0]); pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId); if( pCsr==0 ){ char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId); sqlite3_result_error(context, zErr, -1); sqlite3_free(zErr); }else{ fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]); } } /* ** Given cursor id iId, return a pointer to the corresponding Fts5Index ** object. Or NULL If the cursor id does not exist. ** ** If successful, set *ppConfig to point to the associated config object ** before returning. */ static Fts5Index *sqlite3Fts5IndexFromCsrid( Fts5Global *pGlobal, /* FTS5 global context for db handle */ i64 iCsrId, /* Id of cursor to find */ Fts5Config **ppConfig /* OUT: Configuration object */ ){ Fts5Cursor *pCsr; Fts5Table *pTab; pCsr = fts5CursorFromCsrid(pGlobal, iCsrId); pTab = (Fts5Table*)pCsr->base.pVtab; *ppConfig = pTab->pConfig; return pTab->pIndex; } /* ** Return a "position-list blob" corresponding to the current position of ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains ** the current position-list for each phrase in the query associated with ** cursor pCsr. ** ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is ** the number of phrases in the query. Following the varints are the ** concatenated position lists for each phrase, in order. ** ** The first varint (if it exists) contains the size of the position list ** for phrase 0. The second (same disclaimer) contains the size of position ** list 1. And so on. There is no size field for the final position list, ** as it can be derived from the total size of the blob. */ static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){ int i; int rc = SQLITE_OK; int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr); Fts5Buffer val; memset(&val, 0, sizeof(Fts5Buffer)); switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){ case FTS5_DETAIL_FULL: /* Append the varints */ for(i=0; i<(nPhrase-1); i++){ const u8 *dummy; int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy); sqlite3Fts5BufferAppendVarint(&rc, &val, nByte); } /* Append the position lists */ for(i=0; i<nPhrase; i++){ const u8 *pPoslist; int nPoslist; nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist); sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist); } break; case FTS5_DETAIL_COLUMNS: /* Append the varints */ for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){ const u8 *dummy; int nByte; rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte); sqlite3Fts5BufferAppendVarint(&rc, &val, nByte); } /* Append the position lists */ for(i=0; rc==SQLITE_OK && i<nPhrase; i++){ const u8 *pPoslist; int nPoslist; rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist); sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist); } break; default: break; } sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free); return rc; } /* ** This is the xColumn method, called by SQLite to request a value from ** the row that the supplied cursor currently points to. */ static int fts5ColumnMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab); Fts5Config *pConfig = pTab->pConfig; Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; int rc = SQLITE_OK; assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 ); if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){ if( iCol==pConfig->nCol ){ sqlite3_result_int64(pCtx, pCsr->iSpecial); } }else if( iCol==pConfig->nCol ){ /* User is requesting the value of the special column with the same name ** as the table. Return the cursor integer id number. This value is only ** useful in that it may be passed as the first argument to an FTS5 ** auxiliary function. */ sqlite3_result_int64(pCtx, pCsr->iCsrId); }else if( iCol==pConfig->nCol+1 ){ /* The value of the "rank" column. */ if( pCsr->ePlan==FTS5_PLAN_SOURCE ){ fts5PoslistBlob(pCtx, pCsr); }else if( pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH ){ if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){ fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg); } } }else if( !fts5IsContentless(pTab) ){ rc = fts5SeekCursor(pCsr, 1); if( rc==SQLITE_OK ){ sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); } } return rc; } /* ** This routine implements the xFindFunction method for the FTS3 ** virtual table. */ static int fts5FindFunctionMethod( sqlite3_vtab *pVtab, /* Virtual table handle */ int nUnused, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ void **ppArg /* OUT: User data for *pxFunc */ ){ Fts5Table *pTab = (Fts5Table*)pVtab; Fts5Auxiliary *pAux; UNUSED_PARAM(nUnused); pAux = fts5FindAuxiliary(pTab, zName); if( pAux ){ *pxFunc = fts5ApiCallback; *ppArg = (void*)pAux; return 1; } /* No function of the specified name was found. Return 0. */ return 0; } /* ** Implementation of FTS5 xRename method. Rename an fts5 table. */ static int fts5RenameMethod( sqlite3_vtab *pVtab, /* Virtual table handle */ const char *zName /* New name of table */ ){ Fts5Table *pTab = (Fts5Table*)pVtab; return sqlite3Fts5StorageRename(pTab->pStorage, zName); } /* ** The xSavepoint() method. ** ** Flush the contents of the pending-terms table to disk. */ static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ Fts5Table *pTab = (Fts5Table*)pVtab; UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */ fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint); fts5TripCursors(pTab); return sqlite3Fts5StorageSync(pTab->pStorage, 0); } /* ** The xRelease() method. ** ** This is a no-op. */ static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ Fts5Table *pTab = (Fts5Table*)pVtab; UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */ fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint); fts5TripCursors(pTab); return sqlite3Fts5StorageSync(pTab->pStorage, 0); } /* ** The xRollbackTo() method. ** ** Discard the contents of the pending terms table. */ static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ Fts5Table *pTab = (Fts5Table*)pVtab; UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */ fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint); fts5TripCursors(pTab); return sqlite3Fts5StorageRollback(pTab->pStorage); } /* ** Register a new auxiliary function with global context pGlobal. */ static int fts5CreateAux( fts5_api *pApi, /* Global context (one per db handle) */ const char *zName, /* Name of new function */ void *pUserData, /* User data for aux. function */ fts5_extension_function xFunc, /* Aux. function implementation */ void(*xDestroy)(void*) /* Destructor for pUserData */ ){ Fts5Global *pGlobal = (Fts5Global*)pApi; int rc = sqlite3_overload_function(pGlobal->db, zName, -1); if( rc==SQLITE_OK ){ Fts5Auxiliary *pAux; int nName; /* Size of zName in bytes, including \0 */ int nByte; /* Bytes of space to allocate */ nName = (int)strlen(zName) + 1; nByte = sizeof(Fts5Auxiliary) + nName; pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte); if( pAux ){ memset(pAux, 0, nByte); pAux->zFunc = (char*)&pAux[1]; memcpy(pAux->zFunc, zName, nName); pAux->pGlobal = pGlobal; pAux->pUserData = pUserData; pAux->xFunc = xFunc; pAux->xDestroy = xDestroy; pAux->pNext = pGlobal->pAux; pGlobal->pAux = pAux; }else{ rc = SQLITE_NOMEM; } } return rc; } /* ** Register a new tokenizer. This is the implementation of the ** fts5_api.xCreateTokenizer() method. */ static int fts5CreateTokenizer( fts5_api *pApi, /* Global context (one per db handle) */ const char *zName, /* Name of new function */ void *pUserData, /* User data for aux. function */ fts5_tokenizer *pTokenizer, /* Tokenizer implementation */ void(*xDestroy)(void*) /* Destructor for pUserData */ ){ Fts5Global *pGlobal = (Fts5Global*)pApi; Fts5TokenizerModule *pNew; int nName; /* Size of zName and its \0 terminator */ int nByte; /* Bytes of space to allocate */ int rc = SQLITE_OK; nName = (int)strlen(zName) + 1; nByte = sizeof(Fts5TokenizerModule) + nName; pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte); if( pNew ){ memset(pNew, 0, nByte); pNew->zName = (char*)&pNew[1]; memcpy(pNew->zName, zName, nName); pNew->pUserData = pUserData; pNew->x = *pTokenizer; pNew->xDestroy = xDestroy; pNew->pNext = pGlobal->pTok; pGlobal->pTok = pNew; if( pNew->pNext==0 ){ pGlobal->pDfltTok = pNew; } }else{ rc = SQLITE_NOMEM; } return rc; } static Fts5TokenizerModule *fts5LocateTokenizer( Fts5Global *pGlobal, const char *zName ){ Fts5TokenizerModule *pMod = 0; if( zName==0 ){ pMod = pGlobal->pDfltTok; }else{ for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){ if( sqlite3_stricmp(zName, pMod->zName)==0 ) break; } } return pMod; } /* ** Find a tokenizer. This is the implementation of the ** fts5_api.xFindTokenizer() method. */ static int fts5FindTokenizer( fts5_api *pApi, /* Global context (one per db handle) */ const char *zName, /* Name of new function */ void **ppUserData, fts5_tokenizer *pTokenizer /* Populate this object */ ){ int rc = SQLITE_OK; Fts5TokenizerModule *pMod; pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName); if( pMod ){ *pTokenizer = pMod->x; *ppUserData = pMod->pUserData; }else{ memset(pTokenizer, 0, sizeof(fts5_tokenizer)); rc = SQLITE_ERROR; } return rc; } static int sqlite3Fts5GetTokenizer( Fts5Global *pGlobal, const char **azArg, int nArg, Fts5Tokenizer **ppTok, fts5_tokenizer **ppTokApi, char **pzErr ){ Fts5TokenizerModule *pMod; int rc = SQLITE_OK; pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]); if( pMod==0 ){ assert( nArg>0 ); rc = SQLITE_ERROR; *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]); }else{ rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok); *ppTokApi = &pMod->x; if( rc!=SQLITE_OK && pzErr ){ *pzErr = sqlite3_mprintf("error in tokenizer constructor"); } } if( rc!=SQLITE_OK ){ *ppTokApi = 0; *ppTok = 0; } return rc; } static void fts5ModuleDestroy(void *pCtx){ Fts5TokenizerModule *pTok, *pNextTok; Fts5Auxiliary *pAux, *pNextAux; Fts5Global *pGlobal = (Fts5Global*)pCtx; for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){ pNextAux = pAux->pNext; if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData); sqlite3_free(pAux); } for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){ pNextTok = pTok->pNext; if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData); sqlite3_free(pTok); } sqlite3_free(pGlobal); } static void fts5Fts5Func( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ sqlite3_value **apUnused /* Function arguments */ ){ Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx); char buf[8]; UNUSED_PARAM2(nArg, apUnused); assert( nArg==0 ); assert( sizeof(buf)>=sizeof(pGlobal) ); memcpy(buf, (void*)&pGlobal, sizeof(pGlobal)); sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT); } /* ** Implementation of fts5_source_id() function. */ static void fts5SourceIdFunc( sqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ sqlite3_value **apUnused /* Function arguments */ ){ assert( nArg==0 ); UNUSED_PARAM2(nArg, apUnused); sqlite3_result_text(pCtx, "fts5: 2017-02-13 16:02:40 ada05cfa86ad7f5645450ac7a2a21c9aa6e57d2c", -1, SQLITE_TRANSIENT); } static int fts5Init(sqlite3 *db){ static const sqlite3_module fts5Mod = { /* iVersion */ 2, /* xCreate */ fts5CreateMethod, /* xConnect */ fts5ConnectMethod, /* xBestIndex */ fts5BestIndexMethod, /* xDisconnect */ fts5DisconnectMethod, /* xDestroy */ fts5DestroyMethod, /* xOpen */ fts5OpenMethod, /* xClose */ fts5CloseMethod, /* xFilter */ fts5FilterMethod, /* xNext */ fts5NextMethod, /* xEof */ fts5EofMethod, /* xColumn */ fts5ColumnMethod, /* xRowid */ fts5RowidMethod, /* xUpdate */ fts5UpdateMethod, /* xBegin */ fts5BeginMethod, /* xSync */ fts5SyncMethod, /* xCommit */ fts5CommitMethod, /* xRollback */ fts5RollbackMethod, /* xFindFunction */ fts5FindFunctionMethod, /* xRename */ fts5RenameMethod, /* xSavepoint */ fts5SavepointMethod, /* xRelease */ fts5ReleaseMethod, /* xRollbackTo */ fts5RollbackToMethod, }; int rc; Fts5Global *pGlobal = 0; pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global)); if( pGlobal==0 ){ rc = SQLITE_NOMEM; }else{ void *p = (void*)pGlobal; memset(pGlobal, 0, sizeof(Fts5Global)); pGlobal->db = db; pGlobal->api.iVersion = 2; pGlobal->api.xCreateFunction = fts5CreateAux; pGlobal->api.xCreateTokenizer = fts5CreateTokenizer; pGlobal->api.xFindTokenizer = fts5FindTokenizer; rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy); if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db); if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db); if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api); if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api); if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db); if( rc==SQLITE_OK ){ rc = sqlite3_create_function( db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0 ); } if( rc==SQLITE_OK ){ rc = sqlite3_create_function( db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0 ); } } /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file ** fts5_test_mi.c is compiled and linked into the executable. And call ** its entry point to enable the matchinfo() demo. */ #ifdef SQLITE_FTS5_ENABLE_TEST_MI if( rc==SQLITE_OK ){ extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*); rc = sqlite3Fts5TestRegisterMatchinfo(db); } #endif return rc; } /* ** The following functions are used to register the module with SQLite. If ** this module is being built as part of the SQLite core (SQLITE_CORE is ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly. ** ** Or, if this module is being built as a loadable extension, ** sqlite3Fts5Init() is omitted and the two standard entry points ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead. */ #ifndef SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_fts_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return fts5Init(db); } #ifdef _WIN32 __declspec(dllexport) #endif SQLITE_API int sqlite3_fts5_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return fts5Init(db); } #else SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){ return fts5Init(db); } #endif /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** */ /* #include "fts5Int.h" */ struct Fts5Storage { Fts5Config *pConfig; Fts5Index *pIndex; int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */ i64 nTotalRow; /* Total number of rows in FTS table */ i64 *aTotalSize; /* Total sizes of each column */ sqlite3_stmt *aStmt[11]; }; #if FTS5_STMT_SCAN_ASC!=0 # error "FTS5_STMT_SCAN_ASC mismatch" #endif #if FTS5_STMT_SCAN_DESC!=1 # error "FTS5_STMT_SCAN_DESC mismatch" #endif #if FTS5_STMT_LOOKUP!=2 # error "FTS5_STMT_LOOKUP mismatch" #endif #define FTS5_STMT_INSERT_CONTENT 3 #define FTS5_STMT_REPLACE_CONTENT 4 #define FTS5_STMT_DELETE_CONTENT 5 #define FTS5_STMT_REPLACE_DOCSIZE 6 #define FTS5_STMT_DELETE_DOCSIZE 7 #define FTS5_STMT_LOOKUP_DOCSIZE 8 #define FTS5_STMT_REPLACE_CONFIG 9 #define FTS5_STMT_SCAN 10 /* ** Prepare the two insert statements - Fts5Storage.pInsertContent and ** Fts5Storage.pInsertDocsize - if they have not already been prepared. ** Return SQLITE_OK if successful, or an SQLite error code if an error ** occurs. */ static int fts5StorageGetStmt( Fts5Storage *p, /* Storage handle */ int eStmt, /* FTS5_STMT_XXX constant */ sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */ char **pzErrMsg /* OUT: Error message (if any) */ ){ int rc = SQLITE_OK; /* If there is no %_docsize table, there should be no requests for ** statements to operate on it. */ assert( p->pConfig->bColumnsize || ( eStmt!=FTS5_STMT_REPLACE_DOCSIZE && eStmt!=FTS5_STMT_DELETE_DOCSIZE && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE )); assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) ); if( p->aStmt[eStmt]==0 ){ const char *azStmt[] = { "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC", "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC", "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */ "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */ "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */ "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */ "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */ "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */ "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */ "SELECT %s FROM %s AS T", /* SCAN */ }; Fts5Config *pC = p->pConfig; char *zSql = 0; switch( eStmt ){ case FTS5_STMT_SCAN: zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, pC->zContent ); break; case FTS5_STMT_SCAN_ASC: case FTS5_STMT_SCAN_DESC: zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, pC->zContent, pC->zContentRowid, pC->zContentRowid, pC->zContentRowid ); break; case FTS5_STMT_LOOKUP: zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, pC->zContent, pC->zContentRowid ); break; case FTS5_STMT_INSERT_CONTENT: case FTS5_STMT_REPLACE_CONTENT: { int nCol = pC->nCol + 1; char *zBind; int i; zBind = sqlite3_malloc(1 + nCol*2); if( zBind ){ for(i=0; i<nCol; i++){ zBind[i*2] = '?'; zBind[i*2 + 1] = ','; } zBind[i*2-1] = '\0'; zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind); sqlite3_free(zBind); } break; } default: zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName); break; } if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0); sqlite3_free(zSql); if( rc!=SQLITE_OK && pzErrMsg ){ *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db)); } } } *ppStmt = p->aStmt[eStmt]; sqlite3_reset(*ppStmt); return rc; } static int fts5ExecPrintf( sqlite3 *db, char **pzErr, const char *zFormat, ... ){ int rc; va_list ap; /* ... printf arguments */ char *zSql; va_start(ap, zFormat); zSql = sqlite3_vmprintf(zFormat, ap); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ rc = sqlite3_exec(db, zSql, 0, 0, pzErr); sqlite3_free(zSql); } va_end(ap); return rc; } /* ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error ** code otherwise. */ static int sqlite3Fts5DropAll(Fts5Config *pConfig){ int rc = fts5ExecPrintf(pConfig->db, 0, "DROP TABLE IF EXISTS %Q.'%q_data';" "DROP TABLE IF EXISTS %Q.'%q_idx';" "DROP TABLE IF EXISTS %Q.'%q_config';", pConfig->zDb, pConfig->zName, pConfig->zDb, pConfig->zName, pConfig->zDb, pConfig->zName ); if( rc==SQLITE_OK && pConfig->bColumnsize ){ rc = fts5ExecPrintf(pConfig->db, 0, "DROP TABLE IF EXISTS %Q.'%q_docsize';", pConfig->zDb, pConfig->zName ); } if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){ rc = fts5ExecPrintf(pConfig->db, 0, "DROP TABLE IF EXISTS %Q.'%q_content';", pConfig->zDb, pConfig->zName ); } return rc; } static void fts5StorageRenameOne( Fts5Config *pConfig, /* Current FTS5 configuration */ int *pRc, /* IN/OUT: Error code */ const char *zTail, /* Tail of table name e.g. "data", "config" */ const char *zName /* New name of FTS5 table */ ){ if( *pRc==SQLITE_OK ){ *pRc = fts5ExecPrintf(pConfig->db, 0, "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';", pConfig->zDb, pConfig->zName, zTail, zName, zTail ); } } static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){ Fts5Config *pConfig = pStorage->pConfig; int rc = sqlite3Fts5StorageSync(pStorage, 1); fts5StorageRenameOne(pConfig, &rc, "data", zName); fts5StorageRenameOne(pConfig, &rc, "idx", zName); fts5StorageRenameOne(pConfig, &rc, "config", zName); if( pConfig->bColumnsize ){ fts5StorageRenameOne(pConfig, &rc, "docsize", zName); } if( pConfig->eContent==FTS5_CONTENT_NORMAL ){ fts5StorageRenameOne(pConfig, &rc, "content", zName); } return rc; } /* ** Create the shadow table named zPost, with definition zDefn. Return ** SQLITE_OK if successful, or an SQLite error code otherwise. */ static int sqlite3Fts5CreateTable( Fts5Config *pConfig, /* FTS5 configuration */ const char *zPost, /* Shadow table to create (e.g. "content") */ const char *zDefn, /* Columns etc. for shadow table */ int bWithout, /* True for without rowid */ char **pzErr /* OUT: Error message */ ){ int rc; char *zErr = 0; rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s", pConfig->zDb, pConfig->zName, zPost, zDefn, #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID bWithout?" WITHOUT ROWID": #endif "" ); if( zErr ){ *pzErr = sqlite3_mprintf( "fts5: error creating shadow table %q_%s: %s", pConfig->zName, zPost, zErr ); sqlite3_free(zErr); } return rc; } /* ** Open a new Fts5Index handle. If the bCreate argument is true, create ** and initialize the underlying tables ** ** If successful, set *pp to point to the new object and return SQLITE_OK. ** Otherwise, set *pp to NULL and return an SQLite error code. */ static int sqlite3Fts5StorageOpen( Fts5Config *pConfig, Fts5Index *pIndex, int bCreate, Fts5Storage **pp, char **pzErr /* OUT: Error message */ ){ int rc = SQLITE_OK; Fts5Storage *p; /* New object */ int nByte; /* Bytes of space to allocate */ nByte = sizeof(Fts5Storage) /* Fts5Storage object */ + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */ *pp = p = (Fts5Storage*)sqlite3_malloc(nByte); if( !p ) return SQLITE_NOMEM; memset(p, 0, nByte); p->aTotalSize = (i64*)&p[1]; p->pConfig = pConfig; p->pIndex = pIndex; if( bCreate ){ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){ int nDefn = 32 + pConfig->nCol*10; char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10); if( zDefn==0 ){ rc = SQLITE_NOMEM; }else{ int i; int iOff; sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY"); iOff = (int)strlen(zDefn); for(i=0; i<pConfig->nCol; i++){ sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i); iOff += (int)strlen(&zDefn[iOff]); } rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr); } sqlite3_free(zDefn); } if( rc==SQLITE_OK && pConfig->bColumnsize ){ rc = sqlite3Fts5CreateTable( pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr ); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5CreateTable( pConfig, "config", "k PRIMARY KEY, v", 1, pzErr ); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION); } } if( rc ){ sqlite3Fts5StorageClose(p); *pp = 0; } return rc; } /* ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen(). */ static int sqlite3Fts5StorageClose(Fts5Storage *p){ int rc = SQLITE_OK; if( p ){ int i; /* Finalize all SQL statements */ for(i=0; i<ArraySize(p->aStmt); i++){ sqlite3_finalize(p->aStmt[i]); } sqlite3_free(p); } return rc; } typedef struct Fts5InsertCtx Fts5InsertCtx; struct Fts5InsertCtx { Fts5Storage *pStorage; int iCol; int szCol; /* Size of column value in tokens */ }; /* ** Tokenization callback used when inserting tokens into the FTS index. */ static int fts5StorageInsertCallback( void *pContext, /* Pointer to Fts5InsertCtx object */ int tflags, const char *pToken, /* Buffer containing token */ int nToken, /* Size of token in bytes */ int iUnused1, /* Start offset of token */ int iUnused2 /* End offset of token */ ){ Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext; Fts5Index *pIdx = pCtx->pStorage->pIndex; UNUSED_PARAM2(iUnused1, iUnused2); if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE; if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){ pCtx->szCol++; } return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken); } /* ** If a row with rowid iDel is present in the %_content table, add the ** delete-markers to the FTS index necessary to delete it. Do not actually ** remove the %_content row at this time though. */ static int fts5StorageDeleteFromIndex( Fts5Storage *p, i64 iDel, sqlite3_value **apVal ){ Fts5Config *pConfig = p->pConfig; sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */ int rc; /* Return code */ int rc2; /* sqlite3_reset() return code */ int iCol; Fts5InsertCtx ctx; if( apVal==0 ){ rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0); if( rc!=SQLITE_OK ) return rc; sqlite3_bind_int64(pSeek, 1, iDel); if( sqlite3_step(pSeek)!=SQLITE_ROW ){ return sqlite3_reset(pSeek); } } ctx.pStorage = p; ctx.iCol = -1; rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel); for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){ if( pConfig->abUnindexed[iCol-1]==0 ){ const char *zText; int nText; if( pSeek ){ zText = (const char*)sqlite3_column_text(pSeek, iCol); nText = sqlite3_column_bytes(pSeek, iCol); }else{ zText = (const char*)sqlite3_value_text(apVal[iCol-1]); nText = sqlite3_value_bytes(apVal[iCol-1]); } ctx.szCol = 0; rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, zText, nText, (void*)&ctx, fts5StorageInsertCallback ); p->aTotalSize[iCol-1] -= (i64)ctx.szCol; } } p->nTotalRow--; rc2 = sqlite3_reset(pSeek); if( rc==SQLITE_OK ) rc = rc2; return rc; } /* ** Insert a record into the %_docsize table. Specifically, do: ** ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf); ** ** If there is no %_docsize table (as happens if the columnsize=0 option ** is specified when the FTS5 table is created), this function is a no-op. */ static int fts5StorageInsertDocsize( Fts5Storage *p, /* Storage module to write to */ i64 iRowid, /* id value */ Fts5Buffer *pBuf /* sz value */ ){ int rc = SQLITE_OK; if( p->pConfig->bColumnsize ){ sqlite3_stmt *pReplace = 0; rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pReplace, 1, iRowid); sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC); sqlite3_step(pReplace); rc = sqlite3_reset(pReplace); } } return rc; } /* ** Load the contents of the "averages" record from disk into the ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if ** argument bCache is true, set the p->bTotalsValid flag to indicate ** that the contents of aTotalSize[] and nTotalRow are valid until ** further notice. ** ** Return SQLITE_OK if successful, or an SQLite error code if an error ** occurs. */ static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){ int rc = SQLITE_OK; if( p->bTotalsValid==0 ){ rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize); p->bTotalsValid = bCache; } return rc; } /* ** Store the current contents of the p->nTotalRow and p->aTotalSize[] ** variables in the "averages" record on disk. ** ** Return SQLITE_OK if successful, or an SQLite error code if an error ** occurs. */ static int fts5StorageSaveTotals(Fts5Storage *p){ int nCol = p->pConfig->nCol; int i; Fts5Buffer buf; int rc = SQLITE_OK; memset(&buf, 0, sizeof(buf)); sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow); for(i=0; i<nCol; i++){ sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n); } sqlite3_free(buf.p); return rc; } /* ** Remove a row from the FTS table. */ static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){ Fts5Config *pConfig = p->pConfig; int rc; sqlite3_stmt *pDel = 0; assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 ); rc = fts5StorageLoadTotals(p, 1); /* Delete the index records */ if( rc==SQLITE_OK ){ rc = fts5StorageDeleteFromIndex(p, iDel, apVal); } /* Delete the %_docsize record */ if( rc==SQLITE_OK && pConfig->bColumnsize ){ rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDel, 1, iDel); sqlite3_step(pDel); rc = sqlite3_reset(pDel); } } /* Delete the %_content record */ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){ if( rc==SQLITE_OK ){ rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0); } if( rc==SQLITE_OK ){ sqlite3_bind_int64(pDel, 1, iDel); sqlite3_step(pDel); rc = sqlite3_reset(pDel); } } /* Write the averages record */ if( rc==SQLITE_OK ){ rc = fts5StorageSaveTotals(p); } return rc; } /* ** Delete all entries in the FTS5 index. */ static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){ Fts5Config *pConfig = p->pConfig; int rc; /* Delete the contents of the %_data and %_docsize tables. */ rc = fts5ExecPrintf(pConfig->db, 0, "DELETE FROM %Q.'%q_data';" "DELETE FROM %Q.'%q_idx';", pConfig->zDb, pConfig->zName, pConfig->zDb, pConfig->zName ); if( rc==SQLITE_OK && pConfig->bColumnsize ){ rc = fts5ExecPrintf(pConfig->db, 0, "DELETE FROM %Q.'%q_docsize';", pConfig->zDb, pConfig->zName ); } /* Reinitialize the %_data table. This call creates the initial structure ** and averages records. */ if( rc==SQLITE_OK ){ rc = sqlite3Fts5IndexReinit(p->pIndex); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION); } return rc; } static int sqlite3Fts5StorageRebuild(Fts5Storage *p){ Fts5Buffer buf = {0,0,0}; Fts5Config *pConfig = p->pConfig; sqlite3_stmt *pScan = 0; Fts5InsertCtx ctx; int rc; memset(&ctx, 0, sizeof(Fts5InsertCtx)); ctx.pStorage = p; rc = sqlite3Fts5StorageDeleteAll(p); if( rc==SQLITE_OK ){ rc = fts5StorageLoadTotals(p, 1); } if( rc==SQLITE_OK ){ rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0); } while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){ i64 iRowid = sqlite3_column_int64(pScan, 0); sqlite3Fts5BufferZero(&buf); rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid); for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){ ctx.szCol = 0; if( pConfig->abUnindexed[ctx.iCol]==0 ){ rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, (const char*)sqlite3_column_text(pScan, ctx.iCol+1), sqlite3_column_bytes(pScan, ctx.iCol+1), (void*)&ctx, fts5StorageInsertCallback ); } sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol); p->aTotalSize[ctx.iCol] += (i64)ctx.szCol; } p->nTotalRow++; if( rc==SQLITE_OK ){ rc = fts5StorageInsertDocsize(p, iRowid, &buf); } } sqlite3_free(buf.p); /* Write the averages record */ if( rc==SQLITE_OK ){ rc = fts5StorageSaveTotals(p); } return rc; } static int sqlite3Fts5StorageOptimize(Fts5Storage *p){ return sqlite3Fts5IndexOptimize(p->pIndex); } static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){ return sqlite3Fts5IndexMerge(p->pIndex, nMerge); } static int sqlite3Fts5StorageReset(Fts5Storage *p){ return sqlite3Fts5IndexReset(p->pIndex); } /* ** Allocate a new rowid. This is used for "external content" tables when ** a NULL value is inserted into the rowid column. The new rowid is allocated ** by inserting a dummy row into the %_docsize table. The dummy will be ** overwritten later. ** ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In ** this case the user is required to provide a rowid explicitly. */ static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){ int rc = SQLITE_MISMATCH; if( p->pConfig->bColumnsize ){ sqlite3_stmt *pReplace = 0; rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0); if( rc==SQLITE_OK ){ sqlite3_bind_null(pReplace, 1); sqlite3_bind_null(pReplace, 2); sqlite3_step(pReplace); rc = sqlite3_reset(pReplace); } if( rc==SQLITE_OK ){ *piRowid = sqlite3_last_insert_rowid(p->pConfig->db); } } return rc; } /* ** Insert a new row into the FTS content table. */ static int sqlite3Fts5StorageContentInsert( Fts5Storage *p, sqlite3_value **apVal, i64 *piRowid ){ Fts5Config *pConfig = p->pConfig; int rc = SQLITE_OK; /* Insert the new row into the %_content table. */ if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){ if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){ *piRowid = sqlite3_value_int64(apVal[1]); }else{ rc = fts5StorageNewRowid(p, piRowid); } }else{ sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */ int i; /* Counter variable */ rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0); for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){ rc = sqlite3_bind_value(pInsert, i, apVal[i]); } if( rc==SQLITE_OK ){ sqlite3_step(pInsert); rc = sqlite3_reset(pInsert); } *piRowid = sqlite3_last_insert_rowid(pConfig->db); } return rc; } /* ** Insert new entries into the FTS index and %_docsize table. */ static int sqlite3Fts5StorageIndexInsert( Fts5Storage *p, sqlite3_value **apVal, i64 iRowid ){ Fts5Config *pConfig = p->pConfig; int rc = SQLITE_OK; /* Return code */ Fts5InsertCtx ctx; /* Tokenization callback context object */ Fts5Buffer buf; /* Buffer used to build up %_docsize blob */ memset(&buf, 0, sizeof(Fts5Buffer)); ctx.pStorage = p; rc = fts5StorageLoadTotals(p, 1); if( rc==SQLITE_OK ){ rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid); } for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){ ctx.szCol = 0; if( pConfig->abUnindexed[ctx.iCol]==0 ){ rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, (const char*)sqlite3_value_text(apVal[ctx.iCol+2]), sqlite3_value_bytes(apVal[ctx.iCol+2]), (void*)&ctx, fts5StorageInsertCallback ); } sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol); p->aTotalSize[ctx.iCol] += (i64)ctx.szCol; } p->nTotalRow++; /* Write the %_docsize record */ if( rc==SQLITE_OK ){ rc = fts5StorageInsertDocsize(p, iRowid, &buf); } sqlite3_free(buf.p); /* Write the averages record */ if( rc==SQLITE_OK ){ rc = fts5StorageSaveTotals(p); } return rc; } static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){ Fts5Config *pConfig = p->pConfig; char *zSql; int rc; zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'", pConfig->zDb, pConfig->zName, zSuffix ); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ sqlite3_stmt *pCnt = 0; rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0); if( rc==SQLITE_OK ){ if( SQLITE_ROW==sqlite3_step(pCnt) ){ *pnRow = sqlite3_column_int64(pCnt, 0); } rc = sqlite3_finalize(pCnt); } } sqlite3_free(zSql); return rc; } /* ** Context object used by sqlite3Fts5StorageIntegrity(). */ typedef struct Fts5IntegrityCtx Fts5IntegrityCtx; struct Fts5IntegrityCtx { i64 iRowid; int iCol; int szCol; u64 cksum; Fts5Termset *pTermset; Fts5Config *pConfig; }; /* ** Tokenization callback used by integrity check. */ static int fts5StorageIntegrityCallback( void *pContext, /* Pointer to Fts5IntegrityCtx object */ int tflags, const char *pToken, /* Buffer containing token */ int nToken, /* Size of token in bytes */ int iUnused1, /* Start offset of token */ int iUnused2 /* End offset of token */ ){ Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext; Fts5Termset *pTermset = pCtx->pTermset; int bPresent; int ii; int rc = SQLITE_OK; int iPos; int iCol; UNUSED_PARAM2(iUnused1, iUnused2); if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE; if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){ pCtx->szCol++; } switch( pCtx->pConfig->eDetail ){ case FTS5_DETAIL_FULL: iPos = pCtx->szCol-1; iCol = pCtx->iCol; break; case FTS5_DETAIL_COLUMNS: iPos = pCtx->iCol; iCol = 0; break; default: assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE ); iPos = 0; iCol = 0; break; } rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent); if( rc==SQLITE_OK && bPresent==0 ){ pCtx->cksum ^= sqlite3Fts5IndexEntryCksum( pCtx->iRowid, iCol, iPos, 0, pToken, nToken ); } for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){ const int nChar = pCtx->pConfig->aPrefix[ii]; int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar); if( nByte ){ rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent); if( bPresent==0 ){ pCtx->cksum ^= sqlite3Fts5IndexEntryCksum( pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte ); } } } return rc; } /* ** Check that the contents of the FTS index match that of the %_content ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return ** some other SQLite error code if an error occurs while attempting to ** determine this. */ static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){ Fts5Config *pConfig = p->pConfig; int rc; /* Return code */ int *aColSize; /* Array of size pConfig->nCol */ i64 *aTotalSize; /* Array of size pConfig->nCol */ Fts5IntegrityCtx ctx; sqlite3_stmt *pScan; memset(&ctx, 0, sizeof(Fts5IntegrityCtx)); ctx.pConfig = p->pConfig; aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64))); if( !aTotalSize ) return SQLITE_NOMEM; aColSize = (int*)&aTotalSize[pConfig->nCol]; memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol); /* Generate the expected index checksum based on the contents of the ** %_content table. This block stores the checksum in ctx.cksum. */ rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0); if( rc==SQLITE_OK ){ int rc2; while( SQLITE_ROW==sqlite3_step(pScan) ){ int i; ctx.iRowid = sqlite3_column_int64(pScan, 0); ctx.szCol = 0; if( pConfig->bColumnsize ){ rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize); } if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){ rc = sqlite3Fts5TermsetNew(&ctx.pTermset); } for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){ if( pConfig->abUnindexed[i] ) continue; ctx.iCol = i; ctx.szCol = 0; if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ rc = sqlite3Fts5TermsetNew(&ctx.pTermset); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, (const char*)sqlite3_column_text(pScan, i+1), sqlite3_column_bytes(pScan, i+1), (void*)&ctx, fts5StorageIntegrityCallback ); } if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){ rc = FTS5_CORRUPT; } aTotalSize[i] += ctx.szCol; if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ sqlite3Fts5TermsetFree(ctx.pTermset); ctx.pTermset = 0; } } sqlite3Fts5TermsetFree(ctx.pTermset); ctx.pTermset = 0; if( rc!=SQLITE_OK ) break; } rc2 = sqlite3_reset(pScan); if( rc==SQLITE_OK ) rc = rc2; } /* Test that the "totals" (sometimes called "averages") record looks Ok */ if( rc==SQLITE_OK ){ int i; rc = fts5StorageLoadTotals(p, 0); for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){ if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT; } } /* Check that the %_docsize and %_content tables contain the expected ** number of rows. */ if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){ i64 nRow = 0; rc = fts5StorageCount(p, "content", &nRow); if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT; } if( rc==SQLITE_OK && pConfig->bColumnsize ){ i64 nRow = 0; rc = fts5StorageCount(p, "docsize", &nRow); if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT; } /* Pass the expected checksum down to the FTS index module. It will ** verify, amongst other things, that it matches the checksum generated by ** inspecting the index itself. */ if( rc==SQLITE_OK ){ rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum); } sqlite3_free(aTotalSize); return rc; } /* ** Obtain an SQLite statement handle that may be used to read data from the ** %_content table. */ static int sqlite3Fts5StorageStmt( Fts5Storage *p, int eStmt, sqlite3_stmt **pp, char **pzErrMsg ){ int rc; assert( eStmt==FTS5_STMT_SCAN_ASC || eStmt==FTS5_STMT_SCAN_DESC || eStmt==FTS5_STMT_LOOKUP ); rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg); if( rc==SQLITE_OK ){ assert( p->aStmt[eStmt]==*pp ); p->aStmt[eStmt] = 0; } return rc; } /* ** Release an SQLite statement handle obtained via an earlier call to ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function ** must match that passed to the sqlite3Fts5StorageStmt() call. */ static void sqlite3Fts5StorageStmtRelease( Fts5Storage *p, int eStmt, sqlite3_stmt *pStmt ){ assert( eStmt==FTS5_STMT_SCAN_ASC || eStmt==FTS5_STMT_SCAN_DESC || eStmt==FTS5_STMT_LOOKUP ); if( p->aStmt[eStmt]==0 ){ sqlite3_reset(pStmt); p->aStmt[eStmt] = pStmt; }else{ sqlite3_finalize(pStmt); } } static int fts5StorageDecodeSizeArray( int *aCol, int nCol, /* Array to populate */ const u8 *aBlob, int nBlob /* Record to read varints from */ ){ int i; int iOff = 0; for(i=0; i<nCol; i++){ if( iOff>=nBlob ) return 1; iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]); } return (iOff!=nBlob); } /* ** Argument aCol points to an array of integers containing one entry for ** each table column. This function reads the %_docsize record for the ** specified rowid and populates aCol[] with the results. ** ** An SQLite error code is returned if an error occurs, or SQLITE_OK ** otherwise. */ static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){ int nCol = p->pConfig->nCol; /* Number of user columns in table */ sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */ int rc; /* Return Code */ assert( p->pConfig->bColumnsize ); rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0); if( rc==SQLITE_OK ){ int bCorrupt = 1; sqlite3_bind_int64(pLookup, 1, iRowid); if( SQLITE_ROW==sqlite3_step(pLookup) ){ const u8 *aBlob = sqlite3_column_blob(pLookup, 0); int nBlob = sqlite3_column_bytes(pLookup, 0); if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){ bCorrupt = 0; } } rc = sqlite3_reset(pLookup); if( bCorrupt && rc==SQLITE_OK ){ rc = FTS5_CORRUPT; } } return rc; } static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){ int rc = fts5StorageLoadTotals(p, 0); if( rc==SQLITE_OK ){ *pnToken = 0; if( iCol<0 ){ int i; for(i=0; i<p->pConfig->nCol; i++){ *pnToken += p->aTotalSize[i]; } }else if( iCol<p->pConfig->nCol ){ *pnToken = p->aTotalSize[iCol]; }else{ rc = SQLITE_RANGE; } } return rc; } static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){ int rc = fts5StorageLoadTotals(p, 0); if( rc==SQLITE_OK ){ *pnRow = p->nTotalRow; } return rc; } /* ** Flush any data currently held in-memory to disk. */ static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){ if( bCommit && p->bTotalsValid ){ int rc = fts5StorageSaveTotals(p); p->bTotalsValid = 0; if( rc!=SQLITE_OK ) return rc; } return sqlite3Fts5IndexSync(p->pIndex, bCommit); } static int sqlite3Fts5StorageRollback(Fts5Storage *p){ p->bTotalsValid = 0; return sqlite3Fts5IndexRollback(p->pIndex); } static int sqlite3Fts5StorageConfigValue( Fts5Storage *p, const char *z, sqlite3_value *pVal, int iVal ){ sqlite3_stmt *pReplace = 0; int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0); if( rc==SQLITE_OK ){ sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC); if( pVal ){ sqlite3_bind_value(pReplace, 2, pVal); }else{ sqlite3_bind_int(pReplace, 2, iVal); } sqlite3_step(pReplace); rc = sqlite3_reset(pReplace); } if( rc==SQLITE_OK && pVal ){ int iNew = p->pConfig->iCookie + 1; rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew); if( rc==SQLITE_OK ){ p->pConfig->iCookie = iNew; } } return rc; } /* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** */ /* #include "fts5Int.h" */ /************************************************************************** ** Start of ascii tokenizer implementation. */ /* ** For tokenizers with no "unicode" modifier, the set of token characters ** is the same as the set of ASCII range alphanumeric characters. */ static unsigned char aAsciiTokenChar[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */ }; typedef struct AsciiTokenizer AsciiTokenizer; struct AsciiTokenizer { unsigned char aTokenChar[128]; }; static void fts5AsciiAddExceptions( AsciiTokenizer *p, const char *zArg, int bTokenChars ){ int i; for(i=0; zArg[i]; i++){ if( (zArg[i] & 0x80)==0 ){ p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars; } } } /* ** Delete a "ascii" tokenizer. */ static void fts5AsciiDelete(Fts5Tokenizer *p){ sqlite3_free(p); } /* ** Create an "ascii" tokenizer. */ static int fts5AsciiCreate( void *pUnused, const char **azArg, int nArg, Fts5Tokenizer **ppOut ){ int rc = SQLITE_OK; AsciiTokenizer *p = 0; UNUSED_PARAM(pUnused); if( nArg%2 ){ rc = SQLITE_ERROR; }else{ p = sqlite3_malloc(sizeof(AsciiTokenizer)); if( p==0 ){ rc = SQLITE_NOMEM; }else{ int i; memset(p, 0, sizeof(AsciiTokenizer)); memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar)); for(i=0; rc==SQLITE_OK && i<nArg; i+=2){ const char *zArg = azArg[i+1]; if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){ fts5AsciiAddExceptions(p, zArg, 1); }else if( 0==sqlite3_stricmp(azArg[i], "separators") ){ fts5AsciiAddExceptions(p, zArg, 0); }else{ rc = SQLITE_ERROR; } } if( rc!=SQLITE_OK ){ fts5AsciiDelete((Fts5Tokenizer*)p); p = 0; } } } *ppOut = (Fts5Tokenizer*)p; return rc; } static void asciiFold(char *aOut, const char *aIn, int nByte){ int i; for(i=0; i<nByte; i++){ char c = aIn[i]; if( c>='A' && c<='Z' ) c += 32; aOut[i] = c; } } /* ** Tokenize some text using the ascii tokenizer. */ static int fts5AsciiTokenize( Fts5Tokenizer *pTokenizer, void *pCtx, int iUnused, const char *pText, int nText, int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd) ){ AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer; int rc = SQLITE_OK; int ie; int is = 0; char aFold[64]; int nFold = sizeof(aFold); char *pFold = aFold; unsigned char *a = p->aTokenChar; UNUSED_PARAM(iUnused); while( is<nText && rc==SQLITE_OK ){ int nByte; /* Skip any leading divider characters. */ while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){ is++; } if( is==nText ) break; /* Count the token characters */ ie = is+1; while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){ ie++; } /* Fold to lower case */ nByte = ie-is; if( nByte>nFold ){ if( pFold!=aFold ) sqlite3_free(pFold); pFold = sqlite3_malloc(nByte*2); if( pFold==0 ){ rc = SQLITE_NOMEM; break; } nFold = nByte*2; } asciiFold(pFold, &pText[is], nByte); /* Invoke the token callback */ rc = xToken(pCtx, 0, pFold, nByte, is, ie); is = ie+1; } if( pFold!=aFold ) sqlite3_free(pFold); if( rc==SQLITE_DONE ) rc = SQLITE_OK; return rc; } /************************************************************************** ** Start of unicode61 tokenizer implementation. */ /* ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied ** from the sqlite3 source file utf.c. If this file is compiled as part ** of the amalgamation, they are not required. */ #ifndef SQLITE_AMALGAMATION static const unsigned char sqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = sqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ if( c<0x80 \ || (c&0xFFFFF800)==0xD800 \ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } #define WRITE_UTF8(zOut, c) { \ if( c<0x00080 ){ \ *zOut++ = (unsigned char)(c&0xFF); \ } \ else if( c<0x00800 ){ \ *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \ *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ } \ else if( c<0x10000 ){ \ *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \ *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ }else{ \ *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \ *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \ *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ } \ } #endif /* ifndef SQLITE_AMALGAMATION */ typedef struct Unicode61Tokenizer Unicode61Tokenizer; struct Unicode61Tokenizer { unsigned char aTokenChar[128]; /* ASCII range token characters */ char *aFold; /* Buffer to fold text into */ int nFold; /* Size of aFold[] in bytes */ int bRemoveDiacritic; /* True if remove_diacritics=1 is set */ int nException; int *aiException; }; static int fts5UnicodeAddExceptions( Unicode61Tokenizer *p, /* Tokenizer object */ const char *z, /* Characters to treat as exceptions */ int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */ ){ int rc = SQLITE_OK; int n = (int)strlen(z); int *aNew; if( n>0 ){ aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int)); if( aNew ){ int nNew = p->nException; const unsigned char *zCsr = (const unsigned char*)z; const unsigned char *zTerm = (const unsigned char*)&z[n]; while( zCsr<zTerm ){ int iCode; int bToken; READ_UTF8(zCsr, zTerm, iCode); if( iCode<128 ){ p->aTokenChar[iCode] = (unsigned char)bTokenChars; }else{ bToken = sqlite3Fts5UnicodeIsalnum(iCode); assert( (bToken==0 || bToken==1) ); assert( (bTokenChars==0 || bTokenChars==1) ); if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){ int i; for(i=0; i<nNew; i++){ if( aNew[i]>iCode ) break; } memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int)); aNew[i] = iCode; nNew++; } } } p->aiException = aNew; p->nException = nNew; }else{ rc = SQLITE_NOMEM; } } return rc; } /* ** Return true if the p->aiException[] array contains the value iCode. */ static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){ if( p->nException>0 ){ int *a = p->aiException; int iLo = 0; int iHi = p->nException-1; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( iCode==a[iTest] ){ return 1; }else if( iCode>a[iTest] ){ iLo = iTest+1; }else{ iHi = iTest-1; } } } return 0; } /* ** Delete a "unicode61" tokenizer. */ static void fts5UnicodeDelete(Fts5Tokenizer *pTok){ if( pTok ){ Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok; sqlite3_free(p->aiException); sqlite3_free(p->aFold); sqlite3_free(p); } return; } /* ** Create a "unicode61" tokenizer. */ static int fts5UnicodeCreate( void *pUnused, const char **azArg, int nArg, Fts5Tokenizer **ppOut ){ int rc = SQLITE_OK; /* Return code */ Unicode61Tokenizer *p = 0; /* New tokenizer object */ UNUSED_PARAM(pUnused); if( nArg%2 ){ rc = SQLITE_ERROR; }else{ p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer)); if( p ){ int i; memset(p, 0, sizeof(Unicode61Tokenizer)); memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar)); p->bRemoveDiacritic = 1; p->nFold = 64; p->aFold = sqlite3_malloc(p->nFold * sizeof(char)); if( p->aFold==0 ){ rc = SQLITE_NOMEM; } for(i=0; rc==SQLITE_OK && i<nArg; i+=2){ const char *zArg = azArg[i+1]; if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){ if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){ rc = SQLITE_ERROR; } p->bRemoveDiacritic = (zArg[0]=='1'); }else if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){ rc = fts5UnicodeAddExceptions(p, zArg, 1); }else if( 0==sqlite3_stricmp(azArg[i], "separators") ){ rc = fts5UnicodeAddExceptions(p, zArg, 0); }else{ rc = SQLITE_ERROR; } } }else{ rc = SQLITE_NOMEM; } if( rc!=SQLITE_OK ){ fts5UnicodeDelete((Fts5Tokenizer*)p); p = 0; } *ppOut = (Fts5Tokenizer*)p; } return rc; } /* ** Return true if, for the purposes of tokenizing with the tokenizer ** passed as the first argument, codepoint iCode is considered a token ** character (not a separator). */ static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){ assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode); } static int fts5UnicodeTokenize( Fts5Tokenizer *pTokenizer, void *pCtx, int iUnused, const char *pText, int nText, int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd) ){ Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer; int rc = SQLITE_OK; unsigned char *a = p->aTokenChar; unsigned char *zTerm = (unsigned char*)&pText[nText]; unsigned char *zCsr = (unsigned char *)pText; /* Output buffer */ char *aFold = p->aFold; int nFold = p->nFold; const char *pEnd = &aFold[nFold-6]; UNUSED_PARAM(iUnused); /* Each iteration of this loop gobbles up a contiguous run of separators, ** then the next token. */ while( rc==SQLITE_OK ){ int iCode; /* non-ASCII codepoint read from input */ char *zOut = aFold; int is; int ie; /* Skip any separator characters. */ while( 1 ){ if( zCsr>=zTerm ) goto tokenize_done; if( *zCsr & 0x80 ) { /* A character outside of the ascii range. Skip past it if it is ** a separator character. Or break out of the loop if it is not. */ is = zCsr - (unsigned char*)pText; READ_UTF8(zCsr, zTerm, iCode); if( fts5UnicodeIsAlnum(p, iCode) ){ goto non_ascii_tokenchar; } }else{ if( a[*zCsr] ){ is = zCsr - (unsigned char*)pText; goto ascii_tokenchar; } zCsr++; } } /* Run through the tokenchars. Fold them into the output buffer along ** the way. */ while( zCsr<zTerm ){ /* Grow the output buffer so that there is sufficient space to fit the ** largest possible utf-8 character. */ if( zOut>pEnd ){ aFold = sqlite3_malloc(nFold*2); if( aFold==0 ){ rc = SQLITE_NOMEM; goto tokenize_done; } zOut = &aFold[zOut - p->aFold]; memcpy(aFold, p->aFold, nFold); sqlite3_free(p->aFold); p->aFold = aFold; p->nFold = nFold = nFold*2; pEnd = &aFold[nFold-6]; } if( *zCsr & 0x80 ){ /* An non-ascii-range character. Fold it into the output buffer if ** it is a token character, or break out of the loop if it is not. */ READ_UTF8(zCsr, zTerm, iCode); if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){ non_ascii_tokenchar: iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic); if( iCode ) WRITE_UTF8(zOut, iCode); }else{ break; } }else if( a[*zCsr]==0 ){ /* An ascii-range separator character. End of token. */ break; }else{ ascii_tokenchar: if( *zCsr>='A' && *zCsr<='Z' ){ *zOut++ = *zCsr + 32; }else{ *zOut++ = *zCsr; } zCsr++; } ie = zCsr - (unsigned char*)pText; } /* Invoke the token callback */ rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie); } tokenize_done: if( rc==SQLITE_DONE ) rc = SQLITE_OK; return rc; } /************************************************************************** ** Start of porter stemmer implementation. */ /* Any tokens larger than this (in bytes) are passed through without ** stemming. */ #define FTS5_PORTER_MAX_TOKEN 64 typedef struct PorterTokenizer PorterTokenizer; struct PorterTokenizer { fts5_tokenizer tokenizer; /* Parent tokenizer module */ Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */ char aBuf[FTS5_PORTER_MAX_TOKEN + 64]; }; /* ** Delete a "porter" tokenizer. */ static void fts5PorterDelete(Fts5Tokenizer *pTok){ if( pTok ){ PorterTokenizer *p = (PorterTokenizer*)pTok; if( p->pTokenizer ){ p->tokenizer.xDelete(p->pTokenizer); } sqlite3_free(p); } } /* ** Create a "porter" tokenizer. */ static int fts5PorterCreate( void *pCtx, const char **azArg, int nArg, Fts5Tokenizer **ppOut ){ fts5_api *pApi = (fts5_api*)pCtx; int rc = SQLITE_OK; PorterTokenizer *pRet; void *pUserdata = 0; const char *zBase = "unicode61"; if( nArg>0 ){ zBase = azArg[0]; } pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer)); if( pRet ){ memset(pRet, 0, sizeof(PorterTokenizer)); rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer); }else{ rc = SQLITE_NOMEM; } if( rc==SQLITE_OK ){ int nArg2 = (nArg>0 ? nArg-1 : 0); const char **azArg2 = (nArg2 ? &azArg[1] : 0); rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer); } if( rc!=SQLITE_OK ){ fts5PorterDelete((Fts5Tokenizer*)pRet); pRet = 0; } *ppOut = (Fts5Tokenizer*)pRet; return rc; } typedef struct PorterContext PorterContext; struct PorterContext { void *pCtx; int (*xToken)(void*, int, const char*, int, int, int); char *aBuf; }; typedef struct PorterRule PorterRule; struct PorterRule { const char *zSuffix; int nSuffix; int (*xCond)(char *zStem, int nStem); const char *zOutput; int nOutput; }; #if 0 static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){ int ret = -1; int nBuf = *pnBuf; PorterRule *p; for(p=aRule; p->zSuffix; p++){ assert( strlen(p->zSuffix)==p->nSuffix ); assert( strlen(p->zOutput)==p->nOutput ); if( nBuf<p->nSuffix ) continue; if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break; } if( p->zSuffix ){ int nStem = nBuf - p->nSuffix; if( p->xCond==0 || p->xCond(aBuf, nStem) ){ memcpy(&aBuf[nStem], p->zOutput, p->nOutput); *pnBuf = nStem + p->nOutput; ret = p - aRule; } } return ret; } #endif static int fts5PorterIsVowel(char c, int bYIsVowel){ return ( c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y') ); } static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){ int i; int bCons = bPrevCons; /* Scan for a vowel */ for(i=0; i<nStem; i++){ if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break; } /* Scan for a consonent */ for(i++; i<nStem; i++){ if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1; } return 0; } /* porter rule condition: (m > 0) */ static int fts5Porter_MGt0(char *zStem, int nStem){ return !!fts5PorterGobbleVC(zStem, nStem, 0); } /* porter rule condition: (m > 1) */ static int fts5Porter_MGt1(char *zStem, int nStem){ int n; n = fts5PorterGobbleVC(zStem, nStem, 0); if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){ return 1; } return 0; } /* porter rule condition: (m = 1) */ static int fts5Porter_MEq1(char *zStem, int nStem){ int n; n = fts5PorterGobbleVC(zStem, nStem, 0); if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){ return 1; } return 0; } /* porter rule condition: (*o) */ static int fts5Porter_Ostar(char *zStem, int nStem){ if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){ return 0; }else{ int i; int mask = 0; int bCons = 0; for(i=0; i<nStem; i++){ bCons = !fts5PorterIsVowel(zStem[i], bCons); assert( bCons==0 || bCons==1 ); mask = (mask << 1) + bCons; } return ((mask & 0x0007)==0x0005); } } /* porter rule condition: (m > 1 and (*S or *T)) */ static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){ assert( nStem>0 ); return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t') && fts5Porter_MGt1(zStem, nStem); } /* porter rule condition: (*v*) */ static int fts5Porter_Vowel(char *zStem, int nStem){ int i; for(i=0; i<nStem; i++){ if( fts5PorterIsVowel(zStem[i], i>0) ){ return 1; } } return 0; } /************************************************************************** *************************************************************************** ** GENERATED CODE STARTS HERE (mkportersteps.tcl) */ static int fts5PorterStep4(char *aBuf, int *pnBuf){ int ret = 0; int nBuf = *pnBuf; switch( aBuf[nBuf-2] ){ case 'a': if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){ if( fts5Porter_MGt1(aBuf, nBuf-2) ){ *pnBuf = nBuf - 2; } } break; case 'c': if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt1(aBuf, nBuf-4) ){ *pnBuf = nBuf - 4; } }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt1(aBuf, nBuf-4) ){ *pnBuf = nBuf - 4; } } break; case 'e': if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){ if( fts5Porter_MGt1(aBuf, nBuf-2) ){ *pnBuf = nBuf - 2; } } break; case 'i': if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){ if( fts5Porter_MGt1(aBuf, nBuf-2) ){ *pnBuf = nBuf - 2; } } break; case 'l': if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt1(aBuf, nBuf-4) ){ *pnBuf = nBuf - 4; } }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt1(aBuf, nBuf-4) ){ *pnBuf = nBuf - 4; } } break; case 'n': if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt1(aBuf, nBuf-5) ){ *pnBuf = nBuf - 5; } }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt1(aBuf, nBuf-4) ){ *pnBuf = nBuf - 4; } }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } } break; case 'o': if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){ if( fts5Porter_MGt1(aBuf, nBuf-2) ){ *pnBuf = nBuf - 2; } } break; case 's': if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } } break; case 't': if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } } break; case 'u': if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } } break; case 'v': if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } } break; case 'z': if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt1(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } } break; } return ret; } static int fts5PorterStep1B2(char *aBuf, int *pnBuf){ int ret = 0; int nBuf = *pnBuf; switch( aBuf[nBuf-2] ){ case 'a': if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){ memcpy(&aBuf[nBuf-2], "ate", 3); *pnBuf = nBuf - 2 + 3; ret = 1; } break; case 'b': if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){ memcpy(&aBuf[nBuf-2], "ble", 3); *pnBuf = nBuf - 2 + 3; ret = 1; } break; case 'i': if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){ memcpy(&aBuf[nBuf-2], "ize", 3); *pnBuf = nBuf - 2 + 3; ret = 1; } break; } return ret; } static int fts5PorterStep2(char *aBuf, int *pnBuf){ int ret = 0; int nBuf = *pnBuf; switch( aBuf[nBuf-2] ){ case 'a': if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ memcpy(&aBuf[nBuf-7], "ate", 3); *pnBuf = nBuf - 7 + 3; } }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){ if( fts5Porter_MGt0(aBuf, nBuf-6) ){ memcpy(&aBuf[nBuf-6], "tion", 4); *pnBuf = nBuf - 6 + 4; } } break; case 'c': if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ memcpy(&aBuf[nBuf-4], "ence", 4); *pnBuf = nBuf - 4 + 4; } }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ memcpy(&aBuf[nBuf-4], "ance", 4); *pnBuf = nBuf - 4 + 4; } } break; case 'e': if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ memcpy(&aBuf[nBuf-4], "ize", 3); *pnBuf = nBuf - 4 + 3; } } break; case 'g': if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ memcpy(&aBuf[nBuf-4], "log", 3); *pnBuf = nBuf - 4 + 3; } } break; case 'l': if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt0(aBuf, nBuf-3) ){ memcpy(&aBuf[nBuf-3], "ble", 3); *pnBuf = nBuf - 3 + 3; } }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ memcpy(&aBuf[nBuf-4], "al", 2); *pnBuf = nBuf - 4 + 2; } }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "ent", 3); *pnBuf = nBuf - 5 + 3; } }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt0(aBuf, nBuf-3) ){ memcpy(&aBuf[nBuf-3], "e", 1); *pnBuf = nBuf - 3 + 1; } }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "ous", 3); *pnBuf = nBuf - 5 + 3; } } break; case 'o': if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ memcpy(&aBuf[nBuf-7], "ize", 3); *pnBuf = nBuf - 7 + 3; } }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "ate", 3); *pnBuf = nBuf - 5 + 3; } }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ memcpy(&aBuf[nBuf-4], "ate", 3); *pnBuf = nBuf - 4 + 3; } } break; case 's': if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "al", 2); *pnBuf = nBuf - 5 + 2; } }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ memcpy(&aBuf[nBuf-7], "ive", 3); *pnBuf = nBuf - 7 + 3; } }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ memcpy(&aBuf[nBuf-7], "ful", 3); *pnBuf = nBuf - 7 + 3; } }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){ if( fts5Porter_MGt0(aBuf, nBuf-7) ){ memcpy(&aBuf[nBuf-7], "ous", 3); *pnBuf = nBuf - 7 + 3; } } break; case 't': if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "al", 2); *pnBuf = nBuf - 5 + 2; } }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "ive", 3); *pnBuf = nBuf - 5 + 3; } }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){ if( fts5Porter_MGt0(aBuf, nBuf-6) ){ memcpy(&aBuf[nBuf-6], "ble", 3); *pnBuf = nBuf - 6 + 3; } } break; } return ret; } static int fts5PorterStep3(char *aBuf, int *pnBuf){ int ret = 0; int nBuf = *pnBuf; switch( aBuf[nBuf-2] ){ case 'a': if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ memcpy(&aBuf[nBuf-4], "ic", 2); *pnBuf = nBuf - 4 + 2; } } break; case 's': if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){ if( fts5Porter_MGt0(aBuf, nBuf-4) ){ *pnBuf = nBuf - 4; } } break; case 't': if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "ic", 2); *pnBuf = nBuf - 5 + 2; } }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "ic", 2); *pnBuf = nBuf - 5 + 2; } } break; case 'u': if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt0(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; } } break; case 'v': if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ *pnBuf = nBuf - 5; } } break; case 'z': if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){ if( fts5Porter_MGt0(aBuf, nBuf-5) ){ memcpy(&aBuf[nBuf-5], "al", 2); *pnBuf = nBuf - 5 + 2; } } break; } return ret; } static int fts5PorterStep1B(char *aBuf, int *pnBuf){ int ret = 0; int nBuf = *pnBuf; switch( aBuf[nBuf-2] ){ case 'e': if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){ if( fts5Porter_MGt0(aBuf, nBuf-3) ){ memcpy(&aBuf[nBuf-3], "ee", 2); *pnBuf = nBuf - 3 + 2; } }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){ if( fts5Porter_Vowel(aBuf, nBuf-2) ){ *pnBuf = nBuf - 2; ret = 1; } } break; case 'n': if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){ if( fts5Porter_Vowel(aBuf, nBuf-3) ){ *pnBuf = nBuf - 3; ret = 1; } } break; } return ret; } /* ** GENERATED CODE ENDS HERE (mkportersteps.tcl) *************************************************************************** **************************************************************************/ static void fts5PorterStep1A(char *aBuf, int *pnBuf){ int nBuf = *pnBuf; if( aBuf[nBuf-1]=='s' ){ if( aBuf[nBuf-2]=='e' ){ if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s') || (nBuf>3 && aBuf[nBuf-3]=='i' ) ){ *pnBuf = nBuf-2; }else{ *pnBuf = nBuf-1; } } else if( aBuf[nBuf-2]!='s' ){ *pnBuf = nBuf-1; } } } static int fts5PorterCb( void *pCtx, int tflags, const char *pToken, int nToken, int iStart, int iEnd ){ PorterContext *p = (PorterContext*)pCtx; char *aBuf; int nBuf; if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through; aBuf = p->aBuf; nBuf = nToken; memcpy(aBuf, pToken, nBuf); /* Step 1. */ fts5PorterStep1A(aBuf, &nBuf); if( fts5PorterStep1B(aBuf, &nBuf) ){ if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){ char c = aBuf[nBuf-1]; if( fts5PorterIsVowel(c, 0)==0 && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2] ){ nBuf--; }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){ aBuf[nBuf++] = 'e'; } } } /* Step 1C. */ if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){ aBuf[nBuf-1] = 'i'; } /* Steps 2 through 4. */ fts5PorterStep2(aBuf, &nBuf); fts5PorterStep3(aBuf, &nBuf); fts5PorterStep4(aBuf, &nBuf); /* Step 5a. */ assert( nBuf>0 ); if( aBuf[nBuf-1]=='e' ){ if( fts5Porter_MGt1(aBuf, nBuf-1) || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1)) ){ nBuf--; } } /* Step 5b. */ if( nBuf>1 && aBuf[nBuf-1]=='l' && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1) ){ nBuf--; } return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd); pass_through: return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd); } /* ** Tokenize using the porter tokenizer. */ static int fts5PorterTokenize( Fts5Tokenizer *pTokenizer, void *pCtx, int flags, const char *pText, int nText, int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd) ){ PorterTokenizer *p = (PorterTokenizer*)pTokenizer; PorterContext sCtx; sCtx.xToken = xToken; sCtx.pCtx = pCtx; sCtx.aBuf = p->aBuf; return p->tokenizer.xTokenize( p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb ); } /* ** Register all built-in tokenizers with FTS5. */ static int sqlite3Fts5TokenizerInit(fts5_api *pApi){ struct BuiltinTokenizer { const char *zName; fts5_tokenizer x; } aBuiltin[] = { { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}}, { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }}, { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }}, }; int rc = SQLITE_OK; /* Return code */ int i; /* To iterate through builtin functions */ for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){ rc = pApi->xCreateTokenizer(pApi, aBuiltin[i].zName, (void*)pApi, &aBuiltin[i].x, 0 ); } return rc; } /* ** 2012 May 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** */ /* ** DO NOT EDIT THIS MACHINE GENERATED FILE. */ /* #include <assert.h> */ /* ** Return true if the argument corresponds to a unicode codepoint ** classified as either a letter or a number. Otherwise false. ** ** The results are undefined if the value passed to this function ** is less than zero. */ static int sqlite3Fts5UnicodeIsalnum(int c){ /* Each unsigned integer in the following array corresponds to a contiguous ** range of unicode codepoints that are not either letters or numbers (i.e. ** codepoints for which this function should return 0). ** ** The most significant 22 bits in each 32-bit value contain the first ** codepoint in the range. The least significant 10 bits are used to store ** the size of the range (always at least 1). In other words, the value ** ((C<<22) + N) represents a range of N codepoints starting with codepoint ** C. It is not possible to represent a range larger than 1023 codepoints ** using this format. */ static const unsigned int aEntry[] = { 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07, 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01, 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401, 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01, 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01, 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802, 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F, 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401, 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804, 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403, 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812, 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001, 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802, 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805, 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401, 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03, 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807, 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001, 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01, 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804, 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001, 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802, 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01, 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06, 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007, 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006, 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417, 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14, 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07, 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01, 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001, 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802, 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F, 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002, 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802, 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006, 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D, 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802, 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027, 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403, 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805, 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04, 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401, 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005, 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B, 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A, 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001, 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59, 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807, 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01, 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E, 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100, 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10, 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402, 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804, 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012, 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004, 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002, 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803, 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07, 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02, 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060, 0x380400F0, }; static const unsigned int aAscii[4] = { 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001, }; if( (unsigned int)c<128 ){ return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 ); }else if( (unsigned int)c<(1<<22) ){ unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; int iRes = 0; int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; int iLo = 0; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( key >= aEntry[iTest] ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( aEntry[0]<key ); assert( key>=aEntry[iRes] ); return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF))); } return 1; } /* ** If the argument is a codepoint corresponding to a lowercase letter ** in the ASCII range with a diacritic added, return the codepoint ** of the ASCII letter only. For example, if passed 235 - "LATIN ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER ** E"). The resuls of passing a codepoint that corresponds to an ** uppercase letter are undefined. */ static int fts5_remove_diacritic(int c){ unsigned short aDia[] = { 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995, 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286, 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732, 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336, 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928, 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504, 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62924, 63050, 63082, 63274, 63390, }; char aChar[] = { '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c', 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r', 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o', 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r', 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h', 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't', 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a', 'e', 'i', 'o', 'u', 'y', }; unsigned int key = (((unsigned int)c)<<3) | 0x00000007; int iRes = 0; int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1; int iLo = 0; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( key >= aDia[iTest] ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( key>=aDia[iRes] ); return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]); } /* ** Return true if the argument interpreted as a unicode codepoint ** is a diacritical modifier character. */ static int sqlite3Fts5UnicodeIsdiacritic(int c){ unsigned int mask0 = 0x08029FDF; unsigned int mask1 = 0x000361F8; if( c<768 || c>817 ) return 0; return (c < 768+32) ? (mask0 & (1 << (c-768))) : (mask1 & (1 << (c-768-32))); } /* ** Interpret the argument as a unicode codepoint. If the codepoint ** is an upper case character that has a lower case equivalent, ** return the codepoint corresponding to the lower case version. ** Otherwise, return a copy of the argument. ** ** The results are undefined if the value passed to this function ** is less than zero. */ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){ /* Each entry in the following array defines a rule for folding a range ** of codepoints to lower case. The rule applies to a range of nRange ** codepoints starting at codepoint iCode. ** ** If the least significant bit in flags is clear, then the rule applies ** to all nRange codepoints (i.e. all nRange codepoints are upper case and ** need to be folded). Or, if it is set, then the rule only applies to ** every second codepoint in the range, starting with codepoint C. ** ** The 7 most significant bits in flags are an index into the aiOff[] ** array. If a specific codepoint C does require folding, then its lower ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF). ** ** The contents of this array are generated by parsing the CaseFolding.txt ** file distributed as part of the "Unicode Character Database". See ** http://www.unicode.org for details. */ static const struct TableEntry { unsigned short iCode; unsigned char flags; unsigned char nRange; } aEntry[] = { {65, 14, 26}, {181, 64, 1}, {192, 14, 23}, {216, 14, 7}, {256, 1, 48}, {306, 1, 6}, {313, 1, 16}, {330, 1, 46}, {376, 116, 1}, {377, 1, 6}, {383, 104, 1}, {385, 50, 1}, {386, 1, 4}, {390, 44, 1}, {391, 0, 1}, {393, 42, 2}, {395, 0, 1}, {398, 32, 1}, {399, 38, 1}, {400, 40, 1}, {401, 0, 1}, {403, 42, 1}, {404, 46, 1}, {406, 52, 1}, {407, 48, 1}, {408, 0, 1}, {412, 52, 1}, {413, 54, 1}, {415, 56, 1}, {416, 1, 6}, {422, 60, 1}, {423, 0, 1}, {425, 60, 1}, {428, 0, 1}, {430, 60, 1}, {431, 0, 1}, {433, 58, 2}, {435, 1, 4}, {439, 62, 1}, {440, 0, 1}, {444, 0, 1}, {452, 2, 1}, {453, 0, 1}, {455, 2, 1}, {456, 0, 1}, {458, 2, 1}, {459, 1, 18}, {478, 1, 18}, {497, 2, 1}, {498, 1, 4}, {502, 122, 1}, {503, 134, 1}, {504, 1, 40}, {544, 110, 1}, {546, 1, 18}, {570, 70, 1}, {571, 0, 1}, {573, 108, 1}, {574, 68, 1}, {577, 0, 1}, {579, 106, 1}, {580, 28, 1}, {581, 30, 1}, {582, 1, 10}, {837, 36, 1}, {880, 1, 4}, {886, 0, 1}, {902, 18, 1}, {904, 16, 3}, {908, 26, 1}, {910, 24, 2}, {913, 14, 17}, {931, 14, 9}, {962, 0, 1}, {975, 4, 1}, {976, 140, 1}, {977, 142, 1}, {981, 146, 1}, {982, 144, 1}, {984, 1, 24}, {1008, 136, 1}, {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1}, {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1}, {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32}, {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1}, {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38}, {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1}, {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1}, {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6}, {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6}, {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8}, {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2}, {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1}, {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2}, {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2}, {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2}, {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1}, {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16}, {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47}, {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1}, {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1}, {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1}, {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2}, {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1}, {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14}, {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1}, {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1}, {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1}, {65313, 14, 26}, }; static const unsigned short aiOff[] = { 1, 2, 8, 15, 16, 26, 28, 32, 37, 38, 40, 48, 63, 64, 69, 71, 79, 80, 116, 202, 203, 205, 206, 207, 209, 210, 211, 213, 214, 217, 218, 219, 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721, 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 65514, 65521, 65527, 65528, 65529, }; int ret = c; assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 ); if( c<128 ){ if( c>='A' && c<='Z' ) ret = c + ('a' - 'A'); }else if( c<65536 ){ const struct TableEntry *p; int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; int iLo = 0; int iRes = -1; assert( c>aEntry[0].iCode ); while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; int cmp = (c - aEntry[iTest].iCode); if( cmp>=0 ){ iRes = iTest; iLo = iTest+1; }else{ iHi = iTest-1; } } assert( iRes>=0 && c>=aEntry[iRes].iCode ); p = &aEntry[iRes]; if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; assert( ret>0 ); } if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret); } else if( c>=66560 && c<66600 ){ ret = c + 40; } return ret; } /* ** 2015 May 30 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Routines for varint serialization and deserialization. */ /* #include "fts5Int.h" */ /* ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core. ** Except, this version does handle the single byte case that the core ** version depends on being handled before its function is called. */ static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){ u32 a,b; /* The 1-byte case. Overwhelmingly the most common. */ a = *p; /* a: p0 (unmasked) */ if (!(a&0x80)) { /* Values between 0 and 127 */ *v = a; return 1; } /* The 2-byte case */ p++; b = *p; /* b: p1 (unmasked) */ if (!(b&0x80)) { /* Values between 128 and 16383 */ a &= 0x7f; a = a<<7; *v = a | b; return 2; } /* The 3-byte case */ p++; a = a<<14; a |= *p; /* a: p0<<14 | p2 (unmasked) */ if (!(a&0x80)) { /* Values between 16384 and 2097151 */ a &= (0x7f<<14)|(0x7f); b &= 0x7f; b = b<<7; *v = a | b; return 3; } /* A 32-bit varint is used to store size information in btrees. ** Objects are rarely larger than 2MiB limit of a 3-byte varint. ** A 3-byte varint is sufficient, for example, to record the size ** of a 1048569-byte BLOB or string. ** ** We only unroll the first 1-, 2-, and 3- byte cases. The very ** rare larger cases can be handled by the slower 64-bit varint ** routine. */ { u64 v64; u8 n; p -= 2; n = sqlite3Fts5GetVarint(p, &v64); *v = (u32)v64; assert( n>3 && n<=9 ); return n; } } /* ** Bitmasks used by sqlite3GetVarint(). These precomputed constants ** are defined here rather than simply putting the constant expressions ** inline in order to work around bugs in the RVT compiler. ** ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f ** ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 */ #define SLOT_2_0 0x001fc07f #define SLOT_4_2_0 0xf01fc07f /* ** Read a 64-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read. The value is stored in *v. */ static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){ u32 a,b,s; a = *p; /* a: p0 (unmasked) */ if (!(a&0x80)) { *v = a; return 1; } p++; b = *p; /* b: p1 (unmasked) */ if (!(b&0x80)) { a &= 0x7f; a = a<<7; a |= b; *v = a; return 2; } /* Verify that constants are precomputed correctly */ assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) ); assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) ); p++; a = a<<14; a |= *p; /* a: p0<<14 | p2 (unmasked) */ if (!(a&0x80)) { a &= SLOT_2_0; b &= 0x7f; b = b<<7; a |= b; *v = a; return 3; } /* CSE1 from below */ a &= SLOT_2_0; p++; b = b<<14; b |= *p; /* b: p1<<14 | p3 (unmasked) */ if (!(b&0x80)) { b &= SLOT_2_0; /* moved CSE1 up */ /* a &= (0x7f<<14)|(0x7f); */ a = a<<7; a |= b; *v = a; return 4; } /* a: p0<<14 | p2 (masked) */ /* b: p1<<14 | p3 (unmasked) */ /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ /* moved CSE1 up */ /* a &= (0x7f<<14)|(0x7f); */ b &= SLOT_2_0; s = a; /* s: p0<<14 | p2 (masked) */ p++; a = a<<14; a |= *p; /* a: p0<<28 | p2<<14 | p4 (unmasked) */ if (!(a&0x80)) { /* we can skip these cause they were (effectively) done above in calc'ing s */ /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ /* b &= (0x7f<<14)|(0x7f); */ b = b<<7; a |= b; s = s>>18; *v = ((u64)s)<<32 | a; return 5; } /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ s = s<<7; s |= b; /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ p++; b = b<<14; b |= *p; /* b: p1<<28 | p3<<14 | p5 (unmasked) */ if (!(b&0x80)) { /* we can skip this cause it was (effectively) done above in calc'ing s */ /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ a &= SLOT_2_0; a = a<<7; a |= b; s = s>>18; *v = ((u64)s)<<32 | a; return 6; } p++; a = a<<14; a |= *p; /* a: p2<<28 | p4<<14 | p6 (unmasked) */ if (!(a&0x80)) { a &= SLOT_4_2_0; b &= SLOT_2_0; b = b<<7; a |= b; s = s>>11; *v = ((u64)s)<<32 | a; return 7; } /* CSE2 from below */ a &= SLOT_2_0; p++; b = b<<14; b |= *p; /* b: p3<<28 | p5<<14 | p7 (unmasked) */ if (!(b&0x80)) { b &= SLOT_4_2_0; /* moved CSE2 up */ /* a &= (0x7f<<14)|(0x7f); */ a = a<<7; a |= b; s = s>>4; *v = ((u64)s)<<32 | a; return 8; } p++; a = a<<15; a |= *p; /* a: p4<<29 | p6<<15 | p8 (unmasked) */ /* moved CSE2 up */ /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ b &= SLOT_2_0; b = b<<8; a |= b; s = s<<4; b = p[-4]; b &= 0x7f; b = b>>3; s |= b; *v = ((u64)s)<<32 | a; return 9; } /* ** The variable-length integer encoding is as follows: ** ** KEY: ** A = 0xxxxxxx 7 bits of data and one flag bit ** B = 1xxxxxxx 7 bits of data and one flag bit ** C = xxxxxxxx 8 bits of data ** ** 7 bits - A ** 14 bits - BA ** 21 bits - BBA ** 28 bits - BBBA ** 35 bits - BBBBA ** 42 bits - BBBBBA ** 49 bits - BBBBBBA ** 56 bits - BBBBBBBA ** 64 bits - BBBBBBBBC */ #ifdef SQLITE_NOINLINE # define FTS5_NOINLINE SQLITE_NOINLINE #else # define FTS5_NOINLINE #endif /* ** Write a 64-bit variable-length integer to memory starting at p[0]. ** The length of data write will be between 1 and 9 bytes. The number ** of bytes written is returned. ** ** A variable-length integer consists of the lower 7 bits of each byte ** for all bytes that have the 8th bit set and one byte with the 8th ** bit clear. Except, if we get to the 9th byte, it stores the full ** 8 bits and is the last byte. */ static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){ int i, j, n; u8 buf[10]; if( v & (((u64)0xff000000)<<32) ){ p[8] = (u8)v; v >>= 8; for(i=7; i>=0; i--){ p[i] = (u8)((v & 0x7f) | 0x80); v >>= 7; } return 9; } n = 0; do{ buf[n++] = (u8)((v & 0x7f) | 0x80); v >>= 7; }while( v!=0 ); buf[0] &= 0x7f; assert( n<=9 ); for(i=0, j=n-1; j>=0; j--, i++){ p[i] = buf[j]; } return n; } static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){ if( v<=0x7f ){ p[0] = v&0x7f; return 1; } if( v<=0x3fff ){ p[0] = ((v>>7)&0x7f)|0x80; p[1] = v&0x7f; return 2; } return fts5PutVarint64(p,v); } static int sqlite3Fts5GetVarintLen(u32 iVal){ #if 0 if( iVal<(1 << 7 ) ) return 1; #endif assert( iVal>=(1 << 7) ); if( iVal<(1 << 14) ) return 2; if( iVal<(1 << 21) ) return 3; if( iVal<(1 << 28) ) return 4; return 5; } /* ** 2015 May 08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This is an SQLite virtual table module implementing direct access to an ** existing FTS5 index. The module may create several different types of ** tables: ** ** col: ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col)); ** ** One row for each term/column combination. The value of $doc is set to ** the number of fts5 rows that contain at least one instance of term ** $term within column $col. Field $cnt is set to the total number of ** instances of term $term in column $col (in any row of the fts5 table). ** ** row: ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term)); ** ** One row for each term in the database. The value of $doc is set to ** the number of fts5 rows that contain at least one instance of term ** $term. Field $cnt is set to the total number of instances of term ** $term in the database. */ /* #include "fts5Int.h" */ typedef struct Fts5VocabTable Fts5VocabTable; typedef struct Fts5VocabCursor Fts5VocabCursor; struct Fts5VocabTable { sqlite3_vtab base; char *zFts5Tbl; /* Name of fts5 table */ char *zFts5Db; /* Db containing fts5 table */ sqlite3 *db; /* Database handle */ Fts5Global *pGlobal; /* FTS5 global object for this database */ int eType; /* FTS5_VOCAB_COL or ROW */ }; struct Fts5VocabCursor { sqlite3_vtab_cursor base; sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */ Fts5Index *pIndex; /* Associated FTS5 index */ int bEof; /* True if this cursor is at EOF */ Fts5IndexIter *pIter; /* Term/rowid iterator object */ int nLeTerm; /* Size of zLeTerm in bytes */ char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */ /* These are used by 'col' tables only */ Fts5Config *pConfig; /* Fts5 table configuration */ int iCol; i64 *aCnt; i64 *aDoc; /* Output values used by 'row' and 'col' tables */ i64 rowid; /* This table's current rowid value */ Fts5Buffer term; /* Current value of 'term' column */ }; #define FTS5_VOCAB_COL 0 #define FTS5_VOCAB_ROW 1 #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt" #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt" /* ** Bits for the mask used as the idxNum value by xBestIndex/xFilter. */ #define FTS5_VOCAB_TERM_EQ 0x01 #define FTS5_VOCAB_TERM_GE 0x02 #define FTS5_VOCAB_TERM_LE 0x04 /* ** Translate a string containing an fts5vocab table type to an ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message ** and return SQLITE_ERROR. */ static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){ int rc = SQLITE_OK; char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1); if( rc==SQLITE_OK ){ sqlite3Fts5Dequote(zCopy); if( sqlite3_stricmp(zCopy, "col")==0 ){ *peType = FTS5_VOCAB_COL; }else if( sqlite3_stricmp(zCopy, "row")==0 ){ *peType = FTS5_VOCAB_ROW; }else { *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy); rc = SQLITE_ERROR; } sqlite3_free(zCopy); } return rc; } /* ** The xDisconnect() virtual table method. */ static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){ Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab; sqlite3_free(pTab); return SQLITE_OK; } /* ** The xDestroy() virtual table method. */ static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){ Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab; sqlite3_free(pTab); return SQLITE_OK; } /* ** This function is the implementation of both the xConnect and xCreate ** methods of the FTS3 virtual table. ** ** The argv[] array contains the following: ** ** argv[0] -> module name ("fts5vocab") ** argv[1] -> database name ** argv[2] -> table name ** ** then: ** ** argv[3] -> name of fts5 table ** argv[4] -> type of fts5vocab table ** ** or, for tables in the TEMP schema only. ** ** argv[3] -> name of fts5 tables database ** argv[4] -> name of fts5 table ** argv[5] -> type of fts5vocab table */ static int fts5VocabInitVtab( sqlite3 *db, /* The SQLite database connection */ void *pAux, /* Pointer to Fts5Global object */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ char **pzErr /* Write any error message here */ ){ const char *azSchema[] = { "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")", "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")" }; Fts5VocabTable *pRet = 0; int rc = SQLITE_OK; /* Return code */ int bDb; bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0); if( argc!=5 && bDb==0 ){ *pzErr = sqlite3_mprintf("wrong number of vtable arguments"); rc = SQLITE_ERROR; }else{ int nByte; /* Bytes of space to allocate */ const char *zDb = bDb ? argv[3] : argv[1]; const char *zTab = bDb ? argv[4] : argv[3]; const char *zType = bDb ? argv[5] : argv[4]; int nDb = (int)strlen(zDb)+1; int nTab = (int)strlen(zTab)+1; int eType = 0; rc = fts5VocabTableType(zType, pzErr, &eType); if( rc==SQLITE_OK ){ assert( eType>=0 && eType<ArraySize(azSchema) ); rc = sqlite3_declare_vtab(db, azSchema[eType]); } nByte = sizeof(Fts5VocabTable) + nDb + nTab; pRet = sqlite3Fts5MallocZero(&rc, nByte); if( pRet ){ pRet->pGlobal = (Fts5Global*)pAux; pRet->eType = eType; pRet->db = db; pRet->zFts5Tbl = (char*)&pRet[1]; pRet->zFts5Db = &pRet->zFts5Tbl[nTab]; memcpy(pRet->zFts5Tbl, zTab, nTab); memcpy(pRet->zFts5Db, zDb, nDb); sqlite3Fts5Dequote(pRet->zFts5Tbl); sqlite3Fts5Dequote(pRet->zFts5Db); } } *ppVTab = (sqlite3_vtab*)pRet; return rc; } /* ** The xConnect() and xCreate() methods for the virtual table. All the ** work is done in function fts5VocabInitVtab(). */ static int fts5VocabConnectMethod( sqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr); } static int fts5VocabCreateMethod( sqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ char **pzErr /* OUT: sqlite3_malloc'd error message */ ){ return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr); } /* ** Implementation of the xBestIndex method. */ static int fts5VocabBestIndexMethod( sqlite3_vtab *pUnused, sqlite3_index_info *pInfo ){ int i; int iTermEq = -1; int iTermGe = -1; int iTermLe = -1; int idxNum = 0; int nArg = 0; UNUSED_PARAM(pUnused); for(i=0; i<pInfo->nConstraint; i++){ struct sqlite3_index_constraint *p = &pInfo->aConstraint[i]; if( p->usable==0 ) continue; if( p->iColumn==0 ){ /* term column */ if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i; if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i; if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i; if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i; if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i; } } if( iTermEq>=0 ){ idxNum |= FTS5_VOCAB_TERM_EQ; pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg; pInfo->estimatedCost = 100; }else{ pInfo->estimatedCost = 1000000; if( iTermGe>=0 ){ idxNum |= FTS5_VOCAB_TERM_GE; pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg; pInfo->estimatedCost = pInfo->estimatedCost / 2; } if( iTermLe>=0 ){ idxNum |= FTS5_VOCAB_TERM_LE; pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg; pInfo->estimatedCost = pInfo->estimatedCost / 2; } } /* This virtual table always delivers results in ascending order of ** the "term" column (column 0). So if the user has requested this ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the ** sqlite3_index_info.orderByConsumed flag to tell the core the results ** are already in sorted order. */ if( pInfo->nOrderBy==1 && pInfo->aOrderBy[0].iColumn==0 && pInfo->aOrderBy[0].desc==0 ){ pInfo->orderByConsumed = 1; } pInfo->idxNum = idxNum; return SQLITE_OK; } /* ** Implementation of xOpen method. */ static int fts5VocabOpenMethod( sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr ){ Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab; Fts5Index *pIndex = 0; Fts5Config *pConfig = 0; Fts5VocabCursor *pCsr = 0; int rc = SQLITE_OK; sqlite3_stmt *pStmt = 0; char *zSql = 0; zSql = sqlite3Fts5Mprintf(&rc, "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'", pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl ); if( zSql ){ rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); } sqlite3_free(zSql); assert( rc==SQLITE_OK || pStmt==0 ); if( rc==SQLITE_ERROR ) rc = SQLITE_OK; if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ i64 iId = sqlite3_column_int64(pStmt, 0); pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig); } if( rc==SQLITE_OK && pIndex==0 ){ rc = sqlite3_finalize(pStmt); pStmt = 0; if( rc==SQLITE_OK ){ pVTab->zErrMsg = sqlite3_mprintf( "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl ); rc = SQLITE_ERROR; } } if( rc==SQLITE_OK ){ int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor); pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte); } if( pCsr ){ pCsr->pIndex = pIndex; pCsr->pStmt = pStmt; pCsr->pConfig = pConfig; pCsr->aCnt = (i64*)&pCsr[1]; pCsr->aDoc = &pCsr->aCnt[pConfig->nCol]; }else{ sqlite3_finalize(pStmt); } *ppCsr = (sqlite3_vtab_cursor*)pCsr; return rc; } static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){ pCsr->rowid = 0; sqlite3Fts5IterClose(pCsr->pIter); pCsr->pIter = 0; sqlite3_free(pCsr->zLeTerm); pCsr->nLeTerm = -1; pCsr->zLeTerm = 0; } /* ** Close the cursor. For additional information see the documentation ** on the xClose method of the virtual table interface. */ static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; fts5VocabResetCursor(pCsr); sqlite3Fts5BufferFree(&pCsr->term); sqlite3_finalize(pCsr->pStmt); sqlite3_free(pCsr); return SQLITE_OK; } /* ** Advance the cursor to the next row in the table. */ static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab; int rc = SQLITE_OK; int nCol = pCsr->pConfig->nCol; pCsr->rowid++; if( pTab->eType==FTS5_VOCAB_COL ){ for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){ if( pCsr->aDoc[pCsr->iCol] ) break; } } if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){ if( sqlite3Fts5IterEof(pCsr->pIter) ){ pCsr->bEof = 1; }else{ const char *zTerm; int nTerm; zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm); if( pCsr->nLeTerm>=0 ){ int nCmp = MIN(nTerm, pCsr->nLeTerm); int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp); if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){ pCsr->bEof = 1; return SQLITE_OK; } } sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm); memset(pCsr->aCnt, 0, nCol * sizeof(i64)); memset(pCsr->aDoc, 0, nCol * sizeof(i64)); pCsr->iCol = 0; assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW ); while( rc==SQLITE_OK ){ const u8 *pPos; int nPos; /* Position list */ i64 iPos = 0; /* 64-bit position read from poslist */ int iOff = 0; /* Current offset within position list */ pPos = pCsr->pIter->pData; nPos = pCsr->pIter->nData; switch( pCsr->pConfig->eDetail ){ case FTS5_DETAIL_FULL: pPos = pCsr->pIter->pData; nPos = pCsr->pIter->nData; if( pTab->eType==FTS5_VOCAB_ROW ){ while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){ pCsr->aCnt[0]++; } pCsr->aDoc[0]++; }else{ int iCol = -1; while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){ int ii = FTS5_POS2COLUMN(iPos); pCsr->aCnt[ii]++; if( iCol!=ii ){ if( ii>=nCol ){ rc = FTS5_CORRUPT; break; } pCsr->aDoc[ii]++; iCol = ii; } } } break; case FTS5_DETAIL_COLUMNS: if( pTab->eType==FTS5_VOCAB_ROW ){ pCsr->aDoc[0]++; }else{ while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){ assert_nc( iPos>=0 && iPos<nCol ); if( iPos>=nCol ){ rc = FTS5_CORRUPT; break; } pCsr->aDoc[iPos]++; } } break; default: assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE ); pCsr->aDoc[0]++; break; } if( rc==SQLITE_OK ){ rc = sqlite3Fts5IterNextScan(pCsr->pIter); } if( rc==SQLITE_OK ){ zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm); if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){ break; } if( sqlite3Fts5IterEof(pCsr->pIter) ) break; } } } } if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){ while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++; assert( pCsr->iCol<pCsr->pConfig->nCol ); } return rc; } /* ** This is the xFilter implementation for the virtual table. */ static int fts5VocabFilterMethod( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *zUnused, /* Unused */ int nUnused, /* Number of elements in apVal */ sqlite3_value **apVal /* Arguments for the indexing scheme */ ){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; int rc = SQLITE_OK; int iVal = 0; int f = FTS5INDEX_QUERY_SCAN; const char *zTerm = 0; int nTerm = 0; sqlite3_value *pEq = 0; sqlite3_value *pGe = 0; sqlite3_value *pLe = 0; UNUSED_PARAM2(zUnused, nUnused); fts5VocabResetCursor(pCsr); if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++]; if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++]; if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++]; if( pEq ){ zTerm = (const char *)sqlite3_value_text(pEq); nTerm = sqlite3_value_bytes(pEq); f = 0; }else{ if( pGe ){ zTerm = (const char *)sqlite3_value_text(pGe); nTerm = sqlite3_value_bytes(pGe); } if( pLe ){ const char *zCopy = (const char *)sqlite3_value_text(pLe); pCsr->nLeTerm = sqlite3_value_bytes(pLe); pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1); if( pCsr->zLeTerm==0 ){ rc = SQLITE_NOMEM; }else{ memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1); } } } if( rc==SQLITE_OK ){ rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter); } if( rc==SQLITE_OK ){ rc = fts5VocabNextMethod(pCursor); } return rc; } /* ** This is the xEof method of the virtual table. SQLite calls this ** routine to find out if it has reached the end of a result set. */ static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; return pCsr->bEof; } static int fts5VocabColumnMethod( sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; int eDetail = pCsr->pConfig->eDetail; int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType; i64 iVal = 0; if( iCol==0 ){ sqlite3_result_text( pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT ); }else if( eType==FTS5_VOCAB_COL ){ assert( iCol==1 || iCol==2 || iCol==3 ); if( iCol==1 ){ if( eDetail!=FTS5_DETAIL_NONE ){ const char *z = pCsr->pConfig->azCol[pCsr->iCol]; sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC); } }else if( iCol==2 ){ iVal = pCsr->aDoc[pCsr->iCol]; }else{ iVal = pCsr->aCnt[pCsr->iCol]; } }else{ assert( iCol==1 || iCol==2 ); if( iCol==1 ){ iVal = pCsr->aDoc[0]; }else{ iVal = pCsr->aCnt[0]; } } if( iVal>0 ) sqlite3_result_int64(pCtx, iVal); return SQLITE_OK; } /* ** This is the xRowid method. The SQLite core calls this routine to ** retrieve the rowid for the current row of the result set. The ** rowid should be written to *pRowid. */ static int fts5VocabRowidMethod( sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid ){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; *pRowid = pCsr->rowid; return SQLITE_OK; } static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){ static const sqlite3_module fts5Vocab = { /* iVersion */ 2, /* xCreate */ fts5VocabCreateMethod, /* xConnect */ fts5VocabConnectMethod, /* xBestIndex */ fts5VocabBestIndexMethod, /* xDisconnect */ fts5VocabDisconnectMethod, /* xDestroy */ fts5VocabDestroyMethod, /* xOpen */ fts5VocabOpenMethod, /* xClose */ fts5VocabCloseMethod, /* xFilter */ fts5VocabFilterMethod, /* xNext */ fts5VocabNextMethod, /* xEof */ fts5VocabEofMethod, /* xColumn */ fts5VocabColumnMethod, /* xRowid */ fts5VocabRowidMethod, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindFunction */ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ 0, /* xRollbackTo */ 0, }; void *p = (void*)pGlobal; return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0); } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */ /************** End of fts5.c ************************************************/ #else // USE_LIBSQLITE3 // If users really want to link against the system sqlite3 we // need to make this file a noop. #endif ����������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/error_test.go���������������������������������������0000644�0610621�0607500�00000012524�13172163427�025124� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 import ( "database/sql" "io/ioutil" "os" "path" "testing" ) func TestSimpleError(t *testing.T) { e := ErrError.Error() if e != "SQL logic error or missing database" { t.Error("wrong error code:" + e) } } func TestCorruptDbErrors(t *testing.T) { dirName, err := ioutil.TempDir("", "sqlite3") if err != nil { t.Fatal(err) } defer os.RemoveAll(dirName) dbFileName := path.Join(dirName, "test.db") f, err := os.Create(dbFileName) if err != nil { t.Error(err) } f.Write([]byte{1, 2, 3, 4, 5}) f.Close() db, err := sql.Open("sqlite3", dbFileName) if err == nil { _, err = db.Exec("drop table foo") } sqliteErr := err.(Error) if sqliteErr.Code != ErrNotADB { t.Error("wrong error code for corrupted DB") } if err.Error() == "" { t.Error("wrong error string for corrupted DB") } db.Close() } func TestSqlLogicErrors(t *testing.T) { dirName, err := ioutil.TempDir("", "sqlite3") if err != nil { t.Fatal(err) } defer os.RemoveAll(dirName) dbFileName := path.Join(dirName, "test.db") db, err := sql.Open("sqlite3", dbFileName) if err != nil { t.Error(err) } defer db.Close() _, err = db.Exec("CREATE TABLE Foo (id INTEGER PRIMARY KEY)") if err != nil { t.Error(err) } const expectedErr = "table Foo already exists" _, err = db.Exec("CREATE TABLE Foo (id INTEGER PRIMARY KEY)") if err.Error() != expectedErr { t.Errorf("Unexpected error: %s, expected %s", err.Error(), expectedErr) } } func TestExtendedErrorCodes_ForeignKey(t *testing.T) { dirName, err := ioutil.TempDir("", "sqlite3-err") if err != nil { t.Fatal(err) } defer os.RemoveAll(dirName) dbFileName := path.Join(dirName, "test.db") db, err := sql.Open("sqlite3", dbFileName) if err != nil { t.Error(err) } defer db.Close() _, err = db.Exec("PRAGMA foreign_keys=ON;") if err != nil { t.Errorf("PRAGMA foreign_keys=ON: %v", err) } _, err = db.Exec(`CREATE TABLE Foo ( id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER NOT NULL, ref INTEGER NULL REFERENCES Foo (id), UNIQUE(value) );`) if err != nil { t.Error(err) } _, err = db.Exec("INSERT INTO Foo (ref, value) VALUES (100, 100);") if err == nil { t.Error("No error!") } else { sqliteErr := err.(Error) if sqliteErr.Code != ErrConstraint { t.Errorf("Wrong basic error code: %d != %d", sqliteErr.Code, ErrConstraint) } if sqliteErr.ExtendedCode != ErrConstraintForeignKey { t.Errorf("Wrong extended error code: %d != %d", sqliteErr.ExtendedCode, ErrConstraintForeignKey) } } } func TestExtendedErrorCodes_NotNull(t *testing.T) { dirName, err := ioutil.TempDir("", "sqlite3-err") if err != nil { t.Fatal(err) } defer os.RemoveAll(dirName) dbFileName := path.Join(dirName, "test.db") db, err := sql.Open("sqlite3", dbFileName) if err != nil { t.Error(err) } defer db.Close() _, err = db.Exec("PRAGMA foreign_keys=ON;") if err != nil { t.Errorf("PRAGMA foreign_keys=ON: %v", err) } _, err = db.Exec(`CREATE TABLE Foo ( id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER NOT NULL, ref INTEGER NULL REFERENCES Foo (id), UNIQUE(value) );`) if err != nil { t.Error(err) } res, err := db.Exec("INSERT INTO Foo (value) VALUES (100);") if err != nil { t.Fatalf("Creating first row: %v", err) } id, err := res.LastInsertId() if err != nil { t.Fatalf("Retrieving last insert id: %v", err) } _, err = db.Exec("INSERT INTO Foo (ref) VALUES (?);", id) if err == nil { t.Error("No error!") } else { sqliteErr := err.(Error) if sqliteErr.Code != ErrConstraint { t.Errorf("Wrong basic error code: %d != %d", sqliteErr.Code, ErrConstraint) } if sqliteErr.ExtendedCode != ErrConstraintNotNull { t.Errorf("Wrong extended error code: %d != %d", sqliteErr.ExtendedCode, ErrConstraintNotNull) } } } func TestExtendedErrorCodes_Unique(t *testing.T) { dirName, err := ioutil.TempDir("", "sqlite3-err") if err != nil { t.Fatal(err) } defer os.RemoveAll(dirName) dbFileName := path.Join(dirName, "test.db") db, err := sql.Open("sqlite3", dbFileName) if err != nil { t.Error(err) } defer db.Close() _, err = db.Exec("PRAGMA foreign_keys=ON;") if err != nil { t.Errorf("PRAGMA foreign_keys=ON: %v", err) } _, err = db.Exec(`CREATE TABLE Foo ( id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER NOT NULL, ref INTEGER NULL REFERENCES Foo (id), UNIQUE(value) );`) if err != nil { t.Error(err) } res, err := db.Exec("INSERT INTO Foo (value) VALUES (100);") if err != nil { t.Fatalf("Creating first row: %v", err) } id, err := res.LastInsertId() if err != nil { t.Fatalf("Retrieving last insert id: %v", err) } _, err = db.Exec("INSERT INTO Foo (ref, value) VALUES (?, 100);", id) if err == nil { t.Error("No error!") } else { sqliteErr := err.(Error) if sqliteErr.Code != ErrConstraint { t.Errorf("Wrong basic error code: %d != %d", sqliteErr.Code, ErrConstraint) } if sqliteErr.ExtendedCode != ErrConstraintUnique { t.Errorf("Wrong extended error code: %d != %d", sqliteErr.ExtendedCode, ErrConstraintUnique) } extended := sqliteErr.Code.Extend(3).Error() expected := "constraint failed" if extended != expected { t.Errorf("Wrong basic error code: %q != %q", extended, expected) } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/error.go��������������������������������������������0000644�0610621�0607500�00000013214�13172163427�024062� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 import "C" // ErrNo inherit errno. type ErrNo int // ErrNoMask is mask code. const ErrNoMask C.int = 0xff // ErrNoExtended is extended errno. type ErrNoExtended int // Error implement sqlite error code. type Error struct { Code ErrNo /* The error code returned by SQLite */ ExtendedCode ErrNoExtended /* The extended error code returned by SQLite */ err string /* The error string returned by sqlite3_errmsg(), this usually contains more specific details. */ } // result codes from http://www.sqlite.org/c3ref/c_abort.html var ( ErrError = ErrNo(1) /* SQL error or missing database */ ErrInternal = ErrNo(2) /* Internal logic error in SQLite */ ErrPerm = ErrNo(3) /* Access permission denied */ ErrAbort = ErrNo(4) /* Callback routine requested an abort */ ErrBusy = ErrNo(5) /* The database file is locked */ ErrLocked = ErrNo(6) /* A table in the database is locked */ ErrNomem = ErrNo(7) /* A malloc() failed */ ErrReadonly = ErrNo(8) /* Attempt to write a readonly database */ ErrInterrupt = ErrNo(9) /* Operation terminated by sqlite3_interrupt() */ ErrIoErr = ErrNo(10) /* Some kind of disk I/O error occurred */ ErrCorrupt = ErrNo(11) /* The database disk image is malformed */ ErrNotFound = ErrNo(12) /* Unknown opcode in sqlite3_file_control() */ ErrFull = ErrNo(13) /* Insertion failed because database is full */ ErrCantOpen = ErrNo(14) /* Unable to open the database file */ ErrProtocol = ErrNo(15) /* Database lock protocol error */ ErrEmpty = ErrNo(16) /* Database is empty */ ErrSchema = ErrNo(17) /* The database schema changed */ ErrTooBig = ErrNo(18) /* String or BLOB exceeds size limit */ ErrConstraint = ErrNo(19) /* Abort due to constraint violation */ ErrMismatch = ErrNo(20) /* Data type mismatch */ ErrMisuse = ErrNo(21) /* Library used incorrectly */ ErrNoLFS = ErrNo(22) /* Uses OS features not supported on host */ ErrAuth = ErrNo(23) /* Authorization denied */ ErrFormat = ErrNo(24) /* Auxiliary database format error */ ErrRange = ErrNo(25) /* 2nd parameter to sqlite3_bind out of range */ ErrNotADB = ErrNo(26) /* File opened that is not a database file */ ErrNotice = ErrNo(27) /* Notifications from sqlite3_log() */ ErrWarning = ErrNo(28) /* Warnings from sqlite3_log() */ ) // Error return error message from errno. func (err ErrNo) Error() string { return Error{Code: err}.Error() } // Extend return extended errno. func (err ErrNo) Extend(by int) ErrNoExtended { return ErrNoExtended(int(err) | (by << 8)) } // Error return error message that is extended code. func (err ErrNoExtended) Error() string { return Error{Code: ErrNo(C.int(err) & ErrNoMask), ExtendedCode: err}.Error() } func (err Error) Error() string { if err.err != "" { return err.err } return errorString(err) } // result codes from http://www.sqlite.org/c3ref/c_abort_rollback.html var ( ErrIoErrRead = ErrIoErr.Extend(1) ErrIoErrShortRead = ErrIoErr.Extend(2) ErrIoErrWrite = ErrIoErr.Extend(3) ErrIoErrFsync = ErrIoErr.Extend(4) ErrIoErrDirFsync = ErrIoErr.Extend(5) ErrIoErrTruncate = ErrIoErr.Extend(6) ErrIoErrFstat = ErrIoErr.Extend(7) ErrIoErrUnlock = ErrIoErr.Extend(8) ErrIoErrRDlock = ErrIoErr.Extend(9) ErrIoErrDelete = ErrIoErr.Extend(10) ErrIoErrBlocked = ErrIoErr.Extend(11) ErrIoErrNoMem = ErrIoErr.Extend(12) ErrIoErrAccess = ErrIoErr.Extend(13) ErrIoErrCheckReservedLock = ErrIoErr.Extend(14) ErrIoErrLock = ErrIoErr.Extend(15) ErrIoErrClose = ErrIoErr.Extend(16) ErrIoErrDirClose = ErrIoErr.Extend(17) ErrIoErrSHMOpen = ErrIoErr.Extend(18) ErrIoErrSHMSize = ErrIoErr.Extend(19) ErrIoErrSHMLock = ErrIoErr.Extend(20) ErrIoErrSHMMap = ErrIoErr.Extend(21) ErrIoErrSeek = ErrIoErr.Extend(22) ErrIoErrDeleteNoent = ErrIoErr.Extend(23) ErrIoErrMMap = ErrIoErr.Extend(24) ErrIoErrGetTempPath = ErrIoErr.Extend(25) ErrIoErrConvPath = ErrIoErr.Extend(26) ErrLockedSharedCache = ErrLocked.Extend(1) ErrBusyRecovery = ErrBusy.Extend(1) ErrBusySnapshot = ErrBusy.Extend(2) ErrCantOpenNoTempDir = ErrCantOpen.Extend(1) ErrCantOpenIsDir = ErrCantOpen.Extend(2) ErrCantOpenFullPath = ErrCantOpen.Extend(3) ErrCantOpenConvPath = ErrCantOpen.Extend(4) ErrCorruptVTab = ErrCorrupt.Extend(1) ErrReadonlyRecovery = ErrReadonly.Extend(1) ErrReadonlyCantLock = ErrReadonly.Extend(2) ErrReadonlyRollback = ErrReadonly.Extend(3) ErrReadonlyDbMoved = ErrReadonly.Extend(4) ErrAbortRollback = ErrAbort.Extend(2) ErrConstraintCheck = ErrConstraint.Extend(1) ErrConstraintCommitHook = ErrConstraint.Extend(2) ErrConstraintForeignKey = ErrConstraint.Extend(3) ErrConstraintFunction = ErrConstraint.Extend(4) ErrConstraintNotNull = ErrConstraint.Extend(5) ErrConstraintPrimaryKey = ErrConstraint.Extend(6) ErrConstraintTrigger = ErrConstraint.Extend(7) ErrConstraintUnique = ErrConstraint.Extend(8) ErrConstraintVTab = ErrConstraint.Extend(9) ErrConstraintRowID = ErrConstraint.Extend(10) ErrNoticeRecoverWAL = ErrNotice.Extend(1) ErrNoticeRecoverRollback = ErrNotice.Extend(2) ErrWarningAutoIndex = ErrWarning.Extend(1) ) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/doc.go����������������������������������������������0000644�0610621�0607500�00000006153�13172163427�023502� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Package sqlite3 provides interface to SQLite3 databases. This works as a driver for database/sql. Installation go get github.com/mattn/go-sqlite3 Supported Types Currently, go-sqlite3 supports the following data types. +------------------------------+ |go | sqlite3 | |----------|-------------------| |nil | null | |int | integer | |int64 | integer | |float64 | float | |bool | integer | |[]byte | blob | |string | text | |time.Time | timestamp/datetime| +------------------------------+ SQLite3 Extension You can write your own extension module for sqlite3. For example, below is an extension for a Regexp matcher operation. #include <pcre.h> #include <string.h> #include <stdio.h> #include <sqlite3ext.h> SQLITE_EXTENSION_INIT1 static void regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv) { if (argc >= 2) { const char *target = (const char *)sqlite3_value_text(argv[1]); const char *pattern = (const char *)sqlite3_value_text(argv[0]); const char* errstr = NULL; int erroff = 0; int vec[500]; int n, rc; pcre* re = pcre_compile(pattern, 0, &errstr, &erroff, NULL); rc = pcre_exec(re, NULL, target, strlen(target), 0, 0, vec, 500); if (rc <= 0) { sqlite3_result_error(context, errstr, 0); return; } sqlite3_result_int(context, 1); } } #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_extension_init(sqlite3 *db, char **errmsg, const sqlite3_api_routines *api) { SQLITE_EXTENSION_INIT2(api); return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, (void*)db, regexp_func, NULL, NULL); } It needs to be built as a so/dll shared library. And you need to register the extension module like below. sql.Register("sqlite3_with_extensions", &sqlite3.SQLiteDriver{ Extensions: []string{ "sqlite3_mod_regexp", }, }) Then, you can use this extension. rows, err := db.Query("select text from mytable where name regexp '^golang'") Connection Hook You can hook and inject your code when the connection is established. database/sql doesn't provide a way to get native go-sqlite3 interfaces. So if you want, you need to set ConnectHook and get the SQLiteConn. sql.Register("sqlite3_with_hook_example", &sqlite3.SQLiteDriver{ ConnectHook: func(conn *sqlite3.SQLiteConn) error { sqlite3conn = append(sqlite3conn, conn) return nil }, }) Go SQlite3 Extensions If you want to register Go functions as SQLite extension functions, call RegisterFunction from ConnectHook. regex = func(re, s string) (bool, error) { return regexp.MatchString(re, s) } sql.Register("sqlite3_with_go_func", &sqlite3.SQLiteDriver{ ConnectHook: func(conn *sqlite3.SQLiteConn) error { return conn.RegisterFunc("regexp", regex, true) }, }) See the documentation of RegisterFunc for more details. */ package sqlite3 ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/callback_test.go������������������������������������0000644�0610621�0607500�00000005510�13172163427�025524� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package sqlite3 import ( "errors" "math" "reflect" "testing" ) func TestCallbackArgCast(t *testing.T) { intConv := callbackSyntheticForTests(reflect.ValueOf(int64(math.MaxInt64)), nil) floatConv := callbackSyntheticForTests(reflect.ValueOf(float64(math.MaxFloat64)), nil) errConv := callbackSyntheticForTests(reflect.Value{}, errors.New("test")) tests := []struct { f callbackArgConverter o reflect.Value }{ {intConv, reflect.ValueOf(int8(-1))}, {intConv, reflect.ValueOf(int16(-1))}, {intConv, reflect.ValueOf(int32(-1))}, {intConv, reflect.ValueOf(uint8(math.MaxUint8))}, {intConv, reflect.ValueOf(uint16(math.MaxUint16))}, {intConv, reflect.ValueOf(uint32(math.MaxUint32))}, // Special case, int64->uint64 is only 1<<63 - 1, not 1<<64 - 1 {intConv, reflect.ValueOf(uint64(math.MaxInt64))}, {floatConv, reflect.ValueOf(float32(math.Inf(1)))}, } for _, test := range tests { conv := callbackArgCast{test.f, test.o.Type()} val, err := conv.Run(nil) if err != nil { t.Errorf("Couldn't convert to %s: %s", test.o.Type(), err) } else if !reflect.DeepEqual(val.Interface(), test.o.Interface()) { t.Errorf("Unexpected result from converting to %s: got %v, want %v", test.o.Type(), val.Interface(), test.o.Interface()) } } conv := callbackArgCast{errConv, reflect.TypeOf(int8(0))} _, err := conv.Run(nil) if err == nil { t.Errorf("Expected error during callbackArgCast, but got none") } } func TestCallbackConverters(t *testing.T) { tests := []struct { v interface{} err bool }{ // Unfortunately, we can't tell which converter was returned, // but we can at least check which types can be converted. {[]byte{0}, false}, {"text", false}, {true, false}, {int8(0), false}, {int16(0), false}, {int32(0), false}, {int64(0), false}, {uint8(0), false}, {uint16(0), false}, {uint32(0), false}, {uint64(0), false}, {int(0), false}, {uint(0), false}, {float64(0), false}, {float32(0), false}, {func() {}, true}, {complex64(complex(0, 0)), true}, {complex128(complex(0, 0)), true}, {struct{}{}, true}, {map[string]string{}, true}, {[]string{}, true}, {(*int8)(nil), true}, {make(chan int), true}, } for _, test := range tests { _, err := callbackArg(reflect.TypeOf(test.v)) if test.err && err == nil { t.Errorf("Expected an error when converting %s, got no error", reflect.TypeOf(test.v)) } else if !test.err && err != nil { t.Errorf("Expected converter when converting %s, got error: %s", reflect.TypeOf(test.v), err) } } for _, test := range tests { _, err := callbackRet(reflect.TypeOf(test.v)) if test.err && err == nil { t.Errorf("Expected an error when converting %s, got no error", reflect.TypeOf(test.v)) } else if !test.err && err != nil { t.Errorf("Expected converter when converting %s, got error: %s", reflect.TypeOf(test.v), err) } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/callback.go�����������������������������������������0000644�0610621�0607500�00000024237�13172163427�024474� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 // You can't export a Go function to C and have definitions in the C // preamble in the same file, so we have to have callbackTrampoline in // its own file. Because we need a separate file anyway, the support // code for SQLite custom functions is in here. /* #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif #include <stdlib.h> void _sqlite3_result_text(sqlite3_context* ctx, const char* s); void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l); */ import "C" import ( "errors" "fmt" "math" "reflect" "sync" "unsafe" ) //export callbackTrampoline func callbackTrampoline(ctx *C.sqlite3_context, argc int, argv **C.sqlite3_value) { args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc] fi := lookupHandle(uintptr(C.sqlite3_user_data(ctx))).(*functionInfo) fi.Call(ctx, args) } //export stepTrampoline func stepTrampoline(ctx *C.sqlite3_context, argc C.int, argv **C.sqlite3_value) { args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:int(argc):int(argc)] ai := lookupHandle(uintptr(C.sqlite3_user_data(ctx))).(*aggInfo) ai.Step(ctx, args) } //export doneTrampoline func doneTrampoline(ctx *C.sqlite3_context) { handle := uintptr(C.sqlite3_user_data(ctx)) ai := lookupHandle(handle).(*aggInfo) ai.Done(ctx) } //export compareTrampoline func compareTrampoline(handlePtr uintptr, la C.int, a *C.char, lb C.int, b *C.char) C.int { cmp := lookupHandle(handlePtr).(func(string, string) int) return C.int(cmp(C.GoStringN(a, la), C.GoStringN(b, lb))) } //export commitHookTrampoline func commitHookTrampoline(handle uintptr) int { callback := lookupHandle(handle).(func() int) return callback() } //export rollbackHookTrampoline func rollbackHookTrampoline(handle uintptr) { callback := lookupHandle(handle).(func()) callback() } //export updateHookTrampoline func updateHookTrampoline(handle uintptr, op int, db *C.char, table *C.char, rowid int64) { callback := lookupHandle(handle).(func(int, string, string, int64)) callback(op, C.GoString(db), C.GoString(table), rowid) } // Use handles to avoid passing Go pointers to C. type handleVal struct { db *SQLiteConn val interface{} } var handleLock sync.Mutex var handleVals = make(map[uintptr]handleVal) var handleIndex uintptr = 100 func newHandle(db *SQLiteConn, v interface{}) uintptr { handleLock.Lock() defer handleLock.Unlock() i := handleIndex handleIndex++ handleVals[i] = handleVal{db, v} return i } func lookupHandle(handle uintptr) interface{} { handleLock.Lock() defer handleLock.Unlock() r, ok := handleVals[handle] if !ok { if handle >= 100 && handle < handleIndex { panic("deleted handle") } else { panic("invalid handle") } } return r.val } func deleteHandles(db *SQLiteConn) { handleLock.Lock() defer handleLock.Unlock() for handle, val := range handleVals { if val.db == db { delete(handleVals, handle) } } } // This is only here so that tests can refer to it. type callbackArgRaw C.sqlite3_value type callbackArgConverter func(*C.sqlite3_value) (reflect.Value, error) type callbackArgCast struct { f callbackArgConverter typ reflect.Type } func (c callbackArgCast) Run(v *C.sqlite3_value) (reflect.Value, error) { val, err := c.f(v) if err != nil { return reflect.Value{}, err } if !val.Type().ConvertibleTo(c.typ) { return reflect.Value{}, fmt.Errorf("cannot convert %s to %s", val.Type(), c.typ) } return val.Convert(c.typ), nil } func callbackArgInt64(v *C.sqlite3_value) (reflect.Value, error) { if C.sqlite3_value_type(v) != C.SQLITE_INTEGER { return reflect.Value{}, fmt.Errorf("argument must be an INTEGER") } return reflect.ValueOf(int64(C.sqlite3_value_int64(v))), nil } func callbackArgBool(v *C.sqlite3_value) (reflect.Value, error) { if C.sqlite3_value_type(v) != C.SQLITE_INTEGER { return reflect.Value{}, fmt.Errorf("argument must be an INTEGER") } i := int64(C.sqlite3_value_int64(v)) val := false if i != 0 { val = true } return reflect.ValueOf(val), nil } func callbackArgFloat64(v *C.sqlite3_value) (reflect.Value, error) { if C.sqlite3_value_type(v) != C.SQLITE_FLOAT { return reflect.Value{}, fmt.Errorf("argument must be a FLOAT") } return reflect.ValueOf(float64(C.sqlite3_value_double(v))), nil } func callbackArgBytes(v *C.sqlite3_value) (reflect.Value, error) { switch C.sqlite3_value_type(v) { case C.SQLITE_BLOB: l := C.sqlite3_value_bytes(v) p := C.sqlite3_value_blob(v) return reflect.ValueOf(C.GoBytes(p, l)), nil case C.SQLITE_TEXT: l := C.sqlite3_value_bytes(v) c := unsafe.Pointer(C.sqlite3_value_text(v)) return reflect.ValueOf(C.GoBytes(c, l)), nil default: return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT") } } func callbackArgString(v *C.sqlite3_value) (reflect.Value, error) { switch C.sqlite3_value_type(v) { case C.SQLITE_BLOB: l := C.sqlite3_value_bytes(v) p := (*C.char)(C.sqlite3_value_blob(v)) return reflect.ValueOf(C.GoStringN(p, l)), nil case C.SQLITE_TEXT: c := (*C.char)(unsafe.Pointer(C.sqlite3_value_text(v))) return reflect.ValueOf(C.GoString(c)), nil default: return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT") } } func callbackArgGeneric(v *C.sqlite3_value) (reflect.Value, error) { switch C.sqlite3_value_type(v) { case C.SQLITE_INTEGER: return callbackArgInt64(v) case C.SQLITE_FLOAT: return callbackArgFloat64(v) case C.SQLITE_TEXT: return callbackArgString(v) case C.SQLITE_BLOB: return callbackArgBytes(v) case C.SQLITE_NULL: // Interpret NULL as a nil byte slice. var ret []byte return reflect.ValueOf(ret), nil default: panic("unreachable") } } func callbackArg(typ reflect.Type) (callbackArgConverter, error) { switch typ.Kind() { case reflect.Interface: if typ.NumMethod() != 0 { return nil, errors.New("the only supported interface type is interface{}") } return callbackArgGeneric, nil case reflect.Slice: if typ.Elem().Kind() != reflect.Uint8 { return nil, errors.New("the only supported slice type is []byte") } return callbackArgBytes, nil case reflect.String: return callbackArgString, nil case reflect.Bool: return callbackArgBool, nil case reflect.Int64: return callbackArgInt64, nil case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint: c := callbackArgCast{callbackArgInt64, typ} return c.Run, nil case reflect.Float64: return callbackArgFloat64, nil case reflect.Float32: c := callbackArgCast{callbackArgFloat64, typ} return c.Run, nil default: return nil, fmt.Errorf("don't know how to convert to %s", typ) } } func callbackConvertArgs(argv []*C.sqlite3_value, converters []callbackArgConverter, variadic callbackArgConverter) ([]reflect.Value, error) { var args []reflect.Value if len(argv) < len(converters) { return nil, fmt.Errorf("function requires at least %d arguments", len(converters)) } for i, arg := range argv[:len(converters)] { v, err := converters[i](arg) if err != nil { return nil, err } args = append(args, v) } if variadic != nil { for _, arg := range argv[len(converters):] { v, err := variadic(arg) if err != nil { return nil, err } args = append(args, v) } } return args, nil } type callbackRetConverter func(*C.sqlite3_context, reflect.Value) error func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error { switch v.Type().Kind() { case reflect.Int64: case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint: v = v.Convert(reflect.TypeOf(int64(0))) case reflect.Bool: b := v.Interface().(bool) if b { v = reflect.ValueOf(int64(1)) } else { v = reflect.ValueOf(int64(0)) } default: return fmt.Errorf("cannot convert %s to INTEGER", v.Type()) } C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Interface().(int64))) return nil } func callbackRetFloat(ctx *C.sqlite3_context, v reflect.Value) error { switch v.Type().Kind() { case reflect.Float64: case reflect.Float32: v = v.Convert(reflect.TypeOf(float64(0))) default: return fmt.Errorf("cannot convert %s to FLOAT", v.Type()) } C.sqlite3_result_double(ctx, C.double(v.Interface().(float64))) return nil } func callbackRetBlob(ctx *C.sqlite3_context, v reflect.Value) error { if v.Type().Kind() != reflect.Slice || v.Type().Elem().Kind() != reflect.Uint8 { return fmt.Errorf("cannot convert %s to BLOB", v.Type()) } i := v.Interface() if i == nil || len(i.([]byte)) == 0 { C.sqlite3_result_null(ctx) } else { bs := i.([]byte) C._sqlite3_result_blob(ctx, unsafe.Pointer(&bs[0]), C.int(len(bs))) } return nil } func callbackRetText(ctx *C.sqlite3_context, v reflect.Value) error { if v.Type().Kind() != reflect.String { return fmt.Errorf("cannot convert %s to TEXT", v.Type()) } C._sqlite3_result_text(ctx, C.CString(v.Interface().(string))) return nil } func callbackRet(typ reflect.Type) (callbackRetConverter, error) { switch typ.Kind() { case reflect.Slice: if typ.Elem().Kind() != reflect.Uint8 { return nil, errors.New("the only supported slice type is []byte") } return callbackRetBlob, nil case reflect.String: return callbackRetText, nil case reflect.Bool, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint: return callbackRetInteger, nil case reflect.Float32, reflect.Float64: return callbackRetFloat, nil default: return nil, fmt.Errorf("don't know how to convert to %s", typ) } } func callbackError(ctx *C.sqlite3_context, err error) { cstr := C.CString(err.Error()) defer C.free(unsafe.Pointer(cstr)) C.sqlite3_result_error(ctx, cstr, -1) } // Test support code. Tests are not allowed to import "C", so we can't // declare any functions that use C.sqlite3_value. func callbackSyntheticForTests(v reflect.Value, err error) callbackArgConverter { return func(*C.sqlite3_value) (reflect.Value, error) { return v, err } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/backup_test.go��������������������������������������0000644�0610621�0607500�00000023253�13172163427�025241� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 import ( "database/sql" "fmt" "os" "testing" "time" ) // The number of rows of test data to create in the source database. // Can be used to control how many pages are available to be backed up. const testRowCount = 100 // The maximum number of seconds after which the page-by-page backup is considered to have taken too long. const usePagePerStepsTimeoutSeconds = 30 // Test the backup functionality. func testBackup(t *testing.T, testRowCount int, usePerPageSteps bool) { // This function will be called multiple times. // It uses sql.Register(), which requires the name parameter value to be unique. // There does not currently appear to be a way to unregister a registered driver, however. // So generate a database driver name that will likely be unique. var driverName = fmt.Sprintf("sqlite3_testBackup_%v_%v_%v", testRowCount, usePerPageSteps, time.Now().UnixNano()) // The driver's connection will be needed in order to perform the backup. driverConns := []*SQLiteConn{} sql.Register(driverName, &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { driverConns = append(driverConns, conn) return nil }, }) // Connect to the source database. srcTempFilename := TempFilename(t) defer os.Remove(srcTempFilename) srcDb, err := sql.Open(driverName, srcTempFilename) if err != nil { t.Fatal("Failed to open the source database:", err) } defer srcDb.Close() err = srcDb.Ping() if err != nil { t.Fatal("Failed to connect to the source database:", err) } // Connect to the destination database. destTempFilename := TempFilename(t) defer os.Remove(destTempFilename) destDb, err := sql.Open(driverName, destTempFilename) if err != nil { t.Fatal("Failed to open the destination database:", err) } defer destDb.Close() err = destDb.Ping() if err != nil { t.Fatal("Failed to connect to the destination database:", err) } // Check the driver connections. if len(driverConns) != 2 { t.Fatalf("Expected 2 driver connections, but found %v.", len(driverConns)) } srcDbDriverConn := driverConns[0] if srcDbDriverConn == nil { t.Fatal("The source database driver connection is nil.") } destDbDriverConn := driverConns[1] if destDbDriverConn == nil { t.Fatal("The destination database driver connection is nil.") } // Generate some test data for the given ID. var generateTestData = func(id int) string { return fmt.Sprintf("test-%v", id) } // Populate the source database with a test table containing some test data. tx, err := srcDb.Begin() if err != nil { t.Fatal("Failed to begin a transaction when populating the source database:", err) } _, err = srcDb.Exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)") if err != nil { tx.Rollback() t.Fatal("Failed to create the source database \"test\" table:", err) } for id := 0; id < testRowCount; id++ { _, err = srcDb.Exec("INSERT INTO test (id, value) VALUES (?, ?)", id, generateTestData(id)) if err != nil { tx.Rollback() t.Fatal("Failed to insert a row into the source database \"test\" table:", err) } } err = tx.Commit() if err != nil { t.Fatal("Failed to populate the source database:", err) } // Confirm that the destination database is initially empty. var destTableCount int err = destDb.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table'").Scan(&destTableCount) if err != nil { t.Fatal("Failed to check the destination table count:", err) } if destTableCount != 0 { t.Fatalf("The destination database is not empty; %v table(s) found.", destTableCount) } // Prepare to perform the backup. backup, err := destDbDriverConn.Backup("main", srcDbDriverConn, "main") if err != nil { t.Fatal("Failed to initialize the backup:", err) } // Allow the initial page count and remaining values to be retrieved. // According to <https://www.sqlite.org/c3ref/backup_finish.html>, the page count and remaining values are "... only updated by sqlite3_backup_step()." isDone, err := backup.Step(0) if err != nil { t.Fatal("Unable to perform an initial 0-page backup step:", err) } if isDone { t.Fatal("Backup is unexpectedly done.") } // Check that the page count and remaining values are reasonable. initialPageCount := backup.PageCount() if initialPageCount <= 0 { t.Fatalf("Unexpected initial page count value: %v", initialPageCount) } initialRemaining := backup.Remaining() if initialRemaining <= 0 { t.Fatalf("Unexpected initial remaining value: %v", initialRemaining) } if initialRemaining != initialPageCount { t.Fatalf("Initial remaining value differs from the initial page count value; remaining: %v; page count: %v", initialRemaining, initialPageCount) } // Perform the backup. if usePerPageSteps { var startTime = time.Now().Unix() // Test backing-up using a page-by-page approach. var latestRemaining = initialRemaining for { // Perform the backup step. isDone, err = backup.Step(1) if err != nil { t.Fatal("Failed to perform a backup step:", err) } // The page count should remain unchanged from its initial value. currentPageCount := backup.PageCount() if currentPageCount != initialPageCount { t.Fatalf("Current page count differs from the initial page count; initial page count: %v; current page count: %v", initialPageCount, currentPageCount) } // There should now be one less page remaining. currentRemaining := backup.Remaining() expectedRemaining := latestRemaining - 1 if currentRemaining != expectedRemaining { t.Fatalf("Unexpected remaining value; expected remaining value: %v; actual remaining value: %v", expectedRemaining, currentRemaining) } latestRemaining = currentRemaining if isDone { break } // Limit the runtime of the backup attempt. if (time.Now().Unix() - startTime) > usePagePerStepsTimeoutSeconds { t.Fatal("Backup is taking longer than expected.") } } } else { // Test the copying of all remaining pages. isDone, err = backup.Step(-1) if err != nil { t.Fatal("Failed to perform a backup step:", err) } if !isDone { t.Fatal("Backup is unexpectedly not done.") } } // Check that the page count and remaining values are reasonable. finalPageCount := backup.PageCount() if finalPageCount != initialPageCount { t.Fatalf("Final page count differs from the initial page count; initial page count: %v; final page count: %v", initialPageCount, finalPageCount) } finalRemaining := backup.Remaining() if finalRemaining != 0 { t.Fatalf("Unexpected remaining value: %v", finalRemaining) } // Finish the backup. err = backup.Finish() if err != nil { t.Fatal("Failed to finish backup:", err) } // Confirm that the "test" table now exists in the destination database. var doesTestTableExist bool err = destDb.QueryRow("SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'test' LIMIT 1) AS test_table_exists").Scan(&doesTestTableExist) if err != nil { t.Fatal("Failed to check if the \"test\" table exists in the destination database:", err) } if !doesTestTableExist { t.Fatal("The \"test\" table could not be found in the destination database.") } // Confirm that the number of rows in the destination database's "test" table matches that of the source table. var actualTestTableRowCount int err = destDb.QueryRow("SELECT COUNT(*) FROM test").Scan(&actualTestTableRowCount) if err != nil { t.Fatal("Failed to determine the rowcount of the \"test\" table in the destination database:", err) } if testRowCount != actualTestTableRowCount { t.Fatalf("Unexpected destination \"test\" table row count; expected: %v; found: %v", testRowCount, actualTestTableRowCount) } // Check each of the rows in the destination database. for id := 0; id < testRowCount; id++ { var checkedValue string err = destDb.QueryRow("SELECT value FROM test WHERE id = ?", id).Scan(&checkedValue) if err != nil { t.Fatal("Failed to query the \"test\" table in the destination database:", err) } var expectedValue = generateTestData(id) if checkedValue != expectedValue { t.Fatalf("Unexpected value in the \"test\" table in the destination database; expected value: %v; actual value: %v", expectedValue, checkedValue) } } } func TestBackupStepByStep(t *testing.T) { testBackup(t, testRowCount, true) } func TestBackupAllRemainingPages(t *testing.T) { testBackup(t, testRowCount, false) } // Test the error reporting when preparing to perform a backup. func TestBackupError(t *testing.T) { const driverName = "sqlite3_TestBackupError" // The driver's connection will be needed in order to perform the backup. var dbDriverConn *SQLiteConn sql.Register(driverName, &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { dbDriverConn = conn return nil }, }) // Connect to the database. dbTempFilename := TempFilename(t) defer os.Remove(dbTempFilename) db, err := sql.Open(driverName, dbTempFilename) if err != nil { t.Fatal("Failed to open the database:", err) } defer db.Close() db.Ping() // Need the driver connection in order to perform the backup. if dbDriverConn == nil { t.Fatal("Failed to get the driver connection.") } // Prepare to perform the backup. // Intentionally using the same connection for both the source and destination databases, to trigger an error result. backup, err := dbDriverConn.Backup("main", dbDriverConn, "main") if err == nil { t.Fatal("Failed to get the expected error result.") } const expectedError = "source and destination must be distinct" if err.Error() != expectedError { t.Fatalf("Unexpected error message; expected value: \"%v\"; actual value: \"%v\"", expectedError, err.Error()) } if backup != nil { t.Fatal("Failed to get the expected nil backup result.") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/backup.go�������������������������������������������0000644�0610621�0607500�00000004217�13172163427�024201� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 /* #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif #include <stdlib.h> */ import "C" import ( "runtime" "unsafe" ) // SQLiteBackup implement interface of Backup. type SQLiteBackup struct { b *C.sqlite3_backup } // Backup make backup from src to dest. func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error) { destptr := C.CString(dest) defer C.free(unsafe.Pointer(destptr)) srcptr := C.CString(src) defer C.free(unsafe.Pointer(srcptr)) if b := C.sqlite3_backup_init(c.db, destptr, conn.db, srcptr); b != nil { bb := &SQLiteBackup{b: b} runtime.SetFinalizer(bb, (*SQLiteBackup).Finish) return bb, nil } return nil, c.lastError() } // Step to backs up for one step. Calls the underlying `sqlite3_backup_step` // function. This function returns a boolean indicating if the backup is done // and an error signalling any other error. Done is returned if the underlying // C function returns SQLITE_DONE (Code 101) func (b *SQLiteBackup) Step(p int) (bool, error) { ret := C.sqlite3_backup_step(b.b, C.int(p)) if ret == C.SQLITE_DONE { return true, nil } else if ret != 0 && ret != C.SQLITE_LOCKED && ret != C.SQLITE_BUSY { return false, Error{Code: ErrNo(ret)} } return false, nil } // Remaining return whether have the rest for backup. func (b *SQLiteBackup) Remaining() int { return int(C.sqlite3_backup_remaining(b.b)) } // PageCount return count of pages. func (b *SQLiteBackup) PageCount() int { return int(C.sqlite3_backup_pagecount(b.b)) } // Finish close backup. func (b *SQLiteBackup) Finish() error { return b.Close() } // Close close backup. func (b *SQLiteBackup) Close() error { ret := C.sqlite3_backup_finish(b.b) // sqlite3_backup_finish() never fails, it just returns the // error code from previous operations, so clean up before // checking and returning an error b.b = nil runtime.SetFinalizer(b, nil) if ret != 0 { return Error{Code: ErrNo(ret)} } return nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/�������������������������������������������0000755�0610621�0607500�00000000000�13172163427�024173� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/vtable/������������������������������������0000755�0610621�0607500�00000000000�13172163427�025450� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/vtable/vtable.go���������������������������0000644�0610621�0607500�00000004335�13172163427�027261� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/mattn/go-sqlite3" ) type githubRepo struct { ID int `json:"id"` FullName string `json:"full_name"` Description string `json:"description"` HTMLURL string `json:"html_url"` } type githubModule struct { } func (m *githubModule) Create(c *sqlite3.SQLiteConn, args []string) (sqlite3.VTab, error) { err := c.DeclareVTab(fmt.Sprintf(` CREATE TABLE %s ( id INT, full_name TEXT, description TEXT, html_url TEXT )`, args[0])) if err != nil { return nil, err } return &ghRepoTable{}, nil } func (m *githubModule) Connect(c *sqlite3.SQLiteConn, args []string) (sqlite3.VTab, error) { return m.Create(c, args) } func (m *githubModule) DestroyModule() {} type ghRepoTable struct { repos []githubRepo } func (v *ghRepoTable) Open() (sqlite3.VTabCursor, error) { resp, err := http.Get("https://api.github.com/repositories") if err != nil { return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var repos []githubRepo if err := json.Unmarshal(body, &repos); err != nil { return nil, err } return &ghRepoCursor{0, repos}, nil } func (v *ghRepoTable) BestIndex(cst []sqlite3.InfoConstraint, ob []sqlite3.InfoOrderBy) (*sqlite3.IndexResult, error) { return &sqlite3.IndexResult{}, nil } func (v *ghRepoTable) Disconnect() error { return nil } func (v *ghRepoTable) Destroy() error { return nil } type ghRepoCursor struct { index int repos []githubRepo } func (vc *ghRepoCursor) Column(c *sqlite3.SQLiteContext, col int) error { switch col { case 0: c.ResultInt(vc.repos[vc.index].ID) case 1: c.ResultText(vc.repos[vc.index].FullName) case 2: c.ResultText(vc.repos[vc.index].Description) case 3: c.ResultText(vc.repos[vc.index].HTMLURL) } return nil } func (vc *ghRepoCursor) Filter(idxNum int, idxStr string, vals []interface{}) error { vc.index = 0 return nil } func (vc *ghRepoCursor) Next() error { vc.index++ return nil } func (vc *ghRepoCursor) EOF() bool { return vc.index >= len(vc.repos) } func (vc *ghRepoCursor) Rowid() (int64, error) { return int64(vc.index), nil } func (vc *ghRepoCursor) Close() error { return nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/vtable/main.go�����������������������������0000644�0610621�0607500�00000001550�13172163427�026724� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "fmt" "log" "github.com/mattn/go-sqlite3" ) func main() { sql.Register("sqlite3_with_extensions", &sqlite3.SQLiteDriver{ ConnectHook: func(conn *sqlite3.SQLiteConn) error { return conn.CreateModule("github", &githubModule{}) }, }) db, err := sql.Open("sqlite3_with_extensions", ":memory:") if err != nil { log.Fatal(err) } defer db.Close() _, err = db.Exec("create virtual table repo using github(id, full_name, description, html_url)") if err != nil { log.Fatal(err) } rows, err := db.Query("select id, full_name, description, html_url from repo") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var id, fullName, description, htmlURL string rows.Scan(&id, &fullName, &description, &htmlURL) fmt.Printf("%s: %s\n\t%s\n\t%s\n\n", id, fullName, description, htmlURL) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/trace/�������������������������������������0000755�0610621�0607500�00000000000�13172163427�025271� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/trace/main.go������������������������������0000644�0610621�0607500�00000014372�13172163427�026553� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "fmt" "log" "os" sqlite3 "github.com/mattn/go-sqlite3" ) func traceCallback(info sqlite3.TraceInfo) int { // Not very readable but may be useful; uncomment next line in case of doubt: //fmt.Printf("Trace: %#v\n", info) var dbErrText string if info.DBError.Code != 0 || info.DBError.ExtendedCode != 0 { dbErrText = fmt.Sprintf("; DB error: %#v", info.DBError) } else { dbErrText = "." } // Show the Statement-or-Trigger text in curly braces ('{', '}') // since from the *paired* ASCII characters they are // the least used in SQL syntax, therefore better visual delimiters. // Maybe show 'ExpandedSQL' the same way as 'StmtOrTrigger'. // // A known use of curly braces (outside strings) is // for ODBC escape sequences. Not likely to appear here. // // Template languages, etc. don't matter, we should see their *result* // at *this* level. // Strange curly braces in SQL code that reached the database driver // suggest that there is a bug in the application. // The braces are likely to be either template syntax or // a programming language's string interpolation syntax. var expandedText string if info.ExpandedSQL != "" { if info.ExpandedSQL == info.StmtOrTrigger { expandedText = " = exp" } else { expandedText = fmt.Sprintf(" expanded {%q}", info.ExpandedSQL) } } else { expandedText = "" } // SQLite docs as of September 6, 2016: Tracing and Profiling Functions // https://www.sqlite.org/c3ref/profile.html // // The profile callback time is in units of nanoseconds, however // the current implementation is only capable of millisecond resolution // so the six least significant digits in the time are meaningless. // Future versions of SQLite might provide greater resolution on the profiler callback. var runTimeText string if info.RunTimeNanosec == 0 { if info.EventCode == sqlite3.TraceProfile { //runTimeText = "; no time" // seems confusing runTimeText = "; time 0" // no measurement unit } else { //runTimeText = "; no time" // seems useless and confusing } } else { const nanosPerMillisec = 1000000 if info.RunTimeNanosec%nanosPerMillisec == 0 { runTimeText = fmt.Sprintf("; time %d ms", info.RunTimeNanosec/nanosPerMillisec) } else { // unexpected: better than millisecond resolution runTimeText = fmt.Sprintf("; time %d ns!!!", info.RunTimeNanosec) } } var modeText string if info.AutoCommit { modeText = "-AC-" } else { modeText = "+Tx+" } fmt.Printf("Trace: ev %d %s conn 0x%x, stmt 0x%x {%q}%s%s%s\n", info.EventCode, modeText, info.ConnHandle, info.StmtHandle, info.StmtOrTrigger, expandedText, runTimeText, dbErrText) return 0 } func main() { eventMask := sqlite3.TraceStmt | sqlite3.TraceProfile | sqlite3.TraceRow | sqlite3.TraceClose sql.Register("sqlite3_tracing", &sqlite3.SQLiteDriver{ ConnectHook: func(conn *sqlite3.SQLiteConn) error { err := conn.SetTrace(&sqlite3.TraceConfig{ Callback: traceCallback, EventMask: uint(eventMask), WantExpandedSQL: true, }) return err }, }) os.Exit(dbMain()) } // Harder to do DB work in main(). // It's better with a separate function because // 'defer' and 'os.Exit' don't go well together. // // DO NOT use 'log.Fatal...' below: remember that it's equivalent to // Print() followed by a call to os.Exit(1) --- and // we want to avoid Exit() so 'defer' can do cleanup. // Use 'log.Panic...' instead. func dbMain() int { db, err := sql.Open("sqlite3_tracing", ":memory:") if err != nil { fmt.Printf("Failed to open database: %#+v\n", err) return 1 } defer db.Close() err = db.Ping() if err != nil { log.Panic(err) } dbSetup(db) dbDoInsert(db) dbDoInsertPrepared(db) dbDoSelect(db) dbDoSelectPrepared(db) return 0 } // 'DDL' stands for "Data Definition Language": // Note: "INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT" causes the error // 'near "AUTOINCREMENT": syntax error'; without "NOT NULL" it works. const tableDDL = `CREATE TABLE t1 ( id INTEGER PRIMARY KEY AUTOINCREMENT, note VARCHAR NOT NULL )` // 'DML' stands for "Data Manipulation Language": const insertDML = "INSERT INTO t1 (note) VALUES (?)" const selectDML = "SELECT id, note FROM t1 WHERE note LIKE ?" const textPrefix = "bla-1234567890-" const noteTextPattern = "%Prep%" const nGenRows = 4 // Number of Rows to Generate (for *each* approach tested) func dbSetup(db *sql.DB) { var err error _, err = db.Exec("DROP TABLE IF EXISTS t1") if err != nil { log.Panic(err) } _, err = db.Exec(tableDDL) if err != nil { log.Panic(err) } } func dbDoInsert(db *sql.DB) { const Descr = "DB-Exec" for i := 0; i < nGenRows; i++ { result, err := db.Exec(insertDML, textPrefix+Descr) if err != nil { log.Panic(err) } resultDoCheck(result, Descr, i) } } func dbDoInsertPrepared(db *sql.DB) { const Descr = "DB-Prepare" stmt, err := db.Prepare(insertDML) if err != nil { log.Panic(err) } defer stmt.Close() for i := 0; i < nGenRows; i++ { result, err := stmt.Exec(textPrefix + Descr) if err != nil { log.Panic(err) } resultDoCheck(result, Descr, i) } } func resultDoCheck(result sql.Result, callerDescr string, callIndex int) { lastID, err := result.LastInsertId() if err != nil { log.Panic(err) } nAffected, err := result.RowsAffected() if err != nil { log.Panic(err) } log.Printf("Exec result for %s (%d): ID = %d, affected = %d\n", callerDescr, callIndex, lastID, nAffected) } func dbDoSelect(db *sql.DB) { const Descr = "DB-Query" rows, err := db.Query(selectDML, noteTextPattern) if err != nil { log.Panic(err) } defer rows.Close() rowsDoFetch(rows, Descr) } func dbDoSelectPrepared(db *sql.DB) { const Descr = "DB-Prepare" stmt, err := db.Prepare(selectDML) if err != nil { log.Panic(err) } defer stmt.Close() rows, err := stmt.Query(noteTextPattern) if err != nil { log.Panic(err) } defer rows.Close() rowsDoFetch(rows, Descr) } func rowsDoFetch(rows *sql.Rows, callerDescr string) { var nRows int var id int64 var note string for rows.Next() { err := rows.Scan(&id, &note) if err != nil { log.Panic(err) } log.Printf("Row for %s (%d): id=%d, note=%q\n", callerDescr, nRows, id, note) nRows++ } if err := rows.Err(); err != nil { log.Panic(err) } log.Printf("Total %d rows for %s.\n", nRows, callerDescr) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/simple/������������������������������������0000755�0610621�0607500�00000000000�13172163427�025464� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/simple/simple.go���������������������������0000644�0610621�0607500�00000003433�13172163427�027307� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" "log" "os" ) func main() { os.Remove("./foo.db") db, err := sql.Open("sqlite3", "./foo.db") if err != nil { log.Fatal(err) } defer db.Close() sqlStmt := ` create table foo (id integer not null primary key, name text); delete from foo; ` _, err = db.Exec(sqlStmt) if err != nil { log.Printf("%q: %s\n", err, sqlStmt) return } tx, err := db.Begin() if err != nil { log.Fatal(err) } stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)") if err != nil { log.Fatal(err) } defer stmt.Close() for i := 0; i < 100; i++ { _, err = stmt.Exec(i, fmt.Sprintf("ã“ã‚“ã«ã¡ã‚世界%03d", i)) if err != nil { log.Fatal(err) } } tx.Commit() rows, err := db.Query("select id, name from foo") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var id int var name string err = rows.Scan(&id, &name) if err != nil { log.Fatal(err) } fmt.Println(id, name) } err = rows.Err() if err != nil { log.Fatal(err) } stmt, err = db.Prepare("select name from foo where id = ?") if err != nil { log.Fatal(err) } defer stmt.Close() var name string err = stmt.QueryRow("3").Scan(&name) if err != nil { log.Fatal(err) } fmt.Println(name) _, err = db.Exec("delete from foo") if err != nil { log.Fatal(err) } _, err = db.Exec("insert into foo(id, name) values(1, 'foo'), (2, 'bar'), (3, 'baz')") if err != nil { log.Fatal(err) } rows, err = db.Query("select id, name from foo") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var id int var name string err = rows.Scan(&id, &name) if err != nil { log.Fatal(err) } fmt.Println(id, name) } err = rows.Err() if err != nil { log.Fatal(err) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_vtable/��������������������������������0000755�0610621�0607500�00000000000�13172163427�026307� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_vtable/sqlite3_mod_vtable.cc�����������0000644�0610621�0607500�00000012515�13172163427�032402� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#include <string> #include <sstream> #include <sqlite3-binding.h> #include <sqlite3ext.h> #include <curl/curl.h> #include "picojson.h" #ifdef _WIN32 # define EXPORT __declspec(dllexport) #else # define EXPORT #endif SQLITE_EXTENSION_INIT1; typedef struct { char* data; // response data from server size_t size; // response size of data } MEMFILE; MEMFILE* memfopen() { MEMFILE* mf = (MEMFILE*) malloc(sizeof(MEMFILE)); if (mf) { mf->data = NULL; mf->size = 0; } return mf; } void memfclose(MEMFILE* mf) { if (mf->data) free(mf->data); free(mf); } size_t memfwrite(char* ptr, size_t size, size_t nmemb, void* stream) { MEMFILE* mf = (MEMFILE*) stream; int block = size * nmemb; if (!mf) return block; // through if (!mf->data) mf->data = (char*) malloc(block); else mf->data = (char*) realloc(mf->data, mf->size + block); if (mf->data) { memcpy(mf->data + mf->size, ptr, block); mf->size += block; } return block; } char* memfstrdup(MEMFILE* mf) { char* buf; if (mf->size == 0) return NULL; buf = (char*) malloc(mf->size + 1); memcpy(buf, mf->data, mf->size); buf[mf->size] = 0; return buf; } static int my_connect(sqlite3 *db, void *pAux, int argc, const char * const *argv, sqlite3_vtab **ppVTab, char **c) { std::stringstream ss; ss << "CREATE TABLE " << argv[0] << "(id int, full_name text, description text, html_url text)"; int rc = sqlite3_declare_vtab(db, ss.str().c_str()); *ppVTab = (sqlite3_vtab *) sqlite3_malloc(sizeof(sqlite3_vtab)); memset(*ppVTab, 0, sizeof(sqlite3_vtab)); return rc; } static int my_create(sqlite3 *db, void *pAux, int argc, const char * const * argv, sqlite3_vtab **ppVTab, char **c) { return my_connect(db, pAux, argc, argv, ppVTab, c); } static int my_disconnect(sqlite3_vtab *pVTab) { sqlite3_free(pVTab); return SQLITE_OK; } static int my_destroy(sqlite3_vtab *pVTab) { sqlite3_free(pVTab); return SQLITE_OK; } typedef struct { sqlite3_vtab_cursor base; int index; picojson::value* rows; } cursor; static int my_open(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor) { MEMFILE* mf; CURL* curl; char* json; CURLcode res = CURLE_OK; char error[CURL_ERROR_SIZE] = {0}; char* cert_file = getenv("SSL_CERT_FILE"); mf = memfopen(); curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2); curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/7.29.0"); curl_easy_setopt(curl, CURLOPT_URL, "https://api.github.com/repositories"); if (cert_file) curl_easy_setopt(curl, CURLOPT_CAINFO, cert_file); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error); curl_easy_setopt(curl, CURLOPT_WRITEDATA, mf); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, memfwrite); res = curl_easy_perform(curl); curl_easy_cleanup(curl); if (res != CURLE_OK) { std::cerr << error << std::endl; return SQLITE_FAIL; } picojson::value* v = new picojson::value; std::string err; picojson::parse(*v, mf->data, mf->data + mf->size, &err); memfclose(mf); if (!err.empty()) { delete v; std::cerr << err << std::endl; return SQLITE_FAIL; } cursor *c = (cursor *)sqlite3_malloc(sizeof(cursor)); c->rows = v; c->index = 0; *ppCursor = &c->base; return SQLITE_OK; } static int my_close(cursor *c) { delete c->rows; sqlite3_free(c); return SQLITE_OK; } static int my_filter(cursor *c, int idxNum, const char *idxStr, int argc, sqlite3_value **argv) { c->index = 0; return SQLITE_OK; } static int my_next(cursor *c) { c->index++; return SQLITE_OK; } static int my_eof(cursor *c) { return c->index >= c->rows->get<picojson::array>().size() ? 1 : 0; } static int my_column(cursor *c, sqlite3_context *ctxt, int i) { picojson::value v = c->rows->get<picojson::array>()[c->index]; picojson::object row = v.get<picojson::object>(); const char* p = NULL; switch (i) { case 0: p = row["id"].to_str().c_str(); break; case 1: p = row["full_name"].to_str().c_str(); break; case 2: p = row["description"].to_str().c_str(); break; case 3: p = row["html_url"].to_str().c_str(); break; } sqlite3_result_text(ctxt, strdup(p), strlen(p), free); return SQLITE_OK; } static int my_rowid(cursor *c, sqlite3_int64 *pRowid) { *pRowid = c->index; return SQLITE_OK; } static int my_bestindex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo) { return SQLITE_OK; } static const sqlite3_module module = { 0, my_create, my_connect, my_bestindex, my_disconnect, my_destroy, my_open, (int (*)(sqlite3_vtab_cursor *)) my_close, (int (*)(sqlite3_vtab_cursor *, int, char const *, int, sqlite3_value **)) my_filter, (int (*)(sqlite3_vtab_cursor *)) my_next, (int (*)(sqlite3_vtab_cursor *)) my_eof, (int (*)(sqlite3_vtab_cursor *, sqlite3_context *, int)) my_column, (int (*)(sqlite3_vtab_cursor *, sqlite3_int64 *)) my_rowid, NULL, // my_update NULL, // my_begin NULL, // my_sync NULL, // my_commit NULL, // my_rollback NULL, // my_findfunction NULL, // my_rename }; static void destructor(void *arg) { return; } extern "C" { EXPORT int sqlite3_extension_init(sqlite3 *db, char **errmsg, const sqlite3_api_routines *api) { SQLITE_EXTENSION_INIT2(api); sqlite3_create_module_v2(db, "github", &module, NULL, destructor); return 0; } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_vtable/picojson.h����������������������0000644�0610621�0607500�00000066574�13172163427�030326� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * Copyright 2009-2010 Cybozu Labs, Inc. * Copyright 2011 Kazuho Oku * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY CYBOZU LABS, INC. ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL CYBOZU LABS, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of Cybozu Labs, Inc. * */ #ifndef picojson_h #define picojson_h #include <algorithm> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <iterator> #include <map> #include <string> #include <vector> #ifdef _MSC_VER #define SNPRINTF _snprintf_s #pragma warning(push) #pragma warning(disable : 4244) // conversion from int to char #else #define SNPRINTF snprintf #endif namespace picojson { enum { null_type, boolean_type, number_type, string_type, array_type, object_type }; struct null {}; class value { public: typedef std::vector<value> array; typedef std::map<std::string, value> object; union _storage { bool boolean_; double number_; std::string* string_; array* array_; object* object_; }; protected: int type_; _storage u_; public: value(); value(int type, bool); explicit value(bool b); explicit value(double n); explicit value(const std::string& s); explicit value(const array& a); explicit value(const object& o); explicit value(const char* s); value(const char* s, size_t len); ~value(); value(const value& x); value& operator=(const value& x); void swap(value& x); template <typename T> bool is() const; template <typename T> const T& get() const; template <typename T> T& get(); bool evaluate_as_boolean() const; const value& get(size_t idx) const; const value& get(const std::string& key) const; bool contains(size_t idx) const; bool contains(const std::string& key) const; std::string to_str() const; template <typename Iter> void serialize(Iter os) const; std::string serialize() const; private: template <typename T> value(const T*); // intentionally defined to block implicit conversion of pointer to bool }; typedef value::array array; typedef value::object object; inline value::value() : type_(null_type) {} inline value::value(int type, bool) : type_(type) { switch (type) { #define INIT(p, v) case p##type: u_.p = v; break INIT(boolean_, false); INIT(number_, 0.0); INIT(string_, new std::string()); INIT(array_, new array()); INIT(object_, new object()); #undef INIT default: break; } } inline value::value(bool b) : type_(boolean_type) { u_.boolean_ = b; } inline value::value(double n) : type_(number_type) { u_.number_ = n; } inline value::value(const std::string& s) : type_(string_type) { u_.string_ = new std::string(s); } inline value::value(const array& a) : type_(array_type) { u_.array_ = new array(a); } inline value::value(const object& o) : type_(object_type) { u_.object_ = new object(o); } inline value::value(const char* s) : type_(string_type) { u_.string_ = new std::string(s); } inline value::value(const char* s, size_t len) : type_(string_type) { u_.string_ = new std::string(s, len); } inline value::~value() { switch (type_) { #define DEINIT(p) case p##type: delete u_.p; break DEINIT(string_); DEINIT(array_); DEINIT(object_); #undef DEINIT default: break; } } inline value::value(const value& x) : type_(x.type_) { switch (type_) { #define INIT(p, v) case p##type: u_.p = v; break INIT(string_, new std::string(*x.u_.string_)); INIT(array_, new array(*x.u_.array_)); INIT(object_, new object(*x.u_.object_)); #undef INIT default: u_ = x.u_; break; } } inline value& value::operator=(const value& x) { if (this != &x) { this->~value(); new (this) value(x); } return *this; } inline void value::swap(value& x) { std::swap(type_, x.type_); std::swap(u_, x.u_); } #define IS(ctype, jtype) \ template <> inline bool value::is<ctype>() const { \ return type_ == jtype##_type; \ } IS(null, null) IS(bool, boolean) IS(int, number) IS(double, number) IS(std::string, string) IS(array, array) IS(object, object) #undef IS #define GET(ctype, var) \ template <> inline const ctype& value::get<ctype>() const { \ assert("type mismatch! call vis<type>() before get<type>()" \ && is<ctype>()); \ return var; \ } \ template <> inline ctype& value::get<ctype>() { \ assert("type mismatch! call is<type>() before get<type>()" \ && is<ctype>()); \ return var; \ } GET(bool, u_.boolean_) GET(double, u_.number_) GET(std::string, *u_.string_) GET(array, *u_.array_) GET(object, *u_.object_) #undef GET inline bool value::evaluate_as_boolean() const { switch (type_) { case null_type: return false; case boolean_type: return u_.boolean_; case number_type: return u_.number_ != 0; case string_type: return ! u_.string_->empty(); default: return true; } } inline const value& value::get(size_t idx) const { static value s_null; assert(is<array>()); return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null; } inline const value& value::get(const std::string& key) const { static value s_null; assert(is<object>()); object::const_iterator i = u_.object_->find(key); return i != u_.object_->end() ? i->second : s_null; } inline bool value::contains(size_t idx) const { assert(is<array>()); return idx < u_.array_->size(); } inline bool value::contains(const std::string& key) const { assert(is<object>()); object::const_iterator i = u_.object_->find(key); return i != u_.object_->end(); } inline std::string value::to_str() const { switch (type_) { case null_type: return "null"; case boolean_type: return u_.boolean_ ? "true" : "false"; case number_type: { char buf[256]; double tmp; SNPRINTF(buf, sizeof(buf), fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g", u_.number_); return buf; } case string_type: return *u_.string_; case array_type: return "array"; case object_type: return "object"; default: assert(0); #ifdef _MSC_VER __assume(0); #endif } return std::string(); } template <typename Iter> void copy(const std::string& s, Iter oi) { std::copy(s.begin(), s.end(), oi); } template <typename Iter> void serialize_str(const std::string& s, Iter oi) { *oi++ = '"'; for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) { switch (*i) { #define MAP(val, sym) case val: copy(sym, oi); break MAP('"', "\\\""); MAP('\\', "\\\\"); MAP('/', "\\/"); MAP('\b', "\\b"); MAP('\f', "\\f"); MAP('\n', "\\n"); MAP('\r', "\\r"); MAP('\t', "\\t"); #undef MAP default: if ((unsigned char)*i < 0x20 || *i == 0x7f) { char buf[7]; SNPRINTF(buf, sizeof(buf), "\\u%04x", *i & 0xff); copy(buf, buf + 6, oi); } else { *oi++ = *i; } break; } } *oi++ = '"'; } template <typename Iter> void value::serialize(Iter oi) const { switch (type_) { case string_type: serialize_str(*u_.string_, oi); break; case array_type: { *oi++ = '['; for (array::const_iterator i = u_.array_->begin(); i != u_.array_->end(); ++i) { if (i != u_.array_->begin()) { *oi++ = ','; } i->serialize(oi); } *oi++ = ']'; break; } case object_type: { *oi++ = '{'; for (object::const_iterator i = u_.object_->begin(); i != u_.object_->end(); ++i) { if (i != u_.object_->begin()) { *oi++ = ','; } serialize_str(i->first, oi); *oi++ = ':'; i->second.serialize(oi); } *oi++ = '}'; break; } default: copy(to_str(), oi); break; } } inline std::string value::serialize() const { std::string s; serialize(std::back_inserter(s)); return s; } template <typename Iter> class input { protected: Iter cur_, end_; int last_ch_; bool ungot_; int line_; public: input(const Iter& first, const Iter& last) : cur_(first), end_(last), last_ch_(-1), ungot_(false), line_(1) {} int getc() { if (ungot_) { ungot_ = false; return last_ch_; } if (cur_ == end_) { last_ch_ = -1; return -1; } if (last_ch_ == '\n') { line_++; } last_ch_ = *cur_++ & 0xff; return last_ch_; } void ungetc() { if (last_ch_ != -1) { assert(! ungot_); ungot_ = true; } } Iter cur() const { return cur_; } int line() const { return line_; } void skip_ws() { while (1) { int ch = getc(); if (! (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) { ungetc(); break; } } } bool expect(int expect) { skip_ws(); if (getc() != expect) { ungetc(); return false; } return true; } bool match(const std::string& pattern) { for (std::string::const_iterator pi(pattern.begin()); pi != pattern.end(); ++pi) { if (getc() != *pi) { ungetc(); return false; } } return true; } }; template<typename Iter> inline int _parse_quadhex(input<Iter> &in) { int uni_ch = 0, hex; for (int i = 0; i < 4; i++) { if ((hex = in.getc()) == -1) { return -1; } if ('0' <= hex && hex <= '9') { hex -= '0'; } else if ('A' <= hex && hex <= 'F') { hex -= 'A' - 0xa; } else if ('a' <= hex && hex <= 'f') { hex -= 'a' - 0xa; } else { in.ungetc(); return -1; } uni_ch = uni_ch * 16 + hex; } return uni_ch; } template<typename String, typename Iter> inline bool _parse_codepoint(String& out, input<Iter>& in) { int uni_ch; if ((uni_ch = _parse_quadhex(in)) == -1) { return false; } if (0xd800 <= uni_ch && uni_ch <= 0xdfff) { if (0xdc00 <= uni_ch) { // a second 16-bit of a surrogate pair appeared return false; } // first 16-bit of surrogate pair, get the next one if (in.getc() != '\\' || in.getc() != 'u') { in.ungetc(); return false; } int second = _parse_quadhex(in); if (! (0xdc00 <= second && second <= 0xdfff)) { return false; } uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff); uni_ch += 0x10000; } if (uni_ch < 0x80) { out.push_back(uni_ch); } else { if (uni_ch < 0x800) { out.push_back(0xc0 | (uni_ch >> 6)); } else { if (uni_ch < 0x10000) { out.push_back(0xe0 | (uni_ch >> 12)); } else { out.push_back(0xf0 | (uni_ch >> 18)); out.push_back(0x80 | ((uni_ch >> 12) & 0x3f)); } out.push_back(0x80 | ((uni_ch >> 6) & 0x3f)); } out.push_back(0x80 | (uni_ch & 0x3f)); } return true; } template<typename String, typename Iter> inline bool _parse_string(String& out, input<Iter>& in) { while (1) { int ch = in.getc(); if (ch < ' ') { in.ungetc(); return false; } else if (ch == '"') { return true; } else if (ch == '\\') { if ((ch = in.getc()) == -1) { return false; } switch (ch) { #define MAP(sym, val) case sym: out.push_back(val); break MAP('"', '\"'); MAP('\\', '\\'); MAP('/', '/'); MAP('b', '\b'); MAP('f', '\f'); MAP('n', '\n'); MAP('r', '\r'); MAP('t', '\t'); #undef MAP case 'u': if (! _parse_codepoint(out, in)) { return false; } break; default: return false; } } else { out.push_back(ch); } } return false; } template <typename Context, typename Iter> inline bool _parse_array(Context& ctx, input<Iter>& in) { if (! ctx.parse_array_start()) { return false; } size_t idx = 0; if (in.expect(']')) { return ctx.parse_array_stop(idx); } do { if (! ctx.parse_array_item(in, idx)) { return false; } idx++; } while (in.expect(',')); return in.expect(']') && ctx.parse_array_stop(idx); } template <typename Context, typename Iter> inline bool _parse_object(Context& ctx, input<Iter>& in) { if (! ctx.parse_object_start()) { return false; } if (in.expect('}')) { return true; } do { std::string key; if (! in.expect('"') || ! _parse_string(key, in) || ! in.expect(':')) { return false; } if (! ctx.parse_object_item(in, key)) { return false; } } while (in.expect(',')); return in.expect('}'); } template <typename Iter> inline bool _parse_number(double& out, input<Iter>& in) { std::string num_str; while (1) { int ch = in.getc(); if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == '.' || ch == 'e' || ch == 'E') { num_str.push_back(ch); } else { in.ungetc(); break; } } char* endp; out = strtod(num_str.c_str(), &endp); return endp == num_str.c_str() + num_str.size(); } template <typename Context, typename Iter> inline bool _parse(Context& ctx, input<Iter>& in) { in.skip_ws(); int ch = in.getc(); switch (ch) { #define IS(ch, text, op) case ch: \ if (in.match(text) && op) { \ return true; \ } else { \ return false; \ } IS('n', "ull", ctx.set_null()); IS('f', "alse", ctx.set_bool(false)); IS('t', "rue", ctx.set_bool(true)); #undef IS case '"': return ctx.parse_string(in); case '[': return _parse_array(ctx, in); case '{': return _parse_object(ctx, in); default: if (('0' <= ch && ch <= '9') || ch == '-') { in.ungetc(); double f; if (_parse_number(f, in)) { ctx.set_number(f); return true; } else { return false; } } break; } in.ungetc(); return false; } class deny_parse_context { public: bool set_null() { return false; } bool set_bool(bool) { return false; } bool set_number(double) { return false; } template <typename Iter> bool parse_string(input<Iter>&) { return false; } bool parse_array_start() { return false; } template <typename Iter> bool parse_array_item(input<Iter>&, size_t) { return false; } bool parse_array_stop(size_t) { return false; } bool parse_object_start() { return false; } template <typename Iter> bool parse_object_item(input<Iter>&, const std::string&) { return false; } }; class default_parse_context { protected: value* out_; public: default_parse_context(value* out) : out_(out) {} bool set_null() { *out_ = value(); return true; } bool set_bool(bool b) { *out_ = value(b); return true; } bool set_number(double f) { *out_ = value(f); return true; } template<typename Iter> bool parse_string(input<Iter>& in) { *out_ = value(string_type, false); return _parse_string(out_->get<std::string>(), in); } bool parse_array_start() { *out_ = value(array_type, false); return true; } template <typename Iter> bool parse_array_item(input<Iter>& in, size_t) { array& a = out_->get<array>(); a.push_back(value()); default_parse_context ctx(&a.back()); return _parse(ctx, in); } bool parse_array_stop(size_t) { return true; } bool parse_object_start() { *out_ = value(object_type, false); return true; } template <typename Iter> bool parse_object_item(input<Iter>& in, const std::string& key) { object& o = out_->get<object>(); default_parse_context ctx(&o[key]); return _parse(ctx, in); } private: default_parse_context(const default_parse_context&); default_parse_context& operator=(const default_parse_context&); }; class null_parse_context { public: struct dummy_str { void push_back(int) {} }; public: null_parse_context() {} bool set_null() { return true; } bool set_bool(bool) { return true; } bool set_number(double) { return true; } template <typename Iter> bool parse_string(input<Iter>& in) { dummy_str s; return _parse_string(s, in); } bool parse_array_start() { return true; } template <typename Iter> bool parse_array_item(input<Iter>& in, size_t) { return _parse(*this, in); } bool parse_array_stop(size_t) { return true; } bool parse_object_start() { return true; } template <typename Iter> bool parse_object_item(input<Iter>& in, const std::string&) { return _parse(*this, in); } private: null_parse_context(const null_parse_context&); null_parse_context& operator=(const null_parse_context&); }; // obsolete, use the version below template <typename Iter> inline std::string parse(value& out, Iter& pos, const Iter& last) { std::string err; pos = parse(out, pos, last, &err); return err; } template <typename Context, typename Iter> inline Iter _parse(Context& ctx, const Iter& first, const Iter& last, std::string* err) { input<Iter> in(first, last); if (! _parse(ctx, in) && err != NULL) { char buf[64]; SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line()); *err = buf; while (1) { int ch = in.getc(); if (ch == -1 || ch == '\n') { break; } else if (ch >= ' ') { err->push_back(ch); } } } return in.cur(); } template <typename Iter> inline Iter parse(value& out, const Iter& first, const Iter& last, std::string* err) { default_parse_context ctx(&out); return _parse(ctx, first, last, err); } inline std::string parse(value& out, std::istream& is) { std::string err; parse(out, std::istreambuf_iterator<char>(is.rdbuf()), std::istreambuf_iterator<char>(), &err); return err; } template <typename T> struct last_error_t { static std::string s; }; template <typename T> std::string last_error_t<T>::s; inline void set_last_error(const std::string& s) { last_error_t<bool>::s = s; } inline const std::string& get_last_error() { return last_error_t<bool>::s; } inline bool operator==(const value& x, const value& y) { if (x.is<null>()) return y.is<null>(); #define PICOJSON_CMP(type) \ if (x.is<type>()) \ return y.is<type>() && x.get<type>() == y.get<type>() PICOJSON_CMP(bool); PICOJSON_CMP(double); PICOJSON_CMP(std::string); PICOJSON_CMP(array); PICOJSON_CMP(object); #undef PICOJSON_CMP assert(0); #ifdef _MSC_VER __assume(0); #endif return false; } inline bool operator!=(const value& x, const value& y) { return ! (x == y); } } namespace std { template<> inline void swap(picojson::value& x, picojson::value& y) { x.swap(y); } } inline std::istream& operator>>(std::istream& is, picojson::value& x) { picojson::set_last_error(std::string()); std::string err = picojson::parse(x, is); if (! err.empty()) { picojson::set_last_error(err); is.setstate(std::ios::failbit); } return is; } inline std::ostream& operator<<(std::ostream& os, const picojson::value& x) { x.serialize(std::ostream_iterator<char>(os)); return os; } #ifdef _MSC_VER #pragma warning(pop) #endif #endif #ifdef TEST_PICOJSON #ifdef _MSC_VER #pragma warning(disable : 4127) // conditional expression is constant #endif using namespace std; static void plan(int num) { printf("1..%d\n", num); } static bool success = true; static void ok(bool b, const char* name = "") { static int n = 1; if (! b) success = false; printf("%s %d - %s\n", b ? "ok" : "ng", n++, name); } template <typename T> void is(const T& x, const T& y, const char* name = "") { if (x == y) { ok(true, name); } else { ok(false, name); } } #include <algorithm> #include <sstream> #include <float.h> #include <limits.h> int main(void) { plan(85); // constructors #define TEST(expr, expected) \ is(picojson::value expr .serialize(), string(expected), "picojson::value" #expr) TEST( (true), "true"); TEST( (false), "false"); TEST( (42.0), "42"); TEST( (string("hello")), "\"hello\""); TEST( ("hello"), "\"hello\""); TEST( ("hello", 4), "\"hell\""); { double a = 1; for (int i = 0; i < 1024; i++) { picojson::value vi(a); std::stringstream ss; ss << vi; picojson::value vo; ss >> vo; double b = vo.get<double>(); if ((i < 53 && a != b) || fabs(a - b) / b > 1e-8) { printf("ng i=%d a=%.18e b=%.18e\n", i, a, b); } a *= 2; } } #undef TEST #define TEST(in, type, cmp, serialize_test) { \ picojson::value v; \ const char* s = in; \ string err = picojson::parse(v, s, s + strlen(s)); \ ok(err.empty(), in " no error"); \ ok(v.is<type>(), in " check type"); \ is<type>(v.get<type>(), cmp, in " correct output"); \ is(*s, '\0', in " read to eof"); \ if (serialize_test) { \ is(v.serialize(), string(in), in " serialize"); \ } \ } TEST("false", bool, false, true); TEST("true", bool, true, true); TEST("90.5", double, 90.5, false); TEST("1.7976931348623157e+308", double, DBL_MAX, false); TEST("\"hello\"", string, string("hello"), true); TEST("\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"", string, string("\"\\/\b\f\n\r\t"), true); TEST("\"\\u0061\\u30af\\u30ea\\u30b9\"", string, string("a\xe3\x82\xaf\xe3\x83\xaa\xe3\x82\xb9"), false); TEST("\"\\ud840\\udc0b\"", string, string("\xf0\xa0\x80\x8b"), false); #undef TEST #define TEST(type, expr) { \ picojson::value v; \ const char *s = expr; \ string err = picojson::parse(v, s, s + strlen(s)); \ ok(err.empty(), "empty " #type " no error"); \ ok(v.is<picojson::type>(), "empty " #type " check type"); \ ok(v.get<picojson::type>().empty(), "check " #type " array size"); \ } TEST(array, "[]"); TEST(object, "{}"); #undef TEST { picojson::value v; const char *s = "[1,true,\"hello\"]"; string err = picojson::parse(v, s, s + strlen(s)); ok(err.empty(), "array no error"); ok(v.is<picojson::array>(), "array check type"); is(v.get<picojson::array>().size(), size_t(3), "check array size"); ok(v.contains(0), "check contains array[0]"); ok(v.get(0).is<double>(), "check array[0] type"); is(v.get(0).get<double>(), 1.0, "check array[0] value"); ok(v.contains(1), "check contains array[1]"); ok(v.get(1).is<bool>(), "check array[1] type"); ok(v.get(1).get<bool>(), "check array[1] value"); ok(v.contains(2), "check contains array[2]"); ok(v.get(2).is<string>(), "check array[2] type"); is(v.get(2).get<string>(), string("hello"), "check array[2] value"); ok(!v.contains(3), "check not contains array[3]"); } { picojson::value v; const char *s = "{ \"a\": true }"; string err = picojson::parse(v, s, s + strlen(s)); ok(err.empty(), "object no error"); ok(v.is<picojson::object>(), "object check type"); is(v.get<picojson::object>().size(), size_t(1), "check object size"); ok(v.contains("a"), "check contains property"); ok(v.get("a").is<bool>(), "check bool property exists"); is(v.get("a").get<bool>(), true, "check bool property value"); is(v.serialize(), string("{\"a\":true}"), "serialize object"); ok(!v.contains("z"), "check not contains property"); } #define TEST(json, msg) do { \ picojson::value v; \ const char *s = json; \ string err = picojson::parse(v, s, s + strlen(s)); \ is(err, string("syntax error at line " msg), msg); \ } while (0) TEST("falsoa", "1 near: oa"); TEST("{]", "1 near: ]"); TEST("\n\bbell", "2 near: bell"); TEST("\"abc\nd\"", "1 near: "); #undef TEST { picojson::value v1, v2; const char *s; string err; s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }"; err = picojson::parse(v1, s, s + strlen(s)); s = "{ \"d\": 2.0, \"b\": true, \"a\": [1,2,\"three\"] }"; err = picojson::parse(v2, s, s + strlen(s)); ok((v1 == v2), "check == operator in deep comparison"); } { picojson::value v1, v2; const char *s; string err; s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }"; err = picojson::parse(v1, s, s + strlen(s)); s = "{ \"d\": 2.0, \"a\": [1,\"three\"], \"b\": true }"; err = picojson::parse(v2, s, s + strlen(s)); ok((v1 != v2), "check != operator for array in deep comparison"); } { picojson::value v1, v2; const char *s; string err; s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }"; err = picojson::parse(v1, s, s + strlen(s)); s = "{ \"d\": 2.0, \"a\": [1,2,\"three\"], \"b\": false }"; err = picojson::parse(v2, s, s + strlen(s)); ok((v1 != v2), "check != operator for object in deep comparison"); } { picojson::value v1, v2; const char *s; string err; s = "{ \"b\": true, \"a\": [1,2,\"three\"], \"d\": 2 }"; err = picojson::parse(v1, s, s + strlen(s)); picojson::object& o = v1.get<picojson::object>(); o.erase("b"); picojson::array& a = o["a"].get<picojson::array>(); picojson::array::iterator i; i = std::remove(a.begin(), a.end(), picojson::value(std::string("three"))); a.erase(i, a.end()); s = "{ \"a\": [1,2], \"d\": 2 }"; err = picojson::parse(v2, s, s + strlen(s)); ok((v1 == v2), "check erase()"); } ok(picojson::value(3.0).serialize() == "3", "integral number should be serialized as a integer"); { const char* s = "{ \"a\": [1,2], \"d\": 2 }"; picojson::null_parse_context ctx; string err; picojson::_parse(ctx, s, s + strlen(s), &err); ok(err.empty(), "null_parse_context"); } { picojson::value v1, v2; v1 = picojson::value(true); swap(v1, v2); ok(v1.is<picojson::null>(), "swap (null)"); ok(v2.get<bool>() == true, "swap (bool)"); v1 = picojson::value("a"); v2 = picojson::value(1.0); swap(v1, v2); ok(v1.get<double>() == 1.0, "swap (dobule)"); ok(v2.get<string>() == "a", "swap (string)"); v1 = picojson::value(picojson::object()); v2 = picojson::value(picojson::array()); swap(v1, v2); ok(v1.is<picojson::array>(), "swap (array)"); ok(v2.is<picojson::object>(), "swap (object)"); } return success ? 0 : 1; } #endif ������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_vtable/extension.go��������������������0000644�0610621�0607500�00000001405�13172163427�030652� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "fmt" "log" "github.com/mattn/go-sqlite3" ) func main() { sql.Register("sqlite3_with_extensions", &sqlite3.SQLiteDriver{ Extensions: []string{ "sqlite3_mod_vtable", }, }) db, err := sql.Open("sqlite3_with_extensions", ":memory:") if err != nil { log.Fatal(err) } defer db.Close() db.Exec("create virtual table repo using github(id, full_name, description, html_url)") rows, err := db.Query("select id, full_name, description, html_url from repo") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var id, fullName, description, htmlURL string rows.Scan(&id, &fullName, &description, &htmlURL) fmt.Printf("%s: %s\n\t%s\n\t%s\n\n", id, fullName, description, htmlURL) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_vtable/Makefile������������������������0000644�0610621�0607500�00000000560�13172163427�027750� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ifeq ($(OS),Windows_NT) EXE=extension.exe EXT=sqlite3_mod_vtable.dll RM=cmd /c del LIBCURL=-lcurldll LDFLAG= else EXE=extension EXT=sqlite3_mod_vtable.so RM=rm LDFLAG=-fPIC LIBCURL=-lcurl endif all : $(EXE) $(EXT) $(EXE) : extension.go go build $< $(EXT) : sqlite3_mod_vtable.cc g++ $(LDFLAG) -shared -o $@ $< -lsqlite3 $(LIBCURL) clean : @-$(RM) $(EXE) $(EXT) ������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_regexp/��������������������������������0000755�0610621�0607500�00000000000�13172163427�026324� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_regexp/sqlite3_mod_regexp.c������������0000644�0610621�0607500�00000001702�13172163427�032265� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#include <pcre.h> #include <string.h> #include <stdio.h> #include <sqlite3ext.h> SQLITE_EXTENSION_INIT1 static void regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv) { if (argc >= 2) { const char *target = (const char *)sqlite3_value_text(argv[1]); const char *pattern = (const char *)sqlite3_value_text(argv[0]); const char* errstr = NULL; int erroff = 0; int vec[500]; int n, rc; pcre* re = pcre_compile(pattern, 0, &errstr, &erroff, NULL); rc = pcre_exec(re, NULL, target, strlen(target), 0, 0, vec, 500); if (rc <= 0) { sqlite3_result_error(context, errstr, 0); return; } sqlite3_result_int(context, 1); } } #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_extension_init(sqlite3 *db, char **errmsg, const sqlite3_api_routines *api) { SQLITE_EXTENSION_INIT2(api); return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, (void*)db, regexp_func, NULL, NULL); } ��������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_regexp/extension.go��������������������0000644�0610621�0607500�00000001436�13172163427�030673� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "fmt" "github.com/mattn/go-sqlite3" "log" ) func main() { sql.Register("sqlite3_with_extensions", &sqlite3.SQLiteDriver{ Extensions: []string{ "sqlite3_mod_regexp", }, }) db, err := sql.Open("sqlite3_with_extensions", ":memory:") if err != nil { log.Fatal(err) } defer db.Close() // Force db to make a new connection in pool // by putting the original in a transaction tx, err := db.Begin() if err != nil { log.Fatal(err) } defer tx.Commit() // New connection works (hopefully!) rows, err := db.Query("select 'hello world' where 'hello world' regexp '^hello.*d$'") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var helloworld string rows.Scan(&helloworld) fmt.Println(helloworld) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/mod_regexp/Makefile������������������������0000644�0610621�0607500�00000000512�13172163427�027762� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ifeq ($(OS),Windows_NT) EXE=extension.exe EXT=sqlite3_mod_regexp.dll RM=cmd /c del LDFLAG= else EXE=extension EXT=sqlite3_mod_regexp.so RM=rm LDFLAG=-fPIC endif all : $(EXE) $(EXT) $(EXE) : extension.go go build $< $(EXT) : sqlite3_mod_regexp.c gcc $(LDFLAG) -shared -o $@ $< -lsqlite3 -lpcre clean : @-$(RM) $(EXE) $(EXT) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/hook/��������������������������������������0000755�0610621�0607500�00000000000�13172163427�025133� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/hook/hook.go�������������������������������0000644�0610621�0607500�00000003110�13172163427�026415� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "log" "os" "github.com/mattn/go-sqlite3" ) func main() { sqlite3conn := []*sqlite3.SQLiteConn{} sql.Register("sqlite3_with_hook_example", &sqlite3.SQLiteDriver{ ConnectHook: func(conn *sqlite3.SQLiteConn) error { sqlite3conn = append(sqlite3conn, conn) conn.RegisterUpdateHook(func(op int, db string, table string, rowid int64) { switch op { case sqlite3.SQLITE_INSERT: log.Println("Notified of insert on db", db, "table", table, "rowid", rowid) } }) return nil }, }) os.Remove("./foo.db") os.Remove("./bar.db") srcDb, err := sql.Open("sqlite3_with_hook_example", "./foo.db") if err != nil { log.Fatal(err) } defer srcDb.Close() srcDb.Ping() _, err = srcDb.Exec("create table foo(id int, value text)") if err != nil { log.Fatal(err) } _, err = srcDb.Exec("insert into foo values(1, 'foo')") if err != nil { log.Fatal(err) } _, err = srcDb.Exec("insert into foo values(2, 'bar')") if err != nil { log.Fatal(err) } _, err = srcDb.Query("select * from foo") if err != nil { log.Fatal(err) } destDb, err := sql.Open("sqlite3_with_hook_example", "./bar.db") if err != nil { log.Fatal(err) } defer destDb.Close() destDb.Ping() bk, err := sqlite3conn[1].Backup("main", sqlite3conn[0], "main") if err != nil { log.Fatal(err) } _, err = bk.Step(-1) if err != nil { log.Fatal(err) } _, err = destDb.Query("select * from foo") if err != nil { log.Fatal(err) } _, err = destDb.Exec("insert into foo values(3, 'bar')") if err != nil { log.Fatal(err) } bk.Finish() } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/custom_func/�������������������������������0000755�0610621�0607500�00000000000�13172163427�026520� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/_example/custom_func/main.go������������������������0000644�0610621�0607500�00000005571�13172163427�030003� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "fmt" "log" "math" "math/rand" sqlite "github.com/mattn/go-sqlite3" ) // Computes x^y func pow(x, y int64) int64 { return int64(math.Pow(float64(x), float64(y))) } // Computes the bitwise exclusive-or of all its arguments func xor(xs ...int64) int64 { var ret int64 for _, x := range xs { ret ^= x } return ret } // Returns a random number. It's actually deterministic here because // we don't seed the RNG, but it's an example of a non-pure function // from SQLite's POV. func getrand() int64 { return rand.Int63() } // Computes the standard deviation of a GROUPed BY set of values type stddev struct { xs []int64 // Running average calculation sum int64 n int64 } func newStddev() *stddev { return &stddev{} } func (s *stddev) Step(x int64) { s.xs = append(s.xs, x) s.sum += x s.n++ } func (s *stddev) Done() float64 { mean := float64(s.sum) / float64(s.n) var sqDiff []float64 for _, x := range s.xs { sqDiff = append(sqDiff, math.Pow(float64(x)-mean, 2)) } var dev float64 for _, x := range sqDiff { dev += x } dev /= float64(len(sqDiff)) return math.Sqrt(dev) } func main() { sql.Register("sqlite3_custom", &sqlite.SQLiteDriver{ ConnectHook: func(conn *sqlite.SQLiteConn) error { if err := conn.RegisterFunc("pow", pow, true); err != nil { return err } if err := conn.RegisterFunc("xor", xor, true); err != nil { return err } if err := conn.RegisterFunc("rand", getrand, false); err != nil { return err } if err := conn.RegisterAggregator("stddev", newStddev, true); err != nil { return err } return nil }, }) db, err := sql.Open("sqlite3_custom", ":memory:") if err != nil { log.Fatal("Failed to open database:", err) } defer db.Close() var i int64 err = db.QueryRow("SELECT pow(2,3)").Scan(&i) if err != nil { log.Fatal("POW query error:", err) } fmt.Println("pow(2,3) =", i) // 8 err = db.QueryRow("SELECT xor(1,2,3,4,5,6)").Scan(&i) if err != nil { log.Fatal("XOR query error:", err) } fmt.Println("xor(1,2,3,4,5) =", i) // 7 err = db.QueryRow("SELECT rand()").Scan(&i) if err != nil { log.Fatal("RAND query error:", err) } fmt.Println("rand() =", i) // pseudorandom _, err = db.Exec("create table foo (department integer, profits integer)") if err != nil { log.Fatal("Failed to create table:", err) } _, err = db.Exec("insert into foo values (1, 10), (1, 20), (1, 45), (2, 42), (2, 115)") if err != nil { log.Fatal("Failed to insert records:", err) } rows, err := db.Query("select department, stddev(profits) from foo group by department") if err != nil { log.Fatal("STDDEV query error:", err) } defer rows.Close() for rows.Next() { var dept int64 var dev float64 if err := rows.Scan(&dept, &dev); err != nil { log.Fatal(err) } fmt.Printf("dept=%d stddev=%f\n", dept, dev) } if err := rows.Err(); err != nil { log.Fatal(err) } } ���������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/README.md�������������������������������������������0000644�0610621�0607500�00000006643�13172163427�023671� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������go-sqlite3 ========== [![GoDoc Reference](https://godoc.org/github.com/mattn/go-sqlite3?status.svg)](http://godoc.org/github.com/mattn/go-sqlite3) [![Build Status](https://travis-ci.org/mattn/go-sqlite3.svg?branch=master)](https://travis-ci.org/mattn/go-sqlite3) [![Coverage Status](https://coveralls.io/repos/mattn/go-sqlite3/badge.svg?branch=master)](https://coveralls.io/r/mattn/go-sqlite3?branch=master) [![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-sqlite3)](https://goreportcard.com/report/github.com/mattn/go-sqlite3) Description ----------- sqlite3 driver conforming to the built-in database/sql interface Installation ------------ This package can be installed with the go get command: go get github.com/mattn/go-sqlite3 _go-sqlite3_ is *cgo* package. If you want to build your app using go-sqlite3, you need gcc. However, if you install _go-sqlite3_ with `go install github.com/mattn/go-sqlite3`, you don't need gcc to build your app anymore. Documentation ------------- API documentation can be found here: http://godoc.org/github.com/mattn/go-sqlite3 Examples can be found under the `./_example` directory FAQ --- * Want to build go-sqlite3 with libsqlite3 on my linux. Use `go build --tags "libsqlite3 linux"` * Want to build go-sqlite3 with libsqlite3 on OS X. Install sqlite3 from homebrew: `brew install sqlite3` Use `go build --tags "libsqlite3 darwin"` * Want to build go-sqlite3 with icu extension. Use `go build --tags "icu"` Available extensions: `json1`, `fts5`, `icu` * Can't build go-sqlite3 on windows 64bit. > Probably, you are using go 1.0, go1.0 has a problem when it comes to compiling/linking on windows 64bit. > See: [#27](https://github.com/mattn/go-sqlite3/issues/27) * Getting insert error while query is opened. > You can pass some arguments into the connection string, for example, a URI. > See: [#39](https://github.com/mattn/go-sqlite3/issues/39) * Do you want to cross compile? mingw on Linux or Mac? > See: [#106](https://github.com/mattn/go-sqlite3/issues/106) > See also: http://www.limitlessfx.com/cross-compile-golang-app-for-windows-from-linux.html * Want to get time.Time with current locale Use `_loc=auto` in SQLite3 filename schema like `file:foo.db?_loc=auto`. * Can I use this in multiple routines concurrently? Yes for readonly. But, No for writable. See [#50](https://github.com/mattn/go-sqlite3/issues/50), [#51](https://github.com/mattn/go-sqlite3/issues/51), [#209](https://github.com/mattn/go-sqlite3/issues/209). * Why is it racy if I use a `sql.Open("sqlite3", ":memory:")` database? Each connection to :memory: opens a brand new in-memory sql database, so if the stdlib's sql engine happens to open another connection and you've only specified ":memory:", that connection will see a brand new database. A workaround is to use "file::memory:?mode=memory&cache=shared". Every connection to this string will point to the same in-memory database. See [#204](https://github.com/mattn/go-sqlite3/issues/204) for more info. License ------- MIT: http://mattn.mit-license.org/2012 sqlite3-binding.c, sqlite3-binding.h, sqlite3ext.h The -binding suffix was added to avoid build failures under gccgo. In this repository, those files are an amalgamation of code that was copied from SQLite3. The license of that code is the same as the license of SQLite3. Author ------ Yasuhiro Matsumoto (a.k.a mattn) ���������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/LICENSE���������������������������������������������0000644�0610621�0607500�00000002075�13172163427�023412� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The MIT License (MIT) Copyright (c) 2014 Yasuhiro Matsumoto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-sqlite3/.travis.yml�����������������������������������������0000644�0610621�0607500�00000000550�13172163427�024512� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go sudo: required dist: trusty env: - GOTAGS= - GOTAGS=libsqlite3 - GOTAGS=trace - GOTAGS=vtable go: - 1.7 - 1.8 - tip before_install: - go get github.com/mattn/goveralls - go get golang.org/x/tools/cmd/cover script: - $HOME/gopath/bin/goveralls -repotoken 3qJVUE0iQwqnCbmNcDsjYu1nh4J4KIFXx - go test -race -v . -tags "$GOTAGS" ��������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163420�023017� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/runewidth_windows.go������������������������������0000644�0610621�0607500�00000000640�13172163420�027131� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package runewidth import ( "syscall" ) var ( kernel32 = syscall.NewLazyDLL("kernel32") procGetConsoleOutputCP = kernel32.NewProc("GetConsoleOutputCP") ) // IsEastAsian return true if the current locale is CJK func IsEastAsian() bool { r1, _, _ := procGetConsoleOutputCP.Call() if r1 == 0 { return false } switch int(r1) { case 932, 51932, 936, 949, 950: return true } return false } ������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/runewidth_test.go���������������������������������0000644�0610621�0607500�00000014447�13172163420�026430� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package runewidth import ( "sort" "testing" ) var _ sort.Interface = (*table)(nil) func (t table) Len() int { return len(t) } func (t table) Less(i, j int) bool { return t[i].first < t[j].first } func (t *table) Swap(i, j int) { (*t)[i], (*t)[j] = (*t)[j], (*t)[i] } var tables = []table{ private, nonprint, combining, doublewidth, ambiguous, emoji, notassigned, neutral, } func TestSorted(t *testing.T) { for _, tbl := range tables { if !sort.IsSorted(&tbl) { t.Errorf("not sorted") } } } var runewidthtests = []struct { in rune out int eaout int }{ {'世', 2, 2}, {'界', 2, 2}, {'ï½¾', 1, 1}, {'ï½¶', 1, 1}, {'ï½²', 1, 1}, {'☆', 1, 2}, // double width in ambiguous {'\x00', 0, 0}, {'\x01', 0, 0}, {'\u0300', 0, 0}, {'\u2028', 0, 0}, {'\u2029', 0, 0}, } func TestRuneWidth(t *testing.T) { c := NewCondition() c.EastAsianWidth = false for _, tt := range runewidthtests { if out := c.RuneWidth(tt.in); out != tt.out { t.Errorf("RuneWidth(%q) = %d, want %d", tt.in, out, tt.out) } } c.EastAsianWidth = true for _, tt := range runewidthtests { if out := c.RuneWidth(tt.in); out != tt.eaout { t.Errorf("RuneWidth(%q) = %d, want %d", tt.in, out, tt.eaout) } } } var isambiguouswidthtests = []struct { in rune out bool }{ {'世', false}, {'â– ', true}, {'界', false}, {'â—‹', true}, {'㈱', false}, {'â‘ ', true}, {'â‘¡', true}, {'â‘¢', true}, {'â‘£', true}, {'⑤', true}, {'â‘¥', true}, {'⑦', true}, {'â‘§', true}, {'⑨', true}, {'â‘©', true}, {'⑪', true}, {'â‘«', true}, {'⑬', true}, {'â‘­', true}, {'â‘®', true}, {'⑯', true}, {'â‘°', true}, {'⑱', true}, {'⑲', true}, {'⑳', true}, {'☆', true}, } func TestIsAmbiguousWidth(t *testing.T) { for _, tt := range isambiguouswidthtests { if out := IsAmbiguousWidth(tt.in); out != tt.out { t.Errorf("IsAmbiguousWidth(%q) = %v, want %v", tt.in, out, tt.out) } } } var stringwidthtests = []struct { in string out int eaout int }{ {"■㈱ã®ä¸–界①", 10, 12}, {"スター☆", 7, 8}, {"ã¤ã®ã â˜†HIRO", 11, 12}, } func TestStringWidth(t *testing.T) { c := NewCondition() c.EastAsianWidth = false for _, tt := range stringwidthtests { if out := c.StringWidth(tt.in); out != tt.out { t.Errorf("StringWidth(%q) = %d, want %d", tt.in, out, tt.out) } } c.EastAsianWidth = true for _, tt := range stringwidthtests { if out := c.StringWidth(tt.in); out != tt.eaout { t.Errorf("StringWidth(%q) = %d, want %d", tt.in, out, tt.eaout) } } } func TestStringWidthInvalid(t *testing.T) { s := "ã“ã‚“ã«ã¡ã‚\x00世界" if out := StringWidth(s); out != 14 { t.Errorf("StringWidth(%q) = %d, want %d", s, out, 14) } } func TestTruncateSmaller(t *testing.T) { s := "ã‚ã„ã†ãˆãŠ" expected := "ã‚ã„ã†ãˆãŠ" if out := Truncate(s, 10, "..."); out != expected { t.Errorf("Truncate(%q) = %q, want %q", s, out, expected) } } func TestTruncate(t *testing.T) { s := "ã‚ã„ã†ãˆãŠã‚ã„ã†ãˆãŠãˆãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠ" expected := "ã‚ã„ã†ãˆãŠã‚ã„ã†ãˆãŠãˆãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠ..." out := Truncate(s, 80, "...") if out != expected { t.Errorf("Truncate(%q) = %q, want %q", s, out, expected) } width := StringWidth(out) if width != 79 { t.Errorf("width of Truncate(%q) should be %d, but %d", s, 79, width) } } func TestTruncateFit(t *testing.T) { s := "aã‚ã„ã†ãˆãŠã‚ã„ã†ãˆãŠãˆãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠ" expected := "aã‚ã„ã†ãˆãŠã‚ã„ã†ãˆãŠãˆãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠ..." out := Truncate(s, 80, "...") if out != expected { t.Errorf("Truncate(%q) = %q, want %q", s, out, expected) } width := StringWidth(out) if width != 80 { t.Errorf("width of Truncate(%q) should be %d, but %d", s, 80, width) } } func TestTruncateJustFit(t *testing.T) { s := "ã‚ã„ã†ãˆãŠã‚ã„ã†ãˆãŠãˆãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠ" expected := "ã‚ã„ã†ãˆãŠã‚ã„ã†ãˆãŠãˆãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠãŠ" out := Truncate(s, 80, "...") if out != expected { t.Errorf("Truncate(%q) = %q, want %q", s, out, expected) } width := StringWidth(out) if width != 80 { t.Errorf("width of Truncate(%q) should be %d, but %d", s, 80, width) } } func TestWrap(t *testing.T) { s := `æ±äº¬ç‰¹è¨±è¨±å¯å±€å±€é•·ã¯ã‚ˆã柿喰ã†å®¢ã /æ±äº¬ç‰¹è¨±è¨±å¯å±€å±€é•·ã¯ã‚ˆã柿喰ã†å®¢ã  123456789012345678901234567890 END` expected := `æ±äº¬ç‰¹è¨±è¨±å¯å±€å±€é•·ã¯ã‚ˆã柿喰ㆠ客ã /æ±äº¬ç‰¹è¨±è¨±å¯å±€å±€é•·ã¯ã‚ˆã 柿喰ã†å®¢ã  123456789012345678901234567890 END` if out := Wrap(s, 30); out != expected { t.Errorf("Wrap(%q) = %q, want %q", s, out, expected) } } func TestTruncateNoNeeded(t *testing.T) { s := "ã‚ã„ã†ãˆãŠã‚ã„" expected := "ã‚ã„ã†ãˆãŠã‚ã„" if out := Truncate(s, 80, "..."); out != expected { t.Errorf("Truncate(%q) = %q, want %q", s, out, expected) } } var isneutralwidthtests = []struct { in rune out bool }{ {'→', false}, {'┊', false}, {'┈', false}, {'~', false}, {'â””', false}, {'⣀', true}, {'⣀', true}, } func TestIsNeutralWidth(t *testing.T) { for _, tt := range isneutralwidthtests { if out := IsNeutralWidth(tt.in); out != tt.out { t.Errorf("IsNeutralWidth(%q) = %v, want %v", tt.in, out, tt.out) } } } func TestFillLeft(t *testing.T) { s := "ã‚xã„ã†ãˆãŠ" expected := " ã‚xã„ã†ãˆãŠ" if out := FillLeft(s, 15); out != expected { t.Errorf("FillLeft(%q) = %q, want %q", s, out, expected) } } func TestFillLeftFit(t *testing.T) { s := "ã‚ã„ã†ãˆãŠ" expected := "ã‚ã„ã†ãˆãŠ" if out := FillLeft(s, 10); out != expected { t.Errorf("FillLeft(%q) = %q, want %q", s, out, expected) } } func TestFillRight(t *testing.T) { s := "ã‚xã„ã†ãˆãŠ" expected := "ã‚xã„ã†ãˆãŠ " if out := FillRight(s, 15); out != expected { t.Errorf("FillRight(%q) = %q, want %q", s, out, expected) } } func TestFillRightFit(t *testing.T) { s := "ã‚ã„ã†ãˆãŠ" expected := "ã‚ã„ã†ãˆãŠ" if out := FillRight(s, 10); out != expected { t.Errorf("FillRight(%q) = %q, want %q", s, out, expected) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/runewidth_posix.go��������������������������������0000644�0610621�0607500�00000002540�13172163420�026602� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows,!js package runewidth import ( "os" "regexp" "strings" ) var reLoc = regexp.MustCompile(`^[a-z][a-z][a-z]?(?:_[A-Z][A-Z])?\.(.+)`) var mblenTable = map[string]int{ "utf-8": 6, "utf8": 6, "jis": 8, "eucjp": 3, "euckr": 2, "euccn": 2, "sjis": 2, "cp932": 2, "cp51932": 2, "cp936": 2, "cp949": 2, "cp950": 2, "big5": 2, "gbk": 2, "gb2312": 2, } func isEastAsian(locale string) bool { charset := strings.ToLower(locale) r := reLoc.FindStringSubmatch(locale) if len(r) == 2 { charset = strings.ToLower(r[1]) } if strings.HasSuffix(charset, "@cjk_narrow") { return false } for pos, b := range []byte(charset) { if b == '@' { charset = charset[:pos] break } } max := 1 if m, ok := mblenTable[charset]; ok { max = m } if max > 1 && (charset[0] != 'u' || strings.HasPrefix(locale, "ja") || strings.HasPrefix(locale, "ko") || strings.HasPrefix(locale, "zh")) { return true } return false } // IsEastAsian return true if the current locale is CJK func IsEastAsian() bool { locale := os.Getenv("LC_CTYPE") if locale == "" { locale = os.Getenv("LANG") } // ignore C locale if locale == "POSIX" || locale == "C" { return false } if len(locale) > 1 && locale[0] == 'C' && (locale[1] == '.' || locale[1] == '-') { return false } return isEastAsian(locale) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/runewidth_js.go�����������������������������������0000644�0610621�0607500�00000000251�13172163420�026051� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build js package runewidth func IsEastAsian() bool { // TODO: Implement this for the web. Detect east asian in a compatible way, and return true. return false } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/runewidth.go��������������������������������������0000644�0610621�0607500�00000167436�13172163420�025400� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package runewidth var ( // EastAsianWidth will be set true if the current locale is CJK EastAsianWidth = IsEastAsian() // DefaultCondition is a condition in current locale DefaultCondition = &Condition{EastAsianWidth} ) type interval struct { first rune last rune } type table []interval func inTables(r rune, ts ...table) bool { for _, t := range ts { if inTable(r, t) { return true } } return false } func inTable(r rune, t table) bool { // func (t table) IncludesRune(r rune) bool { if r < t[0].first { return false } bot := 0 top := len(t) - 1 for top >= bot { mid := (bot + top) / 2 switch { case t[mid].last < r: bot = mid + 1 case t[mid].first > r: top = mid - 1 default: return true } } return false } var private = table{ {0x00E000, 0x00F8FF}, {0x0F0000, 0x0FFFFD}, {0x100000, 0x10FFFD}, } var nonprint = table{ {0x0000, 0x001F}, {0x007F, 0x009F}, {0x00AD, 0x00AD}, {0x070F, 0x070F}, {0x180B, 0x180E}, {0x200B, 0x200F}, {0x2028, 0x2029}, {0x202A, 0x202E}, {0x206A, 0x206F}, {0xD800, 0xDFFF}, {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, {0xFFFE, 0xFFFF}, } var combining = table{ {0x0300, 0x036F}, {0x0483, 0x0489}, {0x0591, 0x05BD}, {0x05BF, 0x05BF}, {0x05C1, 0x05C2}, {0x05C4, 0x05C5}, {0x05C7, 0x05C7}, {0x0610, 0x061A}, {0x064B, 0x065F}, {0x0670, 0x0670}, {0x06D6, 0x06DC}, {0x06DF, 0x06E4}, {0x06E7, 0x06E8}, {0x06EA, 0x06ED}, {0x0711, 0x0711}, {0x0730, 0x074A}, {0x07A6, 0x07B0}, {0x07EB, 0x07F3}, {0x0816, 0x0819}, {0x081B, 0x0823}, {0x0825, 0x0827}, {0x0829, 0x082D}, {0x0859, 0x085B}, {0x08D4, 0x08E1}, {0x08E3, 0x0903}, {0x093A, 0x093C}, {0x093E, 0x094F}, {0x0951, 0x0957}, {0x0962, 0x0963}, {0x0981, 0x0983}, {0x09BC, 0x09BC}, {0x09BE, 0x09C4}, {0x09C7, 0x09C8}, {0x09CB, 0x09CD}, {0x09D7, 0x09D7}, {0x09E2, 0x09E3}, {0x0A01, 0x0A03}, {0x0A3C, 0x0A3C}, {0x0A3E, 0x0A42}, {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D}, {0x0A51, 0x0A51}, {0x0A70, 0x0A71}, {0x0A75, 0x0A75}, {0x0A81, 0x0A83}, {0x0ABC, 0x0ABC}, {0x0ABE, 0x0AC5}, {0x0AC7, 0x0AC9}, {0x0ACB, 0x0ACD}, {0x0AE2, 0x0AE3}, {0x0B01, 0x0B03}, {0x0B3C, 0x0B3C}, {0x0B3E, 0x0B44}, {0x0B47, 0x0B48}, {0x0B4B, 0x0B4D}, {0x0B56, 0x0B57}, {0x0B62, 0x0B63}, {0x0B82, 0x0B82}, {0x0BBE, 0x0BC2}, {0x0BC6, 0x0BC8}, {0x0BCA, 0x0BCD}, {0x0BD7, 0x0BD7}, {0x0C00, 0x0C03}, {0x0C3E, 0x0C44}, {0x0C46, 0x0C48}, {0x0C4A, 0x0C4D}, {0x0C55, 0x0C56}, {0x0C62, 0x0C63}, {0x0C81, 0x0C83}, {0x0CBC, 0x0CBC}, {0x0CBE, 0x0CC4}, {0x0CC6, 0x0CC8}, {0x0CCA, 0x0CCD}, {0x0CD5, 0x0CD6}, {0x0CE2, 0x0CE3}, {0x0D01, 0x0D03}, {0x0D3E, 0x0D44}, {0x0D46, 0x0D48}, {0x0D4A, 0x0D4D}, {0x0D57, 0x0D57}, {0x0D62, 0x0D63}, {0x0D82, 0x0D83}, {0x0DCA, 0x0DCA}, {0x0DCF, 0x0DD4}, {0x0DD6, 0x0DD6}, {0x0DD8, 0x0DDF}, {0x0DF2, 0x0DF3}, {0x0E31, 0x0E31}, {0x0E34, 0x0E3A}, {0x0E47, 0x0E4E}, {0x0EB1, 0x0EB1}, {0x0EB4, 0x0EB9}, {0x0EBB, 0x0EBC}, {0x0EC8, 0x0ECD}, {0x0F18, 0x0F19}, {0x0F35, 0x0F35}, {0x0F37, 0x0F37}, {0x0F39, 0x0F39}, {0x0F3E, 0x0F3F}, {0x0F71, 0x0F84}, {0x0F86, 0x0F87}, {0x0F8D, 0x0F97}, {0x0F99, 0x0FBC}, {0x0FC6, 0x0FC6}, {0x102B, 0x103E}, {0x1056, 0x1059}, {0x105E, 0x1060}, {0x1062, 0x1064}, {0x1067, 0x106D}, {0x1071, 0x1074}, {0x1082, 0x108D}, {0x108F, 0x108F}, {0x109A, 0x109D}, {0x135D, 0x135F}, {0x1712, 0x1714}, {0x1732, 0x1734}, {0x1752, 0x1753}, {0x1772, 0x1773}, {0x17B4, 0x17D3}, {0x17DD, 0x17DD}, {0x180B, 0x180D}, {0x1885, 0x1886}, {0x18A9, 0x18A9}, {0x1920, 0x192B}, {0x1930, 0x193B}, {0x1A17, 0x1A1B}, {0x1A55, 0x1A5E}, {0x1A60, 0x1A7C}, {0x1A7F, 0x1A7F}, {0x1AB0, 0x1ABE}, {0x1B00, 0x1B04}, {0x1B34, 0x1B44}, {0x1B6B, 0x1B73}, {0x1B80, 0x1B82}, {0x1BA1, 0x1BAD}, {0x1BE6, 0x1BF3}, {0x1C24, 0x1C37}, {0x1CD0, 0x1CD2}, {0x1CD4, 0x1CE8}, {0x1CED, 0x1CED}, {0x1CF2, 0x1CF4}, {0x1CF8, 0x1CF9}, {0x1DC0, 0x1DF5}, {0x1DFB, 0x1DFF}, {0x20D0, 0x20F0}, {0x2CEF, 0x2CF1}, {0x2D7F, 0x2D7F}, {0x2DE0, 0x2DFF}, {0x302A, 0x302F}, {0x3099, 0x309A}, {0xA66F, 0xA672}, {0xA674, 0xA67D}, {0xA69E, 0xA69F}, {0xA6F0, 0xA6F1}, {0xA802, 0xA802}, {0xA806, 0xA806}, {0xA80B, 0xA80B}, {0xA823, 0xA827}, {0xA880, 0xA881}, {0xA8B4, 0xA8C5}, {0xA8E0, 0xA8F1}, {0xA926, 0xA92D}, {0xA947, 0xA953}, {0xA980, 0xA983}, {0xA9B3, 0xA9C0}, {0xA9E5, 0xA9E5}, {0xAA29, 0xAA36}, {0xAA43, 0xAA43}, {0xAA4C, 0xAA4D}, {0xAA7B, 0xAA7D}, {0xAAB0, 0xAAB0}, {0xAAB2, 0xAAB4}, {0xAAB7, 0xAAB8}, {0xAABE, 0xAABF}, {0xAAC1, 0xAAC1}, {0xAAEB, 0xAAEF}, {0xAAF5, 0xAAF6}, {0xABE3, 0xABEA}, {0xABEC, 0xABED}, {0xFB1E, 0xFB1E}, {0xFE00, 0xFE0F}, {0xFE20, 0xFE2F}, {0x101FD, 0x101FD}, {0x102E0, 0x102E0}, {0x10376, 0x1037A}, {0x10A01, 0x10A03}, {0x10A05, 0x10A06}, {0x10A0C, 0x10A0F}, {0x10A38, 0x10A3A}, {0x10A3F, 0x10A3F}, {0x10AE5, 0x10AE6}, {0x11000, 0x11002}, {0x11038, 0x11046}, {0x1107F, 0x11082}, {0x110B0, 0x110BA}, {0x11100, 0x11102}, {0x11127, 0x11134}, {0x11173, 0x11173}, {0x11180, 0x11182}, {0x111B3, 0x111C0}, {0x111CA, 0x111CC}, {0x1122C, 0x11237}, {0x1123E, 0x1123E}, {0x112DF, 0x112EA}, {0x11300, 0x11303}, {0x1133C, 0x1133C}, {0x1133E, 0x11344}, {0x11347, 0x11348}, {0x1134B, 0x1134D}, {0x11357, 0x11357}, {0x11362, 0x11363}, {0x11366, 0x1136C}, {0x11370, 0x11374}, {0x11435, 0x11446}, {0x114B0, 0x114C3}, {0x115AF, 0x115B5}, {0x115B8, 0x115C0}, {0x115DC, 0x115DD}, {0x11630, 0x11640}, {0x116AB, 0x116B7}, {0x1171D, 0x1172B}, {0x11C2F, 0x11C36}, {0x11C38, 0x11C3F}, {0x11C92, 0x11CA7}, {0x11CA9, 0x11CB6}, {0x16AF0, 0x16AF4}, {0x16B30, 0x16B36}, {0x16F51, 0x16F7E}, {0x16F8F, 0x16F92}, {0x1BC9D, 0x1BC9E}, {0x1D165, 0x1D169}, {0x1D16D, 0x1D172}, {0x1D17B, 0x1D182}, {0x1D185, 0x1D18B}, {0x1D1AA, 0x1D1AD}, {0x1D242, 0x1D244}, {0x1DA00, 0x1DA36}, {0x1DA3B, 0x1DA6C}, {0x1DA75, 0x1DA75}, {0x1DA84, 0x1DA84}, {0x1DA9B, 0x1DA9F}, {0x1DAA1, 0x1DAAF}, {0x1E000, 0x1E006}, {0x1E008, 0x1E018}, {0x1E01B, 0x1E021}, {0x1E023, 0x1E024}, {0x1E026, 0x1E02A}, {0x1E8D0, 0x1E8D6}, {0x1E944, 0x1E94A}, {0xE0100, 0xE01EF}, } var doublewidth = table{ {0x1100, 0x115F}, {0x231A, 0x231B}, {0x2329, 0x232A}, {0x23E9, 0x23EC}, {0x23F0, 0x23F0}, {0x23F3, 0x23F3}, {0x25FD, 0x25FE}, {0x2614, 0x2615}, {0x2648, 0x2653}, {0x267F, 0x267F}, {0x2693, 0x2693}, {0x26A1, 0x26A1}, {0x26AA, 0x26AB}, {0x26BD, 0x26BE}, {0x26C4, 0x26C5}, {0x26CE, 0x26CE}, {0x26D4, 0x26D4}, {0x26EA, 0x26EA}, {0x26F2, 0x26F3}, {0x26F5, 0x26F5}, {0x26FA, 0x26FA}, {0x26FD, 0x26FD}, {0x2705, 0x2705}, {0x270A, 0x270B}, {0x2728, 0x2728}, {0x274C, 0x274C}, {0x274E, 0x274E}, {0x2753, 0x2755}, {0x2757, 0x2757}, {0x2795, 0x2797}, {0x27B0, 0x27B0}, {0x27BF, 0x27BF}, {0x2B1B, 0x2B1C}, {0x2B50, 0x2B50}, {0x2B55, 0x2B55}, {0x2E80, 0x2E99}, {0x2E9B, 0x2EF3}, {0x2F00, 0x2FD5}, {0x2FF0, 0x2FFB}, {0x3000, 0x303E}, {0x3041, 0x3096}, {0x3099, 0x30FF}, {0x3105, 0x312D}, {0x3131, 0x318E}, {0x3190, 0x31BA}, {0x31C0, 0x31E3}, {0x31F0, 0x321E}, {0x3220, 0x3247}, {0x3250, 0x32FE}, {0x3300, 0x4DBF}, {0x4E00, 0xA48C}, {0xA490, 0xA4C6}, {0xA960, 0xA97C}, {0xAC00, 0xD7A3}, {0xF900, 0xFAFF}, {0xFE10, 0xFE19}, {0xFE30, 0xFE52}, {0xFE54, 0xFE66}, {0xFE68, 0xFE6B}, {0xFF01, 0xFF60}, {0xFFE0, 0xFFE6}, {0x16FE0, 0x16FE0}, {0x17000, 0x187EC}, {0x18800, 0x18AF2}, {0x1B000, 0x1B001}, {0x1F004, 0x1F004}, {0x1F0CF, 0x1F0CF}, {0x1F18E, 0x1F18E}, {0x1F191, 0x1F19A}, {0x1F200, 0x1F202}, {0x1F210, 0x1F23B}, {0x1F240, 0x1F248}, {0x1F250, 0x1F251}, {0x1F300, 0x1F320}, {0x1F32D, 0x1F335}, {0x1F337, 0x1F37C}, {0x1F37E, 0x1F393}, {0x1F3A0, 0x1F3CA}, {0x1F3CF, 0x1F3D3}, {0x1F3E0, 0x1F3F0}, {0x1F3F4, 0x1F3F4}, {0x1F3F8, 0x1F43E}, {0x1F440, 0x1F440}, {0x1F442, 0x1F4FC}, {0x1F4FF, 0x1F53D}, {0x1F54B, 0x1F54E}, {0x1F550, 0x1F567}, {0x1F57A, 0x1F57A}, {0x1F595, 0x1F596}, {0x1F5A4, 0x1F5A4}, {0x1F5FB, 0x1F64F}, {0x1F680, 0x1F6C5}, {0x1F6CC, 0x1F6CC}, {0x1F6D0, 0x1F6D2}, {0x1F6EB, 0x1F6EC}, {0x1F6F4, 0x1F6F6}, {0x1F910, 0x1F91E}, {0x1F920, 0x1F927}, {0x1F930, 0x1F930}, {0x1F933, 0x1F93E}, {0x1F940, 0x1F94B}, {0x1F950, 0x1F95E}, {0x1F980, 0x1F991}, {0x1F9C0, 0x1F9C0}, {0x20000, 0x2FFFD}, {0x30000, 0x3FFFD}, } var ambiguous = table{ {0x00A1, 0x00A1}, {0x00A4, 0x00A4}, {0x00A7, 0x00A8}, {0x00AA, 0x00AA}, {0x00AD, 0x00AE}, {0x00B0, 0x00B4}, {0x00B6, 0x00BA}, {0x00BC, 0x00BF}, {0x00C6, 0x00C6}, {0x00D0, 0x00D0}, {0x00D7, 0x00D8}, {0x00DE, 0x00E1}, {0x00E6, 0x00E6}, {0x00E8, 0x00EA}, {0x00EC, 0x00ED}, {0x00F0, 0x00F0}, {0x00F2, 0x00F3}, {0x00F7, 0x00FA}, {0x00FC, 0x00FC}, {0x00FE, 0x00FE}, {0x0101, 0x0101}, {0x0111, 0x0111}, {0x0113, 0x0113}, {0x011B, 0x011B}, {0x0126, 0x0127}, {0x012B, 0x012B}, {0x0131, 0x0133}, {0x0138, 0x0138}, {0x013F, 0x0142}, {0x0144, 0x0144}, {0x0148, 0x014B}, {0x014D, 0x014D}, {0x0152, 0x0153}, {0x0166, 0x0167}, {0x016B, 0x016B}, {0x01CE, 0x01CE}, {0x01D0, 0x01D0}, {0x01D2, 0x01D2}, {0x01D4, 0x01D4}, {0x01D6, 0x01D6}, {0x01D8, 0x01D8}, {0x01DA, 0x01DA}, {0x01DC, 0x01DC}, {0x0251, 0x0251}, {0x0261, 0x0261}, {0x02C4, 0x02C4}, {0x02C7, 0x02C7}, {0x02C9, 0x02CB}, {0x02CD, 0x02CD}, {0x02D0, 0x02D0}, {0x02D8, 0x02DB}, {0x02DD, 0x02DD}, {0x02DF, 0x02DF}, {0x0300, 0x036F}, {0x0391, 0x03A1}, {0x03A3, 0x03A9}, {0x03B1, 0x03C1}, {0x03C3, 0x03C9}, {0x0401, 0x0401}, {0x0410, 0x044F}, {0x0451, 0x0451}, {0x2010, 0x2010}, {0x2013, 0x2016}, {0x2018, 0x2019}, {0x201C, 0x201D}, {0x2020, 0x2022}, {0x2024, 0x2027}, {0x2030, 0x2030}, {0x2032, 0x2033}, {0x2035, 0x2035}, {0x203B, 0x203B}, {0x203E, 0x203E}, {0x2074, 0x2074}, {0x207F, 0x207F}, {0x2081, 0x2084}, {0x20AC, 0x20AC}, {0x2103, 0x2103}, {0x2105, 0x2105}, {0x2109, 0x2109}, {0x2113, 0x2113}, {0x2116, 0x2116}, {0x2121, 0x2122}, {0x2126, 0x2126}, {0x212B, 0x212B}, {0x2153, 0x2154}, {0x215B, 0x215E}, {0x2160, 0x216B}, {0x2170, 0x2179}, {0x2189, 0x2189}, {0x2190, 0x2199}, {0x21B8, 0x21B9}, {0x21D2, 0x21D2}, {0x21D4, 0x21D4}, {0x21E7, 0x21E7}, {0x2200, 0x2200}, {0x2202, 0x2203}, {0x2207, 0x2208}, {0x220B, 0x220B}, {0x220F, 0x220F}, {0x2211, 0x2211}, {0x2215, 0x2215}, {0x221A, 0x221A}, {0x221D, 0x2220}, {0x2223, 0x2223}, {0x2225, 0x2225}, {0x2227, 0x222C}, {0x222E, 0x222E}, {0x2234, 0x2237}, {0x223C, 0x223D}, {0x2248, 0x2248}, {0x224C, 0x224C}, {0x2252, 0x2252}, {0x2260, 0x2261}, {0x2264, 0x2267}, {0x226A, 0x226B}, {0x226E, 0x226F}, {0x2282, 0x2283}, {0x2286, 0x2287}, {0x2295, 0x2295}, {0x2299, 0x2299}, {0x22A5, 0x22A5}, {0x22BF, 0x22BF}, {0x2312, 0x2312}, {0x2460, 0x24E9}, {0x24EB, 0x254B}, {0x2550, 0x2573}, {0x2580, 0x258F}, {0x2592, 0x2595}, {0x25A0, 0x25A1}, {0x25A3, 0x25A9}, {0x25B2, 0x25B3}, {0x25B6, 0x25B7}, {0x25BC, 0x25BD}, {0x25C0, 0x25C1}, {0x25C6, 0x25C8}, {0x25CB, 0x25CB}, {0x25CE, 0x25D1}, {0x25E2, 0x25E5}, {0x25EF, 0x25EF}, {0x2605, 0x2606}, {0x2609, 0x2609}, {0x260E, 0x260F}, {0x261C, 0x261C}, {0x261E, 0x261E}, {0x2640, 0x2640}, {0x2642, 0x2642}, {0x2660, 0x2661}, {0x2663, 0x2665}, {0x2667, 0x266A}, {0x266C, 0x266D}, {0x266F, 0x266F}, {0x269E, 0x269F}, {0x26BF, 0x26BF}, {0x26C6, 0x26CD}, {0x26CF, 0x26D3}, {0x26D5, 0x26E1}, {0x26E3, 0x26E3}, {0x26E8, 0x26E9}, {0x26EB, 0x26F1}, {0x26F4, 0x26F4}, {0x26F6, 0x26F9}, {0x26FB, 0x26FC}, {0x26FE, 0x26FF}, {0x273D, 0x273D}, {0x2776, 0x277F}, {0x2B56, 0x2B59}, {0x3248, 0x324F}, {0xE000, 0xF8FF}, {0xFE00, 0xFE0F}, {0xFFFD, 0xFFFD}, {0x1F100, 0x1F10A}, {0x1F110, 0x1F12D}, {0x1F130, 0x1F169}, {0x1F170, 0x1F18D}, {0x1F18F, 0x1F190}, {0x1F19B, 0x1F1AC}, {0xE0100, 0xE01EF}, {0xF0000, 0xFFFFD}, {0x100000, 0x10FFFD}, } var emoji = table{ {0x1F1E6, 0x1F1FF}, {0x1F321, 0x1F321}, {0x1F324, 0x1F32C}, {0x1F336, 0x1F336}, {0x1F37D, 0x1F37D}, {0x1F396, 0x1F397}, {0x1F399, 0x1F39B}, {0x1F39E, 0x1F39F}, {0x1F3CB, 0x1F3CE}, {0x1F3D4, 0x1F3DF}, {0x1F3F3, 0x1F3F5}, {0x1F3F7, 0x1F3F7}, {0x1F43F, 0x1F43F}, {0x1F441, 0x1F441}, {0x1F4FD, 0x1F4FD}, {0x1F549, 0x1F54A}, {0x1F56F, 0x1F570}, {0x1F573, 0x1F579}, {0x1F587, 0x1F587}, {0x1F58A, 0x1F58D}, {0x1F590, 0x1F590}, {0x1F5A5, 0x1F5A5}, {0x1F5A8, 0x1F5A8}, {0x1F5B1, 0x1F5B2}, {0x1F5BC, 0x1F5BC}, {0x1F5C2, 0x1F5C4}, {0x1F5D1, 0x1F5D3}, {0x1F5DC, 0x1F5DE}, {0x1F5E1, 0x1F5E1}, {0x1F5E3, 0x1F5E3}, {0x1F5E8, 0x1F5E8}, {0x1F5EF, 0x1F5EF}, {0x1F5F3, 0x1F5F3}, {0x1F5FA, 0x1F5FA}, {0x1F6CB, 0x1F6CF}, {0x1F6E0, 0x1F6E5}, {0x1F6E9, 0x1F6E9}, {0x1F6F0, 0x1F6F0}, {0x1F6F3, 0x1F6F3}, } var notassigned = table{ {0x0378, 0x0379}, {0x0380, 0x0383}, {0x038B, 0x038B}, {0x038D, 0x038D}, {0x03A2, 0x03A2}, {0x0530, 0x0530}, {0x0557, 0x0558}, {0x0560, 0x0560}, {0x0588, 0x0588}, {0x058B, 0x058C}, {0x0590, 0x0590}, {0x05C8, 0x05CF}, {0x05EB, 0x05EF}, {0x05F5, 0x05FF}, {0x061D, 0x061D}, {0x070E, 0x070E}, {0x074B, 0x074C}, {0x07B2, 0x07BF}, {0x07FB, 0x07FF}, {0x082E, 0x082F}, {0x083F, 0x083F}, {0x085C, 0x085D}, {0x085F, 0x089F}, {0x08B5, 0x08B5}, {0x08BE, 0x08D3}, {0x0984, 0x0984}, {0x098D, 0x098E}, {0x0991, 0x0992}, {0x09A9, 0x09A9}, {0x09B1, 0x09B1}, {0x09B3, 0x09B5}, {0x09BA, 0x09BB}, {0x09C5, 0x09C6}, {0x09C9, 0x09CA}, {0x09CF, 0x09D6}, {0x09D8, 0x09DB}, {0x09DE, 0x09DE}, {0x09E4, 0x09E5}, {0x09FC, 0x0A00}, {0x0A04, 0x0A04}, {0x0A0B, 0x0A0E}, {0x0A11, 0x0A12}, {0x0A29, 0x0A29}, {0x0A31, 0x0A31}, {0x0A34, 0x0A34}, {0x0A37, 0x0A37}, {0x0A3A, 0x0A3B}, {0x0A3D, 0x0A3D}, {0x0A43, 0x0A46}, {0x0A49, 0x0A4A}, {0x0A4E, 0x0A50}, {0x0A52, 0x0A58}, {0x0A5D, 0x0A5D}, {0x0A5F, 0x0A65}, {0x0A76, 0x0A80}, {0x0A84, 0x0A84}, {0x0A8E, 0x0A8E}, {0x0A92, 0x0A92}, {0x0AA9, 0x0AA9}, {0x0AB1, 0x0AB1}, {0x0AB4, 0x0AB4}, {0x0ABA, 0x0ABB}, {0x0AC6, 0x0AC6}, {0x0ACA, 0x0ACA}, {0x0ACE, 0x0ACF}, {0x0AD1, 0x0ADF}, {0x0AE4, 0x0AE5}, {0x0AF2, 0x0AF8}, {0x0AFA, 0x0B00}, {0x0B04, 0x0B04}, {0x0B0D, 0x0B0E}, {0x0B11, 0x0B12}, {0x0B29, 0x0B29}, {0x0B31, 0x0B31}, {0x0B34, 0x0B34}, {0x0B3A, 0x0B3B}, {0x0B45, 0x0B46}, {0x0B49, 0x0B4A}, {0x0B4E, 0x0B55}, {0x0B58, 0x0B5B}, {0x0B5E, 0x0B5E}, {0x0B64, 0x0B65}, {0x0B78, 0x0B81}, {0x0B84, 0x0B84}, {0x0B8B, 0x0B8D}, {0x0B91, 0x0B91}, {0x0B96, 0x0B98}, {0x0B9B, 0x0B9B}, {0x0B9D, 0x0B9D}, {0x0BA0, 0x0BA2}, {0x0BA5, 0x0BA7}, {0x0BAB, 0x0BAD}, {0x0BBA, 0x0BBD}, {0x0BC3, 0x0BC5}, {0x0BC9, 0x0BC9}, {0x0BCE, 0x0BCF}, {0x0BD1, 0x0BD6}, {0x0BD8, 0x0BE5}, {0x0BFB, 0x0BFF}, {0x0C04, 0x0C04}, {0x0C0D, 0x0C0D}, {0x0C11, 0x0C11}, {0x0C29, 0x0C29}, {0x0C3A, 0x0C3C}, {0x0C45, 0x0C45}, {0x0C49, 0x0C49}, {0x0C4E, 0x0C54}, {0x0C57, 0x0C57}, {0x0C5B, 0x0C5F}, {0x0C64, 0x0C65}, {0x0C70, 0x0C77}, {0x0C84, 0x0C84}, {0x0C8D, 0x0C8D}, {0x0C91, 0x0C91}, {0x0CA9, 0x0CA9}, {0x0CB4, 0x0CB4}, {0x0CBA, 0x0CBB}, {0x0CC5, 0x0CC5}, {0x0CC9, 0x0CC9}, {0x0CCE, 0x0CD4}, {0x0CD7, 0x0CDD}, {0x0CDF, 0x0CDF}, {0x0CE4, 0x0CE5}, {0x0CF0, 0x0CF0}, {0x0CF3, 0x0D00}, {0x0D04, 0x0D04}, {0x0D0D, 0x0D0D}, {0x0D11, 0x0D11}, {0x0D3B, 0x0D3C}, {0x0D45, 0x0D45}, {0x0D49, 0x0D49}, {0x0D50, 0x0D53}, {0x0D64, 0x0D65}, {0x0D80, 0x0D81}, {0x0D84, 0x0D84}, {0x0D97, 0x0D99}, {0x0DB2, 0x0DB2}, {0x0DBC, 0x0DBC}, {0x0DBE, 0x0DBF}, {0x0DC7, 0x0DC9}, {0x0DCB, 0x0DCE}, {0x0DD5, 0x0DD5}, {0x0DD7, 0x0DD7}, {0x0DE0, 0x0DE5}, {0x0DF0, 0x0DF1}, {0x0DF5, 0x0E00}, {0x0E3B, 0x0E3E}, {0x0E5C, 0x0E80}, {0x0E83, 0x0E83}, {0x0E85, 0x0E86}, {0x0E89, 0x0E89}, {0x0E8B, 0x0E8C}, {0x0E8E, 0x0E93}, {0x0E98, 0x0E98}, {0x0EA0, 0x0EA0}, {0x0EA4, 0x0EA4}, {0x0EA6, 0x0EA6}, {0x0EA8, 0x0EA9}, {0x0EAC, 0x0EAC}, {0x0EBA, 0x0EBA}, {0x0EBE, 0x0EBF}, {0x0EC5, 0x0EC5}, {0x0EC7, 0x0EC7}, {0x0ECE, 0x0ECF}, {0x0EDA, 0x0EDB}, {0x0EE0, 0x0EFF}, {0x0F48, 0x0F48}, {0x0F6D, 0x0F70}, {0x0F98, 0x0F98}, {0x0FBD, 0x0FBD}, {0x0FCD, 0x0FCD}, {0x0FDB, 0x0FFF}, {0x10C6, 0x10C6}, {0x10C8, 0x10CC}, {0x10CE, 0x10CF}, {0x1249, 0x1249}, {0x124E, 0x124F}, {0x1257, 0x1257}, {0x1259, 0x1259}, {0x125E, 0x125F}, {0x1289, 0x1289}, {0x128E, 0x128F}, {0x12B1, 0x12B1}, {0x12B6, 0x12B7}, {0x12BF, 0x12BF}, {0x12C1, 0x12C1}, {0x12C6, 0x12C7}, {0x12D7, 0x12D7}, {0x1311, 0x1311}, {0x1316, 0x1317}, {0x135B, 0x135C}, {0x137D, 0x137F}, {0x139A, 0x139F}, {0x13F6, 0x13F7}, {0x13FE, 0x13FF}, {0x169D, 0x169F}, {0x16F9, 0x16FF}, {0x170D, 0x170D}, {0x1715, 0x171F}, {0x1737, 0x173F}, {0x1754, 0x175F}, {0x176D, 0x176D}, {0x1771, 0x1771}, {0x1774, 0x177F}, {0x17DE, 0x17DF}, {0x17EA, 0x17EF}, {0x17FA, 0x17FF}, {0x180F, 0x180F}, {0x181A, 0x181F}, {0x1878, 0x187F}, {0x18AB, 0x18AF}, {0x18F6, 0x18FF}, {0x191F, 0x191F}, {0x192C, 0x192F}, {0x193C, 0x193F}, {0x1941, 0x1943}, {0x196E, 0x196F}, {0x1975, 0x197F}, {0x19AC, 0x19AF}, {0x19CA, 0x19CF}, {0x19DB, 0x19DD}, {0x1A1C, 0x1A1D}, {0x1A5F, 0x1A5F}, {0x1A7D, 0x1A7E}, {0x1A8A, 0x1A8F}, {0x1A9A, 0x1A9F}, {0x1AAE, 0x1AAF}, {0x1ABF, 0x1AFF}, {0x1B4C, 0x1B4F}, {0x1B7D, 0x1B7F}, {0x1BF4, 0x1BFB}, {0x1C38, 0x1C3A}, {0x1C4A, 0x1C4C}, {0x1C89, 0x1CBF}, {0x1CC8, 0x1CCF}, {0x1CF7, 0x1CF7}, {0x1CFA, 0x1CFF}, {0x1DF6, 0x1DFA}, {0x1F16, 0x1F17}, {0x1F1E, 0x1F1F}, {0x1F46, 0x1F47}, {0x1F4E, 0x1F4F}, {0x1F58, 0x1F58}, {0x1F5A, 0x1F5A}, {0x1F5C, 0x1F5C}, {0x1F5E, 0x1F5E}, {0x1F7E, 0x1F7F}, {0x1FB5, 0x1FB5}, {0x1FC5, 0x1FC5}, {0x1FD4, 0x1FD5}, {0x1FDC, 0x1FDC}, {0x1FF0, 0x1FF1}, {0x1FF5, 0x1FF5}, {0x1FFF, 0x1FFF}, {0x2065, 0x2065}, {0x2072, 0x2073}, {0x208F, 0x208F}, {0x209D, 0x209F}, {0x20BF, 0x20CF}, {0x20F1, 0x20FF}, {0x218C, 0x218F}, {0x23FF, 0x23FF}, {0x2427, 0x243F}, {0x244B, 0x245F}, {0x2B74, 0x2B75}, {0x2B96, 0x2B97}, {0x2BBA, 0x2BBC}, {0x2BC9, 0x2BC9}, {0x2BD2, 0x2BEB}, {0x2BF0, 0x2BFF}, {0x2C2F, 0x2C2F}, {0x2C5F, 0x2C5F}, {0x2CF4, 0x2CF8}, {0x2D26, 0x2D26}, {0x2D28, 0x2D2C}, {0x2D2E, 0x2D2F}, {0x2D68, 0x2D6E}, {0x2D71, 0x2D7E}, {0x2D97, 0x2D9F}, {0x2DA7, 0x2DA7}, {0x2DAF, 0x2DAF}, {0x2DB7, 0x2DB7}, {0x2DBF, 0x2DBF}, {0x2DC7, 0x2DC7}, {0x2DCF, 0x2DCF}, {0x2DD7, 0x2DD7}, {0x2DDF, 0x2DDF}, {0x2E45, 0x2E7F}, {0x2E9A, 0x2E9A}, {0x2EF4, 0x2EFF}, {0x2FD6, 0x2FEF}, {0x2FFC, 0x2FFF}, {0x3040, 0x3040}, {0x3097, 0x3098}, {0x3100, 0x3104}, {0x312E, 0x3130}, {0x318F, 0x318F}, {0x31BB, 0x31BF}, {0x31E4, 0x31EF}, {0x321F, 0x321F}, {0x32FF, 0x32FF}, {0x4DB6, 0x4DBF}, {0x9FD6, 0x9FFF}, {0xA48D, 0xA48F}, {0xA4C7, 0xA4CF}, {0xA62C, 0xA63F}, {0xA6F8, 0xA6FF}, {0xA7AF, 0xA7AF}, {0xA7B8, 0xA7F6}, {0xA82C, 0xA82F}, {0xA83A, 0xA83F}, {0xA878, 0xA87F}, {0xA8C6, 0xA8CD}, {0xA8DA, 0xA8DF}, {0xA8FE, 0xA8FF}, {0xA954, 0xA95E}, {0xA97D, 0xA97F}, {0xA9CE, 0xA9CE}, {0xA9DA, 0xA9DD}, {0xA9FF, 0xA9FF}, {0xAA37, 0xAA3F}, {0xAA4E, 0xAA4F}, {0xAA5A, 0xAA5B}, {0xAAC3, 0xAADA}, {0xAAF7, 0xAB00}, {0xAB07, 0xAB08}, {0xAB0F, 0xAB10}, {0xAB17, 0xAB1F}, {0xAB27, 0xAB27}, {0xAB2F, 0xAB2F}, {0xAB66, 0xAB6F}, {0xABEE, 0xABEF}, {0xABFA, 0xABFF}, {0xD7A4, 0xD7AF}, {0xD7C7, 0xD7CA}, {0xD7FC, 0xD7FF}, {0xFA6E, 0xFA6F}, {0xFADA, 0xFAFF}, {0xFB07, 0xFB12}, {0xFB18, 0xFB1C}, {0xFB37, 0xFB37}, {0xFB3D, 0xFB3D}, {0xFB3F, 0xFB3F}, {0xFB42, 0xFB42}, {0xFB45, 0xFB45}, {0xFBC2, 0xFBD2}, {0xFD40, 0xFD4F}, {0xFD90, 0xFD91}, {0xFDC8, 0xFDEF}, {0xFDFE, 0xFDFF}, {0xFE1A, 0xFE1F}, {0xFE53, 0xFE53}, {0xFE67, 0xFE67}, {0xFE6C, 0xFE6F}, {0xFE75, 0xFE75}, {0xFEFD, 0xFEFE}, {0xFF00, 0xFF00}, {0xFFBF, 0xFFC1}, {0xFFC8, 0xFFC9}, {0xFFD0, 0xFFD1}, {0xFFD8, 0xFFD9}, {0xFFDD, 0xFFDF}, {0xFFE7, 0xFFE7}, {0xFFEF, 0xFFF8}, {0xFFFE, 0xFFFF}, {0x1000C, 0x1000C}, {0x10027, 0x10027}, {0x1003B, 0x1003B}, {0x1003E, 0x1003E}, {0x1004E, 0x1004F}, {0x1005E, 0x1007F}, {0x100FB, 0x100FF}, {0x10103, 0x10106}, {0x10134, 0x10136}, {0x1018F, 0x1018F}, {0x1019C, 0x1019F}, {0x101A1, 0x101CF}, {0x101FE, 0x1027F}, {0x1029D, 0x1029F}, {0x102D1, 0x102DF}, {0x102FC, 0x102FF}, {0x10324, 0x1032F}, {0x1034B, 0x1034F}, {0x1037B, 0x1037F}, {0x1039E, 0x1039E}, {0x103C4, 0x103C7}, {0x103D6, 0x103FF}, {0x1049E, 0x1049F}, {0x104AA, 0x104AF}, {0x104D4, 0x104D7}, {0x104FC, 0x104FF}, {0x10528, 0x1052F}, {0x10564, 0x1056E}, {0x10570, 0x105FF}, {0x10737, 0x1073F}, {0x10756, 0x1075F}, {0x10768, 0x107FF}, {0x10806, 0x10807}, {0x10809, 0x10809}, {0x10836, 0x10836}, {0x10839, 0x1083B}, {0x1083D, 0x1083E}, {0x10856, 0x10856}, {0x1089F, 0x108A6}, {0x108B0, 0x108DF}, {0x108F3, 0x108F3}, {0x108F6, 0x108FA}, {0x1091C, 0x1091E}, {0x1093A, 0x1093E}, {0x10940, 0x1097F}, {0x109B8, 0x109BB}, {0x109D0, 0x109D1}, {0x10A04, 0x10A04}, {0x10A07, 0x10A0B}, {0x10A14, 0x10A14}, {0x10A18, 0x10A18}, {0x10A34, 0x10A37}, {0x10A3B, 0x10A3E}, {0x10A48, 0x10A4F}, {0x10A59, 0x10A5F}, {0x10AA0, 0x10ABF}, {0x10AE7, 0x10AEA}, {0x10AF7, 0x10AFF}, {0x10B36, 0x10B38}, {0x10B56, 0x10B57}, {0x10B73, 0x10B77}, {0x10B92, 0x10B98}, {0x10B9D, 0x10BA8}, {0x10BB0, 0x10BFF}, {0x10C49, 0x10C7F}, {0x10CB3, 0x10CBF}, {0x10CF3, 0x10CF9}, {0x10D00, 0x10E5F}, {0x10E7F, 0x10FFF}, {0x1104E, 0x11051}, {0x11070, 0x1107E}, {0x110C2, 0x110CF}, {0x110E9, 0x110EF}, {0x110FA, 0x110FF}, {0x11135, 0x11135}, {0x11144, 0x1114F}, {0x11177, 0x1117F}, {0x111CE, 0x111CF}, {0x111E0, 0x111E0}, {0x111F5, 0x111FF}, {0x11212, 0x11212}, {0x1123F, 0x1127F}, {0x11287, 0x11287}, {0x11289, 0x11289}, {0x1128E, 0x1128E}, {0x1129E, 0x1129E}, {0x112AA, 0x112AF}, {0x112EB, 0x112EF}, {0x112FA, 0x112FF}, {0x11304, 0x11304}, {0x1130D, 0x1130E}, {0x11311, 0x11312}, {0x11329, 0x11329}, {0x11331, 0x11331}, {0x11334, 0x11334}, {0x1133A, 0x1133B}, {0x11345, 0x11346}, {0x11349, 0x1134A}, {0x1134E, 0x1134F}, {0x11351, 0x11356}, {0x11358, 0x1135C}, {0x11364, 0x11365}, {0x1136D, 0x1136F}, {0x11375, 0x113FF}, {0x1145A, 0x1145A}, {0x1145C, 0x1145C}, {0x1145E, 0x1147F}, {0x114C8, 0x114CF}, {0x114DA, 0x1157F}, {0x115B6, 0x115B7}, {0x115DE, 0x115FF}, {0x11645, 0x1164F}, {0x1165A, 0x1165F}, {0x1166D, 0x1167F}, {0x116B8, 0x116BF}, {0x116CA, 0x116FF}, {0x1171A, 0x1171C}, {0x1172C, 0x1172F}, {0x11740, 0x1189F}, {0x118F3, 0x118FE}, {0x11900, 0x11ABF}, {0x11AF9, 0x11BFF}, {0x11C09, 0x11C09}, {0x11C37, 0x11C37}, {0x11C46, 0x11C4F}, {0x11C6D, 0x11C6F}, {0x11C90, 0x11C91}, {0x11CA8, 0x11CA8}, {0x11CB7, 0x11FFF}, {0x1239A, 0x123FF}, {0x1246F, 0x1246F}, {0x12475, 0x1247F}, {0x12544, 0x12FFF}, {0x1342F, 0x143FF}, {0x14647, 0x167FF}, {0x16A39, 0x16A3F}, {0x16A5F, 0x16A5F}, {0x16A6A, 0x16A6D}, {0x16A70, 0x16ACF}, {0x16AEE, 0x16AEF}, {0x16AF6, 0x16AFF}, {0x16B46, 0x16B4F}, {0x16B5A, 0x16B5A}, {0x16B62, 0x16B62}, {0x16B78, 0x16B7C}, {0x16B90, 0x16EFF}, {0x16F45, 0x16F4F}, {0x16F7F, 0x16F8E}, {0x16FA0, 0x16FDF}, {0x16FE1, 0x16FFF}, {0x187ED, 0x187FF}, {0x18AF3, 0x1AFFF}, {0x1B002, 0x1BBFF}, {0x1BC6B, 0x1BC6F}, {0x1BC7D, 0x1BC7F}, {0x1BC89, 0x1BC8F}, {0x1BC9A, 0x1BC9B}, {0x1BCA4, 0x1CFFF}, {0x1D0F6, 0x1D0FF}, {0x1D127, 0x1D128}, {0x1D1E9, 0x1D1FF}, {0x1D246, 0x1D2FF}, {0x1D357, 0x1D35F}, {0x1D372, 0x1D3FF}, {0x1D455, 0x1D455}, {0x1D49D, 0x1D49D}, {0x1D4A0, 0x1D4A1}, {0x1D4A3, 0x1D4A4}, {0x1D4A7, 0x1D4A8}, {0x1D4AD, 0x1D4AD}, {0x1D4BA, 0x1D4BA}, {0x1D4BC, 0x1D4BC}, {0x1D4C4, 0x1D4C4}, {0x1D506, 0x1D506}, {0x1D50B, 0x1D50C}, {0x1D515, 0x1D515}, {0x1D51D, 0x1D51D}, {0x1D53A, 0x1D53A}, {0x1D53F, 0x1D53F}, {0x1D545, 0x1D545}, {0x1D547, 0x1D549}, {0x1D551, 0x1D551}, {0x1D6A6, 0x1D6A7}, {0x1D7CC, 0x1D7CD}, {0x1DA8C, 0x1DA9A}, {0x1DAA0, 0x1DAA0}, {0x1DAB0, 0x1DFFF}, {0x1E007, 0x1E007}, {0x1E019, 0x1E01A}, {0x1E022, 0x1E022}, {0x1E025, 0x1E025}, {0x1E02B, 0x1E7FF}, {0x1E8C5, 0x1E8C6}, {0x1E8D7, 0x1E8FF}, {0x1E94B, 0x1E94F}, {0x1E95A, 0x1E95D}, {0x1E960, 0x1EDFF}, {0x1EE04, 0x1EE04}, {0x1EE20, 0x1EE20}, {0x1EE23, 0x1EE23}, {0x1EE25, 0x1EE26}, {0x1EE28, 0x1EE28}, {0x1EE33, 0x1EE33}, {0x1EE38, 0x1EE38}, {0x1EE3A, 0x1EE3A}, {0x1EE3C, 0x1EE41}, {0x1EE43, 0x1EE46}, {0x1EE48, 0x1EE48}, {0x1EE4A, 0x1EE4A}, {0x1EE4C, 0x1EE4C}, {0x1EE50, 0x1EE50}, {0x1EE53, 0x1EE53}, {0x1EE55, 0x1EE56}, {0x1EE58, 0x1EE58}, {0x1EE5A, 0x1EE5A}, {0x1EE5C, 0x1EE5C}, {0x1EE5E, 0x1EE5E}, {0x1EE60, 0x1EE60}, {0x1EE63, 0x1EE63}, {0x1EE65, 0x1EE66}, {0x1EE6B, 0x1EE6B}, {0x1EE73, 0x1EE73}, {0x1EE78, 0x1EE78}, {0x1EE7D, 0x1EE7D}, {0x1EE7F, 0x1EE7F}, {0x1EE8A, 0x1EE8A}, {0x1EE9C, 0x1EEA0}, {0x1EEA4, 0x1EEA4}, {0x1EEAA, 0x1EEAA}, {0x1EEBC, 0x1EEEF}, {0x1EEF2, 0x1EFFF}, {0x1F02C, 0x1F02F}, {0x1F094, 0x1F09F}, {0x1F0AF, 0x1F0B0}, {0x1F0C0, 0x1F0C0}, {0x1F0D0, 0x1F0D0}, {0x1F0F6, 0x1F0FF}, {0x1F10D, 0x1F10F}, {0x1F12F, 0x1F12F}, {0x1F16C, 0x1F16F}, {0x1F1AD, 0x1F1E5}, {0x1F203, 0x1F20F}, {0x1F23C, 0x1F23F}, {0x1F249, 0x1F24F}, {0x1F252, 0x1F2FF}, {0x1F6D3, 0x1F6DF}, {0x1F6ED, 0x1F6EF}, {0x1F6F7, 0x1F6FF}, {0x1F774, 0x1F77F}, {0x1F7D5, 0x1F7FF}, {0x1F80C, 0x1F80F}, {0x1F848, 0x1F84F}, {0x1F85A, 0x1F85F}, {0x1F888, 0x1F88F}, {0x1F8AE, 0x1F90F}, {0x1F91F, 0x1F91F}, {0x1F928, 0x1F92F}, {0x1F931, 0x1F932}, {0x1F93F, 0x1F93F}, {0x1F94C, 0x1F94F}, {0x1F95F, 0x1F97F}, {0x1F992, 0x1F9BF}, {0x1F9C1, 0x1FFFF}, {0x2A6D7, 0x2A6FF}, {0x2B735, 0x2B73F}, {0x2B81E, 0x2B81F}, {0x2CEA2, 0x2F7FF}, {0x2FA1E, 0xE0000}, {0xE0002, 0xE001F}, {0xE0080, 0xE00FF}, {0xE01F0, 0xEFFFF}, {0xFFFFE, 0xFFFFF}, } var neutral = table{ {0x0000, 0x001F}, {0x007F, 0x007F}, {0x0080, 0x009F}, {0x00A0, 0x00A0}, {0x00A9, 0x00A9}, {0x00AB, 0x00AB}, {0x00B5, 0x00B5}, {0x00BB, 0x00BB}, {0x00C0, 0x00C5}, {0x00C7, 0x00CF}, {0x00D1, 0x00D6}, {0x00D9, 0x00DD}, {0x00E2, 0x00E5}, {0x00E7, 0x00E7}, {0x00EB, 0x00EB}, {0x00EE, 0x00EF}, {0x00F1, 0x00F1}, {0x00F4, 0x00F6}, {0x00FB, 0x00FB}, {0x00FD, 0x00FD}, {0x00FF, 0x00FF}, {0x0100, 0x0100}, {0x0102, 0x0110}, {0x0112, 0x0112}, {0x0114, 0x011A}, {0x011C, 0x0125}, {0x0128, 0x012A}, {0x012C, 0x0130}, {0x0134, 0x0137}, {0x0139, 0x013E}, {0x0143, 0x0143}, {0x0145, 0x0147}, {0x014C, 0x014C}, {0x014E, 0x0151}, {0x0154, 0x0165}, {0x0168, 0x016A}, {0x016C, 0x017F}, {0x0180, 0x01BA}, {0x01BB, 0x01BB}, {0x01BC, 0x01BF}, {0x01C0, 0x01C3}, {0x01C4, 0x01CD}, {0x01CF, 0x01CF}, {0x01D1, 0x01D1}, {0x01D3, 0x01D3}, {0x01D5, 0x01D5}, {0x01D7, 0x01D7}, {0x01D9, 0x01D9}, {0x01DB, 0x01DB}, {0x01DD, 0x024F}, {0x0250, 0x0250}, {0x0252, 0x0260}, {0x0262, 0x0293}, {0x0294, 0x0294}, {0x0295, 0x02AF}, {0x02B0, 0x02C1}, {0x02C2, 0x02C3}, {0x02C5, 0x02C5}, {0x02C6, 0x02C6}, {0x02C8, 0x02C8}, {0x02CC, 0x02CC}, {0x02CE, 0x02CF}, {0x02D1, 0x02D1}, {0x02D2, 0x02D7}, {0x02DC, 0x02DC}, {0x02DE, 0x02DE}, {0x02E0, 0x02E4}, {0x02E5, 0x02EB}, {0x02EC, 0x02EC}, {0x02ED, 0x02ED}, {0x02EE, 0x02EE}, {0x02EF, 0x02FF}, {0x0370, 0x0373}, {0x0374, 0x0374}, {0x0375, 0x0375}, {0x0376, 0x0377}, {0x037A, 0x037A}, {0x037B, 0x037D}, {0x037E, 0x037E}, {0x037F, 0x037F}, {0x0384, 0x0385}, {0x0386, 0x0386}, {0x0387, 0x0387}, {0x0388, 0x038A}, {0x038C, 0x038C}, {0x038E, 0x0390}, {0x03AA, 0x03B0}, {0x03C2, 0x03C2}, {0x03CA, 0x03F5}, {0x03F6, 0x03F6}, {0x03F7, 0x03FF}, {0x0400, 0x0400}, {0x0402, 0x040F}, {0x0450, 0x0450}, {0x0452, 0x0481}, {0x0482, 0x0482}, {0x0483, 0x0487}, {0x0488, 0x0489}, {0x048A, 0x04FF}, {0x0500, 0x052F}, {0x0531, 0x0556}, {0x0559, 0x0559}, {0x055A, 0x055F}, {0x0561, 0x0587}, {0x0589, 0x0589}, {0x058A, 0x058A}, {0x058D, 0x058E}, {0x058F, 0x058F}, {0x0591, 0x05BD}, {0x05BE, 0x05BE}, {0x05BF, 0x05BF}, {0x05C0, 0x05C0}, {0x05C1, 0x05C2}, {0x05C3, 0x05C3}, {0x05C4, 0x05C5}, {0x05C6, 0x05C6}, {0x05C7, 0x05C7}, {0x05D0, 0x05EA}, {0x05F0, 0x05F2}, {0x05F3, 0x05F4}, {0x0600, 0x0605}, {0x0606, 0x0608}, {0x0609, 0x060A}, {0x060B, 0x060B}, {0x060C, 0x060D}, {0x060E, 0x060F}, {0x0610, 0x061A}, {0x061B, 0x061B}, {0x061C, 0x061C}, {0x061E, 0x061F}, {0x0620, 0x063F}, {0x0640, 0x0640}, {0x0641, 0x064A}, {0x064B, 0x065F}, {0x0660, 0x0669}, {0x066A, 0x066D}, {0x066E, 0x066F}, {0x0670, 0x0670}, {0x0671, 0x06D3}, {0x06D4, 0x06D4}, {0x06D5, 0x06D5}, {0x06D6, 0x06DC}, {0x06DD, 0x06DD}, {0x06DE, 0x06DE}, {0x06DF, 0x06E4}, {0x06E5, 0x06E6}, {0x06E7, 0x06E8}, {0x06E9, 0x06E9}, {0x06EA, 0x06ED}, {0x06EE, 0x06EF}, {0x06F0, 0x06F9}, {0x06FA, 0x06FC}, {0x06FD, 0x06FE}, {0x06FF, 0x06FF}, {0x0700, 0x070D}, {0x070F, 0x070F}, {0x0710, 0x0710}, {0x0711, 0x0711}, {0x0712, 0x072F}, {0x0730, 0x074A}, {0x074D, 0x074F}, {0x0750, 0x077F}, {0x0780, 0x07A5}, {0x07A6, 0x07B0}, {0x07B1, 0x07B1}, {0x07C0, 0x07C9}, {0x07CA, 0x07EA}, {0x07EB, 0x07F3}, {0x07F4, 0x07F5}, {0x07F6, 0x07F6}, {0x07F7, 0x07F9}, {0x07FA, 0x07FA}, {0x0800, 0x0815}, {0x0816, 0x0819}, {0x081A, 0x081A}, {0x081B, 0x0823}, {0x0824, 0x0824}, {0x0825, 0x0827}, {0x0828, 0x0828}, {0x0829, 0x082D}, {0x0830, 0x083E}, {0x0840, 0x0858}, {0x0859, 0x085B}, {0x085E, 0x085E}, {0x08A0, 0x08B4}, {0x08B6, 0x08BD}, {0x08D4, 0x08E1}, {0x08E2, 0x08E2}, {0x08E3, 0x08FF}, {0x0900, 0x0902}, {0x0903, 0x0903}, {0x0904, 0x0939}, {0x093A, 0x093A}, {0x093B, 0x093B}, {0x093C, 0x093C}, {0x093D, 0x093D}, {0x093E, 0x0940}, {0x0941, 0x0948}, {0x0949, 0x094C}, {0x094D, 0x094D}, {0x094E, 0x094F}, {0x0950, 0x0950}, {0x0951, 0x0957}, {0x0958, 0x0961}, {0x0962, 0x0963}, {0x0964, 0x0965}, {0x0966, 0x096F}, {0x0970, 0x0970}, {0x0971, 0x0971}, {0x0972, 0x097F}, {0x0980, 0x0980}, {0x0981, 0x0981}, {0x0982, 0x0983}, {0x0985, 0x098C}, {0x098F, 0x0990}, {0x0993, 0x09A8}, {0x09AA, 0x09B0}, {0x09B2, 0x09B2}, {0x09B6, 0x09B9}, {0x09BC, 0x09BC}, {0x09BD, 0x09BD}, {0x09BE, 0x09C0}, {0x09C1, 0x09C4}, {0x09C7, 0x09C8}, {0x09CB, 0x09CC}, {0x09CD, 0x09CD}, {0x09CE, 0x09CE}, {0x09D7, 0x09D7}, {0x09DC, 0x09DD}, {0x09DF, 0x09E1}, {0x09E2, 0x09E3}, {0x09E6, 0x09EF}, {0x09F0, 0x09F1}, {0x09F2, 0x09F3}, {0x09F4, 0x09F9}, {0x09FA, 0x09FA}, {0x09FB, 0x09FB}, {0x0A01, 0x0A02}, {0x0A03, 0x0A03}, {0x0A05, 0x0A0A}, {0x0A0F, 0x0A10}, {0x0A13, 0x0A28}, {0x0A2A, 0x0A30}, {0x0A32, 0x0A33}, {0x0A35, 0x0A36}, {0x0A38, 0x0A39}, {0x0A3C, 0x0A3C}, {0x0A3E, 0x0A40}, {0x0A41, 0x0A42}, {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D}, {0x0A51, 0x0A51}, {0x0A59, 0x0A5C}, {0x0A5E, 0x0A5E}, {0x0A66, 0x0A6F}, {0x0A70, 0x0A71}, {0x0A72, 0x0A74}, {0x0A75, 0x0A75}, {0x0A81, 0x0A82}, {0x0A83, 0x0A83}, {0x0A85, 0x0A8D}, {0x0A8F, 0x0A91}, {0x0A93, 0x0AA8}, {0x0AAA, 0x0AB0}, {0x0AB2, 0x0AB3}, {0x0AB5, 0x0AB9}, {0x0ABC, 0x0ABC}, {0x0ABD, 0x0ABD}, {0x0ABE, 0x0AC0}, {0x0AC1, 0x0AC5}, {0x0AC7, 0x0AC8}, {0x0AC9, 0x0AC9}, {0x0ACB, 0x0ACC}, {0x0ACD, 0x0ACD}, {0x0AD0, 0x0AD0}, {0x0AE0, 0x0AE1}, {0x0AE2, 0x0AE3}, {0x0AE6, 0x0AEF}, {0x0AF0, 0x0AF0}, {0x0AF1, 0x0AF1}, {0x0AF9, 0x0AF9}, {0x0B01, 0x0B01}, {0x0B02, 0x0B03}, {0x0B05, 0x0B0C}, {0x0B0F, 0x0B10}, {0x0B13, 0x0B28}, {0x0B2A, 0x0B30}, {0x0B32, 0x0B33}, {0x0B35, 0x0B39}, {0x0B3C, 0x0B3C}, {0x0B3D, 0x0B3D}, {0x0B3E, 0x0B3E}, {0x0B3F, 0x0B3F}, {0x0B40, 0x0B40}, {0x0B41, 0x0B44}, {0x0B47, 0x0B48}, {0x0B4B, 0x0B4C}, {0x0B4D, 0x0B4D}, {0x0B56, 0x0B56}, {0x0B57, 0x0B57}, {0x0B5C, 0x0B5D}, {0x0B5F, 0x0B61}, {0x0B62, 0x0B63}, {0x0B66, 0x0B6F}, {0x0B70, 0x0B70}, {0x0B71, 0x0B71}, {0x0B72, 0x0B77}, {0x0B82, 0x0B82}, {0x0B83, 0x0B83}, {0x0B85, 0x0B8A}, {0x0B8E, 0x0B90}, {0x0B92, 0x0B95}, {0x0B99, 0x0B9A}, {0x0B9C, 0x0B9C}, {0x0B9E, 0x0B9F}, {0x0BA3, 0x0BA4}, {0x0BA8, 0x0BAA}, {0x0BAE, 0x0BB9}, {0x0BBE, 0x0BBF}, {0x0BC0, 0x0BC0}, {0x0BC1, 0x0BC2}, {0x0BC6, 0x0BC8}, {0x0BCA, 0x0BCC}, {0x0BCD, 0x0BCD}, {0x0BD0, 0x0BD0}, {0x0BD7, 0x0BD7}, {0x0BE6, 0x0BEF}, {0x0BF0, 0x0BF2}, {0x0BF3, 0x0BF8}, {0x0BF9, 0x0BF9}, {0x0BFA, 0x0BFA}, {0x0C00, 0x0C00}, {0x0C01, 0x0C03}, {0x0C05, 0x0C0C}, {0x0C0E, 0x0C10}, {0x0C12, 0x0C28}, {0x0C2A, 0x0C39}, {0x0C3D, 0x0C3D}, {0x0C3E, 0x0C40}, {0x0C41, 0x0C44}, {0x0C46, 0x0C48}, {0x0C4A, 0x0C4D}, {0x0C55, 0x0C56}, {0x0C58, 0x0C5A}, {0x0C60, 0x0C61}, {0x0C62, 0x0C63}, {0x0C66, 0x0C6F}, {0x0C78, 0x0C7E}, {0x0C7F, 0x0C7F}, {0x0C80, 0x0C80}, {0x0C81, 0x0C81}, {0x0C82, 0x0C83}, {0x0C85, 0x0C8C}, {0x0C8E, 0x0C90}, {0x0C92, 0x0CA8}, {0x0CAA, 0x0CB3}, {0x0CB5, 0x0CB9}, {0x0CBC, 0x0CBC}, {0x0CBD, 0x0CBD}, {0x0CBE, 0x0CBE}, {0x0CBF, 0x0CBF}, {0x0CC0, 0x0CC4}, {0x0CC6, 0x0CC6}, {0x0CC7, 0x0CC8}, {0x0CCA, 0x0CCB}, {0x0CCC, 0x0CCD}, {0x0CD5, 0x0CD6}, {0x0CDE, 0x0CDE}, {0x0CE0, 0x0CE1}, {0x0CE2, 0x0CE3}, {0x0CE6, 0x0CEF}, {0x0CF1, 0x0CF2}, {0x0D01, 0x0D01}, {0x0D02, 0x0D03}, {0x0D05, 0x0D0C}, {0x0D0E, 0x0D10}, {0x0D12, 0x0D3A}, {0x0D3D, 0x0D3D}, {0x0D3E, 0x0D40}, {0x0D41, 0x0D44}, {0x0D46, 0x0D48}, {0x0D4A, 0x0D4C}, {0x0D4D, 0x0D4D}, {0x0D4E, 0x0D4E}, {0x0D4F, 0x0D4F}, {0x0D54, 0x0D56}, {0x0D57, 0x0D57}, {0x0D58, 0x0D5E}, {0x0D5F, 0x0D61}, {0x0D62, 0x0D63}, {0x0D66, 0x0D6F}, {0x0D70, 0x0D78}, {0x0D79, 0x0D79}, {0x0D7A, 0x0D7F}, {0x0D82, 0x0D83}, {0x0D85, 0x0D96}, {0x0D9A, 0x0DB1}, {0x0DB3, 0x0DBB}, {0x0DBD, 0x0DBD}, {0x0DC0, 0x0DC6}, {0x0DCA, 0x0DCA}, {0x0DCF, 0x0DD1}, {0x0DD2, 0x0DD4}, {0x0DD6, 0x0DD6}, {0x0DD8, 0x0DDF}, {0x0DE6, 0x0DEF}, {0x0DF2, 0x0DF3}, {0x0DF4, 0x0DF4}, {0x0E01, 0x0E30}, {0x0E31, 0x0E31}, {0x0E32, 0x0E33}, {0x0E34, 0x0E3A}, {0x0E3F, 0x0E3F}, {0x0E40, 0x0E45}, {0x0E46, 0x0E46}, {0x0E47, 0x0E4E}, {0x0E4F, 0x0E4F}, {0x0E50, 0x0E59}, {0x0E5A, 0x0E5B}, {0x0E81, 0x0E82}, {0x0E84, 0x0E84}, {0x0E87, 0x0E88}, {0x0E8A, 0x0E8A}, {0x0E8D, 0x0E8D}, {0x0E94, 0x0E97}, {0x0E99, 0x0E9F}, {0x0EA1, 0x0EA3}, {0x0EA5, 0x0EA5}, {0x0EA7, 0x0EA7}, {0x0EAA, 0x0EAB}, {0x0EAD, 0x0EB0}, {0x0EB1, 0x0EB1}, {0x0EB2, 0x0EB3}, {0x0EB4, 0x0EB9}, {0x0EBB, 0x0EBC}, {0x0EBD, 0x0EBD}, {0x0EC0, 0x0EC4}, {0x0EC6, 0x0EC6}, {0x0EC8, 0x0ECD}, {0x0ED0, 0x0ED9}, {0x0EDC, 0x0EDF}, {0x0F00, 0x0F00}, {0x0F01, 0x0F03}, {0x0F04, 0x0F12}, {0x0F13, 0x0F13}, {0x0F14, 0x0F14}, {0x0F15, 0x0F17}, {0x0F18, 0x0F19}, {0x0F1A, 0x0F1F}, {0x0F20, 0x0F29}, {0x0F2A, 0x0F33}, {0x0F34, 0x0F34}, {0x0F35, 0x0F35}, {0x0F36, 0x0F36}, {0x0F37, 0x0F37}, {0x0F38, 0x0F38}, {0x0F39, 0x0F39}, {0x0F3A, 0x0F3A}, {0x0F3B, 0x0F3B}, {0x0F3C, 0x0F3C}, {0x0F3D, 0x0F3D}, {0x0F3E, 0x0F3F}, {0x0F40, 0x0F47}, {0x0F49, 0x0F6C}, {0x0F71, 0x0F7E}, {0x0F7F, 0x0F7F}, {0x0F80, 0x0F84}, {0x0F85, 0x0F85}, {0x0F86, 0x0F87}, {0x0F88, 0x0F8C}, {0x0F8D, 0x0F97}, {0x0F99, 0x0FBC}, {0x0FBE, 0x0FC5}, {0x0FC6, 0x0FC6}, {0x0FC7, 0x0FCC}, {0x0FCE, 0x0FCF}, {0x0FD0, 0x0FD4}, {0x0FD5, 0x0FD8}, {0x0FD9, 0x0FDA}, {0x1000, 0x102A}, {0x102B, 0x102C}, {0x102D, 0x1030}, {0x1031, 0x1031}, {0x1032, 0x1037}, {0x1038, 0x1038}, {0x1039, 0x103A}, {0x103B, 0x103C}, {0x103D, 0x103E}, {0x103F, 0x103F}, {0x1040, 0x1049}, {0x104A, 0x104F}, {0x1050, 0x1055}, {0x1056, 0x1057}, {0x1058, 0x1059}, {0x105A, 0x105D}, {0x105E, 0x1060}, {0x1061, 0x1061}, {0x1062, 0x1064}, {0x1065, 0x1066}, {0x1067, 0x106D}, {0x106E, 0x1070}, {0x1071, 0x1074}, {0x1075, 0x1081}, {0x1082, 0x1082}, {0x1083, 0x1084}, {0x1085, 0x1086}, {0x1087, 0x108C}, {0x108D, 0x108D}, {0x108E, 0x108E}, {0x108F, 0x108F}, {0x1090, 0x1099}, {0x109A, 0x109C}, {0x109D, 0x109D}, {0x109E, 0x109F}, {0x10A0, 0x10C5}, {0x10C7, 0x10C7}, {0x10CD, 0x10CD}, {0x10D0, 0x10FA}, {0x10FB, 0x10FB}, {0x10FC, 0x10FC}, {0x10FD, 0x10FF}, {0x1160, 0x11FF}, {0x1200, 0x1248}, {0x124A, 0x124D}, {0x1250, 0x1256}, {0x1258, 0x1258}, {0x125A, 0x125D}, {0x1260, 0x1288}, {0x128A, 0x128D}, {0x1290, 0x12B0}, {0x12B2, 0x12B5}, {0x12B8, 0x12BE}, {0x12C0, 0x12C0}, {0x12C2, 0x12C5}, {0x12C8, 0x12D6}, {0x12D8, 0x1310}, {0x1312, 0x1315}, {0x1318, 0x135A}, {0x135D, 0x135F}, {0x1360, 0x1368}, {0x1369, 0x137C}, {0x1380, 0x138F}, {0x1390, 0x1399}, {0x13A0, 0x13F5}, {0x13F8, 0x13FD}, {0x1400, 0x1400}, {0x1401, 0x166C}, {0x166D, 0x166E}, {0x166F, 0x167F}, {0x1680, 0x1680}, {0x1681, 0x169A}, {0x169B, 0x169B}, {0x169C, 0x169C}, {0x16A0, 0x16EA}, {0x16EB, 0x16ED}, {0x16EE, 0x16F0}, {0x16F1, 0x16F8}, {0x1700, 0x170C}, {0x170E, 0x1711}, {0x1712, 0x1714}, {0x1720, 0x1731}, {0x1732, 0x1734}, {0x1735, 0x1736}, {0x1740, 0x1751}, {0x1752, 0x1753}, {0x1760, 0x176C}, {0x176E, 0x1770}, {0x1772, 0x1773}, {0x1780, 0x17B3}, {0x17B4, 0x17B5}, {0x17B6, 0x17B6}, {0x17B7, 0x17BD}, {0x17BE, 0x17C5}, {0x17C6, 0x17C6}, {0x17C7, 0x17C8}, {0x17C9, 0x17D3}, {0x17D4, 0x17D6}, {0x17D7, 0x17D7}, {0x17D8, 0x17DA}, {0x17DB, 0x17DB}, {0x17DC, 0x17DC}, {0x17DD, 0x17DD}, {0x17E0, 0x17E9}, {0x17F0, 0x17F9}, {0x1800, 0x1805}, {0x1806, 0x1806}, {0x1807, 0x180A}, {0x180B, 0x180D}, {0x180E, 0x180E}, {0x1810, 0x1819}, {0x1820, 0x1842}, {0x1843, 0x1843}, {0x1844, 0x1877}, {0x1880, 0x1884}, {0x1885, 0x1886}, {0x1887, 0x18A8}, {0x18A9, 0x18A9}, {0x18AA, 0x18AA}, {0x18B0, 0x18F5}, {0x1900, 0x191E}, {0x1920, 0x1922}, {0x1923, 0x1926}, {0x1927, 0x1928}, {0x1929, 0x192B}, {0x1930, 0x1931}, {0x1932, 0x1932}, {0x1933, 0x1938}, {0x1939, 0x193B}, {0x1940, 0x1940}, {0x1944, 0x1945}, {0x1946, 0x194F}, {0x1950, 0x196D}, {0x1970, 0x1974}, {0x1980, 0x19AB}, {0x19B0, 0x19C9}, {0x19D0, 0x19D9}, {0x19DA, 0x19DA}, {0x19DE, 0x19DF}, {0x19E0, 0x19FF}, {0x1A00, 0x1A16}, {0x1A17, 0x1A18}, {0x1A19, 0x1A1A}, {0x1A1B, 0x1A1B}, {0x1A1E, 0x1A1F}, {0x1A20, 0x1A54}, {0x1A55, 0x1A55}, {0x1A56, 0x1A56}, {0x1A57, 0x1A57}, {0x1A58, 0x1A5E}, {0x1A60, 0x1A60}, {0x1A61, 0x1A61}, {0x1A62, 0x1A62}, {0x1A63, 0x1A64}, {0x1A65, 0x1A6C}, {0x1A6D, 0x1A72}, {0x1A73, 0x1A7C}, {0x1A7F, 0x1A7F}, {0x1A80, 0x1A89}, {0x1A90, 0x1A99}, {0x1AA0, 0x1AA6}, {0x1AA7, 0x1AA7}, {0x1AA8, 0x1AAD}, {0x1AB0, 0x1ABD}, {0x1ABE, 0x1ABE}, {0x1B00, 0x1B03}, {0x1B04, 0x1B04}, {0x1B05, 0x1B33}, {0x1B34, 0x1B34}, {0x1B35, 0x1B35}, {0x1B36, 0x1B3A}, {0x1B3B, 0x1B3B}, {0x1B3C, 0x1B3C}, {0x1B3D, 0x1B41}, {0x1B42, 0x1B42}, {0x1B43, 0x1B44}, {0x1B45, 0x1B4B}, {0x1B50, 0x1B59}, {0x1B5A, 0x1B60}, {0x1B61, 0x1B6A}, {0x1B6B, 0x1B73}, {0x1B74, 0x1B7C}, {0x1B80, 0x1B81}, {0x1B82, 0x1B82}, {0x1B83, 0x1BA0}, {0x1BA1, 0x1BA1}, {0x1BA2, 0x1BA5}, {0x1BA6, 0x1BA7}, {0x1BA8, 0x1BA9}, {0x1BAA, 0x1BAA}, {0x1BAB, 0x1BAD}, {0x1BAE, 0x1BAF}, {0x1BB0, 0x1BB9}, {0x1BBA, 0x1BBF}, {0x1BC0, 0x1BE5}, {0x1BE6, 0x1BE6}, {0x1BE7, 0x1BE7}, {0x1BE8, 0x1BE9}, {0x1BEA, 0x1BEC}, {0x1BED, 0x1BED}, {0x1BEE, 0x1BEE}, {0x1BEF, 0x1BF1}, {0x1BF2, 0x1BF3}, {0x1BFC, 0x1BFF}, {0x1C00, 0x1C23}, {0x1C24, 0x1C2B}, {0x1C2C, 0x1C33}, {0x1C34, 0x1C35}, {0x1C36, 0x1C37}, {0x1C3B, 0x1C3F}, {0x1C40, 0x1C49}, {0x1C4D, 0x1C4F}, {0x1C50, 0x1C59}, {0x1C5A, 0x1C77}, {0x1C78, 0x1C7D}, {0x1C7E, 0x1C7F}, {0x1C80, 0x1C88}, {0x1CC0, 0x1CC7}, {0x1CD0, 0x1CD2}, {0x1CD3, 0x1CD3}, {0x1CD4, 0x1CE0}, {0x1CE1, 0x1CE1}, {0x1CE2, 0x1CE8}, {0x1CE9, 0x1CEC}, {0x1CED, 0x1CED}, {0x1CEE, 0x1CF1}, {0x1CF2, 0x1CF3}, {0x1CF4, 0x1CF4}, {0x1CF5, 0x1CF6}, {0x1CF8, 0x1CF9}, {0x1D00, 0x1D2B}, {0x1D2C, 0x1D6A}, {0x1D6B, 0x1D77}, {0x1D78, 0x1D78}, {0x1D79, 0x1D7F}, {0x1D80, 0x1D9A}, {0x1D9B, 0x1DBF}, {0x1DC0, 0x1DF5}, {0x1DFB, 0x1DFF}, {0x1E00, 0x1EFF}, {0x1F00, 0x1F15}, {0x1F18, 0x1F1D}, {0x1F20, 0x1F45}, {0x1F48, 0x1F4D}, {0x1F50, 0x1F57}, {0x1F59, 0x1F59}, {0x1F5B, 0x1F5B}, {0x1F5D, 0x1F5D}, {0x1F5F, 0x1F7D}, {0x1F80, 0x1FB4}, {0x1FB6, 0x1FBC}, {0x1FBD, 0x1FBD}, {0x1FBE, 0x1FBE}, {0x1FBF, 0x1FC1}, {0x1FC2, 0x1FC4}, {0x1FC6, 0x1FCC}, {0x1FCD, 0x1FCF}, {0x1FD0, 0x1FD3}, {0x1FD6, 0x1FDB}, {0x1FDD, 0x1FDF}, {0x1FE0, 0x1FEC}, {0x1FED, 0x1FEF}, {0x1FF2, 0x1FF4}, {0x1FF6, 0x1FFC}, {0x1FFD, 0x1FFE}, {0x2000, 0x200A}, {0x200B, 0x200F}, {0x2011, 0x2012}, {0x2017, 0x2017}, {0x201A, 0x201A}, {0x201B, 0x201B}, {0x201E, 0x201E}, {0x201F, 0x201F}, {0x2023, 0x2023}, {0x2028, 0x2028}, {0x2029, 0x2029}, {0x202A, 0x202E}, {0x202F, 0x202F}, {0x2031, 0x2031}, {0x2034, 0x2034}, {0x2036, 0x2038}, {0x2039, 0x2039}, {0x203A, 0x203A}, {0x203C, 0x203D}, {0x203F, 0x2040}, {0x2041, 0x2043}, {0x2044, 0x2044}, {0x2045, 0x2045}, {0x2046, 0x2046}, {0x2047, 0x2051}, {0x2052, 0x2052}, {0x2053, 0x2053}, {0x2054, 0x2054}, {0x2055, 0x205E}, {0x205F, 0x205F}, {0x2060, 0x2064}, {0x2066, 0x206F}, {0x2070, 0x2070}, {0x2071, 0x2071}, {0x2075, 0x2079}, {0x207A, 0x207C}, {0x207D, 0x207D}, {0x207E, 0x207E}, {0x2080, 0x2080}, {0x2085, 0x2089}, {0x208A, 0x208C}, {0x208D, 0x208D}, {0x208E, 0x208E}, {0x2090, 0x209C}, {0x20A0, 0x20A8}, {0x20AA, 0x20AB}, {0x20AD, 0x20BE}, {0x20D0, 0x20DC}, {0x20DD, 0x20E0}, {0x20E1, 0x20E1}, {0x20E2, 0x20E4}, {0x20E5, 0x20F0}, {0x2100, 0x2101}, {0x2102, 0x2102}, {0x2104, 0x2104}, {0x2106, 0x2106}, {0x2107, 0x2107}, {0x2108, 0x2108}, {0x210A, 0x2112}, {0x2114, 0x2114}, {0x2115, 0x2115}, {0x2117, 0x2117}, {0x2118, 0x2118}, {0x2119, 0x211D}, {0x211E, 0x2120}, {0x2123, 0x2123}, {0x2124, 0x2124}, {0x2125, 0x2125}, {0x2127, 0x2127}, {0x2128, 0x2128}, {0x2129, 0x2129}, {0x212A, 0x212A}, {0x212C, 0x212D}, {0x212E, 0x212E}, {0x212F, 0x2134}, {0x2135, 0x2138}, {0x2139, 0x2139}, {0x213A, 0x213B}, {0x213C, 0x213F}, {0x2140, 0x2144}, {0x2145, 0x2149}, {0x214A, 0x214A}, {0x214B, 0x214B}, {0x214C, 0x214D}, {0x214E, 0x214E}, {0x214F, 0x214F}, {0x2150, 0x2152}, {0x2155, 0x215A}, {0x215F, 0x215F}, {0x216C, 0x216F}, {0x217A, 0x2182}, {0x2183, 0x2184}, {0x2185, 0x2188}, {0x218A, 0x218B}, {0x219A, 0x219B}, {0x219C, 0x219F}, {0x21A0, 0x21A0}, {0x21A1, 0x21A2}, {0x21A3, 0x21A3}, {0x21A4, 0x21A5}, {0x21A6, 0x21A6}, {0x21A7, 0x21AD}, {0x21AE, 0x21AE}, {0x21AF, 0x21B7}, {0x21BA, 0x21CD}, {0x21CE, 0x21CF}, {0x21D0, 0x21D1}, {0x21D3, 0x21D3}, {0x21D5, 0x21E6}, {0x21E8, 0x21F3}, {0x21F4, 0x21FF}, {0x2201, 0x2201}, {0x2204, 0x2206}, {0x2209, 0x220A}, {0x220C, 0x220E}, {0x2210, 0x2210}, {0x2212, 0x2214}, {0x2216, 0x2219}, {0x221B, 0x221C}, {0x2221, 0x2222}, {0x2224, 0x2224}, {0x2226, 0x2226}, {0x222D, 0x222D}, {0x222F, 0x2233}, {0x2238, 0x223B}, {0x223E, 0x2247}, {0x2249, 0x224B}, {0x224D, 0x2251}, {0x2253, 0x225F}, {0x2262, 0x2263}, {0x2268, 0x2269}, {0x226C, 0x226D}, {0x2270, 0x2281}, {0x2284, 0x2285}, {0x2288, 0x2294}, {0x2296, 0x2298}, {0x229A, 0x22A4}, {0x22A6, 0x22BE}, {0x22C0, 0x22FF}, {0x2300, 0x2307}, {0x2308, 0x2308}, {0x2309, 0x2309}, {0x230A, 0x230A}, {0x230B, 0x230B}, {0x230C, 0x2311}, {0x2313, 0x2319}, {0x231C, 0x231F}, {0x2320, 0x2321}, {0x2322, 0x2328}, {0x232B, 0x237B}, {0x237C, 0x237C}, {0x237D, 0x239A}, {0x239B, 0x23B3}, {0x23B4, 0x23DB}, {0x23DC, 0x23E1}, {0x23E2, 0x23E8}, {0x23ED, 0x23EF}, {0x23F1, 0x23F2}, {0x23F4, 0x23FE}, {0x2400, 0x2426}, {0x2440, 0x244A}, {0x24EA, 0x24EA}, {0x254C, 0x254F}, {0x2574, 0x257F}, {0x2590, 0x2591}, {0x2596, 0x259F}, {0x25A2, 0x25A2}, {0x25AA, 0x25B1}, {0x25B4, 0x25B5}, {0x25B8, 0x25BB}, {0x25BE, 0x25BF}, {0x25C2, 0x25C5}, {0x25C9, 0x25CA}, {0x25CC, 0x25CD}, {0x25D2, 0x25E1}, {0x25E6, 0x25EE}, {0x25F0, 0x25F7}, {0x25F8, 0x25FC}, {0x25FF, 0x25FF}, {0x2600, 0x2604}, {0x2607, 0x2608}, {0x260A, 0x260D}, {0x2610, 0x2613}, {0x2616, 0x261B}, {0x261D, 0x261D}, {0x261F, 0x263F}, {0x2641, 0x2641}, {0x2643, 0x2647}, {0x2654, 0x265F}, {0x2662, 0x2662}, {0x2666, 0x2666}, {0x266B, 0x266B}, {0x266E, 0x266E}, {0x2670, 0x267E}, {0x2680, 0x2692}, {0x2694, 0x269D}, {0x26A0, 0x26A0}, {0x26A2, 0x26A9}, {0x26AC, 0x26BC}, {0x26C0, 0x26C3}, {0x26E2, 0x26E2}, {0x26E4, 0x26E7}, {0x2700, 0x2704}, {0x2706, 0x2709}, {0x270C, 0x2727}, {0x2729, 0x273C}, {0x273E, 0x274B}, {0x274D, 0x274D}, {0x274F, 0x2752}, {0x2756, 0x2756}, {0x2758, 0x2767}, {0x2768, 0x2768}, {0x2769, 0x2769}, {0x276A, 0x276A}, {0x276B, 0x276B}, {0x276C, 0x276C}, {0x276D, 0x276D}, {0x276E, 0x276E}, {0x276F, 0x276F}, {0x2770, 0x2770}, {0x2771, 0x2771}, {0x2772, 0x2772}, {0x2773, 0x2773}, {0x2774, 0x2774}, {0x2775, 0x2775}, {0x2780, 0x2793}, {0x2794, 0x2794}, {0x2798, 0x27AF}, {0x27B1, 0x27BE}, {0x27C0, 0x27C4}, {0x27C5, 0x27C5}, {0x27C6, 0x27C6}, {0x27C7, 0x27E5}, {0x27EE, 0x27EE}, {0x27EF, 0x27EF}, {0x27F0, 0x27FF}, {0x2800, 0x28FF}, {0x2900, 0x297F}, {0x2980, 0x2982}, {0x2983, 0x2983}, {0x2984, 0x2984}, {0x2987, 0x2987}, {0x2988, 0x2988}, {0x2989, 0x2989}, {0x298A, 0x298A}, {0x298B, 0x298B}, {0x298C, 0x298C}, {0x298D, 0x298D}, {0x298E, 0x298E}, {0x298F, 0x298F}, {0x2990, 0x2990}, {0x2991, 0x2991}, {0x2992, 0x2992}, {0x2993, 0x2993}, {0x2994, 0x2994}, {0x2995, 0x2995}, {0x2996, 0x2996}, {0x2997, 0x2997}, {0x2998, 0x2998}, {0x2999, 0x29D7}, {0x29D8, 0x29D8}, {0x29D9, 0x29D9}, {0x29DA, 0x29DA}, {0x29DB, 0x29DB}, {0x29DC, 0x29FB}, {0x29FC, 0x29FC}, {0x29FD, 0x29FD}, {0x29FE, 0x29FF}, {0x2A00, 0x2AFF}, {0x2B00, 0x2B1A}, {0x2B1D, 0x2B2F}, {0x2B30, 0x2B44}, {0x2B45, 0x2B46}, {0x2B47, 0x2B4C}, {0x2B4D, 0x2B4F}, {0x2B51, 0x2B54}, {0x2B5A, 0x2B73}, {0x2B76, 0x2B95}, {0x2B98, 0x2BB9}, {0x2BBD, 0x2BC8}, {0x2BCA, 0x2BD1}, {0x2BEC, 0x2BEF}, {0x2C00, 0x2C2E}, {0x2C30, 0x2C5E}, {0x2C60, 0x2C7B}, {0x2C7C, 0x2C7D}, {0x2C7E, 0x2C7F}, {0x2C80, 0x2CE4}, {0x2CE5, 0x2CEA}, {0x2CEB, 0x2CEE}, {0x2CEF, 0x2CF1}, {0x2CF2, 0x2CF3}, {0x2CF9, 0x2CFC}, {0x2CFD, 0x2CFD}, {0x2CFE, 0x2CFF}, {0x2D00, 0x2D25}, {0x2D27, 0x2D27}, {0x2D2D, 0x2D2D}, {0x2D30, 0x2D67}, {0x2D6F, 0x2D6F}, {0x2D70, 0x2D70}, {0x2D7F, 0x2D7F}, {0x2D80, 0x2D96}, {0x2DA0, 0x2DA6}, {0x2DA8, 0x2DAE}, {0x2DB0, 0x2DB6}, {0x2DB8, 0x2DBE}, {0x2DC0, 0x2DC6}, {0x2DC8, 0x2DCE}, {0x2DD0, 0x2DD6}, {0x2DD8, 0x2DDE}, {0x2DE0, 0x2DFF}, {0x2E00, 0x2E01}, {0x2E02, 0x2E02}, {0x2E03, 0x2E03}, {0x2E04, 0x2E04}, {0x2E05, 0x2E05}, {0x2E06, 0x2E08}, {0x2E09, 0x2E09}, {0x2E0A, 0x2E0A}, {0x2E0B, 0x2E0B}, {0x2E0C, 0x2E0C}, {0x2E0D, 0x2E0D}, {0x2E0E, 0x2E16}, {0x2E17, 0x2E17}, {0x2E18, 0x2E19}, {0x2E1A, 0x2E1A}, {0x2E1B, 0x2E1B}, {0x2E1C, 0x2E1C}, {0x2E1D, 0x2E1D}, {0x2E1E, 0x2E1F}, {0x2E20, 0x2E20}, {0x2E21, 0x2E21}, {0x2E22, 0x2E22}, {0x2E23, 0x2E23}, {0x2E24, 0x2E24}, {0x2E25, 0x2E25}, {0x2E26, 0x2E26}, {0x2E27, 0x2E27}, {0x2E28, 0x2E28}, {0x2E29, 0x2E29}, {0x2E2A, 0x2E2E}, {0x2E2F, 0x2E2F}, {0x2E30, 0x2E39}, {0x2E3A, 0x2E3B}, {0x2E3C, 0x2E3F}, {0x2E40, 0x2E40}, {0x2E41, 0x2E41}, {0x2E42, 0x2E42}, {0x2E43, 0x2E44}, {0x303F, 0x303F}, {0x4DC0, 0x4DFF}, {0xA4D0, 0xA4F7}, {0xA4F8, 0xA4FD}, {0xA4FE, 0xA4FF}, {0xA500, 0xA60B}, {0xA60C, 0xA60C}, {0xA60D, 0xA60F}, {0xA610, 0xA61F}, {0xA620, 0xA629}, {0xA62A, 0xA62B}, {0xA640, 0xA66D}, {0xA66E, 0xA66E}, {0xA66F, 0xA66F}, {0xA670, 0xA672}, {0xA673, 0xA673}, {0xA674, 0xA67D}, {0xA67E, 0xA67E}, {0xA67F, 0xA67F}, {0xA680, 0xA69B}, {0xA69C, 0xA69D}, {0xA69E, 0xA69F}, {0xA6A0, 0xA6E5}, {0xA6E6, 0xA6EF}, {0xA6F0, 0xA6F1}, {0xA6F2, 0xA6F7}, {0xA700, 0xA716}, {0xA717, 0xA71F}, {0xA720, 0xA721}, {0xA722, 0xA76F}, {0xA770, 0xA770}, {0xA771, 0xA787}, {0xA788, 0xA788}, {0xA789, 0xA78A}, {0xA78B, 0xA78E}, {0xA78F, 0xA78F}, {0xA790, 0xA7AE}, {0xA7B0, 0xA7B7}, {0xA7F7, 0xA7F7}, {0xA7F8, 0xA7F9}, {0xA7FA, 0xA7FA}, {0xA7FB, 0xA7FF}, {0xA800, 0xA801}, {0xA802, 0xA802}, {0xA803, 0xA805}, {0xA806, 0xA806}, {0xA807, 0xA80A}, {0xA80B, 0xA80B}, {0xA80C, 0xA822}, {0xA823, 0xA824}, {0xA825, 0xA826}, {0xA827, 0xA827}, {0xA828, 0xA82B}, {0xA830, 0xA835}, {0xA836, 0xA837}, {0xA838, 0xA838}, {0xA839, 0xA839}, {0xA840, 0xA873}, {0xA874, 0xA877}, {0xA880, 0xA881}, {0xA882, 0xA8B3}, {0xA8B4, 0xA8C3}, {0xA8C4, 0xA8C5}, {0xA8CE, 0xA8CF}, {0xA8D0, 0xA8D9}, {0xA8E0, 0xA8F1}, {0xA8F2, 0xA8F7}, {0xA8F8, 0xA8FA}, {0xA8FB, 0xA8FB}, {0xA8FC, 0xA8FC}, {0xA8FD, 0xA8FD}, {0xA900, 0xA909}, {0xA90A, 0xA925}, {0xA926, 0xA92D}, {0xA92E, 0xA92F}, {0xA930, 0xA946}, {0xA947, 0xA951}, {0xA952, 0xA953}, {0xA95F, 0xA95F}, {0xA980, 0xA982}, {0xA983, 0xA983}, {0xA984, 0xA9B2}, {0xA9B3, 0xA9B3}, {0xA9B4, 0xA9B5}, {0xA9B6, 0xA9B9}, {0xA9BA, 0xA9BB}, {0xA9BC, 0xA9BC}, {0xA9BD, 0xA9C0}, {0xA9C1, 0xA9CD}, {0xA9CF, 0xA9CF}, {0xA9D0, 0xA9D9}, {0xA9DE, 0xA9DF}, {0xA9E0, 0xA9E4}, {0xA9E5, 0xA9E5}, {0xA9E6, 0xA9E6}, {0xA9E7, 0xA9EF}, {0xA9F0, 0xA9F9}, {0xA9FA, 0xA9FE}, {0xAA00, 0xAA28}, {0xAA29, 0xAA2E}, {0xAA2F, 0xAA30}, {0xAA31, 0xAA32}, {0xAA33, 0xAA34}, {0xAA35, 0xAA36}, {0xAA40, 0xAA42}, {0xAA43, 0xAA43}, {0xAA44, 0xAA4B}, {0xAA4C, 0xAA4C}, {0xAA4D, 0xAA4D}, {0xAA50, 0xAA59}, {0xAA5C, 0xAA5F}, {0xAA60, 0xAA6F}, {0xAA70, 0xAA70}, {0xAA71, 0xAA76}, {0xAA77, 0xAA79}, {0xAA7A, 0xAA7A}, {0xAA7B, 0xAA7B}, {0xAA7C, 0xAA7C}, {0xAA7D, 0xAA7D}, {0xAA7E, 0xAA7F}, {0xAA80, 0xAAAF}, {0xAAB0, 0xAAB0}, {0xAAB1, 0xAAB1}, {0xAAB2, 0xAAB4}, {0xAAB5, 0xAAB6}, {0xAAB7, 0xAAB8}, {0xAAB9, 0xAABD}, {0xAABE, 0xAABF}, {0xAAC0, 0xAAC0}, {0xAAC1, 0xAAC1}, {0xAAC2, 0xAAC2}, {0xAADB, 0xAADC}, {0xAADD, 0xAADD}, {0xAADE, 0xAADF}, {0xAAE0, 0xAAEA}, {0xAAEB, 0xAAEB}, {0xAAEC, 0xAAED}, {0xAAEE, 0xAAEF}, {0xAAF0, 0xAAF1}, {0xAAF2, 0xAAF2}, {0xAAF3, 0xAAF4}, {0xAAF5, 0xAAF5}, {0xAAF6, 0xAAF6}, {0xAB01, 0xAB06}, {0xAB09, 0xAB0E}, {0xAB11, 0xAB16}, {0xAB20, 0xAB26}, {0xAB28, 0xAB2E}, {0xAB30, 0xAB5A}, {0xAB5B, 0xAB5B}, {0xAB5C, 0xAB5F}, {0xAB60, 0xAB65}, {0xAB70, 0xABBF}, {0xABC0, 0xABE2}, {0xABE3, 0xABE4}, {0xABE5, 0xABE5}, {0xABE6, 0xABE7}, {0xABE8, 0xABE8}, {0xABE9, 0xABEA}, {0xABEB, 0xABEB}, {0xABEC, 0xABEC}, {0xABED, 0xABED}, {0xABF0, 0xABF9}, {0xD7B0, 0xD7C6}, {0xD7CB, 0xD7FB}, {0xD800, 0xDB7F}, {0xDB80, 0xDBFF}, {0xDC00, 0xDFFF}, {0xFB00, 0xFB06}, {0xFB13, 0xFB17}, {0xFB1D, 0xFB1D}, {0xFB1E, 0xFB1E}, {0xFB1F, 0xFB28}, {0xFB29, 0xFB29}, {0xFB2A, 0xFB36}, {0xFB38, 0xFB3C}, {0xFB3E, 0xFB3E}, {0xFB40, 0xFB41}, {0xFB43, 0xFB44}, {0xFB46, 0xFB4F}, {0xFB50, 0xFBB1}, {0xFBB2, 0xFBC1}, {0xFBD3, 0xFD3D}, {0xFD3E, 0xFD3E}, {0xFD3F, 0xFD3F}, {0xFD50, 0xFD8F}, {0xFD92, 0xFDC7}, {0xFDF0, 0xFDFB}, {0xFDFC, 0xFDFC}, {0xFDFD, 0xFDFD}, {0xFE20, 0xFE2F}, {0xFE70, 0xFE74}, {0xFE76, 0xFEFC}, {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, {0xFFFC, 0xFFFC}, {0x10000, 0x1000B}, {0x1000D, 0x10026}, {0x10028, 0x1003A}, {0x1003C, 0x1003D}, {0x1003F, 0x1004D}, {0x10050, 0x1005D}, {0x10080, 0x100FA}, {0x10100, 0x10102}, {0x10107, 0x10133}, {0x10137, 0x1013F}, {0x10140, 0x10174}, {0x10175, 0x10178}, {0x10179, 0x10189}, {0x1018A, 0x1018B}, {0x1018C, 0x1018E}, {0x10190, 0x1019B}, {0x101A0, 0x101A0}, {0x101D0, 0x101FC}, {0x101FD, 0x101FD}, {0x10280, 0x1029C}, {0x102A0, 0x102D0}, {0x102E0, 0x102E0}, {0x102E1, 0x102FB}, {0x10300, 0x1031F}, {0x10320, 0x10323}, {0x10330, 0x10340}, {0x10341, 0x10341}, {0x10342, 0x10349}, {0x1034A, 0x1034A}, {0x10350, 0x10375}, {0x10376, 0x1037A}, {0x10380, 0x1039D}, {0x1039F, 0x1039F}, {0x103A0, 0x103C3}, {0x103C8, 0x103CF}, {0x103D0, 0x103D0}, {0x103D1, 0x103D5}, {0x10400, 0x1044F}, {0x10450, 0x1047F}, {0x10480, 0x1049D}, {0x104A0, 0x104A9}, {0x104B0, 0x104D3}, {0x104D8, 0x104FB}, {0x10500, 0x10527}, {0x10530, 0x10563}, {0x1056F, 0x1056F}, {0x10600, 0x10736}, {0x10740, 0x10755}, {0x10760, 0x10767}, {0x10800, 0x10805}, {0x10808, 0x10808}, {0x1080A, 0x10835}, {0x10837, 0x10838}, {0x1083C, 0x1083C}, {0x1083F, 0x1083F}, {0x10840, 0x10855}, {0x10857, 0x10857}, {0x10858, 0x1085F}, {0x10860, 0x10876}, {0x10877, 0x10878}, {0x10879, 0x1087F}, {0x10880, 0x1089E}, {0x108A7, 0x108AF}, {0x108E0, 0x108F2}, {0x108F4, 0x108F5}, {0x108FB, 0x108FF}, {0x10900, 0x10915}, {0x10916, 0x1091B}, {0x1091F, 0x1091F}, {0x10920, 0x10939}, {0x1093F, 0x1093F}, {0x10980, 0x1099F}, {0x109A0, 0x109B7}, {0x109BC, 0x109BD}, {0x109BE, 0x109BF}, {0x109C0, 0x109CF}, {0x109D2, 0x109FF}, {0x10A00, 0x10A00}, {0x10A01, 0x10A03}, {0x10A05, 0x10A06}, {0x10A0C, 0x10A0F}, {0x10A10, 0x10A13}, {0x10A15, 0x10A17}, {0x10A19, 0x10A33}, {0x10A38, 0x10A3A}, {0x10A3F, 0x10A3F}, {0x10A40, 0x10A47}, {0x10A50, 0x10A58}, {0x10A60, 0x10A7C}, {0x10A7D, 0x10A7E}, {0x10A7F, 0x10A7F}, {0x10A80, 0x10A9C}, {0x10A9D, 0x10A9F}, {0x10AC0, 0x10AC7}, {0x10AC8, 0x10AC8}, {0x10AC9, 0x10AE4}, {0x10AE5, 0x10AE6}, {0x10AEB, 0x10AEF}, {0x10AF0, 0x10AF6}, {0x10B00, 0x10B35}, {0x10B39, 0x10B3F}, {0x10B40, 0x10B55}, {0x10B58, 0x10B5F}, {0x10B60, 0x10B72}, {0x10B78, 0x10B7F}, {0x10B80, 0x10B91}, {0x10B99, 0x10B9C}, {0x10BA9, 0x10BAF}, {0x10C00, 0x10C48}, {0x10C80, 0x10CB2}, {0x10CC0, 0x10CF2}, {0x10CFA, 0x10CFF}, {0x10E60, 0x10E7E}, {0x11000, 0x11000}, {0x11001, 0x11001}, {0x11002, 0x11002}, {0x11003, 0x11037}, {0x11038, 0x11046}, {0x11047, 0x1104D}, {0x11052, 0x11065}, {0x11066, 0x1106F}, {0x1107F, 0x1107F}, {0x11080, 0x11081}, {0x11082, 0x11082}, {0x11083, 0x110AF}, {0x110B0, 0x110B2}, {0x110B3, 0x110B6}, {0x110B7, 0x110B8}, {0x110B9, 0x110BA}, {0x110BB, 0x110BC}, {0x110BD, 0x110BD}, {0x110BE, 0x110C1}, {0x110D0, 0x110E8}, {0x110F0, 0x110F9}, {0x11100, 0x11102}, {0x11103, 0x11126}, {0x11127, 0x1112B}, {0x1112C, 0x1112C}, {0x1112D, 0x11134}, {0x11136, 0x1113F}, {0x11140, 0x11143}, {0x11150, 0x11172}, {0x11173, 0x11173}, {0x11174, 0x11175}, {0x11176, 0x11176}, {0x11180, 0x11181}, {0x11182, 0x11182}, {0x11183, 0x111B2}, {0x111B3, 0x111B5}, {0x111B6, 0x111BE}, {0x111BF, 0x111C0}, {0x111C1, 0x111C4}, {0x111C5, 0x111C9}, {0x111CA, 0x111CC}, {0x111CD, 0x111CD}, {0x111D0, 0x111D9}, {0x111DA, 0x111DA}, {0x111DB, 0x111DB}, {0x111DC, 0x111DC}, {0x111DD, 0x111DF}, {0x111E1, 0x111F4}, {0x11200, 0x11211}, {0x11213, 0x1122B}, {0x1122C, 0x1122E}, {0x1122F, 0x11231}, {0x11232, 0x11233}, {0x11234, 0x11234}, {0x11235, 0x11235}, {0x11236, 0x11237}, {0x11238, 0x1123D}, {0x1123E, 0x1123E}, {0x11280, 0x11286}, {0x11288, 0x11288}, {0x1128A, 0x1128D}, {0x1128F, 0x1129D}, {0x1129F, 0x112A8}, {0x112A9, 0x112A9}, {0x112B0, 0x112DE}, {0x112DF, 0x112DF}, {0x112E0, 0x112E2}, {0x112E3, 0x112EA}, {0x112F0, 0x112F9}, {0x11300, 0x11301}, {0x11302, 0x11303}, {0x11305, 0x1130C}, {0x1130F, 0x11310}, {0x11313, 0x11328}, {0x1132A, 0x11330}, {0x11332, 0x11333}, {0x11335, 0x11339}, {0x1133C, 0x1133C}, {0x1133D, 0x1133D}, {0x1133E, 0x1133F}, {0x11340, 0x11340}, {0x11341, 0x11344}, {0x11347, 0x11348}, {0x1134B, 0x1134D}, {0x11350, 0x11350}, {0x11357, 0x11357}, {0x1135D, 0x11361}, {0x11362, 0x11363}, {0x11366, 0x1136C}, {0x11370, 0x11374}, {0x11400, 0x11434}, {0x11435, 0x11437}, {0x11438, 0x1143F}, {0x11440, 0x11441}, {0x11442, 0x11444}, {0x11445, 0x11445}, {0x11446, 0x11446}, {0x11447, 0x1144A}, {0x1144B, 0x1144F}, {0x11450, 0x11459}, {0x1145B, 0x1145B}, {0x1145D, 0x1145D}, {0x11480, 0x114AF}, {0x114B0, 0x114B2}, {0x114B3, 0x114B8}, {0x114B9, 0x114B9}, {0x114BA, 0x114BA}, {0x114BB, 0x114BE}, {0x114BF, 0x114C0}, {0x114C1, 0x114C1}, {0x114C2, 0x114C3}, {0x114C4, 0x114C5}, {0x114C6, 0x114C6}, {0x114C7, 0x114C7}, {0x114D0, 0x114D9}, {0x11580, 0x115AE}, {0x115AF, 0x115B1}, {0x115B2, 0x115B5}, {0x115B8, 0x115BB}, {0x115BC, 0x115BD}, {0x115BE, 0x115BE}, {0x115BF, 0x115C0}, {0x115C1, 0x115D7}, {0x115D8, 0x115DB}, {0x115DC, 0x115DD}, {0x11600, 0x1162F}, {0x11630, 0x11632}, {0x11633, 0x1163A}, {0x1163B, 0x1163C}, {0x1163D, 0x1163D}, {0x1163E, 0x1163E}, {0x1163F, 0x11640}, {0x11641, 0x11643}, {0x11644, 0x11644}, {0x11650, 0x11659}, {0x11660, 0x1166C}, {0x11680, 0x116AA}, {0x116AB, 0x116AB}, {0x116AC, 0x116AC}, {0x116AD, 0x116AD}, {0x116AE, 0x116AF}, {0x116B0, 0x116B5}, {0x116B6, 0x116B6}, {0x116B7, 0x116B7}, {0x116C0, 0x116C9}, {0x11700, 0x11719}, {0x1171D, 0x1171F}, {0x11720, 0x11721}, {0x11722, 0x11725}, {0x11726, 0x11726}, {0x11727, 0x1172B}, {0x11730, 0x11739}, {0x1173A, 0x1173B}, {0x1173C, 0x1173E}, {0x1173F, 0x1173F}, {0x118A0, 0x118DF}, {0x118E0, 0x118E9}, {0x118EA, 0x118F2}, {0x118FF, 0x118FF}, {0x11AC0, 0x11AF8}, {0x11C00, 0x11C08}, {0x11C0A, 0x11C2E}, {0x11C2F, 0x11C2F}, {0x11C30, 0x11C36}, {0x11C38, 0x11C3D}, {0x11C3E, 0x11C3E}, {0x11C3F, 0x11C3F}, {0x11C40, 0x11C40}, {0x11C41, 0x11C45}, {0x11C50, 0x11C59}, {0x11C5A, 0x11C6C}, {0x11C70, 0x11C71}, {0x11C72, 0x11C8F}, {0x11C92, 0x11CA7}, {0x11CA9, 0x11CA9}, {0x11CAA, 0x11CB0}, {0x11CB1, 0x11CB1}, {0x11CB2, 0x11CB3}, {0x11CB4, 0x11CB4}, {0x11CB5, 0x11CB6}, {0x12000, 0x12399}, {0x12400, 0x1246E}, {0x12470, 0x12474}, {0x12480, 0x12543}, {0x13000, 0x1342E}, {0x14400, 0x14646}, {0x16800, 0x16A38}, {0x16A40, 0x16A5E}, {0x16A60, 0x16A69}, {0x16A6E, 0x16A6F}, {0x16AD0, 0x16AED}, {0x16AF0, 0x16AF4}, {0x16AF5, 0x16AF5}, {0x16B00, 0x16B2F}, {0x16B30, 0x16B36}, {0x16B37, 0x16B3B}, {0x16B3C, 0x16B3F}, {0x16B40, 0x16B43}, {0x16B44, 0x16B44}, {0x16B45, 0x16B45}, {0x16B50, 0x16B59}, {0x16B5B, 0x16B61}, {0x16B63, 0x16B77}, {0x16B7D, 0x16B8F}, {0x16F00, 0x16F44}, {0x16F50, 0x16F50}, {0x16F51, 0x16F7E}, {0x16F8F, 0x16F92}, {0x16F93, 0x16F9F}, {0x1BC00, 0x1BC6A}, {0x1BC70, 0x1BC7C}, {0x1BC80, 0x1BC88}, {0x1BC90, 0x1BC99}, {0x1BC9C, 0x1BC9C}, {0x1BC9D, 0x1BC9E}, {0x1BC9F, 0x1BC9F}, {0x1BCA0, 0x1BCA3}, {0x1D000, 0x1D0F5}, {0x1D100, 0x1D126}, {0x1D129, 0x1D164}, {0x1D165, 0x1D166}, {0x1D167, 0x1D169}, {0x1D16A, 0x1D16C}, {0x1D16D, 0x1D172}, {0x1D173, 0x1D17A}, {0x1D17B, 0x1D182}, {0x1D183, 0x1D184}, {0x1D185, 0x1D18B}, {0x1D18C, 0x1D1A9}, {0x1D1AA, 0x1D1AD}, {0x1D1AE, 0x1D1E8}, {0x1D200, 0x1D241}, {0x1D242, 0x1D244}, {0x1D245, 0x1D245}, {0x1D300, 0x1D356}, {0x1D360, 0x1D371}, {0x1D400, 0x1D454}, {0x1D456, 0x1D49C}, {0x1D49E, 0x1D49F}, {0x1D4A2, 0x1D4A2}, {0x1D4A5, 0x1D4A6}, {0x1D4A9, 0x1D4AC}, {0x1D4AE, 0x1D4B9}, {0x1D4BB, 0x1D4BB}, {0x1D4BD, 0x1D4C3}, {0x1D4C5, 0x1D505}, {0x1D507, 0x1D50A}, {0x1D50D, 0x1D514}, {0x1D516, 0x1D51C}, {0x1D51E, 0x1D539}, {0x1D53B, 0x1D53E}, {0x1D540, 0x1D544}, {0x1D546, 0x1D546}, {0x1D54A, 0x1D550}, {0x1D552, 0x1D6A5}, {0x1D6A8, 0x1D6C0}, {0x1D6C1, 0x1D6C1}, {0x1D6C2, 0x1D6DA}, {0x1D6DB, 0x1D6DB}, {0x1D6DC, 0x1D6FA}, {0x1D6FB, 0x1D6FB}, {0x1D6FC, 0x1D714}, {0x1D715, 0x1D715}, {0x1D716, 0x1D734}, {0x1D735, 0x1D735}, {0x1D736, 0x1D74E}, {0x1D74F, 0x1D74F}, {0x1D750, 0x1D76E}, {0x1D76F, 0x1D76F}, {0x1D770, 0x1D788}, {0x1D789, 0x1D789}, {0x1D78A, 0x1D7A8}, {0x1D7A9, 0x1D7A9}, {0x1D7AA, 0x1D7C2}, {0x1D7C3, 0x1D7C3}, {0x1D7C4, 0x1D7CB}, {0x1D7CE, 0x1D7FF}, {0x1D800, 0x1D9FF}, {0x1DA00, 0x1DA36}, {0x1DA37, 0x1DA3A}, {0x1DA3B, 0x1DA6C}, {0x1DA6D, 0x1DA74}, {0x1DA75, 0x1DA75}, {0x1DA76, 0x1DA83}, {0x1DA84, 0x1DA84}, {0x1DA85, 0x1DA86}, {0x1DA87, 0x1DA8B}, {0x1DA9B, 0x1DA9F}, {0x1DAA1, 0x1DAAF}, {0x1E000, 0x1E006}, {0x1E008, 0x1E018}, {0x1E01B, 0x1E021}, {0x1E023, 0x1E024}, {0x1E026, 0x1E02A}, {0x1E800, 0x1E8C4}, {0x1E8C7, 0x1E8CF}, {0x1E8D0, 0x1E8D6}, {0x1E900, 0x1E943}, {0x1E944, 0x1E94A}, {0x1E950, 0x1E959}, {0x1E95E, 0x1E95F}, {0x1EE00, 0x1EE03}, {0x1EE05, 0x1EE1F}, {0x1EE21, 0x1EE22}, {0x1EE24, 0x1EE24}, {0x1EE27, 0x1EE27}, {0x1EE29, 0x1EE32}, {0x1EE34, 0x1EE37}, {0x1EE39, 0x1EE39}, {0x1EE3B, 0x1EE3B}, {0x1EE42, 0x1EE42}, {0x1EE47, 0x1EE47}, {0x1EE49, 0x1EE49}, {0x1EE4B, 0x1EE4B}, {0x1EE4D, 0x1EE4F}, {0x1EE51, 0x1EE52}, {0x1EE54, 0x1EE54}, {0x1EE57, 0x1EE57}, {0x1EE59, 0x1EE59}, {0x1EE5B, 0x1EE5B}, {0x1EE5D, 0x1EE5D}, {0x1EE5F, 0x1EE5F}, {0x1EE61, 0x1EE62}, {0x1EE64, 0x1EE64}, {0x1EE67, 0x1EE6A}, {0x1EE6C, 0x1EE72}, {0x1EE74, 0x1EE77}, {0x1EE79, 0x1EE7C}, {0x1EE7E, 0x1EE7E}, {0x1EE80, 0x1EE89}, {0x1EE8B, 0x1EE9B}, {0x1EEA1, 0x1EEA3}, {0x1EEA5, 0x1EEA9}, {0x1EEAB, 0x1EEBB}, {0x1EEF0, 0x1EEF1}, {0x1F000, 0x1F003}, {0x1F005, 0x1F02B}, {0x1F030, 0x1F093}, {0x1F0A0, 0x1F0AE}, {0x1F0B1, 0x1F0BF}, {0x1F0C1, 0x1F0CE}, {0x1F0D1, 0x1F0F5}, {0x1F10B, 0x1F10C}, {0x1F12E, 0x1F12E}, {0x1F16A, 0x1F16B}, {0x1F1E6, 0x1F1FF}, {0x1F321, 0x1F32C}, {0x1F336, 0x1F336}, {0x1F37D, 0x1F37D}, {0x1F394, 0x1F39F}, {0x1F3CB, 0x1F3CE}, {0x1F3D4, 0x1F3DF}, {0x1F3F1, 0x1F3F3}, {0x1F3F5, 0x1F3F7}, {0x1F43F, 0x1F43F}, {0x1F441, 0x1F441}, {0x1F4FD, 0x1F4FE}, {0x1F53E, 0x1F54A}, {0x1F54F, 0x1F54F}, {0x1F568, 0x1F579}, {0x1F57B, 0x1F594}, {0x1F597, 0x1F5A3}, {0x1F5A5, 0x1F5FA}, {0x1F650, 0x1F67F}, {0x1F6C6, 0x1F6CB}, {0x1F6CD, 0x1F6CF}, {0x1F6E0, 0x1F6EA}, {0x1F6F0, 0x1F6F3}, {0x1F700, 0x1F773}, {0x1F780, 0x1F7D4}, {0x1F800, 0x1F80B}, {0x1F810, 0x1F847}, {0x1F850, 0x1F859}, {0x1F860, 0x1F887}, {0x1F890, 0x1F8AD}, {0xE0001, 0xE0001}, {0xE0020, 0xE007F}, } // Condition have flag EastAsianWidth whether the current locale is CJK or not. type Condition struct { EastAsianWidth bool } // NewCondition return new instance of Condition which is current locale. func NewCondition() *Condition { return &Condition{EastAsianWidth} } // RuneWidth returns the number of cells in r. // See http://www.unicode.org/reports/tr11/ func (c *Condition) RuneWidth(r rune) int { switch { case r < 0 || r > 0x10FFFF || inTables(r, nonprint, combining, notassigned): return 0 case (c.EastAsianWidth && IsAmbiguousWidth(r)) || inTables(r, doublewidth, emoji): return 2 default: return 1 } } // StringWidth return width as you can see func (c *Condition) StringWidth(s string) (width int) { for _, r := range []rune(s) { width += c.RuneWidth(r) } return width } // Truncate return string truncated with w cells func (c *Condition) Truncate(s string, w int, tail string) string { if c.StringWidth(s) <= w { return s } r := []rune(s) tw := c.StringWidth(tail) w -= tw width := 0 i := 0 for ; i < len(r); i++ { cw := c.RuneWidth(r[i]) if width+cw > w { break } width += cw } return string(r[0:i]) + tail } // Wrap return string wrapped with w cells func (c *Condition) Wrap(s string, w int) string { width := 0 out := "" for _, r := range []rune(s) { cw := RuneWidth(r) if r == '\n' { out += string(r) width = 0 continue } else if width+cw > w { out += "\n" width = 0 out += string(r) width += cw continue } out += string(r) width += cw } return out } // FillLeft return string filled in left by spaces in w cells func (c *Condition) FillLeft(s string, w int) string { width := c.StringWidth(s) count := w - width if count > 0 { b := make([]byte, count) for i := range b { b[i] = ' ' } return string(b) + s } return s } // FillRight return string filled in left by spaces in w cells func (c *Condition) FillRight(s string, w int) string { width := c.StringWidth(s) count := w - width if count > 0 { b := make([]byte, count) for i := range b { b[i] = ' ' } return s + string(b) } return s } // RuneWidth returns the number of cells in r. // See http://www.unicode.org/reports/tr11/ func RuneWidth(r rune) int { return DefaultCondition.RuneWidth(r) } // IsAmbiguousWidth returns whether is ambiguous width or not. func IsAmbiguousWidth(r rune) bool { return inTables(r, private, ambiguous) } // IsNeutralWidth returns whether is neutral width or not. func IsNeutralWidth(r rune) bool { return inTable(r, neutral) } // StringWidth return width as you can see func StringWidth(s string) (width int) { return DefaultCondition.StringWidth(s) } // Truncate return string truncated with w cells func Truncate(s string, w int, tail string) string { return DefaultCondition.Truncate(s, w, tail) } // Wrap return string wrapped with w cells func Wrap(s string, w int) string { return DefaultCondition.Wrap(s, w) } // FillLeft return string filled in left by spaces in w cells func FillLeft(s string, w int) string { return DefaultCondition.FillLeft(s, w) } // FillRight return string filled in left by spaces in w cells func FillRight(s string, w int) string { return DefaultCondition.FillRight(s, w) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/README.mkd����������������������������������������0000644�0610621�0607500�00000001446�13172163420�024456� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������go-runewidth ============ [![Build Status](https://travis-ci.org/mattn/go-runewidth.png?branch=master)](https://travis-ci.org/mattn/go-runewidth) [![Coverage Status](https://coveralls.io/repos/mattn/go-runewidth/badge.png?branch=HEAD)](https://coveralls.io/r/mattn/go-runewidth?branch=HEAD) [![GoDoc](https://godoc.org/github.com/mattn/go-runewidth?status.svg)](http://godoc.org/github.com/mattn/go-runewidth) [![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-runewidth)](https://goreportcard.com/report/github.com/mattn/go-runewidth) Provides functions to get fixed width of the character or string. Usage ----- ```go runewidth.StringWidth("ã¤ã®ã â˜†HIRO") == 12 ``` Author ------ Yasuhiro Matsumoto License ------- under the MIT License: http://mattn.mit-license.org/2013 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/LICENSE�������������������������������������������0000644�0610621�0607500�00000002075�13172163420�024030� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The MIT License (MIT) Copyright (c) 2016 Yasuhiro Matsumoto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-runewidth/.travis.yml���������������������������������������0000644�0610621�0607500�00000000315�13172163420�025127� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go: - tip before_install: - go get github.com/mattn/goveralls - go get golang.org/x/tools/cmd/cover script: - $HOME/gopath/bin/goveralls -repotoken lAKAWPzcGsD3A8yBX3BGGtRUdJ6CaGERL �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163417�022331� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_windows_test.go�������������������������������0000644�0610621�0607500�00000001477�13172163417�027017� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build windows package isatty import ( "testing" ) func TestCygwinPipeName(t *testing.T) { tests := []struct { name string result bool }{ {``, false}, {`\msys-`, false}, {`\cygwin-----`, false}, {`\msys-x-PTY5-pty1-from-master`, false}, {`\cygwin-x-PTY5-from-master`, false}, {`\cygwin-x-pty2-from-toaster`, false}, {`\cygwin--pty2-from-master`, false}, {`\\cygwin-x-pty2-from-master`, false}, {`\cygwin-x-pty2-from-master-`, true}, // for the feature {`\cygwin-e022582115c10879-pty4-from-master`, true}, {`\msys-e022582115c10879-pty4-to-master`, true}, {`\cygwin-e022582115c10879-pty4-to-master`, true}, } for _, test := range tests { want := test.result got := isCygwinPipeName(test.name) if want != got { t.Fatalf("isatty(%q): got %v, want %v:", test.name, got, want) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_windows.go������������������������������������0000644�0610621�0607500�00000004127�13172163417�025753� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build windows // +build !appengine package isatty import ( "strings" "syscall" "unicode/utf16" "unsafe" ) const ( fileNameInfo uintptr = 2 fileTypePipe = 3 ) var ( kernel32 = syscall.NewLazyDLL("kernel32.dll") procGetConsoleMode = kernel32.NewProc("GetConsoleMode") procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx") procGetFileType = kernel32.NewProc("GetFileType") ) func init() { // Check if GetFileInformationByHandleEx is available. if procGetFileInformationByHandleEx.Find() != nil { procGetFileInformationByHandleEx = nil } } // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { var st uint32 r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) return r != 0 && e == 0 } // Check pipe name is used for cygwin/msys2 pty. // Cygwin/MSYS2 PTY has a name like: // \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master func isCygwinPipeName(name string) bool { token := strings.Split(name, "-") if len(token) < 5 { return false } if token[0] != `\msys` && token[0] != `\cygwin` { return false } if token[1] == "" { return false } if !strings.HasPrefix(token[2], "pty") { return false } if token[3] != `from` && token[3] != `to` { return false } if token[4] != "master" { return false } return true } // IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 // terminal. func IsCygwinTerminal(fd uintptr) bool { if procGetFileInformationByHandleEx == nil { return false } // Cygwin/msys's pty is a pipe. ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0) if ft != fileTypePipe || e != 0 { return false } var buf [2 + syscall.MAX_PATH]uint16 r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)), uintptr(len(buf)*2), 0, 0) if r == 0 || e != 0 { return false } l := *(*uint32)(unsafe.Pointer(&buf)) return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2]))) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_solaris.go������������������������������������0000644�0610621�0607500�00000000622�13172163417�025731� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build solaris // +build !appengine package isatty import ( "golang.org/x/sys/unix" ) // IsTerminal returns true if the given file descriptor is a terminal. // see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c func IsTerminal(fd uintptr) bool { var termio unix.Termio err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) return err == nil } ��������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_others_test.go��������������������������������0000644�0610621�0607500�00000000421�13172163417�026615� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows package isatty import ( "os" "testing" ) func TestTerminal(t *testing.T) { // test for non-panic IsTerminal(os.Stdout.Fd()) } func TestCygwinPipeName(t *testing.T) { if IsCygwinTerminal(os.Stdout.Fd()) { t.Fatal("should be false always") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_others.go�������������������������������������0000644�0610621�0607500�00000000374�13172163417�025565� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows // +build !appengine package isatty // IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 // terminal. This is also always false on this environment. func IsCygwinTerminal(fd uintptr) bool { return false } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_linux_ppc64x.go�������������������������������0000644�0610621�0607500�00000000637�13172163417�026626� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux // +build ppc64 ppc64le package isatty import ( "unsafe" syscall "golang.org/x/sys/unix" ) const ioctlReadTermios = syscall.TCGETS // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { var termios syscall.Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } �������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_linux.go��������������������������������������0000644�0610621�0607500�00000000625�13172163417�025417� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux // +build !appengine,!ppc64,!ppc64le package isatty import ( "syscall" "unsafe" ) const ioctlReadTermios = syscall.TCGETS // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { var termios syscall.Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } �����������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_bsd.go����������������������������������������0000644�0610621�0607500�00000000651�13172163417�025027� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build darwin freebsd openbsd netbsd dragonfly // +build !appengine package isatty import ( "syscall" "unsafe" ) const ioctlReadTermios = syscall.TIOCGETA // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { var termios syscall.Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } ���������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/isatty_appengine.go����������������������������������0000644�0610621�0607500�00000000646�13172163417�026231� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build appengine package isatty // IsTerminal returns true if the file descriptor is terminal which // is always false on on appengine classic which is a sandboxed PaaS. func IsTerminal(fd uintptr) bool { return false } // IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 // terminal. This is also always false on this environment. func IsCygwinTerminal(fd uintptr) bool { return false } ������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/example_test.go��������������������������������������0000644�0610621�0607500�00000000462�13172163417�025354� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package isatty_test import ( "fmt" "os" "github.com/mattn/go-isatty" ) func Example() { if isatty.IsTerminal(os.Stdout.Fd()) { fmt.Println("Is Terminal") } else if isatty.IsCygwinTerminal(os.Stdout.Fd()) { fmt.Println("Is Cygwin/MSYS2 Terminal") } else { fmt.Println("Is Not Terminal") } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/doc.go�����������������������������������������������0000644�0610621�0607500�00000000100�13172163417�023414� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package isatty implements interface to isatty package isatty ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/README.md��������������������������������������������0000644�0610621�0607500�00000002071�13172163417�023610� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# go-isatty [![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty) [![Build Status](https://travis-ci.org/mattn/go-isatty.svg?branch=master)](https://travis-ci.org/mattn/go-isatty) [![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master) [![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty) isatty for golang ## Usage ```go package main import ( "fmt" "github.com/mattn/go-isatty" "os" ) func main() { if isatty.IsTerminal(os.Stdout.Fd()) { fmt.Println("Is Terminal") } else if isatty.IsCygwinTerminal(os.Stdout.Fd()) { fmt.Println("Is Cygwin/MSYS2 Terminal") } else { fmt.Println("Is Not Terminal") } } ``` ## Installation ``` $ go get github.com/mattn/go-isatty ``` ## License MIT ## Author Yasuhiro Matsumoto (a.k.a mattn) ## Thanks * k-takata: base idea for IsCygwinTerminal https://github.com/k-takata/go-iscygpty �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/LICENSE����������������������������������������������0000644�0610621�0607500�00000002113�13172163417�023333� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) Yasuhiro MATSUMOTO <mattn.jp@gmail.com> MIT License (Expat) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-isatty/.travis.yml������������������������������������������0000644�0610621�0607500�00000000314�13172163417�024440� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go: - tip before_install: - go get github.com/mattn/goveralls - go get golang.org/x/tools/cmd/cover script: - $HOME/gopath/bin/goveralls -repotoken 3gHdORO5k5ziZcWMBxnd9LrMZaJs8m9x5 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163416�022755� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/noncolorable.go�����������������������������������0000644�0610621�0607500�00000001662�13172163416�025766� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package colorable import ( "bytes" "io" ) // NonColorable hold writer but remove escape sequence. type NonColorable struct { out io.Writer } // NewNonColorable return new instance of Writer which remove escape sequence from Writer. func NewNonColorable(w io.Writer) io.Writer { return &NonColorable{out: w} } // Write write data on console func (w *NonColorable) Write(data []byte) (n int, err error) { er := bytes.NewReader(data) var bw [1]byte loop: for { c1, err := er.ReadByte() if err != nil { break loop } if c1 != 0x1b { bw[0] = c1 w.out.Write(bw[:]) continue } c2, err := er.ReadByte() if err != nil { break loop } if c2 != 0x5b { continue } var buf bytes.Buffer for { c, err := er.ReadByte() if err != nil { break loop } if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { break } buf.Write([]byte(string(c))) } } return len(data), nil } ������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/colorable_windows.go������������������������������0000644�0610621�0607500�00000054255�13172163416�027033� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build windows // +build !appengine package colorable import ( "bytes" "io" "math" "os" "strconv" "strings" "syscall" "unsafe" "github.com/mattn/go-isatty" ) const ( foregroundBlue = 0x1 foregroundGreen = 0x2 foregroundRed = 0x4 foregroundIntensity = 0x8 foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) backgroundBlue = 0x10 backgroundGreen = 0x20 backgroundRed = 0x40 backgroundIntensity = 0x80 backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) ) const ( genericRead = 0x80000000 genericWrite = 0x40000000 ) const ( consoleTextmodeBuffer = 0x1 ) type wchar uint16 type short int16 type dword uint32 type word uint16 type coord struct { x short y short } type smallRect struct { left short top short right short bottom short } type consoleScreenBufferInfo struct { size coord cursorPosition coord attributes word window smallRect maximumWindowSize coord } type consoleCursorInfo struct { size dword visible int32 } var ( kernel32 = syscall.NewLazyDLL("kernel32.dll") procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) // Writer provide colorable Writer to the console type Writer struct { out io.Writer handle syscall.Handle althandle syscall.Handle oldattr word oldpos coord rest bytes.Buffer } // NewColorable return new instance of Writer which handle escape sequence from File. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") } if isatty.IsTerminal(file.Fd()) { var csbi consoleScreenBufferInfo handle := syscall.Handle(file.Fd()) procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) return &Writer{out: file, handle: handle, oldattr: csbi.attributes, oldpos: coord{0, 0}} } return file } // NewColorableStdout return new instance of Writer which handle escape sequence for stdout. func NewColorableStdout() io.Writer { return NewColorable(os.Stdout) } // NewColorableStderr return new instance of Writer which handle escape sequence for stderr. func NewColorableStderr() io.Writer { return NewColorable(os.Stderr) } var color256 = map[int]int{ 0: 0x000000, 1: 0x800000, 2: 0x008000, 3: 0x808000, 4: 0x000080, 5: 0x800080, 6: 0x008080, 7: 0xc0c0c0, 8: 0x808080, 9: 0xff0000, 10: 0x00ff00, 11: 0xffff00, 12: 0x0000ff, 13: 0xff00ff, 14: 0x00ffff, 15: 0xffffff, 16: 0x000000, 17: 0x00005f, 18: 0x000087, 19: 0x0000af, 20: 0x0000d7, 21: 0x0000ff, 22: 0x005f00, 23: 0x005f5f, 24: 0x005f87, 25: 0x005faf, 26: 0x005fd7, 27: 0x005fff, 28: 0x008700, 29: 0x00875f, 30: 0x008787, 31: 0x0087af, 32: 0x0087d7, 33: 0x0087ff, 34: 0x00af00, 35: 0x00af5f, 36: 0x00af87, 37: 0x00afaf, 38: 0x00afd7, 39: 0x00afff, 40: 0x00d700, 41: 0x00d75f, 42: 0x00d787, 43: 0x00d7af, 44: 0x00d7d7, 45: 0x00d7ff, 46: 0x00ff00, 47: 0x00ff5f, 48: 0x00ff87, 49: 0x00ffaf, 50: 0x00ffd7, 51: 0x00ffff, 52: 0x5f0000, 53: 0x5f005f, 54: 0x5f0087, 55: 0x5f00af, 56: 0x5f00d7, 57: 0x5f00ff, 58: 0x5f5f00, 59: 0x5f5f5f, 60: 0x5f5f87, 61: 0x5f5faf, 62: 0x5f5fd7, 63: 0x5f5fff, 64: 0x5f8700, 65: 0x5f875f, 66: 0x5f8787, 67: 0x5f87af, 68: 0x5f87d7, 69: 0x5f87ff, 70: 0x5faf00, 71: 0x5faf5f, 72: 0x5faf87, 73: 0x5fafaf, 74: 0x5fafd7, 75: 0x5fafff, 76: 0x5fd700, 77: 0x5fd75f, 78: 0x5fd787, 79: 0x5fd7af, 80: 0x5fd7d7, 81: 0x5fd7ff, 82: 0x5fff00, 83: 0x5fff5f, 84: 0x5fff87, 85: 0x5fffaf, 86: 0x5fffd7, 87: 0x5fffff, 88: 0x870000, 89: 0x87005f, 90: 0x870087, 91: 0x8700af, 92: 0x8700d7, 93: 0x8700ff, 94: 0x875f00, 95: 0x875f5f, 96: 0x875f87, 97: 0x875faf, 98: 0x875fd7, 99: 0x875fff, 100: 0x878700, 101: 0x87875f, 102: 0x878787, 103: 0x8787af, 104: 0x8787d7, 105: 0x8787ff, 106: 0x87af00, 107: 0x87af5f, 108: 0x87af87, 109: 0x87afaf, 110: 0x87afd7, 111: 0x87afff, 112: 0x87d700, 113: 0x87d75f, 114: 0x87d787, 115: 0x87d7af, 116: 0x87d7d7, 117: 0x87d7ff, 118: 0x87ff00, 119: 0x87ff5f, 120: 0x87ff87, 121: 0x87ffaf, 122: 0x87ffd7, 123: 0x87ffff, 124: 0xaf0000, 125: 0xaf005f, 126: 0xaf0087, 127: 0xaf00af, 128: 0xaf00d7, 129: 0xaf00ff, 130: 0xaf5f00, 131: 0xaf5f5f, 132: 0xaf5f87, 133: 0xaf5faf, 134: 0xaf5fd7, 135: 0xaf5fff, 136: 0xaf8700, 137: 0xaf875f, 138: 0xaf8787, 139: 0xaf87af, 140: 0xaf87d7, 141: 0xaf87ff, 142: 0xafaf00, 143: 0xafaf5f, 144: 0xafaf87, 145: 0xafafaf, 146: 0xafafd7, 147: 0xafafff, 148: 0xafd700, 149: 0xafd75f, 150: 0xafd787, 151: 0xafd7af, 152: 0xafd7d7, 153: 0xafd7ff, 154: 0xafff00, 155: 0xafff5f, 156: 0xafff87, 157: 0xafffaf, 158: 0xafffd7, 159: 0xafffff, 160: 0xd70000, 161: 0xd7005f, 162: 0xd70087, 163: 0xd700af, 164: 0xd700d7, 165: 0xd700ff, 166: 0xd75f00, 167: 0xd75f5f, 168: 0xd75f87, 169: 0xd75faf, 170: 0xd75fd7, 171: 0xd75fff, 172: 0xd78700, 173: 0xd7875f, 174: 0xd78787, 175: 0xd787af, 176: 0xd787d7, 177: 0xd787ff, 178: 0xd7af00, 179: 0xd7af5f, 180: 0xd7af87, 181: 0xd7afaf, 182: 0xd7afd7, 183: 0xd7afff, 184: 0xd7d700, 185: 0xd7d75f, 186: 0xd7d787, 187: 0xd7d7af, 188: 0xd7d7d7, 189: 0xd7d7ff, 190: 0xd7ff00, 191: 0xd7ff5f, 192: 0xd7ff87, 193: 0xd7ffaf, 194: 0xd7ffd7, 195: 0xd7ffff, 196: 0xff0000, 197: 0xff005f, 198: 0xff0087, 199: 0xff00af, 200: 0xff00d7, 201: 0xff00ff, 202: 0xff5f00, 203: 0xff5f5f, 204: 0xff5f87, 205: 0xff5faf, 206: 0xff5fd7, 207: 0xff5fff, 208: 0xff8700, 209: 0xff875f, 210: 0xff8787, 211: 0xff87af, 212: 0xff87d7, 213: 0xff87ff, 214: 0xffaf00, 215: 0xffaf5f, 216: 0xffaf87, 217: 0xffafaf, 218: 0xffafd7, 219: 0xffafff, 220: 0xffd700, 221: 0xffd75f, 222: 0xffd787, 223: 0xffd7af, 224: 0xffd7d7, 225: 0xffd7ff, 226: 0xffff00, 227: 0xffff5f, 228: 0xffff87, 229: 0xffffaf, 230: 0xffffd7, 231: 0xffffff, 232: 0x080808, 233: 0x121212, 234: 0x1c1c1c, 235: 0x262626, 236: 0x303030, 237: 0x3a3a3a, 238: 0x444444, 239: 0x4e4e4e, 240: 0x585858, 241: 0x626262, 242: 0x6c6c6c, 243: 0x767676, 244: 0x808080, 245: 0x8a8a8a, 246: 0x949494, 247: 0x9e9e9e, 248: 0xa8a8a8, 249: 0xb2b2b2, 250: 0xbcbcbc, 251: 0xc6c6c6, 252: 0xd0d0d0, 253: 0xdadada, 254: 0xe4e4e4, 255: 0xeeeeee, } // `\033]0;TITLESTR\007` func doTitleSequence(er *bytes.Reader) error { var c byte var err error c, err = er.ReadByte() if err != nil { return err } if c != '0' && c != '2' { return nil } c, err = er.ReadByte() if err != nil { return err } if c != ';' { return nil } title := make([]byte, 0, 80) for { c, err = er.ReadByte() if err != nil { return err } if c == 0x07 || c == '\n' { break } title = append(title, c) } if len(title) > 0 { title8, err := syscall.UTF16PtrFromString(string(title)) if err == nil { procSetConsoleTitle.Call(uintptr(unsafe.Pointer(title8))) } } return nil } // Write write data on console func (w *Writer) Write(data []byte) (n int, err error) { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) handle := w.handle var er *bytes.Reader if w.rest.Len() > 0 { var rest bytes.Buffer w.rest.WriteTo(&rest) w.rest.Reset() rest.Write(data) er = bytes.NewReader(rest.Bytes()) } else { er = bytes.NewReader(data) } var bw [1]byte loop: for { c1, err := er.ReadByte() if err != nil { break loop } if c1 != 0x1b { bw[0] = c1 w.out.Write(bw[:]) continue } c2, err := er.ReadByte() if err != nil { break loop } if c2 == ']' { w.rest.WriteByte(c1) w.rest.WriteByte(c2) er.WriteTo(&w.rest) if bytes.IndexByte(w.rest.Bytes(), 0x07) == -1 { break loop } er = bytes.NewReader(w.rest.Bytes()[2:]) err := doTitleSequence(er) if err != nil { break loop } w.rest.Reset() continue } if c2 != 0x5b { continue } w.rest.WriteByte(c1) w.rest.WriteByte(c2) er.WriteTo(&w.rest) var buf bytes.Buffer var m byte for i, c := range w.rest.Bytes()[2:] { if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { m = c er = bytes.NewReader(w.rest.Bytes()[2+i+1:]) w.rest.Reset() break } buf.Write([]byte(string(c))) } if m == 0 { break loop } switch m { case 'A': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y -= short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'B': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y += short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'C': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x += short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'D': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x -= short(n) if csbi.cursorPosition.x < 0 { csbi.cursorPosition.x = 0 } procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'E': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y += short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'F': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y -= short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'G': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = short(n - 1) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'H', 'f': procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) if buf.Len() > 0 { token := strings.Split(buf.String(), ";") switch len(token) { case 1: n1, err := strconv.Atoi(token[0]) if err != nil { continue } csbi.cursorPosition.y = short(n1 - 1) case 2: n1, err := strconv.Atoi(token[0]) if err != nil { continue } n2, err := strconv.Atoi(token[1]) if err != nil { continue } csbi.cursorPosition.x = short(n2 - 1) csbi.cursorPosition.y = short(n1 - 1) } } else { csbi.cursorPosition.y = 0 } procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'J': n := 0 if buf.Len() > 0 { n, err = strconv.Atoi(buf.String()) if err != nil { continue } } var count, written dword var cursor coord procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) switch n { case 0: cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) case 1: cursor = coord{x: csbi.window.left, y: csbi.window.top} count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.window.top-csbi.cursorPosition.y)*csbi.size.x) case 2: cursor = coord{x: csbi.window.left, y: csbi.window.top} count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) } procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'K': n := 0 if buf.Len() > 0 { n, err = strconv.Atoi(buf.String()) if err != nil { continue } } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) var cursor coord var count, written dword switch n { case 0: cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} count = dword(csbi.size.x - csbi.cursorPosition.x) case 1: cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} count = dword(csbi.size.x - csbi.cursorPosition.x) case 2: cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} count = dword(csbi.size.x) } procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'm': procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) attr := csbi.attributes cs := buf.String() if cs == "" { procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(w.oldattr)) continue } token := strings.Split(cs, ";") for i := 0; i < len(token); i++ { ns := token[i] if n, err = strconv.Atoi(ns); err == nil { switch { case n == 0 || n == 100: attr = w.oldattr case 1 <= n && n <= 5: attr |= foregroundIntensity case n == 7: attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) case n == 22 || n == 25: attr |= foregroundIntensity case n == 27: attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) case 30 <= n && n <= 37: attr &= backgroundMask if (n-30)&1 != 0 { attr |= foregroundRed } if (n-30)&2 != 0 { attr |= foregroundGreen } if (n-30)&4 != 0 { attr |= foregroundBlue } case n == 38: // set foreground color. if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { if n256, err := strconv.Atoi(token[i+2]); err == nil { if n256foreAttr == nil { n256setup() } attr &= backgroundMask attr |= n256foreAttr[n256] i += 2 } } else if len(token) == 5 && token[i+1] == "2" { var r, g, b int r, _ = strconv.Atoi(token[i+2]) g, _ = strconv.Atoi(token[i+3]) b, _ = strconv.Atoi(token[i+4]) i += 4 if r > 127 { attr |= foregroundRed } if g > 127 { attr |= foregroundGreen } if b > 127 { attr |= foregroundBlue } } else { attr = attr & (w.oldattr & backgroundMask) } case n == 39: // reset foreground color. attr &= backgroundMask attr |= w.oldattr & foregroundMask case 40 <= n && n <= 47: attr &= foregroundMask if (n-40)&1 != 0 { attr |= backgroundRed } if (n-40)&2 != 0 { attr |= backgroundGreen } if (n-40)&4 != 0 { attr |= backgroundBlue } case n == 48: // set background color. if i < len(token)-2 && token[i+1] == "5" { if n256, err := strconv.Atoi(token[i+2]); err == nil { if n256backAttr == nil { n256setup() } attr &= foregroundMask attr |= n256backAttr[n256] i += 2 } } else if len(token) == 5 && token[i+1] == "2" { var r, g, b int r, _ = strconv.Atoi(token[i+2]) g, _ = strconv.Atoi(token[i+3]) b, _ = strconv.Atoi(token[i+4]) i += 4 if r > 127 { attr |= backgroundRed } if g > 127 { attr |= backgroundGreen } if b > 127 { attr |= backgroundBlue } } else { attr = attr & (w.oldattr & foregroundMask) } case n == 49: // reset foreground color. attr &= foregroundMask attr |= w.oldattr & backgroundMask case 90 <= n && n <= 97: attr = (attr & backgroundMask) attr |= foregroundIntensity if (n-90)&1 != 0 { attr |= foregroundRed } if (n-90)&2 != 0 { attr |= foregroundGreen } if (n-90)&4 != 0 { attr |= foregroundBlue } case 100 <= n && n <= 107: attr = (attr & foregroundMask) attr |= backgroundIntensity if (n-100)&1 != 0 { attr |= backgroundRed } if (n-100)&2 != 0 { attr |= backgroundGreen } if (n-100)&4 != 0 { attr |= backgroundBlue } } procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(attr)) } } case 'h': var ci consoleCursorInfo cs := buf.String() if cs == "5>" { procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 0 procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) } else if cs == "?25" { procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 1 procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) } else if cs == "?1049" { if w.althandle == 0 { h, _, _ := procCreateConsoleScreenBuffer.Call(uintptr(genericRead|genericWrite), 0, 0, uintptr(consoleTextmodeBuffer), 0, 0) w.althandle = syscall.Handle(h) if w.althandle != 0 { handle = w.althandle } } } case 'l': var ci consoleCursorInfo cs := buf.String() if cs == "5>" { procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 1 procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) } else if cs == "?25" { procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 0 procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) } else if cs == "?1049" { if w.althandle != 0 { syscall.CloseHandle(w.althandle) w.althandle = 0 handle = w.handle } } case 's': procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) w.oldpos = csbi.cursorPosition case 'u': procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) } } return len(data), nil } type consoleColor struct { rgb int red bool green bool blue bool intensity bool } func (c consoleColor) foregroundAttr() (attr word) { if c.red { attr |= foregroundRed } if c.green { attr |= foregroundGreen } if c.blue { attr |= foregroundBlue } if c.intensity { attr |= foregroundIntensity } return } func (c consoleColor) backgroundAttr() (attr word) { if c.red { attr |= backgroundRed } if c.green { attr |= backgroundGreen } if c.blue { attr |= backgroundBlue } if c.intensity { attr |= backgroundIntensity } return } var color16 = []consoleColor{ {0x000000, false, false, false, false}, {0x000080, false, false, true, false}, {0x008000, false, true, false, false}, {0x008080, false, true, true, false}, {0x800000, true, false, false, false}, {0x800080, true, false, true, false}, {0x808000, true, true, false, false}, {0xc0c0c0, true, true, true, false}, {0x808080, false, false, false, true}, {0x0000ff, false, false, true, true}, {0x00ff00, false, true, false, true}, {0x00ffff, false, true, true, true}, {0xff0000, true, false, false, true}, {0xff00ff, true, false, true, true}, {0xffff00, true, true, false, true}, {0xffffff, true, true, true, true}, } type hsv struct { h, s, v float32 } func (a hsv) dist(b hsv) float32 { dh := a.h - b.h switch { case dh > 0.5: dh = 1 - dh case dh < -0.5: dh = -1 - dh } ds := a.s - b.s dv := a.v - b.v return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) } func toHSV(rgb int) hsv { r, g, b := float32((rgb&0xFF0000)>>16)/256.0, float32((rgb&0x00FF00)>>8)/256.0, float32(rgb&0x0000FF)/256.0 min, max := minmax3f(r, g, b) h := max - min if h > 0 { if max == r { h = (g - b) / h if h < 0 { h += 6 } } else if max == g { h = 2 + (b-r)/h } else { h = 4 + (r-g)/h } } h /= 6.0 s := max - min if max != 0 { s /= max } v := max return hsv{h: h, s: s, v: v} } type hsvTable []hsv func toHSVTable(rgbTable []consoleColor) hsvTable { t := make(hsvTable, len(rgbTable)) for i, c := range rgbTable { t[i] = toHSV(c.rgb) } return t } func (t hsvTable) find(rgb int) consoleColor { hsv := toHSV(rgb) n := 7 l := float32(5.0) for i, p := range t { d := hsv.dist(p) if d < l { l, n = d, i } } return color16[n] } func minmax3f(a, b, c float32) (min, max float32) { if a < b { if b < c { return a, c } else if a < c { return a, b } else { return c, b } } else { if a < c { return b, c } else if b < c { return b, a } else { return c, a } } } var n256foreAttr []word var n256backAttr []word func n256setup() { n256foreAttr = make([]word, 256) n256backAttr = make([]word, 256) t := toHSVTable(color16) for i, rgb := range color256 { c := t.find(rgb) n256foreAttr[i] = c.foregroundAttr() n256backAttr[i] = c.backgroundAttr() } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/colorable_test.go���������������������������������0000644�0610621�0607500�00000003453�13172163416�026312� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package colorable import ( "bytes" "os" "runtime" "testing" ) // checkEncoding checks that colorable is output encoding agnostic as long as // the encoding is a superset of ASCII. This implies that one byte not part of // an ANSI sequence must give exactly one byte in output func checkEncoding(t *testing.T, data []byte) { // Send non-UTF8 data to colorable b := bytes.NewBuffer(make([]byte, 0, 10)) if b.Len() != 0 { t.FailNow() } // TODO move colorable wrapping outside the test c := NewNonColorable(b) c.Write(data) if b.Len() != len(data) { t.Fatalf("%d bytes expected, got %d", len(data), b.Len()) } } func TestEncoding(t *testing.T) { checkEncoding(t, []byte{}) // Empty checkEncoding(t, []byte(`abc`)) // "abc" checkEncoding(t, []byte(`é`)) // "é" in UTF-8 checkEncoding(t, []byte{233}) // 'é' in Latin-1 } func TestNonColorable(t *testing.T) { var buf bytes.Buffer want := "hello" NewNonColorable(&buf).Write([]byte("\x1b[0m" + want + "\x1b[2J")) got := buf.String() if got != "hello" { t.Fatalf("want %q but %q", want, got) } buf.Reset() NewNonColorable(&buf).Write([]byte("\x1b[")) got = buf.String() if got != "" { t.Fatalf("want %q but %q", "", got) } } func TestNonColorableNil(t *testing.T) { paniced := false func() { defer func() { recover() paniced = true }() NewNonColorable(nil) NewColorable(nil) }() if !paniced { t.Fatalf("should panic") } } func TestColorable(t *testing.T) { if runtime.GOOS == "windows" { t.Skipf("skip this test on windows") } _, ok := NewColorableStdout().(*os.File) if !ok { t.Fatalf("should os.Stdout on UNIX") } _, ok = NewColorableStderr().(*os.File) if !ok { t.Fatalf("should os.Stdout on UNIX") } _, ok = NewColorable(os.Stdout).(*os.File) if !ok { t.Fatalf("should os.Stdout on UNIX") } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/colorable_others.go�������������������������������0000644�0610621�0607500�00000001177�13172163416�026640� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows // +build !appengine package colorable import ( "io" "os" _ "github.com/mattn/go-isatty" ) // NewColorable return new instance of Writer which handle escape sequence. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") } return file } // NewColorableStdout return new instance of Writer which handle escape sequence for stdout. func NewColorableStdout() io.Writer { return os.Stdout } // NewColorableStderr return new instance of Writer which handle escape sequence for stderr. func NewColorableStderr() io.Writer { return os.Stderr } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/colorable_appengine.go����������������������������0000644�0610621�0607500�00000001153�13172163416�027274� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build appengine package colorable import ( "io" "os" _ "github.com/mattn/go-isatty" ) // NewColorable return new instance of Writer which handle escape sequence. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") } return file } // NewColorableStdout return new instance of Writer which handle escape sequence for stdout. func NewColorableStdout() io.Writer { return os.Stdout } // NewColorableStderr return new instance of Writer which handle escape sequence for stderr. func NewColorableStderr() io.Writer { return os.Stderr } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/cmd/����������������������������������������������0000755�0610621�0607500�00000000000�13172163416�023520� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/cmd/colorable/������������������������������������0000755�0610621�0607500�00000000000�13172163416�025462� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/cmd/colorable/colorable.go������������������������0000644�0610621�0607500�00000000213�13172163416�027747� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "io" "os" "github.com/mattn/go-colorable" ) func main() { io.Copy(colorable.NewColorableStdout(), os.Stdin) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/_example/�����������������������������������������0000755�0610621�0607500�00000000000�13172163416�024547� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/_example/title/�����������������������������������0000755�0610621�0607500�00000000000�13172163416�025670� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/_example/title/main.go����������������������������0000644�0610621�0607500�00000000343�13172163416�027143� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" . "github.com/mattn/go-colorable" ) func main() { out := NewColorableStdout() fmt.Fprint(out, "\x1B]0;TITLE Changed\007(See title and hit any key)") var c [1]byte os.Stdin.Read(c[:]) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/_example/logrus/����������������������������������0000755�0610621�0607500�00000000000�13172163416�026062� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/_example/logrus/main.go���������������������������0000644�0610621�0607500�00000000511�13172163416�027332� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "github.com/mattn/go-colorable" "github.com/sirupsen/logrus" ) func main() { logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) logrus.SetOutput(colorable.NewColorableStdout()) logrus.Info("succeeded") logrus.Warn("not correct") logrus.Error("something error") logrus.Fatal("panic") } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/_example/escape-seq/������������������������������0000755�0610621�0607500�00000000000�13172163416�026575� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/_example/escape-seq/main.go�����������������������0000644�0610621�0607500�00000000434�13172163416�030051� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "bufio" "fmt" "github.com/mattn/go-colorable" ) func main() { stdOut := bufio.NewWriter(colorable.NewColorableStdout()) fmt.Fprint(stdOut, "\x1B[3GMove to 3rd Column\n") fmt.Fprint(stdOut, "\x1B[1;2HMove to 2nd Column on 1st Line\n") stdOut.Flush() } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/README.md�����������������������������������������0000644�0610621�0607500�00000002536�13172163416�024242� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# go-colorable [![Godoc Reference](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) [![Build Status](https://travis-ci.org/mattn/go-colorable.svg?branch=master)](https://travis-ci.org/mattn/go-colorable) [![Coverage Status](https://coveralls.io/repos/github/mattn/go-colorable/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-colorable?branch=master) [![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable) Colorable writer for windows. For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) This package is possible to handle escape sequence for ansi color on windows. ## Too Bad! ![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) ## So Good! ![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) ## Usage ```go logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) logrus.SetOutput(colorable.NewColorableStdout()) logrus.Info("succeeded") logrus.Warn("not correct") logrus.Error("something error") logrus.Fatal("panic") ``` You can compile above code on non-windows OSs. ## Installation ``` $ go get github.com/mattn/go-colorable ``` # License MIT # Author Yasuhiro Matsumoto (a.k.a mattn) ������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/LICENSE�������������������������������������������0000644�0610621�0607500�00000002075�13172163416�023766� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The MIT License (MIT) Copyright (c) 2016 Yasuhiro Matsumoto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/mattn/go-colorable/.travis.yml���������������������������������������0000644�0610621�0607500�00000000314�13172163416�025064� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go: - tip before_install: - go get github.com/mattn/goveralls - go get golang.org/x/tools/cmd/cover script: - $HOME/gopath/bin/goveralls -repotoken xnXqRGwgW3SXIguzxf90ZSK1GPYZPaGrw ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163415�022433� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163416�023363� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/������������������������������������������0000755�0610621�0607500�00000000000�13172163416�024332� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_windows.go�����������������������0000644�0610621�0607500�00000001132�13172163416�030243� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package term import ( "syscall" "unsafe" ) var kernel32 = syscall.NewLazyDLL("kernel32.dll") var ( procGetConsoleMode = kernel32.NewProc("GetConsoleMode") ) // IsTty returns true if the given file descriptor is a terminal. func IsTty(fd uintptr) bool { var st uint32 r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) return r != 0 && e == 0 } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_solaris.go�����������������������0000644�0610621�0607500�00000000331�13172163416�030225� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package term import "golang.org/x/sys/unix" // IsTty returns true if the given file descriptor is a terminal. func IsTty(fd uintptr) bool { _, err := unix.IoctlGetTermios(int(fd), unix.TCGETA) return err == nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_openbsd.go�����������������������0000644�0610621�0607500�00000000345�13172163416�030210� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package term import "syscall" const ioctlReadTermios = syscall.TIOCGETA // Termios functions describe a general terminal interface that is // provided to control asynchronous communications ports. type Termios syscall.Termios �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_notwindows.go��������������������0000644�0610621�0607500�00000001037�13172163416�030770� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux,!appengine darwin freebsd openbsd netbsd package term import ( "syscall" "unsafe" ) // IsTty returns true if the given file descriptor is a terminal. func IsTty(fd uintptr) bool { var termios Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_netbsd.go������������������������0000644�0610621�0607500�00000000345�13172163416�030035� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package term import "syscall" const ioctlReadTermios = syscall.TIOCGETA // Termios functions describe a general terminal interface that is // provided to control asynchronous communications ports. type Termios syscall.Termios �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_linux.go�������������������������0000644�0610621�0607500�00000000663�13172163416�027720� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !appengine package term import "syscall" const ioctlReadTermios = syscall.TCGETS // Termios functions describe a general terminal interface that is // provided to control asynchronous communications ports. type Termios syscall.Termios �����������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_freebsd.go�����������������������0000644�0610621�0607500�00000000713�13172163416�030167� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package term import ( "syscall" ) const ioctlReadTermios = syscall.TIOCGETA // Termios functions describe a general terminal interface that is // provided to control asynchronous communications ports. // Go 1.2 doesn't include Termios for FreeBSD. This should be added in 1.3 and this could be merged with terminal_darwin. type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } �����������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_darwin.go������������������������0000644�0610621�0607500�00000000664�13172163416�030046� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !appengine package term import "syscall" const ioctlReadTermios = syscall.TIOCGETA // Termios functions describe a general terminal interface that is // provided to control asynchronous communications ports. type Termios syscall.Termios ����������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/terminal_appengine.go���������������������0000644�0610621�0607500�00000000467�13172163416�030531� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Based on ssh/terminal: // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build appengine package term // IsTty always returns false on AppEngine. func IsTty(fd uintptr) bool { return false } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/doc.go������������������������������������0000644�0610621�0607500�00000000271�13172163416�025426� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package term provides utilities for working with terminals. // // Deprecated: This package is no longer used by log15. Please use // github.com/mattn/go-isatty instead. package term ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/term/LICENSE�����������������������������������0000644�0610621�0607500�00000002072�13172163416�025340� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The MIT License (MIT) Copyright (c) 2014 Simon Eskildsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/syslog.go��������������������������������������0000644�0610621�0607500�00000003010�13172163416�025224� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows,!plan9 package log15 import ( "log/syslog" "strings" ) // SyslogHandler opens a connection to the system syslog daemon by calling // syslog.New and writes all records to it. func SyslogHandler(priority syslog.Priority, tag string, fmtr Format) (Handler, error) { wr, err := syslog.New(priority, tag) return sharedSyslog(fmtr, wr, err) } // SyslogNetHandler opens a connection to a log daemon over the network and writes // all log records to it. func SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) (Handler, error) { wr, err := syslog.Dial(net, addr, priority, tag) return sharedSyslog(fmtr, wr, err) } func sharedSyslog(fmtr Format, sysWr *syslog.Writer, err error) (Handler, error) { if err != nil { return nil, err } h := FuncHandler(func(r *Record) error { var syslogFn = sysWr.Info switch r.Lvl { case LvlCrit: syslogFn = sysWr.Crit case LvlError: syslogFn = sysWr.Err case LvlWarn: syslogFn = sysWr.Warning case LvlInfo: syslogFn = sysWr.Info case LvlDebug: syslogFn = sysWr.Debug } s := strings.TrimSpace(string(fmtr.Format(r))) return syslogFn(s) }) return LazyHandler(&closingHandler{sysWr, h}), nil } func (m muster) SyslogHandler(priority syslog.Priority, tag string, fmtr Format) Handler { return must(SyslogHandler(priority, tag, fmtr)) } func (m muster) SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) Handler { return must(SyslogNetHandler(net, addr, priority, tag, fmtr)) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/root.go����������������������������������������0000644�0610621�0607500�00000003251�13172163416�024676� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "os" "github.com/mattn/go-colorable" isatty "github.com/mattn/go-isatty" ) // Predefined handlers var ( root *logger StdoutHandler = StreamHandler(os.Stdout, LogfmtFormat()) StderrHandler = StreamHandler(os.Stderr, LogfmtFormat()) ) func init() { if isatty.IsTerminal(os.Stdout.Fd()) { StdoutHandler = StreamHandler(colorable.NewColorableStdout(), TerminalFormat()) } if isatty.IsTerminal(os.Stderr.Fd()) { StderrHandler = StreamHandler(colorable.NewColorableStderr(), TerminalFormat()) } root = &logger{[]interface{}{}, new(swapHandler)} root.SetHandler(StdoutHandler) } // New returns a new logger with the given context. // New is a convenient alias for Root().New func New(ctx ...interface{}) Logger { return root.New(ctx...) } // Root returns the root logger func Root() Logger { return root } // The following functions bypass the exported logger methods (logger.Debug, // etc.) to keep the call depth the same for all paths to logger.write so // runtime.Caller(2) always refers to the call site in client code. // Debug is a convenient alias for Root().Debug func Debug(msg string, ctx ...interface{}) { root.write(msg, LvlDebug, ctx) } // Info is a convenient alias for Root().Info func Info(msg string, ctx ...interface{}) { root.write(msg, LvlInfo, ctx) } // Warn is a convenient alias for Root().Warn func Warn(msg string, ctx ...interface{}) { root.write(msg, LvlWarn, ctx) } // Error is a convenient alias for Root().Error func Error(msg string, ctx ...interface{}) { root.write(msg, LvlError, ctx) } // Crit is a convenient alias for Root().Crit func Crit(msg string, ctx ...interface{}) { root.write(msg, LvlCrit, ctx) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/logger.go��������������������������������������0000644�0610621�0607500�00000011355�13172163416�025176� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "fmt" "time" "github.com/go-stack/stack" ) const timeKey = "t" const lvlKey = "lvl" const msgKey = "msg" const errorKey = "LOG15_ERROR" // Lvl is a type for predefined log levels. type Lvl int // List of predefined log Levels const ( LvlCrit Lvl = iota LvlError LvlWarn LvlInfo LvlDebug ) // Returns the name of a Lvl func (l Lvl) String() string { switch l { case LvlDebug: return "dbug" case LvlInfo: return "info" case LvlWarn: return "warn" case LvlError: return "eror" case LvlCrit: return "crit" default: panic("bad level") } } // LvlFromString returns the appropriate Lvl from a string name. // Useful for parsing command line args and configuration files. func LvlFromString(lvlString string) (Lvl, error) { switch lvlString { case "debug", "dbug": return LvlDebug, nil case "info": return LvlInfo, nil case "warn": return LvlWarn, nil case "error", "eror": return LvlError, nil case "crit": return LvlCrit, nil default: return LvlDebug, fmt.Errorf("Unknown level: %v", lvlString) } } // A Record is what a Logger asks its handler to write type Record struct { Time time.Time Lvl Lvl Msg string Ctx []interface{} Call stack.Call KeyNames RecordKeyNames } // RecordKeyNames are the predefined names of the log props used by the Logger interface. type RecordKeyNames struct { Time string Msg string Lvl string } // A Logger writes key/value pairs to a Handler type Logger interface { // New returns a new Logger that has this logger's context plus the given context New(ctx ...interface{}) Logger // GetHandler gets the handler associated with the logger. GetHandler() Handler // SetHandler updates the logger to write records to the specified handler. SetHandler(h Handler) // Log a message at the given level with context key/value pairs Debug(msg string, ctx ...interface{}) Info(msg string, ctx ...interface{}) Warn(msg string, ctx ...interface{}) Error(msg string, ctx ...interface{}) Crit(msg string, ctx ...interface{}) } type logger struct { ctx []interface{} h *swapHandler } func (l *logger) write(msg string, lvl Lvl, ctx []interface{}) { l.h.Log(&Record{ Time: time.Now(), Lvl: lvl, Msg: msg, Ctx: newContext(l.ctx, ctx), Call: stack.Caller(2), KeyNames: RecordKeyNames{ Time: timeKey, Msg: msgKey, Lvl: lvlKey, }, }) } func (l *logger) New(ctx ...interface{}) Logger { child := &logger{newContext(l.ctx, ctx), new(swapHandler)} child.SetHandler(l.h) return child } func newContext(prefix []interface{}, suffix []interface{}) []interface{} { normalizedSuffix := normalize(suffix) newCtx := make([]interface{}, len(prefix)+len(normalizedSuffix)) n := copy(newCtx, prefix) copy(newCtx[n:], normalizedSuffix) return newCtx } func (l *logger) Debug(msg string, ctx ...interface{}) { l.write(msg, LvlDebug, ctx) } func (l *logger) Info(msg string, ctx ...interface{}) { l.write(msg, LvlInfo, ctx) } func (l *logger) Warn(msg string, ctx ...interface{}) { l.write(msg, LvlWarn, ctx) } func (l *logger) Error(msg string, ctx ...interface{}) { l.write(msg, LvlError, ctx) } func (l *logger) Crit(msg string, ctx ...interface{}) { l.write(msg, LvlCrit, ctx) } func (l *logger) GetHandler() Handler { return l.h.Get() } func (l *logger) SetHandler(h Handler) { l.h.Swap(h) } func normalize(ctx []interface{}) []interface{} { // if the caller passed a Ctx object, then expand it if len(ctx) == 1 { if ctxMap, ok := ctx[0].(Ctx); ok { ctx = ctxMap.toArray() } } // ctx needs to be even because it's a series of key/value pairs // no one wants to check for errors on logging functions, // so instead of erroring on bad input, we'll just make sure // that things are the right length and users can fix bugs // when they see the output looks wrong if len(ctx)%2 != 0 { ctx = append(ctx, nil, errorKey, "Normalized odd number of arguments by adding nil") } return ctx } // Lazy allows you to defer calculation of a logged value that is expensive // to compute until it is certain that it must be evaluated with the given filters. // // Lazy may also be used in conjunction with a Logger's New() function // to generate a child logger which always reports the current value of changing // state. // // You may wrap any function which takes no arguments to Lazy. It may return any // number of values of any type. type Lazy struct { Fn interface{} } // Ctx is a map of key/value pairs to pass as context to a log function // Use this only if you really need greater safety around the arguments you pass // to the logging functions. type Ctx map[string]interface{} func (c Ctx) toArray() []interface{} { arr := make([]interface{}, len(c)*2) i := 0 for k, v := range c { arr[i] = k arr[i+1] = v i += 2 } return arr } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/log15_test.go����������������������������������0000644�0610621�0607500�00000027536�13172163416�025715� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "net" "regexp" "runtime" "sync" "testing" "time" ) func testHandler() (Handler, *Record) { rec := new(Record) return FuncHandler(func(r *Record) error { *rec = *r return nil }), rec } func testLogger() (Logger, Handler, *Record) { l := New() h, r := testHandler() l.SetHandler(LazyHandler(h)) return l, h, r } func TestLazy(t *testing.T) { t.Parallel() x := 1 lazy := func() int { return x } l, _, r := testLogger() l.Info("", "x", Lazy{lazy}) if r.Ctx[1] != 1 { t.Fatalf("Lazy function not evaluated, got %v, expected %d", r.Ctx[1], 1) } x = 2 l.Info("", "x", Lazy{lazy}) if r.Ctx[1] != 2 { t.Fatalf("Lazy function not evaluated, got %v, expected %d", r.Ctx[1], 1) } } func TestInvalidLazy(t *testing.T) { t.Parallel() l, _, r := testLogger() validate := func() { if len(r.Ctx) < 4 { t.Fatalf("Invalid lazy, got %d args, expecting at least 4", len(r.Ctx)) } if r.Ctx[2] != errorKey { t.Fatalf("Invalid lazy, got key %s expecting %s", r.Ctx[2], errorKey) } } l.Info("", "x", Lazy{1}) validate() l.Info("", "x", Lazy{func(x int) int { return x }}) validate() l.Info("", "x", Lazy{func() {}}) validate() } func TestCtx(t *testing.T) { t.Parallel() l, _, r := testLogger() l.Info("", Ctx{"x": 1, "y": "foo", "tester": t}) if len(r.Ctx) != 6 { t.Fatalf("Expecting Ctx tansformed into %d ctx args, got %d: %v", 6, len(r.Ctx), r.Ctx) } } func testFormatter(f Format) (Logger, *bytes.Buffer) { l := New() var buf bytes.Buffer l.SetHandler(StreamHandler(&buf, f)) return l, &buf } func TestJson(t *testing.T) { t.Parallel() l, buf := testFormatter(JsonFormat()) l.Error("some message", "x", 1, "y", 3.2) var v map[string]interface{} decoder := json.NewDecoder(buf) if err := decoder.Decode(&v); err != nil { t.Fatalf("Error decoding JSON: %v", v) } validate := func(key string, expected interface{}) { if v[key] != expected { t.Fatalf("Got %v expected %v for %v", v[key], expected, key) } } validate("msg", "some message") validate("x", float64(1)) // all numbers are floats in JSON land validate("y", 3.2) validate("lvl", "eror") } type testtype struct { name string } func (tt testtype) String() string { return tt.name } func TestLogfmt(t *testing.T) { t.Parallel() var nilVal *testtype l, buf := testFormatter(LogfmtFormat()) l.Error("some message", "x", 1, "y", 3.2, "equals", "=", "quote", "\"", "nil", nilVal, "carriage_return", "bang"+string('\r')+"foo", "tab", "bar baz", "newline", "foo\nbar") // skip timestamp in comparison got := buf.Bytes()[27:buf.Len()] expected := []byte(`lvl=eror msg="some message" x=1 y=3.200 equals="=" quote="\"" nil=nil carriage_return="bang\rfoo" tab="bar\tbaz" newline="foo\nbar"` + "\n") if !bytes.Equal(got, expected) { t.Fatalf("Got %s, expected %s", got, expected) } } func TestMultiHandler(t *testing.T) { t.Parallel() h1, r1 := testHandler() h2, r2 := testHandler() l := New() l.SetHandler(MultiHandler(h1, h2)) l.Debug("clone") if r1.Msg != "clone" { t.Fatalf("wrong value for h1.Msg. Got %s expected %s", r1.Msg, "clone") } if r2.Msg != "clone" { t.Fatalf("wrong value for h2.Msg. Got %s expected %s", r2.Msg, "clone") } } type waitHandler struct { ch chan Record } func (h *waitHandler) Log(r *Record) error { h.ch <- *r return nil } func TestBufferedHandler(t *testing.T) { t.Parallel() ch := make(chan Record) l := New() l.SetHandler(BufferedHandler(0, &waitHandler{ch})) l.Debug("buffer") if r := <-ch; r.Msg != "buffer" { t.Fatalf("wrong value for r.Msg. Got %s expected %s", r.Msg, "") } } func TestLogContext(t *testing.T) { t.Parallel() l, _, r := testLogger() l = l.New("foo", "bar") l.Crit("baz") if len(r.Ctx) != 2 { t.Fatalf("Expected logger context in record context. Got length %d, expected %d", len(r.Ctx), 2) } if r.Ctx[0] != "foo" { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], "foo") } if r.Ctx[1] != "bar" { t.Fatalf("Wrong context value, got %s expected %s", r.Ctx[1], "bar") } } func TestMapCtx(t *testing.T) { t.Parallel() l, _, r := testLogger() l.Crit("test", Ctx{"foo": "bar"}) if len(r.Ctx) != 2 { t.Fatalf("Wrong context length, got %d, expected %d", len(r.Ctx), 2) } if r.Ctx[0] != "foo" { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], "foo") } if r.Ctx[1] != "bar" { t.Fatalf("Wrong context value, got %s expected %s", r.Ctx[1], "bar") } } func TestLvlFilterHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() l.SetHandler(LvlFilterHandler(LvlWarn, h)) l.Info("info'd") if r.Msg != "" { t.Fatalf("Expected zero record, but got record with msg: %v", r.Msg) } l.Warn("warned") if r.Msg != "warned" { t.Fatalf("Got record msg %s expected %s", r.Msg, "warned") } l.Warn("error'd") if r.Msg != "error'd" { t.Fatalf("Got record msg %s expected %s", r.Msg, "error'd") } } func TestNetHandler(t *testing.T) { t.Parallel() l, err := net.Listen("tcp", "localhost:0") if err != nil { t.Fatalf("Failed to listen: %v", l) } errs := make(chan error) go func() { c, err := l.Accept() if err != nil { errs <- fmt.Errorf("Failed to accept connection: %v", err) return } rd := bufio.NewReader(c) s, err := rd.ReadString('\n') if err != nil { errs <- fmt.Errorf("Failed to read string: %v", err) return } got := s[27:] expected := "lvl=info msg=test x=1\n" if got != expected { t.Errorf("Got log line %s, expected %s", got, expected) } errs <- nil }() lg := New() h, err := NetHandler("tcp", l.Addr().String(), LogfmtFormat()) if err != nil { t.Fatal(err) } lg.SetHandler(h) lg.Info("test", "x", 1) select { case <-time.After(time.Second): t.Fatalf("Test timed out!") case err := <-errs: if err != nil { t.Fatal(err) } } } func TestMatchFilterHandler(t *testing.T) { t.Parallel() l, h, r := testLogger() l.SetHandler(MatchFilterHandler("err", nil, h)) l.Crit("test", "foo", "bar") if r.Msg != "" { t.Fatalf("expected filter handler to discard msg") } l.Crit("test2", "err", "bad fd") if r.Msg != "" { t.Fatalf("expected filter handler to discard msg") } l.Crit("test3", "err", nil) if r.Msg != "test3" { t.Fatalf("expected filter handler to allow msg") } } func TestMatchFilterBuiltin(t *testing.T) { t.Parallel() l, h, r := testLogger() l.SetHandler(MatchFilterHandler("lvl", LvlError, h)) l.Info("does not pass") if r.Msg != "" { t.Fatalf("got info level record that should not have matched") } l.Error("error!") if r.Msg != "error!" { t.Fatalf("did not get error level record that should have matched") } r.Msg = "" l.SetHandler(MatchFilterHandler("msg", "matching message", h)) l.Info("doesn't match") if r.Msg != "" { t.Fatalf("got record with wrong message matched") } l.Debug("matching message") if r.Msg != "matching message" { t.Fatalf("did not get record which matches") } } type failingWriter struct { fail bool } func (w *failingWriter) Write(buf []byte) (int, error) { if w.fail { return 0, errors.New("fail") } return len(buf), nil } func TestFailoverHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() w := &failingWriter{false} l.SetHandler(FailoverHandler( StreamHandler(w, JsonFormat()), h)) l.Debug("test ok") if r.Msg != "" { t.Fatalf("expected no failover") } w.fail = true l.Debug("test failover", "x", 1) if r.Msg != "test failover" { t.Fatalf("expected failover") } if len(r.Ctx) != 4 { t.Fatalf("expected additional failover ctx") } got := r.Ctx[2] expected := "failover_err_0" if got != expected { t.Fatalf("expected failover ctx. got: %s, expected %s", got, expected) } } // https://github.com/inconshreveable/log15/issues/16 func TestIndependentSetHandler(t *testing.T) { t.Parallel() parent, _, r := testLogger() child := parent.New() child.SetHandler(DiscardHandler()) parent.Info("test") if r.Msg != "test" { t.Fatalf("parent handler affected by child") } } // https://github.com/inconshreveable/log15/issues/16 func TestInheritHandler(t *testing.T) { t.Parallel() parent, _, r := testLogger() child := parent.New() parent.SetHandler(DiscardHandler()) child.Info("test") if r.Msg == "test" { t.Fatalf("child handler affected not affected by parent") } } func TestCallerFileHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() l.SetHandler(CallerFileHandler(h)) l.Info("baz") _, _, line, _ := runtime.Caller(0) if len(r.Ctx) != 2 { t.Fatalf("Expected caller in record context. Got length %d, expected %d", len(r.Ctx), 2) } const key = "caller" if r.Ctx[0] != key { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], key) } s, ok := r.Ctx[1].(string) if !ok { t.Fatalf("Wrong context value type, got %T expected string", r.Ctx[1]) } exp := fmt.Sprint("log15_test.go:", line-1) if s != exp { t.Fatalf("Wrong context value, got %s expected string matching %s", s, exp) } } func TestCallerFuncHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() l.SetHandler(CallerFuncHandler(h)) l.Info("baz") if len(r.Ctx) != 2 { t.Fatalf("Expected caller in record context. Got length %d, expected %d", len(r.Ctx), 2) } const key = "fn" if r.Ctx[0] != key { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], key) } const regex = ".*\\.TestCallerFuncHandler" s, ok := r.Ctx[1].(string) if !ok { t.Fatalf("Wrong context value type, got %T expected string", r.Ctx[1]) } match, err := regexp.MatchString(regex, s) if err != nil { t.Fatalf("Error matching %s to regex %s: %v", s, regex, err) } if !match { t.Fatalf("Wrong context value, got %s expected string matching %s", s, regex) } } // https://github.com/inconshreveable/log15/issues/27 func TestCallerStackHandler(t *testing.T) { t.Parallel() l := New() h, r := testHandler() l.SetHandler(CallerStackHandler("%#v", h)) lines := []int{} func() { l.Info("baz") _, _, line, _ := runtime.Caller(0) lines = append(lines, line-1) }() _, file, line, _ := runtime.Caller(0) lines = append(lines, line-1) if len(r.Ctx) != 2 { t.Fatalf("Expected stack in record context. Got length %d, expected %d", len(r.Ctx), 2) } const key = "stack" if r.Ctx[0] != key { t.Fatalf("Wrong context key, got %s expected %s", r.Ctx[0], key) } s, ok := r.Ctx[1].(string) if !ok { t.Fatalf("Wrong context value type, got %T expected string", r.Ctx[1]) } exp := "[" for i, line := range lines { if i > 0 { exp += " " } exp += fmt.Sprint(file, ":", line) } exp += "]" if s != exp { t.Fatalf("Wrong context value, got %s expected string matching %s", s, exp) } } // tests that when logging concurrently to the same logger // from multiple goroutines that the calls are handled independently // this test tries to trigger a previous bug where concurrent calls could // corrupt each other's context values // // this test runs N concurrent goroutines each logging a fixed number of // records and a handler that buckets them based on the index passed in the context. // if the logger is not concurrent-safe then the values in the buckets will not all be the same // // https://github.com/inconshreveable/log15/pull/30 func TestConcurrent(t *testing.T) { root := New() // this was the first value that triggered // go to allocate extra capacity in the logger's context slice which // was necessary to trigger the bug const ctxLen = 34 l := root.New(make([]interface{}, ctxLen)...) const goroutines = 8 var res [goroutines]int l.SetHandler(SyncHandler(FuncHandler(func(r *Record) error { res[r.Ctx[ctxLen+1].(int)]++ return nil }))) var wg sync.WaitGroup wg.Add(goroutines) for i := 0; i < goroutines; i++ { go func(idx int) { defer wg.Done() for j := 0; j < 10000; j++ { l.Info("test message", "goroutine_idx", idx) } }(i) } wg.Wait() for _, val := range res[:] { if val != 10000 { t.Fatalf("Wrong number of messages for context: %+v", res) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/handler_go14.go��������������������������������0000644�0610621�0607500�00000000727�13172163416�026167� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.4 package log15 import "sync/atomic" // swapHandler wraps another handler that may be swapped out // dynamically at runtime in a thread-safe fashion. type swapHandler struct { handler atomic.Value } func (h *swapHandler) Log(r *Record) error { return (*h.handler.Load().(*Handler)).Log(r) } func (h *swapHandler) Swap(newHandler Handler) { h.handler.Store(&newHandler) } func (h *swapHandler) Get() Handler { return *h.handler.Load().(*Handler) } �����������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/handler_go13.go��������������������������������0000644�0610621�0607500�00000001001�13172163416�026150� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.4 package log15 import ( "sync/atomic" "unsafe" ) // swapHandler wraps another handler that may be swapped out // dynamically at runtime in a thread-safe fashion. type swapHandler struct { handler unsafe.Pointer } func (h *swapHandler) Log(r *Record) error { return h.Get().Log(r) } func (h *swapHandler) Get() Handler { return *(*Handler)(atomic.LoadPointer(&h.handler)) } func (h *swapHandler) Swap(newHandler Handler) { atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler)) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/handler.go�������������������������������������0000644�0610621�0607500�00000024001�13172163416�025324� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "fmt" "io" "net" "os" "reflect" "sync" "github.com/go-stack/stack" ) // Handler interface defines where and how log records are written. // A logger prints its log records by writing to a Handler. // Handlers are composable, providing you great flexibility in combining // them to achieve the logging structure that suits your applications. type Handler interface { Log(r *Record) error } // FuncHandler returns a Handler that logs records with the given // function. func FuncHandler(fn func(r *Record) error) Handler { return funcHandler(fn) } type funcHandler func(r *Record) error func (h funcHandler) Log(r *Record) error { return h(r) } // StreamHandler writes log records to an io.Writer // with the given format. StreamHandler can be used // to easily begin writing log records to other // outputs. // // StreamHandler wraps itself with LazyHandler and SyncHandler // to evaluate Lazy objects and perform safe concurrent writes. func StreamHandler(wr io.Writer, fmtr Format) Handler { h := FuncHandler(func(r *Record) error { _, err := wr.Write(fmtr.Format(r)) return err }) return LazyHandler(SyncHandler(h)) } // SyncHandler can be wrapped around a handler to guarantee that // only a single Log operation can proceed at a time. It's necessary // for thread-safe concurrent writes. func SyncHandler(h Handler) Handler { var mu sync.Mutex return FuncHandler(func(r *Record) error { defer mu.Unlock() mu.Lock() return h.Log(r) }) } // FileHandler returns a handler which writes log records to the give file // using the given format. If the path // already exists, FileHandler will append to the given file. If it does not, // FileHandler will create the file with mode 0644. func FileHandler(path string, fmtr Format) (Handler, error) { f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { return nil, err } return closingHandler{f, StreamHandler(f, fmtr)}, nil } // NetHandler opens a socket to the given address and writes records // over the connection. func NetHandler(network, addr string, fmtr Format) (Handler, error) { conn, err := net.Dial(network, addr) if err != nil { return nil, err } return closingHandler{conn, StreamHandler(conn, fmtr)}, nil } // XXX: closingHandler is essentially unused at the moment // it's meant for a future time when the Handler interface supports // a possible Close() operation type closingHandler struct { io.WriteCloser Handler } func (h *closingHandler) Close() error { return h.WriteCloser.Close() } // CallerFileHandler returns a Handler that adds the line number and file of // the calling function to the context with key "caller". func CallerFileHandler(h Handler) Handler { return FuncHandler(func(r *Record) error { r.Ctx = append(r.Ctx, "caller", fmt.Sprint(r.Call)) return h.Log(r) }) } // CallerFuncHandler returns a Handler that adds the calling function name to // the context with key "fn". func CallerFuncHandler(h Handler) Handler { return FuncHandler(func(r *Record) error { r.Ctx = append(r.Ctx, "fn", fmt.Sprintf("%+n", r.Call)) return h.Log(r) }) } // CallerStackHandler returns a Handler that adds a stack trace to the context // with key "stack". The stack trace is formated as a space separated list of // call sites inside matching []'s. The most recent call site is listed first. // Each call site is formatted according to format. See the documentation of // package github.com/go-stack/stack for the list of supported formats. func CallerStackHandler(format string, h Handler) Handler { return FuncHandler(func(r *Record) error { s := stack.Trace().TrimBelow(r.Call).TrimRuntime() if len(s) > 0 { r.Ctx = append(r.Ctx, "stack", fmt.Sprintf(format, s)) } return h.Log(r) }) } // FilterHandler returns a Handler that only writes records to the // wrapped Handler if the given function evaluates true. For example, // to only log records where the 'err' key is not nil: // // logger.SetHandler(FilterHandler(func(r *Record) bool { // for i := 0; i < len(r.Ctx); i += 2 { // if r.Ctx[i] == "err" { // return r.Ctx[i+1] != nil // } // } // return false // }, h)) // func FilterHandler(fn func(r *Record) bool, h Handler) Handler { return FuncHandler(func(r *Record) error { if fn(r) { return h.Log(r) } return nil }) } // MatchFilterHandler returns a Handler that only writes records // to the wrapped Handler if the given key in the logged // context matches the value. For example, to only log records // from your ui package: // // log.MatchFilterHandler("pkg", "app/ui", log.StdoutHandler) // func MatchFilterHandler(key string, value interface{}, h Handler) Handler { return FilterHandler(func(r *Record) (pass bool) { switch key { case r.KeyNames.Lvl: return r.Lvl == value case r.KeyNames.Time: return r.Time == value case r.KeyNames.Msg: return r.Msg == value } for i := 0; i < len(r.Ctx); i += 2 { if r.Ctx[i] == key { return r.Ctx[i+1] == value } } return false }, h) } // LvlFilterHandler returns a Handler that only writes // records which are less than the given verbosity // level to the wrapped Handler. For example, to only // log Error/Crit records: // // log.LvlFilterHandler(log.LvlError, log.StdoutHandler) // func LvlFilterHandler(maxLvl Lvl, h Handler) Handler { return FilterHandler(func(r *Record) (pass bool) { return r.Lvl <= maxLvl }, h) } // MultiHandler dispatches any write to each of its handlers. // This is useful for writing different types of log information // to different locations. For example, to log to a file and // standard error: // // log.MultiHandler( // log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()), // log.StderrHandler) // func MultiHandler(hs ...Handler) Handler { return FuncHandler(func(r *Record) error { for _, h := range hs { // what to do about failures? h.Log(r) } return nil }) } // FailoverHandler writes all log records to the first handler // specified, but will failover and write to the second handler if // the first handler has failed, and so on for all handlers specified. // For example you might want to log to a network socket, but failover // to writing to a file if the network fails, and then to // standard out if the file write fails: // // log.FailoverHandler( // log.Must.NetHandler("tcp", ":9090", log.JsonFormat()), // log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()), // log.StdoutHandler) // // All writes that do not go to the first handler will add context with keys of // the form "failover_err_{idx}" which explain the error encountered while // trying to write to the handlers before them in the list. func FailoverHandler(hs ...Handler) Handler { return FuncHandler(func(r *Record) error { var err error for i, h := range hs { err = h.Log(r) if err == nil { return nil } r.Ctx = append(r.Ctx, fmt.Sprintf("failover_err_%d", i), err) } return err }) } // ChannelHandler writes all records to the given channel. // It blocks if the channel is full. Useful for async processing // of log messages, it's used by BufferedHandler. func ChannelHandler(recs chan<- *Record) Handler { return FuncHandler(func(r *Record) error { recs <- r return nil }) } // BufferedHandler writes all records to a buffered // channel of the given size which flushes into the wrapped // handler whenever it is available for writing. Since these // writes happen asynchronously, all writes to a BufferedHandler // never return an error and any errors from the wrapped handler are ignored. func BufferedHandler(bufSize int, h Handler) Handler { recs := make(chan *Record, bufSize) go func() { for m := range recs { _ = h.Log(m) } }() return ChannelHandler(recs) } // LazyHandler writes all values to the wrapped handler after evaluating // any lazy functions in the record's context. It is already wrapped // around StreamHandler and SyslogHandler in this library, you'll only need // it if you write your own Handler. func LazyHandler(h Handler) Handler { return FuncHandler(func(r *Record) error { // go through the values (odd indices) and reassign // the values of any lazy fn to the result of its execution hadErr := false for i := 1; i < len(r.Ctx); i += 2 { lz, ok := r.Ctx[i].(Lazy) if ok { v, err := evaluateLazy(lz) if err != nil { hadErr = true r.Ctx[i] = err } else { if cs, ok := v.(stack.CallStack); ok { v = cs.TrimBelow(r.Call).TrimRuntime() } r.Ctx[i] = v } } } if hadErr { r.Ctx = append(r.Ctx, errorKey, "bad lazy") } return h.Log(r) }) } func evaluateLazy(lz Lazy) (interface{}, error) { t := reflect.TypeOf(lz.Fn) if t.Kind() != reflect.Func { return nil, fmt.Errorf("INVALID_LAZY, not func: %+v", lz.Fn) } if t.NumIn() > 0 { return nil, fmt.Errorf("INVALID_LAZY, func takes args: %+v", lz.Fn) } if t.NumOut() == 0 { return nil, fmt.Errorf("INVALID_LAZY, no func return val: %+v", lz.Fn) } value := reflect.ValueOf(lz.Fn) results := value.Call([]reflect.Value{}) if len(results) == 1 { return results[0].Interface(), nil } values := make([]interface{}, len(results)) for i, v := range results { values[i] = v.Interface() } return values, nil } // DiscardHandler reports success for all writes but does nothing. // It is useful for dynamically disabling logging at runtime via // a Logger's SetHandler method. func DiscardHandler() Handler { return FuncHandler(func(r *Record) error { return nil }) } // Must object provides the following Handler creation functions // which instead of returning an error parameter only return a Handler // and panic on failure: FileHandler, NetHandler, SyslogHandler, SyslogNetHandler var Must muster func must(h Handler, err error) Handler { if err != nil { panic(err) } return h } type muster struct{} func (m muster) FileHandler(path string, fmtr Format) Handler { return must(FileHandler(path, fmtr)) } func (m muster) NetHandler(network, addr string, fmtr Format) Handler { return must(NetHandler(network, addr, fmtr)) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/format.go��������������������������������������0000644�0610621�0607500�00000014417�13172163416�025211� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package log15 import ( "bytes" "encoding/json" "fmt" "reflect" "strconv" "strings" "sync" "time" ) const ( timeFormat = "2006-01-02T15:04:05-0700" termTimeFormat = "01-02|15:04:05" floatFormat = 'f' termMsgJust = 40 ) // Format is the interface implemented by StreamHandler formatters. type Format interface { Format(r *Record) []byte } // FormatFunc returns a new Format object which uses // the given function to perform record formatting. func FormatFunc(f func(*Record) []byte) Format { return formatFunc(f) } type formatFunc func(*Record) []byte func (f formatFunc) Format(r *Record) []byte { return f(r) } // TerminalFormat formats log records optimized for human readability on // a terminal with color-coded level output and terser human friendly timestamp. // This format should only be used for interactive programs or while developing. // // [TIME] [LEVEL] MESAGE key=value key=value ... // // Example: // // [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002 // func TerminalFormat() Format { return FormatFunc(func(r *Record) []byte { var color = 0 switch r.Lvl { case LvlCrit: color = 35 case LvlError: color = 31 case LvlWarn: color = 33 case LvlInfo: color = 32 case LvlDebug: color = 36 } b := &bytes.Buffer{} lvl := strings.ToUpper(r.Lvl.String()) if color > 0 { fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %s ", color, lvl, r.Time.Format(termTimeFormat), r.Msg) } else { fmt.Fprintf(b, "[%s] [%s] %s ", lvl, r.Time.Format(termTimeFormat), r.Msg) } // try to justify the log output for short messages if len(r.Ctx) > 0 && len(r.Msg) < termMsgJust { b.Write(bytes.Repeat([]byte{' '}, termMsgJust-len(r.Msg))) } // print the keys logfmt style logfmt(b, r.Ctx, color) return b.Bytes() }) } // LogfmtFormat prints records in logfmt format, an easy machine-parseable but human-readable // format for key/value pairs. // // For more details see: http://godoc.org/github.com/kr/logfmt // func LogfmtFormat() Format { return FormatFunc(func(r *Record) []byte { common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg} buf := &bytes.Buffer{} logfmt(buf, append(common, r.Ctx...), 0) return buf.Bytes() }) } func logfmt(buf *bytes.Buffer, ctx []interface{}, color int) { for i := 0; i < len(ctx); i += 2 { if i != 0 { buf.WriteByte(' ') } k, ok := ctx[i].(string) v := formatLogfmtValue(ctx[i+1]) if !ok { k, v = errorKey, formatLogfmtValue(k) } // XXX: we should probably check that all of your key bytes aren't invalid if color > 0 { fmt.Fprintf(buf, "\x1b[%dm%s\x1b[0m=%s", color, k, v) } else { buf.WriteString(k) buf.WriteByte('=') buf.WriteString(v) } } buf.WriteByte('\n') } // JsonFormat formats log records as JSON objects separated by newlines. // It is the equivalent of JsonFormatEx(false, true). func JsonFormat() Format { return JsonFormatEx(false, true) } // JsonFormatEx formats log records as JSON objects. If pretty is true, // records will be pretty-printed. If lineSeparated is true, records // will be logged with a new line between each record. func JsonFormatEx(pretty, lineSeparated bool) Format { jsonMarshal := json.Marshal if pretty { jsonMarshal = func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") } } return FormatFunc(func(r *Record) []byte { props := make(map[string]interface{}) props[r.KeyNames.Time] = r.Time props[r.KeyNames.Lvl] = r.Lvl.String() props[r.KeyNames.Msg] = r.Msg for i := 0; i < len(r.Ctx); i += 2 { k, ok := r.Ctx[i].(string) if !ok { props[errorKey] = fmt.Sprintf("%+v is not a string key", r.Ctx[i]) } props[k] = formatJSONValue(r.Ctx[i+1]) } b, err := jsonMarshal(props) if err != nil { b, _ = jsonMarshal(map[string]string{ errorKey: err.Error(), }) return b } if lineSeparated { b = append(b, '\n') } return b }) } func formatShared(value interface{}) (result interface{}) { defer func() { if err := recover(); err != nil { if v := reflect.ValueOf(value); v.Kind() == reflect.Ptr && v.IsNil() { result = "nil" } else { panic(err) } } }() switch v := value.(type) { case time.Time: return v.Format(timeFormat) case error: return v.Error() case fmt.Stringer: return v.String() default: return v } } func formatJSONValue(value interface{}) interface{} { value = formatShared(value) switch value.(type) { case int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64, string: return value default: return fmt.Sprintf("%+v", value) } } // formatValue formats a value for serialization func formatLogfmtValue(value interface{}) string { if value == nil { return "nil" } if t, ok := value.(time.Time); ok { // Performance optimization: No need for escaping since the provided // timeFormat doesn't have any escape characters, and escaping is // expensive. return t.Format(timeFormat) } value = formatShared(value) switch v := value.(type) { case bool: return strconv.FormatBool(v) case float32: return strconv.FormatFloat(float64(v), floatFormat, 3, 64) case float64: return strconv.FormatFloat(v, floatFormat, 3, 64) case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: return fmt.Sprintf("%d", value) case string: return escapeString(v) default: return escapeString(fmt.Sprintf("%+v", value)) } } var stringBufPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, } func escapeString(s string) string { needsQuotes := false needsEscape := false for _, r := range s { if r <= ' ' || r == '=' || r == '"' { needsQuotes = true } if r == '\\' || r == '"' || r == '\n' || r == '\r' || r == '\t' { needsEscape = true } } if needsEscape == false && needsQuotes == false { return s } e := stringBufPool.Get().(*bytes.Buffer) e.WriteByte('"') for _, r := range s { switch r { case '\\', '"': e.WriteByte('\\') e.WriteByte(byte(r)) case '\n': e.WriteString("\\n") case '\r': e.WriteString("\\r") case '\t': e.WriteString("\\t") default: e.WriteRune(r) } } e.WriteByte('"') var ret string if needsQuotes { ret = e.String() } else { ret = string(e.Bytes()[1 : e.Len()-1]) } e.Reset() stringBufPool.Put(e) return ret } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/ext/�������������������������������������������0000755�0610621�0607500�00000000000�13172163416�024163� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/ext/id.go��������������������������������������0000644�0610621�0607500�00000001765�13172163416�025117� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ext import ( "fmt" "math/rand" "sync" "time" ) var r = rand.New(&lockedSource{src: rand.NewSource(time.Now().Unix())}) // RandId creates a random identifier of the requested length. // Useful for assigning mostly-unique identifiers for logging // and identification that are unlikely to collide because of // short lifespan or low set cardinality func RandId(idlen int) string { b := make([]byte, idlen) var randVal uint32 for i := 0; i < idlen; i++ { byteIdx := i % 4 if byteIdx == 0 { randVal = r.Uint32() } b[i] = byte((randVal >> (8 * uint(byteIdx))) & 0xFF) } return fmt.Sprintf("%x", b) } // lockedSource is a wrapper to allow a rand.Source to be used // concurrently (same type as the one used internally in math/rand). type lockedSource struct { lk sync.Mutex src rand.Source } func (r *lockedSource) Int63() (n int64) { r.lk.Lock() n = r.src.Int63() r.lk.Unlock() return } func (r *lockedSource) Seed(seed int64) { r.lk.Lock() r.src.Seed(seed) r.lk.Unlock() } �����������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/ext/handler.go���������������������������������0000644�0610621�0607500�00000007203�13172163416�026131� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ext import ( "os" "sync" "sync/atomic" "unsafe" log "github.com/inconshreveable/log15" ) // EscalateErrHandler wraps another handler and passes all records through // unchanged except if the logged context contains a non-nil error // value in its context. In that case, the record's level is raised // to LvlError unless it was already more serious (LvlCrit). // // This allows you to log the result of all functions for debugging // and still capture error conditions when in production with a single // log line. As an example, the following the log record will be written // out only if there was an error writing a value to redis: // // logger := logext.EscalateErrHandler( // log.LvlFilterHandler(log.LvlInfo, log.StdoutHandler)) // // reply, err := redisConn.Do("SET", "foo", "bar") // logger.Debug("Wrote value to redis", "reply", reply, "err", err) // if err != nil { // return err // } // func EscalateErrHandler(h log.Handler) log.Handler { return log.FuncHandler(func(r *log.Record) error { if r.Lvl > log.LvlError { for i := 1; i < len(r.Ctx); i++ { if v, ok := r.Ctx[i].(error); ok && v != nil { r.Lvl = log.LvlError break } } } return h.Log(r) }) } // SpeculativeHandler is a handler for speculative logging. It // keeps a ring buffer of the given size full of the last events // logged into it. When Flush is called, all buffered log records // are written to the wrapped handler. This is extremely for // continuosly capturing debug level output, but only flushing those // log records if an exceptional condition is encountered. func SpeculativeHandler(size int, h log.Handler) *Speculative { return &Speculative{ handler: h, recs: make([]*log.Record, size), } } // Speculative is the Log15.Handler. Read `SpeculativeHandler` for more information. type Speculative struct { mu sync.Mutex idx int recs []*log.Record handler log.Handler full bool } // Log implements log15.Handler interface func (h *Speculative) Log(r *log.Record) error { h.mu.Lock() defer h.mu.Unlock() h.recs[h.idx] = r h.idx = (h.idx + 1) % len(h.recs) h.full = h.full || h.idx == 0 return nil } // Flush logs all records on the handler. func (h *Speculative) Flush() { recs := make([]*log.Record, 0) func() { h.mu.Lock() defer h.mu.Unlock() if h.full { recs = append(recs, h.recs[h.idx:]...) } recs = append(recs, h.recs[:h.idx]...) // reset state h.full = false h.idx = 0 }() // don't hold the lock while we flush to the wrapped handler for _, r := range recs { h.handler.Log(r) } } // HotSwapHandler wraps another handler that may swapped out // dynamically at runtime in a thread-safe fashion. // HotSwapHandler is the same functionality // used to implement the SetHandler method for the default // implementation of Logger. func HotSwapHandler(h log.Handler) *HotSwap { hs := new(HotSwap) hs.Swap(h) return hs } // HotSwap is the Log15.Handler. Read `HotSwapHandler` for more information. type HotSwap struct { handler unsafe.Pointer } // Log implements log15.Handler interface. func (h *HotSwap) Log(r *log.Record) error { return (*(*log.Handler)(atomic.LoadPointer(&h.handler))).Log(r) } // Swap atomically the logger handler. func (h *HotSwap) Swap(newHandler log.Handler) { atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler)) } // FatalHandler makes critical errors exit the program // immediately, much like the log.Fatal* methods from the // standard log package func FatalHandler(h log.Handler) log.Handler { return log.FuncHandler(func(r *log.Record) error { err := h.Log(r) if r.Lvl == log.LvlCrit { os.Exit(1) } return err }) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/ext/ext_test.go��������������������������������0000644�0610621�0607500�00000004333�13172163416�026354� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ext import ( "errors" log "github.com/inconshreveable/log15" "math" "testing" ) func testHandler() (log.Handler, *log.Record) { rec := new(log.Record) return log.FuncHandler(func(r *log.Record) error { *rec = *r return nil }), rec } func TestHotSwapHandler(t *testing.T) { t.Parallel() h1, r1 := testHandler() l := log.New() h := HotSwapHandler(h1) l.SetHandler(h) l.Info("to h1") if r1.Msg != "to h1" { t.Fatalf("didn't get expected message to h1") } h2, r2 := testHandler() h.Swap(h2) l.Info("to h2") if r2.Msg != "to h2" { t.Fatalf("didn't get expected message to h2") } } func TestSpeculativeHandler(t *testing.T) { t.Parallel() // test with an even multiple of the buffer size, less than full buffer size // and not a multiple of the buffer size for _, count := range []int{10000, 50, 432} { recs := make(chan *log.Record) done := make(chan int) spec := SpeculativeHandler(100, log.ChannelHandler(recs)) go func() { defer close(done) expectedCount := int(math.Min(float64(count), float64(100))) expectedIdx := count - expectedCount for r := range recs { if r.Ctx[1] != expectedIdx { t.Errorf("Bad ctx 'i', got %d expected %d", r.Ctx[1], expectedIdx) return } expectedIdx++ expectedCount-- if expectedCount == 0 { // got everything we expected break } } select { case <-recs: t.Errorf("got an extra record we shouldn't have!") default: } }() lg := log.New() lg.SetHandler(spec) for i := 0; i < count; i++ { lg.Debug("test speculative", "i", i) } go spec.Flush() // wait for the go routine to finish <-done } } func TestErrorHandler(t *testing.T) { t.Parallel() h, r := testHandler() lg := log.New() lg.SetHandler(EscalateErrHandler( log.LvlFilterHandler(log.LvlError, h))) lg.Debug("some function result", "err", nil) if r.Msg != "" { t.Fatalf("Expected debug level message to be filtered") } lg.Debug("some function result", "err", errors.New("failed operation")) if r.Msg != "some function result" { t.Fatalf("Expected debug level message to be escalated and pass lvlfilter") } if r.Lvl != log.LvlError { t.Fatalf("Expected debug level message to be escalated to LvlError") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/doc.go�����������������������������������������0000644�0610621�0607500�00000027733�13172163416�024473� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Package log15 provides an opinionated, simple toolkit for best-practice logging that is both human and machine readable. It is modeled after the standard library's io and net/http packages. This package enforces you to only log key/value pairs. Keys must be strings. Values may be any type that you like. The default output format is logfmt, but you may also choose to use JSON instead if that suits you. Here's how you log: log.Info("page accessed", "path", r.URL.Path, "user_id", user.id) This will output a line that looks like: lvl=info t=2014-05-02T16:07:23-0700 msg="page accessed" path=/org/71/profile user_id=9 Getting Started To get started, you'll want to import the library: import log "github.com/inconshreveable/log15" Now you're ready to start logging: func main() { log.Info("Program starting", "args", os.Args) } Convention Because recording a human-meaningful message is common and good practice, the first argument to every logging method is the value to the *implicit* key 'msg'. Additionally, the level you choose for a message will be automatically added with the key 'lvl', and so will the current timestamp with key 't'. You may supply any additional context as a set of key/value pairs to the logging function. log15 allows you to favor terseness, ordering, and speed over safety. This is a reasonable tradeoff for logging functions. You don't need to explicitly state keys/values, log15 understands that they alternate in the variadic argument list: log.Warn("size out of bounds", "low", lowBound, "high", highBound, "val", val) If you really do favor your type-safety, you may choose to pass a log.Ctx instead: log.Warn("size out of bounds", log.Ctx{"low": lowBound, "high": highBound, "val": val}) Context loggers Frequently, you want to add context to a logger so that you can track actions associated with it. An http request is a good example. You can easily create new loggers that have context that is automatically included with each log line: requestlogger := log.New("path", r.URL.Path) // later requestlogger.Debug("db txn commit", "duration", txnTimer.Finish()) This will output a log line that includes the path context that is attached to the logger: lvl=dbug t=2014-05-02T16:07:23-0700 path=/repo/12/add_hook msg="db txn commit" duration=0.12 Handlers The Handler interface defines where log lines are printed to and how they are formated. Handler is a single interface that is inspired by net/http's handler interface: type Handler interface { Log(r *Record) error } Handlers can filter records, format them, or dispatch to multiple other Handlers. This package implements a number of Handlers for common logging patterns that are easily composed to create flexible, custom logging structures. Here's an example handler that prints logfmt output to Stdout: handler := log.StreamHandler(os.Stdout, log.LogfmtFormat()) Here's an example handler that defers to two other handlers. One handler only prints records from the rpc package in logfmt to standard out. The other prints records at Error level or above in JSON formatted output to the file /var/log/service.json handler := log.MultiHandler( log.LvlFilterHandler(log.LvlError, log.Must.FileHandler("/var/log/service.json", log.JsonFormat())), log.MatchFilterHandler("pkg", "app/rpc" log.StdoutHandler()) ) Logging File Names and Line Numbers This package implements three Handlers that add debugging information to the context, CallerFileHandler, CallerFuncHandler and CallerStackHandler. Here's an example that adds the source file and line number of each logging call to the context. h := log.CallerFileHandler(log.StdoutHandler) log.Root().SetHandler(h) ... log.Error("open file", "err", err) This will output a line that looks like: lvl=eror t=2014-05-02T16:07:23-0700 msg="open file" err="file not found" caller=data.go:42 Here's an example that logs the call stack rather than just the call site. h := log.CallerStackHandler("%+v", log.StdoutHandler) log.Root().SetHandler(h) ... log.Error("open file", "err", err) This will output a line that looks like: lvl=eror t=2014-05-02T16:07:23-0700 msg="open file" err="file not found" stack="[pkg/data.go:42 pkg/cmd/main.go]" The "%+v" format instructs the handler to include the path of the source file relative to the compile time GOPATH. The github.com/go-stack/stack package documents the full list of formatting verbs and modifiers available. Custom Handlers The Handler interface is so simple that it's also trivial to write your own. Let's create an example handler which tries to write to one handler, but if that fails it falls back to writing to another handler and includes the error that it encountered when trying to write to the primary. This might be useful when trying to log over a network socket, but if that fails you want to log those records to a file on disk. type BackupHandler struct { Primary Handler Secondary Handler } func (h *BackupHandler) Log (r *Record) error { err := h.Primary.Log(r) if err != nil { r.Ctx = append(ctx, "primary_err", err) return h.Secondary.Log(r) } return nil } This pattern is so useful that a generic version that handles an arbitrary number of Handlers is included as part of this library called FailoverHandler. Logging Expensive Operations Sometimes, you want to log values that are extremely expensive to compute, but you don't want to pay the price of computing them if you haven't turned up your logging level to a high level of detail. This package provides a simple type to annotate a logging operation that you want to be evaluated lazily, just when it is about to be logged, so that it would not be evaluated if an upstream Handler filters it out. Just wrap any function which takes no arguments with the log.Lazy type. For example: func factorRSAKey() (factors []int) { // return the factors of a very large number } log.Debug("factors", log.Lazy{factorRSAKey}) If this message is not logged for any reason (like logging at the Error level), then factorRSAKey is never evaluated. Dynamic context values The same log.Lazy mechanism can be used to attach context to a logger which you want to be evaluated when the message is logged, but not when the logger is created. For example, let's imagine a game where you have Player objects: type Player struct { name string alive bool log.Logger } You always want to log a player's name and whether they're alive or dead, so when you create the player object, you might do: p := &Player{name: name, alive: true} p.Logger = log.New("name", p.name, "alive", p.alive) Only now, even after a player has died, the logger will still report they are alive because the logging context is evaluated when the logger was created. By using the Lazy wrapper, we can defer the evaluation of whether the player is alive or not to each log message, so that the log records will reflect the player's current state no matter when the log message is written: p := &Player{name: name, alive: true} isAlive := func() bool { return p.alive } player.Logger = log.New("name", p.name, "alive", log.Lazy{isAlive}) Terminal Format If log15 detects that stdout is a terminal, it will configure the default handler for it (which is log.StdoutHandler) to use TerminalFormat. This format logs records nicely for your terminal, including color-coded output based on log level. Error Handling Becasuse log15 allows you to step around the type system, there are a few ways you can specify invalid arguments to the logging functions. You could, for example, wrap something that is not a zero-argument function with log.Lazy or pass a context key that is not a string. Since logging libraries are typically the mechanism by which errors are reported, it would be onerous for the logging functions to return errors. Instead, log15 handles errors by making these guarantees to you: - Any log record containing an error will still be printed with the error explained to you as part of the log record. - Any log record containing an error will include the context key LOG15_ERROR, enabling you to easily (and if you like, automatically) detect if any of your logging calls are passing bad values. Understanding this, you might wonder why the Handler interface can return an error value in its Log method. Handlers are encouraged to return errors only if they fail to write their log records out to an external source like if the syslog daemon is not responding. This allows the construction of useful handlers which cope with those failures like the FailoverHandler. Library Use log15 is intended to be useful for library authors as a way to provide configurable logging to users of their library. Best practice for use in a library is to always disable all output for your logger by default and to provide a public Logger instance that consumers of your library can configure. Like so: package yourlib import "github.com/inconshreveable/log15" var Log = log.New() func init() { Log.SetHandler(log.DiscardHandler()) } Users of your library may then enable it if they like: import "github.com/inconshreveable/log15" import "example.com/yourlib" func main() { handler := // custom handler setup yourlib.Log.SetHandler(handler) } Best practices attaching logger context The ability to attach context to a logger is a powerful one. Where should you do it and why? I favor embedding a Logger directly into any persistent object in my application and adding unique, tracing context keys to it. For instance, imagine I am writing a web browser: type Tab struct { url string render *RenderingContext // ... Logger } func NewTab(url string) *Tab { return &Tab { // ... url: url, Logger: log.New("url", url), } } When a new tab is created, I assign a logger to it with the url of the tab as context so it can easily be traced through the logs. Now, whenever we perform any operation with the tab, we'll log with its embedded logger and it will include the tab title automatically: tab.Debug("moved position", "idx", tab.idx) There's only one problem. What if the tab url changes? We could use log.Lazy to make sure the current url is always written, but that would mean that we couldn't trace a tab's full lifetime through our logs after the user navigate to a new URL. Instead, think about what values to attach to your loggers the same way you think about what to use as a key in a SQL database schema. If it's possible to use a natural key that is unique for the lifetime of the object, do so. But otherwise, log15's ext package has a handy RandId function to let you generate what you might call "surrogate keys" They're just random hex identifiers to use for tracing. Back to our Tab example, we would prefer to set up our Logger like so: import logext "github.com/inconshreveable/log15/ext" t := &Tab { // ... url: url, } t.Logger = log.New("id", logext.RandId(8), "url", log.Lazy{t.getUrl}) return t Now we'll have a unique traceable identifier even across loading new urls, but we'll still be able to see the tab's current url in the log messages. Must For all Handler functions which can return an error, there is a version of that function which will return no error but panics on failure. They are all available on the Must object. For example: log.Must.FileHandler("/path", log.JsonFormat) log.Must.NetHandler("tcp", ":1234", log.JsonFormat) Inspiration and Credit All of the following excellent projects inspired the design of this library: code.google.com/p/log4go github.com/op/go-logging github.com/technoweenie/grohl github.com/Sirupsen/logrus github.com/kr/logfmt github.com/spacemonkeygo/spacelog golang's stdlib, notably io and net/http The Name https://xkcd.com/927/ */ package log15 �������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/bench_test.go����������������������������������0000644�0610621�0607500�00000007377�13172163416�026046� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.3 package log15 import ( "bytes" "errors" "io/ioutil" "testing" "time" ) func BenchmarkStreamNoCtx(b *testing.B) { lg := New() buf := bytes.Buffer{} lg.SetHandler(StreamHandler(&buf, LogfmtFormat())) for i := 0; i < b.N; i++ { lg.Info("test message") buf.Reset() } } func BenchmarkDiscard(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkCallerFileHandler(b *testing.B) { lg := New() lg.SetHandler(CallerFileHandler(DiscardHandler())) for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkCallerFuncHandler(b *testing.B) { lg := New() lg.SetHandler(CallerFuncHandler(DiscardHandler())) for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkLogfmtNoCtx(b *testing.B) { r := Record{ Time: time.Now(), Lvl: LvlInfo, Msg: "test message", Ctx: []interface{}{}, } logfmt := LogfmtFormat() for i := 0; i < b.N; i++ { logfmt.Format(&r) } } func BenchmarkJsonNoCtx(b *testing.B) { r := Record{ Time: time.Now(), Lvl: LvlInfo, Msg: "test message", Ctx: []interface{}{}, } jsonfmt := JsonFormat() for i := 0; i < b.N; i++ { jsonfmt.Format(&r) } } func BenchmarkMultiLevelFilter(b *testing.B) { handler := MultiHandler( LvlFilterHandler(LvlDebug, DiscardHandler()), LvlFilterHandler(LvlError, DiscardHandler()), ) lg := New() lg.SetHandler(handler) for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkDescendant1(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) lg = lg.New() for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkDescendant2(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) for i := 0; i < 2; i++ { lg = lg.New() } for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkDescendant4(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) for i := 0; i < 4; i++ { lg = lg.New() } for i := 0; i < b.N; i++ { lg.Info("test message") } } func BenchmarkDescendant8(b *testing.B) { lg := New() lg.SetHandler(DiscardHandler()) for i := 0; i < 8; i++ { lg = lg.New() } for i := 0; i < b.N; i++ { lg.Info("test message") } } // Copied from https://github.com/uber-go/zap/blob/master/benchmarks/log15_bench_test.go // (MIT License) func newLog15() Logger { logger := New() logger.SetHandler(StreamHandler(ioutil.Discard, JsonFormat())) return logger } var errExample = errors.New("fail") type user struct { Name string `json:"name"` Email string `json:"email"` CreatedAt time.Time `json:"created_at"` } var _jane = user{ Name: "Jane Doe", Email: "jane@test.com", CreatedAt: time.Date(1980, 1, 1, 12, 0, 0, 0, time.UTC), } func BenchmarkLog15AddingFields(b *testing.B) { logger := newLog15() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { logger.Info("Go fast.", "int", 1, "int64", int64(1), "float", 3.0, "string", "four!", "bool", true, "time", time.Unix(0, 0), "error", errExample.Error(), "duration", time.Second, "user-defined type", _jane, "another string", "done!", ) } }) } func BenchmarkLog15WithAccumulatedContext(b *testing.B) { logger := newLog15().New( "int", 1, "int64", int64(1), "float", 3.0, "string", "four!", "bool", true, "time", time.Unix(0, 0), "error", errExample.Error(), "duration", time.Second, "user-defined type", _jane, "another string", "done!", ) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { logger.Info("Go really fast.") } }) } func BenchmarkLog15WithoutFields(b *testing.B) { logger := newLog15() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { logger.Info("Go fast.") } }) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/README.md��������������������������������������0000644�0610621�0607500�00000006503�13172163416�024646� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������![obligatory xkcd](http://imgs.xkcd.com/comics/standards.png) # log15 [![godoc reference](https://godoc.org/github.com/inconshreveable/log15?status.png)](https://godoc.org/github.com/inconshreveable/log15) [![Build Status](https://travis-ci.org/inconshreveable/log15.svg?branch=master)](https://travis-ci.org/inconshreveable/log15) Package log15 provides an opinionated, simple toolkit for best-practice logging in Go (golang) that is both human and machine readable. It is modeled after the Go standard library's [`io`](http://golang.org/pkg/io/) and [`net/http`](http://golang.org/pkg/net/http/) packages and is an alternative to the standard library's [`log`](http://golang.org/pkg/log/) package. ## Features - A simple, easy-to-understand API - Promotes structured logging by encouraging use of key/value pairs - Child loggers which inherit and add their own private context - Lazy evaluation of expensive operations - Simple Handler interface allowing for construction of flexible, custom logging configurations with a tiny API. - Color terminal support - Built-in support for logging to files, streams, syslog, and the network - Support for forking records to multiple handlers, buffering records for output, failing over from failed handler writes, + more ## Versioning The API of the master branch of log15 should always be considered unstable. If you want to rely on a stable API, you must vendor the library. ## Importing ```go import log "github.com/inconshreveable/log15" ``` ## Examples ```go // all loggers can have key/value context srvlog := log.New("module", "app/server") // all log messages can have key/value context srvlog.Warn("abnormal conn rate", "rate", curRate, "low", lowRate, "high", highRate) // child loggers with inherited context connlog := srvlog.New("raddr", c.RemoteAddr()) connlog.Info("connection open") // lazy evaluation connlog.Debug("ping remote", "latency", log.Lazy{pingRemote}) // flexible configuration srvlog.SetHandler(log.MultiHandler( log.StreamHandler(os.Stderr, log.LogfmtFormat()), log.LvlFilterHandler( log.LvlError, log.Must.FileHandler("errors.json", log.JsonFormat())))) ``` Will result in output that looks like this: ``` WARN[06-17|21:58:10] abnormal conn rate module=app/server rate=0.500 low=0.100 high=0.800 INFO[06-17|21:58:10] connection open module=app/server raddr=10.0.0.1 ``` ## Breaking API Changes The following commits broke API stability. This reference is intended to help you understand the consequences of updating to a newer version of log15. - 57a084d014d4150152b19e4e531399a7145d1540 - Added a `Get()` method to the `Logger` interface to retrieve the current handler - 93404652ee366648fa622b64d1e2b67d75a3094a - `Record` field `Call` changed to `stack.Call` with switch to `github.com/go-stack/stack` - a5e7613673c73281f58e15a87d2cf0cf111e8152 - Restored `syslog.Priority` argument to the `SyslogXxx` handler constructors ## FAQ ### The varargs style is brittle and error prone! Can I have type safety please? Yes. Use `log.Ctx`: ```go srvlog := log.New(log.Ctx{"module": "app/server"}) srvlog.Warn("abnormal conn rate", log.Ctx{"rate": curRate, "low": lowRate, "high": highRate}) ``` ### Regenerating the CONTRIBUTORS file ``` go get -u github.com/kevinburke/write_mailmap write_mailmap > CONTRIBUTORS ``` ## License Apache ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/LICENSE����������������������������������������0000644�0610621�0607500�00000001047�13172163416�024372� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright 2014 Alan Shreve Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/CONTRIBUTORS�����������������������������������0000644�0610621�0607500�00000002037�13172163416�025245� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Aaron L <aaron@bettercoder.net> Alan Shreve <alan@inconshreveable.com> Andy Walker <walkeraj@gmail.com> Andy Watson <andrewmoorewatson@gmail.com> Carl Veazey <Carl_Veazey@cable.comcast.com> Chris Hines <github@cs-guy.com> Christoph Hack <christoph@tux21b.org> Ciaran Downey <me@ciarand.me> Dmitry Chestnykh <dmitry@codingrobots.com> Evan Shaw <edsrzf@gmail.com> Gonzalo Serrano <boikot@gmail.com> Jeremy <jrbudnack@starkandwayne.com> Jonathan Rudenberg <jonathan@titanous.com> Kang Seong-Min <kang.seongmin@gmail.com> Kevin Burke <kev@inburke.com> Marc Abramowitz <marc@marc-abramowitz.com> Nathan Baulch <nathan.baulch@gmail.com> NotZippy <notzippy@gmail.com> Péter Szilágyi <peterke@gmail.com> Robert Egorov <robert.egorov@gmail.com> Robert Starbuck <robstarbuck@gmail.com> Robert Zaremba <robert.zaremba@scale-it.pl> Sean Chittenden <sean@chittenden.org> Spencer Nelson <s@spenczar.com> Tomasz Grodzki <tg@users.noreply.github.com> Trevor Gattis <github@trevorgattis.com> Vincent Vanackere <vincent.vanackere@gmail.com> Will McGovern <will@brkt.com> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/.travis.yml������������������������������������0000644�0610621�0607500�00000000217�13172163416�025474� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go go_import_path: github.com/inconshreveable/log15 sudo: false go: - 1.3 - 1.4 - 1.5 - 1.6 - 1.7 - 1.8 - 1.9 - tip ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/inconshreveable/log15/.mailmap���������������������������������������0000644�0610621�0607500�00000001766�13172163416�025016� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Aaron L <aaron@bettercoder.net> Alan Shreve <alan@inconshreveable.com> Andy Walker <walkeraj@gmail.com> Andy Watson <andrewmoorewatson@gmail.com> Chris Hines <github@cs-guy.com> Chris Hines <chines@comscore.com> Ciaran Downey <me@ciarand.me> Dmitry Chestnykh <dmitry@codingrobots.com> Evan Shaw <edsrzf@gmail.com> Gonzalo Serrano <boikot@gmail.com> Jeremy <jrbudnack@starkandwayne.com> Jonathan Rudenberg <jonathan@titanous.com> Kevin Burke <kev@inburke.com> Marc Abramowitz <marc@marc-abramowitz.com> Nathan Baulch <nathan.baulch@gmail.com> NotZippy <notzippy@gmail.com> Péter Szilágyi <peterke@gmail.com> Robert Egorov <robert.egorov@gmail.com> Robert Starbuck <robstarbuck@gmail.com> Robert Zaremba <robert.zaremba@scale-it.pl> Spencer Nelson <s@spenczar.com> Tomasz Grodzki <tg@users.noreply.github.com> Trevor Gattis <github@trevorgattis.com> Vincent Vanackere <vincent.vanackere@gmail.com> Will McGovern <will@brkt.com> Carl Veazey <Carl_Veazey@cable.comcast.com> Kang Seong-Min <kang.seongmin@gmail.com> ����������lxd-2.0.11/dist/src/github.com/go-stack/������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163415�020774� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/go-stack/stack/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163415�022101� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/go-stack/stack/stackinternal_test.go���������������������������������0000644�0610621�0607500�00000001642�13172163415�026334� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package stack import ( "runtime" "testing" ) func TestCaller(t *testing.T) { t.Parallel() c := Caller(0) _, file, line, ok := runtime.Caller(0) line-- if !ok { t.Fatal("runtime.Caller(0) failed") } if got, want := c.file(), file; got != want { t.Errorf("got file == %v, want file == %v", got, want) } if got, want := c.line(), line; got != want { t.Errorf("got line == %v, want line == %v", got, want) } } type fholder struct { f func() CallStack } func (fh *fholder) labyrinth() CallStack { for { return fh.f() } panic("this line only needed for go 1.0") } func TestTrace(t *testing.T) { t.Parallel() fh := fholder{ f: func() CallStack { cs := Trace() return cs }, } cs := fh.labyrinth() lines := []int{43, 33, 48} for i, line := range lines { if got, want := cs[i].line(), line; got != want { t.Errorf("got line[%d] == %v, want line[%d] == %v", i, got, i, want) } } } ����������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/go-stack/stack/stack_test.go�����������������������������������������0000644�0610621�0607500�00000021037�13172163415�024577� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package stack_test import ( "fmt" "io/ioutil" "path" "path/filepath" "reflect" "runtime" "strings" "testing" "github.com/go-stack/stack" ) const importPath = "github.com/go-stack/stack" type testType struct{} func (tt testType) testMethod() (c stack.Call, pc uintptr, file string, line int, ok bool) { c = stack.Caller(0) pc, file, line, ok = runtime.Caller(0) line-- return } func TestCallFormat(t *testing.T) { t.Parallel() c := stack.Caller(0) pc, file, line, ok := runtime.Caller(0) line-- if !ok { t.Fatal("runtime.Caller(0) failed") } relFile := path.Join(importPath, filepath.Base(file)) c2, pc2, file2, line2, ok2 := testType{}.testMethod() if !ok2 { t.Fatal("runtime.Caller(0) failed") } relFile2 := path.Join(importPath, filepath.Base(file2)) data := []struct { c stack.Call desc string fmt string out string }{ {stack.Call{}, "error", "%s", "%!s(NOFUNC)"}, {c, "func", "%s", path.Base(file)}, {c, "func", "%+s", relFile}, {c, "func", "%#s", file}, {c, "func", "%d", fmt.Sprint(line)}, {c, "func", "%n", "TestCallFormat"}, {c, "func", "%+n", runtime.FuncForPC(pc - 1).Name()}, {c, "func", "%k", "stack_test"}, {c, "func", "%+k", "github.com/go-stack/stack_test"}, {c, "func", "%v", fmt.Sprint(path.Base(file), ":", line)}, {c, "func", "%+v", fmt.Sprint(relFile, ":", line)}, {c, "func", "%#v", fmt.Sprint(file, ":", line)}, {c2, "meth", "%s", path.Base(file2)}, {c2, "meth", "%+s", relFile2}, {c2, "meth", "%#s", file2}, {c2, "meth", "%d", fmt.Sprint(line2)}, {c2, "meth", "%n", "testType.testMethod"}, {c2, "meth", "%+n", runtime.FuncForPC(pc2).Name()}, {c2, "meth", "%k", "stack_test"}, {c2, "meth", "%+k", "github.com/go-stack/stack_test"}, {c2, "meth", "%v", fmt.Sprint(path.Base(file2), ":", line2)}, {c2, "meth", "%+v", fmt.Sprint(relFile2, ":", line2)}, {c2, "meth", "%#v", fmt.Sprint(file2, ":", line2)}, } for _, d := range data { got := fmt.Sprintf(d.fmt, d.c) if got != d.out { t.Errorf("fmt.Sprintf(%q, Call(%s)) = %s, want %s", d.fmt, d.desc, got, d.out) } } } func TestCallString(t *testing.T) { t.Parallel() c := stack.Caller(0) _, file, line, ok := runtime.Caller(0) line-- if !ok { t.Fatal("runtime.Caller(0) failed") } c2, _, file2, line2, ok2 := testType{}.testMethod() if !ok2 { t.Fatal("runtime.Caller(0) failed") } data := []struct { c stack.Call desc string out string }{ {stack.Call{}, "error", "%!v(NOFUNC)"}, {c, "func", fmt.Sprint(path.Base(file), ":", line)}, {c2, "meth", fmt.Sprint(path.Base(file2), ":", line2)}, } for _, d := range data { got := d.c.String() if got != d.out { t.Errorf("got %s, want %s", got, d.out) } } } func TestCallMarshalText(t *testing.T) { t.Parallel() c := stack.Caller(0) _, file, line, ok := runtime.Caller(0) line-- if !ok { t.Fatal("runtime.Caller(0) failed") } c2, _, file2, line2, ok2 := testType{}.testMethod() if !ok2 { t.Fatal("runtime.Caller(0) failed") } data := []struct { c stack.Call desc string out []byte err error }{ {stack.Call{}, "error", nil, stack.ErrNoFunc}, {c, "func", []byte(fmt.Sprint(path.Base(file), ":", line)), nil}, {c2, "meth", []byte(fmt.Sprint(path.Base(file2), ":", line2)), nil}, } for _, d := range data { text, err := d.c.MarshalText() if got, want := err, d.err; got != want { t.Errorf("%s: got err %v, want err %v", d.desc, got, want) } if got, want := text, d.out; !reflect.DeepEqual(got, want) { t.Errorf("%s: got %s, want %s", d.desc, got, want) } } } func TestCallStackString(t *testing.T) { cs, line0 := getTrace(t) _, file, line1, ok := runtime.Caller(0) line1-- if !ok { t.Fatal("runtime.Caller(0) failed") } file = path.Base(file) if got, want := cs.String(), fmt.Sprintf("[%s:%d %s:%d]", file, line0, file, line1); got != want { t.Errorf("\n got %v\nwant %v", got, want) } } func TestCallStackMarshalText(t *testing.T) { cs, line0 := getTrace(t) _, file, line1, ok := runtime.Caller(0) line1-- if !ok { t.Fatal("runtime.Caller(0) failed") } file = path.Base(file) text, _ := cs.MarshalText() if got, want := text, []byte(fmt.Sprintf("[%s:%d %s:%d]", file, line0, file, line1)); !reflect.DeepEqual(got, want) { t.Errorf("\n got %v\nwant %v", got, want) } } func getTrace(t *testing.T) (stack.CallStack, int) { cs := stack.Trace().TrimRuntime() _, _, line, ok := runtime.Caller(0) line-- if !ok { t.Fatal("runtime.Caller(0) failed") } return cs, line } func TestTrimAbove(t *testing.T) { trace := trimAbove() if got, want := len(trace), 2; got != want { t.Errorf("got len(trace) == %v, want %v, trace: %n", got, want, trace) } if got, want := fmt.Sprintf("%n", trace[1]), "TestTrimAbove"; got != want { t.Errorf("got %q, want %q", got, want) } } func trimAbove() stack.CallStack { call := stack.Caller(1) trace := stack.Trace() return trace.TrimAbove(call) } func TestTrimBelow(t *testing.T) { trace := trimBelow() if got, want := fmt.Sprintf("%n", trace[0]), "TestTrimBelow"; got != want { t.Errorf("got %q, want %q", got, want) } } func trimBelow() stack.CallStack { call := stack.Caller(1) trace := stack.Trace() return trace.TrimBelow(call) } func TestTrimRuntime(t *testing.T) { trace := stack.Trace().TrimRuntime() if got, want := len(trace), 1; got != want { t.Errorf("got len(trace) == %v, want %v, goroot: %q, trace: %#v", got, want, runtime.GOROOT(), trace) } } func BenchmarkCallVFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprint(ioutil.Discard, c) } } func BenchmarkCallPlusVFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprintf(ioutil.Discard, "%+v", c) } } func BenchmarkCallSharpVFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprintf(ioutil.Discard, "%#v", c) } } func BenchmarkCallSFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprintf(ioutil.Discard, "%s", c) } } func BenchmarkCallPlusSFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprintf(ioutil.Discard, "%+s", c) } } func BenchmarkCallSharpSFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprintf(ioutil.Discard, "%#s", c) } } func BenchmarkCallDFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprintf(ioutil.Discard, "%d", c) } } func BenchmarkCallNFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprintf(ioutil.Discard, "%n", c) } } func BenchmarkCallPlusNFmt(b *testing.B) { c := stack.Caller(0) b.ResetTimer() for i := 0; i < b.N; i++ { fmt.Fprintf(ioutil.Discard, "%+n", c) } } func BenchmarkCaller(b *testing.B) { for i := 0; i < b.N; i++ { stack.Caller(0) } } func BenchmarkTrace(b *testing.B) { for i := 0; i < b.N; i++ { stack.Trace() } } func deepStack(depth int, b *testing.B) stack.CallStack { if depth > 0 { return deepStack(depth-1, b) } b.StartTimer() s := stack.Trace() return s } func BenchmarkTrace10(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() deepStack(10, b) } } func BenchmarkTrace50(b *testing.B) { b.StopTimer() for i := 0; i < b.N; i++ { deepStack(50, b) } } func BenchmarkTrace100(b *testing.B) { b.StopTimer() for i := 0; i < b.N; i++ { deepStack(100, b) } } //////////////// // Benchmark functions followed by formatting //////////////// func BenchmarkCallerAndVFmt(b *testing.B) { for i := 0; i < b.N; i++ { fmt.Fprint(ioutil.Discard, stack.Caller(0)) } } func BenchmarkTraceAndVFmt(b *testing.B) { for i := 0; i < b.N; i++ { fmt.Fprint(ioutil.Discard, stack.Trace()) } } func BenchmarkTrace10AndVFmt(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() fmt.Fprint(ioutil.Discard, deepStack(10, b)) } } //////////////// // Baseline against package runtime. //////////////// func BenchmarkRuntimeCaller(b *testing.B) { for i := 0; i < b.N; i++ { runtime.Caller(0) } } func BenchmarkRuntimeCallerAndFmt(b *testing.B) { for i := 0; i < b.N; i++ { _, file, line, _ := runtime.Caller(0) const sep = "/" if i := strings.LastIndex(file, sep); i != -1 { file = file[i+len(sep):] } fmt.Fprint(ioutil.Discard, file, ":", line) } } func BenchmarkFuncForPC(b *testing.B) { pc, _, _, _ := runtime.Caller(0) pc-- b.ResetTimer() for i := 0; i < b.N; i++ { runtime.FuncForPC(pc) } } func BenchmarkFuncFileLine(b *testing.B) { pc, _, _, _ := runtime.Caller(0) pc-- fn := runtime.FuncForPC(pc) b.ResetTimer() for i := 0; i < b.N; i++ { fn.FileLine(pc) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/go-stack/stack/stack.go����������������������������������������������0000644�0610621�0607500�00000020661�13172163415�023542� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package stack implements utilities to capture, manipulate, and format call // stacks. It provides a simpler API than package runtime. // // The implementation takes care of the minutia and special cases of // interpreting the program counter (pc) values returned by runtime.Callers. // // Package stack's types implement fmt.Formatter, which provides a simple and // flexible way to declaratively configure formatting when used with logging // or error tracking packages. package stack import ( "bytes" "errors" "fmt" "io" "runtime" "strconv" "strings" ) // Call records a single function invocation from a goroutine stack. type Call struct { fn *runtime.Func pc uintptr } // Caller returns a Call from the stack of the current goroutine. The argument // skip is the number of stack frames to ascend, with 0 identifying the // calling function. func Caller(skip int) Call { var pcs [2]uintptr n := runtime.Callers(skip+1, pcs[:]) var c Call if n < 2 { return c } c.pc = pcs[1] if runtime.FuncForPC(pcs[0]).Name() != "runtime.sigpanic" { c.pc-- } c.fn = runtime.FuncForPC(c.pc) return c } // String implements fmt.Stinger. It is equivalent to fmt.Sprintf("%v", c). func (c Call) String() string { return fmt.Sprint(c) } // MarshalText implements encoding.TextMarshaler. It formats the Call the same // as fmt.Sprintf("%v", c). func (c Call) MarshalText() ([]byte, error) { if c.fn == nil { return nil, ErrNoFunc } buf := bytes.Buffer{} fmt.Fprint(&buf, c) return buf.Bytes(), nil } // ErrNoFunc means that the Call has a nil *runtime.Func. The most likely // cause is a Call with the zero value. var ErrNoFunc = errors.New("no call stack information") // Format implements fmt.Formatter with support for the following verbs. // // %s source file // %d line number // %n function name // %k last segment of the package path // %v equivalent to %s:%d // // It accepts the '+' and '#' flags for most of the verbs as follows. // // %+s path of source file relative to the compile time GOPATH // %#s full path of source file // %+n import path qualified function name // %+k full package path // %+v equivalent to %+s:%d // %#v equivalent to %#s:%d func (c Call) Format(s fmt.State, verb rune) { if c.fn == nil { fmt.Fprintf(s, "%%!%c(NOFUNC)", verb) return } switch verb { case 's', 'v': file, line := c.fn.FileLine(c.pc) switch { case s.Flag('#'): // done case s.Flag('+'): file = file[pkgIndex(file, c.fn.Name()):] default: const sep = "/" if i := strings.LastIndex(file, sep); i != -1 { file = file[i+len(sep):] } } io.WriteString(s, file) if verb == 'v' { buf := [7]byte{':'} s.Write(strconv.AppendInt(buf[:1], int64(line), 10)) } case 'd': _, line := c.fn.FileLine(c.pc) buf := [6]byte{} s.Write(strconv.AppendInt(buf[:0], int64(line), 10)) case 'k': name := c.fn.Name() const pathSep = "/" start, end := 0, len(name) if i := strings.LastIndex(name, pathSep); i != -1 { start = i + len(pathSep) } const pkgSep = "." if i := strings.Index(name[start:], pkgSep); i != -1 { end = start + i } if s.Flag('+') { start = 0 } io.WriteString(s, name[start:end]) case 'n': name := c.fn.Name() if !s.Flag('+') { const pathSep = "/" if i := strings.LastIndex(name, pathSep); i != -1 { name = name[i+len(pathSep):] } const pkgSep = "." if i := strings.Index(name, pkgSep); i != -1 { name = name[i+len(pkgSep):] } } io.WriteString(s, name) } } // PC returns the program counter for this call frame; multiple frames may // have the same PC value. func (c Call) PC() uintptr { return c.pc } // name returns the import path qualified name of the function containing the // call. func (c Call) name() string { if c.fn == nil { return "???" } return c.fn.Name() } func (c Call) file() string { if c.fn == nil { return "???" } file, _ := c.fn.FileLine(c.pc) return file } func (c Call) line() int { if c.fn == nil { return 0 } _, line := c.fn.FileLine(c.pc) return line } // CallStack records a sequence of function invocations from a goroutine // stack. type CallStack []Call // String implements fmt.Stinger. It is equivalent to fmt.Sprintf("%v", cs). func (cs CallStack) String() string { return fmt.Sprint(cs) } var ( openBracketBytes = []byte("[") closeBracketBytes = []byte("]") spaceBytes = []byte(" ") ) // MarshalText implements encoding.TextMarshaler. It formats the CallStack the // same as fmt.Sprintf("%v", cs). func (cs CallStack) MarshalText() ([]byte, error) { buf := bytes.Buffer{} buf.Write(openBracketBytes) for i, pc := range cs { if pc.fn == nil { return nil, ErrNoFunc } if i > 0 { buf.Write(spaceBytes) } fmt.Fprint(&buf, pc) } buf.Write(closeBracketBytes) return buf.Bytes(), nil } // Format implements fmt.Formatter by printing the CallStack as square brackets // ([, ]) surrounding a space separated list of Calls each formatted with the // supplied verb and options. func (cs CallStack) Format(s fmt.State, verb rune) { s.Write(openBracketBytes) for i, pc := range cs { if i > 0 { s.Write(spaceBytes) } pc.Format(s, verb) } s.Write(closeBracketBytes) } // Trace returns a CallStack for the current goroutine with element 0 // identifying the calling function. func Trace() CallStack { var pcs [512]uintptr n := runtime.Callers(2, pcs[:]) cs := make([]Call, n) for i, pc := range pcs[:n] { pcFix := pc if i > 0 && cs[i-1].fn.Name() != "runtime.sigpanic" { pcFix-- } cs[i] = Call{ fn: runtime.FuncForPC(pcFix), pc: pcFix, } } return cs } // TrimBelow returns a slice of the CallStack with all entries below c // removed. func (cs CallStack) TrimBelow(c Call) CallStack { for len(cs) > 0 && cs[0].pc != c.pc { cs = cs[1:] } return cs } // TrimAbove returns a slice of the CallStack with all entries above c // removed. func (cs CallStack) TrimAbove(c Call) CallStack { for len(cs) > 0 && cs[len(cs)-1].pc != c.pc { cs = cs[:len(cs)-1] } return cs } // pkgIndex returns the index that results in file[index:] being the path of // file relative to the compile time GOPATH, and file[:index] being the // $GOPATH/src/ portion of file. funcName must be the name of a function in // file as returned by runtime.Func.Name. func pkgIndex(file, funcName string) int { // As of Go 1.6.2 there is no direct way to know the compile time GOPATH // at runtime, but we can infer the number of path segments in the GOPATH. // We note that runtime.Func.Name() returns the function name qualified by // the import path, which does not include the GOPATH. Thus we can trim // segments from the beginning of the file path until the number of path // separators remaining is one more than the number of path separators in // the function name. For example, given: // // GOPATH /home/user // file /home/user/src/pkg/sub/file.go // fn.Name() pkg/sub.Type.Method // // We want to produce: // // file[:idx] == /home/user/src/ // file[idx:] == pkg/sub/file.go // // From this we can easily see that fn.Name() has one less path separator // than our desired result for file[idx:]. We count separators from the // end of the file path until it finds two more than in the function name // and then move one character forward to preserve the initial path // segment without a leading separator. const sep = "/" i := len(file) for n := strings.Count(funcName, sep) + 2; n > 0; n-- { i = strings.LastIndex(file[:i], sep) if i == -1 { i = -len(sep) break } } // get back to 0 or trim the leading separator return i + len(sep) } var runtimePath string func init() { var pcs [1]uintptr runtime.Callers(0, pcs[:]) fn := runtime.FuncForPC(pcs[0]) file, _ := fn.FileLine(pcs[0]) idx := pkgIndex(file, fn.Name()) runtimePath = file[:idx] if runtime.GOOS == "windows" { runtimePath = strings.ToLower(runtimePath) } } func inGoroot(c Call) bool { file := c.file() if len(file) == 0 || file[0] == '?' { return true } if runtime.GOOS == "windows" { file = strings.ToLower(file) } return strings.HasPrefix(file, runtimePath) || strings.HasSuffix(file, "/_testmain.go") } // TrimRuntime returns a slice of the CallStack with the topmost entries from // the go runtime removed. It considers any calls originating from unknown // files, files under GOROOT, or _testmain.go as part of the runtime. func (cs CallStack) TrimRuntime() CallStack { for len(cs) > 0 && inGoroot(cs[len(cs)-1]) { cs = cs[:len(cs)-1] } return cs } �������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/go-stack/stack/format_test.go����������������������������������������0000644�0610621�0607500�00000000524�13172163415�024760� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.2 package stack_test import ( "fmt" "github.com/go-stack/stack" ) func Example_callFormat() { logCaller("%+s") logCaller("%v %[1]n()") // Output: // github.com/go-stack/stack/format_test.go // format_test.go:13 Example_callFormat() } func logCaller(format string) { fmt.Printf(format+"\n", stack.Caller(1)) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/go-stack/stack/README.md���������������������������������������������0000644�0610621�0607500�00000003027�13172163415�023362� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������[![GoDoc](https://godoc.org/github.com/go-stack/stack?status.svg)](https://godoc.org/github.com/go-stack/stack) [![Go Report Card](https://goreportcard.com/badge/go-stack/stack)](https://goreportcard.com/report/go-stack/stack) [![TravisCI](https://travis-ci.org/go-stack/stack.svg?branch=master)](https://travis-ci.org/go-stack/stack) [![Coverage Status](https://coveralls.io/repos/github/go-stack/stack/badge.svg?branch=master)](https://coveralls.io/github/go-stack/stack?branch=master) # stack Package stack implements utilities to capture, manipulate, and format call stacks. It provides a simpler API than package runtime. The implementation takes care of the minutia and special cases of interpreting the program counter (pc) values returned by runtime.Callers. ## Versioning Package stack publishes releases via [semver](http://semver.org/) compatible Git tags prefixed with a single 'v'. The master branch always contains the latest release. The develop branch contains unreleased commits. ## Formatting Package stack's types implement fmt.Formatter, which provides a simple and flexible way to declaratively configure formatting when used with logging or error tracking packages. ```go func DoTheThing() { c := stack.Caller(0) log.Print(c) // "source.go:10" log.Printf("%+v", c) // "pkg/path/source.go:10" log.Printf("%n", c) // "DoTheThing" s := stack.Trace().TrimRuntime() log.Print(s) // "[source.go:15 caller.go:42 main.go:14]" } ``` See the docs for all of the supported formatting options. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/go-stack/stack/LICENSE.md��������������������������������������������0000644�0610621�0607500�00000002066�13172163415�023511� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The MIT License (MIT) Copyright (c) 2014 Chris Hines Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/go-stack/stack/.travis.yml�������������������������������������������0000644�0610621�0607500�00000000326�13172163415�024213� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go sudo: false go: - 1.2 - 1.3 - 1.4 - 1.5 - 1.6 - tip before_install: - go get github.com/mattn/goveralls - go get golang.org/x/tools/cmd/cover script: - goveralls -service=travis-ci ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/��������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163413�020600� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163413�022264� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/go-xgettext/������������������������������������������0000755�0610621�0607500�00000000000�13172163413�024543� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/go-xgettext/main_test.go������������������������������0000644�0610621�0607500�00000024207�13172163413�027062� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2015-2016 Canonical Ltd * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package main import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "testing" . "gopkg.in/check.v1" ) // Hook up check.v1 into the "go test" runner func Test(t *testing.T) { TestingT(t) } type xgettextTestSuite struct { } var _ = Suite(&xgettextTestSuite{}) // test helper func makeGoSourceFile(c *C, content []byte) string { fname := filepath.Join(c.MkDir(), "foo.go") err := ioutil.WriteFile(fname, []byte(content), 0644) c.Assert(err, IsNil) return fname } func (s *xgettextTestSuite) SetUpTest(c *C) { // our test defaults opts.NoLocation = false opts.AddCommentsTag = "TRANSLATORS:" opts.Keyword = "i18n.G" opts.KeywordPlural = "i18n.NG" opts.SortOutput = true opts.PackageName = "snappy" opts.MsgIDBugsAddress = "snappy-devel@lists.ubuntu.com" // mock time formatTime = func() string { return "2015-06-30 14:48+0200" } } func (s *xgettextTestSuite) TestFormatComment(c *C) { var tests = []struct { in string out string }{ {in: "// foo ", out: "#. foo\n"}, {in: "/* foo */", out: "#. foo\n"}, {in: "/* foo\n */", out: "#. foo\n"}, {in: "/* foo\nbar */", out: "#. foo\n#. bar\n"}, } for _, test := range tests { c.Assert(formatComment(test.in), Equals, test.out) } } func (s *xgettextTestSuite) TestProcessFilesSimple(c *C) { fname := makeGoSourceFile(c, []byte(`package main func main() { // TRANSLATORS: foo comment i18n.G("foo") } `)) err := processFiles([]string{fname}) c.Assert(err, IsNil) c.Assert(msgIDs, DeepEquals, map[string][]msgID{ "foo": []msgID{ { comment: "#. TRANSLATORS: foo comment\n", fname: fname, line: 5, }, }, }) } func (s *xgettextTestSuite) TestProcessFilesMultiple(c *C) { fname := makeGoSourceFile(c, []byte(`package main func main() { // TRANSLATORS: foo comment i18n.G("foo") // TRANSLATORS: bar comment i18n.G("foo") } `)) err := processFiles([]string{fname}) c.Assert(err, IsNil) c.Assert(msgIDs, DeepEquals, map[string][]msgID{ "foo": []msgID{ { comment: "#. TRANSLATORS: foo comment\n", fname: fname, line: 5, }, { comment: "#. TRANSLATORS: bar comment\n", fname: fname, line: 8, }, }, }) } const header = `# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "Project-Id-Version: snappy\n" "Report-Msgid-Bugs-To: snappy-devel@lists.ubuntu.com\n" "POT-Creation-Date: 2015-06-30 14:48+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" ` func (s *xgettextTestSuite) TestWriteOutputSimple(c *C) { msgIDs = map[string][]msgID{ "foo": []msgID{ { fname: "fname", line: 2, comment: "#. foo\n", }, }, } out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #. foo #: fname:2 msgid "foo" msgstr "" `, header) c.Assert(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestWriteOutputMultiple(c *C) { msgIDs = map[string][]msgID{ "foo": []msgID{ { fname: "fname", line: 2, comment: "#. comment1\n", }, { fname: "fname", line: 4, comment: "#. comment2\n", }, }, } out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #. comment1 #. comment2 #: fname:2 fname:4 msgid "foo" msgstr "" `, header) c.Assert(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestWriteOutputNoComment(c *C) { msgIDs = map[string][]msgID{ "foo": []msgID{ { fname: "fname", line: 2, }, }, } out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #: fname:2 msgid "foo" msgstr "" `, header) c.Assert(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestWriteOutputNoLocation(c *C) { msgIDs = map[string][]msgID{ "foo": []msgID{ { fname: "fname", line: 2, }, }, } opts.NoLocation = true out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s msgid "foo" msgstr "" `, header) c.Assert(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestWriteOutputFormatHint(c *C) { msgIDs = map[string][]msgID{ "foo": []msgID{ { fname: "fname", line: 2, formatHint: "c-format", }, }, } out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #: fname:2 #, c-format msgid "foo" msgstr "" `, header) c.Assert(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestWriteOutputPlural(c *C) { msgIDs = map[string][]msgID{ "foo": []msgID{ { msgidPlural: "plural", fname: "fname", line: 2, }, }, } out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #: fname:2 msgid "foo" msgid_plural "plural" msgstr[0] "" msgstr[1] "" `, header) c.Assert(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestWriteOutputSorted(c *C) { msgIDs = map[string][]msgID{ "aaa": []msgID{ { fname: "fname", line: 2, }, }, "zzz": []msgID{ { fname: "fname", line: 2, }, }, } opts.SortOutput = true // we need to run this a bunch of times as the ordering might // be right by pure chance for i := 0; i < 10; i++ { out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #: fname:2 msgid "aaa" msgstr "" #: fname:2 msgid "zzz" msgstr "" `, header) c.Assert(out.String(), Equals, expected) } } func (s *xgettextTestSuite) TestIntegration(c *C) { fname := makeGoSourceFile(c, []byte(`package main func main() { // TRANSLATORS: foo comment // with multiple lines i18n.G("foo") // this comment has no translators tag i18n.G("abc") // TRANSLATORS: plural i18n.NG("singular", "plural", 99) i18n.G("zz %s") } `)) // a real integration test :) outName := filepath.Join(c.MkDir(), "snappy.pot") os.Args = []string{"test-binary", "--output", outName, "--keyword", "i18n.G", "--keyword-plural", "i18n.NG", "--msgid-bugs-address", "snappy-devel@lists.ubuntu.com", "--package-name", "snappy", fname, } main() // verify its what we expect got, err := ioutil.ReadFile(outName) c.Assert(err, IsNil) expected := fmt.Sprintf(`%s #: %[2]s:9 msgid "abc" msgstr "" #. TRANSLATORS: foo comment #. with multiple lines #: %[2]s:6 msgid "foo" msgstr "" #. TRANSLATORS: plural #: %[2]s:12 msgid "singular" msgid_plural "plural" msgstr[0] "" msgstr[1] "" #: %[2]s:14 #, c-format msgid "zz %%s" msgstr "" `, header, fname) c.Assert(string(got), Equals, expected) } func (s *xgettextTestSuite) TestProcessFilesConcat(c *C) { fname := makeGoSourceFile(c, []byte(`package main func main() { // TRANSLATORS: foo comment i18n.G("foo\n" + "bar\n" + "baz") } `)) err := processFiles([]string{fname}) c.Assert(err, IsNil) c.Assert(msgIDs, DeepEquals, map[string][]msgID{ "foo\\nbar\\nbaz": []msgID{ { comment: "#. TRANSLATORS: foo comment\n", fname: fname, line: 5, }, }, }) } func (s *xgettextTestSuite) TestProcessFilesWithQuote(c *C) { fname := makeGoSourceFile(c, []byte(fmt.Sprintf(`package main func main() { i18n.G(%[1]s foo "bar"%[1]s) } `, "`"))) err := processFiles([]string{fname}) c.Assert(err, IsNil) out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #: %[2]s:4 msgid " foo \"bar\"" msgstr "" `, header, fname) c.Check(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestWriteOutputMultilines(c *C) { msgIDs = map[string][]msgID{ "foo\\nbar\\nbaz": []msgID{ { fname: "fname", line: 2, comment: "#. foo\n", }, }, } out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #. foo #: fname:2 msgid "foo\n" "bar\n" "baz" msgstr "" `, header) c.Assert(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestWriteOutputTidy(c *C) { msgIDs = map[string][]msgID{ "foo\\nbar\\nbaz": []msgID{ { fname: "fname", line: 2, }, }, "zzz\\n": []msgID{ { fname: "fname", line: 4, }, }, } out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #: fname:2 msgid "foo\n" "bar\n" "baz" msgstr "" #: fname:4 msgid "zzz\n" msgstr "" `, header) c.Assert(out.String(), Equals, expected) } func (s *xgettextTestSuite) TestProcessFilesWithDoubleQuote(c *C) { fname := makeGoSourceFile(c, []byte(`package main func main() { i18n.G("foo \"bar\"") } `)) err := processFiles([]string{fname}) c.Assert(err, IsNil) out := bytes.NewBuffer([]byte("")) writePotFile(out) expected := fmt.Sprintf(`%s #: %[2]s:4 msgid "foo \"bar\"" msgstr "" `, header, fname) c.Check(out.String(), Equals, expected) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/go-xgettext/main.go�����������������������������������0000644�0610621�0607500�00000023124�13172163413�026020� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2015-2016 Canonical Ltd * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package main import ( "fmt" "go/ast" "go/parser" "go/token" "io" "io/ioutil" "log" "os" "sort" "strings" "time" "github.com/jessevdk/go-flags" ) type msgID struct { msgidPlural string comment string fname string line int formatHint string } var msgIDs map[string][]msgID func formatComment(com string) string { out := "" for _, rawline := range strings.Split(com, "\n") { line := rawline line = strings.TrimPrefix(line, "//") line = strings.TrimPrefix(line, "/*") line = strings.TrimSuffix(line, "*/") line = strings.TrimSpace(line) if line != "" { out += fmt.Sprintf("#. %s\n", line) } } return out } func findCommentsForTranslation(fset *token.FileSet, f *ast.File, posCall token.Position) string { com := "" for _, cg := range f.Comments { // search for all comments in the previous line for i := len(cg.List) - 1; i >= 0; i-- { c := cg.List[i] posComment := fset.Position(c.End()) //println(posCall.Line, posComment.Line, c.Text) if posCall.Line == posComment.Line+1 { posCall = posComment com = fmt.Sprintf("%s\n%s", c.Text, com) } } } // only return if we have a matching prefix formatedComment := formatComment(com) needle := fmt.Sprintf("#. %s", opts.AddCommentsTag) if !strings.HasPrefix(formatedComment, needle) { formatedComment = "" } return formatedComment } func constructValue(val interface{}) string { switch val.(type) { case *ast.BasicLit: return val.(*ast.BasicLit).Value // this happens for constructs like: // gettext.Gettext("foo" + "bar") case *ast.BinaryExpr: // we only support string concat if val.(*ast.BinaryExpr).Op != token.ADD { return "" } left := constructValue(val.(*ast.BinaryExpr).X) // strip right " (or `) left = left[0 : len(left)-1] right := constructValue(val.(*ast.BinaryExpr).Y) // strip left " (or `) right = right[1:len(right)] return left + right default: panic(fmt.Sprintf("unknown type: %v", val)) } } func inspectNodeForTranslations(fset *token.FileSet, f *ast.File, n ast.Node) bool { // FIXME: this assume we always have a "gettext.Gettext" style keyword var gettextSelector, gettextFuncName string l := strings.Split(opts.Keyword, ".") if len(l) > 1 { gettextSelector = l[0] gettextFuncName = l[1] } else { gettextFuncName = l[0] } var gettextSelectorPlural, gettextFuncNamePlural string l = strings.Split(opts.KeywordPlural, ".") if len(l) > 1 { gettextSelectorPlural = l[0] gettextFuncNamePlural = l[1] } else { gettextFuncNamePlural = l[0] } switch x := n.(type) { case *ast.CallExpr: var i18nStr, i18nStrPlural string //if sel, ok := x.Fun.(*ast.Ident); ok { //} switch sel := x.Fun.(type) { case *ast.Ident: if sel.Name == gettextFuncNamePlural { i18nStr = x.Args[0].(*ast.BasicLit).Value i18nStrPlural = x.Args[1].(*ast.BasicLit).Value } if sel.Name == gettextFuncName { i18nStr = constructValue(x.Args[0]) } case *ast.SelectorExpr: if sel.Sel.Name == gettextFuncNamePlural && sel.X.(*ast.Ident).Name == gettextSelectorPlural { i18nStr = x.Args[0].(*ast.BasicLit).Value i18nStrPlural = x.Args[1].(*ast.BasicLit).Value } if sel.Sel.Name == gettextFuncName && sel.X.(*ast.Ident).Name == gettextSelector { i18nStr = constructValue(x.Args[0]) } } if i18nStr == "" { break } // FIXME: too simplistic(?), no %% is considered formatHint := "" if strings.Contains(i18nStr, "%") || strings.Contains(i18nStrPlural, "%") { // well, not quite correct but close enough formatHint = "c-format" } msgidStr := formatI18nStr(i18nStr) posCall := fset.Position(n.Pos()) msgIDs[msgidStr] = append(msgIDs[msgidStr], msgID{ formatHint: formatHint, msgidPlural: formatI18nStr(i18nStrPlural), fname: posCall.Filename, line: posCall.Line, comment: findCommentsForTranslation(fset, f, posCall), }) } return true } func formatI18nStr(s string) string { if s == "" { return "" } // the "`" is special if s[0] == '`' { // replace inner " with \" s = strings.Replace(s, "\"", "\\\"", -1) // replace \n with \\n s = strings.Replace(s, "\n", "\\n", -1) } // strip leading and trailing " (or `) s = s[1 : len(s)-1] return s } func processFiles(args []string) error { // go over the input files msgIDs = make(map[string][]msgID) fset := token.NewFileSet() for _, fname := range args { if err := processSingleGoSource(fset, fname); err != nil { return err } } return nil } func processSingleGoSource(fset *token.FileSet, fname string) error { fnameContent, err := ioutil.ReadFile(fname) if err != nil { panic(err) } // Create the AST by parsing src. f, err := parser.ParseFile(fset, fname, fnameContent, parser.ParseComments) if err != nil { panic(err) } ast.Inspect(f, func(n ast.Node) bool { return inspectNodeForTranslations(fset, f, n) }) return nil } var formatTime = func() string { return time.Now().Format("2006-01-02 15:04-0700") } func writePotFile(out io.Writer) { header := fmt.Sprintf(`# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "Project-Id-Version: %s\n" "Report-Msgid-Bugs-To: %s\n" "POT-Creation-Date: %s\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" `, opts.PackageName, opts.MsgIDBugsAddress, formatTime()) fmt.Fprintf(out, "%s", header) // yes, this is the way to do it in go sortedKeys := []string{} for k := range msgIDs { sortedKeys = append(sortedKeys, k) } if opts.SortOutput { sort.Strings(sortedKeys) } // FIXME: use template here? for _, k := range sortedKeys { msgidList := msgIDs[k] for _, msgid := range msgidList { if opts.AddComments || opts.AddCommentsTag != "" { fmt.Fprintf(out, "%s", msgid.comment) } } if !opts.NoLocation { fmt.Fprintf(out, "#:") for _, msgid := range msgidList { fmt.Fprintf(out, " %s:%d", msgid.fname, msgid.line) } fmt.Fprintf(out, "\n") } msgid := msgidList[0] if msgid.formatHint != "" { fmt.Fprintf(out, "#, %s\n", msgid.formatHint) } var formatOutput = func(in string) string { // split string with \n into multiple lines // to make the output nicer out := strings.Replace(in, "\\n", "\\n\"\n \"", -1) // cleanup too aggressive splitting (empty "" lines) return strings.TrimSuffix(out, "\"\n \"") } fmt.Fprintf(out, "msgid \"%v\"\n", formatOutput(k)) if msgid.msgidPlural != "" { fmt.Fprintf(out, "msgid_plural \"%v\"\n", formatOutput(msgid.msgidPlural)) fmt.Fprintf(out, "msgstr[0] \"\"\n") fmt.Fprintf(out, "msgstr[1] \"\"\n") } else { fmt.Fprintf(out, "msgstr \"\"\n") } fmt.Fprintf(out, "\n") } } // FIXME: this must be setable via go-flags var opts struct { Output string `short:"o" long:"output" description:"output to specified file"` AddComments bool `short:"c" long:"add-comments" description:"place all comment blocks preceding keyword lines in output file"` AddCommentsTag string `long:"add-comments-tag" description:"place comment blocks starting with TAG and prceding keyword lines in output file"` SortOutput bool `short:"s" long:"sort-output" description:"generate sorted output"` NoLocation bool `long:"no-location" description:"do not write '#: filename:line' lines"` MsgIDBugsAddress string `long:"msgid-bugs-address" default:"EMAIL" description:"set report address for msgid bugs"` PackageName string `long:"package-name" description:"set package name in output"` Keyword string `short:"k" long:"keyword" default:"gettext.Gettext" description:"look for WORD as the keyword for singular strings"` KeywordPlural string `long:"keyword-plural" default:"gettext.NGettext" description:"look for WORD as the keyword for plural strings"` } func main() { // parse args args, err := flags.ParseArgs(&opts, os.Args) if err != nil { log.Fatalf("ParseArgs failed %s", err) } if err := processFiles(args[1:]); err != nil { log.Fatalf("processFiles failed with: %s", err) } out := os.Stdout if opts.Output != "" { var err error out, err = os.Create(opts.Output) if err != nil { log.Fatalf("failed to create %s: %s", opts.Output, err) } } writePotFile(out) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/gettext_test.go���������������������������������������0000644�0610621�0607500�00000003273�13172163413�025343� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package gettext import ( "os" "testing" "github.com/stretchr/testify/assert" ) const ( spanishMexico = "es_MX.utf8" deutschDeutschland = "de_DE.utf8" frenchFrance = "fr_FR.utf8" ) // a setUp would be nice func init() { textDomain := "example" BindTextdomain(textDomain, "_examples/") Textdomain(textDomain) } func TestSpanish(t *testing.T) { os.Setenv("LANGUAGE", spanishMexico) SetLocale(LcAll, "") assert.Equal(t, "¡Hola mundo!", Gettext("Hello, world!")) assert.Equal(t, "Una manzana", Sprintf(NGettext("An apple", "%d apples", 1), 1, "garbage")) assert.Equal(t, "3 manzanas", Sprintf(NGettext("An apple", "%d apples", 3), 3)) assert.Equal(t, "Buenos días", Gettext("Good morning")) assert.Equal(t, "¡Hasta luego!", Gettext("Good bye!")) } func TestDeutsch(t *testing.T) { os.Setenv("LANGUAGE", deutschDeutschland) SetLocale(LcAll, "") assert.Equal(t, "Hallo, Welt!", Gettext("Hello, world!")) assert.Equal(t, "Ein Apfel", Sprintf(NGettext("An apple", "%d apples", 1), 1, "garbage")) assert.Equal(t, "3 Äpfel", Sprintf(NGettext("An apple", "%d apples", 3), 3)) assert.Equal(t, "Guten morgen", Gettext("Good morning")) assert.Equal(t, "Auf Wiedersehen!", Gettext("Good bye!")) } func TestFrench(t *testing.T) { // Note that we don't have a french translation. os.Setenv("LANGUAGE", frenchFrance) SetLocale(LcAll, "") assert.Equal(t, "Hello, world!", Gettext("Hello, world!")) assert.Equal(t, "An apple", Sprintf(NGettext("An apple", "%d apples", 1), 1, "garbage")) assert.Equal(t, "3 apples", Sprintf(NGettext("An apple", "%d apples", 3), 3)) assert.Equal(t, "Good morning", Gettext("Good morning")) assert.Equal(t, "Good bye!", Gettext("Good bye!")) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/gettext.go��������������������������������������������0000644�0610621�0607500�00000015231�13172163413�024301� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright (c) 2012-2016 José Carlos Nieto, https://menteslibres.net/xiam // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // Package gettext provides bindings for GNU Gettext. package gettext /* // #cgo LDFLAGS: -lintl // Use this if: /usr/bin/ld: cannot find -lintl, see https://github.com/gosexy/gettext/issues/1 #include <libintl.h> #include <locale.h> #include <stdlib.h> */ import "C" import ( "fmt" "strings" "unsafe" ) var ( // LcAll is for all of the locale. LcAll = uint(C.LC_ALL) // LcCollate is for regular expression matching (it determines the meaning of // range expressions and equivalence classes) and string collation. LcCollate = uint(C.LC_COLLATE) // LcCtype is for regular expression matching, character classification, // conversion, case-sensitive comparison, and wide character functions. LcCtype = uint(C.LC_CTYPE) // LcMessages is for localizable natural-language messages. LcMessages = uint(C.LC_MESSAGES) // LcMonetary is for monetary formatting. LcMonetary = uint(C.LC_MONETARY) // LcNumeric is for number formatting (such as the decimal point and the // thousands separator). LcNumeric = uint(C.LC_NUMERIC) // LcTime is for time and date formatting. LcTime = uint(C.LC_TIME) ) // Deprecated but kept for backwards compatibility. var ( LC_ALL = LcAll LC_COLLATE = LcCollate LC_CTYPE = LcCtype LC_MESSAGES = LcMessages LC_MONETARY = LcMonetary LC_NUMERIC = LcNumeric LC_TIME = LcTime ) // SetLocale sets the program's current locale. func SetLocale(category uint, locale string) string { clocale := C.CString(locale) defer C.free(unsafe.Pointer(clocale)) return C.GoString(C.setlocale(C.int(category), clocale)) } // BindTextdomain sets the directory containing message catalogs. func BindTextdomain(domainname string, dirname string) string { cdirname := C.CString(dirname) defer C.free(unsafe.Pointer(cdirname)) cdomainname := C.CString(domainname) defer C.free(unsafe.Pointer(cdomainname)) return C.GoString(C.bindtextdomain(cdomainname, cdirname)) } // BindTextdomainCodeset sets the output codeset for message catalogs on the // given domainname. func BindTextdomainCodeset(domainname string, codeset string) string { cdomainname := C.CString(domainname) defer C.free(unsafe.Pointer(cdomainname)) ccodeset := C.CString(codeset) defer C.free(unsafe.Pointer(ccodeset)) return C.GoString(C.bind_textdomain_codeset(cdomainname, ccodeset)) } // Textdomain sets or retrieves the current message domain. func Textdomain(domainname string) string { cdomainname := C.CString(domainname) defer C.free(unsafe.Pointer(cdomainname)) return C.GoString(C.textdomain(cdomainname)) } // Gettext attempts to translate a text string into the user's system language, // by looking up the translation in a message catalog. func Gettext(msgid string) string { cmsgid := C.CString(msgid) defer C.free(unsafe.Pointer(cmsgid)) return C.GoString(C.gettext(cmsgid)) } // DGettext is like Gettext(), but looks up the message in the specified // domain. func DGettext(domain string, msgid string) string { cdomain := cDomainName(domain) defer C.free(unsafe.Pointer(cdomain)) cmsgid := C.CString(msgid) defer C.free(unsafe.Pointer(cmsgid)) return C.GoString(C.dgettext(cdomain, cmsgid)) } // DCGettext is like Gettext(), but looks up the message in the specified // domain and category. func DCGettext(domain string, msgid string, category uint) string { cdomain := cDomainName(domain) defer C.free(unsafe.Pointer(cdomain)) cmsgid := C.CString(msgid) defer C.free(unsafe.Pointer(cmsgid)) return C.GoString(C.dcgettext(cdomain, cmsgid, C.int(category))) } // NGettext attempts to translate a text string into the user's system // language, by looking up the appropriate plural form of the translation in a // message catalog. func NGettext(msgid string, msgidPlural string, n uint64) string { cmsgid := C.CString(msgid) defer C.free(unsafe.Pointer(cmsgid)) cmsgidPlural := C.CString(msgidPlural) defer C.free(unsafe.Pointer(cmsgidPlural)) return C.GoString(C.ngettext(cmsgid, cmsgidPlural, C.ulong(n))) } // Sprintf is like fmt.Sprintf() but without %!(EXTRA) errors. func Sprintf(format string, a ...interface{}) string { expects := strings.Count(format, "%") - strings.Count(format, "%%") if expects > 0 { arguments := make([]interface{}, expects) for i := 0; i < expects; i++ { if len(a) > i { arguments[i] = a[i] } } return fmt.Sprintf(format, arguments...) } return format } // DNGettext is like NGettext(), but looks up the message in the specified // domain. func DNGettext(domainname string, msgid string, msgidPlural string, n uint64) string { cdomainname := cDomainName(domainname) cmsgid := C.CString(msgid) cmsgidPlural := C.CString(msgidPlural) defer func() { C.free(unsafe.Pointer(cdomainname)) C.free(unsafe.Pointer(cmsgid)) C.free(unsafe.Pointer(cmsgidPlural)) }() return C.GoString(C.dngettext(cdomainname, cmsgid, cmsgidPlural, C.ulong(n))) } // DCNGettext is like NGettext(), but looks up the message in the specified // domain and category. func DCNGettext(domainname string, msgid string, msgidPlural string, n uint64, category uint) string { cdomainname := cDomainName(domainname) cmsgid := C.CString(msgid) cmsgidPlural := C.CString(msgidPlural) defer func() { C.free(unsafe.Pointer(cdomainname)) C.free(unsafe.Pointer(cmsgid)) C.free(unsafe.Pointer(cmsgidPlural)) }() return C.GoString(C.dcngettext(cdomainname, cmsgid, cmsgidPlural, C.ulong(n), C.int(category))) } // cDomainName returns the domain name CString that can be nil. func cDomainName(domain string) *C.char { if domain == "" { return nil } // The caller is responsible for freeing this up. return C.CString(domain) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/��������������������������������������������0000755�0610621�0607500�00000000000�13172163413�024241� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/gettext.go����������������������������������0000644�0610621�0607500�00000000667�13172163413�026265� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "github.com/gosexy/gettext" ) func main() { gettext.BindTextdomain("example", "./") gettext.Textdomain("example") gettext.SetLocale(gettext.LcAll, "es_MX.utf8") fmt.Println(gettext.Gettext("Hello, world!")) gettext.SetLocale(gettext.LcAll, "de_DE.utf8") fmt.Println(gettext.Gettext("Hello, world!")) gettext.SetLocale(gettext.LcAll, "en_US.utf8") fmt.Println(gettext.Gettext("Hello, world!")) } �������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/es_MX.utf8/���������������������������������0000755�0610621�0607500�00000000000�13172163413�026141� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/es_MX.utf8/example.pot����������������������0000644�0610621�0607500�00000002074�13172163413�030323� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2012-10-06 15:47-0500\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" #: gettext_test.go:32 gettext_test.go:40 #, c-format msgid "An apple" msgid_plural "%d apples" msgstr[0] "Una manzana" msgstr[1] "%d manzanas" #: gettext_test.go:56 msgid "Good bye!" msgstr "¡Hasta luego!" #: gettext_test.go:48 msgid "Good morning" msgstr "Buenos días" #: gettext_test.go:24 msgid "Hello, world!" msgstr "¡Hola mundo!" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/es_MX.utf8/LC_MESSAGES/���������������������0000755�0610621�0607500�00000000000�13172163413�027726� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/es_MX.utf8/LC_MESSAGES/example.mo�����������0000644�0610621�0607500�00000001146�13172163413�031720� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Þ•����������D������l�������ˆ������‰��� ���œ��� ���¦��� ���³���b��Á������$�����<�� ���K�� ���X��������������������������An apple�%d apples�Good bye!�Good morning�Hello, world!�Project-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: POT-Creation-Date: 2012-10-06 15:47-0500 PO-Revision-Date: 2012-10-06 15:48-0500 Last-Translator: <xiam@menteslibres.org> Language-Team: Spanish Language: es_MX MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); �Una manzana�%d manzanas�¡Hasta luego!�Buenos días�¡Hola mundo!���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/de_DE.utf8/���������������������������������0000755�0610621�0607500�00000000000�13172163413�026066� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/de_DE.utf8/example.pot����������������������0000644�0610621�0607500�00000002071�13172163413�030245� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2012-10-06 15:47-0500\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" #: gettext_test.go:32 gettext_test.go:40 #, c-format msgid "An apple" msgid_plural "%d apples" msgstr[0] "Ein Apfel" msgstr[1] "%d Äpfel" #: gettext_test.go:56 msgid "Good bye!" msgstr "Auf Wiedersehen!" #: gettext_test.go:48 msgid "Good morning" msgstr "Guten morgen" #: gettext_test.go:24 msgid "Hello, world!" msgstr "Hallo, Welt!" �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/de_DE.utf8/LC_MESSAGES/���������������������0000755�0610621�0607500�00000000000�13172163413�027653� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/_examples/de_DE.utf8/LC_MESSAGES/example.mo�����������0000644�0610621�0607500�00000001146�13172163413�031645� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Þ•����������D������l�������ˆ������‰��� ���œ��� ���¦��� ���³���e��Á������'�����;�� ���L�� ���Y��������������������������An apple�%d apples�Good bye!�Good morning�Hello, world!�Project-Id-Version: de_DE.utf 8 Report-Msgid-Bugs-To: POT-Creation-Date: 2012-10-06 15:47-0500 PO-Revision-Date: 2016-02-20 07:28-0600 Last-Translator: Carlos Reventlov <user@example.com> Language-Team: German Language: de MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); �Ein Apfel�%d Äpfel�Auf Wiedersehen!�Guten morgen�Hallo, Welt!���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/README.md���������������������������������������������0000644�0610621�0607500�00000004277�13172163413�023555� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������[![Build Status][travis-image]][travis-url] # gosexy/gettext Go bindings for [GNU gettext][1], an internationalization and localization library for writing multilingual systems. ## Requeriments * [GNU gettext][1] ### Linux Installation should be straightforward on Linux. ### OSX Installing gettext on a Mac is a bit awkward: ``` brew install gettext export CGO_LDFLAGS=-L/usr/local/opt/gettext/lib export CGO_CPPFLAGS=-I/usr/local/opt/gettext/include go get github.com/gosexy/gettext ``` ## Getting the library Use `go get` to download and install the binding: ```sh go get github.com/gosexy/gettext ``` ## Usage This is an example program showing the `BindTextdomain`, `Textdomain` and `SetLocale` bindings: ```go package main import ( "fmt" "github.com/gosexy/gettext" ) func main() { textDomain := "default" gettext.BindTextdomain(textDomain, "path/to/domains") gettext.Textdomain(textDomain) gettext.SetLocale(gettext.LcAll, "es_MX.utf8") fmt.Println(gettext.Gettext("Hello, world!")) } ``` Set the `LANGUAGE` env to the name of the language you want to use in your program: ```sh export LANGUAGE="es_MX.utf8" ./myapp ``` You can use the `xgettext` command to extract strings to be translated from a Go program: ``` go get github.com/gosexy/gettext/go-xgettext go-xgettext -o outfile.pot --keyword=Gettext --keyword-plural=NGettext infile.go ``` This will generate a `example.pot` file. After actually translating the `.pot` file, you'll have to generate `.po` and `.mo` files with `msginit` and `msgfmt`: ```sh msginit -l es_MX -o example.po -i example.pot msgfmt -c -v -o example.mo example.po ``` Finally, move the `.mo` file to an appropriate location. ```sh mv example.mo examples/es_MX.utf8/LC_MESSAGES/example.mo ``` ## Documentation Check out the API documentation [godoc.org/github.com/gosexy/gettext)](http://godoc.org/github.com/gosexy/gettext). The original gettext documentation: ```sh man 3 gettext ``` And here's a [good tutorial][2] on using gettext. [1]: http://www.gnu.org/software/gettext/ [2]: http://oriya.sarovar.org/docs/gettext_single.html [travis-image]: https://travis-ci.org/gosexy/gettext.svg?branch=master [travis-url]: https://travis-ci.org/gosexy/gettext ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/LICENSE�����������������������������������������������0000644�0610621�0607500�00000002112�13172163413�023265� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2012-2016 José Carlos Nieto, https://menteslibres.net/xiam Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gosexy/gettext/.travis.yml�������������������������������������������0000644�0610621�0607500�00000000114�13172163413�024371� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go install: - go get -t -v ./... script: - go test -v ./... ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163410�022121� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/��������������������������������������������0000755�0610621�0607500�00000000000�13172163411�024342� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/tree_test.go��������������������������������0000644�0610621�0607500�00000040671�13172163411�026677� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. package httprouter import ( "fmt" "net/http" "reflect" "regexp" "strings" "testing" ) func printChildren(n *node, prefix string) { fmt.Printf(" %02d:%02d %s%s[%d] %v %t %d \r\n", n.priority, n.maxParams, prefix, n.path, len(n.children), n.handle, n.wildChild, n.nType) for l := len(n.path); l > 0; l-- { prefix += " " } for _, child := range n.children { printChildren(child, prefix) } } // Used as a workaround since we can't compare functions or their addresses var fakeHandlerValue string func fakeHandler(val string) Handle { return func(http.ResponseWriter, *http.Request, Params) { fakeHandlerValue = val } } type testRequests []struct { path string nilHandler bool route string ps Params } func checkRequests(t *testing.T, tree *node, requests testRequests) { for _, request := range requests { handler, ps, _ := tree.getValue(request.path) if handler == nil { if !request.nilHandler { t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path) } } else if request.nilHandler { t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path) } else { handler(nil, nil, nil) if fakeHandlerValue != request.route { t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route) } } if !reflect.DeepEqual(ps, request.ps) { t.Errorf("Params mismatch for route '%s'", request.path) } } } func checkPriorities(t *testing.T, n *node) uint32 { var prio uint32 for i := range n.children { prio += checkPriorities(t, n.children[i]) } if n.handle != nil { prio++ } if n.priority != prio { t.Errorf( "priority mismatch for node '%s': is %d, should be %d", n.path, n.priority, prio, ) } return prio } func checkMaxParams(t *testing.T, n *node) uint8 { var maxParams uint8 for i := range n.children { params := checkMaxParams(t, n.children[i]) if params > maxParams { maxParams = params } } if n.nType > root && !n.wildChild { maxParams++ } if n.maxParams != maxParams { t.Errorf( "maxParams mismatch for node '%s': is %d, should be %d", n.path, n.maxParams, maxParams, ) } return maxParams } func TestCountParams(t *testing.T) { if countParams("/path/:param1/static/*catch-all") != 2 { t.Fail() } if countParams(strings.Repeat("/:param", 256)) != 255 { t.Fail() } } func TestTreeAddAndGet(t *testing.T) { tree := &node{} routes := [...]string{ "/hi", "/contact", "/co", "/c", "/a", "/ab", "/doc/", "/doc/go_faq.html", "/doc/go1.html", "/α", "/β", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } //printChildren(tree, "") checkRequests(t, tree, testRequests{ {"/a", false, "/a", nil}, {"/", true, "", nil}, {"/hi", false, "/hi", nil}, {"/contact", false, "/contact", nil}, {"/co", false, "/co", nil}, {"/con", true, "", nil}, // key mismatch {"/cona", true, "", nil}, // key mismatch {"/no", true, "", nil}, // no matching child {"/ab", false, "/ab", nil}, {"/α", false, "/α", nil}, {"/β", false, "/β", nil}, }) checkPriorities(t, tree) checkMaxParams(t, tree) } func TestTreeWildcard(t *testing.T) { tree := &node{} routes := [...]string{ "/", "/cmd/:tool/:sub", "/cmd/:tool/", "/src/*filepath", "/search/", "/search/:query", "/user_:name", "/user_:name/about", "/files/:dir/*filepath", "/doc/", "/doc/go_faq.html", "/doc/go1.html", "/info/:user/public", "/info/:user/project/:project", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } //printChildren(tree, "") checkRequests(t, tree, testRequests{ {"/", false, "/", nil}, {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}}, {"/cmd/test", true, "", Params{Param{"tool", "test"}}}, {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{"tool", "test"}, Param{"sub", "3"}}}, {"/src/", false, "/src/*filepath", Params{Param{"filepath", "/"}}}, {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}}, {"/search/", false, "/search/", nil}, {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}}, {"/user_gopher/about", false, "/user_:name/about", Params{Param{"name", "gopher"}}}, {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{"dir", "js"}, Param{"filepath", "/inc/framework.js"}}}, {"/info/gordon/public", false, "/info/:user/public", Params{Param{"user", "gordon"}}}, {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}}, }) checkPriorities(t, tree) checkMaxParams(t, tree) } func catchPanic(testFunc func()) (recv interface{}) { defer func() { recv = recover() }() testFunc() return } type testRoute struct { path string conflict bool } func testRoutes(t *testing.T, routes []testRoute) { tree := &node{} for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route.path, nil) }) if route.conflict { if recv == nil { t.Errorf("no panic for conflicting route '%s'", route.path) } } else if recv != nil { t.Errorf("unexpected panic for route '%s': %v", route.path, recv) } } //printChildren(tree, "") } func TestTreeWildcardConflict(t *testing.T) { routes := []testRoute{ {"/cmd/:tool/:sub", false}, {"/cmd/vet", true}, {"/src/*filepath", false}, {"/src/*filepathx", true}, {"/src/", true}, {"/src1/", false}, {"/src1/*filepath", true}, {"/src2*filepath", true}, {"/search/:query", false}, {"/search/invalid", true}, {"/user_:name", false}, {"/user_x", true}, {"/user_:name", false}, {"/id:id", false}, {"/id/:id", true}, } testRoutes(t, routes) } func TestTreeChildConflict(t *testing.T) { routes := []testRoute{ {"/cmd/vet", false}, {"/cmd/:tool/:sub", true}, {"/src/AUTHORS", false}, {"/src/*filepath", true}, {"/user_x", false}, {"/user_:name", true}, {"/id/:id", false}, {"/id:id", true}, {"/:id", true}, {"/*filepath", true}, } testRoutes(t, routes) } func TestTreeDupliatePath(t *testing.T) { tree := &node{} routes := [...]string{ "/", "/doc/", "/src/*filepath", "/search/:query", "/user_:name", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } // Add again recv = catchPanic(func() { tree.addRoute(route, nil) }) if recv == nil { t.Fatalf("no panic while inserting duplicate route '%s", route) } } //printChildren(tree, "") checkRequests(t, tree, testRequests{ {"/", false, "/", nil}, {"/doc/", false, "/doc/", nil}, {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}}, {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}}, }) } func TestEmptyWildcardName(t *testing.T) { tree := &node{} routes := [...]string{ "/user:", "/user:/", "/cmd/:/", "/src/*", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, nil) }) if recv == nil { t.Fatalf("no panic while inserting route with empty wildcard name '%s", route) } } } func TestTreeCatchAllConflict(t *testing.T) { routes := []testRoute{ {"/src/*filepath/x", true}, {"/src2/", false}, {"/src2/*filepath/x", true}, } testRoutes(t, routes) } func TestTreeCatchAllConflictRoot(t *testing.T) { routes := []testRoute{ {"/", false}, {"/*filepath", true}, } testRoutes(t, routes) } func TestTreeDoubleWildcard(t *testing.T) { const panicMsg = "only one wildcard per path segment is allowed" routes := [...]string{ "/:foo:bar", "/:foo:bar/", "/:foo*bar", } for _, route := range routes { tree := &node{} recv := catchPanic(func() { tree.addRoute(route, nil) }) if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) { t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv) } } } /*func TestTreeDuplicateWildcard(t *testing.T) { tree := &node{} routes := [...]string{ "/:id/:name/:id", } for _, route := range routes { ... } }*/ func TestTreeTrailingSlashRedirect(t *testing.T) { tree := &node{} routes := [...]string{ "/hi", "/b/", "/search/:query", "/cmd/:tool/", "/src/*filepath", "/x", "/x/y", "/y/", "/y/z", "/0/:id", "/0/:id/1", "/1/:id/", "/1/:id/2", "/aa", "/a/", "/admin", "/admin/:category", "/admin/:category/:page", "/doc", "/doc/go_faq.html", "/doc/go1.html", "/no/a", "/no/b", "/api/hello/:name", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } } //printChildren(tree, "") tsrRoutes := [...]string{ "/hi/", "/b", "/search/gopher/", "/cmd/vet", "/src", "/x/", "/y", "/0/go/", "/1/go", "/a", "/admin/", "/admin/config/", "/admin/config/permissions/", "/doc/", } for _, route := range tsrRoutes { handler, _, tsr := tree.getValue(route) if handler != nil { t.Fatalf("non-nil handler for TSR route '%s", route) } else if !tsr { t.Errorf("expected TSR recommendation for route '%s'", route) } } noTsrRoutes := [...]string{ "/", "/no", "/no/", "/_", "/_/", "/api/world/abc", } for _, route := range noTsrRoutes { handler, _, tsr := tree.getValue(route) if handler != nil { t.Fatalf("non-nil handler for No-TSR route '%s", route) } else if tsr { t.Errorf("expected no TSR recommendation for route '%s'", route) } } } func TestTreeRootTrailingSlashRedirect(t *testing.T) { tree := &node{} recv := catchPanic(func() { tree.addRoute("/:test", fakeHandler("/:test")) }) if recv != nil { t.Fatalf("panic inserting test route: %v", recv) } handler, _, tsr := tree.getValue("/") if handler != nil { t.Fatalf("non-nil handler") } else if tsr { t.Errorf("expected no TSR recommendation") } } func TestTreeFindCaseInsensitivePath(t *testing.T) { tree := &node{} routes := [...]string{ "/hi", "/b/", "/ABC/", "/search/:query", "/cmd/:tool/", "/src/*filepath", "/x", "/x/y", "/y/", "/y/z", "/0/:id", "/0/:id/1", "/1/:id/", "/1/:id/2", "/aa", "/a/", "/doc", "/doc/go_faq.html", "/doc/go1.html", "/doc/go/away", "/no/a", "/no/b", "/Π", "/u/apfêl/", "/u/äpfêl/", "/u/öpfêl", "/v/Äpfêl/", "/v/Öpfêl", "/w/♬", // 3 byte "/w/â™­/", // 3 byte, last byte differs "/w/𠜎", // 4 byte "/w/ð œ/", // 4 byte } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } } // Check out == in for all registered routes // With fixTrailingSlash = true for _, route := range routes { out, found := tree.findCaseInsensitivePath(route, true) if !found { t.Errorf("Route '%s' not found!", route) } else if string(out) != route { t.Errorf("Wrong result for route '%s': %s", route, string(out)) } } // With fixTrailingSlash = false for _, route := range routes { out, found := tree.findCaseInsensitivePath(route, false) if !found { t.Errorf("Route '%s' not found!", route) } else if string(out) != route { t.Errorf("Wrong result for route '%s': %s", route, string(out)) } } tests := []struct { in string out string found bool slash bool }{ {"/HI", "/hi", true, false}, {"/HI/", "/hi", true, true}, {"/B", "/b/", true, true}, {"/B/", "/b/", true, false}, {"/abc", "/ABC/", true, true}, {"/abc/", "/ABC/", true, false}, {"/aBc", "/ABC/", true, true}, {"/aBc/", "/ABC/", true, false}, {"/abC", "/ABC/", true, true}, {"/abC/", "/ABC/", true, false}, {"/SEARCH/QUERY", "/search/QUERY", true, false}, {"/SEARCH/QUERY/", "/search/QUERY", true, true}, {"/CMD/TOOL/", "/cmd/TOOL/", true, false}, {"/CMD/TOOL", "/cmd/TOOL/", true, true}, {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false}, {"/x/Y", "/x/y", true, false}, {"/x/Y/", "/x/y", true, true}, {"/X/y", "/x/y", true, false}, {"/X/y/", "/x/y", true, true}, {"/X/Y", "/x/y", true, false}, {"/X/Y/", "/x/y", true, true}, {"/Y/", "/y/", true, false}, {"/Y", "/y/", true, true}, {"/Y/z", "/y/z", true, false}, {"/Y/z/", "/y/z", true, true}, {"/Y/Z", "/y/z", true, false}, {"/Y/Z/", "/y/z", true, true}, {"/y/Z", "/y/z", true, false}, {"/y/Z/", "/y/z", true, true}, {"/Aa", "/aa", true, false}, {"/Aa/", "/aa", true, true}, {"/AA", "/aa", true, false}, {"/AA/", "/aa", true, true}, {"/aA", "/aa", true, false}, {"/aA/", "/aa", true, true}, {"/A/", "/a/", true, false}, {"/A", "/a/", true, true}, {"/DOC", "/doc", true, false}, {"/DOC/", "/doc", true, true}, {"/NO", "", false, true}, {"/DOC/GO", "", false, true}, {"/Ï€", "/Π", true, false}, {"/Ï€/", "/Π", true, true}, {"/u/ÄPFÊL/", "/u/äpfêl/", true, false}, {"/u/ÄPFÊL", "/u/äpfêl/", true, true}, {"/u/ÖPFÊL/", "/u/öpfêl", true, true}, {"/u/ÖPFÊL", "/u/öpfêl", true, false}, {"/v/äpfêL/", "/v/Äpfêl/", true, false}, {"/v/äpfêL", "/v/Äpfêl/", true, true}, {"/v/öpfêL/", "/v/Öpfêl", true, true}, {"/v/öpfêL", "/v/Öpfêl", true, false}, {"/w/♬/", "/w/♬", true, true}, {"/w/â™­", "/w/â™­/", true, true}, {"/w/𠜎/", "/w/𠜎", true, true}, {"/w/ð œ", "/w/ð œ/", true, true}, } // With fixTrailingSlash = true for _, test := range tests { out, found := tree.findCaseInsensitivePath(test.in, true) if found != test.found || (found && (string(out) != test.out)) { t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t", test.in, string(out), found, test.out, test.found) return } } // With fixTrailingSlash = false for _, test := range tests { out, found := tree.findCaseInsensitivePath(test.in, false) if test.slash { if found { // test needs a trailingSlash fix. It must not be found! t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out)) } } else { if found != test.found || (found && (string(out) != test.out)) { t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t", test.in, string(out), found, test.out, test.found) return } } } } func TestTreeInvalidNodeType(t *testing.T) { const panicMsg = "invalid node type" tree := &node{} tree.addRoute("/", fakeHandler("/")) tree.addRoute("/:page", fakeHandler("/:page")) // set invalid node type tree.children[0].nType = 42 // normal lookup recv := catchPanic(func() { tree.getValue("/test") }) if rs, ok := recv.(string); !ok || rs != panicMsg { t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv) } // case-insensitive lookup recv = catchPanic(func() { tree.findCaseInsensitivePath("/test", true) }) if rs, ok := recv.(string); !ok || rs != panicMsg { t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv) } } func TestTreeWildcardConflictEx(t *testing.T) { conflicts := [...]struct { route string segPath string existPath string existSegPath string }{ {"/who/are/foo", "/foo", `/who/are/\*you`, `/\*you`}, {"/who/are/foo/", "/foo/", `/who/are/\*you`, `/\*you`}, {"/who/are/foo/bar", "/foo/bar", `/who/are/\*you`, `/\*you`}, {"/conxxx", "xxx", `/con:tact`, `:tact`}, {"/conooo/xxx", "ooo", `/con:tact`, `:tact`}, } for _, conflict := range conflicts { // I have to re-create a 'tree', because the 'tree' will be // in an inconsistent state when the loop recovers from the // panic which threw by 'addRoute' function. tree := &node{} routes := [...]string{ "/con:tact", "/who/are/*you", "/who/foo/hello", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } recv := catchPanic(func() { tree.addRoute(conflict.route, fakeHandler(conflict.route)) }) if !regexp.MustCompile(fmt.Sprintf("'%s' in new path .* conflicts with existing wildcard '%s' in existing prefix '%s'", conflict.segPath, conflict.existSegPath, conflict.existPath)).MatchString(fmt.Sprint(recv)) { t.Fatalf("invalid wildcard conflict error (%v)", recv) } } } �����������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/tree.go�������������������������������������0000644�0610621�0607500�00000040223�13172163411�025631� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. package httprouter import ( "strings" "unicode" "unicode/utf8" ) func min(a, b int) int { if a <= b { return a } return b } func countParams(path string) uint8 { var n uint for i := 0; i < len(path); i++ { if path[i] != ':' && path[i] != '*' { continue } n++ } if n >= 255 { return 255 } return uint8(n) } type nodeType uint8 const ( static nodeType = iota // default root param catchAll ) type node struct { path string wildChild bool nType nodeType maxParams uint8 indices string children []*node handle Handle priority uint32 } // increments priority of the given child and reorders if necessary func (n *node) incrementChildPrio(pos int) int { n.children[pos].priority++ prio := n.children[pos].priority // adjust position (move to front) newPos := pos for newPos > 0 && n.children[newPos-1].priority < prio { // swap node positions n.children[newPos-1], n.children[newPos] = n.children[newPos], n.children[newPos-1] newPos-- } // build new index char string if newPos != pos { n.indices = n.indices[:newPos] + // unchanged prefix, might be empty n.indices[pos:pos+1] + // the index char we move n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos' } return newPos } // addRoute adds a node with the given handle to the path. // Not concurrency-safe! func (n *node) addRoute(path string, handle Handle) { fullPath := path n.priority++ numParams := countParams(path) // non-empty tree if len(n.path) > 0 || len(n.children) > 0 { walk: for { // Update maxParams of the current node if numParams > n.maxParams { n.maxParams = numParams } // Find the longest common prefix. // This also implies that the common prefix contains no ':' or '*' // since the existing key can't contain those chars. i := 0 max := min(len(path), len(n.path)) for i < max && path[i] == n.path[i] { i++ } // Split edge if i < len(n.path) { child := node{ path: n.path[i:], wildChild: n.wildChild, nType: static, indices: n.indices, children: n.children, handle: n.handle, priority: n.priority - 1, } // Update maxParams (max of all children) for i := range child.children { if child.children[i].maxParams > child.maxParams { child.maxParams = child.children[i].maxParams } } n.children = []*node{&child} // []byte for proper unicode char conversion, see #65 n.indices = string([]byte{n.path[i]}) n.path = path[:i] n.handle = nil n.wildChild = false } // Make new node a child of this node if i < len(path) { path = path[i:] if n.wildChild { n = n.children[0] n.priority++ // Update maxParams of the child node if numParams > n.maxParams { n.maxParams = numParams } numParams-- // Check if the wildcard matches if len(path) >= len(n.path) && n.path == path[:len(n.path)] && // Check for longer wildcard, e.g. :name and :names (len(n.path) >= len(path) || path[len(n.path)] == '/') { continue walk } else { // Wildcard conflict var pathSeg string if n.nType == catchAll { pathSeg = path } else { pathSeg = strings.SplitN(path, "/", 2)[0] } prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path panic("'" + pathSeg + "' in new path '" + fullPath + "' conflicts with existing wildcard '" + n.path + "' in existing prefix '" + prefix + "'") } } c := path[0] // slash after param if n.nType == param && c == '/' && len(n.children) == 1 { n = n.children[0] n.priority++ continue walk } // Check if a child with the next path byte exists for i := 0; i < len(n.indices); i++ { if c == n.indices[i] { i = n.incrementChildPrio(i) n = n.children[i] continue walk } } // Otherwise insert it if c != ':' && c != '*' { // []byte for proper unicode char conversion, see #65 n.indices += string([]byte{c}) child := &node{ maxParams: numParams, } n.children = append(n.children, child) n.incrementChildPrio(len(n.indices) - 1) n = child } n.insertChild(numParams, path, fullPath, handle) return } else if i == len(path) { // Make node a (in-path) leaf if n.handle != nil { panic("a handle is already registered for path '" + fullPath + "'") } n.handle = handle } return } } else { // Empty tree n.insertChild(numParams, path, fullPath, handle) n.nType = root } } func (n *node) insertChild(numParams uint8, path, fullPath string, handle Handle) { var offset int // already handled bytes of the path // find prefix until first wildcard (beginning with ':'' or '*'') for i, max := 0, len(path); numParams > 0; i++ { c := path[i] if c != ':' && c != '*' { continue } // find wildcard end (either '/' or path end) end := i + 1 for end < max && path[end] != '/' { switch path[end] { // the wildcard name must not contain ':' and '*' case ':', '*': panic("only one wildcard per path segment is allowed, has: '" + path[i:] + "' in path '" + fullPath + "'") default: end++ } } // check if this Node existing children which would be // unreachable if we insert the wildcard here if len(n.children) > 0 { panic("wildcard route '" + path[i:end] + "' conflicts with existing children in path '" + fullPath + "'") } // check if the wildcard has a name if end-i < 2 { panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") } if c == ':' { // param // split path at the beginning of the wildcard if i > 0 { n.path = path[offset:i] offset = i } child := &node{ nType: param, maxParams: numParams, } n.children = []*node{child} n.wildChild = true n = child n.priority++ numParams-- // if the path doesn't end with the wildcard, then there // will be another non-wildcard subpath starting with '/' if end < max { n.path = path[offset:end] offset = end child := &node{ maxParams: numParams, priority: 1, } n.children = []*node{child} n = child } } else { // catchAll if end != max || numParams > 1 { panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") } if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'") } // currently fixed width 1 for '/' i-- if path[i] != '/' { panic("no / before catch-all in path '" + fullPath + "'") } n.path = path[offset:i] // first node: catchAll node with empty path child := &node{ wildChild: true, nType: catchAll, maxParams: 1, } n.children = []*node{child} n.indices = string(path[i]) n = child n.priority++ // second node: node holding the variable child = &node{ path: path[i:], nType: catchAll, maxParams: 1, handle: handle, priority: 1, } n.children = []*node{child} return } } // insert remaining path part and handle to the leaf n.path = path[offset:] n.handle = handle } // Returns the handle registered with the given path (key). The values of // wildcards are saved to a map. // If no handle can be found, a TSR (trailing slash redirect) recommendation is // made if a handle exists with an extra (without the) trailing slash for the // given path. func (n *node) getValue(path string) (handle Handle, p Params, tsr bool) { walk: // outer loop for walking the tree for { if len(path) > len(n.path) { if path[:len(n.path)] == n.path { path = path[len(n.path):] // If this node does not have a wildcard (param or catchAll) // child, we can just look up the next child node and continue // to walk down the tree if !n.wildChild { c := path[0] for i := 0; i < len(n.indices); i++ { if c == n.indices[i] { n = n.children[i] continue walk } } // Nothing found. // We can recommend to redirect to the same URL without a // trailing slash if a leaf exists for that path. tsr = (path == "/" && n.handle != nil) return } // handle wildcard child n = n.children[0] switch n.nType { case param: // find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // save param value if p == nil { // lazy allocation p = make(Params, 0, n.maxParams) } i := len(p) p = p[:i+1] // expand slice within preallocated capacity p[i].Key = n.path[1:] p[i].Value = path[:end] // we need to go deeper! if end < len(path) { if len(n.children) > 0 { path = path[end:] n = n.children[0] continue walk } // ... but we can't tsr = (len(path) == end+1) return } if handle = n.handle; handle != nil { return } else if len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists for TSR recommendation n = n.children[0] tsr = (n.path == "/" && n.handle != nil) } return case catchAll: // save param value if p == nil { // lazy allocation p = make(Params, 0, n.maxParams) } i := len(p) p = p[:i+1] // expand slice within preallocated capacity p[i].Key = n.path[2:] p[i].Value = path handle = n.handle return default: panic("invalid node type") } } } else if path == n.path { // We should have reached the node containing the handle. // Check if this node has a handle registered. if handle = n.handle; handle != nil { return } if path == "/" && n.wildChild && n.nType != root { tsr = true return } // No handle found. Check if a handle for this path + a // trailing slash exists for trailing slash recommendation for i := 0; i < len(n.indices); i++ { if n.indices[i] == '/' { n = n.children[i] tsr = (len(n.path) == 1 && n.handle != nil) || (n.nType == catchAll && n.children[0].handle != nil) return } } return } // Nothing found. We can recommend to redirect to the same URL with an // extra trailing slash if a leaf exists for that path tsr = (path == "/") || (len(n.path) == len(path)+1 && n.path[len(path)] == '/' && path == n.path[:len(n.path)-1] && n.handle != nil) return } } // Makes a case-insensitive lookup of the given path and tries to find a handler. // It can optionally also fix trailing slashes. // It returns the case-corrected path and a bool indicating whether the lookup // was successful. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) { return n.findCaseInsensitivePathRec( path, strings.ToLower(path), make([]byte, 0, len(path)+1), // preallocate enough memory for new path [4]byte{}, // empty rune buffer fixTrailingSlash, ) } // shift bytes in array by n bytes left func shiftNRuneBytes(rb [4]byte, n int) [4]byte { switch n { case 0: return rb case 1: return [4]byte{rb[1], rb[2], rb[3], 0} case 2: return [4]byte{rb[2], rb[3]} case 3: return [4]byte{rb[3]} default: return [4]byte{} } } // recursive case-insensitive lookup function used by n.findCaseInsensitivePath func (n *node) findCaseInsensitivePathRec(path, loPath string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) ([]byte, bool) { loNPath := strings.ToLower(n.path) walk: // outer loop for walking the tree for len(loPath) >= len(loNPath) && (len(loNPath) == 0 || loPath[1:len(loNPath)] == loNPath[1:]) { // add common path to result ciPath = append(ciPath, n.path...) if path = path[len(n.path):]; len(path) > 0 { loOld := loPath loPath = loPath[len(loNPath):] // If this node does not have a wildcard (param or catchAll) child, // we can just look up the next child node and continue to walk down // the tree if !n.wildChild { // skip rune bytes already processed rb = shiftNRuneBytes(rb, len(loNPath)) if rb[0] != 0 { // old rune not finished for i := 0; i < len(n.indices); i++ { if n.indices[i] == rb[0] { // continue with child node n = n.children[i] loNPath = strings.ToLower(n.path) continue walk } } } else { // process a new rune var rv rune // find rune start // runes are up to 4 byte long, // -4 would definitely be another rune var off int for max := min(len(loNPath), 3); off < max; off++ { if i := len(loNPath) - off; utf8.RuneStart(loOld[i]) { // read rune from cached lowercase path rv, _ = utf8.DecodeRuneInString(loOld[i:]) break } } // calculate lowercase bytes of current rune utf8.EncodeRune(rb[:], rv) // skipp already processed bytes rb = shiftNRuneBytes(rb, off) for i := 0; i < len(n.indices); i++ { // lowercase matches if n.indices[i] == rb[0] { // must use a recursive approach since both the // uppercase byte and the lowercase byte might exist // as an index if out, found := n.children[i].findCaseInsensitivePathRec( path, loPath, ciPath, rb, fixTrailingSlash, ); found { return out, true } break } } // same for uppercase rune, if it differs if up := unicode.ToUpper(rv); up != rv { utf8.EncodeRune(rb[:], up) rb = shiftNRuneBytes(rb, off) for i := 0; i < len(n.indices); i++ { // uppercase matches if n.indices[i] == rb[0] { // continue with child node n = n.children[i] loNPath = strings.ToLower(n.path) continue walk } } } } // Nothing found. We can recommend to redirect to the same URL // without a trailing slash if a leaf exists for that path return ciPath, (fixTrailingSlash && path == "/" && n.handle != nil) } n = n.children[0] switch n.nType { case param: // find param end (either '/' or path end) k := 0 for k < len(path) && path[k] != '/' { k++ } // add param value to case insensitive path ciPath = append(ciPath, path[:k]...) // we need to go deeper! if k < len(path) { if len(n.children) > 0 { // continue with child node n = n.children[0] loNPath = strings.ToLower(n.path) loPath = loPath[k:] path = path[k:] continue } // ... but we can't if fixTrailingSlash && len(path) == k+1 { return ciPath, true } return ciPath, false } if n.handle != nil { return ciPath, true } else if fixTrailingSlash && len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists n = n.children[0] if n.path == "/" && n.handle != nil { return append(ciPath, '/'), true } } return ciPath, false case catchAll: return append(ciPath, path...), true default: panic("invalid node type") } } else { // We should have reached the node containing the handle. // Check if this node has a handle registered. if n.handle != nil { return ciPath, true } // No handle found. // Try to fix the path by adding a trailing slash if fixTrailingSlash { for i := 0; i < len(n.indices); i++ { if n.indices[i] == '/' { n = n.children[i] if (len(n.path) == 1 && n.handle != nil) || (n.nType == catchAll && n.children[0].handle != nil) { return append(ciPath, '/'), true } return ciPath, false } } } return ciPath, false } } // Nothing found. // Try to fix the path by adding / removing a trailing slash if fixTrailingSlash { if path == "/" { return ciPath, true } if len(loPath)+1 == len(loNPath) && loNPath[len(loPath)] == '/' && loPath[1:] == loNPath[1:len(loPath)] && n.handle != nil { return append(ciPath, n.path...), true } } return ciPath, false } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/router_test.go������������������������������0000644�0610621�0607500�00000034041�13172163411�027252� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. package httprouter import ( "errors" "fmt" "net/http" "net/http/httptest" "reflect" "testing" ) type mockResponseWriter struct{} func (m *mockResponseWriter) Header() (h http.Header) { return http.Header{} } func (m *mockResponseWriter) Write(p []byte) (n int, err error) { return len(p), nil } func (m *mockResponseWriter) WriteString(s string) (n int, err error) { return len(s), nil } func (m *mockResponseWriter) WriteHeader(int) {} func TestParams(t *testing.T) { ps := Params{ Param{"param1", "value1"}, Param{"param2", "value2"}, Param{"param3", "value3"}, } for i := range ps { if val := ps.ByName(ps[i].Key); val != ps[i].Value { t.Errorf("Wrong value for %s: Got %s; Want %s", ps[i].Key, val, ps[i].Value) } } if val := ps.ByName("noKey"); val != "" { t.Errorf("Expected empty string for not found key; got: %s", val) } } func TestRouter(t *testing.T) { router := New() routed := false router.Handle("GET", "/user/:name", func(w http.ResponseWriter, r *http.Request, ps Params) { routed = true want := Params{Param{"name", "gopher"}} if !reflect.DeepEqual(ps, want) { t.Fatalf("wrong wildcard values: want %v, got %v", want, ps) } }) w := new(mockResponseWriter) req, _ := http.NewRequest("GET", "/user/gopher", nil) router.ServeHTTP(w, req) if !routed { t.Fatal("routing failed") } } type handlerStruct struct { handled *bool } func (h handlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) { *h.handled = true } func TestRouterAPI(t *testing.T) { var get, head, options, post, put, patch, delete, handler, handlerFunc bool httpHandler := handlerStruct{&handler} router := New() router.GET("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) { get = true }) router.HEAD("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) { head = true }) router.OPTIONS("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) { options = true }) router.POST("/POST", func(w http.ResponseWriter, r *http.Request, _ Params) { post = true }) router.PUT("/PUT", func(w http.ResponseWriter, r *http.Request, _ Params) { put = true }) router.PATCH("/PATCH", func(w http.ResponseWriter, r *http.Request, _ Params) { patch = true }) router.DELETE("/DELETE", func(w http.ResponseWriter, r *http.Request, _ Params) { delete = true }) router.Handler("GET", "/Handler", httpHandler) router.HandlerFunc("GET", "/HandlerFunc", func(w http.ResponseWriter, r *http.Request) { handlerFunc = true }) w := new(mockResponseWriter) r, _ := http.NewRequest("GET", "/GET", nil) router.ServeHTTP(w, r) if !get { t.Error("routing GET failed") } r, _ = http.NewRequest("HEAD", "/GET", nil) router.ServeHTTP(w, r) if !head { t.Error("routing HEAD failed") } r, _ = http.NewRequest("OPTIONS", "/GET", nil) router.ServeHTTP(w, r) if !options { t.Error("routing OPTIONS failed") } r, _ = http.NewRequest("POST", "/POST", nil) router.ServeHTTP(w, r) if !post { t.Error("routing POST failed") } r, _ = http.NewRequest("PUT", "/PUT", nil) router.ServeHTTP(w, r) if !put { t.Error("routing PUT failed") } r, _ = http.NewRequest("PATCH", "/PATCH", nil) router.ServeHTTP(w, r) if !patch { t.Error("routing PATCH failed") } r, _ = http.NewRequest("DELETE", "/DELETE", nil) router.ServeHTTP(w, r) if !delete { t.Error("routing DELETE failed") } r, _ = http.NewRequest("GET", "/Handler", nil) router.ServeHTTP(w, r) if !handler { t.Error("routing Handler failed") } r, _ = http.NewRequest("GET", "/HandlerFunc", nil) router.ServeHTTP(w, r) if !handlerFunc { t.Error("routing HandlerFunc failed") } } func TestRouterRoot(t *testing.T) { router := New() recv := catchPanic(func() { router.GET("noSlashRoot", nil) }) if recv == nil { t.Fatal("registering path not beginning with '/' did not panic") } } func TestRouterChaining(t *testing.T) { router1 := New() router2 := New() router1.NotFound = router2 fooHit := false router1.POST("/foo", func(w http.ResponseWriter, req *http.Request, _ Params) { fooHit = true w.WriteHeader(http.StatusOK) }) barHit := false router2.POST("/bar", func(w http.ResponseWriter, req *http.Request, _ Params) { barHit = true w.WriteHeader(http.StatusOK) }) r, _ := http.NewRequest("POST", "/foo", nil) w := httptest.NewRecorder() router1.ServeHTTP(w, r) if !(w.Code == http.StatusOK && fooHit) { t.Errorf("Regular routing failed with router chaining.") t.FailNow() } r, _ = http.NewRequest("POST", "/bar", nil) w = httptest.NewRecorder() router1.ServeHTTP(w, r) if !(w.Code == http.StatusOK && barHit) { t.Errorf("Chained routing failed with router chaining.") t.FailNow() } r, _ = http.NewRequest("POST", "/qax", nil) w = httptest.NewRecorder() router1.ServeHTTP(w, r) if !(w.Code == http.StatusNotFound) { t.Errorf("NotFound behavior failed with router chaining.") t.FailNow() } } func TestRouterOPTIONS(t *testing.T) { handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {} router := New() router.POST("/path", handlerFunc) // test not allowed // * (server) r, _ := http.NewRequest("OPTIONS", "*", nil) w := httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusOK) { t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, w.Header()) } else if allow := w.Header().Get("Allow"); allow != "POST, OPTIONS" { t.Error("unexpected Allow header value: " + allow) } // path r, _ = http.NewRequest("OPTIONS", "/path", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusOK) { t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, w.Header()) } else if allow := w.Header().Get("Allow"); allow != "POST, OPTIONS" { t.Error("unexpected Allow header value: " + allow) } r, _ = http.NewRequest("OPTIONS", "/doesnotexist", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusNotFound) { t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, w.Header()) } // add another method router.GET("/path", handlerFunc) // test again // * (server) r, _ = http.NewRequest("OPTIONS", "*", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusOK) { t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, w.Header()) } else if allow := w.Header().Get("Allow"); allow != "POST, GET, OPTIONS" && allow != "GET, POST, OPTIONS" { t.Error("unexpected Allow header value: " + allow) } // path r, _ = http.NewRequest("OPTIONS", "/path", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusOK) { t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, w.Header()) } else if allow := w.Header().Get("Allow"); allow != "POST, GET, OPTIONS" && allow != "GET, POST, OPTIONS" { t.Error("unexpected Allow header value: " + allow) } // custom handler var custom bool router.OPTIONS("/path", func(w http.ResponseWriter, r *http.Request, _ Params) { custom = true }) // test again // * (server) r, _ = http.NewRequest("OPTIONS", "*", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusOK) { t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, w.Header()) } else if allow := w.Header().Get("Allow"); allow != "POST, GET, OPTIONS" && allow != "GET, POST, OPTIONS" { t.Error("unexpected Allow header value: " + allow) } if custom { t.Error("custom handler called on *") } // path r, _ = http.NewRequest("OPTIONS", "/path", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusOK) { t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, w.Header()) } if !custom { t.Error("custom handler not called") } } func TestRouterNotAllowed(t *testing.T) { handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {} router := New() router.POST("/path", handlerFunc) // test not allowed r, _ := http.NewRequest("GET", "/path", nil) w := httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusMethodNotAllowed) { t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", w.Code, w.Header()) } else if allow := w.Header().Get("Allow"); allow != "POST, OPTIONS" { t.Error("unexpected Allow header value: " + allow) } // add another method router.DELETE("/path", handlerFunc) router.OPTIONS("/path", handlerFunc) // must be ignored // test again r, _ = http.NewRequest("GET", "/path", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == http.StatusMethodNotAllowed) { t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", w.Code, w.Header()) } else if allow := w.Header().Get("Allow"); allow != "POST, DELETE, OPTIONS" && allow != "DELETE, POST, OPTIONS" { t.Error("unexpected Allow header value: " + allow) } // test custom handler w = httptest.NewRecorder() responseText := "custom method" router.MethodNotAllowed = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusTeapot) w.Write([]byte(responseText)) }) router.ServeHTTP(w, r) if got := w.Body.String(); !(got == responseText) { t.Errorf("unexpected response got %q want %q", got, responseText) } if w.Code != http.StatusTeapot { t.Errorf("unexpected response code %d want %d", w.Code, http.StatusTeapot) } if allow := w.Header().Get("Allow"); allow != "POST, DELETE, OPTIONS" && allow != "DELETE, POST, OPTIONS" { t.Error("unexpected Allow header value: " + allow) } } func TestRouterNotFound(t *testing.T) { handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {} router := New() router.GET("/path", handlerFunc) router.GET("/dir/", handlerFunc) router.GET("/", handlerFunc) testRoutes := []struct { route string code int header string }{ {"/path/", 301, "map[Location:[/path]]"}, // TSR -/ {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/ {"", 301, "map[Location:[/]]"}, // TSR +/ {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/ {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/ {"/../path", 301, "map[Location:[/path]]"}, // CleanPath {"/nope", 404, ""}, // NotFound } for _, tr := range testRoutes { r, _ := http.NewRequest("GET", tr.route, nil) w := httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == tr.code && (w.Code == 404 || fmt.Sprint(w.Header()) == tr.header)) { t.Errorf("NotFound handling route %s failed: Code=%d, Header=%v", tr.route, w.Code, w.Header()) } } // Test custom not found handler var notFound bool router.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(404) notFound = true }) r, _ := http.NewRequest("GET", "/nope", nil) w := httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == 404 && notFound == true) { t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header()) } // Test other method than GET (want 307 instead of 301) router.PATCH("/path", handlerFunc) r, _ = http.NewRequest("PATCH", "/path/", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == 307 && fmt.Sprint(w.Header()) == "map[Location:[/path]]") { t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header()) } // Test special case where no node for the prefix "/" exists router = New() router.GET("/a", handlerFunc) r, _ = http.NewRequest("GET", "/", nil) w = httptest.NewRecorder() router.ServeHTTP(w, r) if !(w.Code == 404) { t.Errorf("NotFound handling route / failed: Code=%d", w.Code) } } func TestRouterPanicHandler(t *testing.T) { router := New() panicHandled := false router.PanicHandler = func(rw http.ResponseWriter, r *http.Request, p interface{}) { panicHandled = true } router.Handle("PUT", "/user/:name", func(_ http.ResponseWriter, _ *http.Request, _ Params) { panic("oops!") }) w := new(mockResponseWriter) req, _ := http.NewRequest("PUT", "/user/gopher", nil) defer func() { if rcv := recover(); rcv != nil { t.Fatal("handling panic failed") } }() router.ServeHTTP(w, req) if !panicHandled { t.Fatal("simulating failed") } } func TestRouterLookup(t *testing.T) { routed := false wantHandle := func(_ http.ResponseWriter, _ *http.Request, _ Params) { routed = true } wantParams := Params{Param{"name", "gopher"}} router := New() // try empty router first handle, _, tsr := router.Lookup("GET", "/nope") if handle != nil { t.Fatalf("Got handle for unregistered pattern: %v", handle) } if tsr { t.Error("Got wrong TSR recommendation!") } // insert route and try again router.GET("/user/:name", wantHandle) handle, params, tsr := router.Lookup("GET", "/user/gopher") if handle == nil { t.Fatal("Got no handle!") } else { handle(nil, nil, nil) if !routed { t.Fatal("Routing failed!") } } if !reflect.DeepEqual(params, wantParams) { t.Fatalf("Wrong parameter values: want %v, got %v", wantParams, params) } handle, _, tsr = router.Lookup("GET", "/user/gopher/") if handle != nil { t.Fatalf("Got handle for unregistered pattern: %v", handle) } if !tsr { t.Error("Got no TSR recommendation!") } handle, _, tsr = router.Lookup("GET", "/nope") if handle != nil { t.Fatalf("Got handle for unregistered pattern: %v", handle) } if tsr { t.Error("Got wrong TSR recommendation!") } } type mockFileSystem struct { opened bool } func (mfs *mockFileSystem) Open(name string) (http.File, error) { mfs.opened = true return nil, errors.New("this is just a mock") } func TestRouterServeFiles(t *testing.T) { router := New() mfs := &mockFileSystem{} recv := catchPanic(func() { router.ServeFiles("/noFilepath", mfs) }) if recv == nil { t.Fatal("registering path not ending with '*filepath' did not panic") } router.ServeFiles("/*filepath", mfs) w := new(mockResponseWriter) r, _ := http.NewRequest("GET", "/favicon.ico", nil) router.ServeHTTP(w, r) if !mfs.opened { t.Error("serving file failed") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/router.go�����������������������������������0000644�0610621�0607500�00000031560�13172163411�026216� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. // Package httprouter is a trie based high performance HTTP request router. // // A trivial example is: // // package main // // import ( // "fmt" // "github.com/julienschmidt/httprouter" // "net/http" // "log" // ) // // func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { // fmt.Fprint(w, "Welcome!\n") // } // // func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) // } // // func main() { // router := httprouter.New() // router.GET("/", Index) // router.GET("/hello/:name", Hello) // // log.Fatal(http.ListenAndServe(":8080", router)) // } // // The router matches incoming requests by the request method and the path. // If a handle is registered for this path and method, the router delegates the // request to that function. // For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to // register handles, for all other methods router.Handle can be used. // // The registered path, against which the router matches incoming requests, can // contain two types of parameters: // Syntax Type // :name named parameter // *name catch-all parameter // // Named parameters are dynamic path segments. They match anything until the // next '/' or the path end: // Path: /blog/:category/:post // // Requests: // /blog/go/request-routers match: category="go", post="request-routers" // /blog/go/request-routers/ no match, but the router would redirect // /blog/go/ no match // /blog/go/request-routers/comments no match // // Catch-all parameters match anything until the path end, including the // directory index (the '/' before the catch-all). Since they match anything // until the end, catch-all parameters must always be the final path element. // Path: /files/*filepath // // Requests: // /files/ match: filepath="/" // /files/LICENSE match: filepath="/LICENSE" // /files/templates/article.html match: filepath="/templates/article.html" // /files no match, but the router would redirect // // The value of parameters is saved as a slice of the Param struct, consisting // each of a key and a value. The slice is passed to the Handle func as a third // parameter. // There are two ways to retrieve the value of a parameter: // // by the name of the parameter // user := ps.ByName("user") // defined by :user or *user // // // by the index of the parameter. This way you can also get the name (key) // thirdKey := ps[2].Key // the name of the 3rd parameter // thirdValue := ps[2].Value // the value of the 3rd parameter package httprouter import ( "net/http" ) // Handle is a function that can be registered to a route to handle HTTP // requests. Like http.HandlerFunc, but has a third parameter for the values of // wildcards (variables). type Handle func(http.ResponseWriter, *http.Request, Params) // Param is a single URL parameter, consisting of a key and a value. type Param struct { Key string Value string } // Params is a Param-slice, as returned by the router. // The slice is ordered, the first URL parameter is also the first slice value. // It is therefore safe to read values by the index. type Params []Param // ByName returns the value of the first Param which key matches the given name. // If no matching Param is found, an empty string is returned. func (ps Params) ByName(name string) string { for i := range ps { if ps[i].Key == name { return ps[i].Value } } return "" } // Router is a http.Handler which can be used to dispatch requests to different // handler functions via configurable routes type Router struct { trees map[string]*node // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS bool // Configurable http.Handler which is called when no matching route is // found. If it is not set, http.NotFound is used. NotFound http.Handler // Configurable http.Handler which is called when a request // cannot be routed and HandleMethodNotAllowed is true. // If it is not set, http.Error with http.StatusMethodNotAllowed is used. // The "Allow" header with allowed request methods is set before the handler // is called. MethodNotAllowed http.Handler // Function to handle panics recovered from http handlers. // It should be used to generate a error page and return the http error code // 500 (Internal Server Error). // The handler can be used to keep your server from crashing because of // unrecovered panics. PanicHandler func(http.ResponseWriter, *http.Request, interface{}) } // Make sure the Router conforms with the http.Handler interface var _ http.Handler = New() // New returns a new initialized Router. // Path auto-correction, including trailing slashes, is enabled by default. func New() *Router { return &Router{ RedirectTrailingSlash: true, RedirectFixedPath: true, HandleMethodNotAllowed: true, HandleOPTIONS: true, } } // GET is a shortcut for router.Handle("GET", path, handle) func (r *Router) GET(path string, handle Handle) { r.Handle("GET", path, handle) } // HEAD is a shortcut for router.Handle("HEAD", path, handle) func (r *Router) HEAD(path string, handle Handle) { r.Handle("HEAD", path, handle) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) func (r *Router) OPTIONS(path string, handle Handle) { r.Handle("OPTIONS", path, handle) } // POST is a shortcut for router.Handle("POST", path, handle) func (r *Router) POST(path string, handle Handle) { r.Handle("POST", path, handle) } // PUT is a shortcut for router.Handle("PUT", path, handle) func (r *Router) PUT(path string, handle Handle) { r.Handle("PUT", path, handle) } // PATCH is a shortcut for router.Handle("PATCH", path, handle) func (r *Router) PATCH(path string, handle Handle) { r.Handle("PATCH", path, handle) } // DELETE is a shortcut for router.Handle("DELETE", path, handle) func (r *Router) DELETE(path string, handle Handle) { r.Handle("DELETE", path, handle) } // Handle registers a new request handle with the given path and method. // // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut // functions can be used. // // This function is intended for bulk loading and to allow the usage of less // frequently used, non-standardized or custom methods (e.g. for internal // communication with a proxy). func (r *Router) Handle(method, path string, handle Handle) { if path[0] != '/' { panic("path must begin with '/' in path '" + path + "'") } if r.trees == nil { r.trees = make(map[string]*node) } root := r.trees[method] if root == nil { root = new(node) r.trees[method] = root } root.addRoute(path, handle) } // Handler is an adapter which allows the usage of an http.Handler as a // request handle. func (r *Router) Handler(method, path string, handler http.Handler) { r.Handle(method, path, func(w http.ResponseWriter, req *http.Request, _ Params) { handler.ServeHTTP(w, req) }, ) } // HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a // request handle. func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) { r.Handler(method, path, handler) } // ServeFiles serves files from the given file system root. // The path must end with "/*filepath", files are then served from the local // path /defined/root/dir/*filepath. // For example if root is "/etc" and *filepath is "passwd", the local file // "/etc/passwd" would be served. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use http.Dir: // router.ServeFiles("/src/*filepath", http.Dir("/var/www")) func (r *Router) ServeFiles(path string, root http.FileSystem) { if len(path) < 10 || path[len(path)-10:] != "/*filepath" { panic("path must end with /*filepath in path '" + path + "'") } fileServer := http.FileServer(root) r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) { req.URL.Path = ps.ByName("filepath") fileServer.ServeHTTP(w, req) }) } func (r *Router) recv(w http.ResponseWriter, req *http.Request) { if rcv := recover(); rcv != nil { r.PanicHandler(w, req, rcv) } } // Lookup allows the manual lookup of a method + path combo. // This is e.g. useful to build a framework around this router. // If the path was found, it returns the handle function and the path parameter // values. Otherwise the third return value indicates whether a redirection to // the same path with an extra / without the trailing slash should be performed. func (r *Router) Lookup(method, path string) (Handle, Params, bool) { if root := r.trees[method]; root != nil { return root.getValue(path) } return nil, nil, false } func (r *Router) allowed(path, reqMethod string) (allow string) { if path == "*" { // server-wide for method := range r.trees { if method == "OPTIONS" { continue } // add request method to list of allowed methods if len(allow) == 0 { allow = method } else { allow += ", " + method } } } else { // specific path for method := range r.trees { // Skip the requested method - we already tried this one if method == reqMethod || method == "OPTIONS" { continue } handle, _, _ := r.trees[method].getValue(path) if handle != nil { // add request method to list of allowed methods if len(allow) == 0 { allow = method } else { allow += ", " + method } } } } if len(allow) > 0 { allow += ", OPTIONS" } return } // ServeHTTP makes the router implement the http.Handler interface. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { if r.PanicHandler != nil { defer r.recv(w, req) } path := req.URL.Path if root := r.trees[req.Method]; root != nil { if handle, ps, tsr := root.getValue(path); handle != nil { handle(w, req, ps) return } else if req.Method != "CONNECT" && path != "/" { code := 301 // Permanent redirect, request with GET method if req.Method != "GET" { // Temporary redirect, request with same method // As of Go 1.3, Go does not support status code 308. code = 307 } if tsr && r.RedirectTrailingSlash { if len(path) > 1 && path[len(path)-1] == '/' { req.URL.Path = path[:len(path)-1] } else { req.URL.Path = path + "/" } http.Redirect(w, req, req.URL.String(), code) return } // Try to fix the request path if r.RedirectFixedPath { fixedPath, found := root.findCaseInsensitivePath( CleanPath(path), r.RedirectTrailingSlash, ) if found { req.URL.Path = string(fixedPath) http.Redirect(w, req, req.URL.String(), code) return } } } } if req.Method == "OPTIONS" { // Handle OPTIONS requests if r.HandleOPTIONS { if allow := r.allowed(path, req.Method); len(allow) > 0 { w.Header().Set("Allow", allow) return } } } else { // Handle 405 if r.HandleMethodNotAllowed { if allow := r.allowed(path, req.Method); len(allow) > 0 { w.Header().Set("Allow", allow) if r.MethodNotAllowed != nil { r.MethodNotAllowed.ServeHTTP(w, req) } else { http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed, ) } return } } } // Handle 404 if r.NotFound != nil { r.NotFound.ServeHTTP(w, req) } else { http.NotFound(w, req) } } ������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/path_test.go��������������������������������0000644�0610621�0607500�00000004077�13172163411�026674� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The Go Authors. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. package httprouter import ( "runtime" "testing" ) var cleanTests = []struct { path, result string }{ // Already clean {"/", "/"}, {"/abc", "/abc"}, {"/a/b/c", "/a/b/c"}, {"/abc/", "/abc/"}, {"/a/b/c/", "/a/b/c/"}, // missing root {"", "/"}, {"abc", "/abc"}, {"abc/def", "/abc/def"}, {"a/b/c", "/a/b/c"}, // Remove doubled slash {"//", "/"}, {"/abc//", "/abc/"}, {"/abc/def//", "/abc/def/"}, {"/a/b/c//", "/a/b/c/"}, {"/abc//def//ghi", "/abc/def/ghi"}, {"//abc", "/abc"}, {"///abc", "/abc"}, {"//abc//", "/abc/"}, // Remove . elements {".", "/"}, {"./", "/"}, {"/abc/./def", "/abc/def"}, {"/./abc/def", "/abc/def"}, {"/abc/.", "/abc/"}, // Remove .. elements {"..", "/"}, {"../", "/"}, {"../../", "/"}, {"../..", "/"}, {"../../abc", "/abc"}, {"/abc/def/ghi/../jkl", "/abc/def/jkl"}, {"/abc/def/../ghi/../jkl", "/abc/jkl"}, {"/abc/def/..", "/abc"}, {"/abc/def/../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"}, // Combinations {"abc/./../def", "/def"}, {"abc//./../def", "/def"}, {"abc/../../././../def", "/def"}, } func TestPathClean(t *testing.T) { for _, test := range cleanTests { if s := CleanPath(test.path); s != test.result { t.Errorf("CleanPath(%q) = %q, want %q", test.path, s, test.result) } if s := CleanPath(test.result); s != test.result { t.Errorf("CleanPath(%q) = %q, want %q", test.result, s, test.result) } } } func TestPathCleanMallocs(t *testing.T) { if testing.Short() { t.Skip("skipping malloc count in short mode") } if runtime.GOMAXPROCS(0) > 1 { t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1") return } for _, test := range cleanTests { allocs := testing.AllocsPerRun(100, func() { CleanPath(test.result) }) if allocs > 0 { t.Errorf("CleanPath(%q): %v allocs, want zero", test.result, allocs) } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/path.go�������������������������������������0000644�0610621�0607500�00000005154�13172163411�025632� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The Go Authors. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. package httprouter // CleanPath is the URL version of path.Clean, it returns a canonical URL path // for p, eliminating . and .. elements. // // The following rules are applied iteratively until no further processing can // be done: // 1. Replace multiple slashes with a single slash. // 2. Eliminate each . path name element (the current directory). // 3. Eliminate each inner .. path name element (the parent directory) // along with the non-.. element that precedes it. // 4. Eliminate .. elements that begin a rooted path: // that is, replace "/.." by "/" at the beginning of a path. // // If the result of this process is an empty string, "/" is returned func CleanPath(p string) string { // Turn empty string into "/" if p == "" { return "/" } n := len(p) var buf []byte // Invariants: // reading from path; r is index of next byte to process. // writing to buf; w is index of next byte to write. // path must start with '/' r := 1 w := 1 if p[0] != '/' { r = 0 buf = make([]byte, n+1) buf[0] = '/' } trailing := n > 2 && p[n-1] == '/' // A bit more clunky without a 'lazybuf' like the path package, but the loop // gets completely inlined (bufApp). So in contrast to the path package this // loop has no expensive function calls (except 1x make) for r < n { switch { case p[r] == '/': // empty path element, trailing slash is added after the end r++ case p[r] == '.' && r+1 == n: trailing = true r++ case p[r] == '.' && p[r+1] == '/': // . element r++ case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): // .. element: remove to last / r += 2 if w > 1 { // can backtrack w-- if buf == nil { for w > 1 && p[w] != '/' { w-- } } else { for w > 1 && buf[w] != '/' { w-- } } } default: // real path element. // add slash if needed if w > 1 { bufApp(&buf, p, w, '/') w++ } // copy element for r < n && p[r] != '/' { bufApp(&buf, p, w, p[r]) w++ r++ } } } // re-append trailing slash if trailing && w > 1 { bufApp(&buf, p, w, '/') w++ } if buf == nil { return p[:w] } return string(buf[:w]) } // internal helper to lazily create a buffer if necessary func bufApp(buf *[]byte, s string, w int, c byte) { if *buf == nil { if s[w] == c { return } *buf = make([]byte, len(s)) copy(*buf, s[:w]) } (*buf)[w] = c } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/README.md�����������������������������������0000644�0610621�0607500�00000035600�13172163411�025625� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# HttpRouter [![Build Status](https://travis-ci.org/julienschmidt/httprouter.svg?branch=master)](https://travis-ci.org/julienschmidt/httprouter) [![Coverage Status](https://coveralls.io/repos/github/julienschmidt/httprouter/badge.svg?branch=master)](https://coveralls.io/github/julienschmidt/httprouter?branch=master) [![GoDoc](https://godoc.org/github.com/julienschmidt/httprouter?status.svg)](http://godoc.org/github.com/julienschmidt/httprouter) HttpRouter is a lightweight high performance HTTP request router (also called *multiplexer* or just *mux* for short) for [Go](https://golang.org/). In contrast to the [default mux](https://golang.org/pkg/net/http/#ServeMux) of Go's `net/http` package, this router supports variables in the routing pattern and matches against the request method. It also scales better. The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching. ## Features **Only explicit matches:** With other routers, like [`http.ServeMux`](https://golang.org/pkg/net/http/#ServeMux), a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like *longest match* or *first registered, first matched*. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience. **Stop caring about trailing slashes:** Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can [turn off this behavior](https://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash). **Path auto-correction:** Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like `../` or `//`). Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL. **Parameters in your routing pattern:** Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap. **Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. In fact, the only heap allocations that are made, is by building the slice of the key-value pairs for path parameters. If the request path contains no parameters, not a single heap allocation is necessary. **Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark). See below for technical details of the implementation. **No more server crashes:** You can set a [Panic handler](https://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler) to deal with panics occurring during handling a HTTP request. The router then recovers and lets the `PanicHandler` log what happened and deliver a nice error page. **Perfect for APIs:** The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has builtin native support for [OPTIONS requests](http://zacstewart.com/2012/04/14/http-options-method.html) and `405 Method Not Allowed` replies. Of course you can also set **custom [`NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and [`MethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](https://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles). ## Usage This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details. Let's start with a trivial example: ```go package main import ( "fmt" "github.com/julienschmidt/httprouter" "net/http" "log" ) func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Welcome!\n") } func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) } func main() { router := httprouter.New() router.GET("/", Index) router.GET("/hello/:name", Hello) log.Fatal(http.ListenAndServe(":8080", router)) } ``` ### Named parameters As you can see, `:name` is a *named parameter*. The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s. You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method: `:name` can be retrived by `ByName("name")`. Named parameters only match a single path segment: ``` Pattern: /user/:user /user/gordon match /user/you match /user/gordon/profile no match /user/ no match ``` **Note:** Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns `/user/new` and `/user/:user` for the same request method at the same time. The routing of different request methods is independent from each other. ### Catch-All parameters The second type are *catch-all* parameters and have the form `*name`. Like the name suggests, they match everything. Therefore they must always be at the **end** of the pattern: ``` Pattern: /src/*filepath /src/ match /src/somefile.go match /src/subdir/somefile.go match ``` ## How does it work? The router relies on a tree structure which makes heavy use of *common prefixes*, it is basically a *compact* [*prefix tree*](https://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](https://en.wikipedia.org/wiki/Radix_tree)). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the `GET` request method could look like: ``` Priority Path Handle 9 \ *<1> 3 ├s nil 2 |├earch\ *<2> 1 |â””upport\ *<3> 2 ├blog\ *<4> 1 | â””:post nil 1 | â””\ *<5> 2 ├about-us\ *<6> 1 | â””team\ *<7> 1 â””contact\ *<8> ``` Every `*<num>` represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder ([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the `:post` parameter, since we actually match against the routing patterns instead of just comparing hashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark), this works very well and efficient. Since URL paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, for another thing is also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree. For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways: 1. Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible. 2. It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right. ``` ├------------ ├--------- ├----- ├---- ├-- ├-- â””- ``` ## Why doesn't this work with `http.Handler`? **It does!** The router itself implements the `http.Handler` interface. Moreover the router provides convenient [adapters for `http.Handler`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [`http.HandlerFunc`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s which allows them to be used as a [`httprouter.Handle`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route. The only disadvantage is, that no parameter values can be retrieved when a `http.Handler` or `http.HandlerFunc` is used, since there is no efficient way to pass the values with the existing function parameters. Therefore [`httprouter.Handle`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) has a third function parameter. Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up. ## Where can I find Middleware *X*? This package just provides a very efficient request router with a few extra features. The router is just a [`http.Handler`](https://golang.org/pkg/net/http/#Handler), you can chain any http.Handler compatible middleware before the router, for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers). Or you could [just write your own](https://justinas.org/writing-http-middleware-in-go/), it's very easy! Alternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter). ### Multi-domain / Sub-domains Here is a quick example: Does your server serve multiple domains / hosts? You want to use sub-domains? Define a router per host! ```go // We need an object that implements the http.Handler interface. // Therefore we need a type for which we implement the ServeHTTP method. // We just use a map here, in which we map host names (with port) to http.Handlers type HostSwitch map[string]http.Handler // Implement the ServerHTTP method on our new type func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Check if a http.Handler is registered for the given host. // If yes, use it to handle the request. if handler := hs[r.Host]; handler != nil { handler.ServeHTTP(w, r) } else { // Handle host names for wich no handler is registered http.Error(w, "Forbidden", 403) // Or Redirect? } } func main() { // Initialize a router as usual router := httprouter.New() router.GET("/", Index) router.GET("/hello/:name", Hello) // Make a new HostSwitch and insert the router (our http handler) // for example.com and port 12345 hs := make(HostSwitch) hs["example.com:12345"] = router // Use the HostSwitch to listen and serve on port 12345 log.Fatal(http.ListenAndServe(":12345", hs)) } ``` ### Basic Authentication Another quick example: Basic Authentication (RFC 2617) for handles: ```go package main import ( "fmt" "log" "net/http" "github.com/julienschmidt/httprouter" ) func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // Get the Basic Authentication credentials user, password, hasAuth := r.BasicAuth() if hasAuth && user == requiredUser && password == requiredPassword { // Delegate request to the given handle h(w, r, ps) } else { // Request Basic Authentication otherwise w.Header().Set("WWW-Authenticate", "Basic realm=Restricted") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) } } } func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Not protected!\n") } func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Protected!\n") } func main() { user := "gordon" pass := "secret!" router := httprouter.New() router.GET("/", Index) router.GET("/protected/", BasicAuth(Protected, user, pass)) log.Fatal(http.ListenAndServe(":8080", router)) } ``` ## Chaining with the NotFound handler **NOTE: It might be required to set [`Router.HandleMethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.** You can use another [`http.Handler`](https://golang.org/pkg/net/http/#Handler), for example another router, to handle requests which could not be matched by this router by using the [`Router.NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) handler. This allows chaining. ### Static files The `NotFound` handler can for example be used to serve static files from the root path `/` (like an `index.html` file along with other assets): ```go // Serve static files from the ./public directory router.NotFound = http.FileServer(http.Dir("public")) ``` But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like `/static/*filepath` or `/files/*filepath`. ## Web Frameworks based on HttpRouter If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package: * [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework * [api2go](https://github.com/manyminds/api2go): A JSON API Implementation for Go * [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance * [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go * [goMiddlewareChain](https://github.com/TobiEiss/goMiddlewareChain): An express.js-like-middleware-chain * [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine * [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow * [httpway](https://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support * [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context * [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba * [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang * [River](https://github.com/abiosoft/river): River is a simple and lightweight REST server * [Roxanna](https://github.com/iamthemuffinman/Roxanna): An amalgamation of httprouter, better logging, and hot reload * [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts * [xmux](https://github.com/rs/xmux): xmux is a httprouter fork on top of xhandler (net/context aware) ��������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/LICENSE�������������������������������������0000644�0610621�0607500�00000002662�13172163411�025355� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2013 Julien Schmidt. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JULIEN SCHMIDT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/julienschmidt/httprouter/.travis.yml���������������������������������0000644�0610621�0607500�00000000707�13172163411�026457� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������sudo: false language: go go: - 1.6 - 1.7 - 1.8 - tip before_install: - go get golang.org/x/tools/cmd/cover - go get github.com/mattn/goveralls - go get github.com/golang/lint/golint script: - go test -v -covermode=count -coverprofile=coverage.out - go vet ./... - test -z "$(gofmt -d -s . | tee /dev/stderr)" - test -z "$(golint ./... | tee /dev/stderr)" - $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci ���������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/��������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163405�020532� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163407�022374� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/����������������������������������������������0000755�0610621�0607500�00000000000�13172163407�023720� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/wrappers/�������������������������������������0000755�0610621�0607500�00000000000�13172163407�025563� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto�����������������������0000644�0610621�0607500�00000007241�13172163407�030517� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Wrappers for primitive (non-message) types. These types are useful // for embedding primitives in the `google.protobuf.Any` type and for places // where we need to distinguish between the absence of a primitive // typed field and its default value. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "github.com/golang/protobuf/ptypes/wrappers"; option java_package = "com.google.protobuf"; option java_outer_classname = "WrappersProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // Wrapper message for `double`. // // The JSON representation for `DoubleValue` is JSON number. message DoubleValue { // The double value. double value = 1; } // Wrapper message for `float`. // // The JSON representation for `FloatValue` is JSON number. message FloatValue { // The float value. float value = 1; } // Wrapper message for `int64`. // // The JSON representation for `Int64Value` is JSON string. message Int64Value { // The int64 value. int64 value = 1; } // Wrapper message for `uint64`. // // The JSON representation for `UInt64Value` is JSON string. message UInt64Value { // The uint64 value. uint64 value = 1; } // Wrapper message for `int32`. // // The JSON representation for `Int32Value` is JSON number. message Int32Value { // The int32 value. int32 value = 1; } // Wrapper message for `uint32`. // // The JSON representation for `UInt32Value` is JSON number. message UInt32Value { // The uint32 value. uint32 value = 1; } // Wrapper message for `bool`. // // The JSON representation for `BoolValue` is JSON `true` and `false`. message BoolValue { // The bool value. bool value = 1; } // Wrapper message for `string`. // // The JSON representation for `StringValue` is JSON string. message StringValue { // The string value. string value = 1; } // Wrapper message for `bytes`. // // The JSON representation for `BytesValue` is JSON string. message BytesValue { // The bytes value. bytes value = 1; } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go�����������������������0000644�0610621�0607500�00000022312�13172163407�030355� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/wrappers.proto /* Package wrappers is a generated protocol buffer package. It is generated from these files: google/protobuf/wrappers.proto It has these top-level messages: DoubleValue FloatValue Int64Value UInt64Value Int32Value UInt32Value BoolValue StringValue BytesValue */ package wrappers import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // Wrapper message for `double`. // // The JSON representation for `DoubleValue` is JSON number. type DoubleValue struct { // The double value. Value float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` } func (m *DoubleValue) Reset() { *m = DoubleValue{} } func (m *DoubleValue) String() string { return proto.CompactTextString(m) } func (*DoubleValue) ProtoMessage() {} func (*DoubleValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*DoubleValue) XXX_WellKnownType() string { return "DoubleValue" } func (m *DoubleValue) GetValue() float64 { if m != nil { return m.Value } return 0 } // Wrapper message for `float`. // // The JSON representation for `FloatValue` is JSON number. type FloatValue struct { // The float value. Value float32 `protobuf:"fixed32,1,opt,name=value" json:"value,omitempty"` } func (m *FloatValue) Reset() { *m = FloatValue{} } func (m *FloatValue) String() string { return proto.CompactTextString(m) } func (*FloatValue) ProtoMessage() {} func (*FloatValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (*FloatValue) XXX_WellKnownType() string { return "FloatValue" } func (m *FloatValue) GetValue() float32 { if m != nil { return m.Value } return 0 } // Wrapper message for `int64`. // // The JSON representation for `Int64Value` is JSON string. type Int64Value struct { // The int64 value. Value int64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *Int64Value) Reset() { *m = Int64Value{} } func (m *Int64Value) String() string { return proto.CompactTextString(m) } func (*Int64Value) ProtoMessage() {} func (*Int64Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (*Int64Value) XXX_WellKnownType() string { return "Int64Value" } func (m *Int64Value) GetValue() int64 { if m != nil { return m.Value } return 0 } // Wrapper message for `uint64`. // // The JSON representation for `UInt64Value` is JSON string. type UInt64Value struct { // The uint64 value. Value uint64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *UInt64Value) Reset() { *m = UInt64Value{} } func (m *UInt64Value) String() string { return proto.CompactTextString(m) } func (*UInt64Value) ProtoMessage() {} func (*UInt64Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (*UInt64Value) XXX_WellKnownType() string { return "UInt64Value" } func (m *UInt64Value) GetValue() uint64 { if m != nil { return m.Value } return 0 } // Wrapper message for `int32`. // // The JSON representation for `Int32Value` is JSON number. type Int32Value struct { // The int32 value. Value int32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *Int32Value) Reset() { *m = Int32Value{} } func (m *Int32Value) String() string { return proto.CompactTextString(m) } func (*Int32Value) ProtoMessage() {} func (*Int32Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (*Int32Value) XXX_WellKnownType() string { return "Int32Value" } func (m *Int32Value) GetValue() int32 { if m != nil { return m.Value } return 0 } // Wrapper message for `uint32`. // // The JSON representation for `UInt32Value` is JSON number. type UInt32Value struct { // The uint32 value. Value uint32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *UInt32Value) Reset() { *m = UInt32Value{} } func (m *UInt32Value) String() string { return proto.CompactTextString(m) } func (*UInt32Value) ProtoMessage() {} func (*UInt32Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (*UInt32Value) XXX_WellKnownType() string { return "UInt32Value" } func (m *UInt32Value) GetValue() uint32 { if m != nil { return m.Value } return 0 } // Wrapper message for `bool`. // // The JSON representation for `BoolValue` is JSON `true` and `false`. type BoolValue struct { // The bool value. Value bool `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *BoolValue) Reset() { *m = BoolValue{} } func (m *BoolValue) String() string { return proto.CompactTextString(m) } func (*BoolValue) ProtoMessage() {} func (*BoolValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (*BoolValue) XXX_WellKnownType() string { return "BoolValue" } func (m *BoolValue) GetValue() bool { if m != nil { return m.Value } return false } // Wrapper message for `string`. // // The JSON representation for `StringValue` is JSON string. type StringValue struct { // The string value. Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"` } func (m *StringValue) Reset() { *m = StringValue{} } func (m *StringValue) String() string { return proto.CompactTextString(m) } func (*StringValue) ProtoMessage() {} func (*StringValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (*StringValue) XXX_WellKnownType() string { return "StringValue" } func (m *StringValue) GetValue() string { if m != nil { return m.Value } return "" } // Wrapper message for `bytes`. // // The JSON representation for `BytesValue` is JSON string. type BytesValue struct { // The bytes value. Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` } func (m *BytesValue) Reset() { *m = BytesValue{} } func (m *BytesValue) String() string { return proto.CompactTextString(m) } func (*BytesValue) ProtoMessage() {} func (*BytesValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } func (*BytesValue) XXX_WellKnownType() string { return "BytesValue" } func (m *BytesValue) GetValue() []byte { if m != nil { return m.Value } return nil } func init() { proto.RegisterType((*DoubleValue)(nil), "google.protobuf.DoubleValue") proto.RegisterType((*FloatValue)(nil), "google.protobuf.FloatValue") proto.RegisterType((*Int64Value)(nil), "google.protobuf.Int64Value") proto.RegisterType((*UInt64Value)(nil), "google.protobuf.UInt64Value") proto.RegisterType((*Int32Value)(nil), "google.protobuf.Int32Value") proto.RegisterType((*UInt32Value)(nil), "google.protobuf.UInt32Value") proto.RegisterType((*BoolValue)(nil), "google.protobuf.BoolValue") proto.RegisterType((*StringValue)(nil), "google.protobuf.StringValue") proto.RegisterType((*BytesValue)(nil), "google.protobuf.BytesValue") } func init() { proto.RegisterFile("google/protobuf/wrappers.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 259 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x2f, 0x4a, 0x2c, 0x28, 0x48, 0x2d, 0x2a, 0xd6, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0xca, 0x5c, 0xdc, 0x2e, 0xf9, 0xa5, 0x49, 0x39, 0xa9, 0x61, 0x89, 0x39, 0xa5, 0xa9, 0x42, 0x22, 0x5c, 0xac, 0x65, 0x20, 0x86, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x63, 0x10, 0x84, 0xa3, 0xa4, 0xc4, 0xc5, 0xe5, 0x96, 0x93, 0x9f, 0x58, 0x82, 0x45, 0x0d, 0x13, 0x92, 0x1a, 0xcf, 0xbc, 0x12, 0x33, 0x13, 0x2c, 0x6a, 0x98, 0x61, 0x6a, 0x94, 0xb9, 0xb8, 0x43, 0x71, 0x29, 0x62, 0x41, 0x35, 0xc8, 0xd8, 0x08, 0x8b, 0x1a, 0x56, 0x34, 0x83, 0xb0, 0x2a, 0xe2, 0x85, 0x29, 0x52, 0xe4, 0xe2, 0x74, 0xca, 0xcf, 0xcf, 0xc1, 0xa2, 0x84, 0x03, 0xc9, 0x9c, 0xe0, 0x92, 0xa2, 0xcc, 0xbc, 0x74, 0x2c, 0x8a, 0x38, 0x91, 0x1c, 0xe4, 0x54, 0x59, 0x92, 0x5a, 0x8c, 0x45, 0x0d, 0x0f, 0x54, 0x8d, 0x53, 0x0d, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x5a, 0xe8, 0x3a, 0xf1, 0x86, 0x43, 0x83, 0x3f, 0x00, 0x24, 0x12, 0xc0, 0x18, 0xa5, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f, 0x9e, 0x9f, 0x93, 0x98, 0x97, 0x8e, 0x88, 0xaa, 0x82, 0x92, 0xca, 0x82, 0xd4, 0x62, 0x78, 0x8c, 0xfd, 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78, 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x19, 0x6c, 0xb9, 0xb8, 0xfe, 0x01, 0x00, 0x00, } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/timestamp_test.go�����������������������������0000644�0610621�0607500�00000013267�13172163407�027322� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package ptypes import ( "math" "testing" "time" "github.com/golang/protobuf/proto" tspb "github.com/golang/protobuf/ptypes/timestamp" ) var tests = []struct { ts *tspb.Timestamp valid bool t time.Time }{ // The timestamp representing the Unix epoch date. {&tspb.Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)}, // The smallest representable timestamp. {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false, time.Unix(math.MinInt64, math.MinInt32).UTC()}, // The smallest representable timestamp with non-negative nanos. {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()}, // The earliest valid timestamp. {&tspb.Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)}, //"0001-01-01T00:00:00Z"}, // The largest representable timestamp. {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false, time.Unix(math.MaxInt64, math.MaxInt32).UTC()}, // The largest representable timestamp with nanos in range. {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false, time.Unix(math.MaxInt64, 1e9-1).UTC()}, // The largest valid timestamp. {&tspb.Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true, time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)}, // The smallest invalid timestamp that is larger than the valid range. {&tspb.Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()}, // A date before the epoch. {&tspb.Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)}, // A date after the epoch. {&tspb.Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)}, // A date after the epoch, in the middle of the day. {&tspb.Timestamp{Seconds: 1296012345, Nanos: 940483}, true, time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)}, } func TestValidateTimestamp(t *testing.T) { for _, s := range tests { got := validateTimestamp(s.ts) if (got == nil) != s.valid { t.Errorf("validateTimestamp(%v) = %v, want %v", s.ts, got, s.valid) } } } func TestTimestamp(t *testing.T) { for _, s := range tests { got, err := Timestamp(s.ts) if (err == nil) != s.valid { t.Errorf("Timestamp(%v) error = %v, but valid = %t", s.ts, err, s.valid) } else if s.valid && got != s.t { t.Errorf("Timestamp(%v) = %v, want %v", s.ts, got, s.t) } } // Special case: a nil Timestamp is an error, but returns the 0 Unix time. got, err := Timestamp(nil) want := time.Unix(0, 0).UTC() if got != want { t.Errorf("Timestamp(nil) = %v, want %v", got, want) } if err == nil { t.Errorf("Timestamp(nil) error = nil, expected error") } } func TestTimestampProto(t *testing.T) { for _, s := range tests { got, err := TimestampProto(s.t) if (err == nil) != s.valid { t.Errorf("TimestampProto(%v) error = %v, but valid = %t", s.t, err, s.valid) } else if s.valid && !proto.Equal(got, s.ts) { t.Errorf("TimestampProto(%v) = %v, want %v", s.t, got, s.ts) } } // No corresponding special case here: no time.Time results in a nil Timestamp. } func TestTimestampString(t *testing.T) { for _, test := range []struct { ts *tspb.Timestamp want string }{ // Not much testing needed because presumably time.Format is // well-tested. {&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"}, {&tspb.Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"}, } { got := TimestampString(test.ts) if got != test.want { t.Errorf("TimestampString(%v) = %q, want %q", test.ts, got, test.want) } } } func utcDate(year, month, day int) time.Time { return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) } func TestTimestampNow(t *testing.T) { // Bracket the expected time. before := time.Now() ts := TimestampNow() after := time.Now() tm, err := Timestamp(ts) if err != nil { t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err) } if tm.Before(before) || tm.After(after) { t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm) } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/timestamp/������������������������������������0000755�0610621�0607500�00000000000�13172163407�025723� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto���������������������0000644�0610621�0607500�00000013532�13172163407�031017� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "github.com/golang/protobuf/ptypes/timestamp"; option java_package = "com.google.protobuf"; option java_outer_classname = "TimestampProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // A Timestamp represents a point in time independent of any time zone // or calendar, represented as seconds and fractions of seconds at // nanosecond resolution in UTC Epoch time. It is encoded using the // Proleptic Gregorian Calendar which extends the Gregorian calendar // backwards to year one. It is encoded assuming all minutes are 60 // seconds long, i.e. leap seconds are "smeared" so that no leap second // table is needed for interpretation. Range is from // 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. // By restricting to that range, we ensure that we can convert to // and from RFC 3339 date strings. // See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). // // # Examples // // Example 1: Compute Timestamp from POSIX `time()`. // // Timestamp timestamp; // timestamp.set_seconds(time(NULL)); // timestamp.set_nanos(0); // // Example 2: Compute Timestamp from POSIX `gettimeofday()`. // // struct timeval tv; // gettimeofday(&tv, NULL); // // Timestamp timestamp; // timestamp.set_seconds(tv.tv_sec); // timestamp.set_nanos(tv.tv_usec * 1000); // // Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. // // FILETIME ft; // GetSystemTimeAsFileTime(&ft); // UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // // // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z // // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. // Timestamp timestamp; // timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); // timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); // // Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. // // long millis = System.currentTimeMillis(); // // Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) // .setNanos((int) ((millis % 1000) * 1000000)).build(); // // // Example 5: Compute Timestamp from current time in Python. // // timestamp = Timestamp() // timestamp.GetCurrentTime() // // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required, though only UTC (as indicated by "Z") is presently supported. // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the // standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] // method. In Python, a standard `datetime.datetime` object can be converted // to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) // with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one // can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) // to obtain a formatter capable of generating timestamps in this format. // // message Timestamp { // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. int64 seconds = 1; // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. int32 nanos = 2; } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go���������������������0000644�0610621�0607500�00000015256�13172163407�030666� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/timestamp.proto /* Package timestamp is a generated protocol buffer package. It is generated from these files: google/protobuf/timestamp.proto It has these top-level messages: Timestamp */ package timestamp import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // A Timestamp represents a point in time independent of any time zone // or calendar, represented as seconds and fractions of seconds at // nanosecond resolution in UTC Epoch time. It is encoded using the // Proleptic Gregorian Calendar which extends the Gregorian calendar // backwards to year one. It is encoded assuming all minutes are 60 // seconds long, i.e. leap seconds are "smeared" so that no leap second // table is needed for interpretation. Range is from // 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. // By restricting to that range, we ensure that we can convert to // and from RFC 3339 date strings. // See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). // // # Examples // // Example 1: Compute Timestamp from POSIX `time()`. // // Timestamp timestamp; // timestamp.set_seconds(time(NULL)); // timestamp.set_nanos(0); // // Example 2: Compute Timestamp from POSIX `gettimeofday()`. // // struct timeval tv; // gettimeofday(&tv, NULL); // // Timestamp timestamp; // timestamp.set_seconds(tv.tv_sec); // timestamp.set_nanos(tv.tv_usec * 1000); // // Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. // // FILETIME ft; // GetSystemTimeAsFileTime(&ft); // UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // // // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z // // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. // Timestamp timestamp; // timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); // timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); // // Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. // // long millis = System.currentTimeMillis(); // // Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) // .setNanos((int) ((millis % 1000) * 1000000)).build(); // // // Example 5: Compute Timestamp from current time in Python. // // timestamp = Timestamp() // timestamp.GetCurrentTime() // // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required, though only UTC (as indicated by "Z") is presently supported. // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the // standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] // method. In Python, a standard `datetime.datetime` object can be converted // to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) // with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one // can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) // to obtain a formatter capable of generating timestamps in this format. // // type Timestamp struct { // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` } func (m *Timestamp) Reset() { *m = Timestamp{} } func (m *Timestamp) String() string { return proto.CompactTextString(m) } func (*Timestamp) ProtoMessage() {} func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } func (m *Timestamp) GetSeconds() int64 { if m != nil { return m.Seconds } return 0 } func (m *Timestamp) GetNanos() int32 { if m != nil { return m.Nanos } return 0 } func init() { proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp") } func init() { proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 191 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28, 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5, 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89, 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51, 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89, 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71, 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a, 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00, } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/timestamp.go����������������������������������0000644�0610621�0607500�00000011460�13172163407�026254� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package ptypes // This file implements operations on google.protobuf.Timestamp. import ( "errors" "fmt" "time" tspb "github.com/golang/protobuf/ptypes/timestamp" ) const ( // Seconds field of the earliest valid Timestamp. // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). minValidSeconds = -62135596800 // Seconds field just after the latest valid Timestamp. // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). maxValidSeconds = 253402300800 ) // validateTimestamp determines whether a Timestamp is valid. // A valid timestamp represents a time in the range // [0001-01-01, 10000-01-01) and has a Nanos field // in the range [0, 1e9). // // If the Timestamp is valid, validateTimestamp returns nil. // Otherwise, it returns an error that describes // the problem. // // Every valid Timestamp can be represented by a time.Time, but the converse is not true. func validateTimestamp(ts *tspb.Timestamp) error { if ts == nil { return errors.New("timestamp: nil Timestamp") } if ts.Seconds < minValidSeconds { return fmt.Errorf("timestamp: %v before 0001-01-01", ts) } if ts.Seconds >= maxValidSeconds { return fmt.Errorf("timestamp: %v after 10000-01-01", ts) } if ts.Nanos < 0 || ts.Nanos >= 1e9 { return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts) } return nil } // Timestamp converts a google.protobuf.Timestamp proto to a time.Time. // It returns an error if the argument is invalid. // // Unlike most Go functions, if Timestamp returns an error, the first return value // is not the zero time.Time. Instead, it is the value obtained from the // time.Unix function when passed the contents of the Timestamp, in the UTC // locale. This may or may not be a meaningful time; many invalid Timestamps // do map to valid time.Times. // // A nil Timestamp returns an error. The first return value in that case is // undefined. func Timestamp(ts *tspb.Timestamp) (time.Time, error) { // Don't return the zero value on error, because corresponds to a valid // timestamp. Instead return whatever time.Unix gives us. var t time.Time if ts == nil { t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp } else { t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC() } return t, validateTimestamp(ts) } // TimestampNow returns a google.protobuf.Timestamp for the current time. func TimestampNow() *tspb.Timestamp { ts, err := TimestampProto(time.Now()) if err != nil { panic("ptypes: time.Now() out of Timestamp range") } return ts } // TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. // It returns an error if the resulting Timestamp is invalid. func TimestampProto(t time.Time) (*tspb.Timestamp, error) { seconds := t.Unix() nanos := int32(t.Sub(time.Unix(seconds, 0))) ts := &tspb.Timestamp{ Seconds: seconds, Nanos: nanos, } if err := validateTimestamp(ts); err != nil { return nil, err } return ts, nil } // TimestampString returns the RFC 3339 string for valid Timestamps. For invalid // Timestamps, it returns an error message in parentheses. func TimestampString(ts *tspb.Timestamp) string { t, err := Timestamp(ts) if err != nil { return fmt.Sprintf("(%v)", err) } return t.Format(time.RFC3339Nano) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/struct/���������������������������������������0000755�0610621�0607500�00000000000�13172163407�025244� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/struct/struct.proto���������������������������0000644�0610621�0607500�00000007305�13172163407�027662� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "github.com/golang/protobuf/ptypes/struct;structpb"; option java_package = "com.google.protobuf"; option java_outer_classname = "StructProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` // might be supported by a native representation. For example, in // scripting languages like JS a struct is represented as an // object. The details of that representation are described together // with the proto support for the language. // // The JSON representation for `Struct` is JSON object. message Struct { // Unordered map of dynamically typed values. map<string, Value> fields = 1; } // `Value` represents a dynamically typed value which can be either // null, a number, a string, a boolean, a recursive struct value, or a // list of values. A producer of value is expected to set one of that // variants, absence of any variant indicates an error. // // The JSON representation for `Value` is JSON value. message Value { // The kind of value. oneof kind { // Represents a null value. NullValue null_value = 1; // Represents a double value. double number_value = 2; // Represents a string value. string string_value = 3; // Represents a boolean value. bool bool_value = 4; // Represents a structured value. Struct struct_value = 5; // Represents a repeated `Value`. ListValue list_value = 6; } } // `NullValue` is a singleton enumeration to represent the null value for the // `Value` type union. // // The JSON representation for `NullValue` is JSON `null`. enum NullValue { // Null value. NULL_VALUE = 0; } // `ListValue` is a wrapper around a repeated field of values. // // The JSON representation for `ListValue` is JSON array. message ListValue { // Repeated field of dynamically typed values. repeated Value values = 1; } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/struct/struct.pb.go���������������������������0000644�0610621�0607500�00000031301�13172163407�027515� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/struct.proto /* Package structpb is a generated protocol buffer package. It is generated from these files: google/protobuf/struct.proto It has these top-level messages: Struct Value ListValue */ package structpb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // `NullValue` is a singleton enumeration to represent the null value for the // `Value` type union. // // The JSON representation for `NullValue` is JSON `null`. type NullValue int32 const ( // Null value. NullValue_NULL_VALUE NullValue = 0 ) var NullValue_name = map[int32]string{ 0: "NULL_VALUE", } var NullValue_value = map[string]int32{ "NULL_VALUE": 0, } func (x NullValue) String() string { return proto.EnumName(NullValue_name, int32(x)) } func (NullValue) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (NullValue) XXX_WellKnownType() string { return "NullValue" } // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` // might be supported by a native representation. For example, in // scripting languages like JS a struct is represented as an // object. The details of that representation are described together // with the proto support for the language. // // The JSON representation for `Struct` is JSON object. type Struct struct { // Unordered map of dynamically typed values. Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` } func (m *Struct) Reset() { *m = Struct{} } func (m *Struct) String() string { return proto.CompactTextString(m) } func (*Struct) ProtoMessage() {} func (*Struct) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Struct) XXX_WellKnownType() string { return "Struct" } func (m *Struct) GetFields() map[string]*Value { if m != nil { return m.Fields } return nil } // `Value` represents a dynamically typed value which can be either // null, a number, a string, a boolean, a recursive struct value, or a // list of values. A producer of value is expected to set one of that // variants, absence of any variant indicates an error. // // The JSON representation for `Value` is JSON value. type Value struct { // The kind of value. // // Types that are valid to be assigned to Kind: // *Value_NullValue // *Value_NumberValue // *Value_StringValue // *Value_BoolValue // *Value_StructValue // *Value_ListValue Kind isValue_Kind `protobuf_oneof:"kind"` } func (m *Value) Reset() { *m = Value{} } func (m *Value) String() string { return proto.CompactTextString(m) } func (*Value) ProtoMessage() {} func (*Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (*Value) XXX_WellKnownType() string { return "Value" } type isValue_Kind interface { isValue_Kind() } type Value_NullValue struct { NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,enum=google.protobuf.NullValue,oneof"` } type Value_NumberValue struct { NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,oneof"` } type Value_StringValue struct { StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,oneof"` } type Value_BoolValue struct { BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,oneof"` } type Value_StructValue struct { StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"` } type Value_ListValue struct { ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"` } func (*Value_NullValue) isValue_Kind() {} func (*Value_NumberValue) isValue_Kind() {} func (*Value_StringValue) isValue_Kind() {} func (*Value_BoolValue) isValue_Kind() {} func (*Value_StructValue) isValue_Kind() {} func (*Value_ListValue) isValue_Kind() {} func (m *Value) GetKind() isValue_Kind { if m != nil { return m.Kind } return nil } func (m *Value) GetNullValue() NullValue { if x, ok := m.GetKind().(*Value_NullValue); ok { return x.NullValue } return NullValue_NULL_VALUE } func (m *Value) GetNumberValue() float64 { if x, ok := m.GetKind().(*Value_NumberValue); ok { return x.NumberValue } return 0 } func (m *Value) GetStringValue() string { if x, ok := m.GetKind().(*Value_StringValue); ok { return x.StringValue } return "" } func (m *Value) GetBoolValue() bool { if x, ok := m.GetKind().(*Value_BoolValue); ok { return x.BoolValue } return false } func (m *Value) GetStructValue() *Struct { if x, ok := m.GetKind().(*Value_StructValue); ok { return x.StructValue } return nil } func (m *Value) GetListValue() *ListValue { if x, ok := m.GetKind().(*Value_ListValue); ok { return x.ListValue } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{ (*Value_NullValue)(nil), (*Value_NumberValue)(nil), (*Value_StringValue)(nil), (*Value_BoolValue)(nil), (*Value_StructValue)(nil), (*Value_ListValue)(nil), } } func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Value) // kind switch x := m.Kind.(type) { case *Value_NullValue: b.EncodeVarint(1<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.NullValue)) case *Value_NumberValue: b.EncodeVarint(2<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.NumberValue)) case *Value_StringValue: b.EncodeVarint(3<<3 | proto.WireBytes) b.EncodeStringBytes(x.StringValue) case *Value_BoolValue: t := uint64(0) if x.BoolValue { t = 1 } b.EncodeVarint(4<<3 | proto.WireVarint) b.EncodeVarint(t) case *Value_StructValue: b.EncodeVarint(5<<3 | proto.WireBytes) if err := b.EncodeMessage(x.StructValue); err != nil { return err } case *Value_ListValue: b.EncodeVarint(6<<3 | proto.WireBytes) if err := b.EncodeMessage(x.ListValue); err != nil { return err } case nil: default: return fmt.Errorf("Value.Kind has unexpected type %T", x) } return nil } func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Value) switch tag { case 1: // kind.null_value if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Kind = &Value_NullValue{NullValue(x)} return true, err case 2: // kind.number_value if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Kind = &Value_NumberValue{math.Float64frombits(x)} return true, err case 3: // kind.string_value if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Kind = &Value_StringValue{x} return true, err case 4: // kind.bool_value if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Kind = &Value_BoolValue{x != 0} return true, err case 5: // kind.struct_value if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Struct) err := b.DecodeMessage(msg) m.Kind = &Value_StructValue{msg} return true, err case 6: // kind.list_value if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(ListValue) err := b.DecodeMessage(msg) m.Kind = &Value_ListValue{msg} return true, err default: return false, nil } } func _Value_OneofSizer(msg proto.Message) (n int) { m := msg.(*Value) // kind switch x := m.Kind.(type) { case *Value_NullValue: n += proto.SizeVarint(1<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.NullValue)) case *Value_NumberValue: n += proto.SizeVarint(2<<3 | proto.WireFixed64) n += 8 case *Value_StringValue: n += proto.SizeVarint(3<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.StringValue))) n += len(x.StringValue) case *Value_BoolValue: n += proto.SizeVarint(4<<3 | proto.WireVarint) n += 1 case *Value_StructValue: s := proto.Size(x.StructValue) n += proto.SizeVarint(5<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Value_ListValue: s := proto.Size(x.ListValue) n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // `ListValue` is a wrapper around a repeated field of values. // // The JSON representation for `ListValue` is JSON array. type ListValue struct { // Repeated field of dynamically typed values. Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"` } func (m *ListValue) Reset() { *m = ListValue{} } func (m *ListValue) String() string { return proto.CompactTextString(m) } func (*ListValue) ProtoMessage() {} func (*ListValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (*ListValue) XXX_WellKnownType() string { return "ListValue" } func (m *ListValue) GetValues() []*Value { if m != nil { return m.Values } return nil } func init() { proto.RegisterType((*Struct)(nil), "google.protobuf.Struct") proto.RegisterType((*Value)(nil), "google.protobuf.Value") proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue") proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value) } func init() { proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 417 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x41, 0x8b, 0xd3, 0x40, 0x14, 0xc7, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa2, 0xa1, 0x7b, 0x09, 0x22, 0x29, 0xd6, 0x8b, 0x18, 0x2f, 0x06, 0xd6, 0x5d, 0x30, 0x2c, 0x31, 0xba, 0x15, 0xbc, 0x94, 0x26, 0x4d, 0x63, 0xe8, 0x74, 0x26, 0x24, 0x33, 0x4a, 0x8f, 0x7e, 0x0b, 0xcf, 0x1e, 0x3d, 0xfa, 0xe9, 0x3c, 0xca, 0xcc, 0x24, 0xa9, 0xb4, 0xf4, 0x94, 0xbc, 0xf7, 0x7e, 0xef, 0x3f, 0xef, 0xff, 0x66, 0xe0, 0x71, 0xc1, 0x58, 0x41, 0xf2, 0x49, 0x55, 0x33, 0xce, 0x52, 0xb1, 0x9a, 0x34, 0xbc, 0x16, 0x19, 0xf7, 0x55, 0x8c, 0xef, 0xe9, 0xaa, 0xdf, 0x55, 0xc7, 0x3f, 0x11, 0x58, 0x1f, 0x15, 0x81, 0x03, 0xb0, 0x56, 0x65, 0x4e, 0x96, 0xcd, 0x08, 0xb9, 0xa6, 0xe7, 0x4c, 0x2f, 0xfc, 0x3d, 0xd8, 0xd7, 0xa0, 0xff, 0x4e, 0x51, 0x97, 0x94, 0xd7, 0xdb, 0xa4, 0x6d, 0x39, 0xff, 0x00, 0xce, 0x7f, 0x69, 0x7c, 0x06, 0xe6, 0x3a, 0xdf, 0x8e, 0x90, 0x8b, 0x3c, 0x3b, 0x91, 0xbf, 0xf8, 0x39, 0x0c, 0xbf, 0x2d, 0x88, 0xc8, 0x47, 0x86, 0x8b, 0x3c, 0x67, 0xfa, 0xe0, 0x40, 0x7c, 0x26, 0xab, 0x89, 0x86, 0x5e, 0x1b, 0xaf, 0xd0, 0xf8, 0x8f, 0x01, 0x43, 0x95, 0xc4, 0x01, 0x00, 0x15, 0x84, 0xcc, 0xb5, 0x80, 0x14, 0x3d, 0x9d, 0x9e, 0x1f, 0x08, 0xdc, 0x08, 0x42, 0x14, 0x7f, 0x3d, 0x48, 0x6c, 0xda, 0x05, 0xf8, 0x02, 0xee, 0x52, 0xb1, 0x49, 0xf3, 0x7a, 0xbe, 0x3b, 0x1f, 0x5d, 0x0f, 0x12, 0x47, 0x67, 0x7b, 0xa8, 0xe1, 0x75, 0x49, 0x8b, 0x16, 0x32, 0xe5, 0xe0, 0x12, 0xd2, 0x59, 0x0d, 0x3d, 0x05, 0x48, 0x19, 0xeb, 0xc6, 0x38, 0x71, 0x91, 0x77, 0x47, 0x1e, 0x25, 0x73, 0x1a, 0x78, 0xa3, 0x54, 0x44, 0xc6, 0x5b, 0x64, 0xa8, 0xac, 0x3e, 0x3c, 0xb2, 0xc7, 0x56, 0x5e, 0x64, 0xbc, 0x77, 0x49, 0xca, 0xa6, 0xeb, 0xb5, 0x54, 0xef, 0xa1, 0xcb, 0xa8, 0x6c, 0x78, 0xef, 0x92, 0x74, 0x41, 0x68, 0xc1, 0xc9, 0xba, 0xa4, 0xcb, 0x71, 0x00, 0x76, 0x4f, 0x60, 0x1f, 0x2c, 0x25, 0xd6, 0xdd, 0xe8, 0xb1, 0xa5, 0xb7, 0xd4, 0xb3, 0x47, 0x60, 0xf7, 0x4b, 0xc4, 0xa7, 0x00, 0x37, 0xb7, 0x51, 0x34, 0x9f, 0xbd, 0x8d, 0x6e, 0x2f, 0xcf, 0x06, 0xe1, 0x0f, 0x04, 0xf7, 0x33, 0xb6, 0xd9, 0x97, 0x08, 0x1d, 0xed, 0x26, 0x96, 0x71, 0x8c, 0xbe, 0xbc, 0x28, 0x4a, 0xfe, 0x55, 0xa4, 0x7e, 0xc6, 0x36, 0x93, 0x82, 0x91, 0x05, 0x2d, 0x76, 0x4f, 0xb1, 0xe2, 0xdb, 0x2a, 0x6f, 0xda, 0x17, 0x19, 0xe8, 0x4f, 0x95, 0xfe, 0x45, 0xe8, 0x97, 0x61, 0x5e, 0xc5, 0xe1, 0x6f, 0xe3, 0xc9, 0x95, 0x16, 0x8f, 0xbb, 0xf9, 0x3e, 0xe7, 0x84, 0xbc, 0xa7, 0xec, 0x3b, 0xfd, 0x24, 0x3b, 0x53, 0x4b, 0x49, 0xbd, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x1b, 0x59, 0xf8, 0xe5, 0x02, 0x00, 0x00, } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/regen.sh��������������������������������������0000755�0610621�0607500�00000002226�13172163407�025361� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash -e # # This script fetches and rebuilds the "well-known types" protocol buffers. # To run this you will need protoc and goprotobuf installed; # see https://github.com/golang/protobuf for instructions. # You also need Go and Git installed. PKG=github.com/golang/protobuf/ptypes UPSTREAM=https://github.com/google/protobuf UPSTREAM_SUBDIR=src/google/protobuf PROTO_FILES=(any duration empty struct timestamp wrappers) function die() { echo 1>&2 $* exit 1 } # Sanity check that the right tools are accessible. for tool in go git protoc protoc-gen-go; do q=$(which $tool) || die "didn't find $tool" echo 1>&2 "$tool: $q" done tmpdir=$(mktemp -d -t regen-wkt.XXXXXX) trap 'rm -rf $tmpdir' EXIT echo -n 1>&2 "finding package dir... " pkgdir=$(go list -f '{{.Dir}}' $PKG) echo 1>&2 $pkgdir base=$(echo $pkgdir | sed "s,/$PKG\$,,") echo 1>&2 "base: $base" cd "$base" echo 1>&2 "fetching latest protos... " git clone -q $UPSTREAM $tmpdir for file in ${PROTO_FILES[@]}; do echo 1>&2 "* $file" protoc --go_out=. -I$tmpdir/src $tmpdir/src/google/protobuf/$file.proto || die cp $tmpdir/src/google/protobuf/$file.proto $PKG/$file done echo 1>&2 "All OK" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/empty/����������������������������������������0000755�0610621�0607500�00000000000�13172163407�025056� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/empty/empty.proto�����������������������������0000644�0610621�0607500�00000004566�13172163407�027314� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "github.com/golang/protobuf/ptypes/empty"; option java_package = "com.google.protobuf"; option java_outer_classname = "EmptyProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option cc_enable_arenas = true; // A generic empty message that you can re-use to avoid defining duplicated // empty messages in your APIs. A typical example is to use it as the request // or the response type of an API method. For instance: // // service Foo { // rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); // } // // The JSON representation for `Empty` is empty JSON object `{}`. message Empty {} ������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/empty/empty.pb.go�����������������������������0000644�0610621�0607500�00000005172�13172163407�027150� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/empty.proto /* Package empty is a generated protocol buffer package. It is generated from these files: google/protobuf/empty.proto It has these top-level messages: Empty */ package empty import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // A generic empty message that you can re-use to avoid defining duplicated // empty messages in your APIs. A typical example is to use it as the request // or the response type of an API method. For instance: // // service Foo { // rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); // } // // The JSON representation for `Empty` is empty JSON object `{}`. type Empty struct { } func (m *Empty) Reset() { *m = Empty{} } func (m *Empty) String() string { return proto.CompactTextString(m) } func (*Empty) ProtoMessage() {} func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Empty) XXX_WellKnownType() string { return "Empty" } func init() { proto.RegisterType((*Empty)(nil), "google.protobuf.Empty") } func init() { proto.RegisterFile("google/protobuf/empty.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 148 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcd, 0x2d, 0x28, 0xa9, 0xd4, 0x03, 0x73, 0x85, 0xf8, 0x21, 0x92, 0x7a, 0x30, 0x49, 0x25, 0x76, 0x2e, 0x56, 0x57, 0x90, 0xbc, 0x53, 0x19, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0xbc, 0x13, 0x17, 0x58, 0x36, 0x00, 0xc4, 0x0d, 0x60, 0x8c, 0x52, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0x58, 0x53, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x0c, 0xb1, 0xed, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10, 0x13, 0x03, 0xa0, 0xea, 0xf4, 0xc2, 0x53, 0x73, 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40, 0xea, 0x93, 0xd8, 0xc0, 0x06, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd4, 0xb3, 0xa6, 0xb7, 0x00, 0x00, 0x00, } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/duration_test.go������������������������������0000644�0610621�0607500�00000012114�13172163407�027132� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package ptypes import ( "math" "testing" "time" "github.com/golang/protobuf/proto" durpb "github.com/golang/protobuf/ptypes/duration" ) const ( minGoSeconds = math.MinInt64 / int64(1e9) maxGoSeconds = math.MaxInt64 / int64(1e9) ) var durationTests = []struct { proto *durpb.Duration isValid bool inRange bool dur time.Duration }{ // The zero duration. {&durpb.Duration{Seconds: 0, Nanos: 0}, true, true, 0}, // Some ordinary non-zero durations. {&durpb.Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second}, {&durpb.Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second}, {&durpb.Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987}, {&durpb.Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)}, // The largest duration representable in Go. {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64}, // The smallest duration representable in Go. {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64}, {nil, false, false, 0}, {&durpb.Duration{Seconds: -100, Nanos: 987}, false, false, 0}, {&durpb.Duration{Seconds: 100, Nanos: -987}, false, false, 0}, {&durpb.Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0}, {&durpb.Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0}, // The largest valid duration. {&durpb.Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0}, // The smallest valid duration. {&durpb.Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0}, // The smallest invalid duration above the valid range. {&durpb.Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0}, // The largest invalid duration below the valid range. {&durpb.Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0}, // One nanosecond past the largest duration representable in Go. {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0}, // One nanosecond past the smallest duration representable in Go. {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0}, // One second past the largest duration representable in Go. {&durpb.Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0}, // One second past the smallest duration representable in Go. {&durpb.Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0}, } func TestValidateDuration(t *testing.T) { for _, test := range durationTests { err := validateDuration(test.proto) gotValid := (err == nil) if gotValid != test.isValid { t.Errorf("validateDuration(%v) = %t, want %t", test.proto, gotValid, test.isValid) } } } func TestDuration(t *testing.T) { for _, test := range durationTests { got, err := Duration(test.proto) gotOK := (err == nil) wantOK := test.isValid && test.inRange if gotOK != wantOK { t.Errorf("Duration(%v) ok = %t, want %t", test.proto, gotOK, wantOK) } if err == nil && got != test.dur { t.Errorf("Duration(%v) = %v, want %v", test.proto, got, test.dur) } } } func TestDurationProto(t *testing.T) { for _, test := range durationTests { if test.isValid && test.inRange { got := DurationProto(test.dur) if !proto.Equal(got, test.proto) { t.Errorf("DurationProto(%v) = %v, want %v", test.dur, got, test.proto) } } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/duration/�������������������������������������0000755�0610621�0607500�00000000000�13172163407�025545� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/duration/duration.proto�����������������������0000644�0610621�0607500�00000011432�13172163407�030460� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "github.com/golang/protobuf/ptypes/duration"; option java_package = "com.google.protobuf"; option java_outer_classname = "DurationProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // A Duration represents a signed, fixed-length span of time represented // as a count of seconds and fractions of seconds at nanosecond // resolution. It is independent of any calendar and concepts like "day" // or "month". It is related to Timestamp in that the difference between // two Timestamp values is a Duration and it can be added or subtracted // from a Timestamp. Range is approximately +-10,000 years. // // # Examples // // Example 1: Compute Duration from two Timestamps in pseudo code. // // Timestamp start = ...; // Timestamp end = ...; // Duration duration = ...; // // duration.seconds = end.seconds - start.seconds; // duration.nanos = end.nanos - start.nanos; // // if (duration.seconds < 0 && duration.nanos > 0) { // duration.seconds += 1; // duration.nanos -= 1000000000; // } else if (durations.seconds > 0 && duration.nanos < 0) { // duration.seconds -= 1; // duration.nanos += 1000000000; // } // // Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. // // Timestamp start = ...; // Duration duration = ...; // Timestamp end = ...; // // end.seconds = start.seconds + duration.seconds; // end.nanos = start.nanos + duration.nanos; // // if (end.nanos < 0) { // end.seconds -= 1; // end.nanos += 1000000000; // } else if (end.nanos >= 1000000000) { // end.seconds += 1; // end.nanos -= 1000000000; // } // // Example 3: Compute Duration from datetime.timedelta in Python. // // td = datetime.timedelta(days=3, minutes=10) // duration = Duration() // duration.FromTimedelta(td) // // # JSON Mapping // // In JSON format, the Duration type is encoded as a string rather than an // object, where the string ends in the suffix "s" (indicating seconds) and // is preceded by the number of seconds, with nanoseconds expressed as // fractional seconds. For example, 3 seconds with 0 nanoseconds should be // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 // microsecond should be expressed in JSON format as "3.000001s". // // message Duration { // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years int64 seconds = 1; // Signed fractions of a second at nanosecond resolution of the span // of time. Durations less than one second are represented with a 0 // `seconds` field and a positive or negative `nanos` field. For durations // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. int32 nanos = 2; } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/duration/duration.pb.go�����������������������0000644�0610621�0607500�00000013127�13172163407�030325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/duration.proto /* Package duration is a generated protocol buffer package. It is generated from these files: google/protobuf/duration.proto It has these top-level messages: Duration */ package duration import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // A Duration represents a signed, fixed-length span of time represented // as a count of seconds and fractions of seconds at nanosecond // resolution. It is independent of any calendar and concepts like "day" // or "month". It is related to Timestamp in that the difference between // two Timestamp values is a Duration and it can be added or subtracted // from a Timestamp. Range is approximately +-10,000 years. // // # Examples // // Example 1: Compute Duration from two Timestamps in pseudo code. // // Timestamp start = ...; // Timestamp end = ...; // Duration duration = ...; // // duration.seconds = end.seconds - start.seconds; // duration.nanos = end.nanos - start.nanos; // // if (duration.seconds < 0 && duration.nanos > 0) { // duration.seconds += 1; // duration.nanos -= 1000000000; // } else if (durations.seconds > 0 && duration.nanos < 0) { // duration.seconds -= 1; // duration.nanos += 1000000000; // } // // Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. // // Timestamp start = ...; // Duration duration = ...; // Timestamp end = ...; // // end.seconds = start.seconds + duration.seconds; // end.nanos = start.nanos + duration.nanos; // // if (end.nanos < 0) { // end.seconds -= 1; // end.nanos += 1000000000; // } else if (end.nanos >= 1000000000) { // end.seconds += 1; // end.nanos -= 1000000000; // } // // Example 3: Compute Duration from datetime.timedelta in Python. // // td = datetime.timedelta(days=3, minutes=10) // duration = Duration() // duration.FromTimedelta(td) // // # JSON Mapping // // In JSON format, the Duration type is encoded as a string rather than an // object, where the string ends in the suffix "s" (indicating seconds) and // is preceded by the number of seconds, with nanoseconds expressed as // fractional seconds. For example, 3 seconds with 0 nanoseconds should be // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 // microsecond should be expressed in JSON format as "3.000001s". // // type Duration struct { // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` // Signed fractions of a second at nanosecond resolution of the span // of time. Durations less than one second are represented with a 0 // `seconds` field and a positive or negative `nanos` field. For durations // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` } func (m *Duration) Reset() { *m = Duration{} } func (m *Duration) String() string { return proto.CompactTextString(m) } func (*Duration) ProtoMessage() {} func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Duration) XXX_WellKnownType() string { return "Duration" } func (m *Duration) GetSeconds() int64 { if m != nil { return m.Seconds } return 0 } func (m *Duration) GetNanos() int32 { if m != nil { return m.Nanos } return 0 } func init() { proto.RegisterType((*Duration)(nil), "google.protobuf.Duration") } func init() { proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 190 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a, 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56, 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e, 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c, 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78, 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00, } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/duration.go�����������������������������������0000644�0610621�0607500�00000007443�13172163407�026104� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package ptypes // This file implements conversions between google.protobuf.Duration // and time.Duration. import ( "errors" "fmt" "time" durpb "github.com/golang/protobuf/ptypes/duration" ) const ( // Range of a durpb.Duration in seconds, as specified in // google/protobuf/duration.proto. This is about 10,000 years in seconds. maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60) minSeconds = -maxSeconds ) // validateDuration determines whether the durpb.Duration is valid according to the // definition in google/protobuf/duration.proto. A valid durpb.Duration // may still be too large to fit into a time.Duration (the range of durpb.Duration // is about 10,000 years, and the range of time.Duration is about 290). func validateDuration(d *durpb.Duration) error { if d == nil { return errors.New("duration: nil Duration") } if d.Seconds < minSeconds || d.Seconds > maxSeconds { return fmt.Errorf("duration: %v: seconds out of range", d) } if d.Nanos <= -1e9 || d.Nanos >= 1e9 { return fmt.Errorf("duration: %v: nanos out of range", d) } // Seconds and Nanos must have the same sign, unless d.Nanos is zero. if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) { return fmt.Errorf("duration: %v: seconds and nanos have different signs", d) } return nil } // Duration converts a durpb.Duration to a time.Duration. Duration // returns an error if the durpb.Duration is invalid or is too large to be // represented in a time.Duration. func Duration(p *durpb.Duration) (time.Duration, error) { if err := validateDuration(p); err != nil { return 0, err } d := time.Duration(p.Seconds) * time.Second if int64(d/time.Second) != p.Seconds { return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) } if p.Nanos != 0 { d += time.Duration(p.Nanos) if (d < 0) != (p.Nanos < 0) { return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) } } return d, nil } // DurationProto converts a time.Duration to a durpb.Duration. func DurationProto(d time.Duration) *durpb.Duration { nanos := d.Nanoseconds() secs := nanos / 1e9 nanos -= secs * 1e9 return &durpb.Duration{ Seconds: secs, Nanos: int32(nanos), } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/doc.go����������������������������������������0000644�0610621�0607500�00000003336�13172163407�025021� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Package ptypes contains code for interacting with well-known types. */ package ptypes ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/any_test.go�����������������������������������0000644�0610621�0607500�00000007401�13172163407�026077� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package ptypes import ( "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/golang/protobuf/ptypes/any" ) func TestMarshalUnmarshal(t *testing.T) { orig := &any.Any{Value: []byte("test")} packed, err := MarshalAny(orig) if err != nil { t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err) } unpacked := &any.Any{} err = UnmarshalAny(packed, unpacked) if err != nil || !proto.Equal(unpacked, orig) { t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig) } } func TestIs(t *testing.T) { a, err := MarshalAny(&pb.FileDescriptorProto{}) if err != nil { t.Fatal(err) } if Is(a, &pb.DescriptorProto{}) { t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is") } if !Is(a, &pb.FileDescriptorProto{}) { t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not") } } func TestIsDifferentUrlPrefixes(t *testing.T) { m := &pb.FileDescriptorProto{} a := &any.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)} if !Is(a, m) { t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m)) } } func TestUnmarshalDynamic(t *testing.T) { want := &pb.FileDescriptorProto{Name: proto.String("foo")} a, err := MarshalAny(want) if err != nil { t.Fatal(err) } var got DynamicAny if err := UnmarshalAny(a, &got); err != nil { t.Fatal(err) } if !proto.Equal(got.Message, want) { t.Errorf("invalid result from UnmarshalAny, got %q want %q", got.Message, want) } } func TestEmpty(t *testing.T) { want := &pb.FileDescriptorProto{} a, err := MarshalAny(want) if err != nil { t.Fatal(err) } got, err := Empty(a) if err != nil { t.Fatal(err) } if !proto.Equal(got, want) { t.Errorf("unequal empty message, got %q, want %q", got, want) } // that's a valid type_url for a message which shouldn't be linked into this // test binary. We want an error. a.TypeUrl = "type.googleapis.com/google.protobuf.FieldMask" if _, err := Empty(a); err == nil { t.Errorf("got no error for an attempt to create a message of type %q, which shouldn't be linked in", a.TypeUrl) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/any/������������������������������������������0000755�0610621�0607500�00000000000�13172163407�024507� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/any/any.proto���������������������������������0000644�0610621�0607500�00000012553�13172163407�026371� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "github.com/golang/protobuf/ptypes/any"; option java_package = "com.google.protobuf"; option java_outer_classname = "AnyProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // `Any` contains an arbitrary serialized protocol buffer message along with a // URL that describes the type of the serialized message. // // Protobuf library provides support to pack/unpack Any values in the form // of utility functions or additional generated methods of the Any type. // // Example 1: Pack and unpack a message in C++. // // Foo foo = ...; // Any any; // any.PackFrom(foo); // ... // if (any.UnpackTo(&foo)) { // ... // } // // Example 2: Pack and unpack a message in Java. // // Foo foo = ...; // Any any = Any.pack(foo); // ... // if (any.is(Foo.class)) { // foo = any.unpack(Foo.class); // } // // Example 3: Pack and unpack a message in Python. // // foo = Foo(...) // any = Any() // any.Pack(foo) // ... // if any.Is(Foo.DESCRIPTOR): // any.Unpack(foo) // ... // // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} // any, err := ptypes.MarshalAny(foo) // ... // foo := &pb.Foo{} // if err := ptypes.UnmarshalAny(any, foo); err != nil { // ... // } // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". // // // JSON // ==== // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": <string>, // "lastName": <string> // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } // message Any { // A URL/resource name whose content describes the type of the // serialized protocol buffer message. // // For URLs which use the scheme `http`, `https`, or no scheme, the // following restrictions and interpretations apply: // // * If no scheme is provided, `https` is assumed. // * The last segment of the URL's path must represent the fully // qualified name of the type (as in `path/google.protobuf.Duration`). // The name should be in a canonical form (e.g., leading "." is // not accepted). // * An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // * Applications are allowed to cache lookup results based on the // URL, or have them precompiled into a binary to avoid any // lookup. Therefore, binary compatibility needs to be preserved // on changes to types. (Use versioned type names to manage // breaking changes.) // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. // string type_url = 1; // Must be a valid serialized protocol buffer of the above specified type. bytes value = 2; } �����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/any/any.pb.go���������������������������������0000644�0610621�0607500�00000014153�13172163407�026231� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/any.proto /* Package any is a generated protocol buffer package. It is generated from these files: google/protobuf/any.proto It has these top-level messages: Any */ package any import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // `Any` contains an arbitrary serialized protocol buffer message along with a // URL that describes the type of the serialized message. // // Protobuf library provides support to pack/unpack Any values in the form // of utility functions or additional generated methods of the Any type. // // Example 1: Pack and unpack a message in C++. // // Foo foo = ...; // Any any; // any.PackFrom(foo); // ... // if (any.UnpackTo(&foo)) { // ... // } // // Example 2: Pack and unpack a message in Java. // // Foo foo = ...; // Any any = Any.pack(foo); // ... // if (any.is(Foo.class)) { // foo = any.unpack(Foo.class); // } // // Example 3: Pack and unpack a message in Python. // // foo = Foo(...) // any = Any() // any.Pack(foo) // ... // if any.Is(Foo.DESCRIPTOR): // any.Unpack(foo) // ... // // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} // any, err := ptypes.MarshalAny(foo) // ... // foo := &pb.Foo{} // if err := ptypes.UnmarshalAny(any, foo); err != nil { // ... // } // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". // // // JSON // ==== // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": <string>, // "lastName": <string> // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } // type Any struct { // A URL/resource name whose content describes the type of the // serialized protocol buffer message. // // For URLs which use the scheme `http`, `https`, or no scheme, the // following restrictions and interpretations apply: // // * If no scheme is provided, `https` is assumed. // * The last segment of the URL's path must represent the fully // qualified name of the type (as in `path/google.protobuf.Duration`). // The name should be in a canonical form (e.g., leading "." is // not accepted). // * An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // * Applications are allowed to cache lookup results based on the // URL, or have them precompiled into a binary to avoid any // lookup. Therefore, binary compatibility needs to be preserved // on changes to types. (Use versioned type names to manage // breaking changes.) // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. // TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl" json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } func (m *Any) Reset() { *m = Any{} } func (m *Any) String() string { return proto.CompactTextString(m) } func (*Any) ProtoMessage() {} func (*Any) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Any) XXX_WellKnownType() string { return "Any" } func (m *Any) GetTypeUrl() string { if m != nil { return m.TypeUrl } return "" } func (m *Any) GetValue() []byte { if m != nil { return m.Value } return nil } func init() { proto.RegisterType((*Any)(nil), "google.protobuf.Any") } func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 185 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4, 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a, 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7, 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce, 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52, 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c, 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce, 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00, } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/ptypes/any.go����������������������������������������0000644�0610621�0607500�00000011213�13172163407�025034� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package ptypes // This file implements functions to marshal proto.Message to/from // google.protobuf.Any message. import ( "fmt" "reflect" "strings" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/any" ) const googleApis = "type.googleapis.com/" // AnyMessageName returns the name of the message contained in a google.protobuf.Any message. // // Note that regular type assertions should be done using the Is // function. AnyMessageName is provided for less common use cases like filtering a // sequence of Any messages based on a set of allowed message type names. func AnyMessageName(any *any.Any) (string, error) { if any == nil { return "", fmt.Errorf("message is nil") } slash := strings.LastIndex(any.TypeUrl, "/") if slash < 0 { return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl) } return any.TypeUrl[slash+1:], nil } // MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any. func MarshalAny(pb proto.Message) (*any.Any, error) { value, err := proto.Marshal(pb) if err != nil { return nil, err } return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil } // DynamicAny is a value that can be passed to UnmarshalAny to automatically // allocate a proto.Message for the type specified in a google.protobuf.Any // message. The allocated message is stored in the embedded proto.Message. // // Example: // // var x ptypes.DynamicAny // if err := ptypes.UnmarshalAny(a, &x); err != nil { ... } // fmt.Printf("unmarshaled message: %v", x.Message) type DynamicAny struct { proto.Message } // Empty returns a new proto.Message of the type specified in a // google.protobuf.Any message. It returns an error if corresponding message // type isn't linked in. func Empty(any *any.Any) (proto.Message, error) { aname, err := AnyMessageName(any) if err != nil { return nil, err } t := proto.MessageType(aname) if t == nil { return nil, fmt.Errorf("any: message type %q isn't linked in", aname) } return reflect.New(t.Elem()).Interface().(proto.Message), nil } // UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any // message and places the decoded result in pb. It returns an error if type of // contents of Any message does not match type of pb message. // // pb can be a proto.Message, or a *DynamicAny. func UnmarshalAny(any *any.Any, pb proto.Message) error { if d, ok := pb.(*DynamicAny); ok { if d.Message == nil { var err error d.Message, err = Empty(any) if err != nil { return err } } return UnmarshalAny(any, d.Message) } aname, err := AnyMessageName(any) if err != nil { return err } mname := proto.MessageName(pb) if aname != mname { return fmt.Errorf("mismatched message type: got %q want %q", aname, mname) } return proto.Unmarshal(any.Value, pb) } // Is returns true if any value contains a given message type. func Is(any *any.Any, pb proto.Message) bool { aname, err := AnyMessageName(any) if err != nil { return false } return aname == proto.MessageName(pb) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/���������������������������������������0000755�0610621�0607500�00000000000�13172163407�025054� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/������������������������������0000755�0610621�0607500�00000000000�13172163407�026665� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/proto3.proto������������������0000644�0610621�0607500�00000003723�13172163407�031205� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package proto3; message Request { enum Flavour { SWEET = 0; SOUR = 1; UMAMI = 2; GOPHERLICIOUS = 3; } string name = 1; repeated int64 key = 2; Flavour taste = 3; Book book = 4; repeated int64 unpacked = 5 [packed=false]; } message Book { string title = 1; bytes raw_data = 2; } ���������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/����������������������0000755�0610621�0607500�00000000000�13172163407�030351� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto������������0000644�0610621�0607500�00000010653�13172163407�032422� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; // This package holds interesting messages. package my.test; // dotted package name //import "imp.proto"; import "multi/multi1.proto"; // unused import enum HatType { // deliberately skipping 0 FEDORA = 1; FEZ = 2; } // This enum represents days of the week. enum Days { option allow_alias = true; MONDAY = 1; TUESDAY = 2; LUNDI = 1; // same value as MONDAY } // This is a message that might be sent somewhere. message Request { enum Color { RED = 0; GREEN = 1; BLUE = 2; } repeated int64 key = 1; // optional imp.ImportedMessage imported_message = 2; optional Color hue = 3; // no default optional HatType hat = 4 [default=FEDORA]; // optional imp.ImportedMessage.Owner owner = 6; optional float deadline = 7 [default=inf]; optional group SomeGroup = 8 { optional int32 group_field = 9; } // These foreign types are in imp2.proto, // which is publicly imported by imp.proto. // optional imp.PubliclyImportedMessage pub = 10; // optional imp.PubliclyImportedEnum pub_enum = 13 [default=HAIR]; // This is a map field. It will generate map[int32]string. map<int32, string> name_mapping = 14; // This is a map field whose value type is a message. map<sint64, Reply> msg_mapping = 15; optional int32 reset = 12; // This field should not conflict with any getters. optional string get_key = 16; } message Reply { message Entry { required int64 key_that_needs_1234camel_CasIng = 1; optional int64 value = 2 [default=7]; optional int64 _my_field_name_2 = 3; enum Game { FOOTBALL = 1; TENNIS = 2; } } repeated Entry found = 1; repeated int32 compact_keys = 2 [packed=true]; extensions 100 to max; } message OtherBase { optional string name = 1; extensions 100 to max; } message ReplyExtensions { extend Reply { optional double time = 101; optional ReplyExtensions carrot = 105; } extend OtherBase { optional ReplyExtensions donut = 101; } } message OtherReplyExtensions { optional int32 key = 1; } // top-level extension extend Reply { optional string tag = 103; optional OtherReplyExtensions donut = 106; // optional imp.ImportedMessage elephant = 107; // extend with message from another file. } message OldReply { // Extensions will be encoded in MessageSet wire format. option message_set_wire_format = true; extensions 100 to max; } message Communique { optional bool make_me_cry = 1; // This is a oneof, called "union". oneof union { int32 number = 5; string name = 6; bytes data = 7; double temp_c = 8; float height = 9; Days today = 10; bool maybe = 11; sint32 delta = 12; // name will conflict with Delta below Reply msg = 13; group SomeGroup = 14 { optional string member = 15; } } message Delta {} } �������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden�����0000644�0610621�0607500�00000057412�13172163407�033537� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: my_test/test.proto /* Package my_test is a generated protocol buffer package. This package holds interesting messages. It is generated from these files: my_test/test.proto It has these top-level messages: Request Reply OtherBase ReplyExtensions OtherReplyExtensions OldReply Communique */ package my_test import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type HatType int32 const ( // deliberately skipping 0 HatType_FEDORA HatType = 1 HatType_FEZ HatType = 2 ) var HatType_name = map[int32]string{ 1: "FEDORA", 2: "FEZ", } var HatType_value = map[string]int32{ "FEDORA": 1, "FEZ": 2, } func (x HatType) Enum() *HatType { p := new(HatType) *p = x return p } func (x HatType) String() string { return proto.EnumName(HatType_name, int32(x)) } func (x *HatType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType") if err != nil { return err } *x = HatType(value) return nil } // This enum represents days of the week. type Days int32 const ( Days_MONDAY Days = 1 Days_TUESDAY Days = 2 Days_LUNDI Days = 1 ) var Days_name = map[int32]string{ 1: "MONDAY", 2: "TUESDAY", // Duplicate value: 1: "LUNDI", } var Days_value = map[string]int32{ "MONDAY": 1, "TUESDAY": 2, "LUNDI": 1, } func (x Days) Enum() *Days { p := new(Days) *p = x return p } func (x Days) String() string { return proto.EnumName(Days_name, int32(x)) } func (x *Days) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days") if err != nil { return err } *x = Days(value) return nil } type Request_Color int32 const ( Request_RED Request_Color = 0 Request_GREEN Request_Color = 1 Request_BLUE Request_Color = 2 ) var Request_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Request_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Request_Color) Enum() *Request_Color { p := new(Request_Color) *p = x return p } func (x Request_Color) String() string { return proto.EnumName(Request_Color_name, int32(x)) } func (x *Request_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color") if err != nil { return err } *x = Request_Color(value) return nil } type Reply_Entry_Game int32 const ( Reply_Entry_FOOTBALL Reply_Entry_Game = 1 Reply_Entry_TENNIS Reply_Entry_Game = 2 ) var Reply_Entry_Game_name = map[int32]string{ 1: "FOOTBALL", 2: "TENNIS", } var Reply_Entry_Game_value = map[string]int32{ "FOOTBALL": 1, "TENNIS": 2, } func (x Reply_Entry_Game) Enum() *Reply_Entry_Game { p := new(Reply_Entry_Game) *p = x return p } func (x Reply_Entry_Game) String() string { return proto.EnumName(Reply_Entry_Game_name, int32(x)) } func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game") if err != nil { return err } *x = Reply_Entry_Game(value) return nil } // This is a message that might be sent somewhere. type Request struct { Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"` // optional imp.ImportedMessage imported_message = 2; Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"` Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"` // optional imp.ImportedMessage.Owner owner = 6; Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"` Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` // This is a map field. It will generate map[int32]string. NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // This is a map field whose value type is a message. MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"` // This field should not conflict with any getters. GetKey_ *string `protobuf:"bytes,16,opt,name=get_key,json=getKey" json:"get_key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} const Default_Request_Hat HatType = HatType_FEDORA var Default_Request_Deadline float32 = float32(math.Inf(1)) func (m *Request) GetKey() []int64 { if m != nil { return m.Key } return nil } func (m *Request) GetHue() Request_Color { if m != nil && m.Hue != nil { return *m.Hue } return Request_RED } func (m *Request) GetHat() HatType { if m != nil && m.Hat != nil { return *m.Hat } return Default_Request_Hat } func (m *Request) GetDeadline() float32 { if m != nil && m.Deadline != nil { return *m.Deadline } return Default_Request_Deadline } func (m *Request) GetSomegroup() *Request_SomeGroup { if m != nil { return m.Somegroup } return nil } func (m *Request) GetNameMapping() map[int32]string { if m != nil { return m.NameMapping } return nil } func (m *Request) GetMsgMapping() map[int64]*Reply { if m != nil { return m.MsgMapping } return nil } func (m *Request) GetReset_() int32 { if m != nil && m.Reset_ != nil { return *m.Reset_ } return 0 } func (m *Request) GetGetKey_() string { if m != nil && m.GetKey_ != nil { return *m.GetKey_ } return "" } type Request_SomeGroup struct { GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} } func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Request_SomeGroup) ProtoMessage() {} func (m *Request_SomeGroup) GetGroupField() int32 { if m != nil && m.GroupField != nil { return *m.GroupField } return 0 } type Reply struct { Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"` CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys,json=compactKeys" json:"compact_keys,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Reply) Reset() { *m = Reply{} } func (m *Reply) String() string { return proto.CompactTextString(m) } func (*Reply) ProtoMessage() {} var extRange_Reply = []proto.ExtensionRange{ {100, 536870911}, } func (*Reply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Reply } func (m *Reply) GetFound() []*Reply_Entry { if m != nil { return m.Found } return nil } func (m *Reply) GetCompactKeys() []int32 { if m != nil { return m.CompactKeys } return nil } type Reply_Entry struct { KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng,json=keyThatNeeds1234camelCasIng" json:"key_that_needs_1234camel_CasIng,omitempty"` Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"` XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2,json=MyFieldName2" json:"_my_field_name_2,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Reply_Entry) Reset() { *m = Reply_Entry{} } func (m *Reply_Entry) String() string { return proto.CompactTextString(m) } func (*Reply_Entry) ProtoMessage() {} const Default_Reply_Entry_Value int64 = 7 func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 { if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil { return *m.KeyThatNeeds_1234Camel_CasIng } return 0 } func (m *Reply_Entry) GetValue() int64 { if m != nil && m.Value != nil { return *m.Value } return Default_Reply_Entry_Value } func (m *Reply_Entry) GetXMyFieldName_2() int64 { if m != nil && m.XMyFieldName_2 != nil { return *m.XMyFieldName_2 } return 0 } type OtherBase struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OtherBase) Reset() { *m = OtherBase{} } func (m *OtherBase) String() string { return proto.CompactTextString(m) } func (*OtherBase) ProtoMessage() {} var extRange_OtherBase = []proto.ExtensionRange{ {100, 536870911}, } func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OtherBase } func (m *OtherBase) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } type ReplyExtensions struct { XXX_unrecognized []byte `json:"-"` } func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} } func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) } func (*ReplyExtensions) ProtoMessage() {} var E_ReplyExtensions_Time = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*float64)(nil), Field: 101, Name: "my.test.ReplyExtensions.time", Tag: "fixed64,101,opt,name=time", Filename: "my_test/test.proto", } var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 105, Name: "my.test.ReplyExtensions.carrot", Tag: "bytes,105,opt,name=carrot", Filename: "my_test/test.proto", } var E_ReplyExtensions_Donut = &proto.ExtensionDesc{ ExtendedType: (*OtherBase)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 101, Name: "my.test.ReplyExtensions.donut", Tag: "bytes,101,opt,name=donut", Filename: "my_test/test.proto", } type OtherReplyExtensions struct { Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} } func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) } func (*OtherReplyExtensions) ProtoMessage() {} func (m *OtherReplyExtensions) GetKey() int32 { if m != nil && m.Key != nil { return *m.Key } return 0 } type OldReply struct { proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OldReply) Reset() { *m = OldReply{} } func (m *OldReply) String() string { return proto.CompactTextString(m) } func (*OldReply) ProtoMessage() {} func (m *OldReply) Marshal() ([]byte, error) { return proto.MarshalMessageSet(&m.XXX_InternalExtensions) } func (m *OldReply) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions) } func (m *OldReply) MarshalJSON() ([]byte, error) { return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) } func (m *OldReply) UnmarshalJSON(buf []byte) error { return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) } // ensure OldReply satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*OldReply)(nil) var _ proto.Unmarshaler = (*OldReply)(nil) var extRange_OldReply = []proto.ExtensionRange{ {100, 2147483646}, } func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OldReply } type Communique struct { MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` // This is a oneof, called "union". // // Types that are valid to be assigned to Union: // *Communique_Number // *Communique_Name // *Communique_Data // *Communique_TempC // *Communique_Height // *Communique_Today // *Communique_Maybe // *Communique_Delta_ // *Communique_Msg // *Communique_Somegroup Union isCommunique_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Communique) Reset() { *m = Communique{} } func (m *Communique) String() string { return proto.CompactTextString(m) } func (*Communique) ProtoMessage() {} type isCommunique_Union interface { isCommunique_Union() } type Communique_Number struct { Number int32 `protobuf:"varint,5,opt,name=number,oneof"` } type Communique_Name struct { Name string `protobuf:"bytes,6,opt,name=name,oneof"` } type Communique_Data struct { Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` } type Communique_TempC struct { TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` } type Communique_Height struct { Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"` } type Communique_Today struct { Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"` } type Communique_Maybe struct { Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"` } type Communique_Delta_ struct { Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"` } type Communique_Msg struct { Msg *Reply `protobuf:"bytes,13,opt,name=msg,oneof"` } type Communique_Somegroup struct { Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,json=somegroup,oneof"` } func (*Communique_Number) isCommunique_Union() {} func (*Communique_Name) isCommunique_Union() {} func (*Communique_Data) isCommunique_Union() {} func (*Communique_TempC) isCommunique_Union() {} func (*Communique_Height) isCommunique_Union() {} func (*Communique_Today) isCommunique_Union() {} func (*Communique_Maybe) isCommunique_Union() {} func (*Communique_Delta_) isCommunique_Union() {} func (*Communique_Msg) isCommunique_Union() {} func (*Communique_Somegroup) isCommunique_Union() {} func (m *Communique) GetUnion() isCommunique_Union { if m != nil { return m.Union } return nil } func (m *Communique) GetMakeMeCry() bool { if m != nil && m.MakeMeCry != nil { return *m.MakeMeCry } return false } func (m *Communique) GetNumber() int32 { if x, ok := m.GetUnion().(*Communique_Number); ok { return x.Number } return 0 } func (m *Communique) GetName() string { if x, ok := m.GetUnion().(*Communique_Name); ok { return x.Name } return "" } func (m *Communique) GetData() []byte { if x, ok := m.GetUnion().(*Communique_Data); ok { return x.Data } return nil } func (m *Communique) GetTempC() float64 { if x, ok := m.GetUnion().(*Communique_TempC); ok { return x.TempC } return 0 } func (m *Communique) GetHeight() float32 { if x, ok := m.GetUnion().(*Communique_Height); ok { return x.Height } return 0 } func (m *Communique) GetToday() Days { if x, ok := m.GetUnion().(*Communique_Today); ok { return x.Today } return Days_MONDAY } func (m *Communique) GetMaybe() bool { if x, ok := m.GetUnion().(*Communique_Maybe); ok { return x.Maybe } return false } func (m *Communique) GetDelta() int32 { if x, ok := m.GetUnion().(*Communique_Delta_); ok { return x.Delta } return 0 } func (m *Communique) GetMsg() *Reply { if x, ok := m.GetUnion().(*Communique_Msg); ok { return x.Msg } return nil } func (m *Communique) GetSomegroup() *Communique_SomeGroup { if x, ok := m.GetUnion().(*Communique_Somegroup); ok { return x.Somegroup } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ (*Communique_Number)(nil), (*Communique_Name)(nil), (*Communique_Data)(nil), (*Communique_TempC)(nil), (*Communique_Height)(nil), (*Communique_Today)(nil), (*Communique_Maybe)(nil), (*Communique_Delta_)(nil), (*Communique_Msg)(nil), (*Communique_Somegroup)(nil), } } func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: b.EncodeVarint(5<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Number)) case *Communique_Name: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.Name) case *Communique_Data: b.EncodeVarint(7<<3 | proto.WireBytes) b.EncodeRawBytes(x.Data) case *Communique_TempC: b.EncodeVarint(8<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.TempC)) case *Communique_Height: b.EncodeVarint(9<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.Height))) case *Communique_Today: b.EncodeVarint(10<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Today)) case *Communique_Maybe: t := uint64(0) if x.Maybe { t = 1 } b.EncodeVarint(11<<3 | proto.WireVarint) b.EncodeVarint(t) case *Communique_Delta_: b.EncodeVarint(12<<3 | proto.WireVarint) b.EncodeZigzag32(uint64(x.Delta)) case *Communique_Msg: b.EncodeVarint(13<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Msg); err != nil { return err } case *Communique_Somegroup: b.EncodeVarint(14<<3 | proto.WireStartGroup) if err := b.Marshal(x.Somegroup); err != nil { return err } b.EncodeVarint(14<<3 | proto.WireEndGroup) case nil: default: return fmt.Errorf("Communique.Union has unexpected type %T", x) } return nil } func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Communique) switch tag { case 5: // union.number if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Number{int32(x)} return true, err case 6: // union.name if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Communique_Name{x} return true, err case 7: // union.data if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Communique_Data{x} return true, err case 8: // union.temp_c if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Communique_TempC{math.Float64frombits(x)} return true, err case 9: // union.height if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Communique_Height{math.Float32frombits(uint32(x))} return true, err case 10: // union.today if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Today{Days(x)} return true, err case 11: // union.maybe if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Maybe{x != 0} return true, err case 12: // union.delta if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.Union = &Communique_Delta_{int32(x)} return true, err case 13: // union.msg if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Reply) err := b.DecodeMessage(msg) m.Union = &Communique_Msg{msg} return true, err case 14: // union.somegroup if wire != proto.WireStartGroup { return true, proto.ErrInternalBadWireType } msg := new(Communique_SomeGroup) err := b.DecodeGroup(msg) m.Union = &Communique_Somegroup{msg} return true, err default: return false, nil } } func _Communique_OneofSizer(msg proto.Message) (n int) { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Number)) case *Communique_Name: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Name))) n += len(x.Name) case *Communique_Data: n += proto.SizeVarint(7<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Data))) n += len(x.Data) case *Communique_TempC: n += proto.SizeVarint(8<<3 | proto.WireFixed64) n += 8 case *Communique_Height: n += proto.SizeVarint(9<<3 | proto.WireFixed32) n += 4 case *Communique_Today: n += proto.SizeVarint(10<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Today)) case *Communique_Maybe: n += proto.SizeVarint(11<<3 | proto.WireVarint) n += 1 case *Communique_Delta_: n += proto.SizeVarint(12<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31)))) case *Communique_Msg: s := proto.Size(x.Msg) n += proto.SizeVarint(13<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Communique_Somegroup: n += proto.SizeVarint(14<<3 | proto.WireStartGroup) n += proto.Size(x.Somegroup) n += proto.SizeVarint(14<<3 | proto.WireEndGroup) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Communique_SomeGroup struct { Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} } func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Communique_SomeGroup) ProtoMessage() {} func (m *Communique_SomeGroup) GetMember() string { if m != nil && m.Member != nil { return *m.Member } return "" } type Communique_Delta struct { XXX_unrecognized []byte `json:"-"` } func (m *Communique_Delta) Reset() { *m = Communique_Delta{} } func (m *Communique_Delta) String() string { return proto.CompactTextString(m) } func (*Communique_Delta) ProtoMessage() {} var E_Tag = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*string)(nil), Field: 103, Name: "my.test.tag", Tag: "bytes,103,opt,name=tag", Filename: "my_test/test.proto", } var E_Donut = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*OtherReplyExtensions)(nil), Field: 106, Name: "my.test.donut", Tag: "bytes,106,opt,name=donut", Filename: "my_test/test.proto", } func init() { proto.RegisterType((*Request)(nil), "my.test.Request") proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup") proto.RegisterType((*Reply)(nil), "my.test.Reply") proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry") proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase") proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions") proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions") proto.RegisterType((*OldReply)(nil), "my.test.OldReply") proto.RegisterType((*Communique)(nil), "my.test.Communique") proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup") proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta") proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value) proto.RegisterEnum("my.test.Days", Days_name, Days_value) proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value) proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value) proto.RegisterExtension(E_ReplyExtensions_Time) proto.RegisterExtension(E_ReplyExtensions_Carrot) proto.RegisterExtension(E_ReplyExtensions_Donut) proto.RegisterExtension(E_Tag) proto.RegisterExtension(E_Donut) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go������������0000644�0610621�0607500�00000057412�13172163407�032270� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: my_test/test.proto /* Package my_test is a generated protocol buffer package. This package holds interesting messages. It is generated from these files: my_test/test.proto It has these top-level messages: Request Reply OtherBase ReplyExtensions OtherReplyExtensions OldReply Communique */ package my_test import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type HatType int32 const ( // deliberately skipping 0 HatType_FEDORA HatType = 1 HatType_FEZ HatType = 2 ) var HatType_name = map[int32]string{ 1: "FEDORA", 2: "FEZ", } var HatType_value = map[string]int32{ "FEDORA": 1, "FEZ": 2, } func (x HatType) Enum() *HatType { p := new(HatType) *p = x return p } func (x HatType) String() string { return proto.EnumName(HatType_name, int32(x)) } func (x *HatType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType") if err != nil { return err } *x = HatType(value) return nil } // This enum represents days of the week. type Days int32 const ( Days_MONDAY Days = 1 Days_TUESDAY Days = 2 Days_LUNDI Days = 1 ) var Days_name = map[int32]string{ 1: "MONDAY", 2: "TUESDAY", // Duplicate value: 1: "LUNDI", } var Days_value = map[string]int32{ "MONDAY": 1, "TUESDAY": 2, "LUNDI": 1, } func (x Days) Enum() *Days { p := new(Days) *p = x return p } func (x Days) String() string { return proto.EnumName(Days_name, int32(x)) } func (x *Days) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days") if err != nil { return err } *x = Days(value) return nil } type Request_Color int32 const ( Request_RED Request_Color = 0 Request_GREEN Request_Color = 1 Request_BLUE Request_Color = 2 ) var Request_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Request_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Request_Color) Enum() *Request_Color { p := new(Request_Color) *p = x return p } func (x Request_Color) String() string { return proto.EnumName(Request_Color_name, int32(x)) } func (x *Request_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color") if err != nil { return err } *x = Request_Color(value) return nil } type Reply_Entry_Game int32 const ( Reply_Entry_FOOTBALL Reply_Entry_Game = 1 Reply_Entry_TENNIS Reply_Entry_Game = 2 ) var Reply_Entry_Game_name = map[int32]string{ 1: "FOOTBALL", 2: "TENNIS", } var Reply_Entry_Game_value = map[string]int32{ "FOOTBALL": 1, "TENNIS": 2, } func (x Reply_Entry_Game) Enum() *Reply_Entry_Game { p := new(Reply_Entry_Game) *p = x return p } func (x Reply_Entry_Game) String() string { return proto.EnumName(Reply_Entry_Game_name, int32(x)) } func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game") if err != nil { return err } *x = Reply_Entry_Game(value) return nil } // This is a message that might be sent somewhere. type Request struct { Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"` // optional imp.ImportedMessage imported_message = 2; Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"` Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"` // optional imp.ImportedMessage.Owner owner = 6; Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"` Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` // This is a map field. It will generate map[int32]string. NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // This is a map field whose value type is a message. MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"` // This field should not conflict with any getters. GetKey_ *string `protobuf:"bytes,16,opt,name=get_key,json=getKey" json:"get_key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} const Default_Request_Hat HatType = HatType_FEDORA var Default_Request_Deadline float32 = float32(math.Inf(1)) func (m *Request) GetKey() []int64 { if m != nil { return m.Key } return nil } func (m *Request) GetHue() Request_Color { if m != nil && m.Hue != nil { return *m.Hue } return Request_RED } func (m *Request) GetHat() HatType { if m != nil && m.Hat != nil { return *m.Hat } return Default_Request_Hat } func (m *Request) GetDeadline() float32 { if m != nil && m.Deadline != nil { return *m.Deadline } return Default_Request_Deadline } func (m *Request) GetSomegroup() *Request_SomeGroup { if m != nil { return m.Somegroup } return nil } func (m *Request) GetNameMapping() map[int32]string { if m != nil { return m.NameMapping } return nil } func (m *Request) GetMsgMapping() map[int64]*Reply { if m != nil { return m.MsgMapping } return nil } func (m *Request) GetReset_() int32 { if m != nil && m.Reset_ != nil { return *m.Reset_ } return 0 } func (m *Request) GetGetKey_() string { if m != nil && m.GetKey_ != nil { return *m.GetKey_ } return "" } type Request_SomeGroup struct { GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} } func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Request_SomeGroup) ProtoMessage() {} func (m *Request_SomeGroup) GetGroupField() int32 { if m != nil && m.GroupField != nil { return *m.GroupField } return 0 } type Reply struct { Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"` CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys,json=compactKeys" json:"compact_keys,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Reply) Reset() { *m = Reply{} } func (m *Reply) String() string { return proto.CompactTextString(m) } func (*Reply) ProtoMessage() {} var extRange_Reply = []proto.ExtensionRange{ {100, 536870911}, } func (*Reply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Reply } func (m *Reply) GetFound() []*Reply_Entry { if m != nil { return m.Found } return nil } func (m *Reply) GetCompactKeys() []int32 { if m != nil { return m.CompactKeys } return nil } type Reply_Entry struct { KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng,json=keyThatNeeds1234camelCasIng" json:"key_that_needs_1234camel_CasIng,omitempty"` Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"` XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2,json=MyFieldName2" json:"_my_field_name_2,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Reply_Entry) Reset() { *m = Reply_Entry{} } func (m *Reply_Entry) String() string { return proto.CompactTextString(m) } func (*Reply_Entry) ProtoMessage() {} const Default_Reply_Entry_Value int64 = 7 func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 { if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil { return *m.KeyThatNeeds_1234Camel_CasIng } return 0 } func (m *Reply_Entry) GetValue() int64 { if m != nil && m.Value != nil { return *m.Value } return Default_Reply_Entry_Value } func (m *Reply_Entry) GetXMyFieldName_2() int64 { if m != nil && m.XMyFieldName_2 != nil { return *m.XMyFieldName_2 } return 0 } type OtherBase struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OtherBase) Reset() { *m = OtherBase{} } func (m *OtherBase) String() string { return proto.CompactTextString(m) } func (*OtherBase) ProtoMessage() {} var extRange_OtherBase = []proto.ExtensionRange{ {100, 536870911}, } func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OtherBase } func (m *OtherBase) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } type ReplyExtensions struct { XXX_unrecognized []byte `json:"-"` } func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} } func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) } func (*ReplyExtensions) ProtoMessage() {} var E_ReplyExtensions_Time = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*float64)(nil), Field: 101, Name: "my.test.ReplyExtensions.time", Tag: "fixed64,101,opt,name=time", Filename: "my_test/test.proto", } var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 105, Name: "my.test.ReplyExtensions.carrot", Tag: "bytes,105,opt,name=carrot", Filename: "my_test/test.proto", } var E_ReplyExtensions_Donut = &proto.ExtensionDesc{ ExtendedType: (*OtherBase)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 101, Name: "my.test.ReplyExtensions.donut", Tag: "bytes,101,opt,name=donut", Filename: "my_test/test.proto", } type OtherReplyExtensions struct { Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} } func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) } func (*OtherReplyExtensions) ProtoMessage() {} func (m *OtherReplyExtensions) GetKey() int32 { if m != nil && m.Key != nil { return *m.Key } return 0 } type OldReply struct { proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OldReply) Reset() { *m = OldReply{} } func (m *OldReply) String() string { return proto.CompactTextString(m) } func (*OldReply) ProtoMessage() {} func (m *OldReply) Marshal() ([]byte, error) { return proto.MarshalMessageSet(&m.XXX_InternalExtensions) } func (m *OldReply) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions) } func (m *OldReply) MarshalJSON() ([]byte, error) { return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) } func (m *OldReply) UnmarshalJSON(buf []byte) error { return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) } // ensure OldReply satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*OldReply)(nil) var _ proto.Unmarshaler = (*OldReply)(nil) var extRange_OldReply = []proto.ExtensionRange{ {100, 2147483646}, } func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OldReply } type Communique struct { MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` // This is a oneof, called "union". // // Types that are valid to be assigned to Union: // *Communique_Number // *Communique_Name // *Communique_Data // *Communique_TempC // *Communique_Height // *Communique_Today // *Communique_Maybe // *Communique_Delta_ // *Communique_Msg // *Communique_Somegroup Union isCommunique_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Communique) Reset() { *m = Communique{} } func (m *Communique) String() string { return proto.CompactTextString(m) } func (*Communique) ProtoMessage() {} type isCommunique_Union interface { isCommunique_Union() } type Communique_Number struct { Number int32 `protobuf:"varint,5,opt,name=number,oneof"` } type Communique_Name struct { Name string `protobuf:"bytes,6,opt,name=name,oneof"` } type Communique_Data struct { Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` } type Communique_TempC struct { TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` } type Communique_Height struct { Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"` } type Communique_Today struct { Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"` } type Communique_Maybe struct { Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"` } type Communique_Delta_ struct { Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"` } type Communique_Msg struct { Msg *Reply `protobuf:"bytes,13,opt,name=msg,oneof"` } type Communique_Somegroup struct { Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,json=somegroup,oneof"` } func (*Communique_Number) isCommunique_Union() {} func (*Communique_Name) isCommunique_Union() {} func (*Communique_Data) isCommunique_Union() {} func (*Communique_TempC) isCommunique_Union() {} func (*Communique_Height) isCommunique_Union() {} func (*Communique_Today) isCommunique_Union() {} func (*Communique_Maybe) isCommunique_Union() {} func (*Communique_Delta_) isCommunique_Union() {} func (*Communique_Msg) isCommunique_Union() {} func (*Communique_Somegroup) isCommunique_Union() {} func (m *Communique) GetUnion() isCommunique_Union { if m != nil { return m.Union } return nil } func (m *Communique) GetMakeMeCry() bool { if m != nil && m.MakeMeCry != nil { return *m.MakeMeCry } return false } func (m *Communique) GetNumber() int32 { if x, ok := m.GetUnion().(*Communique_Number); ok { return x.Number } return 0 } func (m *Communique) GetName() string { if x, ok := m.GetUnion().(*Communique_Name); ok { return x.Name } return "" } func (m *Communique) GetData() []byte { if x, ok := m.GetUnion().(*Communique_Data); ok { return x.Data } return nil } func (m *Communique) GetTempC() float64 { if x, ok := m.GetUnion().(*Communique_TempC); ok { return x.TempC } return 0 } func (m *Communique) GetHeight() float32 { if x, ok := m.GetUnion().(*Communique_Height); ok { return x.Height } return 0 } func (m *Communique) GetToday() Days { if x, ok := m.GetUnion().(*Communique_Today); ok { return x.Today } return Days_MONDAY } func (m *Communique) GetMaybe() bool { if x, ok := m.GetUnion().(*Communique_Maybe); ok { return x.Maybe } return false } func (m *Communique) GetDelta() int32 { if x, ok := m.GetUnion().(*Communique_Delta_); ok { return x.Delta } return 0 } func (m *Communique) GetMsg() *Reply { if x, ok := m.GetUnion().(*Communique_Msg); ok { return x.Msg } return nil } func (m *Communique) GetSomegroup() *Communique_SomeGroup { if x, ok := m.GetUnion().(*Communique_Somegroup); ok { return x.Somegroup } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ (*Communique_Number)(nil), (*Communique_Name)(nil), (*Communique_Data)(nil), (*Communique_TempC)(nil), (*Communique_Height)(nil), (*Communique_Today)(nil), (*Communique_Maybe)(nil), (*Communique_Delta_)(nil), (*Communique_Msg)(nil), (*Communique_Somegroup)(nil), } } func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: b.EncodeVarint(5<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Number)) case *Communique_Name: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.Name) case *Communique_Data: b.EncodeVarint(7<<3 | proto.WireBytes) b.EncodeRawBytes(x.Data) case *Communique_TempC: b.EncodeVarint(8<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.TempC)) case *Communique_Height: b.EncodeVarint(9<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.Height))) case *Communique_Today: b.EncodeVarint(10<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Today)) case *Communique_Maybe: t := uint64(0) if x.Maybe { t = 1 } b.EncodeVarint(11<<3 | proto.WireVarint) b.EncodeVarint(t) case *Communique_Delta_: b.EncodeVarint(12<<3 | proto.WireVarint) b.EncodeZigzag32(uint64(x.Delta)) case *Communique_Msg: b.EncodeVarint(13<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Msg); err != nil { return err } case *Communique_Somegroup: b.EncodeVarint(14<<3 | proto.WireStartGroup) if err := b.Marshal(x.Somegroup); err != nil { return err } b.EncodeVarint(14<<3 | proto.WireEndGroup) case nil: default: return fmt.Errorf("Communique.Union has unexpected type %T", x) } return nil } func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Communique) switch tag { case 5: // union.number if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Number{int32(x)} return true, err case 6: // union.name if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Communique_Name{x} return true, err case 7: // union.data if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Communique_Data{x} return true, err case 8: // union.temp_c if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Communique_TempC{math.Float64frombits(x)} return true, err case 9: // union.height if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Communique_Height{math.Float32frombits(uint32(x))} return true, err case 10: // union.today if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Today{Days(x)} return true, err case 11: // union.maybe if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Maybe{x != 0} return true, err case 12: // union.delta if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.Union = &Communique_Delta_{int32(x)} return true, err case 13: // union.msg if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Reply) err := b.DecodeMessage(msg) m.Union = &Communique_Msg{msg} return true, err case 14: // union.somegroup if wire != proto.WireStartGroup { return true, proto.ErrInternalBadWireType } msg := new(Communique_SomeGroup) err := b.DecodeGroup(msg) m.Union = &Communique_Somegroup{msg} return true, err default: return false, nil } } func _Communique_OneofSizer(msg proto.Message) (n int) { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Number)) case *Communique_Name: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Name))) n += len(x.Name) case *Communique_Data: n += proto.SizeVarint(7<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Data))) n += len(x.Data) case *Communique_TempC: n += proto.SizeVarint(8<<3 | proto.WireFixed64) n += 8 case *Communique_Height: n += proto.SizeVarint(9<<3 | proto.WireFixed32) n += 4 case *Communique_Today: n += proto.SizeVarint(10<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Today)) case *Communique_Maybe: n += proto.SizeVarint(11<<3 | proto.WireVarint) n += 1 case *Communique_Delta_: n += proto.SizeVarint(12<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31)))) case *Communique_Msg: s := proto.Size(x.Msg) n += proto.SizeVarint(13<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Communique_Somegroup: n += proto.SizeVarint(14<<3 | proto.WireStartGroup) n += proto.Size(x.Somegroup) n += proto.SizeVarint(14<<3 | proto.WireEndGroup) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Communique_SomeGroup struct { Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} } func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Communique_SomeGroup) ProtoMessage() {} func (m *Communique_SomeGroup) GetMember() string { if m != nil && m.Member != nil { return *m.Member } return "" } type Communique_Delta struct { XXX_unrecognized []byte `json:"-"` } func (m *Communique_Delta) Reset() { *m = Communique_Delta{} } func (m *Communique_Delta) String() string { return proto.CompactTextString(m) } func (*Communique_Delta) ProtoMessage() {} var E_Tag = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*string)(nil), Field: 103, Name: "my.test.tag", Tag: "bytes,103,opt,name=tag", Filename: "my_test/test.proto", } var E_Donut = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*OtherReplyExtensions)(nil), Field: 106, Name: "my.test.donut", Tag: "bytes,106,opt,name=donut", Filename: "my_test/test.proto", } func init() { proto.RegisterType((*Request)(nil), "my.test.Request") proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup") proto.RegisterType((*Reply)(nil), "my.test.Reply") proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry") proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase") proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions") proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions") proto.RegisterType((*OldReply)(nil), "my.test.OldReply") proto.RegisterType((*Communique)(nil), "my.test.Communique") proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup") proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta") proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value) proto.RegisterEnum("my.test.Days", Days_name, Days_value) proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value) proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value) proto.RegisterExtension(E_ReplyExtensions_Time) proto.RegisterExtension(E_ReplyExtensions_Carrot) proto.RegisterExtension(E_ReplyExtensions_Donut) proto.RegisterExtension(E_Tag) proto.RegisterExtension(E_Donut) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/multi/������������������������0000755�0610621�0607500�00000000000�13172163407�030017� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto������������0000644�0610621�0607500�00000003425�13172163407�032325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; package multitest; message Multi3 { enum HatType { FEDORA = 1; FEZ = 2; }; optional HatType hat_type = 1; } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto������������0000644�0610621�0607500�00000003501�13172163407�032317� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; package multitest; message Multi2 { required int32 required_value = 1; enum Color { BLUE = 1; GREEN = 2; RED = 3; }; optional Color color = 2; } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto������������0000644�0610621�0607500�00000003545�13172163407�032326� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; import "multi/multi2.proto"; import "multi/multi3.proto"; package multitest; message Multi1 { required Multi2 multi2 = 1; optional Multi2.Color color = 2; optional Multi3.HatType hat_type = 3; } �����������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go������������������0000644�0610621�0607500�00000003640�13172163407�031202� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A simple binary to link together the protocol buffers in this test. package testdata import ( "testing" mytestpb "./my_test" multipb "github.com/golang/protobuf/protoc-gen-go/testdata/multi" ) func TestLink(t *testing.T) { _ = &multipb.Multi1{} _ = &mytestpb.Request{} } ������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/imp3.proto��������������������0000644�0610621�0607500�00000003347�13172163407�030631� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; package imp; message ForeignImportedMessage { optional string tuber = 1; } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/imp2.proto��������������������0000644�0610621�0607500�00000003441�13172163407�030623� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; package imp; message PubliclyImportedMessage { optional int64 field = 1; } enum PubliclyImportedEnum { GLASSES = 1; HAIR = 2; } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/imp.proto���������������������0000644�0610621�0607500�00000004537�13172163407�030550� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; package imp; import "imp2.proto"; import "imp3.proto"; message ImportedMessage { required int64 field = 1; // The forwarded getters for these fields are fiddly to get right. optional ImportedMessage2 local_msg = 2; optional ForeignImportedMessage foreign_msg = 3; // in imp3.proto optional Owner enum_field = 4; oneof union { int32 state = 9; } repeated string name = 5; repeated Owner boss = 6; repeated ImportedMessage2 memo = 7; map<string, ImportedMessage2> msg_map = 8; enum Owner { DAVE = 1; MIKE = 2; } extensions 90 to 100; } message ImportedMessage2 { } message ImportedExtendable { option message_set_wire_format = true; extensions 100 to max; } �����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/imp.pb.go.golden��������������0000644�0610621�0607500�00000006525�13172163407�031660� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. // source: imp.proto // DO NOT EDIT! package imp import proto "github.com/golang/protobuf/proto" import "math" import "os" import imp1 "imp2.pb" // Reference proto & math imports to suppress error if they are not otherwise used. var _ = proto.GetString var _ = math.Inf // Types from public import imp2.proto type PubliclyImportedMessage imp1.PubliclyImportedMessage func (this *PubliclyImportedMessage) Reset() { (*imp1.PubliclyImportedMessage)(this).Reset() } func (this *PubliclyImportedMessage) String() string { return (*imp1.PubliclyImportedMessage)(this).String() } // PubliclyImportedMessage from public import imp.proto type ImportedMessage_Owner int32 const ( ImportedMessage_DAVE ImportedMessage_Owner = 1 ImportedMessage_MIKE ImportedMessage_Owner = 2 ) var ImportedMessage_Owner_name = map[int32]string{ 1: "DAVE", 2: "MIKE", } var ImportedMessage_Owner_value = map[string]int32{ "DAVE": 1, "MIKE": 2, } // NewImportedMessage_Owner is deprecated. Use x.Enum() instead. func NewImportedMessage_Owner(x ImportedMessage_Owner) *ImportedMessage_Owner { e := ImportedMessage_Owner(x) return &e } func (x ImportedMessage_Owner) Enum() *ImportedMessage_Owner { p := new(ImportedMessage_Owner) *p = x return p } func (x ImportedMessage_Owner) String() string { return proto.EnumName(ImportedMessage_Owner_name, int32(x)) } type ImportedMessage struct { Field *int64 `protobuf:"varint,1,req,name=field" json:"field,omitempty"` XXX_extensions map[int32][]byte `json:",omitempty"` XXX_unrecognized []byte `json:",omitempty"` } func (this *ImportedMessage) Reset() { *this = ImportedMessage{} } func (this *ImportedMessage) String() string { return proto.CompactTextString(this) } var extRange_ImportedMessage = []proto.ExtensionRange{ proto.ExtensionRange{90, 100}, } func (*ImportedMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ImportedMessage } func (this *ImportedMessage) ExtensionMap() map[int32][]byte { if this.XXX_extensions == nil { this.XXX_extensions = make(map[int32][]byte) } return this.XXX_extensions } type ImportedExtendable struct { XXX_extensions map[int32][]byte `json:",omitempty"` XXX_unrecognized []byte `json:",omitempty"` } func (this *ImportedExtendable) Reset() { *this = ImportedExtendable{} } func (this *ImportedExtendable) String() string { return proto.CompactTextString(this) } func (this *ImportedExtendable) Marshal() ([]byte, error) { return proto.MarshalMessageSet(this.ExtensionMap()) } func (this *ImportedExtendable) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, this.ExtensionMap()) } // ensure ImportedExtendable satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*ImportedExtendable)(nil) var _ proto.Unmarshaler = (*ImportedExtendable)(nil) var extRange_ImportedExtendable = []proto.ExtensionRange{ proto.ExtensionRange{100, 536870911}, } func (*ImportedExtendable) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ImportedExtendable } func (this *ImportedExtendable) ExtensionMap() map[int32][]byte { if this.XXX_extensions == nil { this.XXX_extensions = make(map[int32][]byte) } return this.XXX_extensions } func init() { proto.RegisterEnum("imp.ImportedMessage_Owner", ImportedMessage_Owner_name, ImportedMessage_Owner_value) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/grpc.proto��������������������0000644�0610621�0607500�00000004221�13172163407�030704� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package grpc.testing; message SimpleRequest { } message SimpleResponse { } message StreamMsg { } message StreamMsg2 { } service Test { rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // This RPC streams from the server only. rpc Downstream(SimpleRequest) returns (stream StreamMsg); // This RPC streams from the client. rpc Upstream(stream StreamMsg) returns (SimpleResponse); // This one streams in both directions. rpc Bidi(stream StreamMsg) returns (stream StreamMsg2); } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user.proto����������0000644�0610621�0607500�00000006044�13172163407�033030� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; import "extension_base.proto"; import "extension_extra.proto"; package extension_user; message UserMessage { optional string name = 1; optional string rank = 2; } // Extend with a message extend extension_base.BaseMessage { optional UserMessage user_message = 5; } // Extend with a foreign message extend extension_base.BaseMessage { optional extension_extra.ExtraMessage extra_message = 9; } // Extend with some primitive types extend extension_base.BaseMessage { optional int32 width = 6; optional int64 area = 7; } // Extend inside the scope of another type message LoudMessage { extend extension_base.BaseMessage { optional uint32 volume = 8; } extensions 100 to max; } // Extend inside the scope of another type, using a message. message LoginMessage { extend extension_base.BaseMessage { optional UserMessage user_message = 16; } } // Extend with a repeated field extend extension_base.BaseMessage { repeated Detail detail = 17; } message Detail { optional string color = 1; } // An extension of an extension message Announcement { optional string words = 1; extend LoudMessage { optional Announcement loud_ext = 100; } } // Something that can be put in a message set. message OldStyleParcel { extend extension_base.OldStyleMessage { optional OldStyleParcel message_set_extension = 2001; } required string name = 1; optional int32 height = 2; } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go�������������0000644�0610621�0607500�00000015100�13172163407�032264� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Test that we can use protocol buffers that use extensions. package testdata /* import ( "bytes" "regexp" "testing" "github.com/golang/protobuf/proto" base "extension_base.pb" user "extension_user.pb" ) func TestSingleFieldExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(178), } // Use extension within scope of another type. vol := proto.Uint32(11) err := proto.SetExtension(bm, user.E_LoudMessage_Volume, vol) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_LoudMessage_Volume) { t.Fatal("Decoded message didn't contain extension.") } vol_out, err := proto.GetExtension(bm_new, user.E_LoudMessage_Volume) if err != nil { t.Fatal("Failed getting extension:", err) } if v := vol_out.(*uint32); *v != *vol { t.Errorf("vol_out = %v, expected %v", *v, *vol) } proto.ClearExtension(bm_new, user.E_LoudMessage_Volume) if proto.HasExtension(bm_new, user.E_LoudMessage_Volume) { t.Fatal("Failed clearing extension.") } } func TestMessageExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(179), } // Use extension that is itself a message. um := &user.UserMessage{ Name: proto.String("Dave"), Rank: proto.String("Major"), } err := proto.SetExtension(bm, user.E_LoginMessage_UserMessage, um) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) { t.Fatal("Decoded message didn't contain extension.") } um_out, err := proto.GetExtension(bm_new, user.E_LoginMessage_UserMessage) if err != nil { t.Fatal("Failed getting extension:", err) } if n := um_out.(*user.UserMessage).Name; *n != *um.Name { t.Errorf("um_out.Name = %q, expected %q", *n, *um.Name) } if r := um_out.(*user.UserMessage).Rank; *r != *um.Rank { t.Errorf("um_out.Rank = %q, expected %q", *r, *um.Rank) } proto.ClearExtension(bm_new, user.E_LoginMessage_UserMessage) if proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) { t.Fatal("Failed clearing extension.") } } func TestTopLevelExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(179), } width := proto.Int32(17) err := proto.SetExtension(bm, user.E_Width, width) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_Width) { t.Fatal("Decoded message didn't contain extension.") } width_out, err := proto.GetExtension(bm_new, user.E_Width) if err != nil { t.Fatal("Failed getting extension:", err) } if w := width_out.(*int32); *w != *width { t.Errorf("width_out = %v, expected %v", *w, *width) } proto.ClearExtension(bm_new, user.E_Width) if proto.HasExtension(bm_new, user.E_Width) { t.Fatal("Failed clearing extension.") } } func TestMessageSetWireFormat(t *testing.T) { osm := new(base.OldStyleMessage) osp := &user.OldStyleParcel{ Name: proto.String("Dave"), Height: proto.Int32(178), } err := proto.SetExtension(osm, user.E_OldStyleParcel_MessageSetExtension, osp) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(osm) if err != nil { t.Fatal("Failed encoding message:", err) } // Data generated from Python implementation. expected := []byte{ 11, 16, 209, 15, 26, 9, 10, 4, 68, 97, 118, 101, 16, 178, 1, 12, } if !bytes.Equal(expected, buf) { t.Errorf("Encoding mismatch.\nwant %+v\n got %+v", expected, buf) } // Check that it is restored correctly. osm = new(base.OldStyleMessage) if err := proto.Unmarshal(buf, osm); err != nil { t.Fatal("Failed decoding message:", err) } osp_out, err := proto.GetExtension(osm, user.E_OldStyleParcel_MessageSetExtension) if err != nil { t.Fatal("Failed getting extension:", err) } osp = osp_out.(*user.OldStyleParcel) if *osp.Name != "Dave" || *osp.Height != 178 { t.Errorf("Retrieved extension from decoded message is not correct: %+v", osp) } } func main() { // simpler than rigging up gotest testing.Main(regexp.MatchString, []testing.InternalTest{ {"TestSingleFieldExtension", TestSingleFieldExtension}, {"TestMessageExtension", TestMessageExtension}, {"TestTopLevelExtension", TestTopLevelExtension}, }, []testing.InternalBenchmark{}, []testing.InternalExample{}) } */ ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra.proto���������0000644�0610621�0607500�00000003350�13172163407�033172� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; package extension_extra; message ExtraMessage { optional int32 width = 1; } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base.proto����������0000644�0610621�0607500�00000003673�13172163407�032771� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; package extension_base; message BaseMessage { optional int32 height = 1; extensions 4 to 9; extensions 16 to max; } // Another message that may be extended, using message_set_wire_format. message OldStyleMessage { option message_set_wire_format = true; extensions 100 to max; } ���������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/testdata/Makefile����������������������0000644�0610621�0607500�00000005362�13172163407�030333� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. all: @echo run make test include ../../Make.protobuf test: golden testbuild #test: golden testbuild extension_test # ./extension_test # @echo PASS my_test/test.pb.go: my_test/test.proto protoc --go_out=Mmulti/multi1.proto=github.com/golang/protobuf/protoc-gen-go/testdata/multi:. $< golden: make -B my_test/test.pb.go sed -i -e '/return.*fileDescriptor/d' my_test/test.pb.go sed -i -e '/^var fileDescriptor/,/^}/d' my_test/test.pb.go sed -i -e '/proto.RegisterFile.*fileDescriptor/d' my_test/test.pb.go gofmt -w my_test/test.pb.go diff -w my_test/test.pb.go my_test/test.pb.go.golden nuke: clean testbuild: regenerate go test regenerate: # Invoke protoc once to generate three independent .pb.go files in the same package. protoc --go_out=. multi/multi1.proto multi/multi2.proto multi/multi3.proto #extension_test: extension_test.$O # $(LD) -L. -o $@ $< #multi.a: multi3.pb.$O multi2.pb.$O multi1.pb.$O # rm -f multi.a # $(QUOTED_GOBIN)/gopack grc $@ $< #test.pb.go: imp.pb.go #multi1.pb.go: multi2.pb.go multi3.pb.go #main.$O: imp.pb.$O test.pb.$O multi.a #extension_test.$O: extension_base.pb.$O extension_extra.pb.$O extension_user.pb.$O ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/plugin/��������������������������������0000755�0610621�0607500�00000000000�13172163407�026352� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto��������������������0000644�0610621�0607500�00000020010�13172163407�030726� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // // WARNING: The plugin interface is currently EXPERIMENTAL and is subject to // change. // // protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is // just a program that reads a CodeGeneratorRequest from stdin and writes a // CodeGeneratorResponse to stdout. // // Plugins written using C++ can use google/protobuf/compiler/plugin.h instead // of dealing with the raw protocol defined here. // // A plugin executable needs only to be placed somewhere in the path. The // plugin should be named "protoc-gen-$NAME", and will then be used when the // flag "--${NAME}_out" is passed to protoc. syntax = "proto2"; package google.protobuf.compiler; option java_package = "com.google.protobuf.compiler"; option java_outer_classname = "PluginProtos"; option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go"; import "google/protobuf/descriptor.proto"; // The version number of protocol compiler. message Version { optional int32 major = 1; optional int32 minor = 2; optional int32 patch = 3; // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should // be empty for mainline stable releases. optional string suffix = 4; } // An encoded CodeGeneratorRequest is written to the plugin's stdin. message CodeGeneratorRequest { // The .proto files that were explicitly listed on the command-line. The // code generator should generate code only for these files. Each file's // descriptor will be included in proto_file, below. repeated string file_to_generate = 1; // The generator parameter passed on the command-line. optional string parameter = 2; // FileDescriptorProtos for all files in files_to_generate and everything // they import. The files will appear in topological order, so each file // appears before any file that imports it. // // protoc guarantees that all proto_files will be written after // the fields above, even though this is not technically guaranteed by the // protobuf wire format. This theoretically could allow a plugin to stream // in the FileDescriptorProtos and handle them one by one rather than read // the entire set into memory at once. However, as of this writing, this // is not similarly optimized on protoc's end -- it will store all fields in // memory at once before sending them to the plugin. // // Type names of fields and extensions in the FileDescriptorProto are always // fully qualified. repeated FileDescriptorProto proto_file = 15; // The version number of protocol compiler. optional Version compiler_version = 3; } // The plugin writes an encoded CodeGeneratorResponse to stdout. message CodeGeneratorResponse { // Error message. If non-empty, code generation failed. The plugin process // should exit with status code zero even if it reports an error in this way. // // This should be used to indicate errors in .proto files which prevent the // code generator from generating correct code. Errors which indicate a // problem in protoc itself -- such as the input CodeGeneratorRequest being // unparseable -- should be reported by writing a message to stderr and // exiting with a non-zero status code. optional string error = 1; // Represents a single generated file. message File { // The file name, relative to the output directory. The name must not // contain "." or ".." components and must be relative, not be absolute (so, // the file cannot lie outside the output directory). "/" must be used as // the path separator, not "\". // // If the name is omitted, the content will be appended to the previous // file. This allows the generator to break large files into small chunks, // and allows the generated text to be streamed back to protoc so that large // files need not reside completely in memory at one time. Note that as of // this writing protoc does not optimize for this -- it will read the entire // CodeGeneratorResponse before writing files to disk. optional string name = 1; // If non-empty, indicates that the named file should already exist, and the // content here is to be inserted into that file at a defined insertion // point. This feature allows a code generator to extend the output // produced by another code generator. The original generator may provide // insertion points by placing special annotations in the file that look // like: // @@protoc_insertion_point(NAME) // The annotation can have arbitrary text before and after it on the line, // which allows it to be placed in a comment. NAME should be replaced with // an identifier naming the point -- this is what other generators will use // as the insertion_point. Code inserted at this point will be placed // immediately above the line containing the insertion point (thus multiple // insertions to the same point will come out in the order they were added). // The double-@ is intended to make it unlikely that the generated code // could contain things that look like insertion points by accident. // // For example, the C++ code generator places the following line in the // .pb.h files that it generates: // // @@protoc_insertion_point(namespace_scope) // This line appears within the scope of the file's package namespace, but // outside of any particular class. Another plugin can then specify the // insertion_point "namespace_scope" to generate additional classes or // other declarations that should be placed in this scope. // // Note that if the line containing the insertion point begins with // whitespace, the same whitespace will be added to every line of the // inserted text. This is useful for languages like Python, where // indentation matters. In these languages, the insertion point comment // should be indented the same amount as any inserted code will need to be // in order to work correctly in that context. // // The code generator that generates the initial file and the one which // inserts into it must both run as part of a single invocation of protoc. // Code generators are executed in the order in which they appear on the // command line. // // If |insertion_point| is present, |name| must also be present. optional string insertion_point = 2; // The file contents. optional string content = 15; } repeated File file = 15; } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden����������������0000644�0610621�0607500�00000005713�13172163407�031450� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. // source: google/protobuf/compiler/plugin.proto // DO NOT EDIT! package google_protobuf_compiler import proto "github.com/golang/protobuf/proto" import "math" import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" // Reference proto and math imports to suppress error if they are not otherwise used. var _ = proto.GetString var _ = math.Inf type CodeGeneratorRequest struct { FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate" json:"file_to_generate,omitempty"` Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"` ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file" json:"proto_file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorRequest) Reset() { *this = CodeGeneratorRequest{} } func (this *CodeGeneratorRequest) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorRequest) ProtoMessage() {} func (this *CodeGeneratorRequest) GetParameter() string { if this != nil && this.Parameter != nil { return *this.Parameter } return "" } type CodeGeneratorResponse struct { Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorResponse) Reset() { *this = CodeGeneratorResponse{} } func (this *CodeGeneratorResponse) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorResponse) ProtoMessage() {} func (this *CodeGeneratorResponse) GetError() string { if this != nil && this.Error != nil { return *this.Error } return "" } type CodeGeneratorResponse_File struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point" json:"insertion_point,omitempty"` Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorResponse_File) Reset() { *this = CodeGeneratorResponse_File{} } func (this *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorResponse_File) ProtoMessage() {} func (this *CodeGeneratorResponse_File) GetName() string { if this != nil && this.Name != nil { return *this.Name } return "" } func (this *CodeGeneratorResponse_File) GetInsertionPoint() string { if this != nil && this.InsertionPoint != nil { return *this.InsertionPoint } return "" } func (this *CodeGeneratorResponse_File) GetContent() string { if this != nil && this.Content != nil { return *this.Content } return "" } func init() { } �����������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go��������������������0000644�0610621�0607500�00000032214�13172163407�030601� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/compiler/plugin.proto /* Package plugin_go is a generated protocol buffer package. It is generated from these files: google/protobuf/compiler/plugin.proto It has these top-level messages: Version CodeGeneratorRequest CodeGeneratorResponse */ package plugin_go import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The version number of protocol compiler. type Version struct { Major *int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"` Minor *int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"` Patch *int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"` // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should // be empty for mainline stable releases. Suffix *string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Version) Reset() { *m = Version{} } func (m *Version) String() string { return proto.CompactTextString(m) } func (*Version) ProtoMessage() {} func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Version) GetMajor() int32 { if m != nil && m.Major != nil { return *m.Major } return 0 } func (m *Version) GetMinor() int32 { if m != nil && m.Minor != nil { return *m.Minor } return 0 } func (m *Version) GetPatch() int32 { if m != nil && m.Patch != nil { return *m.Patch } return 0 } func (m *Version) GetSuffix() string { if m != nil && m.Suffix != nil { return *m.Suffix } return "" } // An encoded CodeGeneratorRequest is written to the plugin's stdin. type CodeGeneratorRequest struct { // The .proto files that were explicitly listed on the command-line. The // code generator should generate code only for these files. Each file's // descriptor will be included in proto_file, below. FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate,json=fileToGenerate" json:"file_to_generate,omitempty"` // The generator parameter passed on the command-line. Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"` // FileDescriptorProtos for all files in files_to_generate and everything // they import. The files will appear in topological order, so each file // appears before any file that imports it. // // protoc guarantees that all proto_files will be written after // the fields above, even though this is not technically guaranteed by the // protobuf wire format. This theoretically could allow a plugin to stream // in the FileDescriptorProtos and handle them one by one rather than read // the entire set into memory at once. However, as of this writing, this // is not similarly optimized on protoc's end -- it will store all fields in // memory at once before sending them to the plugin. // // Type names of fields and extensions in the FileDescriptorProto are always // fully qualified. ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file,json=protoFile" json:"proto_file,omitempty"` // The version number of protocol compiler. CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CodeGeneratorRequest) Reset() { *m = CodeGeneratorRequest{} } func (m *CodeGeneratorRequest) String() string { return proto.CompactTextString(m) } func (*CodeGeneratorRequest) ProtoMessage() {} func (*CodeGeneratorRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *CodeGeneratorRequest) GetFileToGenerate() []string { if m != nil { return m.FileToGenerate } return nil } func (m *CodeGeneratorRequest) GetParameter() string { if m != nil && m.Parameter != nil { return *m.Parameter } return "" } func (m *CodeGeneratorRequest) GetProtoFile() []*google_protobuf.FileDescriptorProto { if m != nil { return m.ProtoFile } return nil } func (m *CodeGeneratorRequest) GetCompilerVersion() *Version { if m != nil { return m.CompilerVersion } return nil } // The plugin writes an encoded CodeGeneratorResponse to stdout. type CodeGeneratorResponse struct { // Error message. If non-empty, code generation failed. The plugin process // should exit with status code zero even if it reports an error in this way. // // This should be used to indicate errors in .proto files which prevent the // code generator from generating correct code. Errors which indicate a // problem in protoc itself -- such as the input CodeGeneratorRequest being // unparseable -- should be reported by writing a message to stderr and // exiting with a non-zero status code. Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CodeGeneratorResponse) Reset() { *m = CodeGeneratorResponse{} } func (m *CodeGeneratorResponse) String() string { return proto.CompactTextString(m) } func (*CodeGeneratorResponse) ProtoMessage() {} func (*CodeGeneratorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *CodeGeneratorResponse) GetError() string { if m != nil && m.Error != nil { return *m.Error } return "" } func (m *CodeGeneratorResponse) GetFile() []*CodeGeneratorResponse_File { if m != nil { return m.File } return nil } // Represents a single generated file. type CodeGeneratorResponse_File struct { // The file name, relative to the output directory. The name must not // contain "." or ".." components and must be relative, not be absolute (so, // the file cannot lie outside the output directory). "/" must be used as // the path separator, not "\". // // If the name is omitted, the content will be appended to the previous // file. This allows the generator to break large files into small chunks, // and allows the generated text to be streamed back to protoc so that large // files need not reside completely in memory at one time. Note that as of // this writing protoc does not optimize for this -- it will read the entire // CodeGeneratorResponse before writing files to disk. Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` // If non-empty, indicates that the named file should already exist, and the // content here is to be inserted into that file at a defined insertion // point. This feature allows a code generator to extend the output // produced by another code generator. The original generator may provide // insertion points by placing special annotations in the file that look // like: // @@protoc_insertion_point(NAME) // The annotation can have arbitrary text before and after it on the line, // which allows it to be placed in a comment. NAME should be replaced with // an identifier naming the point -- this is what other generators will use // as the insertion_point. Code inserted at this point will be placed // immediately above the line containing the insertion point (thus multiple // insertions to the same point will come out in the order they were added). // The double-@ is intended to make it unlikely that the generated code // could contain things that look like insertion points by accident. // // For example, the C++ code generator places the following line in the // .pb.h files that it generates: // // @@protoc_insertion_point(namespace_scope) // This line appears within the scope of the file's package namespace, but // outside of any particular class. Another plugin can then specify the // insertion_point "namespace_scope" to generate additional classes or // other declarations that should be placed in this scope. // // Note that if the line containing the insertion point begins with // whitespace, the same whitespace will be added to every line of the // inserted text. This is useful for languages like Python, where // indentation matters. In these languages, the insertion point comment // should be indented the same amount as any inserted code will need to be // in order to work correctly in that context. // // The code generator that generates the initial file and the one which // inserts into it must both run as part of a single invocation of protoc. // Code generators are executed in the order in which they appear on the // command line. // // If |insertion_point| is present, |name| must also be present. InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point,json=insertionPoint" json:"insertion_point,omitempty"` // The file contents. Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CodeGeneratorResponse_File) Reset() { *m = CodeGeneratorResponse_File{} } func (m *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(m) } func (*CodeGeneratorResponse_File) ProtoMessage() {} func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } func (m *CodeGeneratorResponse_File) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *CodeGeneratorResponse_File) GetInsertionPoint() string { if m != nil && m.InsertionPoint != nil { return *m.InsertionPoint } return "" } func (m *CodeGeneratorResponse_File) GetContent() string { if m != nil && m.Content != nil { return *m.Content } return "" } func init() { proto.RegisterType((*Version)(nil), "google.protobuf.compiler.Version") proto.RegisterType((*CodeGeneratorRequest)(nil), "google.protobuf.compiler.CodeGeneratorRequest") proto.RegisterType((*CodeGeneratorResponse)(nil), "google.protobuf.compiler.CodeGeneratorResponse") proto.RegisterType((*CodeGeneratorResponse_File)(nil), "google.protobuf.compiler.CodeGeneratorResponse.File") } func init() { proto.RegisterFile("google/protobuf/compiler/plugin.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 417 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xcf, 0x6a, 0x14, 0x41, 0x10, 0xc6, 0x19, 0x77, 0x63, 0x98, 0x8a, 0x64, 0x43, 0x13, 0xa5, 0x09, 0x39, 0x8c, 0x8b, 0xe2, 0x5c, 0x32, 0x0b, 0xc1, 0x8b, 0x78, 0x4b, 0x44, 0x3d, 0x78, 0x58, 0x1a, 0xf1, 0x20, 0xc8, 0x30, 0x99, 0xd4, 0x74, 0x5a, 0x66, 0xba, 0xc6, 0xee, 0x1e, 0xf1, 0x49, 0x7d, 0x0f, 0xdf, 0x40, 0xfa, 0xcf, 0x24, 0xb2, 0xb8, 0xa7, 0xee, 0xef, 0x57, 0xd5, 0xd5, 0x55, 0x1f, 0x05, 0x2f, 0x25, 0x91, 0xec, 0x71, 0x33, 0x1a, 0x72, 0x74, 0x33, 0x75, 0x9b, 0x96, 0x86, 0x51, 0xf5, 0x68, 0x36, 0x63, 0x3f, 0x49, 0xa5, 0xab, 0x10, 0x60, 0x3c, 0xa6, 0x55, 0x73, 0x5a, 0x35, 0xa7, 0x9d, 0x15, 0xbb, 0x05, 0x6e, 0xd1, 0xb6, 0x46, 0x8d, 0x8e, 0x4c, 0xcc, 0x5e, 0xb7, 0x70, 0xf8, 0x05, 0x8d, 0x55, 0xa4, 0xd9, 0x29, 0x1c, 0x0c, 0xcd, 0x77, 0x32, 0x3c, 0x2b, 0xb2, 0xf2, 0x40, 0x44, 0x11, 0xa8, 0xd2, 0x64, 0xf8, 0xa3, 0x44, 0xbd, 0xf0, 0x74, 0x6c, 0x5c, 0x7b, 0xc7, 0x17, 0x91, 0x06, 0xc1, 0x9e, 0xc1, 0x63, 0x3b, 0x75, 0x9d, 0xfa, 0xc5, 0x97, 0x45, 0x56, 0xe6, 0x22, 0xa9, 0xf5, 0x9f, 0x0c, 0x4e, 0xaf, 0xe9, 0x16, 0x3f, 0xa0, 0x46, 0xd3, 0x38, 0x32, 0x02, 0x7f, 0x4c, 0x68, 0x1d, 0x2b, 0xe1, 0xa4, 0x53, 0x3d, 0xd6, 0x8e, 0x6a, 0x19, 0x63, 0xc8, 0xb3, 0x62, 0x51, 0xe6, 0xe2, 0xd8, 0xf3, 0xcf, 0x94, 0x5e, 0x20, 0x3b, 0x87, 0x7c, 0x6c, 0x4c, 0x33, 0xa0, 0xc3, 0xd8, 0x4a, 0x2e, 0x1e, 0x00, 0xbb, 0x06, 0x08, 0xe3, 0xd4, 0xfe, 0x15, 0x5f, 0x15, 0x8b, 0xf2, 0xe8, 0xf2, 0x45, 0xb5, 0x6b, 0xcb, 0x7b, 0xd5, 0xe3, 0xbb, 0x7b, 0x03, 0xb6, 0x1e, 0x8b, 0x3c, 0x44, 0x7d, 0x84, 0x7d, 0x82, 0x93, 0xd9, 0xb8, 0xfa, 0x67, 0xf4, 0x24, 0x8c, 0x77, 0x74, 0xf9, 0xbc, 0xda, 0xe7, 0x70, 0x95, 0xcc, 0x13, 0xab, 0x99, 0x24, 0xb0, 0xfe, 0x9d, 0xc1, 0xd3, 0x9d, 0x99, 0xed, 0x48, 0xda, 0xa2, 0xf7, 0x0e, 0x8d, 0x49, 0x3e, 0xe7, 0x22, 0x0a, 0xf6, 0x11, 0x96, 0xff, 0x34, 0xff, 0x7a, 0xff, 0x8f, 0xff, 0x2d, 0x1a, 0x66, 0x13, 0xa1, 0xc2, 0xd9, 0x37, 0x58, 0x86, 0x79, 0x18, 0x2c, 0x75, 0x33, 0x60, 0xfa, 0x26, 0xdc, 0xd9, 0x2b, 0x58, 0x29, 0x6d, 0xd1, 0x38, 0x45, 0xba, 0x1e, 0x49, 0x69, 0x97, 0xcc, 0x3c, 0xbe, 0xc7, 0x5b, 0x4f, 0x19, 0x87, 0xc3, 0x96, 0xb4, 0x43, 0xed, 0xf8, 0x2a, 0x24, 0xcc, 0xf2, 0x4a, 0xc2, 0x79, 0x4b, 0xc3, 0xde, 0xfe, 0xae, 0x9e, 0x6c, 0xc3, 0x6e, 0x06, 0x7b, 0xed, 0xd7, 0x37, 0x52, 0xb9, 0xbb, 0xe9, 0xc6, 0x87, 0x37, 0x92, 0xfa, 0x46, 0xcb, 0x87, 0x65, 0x0c, 0x97, 0xf6, 0x42, 0xa2, 0xbe, 0x90, 0x94, 0x56, 0xfa, 0x6d, 0x3c, 0x6a, 0x49, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x15, 0x40, 0xc5, 0xfe, 0x02, 0x00, 0x00, } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/plugin/Makefile������������������������0000644�0610621�0607500�00000004325�13172163407�030016� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Not stored here, but plugin.proto is in https://github.com/google/protobuf/ # at src/google/protobuf/compiler/plugin.proto # Also we need to fix an import. regenerate: @echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION cp $(HOME)/src/protobuf/include/google/protobuf/compiler/plugin.proto . protoc --go_out=Mgoogle/protobuf/descriptor.proto=github.com/golang/protobuf/protoc-gen-go/descriptor:../../../../.. \ -I$(HOME)/src/protobuf/include $(HOME)/src/protobuf/include/google/protobuf/compiler/plugin.proto restore: cp plugin.pb.golden plugin.pb.go preserve: cp plugin.pb.go plugin.pb.golden �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/main.go��������������������������������0000644�0610621�0607500�00000006760�13172163407�026340� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // protoc-gen-go is a plugin for the Google protocol buffer compiler to generate // Go code. Run it by building this program and putting it in your path with // the name // protoc-gen-go // That word 'go' at the end becomes part of the option string set for the // protocol compiler, so once the protocol compiler (protoc) is installed // you can run // protoc --go_out=output_directory input_directory/file.proto // to generate Go bindings for the protocol defined by file.proto. // With that input, the output will be written to // output_directory/file.pb.go // // The generated code is documented in the package comment for // the library. // // See the README and documentation for protocol buffers to learn more: // https://developers.google.com/protocol-buffers/ package main import ( "io/ioutil" "os" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/protoc-gen-go/generator" ) func main() { // Begin by allocating a generator. The request and response structures are stored there // so we can do error handling easily - the response structure contains the field to // report failure. g := generator.New() data, err := ioutil.ReadAll(os.Stdin) if err != nil { g.Error(err, "reading input") } if err := proto.Unmarshal(data, g.Request); err != nil { g.Error(err, "parsing input proto") } if len(g.Request.FileToGenerate) == 0 { g.Fail("no files to generate") } g.CommandLineParameters(g.Request.GetParameter()) // Create a wrapped version of the Descriptors and EnumDescriptors that // point to the file that defines them. g.WrapTypes() g.SetPackageNames() g.BuildTypeNameMap() g.GenerateAllFiles() // Send back the results. data, err = proto.Marshal(g.Response) if err != nil { g.Error(err, "failed to marshal output proto") } _, err = os.Stdout.Write(data) if err != nil { g.Error(err, "failed to write output proto") } } ����������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/link_grpc.go���������������������������0000644�0610621�0607500�00000003314�13172163407�027354� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package main import _ "github.com/golang/protobuf/protoc-gen-go/grpc" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/grpc/����������������������������������0000755�0610621�0607500�00000000000�13172163407�026007� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go���������������������������0000644�0610621�0607500�00000036222�13172163407�027276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Package grpc outputs gRPC service descriptions in Go code. // It runs as a plugin for the Go protocol buffer compiler plugin. // It is linked in to protoc-gen-go. package grpc import ( "fmt" "path" "strconv" "strings" pb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/golang/protobuf/protoc-gen-go/generator" ) // generatedCodeVersion indicates a version of the generated code. // It is incremented whenever an incompatibility between the generated code and // the grpc package is introduced; the generated code references // a constant, grpc.SupportPackageIsVersionN (where N is generatedCodeVersion). const generatedCodeVersion = 4 // Paths for packages used by code generated in this file, // relative to the import_prefix of the generator.Generator. const ( contextPkgPath = "golang.org/x/net/context" grpcPkgPath = "google.golang.org/grpc" ) func init() { generator.RegisterPlugin(new(grpc)) } // grpc is an implementation of the Go protocol buffer compiler's // plugin architecture. It generates bindings for gRPC support. type grpc struct { gen *generator.Generator } // Name returns the name of this plugin, "grpc". func (g *grpc) Name() string { return "grpc" } // The names for packages imported in the generated code. // They may vary from the final path component of the import path // if the name is used by other packages. var ( contextPkg string grpcPkg string ) // Init initializes the plugin. func (g *grpc) Init(gen *generator.Generator) { g.gen = gen contextPkg = generator.RegisterUniquePackageName("context", nil) grpcPkg = generator.RegisterUniquePackageName("grpc", nil) } // Given a type name defined in a .proto, return its object. // Also record that we're using it, to guarantee the associated import. func (g *grpc) objectNamed(name string) generator.Object { g.gen.RecordTypeUse(name) return g.gen.ObjectNamed(name) } // Given a type name defined in a .proto, return its name as we will print it. func (g *grpc) typeName(str string) string { return g.gen.TypeName(g.objectNamed(str)) } // P forwards to g.gen.P. func (g *grpc) P(args ...interface{}) { g.gen.P(args...) } // Generate generates code for the services in the given file. func (g *grpc) Generate(file *generator.FileDescriptor) { if len(file.FileDescriptorProto.Service) == 0 { return } g.P("// Reference imports to suppress errors if they are not otherwise used.") g.P("var _ ", contextPkg, ".Context") g.P("var _ ", grpcPkg, ".ClientConn") g.P() // Assert version compatibility. g.P("// This is a compile-time assertion to ensure that this generated file") g.P("// is compatible with the grpc package it is being compiled against.") g.P("const _ = ", grpcPkg, ".SupportPackageIsVersion", generatedCodeVersion) g.P() for i, service := range file.FileDescriptorProto.Service { g.generateService(file, service, i) } } // GenerateImports generates the import declaration for this file. func (g *grpc) GenerateImports(file *generator.FileDescriptor) { if len(file.FileDescriptorProto.Service) == 0 { return } g.P("import (") g.P(contextPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, contextPkgPath))) g.P(grpcPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, grpcPkgPath))) g.P(")") g.P() } // reservedClientName records whether a client name is reserved on the client side. var reservedClientName = map[string]bool{ // TODO: do we need any in gRPC? } func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] } // generateService generates all the code for the named service. func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) { path := fmt.Sprintf("6,%d", index) // 6 means service. origServName := service.GetName() fullServName := origServName if pkg := file.GetPackage(); pkg != "" { fullServName = pkg + "." + fullServName } servName := generator.CamelCase(origServName) g.P() g.P("// Client API for ", servName, " service") g.P() // Client interface. g.P("type ", servName, "Client interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. g.P(g.generateClientSignature(servName, method)) } g.P("}") g.P() // Client structure. g.P("type ", unexport(servName), "Client struct {") g.P("cc *", grpcPkg, ".ClientConn") g.P("}") g.P() // NewClient factory. g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {") g.P("return &", unexport(servName), "Client{cc}") g.P("}") g.P() var methodIndex, streamIndex int serviceDescVar := "_" + servName + "_serviceDesc" // Client method implementations. for _, method := range service.Method { var descExpr string if !method.GetServerStreaming() && !method.GetClientStreaming() { // Unary RPC method descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex) methodIndex++ } else { // Streaming RPC method descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex) streamIndex++ } g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr) } g.P("// Server API for ", servName, " service") g.P() // Server interface. serverType := servName + "Server" g.P("type ", serverType, " interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. g.P(g.generateServerSignature(servName, method)) } g.P("}") g.P() // Server registration. g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {") g.P("s.RegisterService(&", serviceDescVar, `, srv)`) g.P("}") g.P() // Server handler implementations. var handlerNames []string for _, method := range service.Method { hname := g.generateServerMethod(servName, fullServName, method) handlerNames = append(handlerNames, hname) } // Service descriptor. g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {") g.P("ServiceName: ", strconv.Quote(fullServName), ",") g.P("HandlerType: (*", serverType, ")(nil),") g.P("Methods: []", grpcPkg, ".MethodDesc{") for i, method := range service.Method { if method.GetServerStreaming() || method.GetClientStreaming() { continue } g.P("{") g.P("MethodName: ", strconv.Quote(method.GetName()), ",") g.P("Handler: ", handlerNames[i], ",") g.P("},") } g.P("},") g.P("Streams: []", grpcPkg, ".StreamDesc{") for i, method := range service.Method { if !method.GetServerStreaming() && !method.GetClientStreaming() { continue } g.P("{") g.P("StreamName: ", strconv.Quote(method.GetName()), ",") g.P("Handler: ", handlerNames[i], ",") if method.GetServerStreaming() { g.P("ServerStreams: true,") } if method.GetClientStreaming() { g.P("ClientStreams: true,") } g.P("},") } g.P("},") g.P("Metadata: \"", file.GetName(), "\",") g.P("}") g.P() } // generateClientSignature returns the client-side signature for a method. func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } reqArg := ", in *" + g.typeName(method.GetInputType()) if method.GetClientStreaming() { reqArg = "" } respName := "*" + g.typeName(method.GetOutputType()) if method.GetServerStreaming() || method.GetClientStreaming() { respName = servName + "_" + generator.CamelCase(origMethName) + "Client" } return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName) } func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName()) methName := generator.CamelCase(method.GetName()) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{") if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("out := new(", outType, ")") // TODO: Pass descExpr to Invoke. g.P("err := ", grpcPkg, `.Invoke(ctx, "`, sname, `", in, out, c.cc, opts...)`) g.P("if err != nil { return nil, err }") g.P("return out, nil") g.P("}") g.P() return } streamType := unexport(servName) + methName + "Client" g.P("stream, err := ", grpcPkg, ".NewClientStream(ctx, ", descExpr, `, c.cc, "`, sname, `", opts...)`) g.P("if err != nil { return nil, err }") g.P("x := &", streamType, "{stream}") if !method.GetClientStreaming() { g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") } g.P("return x, nil") g.P("}") g.P() genSend := method.GetClientStreaming() genRecv := method.GetServerStreaming() genCloseAndRecv := !method.GetServerStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Client interface {") if genSend { g.P("Send(*", inType, ") error") } if genRecv { g.P("Recv() (*", outType, ", error)") } if genCloseAndRecv { g.P("CloseAndRecv() (*", outType, ", error)") } g.P(grpcPkg, ".ClientStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(grpcPkg, ".ClientStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", inType, ") error {") g.P("return x.ClientStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } if genCloseAndRecv { g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } } // generateServerSignature returns the server-side signature for a method. func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } var reqArgs []string ret := "error" if !method.GetServerStreaming() && !method.GetClientStreaming() { reqArgs = append(reqArgs, contextPkg+".Context") ret = "(*" + g.typeName(method.GetOutputType()) + ", error)" } if !method.GetClientStreaming() { reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType())) } if method.GetServerStreaming() || method.GetClientStreaming() { reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server") } return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret } func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string { methName := generator.CamelCase(method.GetName()) hname := fmt.Sprintf("_%s_%s_Handler", servName, methName) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {") g.P("in := new(", inType, ")") g.P("if err := dec(in); err != nil { return nil, err }") g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }") g.P("info := &", grpcPkg, ".UnaryServerInfo{") g.P("Server: srv,") g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",") g.P("}") g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {") g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))") g.P("}") g.P("return interceptor(ctx, in, info, handler)") g.P("}") g.P() return hname } streamType := unexport(servName) + methName + "Server" g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {") if !method.GetClientStreaming() { g.P("m := new(", inType, ")") g.P("if err := stream.RecvMsg(m); err != nil { return err }") g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})") } else { g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})") } g.P("}") g.P() genSend := method.GetServerStreaming() genSendAndClose := !method.GetServerStreaming() genRecv := method.GetClientStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Server interface {") if genSend { g.P("Send(*", outType, ") error") } if genSendAndClose { g.P("SendAndClose(*", outType, ") error") } if genRecv { g.P("Recv() (*", inType, ", error)") } g.P(grpcPkg, ".ServerStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(grpcPkg, ".ServerStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genSendAndClose { g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {") g.P("m := new(", inType, ")") g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } return hname } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/generator/�����������������������������0000755�0610621�0607500�00000000000�13172163407�027042� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go�����������������0000644�0610621�0607500�00000007531�13172163407�031356� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2013 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package generator import ( "testing" "github.com/golang/protobuf/protoc-gen-go/descriptor" ) func TestCamelCase(t *testing.T) { tests := []struct { in, want string }{ {"one", "One"}, {"one_two", "OneTwo"}, {"_my_field_name_2", "XMyFieldName_2"}, {"Something_Capped", "Something_Capped"}, {"my_Name", "My_Name"}, {"OneTwo", "OneTwo"}, {"_", "X"}, {"_a_", "XA_"}, } for _, tc := range tests { if got := CamelCase(tc.in); got != tc.want { t.Errorf("CamelCase(%q) = %q, want %q", tc.in, got, tc.want) } } } func TestGoPackageOption(t *testing.T) { tests := []struct { in string impPath, pkg string ok bool }{ {"", "", "", false}, {"foo", "", "foo", true}, {"github.com/golang/bar", "github.com/golang/bar", "bar", true}, {"github.com/golang/bar;baz", "github.com/golang/bar", "baz", true}, } for _, tc := range tests { d := &FileDescriptor{ FileDescriptorProto: &descriptor.FileDescriptorProto{ Options: &descriptor.FileOptions{ GoPackage: &tc.in, }, }, } impPath, pkg, ok := d.goPackageOption() if impPath != tc.impPath || pkg != tc.pkg || ok != tc.ok { t.Errorf("go_package = %q => (%q, %q, %t), want (%q, %q, %t)", tc.in, impPath, pkg, ok, tc.impPath, tc.pkg, tc.ok) } } } func TestUnescape(t *testing.T) { tests := []struct { in string out string }{ // successful cases, including all kinds of escapes {"", ""}, {"foo bar baz frob nitz", "foo bar baz frob nitz"}, {`\000\001\002\003\004\005\006\007`, string([]byte{0, 1, 2, 3, 4, 5, 6, 7})}, {`\a\b\f\n\r\t\v\\\?\'\"`, string([]byte{'\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '?', '\'', '"'})}, {`\x10\x20\x30\x40\x50\x60\x70\x80`, string([]byte{16, 32, 48, 64, 80, 96, 112, 128})}, // variable length octal escapes {`\0\018\222\377\3\04\005\6\07`, string([]byte{0, 1, '8', 0222, 255, 3, 4, 5, 6, 7})}, // malformed escape sequences left as is {"foo \\g bar", "foo \\g bar"}, {"foo \\xg0 bar", "foo \\xg0 bar"}, {"\\", "\\"}, {"\\x", "\\x"}, {"\\xf", "\\xf"}, {"\\777", "\\777"}, // overflows byte } for _, tc := range tests { s := unescape(tc.in) if s != tc.out { t.Errorf("doUnescape(%q) = %q; should have been %q", tc.in, s, tc.out) } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/generator/generator.go�����������������0000644�0610621�0607500�00000265316�13172163407�031374� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* The code generator for the plugin for the Google protocol buffer compiler. It generates Go code from the protocol buffer description files read by the main routine. */ package generator import ( "bufio" "bytes" "compress/gzip" "fmt" "go/parser" "go/printer" "go/token" "log" "os" "path" "strconv" "strings" "unicode" "unicode/utf8" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/protoc-gen-go/descriptor" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" ) // generatedCodeVersion indicates a version of the generated code. // It is incremented whenever an incompatibility between the generated code and // proto package is introduced; the generated code references // a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion). const generatedCodeVersion = 2 // A Plugin provides functionality to add to the output during Go code generation, // such as to produce RPC stubs. type Plugin interface { // Name identifies the plugin. Name() string // Init is called once after data structures are built but before // code generation begins. Init(g *Generator) // Generate produces the code generated by the plugin for this file, // except for the imports, by calling the generator's methods P, In, and Out. Generate(file *FileDescriptor) // GenerateImports produces the import declarations for this file. // It is called after Generate. GenerateImports(file *FileDescriptor) } var plugins []Plugin // RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated. // It is typically called during initialization. func RegisterPlugin(p Plugin) { plugins = append(plugins, p) } // Each type we import as a protocol buffer (other than FileDescriptorProto) needs // a pointer to the FileDescriptorProto that represents it. These types achieve that // wrapping by placing each Proto inside a struct with the pointer to its File. The // structs have the same names as their contents, with "Proto" removed. // FileDescriptor is used to store the things that it points to. // The file and package name method are common to messages and enums. type common struct { file *descriptor.FileDescriptorProto // File this object comes from. } // PackageName is name in the package clause in the generated file. func (c *common) PackageName() string { return uniquePackageOf(c.file) } func (c *common) File() *descriptor.FileDescriptorProto { return c.file } func fileIsProto3(file *descriptor.FileDescriptorProto) bool { return file.GetSyntax() == "proto3" } func (c *common) proto3() bool { return fileIsProto3(c.file) } // Descriptor represents a protocol buffer message. type Descriptor struct { common *descriptor.DescriptorProto parent *Descriptor // The containing message, if any. nested []*Descriptor // Inner messages, if any. enums []*EnumDescriptor // Inner enums, if any. ext []*ExtensionDescriptor // Extensions, if any. typename []string // Cached typename vector. index int // The index into the container, whether the file or another message. path string // The SourceCodeInfo path as comma-separated integers. group bool } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (d *Descriptor) TypeName() []string { if d.typename != nil { return d.typename } n := 0 for parent := d; parent != nil; parent = parent.parent { n++ } s := make([]string, n, n) for parent := d; parent != nil; parent = parent.parent { n-- s[n] = parent.GetName() } d.typename = s return s } // EnumDescriptor describes an enum. If it's at top level, its parent will be nil. // Otherwise it will be the descriptor of the message in which it is defined. type EnumDescriptor struct { common *descriptor.EnumDescriptorProto parent *Descriptor // The containing message, if any. typename []string // Cached typename vector. index int // The index into the container, whether the file or a message. path string // The SourceCodeInfo path as comma-separated integers. } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (e *EnumDescriptor) TypeName() (s []string) { if e.typename != nil { return e.typename } name := e.GetName() if e.parent == nil { s = make([]string, 1) } else { pname := e.parent.TypeName() s = make([]string, len(pname)+1) copy(s, pname) } s[len(s)-1] = name e.typename = s return s } // Everything but the last element of the full type name, CamelCased. // The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... . func (e *EnumDescriptor) prefix() string { if e.parent == nil { // If the enum is not part of a message, the prefix is just the type name. return CamelCase(*e.Name) + "_" } typeName := e.TypeName() return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_" } // The integer value of the named constant in this enumerated type. func (e *EnumDescriptor) integerValueAsString(name string) string { for _, c := range e.Value { if c.GetName() == name { return fmt.Sprint(c.GetNumber()) } } log.Fatal("cannot find value for enum constant") return "" } // ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil. // Otherwise it will be the descriptor of the message in which it is defined. type ExtensionDescriptor struct { common *descriptor.FieldDescriptorProto parent *Descriptor // The containing message, if any. } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (e *ExtensionDescriptor) TypeName() (s []string) { name := e.GetName() if e.parent == nil { // top-level extension s = make([]string, 1) } else { pname := e.parent.TypeName() s = make([]string, len(pname)+1) copy(s, pname) } s[len(s)-1] = name return s } // DescName returns the variable name used for the generated descriptor. func (e *ExtensionDescriptor) DescName() string { // The full type name. typeName := e.TypeName() // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix. for i, s := range typeName { typeName[i] = CamelCase(s) } return "E_" + strings.Join(typeName, "_") } // ImportedDescriptor describes a type that has been publicly imported from another file. type ImportedDescriptor struct { common o Object } func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() } // FileDescriptor describes an protocol buffer descriptor file (.proto). // It includes slices of all the messages and enums defined within it. // Those slices are constructed by WrapTypes. type FileDescriptor struct { *descriptor.FileDescriptorProto desc []*Descriptor // All the messages defined in this file. enum []*EnumDescriptor // All the enums defined in this file. ext []*ExtensionDescriptor // All the top-level extensions defined in this file. imp []*ImportedDescriptor // All types defined in files publicly imported by this file. // Comments, stored as a map of path (comma-separated integers) to the comment. comments map[string]*descriptor.SourceCodeInfo_Location // The full list of symbols that are exported, // as a map from the exported object to its symbols. // This is used for supporting public imports. exported map[Object][]symbol index int // The index of this file in the list of files to generate code for proto3 bool // whether to generate proto3 code for this file } // PackageName is the package name we'll use in the generated code to refer to this file. func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) } // VarName is the variable name we'll use in the generated code to refer // to the compressed bytes of this descriptor. It is not exported, so // it is only valid inside the generated package. func (d *FileDescriptor) VarName() string { return fmt.Sprintf("fileDescriptor%d", d.index) } // goPackageOption interprets the file's go_package option. // If there is no go_package, it returns ("", "", false). // If there's a simple name, it returns ("", pkg, true). // If the option implies an import path, it returns (impPath, pkg, true). func (d *FileDescriptor) goPackageOption() (impPath, pkg string, ok bool) { pkg = d.GetOptions().GetGoPackage() if pkg == "" { return } ok = true // The presence of a slash implies there's an import path. slash := strings.LastIndex(pkg, "/") if slash < 0 { return } impPath, pkg = pkg, pkg[slash+1:] // A semicolon-delimited suffix overrides the package name. sc := strings.IndexByte(impPath, ';') if sc < 0 { return } impPath, pkg = impPath[:sc], impPath[sc+1:] return } // goPackageName returns the Go package name to use in the // generated Go file. The result explicit reports whether the name // came from an option go_package statement. If explicit is false, // the name was derived from the protocol buffer's package statement // or the input file name. func (d *FileDescriptor) goPackageName() (name string, explicit bool) { // Does the file have a "go_package" option? if _, pkg, ok := d.goPackageOption(); ok { return pkg, true } // Does the file have a package clause? if pkg := d.GetPackage(); pkg != "" { return pkg, false } // Use the file base name. return baseName(d.GetName()), false } // goFileName returns the output name for the generated Go file. func (d *FileDescriptor) goFileName() string { name := *d.Name if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" { name = name[:len(name)-len(ext)] } name += ".pb.go" // Does the file have a "go_package" option? // If it does, it may override the filename. if impPath, _, ok := d.goPackageOption(); ok && impPath != "" { // Replace the existing dirname with the declared import path. _, name = path.Split(name) name = path.Join(impPath, name) return name } return name } func (d *FileDescriptor) addExport(obj Object, sym symbol) { d.exported[obj] = append(d.exported[obj], sym) } // symbol is an interface representing an exported Go symbol. type symbol interface { // GenerateAlias should generate an appropriate alias // for the symbol from the named package. GenerateAlias(g *Generator, pkg string) } type messageSymbol struct { sym string hasExtensions, isMessageSet bool hasOneof bool getters []getterSymbol } type getterSymbol struct { name string typ string typeName string // canonical name in proto world; empty for proto.Message and similar genType bool // whether typ contains a generated type (message/group/enum) } func (ms *messageSymbol) GenerateAlias(g *Generator, pkg string) { remoteSym := pkg + "." + ms.sym g.P("type ", ms.sym, " ", remoteSym) g.P("func (m *", ms.sym, ") Reset() { (*", remoteSym, ")(m).Reset() }") g.P("func (m *", ms.sym, ") String() string { return (*", remoteSym, ")(m).String() }") g.P("func (*", ms.sym, ") ProtoMessage() {}") if ms.hasExtensions { g.P("func (*", ms.sym, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange ", "{ return (*", remoteSym, ")(nil).ExtensionRangeArray() }") if ms.isMessageSet { g.P("func (m *", ms.sym, ") Marshal() ([]byte, error) ", "{ return (*", remoteSym, ")(m).Marshal() }") g.P("func (m *", ms.sym, ") Unmarshal(buf []byte) error ", "{ return (*", remoteSym, ")(m).Unmarshal(buf) }") } } if ms.hasOneof { // Oneofs and public imports do not mix well. // We can make them work okay for the binary format, // but they're going to break weirdly for text/JSON. enc := "_" + ms.sym + "_OneofMarshaler" dec := "_" + ms.sym + "_OneofUnmarshaler" size := "_" + ms.sym + "_OneofSizer" encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error" decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)" sizeSig := "(msg " + g.Pkg["proto"] + ".Message) int" g.P("func (m *", ms.sym, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {") g.P("return ", enc, ", ", dec, ", ", size, ", nil") g.P("}") g.P("func ", enc, encSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("enc, _, _, _ := m0.XXX_OneofFuncs()") g.P("return enc(m0, b)") g.P("}") g.P("func ", dec, decSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("_, dec, _, _ := m0.XXX_OneofFuncs()") g.P("return dec(m0, tag, wire, b)") g.P("}") g.P("func ", size, sizeSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("_, _, size, _ := m0.XXX_OneofFuncs()") g.P("return size(m0)") g.P("}") } for _, get := range ms.getters { if get.typeName != "" { g.RecordTypeUse(get.typeName) } typ := get.typ val := "(*" + remoteSym + ")(m)." + get.name + "()" if get.genType { // typ will be "*pkg.T" (message/group) or "pkg.T" (enum) // or "map[t]*pkg.T" (map to message/enum). // The first two of those might have a "[]" prefix if it is repeated. // Drop any package qualifier since we have hoisted the type into this package. rep := strings.HasPrefix(typ, "[]") if rep { typ = typ[2:] } isMap := strings.HasPrefix(typ, "map[") star := typ[0] == '*' if !isMap { // map types handled lower down typ = typ[strings.Index(typ, ".")+1:] } if star { typ = "*" + typ } if rep { // Go does not permit conversion between slice types where both // element types are named. That means we need to generate a bit // of code in this situation. // typ is the element type. // val is the expression to get the slice from the imported type. ctyp := typ // conversion type expression; "Foo" or "(*Foo)" if star { ctyp = "(" + typ + ")" } g.P("func (m *", ms.sym, ") ", get.name, "() []", typ, " {") g.In() g.P("o := ", val) g.P("if o == nil {") g.In() g.P("return nil") g.Out() g.P("}") g.P("s := make([]", typ, ", len(o))") g.P("for i, x := range o {") g.In() g.P("s[i] = ", ctyp, "(x)") g.Out() g.P("}") g.P("return s") g.Out() g.P("}") continue } if isMap { // Split map[keyTyp]valTyp. bra, ket := strings.Index(typ, "["), strings.Index(typ, "]") keyTyp, valTyp := typ[bra+1:ket], typ[ket+1:] // Drop any package qualifier. // Only the value type may be foreign. star := valTyp[0] == '*' valTyp = valTyp[strings.Index(valTyp, ".")+1:] if star { valTyp = "*" + valTyp } typ := "map[" + keyTyp + "]" + valTyp g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " {") g.P("o := ", val) g.P("if o == nil { return nil }") g.P("s := make(", typ, ", len(o))") g.P("for k, v := range o {") g.P("s[k] = (", valTyp, ")(v)") g.P("}") g.P("return s") g.P("}") continue } // Convert imported type into the forwarding type. val = "(" + typ + ")(" + val + ")" } g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " { return ", val, " }") } } type enumSymbol struct { name string proto3 bool // Whether this came from a proto3 file. } func (es enumSymbol) GenerateAlias(g *Generator, pkg string) { s := es.name g.P("type ", s, " ", pkg, ".", s) g.P("var ", s, "_name = ", pkg, ".", s, "_name") g.P("var ", s, "_value = ", pkg, ".", s, "_value") g.P("func (x ", s, ") String() string { return (", pkg, ".", s, ")(x).String() }") if !es.proto3 { g.P("func (x ", s, ") Enum() *", s, "{ return (*", s, ")((", pkg, ".", s, ")(x).Enum()) }") g.P("func (x *", s, ") UnmarshalJSON(data []byte) error { return (*", pkg, ".", s, ")(x).UnmarshalJSON(data) }") } } type constOrVarSymbol struct { sym string typ string // either "const" or "var" cast string // if non-empty, a type cast is required (used for enums) } func (cs constOrVarSymbol) GenerateAlias(g *Generator, pkg string) { v := pkg + "." + cs.sym if cs.cast != "" { v = cs.cast + "(" + v + ")" } g.P(cs.typ, " ", cs.sym, " = ", v) } // Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects. type Object interface { PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness. TypeName() []string File() *descriptor.FileDescriptorProto } // Each package name we generate must be unique. The package we're generating // gets its own name but every other package must have a unique name that does // not conflict in the code we generate. These names are chosen globally (although // they don't have to be, it simplifies things to do them globally). func uniquePackageOf(fd *descriptor.FileDescriptorProto) string { s, ok := uniquePackageName[fd] if !ok { log.Fatal("internal error: no package name defined for " + fd.GetName()) } return s } // Generator is the type whose methods generate the output, stored in the associated response structure. type Generator struct { *bytes.Buffer Request *plugin.CodeGeneratorRequest // The input. Response *plugin.CodeGeneratorResponse // The output. Param map[string]string // Command-line parameters. PackageImportPath string // Go import path of the package we're generating code for ImportPrefix string // String to prefix to imported package file names. ImportMap map[string]string // Mapping from .proto file name to import path Pkg map[string]string // The names under which we import support packages packageName string // What we're calling ourselves. allFiles []*FileDescriptor // All files in the tree allFilesByName map[string]*FileDescriptor // All files by filename. genFiles []*FileDescriptor // Those files we will generate output for. file *FileDescriptor // The file we are compiling now. usedPackages map[string]bool // Names of packages used in current file. typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax. init []string // Lines to emit in the init function. indent string writeOutput bool } // New creates a new generator and allocates the request and response protobufs. func New() *Generator { g := new(Generator) g.Buffer = new(bytes.Buffer) g.Request = new(plugin.CodeGeneratorRequest) g.Response = new(plugin.CodeGeneratorResponse) return g } // Error reports a problem, including an error, and exits the program. func (g *Generator) Error(err error, msgs ...string) { s := strings.Join(msgs, " ") + ":" + err.Error() log.Print("protoc-gen-go: error:", s) os.Exit(1) } // Fail reports a problem and exits the program. func (g *Generator) Fail(msgs ...string) { s := strings.Join(msgs, " ") log.Print("protoc-gen-go: error:", s) os.Exit(1) } // CommandLineParameters breaks the comma-separated list of key=value pairs // in the parameter (a member of the request protobuf) into a key/value map. // It then sets file name mappings defined by those entries. func (g *Generator) CommandLineParameters(parameter string) { g.Param = make(map[string]string) for _, p := range strings.Split(parameter, ",") { if i := strings.Index(p, "="); i < 0 { g.Param[p] = "" } else { g.Param[p[0:i]] = p[i+1:] } } g.ImportMap = make(map[string]string) pluginList := "none" // Default list of plugin names to enable (empty means all). for k, v := range g.Param { switch k { case "import_prefix": g.ImportPrefix = v case "import_path": g.PackageImportPath = v case "plugins": pluginList = v default: if len(k) > 0 && k[0] == 'M' { g.ImportMap[k[1:]] = v } } } if pluginList != "" { // Amend the set of plugins. enabled := make(map[string]bool) for _, name := range strings.Split(pluginList, "+") { enabled[name] = true } var nplugins []Plugin for _, p := range plugins { if enabled[p.Name()] { nplugins = append(nplugins, p) } } plugins = nplugins } } // DefaultPackageName returns the package name printed for the object. // If its file is in a different package, it returns the package name we're using for this file, plus ".". // Otherwise it returns the empty string. func (g *Generator) DefaultPackageName(obj Object) string { pkg := obj.PackageName() if pkg == g.packageName { return "" } return pkg + "." } // For each input file, the unique package name to use, underscored. var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string) // Package names already registered. Key is the name from the .proto file; // value is the name that appears in the generated code. var pkgNamesInUse = make(map[string]bool) // Create and remember a guaranteed unique package name for this file descriptor. // Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and // has no file descriptor. func RegisterUniquePackageName(pkg string, f *FileDescriptor) string { // Convert dots to underscores before finding a unique alias. pkg = strings.Map(badToUnderscore, pkg) for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ { // It's a duplicate; must rename. pkg = orig + strconv.Itoa(i) } // Install it. pkgNamesInUse[pkg] = true if f != nil { uniquePackageName[f.FileDescriptorProto] = pkg } return pkg } var isGoKeyword = map[string]bool{ "break": true, "case": true, "chan": true, "const": true, "continue": true, "default": true, "else": true, "defer": true, "fallthrough": true, "for": true, "func": true, "go": true, "goto": true, "if": true, "import": true, "interface": true, "map": true, "package": true, "range": true, "return": true, "select": true, "struct": true, "switch": true, "type": true, "var": true, } // defaultGoPackage returns the package name to use, // derived from the import path of the package we're building code for. func (g *Generator) defaultGoPackage() string { p := g.PackageImportPath if i := strings.LastIndex(p, "/"); i >= 0 { p = p[i+1:] } if p == "" { return "" } p = strings.Map(badToUnderscore, p) // Identifier must not be keyword: insert _. if isGoKeyword[p] { p = "_" + p } // Identifier must not begin with digit: insert _. if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) { p = "_" + p } return p } // SetPackageNames sets the package name for this run. // The package name must agree across all files being generated. // It also defines unique package names for all imported files. func (g *Generator) SetPackageNames() { // Register the name for this package. It will be the first name // registered so is guaranteed to be unmodified. pkg, explicit := g.genFiles[0].goPackageName() // Check all files for an explicit go_package option. for _, f := range g.genFiles { thisPkg, thisExplicit := f.goPackageName() if thisExplicit { if !explicit { // Let this file's go_package option serve for all input files. pkg, explicit = thisPkg, true } else if thisPkg != pkg { g.Fail("inconsistent package names:", thisPkg, pkg) } } } // If we don't have an explicit go_package option but we have an // import path, use that. if !explicit { p := g.defaultGoPackage() if p != "" { pkg, explicit = p, true } } // If there was no go_package and no import path to use, // double-check that all the inputs have the same implicit // Go package name. if !explicit { for _, f := range g.genFiles { thisPkg, _ := f.goPackageName() if thisPkg != pkg { g.Fail("inconsistent package names:", thisPkg, pkg) } } } g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0]) // Register the support package names. They might collide with the // name of a package we import. g.Pkg = map[string]string{ "fmt": RegisterUniquePackageName("fmt", nil), "math": RegisterUniquePackageName("math", nil), "proto": RegisterUniquePackageName("proto", nil), } AllFiles: for _, f := range g.allFiles { for _, genf := range g.genFiles { if f == genf { // In this package already. uniquePackageName[f.FileDescriptorProto] = g.packageName continue AllFiles } } // The file is a dependency, so we want to ignore its go_package option // because that is only relevant for its specific generated output. pkg := f.GetPackage() if pkg == "" { pkg = baseName(*f.Name) } RegisterUniquePackageName(pkg, f) } } // WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos // and FileDescriptorProtos into file-referenced objects within the Generator. // It also creates the list of files to generate and so should be called before GenerateAllFiles. func (g *Generator) WrapTypes() { g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile)) g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles)) for _, f := range g.Request.ProtoFile { // We must wrap the descriptors before we wrap the enums descs := wrapDescriptors(f) g.buildNestedDescriptors(descs) enums := wrapEnumDescriptors(f, descs) g.buildNestedEnums(descs, enums) exts := wrapExtensions(f) fd := &FileDescriptor{ FileDescriptorProto: f, desc: descs, enum: enums, ext: exts, exported: make(map[Object][]symbol), proto3: fileIsProto3(f), } extractComments(fd) g.allFiles = append(g.allFiles, fd) g.allFilesByName[f.GetName()] = fd } for _, fd := range g.allFiles { fd.imp = wrapImported(fd.FileDescriptorProto, g) } g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate)) for _, fileName := range g.Request.FileToGenerate { fd := g.allFilesByName[fileName] if fd == nil { g.Fail("could not find file named", fileName) } fd.index = len(g.genFiles) g.genFiles = append(g.genFiles, fd) } } // Scan the descriptors in this file. For each one, build the slice of nested descriptors func (g *Generator) buildNestedDescriptors(descs []*Descriptor) { for _, desc := range descs { if len(desc.NestedType) != 0 { for _, nest := range descs { if nest.parent == desc { desc.nested = append(desc.nested, nest) } } if len(desc.nested) != len(desc.NestedType) { g.Fail("internal error: nesting failure for", desc.GetName()) } } } } func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) { for _, desc := range descs { if len(desc.EnumType) != 0 { for _, enum := range enums { if enum.parent == desc { desc.enums = append(desc.enums, enum) } } if len(desc.enums) != len(desc.EnumType) { g.Fail("internal error: enum nesting failure for", desc.GetName()) } } } } // Construct the Descriptor func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *Descriptor { d := &Descriptor{ common: common{file}, DescriptorProto: desc, parent: parent, index: index, } if parent == nil { d.path = fmt.Sprintf("%d,%d", messagePath, index) } else { d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index) } // The only way to distinguish a group from a message is whether // the containing message has a TYPE_GROUP field that matches. if parent != nil { parts := d.TypeName() if file.Package != nil { parts = append([]string{*file.Package}, parts...) } exp := "." + strings.Join(parts, ".") for _, field := range parent.Field { if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp { d.group = true break } } } for _, field := range desc.Extension { d.ext = append(d.ext, &ExtensionDescriptor{common{file}, field, d}) } return d } // Return a slice of all the Descriptors defined within this file func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor { sl := make([]*Descriptor, 0, len(file.MessageType)+10) for i, desc := range file.MessageType { sl = wrapThisDescriptor(sl, desc, nil, file, i) } return sl } // Wrap this Descriptor, recursively func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) []*Descriptor { sl = append(sl, newDescriptor(desc, parent, file, index)) me := sl[len(sl)-1] for i, nested := range desc.NestedType { sl = wrapThisDescriptor(sl, nested, me, file, i) } return sl } // Construct the EnumDescriptor func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *EnumDescriptor { ed := &EnumDescriptor{ common: common{file}, EnumDescriptorProto: desc, parent: parent, index: index, } if parent == nil { ed.path = fmt.Sprintf("%d,%d", enumPath, index) } else { ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index) } return ed } // Return a slice of all the EnumDescriptors defined within this file func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor { sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10) // Top-level enums. for i, enum := range file.EnumType { sl = append(sl, newEnumDescriptor(enum, nil, file, i)) } // Enums within messages. Enums within embedded messages appear in the outer-most message. for _, nested := range descs { for i, enum := range nested.EnumType { sl = append(sl, newEnumDescriptor(enum, nested, file, i)) } } return sl } // Return a slice of all the top-level ExtensionDescriptors defined within this file. func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor { var sl []*ExtensionDescriptor for _, field := range file.Extension { sl = append(sl, &ExtensionDescriptor{common{file}, field, nil}) } return sl } // Return a slice of all the types that are publicly imported into this file. func wrapImported(file *descriptor.FileDescriptorProto, g *Generator) (sl []*ImportedDescriptor) { for _, index := range file.PublicDependency { df := g.fileByName(file.Dependency[index]) for _, d := range df.desc { if d.GetOptions().GetMapEntry() { continue } sl = append(sl, &ImportedDescriptor{common{file}, d}) } for _, e := range df.enum { sl = append(sl, &ImportedDescriptor{common{file}, e}) } for _, ext := range df.ext { sl = append(sl, &ImportedDescriptor{common{file}, ext}) } } return } func extractComments(file *FileDescriptor) { file.comments = make(map[string]*descriptor.SourceCodeInfo_Location) for _, loc := range file.GetSourceCodeInfo().GetLocation() { if loc.LeadingComments == nil { continue } var p []string for _, n := range loc.Path { p = append(p, strconv.Itoa(int(n))) } file.comments[strings.Join(p, ",")] = loc } } // BuildTypeNameMap builds the map from fully qualified type names to objects. // The key names for the map come from the input data, which puts a period at the beginning. // It should be called after SetPackageNames and before GenerateAllFiles. func (g *Generator) BuildTypeNameMap() { g.typeNameToObject = make(map[string]Object) for _, f := range g.allFiles { // The names in this loop are defined by the proto world, not us, so the // package name may be empty. If so, the dotted package name of X will // be ".X"; otherwise it will be ".pkg.X". dottedPkg := "." + f.GetPackage() if dottedPkg != "." { dottedPkg += "." } for _, enum := range f.enum { name := dottedPkg + dottedSlice(enum.TypeName()) g.typeNameToObject[name] = enum } for _, desc := range f.desc { name := dottedPkg + dottedSlice(desc.TypeName()) g.typeNameToObject[name] = desc } } } // ObjectNamed, given a fully-qualified input type name as it appears in the input data, // returns the descriptor for the message or enum with that name. func (g *Generator) ObjectNamed(typeName string) Object { o, ok := g.typeNameToObject[typeName] if !ok { g.Fail("can't find object with type", typeName) } // If the file of this object isn't a direct dependency of the current file, // or in the current file, then this object has been publicly imported into // a dependency of the current file. // We should return the ImportedDescriptor object for it instead. direct := *o.File().Name == *g.file.Name if !direct { for _, dep := range g.file.Dependency { if *g.fileByName(dep).Name == *o.File().Name { direct = true break } } } if !direct { found := false Loop: for _, dep := range g.file.Dependency { df := g.fileByName(*g.fileByName(dep).Name) for _, td := range df.imp { if td.o == o { // Found it! o = td found = true break Loop } } } if !found { log.Printf("protoc-gen-go: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name) } } return o } // P prints the arguments to the generated output. It handles strings and int32s, plus // handling indirections because they may be *string, etc. func (g *Generator) P(str ...interface{}) { if !g.writeOutput { return } g.WriteString(g.indent) for _, v := range str { switch s := v.(type) { case string: g.WriteString(s) case *string: g.WriteString(*s) case bool: fmt.Fprintf(g, "%t", s) case *bool: fmt.Fprintf(g, "%t", *s) case int: fmt.Fprintf(g, "%d", s) case *int32: fmt.Fprintf(g, "%d", *s) case *int64: fmt.Fprintf(g, "%d", *s) case float64: fmt.Fprintf(g, "%g", s) case *float64: fmt.Fprintf(g, "%g", *s) default: g.Fail(fmt.Sprintf("unknown type in printer: %T", v)) } } g.WriteByte('\n') } // addInitf stores the given statement to be printed inside the file's init function. // The statement is given as a format specifier and arguments. func (g *Generator) addInitf(stmt string, a ...interface{}) { g.init = append(g.init, fmt.Sprintf(stmt, a...)) } // In Indents the output one tab stop. func (g *Generator) In() { g.indent += "\t" } // Out unindents the output one tab stop. func (g *Generator) Out() { if len(g.indent) > 0 { g.indent = g.indent[1:] } } // GenerateAllFiles generates the output for all the files we're outputting. func (g *Generator) GenerateAllFiles() { // Initialize the plugins for _, p := range plugins { p.Init(g) } // Generate the output. The generator runs for every file, even the files // that we don't generate output for, so that we can collate the full list // of exported symbols to support public imports. genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles)) for _, file := range g.genFiles { genFileMap[file] = true } for _, file := range g.allFiles { g.Reset() g.writeOutput = genFileMap[file] g.generate(file) if !g.writeOutput { continue } g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{ Name: proto.String(file.goFileName()), Content: proto.String(g.String()), }) } } // Run all the plugins associated with the file. func (g *Generator) runPlugins(file *FileDescriptor) { for _, p := range plugins { p.Generate(file) } } // FileOf return the FileDescriptor for this FileDescriptorProto. func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor { for _, file := range g.allFiles { if file.FileDescriptorProto == fd { return file } } g.Fail("could not find file in table:", fd.GetName()) return nil } // Fill the response protocol buffer with the generated output for all the files we're // supposed to generate. func (g *Generator) generate(file *FileDescriptor) { g.file = g.FileOf(file.FileDescriptorProto) g.usedPackages = make(map[string]bool) if g.file.index == 0 { // For one file in the package, assert version compatibility. g.P("// This is a compile-time assertion to ensure that this generated file") g.P("// is compatible with the proto package it is being compiled against.") g.P("// A compilation error at this line likely means your copy of the") g.P("// proto package needs to be updated.") g.P("const _ = ", g.Pkg["proto"], ".ProtoPackageIsVersion", generatedCodeVersion, " // please upgrade the proto package") g.P() } for _, td := range g.file.imp { g.generateImported(td) } for _, enum := range g.file.enum { g.generateEnum(enum) } for _, desc := range g.file.desc { // Don't generate virtual messages for maps. if desc.GetOptions().GetMapEntry() { continue } g.generateMessage(desc) } for _, ext := range g.file.ext { g.generateExtension(ext) } g.generateInitFunction() // Run the plugins before the imports so we know which imports are necessary. g.runPlugins(file) g.generateFileDescriptor(file) // Generate header and imports last, though they appear first in the output. rem := g.Buffer g.Buffer = new(bytes.Buffer) g.generateHeader() g.generateImports() if !g.writeOutput { return } g.Write(rem.Bytes()) // Reformat generated code. fset := token.NewFileSet() raw := g.Bytes() ast, err := parser.ParseFile(fset, "", g, parser.ParseComments) if err != nil { // Print out the bad code with line numbers. // This should never happen in practice, but it can while changing generated code, // so consider this a debugging aid. var src bytes.Buffer s := bufio.NewScanner(bytes.NewReader(raw)) for line := 1; s.Scan(); line++ { fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes()) } g.Fail("bad Go source code was generated:", err.Error(), "\n"+src.String()) } g.Reset() err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast) if err != nil { g.Fail("generated Go source code could not be reformatted:", err.Error()) } } // Generate the header, including package definition func (g *Generator) generateHeader() { g.P("// Code generated by protoc-gen-go. DO NOT EDIT.") g.P("// source: ", g.file.Name) g.P() name := g.file.PackageName() if g.file.index == 0 { // Generate package docs for the first file in the package. g.P("/*") g.P("Package ", name, " is a generated protocol buffer package.") g.P() if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok { // not using g.PrintComments because this is a /* */ comment block. text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") for _, line := range strings.Split(text, "\n") { line = strings.TrimPrefix(line, " ") // ensure we don't escape from the block comment line = strings.Replace(line, "*/", "* /", -1) g.P(line) } g.P() } var topMsgs []string g.P("It is generated from these files:") for _, f := range g.genFiles { g.P("\t", f.Name) for _, msg := range f.desc { if msg.parent != nil { continue } topMsgs = append(topMsgs, CamelCaseSlice(msg.TypeName())) } } g.P() g.P("It has these top-level messages:") for _, msg := range topMsgs { g.P("\t", msg) } g.P("*/") } g.P("package ", name) g.P() } // PrintComments prints any comments from the source .proto file. // The path is a comma-separated list of integers. // It returns an indication of whether any comments were printed. // See descriptor.proto for its format. func (g *Generator) PrintComments(path string) bool { if !g.writeOutput { return false } if loc, ok := g.file.comments[path]; ok { text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") for _, line := range strings.Split(text, "\n") { g.P("// ", strings.TrimPrefix(line, " ")) } return true } return false } func (g *Generator) fileByName(filename string) *FileDescriptor { return g.allFilesByName[filename] } // weak returns whether the ith import of the current file is a weak import. func (g *Generator) weak(i int32) bool { for _, j := range g.file.WeakDependency { if j == i { return true } } return false } // Generate the imports func (g *Generator) generateImports() { // We almost always need a proto import. Rather than computing when we // do, which is tricky when there's a plugin, just import it and // reference it later. The same argument applies to the fmt and math packages. g.P("import " + g.Pkg["proto"] + " " + strconv.Quote(g.ImportPrefix+"github.com/golang/protobuf/proto")) g.P("import " + g.Pkg["fmt"] + ` "fmt"`) g.P("import " + g.Pkg["math"] + ` "math"`) for i, s := range g.file.Dependency { fd := g.fileByName(s) // Do not import our own package. if fd.PackageName() == g.packageName { continue } filename := fd.goFileName() // By default, import path is the dirname of the Go filename. importPath := path.Dir(filename) if substitution, ok := g.ImportMap[s]; ok { importPath = substitution } importPath = g.ImportPrefix + importPath // Skip weak imports. if g.weak(int32(i)) { g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(importPath)) continue } // We need to import all the dependencies, even if we don't reference them, // because other code and tools depend on having the full transitive closure // of protocol buffer types in the binary. pname := fd.PackageName() if _, ok := g.usedPackages[pname]; !ok { pname = "_" } g.P("import ", pname, " ", strconv.Quote(importPath)) } g.P() // TODO: may need to worry about uniqueness across plugins for _, p := range plugins { p.GenerateImports(g.file) g.P() } g.P("// Reference imports to suppress errors if they are not otherwise used.") g.P("var _ = ", g.Pkg["proto"], ".Marshal") g.P("var _ = ", g.Pkg["fmt"], ".Errorf") g.P("var _ = ", g.Pkg["math"], ".Inf") g.P() } func (g *Generator) generateImported(id *ImportedDescriptor) { // Don't generate public import symbols for files that we are generating // code for, since those symbols will already be in this package. // We can't simply avoid creating the ImportedDescriptor objects, // because g.genFiles isn't populated at that stage. tn := id.TypeName() sn := tn[len(tn)-1] df := g.FileOf(id.o.File()) filename := *df.Name for _, fd := range g.genFiles { if *fd.Name == filename { g.P("// Ignoring public import of ", sn, " from ", filename) g.P() return } } g.P("// ", sn, " from public import ", filename) g.usedPackages[df.PackageName()] = true for _, sym := range df.exported[id.o] { sym.GenerateAlias(g, df.PackageName()) } g.P() } // Generate the enum definitions for this EnumDescriptor. func (g *Generator) generateEnum(enum *EnumDescriptor) { // The full type name typeName := enum.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) ccPrefix := enum.prefix() g.PrintComments(enum.path) g.P("type ", ccTypeName, " int32") g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()}) g.P("const (") g.In() for i, e := range enum.Value { g.PrintComments(fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i)) name := ccPrefix + *e.Name g.P(name, " ", ccTypeName, " = ", e.Number) g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName}) } g.Out() g.P(")") g.P("var ", ccTypeName, "_name = map[int32]string{") g.In() generated := make(map[int32]bool) // avoid duplicate values for _, e := range enum.Value { duplicate := "" if _, present := generated[*e.Number]; present { duplicate = "// Duplicate value: " } g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",") generated[*e.Number] = true } g.Out() g.P("}") g.P("var ", ccTypeName, "_value = map[string]int32{") g.In() for _, e := range enum.Value { g.P(strconv.Quote(*e.Name), ": ", e.Number, ",") } g.Out() g.P("}") if !enum.proto3() { g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {") g.In() g.P("p := new(", ccTypeName, ")") g.P("*p = x") g.P("return p") g.Out() g.P("}") } g.P("func (x ", ccTypeName, ") String() string {") g.In() g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))") g.Out() g.P("}") if !enum.proto3() { g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {") g.In() g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`) g.P("if err != nil {") g.In() g.P("return err") g.Out() g.P("}") g.P("*x = ", ccTypeName, "(value)") g.P("return nil") g.Out() g.P("}") } var indexes []string for m := enum.parent; m != nil; m = m.parent { // XXX: skip groups? indexes = append([]string{strconv.Itoa(m.index)}, indexes...) } indexes = append(indexes, strconv.Itoa(enum.index)) g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) { return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "} }") if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" { g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`) } g.P() } // The tag is a string like "varint,2,opt,name=fieldname,def=7" that // identifies details of the field for the protocol buffer marshaling and unmarshaling // code. The fields are: // wire encoding // protocol tag number // opt,req,rep for optional, required, or repeated // packed whether the encoding is "packed" (optional; repeated primitives only) // name= the original declared name // enum= the name of the enum type if it is an enum-typed field. // proto3 if this field is in a proto3 message // def= string representation of the default value, if any. // The default value must be in a representation that can be used at run-time // to generate the default value. Thus bools become 0 and 1, for instance. func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string { optrepreq := "" switch { case isOptional(field): optrepreq = "opt" case isRequired(field): optrepreq = "req" case isRepeated(field): optrepreq = "rep" } var defaultValue string if dv := field.DefaultValue; dv != nil { // set means an explicit default defaultValue = *dv // Some types need tweaking. switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: if defaultValue == "true" { defaultValue = "1" } else { defaultValue = "0" } case descriptor.FieldDescriptorProto_TYPE_STRING, descriptor.FieldDescriptorProto_TYPE_BYTES: // Nothing to do. Quoting is done for the whole tag. case descriptor.FieldDescriptorProto_TYPE_ENUM: // For enums we need to provide the integer constant. obj := g.ObjectNamed(field.GetTypeName()) if id, ok := obj.(*ImportedDescriptor); ok { // It is an enum that was publicly imported. // We need the underlying type. obj = id.o } enum, ok := obj.(*EnumDescriptor) if !ok { log.Printf("obj is a %T", obj) if id, ok := obj.(*ImportedDescriptor); ok { log.Printf("id.o is a %T", id.o) } g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName())) } defaultValue = enum.integerValueAsString(defaultValue) } defaultValue = ",def=" + defaultValue } enum := "" if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM { // We avoid using obj.PackageName(), because we want to use the // original (proto-world) package name. obj := g.ObjectNamed(field.GetTypeName()) if id, ok := obj.(*ImportedDescriptor); ok { obj = id.o } enum = ",enum=" if pkg := obj.File().GetPackage(); pkg != "" { enum += pkg + "." } enum += CamelCaseSlice(obj.TypeName()) } packed := "" if (field.Options != nil && field.Options.GetPacked()) || // Per https://developers.google.com/protocol-buffers/docs/proto3#simple: // "In proto3, repeated fields of scalar numeric types use packed encoding by default." (message.proto3() && (field.Options == nil || field.Options.Packed == nil) && isRepeated(field) && isScalar(field)) { packed = ",packed" } fieldName := field.GetName() name := fieldName if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { // We must use the type name for groups instead of // the field name to preserve capitalization. // type_name in FieldDescriptorProto is fully-qualified, // but we only want the local part. name = *field.TypeName if i := strings.LastIndex(name, "."); i >= 0 { name = name[i+1:] } } if json := field.GetJsonName(); json != "" && json != name { // TODO: escaping might be needed, in which case // perhaps this should be in its own "json" tag. name += ",json=" + json } name = ",name=" + name if message.proto3() { // We only need the extra tag for []byte fields; // no need to add noise for the others. if *field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES { name += ",proto3" } } oneof := "" if field.OneofIndex != nil { oneof = ",oneof" } return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s%s", wiretype, field.GetNumber(), optrepreq, packed, name, enum, oneof, defaultValue)) } func needsStar(typ descriptor.FieldDescriptorProto_Type) bool { switch typ { case descriptor.FieldDescriptorProto_TYPE_GROUP: return false case descriptor.FieldDescriptorProto_TYPE_MESSAGE: return false case descriptor.FieldDescriptorProto_TYPE_BYTES: return false } return true } // TypeName is the printed name appropriate for an item. If the object is in the current file, // TypeName drops the package name and underscores the rest. // Otherwise the object is from another package; and the result is the underscored // package name followed by the item name. // The result always has an initial capital. func (g *Generator) TypeName(obj Object) string { return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName()) } // TypeNameWithPackage is like TypeName, but always includes the package // name even if the object is in our own package. func (g *Generator) TypeNameWithPackage(obj Object) string { return obj.PackageName() + CamelCaseSlice(obj.TypeName()) } // GoType returns a string representing the type name, and the wire type func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) { // TODO: Options. switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: typ, wire = "float64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_FLOAT: typ, wire = "float32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_INT64: typ, wire = "int64", "varint" case descriptor.FieldDescriptorProto_TYPE_UINT64: typ, wire = "uint64", "varint" case descriptor.FieldDescriptorProto_TYPE_INT32: typ, wire = "int32", "varint" case descriptor.FieldDescriptorProto_TYPE_UINT32: typ, wire = "uint32", "varint" case descriptor.FieldDescriptorProto_TYPE_FIXED64: typ, wire = "uint64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_FIXED32: typ, wire = "uint32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_BOOL: typ, wire = "bool", "varint" case descriptor.FieldDescriptorProto_TYPE_STRING: typ, wire = "string", "bytes" case descriptor.FieldDescriptorProto_TYPE_GROUP: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = "*"+g.TypeName(desc), "group" case descriptor.FieldDescriptorProto_TYPE_MESSAGE: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = "*"+g.TypeName(desc), "bytes" case descriptor.FieldDescriptorProto_TYPE_BYTES: typ, wire = "[]byte", "bytes" case descriptor.FieldDescriptorProto_TYPE_ENUM: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = g.TypeName(desc), "varint" case descriptor.FieldDescriptorProto_TYPE_SFIXED32: typ, wire = "int32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_SFIXED64: typ, wire = "int64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_SINT32: typ, wire = "int32", "zigzag32" case descriptor.FieldDescriptorProto_TYPE_SINT64: typ, wire = "int64", "zigzag64" default: g.Fail("unknown type for", field.GetName()) } if isRepeated(field) { typ = "[]" + typ } else if message != nil && message.proto3() { return } else if field.OneofIndex != nil && message != nil { return } else if needsStar(*field.Type) { typ = "*" + typ } return } func (g *Generator) RecordTypeUse(t string) { if obj, ok := g.typeNameToObject[t]; ok { // Call ObjectNamed to get the true object to record the use. obj = g.ObjectNamed(t) g.usedPackages[obj.PackageName()] = true } } // Method names that may be generated. Fields with these names get an // underscore appended. Any change to this set is a potential incompatible // API change because it changes generated field names. var methodNames = [...]string{ "Reset", "String", "ProtoMessage", "Marshal", "Unmarshal", "ExtensionRangeArray", "ExtensionMap", "Descriptor", } // Names of messages in the `google.protobuf` package for which // we will generate XXX_WellKnownType methods. var wellKnownTypes = map[string]bool{ "Any": true, "Duration": true, "Empty": true, "Struct": true, "Timestamp": true, "Value": true, "ListValue": true, "DoubleValue": true, "FloatValue": true, "Int64Value": true, "UInt64Value": true, "Int32Value": true, "UInt32Value": true, "BoolValue": true, "StringValue": true, "BytesValue": true, } // Generate the type and default constant definitions for this Descriptor. func (g *Generator) generateMessage(message *Descriptor) { // The full type name typeName := message.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) usedNames := make(map[string]bool) for _, n := range methodNames { usedNames[n] = true } fieldNames := make(map[*descriptor.FieldDescriptorProto]string) fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string) fieldTypes := make(map[*descriptor.FieldDescriptorProto]string) mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string) oneofFieldName := make(map[int32]string) // indexed by oneof_index field of FieldDescriptorProto oneofDisc := make(map[int32]string) // name of discriminator method oneofTypeName := make(map[*descriptor.FieldDescriptorProto]string) // without star oneofInsertPoints := make(map[int32]int) // oneof_index => offset of g.Buffer g.PrintComments(message.path) g.P("type ", ccTypeName, " struct {") g.In() // allocNames finds a conflict-free variation of the given strings, // consistently mutating their suffixes. // It returns the same number of strings. allocNames := func(ns ...string) []string { Loop: for { for _, n := range ns { if usedNames[n] { for i := range ns { ns[i] += "_" } continue Loop } } for _, n := range ns { usedNames[n] = true } return ns } } for i, field := range message.Field { // Allocate the getter and the field at the same time so name // collisions create field/method consistent names. // TODO: This allocation occurs based on the order of the fields // in the proto file, meaning that a change in the field // ordering can change generated Method/Field names. base := CamelCase(*field.Name) ns := allocNames(base, "Get"+base) fieldName, fieldGetterName := ns[0], ns[1] typename, wiretype := g.GoType(message, field) jsonName := *field.Name tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty") fieldNames[field] = fieldName fieldGetterNames[field] = fieldGetterName oneof := field.OneofIndex != nil if oneof && oneofFieldName[*field.OneofIndex] == "" { odp := message.OneofDecl[int(*field.OneofIndex)] fname := allocNames(CamelCase(odp.GetName()))[0] // This is the first field of a oneof we haven't seen before. // Generate the union field. com := g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex)) if com { g.P("//") } g.P("// Types that are valid to be assigned to ", fname, ":") // Generate the rest of this comment later, // when we've computed any disambiguation. oneofInsertPoints[*field.OneofIndex] = g.Buffer.Len() dname := "is" + ccTypeName + "_" + fname oneofFieldName[*field.OneofIndex] = fname oneofDisc[*field.OneofIndex] = dname tag := `protobuf_oneof:"` + odp.GetName() + `"` g.P(fname, " ", dname, " `", tag, "`") } if *field.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE { desc := g.ObjectNamed(field.GetTypeName()) if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() { // Figure out the Go types and tags for the key and value types. keyField, valField := d.Field[0], d.Field[1] keyType, keyWire := g.GoType(d, keyField) valType, valWire := g.GoType(d, valField) keyTag, valTag := g.goTag(d, keyField, keyWire), g.goTag(d, valField, valWire) // We don't use stars, except for message-typed values. // Message and enum types are the only two possibly foreign types used in maps, // so record their use. They are not permitted as map keys. keyType = strings.TrimPrefix(keyType, "*") switch *valField.Type { case descriptor.FieldDescriptorProto_TYPE_ENUM: valType = strings.TrimPrefix(valType, "*") g.RecordTypeUse(valField.GetTypeName()) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: g.RecordTypeUse(valField.GetTypeName()) default: valType = strings.TrimPrefix(valType, "*") } typename = fmt.Sprintf("map[%s]%s", keyType, valType) mapFieldTypes[field] = typename // record for the getter generation tag += fmt.Sprintf(" protobuf_key:%s protobuf_val:%s", keyTag, valTag) } } fieldTypes[field] = typename if oneof { tname := ccTypeName + "_" + fieldName // It is possible for this to collide with a message or enum // nested in this message. Check for collisions. for { ok := true for _, desc := range message.nested { if CamelCaseSlice(desc.TypeName()) == tname { ok = false break } } for _, enum := range message.enums { if CamelCaseSlice(enum.TypeName()) == tname { ok = false break } } if !ok { tname += "_" continue } break } oneofTypeName[field] = tname continue } g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)) g.P(fieldName, "\t", typename, "\t`", tag, "`") g.RecordTypeUse(field.GetTypeName()) } if len(message.ExtensionRange) > 0 { g.P(g.Pkg["proto"], ".XXX_InternalExtensions `json:\"-\"`") } if !message.proto3() { g.P("XXX_unrecognized\t[]byte `json:\"-\"`") } g.Out() g.P("}") // Update g.Buffer to list valid oneof types. // We do this down here, after we've disambiguated the oneof type names. // We go in reverse order of insertion point to avoid invalidating offsets. for oi := int32(len(message.OneofDecl)); oi >= 0; oi-- { ip := oneofInsertPoints[oi] all := g.Buffer.Bytes() rem := all[ip:] g.Buffer = bytes.NewBuffer(all[:ip:ip]) // set cap so we don't scribble on rem for _, field := range message.Field { if field.OneofIndex == nil || *field.OneofIndex != oi { continue } g.P("//\t*", oneofTypeName[field]) } g.Buffer.Write(rem) } // Reset, String and ProtoMessage methods. g.P("func (m *", ccTypeName, ") Reset() { *m = ", ccTypeName, "{} }") g.P("func (m *", ccTypeName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }") g.P("func (*", ccTypeName, ") ProtoMessage() {}") var indexes []string for m := message; m != nil; m = m.parent { indexes = append([]string{strconv.Itoa(m.index)}, indexes...) } g.P("func (*", ccTypeName, ") Descriptor() ([]byte, []int) { return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "} }") // TODO: Revisit the decision to use a XXX_WellKnownType method // if we change proto.MessageName to work with multiple equivalents. if message.file.GetPackage() == "google.protobuf" && wellKnownTypes[message.GetName()] { g.P("func (*", ccTypeName, `) XXX_WellKnownType() string { return "`, message.GetName(), `" }`) } // Extension support methods var hasExtensions, isMessageSet bool if len(message.ExtensionRange) > 0 { hasExtensions = true // message_set_wire_format only makes sense when extensions are defined. if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() { isMessageSet = true g.P() g.P("func (m *", ccTypeName, ") Marshal() ([]byte, error) {") g.In() g.P("return ", g.Pkg["proto"], ".MarshalMessageSet(&m.XXX_InternalExtensions)") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") Unmarshal(buf []byte) error {") g.In() g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSet(buf, &m.XXX_InternalExtensions)") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") MarshalJSON() ([]byte, error) {") g.In() g.P("return ", g.Pkg["proto"], ".MarshalMessageSetJSON(&m.XXX_InternalExtensions)") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") UnmarshalJSON(buf []byte) error {") g.In() g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)") g.Out() g.P("}") g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler") g.P("var _ ", g.Pkg["proto"], ".Marshaler = (*", ccTypeName, ")(nil)") g.P("var _ ", g.Pkg["proto"], ".Unmarshaler = (*", ccTypeName, ")(nil)") } g.P() g.P("var extRange_", ccTypeName, " = []", g.Pkg["proto"], ".ExtensionRange{") g.In() for _, r := range message.ExtensionRange { end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends g.P("{", r.Start, ", ", end, "},") } g.Out() g.P("}") g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {") g.In() g.P("return extRange_", ccTypeName) g.Out() g.P("}") } // Default constants defNames := make(map[*descriptor.FieldDescriptorProto]string) for _, field := range message.Field { def := field.GetDefaultValue() if def == "" { continue } fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name) defNames[field] = fieldname typename, _ := g.GoType(message, field) if typename[0] == '*' { typename = typename[1:] } kind := "const " switch { case typename == "bool": case typename == "string": def = strconv.Quote(def) case typename == "[]byte": def = "[]byte(" + strconv.Quote(unescape(def)) + ")" kind = "var " case def == "inf", def == "-inf", def == "nan": // These names are known to, and defined by, the protocol language. switch def { case "inf": def = "math.Inf(1)" case "-inf": def = "math.Inf(-1)" case "nan": def = "math.NaN()" } if *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT { def = "float32(" + def + ")" } kind = "var " case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM: // Must be an enum. Need to construct the prefixed name. obj := g.ObjectNamed(field.GetTypeName()) var enum *EnumDescriptor if id, ok := obj.(*ImportedDescriptor); ok { // The enum type has been publicly imported. enum, _ = id.o.(*EnumDescriptor) } else { enum, _ = obj.(*EnumDescriptor) } if enum == nil { log.Printf("don't know how to generate constant for %s", fieldname) continue } def = g.DefaultPackageName(obj) + enum.prefix() + def } g.P(kind, fieldname, " ", typename, " = ", def) g.file.addExport(message, constOrVarSymbol{fieldname, kind, ""}) } g.P() // Oneof per-field types, discriminants and getters. // // Generate unexported named types for the discriminant interfaces. // We shouldn't have to do this, but there was (~19 Aug 2015) a compiler/linker bug // that was triggered by using anonymous interfaces here. // TODO: Revisit this and consider reverting back to anonymous interfaces. for oi := range message.OneofDecl { dname := oneofDisc[int32(oi)] g.P("type ", dname, " interface { ", dname, "() }") } g.P() for _, field := range message.Field { if field.OneofIndex == nil { continue } _, wiretype := g.GoType(message, field) tag := "protobuf:" + g.goTag(message, field, wiretype) g.P("type ", oneofTypeName[field], " struct{ ", fieldNames[field], " ", fieldTypes[field], " `", tag, "` }") g.RecordTypeUse(field.GetTypeName()) } g.P() for _, field := range message.Field { if field.OneofIndex == nil { continue } g.P("func (*", oneofTypeName[field], ") ", oneofDisc[*field.OneofIndex], "() {}") } g.P() for oi := range message.OneofDecl { fname := oneofFieldName[int32(oi)] g.P("func (m *", ccTypeName, ") Get", fname, "() ", oneofDisc[int32(oi)], " {") g.P("if m != nil { return m.", fname, " }") g.P("return nil") g.P("}") } g.P() // Field getters var getters []getterSymbol for _, field := range message.Field { oneof := field.OneofIndex != nil fname := fieldNames[field] typename, _ := g.GoType(message, field) if t, ok := mapFieldTypes[field]; ok { typename = t } mname := fieldGetterNames[field] star := "" if needsStar(*field.Type) && typename[0] == '*' { typename = typename[1:] star = "*" } // Only export getter symbols for basic types, // and for messages and enums in the same package. // Groups are not exported. // Foreign types can't be hoisted through a public import because // the importer may not already be importing the defining .proto. // As an example, imagine we have an import tree like this: // A.proto -> B.proto -> C.proto // If A publicly imports B, we need to generate the getters from B in A's output, // but if one such getter returns something from C then we cannot do that // because A is not importing C already. var getter, genType bool switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_GROUP: getter = false case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_ENUM: // Only export getter if its return type is in this package. getter = g.ObjectNamed(field.GetTypeName()).PackageName() == message.PackageName() genType = true default: getter = true } if getter { getters = append(getters, getterSymbol{ name: mname, typ: typename, typeName: field.GetTypeName(), genType: genType, }) } g.P("func (m *", ccTypeName, ") "+mname+"() "+typename+" {") g.In() def, hasDef := defNames[field] typeDefaultIsNil := false // whether this field type's default value is a literal nil unless specified switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BYTES: typeDefaultIsNil = !hasDef case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE: typeDefaultIsNil = true } if isRepeated(field) { typeDefaultIsNil = true } if typeDefaultIsNil && !oneof { // A bytes field with no explicit default needs less generated code, // as does a message or group field, or a repeated field. g.P("if m != nil {") g.In() g.P("return m." + fname) g.Out() g.P("}") g.P("return nil") g.Out() g.P("}") g.P() continue } if !oneof { if message.proto3() { g.P("if m != nil {") } else { g.P("if m != nil && m." + fname + " != nil {") } g.In() g.P("return " + star + "m." + fname) g.Out() g.P("}") } else { uname := oneofFieldName[*field.OneofIndex] tname := oneofTypeName[field] g.P("if x, ok := m.Get", uname, "().(*", tname, "); ok {") g.P("return x.", fname) g.P("}") } if hasDef { if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES { g.P("return " + def) } else { // The default is a []byte var. // Make a copy when returning it to be safe. g.P("return append([]byte(nil), ", def, "...)") } } else { switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: g.P("return false") case descriptor.FieldDescriptorProto_TYPE_STRING: g.P(`return ""`) case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_BYTES: // This is only possible for oneof fields. g.P("return nil") case descriptor.FieldDescriptorProto_TYPE_ENUM: // The default default for an enum is the first value in the enum, // not zero. obj := g.ObjectNamed(field.GetTypeName()) var enum *EnumDescriptor if id, ok := obj.(*ImportedDescriptor); ok { // The enum type has been publicly imported. enum, _ = id.o.(*EnumDescriptor) } else { enum, _ = obj.(*EnumDescriptor) } if enum == nil { log.Printf("don't know how to generate getter for %s", field.GetName()) continue } if len(enum.Value) == 0 { g.P("return 0 // empty enum") } else { first := enum.Value[0].GetName() g.P("return ", g.DefaultPackageName(obj)+enum.prefix()+first) } default: g.P("return 0") } } g.Out() g.P("}") g.P() } if !message.group { ms := &messageSymbol{ sym: ccTypeName, hasExtensions: hasExtensions, isMessageSet: isMessageSet, hasOneof: len(message.OneofDecl) > 0, getters: getters, } g.file.addExport(message, ms) } // Oneof functions if len(message.OneofDecl) > 0 { fieldWire := make(map[*descriptor.FieldDescriptorProto]string) // method enc := "_" + ccTypeName + "_OneofMarshaler" dec := "_" + ccTypeName + "_OneofUnmarshaler" size := "_" + ccTypeName + "_OneofSizer" encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error" decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)" sizeSig := "(msg " + g.Pkg["proto"] + ".Message) (n int)" g.P("// XXX_OneofFuncs is for the internal use of the proto package.") g.P("func (*", ccTypeName, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {") g.P("return ", enc, ", ", dec, ", ", size, ", []interface{}{") for _, field := range message.Field { if field.OneofIndex == nil { continue } g.P("(*", oneofTypeName[field], ")(nil),") } g.P("}") g.P("}") g.P() // marshaler g.P("func ", enc, encSig, " {") g.P("m := msg.(*", ccTypeName, ")") for oi, odp := range message.OneofDecl { g.P("// ", odp.GetName()) fname := oneofFieldName[int32(oi)] g.P("switch x := m.", fname, ".(type) {") for _, field := range message.Field { if field.OneofIndex == nil || int(*field.OneofIndex) != oi { continue } g.P("case *", oneofTypeName[field], ":") var wire, pre, post string val := "x." + fieldNames[field] // overridden for TYPE_BOOL canFail := false // only TYPE_MESSAGE and TYPE_GROUP can fail switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: wire = "WireFixed64" pre = "b.EncodeFixed64(" + g.Pkg["math"] + ".Float64bits(" post = "))" case descriptor.FieldDescriptorProto_TYPE_FLOAT: wire = "WireFixed32" pre = "b.EncodeFixed32(uint64(" + g.Pkg["math"] + ".Float32bits(" post = ")))" case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64: wire = "WireVarint" pre, post = "b.EncodeVarint(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM: wire = "WireVarint" pre, post = "b.EncodeVarint(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: wire = "WireFixed64" pre, post = "b.EncodeFixed64(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: wire = "WireFixed32" pre, post = "b.EncodeFixed32(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_BOOL: // bool needs special handling. g.P("t := uint64(0)") g.P("if ", val, " { t = 1 }") val = "t" wire = "WireVarint" pre, post = "b.EncodeVarint(", ")" case descriptor.FieldDescriptorProto_TYPE_STRING: wire = "WireBytes" pre, post = "b.EncodeStringBytes(", ")" case descriptor.FieldDescriptorProto_TYPE_GROUP: wire = "WireStartGroup" pre, post = "b.Marshal(", ")" canFail = true case descriptor.FieldDescriptorProto_TYPE_MESSAGE: wire = "WireBytes" pre, post = "b.EncodeMessage(", ")" canFail = true case descriptor.FieldDescriptorProto_TYPE_BYTES: wire = "WireBytes" pre, post = "b.EncodeRawBytes(", ")" case descriptor.FieldDescriptorProto_TYPE_SINT32: wire = "WireVarint" pre, post = "b.EncodeZigzag32(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_SINT64: wire = "WireVarint" pre, post = "b.EncodeZigzag64(uint64(", "))" default: g.Fail("unhandled oneof field type ", field.Type.String()) } fieldWire[field] = wire g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")") if !canFail { g.P(pre, val, post) } else { g.P("if err := ", pre, val, post, "; err != nil {") g.P("return err") g.P("}") } if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)") } } g.P("case nil:") g.P("default: return ", g.Pkg["fmt"], `.Errorf("`, ccTypeName, ".", fname, ` has unexpected type %T", x)`) g.P("}") } g.P("return nil") g.P("}") g.P() // unmarshaler g.P("func ", dec, decSig, " {") g.P("m := msg.(*", ccTypeName, ")") g.P("switch tag {") for _, field := range message.Field { if field.OneofIndex == nil { continue } odp := message.OneofDecl[int(*field.OneofIndex)] g.P("case ", field.Number, ": // ", odp.GetName(), ".", *field.Name) g.P("if wire != ", g.Pkg["proto"], ".", fieldWire[field], " {") g.P("return true, ", g.Pkg["proto"], ".ErrInternalBadWireType") g.P("}") lhs := "x, err" // overridden for TYPE_MESSAGE and TYPE_GROUP var dec, cast, cast2 string switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: dec, cast = "b.DecodeFixed64()", g.Pkg["math"]+".Float64frombits" case descriptor.FieldDescriptorProto_TYPE_FLOAT: dec, cast, cast2 = "b.DecodeFixed32()", "uint32", g.Pkg["math"]+".Float32frombits" case descriptor.FieldDescriptorProto_TYPE_INT64: dec, cast = "b.DecodeVarint()", "int64" case descriptor.FieldDescriptorProto_TYPE_UINT64: dec = "b.DecodeVarint()" case descriptor.FieldDescriptorProto_TYPE_INT32: dec, cast = "b.DecodeVarint()", "int32" case descriptor.FieldDescriptorProto_TYPE_FIXED64: dec = "b.DecodeFixed64()" case descriptor.FieldDescriptorProto_TYPE_FIXED32: dec, cast = "b.DecodeFixed32()", "uint32" case descriptor.FieldDescriptorProto_TYPE_BOOL: dec = "b.DecodeVarint()" // handled specially below case descriptor.FieldDescriptorProto_TYPE_STRING: dec = "b.DecodeStringBytes()" case descriptor.FieldDescriptorProto_TYPE_GROUP: g.P("msg := new(", fieldTypes[field][1:], ")") // drop star lhs = "err" dec = "b.DecodeGroup(msg)" // handled specially below case descriptor.FieldDescriptorProto_TYPE_MESSAGE: g.P("msg := new(", fieldTypes[field][1:], ")") // drop star lhs = "err" dec = "b.DecodeMessage(msg)" // handled specially below case descriptor.FieldDescriptorProto_TYPE_BYTES: dec = "b.DecodeRawBytes(true)" case descriptor.FieldDescriptorProto_TYPE_UINT32: dec, cast = "b.DecodeVarint()", "uint32" case descriptor.FieldDescriptorProto_TYPE_ENUM: dec, cast = "b.DecodeVarint()", fieldTypes[field] case descriptor.FieldDescriptorProto_TYPE_SFIXED32: dec, cast = "b.DecodeFixed32()", "int32" case descriptor.FieldDescriptorProto_TYPE_SFIXED64: dec, cast = "b.DecodeFixed64()", "int64" case descriptor.FieldDescriptorProto_TYPE_SINT32: dec, cast = "b.DecodeZigzag32()", "int32" case descriptor.FieldDescriptorProto_TYPE_SINT64: dec, cast = "b.DecodeZigzag64()", "int64" default: g.Fail("unhandled oneof field type ", field.Type.String()) } g.P(lhs, " := ", dec) val := "x" if cast != "" { val = cast + "(" + val + ")" } if cast2 != "" { val = cast2 + "(" + val + ")" } switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: val += " != 0" case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE: val = "msg" } g.P("m.", oneofFieldName[*field.OneofIndex], " = &", oneofTypeName[field], "{", val, "}") g.P("return true, err") } g.P("default: return false, nil") g.P("}") g.P("}") g.P() // sizer g.P("func ", size, sizeSig, " {") g.P("m := msg.(*", ccTypeName, ")") for oi, odp := range message.OneofDecl { g.P("// ", odp.GetName()) fname := oneofFieldName[int32(oi)] g.P("switch x := m.", fname, ".(type) {") for _, field := range message.Field { if field.OneofIndex == nil || int(*field.OneofIndex) != oi { continue } g.P("case *", oneofTypeName[field], ":") val := "x." + fieldNames[field] var wire, varint, fixed string switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: wire = "WireFixed64" fixed = "8" case descriptor.FieldDescriptorProto_TYPE_FLOAT: wire = "WireFixed32" fixed = "4" case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM: wire = "WireVarint" varint = val case descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: wire = "WireFixed64" fixed = "8" case descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: wire = "WireFixed32" fixed = "4" case descriptor.FieldDescriptorProto_TYPE_BOOL: wire = "WireVarint" fixed = "1" case descriptor.FieldDescriptorProto_TYPE_STRING: wire = "WireBytes" fixed = "len(" + val + ")" varint = fixed case descriptor.FieldDescriptorProto_TYPE_GROUP: wire = "WireStartGroup" fixed = g.Pkg["proto"] + ".Size(" + val + ")" case descriptor.FieldDescriptorProto_TYPE_MESSAGE: wire = "WireBytes" g.P("s := ", g.Pkg["proto"], ".Size(", val, ")") fixed = "s" varint = fixed case descriptor.FieldDescriptorProto_TYPE_BYTES: wire = "WireBytes" fixed = "len(" + val + ")" varint = fixed case descriptor.FieldDescriptorProto_TYPE_SINT32: wire = "WireVarint" varint = "(uint32(" + val + ") << 1) ^ uint32((int32(" + val + ") >> 31))" case descriptor.FieldDescriptorProto_TYPE_SINT64: wire = "WireVarint" varint = "uint64(" + val + " << 1) ^ uint64((int64(" + val + ") >> 63))" default: g.Fail("unhandled oneof field type ", field.Type.String()) } g.P("n += ", g.Pkg["proto"], ".SizeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")") if varint != "" { g.P("n += ", g.Pkg["proto"], ".SizeVarint(uint64(", varint, "))") } if fixed != "" { g.P("n += ", fixed) } if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { g.P("n += ", g.Pkg["proto"], ".SizeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)") } } g.P("case nil:") g.P("default:") g.P("panic(", g.Pkg["fmt"], ".Sprintf(\"proto: unexpected type %T in oneof\", x))") g.P("}") } g.P("return n") g.P("}") g.P() } for _, ext := range message.ext { g.generateExtension(ext) } fullName := strings.Join(message.TypeName(), ".") if g.file.Package != nil { fullName = *g.file.Package + "." + fullName } g.addInitf("%s.RegisterType((*%s)(nil), %q)", g.Pkg["proto"], ccTypeName, fullName) } var escapeChars = [256]byte{ 'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', '\\': '\\', '"': '"', '\'': '\'', '?': '?', } // unescape reverses the "C" escaping that protoc does for default values of bytes fields. // It is best effort in that it effectively ignores malformed input. Seemingly invalid escape // sequences are conveyed, unmodified, into the decoded result. func unescape(s string) string { // NB: Sadly, we can't use strconv.Unquote because protoc will escape both // single and double quotes, but strconv.Unquote only allows one or the // other (based on actual surrounding quotes of its input argument). var out []byte for len(s) > 0 { // regular character, or too short to be valid escape if s[0] != '\\' || len(s) < 2 { out = append(out, s[0]) s = s[1:] } else if c := escapeChars[s[1]]; c != 0 { // escape sequence out = append(out, c) s = s[2:] } else if s[1] == 'x' || s[1] == 'X' { // hex escape, e.g. "\x80 if len(s) < 4 { // too short to be valid out = append(out, s[:2]...) s = s[2:] continue } v, err := strconv.ParseUint(s[2:4], 16, 8) if err != nil { out = append(out, s[:4]...) } else { out = append(out, byte(v)) } s = s[4:] } else if '0' <= s[1] && s[1] <= '7' { // octal escape, can vary from 1 to 3 octal digits; e.g., "\0" "\40" or "\164" // so consume up to 2 more bytes or up to end-of-string n := len(s[1:]) - len(strings.TrimLeft(s[1:], "01234567")) if n > 3 { n = 3 } v, err := strconv.ParseUint(s[1:1+n], 8, 8) if err != nil { out = append(out, s[:1+n]...) } else { out = append(out, byte(v)) } s = s[1+n:] } else { // bad escape, just propagate the slash as-is out = append(out, s[0]) s = s[1:] } } return string(out) } func (g *Generator) generateExtension(ext *ExtensionDescriptor) { ccTypeName := ext.DescName() extObj := g.ObjectNamed(*ext.Extendee) var extDesc *Descriptor if id, ok := extObj.(*ImportedDescriptor); ok { // This is extending a publicly imported message. // We need the underlying type for goTag. extDesc = id.o.(*Descriptor) } else { extDesc = extObj.(*Descriptor) } extendedType := "*" + g.TypeName(extObj) // always use the original field := ext.FieldDescriptorProto fieldType, wireType := g.GoType(ext.parent, field) tag := g.goTag(extDesc, field, wireType) g.RecordTypeUse(*ext.Extendee) if n := ext.FieldDescriptorProto.TypeName; n != nil { // foreign extension type g.RecordTypeUse(*n) } typeName := ext.TypeName() // Special case for proto2 message sets: If this extension is extending // proto2_bridge.MessageSet, and its final name component is "message_set_extension", // then drop that last component. mset := false if extendedType == "*proto2_bridge.MessageSet" && typeName[len(typeName)-1] == "message_set_extension" { typeName = typeName[:len(typeName)-1] mset = true } // For text formatting, the package must be exactly what the .proto file declares, // ignoring overrides such as the go_package option, and with no dot/underscore mapping. extName := strings.Join(typeName, ".") if g.file.Package != nil { extName = *g.file.Package + "." + extName } g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{") g.In() g.P("ExtendedType: (", extendedType, ")(nil),") g.P("ExtensionType: (", fieldType, ")(nil),") g.P("Field: ", field.Number, ",") g.P(`Name: "`, extName, `",`) g.P("Tag: ", tag, ",") g.P(`Filename: "`, g.file.GetName(), `",`) g.Out() g.P("}") g.P() if mset { // Generate a bit more code to register with message_set.go. g.addInitf("%s.RegisterMessageSetType((%s)(nil), %d, %q)", g.Pkg["proto"], fieldType, *field.Number, extName) } g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""}) } func (g *Generator) generateInitFunction() { for _, enum := range g.file.enum { g.generateEnumRegistration(enum) } for _, d := range g.file.desc { for _, ext := range d.ext { g.generateExtensionRegistration(ext) } } for _, ext := range g.file.ext { g.generateExtensionRegistration(ext) } if len(g.init) == 0 { return } g.P("func init() {") g.In() for _, l := range g.init { g.P(l) } g.Out() g.P("}") g.init = nil } func (g *Generator) generateFileDescriptor(file *FileDescriptor) { // Make a copy and trim source_code_info data. // TODO: Trim this more when we know exactly what we need. pb := proto.Clone(file.FileDescriptorProto).(*descriptor.FileDescriptorProto) pb.SourceCodeInfo = nil b, err := proto.Marshal(pb) if err != nil { g.Fail(err.Error()) } var buf bytes.Buffer w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression) w.Write(b) w.Close() b = buf.Bytes() v := file.VarName() g.P() g.P("func init() { ", g.Pkg["proto"], ".RegisterFile(", strconv.Quote(*file.Name), ", ", v, ") }") g.P("var ", v, " = []byte{") g.In() g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto") for len(b) > 0 { n := 16 if n > len(b) { n = len(b) } s := "" for _, c := range b[:n] { s += fmt.Sprintf("0x%02x,", c) } g.P(s) b = b[n:] } g.Out() g.P("}") } func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) { // // We always print the full (proto-world) package name here. pkg := enum.File().GetPackage() if pkg != "" { pkg += "." } // The full type name typeName := enum.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) g.addInitf("%s.RegisterEnum(%q, %[3]s_name, %[3]s_value)", g.Pkg["proto"], pkg+ccTypeName, ccTypeName) } func (g *Generator) generateExtensionRegistration(ext *ExtensionDescriptor) { g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName()) } // And now lots of helper functions. // Is c an ASCII lower-case letter? func isASCIILower(c byte) bool { return 'a' <= c && c <= 'z' } // Is c an ASCII digit? func isASCIIDigit(c byte) bool { return '0' <= c && c <= '9' } // CamelCase returns the CamelCased name. // If there is an interior underscore followed by a lower case letter, // drop the underscore and convert the letter to upper case. // There is a remote possibility of this rewrite causing a name collision, // but it's so remote we're prepared to pretend it's nonexistent - since the // C++ generator lowercases names, it's extremely unlikely to have two fields // with different capitalizations. // In short, _my_field_name_2 becomes XMyFieldName_2. func CamelCase(s string) string { if s == "" { return "" } t := make([]byte, 0, 32) i := 0 if s[0] == '_' { // Need a capital letter; drop the '_'. t = append(t, 'X') i++ } // Invariant: if the next letter is lower case, it must be converted // to upper case. // That is, we process a word at a time, where words are marked by _ or // upper case letter. Digits are treated as words. for ; i < len(s); i++ { c := s[i] if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) { continue // Skip the underscore in s. } if isASCIIDigit(c) { t = append(t, c) continue } // Assume we have a letter now - if not, it's a bogus identifier. // The next word is a sequence of characters that must start upper case. if isASCIILower(c) { c ^= ' ' // Make it a capital letter. } t = append(t, c) // Guaranteed not lower case. // Accept lower case sequence that follows. for i+1 < len(s) && isASCIILower(s[i+1]) { i++ t = append(t, s[i]) } } return string(t) } // CamelCaseSlice is like CamelCase, but the argument is a slice of strings to // be joined with "_". func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) } // dottedSlice turns a sliced name into a dotted name. func dottedSlice(elem []string) string { return strings.Join(elem, ".") } // Is this field optional? func isOptional(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL } // Is this field required? func isRequired(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED } // Is this field repeated? func isRepeated(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED } // Is this field a scalar numeric type? func isScalar(field *descriptor.FieldDescriptorProto) bool { if field.Type == nil { return false } switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE, descriptor.FieldDescriptorProto_TYPE_FLOAT, descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_BOOL, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM, descriptor.FieldDescriptorProto_TYPE_SFIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED64, descriptor.FieldDescriptorProto_TYPE_SINT32, descriptor.FieldDescriptorProto_TYPE_SINT64: return true default: return false } } // badToUnderscore is the mapping function used to generate Go names from package names, // which can be dotted in the input .proto file. It replaces non-identifier characters such as // dot or dash with underscore. func badToUnderscore(r rune) rune { if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { return r } return '_' } // baseName returns the last path element of the name, with the last dotted suffix removed. func baseName(name string) string { // First, find the last element if i := strings.LastIndex(name, "/"); i >= 0 { name = name[i+1:] } // Now drop the suffix if i := strings.LastIndex(name, "."); i >= 0 { name = name[0:i] } return name } // The SourceCodeInfo message describes the location of elements of a parsed // .proto file by way of a "path", which is a sequence of integers that // describe the route from a FileDescriptorProto to the relevant submessage. // The path alternates between a field number of a repeated field, and an index // into that repeated field. The constants below define the field numbers that // are used. // // See descriptor.proto for more information about this. const ( // tag numbers in FileDescriptorProto packagePath = 2 // package messagePath = 4 // message_type enumPath = 5 // enum_type // tag numbers in DescriptorProto messageFieldPath = 2 // field messageMessagePath = 3 // nested_type messageEnumPath = 4 // enum_type messageOneofPath = 8 // oneof_decl // tag numbers in EnumDescriptorProto enumValuePath = 2 // value ) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/generator/Makefile���������������������0000644�0610621�0607500�00000003435�13172163407�030507� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. include $(GOROOT)/src/Make.inc TARG=github.com/golang/protobuf/compiler/generator GOFILES=\ generator.go\ DEPS=../descriptor ../plugin ../../proto include $(GOROOT)/src/Make.pkg �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/doc.go���������������������������������0000644�0610621�0607500�00000004564�13172163407�026161� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* A plugin for the Google protocol buffer compiler to generate Go code. Run it by building this program and putting it in your path with the name protoc-gen-go That word 'go' at the end becomes part of the option string set for the protocol compiler, so once the protocol compiler (protoc) is installed you can run protoc --go_out=output_directory input_directory/file.proto to generate Go bindings for the protocol defined by file.proto. With that input, the output will be written to output_directory/file.pb.go The generated code is documented in the package comment for the library. See the README and documentation for protocol buffers to learn more: https://developers.google.com/protocol-buffers/ */ package documentation ��������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/descriptor/����������������������������0000755�0610621�0607500�00000000000�13172163407�027232� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto������������0000644�0610621�0607500�00000105035�13172163407�032501� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // The messages in this file describe the definitions found in .proto files. // A valid .proto file can be translated directly to a FileDescriptorProto // without any other information (e.g. without reading its imports). syntax = "proto2"; package google.protobuf; option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor"; option java_package = "com.google.protobuf"; option java_outer_classname = "DescriptorProtos"; option csharp_namespace = "Google.Protobuf.Reflection"; option objc_class_prefix = "GPB"; // descriptor.proto must be optimized for speed because reflection-based // algorithms don't work during bootstrapping. option optimize_for = SPEED; // The protocol compiler can output a FileDescriptorSet containing the .proto // files it parses. message FileDescriptorSet { repeated FileDescriptorProto file = 1; } // Describes a complete .proto file. message FileDescriptorProto { optional string name = 1; // file name, relative to root of source tree optional string package = 2; // e.g. "foo", "foo.bar", etc. // Names of files imported by this file. repeated string dependency = 3; // Indexes of the public imported files in the dependency list above. repeated int32 public_dependency = 10; // Indexes of the weak imported files in the dependency list. // For Google-internal migration only. Do not use. repeated int32 weak_dependency = 11; // All top-level definitions in this file. repeated DescriptorProto message_type = 4; repeated EnumDescriptorProto enum_type = 5; repeated ServiceDescriptorProto service = 6; repeated FieldDescriptorProto extension = 7; optional FileOptions options = 8; // This field contains optional information about the original source code. // You may safely remove this entire field without harming runtime // functionality of the descriptors -- the information is needed only by // development tools. optional SourceCodeInfo source_code_info = 9; // The syntax of the proto file. // The supported values are "proto2" and "proto3". optional string syntax = 12; } // Describes a message type. message DescriptorProto { optional string name = 1; repeated FieldDescriptorProto field = 2; repeated FieldDescriptorProto extension = 6; repeated DescriptorProto nested_type = 3; repeated EnumDescriptorProto enum_type = 4; message ExtensionRange { optional int32 start = 1; optional int32 end = 2; optional ExtensionRangeOptions options = 3; } repeated ExtensionRange extension_range = 5; repeated OneofDescriptorProto oneof_decl = 8; optional MessageOptions options = 7; // Range of reserved tag numbers. Reserved tag numbers may not be used by // fields or extension ranges in the same message. Reserved ranges may // not overlap. message ReservedRange { optional int32 start = 1; // Inclusive. optional int32 end = 2; // Exclusive. } repeated ReservedRange reserved_range = 9; // Reserved field names, which may not be used by fields in the same message. // A given name may only be reserved once. repeated string reserved_name = 10; } message ExtensionRangeOptions { // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } // Describes a field within a message. message FieldDescriptorProto { enum Type { // 0 is reserved for errors. // Order is weird for historical reasons. TYPE_DOUBLE = 1; TYPE_FLOAT = 2; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. TYPE_INT64 = 3; TYPE_UINT64 = 4; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. TYPE_INT32 = 5; TYPE_FIXED64 = 6; TYPE_FIXED32 = 7; TYPE_BOOL = 8; TYPE_STRING = 9; // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. TYPE_GROUP = 10; TYPE_MESSAGE = 11; // Length-delimited aggregate. // New in version 2. TYPE_BYTES = 12; TYPE_UINT32 = 13; TYPE_ENUM = 14; TYPE_SFIXED32 = 15; TYPE_SFIXED64 = 16; TYPE_SINT32 = 17; // Uses ZigZag encoding. TYPE_SINT64 = 18; // Uses ZigZag encoding. }; enum Label { // 0 is reserved for errors LABEL_OPTIONAL = 1; LABEL_REQUIRED = 2; LABEL_REPEATED = 3; }; optional string name = 1; optional int32 number = 3; optional Label label = 4; // If type_name is set, this need not be set. If both this and type_name // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. optional Type type = 5; // For message and enum types, this is the name of the type. If the name // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping // rules are used to find the type (i.e. first the nested types within this // message are searched, then within the parent, on up to the root // namespace). optional string type_name = 6; // For extensions, this is the name of the type being extended. It is // resolved in the same manner as type_name. optional string extendee = 2; // For numeric types, contains the original text representation of the value. // For booleans, "true" or "false". // For strings, contains the default text contents (not escaped in any way). // For bytes, contains the C escaped value. All bytes >= 128 are escaped. // TODO(kenton): Base-64 encode? optional string default_value = 7; // If set, gives the index of a oneof in the containing type's oneof_decl // list. This field is a member of that oneof. optional int32 oneof_index = 9; // JSON name of this field. The value is set by protocol compiler. If the // user has set a "json_name" option on this field, that option's value // will be used. Otherwise, it's deduced from the field's name by converting // it to camelCase. optional string json_name = 10; optional FieldOptions options = 8; } // Describes a oneof. message OneofDescriptorProto { optional string name = 1; optional OneofOptions options = 2; } // Describes an enum type. message EnumDescriptorProto { optional string name = 1; repeated EnumValueDescriptorProto value = 2; optional EnumOptions options = 3; } // Describes a value within an enum. message EnumValueDescriptorProto { optional string name = 1; optional int32 number = 2; optional EnumValueOptions options = 3; } // Describes a service. message ServiceDescriptorProto { optional string name = 1; repeated MethodDescriptorProto method = 2; optional ServiceOptions options = 3; } // Describes a method of a service. message MethodDescriptorProto { optional string name = 1; // Input and output type names. These are resolved in the same way as // FieldDescriptorProto.type_name, but must refer to a message type. optional string input_type = 2; optional string output_type = 3; optional MethodOptions options = 4; // Identifies if client streams multiple client messages optional bool client_streaming = 5 [default=false]; // Identifies if server streams multiple server messages optional bool server_streaming = 6 [default=false]; } // =================================================================== // Options // Each of the definitions above may have "options" attached. These are // just annotations which may cause code to be generated slightly differently // or may contain hints for code that manipulates protocol messages. // // Clients may define custom options as extensions of the *Options messages. // These extensions may not yet be known at parsing time, so the parser cannot // store the values in them. Instead it stores them in a field in the *Options // message called uninterpreted_option. This field must have the same name // across all *Options messages. We then use this field to populate the // extensions when we build a descriptor, at which point all protos have been // parsed and so all extensions are known. // // Extension numbers for custom options may be chosen as follows: // * For options which will only be used within a single application or // organization, or for experimental options, use field numbers 50000 // through 99999. It is up to you to ensure that you do not use the // same number for multiple options. // * For options which will be published and used publicly by multiple // independent entities, e-mail protobuf-global-extension-registry@google.com // to reserve extension numbers. Simply provide your project name (e.g. // Objective-C plugin) and your project website (if available) -- there's no // need to explain how you intend to use them. Usually you only need one // extension number. You can declare multiple options with only one extension // number by putting them in a sub-message. See the Custom Options section of // the docs for examples: // https://developers.google.com/protocol-buffers/docs/proto#options // If this turns out to be popular, a web service will be set up // to automatically assign option numbers. message FileOptions { // Sets the Java package where classes generated from this .proto will be // placed. By default, the proto package is used, but this is often // inappropriate because proto packages do not normally start with backwards // domain names. optional string java_package = 1; // If set, all the classes from the .proto file are wrapped in a single // outer class with the given name. This applies to both Proto1 // (equivalent to the old "--one_java_file" option) and Proto2 (where // a .proto always translates to a single class, but you may want to // explicitly choose the class name). optional string java_outer_classname = 8; // If set true, then the Java code generator will generate a separate .java // file for each top-level message, enum, and service defined in the .proto // file. Thus, these types will *not* be nested inside the outer class // named by java_outer_classname. However, the outer class will still be // generated to contain the file's getDescriptor() method as well as any // top-level extensions defined in the file. optional bool java_multiple_files = 10 [default=false]; // This option does nothing. optional bool java_generate_equals_and_hash = 20 [deprecated=true]; // If set true, then the Java2 code generator will generate code that // throws an exception whenever an attempt is made to assign a non-UTF-8 // byte sequence to a string field. // Message reflection will do the same. // However, an extension field still accepts non-UTF-8 byte sequences. // This option has no effect on when used with the lite runtime. optional bool java_string_check_utf8 = 27 [default=false]; // Generated classes can be optimized for speed or code size. enum OptimizeMode { SPEED = 1; // Generate complete code for parsing, serialization, // etc. CODE_SIZE = 2; // Use ReflectionOps to implement these methods. LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. } optional OptimizeMode optimize_for = 9 [default=SPEED]; // Sets the Go package where structs generated from this .proto will be // placed. If omitted, the Go package will be derived from the following: // - The basename of the package import path, if provided. // - Otherwise, the package statement in the .proto file, if present. // - Otherwise, the basename of the .proto file, without extension. optional string go_package = 11; // Should generic services be generated in each language? "Generic" services // are not specific to any particular RPC system. They are generated by the // main code generators in each language (without additional plugins). // Generic services were the only kind of service generation supported by // early versions of google.protobuf. // // Generic services are now considered deprecated in favor of using plugins // that generate code specific to your particular RPC system. Therefore, // these default to false. Old code which depends on generic services should // explicitly set them to true. optional bool cc_generic_services = 16 [default=false]; optional bool java_generic_services = 17 [default=false]; optional bool py_generic_services = 18 [default=false]; optional bool php_generic_services = 42 [default=false]; // Is this file deprecated? // Depending on the target platform, this can emit Deprecated annotations // for everything in the file, or it will be completely ignored; in the very // least, this is a formalization for deprecating files. optional bool deprecated = 23 [default=false]; // Enables the use of arenas for the proto messages in this file. This applies // only to generated classes for C++. optional bool cc_enable_arenas = 31 [default=false]; // Sets the objective c class prefix which is prepended to all objective c // generated classes from this .proto. There is no default. optional string objc_class_prefix = 36; // Namespace for generated classes; defaults to the package. optional string csharp_namespace = 37; // By default Swift generators will take the proto package and CamelCase it // replacing '.' with underscore and use that to prefix the types/symbols // defined. When this options is provided, they will use this value instead // to prefix the types/symbols defined. optional string swift_prefix = 39; // Sets the php class prefix which is prepended to all php generated classes // from this .proto. Default is empty. optional string php_class_prefix = 40; // Use this option to change the namespace of php generated classes. Default // is empty. When this option is empty, the package name will be used for // determining the namespace. optional string php_namespace = 41; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; reserved 38; } message MessageOptions { // Set true to use the old proto1 MessageSet wire format for extensions. // This is provided for backwards-compatibility with the MessageSet wire // format. You should not use this for any other reason: It's less // efficient, has fewer features, and is more complicated. // // The message must be defined exactly as follows: // message Foo { // option message_set_wire_format = true; // extensions 4 to max; // } // Note that the message cannot have any defined fields; MessageSets only // have extensions. // // All extensions of your type must be singular messages; e.g. they cannot // be int32s, enums, or repeated messages. // // Because this is an option, the above two restrictions are not enforced by // the protocol compiler. optional bool message_set_wire_format = 1 [default=false]; // Disables the generation of the standard "descriptor()" accessor, which can // conflict with a field of the same name. This is meant to make migration // from proto1 easier; new code should avoid fields named "descriptor". optional bool no_standard_descriptor_accessor = 2 [default=false]; // Is this message deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the message, or it will be completely ignored; in the very least, // this is a formalization for deprecating messages. optional bool deprecated = 3 [default=false]; // Whether the message is an automatically generated map entry type for the // maps field. // // For maps fields: // map<KeyType, ValueType> map_field = 1; // The parsed descriptor looks like: // message MapFieldEntry { // option map_entry = true; // optional KeyType key = 1; // optional ValueType value = 2; // } // repeated MapFieldEntry map_field = 1; // // Implementations may choose not to generate the map_entry=true message, but // use a native map in the target language to hold the keys and values. // The reflection APIs in such implementions still need to work as // if the field is a repeated message field. // // NOTE: Do not set the option in .proto files. Always use the maps syntax // instead. The option should only be implicitly set by the proto compiler // parser. optional bool map_entry = 7; reserved 8; // javalite_serializable reserved 9; // javanano_as_lite // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message FieldOptions { // The ctype option instructs the C++ code generator to use a different // representation of the field than it normally would. See the specific // options below. This option is not yet implemented in the open source // release -- sorry, we'll try to include it in a future version! optional CType ctype = 1 [default = STRING]; enum CType { // Default mode. STRING = 0; CORD = 1; STRING_PIECE = 2; } // The packed option can be enabled for repeated primitive fields to enable // a more efficient representation on the wire. Rather than repeatedly // writing the tag and type for each element, the entire array is encoded as // a single length-delimited blob. In proto3, only explicit setting it to // false will avoid using packed encoding. optional bool packed = 2; // The jstype option determines the JavaScript type used for values of the // field. The option is permitted only for 64 bit integral and fixed types // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING // is represented as JavaScript string, which avoids loss of precision that // can happen when a large value is converted to a floating point JavaScript. // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to // use the JavaScript "number" type. The behavior of the default option // JS_NORMAL is implementation dependent. // // This option is an enum to permit additional types to be added, e.g. // goog.math.Integer. optional JSType jstype = 6 [default = JS_NORMAL]; enum JSType { // Use the default type. JS_NORMAL = 0; // Use JavaScript strings. JS_STRING = 1; // Use JavaScript numbers. JS_NUMBER = 2; } // Should this field be parsed lazily? Lazy applies only to message-type // fields. It means that when the outer message is initially parsed, the // inner message's contents will not be parsed but instead stored in encoded // form. The inner message will actually be parsed when it is first accessed. // // This is only a hint. Implementations are free to choose whether to use // eager or lazy parsing regardless of the value of this option. However, // setting this option true suggests that the protocol author believes that // using lazy parsing on this field is worth the additional bookkeeping // overhead typically needed to implement it. // // This option does not affect the public interface of any generated code; // all method signatures remain the same. Furthermore, thread-safety of the // interface is not affected by this option; const methods remain safe to // call from multiple threads concurrently, while non-const methods continue // to require exclusive access. // // // Note that implementations may choose not to check required fields within // a lazy sub-message. That is, calling IsInitialized() on the outer message // may return true even if the inner message has missing required fields. // This is necessary because otherwise the inner message would have to be // parsed in order to perform the check, defeating the purpose of lazy // parsing. An implementation which chooses not to check required fields // must be consistent about it. That is, for any particular sub-message, the // implementation must either *always* check its required fields, or *never* // check its required fields, regardless of whether or not the message has // been parsed. optional bool lazy = 5 [default=false]; // Is this field deprecated? // Depending on the target platform, this can emit Deprecated annotations // for accessors, or it will be completely ignored; in the very least, this // is a formalization for deprecating fields. optional bool deprecated = 3 [default=false]; // For Google-internal migration only. Do not use. optional bool weak = 10 [default=false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; reserved 4; // removed jtype } message OneofOptions { // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message EnumOptions { // Set this option to true to allow mapping different tag names to the same // value. optional bool allow_alias = 2; // Is this enum deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum, or it will be completely ignored; in the very least, this // is a formalization for deprecating enums. optional bool deprecated = 3 [default=false]; reserved 5; // javanano_as_lite // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message EnumValueOptions { // Is this enum value deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum value, or it will be completely ignored; in the very least, // this is a formalization for deprecating enum values. optional bool deprecated = 1 [default=false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message ServiceOptions { // Note: Field numbers 1 through 32 are reserved for Google's internal RPC // framework. We apologize for hoarding these numbers to ourselves, but // we were already using them long before we decided to release Protocol // Buffers. // Is this service deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the service, or it will be completely ignored; in the very least, // this is a formalization for deprecating services. optional bool deprecated = 33 [default=false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message MethodOptions { // Note: Field numbers 1 through 32 are reserved for Google's internal RPC // framework. We apologize for hoarding these numbers to ourselves, but // we were already using them long before we decided to release Protocol // Buffers. // Is this method deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the method, or it will be completely ignored; in the very least, // this is a formalization for deprecating methods. optional bool deprecated = 33 [default=false]; // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, // or neither? HTTP based RPC implementation may choose GET verb for safe // methods, and PUT verb for idempotent methods instead of the default POST. enum IdempotencyLevel { IDEMPOTENCY_UNKNOWN = 0; NO_SIDE_EFFECTS = 1; // implies idempotent IDEMPOTENT = 2; // idempotent, but may have side effects } optional IdempotencyLevel idempotency_level = 34 [default=IDEMPOTENCY_UNKNOWN]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } // A message representing a option the parser does not recognize. This only // appears in options protos created by the compiler::Parser class. // DescriptorPool resolves these when building Descriptor objects. Therefore, // options protos in descriptor objects (e.g. returned by Descriptor::options(), // or produced by Descriptor::CopyTo()) will never have UninterpretedOptions // in them. message UninterpretedOption { // The name of the uninterpreted option. Each string represents a segment in // a dot-separated name. is_extension is true iff a segment represents an // extension (denoted with parentheses in options specs in .proto files). // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents // "foo.(bar.baz).qux". message NamePart { required string name_part = 1; required bool is_extension = 2; } repeated NamePart name = 2; // The value of the uninterpreted option, in whatever type the tokenizer // identified it as during parsing. Exactly one of these should be set. optional string identifier_value = 3; optional uint64 positive_int_value = 4; optional int64 negative_int_value = 5; optional double double_value = 6; optional bytes string_value = 7; optional string aggregate_value = 8; } // =================================================================== // Optional source code info // Encapsulates information about the original source file from which a // FileDescriptorProto was generated. message SourceCodeInfo { // A Location identifies a piece of source code in a .proto file which // corresponds to a particular definition. This information is intended // to be useful to IDEs, code indexers, documentation generators, and similar // tools. // // For example, say we have a file like: // message Foo { // optional string foo = 1; // } // Let's look at just the field definition: // optional string foo = 1; // ^ ^^ ^^ ^ ^^^ // a bc de f ghi // We have the following locations: // span path represents // [a,i) [ 4, 0, 2, 0 ] The whole field definition. // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). // // Notes: // - A location may refer to a repeated field itself (i.e. not to any // particular index within it). This is used whenever a set of elements are // logically enclosed in a single code segment. For example, an entire // extend block (possibly containing multiple extension definitions) will // have an outer location whose path refers to the "extensions" repeated // field without an index. // - Multiple locations may have the same path. This happens when a single // logical declaration is spread out across multiple places. The most // obvious example is the "extend" block again -- there may be multiple // extend blocks in the same scope, each of which will have the same path. // - A location's span is not always a subset of its parent's span. For // example, the "extendee" of an extension declaration appears at the // beginning of the "extend" block and is shared by all extensions within // the block. // - Just because a location's span is a subset of some other location's span // does not mean that it is a descendent. For example, a "group" defines // both a type and a field in a single declaration. Thus, the locations // corresponding to the type and field and their components will overlap. // - Code which tries to interpret locations should probably be designed to // ignore those that it doesn't understand, as more types of locations could // be recorded in the future. repeated Location location = 1; message Location { // Identifies which part of the FileDescriptorProto was defined at this // location. // // Each element is a field number or an index. They form a path from // the root FileDescriptorProto to the place where the definition. For // example, this path: // [ 4, 3, 2, 7, 1 ] // refers to: // file.message_type(3) // 4, 3 // .field(7) // 2, 7 // .name() // 1 // This is because FileDescriptorProto.message_type has field number 4: // repeated DescriptorProto message_type = 4; // and DescriptorProto.field has field number 2: // repeated FieldDescriptorProto field = 2; // and FieldDescriptorProto.name has field number 1: // optional string name = 1; // // Thus, the above path gives the location of a field name. If we removed // the last element: // [ 4, 3, 2, 7 ] // this path refers to the whole field declaration (from the beginning // of the label to the terminating semicolon). repeated int32 path = 1 [packed=true]; // Always has exactly three or four elements: start line, start column, // end line (optional, otherwise assumed same as start line), end column. // These are packed into a single field for efficiency. Note that line // and column numbers are zero-based -- typically you will want to add // 1 to each before displaying to a user. repeated int32 span = 2 [packed=true]; // If this SourceCodeInfo represents a complete declaration, these are any // comments appearing before and after the declaration which appear to be // attached to the declaration. // // A series of line comments appearing on consecutive lines, with no other // tokens appearing on those lines, will be treated as a single comment. // // leading_detached_comments will keep paragraphs of comments that appear // before (but not connected to) the current element. Each paragraph, // separated by empty lines, will be one comment element in the repeated // field. // // Only the comment content is provided; comment markers (e.g. //) are // stripped out. For block comments, leading whitespace and an asterisk // will be stripped from the beginning of each line other than the first. // Newlines are included in the output. // // Examples: // // optional int32 foo = 1; // Comment attached to foo. // // Comment attached to bar. // optional int32 bar = 2; // // optional string baz = 3; // // Comment attached to baz. // // Another line attached to baz. // // // Comment attached to qux. // // // // Another line attached to qux. // optional double qux = 4; // // // Detached comment for corge. This is not leading or trailing comments // // to qux or corge because there are blank lines separating it from // // both. // // // Detached comment for corge paragraph 2. // // optional string corge = 5; // /* Block comment attached // * to corge. Leading asterisks // * will be removed. */ // /* Block comment attached to // * grault. */ // optional int32 grault = 6; // // // ignored detached comments. optional string leading_comments = 3; optional string trailing_comments = 4; repeated string leading_detached_comments = 6; } } // Describes the relationship between generated code and its original source // file. A GeneratedCodeInfo message is associated with only one generated // source file, but may contain references to different source .proto files. message GeneratedCodeInfo { // An Annotation connects some span of text in generated code to an element // of its generating .proto file. repeated Annotation annotation = 1; message Annotation { // Identifies the element in the original source .proto file. This field // is formatted the same as SourceCodeInfo.Location.path. repeated int32 path = 1 [packed=true]; // Identifies the filesystem path to the original source .proto. optional string source_file = 2; // Identifies the starting offset in bytes in the generated code // that relates to the identified object. optional int32 begin = 3; // Identifies the ending offset in bytes in the generated code that // relates to the identified offset. The end offset should be one past // the last relevant byte (so the length of the text = end - begin). optional int32 end = 4; } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go������������0000644�0610621�0607500�00000266433�13172163407�032355� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/descriptor.proto /* Package descriptor is a generated protocol buffer package. It is generated from these files: google/protobuf/descriptor.proto It has these top-level messages: FileDescriptorSet FileDescriptorProto DescriptorProto ExtensionRangeOptions FieldDescriptorProto OneofDescriptorProto EnumDescriptorProto EnumValueDescriptorProto ServiceDescriptorProto MethodDescriptorProto FileOptions MessageOptions FieldOptions OneofOptions EnumOptions EnumValueOptions ServiceOptions MethodOptions UninterpretedOption SourceCodeInfo GeneratedCodeInfo */ package descriptor import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type FieldDescriptorProto_Type int32 const ( // 0 is reserved for errors. // Order is weird for historical reasons. FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 // New in version 2. FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 ) var FieldDescriptorProto_Type_name = map[int32]string{ 1: "TYPE_DOUBLE", 2: "TYPE_FLOAT", 3: "TYPE_INT64", 4: "TYPE_UINT64", 5: "TYPE_INT32", 6: "TYPE_FIXED64", 7: "TYPE_FIXED32", 8: "TYPE_BOOL", 9: "TYPE_STRING", 10: "TYPE_GROUP", 11: "TYPE_MESSAGE", 12: "TYPE_BYTES", 13: "TYPE_UINT32", 14: "TYPE_ENUM", 15: "TYPE_SFIXED32", 16: "TYPE_SFIXED64", 17: "TYPE_SINT32", 18: "TYPE_SINT64", } var FieldDescriptorProto_Type_value = map[string]int32{ "TYPE_DOUBLE": 1, "TYPE_FLOAT": 2, "TYPE_INT64": 3, "TYPE_UINT64": 4, "TYPE_INT32": 5, "TYPE_FIXED64": 6, "TYPE_FIXED32": 7, "TYPE_BOOL": 8, "TYPE_STRING": 9, "TYPE_GROUP": 10, "TYPE_MESSAGE": 11, "TYPE_BYTES": 12, "TYPE_UINT32": 13, "TYPE_ENUM": 14, "TYPE_SFIXED32": 15, "TYPE_SFIXED64": 16, "TYPE_SINT32": 17, "TYPE_SINT64": 18, } func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { p := new(FieldDescriptorProto_Type) *p = x return p } func (x FieldDescriptorProto_Type) String() string { return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) } func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") if err != nil { return err } *x = FieldDescriptorProto_Type(value) return nil } func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{4, 0} } type FieldDescriptorProto_Label int32 const ( // 0 is reserved for errors FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 ) var FieldDescriptorProto_Label_name = map[int32]string{ 1: "LABEL_OPTIONAL", 2: "LABEL_REQUIRED", 3: "LABEL_REPEATED", } var FieldDescriptorProto_Label_value = map[string]int32{ "LABEL_OPTIONAL": 1, "LABEL_REQUIRED": 2, "LABEL_REPEATED": 3, } func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { p := new(FieldDescriptorProto_Label) *p = x return p } func (x FieldDescriptorProto_Label) String() string { return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) } func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") if err != nil { return err } *x = FieldDescriptorProto_Label(value) return nil } func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{4, 1} } // Generated classes can be optimized for speed or code size. type FileOptions_OptimizeMode int32 const ( FileOptions_SPEED FileOptions_OptimizeMode = 1 // etc. FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 ) var FileOptions_OptimizeMode_name = map[int32]string{ 1: "SPEED", 2: "CODE_SIZE", 3: "LITE_RUNTIME", } var FileOptions_OptimizeMode_value = map[string]int32{ "SPEED": 1, "CODE_SIZE": 2, "LITE_RUNTIME": 3, } func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { p := new(FileOptions_OptimizeMode) *p = x return p } func (x FileOptions_OptimizeMode) String() string { return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) } func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") if err != nil { return err } *x = FileOptions_OptimizeMode(value) return nil } func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{10, 0} } type FieldOptions_CType int32 const ( // Default mode. FieldOptions_STRING FieldOptions_CType = 0 FieldOptions_CORD FieldOptions_CType = 1 FieldOptions_STRING_PIECE FieldOptions_CType = 2 ) var FieldOptions_CType_name = map[int32]string{ 0: "STRING", 1: "CORD", 2: "STRING_PIECE", } var FieldOptions_CType_value = map[string]int32{ "STRING": 0, "CORD": 1, "STRING_PIECE": 2, } func (x FieldOptions_CType) Enum() *FieldOptions_CType { p := new(FieldOptions_CType) *p = x return p } func (x FieldOptions_CType) String() string { return proto.EnumName(FieldOptions_CType_name, int32(x)) } func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") if err != nil { return err } *x = FieldOptions_CType(value) return nil } func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{12, 0} } type FieldOptions_JSType int32 const ( // Use the default type. FieldOptions_JS_NORMAL FieldOptions_JSType = 0 // Use JavaScript strings. FieldOptions_JS_STRING FieldOptions_JSType = 1 // Use JavaScript numbers. FieldOptions_JS_NUMBER FieldOptions_JSType = 2 ) var FieldOptions_JSType_name = map[int32]string{ 0: "JS_NORMAL", 1: "JS_STRING", 2: "JS_NUMBER", } var FieldOptions_JSType_value = map[string]int32{ "JS_NORMAL": 0, "JS_STRING": 1, "JS_NUMBER": 2, } func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { p := new(FieldOptions_JSType) *p = x return p } func (x FieldOptions_JSType) String() string { return proto.EnumName(FieldOptions_JSType_name, int32(x)) } func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType") if err != nil { return err } *x = FieldOptions_JSType(value) return nil } func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{12, 1} } // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, // or neither? HTTP based RPC implementation may choose GET verb for safe // methods, and PUT verb for idempotent methods instead of the default POST. type MethodOptions_IdempotencyLevel int32 const ( MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 ) var MethodOptions_IdempotencyLevel_name = map[int32]string{ 0: "IDEMPOTENCY_UNKNOWN", 1: "NO_SIDE_EFFECTS", 2: "IDEMPOTENT", } var MethodOptions_IdempotencyLevel_value = map[string]int32{ "IDEMPOTENCY_UNKNOWN": 0, "NO_SIDE_EFFECTS": 1, "IDEMPOTENT": 2, } func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { p := new(MethodOptions_IdempotencyLevel) *p = x return p } func (x MethodOptions_IdempotencyLevel) String() string { return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x)) } func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel") if err != nil { return err } *x = MethodOptions_IdempotencyLevel(value) return nil } func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{17, 0} } // The protocol compiler can output a FileDescriptorSet containing the .proto // files it parses. type FileDescriptorSet struct { File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } func (*FileDescriptorSet) ProtoMessage() {} func (*FileDescriptorSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { if m != nil { return m.File } return nil } // Describes a complete .proto file. type FileDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` // Names of files imported by this file. Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` // Indexes of the public imported files in the dependency list above. PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` // Indexes of the weak imported files in the dependency list. // For Google-internal migration only. Do not use. WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` // All top-level definitions in this file. MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` // This field contains optional information about the original source code. // You may safely remove this entire field without harming runtime // functionality of the descriptors -- the information is needed only by // development tools. SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` // The syntax of the proto file. // The supported values are "proto2" and "proto3". Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } func (*FileDescriptorProto) ProtoMessage() {} func (*FileDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *FileDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *FileDescriptorProto) GetPackage() string { if m != nil && m.Package != nil { return *m.Package } return "" } func (m *FileDescriptorProto) GetDependency() []string { if m != nil { return m.Dependency } return nil } func (m *FileDescriptorProto) GetPublicDependency() []int32 { if m != nil { return m.PublicDependency } return nil } func (m *FileDescriptorProto) GetWeakDependency() []int32 { if m != nil { return m.WeakDependency } return nil } func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { if m != nil { return m.MessageType } return nil } func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { if m != nil { return m.EnumType } return nil } func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { if m != nil { return m.Service } return nil } func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { if m != nil { return m.Extension } return nil } func (m *FileDescriptorProto) GetOptions() *FileOptions { if m != nil { return m.Options } return nil } func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { if m != nil { return m.SourceCodeInfo } return nil } func (m *FileDescriptorProto) GetSyntax() string { if m != nil && m.Syntax != nil { return *m.Syntax } return "" } // Describes a message type. type DescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` // Reserved field names, which may not be used by fields in the same message. // A given name may only be reserved once. ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } func (*DescriptorProto) ProtoMessage() {} func (*DescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *DescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *DescriptorProto) GetField() []*FieldDescriptorProto { if m != nil { return m.Field } return nil } func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { if m != nil { return m.Extension } return nil } func (m *DescriptorProto) GetNestedType() []*DescriptorProto { if m != nil { return m.NestedType } return nil } func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { if m != nil { return m.EnumType } return nil } func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { if m != nil { return m.ExtensionRange } return nil } func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { if m != nil { return m.OneofDecl } return nil } func (m *DescriptorProto) GetOptions() *MessageOptions { if m != nil { return m.Options } return nil } func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { if m != nil { return m.ReservedRange } return nil } func (m *DescriptorProto) GetReservedName() []string { if m != nil { return m.ReservedName } return nil } type DescriptorProto_ExtensionRange struct { Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } func (*DescriptorProto_ExtensionRange) ProtoMessage() {} func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } func (m *DescriptorProto_ExtensionRange) GetStart() int32 { if m != nil && m.Start != nil { return *m.Start } return 0 } func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { if m != nil && m.End != nil { return *m.End } return 0 } func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { if m != nil { return m.Options } return nil } // Range of reserved tag numbers. Reserved tag numbers may not be used by // fields or extension ranges in the same message. Reserved ranges may // not overlap. type DescriptorProto_ReservedRange struct { Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } func (*DescriptorProto_ReservedRange) ProtoMessage() {} func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 1} } func (m *DescriptorProto_ReservedRange) GetStart() int32 { if m != nil && m.Start != nil { return *m.Start } return 0 } func (m *DescriptorProto_ReservedRange) GetEnd() int32 { if m != nil && m.End != nil { return *m.End } return 0 } type ExtensionRangeOptions struct { // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } func (*ExtensionRangeOptions) ProtoMessage() {} func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ExtensionRangeOptions } func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } // Describes a field within a message. type FieldDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` // If type_name is set, this need not be set. If both this and type_name // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` // For message and enum types, this is the name of the type. If the name // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping // rules are used to find the type (i.e. first the nested types within this // message are searched, then within the parent, on up to the root // namespace). TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` // For extensions, this is the name of the type being extended. It is // resolved in the same manner as type_name. Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` // For numeric types, contains the original text representation of the value. // For booleans, "true" or "false". // For strings, contains the default text contents (not escaped in any way). // For bytes, contains the C escaped value. All bytes >= 128 are escaped. // TODO(kenton): Base-64 encode? DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` // If set, gives the index of a oneof in the containing type's oneof_decl // list. This field is a member of that oneof. OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` // JSON name of this field. The value is set by protocol compiler. If the // user has set a "json_name" option on this field, that option's value // will be used. Otherwise, it's deduced from the field's name by converting // it to camelCase. JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } func (*FieldDescriptorProto) ProtoMessage() {} func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *FieldDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *FieldDescriptorProto) GetNumber() int32 { if m != nil && m.Number != nil { return *m.Number } return 0 } func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { if m != nil && m.Label != nil { return *m.Label } return FieldDescriptorProto_LABEL_OPTIONAL } func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { if m != nil && m.Type != nil { return *m.Type } return FieldDescriptorProto_TYPE_DOUBLE } func (m *FieldDescriptorProto) GetTypeName() string { if m != nil && m.TypeName != nil { return *m.TypeName } return "" } func (m *FieldDescriptorProto) GetExtendee() string { if m != nil && m.Extendee != nil { return *m.Extendee } return "" } func (m *FieldDescriptorProto) GetDefaultValue() string { if m != nil && m.DefaultValue != nil { return *m.DefaultValue } return "" } func (m *FieldDescriptorProto) GetOneofIndex() int32 { if m != nil && m.OneofIndex != nil { return *m.OneofIndex } return 0 } func (m *FieldDescriptorProto) GetJsonName() string { if m != nil && m.JsonName != nil { return *m.JsonName } return "" } func (m *FieldDescriptorProto) GetOptions() *FieldOptions { if m != nil { return m.Options } return nil } // Describes a oneof. type OneofDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } func (*OneofDescriptorProto) ProtoMessage() {} func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (m *OneofDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *OneofDescriptorProto) GetOptions() *OneofOptions { if m != nil { return m.Options } return nil } // Describes an enum type. type EnumDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } func (*EnumDescriptorProto) ProtoMessage() {} func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (m *EnumDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { if m != nil { return m.Value } return nil } func (m *EnumDescriptorProto) GetOptions() *EnumOptions { if m != nil { return m.Options } return nil } // Describes a value within an enum. type EnumValueDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } func (*EnumValueDescriptorProto) ProtoMessage() {} func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (m *EnumValueDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *EnumValueDescriptorProto) GetNumber() int32 { if m != nil && m.Number != nil { return *m.Number } return 0 } func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { if m != nil { return m.Options } return nil } // Describes a service. type ServiceDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } func (*ServiceDescriptorProto) ProtoMessage() {} func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } func (m *ServiceDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { if m != nil { return m.Method } return nil } func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { if m != nil { return m.Options } return nil } // Describes a method of a service. type MethodDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` // Input and output type names. These are resolved in the same way as // FieldDescriptorProto.type_name, but must refer to a message type. InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` // Identifies if client streams multiple client messages ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` // Identifies if server streams multiple server messages ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } func (*MethodDescriptorProto) ProtoMessage() {} func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } const Default_MethodDescriptorProto_ClientStreaming bool = false const Default_MethodDescriptorProto_ServerStreaming bool = false func (m *MethodDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *MethodDescriptorProto) GetInputType() string { if m != nil && m.InputType != nil { return *m.InputType } return "" } func (m *MethodDescriptorProto) GetOutputType() string { if m != nil && m.OutputType != nil { return *m.OutputType } return "" } func (m *MethodDescriptorProto) GetOptions() *MethodOptions { if m != nil { return m.Options } return nil } func (m *MethodDescriptorProto) GetClientStreaming() bool { if m != nil && m.ClientStreaming != nil { return *m.ClientStreaming } return Default_MethodDescriptorProto_ClientStreaming } func (m *MethodDescriptorProto) GetServerStreaming() bool { if m != nil && m.ServerStreaming != nil { return *m.ServerStreaming } return Default_MethodDescriptorProto_ServerStreaming } type FileOptions struct { // Sets the Java package where classes generated from this .proto will be // placed. By default, the proto package is used, but this is often // inappropriate because proto packages do not normally start with backwards // domain names. JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` // If set, all the classes from the .proto file are wrapped in a single // outer class with the given name. This applies to both Proto1 // (equivalent to the old "--one_java_file" option) and Proto2 (where // a .proto always translates to a single class, but you may want to // explicitly choose the class name). JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` // If set true, then the Java code generator will generate a separate .java // file for each top-level message, enum, and service defined in the .proto // file. Thus, these types will *not* be nested inside the outer class // named by java_outer_classname. However, the outer class will still be // generated to contain the file's getDescriptor() method as well as any // top-level extensions defined in the file. JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` // This option does nothing. JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // If set true, then the Java2 code generator will generate code that // throws an exception whenever an attempt is made to assign a non-UTF-8 // byte sequence to a string field. // Message reflection will do the same. // However, an extension field still accepts non-UTF-8 byte sequences. // This option has no effect on when used with the lite runtime. JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` // Sets the Go package where structs generated from this .proto will be // placed. If omitted, the Go package will be derived from the following: // - The basename of the package import path, if provided. // - Otherwise, the package statement in the .proto file, if present. // - Otherwise, the basename of the .proto file, without extension. GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` // Should generic services be generated in each language? "Generic" services // are not specific to any particular RPC system. They are generated by the // main code generators in each language (without additional plugins). // Generic services were the only kind of service generation supported by // early versions of google.protobuf. // // Generic services are now considered deprecated in favor of using plugins // that generate code specific to your particular RPC system. Therefore, // these default to false. Old code which depends on generic services should // explicitly set them to true. CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` // Is this file deprecated? // Depending on the target platform, this can emit Deprecated annotations // for everything in the file, or it will be completely ignored; in the very // least, this is a formalization for deprecating files. Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // Enables the use of arenas for the proto messages in this file. This applies // only to generated classes for C++. CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"` // Sets the objective c class prefix which is prepended to all objective c // generated classes from this .proto. There is no default. ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` // Namespace for generated classes; defaults to the package. CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` // By default Swift generators will take the proto package and CamelCase it // replacing '.' with underscore and use that to prefix the types/symbols // defined. When this options is provided, they will use this value instead // to prefix the types/symbols defined. SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` // Sets the php class prefix which is prepended to all php generated classes // from this .proto. Default is empty. PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` // Use this option to change the namespace of php generated classes. Default // is empty. When this option is empty, the package name will be used for // determining the namespace. PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *FileOptions) Reset() { *m = FileOptions{} } func (m *FileOptions) String() string { return proto.CompactTextString(m) } func (*FileOptions) ProtoMessage() {} func (*FileOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } var extRange_FileOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_FileOptions } const Default_FileOptions_JavaMultipleFiles bool = false const Default_FileOptions_JavaStringCheckUtf8 bool = false const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED const Default_FileOptions_CcGenericServices bool = false const Default_FileOptions_JavaGenericServices bool = false const Default_FileOptions_PyGenericServices bool = false const Default_FileOptions_PhpGenericServices bool = false const Default_FileOptions_Deprecated bool = false const Default_FileOptions_CcEnableArenas bool = false func (m *FileOptions) GetJavaPackage() string { if m != nil && m.JavaPackage != nil { return *m.JavaPackage } return "" } func (m *FileOptions) GetJavaOuterClassname() string { if m != nil && m.JavaOuterClassname != nil { return *m.JavaOuterClassname } return "" } func (m *FileOptions) GetJavaMultipleFiles() bool { if m != nil && m.JavaMultipleFiles != nil { return *m.JavaMultipleFiles } return Default_FileOptions_JavaMultipleFiles } func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { if m != nil && m.JavaGenerateEqualsAndHash != nil { return *m.JavaGenerateEqualsAndHash } return false } func (m *FileOptions) GetJavaStringCheckUtf8() bool { if m != nil && m.JavaStringCheckUtf8 != nil { return *m.JavaStringCheckUtf8 } return Default_FileOptions_JavaStringCheckUtf8 } func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { if m != nil && m.OptimizeFor != nil { return *m.OptimizeFor } return Default_FileOptions_OptimizeFor } func (m *FileOptions) GetGoPackage() string { if m != nil && m.GoPackage != nil { return *m.GoPackage } return "" } func (m *FileOptions) GetCcGenericServices() bool { if m != nil && m.CcGenericServices != nil { return *m.CcGenericServices } return Default_FileOptions_CcGenericServices } func (m *FileOptions) GetJavaGenericServices() bool { if m != nil && m.JavaGenericServices != nil { return *m.JavaGenericServices } return Default_FileOptions_JavaGenericServices } func (m *FileOptions) GetPyGenericServices() bool { if m != nil && m.PyGenericServices != nil { return *m.PyGenericServices } return Default_FileOptions_PyGenericServices } func (m *FileOptions) GetPhpGenericServices() bool { if m != nil && m.PhpGenericServices != nil { return *m.PhpGenericServices } return Default_FileOptions_PhpGenericServices } func (m *FileOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_FileOptions_Deprecated } func (m *FileOptions) GetCcEnableArenas() bool { if m != nil && m.CcEnableArenas != nil { return *m.CcEnableArenas } return Default_FileOptions_CcEnableArenas } func (m *FileOptions) GetObjcClassPrefix() string { if m != nil && m.ObjcClassPrefix != nil { return *m.ObjcClassPrefix } return "" } func (m *FileOptions) GetCsharpNamespace() string { if m != nil && m.CsharpNamespace != nil { return *m.CsharpNamespace } return "" } func (m *FileOptions) GetSwiftPrefix() string { if m != nil && m.SwiftPrefix != nil { return *m.SwiftPrefix } return "" } func (m *FileOptions) GetPhpClassPrefix() string { if m != nil && m.PhpClassPrefix != nil { return *m.PhpClassPrefix } return "" } func (m *FileOptions) GetPhpNamespace() string { if m != nil && m.PhpNamespace != nil { return *m.PhpNamespace } return "" } func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type MessageOptions struct { // Set true to use the old proto1 MessageSet wire format for extensions. // This is provided for backwards-compatibility with the MessageSet wire // format. You should not use this for any other reason: It's less // efficient, has fewer features, and is more complicated. // // The message must be defined exactly as follows: // message Foo { // option message_set_wire_format = true; // extensions 4 to max; // } // Note that the message cannot have any defined fields; MessageSets only // have extensions. // // All extensions of your type must be singular messages; e.g. they cannot // be int32s, enums, or repeated messages. // // Because this is an option, the above two restrictions are not enforced by // the protocol compiler. MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` // Disables the generation of the standard "descriptor()" accessor, which can // conflict with a field of the same name. This is meant to make migration // from proto1 easier; new code should avoid fields named "descriptor". NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` // Is this message deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the message, or it will be completely ignored; in the very least, // this is a formalization for deprecating messages. Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // Whether the message is an automatically generated map entry type for the // maps field. // // For maps fields: // map<KeyType, ValueType> map_field = 1; // The parsed descriptor looks like: // message MapFieldEntry { // option map_entry = true; // optional KeyType key = 1; // optional ValueType value = 2; // } // repeated MapFieldEntry map_field = 1; // // Implementations may choose not to generate the map_entry=true message, but // use a native map in the target language to hold the keys and values. // The reflection APIs in such implementions still need to work as // if the field is a repeated message field. // // NOTE: Do not set the option in .proto files. Always use the maps syntax // instead. The option should only be implicitly set by the proto compiler // parser. MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *MessageOptions) Reset() { *m = MessageOptions{} } func (m *MessageOptions) String() string { return proto.CompactTextString(m) } func (*MessageOptions) ProtoMessage() {} func (*MessageOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } var extRange_MessageOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MessageOptions } const Default_MessageOptions_MessageSetWireFormat bool = false const Default_MessageOptions_NoStandardDescriptorAccessor bool = false const Default_MessageOptions_Deprecated bool = false func (m *MessageOptions) GetMessageSetWireFormat() bool { if m != nil && m.MessageSetWireFormat != nil { return *m.MessageSetWireFormat } return Default_MessageOptions_MessageSetWireFormat } func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { if m != nil && m.NoStandardDescriptorAccessor != nil { return *m.NoStandardDescriptorAccessor } return Default_MessageOptions_NoStandardDescriptorAccessor } func (m *MessageOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_MessageOptions_Deprecated } func (m *MessageOptions) GetMapEntry() bool { if m != nil && m.MapEntry != nil { return *m.MapEntry } return false } func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type FieldOptions struct { // The ctype option instructs the C++ code generator to use a different // representation of the field than it normally would. See the specific // options below. This option is not yet implemented in the open source // release -- sorry, we'll try to include it in a future version! Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` // The packed option can be enabled for repeated primitive fields to enable // a more efficient representation on the wire. Rather than repeatedly // writing the tag and type for each element, the entire array is encoded as // a single length-delimited blob. In proto3, only explicit setting it to // false will avoid using packed encoding. Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` // The jstype option determines the JavaScript type used for values of the // field. The option is permitted only for 64 bit integral and fixed types // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING // is represented as JavaScript string, which avoids loss of precision that // can happen when a large value is converted to a floating point JavaScript. // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to // use the JavaScript "number" type. The behavior of the default option // JS_NORMAL is implementation dependent. // // This option is an enum to permit additional types to be added, e.g. // goog.math.Integer. Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` // Should this field be parsed lazily? Lazy applies only to message-type // fields. It means that when the outer message is initially parsed, the // inner message's contents will not be parsed but instead stored in encoded // form. The inner message will actually be parsed when it is first accessed. // // This is only a hint. Implementations are free to choose whether to use // eager or lazy parsing regardless of the value of this option. However, // setting this option true suggests that the protocol author believes that // using lazy parsing on this field is worth the additional bookkeeping // overhead typically needed to implement it. // // This option does not affect the public interface of any generated code; // all method signatures remain the same. Furthermore, thread-safety of the // interface is not affected by this option; const methods remain safe to // call from multiple threads concurrently, while non-const methods continue // to require exclusive access. // // // Note that implementations may choose not to check required fields within // a lazy sub-message. That is, calling IsInitialized() on the outer message // may return true even if the inner message has missing required fields. // This is necessary because otherwise the inner message would have to be // parsed in order to perform the check, defeating the purpose of lazy // parsing. An implementation which chooses not to check required fields // must be consistent about it. That is, for any particular sub-message, the // implementation must either *always* check its required fields, or *never* // check its required fields, regardless of whether or not the message has // been parsed. Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` // Is this field deprecated? // Depending on the target platform, this can emit Deprecated annotations // for accessors, or it will be completely ignored; in the very least, this // is a formalization for deprecating fields. Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // For Google-internal migration only. Do not use. Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *FieldOptions) Reset() { *m = FieldOptions{} } func (m *FieldOptions) String() string { return proto.CompactTextString(m) } func (*FieldOptions) ProtoMessage() {} func (*FieldOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} } var extRange_FieldOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_FieldOptions } const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL const Default_FieldOptions_Lazy bool = false const Default_FieldOptions_Deprecated bool = false const Default_FieldOptions_Weak bool = false func (m *FieldOptions) GetCtype() FieldOptions_CType { if m != nil && m.Ctype != nil { return *m.Ctype } return Default_FieldOptions_Ctype } func (m *FieldOptions) GetPacked() bool { if m != nil && m.Packed != nil { return *m.Packed } return false } func (m *FieldOptions) GetJstype() FieldOptions_JSType { if m != nil && m.Jstype != nil { return *m.Jstype } return Default_FieldOptions_Jstype } func (m *FieldOptions) GetLazy() bool { if m != nil && m.Lazy != nil { return *m.Lazy } return Default_FieldOptions_Lazy } func (m *FieldOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_FieldOptions_Deprecated } func (m *FieldOptions) GetWeak() bool { if m != nil && m.Weak != nil { return *m.Weak } return Default_FieldOptions_Weak } func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type OneofOptions struct { // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OneofOptions) Reset() { *m = OneofOptions{} } func (m *OneofOptions) String() string { return proto.CompactTextString(m) } func (*OneofOptions) ProtoMessage() {} func (*OneofOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} } var extRange_OneofOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OneofOptions } func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type EnumOptions struct { // Set this option to true to allow mapping different tag names to the same // value. AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` // Is this enum deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum, or it will be completely ignored; in the very least, this // is a formalization for deprecating enums. Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *EnumOptions) Reset() { *m = EnumOptions{} } func (m *EnumOptions) String() string { return proto.CompactTextString(m) } func (*EnumOptions) ProtoMessage() {} func (*EnumOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} } var extRange_EnumOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_EnumOptions } const Default_EnumOptions_Deprecated bool = false func (m *EnumOptions) GetAllowAlias() bool { if m != nil && m.AllowAlias != nil { return *m.AllowAlias } return false } func (m *EnumOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_EnumOptions_Deprecated } func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type EnumValueOptions struct { // Is this enum value deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum value, or it will be completely ignored; in the very least, // this is a formalization for deprecating enum values. Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } func (*EnumValueOptions) ProtoMessage() {} func (*EnumValueOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} } var extRange_EnumValueOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_EnumValueOptions } const Default_EnumValueOptions_Deprecated bool = false func (m *EnumValueOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_EnumValueOptions_Deprecated } func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type ServiceOptions struct { // Is this service deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the service, or it will be completely ignored; in the very least, // this is a formalization for deprecating services. Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } func (*ServiceOptions) ProtoMessage() {} func (*ServiceOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} } var extRange_ServiceOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ServiceOptions } const Default_ServiceOptions_Deprecated bool = false func (m *ServiceOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_ServiceOptions_Deprecated } func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type MethodOptions struct { // Is this method deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the method, or it will be completely ignored; in the very least, // this is a formalization for deprecating methods. Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *MethodOptions) Reset() { *m = MethodOptions{} } func (m *MethodOptions) String() string { return proto.CompactTextString(m) } func (*MethodOptions) ProtoMessage() {} func (*MethodOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} } var extRange_MethodOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MethodOptions } const Default_MethodOptions_Deprecated bool = false const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN func (m *MethodOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_MethodOptions_Deprecated } func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { if m != nil && m.IdempotencyLevel != nil { return *m.IdempotencyLevel } return Default_MethodOptions_IdempotencyLevel } func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } // A message representing a option the parser does not recognize. This only // appears in options protos created by the compiler::Parser class. // DescriptorPool resolves these when building Descriptor objects. Therefore, // options protos in descriptor objects (e.g. returned by Descriptor::options(), // or produced by Descriptor::CopyTo()) will never have UninterpretedOptions // in them. type UninterpretedOption struct { Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` // The value of the uninterpreted option, in whatever type the tokenizer // identified it as during parsing. Exactly one of these should be set. IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } func (*UninterpretedOption) ProtoMessage() {} func (*UninterpretedOption) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} } func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { if m != nil { return m.Name } return nil } func (m *UninterpretedOption) GetIdentifierValue() string { if m != nil && m.IdentifierValue != nil { return *m.IdentifierValue } return "" } func (m *UninterpretedOption) GetPositiveIntValue() uint64 { if m != nil && m.PositiveIntValue != nil { return *m.PositiveIntValue } return 0 } func (m *UninterpretedOption) GetNegativeIntValue() int64 { if m != nil && m.NegativeIntValue != nil { return *m.NegativeIntValue } return 0 } func (m *UninterpretedOption) GetDoubleValue() float64 { if m != nil && m.DoubleValue != nil { return *m.DoubleValue } return 0 } func (m *UninterpretedOption) GetStringValue() []byte { if m != nil { return m.StringValue } return nil } func (m *UninterpretedOption) GetAggregateValue() string { if m != nil && m.AggregateValue != nil { return *m.AggregateValue } return "" } // The name of the uninterpreted option. Each string represents a segment in // a dot-separated name. is_extension is true iff a segment represents an // extension (denoted with parentheses in options specs in .proto files). // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents // "foo.(bar.baz).qux". type UninterpretedOption_NamePart struct { NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } func (*UninterpretedOption_NamePart) ProtoMessage() {} func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18, 0} } func (m *UninterpretedOption_NamePart) GetNamePart() string { if m != nil && m.NamePart != nil { return *m.NamePart } return "" } func (m *UninterpretedOption_NamePart) GetIsExtension() bool { if m != nil && m.IsExtension != nil { return *m.IsExtension } return false } // Encapsulates information about the original source file from which a // FileDescriptorProto was generated. type SourceCodeInfo struct { // A Location identifies a piece of source code in a .proto file which // corresponds to a particular definition. This information is intended // to be useful to IDEs, code indexers, documentation generators, and similar // tools. // // For example, say we have a file like: // message Foo { // optional string foo = 1; // } // Let's look at just the field definition: // optional string foo = 1; // ^ ^^ ^^ ^ ^^^ // a bc de f ghi // We have the following locations: // span path represents // [a,i) [ 4, 0, 2, 0 ] The whole field definition. // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). // // Notes: // - A location may refer to a repeated field itself (i.e. not to any // particular index within it). This is used whenever a set of elements are // logically enclosed in a single code segment. For example, an entire // extend block (possibly containing multiple extension definitions) will // have an outer location whose path refers to the "extensions" repeated // field without an index. // - Multiple locations may have the same path. This happens when a single // logical declaration is spread out across multiple places. The most // obvious example is the "extend" block again -- there may be multiple // extend blocks in the same scope, each of which will have the same path. // - A location's span is not always a subset of its parent's span. For // example, the "extendee" of an extension declaration appears at the // beginning of the "extend" block and is shared by all extensions within // the block. // - Just because a location's span is a subset of some other location's span // does not mean that it is a descendent. For example, a "group" defines // both a type and a field in a single declaration. Thus, the locations // corresponding to the type and field and their components will overlap. // - Code which tries to interpret locations should probably be designed to // ignore those that it doesn't understand, as more types of locations could // be recorded in the future. Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } func (*SourceCodeInfo) ProtoMessage() {} func (*SourceCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} } func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { if m != nil { return m.Location } return nil } type SourceCodeInfo_Location struct { // Identifies which part of the FileDescriptorProto was defined at this // location. // // Each element is a field number or an index. They form a path from // the root FileDescriptorProto to the place where the definition. For // example, this path: // [ 4, 3, 2, 7, 1 ] // refers to: // file.message_type(3) // 4, 3 // .field(7) // 2, 7 // .name() // 1 // This is because FileDescriptorProto.message_type has field number 4: // repeated DescriptorProto message_type = 4; // and DescriptorProto.field has field number 2: // repeated FieldDescriptorProto field = 2; // and FieldDescriptorProto.name has field number 1: // optional string name = 1; // // Thus, the above path gives the location of a field name. If we removed // the last element: // [ 4, 3, 2, 7 ] // this path refers to the whole field declaration (from the beginning // of the label to the terminating semicolon). Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` // Always has exactly three or four elements: start line, start column, // end line (optional, otherwise assumed same as start line), end column. // These are packed into a single field for efficiency. Note that line // and column numbers are zero-based -- typically you will want to add // 1 to each before displaying to a user. Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` // If this SourceCodeInfo represents a complete declaration, these are any // comments appearing before and after the declaration which appear to be // attached to the declaration. // // A series of line comments appearing on consecutive lines, with no other // tokens appearing on those lines, will be treated as a single comment. // // leading_detached_comments will keep paragraphs of comments that appear // before (but not connected to) the current element. Each paragraph, // separated by empty lines, will be one comment element in the repeated // field. // // Only the comment content is provided; comment markers (e.g. //) are // stripped out. For block comments, leading whitespace and an asterisk // will be stripped from the beginning of each line other than the first. // Newlines are included in the output. // // Examples: // // optional int32 foo = 1; // Comment attached to foo. // // Comment attached to bar. // optional int32 bar = 2; // // optional string baz = 3; // // Comment attached to baz. // // Another line attached to baz. // // // Comment attached to qux. // // // // Another line attached to qux. // optional double qux = 4; // // // Detached comment for corge. This is not leading or trailing comments // // to qux or corge because there are blank lines separating it from // // both. // // // Detached comment for corge paragraph 2. // // optional string corge = 5; // /* Block comment attached // * to corge. Leading asterisks // * will be removed. */ // /* Block comment attached to // * grault. */ // optional int32 grault = 6; // // // ignored detached comments. LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } func (*SourceCodeInfo_Location) ProtoMessage() {} func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19, 0} } func (m *SourceCodeInfo_Location) GetPath() []int32 { if m != nil { return m.Path } return nil } func (m *SourceCodeInfo_Location) GetSpan() []int32 { if m != nil { return m.Span } return nil } func (m *SourceCodeInfo_Location) GetLeadingComments() string { if m != nil && m.LeadingComments != nil { return *m.LeadingComments } return "" } func (m *SourceCodeInfo_Location) GetTrailingComments() string { if m != nil && m.TrailingComments != nil { return *m.TrailingComments } return "" } func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { if m != nil { return m.LeadingDetachedComments } return nil } // Describes the relationship between generated code and its original source // file. A GeneratedCodeInfo message is associated with only one generated // source file, but may contain references to different source .proto files. type GeneratedCodeInfo struct { // An Annotation connects some span of text in generated code to an element // of its generating .proto file. Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } func (*GeneratedCodeInfo) ProtoMessage() {} func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} } func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { if m != nil { return m.Annotation } return nil } type GeneratedCodeInfo_Annotation struct { // Identifies the element in the original source .proto file. This field // is formatted the same as SourceCodeInfo.Location.path. Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` // Identifies the filesystem path to the original source .proto. SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` // Identifies the starting offset in bytes in the generated code // that relates to the identified object. Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` // Identifies the ending offset in bytes in the generated code that // relates to the identified offset. The end offset should be one past // the last relevant byte (so the length of the text = end - begin). End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20, 0} } func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { if m != nil { return m.Path } return nil } func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string { if m != nil && m.SourceFile != nil { return *m.SourceFile } return "" } func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 { if m != nil && m.Begin != nil { return *m.Begin } return 0 } func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 { if m != nil && m.End != nil { return *m.End } return 0 } func init() { proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet") proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto") proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto") proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange") proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange") proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions") proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions") proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions") proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions") proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions") proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions") proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions") proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions") proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions") proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption") proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart") proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo") proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location") proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo") proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation") proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value) proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) } func init() { proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 2519 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x6e, 0x1b, 0xc7, 0x15, 0x0e, 0x7f, 0x45, 0x1e, 0x52, 0xd4, 0x68, 0xa4, 0xd8, 0x6b, 0xe5, 0xc7, 0x32, 0xf3, 0x63, 0xd9, 0x69, 0xa8, 0x40, 0xb1, 0x1d, 0x47, 0x29, 0xd2, 0x52, 0xe4, 0x5a, 0xa1, 0x4a, 0x91, 0xec, 0x92, 0x6a, 0x7e, 0x6e, 0x16, 0xa3, 0xdd, 0x21, 0xb9, 0xf6, 0x72, 0x77, 0xb3, 0xbb, 0xb4, 0xad, 0xa0, 0x17, 0x06, 0x7a, 0x55, 0xa0, 0x0f, 0x50, 0x14, 0x45, 0x2f, 0x72, 0x13, 0xa0, 0x0f, 0x50, 0x20, 0x77, 0x7d, 0x82, 0x02, 0x79, 0x83, 0xa2, 0x28, 0xd0, 0x3e, 0x46, 0x31, 0x33, 0xbb, 0xcb, 0x5d, 0xfe, 0xc4, 0x6a, 0x80, 0x38, 0x57, 0xe4, 0x7c, 0xe7, 0x3b, 0x67, 0xce, 0x9c, 0x39, 0x33, 0x73, 0x66, 0x16, 0x76, 0x47, 0xb6, 0x3d, 0x32, 0xe9, 0xbe, 0xe3, 0xda, 0xbe, 0x7d, 0x3e, 0x1d, 0xee, 0xeb, 0xd4, 0xd3, 0x5c, 0xc3, 0xf1, 0x6d, 0xb7, 0xc6, 0x31, 0xbc, 0x21, 0x18, 0xb5, 0x90, 0x51, 0x3d, 0x85, 0xcd, 0x07, 0x86, 0x49, 0x9b, 0x11, 0xb1, 0x4f, 0x7d, 0x7c, 0x1f, 0xb2, 0x43, 0xc3, 0xa4, 0x52, 0x6a, 0x37, 0xb3, 0x57, 0x3a, 0x78, 0xb3, 0x36, 0xa7, 0x54, 0x4b, 0x6a, 0xf4, 0x18, 0xac, 0x70, 0x8d, 0xea, 0xbf, 0xb3, 0xb0, 0xb5, 0x44, 0x8a, 0x31, 0x64, 0x2d, 0x32, 0x61, 0x16, 0x53, 0x7b, 0x45, 0x85, 0xff, 0xc7, 0x12, 0xac, 0x39, 0x44, 0x7b, 0x44, 0x46, 0x54, 0x4a, 0x73, 0x38, 0x6c, 0xe2, 0xd7, 0x01, 0x74, 0xea, 0x50, 0x4b, 0xa7, 0x96, 0x76, 0x21, 0x65, 0x76, 0x33, 0x7b, 0x45, 0x25, 0x86, 0xe0, 0x77, 0x60, 0xd3, 0x99, 0x9e, 0x9b, 0x86, 0xa6, 0xc6, 0x68, 0xb0, 0x9b, 0xd9, 0xcb, 0x29, 0x48, 0x08, 0x9a, 0x33, 0xf2, 0x4d, 0xd8, 0x78, 0x42, 0xc9, 0xa3, 0x38, 0xb5, 0xc4, 0xa9, 0x15, 0x06, 0xc7, 0x88, 0x0d, 0x28, 0x4f, 0xa8, 0xe7, 0x91, 0x11, 0x55, 0xfd, 0x0b, 0x87, 0x4a, 0x59, 0x3e, 0xfa, 0xdd, 0x85, 0xd1, 0xcf, 0x8f, 0xbc, 0x14, 0x68, 0x0d, 0x2e, 0x1c, 0x8a, 0xeb, 0x50, 0xa4, 0xd6, 0x74, 0x22, 0x2c, 0xe4, 0x56, 0xc4, 0x4f, 0xb6, 0xa6, 0x93, 0x79, 0x2b, 0x05, 0xa6, 0x16, 0x98, 0x58, 0xf3, 0xa8, 0xfb, 0xd8, 0xd0, 0xa8, 0x94, 0xe7, 0x06, 0x6e, 0x2e, 0x18, 0xe8, 0x0b, 0xf9, 0xbc, 0x8d, 0x50, 0x0f, 0x37, 0xa0, 0x48, 0x9f, 0xfa, 0xd4, 0xf2, 0x0c, 0xdb, 0x92, 0xd6, 0xb8, 0x91, 0xb7, 0x96, 0xcc, 0x22, 0x35, 0xf5, 0x79, 0x13, 0x33, 0x3d, 0x7c, 0x0f, 0xd6, 0x6c, 0xc7, 0x37, 0x6c, 0xcb, 0x93, 0x0a, 0xbb, 0xa9, 0xbd, 0xd2, 0xc1, 0xab, 0x4b, 0x13, 0xa1, 0x2b, 0x38, 0x4a, 0x48, 0xc6, 0x2d, 0x40, 0x9e, 0x3d, 0x75, 0x35, 0xaa, 0x6a, 0xb6, 0x4e, 0x55, 0xc3, 0x1a, 0xda, 0x52, 0x91, 0x1b, 0xb8, 0xbe, 0x38, 0x10, 0x4e, 0x6c, 0xd8, 0x3a, 0x6d, 0x59, 0x43, 0x5b, 0xa9, 0x78, 0x89, 0x36, 0xbe, 0x02, 0x79, 0xef, 0xc2, 0xf2, 0xc9, 0x53, 0xa9, 0xcc, 0x33, 0x24, 0x68, 0x55, 0xbf, 0xcd, 0xc3, 0xc6, 0x65, 0x52, 0xec, 0x23, 0xc8, 0x0d, 0xd9, 0x28, 0xa5, 0xf4, 0xff, 0x13, 0x03, 0xa1, 0x93, 0x0c, 0x62, 0xfe, 0x07, 0x06, 0xb1, 0x0e, 0x25, 0x8b, 0x7a, 0x3e, 0xd5, 0x45, 0x46, 0x64, 0x2e, 0x99, 0x53, 0x20, 0x94, 0x16, 0x53, 0x2a, 0xfb, 0x83, 0x52, 0xea, 0x33, 0xd8, 0x88, 0x5c, 0x52, 0x5d, 0x62, 0x8d, 0xc2, 0xdc, 0xdc, 0x7f, 0x9e, 0x27, 0x35, 0x39, 0xd4, 0x53, 0x98, 0x9a, 0x52, 0xa1, 0x89, 0x36, 0x6e, 0x02, 0xd8, 0x16, 0xb5, 0x87, 0xaa, 0x4e, 0x35, 0x53, 0x2a, 0xac, 0x88, 0x52, 0x97, 0x51, 0x16, 0xa2, 0x64, 0x0b, 0x54, 0x33, 0xf1, 0x87, 0xb3, 0x54, 0x5b, 0x5b, 0x91, 0x29, 0xa7, 0x62, 0x91, 0x2d, 0x64, 0xdb, 0x19, 0x54, 0x5c, 0xca, 0xf2, 0x9e, 0xea, 0xc1, 0xc8, 0x8a, 0xdc, 0x89, 0xda, 0x73, 0x47, 0xa6, 0x04, 0x6a, 0x62, 0x60, 0xeb, 0x6e, 0xbc, 0x89, 0xdf, 0x80, 0x08, 0x50, 0x79, 0x5a, 0x01, 0xdf, 0x85, 0xca, 0x21, 0xd8, 0x21, 0x13, 0xba, 0xf3, 0x15, 0x54, 0x92, 0xe1, 0xc1, 0xdb, 0x90, 0xf3, 0x7c, 0xe2, 0xfa, 0x3c, 0x0b, 0x73, 0x8a, 0x68, 0x60, 0x04, 0x19, 0x6a, 0xe9, 0x7c, 0x97, 0xcb, 0x29, 0xec, 0x2f, 0xfe, 0xe5, 0x6c, 0xc0, 0x19, 0x3e, 0xe0, 0xb7, 0x17, 0x67, 0x34, 0x61, 0x79, 0x7e, 0xdc, 0x3b, 0x1f, 0xc0, 0x7a, 0x62, 0x00, 0x97, 0xed, 0xba, 0xfa, 0x5b, 0x78, 0x79, 0xa9, 0x69, 0xfc, 0x19, 0x6c, 0x4f, 0x2d, 0xc3, 0xf2, 0xa9, 0xeb, 0xb8, 0x94, 0x65, 0xac, 0xe8, 0x4a, 0xfa, 0xcf, 0xda, 0x8a, 0x9c, 0x3b, 0x8b, 0xb3, 0x85, 0x15, 0x65, 0x6b, 0xba, 0x08, 0xde, 0x2e, 0x16, 0xfe, 0xbb, 0x86, 0x9e, 0x3d, 0x7b, 0xf6, 0x2c, 0x5d, 0xfd, 0x63, 0x1e, 0xb6, 0x97, 0xad, 0x99, 0xa5, 0xcb, 0xf7, 0x0a, 0xe4, 0xad, 0xe9, 0xe4, 0x9c, 0xba, 0x3c, 0x48, 0x39, 0x25, 0x68, 0xe1, 0x3a, 0xe4, 0x4c, 0x72, 0x4e, 0x4d, 0x29, 0xbb, 0x9b, 0xda, 0xab, 0x1c, 0xbc, 0x73, 0xa9, 0x55, 0x59, 0x6b, 0x33, 0x15, 0x45, 0x68, 0xe2, 0x8f, 0x21, 0x1b, 0x6c, 0xd1, 0xcc, 0xc2, 0xed, 0xcb, 0x59, 0x60, 0x6b, 0x49, 0xe1, 0x7a, 0xf8, 0x15, 0x28, 0xb2, 0x5f, 0x91, 0x1b, 0x79, 0xee, 0x73, 0x81, 0x01, 0x2c, 0x2f, 0xf0, 0x0e, 0x14, 0xf8, 0x32, 0xd1, 0x69, 0x78, 0xb4, 0x45, 0x6d, 0x96, 0x58, 0x3a, 0x1d, 0x92, 0xa9, 0xe9, 0xab, 0x8f, 0x89, 0x39, 0xa5, 0x3c, 0xe1, 0x8b, 0x4a, 0x39, 0x00, 0x7f, 0xc3, 0x30, 0x7c, 0x1d, 0x4a, 0x62, 0x55, 0x19, 0x96, 0x4e, 0x9f, 0xf2, 0xdd, 0x33, 0xa7, 0x88, 0x85, 0xd6, 0x62, 0x08, 0xeb, 0xfe, 0xa1, 0x67, 0x5b, 0x61, 0x6a, 0xf2, 0x2e, 0x18, 0xc0, 0xbb, 0xff, 0x60, 0x7e, 0xe3, 0x7e, 0x6d, 0xf9, 0xf0, 0xe6, 0x73, 0xaa, 0xfa, 0xb7, 0x34, 0x64, 0xf9, 0x7e, 0xb1, 0x01, 0xa5, 0xc1, 0xe7, 0x3d, 0x59, 0x6d, 0x76, 0xcf, 0x8e, 0xda, 0x32, 0x4a, 0xe1, 0x0a, 0x00, 0x07, 0x1e, 0xb4, 0xbb, 0xf5, 0x01, 0x4a, 0x47, 0xed, 0x56, 0x67, 0x70, 0xef, 0x0e, 0xca, 0x44, 0x0a, 0x67, 0x02, 0xc8, 0xc6, 0x09, 0xef, 0x1f, 0xa0, 0x1c, 0x46, 0x50, 0x16, 0x06, 0x5a, 0x9f, 0xc9, 0xcd, 0x7b, 0x77, 0x50, 0x3e, 0x89, 0xbc, 0x7f, 0x80, 0xd6, 0xf0, 0x3a, 0x14, 0x39, 0x72, 0xd4, 0xed, 0xb6, 0x51, 0x21, 0xb2, 0xd9, 0x1f, 0x28, 0xad, 0xce, 0x31, 0x2a, 0x46, 0x36, 0x8f, 0x95, 0xee, 0x59, 0x0f, 0x41, 0x64, 0xe1, 0x54, 0xee, 0xf7, 0xeb, 0xc7, 0x32, 0x2a, 0x45, 0x8c, 0xa3, 0xcf, 0x07, 0x72, 0x1f, 0x95, 0x13, 0x6e, 0xbd, 0x7f, 0x80, 0xd6, 0xa3, 0x2e, 0xe4, 0xce, 0xd9, 0x29, 0xaa, 0xe0, 0x4d, 0x58, 0x17, 0x5d, 0x84, 0x4e, 0x6c, 0xcc, 0x41, 0xf7, 0xee, 0x20, 0x34, 0x73, 0x44, 0x58, 0xd9, 0x4c, 0x00, 0xf7, 0xee, 0x20, 0x5c, 0x6d, 0x40, 0x8e, 0x67, 0x17, 0xc6, 0x50, 0x69, 0xd7, 0x8f, 0xe4, 0xb6, 0xda, 0xed, 0x0d, 0x5a, 0xdd, 0x4e, 0xbd, 0x8d, 0x52, 0x33, 0x4c, 0x91, 0x7f, 0x7d, 0xd6, 0x52, 0xe4, 0x26, 0x4a, 0xc7, 0xb1, 0x9e, 0x5c, 0x1f, 0xc8, 0x4d, 0x94, 0xa9, 0x6a, 0xb0, 0xbd, 0x6c, 0x9f, 0x5c, 0xba, 0x32, 0x62, 0x53, 0x9c, 0x5e, 0x31, 0xc5, 0xdc, 0xd6, 0xc2, 0x14, 0x7f, 0x9d, 0x82, 0xad, 0x25, 0x67, 0xc5, 0xd2, 0x4e, 0x7e, 0x01, 0x39, 0x91, 0xa2, 0xe2, 0xf4, 0xbc, 0xb5, 0xf4, 0xd0, 0xe1, 0x09, 0xbb, 0x70, 0x82, 0x72, 0xbd, 0x78, 0x05, 0x91, 0x59, 0x51, 0x41, 0x30, 0x13, 0x0b, 0x4e, 0xfe, 0x2e, 0x05, 0xd2, 0x2a, 0xdb, 0xcf, 0xd9, 0x28, 0xd2, 0x89, 0x8d, 0xe2, 0xa3, 0x79, 0x07, 0x6e, 0xac, 0x1e, 0xc3, 0x82, 0x17, 0xdf, 0xa4, 0xe0, 0xca, 0xf2, 0x42, 0x6b, 0xa9, 0x0f, 0x1f, 0x43, 0x7e, 0x42, 0xfd, 0xb1, 0x1d, 0x16, 0x1b, 0x6f, 0x2f, 0x39, 0xc2, 0x98, 0x78, 0x3e, 0x56, 0x81, 0x56, 0xfc, 0x0c, 0xcc, 0xac, 0xaa, 0x96, 0x84, 0x37, 0x0b, 0x9e, 0xfe, 0x3e, 0x0d, 0x2f, 0x2f, 0x35, 0xbe, 0xd4, 0xd1, 0xd7, 0x00, 0x0c, 0xcb, 0x99, 0xfa, 0xa2, 0xa0, 0x10, 0xfb, 0x53, 0x91, 0x23, 0x7c, 0xed, 0xb3, 0xbd, 0x67, 0xea, 0x47, 0xf2, 0x0c, 0x97, 0x83, 0x80, 0x38, 0xe1, 0xfe, 0xcc, 0xd1, 0x2c, 0x77, 0xf4, 0xf5, 0x15, 0x23, 0x5d, 0x38, 0xab, 0xdf, 0x03, 0xa4, 0x99, 0x06, 0xb5, 0x7c, 0xd5, 0xf3, 0x5d, 0x4a, 0x26, 0x86, 0x35, 0xe2, 0x1b, 0x70, 0xe1, 0x30, 0x37, 0x24, 0xa6, 0x47, 0x95, 0x0d, 0x21, 0xee, 0x87, 0x52, 0xa6, 0xc1, 0xcf, 0x38, 0x37, 0xa6, 0x91, 0x4f, 0x68, 0x08, 0x71, 0xa4, 0x51, 0xfd, 0xb6, 0x00, 0xa5, 0x58, 0x59, 0x8a, 0x6f, 0x40, 0xf9, 0x21, 0x79, 0x4c, 0xd4, 0xf0, 0xaa, 0x21, 0x22, 0x51, 0x62, 0x58, 0x2f, 0xb8, 0x6e, 0xbc, 0x07, 0xdb, 0x9c, 0x62, 0x4f, 0x7d, 0xea, 0xaa, 0x9a, 0x49, 0x3c, 0x8f, 0x07, 0xad, 0xc0, 0xa9, 0x98, 0xc9, 0xba, 0x4c, 0xd4, 0x08, 0x25, 0xf8, 0x2e, 0x6c, 0x71, 0x8d, 0xc9, 0xd4, 0xf4, 0x0d, 0xc7, 0xa4, 0x2a, 0xbb, 0xfc, 0x78, 0x7c, 0x23, 0x8e, 0x3c, 0xdb, 0x64, 0x8c, 0xd3, 0x80, 0xc0, 0x3c, 0xf2, 0x70, 0x13, 0x5e, 0xe3, 0x6a, 0x23, 0x6a, 0x51, 0x97, 0xf8, 0x54, 0xa5, 0x5f, 0x4e, 0x89, 0xe9, 0xa9, 0xc4, 0xd2, 0xd5, 0x31, 0xf1, 0xc6, 0xd2, 0x36, 0x33, 0x70, 0x94, 0x96, 0x52, 0xca, 0x35, 0x46, 0x3c, 0x0e, 0x78, 0x32, 0xa7, 0xd5, 0x2d, 0xfd, 0x13, 0xe2, 0x8d, 0xf1, 0x21, 0x5c, 0xe1, 0x56, 0x3c, 0xdf, 0x35, 0xac, 0x91, 0xaa, 0x8d, 0xa9, 0xf6, 0x48, 0x9d, 0xfa, 0xc3, 0xfb, 0xd2, 0x2b, 0xf1, 0xfe, 0xb9, 0x87, 0x7d, 0xce, 0x69, 0x30, 0xca, 0x99, 0x3f, 0xbc, 0x8f, 0xfb, 0x50, 0x66, 0x93, 0x31, 0x31, 0xbe, 0xa2, 0xea, 0xd0, 0x76, 0xf9, 0xc9, 0x52, 0x59, 0xb2, 0xb2, 0x63, 0x11, 0xac, 0x75, 0x03, 0x85, 0x53, 0x5b, 0xa7, 0x87, 0xb9, 0x7e, 0x4f, 0x96, 0x9b, 0x4a, 0x29, 0xb4, 0xf2, 0xc0, 0x76, 0x59, 0x42, 0x8d, 0xec, 0x28, 0xc0, 0x25, 0x91, 0x50, 0x23, 0x3b, 0x0c, 0xef, 0x5d, 0xd8, 0xd2, 0x34, 0x31, 0x66, 0x43, 0x53, 0x83, 0x2b, 0x8a, 0x27, 0xa1, 0x44, 0xb0, 0x34, 0xed, 0x58, 0x10, 0x82, 0x1c, 0xf7, 0xf0, 0x87, 0xf0, 0xf2, 0x2c, 0x58, 0x71, 0xc5, 0xcd, 0x85, 0x51, 0xce, 0xab, 0xde, 0x85, 0x2d, 0xe7, 0x62, 0x51, 0x11, 0x27, 0x7a, 0x74, 0x2e, 0xe6, 0xd5, 0x3e, 0x80, 0x6d, 0x67, 0xec, 0x2c, 0xea, 0xdd, 0x8e, 0xeb, 0x61, 0x67, 0xec, 0xcc, 0x2b, 0xbe, 0xc5, 0xef, 0xab, 0x2e, 0xd5, 0x88, 0x4f, 0x75, 0xe9, 0x6a, 0x9c, 0x1e, 0x13, 0xe0, 0x7d, 0x40, 0x9a, 0xa6, 0x52, 0x8b, 0x9c, 0x9b, 0x54, 0x25, 0x2e, 0xb5, 0x88, 0x27, 0x5d, 0x8f, 0x93, 0x2b, 0x9a, 0x26, 0x73, 0x69, 0x9d, 0x0b, 0xf1, 0x6d, 0xd8, 0xb4, 0xcf, 0x1f, 0x6a, 0x22, 0x25, 0x55, 0xc7, 0xa5, 0x43, 0xe3, 0xa9, 0xf4, 0x26, 0x8f, 0xef, 0x06, 0x13, 0xf0, 0x84, 0xec, 0x71, 0x18, 0xdf, 0x02, 0xa4, 0x79, 0x63, 0xe2, 0x3a, 0xbc, 0x26, 0xf0, 0x1c, 0xa2, 0x51, 0xe9, 0x2d, 0x41, 0x15, 0x78, 0x27, 0x84, 0xd9, 0x92, 0xf0, 0x9e, 0x18, 0x43, 0x3f, 0xb4, 0x78, 0x53, 0x2c, 0x09, 0x8e, 0x05, 0xd6, 0xf6, 0x00, 0xb1, 0x50, 0x24, 0x3a, 0xde, 0xe3, 0xb4, 0x8a, 0x33, 0x76, 0xe2, 0xfd, 0xbe, 0x01, 0xeb, 0x8c, 0x39, 0xeb, 0xf4, 0x96, 0xa8, 0x67, 0x9c, 0x71, 0xac, 0xc7, 0x1f, 0xad, 0xb4, 0xac, 0x1e, 0x42, 0x39, 0x9e, 0x9f, 0xb8, 0x08, 0x22, 0x43, 0x51, 0x8a, 0x9d, 0xf5, 0x8d, 0x6e, 0x93, 0x9d, 0xd2, 0x5f, 0xc8, 0x28, 0xcd, 0xaa, 0x85, 0x76, 0x6b, 0x20, 0xab, 0xca, 0x59, 0x67, 0xd0, 0x3a, 0x95, 0x51, 0x26, 0x56, 0x96, 0x9e, 0x64, 0x0b, 0x6f, 0xa3, 0x9b, 0xd5, 0xef, 0xd2, 0x50, 0x49, 0xde, 0x33, 0xf0, 0xcf, 0xe1, 0x6a, 0xf8, 0x28, 0xe0, 0x51, 0x5f, 0x7d, 0x62, 0xb8, 0x7c, 0xe1, 0x4c, 0x88, 0xa8, 0xb3, 0xa3, 0xa9, 0xdb, 0x0e, 0x58, 0x7d, 0xea, 0x7f, 0x6a, 0xb8, 0x6c, 0x59, 0x4c, 0x88, 0x8f, 0xdb, 0x70, 0xdd, 0xb2, 0x55, 0xcf, 0x27, 0x96, 0x4e, 0x5c, 0x5d, 0x9d, 0x3d, 0xc7, 0xa8, 0x44, 0xd3, 0xa8, 0xe7, 0xd9, 0xe2, 0xc0, 0x8a, 0xac, 0xbc, 0x6a, 0xd9, 0xfd, 0x80, 0x3c, 0xdb, 0xc9, 0xeb, 0x01, 0x75, 0x2e, 0xcd, 0x32, 0xab, 0xd2, 0xec, 0x15, 0x28, 0x4e, 0x88, 0xa3, 0x52, 0xcb, 0x77, 0x2f, 0x78, 0x75, 0x59, 0x50, 0x0a, 0x13, 0xe2, 0xc8, 0xac, 0xfd, 0x42, 0x8a, 0xfc, 0x93, 0x6c, 0xa1, 0x80, 0x8a, 0x27, 0xd9, 0x42, 0x11, 0x41, 0xf5, 0x5f, 0x19, 0x28, 0xc7, 0xab, 0x4d, 0x56, 0xbc, 0x6b, 0xfc, 0x64, 0x49, 0xf1, 0xbd, 0xe7, 0x8d, 0xef, 0xad, 0x4d, 0x6b, 0x0d, 0x76, 0xe4, 0x1c, 0xe6, 0x45, 0x0d, 0xa8, 0x08, 0x4d, 0x76, 0xdc, 0xb3, 0xdd, 0x86, 0x8a, 0x7b, 0x4d, 0x41, 0x09, 0x5a, 0xf8, 0x18, 0xf2, 0x0f, 0x3d, 0x6e, 0x3b, 0xcf, 0x6d, 0xbf, 0xf9, 0xfd, 0xb6, 0x4f, 0xfa, 0xdc, 0x78, 0xf1, 0xa4, 0xaf, 0x76, 0xba, 0xca, 0x69, 0xbd, 0xad, 0x04, 0xea, 0xf8, 0x1a, 0x64, 0x4d, 0xf2, 0xd5, 0x45, 0xf2, 0x70, 0xe2, 0xd0, 0x65, 0x27, 0xe1, 0x1a, 0x64, 0x9f, 0x50, 0xf2, 0x28, 0x79, 0x24, 0x70, 0xe8, 0x47, 0x5c, 0x0c, 0xfb, 0x90, 0xe3, 0xf1, 0xc2, 0x00, 0x41, 0xc4, 0xd0, 0x4b, 0xb8, 0x00, 0xd9, 0x46, 0x57, 0x61, 0x0b, 0x02, 0x41, 0x59, 0xa0, 0x6a, 0xaf, 0x25, 0x37, 0x64, 0x94, 0xae, 0xde, 0x85, 0xbc, 0x08, 0x02, 0x5b, 0x2c, 0x51, 0x18, 0xd0, 0x4b, 0x41, 0x33, 0xb0, 0x91, 0x0a, 0xa5, 0x67, 0xa7, 0x47, 0xb2, 0x82, 0xd2, 0xc9, 0xa9, 0xce, 0xa2, 0x5c, 0xd5, 0x83, 0x72, 0xbc, 0xdc, 0x7c, 0x31, 0x57, 0xc9, 0xbf, 0xa7, 0xa0, 0x14, 0x2b, 0x1f, 0x59, 0xe1, 0x42, 0x4c, 0xd3, 0x7e, 0xa2, 0x12, 0xd3, 0x20, 0x5e, 0x90, 0x1a, 0xc0, 0xa1, 0x3a, 0x43, 0x2e, 0x3b, 0x75, 0x2f, 0x68, 0x89, 0xe4, 0x50, 0xbe, 0xfa, 0x97, 0x14, 0xa0, 0xf9, 0x02, 0x74, 0xce, 0xcd, 0xd4, 0x4f, 0xe9, 0x66, 0xf5, 0xcf, 0x29, 0xa8, 0x24, 0xab, 0xce, 0x39, 0xf7, 0x6e, 0xfc, 0xa4, 0xee, 0xfd, 0x33, 0x0d, 0xeb, 0x89, 0x5a, 0xf3, 0xb2, 0xde, 0x7d, 0x09, 0x9b, 0x86, 0x4e, 0x27, 0x8e, 0xed, 0x53, 0x4b, 0xbb, 0x50, 0x4d, 0xfa, 0x98, 0x9a, 0x52, 0x95, 0x6f, 0x1a, 0xfb, 0xdf, 0x5f, 0xcd, 0xd6, 0x5a, 0x33, 0xbd, 0x36, 0x53, 0x3b, 0xdc, 0x6a, 0x35, 0xe5, 0xd3, 0x5e, 0x77, 0x20, 0x77, 0x1a, 0x9f, 0xab, 0x67, 0x9d, 0x5f, 0x75, 0xba, 0x9f, 0x76, 0x14, 0x64, 0xcc, 0xd1, 0x7e, 0xc4, 0x65, 0xdf, 0x03, 0x34, 0xef, 0x14, 0xbe, 0x0a, 0xcb, 0xdc, 0x42, 0x2f, 0xe1, 0x2d, 0xd8, 0xe8, 0x74, 0xd5, 0x7e, 0xab, 0x29, 0xab, 0xf2, 0x83, 0x07, 0x72, 0x63, 0xd0, 0x17, 0xd7, 0xfb, 0x88, 0x3d, 0x48, 0x2c, 0xf0, 0xea, 0x9f, 0x32, 0xb0, 0xb5, 0xc4, 0x13, 0x5c, 0x0f, 0x6e, 0x16, 0xe2, 0xb2, 0xf3, 0xee, 0x65, 0xbc, 0xaf, 0xb1, 0x82, 0xa0, 0x47, 0x5c, 0x3f, 0xb8, 0x88, 0xdc, 0x02, 0x16, 0x25, 0xcb, 0x37, 0x86, 0x06, 0x75, 0x83, 0xd7, 0x10, 0x71, 0xdd, 0xd8, 0x98, 0xe1, 0xe2, 0x41, 0xe4, 0x67, 0x80, 0x1d, 0xdb, 0x33, 0x7c, 0xe3, 0x31, 0x55, 0x0d, 0x2b, 0x7c, 0x3a, 0x61, 0xd7, 0x8f, 0xac, 0x82, 0x42, 0x49, 0xcb, 0xf2, 0x23, 0xb6, 0x45, 0x47, 0x64, 0x8e, 0xcd, 0x36, 0xf3, 0x8c, 0x82, 0x42, 0x49, 0xc4, 0xbe, 0x01, 0x65, 0xdd, 0x9e, 0xb2, 0x9a, 0x4c, 0xf0, 0xd8, 0xd9, 0x91, 0x52, 0x4a, 0x02, 0x8b, 0x28, 0x41, 0xb5, 0x3d, 0x7b, 0xb3, 0x29, 0x2b, 0x25, 0x81, 0x09, 0xca, 0x4d, 0xd8, 0x20, 0xa3, 0x91, 0xcb, 0x8c, 0x87, 0x86, 0xc4, 0xfd, 0xa1, 0x12, 0xc1, 0x9c, 0xb8, 0x73, 0x02, 0x85, 0x30, 0x0e, 0xec, 0xa8, 0x66, 0x91, 0x50, 0x1d, 0xf1, 0x6e, 0x97, 0xde, 0x2b, 0x2a, 0x05, 0x2b, 0x14, 0xde, 0x80, 0xb2, 0xe1, 0xa9, 0xb3, 0x27, 0xe8, 0xf4, 0x6e, 0x7a, 0xaf, 0xa0, 0x94, 0x0c, 0x2f, 0x7a, 0xbe, 0xab, 0x7e, 0x93, 0x86, 0x4a, 0xf2, 0x09, 0x1d, 0x37, 0xa1, 0x60, 0xda, 0x1a, 0xe1, 0xa9, 0x25, 0xbe, 0xdf, 0xec, 0x3d, 0xe7, 0xd5, 0xbd, 0xd6, 0x0e, 0xf8, 0x4a, 0xa4, 0xb9, 0xf3, 0x8f, 0x14, 0x14, 0x42, 0x18, 0x5f, 0x81, 0xac, 0x43, 0xfc, 0x31, 0x37, 0x97, 0x3b, 0x4a, 0xa3, 0x94, 0xc2, 0xdb, 0x0c, 0xf7, 0x1c, 0x62, 0xf1, 0x14, 0x08, 0x70, 0xd6, 0x66, 0xf3, 0x6a, 0x52, 0xa2, 0xf3, 0xcb, 0x89, 0x3d, 0x99, 0x50, 0xcb, 0xf7, 0xc2, 0x79, 0x0d, 0xf0, 0x46, 0x00, 0xe3, 0x77, 0x60, 0xd3, 0x77, 0x89, 0x61, 0x26, 0xb8, 0x59, 0xce, 0x45, 0xa1, 0x20, 0x22, 0x1f, 0xc2, 0xb5, 0xd0, 0xae, 0x4e, 0x7d, 0xa2, 0x8d, 0xa9, 0x3e, 0x53, 0xca, 0xf3, 0xf7, 0xd9, 0xab, 0x01, 0xa1, 0x19, 0xc8, 0x43, 0xdd, 0xea, 0x77, 0x29, 0xd8, 0x0c, 0xaf, 0x53, 0x7a, 0x14, 0xac, 0x53, 0x00, 0x62, 0x59, 0xb6, 0x1f, 0x0f, 0xd7, 0x62, 0x2a, 0x2f, 0xe8, 0xd5, 0xea, 0x91, 0x92, 0x12, 0x33, 0xb0, 0x33, 0x01, 0x98, 0x49, 0x56, 0x86, 0xed, 0x3a, 0x94, 0x82, 0xef, 0x23, 0xfc, 0x23, 0x9b, 0xb8, 0x80, 0x83, 0x80, 0xd8, 0xbd, 0x0b, 0x6f, 0x43, 0xee, 0x9c, 0x8e, 0x0c, 0x2b, 0x78, 0xf5, 0x14, 0x8d, 0xf0, 0x25, 0x37, 0x1b, 0xbd, 0xe4, 0x1e, 0xfd, 0x21, 0x05, 0x5b, 0x9a, 0x3d, 0x99, 0xf7, 0xf7, 0x08, 0xcd, 0xbd, 0x02, 0x78, 0x9f, 0xa4, 0xbe, 0xf8, 0x78, 0x64, 0xf8, 0xe3, 0xe9, 0x79, 0x4d, 0xb3, 0x27, 0xfb, 0x23, 0xdb, 0x24, 0xd6, 0x68, 0xf6, 0x95, 0x90, 0xff, 0xd1, 0xde, 0x1d, 0x51, 0xeb, 0xdd, 0x91, 0x1d, 0xfb, 0x66, 0xf8, 0xd1, 0xec, 0xef, 0xd7, 0xe9, 0xcc, 0x71, 0xef, 0xe8, 0xaf, 0xe9, 0x9d, 0x63, 0xd1, 0x57, 0x2f, 0x8c, 0x8d, 0x42, 0x87, 0x26, 0xd5, 0xd8, 0x78, 0xff, 0x17, 0x00, 0x00, 0xff, 0xff, 0x0c, 0xab, 0xb6, 0x37, 0x7e, 0x1c, 0x00, 0x00, } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile��������������������0000644�0610621�0607500�00000003766�13172163407�030706� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Not stored here, but descriptor.proto is in https://github.com/google/protobuf/ # at src/google/protobuf/descriptor.proto regenerate: @echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION cp $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto . protoc --go_out=../../../../.. -I$(HOME)/src/protobuf/include $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto ����������lxd-2.0.11/dist/src/github.com/golang/protobuf/protoc-gen-go/Makefile�������������������������������0000644�0610621�0607500�00000003207�13172163407�026516� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. test: cd testdata && make test �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163407�023537� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/text_test.go�����������������������������������0000644�0610621�0607500�00000027563�13172163407�026126� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "bytes" "errors" "io/ioutil" "math" "strings" "testing" "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) // textMessage implements the methods that allow it to marshal and unmarshal // itself as text. type textMessage struct { } func (*textMessage) MarshalText() ([]byte, error) { return []byte("custom"), nil } func (*textMessage) UnmarshalText(bytes []byte) error { if string(bytes) != "custom" { return errors.New("expected 'custom'") } return nil } func (*textMessage) Reset() {} func (*textMessage) String() string { return "" } func (*textMessage) ProtoMessage() {} func newTestMessage() *pb.MyMessage { msg := &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), Quote: proto.String(`"I didn't want to go."`), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &pb.InnerMessage{ Host: proto.String("footrest.syd"), Port: proto.Int32(7001), Connected: proto.Bool(true), }, Others: []*pb.OtherMessage{ { Key: proto.Int64(0xdeadbeef), Value: []byte{1, 65, 7, 12}, }, { Weight: proto.Float32(6.022), Inner: &pb.InnerMessage{ Host: proto.String("lesha.mtv"), Port: proto.Int32(8002), }, }, }, Bikeshed: pb.MyMessage_BLUE.Enum(), Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(8), }, // One normally wouldn't do this. // This is an undeclared tag 13, as a varint (wire type 0) with value 4. XXX_unrecognized: []byte{13<<3 | 0, 4}, } ext := &pb.Ext{ Data: proto.String("Big gobs for big rats"), } if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { panic(err) } greetings := []string{"adg", "easy", "cow"} if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { panic(err) } // Add an unknown extension. We marshal a pb.Ext, and fake the ID. b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) if err != nil { panic(err) } b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) proto.SetRawExtension(msg, 201, b) // Extensions can be plain fields, too, so let's test that. b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) proto.SetRawExtension(msg, 202, b) return msg } const text = `count: 42 name: "Dave" quote: "\"I didn't want to go.\"" pet: "bunny" pet: "kitty" pet: "horsey" inner: < host: "footrest.syd" port: 7001 connected: true > others: < key: 3735928559 value: "\001A\007\014" > others: < weight: 6.022 inner: < host: "lesha.mtv" port: 8002 > > bikeshed: BLUE SomeGroup { group_field: 8 } /* 2 unknown bytes */ 13: 4 [testdata.Ext.more]: < data: "Big gobs for big rats" > [testdata.greeting]: "adg" [testdata.greeting]: "easy" [testdata.greeting]: "cow" /* 13 unknown bytes */ 201: "\t3G skiing" /* 3 unknown bytes */ 202: 19 ` func TestMarshalText(t *testing.T) { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, newTestMessage()); err != nil { t.Fatalf("proto.MarshalText: %v", err) } s := buf.String() if s != text { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) } } func TestMarshalTextCustomMessage(t *testing.T) { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, &textMessage{}); err != nil { t.Fatalf("proto.MarshalText: %v", err) } s := buf.String() if s != "custom" { t.Errorf("Got %q, expected %q", s, "custom") } } func TestMarshalTextNil(t *testing.T) { want := "<nil>" tests := []proto.Message{nil, (*pb.MyMessage)(nil)} for i, test := range tests { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, test); err != nil { t.Fatal(err) } if got := buf.String(); got != want { t.Errorf("%d: got %q want %q", i, got, want) } } } func TestMarshalTextUnknownEnum(t *testing.T) { // The Color enum only specifies values 0-2. m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} got := m.String() const want = `bikeshed:3 ` if got != want { t.Errorf("\n got %q\nwant %q", got, want) } } func TestTextOneof(t *testing.T) { tests := []struct { m proto.Message want string }{ // zero message {&pb.Communique{}, ``}, // scalar field {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`}, // message field {&pb.Communique{Union: &pb.Communique_Msg{ &pb.Strings{StringField: proto.String("why hello!")}, }}, `msg:<string_field:"why hello!" >`}, // bad oneof (should not panic) {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`}, } for _, test := range tests { got := strings.TrimSpace(test.m.String()) if got != test.want { t.Errorf("\n got %s\nwant %s", got, test.want) } } } func BenchmarkMarshalTextBuffered(b *testing.B) { buf := new(bytes.Buffer) m := newTestMessage() for i := 0; i < b.N; i++ { buf.Reset() proto.MarshalText(buf, m) } } func BenchmarkMarshalTextUnbuffered(b *testing.B) { w := ioutil.Discard m := newTestMessage() for i := 0; i < b.N; i++ { proto.MarshalText(w, m) } } func compact(src string) string { // s/[ \n]+/ /g; s/ $//; dst := make([]byte, len(src)) space, comment := false, false j := 0 for i := 0; i < len(src); i++ { if strings.HasPrefix(src[i:], "/*") { comment = true i++ continue } if comment && strings.HasPrefix(src[i:], "*/") { comment = false i++ continue } if comment { continue } c := src[i] if c == ' ' || c == '\n' { space = true continue } if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { space = false } if c == '{' { space = false } if space { dst[j] = ' ' j++ space = false } dst[j] = c j++ } if space { dst[j] = ' ' j++ } return string(dst[0:j]) } var compactText = compact(text) func TestCompactText(t *testing.T) { s := proto.CompactTextString(newTestMessage()) if s != compactText { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) } } func TestStringEscaping(t *testing.T) { testCases := []struct { in *pb.Strings out string }{ { // Test data from C++ test (TextFormatTest.StringEscape). // Single divergence: we don't escape apostrophes. &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", }, { // Test data from the same C++ test. &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", }, { // Some UTF-8. &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, `string_field: "\000\001\377\201"` + "\n", }, } for i, tc := range testCases { var buf bytes.Buffer if err := proto.MarshalText(&buf, tc.in); err != nil { t.Errorf("proto.MarsalText: %v", err) continue } s := buf.String() if s != tc.out { t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) continue } // Check round-trip. pb := new(pb.Strings) if err := proto.UnmarshalText(s, pb); err != nil { t.Errorf("#%d: UnmarshalText: %v", i, err) continue } if !proto.Equal(pb, tc.in) { t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) } } } // A limitedWriter accepts some output before it fails. // This is a proxy for something like a nearly-full or imminently-failing disk, // or a network connection that is about to die. type limitedWriter struct { b bytes.Buffer limit int } var outOfSpace = errors.New("proto: insufficient space") func (w *limitedWriter) Write(p []byte) (n int, err error) { var avail = w.limit - w.b.Len() if avail <= 0 { return 0, outOfSpace } if len(p) <= avail { return w.b.Write(p) } n, _ = w.b.Write(p[:avail]) return n, outOfSpace } func TestMarshalTextFailing(t *testing.T) { // Try lots of different sizes to exercise more error code-paths. for lim := 0; lim < len(text); lim++ { buf := new(limitedWriter) buf.limit = lim err := proto.MarshalText(buf, newTestMessage()) // We expect a certain error, but also some partial results in the buffer. if err != outOfSpace { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) } s := buf.b.String() x := text[:buf.limit] if s != x { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) } } } func TestFloats(t *testing.T) { tests := []struct { f float64 want string }{ {0, "0"}, {4.7, "4.7"}, {math.Inf(1), "inf"}, {math.Inf(-1), "-inf"}, {math.NaN(), "nan"}, } for _, test := range tests { msg := &pb.FloatingPoint{F: &test.f} got := strings.TrimSpace(msg.String()) want := `f:` + test.want if got != want { t.Errorf("f=%f: got %q, want %q", test.f, got, want) } } } func TestRepeatedNilText(t *testing.T) { m := &pb.MessageList{ Message: []*pb.MessageList_Message{ nil, &pb.MessageList_Message{ Name: proto.String("Horse"), }, nil, }, } want := `Message <nil> Message { name: "Horse" } Message <nil> ` if s := proto.MarshalTextString(m); s != want { t.Errorf(" got: %s\nwant: %s", s, want) } } func TestProto3Text(t *testing.T) { tests := []struct { m proto.Message want string }{ // zero message {&proto3pb.Message{}, ``}, // zero message except for an empty byte slice {&proto3pb.Message{Data: []byte{}}, ``}, // trivial case {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, // empty map {&pb.MessageWithMap{}, ``}, // non-empty map; map format is the same as a repeated struct, // and they are sorted by key (numerically for numeric keys). { &pb.MessageWithMap{NameMapping: map[int32]string{ -1: "Negatory", 7: "Lucky", 1234: "Feist", 6345789: "Otis", }}, `name_mapping:<key:-1 value:"Negatory" > ` + `name_mapping:<key:7 value:"Lucky" > ` + `name_mapping:<key:1234 value:"Feist" > ` + `name_mapping:<key:6345789 value:"Otis" >`, }, // map with nil value; not well-defined, but we shouldn't crash { &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, `msg_mapping:<key:7 >`, }, } for _, test := range tests { got := strings.TrimSpace(test.m.String()) if got != test.want { t.Errorf("\n got %s\nwant %s", got, test.want) } } } ���������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/text_parser_test.go����������������������������0000644�0610621�0607500�00000037136�13172163407�027477� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "math" "reflect" "testing" . "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" . "github.com/golang/protobuf/proto/testdata" ) type UnmarshalTextTest struct { in string err string // if "", no error expected out *MyMessage } func buildExtStructTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } SetExtension(msg, E_Ext_More, &Ext{ Data: String("Hello, world!"), }) return UnmarshalTextTest{in: text, out: msg} } func buildExtDataTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } SetExtension(msg, E_Ext_Text, String("Hello, world!")) SetExtension(msg, E_Ext_Number, Int32(1729)) return UnmarshalTextTest{in: text, out: msg} } func buildExtRepStringTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { panic(err) } return UnmarshalTextTest{in: text, out: msg} } var unMarshalTextTests = []UnmarshalTextTest{ // Basic { in: " count:42\n name:\"Dave\" ", out: &MyMessage{ Count: Int32(42), Name: String("Dave"), }, }, // Empty quoted string { in: `count:42 name:""`, out: &MyMessage{ Count: Int32(42), Name: String(""), }, }, // Quoted string concatenation with double quotes { in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string concatenation with single quotes { in: "count:42 name: 'My name is '\n'elsewhere'", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string concatenations with mixed quotes { in: "count:42 name: 'My name is '\n\"elsewhere\"", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, { in: "count:42 name: \"My name is \"\n'elsewhere'", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string with escaped apostrophe { in: `count:42 name: "HOLIDAY - New Year\'s Day"`, out: &MyMessage{ Count: Int32(42), Name: String("HOLIDAY - New Year's Day"), }, }, // Quoted string with single quote { in: `count:42 name: 'Roger "The Ramster" Ramjet'`, out: &MyMessage{ Count: Int32(42), Name: String(`Roger "The Ramster" Ramjet`), }, }, // Quoted string with all the accepted special characters from the C++ test { in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", out: &MyMessage{ Count: Int32(42), Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), }, }, // Quoted string with quoted backslash { in: `count:42 name: "\\'xyz"`, out: &MyMessage{ Count: Int32(42), Name: String(`\'xyz`), }, }, // Quoted string with UTF-8 bytes. { in: "count:42 name: '\303\277\302\201\xAB'", out: &MyMessage{ Count: Int32(42), Name: String("\303\277\302\201\xAB"), }, }, // Bad quoted string { in: `inner: < host: "\0" >` + "\n", err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, }, // Number too large for int64 { in: "count: 1 others { key: 123456789012345678901 }", err: "line 1.23: invalid int64: 123456789012345678901", }, // Number too large for int32 { in: "count: 1234567890123", err: "line 1.7: invalid int32: 1234567890123", }, // Number in hexadecimal { in: "count: 0x2beef", out: &MyMessage{ Count: Int32(0x2beef), }, }, // Number in octal { in: "count: 024601", out: &MyMessage{ Count: Int32(024601), }, }, // Floating point number with "f" suffix { in: "count: 4 others:< weight: 17.0f >", out: &MyMessage{ Count: Int32(4), Others: []*OtherMessage{ { Weight: Float32(17), }, }, }, }, // Floating point positive infinity { in: "count: 4 bigfloat: inf", out: &MyMessage{ Count: Int32(4), Bigfloat: Float64(math.Inf(1)), }, }, // Floating point negative infinity { in: "count: 4 bigfloat: -inf", out: &MyMessage{ Count: Int32(4), Bigfloat: Float64(math.Inf(-1)), }, }, // Number too large for float32 { in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", }, // Number posing as a quoted string { in: `inner: < host: 12 >` + "\n", err: `line 1.15: invalid string: 12`, }, // Quoted string posing as int32 { in: `count: "12"`, err: `line 1.7: invalid int32: "12"`, }, // Quoted string posing a float32 { in: `others:< weight: "17.4" >`, err: `line 1.17: invalid float32: "17.4"`, }, // Enum { in: `count:42 bikeshed: BLUE`, out: &MyMessage{ Count: Int32(42), Bikeshed: MyMessage_BLUE.Enum(), }, }, // Repeated field { in: `count:42 pet: "horsey" pet:"bunny"`, out: &MyMessage{ Count: Int32(42), Pet: []string{"horsey", "bunny"}, }, }, // Repeated field with list notation { in: `count:42 pet: ["horsey", "bunny"]`, out: &MyMessage{ Count: Int32(42), Pet: []string{"horsey", "bunny"}, }, }, // Repeated message with/without colon and <>/{} { in: `count:42 others:{} others{} others:<> others:{}`, out: &MyMessage{ Count: Int32(42), Others: []*OtherMessage{ {}, {}, {}, {}, }, }, }, // Missing colon for inner message { in: `count:42 inner < host: "cauchy.syd" >`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("cauchy.syd"), }, }, }, // Missing colon for string field { in: `name "Dave"`, err: `line 1.5: expected ':', found "\"Dave\""`, }, // Missing colon for int32 field { in: `count 42`, err: `line 1.6: expected ':', found "42"`, }, // Missing required field { in: `name: "Pawel"`, err: `proto: required field "testdata.MyMessage.count" not set`, out: &MyMessage{ Name: String("Pawel"), }, }, // Missing required field in a required submessage { in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, err: `proto: required field "testdata.InnerMessage.host" not set`, out: &MyMessage{ Count: Int32(42), WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, }, }, // Repeated non-repeated field { in: `name: "Rob" name: "Russ"`, err: `line 1.12: non-repeated field "name" was repeated`, }, // Group { in: `count: 17 SomeGroup { group_field: 12 }`, out: &MyMessage{ Count: Int32(17), Somegroup: &MyMessage_SomeGroup{ GroupField: Int32(12), }, }, }, // Semicolon between fields { in: `count:3;name:"Calvin"`, out: &MyMessage{ Count: Int32(3), Name: String("Calvin"), }, }, // Comma between fields { in: `count:4,name:"Ezekiel"`, out: &MyMessage{ Count: Int32(4), Name: String("Ezekiel"), }, }, // Boolean false { in: `count:42 inner { host: "example.com" connected: false }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(false), }, }, }, // Boolean true { in: `count:42 inner { host: "example.com" connected: true }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(true), }, }, }, // Boolean 0 { in: `count:42 inner { host: "example.com" connected: 0 }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(false), }, }, }, // Boolean 1 { in: `count:42 inner { host: "example.com" connected: 1 }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(true), }, }, }, // Boolean f { in: `count:42 inner { host: "example.com" connected: f }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(false), }, }, }, // Boolean t { in: `count:42 inner { host: "example.com" connected: t }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(true), }, }, }, // Boolean False { in: `count:42 inner { host: "example.com" connected: False }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(false), }, }, }, // Boolean True { in: `count:42 inner { host: "example.com" connected: True }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(true), }, }, }, // Extension buildExtStructTest(`count: 42 [testdata.Ext.more]:<data:"Hello, world!" >`), buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), // Big all-in-one { in: "count:42 # Meaning\n" + `name:"Dave" ` + `quote:"\"I didn't want to go.\"" ` + `pet:"bunny" ` + `pet:"kitty" ` + `pet:"horsey" ` + `inner:<` + ` host:"footrest.syd" ` + ` port:7001 ` + ` connected:true ` + `> ` + `others:<` + ` key:3735928559 ` + ` value:"\x01A\a\f" ` + `> ` + `others:<` + " weight:58.9 # Atomic weight of Co\n" + ` inner:<` + ` host:"lesha.mtv" ` + ` port:8002 ` + ` >` + `>`, out: &MyMessage{ Count: Int32(42), Name: String("Dave"), Quote: String(`"I didn't want to go."`), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &InnerMessage{ Host: String("footrest.syd"), Port: Int32(7001), Connected: Bool(true), }, Others: []*OtherMessage{ { Key: Int64(3735928559), Value: []byte{0x1, 'A', '\a', '\f'}, }, { Weight: Float32(58.9), Inner: &InnerMessage{ Host: String("lesha.mtv"), Port: Int32(8002), }, }, }, }, }, } func TestUnmarshalText(t *testing.T) { for i, test := range unMarshalTextTests { pb := new(MyMessage) err := UnmarshalText(test.in, pb) if test.err == "" { // We don't expect failure. if err != nil { t.Errorf("Test %d: Unexpected error: %v", i, err) } else if !reflect.DeepEqual(pb, test.out) { t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", i, pb, test.out) } } else { // We do expect failure. if err == nil { t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) } else if err.Error() != test.err { t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", i, err.Error(), test.err) } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", i, pb, test.out) } } } } func TestUnmarshalTextCustomMessage(t *testing.T) { msg := &textMessage{} if err := UnmarshalText("custom", msg); err != nil { t.Errorf("Unexpected error from custom unmarshal: %v", err) } if UnmarshalText("not custom", msg) == nil { t.Errorf("Didn't get expected error from custom unmarshal") } } // Regression test; this caused a panic. func TestRepeatedEnum(t *testing.T) { pb := new(RepeatedEnum) if err := UnmarshalText("color: RED", pb); err != nil { t.Fatal(err) } exp := &RepeatedEnum{ Color: []RepeatedEnum_Color{RepeatedEnum_RED}, } if !Equal(pb, exp) { t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) } } func TestProto3TextParsing(t *testing.T) { m := new(proto3pb.Message) const in = `name: "Wallace" true_scotsman: true` want := &proto3pb.Message{ Name: "Wallace", TrueScotsman: true, } if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } } func TestMapParsing(t *testing.T) { m := new(MessageWithMap) const in = `name_mapping:<key:1234 value:"Feist"> name_mapping:<key:1 value:"Beatles">` + `msg_mapping:<key:-4, value:<f: 2.0>,>` + // separating commas are okay `msg_mapping<key:-2 value<f: 4.0>>` + // no colon after "value" `msg_mapping:<value:<f: 5.0>>` + // omitted key `msg_mapping:<key:1>` + // omitted value `byte_mapping:<key:true value:"so be it">` + `byte_mapping:<>` // omitted key and value want := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Beatles", 1234: "Feist", }, MsgMapping: map[int64]*FloatingPoint{ -4: {F: Float64(2.0)}, -2: {F: Float64(4.0)}, 0: {F: Float64(5.0)}, 1: nil, }, ByteMapping: map[bool][]byte{ false: nil, true: []byte("so be it"), }, } if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } } func TestOneofParsing(t *testing.T) { const in = `name:"Shrek"` m := new(Communique) want := &Communique{Union: &Communique_Name{"Shrek"}} if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } const inOverwrite = `name:"Shrek" number:42` m = new(Communique) testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" if err := UnmarshalText(inOverwrite, m); err == nil { t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) } else if err.Error() != testErr { t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", err.Error(), testErr) } } var benchInput string func init() { benchInput = "count: 4\n" for i := 0; i < 1000; i++ { benchInput += "pet: \"fido\"\n" } // Check it is valid input. pb := new(MyMessage) err := UnmarshalText(benchInput, pb) if err != nil { panic("Bad benchmark input: " + err.Error()) } } func BenchmarkUnmarshalText(b *testing.B) { pb := new(MyMessage) for i := 0; i < b.N; i++ { UnmarshalText(benchInput, pb) } b.SetBytes(int64(len(benchInput))) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/text_parser.go���������������������������������0000644�0610621�0607500�00000053635�13172163407�026442� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto // Functions for parsing the Text protocol buffer format. // TODO: message sets. import ( "encoding" "errors" "fmt" "reflect" "strconv" "strings" "unicode/utf8" ) // Error string emitted when deserializing Any and fields are already set const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" type ParseError struct { Message string Line int // 1-based line number Offset int // 0-based byte offset from start of input } func (p *ParseError) Error() string { if p.Line == 1 { // show offset only for first line return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) } return fmt.Sprintf("line %d: %v", p.Line, p.Message) } type token struct { value string err *ParseError line int // line number offset int // byte number from start of input, not start of line unquoted string // the unquoted version of value, if it was a quoted string } func (t *token) String() string { if t.err == nil { return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) } return fmt.Sprintf("parse error: %v", t.err) } type textParser struct { s string // remaining input done bool // whether the parsing is finished (success or error) backed bool // whether back() was called offset, line int cur token } func newTextParser(s string) *textParser { p := new(textParser) p.s = s p.line = 1 p.cur.line = 1 return p } func (p *textParser) errorf(format string, a ...interface{}) *ParseError { pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} p.cur.err = pe p.done = true return pe } // Numbers and identifiers are matched by [-+._A-Za-z0-9] func isIdentOrNumberChar(c byte) bool { switch { case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': return true case '0' <= c && c <= '9': return true } switch c { case '-', '+', '.', '_': return true } return false } func isWhitespace(c byte) bool { switch c { case ' ', '\t', '\n', '\r': return true } return false } func isQuote(c byte) bool { switch c { case '"', '\'': return true } return false } func (p *textParser) skipWhitespace() { i := 0 for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { if p.s[i] == '#' { // comment; skip to end of line or input for i < len(p.s) && p.s[i] != '\n' { i++ } if i == len(p.s) { break } } if p.s[i] == '\n' { p.line++ } i++ } p.offset += i p.s = p.s[i:len(p.s)] if len(p.s) == 0 { p.done = true } } func (p *textParser) advance() { // Skip whitespace p.skipWhitespace() if p.done { return } // Start of non-whitespace p.cur.err = nil p.cur.offset, p.cur.line = p.offset, p.line p.cur.unquoted = "" switch p.s[0] { case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': // Single symbol p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] case '"', '\'': // Quoted string i := 1 for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { if p.s[i] == '\\' && i+1 < len(p.s) { // skip escaped char i++ } i++ } if i >= len(p.s) || p.s[i] != p.s[0] { p.errorf("unmatched quote") return } unq, err := unquoteC(p.s[1:i], rune(p.s[0])) if err != nil { p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) return } p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] p.cur.unquoted = unq default: i := 0 for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { i++ } if i == 0 { p.errorf("unexpected byte %#x", p.s[0]) return } p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] } p.offset += len(p.cur.value) } var ( errBadUTF8 = errors.New("proto: bad UTF-8") errBadHex = errors.New("proto: bad hexadecimal") ) func unquoteC(s string, quote rune) (string, error) { // This is based on C++'s tokenizer.cc. // Despite its name, this is *not* parsing C syntax. // For instance, "\0" is an invalid quoted string. // Avoid allocation in trivial cases. simple := true for _, r := range s { if r == '\\' || r == quote { simple = false break } } if simple { return s, nil } buf := make([]byte, 0, 3*len(s)/2) for len(s) > 0 { r, n := utf8.DecodeRuneInString(s) if r == utf8.RuneError && n == 1 { return "", errBadUTF8 } s = s[n:] if r != '\\' { if r < utf8.RuneSelf { buf = append(buf, byte(r)) } else { buf = append(buf, string(r)...) } continue } ch, tail, err := unescape(s) if err != nil { return "", err } buf = append(buf, ch...) s = tail } return string(buf), nil } func unescape(s string) (ch string, tail string, err error) { r, n := utf8.DecodeRuneInString(s) if r == utf8.RuneError && n == 1 { return "", "", errBadUTF8 } s = s[n:] switch r { case 'a': return "\a", s, nil case 'b': return "\b", s, nil case 'f': return "\f", s, nil case 'n': return "\n", s, nil case 'r': return "\r", s, nil case 't': return "\t", s, nil case 'v': return "\v", s, nil case '?': return "?", s, nil // trigraph workaround case '\'', '"', '\\': return string(r), s, nil case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': if len(s) < 2 { return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) } base := 8 ss := s[:2] s = s[2:] if r == 'x' || r == 'X' { base = 16 } else { ss = string(r) + ss } i, err := strconv.ParseUint(ss, base, 8) if err != nil { return "", "", err } return string([]byte{byte(i)}), s, nil case 'u', 'U': n := 4 if r == 'U' { n = 8 } if len(s) < n { return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) } bs := make([]byte, n/2) for i := 0; i < n; i += 2 { a, ok1 := unhex(s[i]) b, ok2 := unhex(s[i+1]) if !ok1 || !ok2 { return "", "", errBadHex } bs[i/2] = a<<4 | b } s = s[n:] return string(bs), s, nil } return "", "", fmt.Errorf(`unknown escape \%c`, r) } // Adapted from src/pkg/strconv/quote.go. func unhex(b byte) (v byte, ok bool) { switch { case '0' <= b && b <= '9': return b - '0', true case 'a' <= b && b <= 'f': return b - 'a' + 10, true case 'A' <= b && b <= 'F': return b - 'A' + 10, true } return 0, false } // Back off the parser by one token. Can only be done between calls to next(). // It makes the next advance() a no-op. func (p *textParser) back() { p.backed = true } // Advances the parser and returns the new current token. func (p *textParser) next() *token { if p.backed || p.done { p.backed = false return &p.cur } p.advance() if p.done { p.cur.value = "" } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { // Look for multiple quoted strings separated by whitespace, // and concatenate them. cat := p.cur for { p.skipWhitespace() if p.done || !isQuote(p.s[0]) { break } p.advance() if p.cur.err != nil { return &p.cur } cat.value += " " + p.cur.value cat.unquoted += p.cur.unquoted } p.done = false // parser may have seen EOF, but we want to return cat p.cur = cat } return &p.cur } func (p *textParser) consumeToken(s string) error { tok := p.next() if tok.err != nil { return tok.err } if tok.value != s { p.back() return p.errorf("expected %q, found %q", s, tok.value) } return nil } // Return a RequiredNotSetError indicating which required field was not set. func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { st := sv.Type() sprops := GetProperties(st) for i := 0; i < st.NumField(); i++ { if !isNil(sv.Field(i)) { continue } props := sprops.Prop[i] if props.Required { return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} } } return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen } // Returns the index in the struct for the named field, as well as the parsed tag properties. func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { i, ok := sprops.decoderOrigNames[name] if ok { return i, sprops.Prop[i], true } return -1, nil, false } // Consume a ':' from the input stream (if the next token is a colon), // returning an error if a colon is needed but not present. func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { tok := p.next() if tok.err != nil { return tok.err } if tok.value != ":" { // Colon is optional when the field is a group or message. needColon := true switch props.Wire { case "group": needColon = false case "bytes": // A "bytes" field is either a message, a string, or a repeated field; // those three become *T, *string and []T respectively, so we can check for // this field being a pointer to a non-string. if typ.Kind() == reflect.Ptr { // *T or *string if typ.Elem().Kind() == reflect.String { break } } else if typ.Kind() == reflect.Slice { // []T or []*T if typ.Elem().Kind() != reflect.Ptr { break } } else if typ.Kind() == reflect.String { // The proto3 exception is for a string field, // which requires a colon. break } needColon = false } if needColon { return p.errorf("expected ':', found %q", tok.value) } p.back() } return nil } func (p *textParser) readStruct(sv reflect.Value, terminator string) error { st := sv.Type() sprops := GetProperties(st) reqCount := sprops.reqCount var reqFieldErr error fieldSet := make(map[string]bool) // A struct is a sequence of "name: value", terminated by one of // '>' or '}', or the end of the input. A name may also be // "[extension]" or "[type/url]". // // The whole struct can also be an expanded Any message, like: // [type/url] < ... struct contents ... > for { tok := p.next() if tok.err != nil { return tok.err } if tok.value == terminator { break } if tok.value == "[" { // Looks like an extension or an Any. // // TODO: Check whether we need to handle // namespace rooted names (e.g. ".something.Foo"). extName, err := p.consumeExtName() if err != nil { return err } if s := strings.LastIndex(extName, "/"); s >= 0 { // If it contains a slash, it's an Any type URL. messageName := extName[s+1:] mt := MessageType(messageName) if mt == nil { return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) } tok = p.next() if tok.err != nil { return tok.err } // consume an optional colon if tok.value == ":" { tok = p.next() if tok.err != nil { return tok.err } } var terminator string switch tok.value { case "<": terminator = ">" case "{": terminator = "}" default: return p.errorf("expected '{' or '<', found %q", tok.value) } v := reflect.New(mt.Elem()) if pe := p.readStruct(v.Elem(), terminator); pe != nil { return pe } b, err := Marshal(v.Interface().(Message)) if err != nil { return p.errorf("failed to marshal message of type %q: %v", messageName, err) } if fieldSet["type_url"] { return p.errorf(anyRepeatedlyUnpacked, "type_url") } if fieldSet["value"] { return p.errorf(anyRepeatedlyUnpacked, "value") } sv.FieldByName("TypeUrl").SetString(extName) sv.FieldByName("Value").SetBytes(b) fieldSet["type_url"] = true fieldSet["value"] = true continue } var desc *ExtensionDesc // This could be faster, but it's functional. // TODO: Do something smarter than a linear scan. for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { if d.Name == extName { desc = d break } } if desc == nil { return p.errorf("unrecognized extension %q", extName) } props := &Properties{} props.Parse(desc.Tag) typ := reflect.TypeOf(desc.ExtensionType) if err := p.checkForColon(props, typ); err != nil { return err } rep := desc.repeated() // Read the extension structure, and set it in // the value we're constructing. var ext reflect.Value if !rep { ext = reflect.New(typ).Elem() } else { ext = reflect.New(typ.Elem()).Elem() } if err := p.readAny(ext, props); err != nil { if _, ok := err.(*RequiredNotSetError); !ok { return err } reqFieldErr = err } ep := sv.Addr().Interface().(Message) if !rep { SetExtension(ep, desc, ext.Interface()) } else { old, err := GetExtension(ep, desc) var sl reflect.Value if err == nil { sl = reflect.ValueOf(old) // existing slice } else { sl = reflect.MakeSlice(typ, 0, 1) } sl = reflect.Append(sl, ext) SetExtension(ep, desc, sl.Interface()) } if err := p.consumeOptionalSeparator(); err != nil { return err } continue } // This is a normal, non-extension field. name := tok.value var dst reflect.Value fi, props, ok := structFieldByName(sprops, name) if ok { dst = sv.Field(fi) } else if oop, ok := sprops.OneofTypes[name]; ok { // It is a oneof. props = oop.Prop nv := reflect.New(oop.Type.Elem()) dst = nv.Elem().Field(0) field := sv.Field(oop.Field) if !field.IsNil() { return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) } field.Set(nv) } if !dst.IsValid() { return p.errorf("unknown field name %q in %v", name, st) } if dst.Kind() == reflect.Map { // Consume any colon. if err := p.checkForColon(props, dst.Type()); err != nil { return err } // Construct the map if it doesn't already exist. if dst.IsNil() { dst.Set(reflect.MakeMap(dst.Type())) } key := reflect.New(dst.Type().Key()).Elem() val := reflect.New(dst.Type().Elem()).Elem() // The map entry should be this sequence of tokens: // < key : KEY value : VALUE > // However, implementations may omit key or value, and technically // we should support them in any order. See b/28924776 for a time // this went wrong. tok := p.next() var terminator string switch tok.value { case "<": terminator = ">" case "{": terminator = "}" default: return p.errorf("expected '{' or '<', found %q", tok.value) } for { tok := p.next() if tok.err != nil { return tok.err } if tok.value == terminator { break } switch tok.value { case "key": if err := p.consumeToken(":"); err != nil { return err } if err := p.readAny(key, props.mkeyprop); err != nil { return err } if err := p.consumeOptionalSeparator(); err != nil { return err } case "value": if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { return err } if err := p.readAny(val, props.mvalprop); err != nil { return err } if err := p.consumeOptionalSeparator(); err != nil { return err } default: p.back() return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) } } dst.SetMapIndex(key, val) continue } // Check that it's not already set if it's not a repeated field. if !props.Repeated && fieldSet[name] { return p.errorf("non-repeated field %q was repeated", name) } if err := p.checkForColon(props, dst.Type()); err != nil { return err } // Parse into the field. fieldSet[name] = true if err := p.readAny(dst, props); err != nil { if _, ok := err.(*RequiredNotSetError); !ok { return err } reqFieldErr = err } if props.Required { reqCount-- } if err := p.consumeOptionalSeparator(); err != nil { return err } } if reqCount > 0 { return p.missingRequiredFieldError(sv) } return reqFieldErr } // consumeExtName consumes extension name or expanded Any type URL and the // following ']'. It returns the name or URL consumed. func (p *textParser) consumeExtName() (string, error) { tok := p.next() if tok.err != nil { return "", tok.err } // If extension name or type url is quoted, it's a single token. if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) if err != nil { return "", err } return name, p.consumeToken("]") } // Consume everything up to "]" var parts []string for tok.value != "]" { parts = append(parts, tok.value) tok = p.next() if tok.err != nil { return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) } } return strings.Join(parts, ""), nil } // consumeOptionalSeparator consumes an optional semicolon or comma. // It is used in readStruct to provide backward compatibility. func (p *textParser) consumeOptionalSeparator() error { tok := p.next() if tok.err != nil { return tok.err } if tok.value != ";" && tok.value != "," { p.back() } return nil } func (p *textParser) readAny(v reflect.Value, props *Properties) error { tok := p.next() if tok.err != nil { return tok.err } if tok.value == "" { return p.errorf("unexpected EOF") } switch fv := v; fv.Kind() { case reflect.Slice: at := v.Type() if at.Elem().Kind() == reflect.Uint8 { // Special case for []byte if tok.value[0] != '"' && tok.value[0] != '\'' { // Deliberately written out here, as the error after // this switch statement would write "invalid []byte: ...", // which is not as user-friendly. return p.errorf("invalid string: %v", tok.value) } bytes := []byte(tok.unquoted) fv.Set(reflect.ValueOf(bytes)) return nil } // Repeated field. if tok.value == "[" { // Repeated field with list notation, like [1,2,3]. for { fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) err := p.readAny(fv.Index(fv.Len()-1), props) if err != nil { return err } tok := p.next() if tok.err != nil { return tok.err } if tok.value == "]" { break } if tok.value != "," { return p.errorf("Expected ']' or ',' found %q", tok.value) } } return nil } // One value of the repeated field. p.back() fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) return p.readAny(fv.Index(fv.Len()-1), props) case reflect.Bool: // true/1/t/True or false/f/0/False. switch tok.value { case "true", "1", "t", "True": fv.SetBool(true) return nil case "false", "0", "f", "False": fv.SetBool(false) return nil } case reflect.Float32, reflect.Float64: v := tok.value // Ignore 'f' for compatibility with output generated by C++, but don't // remove 'f' when the value is "-inf" or "inf". if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { v = v[:len(v)-1] } if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { fv.SetFloat(f) return nil } case reflect.Int32: if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { fv.SetInt(x) return nil } if len(props.Enum) == 0 { break } m, ok := enumValueMaps[props.Enum] if !ok { break } x, ok := m[tok.value] if !ok { break } fv.SetInt(int64(x)) return nil case reflect.Int64: if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { fv.SetInt(x) return nil } case reflect.Ptr: // A basic field (indirected through pointer), or a repeated message/group p.back() fv.Set(reflect.New(fv.Type().Elem())) return p.readAny(fv.Elem(), props) case reflect.String: if tok.value[0] == '"' || tok.value[0] == '\'' { fv.SetString(tok.unquoted) return nil } case reflect.Struct: var terminator string switch tok.value { case "{": terminator = "}" case "<": terminator = ">" default: return p.errorf("expected '{' or '<', found %q", tok.value) } // TODO: Handle nested messages which implement encoding.TextUnmarshaler. return p.readStruct(fv, terminator) case reflect.Uint32: if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { fv.SetUint(x) return nil } case reflect.Uint64: if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { fv.SetUint(x) return nil } } return p.errorf("invalid %v: %v", v.Type(), tok.value) } // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb // before starting to unmarshal, so any existing data in pb is always removed. // If a required field is not set and no other error occurs, // UnmarshalText returns *RequiredNotSetError. func UnmarshalText(s string, pb Message) error { if um, ok := pb.(encoding.TextUnmarshaler); ok { err := um.UnmarshalText([]byte(s)) return err } pb.Reset() v := reflect.ValueOf(pb) if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { return pe } return nil } ���������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/text.go����������������������������������������0000644�0610621�0607500�00000051314�13172163407�025056� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto // Functions for writing the text protocol buffer format. import ( "bufio" "bytes" "encoding" "errors" "fmt" "io" "log" "math" "reflect" "sort" "strings" ) var ( newline = []byte("\n") spaces = []byte(" ") gtNewline = []byte(">\n") endBraceNewline = []byte("}\n") backslashN = []byte{'\\', 'n'} backslashR = []byte{'\\', 'r'} backslashT = []byte{'\\', 't'} backslashDQ = []byte{'\\', '"'} backslashBS = []byte{'\\', '\\'} posInf = []byte("inf") negInf = []byte("-inf") nan = []byte("nan") ) type writer interface { io.Writer WriteByte(byte) error } // textWriter is an io.Writer that tracks its indentation level. type textWriter struct { ind int complete bool // if the current position is a complete line compact bool // whether to write out as a one-liner w writer } func (w *textWriter) WriteString(s string) (n int, err error) { if !strings.Contains(s, "\n") { if !w.compact && w.complete { w.writeIndent() } w.complete = false return io.WriteString(w.w, s) } // WriteString is typically called without newlines, so this // codepath and its copy are rare. We copy to avoid // duplicating all of Write's logic here. return w.Write([]byte(s)) } func (w *textWriter) Write(p []byte) (n int, err error) { newlines := bytes.Count(p, newline) if newlines == 0 { if !w.compact && w.complete { w.writeIndent() } n, err = w.w.Write(p) w.complete = false return n, err } frags := bytes.SplitN(p, newline, newlines+1) if w.compact { for i, frag := range frags { if i > 0 { if err := w.w.WriteByte(' '); err != nil { return n, err } n++ } nn, err := w.w.Write(frag) n += nn if err != nil { return n, err } } return n, nil } for i, frag := range frags { if w.complete { w.writeIndent() } nn, err := w.w.Write(frag) n += nn if err != nil { return n, err } if i+1 < len(frags) { if err := w.w.WriteByte('\n'); err != nil { return n, err } n++ } } w.complete = len(frags[len(frags)-1]) == 0 return n, nil } func (w *textWriter) WriteByte(c byte) error { if w.compact && c == '\n' { c = ' ' } if !w.compact && w.complete { w.writeIndent() } err := w.w.WriteByte(c) w.complete = c == '\n' return err } func (w *textWriter) indent() { w.ind++ } func (w *textWriter) unindent() { if w.ind == 0 { log.Print("proto: textWriter unindented too far") return } w.ind-- } func writeName(w *textWriter, props *Properties) error { if _, err := w.WriteString(props.OrigName); err != nil { return err } if props.Wire != "group" { return w.WriteByte(':') } return nil } // raw is the interface satisfied by RawMessage. type raw interface { Bytes() []byte } func requiresQuotes(u string) bool { // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. for _, ch := range u { switch { case ch == '.' || ch == '/' || ch == '_': continue case '0' <= ch && ch <= '9': continue case 'A' <= ch && ch <= 'Z': continue case 'a' <= ch && ch <= 'z': continue default: return true } } return false } // isAny reports whether sv is a google.protobuf.Any message func isAny(sv reflect.Value) bool { type wkt interface { XXX_WellKnownType() string } t, ok := sv.Addr().Interface().(wkt) return ok && t.XXX_WellKnownType() == "Any" } // writeProto3Any writes an expanded google.protobuf.Any message. // // It returns (false, nil) if sv value can't be unmarshaled (e.g. because // required messages are not linked in). // // It returns (true, error) when sv was written in expanded format or an error // was encountered. func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { turl := sv.FieldByName("TypeUrl") val := sv.FieldByName("Value") if !turl.IsValid() || !val.IsValid() { return true, errors.New("proto: invalid google.protobuf.Any message") } b, ok := val.Interface().([]byte) if !ok { return true, errors.New("proto: invalid google.protobuf.Any message") } parts := strings.Split(turl.String(), "/") mt := MessageType(parts[len(parts)-1]) if mt == nil { return false, nil } m := reflect.New(mt.Elem()) if err := Unmarshal(b, m.Interface().(Message)); err != nil { return false, nil } w.Write([]byte("[")) u := turl.String() if requiresQuotes(u) { writeString(w, u) } else { w.Write([]byte(u)) } if w.compact { w.Write([]byte("]:<")) } else { w.Write([]byte("]: <\n")) w.ind++ } if err := tm.writeStruct(w, m.Elem()); err != nil { return true, err } if w.compact { w.Write([]byte("> ")) } else { w.ind-- w.Write([]byte(">\n")) } return true, nil } func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { if tm.ExpandAny && isAny(sv) { if canExpand, err := tm.writeProto3Any(w, sv); canExpand { return err } } st := sv.Type() sprops := GetProperties(st) for i := 0; i < sv.NumField(); i++ { fv := sv.Field(i) props := sprops.Prop[i] name := st.Field(i).Name if strings.HasPrefix(name, "XXX_") { // There are two XXX_ fields: // XXX_unrecognized []byte // XXX_extensions map[int32]proto.Extension // The first is handled here; // the second is handled at the bottom of this function. if name == "XXX_unrecognized" && !fv.IsNil() { if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { return err } } continue } if fv.Kind() == reflect.Ptr && fv.IsNil() { // Field not filled in. This could be an optional field or // a required field that wasn't filled in. Either way, there // isn't anything we can show for it. continue } if fv.Kind() == reflect.Slice && fv.IsNil() { // Repeated field that is empty, or a bytes field that is unused. continue } if props.Repeated && fv.Kind() == reflect.Slice { // Repeated field. for j := 0; j < fv.Len(); j++ { if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } v := fv.Index(j) if v.Kind() == reflect.Ptr && v.IsNil() { // A nil message in a repeated field is not valid, // but we can handle that more gracefully than panicking. if _, err := w.Write([]byte("<nil>\n")); err != nil { return err } continue } if err := tm.writeAny(w, v, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } continue } if fv.Kind() == reflect.Map { // Map fields are rendered as a repeated struct with key/value fields. keys := fv.MapKeys() sort.Sort(mapKeys(keys)) for _, key := range keys { val := fv.MapIndex(key) if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } // open struct if err := w.WriteByte('<'); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() // key if _, err := w.WriteString("key:"); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, key, props.mkeyprop); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } // nil values aren't legal, but we can avoid panicking because of them. if val.Kind() != reflect.Ptr || !val.IsNil() { // value if _, err := w.WriteString("value:"); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, val, props.mvalprop); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } // close struct w.unindent() if err := w.WriteByte('>'); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } continue } if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { // empty bytes field continue } if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { // proto3 non-repeated scalar field; skip if zero value if isProto3Zero(fv) { continue } } if fv.Kind() == reflect.Interface { // Check if it is a oneof. if st.Field(i).Tag.Get("protobuf_oneof") != "" { // fv is nil, or holds a pointer to generated struct. // That generated struct has exactly one field, // which has a protobuf struct tag. if fv.IsNil() { continue } inner := fv.Elem().Elem() // interface -> *T -> T tag := inner.Type().Field(0).Tag.Get("protobuf") props = new(Properties) // Overwrite the outer props var, but not its pointee. props.Parse(tag) // Write the value in the oneof, not the oneof itself. fv = inner.Field(0) // Special case to cope with malformed messages gracefully: // If the value in the oneof is a nil pointer, don't panic // in writeAny. if fv.Kind() == reflect.Ptr && fv.IsNil() { // Use errors.New so writeAny won't render quotes. msg := errors.New("/* nil */") fv = reflect.ValueOf(&msg).Elem() } } } if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if b, ok := fv.Interface().(raw); ok { if err := writeRaw(w, b.Bytes()); err != nil { return err } continue } // Enums have a String method, so writeAny will work fine. if err := tm.writeAny(w, fv, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } // Extensions (the XXX_extensions field). pv := sv.Addr() if _, ok := extendable(pv.Interface()); ok { if err := tm.writeExtensions(w, pv); err != nil { return err } } return nil } // writeRaw writes an uninterpreted raw message. func writeRaw(w *textWriter, b []byte) error { if err := w.WriteByte('<'); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() if err := writeUnknownStruct(w, b); err != nil { return err } w.unindent() if err := w.WriteByte('>'); err != nil { return err } return nil } // writeAny writes an arbitrary field. func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { v = reflect.Indirect(v) // Floats have special cases. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { x := v.Float() var b []byte switch { case math.IsInf(x, 1): b = posInf case math.IsInf(x, -1): b = negInf case math.IsNaN(x): b = nan } if b != nil { _, err := w.Write(b) return err } // Other values are handled below. } // We don't attempt to serialise every possible value type; only those // that can occur in protocol buffers. switch v.Kind() { case reflect.Slice: // Should only be a []byte; repeated fields are handled in writeStruct. if err := writeString(w, string(v.Bytes())); err != nil { return err } case reflect.String: if err := writeString(w, v.String()); err != nil { return err } case reflect.Struct: // Required/optional group/message. var bra, ket byte = '<', '>' if props != nil && props.Wire == "group" { bra, ket = '{', '}' } if err := w.WriteByte(bra); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() if etm, ok := v.Interface().(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { return err } if _, err = w.Write(text); err != nil { return err } } else if err := tm.writeStruct(w, v); err != nil { return err } w.unindent() if err := w.WriteByte(ket); err != nil { return err } default: _, err := fmt.Fprint(w, v.Interface()) return err } return nil } // equivalent to C's isprint. func isprint(c byte) bool { return c >= 0x20 && c < 0x7f } // writeString writes a string in the protocol buffer text format. // It is similar to strconv.Quote except we don't use Go escape sequences, // we treat the string as a byte sequence, and we use octal escapes. // These differences are to maintain interoperability with the other // languages' implementations of the text format. func writeString(w *textWriter, s string) error { // use WriteByte here to get any needed indent if err := w.WriteByte('"'); err != nil { return err } // Loop over the bytes, not the runes. for i := 0; i < len(s); i++ { var err error // Divergence from C++: we don't escape apostrophes. // There's no need to escape them, and the C++ parser // copes with a naked apostrophe. switch c := s[i]; c { case '\n': _, err = w.w.Write(backslashN) case '\r': _, err = w.w.Write(backslashR) case '\t': _, err = w.w.Write(backslashT) case '"': _, err = w.w.Write(backslashDQ) case '\\': _, err = w.w.Write(backslashBS) default: if isprint(c) { err = w.w.WriteByte(c) } else { _, err = fmt.Fprintf(w.w, "\\%03o", c) } } if err != nil { return err } } return w.WriteByte('"') } func writeUnknownStruct(w *textWriter, data []byte) (err error) { if !w.compact { if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { return err } } b := NewBuffer(data) for b.index < len(b.buf) { x, err := b.DecodeVarint() if err != nil { _, err := fmt.Fprintf(w, "/* %v */\n", err) return err } wire, tag := x&7, x>>3 if wire == WireEndGroup { w.unindent() if _, err := w.Write(endBraceNewline); err != nil { return err } continue } if _, err := fmt.Fprint(w, tag); err != nil { return err } if wire != WireStartGroup { if err := w.WriteByte(':'); err != nil { return err } } if !w.compact || wire == WireStartGroup { if err := w.WriteByte(' '); err != nil { return err } } switch wire { case WireBytes: buf, e := b.DecodeRawBytes(false) if e == nil { _, err = fmt.Fprintf(w, "%q", buf) } else { _, err = fmt.Fprintf(w, "/* %v */", e) } case WireFixed32: x, err = b.DecodeFixed32() err = writeUnknownInt(w, x, err) case WireFixed64: x, err = b.DecodeFixed64() err = writeUnknownInt(w, x, err) case WireStartGroup: err = w.WriteByte('{') w.indent() case WireVarint: x, err = b.DecodeVarint() err = writeUnknownInt(w, x, err) default: _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) } if err != nil { return err } if err = w.WriteByte('\n'); err != nil { return err } } return nil } func writeUnknownInt(w *textWriter, x uint64, err error) error { if err == nil { _, err = fmt.Fprint(w, x) } else { _, err = fmt.Fprintf(w, "/* %v */", err) } return err } type int32Slice []int32 func (s int32Slice) Len() int { return len(s) } func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // writeExtensions writes all the extensions in pv. // pv is assumed to be a pointer to a protocol message struct that is extendable. func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { emap := extensionMaps[pv.Type().Elem()] ep, _ := extendable(pv.Interface()) // Order the extensions by ID. // This isn't strictly necessary, but it will give us // canonical output, which will also make testing easier. m, mu := ep.extensionsRead() if m == nil { return nil } mu.Lock() ids := make([]int32, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Sort(int32Slice(ids)) mu.Unlock() for _, extNum := range ids { ext := m[extNum] var desc *ExtensionDesc if emap != nil { desc = emap[extNum] } if desc == nil { // Unknown extension. if err := writeUnknownStruct(w, ext.enc); err != nil { return err } continue } pb, err := GetExtension(ep, desc) if err != nil { return fmt.Errorf("failed getting extension: %v", err) } // Repeated extensions will appear as a slice. if !desc.repeated() { if err := tm.writeExtension(w, desc.Name, pb); err != nil { return err } } else { v := reflect.ValueOf(pb) for i := 0; i < v.Len(); i++ { if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { return err } } } } return nil } func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } return nil } func (w *textWriter) writeIndent() { if !w.complete { return } remain := w.ind * 2 for remain > 0 { n := remain if n > len(spaces) { n = len(spaces) } w.w.Write(spaces[:n]) remain -= n } w.complete = false } // TextMarshaler is a configurable text format marshaler. type TextMarshaler struct { Compact bool // use compact text format (one line). ExpandAny bool // expand google.protobuf.Any messages of known types } // Marshal writes a given protocol buffer in text format. // The only errors returned are from w. func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { val := reflect.ValueOf(pb) if pb == nil || val.IsNil() { w.Write([]byte("<nil>")) return nil } var bw *bufio.Writer ww, ok := w.(writer) if !ok { bw = bufio.NewWriter(w) ww = bw } aw := &textWriter{ w: ww, complete: true, compact: tm.Compact, } if etm, ok := pb.(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { return err } if _, err = aw.Write(text); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // Dereference the received pointer so we don't have outer < and >. v := reflect.Indirect(val) if err := tm.writeStruct(aw, v); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // Text is the same as Marshal, but returns the string directly. func (tm *TextMarshaler) Text(pb Message) string { var buf bytes.Buffer tm.Marshal(&buf, pb) return buf.String() } var ( defaultTextMarshaler = TextMarshaler{} compactTextMarshaler = TextMarshaler{Compact: true} ) // TODO: consider removing some of the Marshal functions below. // MarshalText writes a given protocol buffer in text format. // The only errors returned are from w. func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } // MarshalTextString is the same as MarshalText, but returns the string directly. func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } // CompactText writes a given protocol buffer in compact text format (one line). func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } // CompactTextString is the same as CompactText, but returns the string directly. func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/testdata/��������������������������������������0000755�0610621�0607500�00000000000�13172163407�025350� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/testdata/test.proto����������������������������0000644�0610621�0607500�00000036525�13172163407�027427� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A feature-rich test file for the protocol compiler and libraries. syntax = "proto2"; package testdata; enum FOO { FOO1 = 1; }; message GoEnum { required FOO foo = 1; } message GoTestField { required string Label = 1; required string Type = 2; } message GoTest { // An enum, for completeness. enum KIND { VOID = 0; // Basic types BOOL = 1; BYTES = 2; FINGERPRINT = 3; FLOAT = 4; INT = 5; STRING = 6; TIME = 7; // Groupings TUPLE = 8; ARRAY = 9; MAP = 10; // Table types TABLE = 11; // Functions FUNCTION = 12; // last tag }; // Some typical parameters required KIND Kind = 1; optional string Table = 2; optional int32 Param = 3; // Required, repeated and optional foreign fields. required GoTestField RequiredField = 4; repeated GoTestField RepeatedField = 5; optional GoTestField OptionalField = 6; // Required fields of all basic types required bool F_Bool_required = 10; required int32 F_Int32_required = 11; required int64 F_Int64_required = 12; required fixed32 F_Fixed32_required = 13; required fixed64 F_Fixed64_required = 14; required uint32 F_Uint32_required = 15; required uint64 F_Uint64_required = 16; required float F_Float_required = 17; required double F_Double_required = 18; required string F_String_required = 19; required bytes F_Bytes_required = 101; required sint32 F_Sint32_required = 102; required sint64 F_Sint64_required = 103; // Repeated fields of all basic types repeated bool F_Bool_repeated = 20; repeated int32 F_Int32_repeated = 21; repeated int64 F_Int64_repeated = 22; repeated fixed32 F_Fixed32_repeated = 23; repeated fixed64 F_Fixed64_repeated = 24; repeated uint32 F_Uint32_repeated = 25; repeated uint64 F_Uint64_repeated = 26; repeated float F_Float_repeated = 27; repeated double F_Double_repeated = 28; repeated string F_String_repeated = 29; repeated bytes F_Bytes_repeated = 201; repeated sint32 F_Sint32_repeated = 202; repeated sint64 F_Sint64_repeated = 203; // Optional fields of all basic types optional bool F_Bool_optional = 30; optional int32 F_Int32_optional = 31; optional int64 F_Int64_optional = 32; optional fixed32 F_Fixed32_optional = 33; optional fixed64 F_Fixed64_optional = 34; optional uint32 F_Uint32_optional = 35; optional uint64 F_Uint64_optional = 36; optional float F_Float_optional = 37; optional double F_Double_optional = 38; optional string F_String_optional = 39; optional bytes F_Bytes_optional = 301; optional sint32 F_Sint32_optional = 302; optional sint64 F_Sint64_optional = 303; // Default-valued fields of all basic types optional bool F_Bool_defaulted = 40 [default=true]; optional int32 F_Int32_defaulted = 41 [default=32]; optional int64 F_Int64_defaulted = 42 [default=64]; optional fixed32 F_Fixed32_defaulted = 43 [default=320]; optional fixed64 F_Fixed64_defaulted = 44 [default=640]; optional uint32 F_Uint32_defaulted = 45 [default=3200]; optional uint64 F_Uint64_defaulted = 46 [default=6400]; optional float F_Float_defaulted = 47 [default=314159.]; optional double F_Double_defaulted = 48 [default=271828.]; optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; optional sint32 F_Sint32_defaulted = 402 [default = -32]; optional sint64 F_Sint64_defaulted = 403 [default = -64]; // Packed repeated fields (no string or bytes). repeated bool F_Bool_repeated_packed = 50 [packed=true]; repeated int32 F_Int32_repeated_packed = 51 [packed=true]; repeated int64 F_Int64_repeated_packed = 52 [packed=true]; repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; repeated float F_Float_repeated_packed = 57 [packed=true]; repeated double F_Double_repeated_packed = 58 [packed=true]; repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; // Required, repeated, and optional groups. required group RequiredGroup = 70 { required string RequiredField = 71; }; repeated group RepeatedGroup = 80 { required string RequiredField = 81; }; optional group OptionalGroup = 90 { required string RequiredField = 91; }; } // For testing a group containing a required field. message GoTestRequiredGroupField { required group Group = 1 { required int32 Field = 2; }; } // For testing skipping of unrecognized fields. // Numbers are all big, larger than tag numbers in GoTestField, // the message used in the corresponding test. message GoSkipTest { required int32 skip_int32 = 11; required fixed32 skip_fixed32 = 12; required fixed64 skip_fixed64 = 13; required string skip_string = 14; required group SkipGroup = 15 { required int32 group_int32 = 16; required string group_string = 17; } } // For testing packed/non-packed decoder switching. // A serialized instance of one should be deserializable as the other. message NonPackedTest { repeated int32 a = 1; } message PackedTest { repeated int32 b = 1 [packed=true]; } message MaxTag { // Maximum possible tag number. optional string last_field = 536870911; } message OldMessage { message Nested { optional string name = 1; } optional Nested nested = 1; optional int32 num = 2; } // NewMessage is wire compatible with OldMessage; // imagine it as a future version. message NewMessage { message Nested { optional string name = 1; optional string food_group = 2; } optional Nested nested = 1; // This is an int32 in OldMessage. optional int64 num = 2; } // Smaller tests for ASCII formatting. message InnerMessage { required string host = 1; optional int32 port = 2 [default=4000]; optional bool connected = 3; } message OtherMessage { optional int64 key = 1; optional bytes value = 2; optional float weight = 3; optional InnerMessage inner = 4; extensions 100 to max; } message RequiredInnerMessage { required InnerMessage leo_finally_won_an_oscar = 1; } message MyMessage { required int32 count = 1; optional string name = 2; optional string quote = 3; repeated string pet = 4; optional InnerMessage inner = 5; repeated OtherMessage others = 6; optional RequiredInnerMessage we_must_go_deeper = 13; repeated InnerMessage rep_inner = 12; enum Color { RED = 0; GREEN = 1; BLUE = 2; }; optional Color bikeshed = 7; optional group SomeGroup = 8 { optional int32 group_field = 9; } // This field becomes [][]byte in the generated code. repeated bytes rep_bytes = 10; optional double bigfloat = 11; extensions 100 to max; } message Ext { extend MyMessage { optional Ext more = 103; optional string text = 104; optional int32 number = 105; } optional string data = 1; } extend MyMessage { repeated string greeting = 106; } message ComplexExtension { optional int32 first = 1; optional int32 second = 2; repeated int32 third = 3; } extend OtherMessage { optional ComplexExtension complex = 200; repeated ComplexExtension r_complex = 201; } message DefaultsMessage { enum DefaultsEnum { ZERO = 0; ONE = 1; TWO = 2; }; extensions 100 to max; } extend DefaultsMessage { optional double no_default_double = 101; optional float no_default_float = 102; optional int32 no_default_int32 = 103; optional int64 no_default_int64 = 104; optional uint32 no_default_uint32 = 105; optional uint64 no_default_uint64 = 106; optional sint32 no_default_sint32 = 107; optional sint64 no_default_sint64 = 108; optional fixed32 no_default_fixed32 = 109; optional fixed64 no_default_fixed64 = 110; optional sfixed32 no_default_sfixed32 = 111; optional sfixed64 no_default_sfixed64 = 112; optional bool no_default_bool = 113; optional string no_default_string = 114; optional bytes no_default_bytes = 115; optional DefaultsMessage.DefaultsEnum no_default_enum = 116; optional double default_double = 201 [default = 3.1415]; optional float default_float = 202 [default = 3.14]; optional int32 default_int32 = 203 [default = 42]; optional int64 default_int64 = 204 [default = 43]; optional uint32 default_uint32 = 205 [default = 44]; optional uint64 default_uint64 = 206 [default = 45]; optional sint32 default_sint32 = 207 [default = 46]; optional sint64 default_sint64 = 208 [default = 47]; optional fixed32 default_fixed32 = 209 [default = 48]; optional fixed64 default_fixed64 = 210 [default = 49]; optional sfixed32 default_sfixed32 = 211 [default = 50]; optional sfixed64 default_sfixed64 = 212 [default = 51]; optional bool default_bool = 213 [default = true]; optional string default_string = 214 [default = "Hello, string"]; optional bytes default_bytes = 215 [default = "Hello, bytes"]; optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE]; } message MyMessageSet { option message_set_wire_format = true; extensions 100 to max; } message Empty { } extend MyMessageSet { optional Empty x201 = 201; optional Empty x202 = 202; optional Empty x203 = 203; optional Empty x204 = 204; optional Empty x205 = 205; optional Empty x206 = 206; optional Empty x207 = 207; optional Empty x208 = 208; optional Empty x209 = 209; optional Empty x210 = 210; optional Empty x211 = 211; optional Empty x212 = 212; optional Empty x213 = 213; optional Empty x214 = 214; optional Empty x215 = 215; optional Empty x216 = 216; optional Empty x217 = 217; optional Empty x218 = 218; optional Empty x219 = 219; optional Empty x220 = 220; optional Empty x221 = 221; optional Empty x222 = 222; optional Empty x223 = 223; optional Empty x224 = 224; optional Empty x225 = 225; optional Empty x226 = 226; optional Empty x227 = 227; optional Empty x228 = 228; optional Empty x229 = 229; optional Empty x230 = 230; optional Empty x231 = 231; optional Empty x232 = 232; optional Empty x233 = 233; optional Empty x234 = 234; optional Empty x235 = 235; optional Empty x236 = 236; optional Empty x237 = 237; optional Empty x238 = 238; optional Empty x239 = 239; optional Empty x240 = 240; optional Empty x241 = 241; optional Empty x242 = 242; optional Empty x243 = 243; optional Empty x244 = 244; optional Empty x245 = 245; optional Empty x246 = 246; optional Empty x247 = 247; optional Empty x248 = 248; optional Empty x249 = 249; optional Empty x250 = 250; } message MessageList { repeated group Message = 1 { required string name = 2; required int32 count = 3; } } message Strings { optional string string_field = 1; optional bytes bytes_field = 2; } message Defaults { enum Color { RED = 0; GREEN = 1; BLUE = 2; } // Default-valued fields of all basic types. // Same as GoTest, but copied here to make testing easier. optional bool F_Bool = 1 [default=true]; optional int32 F_Int32 = 2 [default=32]; optional int64 F_Int64 = 3 [default=64]; optional fixed32 F_Fixed32 = 4 [default=320]; optional fixed64 F_Fixed64 = 5 [default=640]; optional uint32 F_Uint32 = 6 [default=3200]; optional uint64 F_Uint64 = 7 [default=6400]; optional float F_Float = 8 [default=314159.]; optional double F_Double = 9 [default=271828.]; optional string F_String = 10 [default="hello, \"world!\"\n"]; optional bytes F_Bytes = 11 [default="Bignose"]; optional sint32 F_Sint32 = 12 [default=-32]; optional sint64 F_Sint64 = 13 [default=-64]; optional Color F_Enum = 14 [default=GREEN]; // More fields with crazy defaults. optional float F_Pinf = 15 [default=inf]; optional float F_Ninf = 16 [default=-inf]; optional float F_Nan = 17 [default=nan]; // Sub-message. optional SubDefaults sub = 18; // Redundant but explicit defaults. optional string str_zero = 19 [default=""]; } message SubDefaults { optional int64 n = 1 [default=7]; } message RepeatedEnum { enum Color { RED = 1; } repeated Color color = 1; } message MoreRepeated { repeated bool bools = 1; repeated bool bools_packed = 2 [packed=true]; repeated int32 ints = 3; repeated int32 ints_packed = 4 [packed=true]; repeated int64 int64s_packed = 7 [packed=true]; repeated string strings = 5; repeated fixed32 fixeds = 6; } // GroupOld and GroupNew have the same wire format. // GroupNew has a new field inside a group. message GroupOld { optional group G = 101 { optional int32 x = 2; } } message GroupNew { optional group G = 101 { optional int32 x = 2; optional int32 y = 3; } } message FloatingPoint { required double f = 1; optional bool exact = 2; } message MessageWithMap { map<int32, string> name_mapping = 1; map<sint64, FloatingPoint> msg_mapping = 2; map<bool, bytes> byte_mapping = 3; map<string, string> str_to_str = 4; } message Oneof { oneof union { bool F_Bool = 1; int32 F_Int32 = 2; int64 F_Int64 = 3; fixed32 F_Fixed32 = 4; fixed64 F_Fixed64 = 5; uint32 F_Uint32 = 6; uint64 F_Uint64 = 7; float F_Float = 8; double F_Double = 9; string F_String = 10; bytes F_Bytes = 11; sint32 F_Sint32 = 12; sint64 F_Sint64 = 13; MyMessage.Color F_Enum = 14; GoTestField F_Message = 15; group F_Group = 16 { optional int32 x = 17; } int32 F_Largest_Tag = 536870911; } oneof tormato { int32 value = 100; } } message Communique { optional bool make_me_cry = 1; // This is a oneof, called "union". oneof union { int32 number = 5; string name = 6; bytes data = 7; double temp_c = 8; MyMessage.Color col = 9; Strings msg = 10; } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/testdata/test.pb.go����������������������������0000644�0610621�0607500�00000435556�13172163407�027300� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: test.proto /* Package testdata is a generated protocol buffer package. It is generated from these files: test.proto It has these top-level messages: GoEnum GoTestField GoTest GoTestRequiredGroupField GoSkipTest NonPackedTest PackedTest MaxTag OldMessage NewMessage InnerMessage OtherMessage RequiredInnerMessage MyMessage Ext ComplexExtension DefaultsMessage MyMessageSet Empty MessageList Strings Defaults SubDefaults RepeatedEnum MoreRepeated GroupOld GroupNew FloatingPoint MessageWithMap Oneof Communique */ package testdata import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type FOO int32 const ( FOO_FOO1 FOO = 1 ) var FOO_name = map[int32]string{ 1: "FOO1", } var FOO_value = map[string]int32{ "FOO1": 1, } func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return proto.EnumName(FOO_name, int32(x)) } func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") if err != nil { return err } *x = FOO(value) return nil } func (FOO) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } // An enum, for completeness. type GoTest_KIND int32 const ( GoTest_VOID GoTest_KIND = 0 // Basic types GoTest_BOOL GoTest_KIND = 1 GoTest_BYTES GoTest_KIND = 2 GoTest_FINGERPRINT GoTest_KIND = 3 GoTest_FLOAT GoTest_KIND = 4 GoTest_INT GoTest_KIND = 5 GoTest_STRING GoTest_KIND = 6 GoTest_TIME GoTest_KIND = 7 // Groupings GoTest_TUPLE GoTest_KIND = 8 GoTest_ARRAY GoTest_KIND = 9 GoTest_MAP GoTest_KIND = 10 // Table types GoTest_TABLE GoTest_KIND = 11 // Functions GoTest_FUNCTION GoTest_KIND = 12 ) var GoTest_KIND_name = map[int32]string{ 0: "VOID", 1: "BOOL", 2: "BYTES", 3: "FINGERPRINT", 4: "FLOAT", 5: "INT", 6: "STRING", 7: "TIME", 8: "TUPLE", 9: "ARRAY", 10: "MAP", 11: "TABLE", 12: "FUNCTION", } var GoTest_KIND_value = map[string]int32{ "VOID": 0, "BOOL": 1, "BYTES": 2, "FINGERPRINT": 3, "FLOAT": 4, "INT": 5, "STRING": 6, "TIME": 7, "TUPLE": 8, "ARRAY": 9, "MAP": 10, "TABLE": 11, "FUNCTION": 12, } func (x GoTest_KIND) Enum() *GoTest_KIND { p := new(GoTest_KIND) *p = x return p } func (x GoTest_KIND) String() string { return proto.EnumName(GoTest_KIND_name, int32(x)) } func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") if err != nil { return err } *x = GoTest_KIND(value) return nil } func (GoTest_KIND) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } type MyMessage_Color int32 const ( MyMessage_RED MyMessage_Color = 0 MyMessage_GREEN MyMessage_Color = 1 MyMessage_BLUE MyMessage_Color = 2 ) var MyMessage_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var MyMessage_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x MyMessage_Color) Enum() *MyMessage_Color { p := new(MyMessage_Color) *p = x return p } func (x MyMessage_Color) String() string { return proto.EnumName(MyMessage_Color_name, int32(x)) } func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") if err != nil { return err } *x = MyMessage_Color(value) return nil } func (MyMessage_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{13, 0} } type DefaultsMessage_DefaultsEnum int32 const ( DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0 DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1 DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2 ) var DefaultsMessage_DefaultsEnum_name = map[int32]string{ 0: "ZERO", 1: "ONE", 2: "TWO", } var DefaultsMessage_DefaultsEnum_value = map[string]int32{ "ZERO": 0, "ONE": 1, "TWO": 2, } func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum { p := new(DefaultsMessage_DefaultsEnum) *p = x return p } func (x DefaultsMessage_DefaultsEnum) String() string { return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x)) } func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum") if err != nil { return err } *x = DefaultsMessage_DefaultsEnum(value) return nil } func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{16, 0} } type Defaults_Color int32 const ( Defaults_RED Defaults_Color = 0 Defaults_GREEN Defaults_Color = 1 Defaults_BLUE Defaults_Color = 2 ) var Defaults_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Defaults_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Defaults_Color) Enum() *Defaults_Color { p := new(Defaults_Color) *p = x return p } func (x Defaults_Color) String() string { return proto.EnumName(Defaults_Color_name, int32(x)) } func (x *Defaults_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") if err != nil { return err } *x = Defaults_Color(value) return nil } func (Defaults_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{21, 0} } type RepeatedEnum_Color int32 const ( RepeatedEnum_RED RepeatedEnum_Color = 1 ) var RepeatedEnum_Color_name = map[int32]string{ 1: "RED", } var RepeatedEnum_Color_value = map[string]int32{ "RED": 1, } func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { p := new(RepeatedEnum_Color) *p = x return p } func (x RepeatedEnum_Color) String() string { return proto.EnumName(RepeatedEnum_Color_name, int32(x)) } func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") if err != nil { return err } *x = RepeatedEnum_Color(value) return nil } func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{23, 0} } type GoEnum struct { Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoEnum) Reset() { *m = GoEnum{} } func (m *GoEnum) String() string { return proto.CompactTextString(m) } func (*GoEnum) ProtoMessage() {} func (*GoEnum) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *GoEnum) GetFoo() FOO { if m != nil && m.Foo != nil { return *m.Foo } return FOO_FOO1 } type GoTestField struct { Label *string `protobuf:"bytes,1,req,name=Label" json:"Label,omitempty"` Type *string `protobuf:"bytes,2,req,name=Type" json:"Type,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTestField) Reset() { *m = GoTestField{} } func (m *GoTestField) String() string { return proto.CompactTextString(m) } func (*GoTestField) ProtoMessage() {} func (*GoTestField) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *GoTestField) GetLabel() string { if m != nil && m.Label != nil { return *m.Label } return "" } func (m *GoTestField) GetType() string { if m != nil && m.Type != nil { return *m.Type } return "" } type GoTest struct { // Some typical parameters Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` Table *string `protobuf:"bytes,2,opt,name=Table" json:"Table,omitempty"` Param *int32 `protobuf:"varint,3,opt,name=Param" json:"Param,omitempty"` // Required, repeated and optional foreign fields. RequiredField *GoTestField `protobuf:"bytes,4,req,name=RequiredField" json:"RequiredField,omitempty"` RepeatedField []*GoTestField `protobuf:"bytes,5,rep,name=RepeatedField" json:"RepeatedField,omitempty"` OptionalField *GoTestField `protobuf:"bytes,6,opt,name=OptionalField" json:"OptionalField,omitempty"` // Required fields of all basic types F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required,json=FBoolRequired" json:"F_Bool_required,omitempty"` F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required,json=FInt32Required" json:"F_Int32_required,omitempty"` F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required,json=FInt64Required" json:"F_Int64_required,omitempty"` F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required,json=FFixed32Required" json:"F_Fixed32_required,omitempty"` F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required,json=FFixed64Required" json:"F_Fixed64_required,omitempty"` F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required,json=FUint32Required" json:"F_Uint32_required,omitempty"` F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required,json=FUint64Required" json:"F_Uint64_required,omitempty"` F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required,json=FFloatRequired" json:"F_Float_required,omitempty"` F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required,json=FDoubleRequired" json:"F_Double_required,omitempty"` F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required,json=FStringRequired" json:"F_String_required,omitempty"` F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required,json=FBytesRequired" json:"F_Bytes_required,omitempty"` F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required,json=FSint32Required" json:"F_Sint32_required,omitempty"` F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required,json=FSint64Required" json:"F_Sint64_required,omitempty"` // Repeated fields of all basic types F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated,json=FBoolRepeated" json:"F_Bool_repeated,omitempty"` F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated,json=FInt32Repeated" json:"F_Int32_repeated,omitempty"` F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated,json=FInt64Repeated" json:"F_Int64_repeated,omitempty"` F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated,json=FFixed32Repeated" json:"F_Fixed32_repeated,omitempty"` F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated,json=FFixed64Repeated" json:"F_Fixed64_repeated,omitempty"` F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated,json=FUint32Repeated" json:"F_Uint32_repeated,omitempty"` F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated,json=FUint64Repeated" json:"F_Uint64_repeated,omitempty"` F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated,json=FFloatRepeated" json:"F_Float_repeated,omitempty"` F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated,json=FDoubleRepeated" json:"F_Double_repeated,omitempty"` F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated,json=FStringRepeated" json:"F_String_repeated,omitempty"` F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated,json=FBytesRepeated" json:"F_Bytes_repeated,omitempty"` F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated,json=FSint32Repeated" json:"F_Sint32_repeated,omitempty"` F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated,json=FSint64Repeated" json:"F_Sint64_repeated,omitempty"` // Optional fields of all basic types F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional,json=FBoolOptional" json:"F_Bool_optional,omitempty"` F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional,json=FInt32Optional" json:"F_Int32_optional,omitempty"` F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional,json=FInt64Optional" json:"F_Int64_optional,omitempty"` F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional,json=FFixed32Optional" json:"F_Fixed32_optional,omitempty"` F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional,json=FFixed64Optional" json:"F_Fixed64_optional,omitempty"` F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional,json=FUint32Optional" json:"F_Uint32_optional,omitempty"` F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional,json=FUint64Optional" json:"F_Uint64_optional,omitempty"` F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional,json=FFloatOptional" json:"F_Float_optional,omitempty"` F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional,json=FDoubleOptional" json:"F_Double_optional,omitempty"` F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional,json=FStringOptional" json:"F_String_optional,omitempty"` F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional,json=FBytesOptional" json:"F_Bytes_optional,omitempty"` F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional,json=FSint32Optional" json:"F_Sint32_optional,omitempty"` F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional,json=FSint64Optional" json:"F_Sint64_optional,omitempty"` // Default-valued fields of all basic types F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,json=FBoolDefaulted,def=1" json:"F_Bool_defaulted,omitempty"` F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,json=FInt32Defaulted,def=32" json:"F_Int32_defaulted,omitempty"` F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,json=FInt64Defaulted,def=64" json:"F_Int64_defaulted,omitempty"` F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,json=FFixed32Defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,json=FFixed64Defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,json=FUint32Defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,json=FUint64Defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,json=FFloatDefaulted,def=314159" json:"F_Float_defaulted,omitempty"` F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,json=FDoubleDefaulted,def=271828" json:"F_Double_defaulted,omitempty"` F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,json=FStringDefaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,json=FBytesDefaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,json=FSint32Defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,json=FSint64Defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` // Packed repeated fields (no string or bytes). F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed,json=FBoolRepeatedPacked" json:"F_Bool_repeated_packed,omitempty"` F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed,json=FInt32RepeatedPacked" json:"F_Int32_repeated_packed,omitempty"` F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed,json=FInt64RepeatedPacked" json:"F_Int64_repeated_packed,omitempty"` F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed,json=FFixed32RepeatedPacked" json:"F_Fixed32_repeated_packed,omitempty"` F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed,json=FFixed64RepeatedPacked" json:"F_Fixed64_repeated_packed,omitempty"` F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed,json=FUint32RepeatedPacked" json:"F_Uint32_repeated_packed,omitempty"` F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed,json=FUint64RepeatedPacked" json:"F_Uint64_repeated_packed,omitempty"` F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed,json=FFloatRepeatedPacked" json:"F_Float_repeated_packed,omitempty"` F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed,json=FDoubleRepeatedPacked" json:"F_Double_repeated_packed,omitempty"` F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed,json=FSint32RepeatedPacked" json:"F_Sint32_repeated_packed,omitempty"` F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed,json=FSint64RepeatedPacked" json:"F_Sint64_repeated_packed,omitempty"` Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup,json=requiredgroup" json:"requiredgroup,omitempty"` Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup,json=repeatedgroup" json:"repeatedgroup,omitempty"` Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTest) Reset() { *m = GoTest{} } func (m *GoTest) String() string { return proto.CompactTextString(m) } func (*GoTest) ProtoMessage() {} func (*GoTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } const Default_GoTest_F_BoolDefaulted bool = true const Default_GoTest_F_Int32Defaulted int32 = 32 const Default_GoTest_F_Int64Defaulted int64 = 64 const Default_GoTest_F_Fixed32Defaulted uint32 = 320 const Default_GoTest_F_Fixed64Defaulted uint64 = 640 const Default_GoTest_F_Uint32Defaulted uint32 = 3200 const Default_GoTest_F_Uint64Defaulted uint64 = 6400 const Default_GoTest_F_FloatDefaulted float32 = 314159 const Default_GoTest_F_DoubleDefaulted float64 = 271828 const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") const Default_GoTest_F_Sint32Defaulted int32 = -32 const Default_GoTest_F_Sint64Defaulted int64 = -64 func (m *GoTest) GetKind() GoTest_KIND { if m != nil && m.Kind != nil { return *m.Kind } return GoTest_VOID } func (m *GoTest) GetTable() string { if m != nil && m.Table != nil { return *m.Table } return "" } func (m *GoTest) GetParam() int32 { if m != nil && m.Param != nil { return *m.Param } return 0 } func (m *GoTest) GetRequiredField() *GoTestField { if m != nil { return m.RequiredField } return nil } func (m *GoTest) GetRepeatedField() []*GoTestField { if m != nil { return m.RepeatedField } return nil } func (m *GoTest) GetOptionalField() *GoTestField { if m != nil { return m.OptionalField } return nil } func (m *GoTest) GetF_BoolRequired() bool { if m != nil && m.F_BoolRequired != nil { return *m.F_BoolRequired } return false } func (m *GoTest) GetF_Int32Required() int32 { if m != nil && m.F_Int32Required != nil { return *m.F_Int32Required } return 0 } func (m *GoTest) GetF_Int64Required() int64 { if m != nil && m.F_Int64Required != nil { return *m.F_Int64Required } return 0 } func (m *GoTest) GetF_Fixed32Required() uint32 { if m != nil && m.F_Fixed32Required != nil { return *m.F_Fixed32Required } return 0 } func (m *GoTest) GetF_Fixed64Required() uint64 { if m != nil && m.F_Fixed64Required != nil { return *m.F_Fixed64Required } return 0 } func (m *GoTest) GetF_Uint32Required() uint32 { if m != nil && m.F_Uint32Required != nil { return *m.F_Uint32Required } return 0 } func (m *GoTest) GetF_Uint64Required() uint64 { if m != nil && m.F_Uint64Required != nil { return *m.F_Uint64Required } return 0 } func (m *GoTest) GetF_FloatRequired() float32 { if m != nil && m.F_FloatRequired != nil { return *m.F_FloatRequired } return 0 } func (m *GoTest) GetF_DoubleRequired() float64 { if m != nil && m.F_DoubleRequired != nil { return *m.F_DoubleRequired } return 0 } func (m *GoTest) GetF_StringRequired() string { if m != nil && m.F_StringRequired != nil { return *m.F_StringRequired } return "" } func (m *GoTest) GetF_BytesRequired() []byte { if m != nil { return m.F_BytesRequired } return nil } func (m *GoTest) GetF_Sint32Required() int32 { if m != nil && m.F_Sint32Required != nil { return *m.F_Sint32Required } return 0 } func (m *GoTest) GetF_Sint64Required() int64 { if m != nil && m.F_Sint64Required != nil { return *m.F_Sint64Required } return 0 } func (m *GoTest) GetF_BoolRepeated() []bool { if m != nil { return m.F_BoolRepeated } return nil } func (m *GoTest) GetF_Int32Repeated() []int32 { if m != nil { return m.F_Int32Repeated } return nil } func (m *GoTest) GetF_Int64Repeated() []int64 { if m != nil { return m.F_Int64Repeated } return nil } func (m *GoTest) GetF_Fixed32Repeated() []uint32 { if m != nil { return m.F_Fixed32Repeated } return nil } func (m *GoTest) GetF_Fixed64Repeated() []uint64 { if m != nil { return m.F_Fixed64Repeated } return nil } func (m *GoTest) GetF_Uint32Repeated() []uint32 { if m != nil { return m.F_Uint32Repeated } return nil } func (m *GoTest) GetF_Uint64Repeated() []uint64 { if m != nil { return m.F_Uint64Repeated } return nil } func (m *GoTest) GetF_FloatRepeated() []float32 { if m != nil { return m.F_FloatRepeated } return nil } func (m *GoTest) GetF_DoubleRepeated() []float64 { if m != nil { return m.F_DoubleRepeated } return nil } func (m *GoTest) GetF_StringRepeated() []string { if m != nil { return m.F_StringRepeated } return nil } func (m *GoTest) GetF_BytesRepeated() [][]byte { if m != nil { return m.F_BytesRepeated } return nil } func (m *GoTest) GetF_Sint32Repeated() []int32 { if m != nil { return m.F_Sint32Repeated } return nil } func (m *GoTest) GetF_Sint64Repeated() []int64 { if m != nil { return m.F_Sint64Repeated } return nil } func (m *GoTest) GetF_BoolOptional() bool { if m != nil && m.F_BoolOptional != nil { return *m.F_BoolOptional } return false } func (m *GoTest) GetF_Int32Optional() int32 { if m != nil && m.F_Int32Optional != nil { return *m.F_Int32Optional } return 0 } func (m *GoTest) GetF_Int64Optional() int64 { if m != nil && m.F_Int64Optional != nil { return *m.F_Int64Optional } return 0 } func (m *GoTest) GetF_Fixed32Optional() uint32 { if m != nil && m.F_Fixed32Optional != nil { return *m.F_Fixed32Optional } return 0 } func (m *GoTest) GetF_Fixed64Optional() uint64 { if m != nil && m.F_Fixed64Optional != nil { return *m.F_Fixed64Optional } return 0 } func (m *GoTest) GetF_Uint32Optional() uint32 { if m != nil && m.F_Uint32Optional != nil { return *m.F_Uint32Optional } return 0 } func (m *GoTest) GetF_Uint64Optional() uint64 { if m != nil && m.F_Uint64Optional != nil { return *m.F_Uint64Optional } return 0 } func (m *GoTest) GetF_FloatOptional() float32 { if m != nil && m.F_FloatOptional != nil { return *m.F_FloatOptional } return 0 } func (m *GoTest) GetF_DoubleOptional() float64 { if m != nil && m.F_DoubleOptional != nil { return *m.F_DoubleOptional } return 0 } func (m *GoTest) GetF_StringOptional() string { if m != nil && m.F_StringOptional != nil { return *m.F_StringOptional } return "" } func (m *GoTest) GetF_BytesOptional() []byte { if m != nil { return m.F_BytesOptional } return nil } func (m *GoTest) GetF_Sint32Optional() int32 { if m != nil && m.F_Sint32Optional != nil { return *m.F_Sint32Optional } return 0 } func (m *GoTest) GetF_Sint64Optional() int64 { if m != nil && m.F_Sint64Optional != nil { return *m.F_Sint64Optional } return 0 } func (m *GoTest) GetF_BoolDefaulted() bool { if m != nil && m.F_BoolDefaulted != nil { return *m.F_BoolDefaulted } return Default_GoTest_F_BoolDefaulted } func (m *GoTest) GetF_Int32Defaulted() int32 { if m != nil && m.F_Int32Defaulted != nil { return *m.F_Int32Defaulted } return Default_GoTest_F_Int32Defaulted } func (m *GoTest) GetF_Int64Defaulted() int64 { if m != nil && m.F_Int64Defaulted != nil { return *m.F_Int64Defaulted } return Default_GoTest_F_Int64Defaulted } func (m *GoTest) GetF_Fixed32Defaulted() uint32 { if m != nil && m.F_Fixed32Defaulted != nil { return *m.F_Fixed32Defaulted } return Default_GoTest_F_Fixed32Defaulted } func (m *GoTest) GetF_Fixed64Defaulted() uint64 { if m != nil && m.F_Fixed64Defaulted != nil { return *m.F_Fixed64Defaulted } return Default_GoTest_F_Fixed64Defaulted } func (m *GoTest) GetF_Uint32Defaulted() uint32 { if m != nil && m.F_Uint32Defaulted != nil { return *m.F_Uint32Defaulted } return Default_GoTest_F_Uint32Defaulted } func (m *GoTest) GetF_Uint64Defaulted() uint64 { if m != nil && m.F_Uint64Defaulted != nil { return *m.F_Uint64Defaulted } return Default_GoTest_F_Uint64Defaulted } func (m *GoTest) GetF_FloatDefaulted() float32 { if m != nil && m.F_FloatDefaulted != nil { return *m.F_FloatDefaulted } return Default_GoTest_F_FloatDefaulted } func (m *GoTest) GetF_DoubleDefaulted() float64 { if m != nil && m.F_DoubleDefaulted != nil { return *m.F_DoubleDefaulted } return Default_GoTest_F_DoubleDefaulted } func (m *GoTest) GetF_StringDefaulted() string { if m != nil && m.F_StringDefaulted != nil { return *m.F_StringDefaulted } return Default_GoTest_F_StringDefaulted } func (m *GoTest) GetF_BytesDefaulted() []byte { if m != nil && m.F_BytesDefaulted != nil { return m.F_BytesDefaulted } return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) } func (m *GoTest) GetF_Sint32Defaulted() int32 { if m != nil && m.F_Sint32Defaulted != nil { return *m.F_Sint32Defaulted } return Default_GoTest_F_Sint32Defaulted } func (m *GoTest) GetF_Sint64Defaulted() int64 { if m != nil && m.F_Sint64Defaulted != nil { return *m.F_Sint64Defaulted } return Default_GoTest_F_Sint64Defaulted } func (m *GoTest) GetF_BoolRepeatedPacked() []bool { if m != nil { return m.F_BoolRepeatedPacked } return nil } func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { if m != nil { return m.F_Int32RepeatedPacked } return nil } func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { if m != nil { return m.F_Int64RepeatedPacked } return nil } func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { if m != nil { return m.F_Fixed32RepeatedPacked } return nil } func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { if m != nil { return m.F_Fixed64RepeatedPacked } return nil } func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { if m != nil { return m.F_Uint32RepeatedPacked } return nil } func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { if m != nil { return m.F_Uint64RepeatedPacked } return nil } func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { if m != nil { return m.F_FloatRepeatedPacked } return nil } func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { if m != nil { return m.F_DoubleRepeatedPacked } return nil } func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { if m != nil { return m.F_Sint32RepeatedPacked } return nil } func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { if m != nil { return m.F_Sint64RepeatedPacked } return nil } func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { if m != nil { return m.Requiredgroup } return nil } func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { if m != nil { return m.Repeatedgroup } return nil } func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { if m != nil { return m.Optionalgroup } return nil } // Required, repeated, and optional groups. type GoTest_RequiredGroup struct { RequiredField *string `protobuf:"bytes,71,req,name=RequiredField" json:"RequiredField,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) } func (*GoTest_RequiredGroup) ProtoMessage() {} func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } func (m *GoTest_RequiredGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } type GoTest_RepeatedGroup struct { RequiredField *string `protobuf:"bytes,81,req,name=RequiredField" json:"RequiredField,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) } func (*GoTest_RepeatedGroup) ProtoMessage() {} func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 1} } func (m *GoTest_RepeatedGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } type GoTest_OptionalGroup struct { RequiredField *string `protobuf:"bytes,91,req,name=RequiredField" json:"RequiredField,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) } func (*GoTest_OptionalGroup) ProtoMessage() {} func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 2} } func (m *GoTest_OptionalGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } // For testing a group containing a required field. type GoTestRequiredGroupField struct { Group *GoTestRequiredGroupField_Group `protobuf:"group,1,req,name=Group,json=group" json:"group,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTestRequiredGroupField) Reset() { *m = GoTestRequiredGroupField{} } func (m *GoTestRequiredGroupField) String() string { return proto.CompactTextString(m) } func (*GoTestRequiredGroupField) ProtoMessage() {} func (*GoTestRequiredGroupField) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *GoTestRequiredGroupField) GetGroup() *GoTestRequiredGroupField_Group { if m != nil { return m.Group } return nil } type GoTestRequiredGroupField_Group struct { Field *int32 `protobuf:"varint,2,req,name=Field" json:"Field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTestRequiredGroupField_Group) Reset() { *m = GoTestRequiredGroupField_Group{} } func (m *GoTestRequiredGroupField_Group) String() string { return proto.CompactTextString(m) } func (*GoTestRequiredGroupField_Group) ProtoMessage() {} func (*GoTestRequiredGroupField_Group) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3, 0} } func (m *GoTestRequiredGroupField_Group) GetField() int32 { if m != nil && m.Field != nil { return *m.Field } return 0 } // For testing skipping of unrecognized fields. // Numbers are all big, larger than tag numbers in GoTestField, // the message used in the corresponding test. type GoSkipTest struct { SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32,json=skipInt32" json:"skip_int32,omitempty"` SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32,json=skipFixed32" json:"skip_fixed32,omitempty"` SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64,json=skipFixed64" json:"skip_fixed64,omitempty"` SkipString *string `protobuf:"bytes,14,req,name=skip_string,json=skipString" json:"skip_string,omitempty"` Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup,json=skipgroup" json:"skipgroup,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } func (*GoSkipTest) ProtoMessage() {} func (*GoSkipTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *GoSkipTest) GetSkipInt32() int32 { if m != nil && m.SkipInt32 != nil { return *m.SkipInt32 } return 0 } func (m *GoSkipTest) GetSkipFixed32() uint32 { if m != nil && m.SkipFixed32 != nil { return *m.SkipFixed32 } return 0 } func (m *GoSkipTest) GetSkipFixed64() uint64 { if m != nil && m.SkipFixed64 != nil { return *m.SkipFixed64 } return 0 } func (m *GoSkipTest) GetSkipString() string { if m != nil && m.SkipString != nil { return *m.SkipString } return "" } func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { if m != nil { return m.Skipgroup } return nil } type GoSkipTest_SkipGroup struct { GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32,json=groupInt32" json:"group_int32,omitempty"` GroupString *string `protobuf:"bytes,17,req,name=group_string,json=groupString" json:"group_string,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) } func (*GoSkipTest_SkipGroup) ProtoMessage() {} func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4, 0} } func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { if m != nil && m.GroupInt32 != nil { return *m.GroupInt32 } return 0 } func (m *GoSkipTest_SkipGroup) GetGroupString() string { if m != nil && m.GroupString != nil { return *m.GroupString } return "" } // For testing packed/non-packed decoder switching. // A serialized instance of one should be deserializable as the other. type NonPackedTest struct { A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } func (*NonPackedTest) ProtoMessage() {} func (*NonPackedTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (m *NonPackedTest) GetA() []int32 { if m != nil { return m.A } return nil } type PackedTest struct { B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *PackedTest) Reset() { *m = PackedTest{} } func (m *PackedTest) String() string { return proto.CompactTextString(m) } func (*PackedTest) ProtoMessage() {} func (*PackedTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (m *PackedTest) GetB() []int32 { if m != nil { return m.B } return nil } type MaxTag struct { // Maximum possible tag number. LastField *string `protobuf:"bytes,536870911,opt,name=last_field,json=lastField" json:"last_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MaxTag) Reset() { *m = MaxTag{} } func (m *MaxTag) String() string { return proto.CompactTextString(m) } func (*MaxTag) ProtoMessage() {} func (*MaxTag) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (m *MaxTag) GetLastField() string { if m != nil && m.LastField != nil { return *m.LastField } return "" } type OldMessage struct { Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OldMessage) Reset() { *m = OldMessage{} } func (m *OldMessage) String() string { return proto.CompactTextString(m) } func (*OldMessage) ProtoMessage() {} func (*OldMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } func (m *OldMessage) GetNested() *OldMessage_Nested { if m != nil { return m.Nested } return nil } func (m *OldMessage) GetNum() int32 { if m != nil && m.Num != nil { return *m.Num } return 0 } type OldMessage_Nested struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } func (*OldMessage_Nested) ProtoMessage() {} func (*OldMessage_Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8, 0} } func (m *OldMessage_Nested) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } // NewMessage is wire compatible with OldMessage; // imagine it as a future version. type NewMessage struct { Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` // This is an int32 in OldMessage. Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *NewMessage) Reset() { *m = NewMessage{} } func (m *NewMessage) String() string { return proto.CompactTextString(m) } func (*NewMessage) ProtoMessage() {} func (*NewMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } func (m *NewMessage) GetNested() *NewMessage_Nested { if m != nil { return m.Nested } return nil } func (m *NewMessage) GetNum() int64 { if m != nil && m.Num != nil { return *m.Num } return 0 } type NewMessage_Nested struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` FoodGroup *string `protobuf:"bytes,2,opt,name=food_group,json=foodGroup" json:"food_group,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } func (*NewMessage_Nested) ProtoMessage() {} func (*NewMessage_Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9, 0} } func (m *NewMessage_Nested) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *NewMessage_Nested) GetFoodGroup() string { if m != nil && m.FoodGroup != nil { return *m.FoodGroup } return "" } type InnerMessage struct { Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *InnerMessage) Reset() { *m = InnerMessage{} } func (m *InnerMessage) String() string { return proto.CompactTextString(m) } func (*InnerMessage) ProtoMessage() {} func (*InnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } const Default_InnerMessage_Port int32 = 4000 func (m *InnerMessage) GetHost() string { if m != nil && m.Host != nil { return *m.Host } return "" } func (m *InnerMessage) GetPort() int32 { if m != nil && m.Port != nil { return *m.Port } return Default_InnerMessage_Port } func (m *InnerMessage) GetConnected() bool { if m != nil && m.Connected != nil { return *m.Connected } return false } type OtherMessage struct { Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OtherMessage) Reset() { *m = OtherMessage{} } func (m *OtherMessage) String() string { return proto.CompactTextString(m) } func (*OtherMessage) ProtoMessage() {} func (*OtherMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } var extRange_OtherMessage = []proto.ExtensionRange{ {100, 536870911}, } func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OtherMessage } func (m *OtherMessage) GetKey() int64 { if m != nil && m.Key != nil { return *m.Key } return 0 } func (m *OtherMessage) GetValue() []byte { if m != nil { return m.Value } return nil } func (m *OtherMessage) GetWeight() float32 { if m != nil && m.Weight != nil { return *m.Weight } return 0 } func (m *OtherMessage) GetInner() *InnerMessage { if m != nil { return m.Inner } return nil } type RequiredInnerMessage struct { LeoFinallyWonAnOscar *InnerMessage `protobuf:"bytes,1,req,name=leo_finally_won_an_oscar,json=leoFinallyWonAnOscar" json:"leo_finally_won_an_oscar,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *RequiredInnerMessage) Reset() { *m = RequiredInnerMessage{} } func (m *RequiredInnerMessage) String() string { return proto.CompactTextString(m) } func (*RequiredInnerMessage) ProtoMessage() {} func (*RequiredInnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} } func (m *RequiredInnerMessage) GetLeoFinallyWonAnOscar() *InnerMessage { if m != nil { return m.LeoFinallyWonAnOscar } return nil } type MyMessage struct { Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` WeMustGoDeeper *RequiredInnerMessage `protobuf:"bytes,13,opt,name=we_must_go_deeper,json=weMustGoDeeper" json:"we_must_go_deeper,omitempty"` RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner,json=repInner" json:"rep_inner,omitempty"` Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` // This field becomes [][]byte in the generated code. RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes,json=repBytes" json:"rep_bytes,omitempty"` Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *MyMessage) Reset() { *m = MyMessage{} } func (m *MyMessage) String() string { return proto.CompactTextString(m) } func (*MyMessage) ProtoMessage() {} func (*MyMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} } var extRange_MyMessage = []proto.ExtensionRange{ {100, 536870911}, } func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MyMessage } func (m *MyMessage) GetCount() int32 { if m != nil && m.Count != nil { return *m.Count } return 0 } func (m *MyMessage) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *MyMessage) GetQuote() string { if m != nil && m.Quote != nil { return *m.Quote } return "" } func (m *MyMessage) GetPet() []string { if m != nil { return m.Pet } return nil } func (m *MyMessage) GetInner() *InnerMessage { if m != nil { return m.Inner } return nil } func (m *MyMessage) GetOthers() []*OtherMessage { if m != nil { return m.Others } return nil } func (m *MyMessage) GetWeMustGoDeeper() *RequiredInnerMessage { if m != nil { return m.WeMustGoDeeper } return nil } func (m *MyMessage) GetRepInner() []*InnerMessage { if m != nil { return m.RepInner } return nil } func (m *MyMessage) GetBikeshed() MyMessage_Color { if m != nil && m.Bikeshed != nil { return *m.Bikeshed } return MyMessage_RED } func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { if m != nil { return m.Somegroup } return nil } func (m *MyMessage) GetRepBytes() [][]byte { if m != nil { return m.RepBytes } return nil } func (m *MyMessage) GetBigfloat() float64 { if m != nil && m.Bigfloat != nil { return *m.Bigfloat } return 0 } type MyMessage_SomeGroup struct { GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) } func (*MyMessage_SomeGroup) ProtoMessage() {} func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13, 0} } func (m *MyMessage_SomeGroup) GetGroupField() int32 { if m != nil && m.GroupField != nil { return *m.GroupField } return 0 } type Ext struct { Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Ext) Reset() { *m = Ext{} } func (m *Ext) String() string { return proto.CompactTextString(m) } func (*Ext) ProtoMessage() {} func (*Ext) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} } func (m *Ext) GetData() string { if m != nil && m.Data != nil { return *m.Data } return "" } var E_Ext_More = &proto.ExtensionDesc{ ExtendedType: (*MyMessage)(nil), ExtensionType: (*Ext)(nil), Field: 103, Name: "testdata.Ext.more", Tag: "bytes,103,opt,name=more", Filename: "test.proto", } var E_Ext_Text = &proto.ExtensionDesc{ ExtendedType: (*MyMessage)(nil), ExtensionType: (*string)(nil), Field: 104, Name: "testdata.Ext.text", Tag: "bytes,104,opt,name=text", Filename: "test.proto", } var E_Ext_Number = &proto.ExtensionDesc{ ExtendedType: (*MyMessage)(nil), ExtensionType: (*int32)(nil), Field: 105, Name: "testdata.Ext.number", Tag: "varint,105,opt,name=number", Filename: "test.proto", } type ComplexExtension struct { First *int32 `protobuf:"varint,1,opt,name=first" json:"first,omitempty"` Second *int32 `protobuf:"varint,2,opt,name=second" json:"second,omitempty"` Third []int32 `protobuf:"varint,3,rep,name=third" json:"third,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *ComplexExtension) Reset() { *m = ComplexExtension{} } func (m *ComplexExtension) String() string { return proto.CompactTextString(m) } func (*ComplexExtension) ProtoMessage() {} func (*ComplexExtension) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} } func (m *ComplexExtension) GetFirst() int32 { if m != nil && m.First != nil { return *m.First } return 0 } func (m *ComplexExtension) GetSecond() int32 { if m != nil && m.Second != nil { return *m.Second } return 0 } func (m *ComplexExtension) GetThird() []int32 { if m != nil { return m.Third } return nil } type DefaultsMessage struct { proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} } func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) } func (*DefaultsMessage) ProtoMessage() {} func (*DefaultsMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} } var extRange_DefaultsMessage = []proto.ExtensionRange{ {100, 536870911}, } func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_DefaultsMessage } type MyMessageSet struct { proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *MyMessageSet) Reset() { *m = MyMessageSet{} } func (m *MyMessageSet) String() string { return proto.CompactTextString(m) } func (*MyMessageSet) ProtoMessage() {} func (*MyMessageSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} } func (m *MyMessageSet) Marshal() ([]byte, error) { return proto.MarshalMessageSet(&m.XXX_InternalExtensions) } func (m *MyMessageSet) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions) } func (m *MyMessageSet) MarshalJSON() ([]byte, error) { return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) } func (m *MyMessageSet) UnmarshalJSON(buf []byte) error { return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) } // ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*MyMessageSet)(nil) var _ proto.Unmarshaler = (*MyMessageSet)(nil) var extRange_MyMessageSet = []proto.ExtensionRange{ {100, 2147483646}, } func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MyMessageSet } type Empty struct { XXX_unrecognized []byte `json:"-"` } func (m *Empty) Reset() { *m = Empty{} } func (m *Empty) String() string { return proto.CompactTextString(m) } func (*Empty) ProtoMessage() {} func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} } type MessageList struct { Message []*MessageList_Message `protobuf:"group,1,rep,name=Message,json=message" json:"message,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MessageList) Reset() { *m = MessageList{} } func (m *MessageList) String() string { return proto.CompactTextString(m) } func (*MessageList) ProtoMessage() {} func (*MessageList) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} } func (m *MessageList) GetMessage() []*MessageList_Message { if m != nil { return m.Message } return nil } type MessageList_Message struct { Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } func (m *MessageList_Message) String() string { return proto.CompactTextString(m) } func (*MessageList_Message) ProtoMessage() {} func (*MessageList_Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19, 0} } func (m *MessageList_Message) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *MessageList_Message) GetCount() int32 { if m != nil && m.Count != nil { return *m.Count } return 0 } type Strings struct { StringField *string `protobuf:"bytes,1,opt,name=string_field,json=stringField" json:"string_field,omitempty"` BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field,json=bytesField" json:"bytes_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Strings) Reset() { *m = Strings{} } func (m *Strings) String() string { return proto.CompactTextString(m) } func (*Strings) ProtoMessage() {} func (*Strings) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} } func (m *Strings) GetStringField() string { if m != nil && m.StringField != nil { return *m.StringField } return "" } func (m *Strings) GetBytesField() []byte { if m != nil { return m.BytesField } return nil } type Defaults struct { // Default-valued fields of all basic types. // Same as GoTest, but copied here to make testing easier. F_Bool *bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,def=1" json:"F_Bool,omitempty"` F_Int32 *int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,def=32" json:"F_Int32,omitempty"` F_Int64 *int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,def=64" json:"F_Int64,omitempty"` F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,def=320" json:"F_Fixed32,omitempty"` F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,def=640" json:"F_Fixed64,omitempty"` F_Uint32 *uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,def=3200" json:"F_Uint32,omitempty"` F_Uint64 *uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,def=6400" json:"F_Uint64,omitempty"` F_Float *float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,def=314159" json:"F_Float,omitempty"` F_Double *float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,def=271828" json:"F_Double,omitempty"` F_String *string `protobuf:"bytes,10,opt,name=F_String,json=FString,def=hello, \"world!\"\n" json:"F_String,omitempty"` F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,def=Bignose" json:"F_Bytes,omitempty"` F_Sint32 *int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,def=-32" json:"F_Sint32,omitempty"` F_Sint64 *int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,def=-64" json:"F_Sint64,omitempty"` F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` // More fields with crazy defaults. F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,json=FPinf,def=inf" json:"F_Pinf,omitempty"` F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,json=FNinf,def=-inf" json:"F_Ninf,omitempty"` F_Nan *float32 `protobuf:"fixed32,17,opt,name=F_Nan,json=FNan,def=nan" json:"F_Nan,omitempty"` // Sub-message. Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` // Redundant but explicit defaults. StrZero *string `protobuf:"bytes,19,opt,name=str_zero,json=strZero,def=" json:"str_zero,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Defaults) Reset() { *m = Defaults{} } func (m *Defaults) String() string { return proto.CompactTextString(m) } func (*Defaults) ProtoMessage() {} func (*Defaults) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{21} } const Default_Defaults_F_Bool bool = true const Default_Defaults_F_Int32 int32 = 32 const Default_Defaults_F_Int64 int64 = 64 const Default_Defaults_F_Fixed32 uint32 = 320 const Default_Defaults_F_Fixed64 uint64 = 640 const Default_Defaults_F_Uint32 uint32 = 3200 const Default_Defaults_F_Uint64 uint64 = 6400 const Default_Defaults_F_Float float32 = 314159 const Default_Defaults_F_Double float64 = 271828 const Default_Defaults_F_String string = "hello, \"world!\"\n" var Default_Defaults_F_Bytes []byte = []byte("Bignose") const Default_Defaults_F_Sint32 int32 = -32 const Default_Defaults_F_Sint64 int64 = -64 const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) var Default_Defaults_F_Nan float32 = float32(math.NaN()) func (m *Defaults) GetF_Bool() bool { if m != nil && m.F_Bool != nil { return *m.F_Bool } return Default_Defaults_F_Bool } func (m *Defaults) GetF_Int32() int32 { if m != nil && m.F_Int32 != nil { return *m.F_Int32 } return Default_Defaults_F_Int32 } func (m *Defaults) GetF_Int64() int64 { if m != nil && m.F_Int64 != nil { return *m.F_Int64 } return Default_Defaults_F_Int64 } func (m *Defaults) GetF_Fixed32() uint32 { if m != nil && m.F_Fixed32 != nil { return *m.F_Fixed32 } return Default_Defaults_F_Fixed32 } func (m *Defaults) GetF_Fixed64() uint64 { if m != nil && m.F_Fixed64 != nil { return *m.F_Fixed64 } return Default_Defaults_F_Fixed64 } func (m *Defaults) GetF_Uint32() uint32 { if m != nil && m.F_Uint32 != nil { return *m.F_Uint32 } return Default_Defaults_F_Uint32 } func (m *Defaults) GetF_Uint64() uint64 { if m != nil && m.F_Uint64 != nil { return *m.F_Uint64 } return Default_Defaults_F_Uint64 } func (m *Defaults) GetF_Float() float32 { if m != nil && m.F_Float != nil { return *m.F_Float } return Default_Defaults_F_Float } func (m *Defaults) GetF_Double() float64 { if m != nil && m.F_Double != nil { return *m.F_Double } return Default_Defaults_F_Double } func (m *Defaults) GetF_String() string { if m != nil && m.F_String != nil { return *m.F_String } return Default_Defaults_F_String } func (m *Defaults) GetF_Bytes() []byte { if m != nil && m.F_Bytes != nil { return m.F_Bytes } return append([]byte(nil), Default_Defaults_F_Bytes...) } func (m *Defaults) GetF_Sint32() int32 { if m != nil && m.F_Sint32 != nil { return *m.F_Sint32 } return Default_Defaults_F_Sint32 } func (m *Defaults) GetF_Sint64() int64 { if m != nil && m.F_Sint64 != nil { return *m.F_Sint64 } return Default_Defaults_F_Sint64 } func (m *Defaults) GetF_Enum() Defaults_Color { if m != nil && m.F_Enum != nil { return *m.F_Enum } return Default_Defaults_F_Enum } func (m *Defaults) GetF_Pinf() float32 { if m != nil && m.F_Pinf != nil { return *m.F_Pinf } return Default_Defaults_F_Pinf } func (m *Defaults) GetF_Ninf() float32 { if m != nil && m.F_Ninf != nil { return *m.F_Ninf } return Default_Defaults_F_Ninf } func (m *Defaults) GetF_Nan() float32 { if m != nil && m.F_Nan != nil { return *m.F_Nan } return Default_Defaults_F_Nan } func (m *Defaults) GetSub() *SubDefaults { if m != nil { return m.Sub } return nil } func (m *Defaults) GetStrZero() string { if m != nil && m.StrZero != nil { return *m.StrZero } return "" } type SubDefaults struct { N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SubDefaults) Reset() { *m = SubDefaults{} } func (m *SubDefaults) String() string { return proto.CompactTextString(m) } func (*SubDefaults) ProtoMessage() {} func (*SubDefaults) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{22} } const Default_SubDefaults_N int64 = 7 func (m *SubDefaults) GetN() int64 { if m != nil && m.N != nil { return *m.N } return Default_SubDefaults_N } type RepeatedEnum struct { Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } func (*RepeatedEnum) ProtoMessage() {} func (*RepeatedEnum) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{23} } func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { if m != nil { return m.Color } return nil } type MoreRepeated struct { Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed,json=boolsPacked" json:"bools_packed,omitempty"` Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed,json=intsPacked" json:"ints_packed,omitempty"` Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed,json=int64sPacked" json:"int64s_packed,omitempty"` Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } func (*MoreRepeated) ProtoMessage() {} func (*MoreRepeated) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24} } func (m *MoreRepeated) GetBools() []bool { if m != nil { return m.Bools } return nil } func (m *MoreRepeated) GetBoolsPacked() []bool { if m != nil { return m.BoolsPacked } return nil } func (m *MoreRepeated) GetInts() []int32 { if m != nil { return m.Ints } return nil } func (m *MoreRepeated) GetIntsPacked() []int32 { if m != nil { return m.IntsPacked } return nil } func (m *MoreRepeated) GetInt64SPacked() []int64 { if m != nil { return m.Int64SPacked } return nil } func (m *MoreRepeated) GetStrings() []string { if m != nil { return m.Strings } return nil } func (m *MoreRepeated) GetFixeds() []uint32 { if m != nil { return m.Fixeds } return nil } type GroupOld struct { G *GroupOld_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GroupOld) Reset() { *m = GroupOld{} } func (m *GroupOld) String() string { return proto.CompactTextString(m) } func (*GroupOld) ProtoMessage() {} func (*GroupOld) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25} } func (m *GroupOld) GetG() *GroupOld_G { if m != nil { return m.G } return nil } type GroupOld_G struct { X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } func (m *GroupOld_G) String() string { return proto.CompactTextString(m) } func (*GroupOld_G) ProtoMessage() {} func (*GroupOld_G) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25, 0} } func (m *GroupOld_G) GetX() int32 { if m != nil && m.X != nil { return *m.X } return 0 } type GroupNew struct { G *GroupNew_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GroupNew) Reset() { *m = GroupNew{} } func (m *GroupNew) String() string { return proto.CompactTextString(m) } func (*GroupNew) ProtoMessage() {} func (*GroupNew) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26} } func (m *GroupNew) GetG() *GroupNew_G { if m != nil { return m.G } return nil } type GroupNew_G struct { X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } func (m *GroupNew_G) String() string { return proto.CompactTextString(m) } func (*GroupNew_G) ProtoMessage() {} func (*GroupNew_G) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26, 0} } func (m *GroupNew_G) GetX() int32 { if m != nil && m.X != nil { return *m.X } return 0 } func (m *GroupNew_G) GetY() int32 { if m != nil && m.Y != nil { return *m.Y } return 0 } type FloatingPoint struct { F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` Exact *bool `protobuf:"varint,2,opt,name=exact" json:"exact,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FloatingPoint) Reset() { *m = FloatingPoint{} } func (m *FloatingPoint) String() string { return proto.CompactTextString(m) } func (*FloatingPoint) ProtoMessage() {} func (*FloatingPoint) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{27} } func (m *FloatingPoint) GetF() float64 { if m != nil && m.F != nil { return *m.F } return 0 } func (m *FloatingPoint) GetExact() bool { if m != nil && m.Exact != nil { return *m.Exact } return false } type MessageWithMap struct { NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str,json=strToStr" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` XXX_unrecognized []byte `json:"-"` } func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } func (*MessageWithMap) ProtoMessage() {} func (*MessageWithMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28} } func (m *MessageWithMap) GetNameMapping() map[int32]string { if m != nil { return m.NameMapping } return nil } func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint { if m != nil { return m.MsgMapping } return nil } func (m *MessageWithMap) GetByteMapping() map[bool][]byte { if m != nil { return m.ByteMapping } return nil } func (m *MessageWithMap) GetStrToStr() map[string]string { if m != nil { return m.StrToStr } return nil } type Oneof struct { // Types that are valid to be assigned to Union: // *Oneof_F_Bool // *Oneof_F_Int32 // *Oneof_F_Int64 // *Oneof_F_Fixed32 // *Oneof_F_Fixed64 // *Oneof_F_Uint32 // *Oneof_F_Uint64 // *Oneof_F_Float // *Oneof_F_Double // *Oneof_F_String // *Oneof_F_Bytes // *Oneof_F_Sint32 // *Oneof_F_Sint64 // *Oneof_F_Enum // *Oneof_F_Message // *Oneof_FGroup // *Oneof_F_Largest_Tag Union isOneof_Union `protobuf_oneof:"union"` // Types that are valid to be assigned to Tormato: // *Oneof_Value Tormato isOneof_Tormato `protobuf_oneof:"tormato"` XXX_unrecognized []byte `json:"-"` } func (m *Oneof) Reset() { *m = Oneof{} } func (m *Oneof) String() string { return proto.CompactTextString(m) } func (*Oneof) ProtoMessage() {} func (*Oneof) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29} } type isOneof_Union interface { isOneof_Union() } type isOneof_Tormato interface { isOneof_Tormato() } type Oneof_F_Bool struct { F_Bool bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,oneof"` } type Oneof_F_Int32 struct { F_Int32 int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,oneof"` } type Oneof_F_Int64 struct { F_Int64 int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,oneof"` } type Oneof_F_Fixed32 struct { F_Fixed32 uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,oneof"` } type Oneof_F_Fixed64 struct { F_Fixed64 uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,oneof"` } type Oneof_F_Uint32 struct { F_Uint32 uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,oneof"` } type Oneof_F_Uint64 struct { F_Uint64 uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,oneof"` } type Oneof_F_Float struct { F_Float float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,oneof"` } type Oneof_F_Double struct { F_Double float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,oneof"` } type Oneof_F_String struct { F_String string `protobuf:"bytes,10,opt,name=F_String,json=FString,oneof"` } type Oneof_F_Bytes struct { F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,oneof"` } type Oneof_F_Sint32 struct { F_Sint32 int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,oneof"` } type Oneof_F_Sint64 struct { F_Sint64 int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,oneof"` } type Oneof_F_Enum struct { F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=testdata.MyMessage_Color,oneof"` } type Oneof_F_Message struct { F_Message *GoTestField `protobuf:"bytes,15,opt,name=F_Message,json=FMessage,oneof"` } type Oneof_FGroup struct { FGroup *Oneof_F_Group `protobuf:"group,16,opt,name=F_Group,json=fGroup,oneof"` } type Oneof_F_Largest_Tag struct { F_Largest_Tag int32 `protobuf:"varint,536870911,opt,name=F_Largest_Tag,json=FLargestTag,oneof"` } type Oneof_Value struct { Value int32 `protobuf:"varint,100,opt,name=value,oneof"` } func (*Oneof_F_Bool) isOneof_Union() {} func (*Oneof_F_Int32) isOneof_Union() {} func (*Oneof_F_Int64) isOneof_Union() {} func (*Oneof_F_Fixed32) isOneof_Union() {} func (*Oneof_F_Fixed64) isOneof_Union() {} func (*Oneof_F_Uint32) isOneof_Union() {} func (*Oneof_F_Uint64) isOneof_Union() {} func (*Oneof_F_Float) isOneof_Union() {} func (*Oneof_F_Double) isOneof_Union() {} func (*Oneof_F_String) isOneof_Union() {} func (*Oneof_F_Bytes) isOneof_Union() {} func (*Oneof_F_Sint32) isOneof_Union() {} func (*Oneof_F_Sint64) isOneof_Union() {} func (*Oneof_F_Enum) isOneof_Union() {} func (*Oneof_F_Message) isOneof_Union() {} func (*Oneof_FGroup) isOneof_Union() {} func (*Oneof_F_Largest_Tag) isOneof_Union() {} func (*Oneof_Value) isOneof_Tormato() {} func (m *Oneof) GetUnion() isOneof_Union { if m != nil { return m.Union } return nil } func (m *Oneof) GetTormato() isOneof_Tormato { if m != nil { return m.Tormato } return nil } func (m *Oneof) GetF_Bool() bool { if x, ok := m.GetUnion().(*Oneof_F_Bool); ok { return x.F_Bool } return false } func (m *Oneof) GetF_Int32() int32 { if x, ok := m.GetUnion().(*Oneof_F_Int32); ok { return x.F_Int32 } return 0 } func (m *Oneof) GetF_Int64() int64 { if x, ok := m.GetUnion().(*Oneof_F_Int64); ok { return x.F_Int64 } return 0 } func (m *Oneof) GetF_Fixed32() uint32 { if x, ok := m.GetUnion().(*Oneof_F_Fixed32); ok { return x.F_Fixed32 } return 0 } func (m *Oneof) GetF_Fixed64() uint64 { if x, ok := m.GetUnion().(*Oneof_F_Fixed64); ok { return x.F_Fixed64 } return 0 } func (m *Oneof) GetF_Uint32() uint32 { if x, ok := m.GetUnion().(*Oneof_F_Uint32); ok { return x.F_Uint32 } return 0 } func (m *Oneof) GetF_Uint64() uint64 { if x, ok := m.GetUnion().(*Oneof_F_Uint64); ok { return x.F_Uint64 } return 0 } func (m *Oneof) GetF_Float() float32 { if x, ok := m.GetUnion().(*Oneof_F_Float); ok { return x.F_Float } return 0 } func (m *Oneof) GetF_Double() float64 { if x, ok := m.GetUnion().(*Oneof_F_Double); ok { return x.F_Double } return 0 } func (m *Oneof) GetF_String() string { if x, ok := m.GetUnion().(*Oneof_F_String); ok { return x.F_String } return "" } func (m *Oneof) GetF_Bytes() []byte { if x, ok := m.GetUnion().(*Oneof_F_Bytes); ok { return x.F_Bytes } return nil } func (m *Oneof) GetF_Sint32() int32 { if x, ok := m.GetUnion().(*Oneof_F_Sint32); ok { return x.F_Sint32 } return 0 } func (m *Oneof) GetF_Sint64() int64 { if x, ok := m.GetUnion().(*Oneof_F_Sint64); ok { return x.F_Sint64 } return 0 } func (m *Oneof) GetF_Enum() MyMessage_Color { if x, ok := m.GetUnion().(*Oneof_F_Enum); ok { return x.F_Enum } return MyMessage_RED } func (m *Oneof) GetF_Message() *GoTestField { if x, ok := m.GetUnion().(*Oneof_F_Message); ok { return x.F_Message } return nil } func (m *Oneof) GetFGroup() *Oneof_F_Group { if x, ok := m.GetUnion().(*Oneof_FGroup); ok { return x.FGroup } return nil } func (m *Oneof) GetF_Largest_Tag() int32 { if x, ok := m.GetUnion().(*Oneof_F_Largest_Tag); ok { return x.F_Largest_Tag } return 0 } func (m *Oneof) GetValue() int32 { if x, ok := m.GetTormato().(*Oneof_Value); ok { return x.Value } return 0 } // XXX_OneofFuncs is for the internal use of the proto package. func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Oneof_OneofMarshaler, _Oneof_OneofUnmarshaler, _Oneof_OneofSizer, []interface{}{ (*Oneof_F_Bool)(nil), (*Oneof_F_Int32)(nil), (*Oneof_F_Int64)(nil), (*Oneof_F_Fixed32)(nil), (*Oneof_F_Fixed64)(nil), (*Oneof_F_Uint32)(nil), (*Oneof_F_Uint64)(nil), (*Oneof_F_Float)(nil), (*Oneof_F_Double)(nil), (*Oneof_F_String)(nil), (*Oneof_F_Bytes)(nil), (*Oneof_F_Sint32)(nil), (*Oneof_F_Sint64)(nil), (*Oneof_F_Enum)(nil), (*Oneof_F_Message)(nil), (*Oneof_FGroup)(nil), (*Oneof_F_Largest_Tag)(nil), (*Oneof_Value)(nil), } } func _Oneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Oneof) // union switch x := m.Union.(type) { case *Oneof_F_Bool: t := uint64(0) if x.F_Bool { t = 1 } b.EncodeVarint(1<<3 | proto.WireVarint) b.EncodeVarint(t) case *Oneof_F_Int32: b.EncodeVarint(2<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Int32)) case *Oneof_F_Int64: b.EncodeVarint(3<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Int64)) case *Oneof_F_Fixed32: b.EncodeVarint(4<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(x.F_Fixed32)) case *Oneof_F_Fixed64: b.EncodeVarint(5<<3 | proto.WireFixed64) b.EncodeFixed64(uint64(x.F_Fixed64)) case *Oneof_F_Uint32: b.EncodeVarint(6<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Uint32)) case *Oneof_F_Uint64: b.EncodeVarint(7<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Uint64)) case *Oneof_F_Float: b.EncodeVarint(8<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.F_Float))) case *Oneof_F_Double: b.EncodeVarint(9<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.F_Double)) case *Oneof_F_String: b.EncodeVarint(10<<3 | proto.WireBytes) b.EncodeStringBytes(x.F_String) case *Oneof_F_Bytes: b.EncodeVarint(11<<3 | proto.WireBytes) b.EncodeRawBytes(x.F_Bytes) case *Oneof_F_Sint32: b.EncodeVarint(12<<3 | proto.WireVarint) b.EncodeZigzag32(uint64(x.F_Sint32)) case *Oneof_F_Sint64: b.EncodeVarint(13<<3 | proto.WireVarint) b.EncodeZigzag64(uint64(x.F_Sint64)) case *Oneof_F_Enum: b.EncodeVarint(14<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Enum)) case *Oneof_F_Message: b.EncodeVarint(15<<3 | proto.WireBytes) if err := b.EncodeMessage(x.F_Message); err != nil { return err } case *Oneof_FGroup: b.EncodeVarint(16<<3 | proto.WireStartGroup) if err := b.Marshal(x.FGroup); err != nil { return err } b.EncodeVarint(16<<3 | proto.WireEndGroup) case *Oneof_F_Largest_Tag: b.EncodeVarint(536870911<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Largest_Tag)) case nil: default: return fmt.Errorf("Oneof.Union has unexpected type %T", x) } // tormato switch x := m.Tormato.(type) { case *Oneof_Value: b.EncodeVarint(100<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Value)) case nil: default: return fmt.Errorf("Oneof.Tormato has unexpected type %T", x) } return nil } func _Oneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Oneof) switch tag { case 1: // union.F_Bool if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Bool{x != 0} return true, err case 2: // union.F_Int32 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Int32{int32(x)} return true, err case 3: // union.F_Int64 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Int64{int64(x)} return true, err case 4: // union.F_Fixed32 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Oneof_F_Fixed32{uint32(x)} return true, err case 5: // union.F_Fixed64 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Oneof_F_Fixed64{x} return true, err case 6: // union.F_Uint32 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Uint32{uint32(x)} return true, err case 7: // union.F_Uint64 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Uint64{x} return true, err case 8: // union.F_Float if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Oneof_F_Float{math.Float32frombits(uint32(x))} return true, err case 9: // union.F_Double if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Oneof_F_Double{math.Float64frombits(x)} return true, err case 10: // union.F_String if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Oneof_F_String{x} return true, err case 11: // union.F_Bytes if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Oneof_F_Bytes{x} return true, err case 12: // union.F_Sint32 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.Union = &Oneof_F_Sint32{int32(x)} return true, err case 13: // union.F_Sint64 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag64() m.Union = &Oneof_F_Sint64{int64(x)} return true, err case 14: // union.F_Enum if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Enum{MyMessage_Color(x)} return true, err case 15: // union.F_Message if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(GoTestField) err := b.DecodeMessage(msg) m.Union = &Oneof_F_Message{msg} return true, err case 16: // union.f_group if wire != proto.WireStartGroup { return true, proto.ErrInternalBadWireType } msg := new(Oneof_F_Group) err := b.DecodeGroup(msg) m.Union = &Oneof_FGroup{msg} return true, err case 536870911: // union.F_Largest_Tag if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Largest_Tag{int32(x)} return true, err case 100: // tormato.value if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Tormato = &Oneof_Value{int32(x)} return true, err default: return false, nil } } func _Oneof_OneofSizer(msg proto.Message) (n int) { m := msg.(*Oneof) // union switch x := m.Union.(type) { case *Oneof_F_Bool: n += proto.SizeVarint(1<<3 | proto.WireVarint) n += 1 case *Oneof_F_Int32: n += proto.SizeVarint(2<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Int32)) case *Oneof_F_Int64: n += proto.SizeVarint(3<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Int64)) case *Oneof_F_Fixed32: n += proto.SizeVarint(4<<3 | proto.WireFixed32) n += 4 case *Oneof_F_Fixed64: n += proto.SizeVarint(5<<3 | proto.WireFixed64) n += 8 case *Oneof_F_Uint32: n += proto.SizeVarint(6<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Uint32)) case *Oneof_F_Uint64: n += proto.SizeVarint(7<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Uint64)) case *Oneof_F_Float: n += proto.SizeVarint(8<<3 | proto.WireFixed32) n += 4 case *Oneof_F_Double: n += proto.SizeVarint(9<<3 | proto.WireFixed64) n += 8 case *Oneof_F_String: n += proto.SizeVarint(10<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.F_String))) n += len(x.F_String) case *Oneof_F_Bytes: n += proto.SizeVarint(11<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.F_Bytes))) n += len(x.F_Bytes) case *Oneof_F_Sint32: n += proto.SizeVarint(12<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.F_Sint32) << 1) ^ uint32((int32(x.F_Sint32) >> 31)))) case *Oneof_F_Sint64: n += proto.SizeVarint(13<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(uint64(x.F_Sint64<<1) ^ uint64((int64(x.F_Sint64) >> 63)))) case *Oneof_F_Enum: n += proto.SizeVarint(14<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Enum)) case *Oneof_F_Message: s := proto.Size(x.F_Message) n += proto.SizeVarint(15<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Oneof_FGroup: n += proto.SizeVarint(16<<3 | proto.WireStartGroup) n += proto.Size(x.FGroup) n += proto.SizeVarint(16<<3 | proto.WireEndGroup) case *Oneof_F_Largest_Tag: n += proto.SizeVarint(536870911<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Largest_Tag)) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } // tormato switch x := m.Tormato.(type) { case *Oneof_Value: n += proto.SizeVarint(100<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Value)) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Oneof_F_Group struct { X *int32 `protobuf:"varint,17,opt,name=x" json:"x,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Oneof_F_Group) Reset() { *m = Oneof_F_Group{} } func (m *Oneof_F_Group) String() string { return proto.CompactTextString(m) } func (*Oneof_F_Group) ProtoMessage() {} func (*Oneof_F_Group) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29, 0} } func (m *Oneof_F_Group) GetX() int32 { if m != nil && m.X != nil { return *m.X } return 0 } type Communique struct { MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` // This is a oneof, called "union". // // Types that are valid to be assigned to Union: // *Communique_Number // *Communique_Name // *Communique_Data // *Communique_TempC // *Communique_Col // *Communique_Msg Union isCommunique_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Communique) Reset() { *m = Communique{} } func (m *Communique) String() string { return proto.CompactTextString(m) } func (*Communique) ProtoMessage() {} func (*Communique) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{30} } type isCommunique_Union interface { isCommunique_Union() } type Communique_Number struct { Number int32 `protobuf:"varint,5,opt,name=number,oneof"` } type Communique_Name struct { Name string `protobuf:"bytes,6,opt,name=name,oneof"` } type Communique_Data struct { Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` } type Communique_TempC struct { TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` } type Communique_Col struct { Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=testdata.MyMessage_Color,oneof"` } type Communique_Msg struct { Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"` } func (*Communique_Number) isCommunique_Union() {} func (*Communique_Name) isCommunique_Union() {} func (*Communique_Data) isCommunique_Union() {} func (*Communique_TempC) isCommunique_Union() {} func (*Communique_Col) isCommunique_Union() {} func (*Communique_Msg) isCommunique_Union() {} func (m *Communique) GetUnion() isCommunique_Union { if m != nil { return m.Union } return nil } func (m *Communique) GetMakeMeCry() bool { if m != nil && m.MakeMeCry != nil { return *m.MakeMeCry } return false } func (m *Communique) GetNumber() int32 { if x, ok := m.GetUnion().(*Communique_Number); ok { return x.Number } return 0 } func (m *Communique) GetName() string { if x, ok := m.GetUnion().(*Communique_Name); ok { return x.Name } return "" } func (m *Communique) GetData() []byte { if x, ok := m.GetUnion().(*Communique_Data); ok { return x.Data } return nil } func (m *Communique) GetTempC() float64 { if x, ok := m.GetUnion().(*Communique_TempC); ok { return x.TempC } return 0 } func (m *Communique) GetCol() MyMessage_Color { if x, ok := m.GetUnion().(*Communique_Col); ok { return x.Col } return MyMessage_RED } func (m *Communique) GetMsg() *Strings { if x, ok := m.GetUnion().(*Communique_Msg); ok { return x.Msg } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ (*Communique_Number)(nil), (*Communique_Name)(nil), (*Communique_Data)(nil), (*Communique_TempC)(nil), (*Communique_Col)(nil), (*Communique_Msg)(nil), } } func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: b.EncodeVarint(5<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Number)) case *Communique_Name: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.Name) case *Communique_Data: b.EncodeVarint(7<<3 | proto.WireBytes) b.EncodeRawBytes(x.Data) case *Communique_TempC: b.EncodeVarint(8<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.TempC)) case *Communique_Col: b.EncodeVarint(9<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Col)) case *Communique_Msg: b.EncodeVarint(10<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Msg); err != nil { return err } case nil: default: return fmt.Errorf("Communique.Union has unexpected type %T", x) } return nil } func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Communique) switch tag { case 5: // union.number if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Number{int32(x)} return true, err case 6: // union.name if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Communique_Name{x} return true, err case 7: // union.data if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Communique_Data{x} return true, err case 8: // union.temp_c if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Communique_TempC{math.Float64frombits(x)} return true, err case 9: // union.col if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Col{MyMessage_Color(x)} return true, err case 10: // union.msg if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Strings) err := b.DecodeMessage(msg) m.Union = &Communique_Msg{msg} return true, err default: return false, nil } } func _Communique_OneofSizer(msg proto.Message) (n int) { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Number)) case *Communique_Name: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Name))) n += len(x.Name) case *Communique_Data: n += proto.SizeVarint(7<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Data))) n += len(x.Data) case *Communique_TempC: n += proto.SizeVarint(8<<3 | proto.WireFixed64) n += 8 case *Communique_Col: n += proto.SizeVarint(9<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Col)) case *Communique_Msg: s := proto.Size(x.Msg) n += proto.SizeVarint(10<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } var E_Greeting = &proto.ExtensionDesc{ ExtendedType: (*MyMessage)(nil), ExtensionType: ([]string)(nil), Field: 106, Name: "testdata.greeting", Tag: "bytes,106,rep,name=greeting", Filename: "test.proto", } var E_Complex = &proto.ExtensionDesc{ ExtendedType: (*OtherMessage)(nil), ExtensionType: (*ComplexExtension)(nil), Field: 200, Name: "testdata.complex", Tag: "bytes,200,opt,name=complex", Filename: "test.proto", } var E_RComplex = &proto.ExtensionDesc{ ExtendedType: (*OtherMessage)(nil), ExtensionType: ([]*ComplexExtension)(nil), Field: 201, Name: "testdata.r_complex", Tag: "bytes,201,rep,name=r_complex,json=rComplex", Filename: "test.proto", } var E_NoDefaultDouble = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*float64)(nil), Field: 101, Name: "testdata.no_default_double", Tag: "fixed64,101,opt,name=no_default_double,json=noDefaultDouble", Filename: "test.proto", } var E_NoDefaultFloat = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*float32)(nil), Field: 102, Name: "testdata.no_default_float", Tag: "fixed32,102,opt,name=no_default_float,json=noDefaultFloat", Filename: "test.proto", } var E_NoDefaultInt32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 103, Name: "testdata.no_default_int32", Tag: "varint,103,opt,name=no_default_int32,json=noDefaultInt32", Filename: "test.proto", } var E_NoDefaultInt64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 104, Name: "testdata.no_default_int64", Tag: "varint,104,opt,name=no_default_int64,json=noDefaultInt64", Filename: "test.proto", } var E_NoDefaultUint32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint32)(nil), Field: 105, Name: "testdata.no_default_uint32", Tag: "varint,105,opt,name=no_default_uint32,json=noDefaultUint32", Filename: "test.proto", } var E_NoDefaultUint64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint64)(nil), Field: 106, Name: "testdata.no_default_uint64", Tag: "varint,106,opt,name=no_default_uint64,json=noDefaultUint64", Filename: "test.proto", } var E_NoDefaultSint32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 107, Name: "testdata.no_default_sint32", Tag: "zigzag32,107,opt,name=no_default_sint32,json=noDefaultSint32", Filename: "test.proto", } var E_NoDefaultSint64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 108, Name: "testdata.no_default_sint64", Tag: "zigzag64,108,opt,name=no_default_sint64,json=noDefaultSint64", Filename: "test.proto", } var E_NoDefaultFixed32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint32)(nil), Field: 109, Name: "testdata.no_default_fixed32", Tag: "fixed32,109,opt,name=no_default_fixed32,json=noDefaultFixed32", Filename: "test.proto", } var E_NoDefaultFixed64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint64)(nil), Field: 110, Name: "testdata.no_default_fixed64", Tag: "fixed64,110,opt,name=no_default_fixed64,json=noDefaultFixed64", Filename: "test.proto", } var E_NoDefaultSfixed32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 111, Name: "testdata.no_default_sfixed32", Tag: "fixed32,111,opt,name=no_default_sfixed32,json=noDefaultSfixed32", Filename: "test.proto", } var E_NoDefaultSfixed64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 112, Name: "testdata.no_default_sfixed64", Tag: "fixed64,112,opt,name=no_default_sfixed64,json=noDefaultSfixed64", Filename: "test.proto", } var E_NoDefaultBool = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*bool)(nil), Field: 113, Name: "testdata.no_default_bool", Tag: "varint,113,opt,name=no_default_bool,json=noDefaultBool", Filename: "test.proto", } var E_NoDefaultString = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*string)(nil), Field: 114, Name: "testdata.no_default_string", Tag: "bytes,114,opt,name=no_default_string,json=noDefaultString", Filename: "test.proto", } var E_NoDefaultBytes = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: ([]byte)(nil), Field: 115, Name: "testdata.no_default_bytes", Tag: "bytes,115,opt,name=no_default_bytes,json=noDefaultBytes", Filename: "test.proto", } var E_NoDefaultEnum = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), Field: 116, Name: "testdata.no_default_enum", Tag: "varint,116,opt,name=no_default_enum,json=noDefaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum", Filename: "test.proto", } var E_DefaultDouble = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*float64)(nil), Field: 201, Name: "testdata.default_double", Tag: "fixed64,201,opt,name=default_double,json=defaultDouble,def=3.1415", Filename: "test.proto", } var E_DefaultFloat = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*float32)(nil), Field: 202, Name: "testdata.default_float", Tag: "fixed32,202,opt,name=default_float,json=defaultFloat,def=3.14", Filename: "test.proto", } var E_DefaultInt32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 203, Name: "testdata.default_int32", Tag: "varint,203,opt,name=default_int32,json=defaultInt32,def=42", Filename: "test.proto", } var E_DefaultInt64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 204, Name: "testdata.default_int64", Tag: "varint,204,opt,name=default_int64,json=defaultInt64,def=43", Filename: "test.proto", } var E_DefaultUint32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint32)(nil), Field: 205, Name: "testdata.default_uint32", Tag: "varint,205,opt,name=default_uint32,json=defaultUint32,def=44", Filename: "test.proto", } var E_DefaultUint64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint64)(nil), Field: 206, Name: "testdata.default_uint64", Tag: "varint,206,opt,name=default_uint64,json=defaultUint64,def=45", Filename: "test.proto", } var E_DefaultSint32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 207, Name: "testdata.default_sint32", Tag: "zigzag32,207,opt,name=default_sint32,json=defaultSint32,def=46", Filename: "test.proto", } var E_DefaultSint64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 208, Name: "testdata.default_sint64", Tag: "zigzag64,208,opt,name=default_sint64,json=defaultSint64,def=47", Filename: "test.proto", } var E_DefaultFixed32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint32)(nil), Field: 209, Name: "testdata.default_fixed32", Tag: "fixed32,209,opt,name=default_fixed32,json=defaultFixed32,def=48", Filename: "test.proto", } var E_DefaultFixed64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint64)(nil), Field: 210, Name: "testdata.default_fixed64", Tag: "fixed64,210,opt,name=default_fixed64,json=defaultFixed64,def=49", Filename: "test.proto", } var E_DefaultSfixed32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 211, Name: "testdata.default_sfixed32", Tag: "fixed32,211,opt,name=default_sfixed32,json=defaultSfixed32,def=50", Filename: "test.proto", } var E_DefaultSfixed64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 212, Name: "testdata.default_sfixed64", Tag: "fixed64,212,opt,name=default_sfixed64,json=defaultSfixed64,def=51", Filename: "test.proto", } var E_DefaultBool = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*bool)(nil), Field: 213, Name: "testdata.default_bool", Tag: "varint,213,opt,name=default_bool,json=defaultBool,def=1", Filename: "test.proto", } var E_DefaultString = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*string)(nil), Field: 214, Name: "testdata.default_string", Tag: "bytes,214,opt,name=default_string,json=defaultString,def=Hello, string", Filename: "test.proto", } var E_DefaultBytes = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: ([]byte)(nil), Field: 215, Name: "testdata.default_bytes", Tag: "bytes,215,opt,name=default_bytes,json=defaultBytes,def=Hello, bytes", Filename: "test.proto", } var E_DefaultEnum = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), Field: 216, Name: "testdata.default_enum", Tag: "varint,216,opt,name=default_enum,json=defaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1", Filename: "test.proto", } var E_X201 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 201, Name: "testdata.x201", Tag: "bytes,201,opt,name=x201", Filename: "test.proto", } var E_X202 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 202, Name: "testdata.x202", Tag: "bytes,202,opt,name=x202", Filename: "test.proto", } var E_X203 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 203, Name: "testdata.x203", Tag: "bytes,203,opt,name=x203", Filename: "test.proto", } var E_X204 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 204, Name: "testdata.x204", Tag: "bytes,204,opt,name=x204", Filename: "test.proto", } var E_X205 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 205, Name: "testdata.x205", Tag: "bytes,205,opt,name=x205", Filename: "test.proto", } var E_X206 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 206, Name: "testdata.x206", Tag: "bytes,206,opt,name=x206", Filename: "test.proto", } var E_X207 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 207, Name: "testdata.x207", Tag: "bytes,207,opt,name=x207", Filename: "test.proto", } var E_X208 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 208, Name: "testdata.x208", Tag: "bytes,208,opt,name=x208", Filename: "test.proto", } var E_X209 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 209, Name: "testdata.x209", Tag: "bytes,209,opt,name=x209", Filename: "test.proto", } var E_X210 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 210, Name: "testdata.x210", Tag: "bytes,210,opt,name=x210", Filename: "test.proto", } var E_X211 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 211, Name: "testdata.x211", Tag: "bytes,211,opt,name=x211", Filename: "test.proto", } var E_X212 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 212, Name: "testdata.x212", Tag: "bytes,212,opt,name=x212", Filename: "test.proto", } var E_X213 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 213, Name: "testdata.x213", Tag: "bytes,213,opt,name=x213", Filename: "test.proto", } var E_X214 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 214, Name: "testdata.x214", Tag: "bytes,214,opt,name=x214", Filename: "test.proto", } var E_X215 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 215, Name: "testdata.x215", Tag: "bytes,215,opt,name=x215", Filename: "test.proto", } var E_X216 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 216, Name: "testdata.x216", Tag: "bytes,216,opt,name=x216", Filename: "test.proto", } var E_X217 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 217, Name: "testdata.x217", Tag: "bytes,217,opt,name=x217", Filename: "test.proto", } var E_X218 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 218, Name: "testdata.x218", Tag: "bytes,218,opt,name=x218", Filename: "test.proto", } var E_X219 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 219, Name: "testdata.x219", Tag: "bytes,219,opt,name=x219", Filename: "test.proto", } var E_X220 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 220, Name: "testdata.x220", Tag: "bytes,220,opt,name=x220", Filename: "test.proto", } var E_X221 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 221, Name: "testdata.x221", Tag: "bytes,221,opt,name=x221", Filename: "test.proto", } var E_X222 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 222, Name: "testdata.x222", Tag: "bytes,222,opt,name=x222", Filename: "test.proto", } var E_X223 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 223, Name: "testdata.x223", Tag: "bytes,223,opt,name=x223", Filename: "test.proto", } var E_X224 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 224, Name: "testdata.x224", Tag: "bytes,224,opt,name=x224", Filename: "test.proto", } var E_X225 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 225, Name: "testdata.x225", Tag: "bytes,225,opt,name=x225", Filename: "test.proto", } var E_X226 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 226, Name: "testdata.x226", Tag: "bytes,226,opt,name=x226", Filename: "test.proto", } var E_X227 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 227, Name: "testdata.x227", Tag: "bytes,227,opt,name=x227", Filename: "test.proto", } var E_X228 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 228, Name: "testdata.x228", Tag: "bytes,228,opt,name=x228", Filename: "test.proto", } var E_X229 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 229, Name: "testdata.x229", Tag: "bytes,229,opt,name=x229", Filename: "test.proto", } var E_X230 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 230, Name: "testdata.x230", Tag: "bytes,230,opt,name=x230", Filename: "test.proto", } var E_X231 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 231, Name: "testdata.x231", Tag: "bytes,231,opt,name=x231", Filename: "test.proto", } var E_X232 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 232, Name: "testdata.x232", Tag: "bytes,232,opt,name=x232", Filename: "test.proto", } var E_X233 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 233, Name: "testdata.x233", Tag: "bytes,233,opt,name=x233", Filename: "test.proto", } var E_X234 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 234, Name: "testdata.x234", Tag: "bytes,234,opt,name=x234", Filename: "test.proto", } var E_X235 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 235, Name: "testdata.x235", Tag: "bytes,235,opt,name=x235", Filename: "test.proto", } var E_X236 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 236, Name: "testdata.x236", Tag: "bytes,236,opt,name=x236", Filename: "test.proto", } var E_X237 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 237, Name: "testdata.x237", Tag: "bytes,237,opt,name=x237", Filename: "test.proto", } var E_X238 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 238, Name: "testdata.x238", Tag: "bytes,238,opt,name=x238", Filename: "test.proto", } var E_X239 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 239, Name: "testdata.x239", Tag: "bytes,239,opt,name=x239", Filename: "test.proto", } var E_X240 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 240, Name: "testdata.x240", Tag: "bytes,240,opt,name=x240", Filename: "test.proto", } var E_X241 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 241, Name: "testdata.x241", Tag: "bytes,241,opt,name=x241", Filename: "test.proto", } var E_X242 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 242, Name: "testdata.x242", Tag: "bytes,242,opt,name=x242", Filename: "test.proto", } var E_X243 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 243, Name: "testdata.x243", Tag: "bytes,243,opt,name=x243", Filename: "test.proto", } var E_X244 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 244, Name: "testdata.x244", Tag: "bytes,244,opt,name=x244", Filename: "test.proto", } var E_X245 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 245, Name: "testdata.x245", Tag: "bytes,245,opt,name=x245", Filename: "test.proto", } var E_X246 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 246, Name: "testdata.x246", Tag: "bytes,246,opt,name=x246", Filename: "test.proto", } var E_X247 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 247, Name: "testdata.x247", Tag: "bytes,247,opt,name=x247", Filename: "test.proto", } var E_X248 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 248, Name: "testdata.x248", Tag: "bytes,248,opt,name=x248", Filename: "test.proto", } var E_X249 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 249, Name: "testdata.x249", Tag: "bytes,249,opt,name=x249", Filename: "test.proto", } var E_X250 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 250, Name: "testdata.x250", Tag: "bytes,250,opt,name=x250", Filename: "test.proto", } func init() { proto.RegisterType((*GoEnum)(nil), "testdata.GoEnum") proto.RegisterType((*GoTestField)(nil), "testdata.GoTestField") proto.RegisterType((*GoTest)(nil), "testdata.GoTest") proto.RegisterType((*GoTest_RequiredGroup)(nil), "testdata.GoTest.RequiredGroup") proto.RegisterType((*GoTest_RepeatedGroup)(nil), "testdata.GoTest.RepeatedGroup") proto.RegisterType((*GoTest_OptionalGroup)(nil), "testdata.GoTest.OptionalGroup") proto.RegisterType((*GoTestRequiredGroupField)(nil), "testdata.GoTestRequiredGroupField") proto.RegisterType((*GoTestRequiredGroupField_Group)(nil), "testdata.GoTestRequiredGroupField.Group") proto.RegisterType((*GoSkipTest)(nil), "testdata.GoSkipTest") proto.RegisterType((*GoSkipTest_SkipGroup)(nil), "testdata.GoSkipTest.SkipGroup") proto.RegisterType((*NonPackedTest)(nil), "testdata.NonPackedTest") proto.RegisterType((*PackedTest)(nil), "testdata.PackedTest") proto.RegisterType((*MaxTag)(nil), "testdata.MaxTag") proto.RegisterType((*OldMessage)(nil), "testdata.OldMessage") proto.RegisterType((*OldMessage_Nested)(nil), "testdata.OldMessage.Nested") proto.RegisterType((*NewMessage)(nil), "testdata.NewMessage") proto.RegisterType((*NewMessage_Nested)(nil), "testdata.NewMessage.Nested") proto.RegisterType((*InnerMessage)(nil), "testdata.InnerMessage") proto.RegisterType((*OtherMessage)(nil), "testdata.OtherMessage") proto.RegisterType((*RequiredInnerMessage)(nil), "testdata.RequiredInnerMessage") proto.RegisterType((*MyMessage)(nil), "testdata.MyMessage") proto.RegisterType((*MyMessage_SomeGroup)(nil), "testdata.MyMessage.SomeGroup") proto.RegisterType((*Ext)(nil), "testdata.Ext") proto.RegisterType((*ComplexExtension)(nil), "testdata.ComplexExtension") proto.RegisterType((*DefaultsMessage)(nil), "testdata.DefaultsMessage") proto.RegisterType((*MyMessageSet)(nil), "testdata.MyMessageSet") proto.RegisterType((*Empty)(nil), "testdata.Empty") proto.RegisterType((*MessageList)(nil), "testdata.MessageList") proto.RegisterType((*MessageList_Message)(nil), "testdata.MessageList.Message") proto.RegisterType((*Strings)(nil), "testdata.Strings") proto.RegisterType((*Defaults)(nil), "testdata.Defaults") proto.RegisterType((*SubDefaults)(nil), "testdata.SubDefaults") proto.RegisterType((*RepeatedEnum)(nil), "testdata.RepeatedEnum") proto.RegisterType((*MoreRepeated)(nil), "testdata.MoreRepeated") proto.RegisterType((*GroupOld)(nil), "testdata.GroupOld") proto.RegisterType((*GroupOld_G)(nil), "testdata.GroupOld.G") proto.RegisterType((*GroupNew)(nil), "testdata.GroupNew") proto.RegisterType((*GroupNew_G)(nil), "testdata.GroupNew.G") proto.RegisterType((*FloatingPoint)(nil), "testdata.FloatingPoint") proto.RegisterType((*MessageWithMap)(nil), "testdata.MessageWithMap") proto.RegisterType((*Oneof)(nil), "testdata.Oneof") proto.RegisterType((*Oneof_F_Group)(nil), "testdata.Oneof.F_Group") proto.RegisterType((*Communique)(nil), "testdata.Communique") proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value) proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) proto.RegisterEnum("testdata.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value) proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value) proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) proto.RegisterExtension(E_Ext_More) proto.RegisterExtension(E_Ext_Text) proto.RegisterExtension(E_Ext_Number) proto.RegisterExtension(E_Greeting) proto.RegisterExtension(E_Complex) proto.RegisterExtension(E_RComplex) proto.RegisterExtension(E_NoDefaultDouble) proto.RegisterExtension(E_NoDefaultFloat) proto.RegisterExtension(E_NoDefaultInt32) proto.RegisterExtension(E_NoDefaultInt64) proto.RegisterExtension(E_NoDefaultUint32) proto.RegisterExtension(E_NoDefaultUint64) proto.RegisterExtension(E_NoDefaultSint32) proto.RegisterExtension(E_NoDefaultSint64) proto.RegisterExtension(E_NoDefaultFixed32) proto.RegisterExtension(E_NoDefaultFixed64) proto.RegisterExtension(E_NoDefaultSfixed32) proto.RegisterExtension(E_NoDefaultSfixed64) proto.RegisterExtension(E_NoDefaultBool) proto.RegisterExtension(E_NoDefaultString) proto.RegisterExtension(E_NoDefaultBytes) proto.RegisterExtension(E_NoDefaultEnum) proto.RegisterExtension(E_DefaultDouble) proto.RegisterExtension(E_DefaultFloat) proto.RegisterExtension(E_DefaultInt32) proto.RegisterExtension(E_DefaultInt64) proto.RegisterExtension(E_DefaultUint32) proto.RegisterExtension(E_DefaultUint64) proto.RegisterExtension(E_DefaultSint32) proto.RegisterExtension(E_DefaultSint64) proto.RegisterExtension(E_DefaultFixed32) proto.RegisterExtension(E_DefaultFixed64) proto.RegisterExtension(E_DefaultSfixed32) proto.RegisterExtension(E_DefaultSfixed64) proto.RegisterExtension(E_DefaultBool) proto.RegisterExtension(E_DefaultString) proto.RegisterExtension(E_DefaultBytes) proto.RegisterExtension(E_DefaultEnum) proto.RegisterExtension(E_X201) proto.RegisterExtension(E_X202) proto.RegisterExtension(E_X203) proto.RegisterExtension(E_X204) proto.RegisterExtension(E_X205) proto.RegisterExtension(E_X206) proto.RegisterExtension(E_X207) proto.RegisterExtension(E_X208) proto.RegisterExtension(E_X209) proto.RegisterExtension(E_X210) proto.RegisterExtension(E_X211) proto.RegisterExtension(E_X212) proto.RegisterExtension(E_X213) proto.RegisterExtension(E_X214) proto.RegisterExtension(E_X215) proto.RegisterExtension(E_X216) proto.RegisterExtension(E_X217) proto.RegisterExtension(E_X218) proto.RegisterExtension(E_X219) proto.RegisterExtension(E_X220) proto.RegisterExtension(E_X221) proto.RegisterExtension(E_X222) proto.RegisterExtension(E_X223) proto.RegisterExtension(E_X224) proto.RegisterExtension(E_X225) proto.RegisterExtension(E_X226) proto.RegisterExtension(E_X227) proto.RegisterExtension(E_X228) proto.RegisterExtension(E_X229) proto.RegisterExtension(E_X230) proto.RegisterExtension(E_X231) proto.RegisterExtension(E_X232) proto.RegisterExtension(E_X233) proto.RegisterExtension(E_X234) proto.RegisterExtension(E_X235) proto.RegisterExtension(E_X236) proto.RegisterExtension(E_X237) proto.RegisterExtension(E_X238) proto.RegisterExtension(E_X239) proto.RegisterExtension(E_X240) proto.RegisterExtension(E_X241) proto.RegisterExtension(E_X242) proto.RegisterExtension(E_X243) proto.RegisterExtension(E_X244) proto.RegisterExtension(E_X245) proto.RegisterExtension(E_X246) proto.RegisterExtension(E_X247) proto.RegisterExtension(E_X248) proto.RegisterExtension(E_X249) proto.RegisterExtension(E_X250) } func init() { proto.RegisterFile("test.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 4453 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5a, 0xc9, 0x77, 0xdb, 0x48, 0x7a, 0x37, 0xc0, 0xfd, 0x23, 0x25, 0x42, 0x65, 0xb5, 0x9b, 0x96, 0xbc, 0xc0, 0x9c, 0xe9, 0x6e, 0x7a, 0xd3, 0x48, 0x20, 0x44, 0xdb, 0x74, 0xa7, 0xdf, 0xf3, 0x42, 0xca, 0x7a, 0x63, 0x89, 0x0a, 0xa4, 0xee, 0x7e, 0xd3, 0x39, 0xf0, 0x51, 0x22, 0x44, 0xb3, 0x4d, 0x02, 0x34, 0x09, 0xc5, 0x52, 0x72, 0xe9, 0x4b, 0x72, 0xcd, 0x76, 0xc9, 0x35, 0xa7, 0x9c, 0x92, 0xbc, 0x97, 0x7f, 0x22, 0xe9, 0xee, 0x59, 0x7b, 0xd6, 0xac, 0x93, 0x7d, 0x99, 0xec, 0xdb, 0x4c, 0x92, 0x4b, 0xcf, 0xab, 0xaf, 0x0a, 0x40, 0x01, 0x24, 0x20, 0xf9, 0x24, 0x56, 0xd5, 0xef, 0xf7, 0xd5, 0xf6, 0xab, 0xef, 0xab, 0xaf, 0x20, 0x00, 0xc7, 0x9c, 0x38, 0x2b, 0xa3, 0xb1, 0xed, 0xd8, 0x24, 0x4b, 0x7f, 0x77, 0x3b, 0x4e, 0xa7, 0x7c, 0x1d, 0xd2, 0x1b, 0x76, 0xc3, 0x3a, 0x1a, 0x92, 0xab, 0x90, 0x38, 0xb4, 0xed, 0x92, 0xa4, 0xca, 0x95, 0x79, 0x6d, 0x6e, 0xc5, 0x45, 0xac, 0x34, 0x5b, 0x2d, 0x83, 0xb6, 0x94, 0xef, 0x40, 0x7e, 0xc3, 0xde, 0x33, 0x27, 0x4e, 0xb3, 0x6f, 0x0e, 0xba, 0x64, 0x11, 0x52, 0x4f, 0x3b, 0xfb, 0xe6, 0x00, 0x19, 0x39, 0x83, 0x15, 0x08, 0x81, 0xe4, 0xde, 0xc9, 0xc8, 0x2c, 0xc9, 0x58, 0x89, 0xbf, 0xcb, 0xbf, 0x72, 0x85, 0x76, 0x42, 0x99, 0xe4, 0x3a, 0x24, 0xbf, 0xdc, 0xb7, 0xba, 0xbc, 0x97, 0xd7, 0xfc, 0x5e, 0x58, 0xfb, 0xca, 0x97, 0x37, 0xb7, 0x1f, 0x1b, 0x08, 0xa1, 0xf6, 0xf7, 0x3a, 0xfb, 0x03, 0x6a, 0x4a, 0xa2, 0xf6, 0xb1, 0x40, 0x6b, 0x77, 0x3a, 0xe3, 0xce, 0xb0, 0x94, 0x50, 0xa5, 0x4a, 0xca, 0x60, 0x05, 0x72, 0x1f, 0xe6, 0x0c, 0xf3, 0xc5, 0x51, 0x7f, 0x6c, 0x76, 0x71, 0x70, 0xa5, 0xa4, 0x2a, 0x57, 0xf2, 0xd3, 0xf6, 0xb1, 0xd1, 0x08, 0x62, 0x19, 0x79, 0x64, 0x76, 0x1c, 0x97, 0x9c, 0x52, 0x13, 0xb1, 0x64, 0x01, 0x4b, 0xc9, 0xad, 0x91, 0xd3, 0xb7, 0xad, 0xce, 0x80, 0x91, 0xd3, 0xaa, 0x14, 0x43, 0x0e, 0x60, 0xc9, 0x9b, 0x50, 0x6c, 0xb6, 0x1f, 0xda, 0xf6, 0xa0, 0x3d, 0xe6, 0x23, 0x2a, 0x81, 0x2a, 0x57, 0xb2, 0xc6, 0x5c, 0x93, 0xd6, 0xba, 0xc3, 0x24, 0x15, 0x50, 0x9a, 0xed, 0x4d, 0xcb, 0xa9, 0x6a, 0x3e, 0x30, 0xaf, 0xca, 0x95, 0x94, 0x31, 0xdf, 0xc4, 0xea, 0x29, 0x64, 0x4d, 0xf7, 0x91, 0x05, 0x55, 0xae, 0x24, 0x18, 0xb2, 0xa6, 0x7b, 0xc8, 0x5b, 0x40, 0x9a, 0xed, 0x66, 0xff, 0xd8, 0xec, 0x8a, 0x56, 0xe7, 0x54, 0xb9, 0x92, 0x31, 0x94, 0x26, 0x6f, 0x98, 0x81, 0x16, 0x2d, 0xcf, 0xab, 0x72, 0x25, 0xed, 0xa2, 0x05, 0xdb, 0x37, 0x60, 0xa1, 0xd9, 0x7e, 0xb7, 0x1f, 0x1c, 0x70, 0x51, 0x95, 0x2b, 0x73, 0x46, 0xb1, 0xc9, 0xea, 0xa7, 0xb1, 0xa2, 0x61, 0x45, 0x95, 0x2b, 0x49, 0x8e, 0x15, 0xec, 0xe2, 0xec, 0x9a, 0x03, 0xbb, 0xe3, 0xf8, 0xd0, 0x05, 0x55, 0xae, 0xc8, 0xc6, 0x7c, 0x13, 0xab, 0x83, 0x56, 0x1f, 0xdb, 0x47, 0xfb, 0x03, 0xd3, 0x87, 0x12, 0x55, 0xae, 0x48, 0x46, 0xb1, 0xc9, 0xea, 0x83, 0xd8, 0x5d, 0x67, 0xdc, 0xb7, 0x7a, 0x3e, 0xf6, 0x3c, 0xea, 0xb7, 0xd8, 0x64, 0xf5, 0xc1, 0x11, 0x3c, 0x3c, 0x71, 0xcc, 0x89, 0x0f, 0x35, 0x55, 0xb9, 0x52, 0x30, 0xe6, 0x9b, 0x58, 0x1d, 0xb2, 0x1a, 0x5a, 0x83, 0x43, 0x55, 0xae, 0x2c, 0x50, 0xab, 0x33, 0xd6, 0x60, 0x37, 0xb4, 0x06, 0x3d, 0x55, 0xae, 0x10, 0x8e, 0x15, 0xd6, 0x40, 0xd4, 0x0c, 0x13, 0x62, 0x69, 0x51, 0x4d, 0x08, 0x9a, 0x61, 0x95, 0x41, 0xcd, 0x70, 0xe0, 0x6b, 0x6a, 0x42, 0xd4, 0x4c, 0x08, 0x89, 0x9d, 0x73, 0xe4, 0x05, 0x35, 0x21, 0x6a, 0x86, 0x23, 0x43, 0x9a, 0xe1, 0xd8, 0xd7, 0xd5, 0x44, 0x50, 0x33, 0x53, 0x68, 0xd1, 0x72, 0x49, 0x4d, 0x04, 0x35, 0xc3, 0xd1, 0x41, 0xcd, 0x70, 0xf0, 0x45, 0x35, 0x11, 0xd0, 0x4c, 0x18, 0x2b, 0x1a, 0x5e, 0x52, 0x13, 0x01, 0xcd, 0x88, 0xb3, 0x73, 0x35, 0xc3, 0xa1, 0xcb, 0x6a, 0x42, 0xd4, 0x8c, 0x68, 0xd5, 0xd3, 0x0c, 0x87, 0x5e, 0x52, 0x13, 0x01, 0xcd, 0x88, 0x58, 0x4f, 0x33, 0x1c, 0x7b, 0x59, 0x4d, 0x04, 0x34, 0xc3, 0xb1, 0xd7, 0x45, 0xcd, 0x70, 0xe8, 0xc7, 0x92, 0x9a, 0x10, 0x45, 0xc3, 0xa1, 0x37, 0x03, 0xa2, 0xe1, 0xd8, 0x4f, 0x28, 0x56, 0x54, 0x4d, 0x18, 0x2c, 0xae, 0xc2, 0xa7, 0x14, 0x2c, 0xca, 0x86, 0x83, 0x7d, 0xd9, 0xd8, 0xdc, 0x05, 0x95, 0xae, 0xa8, 0x92, 0x27, 0x1b, 0xd7, 0x2f, 0x89, 0xb2, 0xf1, 0x80, 0x57, 0xd1, 0xd5, 0x72, 0xd9, 0x4c, 0x21, 0x6b, 0xba, 0x8f, 0x54, 0x55, 0xc9, 0x97, 0x8d, 0x87, 0x0c, 0xc8, 0xc6, 0xc3, 0x5e, 0x53, 0x25, 0x51, 0x36, 0x33, 0xd0, 0xa2, 0xe5, 0xb2, 0x2a, 0x89, 0xb2, 0xf1, 0xd0, 0xa2, 0x6c, 0x3c, 0xf0, 0x17, 0x54, 0x49, 0x90, 0xcd, 0x34, 0x56, 0x34, 0xfc, 0x45, 0x55, 0x12, 0x64, 0x13, 0x9c, 0x1d, 0x93, 0x8d, 0x07, 0x7d, 0x43, 0x95, 0x7c, 0xd9, 0x04, 0xad, 0x72, 0xd9, 0x78, 0xd0, 0x37, 0x55, 0x49, 0x90, 0x4d, 0x10, 0xcb, 0x65, 0xe3, 0x61, 0xdf, 0xc2, 0xf8, 0xe6, 0xca, 0xc6, 0xc3, 0x0a, 0xb2, 0xf1, 0xa0, 0xbf, 0x43, 0x63, 0xa1, 0x27, 0x1b, 0x0f, 0x2a, 0xca, 0xc6, 0xc3, 0xfe, 0x2e, 0xc5, 0xfa, 0xb2, 0x99, 0x06, 0x8b, 0xab, 0xf0, 0x7b, 0x14, 0xec, 0xcb, 0xc6, 0x03, 0xaf, 0xe0, 0x20, 0xa8, 0x6c, 0xba, 0xe6, 0x61, 0xe7, 0x68, 0x40, 0x25, 0x56, 0xa1, 0xba, 0xa9, 0x27, 0x9d, 0xf1, 0x91, 0x49, 0x47, 0x62, 0xdb, 0x83, 0xc7, 0x6e, 0x1b, 0x59, 0xa1, 0xc6, 0x99, 0x7c, 0x7c, 0xc2, 0x75, 0xaa, 0x9f, 0xba, 0x5c, 0xd5, 0x8c, 0x22, 0xd3, 0xd0, 0x34, 0xbe, 0xa6, 0x0b, 0xf8, 0x1b, 0x54, 0x45, 0x75, 0xb9, 0xa6, 0x33, 0x7c, 0x4d, 0xf7, 0xf1, 0x55, 0x38, 0xef, 0x4b, 0xc9, 0x67, 0xdc, 0xa4, 0x5a, 0xaa, 0x27, 0xaa, 0xda, 0xaa, 0xb1, 0xe0, 0x0a, 0x6a, 0x16, 0x29, 0xd0, 0xcd, 0x2d, 0x2a, 0xa9, 0x7a, 0xa2, 0xa6, 0x7b, 0x24, 0xb1, 0x27, 0x8d, 0xca, 0x90, 0x0b, 0xcb, 0xe7, 0xdc, 0xa6, 0xca, 0xaa, 0x27, 0xab, 0xda, 0xea, 0xaa, 0xa1, 0x70, 0x7d, 0xcd, 0xe0, 0x04, 0xfa, 0x59, 0xa1, 0x0a, 0xab, 0x27, 0x6b, 0xba, 0xc7, 0x09, 0xf6, 0xb3, 0xe0, 0x0a, 0xcd, 0xa7, 0x7c, 0x89, 0x2a, 0xad, 0x9e, 0xae, 0xae, 0xe9, 0x6b, 0xeb, 0xf7, 0x8c, 0x22, 0x53, 0x9c, 0xcf, 0xd1, 0x69, 0x3f, 0x5c, 0x72, 0x3e, 0x69, 0x95, 0x6a, 0xae, 0x9e, 0xd6, 0xee, 0xac, 0xdd, 0xd5, 0xee, 0x1a, 0x0a, 0xd7, 0x9e, 0xcf, 0x7a, 0x87, 0xb2, 0xb8, 0xf8, 0x7c, 0xd6, 0x1a, 0x55, 0x5f, 0x5d, 0x79, 0x66, 0x0e, 0x06, 0xf6, 0x2d, 0xb5, 0xfc, 0xd2, 0x1e, 0x0f, 0xba, 0xd7, 0xca, 0x60, 0x28, 0x5c, 0x8f, 0x62, 0xaf, 0x0b, 0xae, 0x20, 0x7d, 0xfa, 0xaf, 0xd1, 0x7b, 0x58, 0xa1, 0x9e, 0x79, 0xd8, 0xef, 0x59, 0xf6, 0xc4, 0x34, 0x8a, 0x4c, 0x9a, 0xa1, 0x35, 0xd9, 0x0d, 0xaf, 0xe3, 0xaf, 0x53, 0xda, 0x42, 0x3d, 0x71, 0xbb, 0xaa, 0xd1, 0x9e, 0x66, 0xad, 0xe3, 0x6e, 0x78, 0x1d, 0x7f, 0x83, 0x72, 0x48, 0x3d, 0x71, 0xbb, 0xa6, 0x73, 0x8e, 0xb8, 0x8e, 0x77, 0xe0, 0x42, 0x28, 0x2e, 0xb6, 0x47, 0x9d, 0x83, 0xe7, 0x66, 0xb7, 0xa4, 0xd1, 0xf0, 0xf8, 0x50, 0x56, 0x24, 0xe3, 0x7c, 0x20, 0x44, 0xee, 0x60, 0x33, 0xb9, 0x07, 0xaf, 0x87, 0x03, 0xa5, 0xcb, 0xac, 0xd2, 0x78, 0x89, 0xcc, 0xc5, 0x60, 0xcc, 0x0c, 0x51, 0x05, 0x07, 0xec, 0x52, 0x75, 0x1a, 0x40, 0x7d, 0xaa, 0xef, 0x89, 0x39, 0xf5, 0x67, 0xe0, 0xe2, 0x74, 0x28, 0x75, 0xc9, 0xeb, 0x34, 0xa2, 0x22, 0xf9, 0x42, 0x38, 0xaa, 0x4e, 0xd1, 0x67, 0xf4, 0x5d, 0xa3, 0x21, 0x56, 0xa4, 0x4f, 0xf5, 0x7e, 0x1f, 0x4a, 0x53, 0xc1, 0xd6, 0x65, 0xdf, 0xa1, 0x31, 0x17, 0xd9, 0xaf, 0x85, 0xe2, 0x6e, 0x98, 0x3c, 0xa3, 0xeb, 0xbb, 0x34, 0x08, 0x0b, 0xe4, 0xa9, 0x9e, 0x71, 0xc9, 0x82, 0xe1, 0xd8, 0xe5, 0xde, 0xa3, 0x51, 0x99, 0x2f, 0x59, 0x20, 0x32, 0x8b, 0xfd, 0x86, 0xe2, 0xb3, 0xcb, 0xad, 0xd3, 0x30, 0xcd, 0xfb, 0x0d, 0x86, 0x6a, 0x4e, 0x7e, 0x9b, 0x92, 0x77, 0x67, 0xcf, 0xf8, 0xc7, 0x09, 0x1a, 0x60, 0x39, 0x7b, 0x77, 0xd6, 0x94, 0x3d, 0xf6, 0x8c, 0x29, 0xff, 0x84, 0xb2, 0x89, 0xc0, 0x9e, 0x9a, 0xf3, 0x63, 0x98, 0x73, 0x6f, 0x75, 0xbd, 0xb1, 0x7d, 0x34, 0x2a, 0x35, 0x55, 0xb9, 0x02, 0xda, 0x95, 0xa9, 0xec, 0xc7, 0xbd, 0xe4, 0x6d, 0x50, 0x94, 0x11, 0x24, 0x31, 0x2b, 0xcc, 0x2e, 0xb3, 0xb2, 0xa3, 0x26, 0x22, 0xac, 0x30, 0x94, 0x67, 0x45, 0x20, 0x51, 0x2b, 0xae, 0xd3, 0x67, 0x56, 0x3e, 0x50, 0xa5, 0x99, 0x56, 0xdc, 0x10, 0xc0, 0xad, 0x04, 0x48, 0x4b, 0xeb, 0x7e, 0xbe, 0x85, 0xed, 0xe4, 0x8b, 0xe1, 0x04, 0x6c, 0x03, 0xef, 0xcf, 0xc1, 0x4a, 0x46, 0x13, 0x06, 0x37, 0x4d, 0xfb, 0xd9, 0x08, 0x5a, 0x60, 0x34, 0xd3, 0xb4, 0x9f, 0x9b, 0x41, 0x2b, 0xff, 0xa6, 0x04, 0x49, 0x9a, 0x4f, 0x92, 0x2c, 0x24, 0xdf, 0x6b, 0x6d, 0x3e, 0x56, 0xce, 0xd1, 0x5f, 0x0f, 0x5b, 0xad, 0xa7, 0x8a, 0x44, 0x72, 0x90, 0x7a, 0xf8, 0x95, 0xbd, 0xc6, 0xae, 0x22, 0x93, 0x22, 0xe4, 0x9b, 0x9b, 0xdb, 0x1b, 0x0d, 0x63, 0xc7, 0xd8, 0xdc, 0xde, 0x53, 0x12, 0xb4, 0xad, 0xf9, 0xb4, 0xf5, 0x60, 0x4f, 0x49, 0x92, 0x0c, 0x24, 0x68, 0x5d, 0x8a, 0x00, 0xa4, 0x77, 0xf7, 0x8c, 0xcd, 0xed, 0x0d, 0x25, 0x4d, 0xad, 0xec, 0x6d, 0x6e, 0x35, 0x94, 0x0c, 0x45, 0xee, 0xbd, 0xbb, 0xf3, 0xb4, 0xa1, 0x64, 0xe9, 0xcf, 0x07, 0x86, 0xf1, 0xe0, 0x2b, 0x4a, 0x8e, 0x92, 0xb6, 0x1e, 0xec, 0x28, 0x80, 0xcd, 0x0f, 0x1e, 0x3e, 0x6d, 0x28, 0x79, 0x52, 0x80, 0x6c, 0xf3, 0xdd, 0xed, 0x47, 0x7b, 0x9b, 0xad, 0x6d, 0xa5, 0x50, 0x3e, 0x81, 0x12, 0x5b, 0xe6, 0xc0, 0x2a, 0xb2, 0xa4, 0xf0, 0x1d, 0x48, 0xb1, 0x9d, 0x91, 0x50, 0x25, 0x95, 0xf0, 0xce, 0x4c, 0x53, 0x56, 0xd8, 0x1e, 0x31, 0xda, 0xd2, 0x65, 0x48, 0xb1, 0x55, 0x5a, 0x84, 0x14, 0x5b, 0x1d, 0x19, 0x53, 0x45, 0x56, 0x28, 0xff, 0x96, 0x0c, 0xb0, 0x61, 0xef, 0x3e, 0xef, 0x8f, 0x30, 0x21, 0xbf, 0x0c, 0x30, 0x79, 0xde, 0x1f, 0xb5, 0x51, 0xf5, 0x3c, 0xa9, 0xcc, 0xd1, 0x1a, 0xf4, 0x77, 0xe4, 0x1a, 0x14, 0xb0, 0xf9, 0x90, 0x79, 0x21, 0xcc, 0x25, 0x33, 0x46, 0x9e, 0xd6, 0x71, 0xc7, 0x14, 0x84, 0xd4, 0x74, 0x4c, 0x21, 0xd3, 0x02, 0xa4, 0xa6, 0x93, 0xab, 0x80, 0xc5, 0xf6, 0x04, 0x23, 0x0a, 0xa6, 0x8d, 0x39, 0x03, 0xfb, 0x65, 0x31, 0x86, 0xbc, 0x0d, 0xd8, 0x27, 0x9b, 0x77, 0x71, 0xfa, 0x74, 0xb8, 0xc3, 0x5d, 0xa1, 0x3f, 0xd8, 0x6c, 0x7d, 0xc2, 0x52, 0x0b, 0x72, 0x5e, 0x3d, 0xed, 0x0b, 0x6b, 0xf9, 0x8c, 0x14, 0x9c, 0x11, 0x60, 0x95, 0x37, 0x25, 0x06, 0xe0, 0xa3, 0x59, 0xc0, 0xd1, 0x30, 0x12, 0x1b, 0x4e, 0xf9, 0x32, 0xcc, 0x6d, 0xdb, 0x16, 0x3b, 0xbd, 0xb8, 0x4a, 0x05, 0x90, 0x3a, 0x25, 0x09, 0xb3, 0x27, 0xa9, 0x53, 0xbe, 0x02, 0x20, 0xb4, 0x29, 0x20, 0xed, 0xb3, 0x36, 0xf4, 0x01, 0xd2, 0x7e, 0xf9, 0x26, 0xa4, 0xb7, 0x3a, 0xc7, 0x7b, 0x9d, 0x1e, 0xb9, 0x06, 0x30, 0xe8, 0x4c, 0x9c, 0xf6, 0x21, 0xee, 0xc3, 0xe7, 0x9f, 0x7f, 0xfe, 0xb9, 0x84, 0x97, 0xbd, 0x1c, 0xad, 0x65, 0xfb, 0xf1, 0x02, 0xa0, 0x35, 0xe8, 0x6e, 0x99, 0x93, 0x49, 0xa7, 0x67, 0x92, 0x2a, 0xa4, 0x2d, 0x73, 0x42, 0xa3, 0x9d, 0x84, 0xef, 0x08, 0xcb, 0xfe, 0x2a, 0xf8, 0xa8, 0x95, 0x6d, 0x84, 0x18, 0x1c, 0x4a, 0x14, 0x48, 0x58, 0x47, 0x43, 0x7c, 0x27, 0x49, 0x19, 0xf4, 0xe7, 0xd2, 0x25, 0x48, 0x33, 0x0c, 0x21, 0x90, 0xb4, 0x3a, 0x43, 0xb3, 0xc4, 0xfa, 0xc5, 0xdf, 0xe5, 0x5f, 0x95, 0x00, 0xb6, 0xcd, 0x97, 0x67, 0xe8, 0xd3, 0x47, 0xc5, 0xf4, 0x99, 0x60, 0x7d, 0xde, 0x8f, 0xeb, 0x93, 0xea, 0xec, 0xd0, 0xb6, 0xbb, 0x6d, 0xb6, 0xc5, 0xec, 0x49, 0x27, 0x47, 0x6b, 0x70, 0xd7, 0xca, 0x1f, 0x40, 0x61, 0xd3, 0xb2, 0xcc, 0xb1, 0x3b, 0x26, 0x02, 0xc9, 0x67, 0xf6, 0xc4, 0xe1, 0x6f, 0x4b, 0xf8, 0x9b, 0x94, 0x20, 0x39, 0xb2, 0xc7, 0x0e, 0x9b, 0x67, 0x3d, 0xa9, 0xaf, 0xae, 0xae, 0x1a, 0x58, 0x43, 0x2e, 0x41, 0xee, 0xc0, 0xb6, 0x2c, 0xf3, 0x80, 0x4e, 0x22, 0x81, 0x69, 0x8d, 0x5f, 0x51, 0xfe, 0x65, 0x09, 0x0a, 0x2d, 0xe7, 0x99, 0x6f, 0x5c, 0x81, 0xc4, 0x73, 0xf3, 0x04, 0x87, 0x97, 0x30, 0xe8, 0x4f, 0x7a, 0x54, 0x7e, 0xbe, 0x33, 0x38, 0x62, 0x6f, 0x4d, 0x05, 0x83, 0x15, 0xc8, 0x05, 0x48, 0xbf, 0x34, 0xfb, 0xbd, 0x67, 0x0e, 0xda, 0x94, 0x0d, 0x5e, 0x22, 0xb7, 0x20, 0xd5, 0xa7, 0x83, 0x2d, 0x25, 0x71, 0xbd, 0x2e, 0xf8, 0xeb, 0x25, 0xce, 0xc1, 0x60, 0xa0, 0x1b, 0xd9, 0x6c, 0x57, 0xf9, 0xe8, 0xa3, 0x8f, 0x3e, 0x92, 0xcb, 0x87, 0xb0, 0xe8, 0x1e, 0xde, 0xc0, 0x64, 0xb7, 0xa1, 0x34, 0x30, 0xed, 0xf6, 0x61, 0xdf, 0xea, 0x0c, 0x06, 0x27, 0xed, 0x97, 0xb6, 0xd5, 0xee, 0x58, 0x6d, 0x7b, 0x72, 0xd0, 0x19, 0xe3, 0x02, 0x44, 0x77, 0xb1, 0x38, 0x30, 0xed, 0x26, 0xa3, 0xbd, 0x6f, 0x5b, 0x0f, 0xac, 0x16, 0xe5, 0x94, 0xff, 0x20, 0x09, 0xb9, 0xad, 0x13, 0xd7, 0xfa, 0x22, 0xa4, 0x0e, 0xec, 0x23, 0x8b, 0xad, 0x65, 0xca, 0x60, 0x05, 0x6f, 0x8f, 0x64, 0x61, 0x8f, 0x16, 0x21, 0xf5, 0xe2, 0xc8, 0x76, 0x4c, 0x9c, 0x6e, 0xce, 0x60, 0x05, 0xba, 0x5a, 0x23, 0xd3, 0x29, 0x25, 0x31, 0xb9, 0xa5, 0x3f, 0xfd, 0xf9, 0xa7, 0xce, 0x30, 0x7f, 0xb2, 0x02, 0x69, 0x9b, 0xae, 0xfe, 0xa4, 0x94, 0xc6, 0x77, 0x35, 0x01, 0x2e, 0xee, 0x8a, 0xc1, 0x51, 0x64, 0x13, 0x16, 0x5e, 0x9a, 0xed, 0xe1, 0xd1, 0xc4, 0x69, 0xf7, 0xec, 0x76, 0xd7, 0x34, 0x47, 0xe6, 0xb8, 0x34, 0x87, 0x3d, 0x09, 0x3e, 0x61, 0xd6, 0x42, 0x1a, 0xf3, 0x2f, 0xcd, 0xad, 0xa3, 0x89, 0xb3, 0x61, 0x3f, 0x46, 0x16, 0xa9, 0x42, 0x6e, 0x6c, 0x52, 0x4f, 0x40, 0x07, 0x5b, 0x08, 0xf7, 0x1e, 0xa0, 0x66, 0xc7, 0xe6, 0x08, 0x2b, 0xc8, 0x3a, 0x64, 0xf7, 0xfb, 0xcf, 0xcd, 0xc9, 0x33, 0xb3, 0x5b, 0xca, 0xa8, 0x52, 0x65, 0x5e, 0xbb, 0xe8, 0x73, 0xbc, 0x65, 0x5d, 0x79, 0x64, 0x0f, 0xec, 0xb1, 0xe1, 0x41, 0xc9, 0x7d, 0xc8, 0x4d, 0xec, 0xa1, 0xc9, 0xf4, 0x9d, 0xc5, 0xa0, 0x7a, 0x79, 0x16, 0x6f, 0xd7, 0x1e, 0x9a, 0xae, 0x07, 0x73, 0xf1, 0x64, 0x99, 0x0d, 0x74, 0x9f, 0x5e, 0x9d, 0x4b, 0x80, 0x4f, 0x03, 0x74, 0x40, 0x78, 0x95, 0x26, 0x4b, 0x74, 0x40, 0xbd, 0x43, 0x7a, 0x23, 0x2a, 0xe5, 0x31, 0xaf, 0xf4, 0xca, 0x4b, 0xb7, 0x20, 0xe7, 0x19, 0xf4, 0x5d, 0x1f, 0x73, 0x37, 0x39, 0xf4, 0x07, 0xcc, 0xf5, 0x31, 0x5f, 0xf3, 0x06, 0xa4, 0x70, 0xd8, 0x34, 0x42, 0x19, 0x0d, 0x1a, 0x10, 0x73, 0x90, 0xda, 0x30, 0x1a, 0x8d, 0x6d, 0x45, 0xc2, 0xd8, 0xf8, 0xf4, 0xdd, 0x86, 0x22, 0x0b, 0x8a, 0xfd, 0x6d, 0x09, 0x12, 0x8d, 0x63, 0x54, 0x0b, 0x9d, 0x86, 0x7b, 0xa2, 0xe9, 0x6f, 0xad, 0x06, 0xc9, 0xa1, 0x3d, 0x36, 0xc9, 0xf9, 0x19, 0xb3, 0x2c, 0xf5, 0x70, 0xbf, 0x84, 0x57, 0xe4, 0xc6, 0xb1, 0x63, 0x20, 0x5e, 0x7b, 0x0b, 0x92, 0x8e, 0x79, 0xec, 0xcc, 0xe6, 0x3d, 0x63, 0x1d, 0x50, 0x80, 0x76, 0x13, 0xd2, 0xd6, 0xd1, 0x70, 0xdf, 0x1c, 0xcf, 0x86, 0xf6, 0x71, 0x7a, 0x1c, 0x52, 0x7e, 0x0f, 0x94, 0x47, 0xf6, 0x70, 0x34, 0x30, 0x8f, 0x1b, 0xc7, 0x8e, 0x69, 0x4d, 0xfa, 0xb6, 0x45, 0xf5, 0x7c, 0xd8, 0x1f, 0xa3, 0x17, 0xc1, 0xb7, 0x62, 0x2c, 0xd0, 0x53, 0x3d, 0x31, 0x0f, 0x6c, 0xab, 0xcb, 0x1d, 0x26, 0x2f, 0x51, 0xb4, 0xf3, 0xac, 0x3f, 0xa6, 0x0e, 0x84, 0xfa, 0x79, 0x56, 0x28, 0x6f, 0x40, 0x91, 0xe7, 0x18, 0x13, 0xde, 0x71, 0xf9, 0x06, 0x14, 0xdc, 0x2a, 0x7c, 0x38, 0xcf, 0x42, 0xf2, 0x83, 0x86, 0xd1, 0x52, 0xce, 0xd1, 0x65, 0x6d, 0x6d, 0x37, 0x14, 0x89, 0xfe, 0xd8, 0x7b, 0xbf, 0x15, 0x58, 0xca, 0x4b, 0x50, 0xf0, 0xc6, 0xbe, 0x6b, 0x3a, 0xd8, 0x42, 0x03, 0x42, 0xa6, 0x2e, 0x67, 0xa5, 0x72, 0x06, 0x52, 0x8d, 0xe1, 0xc8, 0x39, 0x29, 0xff, 0x22, 0xe4, 0x39, 0xe8, 0x69, 0x7f, 0xe2, 0x90, 0x3b, 0x90, 0x19, 0xf2, 0xf9, 0x4a, 0x78, 0xdd, 0x13, 0x35, 0xe5, 0xe3, 0xdc, 0xdf, 0x86, 0x8b, 0x5e, 0xaa, 0x42, 0x46, 0xf0, 0xa5, 0xfc, 0xa8, 0xcb, 0xe2, 0x51, 0x67, 0x4e, 0x21, 0x21, 0x38, 0x85, 0xf2, 0x16, 0x64, 0x58, 0x04, 0x9c, 0x60, 0x54, 0x67, 0xa9, 0x22, 0x13, 0x13, 0xdb, 0xf9, 0x3c, 0xab, 0x63, 0x17, 0x95, 0xab, 0x90, 0x47, 0xc1, 0x72, 0x04, 0x73, 0x9d, 0x80, 0x55, 0x4c, 0x6e, 0xbf, 0x9f, 0x82, 0xac, 0xbb, 0x52, 0x64, 0x19, 0xd2, 0x2c, 0x3f, 0x43, 0x53, 0xee, 0xfb, 0x41, 0x0a, 0x33, 0x32, 0xb2, 0x0c, 0x19, 0x9e, 0x83, 0x71, 0xef, 0x2e, 0x57, 0x35, 0x23, 0xcd, 0x72, 0x2e, 0xaf, 0xb1, 0xa6, 0xa3, 0x63, 0x62, 0x2f, 0x03, 0x69, 0x96, 0x55, 0x11, 0x15, 0x72, 0x5e, 0x1e, 0x85, 0xfe, 0x98, 0x3f, 0x03, 0x64, 0xdd, 0xc4, 0x49, 0x40, 0xd4, 0x74, 0xf4, 0x58, 0x3c, 0xe7, 0xcf, 0x36, 0xfd, 0xeb, 0x49, 0xd6, 0xcd, 0x86, 0xf0, 0xf9, 0xde, 0x4d, 0xf0, 0x33, 0x3c, 0xff, 0xf1, 0x01, 0x35, 0x1d, 0x5d, 0x82, 0x9b, 0xcd, 0x67, 0x78, 0x8e, 0x43, 0xae, 0xd2, 0x21, 0x62, 0xce, 0x82, 0x47, 0xdf, 0x4f, 0xdd, 0xd3, 0x2c, 0x93, 0x21, 0xd7, 0xa8, 0x05, 0x96, 0x98, 0xe0, 0xb9, 0xf4, 0xf3, 0xf4, 0x0c, 0xcf, 0x57, 0xc8, 0x4d, 0x0a, 0x61, 0xcb, 0x5f, 0x82, 0x88, 0xa4, 0x3c, 0xc3, 0x93, 0x72, 0xa2, 0xd2, 0x0e, 0xd1, 0x3d, 0xa0, 0x4b, 0x10, 0x12, 0xf0, 0x34, 0x4b, 0xc0, 0xc9, 0x15, 0x34, 0xc7, 0x26, 0x55, 0xf0, 0x93, 0xed, 0x0c, 0x4f, 0x70, 0xfc, 0x76, 0xbc, 0xb2, 0x79, 0x89, 0x75, 0x86, 0xa7, 0x30, 0xa4, 0x46, 0xf7, 0x8b, 0xea, 0xbb, 0x34, 0x8f, 0x4e, 0xb0, 0xe4, 0x0b, 0xcf, 0xdd, 0x53, 0xe6, 0x03, 0xeb, 0xcc, 0x83, 0x18, 0xa9, 0x26, 0x9e, 0x86, 0x25, 0xca, 0xdb, 0xe9, 0x5b, 0x87, 0xa5, 0x22, 0xae, 0x44, 0xa2, 0x6f, 0x1d, 0x1a, 0xa9, 0x26, 0xad, 0x61, 0x1a, 0xd8, 0xa6, 0x6d, 0x0a, 0xb6, 0x25, 0x6f, 0xb3, 0x46, 0x5a, 0x45, 0x4a, 0x90, 0x6a, 0xb6, 0xb7, 0x3b, 0x56, 0x69, 0x81, 0xf1, 0xac, 0x8e, 0x65, 0x24, 0x9b, 0xdb, 0x1d, 0x8b, 0xbc, 0x05, 0x89, 0xc9, 0xd1, 0x7e, 0x89, 0x84, 0xbf, 0xac, 0xec, 0x1e, 0xed, 0xbb, 0x43, 0x31, 0x28, 0x82, 0x2c, 0x43, 0x76, 0xe2, 0x8c, 0xdb, 0xbf, 0x60, 0x8e, 0xed, 0xd2, 0x79, 0x5c, 0xc2, 0x73, 0x46, 0x66, 0xe2, 0x8c, 0x3f, 0x30, 0xc7, 0xf6, 0x19, 0x9d, 0x5f, 0xf9, 0x0a, 0xe4, 0x05, 0xbb, 0xa4, 0x08, 0x92, 0xc5, 0x6e, 0x0a, 0x75, 0xe9, 0x8e, 0x21, 0x59, 0xe5, 0x3d, 0x28, 0xb8, 0x39, 0x0c, 0xce, 0x57, 0xa3, 0x27, 0x69, 0x60, 0x8f, 0xf1, 0x7c, 0xce, 0x6b, 0x97, 0xc4, 0x10, 0xe5, 0xc3, 0x78, 0xb8, 0x60, 0xd0, 0xb2, 0x12, 0x1a, 0x8a, 0x54, 0xfe, 0xa1, 0x04, 0x85, 0x2d, 0x7b, 0xec, 0x3f, 0x30, 0x2f, 0x42, 0x6a, 0xdf, 0xb6, 0x07, 0x13, 0x34, 0x9b, 0x35, 0x58, 0x81, 0xbc, 0x01, 0x05, 0xfc, 0xe1, 0xe6, 0x9e, 0xb2, 0xf7, 0xb4, 0x91, 0xc7, 0x7a, 0x9e, 0x70, 0x12, 0x48, 0xf6, 0x2d, 0x67, 0xc2, 0x3d, 0x19, 0xfe, 0x26, 0x5f, 0x80, 0x3c, 0xfd, 0xeb, 0x32, 0x93, 0xde, 0x85, 0x15, 0x68, 0x35, 0x27, 0xbe, 0x05, 0x73, 0xb8, 0xfb, 0x1e, 0x2c, 0xe3, 0x3d, 0x63, 0x14, 0x58, 0x03, 0x07, 0x96, 0x20, 0xc3, 0x5c, 0xc1, 0x04, 0xbf, 0x96, 0xe5, 0x0c, 0xb7, 0x48, 0xdd, 0x2b, 0x66, 0x02, 0x2c, 0xdc, 0x67, 0x0c, 0x5e, 0x2a, 0x3f, 0x80, 0x2c, 0x46, 0xa9, 0xd6, 0xa0, 0x4b, 0xca, 0x20, 0xf5, 0x4a, 0x26, 0xc6, 0xc8, 0x45, 0xe1, 0x9a, 0xcf, 0x9b, 0x57, 0x36, 0x0c, 0xa9, 0xb7, 0xb4, 0x00, 0xd2, 0x06, 0xbd, 0x77, 0x1f, 0x73, 0x37, 0x2d, 0x1d, 0x97, 0x5b, 0xdc, 0xc4, 0xb6, 0xf9, 0x32, 0xce, 0xc4, 0xb6, 0xf9, 0x92, 0x99, 0xb8, 0x3a, 0x65, 0x82, 0x96, 0x4e, 0xf8, 0xa7, 0x43, 0xe9, 0xa4, 0x5c, 0x85, 0x39, 0x3c, 0x9e, 0x7d, 0xab, 0xb7, 0x63, 0xf7, 0x2d, 0xbc, 0xe7, 0x1f, 0xe2, 0x3d, 0x49, 0x32, 0xa4, 0x43, 0xba, 0x07, 0xe6, 0x71, 0xe7, 0x80, 0xdd, 0x38, 0xb3, 0x06, 0x2b, 0x94, 0x3f, 0x4b, 0xc2, 0x3c, 0x77, 0xad, 0xef, 0xf7, 0x9d, 0x67, 0x5b, 0x9d, 0x11, 0x79, 0x0a, 0x05, 0xea, 0x55, 0xdb, 0xc3, 0xce, 0x68, 0x44, 0x8f, 0xaf, 0x84, 0x57, 0x8d, 0xeb, 0x53, 0xae, 0x9a, 0xe3, 0x57, 0xb6, 0x3b, 0x43, 0x73, 0x8b, 0x61, 0x1b, 0x96, 0x33, 0x3e, 0x31, 0xf2, 0x96, 0x5f, 0x43, 0x36, 0x21, 0x3f, 0x9c, 0xf4, 0x3c, 0x63, 0x32, 0x1a, 0xab, 0x44, 0x1a, 0xdb, 0x9a, 0xf4, 0x02, 0xb6, 0x60, 0xe8, 0x55, 0xd0, 0x81, 0x51, 0x7f, 0xec, 0xd9, 0x4a, 0x9c, 0x32, 0x30, 0xea, 0x3a, 0x82, 0x03, 0xdb, 0xf7, 0x6b, 0xc8, 0x63, 0x00, 0x7a, 0xbc, 0x1c, 0x9b, 0xa6, 0x4e, 0xa8, 0xa0, 0xbc, 0xf6, 0x66, 0xa4, 0xad, 0x5d, 0x67, 0xbc, 0x67, 0xef, 0x3a, 0x63, 0x66, 0x88, 0x1e, 0x4c, 0x2c, 0x2e, 0xbd, 0x03, 0x4a, 0x78, 0xfe, 0xe2, 0x8d, 0x3c, 0x35, 0xe3, 0x46, 0x9e, 0xe3, 0x37, 0xf2, 0xba, 0x7c, 0x57, 0x5a, 0x7a, 0x0f, 0x8a, 0xa1, 0x29, 0x8b, 0x74, 0xc2, 0xe8, 0xb7, 0x45, 0x7a, 0x5e, 0x7b, 0x5d, 0xf8, 0x9c, 0x2d, 0x6e, 0xb8, 0x68, 0xf7, 0x1d, 0x50, 0xc2, 0xd3, 0x17, 0x0d, 0x67, 0x63, 0x32, 0x05, 0xe4, 0xdf, 0x87, 0xb9, 0xc0, 0x94, 0x45, 0x72, 0xee, 0x94, 0x49, 0x95, 0x7f, 0x29, 0x05, 0xa9, 0x96, 0x65, 0xda, 0x87, 0xe4, 0xf5, 0x60, 0x9c, 0x7c, 0x72, 0xce, 0x8d, 0x91, 0x17, 0x43, 0x31, 0xf2, 0xc9, 0x39, 0x2f, 0x42, 0x5e, 0x0c, 0x45, 0x48, 0xb7, 0xa9, 0xa6, 0x93, 0xcb, 0x53, 0xf1, 0xf1, 0xc9, 0x39, 0x21, 0x38, 0x5e, 0x9e, 0x0a, 0x8e, 0x7e, 0x73, 0x4d, 0xa7, 0x0e, 0x35, 0x18, 0x19, 0x9f, 0x9c, 0xf3, 0xa3, 0xe2, 0x72, 0x38, 0x2a, 0x7a, 0x8d, 0x35, 0x9d, 0x0d, 0x49, 0x88, 0x88, 0x38, 0x24, 0x16, 0x0b, 0x97, 0xc3, 0xb1, 0x10, 0x79, 0x3c, 0x0a, 0x2e, 0x87, 0xa3, 0x20, 0x36, 0xf2, 0xa8, 0x77, 0x31, 0x14, 0xf5, 0xd0, 0x28, 0x0b, 0x77, 0xcb, 0xe1, 0x70, 0xc7, 0x78, 0xc2, 0x48, 0xc5, 0x58, 0xe7, 0x35, 0xd6, 0x74, 0xa2, 0x85, 0x02, 0x5d, 0xf4, 0x6d, 0x1f, 0xf7, 0x02, 0x9d, 0xbe, 0x4e, 0x97, 0xcd, 0xbd, 0x88, 0x16, 0x63, 0xbe, 0xf8, 0xe3, 0x6a, 0xba, 0x17, 0x31, 0x0d, 0x32, 0x87, 0x3c, 0x01, 0x56, 0xd0, 0x73, 0x09, 0xb2, 0xc4, 0xcd, 0x5f, 0x69, 0xb6, 0xd1, 0x83, 0xd1, 0x79, 0x1d, 0xb2, 0x3b, 0x7d, 0x05, 0xe6, 0x9a, 0xed, 0xa7, 0x9d, 0x71, 0xcf, 0x9c, 0x38, 0xed, 0xbd, 0x4e, 0xcf, 0x7b, 0x44, 0xa0, 0xfb, 0x9f, 0x6f, 0xf2, 0x96, 0xbd, 0x4e, 0x8f, 0x5c, 0x70, 0xc5, 0xd5, 0xc5, 0x56, 0x89, 0xcb, 0x6b, 0xe9, 0x75, 0xba, 0x68, 0xcc, 0x18, 0xfa, 0xc2, 0x05, 0xee, 0x0b, 0x1f, 0x66, 0x20, 0x75, 0x64, 0xf5, 0x6d, 0xeb, 0x61, 0x0e, 0x32, 0x8e, 0x3d, 0x1e, 0x76, 0x1c, 0xbb, 0xfc, 0x23, 0x09, 0xe0, 0x91, 0x3d, 0x1c, 0x1e, 0x59, 0xfd, 0x17, 0x47, 0x26, 0xb9, 0x02, 0xf9, 0x61, 0xe7, 0xb9, 0xd9, 0x1e, 0x9a, 0xed, 0x83, 0xb1, 0x7b, 0x0e, 0x72, 0xb4, 0x6a, 0xcb, 0x7c, 0x34, 0x3e, 0x21, 0x25, 0xf7, 0x8a, 0x8e, 0xda, 0x41, 0x49, 0xf2, 0x2b, 0xfb, 0x22, 0xbf, 0x74, 0xa6, 0xf9, 0x1e, 0xba, 0xd7, 0x4e, 0x96, 0x47, 0x64, 0xf8, 0xee, 0x61, 0x89, 0x4a, 0xde, 0x31, 0x87, 0xa3, 0xf6, 0x01, 0x4a, 0x85, 0xca, 0x21, 0x45, 0xcb, 0x8f, 0xc8, 0x6d, 0x48, 0x1c, 0xd8, 0x03, 0x14, 0xc9, 0x29, 0xfb, 0x42, 0x71, 0xe4, 0x0d, 0x48, 0x0c, 0x27, 0x4c, 0x36, 0x79, 0x6d, 0x41, 0xb8, 0x27, 0xb0, 0xd0, 0x44, 0x61, 0xc3, 0x49, 0xcf, 0x9b, 0xf7, 0x8d, 0x22, 0x24, 0x9a, 0xad, 0x16, 0x8d, 0xfd, 0xcd, 0x56, 0x6b, 0x4d, 0x91, 0xea, 0x5f, 0x82, 0x6c, 0x6f, 0x6c, 0x9a, 0xd4, 0x3d, 0xcc, 0xce, 0x39, 0x3e, 0xc4, 0x58, 0xe7, 0x81, 0xea, 0x5b, 0x90, 0x39, 0x60, 0x59, 0x07, 0x89, 0x48, 0x6b, 0x4b, 0x7f, 0xc8, 0x1e, 0x55, 0x96, 0xfc, 0xe6, 0x70, 0x9e, 0x62, 0xb8, 0x36, 0xea, 0x3b, 0x90, 0x1b, 0xb7, 0x4f, 0x33, 0xf8, 0x31, 0x8b, 0x2e, 0x71, 0x06, 0xb3, 0x63, 0x5e, 0x55, 0x6f, 0xc0, 0x82, 0x65, 0xbb, 0xdf, 0x50, 0xda, 0x5d, 0x76, 0xc6, 0x2e, 0x4e, 0x5f, 0xe5, 0x5c, 0xe3, 0x26, 0xfb, 0x6e, 0x69, 0xd9, 0xbc, 0x81, 0x9d, 0xca, 0xfa, 0x23, 0x50, 0x04, 0x33, 0x98, 0x7a, 0xc6, 0x59, 0x39, 0x64, 0x1f, 0x4a, 0x3d, 0x2b, 0x78, 0xee, 0x43, 0x46, 0xd8, 0xc9, 0x8c, 0x31, 0xd2, 0x63, 0x5f, 0x9d, 0x3d, 0x23, 0xe8, 0xea, 0xa6, 0x8d, 0x50, 0x5f, 0x13, 0x6d, 0xe4, 0x19, 0xfb, 0x20, 0x2d, 0x1a, 0xa9, 0xe9, 0xa1, 0x55, 0x39, 0x3a, 0x75, 0x28, 0x7d, 0xf6, 0x3d, 0xd9, 0xb3, 0xc2, 0x1c, 0xe0, 0x0c, 0x33, 0xf1, 0x83, 0xf9, 0x90, 0x7d, 0x6a, 0x0e, 0x98, 0x99, 0x1a, 0xcd, 0xe4, 0xd4, 0xd1, 0x3c, 0x67, 0xdf, 0x75, 0x3d, 0x33, 0xbb, 0xb3, 0x46, 0x33, 0x39, 0x75, 0x34, 0x03, 0xf6, 0xc5, 0x37, 0x60, 0xa6, 0xa6, 0xd7, 0x37, 0x80, 0x88, 0x5b, 0xcd, 0xe3, 0x44, 0x8c, 0x9d, 0x21, 0xfb, 0x8e, 0xef, 0x6f, 0x36, 0xa3, 0xcc, 0x32, 0x14, 0x3f, 0x20, 0x8b, 0x7d, 0xe2, 0x0f, 0x1a, 0xaa, 0xe9, 0xf5, 0x4d, 0x38, 0x2f, 0x4e, 0xec, 0x0c, 0x43, 0xb2, 0x55, 0xa9, 0x52, 0x34, 0x16, 0xfc, 0xa9, 0x71, 0xce, 0x4c, 0x53, 0xf1, 0x83, 0x1a, 0xa9, 0x52, 0x45, 0x99, 0x32, 0x55, 0xd3, 0xeb, 0x0f, 0xa0, 0x28, 0x98, 0xda, 0xc7, 0x08, 0x1d, 0x6d, 0xe6, 0x05, 0xfb, 0x5f, 0x0b, 0xcf, 0x0c, 0x8d, 0xe8, 0xe1, 0x1d, 0xe3, 0x31, 0x2e, 0xda, 0xc8, 0x98, 0xfd, 0xa3, 0x80, 0x3f, 0x16, 0x64, 0x84, 0x8e, 0x04, 0xe6, 0xdf, 0x71, 0x56, 0x26, 0xec, 0x5f, 0x08, 0xfc, 0xa1, 0x50, 0x42, 0xbd, 0x1f, 0x98, 0x8e, 0x49, 0x83, 0x5c, 0x8c, 0x0d, 0x07, 0x3d, 0xf2, 0x9b, 0x91, 0x80, 0x15, 0xf1, 0x81, 0x44, 0x98, 0x36, 0x2d, 0xd6, 0x37, 0x61, 0xfe, 0xec, 0x0e, 0xe9, 0x63, 0x89, 0x65, 0xcb, 0xd5, 0x15, 0x9a, 0x50, 0x1b, 0x73, 0xdd, 0x80, 0x5f, 0x6a, 0xc0, 0xdc, 0x99, 0x9d, 0xd2, 0x27, 0x12, 0xcb, 0x39, 0xa9, 0x25, 0xa3, 0xd0, 0x0d, 0x7a, 0xa6, 0xb9, 0x33, 0xbb, 0xa5, 0x4f, 0x25, 0xf6, 0x40, 0xa1, 0x6b, 0x9e, 0x11, 0xd7, 0x33, 0xcd, 0x9d, 0xd9, 0x2d, 0x7d, 0x95, 0x65, 0x94, 0xb2, 0x5e, 0x15, 0x8d, 0xa0, 0x2f, 0x98, 0x3f, 0xbb, 0x5b, 0xfa, 0x9a, 0x84, 0x8f, 0x15, 0xb2, 0xae, 0x7b, 0xeb, 0xe2, 0x79, 0xa6, 0xf9, 0xb3, 0xbb, 0xa5, 0xaf, 0x4b, 0xf8, 0xa4, 0x21, 0xeb, 0xeb, 0x01, 0x33, 0xc1, 0xd1, 0x9c, 0xee, 0x96, 0xbe, 0x21, 0xe1, 0x2b, 0x83, 0xac, 0xd7, 0x3c, 0x33, 0xbb, 0x53, 0xa3, 0x39, 0xdd, 0x2d, 0x7d, 0x13, 0x6f, 0xf1, 0x75, 0x59, 0xbf, 0x13, 0x30, 0x83, 0x9e, 0xa9, 0xf8, 0x0a, 0x6e, 0xe9, 0x5b, 0x12, 0x3e, 0x06, 0xc9, 0xfa, 0x5d, 0xc3, 0xed, 0xdd, 0xf7, 0x4c, 0xc5, 0x57, 0x70, 0x4b, 0x9f, 0x49, 0xf8, 0x66, 0x24, 0xeb, 0xf7, 0x82, 0x86, 0xd0, 0x33, 0x29, 0xaf, 0xe2, 0x96, 0xbe, 0x4d, 0x2d, 0x15, 0xeb, 0xf2, 0xfa, 0xaa, 0xe1, 0x0e, 0x40, 0xf0, 0x4c, 0xca, 0xab, 0xb8, 0xa5, 0xef, 0x50, 0x53, 0x4a, 0x5d, 0x5e, 0x5f, 0x0b, 0x99, 0xaa, 0xe9, 0xf5, 0x47, 0x50, 0x38, 0xab, 0x5b, 0xfa, 0xae, 0xf8, 0x16, 0x97, 0xef, 0x0a, 0xbe, 0x69, 0x47, 0xd8, 0xb3, 0x53, 0x1d, 0xd3, 0xf7, 0x30, 0xc7, 0xa9, 0xcf, 0x3d, 0x61, 0xef, 0x55, 0x8c, 0xe0, 0x6f, 0x1f, 0x73, 0x53, 0x5b, 0xfe, 0xf9, 0x38, 0xd5, 0x47, 0x7d, 0x5f, 0xc2, 0x47, 0xad, 0x02, 0x37, 0x88, 0x78, 0xef, 0xa4, 0x30, 0x87, 0xf5, 0xa1, 0x3f, 0xcb, 0xd3, 0xbc, 0xd5, 0x0f, 0xa4, 0x57, 0x71, 0x57, 0xf5, 0x44, 0x6b, 0xbb, 0xe1, 0x2d, 0x06, 0xd6, 0xbc, 0x0d, 0xc9, 0x63, 0x6d, 0x75, 0x4d, 0xbc, 0x92, 0x89, 0x6f, 0xb9, 0xcc, 0x49, 0xe5, 0xb5, 0xa2, 0xf0, 0xdc, 0x3d, 0x1c, 0x39, 0x27, 0x06, 0xb2, 0x38, 0x5b, 0x8b, 0x64, 0x7f, 0x12, 0xc3, 0xd6, 0x38, 0xbb, 0x1a, 0xc9, 0xfe, 0x34, 0x86, 0x5d, 0xe5, 0x6c, 0x3d, 0x92, 0xfd, 0xd5, 0x18, 0xb6, 0xce, 0xd9, 0xeb, 0x91, 0xec, 0xaf, 0xc5, 0xb0, 0xd7, 0x39, 0xbb, 0x16, 0xc9, 0xfe, 0x7a, 0x0c, 0xbb, 0xc6, 0xd9, 0x77, 0x22, 0xd9, 0xdf, 0x88, 0x61, 0xdf, 0xe1, 0xec, 0xbb, 0x91, 0xec, 0x6f, 0xc6, 0xb0, 0xef, 0x72, 0xf6, 0xbd, 0x48, 0xf6, 0xb7, 0x62, 0xd8, 0xf7, 0x18, 0x7b, 0x6d, 0x35, 0x92, 0xfd, 0x59, 0x34, 0x7b, 0x6d, 0x95, 0xb3, 0xa3, 0xb5, 0xf6, 0xed, 0x18, 0x36, 0xd7, 0xda, 0x5a, 0xb4, 0xd6, 0xbe, 0x13, 0xc3, 0xe6, 0x5a, 0x5b, 0x8b, 0xd6, 0xda, 0x77, 0x63, 0xd8, 0x5c, 0x6b, 0x6b, 0xd1, 0x5a, 0xfb, 0x5e, 0x0c, 0x9b, 0x6b, 0x6d, 0x2d, 0x5a, 0x6b, 0xdf, 0x8f, 0x61, 0x73, 0xad, 0xad, 0x45, 0x6b, 0xed, 0x07, 0x31, 0x6c, 0xae, 0xb5, 0xb5, 0x68, 0xad, 0xfd, 0x51, 0x0c, 0x9b, 0x6b, 0x6d, 0x2d, 0x5a, 0x6b, 0x7f, 0x1c, 0xc3, 0xe6, 0x5a, 0x5b, 0x8b, 0xd6, 0xda, 0x9f, 0xc4, 0xb0, 0xb9, 0xd6, 0xb4, 0x68, 0xad, 0xfd, 0x69, 0x34, 0x5b, 0xe3, 0x5a, 0xd3, 0xa2, 0xb5, 0xf6, 0x67, 0x31, 0x6c, 0xae, 0x35, 0x2d, 0x5a, 0x6b, 0x7f, 0x1e, 0xc3, 0xe6, 0x5a, 0xd3, 0xa2, 0xb5, 0xf6, 0xc3, 0x18, 0x36, 0xd7, 0x9a, 0x16, 0xad, 0xb5, 0xbf, 0x88, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xcb, 0x18, 0x36, 0xd7, 0x9a, 0x16, 0xad, 0xb5, 0xbf, 0x8a, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xeb, 0x18, 0x36, 0xd7, 0x9a, 0x16, 0xad, 0xb5, 0xbf, 0x89, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xdb, 0x18, 0x36, 0xd7, 0x5a, 0x35, 0x5a, 0x6b, 0x7f, 0x17, 0xcd, 0xae, 0x72, 0xad, 0x55, 0xa3, 0xb5, 0xf6, 0xf7, 0x31, 0x6c, 0xae, 0xb5, 0x6a, 0xb4, 0xd6, 0xfe, 0x21, 0x86, 0xcd, 0xb5, 0x56, 0x8d, 0xd6, 0xda, 0x3f, 0xc6, 0xb0, 0xb9, 0xd6, 0xaa, 0xd1, 0x5a, 0xfb, 0x51, 0x0c, 0x9b, 0x6b, 0xad, 0x1a, 0xad, 0xb5, 0x7f, 0x8a, 0x61, 0x73, 0xad, 0x55, 0xa3, 0xb5, 0xf6, 0xcf, 0x31, 0x6c, 0xae, 0xb5, 0x6a, 0xb4, 0xd6, 0xfe, 0x25, 0x86, 0xcd, 0xb5, 0x56, 0x8d, 0xd6, 0xda, 0xbf, 0xc6, 0xb0, 0xb9, 0xd6, 0xaa, 0xd1, 0x5a, 0xfb, 0xb7, 0x18, 0x36, 0xd7, 0x9a, 0x1e, 0xad, 0xb5, 0x7f, 0x8f, 0x66, 0xeb, 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x23, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed, 0x3f, 0x63, 0xd8, 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x2b, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed, 0xbf, 0x63, 0xd8, 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x27, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed, 0xc7, 0x31, 0x6c, 0xae, 0x35, 0x3d, 0x5a, 0x6b, 0x3f, 0x89, 0x61, 0x73, 0xad, 0xe9, 0xd1, 0x5a, 0xfb, 0xdf, 0x18, 0x36, 0xd7, 0x9a, 0x1e, 0xad, 0xb5, 0xff, 0x8b, 0x61, 0x73, 0xad, 0xad, 0x47, 0x6b, 0xed, 0xff, 0xa3, 0xd9, 0xeb, 0xab, 0x3f, 0x0d, 0x00, 0x00, 0xff, 0xff, 0xaa, 0x00, 0xcd, 0x32, 0x57, 0x39, 0x00, 0x00, } ��������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/testdata/golden_test.go������������������������0000644�0610621�0607500�00000005560�13172163407�030214� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Verify that the compiler output for test.proto is unchanged. package testdata import ( "crypto/sha1" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "testing" ) // sum returns in string form (for easy comparison) the SHA-1 hash of the named file. func sum(t *testing.T, name string) string { data, err := ioutil.ReadFile(name) if err != nil { t.Fatal(err) } t.Logf("sum(%q): length is %d", name, len(data)) hash := sha1.New() _, err = hash.Write(data) if err != nil { t.Fatal(err) } return fmt.Sprintf("% x", hash.Sum(nil)) } func run(t *testing.T, name string, args ...string) { cmd := exec.Command(name, args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { t.Fatal(err) } } func TestGolden(t *testing.T) { // Compute the original checksum. goldenSum := sum(t, "test.pb.go") // Run the proto compiler. run(t, "protoc", "--go_out="+os.TempDir(), "test.proto") newFile := filepath.Join(os.TempDir(), "test.pb.go") defer os.Remove(newFile) // Compute the new checksum. newSum := sum(t, newFile) // Verify if newSum != goldenSum { run(t, "diff", "-u", "test.pb.go", newFile) t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") } } ������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/testdata/Makefile������������������������������0000644�0610621�0607500�00000003630�13172163407�027012� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. include ../../Make.protobuf all: regenerate regenerate: rm -f test.pb.go make test.pb.go # The following rules are just aids to development. Not needed for typical testing. diff: regenerate git diff test.pb.go restore: cp test.pb.go.golden test.pb.go preserve: cp test.pb.go test.pb.go.golden ��������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/size_test.go�����������������������������������0000644�0610621�0607500�00000017522�13172163407�026106� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "log" "strings" "testing" . "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} // messageWithExtension2 is in equal_test.go. var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} func init() { if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { log.Panicf("SetExtension: %v", err) } if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { log.Panicf("SetExtension: %v", err) } // Force messageWithExtension3 to have the extension encoded. Marshal(messageWithExtension3) } var SizeTests = []struct { desc string pb Message }{ {"empty", &pb.OtherMessage{}}, // Basic types. {"bool", &pb.Defaults{F_Bool: Bool(true)}}, {"int32", &pb.Defaults{F_Int32: Int32(12)}}, {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, {"float", &pb.Defaults{F_Float: Float32(12.6)}}, {"double", &pb.Defaults{F_Double: Float64(13.9)}}, {"string", &pb.Defaults{F_String: String("niles")}}, {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, // Repeated. {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ // Need enough large numbers to verify that the header is counting the number of bytes // for the field, not the number of elements. 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, }}}, {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, // Nested. {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, // Other things. {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, {"extension (unencoded)", messageWithExtension1}, {"extension (encoded)", messageWithExtension3}, // proto3 message {"proto3 empty", &proto3pb.Message{}}, {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, {"proto3 float", &proto3pb.Message{Score: 12.6}}, {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, {"oneof not set", &pb.Oneof{}}, {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}}, {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}}, {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}}, {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}}, {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}}, {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}}, {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}}, {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}}, {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}}, {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}}, {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}}, {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}}, {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}}, {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}}, {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}}, {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}}, {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}}, {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}}, {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}}, } func TestSize(t *testing.T) { for _, tc := range SizeTests { size := Size(tc.pb) b, err := Marshal(tc.pb) if err != nil { t.Errorf("%v: Marshal failed: %v", tc.desc, err) continue } if size != len(b) { t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) t.Logf("%v: bytes: %#v", tc.desc, b) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/size2_test.go����������������������������������0000644�0610621�0607500�00000004436�13172163407�026170� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto import ( "testing" ) // This is a separate file and package from size_test.go because that one uses // generated messages and thus may not be in package proto without having a circular // dependency, whereas this file tests unexported details of size.go. func TestVarintSize(t *testing.T) { // Check the edge cases carefully. testCases := []struct { n uint64 size int }{ {0, 1}, {1, 1}, {127, 1}, {128, 2}, {16383, 2}, {16384, 3}, {1<<63 - 1, 9}, {1 << 63, 10}, } for _, tc := range testCases { size := sizeVarint(tc.n) if size != tc.size { t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/proto3_test.go���������������������������������0000644�0610621�0607500�00000010402�13172163407�026350� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/proto/proto3_proto" tpb "github.com/golang/protobuf/proto/testdata" ) func TestProto3ZeroValues(t *testing.T) { tests := []struct { desc string m proto.Message }{ {"zero message", &pb.Message{}}, {"empty bytes field", &pb.Message{Data: []byte{}}}, } for _, test := range tests { b, err := proto.Marshal(test.m) if err != nil { t.Errorf("%s: proto.Marshal: %v", test.desc, err) continue } if len(b) > 0 { t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) } } } func TestRoundTripProto3(t *testing.T) { m := &pb.Message{ Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" ResultCount: 47, // (0 | 7<<3): 0x38 0x2f TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 Score: 8.1, // (5 | 9<<3): 0x4d <8.1> Key: []uint64{1, 0xdeadbeef}, Nested: &pb.Nested{ Bunny: "Monty", }, } t.Logf(" m: %v", m) b, err := proto.Marshal(m) if err != nil { t.Fatalf("proto.Marshal: %v", err) } t.Logf(" b: %q", b) m2 := new(pb.Message) if err := proto.Unmarshal(b, m2); err != nil { t.Fatalf("proto.Unmarshal: %v", err) } t.Logf("m2: %v", m2) if !proto.Equal(m, m2) { t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) } } func TestGettersForBasicTypesExist(t *testing.T) { var m pb.Message if got := m.GetNested().GetBunny(); got != "" { t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) } if got := m.GetNested().GetCute(); got { t.Errorf("m.GetNested().GetCute() = %t, want false", got) } } func TestProto3SetDefaults(t *testing.T) { in := &pb.Message{ Terrain: map[string]*pb.Nested{ "meadow": new(pb.Nested), }, Proto2Field: new(tpb.SubDefaults), Proto2Value: map[string]*tpb.SubDefaults{ "badlands": new(tpb.SubDefaults), }, } got := proto.Clone(in).(*pb.Message) proto.SetDefaults(got) // There are no defaults in proto3. Everything should be the zero value, but // we need to remember to set defaults for nested proto2 messages. want := &pb.Message{ Terrain: map[string]*pb.Nested{ "meadow": new(pb.Nested), }, Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, Proto2Value: map[string]*tpb.SubDefaults{ "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, }, } if !proto.Equal(got, want) { t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/proto3_proto/����������������������������������0000755�0610621�0607500�00000000000�13172163407�026210� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto����������������������0000644�0610621�0607500�00000005153�13172163407�030527� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; import "google/protobuf/any.proto"; import "testdata/test.proto"; package proto3_proto; message Message { enum Humour { UNKNOWN = 0; PUNS = 1; SLAPSTICK = 2; BILL_BAILEY = 3; } string name = 1; Humour hilarity = 2; uint32 height_in_cm = 3; bytes data = 4; int64 result_count = 7; bool true_scotsman = 8; float score = 9; repeated uint64 key = 5; repeated int32 short_key = 19; Nested nested = 6; repeated Humour r_funny = 16; map<string, Nested> terrain = 10; testdata.SubDefaults proto2_field = 11; map<string, testdata.SubDefaults> proto2_value = 13; google.protobuf.Any anything = 14; repeated google.protobuf.Any many_things = 15; Message submessage = 17; repeated Message children = 18; } message Nested { string bunny = 1; bool cute = 2; } message MessageWithMap { map<bool, bytes> byte_mapping = 1; } message IntMap { map<int32, int32> rtt = 1; } message IntMaps { repeated IntMap maps = 1; } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go����������������������0000644�0610621�0607500�00000032206�13172163407�030370� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. // source: proto3_proto/proto3.proto // DO NOT EDIT! /* Package proto3_proto is a generated protocol buffer package. It is generated from these files: proto3_proto/proto3.proto It has these top-level messages: Message Nested MessageWithMap IntMap IntMaps */ package proto3_proto import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/ptypes/any" import testdata "github.com/golang/protobuf/proto/testdata" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type Message_Humour int32 const ( Message_UNKNOWN Message_Humour = 0 Message_PUNS Message_Humour = 1 Message_SLAPSTICK Message_Humour = 2 Message_BILL_BAILEY Message_Humour = 3 ) var Message_Humour_name = map[int32]string{ 0: "UNKNOWN", 1: "PUNS", 2: "SLAPSTICK", 3: "BILL_BAILEY", } var Message_Humour_value = map[string]int32{ "UNKNOWN": 0, "PUNS": 1, "SLAPSTICK": 2, "BILL_BAILEY": 3, } func (x Message_Humour) String() string { return proto.EnumName(Message_Humour_name, int32(x)) } func (Message_Humour) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} } type Message struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"` HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm,json=heightInCm" json:"height_in_cm,omitempty"` Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` ResultCount int64 `protobuf:"varint,7,opt,name=result_count,json=resultCount" json:"result_count,omitempty"` TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman,json=trueScotsman" json:"true_scotsman,omitempty"` Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"` Key []uint64 `protobuf:"varint,5,rep,packed,name=key" json:"key,omitempty"` ShortKey []int32 `protobuf:"varint,19,rep,packed,name=short_key,json=shortKey" json:"short_key,omitempty"` Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"` RFunny []Message_Humour `protobuf:"varint,16,rep,packed,name=r_funny,json=rFunny,enum=proto3_proto.Message_Humour" json:"r_funny,omitempty"` Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field,json=proto2Field" json:"proto2_field,omitempty"` Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value,json=proto2Value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Anything *google_protobuf.Any `protobuf:"bytes,14,opt,name=anything" json:"anything,omitempty"` ManyThings []*google_protobuf.Any `protobuf:"bytes,15,rep,name=many_things,json=manyThings" json:"many_things,omitempty"` Submessage *Message `protobuf:"bytes,17,opt,name=submessage" json:"submessage,omitempty"` Children []*Message `protobuf:"bytes,18,rep,name=children" json:"children,omitempty"` } func (m *Message) Reset() { *m = Message{} } func (m *Message) String() string { return proto.CompactTextString(m) } func (*Message) ProtoMessage() {} func (*Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Message) GetName() string { if m != nil { return m.Name } return "" } func (m *Message) GetHilarity() Message_Humour { if m != nil { return m.Hilarity } return Message_UNKNOWN } func (m *Message) GetHeightInCm() uint32 { if m != nil { return m.HeightInCm } return 0 } func (m *Message) GetData() []byte { if m != nil { return m.Data } return nil } func (m *Message) GetResultCount() int64 { if m != nil { return m.ResultCount } return 0 } func (m *Message) GetTrueScotsman() bool { if m != nil { return m.TrueScotsman } return false } func (m *Message) GetScore() float32 { if m != nil { return m.Score } return 0 } func (m *Message) GetKey() []uint64 { if m != nil { return m.Key } return nil } func (m *Message) GetShortKey() []int32 { if m != nil { return m.ShortKey } return nil } func (m *Message) GetNested() *Nested { if m != nil { return m.Nested } return nil } func (m *Message) GetRFunny() []Message_Humour { if m != nil { return m.RFunny } return nil } func (m *Message) GetTerrain() map[string]*Nested { if m != nil { return m.Terrain } return nil } func (m *Message) GetProto2Field() *testdata.SubDefaults { if m != nil { return m.Proto2Field } return nil } func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults { if m != nil { return m.Proto2Value } return nil } func (m *Message) GetAnything() *google_protobuf.Any { if m != nil { return m.Anything } return nil } func (m *Message) GetManyThings() []*google_protobuf.Any { if m != nil { return m.ManyThings } return nil } func (m *Message) GetSubmessage() *Message { if m != nil { return m.Submessage } return nil } func (m *Message) GetChildren() []*Message { if m != nil { return m.Children } return nil } type Nested struct { Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"` Cute bool `protobuf:"varint,2,opt,name=cute" json:"cute,omitempty"` } func (m *Nested) Reset() { *m = Nested{} } func (m *Nested) String() string { return proto.CompactTextString(m) } func (*Nested) ProtoMessage() {} func (*Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *Nested) GetBunny() string { if m != nil { return m.Bunny } return "" } func (m *Nested) GetCute() bool { if m != nil { return m.Cute } return false } type MessageWithMap struct { ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` } func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } func (*MessageWithMap) ProtoMessage() {} func (*MessageWithMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *MessageWithMap) GetByteMapping() map[bool][]byte { if m != nil { return m.ByteMapping } return nil } type IntMap struct { Rtt map[int32]int32 `protobuf:"bytes,1,rep,name=rtt" json:"rtt,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` } func (m *IntMap) Reset() { *m = IntMap{} } func (m *IntMap) String() string { return proto.CompactTextString(m) } func (*IntMap) ProtoMessage() {} func (*IntMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *IntMap) GetRtt() map[int32]int32 { if m != nil { return m.Rtt } return nil } type IntMaps struct { Maps []*IntMap `protobuf:"bytes,1,rep,name=maps" json:"maps,omitempty"` } func (m *IntMaps) Reset() { *m = IntMaps{} } func (m *IntMaps) String() string { return proto.CompactTextString(m) } func (*IntMaps) ProtoMessage() {} func (*IntMaps) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *IntMaps) GetMaps() []*IntMap { if m != nil { return m.Maps } return nil } func init() { proto.RegisterType((*Message)(nil), "proto3_proto.Message") proto.RegisterType((*Nested)(nil), "proto3_proto.Nested") proto.RegisterType((*MessageWithMap)(nil), "proto3_proto.MessageWithMap") proto.RegisterType((*IntMap)(nil), "proto3_proto.IntMap") proto.RegisterType((*IntMaps)(nil), "proto3_proto.IntMaps") proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value) } func init() { proto.RegisterFile("proto3_proto/proto3.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 733 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x84, 0x53, 0x6d, 0x6f, 0xf3, 0x34, 0x14, 0x25, 0x4d, 0x5f, 0xd2, 0x9b, 0x74, 0x0b, 0x5e, 0x91, 0xbc, 0x02, 0x52, 0x28, 0x12, 0x8a, 0x78, 0x49, 0xa1, 0xd3, 0xd0, 0x84, 0x10, 0x68, 0x1b, 0x9b, 0xa8, 0xd6, 0x95, 0xca, 0xdd, 0x98, 0xf8, 0x14, 0xa5, 0xad, 0xdb, 0x46, 0x34, 0x4e, 0x49, 0x1c, 0xa4, 0xfc, 0x1d, 0xfe, 0x28, 0x8f, 0x6c, 0xa7, 0x5d, 0x36, 0x65, 0xcf, 0xf3, 0x29, 0xf6, 0xf1, 0xb9, 0xf7, 0x9c, 0x1c, 0x5f, 0xc3, 0xe9, 0x2e, 0x89, 0x79, 0x7c, 0xe6, 0xcb, 0xcf, 0x40, 0x6d, 0x3c, 0xf9, 0x41, 0x56, 0xf9, 0xa8, 0x77, 0xba, 0x8e, 0xe3, 0xf5, 0x96, 0x2a, 0xca, 0x3c, 0x5b, 0x0d, 0x02, 0x96, 0x2b, 0x62, 0xef, 0x84, 0xd3, 0x94, 0x2f, 0x03, 0x1e, 0x0c, 0xc4, 0x42, 0x81, 0xfd, 0xff, 0x5b, 0xd0, 0xba, 0xa7, 0x69, 0x1a, 0xac, 0x29, 0x42, 0x50, 0x67, 0x41, 0x44, 0xb1, 0xe6, 0x68, 0x6e, 0x9b, 0xc8, 0x35, 0xba, 0x00, 0x63, 0x13, 0x6e, 0x83, 0x24, 0xe4, 0x39, 0xae, 0x39, 0x9a, 0x7b, 0x34, 0xfc, 0xcc, 0x2b, 0x0b, 0x7a, 0x45, 0xb1, 0xf7, 0x7b, 0x16, 0xc5, 0x59, 0x42, 0x0e, 0x6c, 0xe4, 0x80, 0xb5, 0xa1, 0xe1, 0x7a, 0xc3, 0xfd, 0x90, 0xf9, 0x8b, 0x08, 0xeb, 0x8e, 0xe6, 0x76, 0x08, 0x28, 0x6c, 0xc4, 0xae, 0x23, 0xa1, 0x27, 0xec, 0xe0, 0xba, 0xa3, 0xb9, 0x16, 0x91, 0x6b, 0xf4, 0x05, 0x58, 0x09, 0x4d, 0xb3, 0x2d, 0xf7, 0x17, 0x71, 0xc6, 0x38, 0x6e, 0x39, 0x9a, 0xab, 0x13, 0x53, 0x61, 0xd7, 0x02, 0x42, 0x5f, 0x42, 0x87, 0x27, 0x19, 0xf5, 0xd3, 0x45, 0xcc, 0xd3, 0x28, 0x60, 0xd8, 0x70, 0x34, 0xd7, 0x20, 0x96, 0x00, 0x67, 0x05, 0x86, 0xba, 0xd0, 0x48, 0x17, 0x71, 0x42, 0x71, 0xdb, 0xd1, 0xdc, 0x1a, 0x51, 0x1b, 0x64, 0x83, 0xfe, 0x37, 0xcd, 0x71, 0xc3, 0xd1, 0xdd, 0x3a, 0x11, 0x4b, 0xf4, 0x29, 0xb4, 0xd3, 0x4d, 0x9c, 0x70, 0x5f, 0xe0, 0x27, 0x8e, 0xee, 0x36, 0x88, 0x21, 0x81, 0x3b, 0x9a, 0xa3, 0x6f, 0xa1, 0xc9, 0x68, 0xca, 0xe9, 0x12, 0x37, 0x1d, 0xcd, 0x35, 0x87, 0xdd, 0x97, 0xbf, 0x3e, 0x91, 0x67, 0xa4, 0xe0, 0xa0, 0x73, 0x68, 0x25, 0xfe, 0x2a, 0x63, 0x2c, 0xc7, 0xb6, 0xa3, 0x7f, 0x30, 0xa9, 0x66, 0x72, 0x2b, 0xb8, 0xe8, 0x67, 0x68, 0x71, 0x9a, 0x24, 0x41, 0xc8, 0x30, 0x38, 0xba, 0x6b, 0x0e, 0xfb, 0xd5, 0x65, 0x0f, 0x8a, 0x74, 0xc3, 0x78, 0x92, 0x93, 0x7d, 0x09, 0xba, 0x00, 0x75, 0xff, 0x43, 0x7f, 0x15, 0xd2, 0xed, 0x12, 0x9b, 0xd2, 0xe8, 0x27, 0xde, 0xfe, 0xae, 0xbd, 0x59, 0x36, 0xff, 0x8d, 0xae, 0x82, 0x6c, 0xcb, 0x53, 0x62, 0x2a, 0xea, 0xad, 0x60, 0xa2, 0xd1, 0xa1, 0xf2, 0xdf, 0x60, 0x9b, 0x51, 0xdc, 0x91, 0xe2, 0x5f, 0x55, 0x8b, 0x4f, 0x25, 0xf3, 0x4f, 0x41, 0x54, 0x06, 0x8a, 0x56, 0x12, 0x41, 0xdf, 0x83, 0x11, 0xb0, 0x9c, 0x6f, 0x42, 0xb6, 0xc6, 0x47, 0x45, 0x52, 0x6a, 0x0e, 0xbd, 0xfd, 0x1c, 0x7a, 0x97, 0x2c, 0x27, 0x07, 0x16, 0x3a, 0x07, 0x33, 0x0a, 0x58, 0xee, 0xcb, 0x5d, 0x8a, 0x8f, 0xa5, 0x76, 0x75, 0x11, 0x08, 0xe2, 0x83, 0xe4, 0xa1, 0x73, 0x80, 0x34, 0x9b, 0x47, 0xca, 0x14, 0xfe, 0xb8, 0xf8, 0xd7, 0x2a, 0xc7, 0xa4, 0x44, 0x44, 0x3f, 0x80, 0xb1, 0xd8, 0x84, 0xdb, 0x65, 0x42, 0x19, 0x46, 0x52, 0xea, 0x8d, 0xa2, 0x03, 0xad, 0x37, 0x05, 0xab, 0x1c, 0xf8, 0x7e, 0x72, 0xd4, 0xd3, 0x90, 0x93, 0xf3, 0x35, 0x34, 0x54, 0x70, 0xb5, 0xf7, 0xcc, 0x86, 0xa2, 0xfc, 0x54, 0xbb, 0xd0, 0x7a, 0x8f, 0x60, 0xbf, 0x4e, 0xb1, 0xa2, 0xeb, 0x37, 0x2f, 0xbb, 0xbe, 0x71, 0x91, 0xcf, 0x6d, 0xfb, 0xbf, 0x42, 0x53, 0x0d, 0x14, 0x32, 0xa1, 0xf5, 0x38, 0xb9, 0x9b, 0xfc, 0xf1, 0x34, 0xb1, 0x3f, 0x42, 0x06, 0xd4, 0xa7, 0x8f, 0x93, 0x99, 0xad, 0xa1, 0x0e, 0xb4, 0x67, 0xe3, 0xcb, 0xe9, 0xec, 0x61, 0x74, 0x7d, 0x67, 0xd7, 0xd0, 0x31, 0x98, 0x57, 0xa3, 0xf1, 0xd8, 0xbf, 0xba, 0x1c, 0x8d, 0x6f, 0xfe, 0xb2, 0xf5, 0xfe, 0x10, 0x9a, 0xca, 0xac, 0x78, 0x33, 0x73, 0x39, 0xbe, 0xca, 0x8f, 0xda, 0x88, 0x57, 0xba, 0xc8, 0xb8, 0x32, 0x64, 0x10, 0xb9, 0xee, 0xff, 0xa7, 0xc1, 0x51, 0x91, 0xd9, 0x53, 0xc8, 0x37, 0xf7, 0xc1, 0x0e, 0x4d, 0xc1, 0x9a, 0xe7, 0x9c, 0xfa, 0x51, 0xb0, 0xdb, 0x89, 0x39, 0xd0, 0x64, 0xce, 0xdf, 0x55, 0xe6, 0x5c, 0xd4, 0x78, 0x57, 0x39, 0xa7, 0xf7, 0x8a, 0x5f, 0x4c, 0xd5, 0xfc, 0x19, 0xe9, 0xfd, 0x02, 0xf6, 0x6b, 0x42, 0x39, 0x30, 0x43, 0x05, 0xd6, 0x2d, 0x07, 0x66, 0x95, 0x93, 0xf9, 0x07, 0x9a, 0x23, 0xc6, 0x85, 0xb7, 0x01, 0xe8, 0x09, 0xe7, 0x85, 0xa5, 0xcf, 0x5f, 0x5a, 0x52, 0x14, 0x8f, 0x70, 0xae, 0x2c, 0x08, 0x66, 0xef, 0x47, 0x30, 0xf6, 0x40, 0x59, 0xb2, 0x51, 0x21, 0xd9, 0x28, 0x4b, 0x9e, 0x41, 0x4b, 0xf5, 0x4b, 0x91, 0x0b, 0xf5, 0x28, 0xd8, 0xa5, 0x85, 0x68, 0xb7, 0x4a, 0x94, 0x48, 0xc6, 0xbc, 0xa9, 0x8e, 0xde, 0x05, 0x00, 0x00, 0xff, 0xff, 0x75, 0x38, 0xad, 0x84, 0xe4, 0x05, 0x00, 0x00, } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/properties.go����������������������������������0000644�0610621�0607500�00000062331�13172163407�026267� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto /* * Routines for encoding data into the wire format for protocol buffers. */ import ( "fmt" "log" "os" "reflect" "sort" "strconv" "strings" "sync" ) const debug bool = false // Constants that identify the encoding of a value on the wire. const ( WireVarint = 0 WireFixed64 = 1 WireBytes = 2 WireStartGroup = 3 WireEndGroup = 4 WireFixed32 = 5 ) const startSize = 10 // initial slice/string sizes // Encoders are defined in encode.go // An encoder outputs the full representation of a field, including its // tag and encoder type. type encoder func(p *Buffer, prop *Properties, base structPointer) error // A valueEncoder encodes a single integer in a particular encoding. type valueEncoder func(o *Buffer, x uint64) error // Sizers are defined in encode.go // A sizer returns the encoded size of a field, including its tag and encoder // type. type sizer func(prop *Properties, base structPointer) int // A valueSizer returns the encoded size of a single integer in a particular // encoding. type valueSizer func(x uint64) int // Decoders are defined in decode.go // A decoder creates a value from its wire representation. // Unrecognized subelements are saved in unrec. type decoder func(p *Buffer, prop *Properties, base structPointer) error // A valueDecoder decodes a single integer in a particular encoding. type valueDecoder func(o *Buffer) (x uint64, err error) // A oneofMarshaler does the marshaling for all oneof fields in a message. type oneofMarshaler func(Message, *Buffer) error // A oneofUnmarshaler does the unmarshaling for a oneof field in a message. type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error) // A oneofSizer does the sizing for all oneof fields in a message. type oneofSizer func(Message) int // tagMap is an optimization over map[int]int for typical protocol buffer // use-cases. Encoded protocol buffers are often in tag order with small tag // numbers. type tagMap struct { fastTags []int slowTags map[int]int } // tagMapFastLimit is the upper bound on the tag number that will be stored in // the tagMap slice rather than its map. const tagMapFastLimit = 1024 func (p *tagMap) get(t int) (int, bool) { if t > 0 && t < tagMapFastLimit { if t >= len(p.fastTags) { return 0, false } fi := p.fastTags[t] return fi, fi >= 0 } fi, ok := p.slowTags[t] return fi, ok } func (p *tagMap) put(t int, fi int) { if t > 0 && t < tagMapFastLimit { for len(p.fastTags) < t+1 { p.fastTags = append(p.fastTags, -1) } p.fastTags[t] = fi return } if p.slowTags == nil { p.slowTags = make(map[int]int) } p.slowTags[t] = fi } // StructProperties represents properties for all the fields of a struct. // decoderTags and decoderOrigNames should only be used by the decoder. type StructProperties struct { Prop []*Properties // properties for each field reqCount int // required count decoderTags tagMap // map from proto tag to struct field number decoderOrigNames map[string]int // map from original name to struct field number order []int // list of struct field numbers in tag order unrecField field // field id of the XXX_unrecognized []byte field extendable bool // is this an extendable proto oneofMarshaler oneofMarshaler oneofUnmarshaler oneofUnmarshaler oneofSizer oneofSizer stype reflect.Type // OneofTypes contains information about the oneof fields in this message. // It is keyed by the original name of a field. OneofTypes map[string]*OneofProperties } // OneofProperties represents information about a specific field in a oneof. type OneofProperties struct { Type reflect.Type // pointer to generated struct type for this oneof field Field int // struct field number of the containing oneof in the message Prop *Properties } // Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. // See encode.go, (*Buffer).enc_struct. func (sp *StructProperties) Len() int { return len(sp.order) } func (sp *StructProperties) Less(i, j int) bool { return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag } func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } // Properties represents the protocol-specific behavior of a single struct field. type Properties struct { Name string // name of the field, for error messages OrigName string // original name before protocol compiler (always set) JSONName string // name to use for JSON; determined by protoc Wire string WireType int Tag int Required bool Optional bool Repeated bool Packed bool // relevant for repeated primitives only Enum string // set for enum types only proto3 bool // whether this is known to be a proto3 field; set for []byte only oneof bool // whether this is a oneof field Default string // default value HasDefault bool // whether an explicit default was provided def_uint64 uint64 enc encoder valEnc valueEncoder // set for bool and numeric types only field field tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) tagbuf [8]byte stype reflect.Type // set for struct types only sprop *StructProperties // set for struct types only isMarshaler bool isUnmarshaler bool mtype reflect.Type // set for map types only mkeyprop *Properties // set for map types only mvalprop *Properties // set for map types only size sizer valSize valueSizer // set for bool and numeric types only dec decoder valDec valueDecoder // set for bool and numeric types only // If this is a packable field, this will be the decoder for the packed version of the field. packedDec decoder } // String formats the properties in the protobuf struct field tag style. func (p *Properties) String() string { s := p.Wire s = "," s += strconv.Itoa(p.Tag) if p.Required { s += ",req" } if p.Optional { s += ",opt" } if p.Repeated { s += ",rep" } if p.Packed { s += ",packed" } s += ",name=" + p.OrigName if p.JSONName != p.OrigName { s += ",json=" + p.JSONName } if p.proto3 { s += ",proto3" } if p.oneof { s += ",oneof" } if len(p.Enum) > 0 { s += ",enum=" + p.Enum } if p.HasDefault { s += ",def=" + p.Default } return s } // Parse populates p by parsing a string in the protobuf struct field tag style. func (p *Properties) Parse(s string) { // "bytes,49,opt,name=foo,def=hello!" fields := strings.Split(s, ",") // breaks def=, but handled below. if len(fields) < 2 { fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) return } p.Wire = fields[0] switch p.Wire { case "varint": p.WireType = WireVarint p.valEnc = (*Buffer).EncodeVarint p.valDec = (*Buffer).DecodeVarint p.valSize = sizeVarint case "fixed32": p.WireType = WireFixed32 p.valEnc = (*Buffer).EncodeFixed32 p.valDec = (*Buffer).DecodeFixed32 p.valSize = sizeFixed32 case "fixed64": p.WireType = WireFixed64 p.valEnc = (*Buffer).EncodeFixed64 p.valDec = (*Buffer).DecodeFixed64 p.valSize = sizeFixed64 case "zigzag32": p.WireType = WireVarint p.valEnc = (*Buffer).EncodeZigzag32 p.valDec = (*Buffer).DecodeZigzag32 p.valSize = sizeZigzag32 case "zigzag64": p.WireType = WireVarint p.valEnc = (*Buffer).EncodeZigzag64 p.valDec = (*Buffer).DecodeZigzag64 p.valSize = sizeZigzag64 case "bytes", "group": p.WireType = WireBytes // no numeric converter for non-numeric types default: fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) return } var err error p.Tag, err = strconv.Atoi(fields[1]) if err != nil { return } for i := 2; i < len(fields); i++ { f := fields[i] switch { case f == "req": p.Required = true case f == "opt": p.Optional = true case f == "rep": p.Repeated = true case f == "packed": p.Packed = true case strings.HasPrefix(f, "name="): p.OrigName = f[5:] case strings.HasPrefix(f, "json="): p.JSONName = f[5:] case strings.HasPrefix(f, "enum="): p.Enum = f[5:] case f == "proto3": p.proto3 = true case f == "oneof": p.oneof = true case strings.HasPrefix(f, "def="): p.HasDefault = true p.Default = f[4:] // rest of string if i+1 < len(fields) { // Commas aren't escaped, and def is always last. p.Default += "," + strings.Join(fields[i+1:], ",") break } } } } func logNoSliceEnc(t1, t2 reflect.Type) { fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) } var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() // Initialize the fields for encoding and decoding. func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { p.enc = nil p.dec = nil p.size = nil switch t1 := typ; t1.Kind() { default: fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) // proto3 scalar types case reflect.Bool: p.enc = (*Buffer).enc_proto3_bool p.dec = (*Buffer).dec_proto3_bool p.size = size_proto3_bool case reflect.Int32: p.enc = (*Buffer).enc_proto3_int32 p.dec = (*Buffer).dec_proto3_int32 p.size = size_proto3_int32 case reflect.Uint32: p.enc = (*Buffer).enc_proto3_uint32 p.dec = (*Buffer).dec_proto3_int32 // can reuse p.size = size_proto3_uint32 case reflect.Int64, reflect.Uint64: p.enc = (*Buffer).enc_proto3_int64 p.dec = (*Buffer).dec_proto3_int64 p.size = size_proto3_int64 case reflect.Float32: p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits p.dec = (*Buffer).dec_proto3_int32 p.size = size_proto3_uint32 case reflect.Float64: p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits p.dec = (*Buffer).dec_proto3_int64 p.size = size_proto3_int64 case reflect.String: p.enc = (*Buffer).enc_proto3_string p.dec = (*Buffer).dec_proto3_string p.size = size_proto3_string case reflect.Ptr: switch t2 := t1.Elem(); t2.Kind() { default: fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) break case reflect.Bool: p.enc = (*Buffer).enc_bool p.dec = (*Buffer).dec_bool p.size = size_bool case reflect.Int32: p.enc = (*Buffer).enc_int32 p.dec = (*Buffer).dec_int32 p.size = size_int32 case reflect.Uint32: p.enc = (*Buffer).enc_uint32 p.dec = (*Buffer).dec_int32 // can reuse p.size = size_uint32 case reflect.Int64, reflect.Uint64: p.enc = (*Buffer).enc_int64 p.dec = (*Buffer).dec_int64 p.size = size_int64 case reflect.Float32: p.enc = (*Buffer).enc_uint32 // can just treat them as bits p.dec = (*Buffer).dec_int32 p.size = size_uint32 case reflect.Float64: p.enc = (*Buffer).enc_int64 // can just treat them as bits p.dec = (*Buffer).dec_int64 p.size = size_int64 case reflect.String: p.enc = (*Buffer).enc_string p.dec = (*Buffer).dec_string p.size = size_string case reflect.Struct: p.stype = t1.Elem() p.isMarshaler = isMarshaler(t1) p.isUnmarshaler = isUnmarshaler(t1) if p.Wire == "bytes" { p.enc = (*Buffer).enc_struct_message p.dec = (*Buffer).dec_struct_message p.size = size_struct_message } else { p.enc = (*Buffer).enc_struct_group p.dec = (*Buffer).dec_struct_group p.size = size_struct_group } } case reflect.Slice: switch t2 := t1.Elem(); t2.Kind() { default: logNoSliceEnc(t1, t2) break case reflect.Bool: if p.Packed { p.enc = (*Buffer).enc_slice_packed_bool p.size = size_slice_packed_bool } else { p.enc = (*Buffer).enc_slice_bool p.size = size_slice_bool } p.dec = (*Buffer).dec_slice_bool p.packedDec = (*Buffer).dec_slice_packed_bool case reflect.Int32: if p.Packed { p.enc = (*Buffer).enc_slice_packed_int32 p.size = size_slice_packed_int32 } else { p.enc = (*Buffer).enc_slice_int32 p.size = size_slice_int32 } p.dec = (*Buffer).dec_slice_int32 p.packedDec = (*Buffer).dec_slice_packed_int32 case reflect.Uint32: if p.Packed { p.enc = (*Buffer).enc_slice_packed_uint32 p.size = size_slice_packed_uint32 } else { p.enc = (*Buffer).enc_slice_uint32 p.size = size_slice_uint32 } p.dec = (*Buffer).dec_slice_int32 p.packedDec = (*Buffer).dec_slice_packed_int32 case reflect.Int64, reflect.Uint64: if p.Packed { p.enc = (*Buffer).enc_slice_packed_int64 p.size = size_slice_packed_int64 } else { p.enc = (*Buffer).enc_slice_int64 p.size = size_slice_int64 } p.dec = (*Buffer).dec_slice_int64 p.packedDec = (*Buffer).dec_slice_packed_int64 case reflect.Uint8: p.dec = (*Buffer).dec_slice_byte if p.proto3 { p.enc = (*Buffer).enc_proto3_slice_byte p.size = size_proto3_slice_byte } else { p.enc = (*Buffer).enc_slice_byte p.size = size_slice_byte } case reflect.Float32, reflect.Float64: switch t2.Bits() { case 32: // can just treat them as bits if p.Packed { p.enc = (*Buffer).enc_slice_packed_uint32 p.size = size_slice_packed_uint32 } else { p.enc = (*Buffer).enc_slice_uint32 p.size = size_slice_uint32 } p.dec = (*Buffer).dec_slice_int32 p.packedDec = (*Buffer).dec_slice_packed_int32 case 64: // can just treat them as bits if p.Packed { p.enc = (*Buffer).enc_slice_packed_int64 p.size = size_slice_packed_int64 } else { p.enc = (*Buffer).enc_slice_int64 p.size = size_slice_int64 } p.dec = (*Buffer).dec_slice_int64 p.packedDec = (*Buffer).dec_slice_packed_int64 default: logNoSliceEnc(t1, t2) break } case reflect.String: p.enc = (*Buffer).enc_slice_string p.dec = (*Buffer).dec_slice_string p.size = size_slice_string case reflect.Ptr: switch t3 := t2.Elem(); t3.Kind() { default: fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) break case reflect.Struct: p.stype = t2.Elem() p.isMarshaler = isMarshaler(t2) p.isUnmarshaler = isUnmarshaler(t2) if p.Wire == "bytes" { p.enc = (*Buffer).enc_slice_struct_message p.dec = (*Buffer).dec_slice_struct_message p.size = size_slice_struct_message } else { p.enc = (*Buffer).enc_slice_struct_group p.dec = (*Buffer).dec_slice_struct_group p.size = size_slice_struct_group } } case reflect.Slice: switch t2.Elem().Kind() { default: fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) break case reflect.Uint8: p.enc = (*Buffer).enc_slice_slice_byte p.dec = (*Buffer).dec_slice_slice_byte p.size = size_slice_slice_byte } } case reflect.Map: p.enc = (*Buffer).enc_new_map p.dec = (*Buffer).dec_new_map p.size = size_new_map p.mtype = t1 p.mkeyprop = &Properties{} p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) p.mvalprop = &Properties{} vtype := p.mtype.Elem() if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { // The value type is not a message (*T) or bytes ([]byte), // so we need encoders for the pointer to this type. vtype = reflect.PtrTo(vtype) } p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) } // precalculate tag code wire := p.WireType if p.Packed { wire = WireBytes } x := uint32(p.Tag)<<3 | uint32(wire) i := 0 for i = 0; x > 127; i++ { p.tagbuf[i] = 0x80 | uint8(x&0x7F) x >>= 7 } p.tagbuf[i] = uint8(x) p.tagcode = p.tagbuf[0 : i+1] if p.stype != nil { if lockGetProp { p.sprop = GetProperties(p.stype) } else { p.sprop = getPropertiesLocked(p.stype) } } } var ( marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() ) // isMarshaler reports whether type t implements Marshaler. func isMarshaler(t reflect.Type) bool { // We're checking for (likely) pointer-receiver methods // so if t is not a pointer, something is very wrong. // The calls above only invoke isMarshaler on pointer types. if t.Kind() != reflect.Ptr { panic("proto: misuse of isMarshaler") } return t.Implements(marshalerType) } // isUnmarshaler reports whether type t implements Unmarshaler. func isUnmarshaler(t reflect.Type) bool { // We're checking for (likely) pointer-receiver methods // so if t is not a pointer, something is very wrong. // The calls above only invoke isUnmarshaler on pointer types. if t.Kind() != reflect.Ptr { panic("proto: misuse of isUnmarshaler") } return t.Implements(unmarshalerType) } // Init populates the properties from a protocol buffer struct tag. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { p.init(typ, name, tag, f, true) } func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { // "bytes,49,opt,def=hello!" p.Name = name p.OrigName = name if f != nil { p.field = toField(f) } if tag == "" { return } p.Parse(tag) p.setEncAndDec(typ, f, lockGetProp) } var ( propertiesMu sync.RWMutex propertiesMap = make(map[reflect.Type]*StructProperties) ) // GetProperties returns the list of properties for the type represented by t. // t must represent a generated struct type of a protocol message. func GetProperties(t reflect.Type) *StructProperties { if t.Kind() != reflect.Struct { panic("proto: type must have kind struct") } // Most calls to GetProperties in a long-running program will be // retrieving details for types we have seen before. propertiesMu.RLock() sprop, ok := propertiesMap[t] propertiesMu.RUnlock() if ok { if collectStats { stats.Chit++ } return sprop } propertiesMu.Lock() sprop = getPropertiesLocked(t) propertiesMu.Unlock() return sprop } // getPropertiesLocked requires that propertiesMu is held. func getPropertiesLocked(t reflect.Type) *StructProperties { if prop, ok := propertiesMap[t]; ok { if collectStats { stats.Chit++ } return prop } if collectStats { stats.Cmiss++ } prop := new(StructProperties) // in case of recursive protos, fill this in now. propertiesMap[t] = prop // build properties prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) || reflect.PtrTo(t).Implements(extendableProtoV1Type) prop.unrecField = invalidField prop.Prop = make([]*Properties, t.NumField()) prop.order = make([]int, t.NumField()) for i := 0; i < t.NumField(); i++ { f := t.Field(i) p := new(Properties) name := f.Name p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) if f.Name == "XXX_InternalExtensions" { // special case p.enc = (*Buffer).enc_exts p.dec = nil // not needed p.size = size_exts } else if f.Name == "XXX_extensions" { // special case p.enc = (*Buffer).enc_map p.dec = nil // not needed p.size = size_map } else if f.Name == "XXX_unrecognized" { // special case prop.unrecField = toField(&f) } oneof := f.Tag.Get("protobuf_oneof") // special case if oneof != "" { // Oneof fields don't use the traditional protobuf tag. p.OrigName = oneof } prop.Prop[i] = p prop.order[i] = i if debug { print(i, " ", f.Name, " ", t.String(), " ") if p.Tag > 0 { print(p.String()) } print("\n") } if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" { fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") } } // Re-order prop.order. sort.Sort(prop) type oneofMessage interface { XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) } if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { var oots []interface{} prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs() prop.stype = t // Interpret oneof metadata. prop.OneofTypes = make(map[string]*OneofProperties) for _, oot := range oots { oop := &OneofProperties{ Type: reflect.ValueOf(oot).Type(), // *T Prop: new(Properties), } sft := oop.Type.Elem().Field(0) oop.Prop.Name = sft.Name oop.Prop.Parse(sft.Tag.Get("protobuf")) // There will be exactly one interface field that // this new value is assignable to. for i := 0; i < t.NumField(); i++ { f := t.Field(i) if f.Type.Kind() != reflect.Interface { continue } if !oop.Type.AssignableTo(f.Type) { continue } oop.Field = i break } prop.OneofTypes[oop.Prop.OrigName] = oop } } // build required counts // build tags reqCount := 0 prop.decoderOrigNames = make(map[string]int) for i, p := range prop.Prop { if strings.HasPrefix(p.Name, "XXX_") { // Internal fields should not appear in tags/origNames maps. // They are handled specially when encoding and decoding. continue } if p.Required { reqCount++ } prop.decoderTags.put(p.Tag, i) prop.decoderOrigNames[p.OrigName] = i } prop.reqCount = reqCount return prop } // Return the Properties object for the x[0]'th field of the structure. func propByIndex(t reflect.Type, x []int) *Properties { if len(x) != 1 { fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) return nil } prop := GetProperties(t) return prop.Prop[x[0]] } // Get the address and type of a pointer to a struct from an interface. func getbase(pb Message) (t reflect.Type, b structPointer, err error) { if pb == nil { err = ErrNil return } // get the reflect type of the pointer to the struct. t = reflect.TypeOf(pb) // get the address of the struct. value := reflect.ValueOf(pb) b = toStructPointer(value) return } // A global registry of enum types. // The generated code will register the generated maps by calling RegisterEnum. var enumValueMaps = make(map[string]map[string]int32) // RegisterEnum is called from the generated code to install the enum descriptor // maps into the global table to aid parsing text format protocol buffers. func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { if _, ok := enumValueMaps[typeName]; ok { panic("proto: duplicate enum registered: " + typeName) } enumValueMaps[typeName] = valueMap } // EnumValueMap returns the mapping from names to integers of the // enum type enumType, or a nil if not found. func EnumValueMap(enumType string) map[string]int32 { return enumValueMaps[enumType] } // A registry of all linked message types. // The string is a fully-qualified proto name ("pkg.Message"). var ( protoTypes = make(map[string]reflect.Type) revProtoTypes = make(map[reflect.Type]string) ) // RegisterType is called from generated code and maps from the fully qualified // proto name to the type (pointer to struct) of the protocol buffer. func RegisterType(x Message, name string) { if _, ok := protoTypes[name]; ok { // TODO: Some day, make this a panic. log.Printf("proto: duplicate proto type registered: %s", name) return } t := reflect.TypeOf(x) protoTypes[name] = t revProtoTypes[t] = name } // MessageName returns the fully-qualified proto name for the given message type. func MessageName(x Message) string { type xname interface { XXX_MessageName() string } if m, ok := x.(xname); ok { return m.XXX_MessageName() } return revProtoTypes[reflect.TypeOf(x)] } // MessageType returns the message type (pointer to struct) for a named message. func MessageType(name string) reflect.Type { return protoTypes[name] } // A registry of all linked proto files. var ( protoFiles = make(map[string][]byte) // file name => fileDescriptor ) // RegisterFile is called from generated code and maps from the // full file name of a .proto file to its compressed FileDescriptorProto. func RegisterFile(filename string, fileDescriptor []byte) { protoFiles[filename] = fileDescriptor } // FileDescriptor returns the compressed FileDescriptorProto for a .proto file. func FileDescriptor(filename string) []byte { return protoFiles[filename] } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/pointer_unsafe.go������������������������������0000644�0610621�0607500�00000022425�13172163407�027114� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // +build !appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. package proto import ( "reflect" "unsafe" ) // NOTE: These type_Foo functions would more idiomatically be methods, // but Go does not allow methods on pointer types, and we must preserve // some pointer type for the garbage collector. We use these // funcs with clunky names as our poor approximation to methods. // // An alternative would be // type structPointer struct { p unsafe.Pointer } // but that does not registerize as well. // A structPointer is a pointer to a struct. type structPointer unsafe.Pointer // toStructPointer returns a structPointer equivalent to the given reflect value. func toStructPointer(v reflect.Value) structPointer { return structPointer(unsafe.Pointer(v.Pointer())) } // IsNil reports whether p is nil. func structPointer_IsNil(p structPointer) bool { return p == nil } // Interface returns the struct pointer, assumed to have element type t, // as an interface value. func structPointer_Interface(p structPointer, t reflect.Type) interface{} { return reflect.NewAt(t, unsafe.Pointer(p)).Interface() } // A field identifies a field in a struct, accessible from a structPointer. // In this implementation, a field is identified by its byte offset from the start of the struct. type field uintptr // toField returns a field equivalent to the given reflect field. func toField(f *reflect.StructField) field { return field(f.Offset) } // invalidField is an invalid field identifier. const invalidField = ^field(0) // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { return f != ^field(0) } // Bytes returns the address of a []byte field in the struct. func structPointer_Bytes(p structPointer, f field) *[]byte { return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BytesSlice returns the address of a [][]byte field in the struct. func structPointer_BytesSlice(p structPointer, f field) *[][]byte { return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // Bool returns the address of a *bool field in the struct. func structPointer_Bool(p structPointer, f field) **bool { return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BoolVal returns the address of a bool field in the struct. func structPointer_BoolVal(p structPointer, f field) *bool { return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BoolSlice returns the address of a []bool field in the struct. func structPointer_BoolSlice(p structPointer, f field) *[]bool { return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // String returns the address of a *string field in the struct. func structPointer_String(p structPointer, f field) **string { return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StringVal returns the address of a string field in the struct. func structPointer_StringVal(p structPointer, f field) *string { return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StringSlice returns the address of a []string field in the struct. func structPointer_StringSlice(p structPointer, f field) *[]string { return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // ExtMap returns the address of an extension map field in the struct. func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f))) } func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // NewAt returns the reflect.Value for a pointer to a field in the struct. func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) } // SetStructPointer writes a *struct field in the struct. func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q } // GetStructPointer reads a *struct field in the struct. func structPointer_GetStructPointer(p structPointer, f field) structPointer { return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StructPointerSlice the address of a []*struct field in the struct. func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). type structPointerSlice []structPointer func (v *structPointerSlice) Len() int { return len(*v) } func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } // A word32 is the address of a "pointer to 32-bit value" field. type word32 **uint32 // IsNil reports whether *v is nil. func word32_IsNil(p word32) bool { return *p == nil } // Set sets *v to point at a newly allocated word set to x. func word32_Set(p word32, o *Buffer, x uint32) { if len(o.uint32s) == 0 { o.uint32s = make([]uint32, uint32PoolSize) } o.uint32s[0] = x *p = &o.uint32s[0] o.uint32s = o.uint32s[1:] } // Get gets the value pointed at by *v. func word32_Get(p word32) uint32 { return **p } // Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. func structPointer_Word32(p structPointer, f field) word32 { return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // A word32Val is the address of a 32-bit value field. type word32Val *uint32 // Set sets *p to x. func word32Val_Set(p word32Val, x uint32) { *p = x } // Get gets the value pointed at by p. func word32Val_Get(p word32Val) uint32 { return *p } // Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. func structPointer_Word32Val(p structPointer, f field) word32Val { return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // A word32Slice is a slice of 32-bit values. type word32Slice []uint32 func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } func (v *word32Slice) Len() int { return len(*v) } func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } // Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. func structPointer_Word32Slice(p structPointer, f field) *word32Slice { return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // word64 is like word32 but for 64-bit values. type word64 **uint64 func word64_Set(p word64, o *Buffer, x uint64) { if len(o.uint64s) == 0 { o.uint64s = make([]uint64, uint64PoolSize) } o.uint64s[0] = x *p = &o.uint64s[0] o.uint64s = o.uint64s[1:] } func word64_IsNil(p word64) bool { return *p == nil } func word64_Get(p word64) uint64 { return **p } func structPointer_Word64(p structPointer, f field) word64 { return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // word64Val is like word32Val but for 64-bit values. type word64Val *uint64 func word64Val_Set(p word64Val, o *Buffer, x uint64) { *p = x } func word64Val_Get(p word64Val) uint64 { return *p } func structPointer_Word64Val(p structPointer, f field) word64Val { return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // word64Slice is like word32Slice but for 64-bit values. type word64Slice []uint64 func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } func (v *word64Slice) Len() int { return len(*v) } func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } func structPointer_Word64Slice(p structPointer, f field) *word64Slice { return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/pointer_reflect.go�����������������������������0000644�0610621�0607500�00000033110�13172163407�027250� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // +build appengine js // This file contains an implementation of proto field accesses using package reflect. // It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can // be used on App Engine. package proto import ( "math" "reflect" ) // A structPointer is a pointer to a struct. type structPointer struct { v reflect.Value } // toStructPointer returns a structPointer equivalent to the given reflect value. // The reflect value must itself be a pointer to a struct. func toStructPointer(v reflect.Value) structPointer { return structPointer{v} } // IsNil reports whether p is nil. func structPointer_IsNil(p structPointer) bool { return p.v.IsNil() } // Interface returns the struct pointer as an interface value. func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { return p.v.Interface() } // A field identifies a field in a struct, accessible from a structPointer. // In this implementation, a field is identified by the sequence of field indices // passed to reflect's FieldByIndex. type field []int // toField returns a field equivalent to the given reflect field. func toField(f *reflect.StructField) field { return f.Index } // invalidField is an invalid field identifier. var invalidField = field(nil) // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { return f != nil } // field returns the given field in the struct as a reflect value. func structPointer_field(p structPointer, f field) reflect.Value { // Special case: an extension map entry with a value of type T // passes a *T to the struct-handling code with a zero field, // expecting that it will be treated as equivalent to *struct{ X T }, // which has the same memory layout. We have to handle that case // specially, because reflect will panic if we call FieldByIndex on a // non-struct. if f == nil { return p.v.Elem() } return p.v.Elem().FieldByIndex(f) } // ifield returns the given field in the struct as an interface value. func structPointer_ifield(p structPointer, f field) interface{} { return structPointer_field(p, f).Addr().Interface() } // Bytes returns the address of a []byte field in the struct. func structPointer_Bytes(p structPointer, f field) *[]byte { return structPointer_ifield(p, f).(*[]byte) } // BytesSlice returns the address of a [][]byte field in the struct. func structPointer_BytesSlice(p structPointer, f field) *[][]byte { return structPointer_ifield(p, f).(*[][]byte) } // Bool returns the address of a *bool field in the struct. func structPointer_Bool(p structPointer, f field) **bool { return structPointer_ifield(p, f).(**bool) } // BoolVal returns the address of a bool field in the struct. func structPointer_BoolVal(p structPointer, f field) *bool { return structPointer_ifield(p, f).(*bool) } // BoolSlice returns the address of a []bool field in the struct. func structPointer_BoolSlice(p structPointer, f field) *[]bool { return structPointer_ifield(p, f).(*[]bool) } // String returns the address of a *string field in the struct. func structPointer_String(p structPointer, f field) **string { return structPointer_ifield(p, f).(**string) } // StringVal returns the address of a string field in the struct. func structPointer_StringVal(p structPointer, f field) *string { return structPointer_ifield(p, f).(*string) } // StringSlice returns the address of a []string field in the struct. func structPointer_StringSlice(p structPointer, f field) *[]string { return structPointer_ifield(p, f).(*[]string) } // Extensions returns the address of an extension map field in the struct. func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { return structPointer_ifield(p, f).(*XXX_InternalExtensions) } // ExtMap returns the address of an extension map field in the struct. func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return structPointer_ifield(p, f).(*map[int32]Extension) } // NewAt returns the reflect.Value for a pointer to a field in the struct. func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { return structPointer_field(p, f).Addr() } // SetStructPointer writes a *struct field in the struct. func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { structPointer_field(p, f).Set(q.v) } // GetStructPointer reads a *struct field in the struct. func structPointer_GetStructPointer(p structPointer, f field) structPointer { return structPointer{structPointer_field(p, f)} } // StructPointerSlice the address of a []*struct field in the struct. func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { return structPointerSlice{structPointer_field(p, f)} } // A structPointerSlice represents the address of a slice of pointers to structs // (themselves messages or groups). That is, v.Type() is *[]*struct{...}. type structPointerSlice struct { v reflect.Value } func (p structPointerSlice) Len() int { return p.v.Len() } func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } func (p structPointerSlice) Append(q structPointer) { p.v.Set(reflect.Append(p.v, q.v)) } var ( int32Type = reflect.TypeOf(int32(0)) uint32Type = reflect.TypeOf(uint32(0)) float32Type = reflect.TypeOf(float32(0)) int64Type = reflect.TypeOf(int64(0)) uint64Type = reflect.TypeOf(uint64(0)) float64Type = reflect.TypeOf(float64(0)) ) // A word32 represents a field of type *int32, *uint32, *float32, or *enum. // That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. type word32 struct { v reflect.Value } // IsNil reports whether p is nil. func word32_IsNil(p word32) bool { return p.v.IsNil() } // Set sets p to point at a newly allocated word with bits set to x. func word32_Set(p word32, o *Buffer, x uint32) { t := p.v.Type().Elem() switch t { case int32Type: if len(o.int32s) == 0 { o.int32s = make([]int32, uint32PoolSize) } o.int32s[0] = int32(x) p.v.Set(reflect.ValueOf(&o.int32s[0])) o.int32s = o.int32s[1:] return case uint32Type: if len(o.uint32s) == 0 { o.uint32s = make([]uint32, uint32PoolSize) } o.uint32s[0] = x p.v.Set(reflect.ValueOf(&o.uint32s[0])) o.uint32s = o.uint32s[1:] return case float32Type: if len(o.float32s) == 0 { o.float32s = make([]float32, uint32PoolSize) } o.float32s[0] = math.Float32frombits(x) p.v.Set(reflect.ValueOf(&o.float32s[0])) o.float32s = o.float32s[1:] return } // must be enum p.v.Set(reflect.New(t)) p.v.Elem().SetInt(int64(int32(x))) } // Get gets the bits pointed at by p, as a uint32. func word32_Get(p word32) uint32 { elem := p.v.Elem() switch elem.Kind() { case reflect.Int32: return uint32(elem.Int()) case reflect.Uint32: return uint32(elem.Uint()) case reflect.Float32: return math.Float32bits(float32(elem.Float())) } panic("unreachable") } // Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. func structPointer_Word32(p structPointer, f field) word32 { return word32{structPointer_field(p, f)} } // A word32Val represents a field of type int32, uint32, float32, or enum. // That is, v.Type() is int32, uint32, float32, or enum and v is assignable. type word32Val struct { v reflect.Value } // Set sets *p to x. func word32Val_Set(p word32Val, x uint32) { switch p.v.Type() { case int32Type: p.v.SetInt(int64(x)) return case uint32Type: p.v.SetUint(uint64(x)) return case float32Type: p.v.SetFloat(float64(math.Float32frombits(x))) return } // must be enum p.v.SetInt(int64(int32(x))) } // Get gets the bits pointed at by p, as a uint32. func word32Val_Get(p word32Val) uint32 { elem := p.v switch elem.Kind() { case reflect.Int32: return uint32(elem.Int()) case reflect.Uint32: return uint32(elem.Uint()) case reflect.Float32: return math.Float32bits(float32(elem.Float())) } panic("unreachable") } // Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. func structPointer_Word32Val(p structPointer, f field) word32Val { return word32Val{structPointer_field(p, f)} } // A word32Slice is a slice of 32-bit values. // That is, v.Type() is []int32, []uint32, []float32, or []enum. type word32Slice struct { v reflect.Value } func (p word32Slice) Append(x uint32) { n, m := p.v.Len(), p.v.Cap() if n < m { p.v.SetLen(n + 1) } else { t := p.v.Type().Elem() p.v.Set(reflect.Append(p.v, reflect.Zero(t))) } elem := p.v.Index(n) switch elem.Kind() { case reflect.Int32: elem.SetInt(int64(int32(x))) case reflect.Uint32: elem.SetUint(uint64(x)) case reflect.Float32: elem.SetFloat(float64(math.Float32frombits(x))) } } func (p word32Slice) Len() int { return p.v.Len() } func (p word32Slice) Index(i int) uint32 { elem := p.v.Index(i) switch elem.Kind() { case reflect.Int32: return uint32(elem.Int()) case reflect.Uint32: return uint32(elem.Uint()) case reflect.Float32: return math.Float32bits(float32(elem.Float())) } panic("unreachable") } // Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. func structPointer_Word32Slice(p structPointer, f field) word32Slice { return word32Slice{structPointer_field(p, f)} } // word64 is like word32 but for 64-bit values. type word64 struct { v reflect.Value } func word64_Set(p word64, o *Buffer, x uint64) { t := p.v.Type().Elem() switch t { case int64Type: if len(o.int64s) == 0 { o.int64s = make([]int64, uint64PoolSize) } o.int64s[0] = int64(x) p.v.Set(reflect.ValueOf(&o.int64s[0])) o.int64s = o.int64s[1:] return case uint64Type: if len(o.uint64s) == 0 { o.uint64s = make([]uint64, uint64PoolSize) } o.uint64s[0] = x p.v.Set(reflect.ValueOf(&o.uint64s[0])) o.uint64s = o.uint64s[1:] return case float64Type: if len(o.float64s) == 0 { o.float64s = make([]float64, uint64PoolSize) } o.float64s[0] = math.Float64frombits(x) p.v.Set(reflect.ValueOf(&o.float64s[0])) o.float64s = o.float64s[1:] return } panic("unreachable") } func word64_IsNil(p word64) bool { return p.v.IsNil() } func word64_Get(p word64) uint64 { elem := p.v.Elem() switch elem.Kind() { case reflect.Int64: return uint64(elem.Int()) case reflect.Uint64: return elem.Uint() case reflect.Float64: return math.Float64bits(elem.Float()) } panic("unreachable") } func structPointer_Word64(p structPointer, f field) word64 { return word64{structPointer_field(p, f)} } // word64Val is like word32Val but for 64-bit values. type word64Val struct { v reflect.Value } func word64Val_Set(p word64Val, o *Buffer, x uint64) { switch p.v.Type() { case int64Type: p.v.SetInt(int64(x)) return case uint64Type: p.v.SetUint(x) return case float64Type: p.v.SetFloat(math.Float64frombits(x)) return } panic("unreachable") } func word64Val_Get(p word64Val) uint64 { elem := p.v switch elem.Kind() { case reflect.Int64: return uint64(elem.Int()) case reflect.Uint64: return elem.Uint() case reflect.Float64: return math.Float64bits(elem.Float()) } panic("unreachable") } func structPointer_Word64Val(p structPointer, f field) word64Val { return word64Val{structPointer_field(p, f)} } type word64Slice struct { v reflect.Value } func (p word64Slice) Append(x uint64) { n, m := p.v.Len(), p.v.Cap() if n < m { p.v.SetLen(n + 1) } else { t := p.v.Type().Elem() p.v.Set(reflect.Append(p.v, reflect.Zero(t))) } elem := p.v.Index(n) switch elem.Kind() { case reflect.Int64: elem.SetInt(int64(int64(x))) case reflect.Uint64: elem.SetUint(uint64(x)) case reflect.Float64: elem.SetFloat(float64(math.Float64frombits(x))) } } func (p word64Slice) Len() int { return p.v.Len() } func (p word64Slice) Index(i int) uint64 { elem := p.v.Index(i) switch elem.Kind() { case reflect.Int64: return uint64(elem.Int()) case reflect.Uint64: return uint64(elem.Uint()) case reflect.Float64: return math.Float64bits(float64(elem.Float())) } panic("unreachable") } func structPointer_Word64Slice(p structPointer, f field) word64Slice { return word64Slice{structPointer_field(p, f)} } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/message_set_test.go����������������������������0000644�0610621�0607500�00000005060�13172163407�027425� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto import ( "bytes" "testing" ) func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { // Check that a repeated message set entry will be concatenated. in := &messageSet{ Item: []*_MessageSet_Item{ {TypeId: Int32(12345), Message: []byte("hoo")}, {TypeId: Int32(12345), Message: []byte("hah")}, }, } b, err := Marshal(in) if err != nil { t.Fatalf("Marshal: %v", err) } t.Logf("Marshaled bytes: %q", b) var extensions XXX_InternalExtensions if err := UnmarshalMessageSet(b, &extensions); err != nil { t.Fatalf("UnmarshalMessageSet: %v", err) } ext, ok := extensions.p.extensionMap[12345] if !ok { t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) } // Skip wire type/field number and length varints. got := skipVarint(skipVarint(ext.enc)) if want := []byte("hoohah"); !bytes.Equal(got, want) { t.Errorf("Combined extension is %q, want %q", got, want) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/message_set.go���������������������������������0000644�0610621�0607500�00000021611�13172163407�026366� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto /* * Support for message sets. */ import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "sort" ) // errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. // A message type ID is required for storing a protocol buffer in a message set. var errNoMessageTypeID = errors.New("proto does not have a message type ID") // The first two types (_MessageSet_Item and messageSet) // model what the protocol compiler produces for the following protocol message: // message MessageSet { // repeated group Item = 1 { // required int32 type_id = 2; // required string message = 3; // }; // } // That is the MessageSet wire format. We can't use a proto to generate these // because that would introduce a circular dependency between it and this package. type _MessageSet_Item struct { TypeId *int32 `protobuf:"varint,2,req,name=type_id"` Message []byte `protobuf:"bytes,3,req,name=message"` } type messageSet struct { Item []*_MessageSet_Item `protobuf:"group,1,rep"` XXX_unrecognized []byte // TODO: caching? } // Make sure messageSet is a Message. var _ Message = (*messageSet)(nil) // messageTypeIder is an interface satisfied by a protocol buffer type // that may be stored in a MessageSet. type messageTypeIder interface { MessageTypeId() int32 } func (ms *messageSet) find(pb Message) *_MessageSet_Item { mti, ok := pb.(messageTypeIder) if !ok { return nil } id := mti.MessageTypeId() for _, item := range ms.Item { if *item.TypeId == id { return item } } return nil } func (ms *messageSet) Has(pb Message) bool { if ms.find(pb) != nil { return true } return false } func (ms *messageSet) Unmarshal(pb Message) error { if item := ms.find(pb); item != nil { return Unmarshal(item.Message, pb) } if _, ok := pb.(messageTypeIder); !ok { return errNoMessageTypeID } return nil // TODO: return error instead? } func (ms *messageSet) Marshal(pb Message) error { msg, err := Marshal(pb) if err != nil { return err } if item := ms.find(pb); item != nil { // reuse existing item item.Message = msg return nil } mti, ok := pb.(messageTypeIder) if !ok { return errNoMessageTypeID } mtid := mti.MessageTypeId() ms.Item = append(ms.Item, &_MessageSet_Item{ TypeId: &mtid, Message: msg, }) return nil } func (ms *messageSet) Reset() { *ms = messageSet{} } func (ms *messageSet) String() string { return CompactTextString(ms) } func (*messageSet) ProtoMessage() {} // Support for the message_set_wire_format message option. func skipVarint(buf []byte) []byte { i := 0 for ; buf[i]&0x80 != 0; i++ { } return buf[i+1:] } // MarshalMessageSet encodes the extension map represented by m in the message set wire format. // It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. func MarshalMessageSet(exts interface{}) ([]byte, error) { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: if err := encodeExtensions(exts); err != nil { return nil, err } m, _ = exts.extensionsRead() case map[int32]Extension: if err := encodeExtensionsMap(exts); err != nil { return nil, err } m = exts default: return nil, errors.New("proto: not an extension map") } // Sort extension IDs to provide a deterministic encoding. // See also enc_map in encode.go. ids := make([]int, 0, len(m)) for id := range m { ids = append(ids, int(id)) } sort.Ints(ids) ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))} for _, id := range ids { e := m[int32(id)] // Remove the wire type and field number varint, as well as the length varint. msg := skipVarint(skipVarint(e.enc)) ms.Item = append(ms.Item, &_MessageSet_Item{ TypeId: Int32(int32(id)), Message: msg, }) } return Marshal(ms) } // UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. // It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. func UnmarshalMessageSet(buf []byte, exts interface{}) error { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: m = exts.extensionsWrite() case map[int32]Extension: m = exts default: return errors.New("proto: not an extension map") } ms := new(messageSet) if err := Unmarshal(buf, ms); err != nil { return err } for _, item := range ms.Item { id := *item.TypeId msg := item.Message // Restore wire type and field number varint, plus length varint. // Be careful to preserve duplicate items. b := EncodeVarint(uint64(id)<<3 | WireBytes) if ext, ok := m[id]; ok { // Existing data; rip off the tag and length varint // so we join the new data correctly. // We can assume that ext.enc is set because we are unmarshaling. o := ext.enc[len(b):] // skip wire type and field number _, n := DecodeVarint(o) // calculate length of length varint o = o[n:] // skip length varint msg = append(o, msg...) // join old data and new data } b = append(b, EncodeVarint(uint64(len(msg)))...) b = append(b, msg...) m[id] = Extension{enc: b} } return nil } // MarshalMessageSetJSON encodes the extension map represented by m in JSON format. // It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: m, _ = exts.extensionsRead() case map[int32]Extension: m = exts default: return nil, errors.New("proto: not an extension map") } var b bytes.Buffer b.WriteByte('{') // Process the map in key order for deterministic output. ids := make([]int32, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Sort(int32Slice(ids)) // int32Slice defined in text.go for i, id := range ids { ext := m[id] if i > 0 { b.WriteByte(',') } msd, ok := messageSetMap[id] if !ok { // Unknown type; we can't render it, so skip it. continue } fmt.Fprintf(&b, `"[%s]":`, msd.name) x := ext.value if x == nil { x = reflect.New(msd.t.Elem()).Interface() if err := Unmarshal(ext.enc, x.(Message)); err != nil { return nil, err } } d, err := json.Marshal(x) if err != nil { return nil, err } b.Write(d) } b.WriteByte('}') return b.Bytes(), nil } // UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. // It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { // Common-case fast path. if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { return nil } // This is fairly tricky, and it's not clear that it is needed. return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") } // A global registry of types that can be used in a MessageSet. var messageSetMap = make(map[int32]messageSetDesc) type messageSetDesc struct { t reflect.Type // pointer to struct name string } // RegisterMessageSetType is called from the generated code. func RegisterMessageSetType(m Message, fieldNum int32, name string) { messageSetMap[fieldNum] = messageSetDesc{ t: reflect.TypeOf(m), name: name, } } �����������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/map_test.go������������������������������������0000644�0610621�0607500�00000001650�13172163407�025704� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package proto_test import ( "fmt" "testing" "github.com/golang/protobuf/proto" ppb "github.com/golang/protobuf/proto/proto3_proto" ) func marshalled() []byte { m := &ppb.IntMaps{} for i := 0; i < 1000; i++ { m.Maps = append(m.Maps, &ppb.IntMap{ Rtt: map[int32]int32{1: 2}, }) } b, err := proto.Marshal(m) if err != nil { panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) } return b } func BenchmarkConcurrentMapUnmarshal(b *testing.B) { in := marshalled() b.RunParallel(func(pb *testing.PB) { for pb.Next() { var out ppb.IntMaps if err := proto.Unmarshal(in, &out); err != nil { b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) } } }) } func BenchmarkSequentialMapUnmarshal(b *testing.B) { in := marshalled() b.ResetTimer() for i := 0; i < b.N; i++ { var out ppb.IntMaps if err := proto.Unmarshal(in, &out); err != nil { b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) } } } ����������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/lib.go�����������������������������������������0000644�0610621�0607500�00000057150�13172163407�024644� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Package proto converts data structures to and from the wire format of protocol buffers. It works in concert with the Go source code generated for .proto files by the protocol compiler. A summary of the properties of the protocol buffer interface for a protocol buffer variable v: - Names are turned from camel_case to CamelCase for export. - There are no methods on v to set fields; just treat them as structure fields. - There are getters that return a field's value if set, and return the field's default value if unset. The getters work even if the receiver is a nil message. - The zero value for a struct is its correct initialization state. All desired fields must be set before marshaling. - A Reset() method will restore a protobuf struct to its zero state. - Non-repeated fields are pointers to the values; nil means unset. That is, optional or required field int32 f becomes F *int32. - Repeated fields are slices. - Helper functions are available to aid the setting of fields. msg.Foo = proto.String("hello") // set field - Constants are defined to hold the default values of all fields that have them. They have the form Default_StructName_FieldName. Because the getter methods handle defaulted values, direct use of these constants should be rare. - Enums are given type names and maps from names to values. Enum values are prefixed by the enclosing message's name, or by the enum's type name if it is a top-level enum. Enum types have a String method, and a Enum method to assist in message construction. - Nested messages, groups and enums have type names prefixed with the name of the surrounding message type. - Extensions are given descriptor names that start with E_, followed by an underscore-delimited list of the nested messages that contain it (if any) followed by the CamelCased name of the extension field itself. HasExtension, ClearExtension, GetExtension and SetExtension are functions for manipulating extensions. - Oneof field sets are given a single field in their message, with distinguished wrapper types for each possible field value. - Marshal and Unmarshal are functions to encode and decode the wire format. When the .proto file specifies `syntax="proto3"`, there are some differences: - Non-repeated fields of non-message type are values instead of pointers. - Enum types do not get an Enum method. The simplest way to describe this is to see an example. Given file test.proto, containing package example; enum FOO { X = 17; } message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } oneof union { int32 number = 6; string name = 7; } } The resulting file, test.pb.go, is: package example import proto "github.com/golang/protobuf/proto" import math "math" type FOO int32 const ( FOO_X FOO = 17 ) var FOO_name = map[int32]string{ 17: "X", } var FOO_value = map[string]int32{ "X": 17, } func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return proto.EnumName(FOO_name, int32(x)) } func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data) if err != nil { return err } *x = FOO(value) return nil } type Test struct { Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` // Types that are valid to be assigned to Union: // *Test_Number // *Test_Name Union isTest_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Test) Reset() { *m = Test{} } func (m *Test) String() string { return proto.CompactTextString(m) } func (*Test) ProtoMessage() {} type isTest_Union interface { isTest_Union() } type Test_Number struct { Number int32 `protobuf:"varint,6,opt,name=number"` } type Test_Name struct { Name string `protobuf:"bytes,7,opt,name=name"` } func (*Test_Number) isTest_Union() {} func (*Test_Name) isTest_Union() {} func (m *Test) GetUnion() isTest_Union { if m != nil { return m.Union } return nil } const Default_Test_Type int32 = 77 func (m *Test) GetLabel() string { if m != nil && m.Label != nil { return *m.Label } return "" } func (m *Test) GetType() int32 { if m != nil && m.Type != nil { return *m.Type } return Default_Test_Type } func (m *Test) GetOptionalgroup() *Test_OptionalGroup { if m != nil { return m.Optionalgroup } return nil } type Test_OptionalGroup struct { RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` } func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } func (m *Test_OptionalGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } func (m *Test) GetNumber() int32 { if x, ok := m.GetUnion().(*Test_Number); ok { return x.Number } return 0 } func (m *Test) GetName() string { if x, ok := m.GetUnion().(*Test_Name); ok { return x.Name } return "" } func init() { proto.RegisterEnum("example.FOO", FOO_name, FOO_value) } To create and play with a Test object: package main import ( "log" "github.com/golang/protobuf/proto" pb "./example.pb" ) func main() { test := &pb.Test{ Label: proto.String("hello"), Type: proto.Int32(17), Reps: []int64{1, 2, 3}, Optionalgroup: &pb.Test_OptionalGroup{ RequiredField: proto.String("good bye"), }, Union: &pb.Test_Name{"fred"}, } data, err := proto.Marshal(test) if err != nil { log.Fatal("marshaling error: ", err) } newTest := &pb.Test{} err = proto.Unmarshal(data, newTest) if err != nil { log.Fatal("unmarshaling error: ", err) } // Now test and newTest contain the same data. if test.GetLabel() != newTest.GetLabel() { log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } // Use a type switch to determine which oneof was set. switch u := test.Union.(type) { case *pb.Test_Number: // u.Number contains the number. case *pb.Test_Name: // u.Name contains the string. } // etc. } */ package proto import ( "encoding/json" "fmt" "log" "reflect" "sort" "strconv" "sync" ) // Message is implemented by generated protocol buffer messages. type Message interface { Reset() String() string ProtoMessage() } // Stats records allocation details about the protocol buffer encoders // and decoders. Useful for tuning the library itself. type Stats struct { Emalloc uint64 // mallocs in encode Dmalloc uint64 // mallocs in decode Encode uint64 // number of encodes Decode uint64 // number of decodes Chit uint64 // number of cache hits Cmiss uint64 // number of cache misses Size uint64 // number of sizes } // Set to true to enable stats collection. const collectStats = false var stats Stats // GetStats returns a copy of the global Stats structure. func GetStats() Stats { return stats } // A Buffer is a buffer manager for marshaling and unmarshaling // protocol buffers. It may be reused between invocations to // reduce memory usage. It is not necessary to use a Buffer; // the global functions Marshal and Unmarshal create a // temporary Buffer and are fine for most applications. type Buffer struct { buf []byte // encode/decode byte stream index int // read point // pools of basic types to amortize allocation. bools []bool uint32s []uint32 uint64s []uint64 // extra pools, only used with pointer_reflect.go int32s []int32 int64s []int64 float32s []float32 float64s []float64 } // NewBuffer allocates a new Buffer and initializes its internal data to // the contents of the argument slice. func NewBuffer(e []byte) *Buffer { return &Buffer{buf: e} } // Reset resets the Buffer, ready for marshaling a new protocol buffer. func (p *Buffer) Reset() { p.buf = p.buf[0:0] // for reading/writing p.index = 0 // for reading } // SetBuf replaces the internal buffer with the slice, // ready for unmarshaling the contents of the slice. func (p *Buffer) SetBuf(s []byte) { p.buf = s p.index = 0 } // Bytes returns the contents of the Buffer. func (p *Buffer) Bytes() []byte { return p.buf } /* * Helper routines for simplifying the creation of optional fields of basic type. */ // Bool is a helper routine that allocates a new bool value // to store v and returns a pointer to it. func Bool(v bool) *bool { return &v } // Int32 is a helper routine that allocates a new int32 value // to store v and returns a pointer to it. func Int32(v int32) *int32 { return &v } // Int is a helper routine that allocates a new int32 value // to store v and returns a pointer to it, but unlike Int32 // its argument value is an int. func Int(v int) *int32 { p := new(int32) *p = int32(v) return p } // Int64 is a helper routine that allocates a new int64 value // to store v and returns a pointer to it. func Int64(v int64) *int64 { return &v } // Float32 is a helper routine that allocates a new float32 value // to store v and returns a pointer to it. func Float32(v float32) *float32 { return &v } // Float64 is a helper routine that allocates a new float64 value // to store v and returns a pointer to it. func Float64(v float64) *float64 { return &v } // Uint32 is a helper routine that allocates a new uint32 value // to store v and returns a pointer to it. func Uint32(v uint32) *uint32 { return &v } // Uint64 is a helper routine that allocates a new uint64 value // to store v and returns a pointer to it. func Uint64(v uint64) *uint64 { return &v } // String is a helper routine that allocates a new string value // to store v and returns a pointer to it. func String(v string) *string { return &v } // EnumName is a helper function to simplify printing protocol buffer enums // by name. Given an enum map and a value, it returns a useful string. func EnumName(m map[int32]string, v int32) string { s, ok := m[v] if ok { return s } return strconv.Itoa(int(v)) } // UnmarshalJSONEnum is a helper function to simplify recovering enum int values // from their JSON-encoded representation. Given a map from the enum's symbolic // names to its int values, and a byte buffer containing the JSON-encoded // value, it returns an int32 that can be cast to the enum type by the caller. // // The function can deal with both JSON representations, numeric and symbolic. func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { if data[0] == '"' { // New style: enums are strings. var repr string if err := json.Unmarshal(data, &repr); err != nil { return -1, err } val, ok := m[repr] if !ok { return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) } return val, nil } // Old style: enums are ints. var val int32 if err := json.Unmarshal(data, &val); err != nil { return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) } return val, nil } // DebugPrint dumps the encoded data in b in a debugging format with a header // including the string s. Used in testing but made available for general debugging. func (p *Buffer) DebugPrint(s string, b []byte) { var u uint64 obuf := p.buf index := p.index p.buf = b p.index = 0 depth := 0 fmt.Printf("\n--- %s ---\n", s) out: for { for i := 0; i < depth; i++ { fmt.Print(" ") } index := p.index if index == len(p.buf) { break } op, err := p.DecodeVarint() if err != nil { fmt.Printf("%3d: fetching op err %v\n", index, err) break out } tag := op >> 3 wire := op & 7 switch wire { default: fmt.Printf("%3d: t=%3d unknown wire=%d\n", index, tag, wire) break out case WireBytes: var r []byte r, err = p.DecodeRawBytes(false) if err != nil { break out } fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) if len(r) <= 6 { for i := 0; i < len(r); i++ { fmt.Printf(" %.2x", r[i]) } } else { for i := 0; i < 3; i++ { fmt.Printf(" %.2x", r[i]) } fmt.Printf(" ..") for i := len(r) - 3; i < len(r); i++ { fmt.Printf(" %.2x", r[i]) } } fmt.Printf("\n") case WireFixed32: u, err = p.DecodeFixed32() if err != nil { fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) case WireFixed64: u, err = p.DecodeFixed64() if err != nil { fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) case WireVarint: u, err = p.DecodeVarint() if err != nil { fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) case WireStartGroup: fmt.Printf("%3d: t=%3d start\n", index, tag) depth++ case WireEndGroup: depth-- fmt.Printf("%3d: t=%3d end\n", index, tag) } } if depth != 0 { fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) } fmt.Printf("\n") p.buf = obuf p.index = index } // SetDefaults sets unset protocol buffer fields to their default values. // It only modifies fields that are both unset and have defined defaults. // It recursively sets default values in any non-nil sub-messages. func SetDefaults(pb Message) { setDefaults(reflect.ValueOf(pb), true, false) } // v is a pointer to a struct. func setDefaults(v reflect.Value, recur, zeros bool) { v = v.Elem() defaultMu.RLock() dm, ok := defaults[v.Type()] defaultMu.RUnlock() if !ok { dm = buildDefaultMessage(v.Type()) defaultMu.Lock() defaults[v.Type()] = dm defaultMu.Unlock() } for _, sf := range dm.scalars { f := v.Field(sf.index) if !f.IsNil() { // field already set continue } dv := sf.value if dv == nil && !zeros { // no explicit default, and don't want to set zeros continue } fptr := f.Addr().Interface() // **T // TODO: Consider batching the allocations we do here. switch sf.kind { case reflect.Bool: b := new(bool) if dv != nil { *b = dv.(bool) } *(fptr.(**bool)) = b case reflect.Float32: f := new(float32) if dv != nil { *f = dv.(float32) } *(fptr.(**float32)) = f case reflect.Float64: f := new(float64) if dv != nil { *f = dv.(float64) } *(fptr.(**float64)) = f case reflect.Int32: // might be an enum if ft := f.Type(); ft != int32PtrType { // enum f.Set(reflect.New(ft.Elem())) if dv != nil { f.Elem().SetInt(int64(dv.(int32))) } } else { // int32 field i := new(int32) if dv != nil { *i = dv.(int32) } *(fptr.(**int32)) = i } case reflect.Int64: i := new(int64) if dv != nil { *i = dv.(int64) } *(fptr.(**int64)) = i case reflect.String: s := new(string) if dv != nil { *s = dv.(string) } *(fptr.(**string)) = s case reflect.Uint8: // exceptional case: []byte var b []byte if dv != nil { db := dv.([]byte) b = make([]byte, len(db)) copy(b, db) } else { b = []byte{} } *(fptr.(*[]byte)) = b case reflect.Uint32: u := new(uint32) if dv != nil { *u = dv.(uint32) } *(fptr.(**uint32)) = u case reflect.Uint64: u := new(uint64) if dv != nil { *u = dv.(uint64) } *(fptr.(**uint64)) = u default: log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) } } for _, ni := range dm.nested { f := v.Field(ni) // f is *T or []*T or map[T]*T switch f.Kind() { case reflect.Ptr: if f.IsNil() { continue } setDefaults(f, recur, zeros) case reflect.Slice: for i := 0; i < f.Len(); i++ { e := f.Index(i) if e.IsNil() { continue } setDefaults(e, recur, zeros) } case reflect.Map: for _, k := range f.MapKeys() { e := f.MapIndex(k) if e.IsNil() { continue } setDefaults(e, recur, zeros) } } } } var ( // defaults maps a protocol buffer struct type to a slice of the fields, // with its scalar fields set to their proto-declared non-zero default values. defaultMu sync.RWMutex defaults = make(map[reflect.Type]defaultMessage) int32PtrType = reflect.TypeOf((*int32)(nil)) ) // defaultMessage represents information about the default values of a message. type defaultMessage struct { scalars []scalarField nested []int // struct field index of nested messages } type scalarField struct { index int // struct field index kind reflect.Kind // element type (the T in *T or []T) value interface{} // the proto-declared default value, or nil } // t is a struct type. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { sprop := GetProperties(t) for _, prop := range sprop.Prop { fi, ok := sprop.decoderTags.get(prop.Tag) if !ok { // XXX_unrecognized continue } ft := t.Field(fi).Type sf, nested, err := fieldDefault(ft, prop) switch { case err != nil: log.Print(err) case nested: dm.nested = append(dm.nested, fi) case sf != nil: sf.index = fi dm.scalars = append(dm.scalars, *sf) } } return dm } // fieldDefault returns the scalarField for field type ft. // sf will be nil if the field can not have a default. // nestedMessage will be true if this is a nested message. // Note that sf.index is not set on return. func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { var canHaveDefault bool switch ft.Kind() { case reflect.Ptr: if ft.Elem().Kind() == reflect.Struct { nestedMessage = true } else { canHaveDefault = true // proto2 scalar field } case reflect.Slice: switch ft.Elem().Kind() { case reflect.Ptr: nestedMessage = true // repeated message case reflect.Uint8: canHaveDefault = true // bytes field } case reflect.Map: if ft.Elem().Kind() == reflect.Ptr { nestedMessage = true // map with message values } } if !canHaveDefault { if nestedMessage { return nil, true, nil } return nil, false, nil } // We now know that ft is a pointer or slice. sf = &scalarField{kind: ft.Elem().Kind()} // scalar fields without defaults if !prop.HasDefault { return sf, false, nil } // a scalar field: either *T or []byte switch ft.Elem().Kind() { case reflect.Bool: x, err := strconv.ParseBool(prop.Default) if err != nil { return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) } sf.value = x case reflect.Float32: x, err := strconv.ParseFloat(prop.Default, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) } sf.value = float32(x) case reflect.Float64: x, err := strconv.ParseFloat(prop.Default, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) } sf.value = x case reflect.Int32: x, err := strconv.ParseInt(prop.Default, 10, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) } sf.value = int32(x) case reflect.Int64: x, err := strconv.ParseInt(prop.Default, 10, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) } sf.value = x case reflect.String: sf.value = prop.Default case reflect.Uint8: // []byte (not *uint8) sf.value = []byte(prop.Default) case reflect.Uint32: x, err := strconv.ParseUint(prop.Default, 10, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) } sf.value = uint32(x) case reflect.Uint64: x, err := strconv.ParseUint(prop.Default, 10, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) } sf.value = x default: return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) } return sf, false, nil } // Map fields may have key types of non-float scalars, strings and enums. // The easiest way to sort them in some deterministic order is to use fmt. // If this turns out to be inefficient we can always consider other options, // such as doing a Schwartzian transform. func mapKeys(vs []reflect.Value) sort.Interface { s := mapKeySorter{ vs: vs, // default Less function: textual comparison less: func(a, b reflect.Value) bool { return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface()) }, } // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps; // numeric keys are sorted numerically. if len(vs) == 0 { return s } switch vs[0].Kind() { case reflect.Int32, reflect.Int64: s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } case reflect.Uint32, reflect.Uint64: s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } } return s } type mapKeySorter struct { vs []reflect.Value less func(a, b reflect.Value) bool } func (s mapKeySorter) Len() int { return len(s.vs) } func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } func (s mapKeySorter) Less(i, j int) bool { return s.less(s.vs[i], s.vs[j]) } // isProto3Zero reports whether v is a zero proto3 value. func isProto3Zero(v reflect.Value) bool { switch v.Kind() { case reflect.Bool: return !v.Bool() case reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint32, reflect.Uint64: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.String: return v.String() == "" } return false } // ProtoPackageIsVersion2 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion2 = true // ProtoPackageIsVersion1 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion1 = true ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/extensions_test.go�����������������������������0000644�0610621�0607500�00000040674�13172163407�027337� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "bytes" "fmt" "reflect" "sort" "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/proto/testdata" "golang.org/x/sync/errgroup" ) func TestGetExtensionsWithMissingExtensions(t *testing.T) { msg := &pb.MyMessage{} ext1 := &pb.Ext{} if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { t.Fatalf("Could not set ext1: %s", err) } exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ pb.E_Ext_More, pb.E_Ext_Text, }) if err != nil { t.Fatalf("GetExtensions() failed: %s", err) } if exts[0] != ext1 { t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) } if exts[1] != nil { t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) } } func TestExtensionDescsWithMissingExtensions(t *testing.T) { msg := &pb.MyMessage{Count: proto.Int32(0)} extdesc1 := pb.E_Ext_More if descs, err := proto.ExtensionDescs(msg); len(descs) != 0 || err != nil { t.Errorf("proto.ExtensionDescs: got %d descs, error %v; want 0, nil", len(descs), err) } ext1 := &pb.Ext{} if err := proto.SetExtension(msg, extdesc1, ext1); err != nil { t.Fatalf("Could not set ext1: %s", err) } extdesc2 := &proto.ExtensionDesc{ ExtendedType: (*pb.MyMessage)(nil), ExtensionType: (*bool)(nil), Field: 123456789, Name: "a.b", Tag: "varint,123456789,opt", } ext2 := proto.Bool(false) if err := proto.SetExtension(msg, extdesc2, ext2); err != nil { t.Fatalf("Could not set ext2: %s", err) } b, err := proto.Marshal(msg) if err != nil { t.Fatalf("Could not marshal msg: %v", err) } if err := proto.Unmarshal(b, msg); err != nil { t.Fatalf("Could not unmarshal into msg: %v", err) } descs, err := proto.ExtensionDescs(msg) if err != nil { t.Fatalf("proto.ExtensionDescs: got error %v", err) } sortExtDescs(descs) wantDescs := []*proto.ExtensionDesc{extdesc1, &proto.ExtensionDesc{Field: extdesc2.Field}} if !reflect.DeepEqual(descs, wantDescs) { t.Errorf("proto.ExtensionDescs(msg) sorted extension ids: got %+v, want %+v", descs, wantDescs) } } type ExtensionDescSlice []*proto.ExtensionDesc func (s ExtensionDescSlice) Len() int { return len(s) } func (s ExtensionDescSlice) Less(i, j int) bool { return s[i].Field < s[j].Field } func (s ExtensionDescSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func sortExtDescs(s []*proto.ExtensionDesc) { sort.Sort(ExtensionDescSlice(s)) } func TestGetExtensionStability(t *testing.T) { check := func(m *pb.MyMessage) bool { ext1, err := proto.GetExtension(m, pb.E_Ext_More) if err != nil { t.Fatalf("GetExtension() failed: %s", err) } ext2, err := proto.GetExtension(m, pb.E_Ext_More) if err != nil { t.Fatalf("GetExtension() failed: %s", err) } return ext1 == ext2 } msg := &pb.MyMessage{Count: proto.Int32(4)} ext0 := &pb.Ext{} if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { t.Fatalf("Could not set ext1: %s", ext0) } if !check(msg) { t.Errorf("GetExtension() not stable before marshaling") } bb, err := proto.Marshal(msg) if err != nil { t.Fatalf("Marshal() failed: %s", err) } msg1 := &pb.MyMessage{} err = proto.Unmarshal(bb, msg1) if err != nil { t.Fatalf("Unmarshal() failed: %s", err) } if !check(msg1) { t.Errorf("GetExtension() not stable after unmarshaling") } } func TestGetExtensionDefaults(t *testing.T) { var setFloat64 float64 = 1 var setFloat32 float32 = 2 var setInt32 int32 = 3 var setInt64 int64 = 4 var setUint32 uint32 = 5 var setUint64 uint64 = 6 var setBool = true var setBool2 = false var setString = "Goodnight string" var setBytes = []byte("Goodnight bytes") var setEnum = pb.DefaultsMessage_TWO type testcase struct { ext *proto.ExtensionDesc // Extension we are testing. want interface{} // Expected value of extension, or nil (meaning that GetExtension will fail). def interface{} // Expected value of extension after ClearExtension(). } tests := []testcase{ {pb.E_NoDefaultDouble, setFloat64, nil}, {pb.E_NoDefaultFloat, setFloat32, nil}, {pb.E_NoDefaultInt32, setInt32, nil}, {pb.E_NoDefaultInt64, setInt64, nil}, {pb.E_NoDefaultUint32, setUint32, nil}, {pb.E_NoDefaultUint64, setUint64, nil}, {pb.E_NoDefaultSint32, setInt32, nil}, {pb.E_NoDefaultSint64, setInt64, nil}, {pb.E_NoDefaultFixed32, setUint32, nil}, {pb.E_NoDefaultFixed64, setUint64, nil}, {pb.E_NoDefaultSfixed32, setInt32, nil}, {pb.E_NoDefaultSfixed64, setInt64, nil}, {pb.E_NoDefaultBool, setBool, nil}, {pb.E_NoDefaultBool, setBool2, nil}, {pb.E_NoDefaultString, setString, nil}, {pb.E_NoDefaultBytes, setBytes, nil}, {pb.E_NoDefaultEnum, setEnum, nil}, {pb.E_DefaultDouble, setFloat64, float64(3.1415)}, {pb.E_DefaultFloat, setFloat32, float32(3.14)}, {pb.E_DefaultInt32, setInt32, int32(42)}, {pb.E_DefaultInt64, setInt64, int64(43)}, {pb.E_DefaultUint32, setUint32, uint32(44)}, {pb.E_DefaultUint64, setUint64, uint64(45)}, {pb.E_DefaultSint32, setInt32, int32(46)}, {pb.E_DefaultSint64, setInt64, int64(47)}, {pb.E_DefaultFixed32, setUint32, uint32(48)}, {pb.E_DefaultFixed64, setUint64, uint64(49)}, {pb.E_DefaultSfixed32, setInt32, int32(50)}, {pb.E_DefaultSfixed64, setInt64, int64(51)}, {pb.E_DefaultBool, setBool, true}, {pb.E_DefaultBool, setBool2, true}, {pb.E_DefaultString, setString, "Hello, string"}, {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")}, {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE}, } checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error { val, err := proto.GetExtension(msg, test.ext) if err != nil { if valWant != nil { return fmt.Errorf("GetExtension(): %s", err) } if want := proto.ErrMissingExtension; err != want { return fmt.Errorf("Unexpected error: got %v, want %v", err, want) } return nil } // All proto2 extension values are either a pointer to a value or a slice of values. ty := reflect.TypeOf(val) tyWant := reflect.TypeOf(test.ext.ExtensionType) if got, want := ty, tyWant; got != want { return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want) } tye := ty.Elem() tyeWant := tyWant.Elem() if got, want := tye, tyeWant; got != want { return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want) } // Check the name of the type of the value. // If it is an enum it will be type int32 with the name of the enum. if got, want := tye.Name(), tye.Name(); got != want { return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want) } // Check that value is what we expect. // If we have a pointer in val, get the value it points to. valExp := val if ty.Kind() == reflect.Ptr { valExp = reflect.ValueOf(val).Elem().Interface() } if got, want := valExp, valWant; !reflect.DeepEqual(got, want) { return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want) } return nil } setTo := func(test testcase) interface{} { setTo := reflect.ValueOf(test.want) if typ := reflect.TypeOf(test.ext.ExtensionType); typ.Kind() == reflect.Ptr { setTo = reflect.New(typ).Elem() setTo.Set(reflect.New(setTo.Type().Elem())) setTo.Elem().Set(reflect.ValueOf(test.want)) } return setTo.Interface() } for _, test := range tests { msg := &pb.DefaultsMessage{} name := test.ext.Name // Check the initial value. if err := checkVal(test, msg, test.def); err != nil { t.Errorf("%s: %v", name, err) } // Set the per-type value and check value. name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want) if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil { t.Errorf("%s: SetExtension(): %v", name, err) continue } if err := checkVal(test, msg, test.want); err != nil { t.Errorf("%s: %v", name, err) continue } // Set and check the value. name += " (cleared)" proto.ClearExtension(msg, test.ext) if err := checkVal(test, msg, test.def); err != nil { t.Errorf("%s: %v", name, err) } } } func TestExtensionsRoundTrip(t *testing.T) { msg := &pb.MyMessage{} ext1 := &pb.Ext{ Data: proto.String("hi"), } ext2 := &pb.Ext{ Data: proto.String("there"), } exists := proto.HasExtension(msg, pb.E_Ext_More) if exists { t.Error("Extension More present unexpectedly") } if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { t.Error(err) } if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { t.Error(err) } e, err := proto.GetExtension(msg, pb.E_Ext_More) if err != nil { t.Error(err) } x, ok := e.(*pb.Ext) if !ok { t.Errorf("e has type %T, expected testdata.Ext", e) } else if *x.Data != "there" { t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) } proto.ClearExtension(msg, pb.E_Ext_More) if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { t.Errorf("got %v, expected ErrMissingExtension", e) } if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { t.Error("expected bad extension error, got nil") } if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { t.Error("expected extension err") } if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { t.Error("expected some sort of type mismatch error, got nil") } } func TestNilExtension(t *testing.T) { msg := &pb.MyMessage{ Count: proto.Int32(1), } if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil { t.Fatal(err) } if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil { t.Error("expected SetExtension to fail due to a nil extension") } else if want := "proto: SetExtension called with nil value of type *testdata.Ext"; err.Error() != want { t.Errorf("expected error %v, got %v", want, err) } // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update // this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal. } func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { // Add a repeated extension to the result. tests := []struct { name string ext []*pb.ComplexExtension }{ { "two fields", []*pb.ComplexExtension{ {First: proto.Int32(7)}, {Second: proto.Int32(11)}, }, }, { "repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {Third: []int32{2000}}, }, }, { "two fields and repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {First: proto.Int32(9)}, {Second: proto.Int32(21)}, {Third: []int32{2000}}, }, }, } for _, test := range tests { // Marshal message with a repeated extension. msg1 := new(pb.OtherMessage) err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) if err != nil { t.Fatalf("[%s] Error setting extension: %v", test.name, err) } b, err := proto.Marshal(msg1) if err != nil { t.Fatalf("[%s] Error marshaling message: %v", test.name, err) } // Unmarshal and read the merged proto. msg2 := new(pb.OtherMessage) err = proto.Unmarshal(b, msg2) if err != nil { t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) } e, err := proto.GetExtension(msg2, pb.E_RComplex) if err != nil { t.Fatalf("[%s] Error getting extension: %v", test.name, err) } ext := e.([]*pb.ComplexExtension) if ext == nil { t.Fatalf("[%s] Invalid extension", test.name) } if !reflect.DeepEqual(ext, test.ext) { t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) } } } func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { // We may see multiple instances of the same extension in the wire // format. For example, the proto compiler may encode custom options in // this way. Here, we verify that we merge the extensions together. tests := []struct { name string ext []*pb.ComplexExtension }{ { "two fields", []*pb.ComplexExtension{ {First: proto.Int32(7)}, {Second: proto.Int32(11)}, }, }, { "repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {Third: []int32{2000}}, }, }, { "two fields and repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {First: proto.Int32(9)}, {Second: proto.Int32(21)}, {Third: []int32{2000}}, }, }, } for _, test := range tests { var buf bytes.Buffer var want pb.ComplexExtension // Generate a serialized representation of a repeated extension // by catenating bytes together. for i, e := range test.ext { // Merge to create the wanted proto. proto.Merge(&want, e) // serialize the message msg := new(pb.OtherMessage) err := proto.SetExtension(msg, pb.E_Complex, e) if err != nil { t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) } b, err := proto.Marshal(msg) if err != nil { t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) } buf.Write(b) } // Unmarshal and read the merged proto. msg2 := new(pb.OtherMessage) err := proto.Unmarshal(buf.Bytes(), msg2) if err != nil { t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) } e, err := proto.GetExtension(msg2, pb.E_Complex) if err != nil { t.Fatalf("[%s] Error getting extension: %v", test.name, err) } ext := e.(*pb.ComplexExtension) if ext == nil { t.Fatalf("[%s] Invalid extension", test.name) } if !reflect.DeepEqual(*ext, want) { t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, want) } } } func TestClearAllExtensions(t *testing.T) { // unregistered extension desc := &proto.ExtensionDesc{ ExtendedType: (*pb.MyMessage)(nil), ExtensionType: (*bool)(nil), Field: 101010100, Name: "emptyextension", Tag: "varint,0,opt", } m := &pb.MyMessage{} if proto.HasExtension(m, desc) { t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) } if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) } if !proto.HasExtension(m, desc) { t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) } proto.ClearAllExtensions(m) if proto.HasExtension(m, desc) { t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) } } func TestMarshalRace(t *testing.T) { // unregistered extension desc := &proto.ExtensionDesc{ ExtendedType: (*pb.MyMessage)(nil), ExtensionType: (*bool)(nil), Field: 101010100, Name: "emptyextension", Tag: "varint,0,opt", } m := &pb.MyMessage{Count: proto.Int32(4)} if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) } var g errgroup.Group for n := 3; n > 0; n-- { g.Go(func() error { _, err := proto.Marshal(m) return err }) } if err := g.Wait(); err != nil { t.Fatal(err) } } ��������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/extensions.go����������������������������������0000644�0610621�0607500�00000043430�13172163407�026271� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto /* * Types and routines for supporting protocol buffer extensions. */ import ( "errors" "fmt" "reflect" "strconv" "sync" ) // ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. var ErrMissingExtension = errors.New("proto: missing extension") // ExtensionRange represents a range of message extensions for a protocol buffer. // Used in code generated by the protocol compiler. type ExtensionRange struct { Start, End int32 // both inclusive } // extendableProto is an interface implemented by any protocol buffer generated by the current // proto compiler that may be extended. type extendableProto interface { Message ExtensionRangeArray() []ExtensionRange extensionsWrite() map[int32]Extension extensionsRead() (map[int32]Extension, sync.Locker) } // extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous // version of the proto compiler that may be extended. type extendableProtoV1 interface { Message ExtensionRangeArray() []ExtensionRange ExtensionMap() map[int32]Extension } // extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. type extensionAdapter struct { extendableProtoV1 } func (e extensionAdapter) extensionsWrite() map[int32]Extension { return e.ExtensionMap() } func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { return e.ExtensionMap(), notLocker{} } // notLocker is a sync.Locker whose Lock and Unlock methods are nops. type notLocker struct{} func (n notLocker) Lock() {} func (n notLocker) Unlock() {} // extendable returns the extendableProto interface for the given generated proto message. // If the proto message has the old extension format, it returns a wrapper that implements // the extendableProto interface. func extendable(p interface{}) (extendableProto, bool) { if ep, ok := p.(extendableProto); ok { return ep, ok } if ep, ok := p.(extendableProtoV1); ok { return extensionAdapter{ep}, ok } return nil, false } // XXX_InternalExtensions is an internal representation of proto extensions. // // Each generated message struct type embeds an anonymous XXX_InternalExtensions field, // thus gaining the unexported 'extensions' method, which can be called only from the proto package. // // The methods of XXX_InternalExtensions are not concurrency safe in general, // but calls to logically read-only methods such as has and get may be executed concurrently. type XXX_InternalExtensions struct { // The struct must be indirect so that if a user inadvertently copies a // generated message and its embedded XXX_InternalExtensions, they // avoid the mayhem of a copied mutex. // // The mutex serializes all logically read-only operations to p.extensionMap. // It is up to the client to ensure that write operations to p.extensionMap are // mutually exclusive with other accesses. p *struct { mu sync.Mutex extensionMap map[int32]Extension } } // extensionsWrite returns the extension map, creating it on first use. func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { if e.p == nil { e.p = new(struct { mu sync.Mutex extensionMap map[int32]Extension }) e.p.extensionMap = make(map[int32]Extension) } return e.p.extensionMap } // extensionsRead returns the extensions map for read-only use. It may be nil. // The caller must hold the returned mutex's lock when accessing Elements within the map. func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { if e.p == nil { return nil, nil } return e.p.extensionMap, &e.p.mu } var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem() var extendableProtoV1Type = reflect.TypeOf((*extendableProtoV1)(nil)).Elem() // ExtensionDesc represents an extension specification. // Used in generated code from the protocol compiler. type ExtensionDesc struct { ExtendedType Message // nil pointer to the type that is being extended ExtensionType interface{} // nil pointer to the extension type Field int32 // field number Name string // fully-qualified name of extension, for text formatting Tag string // protobuf tag style Filename string // name of the file in which the extension is defined } func (ed *ExtensionDesc) repeated() bool { t := reflect.TypeOf(ed.ExtensionType) return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 } // Extension represents an extension in a message. type Extension struct { // When an extension is stored in a message using SetExtension // only desc and value are set. When the message is marshaled // enc will be set to the encoded form of the message. // // When a message is unmarshaled and contains extensions, each // extension will have only enc set. When such an extension is // accessed using GetExtension (or GetExtensions) desc and value // will be set. desc *ExtensionDesc value interface{} enc []byte } // SetRawExtension is for testing only. func SetRawExtension(base Message, id int32, b []byte) { epb, ok := extendable(base) if !ok { return } extmap := epb.extensionsWrite() extmap[id] = Extension{enc: b} } // isExtensionField returns true iff the given field number is in an extension range. func isExtensionField(pb extendableProto, field int32) bool { for _, er := range pb.ExtensionRangeArray() { if er.Start <= field && field <= er.End { return true } } return false } // checkExtensionTypes checks that the given extension is valid for pb. func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { var pbi interface{} = pb // Check the extended type. if ea, ok := pbi.(extensionAdapter); ok { pbi = ea.extendableProtoV1 } if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String()) } // Check the range. if !isExtensionField(pb, extension.Field) { return errors.New("proto: bad extension number; not in declared ranges") } return nil } // extPropKey is sufficient to uniquely identify an extension. type extPropKey struct { base reflect.Type field int32 } var extProp = struct { sync.RWMutex m map[extPropKey]*Properties }{ m: make(map[extPropKey]*Properties), } func extensionProperties(ed *ExtensionDesc) *Properties { key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} extProp.RLock() if prop, ok := extProp.m[key]; ok { extProp.RUnlock() return prop } extProp.RUnlock() extProp.Lock() defer extProp.Unlock() // Check again. if prop, ok := extProp.m[key]; ok { return prop } prop := new(Properties) prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) extProp.m[key] = prop return prop } // encode encodes any unmarshaled (unencoded) extensions in e. func encodeExtensions(e *XXX_InternalExtensions) error { m, mu := e.extensionsRead() if m == nil { return nil // fast path } mu.Lock() defer mu.Unlock() return encodeExtensionsMap(m) } // encode encodes any unmarshaled (unencoded) extensions in e. func encodeExtensionsMap(m map[int32]Extension) error { for k, e := range m { if e.value == nil || e.desc == nil { // Extension is only in its encoded form. continue } // We don't skip extensions that have an encoded form set, // because the extension value may have been mutated after // the last time this function was called. et := reflect.TypeOf(e.desc.ExtensionType) props := extensionProperties(e.desc) p := NewBuffer(nil) // If e.value has type T, the encoder expects a *struct{ X T }. // Pass a *T with a zero field and hope it all works out. x := reflect.New(et) x.Elem().Set(reflect.ValueOf(e.value)) if err := props.enc(p, props, toStructPointer(x)); err != nil { return err } e.enc = p.buf m[k] = e } return nil } func extensionsSize(e *XXX_InternalExtensions) (n int) { m, mu := e.extensionsRead() if m == nil { return 0 } mu.Lock() defer mu.Unlock() return extensionsMapSize(m) } func extensionsMapSize(m map[int32]Extension) (n int) { for _, e := range m { if e.value == nil || e.desc == nil { // Extension is only in its encoded form. n += len(e.enc) continue } // We don't skip extensions that have an encoded form set, // because the extension value may have been mutated after // the last time this function was called. et := reflect.TypeOf(e.desc.ExtensionType) props := extensionProperties(e.desc) // If e.value has type T, the encoder expects a *struct{ X T }. // Pass a *T with a zero field and hope it all works out. x := reflect.New(et) x.Elem().Set(reflect.ValueOf(e.value)) n += props.size(props, toStructPointer(x)) } return } // HasExtension returns whether the given extension is present in pb. func HasExtension(pb Message, extension *ExtensionDesc) bool { // TODO: Check types, field numbers, etc.? epb, ok := extendable(pb) if !ok { return false } extmap, mu := epb.extensionsRead() if extmap == nil { return false } mu.Lock() _, ok = extmap[extension.Field] mu.Unlock() return ok } // ClearExtension removes the given extension from pb. func ClearExtension(pb Message, extension *ExtensionDesc) { epb, ok := extendable(pb) if !ok { return } // TODO: Check types, field numbers, etc.? extmap := epb.extensionsWrite() delete(extmap, extension.Field) } // GetExtension parses and returns the given extension of pb. // If the extension is not present and has no default value it returns ErrMissingExtension. func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { epb, ok := extendable(pb) if !ok { return nil, errors.New("proto: not an extendable proto") } if err := checkExtensionTypes(epb, extension); err != nil { return nil, err } emap, mu := epb.extensionsRead() if emap == nil { return defaultExtensionValue(extension) } mu.Lock() defer mu.Unlock() e, ok := emap[extension.Field] if !ok { // defaultExtensionValue returns the default value or // ErrMissingExtension if there is no default. return defaultExtensionValue(extension) } if e.value != nil { // Already decoded. Check the descriptor, though. if e.desc != extension { // This shouldn't happen. If it does, it means that // GetExtension was called twice with two different // descriptors with the same field number. return nil, errors.New("proto: descriptor conflict") } return e.value, nil } v, err := decodeExtension(e.enc, extension) if err != nil { return nil, err } // Remember the decoded version and drop the encoded version. // That way it is safe to mutate what we return. e.value = v e.desc = extension e.enc = nil emap[extension.Field] = e return e.value, nil } // defaultExtensionValue returns the default value for extension. // If no default for an extension is defined ErrMissingExtension is returned. func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { t := reflect.TypeOf(extension.ExtensionType) props := extensionProperties(extension) sf, _, err := fieldDefault(t, props) if err != nil { return nil, err } if sf == nil || sf.value == nil { // There is no default value. return nil, ErrMissingExtension } if t.Kind() != reflect.Ptr { // We do not need to return a Ptr, we can directly return sf.value. return sf.value, nil } // We need to return an interface{} that is a pointer to sf.value. value := reflect.New(t).Elem() value.Set(reflect.New(value.Type().Elem())) if sf.kind == reflect.Int32 { // We may have an int32 or an enum, but the underlying data is int32. // Since we can't set an int32 into a non int32 reflect.value directly // set it as a int32. value.Elem().SetInt(int64(sf.value.(int32))) } else { value.Elem().Set(reflect.ValueOf(sf.value)) } return value.Interface(), nil } // decodeExtension decodes an extension encoded in b. func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { o := NewBuffer(b) t := reflect.TypeOf(extension.ExtensionType) props := extensionProperties(extension) // t is a pointer to a struct, pointer to basic type or a slice. // Allocate a "field" to store the pointer/slice itself; the // pointer/slice will be stored here. We pass // the address of this field to props.dec. // This passes a zero field and a *t and lets props.dec // interpret it as a *struct{ x t }. value := reflect.New(t).Elem() for { // Discard wire type and field number varint. It isn't needed. if _, err := o.DecodeVarint(); err != nil { return nil, err } if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil { return nil, err } if o.index >= len(o.buf) { break } } return value.Interface(), nil } // GetExtensions returns a slice of the extensions present in pb that are also listed in es. // The returned slice has the same length as es; missing extensions will appear as nil elements. func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { epb, ok := extendable(pb) if !ok { return nil, errors.New("proto: not an extendable proto") } extensions = make([]interface{}, len(es)) for i, e := range es { extensions[i], err = GetExtension(epb, e) if err == ErrMissingExtension { err = nil } if err != nil { return } } return } // ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. // For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing // just the Field field, which defines the extension's field number. func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { epb, ok := extendable(pb) if !ok { return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb) } registeredExtensions := RegisteredExtensions(pb) emap, mu := epb.extensionsRead() if emap == nil { return nil, nil } mu.Lock() defer mu.Unlock() extensions := make([]*ExtensionDesc, 0, len(emap)) for extid, e := range emap { desc := e.desc if desc == nil { desc = registeredExtensions[extid] if desc == nil { desc = &ExtensionDesc{Field: extid} } } extensions = append(extensions, desc) } return extensions, nil } // SetExtension sets the specified extension of pb to the specified value. func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { epb, ok := extendable(pb) if !ok { return errors.New("proto: not an extendable proto") } if err := checkExtensionTypes(epb, extension); err != nil { return err } typ := reflect.TypeOf(extension.ExtensionType) if typ != reflect.TypeOf(value) { return errors.New("proto: bad extension value type") } // nil extension values need to be caught early, because the // encoder can't distinguish an ErrNil due to a nil extension // from an ErrNil due to a missing field. Extensions are // always optional, so the encoder would just swallow the error // and drop all the extensions from the encoded message. if reflect.ValueOf(value).IsNil() { return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) } extmap := epb.extensionsWrite() extmap[extension.Field] = Extension{desc: extension, value: value} return nil } // ClearAllExtensions clears all extensions from pb. func ClearAllExtensions(pb Message) { epb, ok := extendable(pb) if !ok { return } m := epb.extensionsWrite() for k := range m { delete(m, k) } } // A global registry of extensions. // The generated code will register the generated descriptors by calling RegisterExtension. var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) // RegisterExtension is called from the generated code. func RegisterExtension(desc *ExtensionDesc) { st := reflect.TypeOf(desc.ExtendedType).Elem() m := extensionMaps[st] if m == nil { m = make(map[int32]*ExtensionDesc) extensionMaps[st] = m } if _, ok := m[desc.Field]; ok { panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) } m[desc.Field] = desc } // RegisteredExtensions returns a map of the registered extensions of a // protocol buffer struct, indexed by the extension number. // The argument pb should be a nil pointer to the struct type. func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { return extensionMaps[reflect.TypeOf(pb).Elem()] } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/equal_test.go����������������������������������0000644�0610621�0607500�00000020530�13172163407�026234� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "testing" . "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) // Four identical base messages. // The init function adds extensions to some of them. var messageWithoutExtension = &pb.MyMessage{Count: Int32(7)} var messageWithExtension1a = &pb.MyMessage{Count: Int32(7)} var messageWithExtension1b = &pb.MyMessage{Count: Int32(7)} var messageWithExtension2 = &pb.MyMessage{Count: Int32(7)} // Two messages with non-message extensions. var messageWithInt32Extension1 = &pb.MyMessage{Count: Int32(8)} var messageWithInt32Extension2 = &pb.MyMessage{Count: Int32(8)} func init() { ext1 := &pb.Ext{Data: String("Kirk")} ext2 := &pb.Ext{Data: String("Picard")} // messageWithExtension1a has ext1, but never marshals it. if err := SetExtension(messageWithExtension1a, pb.E_Ext_More, ext1); err != nil { panic("SetExtension on 1a failed: " + err.Error()) } // messageWithExtension1b is the unmarshaled form of messageWithExtension1a. if err := SetExtension(messageWithExtension1b, pb.E_Ext_More, ext1); err != nil { panic("SetExtension on 1b failed: " + err.Error()) } buf, err := Marshal(messageWithExtension1b) if err != nil { panic("Marshal of 1b failed: " + err.Error()) } messageWithExtension1b.Reset() if err := Unmarshal(buf, messageWithExtension1b); err != nil { panic("Unmarshal of 1b failed: " + err.Error()) } // messageWithExtension2 has ext2. if err := SetExtension(messageWithExtension2, pb.E_Ext_More, ext2); err != nil { panic("SetExtension on 2 failed: " + err.Error()) } if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(23)); err != nil { panic("SetExtension on Int32-1 failed: " + err.Error()) } if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(24)); err != nil { panic("SetExtension on Int32-2 failed: " + err.Error()) } } var EqualTests = []struct { desc string a, b Message exp bool }{ {"different types", &pb.GoEnum{}, &pb.GoTestField{}, false}, {"equal empty", &pb.GoEnum{}, &pb.GoEnum{}, true}, {"nil vs nil", nil, nil, true}, {"typed nil vs typed nil", (*pb.GoEnum)(nil), (*pb.GoEnum)(nil), true}, {"typed nil vs empty", (*pb.GoEnum)(nil), &pb.GoEnum{}, false}, {"different typed nil", (*pb.GoEnum)(nil), (*pb.GoTestField)(nil), false}, {"one set field, one unset field", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{}, false}, {"one set field zero, one unset field", &pb.GoTest{Param: Int32(0)}, &pb.GoTest{}, false}, {"different set fields", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("bar")}, false}, {"equal set", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("foo")}, true}, {"repeated, one set", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{}, false}, {"repeated, different length", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{F_Int32Repeated: []int32{2}}, false}, {"repeated, different value", &pb.GoTest{F_Int32Repeated: []int32{2}}, &pb.GoTest{F_Int32Repeated: []int32{3}}, false}, {"repeated, equal", &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, true}, {"repeated, nil equal nil", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: nil}, true}, {"repeated, nil equal empty", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: []int32{}}, true}, {"repeated, empty equal nil", &pb.GoTest{F_Int32Repeated: []int32{}}, &pb.GoTest{F_Int32Repeated: nil}, true}, { "nested, different", &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("foo")}}, &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("bar")}}, false, }, { "nested, equal", &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, true, }, {"bytes", &pb.OtherMessage{Value: []byte("foo")}, &pb.OtherMessage{Value: []byte("foo")}, true}, {"bytes, empty", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: []byte{}}, true}, {"bytes, empty vs nil", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: nil}, false}, { "repeated bytes", &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, true, }, // In proto3, []byte{} and []byte(nil) are equal. {"proto3 bytes, empty vs nil", &proto3pb.Message{Data: []byte{}}, &proto3pb.Message{Data: nil}, true}, {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false}, {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true}, {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false}, {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true}, {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false}, { "message with group", &pb.MyMessage{ Count: Int32(1), Somegroup: &pb.MyMessage_SomeGroup{ GroupField: Int32(5), }, }, &pb.MyMessage{ Count: Int32(1), Somegroup: &pb.MyMessage_SomeGroup{ GroupField: Int32(5), }, }, true, }, { "map same", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, true, }, { "map different entry", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}}, false, }, { "map different key only", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, &pb.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}}, false, }, { "map different value only", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}}, false, }, { "zero-length maps same", &pb.MessageWithMap{NameMapping: map[int32]string{}}, &pb.MessageWithMap{NameMapping: nil}, true, }, { "orders in map don't matter", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken", 2: "Rob"}}, &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob", 1: "Ken"}}, true, }, { "oneof same", &pb.Communique{Union: &pb.Communique_Number{41}}, &pb.Communique{Union: &pb.Communique_Number{41}}, true, }, { "oneof one nil", &pb.Communique{Union: &pb.Communique_Number{41}}, &pb.Communique{}, false, }, { "oneof different", &pb.Communique{Union: &pb.Communique_Number{41}}, &pb.Communique{Union: &pb.Communique_Name{"Bobby Tables"}}, false, }, } func TestEqual(t *testing.T) { for _, tc := range EqualTests { if res := Equal(tc.a, tc.b); res != tc.exp { t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/equal.go���������������������������������������0000644�0610621�0607500�00000020661�13172163407�025202� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Protocol buffer comparison. package proto import ( "bytes" "log" "reflect" "strings" ) /* Equal returns true iff protocol buffers a and b are equal. The arguments must both be pointers to protocol buffer structs. Equality is defined in this way: - Two messages are equal iff they are the same type, corresponding fields are equal, unknown field sets are equal, and extensions sets are equal. - Two set scalar fields are equal iff their values are equal. If the fields are of a floating-point type, remember that NaN != x for all x, including NaN. If the message is defined in a proto3 .proto file, fields are not "set"; specifically, zero length proto3 "bytes" fields are equal (nil == {}). - Two repeated fields are equal iff their lengths are the same, and their corresponding elements are equal. Note a "bytes" field, although represented by []byte, is not a repeated field and the rule for the scalar fields described above applies. - Two unset fields are equal. - Two unknown field sets are equal if their current encoded state is equal. - Two extension sets are equal iff they have corresponding elements that are pairwise equal. - Two map fields are equal iff their lengths are the same, and they contain the same set of elements. Zero-length map fields are equal. - Every other combination of things are not equal. The return value is undefined if a and b are not protocol buffers. */ func Equal(a, b Message) bool { if a == nil || b == nil { return a == b } v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) if v1.Type() != v2.Type() { return false } if v1.Kind() == reflect.Ptr { if v1.IsNil() { return v2.IsNil() } if v2.IsNil() { return false } v1, v2 = v1.Elem(), v2.Elem() } if v1.Kind() != reflect.Struct { return false } return equalStruct(v1, v2) } // v1 and v2 are known to have the same type. func equalStruct(v1, v2 reflect.Value) bool { sprop := GetProperties(v1.Type()) for i := 0; i < v1.NumField(); i++ { f := v1.Type().Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } f1, f2 := v1.Field(i), v2.Field(i) if f.Type.Kind() == reflect.Ptr { if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { // both unset continue } else if n1 != n2 { // set/unset mismatch return false } b1, ok := f1.Interface().(raw) if ok { b2 := f2.Interface().(raw) // RawMessage if !bytes.Equal(b1.Bytes(), b2.Bytes()) { return false } continue } f1, f2 = f1.Elem(), f2.Elem() } if !equalAny(f1, f2, sprop.Prop[i]) { return false } } if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { em2 := v2.FieldByName("XXX_InternalExtensions") if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { return false } } if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { em2 := v2.FieldByName("XXX_extensions") if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { return false } } uf := v1.FieldByName("XXX_unrecognized") if !uf.IsValid() { return true } u1 := uf.Bytes() u2 := v2.FieldByName("XXX_unrecognized").Bytes() if !bytes.Equal(u1, u2) { return false } return true } // v1 and v2 are known to have the same type. // prop may be nil. func equalAny(v1, v2 reflect.Value, prop *Properties) bool { if v1.Type() == protoMessageType { m1, _ := v1.Interface().(Message) m2, _ := v2.Interface().(Message) return Equal(m1, m2) } switch v1.Kind() { case reflect.Bool: return v1.Bool() == v2.Bool() case reflect.Float32, reflect.Float64: return v1.Float() == v2.Float() case reflect.Int32, reflect.Int64: return v1.Int() == v2.Int() case reflect.Interface: // Probably a oneof field; compare the inner values. n1, n2 := v1.IsNil(), v2.IsNil() if n1 || n2 { return n1 == n2 } e1, e2 := v1.Elem(), v2.Elem() if e1.Type() != e2.Type() { return false } return equalAny(e1, e2, nil) case reflect.Map: if v1.Len() != v2.Len() { return false } for _, key := range v1.MapKeys() { val2 := v2.MapIndex(key) if !val2.IsValid() { // This key was not found in the second map. return false } if !equalAny(v1.MapIndex(key), val2, nil) { return false } } return true case reflect.Ptr: // Maps may have nil values in them, so check for nil. if v1.IsNil() && v2.IsNil() { return true } if v1.IsNil() != v2.IsNil() { return false } return equalAny(v1.Elem(), v2.Elem(), prop) case reflect.Slice: if v1.Type().Elem().Kind() == reflect.Uint8 { // short circuit: []byte // Edge case: if this is in a proto3 message, a zero length // bytes field is considered the zero value. if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { return true } if v1.IsNil() != v2.IsNil() { return false } return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) } if v1.Len() != v2.Len() { return false } for i := 0; i < v1.Len(); i++ { if !equalAny(v1.Index(i), v2.Index(i), prop) { return false } } return true case reflect.String: return v1.Interface().(string) == v2.Interface().(string) case reflect.Struct: return equalStruct(v1, v2) case reflect.Uint32, reflect.Uint64: return v1.Uint() == v2.Uint() } // unknown type, so not a protocol buffer log.Printf("proto: don't know how to compare %v", v1) return false } // base is the struct type that the extensions are based on. // x1 and x2 are InternalExtensions. func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { em1, _ := x1.extensionsRead() em2, _ := x2.extensionsRead() return equalExtMap(base, em1, em2) } func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { if len(em1) != len(em2) { return false } for extNum, e1 := range em1 { e2, ok := em2[extNum] if !ok { return false } m1, m2 := e1.value, e2.value if m1 != nil && m2 != nil { // Both are unencoded. if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { return false } continue } // At least one is encoded. To do a semantically correct comparison // we need to unmarshal them first. var desc *ExtensionDesc if m := extensionMaps[base]; m != nil { desc = m[extNum] } if desc == nil { log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) continue } var err error if m1 == nil { m1, err = decodeExtension(e1.enc, desc) } if m2 == nil && err == nil { m2, err = decodeExtension(e2.enc, desc) } if err != nil { // The encoded form is invalid. log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) return false } if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { return false } } return true } �������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/encode_test.go���������������������������������0000644�0610621�0607500�00000005350�13172163407�026365� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // +build go1.7 package proto_test import ( "strconv" "testing" "github.com/golang/protobuf/proto" tpb "github.com/golang/protobuf/proto/proto3_proto" "github.com/golang/protobuf/ptypes" ) var ( blackhole []byte ) // BenchmarkAny creates increasingly large arbitrary Any messages. The type is always the // same. func BenchmarkAny(b *testing.B) { data := make([]byte, 1<<20) quantum := 1 << 10 for i := uint(0); i <= 10; i++ { b.Run(strconv.Itoa(quantum<<i), func(b *testing.B) { for k := 0; k < b.N; k++ { inner := &tpb.Message{ Data: data[:quantum<<i], } outer, err := ptypes.MarshalAny(inner) if err != nil { b.Error("wrong encode", err) } raw, err := proto.Marshal(&tpb.Message{ Anything: outer, }) if err != nil { b.Error("wrong encode", err) } blackhole = raw } }) } } // BenchmarkEmpy measures the overhead of doing the minimal possible encode. func BenchmarkEmpy(b *testing.B) { for i := 0; i < b.N; i++ { raw, err := proto.Marshal(&tpb.Message{}) if err != nil { b.Error("wrong encode", err) } blackhole = raw } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/encode.go��������������������������������������0000644�0610621�0607500�00000103726�13172163407�025334� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto /* * Routines for encoding data into the wire format for protocol buffers. */ import ( "errors" "fmt" "reflect" "sort" ) // RequiredNotSetError is the error returned if Marshal is called with // a protocol buffer struct whose required fields have not // all been initialized. It is also the error returned if Unmarshal is // called with an encoded protocol buffer that does not include all the // required fields. // // When printed, RequiredNotSetError reports the first unset required field in a // message. If the field cannot be precisely determined, it is reported as // "{Unknown}". type RequiredNotSetError struct { field string } func (e *RequiredNotSetError) Error() string { return fmt.Sprintf("proto: required field %q not set", e.field) } var ( // errRepeatedHasNil is the error returned if Marshal is called with // a struct with a repeated field containing a nil element. errRepeatedHasNil = errors.New("proto: repeated field has nil element") // errOneofHasNil is the error returned if Marshal is called with // a struct with a oneof field containing a nil element. errOneofHasNil = errors.New("proto: oneof field has nil value") // ErrNil is the error returned if Marshal is called with nil. ErrNil = errors.New("proto: Marshal called with nil") // ErrTooLarge is the error returned if Marshal is called with a // message that encodes to >2GB. ErrTooLarge = errors.New("proto: message encodes to over 2 GB") ) // The fundamental encoders that put bytes on the wire. // Those that take integer types all accept uint64 and are // therefore of type valueEncoder. const maxVarintBytes = 10 // maximum length of a varint // maxMarshalSize is the largest allowed size of an encoded protobuf, // since C++ and Java use signed int32s for the size. const maxMarshalSize = 1<<31 - 1 // EncodeVarint returns the varint encoding of x. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. // Not used by the package itself, but helpful to clients // wishing to use the same encoding. func EncodeVarint(x uint64) []byte { var buf [maxVarintBytes]byte var n int for n = 0; x > 127; n++ { buf[n] = 0x80 | uint8(x&0x7F) x >>= 7 } buf[n] = uint8(x) n++ return buf[0:n] } // EncodeVarint writes a varint-encoded integer to the Buffer. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func (p *Buffer) EncodeVarint(x uint64) error { for x >= 1<<7 { p.buf = append(p.buf, uint8(x&0x7f|0x80)) x >>= 7 } p.buf = append(p.buf, uint8(x)) return nil } // SizeVarint returns the varint encoding size of an integer. func SizeVarint(x uint64) int { return sizeVarint(x) } func sizeVarint(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } // EncodeFixed64 writes a 64-bit integer to the Buffer. // This is the format for the // fixed64, sfixed64, and double protocol buffer types. func (p *Buffer) EncodeFixed64(x uint64) error { p.buf = append(p.buf, uint8(x), uint8(x>>8), uint8(x>>16), uint8(x>>24), uint8(x>>32), uint8(x>>40), uint8(x>>48), uint8(x>>56)) return nil } func sizeFixed64(x uint64) int { return 8 } // EncodeFixed32 writes a 32-bit integer to the Buffer. // This is the format for the // fixed32, sfixed32, and float protocol buffer types. func (p *Buffer) EncodeFixed32(x uint64) error { p.buf = append(p.buf, uint8(x), uint8(x>>8), uint8(x>>16), uint8(x>>24)) return nil } func sizeFixed32(x uint64) int { return 4 } // EncodeZigzag64 writes a zigzag-encoded 64-bit integer // to the Buffer. // This is the format used for the sint64 protocol buffer type. func (p *Buffer) EncodeZigzag64(x uint64) error { // use signed number to get arithmetic right shift. return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63))) } func sizeZigzag64(x uint64) int { return sizeVarint((x << 1) ^ uint64((int64(x) >> 63))) } // EncodeZigzag32 writes a zigzag-encoded 32-bit integer // to the Buffer. // This is the format used for the sint32 protocol buffer type. func (p *Buffer) EncodeZigzag32(x uint64) error { // use signed number to get arithmetic right shift. return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) } func sizeZigzag32(x uint64) int { return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) } // EncodeRawBytes writes a count-delimited byte buffer to the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. func (p *Buffer) EncodeRawBytes(b []byte) error { p.EncodeVarint(uint64(len(b))) p.buf = append(p.buf, b...) return nil } func sizeRawBytes(b []byte) int { return sizeVarint(uint64(len(b))) + len(b) } // EncodeStringBytes writes an encoded string to the Buffer. // This is the format used for the proto2 string type. func (p *Buffer) EncodeStringBytes(s string) error { p.EncodeVarint(uint64(len(s))) p.buf = append(p.buf, s...) return nil } func sizeStringBytes(s string) int { return sizeVarint(uint64(len(s))) + len(s) } // Marshaler is the interface representing objects that can marshal themselves. type Marshaler interface { Marshal() ([]byte, error) } // Marshal takes the protocol buffer // and encodes it into the wire format, returning the data. func Marshal(pb Message) ([]byte, error) { // Can the object marshal itself? if m, ok := pb.(Marshaler); ok { return m.Marshal() } p := NewBuffer(nil) err := p.Marshal(pb) if p.buf == nil && err == nil { // Return a non-nil slice on success. return []byte{}, nil } return p.buf, err } // EncodeMessage writes the protocol buffer to the Buffer, // prefixed by a varint-encoded length. func (p *Buffer) EncodeMessage(pb Message) error { t, base, err := getbase(pb) if structPointer_IsNil(base) { return ErrNil } if err == nil { var state errorState err = p.enc_len_struct(GetProperties(t.Elem()), base, &state) } return err } // Marshal takes the protocol buffer // and encodes it into the wire format, writing the result to the // Buffer. func (p *Buffer) Marshal(pb Message) error { // Can the object marshal itself? if m, ok := pb.(Marshaler); ok { data, err := m.Marshal() p.buf = append(p.buf, data...) return err } t, base, err := getbase(pb) if structPointer_IsNil(base) { return ErrNil } if err == nil { err = p.enc_struct(GetProperties(t.Elem()), base) } if collectStats { (stats).Encode++ // Parens are to work around a goimports bug. } if len(p.buf) > maxMarshalSize { return ErrTooLarge } return err } // Size returns the encoded size of a protocol buffer. func Size(pb Message) (n int) { // Can the object marshal itself? If so, Size is slow. // TODO: add Size to Marshaler, or add a Sizer interface. if m, ok := pb.(Marshaler); ok { b, _ := m.Marshal() return len(b) } t, base, err := getbase(pb) if structPointer_IsNil(base) { return 0 } if err == nil { n = size_struct(GetProperties(t.Elem()), base) } if collectStats { (stats).Size++ // Parens are to work around a goimports bug. } return } // Individual type encoders. // Encode a bool. func (o *Buffer) enc_bool(p *Properties, base structPointer) error { v := *structPointer_Bool(base, p.field) if v == nil { return ErrNil } x := 0 if *v { x = 1 } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { v := *structPointer_BoolVal(base, p.field) if !v { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, 1) return nil } func size_bool(p *Properties, base structPointer) int { v := *structPointer_Bool(base, p.field) if v == nil { return 0 } return len(p.tagcode) + 1 // each bool takes exactly one byte } func size_proto3_bool(p *Properties, base structPointer) int { v := *structPointer_BoolVal(base, p.field) if !v && !p.oneof { return 0 } return len(p.tagcode) + 1 // each bool takes exactly one byte } // Encode an int32. func (o *Buffer) enc_int32(p *Properties, base structPointer) error { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return ErrNil } x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { v := structPointer_Word32Val(base, p.field) x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func size_int32(p *Properties, base structPointer) (n int) { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return 0 } x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range n += len(p.tagcode) n += p.valSize(uint64(x)) return } func size_proto3_int32(p *Properties, base structPointer) (n int) { v := structPointer_Word32Val(base, p.field) x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(uint64(x)) return } // Encode a uint32. // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return ErrNil } x := word32_Get(v) o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { v := structPointer_Word32Val(base, p.field) x := word32Val_Get(v) if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func size_uint32(p *Properties, base structPointer) (n int) { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return 0 } x := word32_Get(v) n += len(p.tagcode) n += p.valSize(uint64(x)) return } func size_proto3_uint32(p *Properties, base structPointer) (n int) { v := structPointer_Word32Val(base, p.field) x := word32Val_Get(v) if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(uint64(x)) return } // Encode an int64. func (o *Buffer) enc_int64(p *Properties, base structPointer) error { v := structPointer_Word64(base, p.field) if word64_IsNil(v) { return ErrNil } x := word64_Get(v) o.buf = append(o.buf, p.tagcode...) p.valEnc(o, x) return nil } func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { v := structPointer_Word64Val(base, p.field) x := word64Val_Get(v) if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, x) return nil } func size_int64(p *Properties, base structPointer) (n int) { v := structPointer_Word64(base, p.field) if word64_IsNil(v) { return 0 } x := word64_Get(v) n += len(p.tagcode) n += p.valSize(x) return } func size_proto3_int64(p *Properties, base structPointer) (n int) { v := structPointer_Word64Val(base, p.field) x := word64Val_Get(v) if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(x) return } // Encode a string. func (o *Buffer) enc_string(p *Properties, base structPointer) error { v := *structPointer_String(base, p.field) if v == nil { return ErrNil } x := *v o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(x) return nil } func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { v := *structPointer_StringVal(base, p.field) if v == "" { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(v) return nil } func size_string(p *Properties, base structPointer) (n int) { v := *structPointer_String(base, p.field) if v == nil { return 0 } x := *v n += len(p.tagcode) n += sizeStringBytes(x) return } func size_proto3_string(p *Properties, base structPointer) (n int) { v := *structPointer_StringVal(base, p.field) if v == "" && !p.oneof { return 0 } n += len(p.tagcode) n += sizeStringBytes(v) return } // All protocol buffer fields are nillable, but be careful. func isNil(v reflect.Value) bool { switch v.Kind() { case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false } // Encode a message struct. func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { var state errorState structp := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(structp) { return ErrNil } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, err := m.Marshal() if err != nil && !state.shouldContinue(err, nil) { return err } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(data) return state.err } o.buf = append(o.buf, p.tagcode...) return o.enc_len_struct(p.sprop, structp, &state) } func size_struct_message(p *Properties, base structPointer) int { structp := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(structp) { return 0 } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, _ := m.Marshal() n0 := len(p.tagcode) n1 := sizeRawBytes(data) return n0 + n1 } n0 := len(p.tagcode) n1 := size_struct(p.sprop, structp) n2 := sizeVarint(uint64(n1)) // size of encoded length return n0 + n1 + n2 } // Encode a group struct. func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { var state errorState b := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(b) { return ErrNil } o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) err := o.enc_struct(p.sprop, b) if err != nil && !state.shouldContinue(err, nil) { return err } o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) return state.err } func size_struct_group(p *Properties, base structPointer) (n int) { b := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(b) { return 0 } n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) n += size_struct(p.sprop, b) n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) return } // Encode a slice of bools ([]bool). func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return ErrNil } for _, x := range s { o.buf = append(o.buf, p.tagcode...) v := uint64(0) if x { v = 1 } p.valEnc(o, v) } return nil } func size_slice_bool(p *Properties, base structPointer) int { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return 0 } return l * (len(p.tagcode) + 1) // each bool takes exactly one byte } // Encode a slice of bools ([]bool) in packed format. func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(l)) // each bool takes exactly one byte for _, x := range s { v := uint64(0) if x { v = 1 } p.valEnc(o, v) } return nil } func size_slice_packed_bool(p *Properties, base structPointer) (n int) { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return 0 } n += len(p.tagcode) n += sizeVarint(uint64(l)) n += l // each bool takes exactly one byte return } // Encode a slice of bytes ([]byte). func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { s := *structPointer_Bytes(base, p.field) if s == nil { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(s) return nil } func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { s := *structPointer_Bytes(base, p.field) if len(s) == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(s) return nil } func size_slice_byte(p *Properties, base structPointer) (n int) { s := *structPointer_Bytes(base, p.field) if s == nil && !p.oneof { return 0 } n += len(p.tagcode) n += sizeRawBytes(s) return } func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { s := *structPointer_Bytes(base, p.field) if len(s) == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += sizeRawBytes(s) return } // Encode a slice of int32s ([]int32). func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) x := int32(s.Index(i)) // permit sign extension to use full 64-bit range p.valEnc(o, uint64(x)) } return nil } func size_slice_int32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) x := int32(s.Index(i)) // permit sign extension to use full 64-bit range n += p.valSize(uint64(x)) } return } // Encode a slice of int32s ([]int32) in packed format. func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { x := int32(s.Index(i)) // permit sign extension to use full 64-bit range p.valEnc(buf, uint64(x)) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_int32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { x := int32(s.Index(i)) // permit sign extension to use full 64-bit range bufSize += p.valSize(uint64(x)) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of uint32s ([]uint32). // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) x := s.Index(i) p.valEnc(o, uint64(x)) } return nil } func size_slice_uint32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) x := s.Index(i) n += p.valSize(uint64(x)) } return } // Encode a slice of uint32s ([]uint32) in packed format. // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { p.valEnc(buf, uint64(s.Index(i))) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { bufSize += p.valSize(uint64(s.Index(i))) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of int64s ([]int64). func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) p.valEnc(o, s.Index(i)) } return nil } func size_slice_int64(p *Properties, base structPointer) (n int) { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) n += p.valSize(s.Index(i)) } return } // Encode a slice of int64s ([]int64) in packed format. func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { p.valEnc(buf, s.Index(i)) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_int64(p *Properties, base structPointer) (n int) { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { bufSize += p.valSize(s.Index(i)) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of slice of bytes ([][]byte). func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { ss := *structPointer_BytesSlice(base, p.field) l := len(ss) if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(ss[i]) } return nil } func size_slice_slice_byte(p *Properties, base structPointer) (n int) { ss := *structPointer_BytesSlice(base, p.field) l := len(ss) if l == 0 { return 0 } n += l * len(p.tagcode) for i := 0; i < l; i++ { n += sizeRawBytes(ss[i]) } return } // Encode a slice of strings ([]string). func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { ss := *structPointer_StringSlice(base, p.field) l := len(ss) for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(ss[i]) } return nil } func size_slice_string(p *Properties, base structPointer) (n int) { ss := *structPointer_StringSlice(base, p.field) l := len(ss) n += l * len(p.tagcode) for i := 0; i < l; i++ { n += sizeStringBytes(ss[i]) } return } // Encode a slice of message structs ([]*struct). func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { var state errorState s := structPointer_StructPointerSlice(base, p.field) l := s.Len() for i := 0; i < l; i++ { structp := s.Index(i) if structPointer_IsNil(structp) { return errRepeatedHasNil } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, err := m.Marshal() if err != nil && !state.shouldContinue(err, nil) { return err } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(data) continue } o.buf = append(o.buf, p.tagcode...) err := o.enc_len_struct(p.sprop, structp, &state) if err != nil && !state.shouldContinue(err, nil) { if err == ErrNil { return errRepeatedHasNil } return err } } return state.err } func size_slice_struct_message(p *Properties, base structPointer) (n int) { s := structPointer_StructPointerSlice(base, p.field) l := s.Len() n += l * len(p.tagcode) for i := 0; i < l; i++ { structp := s.Index(i) if structPointer_IsNil(structp) { return // return the size up to this point } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, _ := m.Marshal() n += sizeRawBytes(data) continue } n0 := size_struct(p.sprop, structp) n1 := sizeVarint(uint64(n0)) // size of encoded length n += n0 + n1 } return } // Encode a slice of group structs ([]*struct). func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { var state errorState s := structPointer_StructPointerSlice(base, p.field) l := s.Len() for i := 0; i < l; i++ { b := s.Index(i) if structPointer_IsNil(b) { return errRepeatedHasNil } o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) err := o.enc_struct(p.sprop, b) if err != nil && !state.shouldContinue(err, nil) { if err == ErrNil { return errRepeatedHasNil } return err } o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) } return state.err } func size_slice_struct_group(p *Properties, base structPointer) (n int) { s := structPointer_StructPointerSlice(base, p.field) l := s.Len() n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) for i := 0; i < l; i++ { b := s.Index(i) if structPointer_IsNil(b) { return // return size up to this point } n += size_struct(p.sprop, b) } return } // Encode an extension map. func (o *Buffer) enc_map(p *Properties, base structPointer) error { exts := structPointer_ExtMap(base, p.field) if err := encodeExtensionsMap(*exts); err != nil { return err } return o.enc_map_body(*exts) } func (o *Buffer) enc_exts(p *Properties, base structPointer) error { exts := structPointer_Extensions(base, p.field) v, mu := exts.extensionsRead() if v == nil { return nil } mu.Lock() defer mu.Unlock() if err := encodeExtensionsMap(v); err != nil { return err } return o.enc_map_body(v) } func (o *Buffer) enc_map_body(v map[int32]Extension) error { // Fast-path for common cases: zero or one extensions. if len(v) <= 1 { for _, e := range v { o.buf = append(o.buf, e.enc...) } return nil } // Sort keys to provide a deterministic encoding. keys := make([]int, 0, len(v)) for k := range v { keys = append(keys, int(k)) } sort.Ints(keys) for _, k := range keys { o.buf = append(o.buf, v[int32(k)].enc...) } return nil } func size_map(p *Properties, base structPointer) int { v := structPointer_ExtMap(base, p.field) return extensionsMapSize(*v) } func size_exts(p *Properties, base structPointer) int { v := structPointer_Extensions(base, p.field) return extensionsSize(v) } // Encode a map field. func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { var state errorState // XXX: or do we need to plumb this through? /* A map defined as map<key_type, value_type> map_field = N; is encoded in the same way as message MapFieldEntry { key_type key = 1; value_type value = 2; } repeated MapFieldEntry map_field = N; */ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V if v.Len() == 0 { return nil } keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) enc := func() error { if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { return err } if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil { return err } return nil } // Don't sort map keys. It is not required by the spec, and C++ doesn't do it. for _, key := range v.MapKeys() { val := v.MapIndex(key) keycopy.Set(key) valcopy.Set(val) o.buf = append(o.buf, p.tagcode...) if err := o.enc_len_thing(enc, &state); err != nil { return err } } return nil } func size_new_map(p *Properties, base structPointer) int { v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) n := 0 for _, key := range v.MapKeys() { val := v.MapIndex(key) keycopy.Set(key) valcopy.Set(val) // Tag codes for key and val are the responsibility of the sub-sizer. keysize := p.mkeyprop.size(p.mkeyprop, keybase) valsize := p.mvalprop.size(p.mvalprop, valbase) entry := keysize + valsize // Add on tag code and length of map entry itself. n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry } return n } // mapEncodeScratch returns a new reflect.Value matching the map's value type, // and a structPointer suitable for passing to an encoder or sizer. func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { // Prepare addressable doubly-indirect placeholders for the key and value types. // This is needed because the element-type encoders expect **T, but the map iteration produces T. keycopy = reflect.New(mapType.Key()).Elem() // addressable K keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K keyptr.Set(keycopy.Addr()) // keybase = toStructPointer(keyptr.Addr()) // **K // Value types are more varied and require special handling. switch mapType.Elem().Kind() { case reflect.Slice: // []byte var dummy []byte valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte valbase = toStructPointer(valcopy.Addr()) case reflect.Ptr: // message; the generated field type is map[K]*Msg (so V is *Msg), // so we only need one level of indirection. valcopy = reflect.New(mapType.Elem()).Elem() // addressable V valbase = toStructPointer(valcopy.Addr()) default: // everything else valcopy = reflect.New(mapType.Elem()).Elem() // addressable V valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V valptr.Set(valcopy.Addr()) // valbase = toStructPointer(valptr.Addr()) // **V } return } // Encode a struct. func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { var state errorState // Encode fields in tag order so that decoders may use optimizations // that depend on the ordering. // https://developers.google.com/protocol-buffers/docs/encoding#order for _, i := range prop.order { p := prop.Prop[i] if p.enc != nil { err := p.enc(o, p, base) if err != nil { if err == ErrNil { if p.Required && state.err == nil { state.err = &RequiredNotSetError{p.Name} } } else if err == errRepeatedHasNil { // Give more context to nil values in repeated fields. return errors.New("repeated field " + p.OrigName + " has nil element") } else if !state.shouldContinue(err, p) { return err } } if len(o.buf) > maxMarshalSize { return ErrTooLarge } } } // Do oneof fields. if prop.oneofMarshaler != nil { m := structPointer_Interface(base, prop.stype).(Message) if err := prop.oneofMarshaler(m, o); err == ErrNil { return errOneofHasNil } else if err != nil { return err } } // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) if len(o.buf)+len(v) > maxMarshalSize { return ErrTooLarge } if len(v) > 0 { o.buf = append(o.buf, v...) } } return state.err } func size_struct(prop *StructProperties, base structPointer) (n int) { for _, i := range prop.order { p := prop.Prop[i] if p.size != nil { n += p.size(p, base) } } // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) n += len(v) } // Factor in any oneof fields. if prop.oneofSizer != nil { m := structPointer_Interface(base, prop.stype).(Message) n += prop.oneofSizer(m) } return } var zeroes [20]byte // longer than any conceivable sizeVarint // Encode a struct, preceded by its encoded length (as a varint). func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) } // Encode something, preceded by its encoded length (as a varint). func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { iLen := len(o.buf) o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length iMsg := len(o.buf) err := enc() if err != nil && !state.shouldContinue(err, nil) { return err } lMsg := len(o.buf) - iMsg lLen := sizeVarint(uint64(lMsg)) switch x := lLen - (iMsg - iLen); { case x > 0: // actual length is x bytes larger than the space we reserved // Move msg x bytes right. o.buf = append(o.buf, zeroes[:x]...) copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) case x < 0: // actual length is x bytes smaller than the space we reserved // Move msg x bytes left. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) o.buf = o.buf[:len(o.buf)+x] // x is negative } // Encode the length in the reserved space. o.buf = o.buf[:iLen] o.EncodeVarint(uint64(lMsg)) o.buf = o.buf[:len(o.buf)+lMsg] return state.err } // errorState maintains the first error that occurs and updates that error // with additional context. type errorState struct { err error } // shouldContinue reports whether encoding should continue upon encountering the // given error. If the error is RequiredNotSetError, shouldContinue returns true // and, if this is the first appearance of that error, remembers it for future // reporting. // // If prop is not nil, it may update any error with additional context about the // field with the error. func (s *errorState) shouldContinue(err error, prop *Properties) bool { // Ignore unset required fields. reqNotSet, ok := err.(*RequiredNotSetError) if !ok { return false } if s.err == nil { if prop != nil { err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} } s.err = err } return true } ������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/decode_test.go���������������������������������0000644�0610621�0607500�00000016516�13172163407�026361� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // +build go1.7 package proto_test import ( "fmt" "testing" "github.com/golang/protobuf/proto" tpb "github.com/golang/protobuf/proto/proto3_proto" ) var ( bytesBlackhole []byte msgBlackhole = new(tpb.Message) ) // BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and // 2 bytes long). func BenchmarkVarint32ArraySmall(b *testing.B) { for i := uint(1); i <= 10; i++ { dist := genInt32Dist([7]int{0, 3, 1}, 1<<i) raw, err := proto.Marshal(&tpb.Message{ ShortKey: dist, }) if err != nil { b.Error("wrong encode", err) } b.Run(fmt.Sprintf("Len%v", len(dist)), func(b *testing.B) { scratchBuf := proto.NewBuffer(nil) b.ResetTimer() for k := 0; k < b.N; k++ { scratchBuf.SetBuf(raw) msgBlackhole.Reset() if err := scratchBuf.Unmarshal(msgBlackhole); err != nil { b.Error("wrong decode", err) } } }) } } // BenchmarkVarint32ArrayLarge shows the performance on an array of large int32 fields (3 and // 4 bytes long, with a small number of 1, 2, 5 and 10 byte long versions). func BenchmarkVarint32ArrayLarge(b *testing.B) { for i := uint(1); i <= 10; i++ { dist := genInt32Dist([7]int{0, 1, 2, 4, 8, 1, 1}, 1<<i) raw, err := proto.Marshal(&tpb.Message{ ShortKey: dist, }) if err != nil { b.Error("wrong encode", err) } b.Run(fmt.Sprintf("Len%v", len(dist)), func(b *testing.B) { scratchBuf := proto.NewBuffer(nil) b.ResetTimer() for k := 0; k < b.N; k++ { scratchBuf.SetBuf(raw) msgBlackhole.Reset() if err := scratchBuf.Unmarshal(msgBlackhole); err != nil { b.Error("wrong decode", err) } } }) } } // BenchmarkVarint64ArraySmall shows the performance on an array of small int64 fields (1 and // 2 bytes long). func BenchmarkVarint64ArraySmall(b *testing.B) { for i := uint(1); i <= 10; i++ { dist := genUint64Dist([11]int{0, 3, 1}, 1<<i) raw, err := proto.Marshal(&tpb.Message{ Key: dist, }) if err != nil { b.Error("wrong encode", err) } b.Run(fmt.Sprintf("Len%v", len(dist)), func(b *testing.B) { scratchBuf := proto.NewBuffer(nil) b.ResetTimer() for k := 0; k < b.N; k++ { scratchBuf.SetBuf(raw) msgBlackhole.Reset() if err := scratchBuf.Unmarshal(msgBlackhole); err != nil { b.Error("wrong decode", err) } } }) } } // BenchmarkVarint64ArrayLarge shows the performance on an array of large int64 fields (6, 7, // and 8 bytes long with a small number of the other sizes). func BenchmarkVarint64ArrayLarge(b *testing.B) { for i := uint(1); i <= 10; i++ { dist := genUint64Dist([11]int{0, 1, 1, 2, 4, 8, 16, 32, 16, 1, 1}, 1<<i) raw, err := proto.Marshal(&tpb.Message{ Key: dist, }) if err != nil { b.Error("wrong encode", err) } b.Run(fmt.Sprintf("Len%v", len(dist)), func(b *testing.B) { scratchBuf := proto.NewBuffer(nil) b.ResetTimer() for k := 0; k < b.N; k++ { scratchBuf.SetBuf(raw) msgBlackhole.Reset() if err := scratchBuf.Unmarshal(msgBlackhole); err != nil { b.Error("wrong decode", err) } } }) } } // BenchmarkVarint64ArrayMixed shows the performance of lots of small messages, each // containing a small number of large (3, 4, and 5 byte) repeated int64s. func BenchmarkVarint64ArrayMixed(b *testing.B) { for i := uint(1); i <= 1<<5; i <<= 1 { dist := genUint64Dist([11]int{0, 0, 0, 4, 6, 4, 0, 0, 0, 0, 0}, int(i)) // number of sub fields for k := uint(1); k <= 1<<10; k <<= 2 { msg := &tpb.Message{} for m := uint(0); m < k; m++ { msg.Children = append(msg.Children, &tpb.Message{ Key: dist, }) } raw, err := proto.Marshal(msg) if err != nil { b.Error("wrong encode", err) } b.Run(fmt.Sprintf("Fields%vLen%v", k, i), func(b *testing.B) { scratchBuf := proto.NewBuffer(nil) b.ResetTimer() for k := 0; k < b.N; k++ { scratchBuf.SetBuf(raw) msgBlackhole.Reset() if err := scratchBuf.Unmarshal(msgBlackhole); err != nil { b.Error("wrong decode", err) } } }) } } } // genInt32Dist generates a slice of ints that will match the size distribution of dist. // A size of 6 corresponds to a max length varint32, which is 10 bytes. The distribution // is 1-indexed. (i.e. the value at index 1 is how many 1 byte ints to create). func genInt32Dist(dist [7]int, count int) (dest []int32) { for i := 0; i < count; i++ { for k := 0; k < len(dist); k++ { var num int32 switch k { case 1: num = 1<<7 - 1 case 2: num = 1<<14 - 1 case 3: num = 1<<21 - 1 case 4: num = 1<<28 - 1 case 5: num = 1<<29 - 1 case 6: num = -1 } for m := 0; m < dist[k]; m++ { dest = append(dest, num) } } } return } // genUint64Dist generates a slice of ints that will match the size distribution of dist. // The distribution is 1-indexed. (i.e. the value at index 1 is how many 1 byte ints to create). func genUint64Dist(dist [11]int, count int) (dest []uint64) { for i := 0; i < count; i++ { for k := 0; k < len(dist); k++ { var num uint64 switch k { case 1: num = 1<<7 - 1 case 2: num = 1<<14 - 1 case 3: num = 1<<21 - 1 case 4: num = 1<<28 - 1 case 5: num = 1<<35 - 1 case 6: num = 1<<42 - 1 case 7: num = 1<<49 - 1 case 8: num = 1<<56 - 1 case 9: num = 1<<63 - 1 case 10: num = 1<<64 - 1 } for m := 0; m < dist[k]; m++ { dest = append(dest, num) } } } return } // BenchmarkDecodeEmpty measures the overhead of doing the minimal possible decode. func BenchmarkDecodeEmpty(b *testing.B) { raw, err := proto.Marshal(&tpb.Message{}) if err != nil { b.Error("wrong encode", err) } b.ResetTimer() for i := 0; i < b.N; i++ { if err := proto.Unmarshal(raw, msgBlackhole); err != nil { b.Error("wrong decode", err) } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/decode.go��������������������������������������0000644�0610621�0607500�00000057553�13172163407�025330� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto /* * Routines for decoding protocol buffer data to construct in-memory representations. */ import ( "errors" "fmt" "io" "os" "reflect" ) // errOverflow is returned when an integer is too large to be represented. var errOverflow = errors.New("proto: integer overflow") // ErrInternalBadWireType is returned by generated code when an incorrect // wire type is encountered. It does not get returned to user code. var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") // The fundamental decoders that interpret bytes on the wire. // Those that take integer types all return uint64 and are // therefore of type valueDecoder. // DecodeVarint reads a varint-encoded integer from the slice. // It returns the integer and the number of bytes consumed, or // zero if there is not enough. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func DecodeVarint(buf []byte) (x uint64, n int) { for shift := uint(0); shift < 64; shift += 7 { if n >= len(buf) { return 0, 0 } b := uint64(buf[n]) n++ x |= (b & 0x7F) << shift if (b & 0x80) == 0 { return x, n } } // The number is too large to represent in a 64-bit value. return 0, 0 } func (p *Buffer) decodeVarintSlow() (x uint64, err error) { i := p.index l := len(p.buf) for shift := uint(0); shift < 64; shift += 7 { if i >= l { err = io.ErrUnexpectedEOF return } b := p.buf[i] i++ x |= (uint64(b) & 0x7F) << shift if b < 0x80 { p.index = i return } } // The number is too large to represent in a 64-bit value. err = errOverflow return } // DecodeVarint reads a varint-encoded integer from the Buffer. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func (p *Buffer) DecodeVarint() (x uint64, err error) { i := p.index buf := p.buf if i >= len(buf) { return 0, io.ErrUnexpectedEOF } else if buf[i] < 0x80 { p.index++ return uint64(buf[i]), nil } else if len(buf)-i < 10 { return p.decodeVarintSlow() } var b uint64 // we already checked the first byte x = uint64(buf[i]) - 0x80 i++ b = uint64(buf[i]) i++ x += b << 7 if b&0x80 == 0 { goto done } x -= 0x80 << 7 b = uint64(buf[i]) i++ x += b << 14 if b&0x80 == 0 { goto done } x -= 0x80 << 14 b = uint64(buf[i]) i++ x += b << 21 if b&0x80 == 0 { goto done } x -= 0x80 << 21 b = uint64(buf[i]) i++ x += b << 28 if b&0x80 == 0 { goto done } x -= 0x80 << 28 b = uint64(buf[i]) i++ x += b << 35 if b&0x80 == 0 { goto done } x -= 0x80 << 35 b = uint64(buf[i]) i++ x += b << 42 if b&0x80 == 0 { goto done } x -= 0x80 << 42 b = uint64(buf[i]) i++ x += b << 49 if b&0x80 == 0 { goto done } x -= 0x80 << 49 b = uint64(buf[i]) i++ x += b << 56 if b&0x80 == 0 { goto done } x -= 0x80 << 56 b = uint64(buf[i]) i++ x += b << 63 if b&0x80 == 0 { goto done } // x -= 0x80 << 63 // Always zero. return 0, errOverflow done: p.index = i return x, nil } // DecodeFixed64 reads a 64-bit integer from the Buffer. // This is the format for the // fixed64, sfixed64, and double protocol buffer types. func (p *Buffer) DecodeFixed64() (x uint64, err error) { // x, err already 0 i := p.index + 8 if i < 0 || i > len(p.buf) { err = io.ErrUnexpectedEOF return } p.index = i x = uint64(p.buf[i-8]) x |= uint64(p.buf[i-7]) << 8 x |= uint64(p.buf[i-6]) << 16 x |= uint64(p.buf[i-5]) << 24 x |= uint64(p.buf[i-4]) << 32 x |= uint64(p.buf[i-3]) << 40 x |= uint64(p.buf[i-2]) << 48 x |= uint64(p.buf[i-1]) << 56 return } // DecodeFixed32 reads a 32-bit integer from the Buffer. // This is the format for the // fixed32, sfixed32, and float protocol buffer types. func (p *Buffer) DecodeFixed32() (x uint64, err error) { // x, err already 0 i := p.index + 4 if i < 0 || i > len(p.buf) { err = io.ErrUnexpectedEOF return } p.index = i x = uint64(p.buf[i-4]) x |= uint64(p.buf[i-3]) << 8 x |= uint64(p.buf[i-2]) << 16 x |= uint64(p.buf[i-1]) << 24 return } // DecodeZigzag64 reads a zigzag-encoded 64-bit integer // from the Buffer. // This is the format used for the sint64 protocol buffer type. func (p *Buffer) DecodeZigzag64() (x uint64, err error) { x, err = p.DecodeVarint() if err != nil { return } x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) return } // DecodeZigzag32 reads a zigzag-encoded 32-bit integer // from the Buffer. // This is the format used for the sint32 protocol buffer type. func (p *Buffer) DecodeZigzag32() (x uint64, err error) { x, err = p.DecodeVarint() if err != nil { return } x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) return } // These are not ValueDecoders: they produce an array of bytes or a string. // bytes, embedded messages // DecodeRawBytes reads a count-delimited byte buffer from the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { n, err := p.DecodeVarint() if err != nil { return nil, err } nb := int(n) if nb < 0 { return nil, fmt.Errorf("proto: bad byte length %d", nb) } end := p.index + nb if end < p.index || end > len(p.buf) { return nil, io.ErrUnexpectedEOF } if !alloc { // todo: check if can get more uses of alloc=false buf = p.buf[p.index:end] p.index += nb return } buf = make([]byte, nb) copy(buf, p.buf[p.index:]) p.index += nb return } // DecodeStringBytes reads an encoded string from the Buffer. // This is the format used for the proto2 string type. func (p *Buffer) DecodeStringBytes() (s string, err error) { buf, err := p.DecodeRawBytes(false) if err != nil { return } return string(buf), nil } // Skip the next item in the buffer. Its wire type is decoded and presented as an argument. // If the protocol buffer has extensions, and the field matches, add it as an extension. // Otherwise, if the XXX_unrecognized field exists, append the skipped data there. func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { oi := o.index err := o.skip(t, tag, wire) if err != nil { return err } if !unrecField.IsValid() { return nil } ptr := structPointer_Bytes(base, unrecField) // Add the skipped field to struct field obuf := o.buf o.buf = *ptr o.EncodeVarint(uint64(tag<<3 | wire)) *ptr = append(o.buf, obuf[oi:o.index]...) o.buf = obuf return nil } // Skip the next item in the buffer. Its wire type is decoded and presented as an argument. func (o *Buffer) skip(t reflect.Type, tag, wire int) error { var u uint64 var err error switch wire { case WireVarint: _, err = o.DecodeVarint() case WireFixed64: _, err = o.DecodeFixed64() case WireBytes: _, err = o.DecodeRawBytes(false) case WireFixed32: _, err = o.DecodeFixed32() case WireStartGroup: for { u, err = o.DecodeVarint() if err != nil { break } fwire := int(u & 0x7) if fwire == WireEndGroup { break } ftag := int(u >> 3) err = o.skip(t, ftag, fwire) if err != nil { break } } default: err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) } return err } // Unmarshaler is the interface representing objects that can // unmarshal themselves. The method should reset the receiver before // decoding starts. The argument points to data that may be // overwritten, so implementations should not keep references to the // buffer. type Unmarshaler interface { Unmarshal([]byte) error } // Unmarshal parses the protocol buffer representation in buf and places the // decoded result in pb. If the struct underlying pb does not match // the data in buf, the results can be unpredictable. // // Unmarshal resets pb before starting to unmarshal, so any // existing data in pb is always removed. Use UnmarshalMerge // to preserve and append to existing data. func Unmarshal(buf []byte, pb Message) error { pb.Reset() return UnmarshalMerge(buf, pb) } // UnmarshalMerge parses the protocol buffer representation in buf and // writes the decoded result to pb. If the struct underlying pb does not match // the data in buf, the results can be unpredictable. // // UnmarshalMerge merges into existing data in pb. // Most code should use Unmarshal instead. func UnmarshalMerge(buf []byte, pb Message) error { // If the object can unmarshal itself, let it. if u, ok := pb.(Unmarshaler); ok { return u.Unmarshal(buf) } return NewBuffer(buf).Unmarshal(pb) } // DecodeMessage reads a count-delimited message from the Buffer. func (p *Buffer) DecodeMessage(pb Message) error { enc, err := p.DecodeRawBytes(false) if err != nil { return err } return NewBuffer(enc).Unmarshal(pb) } // DecodeGroup reads a tag-delimited group from the Buffer. func (p *Buffer) DecodeGroup(pb Message) error { typ, base, err := getbase(pb) if err != nil { return err } return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base) } // Unmarshal parses the protocol buffer representation in the // Buffer and places the decoded result in pb. If the struct // underlying pb does not match the data in the buffer, the results can be // unpredictable. // // Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. func (p *Buffer) Unmarshal(pb Message) error { // If the object can unmarshal itself, let it. if u, ok := pb.(Unmarshaler); ok { err := u.Unmarshal(p.buf[p.index:]) p.index = len(p.buf) return err } typ, base, err := getbase(pb) if err != nil { return err } err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) if collectStats { stats.Decode++ } return err } // unmarshalType does the work of unmarshaling a structure. func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { var state errorState required, reqFields := prop.reqCount, uint64(0) var err error for err == nil && o.index < len(o.buf) { oi := o.index var u uint64 u, err = o.DecodeVarint() if err != nil { break } wire := int(u & 0x7) if wire == WireEndGroup { if is_group { if required > 0 { // Not enough information to determine the exact field. // (See below.) return &RequiredNotSetError{"{Unknown}"} } return nil // input is satisfied } return fmt.Errorf("proto: %s: wiretype end group for non-group", st) } tag := int(u >> 3) if tag <= 0 { return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) } fieldnum, ok := prop.decoderTags.get(tag) if !ok { // Maybe it's an extension? if prop.extendable { if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) { if err = o.skip(st, tag, wire); err == nil { extmap := e.extensionsWrite() ext := extmap[int32(tag)] // may be missing ext.enc = append(ext.enc, o.buf[oi:o.index]...) extmap[int32(tag)] = ext } continue } } // Maybe it's a oneof? if prop.oneofUnmarshaler != nil { m := structPointer_Interface(base, st).(Message) // First return value indicates whether tag is a oneof field. ok, err = prop.oneofUnmarshaler(m, tag, wire, o) if err == ErrInternalBadWireType { // Map the error to something more descriptive. // Do the formatting here to save generated code space. err = fmt.Errorf("bad wiretype for oneof field in %T", m) } if ok { continue } } err = o.skipAndSave(st, tag, wire, base, prop.unrecField) continue } p := prop.Prop[fieldnum] if p.dec == nil { fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) continue } dec := p.dec if wire != WireStartGroup && wire != p.WireType { if wire == WireBytes && p.packedDec != nil { // a packable field dec = p.packedDec } else { err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) continue } } decErr := dec(o, p, base) if decErr != nil && !state.shouldContinue(decErr, p) { err = decErr } if err == nil && p.Required { // Successfully decoded a required field. if tag <= 64 { // use bitmap for fields 1-64 to catch field reuse. var mask uint64 = 1 << uint64(tag-1) if reqFields&mask == 0 { // new required field reqFields |= mask required-- } } else { // This is imprecise. It can be fooled by a required field // with a tag > 64 that is encoded twice; that's very rare. // A fully correct implementation would require allocating // a data structure, which we would like to avoid. required-- } } } if err == nil { if is_group { return io.ErrUnexpectedEOF } if state.err != nil { return state.err } if required > 0 { // Not enough information to determine the exact field. If we use extra // CPU, we could determine the field only if the missing required field // has a tag <= 64 and we check reqFields. return &RequiredNotSetError{"{Unknown}"} } } return err } // Individual type decoders // For each, // u is the decoded value, // v is a pointer to the field (pointer) in the struct // Sizes of the pools to allocate inside the Buffer. // The goal is modest amortization and allocation // on at least 16-byte boundaries. const ( boolPoolSize = 16 uint32PoolSize = 8 uint64PoolSize = 4 ) // Decode a bool. func (o *Buffer) dec_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } if len(o.bools) == 0 { o.bools = make([]bool, boolPoolSize) } o.bools[0] = u != 0 *structPointer_Bool(base, p.field) = &o.bools[0] o.bools = o.bools[1:] return nil } func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } *structPointer_BoolVal(base, p.field) = u != 0 return nil } // Decode an int32. func (o *Buffer) dec_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) return nil } func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) return nil } // Decode an int64. func (o *Buffer) dec_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word64_Set(structPointer_Word64(base, p.field), o, u) return nil } func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word64Val_Set(structPointer_Word64Val(base, p.field), o, u) return nil } // Decode a string. func (o *Buffer) dec_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } *structPointer_String(base, p.field) = &s return nil } func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } *structPointer_StringVal(base, p.field) = s return nil } // Decode a slice of bytes ([]byte). func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { b, err := o.DecodeRawBytes(true) if err != nil { return err } *structPointer_Bytes(base, p.field) = b return nil } // Decode a slice of bools ([]bool). func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } v := structPointer_BoolSlice(base, p.field) *v = append(*v, u != 0) return nil } // Decode a slice of bools ([]bool) in packed format. func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { v := structPointer_BoolSlice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded bools fin := o.index + nb if fin < o.index { return errOverflow } y := *v for o.index < fin { u, err := p.valDec(o) if err != nil { return err } y = append(y, u != 0) } *v = y return nil } // Decode a slice of int32s ([]int32). func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } structPointer_Word32Slice(base, p.field).Append(uint32(u)) return nil } // Decode a slice of int32s ([]int32) in packed format. func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { v := structPointer_Word32Slice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded int32s fin := o.index + nb if fin < o.index { return errOverflow } for o.index < fin { u, err := p.valDec(o) if err != nil { return err } v.Append(uint32(u)) } return nil } // Decode a slice of int64s ([]int64). func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } structPointer_Word64Slice(base, p.field).Append(u) return nil } // Decode a slice of int64s ([]int64) in packed format. func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { v := structPointer_Word64Slice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded int64s fin := o.index + nb if fin < o.index { return errOverflow } for o.index < fin { u, err := p.valDec(o) if err != nil { return err } v.Append(u) } return nil } // Decode a slice of strings ([]string). func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } v := structPointer_StringSlice(base, p.field) *v = append(*v, s) return nil } // Decode a slice of slice of bytes ([][]byte). func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { b, err := o.DecodeRawBytes(true) if err != nil { return err } v := structPointer_BytesSlice(base, p.field) *v = append(*v, b) return nil } // Decode a map field. func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { raw, err := o.DecodeRawBytes(false) if err != nil { return err } oi := o.index // index at the end of this map entry o.index -= len(raw) // move buffer back to start of map entry mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V if mptr.Elem().IsNil() { mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) } v := mptr.Elem() // map[K]V // Prepare addressable doubly-indirect placeholders for the key and value types. // See enc_new_map for why. keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K keybase := toStructPointer(keyptr.Addr()) // **K var valbase structPointer var valptr reflect.Value switch p.mtype.Elem().Kind() { case reflect.Slice: // []byte var dummy []byte valptr = reflect.ValueOf(&dummy) // *[]byte valbase = toStructPointer(valptr) // *[]byte case reflect.Ptr: // message; valptr is **Msg; need to allocate the intermediate pointer valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V valptr.Set(reflect.New(valptr.Type().Elem())) valbase = toStructPointer(valptr) default: // everything else valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V valbase = toStructPointer(valptr.Addr()) // **V } // Decode. // This parses a restricted wire format, namely the encoding of a message // with two fields. See enc_new_map for the format. for o.index < oi { // tagcode for key and value properties are always a single byte // because they have tags 1 and 2. tagcode := o.buf[o.index] o.index++ switch tagcode { case p.mkeyprop.tagcode[0]: if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { return err } case p.mvalprop.tagcode[0]: if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { return err } default: // TODO: Should we silently skip this instead? return fmt.Errorf("proto: bad map data tag %d", raw[0]) } } keyelem, valelem := keyptr.Elem(), valptr.Elem() if !keyelem.IsValid() { keyelem = reflect.Zero(p.mtype.Key()) } if !valelem.IsValid() { valelem = reflect.Zero(p.mtype.Elem()) } v.SetMapIndex(keyelem, valelem) return nil } // Decode a group. func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { bas := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(bas) { // allocate new nested message bas = toStructPointer(reflect.New(p.stype)) structPointer_SetStructPointer(base, p.field, bas) } return o.unmarshalType(p.stype, p.sprop, true, bas) } // Decode an embedded message. func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { raw, e := o.DecodeRawBytes(false) if e != nil { return e } bas := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(bas) { // allocate new nested message bas = toStructPointer(reflect.New(p.stype)) structPointer_SetStructPointer(base, p.field, bas) } // If the object can unmarshal itself, let it. if p.isUnmarshaler { iv := structPointer_Interface(bas, p.stype) return iv.(Unmarshaler).Unmarshal(raw) } obuf := o.buf oi := o.index o.buf = raw o.index = 0 err = o.unmarshalType(p.stype, p.sprop, false, bas) o.buf = obuf o.index = oi return err } // Decode a slice of embedded messages. func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { return o.dec_slice_struct(p, false, base) } // Decode a slice of embedded groups. func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { return o.dec_slice_struct(p, true, base) } // Decode a slice of structs ([]*struct). func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { v := reflect.New(p.stype) bas := toStructPointer(v) structPointer_StructPointerSlice(base, p.field).Append(bas) if is_group { err := o.unmarshalType(p.stype, p.sprop, is_group, bas) return err } raw, err := o.DecodeRawBytes(false) if err != nil { return err } // If the object can unmarshal itself, let it. if p.isUnmarshaler { iv := v.Interface() return iv.(Unmarshaler).Unmarshal(raw) } obuf := o.buf oi := o.index o.buf = raw o.index = 0 err = o.unmarshalType(p.stype, p.sprop, is_group, bas) o.buf = obuf o.index = oi return err } �����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/clone_test.go����������������������������������0000644�0610621�0607500�00000017535�13172163407�026240� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "testing" "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) var cloneTestMessage = &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &pb.InnerMessage{ Host: proto.String("niles"), Port: proto.Int32(9099), Connected: proto.Bool(true), }, Others: []*pb.OtherMessage{ { Value: []byte("some bytes"), }, }, Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, } func init() { ext := &pb.Ext{ Data: proto.String("extension"), } if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { panic("SetExtension: " + err.Error()) } } func TestClone(t *testing.T) { m := proto.Clone(cloneTestMessage).(*pb.MyMessage) if !proto.Equal(m, cloneTestMessage) { t.Errorf("Clone(%v) = %v", cloneTestMessage, m) } // Verify it was a deep copy. *m.Inner.Port++ if proto.Equal(m, cloneTestMessage) { t.Error("Mutating clone changed the original") } // Byte fields and repeated fields should be copied. if &m.Pet[0] == &cloneTestMessage.Pet[0] { t.Error("Pet: repeated field not copied") } if &m.Others[0] == &cloneTestMessage.Others[0] { t.Error("Others: repeated field not copied") } if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { t.Error("Others[0].Value: bytes field not copied") } if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { t.Error("RepBytes: repeated field not copied") } if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { t.Error("RepBytes[0]: bytes field not copied") } } func TestCloneNil(t *testing.T) { var m *pb.MyMessage if c := proto.Clone(m); !proto.Equal(m, c) { t.Errorf("Clone(%v) = %v", m, c) } } var mergeTests = []struct { src, dst, want proto.Message }{ { src: &pb.MyMessage{ Count: proto.Int32(42), }, dst: &pb.MyMessage{ Name: proto.String("Dave"), }, want: &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), }, }, { src: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("hey"), Connected: proto.Bool(true), }, Pet: []string{"horsey"}, Others: []*pb.OtherMessage{ { Value: []byte("some bytes"), }, }, }, dst: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("niles"), Port: proto.Int32(9099), }, Pet: []string{"bunny", "kitty"}, Others: []*pb.OtherMessage{ { Key: proto.Int64(31415926535), }, { // Explicitly test a src=nil field Inner: nil, }, }, }, want: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("hey"), Connected: proto.Bool(true), Port: proto.Int32(9099), }, Pet: []string{"bunny", "kitty", "horsey"}, Others: []*pb.OtherMessage{ { Key: proto.Int64(31415926535), }, {}, { Value: []byte("some bytes"), }, }, }, }, { src: &pb.MyMessage{ RepBytes: [][]byte{[]byte("wow")}, }, dst: &pb.MyMessage{ Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham")}, }, want: &pb.MyMessage{ Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, }, }, // Check that a scalar bytes field replaces rather than appends. { src: &pb.OtherMessage{Value: []byte("foo")}, dst: &pb.OtherMessage{Value: []byte("bar")}, want: &pb.OtherMessage{Value: []byte("foo")}, }, { src: &pb.MessageWithMap{ NameMapping: map[int32]string{6: "Nigel"}, MsgMapping: map[int64]*pb.FloatingPoint{ 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, 0x4002: &pb.FloatingPoint{ F: proto.Float64(2.0), }, }, ByteMapping: map[bool][]byte{true: []byte("wowsa")}, }, dst: &pb.MessageWithMap{ NameMapping: map[int32]string{ 6: "Bruce", // should be overwritten 7: "Andrew", }, MsgMapping: map[int64]*pb.FloatingPoint{ 0x4002: &pb.FloatingPoint{ F: proto.Float64(3.0), Exact: proto.Bool(true), }, // the entire message should be overwritten }, }, want: &pb.MessageWithMap{ NameMapping: map[int32]string{ 6: "Nigel", 7: "Andrew", }, MsgMapping: map[int64]*pb.FloatingPoint{ 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, 0x4002: &pb.FloatingPoint{ F: proto.Float64(2.0), }, }, ByteMapping: map[bool][]byte{true: []byte("wowsa")}, }, }, // proto3 shouldn't merge zero values, // in the same way that proto2 shouldn't merge nils. { src: &proto3pb.Message{ Name: "Aaron", Data: []byte(""), // zero value, but not nil }, dst: &proto3pb.Message{ HeightInCm: 176, Data: []byte("texas!"), }, want: &proto3pb.Message{ Name: "Aaron", HeightInCm: 176, Data: []byte("texas!"), }, }, // Oneof fields should merge by assignment. { src: &pb.Communique{ Union: &pb.Communique_Number{41}, }, dst: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, want: &pb.Communique{ Union: &pb.Communique_Number{41}, }, }, // Oneof nil is the same as not set. { src: &pb.Communique{}, dst: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, want: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, }, { src: &proto3pb.Message{ Terrain: map[string]*proto3pb.Nested{ "kay_a": &proto3pb.Nested{Cute: true}, // replace "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert }, }, dst: &proto3pb.Message{ Terrain: map[string]*proto3pb.Nested{ "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep }, }, want: &proto3pb.Message{ Terrain: map[string]*proto3pb.Nested{ "kay_a": &proto3pb.Nested{Cute: true}, "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, "kay_c": &proto3pb.Nested{Bunny: "bunny"}, }, }, }, } func TestMerge(t *testing.T) { for _, m := range mergeTests { got := proto.Clone(m.dst) proto.Merge(got, m.src) if !proto.Equal(got, m.want) { t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/clone.go���������������������������������������0000644�0610621�0607500�00000015471�13172163407�025176� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Protocol buffer deep copy and merge. // TODO: RawMessage. package proto import ( "log" "reflect" "strings" ) // Clone returns a deep copy of a protocol buffer. func Clone(pb Message) Message { in := reflect.ValueOf(pb) if in.IsNil() { return pb } out := reflect.New(in.Type().Elem()) // out is empty so a merge is a deep copy. mergeStruct(out.Elem(), in.Elem()) return out.Interface().(Message) } // Merge merges src into dst. // Required and optional fields that are set in src will be set to that value in dst. // Elements of repeated fields will be appended. // Merge panics if src and dst are not the same type, or if dst is nil. func Merge(dst, src Message) { in := reflect.ValueOf(src) out := reflect.ValueOf(dst) if out.IsNil() { panic("proto: nil destination") } if in.Type() != out.Type() { // Explicit test prior to mergeStruct so that mistyped nils will fail panic("proto: type mismatch") } if in.IsNil() { // Merging nil into non-nil is a quiet no-op return } mergeStruct(out.Elem(), in.Elem()) } func mergeStruct(out, in reflect.Value) { sprop := GetProperties(in.Type()) for i := 0; i < in.NumField(); i++ { f := in.Type().Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) } if emIn, ok := extendable(in.Addr().Interface()); ok { emOut, _ := extendable(out.Addr().Interface()) mIn, muIn := emIn.extensionsRead() if mIn != nil { mOut := emOut.extensionsWrite() muIn.Lock() mergeExtension(mOut, mIn) muIn.Unlock() } } uf := in.FieldByName("XXX_unrecognized") if !uf.IsValid() { return } uin := uf.Bytes() if len(uin) > 0 { out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) } } // mergeAny performs a merge between two values of the same type. // viaPtr indicates whether the values were indirected through a pointer (implying proto2). // prop is set if this is a struct field (it may be nil). func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { if in.Type() == protoMessageType { if !in.IsNil() { if out.IsNil() { out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) } else { Merge(out.Interface().(Message), in.Interface().(Message)) } } return } switch in.Kind() { case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: if !viaPtr && isProto3Zero(in) { return } out.Set(in) case reflect.Interface: // Probably a oneof field; copy non-nil values. if in.IsNil() { return } // Allocate destination if it is not set, or set to a different type. // Otherwise we will merge as normal. if out.IsNil() || out.Elem().Type() != in.Elem().Type() { out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) } mergeAny(out.Elem(), in.Elem(), false, nil) case reflect.Map: if in.Len() == 0 { return } if out.IsNil() { out.Set(reflect.MakeMap(in.Type())) } // For maps with value types of *T or []byte we need to deep copy each value. elemKind := in.Type().Elem().Kind() for _, key := range in.MapKeys() { var val reflect.Value switch elemKind { case reflect.Ptr: val = reflect.New(in.Type().Elem().Elem()) mergeAny(val, in.MapIndex(key), false, nil) case reflect.Slice: val = in.MapIndex(key) val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) default: val = in.MapIndex(key) } out.SetMapIndex(key, val) } case reflect.Ptr: if in.IsNil() { return } if out.IsNil() { out.Set(reflect.New(in.Elem().Type())) } mergeAny(out.Elem(), in.Elem(), true, nil) case reflect.Slice: if in.IsNil() { return } if in.Type().Elem().Kind() == reflect.Uint8 { // []byte is a scalar bytes field, not a repeated field. // Edge case: if this is in a proto3 message, a zero length // bytes field is considered the zero value, and should not // be merged. if prop != nil && prop.proto3 && in.Len() == 0 { return } // Make a deep copy. // Append to []byte{} instead of []byte(nil) so that we never end up // with a nil result. out.SetBytes(append([]byte{}, in.Bytes()...)) return } n := in.Len() if out.IsNil() { out.Set(reflect.MakeSlice(in.Type(), 0, n)) } switch in.Type().Elem().Kind() { case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: out.Set(reflect.AppendSlice(out, in)) default: for i := 0; i < n; i++ { x := reflect.Indirect(reflect.New(in.Type().Elem())) mergeAny(x, in.Index(i), false, nil) out.Set(reflect.Append(out, x)) } } case reflect.Struct: mergeStruct(out, in) default: // unknown type, so not a protocol buffer log.Printf("proto: don't know how to copy %v", in) } } func mergeExtension(out, in map[int32]Extension) { for extNum, eIn := range in { eOut := Extension{desc: eIn.desc} if eIn.value != nil { v := reflect.New(reflect.TypeOf(eIn.value)).Elem() mergeAny(v, reflect.ValueOf(eIn.value), false, nil) eOut.value = v.Interface() } if eIn.enc != nil { eOut.enc = make([]byte, len(eIn.enc)) copy(eOut.enc, eIn.enc) } out[extNum] = eOut } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/any_test.go������������������������������������0000644�0610621�0607500�00000021211�13172163407�025711� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "strings" "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/proto/proto3_proto" testpb "github.com/golang/protobuf/proto/testdata" anypb "github.com/golang/protobuf/ptypes/any" ) var ( expandedMarshaler = proto.TextMarshaler{ExpandAny: true} expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} ) // anyEqual reports whether two messages which may be google.protobuf.Any or may // contain google.protobuf.Any fields are equal. We can't use proto.Equal for // comparison, because semantically equivalent messages may be marshaled to // binary in different tag order. Instead, trust that TextMarshaler with // ExpandAny option works and compare the text marshaling results. func anyEqual(got, want proto.Message) bool { // if messages are proto.Equal, no need to marshal. if proto.Equal(got, want) { return true } g := expandedMarshaler.Text(got) w := expandedMarshaler.Text(want) return g == w } type golden struct { m proto.Message t, c string } var goldenMessages = makeGolden() func makeGolden() []golden { nested := &pb.Nested{Bunny: "Monty"} nb, err := proto.Marshal(nested) if err != nil { panic(err) } m1 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, } m2 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, } m3 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, } m4 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, } m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) any1b, err := proto.Marshal(any1) if err != nil { panic(err) } any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) any2b, err := proto.Marshal(any2) if err != nil { panic(err) } m6 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, ManyThings: []*anypb.Any{ &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, }, } const ( m1Golden = ` name: "David" result_count: 47 anything: < [type.googleapis.com/proto3_proto.Nested]: < bunny: "Monty" > > ` m2Golden = ` name: "David" result_count: 47 anything: < ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < bunny: "Monty" > > ` m3Golden = ` name: "David" result_count: 47 anything: < ["type.googleapis.com/\"/proto3_proto.Nested"]: < bunny: "Monty" > > ` m4Golden = ` name: "David" result_count: 47 anything: < [type.googleapis.com/a/path/proto3_proto.Nested]: < bunny: "Monty" > > ` m5Golden = ` [type.googleapis.com/proto3_proto.Nested]: < bunny: "Monty" > ` m6Golden = ` name: "David" result_count: 47 anything: < [type.googleapis.com/testdata.MyMessage]: < count: 47 name: "David" [testdata.Ext.more]: < data: "foo" > [testdata.Ext.text]: "bar" > > many_things: < [type.googleapis.com/testdata.MyMessage]: < count: 42 bikeshed: GREEN rep_bytes: "roboto" [testdata.Ext.more]: < data: "baz" > > > many_things: < [type.googleapis.com/testdata.MyMessage]: < count: 47 name: "David" [testdata.Ext.more]: < data: "foo" > [testdata.Ext.text]: "bar" > > ` ) return []golden{ {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, } } func TestMarshalGolden(t *testing.T) { for _, tt := range goldenMessages { if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) } if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) } } } func TestUnmarshalGolden(t *testing.T) { for _, tt := range goldenMessages { want := tt.m got := proto.Clone(tt.m) got.Reset() if err := proto.UnmarshalText(tt.t, got); err != nil { t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) } if !anyEqual(got, want) { t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) } got.Reset() if err := proto.UnmarshalText(tt.c, got); err != nil { t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) } if !anyEqual(got, want) { t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) } } } func TestMarshalUnknownAny(t *testing.T) { m := &pb.Message{ Anything: &anypb.Any{ TypeUrl: "foo", Value: []byte("bar"), }, } want := `anything: < type_url: "foo" value: "bar" > ` got := expandedMarshaler.Text(m) if got != want { t.Errorf("got\n`%s`\nwant\n`%s`", got, want) } } func TestAmbiguousAny(t *testing.T) { pb := &anypb.Any{} err := proto.UnmarshalText(` type_url: "ttt/proto3_proto.Nested" value: "\n\x05Monty" `, pb) t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) if err != nil { t.Errorf("failed to parse ambiguous Any message: %v", err) } } func TestUnmarshalOverwriteAny(t *testing.T) { pb := &anypb.Any{} err := proto.UnmarshalText(` [type.googleapis.com/a/path/proto3_proto.Nested]: < bunny: "Monty" > [type.googleapis.com/a/path/proto3_proto.Nested]: < bunny: "Rabbit of Caerbannog" > `, pb) want := `line 7: Any message unpacked multiple times, or "type_url" already set` if err.Error() != want { t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) } } func TestUnmarshalAnyMixAndMatch(t *testing.T) { pb := &anypb.Any{} err := proto.UnmarshalText(` value: "\n\x05Monty" [type.googleapis.com/a/path/proto3_proto.Nested]: < bunny: "Rabbit of Caerbannog" > `, pb) want := `line 5: Any message unpacked multiple times, or "value" already set` if err.Error() != want { t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/all_test.go������������������������������������0000644�0610621�0607500�00000203500�13172163407�025675� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto_test import ( "bytes" "encoding/json" "errors" "fmt" "math" "math/rand" "reflect" "runtime/debug" "strings" "testing" "time" . "github.com/golang/protobuf/proto" . "github.com/golang/protobuf/proto/testdata" ) var globalO *Buffer func old() *Buffer { if globalO == nil { globalO = NewBuffer(nil) } globalO.Reset() return globalO } func equalbytes(b1, b2 []byte, t *testing.T) { if len(b1) != len(b2) { t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) return } for i := 0; i < len(b1); i++ { if b1[i] != b2[i] { t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) } } } func initGoTestField() *GoTestField { f := new(GoTestField) f.Label = String("label") f.Type = String("type") return f } // These are all structurally equivalent but the tag numbers differ. // (It's remarkable that required, optional, and repeated all have // 8 letters.) func initGoTest_RequiredGroup() *GoTest_RequiredGroup { return &GoTest_RequiredGroup{ RequiredField: String("required"), } } func initGoTest_OptionalGroup() *GoTest_OptionalGroup { return &GoTest_OptionalGroup{ RequiredField: String("optional"), } } func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { return &GoTest_RepeatedGroup{ RequiredField: String("repeated"), } } func initGoTest(setdefaults bool) *GoTest { pb := new(GoTest) if setdefaults { pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) } pb.Kind = GoTest_TIME.Enum() pb.RequiredField = initGoTestField() pb.F_BoolRequired = Bool(true) pb.F_Int32Required = Int32(3) pb.F_Int64Required = Int64(6) pb.F_Fixed32Required = Uint32(32) pb.F_Fixed64Required = Uint64(64) pb.F_Uint32Required = Uint32(3232) pb.F_Uint64Required = Uint64(6464) pb.F_FloatRequired = Float32(3232) pb.F_DoubleRequired = Float64(6464) pb.F_StringRequired = String("string") pb.F_BytesRequired = []byte("bytes") pb.F_Sint32Required = Int32(-32) pb.F_Sint64Required = Int64(-64) pb.Requiredgroup = initGoTest_RequiredGroup() return pb } func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { data := b.Bytes() ld := len(data) ls := len(s) / 2 fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) // find the interesting spot - n n := ls if ld < ls { n = ld } j := 0 for i := 0; i < n; i++ { bs := hex(s[j])*16 + hex(s[j+1]) j += 2 if data[i] == bs { continue } n = i break } l := n - 10 if l < 0 { l = 0 } h := n + 10 // find the interesting spot - n fmt.Printf("is[%d]:", l) for i := l; i < h; i++ { if i >= ld { fmt.Printf(" --") continue } fmt.Printf(" %.2x", data[i]) } fmt.Printf("\n") fmt.Printf("sb[%d]:", l) for i := l; i < h; i++ { if i >= ls { fmt.Printf(" --") continue } bs := hex(s[j])*16 + hex(s[j+1]) j += 2 fmt.Printf(" %.2x", bs) } fmt.Printf("\n") t.Fail() // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) // Print the output in a partially-decoded format; can // be helpful when updating the test. It produces the output // that is pasted, with minor edits, into the argument to verify(). // data := b.Bytes() // nesting := 0 // for b.Len() > 0 { // start := len(data) - b.Len() // var u uint64 // u, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on varint:", err) // return // } // wire := u & 0x7 // tag := u >> 3 // switch wire { // case WireVarint: // v, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on varint:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireFixed32: // v, err := DecodeFixed32(b) // if err != nil { // fmt.Printf("decode error on fixed32:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireFixed64: // v, err := DecodeFixed64(b) // if err != nil { // fmt.Printf("decode error on fixed64:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireBytes: // nb, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on bytes:", err) // return // } // after_tag := len(data) - b.Len() // str := make([]byte, nb) // _, err = b.Read(str) // if err != nil { // fmt.Printf("decode error on bytes:", err) // return // } // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", // data[start:after_tag], str, tag, wire) // case WireStartGroup: // nesting++ // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", // data[start:len(data)-b.Len()], tag, nesting) // case WireEndGroup: // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", // data[start:len(data)-b.Len()], tag, nesting) // nesting-- // default: // fmt.Printf("unrecognized wire type %d\n", wire) // return // } // } } func hex(c uint8) uint8 { if '0' <= c && c <= '9' { return c - '0' } if 'a' <= c && c <= 'f' { return 10 + c - 'a' } if 'A' <= c && c <= 'F' { return 10 + c - 'A' } return 0 } func equal(b []byte, s string, t *testing.T) bool { if 2*len(b) != len(s) { // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) return false } for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { x := hex(s[j])*16 + hex(s[j+1]) if b[i] != x { // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) return false } } return true } func overify(t *testing.T, pb *GoTest, expected string) { o := old() err := o.Marshal(pb) if err != nil { fmt.Printf("overify marshal-1 err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("expected = %s", expected) } if !equal(o.Bytes(), expected, t) { o.DebugPrint("overify neq 1", o.Bytes()) t.Fatalf("expected = %s", expected) } // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) err = o.Unmarshal(pbd) if err != nil { t.Fatalf("overify unmarshal err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("string = %s", expected) } o.Reset() err = o.Marshal(pbd) if err != nil { t.Errorf("overify marshal-2 err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("string = %s", expected) } if !equal(o.Bytes(), expected, t) { o.DebugPrint("overify neq 2", o.Bytes()) t.Fatalf("string = %s", expected) } } // Simple tests for numeric encode/decode primitives (varint, etc.) func TestNumericPrimitives(t *testing.T) { for i := uint64(0); i < 1e6; i += 111 { o := old() if o.EncodeVarint(i) != nil { t.Error("EncodeVarint") break } x, e := o.DecodeVarint() if e != nil { t.Fatal("DecodeVarint") } if x != i { t.Fatal("varint decode fail:", i, x) } o = old() if o.EncodeFixed32(i) != nil { t.Fatal("encFixed32") } x, e = o.DecodeFixed32() if e != nil { t.Fatal("decFixed32") } if x != i { t.Fatal("fixed32 decode fail:", i, x) } o = old() if o.EncodeFixed64(i*1234567) != nil { t.Error("encFixed64") break } x, e = o.DecodeFixed64() if e != nil { t.Error("decFixed64") break } if x != i*1234567 { t.Error("fixed64 decode fail:", i*1234567, x) break } o = old() i32 := int32(i - 12345) if o.EncodeZigzag32(uint64(i32)) != nil { t.Fatal("EncodeZigzag32") } x, e = o.DecodeZigzag32() if e != nil { t.Fatal("DecodeZigzag32") } if x != uint64(uint32(i32)) { t.Fatal("zigzag32 decode fail:", i32, x) } o = old() i64 := int64(i - 12345) if o.EncodeZigzag64(uint64(i64)) != nil { t.Fatal("EncodeZigzag64") } x, e = o.DecodeZigzag64() if e != nil { t.Fatal("DecodeZigzag64") } if x != uint64(i64) { t.Fatal("zigzag64 decode fail:", i64, x) } } } // fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. type fakeMarshaler struct { b []byte err error } func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } func (f *fakeMarshaler) ProtoMessage() {} func (f *fakeMarshaler) Reset() {} type msgWithFakeMarshaler struct { M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` } func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } func (m *msgWithFakeMarshaler) ProtoMessage() {} func (m *msgWithFakeMarshaler) Reset() {} // Simple tests for proto messages that implement the Marshaler interface. func TestMarshalerEncoding(t *testing.T) { tests := []struct { name string m Message want []byte errType reflect.Type }{ { name: "Marshaler that fails", m: &fakeMarshaler{ err: errors.New("some marshal err"), b: []byte{5, 6, 7}, }, // Since the Marshal method returned bytes, they should be written to the // buffer. (For efficiency, we assume that Marshal implementations are // always correct w.r.t. RequiredNotSetError and output.) want: []byte{5, 6, 7}, errType: reflect.TypeOf(errors.New("some marshal err")), }, { name: "Marshaler that fails with RequiredNotSetError", m: &msgWithFakeMarshaler{ M: &fakeMarshaler{ err: &RequiredNotSetError{}, b: []byte{5, 6, 7}, }, }, // Since there's an error that can be continued after, // the buffer should be written. want: []byte{ 10, 3, // for &msgWithFakeMarshaler 5, 6, 7, // for &fakeMarshaler }, errType: reflect.TypeOf(&RequiredNotSetError{}), }, { name: "Marshaler that succeeds", m: &fakeMarshaler{ b: []byte{0, 1, 2, 3, 4, 127, 255}, }, want: []byte{0, 1, 2, 3, 4, 127, 255}, }, } for _, test := range tests { b := NewBuffer(nil) err := b.Marshal(test.m) if reflect.TypeOf(err) != test.errType { t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) } if !reflect.DeepEqual(test.want, b.Bytes()) { t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) } if size := Size(test.m); size != len(b.Bytes()) { t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) } m, mErr := Marshal(test.m) if !bytes.Equal(b.Bytes(), m) { t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) } if !reflect.DeepEqual(err, mErr) { t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", test.name, fmt.Sprint(mErr), fmt.Sprint(err)) } } } // Simple tests for bytes func TestBytesPrimitives(t *testing.T) { o := old() bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} if o.EncodeRawBytes(bytes) != nil { t.Error("EncodeRawBytes") } decb, e := o.DecodeRawBytes(false) if e != nil { t.Error("DecodeRawBytes") } equalbytes(bytes, decb, t) } // Simple tests for strings func TestStringPrimitives(t *testing.T) { o := old() s := "now is the time" if o.EncodeStringBytes(s) != nil { t.Error("enc_string") } decs, e := o.DecodeStringBytes() if e != nil { t.Error("dec_string") } if s != decs { t.Error("string encode/decode fail:", s, decs) } } // Do we catch the "required bit not set" case? func TestRequiredBit(t *testing.T) { o := old() pb := new(GoTest) err := o.Marshal(pb) if err == nil { t.Error("did not catch missing required fields") } else if strings.Index(err.Error(), "Kind") < 0 { t.Error("wrong error type:", err) } } // Check that all fields are nil. // Clearly silly, and a residue from a more interesting test with an earlier, // different initialization property, but it once caught a compiler bug so // it lives. func checkInitialized(pb *GoTest, t *testing.T) { if pb.F_BoolDefaulted != nil { t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) } if pb.F_Int32Defaulted != nil { t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) } if pb.F_Int64Defaulted != nil { t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) } if pb.F_Fixed32Defaulted != nil { t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) } if pb.F_Fixed64Defaulted != nil { t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) } if pb.F_Uint32Defaulted != nil { t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) } if pb.F_Uint64Defaulted != nil { t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) } if pb.F_FloatDefaulted != nil { t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) } if pb.F_DoubleDefaulted != nil { t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) } if pb.F_StringDefaulted != nil { t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) } if pb.F_BytesDefaulted != nil { t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) } if pb.F_Sint32Defaulted != nil { t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) } if pb.F_Sint64Defaulted != nil { t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) } } // Does Reset() reset? func TestReset(t *testing.T) { pb := initGoTest(true) // muck with some values pb.F_BoolDefaulted = Bool(false) pb.F_Int32Defaulted = Int32(237) pb.F_Int64Defaulted = Int64(12346) pb.F_Fixed32Defaulted = Uint32(32000) pb.F_Fixed64Defaulted = Uint64(666) pb.F_Uint32Defaulted = Uint32(323232) pb.F_Uint64Defaulted = nil pb.F_FloatDefaulted = nil pb.F_DoubleDefaulted = Float64(0) pb.F_StringDefaulted = String("gotcha") pb.F_BytesDefaulted = []byte("asdfasdf") pb.F_Sint32Defaulted = Int32(123) pb.F_Sint64Defaulted = Int64(789) pb.Reset() checkInitialized(pb, t) } // All required fields set, no defaults provided. func TestEncodeDecode1(t *testing.T) { pb := initGoTest(false) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 0x20 "714000000000000000"+ // field 14, encoding 1, value 0x40 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" "b304"+ // field 70, encoding 3, start group "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // field 70, encoding 4, end group "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f") // field 103, encoding 0, 0x7f zigzag64 } // All required fields set, defaults provided. func TestEncodeDecode2(t *testing.T) { pb := initGoTest(true) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All default fields set to their default value by hand func TestEncodeDecode3(t *testing.T) { pb := initGoTest(false) pb.F_BoolDefaulted = Bool(true) pb.F_Int32Defaulted = Int32(32) pb.F_Int64Defaulted = Int64(64) pb.F_Fixed32Defaulted = Uint32(320) pb.F_Fixed64Defaulted = Uint64(640) pb.F_Uint32Defaulted = Uint32(3200) pb.F_Uint64Defaulted = Uint64(6400) pb.F_FloatDefaulted = Float32(314159) pb.F_DoubleDefaulted = Float64(271828) pb.F_StringDefaulted = String("hello, \"world!\"\n") pb.F_BytesDefaulted = []byte("Bignose") pb.F_Sint32Defaulted = Int32(-32) pb.F_Sint64Defaulted = Int64(-64) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, defaults provided, all non-defaulted optional fields have values. func TestEncodeDecode4(t *testing.T) { pb := initGoTest(true) pb.Table = String("hello") pb.Param = Int32(7) pb.OptionalField = initGoTestField() pb.F_BoolOptional = Bool(true) pb.F_Int32Optional = Int32(32) pb.F_Int64Optional = Int64(64) pb.F_Fixed32Optional = Uint32(3232) pb.F_Fixed64Optional = Uint64(6464) pb.F_Uint32Optional = Uint32(323232) pb.F_Uint64Optional = Uint64(646464) pb.F_FloatOptional = Float32(32.) pb.F_DoubleOptional = Float64(64.) pb.F_StringOptional = String("hello") pb.F_BytesOptional = []byte("Bignose") pb.F_Sint32Optional = Int32(-32) pb.F_Sint64Optional = Int64(-64) pb.Optionalgroup = initGoTest_OptionalGroup() overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" "1807"+ // field 3, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "f00101"+ // field 30, encoding 0, value 1 "f80120"+ // field 31, encoding 0, value 32 "800240"+ // field 32, encoding 0, value 64 "8d02a00c0000"+ // field 33, encoding 5, value 3232 "91024019000000000000"+ // field 34, encoding 1, value 6464 "9802a0dd13"+ // field 35, encoding 0, value 323232 "a002c0ba27"+ // field 36, encoding 0, value 646464 "ad0200000042"+ // field 37, encoding 5, value 32.0 "b1020000000000005040"+ // field 38, encoding 1, value 64.0 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "d305"+ // start group field 90 level 1 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" "d405"+ // end group field 90 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" "f0123f"+ // field 302, encoding 0, value 63 "f8127f"+ // field 303, encoding 0, value 127 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, defaults provided, all repeated fields given two values. func TestEncodeDecode5(t *testing.T) { pb := initGoTest(true) pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} pb.F_BoolRepeated = []bool{false, true} pb.F_Int32Repeated = []int32{32, 33} pb.F_Int64Repeated = []int64{64, 65} pb.F_Fixed32Repeated = []uint32{3232, 3333} pb.F_Fixed64Repeated = []uint64{6464, 6565} pb.F_Uint32Repeated = []uint32{323232, 333333} pb.F_Uint64Repeated = []uint64{646464, 656565} pb.F_FloatRepeated = []float32{32., 33.} pb.F_DoubleRepeated = []float64{64., 65.} pb.F_StringRepeated = []string{"hello", "sailor"} pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} pb.F_Sint32Repeated = []int32{32, -32} pb.F_Sint64Repeated = []int64{64, -64} pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "a00100"+ // field 20, encoding 0, value 0 "a00101"+ // field 20, encoding 0, value 1 "a80120"+ // field 21, encoding 0, value 32 "a80121"+ // field 21, encoding 0, value 33 "b00140"+ // field 22, encoding 0, value 64 "b00141"+ // field 22, encoding 0, value 65 "bd01a00c0000"+ // field 23, encoding 5, value 3232 "bd01050d0000"+ // field 23, encoding 5, value 3333 "c1014019000000000000"+ // field 24, encoding 1, value 6464 "c101a519000000000000"+ // field 24, encoding 1, value 6565 "c801a0dd13"+ // field 25, encoding 0, value 323232 "c80195ac14"+ // field 25, encoding 0, value 333333 "d001c0ba27"+ // field 26, encoding 0, value 646464 "d001b58928"+ // field 26, encoding 0, value 656565 "dd0100000042"+ // field 27, encoding 5, value 32.0 "dd0100000442"+ // field 27, encoding 5, value 33.0 "e1010000000000005040"+ // field 28, encoding 1, value 64.0 "e1010000000000405040"+ // field 28, encoding 1, value 65.0 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "8305"+ // start group field 80 level 1 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" "8405"+ // end group field 80 level 1 "8305"+ // start group field 80 level 1 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" "8405"+ // end group field 80 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "ca0c03"+"626967"+ // field 201, encoding 2, string "big" "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" "d00c40"+ // field 202, encoding 0, value 32 "d00c3f"+ // field 202, encoding 0, value -32 "d80c8001"+ // field 203, encoding 0, value 64 "d80c7f"+ // field 203, encoding 0, value -64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, all packed repeated fields given two values. func TestEncodeDecode6(t *testing.T) { pb := initGoTest(false) pb.F_BoolRepeatedPacked = []bool{false, true} pb.F_Int32RepeatedPacked = []int32{32, 33} pb.F_Int64RepeatedPacked = []int64{64, 65} pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} pb.F_FloatRepeatedPacked = []float32{32., 33.} pb.F_DoubleRepeatedPacked = []float64{64., 65.} pb.F_Sint32RepeatedPacked = []int32{32, -32} pb.F_Sint64RepeatedPacked = []int64{64, -64} overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 "aa0308"+ // field 53, encoding 2, 8 bytes "a00c0000050d0000"+ // value 3232, value 3333 "b20310"+ // field 54, encoding 2, 16 bytes "4019000000000000a519000000000000"+ // value 6464, value 6565 "ba0306"+ // field 55, encoding 2, 6 bytes "a0dd1395ac14"+ // value 323232, value 333333 "c20306"+ // field 56, encoding 2, 6 bytes "c0ba27b58928"+ // value 646464, value 656565 "ca0308"+ // field 57, encoding 2, 8 bytes "0000004200000442"+ // value 32.0, value 33.0 "d20310"+ // field 58, encoding 2, 16 bytes "00000000000050400000000000405040"+ // value 64.0, value 65.0 "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "b21f02"+ // field 502, encoding 2, 2 bytes "403f"+ // value 32, value -32 "ba1f03"+ // field 503, encoding 2, 3 bytes "80017f") // value 64, value -64 } // Test that we can encode empty bytes fields. func TestEncodeDecodeBytes1(t *testing.T) { pb := initGoTest(false) // Create our bytes pb.F_BytesRequired = []byte{} pb.F_BytesRepeated = [][]byte{{}} pb.F_BytesOptional = []byte{} d, err := Marshal(pb) if err != nil { t.Error(err) } pbd := new(GoTest) if err := Unmarshal(d, pbd); err != nil { t.Error(err) } if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { t.Error("required empty bytes field is incorrect") } if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { t.Error("repeated empty bytes field is incorrect") } if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { t.Error("optional empty bytes field is incorrect") } } // Test that we encode nil-valued fields of a repeated bytes field correctly. // Since entries in a repeated field cannot be nil, nil must mean empty value. func TestEncodeDecodeBytes2(t *testing.T) { pb := initGoTest(false) // Create our bytes pb.F_BytesRepeated = [][]byte{nil} d, err := Marshal(pb) if err != nil { t.Error(err) } pbd := new(GoTest) if err := Unmarshal(d, pbd); err != nil { t.Error(err) } if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { t.Error("Unexpected value for repeated bytes field") } } // All required fields set, defaults provided, all repeated fields given two values. func TestSkippingUnrecognizedFields(t *testing.T) { o := old() pb := initGoTestField() // Marshal it normally. o.Marshal(pb) // Now new a GoSkipTest record. skip := &GoSkipTest{ SkipInt32: Int32(32), SkipFixed32: Uint32(3232), SkipFixed64: Uint64(6464), SkipString: String("skipper"), Skipgroup: &GoSkipTest_SkipGroup{ GroupInt32: Int32(75), GroupString: String("wxyz"), }, } // Marshal it into same buffer. o.Marshal(skip) pbd := new(GoTestField) o.Unmarshal(pbd) // The __unrecognized field should be a marshaling of GoSkipTest skipd := new(GoSkipTest) o.SetBuf(pbd.XXX_unrecognized) o.Unmarshal(skipd) if *skipd.SkipInt32 != *skip.SkipInt32 { t.Error("skip int32", skipd.SkipInt32) } if *skipd.SkipFixed32 != *skip.SkipFixed32 { t.Error("skip fixed32", skipd.SkipFixed32) } if *skipd.SkipFixed64 != *skip.SkipFixed64 { t.Error("skip fixed64", skipd.SkipFixed64) } if *skipd.SkipString != *skip.SkipString { t.Error("skip string", *skipd.SkipString) } if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { t.Error("skip group int32", skipd.Skipgroup.GroupInt32) } if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { t.Error("skip group string", *skipd.Skipgroup.GroupString) } } // Check that unrecognized fields of a submessage are preserved. func TestSubmessageUnrecognizedFields(t *testing.T) { nm := &NewMessage{ Nested: &NewMessage_Nested{ Name: String("Nigel"), FoodGroup: String("carbs"), }, } b, err := Marshal(nm) if err != nil { t.Fatalf("Marshal of NewMessage: %v", err) } // Unmarshal into an OldMessage. om := new(OldMessage) if err := Unmarshal(b, om); err != nil { t.Fatalf("Unmarshal to OldMessage: %v", err) } exp := &OldMessage{ Nested: &OldMessage_Nested{ Name: String("Nigel"), // normal protocol buffer users should not do this XXX_unrecognized: []byte("\x12\x05carbs"), }, } if !Equal(om, exp) { t.Errorf("om = %v, want %v", om, exp) } // Clone the OldMessage. om = Clone(om).(*OldMessage) if !Equal(om, exp) { t.Errorf("Clone(om) = %v, want %v", om, exp) } // Marshal the OldMessage, then unmarshal it into an empty NewMessage. if b, err = Marshal(om); err != nil { t.Fatalf("Marshal of OldMessage: %v", err) } t.Logf("Marshal(%v) -> %q", om, b) nm2 := new(NewMessage) if err := Unmarshal(b, nm2); err != nil { t.Fatalf("Unmarshal to NewMessage: %v", err) } if !Equal(nm, nm2) { t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) } } // Check that an int32 field can be upgraded to an int64 field. func TestNegativeInt32(t *testing.T) { om := &OldMessage{ Num: Int32(-1), } b, err := Marshal(om) if err != nil { t.Fatalf("Marshal of OldMessage: %v", err) } // Check the size. It should be 11 bytes; // 1 for the field/wire type, and 10 for the negative number. if len(b) != 11 { t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) } // Unmarshal into a NewMessage. nm := new(NewMessage) if err := Unmarshal(b, nm); err != nil { t.Fatalf("Unmarshal to NewMessage: %v", err) } want := &NewMessage{ Num: Int64(-1), } if !Equal(nm, want) { t.Errorf("nm = %v, want %v", nm, want) } } // Check that we can grow an array (repeated field) to have many elements. // This test doesn't depend only on our encoding; for variety, it makes sure // we create, encode, and decode the correct contents explicitly. It's therefore // a bit messier. // This test also uses (and hence tests) the Marshal/Unmarshal functions // instead of the methods. func TestBigRepeated(t *testing.T) { pb := initGoTest(true) // Create the arrays const N = 50 // Internally the library starts much smaller. pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) pb.F_Sint64Repeated = make([]int64, N) pb.F_Sint32Repeated = make([]int32, N) pb.F_BytesRepeated = make([][]byte, N) pb.F_StringRepeated = make([]string, N) pb.F_DoubleRepeated = make([]float64, N) pb.F_FloatRepeated = make([]float32, N) pb.F_Uint64Repeated = make([]uint64, N) pb.F_Uint32Repeated = make([]uint32, N) pb.F_Fixed64Repeated = make([]uint64, N) pb.F_Fixed32Repeated = make([]uint32, N) pb.F_Int64Repeated = make([]int64, N) pb.F_Int32Repeated = make([]int32, N) pb.F_BoolRepeated = make([]bool, N) pb.RepeatedField = make([]*GoTestField, N) // Fill in the arrays with checkable values. igtf := initGoTestField() igtrg := initGoTest_RepeatedGroup() for i := 0; i < N; i++ { pb.Repeatedgroup[i] = igtrg pb.F_Sint64Repeated[i] = int64(i) pb.F_Sint32Repeated[i] = int32(i) s := fmt.Sprint(i) pb.F_BytesRepeated[i] = []byte(s) pb.F_StringRepeated[i] = s pb.F_DoubleRepeated[i] = float64(i) pb.F_FloatRepeated[i] = float32(i) pb.F_Uint64Repeated[i] = uint64(i) pb.F_Uint32Repeated[i] = uint32(i) pb.F_Fixed64Repeated[i] = uint64(i) pb.F_Fixed32Repeated[i] = uint32(i) pb.F_Int64Repeated[i] = int64(i) pb.F_Int32Repeated[i] = int32(i) pb.F_BoolRepeated[i] = i%2 == 0 pb.RepeatedField[i] = igtf } // Marshal. buf, _ := Marshal(pb) // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) Unmarshal(buf, pbd) // Check the checkable values for i := uint64(0); i < N; i++ { if pbd.Repeatedgroup[i] == nil { // TODO: more checking? t.Error("pbd.Repeatedgroup bad") } var x uint64 x = uint64(pbd.F_Sint64Repeated[i]) if x != i { t.Error("pbd.F_Sint64Repeated bad", x, i) } x = uint64(pbd.F_Sint32Repeated[i]) if x != i { t.Error("pbd.F_Sint32Repeated bad", x, i) } s := fmt.Sprint(i) equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) if pbd.F_StringRepeated[i] != s { t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) } x = uint64(pbd.F_DoubleRepeated[i]) if x != i { t.Error("pbd.F_DoubleRepeated bad", x, i) } x = uint64(pbd.F_FloatRepeated[i]) if x != i { t.Error("pbd.F_FloatRepeated bad", x, i) } x = pbd.F_Uint64Repeated[i] if x != i { t.Error("pbd.F_Uint64Repeated bad", x, i) } x = uint64(pbd.F_Uint32Repeated[i]) if x != i { t.Error("pbd.F_Uint32Repeated bad", x, i) } x = pbd.F_Fixed64Repeated[i] if x != i { t.Error("pbd.F_Fixed64Repeated bad", x, i) } x = uint64(pbd.F_Fixed32Repeated[i]) if x != i { t.Error("pbd.F_Fixed32Repeated bad", x, i) } x = uint64(pbd.F_Int64Repeated[i]) if x != i { t.Error("pbd.F_Int64Repeated bad", x, i) } x = uint64(pbd.F_Int32Repeated[i]) if x != i { t.Error("pbd.F_Int32Repeated bad", x, i) } if pbd.F_BoolRepeated[i] != (i%2 == 0) { t.Error("pbd.F_BoolRepeated bad", x, i) } if pbd.RepeatedField[i] == nil { // TODO: more checking? t.Error("pbd.RepeatedField bad") } } } // Verify we give a useful message when decoding to the wrong structure type. func TestTypeMismatch(t *testing.T) { pb1 := initGoTest(true) // Marshal o := old() o.Marshal(pb1) // Now Unmarshal it to the wrong type. pb2 := initGoTestField() err := o.Unmarshal(pb2) if err == nil { t.Error("expected error, got no error") } else if !strings.Contains(err.Error(), "bad wiretype") { t.Error("expected bad wiretype error, got", err) } } func encodeDecode(t *testing.T, in, out Message, msg string) { buf, err := Marshal(in) if err != nil { t.Fatalf("failed marshaling %v: %v", msg, err) } if err := Unmarshal(buf, out); err != nil { t.Fatalf("failed unmarshaling %v: %v", msg, err) } } func TestPackedNonPackedDecoderSwitching(t *testing.T) { np, p := new(NonPackedTest), new(PackedTest) // non-packed -> packed np.A = []int32{0, 1, 1, 2, 3, 5} encodeDecode(t, np, p, "non-packed -> packed") if !reflect.DeepEqual(np.A, p.B) { t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) } // packed -> non-packed np.Reset() p.B = []int32{3, 1, 4, 1, 5, 9} encodeDecode(t, p, np, "packed -> non-packed") if !reflect.DeepEqual(p.B, np.A) { t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) } } func TestProto1RepeatedGroup(t *testing.T) { pb := &MessageList{ Message: []*MessageList_Message{ { Name: String("blah"), Count: Int32(7), }, // NOTE: pb.Message[1] is a nil nil, }, } o := old() err := o.Marshal(pb) if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { t.Fatalf("unexpected or no error when marshaling: %v", err) } } // Test that enums work. Checks for a bug introduced by making enums // named types instead of int32: newInt32FromUint64 would crash with // a type mismatch in reflect.PointTo. func TestEnum(t *testing.T) { pb := new(GoEnum) pb.Foo = FOO_FOO1.Enum() o := old() if err := o.Marshal(pb); err != nil { t.Fatal("error encoding enum:", err) } pb1 := new(GoEnum) if err := o.Unmarshal(pb1); err != nil { t.Fatal("error decoding enum:", err) } if *pb1.Foo != FOO_FOO1 { t.Error("expected 7 but got ", *pb1.Foo) } } // Enum types have String methods. Check that enum fields can be printed. // We don't care what the value actually is, just as long as it doesn't crash. func TestPrintingNilEnumFields(t *testing.T) { pb := new(GoEnum) _ = fmt.Sprintf("%+v", pb) } // Verify that absent required fields cause Marshal/Unmarshal to return errors. func TestRequiredFieldEnforcement(t *testing.T) { pb := new(GoTestField) _, err := Marshal(pb) if err == nil { t.Error("marshal: expected error, got nil") } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { t.Errorf("marshal: bad error type: %v", err) } // A slightly sneaky, yet valid, proto. It encodes the same required field twice, // so simply counting the required fields is insufficient. // field 1, encoding 2, value "hi" buf := []byte("\x0A\x02hi\x0A\x02hi") err = Unmarshal(buf, pb) if err == nil { t.Error("unmarshal: expected error, got nil") } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") { t.Errorf("unmarshal: bad error type: %v", err) } } // Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. func TestRequiredFieldEnforcementGroups(t *testing.T) { pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} if _, err := Marshal(pb); err == nil { t.Error("marshal: expected error, got nil") } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { t.Errorf("marshal: bad error type: %v", err) } buf := []byte{11, 12} if err := Unmarshal(buf, pb); err == nil { t.Error("unmarshal: expected error, got nil") } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") { t.Errorf("unmarshal: bad error type: %v", err) } } func TestTypedNilMarshal(t *testing.T) { // A typed nil should return ErrNil and not crash. { var m *GoEnum if _, err := Marshal(m); err != ErrNil { t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) } } { m := &Communique{Union: &Communique_Msg{nil}} if _, err := Marshal(m); err == nil || err == ErrNil { t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) } } } // A type that implements the Marshaler interface, but is not nillable. type nonNillableInt uint64 func (nni nonNillableInt) Marshal() ([]byte, error) { return EncodeVarint(uint64(nni)), nil } type NNIMessage struct { nni nonNillableInt } func (*NNIMessage) Reset() {} func (*NNIMessage) String() string { return "" } func (*NNIMessage) ProtoMessage() {} // A type that implements the Marshaler interface and is nillable. type nillableMessage struct { x uint64 } func (nm *nillableMessage) Marshal() ([]byte, error) { return EncodeVarint(nm.x), nil } type NMMessage struct { nm *nillableMessage } func (*NMMessage) Reset() {} func (*NMMessage) String() string { return "" } func (*NMMessage) ProtoMessage() {} // Verify a type that uses the Marshaler interface, but has a nil pointer. func TestNilMarshaler(t *testing.T) { // Try a struct with a Marshaler field that is nil. // It should be directly marshable. nmm := new(NMMessage) if _, err := Marshal(nmm); err != nil { t.Error("unexpected error marshaling nmm: ", err) } // Try a struct with a Marshaler field that is not nillable. nnim := new(NNIMessage) nnim.nni = 7 var _ Marshaler = nnim.nni // verify it is truly a Marshaler if _, err := Marshal(nnim); err != nil { t.Error("unexpected error marshaling nnim: ", err) } } func TestAllSetDefaults(t *testing.T) { // Exercise SetDefaults with all scalar field types. m := &Defaults{ // NaN != NaN, so override that here. F_Nan: Float32(1.7), } expected := &Defaults{ F_Bool: Bool(true), F_Int32: Int32(32), F_Int64: Int64(64), F_Fixed32: Uint32(320), F_Fixed64: Uint64(640), F_Uint32: Uint32(3200), F_Uint64: Uint64(6400), F_Float: Float32(314159), F_Double: Float64(271828), F_String: String(`hello, "world!"` + "\n"), F_Bytes: []byte("Bignose"), F_Sint32: Int32(-32), F_Sint64: Int64(-64), F_Enum: Defaults_GREEN.Enum(), F_Pinf: Float32(float32(math.Inf(1))), F_Ninf: Float32(float32(math.Inf(-1))), F_Nan: Float32(1.7), StrZero: String(""), } SetDefaults(m) if !Equal(m, expected) { t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) } } func TestSetDefaultsWithSetField(t *testing.T) { // Check that a set value is not overridden. m := &Defaults{ F_Int32: Int32(12), } SetDefaults(m) if v := m.GetF_Int32(); v != 12 { t.Errorf("m.FInt32 = %v, want 12", v) } } func TestSetDefaultsWithSubMessage(t *testing.T) { m := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("gopher"), }, } expected := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("gopher"), Port: Int32(4000), }, } SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { m := &MyMessage{ RepInner: []*InnerMessage{{}}, } expected := &MyMessage{ RepInner: []*InnerMessage{{ Port: Int32(4000), }}, } SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { m := &MyMessage{ Pet: []string{"turtle", "wombat"}, } expected := Clone(m) SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestMaximumTagNumber(t *testing.T) { m := &MaxTag{ LastField: String("natural goat essence"), } buf, err := Marshal(m) if err != nil { t.Fatalf("proto.Marshal failed: %v", err) } m2 := new(MaxTag) if err := Unmarshal(buf, m2); err != nil { t.Fatalf("proto.Unmarshal failed: %v", err) } if got, want := m2.GetLastField(), *m.LastField; got != want { t.Errorf("got %q, want %q", got, want) } } func TestJSON(t *testing.T) { m := &MyMessage{ Count: Int32(4), Pet: []string{"bunny", "kitty"}, Inner: &InnerMessage{ Host: String("cauchy"), }, Bikeshed: MyMessage_GREEN.Enum(), } const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` b, err := json.Marshal(m) if err != nil { t.Fatalf("json.Marshal failed: %v", err) } s := string(b) if s != expected { t.Errorf("got %s\nwant %s", s, expected) } received := new(MyMessage) if err := json.Unmarshal(b, received); err != nil { t.Fatalf("json.Unmarshal failed: %v", err) } if !Equal(received, m) { t.Fatalf("got %s, want %s", received, m) } // Test unmarshalling of JSON with symbolic enum name. const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` received.Reset() if err := json.Unmarshal([]byte(old), received); err != nil { t.Fatalf("json.Unmarshal failed: %v", err) } if !Equal(received, m) { t.Fatalf("got %s, want %s", received, m) } } func TestBadWireType(t *testing.T) { b := []byte{7<<3 | 6} // field 7, wire type 6 pb := new(OtherMessage) if err := Unmarshal(b, pb); err == nil { t.Errorf("Unmarshal did not fail") } else if !strings.Contains(err.Error(), "unknown wire type") { t.Errorf("wrong error: %v", err) } } func TestBytesWithInvalidLength(t *testing.T) { // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} Unmarshal(b, new(MyMessage)) } func TestLengthOverflow(t *testing.T) { // Overflowing a length should not panic. b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} Unmarshal(b, new(MyMessage)) } func TestVarintOverflow(t *testing.T) { // Overflowing a 64-bit length should not be allowed. b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} if err := Unmarshal(b, new(MyMessage)); err == nil { t.Fatalf("Overflowed uint64 length without error") } } func TestUnmarshalFuzz(t *testing.T) { const N = 1000 seed := time.Now().UnixNano() t.Logf("RNG seed is %d", seed) rng := rand.New(rand.NewSource(seed)) buf := make([]byte, 20) for i := 0; i < N; i++ { for j := range buf { buf[j] = byte(rng.Intn(256)) } fuzzUnmarshal(t, buf) } } func TestMergeMessages(t *testing.T) { pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} data, err := Marshal(pb) if err != nil { t.Fatalf("Marshal: %v", err) } pb1 := new(MessageList) if err := Unmarshal(data, pb1); err != nil { t.Fatalf("first Unmarshal: %v", err) } if err := Unmarshal(data, pb1); err != nil { t.Fatalf("second Unmarshal: %v", err) } if len(pb1.Message) != 1 { t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) } pb2 := new(MessageList) if err := UnmarshalMerge(data, pb2); err != nil { t.Fatalf("first UnmarshalMerge: %v", err) } if err := UnmarshalMerge(data, pb2); err != nil { t.Fatalf("second UnmarshalMerge: %v", err) } if len(pb2.Message) != 2 { t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) } } func TestExtensionMarshalOrder(t *testing.T) { m := &MyMessage{Count: Int(123)} if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { t.Fatalf("SetExtension: %v", err) } if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { t.Fatalf("SetExtension: %v", err) } if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { t.Fatalf("SetExtension: %v", err) } // Serialize m several times, and check we get the same bytes each time. var orig []byte for i := 0; i < 100; i++ { b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } if i == 0 { orig = b continue } if !bytes.Equal(b, orig) { t.Errorf("Bytes differ on attempt #%d", i) } } } // Many extensions, because small maps might not iterate differently on each iteration. var exts = []*ExtensionDesc{ E_X201, E_X202, E_X203, E_X204, E_X205, E_X206, E_X207, E_X208, E_X209, E_X210, E_X211, E_X212, E_X213, E_X214, E_X215, E_X216, E_X217, E_X218, E_X219, E_X220, E_X221, E_X222, E_X223, E_X224, E_X225, E_X226, E_X227, E_X228, E_X229, E_X230, E_X231, E_X232, E_X233, E_X234, E_X235, E_X236, E_X237, E_X238, E_X239, E_X240, E_X241, E_X242, E_X243, E_X244, E_X245, E_X246, E_X247, E_X248, E_X249, E_X250, } func TestMessageSetMarshalOrder(t *testing.T) { m := &MyMessageSet{} for _, x := range exts { if err := SetExtension(m, x, &Empty{}); err != nil { t.Fatalf("SetExtension: %v", err) } } buf, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } // Serialize m several times, and check we get the same bytes each time. for i := 0; i < 10; i++ { b1, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } if !bytes.Equal(b1, buf) { t.Errorf("Bytes differ on re-Marshal #%d", i) } m2 := &MyMessageSet{} if err := Unmarshal(buf, m2); err != nil { t.Errorf("Unmarshal: %v", err) } b2, err := Marshal(m2) if err != nil { t.Errorf("re-Marshal: %v", err) } if !bytes.Equal(b2, buf) { t.Errorf("Bytes differ on round-trip #%d", i) } } } func TestUnmarshalMergesMessages(t *testing.T) { // If a nested message occurs twice in the input, // the fields should be merged when decoding. a := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("polhode"), Port: Int32(1234), }, } aData, err := Marshal(a) if err != nil { t.Fatalf("Marshal(a): %v", err) } b := &OtherMessage{ Weight: Float32(1.2), Inner: &InnerMessage{ Host: String("herpolhode"), Connected: Bool(true), }, } bData, err := Marshal(b) if err != nil { t.Fatalf("Marshal(b): %v", err) } want := &OtherMessage{ Key: Int64(123), Weight: Float32(1.2), Inner: &InnerMessage{ Host: String("herpolhode"), Port: Int32(1234), Connected: Bool(true), }, } got := new(OtherMessage) if err := Unmarshal(append(aData, bData...), got); err != nil { t.Fatalf("Unmarshal: %v", err) } if !Equal(got, want) { t.Errorf("\n got %v\nwant %v", got, want) } } func TestEncodingSizes(t *testing.T) { tests := []struct { m Message n int }{ {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, } for _, test := range tests { b, err := Marshal(test.m) if err != nil { t.Errorf("Marshal(%v): %v", test.m, err) continue } if len(b) != test.n { t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) } } } func TestRequiredNotSetError(t *testing.T) { pb := initGoTest(false) pb.RequiredField.Label = nil pb.F_Int32Required = nil pb.F_Int64Required = nil expected := "0807" + // field 1, encoding 0, value 7 "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) "5001" + // field 10, encoding 0, value 1 "6d20000000" + // field 13, encoding 5, value 0x20 "714000000000000000" + // field 14, encoding 1, value 0x40 "78a019" + // field 15, encoding 0, value 0xca0 = 3232 "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 "8d0100004a45" + // field 17, encoding 5, value 3232.0 "9101000000000040b940" + // field 18, encoding 1, value 6464.0 "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" "b304" + // field 70, encoding 3, start group "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" "b404" + // field 70, encoding 4, end group "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" "b0063f" + // field 102, encoding 0, 0x3f zigzag32 "b8067f" // field 103, encoding 0, 0x7f zigzag64 o := old() bytes, err := Marshal(pb) if _, ok := err.(*RequiredNotSetError); !ok { fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("expected = %s", expected) } if strings.Index(err.Error(), "RequiredField.Label") < 0 { t.Errorf("marshal-1 wrong err msg: %v", err) } if !equal(bytes, expected, t) { o.DebugPrint("neq 1", bytes) t.Fatalf("expected = %s", expected) } // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) err = Unmarshal(bytes, pbd) if _, ok := err.(*RequiredNotSetError); !ok { t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("string = %s", expected) } if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { t.Errorf("unmarshal wrong err msg: %v", err) } bytes, err = Marshal(pbd) if _, ok := err.(*RequiredNotSetError); !ok { t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("string = %s", expected) } if strings.Index(err.Error(), "RequiredField.Label") < 0 { t.Errorf("marshal-2 wrong err msg: %v", err) } if !equal(bytes, expected, t) { o.DebugPrint("neq 2", bytes) t.Fatalf("string = %s", expected) } } func fuzzUnmarshal(t *testing.T, data []byte) { defer func() { if e := recover(); e != nil { t.Errorf("These bytes caused a panic: %+v", data) t.Logf("Stack:\n%s", debug.Stack()) t.FailNow() } }() pb := new(MyMessage) Unmarshal(data, pb) } func TestMapFieldMarshal(t *testing.T) { m := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Rob", 4: "Ian", 8: "Dave", }, } b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } // b should be the concatenation of these three byte sequences in some order. parts := []string{ "\n\a\b\x01\x12\x03Rob", "\n\a\b\x04\x12\x03Ian", "\n\b\b\x08\x12\x04Dave", } ok := false for i := range parts { for j := range parts { if j == i { continue } for k := range parts { if k == i || k == j { continue } try := parts[i] + parts[j] + parts[k] if bytes.Equal(b, []byte(try)) { ok = true break } } } } if !ok { t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) } t.Logf("FYI b: %q", b) (new(Buffer)).DebugPrint("Dump of b", b) } func TestMapFieldRoundTrips(t *testing.T) { m := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Rob", 4: "Ian", 8: "Dave", }, MsgMapping: map[int64]*FloatingPoint{ 0x7001: &FloatingPoint{F: Float64(2.0)}, }, ByteMapping: map[bool][]byte{ false: []byte("that's not right!"), true: []byte("aye, 'tis true!"), }, } b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } t.Logf("FYI b: %q", b) m2 := new(MessageWithMap) if err := Unmarshal(b, m2); err != nil { t.Fatalf("Unmarshal: %v", err) } for _, pair := range [][2]interface{}{ {m.NameMapping, m2.NameMapping}, {m.MsgMapping, m2.MsgMapping}, {m.ByteMapping, m2.ByteMapping}, } { if !reflect.DeepEqual(pair[0], pair[1]) { t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) } } } func TestMapFieldWithNil(t *testing.T) { m1 := &MessageWithMap{ MsgMapping: map[int64]*FloatingPoint{ 1: nil, }, } b, err := Marshal(m1) if err != nil { t.Fatalf("Marshal: %v", err) } m2 := new(MessageWithMap) if err := Unmarshal(b, m2); err != nil { t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) } if v, ok := m2.MsgMapping[1]; !ok { t.Error("msg_mapping[1] not present") } else if v != nil { t.Errorf("msg_mapping[1] not nil: %v", v) } } func TestMapFieldWithNilBytes(t *testing.T) { m1 := &MessageWithMap{ ByteMapping: map[bool][]byte{ false: []byte{}, true: nil, }, } n := Size(m1) b, err := Marshal(m1) if err != nil { t.Fatalf("Marshal: %v", err) } if n != len(b) { t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) } m2 := new(MessageWithMap) if err := Unmarshal(b, m2); err != nil { t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) } if v, ok := m2.ByteMapping[false]; !ok { t.Error("byte_mapping[false] not present") } else if len(v) != 0 { t.Errorf("byte_mapping[false] not empty: %#v", v) } if v, ok := m2.ByteMapping[true]; !ok { t.Error("byte_mapping[true] not present") } else if len(v) != 0 { t.Errorf("byte_mapping[true] not empty: %#v", v) } } func TestDecodeMapFieldMissingKey(t *testing.T) { b := []byte{ 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes // no key 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" } got := &MessageWithMap{} err := Unmarshal(b, got) if err != nil { t.Fatalf("failed to marshal map with missing key: %v", err) } want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} if !Equal(got, want) { t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) } } func TestDecodeMapFieldMissingValue(t *testing.T) { b := []byte{ 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes 0x08, 0x01, // varint key, value 1 // no value } got := &MessageWithMap{} err := Unmarshal(b, got) if err != nil { t.Fatalf("failed to marshal map with missing value: %v", err) } want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} if !Equal(got, want) { t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) } } func TestOneof(t *testing.T) { m := &Communique{} b, err := Marshal(m) if err != nil { t.Fatalf("Marshal of empty message with oneof: %v", err) } if len(b) != 0 { t.Errorf("Marshal of empty message yielded too many bytes: %v", b) } m = &Communique{ Union: &Communique_Name{"Barry"}, } // Round-trip. b, err = Marshal(m) if err != nil { t.Fatalf("Marshal of message with oneof: %v", err) } if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) t.Errorf("Incorrect marshal of message with oneof: %v", b) } m.Reset() if err := Unmarshal(b, m); err != nil { t.Fatalf("Unmarshal of message with oneof: %v", err) } if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { t.Errorf("After round trip, Union = %+v", m.Union) } if name := m.GetName(); name != "Barry" { t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") } // Let's try with a message in the oneof. m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} b, err = Marshal(m) if err != nil { t.Fatalf("Marshal of message with oneof set to message: %v", err) } if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) } m.Reset() if err := Unmarshal(b, m); err != nil { t.Fatalf("Unmarshal of message with oneof set to message: %v", err) } ss, ok := m.Union.(*Communique_Msg) if !ok || ss.Msg.GetStringField() != "deep deep string" { t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) } } func TestInefficientPackedBool(t *testing.T) { // https://github.com/golang/protobuf/issues/76 inp := []byte{ 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes // Usually a bool should take a single byte, // but it is permitted to be any varint. 0xb9, 0x30, } if err := Unmarshal(inp, new(MoreRepeated)); err != nil { t.Error(err) } } // Benchmarks func testMsg() *GoTest { pb := initGoTest(true) const N = 1000 // Internally the library starts much smaller. pb.F_Int32Repeated = make([]int32, N) pb.F_DoubleRepeated = make([]float64, N) for i := 0; i < N; i++ { pb.F_Int32Repeated[i] = int32(i) pb.F_DoubleRepeated[i] = float64(i) } return pb } func bytesMsg() *GoTest { pb := initGoTest(true) buf := make([]byte, 4000) for i := range buf { buf[i] = byte(i) } pb.F_BytesDefaulted = buf return pb } func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { d, _ := marshal(pb) b.SetBytes(int64(len(d))) b.ResetTimer() for i := 0; i < b.N; i++ { marshal(pb) } } func benchmarkBufferMarshal(b *testing.B, pb Message) { p := NewBuffer(nil) benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { p.Reset() err := p.Marshal(pb0) return p.Bytes(), err }) } func benchmarkSize(b *testing.B, pb Message) { benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { Size(pb) return nil, nil }) } func newOf(pb Message) Message { in := reflect.ValueOf(pb) if in.IsNil() { return pb } return reflect.New(in.Type().Elem()).Interface().(Message) } func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { d, _ := Marshal(pb) b.SetBytes(int64(len(d))) pbd := newOf(pb) b.ResetTimer() for i := 0; i < b.N; i++ { unmarshal(d, pbd) } } func benchmarkBufferUnmarshal(b *testing.B, pb Message) { p := NewBuffer(nil) benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { p.SetBuf(d) return p.Unmarshal(pb0) }) } // Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} func BenchmarkMarshal(b *testing.B) { benchmarkMarshal(b, testMsg(), Marshal) } func BenchmarkBufferMarshal(b *testing.B) { benchmarkBufferMarshal(b, testMsg()) } func BenchmarkSize(b *testing.B) { benchmarkSize(b, testMsg()) } func BenchmarkUnmarshal(b *testing.B) { benchmarkUnmarshal(b, testMsg(), Unmarshal) } func BenchmarkBufferUnmarshal(b *testing.B) { benchmarkBufferUnmarshal(b, testMsg()) } func BenchmarkMarshalBytes(b *testing.B) { benchmarkMarshal(b, bytesMsg(), Marshal) } func BenchmarkBufferMarshalBytes(b *testing.B) { benchmarkBufferMarshal(b, bytesMsg()) } func BenchmarkSizeBytes(b *testing.B) { benchmarkSize(b, bytesMsg()) } func BenchmarkUnmarshalBytes(b *testing.B) { benchmarkUnmarshal(b, bytesMsg(), Unmarshal) } func BenchmarkBufferUnmarshalBytes(b *testing.B) { benchmarkBufferUnmarshal(b, bytesMsg()) } func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { b.StopTimer() pb := initGoTestField() skip := &GoSkipTest{ SkipInt32: Int32(32), SkipFixed32: Uint32(3232), SkipFixed64: Uint64(6464), SkipString: String("skipper"), Skipgroup: &GoSkipTest_SkipGroup{ GroupInt32: Int32(75), GroupString: String("wxyz"), }, } pbd := new(GoTestField) p := NewBuffer(nil) p.Marshal(pb) p.Marshal(skip) p2 := NewBuffer(nil) b.StartTimer() for i := 0; i < b.N; i++ { p2.SetBuf(p.Bytes()) p2.Unmarshal(pbd) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/proto/Makefile���������������������������������������0000644�0610621�0607500�00000003616�13172163407�025205� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. install: go install test: install generate-test-pbs go test generate-test-pbs: make install make -C testdata protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto make ������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/����������������������������������������������0000755�0610621�0607500�00000000000�13172163407�023667� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/����������������������������0000755�0610621�0607500�00000000000�13172163407�027444� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto����������0000644�0610621�0607500�00000010675�13172163407�033232� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto2"; import "google/protobuf/any.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/struct.proto"; import "google/protobuf/timestamp.proto"; import "google/protobuf/wrappers.proto"; package jsonpb; // Test message for holding primitive types. message Simple { optional bool o_bool = 1; optional int32 o_int32 = 2; optional int64 o_int64 = 3; optional uint32 o_uint32 = 4; optional uint64 o_uint64 = 5; optional sint32 o_sint32 = 6; optional sint64 o_sint64 = 7; optional float o_float = 8; optional double o_double = 9; optional string o_string = 10; optional bytes o_bytes = 11; } // Test message for holding special non-finites primitives. message NonFinites { optional float f_nan = 1; optional float f_pinf = 2; optional float f_ninf = 3; optional double d_nan = 4; optional double d_pinf = 5; optional double d_ninf = 6; } // Test message for holding repeated primitives. message Repeats { repeated bool r_bool = 1; repeated int32 r_int32 = 2; repeated int64 r_int64 = 3; repeated uint32 r_uint32 = 4; repeated uint64 r_uint64 = 5; repeated sint32 r_sint32 = 6; repeated sint64 r_sint64 = 7; repeated float r_float = 8; repeated double r_double = 9; repeated string r_string = 10; repeated bytes r_bytes = 11; } // Test message for holding enums and nested messages. message Widget { enum Color { RED = 0; GREEN = 1; BLUE = 2; }; optional Color color = 1; repeated Color r_color = 2; optional Simple simple = 10; repeated Simple r_simple = 11; optional Repeats repeats = 20; repeated Repeats r_repeats = 21; } message Maps { map<int64, string> m_int64_str = 1; map<bool, Simple> m_bool_simple = 2; } message MsgWithOneof { oneof union { string title = 1; int64 salary = 2; string Country = 3; string home_address = 4; } } message Real { optional double value = 1; extensions 100 to max; } extend Real { optional string name = 124; } message Complex { extend Real { optional Complex real_extension = 123; } optional double imaginary = 1; extensions 100 to max; } message KnownTypes { optional google.protobuf.Any an = 14; optional google.protobuf.Duration dur = 1; optional google.protobuf.Struct st = 12; optional google.protobuf.Timestamp ts = 2; optional google.protobuf.ListValue lv = 15; optional google.protobuf.Value val = 16; optional google.protobuf.DoubleValue dbl = 3; optional google.protobuf.FloatValue flt = 4; optional google.protobuf.Int64Value i64 = 5; optional google.protobuf.UInt64Value u64 = 6; optional google.protobuf.Int32Value i32 = 7; optional google.protobuf.UInt32Value u32 = 8; optional google.protobuf.BoolValue bool = 9; optional google.protobuf.StringValue str = 10; optional google.protobuf.BytesValue bytes = 11; } �������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go����������0000644�0610621�0607500�00000071243�13172163407�033072� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: test_objects.proto package jsonpb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/ptypes/any" import google_protobuf1 "github.com/golang/protobuf/ptypes/duration" import google_protobuf2 "github.com/golang/protobuf/ptypes/struct" import google_protobuf3 "github.com/golang/protobuf/ptypes/timestamp" import google_protobuf4 "github.com/golang/protobuf/ptypes/wrappers" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf type Widget_Color int32 const ( Widget_RED Widget_Color = 0 Widget_GREEN Widget_Color = 1 Widget_BLUE Widget_Color = 2 ) var Widget_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Widget_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Widget_Color) Enum() *Widget_Color { p := new(Widget_Color) *p = x return p } func (x Widget_Color) String() string { return proto.EnumName(Widget_Color_name, int32(x)) } func (x *Widget_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Widget_Color_value, data, "Widget_Color") if err != nil { return err } *x = Widget_Color(value) return nil } func (Widget_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{3, 0} } // Test message for holding primitive types. type Simple struct { OBool *bool `protobuf:"varint,1,opt,name=o_bool,json=oBool" json:"o_bool,omitempty"` OInt32 *int32 `protobuf:"varint,2,opt,name=o_int32,json=oInt32" json:"o_int32,omitempty"` OInt64 *int64 `protobuf:"varint,3,opt,name=o_int64,json=oInt64" json:"o_int64,omitempty"` OUint32 *uint32 `protobuf:"varint,4,opt,name=o_uint32,json=oUint32" json:"o_uint32,omitempty"` OUint64 *uint64 `protobuf:"varint,5,opt,name=o_uint64,json=oUint64" json:"o_uint64,omitempty"` OSint32 *int32 `protobuf:"zigzag32,6,opt,name=o_sint32,json=oSint32" json:"o_sint32,omitempty"` OSint64 *int64 `protobuf:"zigzag64,7,opt,name=o_sint64,json=oSint64" json:"o_sint64,omitempty"` OFloat *float32 `protobuf:"fixed32,8,opt,name=o_float,json=oFloat" json:"o_float,omitempty"` ODouble *float64 `protobuf:"fixed64,9,opt,name=o_double,json=oDouble" json:"o_double,omitempty"` OString *string `protobuf:"bytes,10,opt,name=o_string,json=oString" json:"o_string,omitempty"` OBytes []byte `protobuf:"bytes,11,opt,name=o_bytes,json=oBytes" json:"o_bytes,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Simple) Reset() { *m = Simple{} } func (m *Simple) String() string { return proto.CompactTextString(m) } func (*Simple) ProtoMessage() {} func (*Simple) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} } func (m *Simple) GetOBool() bool { if m != nil && m.OBool != nil { return *m.OBool } return false } func (m *Simple) GetOInt32() int32 { if m != nil && m.OInt32 != nil { return *m.OInt32 } return 0 } func (m *Simple) GetOInt64() int64 { if m != nil && m.OInt64 != nil { return *m.OInt64 } return 0 } func (m *Simple) GetOUint32() uint32 { if m != nil && m.OUint32 != nil { return *m.OUint32 } return 0 } func (m *Simple) GetOUint64() uint64 { if m != nil && m.OUint64 != nil { return *m.OUint64 } return 0 } func (m *Simple) GetOSint32() int32 { if m != nil && m.OSint32 != nil { return *m.OSint32 } return 0 } func (m *Simple) GetOSint64() int64 { if m != nil && m.OSint64 != nil { return *m.OSint64 } return 0 } func (m *Simple) GetOFloat() float32 { if m != nil && m.OFloat != nil { return *m.OFloat } return 0 } func (m *Simple) GetODouble() float64 { if m != nil && m.ODouble != nil { return *m.ODouble } return 0 } func (m *Simple) GetOString() string { if m != nil && m.OString != nil { return *m.OString } return "" } func (m *Simple) GetOBytes() []byte { if m != nil { return m.OBytes } return nil } // Test message for holding special non-finites primitives. type NonFinites struct { FNan *float32 `protobuf:"fixed32,1,opt,name=f_nan,json=fNan" json:"f_nan,omitempty"` FPinf *float32 `protobuf:"fixed32,2,opt,name=f_pinf,json=fPinf" json:"f_pinf,omitempty"` FNinf *float32 `protobuf:"fixed32,3,opt,name=f_ninf,json=fNinf" json:"f_ninf,omitempty"` DNan *float64 `protobuf:"fixed64,4,opt,name=d_nan,json=dNan" json:"d_nan,omitempty"` DPinf *float64 `protobuf:"fixed64,5,opt,name=d_pinf,json=dPinf" json:"d_pinf,omitempty"` DNinf *float64 `protobuf:"fixed64,6,opt,name=d_ninf,json=dNinf" json:"d_ninf,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *NonFinites) Reset() { *m = NonFinites{} } func (m *NonFinites) String() string { return proto.CompactTextString(m) } func (*NonFinites) ProtoMessage() {} func (*NonFinites) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} } func (m *NonFinites) GetFNan() float32 { if m != nil && m.FNan != nil { return *m.FNan } return 0 } func (m *NonFinites) GetFPinf() float32 { if m != nil && m.FPinf != nil { return *m.FPinf } return 0 } func (m *NonFinites) GetFNinf() float32 { if m != nil && m.FNinf != nil { return *m.FNinf } return 0 } func (m *NonFinites) GetDNan() float64 { if m != nil && m.DNan != nil { return *m.DNan } return 0 } func (m *NonFinites) GetDPinf() float64 { if m != nil && m.DPinf != nil { return *m.DPinf } return 0 } func (m *NonFinites) GetDNinf() float64 { if m != nil && m.DNinf != nil { return *m.DNinf } return 0 } // Test message for holding repeated primitives. type Repeats struct { RBool []bool `protobuf:"varint,1,rep,name=r_bool,json=rBool" json:"r_bool,omitempty"` RInt32 []int32 `protobuf:"varint,2,rep,name=r_int32,json=rInt32" json:"r_int32,omitempty"` RInt64 []int64 `protobuf:"varint,3,rep,name=r_int64,json=rInt64" json:"r_int64,omitempty"` RUint32 []uint32 `protobuf:"varint,4,rep,name=r_uint32,json=rUint32" json:"r_uint32,omitempty"` RUint64 []uint64 `protobuf:"varint,5,rep,name=r_uint64,json=rUint64" json:"r_uint64,omitempty"` RSint32 []int32 `protobuf:"zigzag32,6,rep,name=r_sint32,json=rSint32" json:"r_sint32,omitempty"` RSint64 []int64 `protobuf:"zigzag64,7,rep,name=r_sint64,json=rSint64" json:"r_sint64,omitempty"` RFloat []float32 `protobuf:"fixed32,8,rep,name=r_float,json=rFloat" json:"r_float,omitempty"` RDouble []float64 `protobuf:"fixed64,9,rep,name=r_double,json=rDouble" json:"r_double,omitempty"` RString []string `protobuf:"bytes,10,rep,name=r_string,json=rString" json:"r_string,omitempty"` RBytes [][]byte `protobuf:"bytes,11,rep,name=r_bytes,json=rBytes" json:"r_bytes,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Repeats) Reset() { *m = Repeats{} } func (m *Repeats) String() string { return proto.CompactTextString(m) } func (*Repeats) ProtoMessage() {} func (*Repeats) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} } func (m *Repeats) GetRBool() []bool { if m != nil { return m.RBool } return nil } func (m *Repeats) GetRInt32() []int32 { if m != nil { return m.RInt32 } return nil } func (m *Repeats) GetRInt64() []int64 { if m != nil { return m.RInt64 } return nil } func (m *Repeats) GetRUint32() []uint32 { if m != nil { return m.RUint32 } return nil } func (m *Repeats) GetRUint64() []uint64 { if m != nil { return m.RUint64 } return nil } func (m *Repeats) GetRSint32() []int32 { if m != nil { return m.RSint32 } return nil } func (m *Repeats) GetRSint64() []int64 { if m != nil { return m.RSint64 } return nil } func (m *Repeats) GetRFloat() []float32 { if m != nil { return m.RFloat } return nil } func (m *Repeats) GetRDouble() []float64 { if m != nil { return m.RDouble } return nil } func (m *Repeats) GetRString() []string { if m != nil { return m.RString } return nil } func (m *Repeats) GetRBytes() [][]byte { if m != nil { return m.RBytes } return nil } // Test message for holding enums and nested messages. type Widget struct { Color *Widget_Color `protobuf:"varint,1,opt,name=color,enum=jsonpb.Widget_Color" json:"color,omitempty"` RColor []Widget_Color `protobuf:"varint,2,rep,name=r_color,json=rColor,enum=jsonpb.Widget_Color" json:"r_color,omitempty"` Simple *Simple `protobuf:"bytes,10,opt,name=simple" json:"simple,omitempty"` RSimple []*Simple `protobuf:"bytes,11,rep,name=r_simple,json=rSimple" json:"r_simple,omitempty"` Repeats *Repeats `protobuf:"bytes,20,opt,name=repeats" json:"repeats,omitempty"` RRepeats []*Repeats `protobuf:"bytes,21,rep,name=r_repeats,json=rRepeats" json:"r_repeats,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Widget) Reset() { *m = Widget{} } func (m *Widget) String() string { return proto.CompactTextString(m) } func (*Widget) ProtoMessage() {} func (*Widget) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} } func (m *Widget) GetColor() Widget_Color { if m != nil && m.Color != nil { return *m.Color } return Widget_RED } func (m *Widget) GetRColor() []Widget_Color { if m != nil { return m.RColor } return nil } func (m *Widget) GetSimple() *Simple { if m != nil { return m.Simple } return nil } func (m *Widget) GetRSimple() []*Simple { if m != nil { return m.RSimple } return nil } func (m *Widget) GetRepeats() *Repeats { if m != nil { return m.Repeats } return nil } func (m *Widget) GetRRepeats() []*Repeats { if m != nil { return m.RRepeats } return nil } type Maps struct { MInt64Str map[int64]string `protobuf:"bytes,1,rep,name=m_int64_str,json=mInt64Str" json:"m_int64_str,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MBoolSimple map[bool]*Simple `protobuf:"bytes,2,rep,name=m_bool_simple,json=mBoolSimple" json:"m_bool_simple,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` XXX_unrecognized []byte `json:"-"` } func (m *Maps) Reset() { *m = Maps{} } func (m *Maps) String() string { return proto.CompactTextString(m) } func (*Maps) ProtoMessage() {} func (*Maps) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} } func (m *Maps) GetMInt64Str() map[int64]string { if m != nil { return m.MInt64Str } return nil } func (m *Maps) GetMBoolSimple() map[bool]*Simple { if m != nil { return m.MBoolSimple } return nil } type MsgWithOneof struct { // Types that are valid to be assigned to Union: // *MsgWithOneof_Title // *MsgWithOneof_Salary // *MsgWithOneof_Country // *MsgWithOneof_HomeAddress Union isMsgWithOneof_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *MsgWithOneof) Reset() { *m = MsgWithOneof{} } func (m *MsgWithOneof) String() string { return proto.CompactTextString(m) } func (*MsgWithOneof) ProtoMessage() {} func (*MsgWithOneof) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} } type isMsgWithOneof_Union interface { isMsgWithOneof_Union() } type MsgWithOneof_Title struct { Title string `protobuf:"bytes,1,opt,name=title,oneof"` } type MsgWithOneof_Salary struct { Salary int64 `protobuf:"varint,2,opt,name=salary,oneof"` } type MsgWithOneof_Country struct { Country string `protobuf:"bytes,3,opt,name=Country,oneof"` } type MsgWithOneof_HomeAddress struct { HomeAddress string `protobuf:"bytes,4,opt,name=home_address,json=homeAddress,oneof"` } func (*MsgWithOneof_Title) isMsgWithOneof_Union() {} func (*MsgWithOneof_Salary) isMsgWithOneof_Union() {} func (*MsgWithOneof_Country) isMsgWithOneof_Union() {} func (*MsgWithOneof_HomeAddress) isMsgWithOneof_Union() {} func (m *MsgWithOneof) GetUnion() isMsgWithOneof_Union { if m != nil { return m.Union } return nil } func (m *MsgWithOneof) GetTitle() string { if x, ok := m.GetUnion().(*MsgWithOneof_Title); ok { return x.Title } return "" } func (m *MsgWithOneof) GetSalary() int64 { if x, ok := m.GetUnion().(*MsgWithOneof_Salary); ok { return x.Salary } return 0 } func (m *MsgWithOneof) GetCountry() string { if x, ok := m.GetUnion().(*MsgWithOneof_Country); ok { return x.Country } return "" } func (m *MsgWithOneof) GetHomeAddress() string { if x, ok := m.GetUnion().(*MsgWithOneof_HomeAddress); ok { return x.HomeAddress } return "" } // XXX_OneofFuncs is for the internal use of the proto package. func (*MsgWithOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _MsgWithOneof_OneofMarshaler, _MsgWithOneof_OneofUnmarshaler, _MsgWithOneof_OneofSizer, []interface{}{ (*MsgWithOneof_Title)(nil), (*MsgWithOneof_Salary)(nil), (*MsgWithOneof_Country)(nil), (*MsgWithOneof_HomeAddress)(nil), } } func _MsgWithOneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*MsgWithOneof) // union switch x := m.Union.(type) { case *MsgWithOneof_Title: b.EncodeVarint(1<<3 | proto.WireBytes) b.EncodeStringBytes(x.Title) case *MsgWithOneof_Salary: b.EncodeVarint(2<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Salary)) case *MsgWithOneof_Country: b.EncodeVarint(3<<3 | proto.WireBytes) b.EncodeStringBytes(x.Country) case *MsgWithOneof_HomeAddress: b.EncodeVarint(4<<3 | proto.WireBytes) b.EncodeStringBytes(x.HomeAddress) case nil: default: return fmt.Errorf("MsgWithOneof.Union has unexpected type %T", x) } return nil } func _MsgWithOneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*MsgWithOneof) switch tag { case 1: // union.title if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &MsgWithOneof_Title{x} return true, err case 2: // union.salary if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &MsgWithOneof_Salary{int64(x)} return true, err case 3: // union.Country if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &MsgWithOneof_Country{x} return true, err case 4: // union.home_address if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &MsgWithOneof_HomeAddress{x} return true, err default: return false, nil } } func _MsgWithOneof_OneofSizer(msg proto.Message) (n int) { m := msg.(*MsgWithOneof) // union switch x := m.Union.(type) { case *MsgWithOneof_Title: n += proto.SizeVarint(1<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Title))) n += len(x.Title) case *MsgWithOneof_Salary: n += proto.SizeVarint(2<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Salary)) case *MsgWithOneof_Country: n += proto.SizeVarint(3<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Country))) n += len(x.Country) case *MsgWithOneof_HomeAddress: n += proto.SizeVarint(4<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.HomeAddress))) n += len(x.HomeAddress) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Real struct { Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Real) Reset() { *m = Real{} } func (m *Real) String() string { return proto.CompactTextString(m) } func (*Real) ProtoMessage() {} func (*Real) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} } var extRange_Real = []proto.ExtensionRange{ {100, 536870911}, } func (*Real) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Real } func (m *Real) GetValue() float64 { if m != nil && m.Value != nil { return *m.Value } return 0 } type Complex struct { Imaginary *float64 `protobuf:"fixed64,1,opt,name=imaginary" json:"imaginary,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Complex) Reset() { *m = Complex{} } func (m *Complex) String() string { return proto.CompactTextString(m) } func (*Complex) ProtoMessage() {} func (*Complex) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} } var extRange_Complex = []proto.ExtensionRange{ {100, 536870911}, } func (*Complex) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Complex } func (m *Complex) GetImaginary() float64 { if m != nil && m.Imaginary != nil { return *m.Imaginary } return 0 } var E_Complex_RealExtension = &proto.ExtensionDesc{ ExtendedType: (*Real)(nil), ExtensionType: (*Complex)(nil), Field: 123, Name: "jsonpb.Complex.real_extension", Tag: "bytes,123,opt,name=real_extension,json=realExtension", Filename: "test_objects.proto", } type KnownTypes struct { An *google_protobuf.Any `protobuf:"bytes,14,opt,name=an" json:"an,omitempty"` Dur *google_protobuf1.Duration `protobuf:"bytes,1,opt,name=dur" json:"dur,omitempty"` St *google_protobuf2.Struct `protobuf:"bytes,12,opt,name=st" json:"st,omitempty"` Ts *google_protobuf3.Timestamp `protobuf:"bytes,2,opt,name=ts" json:"ts,omitempty"` Lv *google_protobuf2.ListValue `protobuf:"bytes,15,opt,name=lv" json:"lv,omitempty"` Val *google_protobuf2.Value `protobuf:"bytes,16,opt,name=val" json:"val,omitempty"` Dbl *google_protobuf4.DoubleValue `protobuf:"bytes,3,opt,name=dbl" json:"dbl,omitempty"` Flt *google_protobuf4.FloatValue `protobuf:"bytes,4,opt,name=flt" json:"flt,omitempty"` I64 *google_protobuf4.Int64Value `protobuf:"bytes,5,opt,name=i64" json:"i64,omitempty"` U64 *google_protobuf4.UInt64Value `protobuf:"bytes,6,opt,name=u64" json:"u64,omitempty"` I32 *google_protobuf4.Int32Value `protobuf:"bytes,7,opt,name=i32" json:"i32,omitempty"` U32 *google_protobuf4.UInt32Value `protobuf:"bytes,8,opt,name=u32" json:"u32,omitempty"` Bool *google_protobuf4.BoolValue `protobuf:"bytes,9,opt,name=bool" json:"bool,omitempty"` Str *google_protobuf4.StringValue `protobuf:"bytes,10,opt,name=str" json:"str,omitempty"` Bytes *google_protobuf4.BytesValue `protobuf:"bytes,11,opt,name=bytes" json:"bytes,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *KnownTypes) Reset() { *m = KnownTypes{} } func (m *KnownTypes) String() string { return proto.CompactTextString(m) } func (*KnownTypes) ProtoMessage() {} func (*KnownTypes) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} } func (m *KnownTypes) GetAn() *google_protobuf.Any { if m != nil { return m.An } return nil } func (m *KnownTypes) GetDur() *google_protobuf1.Duration { if m != nil { return m.Dur } return nil } func (m *KnownTypes) GetSt() *google_protobuf2.Struct { if m != nil { return m.St } return nil } func (m *KnownTypes) GetTs() *google_protobuf3.Timestamp { if m != nil { return m.Ts } return nil } func (m *KnownTypes) GetLv() *google_protobuf2.ListValue { if m != nil { return m.Lv } return nil } func (m *KnownTypes) GetVal() *google_protobuf2.Value { if m != nil { return m.Val } return nil } func (m *KnownTypes) GetDbl() *google_protobuf4.DoubleValue { if m != nil { return m.Dbl } return nil } func (m *KnownTypes) GetFlt() *google_protobuf4.FloatValue { if m != nil { return m.Flt } return nil } func (m *KnownTypes) GetI64() *google_protobuf4.Int64Value { if m != nil { return m.I64 } return nil } func (m *KnownTypes) GetU64() *google_protobuf4.UInt64Value { if m != nil { return m.U64 } return nil } func (m *KnownTypes) GetI32() *google_protobuf4.Int32Value { if m != nil { return m.I32 } return nil } func (m *KnownTypes) GetU32() *google_protobuf4.UInt32Value { if m != nil { return m.U32 } return nil } func (m *KnownTypes) GetBool() *google_protobuf4.BoolValue { if m != nil { return m.Bool } return nil } func (m *KnownTypes) GetStr() *google_protobuf4.StringValue { if m != nil { return m.Str } return nil } func (m *KnownTypes) GetBytes() *google_protobuf4.BytesValue { if m != nil { return m.Bytes } return nil } var E_Name = &proto.ExtensionDesc{ ExtendedType: (*Real)(nil), ExtensionType: (*string)(nil), Field: 124, Name: "jsonpb.name", Tag: "bytes,124,opt,name=name", Filename: "test_objects.proto", } func init() { proto.RegisterType((*Simple)(nil), "jsonpb.Simple") proto.RegisterType((*NonFinites)(nil), "jsonpb.NonFinites") proto.RegisterType((*Repeats)(nil), "jsonpb.Repeats") proto.RegisterType((*Widget)(nil), "jsonpb.Widget") proto.RegisterType((*Maps)(nil), "jsonpb.Maps") proto.RegisterType((*MsgWithOneof)(nil), "jsonpb.MsgWithOneof") proto.RegisterType((*Real)(nil), "jsonpb.Real") proto.RegisterType((*Complex)(nil), "jsonpb.Complex") proto.RegisterType((*KnownTypes)(nil), "jsonpb.KnownTypes") proto.RegisterEnum("jsonpb.Widget_Color", Widget_Color_name, Widget_Color_value) proto.RegisterExtension(E_Complex_RealExtension) proto.RegisterExtension(E_Name) } func init() { proto.RegisterFile("test_objects.proto", fileDescriptor1) } var fileDescriptor1 = []byte{ // 1160 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x95, 0x41, 0x73, 0xdb, 0x44, 0x14, 0xc7, 0x23, 0xc9, 0x92, 0xed, 0x75, 0x92, 0x9a, 0x6d, 0xda, 0x2a, 0x26, 0x80, 0xc6, 0x94, 0x22, 0x0a, 0x75, 0x07, 0xc7, 0xe3, 0x61, 0x0a, 0x97, 0xa4, 0x71, 0x29, 0x43, 0x13, 0x98, 0x4d, 0x43, 0x8f, 0x1e, 0x39, 0x5a, 0xbb, 0x2a, 0xf2, 0xae, 0x67, 0x77, 0x95, 0xd4, 0x03, 0x87, 0x9c, 0x39, 0x32, 0x7c, 0x05, 0xf8, 0x08, 0x1c, 0xf8, 0x74, 0xcc, 0xdb, 0x95, 0xac, 0xc4, 0x8e, 0x4f, 0xf1, 0x7b, 0xef, 0xff, 0xfe, 0x59, 0xed, 0x6f, 0x77, 0x1f, 0xc2, 0x8a, 0x4a, 0x35, 0xe4, 0xa3, 0x77, 0xf4, 0x5c, 0xc9, 0xce, 0x4c, 0x70, 0xc5, 0xb1, 0xf7, 0x4e, 0x72, 0x36, 0x1b, 0xb5, 0x76, 0x27, 0x9c, 0x4f, 0x52, 0xfa, 0x54, 0x67, 0x47, 0xd9, 0xf8, 0x69, 0xc4, 0xe6, 0x46, 0xd2, 0xfa, 0x78, 0xb9, 0x14, 0x67, 0x22, 0x52, 0x09, 0x67, 0x79, 0x7d, 0x6f, 0xb9, 0x2e, 0x95, 0xc8, 0xce, 0x55, 0x5e, 0xfd, 0x64, 0xb9, 0xaa, 0x92, 0x29, 0x95, 0x2a, 0x9a, 0xce, 0xd6, 0xd9, 0x5f, 0x8a, 0x68, 0x36, 0xa3, 0x22, 0x5f, 0x61, 0xfb, 0x6f, 0x1b, 0x79, 0xa7, 0xc9, 0x74, 0x96, 0x52, 0x7c, 0x0f, 0x79, 0x7c, 0x38, 0xe2, 0x3c, 0xf5, 0xad, 0xc0, 0x0a, 0x6b, 0xc4, 0xe5, 0x87, 0x9c, 0xa7, 0xf8, 0x01, 0xaa, 0xf2, 0x61, 0xc2, 0xd4, 0x7e, 0xd7, 0xb7, 0x03, 0x2b, 0x74, 0x89, 0xc7, 0x7f, 0x80, 0x68, 0x51, 0xe8, 0xf7, 0x7c, 0x27, 0xb0, 0x42, 0xc7, 0x14, 0xfa, 0x3d, 0xbc, 0x8b, 0x6a, 0x7c, 0x98, 0x99, 0x96, 0x4a, 0x60, 0x85, 0x5b, 0xa4, 0xca, 0xcf, 0x74, 0x58, 0x96, 0xfa, 0x3d, 0xdf, 0x0d, 0xac, 0xb0, 0x92, 0x97, 0x8a, 0x2e, 0x69, 0xba, 0xbc, 0xc0, 0x0a, 0x3f, 0x20, 0x55, 0x7e, 0x7a, 0xad, 0x4b, 0x9a, 0xae, 0x6a, 0x60, 0x85, 0x38, 0x2f, 0xf5, 0x7b, 0x66, 0x11, 0xe3, 0x94, 0x47, 0xca, 0xaf, 0x05, 0x56, 0x68, 0x13, 0x8f, 0xbf, 0x80, 0xc8, 0xf4, 0xc4, 0x3c, 0x1b, 0xa5, 0xd4, 0xaf, 0x07, 0x56, 0x68, 0x91, 0x2a, 0x3f, 0xd2, 0x61, 0x6e, 0xa7, 0x44, 0xc2, 0x26, 0x3e, 0x0a, 0xac, 0xb0, 0x0e, 0x76, 0x3a, 0x34, 0x76, 0xa3, 0xb9, 0xa2, 0xd2, 0x6f, 0x04, 0x56, 0xb8, 0x49, 0x3c, 0x7e, 0x08, 0x51, 0xfb, 0x4f, 0x0b, 0xa1, 0x13, 0xce, 0x5e, 0x24, 0x2c, 0x51, 0x54, 0xe2, 0xbb, 0xc8, 0x1d, 0x0f, 0x59, 0xc4, 0xf4, 0x56, 0xd9, 0xa4, 0x32, 0x3e, 0x89, 0x18, 0x6c, 0xe0, 0x78, 0x38, 0x4b, 0xd8, 0x58, 0x6f, 0x94, 0x4d, 0xdc, 0xf1, 0xcf, 0x09, 0x1b, 0x9b, 0x34, 0x83, 0xb4, 0x93, 0xa7, 0x4f, 0x20, 0x7d, 0x17, 0xb9, 0xb1, 0xb6, 0xa8, 0xe8, 0xd5, 0x55, 0xe2, 0xdc, 0x22, 0x36, 0x16, 0xae, 0xce, 0xba, 0x71, 0x61, 0x11, 0x1b, 0x0b, 0x2f, 0x4f, 0x83, 0x45, 0xfb, 0x1f, 0x1b, 0x55, 0x09, 0x9d, 0xd1, 0x48, 0x49, 0x90, 0x88, 0x82, 0x9e, 0x03, 0xf4, 0x44, 0x41, 0x4f, 0x2c, 0xe8, 0x39, 0x40, 0x4f, 0x2c, 0xe8, 0x89, 0x05, 0x3d, 0x07, 0xe8, 0x89, 0x05, 0x3d, 0x51, 0xd2, 0x73, 0x80, 0x9e, 0x28, 0xe9, 0x89, 0x92, 0x9e, 0x03, 0xf4, 0x44, 0x49, 0x4f, 0x94, 0xf4, 0x1c, 0xa0, 0x27, 0x4e, 0xaf, 0x75, 0x2d, 0xe8, 0x39, 0x40, 0x4f, 0x94, 0xf4, 0xc4, 0x82, 0x9e, 0x03, 0xf4, 0xc4, 0x82, 0x9e, 0x28, 0xe9, 0x39, 0x40, 0x4f, 0x94, 0xf4, 0x44, 0x49, 0xcf, 0x01, 0x7a, 0xa2, 0xa4, 0x27, 0x16, 0xf4, 0x1c, 0xa0, 0x27, 0x0c, 0xbd, 0x7f, 0x6d, 0xe4, 0xbd, 0x49, 0xe2, 0x09, 0x55, 0xf8, 0x31, 0x72, 0xcf, 0x79, 0xca, 0x85, 0x26, 0xb7, 0xdd, 0xdd, 0xe9, 0x98, 0x2b, 0xda, 0x31, 0xe5, 0xce, 0x73, 0xa8, 0x11, 0x23, 0xc1, 0x4f, 0xc0, 0xcf, 0xa8, 0x61, 0xf3, 0xd6, 0xa9, 0x3d, 0xa1, 0xff, 0xe2, 0x47, 0xc8, 0x93, 0xfa, 0x2a, 0xe9, 0x53, 0xd5, 0xe8, 0x6e, 0x17, 0x6a, 0x73, 0xc1, 0x48, 0x5e, 0xc5, 0x5f, 0x98, 0x0d, 0xd1, 0x4a, 0x58, 0xe7, 0xaa, 0x12, 0x36, 0x28, 0x97, 0x56, 0x85, 0x01, 0xec, 0xef, 0x68, 0xcf, 0x3b, 0x85, 0x32, 0xe7, 0x4e, 0x8a, 0x3a, 0xfe, 0x0a, 0xd5, 0xc5, 0xb0, 0x10, 0xdf, 0xd3, 0xb6, 0x2b, 0xe2, 0x9a, 0xc8, 0x7f, 0xb5, 0x3f, 0x43, 0xae, 0x59, 0x74, 0x15, 0x39, 0x64, 0x70, 0xd4, 0xdc, 0xc0, 0x75, 0xe4, 0x7e, 0x4f, 0x06, 0x83, 0x93, 0xa6, 0x85, 0x6b, 0xa8, 0x72, 0xf8, 0xea, 0x6c, 0xd0, 0xb4, 0xdb, 0x7f, 0xd9, 0xa8, 0x72, 0x1c, 0xcd, 0x24, 0xfe, 0x16, 0x35, 0xa6, 0xe6, 0xb8, 0xc0, 0xde, 0xeb, 0x33, 0xd6, 0xe8, 0x7e, 0x58, 0xf8, 0x83, 0xa4, 0x73, 0xac, 0xcf, 0xcf, 0xa9, 0x12, 0x03, 0xa6, 0xc4, 0x9c, 0xd4, 0xa7, 0x45, 0x8c, 0x0f, 0xd0, 0xd6, 0x54, 0x9f, 0xcd, 0xe2, 0xab, 0x6d, 0xdd, 0xfe, 0xd1, 0xcd, 0x76, 0x38, 0xaf, 0xe6, 0xb3, 0x8d, 0x41, 0x63, 0x5a, 0x66, 0x5a, 0xdf, 0xa1, 0xed, 0x9b, 0xfe, 0xb8, 0x89, 0x9c, 0x5f, 0xe9, 0x5c, 0x63, 0x74, 0x08, 0xfc, 0xc4, 0x3b, 0xc8, 0xbd, 0x88, 0xd2, 0x8c, 0xea, 0xeb, 0x57, 0x27, 0x26, 0x78, 0x66, 0x7f, 0x63, 0xb5, 0x4e, 0x50, 0x73, 0xd9, 0xfe, 0x7a, 0x7f, 0xcd, 0xf4, 0x3f, 0xbc, 0xde, 0xbf, 0x0a, 0xa5, 0xf4, 0x6b, 0xff, 0x61, 0xa1, 0xcd, 0x63, 0x39, 0x79, 0x93, 0xa8, 0xb7, 0x3f, 0x31, 0xca, 0xc7, 0xf8, 0x3e, 0x72, 0x55, 0xa2, 0x52, 0xaa, 0xed, 0xea, 0x2f, 0x37, 0x88, 0x09, 0xb1, 0x8f, 0x3c, 0x19, 0xa5, 0x91, 0x98, 0x6b, 0x4f, 0xe7, 0xe5, 0x06, 0xc9, 0x63, 0xdc, 0x42, 0xd5, 0xe7, 0x3c, 0x83, 0x95, 0xe8, 0x67, 0x01, 0x7a, 0x8a, 0x04, 0xfe, 0x14, 0x6d, 0xbe, 0xe5, 0x53, 0x3a, 0x8c, 0xe2, 0x58, 0x50, 0x29, 0xf5, 0x0b, 0x01, 0x82, 0x06, 0x64, 0x0f, 0x4c, 0xf2, 0xb0, 0x8a, 0xdc, 0x8c, 0x25, 0x9c, 0xb5, 0x1f, 0xa1, 0x0a, 0xa1, 0x51, 0x5a, 0x7e, 0xbe, 0x65, 0xde, 0x08, 0x1d, 0x3c, 0xae, 0xd5, 0xe2, 0xe6, 0xd5, 0xd5, 0xd5, 0x95, 0xdd, 0xbe, 0x84, 0xff, 0x08, 0x5f, 0xf2, 0x1e, 0xef, 0xa1, 0x7a, 0x32, 0x8d, 0x26, 0x09, 0x83, 0x95, 0x19, 0x79, 0x99, 0x28, 0x5b, 0xba, 0x47, 0x68, 0x5b, 0xd0, 0x28, 0x1d, 0xd2, 0xf7, 0x8a, 0x32, 0x99, 0x70, 0x86, 0x37, 0xcb, 0x23, 0x15, 0xa5, 0xfe, 0x6f, 0x37, 0xcf, 0x64, 0x6e, 0x4f, 0xb6, 0xa0, 0x69, 0x50, 0xf4, 0xb4, 0xff, 0x73, 0x11, 0xfa, 0x91, 0xf1, 0x4b, 0xf6, 0x7a, 0x3e, 0xa3, 0x12, 0x3f, 0x44, 0x76, 0xc4, 0xfc, 0x6d, 0xdd, 0xba, 0xd3, 0x31, 0xf3, 0xa9, 0x53, 0xcc, 0xa7, 0xce, 0x01, 0x9b, 0x13, 0x3b, 0x62, 0xf8, 0x4b, 0xe4, 0xc4, 0x99, 0xb9, 0xa5, 0x8d, 0xee, 0xee, 0x8a, 0xec, 0x28, 0x9f, 0x92, 0x04, 0x54, 0xf8, 0x73, 0x64, 0x4b, 0xe5, 0x6f, 0x6a, 0xed, 0x83, 0x15, 0xed, 0xa9, 0x9e, 0x98, 0xc4, 0x96, 0x70, 0xfb, 0x6d, 0x25, 0x73, 0xbe, 0xad, 0x15, 0xe1, 0xeb, 0x62, 0x78, 0x12, 0x5b, 0x49, 0xd0, 0xa6, 0x17, 0xfe, 0x9d, 0x35, 0xda, 0x57, 0x89, 0x54, 0xbf, 0xc0, 0x0e, 0x13, 0x3b, 0xbd, 0xc0, 0x21, 0x72, 0x2e, 0xa2, 0xd4, 0x6f, 0x6a, 0xf1, 0xfd, 0x15, 0xb1, 0x11, 0x82, 0x04, 0x77, 0x90, 0x13, 0x8f, 0x52, 0xcd, 0xbc, 0xd1, 0xdd, 0x5b, 0xfd, 0x2e, 0xfd, 0xc8, 0xe5, 0xfa, 0x78, 0x94, 0xe2, 0x27, 0xc8, 0x19, 0xa7, 0x4a, 0x1f, 0x01, 0xb8, 0x70, 0xcb, 0x7a, 0xfd, 0x5c, 0xe6, 0xf2, 0x71, 0xaa, 0x40, 0x9e, 0xe4, 0xb3, 0xf5, 0x36, 0xb9, 0xbe, 0x42, 0xb9, 0x3c, 0xe9, 0xf7, 0x60, 0x35, 0x59, 0xbf, 0xa7, 0xa7, 0xca, 0x6d, 0xab, 0x39, 0xbb, 0xae, 0xcf, 0xfa, 0x3d, 0x6d, 0xbf, 0xdf, 0xd5, 0x43, 0x78, 0x8d, 0xfd, 0x7e, 0xb7, 0xb0, 0xdf, 0xef, 0x6a, 0xfb, 0xfd, 0xae, 0x9e, 0xcc, 0xeb, 0xec, 0x17, 0xfa, 0x4c, 0xeb, 0x2b, 0x7a, 0x84, 0xd5, 0xd7, 0x6c, 0x3a, 0xdc, 0x61, 0x23, 0xd7, 0x3a, 0xf0, 0x87, 0xd7, 0x08, 0xad, 0xf1, 0x37, 0x63, 0x21, 0xf7, 0x97, 0x4a, 0xe0, 0xaf, 0x91, 0x5b, 0x0e, 0xf7, 0xdb, 0x3e, 0x40, 0x8f, 0x0b, 0xd3, 0x60, 0x94, 0xcf, 0x02, 0x54, 0x61, 0xd1, 0x94, 0x2e, 0x1d, 0xfc, 0xdf, 0xf5, 0x0b, 0xa3, 0x2b, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff, 0xd5, 0x39, 0x32, 0x09, 0xf9, 0x09, 0x00, 0x00, } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto�����0000644�0610621�0607500�00000004407�13172163407�034250� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package jsonpb; message Simple3 { double dub = 1; } message SimpleSlice3 { repeated string slices = 1; } message SimpleMap3 { map<string,string> stringy = 1; } message SimpleNull3 { Simple3 simple = 1; } enum Numeral { UNKNOWN = 0; ARABIC = 1; ROMAN = 2; } message Mappy { map<int64, int32> nummy = 1; map<string, string> strry = 2; map<int32, Simple3> objjy = 3; map<int64, string> buggy = 4; map<bool, bool> booly = 5; map<string, Numeral> enumy = 6; map<int32, bool> s32booly = 7; map<int64, bool> s64booly = 8; map<uint32, bool> u32booly = 9; map<uint64, bool> u64booly = 10; } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go�����0000644�0610621�0607500�00000023634�13172163407�034115� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: more_test_objects.proto /* Package jsonpb is a generated protocol buffer package. It is generated from these files: more_test_objects.proto test_objects.proto It has these top-level messages: Simple3 SimpleSlice3 SimpleMap3 SimpleNull3 Mappy Simple NonFinites Repeats Widget Maps MsgWithOneof Real Complex KnownTypes */ package jsonpb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type Numeral int32 const ( Numeral_UNKNOWN Numeral = 0 Numeral_ARABIC Numeral = 1 Numeral_ROMAN Numeral = 2 ) var Numeral_name = map[int32]string{ 0: "UNKNOWN", 1: "ARABIC", 2: "ROMAN", } var Numeral_value = map[string]int32{ "UNKNOWN": 0, "ARABIC": 1, "ROMAN": 2, } func (x Numeral) String() string { return proto.EnumName(Numeral_name, int32(x)) } func (Numeral) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } type Simple3 struct { Dub float64 `protobuf:"fixed64,1,opt,name=dub" json:"dub,omitempty"` } func (m *Simple3) Reset() { *m = Simple3{} } func (m *Simple3) String() string { return proto.CompactTextString(m) } func (*Simple3) ProtoMessage() {} func (*Simple3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Simple3) GetDub() float64 { if m != nil { return m.Dub } return 0 } type SimpleSlice3 struct { Slices []string `protobuf:"bytes,1,rep,name=slices" json:"slices,omitempty"` } func (m *SimpleSlice3) Reset() { *m = SimpleSlice3{} } func (m *SimpleSlice3) String() string { return proto.CompactTextString(m) } func (*SimpleSlice3) ProtoMessage() {} func (*SimpleSlice3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *SimpleSlice3) GetSlices() []string { if m != nil { return m.Slices } return nil } type SimpleMap3 struct { Stringy map[string]string `protobuf:"bytes,1,rep,name=stringy" json:"stringy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` } func (m *SimpleMap3) Reset() { *m = SimpleMap3{} } func (m *SimpleMap3) String() string { return proto.CompactTextString(m) } func (*SimpleMap3) ProtoMessage() {} func (*SimpleMap3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *SimpleMap3) GetStringy() map[string]string { if m != nil { return m.Stringy } return nil } type SimpleNull3 struct { Simple *Simple3 `protobuf:"bytes,1,opt,name=simple" json:"simple,omitempty"` } func (m *SimpleNull3) Reset() { *m = SimpleNull3{} } func (m *SimpleNull3) String() string { return proto.CompactTextString(m) } func (*SimpleNull3) ProtoMessage() {} func (*SimpleNull3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *SimpleNull3) GetSimple() *Simple3 { if m != nil { return m.Simple } return nil } type Mappy struct { Nummy map[int64]int32 `protobuf:"bytes,1,rep,name=nummy" json:"nummy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` Strry map[string]string `protobuf:"bytes,2,rep,name=strry" json:"strry,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Objjy map[int32]*Simple3 `protobuf:"bytes,3,rep,name=objjy" json:"objjy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Buggy map[int64]string `protobuf:"bytes,4,rep,name=buggy" json:"buggy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Booly map[bool]bool `protobuf:"bytes,5,rep,name=booly" json:"booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` Enumy map[string]Numeral `protobuf:"bytes,6,rep,name=enumy" json:"enumy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=jsonpb.Numeral"` S32Booly map[int32]bool `protobuf:"bytes,7,rep,name=s32booly" json:"s32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` S64Booly map[int64]bool `protobuf:"bytes,8,rep,name=s64booly" json:"s64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` U32Booly map[uint32]bool `protobuf:"bytes,9,rep,name=u32booly" json:"u32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` U64Booly map[uint64]bool `protobuf:"bytes,10,rep,name=u64booly" json:"u64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` } func (m *Mappy) Reset() { *m = Mappy{} } func (m *Mappy) String() string { return proto.CompactTextString(m) } func (*Mappy) ProtoMessage() {} func (*Mappy) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *Mappy) GetNummy() map[int64]int32 { if m != nil { return m.Nummy } return nil } func (m *Mappy) GetStrry() map[string]string { if m != nil { return m.Strry } return nil } func (m *Mappy) GetObjjy() map[int32]*Simple3 { if m != nil { return m.Objjy } return nil } func (m *Mappy) GetBuggy() map[int64]string { if m != nil { return m.Buggy } return nil } func (m *Mappy) GetBooly() map[bool]bool { if m != nil { return m.Booly } return nil } func (m *Mappy) GetEnumy() map[string]Numeral { if m != nil { return m.Enumy } return nil } func (m *Mappy) GetS32Booly() map[int32]bool { if m != nil { return m.S32Booly } return nil } func (m *Mappy) GetS64Booly() map[int64]bool { if m != nil { return m.S64Booly } return nil } func (m *Mappy) GetU32Booly() map[uint32]bool { if m != nil { return m.U32Booly } return nil } func (m *Mappy) GetU64Booly() map[uint64]bool { if m != nil { return m.U64Booly } return nil } func init() { proto.RegisterType((*Simple3)(nil), "jsonpb.Simple3") proto.RegisterType((*SimpleSlice3)(nil), "jsonpb.SimpleSlice3") proto.RegisterType((*SimpleMap3)(nil), "jsonpb.SimpleMap3") proto.RegisterType((*SimpleNull3)(nil), "jsonpb.SimpleNull3") proto.RegisterType((*Mappy)(nil), "jsonpb.Mappy") proto.RegisterEnum("jsonpb.Numeral", Numeral_name, Numeral_value) } func init() { proto.RegisterFile("more_test_objects.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 526 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdd, 0x6b, 0xdb, 0x3c, 0x14, 0x87, 0x5f, 0x27, 0xf5, 0xd7, 0x49, 0xfb, 0x2e, 0x88, 0xb1, 0x99, 0xf4, 0x62, 0xc5, 0xb0, 0xad, 0x0c, 0xe6, 0x8b, 0x78, 0x74, 0x5d, 0x77, 0x95, 0x8e, 0x5e, 0x94, 0x11, 0x07, 0x1c, 0xc2, 0x2e, 0x4b, 0xdc, 0x99, 0x90, 0xcc, 0x5f, 0xd8, 0xd6, 0xc0, 0xd7, 0xfb, 0xbb, 0x07, 0xe3, 0x48, 0x72, 0x2d, 0x07, 0x85, 0x6c, 0x77, 0x52, 0x7e, 0xcf, 0xe3, 0x73, 0x24, 0x1d, 0x02, 0x2f, 0xd3, 0xbc, 0x8c, 0x1f, 0xea, 0xb8, 0xaa, 0x1f, 0xf2, 0x68, 0x17, 0x3f, 0xd6, 0x95, 0x57, 0x94, 0x79, 0x9d, 0x13, 0x63, 0x57, 0xe5, 0x59, 0x11, 0xb9, 0xe7, 0x60, 0x2e, 0xb7, 0x69, 0x91, 0xc4, 0x3e, 0x19, 0xc3, 0xf0, 0x3b, 0x8d, 0x1c, 0xed, 0x42, 0xbb, 0xd4, 0x42, 0x5c, 0xba, 0x6f, 0xe0, 0x94, 0x87, 0xcb, 0x64, 0xfb, 0x18, 0xfb, 0xe4, 0x05, 0x18, 0x15, 0xae, 0x2a, 0x47, 0xbb, 0x18, 0x5e, 0xda, 0xa1, 0xd8, 0xb9, 0xbf, 0x34, 0x00, 0x0e, 0xce, 0xd7, 0x85, 0x4f, 0x3e, 0x81, 0x59, 0xd5, 0xe5, 0x36, 0xdb, 0x34, 0x8c, 0x1b, 0x4d, 0x5f, 0x79, 0xbc, 0x9a, 0xd7, 0x41, 0xde, 0x92, 0x13, 0x77, 0x59, 0x5d, 0x36, 0x61, 0xcb, 0x4f, 0x6e, 0xe0, 0x54, 0x0e, 0xb0, 0xa7, 0x1f, 0x71, 0xc3, 0x7a, 0xb2, 0x43, 0x5c, 0x92, 0xe7, 0xa0, 0xff, 0x5c, 0x27, 0x34, 0x76, 0x06, 0xec, 0x37, 0xbe, 0xb9, 0x19, 0x5c, 0x6b, 0xee, 0x15, 0x8c, 0xf8, 0xf7, 0x03, 0x9a, 0x24, 0x3e, 0x79, 0x0b, 0x46, 0xc5, 0xb6, 0xcc, 0x1e, 0x4d, 0x9f, 0xf5, 0x9b, 0xf0, 0x43, 0x11, 0xbb, 0xbf, 0x2d, 0xd0, 0xe7, 0xeb, 0xa2, 0x68, 0x88, 0x07, 0x7a, 0x46, 0xd3, 0xb4, 0x6d, 0xdb, 0x69, 0x0d, 0x96, 0x7a, 0x01, 0x46, 0xbc, 0x5f, 0x8e, 0x21, 0x5f, 0xd5, 0x65, 0xd9, 0x38, 0x03, 0x15, 0xbf, 0xc4, 0x48, 0xf0, 0x0c, 0x43, 0x3e, 0x8f, 0x76, 0xbb, 0xc6, 0x19, 0xaa, 0xf8, 0x05, 0x46, 0x82, 0x67, 0x18, 0xf2, 0x11, 0xdd, 0x6c, 0x1a, 0xe7, 0x44, 0xc5, 0xdf, 0x62, 0x24, 0x78, 0x86, 0x31, 0x3e, 0xcf, 0x93, 0xc6, 0xd1, 0x95, 0x3c, 0x46, 0x2d, 0x8f, 0x6b, 0xe4, 0xe3, 0x8c, 0xa6, 0x8d, 0x63, 0xa8, 0xf8, 0x3b, 0x8c, 0x04, 0xcf, 0x30, 0xf2, 0x11, 0xac, 0xca, 0x9f, 0xf2, 0x12, 0x26, 0x53, 0xce, 0xf7, 0x8e, 0x2c, 0x52, 0x6e, 0x3d, 0xc1, 0x4c, 0xbc, 0xfa, 0xc0, 0x45, 0x4b, 0x29, 0x8a, 0xb4, 0x15, 0xc5, 0x16, 0x45, 0xda, 0x56, 0xb4, 0x55, 0xe2, 0xaa, 0x5f, 0x91, 0x4a, 0x15, 0x69, 0x5b, 0x11, 0x94, 0x62, 0xbf, 0x62, 0x0b, 0x4f, 0xae, 0x01, 0xba, 0x87, 0x96, 0xe7, 0x6f, 0xa8, 0x98, 0x3f, 0x5d, 0x9a, 0x3f, 0x34, 0xbb, 0x27, 0xff, 0x97, 0xc9, 0x9d, 0xdc, 0x03, 0x74, 0x8f, 0x2f, 0x9b, 0x3a, 0x37, 0x5f, 0xcb, 0xa6, 0x62, 0x92, 0xfb, 0x4d, 0x74, 0x73, 0x71, 0xac, 0x7d, 0x7b, 0xdf, 0x7c, 0xba, 0x10, 0xd9, 0xb4, 0x14, 0xa6, 0xb5, 0xd7, 0x7e, 0x37, 0x2b, 0x8a, 0x83, 0xf7, 0xda, 0xff, 0xbf, 0x6b, 0x3f, 0xa0, 0x69, 0x5c, 0xae, 0x13, 0xf9, 0x53, 0x9f, 0xe1, 0xac, 0x37, 0x43, 0x8a, 0xcb, 0x38, 0xdc, 0x07, 0xca, 0xf2, 0xab, 0x1e, 0x3b, 0xfe, 0xbe, 0xbc, 0x3a, 0x54, 0xf9, 0xec, 0x6f, 0xe4, 0x43, 0x95, 0x4f, 0x8e, 0xc8, 0xef, 0xde, 0x83, 0x29, 0x6e, 0x82, 0x8c, 0xc0, 0x5c, 0x05, 0x5f, 0x83, 0xc5, 0xb7, 0x60, 0xfc, 0x1f, 0x01, 0x30, 0x66, 0xe1, 0xec, 0xf6, 0xfe, 0xcb, 0x58, 0x23, 0x36, 0xe8, 0xe1, 0x62, 0x3e, 0x0b, 0xc6, 0x83, 0xc8, 0x60, 0x7f, 0xe0, 0xfe, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x34, 0xaf, 0xdb, 0x05, 0x00, 0x00, } ����������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/Makefile��������������������0000644�0610621�0607500�00000003771�13172163407�031114� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2015 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. regenerate: protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any,Mgoogle/protobuf/duration.proto=github.com/golang/protobuf/ptypes/duration,Mgoogle/protobuf/struct.proto=github.com/golang/protobuf/ptypes/struct,Mgoogle/protobuf/timestamp.proto=github.com/golang/protobuf/ptypes/timestamp,Mgoogle/protobuf/wrappers.proto=github.com/golang/protobuf/ptypes/wrappers:. *.proto �������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/jsonpb_test.go��������������������������������0000644�0610621�0607500�00000103537�13172163407�026561� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package jsonpb import ( "bytes" "encoding/json" "io" "math" "reflect" "strings" "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" "github.com/golang/protobuf/ptypes" anypb "github.com/golang/protobuf/ptypes/any" durpb "github.com/golang/protobuf/ptypes/duration" stpb "github.com/golang/protobuf/ptypes/struct" tspb "github.com/golang/protobuf/ptypes/timestamp" wpb "github.com/golang/protobuf/ptypes/wrappers" ) var ( marshaler = Marshaler{} marshalerAllOptions = Marshaler{ Indent: " ", } simpleObject = &pb.Simple{ OInt32: proto.Int32(-32), OInt64: proto.Int64(-6400000000), OUint32: proto.Uint32(32), OUint64: proto.Uint64(6400000000), OSint32: proto.Int32(-13), OSint64: proto.Int64(-2600000000), OFloat: proto.Float32(3.14), ODouble: proto.Float64(6.02214179e23), OBool: proto.Bool(true), OString: proto.String("hello \"there\""), OBytes: []byte("beep boop"), } simpleObjectJSON = `{` + `"oBool":true,` + `"oInt32":-32,` + `"oInt64":"-6400000000",` + `"oUint32":32,` + `"oUint64":"6400000000",` + `"oSint32":-13,` + `"oSint64":"-2600000000",` + `"oFloat":3.14,` + `"oDouble":6.02214179e+23,` + `"oString":"hello \"there\"",` + `"oBytes":"YmVlcCBib29w"` + `}` simpleObjectPrettyJSON = `{ "oBool": true, "oInt32": -32, "oInt64": "-6400000000", "oUint32": 32, "oUint64": "6400000000", "oSint32": -13, "oSint64": "-2600000000", "oFloat": 3.14, "oDouble": 6.02214179e+23, "oString": "hello \"there\"", "oBytes": "YmVlcCBib29w" }` repeatsObject = &pb.Repeats{ RBool: []bool{true, false, true}, RInt32: []int32{-3, -4, -5}, RInt64: []int64{-123456789, -987654321}, RUint32: []uint32{1, 2, 3}, RUint64: []uint64{6789012345, 3456789012}, RSint32: []int32{-1, -2, -3}, RSint64: []int64{-6789012345, -3456789012}, RFloat: []float32{3.14, 6.28}, RDouble: []float64{299792458 * 1e20, 6.62606957e-34}, RString: []string{"happy", "days"}, RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")}, } repeatsObjectJSON = `{` + `"rBool":[true,false,true],` + `"rInt32":[-3,-4,-5],` + `"rInt64":["-123456789","-987654321"],` + `"rUint32":[1,2,3],` + `"rUint64":["6789012345","3456789012"],` + `"rSint32":[-1,-2,-3],` + `"rSint64":["-6789012345","-3456789012"],` + `"rFloat":[3.14,6.28],` + `"rDouble":[2.99792458e+28,6.62606957e-34],` + `"rString":["happy","days"],` + `"rBytes":["c2tpdHRsZXM=","bSZtJ3M="]` + `}` repeatsObjectPrettyJSON = `{ "rBool": [ true, false, true ], "rInt32": [ -3, -4, -5 ], "rInt64": [ "-123456789", "-987654321" ], "rUint32": [ 1, 2, 3 ], "rUint64": [ "6789012345", "3456789012" ], "rSint32": [ -1, -2, -3 ], "rSint64": [ "-6789012345", "-3456789012" ], "rFloat": [ 3.14, 6.28 ], "rDouble": [ 2.99792458e+28, 6.62606957e-34 ], "rString": [ "happy", "days" ], "rBytes": [ "c2tpdHRsZXM=", "bSZtJ3M=" ] }` innerSimple = &pb.Simple{OInt32: proto.Int32(-32)} innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)} innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}} innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}} complexObject = &pb.Widget{ Color: pb.Widget_GREEN.Enum(), RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE}, Simple: innerSimple, RSimple: []*pb.Simple{innerSimple, innerSimple2}, Repeats: innerRepeats, RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2}, } complexObjectJSON = `{"color":"GREEN",` + `"rColor":["RED","GREEN","BLUE"],` + `"simple":{"oInt32":-32},` + `"rSimple":[{"oInt32":-32},{"oInt64":"25"}],` + `"repeats":{"rString":["roses","red"]},` + `"rRepeats":[{"rString":["roses","red"]},{"rString":["violets","blue"]}]` + `}` complexObjectPrettyJSON = `{ "color": "GREEN", "rColor": [ "RED", "GREEN", "BLUE" ], "simple": { "oInt32": -32 }, "rSimple": [ { "oInt32": -32 }, { "oInt64": "25" } ], "repeats": { "rString": [ "roses", "red" ] }, "rRepeats": [ { "rString": [ "roses", "red" ] }, { "rString": [ "violets", "blue" ] } ] }` colorPrettyJSON = `{ "color": 2 }` colorListPrettyJSON = `{ "color": 1000, "rColor": [ "RED" ] }` nummyPrettyJSON = `{ "nummy": { "1": 2, "3": 4 } }` objjyPrettyJSON = `{ "objjy": { "1": { "dub": 1 } } }` realNumber = &pb.Real{Value: proto.Float64(3.14159265359)} realNumberName = "Pi" complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)} realNumberJSON = `{` + `"value":3.14159265359,` + `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` + `"[jsonpb.name]":"Pi"` + `}` anySimple = &pb.KnownTypes{ An: &anypb.Any{ TypeUrl: "something.example.com/jsonpb.Simple", Value: []byte{ // &pb.Simple{OBool:true} 1 << 3, 1, }, }, } anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}` anySimplePrettyJSON = `{ "an": { "@type": "something.example.com/jsonpb.Simple", "oBool": true } }` anyWellKnown = &pb.KnownTypes{ An: &anypb.Any{ TypeUrl: "type.googleapis.com/google.protobuf.Duration", Value: []byte{ // &durpb.Duration{Seconds: 1, Nanos: 212000000 } 1 << 3, 1, // seconds 2 << 3, 0x80, 0xba, 0x8b, 0x65, // nanos }, }, } anyWellKnownJSON = `{"an":{"@type":"type.googleapis.com/google.protobuf.Duration","value":"1.212s"}}` anyWellKnownPrettyJSON = `{ "an": { "@type": "type.googleapis.com/google.protobuf.Duration", "value": "1.212s" } }` nonFinites = &pb.NonFinites{ FNan: proto.Float32(float32(math.NaN())), FPinf: proto.Float32(float32(math.Inf(1))), FNinf: proto.Float32(float32(math.Inf(-1))), DNan: proto.Float64(float64(math.NaN())), DPinf: proto.Float64(float64(math.Inf(1))), DNinf: proto.Float64(float64(math.Inf(-1))), } nonFinitesJSON = `{` + `"fNan":"NaN",` + `"fPinf":"Infinity",` + `"fNinf":"-Infinity",` + `"dNan":"NaN",` + `"dPinf":"Infinity",` + `"dNinf":"-Infinity"` + `}` ) func init() { if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil { panic(err) } if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil { panic(err) } } var marshalingTests = []struct { desc string marshaler Marshaler pb proto.Message json string }{ {"simple flat object", marshaler, simpleObject, simpleObjectJSON}, {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON}, {"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON}, {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON}, {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON}, {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON}, {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON}, {"enum-string flat object", Marshaler{}, &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`}, {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "}, &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON}, {"unknown enum value object", marshalerAllOptions, &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON}, {"repeated proto3 enum", Marshaler{}, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}, `{"rFunny":["PUNS","SLAPSTICK"]}`}, {"repeated proto3 enum as int", Marshaler{EnumsAsInts: true}, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}, `{"rFunny":[1,2]}`}, {"empty value", marshaler, &pb.Simple3{}, `{}`}, {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`}, {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`}, {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`}, {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`}, {"map<int64, int32>", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`}, {"map<int64, int32>", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON}, {"map<string, string>", marshaler, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}, `{"strry":{"\"one\"":"two","three":"four"}}`}, {"map<int32, Object>", marshaler, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`}, {"map<int32, Object>", marshalerAllOptions, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, objjyPrettyJSON}, {"map<int64, string>", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}}, `{"buggy":{"1234":"yup"}}`}, {"map<bool, bool>", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`}, // TODO: This is broken. //{"map<string, enum>", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`}, {"map<string, enum as int>", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`}, {"map<int32, bool>", marshaler, &pb.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`}, {"map<int64, bool>", marshaler, &pb.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`}, {"map<uint32, bool>", marshaler, &pb.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`}, {"map<uint64, bool>", marshaler, &pb.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`}, {"proto2 map<int64, string>", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}}, `{"mInt64Str":{"213":"cat"}}`}, {"proto2 map<bool, Object>", marshaler, &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: {OInt32: proto.Int32(1)}}}, `{"mBoolSimple":{"true":{"oInt32":1}}}`}, {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`}, {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`}, {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)}, `{"o_int32":4}`}, {"proto2 extension", marshaler, realNumber, realNumberJSON}, {"Any with message", marshaler, anySimple, anySimpleJSON}, {"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON}, {"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON}, {"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON}, {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}, `{"dur":"3.000s"}`}, {"Struct", marshaler, &pb.KnownTypes{St: &stpb.Struct{ Fields: map[string]*stpb.Value{ "one": {Kind: &stpb.Value_StringValue{"loneliest number"}}, "two": {Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}, }, }}, `{"st":{"one":"loneliest number","two":null}}`}, {"empty ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{}}, `{"lv":[]}`}, {"basic ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{ {Kind: &stpb.Value_StringValue{"x"}}, {Kind: &stpb.Value_NullValue{}}, {Kind: &stpb.Value_NumberValue{3}}, {Kind: &stpb.Value_BoolValue{true}}, }}}, `{"lv":["x",null,3,true]}`}, {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`}, {"number Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}, `{"val":1}`}, {"null Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}, `{"val":null}`}, {"string number value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}, `{"val":"9223372036854775807"}`}, {"list of lists Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{ Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{ {Kind: &stpb.Value_StringValue{"x"}}, {Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{ {Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}}, }}}, {Kind: &stpb.Value_StringValue{"z"}}, }, }}}, }, }}, }}, `{"val":["x",[["y"],"z"]]}`}, {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`}, {"FloatValue", marshaler, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`}, {"Int64Value", marshaler, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`}, {"UInt64Value", marshaler, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`}, {"Int32Value", marshaler, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`}, {"UInt32Value", marshaler, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`}, {"BoolValue", marshaler, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`}, {"StringValue", marshaler, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`}, {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`}, } func TestMarshaling(t *testing.T) { for _, tt := range marshalingTests { json, err := tt.marshaler.MarshalToString(tt.pb) if err != nil { t.Errorf("%s: marshaling error: %v", tt.desc, err) } else if tt.json != json { t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json) } } } func TestMarshalJSONPBMarshaler(t *testing.T) { rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` msg := dynamicMessage{rawJson: rawJson} str, err := new(Marshaler).MarshalToString(&msg) if err != nil { t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err) } if str != rawJson { t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson) } } func TestMarshalAnyJSONPBMarshaler(t *testing.T) { msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`} a, err := ptypes.MarshalAny(&msg) if err != nil { t.Errorf("an unexpected error occurred when marshalling to Any: %v", err) } str, err := new(Marshaler).MarshalToString(a) if err != nil { t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err) } // after custom marshaling, it's round-tripped through JSON decoding/encoding already, // so the keys are sorted, whitespace is compacted, and "@type" key has been added expected := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}` if str != expected { t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected) } } var unmarshalingTests = []struct { desc string unmarshaler Unmarshaler json string pb proto.Message }{ {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject}, {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject}, {"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject}, {"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject}, {"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject}, {"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject}, {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)}, {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"unknown enum value object", Unmarshaler{}, "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}", &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}}, {"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}}, {"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}}, {"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}}, {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}}, {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}}, {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}}, {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}}, {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}}, {"map<int64, int32>", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}}, {"map<string, string>", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}}, {"map<int32, Object>", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}}, {"proto2 extension", Unmarshaler{}, realNumberJSON, realNumber}, {"Any with message", Unmarshaler{}, anySimpleJSON, anySimple}, {"Any with message and indent", Unmarshaler{}, anySimplePrettyJSON, anySimple}, {"Any with WKT", Unmarshaler{}, anyWellKnownJSON, anyWellKnown}, {"Any with WKT and indent", Unmarshaler{}, anyWellKnownPrettyJSON, anyWellKnown}, // TODO: This is broken. //{"map<string, enum>", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, {"map<string, enum as int>", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}}, {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}}, {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}}, {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}}, {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}}, {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}}, {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb.KnownTypes{Dur: nil}}, {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}}, {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}}, {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}}, {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb.KnownTypes{Ts: nil}}, {"null Struct", Unmarshaler{}, `{"st": null}`, &pb.KnownTypes{St: nil}}, {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb.KnownTypes{St: &stpb.Struct{}}}, {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{ "a": {Kind: &stpb.Value_StringValue{"x"}}, "b": {Kind: &stpb.Value_NullValue{}}, "c": {Kind: &stpb.Value_NumberValue{3}}, "d": {Kind: &stpb.Value_BoolValue{true}}, }}}}, {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{ "a": {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{ "b": {Kind: &stpb.Value_NumberValue{1}}, "c": {Kind: &stpb.Value_ListValue{&stpb.ListValue{Values: []*stpb.Value{ {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{"d": {Kind: &stpb.Value_BoolValue{true}}}}}}, {Kind: &stpb.Value_StringValue{"f"}}, }}}}, }}}}, }}}}, {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb.KnownTypes{Lv: nil}}, {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb.KnownTypes{Lv: &stpb.ListValue{}}}, {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{ {Kind: &stpb.Value_StringValue{"x"}}, {Kind: &stpb.Value_NullValue{}}, {Kind: &stpb.Value_NumberValue{3}}, {Kind: &stpb.Value_BoolValue{true}}, }}}}, {"number Value", Unmarshaler{}, `{"val":1}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}}, {"null Value", Unmarshaler{}, `{"val":null}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}}, {"bool Value", Unmarshaler{}, `{"val":true}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_BoolValue{true}}}}, {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"x"}}}}, {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}}, {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb.KnownTypes{Val: &stpb.Value{ Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{ {Kind: &stpb.Value_StringValue{"x"}}, {Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{ {Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}}, }}}, {Kind: &stpb.Value_StringValue{"z"}}, }, }}}, }, }}}}}, {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}}, {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}}, {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}}, {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}}, {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}}, {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}}, {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}}, {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}}, {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}}, // Ensure that `null` as a value ends up with a nil pointer instead of a [type]Value struct. {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: nil}}, {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb.KnownTypes{Flt: nil}}, {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb.KnownTypes{I64: nil}}, {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb.KnownTypes{U64: nil}}, {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb.KnownTypes{I32: nil}}, {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb.KnownTypes{U32: nil}}, {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb.KnownTypes{Bool: nil}}, {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb.KnownTypes{Str: nil}}, {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb.KnownTypes{Bytes: nil}}, } func TestUnmarshaling(t *testing.T) { for _, tt := range unmarshalingTests { // Make a new instance of the type of our expected object. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p) if err != nil { t.Errorf("%s: %v", tt.desc, err) continue } // For easier diffs, compare text strings of the protos. exp := proto.MarshalTextString(tt.pb) act := proto.MarshalTextString(p) if string(exp) != string(act) { t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) } } } func TestUnmarshalNullArray(t *testing.T) { var repeats pb.Repeats if err := UnmarshalString(`{"rBool":null}`, &repeats); err != nil { t.Fatal(err) } if !reflect.DeepEqual(repeats, pb.Repeats{}) { t.Errorf("got non-nil fields in [%#v]", repeats) } } func TestUnmarshalNullObject(t *testing.T) { var maps pb.Maps if err := UnmarshalString(`{"mInt64Str":null}`, &maps); err != nil { t.Fatal(err) } if !reflect.DeepEqual(maps, pb.Maps{}) { t.Errorf("got non-nil fields in [%#v]", maps) } } func TestUnmarshalNext(t *testing.T) { // We only need to check against a few, not all of them. tests := unmarshalingTests[:5] // Create a buffer with many concatenated JSON objects. var b bytes.Buffer for _, tt := range tests { b.WriteString(tt.json) } dec := json.NewDecoder(&b) for _, tt := range tests { // Make a new instance of the type of our expected object. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) err := tt.unmarshaler.UnmarshalNext(dec, p) if err != nil { t.Errorf("%s: %v", tt.desc, err) continue } // For easier diffs, compare text strings of the protos. exp := proto.MarshalTextString(tt.pb) act := proto.MarshalTextString(p) if string(exp) != string(act) { t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) } } p := &pb.Simple{} err := new(Unmarshaler).UnmarshalNext(dec, p) if err != io.EOF { t.Errorf("eof: got %v, expected io.EOF", err) } } var unmarshalingShouldError = []struct { desc string in string pb proto.Message }{ {"a value", "666", new(pb.Simple)}, {"gibberish", "{adskja123;l23=-=", new(pb.Simple)}, {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)}, {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)}, } func TestUnmarshalingBadInput(t *testing.T) { for _, tt := range unmarshalingShouldError { err := UnmarshalString(tt.in, tt.pb) if err == nil { t.Errorf("an error was expected when parsing %q instead of an object", tt.desc) } } } type funcResolver func(turl string) (proto.Message, error) func (fn funcResolver) Resolve(turl string) (proto.Message, error) { return fn(turl) } func TestAnyWithCustomResolver(t *testing.T) { var resolvedTypeUrls []string resolver := funcResolver(func(turl string) (proto.Message, error) { resolvedTypeUrls = append(resolvedTypeUrls, turl) return new(pb.Simple), nil }) msg := &pb.Simple{ OBytes: []byte{1, 2, 3, 4}, OBool: proto.Bool(true), OString: proto.String("foobar"), OInt64: proto.Int64(1020304), } msgBytes, err := proto.Marshal(msg) if err != nil { t.Errorf("an unexpected error occurred when marshaling message: %v", err) } // make an Any with a type URL that won't resolve w/out custom resolver any := &anypb.Any{ TypeUrl: "https://foobar.com/some.random.MessageKind", Value: msgBytes, } m := Marshaler{AnyResolver: resolver} js, err := m.MarshalToString(any) if err != nil { t.Errorf("an unexpected error occurred when marshaling any to JSON: %v", err) } if len(resolvedTypeUrls) != 1 { t.Errorf("custom resolver was not invoked during marshaling") } else if resolvedTypeUrls[0] != "https://foobar.com/some.random.MessageKind" { t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[0], "https://foobar.com/some.random.MessageKind") } wanted := `{"@type":"https://foobar.com/some.random.MessageKind","oBool":true,"oInt64":"1020304","oString":"foobar","oBytes":"AQIDBA=="}` if js != wanted { t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", js, wanted) } u := Unmarshaler{AnyResolver: resolver} roundTrip := &anypb.Any{} err = u.Unmarshal(bytes.NewReader([]byte(js)), roundTrip) if err != nil { t.Errorf("an unexpected error occurred when unmarshaling any from JSON: %v", err) } if len(resolvedTypeUrls) != 2 { t.Errorf("custom resolver was not invoked during marshaling") } else if resolvedTypeUrls[1] != "https://foobar.com/some.random.MessageKind" { t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[1], "https://foobar.com/some.random.MessageKind") } if !proto.Equal(any, roundTrip) { t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", roundTrip, any) } } func TestUnmarshalJSONPBUnmarshaler(t *testing.T) { rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` var msg dynamicMessage if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil { t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) } if msg.rawJson != rawJson { t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson) } } func TestUnmarshalNullWithJSONPBUnmarshaler(t *testing.T) { rawJson := `{"stringField":null}` var ptrFieldMsg ptrFieldMessage if err := Unmarshal(strings.NewReader(rawJson), &ptrFieldMsg); err != nil { t.Errorf("unmarshal error: %v", err) } want := ptrFieldMessage{StringField: &stringField{IsSet: true, StringValue: "null"}} if !proto.Equal(&ptrFieldMsg, &want) { t.Errorf("unmarshal result StringField: got %v, want %v", ptrFieldMsg, want) } } func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) { rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }` var got anypb.Any if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil { t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) } dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`} var want anypb.Any if b, err := proto.Marshal(dm); err != nil { t.Errorf("an unexpected error occurred when marshaling message: %v", err) } else { want.TypeUrl = "blah.com/" + dynamicMessageName want.Value = b } if !proto.Equal(&got, &want) { t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", got, want) } } const ( dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage" ) func init() { // we register the custom type below so that we can use it in Any types proto.RegisterType((*dynamicMessage)(nil), dynamicMessageName) } type ptrFieldMessage struct { StringField *stringField `protobuf:"bytes,1,opt,name=stringField"` } func (m *ptrFieldMessage) Reset() { } func (m *ptrFieldMessage) String() string { return m.StringField.StringValue } func (m *ptrFieldMessage) ProtoMessage() { } type stringField struct { IsSet bool `protobuf:"varint,1,opt,name=isSet"` StringValue string `protobuf:"bytes,2,opt,name=stringValue"` } func (s *stringField) Reset() { } func (s *stringField) String() string { return s.StringValue } func (s *stringField) ProtoMessage() { } func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { s.IsSet = true s.StringValue = string(js) return nil } // dynamicMessage implements protobuf.Message but is not a normal generated message type. // It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support. type dynamicMessage struct { rawJson string `protobuf:"bytes,1,opt,name=rawJson"` } func (m *dynamicMessage) Reset() { m.rawJson = "{}" } func (m *dynamicMessage) String() string { return m.rawJson } func (m *dynamicMessage) ProtoMessage() { } func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) { return []byte(m.rawJson), nil } func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { m.rawJson = string(js) return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/jsonpb/jsonpb.go�������������������������������������0000644�0610621�0607500�00000075324�13172163407�025524� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON. It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json. This package produces a different output than the standard "encoding/json" package, which does not operate correctly on protocol buffers. */ package jsonpb import ( "bytes" "encoding/json" "errors" "fmt" "io" "math" "reflect" "sort" "strconv" "strings" "time" "github.com/golang/protobuf/proto" stpb "github.com/golang/protobuf/ptypes/struct" ) // Marshaler is a configurable object for converting between // protocol buffer objects and a JSON representation for them. type Marshaler struct { // Whether to render enum values as integers, as opposed to string values. EnumsAsInts bool // Whether to render fields with zero values. EmitDefaults bool // A string to indent each level by. The presence of this field will // also cause a space to appear between the field separator and // value, and for newlines to be appear between fields and array // elements. Indent string // Whether to use the original (.proto) name for fields. OrigName bool // A custom URL resolver to use when marshaling Any messages to JSON. // If unset, the default resolution strategy is to extract the // fully-qualified type name from the type URL and pass that to // proto.MessageType(string). AnyResolver AnyResolver } // AnyResolver takes a type URL, present in an Any message, and resolves it into // an instance of the associated message. type AnyResolver interface { Resolve(typeUrl string) (proto.Message, error) } func defaultResolveAny(typeUrl string) (proto.Message, error) { // Only the part of typeUrl after the last slash is relevant. mname := typeUrl if slash := strings.LastIndex(mname, "/"); slash >= 0 { mname = mname[slash+1:] } mt := proto.MessageType(mname) if mt == nil { return nil, fmt.Errorf("unknown message type %q", mname) } return reflect.New(mt.Elem()).Interface().(proto.Message), nil } // JSONPBMarshaler is implemented by protobuf messages that customize the // way they are marshaled to JSON. Messages that implement this should // also implement JSONPBUnmarshaler so that the custom format can be // parsed. type JSONPBMarshaler interface { MarshalJSONPB(*Marshaler) ([]byte, error) } // JSONPBUnmarshaler is implemented by protobuf messages that customize // the way they are unmarshaled from JSON. Messages that implement this // should also implement JSONPBMarshaler so that the custom format can be // produced. type JSONPBUnmarshaler interface { UnmarshalJSONPB(*Unmarshaler, []byte) error } // Marshal marshals a protocol buffer into JSON. func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error { writer := &errWriter{writer: out} return m.marshalObject(writer, pb, "", "") } // MarshalToString converts a protocol buffer object to JSON string. func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) { var buf bytes.Buffer if err := m.Marshal(&buf, pb); err != nil { return "", err } return buf.String(), nil } type int32Slice []int32 var nonFinite = map[string]float64{ `"NaN"`: math.NaN(), `"Infinity"`: math.Inf(1), `"-Infinity"`: math.Inf(-1), } // For sorting extensions ids to ensure stable output. func (s int32Slice) Len() int { return len(s) } func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } type wkt interface { XXX_WellKnownType() string } // marshalObject writes a struct to the Writer. func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error { if jsm, ok := v.(JSONPBMarshaler); ok { b, err := jsm.MarshalJSONPB(m) if err != nil { return err } if typeURL != "" { // we are marshaling this object to an Any type var js map[string]*json.RawMessage if err = json.Unmarshal(b, &js); err != nil { return fmt.Errorf("type %T produced invalid JSON: %v", v, err) } turl, err := json.Marshal(typeURL) if err != nil { return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err) } js["@type"] = (*json.RawMessage)(&turl) if b, err = json.Marshal(js); err != nil { return err } } out.write(string(b)) return out.err } s := reflect.ValueOf(v).Elem() // Handle well-known types. if wkt, ok := v.(wkt); ok { switch wkt.XXX_WellKnownType() { case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value", "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue": // "Wrappers use the same representation in JSON // as the wrapped primitive type, ..." sprop := proto.GetProperties(s.Type()) return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent) case "Any": // Any is a bit more involved. return m.marshalAny(out, v, indent) case "Duration": // "Generated output always contains 3, 6, or 9 fractional digits, // depending on required precision." s, ns := s.Field(0).Int(), s.Field(1).Int() d := time.Duration(s)*time.Second + time.Duration(ns)*time.Nanosecond x := fmt.Sprintf("%.9f", d.Seconds()) x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") out.write(`"`) out.write(x) out.write(`s"`) return out.err case "Struct", "ListValue": // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice. // TODO: pass the correct Properties if needed. return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent) case "Timestamp": // "RFC 3339, where generated output will always be Z-normalized // and uses 3, 6 or 9 fractional digits." s, ns := s.Field(0).Int(), s.Field(1).Int() t := time.Unix(s, ns).UTC() // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits). x := t.Format("2006-01-02T15:04:05.000000000") x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") out.write(`"`) out.write(x) out.write(`Z"`) return out.err case "Value": // Value has a single oneof. kind := s.Field(0) if kind.IsNil() { // "absence of any variant indicates an error" return errors.New("nil Value") } // oneof -> *T -> T -> T.F x := kind.Elem().Elem().Field(0) // TODO: pass the correct Properties if needed. return m.marshalValue(out, &proto.Properties{}, x, indent) } } out.write("{") if m.Indent != "" { out.write("\n") } firstField := true if typeURL != "" { if err := m.marshalTypeURL(out, indent, typeURL); err != nil { return err } firstField = false } for i := 0; i < s.NumField(); i++ { value := s.Field(i) valueField := s.Type().Field(i) if strings.HasPrefix(valueField.Name, "XXX_") { continue } // IsNil will panic on most value kinds. switch value.Kind() { case reflect.Chan, reflect.Func, reflect.Interface: if value.IsNil() { continue } } if !m.EmitDefaults { switch value.Kind() { case reflect.Bool: if !value.Bool() { continue } case reflect.Int32, reflect.Int64: if value.Int() == 0 { continue } case reflect.Uint32, reflect.Uint64: if value.Uint() == 0 { continue } case reflect.Float32, reflect.Float64: if value.Float() == 0 { continue } case reflect.String: if value.Len() == 0 { continue } case reflect.Map, reflect.Ptr, reflect.Slice: if value.IsNil() { continue } } } // Oneof fields need special handling. if valueField.Tag.Get("protobuf_oneof") != "" { // value is an interface containing &T{real_value}. sv := value.Elem().Elem() // interface -> *T -> T value = sv.Field(0) valueField = sv.Type().Field(0) } prop := jsonProperties(valueField, m.OrigName) if !firstField { m.writeSep(out) } if err := m.marshalField(out, prop, value, indent); err != nil { return err } firstField = false } // Handle proto2 extensions. if ep, ok := v.(proto.Message); ok { extensions := proto.RegisteredExtensions(v) // Sort extensions for stable output. ids := make([]int32, 0, len(extensions)) for id, desc := range extensions { if !proto.HasExtension(ep, desc) { continue } ids = append(ids, id) } sort.Sort(int32Slice(ids)) for _, id := range ids { desc := extensions[id] if desc == nil { // unknown extension continue } ext, extErr := proto.GetExtension(ep, desc) if extErr != nil { return extErr } value := reflect.ValueOf(ext) var prop proto.Properties prop.Parse(desc.Tag) prop.JSONName = fmt.Sprintf("[%s]", desc.Name) if !firstField { m.writeSep(out) } if err := m.marshalField(out, &prop, value, indent); err != nil { return err } firstField = false } } if m.Indent != "" { out.write("\n") out.write(indent) } out.write("}") return out.err } func (m *Marshaler) writeSep(out *errWriter) { if m.Indent != "" { out.write(",\n") } else { out.write(",") } } func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error { // "If the Any contains a value that has a special JSON mapping, // it will be converted as follows: {"@type": xxx, "value": yyy}. // Otherwise, the value will be converted into a JSON object, // and the "@type" field will be inserted to indicate the actual data type." v := reflect.ValueOf(any).Elem() turl := v.Field(0).String() val := v.Field(1).Bytes() var msg proto.Message var err error if m.AnyResolver != nil { msg, err = m.AnyResolver.Resolve(turl) } else { msg, err = defaultResolveAny(turl) } if err != nil { return err } if err := proto.Unmarshal(val, msg); err != nil { return err } if _, ok := msg.(wkt); ok { out.write("{") if m.Indent != "" { out.write("\n") } if err := m.marshalTypeURL(out, indent, turl); err != nil { return err } m.writeSep(out) if m.Indent != "" { out.write(indent) out.write(m.Indent) out.write(`"value": `) } else { out.write(`"value":`) } if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil { return err } if m.Indent != "" { out.write("\n") out.write(indent) } out.write("}") return out.err } return m.marshalObject(out, msg, indent, turl) } func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error { if m.Indent != "" { out.write(indent) out.write(m.Indent) } out.write(`"@type":`) if m.Indent != "" { out.write(" ") } b, err := json.Marshal(typeURL) if err != nil { return err } out.write(string(b)) return out.err } // marshalField writes field description and value to the Writer. func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { if m.Indent != "" { out.write(indent) out.write(m.Indent) } out.write(`"`) out.write(prop.JSONName) out.write(`":`) if m.Indent != "" { out.write(" ") } if err := m.marshalValue(out, prop, v, indent); err != nil { return err } return nil } // marshalValue writes the value to the Writer. func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { var err error v = reflect.Indirect(v) // Handle nil pointer if v.Kind() == reflect.Invalid { out.write("null") return out.err } // Handle repeated elements. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 { out.write("[") comma := "" for i := 0; i < v.Len(); i++ { sliceVal := v.Index(i) out.write(comma) if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil { return err } comma = "," } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write("]") return out.err } // Handle well-known types. // Most are handled up in marshalObject (because 99% are messages). if wkt, ok := v.Interface().(wkt); ok { switch wkt.XXX_WellKnownType() { case "NullValue": out.write("null") return out.err } } // Handle enumerations. if !m.EnumsAsInts && prop.Enum != "" { // Unknown enum values will are stringified by the proto library as their // value. Such values should _not_ be quoted or they will be interpreted // as an enum string instead of their value. enumStr := v.Interface().(fmt.Stringer).String() var valStr string if v.Kind() == reflect.Ptr { valStr = strconv.Itoa(int(v.Elem().Int())) } else { valStr = strconv.Itoa(int(v.Int())) } isKnownEnum := enumStr != valStr if isKnownEnum { out.write(`"`) } out.write(enumStr) if isKnownEnum { out.write(`"`) } return out.err } // Handle nested messages. if v.Kind() == reflect.Struct { return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent, "") } // Handle maps. // Since Go randomizes map iteration, we sort keys for stable output. if v.Kind() == reflect.Map { out.write(`{`) keys := v.MapKeys() sort.Sort(mapKeys(keys)) for i, k := range keys { if i > 0 { out.write(`,`) } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } b, err := json.Marshal(k.Interface()) if err != nil { return err } s := string(b) // If the JSON is not a string value, encode it again to make it one. if !strings.HasPrefix(s, `"`) { b, err := json.Marshal(s) if err != nil { return err } s = string(b) } out.write(s) out.write(`:`) if m.Indent != "" { out.write(` `) } if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil { return err } } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write(`}`) return out.err } // Handle non-finite floats, e.g. NaN, Infinity and -Infinity. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { f := v.Float() var sval string switch { case math.IsInf(f, 1): sval = `"Infinity"` case math.IsInf(f, -1): sval = `"-Infinity"` case math.IsNaN(f): sval = `"NaN"` } if sval != "" { out.write(sval) return out.err } } // Default handling defers to the encoding/json library. b, err := json.Marshal(v.Interface()) if err != nil { return err } needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64) if needToQuote { out.write(`"`) } out.write(string(b)) if needToQuote { out.write(`"`) } return out.err } // Unmarshaler is a configurable object for converting from a JSON // representation to a protocol buffer object. type Unmarshaler struct { // Whether to allow messages to contain unknown fields, as opposed to // failing to unmarshal. AllowUnknownFields bool // A custom URL resolver to use when unmarshaling Any messages from JSON. // If unset, the default resolution strategy is to extract the // fully-qualified type name from the type URL and pass that to // proto.MessageType(string). AnyResolver AnyResolver } // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. // This function is lenient and will decode any options permutations of the // related Marshaler. func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error { inputValue := json.RawMessage{} if err := dec.Decode(&inputValue); err != nil { return err } return u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil) } // Unmarshal unmarshals a JSON object stream into a protocol // buffer. This function is lenient and will decode any options // permutations of the related Marshaler. func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error { dec := json.NewDecoder(r) return u.UnmarshalNext(dec, pb) } // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. // This function is lenient and will decode any options permutations of the // related Marshaler. func UnmarshalNext(dec *json.Decoder, pb proto.Message) error { return new(Unmarshaler).UnmarshalNext(dec, pb) } // Unmarshal unmarshals a JSON object stream into a protocol // buffer. This function is lenient and will decode any options // permutations of the related Marshaler. func Unmarshal(r io.Reader, pb proto.Message) error { return new(Unmarshaler).Unmarshal(r, pb) } // UnmarshalString will populate the fields of a protocol buffer based // on a JSON string. This function is lenient and will decode any options // permutations of the related Marshaler. func UnmarshalString(str string, pb proto.Message) error { return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb) } // unmarshalValue converts/copies a value into the target. // prop may be nil. func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error { targetType := target.Type() // Allocate memory for pointer fields. if targetType.Kind() == reflect.Ptr { // If input value is "null" and target is a pointer type, then the field should be treated as not set // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue. _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler) if string(inputValue) == "null" && targetType != reflect.TypeOf(&stpb.Value{}) && !isJSONPBUnmarshaler { return nil } target.Set(reflect.New(targetType.Elem())) return u.unmarshalValue(target.Elem(), inputValue, prop) } if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok { return jsu.UnmarshalJSONPB(u, []byte(inputValue)) } // Handle well-known types that are not pointers. if w, ok := target.Addr().Interface().(wkt); ok { switch w.XXX_WellKnownType() { case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value", "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue": return u.unmarshalValue(target.Field(0), inputValue, prop) case "Any": // Use json.RawMessage pointer type instead of value to support pre-1.8 version. // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see // https://github.com/golang/go/issues/14493 var jsonFields map[string]*json.RawMessage if err := json.Unmarshal(inputValue, &jsonFields); err != nil { return err } val, ok := jsonFields["@type"] if !ok || val == nil { return errors.New("Any JSON doesn't have '@type'") } var turl string if err := json.Unmarshal([]byte(*val), &turl); err != nil { return fmt.Errorf("can't unmarshal Any's '@type': %q", *val) } target.Field(0).SetString(turl) var m proto.Message var err error if u.AnyResolver != nil { m, err = u.AnyResolver.Resolve(turl) } else { m, err = defaultResolveAny(turl) } if err != nil { return err } if _, ok := m.(wkt); ok { val, ok := jsonFields["value"] if !ok { return errors.New("Any JSON doesn't have 'value'") } if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil { return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err) } } else { delete(jsonFields, "@type") nestedProto, err := json.Marshal(jsonFields) if err != nil { return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err) } if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil { return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err) } } b, err := proto.Marshal(m) if err != nil { return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err) } target.Field(1).SetBytes(b) return nil case "Duration": unq, err := strconv.Unquote(string(inputValue)) if err != nil { return err } d, err := time.ParseDuration(unq) if err != nil { return fmt.Errorf("bad Duration: %v", err) } ns := d.Nanoseconds() s := ns / 1e9 ns %= 1e9 target.Field(0).SetInt(s) target.Field(1).SetInt(ns) return nil case "Timestamp": unq, err := strconv.Unquote(string(inputValue)) if err != nil { return err } t, err := time.Parse(time.RFC3339Nano, unq) if err != nil { return fmt.Errorf("bad Timestamp: %v", err) } target.Field(0).SetInt(t.Unix()) target.Field(1).SetInt(int64(t.Nanosecond())) return nil case "Struct": var m map[string]json.RawMessage if err := json.Unmarshal(inputValue, &m); err != nil { return fmt.Errorf("bad StructValue: %v", err) } target.Field(0).Set(reflect.ValueOf(map[string]*stpb.Value{})) for k, jv := range m { pv := &stpb.Value{} if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil { return fmt.Errorf("bad value in StructValue for key %q: %v", k, err) } target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv)) } return nil case "ListValue": var s []json.RawMessage if err := json.Unmarshal(inputValue, &s); err != nil { return fmt.Errorf("bad ListValue: %v", err) } target.Field(0).Set(reflect.ValueOf(make([]*stpb.Value, len(s), len(s)))) for i, sv := range s { if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil { return err } } return nil case "Value": ivStr := string(inputValue) if ivStr == "null" { target.Field(0).Set(reflect.ValueOf(&stpb.Value_NullValue{})) } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil { target.Field(0).Set(reflect.ValueOf(&stpb.Value_NumberValue{v})) } else if v, err := strconv.Unquote(ivStr); err == nil { target.Field(0).Set(reflect.ValueOf(&stpb.Value_StringValue{v})) } else if v, err := strconv.ParseBool(ivStr); err == nil { target.Field(0).Set(reflect.ValueOf(&stpb.Value_BoolValue{v})) } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil { lv := &stpb.ListValue{} target.Field(0).Set(reflect.ValueOf(&stpb.Value_ListValue{lv})) return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop) } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil { sv := &stpb.Struct{} target.Field(0).Set(reflect.ValueOf(&stpb.Value_StructValue{sv})) return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop) } else { return fmt.Errorf("unrecognized type for Value %q", ivStr) } return nil } } // Handle enums, which have an underlying type of int32, // and may appear as strings. // The case of an enum appearing as a number is handled // at the bottom of this function. if inputValue[0] == '"' && prop != nil && prop.Enum != "" { vmap := proto.EnumValueMap(prop.Enum) // Don't need to do unquoting; valid enum names // are from a limited character set. s := inputValue[1 : len(inputValue)-1] n, ok := vmap[string(s)] if !ok { return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum) } if target.Kind() == reflect.Ptr { // proto2 target.Set(reflect.New(targetType.Elem())) target = target.Elem() } target.SetInt(int64(n)) return nil } // Handle nested messages. if targetType.Kind() == reflect.Struct { var jsonFields map[string]json.RawMessage if err := json.Unmarshal(inputValue, &jsonFields); err != nil { return err } consumeField := func(prop *proto.Properties) (json.RawMessage, bool) { // Be liberal in what names we accept; both orig_name and camelName are okay. fieldNames := acceptedJSONFieldNames(prop) vOrig, okOrig := jsonFields[fieldNames.orig] vCamel, okCamel := jsonFields[fieldNames.camel] if !okOrig && !okCamel { return nil, false } // If, for some reason, both are present in the data, favour the camelName. var raw json.RawMessage if okOrig { raw = vOrig delete(jsonFields, fieldNames.orig) } if okCamel { raw = vCamel delete(jsonFields, fieldNames.camel) } return raw, true } sprops := proto.GetProperties(targetType) for i := 0; i < target.NumField(); i++ { ft := target.Type().Field(i) if strings.HasPrefix(ft.Name, "XXX_") { continue } valueForField, ok := consumeField(sprops.Prop[i]) if !ok { continue } if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil { return err } } // Check for any oneof fields. if len(jsonFields) > 0 { for _, oop := range sprops.OneofTypes { raw, ok := consumeField(oop.Prop) if !ok { continue } nv := reflect.New(oop.Type.Elem()) target.Field(oop.Field).Set(nv) if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil { return err } } } // Handle proto2 extensions. if len(jsonFields) > 0 { if ep, ok := target.Addr().Interface().(proto.Message); ok { for _, ext := range proto.RegisteredExtensions(ep) { name := fmt.Sprintf("[%s]", ext.Name) raw, ok := jsonFields[name] if !ok { continue } delete(jsonFields, name) nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem()) if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil { return err } if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil { return err } } } } if !u.AllowUnknownFields && len(jsonFields) > 0 { // Pick any field to be the scapegoat. var f string for fname := range jsonFields { f = fname break } return fmt.Errorf("unknown field %q in %v", f, targetType) } return nil } // Handle arrays (which aren't encoded bytes) if targetType.Kind() == reflect.Slice && targetType.Elem().Kind() != reflect.Uint8 { var slc []json.RawMessage if err := json.Unmarshal(inputValue, &slc); err != nil { return err } if slc != nil { l := len(slc) target.Set(reflect.MakeSlice(targetType, l, l)) for i := 0; i < l; i++ { if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil { return err } } } return nil } // Handle maps (whose keys are always strings) if targetType.Kind() == reflect.Map { var mp map[string]json.RawMessage if err := json.Unmarshal(inputValue, &mp); err != nil { return err } if mp != nil { target.Set(reflect.MakeMap(targetType)) var keyprop, valprop *proto.Properties if prop != nil { // These could still be nil if the protobuf metadata is broken somehow. // TODO: This won't work because the fields are unexported. // We should probably just reparse them. //keyprop, valprop = prop.mkeyprop, prop.mvalprop } for ks, raw := range mp { // Unmarshal map key. The core json library already decoded the key into a // string, so we handle that specially. Other types were quoted post-serialization. var k reflect.Value if targetType.Key().Kind() == reflect.String { k = reflect.ValueOf(ks) } else { k = reflect.New(targetType.Key()).Elem() if err := u.unmarshalValue(k, json.RawMessage(ks), keyprop); err != nil { return err } } // Unmarshal map value. v := reflect.New(targetType.Elem()).Elem() if err := u.unmarshalValue(v, raw, valprop); err != nil { return err } target.SetMapIndex(k, v) } } return nil } // 64-bit integers can be encoded as strings. In this case we drop // the quotes and proceed as normal. isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 if isNum && strings.HasPrefix(string(inputValue), `"`) { inputValue = inputValue[1 : len(inputValue)-1] } // Non-finite numbers can be encoded as strings. isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64 if isFloat { if num, ok := nonFinite[string(inputValue)]; ok { target.SetFloat(num) return nil } } // Use the encoding/json for parsing other value types. return json.Unmarshal(inputValue, target.Addr().Interface()) } // jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute. func jsonProperties(f reflect.StructField, origName bool) *proto.Properties { var prop proto.Properties prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f) if origName || prop.JSONName == "" { prop.JSONName = prop.OrigName } return &prop } type fieldNames struct { orig, camel string } func acceptedJSONFieldNames(prop *proto.Properties) fieldNames { opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName} if prop.JSONName != "" { opts.camel = prop.JSONName } return opts } // Writer wrapper inspired by https://blog.golang.org/errors-are-values type errWriter struct { writer io.Writer err error } func (w *errWriter) write(str string) { if w.err != nil { return } _, w.err = w.writer.Write([]byte(str)) } // Map fields may have key types of non-float scalars, strings and enums. // The easiest way to sort them in some deterministic order is to use fmt. // If this turns out to be inefficient we can always consider other options, // such as doing a Schwartzian transform. // // Numeric keys are sorted in numeric order per // https://developers.google.com/protocol-buffers/docs/proto#maps. type mapKeys []reflect.Value func (s mapKeys) Len() int { return len(s) } func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s mapKeys) Less(i, j int) bool { if k := s[i].Kind(); k == s[j].Kind() { switch k { case reflect.Int32, reflect.Int64: return s[i].Int() < s[j].Int() case reflect.Uint32, reflect.Uint64: return s[i].Uint() < s[j].Uint() } } return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/descriptor/������������������������������������������0000755�0610621�0607500�00000000000�13172163407�024552� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/descriptor/descriptor_test.go������������������������0000644�0610621�0607500�00000001607�13172163407�030322� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package descriptor_test import ( "fmt" "testing" "github.com/golang/protobuf/descriptor" tpb "github.com/golang/protobuf/proto/testdata" protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" ) func TestMessage(t *testing.T) { var msg *protobuf.DescriptorProto fd, md := descriptor.ForMessage(msg) if pkg, want := fd.GetPackage(), "google.protobuf"; pkg != want { t.Errorf("descriptor.ForMessage(%T).GetPackage() = %q; want %q", msg, pkg, want) } if name, want := md.GetName(), "DescriptorProto"; name != want { t.Fatalf("descriptor.ForMessage(%T).GetName() = %q; want %q", msg, name, want) } } func Example_Options() { var msg *tpb.MyMessageSet _, md := descriptor.ForMessage(msg) if md.GetOptions().GetMessageSetWireFormat() { fmt.Printf("%v uses option message_set_wire_format.\n", md.GetName()) } // Output: // MyMessageSet uses option message_set_wire_format. } �������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/descriptor/descriptor.go�����������������������������0000644�0610621�0607500�00000006510�13172163407�027261� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Package descriptor provides functions for obtaining protocol buffer // descriptors for generated Go types. // // These functions cannot go in package proto because they depend on the // generated protobuf descriptor messages, which themselves depend on proto. package descriptor import ( "bytes" "compress/gzip" "fmt" "io/ioutil" "github.com/golang/protobuf/proto" protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" ) // extractFile extracts a FileDescriptorProto from a gzip'd buffer. func extractFile(gz []byte) (*protobuf.FileDescriptorProto, error) { r, err := gzip.NewReader(bytes.NewReader(gz)) if err != nil { return nil, fmt.Errorf("failed to open gzip reader: %v", err) } defer r.Close() b, err := ioutil.ReadAll(r) if err != nil { return nil, fmt.Errorf("failed to uncompress descriptor: %v", err) } fd := new(protobuf.FileDescriptorProto) if err := proto.Unmarshal(b, fd); err != nil { return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err) } return fd, nil } // Message is a proto.Message with a method to return its descriptor. // // Message types generated by the protocol compiler always satisfy // the Message interface. type Message interface { proto.Message Descriptor() ([]byte, []int) } // ForMessage returns a FileDescriptorProto and a DescriptorProto from within it // describing the given message. func ForMessage(msg Message) (fd *protobuf.FileDescriptorProto, md *protobuf.DescriptorProto) { gz, path := msg.Descriptor() fd, err := extractFile(gz) if err != nil { panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err)) } md = fd.MessageType[path[0]] for _, i := range path[1:] { md = md.NestedType[i] } return fd, md } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/_conformance/����������������������������������������0000755�0610621�0607500�00000000000�13172163407�025025� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/_conformance/conformance_proto/����������������������0000755�0610621�0607500�00000000000�13172163407�030542� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/_conformance/conformance_proto/conformance.proto�����0000644�0610621�0607500�00000025405�13172163407�034127� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package conformance; option java_package = "com.google.protobuf.conformance"; import "google/protobuf/any.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/field_mask.proto"; import "google/protobuf/struct.proto"; import "google/protobuf/timestamp.proto"; import "google/protobuf/wrappers.proto"; // This defines the conformance testing protocol. This protocol exists between // the conformance test suite itself and the code being tested. For each test, // the suite will send a ConformanceRequest message and expect a // ConformanceResponse message. // // You can either run the tests in two different ways: // // 1. in-process (using the interface in conformance_test.h). // // 2. as a sub-process communicating over a pipe. Information about how to // do this is in conformance_test_runner.cc. // // Pros/cons of the two approaches: // // - running as a sub-process is much simpler for languages other than C/C++. // // - running as a sub-process may be more tricky in unusual environments like // iOS apps, where fork/stdin/stdout are not available. enum WireFormat { UNSPECIFIED = 0; PROTOBUF = 1; JSON = 2; } // Represents a single test case's input. The testee should: // // 1. parse this proto (which should always succeed) // 2. parse the protobuf or JSON payload in "payload" (which may fail) // 3. if the parse succeeded, serialize the message in the requested format. message ConformanceRequest { // The payload (whether protobuf of JSON) is always for a TestAllTypes proto // (see below). oneof payload { bytes protobuf_payload = 1; string json_payload = 2; } // Which format should the testee serialize its message to? WireFormat requested_output_format = 3; } // Represents a single test case's output. message ConformanceResponse { oneof result { // This string should be set to indicate parsing failed. The string can // provide more information about the parse error if it is available. // // Setting this string does not necessarily mean the testee failed the // test. Some of the test cases are intentionally invalid input. string parse_error = 1; // If the input was successfully parsed but errors occurred when // serializing it to the requested output format, set the error message in // this field. string serialize_error = 6; // This should be set if some other error occurred. This will always // indicate that the test failed. The string can provide more information // about the failure. string runtime_error = 2; // If the input was successfully parsed and the requested output was // protobuf, serialize it to protobuf and set it in this field. bytes protobuf_payload = 3; // If the input was successfully parsed and the requested output was JSON, // serialize to JSON and set it in this field. string json_payload = 4; // For when the testee skipped the test, likely because a certain feature // wasn't supported, like JSON input/output. string skipped = 5; } } // This proto includes every type of field in both singular and repeated // forms. message TestAllTypes { message NestedMessage { int32 a = 1; TestAllTypes corecursive = 2; } enum NestedEnum { FOO = 0; BAR = 1; BAZ = 2; NEG = -1; // Intentionally negative. } // Singular int32 optional_int32 = 1; int64 optional_int64 = 2; uint32 optional_uint32 = 3; uint64 optional_uint64 = 4; sint32 optional_sint32 = 5; sint64 optional_sint64 = 6; fixed32 optional_fixed32 = 7; fixed64 optional_fixed64 = 8; sfixed32 optional_sfixed32 = 9; sfixed64 optional_sfixed64 = 10; float optional_float = 11; double optional_double = 12; bool optional_bool = 13; string optional_string = 14; bytes optional_bytes = 15; NestedMessage optional_nested_message = 18; ForeignMessage optional_foreign_message = 19; NestedEnum optional_nested_enum = 21; ForeignEnum optional_foreign_enum = 22; string optional_string_piece = 24 [ctype=STRING_PIECE]; string optional_cord = 25 [ctype=CORD]; TestAllTypes recursive_message = 27; // Repeated repeated int32 repeated_int32 = 31; repeated int64 repeated_int64 = 32; repeated uint32 repeated_uint32 = 33; repeated uint64 repeated_uint64 = 34; repeated sint32 repeated_sint32 = 35; repeated sint64 repeated_sint64 = 36; repeated fixed32 repeated_fixed32 = 37; repeated fixed64 repeated_fixed64 = 38; repeated sfixed32 repeated_sfixed32 = 39; repeated sfixed64 repeated_sfixed64 = 40; repeated float repeated_float = 41; repeated double repeated_double = 42; repeated bool repeated_bool = 43; repeated string repeated_string = 44; repeated bytes repeated_bytes = 45; repeated NestedMessage repeated_nested_message = 48; repeated ForeignMessage repeated_foreign_message = 49; repeated NestedEnum repeated_nested_enum = 51; repeated ForeignEnum repeated_foreign_enum = 52; repeated string repeated_string_piece = 54 [ctype=STRING_PIECE]; repeated string repeated_cord = 55 [ctype=CORD]; // Map map < int32, int32> map_int32_int32 = 56; map < int64, int64> map_int64_int64 = 57; map < uint32, uint32> map_uint32_uint32 = 58; map < uint64, uint64> map_uint64_uint64 = 59; map < sint32, sint32> map_sint32_sint32 = 60; map < sint64, sint64> map_sint64_sint64 = 61; map < fixed32, fixed32> map_fixed32_fixed32 = 62; map < fixed64, fixed64> map_fixed64_fixed64 = 63; map <sfixed32, sfixed32> map_sfixed32_sfixed32 = 64; map <sfixed64, sfixed64> map_sfixed64_sfixed64 = 65; map < int32, float> map_int32_float = 66; map < int32, double> map_int32_double = 67; map < bool, bool> map_bool_bool = 68; map < string, string> map_string_string = 69; map < string, bytes> map_string_bytes = 70; map < string, NestedMessage> map_string_nested_message = 71; map < string, ForeignMessage> map_string_foreign_message = 72; map < string, NestedEnum> map_string_nested_enum = 73; map < string, ForeignEnum> map_string_foreign_enum = 74; oneof oneof_field { uint32 oneof_uint32 = 111; NestedMessage oneof_nested_message = 112; string oneof_string = 113; bytes oneof_bytes = 114; bool oneof_bool = 115; uint64 oneof_uint64 = 116; float oneof_float = 117; double oneof_double = 118; NestedEnum oneof_enum = 119; } // Well-known types google.protobuf.BoolValue optional_bool_wrapper = 201; google.protobuf.Int32Value optional_int32_wrapper = 202; google.protobuf.Int64Value optional_int64_wrapper = 203; google.protobuf.UInt32Value optional_uint32_wrapper = 204; google.protobuf.UInt64Value optional_uint64_wrapper = 205; google.protobuf.FloatValue optional_float_wrapper = 206; google.protobuf.DoubleValue optional_double_wrapper = 207; google.protobuf.StringValue optional_string_wrapper = 208; google.protobuf.BytesValue optional_bytes_wrapper = 209; repeated google.protobuf.BoolValue repeated_bool_wrapper = 211; repeated google.protobuf.Int32Value repeated_int32_wrapper = 212; repeated google.protobuf.Int64Value repeated_int64_wrapper = 213; repeated google.protobuf.UInt32Value repeated_uint32_wrapper = 214; repeated google.protobuf.UInt64Value repeated_uint64_wrapper = 215; repeated google.protobuf.FloatValue repeated_float_wrapper = 216; repeated google.protobuf.DoubleValue repeated_double_wrapper = 217; repeated google.protobuf.StringValue repeated_string_wrapper = 218; repeated google.protobuf.BytesValue repeated_bytes_wrapper = 219; google.protobuf.Duration optional_duration = 301; google.protobuf.Timestamp optional_timestamp = 302; google.protobuf.FieldMask optional_field_mask = 303; google.protobuf.Struct optional_struct = 304; google.protobuf.Any optional_any = 305; google.protobuf.Value optional_value = 306; repeated google.protobuf.Duration repeated_duration = 311; repeated google.protobuf.Timestamp repeated_timestamp = 312; repeated google.protobuf.FieldMask repeated_fieldmask = 313; repeated google.protobuf.Struct repeated_struct = 324; repeated google.protobuf.Any repeated_any = 315; repeated google.protobuf.Value repeated_value = 316; // Test field-name-to-JSON-name convention. // (protobuf says names can be any valid C/C++ identifier.) int32 fieldname1 = 401; int32 field_name2 = 402; int32 _field_name3 = 403; int32 field__name4_ = 404; int32 field0name5 = 405; int32 field_0_name6 = 406; int32 fieldName7 = 407; int32 FieldName8 = 408; int32 field_Name9 = 409; int32 Field_Name10 = 410; int32 FIELD_NAME11 = 411; int32 FIELD_name12 = 412; int32 __field_name13 = 413; int32 __Field_name14 = 414; int32 field__name15 = 415; int32 field__Name16 = 416; int32 field_name17__ = 417; int32 Field_name18__ = 418; } message ForeignMessage { int32 c = 1; } enum ForeignEnum { FOREIGN_FOO = 0; FOREIGN_BAR = 1; FOREIGN_BAZ = 2; } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/_conformance/conformance_proto/conformance.pb.go�����0000644�0610621�0607500�00000225751�13172163407�033777� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. DO NOT EDIT. // source: conformance_proto/conformance.proto /* Package conformance is a generated protocol buffer package. It is generated from these files: conformance_proto/conformance.proto It has these top-level messages: ConformanceRequest ConformanceResponse TestAllTypes ForeignMessage */ package conformance import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/ptypes/any" import google_protobuf1 "github.com/golang/protobuf/ptypes/duration" import google_protobuf2 "google.golang.org/genproto/protobuf" import google_protobuf3 "github.com/golang/protobuf/ptypes/struct" import google_protobuf4 "github.com/golang/protobuf/ptypes/timestamp" import google_protobuf5 "github.com/golang/protobuf/ptypes/wrappers" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type WireFormat int32 const ( WireFormat_UNSPECIFIED WireFormat = 0 WireFormat_PROTOBUF WireFormat = 1 WireFormat_JSON WireFormat = 2 ) var WireFormat_name = map[int32]string{ 0: "UNSPECIFIED", 1: "PROTOBUF", 2: "JSON", } var WireFormat_value = map[string]int32{ "UNSPECIFIED": 0, "PROTOBUF": 1, "JSON": 2, } func (x WireFormat) String() string { return proto.EnumName(WireFormat_name, int32(x)) } func (WireFormat) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } type ForeignEnum int32 const ( ForeignEnum_FOREIGN_FOO ForeignEnum = 0 ForeignEnum_FOREIGN_BAR ForeignEnum = 1 ForeignEnum_FOREIGN_BAZ ForeignEnum = 2 ) var ForeignEnum_name = map[int32]string{ 0: "FOREIGN_FOO", 1: "FOREIGN_BAR", 2: "FOREIGN_BAZ", } var ForeignEnum_value = map[string]int32{ "FOREIGN_FOO": 0, "FOREIGN_BAR": 1, "FOREIGN_BAZ": 2, } func (x ForeignEnum) String() string { return proto.EnumName(ForeignEnum_name, int32(x)) } func (ForeignEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } type TestAllTypes_NestedEnum int32 const ( TestAllTypes_FOO TestAllTypes_NestedEnum = 0 TestAllTypes_BAR TestAllTypes_NestedEnum = 1 TestAllTypes_BAZ TestAllTypes_NestedEnum = 2 TestAllTypes_NEG TestAllTypes_NestedEnum = -1 ) var TestAllTypes_NestedEnum_name = map[int32]string{ 0: "FOO", 1: "BAR", 2: "BAZ", -1: "NEG", } var TestAllTypes_NestedEnum_value = map[string]int32{ "FOO": 0, "BAR": 1, "BAZ": 2, "NEG": -1, } func (x TestAllTypes_NestedEnum) String() string { return proto.EnumName(TestAllTypes_NestedEnum_name, int32(x)) } func (TestAllTypes_NestedEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } // Represents a single test case's input. The testee should: // // 1. parse this proto (which should always succeed) // 2. parse the protobuf or JSON payload in "payload" (which may fail) // 3. if the parse succeeded, serialize the message in the requested format. type ConformanceRequest struct { // The payload (whether protobuf of JSON) is always for a TestAllTypes proto // (see below). // // Types that are valid to be assigned to Payload: // *ConformanceRequest_ProtobufPayload // *ConformanceRequest_JsonPayload Payload isConformanceRequest_Payload `protobuf_oneof:"payload"` // Which format should the testee serialize its message to? RequestedOutputFormat WireFormat `protobuf:"varint,3,opt,name=requested_output_format,json=requestedOutputFormat,enum=conformance.WireFormat" json:"requested_output_format,omitempty"` } func (m *ConformanceRequest) Reset() { *m = ConformanceRequest{} } func (m *ConformanceRequest) String() string { return proto.CompactTextString(m) } func (*ConformanceRequest) ProtoMessage() {} func (*ConformanceRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } type isConformanceRequest_Payload interface { isConformanceRequest_Payload() } type ConformanceRequest_ProtobufPayload struct { ProtobufPayload []byte `protobuf:"bytes,1,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"` } type ConformanceRequest_JsonPayload struct { JsonPayload string `protobuf:"bytes,2,opt,name=json_payload,json=jsonPayload,oneof"` } func (*ConformanceRequest_ProtobufPayload) isConformanceRequest_Payload() {} func (*ConformanceRequest_JsonPayload) isConformanceRequest_Payload() {} func (m *ConformanceRequest) GetPayload() isConformanceRequest_Payload { if m != nil { return m.Payload } return nil } func (m *ConformanceRequest) GetProtobufPayload() []byte { if x, ok := m.GetPayload().(*ConformanceRequest_ProtobufPayload); ok { return x.ProtobufPayload } return nil } func (m *ConformanceRequest) GetJsonPayload() string { if x, ok := m.GetPayload().(*ConformanceRequest_JsonPayload); ok { return x.JsonPayload } return "" } func (m *ConformanceRequest) GetRequestedOutputFormat() WireFormat { if m != nil { return m.RequestedOutputFormat } return WireFormat_UNSPECIFIED } // XXX_OneofFuncs is for the internal use of the proto package. func (*ConformanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _ConformanceRequest_OneofMarshaler, _ConformanceRequest_OneofUnmarshaler, _ConformanceRequest_OneofSizer, []interface{}{ (*ConformanceRequest_ProtobufPayload)(nil), (*ConformanceRequest_JsonPayload)(nil), } } func _ConformanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*ConformanceRequest) // payload switch x := m.Payload.(type) { case *ConformanceRequest_ProtobufPayload: b.EncodeVarint(1<<3 | proto.WireBytes) b.EncodeRawBytes(x.ProtobufPayload) case *ConformanceRequest_JsonPayload: b.EncodeVarint(2<<3 | proto.WireBytes) b.EncodeStringBytes(x.JsonPayload) case nil: default: return fmt.Errorf("ConformanceRequest.Payload has unexpected type %T", x) } return nil } func _ConformanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*ConformanceRequest) switch tag { case 1: // payload.protobuf_payload if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Payload = &ConformanceRequest_ProtobufPayload{x} return true, err case 2: // payload.json_payload if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Payload = &ConformanceRequest_JsonPayload{x} return true, err default: return false, nil } } func _ConformanceRequest_OneofSizer(msg proto.Message) (n int) { m := msg.(*ConformanceRequest) // payload switch x := m.Payload.(type) { case *ConformanceRequest_ProtobufPayload: n += proto.SizeVarint(1<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.ProtobufPayload))) n += len(x.ProtobufPayload) case *ConformanceRequest_JsonPayload: n += proto.SizeVarint(2<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.JsonPayload))) n += len(x.JsonPayload) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // Represents a single test case's output. type ConformanceResponse struct { // Types that are valid to be assigned to Result: // *ConformanceResponse_ParseError // *ConformanceResponse_SerializeError // *ConformanceResponse_RuntimeError // *ConformanceResponse_ProtobufPayload // *ConformanceResponse_JsonPayload // *ConformanceResponse_Skipped Result isConformanceResponse_Result `protobuf_oneof:"result"` } func (m *ConformanceResponse) Reset() { *m = ConformanceResponse{} } func (m *ConformanceResponse) String() string { return proto.CompactTextString(m) } func (*ConformanceResponse) ProtoMessage() {} func (*ConformanceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } type isConformanceResponse_Result interface { isConformanceResponse_Result() } type ConformanceResponse_ParseError struct { ParseError string `protobuf:"bytes,1,opt,name=parse_error,json=parseError,oneof"` } type ConformanceResponse_SerializeError struct { SerializeError string `protobuf:"bytes,6,opt,name=serialize_error,json=serializeError,oneof"` } type ConformanceResponse_RuntimeError struct { RuntimeError string `protobuf:"bytes,2,opt,name=runtime_error,json=runtimeError,oneof"` } type ConformanceResponse_ProtobufPayload struct { ProtobufPayload []byte `protobuf:"bytes,3,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"` } type ConformanceResponse_JsonPayload struct { JsonPayload string `protobuf:"bytes,4,opt,name=json_payload,json=jsonPayload,oneof"` } type ConformanceResponse_Skipped struct { Skipped string `protobuf:"bytes,5,opt,name=skipped,oneof"` } func (*ConformanceResponse_ParseError) isConformanceResponse_Result() {} func (*ConformanceResponse_SerializeError) isConformanceResponse_Result() {} func (*ConformanceResponse_RuntimeError) isConformanceResponse_Result() {} func (*ConformanceResponse_ProtobufPayload) isConformanceResponse_Result() {} func (*ConformanceResponse_JsonPayload) isConformanceResponse_Result() {} func (*ConformanceResponse_Skipped) isConformanceResponse_Result() {} func (m *ConformanceResponse) GetResult() isConformanceResponse_Result { if m != nil { return m.Result } return nil } func (m *ConformanceResponse) GetParseError() string { if x, ok := m.GetResult().(*ConformanceResponse_ParseError); ok { return x.ParseError } return "" } func (m *ConformanceResponse) GetSerializeError() string { if x, ok := m.GetResult().(*ConformanceResponse_SerializeError); ok { return x.SerializeError } return "" } func (m *ConformanceResponse) GetRuntimeError() string { if x, ok := m.GetResult().(*ConformanceResponse_RuntimeError); ok { return x.RuntimeError } return "" } func (m *ConformanceResponse) GetProtobufPayload() []byte { if x, ok := m.GetResult().(*ConformanceResponse_ProtobufPayload); ok { return x.ProtobufPayload } return nil } func (m *ConformanceResponse) GetJsonPayload() string { if x, ok := m.GetResult().(*ConformanceResponse_JsonPayload); ok { return x.JsonPayload } return "" } func (m *ConformanceResponse) GetSkipped() string { if x, ok := m.GetResult().(*ConformanceResponse_Skipped); ok { return x.Skipped } return "" } // XXX_OneofFuncs is for the internal use of the proto package. func (*ConformanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _ConformanceResponse_OneofMarshaler, _ConformanceResponse_OneofUnmarshaler, _ConformanceResponse_OneofSizer, []interface{}{ (*ConformanceResponse_ParseError)(nil), (*ConformanceResponse_SerializeError)(nil), (*ConformanceResponse_RuntimeError)(nil), (*ConformanceResponse_ProtobufPayload)(nil), (*ConformanceResponse_JsonPayload)(nil), (*ConformanceResponse_Skipped)(nil), } } func _ConformanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*ConformanceResponse) // result switch x := m.Result.(type) { case *ConformanceResponse_ParseError: b.EncodeVarint(1<<3 | proto.WireBytes) b.EncodeStringBytes(x.ParseError) case *ConformanceResponse_SerializeError: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.SerializeError) case *ConformanceResponse_RuntimeError: b.EncodeVarint(2<<3 | proto.WireBytes) b.EncodeStringBytes(x.RuntimeError) case *ConformanceResponse_ProtobufPayload: b.EncodeVarint(3<<3 | proto.WireBytes) b.EncodeRawBytes(x.ProtobufPayload) case *ConformanceResponse_JsonPayload: b.EncodeVarint(4<<3 | proto.WireBytes) b.EncodeStringBytes(x.JsonPayload) case *ConformanceResponse_Skipped: b.EncodeVarint(5<<3 | proto.WireBytes) b.EncodeStringBytes(x.Skipped) case nil: default: return fmt.Errorf("ConformanceResponse.Result has unexpected type %T", x) } return nil } func _ConformanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*ConformanceResponse) switch tag { case 1: // result.parse_error if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_ParseError{x} return true, err case 6: // result.serialize_error if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_SerializeError{x} return true, err case 2: // result.runtime_error if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_RuntimeError{x} return true, err case 3: // result.protobuf_payload if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Result = &ConformanceResponse_ProtobufPayload{x} return true, err case 4: // result.json_payload if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_JsonPayload{x} return true, err case 5: // result.skipped if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_Skipped{x} return true, err default: return false, nil } } func _ConformanceResponse_OneofSizer(msg proto.Message) (n int) { m := msg.(*ConformanceResponse) // result switch x := m.Result.(type) { case *ConformanceResponse_ParseError: n += proto.SizeVarint(1<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.ParseError))) n += len(x.ParseError) case *ConformanceResponse_SerializeError: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.SerializeError))) n += len(x.SerializeError) case *ConformanceResponse_RuntimeError: n += proto.SizeVarint(2<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.RuntimeError))) n += len(x.RuntimeError) case *ConformanceResponse_ProtobufPayload: n += proto.SizeVarint(3<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.ProtobufPayload))) n += len(x.ProtobufPayload) case *ConformanceResponse_JsonPayload: n += proto.SizeVarint(4<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.JsonPayload))) n += len(x.JsonPayload) case *ConformanceResponse_Skipped: n += proto.SizeVarint(5<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Skipped))) n += len(x.Skipped) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // This proto includes every type of field in both singular and repeated // forms. type TestAllTypes struct { // Singular OptionalInt32 int32 `protobuf:"varint,1,opt,name=optional_int32,json=optionalInt32" json:"optional_int32,omitempty"` OptionalInt64 int64 `protobuf:"varint,2,opt,name=optional_int64,json=optionalInt64" json:"optional_int64,omitempty"` OptionalUint32 uint32 `protobuf:"varint,3,opt,name=optional_uint32,json=optionalUint32" json:"optional_uint32,omitempty"` OptionalUint64 uint64 `protobuf:"varint,4,opt,name=optional_uint64,json=optionalUint64" json:"optional_uint64,omitempty"` OptionalSint32 int32 `protobuf:"zigzag32,5,opt,name=optional_sint32,json=optionalSint32" json:"optional_sint32,omitempty"` OptionalSint64 int64 `protobuf:"zigzag64,6,opt,name=optional_sint64,json=optionalSint64" json:"optional_sint64,omitempty"` OptionalFixed32 uint32 `protobuf:"fixed32,7,opt,name=optional_fixed32,json=optionalFixed32" json:"optional_fixed32,omitempty"` OptionalFixed64 uint64 `protobuf:"fixed64,8,opt,name=optional_fixed64,json=optionalFixed64" json:"optional_fixed64,omitempty"` OptionalSfixed32 int32 `protobuf:"fixed32,9,opt,name=optional_sfixed32,json=optionalSfixed32" json:"optional_sfixed32,omitempty"` OptionalSfixed64 int64 `protobuf:"fixed64,10,opt,name=optional_sfixed64,json=optionalSfixed64" json:"optional_sfixed64,omitempty"` OptionalFloat float32 `protobuf:"fixed32,11,opt,name=optional_float,json=optionalFloat" json:"optional_float,omitempty"` OptionalDouble float64 `protobuf:"fixed64,12,opt,name=optional_double,json=optionalDouble" json:"optional_double,omitempty"` OptionalBool bool `protobuf:"varint,13,opt,name=optional_bool,json=optionalBool" json:"optional_bool,omitempty"` OptionalString string `protobuf:"bytes,14,opt,name=optional_string,json=optionalString" json:"optional_string,omitempty"` OptionalBytes []byte `protobuf:"bytes,15,opt,name=optional_bytes,json=optionalBytes,proto3" json:"optional_bytes,omitempty"` OptionalNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,18,opt,name=optional_nested_message,json=optionalNestedMessage" json:"optional_nested_message,omitempty"` OptionalForeignMessage *ForeignMessage `protobuf:"bytes,19,opt,name=optional_foreign_message,json=optionalForeignMessage" json:"optional_foreign_message,omitempty"` OptionalNestedEnum TestAllTypes_NestedEnum `protobuf:"varint,21,opt,name=optional_nested_enum,json=optionalNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"optional_nested_enum,omitempty"` OptionalForeignEnum ForeignEnum `protobuf:"varint,22,opt,name=optional_foreign_enum,json=optionalForeignEnum,enum=conformance.ForeignEnum" json:"optional_foreign_enum,omitempty"` OptionalStringPiece string `protobuf:"bytes,24,opt,name=optional_string_piece,json=optionalStringPiece" json:"optional_string_piece,omitempty"` OptionalCord string `protobuf:"bytes,25,opt,name=optional_cord,json=optionalCord" json:"optional_cord,omitempty"` RecursiveMessage *TestAllTypes `protobuf:"bytes,27,opt,name=recursive_message,json=recursiveMessage" json:"recursive_message,omitempty"` // Repeated RepeatedInt32 []int32 `protobuf:"varint,31,rep,packed,name=repeated_int32,json=repeatedInt32" json:"repeated_int32,omitempty"` RepeatedInt64 []int64 `protobuf:"varint,32,rep,packed,name=repeated_int64,json=repeatedInt64" json:"repeated_int64,omitempty"` RepeatedUint32 []uint32 `protobuf:"varint,33,rep,packed,name=repeated_uint32,json=repeatedUint32" json:"repeated_uint32,omitempty"` RepeatedUint64 []uint64 `protobuf:"varint,34,rep,packed,name=repeated_uint64,json=repeatedUint64" json:"repeated_uint64,omitempty"` RepeatedSint32 []int32 `protobuf:"zigzag32,35,rep,packed,name=repeated_sint32,json=repeatedSint32" json:"repeated_sint32,omitempty"` RepeatedSint64 []int64 `protobuf:"zigzag64,36,rep,packed,name=repeated_sint64,json=repeatedSint64" json:"repeated_sint64,omitempty"` RepeatedFixed32 []uint32 `protobuf:"fixed32,37,rep,packed,name=repeated_fixed32,json=repeatedFixed32" json:"repeated_fixed32,omitempty"` RepeatedFixed64 []uint64 `protobuf:"fixed64,38,rep,packed,name=repeated_fixed64,json=repeatedFixed64" json:"repeated_fixed64,omitempty"` RepeatedSfixed32 []int32 `protobuf:"fixed32,39,rep,packed,name=repeated_sfixed32,json=repeatedSfixed32" json:"repeated_sfixed32,omitempty"` RepeatedSfixed64 []int64 `protobuf:"fixed64,40,rep,packed,name=repeated_sfixed64,json=repeatedSfixed64" json:"repeated_sfixed64,omitempty"` RepeatedFloat []float32 `protobuf:"fixed32,41,rep,packed,name=repeated_float,json=repeatedFloat" json:"repeated_float,omitempty"` RepeatedDouble []float64 `protobuf:"fixed64,42,rep,packed,name=repeated_double,json=repeatedDouble" json:"repeated_double,omitempty"` RepeatedBool []bool `protobuf:"varint,43,rep,packed,name=repeated_bool,json=repeatedBool" json:"repeated_bool,omitempty"` RepeatedString []string `protobuf:"bytes,44,rep,name=repeated_string,json=repeatedString" json:"repeated_string,omitempty"` RepeatedBytes [][]byte `protobuf:"bytes,45,rep,name=repeated_bytes,json=repeatedBytes,proto3" json:"repeated_bytes,omitempty"` RepeatedNestedMessage []*TestAllTypes_NestedMessage `protobuf:"bytes,48,rep,name=repeated_nested_message,json=repeatedNestedMessage" json:"repeated_nested_message,omitempty"` RepeatedForeignMessage []*ForeignMessage `protobuf:"bytes,49,rep,name=repeated_foreign_message,json=repeatedForeignMessage" json:"repeated_foreign_message,omitempty"` RepeatedNestedEnum []TestAllTypes_NestedEnum `protobuf:"varint,51,rep,packed,name=repeated_nested_enum,json=repeatedNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"repeated_nested_enum,omitempty"` RepeatedForeignEnum []ForeignEnum `protobuf:"varint,52,rep,packed,name=repeated_foreign_enum,json=repeatedForeignEnum,enum=conformance.ForeignEnum" json:"repeated_foreign_enum,omitempty"` RepeatedStringPiece []string `protobuf:"bytes,54,rep,name=repeated_string_piece,json=repeatedStringPiece" json:"repeated_string_piece,omitempty"` RepeatedCord []string `protobuf:"bytes,55,rep,name=repeated_cord,json=repeatedCord" json:"repeated_cord,omitempty"` // Map MapInt32Int32 map[int32]int32 `protobuf:"bytes,56,rep,name=map_int32_int32,json=mapInt32Int32" json:"map_int32_int32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapInt64Int64 map[int64]int64 `protobuf:"bytes,57,rep,name=map_int64_int64,json=mapInt64Int64" json:"map_int64_int64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapUint32Uint32 map[uint32]uint32 `protobuf:"bytes,58,rep,name=map_uint32_uint32,json=mapUint32Uint32" json:"map_uint32_uint32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapUint64Uint64 map[uint64]uint64 `protobuf:"bytes,59,rep,name=map_uint64_uint64,json=mapUint64Uint64" json:"map_uint64_uint64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapSint32Sint32 map[int32]int32 `protobuf:"bytes,60,rep,name=map_sint32_sint32,json=mapSint32Sint32" json:"map_sint32_sint32,omitempty" protobuf_key:"zigzag32,1,opt,name=key" protobuf_val:"zigzag32,2,opt,name=value"` MapSint64Sint64 map[int64]int64 `protobuf:"bytes,61,rep,name=map_sint64_sint64,json=mapSint64Sint64" json:"map_sint64_sint64,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"zigzag64,2,opt,name=value"` MapFixed32Fixed32 map[uint32]uint32 `protobuf:"bytes,62,rep,name=map_fixed32_fixed32,json=mapFixed32Fixed32" json:"map_fixed32_fixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` MapFixed64Fixed64 map[uint64]uint64 `protobuf:"bytes,63,rep,name=map_fixed64_fixed64,json=mapFixed64Fixed64" json:"map_fixed64_fixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` MapSfixed32Sfixed32 map[int32]int32 `protobuf:"bytes,64,rep,name=map_sfixed32_sfixed32,json=mapSfixed32Sfixed32" json:"map_sfixed32_sfixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` MapSfixed64Sfixed64 map[int64]int64 `protobuf:"bytes,65,rep,name=map_sfixed64_sfixed64,json=mapSfixed64Sfixed64" json:"map_sfixed64_sfixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` MapInt32Float map[int32]float32 `protobuf:"bytes,66,rep,name=map_int32_float,json=mapInt32Float" json:"map_int32_float,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` MapInt32Double map[int32]float64 `protobuf:"bytes,67,rep,name=map_int32_double,json=mapInt32Double" json:"map_int32_double,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` MapBoolBool map[bool]bool `protobuf:"bytes,68,rep,name=map_bool_bool,json=mapBoolBool" json:"map_bool_bool,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapStringString map[string]string `protobuf:"bytes,69,rep,name=map_string_string,json=mapStringString" json:"map_string_string,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MapStringBytes map[string][]byte `protobuf:"bytes,70,rep,name=map_string_bytes,json=mapStringBytes" json:"map_string_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` MapStringNestedMessage map[string]*TestAllTypes_NestedMessage `protobuf:"bytes,71,rep,name=map_string_nested_message,json=mapStringNestedMessage" json:"map_string_nested_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MapStringForeignMessage map[string]*ForeignMessage `protobuf:"bytes,72,rep,name=map_string_foreign_message,json=mapStringForeignMessage" json:"map_string_foreign_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MapStringNestedEnum map[string]TestAllTypes_NestedEnum `protobuf:"bytes,73,rep,name=map_string_nested_enum,json=mapStringNestedEnum" json:"map_string_nested_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.TestAllTypes_NestedEnum"` MapStringForeignEnum map[string]ForeignEnum `protobuf:"bytes,74,rep,name=map_string_foreign_enum,json=mapStringForeignEnum" json:"map_string_foreign_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.ForeignEnum"` // Types that are valid to be assigned to OneofField: // *TestAllTypes_OneofUint32 // *TestAllTypes_OneofNestedMessage // *TestAllTypes_OneofString // *TestAllTypes_OneofBytes // *TestAllTypes_OneofBool // *TestAllTypes_OneofUint64 // *TestAllTypes_OneofFloat // *TestAllTypes_OneofDouble // *TestAllTypes_OneofEnum OneofField isTestAllTypes_OneofField `protobuf_oneof:"oneof_field"` // Well-known types OptionalBoolWrapper *google_protobuf5.BoolValue `protobuf:"bytes,201,opt,name=optional_bool_wrapper,json=optionalBoolWrapper" json:"optional_bool_wrapper,omitempty"` OptionalInt32Wrapper *google_protobuf5.Int32Value `protobuf:"bytes,202,opt,name=optional_int32_wrapper,json=optionalInt32Wrapper" json:"optional_int32_wrapper,omitempty"` OptionalInt64Wrapper *google_protobuf5.Int64Value `protobuf:"bytes,203,opt,name=optional_int64_wrapper,json=optionalInt64Wrapper" json:"optional_int64_wrapper,omitempty"` OptionalUint32Wrapper *google_protobuf5.UInt32Value `protobuf:"bytes,204,opt,name=optional_uint32_wrapper,json=optionalUint32Wrapper" json:"optional_uint32_wrapper,omitempty"` OptionalUint64Wrapper *google_protobuf5.UInt64Value `protobuf:"bytes,205,opt,name=optional_uint64_wrapper,json=optionalUint64Wrapper" json:"optional_uint64_wrapper,omitempty"` OptionalFloatWrapper *google_protobuf5.FloatValue `protobuf:"bytes,206,opt,name=optional_float_wrapper,json=optionalFloatWrapper" json:"optional_float_wrapper,omitempty"` OptionalDoubleWrapper *google_protobuf5.DoubleValue `protobuf:"bytes,207,opt,name=optional_double_wrapper,json=optionalDoubleWrapper" json:"optional_double_wrapper,omitempty"` OptionalStringWrapper *google_protobuf5.StringValue `protobuf:"bytes,208,opt,name=optional_string_wrapper,json=optionalStringWrapper" json:"optional_string_wrapper,omitempty"` OptionalBytesWrapper *google_protobuf5.BytesValue `protobuf:"bytes,209,opt,name=optional_bytes_wrapper,json=optionalBytesWrapper" json:"optional_bytes_wrapper,omitempty"` RepeatedBoolWrapper []*google_protobuf5.BoolValue `protobuf:"bytes,211,rep,name=repeated_bool_wrapper,json=repeatedBoolWrapper" json:"repeated_bool_wrapper,omitempty"` RepeatedInt32Wrapper []*google_protobuf5.Int32Value `protobuf:"bytes,212,rep,name=repeated_int32_wrapper,json=repeatedInt32Wrapper" json:"repeated_int32_wrapper,omitempty"` RepeatedInt64Wrapper []*google_protobuf5.Int64Value `protobuf:"bytes,213,rep,name=repeated_int64_wrapper,json=repeatedInt64Wrapper" json:"repeated_int64_wrapper,omitempty"` RepeatedUint32Wrapper []*google_protobuf5.UInt32Value `protobuf:"bytes,214,rep,name=repeated_uint32_wrapper,json=repeatedUint32Wrapper" json:"repeated_uint32_wrapper,omitempty"` RepeatedUint64Wrapper []*google_protobuf5.UInt64Value `protobuf:"bytes,215,rep,name=repeated_uint64_wrapper,json=repeatedUint64Wrapper" json:"repeated_uint64_wrapper,omitempty"` RepeatedFloatWrapper []*google_protobuf5.FloatValue `protobuf:"bytes,216,rep,name=repeated_float_wrapper,json=repeatedFloatWrapper" json:"repeated_float_wrapper,omitempty"` RepeatedDoubleWrapper []*google_protobuf5.DoubleValue `protobuf:"bytes,217,rep,name=repeated_double_wrapper,json=repeatedDoubleWrapper" json:"repeated_double_wrapper,omitempty"` RepeatedStringWrapper []*google_protobuf5.StringValue `protobuf:"bytes,218,rep,name=repeated_string_wrapper,json=repeatedStringWrapper" json:"repeated_string_wrapper,omitempty"` RepeatedBytesWrapper []*google_protobuf5.BytesValue `protobuf:"bytes,219,rep,name=repeated_bytes_wrapper,json=repeatedBytesWrapper" json:"repeated_bytes_wrapper,omitempty"` OptionalDuration *google_protobuf1.Duration `protobuf:"bytes,301,opt,name=optional_duration,json=optionalDuration" json:"optional_duration,omitempty"` OptionalTimestamp *google_protobuf4.Timestamp `protobuf:"bytes,302,opt,name=optional_timestamp,json=optionalTimestamp" json:"optional_timestamp,omitempty"` OptionalFieldMask *google_protobuf2.FieldMask `protobuf:"bytes,303,opt,name=optional_field_mask,json=optionalFieldMask" json:"optional_field_mask,omitempty"` OptionalStruct *google_protobuf3.Struct `protobuf:"bytes,304,opt,name=optional_struct,json=optionalStruct" json:"optional_struct,omitempty"` OptionalAny *google_protobuf.Any `protobuf:"bytes,305,opt,name=optional_any,json=optionalAny" json:"optional_any,omitempty"` OptionalValue *google_protobuf3.Value `protobuf:"bytes,306,opt,name=optional_value,json=optionalValue" json:"optional_value,omitempty"` RepeatedDuration []*google_protobuf1.Duration `protobuf:"bytes,311,rep,name=repeated_duration,json=repeatedDuration" json:"repeated_duration,omitempty"` RepeatedTimestamp []*google_protobuf4.Timestamp `protobuf:"bytes,312,rep,name=repeated_timestamp,json=repeatedTimestamp" json:"repeated_timestamp,omitempty"` RepeatedFieldmask []*google_protobuf2.FieldMask `protobuf:"bytes,313,rep,name=repeated_fieldmask,json=repeatedFieldmask" json:"repeated_fieldmask,omitempty"` RepeatedStruct []*google_protobuf3.Struct `protobuf:"bytes,324,rep,name=repeated_struct,json=repeatedStruct" json:"repeated_struct,omitempty"` RepeatedAny []*google_protobuf.Any `protobuf:"bytes,315,rep,name=repeated_any,json=repeatedAny" json:"repeated_any,omitempty"` RepeatedValue []*google_protobuf3.Value `protobuf:"bytes,316,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` // Test field-name-to-JSON-name convention. // (protobuf says names can be any valid C/C++ identifier.) Fieldname1 int32 `protobuf:"varint,401,opt,name=fieldname1" json:"fieldname1,omitempty"` FieldName2 int32 `protobuf:"varint,402,opt,name=field_name2,json=fieldName2" json:"field_name2,omitempty"` XFieldName3 int32 `protobuf:"varint,403,opt,name=_field_name3,json=FieldName3" json:"_field_name3,omitempty"` Field_Name4_ int32 `protobuf:"varint,404,opt,name=field__name4_,json=fieldName4" json:"field__name4_,omitempty"` Field0Name5 int32 `protobuf:"varint,405,opt,name=field0name5" json:"field0name5,omitempty"` Field_0Name6 int32 `protobuf:"varint,406,opt,name=field_0_name6,json=field0Name6" json:"field_0_name6,omitempty"` FieldName7 int32 `protobuf:"varint,407,opt,name=fieldName7" json:"fieldName7,omitempty"` FieldName8 int32 `protobuf:"varint,408,opt,name=FieldName8" json:"FieldName8,omitempty"` Field_Name9 int32 `protobuf:"varint,409,opt,name=field_Name9,json=fieldName9" json:"field_Name9,omitempty"` Field_Name10 int32 `protobuf:"varint,410,opt,name=Field_Name10,json=FieldName10" json:"Field_Name10,omitempty"` FIELD_NAME11 int32 `protobuf:"varint,411,opt,name=FIELD_NAME11,json=FIELDNAME11" json:"FIELD_NAME11,omitempty"` FIELDName12 int32 `protobuf:"varint,412,opt,name=FIELD_name12,json=FIELDName12" json:"FIELD_name12,omitempty"` XFieldName13 int32 `protobuf:"varint,413,opt,name=__field_name13,json=FieldName13" json:"__field_name13,omitempty"` X_FieldName14 int32 `protobuf:"varint,414,opt,name=__Field_name14,json=FieldName14" json:"__Field_name14,omitempty"` Field_Name15 int32 `protobuf:"varint,415,opt,name=field__name15,json=fieldName15" json:"field__name15,omitempty"` Field__Name16 int32 `protobuf:"varint,416,opt,name=field__Name16,json=fieldName16" json:"field__Name16,omitempty"` FieldName17__ int32 `protobuf:"varint,417,opt,name=field_name17__,json=fieldName17" json:"field_name17__,omitempty"` FieldName18__ int32 `protobuf:"varint,418,opt,name=Field_name18__,json=FieldName18" json:"Field_name18__,omitempty"` } func (m *TestAllTypes) Reset() { *m = TestAllTypes{} } func (m *TestAllTypes) String() string { return proto.CompactTextString(m) } func (*TestAllTypes) ProtoMessage() {} func (*TestAllTypes) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } type isTestAllTypes_OneofField interface { isTestAllTypes_OneofField() } type TestAllTypes_OneofUint32 struct { OneofUint32 uint32 `protobuf:"varint,111,opt,name=oneof_uint32,json=oneofUint32,oneof"` } type TestAllTypes_OneofNestedMessage struct { OneofNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,112,opt,name=oneof_nested_message,json=oneofNestedMessage,oneof"` } type TestAllTypes_OneofString struct { OneofString string `protobuf:"bytes,113,opt,name=oneof_string,json=oneofString,oneof"` } type TestAllTypes_OneofBytes struct { OneofBytes []byte `protobuf:"bytes,114,opt,name=oneof_bytes,json=oneofBytes,proto3,oneof"` } type TestAllTypes_OneofBool struct { OneofBool bool `protobuf:"varint,115,opt,name=oneof_bool,json=oneofBool,oneof"` } type TestAllTypes_OneofUint64 struct { OneofUint64 uint64 `protobuf:"varint,116,opt,name=oneof_uint64,json=oneofUint64,oneof"` } type TestAllTypes_OneofFloat struct { OneofFloat float32 `protobuf:"fixed32,117,opt,name=oneof_float,json=oneofFloat,oneof"` } type TestAllTypes_OneofDouble struct { OneofDouble float64 `protobuf:"fixed64,118,opt,name=oneof_double,json=oneofDouble,oneof"` } type TestAllTypes_OneofEnum struct { OneofEnum TestAllTypes_NestedEnum `protobuf:"varint,119,opt,name=oneof_enum,json=oneofEnum,enum=conformance.TestAllTypes_NestedEnum,oneof"` } func (*TestAllTypes_OneofUint32) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofNestedMessage) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofString) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofBytes) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofBool) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofUint64) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofFloat) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofDouble) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofEnum) isTestAllTypes_OneofField() {} func (m *TestAllTypes) GetOneofField() isTestAllTypes_OneofField { if m != nil { return m.OneofField } return nil } func (m *TestAllTypes) GetOptionalInt32() int32 { if m != nil { return m.OptionalInt32 } return 0 } func (m *TestAllTypes) GetOptionalInt64() int64 { if m != nil { return m.OptionalInt64 } return 0 } func (m *TestAllTypes) GetOptionalUint32() uint32 { if m != nil { return m.OptionalUint32 } return 0 } func (m *TestAllTypes) GetOptionalUint64() uint64 { if m != nil { return m.OptionalUint64 } return 0 } func (m *TestAllTypes) GetOptionalSint32() int32 { if m != nil { return m.OptionalSint32 } return 0 } func (m *TestAllTypes) GetOptionalSint64() int64 { if m != nil { return m.OptionalSint64 } return 0 } func (m *TestAllTypes) GetOptionalFixed32() uint32 { if m != nil { return m.OptionalFixed32 } return 0 } func (m *TestAllTypes) GetOptionalFixed64() uint64 { if m != nil { return m.OptionalFixed64 } return 0 } func (m *TestAllTypes) GetOptionalSfixed32() int32 { if m != nil { return m.OptionalSfixed32 } return 0 } func (m *TestAllTypes) GetOptionalSfixed64() int64 { if m != nil { return m.OptionalSfixed64 } return 0 } func (m *TestAllTypes) GetOptionalFloat() float32 { if m != nil { return m.OptionalFloat } return 0 } func (m *TestAllTypes) GetOptionalDouble() float64 { if m != nil { return m.OptionalDouble } return 0 } func (m *TestAllTypes) GetOptionalBool() bool { if m != nil { return m.OptionalBool } return false } func (m *TestAllTypes) GetOptionalString() string { if m != nil { return m.OptionalString } return "" } func (m *TestAllTypes) GetOptionalBytes() []byte { if m != nil { return m.OptionalBytes } return nil } func (m *TestAllTypes) GetOptionalNestedMessage() *TestAllTypes_NestedMessage { if m != nil { return m.OptionalNestedMessage } return nil } func (m *TestAllTypes) GetOptionalForeignMessage() *ForeignMessage { if m != nil { return m.OptionalForeignMessage } return nil } func (m *TestAllTypes) GetOptionalNestedEnum() TestAllTypes_NestedEnum { if m != nil { return m.OptionalNestedEnum } return TestAllTypes_FOO } func (m *TestAllTypes) GetOptionalForeignEnum() ForeignEnum { if m != nil { return m.OptionalForeignEnum } return ForeignEnum_FOREIGN_FOO } func (m *TestAllTypes) GetOptionalStringPiece() string { if m != nil { return m.OptionalStringPiece } return "" } func (m *TestAllTypes) GetOptionalCord() string { if m != nil { return m.OptionalCord } return "" } func (m *TestAllTypes) GetRecursiveMessage() *TestAllTypes { if m != nil { return m.RecursiveMessage } return nil } func (m *TestAllTypes) GetRepeatedInt32() []int32 { if m != nil { return m.RepeatedInt32 } return nil } func (m *TestAllTypes) GetRepeatedInt64() []int64 { if m != nil { return m.RepeatedInt64 } return nil } func (m *TestAllTypes) GetRepeatedUint32() []uint32 { if m != nil { return m.RepeatedUint32 } return nil } func (m *TestAllTypes) GetRepeatedUint64() []uint64 { if m != nil { return m.RepeatedUint64 } return nil } func (m *TestAllTypes) GetRepeatedSint32() []int32 { if m != nil { return m.RepeatedSint32 } return nil } func (m *TestAllTypes) GetRepeatedSint64() []int64 { if m != nil { return m.RepeatedSint64 } return nil } func (m *TestAllTypes) GetRepeatedFixed32() []uint32 { if m != nil { return m.RepeatedFixed32 } return nil } func (m *TestAllTypes) GetRepeatedFixed64() []uint64 { if m != nil { return m.RepeatedFixed64 } return nil } func (m *TestAllTypes) GetRepeatedSfixed32() []int32 { if m != nil { return m.RepeatedSfixed32 } return nil } func (m *TestAllTypes) GetRepeatedSfixed64() []int64 { if m != nil { return m.RepeatedSfixed64 } return nil } func (m *TestAllTypes) GetRepeatedFloat() []float32 { if m != nil { return m.RepeatedFloat } return nil } func (m *TestAllTypes) GetRepeatedDouble() []float64 { if m != nil { return m.RepeatedDouble } return nil } func (m *TestAllTypes) GetRepeatedBool() []bool { if m != nil { return m.RepeatedBool } return nil } func (m *TestAllTypes) GetRepeatedString() []string { if m != nil { return m.RepeatedString } return nil } func (m *TestAllTypes) GetRepeatedBytes() [][]byte { if m != nil { return m.RepeatedBytes } return nil } func (m *TestAllTypes) GetRepeatedNestedMessage() []*TestAllTypes_NestedMessage { if m != nil { return m.RepeatedNestedMessage } return nil } func (m *TestAllTypes) GetRepeatedForeignMessage() []*ForeignMessage { if m != nil { return m.RepeatedForeignMessage } return nil } func (m *TestAllTypes) GetRepeatedNestedEnum() []TestAllTypes_NestedEnum { if m != nil { return m.RepeatedNestedEnum } return nil } func (m *TestAllTypes) GetRepeatedForeignEnum() []ForeignEnum { if m != nil { return m.RepeatedForeignEnum } return nil } func (m *TestAllTypes) GetRepeatedStringPiece() []string { if m != nil { return m.RepeatedStringPiece } return nil } func (m *TestAllTypes) GetRepeatedCord() []string { if m != nil { return m.RepeatedCord } return nil } func (m *TestAllTypes) GetMapInt32Int32() map[int32]int32 { if m != nil { return m.MapInt32Int32 } return nil } func (m *TestAllTypes) GetMapInt64Int64() map[int64]int64 { if m != nil { return m.MapInt64Int64 } return nil } func (m *TestAllTypes) GetMapUint32Uint32() map[uint32]uint32 { if m != nil { return m.MapUint32Uint32 } return nil } func (m *TestAllTypes) GetMapUint64Uint64() map[uint64]uint64 { if m != nil { return m.MapUint64Uint64 } return nil } func (m *TestAllTypes) GetMapSint32Sint32() map[int32]int32 { if m != nil { return m.MapSint32Sint32 } return nil } func (m *TestAllTypes) GetMapSint64Sint64() map[int64]int64 { if m != nil { return m.MapSint64Sint64 } return nil } func (m *TestAllTypes) GetMapFixed32Fixed32() map[uint32]uint32 { if m != nil { return m.MapFixed32Fixed32 } return nil } func (m *TestAllTypes) GetMapFixed64Fixed64() map[uint64]uint64 { if m != nil { return m.MapFixed64Fixed64 } return nil } func (m *TestAllTypes) GetMapSfixed32Sfixed32() map[int32]int32 { if m != nil { return m.MapSfixed32Sfixed32 } return nil } func (m *TestAllTypes) GetMapSfixed64Sfixed64() map[int64]int64 { if m != nil { return m.MapSfixed64Sfixed64 } return nil } func (m *TestAllTypes) GetMapInt32Float() map[int32]float32 { if m != nil { return m.MapInt32Float } return nil } func (m *TestAllTypes) GetMapInt32Double() map[int32]float64 { if m != nil { return m.MapInt32Double } return nil } func (m *TestAllTypes) GetMapBoolBool() map[bool]bool { if m != nil { return m.MapBoolBool } return nil } func (m *TestAllTypes) GetMapStringString() map[string]string { if m != nil { return m.MapStringString } return nil } func (m *TestAllTypes) GetMapStringBytes() map[string][]byte { if m != nil { return m.MapStringBytes } return nil } func (m *TestAllTypes) GetMapStringNestedMessage() map[string]*TestAllTypes_NestedMessage { if m != nil { return m.MapStringNestedMessage } return nil } func (m *TestAllTypes) GetMapStringForeignMessage() map[string]*ForeignMessage { if m != nil { return m.MapStringForeignMessage } return nil } func (m *TestAllTypes) GetMapStringNestedEnum() map[string]TestAllTypes_NestedEnum { if m != nil { return m.MapStringNestedEnum } return nil } func (m *TestAllTypes) GetMapStringForeignEnum() map[string]ForeignEnum { if m != nil { return m.MapStringForeignEnum } return nil } func (m *TestAllTypes) GetOneofUint32() uint32 { if x, ok := m.GetOneofField().(*TestAllTypes_OneofUint32); ok { return x.OneofUint32 } return 0 } func (m *TestAllTypes) GetOneofNestedMessage() *TestAllTypes_NestedMessage { if x, ok := m.GetOneofField().(*TestAllTypes_OneofNestedMessage); ok { return x.OneofNestedMessage } return nil } func (m *TestAllTypes) GetOneofString() string { if x, ok := m.GetOneofField().(*TestAllTypes_OneofString); ok { return x.OneofString } return "" } func (m *TestAllTypes) GetOneofBytes() []byte { if x, ok := m.GetOneofField().(*TestAllTypes_OneofBytes); ok { return x.OneofBytes } return nil } func (m *TestAllTypes) GetOneofBool() bool { if x, ok := m.GetOneofField().(*TestAllTypes_OneofBool); ok { return x.OneofBool } return false } func (m *TestAllTypes) GetOneofUint64() uint64 { if x, ok := m.GetOneofField().(*TestAllTypes_OneofUint64); ok { return x.OneofUint64 } return 0 } func (m *TestAllTypes) GetOneofFloat() float32 { if x, ok := m.GetOneofField().(*TestAllTypes_OneofFloat); ok { return x.OneofFloat } return 0 } func (m *TestAllTypes) GetOneofDouble() float64 { if x, ok := m.GetOneofField().(*TestAllTypes_OneofDouble); ok { return x.OneofDouble } return 0 } func (m *TestAllTypes) GetOneofEnum() TestAllTypes_NestedEnum { if x, ok := m.GetOneofField().(*TestAllTypes_OneofEnum); ok { return x.OneofEnum } return TestAllTypes_FOO } func (m *TestAllTypes) GetOptionalBoolWrapper() *google_protobuf5.BoolValue { if m != nil { return m.OptionalBoolWrapper } return nil } func (m *TestAllTypes) GetOptionalInt32Wrapper() *google_protobuf5.Int32Value { if m != nil { return m.OptionalInt32Wrapper } return nil } func (m *TestAllTypes) GetOptionalInt64Wrapper() *google_protobuf5.Int64Value { if m != nil { return m.OptionalInt64Wrapper } return nil } func (m *TestAllTypes) GetOptionalUint32Wrapper() *google_protobuf5.UInt32Value { if m != nil { return m.OptionalUint32Wrapper } return nil } func (m *TestAllTypes) GetOptionalUint64Wrapper() *google_protobuf5.UInt64Value { if m != nil { return m.OptionalUint64Wrapper } return nil } func (m *TestAllTypes) GetOptionalFloatWrapper() *google_protobuf5.FloatValue { if m != nil { return m.OptionalFloatWrapper } return nil } func (m *TestAllTypes) GetOptionalDoubleWrapper() *google_protobuf5.DoubleValue { if m != nil { return m.OptionalDoubleWrapper } return nil } func (m *TestAllTypes) GetOptionalStringWrapper() *google_protobuf5.StringValue { if m != nil { return m.OptionalStringWrapper } return nil } func (m *TestAllTypes) GetOptionalBytesWrapper() *google_protobuf5.BytesValue { if m != nil { return m.OptionalBytesWrapper } return nil } func (m *TestAllTypes) GetRepeatedBoolWrapper() []*google_protobuf5.BoolValue { if m != nil { return m.RepeatedBoolWrapper } return nil } func (m *TestAllTypes) GetRepeatedInt32Wrapper() []*google_protobuf5.Int32Value { if m != nil { return m.RepeatedInt32Wrapper } return nil } func (m *TestAllTypes) GetRepeatedInt64Wrapper() []*google_protobuf5.Int64Value { if m != nil { return m.RepeatedInt64Wrapper } return nil } func (m *TestAllTypes) GetRepeatedUint32Wrapper() []*google_protobuf5.UInt32Value { if m != nil { return m.RepeatedUint32Wrapper } return nil } func (m *TestAllTypes) GetRepeatedUint64Wrapper() []*google_protobuf5.UInt64Value { if m != nil { return m.RepeatedUint64Wrapper } return nil } func (m *TestAllTypes) GetRepeatedFloatWrapper() []*google_protobuf5.FloatValue { if m != nil { return m.RepeatedFloatWrapper } return nil } func (m *TestAllTypes) GetRepeatedDoubleWrapper() []*google_protobuf5.DoubleValue { if m != nil { return m.RepeatedDoubleWrapper } return nil } func (m *TestAllTypes) GetRepeatedStringWrapper() []*google_protobuf5.StringValue { if m != nil { return m.RepeatedStringWrapper } return nil } func (m *TestAllTypes) GetRepeatedBytesWrapper() []*google_protobuf5.BytesValue { if m != nil { return m.RepeatedBytesWrapper } return nil } func (m *TestAllTypes) GetOptionalDuration() *google_protobuf1.Duration { if m != nil { return m.OptionalDuration } return nil } func (m *TestAllTypes) GetOptionalTimestamp() *google_protobuf4.Timestamp { if m != nil { return m.OptionalTimestamp } return nil } func (m *TestAllTypes) GetOptionalFieldMask() *google_protobuf2.FieldMask { if m != nil { return m.OptionalFieldMask } return nil } func (m *TestAllTypes) GetOptionalStruct() *google_protobuf3.Struct { if m != nil { return m.OptionalStruct } return nil } func (m *TestAllTypes) GetOptionalAny() *google_protobuf.Any { if m != nil { return m.OptionalAny } return nil } func (m *TestAllTypes) GetOptionalValue() *google_protobuf3.Value { if m != nil { return m.OptionalValue } return nil } func (m *TestAllTypes) GetRepeatedDuration() []*google_protobuf1.Duration { if m != nil { return m.RepeatedDuration } return nil } func (m *TestAllTypes) GetRepeatedTimestamp() []*google_protobuf4.Timestamp { if m != nil { return m.RepeatedTimestamp } return nil } func (m *TestAllTypes) GetRepeatedFieldmask() []*google_protobuf2.FieldMask { if m != nil { return m.RepeatedFieldmask } return nil } func (m *TestAllTypes) GetRepeatedStruct() []*google_protobuf3.Struct { if m != nil { return m.RepeatedStruct } return nil } func (m *TestAllTypes) GetRepeatedAny() []*google_protobuf.Any { if m != nil { return m.RepeatedAny } return nil } func (m *TestAllTypes) GetRepeatedValue() []*google_protobuf3.Value { if m != nil { return m.RepeatedValue } return nil } func (m *TestAllTypes) GetFieldname1() int32 { if m != nil { return m.Fieldname1 } return 0 } func (m *TestAllTypes) GetFieldName2() int32 { if m != nil { return m.FieldName2 } return 0 } func (m *TestAllTypes) GetXFieldName3() int32 { if m != nil { return m.XFieldName3 } return 0 } func (m *TestAllTypes) GetField_Name4_() int32 { if m != nil { return m.Field_Name4_ } return 0 } func (m *TestAllTypes) GetField0Name5() int32 { if m != nil { return m.Field0Name5 } return 0 } func (m *TestAllTypes) GetField_0Name6() int32 { if m != nil { return m.Field_0Name6 } return 0 } func (m *TestAllTypes) GetFieldName7() int32 { if m != nil { return m.FieldName7 } return 0 } func (m *TestAllTypes) GetFieldName8() int32 { if m != nil { return m.FieldName8 } return 0 } func (m *TestAllTypes) GetField_Name9() int32 { if m != nil { return m.Field_Name9 } return 0 } func (m *TestAllTypes) GetField_Name10() int32 { if m != nil { return m.Field_Name10 } return 0 } func (m *TestAllTypes) GetFIELD_NAME11() int32 { if m != nil { return m.FIELD_NAME11 } return 0 } func (m *TestAllTypes) GetFIELDName12() int32 { if m != nil { return m.FIELDName12 } return 0 } func (m *TestAllTypes) GetXFieldName13() int32 { if m != nil { return m.XFieldName13 } return 0 } func (m *TestAllTypes) GetX_FieldName14() int32 { if m != nil { return m.X_FieldName14 } return 0 } func (m *TestAllTypes) GetField_Name15() int32 { if m != nil { return m.Field_Name15 } return 0 } func (m *TestAllTypes) GetField__Name16() int32 { if m != nil { return m.Field__Name16 } return 0 } func (m *TestAllTypes) GetFieldName17__() int32 { if m != nil { return m.FieldName17__ } return 0 } func (m *TestAllTypes) GetFieldName18__() int32 { if m != nil { return m.FieldName18__ } return 0 } // XXX_OneofFuncs is for the internal use of the proto package. func (*TestAllTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _TestAllTypes_OneofMarshaler, _TestAllTypes_OneofUnmarshaler, _TestAllTypes_OneofSizer, []interface{}{ (*TestAllTypes_OneofUint32)(nil), (*TestAllTypes_OneofNestedMessage)(nil), (*TestAllTypes_OneofString)(nil), (*TestAllTypes_OneofBytes)(nil), (*TestAllTypes_OneofBool)(nil), (*TestAllTypes_OneofUint64)(nil), (*TestAllTypes_OneofFloat)(nil), (*TestAllTypes_OneofDouble)(nil), (*TestAllTypes_OneofEnum)(nil), } } func _TestAllTypes_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*TestAllTypes) // oneof_field switch x := m.OneofField.(type) { case *TestAllTypes_OneofUint32: b.EncodeVarint(111<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.OneofUint32)) case *TestAllTypes_OneofNestedMessage: b.EncodeVarint(112<<3 | proto.WireBytes) if err := b.EncodeMessage(x.OneofNestedMessage); err != nil { return err } case *TestAllTypes_OneofString: b.EncodeVarint(113<<3 | proto.WireBytes) b.EncodeStringBytes(x.OneofString) case *TestAllTypes_OneofBytes: b.EncodeVarint(114<<3 | proto.WireBytes) b.EncodeRawBytes(x.OneofBytes) case *TestAllTypes_OneofBool: t := uint64(0) if x.OneofBool { t = 1 } b.EncodeVarint(115<<3 | proto.WireVarint) b.EncodeVarint(t) case *TestAllTypes_OneofUint64: b.EncodeVarint(116<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.OneofUint64)) case *TestAllTypes_OneofFloat: b.EncodeVarint(117<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.OneofFloat))) case *TestAllTypes_OneofDouble: b.EncodeVarint(118<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.OneofDouble)) case *TestAllTypes_OneofEnum: b.EncodeVarint(119<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.OneofEnum)) case nil: default: return fmt.Errorf("TestAllTypes.OneofField has unexpected type %T", x) } return nil } func _TestAllTypes_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*TestAllTypes) switch tag { case 111: // oneof_field.oneof_uint32 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofField = &TestAllTypes_OneofUint32{uint32(x)} return true, err case 112: // oneof_field.oneof_nested_message if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(TestAllTypes_NestedMessage) err := b.DecodeMessage(msg) m.OneofField = &TestAllTypes_OneofNestedMessage{msg} return true, err case 113: // oneof_field.oneof_string if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.OneofField = &TestAllTypes_OneofString{x} return true, err case 114: // oneof_field.oneof_bytes if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.OneofField = &TestAllTypes_OneofBytes{x} return true, err case 115: // oneof_field.oneof_bool if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofField = &TestAllTypes_OneofBool{x != 0} return true, err case 116: // oneof_field.oneof_uint64 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofField = &TestAllTypes_OneofUint64{x} return true, err case 117: // oneof_field.oneof_float if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.OneofField = &TestAllTypes_OneofFloat{math.Float32frombits(uint32(x))} return true, err case 118: // oneof_field.oneof_double if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.OneofField = &TestAllTypes_OneofDouble{math.Float64frombits(x)} return true, err case 119: // oneof_field.oneof_enum if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofField = &TestAllTypes_OneofEnum{TestAllTypes_NestedEnum(x)} return true, err default: return false, nil } } func _TestAllTypes_OneofSizer(msg proto.Message) (n int) { m := msg.(*TestAllTypes) // oneof_field switch x := m.OneofField.(type) { case *TestAllTypes_OneofUint32: n += proto.SizeVarint(111<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.OneofUint32)) case *TestAllTypes_OneofNestedMessage: s := proto.Size(x.OneofNestedMessage) n += proto.SizeVarint(112<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *TestAllTypes_OneofString: n += proto.SizeVarint(113<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.OneofString))) n += len(x.OneofString) case *TestAllTypes_OneofBytes: n += proto.SizeVarint(114<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.OneofBytes))) n += len(x.OneofBytes) case *TestAllTypes_OneofBool: n += proto.SizeVarint(115<<3 | proto.WireVarint) n += 1 case *TestAllTypes_OneofUint64: n += proto.SizeVarint(116<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.OneofUint64)) case *TestAllTypes_OneofFloat: n += proto.SizeVarint(117<<3 | proto.WireFixed32) n += 4 case *TestAllTypes_OneofDouble: n += proto.SizeVarint(118<<3 | proto.WireFixed64) n += 8 case *TestAllTypes_OneofEnum: n += proto.SizeVarint(119<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.OneofEnum)) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type TestAllTypes_NestedMessage struct { A int32 `protobuf:"varint,1,opt,name=a" json:"a,omitempty"` Corecursive *TestAllTypes `protobuf:"bytes,2,opt,name=corecursive" json:"corecursive,omitempty"` } func (m *TestAllTypes_NestedMessage) Reset() { *m = TestAllTypes_NestedMessage{} } func (m *TestAllTypes_NestedMessage) String() string { return proto.CompactTextString(m) } func (*TestAllTypes_NestedMessage) ProtoMessage() {} func (*TestAllTypes_NestedMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } func (m *TestAllTypes_NestedMessage) GetA() int32 { if m != nil { return m.A } return 0 } func (m *TestAllTypes_NestedMessage) GetCorecursive() *TestAllTypes { if m != nil { return m.Corecursive } return nil } type ForeignMessage struct { C int32 `protobuf:"varint,1,opt,name=c" json:"c,omitempty"` } func (m *ForeignMessage) Reset() { *m = ForeignMessage{} } func (m *ForeignMessage) String() string { return proto.CompactTextString(m) } func (*ForeignMessage) ProtoMessage() {} func (*ForeignMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *ForeignMessage) GetC() int32 { if m != nil { return m.C } return 0 } func init() { proto.RegisterType((*ConformanceRequest)(nil), "conformance.ConformanceRequest") proto.RegisterType((*ConformanceResponse)(nil), "conformance.ConformanceResponse") proto.RegisterType((*TestAllTypes)(nil), "conformance.TestAllTypes") proto.RegisterType((*TestAllTypes_NestedMessage)(nil), "conformance.TestAllTypes.NestedMessage") proto.RegisterType((*ForeignMessage)(nil), "conformance.ForeignMessage") proto.RegisterEnum("conformance.WireFormat", WireFormat_name, WireFormat_value) proto.RegisterEnum("conformance.ForeignEnum", ForeignEnum_name, ForeignEnum_value) proto.RegisterEnum("conformance.TestAllTypes_NestedEnum", TestAllTypes_NestedEnum_name, TestAllTypes_NestedEnum_value) } func init() { proto.RegisterFile("conformance_proto/conformance.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 2737 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5a, 0xd9, 0x72, 0xdb, 0xc8, 0xd5, 0x16, 0x08, 0x59, 0x4b, 0x93, 0x92, 0xa8, 0xd6, 0xd6, 0x96, 0x5d, 0x63, 0x58, 0xb2, 0x7f, 0xd3, 0xf6, 0x8c, 0xac, 0x05, 0x86, 0x65, 0xcf, 0x3f, 0x8e, 0x45, 0x9b, 0xb4, 0xe4, 0x8c, 0x25, 0x17, 0x64, 0x8d, 0xab, 0x9c, 0x0b, 0x06, 0xa6, 0x20, 0x15, 0xc7, 0x24, 0xc1, 0x01, 0x48, 0x4f, 0x94, 0xcb, 0xbc, 0x41, 0xf6, 0x7d, 0xbd, 0xcf, 0x7a, 0x93, 0xa4, 0x92, 0xab, 0x54, 0x6e, 0xb2, 0x27, 0x95, 0x3d, 0x79, 0x85, 0xbc, 0x43, 0x52, 0xbd, 0xa2, 0xbb, 0x01, 0x50, 0xf4, 0x54, 0x0d, 0x25, 0x1e, 0x7c, 0xfd, 0x9d, 0xd3, 0xe7, 0x1c, 0x7c, 0x2d, 0x1c, 0x18, 0x2c, 0xd7, 0x83, 0xf6, 0x51, 0x10, 0xb6, 0xbc, 0x76, 0xdd, 0xaf, 0x75, 0xc2, 0xa0, 0x1b, 0xdc, 0x90, 0x2c, 0x2b, 0xc4, 0x02, 0xf3, 0x92, 0x69, 0xf1, 0xec, 0x71, 0x10, 0x1c, 0x37, 0xfd, 0x1b, 0xe4, 0xd2, 0x8b, 0xde, 0xd1, 0x0d, 0xaf, 0x7d, 0x42, 0x71, 0x8b, 0x6f, 0xe8, 0x97, 0x0e, 0x7b, 0xa1, 0xd7, 0x6d, 0x04, 0x6d, 0x76, 0xdd, 0xd2, 0xaf, 0x1f, 0x35, 0xfc, 0xe6, 0x61, 0xad, 0xe5, 0x45, 0x2f, 0x19, 0xe2, 0xbc, 0x8e, 0x88, 0xba, 0x61, 0xaf, 0xde, 0x65, 0x57, 0x2f, 0xe8, 0x57, 0xbb, 0x8d, 0x96, 0x1f, 0x75, 0xbd, 0x56, 0x27, 0x2b, 0x80, 0x0f, 0x43, 0xaf, 0xd3, 0xf1, 0xc3, 0x88, 0x5e, 0x5f, 0xfa, 0x85, 0x01, 0xe0, 0xfd, 0x78, 0x2f, 0xae, 0xff, 0x41, 0xcf, 0x8f, 0xba, 0xf0, 0x3a, 0x28, 0xf2, 0x15, 0xb5, 0x8e, 0x77, 0xd2, 0x0c, 0xbc, 0x43, 0x64, 0x58, 0x46, 0xa9, 0xb0, 0x3d, 0xe4, 0x4e, 0xf1, 0x2b, 0x4f, 0xe8, 0x05, 0xb8, 0x0c, 0x0a, 0xef, 0x47, 0x41, 0x5b, 0x00, 0x73, 0x96, 0x51, 0x1a, 0xdf, 0x1e, 0x72, 0xf3, 0xd8, 0xca, 0x41, 0x7b, 0x60, 0x21, 0xa4, 0xe4, 0xfe, 0x61, 0x2d, 0xe8, 0x75, 0x3b, 0xbd, 0x6e, 0x8d, 0x78, 0xed, 0x22, 0xd3, 0x32, 0x4a, 0x93, 0xeb, 0x0b, 0x2b, 0x72, 0x9a, 0x9f, 0x35, 0x42, 0xbf, 0x4a, 0x2e, 0xbb, 0x73, 0x62, 0xdd, 0x1e, 0x59, 0x46, 0xcd, 0xe5, 0x71, 0x30, 0xca, 0x1c, 0x2e, 0x7d, 0x2a, 0x07, 0x66, 0x94, 0x4d, 0x44, 0x9d, 0xa0, 0x1d, 0xf9, 0xf0, 0x22, 0xc8, 0x77, 0xbc, 0x30, 0xf2, 0x6b, 0x7e, 0x18, 0x06, 0x21, 0xd9, 0x00, 0x8e, 0x0b, 0x10, 0x63, 0x05, 0xdb, 0xe0, 0x55, 0x30, 0x15, 0xf9, 0x61, 0xc3, 0x6b, 0x36, 0x3e, 0xc9, 0x61, 0x23, 0x0c, 0x36, 0x29, 0x2e, 0x50, 0xe8, 0x65, 0x30, 0x11, 0xf6, 0xda, 0x38, 0xc1, 0x0c, 0xc8, 0xf7, 0x59, 0x60, 0x66, 0x0a, 0x4b, 0x4b, 0x9d, 0x39, 0x68, 0xea, 0x86, 0xd3, 0x52, 0xb7, 0x08, 0x46, 0xa3, 0x97, 0x8d, 0x4e, 0xc7, 0x3f, 0x44, 0x67, 0xd8, 0x75, 0x6e, 0x28, 0x8f, 0x81, 0x91, 0xd0, 0x8f, 0x7a, 0xcd, 0xee, 0xd2, 0x7f, 0xaa, 0xa0, 0xf0, 0xd4, 0x8f, 0xba, 0x5b, 0xcd, 0xe6, 0xd3, 0x93, 0x8e, 0x1f, 0xc1, 0xcb, 0x60, 0x32, 0xe8, 0xe0, 0x5e, 0xf3, 0x9a, 0xb5, 0x46, 0xbb, 0xbb, 0xb1, 0x4e, 0x12, 0x70, 0xc6, 0x9d, 0xe0, 0xd6, 0x1d, 0x6c, 0xd4, 0x61, 0x8e, 0x4d, 0xf6, 0x65, 0x2a, 0x30, 0xc7, 0x86, 0x57, 0xc0, 0x94, 0x80, 0xf5, 0x28, 0x1d, 0xde, 0xd5, 0x84, 0x2b, 0x56, 0x1f, 0x10, 0x6b, 0x02, 0xe8, 0xd8, 0x64, 0x57, 0xc3, 0x2a, 0x50, 0x63, 0x8c, 0x28, 0x23, 0xde, 0xde, 0x74, 0x0c, 0xdc, 0x4f, 0x32, 0x46, 0x94, 0x11, 0xd7, 0x08, 0xaa, 0x40, 0xc7, 0x86, 0x57, 0x41, 0x51, 0x00, 0x8f, 0x1a, 0x9f, 0xf0, 0x0f, 0x37, 0xd6, 0xd1, 0xa8, 0x65, 0x94, 0x46, 0x5d, 0x41, 0x50, 0xa5, 0xe6, 0x24, 0xd4, 0xb1, 0xd1, 0x98, 0x65, 0x94, 0x46, 0x34, 0xa8, 0x63, 0xc3, 0xeb, 0x60, 0x3a, 0x76, 0xcf, 0x69, 0xc7, 0x2d, 0xa3, 0x34, 0xe5, 0x0a, 0x8e, 0x7d, 0x66, 0x4f, 0x01, 0x3b, 0x36, 0x02, 0x96, 0x51, 0x2a, 0xea, 0x60, 0xc7, 0x56, 0x52, 0x7f, 0xd4, 0x0c, 0xbc, 0x2e, 0xca, 0x5b, 0x46, 0x29, 0x17, 0xa7, 0xbe, 0x8a, 0x8d, 0xca, 0xfe, 0x0f, 0x83, 0xde, 0x8b, 0xa6, 0x8f, 0x0a, 0x96, 0x51, 0x32, 0xe2, 0xfd, 0x3f, 0x20, 0x56, 0xb8, 0x0c, 0xc4, 0xca, 0xda, 0x8b, 0x20, 0x68, 0xa2, 0x09, 0xcb, 0x28, 0x8d, 0xb9, 0x05, 0x6e, 0x2c, 0x07, 0x41, 0x53, 0xcd, 0x66, 0x37, 0x6c, 0xb4, 0x8f, 0xd1, 0x24, 0xee, 0x2a, 0x29, 0x9b, 0xc4, 0xaa, 0x44, 0xf7, 0xe2, 0xa4, 0xeb, 0x47, 0x68, 0x0a, 0xb7, 0x71, 0x1c, 0x5d, 0x19, 0x1b, 0x61, 0x0d, 0x2c, 0x08, 0x58, 0x9b, 0xde, 0xde, 0x2d, 0x3f, 0x8a, 0xbc, 0x63, 0x1f, 0x41, 0xcb, 0x28, 0xe5, 0xd7, 0xaf, 0x28, 0x37, 0xb6, 0xdc, 0xa2, 0x2b, 0xbb, 0x04, 0xff, 0x98, 0xc2, 0xdd, 0x39, 0xce, 0xa3, 0x98, 0xe1, 0x01, 0x40, 0x71, 0x96, 0x82, 0xd0, 0x6f, 0x1c, 0xb7, 0x85, 0x87, 0x19, 0xe2, 0xe1, 0x9c, 0xe2, 0xa1, 0x4a, 0x31, 0x9c, 0x75, 0x5e, 0x24, 0x53, 0xb1, 0xc3, 0xf7, 0xc0, 0xac, 0x1e, 0xb7, 0xdf, 0xee, 0xb5, 0xd0, 0x1c, 0x51, 0xa3, 0x4b, 0xa7, 0x05, 0x5d, 0x69, 0xf7, 0x5a, 0x2e, 0x54, 0x23, 0xc6, 0x36, 0xf8, 0x2e, 0x98, 0x4b, 0x84, 0x4b, 0x88, 0xe7, 0x09, 0x31, 0x4a, 0x8b, 0x95, 0x90, 0xcd, 0x68, 0x81, 0x12, 0x36, 0x47, 0x62, 0xa3, 0xd5, 0xaa, 0x75, 0x1a, 0x7e, 0xdd, 0x47, 0x08, 0xd7, 0xac, 0x9c, 0x1b, 0xcb, 0xc5, 0xeb, 0x68, 0xdd, 0x9e, 0xe0, 0xcb, 0xf0, 0x8a, 0xd4, 0x0a, 0xf5, 0x20, 0x3c, 0x44, 0x67, 0x19, 0xde, 0x88, 0xdb, 0xe1, 0x7e, 0x10, 0x1e, 0xc2, 0x2a, 0x98, 0x0e, 0xfd, 0x7a, 0x2f, 0x8c, 0x1a, 0xaf, 0x7c, 0x91, 0xd6, 0x73, 0x24, 0xad, 0x67, 0x33, 0x73, 0xe0, 0x16, 0xc5, 0x1a, 0x9e, 0xce, 0xcb, 0x60, 0x32, 0xf4, 0x3b, 0xbe, 0x87, 0xf3, 0x48, 0x6f, 0xe6, 0x0b, 0x96, 0x89, 0xd5, 0x86, 0x5b, 0x85, 0xda, 0xc8, 0x30, 0xc7, 0x46, 0x96, 0x65, 0x62, 0xb5, 0x91, 0x60, 0x54, 0x1b, 0x04, 0x8c, 0xa9, 0xcd, 0x45, 0xcb, 0xc4, 0x6a, 0xc3, 0xcd, 0xb1, 0xda, 0x28, 0x40, 0xc7, 0x46, 0x4b, 0x96, 0x89, 0xd5, 0x46, 0x06, 0x6a, 0x8c, 0x4c, 0x6d, 0x96, 0x2d, 0x13, 0xab, 0x0d, 0x37, 0xef, 0x27, 0x19, 0x99, 0xda, 0x5c, 0xb2, 0x4c, 0xac, 0x36, 0x32, 0x90, 0xaa, 0x8d, 0x00, 0x72, 0x59, 0xb8, 0x6c, 0x99, 0x58, 0x6d, 0xb8, 0x5d, 0x52, 0x1b, 0x15, 0xea, 0xd8, 0xe8, 0xff, 0x2c, 0x13, 0xab, 0x8d, 0x02, 0xa5, 0x6a, 0x13, 0xbb, 0xe7, 0xb4, 0x57, 0x2c, 0x13, 0xab, 0x8d, 0x08, 0x40, 0x52, 0x1b, 0x0d, 0xec, 0xd8, 0xa8, 0x64, 0x99, 0x58, 0x6d, 0x54, 0x30, 0x55, 0x9b, 0x38, 0x08, 0xa2, 0x36, 0x57, 0x2d, 0x13, 0xab, 0x8d, 0x08, 0x81, 0xab, 0x8d, 0x80, 0x31, 0xb5, 0xb9, 0x66, 0x99, 0x58, 0x6d, 0xb8, 0x39, 0x56, 0x1b, 0x01, 0x24, 0x6a, 0x73, 0xdd, 0x32, 0xb1, 0xda, 0x70, 0x23, 0x57, 0x9b, 0x38, 0x42, 0xaa, 0x36, 0x6f, 0x5a, 0x26, 0x56, 0x1b, 0x11, 0x9f, 0x50, 0x9b, 0x98, 0x8d, 0xa8, 0xcd, 0x5b, 0x96, 0x89, 0xd5, 0x46, 0xd0, 0x71, 0xb5, 0x11, 0x30, 0x4d, 0x6d, 0x56, 0x2d, 0xf3, 0xb5, 0xd4, 0x86, 0xf3, 0x24, 0xd4, 0x26, 0xce, 0x92, 0xa6, 0x36, 0x6b, 0xc4, 0x43, 0x7f, 0xb5, 0x11, 0xc9, 0x4c, 0xa8, 0x8d, 0x1e, 0x37, 0x11, 0x85, 0x0d, 0xcb, 0x1c, 0x5c, 0x6d, 0xd4, 0x88, 0xb9, 0xda, 0x24, 0xc2, 0x25, 0xc4, 0x36, 0x21, 0xee, 0xa3, 0x36, 0x5a, 0xa0, 0x5c, 0x6d, 0xb4, 0x6a, 0x31, 0xb5, 0x71, 0x70, 0xcd, 0xa8, 0xda, 0xa8, 0x75, 0x13, 0x6a, 0x23, 0xd6, 0x11, 0xb5, 0xb9, 0xc5, 0xf0, 0x46, 0xdc, 0x0e, 0x44, 0x6d, 0x9e, 0x82, 0xa9, 0x96, 0xd7, 0xa1, 0x02, 0xc1, 0x64, 0x62, 0x93, 0x24, 0xf5, 0xcd, 0xec, 0x0c, 0x3c, 0xf6, 0x3a, 0x44, 0x3b, 0xc8, 0x47, 0xa5, 0xdd, 0x0d, 0x4f, 0xdc, 0x89, 0x96, 0x6c, 0x93, 0x58, 0x1d, 0x9b, 0xa9, 0xca, 0xed, 0xc1, 0x58, 0x1d, 0x9b, 0x7c, 0x28, 0xac, 0xcc, 0x06, 0x9f, 0x83, 0x69, 0xcc, 0x4a, 0xe5, 0x87, 0xab, 0xd0, 0x1d, 0xc2, 0xbb, 0xd2, 0x97, 0x97, 0x4a, 0x13, 0xfd, 0xa4, 0xcc, 0x38, 0x3c, 0xd9, 0x2a, 0x73, 0x3b, 0x36, 0x17, 0xae, 0xb7, 0x07, 0xe4, 0x76, 0x6c, 0xfa, 0xa9, 0x72, 0x73, 0x2b, 0xe7, 0xa6, 0x22, 0xc7, 0xb5, 0xee, 0xff, 0x07, 0xe0, 0xa6, 0x02, 0xb8, 0xaf, 0xc5, 0x2d, 0x5b, 0x65, 0x6e, 0xc7, 0xe6, 0xf2, 0xf8, 0xce, 0x80, 0xdc, 0x8e, 0xbd, 0xaf, 0xc5, 0x2d, 0x5b, 0xe1, 0xc7, 0xc1, 0x0c, 0xe6, 0x66, 0xda, 0x26, 0x24, 0xf5, 0x2e, 0x61, 0x5f, 0xed, 0xcb, 0xce, 0x74, 0x96, 0xfd, 0xa0, 0xfc, 0x38, 0x50, 0xd5, 0xae, 0x78, 0x70, 0x6c, 0xa1, 0xc4, 0x1f, 0x19, 0xd4, 0x83, 0x63, 0xb3, 0x1f, 0x9a, 0x07, 0x61, 0x87, 0x47, 0x60, 0x8e, 0xe4, 0x87, 0x6f, 0x42, 0x28, 0xf8, 0x3d, 0xe2, 0x63, 0xbd, 0x7f, 0x8e, 0x18, 0x98, 0xff, 0xa4, 0x5e, 0x70, 0xc8, 0xfa, 0x15, 0xd5, 0x0f, 0xae, 0x04, 0xdf, 0xcb, 0xd6, 0xc0, 0x7e, 0x1c, 0x9b, 0xff, 0xd4, 0xfd, 0xc4, 0x57, 0xd4, 0xfb, 0x95, 0x1e, 0x1a, 0xe5, 0x41, 0xef, 0x57, 0x72, 0x9c, 0x68, 0xf7, 0x2b, 0x3d, 0x62, 0x9e, 0x81, 0x62, 0xcc, 0xca, 0xce, 0x98, 0xfb, 0x84, 0xf6, 0xad, 0xd3, 0x69, 0xe9, 0xe9, 0x43, 0x79, 0x27, 0x5b, 0x8a, 0x11, 0xee, 0x02, 0xec, 0x89, 0x9c, 0x46, 0xf4, 0x48, 0x7a, 0x40, 0x58, 0xaf, 0xf5, 0x65, 0xc5, 0xe7, 0x14, 0xfe, 0x9f, 0x52, 0xe6, 0x5b, 0xb1, 0x45, 0xb4, 0x3b, 0x95, 0x42, 0x76, 0x7e, 0x55, 0x06, 0x69, 0x77, 0x02, 0xa5, 0x9f, 0x52, 0xbb, 0x4b, 0x56, 0x9e, 0x04, 0xc6, 0x4d, 0x8f, 0xbc, 0xea, 0x00, 0x49, 0xa0, 0xcb, 0xc9, 0x69, 0x18, 0x27, 0x41, 0x32, 0xc2, 0x0e, 0x38, 0x2b, 0x11, 0x6b, 0x87, 0xe4, 0x43, 0xe2, 0xe1, 0xe6, 0x00, 0x1e, 0x94, 0x63, 0x91, 0x7a, 0x9a, 0x6f, 0xa5, 0x5e, 0x84, 0x11, 0x58, 0x94, 0x3c, 0xea, 0xa7, 0xe6, 0x36, 0x71, 0xe9, 0x0c, 0xe0, 0x52, 0x3d, 0x33, 0xa9, 0xcf, 0x85, 0x56, 0xfa, 0x55, 0x78, 0x0c, 0xe6, 0x93, 0xdb, 0x24, 0x47, 0xdf, 0xce, 0x20, 0xf7, 0x80, 0xb4, 0x0d, 0x7c, 0xf4, 0x49, 0xf7, 0x80, 0x76, 0x05, 0xbe, 0x0f, 0x16, 0x52, 0x76, 0x47, 0x3c, 0x3d, 0x22, 0x9e, 0x36, 0x06, 0xdf, 0x5a, 0xec, 0x6a, 0xb6, 0x95, 0x72, 0x09, 0x2e, 0x83, 0x42, 0xd0, 0xf6, 0x83, 0x23, 0x7e, 0xdc, 0x04, 0xf8, 0x11, 0x7b, 0x7b, 0xc8, 0xcd, 0x13, 0x2b, 0x3b, 0x3c, 0x3e, 0x06, 0x66, 0x29, 0x48, 0xab, 0x6d, 0xe7, 0xb5, 0x1e, 0xb7, 0xb6, 0x87, 0x5c, 0x48, 0x68, 0xd4, 0x5a, 0x8a, 0x08, 0x58, 0xb7, 0x7f, 0xc0, 0x27, 0x12, 0xc4, 0xca, 0x7a, 0xf7, 0x22, 0xa0, 0x5f, 0x59, 0xdb, 0x86, 0x6c, 0xbc, 0x01, 0x88, 0x91, 0x76, 0xe1, 0x05, 0x00, 0x18, 0x04, 0xdf, 0x87, 0x11, 0x7e, 0x10, 0xdd, 0x1e, 0x72, 0xc7, 0x29, 0x02, 0xdf, 0x5b, 0xca, 0x56, 0x1d, 0x1b, 0x75, 0x2d, 0xa3, 0x34, 0xac, 0x6c, 0xd5, 0xb1, 0x63, 0x47, 0x54, 0x7b, 0x7a, 0xf8, 0xf1, 0x58, 0x38, 0xa2, 0x62, 0x22, 0x78, 0x98, 0x90, 0xbc, 0xc2, 0x8f, 0xc6, 0x82, 0x87, 0x09, 0x43, 0x85, 0x47, 0x43, 0xca, 0xf6, 0xe1, 0xe0, 0x8f, 0x78, 0x22, 0x66, 0x52, 0x9e, 0x3d, 0xe9, 0x69, 0x8c, 0x88, 0x0c, 0x9b, 0xa6, 0xa1, 0x5f, 0x19, 0x24, 0xf7, 0x8b, 0x2b, 0x74, 0xdc, 0xb6, 0xc2, 0xe7, 0x3c, 0x2b, 0x78, 0xab, 0xef, 0x79, 0xcd, 0x9e, 0x1f, 0x3f, 0xa6, 0x61, 0xd3, 0x33, 0xba, 0x0e, 0xba, 0x60, 0x5e, 0x9d, 0xd1, 0x08, 0xc6, 0x5f, 0x1b, 0xec, 0xd1, 0x56, 0x67, 0x24, 0x7a, 0x47, 0x29, 0x67, 0x95, 0x49, 0x4e, 0x06, 0xa7, 0x63, 0x0b, 0xce, 0xdf, 0xf4, 0xe1, 0x74, 0xec, 0x24, 0xa7, 0x63, 0x73, 0xce, 0x03, 0xe9, 0x21, 0xbf, 0xa7, 0x06, 0xfa, 0x5b, 0x4a, 0x7a, 0x3e, 0x41, 0x7a, 0x20, 0x45, 0x3a, 0xa7, 0x0e, 0x89, 0xb2, 0x68, 0xa5, 0x58, 0x7f, 0xd7, 0x8f, 0x96, 0x07, 0x3b, 0xa7, 0x8e, 0x94, 0xd2, 0x32, 0x40, 0x1a, 0x47, 0xb0, 0xfe, 0x3e, 0x2b, 0x03, 0xa4, 0x97, 0xb4, 0x0c, 0x10, 0x5b, 0x5a, 0xa8, 0xb4, 0xd3, 0x04, 0xe9, 0x1f, 0xb2, 0x42, 0xa5, 0xcd, 0xa7, 0x85, 0x4a, 0x8d, 0x69, 0xb4, 0x4c, 0x61, 0x38, 0xed, 0x1f, 0xb3, 0x68, 0xe9, 0x4d, 0xa8, 0xd1, 0x52, 0x63, 0x5a, 0x06, 0xc8, 0x3d, 0x2a, 0x58, 0xff, 0x94, 0x95, 0x01, 0x72, 0xdb, 0x6a, 0x19, 0x20, 0x36, 0xce, 0xb9, 0x27, 0x3d, 0x1c, 0x28, 0xcd, 0xff, 0x67, 0x83, 0xc8, 0x60, 0xdf, 0xe6, 0x97, 0x1f, 0x0a, 0xa5, 0x20, 0xd5, 0x91, 0x81, 0x60, 0xfc, 0x8b, 0xc1, 0x9e, 0xb4, 0xfa, 0x35, 0xbf, 0x32, 0x58, 0xc8, 0xe0, 0x94, 0x1a, 0xea, 0xaf, 0x7d, 0x38, 0x45, 0xf3, 0x2b, 0x53, 0x08, 0xa9, 0x46, 0xda, 0x30, 0x42, 0x90, 0xfe, 0x8d, 0x92, 0x9e, 0xd2, 0xfc, 0xea, 0xcc, 0x22, 0x8b, 0x56, 0x8a, 0xf5, 0xef, 0xfd, 0x68, 0x45, 0xf3, 0xab, 0x13, 0x8e, 0xb4, 0x0c, 0xa8, 0xcd, 0xff, 0x8f, 0xac, 0x0c, 0xc8, 0xcd, 0xaf, 0x0c, 0x03, 0xd2, 0x42, 0xd5, 0x9a, 0xff, 0x9f, 0x59, 0xa1, 0x2a, 0xcd, 0xaf, 0x8e, 0x0e, 0xd2, 0x68, 0xb5, 0xe6, 0xff, 0x57, 0x16, 0xad, 0xd2, 0xfc, 0xea, 0xb3, 0x68, 0x5a, 0x06, 0xd4, 0xe6, 0xff, 0x77, 0x56, 0x06, 0xe4, 0xe6, 0x57, 0x06, 0x0e, 0x9c, 0xf3, 0xa1, 0x34, 0xd7, 0xe5, 0xef, 0x70, 0xd0, 0x77, 0x73, 0x6c, 0x4e, 0x96, 0xd8, 0x3b, 0x43, 0xc4, 0x33, 0x5f, 0x6e, 0x81, 0x8f, 0x80, 0x18, 0x1a, 0xd6, 0xc4, 0xcb, 0x1a, 0xf4, 0xbd, 0x5c, 0xc6, 0xf9, 0xf1, 0x94, 0x43, 0x5c, 0xe1, 0x5f, 0x98, 0xe0, 0x47, 0xc1, 0x8c, 0x34, 0xc4, 0xe6, 0x2f, 0x8e, 0xd0, 0xf7, 0xb3, 0xc8, 0xaa, 0x18, 0xf3, 0xd8, 0x8b, 0x5e, 0xc6, 0x64, 0xc2, 0x04, 0xb7, 0xd4, 0xb9, 0x70, 0xaf, 0xde, 0x45, 0x3f, 0xa0, 0x44, 0x0b, 0x69, 0x45, 0xe8, 0xd5, 0xbb, 0xca, 0xc4, 0xb8, 0x57, 0xef, 0xc2, 0x4d, 0x20, 0x66, 0x8b, 0x35, 0xaf, 0x7d, 0x82, 0x7e, 0x48, 0xd7, 0xcf, 0x26, 0xd6, 0x6f, 0xb5, 0x4f, 0xdc, 0x3c, 0x87, 0x6e, 0xb5, 0x4f, 0xe0, 0x5d, 0x69, 0xd6, 0xfc, 0x0a, 0x97, 0x01, 0xfd, 0x88, 0xae, 0x9d, 0x4f, 0xac, 0xa5, 0x55, 0x12, 0xd3, 0x4d, 0xf2, 0x15, 0x97, 0x27, 0x6e, 0x50, 0x5e, 0x9e, 0x1f, 0xe7, 0x48, 0xb5, 0xfb, 0x95, 0x47, 0xf4, 0xa5, 0x54, 0x1e, 0x41, 0x14, 0x97, 0xe7, 0x27, 0xb9, 0x0c, 0x85, 0x93, 0xca, 0xc3, 0x97, 0xc5, 0xe5, 0x91, 0xb9, 0x48, 0x79, 0x48, 0x75, 0x7e, 0x9a, 0xc5, 0x25, 0x55, 0x27, 0x1e, 0x0a, 0xb2, 0x55, 0xb8, 0x3a, 0xf2, 0xad, 0x82, 0xab, 0xf3, 0x4b, 0x4a, 0x94, 0x5d, 0x1d, 0xe9, 0xee, 0x60, 0xd5, 0x11, 0x14, 0xb8, 0x3a, 0x3f, 0xa3, 0xeb, 0x33, 0xaa, 0xc3, 0xa1, 0xac, 0x3a, 0x62, 0x25, 0xad, 0xce, 0xcf, 0xe9, 0xda, 0xcc, 0xea, 0x70, 0x38, 0xad, 0xce, 0x05, 0x00, 0xc8, 0xfe, 0xdb, 0x5e, 0xcb, 0x5f, 0x43, 0x9f, 0x36, 0xc9, 0x6b, 0x28, 0xc9, 0x04, 0x2d, 0x90, 0xa7, 0xfd, 0x8b, 0xbf, 0xae, 0xa3, 0xcf, 0xc8, 0x88, 0x5d, 0x6c, 0x82, 0x17, 0x41, 0xa1, 0x16, 0x43, 0x36, 0xd0, 0x67, 0x19, 0xa4, 0xca, 0x21, 0x1b, 0x70, 0x09, 0x4c, 0x50, 0x04, 0x81, 0xd8, 0x35, 0xf4, 0x39, 0x9d, 0x86, 0xfc, 0x3d, 0x49, 0xbe, 0xad, 0x62, 0xc8, 0x4d, 0xf4, 0x79, 0x8a, 0x90, 0x6d, 0x70, 0x99, 0xd3, 0xac, 0x12, 0x1e, 0x07, 0x7d, 0x41, 0x01, 0x61, 0x1e, 0x47, 0xec, 0x08, 0x7f, 0xbb, 0x85, 0xbe, 0xa8, 0x3b, 0xba, 0x85, 0x01, 0x22, 0xb4, 0x4d, 0xf4, 0x25, 0x3d, 0xda, 0xcd, 0x78, 0xcb, 0xf8, 0xeb, 0x6d, 0xf4, 0x65, 0x9d, 0xe2, 0x36, 0x5c, 0x02, 0x85, 0xaa, 0x40, 0xac, 0xad, 0xa2, 0xaf, 0xb0, 0x38, 0x04, 0xc9, 0xda, 0x2a, 0xc1, 0xec, 0x54, 0xde, 0x7d, 0x50, 0xdb, 0xdd, 0x7a, 0x5c, 0x59, 0x5b, 0x43, 0x5f, 0xe5, 0x18, 0x6c, 0xa4, 0xb6, 0x18, 0x43, 0x72, 0xbd, 0x8e, 0xbe, 0xa6, 0x60, 0x88, 0x0d, 0x5e, 0x02, 0x93, 0x35, 0x29, 0xbf, 0x6b, 0x1b, 0xe8, 0xeb, 0x09, 0x6f, 0x1b, 0x14, 0x55, 0x8d, 0x51, 0x36, 0xfa, 0x46, 0x02, 0x65, 0xc7, 0x09, 0xa4, 0xa0, 0x9b, 0xe8, 0x9b, 0x72, 0x02, 0x09, 0x48, 0xca, 0x32, 0xdd, 0x9d, 0x83, 0xbe, 0x95, 0x00, 0x39, 0xd8, 0x9f, 0x14, 0xd3, 0xad, 0x5a, 0x0d, 0x7d, 0x3b, 0x81, 0xba, 0x85, 0x51, 0x52, 0x4c, 0x9b, 0xb5, 0x1a, 0xfa, 0x4e, 0x22, 0xaa, 0xcd, 0xc5, 0xe7, 0x60, 0x42, 0x7d, 0xd0, 0x29, 0x00, 0xc3, 0x63, 0x6f, 0x44, 0x0d, 0x0f, 0xbe, 0x0d, 0xf2, 0xf5, 0x40, 0xbc, 0xd4, 0x40, 0xb9, 0xd3, 0x5e, 0x80, 0xc8, 0xe8, 0xc5, 0x7b, 0x00, 0x26, 0x87, 0x94, 0xb0, 0x08, 0xcc, 0x97, 0xfe, 0x09, 0x73, 0x81, 0x7f, 0x85, 0xb3, 0xe0, 0x0c, 0xbd, 0x7d, 0x72, 0xc4, 0x46, 0xbf, 0xdc, 0xc9, 0x6d, 0x1a, 0x31, 0x83, 0x3c, 0x90, 0x94, 0x19, 0xcc, 0x14, 0x06, 0x53, 0x66, 0x28, 0x83, 0xd9, 0xb4, 0xd1, 0xa3, 0xcc, 0x31, 0x91, 0xc2, 0x31, 0x91, 0xce, 0xa1, 0x8c, 0x18, 0x65, 0x8e, 0xe1, 0x14, 0x8e, 0xe1, 0x24, 0x47, 0x62, 0x94, 0x28, 0x73, 0x4c, 0xa7, 0x70, 0x4c, 0xa7, 0x73, 0x28, 0x23, 0x43, 0x99, 0x03, 0xa6, 0x70, 0x40, 0x99, 0xe3, 0x01, 0x98, 0x4f, 0x1f, 0x0c, 0xca, 0x2c, 0xa3, 0x29, 0x2c, 0xa3, 0x19, 0x2c, 0xea, 0xf0, 0x4f, 0x66, 0x19, 0x49, 0x61, 0x19, 0x91, 0x59, 0xaa, 0x00, 0x65, 0x8d, 0xf7, 0x64, 0x9e, 0xa9, 0x14, 0x9e, 0xa9, 0x2c, 0x1e, 0x6d, 0x7c, 0x27, 0xf3, 0x14, 0x53, 0x78, 0x8a, 0xa9, 0xdd, 0x26, 0x0f, 0xe9, 0x4e, 0xeb, 0xd7, 0x9c, 0xcc, 0xb0, 0x05, 0x66, 0x52, 0xe6, 0x71, 0xa7, 0x51, 0x18, 0x32, 0xc5, 0x5d, 0x50, 0xd4, 0x87, 0x6f, 0xf2, 0xfa, 0xb1, 0x94, 0xf5, 0x63, 0x29, 0x4d, 0xa2, 0x0f, 0xda, 0x64, 0x8e, 0xf1, 0x14, 0x8e, 0xf1, 0xe4, 0x36, 0xf4, 0x89, 0xda, 0x69, 0x14, 0x05, 0x99, 0x22, 0x04, 0xe7, 0xfa, 0x8c, 0xcc, 0x52, 0xa8, 0xde, 0x91, 0xa9, 0x5e, 0xe3, 0x7d, 0x95, 0xe4, 0xf3, 0x18, 0x9c, 0xef, 0x37, 0x33, 0x4b, 0x71, 0xba, 0xa6, 0x3a, 0xed, 0xfb, 0x0a, 0x4b, 0x72, 0xd4, 0xa4, 0x0d, 0x97, 0x36, 0x2b, 0x4b, 0x71, 0x72, 0x47, 0x76, 0x32, 0xe8, 0x4b, 0x2d, 0xc9, 0x9b, 0x07, 0xce, 0x66, 0xce, 0xcb, 0x52, 0xdc, 0xad, 0xa8, 0xee, 0xb2, 0x5f, 0x75, 0xc5, 0x2e, 0x96, 0x6e, 0x03, 0x20, 0x4d, 0xf6, 0x46, 0x81, 0x59, 0xdd, 0xdb, 0x2b, 0x0e, 0xe1, 0x5f, 0xca, 0x5b, 0x6e, 0xd1, 0xa0, 0xbf, 0x3c, 0x2f, 0xe6, 0xb0, 0xbb, 0xdd, 0xca, 0xc3, 0xe2, 0x7f, 0xf9, 0x7f, 0x46, 0x79, 0x42, 0x8c, 0xa2, 0xf0, 0xa9, 0xb2, 0xf4, 0x06, 0x98, 0xd4, 0x06, 0x92, 0x05, 0x60, 0xd4, 0xf9, 0x81, 0x52, 0xbf, 0x76, 0x13, 0x80, 0xf8, 0xdf, 0x30, 0xc1, 0x29, 0x90, 0x3f, 0xd8, 0xdd, 0x7f, 0x52, 0xb9, 0xbf, 0x53, 0xdd, 0xa9, 0x3c, 0x28, 0x0e, 0xc1, 0x02, 0x18, 0x7b, 0xe2, 0xee, 0x3d, 0xdd, 0x2b, 0x1f, 0x54, 0x8b, 0x06, 0x1c, 0x03, 0xc3, 0x8f, 0xf6, 0xf7, 0x76, 0x8b, 0xb9, 0x6b, 0xf7, 0x40, 0x5e, 0x9e, 0x07, 0x4e, 0x81, 0x7c, 0x75, 0xcf, 0xad, 0xec, 0x3c, 0xdc, 0xad, 0xd1, 0x48, 0x25, 0x03, 0x8d, 0x58, 0x31, 0x3c, 0x2f, 0xe6, 0xca, 0x17, 0xc1, 0x85, 0x7a, 0xd0, 0x4a, 0xfc, 0x61, 0x26, 0x25, 0xe7, 0xc5, 0x08, 0xb1, 0x6e, 0xfc, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x33, 0xc2, 0x0c, 0xb6, 0xeb, 0x26, 0x00, 0x00, } �����������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/_conformance/conformance.go��������������������������0000644�0610621�0607500�00000011611�13172163407�027646� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // conformance implements the conformance test subprocess protocol as // documented in conformance.proto. package main import ( "encoding/binary" "fmt" "io" "os" pb "github.com/golang/protobuf/_conformance/conformance_proto" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" ) func main() { var sizeBuf [4]byte inbuf := make([]byte, 0, 4096) outbuf := proto.NewBuffer(nil) for { if _, err := io.ReadFull(os.Stdin, sizeBuf[:]); err == io.EOF { break } else if err != nil { fmt.Fprintln(os.Stderr, "go conformance: read request:", err) os.Exit(1) } size := binary.LittleEndian.Uint32(sizeBuf[:]) if int(size) > cap(inbuf) { inbuf = make([]byte, size) } inbuf = inbuf[:size] if _, err := io.ReadFull(os.Stdin, inbuf); err != nil { fmt.Fprintln(os.Stderr, "go conformance: read request:", err) os.Exit(1) } req := new(pb.ConformanceRequest) if err := proto.Unmarshal(inbuf, req); err != nil { fmt.Fprintln(os.Stderr, "go conformance: parse request:", err) os.Exit(1) } res := handle(req) if err := outbuf.Marshal(res); err != nil { fmt.Fprintln(os.Stderr, "go conformance: marshal response:", err) os.Exit(1) } binary.LittleEndian.PutUint32(sizeBuf[:], uint32(len(outbuf.Bytes()))) if _, err := os.Stdout.Write(sizeBuf[:]); err != nil { fmt.Fprintln(os.Stderr, "go conformance: write response:", err) os.Exit(1) } if _, err := os.Stdout.Write(outbuf.Bytes()); err != nil { fmt.Fprintln(os.Stderr, "go conformance: write response:", err) os.Exit(1) } outbuf.Reset() } } var jsonMarshaler = jsonpb.Marshaler{ OrigName: true, } func handle(req *pb.ConformanceRequest) *pb.ConformanceResponse { var err error var msg pb.TestAllTypes switch p := req.Payload.(type) { case *pb.ConformanceRequest_ProtobufPayload: err = proto.Unmarshal(p.ProtobufPayload, &msg) case *pb.ConformanceRequest_JsonPayload: err = jsonpb.UnmarshalString(p.JsonPayload, &msg) if err != nil && err.Error() == "unmarshaling Any not supported yet" { return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_Skipped{ Skipped: err.Error(), }, } } default: return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_RuntimeError{ RuntimeError: "unknown request payload type", }, } } if err != nil { return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_ParseError{ ParseError: err.Error(), }, } } switch req.RequestedOutputFormat { case pb.WireFormat_PROTOBUF: p, err := proto.Marshal(&msg) if err != nil { return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_SerializeError{ SerializeError: err.Error(), }, } } return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_ProtobufPayload{ ProtobufPayload: p, }, } case pb.WireFormat_JSON: p, err := jsonMarshaler.MarshalToString(&msg) if err != nil { return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_SerializeError{ SerializeError: err.Error(), }, } } return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_JsonPayload{ JsonPayload: p, }, } default: return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_RuntimeError{ RuntimeError: "unknown output format", }, } } } �����������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/_conformance/Makefile��������������������������������0000644�0610621�0607500�00000004133�13172163407�026466� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2016 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. regenerate: protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any,Mgoogle/protobuf/duration.proto=github.com/golang/protobuf/ptypes/duration,Mgoogle/protobuf/struct.proto=github.com/golang/protobuf/ptypes/struct,Mgoogle/protobuf/timestamp.proto=github.com/golang/protobuf/ptypes/timestamp,Mgoogle/protobuf/wrappers.proto=github.com/golang/protobuf/ptypes/wrappers,Mgoogle/protobuf/field_mask.proto=google.golang.org/genproto/protobuf:. conformance_proto/conformance.proto �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/README.md��������������������������������������������0000644�0610621�0607500�00000023136�13172163407�023660� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers [![Build Status](https://travis-ci.org/golang/protobuf.svg?branch=master)](https://travis-ci.org/golang/protobuf) Google's data interchange format. Copyright 2010 The Go Authors. https://github.com/golang/protobuf This package and the code it generates requires at least Go 1.4. This software implements Go bindings for protocol buffers. For information about protocol buffers themselves, see https://developers.google.com/protocol-buffers/ ## Installation ## To use this software, you must: - Install the standard C++ implementation of protocol buffers from https://developers.google.com/protocol-buffers/ - Of course, install the Go compiler and tools from https://golang.org/ See https://golang.org/doc/install for details or, if you are using gccgo, follow the instructions at https://golang.org/doc/install/gccgo - Grab the code from the repository and install the proto package. The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`. The compiler plugin, protoc-gen-go, will be installed in $GOBIN, defaulting to $GOPATH/bin. It must be in your $PATH for the protocol compiler, protoc, to find it. This software has two parts: a 'protocol compiler plugin' that generates Go source files that, once compiled, can access and manage protocol buffers; and a library that implements run-time support for encoding (marshaling), decoding (unmarshaling), and accessing protocol buffers. There is support for gRPC in Go using protocol buffers. See the note at the bottom of this file for details. There are no insertion points in the plugin. ## Using protocol buffers with Go ## Once the software is installed, there are two steps to using it. First you must compile the protocol buffer definitions and then import them, with the support library, into your program. To compile the protocol buffer definition, run protoc with the --go_out parameter set to the directory you want to output the Go code to. protoc --go_out=. *.proto The generated files will be suffixed .pb.go. See the Test code below for an example using such a file. The package comment for the proto library contains text describing the interface provided in Go for protocol buffers. Here is an edited version. ========== The proto package converts data structures to and from the wire format of protocol buffers. It works in concert with the Go source code generated for .proto files by the protocol compiler. A summary of the properties of the protocol buffer interface for a protocol buffer variable v: - Names are turned from camel_case to CamelCase for export. - There are no methods on v to set fields; just treat them as structure fields. - There are getters that return a field's value if set, and return the field's default value if unset. The getters work even if the receiver is a nil message. - The zero value for a struct is its correct initialization state. All desired fields must be set before marshaling. - A Reset() method will restore a protobuf struct to its zero state. - Non-repeated fields are pointers to the values; nil means unset. That is, optional or required field int32 f becomes F *int32. - Repeated fields are slices. - Helper functions are available to aid the setting of fields. Helpers for getting values are superseded by the GetFoo methods and their use is deprecated. msg.Foo = proto.String("hello") // set field - Constants are defined to hold the default values of all fields that have them. They have the form Default_StructName_FieldName. Because the getter methods handle defaulted values, direct use of these constants should be rare. - Enums are given type names and maps from names to values. Enum values are prefixed with the enum's type name. Enum types have a String method, and a Enum method to assist in message construction. - Nested groups and enums have type names prefixed with the name of the surrounding message type. - Extensions are given descriptor names that start with E_, followed by an underscore-delimited list of the nested messages that contain it (if any) followed by the CamelCased name of the extension field itself. HasExtension, ClearExtension, GetExtension and SetExtension are functions for manipulating extensions. - Oneof field sets are given a single field in their message, with distinguished wrapper types for each possible field value. - Marshal and Unmarshal are functions to encode and decode the wire format. When the .proto file specifies `syntax="proto3"`, there are some differences: - Non-repeated fields of non-message type are values instead of pointers. - Enum types do not get an Enum method. Consider file test.proto, containing ```proto syntax = "proto2"; package example; enum FOO { X = 17; }; message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } } ``` To create and play with a Test object from the example package, ```go package main import ( "log" "github.com/golang/protobuf/proto" "path/to/example" ) func main() { test := &example.Test { Label: proto.String("hello"), Type: proto.Int32(17), Reps: []int64{1, 2, 3}, Optionalgroup: &example.Test_OptionalGroup { RequiredField: proto.String("good bye"), }, } data, err := proto.Marshal(test) if err != nil { log.Fatal("marshaling error: ", err) } newTest := &example.Test{} err = proto.Unmarshal(data, newTest) if err != nil { log.Fatal("unmarshaling error: ", err) } // Now test and newTest contain the same data. if test.GetLabel() != newTest.GetLabel() { log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } // etc. } ``` ## Parameters ## To pass extra parameters to the plugin, use a comma-separated parameter list separated from the output directory by a colon: protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto - `import_prefix=xxx` - a prefix that is added onto the beginning of all imports. Useful for things like generating protos in a subdirectory, or regenerating vendored protobufs in-place. - `import_path=foo/bar` - used as the package if no input files declare `go_package`. If it contains slashes, everything up to the rightmost slash is ignored. - `plugins=plugin1+plugin2` - specifies the list of sub-plugins to load. The only plugin in this repo is `grpc`. - `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is associated with Go package quux/shme. This is subject to the import_prefix parameter. ## gRPC Support ## If a proto file specifies RPC services, protoc-gen-go can be instructed to generate code compatible with gRPC (http://www.grpc.io/). To do this, pass the `plugins` parameter to protoc-gen-go; the usual way is to insert it into the --go_out argument to protoc: protoc --go_out=plugins=grpc:. *.proto ## Compatibility ## The library and the generated code are expected to be stable over time. However, we reserve the right to make breaking changes without notice for the following reasons: - Security. A security issue in the specification or implementation may come to light whose resolution requires breaking compatibility. We reserve the right to address such security issues. - Unspecified behavior. There are some aspects of the Protocol Buffers specification that are undefined. Programs that depend on such unspecified behavior may break in future releases. - Specification errors or changes. If it becomes necessary to address an inconsistency, incompleteness, or change in the Protocol Buffers specification, resolving the issue could affect the meaning or legality of existing programs. We reserve the right to address such issues, including updating the implementations. - Bugs. If the library has a bug that violates the specification, a program that depends on the buggy behavior may break if the bug is fixed. We reserve the right to fix such bugs. - Adding methods or fields to generated structs. These may conflict with field names that already exist in a schema, causing applications to break. When the code generator encounters a field in the schema that would collide with a generated field or method name, the code generator will append an underscore to the generated field or method name. - Adding, removing, or changing methods or fields in generated structs that start with `XXX`. These parts of the generated code are exported out of necessity, but should not be considered part of the public API. - Adding, removing, or changing unexported symbols in generated code. Any breaking changes outside of these will be announced 6 months in advance to protobuf@googlegroups.com. You should, whenever possible, use generated code created by the `protoc-gen-go` tool built at the same commit as the `proto` package. The `proto` package declares package-level constants in the form `ProtoPackageIsVersionX`. Application code and generated code may depend on one of these constants to ensure that compilation will fail if the available version of the proto library is too old. Whenever we make a change to the generated code that requires newer library support, in the same commit we will increment the version number of the generated code and declare a new package-level constant whose name incorporates the latest version number. Removing a compatibility constant is considered a breaking change and would be subject to the announcement policy stated above. The `protoc-gen-go/generator` package exposes a plugin interface, which is used by the gRPC code generation. This interface is not supported and is subject to incompatible changes without notice. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/Makefile���������������������������������������������0000644�0610621�0607500�00000004101�13172163407�024030� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. all: install install: go install ./proto ./jsonpb ./ptypes go install ./protoc-gen-go test: go test ./proto ./jsonpb ./ptypes make -C protoc-gen-go/testdata test clean: go clean ./... nuke: go clean -i ./... regenerate: make -C protoc-gen-go/descriptor regenerate make -C protoc-gen-go/plugin regenerate make -C protoc-gen-go/testdata regenerate make -C proto/testdata regenerate make -C jsonpb/jsonpb_test_proto regenerate make -C _conformance regenerate ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/Make.protobuf����������������������������������������0000644�0610621�0607500�00000003643�13172163407�025041� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/protobuf # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Includable Makefile to add a rule for generating .pb.go files from .proto files # (Google protocol buffer descriptions). # Typical use if myproto.proto is a file in package mypackage in this directory: # # include $(GOROOT)/src/pkg/github.com/golang/protobuf/Make.protobuf %.pb.go: %.proto protoc --go_out=. $< ���������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/LICENSE����������������������������������������������0000644�0610621�0607500�00000003057�13172163407�023406� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Go support for Protocol Buffers - Google's data interchange format Copyright 2010 The Go Authors. All rights reserved. https://github.com/golang/protobuf Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/CONTRIBUTORS�����������������������������������������0000644�0610621�0607500�00000000252�13172163407�024253� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at http://tip.golang.org/CONTRIBUTORS. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/AUTHORS����������������������������������������������0000644�0610621�0607500�00000000255�13172163407�023446� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This source code refers to The Go Authors for copyright purposes. # The master list of authors is in the main Go distribution, # visible at http://tip.golang.org/AUTHORS. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/golang/protobuf/.travis.yml������������������������������������������0000644�0610621�0607500�00000000536�13172163407�024511� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������sudo: false language: go go: - 1.6.x - 1.7.x - 1.8.x - 1.9.x install: - go get -v -d -t github.com/golang/protobuf/... - curl -L https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip -o /tmp/protoc.zip - unzip /tmp/protoc.zip -d $HOME/protoc env: - PATH=$HOME/protoc/bin:$PATH script: - make all test ������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/rogpeppe/������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163312�021101� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/rogpeppe/fastuuid/���������������������������������������������������0000755�0610621�0607500�00000000000�13172163312�022725� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/rogpeppe/fastuuid/uuid_test.go���������������������������������������0000644�0610621�0607500�00000001643�13172163312�025265� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package fastuuid import ( "bytes" "crypto/rand" "testing" ) func TestUUID(t *testing.T) { var buf [24]byte for i := range buf { buf[i] = byte(i) + 1 } oldReader := rand.Reader rand.Reader = bytes.NewReader(buf[:]) g, err := NewGenerator() rand.Reader = oldReader if err != nil { t.Fatalf("cannot make generator: %v", err) } uuid := g.Next() buf[0] = 1 ^ 1 if uuid != buf { t.Fatalf("unexpected UUID; got %x; want %x", uuid, buf) } uuid = g.Next() buf[0] = 1 ^ 2 if uuid != buf { t.Fatalf("unexpected next UUID; got %x; want %x", uuid, buf) } } func TestUniqueness(t *testing.T) { g := MustNewGenerator() m := make(map[[24]byte]int) for i := 0; i < 65537; i++ { uuid := g.Next() if old, ok := m[uuid]; ok { t.Fatalf("non-unique uuid seq at %d, other %d", i, old) } m[uuid] = i } } func BenchmarkNext(b *testing.B) { g := MustNewGenerator() for i := 0; i < b.N; i++ { g.Next() } } ���������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/rogpeppe/fastuuid/uuid.go��������������������������������������������0000644�0610621�0607500�00000003247�13172163312�024230� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package fastuuid provides fast UUID generation of 192 bit // universally unique identifiers. It does not provide // formatting or parsing of the identifiers (it is assumed // that a simple hexadecimal or base64 representation // is sufficient, for which adequate functionality exists elsewhere). // // Note that the generated UUIDs are not unguessable - each // UUID generated from a Generator is adjacent to the // previously generated UUID. // // It ignores RFC 4122. package fastuuid import ( "crypto/rand" "encoding/binary" "errors" "sync/atomic" ) // Generator represents a UUID generator that // generates UUIDs in sequence from a random starting // point. type Generator struct { seed [24]byte counter uint64 } // NewGenerator returns a new Generator. // It can fail if the crypto/rand read fails. func NewGenerator() (*Generator, error) { var g Generator _, err := rand.Read(g.seed[:]) if err != nil { return nil, errors.New("cannot generate random seed: " + err.Error()) } return &g, nil } // MustNewGenerator is like NewGenerator // but panics on failure. func MustNewGenerator() *Generator { g, err := NewGenerator() if err != nil { panic(err) } return g } // Next returns the next UUID from the generator. // Only the first 8 bytes can differ from the previous // UUID, so taking a slice of the first 16 bytes // is sufficient to provide a somewhat less secure 128 bit UUID. // // It is OK to call this method concurrently. func (g *Generator) Next() [24]byte { x := atomic.AddUint64(&g.counter, 1) var counterBytes [8]byte binary.LittleEndian.PutUint64(counterBytes[:], x) uuid := g.seed for i, b := range counterBytes { uuid[i] ^= b } return uuid } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/rogpeppe/fastuuid/README.md������������������������������������������0000644�0610621�0607500�00000002411�13172163312�024202� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# fastuuid -- import "github.com/rogpeppe/fastuuid" Package fastuuid provides fast UUID generation of 192 bit universally unique identifiers. It does not provide formatting or parsing of the identifiers (it is assumed that a simple hexadecimal or base64 representation is sufficient, for which adequate functionality exists elsewhere). Note that the generated UUIDs are not unguessable - each UUID generated from a Generator is adjacent to the previously generated UUID. It ignores RFC 4122. ## Usage #### type Generator ```go type Generator struct { } ``` Generator represents a UUID generator that generates UUIDs in sequence from a random starting point. #### func MustNewGenerator ```go func MustNewGenerator() *Generator ``` MustNewGenerator is like NewGenerator but panics on failure. #### func NewGenerator ```go func NewGenerator() (*Generator, error) ``` NewGenerator returns a new Generator. It can fail if the crypto/rand read fails. #### func (*Generator) Next ```go func (g *Generator) Next() [24]byte ``` Next returns the next UUID from the generator. Only the first 8 bytes can differ from the previous UUID, so taking a slice of the first 16 bytes is sufficient to provide a somewhat less secure 128 bit UUID. It is OK to call this method concurrently. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/rogpeppe/fastuuid/LICENSE��������������������������������������������0000644�0610621�0607500�00000002745�13172163312�023742� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright © 2014, Roger Peppe All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of this project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ���������������������������lxd-2.0.11/dist/src/github.com/juju/����������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163411�020235� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�020727� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/writerutil/�������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�023141� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/writerutil/writerutil_test.go�������������������������������0000644�0610621�0607500�00000003164�13172163412�026745� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2016 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package writerutil import ( "io" "testing" ) func TestPrefixSuffixSaver(t *testing.T) { tests := []struct { N int writes []string want string }{ { N: 2, writes: nil, want: "", }, { N: 2, writes: []string{"a"}, want: "a", }, { N: 2, writes: []string{"abc", "d"}, want: "abcd", }, { N: 2, writes: []string{"abc", "d", "e"}, want: "ab\n... omitting 1 bytes ...\nde", }, { N: 2, writes: []string{"ab______________________yz"}, want: "ab\n... omitting 22 bytes ...\nyz", }, { N: 2, writes: []string{"ab_______________________y", "z"}, want: "ab\n... omitting 23 bytes ...\nyz", }, } for i, tt := range tests { w := &PrefixSuffixSaver{N: tt.N} for _, s := range tt.writes { n, err := io.WriteString(w, s) if err != nil || n != len(s) { t.Errorf("%d. WriteString(%q) = %v, %v; want %v, %v", i, s, n, err, len(s), nil) } } if got := string(w.Bytes()); got != tt.want { t.Errorf("%d. Bytes = %q; want %q", i, got, tt.want) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/writerutil/writerutil.go������������������������������������0000644�0610621�0607500�00000006162�13172163412�025707� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2016 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package writerutil contains io.Writer types. package writerutil // import "github.com/juju/go4/writerutil" import ( "bytes" "strconv" ) // PrefixSuffixSaver is an io.Writer which retains the first N bytes // and the last N bytes written to it. The Bytes method reconstructs // it with a pretty error message. // It is copied from os/exec/exec.go of the Go stdlib. type PrefixSuffixSaver struct { N int // max size of prefix or suffix prefix []byte suffix []byte // ring buffer once len(suffix) == N suffixOff int // offset to write into suffix skipped int64 // TODO(bradfitz): we could keep one large []byte and use part of it for // the prefix, reserve space for the '... Omitting N bytes ...' message, // then the ring buffer suffix, and just rearrange the ring buffer // suffix when Bytes() is called, but it doesn't seem worth it for // now just for error messages. It's only ~64KB anyway. } func (w *PrefixSuffixSaver) Write(p []byte) (n int, err error) { lenp := len(p) p = w.fill(&w.prefix, p) // Only keep the last w.N bytes of suffix data. if overage := len(p) - w.N; overage > 0 { p = p[overage:] w.skipped += int64(overage) } p = w.fill(&w.suffix, p) // w.suffix is full now if p is non-empty. Overwrite it in a circle. for len(p) > 0 { // 0, 1, or 2 iterations. n := copy(w.suffix[w.suffixOff:], p) p = p[n:] w.skipped += int64(n) w.suffixOff += n if w.suffixOff == w.N { w.suffixOff = 0 } } return lenp, nil } // fill appends up to len(p) bytes of p to *dst, such that *dst does not // grow larger than w.N. It returns the un-appended suffix of p. func (w *PrefixSuffixSaver) fill(dst *[]byte, p []byte) (pRemain []byte) { if remain := w.N - len(*dst); remain > 0 { add := minInt(len(p), remain) *dst = append(*dst, p[:add]...) p = p[add:] } return p } // Bytes returns a slice of the bytes, or a copy of the bytes, retained by w. // If more bytes than could be retained were written to w, it returns a // concatenation of the N first bytes, a message for how many bytes were dropped, // and the N last bytes. func (w *PrefixSuffixSaver) Bytes() []byte { if w.suffix == nil { return w.prefix } if w.skipped == 0 { return append(w.prefix, w.suffix...) } var buf bytes.Buffer buf.Grow(len(w.prefix) + len(w.suffix) + 50) buf.Write(w.prefix) buf.WriteString("\n... omitting ") buf.WriteString(strconv.FormatInt(w.skipped, 10)) buf.WriteString(" bytes ...\n") buf.Write(w.suffix[w.suffixOff:]) buf.Write(w.suffix[:w.suffixOff]) return buf.Bytes() } func minInt(a, b int) int { if a < b { return a } return b } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/wkfs/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�021701� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/wkfs/wkfs.go������������������������������������������������0000644�0610621�0607500�00000010000�13172163412�023171� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package wkfs implements the pluggable "well-known filesystem" abstraction layer. // // Instead of accessing files directly through the operating system // using os.Open or os.Stat, code should use wkfs.Open or wkfs.Stat, // which first try to intercept paths at well-known top-level // directories representing previously-registered mount types, // otherwise fall through to the operating system paths. // // Example of top-level well-known directories that might be // registered include /gcs/bucket/object for Google Cloud Storage or // /s3/bucket/object for AWS S3. package wkfs import ( "io" "io/ioutil" "os" "strings" ) type File interface { io.Reader io.ReaderAt io.Closer io.Seeker Name() string Stat() (os.FileInfo, error) } type FileWriter interface { io.Writer io.Closer } func Open(name string) (File, error) { return fs(name).Open(name) } func Stat(name string) (os.FileInfo, error) { return fs(name).Stat(name) } func Lstat(name string) (os.FileInfo, error) { return fs(name).Lstat(name) } func MkdirAll(path string, perm os.FileMode) error { return fs(path).MkdirAll(path, perm) } func OpenFile(name string, flag int, perm os.FileMode) (FileWriter, error) { return fs(name).OpenFile(name, flag, perm) } func Create(name string) (FileWriter, error) { // like os.Create but WRONLY instead of RDWR because we don't // expose a Reader here. return OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) } func fs(name string) FileSystem { for pfx, fs := range wkFS { if strings.HasPrefix(name, pfx) { return fs } } return osFS{} } type osFS struct{} func (osFS) Open(name string) (File, error) { return os.Open(name) } func (osFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) } func (osFS) Lstat(name string) (os.FileInfo, error) { return os.Lstat(name) } func (osFS) MkdirAll(path string, perm os.FileMode) error { return os.MkdirAll(path, perm) } func (osFS) OpenFile(name string, flag int, perm os.FileMode) (FileWriter, error) { return os.OpenFile(name, flag, perm) } type FileSystem interface { Open(name string) (File, error) OpenFile(name string, flag int, perm os.FileMode) (FileWriter, error) Stat(name string) (os.FileInfo, error) Lstat(name string) (os.FileInfo, error) MkdirAll(path string, perm os.FileMode) error } // well-known filesystems var wkFS = map[string]FileSystem{} // RegisterFS registers a well-known filesystem. It intercepts // anything beginning with prefix (which must start and end with a // forward slash) and forwards it to fs. func RegisterFS(prefix string, fs FileSystem) { if !strings.HasPrefix(prefix, "/") || !strings.HasSuffix(prefix, "/") { panic("bogus prefix: " + prefix) } if _, dup := wkFS[prefix]; dup { panic("duplication registration of " + prefix) } wkFS[prefix] = fs } // WriteFile writes data to a file named by filename. // If the file does not exist, WriteFile creates it with permissions perm; // otherwise WriteFile truncates it before writing. func WriteFile(filename string, data []byte, perm os.FileMode) error { f, err := OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) if err != nil { return err } n, err := f.Write(data) if err == nil && n < len(data) { err = io.ErrShortWrite } if err1 := f.Close(); err == nil { err = err1 } return err } func ReadFile(filename string) ([]byte, error) { f, err := Open(filename) if err != nil { return nil, err } defer f.Close() return ioutil.ReadAll(f) } lxd-2.0.11/dist/src/github.com/juju/go4/wkfs/gcs/���������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022455� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/wkfs/gcs/gcs_test.go����������������������������������������0000644�0610621�0607500�00000004361�13172163412�024623� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gcs import ( "bytes" "flag" "io" "strings" "testing" "github.com/juju/go4/wkfs" "golang.org/x/net/context" "google.golang.org/cloud/compute/metadata" "google.golang.org/cloud/storage" ) var flagBucket = flag.String("bucket", "", "Google Cloud Storage bucket where to run the tests. It should be empty.") func TestWriteRead(t *testing.T) { if !metadata.OnGCE() { t.Skipf("Not testing on GCE") } if *flagBucket == "" { t.Skipf("No bucket specified") } ctx := context.Background() cl, err := storage.NewClient(ctx) list, err := cl.Bucket(*flagBucket).List(ctx, nil) if err != nil { t.Fatal(err) } if len(list.Results) > 0 { t.Fatalf("Bucket %v is not empty, aborting test.", *flagBucket) } filename := "camli-gcs_test.txt" defer func() { if err := cl.Bucket(*flagBucket).Object(filename).Delete(ctx); err != nil { t.Fatalf("error while cleaning up: %v", err) } }() // Write to camli-gcs_test.txt gcsPath := "/gcs/" + *flagBucket + "/" + filename f, err := wkfs.Create(gcsPath) if err != nil { t.Fatalf("error creating %v: %v", gcsPath, err) } data := "Hello World" if _, err := io.Copy(f, strings.NewReader(data)); err != nil { t.Fatalf("error writing to %v: %v", gcsPath, err) } if err := f.Close(); err != nil { t.Fatalf("error closing %v: %v", gcsPath, err) } // Read back from camli-gcs_test.txt g, err := wkfs.Open(gcsPath) if err != nil { t.Fatalf("error opening %v: %v", gcsPath, err) } defer g.Close() var buf bytes.Buffer if _, err := io.Copy(&buf, g); err != nil { t.Fatalf("error reading %v: %v", gcsPath, err) } if buf.String() != data { t.Fatalf("error with %v contents: got %v, wanted %v", gcsPath, buf.String(), data) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/wkfs/gcs/gcs.go���������������������������������������������0000644�0610621�0607500�00000012104�13172163412�023556� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package gcs registers a Google Cloud Storage filesystem at the // well-known /gcs/ filesystem path if the current machine is running // on Google Compute Engine. // // It was initially only meant for small files, and as such, it can only // read files smaller than 1MB for now. package gcs import ( "bytes" "fmt" "io" "io/ioutil" "os" "path" "strings" "time" "github.com/juju/go4/wkfs" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/cloud" "google.golang.org/cloud/compute/metadata" "google.golang.org/cloud/storage" ) // Max size for all files read, because we use a bytes.Reader as our file // reader, instead of storage.NewReader. This is because we get all wkfs.File // methods for free by embedding a bytes.Reader. This filesystem was only supposed // to be for configuration data only, so this is ok for now. const maxSize = 1 << 20 func init() { if !metadata.OnGCE() { return } hc, err := google.DefaultClient(oauth2.NoContext) if err != nil { registerBrokenFS(fmt.Errorf("could not get http client for context: %v", err)) return } projID, err := metadata.ProjectID() if projID == "" || err != nil { registerBrokenFS(fmt.Errorf("could not get GCE project ID: %v", err)) return } ctx := cloud.NewContext(projID, hc) sc, err := storage.NewClient(ctx) if err != nil { registerBrokenFS(fmt.Errorf("could not get cloud storage client: %v", err)) return } wkfs.RegisterFS("/gcs/", &gcsFS{ ctx: ctx, sc: sc, }) } type gcsFS struct { ctx context.Context sc *storage.Client err error // sticky error } func registerBrokenFS(err error) { wkfs.RegisterFS("/gcs/", &gcsFS{ err: err, }) } func (fs *gcsFS) parseName(name string) (bucket, fileName string, err error) { if fs.err != nil { return "", "", fs.err } name = strings.TrimPrefix(name, "/gcs/") i := strings.Index(name, "/") if i < 0 { return name, "", nil } return name[:i], name[i+1:], nil } // Open opens the named file for reading. It returns an error if the file size // is larger than 1 << 20. func (fs *gcsFS) Open(name string) (wkfs.File, error) { bucket, fileName, err := fs.parseName(name) if err != nil { return nil, err } obj := fs.sc.Bucket(bucket).Object(fileName) attrs, err := obj.Attrs(fs.ctx) if err != nil { return nil, err } size := attrs.Size if size > maxSize { return nil, fmt.Errorf("file %s too large (%d bytes) for /gcs/ filesystem", name, size) } rc, err := obj.NewReader(fs.ctx) if err != nil { return nil, err } defer rc.Close() slurp, err := ioutil.ReadAll(io.LimitReader(rc, size)) if err != nil { return nil, err } return &file{ name: name, Reader: bytes.NewReader(slurp), }, nil } func (fs *gcsFS) Stat(name string) (os.FileInfo, error) { return fs.Lstat(name) } func (fs *gcsFS) Lstat(name string) (os.FileInfo, error) { bucket, fileName, err := fs.parseName(name) if err != nil { return nil, err } attrs, err := fs.sc.Bucket(bucket).Object(fileName).Attrs(fs.ctx) if err == storage.ErrObjectNotExist { return nil, os.ErrNotExist } if err != nil { return nil, err } return &statInfo{ name: attrs.Name, size: attrs.Size, }, nil } func (fs *gcsFS) MkdirAll(path string, perm os.FileMode) error { return nil } func (fs *gcsFS) OpenFile(name string, flag int, perm os.FileMode) (wkfs.FileWriter, error) { bucket, fileName, err := fs.parseName(name) if err != nil { return nil, err } switch flag { case os.O_WRONLY | os.O_CREATE | os.O_EXCL: case os.O_WRONLY | os.O_CREATE | os.O_TRUNC: default: return nil, fmt.Errorf("Unsupported OpenFlag flag mode %d on Google Cloud Storage", flag) } if flag&os.O_EXCL != 0 { if _, err := fs.Stat(name); err == nil { return nil, os.ErrExist } } // TODO(mpl): consider adding perm to the object's ObjectAttrs.Metadata return fs.sc.Bucket(bucket).Object(fileName).NewWriter(fs.ctx), nil } type statInfo struct { name string size int64 isDir bool modtime time.Time } func (si *statInfo) IsDir() bool { return si.isDir } func (si *statInfo) ModTime() time.Time { return si.modtime } func (si *statInfo) Mode() os.FileMode { return 0644 } func (si *statInfo) Name() string { return path.Base(si.name) } func (si *statInfo) Size() int64 { return si.size } func (si *statInfo) Sys() interface{} { return nil } type file struct { name string *bytes.Reader } func (*file) Close() error { return nil } func (f *file) Name() string { return path.Base(f.name) } func (f *file) Stat() (os.FileInfo, error) { panic("Stat not implemented on /gcs/ files yet") } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/types/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022073� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/types/types_test.go�����������������������������������������0000644�0610621�0607500�00000005125�13172163412�024630� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package types import ( "encoding/json" "strings" "testing" "time" ) func TestTime3339(t *testing.T) { tm := time.Unix(123, 456) t3 := Time3339(tm) type O struct { SomeTime Time3339 `json:"someTime"` } o := &O{SomeTime: t3} got, err := json.Marshal(o) if err != nil { t.Fatal(err) } goodEnc := "{\"someTime\":\"1970-01-01T00:02:03.000000456Z\"}" if string(got) != goodEnc { t.Errorf("Encoding wrong.\n Got: %q\nWant: %q", got, goodEnc) } ogot := &O{} err = json.Unmarshal([]byte(goodEnc), ogot) if err != nil { t.Fatal(err) } if !tm.Equal(ogot.SomeTime.Time()) { t.Errorf("Unmarshal got time %v; want %v", ogot.SomeTime.Time(), tm) } } func TestTime3339_Marshal(t *testing.T) { tests := []struct { in time.Time want string }{ {time.Time{}, "null"}, {time.Unix(1, 0), `"1970-01-01T00:00:01Z"`}, } for i, tt := range tests { got, err := Time3339(tt.in).MarshalJSON() if err != nil { t.Errorf("%d. marshal(%v) got error: %v", i, tt.in, err) continue } if string(got) != tt.want { t.Errorf("%d. marshal(%v) = %q; want %q", i, tt.in, got, tt.want) } } } func TestTime3339_empty(t *testing.T) { tests := []struct { enc string z bool }{ {enc: "null", z: true}, {enc: `""`, z: true}, {enc: "0000-00-00T00:00:00Z", z: true}, {enc: "0001-01-01T00:00:00Z", z: true}, {enc: "1970-01-01T00:00:00Z", z: true}, {enc: "2001-02-03T04:05:06Z", z: false}, {enc: "2001-02-03T04:05:06+06:00", z: false}, {enc: "2001-02-03T04:05:06-06:00", z: false}, {enc: "2001-02-03T04:05:06.123456789Z", z: false}, {enc: "2001-02-03T04:05:06.123456789+06:00", z: false}, {enc: "2001-02-03T04:05:06.123456789-06:00", z: false}, } for _, tt := range tests { var tm Time3339 enc := tt.enc if strings.Contains(enc, "T") { enc = "\"" + enc + "\"" } err := json.Unmarshal([]byte(enc), &tm) if err != nil { t.Errorf("unmarshal %q = %v", enc, err) } if tm.IsAnyZero() != tt.z { t.Errorf("unmarshal %q = %v (%d), %v; zero=%v; want %v", tt.enc, tm.Time(), tm.Time().Unix(), err, !tt.z, tt.z) } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/types/types.go����������������������������������������������0000644�0610621�0607500�00000006644�13172163412�023600� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package types provides various common types. package types import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "strings" "sync" "time" ) var null_b = []byte("null") // NopCloser is an io.Closer that does nothing. var NopCloser io.Closer = CloseFunc(func() error { return nil }) // EmptyBody is a ReadCloser that returns EOF on Read and does nothing // on Close. var EmptyBody io.ReadCloser = ioutil.NopCloser(strings.NewReader("")) // Time3339 is a time.Time which encodes to and from JSON // as an RFC 3339 time in UTC. type Time3339 time.Time var ( _ json.Marshaler = Time3339{} _ json.Unmarshaler = (*Time3339)(nil) ) func (t Time3339) String() string { return time.Time(t).UTC().Format(time.RFC3339Nano) } func (t Time3339) MarshalJSON() ([]byte, error) { if t.Time().IsZero() { return null_b, nil } return json.Marshal(t.String()) } func (t *Time3339) UnmarshalJSON(b []byte) error { if bytes.Equal(b, null_b) { *t = Time3339{} return nil } if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' { return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b) } s := string(b[1 : len(b)-1]) if s == "" { *t = Time3339{} return nil } tm, err := time.Parse(time.RFC3339Nano, s) if err != nil { if strings.HasPrefix(s, "0000-00-00T00:00:00") { *t = Time3339{} return nil } return err } *t = Time3339(tm) return nil } // ParseTime3339OrZero parses a string in RFC3339 format. If it's invalid, // the zero time value is returned instead. func ParseTime3339OrZero(v string) Time3339 { t, err := time.Parse(time.RFC3339Nano, v) if err != nil { return Time3339{} } return Time3339(t) } func ParseTime3339OrNil(v string) *Time3339 { t, err := time.Parse(time.RFC3339Nano, v) if err != nil { return nil } tm := Time3339(t) return &tm } // Time returns the time as a time.Time with slightly less stutter // than a manual conversion. func (t Time3339) Time() time.Time { return time.Time(t) } // IsZero returns whether the time is Go zero or Unix zero. func (t *Time3339) IsAnyZero() bool { return t == nil || time.Time(*t).IsZero() || time.Time(*t).Unix() == 0 } // ByTime sorts times. type ByTime []time.Time func (s ByTime) Len() int { return len(s) } func (s ByTime) Less(i, j int) bool { return s[i].Before(s[j]) } func (s ByTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // NewOnceCloser returns a Closer wrapping c which only calls Close on c // once. Subsequent calls to Close return nil. func NewOnceCloser(c io.Closer) io.Closer { return &onceCloser{c: c} } type onceCloser struct { mu sync.Mutex c io.Closer } func (c *onceCloser) Close() error { c.mu.Lock() defer c.mu.Unlock() if c.c == nil { return nil } err := c.c.Close() c.c = nil return err } // CloseFunc implements io.Closer with a function. type CloseFunc func() error func (fn CloseFunc) Close() error { return fn() } ��������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/���������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022601� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/syncutil.go����������������������������������������0000644�0610621�0607500�00000001255�13172163412�025005� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package syncutil contains synchronization utilities. package syncutil // import "github.com/juju/go4/syncutil" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/syncdebug/�����������������������������������������0000755�0610621�0607500�00000000000�13172163412�024564� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/syncdebug/syncdebug_test.go������������������������0000644�0610621�0607500�00000001476�13172163412�030145� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package syncdebug import "testing" func TestGoroutineID(t *testing.T) { c := make(chan int64, 2) c <- GoroutineID() go func() { c <- GoroutineID() }() if a, b := <-c, <-c; a == b { t.Errorf("both goroutine IDs were %d; expected different", a) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/syncdebug/syncdebug.go�����������������������������0000644�0610621�0607500�00000010750�13172163412�027101� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package syncdebug contains facilities for debugging synchronization // problems. package syncdebug import ( "bytes" "fmt" "log" "runtime" "sync" "sync/atomic" "time" "github.com/juju/go4/strutil" ) // RWMutexTracker is a sync.RWMutex that tracks who owns the current // exclusive lock. It's used for debugging deadlocks. type RWMutexTracker struct { mu sync.RWMutex // Atomic counters for number waiting and having read and write locks. nwaitr int32 nwaitw int32 nhaver int32 nhavew int32 // should always be 0 or 1 logOnce sync.Once hmu sync.Mutex holder []byte holdr map[int64]bool // goroutines holding read lock } const stackBufSize = 16 << 20 var stackBuf = make(chan []byte, 8) func getBuf() []byte { select { case b := <-stackBuf: return b[:stackBufSize] default: return make([]byte, stackBufSize) } } func putBuf(b []byte) { select { case stackBuf <- b: default: } } var goroutineSpace = []byte("goroutine ") // GoroutineID returns the current goroutine's ID. // Use of this function is almost always a terrible idea. // It is also very slow. // GoroutineID is intended only for debugging. // In particular, it is used by syncutil. func GoroutineID() int64 { b := getBuf() defer putBuf(b) b = b[:runtime.Stack(b, false)] // Parse the 4707 out of "goroutine 4707 [" b = bytes.TrimPrefix(b, goroutineSpace) i := bytes.IndexByte(b, ' ') if i < 0 { panic(fmt.Sprintf("No space found in %q", b)) } b = b[:i] n, err := strutil.ParseUintBytes(b, 10, 64) if err != nil { panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) } return int64(n) } func (m *RWMutexTracker) startLogger() { go func() { var buf bytes.Buffer for { time.Sleep(1 * time.Second) buf.Reset() m.hmu.Lock() for gid := range m.holdr { fmt.Fprintf(&buf, " [%d]", gid) } m.hmu.Unlock() log.Printf("Mutex %p: waitW %d haveW %d waitR %d haveR %d %s", m, atomic.LoadInt32(&m.nwaitw), atomic.LoadInt32(&m.nhavew), atomic.LoadInt32(&m.nwaitr), atomic.LoadInt32(&m.nhaver), buf.Bytes()) } }() } func (m *RWMutexTracker) Lock() { m.logOnce.Do(m.startLogger) atomic.AddInt32(&m.nwaitw, 1) m.mu.Lock() atomic.AddInt32(&m.nwaitw, -1) atomic.AddInt32(&m.nhavew, 1) m.hmu.Lock() defer m.hmu.Unlock() if len(m.holder) == 0 { m.holder = make([]byte, stackBufSize) } m.holder = m.holder[:runtime.Stack(m.holder[:stackBufSize], false)] log.Printf("Lock at %s", string(m.holder)) } func (m *RWMutexTracker) Unlock() { m.hmu.Lock() m.holder = nil m.hmu.Unlock() atomic.AddInt32(&m.nhavew, -1) m.mu.Unlock() } func (m *RWMutexTracker) RLock() { m.logOnce.Do(m.startLogger) atomic.AddInt32(&m.nwaitr, 1) // Catch read-write-read lock. See if somebody (us? via // another goroutine?) already has a read lock, and then // somebody else is waiting to write, meaning our second read // will deadlock. if atomic.LoadInt32(&m.nhaver) > 0 && atomic.LoadInt32(&m.nwaitw) > 0 { buf := getBuf() buf = buf[:runtime.Stack(buf, false)] log.Printf("Potential R-W-R deadlock at: %s", buf) putBuf(buf) } m.mu.RLock() atomic.AddInt32(&m.nwaitr, -1) atomic.AddInt32(&m.nhaver, 1) gid := GoroutineID() m.hmu.Lock() defer m.hmu.Unlock() if m.holdr == nil { m.holdr = make(map[int64]bool) } if m.holdr[gid] { buf := getBuf() buf = buf[:runtime.Stack(buf, false)] log.Fatalf("Recursive call to RLock: %s", buf) } m.holdr[gid] = true } func stack() []byte { buf := make([]byte, 1024) return buf[:runtime.Stack(buf, false)] } func (m *RWMutexTracker) RUnlock() { atomic.AddInt32(&m.nhaver, -1) gid := GoroutineID() m.hmu.Lock() delete(m.holdr, gid) m.hmu.Unlock() m.mu.RUnlock() } // Holder returns the stack trace of the current exclusive lock holder's stack // when it acquired the lock (with Lock). It returns the empty string if the lock // is not currently held. func (m *RWMutexTracker) Holder() string { m.hmu.Lock() defer m.hmu.Unlock() return string(m.holder) } ������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/singleflight/��������������������������������������0000755�0610621�0607500�00000000000�13172163412�025260� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/singleflight/singleflight_test.go������������������0000644�0610621�0607500�00000003557�13172163412�031337� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package singleflight import ( "errors" "fmt" "sync" "sync/atomic" "testing" "time" ) func TestDo(t *testing.T) { var g Group v, err := g.Do("key", func() (interface{}, error) { return "bar", nil }) if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want { t.Errorf("Do = %v; want %v", got, want) } if err != nil { t.Errorf("Do error = %v", err) } } func TestDoErr(t *testing.T) { var g Group someErr := errors.New("Some error") v, err := g.Do("key", func() (interface{}, error) { return nil, someErr }) if err != someErr { t.Errorf("Do error = %v; want someErr %v", err, someErr) } if v != nil { t.Errorf("unexpected non-nil value %#v", v) } } func TestDoDupSuppress(t *testing.T) { var g Group c := make(chan string) var calls int32 fn := func() (interface{}, error) { atomic.AddInt32(&calls, 1) return <-c, nil } const n = 10 var wg sync.WaitGroup for i := 0; i < n; i++ { wg.Add(1) go func() { v, err := g.Do("key", fn) if err != nil { t.Errorf("Do error: %v", err) } if v.(string) != "bar" { t.Errorf("got %q; want %q", v, "bar") } wg.Done() }() } time.Sleep(100 * time.Millisecond) // let goroutines above block c <- "bar" wg.Wait() if got := atomic.LoadInt32(&calls); got != 1 { t.Errorf("number of calls = %d; want 1", got) } } �������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/singleflight/singleflight.go�����������������������0000644�0610621�0607500�00000003310�13172163412�030263� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package singleflight provides a duplicate function call suppression // mechanism. package singleflight // import "github.com/juju/go4/syncutil/singleflight" import "sync" // call is an in-flight or completed Do call type call struct { wg sync.WaitGroup val interface{} err error } // Group represents a class of work and forms a namespace in which // units of work can be executed with duplicate suppression. type Group struct { mu sync.Mutex // protects m m map[string]*call // lazily initialized } // Do executes and returns the results of the given function, making // sure that only one execution is in-flight for a given key at a // time. If a duplicate comes in, the duplicate caller waits for the // original to complete and receives the same results. func (g *Group) Do(key string, fn func() (interface{}, error)) (interface{}, error) { g.mu.Lock() if g.m == nil { g.m = make(map[string]*call) } if c, ok := g.m[key]; ok { g.mu.Unlock() c.wg.Wait() return c.val, c.err } c := new(call) c.wg.Add(1) g.m[key] = c g.mu.Unlock() c.val, c.err = fn() c.wg.Done() g.mu.Lock() delete(g.m, key) g.mu.Unlock() return c.val, c.err } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/sem_test.go����������������������������������������0000644�0610621�0607500�00000001000�13172163412�024742� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package syncutil_test import ( "testing" "github.com/juju/go4/syncutil" ) func TestSem(t *testing.T) { s := syncutil.NewSem(5) if err := s.Acquire(2); err != nil { t.Fatal(err) } if err := s.Acquire(2); err != nil { t.Fatal(err) } go func() { s.Release(2) s.Release(2) }() if err := s.Acquire(5); err != nil { t.Fatal(err) } } func TestSemErr(t *testing.T) { s := syncutil.NewSem(5) if err := s.Acquire(6); err == nil { t.Fatal("Didn't get expected error for large acquire.") } } lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/sem.go���������������������������������������������0000644�0610621�0607500�00000003013�13172163412�023711� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package syncutil import ( "fmt" "log" "sync" ) type debugT bool var debug = debugT(false) func (d debugT) Printf(format string, args ...interface{}) { if bool(d) { log.Printf(format, args...) } } // Sem implements a semaphore that can have multiple units acquired/released // at a time. type Sem struct { c *sync.Cond // Protects size max, free int64 } // NewSem creates a semaphore with max units available for acquisition. func NewSem(max int64) *Sem { return &Sem{ c: sync.NewCond(new(sync.Mutex)), free: max, max: max, } } // Acquire will deduct n units from the semaphore. If the deduction would // result in the available units falling below zero, the call will block until // another go routine returns units via a call to Release. If more units are // requested than the semaphore is configured to hold, error will be non-nil. func (s *Sem) Acquire(n int64) error { if n > s.max { return fmt.Errorf("sem: attempt to acquire more units than semaphore size %d > %d", n, s.max) } s.c.L.Lock() defer s.c.L.Unlock() for { debug.Printf("Acquire check max %d free %d, n %d", s.max, s.free, n) if s.free >= n { s.free -= n return nil } debug.Printf("Acquire Wait max %d free %d, n %d", s.max, s.free, n) s.c.Wait() } } // Release will return n units to the semaphore and notify any currently // blocking Acquire calls. func (s *Sem) Release(n int64) { s.c.L.Lock() defer s.c.L.Unlock() debug.Printf("Release max %d free %d, n %d", s.max, s.free, n) s.free += n s.c.Broadcast() } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/once_test.go���������������������������������������0000644�0610621�0607500�00000001665�13172163412�025123� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package syncutil import ( "errors" "testing" ) func TestOnce(t *testing.T) { timesRan := 0 f := func() error { timesRan++ return nil } once := Once{} grp := Group{} for i := 0; i < 10; i++ { grp.Go(func() error { return once.Do(f) }) } if grp.Err() != nil { t.Errorf("Expected no errors, got %v", grp.Err()) } if timesRan != 1 { t.Errorf("Expected to run one time, ran %d", timesRan) } } // TestOnceErroring verifies we retry on every error, but stop after // the first success. func TestOnceErroring(t *testing.T) { timesRan := 0 f := func() error { timesRan++ if timesRan < 3 { return errors.New("retry") } return nil } once := Once{} grp := Group{} for i := 0; i < 10; i++ { grp.Go(func() error { return once.Do(f) }) } if len(grp.Errs()) != 2 { t.Errorf("Expected two errors, got %d", len(grp.Errs())) } if timesRan != 3 { t.Errorf("Expected to run two times, ran %d", timesRan) } } ���������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/once.go��������������������������������������������0000644�0610621�0607500�00000003320�13172163412�024052� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package syncutil import ( "sync" "sync/atomic" ) // A Once will perform a successful action exactly once. // // Unlike a sync.Once, this Once's func returns an error // and is re-armed on failure. type Once struct { m sync.Mutex done uint32 } // Do calls the function f if and only if Do has not been invoked // without error for this instance of Once. In other words, given // var once Once // if once.Do(f) is called multiple times, only the first call will // invoke f, even if f has a different value in each invocation unless // f returns an error. A new instance of Once is required for each // function to execute. // // Do is intended for initialization that must be run exactly once. Since f // is niladic, it may be necessary to use a function literal to capture the // arguments to a function to be invoked by Do: // err := config.once.Do(func() error { return config.init(filename) }) func (o *Once) Do(f func() error) error { if atomic.LoadUint32(&o.done) == 1 { return nil } // Slow-path. o.m.Lock() defer o.m.Unlock() var err error if o.done == 0 { err = f() if err == nil { atomic.StoreUint32(&o.done, 1) } } return err } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/group.go�������������������������������������������0000644�0610621�0607500�00000003073�13172163412�024267� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package syncutil import "sync" // A Group is like a sync.WaitGroup and coordinates doing // multiple things at once. Its zero value is ready to use. type Group struct { wg sync.WaitGroup mu sync.Mutex // guards errs errs []error } // Go runs fn in its own goroutine, but does not wait for it to complete. // Call Err or Errs to wait for all the goroutines to complete. func (g *Group) Go(fn func() error) { g.wg.Add(1) go func() { defer g.wg.Done() err := fn() if err != nil { g.mu.Lock() defer g.mu.Unlock() g.errs = append(g.errs, err) } }() } // Wait waits for all the previous calls to Go to complete. func (g *Group) Wait() { g.wg.Wait() } // Err waits for all previous calls to Go to complete and returns the // first non-nil error, or nil. func (g *Group) Err() error { g.wg.Wait() if len(g.errs) > 0 { return g.errs[0] } return nil } // Errs waits for all previous calls to Go to complete and returns // all non-nil errors. func (g *Group) Errs() []error { g.wg.Wait() return g.errs } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/syncutil/gate.go��������������������������������������������0000644�0610621�0607500�00000002114�13172163412�024046� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package syncutil provides various concurrency mechanisms. package syncutil // A Gate limits concurrency. type Gate struct { c chan struct{} } // NewGate returns a new gate that will only permit max operations at once. func NewGate(max int) *Gate { return &Gate{make(chan struct{}, max)} } // Start starts an operation, blocking until the gate has room. func (g *Gate) Start() { g.c <- struct{}{} } // Done finishes an operation. func (g *Gate) Done() { select { case <-g.c: default: panic("Done called more than Start") } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/strutil/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022435� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/strutil/strutil_test.go�������������������������������������0000644�0610621�0607500�00000014046�13172163412�025536� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package strutil import ( "reflect" "strings" "testing" ) func TestAppendSplitN(t *testing.T) { var got []string tests := []struct { s, sep string n int }{ {"foo", "|", 1}, {"foo", "|", -1}, {"foo|bar", "|", 1}, {"foo|bar", "|", -1}, {"foo|bar|", "|", 2}, {"foo|bar|", "|", -1}, {"foo|bar|baz", "|", 1}, {"foo|bar|baz", "|", 2}, {"foo|bar|baz", "|", 3}, {"foo|bar|baz", "|", -1}, } for _, tt := range tests { want := strings.SplitN(tt.s, tt.sep, tt.n) got = AppendSplitN(got[:0], tt.s, tt.sep, tt.n) if !reflect.DeepEqual(want, got) { t.Errorf("AppendSplitN(%q, %q, %d) = %q; want %q", tt.s, tt.sep, tt.n, got, want) } } } func TestStringFromBytes(t *testing.T) { for _, s := range []string{"foo", "permanode", "file", "zzzz"} { got := StringFromBytes([]byte(s)) if got != s { t.Errorf("StringFromBytes(%q) didn't round-trip; got %q instead", s, got) } } } func TestHasPrefixFold(t *testing.T) { tests := []struct { s, prefix string result bool }{ {"camli", "CAML", true}, {"CAMLI", "caml", true}, {"cam", "Cam", true}, {"camli", "car", false}, {"caml", "camli", false}, {"Hello, 世界 dasdsa", "HeLlO, 世界", true}, {"Hello, 世界", "HeLlO, 世界-", false}, {"kelvin", "\u212A" + "elvin", true}, // "\u212A" is the Kelvin temperature sign {"Kelvin", "\u212A" + "elvin", true}, {"kelvin", "\u212A" + "el", true}, {"Kelvin", "\u212A" + "el", true}, {"\u212A" + "elvin", "Kelvin", true}, {"\u212A" + "elvin", "kelvin", true}, {"\u212A" + "elvin", "Kel", true}, {"\u212A" + "elvin", "kel", true}, } for _, tt := range tests { r := HasPrefixFold(tt.s, tt.prefix) if r != tt.result { t.Errorf("HasPrefixFold(%q, %q) returned %v", tt.s, tt.prefix, r) } } } func TestHasSuffixFold(t *testing.T) { tests := []struct { s, suffix string result bool }{ {"camli", "AMLI", true}, {"CAMLI", "amli", true}, {"mli", "MLI", true}, {"camli", "ali", false}, {"amli", "camli", false}, {"asas Hello, 世界", "HeLlO, 世界", true}, {"Hello, 世界", "HeLlO, 世界-", false}, {"KkkkKKkelvin", "\u212A" + "elvin", true}, // "\u212A" is the Kelvin temperature sign {"kelvin", "\u212A" + "elvin", true}, // "\u212A" is the Kelvin temperature sign {"Kelvin", "\u212A" + "elvin", true}, {"\u212A" + "elvin", "Kelvin", true}, {"\u212A" + "elvin", "kelvin", true}, {"\u212A" + "elvin", "vin", true}, {"\u212A" + "elvin", "viN", true}, } for _, tt := range tests { r := HasSuffixFold(tt.s, tt.suffix) if r != tt.result { t.Errorf("HasSuffixFold(%q, %q) returned %v", tt.s, tt.suffix, r) } } } func TestContainsFold(t *testing.T) { // TODO: more tests, more languages. tests := []struct { s, substr string result bool }{ {"camli", "CAML", true}, {"CAMLI", "caml", true}, {"cam", "Cam", true}, {"мир", "ми", true}, {"МИP", "ми", true}, {"КÐМЛИЙСТОР", "камлийÑ", true}, {"КаМлИйСтОр", "КаМлИйС", true}, {"camli", "car", false}, {"caml", "camli", false}, {"camli", "AMLI", true}, {"CAMLI", "amli", true}, {"mli", "MLI", true}, {"мир", "ир", true}, {"МИP", "ми", true}, {"КÐМЛИЙСТОР", "лийÑтор", true}, {"КаМлИйСтОр", "лИйСтОр", true}, {"мир", "Ñ€", true}, {"camli", "ali", false}, {"amli", "camli", false}, {"МИP", "и", true}, {"мир", "и", true}, {"КÐМЛИЙСТОР", "лийÑ", true}, {"КаМлИйСтОр", "лИйС", true}, {"árvíztűrÅ‘ tükörfúrógép", "árvíztŰrÅ", true}, {"I love ☕", "i love ☕", true}, {"k", "\u212A", true}, // "\u212A" is the Kelvin temperature sign {"\u212A" + "elvin", "k", true}, {"kelvin", "\u212A" + "elvin", true}, {"Kelvin", "\u212A" + "elvin", true}, {"\u212A" + "elvin", "Kelvin", true}, {"\u212A" + "elvin", "kelvin", true}, {"273.15 kelvin", "\u212A" + "elvin", true}, {"273.15 Kelvin", "\u212A" + "elvin", true}, {"273.15 \u212A" + "elvin", "Kelvin", true}, {"273.15 \u212A" + "elvin", "kelvin", true}, } for _, tt := range tests { r := ContainsFold(tt.s, tt.substr) if r != tt.result { t.Errorf("ContainsFold(%q, %q) returned %v", tt.s, tt.substr, r) } } } func TestIsPlausibleJSON(t *testing.T) { tests := []struct { in string want bool }{ {"{}", true}, {" {}", true}, {"{} ", true}, {"\n\r\t {}\t \r \n", true}, {"\n\r\t {x\t \r \n", false}, {"{x", false}, {"x}", false}, {"x", false}, {"", false}, } for _, tt := range tests { got := IsPlausibleJSON(tt.in) if got != tt.want { t.Errorf("IsPlausibleJSON(%q) = %v; want %v", tt.in, got, tt.want) } } } func BenchmarkHasSuffixFoldToLower(tb *testing.B) { a, b := "camlik", "AMLI\u212A" for i := 0; i < tb.N; i++ { if !strings.HasSuffix(strings.ToLower(a), strings.ToLower(b)) { tb.Fatalf("%q should have the same suffix as %q", a, b) } } } func BenchmarkHasSuffixFold(tb *testing.B) { a, b := "camlik", "AMLI\u212A" for i := 0; i < tb.N; i++ { if !HasSuffixFold(a, b) { tb.Fatalf("%q should have the same suffix as %q", a, b) } } } func BenchmarkHasPrefixFoldToLower(tb *testing.B) { a, b := "kamlistore", "\u212AAMLI" for i := 0; i < tb.N; i++ { if !strings.HasPrefix(strings.ToLower(a), strings.ToLower(b)) { tb.Fatalf("%q should have the same suffix as %q", a, b) } } } func BenchmarkHasPrefixFold(tb *testing.B) { a, b := "kamlistore", "\u212AAMLI" for i := 0; i < tb.N; i++ { if !HasPrefixFold(a, b) { tb.Fatalf("%q should have the same suffix as %q", a, b) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/strutil/strutil.go������������������������������������������0000644�0610621�0607500�00000011221�13172163412�024467� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package strutil contains string and byte processing functions. package strutil // import "github.com/juju/go4/strutil" import ( "strings" "unicode" "unicode/utf8" ) // Fork of Go's implementation in pkg/strings/strings.go: // Generic split: splits after each instance of sep, // including sepSave bytes of sep in the subarrays. func genSplit(dst []string, s, sep string, sepSave, n int) []string { if n == 0 { return nil } if sep == "" { panic("sep is empty") } if n < 0 { n = strings.Count(s, sep) + 1 } c := sep[0] start := 0 na := 0 for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ { if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) { dst = append(dst, s[start:i+sepSave]) na++ start = i + len(sep) i += len(sep) - 1 } } dst = append(dst, s[start:]) return dst } // AppendSplitN is like strings.SplitN but appends to and returns dst. // Unlike strings.SplitN, an empty separator is not supported. // The count n determines the number of substrings to return: // n > 0: at most n substrings; the last substring will be the unsplit remainder. // n == 0: the result is nil (zero substrings) // n < 0: all substrings func AppendSplitN(dst []string, s, sep string, n int) []string { return genSplit(dst, s, sep, 0, n) } // equalFoldRune compares a and b runes whether they fold equally. // // The code comes from strings.EqualFold, but shortened to only one rune. func equalFoldRune(sr, tr rune) bool { if sr == tr { return true } // Make sr < tr to simplify what follows. if tr < sr { sr, tr = tr, sr } // Fast check for ASCII. if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' { // ASCII, and sr is upper case. tr must be lower case. if tr == sr+'a'-'A' { return true } return false } // General case. SimpleFold(x) returns the next equivalent rune > x // or wraps around to smaller values. r := unicode.SimpleFold(sr) for r != sr && r < tr { r = unicode.SimpleFold(r) } if r == tr { return true } return false } // HasPrefixFold is like strings.HasPrefix but uses Unicode case-folding. func HasPrefixFold(s, prefix string) bool { if prefix == "" { return true } for _, pr := range prefix { if s == "" { return false } // step with s, too sr, size := utf8.DecodeRuneInString(s) if sr == utf8.RuneError { return false } s = s[size:] if !equalFoldRune(sr, pr) { return false } } return true } // HasSuffixFold is like strings.HasPrefix but uses Unicode case-folding. func HasSuffixFold(s, suffix string) bool { if suffix == "" { return true } // count the runes and bytes in s, but only till rune count of suffix bo, so := len(s), len(suffix) for bo > 0 && so > 0 { r, size := utf8.DecodeLastRuneInString(s[:bo]) if r == utf8.RuneError { return false } bo -= size sr, size := utf8.DecodeLastRuneInString(suffix[:so]) if sr == utf8.RuneError { return false } so -= size if !equalFoldRune(r, sr) { return false } } return so == 0 } // ContainsFold is like strings.Contains but uses Unicode case-folding. func ContainsFold(s, substr string) bool { if substr == "" { return true } if s == "" { return false } firstRune := rune(substr[0]) if firstRune >= utf8.RuneSelf { firstRune, _ = utf8.DecodeRuneInString(substr) } for i, rune := range s { if equalFoldRune(rune, firstRune) && HasPrefixFold(s[i:], substr) { return true } } return false } // IsPlausibleJSON reports whether s likely contains a JSON object, without // actually parsing it. It's meant to be a light heuristic. func IsPlausibleJSON(s string) bool { return startsWithOpenBrace(s) && endsWithCloseBrace(s) } func isASCIIWhite(b byte) bool { return b == ' ' || b == '\n' || b == '\r' || b == '\t' } func startsWithOpenBrace(s string) bool { for len(s) > 0 { switch { case s[0] == '{': return true case isASCIIWhite(s[0]): s = s[1:] default: return false } } return false } func endsWithCloseBrace(s string) bool { for len(s) > 0 { last := len(s) - 1 switch { case s[last] == '}': return true case isASCIIWhite(s[last]): s = s[:last] default: return false } } return false } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/strutil/strconv.go������������������������������������������0000644�0610621�0607500�00000004364�13172163412�024471� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package strutil import ( "errors" "strconv" ) // ParseUintBytes is like strconv.ParseUint, but using a []byte. func ParseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) { var cutoff, maxVal uint64 if bitSize == 0 { bitSize = int(strconv.IntSize) } s0 := s switch { case len(s) < 1: err = strconv.ErrSyntax goto Error case 2 <= base && base <= 36: // valid base; nothing to do case base == 0: // Look for octal, hex prefix. switch { case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'): base = 16 s = s[2:] if len(s) < 1 { err = strconv.ErrSyntax goto Error } case s[0] == '0': base = 8 default: base = 10 } default: err = errors.New("invalid base " + strconv.Itoa(base)) goto Error } n = 0 cutoff = cutoff64(base) maxVal = 1<<uint(bitSize) - 1 for i := 0; i < len(s); i++ { var v byte d := s[i] switch { case '0' <= d && d <= '9': v = d - '0' case 'a' <= d && d <= 'z': v = d - 'a' + 10 case 'A' <= d && d <= 'Z': v = d - 'A' + 10 default: n = 0 err = strconv.ErrSyntax goto Error } if int(v) >= base { n = 0 err = strconv.ErrSyntax goto Error } if n >= cutoff { // n*base overflows n = 1<<64 - 1 err = strconv.ErrRange goto Error } n *= uint64(base) n1 := n + uint64(v) if n1 < n || n1 > maxVal { // n+v overflows n = 1<<64 - 1 err = strconv.ErrRange goto Error } n = n1 } return n, nil Error: return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err} } // Return the first number n such that n*base >= 1<<64. func cutoff64(base int) uint64 { if base < 2 { return 0 } return (1<<64-1)/uint64(base) + 1 } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/strutil/intern.go�������������������������������������������0000644�0610621�0607500�00000002365�13172163412�024271� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package strutil var internStr = map[string]string{} // RegisterCommonString adds common strings to the interned string // table. This should be called during init from the main // goroutine, not later at runtime. func RegisterCommonString(s ...string) { for _, v := range s { internStr[v] = v } } // StringFromBytes returns string(v), minimizing copies for common values of v // as previously registered with RegisterCommonString. func StringFromBytes(v []byte) string { // In Go 1.3, this string conversion in the map lookup does not allocate // to make a new string. We depend on Go 1.3, so this is always free: if s, ok := internStr[string(v)]; ok { return s } return string(v) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/readerutil/�������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�023067� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/readerutil/readerutil_test.go�������������������������������0000644�0610621�0607500�00000001764�13172163412�026625� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2016 The Go4 Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package readerutil import ( "expvar" "fmt" "io" "io/ioutil" "strings" ) func ExampleNewStatsReader() { var ( // r is the io.Reader we'd like to count read from. r = strings.NewReader("Hello world") v = expvar.NewInt("read-bytes") sw = NewStatsReader(v, r) ) // Read from the wrapped io.Reader, StatReader will count the bytes. io.Copy(ioutil.Discard, sw) fmt.Printf("Read %s bytes\n", v.String()) // Output: Read 11 bytes } ������������lxd-2.0.11/dist/src/github.com/juju/go4/readerutil/readerutil.go������������������������������������0000644�0610621�0607500�00000003752�13172163412�025565� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2016 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package readerutil contains io.Reader types. package readerutil // import "github.com/juju/go4/readerutil" import ( "expvar" "io" ) // A SizeReaderAt is a ReaderAt with a Size method. // // An io.SectionReader implements SizeReaderAt. type SizeReaderAt interface { Size() int64 io.ReaderAt } // A ReadSeekCloser can Read, Seek, and Close. type ReadSeekCloser interface { io.Reader io.Seeker io.Closer } type ReaderAtCloser interface { io.ReaderAt io.Closer } // TODO(wathiede): make sure all the stat readers work with code that // type asserts ReadFrom/WriteTo. type varStatReader struct { *expvar.Int r io.Reader } // NewReaderStats returns an io.Reader that will have the number of bytes // read from r added to v. func NewStatsReader(v *expvar.Int, r io.Reader) io.Reader { return &varStatReader{v, r} } func (v *varStatReader) Read(p []byte) (int, error) { n, err := v.r.Read(p) v.Int.Add(int64(n)) return n, err } type varStatReadSeeker struct { *expvar.Int rs io.ReadSeeker } // NewReaderStats returns an io.ReadSeeker that will have the number of bytes // read from rs added to v. func NewStatsReadSeeker(v *expvar.Int, rs io.ReadSeeker) io.ReadSeeker { return &varStatReadSeeker{v, rs} } func (v *varStatReadSeeker) Read(p []byte) (int, error) { n, err := v.rs.Read(p) v.Int.Add(int64(n)) return n, err } func (v *varStatReadSeeker) Seek(offset int64, whence int) (int64, error) { return v.rs.Seek(offset, whence) } ����������������������lxd-2.0.11/dist/src/github.com/juju/go4/readerutil/multireaderat_test.go����������������������������0000644�0610621�0607500�00000002502�13172163412�027316� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2016 The Go4 Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package readerutil import ( "io" "io/ioutil" "strings" "testing" ) func TestMultiReaderAt(t *testing.T) { sra := NewMultiReaderAt( io.NewSectionReader(strings.NewReader("xaaax"), 1, 3), io.NewSectionReader(strings.NewReader("xxbbbbxx"), 2, 3), io.NewSectionReader(strings.NewReader("cccx"), 0, 3), ) if sra.Size() != 9 { t.Fatalf("Size = %d; want 9", sra.Size()) } const full = "aaabbbccc" for start := 0; start < len(full); start++ { for end := start; end < len(full); end++ { want := full[start:end] got, err := ioutil.ReadAll(io.NewSectionReader(sra, int64(start), int64(end-start))) if err != nil { t.Fatal(err) } if string(got) != want { t.Errorf("for start=%d, end=%d: ReadAll = %q; want %q", start, end, got, want) } } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/readerutil/multireaderat.go���������������������������������0000644�0610621�0607500�00000003776�13172163412�026275� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2016 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package readerutil import ( "io" "sort" ) // NewMultiReaderAt is like io.MultiReader but produces a ReaderAt // (and Size), instead of just a reader. func NewMultiReaderAt(parts ...SizeReaderAt) SizeReaderAt { m := &multiRA{ parts: make([]offsetAndSource, 0, len(parts)), } var off int64 for _, p := range parts { m.parts = append(m.parts, offsetAndSource{off, p}) off += p.Size() } m.size = off return m } type offsetAndSource struct { off int64 SizeReaderAt } type multiRA struct { parts []offsetAndSource size int64 } func (m *multiRA) Size() int64 { return m.size } func (m *multiRA) ReadAt(p []byte, off int64) (n int, err error) { wantN := len(p) // Skip past the requested offset. skipParts := sort.Search(len(m.parts), func(i int) bool { // This function returns whether parts[i] will // contribute any bytes to our output. part := m.parts[i] return part.off+part.Size() > off }) parts := m.parts[skipParts:] // How far to skip in the first part. needSkip := off if len(parts) > 0 { needSkip -= parts[0].off } for len(parts) > 0 && len(p) > 0 { readP := p partSize := parts[0].Size() if int64(len(readP)) > partSize-needSkip { readP = readP[:partSize-needSkip] } pn, err0 := parts[0].ReadAt(readP, needSkip) if err0 != nil { return n, err0 } n += pn p = p[pn:] if int64(pn)+needSkip == partSize { parts = parts[1:] } needSkip = 0 } if n != wantN { err = io.ErrUnexpectedEOF } return } ��lxd-2.0.11/dist/src/github.com/juju/go4/readerutil/fakeseeker_test.go�������������������������������0000644�0610621�0607500�00000003553�13172163412�026570� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package readerutil import ( "os" "strings" "testing" ) func TestFakeSeeker(t *testing.T) { rs := NewFakeSeeker(strings.NewReader("foobar"), 6) if pos, err := rs.Seek(0, os.SEEK_END); err != nil || pos != 6 { t.Fatalf("SEEK_END = %d, %v; want 6, nil", pos, err) } if pos, err := rs.Seek(0, os.SEEK_CUR); err != nil || pos != 6 { t.Fatalf("SEEK_CUR = %d, %v; want 6, nil", pos, err) } if pos, err := rs.Seek(0, os.SEEK_SET); err != nil || pos != 0 { t.Fatalf("SEEK_SET = %d, %v; want 0, nil", pos, err) } buf := make([]byte, 3) if n, err := rs.Read(buf); n != 3 || err != nil || string(buf) != "foo" { t.Fatalf("First read = %d, %v (buf = %q); want foo", n, err, buf) } if pos, err := rs.Seek(0, os.SEEK_CUR); err != nil || pos != 3 { t.Fatalf("Seek cur pos after first read = %d, %v; want 3, nil", pos, err) } if n, err := rs.Read(buf); n != 3 || err != nil || string(buf) != "bar" { t.Fatalf("Second read = %d, %v (buf = %q); want foo", n, err, buf) } if pos, err := rs.Seek(1, os.SEEK_SET); err != nil || pos != 1 { t.Fatalf("SEEK_SET = %d, %v; want 1, nil", pos, err) } const msg = "attempt to read from fake seek offset" if _, err := rs.Read(buf); err == nil || !strings.Contains(err.Error(), msg) { t.Fatalf("bogus Read after seek = %v; want something containing %q", err, msg) } } �����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/readerutil/fakeseeker.go������������������������������������0000644�0610621�0607500�00000003362�13172163412�025527� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package readerutil import ( "errors" "fmt" "io" "os" ) // fakeSeeker can seek to the ends but any read not at the current // position will fail. type fakeSeeker struct { r io.Reader size int64 fakePos int64 realPos int64 } // NewFakeSeeker returns a ReadSeeker that can pretend to Seek (based // on the provided total size of the reader's content), but any reads // will fail if the fake seek position doesn't match reality. func NewFakeSeeker(r io.Reader, size int64) io.ReadSeeker { return &fakeSeeker{r: r, size: size} } func (fs *fakeSeeker) Seek(offset int64, whence int) (int64, error) { var newo int64 switch whence { default: return 0, errors.New("invalid whence") case os.SEEK_SET: newo = offset case os.SEEK_CUR: newo = fs.fakePos + offset case os.SEEK_END: newo = fs.size + offset } if newo < 0 { return 0, errors.New("negative seek") } fs.fakePos = newo return newo, nil } func (fs *fakeSeeker) Read(p []byte) (n int, err error) { if fs.fakePos != fs.realPos { return 0, fmt.Errorf("attempt to read from fake seek offset %d; real offset is %d", fs.fakePos, fs.realPos) } n, err = fs.r.Read(p) fs.fakePos += int64(n) fs.realPos += int64(n) return } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/osutil/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022246� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/osutil/osutil.go��������������������������������������������0000644�0610621�0607500�00000002236�13172163412�024117� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package osutil contains os level functions. package osutil // import "github.com/juju/go4/osutil" // capture executable on package init to work around various os issues if // captured after executable has been renamed. var execPath, execError = executable() // Executable returns the path name for the executable that starts the // current process. The result is the path that was used to start the // current process, but there is no guarantee that the path is still // pointing to the correct executable. // // OpenBSD is currently unsupported. func Executable() (string, error) { return execPath, execError } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/osutil/exec_windows.go��������������������������������������0000644�0610621�0607500�00000003036�13172163412�025275� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package osutil import ( "path/filepath" "syscall" "unsafe" ) var ( modkernel32 = syscall.MustLoadDLL("kernel32.dll") procGetModuleFileNameW = modkernel32.MustFindProc("GetModuleFileNameW") ) func getModuleFileName(handle syscall.Handle) (string, error) { n := uint32(1024) var buf []uint16 for { buf = make([]uint16, n) r, err := syscallGetModuleFileName(handle, &buf[0], n) if err != nil { return "", err } if r < n { break } // r == n means n not big enough n += 1024 } return syscall.UTF16ToString(buf), nil } func executable() (string, error) { p, err := getModuleFileName(0) return filepath.Clean(p), err } func syscallGetModuleFileName(module syscall.Handle, fn *uint16, len uint32) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procGetModuleFileNameW.Addr(), 3, uintptr(module), uintptr(unsafe.Pointer(fn)), uintptr(len)) n = uint32(r0) if n == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/osutil/exec_test.go�����������������������������������������0000644�0610621�0607500�00000004567�13172163412�024574� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The go4 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package osutil import ( "fmt" "os" osexec "os/exec" "path/filepath" "runtime" "testing" ) const executable_EnvVar = "OSTEST_OUTPUT_EXECPATH" func TestExecutable(t *testing.T) { if runtime.GOOS == "nacl" { t.Skip() } ep, err := Executable() if err != nil { switch goos := runtime.GOOS; goos { case "openbsd": // procfs is not mounted by default t.Skipf("Executable failed on %s: %v, expected", goos, err) } t.Fatalf("Executable failed: %v", err) } // we want fn to be of the form "dir/prog" dir := filepath.Dir(filepath.Dir(ep)) fn, err := filepath.Rel(dir, ep) if err != nil { t.Fatalf("filepath.Rel: %v", err) } cmd := &osexec.Cmd{} // make child start with a relative program path cmd.Dir = dir cmd.Path = fn // forge argv[0] for child, so that we can verify we could correctly // get real path of the executable without influenced by argv[0]. cmd.Args = []string{"-", "-test.run=XXXX"} cmd.Env = []string{fmt.Sprintf("%s=1", executable_EnvVar)} out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("exec(self) failed: %v", err) } outs := string(out) if !filepath.IsAbs(outs) { t.Fatalf("Child returned %q, want an absolute path", out) } if !sameFile(outs, ep) { t.Fatalf("Child returned %q, not the same file as %q", out, ep) } } func sameFile(fn1, fn2 string) bool { fi1, err := os.Stat(fn1) if err != nil { return false } fi2, err := os.Stat(fn2) if err != nil { return false } return os.SameFile(fi1, fi2) } func init() { if e := os.Getenv(executable_EnvVar); e != "" { // first chdir to another path dir := "/" if runtime.GOOS == "windows" { dir = filepath.VolumeName(".") } os.Chdir(dir) if ep, err := Executable(); err != nil { fmt.Fprint(os.Stderr, "ERROR: ", err) } else { fmt.Fprint(os.Stderr, ep) } os.Exit(0) } } �����������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/osutil/exec_sysctl.go���������������������������������������0000644�0610621�0607500�00000003303�13172163412�025121� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The go4 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build freebsd darwin package osutil import ( "os" "path/filepath" "runtime" "syscall" "unsafe" ) var cacheWD, cacheWDErr = os.Getwd() func executable() (string, error) { var mib [4]int32 switch runtime.GOOS { case "freebsd": mib = [4]int32{1 /* CTL_KERN */, 14 /* KERN_PROC */, 12 /* KERN_PROC_PATHNAME */, -1} case "darwin": mib = [4]int32{1 /* CTL_KERN */, 38 /* KERN_PROCARGS */, int32(os.Getpid()), -1} } n := uintptr(0) // get length _, _, err := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, 0, uintptr(unsafe.Pointer(&n)), 0, 0) if err != 0 { return "", err } if n == 0 { // shouldn't happen return "", nil } buf := make([]byte, n) _, _, err = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n)), 0, 0) if err != 0 { return "", err } if n == 0 { // shouldn't happen return "", nil } p := string(buf[:n-1]) if !filepath.IsAbs(p) { if cacheWDErr != nil { return p, cacheWDErr } p = filepath.Join(cacheWD, filepath.Clean(p)) } return filepath.EvalSymlinks(p) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/osutil/exec_solaris_amd64.go��������������������������������0000644�0610621�0607500�00000003222�13172163412�026247� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The go4 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build amd64,solaris package osutil import ( "os" "syscall" "unsafe" ) //go:cgo_import_dynamic libc_getexecname getexecname "libc.so" //go:linkname libc_getexecname libc_getexecname var libc_getexecname uintptr func getexecname() (path unsafe.Pointer, err error) { r0, _, e1 := syscall.Syscall6(uintptr(unsafe.Pointer(&libc_getexecname)), 0, 0, 0, 0, 0, 0) path = unsafe.Pointer(r0) if e1 != 0 { err = syscall.Errno(e1) } return } func syscallGetexecname() (path string, err error) { ptr, err := getexecname() if err != nil { return "", err } bytes := (*[1 << 29]byte)(ptr)[:] for i, b := range bytes { if b == 0 { return string(bytes[:i]), nil } } panic("unreachable") } var initCwd, initCwdErr = os.Getwd() func executable() (string, error) { path, err := syscallGetexecname() if err != nil { return path, err } if len(path) > 0 && path[0] != '/' { if initCwdErr != nil { return path, initCwdErr } if len(path) > 2 && path[0:2] == "./" { // skip "./" path = path[2:] } return initCwd + "/" + path, nil } return path, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/osutil/exec_procfs.go���������������������������������������0000644�0610621�0607500�00000002153�13172163412�025076� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The go4 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build linux netbsd openbsd dragonfly nacl package osutil import ( "errors" "os" "path/filepath" "runtime" ) func executable() (string, error) { var procfn string switch runtime.GOOS { default: return "", errors.New("Executable not implemented for " + runtime.GOOS) case "linux": procfn = "/proc/self/exe" case "netbsd": procfn = "/proc/curproc/exe" case "openbsd": procfn = "/proc/curproc/file" case "dragonfly": procfn = "/proc/curproc/file" } p, err := os.Readlink(procfn) return filepath.Clean(p), err } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/osutil/exec_plan9.go����������������������������������������0000644�0610621�0607500�00000001622�13172163412�024625� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The go4 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build plan9 package osutil import ( "fmt" "os" "path/filepath" "syscall" ) func executable() (string, error) { fn := fmt.Sprintf("/proc/%d/text", os.Getpid()) f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() p, err := syscall.Fd2path(int(f.Fd())) return filepath.Clean(p), err } ��������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/oauthutil/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022745� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/oauthutil/oauth.go������������������������������������������0000644�0610621�0607500�00000010032�13172163412�024410� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package oauthutil contains OAuth 2 related utilities. package oauthutil import ( "encoding/json" "errors" "fmt" "time" "github.com/juju/go4/wkfs" "golang.org/x/oauth2" ) // TitleBarRedirectURL is the OAuth2 redirect URL to use when the authorization // code should be returned in the title bar of the browser, with the page text // prompting the user to copy the code and paste it in the application. const TitleBarRedirectURL = "urn:ietf:wg:oauth:2.0:oob" // ErrNoAuthCode is returned when Token() has not found any valid cached token // and TokenSource does not have an AuthCode for getting a new token. var ErrNoAuthCode = errors.New("oauthutil: unspecified TokenSource.AuthCode") // TokenSource is an implementation of oauth2.TokenSource. It uses CacheFile to store and // reuse the the acquired token, and AuthCode to provide the authorization code that will be // exchanged for a token otherwise. type TokenSource struct { Config *oauth2.Config // CacheFile is where the token will be stored JSON-encoded. Any call to Token // first tries to read a valid token from CacheFile. CacheFile string // AuthCode provides the authorization code that Token will exchange for a token. // It usually is a way to prompt the user for the code. If CacheFile does not provide // a token and AuthCode is nil, Token returns ErrNoAuthCode. AuthCode func() string } var errExpiredToken = errors.New("expired token") // cachedToken returns the token saved in cacheFile. It specifically returns // errTokenExpired if the token is expired. func cachedToken(cacheFile string) (*oauth2.Token, error) { tok := new(oauth2.Token) tokenData, err := wkfs.ReadFile(cacheFile) if err != nil { return nil, err } if err = json.Unmarshal(tokenData, tok); err != nil { return nil, err } if !tok.Valid() { if tok != nil && time.Now().After(tok.Expiry) { return nil, errExpiredToken } return nil, errors.New("invalid token") } return tok, nil } // Token first tries to find a valid token in CacheFile, and otherwise uses // Config and AuthCode to fetch a new token. This new token is saved in CacheFile // (if not blank). If CacheFile did not provide a token and AuthCode is nil, // ErrNoAuthCode is returned. func (src TokenSource) Token() (*oauth2.Token, error) { var tok *oauth2.Token var err error if src.CacheFile != "" { tok, err = cachedToken(src.CacheFile) if err == nil { return tok, nil } if err != errExpiredToken { fmt.Printf("Error getting token from %s: %v\n", src.CacheFile, err) } } if src.AuthCode == nil { return nil, ErrNoAuthCode } tok, err = src.Config.Exchange(oauth2.NoContext, src.AuthCode()) if err != nil { return nil, fmt.Errorf("could not exchange auth code for a token: %v", err) } if src.CacheFile == "" { return tok, nil } tokenData, err := json.Marshal(&tok) if err != nil { return nil, fmt.Errorf("could not encode token as json: %v", err) } if err := wkfs.WriteFile(src.CacheFile, tokenData, 0600); err != nil { return nil, fmt.Errorf("could not cache token in %v: %v", src.CacheFile, err) } return tok, nil } // NewRefreshTokenSource returns a token source that obtains its initial token // based on the provided config and the refresh token. func NewRefreshTokenSource(config *oauth2.Config, refreshToken string) oauth2.TokenSource { var noInitialToken *oauth2.Token = nil return oauth2.ReuseTokenSource(noInitialToken, config.TokenSource( oauth2.NoContext, // TODO: maybe accept a context later. &oauth2.Token{RefreshToken: refreshToken}, )) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/net/��������������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�021515� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/net/throttle/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163412�023362� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/net/throttle/throttle.go������������������������������������0000644�0610621�0607500�00000005435�13172163412�025565� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2012 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package throttle provides a net.Listener that returns // artificially-delayed connections for testing real-world // connectivity. package throttle // import "github.com/juju/go4/net/throttle" import ( "fmt" "net" "sync" "time" ) const unitSize = 1400 // read/write chunk size. ~MTU size. type Rate struct { KBps int // or 0, to not rate-limit bandwidth Latency time.Duration } // byteTime returns the time required for n bytes. func (r Rate) byteTime(n int) time.Duration { if r.KBps == 0 { return 0 } return time.Duration(float64(n)/1024/float64(r.KBps)) * time.Second } type Listener struct { net.Listener Down Rate // server Writes to Client Up Rate // server Reads from client } func (ln *Listener) Accept() (net.Conn, error) { c, err := ln.Listener.Accept() time.Sleep(ln.Up.Latency) if err != nil { return nil, err } tc := &conn{Conn: c, Down: ln.Down, Up: ln.Up} tc.start() return tc, nil } type nErr struct { n int err error } type writeReq struct { writeAt time.Time p []byte resc chan nErr } type conn struct { net.Conn Down Rate // for reads Up Rate // for writes wchan chan writeReq closeOnce sync.Once closeErr error } func (c *conn) start() { c.wchan = make(chan writeReq, 1024) go c.writeLoop() } func (c *conn) writeLoop() { for req := range c.wchan { time.Sleep(req.writeAt.Sub(time.Now())) var res nErr for len(req.p) > 0 && res.err == nil { writep := req.p if len(writep) > unitSize { writep = writep[:unitSize] } n, err := c.Conn.Write(writep) time.Sleep(c.Up.byteTime(len(writep))) res.n += n res.err = err req.p = req.p[n:] } req.resc <- res } } func (c *conn) Close() error { c.closeOnce.Do(func() { err := c.Conn.Close() close(c.wchan) c.closeErr = err }) return c.closeErr } func (c *conn) Write(p []byte) (n int, err error) { defer func() { if e := recover(); e != nil { n = 0 err = fmt.Errorf("%v", err) return } }() resc := make(chan nErr, 1) c.wchan <- writeReq{time.Now().Add(c.Up.Latency), p, resc} res := <-resc return res.n, res.err } func (c *conn) Read(p []byte) (n int, err error) { const max = 1024 if len(p) > max { p = p[:max] } n, err = c.Conn.Read(p) time.Sleep(c.Down.byteTime(n)) return } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/�������������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�021657� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock_test.go�������������������������������������������0000644�0610621�0607500�00000010643�13172163412�024201� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lock import ( "bufio" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "strconv" "testing" ) func TestLock(t *testing.T) { testLock(t, false) } func TestLockPortable(t *testing.T) { testLock(t, true) } func TestLockInChild(t *testing.T) { f := os.Getenv("TEST_LOCK_FILE") if f == "" { // not child return } lock := Lock if v, _ := strconv.ParseBool(os.Getenv("TEST_LOCK_PORTABLE")); v { lock = lockPortable } var lk io.Closer for scan := bufio.NewScanner(os.Stdin); scan.Scan(); { var err error switch scan.Text() { case "lock": lk, err = lock(f) case "unlock": err = lk.Close() lk = nil case "exit": // Simulate a crash, or at least not unlocking the lock. os.Exit(0) default: err = fmt.Errorf("unexpected child command %q", scan.Text()) } if err != nil { fmt.Println(err) } else { fmt.Println("") } } } func testLock(t *testing.T, portable bool) { lock := Lock if portable { lock = lockPortable } t.Logf("test lock, portable %v", portable) td, err := ioutil.TempDir("", "") if err != nil { t.Fatal(err) } defer os.RemoveAll(td) path := filepath.Join(td, "foo.lock") proc := newChildProc(t, path, portable) defer proc.kill() t.Logf("First lock in child") if err := proc.do("lock"); err != nil { t.Fatalf("first lock in child process: %v", err) } t.Logf("Crash child") if err := proc.do("exit"); err != nil { t.Fatalf("crash in child process: %v", err) } proc = newChildProc(t, path, portable) defer proc.kill() t.Logf("Locking+unlocking in child...") if err := proc.do("lock"); err != nil { t.Fatalf("lock in child process after crashing child: %v", err) } if err := proc.do("unlock"); err != nil { t.Fatalf("lock in child process after crashing child: %v", err) } t.Logf("Locking in parent...") lk1, err := lock(path) if err != nil { t.Fatal(err) } t.Logf("Again in parent...") _, err = lock(path) if err == nil { t.Fatal("expected second lock to fail") } t.Logf("Locking in child...") if err := proc.do("lock"); err == nil { t.Fatalf("expected lock in child process to fail") } t.Logf("Unlocking lock in parent") if err := lk1.Close(); err != nil { t.Fatal(err) } t.Logf("Trying lock again in child...") if err := proc.do("lock"); err != nil { t.Fatal(err) } if err := proc.do("unlock"); err != nil { t.Fatal(err) } lk3, err := lock(path) if err != nil { t.Fatal(err) } lk3.Close() } type childLockCmd struct { op string reply chan<- error } type childProc struct { proc *os.Process c chan childLockCmd } func (c *childProc) kill() { c.proc.Kill() } func (c *childProc) do(op string) error { reply := make(chan error) c.c <- childLockCmd{ op: op, reply: reply, } return <-reply } func newChildProc(t *testing.T, path string, portable bool) *childProc { cmd := exec.Command(os.Args[0], "-test.run=LockInChild$") cmd.Env = []string{"TEST_LOCK_FILE=" + path} toChild, err := cmd.StdinPipe() if err != nil { t.Fatalf("cannot make pipe: %v", err) } fromChild, err := cmd.StdoutPipe() if err != nil { t.Fatalf("cannot make pipe: %v", err) } cmd.Stderr = os.Stderr if portable { cmd.Env = append(cmd.Env, "TEST_LOCK_PORTABLE=1") } if err := cmd.Start(); err != nil { t.Fatalf("cannot start child: %v", err) } cmdChan := make(chan childLockCmd) go func() { defer fromChild.Close() defer toChild.Close() inScan := bufio.NewScanner(fromChild) for c := range cmdChan { fmt.Fprintln(toChild, c.op) ok := inScan.Scan() if c.op == "exit" { if ok { c.reply <- errors.New("child did not exit") } else { cmd.Wait() c.reply <- nil } break } if !ok { panic("child exited early") } if errText := inScan.Text(); errText != "" { c.reply <- errors.New(errText) } else { c.reply <- nil } } }() return &childProc{ c: cmdChan, proc: cmd.Process, } } ���������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock_sigzero.go����������������������������������������0000644�0610621�0607500�00000001321�13172163412�024675� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !appengine // +build linux darwin freebsd openbsd netbsd dragonfly /* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lock import "syscall" func init() { signalZero = syscall.Signal(0) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock_plan9.go������������������������������������������0000644�0610621�0607500�00000002014�13172163412�024236� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lock import ( "fmt" "io" "os" ) func init() { lockFn = lockPlan9 } func lockPlan9(name string) (io.Closer, error) { fi, err := os.Stat(name) if err == nil && fi.Size() > 0 { return nil, fmt.Errorf("can't Lock file %q: has non-zero size", name) } f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, os.ModeExclusive|0644) if err != nil { return nil, fmt.Errorf("Lock Create of %s failed: %v", name, err) } return &unlocker{f: f, abs: name}, nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock_linux_arm.go��������������������������������������0000644�0610621�0607500�00000003137�13172163412�025220� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux,arm // +build !appengine /* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lock import ( "fmt" "io" "os" "syscall" "unsafe" ) func init() { lockFn = lockFcntl } func lockFcntl(name string) (io.Closer, error) { fi, err := os.Stat(name) if err == nil && fi.Size() > 0 { return nil, fmt.Errorf("can't Lock file %q: has non-zero size", name) } f, err := os.Create(name) if err != nil { return nil, err } // This type matches C's "struct flock" defined in /usr/include/bits/fcntl.h. // TODO: move this into the standard syscall package. k := struct { Type uint16 Whence uint16 Start uint32 Len uint32 Pid uint32 }{ Type: syscall.F_WRLCK, Whence: uint16(os.SEEK_SET), Start: 0, Len: 0, // 0 means to lock the entire file. Pid: uint32(os.Getpid()), } const F_SETLK = 6 // actual value. syscall package is wrong: golang.org/issue/7059 _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(F_SETLK), uintptr(unsafe.Pointer(&k))) if errno != 0 { f.Close() return nil, errno } return &unlocker{f: f, abs: name}, nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock_linux_amd64.go������������������������������������0000644�0610621�0607500�00000003025�13172163412�025350� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux,amd64 // +build !appengine /* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lock import ( "fmt" "io" "os" "syscall" "unsafe" ) func init() { lockFn = lockFcntl } func lockFcntl(name string) (io.Closer, error) { fi, err := os.Stat(name) if err == nil && fi.Size() > 0 { return nil, fmt.Errorf("can't Lock file %q: has non-zero size", name) } f, err := os.Create(name) if err != nil { return nil, err } // This type matches C's "struct flock" defined in /usr/include/bits/fcntl.h. // TODO: move this into the standard syscall package. k := struct { Type uint32 Whence uint32 Start uint64 Len uint64 Pid uint32 }{ Type: syscall.F_WRLCK, Whence: uint32(os.SEEK_SET), Start: 0, Len: 0, // 0 means to lock the entire file. Pid: uint32(os.Getpid()), } _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(syscall.F_SETLK), uintptr(unsafe.Pointer(&k))) if errno != 0 { f.Close() return nil, errno } return &unlocker{f: f, abs: name}, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock_freebsd.go����������������������������������������0000644�0610621�0607500�00000003313�13172163412�024630� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lock import ( "fmt" "io" "os" "syscall" "unsafe" ) func init() { lockFn = lockFcntl } func lockFcntl(name string) (io.Closer, error) { fi, err := os.Stat(name) if err == nil && fi.Size() > 0 { return nil, fmt.Errorf("can't Lock file %q: has non-zero size", name) } f, err := os.Create(name) if err != nil { return nil, err } // This type matches C's "struct flock" defined in /usr/include/fcntl.h. // TODO: move this into the standard syscall package. k := struct { Start int64 /* off_t starting offset */ Len int64 /* off_t len = 0 means until end of file */ Pid int32 /* pid_t lock owner */ Type int16 /* short lock type: read/write, etc. */ Whence int16 /* short type of l_start */ Sysid int32 /* int remote system id or zero for local */ }{ Start: 0, Len: 0, // 0 means to lock the entire file. Pid: int32(os.Getpid()), Type: syscall.F_WRLCK, Whence: int16(os.SEEK_SET), Sysid: 0, } _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(syscall.F_SETLK), uintptr(unsafe.Pointer(&k))) if errno != 0 { f.Close() return nil, errno } return &unlocker{f: f, abs: name}, nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock_darwin_amd64.go�����������������������������������0000644�0610621�0607500�00000003253�13172163412�025500� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build darwin,amd64 // +build !appengine /* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lock import ( "fmt" "io" "os" "syscall" "unsafe" ) func init() { lockFn = lockFcntl } func lockFcntl(name string) (io.Closer, error) { fi, err := os.Stat(name) if err == nil && fi.Size() > 0 { return nil, fmt.Errorf("can't Lock file %q: has non-zero size", name) } f, err := os.Create(name) if err != nil { return nil, fmt.Errorf("Lock Create of %s failed: %v", name, err) } // This type matches C's "struct flock" defined in /usr/include/sys/fcntl.h. // TODO: move this into the standard syscall package. k := struct { Start uint64 // sizeof(off_t): 8 Len uint64 // sizeof(off_t): 8 Pid uint32 // sizeof(pid_t): 4 Type uint16 // sizeof(short): 2 Whence uint16 // sizeof(short): 2 }{ Type: syscall.F_WRLCK, Whence: uint16(os.SEEK_SET), Start: 0, Len: 0, // 0 means to lock the entire file. Pid: uint32(os.Getpid()), } _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(syscall.F_SETLK), uintptr(unsafe.Pointer(&k))) if errno != 0 { f.Close() return nil, errno } return &unlocker{f: f, abs: name}, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock_appengine.go��������������������������������������0000644�0610621�0607500�00000001416�13172163412�025166� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build appengine /* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lock import ( "errors" "io" ) func init() { lockFn = lockAppEngine } func lockAppEngine(name string) (io.Closer, error) { return nil, errors.New("Lock not available on App Engine") } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/lock/lock.go������������������������������������������������0000644�0610621�0607500�00000011233�13172163412�023136� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2013 The Go Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package lock is a file locking library. package lock import ( "encoding/json" "fmt" "io" "os" "path/filepath" "sync" ) // Lock locks the given file, creating the file if necessary. If the // file already exists, it must have zero size or an error is returned. // The lock is an exclusive lock (a write lock), but locked files // should neither be read from nor written to. Such files should have // zero size and only exist to co-ordinate ownership across processes. // // A nil Closer is returned if an error occurred. Otherwise, close that // Closer to release the lock. // // On Linux, FreeBSD and OSX, a lock has the same semantics as fcntl(2)'s // advisory locks. In particular, closing any other file descriptor for the // same file will release the lock prematurely. // // Attempting to lock a file that is already locked by the current process // has undefined behavior. // // On other operating systems, lock will fallback to using the presence and // content of a file named name + '.lock' to implement locking behavior. func Lock(name string) (io.Closer, error) { abs, err := filepath.Abs(name) if err != nil { return nil, err } lockmu.Lock() defer lockmu.Unlock() if locked[abs] { return nil, fmt.Errorf("file %q already locked", abs) } c, err := lockFn(abs) if err != nil { return nil, fmt.Errorf("cannot acquire lock: %v", err) } locked[abs] = true return c, nil } var lockFn = lockPortable // lockPortable is a portable version not using fcntl. Doesn't handle crashes as gracefully, // since it can leave stale lock files. func lockPortable(name string) (io.Closer, error) { fi, err := os.Stat(name) if err == nil && fi.Size() > 0 { st := portableLockStatus(name) switch st { case statusLocked: return nil, fmt.Errorf("file %q already locked", name) case statusStale: os.Remove(name) case statusInvalid: return nil, fmt.Errorf("can't Lock file %q: has invalid contents", name) } } f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_EXCL, 0666) if err != nil { return nil, fmt.Errorf("failed to create lock file %s %v", name, err) } if err := json.NewEncoder(f).Encode(&pidLockMeta{OwnerPID: os.Getpid()}); err != nil { return nil, fmt.Errorf("cannot write owner pid: %v", err) } return &unlocker{ f: f, abs: name, portable: true, }, nil } type lockStatus int const ( statusInvalid lockStatus = iota statusLocked statusUnlocked statusStale ) type pidLockMeta struct { OwnerPID int } func portableLockStatus(path string) lockStatus { f, err := os.Open(path) if err != nil { return statusUnlocked } defer f.Close() var meta pidLockMeta if json.NewDecoder(f).Decode(&meta) != nil { return statusInvalid } if meta.OwnerPID == 0 { return statusInvalid } p, err := os.FindProcess(meta.OwnerPID) if err != nil { // e.g. on Windows return statusStale } // On unix, os.FindProcess always is true, so we have to send // it a signal to see if it's alive. if signalZero != nil { if p.Signal(signalZero) != nil { return statusStale } } return statusLocked } var signalZero os.Signal // nil or set by lock_sigzero.go var ( lockmu sync.Mutex locked = map[string]bool{} // abs path -> true ) type unlocker struct { portable bool f *os.File abs string // once guards the close method call. once sync.Once // err holds the error returned by Close. err error } func (u *unlocker) Close() error { u.once.Do(u.close) return u.err } func (u *unlocker) close() { lockmu.Lock() defer lockmu.Unlock() delete(locked, u.abs) if u.portable { // In the portable lock implementation, it's // important to close before removing because // Windows won't allow us to remove an open // file. if err := u.f.Close(); err != nil { u.err = err } if err := os.Remove(u.abs); err != nil { // Note that if both Close and Remove fail, // we care more about the latter than the former // so we'll return that error. u.err = err } return } // In other implementatioons, it's nice for us to clean up. // If we do do this, though, it needs to be before the // u.f.Close below. os.Remove(u.abs) u.err = u.f.Close() } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/legal/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022013� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/legal/legal_test.go�����������������������������������������0000644�0610621�0607500�00000001377�13172163412�024475� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package legal import ( "testing" ) func TestRegisterLicense(t *testing.T) { initial := len(licenses) RegisterLicense("dummy") if initial+1 != len(licenses) { t.Fatal("didn't add a license") } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/legal/legal.go����������������������������������������������0000644�0610621�0607500�00000001664�13172163412�023435� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package legal provides in-process storage for compiled-in licenses. package legal var licenses []string // RegisterLicense stores the license text. // It doesn't check whether the text was already present. func RegisterLicense(text string) { licenses = append(licenses, text) return } // Licenses returns a slice of the licenses. func Licenses() []string { return licenses } ����������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/�������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�023066� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/testdata/����������������������������������������0000755�0610621�0607500�00000000000�13172163412�024677� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/testdata/loop2.json������������������������������0000644�0610621�0607500�00000000061�13172163412�026622� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "obj": ["_fileobj", "testdata/loop1.json"] } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/testdata/loop1.json������������������������������0000644�0610621�0607500�00000000061�13172163412�026621� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "obj": ["_fileobj", "testdata/loop2.json"] } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/testdata/listexpand.json�������������������������0000644�0610621�0607500�00000000121�13172163412�027737� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "list": ["foo", ["_env", "${TEST_BAR}"]], "str": ["_env", "${TEST_BAR}"] } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/testdata/include2.json���������������������������0000644�0610621�0607500�00000000025�13172163412�027274� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "key": "value" } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/testdata/include1bis.json������������������������0000644�0610621�0607500�00000000053�13172163412�027772� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "two": ["_fileobj", "include2.json"] } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/testdata/include1.json���������������������������0000644�0610621�0607500�00000000064�13172163412�027276� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "two": ["_fileobj", "testdata/include2.json"] } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/testdata/boolenv.json����������������������������0000644�0610621�0607500�00000000551�13172163412�027237� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "emptystr": ["_env", "${TEST_EMPTY}", ""], "def_false": ["_env", "${TEST_EMPTY}", false], "def_true": ["_env", "${TEST_EMPTY}", true], "set_true_def_false": ["_env", "${TEST_TRUE}", false], "set_false_def_true": ["_env", "${TEST_FALSE}", true], "one": ["_env", "${TEST_ONE}"], "zero": ["_env", "${TEST_ZERO}"], "lit_true": true, "lit_false": false } �������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/jsonconfig_test.go�������������������������������0000644�0610621�0607500�00000005302�13172163412�026613� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2011 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package jsonconfig import ( "os" "reflect" "strings" "testing" ) func testIncludes(configFile string, t *testing.T) { var c ConfigParser c.IncludeDirs = []string{"testdata"} obj, err := c.ReadFile(configFile) if err != nil { t.Fatal(err) } two := obj.RequiredObject("two") if err := obj.Validate(); err != nil { t.Error(err) } if g, e := two.RequiredString("key"), "value"; g != e { t.Errorf("sub object key = %q; want %q", g, e) } } func TestIncludesCWD(t *testing.T) { testIncludes("testdata/include1.json", t) } func TestIncludesIncludeDirs(t *testing.T) { testIncludes("testdata/include1bis.json", t) } func TestIncludeLoop(t *testing.T) { _, err := ReadFile("testdata/loop1.json") if err == nil { t.Fatal("expected an error about import cycles.") } if !strings.Contains(err.Error(), "include cycle detected") { t.Fatalf("expected an error about import cycles; got: %v", err) } } func TestBoolEnvs(t *testing.T) { os.Setenv("TEST_EMPTY", "") os.Setenv("TEST_TRUE", "true") os.Setenv("TEST_ONE", "1") os.Setenv("TEST_ZERO", "0") os.Setenv("TEST_FALSE", "false") obj, err := ReadFile("testdata/boolenv.json") if err != nil { t.Fatal(err) } if str := obj.RequiredString("emptystr"); str != "" { t.Errorf("str = %q, want empty", str) } tests := []struct { key string want bool }{ {"def_false", false}, {"def_true", true}, {"set_true_def_false", true}, {"set_false_def_true", false}, {"lit_true", true}, {"lit_false", false}, {"one", true}, {"zero", false}, } for _, tt := range tests { if v := obj.RequiredBool(tt.key); v != tt.want { t.Errorf("key %q = %v; want %v", tt.key, v, tt.want) } } if err := obj.Validate(); err != nil { t.Error(err) } } func TestListExpansion(t *testing.T) { os.Setenv("TEST_BAR", "bar") obj, err := ReadFile("testdata/listexpand.json") if err != nil { t.Fatal(err) } s := obj.RequiredString("str") l := obj.RequiredList("list") if err := obj.Validate(); err != nil { t.Error(err) } want := []string{"foo", "bar"} if !reflect.DeepEqual(l, want) { t.Errorf("got = %#v\nwant = %#v", l, want) } if s != "bar" { t.Errorf("str = %q, want %q", s, "bar") } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/jsonconfig.go������������������������������������0000644�0610621�0607500�00000015101�13172163412�025552� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2011 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package jsonconfig defines a helper type for JSON objects to be // used for configuration. package jsonconfig import ( "fmt" "sort" "strconv" "strings" ) // Obj is a JSON configuration map. type Obj map[string]interface{} // ReadFile reads JSON config data from the specified open file, expanding // all expressions. Use *ConfigParser.ReadFile instead if you // need to set c.IncludeDirs. func ReadFile(configPath string) (Obj, error) { var c ConfigParser return c.ReadFile(configPath) } func (jc Obj) RequiredObject(key string) Obj { return jc.obj(key, false) } func (jc Obj) OptionalObject(key string) Obj { return jc.obj(key, true) } func (jc Obj) obj(key string, optional bool) Obj { jc.noteKnownKey(key) ei, ok := jc[key] if !ok { if optional { return make(Obj) } jc.appendError(fmt.Errorf("Missing required config key %q (object)", key)) return make(Obj) } m, ok := ei.(map[string]interface{}) if !ok { jc.appendError(fmt.Errorf("Expected config key %q to be an object, not %T", key, ei)) return make(Obj) } return m } func (jc Obj) RequiredString(key string) string { return jc.string(key, nil) } func (jc Obj) OptionalString(key, def string) string { return jc.string(key, &def) } func (jc Obj) string(key string, def *string) string { jc.noteKnownKey(key) ei, ok := jc[key] if !ok { if def != nil { return *def } jc.appendError(fmt.Errorf("Missing required config key %q (string)", key)) return "" } s, ok := ei.(string) if !ok { jc.appendError(fmt.Errorf("Expected config key %q to be a string", key)) return "" } return s } func (jc Obj) RequiredStringOrObject(key string) interface{} { return jc.stringOrObject(key, true) } func (jc Obj) OptionalStringOrObject(key string) interface{} { return jc.stringOrObject(key, false) } func (jc Obj) stringOrObject(key string, required bool) interface{} { jc.noteKnownKey(key) ei, ok := jc[key] if !ok { if !required { return nil } jc.appendError(fmt.Errorf("Missing required config key %q (string or object)", key)) return "" } if _, ok := ei.(map[string]interface{}); ok { return ei } if _, ok := ei.(string); ok { return ei } jc.appendError(fmt.Errorf("Expected config key %q to be a string or object", key)) return "" } func (jc Obj) RequiredBool(key string) bool { return jc.bool(key, nil) } func (jc Obj) OptionalBool(key string, def bool) bool { return jc.bool(key, &def) } func (jc Obj) bool(key string, def *bool) bool { jc.noteKnownKey(key) ei, ok := jc[key] if !ok { if def != nil { return *def } jc.appendError(fmt.Errorf("Missing required config key %q (boolean)", key)) return false } switch v := ei.(type) { case bool: return v case string: b, err := strconv.ParseBool(v) if err != nil { jc.appendError(fmt.Errorf("Config key %q has bad boolean format %q", key, v)) } return b default: jc.appendError(fmt.Errorf("Expected config key %q to be a boolean", key)) return false } } func (jc Obj) RequiredInt(key string) int { return jc.int(key, nil) } func (jc Obj) OptionalInt(key string, def int) int { return jc.int(key, &def) } func (jc Obj) int(key string, def *int) int { jc.noteKnownKey(key) ei, ok := jc[key] if !ok { if def != nil { return *def } jc.appendError(fmt.Errorf("Missing required config key %q (integer)", key)) return 0 } b, ok := ei.(float64) if !ok { jc.appendError(fmt.Errorf("Expected config key %q to be a number", key)) return 0 } return int(b) } func (jc Obj) RequiredInt64(key string) int64 { return jc.int64(key, nil) } func (jc Obj) OptionalInt64(key string, def int64) int64 { return jc.int64(key, &def) } func (jc Obj) int64(key string, def *int64) int64 { jc.noteKnownKey(key) ei, ok := jc[key] if !ok { if def != nil { return *def } jc.appendError(fmt.Errorf("Missing required config key %q (integer)", key)) return 0 } b, ok := ei.(float64) if !ok { jc.appendError(fmt.Errorf("Expected config key %q to be a number", key)) return 0 } return int64(b) } func (jc Obj) RequiredList(key string) []string { return jc.requiredList(key, true) } func (jc Obj) OptionalList(key string) []string { return jc.requiredList(key, false) } func (jc Obj) requiredList(key string, required bool) []string { jc.noteKnownKey(key) ei, ok := jc[key] if !ok { if required { jc.appendError(fmt.Errorf("Missing required config key %q (list of strings)", key)) } return nil } eil, ok := ei.([]interface{}) if !ok { jc.appendError(fmt.Errorf("Expected config key %q to be a list, not %T", key, ei)) return nil } sl := make([]string, len(eil)) for i, ei := range eil { s, ok := ei.(string) if !ok { jc.appendError(fmt.Errorf("Expected config key %q index %d to be a string, not %T", key, i, ei)) return nil } sl[i] = s } return sl } func (jc Obj) noteKnownKey(key string) { _, ok := jc["_knownkeys"] if !ok { jc["_knownkeys"] = make(map[string]bool) } jc["_knownkeys"].(map[string]bool)[key] = true } func (jc Obj) appendError(err error) { ei, ok := jc["_errors"] if ok { jc["_errors"] = append(ei.([]error), err) } else { jc["_errors"] = []error{err} } } // UnknownKeys returns the keys from the config that have not yet been discovered by one of the RequiredT or OptionalT calls. func (jc Obj) UnknownKeys() []string { ei, ok := jc["_knownkeys"] var known map[string]bool if ok { known = ei.(map[string]bool) } var unknown []string for k, _ := range jc { if ok && known[k] { continue } if strings.HasPrefix(k, "_") { // Permit keys with a leading underscore as a // form of comments. continue } unknown = append(unknown, k) } sort.Strings(unknown) return unknown } func (jc Obj) Validate() error { unknown := jc.UnknownKeys() for _, k := range unknown { jc.appendError(fmt.Errorf("Unknown key %q", k)) } ei, ok := jc["_errors"] if !ok { return nil } errList := ei.([]error) if len(errList) == 1 { return errList[0] } strs := make([]string, 0) for _, v := range errList { strs = append(strs, v.Error()) } return fmt.Errorf("Multiple errors: " + strings.Join(strs, ", ")) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/jsonconfig/eval.go������������������������������������������0000644�0610621�0607500�00000021244�13172163412�024347� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2011 The go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package jsonconfig import ( "encoding/json" "errors" "fmt" "io" "log" "os" "path/filepath" "regexp" "runtime" "strconv" "strings" "github.com/juju/go4/errorutil" "github.com/juju/go4/wkfs" ) type stringVector struct { v []string } func (v *stringVector) Push(s string) { v.v = append(v.v, s) } func (v *stringVector) Pop() { v.v = v.v[:len(v.v)-1] } func (v *stringVector) Last() string { return v.v[len(v.v)-1] } // A File is the type returned by ConfigParser.Open. type File interface { io.ReadSeeker io.Closer Name() string } // ConfigParser specifies the environment for parsing a config file // and evaluating expressions. type ConfigParser struct { rootJSON Obj touchedFiles map[string]bool includeStack stringVector // Open optionally specifies an opener function. Open func(filename string) (File, error) // IncludeDirs optionally specifies where to find the other config files which are child // objects of this config, if any. Even if nil, the working directory is always searched // first. IncludeDirs []string } func (c *ConfigParser) open(filename string) (File, error) { if c.Open == nil { return wkfs.Open(filename) } return c.Open(filename) } // Validates variable names for config _env expresssions var envPattern = regexp.MustCompile(`\$\{[A-Za-z0-9_]+\}`) // ReadFile parses the provided path and returns the config file. // If path is empty, the c.Open function must be defined. func (c *ConfigParser) ReadFile(path string) (Obj, error) { if path == "" && c.Open == nil { return nil, errors.New("ReadFile of empty string but Open hook not defined") } c.touchedFiles = make(map[string]bool) var err error c.rootJSON, err = c.recursiveReadJSON(path) return c.rootJSON, err } // Decodes and evaluates a json config file, watching for include cycles. func (c *ConfigParser) recursiveReadJSON(configPath string) (decodedObject map[string]interface{}, err error) { if configPath != "" { absConfigPath, err := filepath.Abs(configPath) if err != nil { return nil, fmt.Errorf("Failed to expand absolute path for %s", configPath) } if c.touchedFiles[absConfigPath] { return nil, fmt.Errorf("ConfigParser include cycle detected reading config: %v", absConfigPath) } c.touchedFiles[absConfigPath] = true c.includeStack.Push(absConfigPath) defer c.includeStack.Pop() } var f File if f, err = c.open(configPath); err != nil { return nil, fmt.Errorf("Failed to open config: %v", err) } defer f.Close() decodedObject = make(map[string]interface{}) dj := json.NewDecoder(f) if err = dj.Decode(&decodedObject); err != nil { extra := "" if serr, ok := err.(*json.SyntaxError); ok { if _, serr := f.Seek(0, os.SEEK_SET); serr != nil { log.Fatalf("seek error: %v", serr) } line, col, highlight := errorutil.HighlightBytePosition(f, serr.Offset) extra = fmt.Sprintf(":\nError at line %d, column %d (file offset %d):\n%s", line, col, serr.Offset, highlight) } return nil, fmt.Errorf("error parsing JSON object in config file %s%s\n%v", f.Name(), extra, err) } if err = c.evaluateExpressions(decodedObject, nil, false); err != nil { return nil, fmt.Errorf("error expanding JSON config expressions in %s:\n%v", f.Name(), err) } return decodedObject, nil } var regFunc = map[string]expanderFunc{} // RegisterFunc registers a new function that may be called from JSON // configs using an array of the form ["_name", arg0, argN...]. // The provided name must begin with an underscore. func RegisterFunc(name string, fn func(c *ConfigParser, v []interface{}) (interface{}, error)) { if len(name) < 2 || !strings.HasPrefix(name, "_") { panic("illegal name") } if _, dup := regFunc[name]; dup { panic("duplicate registration of " + name) } regFunc[name] = fn } type expanderFunc func(c *ConfigParser, v []interface{}) (interface{}, error) func namedExpander(name string) (fn expanderFunc, ok bool) { switch name { case "_env": return (*ConfigParser).expandEnv, true case "_fileobj": return (*ConfigParser).expandFile, true } fn, ok = regFunc[name] return } func (c *ConfigParser) evalValue(v interface{}) (interface{}, error) { sl, ok := v.([]interface{}) if !ok { return v, nil } if name, ok := sl[0].(string); ok { if expander, ok := namedExpander(name); ok { newval, err := expander(c, sl[1:]) if err != nil { return nil, err } return newval, nil } } for i, oldval := range sl { newval, err := c.evalValue(oldval) if err != nil { return nil, err } sl[i] = newval } return v, nil } // CheckTypes parses m and returns an error if it encounters a type or value // that is not supported by this package. func (c *ConfigParser) CheckTypes(m map[string]interface{}) error { return c.evaluateExpressions(m, nil, true) } // evaluateExpressions parses recursively m, populating it with the values // that are found, unless testOnly is true. func (c *ConfigParser) evaluateExpressions(m map[string]interface{}, seenKeys []string, testOnly bool) error { for k, ei := range m { thisPath := append(seenKeys, k) switch subval := ei.(type) { case string, bool, float64, nil: continue case []interface{}: if len(subval) == 0 { continue } evaled, err := c.evalValue(subval) if err != nil { return fmt.Errorf("%s: value error %v", strings.Join(thisPath, "."), err) } if !testOnly { m[k] = evaled } case map[string]interface{}: if err := c.evaluateExpressions(subval, thisPath, testOnly); err != nil { return err } default: return fmt.Errorf("%s: unhandled type %T", strings.Join(thisPath, "."), ei) } } return nil } // Permit either: // ["_env", "VARIABLE"] (required to be set) // or ["_env", "VARIABLE", "default_value"] func (c *ConfigParser) expandEnv(v []interface{}) (interface{}, error) { hasDefault := false def := "" if len(v) < 1 || len(v) > 2 { return "", fmt.Errorf("_env expansion expected 1 or 2 args, got %d", len(v)) } s, ok := v[0].(string) if !ok { return "", fmt.Errorf("Expected a string after _env expansion; got %#v", v[0]) } boolDefault, wantsBool := false, false if len(v) == 2 { hasDefault = true switch vdef := v[1].(type) { case string: def = vdef case bool: wantsBool = true boolDefault = vdef default: return "", fmt.Errorf("Expected default value in %q _env expansion; got %#v", s, v[1]) } } var err error expanded := envPattern.ReplaceAllStringFunc(s, func(match string) string { envVar := match[2 : len(match)-1] val := os.Getenv(envVar) // Special case: if val == "" && envVar == "USER" && runtime.GOOS == "windows" { val = os.Getenv("USERNAME") } if val == "" { if hasDefault { return def } err = fmt.Errorf("couldn't expand environment variable %q", envVar) } return val }) if wantsBool { if expanded == "" { return boolDefault, nil } return strconv.ParseBool(expanded) } return expanded, err } func (c *ConfigParser) expandFile(v []interface{}) (exp interface{}, err error) { if len(v) != 1 { return "", fmt.Errorf("_file expansion expected 1 arg, got %d", len(v)) } var incPath string if incPath, err = c.ConfigFilePath(v[0].(string)); err != nil { return "", fmt.Errorf("Included config does not exist: %v", v[0]) } if exp, err = c.recursiveReadJSON(incPath); err != nil { return "", fmt.Errorf("In file included from %s:\n%v", c.includeStack.Last(), err) } return exp, nil } // ConfigFilePath checks if configFile is found and returns a usable path to it. // It first checks if configFile is an absolute path, or if it's found in the // current working directory. If not, it then checks if configFile is in one of // c.IncludeDirs. It returns an error if configFile is absolute and could not be // statted, or os.ErrNotExist if configFile was not found. func (c *ConfigParser) ConfigFilePath(configFile string) (path string, err error) { // Try to open as absolute / relative to CWD _, err = os.Stat(configFile) if err != nil && filepath.IsAbs(configFile) { return "", err } if err == nil { return configFile, nil } for _, d := range c.IncludeDirs { if _, err := os.Stat(filepath.Join(d, configFile)); err == nil { return filepath.Join(d, configFile), nil } } return "", os.ErrNotExist } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/fault/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022042� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/fault/fault.go����������������������������������������������0000644�0610621�0607500�00000003201�13172163412�023500� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2014 The Go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package fault handles fault injection for testing. package fault import ( "errors" "math/rand" "os" "strconv" "strings" ) var fakeErr = errors.New("fake injected error for testing") // An Injector reports whether fake errors should be returned. type Injector struct { failPercent int } // NewInjector returns a new fault injector with the given name. The // environment variable "FAULT_" + capital(name) + "_FAIL_PERCENT" // controls the percentage of requests that fail. If undefined or // zero, no requests fail. func NewInjector(name string) *Injector { var failPercent, _ = strconv.Atoi(os.Getenv("FAULT_" + strings.ToUpper(name) + "_FAIL_PERCENT")) return &Injector{ failPercent: failPercent, } } // ShouldFail reports whether a fake error should be returned. func (in *Injector) ShouldFail() bool { return in.failPercent > 0 && in.failPercent > rand.Intn(100) } // FailErr checks ShouldFail and, if true, assigns a fake error to err // and returns true. func (in *Injector) FailErr(err *error) bool { if !in.ShouldFail() { return false } *err = fakeErr return true } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/errorutil/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022756� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/errorutil/highlight.go��������������������������������������0000644�0610621�0607500�00000003055�13172163412�025257� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package errorutil helps make better error messages. package errorutil import ( "bufio" "bytes" "fmt" "io" "strings" ) // HighlightBytePosition takes a reader and the location in bytes of a parse // error (for instance, from json.SyntaxError.Offset) and returns the line, column, // and pretty-printed context around the error with an arrow indicating the exact // position of the syntax error. func HighlightBytePosition(f io.Reader, pos int64) (line, col int, highlight string) { line = 1 br := bufio.NewReader(f) lastLine := "" thisLine := new(bytes.Buffer) for n := int64(0); n < pos; n++ { b, err := br.ReadByte() if err != nil { break } if b == '\n' { lastLine = thisLine.String() thisLine.Reset() line++ col = 1 } else { col++ thisLine.WriteByte(b) } } if line > 1 { highlight += fmt.Sprintf("%5d: %s\n", line-1, lastLine) } highlight += fmt.Sprintf("%5d: %s\n", line, thisLine.String()) highlight += fmt.Sprintf("%s^\n", strings.Repeat(" ", col+5)) return } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/dependencies.tsv��������������������������������������������0000644�0610621�0607500�00000001021�13172163412�024105� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������github.com/golang/protobuf git 3c84672111d91bb5ac31719e112f9f7126a0e26e 2016-02-21T21:49:41Z golang.org/x/net git b6d7b1396ec874c3b00f6c84cd4301a17c56c8ed 2016-02-17T01:13:48Z golang.org/x/oauth2 git 2cd4472c321b6cba78e029d99f0e7fe51032fd21 2016-02-22T10:17:51Z google.golang.org/api git e6294e63a06b2be522ff3d328d8cacded0b1bd31 2016-02-19T05:54:22Z google.golang.org/cloud git 872c736f496c2ba12786bedbb8325576bbdb33cf 2016-02-19T05:41:52Z google.golang.org/grpc git 178b68e2819d3ed711040301c12f3f97b6c270ce 2016-02-17T23:38:44Z ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/ctxutil/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022423� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/ctxutil/ctxutil.go������������������������������������������0000644�0610621�0607500�00000002631�13172163412�024450� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The Go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package ctxutil contains golang.org/x/net/context related utilities. package ctxutil import ( "net/http" "golang.org/x/net/context" "golang.org/x/oauth2" ) // HTTPClient is the context key to use with golang.org/x/net/context's WithValue function // to associate an *http.Client value with a context. // // We use the same value as the oauth2 package (which first introduced this key) rather // than creating a new one and forcing users to possibly set two. var HTTPClient = oauth2.HTTPClient // Client returns the HTTP client to use for the provided context. // If ctx is non-nil and has an associated HTTP client, that client is returned. // Otherwise, http.DefaultClient is returned. func Client(ctx context.Context) *http.Client { if ctx != nil { if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok { return hc } } return http.DefaultClient } �������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/cloud/������������������������������������������������������0000755�0610621�0607500�00000000000�13172163412�022035� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/cloud/google/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163412�023311� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/cloud/google/gcsutil/���������������������������������������0000755�0610621�0607500�00000000000�13172163412�024763� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/cloud/google/gcsutil/storage.go�����������������������������0000644�0610621�0607500�00000012054�13172163412�026760� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The Go4 Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package gcsutil provides tools for accessing Google Cloud Storage until they can be // completely replaced by google.golang.org/cloud/storage. package gcsutil import ( "encoding/xml" "errors" "fmt" "io" "net/http" "net/url" "os" "strings" "github.com/juju/go4/ctxutil" "golang.org/x/net/context" "google.golang.org/cloud/storage" ) const gsAccessURL = "https://storage.googleapis.com" // An Object holds the name of an object (its bucket and key) within // Google Cloud Storage. type Object struct { Bucket string Key string } func (o *Object) valid() error { if o == nil { return errors.New("invalid nil Object") } if o.Bucket == "" { return errors.New("missing required Bucket field in Object") } if o.Key == "" { return errors.New("missing required Key field in Object") } return nil } // A SizedObject holds the bucket, key, and size of an object. type SizedObject struct { Object Size int64 } func (o *Object) String() string { if o == nil { return "<nil *Object>" } return fmt.Sprintf("%v/%v", o.Bucket, o.Key) } func (so SizedObject) String() string { return fmt.Sprintf("%v/%v (%vB)", so.Bucket, so.Key, so.Size) } // Makes a simple body-less google storage request func simpleRequest(method, url_ string) (*http.Request, error) { req, err := http.NewRequest(method, url_, nil) if err != nil { return nil, err } req.Header.Set("x-goog-api-version", "2") return req, err } // ErrInvalidRange is used when the server has returned http.StatusRequestedRangeNotSatisfiable. var ErrInvalidRange = errors.New("gcsutil: requested range not satisfiable") // GetPartialObject fetches part of a Google Cloud Storage object. // This function relies on the ctx ctxutil.HTTPClient value being set to an OAuth2 // authorized and authenticated HTTP client. // If length is negative, the rest of the object is returned. // It returns ErrInvalidRange if the server replies with http.StatusRequestedRangeNotSatisfiable. // The caller must call Close on the returned value. func GetPartialObject(ctx context.Context, obj Object, offset, length int64) (io.ReadCloser, error) { if offset < 0 { return nil, errors.New("invalid negative offset") } if err := obj.valid(); err != nil { return nil, err } req, err := simpleRequest("GET", gsAccessURL+"/"+obj.Bucket+"/"+obj.Key) if err != nil { return nil, err } if length >= 0 { req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) } else { req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) } req.Cancel = ctx.Done() res, err := ctxutil.Client(ctx).Do(req) if err != nil { return nil, fmt.Errorf("GET (offset=%d, length=%d) failed: %v\n", offset, length, err) } if res.StatusCode == http.StatusNotFound { res.Body.Close() return nil, os.ErrNotExist } if !(res.StatusCode == http.StatusPartialContent || (offset == 0 && res.StatusCode == http.StatusOK)) { res.Body.Close() if res.StatusCode == http.StatusRequestedRangeNotSatisfiable { return nil, ErrInvalidRange } return nil, fmt.Errorf("GET (offset=%d, length=%d) got failed status: %v\n", offset, length, res.Status) } return res.Body, nil } // EnumerateObjects lists the objects in a bucket. // This function relies on the ctx oauth2.HTTPClient value being set to an OAuth2 // authorized and authenticated HTTP client. // If after is non-empty, listing will begin with lexically greater object names. // If limit is non-zero, the length of the list will be limited to that number. func EnumerateObjects(ctx context.Context, bucket, after string, limit int) ([]*storage.ObjectAttrs, error) { // Build url, with query params var params []string if after != "" { params = append(params, "marker="+url.QueryEscape(after)) } if limit > 0 { params = append(params, fmt.Sprintf("max-keys=%v", limit)) } query := "" if len(params) > 0 { query = "?" + strings.Join(params, "&") } req, err := simpleRequest("GET", gsAccessURL+"/"+bucket+"/"+query) if err != nil { return nil, err } req.Cancel = ctx.Done() res, err := ctxutil.Client(ctx).Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("gcsutil: bad enumerate response code: %v", res.Status) } var xres struct { Contents []SizedObject } if err = xml.NewDecoder(res.Body).Decode(&xres); err != nil { return nil, err } objAttrs := make([]*storage.ObjectAttrs, len(xres.Contents)) for k, o := range xres.Contents { objAttrs[k] = &storage.ObjectAttrs{ Name: o.Key, Size: o.Size, } } return objAttrs, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/cloud/google/gceutil/���������������������������������������0000755�0610621�0607500�00000000000�13172163412�024745� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/cloud/google/gceutil/gceutil.go�����������������������������0000644�0610621�0607500�00000006273�13172163412�026740� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package gceutil provides utility functions to help with instances on // Google Compute Engine. package gceutil import ( "encoding/json" "errors" "net/http" "strings" "time" "google.golang.org/api/compute/v1" ) // CoreOSImageURL returns the URL of the latest stable CoreOS image for running on Google Compute Engine. func CoreOSImageURL(cl *http.Client) (string, error) { resp, err := cl.Get("https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images") if err != nil { return "", err } defer resp.Body.Close() type coreOSImage struct { SelfLink string CreationTimestamp time.Time Name string } type coreOSImageList struct { Items []coreOSImage } imageList := &coreOSImageList{} if err := json.NewDecoder(resp.Body).Decode(imageList); err != nil { return "", err } if imageList == nil || len(imageList.Items) == 0 { return "", errors.New("no images list in response") } imageURL := "" var max time.Time // latest stable image creation time for _, v := range imageList.Items { if !strings.HasPrefix(v.Name, "coreos-stable") { continue } if v.CreationTimestamp.After(max) { max = v.CreationTimestamp imageURL = v.SelfLink } } if imageURL == "" { return "", errors.New("no stable coreOS image found") } return imageURL, nil } // InstanceGroupAndManager contains both an InstanceGroup and // its InstanceGroupManager, if any. type InstanceGroupAndManager struct { Group *compute.InstanceGroup // Manager is the manager of the Group. It may be nil. Manager *compute.InstanceGroupManager } // InstanceGroups returns all the instance groups in a project's zone, along // with their associated InstanceGroupManagers. // The returned map is keyed by the instance group identifier URL. func InstanceGroups(svc *compute.Service, proj, zone string) (map[string]InstanceGroupAndManager, error) { managerList, err := svc.InstanceGroupManagers.List(proj, zone).Do() if err != nil { return nil, err } if managerList.NextPageToken != "" { return nil, errors.New("too many managers; pagination not supported") } managedBy := make(map[string]*compute.InstanceGroupManager) // instance group URL -> its manager for _, it := range managerList.Items { managedBy[it.InstanceGroup] = it } groupList, err := svc.InstanceGroups.List(proj, zone).Do() if err != nil { return nil, err } if groupList.NextPageToken != "" { return nil, errors.New("too many instance groups; pagination not supported") } ret := make(map[string]InstanceGroupAndManager) for _, it := range groupList.Items { ret[it.SelfLink] = InstanceGroupAndManager{it, managedBy[it.SelfLink]} } return ret, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/cloud/cloudlaunch/������������������������������������������0000755�0610621�0607500�00000000000�13172163412�024336� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/cloud/cloudlaunch/cloudlaunch.go����������������������������0000644�0610621�0607500�00000027257�13172163412�027203� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package cloudlaunch helps binaries run themselves on The Cloud, copying // themselves to GCE. package cloudlaunch import ( "encoding/json" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "os" "path" "path/filepath" "runtime" "strings" "time" "github.com/juju/go4/cloud/google/gceutil" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/google" compute "google.golang.org/api/compute/v1" "google.golang.org/api/googleapi" storageapi "google.golang.org/api/storage/v1" "google.golang.org/cloud" "google.golang.org/cloud/storage" ) func readFile(v string) string { slurp, err := ioutil.ReadFile(v) if err != nil { log.Fatalf("Error reading %s: %v", v, err) } return strings.TrimSpace(string(slurp)) } const baseConfig = `#cloud-config coreos: update: group: stable reboot-strategy: off units: - name: $NAME.service command: start content: | [Unit] Description=$NAME service After=network.target [Service] Type=simple ExecStartPre=/bin/sh -c 'mkdir -p /opt/bin && /usr/bin/curl --silent -f -o /opt/bin/$NAME $URL?$(date +%s) && chmod +x /opt/bin/$NAME' ExecStart=/opt/bin/$NAME RestartSec=10 Restart=always StartLimitInterval=0 [Install] WantedBy=network-online.target ` // RestartPolicy controls whether the binary automatically restarts. type RestartPolicy int const ( RestartOnUpdates RestartPolicy = iota RestartNever // TODO: more graceful restarts; make systemd own listening on network sockets, // don't break connections. ) type Config struct { // Name is the name of a service to run. // This is the name of the systemd service (without .service) // and the name of the GCE instance. Name string // RestartPolicy controls whether the binary automatically restarts // on updates. The zero value means automatic. RestartPolicy RestartPolicy // BinaryBucket and BinaryObject are the GCS bucket and object // within that bucket containing the Linux binary to download // on boot and occasionally run. This binary must be public // (at least for now). BinaryBucket string BinaryObject string // defaults to Name GCEProjectID string Zone string // defaults to us-central1-f SSD bool Scopes []string // any additional scopes MachineType string InstanceName string } // cloudLaunch is a launch of a Config. type cloudLaunch struct { *Config oauthClient *http.Client computeService *compute.Service } func (c *Config) binaryURL() string { return "https://storage.googleapis.com/" + c.BinaryBucket + "/" + c.binaryObject() } func (c *Config) instName() string { return c.Name } // for now func (c *Config) zone() string { return strDefault(c.Zone, "us-central1-f") } func (c *Config) machineType() string { return strDefault(c.MachineType, "g1-small") } func (c *Config) binaryObject() string { return strDefault(c.BinaryObject, c.Name) } func (c *Config) projectAPIURL() string { return "https://www.googleapis.com/compute/v1/projects/" + c.GCEProjectID } func (c *Config) machineTypeURL() string { return c.projectAPIURL() + "/zones/" + c.zone() + "/machineTypes/" + c.machineType() } func strDefault(a, b string) string { if a != "" { return a } return b } var ( doLaunch = flag.Bool("cloudlaunch", false, "Deploy or update this binary to the cloud. Must be on Linux, for now.") ) func (c *Config) MaybeDeploy() { flag.Parse() if !*doLaunch { go c.restartLoop() return } defer os.Exit(1) // backup, in case we return without Fatal or os.Exit later if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" { log.Fatal("Can only use --cloudlaunch on linux/amd64, for now.") } if c.GCEProjectID == "" { log.Fatal("cloudconfig.GCEProjectID is empty") } filename := filepath.Join(os.Getenv("HOME"), "keys", c.GCEProjectID+".key.json") log.Printf("Using OAuth config from JSON service file: %s", filename) jwtConf, err := google.JWTConfigFromJSON([]byte(readFile(filename)), append([]string{ storageapi.DevstorageFullControlScope, compute.ComputeScope, "https://www.googleapis.com/auth/cloud-platform", }, c.Scopes...)...) if err != nil { log.Fatalf("ConfigFromJSON: %v", err) } cl := &cloudLaunch{ Config: c, oauthClient: jwtConf.Client(oauth2.NoContext), } cl.computeService, _ = compute.New(cl.oauthClient) cl.uploadBinary() cl.createInstance() os.Exit(0) } func (c *Config) restartLoop() { if c.RestartPolicy == RestartNever { return } url := "https://storage.googleapis.com/" + c.BinaryBucket + "/" + c.binaryObject() var lastEtag string for { res, err := http.Head(url + "?" + fmt.Sprint(time.Now().Unix())) if err != nil { log.Printf("Warning: %v", err) time.Sleep(15 * time.Second) continue } etag := res.Header.Get("Etag") if etag == "" { log.Printf("Warning, no ETag in response: %v", res) time.Sleep(15 * time.Second) continue } if lastEtag != "" && etag != lastEtag { log.Printf("Binary updated; restarting.") // TODO: more graceful restart, letting systemd own the network connections. // Then we can finish up requests here. os.Exit(0) } lastEtag = etag time.Sleep(15 * time.Second) } } // uploadBinary uploads the currently-running Linux binary. // It crashes if it fails. func (cl *cloudLaunch) uploadBinary() { ctx := context.Background() if cl.BinaryBucket == "" { log.Fatal("cloudlaunch: Config.BinaryBucket is empty") } stoClient, err := storage.NewClient(ctx, cloud.WithBaseHTTP(cl.oauthClient)) if err != nil { log.Fatal(err) } w := stoClient.Bucket(cl.BinaryBucket).Object(cl.binaryObject()).NewWriter(ctx) if err != nil { log.Fatal(err) } w.ACL = []storage.ACLRule{ // If you don't give the owners access, the web UI seems to // have a bug and doesn't have access to see that it's public, so // won't render the "Shared Publicly" link. So we do that, even // though it's dumb and unnecessary otherwise: { Entity: storage.ACLEntity("project-owners-" + cl.GCEProjectID), Role: storage.RoleOwner, }, // Public, so our systemd unit can get it easily: { Entity: storage.AllUsers, Role: storage.RoleReader, }, } w.CacheControl = "no-cache" selfPath := getSelfPath() log.Printf("Uploading %q to %v", selfPath, cl.binaryURL()) f, err := os.Open(selfPath) if err != nil { log.Fatal(err) } defer f.Close() n, err := io.Copy(w, f) if err != nil { log.Fatal(err) } if err := w.Close(); err != nil { log.Fatal(err) } log.Printf("Uploaded %d bytes", n) } func getSelfPath() string { if runtime.GOOS != "linux" { panic("TODO") } v, err := os.Readlink("/proc/self/exe") if err != nil { log.Fatal(err) } return v } func zoneInRegion(zone, regionURL string) bool { if zone == "" { panic("empty zone") } if regionURL == "" { panic("empty regionURL") } // zone is like "us-central1-f" // regionURL is like "https://www.googleapis.com/compute/v1/projects/camlistore-website/regions/us-central1" region := path.Base(regionURL) // "us-central1" if region == "" { panic("empty region") } return strings.HasPrefix(zone, region) } // findIP finds an IP address to use, or returns the empty string if none is found. // It tries to find a reserved one in the same region where the name of the reserved IP // is "NAME-ip" and the IP is not in use. func (cl *cloudLaunch) findIP() string { // Try to find it by name. aggAddrList, err := cl.computeService.Addresses.AggregatedList(cl.GCEProjectID).Do() if err != nil { log.Fatal(err) } // https://godoc.org/google.golang.org/api/compute/v1#AddressAggregatedList var ip string IPLoop: for _, asl := range aggAddrList.Items { for _, addr := range asl.Addresses { log.Printf(" addr: %#v", addr) if addr.Name == cl.Name+"-ip" && addr.Status == "RESERVED" && zoneInRegion(cl.zone(), addr.Region) { ip = addr.Address break IPLoop } } } return ip } func (cl *cloudLaunch) createInstance() { inst := cl.lookupInstance() if inst != nil { log.Printf("Instance exists; not re-creating.") return } log.Printf("Instance doesn't exist; creating...") ip := cl.findIP() log.Printf("Found IP: %v", ip) cloudConfig := strings.NewReplacer( "$NAME", cl.Name, "$URL", cl.binaryURL(), ).Replace(baseConfig) instance := &compute.Instance{ Name: cl.instName(), Description: cl.Name, MachineType: cl.machineTypeURL(), Disks: []*compute.AttachedDisk{cl.instanceDisk()}, Tags: &compute.Tags{ Items: []string{"http-server", "https-server"}, }, Metadata: &compute.Metadata{ Items: []*compute.MetadataItems{ { Key: "user-data", Value: googleapi.String(cloudConfig), }, }, }, NetworkInterfaces: []*compute.NetworkInterface{ &compute.NetworkInterface{ AccessConfigs: []*compute.AccessConfig{ &compute.AccessConfig{ Type: "ONE_TO_ONE_NAT", Name: "External NAT", NatIP: ip, }, }, Network: cl.projectAPIURL() + "/global/networks/default", }, }, ServiceAccounts: []*compute.ServiceAccount{ { Email: "default", Scopes: cl.Scopes, }, }, } log.Printf("Creating instance...") op, err := cl.computeService.Instances.Insert(cl.GCEProjectID, cl.zone(), instance).Do() if err != nil { log.Fatalf("Failed to create instance: %v", err) } opName := op.Name log.Printf("Created. Waiting on operation %v", opName) OpLoop: for { time.Sleep(2 * time.Second) op, err := cl.computeService.ZoneOperations.Get(cl.GCEProjectID, cl.zone(), opName).Do() if err != nil { log.Fatalf("Failed to get op %s: %v", opName, err) } switch op.Status { case "PENDING", "RUNNING": log.Printf("Waiting on operation %v", opName) continue case "DONE": if op.Error != nil { for _, operr := range op.Error.Errors { log.Printf("Error: %+v", operr) } log.Fatalf("Failed to start.") } log.Printf("Success. %+v", op) break OpLoop default: log.Fatalf("Unknown status %q: %+v", op.Status, op) } } inst, err = cl.computeService.Instances.Get(cl.GCEProjectID, cl.zone(), cl.instName()).Do() if err != nil { log.Fatalf("Error getting instance after creation: %v", err) } ij, _ := json.MarshalIndent(inst, "", " ") log.Printf("%s", ij) log.Printf("Instance created.") os.Exit(0) } // returns nil if instance doesn't exist. func (cl *cloudLaunch) lookupInstance() *compute.Instance { inst, err := cl.computeService.Instances.Get(cl.GCEProjectID, cl.zone(), cl.instName()).Do() if ae, ok := err.(*googleapi.Error); ok && ae.Code == 404 { return nil } else if err != nil { log.Fatalf("Instances.Get: %v", err) } return inst } func (cl *cloudLaunch) instanceDisk() *compute.AttachedDisk { imageURL, err := gceutil.CoreOSImageURL(cl.oauthClient) if err != nil { log.Fatalf("error looking up latest CoreOS stable image: %v", err) } diskName := cl.instName() + "-coreos-stateless-pd" var diskType string if cl.SSD { diskType = cl.projectAPIURL() + "/zones/" + cl.zone() + "/diskTypes/pd-ssd" } return &compute.AttachedDisk{ AutoDelete: true, Boot: true, Type: "PERSISTENT", InitializeParams: &compute.AttachedDiskInitializeParams{ DiskName: diskName, SourceImage: imageURL, DiskSizeGb: 50, DiskType: diskType, }, } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/bytereplacer/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163412�023410� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/bytereplacer/bytereplacer_test.go���������������������������0000644�0610621�0607500�00000025774�13172163412�027476� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package bytereplacer import ( "bytes" "strings" "testing" ) var htmlEscaper = New( "&", "&amp;", "<", "&lt;", ">", "&gt;", `"`, "&quot;", "'", "&apos;", ) var htmlUnescaper = New( "&amp;", "&", "&lt;", "<", "&gt;", ">", "&quot;", `"`, "&apos;", "'", ) var capitalLetters = New("a", "A", "b", "B") func TestReplacer(t *testing.T) { type testCase struct { r *Replacer in, out string } var testCases []testCase // str converts 0xff to "\xff". This isn't just string(b) since that converts to UTF-8. str := func(b byte) string { return string([]byte{b}) } var s []string // inc maps "\x00"->"\x01", ..., "a"->"b", "b"->"c", ..., "\xff"->"\x00". s = nil for i := 0; i < 256; i++ { s = append(s, str(byte(i)), str(byte(i+1))) } inc := New(s...) // Test cases with 1-byte old strings, 1-byte new strings. testCases = append(testCases, testCase{capitalLetters, "brad", "BrAd"}, testCase{capitalLetters, strings.Repeat("a", (32<<10)+123), strings.Repeat("A", (32<<10)+123)}, testCase{capitalLetters, "", ""}, testCase{inc, "brad", "csbe"}, testCase{inc, "\x00\xff", "\x01\x00"}, testCase{inc, "", ""}, testCase{New("a", "1", "a", "2"), "brad", "br1d"}, ) // repeat maps "a"->"a", "b"->"bb", "c"->"ccc", ... s = nil for i := 0; i < 256; i++ { n := i + 1 - 'a' if n < 1 { n = 1 } s = append(s, str(byte(i)), strings.Repeat(str(byte(i)), n)) } repeat := New(s...) // Test cases with 1-byte old strings, variable length new strings. testCases = append(testCases, testCase{htmlEscaper, "No changes", "No changes"}, testCase{htmlEscaper, "I <3 escaping & stuff", "I &lt;3 escaping &amp; stuff"}, testCase{htmlEscaper, "&&&", "&amp;&amp;&amp;"}, testCase{htmlEscaper, "", ""}, testCase{repeat, "brad", "bbrrrrrrrrrrrrrrrrrradddd"}, testCase{repeat, "abba", "abbbba"}, testCase{repeat, "", ""}, testCase{New("a", "11", "a", "22"), "brad", "br11d"}, ) // The remaining test cases have variable length old strings. testCases = append(testCases, testCase{htmlUnescaper, "&amp;amp;", "&amp;"}, testCase{htmlUnescaper, "&lt;b&gt;HTML&apos;s neat&lt;/b&gt;", "<b>HTML's neat</b>"}, testCase{htmlUnescaper, "", ""}, testCase{New("a", "1", "a", "2", "xxx", "xxx"), "brad", "br1d"}, testCase{New("a", "1", "aa", "2", "aaa", "3"), "aaaa", "1111"}, testCase{New("aaa", "3", "aa", "2", "a", "1"), "aaaa", "31"}, ) // gen1 has multiple old strings of variable length. There is no // overall non-empty common prefix, but some pairwise common prefixes. gen1 := New( "aaa", "3[aaa]", "aa", "2[aa]", "a", "1[a]", "i", "i", "longerst", "most long", "longer", "medium", "long", "short", "xx", "xx", "x", "X", "X", "Y", "Y", "Z", ) testCases = append(testCases, testCase{gen1, "fooaaabar", "foo3[aaa]b1[a]r"}, testCase{gen1, "long, longerst, longer", "short, most long, medium"}, testCase{gen1, "xxxxx", "xxxxX"}, testCase{gen1, "XiX", "YiY"}, testCase{gen1, "", ""}, ) // gen2 has multiple old strings with no pairwise common prefix. gen2 := New( "roses", "red", "violets", "blue", "sugar", "sweet", ) testCases = append(testCases, testCase{gen2, "roses are red, violets are blue...", "red are red, blue are blue..."}, testCase{gen2, "", ""}, ) // gen3 has multiple old strings with an overall common prefix. gen3 := New( "abracadabra", "poof", "abracadabrakazam", "splat", "abraham", "lincoln", "abrasion", "scrape", "abraham", "isaac", ) testCases = append(testCases, testCase{gen3, "abracadabrakazam abraham", "poofkazam lincoln"}, testCase{gen3, "abrasion abracad", "scrape abracad"}, testCase{gen3, "abba abram abrasive", "abba abram abrasive"}, testCase{gen3, "", ""}, ) // foo{1,2,3,4} have multiple old strings with an overall common prefix // and 1- or 2- byte extensions from the common prefix. foo1 := New( "foo1", "A", "foo2", "B", "foo3", "C", ) foo2 := New( "foo1", "A", "foo2", "B", "foo31", "C", "foo32", "D", ) foo3 := New( "foo11", "A", "foo12", "B", "foo31", "C", "foo32", "D", ) foo4 := New( "foo12", "B", "foo32", "D", ) testCases = append(testCases, testCase{foo1, "fofoofoo12foo32oo", "fofooA2C2oo"}, testCase{foo1, "", ""}, testCase{foo2, "fofoofoo12foo32oo", "fofooA2Doo"}, testCase{foo2, "", ""}, testCase{foo3, "fofoofoo12foo32oo", "fofooBDoo"}, testCase{foo3, "", ""}, testCase{foo4, "fofoofoo12foo32oo", "fofooBDoo"}, testCase{foo4, "", ""}, ) // genAll maps "\x00\x01\x02...\xfe\xff" to "[all]", amongst other things. allBytes := make([]byte, 256) for i := range allBytes { allBytes[i] = byte(i) } allString := string(allBytes) genAll := New( allString, "[all]", "\xff", "[ff]", "\x00", "[00]", ) testCases = append(testCases, testCase{genAll, allString, "[all]"}, testCase{genAll, "a\xff" + allString + "\x00", "a[ff][all][00]"}, testCase{genAll, "", ""}, ) // Test cases with empty old strings. blankToX1 := New("", "X") blankToX2 := New("", "X", "", "") blankHighPriority := New("", "X", "o", "O") blankLowPriority := New("o", "O", "", "X") blankNoOp1 := New("", "") blankNoOp2 := New("", "", "", "A") blankFoo := New("", "X", "foobar", "R", "foobaz", "Z") testCases = append(testCases, testCase{blankToX1, "foo", "XfXoXoX"}, testCase{blankToX1, "", "X"}, testCase{blankToX2, "foo", "XfXoXoX"}, testCase{blankToX2, "", "X"}, testCase{blankHighPriority, "oo", "XOXOX"}, testCase{blankHighPriority, "ii", "XiXiX"}, testCase{blankHighPriority, "oiio", "XOXiXiXOX"}, testCase{blankHighPriority, "iooi", "XiXOXOXiX"}, testCase{blankHighPriority, "", "X"}, testCase{blankLowPriority, "oo", "OOX"}, testCase{blankLowPriority, "ii", "XiXiX"}, testCase{blankLowPriority, "oiio", "OXiXiOX"}, testCase{blankLowPriority, "iooi", "XiOOXiX"}, testCase{blankLowPriority, "", "X"}, testCase{blankNoOp1, "foo", "foo"}, testCase{blankNoOp1, "", ""}, testCase{blankNoOp2, "foo", "foo"}, testCase{blankNoOp2, "", ""}, testCase{blankFoo, "foobarfoobaz", "XRXZX"}, testCase{blankFoo, "foobar-foobaz", "XRX-XZX"}, testCase{blankFoo, "", "X"}, ) // single string replacer abcMatcher := New("abc", "[match]") testCases = append(testCases, testCase{abcMatcher, "", ""}, testCase{abcMatcher, "ab", "ab"}, testCase{abcMatcher, "abc", "[match]"}, testCase{abcMatcher, "abcd", "[match]d"}, testCase{abcMatcher, "cabcabcdabca", "c[match][match]d[match]a"}, ) // Issue 6659 cases (more single string replacer) noHello := New("Hello", "") testCases = append(testCases, testCase{noHello, "Hello", ""}, testCase{noHello, "Hellox", "x"}, testCase{noHello, "xHello", "x"}, testCase{noHello, "xHellox", "xx"}, ) // No-arg test cases. nop := New() testCases = append(testCases, testCase{nop, "abc", "abc"}, testCase{nop, "", ""}, ) // Run the test cases. for i, tc := range testCases { { // Replace with len(in) == cap(in) in := make([]byte, len(tc.in)) copy(in, tc.in) if s := string(tc.r.Replace(in)); s != tc.out { t.Errorf("%d. Replace(%q /* len == cap */) = %q, want %q", i, tc.in, s, tc.out) } } { // Replace with len(in) < cap(in) in := make([]byte, len(tc.in), len(tc.in)*2) copy(in, tc.in) if s := string(tc.r.Replace(in)); s != tc.out { t.Errorf("%d. Replace(%q /* len < cap */) = %q, want %q", i, tc.in, s, tc.out) } } } } func BenchmarkGenericNoMatch(b *testing.B) { str := []byte(strings.Repeat("A", 100) + strings.Repeat("B", 100)) generic := New("a", "A", "b", "B", "12", "123") // varying lengths forces generic for i := 0; i < b.N; i++ { generic.Replace(str) } } func BenchmarkGenericMatch1(b *testing.B) { str := []byte(strings.Repeat("a", 100) + strings.Repeat("b", 100)) generic := New("a", "A", "b", "B", "12", "123") for i := 0; i < b.N; i++ { generic.Replace(str) } } func BenchmarkGenericMatch2(b *testing.B) { str := bytes.Repeat([]byte("It&apos;s &lt;b&gt;HTML&lt;/b&gt;!"), 100) for i := 0; i < b.N; i++ { htmlUnescaper.Replace(str) } } func benchmarkSingleString(b *testing.B, pattern, text string) { r := New(pattern, "[match]") buf := make([]byte, len(text), len(text)*7) b.SetBytes(int64(len(text))) b.ResetTimer() for i := 0; i < b.N; i++ { copy(buf, text) r.Replace(buf) } } func BenchmarkSingleMaxSkipping(b *testing.B) { benchmarkSingleString(b, strings.Repeat("b", 25), strings.Repeat("a", 10000)) } func BenchmarkSingleLongSuffixFail(b *testing.B) { benchmarkSingleString(b, "b"+strings.Repeat("a", 500), strings.Repeat("a", 1002)) } func BenchmarkSingleMatch(b *testing.B) { benchmarkSingleString(b, "abcdef", strings.Repeat("abcdefghijklmno", 1000)) } func benchmarkReplacer(b *testing.B, r *Replacer, str string) { buf := make([]byte, len(str)) b.ResetTimer() for i := 0; i < b.N; i++ { copy(buf, str) r.Replace(buf) } } func BenchmarkByteByteNoMatch(b *testing.B) { benchmarkReplacer(b, capitalLetters, strings.Repeat("A", 100)+strings.Repeat("B", 100)) } func BenchmarkByteByteMatch(b *testing.B) { benchmarkReplacer(b, capitalLetters, strings.Repeat("a", 100)+strings.Repeat("b", 100)) } func BenchmarkByteStringMatch(b *testing.B) { benchmarkReplacer(b, htmlEscaper, "<"+strings.Repeat("a", 99)+strings.Repeat("b", 99)+">") } func BenchmarkHTMLEscapeNew(b *testing.B) { benchmarkReplacer(b, htmlEscaper, "I <3 to escape HTML & other text too.") } func BenchmarkHTMLEscapeOld(b *testing.B) { str := "I <3 to escape HTML & other text too." buf := make([]byte, len(str)) for i := 0; i < b.N; i++ { copy(buf, str) oldHTMLEscape(buf) } } // The http package's old HTML escaping function in bytes form. func oldHTMLEscape(s []byte) []byte { s = bytes.Replace(s, []byte("&"), []byte("&amp;"), -1) s = bytes.Replace(s, []byte("<"), []byte("&lt;"), -1) s = bytes.Replace(s, []byte(">"), []byte("&gt;"), -1) s = bytes.Replace(s, []byte(`"`), []byte("&quot;"), -1) s = bytes.Replace(s, []byte("'"), []byte("&apos;"), -1) return s } // BenchmarkByteByteReplaces compares byteByteImpl against multiple Replaces. func BenchmarkByteByteReplaces(b *testing.B) { str := strings.Repeat("a", 100) + strings.Repeat("b", 100) for i := 0; i < b.N; i++ { bytes.Replace(bytes.Replace([]byte(str), []byte{'a'}, []byte{'A'}, -1), []byte{'b'}, []byte{'B'}, -1) } } // BenchmarkByteByteMap compares byteByteImpl against Map. func BenchmarkByteByteMap(b *testing.B) { str := strings.Repeat("a", 100) + strings.Repeat("b", 100) fn := func(r rune) rune { switch r { case 'a': return 'A' case 'b': return 'B' } return r } for i := 0; i < b.N; i++ { bytes.Map(fn, []byte(str)) } } ����lxd-2.0.11/dist/src/github.com/juju/go4/bytereplacer/bytereplacer.go��������������������������������0000644�0610621�0607500�00000016146�13172163412�026430� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* Copyright 2015 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package bytereplacer provides a utility for replacing parts of byte slices. package bytereplacer import "bytes" // Replacer replaces a list of strings with replacements. // It is safe for concurrent use by multiple goroutines. type Replacer struct { r replacer } // replacer is the interface that a replacement algorithm needs to implement. type replacer interface { // Replace performs all replacements, in-place if possible. Replace(s []byte) []byte } // New returns a new Replacer from a list of old, new string pairs. // Replacements are performed in order, without overlapping matches. func New(oldnew ...string) *Replacer { if len(oldnew)%2 == 1 { panic("bytes.NewReplacer: odd argument count") } allNewBytes := true for i := 0; i < len(oldnew); i += 2 { if len(oldnew[i]) != 1 { return &Replacer{r: makeGenericReplacer(oldnew)} } if len(oldnew[i+1]) != 1 { allNewBytes = false } } if allNewBytes { r := byteReplacer{} for i := range r { r[i] = byte(i) } // The first occurrence of old->new map takes precedence // over the others with the same old string. for i := len(oldnew) - 2; i >= 0; i -= 2 { o := oldnew[i][0] n := oldnew[i+1][0] r[o] = n } return &Replacer{r: &r} } return &Replacer{r: makeGenericReplacer(oldnew)} } // Replace performs all replacements in-place on s. If the capacity // of s is not sufficient, a new slice is allocated, otherwise Replace // returns s. func (r *Replacer) Replace(s []byte) []byte { return r.r.Replace(s) } type trieNode struct { value []byte priority int prefix []byte next *trieNode table []*trieNode } func (t *trieNode) add(key, val []byte, priority int, r *genericReplacer) { if len(key) == 0 { if t.priority == 0 { t.value = val t.priority = priority } return } if len(t.prefix) > 0 { // Need to split the prefix among multiple nodes. var n int // length of the longest common prefix for ; n < len(t.prefix) && n < len(key); n++ { if t.prefix[n] != key[n] { break } } if n == len(t.prefix) { t.next.add(key[n:], val, priority, r) } else if n == 0 { // First byte differs, start a new lookup table here. Looking up // what is currently t.prefix[0] will lead to prefixNode, and // looking up key[0] will lead to keyNode. var prefixNode *trieNode if len(t.prefix) == 1 { prefixNode = t.next } else { prefixNode = &trieNode{ prefix: t.prefix[1:], next: t.next, } } keyNode := new(trieNode) t.table = make([]*trieNode, r.tableSize) t.table[r.mapping[t.prefix[0]]] = prefixNode t.table[r.mapping[key[0]]] = keyNode t.prefix = nil t.next = nil keyNode.add(key[1:], val, priority, r) } else { // Insert new node after the common section of the prefix. next := &trieNode{ prefix: t.prefix[n:], next: t.next, } t.prefix = t.prefix[:n] t.next = next next.add(key[n:], val, priority, r) } } else if t.table != nil { // Insert into existing table. m := r.mapping[key[0]] if t.table[m] == nil { t.table[m] = new(trieNode) } t.table[m].add(key[1:], val, priority, r) } else { t.prefix = key t.next = new(trieNode) t.next.add(nil, val, priority, r) } } func (r *genericReplacer) lookup(s []byte, ignoreRoot bool) (val []byte, keylen int, found bool) { // Iterate down the trie to the end, and grab the value and keylen with // the highest priority. bestPriority := 0 node := &r.root n := 0 for node != nil { if node.priority > bestPriority && !(ignoreRoot && node == &r.root) { bestPriority = node.priority val = node.value keylen = n found = true } if len(s) == 0 { break } if node.table != nil { index := r.mapping[s[0]] if int(index) == r.tableSize { break } node = node.table[index] s = s[1:] n++ } else if len(node.prefix) > 0 && bytes.HasPrefix(s, node.prefix) { n += len(node.prefix) s = s[len(node.prefix):] node = node.next } else { break } } return } // genericReplacer is the fully generic algorithm. // It's used as a fallback when nothing faster can be used. type genericReplacer struct { root trieNode // tableSize is the size of a trie node's lookup table. It is the number // of unique key bytes. tableSize int // mapping maps from key bytes to a dense index for trieNode.table. mapping [256]byte } func makeGenericReplacer(oldnew []string) *genericReplacer { r := new(genericReplacer) // Find each byte used, then assign them each an index. for i := 0; i < len(oldnew); i += 2 { key := oldnew[i] for j := 0; j < len(key); j++ { r.mapping[key[j]] = 1 } } for _, b := range r.mapping { r.tableSize += int(b) } var index byte for i, b := range r.mapping { if b == 0 { r.mapping[i] = byte(r.tableSize) } else { r.mapping[i] = index index++ } } // Ensure root node uses a lookup table (for performance). r.root.table = make([]*trieNode, r.tableSize) for i := 0; i < len(oldnew); i += 2 { r.root.add([]byte(oldnew[i]), []byte(oldnew[i+1]), len(oldnew)-i, r) } return r } func (r *genericReplacer) Replace(s []byte) []byte { var last int var prevMatchEmpty bool dst := s[:0] grown := false for i := 0; i <= len(s); { // Fast path: s[i] is not a prefix of any pattern. if i != len(s) && r.root.priority == 0 { index := int(r.mapping[s[i]]) if index == r.tableSize || r.root.table[index] == nil { i++ continue } } // Ignore the empty match iff the previous loop found the empty match. val, keylen, match := r.lookup(s[i:], prevMatchEmpty) prevMatchEmpty = match && keylen == 0 if match { dst = append(dst, s[last:i]...) if diff := len(val) - keylen; grown || diff < 0 { dst = append(dst, val...) i += keylen } else if diff <= cap(s)-len(s) { // The replacement is larger than the original, but can still fit in the original buffer. copy(s[i+len(val):cap(dst)], s[i+keylen:]) dst = append(dst, val...) s = s[:len(s)+diff] i += len(val) } else { // The output will grow larger than the original buffer. Allocate a new one. grown = true newDst := make([]byte, len(dst), cap(dst)+diff) copy(newDst, dst) dst = newDst dst = append(dst, val...) i += keylen } last = i continue } i++ } if last != len(s) { dst = append(dst, s[last:]...) } return dst } // byteReplacer is the implementation that's used when all the "old" // and "new" values are single ASCII bytes. // The array contains replacement bytes indexed by old byte. type byteReplacer [256]byte func (r *byteReplacer) Replace(s []byte) []byte { for i, b := range s { s[i] = r[b] } return s } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/README.md���������������������������������������������������0000644�0610621�0607500�00000006703�13172163412�022214� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# go4 [![travis badge](https://travis-ci.org/camlistore/go4.svg?branch=master)](https://travis-ci.org/camlistore/go4 "Travis CI") [go4.org](http://go4.org) is a collection of packages for Go programmers. They started out living in [Camlistore](https://camlistore.org)'s repo and elsewhere but they have nothing to do with Camlistore, so we're moving them here. ## Details * **single repo**. go4 is a single repo. That means things can be changed and rearranged globally atomically with ease and confidence. * **no backwards compatibility**. go4 makes no backwards compatibility promises. If you want to use go4, vendor it. And next time you update your vendor tree, update to the latest API if things in go4 changed. The plan is to eventually provide tools to make this easier. * **forward progress** because we have no backwards compatibility, it's always okay to change things to make things better. That also means the bar for contributions is lower. We don't have to get the API 100% correct in the first commit. * **code review** contributions must be code-reviewed. We're trying out Gerrithub, to see if we can find a mix of Github Pull Requests and Gerrit that works well for many people. We'll see. * **CLA compliant** contributors must agree to the Google CLA (the same as Go itself). This ensures we can move things into Go as necessary in the future. It also makes lawyers at various companies happy. The CLA is **not** a copyright *assignment*; you retain the copyright on your work. The CLA just says that your work is open source and you have permission to open source it. See https://golang.org/doc/contribute.html#tmp_6 * **docs, tests, portability** all code should be documented in the normal Go style, have tests, and be portable to different operating systems and architectures. We'll try to get builders in place to help run the tests on different OS/arches. For now we have Travis at least. ## Contributing To add code to go4, send a pull request or push a change to Gerrithub. We assume you already have your $GOPATH set and the go4 code cloned at $GOPATH/src/go4.org. For example: * `git clone https://review.gerrithub.io/camlistore/go4 $GOPATH/src/go4.org` ### To push a code review to Gerrithub directly: * Sign in to [http://gerrithub.io](http://gerrithub.io "Gerrithub") with your Github account. * Install the git hook that adds the magic "Change-Id" line to your commit messages: `curl -o $GOPATH/src/go4.org/.git/hooks/commit-msg https://camlistore.googlesource.com/camlistore/+/master/misc/commit-msg.githook` * make changes * commit (the unit of code review is a single commit identified by the Change-ID, **NOT** a series of commits on a branch) * `git push ssh://$YOUR_GITHUB_USERNAME@review.gerrithub.io:29418/camlistore/go4 HEAD:refs/for/master` ### Using Github Pull Requests * send a pull request with a single commit * create a Gerrithub code review at https://review.gerrithub.io/plugins/github-plugin/static/pullrequests.html, selecting the pull request you just created. ### Problems contributing? * Please file an issue or contact the [Camlistore mailing list](https://groups.google.com/forum/#!forum/camlistore) for any problems with the above. See [https://review.gerrithub.io/Documentation/user-upload.html](https://review.gerrithub.io/Documentation/user-upload.html) for more generic documentation. (TODO: more docs on Gerrit, integrate git-codereview, etc.) �������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/LICENSE�����������������������������������������������������0000644�0610621�0607500�00000026136�13172163412�021744� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/AUTHORS�����������������������������������������������������0000644�0610621�0607500�00000000472�13172163412�022002� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This is the official list of go4 authors for copyright purposes. # This is distinct from the CONTRIBUTORS file, which is the list of # people who have contributed, even if they don't own the copyright on # their work. Mathieu Lonjaret <mathieu.lonjaret@gmail.com> Daniel Theophanes <kardianos@gmail.com> Google ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/go4/.travis.yml�������������������������������������������������0000644�0610621�0607500�00000000405�13172163412�023037� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������go_import_path: go4.org language: go go: - 1.5 - tip before_install: - go get -u google.golang.org/cloud/storage - cd $HOME/gopath/src/google.golang.org/cloud - git reset --hard 2375e186ca77be721a7c9c7b13a659738a8511d2 - cd $HOME/gopath/src/go4.org �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/�������������������������������������������0000755�0610621�0607500�00000000000�13172163411�024401� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/serialize.go�������������������������������0000644�0610621�0607500�00000007672�13172163411�026733� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cookiejar import ( "encoding/json" "io" "log" "os" "path/filepath" "sort" "time" "gopkg.in/retry.v1" filelock "github.com/juju/go4/lock" "gopkg.in/errgo.v1" ) // Save saves the cookies to the persistent cookie file. // Before the file is written, it reads any cookies that // have been stored from it and merges them into j. func (j *Jar) Save() error { if j.filename == "" { return nil } return j.save(time.Now()) } // save is like Save but takes the current time as a parameter. func (j *Jar) save(now time.Time) error { locked, err := lockFile(lockFileName(j.filename)) if err != nil { return errgo.Mask(err) } defer locked.Close() f, err := os.OpenFile(j.filename, os.O_RDWR|os.O_CREATE, 0600) if err != nil { return errgo.Mask(err) } defer f.Close() // TODO optimization: if the file hasn't changed since we // loaded it, don't bother with the merge step. j.mu.Lock() defer j.mu.Unlock() if err := j.mergeFrom(f); err != nil { // The cookie file is probably corrupt. log.Printf("cannot read cookie file to merge it; ignoring it: %v", err) } j.deleteExpired(now) if err := f.Truncate(0); err != nil { return errgo.Notef(err, "cannot truncate file") } if _, err := f.Seek(0, 0); err != nil { return errgo.Mask(err) } return j.writeTo(f) } // load loads the cookies from j.filename. If the file does not exist, // no error will be returned and no cookies will be loaded. func (j *Jar) load() error { if _, err := os.Stat(filepath.Dir(j.filename)); os.IsNotExist(err) { // The directory that we'll store the cookie jar // in doesn't exist, so don't bother trying // to acquire the lock. return nil } locked, err := lockFile(lockFileName(j.filename)) if err != nil { return errgo.Mask(err) } defer locked.Close() f, err := os.Open(j.filename) if err != nil { if os.IsNotExist(err) { return nil } return err } defer f.Close() if err := j.mergeFrom(f); err != nil { return errgo.Mask(err) } return nil } // mergeFrom reads all the cookies from r and stores them in the Jar. func (j *Jar) mergeFrom(r io.Reader) error { decoder := json.NewDecoder(r) // Cope with old cookiejar format by just discarding // cookies, but still return an error if it's invalid JSON. var data json.RawMessage if err := decoder.Decode(&data); err != nil { if err == io.EOF { // Empty file. return nil } return err } var entries []entry if err := json.Unmarshal(data, &entries); err != nil { log.Printf("warning: discarding cookies in invalid format (error: %v)", err) return nil } j.merge(entries) return nil } // writeTo writes all the cookies in the jar to w // as a JSON array. func (j *Jar) writeTo(w io.Writer) error { encoder := json.NewEncoder(w) entries := j.allPersistentEntries() if err := encoder.Encode(entries); err != nil { return err } return nil } // allPersistentEntries returns all the entries in the jar, sorted by primarly by canonical host // name and secondarily by path length. func (j *Jar) allPersistentEntries() []entry { var entries []entry for _, submap := range j.entries { for _, e := range submap { if e.Persistent { entries = append(entries, e) } } } sort.Sort(byCanonicalHost{entries}) return entries } // lockFileName returns the name of the lock file associated with // the given path. func lockFileName(path string) string { return path + ".lock" } var attempt = retry.LimitTime(3*time.Second, retry.Exponential{ Initial: 100 * time.Microsecond, Factor: 1.5, MaxDelay: 100 * time.Millisecond, }) func lockFile(path string) (io.Closer, error) { for a := retry.Start(attempt, nil); a.Next(); { locker, err := filelock.Lock(path) if err == nil { return locker, nil } if !a.More() { return nil, errgo.Notef(err, "file locked for too long; giving up") } } panic("unreachable") } ����������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/punycode_test.go���������������������������0000644�0610621�0607500�00000011206�13172163411�027615� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cookiejar import ( "testing" ) var punycodeTestCases = [...]struct { s, encoded string }{ {"", ""}, {"-", "--"}, {"-a", "-a-"}, {"-a-", "-a--"}, {"a", "a-"}, {"a-", "a--"}, {"a-b", "a-b-"}, {"books", "books-"}, {"bücher", "bcher-kva"}, {"Hello世界", "Hello-ck1hg65u"}, {"ü", "tda"}, {"üý", "tdac"}, // The test cases below come from RFC 3492 section 7.1 with Errata 3026. { // (A) Arabic (Egyptian). "\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" + "\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", "egbpdaj6bu4bxfgehfvwxn", }, { // (B) Chinese (simplified). "\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", "ihqwcrb4cv8a8dqg056pqjye", }, { // (C) Chinese (traditional). "\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587", "ihqwctvzc91f659drss3x8bo0yb", }, { // (D) Czech. "\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074" + "\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D" + "\u0065\u0073\u006B\u0079", "Proprostnemluvesky-uyb24dma41a", }, { // (E) Hebrew. "\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8" + "\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2" + "\u05D1\u05E8\u05D9\u05EA", "4dbcagdahymbxekheh6e0a7fei0b", }, { // (F) Hindi (Devanagari). "\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D" + "\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939" + "\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947" + "\u0939\u0948\u0902", "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd", }, { // (G) Japanese (kanji and hiragana). "\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092" + "\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B", "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa", }, { // (H) Korean (Hangul syllables). "\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774" + "\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74" + "\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C", "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j" + "psd879ccm6fea98c", }, { // (I) Russian (Cyrillic). "\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E" + "\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440" + "\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A" + "\u0438", "b1abfaaepdrnnbgefbadotcwatmq2g4l", }, { // (J) Spanish. "\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070" + "\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070" + "\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061" + "\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070" + "\u0061\u00F1\u006F\u006C", "PorqunopuedensimplementehablarenEspaol-fmd56a", }, { // (K) Vietnamese. "\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B" + "\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068" + "\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067" + "\u0056\u0069\u1EC7\u0074", "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g", }, { // (L) 3<nen>B<gumi><kinpachi><sensei>. "\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F", "3B-ww4c5e180e575a65lsy2b", }, { // (M) <amuro><namie>-with-SUPER-MONKEYS. "\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074" + "\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D" + "\u004F\u004E\u004B\u0045\u0059\u0053", "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n", }, { // (N) Hello-Another-Way-<sorezore><no><basho>. "\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F" + "\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D" + "\u305D\u308C\u305E\u308C\u306E\u5834\u6240", "Hello-Another-Way--fc4qua05auwb3674vfr0b", }, { // (O) <hitotsu><yane><no><shita>2. "\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032", "2-u9tlzr9756bt3uc0v", }, { // (P) Maji<de>Koi<suru>5<byou><mae> "\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" + "\u308B\u0035\u79D2\u524D", "MajiKoi5-783gue6qz075azm5e", }, { // (Q) <pafii>de<runba> "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", "de-jg4avhby1noc0d", }, { // (R) <sono><supiido><de> "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", "d9juau41awczczp", }, { // (S) -> $1.00 <- "\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020" + "\u003C\u002D", "-> $1.00 <--", }, } func TestPunycode(t *testing.T) { for _, tc := range punycodeTestCases { if got, err := encode("", tc.s); err != nil { t.Errorf(`encode("", %q): %v`, tc.s, err) } else if got != tc.encoded { t.Errorf(`encode("", %q): got %q, want %q`, tc.s, got, tc.encoded) } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/punycode.go��������������������������������0000644�0610621�0607500�00000006732�13172163411�026566� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cookiejar // This file implements the Punycode algorithm from RFC 3492. import ( "fmt" "strings" "unicode/utf8" ) // These parameter values are specified in section 5. // // All computation is done with int32s, so that overflow behavior is identical // regardless of whether int is 32-bit or 64-bit. const ( base int32 = 36 damp int32 = 700 initialBias int32 = 72 initialN int32 = 128 skew int32 = 38 tmax int32 = 26 tmin int32 = 1 ) // encode encodes a string as specified in section 6.3 and prepends prefix to // the result. // // The "while h < length(input)" line in the specification becomes "for // remaining != 0" in the Go code, because len(s) in Go is in bytes, not runes. func encode(prefix, s string) (string, error) { output := make([]byte, len(prefix), len(prefix)+1+2*len(s)) copy(output, prefix) delta, n, bias := int32(0), initialN, initialBias b, remaining := int32(0), int32(0) for _, r := range s { if r < 0x80 { b++ output = append(output, byte(r)) } else { remaining++ } } h := b if b > 0 { output = append(output, '-') } for remaining != 0 { m := int32(0x7fffffff) for _, r := range s { if m > r && r >= n { m = r } } delta += (m - n) * (h + 1) if delta < 0 { return "", fmt.Errorf("cookiejar: invalid label %q", s) } n = m for _, r := range s { if r < n { delta++ if delta < 0 { return "", fmt.Errorf("cookiejar: invalid label %q", s) } continue } if r > n { continue } q := delta for k := base; ; k += base { t := k - bias if t < tmin { t = tmin } else if t > tmax { t = tmax } if q < t { break } output = append(output, encodeDigit(t+(q-t)%(base-t))) q = (q - t) / (base - t) } output = append(output, encodeDigit(q)) bias = adapt(delta, h+1, h == b) delta = 0 h++ remaining-- } delta++ n++ } return string(output), nil } func encodeDigit(digit int32) byte { switch { case 0 <= digit && digit < 26: return byte(digit + 'a') case 26 <= digit && digit < 36: return byte(digit + ('0' - 26)) } panic("cookiejar: internal error in punycode encoding") } // adapt is the bias adaptation function specified in section 6.1. func adapt(delta, numPoints int32, firstTime bool) int32 { if firstTime { delta /= damp } else { delta /= 2 } delta += delta / numPoints k := int32(0) for delta > ((base-tmin)*tmax)/2 { delta /= base - tmin k += base } return k + (base-tmin+1)*delta/(delta+skew) } // Strictly speaking, the remaining code below deals with IDNA (RFC 5890 and // friends) and not Punycode (RFC 3492) per se. // acePrefix is the ASCII Compatible Encoding prefix. const acePrefix = "xn--" // toASCII converts a domain or domain label to its ASCII form. For example, // toASCII("bücher.example.com") is "xn--bcher-kva.example.com", and // toASCII("golang") is "golang". func toASCII(s string) (string, error) { if ascii(s) { return s, nil } labels := strings.Split(s, ".") for i, label := range labels { if !ascii(label) { a, err := encode(acePrefix, label) if err != nil { return "", err } labels[i] = a } } return strings.Join(labels, "."), nil } func ascii(s string) bool { for i := 0; i < len(s); i++ { if s[i] >= utf8.RuneSelf { return false } } return true } ��������������������������������������lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/jar_test.go��������������������������������0000644�0610621�0607500�00000151554�13172163411�026556� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cookiejar import ( "fmt" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "reflect" "regexp" "sort" "strings" "sync" "sync/atomic" "testing" "time" ) // tNow is the synthetic current time used as now during testing. var tNow = time.Date(2013, 1, 1, 12, 0, 0, 0, time.UTC) // testPSL implements PublicSuffixList with just two rules: "co.uk" // and the default rule "*". type testPSL struct{} func (testPSL) String() string { return "testPSL" } func (testPSL) PublicSuffix(d string) string { if d == "co.uk" || strings.HasSuffix(d, ".co.uk") { return "co.uk" } return d[strings.LastIndex(d, ".")+1:] } // emptyPSL implements PublicSuffixList with just the default // rule "*". type emptyPSL struct{} func (emptyPSL) String() string { return "emptyPSL" } func (emptyPSL) PublicSuffix(d string) string { return d[strings.LastIndex(d, ".")+1:] } // newTestJar creates an empty Jar with testPSL as the public suffix list. func newTestJar(path string) *Jar { jar, err := New(&Options{ PublicSuffixList: testPSL{}, Filename: path, NoPersist: path == "", }) if err != nil { panic(err) } return jar } var hasDotSuffixTests = [...]struct { s, suffix string }{ {"", ""}, {"", "."}, {"", "x"}, {".", ""}, {".", "."}, {".", ".."}, {".", "x"}, {".", "x."}, {".", ".x"}, {".", ".x."}, {"x", ""}, {"x", "."}, {"x", ".."}, {"x", "x"}, {"x", "x."}, {"x", ".x"}, {"x", ".x."}, {".x", ""}, {".x", "."}, {".x", ".."}, {".x", "x"}, {".x", "x."}, {".x", ".x"}, {".x", ".x."}, {"x.", ""}, {"x.", "."}, {"x.", ".."}, {"x.", "x"}, {"x.", "x."}, {"x.", ".x"}, {"x.", ".x."}, {"com", ""}, {"com", "m"}, {"com", "om"}, {"com", "com"}, {"com", ".com"}, {"com", "x.com"}, {"com", "xcom"}, {"com", "xorg"}, {"com", "org"}, {"com", "rg"}, {"foo.com", ""}, {"foo.com", "m"}, {"foo.com", "om"}, {"foo.com", "com"}, {"foo.com", ".com"}, {"foo.com", "o.com"}, {"foo.com", "oo.com"}, {"foo.com", "foo.com"}, {"foo.com", ".foo.com"}, {"foo.com", "x.foo.com"}, {"foo.com", "xfoo.com"}, {"foo.com", "xfoo.org"}, {"foo.com", "foo.org"}, {"foo.com", "oo.org"}, {"foo.com", "o.org"}, {"foo.com", ".org"}, {"foo.com", "org"}, {"foo.com", "rg"}, } func TestHasDotSuffix(t *testing.T) { for _, tc := range hasDotSuffixTests { got := hasDotSuffix(tc.s, tc.suffix) want := strings.HasSuffix(tc.s, "."+tc.suffix) if got != want { t.Errorf("s=%q, suffix=%q: got %v, want %v", tc.s, tc.suffix, got, want) } } } var canonicalHostTests = map[string]string{ "www.example.com": "www.example.com", "WWW.EXAMPLE.COM": "www.example.com", "wWw.eXAmple.CoM": "www.example.com", "www.example.com:80": "www.example.com", "192.168.0.10": "192.168.0.10", "192.168.0.5:8080": "192.168.0.5", "2001:4860:0:2001::68": "2001:4860:0:2001::68", "[2001:4860:0:::68]:8080": "2001:4860:0:::68", "www.bücher.de": "www.xn--bcher-kva.de", "www.example.com.": "www.example.com", "[bad.unmatched.bracket:": "error", } func TestCanonicalHost(t *testing.T) { for h, want := range canonicalHostTests { got, err := canonicalHost(h) if want == "error" { if err == nil { t.Errorf("%q: got nil error, want non-nil", h) } continue } if err != nil { t.Errorf("%q: %v", h, err) continue } if got != want { t.Errorf("%q: got %q, want %q", h, got, want) continue } } } var hasPortTests = map[string]bool{ "www.example.com": false, "www.example.com:80": true, "127.0.0.1": false, "127.0.0.1:8080": true, "2001:4860:0:2001::68": false, "[2001::0:::68]:80": true, } func TestHasPort(t *testing.T) { for host, want := range hasPortTests { if got := hasPort(host); got != want { t.Errorf("%q: got %t, want %t", host, got, want) } } } var jarKeyTests = map[string]string{ "foo.www.example.com": "example.com", "www.example.com": "example.com", "example.com": "example.com", "com": "com", "foo.www.bbc.co.uk": "bbc.co.uk", "www.bbc.co.uk": "bbc.co.uk", "bbc.co.uk": "bbc.co.uk", "co.uk": "co.uk", "uk": "uk", "192.168.0.5": "192.168.0.5", } func TestJarKey(t *testing.T) { for host, want := range jarKeyTests { if got := jarKey(host, testPSL{}); got != want { t.Errorf("%q: got %q, want %q", host, got, want) } } } var jarKeyNilPSLTests = map[string]string{ "foo.www.example.com": "example.com", "www.example.com": "example.com", "example.com": "example.com", "com": "com", "foo.www.bbc.co.uk": "co.uk", "www.bbc.co.uk": "co.uk", "bbc.co.uk": "co.uk", "co.uk": "co.uk", "uk": "uk", "192.168.0.5": "192.168.0.5", } func TestJarKeyNilPSL(t *testing.T) { for host, want := range jarKeyNilPSLTests { if got := jarKey(host, nil); got != want { t.Errorf("%q: got %q, want %q", host, got, want) } } } var isIPTests = map[string]bool{ "127.0.0.1": true, "1.2.3.4": true, "2001:4860:0:2001::68": true, "example.com": false, "1.1.1.300": false, "www.foo.bar.net": false, "123.foo.bar.net": false, } func TestIsIP(t *testing.T) { for host, want := range isIPTests { if got := isIP(host); got != want { t.Errorf("%q: got %t, want %t", host, got, want) } } } var defaultPathTests = map[string]string{ "/": "/", "/abc": "/", "/abc/": "/abc", "/abc/xyz": "/abc", "/abc/xyz/": "/abc/xyz", "/a/b/c.html": "/a/b", "": "/", "strange": "/", "//": "/", "/a//b": "/a/", "/a/./b": "/a/.", "/a/../b": "/a/..", } func TestDefaultPath(t *testing.T) { for path, want := range defaultPathTests { if got := defaultPath(path); got != want { t.Errorf("%q: got %q, want %q", path, got, want) } } } var domainAndTypeTests = [...]struct { host string // host Set-Cookie header was received from domain string // domain attribute in Set-Cookie header wantDomain string // expected domain of cookie wantHostOnly bool // expected host-cookie flag wantErr error // expected error }{ {"www.example.com", "", "www.example.com", true, nil}, {"127.0.0.1", "", "127.0.0.1", true, nil}, {"2001:4860:0:2001::68", "", "2001:4860:0:2001::68", true, nil}, {"www.example.com", "example.com", "example.com", false, nil}, {"www.example.com", ".example.com", "example.com", false, nil}, {"www.example.com", "www.example.com", "www.example.com", false, nil}, {"www.example.com", ".www.example.com", "www.example.com", false, nil}, {"foo.sso.example.com", "sso.example.com", "sso.example.com", false, nil}, {"bar.co.uk", "bar.co.uk", "bar.co.uk", false, nil}, {"foo.bar.co.uk", ".bar.co.uk", "bar.co.uk", false, nil}, {"127.0.0.1", "127.0.0.1", "", false, errNoHostname}, {"2001:4860:0:2001::68", "2001:4860:0:2001::68", "2001:4860:0:2001::68", false, errNoHostname}, {"www.example.com", ".", "", false, errMalformedDomain}, {"www.example.com", "..", "", false, errMalformedDomain}, {"www.example.com", "other.com", "", false, errIllegalDomain}, {"www.example.com", "com", "", false, errIllegalDomain}, {"www.example.com", ".com", "", false, errIllegalDomain}, {"foo.bar.co.uk", ".co.uk", "", false, errIllegalDomain}, {"127.www.0.0.1", "127.0.0.1", "", false, errIllegalDomain}, {"com", "", "com", true, nil}, {"com", "com", "com", true, nil}, {"com", ".com", "com", true, nil}, {"co.uk", "", "co.uk", true, nil}, {"co.uk", "co.uk", "co.uk", true, nil}, {"co.uk", ".co.uk", "co.uk", true, nil}, } func TestDomainAndType(t *testing.T) { jar := newTestJar("") for _, tc := range domainAndTypeTests { domain, hostOnly, err := jar.domainAndType(tc.host, tc.domain) if err != tc.wantErr { t.Errorf("%q/%q: got %q error, want %q", tc.host, tc.domain, err, tc.wantErr) continue } if err != nil { continue } if domain != tc.wantDomain || hostOnly != tc.wantHostOnly { t.Errorf("%q/%q: got %q/%t want %q/%t", tc.host, tc.domain, domain, hostOnly, tc.wantDomain, tc.wantHostOnly) } } } // basicsTests contains fundamental tests. Each jarTest has to be performed on // a fresh, empty Jar. var basicsTests = [...]jarTest{ { "Retrieval of a plain host cookie.", "http://www.host.test/", []string{"A=a"}, "A=a", []query{ {"http://www.host.test", "A=a"}, {"http://www.host.test/", "A=a"}, {"http://www.host.test/some/path", "A=a"}, {"https://www.host.test", "A=a"}, {"https://www.host.test/", "A=a"}, {"https://www.host.test/some/path", "A=a"}, {"ftp://www.host.test", ""}, {"ftp://www.host.test/", ""}, {"ftp://www.host.test/some/path", ""}, {"http://www.other.org", ""}, {"http://sibling.host.test", ""}, {"http://deep.www.host.test", ""}, }, }, { "Secure cookies are not returned to http.", "http://www.host.test/", []string{"A=a; secure"}, "A=a", []query{ {"http://www.host.test", ""}, {"http://www.host.test/", ""}, {"http://www.host.test/some/path", ""}, {"https://www.host.test", "A=a"}, {"https://www.host.test/", "A=a"}, {"https://www.host.test/some/path", "A=a"}, }, }, { "Explicit path.", "http://www.host.test/", []string{"A=a; path=/some/path"}, "A=a", []query{ {"http://www.host.test", ""}, {"http://www.host.test/", ""}, {"http://www.host.test/some", ""}, {"http://www.host.test/some/", ""}, {"http://www.host.test/some/path", "A=a"}, {"http://www.host.test/some/paths", ""}, {"http://www.host.test/some/path/foo", "A=a"}, {"http://www.host.test/some/path/foo/", "A=a"}, }, }, { "Implicit path #1: path is a directory.", "http://www.host.test/some/path/", []string{"A=a"}, "A=a", []query{ {"http://www.host.test", ""}, {"http://www.host.test/", ""}, {"http://www.host.test/some", ""}, {"http://www.host.test/some/", ""}, {"http://www.host.test/some/path", "A=a"}, {"http://www.host.test/some/paths", ""}, {"http://www.host.test/some/path/foo", "A=a"}, {"http://www.host.test/some/path/foo/", "A=a"}, }, }, { "Implicit path #2: path is not a directory.", "http://www.host.test/some/path/index.html", []string{"A=a"}, "A=a", []query{ {"http://www.host.test", ""}, {"http://www.host.test/", ""}, {"http://www.host.test/some", ""}, {"http://www.host.test/some/", ""}, {"http://www.host.test/some/path", "A=a"}, {"http://www.host.test/some/paths", ""}, {"http://www.host.test/some/path/foo", "A=a"}, {"http://www.host.test/some/path/foo/", "A=a"}, }, }, { "Implicit path #3: no path in URL at all.", "http://www.host.test", []string{"A=a"}, "A=a", []query{ {"http://www.host.test", "A=a"}, {"http://www.host.test/", "A=a"}, {"http://www.host.test/some/path", "A=a"}, }, }, { "Cookies are sorted by path length.", "http://www.host.test/", []string{ "A=a; path=/foo/bar", "B=b; path=/foo/bar/baz/qux", "C=c; path=/foo/bar/baz", "D=d; path=/foo"}, "A=a B=b C=c D=d", []query{ {"http://www.host.test/foo/bar/baz/qux", "B=b C=c A=a D=d"}, {"http://www.host.test/foo/bar/baz/", "C=c A=a D=d"}, {"http://www.host.test/foo/bar", "A=a D=d"}, }, }, // TODO fix this test. It has never actually tested sorting on // creation time because all the cookies are actually created at // the same moment in time. // { // "Creation time determines sorting on same length paths.", // "http://www.host.test/", // []string{ // "A=a; path=/foo/bar", // "X=x; path=/foo/bar", // "Y=y; path=/foo/bar/baz/qux", // "B=b; path=/foo/bar/baz/qux", // "C=c; path=/foo/bar/baz", // "W=w; path=/foo/bar/baz", // "Z=z; path=/foo", // "D=d; path=/foo"}, // "A=a B=b C=c D=d W=w X=x Y=y Z=z", // []query{ // {"http://www.host.test/foo/bar/baz/qux", "Y=y B=b C=c W=w A=a X=x Z=z D=d"}, // {"http://www.host.test/foo/bar/baz/", "C=c W=w A=a X=x Z=z D=d"}, // {"http://www.host.test/foo/bar", "A=a X=x Z=z D=d"}, // }, // }, { "Sorting of same-name cookies.", "http://www.host.test/", []string{ "A=1; path=/", "A=2; path=/path", "A=3; path=/quux", "A=4; path=/path/foo", "A=5; domain=.host.test; path=/path", "A=6; domain=.host.test; path=/quux", "A=7; domain=.host.test; path=/path/foo", }, "A=1 A=2 A=3 A=4 A=5 A=6 A=7", []query{ {"http://www.host.test/path", "A=2 A=5 A=1"}, {"http://www.host.test/path/foo", "A=4 A=7 A=2 A=5 A=1"}, }, }, { "Disallow domain cookie on public suffix.", "http://www.bbc.co.uk", []string{ "a=1", "b=2; domain=co.uk", }, "a=1", []query{{"http://www.bbc.co.uk", "a=1"}}, }, { "Host cookie on IP.", "http://192.168.0.10", []string{"a=1"}, "a=1", []query{{"http://192.168.0.10", "a=1"}}, }, { "Port is ignored #1.", "http://www.host.test/", []string{"a=1"}, "a=1", []query{ {"http://www.host.test", "a=1"}, {"http://www.host.test:8080/", "a=1"}, }, }, { "Port is ignored #2.", "http://www.host.test:8080/", []string{"a=1"}, "a=1", []query{ {"http://www.host.test", "a=1"}, {"http://www.host.test:8080/", "a=1"}, {"http://www.host.test:1234/", "a=1"}, }, }, } func TestBasics(t *testing.T) { for _, test := range basicsTests { jar := newTestJar("") test.run(t, jar) } } // updateAndDeleteTests contains jarTests which must be performed on the same // Jar. var updateAndDeleteTests = [...]jarTest{ { "Set initial cookies.", "http://www.host.test", []string{ "a=1", "b=2; secure", "c=3; httponly", "d=4; secure; httponly"}, "a=1 b=2 c=3 d=4", []query{ {"http://www.host.test", "a=1 c=3"}, {"https://www.host.test", "a=1 b=2 c=3 d=4"}, }, }, { "Update value via http.", "http://www.host.test", []string{ "a=w", "b=x; secure", "c=y; httponly", "d=z; secure; httponly"}, "a=w b=x c=y d=z", []query{ {"http://www.host.test", "a=w c=y"}, {"https://www.host.test", "a=w b=x c=y d=z"}, }, }, { "Clear Secure flag from a http.", "http://www.host.test/", []string{ "b=xx", "d=zz; httponly"}, "a=w b=xx c=y d=zz", []query{{"http://www.host.test", "a=w b=xx c=y d=zz"}}, }, { "Delete all.", "http://www.host.test/", []string{ "a=1; max-Age=-1", // delete via MaxAge "b=2; " + expiresIn(-10), // delete via Expires "c=2; max-age=-1; " + expiresIn(-10), // delete via both "d=4; max-age=-1; " + expiresIn(10)}, // MaxAge takes precedence "", []query{{"http://www.host.test", ""}}, }, { "Refill #1.", "http://www.host.test", []string{ "A=1", "A=2; path=/foo", "A=3; domain=.host.test", "A=4; path=/foo; domain=.host.test"}, "A=1 A=2 A=3 A=4", []query{{"http://www.host.test/foo", "A=2 A=4 A=1 A=3"}}, }, { "Refill #2.", "http://www.google.com", []string{ "A=6", "A=7; path=/foo", "A=8; domain=.google.com", "A=9; path=/foo; domain=.google.com"}, "A=1 A=2 A=3 A=4 A=6 A=7 A=8 A=9", []query{ {"http://www.host.test/foo", "A=2 A=4 A=1 A=3"}, {"http://www.google.com/foo", "A=7 A=9 A=6 A=8"}, }, }, { "Delete A7.", "http://www.google.com", []string{"A=; path=/foo; max-age=-1"}, "A=1 A=2 A=3 A=4 A=6 A=8 A=9", []query{ {"http://www.host.test/foo", "A=2 A=4 A=1 A=3"}, {"http://www.google.com/foo", "A=9 A=6 A=8"}, }, }, { "Delete A4.", "http://www.host.test", []string{"A=; path=/foo; domain=host.test; max-age=-1"}, "A=1 A=2 A=3 A=6 A=8 A=9", []query{ {"http://www.host.test/foo", "A=2 A=1 A=3"}, {"http://www.google.com/foo", "A=9 A=6 A=8"}, }, }, { "Delete A6.", "http://www.google.com", []string{"A=; max-age=-1"}, "A=1 A=2 A=3 A=8 A=9", []query{ {"http://www.host.test/foo", "A=2 A=1 A=3"}, {"http://www.google.com/foo", "A=9 A=8"}, }, }, { "Delete A3.", "http://www.host.test", []string{"A=; domain=host.test; max-age=-1"}, "A=1 A=2 A=8 A=9", []query{ {"http://www.host.test/foo", "A=2 A=1"}, {"http://www.google.com/foo", "A=9 A=8"}, }, }, { "No cross-domain delete.", "http://www.host.test", []string{ "A=; domain=google.com; max-age=-1", "A=; path=/foo; domain=google.com; max-age=-1"}, "A=1 A=2 A=8 A=9", []query{ {"http://www.host.test/foo", "A=2 A=1"}, {"http://www.google.com/foo", "A=9 A=8"}, }, }, { "Delete A8 and A9.", "http://www.google.com", []string{ "A=; domain=google.com; max-age=-1", "A=; path=/foo; domain=google.com; max-age=-1"}, "A=1 A=2", []query{ {"http://www.host.test/foo", "A=2 A=1"}, {"http://www.google.com/foo", ""}, }, }, } func TestUpdateAndDelete(t *testing.T) { jar := newTestJar("") for _, test := range updateAndDeleteTests { test.run(t, jar) } } func TestExpiration(t *testing.T) { jar := newTestJar("") jarTest{ "Expiration.", "http://www.host.test", []string{ "a=1", "b=2; max-age=3", "c=3; " + expiresIn(3), "d=4; max-age=5", "e=5; " + expiresIn(5), "f=6; max-age=100", }, "a=1 b=2 c=3 d=4 e=5 f=6", // executed at t0 + 1001 ms []query{ {"http://www.host.test", "a=1 b=2 c=3 d=4 e=5 f=6"}, // t0 + 2002 ms {"http://www.host.test", "a=1 d=4 e=5 f=6"}, // t0 + 3003 ms {"http://www.host.test", "a=1 d=4 e=5 f=6"}, // t0 + 4004 ms {"http://www.host.test", "a=1 f=6"}, // t0 + 5005 ms {"http://www.host.test", "a=1 f=6"}, // t0 + 6006 ms }, }.run(t, jar) } // // Tests derived from Chromium's cookie_store_unittest.h. // // See http://src.chromium.org/viewvc/chrome/trunk/src/net/cookies/cookie_store_unittest.h?revision=159685&content-type=text/plain // Some of the original tests are in a bad condition (e.g. // DomainWithTrailingDotTest) or are not RFC 6265 conforming (e.g. // TestNonDottedAndTLD #1 and #6) and have not been ported. // chromiumBasicsTests contains fundamental tests. Each jarTest has to be // performed on a fresh, empty Jar. var chromiumBasicsTests = [...]jarTest{ { "DomainWithTrailingDotTest.", "http://www.google.com/", []string{ "a=1; domain=.www.google.com.", "b=2; domain=.www.google.com..", }, "", []query{ {"http://www.google.com", ""}, }, }, { "ValidSubdomainTest #1.", "http://a.b.c.d.com", []string{ "a=1; domain=.a.b.c.d.com", "b=2; domain=.b.c.d.com", "c=3; domain=.c.d.com", "d=4; domain=.d.com", }, "a=1 b=2 c=3 d=4", []query{ {"http://a.b.c.d.com", "a=1 b=2 c=3 d=4"}, {"http://b.c.d.com", "b=2 c=3 d=4"}, {"http://c.d.com", "c=3 d=4"}, {"http://d.com", "d=4"}, }, }, { "ValidSubdomainTest #2.", "http://a.b.c.d.com", []string{ "a=1; domain=.a.b.c.d.com", "b=2; domain=.b.c.d.com", "c=3; domain=.c.d.com", "d=4; domain=.d.com", "X=bcd; domain=.b.c.d.com", "X=cd; domain=.c.d.com"}, "X=bcd X=cd a=1 b=2 c=3 d=4", []query{ {"http://b.c.d.com", "X=bcd X=cd b=2 c=3 d=4"}, {"http://c.d.com", "X=cd c=3 d=4"}, }, }, { "InvalidDomainTest #1.", "http://foo.bar.com", []string{ "a=1; domain=.yo.foo.bar.com", "b=2; domain=.foo.com", "c=3; domain=.bar.foo.com", "d=4; domain=.foo.bar.com.net", "e=5; domain=ar.com", "f=6; domain=.", "g=7; domain=/", "h=8; domain=http://foo.bar.com", "i=9; domain=..foo.bar.com", "j=10; domain=..bar.com", "k=11; domain=.foo.bar.com?blah", "l=12; domain=.foo.bar.com/blah", "m=12; domain=.foo.bar.com:80", "n=14; domain=.foo.bar.com:", "o=15; domain=.foo.bar.com#sup", }, "", // Jar is empty. []query{{"http://foo.bar.com", ""}}, }, { "InvalidDomainTest #2.", "http://foo.com.com", []string{"a=1; domain=.foo.com.com.com"}, "", []query{{"http://foo.bar.com", ""}}, }, { "DomainWithoutLeadingDotTest #1.", "http://manage.hosted.filefront.com", []string{"a=1; domain=filefront.com"}, "a=1", []query{{"http://www.filefront.com", "a=1"}}, }, { "DomainWithoutLeadingDotTest #2.", "http://www.google.com", []string{"a=1; domain=www.google.com"}, "a=1", []query{ {"http://www.google.com", "a=1"}, {"http://sub.www.google.com", "a=1"}, {"http://something-else.com", ""}, }, }, { "CaseInsensitiveDomainTest.", "http://www.google.com", []string{ "a=1; domain=.GOOGLE.COM", "b=2; domain=.www.gOOgLE.coM"}, "a=1 b=2", []query{{"http://www.google.com", "a=1 b=2"}}, }, { "TestIpAddress #1.", "http://1.2.3.4/foo", []string{"a=1; path=/"}, "a=1", []query{{"http://1.2.3.4/foo", "a=1"}}, }, { "TestIpAddress #2.", "http://1.2.3.4/foo", []string{ "a=1; domain=.1.2.3.4", "b=2; domain=.3.4"}, "", []query{{"http://1.2.3.4/foo", ""}}, }, { "TestIpAddress #3.", "http://1.2.3.4/foo", []string{"a=1; domain=1.2.3.4"}, "", []query{{"http://1.2.3.4/foo", ""}}, }, { "TestNonDottedAndTLD #2.", "http://com./index.html", []string{"a=1"}, "a=1", []query{ {"http://com./index.html", "a=1"}, {"http://no-cookies.com./index.html", ""}, }, }, { "TestNonDottedAndTLD #3.", "http://a.b", []string{ "a=1; domain=.b", "b=2; domain=b"}, "", []query{{"http://bar.foo", ""}}, }, { "TestNonDottedAndTLD #4.", "http://google.com", []string{ "a=1; domain=.com", "b=2; domain=com"}, "", []query{{"http://google.com", ""}}, }, { "TestNonDottedAndTLD #5.", "http://google.co.uk", []string{ "a=1; domain=.co.uk", "b=2; domain=.uk"}, "", []query{ {"http://google.co.uk", ""}, {"http://else.co.com", ""}, {"http://else.uk", ""}, }, }, { "TestHostEndsWithDot.", "http://www.google.com", []string{ "a=1", "b=2; domain=.www.google.com."}, "a=1", []query{{"http://www.google.com", "a=1"}}, }, { "PathTest", "http://www.google.izzle", []string{"a=1; path=/wee"}, "a=1", []query{ {"http://www.google.izzle/wee", "a=1"}, {"http://www.google.izzle/wee/", "a=1"}, {"http://www.google.izzle/wee/war", "a=1"}, {"http://www.google.izzle/wee/war/more/more", "a=1"}, {"http://www.google.izzle/weehee", ""}, {"http://www.google.izzle/", ""}, }, }, } func TestChromiumBasics(t *testing.T) { for _, test := range chromiumBasicsTests { jar := newTestJar("") test.run(t, jar) } } // chromiumDomainTests contains jarTests which must be executed all on the // same Jar. var chromiumDomainTests = [...]jarTest{ { "Fill #1.", "http://www.google.izzle", []string{"A=B"}, "A=B", []query{{"http://www.google.izzle", "A=B"}}, }, { "Fill #2.", "http://www.google.izzle", []string{"C=D; domain=.google.izzle"}, "A=B C=D", []query{{"http://www.google.izzle", "A=B C=D"}}, }, { "Verify A is a host cookie and not accessible from subdomain.", "http://unused.nil", []string{}, "A=B C=D", []query{{"http://foo.www.google.izzle", "C=D"}}, }, { "Verify domain cookies are found on proper domain.", "http://www.google.izzle", []string{"E=F; domain=.www.google.izzle"}, "A=B C=D E=F", []query{{"http://www.google.izzle", "A=B C=D E=F"}}, }, { "Leading dots in domain attributes are optional.", "http://www.google.izzle", []string{"G=H; domain=www.google.izzle"}, "A=B C=D E=F G=H", []query{{"http://www.google.izzle", "A=B C=D E=F G=H"}}, }, { "Verify domain enforcement works #1.", "http://www.google.izzle", []string{"K=L; domain=.bar.www.google.izzle"}, "A=B C=D E=F G=H", []query{{"http://bar.www.google.izzle", "C=D E=F G=H"}}, }, { "Verify domain enforcement works #2.", "http://unused.nil", []string{}, "A=B C=D E=F G=H", []query{{"http://www.google.izzle", "A=B C=D E=F G=H"}}, }, } func TestChromiumDomain(t *testing.T) { jar := newTestJar("") for _, test := range chromiumDomainTests { test.run(t, jar) } } // chromiumDeletionTests must be performed all on the same Jar. var chromiumDeletionTests = [...]jarTest{ { "Create session cookie a1.", "http://www.google.com", []string{"a=1"}, "a=1", []query{{"http://www.google.com", "a=1"}}, }, { "Delete sc a1 via MaxAge.", "http://www.google.com", []string{"a=1; max-age=-1"}, "", []query{{"http://www.google.com", ""}}, }, { "Create session cookie b2.", "http://www.google.com", []string{"b=2"}, "b=2", []query{{"http://www.google.com", "b=2"}}, }, { "Delete sc b2 via Expires.", "http://www.google.com", []string{"b=2; " + expiresIn(-10)}, "", []query{{"http://www.google.com", ""}}, }, { "Create persistent cookie c3.", "http://www.google.com", []string{"c=3; max-age=3600"}, "c=3", []query{{"http://www.google.com", "c=3"}}, }, { "Delete pc c3 via MaxAge.", "http://www.google.com", []string{"c=3; max-age=-1"}, "", []query{{"http://www.google.com", ""}}, }, { "Create persistent cookie d4.", "http://www.google.com", []string{"d=4; max-age=3600"}, "d=4", []query{{"http://www.google.com", "d=4"}}, }, { "Delete pc d4 via Expires.", "http://www.google.com", []string{"d=4; " + expiresIn(-10)}, "", []query{{"http://www.google.com", ""}}, }, } func TestChromiumDeletion(t *testing.T) { jar := newTestJar("") for _, test := range chromiumDeletionTests { test.run(t, jar) } } // domainHandlingTests tests and documents the rules for domain handling. // Each test must be performed on an empty new Jar. var domainHandlingTests = [...]jarTest{ { "Host cookie", "http://www.host.test", []string{"a=1"}, "a=1", []query{ {"http://www.host.test", "a=1"}, {"http://host.test", ""}, {"http://bar.host.test", ""}, {"http://foo.www.host.test", ""}, {"http://other.test", ""}, {"http://test", ""}, }, }, { "Domain cookie #1", "http://www.host.test", []string{"a=1; domain=host.test"}, "a=1", []query{ {"http://www.host.test", "a=1"}, {"http://host.test", "a=1"}, {"http://bar.host.test", "a=1"}, {"http://foo.www.host.test", "a=1"}, {"http://other.test", ""}, {"http://test", ""}, }, }, { "Domain cookie #2", "http://www.host.test", []string{"a=1; domain=.host.test"}, "a=1", []query{ {"http://www.host.test", "a=1"}, {"http://host.test", "a=1"}, {"http://bar.host.test", "a=1"}, {"http://foo.www.host.test", "a=1"}, {"http://other.test", ""}, {"http://test", ""}, }, }, { "Host cookie on IDNA domain #1", "http://www.bücher.test", []string{"a=1"}, "a=1", []query{ {"http://www.bücher.test", "a=1"}, {"http://www.xn--bcher-kva.test", "a=1"}, {"http://bücher.test", ""}, {"http://xn--bcher-kva.test", ""}, {"http://bar.bücher.test", ""}, {"http://bar.xn--bcher-kva.test", ""}, {"http://foo.www.bücher.test", ""}, {"http://foo.www.xn--bcher-kva.test", ""}, {"http://other.test", ""}, {"http://test", ""}, }, }, { "Host cookie on IDNA domain #2", "http://www.xn--bcher-kva.test", []string{"a=1"}, "a=1", []query{ {"http://www.bücher.test", "a=1"}, {"http://www.xn--bcher-kva.test", "a=1"}, {"http://bücher.test", ""}, {"http://xn--bcher-kva.test", ""}, {"http://bar.bücher.test", ""}, {"http://bar.xn--bcher-kva.test", ""}, {"http://foo.www.bücher.test", ""}, {"http://foo.www.xn--bcher-kva.test", ""}, {"http://other.test", ""}, {"http://test", ""}, }, }, { "Domain cookie on IDNA domain #1", "http://www.bücher.test", []string{"a=1; domain=xn--bcher-kva.test"}, "a=1", []query{ {"http://www.bücher.test", "a=1"}, {"http://www.xn--bcher-kva.test", "a=1"}, {"http://bücher.test", "a=1"}, {"http://xn--bcher-kva.test", "a=1"}, {"http://bar.bücher.test", "a=1"}, {"http://bar.xn--bcher-kva.test", "a=1"}, {"http://foo.www.bücher.test", "a=1"}, {"http://foo.www.xn--bcher-kva.test", "a=1"}, {"http://other.test", ""}, {"http://test", ""}, }, }, { "Domain cookie on IDNA domain #2", "http://www.xn--bcher-kva.test", []string{"a=1; domain=xn--bcher-kva.test"}, "a=1", []query{ {"http://www.bücher.test", "a=1"}, {"http://www.xn--bcher-kva.test", "a=1"}, {"http://bücher.test", "a=1"}, {"http://xn--bcher-kva.test", "a=1"}, {"http://bar.bücher.test", "a=1"}, {"http://bar.xn--bcher-kva.test", "a=1"}, {"http://foo.www.bücher.test", "a=1"}, {"http://foo.www.xn--bcher-kva.test", "a=1"}, {"http://other.test", ""}, {"http://test", ""}, }, }, { "Host cookie on TLD.", "http://com", []string{"a=1"}, "a=1", []query{ {"http://com", "a=1"}, {"http://any.com", ""}, {"http://any.test", ""}, }, }, { "Domain cookie on TLD becomes a host cookie.", "http://com", []string{"a=1; domain=com"}, "a=1", []query{ {"http://com", "a=1"}, {"http://any.com", ""}, {"http://any.test", ""}, }, }, { "Host cookie on public suffix.", "http://co.uk", []string{"a=1"}, "a=1", []query{ {"http://co.uk", "a=1"}, {"http://uk", ""}, {"http://some.co.uk", ""}, {"http://foo.some.co.uk", ""}, {"http://any.uk", ""}, }, }, { "Domain cookie on public suffix is ignored.", "http://some.co.uk", []string{"a=1; domain=co.uk"}, "", []query{ {"http://co.uk", ""}, {"http://uk", ""}, {"http://some.co.uk", ""}, {"http://foo.some.co.uk", ""}, {"http://any.uk", ""}, }, }, } func TestDomainHandling(t *testing.T) { for _, test := range domainHandlingTests { jar := newTestJar("") test.run(t, jar) } } type mergeCookie struct { when time.Time url string cookie string } func (c mergeCookie) set(jar *Jar) { setCookies(jar, c.url, []string{c.cookie}, c.when) } var mergeTests = []struct { description string setCookies0 []mergeCookie setCookies1 []mergeCookie now time.Time content string queries []query // Queries to test the Jar.Cookies method }{{ description: "empty jar1", setCookies0: []mergeCookie{ {atTime(0), "http://www.host.test", "A=a; max-age=10"}, }, now: atTime(1), content: "A=a", }, { description: "empty jar0", setCookies1: []mergeCookie{ {atTime(0), "http://www.host.test", "A=a; max-age=10"}, }, now: atTime(1), content: "A=a", }, { description: "simple override (1)", setCookies0: []mergeCookie{ {atTime(0), "http://www.host.test", "A=a; max-age=10"}, }, setCookies1: []mergeCookie{ {atTime(1), "http://www.host.test", "A=b; max-age=10"}, }, now: atTime(2), content: "A=b", }, { description: "simple override (2)", setCookies0: []mergeCookie{ {atTime(1), "http://www.host.test", "A=a; max-age=10"}, }, setCookies1: []mergeCookie{ {atTime(0), "http://www.host.test", "A=b; max-age=10"}, }, now: atTime(2), content: "A=a", }, { description: "expired cookie overrides unexpired cookie", setCookies0: []mergeCookie{ {atTime(1), "http://www.host.test", "A=a; max-age=-1"}, }, setCookies1: []mergeCookie{ {atTime(0), "http://www.host.test", "A=b; max-age=10"}, }, now: atTime(2), content: "", }, { description: "set overrides expires", setCookies0: []mergeCookie{ {atTime(1), "http://www.host.test", "A=a; max-age=10"}, }, setCookies1: []mergeCookie{ {atTime(0), "http://www.host.test", "A=b; max-age=-1"}, }, now: atTime(2), content: "A=a", }, { description: "expiry times preserved", setCookies0: []mergeCookie{ {atTime(1), "http://www.host.test", "A=a; " + expiresIn(5)}, }, setCookies1: []mergeCookie{ {atTime(0), "http://www.host.test", "B=b; " + expiresIn(4)}, }, now: atTime(2), content: "A=a B=b", queries: []query{ {"http://www.host.test", "B=b A=a"}, {"http://www.host.test", "A=a"}, {"http://www.host.test", ""}, }, }, { description: "prefer receiver when creation times are identical", setCookies0: []mergeCookie{ {atTime(0), "http://www.host.test", "A=a; max-age=10"}, }, setCookies1: []mergeCookie{ {atTime(0), "http://www.host.test", "A=b; max-age=10"}, }, now: atTime(2), content: "A=a", }, { description: "max-age is persistent even when negative", setCookies0: []mergeCookie{ {atTime(0), "http://www.host.test", "A=a; max-age=10"}, }, setCookies1: []mergeCookie{ {atTime(1), "http://www.host.test", "A=b; max-age=-1"}, }, now: atTime(2), content: "", }, { description: "expires is persistent even when in the past", setCookies0: []mergeCookie{ {atTime(0), "http://www.host.test", "A=a; " + expiresIn(2)}, }, setCookies1: []mergeCookie{ {atTime(1), "http://www.host.test", "A=b; " + expiresIn(-1)}, }, now: atTime(2), content: "", }, { description: "many hosts", setCookies0: []mergeCookie{ {atTime(1), "http://www.host.test", "A=a0; max-age=10"}, {atTime(2), "http://www.host.test/foo/", "A=foo0; max-age=10"}, {atTime(1), "http://www.elsewhere", "X=x; max-age=10"}, }, setCookies1: []mergeCookie{ {atTime(1), "http://www.host.test", "A=a1; max-age=10"}, {atTime(3), "http://www.host.test", "B=b; max-age=10"}, {atTime(1), "http://www.host.test/foo/", "A=foo1; max-age=10"}, {atTime(0), "http://www.host.test/foo/", "C=arble; max-age=10"}, {atTime(1), "http://nowhere.com", "A=n; max-age=10"}, }, now: atTime(2), content: "A=a0 A=foo0 A=n B=b C=arble X=x", queries: []query{ {"http://www.host.test/", "A=a0 B=b"}, {"http://www.host.test/foo/", "C=arble A=foo0 A=a0 B=b"}, {"http://nowhere.com", "A=n"}, {"http://www.elsewhere", "X=x"}, }, }} func TestSaveMerge(t *testing.T) { dir, err := ioutil.TempDir("", "cookiejar-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) for i, test := range mergeTests { path := filepath.Join(dir, fmt.Sprintf("jar%d", i)) jar0 := newTestJar(path) for _, sc := range test.setCookies0 { sc.set(jar0) } jar1 := newTestJar(path) for _, sc := range test.setCookies1 { sc.set(jar1) } err := jar1.save(test.now) if err != nil { t.Fatalf("Test %q; cannot save first jar: %v", test.description, err) } err = jar0.save(test.now) if err != nil { t.Fatalf("Test %q; cannot save: %v", test.description, err) } got := allCookies(jar0, test.now) // Make sure jar content matches our expectations. if got != test.content { t.Logf("entries: %#v", jar0.entries) t.Errorf("Test %q Content\ngot %q\nwant %q", test.description, got, test.content) } testQueries(t, test.queries, test.description, jar0, test.now) } } func TestMergeConcurrent(t *testing.T) { // This test is designed to fail when run with the race // detector. The actual final content of the jars is non-deterministic // so we don't test that. const N = 10 f, err := ioutil.TempFile("", "cookiejar-test") if err != nil { t.Fatal(err) } defer os.Remove(f.Name()) defer f.Close() jar0 := newTestJar(f.Name()) jar1 := newTestJar(f.Name()) var wg sync.WaitGroup url := mustParseURL("http://foo.com") merger := func(j *Jar) { defer wg.Done() for i := 0; i < N; i++ { j.Save() } } getter := func(j *Jar) { defer wg.Done() for i := 0; i < N; i++ { j.Cookies(url) } } setter := func(j *Jar, what string) { defer wg.Done() for i := 0; i < N; i++ { setCookies(j, url.String(), []string{fmt.Sprintf("A=a%s%d; max-age=10", what, i)}, time.Now()) } } wg.Add(1) go merger(jar1) wg.Add(1) go merger(jar0) wg.Add(1) go getter(jar0) wg.Add(1) go getter(jar1) wg.Add(1) go setter(jar0, "first") wg.Add(1) go setter(jar1, "second") wg.Wait() } func TestDeleteExpired(t *testing.T) { expirySeconds := int(expiryRemovalDuration / time.Second) jar := newTestJar("") now := tNow setCookies(jar, "http://foo.com", []string{ "a=a; " + expiresIn(1), "b=b; " + expiresIn(expirySeconds+3), }, tNow) setCookies(jar, "http://bar.com", []string{ "c=c; " + expiresIn(1), }, tNow) // Make sure all the cookies are there to start with. got := allCookies(jar, now) want := "a=a b=b c=c" // Make sure jar content matches our expectations. if got != want { t.Errorf("Unexpected content\ngot %q\nwant %q", got, want) } now = now.Add(expiryRemovalDuration - time.Millisecond) // Ensure that they've timed out but their entries // are still around before the cutoff period. jar.deleteExpired(now) got = allCookiesIncludingExpired(jar, now) want = "a= b=b c=" if got != want { t.Errorf("Unexpected content\ngot %q\nwant %q", got, want) } // Try just after the expiry duration. The entries should really have // been removed now. now = now.Add(2 * time.Millisecond) jar.deleteExpired(now) got = allCookiesIncludingExpired(jar, now) want = "b=b" if got != want { t.Errorf("Unexpected content\ngot %q\nwant %q", got, want) } } var serializeTestCookies = []*http.Cookie{{ Name: "foo", Value: "bar", Path: "/p", Domain: "0.4.4.4", Expires: time.Now(), RawExpires: time.Now().Format(time.RFC3339Nano), MaxAge: 99, Secure: true, HttpOnly: true, Raw: "raw string", Unparsed: []string{"x", "y", "z"}, }} var serializeTestURL, _ = url.Parse("http://0.1.2.3/x") func TestLoadSave(t *testing.T) { d, err := ioutil.TempDir("", "") if err != nil { t.Fatalf("cannot make temp dir: %v", err) } defer os.RemoveAll(d) file := filepath.Join(d, "cookies") j := newTestJar(file) j.SetCookies(serializeTestURL, serializeTestCookies) if err := j.Save(); err != nil { t.Fatalf("cannot save: %v", err) } if _, err := os.Stat(file); err != nil { t.Fatalf("file was not created") } j1 := newTestJar(file) if !reflect.DeepEqual(j1.entries, j.entries) { t.Fatalf("entries differ after serialization") } } func TestLoadSaveWithNoPersist(t *testing.T) { // Create a cookie file so that we can verify // that it's not read when NoPersist is set. d, err := ioutil.TempDir("", "") if err != nil { t.Fatalf("cannot make temp dir: %v", err) } defer os.RemoveAll(d) file := filepath.Join(d, "cookies") j := newTestJar(file) j.SetCookies(serializeTestURL, serializeTestCookies) if err := j.Save(); err != nil { t.Fatalf("cannot save: %v", err) } jar, err := New(&Options{ PublicSuffixList: testPSL{}, Filename: file, NoPersist: true, }) if err != nil { t.Fatal(err) } if got := allCookiesIncludingExpired(jar, tNow); got != "" { t.Errorf("Cookies unexpectedly loaded: %v", got) } if err := os.Remove(file); err != nil { t.Fatal(err) } if err := jar.Save(); err != nil { t.Fatal(err) } if _, err := os.Stat(file); err == nil { t.Fatalf("file was unexpectedly saved") } } func TestLoadNonExistentParent(t *testing.T) { d, err := ioutil.TempDir("", "") if err != nil { t.Fatalf("cannot make temp dir: %v", err) } defer os.RemoveAll(d) file := filepath.Join(d, "foo", "cookies") _, err = New(&Options{ PublicSuffixList: testPSL{}, Filename: file, }) if err != nil { t.Fatalf("cannot make cookie jar: %v", err) } } func TestLoadNonExistentParentOfParent(t *testing.T) { d, err := ioutil.TempDir("", "") if err != nil { t.Fatalf("cannot make temp dir: %v", err) } defer os.RemoveAll(d) file := filepath.Join(d, "foo", "foo", "cookies") _, err = New(&Options{ PublicSuffixList: testPSL{}, Filename: file, }) if err != nil { t.Fatalf("cannot make cookie jar: %v", err) } } func TestLoadOldFormat(t *testing.T) { // Check that loading the old format (a JSON object) // doesn't result in an error. f, err := ioutil.TempFile("", "cookiejar-test") if err != nil { t.Fatal(err) } defer os.Remove(f.Name()) f.Write([]byte("{}")) f.Close() jar, err := New(&Options{ Filename: f.Name(), }) if err != nil { t.Errorf("got error: %v", err) } if jar == nil { t.Errorf("nil jar") } } func TestLoadInvalidJSON(t *testing.T) { f, err := ioutil.TempFile("", "cookiejar-test") if err != nil { t.Fatal(err) } defer os.Remove(f.Name()) f.Write([]byte("[")) f.Close() jar, err := New(&Options{ Filename: f.Name(), }) if err == nil { t.Fatalf("expected error, got none") } want := "cannot load cookies: unexpected EOF" if ok, _ := regexp.MatchString(want, err.Error()); !ok { t.Fatalf("unexpected error message; want %q got %q", want, err.Error()) } if jar != nil { t.Fatalf("got nil jar") } } func TestLoadDifferentPublicSuffixList(t *testing.T) { f, err := ioutil.TempFile("", "cookiejar-test") if err != nil { t.Fatal(err) } f.Close() defer os.Remove(f.Name()) now := tNow // With no public suffix list, some domains that should be // separate can set cookies for each other. jar, err := newAtTime(&Options{ Filename: f.Name(), PublicSuffixList: emptyPSL{}, }, now) if err != nil { t.Fatal(err) } setCookies(jar, "http://foo.co.uk", []string{ "a=a; max-age=10; domain=.co.uk", }, now) setCookies(jar, "http://bar.co.uk", []string{ "b=b; max-age=10; domain=.co.uk", }, now) // With the default public suffix, the cookies are // correctly segmented into their proper domains. queries := []query{ {"http://foo.co.uk/", "a=a b=b"}, {"http://bar.co.uk/", "a=a b=b"}, } testQueries(t, queries, "no public suffix list", jar, now) if err := jar.save(now); err != nil { t.Fatalf("cannot save jar: %v", err) } jar, err = newAtTime(&Options{ Filename: f.Name(), PublicSuffixList: testPSL{}, }, now) if err != nil { t.Fatal(err) } queries = []query{ {"http://foo.co.uk/", "a=a"}, {"http://bar.co.uk/", "b=b"}, } testQueries(t, queries, "with test public suffix list", jar, now) if err := jar.save(now); err != nil { t.Fatalf("cannot save jar: %v", err) } // When we reload with the original (empty) public suffix // we get all the original cookies back. jar, err = newAtTime(&Options{ Filename: f.Name(), PublicSuffixList: emptyPSL{}, }, now) if err != nil { t.Fatal(err) } queries = []query{ {"http://foo.co.uk/", "a=a b=b"}, {"http://bar.co.uk/", "a=a b=b"}, } testQueries(t, queries, "no public suffix list #2", jar, now) if err := jar.save(now); err != nil { t.Fatalf("cannot save jar: %v", err) } } func TestLockFile(t *testing.T) { d, err := ioutil.TempDir("", "cookiejar_test") if err != nil { t.Fatal(err) } defer os.RemoveAll(d) filename := filepath.Join(d, "lockfile") concurrentCount := int64(0) var wg sync.WaitGroup locker := func() { defer wg.Done() closer, err := lockFile(filename) if err != nil { t.Errorf("cannot obtain lock: %v", err) return } x := atomic.AddInt64(&concurrentCount, 1) if x > 1 { t.Errorf("multiple locks held at one time") } defer closer.Close() time.Sleep(10 * time.Millisecond) atomic.AddInt64(&concurrentCount, -1) } wg.Add(4) for i := 0; i < 4; i++ { go locker() } wg.Wait() if concurrentCount != 0 { t.Errorf("expected no running goroutines left") } } // jarTest encapsulates the following actions on a jar: // 1. Perform SetCookies with fromURL and the cookies from setCookies. // (Done at time tNow + 0 ms.) // 2. Check that the entries in the jar matches content. // (Done at time tNow + 1001 ms.) // 3. For each query in tests: Check that Cookies with toURL yields the // cookies in want. // (Query n done at tNow + (n+2)*1001 ms.) type jarTest struct { description string // The description of what this test is supposed to test fromURL string // The full URL of the request from which Set-Cookie headers where received setCookies []string // All the cookies received from fromURL content string // The whole (non-expired) content of the jar queries []query // Queries to test the Jar.Cookies method } // query contains one test of the cookies returned from Jar.Cookies. type query struct { toURL string // the URL in the Cookies call want string // the expected list of cookies (order matters) } // run runs the jarTest. func (test jarTest) run(t *testing.T, jar *Jar) { now := tNow // Populate jar with cookies. setCookies(jar, test.fromURL, test.setCookies, now) now = now.Add(1001 * time.Millisecond) got := allCookies(jar, now) // Make sure jar content matches our expectations. if got != test.content { t.Errorf("Test %q Content\ngot %q\nwant %q", test.description, got, test.content) } testQueries(t, test.queries, test.description, jar, now) } // setCookies sets the given cookies in the given jar associated // with the given URL at the given time. func setCookies(jar *Jar, fromURL string, cookies []string, now time.Time) { setCookies := make([]*http.Cookie, len(cookies)) for i, cs := range cookies { cookies := (&http.Response{Header: http.Header{"Set-Cookie": {cs}}}).Cookies() if len(cookies) != 1 { panic(fmt.Sprintf("Wrong cookie line %q: %#v", cs, cookies)) } setCookies[i] = cookies[0] } jar.setCookies(mustParseURL(fromURL), setCookies, now) } // allCookies returns all unexpired cookies in the jar // in the form "name1=val1 name2=val2" // (entries sorted by string). func allCookies(jar *Jar, now time.Time) string { var cs []string for _, submap := range jar.entries { for _, cookie := range submap { if !cookie.Expires.After(now) { continue } cs = append(cs, cookie.Name+"="+cookie.Value) } } sort.Strings(cs) return strings.Join(cs, " ") } // allCookiesIncludingExpired returns all cookies in the jar // in the form "name1=val1 name2=val2" // (entries sorted by string), including cookies that // have expired (without their values) func allCookiesIncludingExpired(jar *Jar, now time.Time) string { var cs []string for _, submap := range jar.entries { for _, cookie := range submap { if !cookie.Expires.After(now) { cs = append(cs, cookie.Name+"=") } else { cs = append(cs, cookie.Name+"="+cookie.Value) } } } sort.Strings(cs) return strings.Join(cs, " ") } func testQueries(t *testing.T, queries []query, description string, jar *Jar, now time.Time) { // Test different calls to Cookies. for i, query := range queries { now = now.Add(1001 * time.Millisecond) if got := queryJar(jar, query.toURL, now); got != query.want { t.Errorf("Test %q #%d\ngot %q\nwant %q", description, i, got, query.want) } } } // queryJar returns the results of querying jar for // cookies associated with url at the given time, // in "name1=val1 name2=val2" form. func queryJar(jar *Jar, toURL string, now time.Time) string { var s []string for _, c := range jar.cookies(mustParseURL(toURL), now) { s = append(s, c.Name+"="+c.Value) } return strings.Join(s, " ") } // expiresIn creates an expires attribute delta seconds from tNow. func expiresIn(delta int) string { return "expires=" + atTime(delta).Format(time.RFC1123) } // atTime returns a time delta seconds from tNow. func atTime(delta int) time.Time { return tNow.Add(time.Duration(delta) * time.Second) } // mustParseURL parses s to an URL and panics on error. func mustParseURL(s string) *url.URL { u, err := url.Parse(s) if err != nil || u.Scheme == "" || u.Host == "" { panic(fmt.Sprintf("Unable to parse URL %s.", s)) } return u } type setCommand struct { url *url.URL cookies []*http.Cookie } var allCookiesTests = []struct { about string set []setCommand expectCookies []*http.Cookie }{{ about: "no cookies", }, { about: "a cookie", set: []setCommand{{ url: mustParseURL("https://www.google.com/"), cookies: []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Expires: tNow.Add(24 * time.Hour), }, }, }}, expectCookies: []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Domain: "www.google.com", Path: "/", Secure: false, HttpOnly: false, Expires: tNow.Add(24 * time.Hour), }, }, }, { about: "expired cookie", set: []setCommand{{ url: mustParseURL("https://www.google.com/"), cookies: []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Expires: tNow.Add(-24 * time.Hour), }, }, }}, }, { about: "cookie for subpath", set: []setCommand{{ url: mustParseURL("https://www.google.com/subpath/place"), cookies: []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Expires: tNow.Add(24 * time.Hour), }, }, }}, expectCookies: []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Domain: "www.google.com", Path: "/subpath", Secure: false, HttpOnly: false, Expires: tNow.Add(24 * time.Hour), }, }, }, { about: "multiple cookies", set: []setCommand{{ url: mustParseURL("https://www.google.com/"), cookies: []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Expires: tNow.Add(24 * time.Hour), }, }, }, { url: mustParseURL("https://www.google.com/subpath/"), cookies: []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Expires: tNow.Add(24 * time.Hour), }, }, }}, expectCookies: []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Domain: "www.google.com", Path: "/subpath", Secure: false, HttpOnly: false, Expires: tNow.Add(24 * time.Hour), }, &http.Cookie{ Name: "test-cookie", Value: "test-value", Domain: "www.google.com", Path: "/", Secure: false, HttpOnly: false, Expires: tNow.Add(24 * time.Hour), }, }, }} func TestAllCookies(t *testing.T) { dir, err := ioutil.TempDir("", "cookiejar-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) for i, test := range allCookiesTests { path := filepath.Join(dir, fmt.Sprintf("jar%d", i)) jar := newTestJar(path) for _, s := range test.set { jar.setCookies(s.url, s.cookies, tNow) } gotCookies := jar.allCookies(tNow) if len(gotCookies) != len(test.expectCookies) { t.Fatalf("Test %q: unexpected number of cookies returned, expected: %d, got: %d", test.about, len(test.expectCookies), len(gotCookies)) } for j, c := range test.expectCookies { if !cookiesEqual(c, gotCookies[j]) { t.Fatalf("Test %q: mismatch in cookies[%d], expected: %#v, got: %#v", test.about, j, *c, *gotCookies[j]) } } } } func TestRemoveCookies(t *testing.T) { jar := newTestJar("") jar.SetCookies( mustParseURL("https://www.google.com"), []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, &http.Cookie{ Name: "test-cookie2", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, }, ) cookies := jar.AllCookies() if len(cookies) != 2 { t.Fatalf("Expected 2 cookies got %d", len(cookies)) } jar.RemoveCookie(cookies[0]) cookies2 := jar.AllCookies() if len(cookies2) != 1 { t.Fatalf("Expected 1 cookie got %d", len(cookies)) } if !cookiesEqual(cookies[1], cookies2[0]) { t.Fatalf("Unexpected cookie removed") } } func TestRemoveAllHost(t *testing.T) { testRemoveAllHost(t, mustParseURL("https://www.apple.com"), "www.apple.com", true) } func TestRemoveAllHostRoot(t *testing.T) { testRemoveAllHost(t, mustParseURL("https://www.apple.com"), "apple.com", false) } func TestRemoveAllHostDifferent(t *testing.T) { testRemoveAllHost(t, mustParseURL("https://www.apple.com"), "foo.apple.com", false) } func TestRemoveAllHostWithPort(t *testing.T) { testRemoveAllHost(t, mustParseURL("https://www.apple.com"), "www.apple.com:80", true) } func TestRemoveAllHostIP(t *testing.T) { testRemoveAllHost(t, mustParseURL("https://10.1.1.1"), "10.1.1.1", true) } func testRemoveAllHost(t *testing.T, setURL *url.URL, removeHost string, shouldRemove bool) { jar := newTestJar("") google := mustParseURL("https://www.google.com") jar.SetCookies( google, []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, &http.Cookie{ Name: "test-cookie2", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, }, ) onlyGoogle := jar.AllCookies() if len(onlyGoogle) != 2 { t.Fatalf("Expected 2 cookies, got %d", len(onlyGoogle)) } jar.SetCookies( setURL, []*http.Cookie{ &http.Cookie{ Name: "test-cookie3", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, &http.Cookie{ Name: "test-cookie4", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, }, ) withSet := jar.AllCookies() if len(withSet) != 4 { t.Fatalf("Expected 4 cookies, got %d", len(withSet)) } jar.RemoveAllHost(removeHost) after := jar.AllCookies() if !shouldRemove { if len(after) != len(withSet) { t.Fatalf("Expected %d cookies, got %d", len(withSet), len(after)) } return } if len(after) != len(onlyGoogle) { t.Fatalf("Expected %d cookies, got %d", len(onlyGoogle), len(after)) } if !cookiesEqual(onlyGoogle[0], after[0]) { t.Fatalf("Expected %v, got %v", onlyGoogle[0], after[0]) } if !cookiesEqual(onlyGoogle[1], after[1]) { t.Fatalf("Expected %v, got %v", onlyGoogle[1], after[1]) } } func TestRemoveAll(t *testing.T) { jar := newTestJar("") jar.SetCookies( mustParseURL("https://www.google.com"), []*http.Cookie{ &http.Cookie{ Name: "test-cookie", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, &http.Cookie{ Name: "test-cookie2", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, }, ) jar.SetCookies( mustParseURL("https://foo.com"), []*http.Cookie{ &http.Cookie{ Name: "test-cookie3", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, &http.Cookie{ Name: "test-cookie4", Value: "test-value", Expires: time.Now().Add(24 * time.Hour), }, }, ) jar.RemoveAll() if after := len(jar.AllCookies()); after != 0 { t.Fatalf("%d cookies remaining after RemoveAll", after) } } func cookiesEqual(a, b *http.Cookie) bool { return a.Name == b.Name && a.Value == b.Value && a.Domain == b.Domain && a.Path == b.Path && a.Expires.Equal(b.Expires) && a.HttpOnly == b.HttpOnly && a.Secure == b.Secure } ����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/jar.go�������������������������������������0000644�0610621�0607500�00000046000�13172163411�025504� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar. // // This implementation is a fork of net/http/cookiejar which also // implements methods for dumping the cookies to persistent // storage and retrieving them. package cookiejar import ( "errors" "fmt" "net" "net/http" "net/url" "os" "path/filepath" "runtime" "sort" "strings" "sync" "time" "golang.org/x/net/publicsuffix" "gopkg.in/errgo.v1" ) // PublicSuffixList provides the public suffix of a domain. For example: // - the public suffix of "example.com" is "com", // - the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and // - the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us". // // Implementations of PublicSuffixList must be safe for concurrent use by // multiple goroutines. // // An implementation that always returns "" is valid and may be useful for // testing but it is not secure: it means that the HTTP server for foo.com can // set a cookie for bar.com. // // A public suffix list implementation is in the package // golang.org/x/net/publicsuffix. type PublicSuffixList interface { // PublicSuffix returns the public suffix of domain. // // TODO: specify which of the caller and callee is responsible for IP // addresses, for leading and trailing dots, for case sensitivity, and // for IDN/Punycode. PublicSuffix(domain string) string // String returns a description of the source of this public suffix // list. The description will typically contain something like a time // stamp or version number. String() string } // Options are the options for creating a new Jar. type Options struct { // PublicSuffixList is the public suffix list that determines whether // an HTTP server can set a cookie for a domain. // // If this is nil, the public suffix list implementation in golang.org/x/net/publicsuffix // is used. PublicSuffixList PublicSuffixList // Filename holds the file to use for storage of the cookies. // If it is empty, the value of DefaultCookieFile will be used. Filename string // NoPersist specifies whether no persistence should be used // (useful for tests). If this is true, the value of Filename will be // ignored. NoPersist bool } // Jar implements the http.CookieJar interface from the net/http package. type Jar struct { // filename holds the file that the cookies were loaded from. filename string psList PublicSuffixList // mu locks the remaining fields. mu sync.Mutex // entries is a set of entries, keyed by their eTLD+1 and subkeyed by // their name/domain/path. entries map[string]map[string]entry } var noOptions Options // New returns a new cookie jar. A nil *Options is equivalent to a zero // Options. // // New will return an error if the cookies could not be loaded // from the file for any reason than if the file does not exist. func New(o *Options) (*Jar, error) { return newAtTime(o, time.Now()) } // newAtTime is like New but takes the current time as a parameter. func newAtTime(o *Options, now time.Time) (*Jar, error) { jar := &Jar{ entries: make(map[string]map[string]entry), } if o == nil { o = &noOptions } if jar.psList = o.PublicSuffixList; jar.psList == nil { jar.psList = publicsuffix.List } if !o.NoPersist { if jar.filename = o.Filename; jar.filename == "" { jar.filename = DefaultCookieFile() } if err := jar.load(); err != nil { return nil, errgo.Notef(err, "cannot load cookies") } } jar.deleteExpired(now) return jar, nil } // homeDir returns the OS-specific home path as specified in the environment. func homeDir() string { if runtime.GOOS == "windows" { return filepath.Join(os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH")) } return os.Getenv("HOME") } // entry is the internal representation of a cookie. // // This struct type is not used outside of this package per se, but the exported // fields are those of RFC 6265. // Note that this structure is marshaled to JSON, so backward-compatibility // should be preserved. type entry struct { Name string Value string Domain string Path string Secure bool HttpOnly bool Persistent bool HostOnly bool Expires time.Time Creation time.Time LastAccess time.Time // Updated records when the cookie was updated. // This is different from creation time because a cookie // can be changed without updating the creation time. Updated time.Time // CanonicalHost stores the original canonical host name // that the cookie was associated with. We store this // so that even if the public suffix list changes (for example // when storing/loading cookies) we can still get the correct // jar keys. CanonicalHost string } // id returns the domain;path;name triple of e as an id. func (e *entry) id() string { return id(e.Domain, e.Path, e.Name) } // id returns the domain;path;name triple as an id. func id(domain, path, name string) string { return fmt.Sprintf("%s;%s;%s", domain, path, name) } // shouldSend determines whether e's cookie qualifies to be included in a // request to host/path. It is the caller's responsibility to check if the // cookie is expired. func (e *entry) shouldSend(https bool, host, path string) bool { return e.domainMatch(host) && e.pathMatch(path) && (https || !e.Secure) } // domainMatch implements "domain-match" of RFC 6265 section 5.1.3. func (e *entry) domainMatch(host string) bool { if e.Domain == host { return true } return !e.HostOnly && hasDotSuffix(host, e.Domain) } // pathMatch implements "path-match" according to RFC 6265 section 5.1.4. func (e *entry) pathMatch(requestPath string) bool { if requestPath == e.Path { return true } if strings.HasPrefix(requestPath, e.Path) { if e.Path[len(e.Path)-1] == '/' { return true // The "/any/" matches "/any/path" case. } else if requestPath[len(e.Path)] == '/' { return true // The "/any" matches "/any/path" case. } } return false } // hasDotSuffix reports whether s ends in "."+suffix. func hasDotSuffix(s, suffix string) bool { return len(s) > len(suffix) && s[len(s)-len(suffix)-1] == '.' && s[len(s)-len(suffix):] == suffix } type byCanonicalHost struct { byPathLength } func (s byCanonicalHost) Less(i, j int) bool { e0, e1 := &s.byPathLength[i], &s.byPathLength[j] if e0.CanonicalHost != e1.CanonicalHost { return e0.CanonicalHost < e1.CanonicalHost } return s.byPathLength.Less(i, j) } // byPathLength is a []entry sort.Interface that sorts according to RFC 6265 // section 5.4 point 2: by longest path and then by earliest creation time. type byPathLength []entry func (s byPathLength) Len() int { return len(s) } func (s byPathLength) Less(i, j int) bool { e0, e1 := &s[i], &s[j] if len(e0.Path) != len(e1.Path) { return len(e0.Path) > len(e1.Path) } if !e0.Creation.Equal(e1.Creation) { return e0.Creation.Before(e1.Creation) } // The following are not strictly necessary // but are useful for providing deterministic // behaviour in tests. if e0.Name != e1.Name { return e0.Name < e1.Name } return e0.Value < e1.Value } func (s byPathLength) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // Cookies implements the Cookies method of the http.CookieJar interface. // // It returns an empty slice if the URL's scheme is not HTTP or HTTPS. func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie) { return j.cookies(u, time.Now()) } // cookies is like Cookies but takes the current time as a parameter. func (j *Jar) cookies(u *url.URL, now time.Time) (cookies []*http.Cookie) { if u.Scheme != "http" && u.Scheme != "https" { return cookies } host, err := canonicalHost(u.Host) if err != nil { return cookies } key := jarKey(host, j.psList) j.mu.Lock() defer j.mu.Unlock() submap := j.entries[key] if submap == nil { return cookies } https := u.Scheme == "https" path := u.Path if path == "" { path = "/" } var selected []entry for id, e := range submap { if !e.Expires.After(now) { // Save some space by deleting the value when the cookie // expires. We can't delete the cookie itself because then // we wouldn't know that the cookie had expired when // we merge with another cookie jar. if e.Value != "" { e.Value = "" submap[id] = e } continue } if !e.shouldSend(https, host, path) { continue } e.LastAccess = now submap[id] = e selected = append(selected, e) } sort.Sort(byPathLength(selected)) for _, e := range selected { cookies = append(cookies, &http.Cookie{Name: e.Name, Value: e.Value}) } return cookies } // AllCookies returns all cookies in the jar. The returned cookies will // have Domain, Expires, HttpOnly, Name, Secure, Path, and Value filled // out. Expired cookies will not be returned. This function does not // modify the cookie jar. func (j *Jar) AllCookies() (cookies []*http.Cookie) { return j.allCookies(time.Now()) } // allCookies is like AllCookies but takes the current time as a parameter. func (j *Jar) allCookies(now time.Time) []*http.Cookie { var selected []entry j.mu.Lock() defer j.mu.Unlock() for _, submap := range j.entries { for _, e := range submap { if !e.Expires.After(now) { // Do not return expired cookies. continue } selected = append(selected, e) } } sort.Sort(byCanonicalHost{byPathLength(selected)}) cookies := make([]*http.Cookie, len(selected)) for i, e := range selected { // Note: The returned cookies do not contain sufficient // information to recreate the database. cookies[i] = &http.Cookie{ Name: e.Name, Value: e.Value, Path: e.Path, Domain: e.Domain, Expires: e.Expires, Secure: e.Secure, HttpOnly: e.HttpOnly, } } return cookies } // RemoveCookie removes the cookie matching the name, domain and path // specified by c. func (j *Jar) RemoveCookie(c *http.Cookie) { j.mu.Lock() defer j.mu.Unlock() id := id(c.Domain, c.Path, c.Name) key := jarKey(c.Domain, j.psList) if e, ok := j.entries[key][id]; ok { e.Value = "" e.Expires = time.Now().Add(-1 * time.Second) j.entries[key][id] = e } } // merge merges all the given entries into j. More recently changed // cookies take precedence over older ones. func (j *Jar) merge(entries []entry) { for _, e := range entries { if e.CanonicalHost == "" { continue } key := jarKey(e.CanonicalHost, j.psList) id := e.id() submap := j.entries[key] if submap == nil { j.entries[key] = map[string]entry{ id: e, } continue } oldEntry, ok := submap[id] if !ok || e.Updated.After(oldEntry.Updated) { submap[id] = e } } } var expiryRemovalDuration = 24 * time.Hour // deleteExpired deletes all entries that have expired for long enough // that we can actually expect there to be no external copies of it that // might resurrect the dead cookie. func (j *Jar) deleteExpired(now time.Time) { for tld, submap := range j.entries { for id, e := range submap { if !e.Expires.After(now) && !e.Updated.Add(expiryRemovalDuration).After(now) { delete(submap, id) } } if len(submap) == 0 { delete(j.entries, tld) } } } // RemoveAllHost removes any cookies from the jar that were set for the given host. func (j *Jar) RemoveAllHost(host string) { host, err := canonicalHost(host) if err != nil { return } key := jarKey(host, j.psList) j.mu.Lock() defer j.mu.Unlock() expired := time.Now().Add(-1 * time.Second) submap := j.entries[key] for id, e := range submap { if e.CanonicalHost == host { // Save some space by deleting the value when the cookie // expires. We can't delete the cookie itself because then // we wouldn't know that the cookie had expired when // we merge with another cookie jar. e.Value = "" e.Expires = expired submap[id] = e } } } // RemoveAll removes all the cookies from the jar. func (j *Jar) RemoveAll() { expired := time.Now().Add(-1 * time.Second) j.mu.Lock() defer j.mu.Unlock() for _, submap := range j.entries { for id, e := range submap { // Save some space by deleting the value when the cookie // expires. We can't delete the cookie itself because then // we wouldn't know that the cookie had expired when // we merge with another cookie jar. e.Value = "" e.Expires = expired submap[id] = e } } } // SetCookies implements the SetCookies method of the http.CookieJar interface. // // It does nothing if the URL's scheme is not HTTP or HTTPS. func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) { j.setCookies(u, cookies, time.Now()) } // setCookies is like SetCookies but takes the current time as parameter. func (j *Jar) setCookies(u *url.URL, cookies []*http.Cookie, now time.Time) { if len(cookies) == 0 { return } if u.Scheme != "http" && u.Scheme != "https" { // TODO is this really correct? It might be nice to send // cookies to websocket connections, for example. return } host, err := canonicalHost(u.Host) if err != nil { return } key := jarKey(host, j.psList) defPath := defaultPath(u.Path) j.mu.Lock() defer j.mu.Unlock() submap := j.entries[key] for _, cookie := range cookies { e, err := j.newEntry(cookie, now, defPath, host) if err != nil { continue } e.CanonicalHost = host id := e.id() if submap == nil { submap = make(map[string]entry) j.entries[key] = submap } if old, ok := submap[id]; ok { e.Creation = old.Creation } else { e.Creation = now } e.Updated = now e.LastAccess = now submap[id] = e } } // canonicalHost strips port from host if present and returns the canonicalized // host name. func canonicalHost(host string) (string, error) { var err error host = strings.ToLower(host) if hasPort(host) { host, _, err = net.SplitHostPort(host) if err != nil { return "", err } } if strings.HasSuffix(host, ".") { // Strip trailing dot from fully qualified domain names. host = host[:len(host)-1] } return toASCII(host) } // hasPort reports whether host contains a port number. host may be a host // name, an IPv4 or an IPv6 address. func hasPort(host string) bool { colons := strings.Count(host, ":") if colons == 0 { return false } if colons == 1 { return true } return host[0] == '[' && strings.Contains(host, "]:") } // jarKey returns the key to use for a jar. func jarKey(host string, psl PublicSuffixList) string { if isIP(host) { return host } var i int if psl == nil { i = strings.LastIndex(host, ".") if i == -1 { return host } } else { suffix := psl.PublicSuffix(host) if suffix == host { return host } i = len(host) - len(suffix) if i <= 0 || host[i-1] != '.' { // The provided public suffix list psl is broken. // Storing cookies under host is a safe stopgap. return host } } prevDot := strings.LastIndex(host[:i-1], ".") return host[prevDot+1:] } // isIP reports whether host is an IP address. func isIP(host string) bool { return net.ParseIP(host) != nil } // defaultPath returns the directory part of an URL's path according to // RFC 6265 section 5.1.4. func defaultPath(path string) string { if len(path) == 0 || path[0] != '/' { return "/" // Path is empty or malformed. } i := strings.LastIndex(path, "/") // Path starts with "/", so i != -1. if i == 0 { return "/" // Path has the form "/abc". } return path[:i] // Path is either of form "/abc/xyz" or "/abc/xyz/". } // newEntry creates an entry from a http.Cookie c. now is the current // time and is compared to c.Expires to determine deletion of c. defPath // and host are the default-path and the canonical host name of the URL // c was received from. // // The returned entry should be removed if its expiry time is in the // past. In this case, e may be incomplete, but it will be valid to call // e.id (which depends on e's Name, Domain and Path). // // A malformed c.Domain will result in an error. func (j *Jar) newEntry(c *http.Cookie, now time.Time, defPath, host string) (e entry, err error) { e.Name = c.Name if c.Path == "" || c.Path[0] != '/' { e.Path = defPath } else { e.Path = c.Path } e.Domain, e.HostOnly, err = j.domainAndType(host, c.Domain) if err != nil { return e, err } // MaxAge takes precedence over Expires. if c.MaxAge != 0 { e.Persistent = true e.Expires = now.Add(time.Duration(c.MaxAge) * time.Second) if c.MaxAge < 0 { return e, nil } } else if c.Expires.IsZero() { e.Expires = endOfTime } else { e.Persistent = true e.Expires = c.Expires if !c.Expires.After(now) { return e, nil } } e.Value = c.Value e.Secure = c.Secure e.HttpOnly = c.HttpOnly return e, nil } var ( errIllegalDomain = errors.New("cookiejar: illegal cookie domain attribute") errMalformedDomain = errors.New("cookiejar: malformed cookie domain attribute") errNoHostname = errors.New("cookiejar: no host name available (IP only)") ) // endOfTime is the time when session (non-persistent) cookies expire. // This instant is representable in most date/time formats (not just // Go's time.Time) and should be far enough in the future. var endOfTime = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC) // domainAndType determines the cookie's domain and hostOnly attribute. func (j *Jar) domainAndType(host, domain string) (string, bool, error) { if domain == "" { // No domain attribute in the SetCookie header indicates a // host cookie. return host, true, nil } if isIP(host) { // According to RFC 6265 domain-matching includes not being // an IP address. // TODO: This might be relaxed as in common browsers. return "", false, errNoHostname } // From here on: If the cookie is valid, it is a domain cookie (with // the one exception of a public suffix below). // See RFC 6265 section 5.2.3. if domain[0] == '.' { domain = domain[1:] } if len(domain) == 0 || domain[0] == '.' { // Received either "Domain=." or "Domain=..some.thing", // both are illegal. return "", false, errMalformedDomain } domain = strings.ToLower(domain) if domain[len(domain)-1] == '.' { // We received stuff like "Domain=www.example.com.". // Browsers do handle such stuff (actually differently) but // RFC 6265 seems to be clear here (e.g. section 4.1.2.3) in // requiring a reject. 4.1.2.3 is not normative, but // "Domain Matching" (5.1.3) and "Canonicalized Host Names" // (5.1.2) are. return "", false, errMalformedDomain } // See RFC 6265 section 5.3 #5. if j.psList != nil { if ps := j.psList.PublicSuffix(domain); ps != "" && !hasDotSuffix(domain, ps) { if host == domain { // This is the one exception in which a cookie // with a domain attribute is a host cookie. return host, true, nil } return "", false, errIllegalDomain } } // The domain must domain-match host: www.mycompany.com cannot // set cookies for .ourcompetitors.com. if host != domain && !hasDotSuffix(host, domain) { return "", false, errIllegalDomain } return domain, false, nil } // DefaultCookieFile returns the default cookie file to use // for persisting cookie data. // The following names will be used in decending order of preference: // - the value of the $GOCOOKIES environment variable. // - $HOME/.go-cookies func DefaultCookieFile() string { if f := os.Getenv("GOCOOKIES"); f != "" { return f } return filepath.Join(homeDir(), ".go-cookies") } lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/dependencies.tsv���������������������������0000644�0610621�0607500�00000000521�13172163411�027563� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������github.com/juju/go4 git 40d72ab9641a2a8c36a9c46a51e28367115c8e59 2016-02-22T16:32:58Z golang.org/x/net git b6d7b1396ec874c3b00f6c84cd4301a17c56c8ed 2016-02-17T01:13:48Z gopkg.in/errgo.v1 git 66cb46252b94c1f3d65646f54ee8043ab38d766c 2015-10-07T15:31:57Z gopkg.in/retry.v1 git c09f6b86ba4d5d2cf5bdf0665364aec9fd4815db 2016-10-25T18:14:30Z �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/README.md����������������������������������0000644�0610621�0607500�00000006375�13172163411�025673� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# cookiejar -- import "github.com/juju/persistent-cookiejar" Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar. This implementation is a fork of net/http/cookiejar which also implements methods for dumping the cookies to persistent storage and retrieving them. ## Usage #### func DefaultCookieFile ```go func DefaultCookieFile() string ``` DefaultCookieFile returns the default cookie file to use for persisting cookie data. The following names will be used in decending order of preference: - the value of the $GOCOOKIES environment variable. - $HOME/.go-cookies #### type Jar ```go type Jar struct { } ``` Jar implements the http.CookieJar interface from the net/http package. #### func New ```go func New(o *Options) (*Jar, error) ``` New returns a new cookie jar. A nil *Options is equivalent to a zero Options. New will return an error if the cookies could not be loaded from the file for any reason than if the file does not exist. #### func (*Jar) Cookies ```go func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie) ``` Cookies implements the Cookies method of the http.CookieJar interface. It returns an empty slice if the URL's scheme is not HTTP or HTTPS. #### func (*Jar) Save ```go func (j *Jar) Save() error ``` Save saves the cookies to the persistent cookie file. Before the file is written, it reads any cookies that have been stored from it and merges them into j. #### func (*Jar) SetCookies ```go func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) ``` SetCookies implements the SetCookies method of the http.CookieJar interface. It does nothing if the URL's scheme is not HTTP or HTTPS. #### type Options ```go type Options struct { // PublicSuffixList is the public suffix list that determines whether // an HTTP server can set a cookie for a domain. // // If this is nil, the public suffix list implementation in golang.org/x/net/publicsuffix // is used. PublicSuffixList PublicSuffixList // Filename holds the file to use for storage of the cookies. // If it is empty, the value of DefaultCookieFile will be used. Filename string } ``` Options are the options for creating a new Jar. #### type PublicSuffixList ```go type PublicSuffixList interface { // PublicSuffix returns the public suffix of domain. // // TODO: specify which of the caller and callee is responsible for IP // addresses, for leading and trailing dots, for case sensitivity, and // for IDN/Punycode. PublicSuffix(domain string) string // String returns a description of the source of this public suffix // list. The description will typically contain something like a time // stamp or version number. String() string } ``` PublicSuffixList provides the public suffix of a domain. For example: - the public suffix of "example.com" is "com", - the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and - the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us". Implementations of PublicSuffixList must be safe for concurrent use by multiple goroutines. An implementation that always returns "" is valid and may be useful for testing but it is not secure: it means that the HTTP server for foo.com can set a cookie for bar.com. A public suffix list implementation is in the package golang.org/x/net/publicsuffix. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/persistent-cookiejar/LICENSE������������������������������������0000644�0610621�0607500�00000002707�13172163411�025414� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2012 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ���������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/webbrowser/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163411�022416� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/webbrowser/webbrowser.go����������������������������������������0000644�0610621�0607500�00000003026�13172163411�025127� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package webbrowser import ( "errors" "net/url" "os" "os/exec" "runtime" "strings" ) // Open opens a web browser at the given URL. // If the OS is not recognized, an ErrNoBrowser is returned. func Open(url *url.URL) error { var args []string if runtime.GOOS == "windows" { // Windows is special because the start command is built into cmd.exe // and hence requires the argument to be quoted. args = []string{"cmd", "/c", "start", winCmdQuote.Replace(url.String())} } else if b := browser[runtime.GOOS]; b != "" { args = []string{b, url.String()} } else { return ErrNoBrowser } cmd := exec.Command(args[0], args[1:]...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Start() go cmd.Wait() return nil } // ErrNoBrowser is returned when a browser cannot be found for the current OS. var ErrNoBrowser = errors.New("cannot find a browser to open the web page") var browser = map[string]string{ "linux": "sensible-browser", "darwin": "open", "freebsd": "xdg-open", "netbsd": "xdg-open", "openbsd": "xdg-open", } // winCmdQuote can quote metacharacters special to the Windows // cmd.exe command interpreter. It does that by inserting // a '^' character before each metacharacter. Note that // most of these cannot actually be produced by URL.String, // but we include them for completeness. var winCmdQuote = strings.NewReplacer( "&", "^&", "%", "^%", "(", "^(", ")", "^)", "^", "^^", "<", "^<", ">", "^>", "|", "^|", ) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/webbrowser/README.md��������������������������������������������0000644�0610621�0607500�00000000073�13172163411�023675� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# webbrowser Go helpers for interacting with Web browsers. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/webbrowser/LICENSE����������������������������������������������0000644�0610621�0607500�00000016743�13172163411�023436� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. �����������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/����������������������������������������������������0000755�0610621�0607500�00000000000�13172163410�022624� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/unmarshal_test.go�����������������������������������0000644�0610621�0607500�00000024736�13172163410�026220� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest_test import ( "fmt" "io" "io/ioutil" "net/http" "net/url" "reflect" "strings" jc "github.com/juju/testing/checkers" "github.com/julienschmidt/httprouter" gc "gopkg.in/check.v1" "github.com/juju/httprequest" ) type unmarshalSuite struct{} var _ = gc.Suite(&unmarshalSuite{}) var unmarshalTests = []struct { about string val interface{} expect interface{} params httprequest.Params expectError string // TODO expectErrorCause func(error) bool }{{ about: "struct with simple fields", val: struct { F1 int `httprequest:",form"` F2 int `httprequest:",form"` G1 string `httprequest:",path"` G2 string `httprequest:",path"` H string `httprequest:",body"` UnknownForm string `httprequest:",form"` UnknownPath string `httprequest:",path"` }{ F1: 99, F2: -35, G1: "g1 val", G2: "g2 val", H: "h val", }, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{"Content-Type": {"application/json"}}, Form: url.Values{ "F1": {"99"}, "F2": {"-35", "not a number"}, }, Body: body(`"h val"`), }, PathVar: httprouter.Params{{ Key: "G2", Value: "g2 val", }, { Key: "G1", Value: "g1 val", }, { Key: "G1", Value: "g1 wrong val", }}, }, }, { about: "struct with renamed fields", val: struct { F1 int `httprequest:"x1,form"` F2 int `httprequest:"x2,form"` G1 string `httprequest:"g1,path"` G2 string `httprequest:"g2,path"` }{ F1: 99, F2: -35, G1: "g1 val", G2: "g2 val", }, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "x1": {"99"}, "x2": {"-35", "not a number"}, }, }, PathVar: httprouter.Params{{ Key: "g2", Value: "g2 val", }, { Key: "g1", Value: "g1 val", }, { Key: "g1", Value: "g1 wrong val", }}, }, }, { about: "unexported fields are ignored", val: struct { f int `httprequest:",form"` G int `httprequest:",form"` }{ G: 99, }, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "G": {"99"}, "f": {"100"}, }, }, }, }, { about: "unexported embedded type works ok", val: struct { sFG }{ sFG: sFG{ F: 99, G: 100, }, }, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "F": {"99"}, "G": {"100"}, }, }, }, }, { about: "unexported type for body is ignored", val: struct { foo sFG `httprequest:",body"` }{}, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{"Content-Type": {"application/json"}}, Body: body(`{"F": 99, "G": 100}`), }, }, }, { about: "fields without httprequest tags are ignored", val: struct { F int }{}, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "F": {"foo"}, }, }, PathVar: httprouter.Params{{ Key: "F", Value: "foo", }}, }, }, { about: "pointer fields are filled out", val: struct { F *int `httprequest:",form"` *SFG S *string `httprequest:",form"` T *string `httprequest:",form"` }{ F: newInt(99), SFG: &SFG{ F: 0, G: 534, }, S: newString("s val"), }, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "F": {"99"}, "G": {"534"}, "S": {"s val"}, }, }, }, }, { about: "UnmarshalText called on TextUnmarshalers", val: struct { F exclamationUnmarshaler `httprequest:",form"` G exclamationUnmarshaler `httprequest:",path"` FP *exclamationUnmarshaler `httprequest:",form"` }{ F: "yes!", G: "no!", FP: (*exclamationUnmarshaler)(newString("maybe!")), }, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "F": {"yes"}, "FP": {"maybe"}, }, }, PathVar: httprouter.Params{{ Key: "G", Value: "no", }}, }, }, { about: "UnmarshalText not called on values with a non-TextUnmarshaler UnmarshalText method", val: struct { F notTextUnmarshaler `httprequest:",form"` }{ F: "hello", }, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "F": {"hello"}, }, }, }, }, { about: "UnmarshalText returning an error", val: struct { F exclamationUnmarshaler `httprequest:",form"` }{}, params: httprequest.Params{ Request: &http.Request{}, }, expectError: "cannot unmarshal into field: empty string!", }, { about: "all field form values", val: struct { A []string `httprequest:",form"` B *[]string `httprequest:",form"` C []string `httprequest:",form"` D *[]string `httprequest:",form"` }{ A: []string{"a1", "a2"}, B: func() *[]string { x := []string{"b1", "b2", "b3"} return &x }(), }, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "A": {"a1", "a2"}, "B": {"b1", "b2", "b3"}, }, }, }, }, { about: "invalid scan field", val: struct { A int `httprequest:",form"` }{}, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "A": {"not an int"}, }, }, }, expectError: `cannot unmarshal into field: cannot parse "not an int" into int: expected integer`, }, { about: "scan field not present", val: struct { A int `httprequest:",form"` }{}, params: httprequest.Params{ Request: &http.Request{}, }, }, { about: "invalid JSON body", val: struct { A string `httprequest:",body"` }{}, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{"Content-Type": {"application/json"}}, Body: body("invalid JSON"), }, }, expectError: "cannot unmarshal into field: cannot unmarshal request body: invalid character 'i' looking for beginning of value", }, { about: "body with read error", val: struct { A string `httprequest:",body"` }{}, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{"Content-Type": {"application/json"}}, Body: errorReader("some error"), }, }, expectError: "cannot unmarshal into field: cannot read request body: some error", }, { about: "[]string not allowed for URL source", val: struct { A []string `httprequest:",path"` }{}, expectError: `bad type .*: invalid target type \[]string for path parameter`, }, { about: "duplicated body", val: struct { B1 int `httprequest:",body"` B2 string `httprequest:",body"` }{}, expectError: "bad type .*: more than one body field specified", }, { about: "body tag name is ignored", val: struct { B string `httprequest:"foo,body"` }{ B: "hello", }, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{"Content-Type": {"application/json"}}, Body: body(`"hello"`), }, }, }, { about: "tag with invalid source", val: struct { B1 int `httprequest:",xxx"` }{}, expectError: `bad type .*: bad tag "httprequest:\\",xxx\\"" in field B1: unknown tag flag "xxx"`, }, { about: "non-struct pointer", val: 0, expectError: `bad type \*int: type is not pointer to struct`, }, { about: "unmarshaling with wrong request content type", val: struct { A string `httprequest:",body"` }{}, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{"Content-Type": {"text/html"}}, Body: body("invalid JSON"), }, }, expectError: `cannot unmarshal into field: unexpected content type text/html; want application/json; content: invalid JSON`, }, { about: "struct with header fields", val: struct { F1 int `httprequest:"x1,header"` G1 string `httprequest:"g1,header"` }{ F1: 99, G1: "g1 val", }, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{ "x1": {"99"}, "g1": {"g1 val"}, }, }, }, }, { about: "all field header values", val: struct { A []string `httprequest:",header"` B *[]string `httprequest:",header"` C []string `httprequest:",header"` D *[]string `httprequest:",header"` }{ A: []string{"a1", "a2"}, B: func() *[]string { x := []string{"b1", "b2", "b3"} return &x }(), }, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{ "A": {"a1", "a2"}, "B": {"b1", "b2", "b3"}, }, }, }, }, { about: "anonymous body field with pointer field", val: struct { BodyWithPointer `httprequest:",body"` }{}, params: httprequest.Params{ Request: &http.Request{ Header: http.Header{"Content-Type": {"application/json"}}, Body: body("{}"), }, }, }, { about: "anonymous field with tag", val: struct { StructTextUnmarshaler `httprequest:"x,form"` }{ StructTextUnmarshaler{"something"}, }, params: httprequest.Params{ Request: &http.Request{ Form: url.Values{ "x": {"something"}, }, Body: body(`"h val"`), }, PathVar: httprouter.Params{{ // Note that this is the tagged field in the StructTextUnmarshaler type. Key: "foo", Value: "ignored", }}, }, }} // User represents a user in the system. type BodyWithPointer struct { N *int } type SFG struct { F int `httprequest:",form"` G int `httprequest:",form"` } type sFG struct { F int `httprequest:",form"` G int `httprequest:",form"` } func (*unmarshalSuite) TestUnmarshal(c *gc.C) { for i, test := range unmarshalTests[len(unmarshalTests)-1:] { c.Logf("%d: %s", i, test.about) t := reflect.TypeOf(test.val) fillv := reflect.New(t) err := httprequest.Unmarshal(test.params, fillv.Interface()) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) continue } c.Assert(err, gc.Equals, nil) c.Assert(fillv.Elem().Interface(), jc.DeepEquals, test.val) } } // TODO non-pointer struct type notTextUnmarshaler string // UnmarshalText does *not* implement encoding.TextUnmarshaler // (it has no arguments or error return value) func (t *notTextUnmarshaler) UnmarshalText() { panic("unexpected call") } type exclamationUnmarshaler string func (t *exclamationUnmarshaler) UnmarshalText(b []byte) error { if len(b) == 0 { return fmt.Errorf("empty string!") } *t = exclamationUnmarshaler(b) + "!" return nil } type StructTextUnmarshaler struct { // The tag on this field should be ignored because // the struct is embedded as an anonymous field. Foo string `httprequest:"foo,path"` } func (t *StructTextUnmarshaler) UnmarshalText(data []byte) error { t.Foo = string(data) return nil } func newInt(i int) *int { return &i } func newString(s string) *string { return &s } type errorReader string func (r errorReader) Read([]byte) (int, error) { return 0, fmt.Errorf("%s", r) } func (r errorReader) Close() error { return nil } func body(s string) io.ReadCloser { return ioutil.NopCloser(strings.NewReader(s)) } ����������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/unmarshal.go����������������������������������������0000644�0610621�0607500�00000017162�13172163410�025154� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httprequest import ( "encoding/json" "fmt" "io/ioutil" "reflect" "gopkg.in/errgo.v1" ) var ( ErrUnmarshal = errgo.New("httprequest unmarshal error") ErrBadUnmarshalType = errgo.New("httprequest bad unmarshal type") ) // Unmarshal takes values from given parameters and fills // out fields in x, which must be a pointer to a struct. // // Tags on the struct's fields determine where each field is filled in // from. Similar to encoding/json and other encoding packages, the tag // holds a comma-separated list. The first item in the list is an // alternative name for the field (the field name itself will be used if // this is empty). The next item specifies where the field is filled in // from. It may be: // // "path" - the field is taken from a parameter in p.PathVar // with a matching field name. // // "form" - the field is taken from the given name in p.Request.Form // (note that this covers both URL query parameters and // POST form parameters). // // "header" - the field is taken from the given name in // p.Request.Header. // // "body" - the field is filled in by parsing the request body // as JSON. // // For path and form parameters, the field will be filled out from // the field in p.PathVar or p.Form using one of the following // methods (in descending order of preference): // // - if the type is string, it will be set from the first value. // // - if the type is []string, it will be filled out using all values for that field // (allowed only for form) // // - if the type implements encoding.TextUnmarshaler, its // UnmarshalText method will be used // // - otherwise fmt.Sscan will be used to set the value. // // When the unmarshaling fails, Unmarshal returns an error with an // ErrUnmarshal cause. If the type of x is inappropriate, // it returns an error with an ErrBadUnmarshalType cause. func Unmarshal(p Params, x interface{}) error { xv := reflect.ValueOf(x) pt, err := getRequestType(xv.Type()) if err != nil { return errgo.WithCausef(err, ErrBadUnmarshalType, "bad type %s", xv.Type()) } if err := unmarshal(p, xv, pt); err != nil { return errgo.Mask(err, errgo.Is(ErrUnmarshal)) } return nil } // unmarshal is the internal version of Unmarshal. func unmarshal(p Params, xv reflect.Value, pt *requestType) error { xv = xv.Elem() for _, f := range pt.fields { fv := xv.FieldByIndex(f.index) if err := f.unmarshal(fv, p, f.makeResult); err != nil { return errgo.WithCausef(err, ErrUnmarshal, "cannot unmarshal into field %s", f.name) } } return nil } // getUnmarshaler returns an unmarshaler function // suitable for unmarshaling a field with the given tag // into a value of the given type. func getUnmarshaler(tag tag, t reflect.Type) (unmarshaler, error) { switch { case tag.source == sourceNone: return unmarshalNop, nil case tag.source == sourceBody: return unmarshalBody, nil case t == reflect.TypeOf([]string(nil)): switch tag.source { default: return nil, errgo.New("invalid target type []string for path parameter") case sourceForm: return unmarshalAllField(tag.name), nil case sourceHeader: return unmarshalAllHeader(tag.name), nil } case t == reflect.TypeOf(""): return unmarshalString(tag), nil case implementsTextUnmarshaler(t): return unmarshalWithUnmarshalText(t, tag), nil default: return unmarshalWithScan(tag), nil } } // unmarshalNop just creates the result value but does not // fill it out with anything. This is used to create pointers // to new anonymous field members. func unmarshalNop(v reflect.Value, p Params, makeResult resultMaker) error { makeResult(v) return nil } // unmarshalAllField unmarshals all the form fields for a given // attribute into a []string slice. func unmarshalAllField(name string) unmarshaler { return func(v reflect.Value, p Params, makeResult resultMaker) error { vals := p.Request.Form[name] if len(vals) > 0 { makeResult(v).Set(reflect.ValueOf(vals)) } return nil } } // unmarshalAllHeader unmarshals all the header fields for a given // attribute into a []string slice. func unmarshalAllHeader(name string) unmarshaler { return func(v reflect.Value, p Params, makeResult resultMaker) error { vals := p.Request.Header[name] if len(vals) > 0 { makeResult(v).Set(reflect.ValueOf(vals)) } return nil } } // unmarshalString unmarshals into a string field. func unmarshalString(tag tag) unmarshaler { getVal := formGetters[tag.source] if getVal == nil { panic("unexpected source") } return func(v reflect.Value, p Params, makeResult resultMaker) error { val, ok := getVal(tag.name, p) if ok { makeResult(v).SetString(val) } return nil } } // unmarshalBody unmarshals the http request body // into the given value. func unmarshalBody(v reflect.Value, p Params, makeResult resultMaker) error { if !isJSONMediaType(p.Request.Header) { fancyErr := newFancyDecodeError(p.Request.Header, p.Request.Body) return newDecodeRequestError(p.Request, fancyErr.body, fancyErr) } data, err := ioutil.ReadAll(p.Request.Body) if err != nil { return errgo.Notef(err, "cannot read request body") } // TODO allow body types that aren't necessarily JSON. result := makeResult(v) if err := json.Unmarshal(data, result.Addr().Interface()); err != nil { return errgo.Notef(err, "cannot unmarshal request body") } return nil } // formGetters maps from source to a function that // returns the value for a given key and reports // whether the value was found. var formGetters = []func(name string, p Params) (string, bool){ sourceForm: func(name string, p Params) (string, bool) { vs := p.Request.Form[name] if len(vs) == 0 { return "", false } return vs[0], true }, sourcePath: func(name string, p Params) (string, bool) { for _, pv := range p.PathVar { if pv.Key == name { return pv.Value, true } } return "", false }, sourceBody: nil, sourceHeader: func(name string, p Params) (string, bool) { vs := p.Request.Header[name] if len(vs) == 0 { return "", false } return vs[0], true }, } // encodingTextUnmarshaler is the same as encoding.TextUnmarshaler // but avoids us importing the encoding package, which some // broken gccgo installations do not allow. // TODO remove this and use encoding.TextUnmarshaler instead. type encodingTextUnmarshaler interface { UnmarshalText(text []byte) error } var textUnmarshalerType = reflect.TypeOf((*encodingTextUnmarshaler)(nil)).Elem() func implementsTextUnmarshaler(t reflect.Type) bool { // Use the pointer type, because a pointer // type will implement a superset of the methods // of a non-pointer type. return reflect.PtrTo(t).Implements(textUnmarshalerType) } // unmarshalWithUnmarshalText returns an unmarshaler // that unmarshals the given type from the given tag // using its UnmarshalText method. func unmarshalWithUnmarshalText(t reflect.Type, tag tag) unmarshaler { getVal := formGetters[tag.source] if getVal == nil { panic("unexpected source") } return func(v reflect.Value, p Params, makeResult resultMaker) error { val, _ := getVal(tag.name, p) uv := makeResult(v).Addr().Interface().(encodingTextUnmarshaler) return uv.UnmarshalText([]byte(val)) } } // unmarshalWithScan returns an unmarshaler // that unmarshals the given tag using fmt.Scan. func unmarshalWithScan(tag tag) unmarshaler { formGet := formGetters[tag.source] if formGet == nil { panic("unexpected source") } return func(v reflect.Value, p Params, makeResult resultMaker) error { val, ok := formGet(tag.name, p) if !ok { // TODO allow specifying that a field is mandatory? return nil } _, err := fmt.Sscan(val, makeResult(v).Addr().Interface()) if err != nil { return errgo.Notef(err, "cannot parse %q into %s", val, v.Type()) } return nil } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/type.go���������������������������������������������0000644�0610621�0607500�00000023537�13172163410�024146� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. // Package httprequest provides functionality for unmarshaling // HTTP request parameters into a struct type. // // Please note that the API is not considered stable at this // point and may be changed in a backwardly incompatible // manner at any time. package httprequest import ( "fmt" "net/http" "reflect" "sort" "strings" "sync" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" "gopkg.in/errgo.v1" ) // TODO include field name and source in error messages. var ( typeMutex sync.RWMutex typeMap = make(map[reflect.Type]*requestType) ) // Route is the type of a field that specifies a routing // path and HTTP method. See Marshal and Unmarshal // for details. type Route struct{} // Params holds the parameters provided to an HTTP request. type Params struct { Response http.ResponseWriter Request *http.Request PathVar httprouter.Params // PathPattern holds the path pattern matched by httprouter. // It is only set where httprequest has the information; // that is where the call was made by Server.Handler // or Server.Handlers. PathPattern string // Context holds a context for the request. In Go 1.7 and later, // this should be used in preference to Request.Context. Context context.Context } // resultMaker is provided to the unmarshal functions. // When called with the value passed to the unmarshaler, // it returns the field value to be assigned to, // creating it if necessary. type resultMaker func(reflect.Value) reflect.Value // unmarshaler unmarshals some value from params into // the given value. The value should not be assigned to directly, // but passed to makeResult and then updated. type unmarshaler func(v reflect.Value, p Params, makeResult resultMaker) error // marshaler marshals the specified value into params. // The value is always the value type, even if the field type // is a pointer. type marshaler func(reflect.Value, *Params) error // requestType holds information derived from a request // type, preprocessed so that it's quick to marshal or unmarshal. type requestType struct { method string path string fields []field } // field holds preprocessed information on an individual field // in the request. type field struct { name string // index holds the index slice of the field. index []int // unmarshal is used to unmarshal the value into // the given field. The value passed as its first // argument is not a pointer type, but is addressable. unmarshal unmarshaler // marshal is used to marshal the value into the // give filed. The value passed as its first argument is not // a pointer type, but it is addressable. marshal marshaler // makeResult is the resultMaker that will be // passed into the unmarshaler. makeResult resultMaker // isPointer is true if the field is pointer to the underlying type. isPointer bool } // getRequestType is like parseRequestType except that // it returns the cached requestType when possible, // adding the type to the cache otherwise. func getRequestType(t reflect.Type) (*requestType, error) { typeMutex.RLock() pt := typeMap[t] typeMutex.RUnlock() if pt != nil { return pt, nil } typeMutex.Lock() defer typeMutex.Unlock() if pt = typeMap[t]; pt != nil { // The type has been parsed after we dropped // the read lock, so use it. return pt, nil } pt, err := parseRequestType(t) if err != nil { return nil, errgo.Mask(err) } typeMap[t] = pt return pt, nil } // parseRequestType preprocesses the given type // into a form that can be efficiently interpreted // by Unmarshal. func parseRequestType(t reflect.Type) (*requestType, error) { if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct { return nil, fmt.Errorf("type is not pointer to struct") } hasBody := false var pt requestType foundRoute := false // taggedFieldIndex holds the index of most recent anonymous // tagged field - we will skip any fields inside that. // It is nil when we're not inside an anonymous tagged field. var taggedFieldIndex []int for _, f := range fields(t.Elem()) { if f.PkgPath != "" && !f.Anonymous { // Ignore non-anonymous unexported fields. continue } if taggedFieldIndex != nil && withinIndex(f.Index, taggedFieldIndex) { // Ignore fields within tagged anonymous fields. continue } taggedFieldIndex = nil if !foundRoute && f.Anonymous && f.Type == reflect.TypeOf(Route{}) { var err error pt.method, pt.path, err = parseRouteTag(f.Tag) if err != nil { return nil, errgo.Notef(err, "bad route tag %q", f.Tag) } foundRoute = true continue } tag, err := parseTag(f.Tag, f.Name) if err != nil { return nil, errgo.Notef(err, "bad tag %q in field %s", f.Tag, f.Name) } if tag.source == sourceBody { if hasBody { return nil, errgo.New("more than one body field specified") } hasBody = true } field := field{ index: f.Index, name: f.Name, } if f.Type.Kind() == reflect.Ptr { // The field is a pointer, so when the value is set, // we need to create a new pointer to put // it into. field.makeResult = makePointerResult field.isPointer = true f.Type = f.Type.Elem() } else { field.makeResult = makeValueResult field.isPointer = false } field.unmarshal, err = getUnmarshaler(tag, f.Type) if err != nil { return nil, errgo.Mask(err) } field.marshal, err = getMarshaler(tag, f.Type) if err != nil { return nil, errgo.Mask(err) } if f.Anonymous && tag.source != sourceNone { taggedFieldIndex = f.Index } pt.fields = append(pt.fields, field) } return &pt, nil } // withinIndex reports whether the field with index i0 should be // considered to be within the field with index i1. func withinIndex(i0, i1 []int) bool { // The index of a field within an anonymous field is formed by // appending its field offset to the anonymous field's index, so // it is sufficient that we check that i0 is prefixed by i1. if len(i0) < len(i1) { return false } for i := range i1 { if i0[i] != i1[i] { return false } } return true } // Note: we deliberately omit HEAD and OPTIONS // from this list. HEAD will be routed through GET handlers // and OPTIONS is handled separately. var validMethod = map[string]bool{ "PUT": true, "POST": true, "DELETE": true, "GET": true, "PATCH": true, } func parseRouteTag(tag reflect.StructTag) (method, path string, err error) { tagStr := tag.Get("httprequest") if tagStr == "" { return "", "", errgo.New("no httprequest tag") } f := strings.Fields(tagStr) switch len(f) { case 2: path = f[1] fallthrough case 1: method = f[0] default: return "", "", errgo.New("wrong field count") } if !validMethod[method] { return "", "", errgo.Newf("invalid method") } // TODO check that path looks valid return method, path, nil } func makePointerResult(v reflect.Value) reflect.Value { if v.IsNil() { v.Set(reflect.New(v.Type().Elem())) } return v.Elem() } func makeValueResult(v reflect.Value) reflect.Value { return v } type tagSource uint8 const ( sourceNone = iota sourcePath sourceForm sourceBody sourceHeader ) type tag struct { name string source tagSource omitempty bool } // parseTag parses the given struct tag attached to the given // field name into a tag structure. func parseTag(rtag reflect.StructTag, fieldName string) (tag, error) { t := tag{ name: fieldName, } tagStr := rtag.Get("httprequest") if tagStr == "" { return t, nil } fields := strings.Split(tagStr, ",") if fields[0] != "" { t.name = fields[0] } for _, f := range fields[1:] { switch f { case "path": t.source = sourcePath case "form": t.source = sourceForm case "body": t.source = sourceBody case "header": t.source = sourceHeader case "omitempty": t.omitempty = true default: return tag{}, fmt.Errorf("unknown tag flag %q", f) } } if t.omitempty && t.source != sourceForm && t.source != sourceHeader { return tag{}, fmt.Errorf("can only use omitempty with form or header fields") } return t, nil } // fields returns all the fields in the given struct type // including fields inside anonymous struct members. // The fields are ordered with top level fields first // followed by the members of those fields // for anonymous fields. func fields(t reflect.Type) []reflect.StructField { byName := make(map[string]reflect.StructField) addFields(t, byName, nil) fields := make(fieldsByIndex, 0, len(byName)) for _, f := range byName { if f.Name != "" { fields = append(fields, f) } } sort.Sort(fields) return fields } func addFields(t reflect.Type, byName map[string]reflect.StructField, index []int) { for i := 0; i < t.NumField(); i++ { f := t.Field(i) index := append(index, i) var add bool old, ok := byName[f.Name] switch { case ok && len(old.Index) == len(index): // Fields with the same name at the same depth // cancel one another out. Set the field name // to empty to signify that has happened. old.Name = "" byName[f.Name] = old add = false case ok: // Fields at less depth win. add = len(index) < len(old.Index) default: // The field did not previously exist. add = true } if add { // copy the index so that it's not overwritten // by the other appends. f.Index = append([]int(nil), index...) byName[f.Name] = f } if f.Anonymous { if f.Type.Kind() == reflect.Ptr { f.Type = f.Type.Elem() } if f.Type.Kind() == reflect.Struct { addFields(f.Type, byName, index) } } } } type fieldsByIndex []reflect.StructField func (f fieldsByIndex) Len() int { return len(f) } func (f fieldsByIndex) Swap(i, j int) { f[i], f[j] = f[j], f[i] } func (f fieldsByIndex) Less(i, j int) bool { indexi, indexj := f[i].Index, f[j].Index for len(indexi) != 0 && len(indexj) != 0 { ii, ij := indexi[0], indexj[0] if ii != ij { return ii < ij } indexi, indexj = indexi[1:], indexj[1:] } return len(indexi) < len(indexj) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/package_test.go�������������������������������������0000644�0610621�0607500�00000000333�13172163410�025604� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest_test import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/marshal_test.go�������������������������������������0000644�0610621�0607500�00000027740�13172163410�025653� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest_test import ( "io/ioutil" "net/http" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "github.com/juju/httprequest" ) type marshalSuite struct{} var _ = gc.Suite(&marshalSuite{}) type embedded struct { F1 string `json:"name"` F2 int `json:"age"` F3 *string `json:"address"` } var marshalTests = []struct { about string urlString string method string val interface{} expectURLString string expectBody *string expectHeader http.Header expectError string }{{ about: "struct with simple fields", urlString: "http://localhost:8081/:F1", val: &struct { F1 int `httprequest:",path"` F2 string `httprequest:",form"` F3 string `httprequest:",form,omitempty"` F4 string `httprequest:",form,omitempty"` }{ F1: 99, F2: "some text", F3: "", F4: "something", }, expectURLString: "http://localhost:8081/99?F2=some+text&F4=something", }, { about: "struct with renamed fields", urlString: "http://localhost:8081/:name", val: &struct { F1 string `httprequest:"name,path"` F2 int `httprequest:"age,form"` }{ F1: "some random user", F2: 42, }, expectURLString: "http://localhost:8081/some%20random%20user?age=42", }, { about: "fields without httprequest tags are ignored", urlString: "http://localhost:8081/:name", val: &struct { F1 string `httprequest:"name,path"` F2 int `httprequest:"age,form"` F3 string }{ F1: "some random user", F2: 42, F3: "some more random text", }, expectURLString: "http://localhost:8081/some%20random%20user?age=42", }, { about: "pointer fields are correctly handled", urlString: "http://localhost:8081/:name", val: &struct { F1 *string `httprequest:"name,path"` F2 *string `httprequest:"age,form"` F3 *string `httprequest:"address,form"` }{ F1: newString("some random user"), F2: newString("42"), }, expectURLString: "http://localhost:8081/some%20random%20user?age=42", }, { about: "MarshalText called on TextMarshalers", urlString: "http://localhost:8081/:param1/:param2", val: &struct { F1 testMarshaler `httprequest:"param1,path"` F2 *testMarshaler `httprequest:"param2,path"` F3 testMarshaler `httprequest:"param3,form"` F4 *testMarshaler `httprequest:"param4,form"` }{ F1: "test1", F2: (*testMarshaler)(newString("test2")), F3: "test3", F4: (*testMarshaler)(newString("test4")), }, expectURLString: "http://localhost:8081/test_test1/test_test2?param3=test_test3&param4=test_test4", }, { about: "MarshalText not called on values that do not implement TextMarshaler", urlString: "http://localhost:8081/user/:name/:surname", val: &struct { F1 notTextMarshaler `httprequest:"name,path"` F2 *notTextMarshaler `httprequest:"surname,path"` }{ F1: "name", F2: (*notTextMarshaler)(newString("surname")), }, expectURLString: "http://localhost:8081/user/name/surname", }, { about: "MarshalText returns an error", urlString: "http://localhost:8081/user/:name/:surname", val: &struct { F1 testMarshaler `httprequest:"name,path"` F2 *testMarshaler `httprequest:"surname,path"` }{ F1: "", F2: (*testMarshaler)(newString("surname")), }, expectError: "cannot marshal field: empty string", }, { about: "[]string field form value", urlString: "http://localhost:8081/user", val: &struct { F1 []string `httprequest:"users,form"` }{ F1: []string{"user1", "user2", "user3"}, }, expectURLString: "http://localhost:8081/user?users=user1&users=user2&users=user3", }, { about: "nil []string field form value", urlString: "http://localhost:8081/user", val: &struct { F1 *[]string `httprequest:"users,form"` }{ F1: nil, }, expectURLString: "http://localhost:8081/user", }, { about: "cannot marshal []string field to path", urlString: "http://localhost:8081/:users", val: &struct { F1 []string `httprequest:"users,path"` }{ F1: []string{"user1", "user2"}, }, expectError: `bad type \*struct { F1 \[\]string "httprequest:\\"users,path\\"" }: invalid target type \[\]string for path parameter`, }, { about: "[]string field fails to marshal to path", urlString: "http://localhost:8081/user/:users", val: &struct { F1 []string `httprequest:"users,path"` }{ F1: []string{"user1", "user2", "user3"}, }, expectError: "bad type .*: invalid target type.*", }, { about: "omitempty on body", urlString: "http://localhost:8081/:users", val: &struct { Body string `httprequest:",body,omitempty"` }{}, expectError: `bad type \*struct { Body string "httprequest:\\",body,omitempty\\"" }: bad tag "httprequest:\\",body,omitempty\\"" in field Body: can only use omitempty with form or header fields`, }, { about: "omitempty on path", urlString: "http://localhost:8081/:Users", val: &struct { Users string `httprequest:",path,omitempty"` }{}, expectError: `bad type \*struct { Users string "httprequest:\\",path,omitempty\\"" }: bad tag "httprequest:\\",path,omitempty\\"" in field Users: can only use omitempty with form or header fields`, }, { about: "more than one field with body tag", urlString: "http://localhost:8081/user", method: "POST", val: &struct { F1 string `httprequest:"user,body"` F2 int `httprequest:"age,body"` }{ F1: "test user", F2: 42, }, expectError: "bad type .*: more than one body field specified", }, { about: "required path parameter, but not specified", urlString: "http://localhost:8081/u/:username", method: "POST", val: &struct { F1 string `httprequest:"user,body"` }{ F1: "test user", }, expectError: `missing value for path parameter "username"`, }, { about: "marshal to body", urlString: "http://localhost:8081/u", method: "POST", val: &struct { F1 embedded `httprequest:"info,body"` }{ F1: embedded{ F1: "test user", F2: 42, F3: newString("test address"), }, }, expectBody: newString(`{"name":"test user","age":42,"address":"test address"}`), }, { about: "empty path wildcard", urlString: "http://localhost:8081/u/:", method: "POST", val: &struct { F1 string `httprequest:"user,body"` }{ F1: "test user", }, expectError: "empty path parameter", }, { about: "nil field to form", urlString: "http://localhost:8081/u", val: &struct { F1 *string `httprequest:"user,form"` }{}, expectURLString: "http://localhost:8081/u", }, { about: "nil field to path", urlString: "http://localhost:8081/u", val: &struct { F1 *string `httprequest:"user,path"` }{}, expectURLString: "http://localhost:8081/u", }, { about: "marshal to body of a GET request", urlString: "http://localhost:8081/u", val: &struct { F1 string `httprequest:",body"` }{ F1: "hello test", }, // Providing a body to a GET request is unusual but // some people do it anyway. expectBody: newString(`"hello test"`), }, { about: "marshal to nil value to body", urlString: "http://localhost:8081/u", val: &struct { F1 *string `httprequest:",body"` }{ F1: nil, }, expectBody: newString(""), }, { about: "nil TextMarshaler", urlString: "http://localhost:8081/u", val: &struct { F1 *testMarshaler `httprequest:"surname,form"` }{ F1: (*testMarshaler)(nil), }, expectURLString: "http://localhost:8081/u", }, { about: "marshal nil with Sprint", urlString: "http://localhost:8081/u", val: &struct { F1 *int `httprequest:"surname,form"` }{ F1: (*int)(nil), }, expectURLString: "http://localhost:8081/u", }, { about: "marshal to path with * placeholder", urlString: "http://localhost:8081/u/*name", val: &struct { F1 string `httprequest:"name,path"` }{ F1: "/test", }, expectURLString: "http://localhost:8081/u/test", }, { about: "marshal to path with * placeholder, but the marshaled value does not start with /", urlString: "http://localhost:8081/u/*name", val: &struct { F1 string `httprequest:"name,path"` }{ F1: "test", }, expectError: `value \"test\" for path parameter \"\*name\" does not start with required /`, }, { about: "* placeholder allowed only at the end", urlString: "http://localhost:8081/u/*name/document", val: &struct { F1 string `httprequest:"name,path"` }{ F1: "test", }, expectError: "star path parameter is not at end of path", }, { about: "unparsable base url string", urlString: "%%", val: &struct { F1 string `httprequest:"name,form"` }{ F1: "test", }, expectError: `parse %%: invalid URL escape \"%%\"`, }, { about: "value cannot be marshaled to json", urlString: "http://localhost", method: "POST", val: &struct { F1 failJSONMarshaler `httprequest:"field,body"` }{ F1: "test", }, expectError: `cannot marshal field: cannot marshal request body: json: error calling MarshalJSON for type \*httprequest_test.failJSONMarshaler: marshal error`, }, { about: "url with query parameters", urlString: "http://localhost?a=b", method: "POST", val: &struct { F1 failJSONMarshaler `httprequest:"f1,form"` }{ F1: "test", }, expectURLString: "http://localhost?a=b&f1=test", }, { about: "url with query parameters no form", urlString: "http://localhost?a=b", method: "POST", val: &struct{}{}, expectURLString: "http://localhost?a=b", }, { about: "struct with headers", urlString: "http://localhost:8081/", val: &struct { F1 string `httprequest:",header"` F2 int `httprequest:",header"` F3 bool `httprequest:",header"` F4 string `httprequest:",header,omitempty"` F5 string `httprequest:",header,omitempty"` }{ F1: "some text", F2: 99, F3: true, F4: "", F5: "something", }, expectURLString: "http://localhost:8081/", expectHeader: http.Header{ "F1": []string{"some text"}, "F2": []string{"99"}, "F3": []string{"true"}, "F5": []string{"something"}, }, }, { about: "struct with header slice", urlString: "http://localhost:8081/:F1", val: &struct { F1 int `httprequest:",path"` F2 string `httprequest:",form"` F3 []string `httprequest:",header"` }{ F1: 99, F2: "some text", F3: []string{"A", "B", "C"}, }, expectURLString: "http://localhost:8081/99?F2=some+text", expectHeader: http.Header{"F3": []string{"A", "B", "C"}}, }, { about: "SetHeader called after marshaling", urlString: "http://localhost:8081/", val: &httprequest.CustomHeader{ Body: &struct { F1 string `httprequest:",header"` F2 int `httprequest:",header"` F3 bool `httprequest:",header"` }{ F1: "some text", F2: 99, F3: false, }, SetHeaderFunc: func(h http.Header) { h.Set("F2", "some other text") }, }, expectURLString: "http://localhost:8081/", expectHeader: http.Header{ "F1": []string{"some text"}, "F2": []string{"some other text"}, "F3": []string{"false"}, }, }} func getStruct() interface{} { return &struct { F1 string }{ F1: "hello", } } func (*marshalSuite) TestMarshal(c *gc.C) { for i, test := range marshalTests { c.Logf("%d: %s", i, test.about) method := "GET" if test.method != "" { method = test.method } req, err := httprequest.Marshal(test.urlString, method, test.val) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) continue } c.Assert(err, gc.IsNil) if test.expectURLString != "" { c.Assert(req.URL.String(), gc.DeepEquals, test.expectURLString) } if test.expectBody != nil { data, err := ioutil.ReadAll(req.Body) c.Assert(err, gc.IsNil) if *test.expectBody != "" { c.Assert(req.Header.Get("Content-Type"), gc.Equals, "application/json") } c.Assert(string(data), gc.DeepEquals, *test.expectBody) } for k, v := range test.expectHeader { c.Assert(req.Header[k], gc.DeepEquals, v) } } } type testMarshaler string func (t *testMarshaler) MarshalText() ([]byte, error) { if len(*t) == 0 { return nil, errgo.New("empty string") } return []byte("test_" + *t), nil } type notTextMarshaler string // MarshalText does *not* implement encoding.TextMarshaler func (t *notTextMarshaler) MarshalText() { panic("unexpected call") } type failJSONMarshaler string func (*failJSONMarshaler) MarshalJSON() ([]byte, error) { return nil, errgo.New("marshal error") } ��������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/marshal.go������������������������������������������0000644�0610621�0607500�00000023260�13172163410�024605� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest import ( "bytes" "encoding/json" "fmt" "net/http" "net/url" "reflect" "strings" "github.com/julienschmidt/httprouter" "gopkg.in/errgo.v1" ) var emptyReader = bytes.NewReader(nil) // Marshal is the counterpart of Unmarshal. It takes information from // x, which must be a pointer to a struct, and returns an HTTP request // using the given method that holds all of the information. // // The Body field in the returned request will always be of type // BytesReaderCloser. // // If x implements the HeaderSetter interface, its SetHeader method will // be called to add additional headers to the HTTP request after it has // been marshaled. If x is pointer to a CustomHeader object then Marshal will use // its Body member to create the HTTP request. // // The HTTP request will use the given method. Named fields in the given // baseURL will be filled out from "path"-tagged fields in x to form the // URL path in the returned request. These are specified as for httprouter. // // If a field in baseURL is a suffix of the form "*var" (a trailing wildcard element // that holds the rest of the path), the marshaled string must begin with a "/". // This matches the httprouter convention that it always returns such fields // with a "/" prefix. // // If a field is of type string or []string, the value of the field will // be used directly; otherwise if implements encoding.TextMarshaler, that // will be used to marshal the field, otherwise fmt.Sprint will be used. // // An "omitempty" attribute on a form or header field specifies that // if the form or header value is empty, the form or header entry // will be omitted. // // For example, this code: // // type UserDetails struct { // Age int // } // // type Test struct { // Username string `httprequest:"user,path"` // ContextId int64 `httprequest:"context,form"` // Extra string `httprequest:"context,form,omitempty"` // Details UserDetails `httprequest:",body"` // } // req, err := Marshal("GET", "http://example.com/users/:user/details", &Test{ // Username: "bob", // ContextId: 1234, // Details: UserDetails{ // Age: 36, // } // }) // if err != nil { // ... // } // // will produce an HTTP request req with a URL of // http://example.com/users/bob/details?context=1234 and a JSON-encoded // body holding `{"Age":36}`. // // It is an error if there is a field specified in the URL that is not // found in x. func Marshal(baseURL, method string, x interface{}) (*http.Request, error) { var xv reflect.Value if ch, ok := x.(*CustomHeader); ok { xv = reflect.ValueOf(ch.Body) } else { xv = reflect.ValueOf(x) } pt, err := getRequestType(xv.Type()) if err != nil { return nil, errgo.WithCausef(err, ErrBadUnmarshalType, "bad type %s", xv.Type()) } req, err := http.NewRequest(method, baseURL, BytesReaderCloser{emptyReader}) if err != nil { return nil, errgo.Mask(err) } req.Form = url.Values{} p := &Params{ Request: req, } if err := marshal(p, xv, pt); err != nil { return nil, errgo.Mask(err, errgo.Is(ErrUnmarshal)) } if headerSetter, ok := x.(HeaderSetter); ok { headerSetter.SetHeader(p.Request.Header) } return p.Request, nil } // marshal is the internal version of Marshal. func marshal(p *Params, xv reflect.Value, pt *requestType) error { xv = xv.Elem() for _, f := range pt.fields { fv := xv.FieldByIndex(f.index) if f.isPointer { if fv.IsNil() { continue } fv = fv.Elem() } // TODO store the field name in the field so // that we can produce a nice error message. if err := f.marshal(fv, p); err != nil { return errgo.WithCausef(err, ErrUnmarshal, "cannot marshal field") } } path, err := buildPath(p.Request.URL.Path, p.PathVar) if err != nil { return errgo.Mask(err) } p.Request.URL.Path = path if q := p.Request.Form.Encode(); q != "" && p.Request.URL.RawQuery != "" { p.Request.URL.RawQuery += "&" + q } else { p.Request.URL.RawQuery += q } return nil } func buildPath(path string, p httprouter.Params) (string, error) { pathBytes := make([]byte, 0, len(path)*2) for { s, rest := nextPathSegment(path) if s == "" { break } if s[0] != ':' && s[0] != '*' { pathBytes = append(pathBytes, s...) path = rest continue } if s[0] == '*' && rest != "" { return "", errgo.New("star path parameter is not at end of path") } if len(s) == 1 { return "", errgo.New("empty path parameter") } val := p.ByName(s[1:]) if val == "" { return "", errgo.Newf("missing value for path parameter %q", s[1:]) } if s[0] == '*' { if !strings.HasPrefix(val, "/") { return "", errgo.Newf("value %q for path parameter %q does not start with required /", val, s) } val = val[1:] } pathBytes = append(pathBytes, val...) path = rest } return string(pathBytes), nil } // nextPathSegment returns the next wildcard or constant // segment of the given path and everything after that // segment. func nextPathSegment(s string) (string, string) { if s == "" { return "", "" } if s[0] == ':' || s[0] == '*' { if i := strings.Index(s, "/"); i != -1 { return s[0:i], s[i:] } return s, "" } if i := strings.IndexAny(s, ":*"); i != -1 { return s[0:i], s[i:] } return s, "" } // getMarshaler returns a marshaler function suitable for marshaling // a field with the given tag into and http request. func getMarshaler(tag tag, t reflect.Type) (marshaler, error) { switch { case tag.source == sourceNone: return marshalNop, nil case tag.source == sourceBody: return marshalBody, nil case t == reflect.TypeOf([]string(nil)): switch tag.source { default: return nil, errgo.New("invalid target type []string for path parameter") case sourceForm: return marshalAllField(tag.name), nil case sourceHeader: return marshalAllHeader(tag.name), nil } case t == reflect.TypeOf(""): return marshalString(tag), nil case implementsTextMarshaler(t): return marshalWithMarshalText(t, tag), nil default: return marshalWithSprint(tag), nil } } // marshalNop does nothing with the value. func marshalNop(v reflect.Value, p *Params) error { return nil } // mashalBody marshals the specified value into the body of the http request. func marshalBody(v reflect.Value, p *Params) error { // TODO allow body types that aren't necessarily JSON. data, err := json.Marshal(v.Addr().Interface()) if err != nil { return errgo.Notef(err, "cannot marshal request body") } p.Request.Body = BytesReaderCloser{bytes.NewReader(data)} p.Request.ContentLength = int64(len(data)) p.Request.Header.Set("Content-Type", "application/json") return nil } // marshalAllField marshals a []string slice into form fields. func marshalAllField(name string) marshaler { return func(v reflect.Value, p *Params) error { if ss := v.Interface().([]string); len(ss) > 0 { p.Request.Form[name] = ss } return nil } } // marshalAllHeader marshals a []string slice into a header. func marshalAllHeader(name string) marshaler { return func(v reflect.Value, p *Params) error { if ss := v.Interface().([]string); len(ss) > 0 { p.Request.Header[name] = ss } return nil } } // marshalString marshals s string field. func marshalString(tag tag) marshaler { formSet := formSetter(tag) return func(v reflect.Value, p *Params) error { formSet(tag.name, v.String(), p) return nil } } // encodingTextMarshaler is the same as encoding.TextUnmarshaler // but avoids us importing the encoding package, which some // broken gccgo installations do not allow. // TODO remove this and use encoding.TextMarshaler instead. type encodingTextMarshaler interface { MarshalText() (text []byte, err error) } var textMarshalerType = reflect.TypeOf((*encodingTextMarshaler)(nil)).Elem() func implementsTextMarshaler(t reflect.Type) bool { // Use the pointer type, because a pointer // type will implement a superset of the methods // of a non-pointer type. return reflect.PtrTo(t).Implements(textMarshalerType) } // marshalWithMarshalText returns a marshaler // that marshals the given type from the given tag // using its MarshalText method. func marshalWithMarshalText(t reflect.Type, tag tag) marshaler { formSet := formSetter(tag) return func(v reflect.Value, p *Params) error { m := v.Addr().Interface().(encodingTextMarshaler) data, err := m.MarshalText() if err != nil { return errgo.Mask(err) } formSet(tag.name, string(data), p) return nil } } // marshalWithSprint returns an marshaler // that unmarshals the given tag using fmt.Sprint. func marshalWithSprint(tag tag) marshaler { formSet := formSetter(tag) return func(v reflect.Value, p *Params) error { formSet(tag.name, fmt.Sprint(v.Interface()), p) return nil } } // formSetter returns a function that can set the value // for a given tag. func formSetter(t tag) func(name, value string, p *Params) { formSet := formSetters[t.source] if formSet == nil { panic("unexpected source") } if !t.omitempty { return formSet } return func(name, value string, p *Params) { if value != "" { formSet(name, value, p) } } } // formSetters maps from source to a function that // sets the value for a given key. var formSetters = []func(string, string, *Params){ sourceForm: func(name, value string, p *Params) { p.Request.Form.Set(name, value) }, sourcePath: func(name, value string, p *Params) { p.PathVar = append(p.PathVar, httprouter.Param{Key: name, Value: value}) }, sourceBody: nil, sourceHeader: func(name, value string, p *Params) { p.Request.Header.Set(name, value) }, } // BytesReaderCloser is a bytes.Reader which // implements io.Closer with a no-op Close method. type BytesReaderCloser struct { *bytes.Reader } // Close implements io.Closer.Close. func (BytesReaderCloser) Close() error { return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/handler_test.go�������������������������������������0000644�0610621�0607500�00000102326�13172163410�025633� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest_test import ( "encoding/json" "errors" "net/http" "net/http/httptest" "net/url" jc "github.com/juju/testing/checkers" "github.com/juju/testing/httptesting" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "github.com/juju/httprequest" ) type handlerSuite struct{} var _ = gc.Suite(&handlerSuite{}) var handleTests = []struct { about string f func(c *gc.C) interface{} req *http.Request pathVar httprouter.Params expectMethod string expectPath string expectBody interface{} expectStatus int }{{ about: "function with no return", f: func(c *gc.C) interface{} { type testStruct struct { A string `httprequest:"a,path"` B map[string]int `httprequest:",body"` C int `httprequest:"c,form"` } return func(p httprequest.Params, s *testStruct) { c.Assert(s, jc.DeepEquals, &testStruct{ A: "A", B: map[string]int{"hello": 99}, C: 43, }) c.Assert(p.PathVar, jc.DeepEquals, httprouter.Params{{ Key: "a", Value: "A", }}) c.Assert(p.Request.Form, jc.DeepEquals, url.Values{ "c": {"43"}, }) c.Assert(p.PathPattern, gc.Equals, "") p.Response.Header().Set("Content-Type", "application/json") p.Response.Write([]byte("true")) } }, req: &http.Request{ Header: http.Header{"Content-Type": {"application/json"}}, Form: url.Values{ "c": {"43"}, }, Body: body(`{"hello": 99}`), }, pathVar: httprouter.Params{{ Key: "a", Value: "A", }}, expectBody: true, }, { about: "function with error return that returns no error", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(p httprequest.Params, s *testStruct) error { c.Assert(s, jc.DeepEquals, &testStruct{123}) c.Assert(p.PathPattern, gc.Equals, "") p.Response.Header().Set("Content-Type", "application/json") p.Response.Write([]byte("true")) return nil } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, expectBody: true, }, { about: "function with error return that returns an error", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(p httprequest.Params, s *testStruct) error { c.Assert(p.PathPattern, gc.Equals, "") c.Assert(s, jc.DeepEquals, &testStruct{123}) return errUnauth } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, expectBody: httprequest.RemoteError{ Message: errUnauth.Error(), Code: "unauthorized", }, expectStatus: http.StatusUnauthorized, }, { about: "function with value return that returns a value", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(p httprequest.Params, s *testStruct) (int, error) { c.Assert(p.PathPattern, gc.Equals, "") c.Assert(s, jc.DeepEquals, &testStruct{123}) return 1234, nil } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, expectBody: 1234, }, { about: "function with value return that returns an error", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(p httprequest.Params, s *testStruct) (int, error) { c.Assert(p.PathPattern, gc.Equals, "") c.Assert(s, jc.DeepEquals, &testStruct{123}) return 0, errUnauth } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, expectBody: httprequest.RemoteError{ Message: errUnauth.Error(), Code: "unauthorized", }, expectStatus: http.StatusUnauthorized, }, { about: "function with value return that writes to p.Response", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(p httprequest.Params, s *testStruct) (int, error) { c.Assert(p.PathPattern, gc.Equals, "") _, err := p.Response.Write(nil) c.Assert(err, gc.ErrorMatches, "inappropriate call to ResponseWriter.Write in JSON-returning handler") p.Response.WriteHeader(http.StatusTeapot) c.Assert(s, jc.DeepEquals, &testStruct{123}) return 1234, nil } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, expectBody: 1234, }, { about: "function with no Params and no return", f: func(c *gc.C) interface{} { type testStruct struct { A string `httprequest:"a,path"` B map[string]int `httprequest:",body"` C int `httprequest:"c,form"` } return func(s *testStruct) { c.Assert(s, jc.DeepEquals, &testStruct{ A: "A", B: map[string]int{"hello": 99}, C: 43, }) } }, req: &http.Request{ Header: http.Header{"Content-Type": {"application/json"}}, Form: url.Values{ "c": {"43"}, }, Body: body(`{"hello": 99}`), }, pathVar: httprouter.Params{{ Key: "a", Value: "A", }}, }, { about: "function with no Params with error return that returns no error", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(s *testStruct) error { c.Assert(s, jc.DeepEquals, &testStruct{123}) return nil } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, }, { about: "function with no Params with error return that returns an error", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(s *testStruct) error { c.Assert(s, jc.DeepEquals, &testStruct{123}) return errUnauth } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, expectBody: httprequest.RemoteError{ Message: errUnauth.Error(), Code: "unauthorized", }, expectStatus: http.StatusUnauthorized, }, { about: "function with no Params with value return that returns a value", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(s *testStruct) (int, error) { c.Assert(s, jc.DeepEquals, &testStruct{123}) return 1234, nil } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, expectBody: 1234, }, { about: "function with no Params with value return that returns an error", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(s *testStruct) (int, error) { c.Assert(s, jc.DeepEquals, &testStruct{123}) return 0, errUnauth } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "123", }}, expectBody: httprequest.RemoteError{ Message: errUnauth.Error(), Code: "unauthorized", }, expectStatus: http.StatusUnauthorized, }, { about: "error when unmarshaling", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(p httprequest.Params, s *testStruct) (int, error) { c.Errorf("function should not have been called") return 0, nil } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "not a number", }}, expectBody: httprequest.RemoteError{ Message: `cannot unmarshal parameters: cannot unmarshal into field A: cannot parse "not a number" into int: expected integer`, Code: "bad request", }, expectStatus: http.StatusBadRequest, }, { about: "error when unmarshaling, no Params", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(s *testStruct) (int, error) { c.Errorf("function should not have been called") return 0, nil } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "not a number", }}, expectBody: httprequest.RemoteError{ Message: `cannot unmarshal parameters: cannot unmarshal into field A: cannot parse "not a number" into int: expected integer`, Code: "bad request", }, expectStatus: http.StatusBadRequest, }, { about: "error when unmarshaling single value return", f: func(c *gc.C) interface{} { type testStruct struct { A int `httprequest:"a,path"` } return func(p httprequest.Params, s *testStruct) error { c.Errorf("function should not have been called") return nil } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "a", Value: "not a number", }}, expectBody: httprequest.RemoteError{ Message: `cannot unmarshal parameters: cannot unmarshal into field A: cannot parse "not a number" into int: expected integer`, Code: "bad request", }, expectStatus: http.StatusBadRequest, }, { about: "return type that can't be marshaled as JSON", f: func(c *gc.C) interface{} { return func(p httprequest.Params, s *struct{}) (chan int, error) { return make(chan int), nil } }, req: &http.Request{}, pathVar: httprouter.Params{}, expectBody: httprequest.RemoteError{ Message: "json: unsupported type: chan int", }, expectStatus: http.StatusInternalServerError, }, { about: "argument with route", f: func(c *gc.C) interface{} { type testStruct struct { httprequest.Route `httprequest:"GET /foo/:bar"` A string `httprequest:"bar,path"` } return func(p httprequest.Params, s *testStruct) { c.Check(s.A, gc.Equals, "val") c.Assert(p.PathPattern, gc.Equals, "/foo/:bar") } }, req: &http.Request{}, pathVar: httprouter.Params{{ Key: "bar", Value: "val", }}, expectMethod: "GET", expectPath: "/foo/:bar", }} func (*handlerSuite) TestHandle(c *gc.C) { for i, test := range handleTests { c.Logf("%d: %s", i, test.about) h := testServer.Handle(test.f(c)) c.Assert(h.Method, gc.Equals, test.expectMethod) c.Assert(h.Path, gc.Equals, test.expectPath) rec := httptest.NewRecorder() h.Handle(rec, test.req, test.pathVar) if test.expectStatus == 0 { test.expectStatus = http.StatusOK } httptesting.AssertJSONResponse(c, rec, test.expectStatus, test.expectBody) } } var handlePanicTests = []struct { f interface{} expect string }{{ f: 42, expect: "bad handler function: not a function", }, { f: func(httprequest.Params) {}, expect: "bad handler function: no argument parameter after Params argument", }, { f: func(httprequest.Params, *struct{}, struct{}) {}, expect: "bad handler function: has 3 parameters, need 1 or 2", }, { f: func(httprequest.Params, *struct{}) struct{} { return struct{}{} }, expect: "bad handler function: final result parameter is struct {}, need error", }, { f: func(http.ResponseWriter, httprequest.Params) (struct{}, error) { return struct{}{}, nil }, expect: "bad handler function: first argument is http.ResponseWriter, need httprequest.Params", }, { f: func(httprequest.Params, *struct{}) (struct{}, struct{}) { return struct{}{}, struct{}{} }, expect: "bad handler function: final result parameter is struct {}, need error", }, { f: func(*http.Request, *struct{}) {}, expect: `bad handler function: first argument is \*http.Request, need httprequest.Params`, }, { f: func(httprequest.Params, struct{}) {}, expect: "bad handler function: last argument cannot be used for Unmarshal: type is not pointer to struct", }, { f: func(httprequest.Params, *struct { A int `httprequest:"a,the-ether"` }) { }, expect: `bad handler function: last argument cannot be used for Unmarshal: bad tag "httprequest:\\"a,the-ether\\"" in field A: unknown tag flag "the-ether"`, }, { f: func(httprequest.Params, *struct{}) (a, b, c struct{}) { return }, expect: `bad handler function: has 3 result parameters, need 0, 1 or 2`, }, { f: func(*struct { httprequest.Route }) { }, expect: `bad handler function: last argument cannot be used for Unmarshal: bad route tag "": no httprequest tag`, }, { f: func(*struct { httprequest.Route `othertag:"foo"` }) { }, expect: `bad handler function: last argument cannot be used for Unmarshal: bad route tag "othertag:\\"foo\\"": no httprequest tag`, }, { f: func(*struct { httprequest.Route `httprequest:""` }) { }, expect: `bad handler function: last argument cannot be used for Unmarshal: bad route tag "httprequest:\\"\\"": no httprequest tag`, }, { f: func(*struct { httprequest.Route `httprequest:"GET /foo /bar"` }) { }, expect: `bad handler function: last argument cannot be used for Unmarshal: bad route tag "httprequest:\\"GET /foo /bar\\"": wrong field count`, }, { f: func(*struct { httprequest.Route `httprequest:"BAD /foo"` }) { }, expect: `bad handler function: last argument cannot be used for Unmarshal: bad route tag "httprequest:\\"BAD /foo\\"": invalid method`, }} func (*handlerSuite) TestHandlePanicsWithBadFunctions(c *gc.C) { for i, test := range handlePanicTests { c.Logf("%d: %s", i, test.expect) c.Check(func() { testServer.Handle(test.f) }, gc.PanicMatches, test.expect) } } var handlersTests = []struct { calledMethod string callParams httptesting.JSONCallParams expectPathPattern string }{{ calledMethod: "M1", callParams: httptesting.JSONCallParams{ URL: "/m1/99", }, expectPathPattern: "/m1/:p", }, { calledMethod: "M2", callParams: httptesting.JSONCallParams{ URL: "/m2/99", ExpectBody: 999, }, expectPathPattern: "/m2/:p", }, { calledMethod: "M3", callParams: httptesting.JSONCallParams{ URL: "/m3/99", ExpectBody: &httprequest.RemoteError{ Message: "m3 error", }, ExpectStatus: http.StatusInternalServerError, }, expectPathPattern: "/m3/:p", }, { calledMethod: "M3Post", callParams: httptesting.JSONCallParams{ Method: "POST", URL: "/m3/99", JSONBody: make(map[string]interface{}), }, expectPathPattern: "/m3/:p", }} func (*handlerSuite) TestHandlers(c *gc.C) { handleVal := testHandlers{ c: c, } f := func(p httprequest.Params) (*testHandlers, context.Context, error) { handleVal.p = p return &handleVal, p.Context, nil } handlers := testServer.Handlers(f) handlers1 := make([]httprequest.Handler, len(handlers)) copy(handlers1, handlers) for i := range handlers1 { handlers1[i].Handle = nil } expectHandlers := []httprequest.Handler{{ Method: "GET", Path: "/m1/:p", }, { Method: "GET", Path: "/m2/:p", }, { Method: "GET", Path: "/m3/:p", }, { Method: "POST", Path: "/m3/:p", }} c.Assert(handlers1, jc.DeepEquals, expectHandlers) c.Assert(handlersTests, gc.HasLen, len(expectHandlers)) router := httprouter.New() for _, h := range handlers { c.Logf("adding %s %s", h.Method, h.Path) router.Handle(h.Method, h.Path, h.Handle) } for i, test := range handlersTests { c.Logf("test %d: %s", i, test.calledMethod) handleVal = testHandlers{ c: c, } test.callParams.Handler = router httptesting.AssertJSONCall(c, test.callParams) c.Assert(handleVal.calledMethod, gc.Equals, test.calledMethod) c.Assert(handleVal.p.PathPattern, gc.Equals, test.expectPathPattern) } } type testHandlers struct { calledMethod string calledContext context.Context c *gc.C p httprequest.Params } func (h *testHandlers) M1(p httprequest.Params, arg *struct { httprequest.Route `httprequest:"GET /m1/:p"` P int `httprequest:"p,path"` }) { h.calledMethod = "M1" h.calledContext = p.Context h.c.Check(arg.P, gc.Equals, 99) h.c.Check(p.Response, gc.Equals, h.p.Response) h.c.Check(p.Request, gc.Equals, h.p.Request) h.c.Check(p.PathVar, gc.DeepEquals, h.p.PathVar) h.c.Check(p.PathPattern, gc.Equals, "/m1/:p") h.c.Check(p.Context, gc.NotNil) } type m2Request struct { httprequest.Route `httprequest:"GET /m2/:p"` P int `httprequest:"p,path"` } func (h *testHandlers) M2(arg *m2Request) (int, error) { h.calledMethod = "M2" h.c.Check(arg.P, gc.Equals, 99) return 999, nil } func (h *testHandlers) unexported() { } func (h *testHandlers) M3(arg *struct { httprequest.Route `httprequest:"GET /m3/:p"` P int `httprequest:"p,path"` }) (int, error) { h.calledMethod = "M3" h.c.Check(arg.P, gc.Equals, 99) return 0, errgo.New("m3 error") } func (h *testHandlers) M3Post(arg *struct { httprequest.Route `httprequest:"POST /m3/:p"` P int `httprequest:"p,path"` }) { h.calledMethod = "M3Post" h.c.Check(arg.P, gc.Equals, 99) } func (*handlerSuite) TestHandlersRootFuncWithRequestArg(c *gc.C) { handleVal := testHandlers{ c: c, } var gotArg interface{} f := func(p httprequest.Params, arg interface{}) (*testHandlers, context.Context, error) { gotArg = arg return &handleVal, p.Context, nil } router := httprouter.New() for _, h := range testServer.Handlers(f) { router.Handle(h.Method, h.Path, h.Handle) } httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: router, URL: "/m2/99", ExpectBody: 999, }) c.Assert(gotArg, jc.DeepEquals, &m2Request{ P: 99, }) } func (*handlerSuite) TestHandlersRootFuncWithIncompatibleRequestArg(c *gc.C) { handleVal := testHandlers{ c: c, } var gotArg interface{} f := func(p httprequest.Params, arg interface { Foo() }) (*testHandlers, context.Context, error) { gotArg = arg return &handleVal, p.Context, nil } c.Assert(func() { testServer.Handlers(f) }, gc.PanicMatches, `bad type for method M1: argument of type \*struct {.*} does not implement interface required by root handler interface \{ Foo\(\) \}`) } func (*handlerSuite) TestHandlersRootFuncWithNonEmptyInterfaceRequestArg(c *gc.C) { type tester interface { Test() string } var argResult string f := func(p httprequest.Params, arg tester) (*handlersWithRequestMethod, context.Context, error) { argResult = arg.Test() return &handlersWithRequestMethod{}, p.Context, nil } router := httprouter.New() for _, h := range testServer.Handlers(f) { router.Handle(h.Method, h.Path, h.Handle) } httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: router, URL: "/x1/something", ExpectBody: "something", }) c.Assert(argResult, jc.DeepEquals, "test something") } var badHandlersFuncTests = []struct { about string f interface{} expectPanic string }{{ about: "not a function", f: 123, expectPanic: "bad handler function: expected function, got int", }, { about: "nil function", f: (func())(nil), expectPanic: "bad handler function: function is nil", }, { about: "no arguments", f: func() {}, expectPanic: "bad handler function: got 0 arguments, want 1 or 2", }, { about: "more than two argument", f: func(http.ResponseWriter, *http.Request, int) {}, expectPanic: "bad handler function: got 3 arguments, want 1 or 2", }, { about: "no return values", f: func(httprequest.Params) {}, expectPanic: `bad handler function: function returns 0 values, want \(<T>, context.Context, error\)`, }, { about: "only one return value", f: func(httprequest.Params) string { return "" }, expectPanic: `bad handler function: function returns 1 values, want \(<T>, context.Context, error\)`, }, { about: "only two return values", f: func(httprequest.Params) (_ arithHandler, _ error) { return }, expectPanic: `bad handler function: function returns 2 values, want \(<T>, context.Context, error\)`, }, { about: "too many return values", f: func(httprequest.Params) (_ string, _ error, _ error, _ error) { return }, expectPanic: `bad handler function: function returns 4 values, want \(<T>, context.Context, error\)`, }, { about: "invalid first argument", f: func(string) (_ string, _ context.Context, _ error) { return }, expectPanic: `bad handler function: invalid first argument, want httprequest.Params, got string`, }, { about: "second argument not an interface", f: func(httprequest.Params, *http.Request) (_ string, _ context.Context, _ error) { return }, expectPanic: `bad handler function: invalid second argument, want interface type, got \*http.Request`, }, { about: "non-error return", f: func(httprequest.Params) (_ string, _ context.Context, _ string) { return }, expectPanic: `bad handler function: invalid third return parameter, want error, got string`, }, { about: "non-context return", f: func(httprequest.Params) (_ arithHandler, _ string, _ error) { return }, expectPanic: `bad handler function: second return parameter of type string does not implement context.Context`, }, { about: "no methods on return type", f: func(httprequest.Params) (_ string, _ context.Context, _ error) { return }, expectPanic: `no exported methods defined on string`, }, { about: "method with invalid parameter count", f: func(httprequest.Params) (_ badHandlersType1, _ context.Context, _ error) { return }, expectPanic: `bad type for method M: has 3 parameters, need 1 or 2`, }, { about: "method with invalid route", f: func(httprequest.Params) (_ badHandlersType2, _ context.Context, _ error) { return }, expectPanic: `method M does not specify route method and path`, }, { about: "bad type for close method", f: func(httprequest.Params) (_ badHandlersType3, _ context.Context, _ error) { return }, expectPanic: `bad type for Close method \(got func\(httprequest_test\.badHandlersType3\) want func\(httprequest_test.badHandlersType3\) error`, }} type badHandlersType1 struct{} func (badHandlersType1) M(a, b, c int) { } type badHandlersType2 struct{} func (badHandlersType2) M(*struct { P int `httprequest:",path"` }) { } type badHandlersType3 struct{} func (badHandlersType3) M(arg *struct { httprequest.Route `httprequest:"GET /m1/:P"` P int `httprequest:",path"` }) { } func (badHandlersType3) Close() { } func (*handlerSuite) TestBadHandlersFunc(c *gc.C) { for i, test := range badHandlersFuncTests { c.Logf("test %d: %s", i, test.about) c.Check(func() { testServer.Handlers(test.f) }, gc.PanicMatches, test.expectPanic) } } func (*handlerSuite) TestHandlersFuncReturningError(c *gc.C) { handlers := testServer.Handlers(func(p httprequest.Params) (*testHandlers, context.Context, error) { return nil, p.Context, errgo.WithCausef(errgo.New("failure"), errUnauth, "something") }) router := httprouter.New() for _, h := range handlers { router.Handle(h.Method, h.Path, h.Handle) } httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ URL: "/m1/99", Handler: router, ExpectStatus: http.StatusUnauthorized, ExpectBody: &httprequest.RemoteError{ Message: "something: failure", Code: "unauthorized", }, }) } func (*handlerSuite) TestHandlersFuncReturningCustomContext(c *gc.C) { handleVal := testHandlers{ c: c, } handlers := testServer.Handlers(func(p httprequest.Params) (*testHandlers, context.Context, error) { handleVal.p = p ctx := context.WithValue(p.Context, "some key", "some value") return &handleVal, ctx, nil }) router := httprouter.New() for _, h := range handlers { router.Handle(h.Method, h.Path, h.Handle) } httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ URL: "/m1/99", Handler: router, }) c.Assert(handleVal.calledContext, gc.NotNil) c.Assert(handleVal.calledContext.Value("some key"), gc.Equals, "some value") } type closeHandlersType struct { p int closed bool } func (h *closeHandlersType) M(arg *struct { httprequest.Route `httprequest:"GET /m1/:P"` P int `httprequest:",path"` }) { h.p = arg.P } func (h *closeHandlersType) Close() error { h.closed = true return nil } func (*handlerSuite) TestHandlersWithTypeThatImplementsIOCloser(c *gc.C) { var v closeHandlersType handlers := testServer.Handlers(func(p httprequest.Params) (*closeHandlersType, context.Context, error) { return &v, p.Context, nil }) router := httprouter.New() for _, h := range handlers { router.Handle(h.Method, h.Path, h.Handle) } httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ URL: "/m1/99", Handler: router, }) c.Assert(v.closed, gc.Equals, true) c.Assert(v.p, gc.Equals, 99) } func (*handlerSuite) TestBadForm(c *gc.C) { h := testServer.Handle(func(p httprequest.Params, _ *struct{}) { c.Fatalf("shouldn't be called") }) testBadForm(c, h.Handle) } func (*handlerSuite) TestBadFormNoParams(c *gc.C) { h := testServer.Handle(func(_ *struct{}) { c.Fatalf("shouldn't be called") }) testBadForm(c, h.Handle) } func testBadForm(c *gc.C, h httprouter.Handle) { rec := httptest.NewRecorder() req := &http.Request{ Method: "POST", Header: http.Header{ "Content-Type": {"application/x-www-form-urlencoded"}, }, Body: body("%6"), } h(rec, req, httprouter.Params{}) httptesting.AssertJSONResponse(c, rec, http.StatusBadRequest, httprequest.RemoteError{ Message: `cannot parse HTTP request form: invalid URL escape "%6"`, Code: "bad request", }) } func (*handlerSuite) TestToHTTP(c *gc.C) { var h http.Handler h = httprequest.ToHTTP(testServer.Handle(func(p httprequest.Params, s *struct{}) { c.Assert(p.PathVar, gc.IsNil) p.Response.WriteHeader(http.StatusOK) }).Handle) rec := httptest.NewRecorder() req := &http.Request{ Body: body(""), } h.ServeHTTP(rec, req) c.Assert(rec.Code, gc.Equals, http.StatusOK) } func (*handlerSuite) TestWriteJSON(c *gc.C) { rec := httptest.NewRecorder() type Number struct { N int } err := httprequest.WriteJSON(rec, http.StatusTeapot, Number{1234}) c.Assert(err, gc.IsNil) c.Assert(rec.Code, gc.Equals, http.StatusTeapot) c.Assert(rec.Body.String(), gc.Equals, `{"N":1234}`) c.Assert(rec.Header().Get("content-type"), gc.Equals, "application/json") } var ( errUnauth = errors.New("unauth") errBadReq = errors.New("bad request") errOther = errors.New("other") errCustomHeaders = errors.New("custom headers") errUnmarshalableError = errors.New("unmarshalable error") errNil = errors.New("nil result") ) type HeaderNumber struct { N int } func (HeaderNumber) SetHeader(h http.Header) { h.Add("some-custom-header", "yes") } func (*handlerSuite) TestSetHeader(c *gc.C) { rec := httptest.NewRecorder() err := httprequest.WriteJSON(rec, http.StatusTeapot, HeaderNumber{1234}) c.Assert(err, gc.IsNil) c.Assert(rec.Code, gc.Equals, http.StatusTeapot) c.Assert(rec.Body.String(), gc.Equals, `{"N":1234}`) c.Assert(rec.Header().Get("content-type"), gc.Equals, "application/json") c.Assert(rec.Header().Get("some-custom-header"), gc.Equals, "yes") } var testServer = httprequest.Server{ ErrorMapper: testErrorMapper, } func testErrorMapper(_ context.Context, err error) (int, interface{}) { resp := &httprequest.RemoteError{ Message: err.Error(), } status := http.StatusInternalServerError switch errgo.Cause(err) { case errUnauth: status = http.StatusUnauthorized resp.Code = "unauthorized" case errBadReq, httprequest.ErrUnmarshal: status = http.StatusBadRequest resp.Code = "bad request" case errCustomHeaders: return http.StatusNotAcceptable, httprequest.CustomHeader{ Body: resp, SetHeaderFunc: func(h http.Header) { h.Set("Acceptability", "not at all") }, } case errUnmarshalableError: return http.StatusTeapot, make(chan int) case errNil: return status, nil } return status, &resp } var writeErrorTests = []struct { err error expectStatus int expectResp *httprequest.RemoteError expectHeader http.Header }{{ err: errUnauth, expectStatus: http.StatusUnauthorized, expectResp: &httprequest.RemoteError{ Message: errUnauth.Error(), Code: "unauthorized", }, }, { err: errBadReq, expectStatus: http.StatusBadRequest, expectResp: &httprequest.RemoteError{ Message: errBadReq.Error(), Code: "bad request", }, }, { err: errOther, expectStatus: http.StatusInternalServerError, expectResp: &httprequest.RemoteError{ Message: errOther.Error(), }, }, { err: errNil, expectStatus: http.StatusInternalServerError, }, { err: errCustomHeaders, expectStatus: http.StatusNotAcceptable, expectResp: &httprequest.RemoteError{ Message: errCustomHeaders.Error(), }, expectHeader: http.Header{ "Acceptability": {"not at all"}, }, }, { err: errUnmarshalableError, expectStatus: http.StatusInternalServerError, expectResp: &httprequest.RemoteError{ Message: `cannot marshal error response "unmarshalable error": json: unsupported type: chan int`, }, }} func (s *handlerSuite) TestWriteError(c *gc.C) { for i, test := range writeErrorTests { c.Logf("%d: %s", i, test.err) rec := httptest.NewRecorder() testServer.WriteError(context.TODO(), rec, test.err) resp := parseErrorResponse(c, rec.Body.Bytes()) c.Assert(resp, gc.DeepEquals, test.expectResp) c.Assert(rec.Code, gc.Equals, test.expectStatus) for name, vals := range test.expectHeader { c.Assert(rec.HeaderMap[name], jc.DeepEquals, vals) } } } func parseErrorResponse(c *gc.C, body []byte) *httprequest.RemoteError { var errResp *httprequest.RemoteError err := json.Unmarshal(body, &errResp) c.Assert(err, gc.IsNil) return errResp } func (s *handlerSuite) TestHandleErrors(c *gc.C) { req := new(http.Request) params := httprouter.Params{} // Test when handler returns an error. handler := testServer.HandleErrors(func(p httprequest.Params) error { assertRequestEquals(c, p.Request, req) c.Assert(p.PathVar, jc.DeepEquals, params) c.Assert(p.PathPattern, gc.Equals, "") ctx := p.Context c.Assert(ctx, gc.Not(gc.IsNil)) return errUnauth }) rec := httptest.NewRecorder() handler(rec, req, params) c.Assert(rec.Code, gc.Equals, http.StatusUnauthorized) resp := parseErrorResponse(c, rec.Body.Bytes()) c.Assert(resp, gc.DeepEquals, &httprequest.RemoteError{ Message: errUnauth.Error(), Code: "unauthorized", }) // Test when handler returns nil. handler = testServer.HandleErrors(func(p httprequest.Params) error { assertRequestEquals(c, p.Request, req) c.Assert(p.PathVar, jc.DeepEquals, params) c.Assert(p.PathPattern, gc.Equals, "") ctx := p.Context c.Assert(ctx, gc.Not(gc.IsNil)) p.Response.WriteHeader(http.StatusCreated) p.Response.Write([]byte("something")) return nil }) rec = httptest.NewRecorder() handler(rec, req, params) c.Assert(rec.Code, gc.Equals, http.StatusCreated) c.Assert(rec.Body.String(), gc.Equals, "something") } var handleErrorsWithErrorAfterWriteHeaderTests = []struct { about string causeWriteHeader func(w http.ResponseWriter) }{{ about: "write", causeWriteHeader: func(w http.ResponseWriter) { w.Write([]byte("")) }, }, { about: "write header", causeWriteHeader: func(w http.ResponseWriter) { w.WriteHeader(http.StatusOK) }, }, { about: "flush", causeWriteHeader: func(w http.ResponseWriter) { w.(http.Flusher).Flush() }, }} func (s *handlerSuite) TestHandleErrorsWithErrorAfterWriteHeader(c *gc.C) { for i, test := range handleErrorsWithErrorAfterWriteHeaderTests { c.Logf("test %d: %s", i, test.about) handler := testServer.HandleErrors(func(p httprequest.Params) error { test.causeWriteHeader(p.Response) return errgo.New("unexpected") }) rec := httptest.NewRecorder() handler(rec, new(http.Request), nil) c.Assert(rec.Code, gc.Equals, http.StatusOK) c.Assert(rec.Body.String(), gc.Equals, "") } } func (s *handlerSuite) TestHandleJSON(c *gc.C) { req := new(http.Request) params := httprouter.Params{} // Test when handler returns an error. handler := testServer.HandleJSON(func(p httprequest.Params) (interface{}, error) { assertRequestEquals(c, p.Request, req) c.Assert(p.PathVar, jc.DeepEquals, params) c.Assert(p.PathPattern, gc.Equals, "") return nil, errUnauth }) rec := httptest.NewRecorder() handler(rec, new(http.Request), params) resp := parseErrorResponse(c, rec.Body.Bytes()) c.Assert(resp, gc.DeepEquals, &httprequest.RemoteError{ Message: errUnauth.Error(), Code: "unauthorized", }) c.Assert(rec.Code, gc.Equals, http.StatusUnauthorized) // Test when handler returns a body. handler = testServer.HandleJSON(func(p httprequest.Params) (interface{}, error) { assertRequestEquals(c, p.Request, req) c.Assert(p.PathVar, jc.DeepEquals, params) c.Assert(p.PathPattern, gc.Equals, "") p.Response.Header().Set("Some-Header", "value") return "something", nil }) rec = httptest.NewRecorder() handler(rec, req, params) c.Assert(rec.Code, gc.Equals, http.StatusOK) c.Assert(rec.Body.String(), gc.Equals, `"something"`) c.Assert(rec.Header().Get("Some-Header"), gc.Equals, "value") } func assertRequestEquals(c *gc.C, req1, req2 *http.Request) { c.Assert(req1.Method, gc.Equals, req2.Method) c.Assert(req1.URL, jc.DeepEquals, req2.URL) c.Assert(req1.Proto, gc.Equals, req2.Proto) c.Assert(req1.ProtoMajor, gc.Equals, req2.ProtoMajor) c.Assert(req1.ProtoMinor, gc.Equals, req2.ProtoMinor) c.Assert(req1.Header, jc.DeepEquals, req2.Header) c.Assert(req1.Body, gc.Equals, req2.Body) c.Assert(req1.ContentLength, gc.Equals, req2.ContentLength) c.Assert(req1.TransferEncoding, jc.DeepEquals, req2.TransferEncoding) c.Assert(req1.Close, gc.Equals, req2.Close) c.Assert(req1.Host, gc.Equals, req2.Host) c.Assert(req1.Form, jc.DeepEquals, req2.Form) c.Assert(req1.PostForm, jc.DeepEquals, req2.PostForm) c.Assert(req1.MultipartForm, jc.DeepEquals, req2.MultipartForm) c.Assert(req1.Trailer, jc.DeepEquals, req2.Trailer) c.Assert(req1.RemoteAddr, gc.Equals, req2.RemoteAddr) c.Assert(req1.RequestURI, gc.Equals, req2.RequestURI) c.Assert(req1.TLS, gc.Equals, req2.TLS) c.Assert(req1.Cancel, gc.Equals, req2.Cancel) } type handlersWithRequestMethod struct{} type x1Request struct { httprequest.Route `httprequest:"GET /x1/:p"` P string `httprequest:"p,path"` } func (r *x1Request) Test() string { return "test " + r.P } func (h *handlersWithRequestMethod) X1(arg *x1Request) (string, error) { return arg.P, nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/handler.go������������������������������������������0000644�0610621�0607500�00000050367�13172163410�024603� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest import ( "encoding/json" "fmt" "io" "net/http" "reflect" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" "gopkg.in/errgo.v1" ) // Server represents the server side of an HTTP servers, and can be // used to create HTTP handlers although it is not an HTTP handler // itself. type Server struct { // ErrorMapper holds a function that can convert a Go error // into a form that can be returned as a JSON body from an HTTP request. // // The httpStatus value reports the desired HTTP status. // // If the returned errorBody implements HeaderSetter, then // that method will be called to add custom headers to the request. ErrorMapper func(ctxt context.Context, err error) (httpStatus int, errorBody interface{}) } // Handler defines a HTTP handler that will handle the // given HTTP method at the given httprouter path type Handler struct { Method string Path string Handle httprouter.Handle } // handlerFunc represents a function that can handle an HTTP request. type handlerFunc struct { // unmarshal unmarshals the request parameters into // the argument value required by the method. unmarshal func(p Params) (reflect.Value, error) // call invokes the request on the given function value with the // given argument value (as returned by unmarshal). call func(fv, argv reflect.Value, p Params) // method holds the HTTP method the function will be // registered for. method string // pathPattern holds the path pattern the function will // be registered for. pathPattern string } var ( paramsType = reflect.TypeOf(Params{}) errorType = reflect.TypeOf((*error)(nil)).Elem() contextType = reflect.TypeOf((*context.Context)(nil)).Elem() httpResponseWriterType = reflect.TypeOf((*http.ResponseWriter)(nil)).Elem() httpHeaderType = reflect.TypeOf(http.Header(nil)) httpRequestType = reflect.TypeOf((*http.Request)(nil)) ioCloserType = reflect.TypeOf((*io.Closer)(nil)).Elem() ) // AddHandlers adds all the handlers in the given slice to r. func AddHandlers(r *httprouter.Router, hs []Handler) { for _, h := range hs { r.Handle(h.Method, h.Path, h.Handle) } } // Handle converts a function into a Handler. The argument f // must be a function of one of the following six forms, where ArgT // must be a struct type acceptable to Unmarshal and ResultT is a type // that can be marshaled as JSON: // // func(p Params, arg *ArgT) // func(p Params, arg *ArgT) error // func(p Params, arg *ArgT) (ResultT, error) // // func(arg *ArgT) // func(arg *ArgT) error // func(arg *ArgT) (ResultT, error) // // When processing a call to the returned handler, the provided // parameters are unmarshaled into a new ArgT value using Unmarshal, // then f is called with this value. If the unmarshaling fails, f will // not be called and the unmarshal error will be written as a JSON // response. // // As an additional special case to the rules defined in Unmarshal, the // tag on an anonymous field of type Route specifies the method and path // to use in the HTTP request. It should hold two space-separated // fields; the first specifies the HTTP method, the second the URL path // to use for the request. If this is given, the returned handler will // hold that method and path, otherwise they will be empty. // // If an error is returned from f, it is passed through the error mapper // before writing as a JSON response. // // In the third form, when no error is returned, the result is written // as a JSON response with status http.StatusOK. Also in this case, any // calls to Params.Response.Write or Params.Response.WriteHeader will be // ignored, as the response code and data should be defined entirely by // the returned result and error. // // Handle will panic if the provided function is not in one of the above // forms. func (srv *Server) Handle(f interface{}) Handler { fv := reflect.ValueOf(f) hf, err := srv.handlerFunc(fv.Type(), nil) if err != nil { panic(errgo.Notef(err, "bad handler function")) } return Handler{ Method: hf.method, Path: hf.pathPattern, Handle: func(w http.ResponseWriter, req *http.Request, p httprouter.Params) { ctx, cancel := contextFromRequest(req) defer cancel() p1 := Params{ Response: w, Request: req, PathVar: p, PathPattern: hf.pathPattern, Context: ctx, } argv, err := hf.unmarshal(p1) if err != nil { srv.WriteError(ctx, w, err) return } hf.call(fv, argv, p1) }, } } // Handlers returns a list of handlers that will be handled by the value // returned by the given argument, which must be a function in one of the // following forms: // // func(p httprequest.Params) (T, context.Context, error) // func(p httprequest.Params, handlerArg I) (T, context.Context, error) // // for some type T and some interface type I. Each exported method defined on T defines a handler, // and should be in one of the forms accepted by ErrorMapper.Handle // with the additional constraint that the argument to each // of the handlers must be compatible with the type I when the // second form is used above. // // The returned context will be used as the value of Params.Context // when Params is passed to any method. It will also be used // when writing an error if the function returns an error. // Note that it is OK to use both the standard library context.Context // or golang.org/x/net/context.Context in the context return value. // // Handlers will panic if f is not of the required form, no methods are // defined on T or any method defined on T is not suitable for Handle. // // When any of the returned handlers is invoked, f will be called and // then the appropriate method will be called on the value it returns. // If specified, the handlerArg parameter to f will hold the ArgT argument that // will be passed to the handler method. // // If T implements io.Closer, its Close method will be called // after the request is completed. func (srv Server) Handlers(f interface{}) []Handler { rootv := reflect.ValueOf(f) wt, argInterfacet, err := checkHandlersWrapperFunc(rootv) if err != nil { panic(errgo.Notef(err, "bad handler function")) } hasClose := wt.Implements(ioCloserType) hs := make([]Handler, 0, wt.NumMethod()) for i := 0; i < wt.NumMethod(); i++ { i := i m := wt.Method(i) if m.PkgPath != "" { continue } if m.Name == "Close" { if !hasClose { panic(errgo.Newf("bad type for Close method (got %v want func(%v) error", m.Type, wt)) } continue } h, err := srv.methodHandler(m, rootv, argInterfacet, hasClose) if err != nil { panic(err) } hs = append(hs, h) } if len(hs) == 0 { panic(errgo.Newf("no exported methods defined on %s", wt)) } return hs } func (srv *Server) methodHandler(m reflect.Method, rootv reflect.Value, argInterfacet reflect.Type, hasClose bool) (Handler, error) { // The type in the Method struct includes the receiver type, // which we don't want to look at (and we won't see when // we get the method from the actual value at dispatch time), // so we hide it. mt := withoutReceiver(m.Type) hf, err := srv.handlerFunc(mt, argInterfacet) if err != nil { return Handler{}, errgo.Notef(err, "bad type for method %s", m.Name) } if hf.method == "" || hf.pathPattern == "" { return Handler{}, errgo.Notef(err, "method %s does not specify route method and path", m.Name) } handler := func(w http.ResponseWriter, req *http.Request, p httprouter.Params) { ctx, cancel := contextFromRequest(req) defer cancel() p1 := Params{ Response: w, Request: req, PathVar: p, PathPattern: hf.pathPattern, Context: ctx, } inv, err := hf.unmarshal(p1) if err != nil { srv.WriteError(ctx, w, err) return } var outv []reflect.Value if argInterfacet != nil { outv = rootv.Call([]reflect.Value{ reflect.ValueOf(p1), // Pass the value to the root function so it can do wrappy things with it. // Note that because of the checks we've applied earlier, we can be // sure that the value will implement the interface type of this argument. inv, }) } else { outv = rootv.Call([]reflect.Value{ reflect.ValueOf(p1), }) } tv, ctxv, errv := outv[0], outv[1], outv[2] // Get the context value robustly even if the // handler stupidly decides to return nil, and fall // back to the original context if it does. ctx1, _ := ctxv.Interface().(context.Context) if ctx1 != nil { ctx = ctx1 } if !errv.IsNil() { srv.WriteError(ctx, w, errv.Interface().(error)) return } if hasClose { defer tv.Interface().(io.Closer).Close() } hf.call(tv.Method(m.Index), inv, Params{ Response: w, Request: req, PathVar: p, PathPattern: hf.pathPattern, Context: ctx, }) } return Handler{ Method: hf.method, Path: hf.pathPattern, Handle: handler, }, nil } func checkHandlersWrapperFunc(fv reflect.Value) (returnt, argInterfacet reflect.Type, err error) { ft := fv.Type() if ft.Kind() != reflect.Func { return nil, nil, errgo.Newf("expected function, got %v", ft) } if fv.IsNil() { return nil, nil, errgo.Newf("function is nil") } if n := ft.NumIn(); n != 1 && n != 2 { return nil, nil, errgo.Newf("got %d arguments, want 1 or 2", n) } if n := ft.NumOut(); n != 3 { return nil, nil, errgo.Newf("function returns %d values, want (<T>, context.Context, error)", n) } if t := ft.In(0); t != paramsType { return nil, nil, errgo.Newf("invalid first argument, want httprequest.Params, got %v", t) } if ft.NumIn() > 1 { if t := ft.In(1); t.Kind() != reflect.Interface { return nil, nil, errgo.Newf("invalid second argument, want interface type, got %v", t) } argInterfacet = ft.In(1) } if t := ft.Out(1); !t.Implements(contextType) { return nil, nil, errgo.Newf("second return parameter of type %v does not implement context.Context", t) } if t := ft.Out(2); t != errorType { return nil, nil, errgo.Newf("invalid third return parameter, want error, got %v", t) } return ft.Out(0), argInterfacet, nil } func checkHandleType(t, argInterfacet reflect.Type) (*requestType, error) { if t.Kind() != reflect.Func { return nil, errgo.New("not a function") } if n := t.NumIn(); n != 1 && n != 2 { return nil, errgo.Newf("has %d parameters, need 1 or 2", t.NumIn()) } if t.NumOut() > 2 { return nil, errgo.Newf("has %d result parameters, need 0, 1 or 2", t.NumOut()) } if t.NumIn() == 2 { if t.In(0) != paramsType { return nil, errgo.Newf("first argument is %v, need httprequest.Params", t.In(0)) } } else { if t.In(0) == paramsType { return nil, errgo.Newf("no argument parameter after Params argument") } } argt := t.In(t.NumIn() - 1) pt, err := getRequestType(argt) if err != nil { return nil, errgo.Notef(err, "last argument cannot be used for Unmarshal") } if argInterfacet != nil && !argt.Implements(argInterfacet) { return nil, errgo.Notef(err, "argument of type %v does not implement interface required by root handler %v", argt, argInterfacet) } if t.NumOut() > 0 { // func(p Params, arg *ArgT) error // func(p Params, arg *ArgT) (ResultT, error) if et := t.Out(t.NumOut() - 1); et != errorType { return nil, errgo.Newf("final result parameter is %s, need error", et) } } return pt, nil } // handlerFunc returns a function that will call a function of the given type, // unmarshaling request parameters and marshaling the response as // appropriate. func (srv *Server) handlerFunc(ft, argInterfacet reflect.Type) (handlerFunc, error) { rt, err := checkHandleType(ft, argInterfacet) if err != nil { return handlerFunc{}, errgo.Mask(err) } return handlerFunc{ unmarshal: handlerUnmarshaler(ft, rt), call: srv.handlerCaller(ft, rt), method: rt.method, pathPattern: rt.path, }, nil } func handlerUnmarshaler( ft reflect.Type, rt *requestType, ) func(p Params) (reflect.Value, error) { argStructType := ft.In(ft.NumIn() - 1).Elem() return func(p Params) (reflect.Value, error) { if err := p.Request.ParseForm(); err != nil { return reflect.Value{}, errgo.WithCausef(err, ErrUnmarshal, "cannot parse HTTP request form") } argv := reflect.New(argStructType) if err := unmarshal(p, argv, rt); err != nil { return reflect.Value{}, errgo.NoteMask(err, "cannot unmarshal parameters", errgo.Is(ErrUnmarshal)) } return argv, nil } } func (srv *Server) handlerCaller( ft reflect.Type, rt *requestType, ) func(fv, argv reflect.Value, p Params) { returnJSON := ft.NumOut() > 1 needsParams := ft.In(0) == paramsType respond := srv.handlerResponder(ft) return func(fv, argv reflect.Value, p Params) { var rv []reflect.Value if needsParams { p := p if returnJSON { p.Response = headerOnlyResponseWriter{p.Response.Header()} } rv = fv.Call([]reflect.Value{ reflect.ValueOf(p), argv, }) } else { rv = fv.Call([]reflect.Value{ argv, }) } respond(p, rv) } } // handlerResponder handles the marshaling of the result values from the call to a function // of type ft. The returned function accepts the values returned by the handler. func (srv *Server) handlerResponder(ft reflect.Type) func(p Params, outv []reflect.Value) { switch ft.NumOut() { case 0: // func(...) return func(Params, []reflect.Value) {} case 1: // func(...) error return func(p Params, outv []reflect.Value) { if err := outv[0].Interface(); err != nil { srv.WriteError(p.Context, p.Response, err.(error)) } } case 2: // func(...) (ResultT, error) return func(p Params, outv []reflect.Value) { if err := outv[1].Interface(); err != nil { srv.WriteError(p.Context, p.Response, err.(error)) return } if err := WriteJSON(p.Response, http.StatusOK, outv[0].Interface()); err != nil { srv.WriteError(p.Context, p.Response, err) } } default: panic("unreachable") } } // ToHTTP converts an httprouter.Handle into an http.Handler. // It will pass no path variables to h. func ToHTTP(h httprouter.Handle) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { h(w, req, nil) }) } // JSONHandler is like httprouter.Handle except that it returns a // body (to be converted to JSON) and an error. // The Header parameter can be used to set // custom headers on the response. type JSONHandler func(Params) (interface{}, error) // ErrorHandler is like httprouter.Handle except it returns an error // which may be returned as the error body of the response. // An ErrorHandler function should not itself write to the ResponseWriter // if it returns an error. type ErrorHandler func(Params) error // HandleJSON returns a handler that writes the return value of handle // as a JSON response. If handle returns an error, it is passed through // the error mapper. // // Note that the Params argument passed to handle will not // have its PathPattern set as that information is not available. func (srv *Server) HandleJSON(handle JSONHandler) httprouter.Handle { return func(w http.ResponseWriter, req *http.Request, p httprouter.Params) { ctx, cancel := contextFromRequest(req) defer cancel() val, err := handle(Params{ Response: headerOnlyResponseWriter{w.Header()}, Request: req, PathVar: p, Context: ctx, }) if err == nil { if err = WriteJSON(w, http.StatusOK, val); err == nil { return } } srv.WriteError(ctx, w, err) } } // HandleErrors returns a handler that passes any non-nil error returned // by handle through the error mapper and writes it as a JSON response. // // Note that the Params argument passed to handle will not // have its PathPattern set as that information is not available. func (srv *Server) HandleErrors(handle ErrorHandler) httprouter.Handle { return func(w http.ResponseWriter, req *http.Request, p httprouter.Params) { w1 := responseWriter{ ResponseWriter: w, } ctx, cancel := contextFromRequest(req) defer cancel() if err := handle(Params{ Response: &w1, Request: req, PathVar: p, Context: ctx, }); err != nil { if w1.headerWritten { // The header has already been written, // so we can't set the appropriate error // response code and there's a danger // that we may be corrupting the // response by appending a JSON error // message to it. // TODO log an error in this case. return } srv.WriteError(ctx, w, err) } } } // WriteError writes an error to a ResponseWriter // and sets the HTTP status code. // // It uses WriteJSON to write the error body returned from // the ErrorMapper so it is possible to add custom // headers to the HTTP error response by implementing // HeaderSetter. func (srv *Server) WriteError(ctx context.Context, w http.ResponseWriter, err error) { status, resp := srv.ErrorMapper(ctx, err) err1 := WriteJSON(w, status, resp) if err1 == nil { return } // TODO log an error ? // JSON-marshaling the original error failed, so try to send that // error instead; if that fails, give up and go home. status1, resp1 := srv.ErrorMapper(ctx, errgo.Notef(err1, "cannot marshal error response %q", err)) err2 := WriteJSON(w, status1, resp1) if err2 == nil { return } w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("really cannot marshal error response %q: %v", err, err1))) } // WriteJSON writes the given value to the ResponseWriter // and sets the HTTP status to the given code. // // If val implements the HeaderSetter interface, the SetHeader // method will be called to add additional headers to the // HTTP response. It is called after the Content-Type header // has been added, so can be used to override the content type // if required. func WriteJSON(w http.ResponseWriter, code int, val interface{}) error { // TODO consider marshalling directly to w using json.NewEncoder. // pro: this will not require a full buffer allocation. // con: if there's an error after the first write, it will be lost. data, err := json.Marshal(val) if err != nil { return errgo.Mask(err) } w.Header().Set("content-type", "application/json") if headerSetter, ok := val.(HeaderSetter); ok { headerSetter.SetHeader(w.Header()) } w.WriteHeader(code) w.Write(data) return nil } // HeaderSetter is the interface checked for by WriteJSON. // If implemented on a value passed to WriteJSON, the SetHeader // method will be called to allow it to set custom headers // on the response. type HeaderSetter interface { SetHeader(http.Header) } // CustomHeader is a type that allows a JSON value to // set custom HTTP headers associated with the // HTTP response. type CustomHeader struct { // Body holds the JSON-marshaled body of the response. Body interface{} // SetHeaderFunc holds a function that will be called // to set any custom headers on the response. SetHeaderFunc func(http.Header) } // MarshalJSON implements json.Marshaler by marshaling // h.Body. func (h CustomHeader) MarshalJSON() ([]byte, error) { return json.Marshal(h.Body) } // SetHeader implements HeaderSetter by calling // h.SetHeaderFunc. func (h CustomHeader) SetHeader(header http.Header) { h.SetHeaderFunc(header) } // Ensure statically that responseWriter does implement http.Flusher. var _ http.Flusher = (*responseWriter)(nil) // responseWriter wraps http.ResponseWriter but allows us // to find out whether any body has already been written. type responseWriter struct { headerWritten bool http.ResponseWriter } func (w *responseWriter) Write(data []byte) (int, error) { w.headerWritten = true return w.ResponseWriter.Write(data) } func (w *responseWriter) WriteHeader(code int) { w.headerWritten = true w.ResponseWriter.WriteHeader(code) } // Flush implements http.Flusher.Flush. func (w *responseWriter) Flush() { w.headerWritten = true if f, ok := w.ResponseWriter.(http.Flusher); ok { f.Flush() } } type headerOnlyResponseWriter struct { h http.Header } func (w headerOnlyResponseWriter) Header() http.Header { return w.h } func (w headerOnlyResponseWriter) Write([]byte) (int, error) { // TODO log or panic when this happens? return 0, errgo.New("inappropriate call to ResponseWriter.Write in JSON-returning handler") } func (w headerOnlyResponseWriter) WriteHeader(code int) { // TODO log or panic when this happens? } func withoutReceiver(t reflect.Type) reflect.Type { return withoutReceiverType{t} } type withoutReceiverType struct { reflect.Type } func (t withoutReceiverType) NumIn() int { return t.Type.NumIn() - 1 } func (t withoutReceiverType) In(i int) reflect.Type { return t.Type.In(i + 1) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/fields_test.go��������������������������������������0000644�0610621�0607500�00000010106�13172163410�025456� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest import ( "reflect" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" ) type fieldsSuite struct{} var _ = gc.Suite(&fieldsSuite{}) type structField struct { name string index []int } var fieldsTests = []struct { about string val interface{} expect []structField }{{ about: "simple struct", val: struct { A int B string C bool }{}, expect: []structField{{ name: "A", index: []int{0}, }, { name: "B", index: []int{1}, }, { name: "C", index: []int{2}, }}, }, { about: "non-embedded struct member", val: struct { A struct { X int } }{}, expect: []structField{{ name: "A", index: []int{0}, }}, }, { about: "embedded exported struct", val: struct { SFG }{}, expect: []structField{{ name: "SFG", index: []int{0}, }, { name: "F", index: []int{0, 0}, }, { name: "G", index: []int{0, 1}, }}, }, { about: "embedded unexported struct", val: struct { sFG }{}, expect: []structField{{ name: "sFG", index: []int{0}, }, { name: "F", index: []int{0, 0}, }, { name: "G", index: []int{0, 1}, }}, }, { about: "two embedded structs with cancelling members", val: struct { SFG SF }{}, expect: []structField{{ name: "SFG", index: []int{0}, }, { name: "G", index: []int{0, 1}, }, { name: "SF", index: []int{1}, }}, }, { about: "embedded structs with same fields at different depths", val: struct { SFGH3 SG1 SFG2 SF2 L int }{}, expect: []structField{{ name: "SFGH3", index: []int{0}, }, { name: "SFGH2", index: []int{0, 0}, }, { name: "SFGH1", index: []int{0, 0, 0}, }, { name: "SFGH", index: []int{0, 0, 0, 0}, }, { name: "H", index: []int{0, 0, 0, 0, 2}, }, { name: "SG1", index: []int{1}, }, { name: "SG", index: []int{1, 0}, }, { name: "G", index: []int{1, 0, 0}, }, { name: "SFG2", index: []int{2}, }, { name: "SFG1", index: []int{2, 0}, }, { name: "SFG", index: []int{2, 0, 0}, }, { name: "SF2", index: []int{3}, }, { name: "SF1", index: []int{3, 0}, }, { name: "SF", index: []int{3, 0, 0}, }, { name: "L", index: []int{4}, }}, }, { about: "embedded pointer struct", val: struct { *SF }{}, expect: []structField{{ name: "SF", index: []int{0}, }, { name: "F", index: []int{0, 0}, }}, }, { about: "embedded not a pointer", val: struct { M }{}, expect: []structField{{ name: "M", index: []int{0}, }}, }} type SFG struct { F int `httprequest:",form"` G int `httprequest:",form"` } type SFG1 struct { SFG } type SFG2 struct { SFG1 } type SFGH struct { F int `httprequest:",form"` G int `httprequest:",form"` H int `httprequest:",form"` } type SFGH1 struct { SFGH } type SFGH2 struct { SFGH1 } type SFGH3 struct { SFGH2 } type SF struct { F int `httprequest:",form"` } type SF1 struct { SF } type SF2 struct { SF1 } type SG struct { G int `httprequest:",form"` } type SG1 struct { SG } type sFG struct { F int `httprequest:",form"` G int `httprequest:",form"` } type M map[string]interface{} func (*fieldsSuite) TestFields(c *gc.C) { for i, test := range fieldsTests { c.Logf("%d: %s", i, test.about) t := reflect.TypeOf(test.val) got := fields(t) c.Assert(got, gc.HasLen, len(test.expect)) for j, field := range got { expect := test.expect[j] c.Logf("field %d: %s", j, expect.name) gotField := t.FieldByIndex(field.Index) // Unfortunately, FieldByIndex does not return // a field with the same index that we passed in, // so we set it to the expected value so that // it can be compared later with the result of FieldByName. gotField.Index = field.Index expectField := t.FieldByIndex(expect.index) // ditto. expectField.Index = expect.index c.Assert(gotField, jc.DeepEquals, expectField) // Sanity check that we can actually access the field by the // expected name. expectField1, ok := t.FieldByName(expect.name) c.Assert(ok, jc.IsTrue) c.Assert(expectField1, jc.DeepEquals, expectField) } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/fancyerror_test.go����������������������������������0000644�0610621�0607500�00000036671�13172163410�026401� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httprequest import ( "strings" gc "gopkg.in/check.v1" ) type checkIsJSONSuite struct{} var _ = gc.Suite(&checkIsJSONSuite{}) var fancyDecodeErrorTests = []struct { about string contentType string body string expectError string }{{ about: "plain text", contentType: "text/plain; charset=UTF-8", body: " some\n text\t\n", expectError: `unexpected content type text/plain; want application/json; content: some; text`, }, { about: "plain text with leading newline", contentType: "text/plain; charset=UTF-8", body: "\nsome text", expectError: `unexpected content type text/plain; want application/json; content: some text`, }, { about: "unknown content type", contentType: "something", body: "some \nstuff", expectError: `unexpected content type something; want application/json; content: "some \\nstuff"`, }, { about: "bad content type", contentType: "/; charset=foo", body: `some stuff`, expectError: `unexpected content type "/; charset=foo"; want application/json; content: "some stuff"`, }, { about: "large text body", contentType: "text/plain", body: strings.Repeat("x", 1024+300), expectError: `unexpected content type text/plain; want application/json; content: ` + strings.Repeat("x", 1024) + ` \.\.\. \[300 bytes omitted]`, }, { about: "html with no text", contentType: "text/html", body: "<html><a href=\"foo\">\n</a></html>", expectError: `unexpected content type text/html; want application/json; content: "<html><a href=\\"foo\\">\\n</a></html>"`, }, { about: "non-utf8 text", contentType: "text/plain; charset=iso8859-1", body: "Pepp\xe9\n", // It would be nice to make this better, but we don't // really want to drag in all the charsets for this. expectError: "unexpected content type text/plain; want application/json; content: Pepp\uFFFD", }, { about: "actual html error message from proxy", contentType: "text/html; charset=UTF-8", body: `<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>502 Proxy Error</title> </head><body> <h1>Proxy Error</h1> <p>The proxy server received an invalid response from an upstream server.<br /> The proxy server could not handle the request <em><a href="/identity/v1/wait">GET&nbsp;/identity/v1/wait</a></em>.<p> Reason: <strong>Error reading from remote server</strong></p></p> <hr> <address>Apache/2.4.7 (Ubuntu) Server at api.jujucharms.com Port 443</address> </body></html>`, expectError: `unexpected content type text/html; want application/json; content: 502 Proxy Error; Proxy Error; The proxy server received an invalid response from an upstream server; The proxy server could not handle the request; GET /identity/v1/wait; Reason:; Error reading from remote server; Apache/2\.4\.7 \(Ubuntu\) Server at api.jujucharms.com Port 443`, }, { about: "actual html error message web page", contentType: "text/html; charset=UTF-8", body: `<!doctype html> <!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en" dir="ltr"> <![endif]--> <!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en" dir="ltr"> <![endif]--> <!--[if IE 8]> <html class="lt-ie9" lang="en" dir="ltr"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" dir="ltr" itemscope itemtype="http://schema.org/Product"> <!--<![endif]--> <head> <title>Page not found | Juju</title> <meta charset="UTF-8" /> <meta name="description" content="Deploy, manage and scale your environments on any cloud." /> <meta name="keywords" content="juju, charms, services, service orchestration, cloud, deployment, puppet, chef, fuel, cloud tools, service management, cloud management, configuration management, linux tool, openstack tool, ubuntu, cloud design, cloud orchestration" /> <meta name="author" content="Canonical" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=8"> <![endif]--> <link rel="shortcut icon" href="/static/img/favicon.ico" type="image/x-icon" /> <link rel="apple-touch-icon-precomposed" sizes="57x57" href="/static/img/icons/apple-touch-icon-57x57-precomposed.png"/> <link rel="apple-touch-icon-precomposed" sizes="60x60" href="/static/img/icons/apple-touch-icon-60x60-precomposed.png"/> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/static/img/icons/apple-touch-icon-72x72-precomposed.png"/> <link rel="apple-touch-icon-precomposed" sizes="76x76" href="/static/img/icons/apple-touch-icon-76x76-precomposed.png"/> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/static/img/icons/apple-touch-icon-114x114-precomposed.png"/> <link rel="apple-touch-icon-precomposed" sizes="120x120" href="/static/img/icons/apple-touch-icon-120x120-precomposed.png"/> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/static/img/icons/apple-touch-icon-144x144-precomposed.png"/> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="/static/img/icons/apple-touch-icon-152x152-precomposed.png"/> <link rel="apple-touch-icon-precomposed" sizes="180x180" href="/static/img/icons/apple-touch-icon-180x180-precomposed.png"/> <link rel="apple-touch-icon-precomposed" href="/static/img/icons/apple-touch-icon-precomposed.png"/> <!-- google fonts --> <link href='https://fonts.googleapis.com/css?family=Ubuntu:400,300,300italic,400italic,700,700italic%7CUbuntu+Mono' rel='stylesheet' type='text/css' /> <!-- stylesheets --> <link rel="stylesheet" type="text/css" media="screen" href="//assets.ubuntu.com/sites/guidelines/css/responsive/latest/ubuntu-styles.css" /> <link rel="stylesheet" type="text/css" media="screen" href="/static/css/build.css" /> <!-- load basic yui, our modules file, the loader and sub to set up modules with combo load --> <script type="text/javascript" src="/prod/combo?yui/yui/yui-min.js&amp;app/modules-min.js&amp;yui/loader/loader-min.js&amp;yui/substitute/substitute-min.js&amp;plugins/respond.min.js&amp;plugins/modernizr.2.7.1.js&amp;plugins/handlebars.runtime-v2.0.0.js&amp;plugins/highlight.pack.js&amp;templates/templates.js"> </script> <script type="text/javascript"> YUI.GlobalConfig = { combine: true, base: '/prod/combo?yui/', comboBase: '/prod/combo?', maxURLLength: 1300, root: 'yui/', groups: { app: { combine: true, base: '/prod/combo?app', comboBase: '/prod/combo?', root: 'app/', filter: 'min', // From modules.js modules: YUI_MODULES, } }, static_root:'/static/' }; </script> <!-- provide charmstore url --> <script type="text/javascript"> window.csUrl = "https://api.jujucharms.com/charmstore/v4"; </script> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@ubuntucloud"> <meta name="twitter:creator" content="@ubuntucloud"> <meta name="twitter:domain" content="jujucharms.com"> <meta name="twitter:title" content="Search results for foo in Juju"> <meta name="twitter:description" content="Deploy, manage, and scale your environments on any cloud."> <meta name="twitter:image" content="https://jujucharms.com/static/img/juju-twitter.png"> </head> <body class=" no-results no-match"> <header class="banner global" role="banner"> <nav role="navigation" class="nav-primary nav-right"> <span class="accessibility-aid"> <a accesskey="s" href="#main-content">Jump to content</a> </span> <ul> <li> <a class="" href="/store" > Store </a> </li> <li><a href="https://demo.jujucharms.com" target="_blank" >Demo</a></li> <li> <a class="" href="/about" > About </a> </li> <li> <a class="" href="/about/features" > Features </a> </li> <li> <a class="" href="/community" > Community </a> </li> <li> <a class="" href="/docs/" > Docs </a> </li> <li> <a class="" href="/get-started" > Get started </a> </li> </ul> <ul class="user-nav"> <li class="user-dropdown"><span id="user-dropdown"></span></li> </ul> <a href="#canonlist" class="nav-toggle no-script">☰</a> </nav> </header> <div class="contextual-bar"> <div class="logo"> <a class="logo-ubuntu" href="/"> <img width="73" height="30" src="/static/img/logos/logo.png" alt="" /> </a> </div> <ul class="directory-path"> <li><a href="https://demo.jujucharms.com" class="btn__see--more">Create <span>+</span></a></li> </ul> <form class="search-form" action="/q" method="GET"> <input type="search" name="text" class="form-text" placeholder="Search the store" value="foo" /> <button type="submit"> <img src="/static/img/icons/search_16_active.svg" alt="Search" height="28" /> </button> <a href="" class="search-close"><img src="/static/img/icons/close_16.svg" alt="" /></a> </form> </div> <div class="wrapper"> <div id="main-content"> <div class="row"> <div class="inner-wrapper"> <h2 class="error-title">404: Sorry, we couldn&rsquo;t find the page.</h2> <p class="cta">Try a different URL, try searching for solutions or learn how to <a href="/docs/authors-charm-writing">create your own solution</a>.</p> <nav class="error-nav"> <ul> <li><a href="/store" class="link-cta-positive">Browse the store</a></li> <li><a href="/q/?type=bundle" class="link-cta-negative">All bundles</a></li> <li><a href="/q/?type=charm" class="link-cta-negative">All charms</a></li> <li><a href="https://github.com/CanonicalLtd/jujucharms.com/issues">Submit a bug</a></li> </ul> </nav> </div> </div> </div><!-- /.inner-wrapper --> </div><!-- /.wrapper --> <div class="footer-wrapper strip-light"> <div class="store-cta"> <a href="/store">Browse the store&nbsp;&rsaquo;</a> </div> <footer class="global clearfix"> <p class="top-link"> <a href="#">Back to the top</a> </p> <nav role="navigation" class="inner-wrapper"> <div class="row"> <div class="seven-col"> <ul class="no-bullets"> <li><a class="external" href="https://demo.jujucharms.com">Demo</a></li> <li><a href="/about">About</a></li> <li><a href="/about/features">Features</a></li> <li><a href="/docs">Docs</a></li> <li><a href="/get-started">Get Started</a></li> </ul> </div> <div class="five-col last-col"> <ul class="social--right"> <li class="social__item"> <a href="https://plus.google.com/106305712267007929608/posts" class="social__google"><span class="accessibility-aid">Juju on Google+</span></a> </li> <li class="social__item"> <a href="http://www.twitter.com/ubuntucloud" class="social__twitter"><span class="accessibility-aid">Ubuntu Cloud on Twitter</span></a> </li> <li class="social__item"> <a href="http://www.facebook.com/ubuntucloud" class="social__facebook"><span class="accessibility-aid">Ubuntu Cloud on Facebook</span></a> </li> </ul> </div> </div> </nav> <div class="legal clearfix"> <div class="legal-inner"> <p class="twelve-col"> &copy; 2015 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd. </p> <ul class="inline bullets clear"> <li><a href="http://www.ubuntu.com/legal">Legal information</a></li> <li><a href="https://github.com/CanonicalLtd/jujucharms.com/issues">Report a bug on this site</a></li> </ul> <span class="accessibility-aid"> <a href="#">Got to the top of the page</a> </span> </div> </div> </footer> </div> <script> var isOperaMini = (navigator.userAgent.indexOf('Opera Mini') > -1); if(isOperaMini) { var root = document.documentElement; root.className += " opera-mini"; } </script> <script> YUI().use('storefront-cookie', 'storefront-utils', 'user-dropdown', function (Y) { Y.on('domready', function() { var inSession = false; var cookie = new Y.storefront.CookiePolicy(); var utils = Y.storefront.utils; cookie.render(); utils.mobileNav(Y.one('header.banner')); utils.setupSearch(); var userDropdown = new Y.storefront.UserDropdownView({ container: Y.one('#user-dropdown') }); userDropdown.set('authenticated', inSession); if (inSession) { userDropdown.set('username', ''); } userDropdown.render(); }); }); </script> <script type="text/template" id="cookie-warning-template"> <div class="cookie-policy"> <div class="inner-wrapper"> <a href="?cp=close" class="link-cta">Close</a> <p>We use cookies to improve your experience. By your continued use of this site you accept such use. To change your settings please <a href="http://www.ubuntu.com/legal/terms-and-policies/privacy-policy#cookies">see our policy</a>.</p> </div> </div> </script> <script> YUI().use('node', 'search-view', function (Y) { Y.on('domready', function() { var view = new Y.storefront.SearchView({ container: Y.one('#main-content') }); view.render(); }); }); </script> <!-- google analytics --> <script> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1018242-44']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- {version: ['0.1.29', '']} --> </body> </html> `, expectError: `unexpected content type text/html; want application/json; content: Page not found | Juju; Jump to content; Store; Demo; About; Features; Community; Docs; Get started; ☰; Create; \+; 404: Sorry, we couldn’t find the page; Try a different URL, try searching for solutions or learn how to; create your own solution; Browse the store; All bundles; All charms; Submit a bug; Browse the store ›; Back to the top; Demo; About; Features; Docs; Get Started; Juju on Google+; Ubuntu Cloud on Twitter; Ubuntu Cloud on Facebook; © 2015 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd; Legal information; Report a bug on this site; Got to the top of the page`, }} func (checkIsJSONSuite) TestFancyDecodeError(c *gc.C) { for i, test := range fancyDecodeErrorTests { c.Logf("test %d: %s", i, test.about) err := &fancyDecodeError{ contentType: test.contentType, body: []byte(test.body), } c.Assert(err, gc.ErrorMatches, test.expectError) } } �����������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/fancyerror.go���������������������������������������0000644�0610621�0607500�00000016776�13172163410�025346� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httprequest import ( "bytes" "fmt" "io" "io/ioutil" "mime" "net/http" "unicode" "golang.org/x/net/html" "golang.org/x/net/html/atom" "gopkg.in/errgo.v1" ) func isDecodeResponseError(err error) bool { _, ok := err.(*DecodeResponseError) return ok } // DecodeResponseError represents an error when an HTTP // response could not be decoded. type DecodeResponseError struct { // Response holds the problematic HTTP response. // The body of this does not need to be closed // and may be truncated if the response is large. Response *http.Response // DecodeError holds the error that was encountered // when decoding. DecodeError error } func (e *DecodeResponseError) Error() string { return e.DecodeError.Error() } // newDecodeResponseError returns a new DecodeResponseError that // uses the given error for its message. The Response field // holds a copy of req. If bodyData is non-nil, it // will be used as the data in the Response.Body field; // otherwise body data will be read from req.Body. func newDecodeResponseError(resp *http.Response, bodyData []byte, err error) *DecodeResponseError { if bodyData == nil { bodyData = readBodyForError(resp.Body) } resp1 := *resp resp1.Body = ioutil.NopCloser(bytes.NewReader(bodyData)) return &DecodeResponseError{ Response: &resp1, DecodeError: errgo.Mask(err, errgo.Any), } } // newDecodeRequestError returns a new DecodeRequestError that // uses the given error for its message. The Request field // holds a copy of req. If bodyData is non-nil, it // will be used as the data in the Request.Body field; // otherwise body data will be read from req.Body. func newDecodeRequestError(req *http.Request, bodyData []byte, err error) *DecodeRequestError { if bodyData == nil { bodyData = readBodyForError(req.Body) } req1 := *req req1.Body = ioutil.NopCloser(bytes.NewReader(bodyData)) return &DecodeRequestError{ Request: &req1, DecodeError: errgo.Mask(err, errgo.Any), } } // DecodeRequestError represents an error when an HTTP // request could not be decoded. type DecodeRequestError struct { // Request holds the problematic HTTP request. // The body of this does not need to be closed // and may be truncated if the response is large. Request *http.Request // DecodeError holds the error that was encountered // when decoding. DecodeError error } func (e *DecodeRequestError) Error() string { return e.DecodeError.Error() } // fancyDecodeError is an error type that tries to // produce a nice error message when the content // type of a request or response is wrong. type fancyDecodeError struct { // contentType holds the contentType of the request or response. contentType string // body holds up to maxErrorBodySize saved bytes of the // request or response body. body []byte } func newFancyDecodeError(h http.Header, body io.Reader) *fancyDecodeError { return &fancyDecodeError{ contentType: h.Get("Content-Type"), body: readBodyForError(body), } } func readBodyForError(r io.Reader) []byte { data, _ := ioutil.ReadAll(io.LimitReader(noErrorReader{r}, int64(maxErrorBodySize))) return data } // maxErrorBodySize holds the maximum amount of body that // we try to read for an error before extracting text from it. // It's reasonably large because: // a) HTML often has large embedded scripts which we want // to skip and // b) it should be an relatively unusual case so the size // shouldn't harm. // // It's defined as a variable so that it can be redefined in tests. var maxErrorBodySize = 200 * 1024 // isJSONMediaType reports whether the content type of the given header implies // that the content is JSON. func isJSONMediaType(header http.Header) bool { contentType := header.Get("Content-Type") mediaType, _, _ := mime.ParseMediaType(contentType) return mediaType == "application/json" } // Error implements error.Error by trying to produce a decent // error message derived from the body content. func (e *fancyDecodeError) Error() string { mediaType, _, err := mime.ParseMediaType(e.contentType) if err != nil { // Even if there's no media type, we want to see something useful. mediaType = fmt.Sprintf("%q", e.contentType) } // TODO use charset.NewReader to convert from non-utf8 content? switch mediaType { case "text/html": text, err := htmlToText(bytes.NewReader(e.body)) if err != nil { // Note: it seems that this can never actually // happen - the only way that the HTML parser // can fail is if there's a read error and we've // removed that possibility by using // noErrorReader above. return fmt.Sprintf("unexpected (and invalid) content text/html; want application/json; content: %q", sizeLimit(e.body)) } if len(text) == 0 { return fmt.Sprintf(`unexpected content type text/html; want application/json; content: %q`, sizeLimit(e.body)) } return fmt.Sprintf(`unexpected content type text/html; want application/json; content: %s`, sizeLimit(text)) case "text/plain": return fmt.Sprintf(`unexpected content type text/plain; want application/json; content: %s`, sizeLimit(sanitizeText(string(e.body), true))) default: return fmt.Sprintf(`unexpected content type %s; want application/json; content: %q`, mediaType, sizeLimit(e.body)) } } // noErrorReader wraps a reader, turning any errors into io.EOF // so that we can extract some content even if we get an io error. type noErrorReader struct { r io.Reader } func (r noErrorReader) Read(buf []byte) (int, error) { n, err := r.r.Read(buf) if err != nil { err = io.EOF } return n, err } func sizeLimit(data []byte) []byte { const max = 1024 if len(data) < max { return data } return append(data[0:max], fmt.Sprintf(" ... [%d bytes omitted]", len(data)-max)...) } // htmlToText attempts to return some relevant textual content // from the HTML content in the given reader, formatted // as a single line. func htmlToText(r io.Reader) ([]byte, error) { n, err := html.Parse(r) if err != nil { return nil, err } var buf bytes.Buffer htmlNodeToText(&buf, n) return buf.Bytes(), nil } // htmlNodeToText tries to extract some text from an arbitrary HTML // page. It doesn't try to avoid looking in the header, because the // title is in the header and is often the most succinct description of // the page. func htmlNodeToText(w *bytes.Buffer, n *html.Node) { for ; n != nil; n = n.NextSibling { switch n.Type { case html.TextNode: data := sanitizeText(n.Data, false) if len(data) == 0 { break } if w.Len() > 0 { w.WriteString("; ") } w.Write(data) case html.ElementNode: if n.DataAtom != atom.Script { htmlNodeToText(w, n.FirstChild) } case html.DocumentNode: htmlNodeToText(w, n.FirstChild) } } } // sanitizeText tries to make the given string easier to read when presented // as a single line. It squashes each run of white space into a single // space, trims leading and trailing white space and trailing full // stops. If newlineSemi is true, any newlines will be replaced with a // semicolon. func sanitizeText(s string, newlineSemi bool) []byte { out := make([]byte, 0, len(s)) prevWhite := false for _, r := range s { if newlineSemi && r == '\n' && len(out) > 0 { out = append(out, ';') prevWhite = true continue } if unicode.IsSpace(r) { if len(out) > 0 { prevWhite = true } continue } if prevWhite { out = append(out, ' ') prevWhite = false } out = append(out, string(r)...) } // Remove final space, any full stops and any final semicolon // we might have added. out = bytes.TrimRightFunc(out, func(r rune) bool { return r == '.' || r == ' ' || r == ';' }) return out } ��lxd-2.0.11/dist/src/github.com/juju/httprequest/export_test.go��������������������������������������0000644�0610621�0607500�00000000130�13172163410�025525� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httprequest var AppendURL = appendURL var MaxErrorBodySize = &maxErrorBodySize ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/example_handlers_test.go����������������������������0000644�0610621�0607500�00000002616�13172163410�027532� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httprequest_test import ( "fmt" "io" "net/http" "net/http/httptest" "os" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" "github.com/juju/httprequest" ) type arithHandler struct { } type number struct { N int } func (arithHandler) Add(arg *struct { httprequest.Route `httprequest:"GET /:A/add/:B"` A int `httprequest:",path"` B int `httprequest:",path"` }) (number, error) { return number{ N: arg.A + arg.B, }, nil } func ExampleServer_Handlers() { f := func(p httprequest.Params) (arithHandler, context.Context, error) { fmt.Printf("handle %s %s\n", p.Request.Method, p.Request.URL) return arithHandler{}, p.Context, nil } router := httprouter.New() for _, h := range exampleServer.Handlers(f) { router.Handle(h.Method, h.Path, h.Handle) } srv := httptest.NewServer(router) resp, err := http.Get(srv.URL + "/123/add/11") if err != nil { panic(err) } defer resp.Body.Close() if resp.StatusCode != 200 { panic("status " + resp.Status) } fmt.Println("result:") io.Copy(os.Stdout, resp.Body) // Output: handle GET /123/add/11 // result: // {"N":134} } type exampleErrorResponse struct { Message string } var exampleServer = httprequest.Server{ ErrorMapper: func(ctx context.Context, err error) (int, interface{}) { return http.StatusInternalServerError, &exampleErrorResponse{ Message: err.Error(), } }, } ������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/dependencies.tsv������������������������������������0000644�0610621�0607500�00000003235�13172163410�026013� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������github.com/juju/ansiterm git b99631de12cf04a906c1d4e4ec54fb86eae5863d 2016-09-07T23:45:32Z github.com/juju/errors git 1b5e39b83d1835fa480e0c2ddefb040ee82d58b3 2015-09-16T12:56:42Z github.com/juju/loggo git 3b7ece48644d35850f4ced4c2cbc2cf8413f58e0 2016-08-18T02:57:24Z github.com/juju/retry git 62c62032529169c7ec02fa48f93349604c345e1f 2015-10-29T02:48:21Z github.com/juju/testing git b8689951f6db31943dd8c3d540b8c4dd368cf850 2016-10-31T10:37:13Z github.com/juju/utils git 28c01ec2ad930d41fe5acd9969b96284eb61660b 2016-10-03T23:32:26Z github.com/juju/version git 4ae6172c00626779a5a462c3e3d22fc0e889431a 2016-06-03T19:49:58Z github.com/julienschmidt/httprouter git 77a895ad01ebc98a4dc95d8355bc825ce80a56f6 2015-10-13T22:55:20Z github.com/lunixbochs/vtclean git 4fbf7632a2c6d3fbdb9931439bdbbeded02cbe36 2016-01-25T03:51:06Z github.com/mattn/go-colorable git ed8eb9e318d7a84ce5915b495b7d35e0cfe7b5a8 2016-07-31T23:54:17Z github.com/mattn/go-isatty git 66b8e73f3f5cda9f96b69efd03dd3d7fc4a5cdb8 2016-08-06T12:27:52Z github.com/rogpeppe/fastuuid git 6724a57986aff9bff1a1770e9347036def7c89f6 2015-01-06T09:32:20Z golang.org/x/crypto git 8e06e8ddd9629eb88639aba897641bff8031f1d3 2016-09-22T17:06:29Z golang.org/x/net git ea47fc708ee3e20177f3ca3716217c4ab75942cb 2015-08-29T23:03:18Z golang.org/x/tools git 1f1b3322f67af76803c942fd237291538ec68262 2016-04-27T05:26:01Z gopkg.in/check.v1 git 4f90aeace3a26ad7021961c297b22c42160c7b25 2016-01-05T16:49:36Z gopkg.in/errgo.v1 git 66cb46252b94c1f3d65646f54ee8043ab38d766c 2015-10-07T15:31:57Z gopkg.in/mgo.v2 git f2b6f6c918c452ad107eec89615f074e3bd80e33 2016-08-18T01:52:18Z gopkg.in/yaml.v2 git a83829b6f1293c91addabc89d0571c246397bbf4 2016-03-01T20:40:22Z �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/context_test.go�������������������������������������0000644�0610621�0607500�00000001530�13172163410�025675� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest_test import ( "net/http" "net/http/httptest" "github.com/julienschmidt/httprouter" gc "gopkg.in/check.v1" "github.com/juju/httprequest" ) type contextSuite struct{} var _ = gc.Suite(&contextSuite{}) type testRequest struct { httprequest.Route `httprequest:"GET /foo"` } func (s *contextSuite) TestContextCancelledWhenDone(c *gc.C) { var ch <-chan struct{} hnd := testServer.Handle(func(p httprequest.Params, req *testRequest) { ch = p.Context.Done() }) router := httprouter.New() router.Handle(hnd.Method, hnd.Path, hnd.Handle) srv := httptest.NewServer(router) _, err := http.Get(srv.URL + "/foo") c.Assert(err, gc.Equals, nil) select { case <-ch: default: c.Fatal("context not canceled at end of handler.") } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/context_prego17.go����������������������������������0000644�0610621�0607500�00000000671�13172163410�026207� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. // +build !go1.7 package httprequest import ( "net/http" "golang.org/x/net/context" ) func contextFromRequest(req *http.Request) (context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) return ctx, cancel } func requestWithContext(req *http.Request, _ context.Context) *http.Request { return req } �����������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/context_go17.go�������������������������������������0000644�0610621�0607500�00000000615�13172163410�025476� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. // +build go1.7 package httprequest import ( "context" "net/http" ) func contextFromRequest(req *http.Request) (context.Context, context.CancelFunc) { return req.Context(), func() {} } func requestWithContext(req *http.Request, ctx context.Context) *http.Request { return req.WithContext(ctx) } �������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/cmd/������������������������������������������������0000755�0610621�0607500�00000000000�13172163410�023367� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/cmd/httprequest-generate-client/��������������������0000755�0610621�0607500�00000000000�13172163410�031023� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/cmd/httprequest-generate-client/main.go�������������0000644�0610621�0607500�00000016150�13172163410�032301� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.6 package main import ( "bytes" "flag" "fmt" "go/ast" "go/build" "go/format" "go/parser" "io/ioutil" "os" "strings" "text/template" "go/types" "golang.org/x/tools/go/loader" "gopkg.in/errgo.v1" ) // TODO: // - generate exported types if the parameter/response types aren't exported? // - deal with literal interface and struct types. // - copy doc comments from server methods. func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "usage: httprequest-generate server-package server-type client-type\n") os.Exit(2) } flag.Parse() if flag.NArg() != 3 { flag.Usage() } serverPkg, serverType, clientType := flag.Arg(0), flag.Arg(1), flag.Arg(2) if err := generate(serverPkg, serverType, clientType); err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } } type templateArg struct { PkgName string Imports []string Methods []method ClientType string } var code = template.Must(template.New("").Parse(` // The code in this file was automatically generated by running httprequest-generate-client. // DO NOT EDIT package {{.PkgName}} import ( {{range .Imports}}{{printf "%q" .}} {{end}} ) type {{.ClientType}} struct { Client httprequest.Client } {{range .Methods}} {{if .RespType}} {{.Doc}} func (c *{{$.ClientType}}) {{.Name}}(ctx context.Context, p *{{.ParamType}}) ({{.RespType}}, error) { var r {{.RespType}} err := c.Client.Call(ctx, p, &r) return r, err } {{else}} {{.Doc}} func (c *{{$.ClientType}}) {{.Name}}(ctx context.Context, p *{{.ParamType}}) (error) { return c.Client.Call(ctx, p, nil) } {{end}} {{end}} `)) func generate(serverPkgPath, serverType, clientType string) error { currentDir, err := os.Getwd() if err != nil { return err } localPkg, err := build.Import(".", currentDir, 0) if err != nil { return errgo.Notef(err, "cannot open package in current directory") } serverPkg, err := build.Import(serverPkgPath, currentDir, 0) if err != nil { return errgo.Notef(err, "cannot open %q", serverPkgPath) } methods, imports, err := serverMethods(serverPkg.ImportPath, serverType, localPkg.ImportPath) if err != nil { return errgo.Mask(err) } arg := templateArg{ Imports: imports, Methods: methods, PkgName: localPkg.Name, ClientType: clientType, } var buf bytes.Buffer if err := code.Execute(&buf, arg); err != nil { return errgo.Mask(err) } data, err := format.Source(buf.Bytes()) if err != nil { return errgo.Notef(err, "cannot format source") } if err := writeOutput(data, clientType); err != nil { return errgo.Mask(err) } return nil } func writeOutput(data []byte, clientType string) error { filename := strings.ToLower(clientType) + "_generated.go" if err := ioutil.WriteFile(filename, data, 0644); err != nil { return errgo.Mask(err) } return nil } type method struct { Name string Doc string ParamType string RespType string } func serverMethods(serverPkg, serverType, localPkg string) ([]method, []string, error) { cfg := loader.Config{ TypeCheckFuncBodies: func(string) bool { return false }, ImportPkgs: map[string]bool{ serverPkg: false, // false means don't load tests. }, ParserMode: parser.ParseComments, } prog, err := cfg.Load() if err != nil { return nil, nil, errgo.Notef(err, "cannot load %q", serverPkg) } pkgInfo := prog.Imported[serverPkg] if pkgInfo == nil { return nil, nil, errgo.Newf("cannot find %q in imported code", serverPkg) } pkg := pkgInfo.Pkg obj := pkg.Scope().Lookup(serverType) if obj == nil { return nil, nil, errgo.Newf("type %s not found in %s", serverType, serverPkg) } objTypeName, ok := obj.(*types.TypeName) if !ok { return nil, nil, errgo.Newf("%s is not a type", serverType) } // Use the pointer type to get as many methods as possible. ptrObjType := types.NewPointer(objTypeName.Type()) imports := map[string]string{ "github.com/juju/httprequest": "httprequest", "golang.org/x/net/context": "context", localPkg: "", } var methods []method mset := types.NewMethodSet(ptrObjType) for i := 0; i < mset.Len(); i++ { sel := mset.At(i) if !sel.Obj().Exported() { continue } name := sel.Obj().Name() if name == "Close" { continue } ptype, rtype, err := parseMethodType(sel.Type().(*types.Signature)) if err != nil { fmt.Fprintf(os.Stderr, "ignoring method %s: %v\n", name, err) continue } comment := docComment(prog, sel) methods = append(methods, method{ Name: name, Doc: comment, ParamType: typeStr(ptype, imports), RespType: typeStr(rtype, imports), }) } delete(imports, localPkg) var allImports []string for path := range imports { allImports = append(allImports, path) } return methods, allImports, nil } // docComment returns the doc comment for the method referred to // by the given selection. func docComment(prog *loader.Program, sel *types.Selection) string { obj := sel.Obj() tokFile := prog.Fset.File(obj.Pos()) if tokFile == nil { panic("no file found for method") } filename := tokFile.Name() for _, pkgInfo := range prog.AllPackages { for _, f := range pkgInfo.Files { if tokFile := prog.Fset.File(f.Pos()); tokFile == nil || tokFile.Name() != filename { continue } // We've found the file we're looking for. Now traverse all // top level declarations looking for the right function declaration. for _, decl := range f.Decls { fdecl, ok := decl.(*ast.FuncDecl) if ok && fdecl.Name.Pos() == obj.Pos() { // Found it! return commentStr(fdecl.Doc) } } } } panic("method declaration not found") } func commentStr(c *ast.CommentGroup) string { if c == nil { return "" } var b []byte for i, cc := range c.List { if i > 0 { b = append(b, '\n') } b = append(b, cc.Text...) } return string(b) } // typeStr returns the type string to be used when using the // given type. It adds any needed import paths to the given // imports map (map from package path to package id). func typeStr(t types.Type, imports map[string]string) string { if t == nil { return "" } qualify := func(pkg *types.Package) string { if name, ok := imports[pkg.Path()]; ok { return name } name := pkg.Name() // Make sure we're not duplicating the name. // TODO if we are, make a new non-duplicated version. for oldPkg, oldName := range imports { if oldName == name { panic(errgo.Newf("duplicate package name %s vs %s", pkg.Path(), oldPkg)) } } imports[pkg.Path()] = name return name } return types.TypeString(t, qualify) } func parseMethodType(t *types.Signature) (ptype, rtype types.Type, err error) { mp := t.Params() if mp.Len() != 1 && mp.Len() != 2 { return nil, nil, errgo.New("wrong argument count") } ptype0 := mp.At(mp.Len() - 1).Type() ptype1, ok := ptype0.(*types.Pointer) if !ok { return nil, nil, errgo.New("parameter is not a pointer") } ptype = ptype1.Elem() if _, ok := ptype.Underlying().(*types.Struct); !ok { return nil, nil, errgo.Newf("parameter is %s, not a pointer to struct", ptype1.Elem()) } rp := t.Results() if rp.Len() > 2 { return nil, nil, errgo.New("wrong result count") } if rp.Len() == 2 { rtype = rp.At(0).Type() } return ptype, rtype, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/client_test.go��������������������������������������0000644�0610621�0607500�00000051121�13172163410�025470� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package httprequest_test import ( "io" "io/ioutil" "net/http" "net/http/httptest" "reflect" "strings" "github.com/juju/testing" jc "github.com/juju/testing/checkers" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" "golang.org/x/net/context/ctxhttp" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "github.com/juju/httprequest" ) type clientSuite struct { testing.CleanupSuite } var _ = gc.Suite(&clientSuite{}) var callTests = []struct { about string client httprequest.Client req interface{} requestUUID string expectError string assertError func(c *gc.C, err error) expectResp interface{} }{{ about: "GET success", req: &chM1Req{ P: "hello", }, expectResp: &chM1Resp{"hello"}, }, { about: "GET with nil response", req: &chM1Req{ P: "hello", }, }, { about: "POST success", req: &chM2Req{ P: "hello", Body: struct{ I int }{999}, }, expectResp: &chM2Resp{"hello", 999}, }, { about: "GET marshal error", req: 123, expectError: `type is not pointer to struct`, }, { about: "error response", req: &chInvalidM2Req{ P: "hello", Body: struct{ I bool }{true}, }, expectError: `Post http:.*: cannot unmarshal parameters: cannot unmarshal into field Body: cannot unmarshal request body: json: cannot unmarshal .*`, assertError: func(c *gc.C, err error) { c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httprequest.RemoteError)(nil)) err1 := errgo.Cause(err).(*httprequest.RemoteError) c.Assert(err1.Code, gc.Equals, "bad request") c.Assert(err1.Message, gc.Matches, `cannot unmarshal parameters: cannot unmarshal into field Body: cannot unmarshal request body: json: cannot unmarshal .*`) }, }, { about: "error unmarshaler returns nil", client: httprequest.Client{ UnmarshalError: func(*http.Response) error { return nil }, }, req: &chM3Req{}, expectError: `Get http://.*/m3: unexpected HTTP response status: 500 Internal Server Error`, }, { about: "unexpected redirect", req: &chM2RedirectM2Req{}, expectError: `Post http://.*/m2/foo//: unexpected redirect \(status 307 Temporary Redirect\) from "http://.*/m2/foo//" to "http://.*/m2/foo"`, }, { about: "bad content in successful response", req: &chM4Req{}, expectResp: new(int), expectError: `Get http://.*/m4: unexpected content type text/plain; want application/json; content: bad response`, assertError: func(c *gc.C, err error) { c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httprequest.DecodeResponseError)(nil)) err1 := errgo.Cause(err).(*httprequest.DecodeResponseError) c.Assert(err1.Response, gc.NotNil) data, err := ioutil.ReadAll(err1.Response.Body) c.Assert(err, gc.IsNil) c.Assert(string(data), gc.Equals, "bad response") }, }, { about: "bad content in error response", req: &chM5Req{}, expectResp: new(int), expectError: `Get http://.*/m5: cannot unmarshal error response \(status 418 I'm a teapot\): unexpected content type text/plain; want application/json; content: bad error value`, assertError: func(c *gc.C, err error) { c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httprequest.DecodeResponseError)(nil)) err1 := errgo.Cause(err).(*httprequest.DecodeResponseError) c.Assert(err1.Response, gc.NotNil) data, err := ioutil.ReadAll(err1.Response.Body) c.Assert(err, gc.IsNil) c.Assert(string(data), gc.Equals, "bad error value") c.Assert(err1.Response.StatusCode, gc.Equals, http.StatusTeapot) }, }, { about: "doer with context", client: httprequest.Client{ Doer: doerWithContextFunc(func(ctx context.Context, req *http.Request) (*http.Response, error) { if ctx == nil { panic("Do called when DoWithContext expected") } return ctxhttp.Do(ctx, http.DefaultClient, req) }), }, req: &chM2Req{ P: "hello", Body: struct{ I int }{999}, }, expectResp: &chM2Resp{"hello", 999}, }, { about: "doer with context and body", client: httprequest.Client{ Doer: doerWithContextFunc(func(ctx context.Context, req *http.Request) (*http.Response, error) { if ctx == nil { panic("Do called when DoWithContext expected") } return ctxhttp.Do(ctx, http.DefaultClient, req) }), }, req: &chM2Req{ P: "hello", Body: struct{ I int }{999}, }, expectResp: &chM2Resp{"hello", 999}, }, { about: "doer with context and body but no body", client: httprequest.Client{ Doer: doerWithContextFunc(func(ctx context.Context, req *http.Request) (*http.Response, error) { if ctx == nil { panic("Do called when DoWithContext expected") } return ctxhttp.Do(ctx, http.DefaultClient, req) }), }, req: &chM1Req{ P: "hello", }, expectResp: &chM1Resp{"hello"}, }} func (s *clientSuite) TestCall(c *gc.C) { srv := s.newServer() defer srv.Close() for i, test := range callTests { c.Logf("test %d: %s", i, test.about) var resp interface{} if test.expectResp != nil { resp = reflect.New(reflect.TypeOf(test.expectResp).Elem()).Interface() } client := test.client client.BaseURL = srv.URL ctx := context.Background() err := client.Call(ctx, test.req, resp) if test.expectError != "" { c.Logf("err %v", errgo.Details(err)) c.Check(err, gc.ErrorMatches, test.expectError) if test.assertError != nil { test.assertError(c, err) } continue } c.Assert(err, gc.IsNil) c.Assert(resp, jc.DeepEquals, test.expectResp) } } func (s *clientSuite) TestCallURLNoRequestPath(c *gc.C) { srv := s.newServer() defer srv.Close() var client httprequest.Client req := struct { httprequest.Route `httprequest:"GET"` chM1Req }{ chM1Req: chM1Req{ P: "hello", }, } var resp chM1Resp err := client.CallURL(context.Background(), srv.URL+"/m1/:P", &req, &resp) c.Assert(err, gc.IsNil) c.Assert(resp, jc.DeepEquals, chM1Resp{"hello"}) } func mustNewRequest(url string, method string, body io.Reader) *http.Request { return mustNewRequestWithHeader(url, method, body, http.Header{ "Content-Type": []string{"application/json"}, }) } func mustNewRequestWithHeader(url string, method string, body io.Reader, hdr http.Header) *http.Request { req, err := http.NewRequest(method, url, body) if err != nil { panic(err) } for k, v := range hdr { req.Header[k] = append(req.Header[k], v...) } return req } var doTests = []struct { about string client httprequest.Client request *http.Request requestUUID string expectError string expectCause interface{} expectResp interface{} }{{ about: "GET success", request: mustNewRequest("/m1/hello", "GET", nil), expectResp: &chM1Resp{"hello"}, }, { about: "appendURL error", request: mustNewRequest("/m1/hello", "GET", nil), client: httprequest.Client{ BaseURL: ":::", }, expectError: `cannot parse ":::": parse :::: missing protocol scheme`, }, { about: "Do returns error", client: httprequest.Client{ Doer: doerFunc(func(req *http.Request) (*http.Response, error) { return nil, errgo.Newf("an error") }), }, request: mustNewRequest("/m2/foo", "POST", strings.NewReader(`{"I": 999}`)), expectError: "Post http://.*/m2/foo: an error", }, { about: "doer with context", client: httprequest.Client{ Doer: doerWithContextFunc(func(ctx context.Context, req *http.Request) (*http.Response, error) { if ctx == nil { panic("Do called when DoWithContext expected") } return ctxhttp.Do(ctx, http.DefaultClient, req) }), }, request: mustNewRequest("/m2/foo", "POST", strings.NewReader(`{"I": 999}`)), expectResp: &chM2Resp{"foo", 999}, }} func newInt64(i int64) *int64 { return &i } func (s *clientSuite) TestDo(c *gc.C) { srv := s.newServer() defer srv.Close() for i, test := range doTests { c.Logf("test %d: %s", i, test.about) var resp interface{} if test.expectResp != nil { resp = reflect.New(reflect.TypeOf(test.expectResp).Elem()).Interface() } client := test.client if client.BaseURL == "" { client.BaseURL = srv.URL } ctx := context.Background() err := client.Do(ctx, test.request, resp) if test.expectError != "" { c.Assert(err, gc.ErrorMatches, test.expectError) if test.expectCause != nil { c.Assert(errgo.Cause(err), jc.DeepEquals, test.expectCause) } continue } c.Assert(err, gc.IsNil) c.Assert(resp, jc.DeepEquals, test.expectResp) } } func (s *clientSuite) TestDoWithHTTPReponse(c *gc.C) { srv := s.newServer() defer srv.Close() client := &httprequest.Client{ BaseURL: srv.URL, } var resp *http.Response err := client.Get(context.Background(), "/m1/foo", &resp) c.Assert(err, gc.IsNil) defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) c.Assert(err, gc.IsNil) c.Assert(string(data), gc.Equals, `{"P":"foo"}`) } func (s *clientSuite) TestDoWithHTTPReponseAndError(c *gc.C) { srv := s.newServer() defer srv.Close() var doer closeCountingDoer // Also check the body is closed. client := &httprequest.Client{ BaseURL: srv.URL, Doer: &doer, } var resp *http.Response err := client.Get(context.Background(), "/m3", &resp) c.Assert(resp, gc.IsNil) c.Assert(err, gc.ErrorMatches, `Get http:.*/m3: m3 error`) c.Assert(doer.openedBodies, gc.Equals, 1) c.Assert(doer.closedBodies, gc.Equals, 1) } func (s *clientSuite) TestCallWithHTTPResponse(c *gc.C) { srv := s.newServer() defer srv.Close() client := &httprequest.Client{ BaseURL: srv.URL, } var resp *http.Response err := client.Call(context.Background(), &chM1Req{ P: "foo", }, &resp) defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) c.Assert(err, gc.IsNil) c.Assert(string(data), gc.Equals, `{"P":"foo"}`) } func (s *clientSuite) TestCallClosesResponseBodyOnSuccess(c *gc.C) { srv := s.newServer() defer srv.Close() var doer closeCountingDoer client := &httprequest.Client{ BaseURL: srv.URL, Doer: &doer, } var resp chM1Resp err := client.Call(context.Background(), &chM1Req{ P: "foo", }, &resp) c.Assert(err, gc.IsNil) c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"}) c.Assert(doer.openedBodies, gc.Equals, 1) c.Assert(doer.closedBodies, gc.Equals, 1) } func (s *clientSuite) TestCallClosesResponseBodyOnError(c *gc.C) { srv := s.newServer() defer srv.Close() var doer closeCountingDoer client := &httprequest.Client{ BaseURL: srv.URL, Doer: &doer, } err := client.Call(context.Background(), &chM3Req{}, nil) c.Assert(err, gc.ErrorMatches, ".*m3 error") c.Assert(doer.openedBodies, gc.Equals, 1) c.Assert(doer.closedBodies, gc.Equals, 1) } func (s *clientSuite) TestDoClosesResponseBodyOnSuccess(c *gc.C) { srv := s.newServer() defer srv.Close() var doer closeCountingDoer client := &httprequest.Client{ BaseURL: srv.URL, Doer: &doer, } req, err := http.NewRequest("GET", "/m1/foo", nil) c.Assert(err, gc.IsNil) var resp chM1Resp err = client.Do(context.Background(), req, &resp) c.Assert(err, gc.IsNil) c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"}) c.Assert(doer.openedBodies, gc.Equals, 1) c.Assert(doer.closedBodies, gc.Equals, 1) } func (s *clientSuite) TestDoClosesResponseBodyOnError(c *gc.C) { srv := s.newServer() defer srv.Close() var doer closeCountingDoer client := &httprequest.Client{ BaseURL: srv.URL, Doer: &doer, } req, err := http.NewRequest("GET", "/m3", nil) c.Assert(err, gc.IsNil) err = client.Do(context.Background(), req, nil) c.Assert(err, gc.ErrorMatches, ".*m3 error") c.Assert(doer.openedBodies, gc.Equals, 1) c.Assert(doer.closedBodies, gc.Equals, 1) } func (s *clientSuite) TestGet(c *gc.C) { srv := s.newServer() defer srv.Close() client := httprequest.Client{ BaseURL: srv.URL, } var resp chM1Resp err := client.Get(context.Background(), "/m1/foo", &resp) c.Assert(err, gc.IsNil) c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"}) } func (s *clientSuite) TestGetNoBaseURL(c *gc.C) { srv := s.newServer() defer srv.Close() client := httprequest.Client{} var resp chM1Resp err := client.Get(context.Background(), srv.URL+"/m1/foo", &resp) c.Assert(err, gc.IsNil) c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"}) } func (s *clientSuite) TestUnmarshalJSONResponseWithBodyReadError(c *gc.C) { resp := &http.Response{ Header: http.Header{ "Content-Type": {"application/json"}, }, StatusCode: http.StatusOK, Body: ioutil.NopCloser(io.MultiReader( strings.NewReader(`{"one": "two"}`), errorReader("some bad read"), )), } var val map[string]string err := httprequest.UnmarshalJSONResponse(resp, &val) c.Assert(err, gc.ErrorMatches, `error reading response body: some bad read`) c.Assert(val, gc.IsNil) assertDecodeResponseError(c, err, http.StatusOK, `{"one": "two"}`) } func (s *clientSuite) TestUnmarshalJSONResponseWithBadContentType(c *gc.C) { resp := &http.Response{ Header: http.Header{ "Content-Type": {"foo/bar"}, }, StatusCode: http.StatusTeapot, Body: ioutil.NopCloser(strings.NewReader(`something or other`)), } var val map[string]string err := httprequest.UnmarshalJSONResponse(resp, &val) c.Assert(err, gc.ErrorMatches, `unexpected content type foo/bar; want application/json; content: "something or other"`) c.Assert(val, gc.IsNil) assertDecodeResponseError(c, err, http.StatusTeapot, `something or other`) } func (s *clientSuite) TestUnmarshalJSONResponseWithErrorAndLargeBody(c *gc.C) { s.PatchValue(httprequest.MaxErrorBodySize, 11) resp := &http.Response{ Header: http.Header{ "Content-Type": {"foo/bar"}, }, StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader(`123456789 123456789`)), } var val map[string]string err := httprequest.UnmarshalJSONResponse(resp, &val) c.Assert(err, gc.ErrorMatches, `unexpected content type foo/bar; want application/json; content: "123456789 1"`) c.Assert(val, gc.IsNil) assertDecodeResponseError(c, err, http.StatusOK, `123456789 1`) } func (s *clientSuite) TestUnmarshalJSONResponseWithLargeBody(c *gc.C) { s.PatchValue(httprequest.MaxErrorBodySize, 11) resp := &http.Response{ Header: http.Header{ "Content-Type": {"application/json"}, }, StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader(`"23456789 123456789"`)), } var val string err := httprequest.UnmarshalJSONResponse(resp, &val) c.Assert(err, gc.IsNil) c.Assert(val, gc.Equals, "23456789 123456789") } func (s *clientSuite) TestUnmarshalJSONWithDecodeError(c *gc.C) { resp := &http.Response{ Header: http.Header{ "Content-Type": {"application/json"}, }, StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader(`{"one": "two"}`)), } var val chan string err := httprequest.UnmarshalJSONResponse(resp, &val) c.Assert(err, gc.ErrorMatches, `json: cannot unmarshal object into Go value of type chan string`) c.Assert(val, gc.IsNil) assertDecodeResponseError(c, err, http.StatusOK, `{"one": "two"}`) } func (s *clientSuite) TestUnmarshalJSONWithDecodeErrorAndLargeBody(c *gc.C) { s.PatchValue(httprequest.MaxErrorBodySize, 11) resp := &http.Response{ Header: http.Header{ "Content-Type": {"application/json"}, }, StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader(`"23456789 123456789"`)), } var val chan string err := httprequest.UnmarshalJSONResponse(resp, &val) c.Assert(err, gc.ErrorMatches, `json: cannot unmarshal string into Go value of type chan string`) c.Assert(val, gc.IsNil) assertDecodeResponseError(c, err, http.StatusOK, `"23456789 1`) } func assertDecodeResponseError(c *gc.C, err error, status int, body string) { c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httprequest.DecodeResponseError)(nil)) err1 := errgo.Cause(err).(*httprequest.DecodeResponseError) data, err := ioutil.ReadAll(err1.Response.Body) c.Assert(err, gc.IsNil) c.Assert(err1.Response.StatusCode, gc.Equals, status) c.Assert(string(data), gc.Equals, body) } func (*clientSuite) newServer() *httptest.Server { f := func(p httprequest.Params) (clientHandlers, context.Context, error) { return clientHandlers{}, p.Context, nil } handlers := testServer.Handlers(f) router := httprouter.New() for _, h := range handlers { router.Handle(h.Method, h.Path, h.Handle) } return httptest.NewServer(router) } var appendURLTests = []struct { u string p string expect string expectError string }{{ u: "http://foo", p: "bar", expect: "http://foo/bar", }, { u: "http://foo", p: "/bar", expect: "http://foo/bar", }, { u: "http://foo/", p: "bar", expect: "http://foo/bar", }, { u: "http://foo/", p: "/bar", expect: "http://foo/bar", }, { u: "", p: "bar", expect: "/bar", }, { u: "http://xxx", p: "", expect: "http://xxx", }, { u: "http://xxx.com", p: "http://foo.com", expectError: "relative URL specifies a host", }, { u: "http://xxx.com/a/b", p: "foo?a=45&b=c", expect: "http://xxx.com/a/b/foo?a=45&b=c", }, { u: "http://xxx.com", p: "?a=45&b=c", expect: "http://xxx.com?a=45&b=c", }, { u: "http://xxx.com/a?z=w", p: "foo?a=45&b=c", expect: "http://xxx.com/a/foo?z=w&a=45&b=c", }, { u: "http://xxx.com?z=w", p: "/a/b/c", expect: "http://xxx.com/a/b/c?z=w", }} func (*clientSuite) TestAppendURL(c *gc.C) { for i, test := range appendURLTests { c.Logf("test %d: %s %s", i, test.u, test.p) u, err := httprequest.AppendURL(test.u, test.p) if test.expectError != "" { c.Assert(u, gc.IsNil) c.Assert(err, gc.ErrorMatches, test.expectError) } else { c.Assert(err, gc.IsNil) c.Assert(u.String(), gc.Equals, test.expect) } } } type clientHandlers struct{} type chM1Req struct { httprequest.Route `httprequest:"GET /m1/:P"` P string `httprequest:",path"` } type chM1Resp struct { P string } func (clientHandlers) M1(p *chM1Req) (*chM1Resp, error) { return &chM1Resp{p.P}, nil } type chM2Req struct { httprequest.Route `httprequest:"POST /m2/:P"` P string `httprequest:",path"` Body struct { I int } `httprequest:",body"` } type chInvalidM2Req struct { httprequest.Route `httprequest:"POST /m2/:P"` P string `httprequest:",path"` Body struct { I bool } `httprequest:",body"` } type chM2RedirectM2Req struct { httprequest.Route `httprequest:"POST /m2/foo//"` } type chM2Resp struct { P string Arg int } func (clientHandlers) M2(p *chM2Req) (*chM2Resp, error) { return &chM2Resp{p.P, p.Body.I}, nil } type chM3Req struct { httprequest.Route `httprequest:"GET /m3"` } func (clientHandlers) M3(p *chM3Req) error { return errgo.New("m3 error") } type chM4Req struct { httprequest.Route `httprequest:"GET /m4"` } func (clientHandlers) M4(p httprequest.Params, _ *chM4Req) { p.Response.Write([]byte("bad response")) } type chM5Req struct { httprequest.Route `httprequest:"GET /m5"` } func (clientHandlers) M5(p httprequest.Params, _ *chM5Req) { p.Response.WriteHeader(http.StatusTeapot) p.Response.Write([]byte("bad error value")) } type chContentLengthReq struct { httprequest.Route `httprequest:"PUT /content-length"` } func (clientHandlers) ContentLength(rp httprequest.Params, p *chContentLengthReq) (int64, error) { return rp.Request.ContentLength, nil } type doerFunc func(req *http.Request) (*http.Response, error) func (f doerFunc) Do(req *http.Request) (*http.Response, error) { return f(req) } type doerWithContextFunc func(ctx context.Context, req *http.Request) (*http.Response, error) func (f doerWithContextFunc) Do(req *http.Request) (*http.Response, error) { return f(nil, req) } func (f doerWithContextFunc) DoWithContext(ctx context.Context, req *http.Request) (*http.Response, error) { if ctx == nil { panic("unexpected nil context") } return f(ctx, req) } type closeCountingDoer struct { // openBodies records the number of response bodies // that have been returned. openedBodies int // closedBodies records the number of response bodies // that have been closed. closedBodies int } func (doer *closeCountingDoer) Do(req *http.Request) (*http.Response, error) { resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } resp.Body = &closeCountingReader{ doer: doer, ReadCloser: resp.Body, } doer.openedBodies++ return resp, nil } type closeCountingReader struct { doer *closeCountingDoer io.ReadCloser } func (r *closeCountingReader) Close() error { r.doer.closedBodies++ return r.ReadCloser.Close() } // largeReader implements a reader that produces up to total bytes // in 1 byte reads. type largeReader struct { byte byte total int n int } func (r *largeReader) Read(buf []byte) (int, error) { if r.n >= r.total { return 0, io.EOF } r.n++ return copy(buf, []byte{r.byte}), nil } func (r *largeReader) Seek(offset int64, whence int) (int64, error) { if offset != 0 || whence != 0 { panic("unexpected seek") } r.n = 0 return 0, nil } func (r *largeReader) Close() error { // By setting n to zero, we ensure that if there's // a concurrent read, it will also read from n // and so the race detector should pick up the // problem. r.n = 0 return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/client.go�������������������������������������������0000644�0610621�0607500�00000025415�13172163410�024440� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "reflect" "strings" "golang.org/x/net/context" "gopkg.in/errgo.v1" ) // Doer is implemented by HTTP client packages // to make an HTTP request. It is notably implemented // by http.Client and httpbakery.Client. type Doer interface { Do(req *http.Request) (*http.Response, error) } // DoerWithContext is implemented by HTTP clients that can use a context // with the HTTP request. type DoerWithContext interface { DoWithContext(ctx context.Context, req *http.Request) (*http.Response, error) } // Client represents a client that can invoke httprequest endpoints. type Client struct { // BaseURL holds the base URL to use when making // HTTP requests. BaseURL string // Doer holds a value that will be used to actually // make the HTTP request. If it is nil, http.DefaultClient // will be used instead. If Doer implements DoerWithContext, // DoWithContext will be used instead. Doer Doer // If a request returns an HTTP response that signifies an // error, UnmarshalError is used to unmarshal the response into // an appropriate error. See ErrorUnmarshaler for a convenient // way to create an UnmarshalError function for a given type. If // this is nil, DefaultErrorUnmarshaler will be used. UnmarshalError func(resp *http.Response) error } // DefaultErrorUnmarshaler is the default error unmarshaler // used by Client. var DefaultErrorUnmarshaler = ErrorUnmarshaler(new(RemoteError)) // Call invokes the endpoint implied by the given params, // which should be of the form accepted by the ArgT // argument to a function passed to Handle, and // unmarshals the response into the given response parameter, // which should be a pointer to the response value. // // If params implements the HeaderSetter interface, its SetHeader method // will be called to add additional headers to the HTTP request. // // If resp is nil, the response will be ignored if the // request was successful. // // If resp is of type **http.Response, instead of unmarshaling // into it, its element will be set to the returned HTTP // response directly and the caller is responsible for // closing its Body field. // // Any error that c.UnmarshalError or c.Doer returns will not // have its cause masked. // // If the request returns a response with a status code signifying // success, but the response could not be unmarshaled, a // *DecodeResponseError will be returned holding the response. Note that if // the request returns an error status code, the Client.UnmarshalError // function is responsible for doing this if desired (the default error // unmarshal functions do). func (c *Client) Call(ctx context.Context, params, resp interface{}) error { return c.CallURL(ctx, c.BaseURL, params, resp) } // CallURL is like Call except that the given URL is used instead of // c.BaseURL. func (c *Client) CallURL(ctx context.Context, url string, params, resp interface{}) error { rt, err := getRequestType(reflect.TypeOf(params)) if err != nil { return errgo.Mask(err) } if rt.method == "" { return errgo.Newf("type %T has no httprequest.Route field", params) } reqURL, err := appendURL(url, rt.path) if err != nil { return errgo.Mask(err) } req, err := Marshal(reqURL.String(), rt.method, params) if err != nil { return errgo.Mask(err) } return c.Do(ctx, req, resp) } // Do sends the given request and unmarshals its JSON // result into resp, which should be a pointer to the response value. // If an error status is returned, the error will be unmarshaled // as in Client.Call. // // If resp is nil, the response will be ignored if the response was // successful. // // If resp is of type **http.Response, instead of unmarshaling // into it, its element will be set to the returned HTTP // response directly and the caller is responsible for // closing its Body field. // // Any error that c.UnmarshalError or c.Doer returns will not // have its cause masked. // // If req.URL does not have a host part it will be treated as relative to // c.BaseURL. req.URL will be updated to the actual URL used. // // If the response cannot by unmarshaled, a *DecodeResponseError // will be returned holding the response from the request. // the entire response body. func (c *Client) Do(ctx context.Context, req *http.Request, resp interface{}) error { if req.URL.Host == "" { var err error req.URL, err = appendURL(c.BaseURL, req.URL.String()) if err != nil { return errgo.Mask(err) } } doer := c.Doer if doer == nil { doer = http.DefaultClient } var httpResp *http.Response var err error if ctxDoer, ok := doer.(DoerWithContext); ok { httpResp, err = ctxDoer.DoWithContext(ctx, req) } else { httpResp, err = doer.Do(requestWithContext(req, ctx)) } if err != nil { return errgo.Mask(urlError(err, req), errgo.Any) } return c.unmarshalResponse(httpResp, resp) } // Get is a convenience method that uses c.Do to issue a GET request to // the given URL. If the given URL does not have a host part then it will // be treated as relative to c.BaseURL. func (c *Client) Get(ctx context.Context, url string, resp interface{}) error { req, err := http.NewRequest("GET", url, nil) if err != nil { return errgo.Notef(err, "cannot make request") } return c.Do(ctx, req, resp) } // unmarshalResponse unmarshals an HTTP response into the given value. func (c *Client) unmarshalResponse(httpResp *http.Response, resp interface{}) error { if 200 <= httpResp.StatusCode && httpResp.StatusCode < 300 { if respPt, ok := resp.(**http.Response); ok { *respPt = httpResp return nil } defer httpResp.Body.Close() if err := UnmarshalJSONResponse(httpResp, resp); err != nil { return errgo.Mask(urlError(err, httpResp.Request), isDecodeResponseError) } return nil } defer httpResp.Body.Close() errUnmarshaler := c.UnmarshalError if errUnmarshaler == nil { errUnmarshaler = DefaultErrorUnmarshaler } err := errUnmarshaler(httpResp) if err == nil { err = errgo.Newf("unexpected HTTP response status: %s", httpResp.Status) } return errgo.Mask(urlError(err, httpResp.Request), errgo.Any) } // ErrorUnmarshaler returns a function which will unmarshal error // responses into new values of the same type as template. The argument // must be a pointer. A new instance of it is created every time the // returned function is called. // // If the error cannot by unmarshaled, the function will return an // *HTTPResponseError holding the response from the request. func ErrorUnmarshaler(template error) func(*http.Response) error { t := reflect.TypeOf(template) if t.Kind() != reflect.Ptr { panic(errgo.Newf("cannot unmarshal errors into value of type %T", template)) } t = t.Elem() return func(resp *http.Response) error { if 300 <= resp.StatusCode && resp.StatusCode < 400 { // It's a redirection error. loc, _ := resp.Location() return newDecodeResponseError(resp, nil, fmt.Errorf("unexpected redirect (status %s) from %q to %q", resp.Status, resp.Request.URL, loc)) } errv := reflect.New(t) if err := UnmarshalJSONResponse(resp, errv.Interface()); err != nil { return errgo.NoteMask(err, fmt.Sprintf("cannot unmarshal error response (status %s)", resp.Status), isDecodeResponseError) } return errv.Interface().(error) } } // UnmarshalJSONResponse unmarshals the given HTTP response // into x, which should be a pointer to the result to be // unmarshaled into. // // If the response cannot be unmarshaled, an error of type // *DecodeResponseError will be returned. func UnmarshalJSONResponse(resp *http.Response, x interface{}) error { if x == nil { return nil } if !isJSONMediaType(resp.Header) { fancyErr := newFancyDecodeError(resp.Header, resp.Body) return newDecodeResponseError(resp, fancyErr.body, fancyErr) } // Read enough data that we can produce a plausible-looking // possibly-truncated response body in the error. var buf bytes.Buffer n, err := io.Copy(&buf, io.LimitReader(resp.Body, int64(maxErrorBodySize))) bodyData := buf.Bytes() if err != nil { return newDecodeResponseError(resp, bodyData, errgo.Notef(err, "error reading response body")) } if n < int64(maxErrorBodySize) { // We've read all the data; unmarshal it. if err := json.Unmarshal(bodyData, x); err != nil { return newDecodeResponseError(resp, bodyData, err) } return nil } // The response is longer than maxErrorBodySize; stitch the read // bytes together with the body so that we can still read // bodies larger than maxErrorBodySize. dec := json.NewDecoder(io.MultiReader(&buf, resp.Body)) // Try to read all the body so that we can reuse the // connection, but don't try *too* hard. Note that the // usual number of additional bytes is 1 (a single newline // after the JSON). defer io.Copy(ioutil.Discard, io.LimitReader(resp.Body, 8*1024)) if err := dec.Decode(x); err != nil { return newDecodeResponseError(resp, bodyData, err) } return nil } // RemoteError holds the default type of a remote error // used by Client when no custom error unmarshaler // is set. type RemoteError struct { // Message holds the error message. Message string // Code may hold a code that classifies the error. Code string `json:",omitempty"` // Info holds any other information associated with the error. Info *json.RawMessage `json:",omitempty"` } // Error implements the error interface. func (e *RemoteError) Error() string { if e.Message == "" { return "httprequest: no error message found" } return e.Message } // appendURL returns the result of combining the // given base URL and relative URL. // // The path of the relative URL will be appended // to the base URL, separated by a slash (/) if // needed. // // Any query parameters will be concatenated together. // // appendURL will return an error if relURLStr contains // a host name. func appendURL(baseURLStr, relURLStr string) (*url.URL, error) { b, err := url.Parse(baseURLStr) if err != nil { return nil, errgo.Notef(err, "cannot parse %q", baseURLStr) } r, err := url.Parse(relURLStr) if err != nil { return nil, errgo.Notef(err, "cannot parse %q", relURLStr) } if r.Host != "" { return nil, errgo.Newf("relative URL specifies a host") } if r.Path != "" { b.Path = strings.TrimSuffix(b.Path, "/") + "/" + strings.TrimPrefix(r.Path, "/") } if r.RawQuery != "" { if b.RawQuery != "" { b.RawQuery += "&" + r.RawQuery } else { b.RawQuery = r.RawQuery } } return b, nil } func urlError(err error, req *http.Request) error { _, ok := errgo.Cause(err).(*url.Error) if ok { // The error is already sufficiently annotated. return err } // Convert the method to mostly lower case to match net/http's behaviour // so we don't get silly divergence of messages. method := req.Method[:1] + strings.ToLower(req.Method[1:]) return errgo.NoteMask(err, fmt.Sprintf("%s %s", method, req.URL), errgo.Any) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/bench_test.go���������������������������������������0000644�0610621�0607500�00000030233�13172163410�025272� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package httprequest_test import ( "fmt" "net/http" "net/http/httptest" "net/url" "reflect" "strconv" "testing" "time" "github.com/julienschmidt/httprouter" "gopkg.in/errgo.v1" "github.com/juju/httprequest" ) const dateFormat = "2006-01-02" type testResult struct { Key string `json:",omitempty"` Date string `json:",omitempty"` Count int64 } type testParams2Fields struct { Id string `httprequest:"id,path"` Limit int `httprequest:"limit,form"` } type testParams4Fields struct { Id string `httprequest:"id,path"` Limit int `httprequest:"limit,form"` From dateTime `httprequest:"from,form"` To dateTime `httprequest:"to,form"` } type dateTime struct { time.Time } func (dt *dateTime) UnmarshalText(b []byte) (err error) { dt.Time, err = time.Parse(dateFormat, string(b)) return } type testParams2StringFields struct { Field0 string `httprequest:",form"` Field1 string `httprequest:",form"` } type testParams4StringFields struct { Field0 string `httprequest:",form"` Field1 string `httprequest:",form"` Field2 string `httprequest:",form"` Field3 string `httprequest:",form"` } type testParams8StringFields struct { Field0 string `httprequest:",form"` Field1 string `httprequest:",form"` Field2 string `httprequest:",form"` Field3 string `httprequest:",form"` Field4 string `httprequest:",form"` Field5 string `httprequest:",form"` Field6 string `httprequest:",form"` Field7 string `httprequest:",form"` } type testParams16StringFields struct { Field0 string `httprequest:",form"` Field1 string `httprequest:",form"` Field2 string `httprequest:",form"` Field3 string `httprequest:",form"` Field4 string `httprequest:",form"` Field5 string `httprequest:",form"` Field6 string `httprequest:",form"` Field7 string `httprequest:",form"` Field8 string `httprequest:",form"` Field9 string `httprequest:",form"` Field10 string `httprequest:",form"` Field11 string `httprequest:",form"` Field12 string `httprequest:",form"` Field13 string `httprequest:",form"` Field14 string `httprequest:",form"` Field15 string `httprequest:",form"` } func BenchmarkUnmarshal2Fields(b *testing.B) { params := httprequest.Params{ Request: &http.Request{ Form: url.Values{ "limit": {"2000"}, }, }, PathVar: httprouter.Params{{ Key: "id", Value: "someid", }}, } var arg testParams2Fields b.ResetTimer() for i := 0; i < b.N; i++ { arg = testParams2Fields{} err := httprequest.Unmarshal(params, &arg) if err != nil { b.Fatalf("unmarshal failed: %v", err) } } b.StopTimer() if !reflect.DeepEqual(arg, testParams2Fields{ Id: "someid", Limit: 2000, }) { b.Errorf("unexpected result: got %#v", arg) } } func BenchmarkHandle2FieldsTrad(b *testing.B) { results := []testResult{} benchmarkHandle2Fields(b, testServer.HandleJSON(func(p httprequest.Params) (interface{}, error) { limit := -1 if limitStr := p.Request.Form.Get("limit"); limitStr != "" { var err error limit, err = strconv.Atoi(limitStr) if err != nil || limit <= 0 { panic("unreachable") } } if id := p.PathVar.ByName("id"); id == "" { panic("unreachable") } return results, nil })) } func BenchmarkHandle2Fields(b *testing.B) { results := []testResult{} benchmarkHandle2Fields(b, testServer.Handle(func(p httprequest.Params, arg *testParams2Fields) ([]testResult, error) { if arg.Limit <= 0 { panic("unreachable") } return results, nil }).Handle) } func BenchmarkHandle2FieldsUnmarshalOnly(b *testing.B) { results := []testResult{} benchmarkHandle2Fields(b, testServer.HandleJSON(func(p httprequest.Params) (interface{}, error) { var arg testParams2Fields if err := httprequest.Unmarshal(p, &arg); err != nil { return nil, err } if arg.Limit <= 0 { panic("unreachable") } return results, nil })) } func benchmarkHandle2Fields(b *testing.B, handle func(w http.ResponseWriter, req *http.Request, pvar httprouter.Params)) { rec := httptest.NewRecorder() params := httprequest.Params{ Request: &http.Request{ Form: url.Values{ "limit": {"2000"}, }, }, PathVar: httprouter.Params{{ Key: "id", Value: "someid", }}, } b.ResetTimer() for i := 0; i < b.N; i++ { rec.Body.Reset() handle(rec, params.Request, params.PathVar) } } func BenchmarkUnmarshal4Fields(b *testing.B) { fromDate, err1 := time.Parse(dateFormat, "2010-10-10") toDate, err2 := time.Parse(dateFormat, "2011-11-11") if err1 != nil || err2 != nil { b.Fatalf("bad times") } type P testParams4Fields params := httprequest.Params{ Request: &http.Request{ Form: url.Values{ "limit": {"2000"}, "from": {fromDate.Format(dateFormat)}, "to": {toDate.Format(dateFormat)}, }, }, PathVar: httprouter.Params{{ Key: "id", Value: "someid", }}, } var args P b.ResetTimer() for i := 0; i < b.N; i++ { args = P{} err := httprequest.Unmarshal(params, &args) if err != nil { b.Fatalf("unmarshal failed: %v", err) } } b.StopTimer() if !reflect.DeepEqual(args, P{ Id: "someid", Limit: 2000, From: dateTime{fromDate}, To: dateTime{toDate}, }) { b.Errorf("unexpected result: got %#v", args) } } func BenchmarkHandle4FieldsTrad(b *testing.B) { results := []testResult{} benchmarkHandle4Fields(b, testServer.HandleJSON(func(p httprequest.Params) (interface{}, error) { start, stop, err := parseDateRange(p.Request.Form) if err != nil { panic("unreachable") } _ = start _ = stop limit := -1 if limitStr := p.Request.Form.Get("limit"); limitStr != "" { limit, err = strconv.Atoi(limitStr) if err != nil || limit <= 0 { panic("unreachable") } } if id := p.PathVar.ByName("id"); id == "" { panic("unreachable") } return results, nil })) } // parseDateRange parses a date range as specified in an http // request. The returned times will be zero if not specified. func parseDateRange(form url.Values) (start, stop time.Time, err error) { if v := form.Get("start"); v != "" { var err error start, err = time.Parse(dateFormat, v) if err != nil { return time.Time{}, time.Time{}, errgo.Newf("invalid 'start' value %q", v) } } if v := form.Get("stop"); v != "" { var err error stop, err = time.Parse(dateFormat, v) if err != nil { return time.Time{}, time.Time{}, errgo.Newf("invalid 'stop' value %q", v) } // Cover all timestamps within the stop day. stop = stop.Add(24*time.Hour - 1*time.Second) } return } func BenchmarkHandle4Fields(b *testing.B) { results := []testResult{} benchmarkHandle4Fields(b, testServer.Handle(func(p httprequest.Params, arg *testParams4Fields) ([]testResult, error) { if arg.To.Before(arg.From.Time) { panic("unreachable") } if arg.Limit <= 0 { panic("unreachable") } return results, nil }).Handle) } func BenchmarkHandle4FieldsUnmarshalOnly(b *testing.B) { results := []testResult{} benchmarkHandle4Fields(b, testServer.HandleJSON(func(p httprequest.Params) (interface{}, error) { var arg testParams4Fields if err := httprequest.Unmarshal(p, &arg); err != nil { return nil, err } if arg.To.Before(arg.From.Time) { panic("unreachable") } if arg.Limit <= 0 { panic("unreachable") } return results, nil })) } func benchmarkHandle4Fields(b *testing.B, handle func(w http.ResponseWriter, req *http.Request, pvar httprouter.Params)) { // example taken from charmstore changes/published endpoint fromDate, err1 := time.Parse(dateFormat, "2010-10-10") toDate, err2 := time.Parse(dateFormat, "2011-11-11") if err1 != nil || err2 != nil { b.Fatalf("bad times") } rec := httptest.NewRecorder() params := httprequest.Params{ Request: &http.Request{ Form: url.Values{ "limit": {"2000"}, "from": {fromDate.Format(dateFormat)}, "to": {toDate.Format(dateFormat)}, }, }, PathVar: httprouter.Params{{ Key: "id", Value: "someid", }}, } b.ResetTimer() for i := 0; i < b.N; i++ { rec.Body.Reset() handle(rec, params.Request, params.PathVar) } } func BenchmarkHandle2StringFields(b *testing.B) { benchmarkHandleNFields(b, 2, testServer.Handle(func(p httprequest.Params, arg *testParams2StringFields) error { return nil }).Handle) } func BenchmarkHandle2StringFieldsUnmarshalOnly(b *testing.B) { benchmarkHandleNFields(b, 2, testServer.HandleErrors(func(p httprequest.Params) error { var arg testParams2StringFields return httprequest.Unmarshal(p, &arg) })) } func BenchmarkHandle2StringFieldsTrad(b *testing.B) { benchmarkHandleNFields(b, 2, testServer.HandleErrors(func(p httprequest.Params) error { var arg testParams2StringFields arg.Field0 = p.Request.Form.Get("Field0") arg.Field1 = p.Request.Form.Get("Field1") return nil })) } func BenchmarkHandle4StringFields(b *testing.B) { benchmarkHandleNFields(b, 4, testServer.Handle(func(p httprequest.Params, arg *testParams4StringFields) error { return nil }).Handle) } func BenchmarkHandle4StringFieldsUnmarshalOnly(b *testing.B) { benchmarkHandleNFields(b, 4, testServer.HandleErrors(func(p httprequest.Params) error { var arg testParams4StringFields return httprequest.Unmarshal(p, &arg) })) } func BenchmarkHandle4StringFieldsTrad(b *testing.B) { benchmarkHandleNFields(b, 4, testServer.HandleErrors(func(p httprequest.Params) error { var arg testParams4StringFields arg.Field0 = p.Request.Form.Get("Field0") arg.Field1 = p.Request.Form.Get("Field1") arg.Field2 = p.Request.Form.Get("Field2") arg.Field3 = p.Request.Form.Get("Field3") return nil })) } func BenchmarkHandle8StringFields(b *testing.B) { benchmarkHandleNFields(b, 8, testServer.Handle(func(p httprequest.Params, arg *testParams8StringFields) error { return nil }).Handle) } func BenchmarkHandle8StringFieldsUnmarshalOnly(b *testing.B) { benchmarkHandleNFields(b, 8, testServer.HandleErrors(func(p httprequest.Params) error { var arg testParams8StringFields return httprequest.Unmarshal(p, &arg) })) } func BenchmarkHandle8StringFieldsTrad(b *testing.B) { benchmarkHandleNFields(b, 8, testServer.HandleErrors(func(p httprequest.Params) error { var arg testParams8StringFields arg.Field0 = p.Request.Form.Get("Field0") arg.Field1 = p.Request.Form.Get("Field1") arg.Field2 = p.Request.Form.Get("Field2") arg.Field3 = p.Request.Form.Get("Field3") arg.Field4 = p.Request.Form.Get("Field4") arg.Field5 = p.Request.Form.Get("Field5") arg.Field6 = p.Request.Form.Get("Field6") arg.Field7 = p.Request.Form.Get("Field7") return nil })) } func BenchmarkHandle16StringFields(b *testing.B) { benchmarkHandleNFields(b, 16, testServer.Handle(func(p httprequest.Params, arg *testParams16StringFields) error { return nil }).Handle) } func BenchmarkHandle16StringFieldsUnmarshalOnly(b *testing.B) { benchmarkHandleNFields(b, 16, testServer.HandleErrors(func(p httprequest.Params) error { var arg testParams16StringFields return httprequest.Unmarshal(p, &arg) })) } func BenchmarkHandle16StringFieldsTrad(b *testing.B) { benchmarkHandleNFields(b, 16, testServer.HandleErrors(func(p httprequest.Params) error { var arg testParams16StringFields arg.Field0 = p.Request.Form.Get("Field0") arg.Field1 = p.Request.Form.Get("Field1") arg.Field2 = p.Request.Form.Get("Field2") arg.Field3 = p.Request.Form.Get("Field3") arg.Field4 = p.Request.Form.Get("Field4") arg.Field5 = p.Request.Form.Get("Field5") arg.Field6 = p.Request.Form.Get("Field6") arg.Field7 = p.Request.Form.Get("Field7") arg.Field8 = p.Request.Form.Get("Field8") arg.Field9 = p.Request.Form.Get("Field9") arg.Field10 = p.Request.Form.Get("Field10") arg.Field11 = p.Request.Form.Get("Field11") arg.Field12 = p.Request.Form.Get("Field12") arg.Field13 = p.Request.Form.Get("Field13") arg.Field14 = p.Request.Form.Get("Field14") arg.Field15 = p.Request.Form.Get("Field15") return nil })) } func benchmarkHandleNFields(b *testing.B, n int, handle func(w http.ResponseWriter, req *http.Request, pvar httprouter.Params)) { form := make(url.Values) for i := 0; i < n; i++ { form[fmt.Sprint("Field", i)] = []string{fmt.Sprintf("field %d", i)} } rec := httptest.NewRecorder() params := httprequest.Params{ Request: &http.Request{ Form: form, }, } b.ResetTimer() for i := 0; i < b.N; i++ { rec.Body.Reset() handle(rec, params.Request, params.PathVar) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/README.md�������������������������������������������0000644�0610621�0607500�00000015407�13172163410�024112� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# httprequest -- import "github.com/juju/httprequest" Package httprequest provides functionality for unmarshaling HTTP request parameters into a struct type. Please note that the API is not considered stable at this point and may be changed in a backwardly incompatible manner at any time. ## Usage ```go var ( ErrUnmarshal = errgo.New("httprequest unmarshal error") ErrBadUnmarshalType = errgo.New("httprequest bad unmarshal type") ) ``` #### func Marshal ```go func Marshal(baseURL, method string, x interface{}) (*http.Request, error) ``` Marshal is the counterpart of Unmarshal. It takes information from x, which must be a pointer to a struct, and returns an HTTP request using the given method that holds all of the information The HTTP request will use the given method. Named fields in the given baseURL will be filled out from "path"-tagged fields in x to form the URL path in the returned request. These are specified as for httprouter. If a field in baseURL is a suffix of the form "*var" (a trailing wildcard element that holds the rest of the path), the marshaled string must begin with a "/". This matches the httprouter convention that it always returns such fields with a "/" prefix. If a field is of type string or []string, the value of the field will be used directly; otherwise if implements encoding.TextMarshaler, that will be used to marshal the field, otherwise fmt.Sprint will be used. For example, this code: type UserDetails struct { Age int } type Test struct { Username string `httprequest:"user,path"` ContextId int64 `httprequest:"context,form"` Details UserDetails `httprequest:",body"` } req, err := Marshal("GET", "http://example.com/users/:user/details", &Test{ Username: "bob", ContextId: 1234, Details: UserDetails{ Age: 36, } }) if err != nil { ... } will produce an HTTP request req with a URL of http://example.com/users/bob/details?context=1234 and a JSON-encoded body holding `{"Age":36}`. It is an error if there is a field specified in the URL that is not found in x. #### func ToHTTP ```go func ToHTTP(h httprouter.Handle) http.Handler ``` ToHTTP converts an httprouter.Handle into an http.Handler. It will pass no path variables to h. #### func Unmarshal ```go func Unmarshal(p Params, x interface{}) error ``` Unmarshal takes values from given parameters and fills out fields in x, which must be a pointer to a struct. Tags on the struct's fields determine where each field is filled in from. Similar to encoding/json and other encoding packages, the tag holds a comma-separated list. The first item in the list is an alternative name for the field (the field name itself will be used if this is empty). The next item specifies where the field is filled in from. It may be: "path" - the field is taken from a parameter in p.PathVar with a matching field name. "form" - the field is taken from the given name in p.Form (note that this covers both URL query parameters and POST form parameters) "body" - the field is filled in by parsing the request body as JSON. For path and form parameters, the field will be filled out from the field in p.PathVar or p.Form using one of the following methods (in descending order of preference): - if the type is string, it will be set from the first value. - if the type is []string, it will be filled out using all values for that field (allowed only for form) - if the type implements encoding.TextUnmarshaler, its UnmarshalText method will be used - otherwise fmt.Sscan will be used to set the value. When the unmarshaling fails, Unmarshal returns an error with an ErrUnmarshal cause. If the type of x is inappropriate, it returns an error with an ErrBadUnmarshalType cause. #### func WriteJSON ```go func WriteJSON(w http.ResponseWriter, code int, val interface{}) error ``` WriteJSON writes the given value to the ResponseWriter and sets the HTTP status to the given code. #### type ErrorHandler ```go type ErrorHandler func(http.ResponseWriter, Params) error ``` ErrorHandler is like httprouter.Handle except it returns an error which may be returned as the error body of the response. An ErrorHandler function should not itself write to the ResponseWriter if it returns an error. #### type ErrorMapper ```go type ErrorMapper func(err error) (httpStatus int, errorBody interface{}) ``` ErrorMapper holds a function that can convert a Go error into a form that can be returned as a JSON body from an HTTP request. The httpStatus value reports the desired HTTP status. #### func (ErrorMapper) Handle ```go func (e ErrorMapper) Handle(f interface{}) httprouter.Handle ``` Handle converts a function into an httprouter.Handle. The argument f must be a function of one of the following three forms, where ArgT must be a struct type acceptable to Unmarshal and ResultT is a type that can be marshaled as JSON: func(w http.ResponseWriter, p Params, arg *ArgT) func(w http.ResponseWriter, p Params, arg *ArgT) error func(header http.Header, p Params, arg *ArgT) (ResultT, error) When processing a call to the returned handler, the provided parameters are unmarshaled into a new ArgT value using Unmarshal, then f is called with this value. If the unmarshaling fails, f will not be called and the unmarshal error will be written as a JSON response. If an error is returned from f, it is passed through the error mapper before writing as a JSON response. In the third form, when no error is returned, the result is written as a JSON response with status http.StatusOK. Handle will panic if the provided function is not in one of the above forms. #### func (ErrorMapper) HandleErrors ```go func (e ErrorMapper) HandleErrors(handle ErrorHandler) httprouter.Handle ``` HandleErrors returns a handler that passes any non-nil error returned by handle through the error mapper and writes it as a JSON response. #### func (ErrorMapper) HandleJSON ```go func (e ErrorMapper) HandleJSON(handle JSONHandler) httprouter.Handle ``` HandleJSON returns a handler that writes the return value of handle as a JSON response. If handle returns an error, it is passed through the error mapper. #### func (ErrorMapper) WriteError ```go func (e ErrorMapper) WriteError(w http.ResponseWriter, err error) ``` WriteError writes an error to a ResponseWriter and sets the HTTP status code. #### type JSONHandler ```go type JSONHandler func(http.Header, Params) (interface{}, error) ``` JSONHandler is like httprouter.Handle except that it returns a body (to be converted to JSON) and an error. The Header parameter can be used to set custom headers on the response. #### type Params ```go type Params struct { *http.Request PathVar httprouter.Params } ``` Params holds request parameters that can be unmarshaled into a struct. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/httprequest/LICENSE���������������������������������������������0000644�0610621�0607500�00000021053�13172163410�023632� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/����������������������������������������������������������0000755�0610621�0607500�00000000000�13172163311�021343� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/writer_test.go��������������������������������������������0000644�0610621�0607500�00000001334�13172163311�024246� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "bytes" "time" gc "gopkg.in/check.v1" "github.com/juju/loggo" ) type SimpleWriterSuite struct{} var _ = gc.Suite(&SimpleWriterSuite{}) func (s *SimpleWriterSuite) TestNewSimpleWriter(c *gc.C) { now := time.Now() formatter := func(entry loggo.Entry) string { return "<< " + entry.Message + " >>" } buf := &bytes.Buffer{} writer := loggo.NewSimpleWriter(buf, formatter) writer.Write(loggo.Entry{ Level: loggo.INFO, Module: "test", Filename: "somefile.go", Line: 12, Timestamp: now, Message: "a message", }) c.Check(buf.String(), gc.Equals, "<< a message >>\n") } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/writer.go�������������������������������������������������0000644�0610621�0607500�00000003376�13172163311�023217� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import ( "fmt" "io" "os" ) // DefaultWriterName is the name of the default writer for // a Context. const DefaultWriterName = "default" // Writer is implemented by any recipient of log messages. type Writer interface { // Write writes a message to the Writer with the given level and module // name. The filename and line hold the file name and line number of the // code that is generating the log message; the time stamp holds the time // the log message was generated, and message holds the log message // itself. Write(entry Entry) } // NewMinLevelWriter returns a Writer that will only pass on the Write calls // to the provided writer if the log level is at or above the specified // minimum level. func NewMinimumLevelWriter(writer Writer, minLevel Level) Writer { return &minLevelWriter{ writer: writer, level: minLevel, } } type minLevelWriter struct { writer Writer level Level } // Write writes the log record. func (w minLevelWriter) Write(entry Entry) { if entry.Level < w.level { return } w.writer.Write(entry) } type simpleWriter struct { writer io.Writer formatter func(entry Entry) string } // NewSimpleWriter returns a new writer that writes log messages to the given // io.Writer formatting the messages with the given formatter. func NewSimpleWriter(writer io.Writer, formatter func(entry Entry) string) Writer { if formatter == nil { formatter = DefaultFormatter } return &simpleWriter{writer, formatter} } func (simple *simpleWriter) Write(entry Entry) { logLine := simple.formatter(entry) fmt.Fprintln(simple.writer, logLine) } func defaultWriter() Writer { return NewSimpleWriter(os.Stderr, DefaultFormatter) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/util_test.go����������������������������������������������0000644�0610621�0607500�00000003161�13172163311�023707� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "fmt" "io/ioutil" "strings" "github.com/juju/loggo" gc "gopkg.in/check.v1" ) func init() { setLocationsForTags("logging_test.go") setLocationsForTags("writer_test.go") } func assertLocation(c *gc.C, msg loggo.Entry, tag string) { loc := location(tag) c.Assert(msg.Filename, gc.Equals, loc.file) c.Assert(msg.Line, gc.Equals, loc.line) } // All this location stuff is to avoid having hard coded line numbers // in the tests. Any line where as a test writer you want to capture the // file and line number, add a comment that has `//tag name` as the end of // the line. The name must be unique across all the tests, and the test // will panic if it is not. This name is then used to read the actual // file and line numbers. func location(tag string) Location { loc, ok := tagToLocation[tag] if !ok { panic(fmt.Errorf("tag %q not found", tag)) } return loc } type Location struct { file string line int } func (loc Location) String() string { return fmt.Sprintf("%s:%d", loc.file, loc.line) } var tagToLocation = make(map[string]Location) func setLocationsForTags(filename string) { data, err := ioutil.ReadFile(filename) if err != nil { panic(err) } lines := strings.Split(string(data), "\n") for i, line := range lines { if j := strings.Index(line, "//tag "); j >= 0 { tag := line[j+len("//tag "):] if _, found := tagToLocation[tag]; found { panic(fmt.Errorf("tag %q already processed previously")) } tagToLocation[tag] = Location{file: filename, line: i + 1} } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/testwriter.go���������������������������������������������0000644�0610621�0607500�00000001653�13172163311�024113� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import ( "path" "sync" ) // TestWriter is a useful Writer for testing purposes. Each component of the // logging message is stored in the Log array. type TestWriter struct { mu sync.Mutex log []Entry } // Write saves the params as members in the TestLogValues struct appended to the Log array. func (writer *TestWriter) Write(entry Entry) { writer.mu.Lock() defer writer.mu.Unlock() entry.Filename = path.Base(entry.Filename) writer.log = append(writer.log, entry) } // Clear removes any saved log messages. func (writer *TestWriter) Clear() { writer.mu.Lock() defer writer.mu.Unlock() writer.log = nil } // Log returns a copy of the current logged values. func (writer *TestWriter) Log() []Entry { writer.mu.Lock() defer writer.mu.Unlock() v := make([]Entry, len(writer.log)) copy(v, writer.log) return v } �������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/package_test.go�������������������������������������������0000644�0610621�0607500�00000000316�13172163311�024324� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "testing" gc "gopkg.in/check.v1" ) func Test(t *testing.T) { gc.TestingT(t) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/module.go�������������������������������������������������0000644�0610621�0607500�00000002533�13172163311�023162� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo // Do not change rootName: modules.resolve() will misbehave if it isn't "". const ( rootString = "<root>" defaultRootLevel = WARNING defaultLevel = UNSPECIFIED ) type module struct { name string level Level parent *module context *Context } // Name returns the module's name. func (module *module) Name() string { if module.name == "" { return rootString } return module.name } func (m *module) willWrite(level Level) bool { if level < TRACE || level > CRITICAL { return false } return level >= m.getEffectiveLogLevel() } func (module *module) getEffectiveLogLevel() Level { // Note: the root module is guaranteed to have a // specified logging level, so acts as a suitable sentinel // for this loop. for { if level := module.level.get(); level != UNSPECIFIED { return level } module = module.parent } panic("unreachable") } // setLevel sets the severity level of the given module. // The root module cannot be set to UNSPECIFIED level. func (module *module) setLevel(level Level) { // The root module can't be unspecified. if module.name == "" && level == UNSPECIFIED { level = WARNING } module.level.set(level) } func (m *module) write(entry Entry) { entry.Module = m.name m.context.write(entry) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/loggocolor/�����������������������������������������������0000755�0610621�0607500�00000000000�13172163311�023511� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/loggocolor/writer.go��������������������������������������0000644�0610621�0607500�00000002740�13172163311�025357� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package loggocolor import ( "fmt" "io" "path/filepath" "github.com/juju/loggo" "github.com/juju/ansiterm" ) var ( // SeverityColor defines the colors for the levels output by the ColorWriter. SeverityColor = map[loggo.Level]*ansiterm.Context{ loggo.TRACE: ansiterm.Foreground(ansiterm.Default), loggo.DEBUG: ansiterm.Foreground(ansiterm.Green), loggo.INFO: ansiterm.Foreground(ansiterm.BrightBlue), loggo.WARNING: ansiterm.Foreground(ansiterm.Yellow), loggo.ERROR: ansiterm.Foreground(ansiterm.BrightRed), loggo.CRITICAL: &ansiterm.Context{ Foreground: ansiterm.White, Background: ansiterm.Red, }, } // LocationColor defines the colors for the location output by the ColorWriter. LocationColor = ansiterm.Foreground(ansiterm.BrightBlue) ) type colorWriter struct { writer *ansiterm.Writer } // NewColorWriter will write out colored severity levels if the writer is // outputting to a terminal. func NewWriter(writer io.Writer) loggo.Writer { return &colorWriter{ansiterm.NewWriter(writer)} } // Write implements Writer. func (w *colorWriter) Write(entry loggo.Entry) { ts := entry.Timestamp.Format(loggo.TimeFormat) // Just get the basename from the filename filename := filepath.Base(entry.Filename) fmt.Fprintf(w.writer, "%s ", ts) SeverityColor[entry.Level].Fprintf(w.writer, entry.Level.Short()) fmt.Fprintf(w.writer, " %s ", entry.Module) LocationColor.Fprintf(w.writer, "%s:%d ", filename, entry.Line) fmt.Fprintln(w.writer, entry.Message) } ��������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/logging_test.go�������������������������������������������0000644�0610621�0607500�00000004765�13172163311�024373� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "time" gc "gopkg.in/check.v1" "github.com/juju/loggo" ) type LoggingSuite struct { context *loggo.Context writer *writer logger loggo.Logger } var _ = gc.Suite(&LoggingSuite{}) func (s *LoggingSuite) SetUpTest(c *gc.C) { s.writer = &writer{} s.context = loggo.NewContext(loggo.TRACE) s.context.AddWriter("test", s.writer) s.logger = s.context.GetLogger("test") } func (s *LoggingSuite) TestLoggingStrings(c *gc.C) { s.logger.Infof("simple") s.logger.Infof("with args %d", 42) s.logger.Infof("working 100%") s.logger.Infof("missing %s") checkLogEntries(c, s.writer.Log(), []loggo.Entry{ {Level: loggo.INFO, Module: "test", Message: "simple"}, {Level: loggo.INFO, Module: "test", Message: "with args 42"}, {Level: loggo.INFO, Module: "test", Message: "working 100%"}, {Level: loggo.INFO, Module: "test", Message: "missing %s"}, }) } func (s *LoggingSuite) TestLoggingLimitWarning(c *gc.C) { s.logger.SetLogLevel(loggo.WARNING) start := time.Now() logAllSeverities(s.logger) end := time.Now() entries := s.writer.Log() checkLogEntries(c, entries, []loggo.Entry{ {Level: loggo.CRITICAL, Module: "test", Message: "something critical"}, {Level: loggo.ERROR, Module: "test", Message: "an error"}, {Level: loggo.WARNING, Module: "test", Message: "a warning message"}, }) for _, entry := range entries { c.Check(entry.Timestamp, Between(start, end)) } } func (s *LoggingSuite) TestLocationCapture(c *gc.C) { s.logger.Criticalf("critical message") //tag critical-location s.logger.Errorf("error message") //tag error-location s.logger.Warningf("warning message") //tag warning-location s.logger.Infof("info message") //tag info-location s.logger.Debugf("debug message") //tag debug-location s.logger.Tracef("trace message") //tag trace-location log := s.writer.Log() tags := []string{ "critical-location", "error-location", "warning-location", "info-location", "debug-location", "trace-location", } c.Assert(log, gc.HasLen, len(tags)) for x := range tags { assertLocation(c, log[x], tags[x]) } } func (s *LoggingSuite) TestLogDoesntLogWeirdLevels(c *gc.C) { s.logger.Logf(loggo.UNSPECIFIED, "message") c.Assert(s.writer.Log(), gc.HasLen, 0) s.logger.Logf(loggo.Level(42), "message") c.Assert(s.writer.Log(), gc.HasLen, 0) s.logger.Logf(loggo.CRITICAL+loggo.Level(1), "message") c.Assert(s.writer.Log(), gc.HasLen, 0) } �����������lxd-2.0.11/dist/src/github.com/juju/loggo/logger_test.go��������������������������������������������0000644�0610621�0607500�00000013315�13172163311�024213� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( gc "gopkg.in/check.v1" "github.com/juju/loggo" ) type LoggerSuite struct{} var _ = gc.Suite(&LoggerSuite{}) func (*LoggerSuite) SetUpTest(c *gc.C) { loggo.ResetDefaultContext() } func (s *LoggerSuite) TestRootLogger(c *gc.C) { root := loggo.Logger{} c.Check(root.Name(), gc.Equals, "<root>") c.Check(root.LogLevel(), gc.Equals, loggo.WARNING) c.Check(root.IsErrorEnabled(), gc.Equals, true) c.Check(root.IsWarningEnabled(), gc.Equals, true) c.Check(root.IsInfoEnabled(), gc.Equals, false) c.Check(root.IsDebugEnabled(), gc.Equals, false) c.Check(root.IsTraceEnabled(), gc.Equals, false) } func (s *LoggerSuite) TestSetLevel(c *gc.C) { logger := loggo.GetLogger("testing") c.Assert(logger.LogLevel(), gc.Equals, loggo.UNSPECIFIED) c.Assert(logger.EffectiveLogLevel(), gc.Equals, loggo.WARNING) c.Assert(logger.IsErrorEnabled(), gc.Equals, true) c.Assert(logger.IsWarningEnabled(), gc.Equals, true) c.Assert(logger.IsInfoEnabled(), gc.Equals, false) c.Assert(logger.IsDebugEnabled(), gc.Equals, false) c.Assert(logger.IsTraceEnabled(), gc.Equals, false) logger.SetLogLevel(loggo.TRACE) c.Assert(logger.LogLevel(), gc.Equals, loggo.TRACE) c.Assert(logger.EffectiveLogLevel(), gc.Equals, loggo.TRACE) c.Assert(logger.IsErrorEnabled(), gc.Equals, true) c.Assert(logger.IsWarningEnabled(), gc.Equals, true) c.Assert(logger.IsInfoEnabled(), gc.Equals, true) c.Assert(logger.IsDebugEnabled(), gc.Equals, true) c.Assert(logger.IsTraceEnabled(), gc.Equals, true) logger.SetLogLevel(loggo.DEBUG) c.Assert(logger.LogLevel(), gc.Equals, loggo.DEBUG) c.Assert(logger.EffectiveLogLevel(), gc.Equals, loggo.DEBUG) c.Assert(logger.IsErrorEnabled(), gc.Equals, true) c.Assert(logger.IsWarningEnabled(), gc.Equals, true) c.Assert(logger.IsInfoEnabled(), gc.Equals, true) c.Assert(logger.IsDebugEnabled(), gc.Equals, true) c.Assert(logger.IsTraceEnabled(), gc.Equals, false) logger.SetLogLevel(loggo.INFO) c.Assert(logger.LogLevel(), gc.Equals, loggo.INFO) c.Assert(logger.EffectiveLogLevel(), gc.Equals, loggo.INFO) c.Assert(logger.IsErrorEnabled(), gc.Equals, true) c.Assert(logger.IsWarningEnabled(), gc.Equals, true) c.Assert(logger.IsInfoEnabled(), gc.Equals, true) c.Assert(logger.IsDebugEnabled(), gc.Equals, false) c.Assert(logger.IsTraceEnabled(), gc.Equals, false) logger.SetLogLevel(loggo.WARNING) c.Assert(logger.LogLevel(), gc.Equals, loggo.WARNING) c.Assert(logger.EffectiveLogLevel(), gc.Equals, loggo.WARNING) c.Assert(logger.IsErrorEnabled(), gc.Equals, true) c.Assert(logger.IsWarningEnabled(), gc.Equals, true) c.Assert(logger.IsInfoEnabled(), gc.Equals, false) c.Assert(logger.IsDebugEnabled(), gc.Equals, false) c.Assert(logger.IsTraceEnabled(), gc.Equals, false) logger.SetLogLevel(loggo.ERROR) c.Assert(logger.LogLevel(), gc.Equals, loggo.ERROR) c.Assert(logger.EffectiveLogLevel(), gc.Equals, loggo.ERROR) c.Assert(logger.IsErrorEnabled(), gc.Equals, true) c.Assert(logger.IsWarningEnabled(), gc.Equals, false) c.Assert(logger.IsInfoEnabled(), gc.Equals, false) c.Assert(logger.IsDebugEnabled(), gc.Equals, false) c.Assert(logger.IsTraceEnabled(), gc.Equals, false) // This is added for completeness, but not really expected to be used. logger.SetLogLevel(loggo.CRITICAL) c.Assert(logger.LogLevel(), gc.Equals, loggo.CRITICAL) c.Assert(logger.EffectiveLogLevel(), gc.Equals, loggo.CRITICAL) c.Assert(logger.IsErrorEnabled(), gc.Equals, false) c.Assert(logger.IsWarningEnabled(), gc.Equals, false) c.Assert(logger.IsInfoEnabled(), gc.Equals, false) c.Assert(logger.IsDebugEnabled(), gc.Equals, false) c.Assert(logger.IsTraceEnabled(), gc.Equals, false) logger.SetLogLevel(loggo.UNSPECIFIED) c.Assert(logger.LogLevel(), gc.Equals, loggo.UNSPECIFIED) c.Assert(logger.EffectiveLogLevel(), gc.Equals, loggo.WARNING) } func (s *LoggerSuite) TestModuleLowered(c *gc.C) { logger1 := loggo.GetLogger("TESTING.MODULE") logger2 := loggo.GetLogger("Testing") c.Assert(logger1.Name(), gc.Equals, "testing.module") c.Assert(logger2.Name(), gc.Equals, "testing") } func (s *LoggerSuite) TestLevelsInherited(c *gc.C) { root := loggo.GetLogger("") first := loggo.GetLogger("first") second := loggo.GetLogger("first.second") root.SetLogLevel(loggo.ERROR) c.Assert(root.LogLevel(), gc.Equals, loggo.ERROR) c.Assert(root.EffectiveLogLevel(), gc.Equals, loggo.ERROR) c.Assert(first.LogLevel(), gc.Equals, loggo.UNSPECIFIED) c.Assert(first.EffectiveLogLevel(), gc.Equals, loggo.ERROR) c.Assert(second.LogLevel(), gc.Equals, loggo.UNSPECIFIED) c.Assert(second.EffectiveLogLevel(), gc.Equals, loggo.ERROR) first.SetLogLevel(loggo.DEBUG) c.Assert(root.LogLevel(), gc.Equals, loggo.ERROR) c.Assert(root.EffectiveLogLevel(), gc.Equals, loggo.ERROR) c.Assert(first.LogLevel(), gc.Equals, loggo.DEBUG) c.Assert(first.EffectiveLogLevel(), gc.Equals, loggo.DEBUG) c.Assert(second.LogLevel(), gc.Equals, loggo.UNSPECIFIED) c.Assert(second.EffectiveLogLevel(), gc.Equals, loggo.DEBUG) second.SetLogLevel(loggo.INFO) c.Assert(root.LogLevel(), gc.Equals, loggo.ERROR) c.Assert(root.EffectiveLogLevel(), gc.Equals, loggo.ERROR) c.Assert(first.LogLevel(), gc.Equals, loggo.DEBUG) c.Assert(first.EffectiveLogLevel(), gc.Equals, loggo.DEBUG) c.Assert(second.LogLevel(), gc.Equals, loggo.INFO) c.Assert(second.EffectiveLogLevel(), gc.Equals, loggo.INFO) first.SetLogLevel(loggo.UNSPECIFIED) c.Assert(root.LogLevel(), gc.Equals, loggo.ERROR) c.Assert(root.EffectiveLogLevel(), gc.Equals, loggo.ERROR) c.Assert(first.LogLevel(), gc.Equals, loggo.UNSPECIFIED) c.Assert(first.EffectiveLogLevel(), gc.Equals, loggo.ERROR) c.Assert(second.LogLevel(), gc.Equals, loggo.INFO) c.Assert(second.EffectiveLogLevel(), gc.Equals, loggo.INFO) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/logger.go�������������������������������������������������0000644�0610621�0607500�00000012553�13172163311�023157� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import ( "fmt" "runtime" "time" ) // A Logger represents a logging module. It has an associated logging // level which can be changed; messages of lesser severity will // be dropped. Loggers have a hierarchical relationship - see // the package documentation. // // The zero Logger value is usable - any messages logged // to it will be sent to the root Logger. type Logger struct { impl *module } func (logger Logger) getModule() *module { if logger.impl == nil { return defaultContext.root } return logger.impl } // Name returns the logger's module name. func (logger Logger) Name() string { return logger.getModule().Name() } // LogLevel returns the configured min log level of the logger. func (logger Logger) LogLevel() Level { return logger.getModule().level } // EffectiveLogLevel returns the effective min log level of // the receiver - that is, messages with a lesser severity // level will be discarded. // // If the log level of the receiver is unspecified, // it will be taken from the effective log level of its // parent. func (logger Logger) EffectiveLogLevel() Level { return logger.getModule().getEffectiveLogLevel() } // SetLogLevel sets the severity level of the given logger. // The root logger cannot be set to UNSPECIFIED level. // See EffectiveLogLevel for how this affects the // actual messages logged. func (logger Logger) SetLogLevel(level Level) { logger.getModule().setLevel(level) } // Logf logs a printf-formatted message at the given level. // A message will be discarded if level is less than the // the effective log level of the logger. // Note that the writers may also filter out messages that // are less than their registered minimum severity level. func (logger Logger) Logf(level Level, message string, args ...interface{}) { logger.LogCallf(2, level, message, args...) } // LogCallf logs a printf-formatted message at the given level. // The location of the call is indicated by the calldepth argument. // A calldepth of 1 means the function that called this function. // A message will be discarded if level is less than the // the effective log level of the logger. // Note that the writers may also filter out messages that // are less than their registered minimum severity level. func (logger Logger) LogCallf(calldepth int, level Level, message string, args ...interface{}) { module := logger.getModule() if !module.willWrite(level) { return } // Gather time, and filename, line number. now := time.Now() // get this early. // Param to Caller is the call depth. Since this method is called from // the Logger methods, we want the place that those were called from. _, file, line, ok := runtime.Caller(calldepth + 1) if !ok { file = "???" line = 0 } // Trim newline off format string, following usual // Go logging conventions. if len(message) > 0 && message[len(message)-1] == '\n' { message = message[0 : len(message)-1] } // To avoid having a proliferation of Info/Infof methods, // only use Sprintf if there are any args, and rely on the // `go vet` tool for the obvious cases where someone has forgotten // to provide an arg. formattedMessage := message if len(args) > 0 { formattedMessage = fmt.Sprintf(message, args...) } module.write(Entry{ Level: level, Filename: file, Line: line, Timestamp: now, Message: formattedMessage, }) } // Criticalf logs the printf-formatted message at critical level. func (logger Logger) Criticalf(message string, args ...interface{}) { logger.Logf(CRITICAL, message, args...) } // Errorf logs the printf-formatted message at error level. func (logger Logger) Errorf(message string, args ...interface{}) { logger.Logf(ERROR, message, args...) } // Warningf logs the printf-formatted message at warning level. func (logger Logger) Warningf(message string, args ...interface{}) { logger.Logf(WARNING, message, args...) } // Infof logs the printf-formatted message at info level. func (logger Logger) Infof(message string, args ...interface{}) { logger.Logf(INFO, message, args...) } // Debugf logs the printf-formatted message at debug level. func (logger Logger) Debugf(message string, args ...interface{}) { logger.Logf(DEBUG, message, args...) } // Tracef logs the printf-formatted message at trace level. func (logger Logger) Tracef(message string, args ...interface{}) { logger.Logf(TRACE, message, args...) } // IsLevelEnabled returns whether debugging is enabled // for the given log level. func (logger Logger) IsLevelEnabled(level Level) bool { return logger.getModule().willWrite(level) } // IsErrorEnabled returns whether debugging is enabled // at error level. func (logger Logger) IsErrorEnabled() bool { return logger.IsLevelEnabled(ERROR) } // IsWarningEnabled returns whether debugging is enabled // at warning level. func (logger Logger) IsWarningEnabled() bool { return logger.IsLevelEnabled(WARNING) } // IsInfoEnabled returns whether debugging is enabled // at info level. func (logger Logger) IsInfoEnabled() bool { return logger.IsLevelEnabled(INFO) } // IsDebugEnabled returns whether debugging is enabled // at debug level. func (logger Logger) IsDebugEnabled() bool { return logger.IsLevelEnabled(DEBUG) } // IsTraceEnabled returns whether debugging is enabled // at trace level. func (logger Logger) IsTraceEnabled() bool { return logger.IsLevelEnabled(TRACE) } �����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/level_test.go���������������������������������������������0000644�0610621�0607500�00000003300�13172163311�024034� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( gc "gopkg.in/check.v1" "github.com/juju/loggo" ) type LevelSuite struct{} var _ = gc.Suite(&LevelSuite{}) var parseLevelTests = []struct { str string level loggo.Level fail bool }{{ str: "trace", level: loggo.TRACE, }, { str: "TrAce", level: loggo.TRACE, }, { str: "TRACE", level: loggo.TRACE, }, { str: "debug", level: loggo.DEBUG, }, { str: "DEBUG", level: loggo.DEBUG, }, { str: "info", level: loggo.INFO, }, { str: "INFO", level: loggo.INFO, }, { str: "warn", level: loggo.WARNING, }, { str: "WARN", level: loggo.WARNING, }, { str: "warning", level: loggo.WARNING, }, { str: "WARNING", level: loggo.WARNING, }, { str: "error", level: loggo.ERROR, }, { str: "ERROR", level: loggo.ERROR, }, { str: "critical", level: loggo.CRITICAL, }, { str: "not_specified", fail: true, }, { str: "other", fail: true, }, { str: "", fail: true, }} func (s *LevelSuite) TestParseLevel(c *gc.C) { for _, test := range parseLevelTests { level, ok := loggo.ParseLevel(test.str) c.Assert(level, gc.Equals, test.level) c.Assert(ok, gc.Equals, !test.fail) } } var levelStringValueTests = map[loggo.Level]string{ loggo.UNSPECIFIED: "UNSPECIFIED", loggo.DEBUG: "DEBUG", loggo.TRACE: "TRACE", loggo.INFO: "INFO", loggo.WARNING: "WARNING", loggo.ERROR: "ERROR", loggo.CRITICAL: "CRITICAL", loggo.Level(42): "<unknown>", // other values are unknown } func (s *LevelSuite) TestLevelStringValue(c *gc.C) { for level, str := range levelStringValueTests { c.Assert(level.String(), gc.Equals, str) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/level.go��������������������������������������������������0000644�0610621�0607500�00000003603�13172163311�023003� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import ( "strings" "sync/atomic" ) // The severity levels. Higher values are more considered more // important. const ( UNSPECIFIED Level = iota TRACE DEBUG INFO WARNING ERROR CRITICAL ) // Level holds a severity level. type Level uint32 // ParseLevel converts a string representation of a logging level to a // Level. It returns the level and whether it was valid or not. func ParseLevel(level string) (Level, bool) { level = strings.ToUpper(level) switch level { case "UNSPECIFIED": return UNSPECIFIED, true case "TRACE": return TRACE, true case "DEBUG": return DEBUG, true case "INFO": return INFO, true case "WARN", "WARNING": return WARNING, true case "ERROR": return ERROR, true case "CRITICAL": return CRITICAL, true default: return UNSPECIFIED, false } } // String implements Stringer. func (level Level) String() string { switch level { case UNSPECIFIED: return "UNSPECIFIED" case TRACE: return "TRACE" case DEBUG: return "DEBUG" case INFO: return "INFO" case WARNING: return "WARNING" case ERROR: return "ERROR" case CRITICAL: return "CRITICAL" default: return "<unknown>" } } // Short returns a five character string to use in // aligned logging output. func (level Level) Short() string { switch level { case TRACE: return "TRACE" case DEBUG: return "DEBUG" case INFO: return "INFO " case WARNING: return "WARN " case ERROR: return "ERROR" case CRITICAL: return "CRITC" default: return " " } } // get atomically gets the value of the given level. func (level *Level) get() Level { return Level(atomic.LoadUint32((*uint32)(level))) } // set atomically sets the value of the receiver // to the given level. func (level *Level) set(newLevel Level) { atomic.StoreUint32((*uint32)(level), uint32(newLevel)) } �����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/global_test.go��������������������������������������������0000644�0610621�0607500�00000004702�13172163311�024174� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "github.com/juju/loggo" gc "gopkg.in/check.v1" ) type GlobalSuite struct{} var _ = gc.Suite(&GlobalSuite{}) func (*GlobalSuite) SetUpTest(c *gc.C) { loggo.ResetDefaultContext() } func (*GlobalSuite) TestRootLogger(c *gc.C) { var root loggo.Logger got := loggo.GetLogger("") c.Check(got.Name(), gc.Equals, root.Name()) c.Check(got.LogLevel(), gc.Equals, root.LogLevel()) } func (*GlobalSuite) TestModuleName(c *gc.C) { logger := loggo.GetLogger("loggo.testing") c.Check(logger.Name(), gc.Equals, "loggo.testing") } func (*GlobalSuite) TestLevel(c *gc.C) { logger := loggo.GetLogger("testing") level := logger.LogLevel() c.Check(level, gc.Equals, loggo.UNSPECIFIED) } func (*GlobalSuite) TestEffectiveLevel(c *gc.C) { logger := loggo.GetLogger("testing") level := logger.EffectiveLogLevel() c.Check(level, gc.Equals, loggo.WARNING) } func (*GlobalSuite) TestLevelsSharedForSameModule(c *gc.C) { logger1 := loggo.GetLogger("testing.module") logger2 := loggo.GetLogger("testing.module") logger1.SetLogLevel(loggo.INFO) c.Assert(logger1.IsInfoEnabled(), gc.Equals, true) c.Assert(logger2.IsInfoEnabled(), gc.Equals, true) } func (*GlobalSuite) TestModuleLowered(c *gc.C) { logger1 := loggo.GetLogger("TESTING.MODULE") logger2 := loggo.GetLogger("Testing") c.Assert(logger1.Name(), gc.Equals, "testing.module") c.Assert(logger2.Name(), gc.Equals, "testing") } func (s *GlobalSuite) TestConfigureLoggers(c *gc.C) { err := loggo.ConfigureLoggers("testing.module=debug") c.Assert(err, gc.IsNil) expected := "<root>=WARNING;testing.module=DEBUG" c.Assert(loggo.DefaultContext().Config().String(), gc.Equals, expected) c.Assert(loggo.LoggerInfo(), gc.Equals, expected) } func (*GlobalSuite) TestRegisterWriterExistingName(c *gc.C) { err := loggo.RegisterWriter("default", &writer{}) c.Assert(err, gc.ErrorMatches, `context already has a writer named "default"`) } func (*GlobalSuite) TestReplaceDefaultWriter(c *gc.C) { oldWriter, err := loggo.ReplaceDefaultWriter(&writer{}) c.Assert(oldWriter, gc.NotNil) c.Assert(err, gc.IsNil) c.Assert(loggo.DefaultContext().WriterNames(), gc.DeepEquals, []string{"default"}) } func (*GlobalSuite) TestRemoveWriter(c *gc.C) { oldWriter, err := loggo.RemoveWriter("default") c.Assert(oldWriter, gc.NotNil) c.Assert(err, gc.IsNil) c.Assert(loggo.DefaultContext().WriterNames(), gc.HasLen, 0) } ��������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/global.go�������������������������������������������������0000644�0610621�0607500�00000005417�13172163311�023141� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo var ( defaultContext = newDefaultContxt() ) func newDefaultContxt() *Context { ctx := NewContext(WARNING) ctx.AddWriter(DefaultWriterName, defaultWriter()) return ctx } // DefaultContext returns the global default logging context. func DefaultContext() *Context { return defaultContext } // LoggerInfo returns information about the configured loggers and their // logging levels. The information is returned in the format expected by // ConfigureLoggers. Loggers with UNSPECIFIED level will not // be included. func LoggerInfo() string { return defaultContext.Config().String() } // GetLogger returns a Logger for the given module name, // creating it and its parents if necessary. func GetLogger(name string) Logger { return defaultContext.GetLogger(name) } // ResetLogging iterates through the known modules and sets the levels of all // to UNSPECIFIED, except for <root> which is set to WARNING. The call also // removes all writers in the DefaultContext and puts the original default // writer back as the only writer. func ResetLogging() { defaultContext.ResetLoggerLevels() defaultContext.ResetWriters() } // ResetWriters puts the list of writers back into the initial state. func ResetWriters() { defaultContext.ResetWriters() } // ReplaceDefaultWriter is a convenience method that does the equivalent of // RemoveWriter and then RegisterWriter with the name "default". The previous // default writer, if any is returned. func ReplaceDefaultWriter(writer Writer) (Writer, error) { return defaultContext.ReplaceWriter(DefaultWriterName, writer) } // RegisterWriter adds the writer to the list of writers in the DefaultContext // that get notified when logging. If there is already a registered writer // with that name, an error is returned. func RegisterWriter(name string, writer Writer) error { return defaultContext.AddWriter(name, writer) } // RemoveWriter removes the Writer identified by 'name' and returns it. // If the Writer is not found, an error is returned. func RemoveWriter(name string) (Writer, error) { return defaultContext.RemoveWriter(name) } // ConfigureLoggers configures loggers according to the given string // specification, which specifies a set of modules and their associated // logging levels. Loggers are colon- or semicolon-separated; each // module is specified as <modulename>=<level>. White space outside of // module names and levels is ignored. The root module is specified // with the name "<root>". // // An example specification: // `<root>=ERROR; foo.bar=WARNING` func ConfigureLoggers(specification string) error { config, err := ParseConfigString(specification) if err != nil { return err } defaultContext.ApplyConfig(config) return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/formatter_test.go�����������������������������������������0000644�0610621�0607500�00000001401�13172163311�024730� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "time" gc "gopkg.in/check.v1" "github.com/juju/loggo" ) type formatterSuite struct{} var _ = gc.Suite(&formatterSuite{}) func (*formatterSuite) TestDefaultFormat(c *gc.C) { location, err := time.LoadLocation("UTC") testTime := time.Date(2013, 5, 3, 10, 53, 24, 123456, location) c.Assert(err, gc.IsNil) entry := loggo.Entry{ Level: loggo.WARNING, Module: "test.module", Filename: "some/deep/filename", Line: 42, Timestamp: testTime, Message: "hello world!", } formatted := loggo.DefaultFormatter(entry) c.Assert(formatted, gc.Equals, "2013-05-03 10:53:24 WARNING test.module filename:42 hello world!") } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/formatter.go����������������������������������������������0000644�0610621�0607500�00000002042�13172163311�023673� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import ( "fmt" "os" "path/filepath" "time" ) // DefaultFormatter returns the parameters separated by spaces except for // filename and line which are separated by a colon. The timestamp is shown // to second resolution in UTC. For example: // 2016-07-02 15:04:05 func DefaultFormatter(entry Entry) string { ts := entry.Timestamp.In(time.UTC).Format("2006-01-02 15:04:05") // Just get the basename from the filename filename := filepath.Base(entry.Filename) return fmt.Sprintf("%s %s %s %s:%d %s", ts, entry.Level, entry.Module, filename, entry.Line, entry.Message) } // TimeFormat is the time format used for the default writer. // This can be set with the environment variable LOGGO_TIME_FORMAT. var TimeFormat = initTimeFormat() func initTimeFormat() string { format := os.Getenv("LOGGO_TIME_FORMAT") if format != "" { return format } return "15:04:05" } func formatTime(ts time.Time) string { return ts.Format(TimeFormat) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/export_test.go��������������������������������������������0000644�0610621�0607500�00000000766�13172163311�024263� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo // WriterNames returns the names of the context's writers for testing purposes. func (c *Context) WriterNames() []string { c.writersMutex.Lock() defer c.writersMutex.Unlock() var result []string for name := range c.writers { result = append(result, name) } return result } func ResetDefaultContext() { ResetLogging() DefaultContext().AddWriter(DefaultWriterName, defaultWriter()) } ����������lxd-2.0.11/dist/src/github.com/juju/loggo/example/��������������������������������������������������0000755�0610621�0607500�00000000000�13172163311�022776� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/example/second.go�����������������������������������������0000644�0610621�0607500�00000000725�13172163311�024604� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "github.com/juju/loggo" ) var second = loggo.GetLogger("second") func SecondCritical(message string) { second.Criticalf(message) } func SecondError(message string) { second.Errorf(message) } func SecondWarning(message string) { second.Warningf(message) } func SecondInfo(message string) { second.Infof(message) } func SecondDebug(message string) { second.Debugf(message) } func SecondTrace(message string) { second.Tracef(message) } �������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/example/main.go�������������������������������������������0000644�0610621�0607500�00000001501�13172163311�024246� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "github.com/juju/loggo" ) var logger = loggo.GetLogger("main") var rootLogger = loggo.GetLogger("") func main() { args := os.Args if len(args) > 1 { loggo.ConfigureLoggers(args[1]) } else { fmt.Println("Add a parameter to configure the logging:") fmt.Println("E.g. \"<root>=INFO;first=TRACE\"") } fmt.Println("\nCurrent logging levels:") fmt.Println(loggo.LoggerInfo()) fmt.Println("") rootLogger.Infof("Start of test.") FirstCritical("first critical") FirstError("first error") FirstWarning("first warning") FirstInfo("first info") FirstDebug("first debug") FirstTrace("first trace") SecondCritical("second critical") SecondError("second error") SecondWarning("second warning") SecondInfo("second info") SecondDebug("second debug") SecondTrace("second trace") } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/example/first.go������������������������������������������0000644�0610621�0607500�00000000710�13172163311�024452� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "github.com/juju/loggo" ) var first = loggo.GetLogger("first") func FirstCritical(message string) { first.Criticalf(message) } func FirstError(message string) { first.Errorf(message) } func FirstWarning(message string) { first.Warningf(message) } func FirstInfo(message string) { first.Infof(message) } func FirstDebug(message string) { first.Debugf(message) } func FirstTrace(message string) { first.Tracef(message) } ��������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/entry.go��������������������������������������������������0000644�0610621�0607500�00000001122�13172163311�023027� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import "time" // Entry represents a single log message. type Entry struct { // Level is the severity of the log message. Level Level // Module is the dotted module name from the logger. Module string // Filename is the full path the file that logged the message. Filename string // Line is the line number of the Filename. Line int // Timestamp is when the log message was created Timestamp time.Time // Message is the formatted string from teh log call. Message string } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/doc.go����������������������������������������������������0000644�0610621�0607500�00000003141�13172163311�022436� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. /* [godoc-link-here] Module level logging for Go This package provides an alternative to the standard library log package. The actual logging functions never return errors. If you are logging something, you really don't want to be worried about the logging having trouble. Modules have names that are defined by dotted strings. "first.second.third" There is a root module that has the name `""`. Each module (except the root module) has a parent, identified by the part of the name without the last dotted value. * the parent of "first.second.third" is "first.second" * the parent of "first.second" is "first" * the parent of "first" is "" (the root module) Each module can specify its own severity level. Logging calls that are of a lower severity than the module's effective severity level are not written out. Loggers are created using the GetLogger function. logger := loggo.GetLogger("foo.bar") By default there is one writer registered, which will write to Stderr, and the root module, which will only emit warnings and above. If you want to continue using the default logger, but have it emit all logging levels you need to do the following. writer, _, err := loggo.RemoveWriter("default") // err is non-nil if and only if the name isn't found. loggo.RegisterWriter("default", writer) To make loggo produce colored output, you can do the following, having imported github.com/juju/loggo/loggocolor: loggo.RemoveWriter("default") loggo.RegisterWriter("default", loggocolor.NewWriter(os.Stderr)) */ package loggo �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/dependencies.tsv������������������������������������������0000644�0610621�0607500�00000001037�13172163311�024530� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������github.com/juju/ansiterm git b99631de12cf04a906c1d4e4ec54fb86eae5863d 2016-09-07T23:45:32Z github.com/lunixbochs/vtclean git 4fbf7632a2c6d3fbdb9931439bdbbeded02cbe36 2016-01-25T03:51:06Z github.com/mattn/go-colorable git ed8eb9e318d7a84ce5915b495b7d35e0cfe7b5a8 2016-07-31T23:54:17Z github.com/mattn/go-isatty git 66b8e73f3f5cda9f96b69efd03dd3d7fc4a5cdb8 2016-08-06T12:27:52Z golang.org/x/sys git 9bb9f0998d48b31547d975974935ae9b48c7a03c 2016-10-12T00:19:20Z gopkg.in/check.v1 git 4f90aeace3a26ad7021961c297b22c42160c7b25 2016-01-05T16:49:36Z �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/context_test.go�������������������������������������������0000644�0610621�0607500�00000023663�13172163311�024427� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "github.com/juju/loggo" gc "gopkg.in/check.v1" ) type ContextSuite struct{} var _ = gc.Suite(&ContextSuite{}) func (*ContextSuite) TestNewContextRootLevel(c *gc.C) { for i, test := range []struct { level loggo.Level expected loggo.Level }{{ level: loggo.UNSPECIFIED, expected: loggo.WARNING, }, { level: loggo.DEBUG, expected: loggo.DEBUG, }, { level: loggo.INFO, expected: loggo.INFO, }, { level: loggo.WARNING, expected: loggo.WARNING, }, { level: loggo.ERROR, expected: loggo.ERROR, }, { level: loggo.CRITICAL, expected: loggo.CRITICAL, }, { level: loggo.Level(42), expected: loggo.WARNING, }} { c.Log("%d: %s", i, test.level) context := loggo.NewContext(test.level) cfg := context.Config() c.Check(cfg, gc.HasLen, 1) value, found := cfg[""] c.Check(found, gc.Equals, true) c.Check(value, gc.Equals, test.expected) } } func logAllSeverities(logger loggo.Logger) { logger.Criticalf("something critical") logger.Errorf("an error") logger.Warningf("a warning message") logger.Infof("an info message") logger.Debugf("a debug message") logger.Tracef("a trace message") } func checkLogEntry(c *gc.C, entry, expected loggo.Entry) { c.Check(entry.Level, gc.Equals, expected.Level) c.Check(entry.Module, gc.Equals, expected.Module) c.Check(entry.Message, gc.Equals, expected.Message) } func checkLogEntries(c *gc.C, obtained, expected []loggo.Entry) { if c.Check(len(obtained), gc.Equals, len(expected)) { for i := range obtained { checkLogEntry(c, obtained[i], expected[i]) } } } func (*ContextSuite) TestGetLoggerRoot(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) blank := context.GetLogger("") root := context.GetLogger("<root>") c.Assert(blank, gc.Equals, root) } func (*ContextSuite) TestGetLoggerCase(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) upper := context.GetLogger("TEST") lower := context.GetLogger("test") c.Assert(upper, gc.Equals, lower) c.Assert(upper.Name(), gc.Equals, "test") } func (*ContextSuite) TestGetLoggerSpace(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) space := context.GetLogger(" test ") lower := context.GetLogger("test") c.Assert(space, gc.Equals, lower) c.Assert(space.Name(), gc.Equals, "test") } func (*ContextSuite) TestNewContextNoWriter(c *gc.C) { // Should be no output. context := loggo.NewContext(loggo.DEBUG) logger := context.GetLogger("test") logAllSeverities(logger) } func (*ContextSuite) newContextWithTestWriter(c *gc.C, level loggo.Level) (*loggo.Context, *loggo.TestWriter) { writer := &loggo.TestWriter{} context := loggo.NewContext(level) context.AddWriter("test", writer) return context, writer } func (s *ContextSuite) TestNewContextRootSeverityWarning(c *gc.C) { context, writer := s.newContextWithTestWriter(c, loggo.WARNING) logger := context.GetLogger("test") logAllSeverities(logger) checkLogEntries(c, writer.Log(), []loggo.Entry{ {Level: loggo.CRITICAL, Module: "test", Message: "something critical"}, {Level: loggo.ERROR, Module: "test", Message: "an error"}, {Level: loggo.WARNING, Module: "test", Message: "a warning message"}, }) } func (s *ContextSuite) TestNewContextRootSeverityTrace(c *gc.C) { context, writer := s.newContextWithTestWriter(c, loggo.TRACE) logger := context.GetLogger("test") logAllSeverities(logger) checkLogEntries(c, writer.Log(), []loggo.Entry{ {Level: loggo.CRITICAL, Module: "test", Message: "something critical"}, {Level: loggo.ERROR, Module: "test", Message: "an error"}, {Level: loggo.WARNING, Module: "test", Message: "a warning message"}, {Level: loggo.INFO, Module: "test", Message: "an info message"}, {Level: loggo.DEBUG, Module: "test", Message: "a debug message"}, {Level: loggo.TRACE, Module: "test", Message: "a trace message"}, }) } func (*ContextSuite) TestNewContextConfig(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) config := context.Config() c.Assert(config, gc.DeepEquals, loggo.Config{"": loggo.DEBUG}) } func (*ContextSuite) TestNewLoggerAddsConfig(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) _ = context.GetLogger("test.module") c.Assert(context.Config(), gc.DeepEquals, loggo.Config{ "": loggo.DEBUG, }) c.Assert(context.CompleteConfig(), gc.DeepEquals, loggo.Config{ "": loggo.DEBUG, "test": loggo.UNSPECIFIED, "test.module": loggo.UNSPECIFIED, }) } func (*ContextSuite) TestApplyNilConfig(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) context.ApplyConfig(nil) c.Assert(context.Config(), gc.DeepEquals, loggo.Config{"": loggo.DEBUG}) } func (*ContextSuite) TestApplyConfigRootUnspecified(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) context.ApplyConfig(loggo.Config{"": loggo.UNSPECIFIED}) c.Assert(context.Config(), gc.DeepEquals, loggo.Config{"": loggo.WARNING}) } func (*ContextSuite) TestApplyConfigRootTrace(c *gc.C) { context := loggo.NewContext(loggo.WARNING) context.ApplyConfig(loggo.Config{"": loggo.TRACE}) c.Assert(context.Config(), gc.DeepEquals, loggo.Config{"": loggo.TRACE}) } func (*ContextSuite) TestApplyConfigCreatesModules(c *gc.C) { context := loggo.NewContext(loggo.WARNING) context.ApplyConfig(loggo.Config{"first.second": loggo.TRACE}) c.Assert(context.Config(), gc.DeepEquals, loggo.Config{ "": loggo.WARNING, "first.second": loggo.TRACE, }) c.Assert(context.CompleteConfig(), gc.DeepEquals, loggo.Config{ "": loggo.WARNING, "first": loggo.UNSPECIFIED, "first.second": loggo.TRACE, }) } func (*ContextSuite) TestApplyConfigAdditive(c *gc.C) { context := loggo.NewContext(loggo.WARNING) context.ApplyConfig(loggo.Config{"first.second": loggo.TRACE}) context.ApplyConfig(loggo.Config{"other.module": loggo.DEBUG}) c.Assert(context.Config(), gc.DeepEquals, loggo.Config{ "": loggo.WARNING, "first.second": loggo.TRACE, "other.module": loggo.DEBUG, }) c.Assert(context.CompleteConfig(), gc.DeepEquals, loggo.Config{ "": loggo.WARNING, "first": loggo.UNSPECIFIED, "first.second": loggo.TRACE, "other": loggo.UNSPECIFIED, "other.module": loggo.DEBUG, }) } func (*ContextSuite) TestResetLoggerLevels(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) context.ApplyConfig(loggo.Config{"first.second": loggo.TRACE}) context.ResetLoggerLevels() c.Assert(context.Config(), gc.DeepEquals, loggo.Config{ "": loggo.WARNING, }) c.Assert(context.CompleteConfig(), gc.DeepEquals, loggo.Config{ "": loggo.WARNING, "first": loggo.UNSPECIFIED, "first.second": loggo.UNSPECIFIED, }) } func (*ContextSuite) TestWriterNamesNone(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) writers := context.WriterNames() c.Assert(writers, gc.HasLen, 0) } func (*ContextSuite) TestAddWriterNoName(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) err := context.AddWriter("", nil) c.Assert(err.Error(), gc.Equals, "name cannot be empty") } func (*ContextSuite) TestAddWriterNil(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) err := context.AddWriter("foo", nil) c.Assert(err.Error(), gc.Equals, "writer cannot be nil") } func (*ContextSuite) TestNamedAddWriter(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) err := context.AddWriter("foo", &writer{name: "foo"}) c.Assert(err, gc.IsNil) err = context.AddWriter("foo", &writer{name: "foo"}) c.Assert(err.Error(), gc.Equals, `context already has a writer named "foo"`) writers := context.WriterNames() c.Assert(writers, gc.DeepEquals, []string{"foo"}) } func (*ContextSuite) TestRemoveWriter(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) w, err := context.RemoveWriter("unknown") c.Assert(err.Error(), gc.Equals, `context has no writer named "unknown"`) c.Assert(w, gc.IsNil) } func (*ContextSuite) TestRemoveWriterFound(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) original := &writer{name: "foo"} err := context.AddWriter("foo", original) c.Assert(err, gc.IsNil) existing, err := context.RemoveWriter("foo") c.Assert(err, gc.IsNil) c.Assert(existing, gc.Equals, original) writers := context.WriterNames() c.Assert(writers, gc.HasLen, 0) } func (*ContextSuite) TestReplaceWriterNoName(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) existing, err := context.ReplaceWriter("", nil) c.Assert(err.Error(), gc.Equals, "name cannot be empty") c.Assert(existing, gc.IsNil) } func (*ContextSuite) TestReplaceWriterNil(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) existing, err := context.ReplaceWriter("foo", nil) c.Assert(err.Error(), gc.Equals, "writer cannot be nil") c.Assert(existing, gc.IsNil) } func (*ContextSuite) TestReplaceWriterNotFound(c *gc.C) { context := loggo.NewContext(loggo.DEBUG) existing, err := context.ReplaceWriter("foo", &writer{}) c.Assert(err.Error(), gc.Equals, `context has no writer named "foo"`) c.Assert(existing, gc.IsNil) } func (*ContextSuite) TestMultipleWriters(c *gc.C) { first := &writer{} second := &writer{} third := &writer{} context := loggo.NewContext(loggo.TRACE) err := context.AddWriter("first", first) c.Assert(err, gc.IsNil) err = context.AddWriter("second", second) c.Assert(err, gc.IsNil) err = context.AddWriter("third", third) c.Assert(err, gc.IsNil) logger := context.GetLogger("test") logAllSeverities(logger) expected := []loggo.Entry{ {Level: loggo.CRITICAL, Module: "test", Message: "something critical"}, {Level: loggo.ERROR, Module: "test", Message: "an error"}, {Level: loggo.WARNING, Module: "test", Message: "a warning message"}, {Level: loggo.INFO, Module: "test", Message: "an info message"}, {Level: loggo.DEBUG, Module: "test", Message: "a debug message"}, {Level: loggo.TRACE, Module: "test", Message: "a trace message"}, } checkLogEntries(c, first.Log(), expected) checkLogEntries(c, second.Log(), expected) checkLogEntries(c, third.Log(), expected) } type writer struct { loggo.TestWriter // The name exists to discriminate writer equality. name string } �����������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/context.go������������������������������������������������0000644�0610621�0607500�00000012221�13172163311�023354� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import ( "fmt" "strings" "sync" ) // Context produces loggers for a hierarchy of modules. The context holds // a collection of hierarchical loggers and their writers. type Context struct { root *module // Perhaps have one mutex? modulesMutex sync.Mutex modules map[string]*module writersMutex sync.Mutex writers map[string]Writer // writeMuxtex is used to serialise write operations. writeMutex sync.Mutex } // NewLoggers returns a new Context with no writers set. // If the root level is UNSPECIFIED, WARNING is used. func NewContext(rootLevel Level) *Context { if rootLevel < TRACE || rootLevel > CRITICAL { rootLevel = WARNING } context := &Context{ modules: make(map[string]*module), writers: make(map[string]Writer), } context.root = &module{ level: rootLevel, context: context, } context.modules[""] = context.root return context } // GetLogger returns a Logger for the given module name, creating it and // its parents if necessary. func (c *Context) GetLogger(name string) Logger { name = strings.TrimSpace(strings.ToLower(name)) c.modulesMutex.Lock() defer c.modulesMutex.Unlock() return Logger{c.getLoggerModule(name)} } func (c *Context) getLoggerModule(name string) *module { if name == rootString { name = "" } impl, found := c.modules[name] if found { return impl } parentName := "" if i := strings.LastIndex(name, "."); i >= 0 { parentName = name[0:i] } parent := c.getLoggerModule(parentName) impl = &module{name, UNSPECIFIED, parent, c} c.modules[name] = impl return impl } // Config returns the current configuration of the Loggers. Loggers // with UNSPECIFIED level will not be included. func (c *Context) Config() Config { result := make(Config) c.modulesMutex.Lock() defer c.modulesMutex.Unlock() for name, module := range c.modules { if module.level != UNSPECIFIED { result[name] = module.level } } return result } // CompleteConfig returns all the loggers and their defined levels, // even if that level is UNSPECIFIED. func (c *Context) CompleteConfig() Config { result := make(Config) c.modulesMutex.Lock() defer c.modulesMutex.Unlock() for name, module := range c.modules { result[name] = module.level } return result } // ApplyConfig configures the logging modules according to the provided config. func (c *Context) ApplyConfig(config Config) { c.modulesMutex.Lock() defer c.modulesMutex.Unlock() for name, level := range config { module := c.getLoggerModule(name) module.setLevel(level) } } // ResetLoggerLevels iterates through the known logging modules and sets the // levels of all to UNSPECIFIED, except for <root> which is set to WARNING. func (c *Context) ResetLoggerLevels() { c.modulesMutex.Lock() defer c.modulesMutex.Unlock() // Setting the root module to UNSPECIFIED will set it to WARNING. for _, module := range c.modules { module.setLevel(UNSPECIFIED) } } func (c *Context) write(entry Entry) { c.writeMutex.Lock() defer c.writeMutex.Unlock() for _, writer := range c.getWriters() { writer.Write(entry) } } func (c *Context) getWriters() []Writer { c.writersMutex.Lock() defer c.writersMutex.Unlock() var result []Writer for _, writer := range c.writers { result = append(result, writer) } return result } // AddWriter adds a writer to the list to be called for each logging call. // The name cannot be empty, and the writer cannot be nil. If an existing // writer exists with the specified name, an error is returned. func (c *Context) AddWriter(name string, writer Writer) error { if name == "" { return fmt.Errorf("name cannot be empty") } if writer == nil { return fmt.Errorf("writer cannot be nil") } c.writersMutex.Lock() defer c.writersMutex.Unlock() if _, found := c.writers[name]; found { return fmt.Errorf("context already has a writer named %q", name) } c.writers[name] = writer return nil } // RemoveWriter remotes the specified writer. If a writer is not found with // the specified name an error is returned. The writer that was removed is also // returned. func (c *Context) RemoveWriter(name string) (Writer, error) { c.writersMutex.Lock() defer c.writersMutex.Unlock() reg, found := c.writers[name] if !found { return nil, fmt.Errorf("context has no writer named %q", name) } delete(c.writers, name) return reg, nil } // ReplaceWriter is a convenience method that does the equivalent of RemoveWriter // followed by AddWriter with the same name. The replaced writer is returned. func (c *Context) ReplaceWriter(name string, writer Writer) (Writer, error) { if name == "" { return nil, fmt.Errorf("name cannot be empty") } if writer == nil { return nil, fmt.Errorf("writer cannot be nil") } c.writersMutex.Lock() defer c.writersMutex.Unlock() reg, found := c.writers[name] if !found { return nil, fmt.Errorf("context has no writer named %q", name) } oldWriter := reg c.writers[name] = writer return oldWriter, nil } // ResetWriters is generally only used in testing and removes all the writers. func (c *Context) ResetWriters() { c.writersMutex.Lock() defer c.writersMutex.Unlock() c.writers = make(map[string]Writer) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/config_test.go��������������������������������������������0000644�0610621�0607500�00000007216�13172163311�024204� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import gc "gopkg.in/check.v1" type ConfigSuite struct{} var _ = gc.Suite(&ConfigSuite{}) func (*ConfigSuite) TestParseConfigValue(c *gc.C) { for i, test := range []struct { value string module string level Level err string }{{ err: `config value expected '=', found ""`, }, { value: "WARNING", err: `config value expected '=', found "WARNING"`, }, { value: "=WARNING", err: `config value "=WARNING" has missing module name`, }, { value: " name = WARNING ", module: "name", level: WARNING, }, { value: "name = foo", err: `unknown severity level "foo"`, }, { value: "name=DEBUG=INFO", err: `unknown severity level "DEBUG=INFO"`, }, { value: "<root> = info", module: "", level: INFO, }} { c.Logf("%d: %s", i, test.value) module, level, err := parseConfigValue(test.value) if test.err == "" { c.Check(err, gc.IsNil) c.Check(module, gc.Equals, test.module) c.Check(level, gc.Equals, test.level) } else { c.Check(module, gc.Equals, "") c.Check(level, gc.Equals, UNSPECIFIED) c.Check(err.Error(), gc.Equals, test.err) } } } func (*ConfigSuite) TestPaarseConfigurationString(c *gc.C) { for i, test := range []struct { configuration string expected Config err string }{{ configuration: "", // nil Config, no error }, { configuration: "INFO", expected: Config{"": INFO}, }, { configuration: "=INFO", err: `config value "=INFO" has missing module name`, }, { configuration: "<root>=UNSPECIFIED", expected: Config{"": UNSPECIFIED}, }, { configuration: "<root>=DEBUG", expected: Config{"": DEBUG}, }, { configuration: "test.module=debug", expected: Config{"test.module": DEBUG}, }, { configuration: "module=info; sub.module=debug; other.module=warning", expected: Config{ "module": INFO, "sub.module": DEBUG, "other.module": WARNING, }, }, { // colons not semicolons configuration: "module=info: sub.module=debug: other.module=warning", expected: Config{ "module": INFO, "sub.module": DEBUG, "other.module": WARNING, }, }, { configuration: " foo.bar \t\r\n= \t\r\nCRITICAL \t\r\n; \t\r\nfoo \r\t\n = DEBUG", expected: Config{ "foo": DEBUG, "foo.bar": CRITICAL, }, }, { configuration: "foo;bar", err: `config value expected '=', found "foo"`, }, { configuration: "foo=", err: `unknown severity level ""`, }, { configuration: "foo=unknown", err: `unknown severity level "unknown"`, }} { c.Logf("%d: %q", i, test.configuration) config, err := ParseConfigString(test.configuration) if test.err == "" { c.Check(err, gc.IsNil) c.Check(config, gc.DeepEquals, test.expected) } else { c.Check(config, gc.IsNil) c.Check(err.Error(), gc.Equals, test.err) } } } func (*ConfigSuite) TestConfigString(c *gc.C) { for i, test := range []struct { config Config expected string }{{ config: nil, expected: "", }, { config: Config{"": INFO}, expected: "<root>=INFO", }, { config: Config{"": UNSPECIFIED}, expected: "<root>=UNSPECIFIED", }, { config: Config{"": DEBUG}, expected: "<root>=DEBUG", }, { config: Config{"test.module": DEBUG}, expected: "test.module=DEBUG", }, { config: Config{ "": WARNING, "module": INFO, "sub.module": DEBUG, "other.module": WARNING, }, expected: "<root>=WARNING;module=INFO;other.module=WARNING;sub.module=DEBUG", }} { c.Logf("%d: %q", i, test.expected) c.Check(test.config.String(), gc.Equals, test.expected) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/config.go�������������������������������������������������0000644�0610621�0607500�00000005076�13172163311�023147� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo import ( "fmt" "sort" "strings" ) // Config is a mapping of logger module names to logging severity levels. type Config map[string]Level // String returns a logger configuration string that may be parsed // using ParseConfigurationString. func (c Config) String() string { if c == nil { return "" } // output in alphabetical order. names := []string{} for name := range c { names = append(names, name) } sort.Strings(names) var entries []string for _, name := range names { level := c[name] if name == "" { name = rootString } entry := fmt.Sprintf("%s=%s", name, level) entries = append(entries, entry) } return strings.Join(entries, ";") } func parseConfigValue(value string) (string, Level, error) { pair := strings.SplitN(value, "=", 2) if len(pair) < 2 { return "", UNSPECIFIED, fmt.Errorf("config value expected '=', found %q", value) } name := strings.TrimSpace(pair[0]) if name == "" { return "", UNSPECIFIED, fmt.Errorf("config value %q has missing module name", value) } levelStr := strings.TrimSpace(pair[1]) level, ok := ParseLevel(levelStr) if !ok { return "", UNSPECIFIED, fmt.Errorf("unknown severity level %q", levelStr) } if name == rootString { name = "" } return name, level, nil } // ParseConfigString parses a logger configuration string into a map of logger // names and their associated log level. This method is provided to allow // other programs to pre-validate a configuration string rather than just // calling ConfigureLoggers. // // Logging modules are colon- or semicolon-separated; each module is specified // as <modulename>=<level>. White space outside of module names and levels is // ignored. The root module is specified with the name "<root>". // // As a special case, a log level may be specified on its own. // This is equivalent to specifying the level of the root module, // so "DEBUG" is equivalent to `<root>=DEBUG` // // An example specification: // `<root>=ERROR; foo.bar=WARNING` func ParseConfigString(specification string) (Config, error) { specification = strings.TrimSpace(specification) if specification == "" { return nil, nil } cfg := make(Config) if level, ok := ParseLevel(specification); ok { cfg[""] = level return cfg, nil } values := strings.FieldsFunc(specification, func(r rune) bool { return r == ';' || r == ':' }) for _, value := range values { name, level, err := parseConfigValue(value) if err != nil { return nil, err } cfg[name] = level } return cfg, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/checkers_test.go������������������������������������������0000644�0610621�0607500�00000001753�13172163311�024526� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "fmt" "time" gc "gopkg.in/check.v1" ) func Between(start, end time.Time) gc.Checker { if end.Before(start) { return &betweenChecker{end, start} } return &betweenChecker{start, end} } type betweenChecker struct { start, end time.Time } func (checker *betweenChecker) Info() *gc.CheckerInfo { info := gc.CheckerInfo{ Name: "Between", Params: []string{"obtained"}, } return &info } func (checker *betweenChecker) Check(params []interface{}, names []string) (result bool, error string) { when, ok := params[0].(time.Time) if !ok { return false, "obtained value type must be time.Time" } if when.Before(checker.start) { return false, fmt.Sprintf("obtained time %q is before start time %q", when, checker.start) } if when.After(checker.end) { return false, fmt.Sprintf("obtained time %q is after end time %q", when, checker.end) } return true, "" } ���������������������lxd-2.0.11/dist/src/github.com/juju/loggo/benchmarks_test.go����������������������������������������0000644�0610621�0607500�00000005517�13172163311�025056� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package loggo_test import ( "io/ioutil" "os" "github.com/juju/loggo" gc "gopkg.in/check.v1" ) type BenchmarksSuite struct { logger loggo.Logger writer *writer } var _ = gc.Suite(&BenchmarksSuite{}) func (s *BenchmarksSuite) SetUpTest(c *gc.C) { loggo.ResetLogging() s.logger = loggo.GetLogger("test.writer") s.writer = &writer{} err := loggo.RegisterWriter("test", s.writer) c.Assert(err, gc.IsNil) } func (s *BenchmarksSuite) BenchmarkLoggingNoWriters(c *gc.C) { // No writers loggo.RemoveWriter("test") for i := 0; i < c.N; i++ { s.logger.Warningf("just a simple warning for %d", i) } } func (s *BenchmarksSuite) BenchmarkLoggingNoWritersNoFormat(c *gc.C) { // No writers loggo.RemoveWriter("test") for i := 0; i < c.N; i++ { s.logger.Warningf("just a simple warning") } } func (s *BenchmarksSuite) BenchmarkLoggingTestWriters(c *gc.C) { for i := 0; i < c.N; i++ { s.logger.Warningf("just a simple warning for %d", i) } c.Assert(s.writer.Log(), gc.HasLen, c.N) } func (s *BenchmarksSuite) BenchmarkLoggingDiskWriter(c *gc.C) { logFile := s.setupTempFileWriter(c) defer logFile.Close() msg := "just a simple warning for %d" for i := 0; i < c.N; i++ { s.logger.Warningf(msg, i) } offset, err := logFile.Seek(0, os.SEEK_CUR) c.Assert(err, gc.IsNil) c.Assert((offset > int64(len(msg))*int64(c.N)), gc.Equals, true, gc.Commentf("Not enough data was written to the log file.")) } func (s *BenchmarksSuite) BenchmarkLoggingDiskWriterNoMessages(c *gc.C) { logFile := s.setupTempFileWriter(c) defer logFile.Close() // Change the log level writer, err := loggo.RemoveWriter("testfile") c.Assert(err, gc.IsNil) loggo.RegisterWriter("testfile", loggo.NewMinimumLevelWriter(writer, loggo.WARNING)) msg := "just a simple warning for %d" for i := 0; i < c.N; i++ { s.logger.Debugf(msg, i) } offset, err := logFile.Seek(0, os.SEEK_CUR) c.Assert(err, gc.IsNil) c.Assert(offset, gc.Equals, int64(0), gc.Commentf("Data was written to the log file.")) } func (s *BenchmarksSuite) BenchmarkLoggingDiskWriterNoMessagesLogLevel(c *gc.C) { logFile := s.setupTempFileWriter(c) defer logFile.Close() // Change the log level s.logger.SetLogLevel(loggo.WARNING) msg := "just a simple warning for %d" for i := 0; i < c.N; i++ { s.logger.Debugf(msg, i) } offset, err := logFile.Seek(0, os.SEEK_CUR) c.Assert(err, gc.IsNil) c.Assert(offset, gc.Equals, int64(0), gc.Commentf("Data was written to the log file.")) } func (s *BenchmarksSuite) setupTempFileWriter(c *gc.C) *os.File { loggo.RemoveWriter("test") logFile, err := ioutil.TempFile(c.MkDir(), "loggo-test") c.Assert(err, gc.IsNil) writer := loggo.NewSimpleWriter(logFile, loggo.DefaultFormatter) err = loggo.RegisterWriter("testfile", writer) c.Assert(err, gc.IsNil) return logFile } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/README.md�������������������������������������������������0000644�0610621�0607500�00000036726�13172163311�022640� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� # loggo import "github.com/juju/loggo" [![GoDoc](https://godoc.org/github.com/juju/loggo?status.svg)](https://godoc.org/github.com/juju/loggo) ### Module level logging for Go This package provides an alternative to the standard library log package. The actual logging functions never return errors. If you are logging something, you really don't want to be worried about the logging having trouble. Modules have names that are defined by dotted strings. "first.second.third" There is a root module that has the name `""`. Each module (except the root module) has a parent, identified by the part of the name without the last dotted value. * the parent of "first.second.third" is "first.second" * the parent of "first.second" is "first" * the parent of "first" is "" (the root module) Each module can specify its own severity level. Logging calls that are of a lower severity than the module's effective severity level are not written out. Loggers are created using the GetLogger function. logger := loggo.GetLogger("foo.bar") By default there is one writer registered, which will write to Stderr, and the root module, which will only emit warnings and above. If you want to continue using the default logger, but have it emit all logging levels you need to do the following. writer, _, err := loggo.RemoveWriter("default") // err is non-nil if and only if the name isn't found. loggo.RegisterWriter("default", writer, loggo.TRACE) ## Constants ``` go const DefaultWriterName = "default" ``` DefaultWriterName is the name of the default writer for a Context. ## Variables ``` go var ( // SeverityColor defines the colors for the levels output by the ColorWriter. SeverityColor = map[Level]*ansiterm.Context{ TRACE: ansiterm.Foreground(ansiterm.Default), DEBUG: ansiterm.Foreground(ansiterm.Green), INFO: ansiterm.Foreground(ansiterm.BrightBlue), WARNING: ansiterm.Foreground(ansiterm.Yellow), ERROR: ansiterm.Foreground(ansiterm.BrightRed), CRITICAL: &ansiterm.Context{ Foreground: ansiterm.White, Background: ansiterm.Red, }, } // LocationColor defines the colors for the location output by the ColorWriter. LocationColor = ansiterm.Foreground(ansiterm.BrightBlue) ) ``` ``` go var TimeFormat = initTimeFormat() ``` TimeFormat is the time format used for the default writer. This can be set with the environment variable LOGGO_TIME_FORMAT. ## func ConfigureLoggers ``` go func ConfigureLoggers(specification string) error ``` ConfigureLoggers configures loggers according to the given string specification, which specifies a set of modules and their associated logging levels. Loggers are colon- or semicolon-separated; each module is specified as <modulename>=<level>. White space outside of module names and levels is ignored. The root module is specified with the name "<root>". An example specification: `<root>=ERROR; foo.bar=WARNING` ## func DefaultFormatter ``` go func DefaultFormatter(entry Entry) string ``` DefaultFormatter returns the parameters separated by spaces except for filename and line which are separated by a colon. The timestamp is shown to second resolution in UTC. For example: 2016-07-02 15:04:05 ## func LoggerInfo ``` go func LoggerInfo() string ``` LoggerInfo returns information about the configured loggers and their logging levels. The information is returned in the format expected by ConfigureLoggers. Loggers with UNSPECIFIED level will not be included. ## func RegisterWriter ``` go func RegisterWriter(name string, writer Writer) error ``` RegisterWriter adds the writer to the list of writers in the DefaultContext that get notified when logging. If there is already a registered writer with that name, an error is returned. ## func ResetLogging ``` go func ResetLogging() ``` ResetLogging iterates through the known modules and sets the levels of all to UNSPECIFIED, except for <root> which is set to WARNING. The call also removes all writers in the DefaultContext and puts the original default writer back as the only writer. ## func ResetWriters ``` go func ResetWriters() ``` ResetWriters puts the list of writers back into the initial state. ## type Config ``` go type Config map[string]Level ``` Config is a mapping of logger module names to logging severity levels. ### func ParseConfigString ``` go func ParseConfigString(specification string) (Config, error) ``` ParseConfigString parses a logger configuration string into a map of logger names and their associated log level. This method is provided to allow other programs to pre-validate a configuration string rather than just calling ConfigureLoggers. Logging modules are colon- or semicolon-separated; each module is specified as <modulename>=<level>. White space outside of module names and levels is ignored. The root module is specified with the name "<root>". As a special case, a log level may be specified on its own. This is equivalent to specifying the level of the root module, so "DEBUG" is equivalent to `<root>=DEBUG` An example specification: `<root>=ERROR; foo.bar=WARNING` ### func (Config) String ``` go func (c Config) String() string ``` String returns a logger configuration string that may be parsed using ParseConfigurationString. ## type Context ``` go type Context struct { // contains filtered or unexported fields } ``` Context produces loggers for a hierarchy of modules. The context holds a collection of hierarchical loggers and their writers. ### func DefaultContext ``` go func DefaultContext() *Context ``` DefaultContext returns the global default logging context. ### func NewContext ``` go func NewContext(rootLevel Level) *Context ``` NewLoggers returns a new Context with no writers set. If the root level is UNSPECIFIED, WARNING is used. ### func (\*Context) AddWriter ``` go func (c *Context) AddWriter(name string, writer Writer) error ``` AddWriter adds a writer to the list to be called for each logging call. The name cannot be empty, and the writer cannot be nil. If an existing writer exists with the specified name, an error is returned. ### func (\*Context) ApplyConfig ``` go func (c *Context) ApplyConfig(config Config) ``` ApplyConfig configures the logging modules according to the provided config. ### func (\*Context) CompleteConfig ``` go func (c *Context) CompleteConfig() Config ``` CompleteConfig returns all the loggers and their defined levels, even if that level is UNSPECIFIED. ### func (\*Context) Config ``` go func (c *Context) Config() Config ``` Config returns the current configuration of the Loggers. Loggers with UNSPECIFIED level will not be included. ### func (\*Context) GetLogger ``` go func (c *Context) GetLogger(name string) Logger ``` GetLogger returns a Logger for the given module name, creating it and its parents if necessary. ### func (\*Context) RemoveWriter ``` go func (c *Context) RemoveWriter(name string) (Writer, error) ``` RemoveWriter remotes the specified writer. If a writer is not found with the specified name an error is returned. The writer that was removed is also returned. ### func (\*Context) ReplaceWriter ``` go func (c *Context) ReplaceWriter(name string, writer Writer) (Writer, error) ``` ReplaceWriter is a convenience method that does the equivalent of RemoveWriter followed by AddWriter with the same name. The replaced writer is returned. ### func (\*Context) ResetLoggerLevels ``` go func (c *Context) ResetLoggerLevels() ``` ResetLoggerLevels iterates through the known logging modules and sets the levels of all to UNSPECIFIED, except for <root> which is set to WARNING. ### func (\*Context) ResetWriters ``` go func (c *Context) ResetWriters() ``` ResetWriters is generally only used in testing and removes all the writers. ## type Entry ``` go type Entry struct { // Level is the severity of the log message. Level Level // Module is the dotted module name from the logger. Module string // Filename is the full path the file that logged the message. Filename string // Line is the line number of the Filename. Line int // Timestamp is when the log message was created Timestamp time.Time // Message is the formatted string from teh log call. Message string } ``` Entry represents a single log message. ## type Level ``` go type Level uint32 ``` Level holds a severity level. ``` go const ( UNSPECIFIED Level = iota TRACE DEBUG INFO WARNING ERROR CRITICAL ) ``` The severity levels. Higher values are more considered more important. ### func ParseLevel ``` go func ParseLevel(level string) (Level, bool) ``` ParseLevel converts a string representation of a logging level to a Level. It returns the level and whether it was valid or not. ### func (Level) Short ``` go func (level Level) Short() string ``` Short returns a five character string to use in aligned logging output. ### func (Level) String ``` go func (level Level) String() string ``` String implements Stringer. ## type Logger ``` go type Logger struct { // contains filtered or unexported fields } ``` A Logger represents a logging module. It has an associated logging level which can be changed; messages of lesser severity will be dropped. Loggers have a hierarchical relationship - see the package documentation. The zero Logger value is usable - any messages logged to it will be sent to the root Logger. ### func GetLogger ``` go func GetLogger(name string) Logger ``` GetLogger returns a Logger for the given module name, creating it and its parents if necessary. ### func (Logger) Criticalf ``` go func (logger Logger) Criticalf(message string, args ...interface{}) ``` Criticalf logs the printf-formatted message at critical level. ### func (Logger) Debugf ``` go func (logger Logger) Debugf(message string, args ...interface{}) ``` Debugf logs the printf-formatted message at debug level. ### func (Logger) EffectiveLogLevel ``` go func (logger Logger) EffectiveLogLevel() Level ``` EffectiveLogLevel returns the effective min log level of the receiver - that is, messages with a lesser severity level will be discarded. If the log level of the receiver is unspecified, it will be taken from the effective log level of its parent. ### func (Logger) Errorf ``` go func (logger Logger) Errorf(message string, args ...interface{}) ``` Errorf logs the printf-formatted message at error level. ### func (Logger) Infof ``` go func (logger Logger) Infof(message string, args ...interface{}) ``` Infof logs the printf-formatted message at info level. ### func (Logger) IsDebugEnabled ``` go func (logger Logger) IsDebugEnabled() bool ``` IsDebugEnabled returns whether debugging is enabled at debug level. ### func (Logger) IsErrorEnabled ``` go func (logger Logger) IsErrorEnabled() bool ``` IsErrorEnabled returns whether debugging is enabled at error level. ### func (Logger) IsInfoEnabled ``` go func (logger Logger) IsInfoEnabled() bool ``` IsInfoEnabled returns whether debugging is enabled at info level. ### func (Logger) IsLevelEnabled ``` go func (logger Logger) IsLevelEnabled(level Level) bool ``` IsLevelEnabled returns whether debugging is enabled for the given log level. ### func (Logger) IsTraceEnabled ``` go func (logger Logger) IsTraceEnabled() bool ``` IsTraceEnabled returns whether debugging is enabled at trace level. ### func (Logger) IsWarningEnabled ``` go func (logger Logger) IsWarningEnabled() bool ``` IsWarningEnabled returns whether debugging is enabled at warning level. ### func (Logger) LogCallf ``` go func (logger Logger) LogCallf(calldepth int, level Level, message string, args ...interface{}) ``` LogCallf logs a printf-formatted message at the given level. The location of the call is indicated by the calldepth argument. A calldepth of 1 means the function that called this function. A message will be discarded if level is less than the the effective log level of the logger. Note that the writers may also filter out messages that are less than their registered minimum severity level. ### func (Logger) LogLevel ``` go func (logger Logger) LogLevel() Level ``` LogLevel returns the configured min log level of the logger. ### func (Logger) Logf ``` go func (logger Logger) Logf(level Level, message string, args ...interface{}) ``` Logf logs a printf-formatted message at the given level. A message will be discarded if level is less than the the effective log level of the logger. Note that the writers may also filter out messages that are less than their registered minimum severity level. ### func (Logger) Name ``` go func (logger Logger) Name() string ``` Name returns the logger's module name. ### func (Logger) SetLogLevel ``` go func (logger Logger) SetLogLevel(level Level) ``` SetLogLevel sets the severity level of the given logger. The root logger cannot be set to UNSPECIFIED level. See EffectiveLogLevel for how this affects the actual messages logged. ### func (Logger) Tracef ``` go func (logger Logger) Tracef(message string, args ...interface{}) ``` Tracef logs the printf-formatted message at trace level. ### func (Logger) Warningf ``` go func (logger Logger) Warningf(message string, args ...interface{}) ``` Warningf logs the printf-formatted message at warning level. ## type TestWriter ``` go type TestWriter struct { // contains filtered or unexported fields } ``` TestWriter is a useful Writer for testing purposes. Each component of the logging message is stored in the Log array. ### func (\*TestWriter) Clear ``` go func (writer *TestWriter) Clear() ``` Clear removes any saved log messages. ### func (\*TestWriter) Log ``` go func (writer *TestWriter) Log() []Entry ``` Log returns a copy of the current logged values. ### func (\*TestWriter) Write ``` go func (writer *TestWriter) Write(entry Entry) ``` Write saves the params as members in the TestLogValues struct appended to the Log array. ## type Writer ``` go type Writer interface { // Write writes a message to the Writer with the given level and module // name. The filename and line hold the file name and line number of the // code that is generating the log message; the time stamp holds the time // the log message was generated, and message holds the log message // itself. Write(entry Entry) } ``` Writer is implemented by any recipient of log messages. ### func NewColorWriter ``` go func NewColorWriter(writer io.Writer) Writer ``` NewColorWriter will write out colored severity levels if the writer is outputting to a terminal. ### func NewMinimumLevelWriter ``` go func NewMinimumLevelWriter(writer Writer, minLevel Level) Writer ``` NewMinLevelWriter returns a Writer that will only pass on the Write calls to the provided writer if the log level is at or above the specified minimum level. ### func NewSimpleWriter ``` go func NewSimpleWriter(writer io.Writer, formatter func(entry Entry) string) Writer ``` NewSimpleWriter returns a new writer that writes log messages to the given io.Writer formatting the messages with the given formatter. ### func RemoveWriter ``` go func RemoveWriter(name string) (Writer, error) ``` RemoveWriter removes the Writer identified by 'name' and returns it. If the Writer is not found, an error is returned. ### func ReplaceDefaultWriter ``` go func ReplaceDefaultWriter(writer Writer) (Writer, error) ``` ReplaceDefaultWriter is a convenience method that does the equivalent of RemoveWriter and then RegisterWriter with the name "default". The previous default writer, if any is returned. - - - Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md)������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/Makefile��������������������������������������������������0000644�0610621�0607500�00000000404�13172163311�023001� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������default: check check: go test docs: godoc2md github.com/juju/loggo > README.md sed -i 's|\[godoc-link-here\]|[![GoDoc](https://godoc.org/github.com/juju/loggo?status.svg)](https://godoc.org/github.com/juju/loggo)|' README.md .PHONY: default check docs ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/juju/loggo/LICENSE���������������������������������������������������0000644�0610621�0607500�00000021501�13172163311�022347� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������All files in this repository are licensed as follows. If you contribute to this repository, it is assumed that you license your contribution under the same license unless you state otherwise. All files Copyright (C) 2015 Canonical Ltd. unless otherwise specified in the file. This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/�������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163434�020716� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/context/�����������������������������������������������������0000755�0610621�0607500�00000000000�13172163435�022403� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/context/doc.go�����������������������������������������������0000644�0610621�0607500�00000005433�13172163435�023504� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package context stores values shared during a request lifetime. Note: gorilla/context, having been born well before `context.Context` existed, does not play well > with the shallow copying of the request that [`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) (added to net/http Go 1.7 onwards) performs. You should either use *just* gorilla/context, or moving forward, the new `http.Request.Context()`. For example, a router can set variables extracted from the URL and later application handlers can access those values, or it can be used to store sessions values to be saved at the end of a request. There are several others common uses. The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 Here's the basic usage: first define the keys that you will need. The key type is interface{} so a key can be of any type that supports equality. Here we define a key using a custom int type to avoid name collisions: package foo import ( "github.com/gorilla/context" ) type key int const MyKey key = 0 Then set a variable. Variables are bound to an http.Request object, so you need a request instance to set a value: context.Set(r, MyKey, "bar") The application can later access the variable using the same key you provided: func MyHandler(w http.ResponseWriter, r *http.Request) { // val is "bar". val := context.Get(r, foo.MyKey) // returns ("bar", true) val, ok := context.GetOk(r, foo.MyKey) // ... } And that's all about the basic usage. We discuss some other ideas below. Any type can be stored in the context. To enforce a given type, make the key private and wrap Get() and Set() to accept and return values of a specific type: type key int const mykey key = 0 // GetMyKey returns a value for this package from the request values. func GetMyKey(r *http.Request) SomeType { if rv := context.Get(r, mykey); rv != nil { return rv.(SomeType) } return nil } // SetMyKey sets a value for this package in the request values. func SetMyKey(r *http.Request, val SomeType) { context.Set(r, mykey, val) } Variables must be cleared at the end of a request, to remove all values that were stored. This can be done in an http.Handler, after a request was served. Just call Clear() passing the request: context.Clear(r) ...or use ClearHandler(), which conveniently wraps an http.Handler to clear variables at the end of a request lifetime. The Routers from the packages gorilla/mux and gorilla/pat call Clear() so if you are using either of them you don't need to clear the context manually. */ package context �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/context/context_test.go��������������������������������������0000644�0610621�0607500�00000006337�13172163435�025466� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package context import ( "net/http" "testing" ) type keyType int const ( key1 keyType = iota key2 ) func TestContext(t *testing.T) { assertEqual := func(val interface{}, exp interface{}) { if val != exp { t.Errorf("Expected %v, got %v.", exp, val) } } r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) // Get() assertEqual(Get(r, key1), nil) // Set() Set(r, key1, "1") assertEqual(Get(r, key1), "1") assertEqual(len(data[r]), 1) Set(r, key2, "2") assertEqual(Get(r, key2), "2") assertEqual(len(data[r]), 2) //GetOk value, ok := GetOk(r, key1) assertEqual(value, "1") assertEqual(ok, true) value, ok = GetOk(r, "not exists") assertEqual(value, nil) assertEqual(ok, false) Set(r, "nil value", nil) value, ok = GetOk(r, "nil value") assertEqual(value, nil) assertEqual(ok, true) // GetAll() values := GetAll(r) assertEqual(len(values), 3) // GetAll() for empty request values = GetAll(emptyR) if values != nil { t.Error("GetAll didn't return nil value for invalid request") } // GetAllOk() values, ok = GetAllOk(r) assertEqual(len(values), 3) assertEqual(ok, true) // GetAllOk() for empty request values, ok = GetAllOk(emptyR) assertEqual(len(values), 0) assertEqual(ok, false) // Delete() Delete(r, key1) assertEqual(Get(r, key1), nil) assertEqual(len(data[r]), 2) Delete(r, key2) assertEqual(Get(r, key2), nil) assertEqual(len(data[r]), 1) // Clear() Clear(r) assertEqual(len(data), 0) } func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { <-wait for i := 0; i < iterations; i++ { Get(r, key) } done <- struct{}{} } func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { <-wait for i := 0; i < iterations; i++ { Set(r, key, value) } done <- struct{}{} } func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { b.StopTimer() r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) done := make(chan struct{}) b.StartTimer() for i := 0; i < b.N; i++ { wait := make(chan struct{}) for i := 0; i < numReaders; i++ { go parallelReader(r, "test", iterations, wait, done) } for i := 0; i < numWriters; i++ { go parallelWriter(r, "test", "123", iterations, wait, done) } close(wait) for i := 0; i < numReaders+numWriters; i++ { <-done } } } func BenchmarkMutexSameReadWrite1(b *testing.B) { benchmarkMutex(b, 1, 1, 32) } func BenchmarkMutexSameReadWrite2(b *testing.B) { benchmarkMutex(b, 2, 2, 32) } func BenchmarkMutexSameReadWrite4(b *testing.B) { benchmarkMutex(b, 4, 4, 32) } func BenchmarkMutex1(b *testing.B) { benchmarkMutex(b, 2, 8, 32) } func BenchmarkMutex2(b *testing.B) { benchmarkMutex(b, 16, 4, 64) } func BenchmarkMutex3(b *testing.B) { benchmarkMutex(b, 1, 2, 128) } func BenchmarkMutex4(b *testing.B) { benchmarkMutex(b, 128, 32, 256) } func BenchmarkMutex5(b *testing.B) { benchmarkMutex(b, 1024, 2048, 64) } func BenchmarkMutex6(b *testing.B) { benchmarkMutex(b, 2048, 1024, 512) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/context/context.go�������������������������������������������0000644�0610621�0607500�00000006777�13172163435�024437� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package context import ( "net/http" "sync" "time" ) var ( mutex sync.RWMutex data = make(map[*http.Request]map[interface{}]interface{}) datat = make(map[*http.Request]int64) ) // Set stores a value for a given key in a given request. func Set(r *http.Request, key, val interface{}) { mutex.Lock() if data[r] == nil { data[r] = make(map[interface{}]interface{}) datat[r] = time.Now().Unix() } data[r][key] = val mutex.Unlock() } // Get returns a value stored for a given key in a given request. func Get(r *http.Request, key interface{}) interface{} { mutex.RLock() if ctx := data[r]; ctx != nil { value := ctx[key] mutex.RUnlock() return value } mutex.RUnlock() return nil } // GetOk returns stored value and presence state like multi-value return of map access. func GetOk(r *http.Request, key interface{}) (interface{}, bool) { mutex.RLock() if _, ok := data[r]; ok { value, ok := data[r][key] mutex.RUnlock() return value, ok } mutex.RUnlock() return nil, false } // GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. func GetAll(r *http.Request) map[interface{}]interface{} { mutex.RLock() if context, ok := data[r]; ok { result := make(map[interface{}]interface{}, len(context)) for k, v := range context { result[k] = v } mutex.RUnlock() return result } mutex.RUnlock() return nil } // GetAllOk returns all stored values for the request as a map and a boolean value that indicates if // the request was registered. func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { mutex.RLock() context, ok := data[r] result := make(map[interface{}]interface{}, len(context)) for k, v := range context { result[k] = v } mutex.RUnlock() return result, ok } // Delete removes a value stored for a given key in a given request. func Delete(r *http.Request, key interface{}) { mutex.Lock() if data[r] != nil { delete(data[r], key) } mutex.Unlock() } // Clear removes all values stored for a given request. // // This is usually called by a handler wrapper to clean up request // variables at the end of a request lifetime. See ClearHandler(). func Clear(r *http.Request) { mutex.Lock() clear(r) mutex.Unlock() } // clear is Clear without the lock. func clear(r *http.Request) { delete(data, r) delete(datat, r) } // Purge removes request data stored for longer than maxAge, in seconds. // It returns the amount of requests removed. // // If maxAge <= 0, all request data is removed. // // This is only used for sanity check: in case context cleaning was not // properly set some request data can be kept forever, consuming an increasing // amount of memory. In case this is detected, Purge() must be called // periodically until the problem is fixed. func Purge(maxAge int) int { mutex.Lock() count := 0 if maxAge <= 0 { count = len(data) data = make(map[*http.Request]map[interface{}]interface{}) datat = make(map[*http.Request]int64) } else { min := time.Now().Unix() - int64(maxAge) for r := range data { if datat[r] < min { clear(r) count++ } } } mutex.Unlock() return count } // ClearHandler wraps an http.Handler and clears request values at the end // of a request lifetime. func ClearHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer Clear(r) h.ServeHTTP(w, r) }) } �lxd-2.0.11/dist/src/github.com/gorilla/context/README.md��������������������������������������������0000644�0610621�0607500�00000001223�13172163435�023660� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������context ======= [![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) gorilla/context is a general purpose registry for global request variables. > Note: gorilla/context, having been born well before `context.Context` existed, does not play well > with the shallow copying of the request that [`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) (added to net/http Go 1.7 onwards) performs. You should either use *just* gorilla/context, or moving forward, the new `http.Request.Context()`. Read the full documentation here: http://www.gorillatoolkit.org/pkg/context �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/context/LICENSE����������������������������������������������0000644�0610621�0607500�00000002704�13172163435�023413� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2012 Rodrigo Moraes. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/context/.travis.yml������������������������������������������0000644�0610621�0607500�00000000460�13172163435�024514� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go sudo: false matrix: include: - go: 1.3 - go: 1.4 - go: 1.5 - go: 1.6 - go: 1.7 - go: tip allow_failures: - go: tip script: - go get -t -v ./... - diff -u <(echo -n) <(gofmt -d .) - go vet $(go list ./... | grep -v /vendor/) - go test -v -race ./... ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/���������������������������������������������������������0000755�0610621�0607500�00000000000�13172163423�021525� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/route.go�������������������������������������������������0000644�0610621�0607500�00000047721�13172163423�023225� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mux import ( "errors" "fmt" "net/http" "net/url" "regexp" "strings" ) // Route stores information to match a request and build URLs. type Route struct { // Parent where the route was registered (a Router). parent parentRoute // Request handler for the route. handler http.Handler // List of matchers. matchers []matcher // Manager for the variables from host and path. regexp *routeRegexpGroup // If true, when the path pattern is "/path/", accessing "/path" will // redirect to the former and vice versa. strictSlash bool // If true, when the path pattern is "/path//to", accessing "/path//to" // will not redirect skipClean bool // If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to" useEncodedPath bool // The scheme used when building URLs. buildScheme string // If true, this route never matches: it is only used to build URLs. buildOnly bool // The name used to build URLs. name string // Error resulted from building a route. err error buildVarsFunc BuildVarsFunc } func (r *Route) SkipClean() bool { return r.skipClean } // Match matches the route against the request. func (r *Route) Match(req *http.Request, match *RouteMatch) bool { if r.buildOnly || r.err != nil { return false } var matchErr error // Match everything. for _, m := range r.matchers { if matched := m.Match(req, match); !matched { if _, ok := m.(methodMatcher); ok { matchErr = ErrMethodMismatch continue } matchErr = nil return false } } if matchErr != nil { match.MatchErr = matchErr return false } match.MatchErr = nil // Yay, we have a match. Let's collect some info about it. if match.Route == nil { match.Route = r } if match.Handler == nil { match.Handler = r.handler } if match.Vars == nil { match.Vars = make(map[string]string) } // Set variables. if r.regexp != nil { r.regexp.setMatch(req, match, r) } return true } // ---------------------------------------------------------------------------- // Route attributes // ---------------------------------------------------------------------------- // GetError returns an error resulted from building the route, if any. func (r *Route) GetError() error { return r.err } // BuildOnly sets the route to never match: it is only used to build URLs. func (r *Route) BuildOnly() *Route { r.buildOnly = true return r } // Handler -------------------------------------------------------------------- // Handler sets a handler for the route. func (r *Route) Handler(handler http.Handler) *Route { if r.err == nil { r.handler = handler } return r } // HandlerFunc sets a handler function for the route. func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route { return r.Handler(http.HandlerFunc(f)) } // GetHandler returns the handler for the route, if any. func (r *Route) GetHandler() http.Handler { return r.handler } // Name ----------------------------------------------------------------------- // Name sets the name for the route, used to build URLs. // If the name was registered already it will be overwritten. func (r *Route) Name(name string) *Route { if r.name != "" { r.err = fmt.Errorf("mux: route already has name %q, can't set %q", r.name, name) } if r.err == nil { r.name = name r.getNamedRoutes()[name] = r } return r } // GetName returns the name for the route, if any. func (r *Route) GetName() string { return r.name } // ---------------------------------------------------------------------------- // Matchers // ---------------------------------------------------------------------------- // matcher types try to match a request. type matcher interface { Match(*http.Request, *RouteMatch) bool } // addMatcher adds a matcher to the route. func (r *Route) addMatcher(m matcher) *Route { if r.err == nil { r.matchers = append(r.matchers, m) } return r } // addRegexpMatcher adds a host or path matcher and builder to a route. func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error { if r.err != nil { return r.err } r.regexp = r.getRegexpGroup() if !matchHost && !matchQuery { if len(tpl) > 0 && tpl[0] != '/' { return fmt.Errorf("mux: path must start with a slash, got %q", tpl) } if r.regexp.path != nil { tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl } } rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash, r.useEncodedPath) if err != nil { return err } for _, q := range r.regexp.queries { if err = uniqueVars(rr.varsN, q.varsN); err != nil { return err } } if matchHost { if r.regexp.path != nil { if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { return err } } r.regexp.host = rr } else { if r.regexp.host != nil { if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { return err } } if matchQuery { r.regexp.queries = append(r.regexp.queries, rr) } else { r.regexp.path = rr } } r.addMatcher(rr) return nil } // Headers -------------------------------------------------------------------- // headerMatcher matches the request against header values. type headerMatcher map[string]string func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool { return matchMapWithString(m, r.Header, true) } // Headers adds a matcher for request header values. // It accepts a sequence of key/value pairs to be matched. For example: // // r := mux.NewRouter() // r.Headers("Content-Type", "application/json", // "X-Requested-With", "XMLHttpRequest") // // The above route will only match if both request header values match. // If the value is an empty string, it will match any value if the key is set. func (r *Route) Headers(pairs ...string) *Route { if r.err == nil { var headers map[string]string headers, r.err = mapFromPairsToString(pairs...) return r.addMatcher(headerMatcher(headers)) } return r } // headerRegexMatcher matches the request against the route given a regex for the header type headerRegexMatcher map[string]*regexp.Regexp func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool { return matchMapWithRegex(m, r.Header, true) } // HeadersRegexp accepts a sequence of key/value pairs, where the value has regex // support. For example: // // r := mux.NewRouter() // r.HeadersRegexp("Content-Type", "application/(text|json)", // "X-Requested-With", "XMLHttpRequest") // // The above route will only match if both the request header matches both regular expressions. // It the value is an empty string, it will match any value if the key is set. func (r *Route) HeadersRegexp(pairs ...string) *Route { if r.err == nil { var headers map[string]*regexp.Regexp headers, r.err = mapFromPairsToRegex(pairs...) return r.addMatcher(headerRegexMatcher(headers)) } return r } // Host ----------------------------------------------------------------------- // Host adds a matcher for the URL host. // It accepts a template with zero or more URL variables enclosed by {}. // Variables can define an optional regexp pattern to be matched: // // - {name} matches anything until the next dot. // // - {name:pattern} matches the given regexp pattern. // // For example: // // r := mux.NewRouter() // r.Host("www.example.com") // r.Host("{subdomain}.domain.com") // r.Host("{subdomain:[a-z]+}.domain.com") // // Variable names must be unique in a given route. They can be retrieved // calling mux.Vars(request). func (r *Route) Host(tpl string) *Route { r.err = r.addRegexpMatcher(tpl, true, false, false) return r } // MatcherFunc ---------------------------------------------------------------- // MatcherFunc is the function signature used by custom matchers. type MatcherFunc func(*http.Request, *RouteMatch) bool // Match returns the match for a given request. func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool { return m(r, match) } // MatcherFunc adds a custom function to be used as request matcher. func (r *Route) MatcherFunc(f MatcherFunc) *Route { return r.addMatcher(f) } // Methods -------------------------------------------------------------------- // methodMatcher matches the request against HTTP methods. type methodMatcher []string func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool { return matchInArray(m, r.Method) } // Methods adds a matcher for HTTP methods. // It accepts a sequence of one or more methods to be matched, e.g.: // "GET", "POST", "PUT". func (r *Route) Methods(methods ...string) *Route { for k, v := range methods { methods[k] = strings.ToUpper(v) } return r.addMatcher(methodMatcher(methods)) } // Path ----------------------------------------------------------------------- // Path adds a matcher for the URL path. // It accepts a template with zero or more URL variables enclosed by {}. The // template must start with a "/". // Variables can define an optional regexp pattern to be matched: // // - {name} matches anything until the next slash. // // - {name:pattern} matches the given regexp pattern. // // For example: // // r := mux.NewRouter() // r.Path("/products/").Handler(ProductsHandler) // r.Path("/products/{key}").Handler(ProductsHandler) // r.Path("/articles/{category}/{id:[0-9]+}"). // Handler(ArticleHandler) // // Variable names must be unique in a given route. They can be retrieved // calling mux.Vars(request). func (r *Route) Path(tpl string) *Route { r.err = r.addRegexpMatcher(tpl, false, false, false) return r } // PathPrefix ----------------------------------------------------------------- // PathPrefix adds a matcher for the URL path prefix. This matches if the given // template is a prefix of the full URL path. See Route.Path() for details on // the tpl argument. // // Note that it does not treat slashes specially ("/foobar/" will be matched by // the prefix "/foo") so you may want to use a trailing slash here. // // Also note that the setting of Router.StrictSlash() has no effect on routes // with a PathPrefix matcher. func (r *Route) PathPrefix(tpl string) *Route { r.err = r.addRegexpMatcher(tpl, false, true, false) return r } // Query ---------------------------------------------------------------------- // Queries adds a matcher for URL query values. // It accepts a sequence of key/value pairs. Values may define variables. // For example: // // r := mux.NewRouter() // r.Queries("foo", "bar", "id", "{id:[0-9]+}") // // The above route will only match if the URL contains the defined queries // values, e.g.: ?foo=bar&id=42. // // It the value is an empty string, it will match any value if the key is set. // // Variables can define an optional regexp pattern to be matched: // // - {name} matches anything until the next slash. // // - {name:pattern} matches the given regexp pattern. func (r *Route) Queries(pairs ...string) *Route { length := len(pairs) if length%2 != 0 { r.err = fmt.Errorf( "mux: number of parameters must be multiple of 2, got %v", pairs) return nil } for i := 0; i < length; i += 2 { if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil { return r } } return r } // Schemes -------------------------------------------------------------------- // schemeMatcher matches the request against URL schemes. type schemeMatcher []string func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool { return matchInArray(m, r.URL.Scheme) } // Schemes adds a matcher for URL schemes. // It accepts a sequence of schemes to be matched, e.g.: "http", "https". func (r *Route) Schemes(schemes ...string) *Route { for k, v := range schemes { schemes[k] = strings.ToLower(v) } if r.buildScheme == "" && len(schemes) > 0 { r.buildScheme = schemes[0] } return r.addMatcher(schemeMatcher(schemes)) } // BuildVarsFunc -------------------------------------------------------------- // BuildVarsFunc is the function signature used by custom build variable // functions (which can modify route variables before a route's URL is built). type BuildVarsFunc func(map[string]string) map[string]string // BuildVarsFunc adds a custom function to be used to modify build variables // before a route's URL is built. func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route { r.buildVarsFunc = f return r } // Subrouter ------------------------------------------------------------------ // Subrouter creates a subrouter for the route. // // It will test the inner routes only if the parent route matched. For example: // // r := mux.NewRouter() // s := r.Host("www.example.com").Subrouter() // s.HandleFunc("/products/", ProductsHandler) // s.HandleFunc("/products/{key}", ProductHandler) // s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) // // Here, the routes registered in the subrouter won't be tested if the host // doesn't match. func (r *Route) Subrouter() *Router { router := &Router{parent: r, strictSlash: r.strictSlash} r.addMatcher(router) return router } // ---------------------------------------------------------------------------- // URL building // ---------------------------------------------------------------------------- // URL builds a URL for the route. // // It accepts a sequence of key/value pairs for the route variables. For // example, given this route: // // r := mux.NewRouter() // r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). // Name("article") // // ...a URL for it can be built using: // // url, err := r.Get("article").URL("category", "technology", "id", "42") // // ...which will return an url.URL with the following path: // // "/articles/technology/42" // // This also works for host variables: // // r := mux.NewRouter() // r.Host("{subdomain}.domain.com"). // HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). // Name("article") // // // url.String() will be "http://news.domain.com/articles/technology/42" // url, err := r.Get("article").URL("subdomain", "news", // "category", "technology", // "id", "42") // // All variables defined in the route are required, and their values must // conform to the corresponding patterns. func (r *Route) URL(pairs ...string) (*url.URL, error) { if r.err != nil { return nil, r.err } if r.regexp == nil { return nil, errors.New("mux: route doesn't have a host or path") } values, err := r.prepareVars(pairs...) if err != nil { return nil, err } var scheme, host, path string queries := make([]string, 0, len(r.regexp.queries)) if r.regexp.host != nil { if host, err = r.regexp.host.url(values); err != nil { return nil, err } scheme = "http" if s := r.getBuildScheme(); s != "" { scheme = s } } if r.regexp.path != nil { if path, err = r.regexp.path.url(values); err != nil { return nil, err } } for _, q := range r.regexp.queries { var query string if query, err = q.url(values); err != nil { return nil, err } queries = append(queries, query) } return &url.URL{ Scheme: scheme, Host: host, Path: path, RawQuery: strings.Join(queries, "&"), }, nil } // URLHost builds the host part of the URL for a route. See Route.URL(). // // The route must have a host defined. func (r *Route) URLHost(pairs ...string) (*url.URL, error) { if r.err != nil { return nil, r.err } if r.regexp == nil || r.regexp.host == nil { return nil, errors.New("mux: route doesn't have a host") } values, err := r.prepareVars(pairs...) if err != nil { return nil, err } host, err := r.regexp.host.url(values) if err != nil { return nil, err } u := &url.URL{ Scheme: "http", Host: host, } if s := r.getBuildScheme(); s != "" { u.Scheme = s } return u, nil } // URLPath builds the path part of the URL for a route. See Route.URL(). // // The route must have a path defined. func (r *Route) URLPath(pairs ...string) (*url.URL, error) { if r.err != nil { return nil, r.err } if r.regexp == nil || r.regexp.path == nil { return nil, errors.New("mux: route doesn't have a path") } values, err := r.prepareVars(pairs...) if err != nil { return nil, err } path, err := r.regexp.path.url(values) if err != nil { return nil, err } return &url.URL{ Path: path, }, nil } // GetPathTemplate returns the template used to build the // route match. // This is useful for building simple REST API documentation and for instrumentation // against third-party services. // An error will be returned if the route does not define a path. func (r *Route) GetPathTemplate() (string, error) { if r.err != nil { return "", r.err } if r.regexp == nil || r.regexp.path == nil { return "", errors.New("mux: route doesn't have a path") } return r.regexp.path.template, nil } // GetPathRegexp returns the expanded regular expression used to match route path. // This is useful for building simple REST API documentation and for instrumentation // against third-party services. // An error will be returned if the route does not define a path. func (r *Route) GetPathRegexp() (string, error) { if r.err != nil { return "", r.err } if r.regexp == nil || r.regexp.path == nil { return "", errors.New("mux: route does not have a path") } return r.regexp.path.regexp.String(), nil } // GetMethods returns the methods the route matches against // This is useful for building simple REST API documentation and for instrumentation // against third-party services. // An empty list will be returned if route does not have methods. func (r *Route) GetMethods() ([]string, error) { if r.err != nil { return nil, r.err } for _, m := range r.matchers { if methods, ok := m.(methodMatcher); ok { return []string(methods), nil } } return nil, nil } // GetHostTemplate returns the template used to build the // route match. // This is useful for building simple REST API documentation and for instrumentation // against third-party services. // An error will be returned if the route does not define a host. func (r *Route) GetHostTemplate() (string, error) { if r.err != nil { return "", r.err } if r.regexp == nil || r.regexp.host == nil { return "", errors.New("mux: route doesn't have a host") } return r.regexp.host.template, nil } // prepareVars converts the route variable pairs into a map. If the route has a // BuildVarsFunc, it is invoked. func (r *Route) prepareVars(pairs ...string) (map[string]string, error) { m, err := mapFromPairsToString(pairs...) if err != nil { return nil, err } return r.buildVars(m), nil } func (r *Route) buildVars(m map[string]string) map[string]string { if r.parent != nil { m = r.parent.buildVars(m) } if r.buildVarsFunc != nil { m = r.buildVarsFunc(m) } return m } // ---------------------------------------------------------------------------- // parentRoute // ---------------------------------------------------------------------------- // parentRoute allows routes to know about parent host and path definitions. type parentRoute interface { getBuildScheme() string getNamedRoutes() map[string]*Route getRegexpGroup() *routeRegexpGroup buildVars(map[string]string) map[string]string } func (r *Route) getBuildScheme() string { if r.buildScheme != "" { return r.buildScheme } if r.parent != nil { return r.parent.getBuildScheme() } return "" } // getNamedRoutes returns the map where named routes are registered. func (r *Route) getNamedRoutes() map[string]*Route { if r.parent == nil { // During tests router is not always set. r.parent = NewRouter() } return r.parent.getNamedRoutes() } // getRegexpGroup returns regexp definitions from this route. func (r *Route) getRegexpGroup() *routeRegexpGroup { if r.regexp == nil { if r.parent == nil { // During tests router is not always set. r.parent = NewRouter() } regexp := r.parent.getRegexpGroup() if regexp == nil { r.regexp = new(routeRegexpGroup) } else { // Copy. r.regexp = &routeRegexpGroup{ host: regexp.host, path: regexp.path, queries: regexp.queries, } } } return r.regexp } �����������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/regexp.go������������������������������������������������0000644�0610621�0607500�00000021462�13172163423�023353� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mux import ( "bytes" "fmt" "net/http" "net/url" "regexp" "strconv" "strings" ) // newRouteRegexp parses a route template and returns a routeRegexp, // used to match a host, a path or a query string. // // It will extract named variables, assemble a regexp to be matched, create // a "reverse" template to build URLs and compile regexps to validate variable // values used in URL building. // // Previously we accepted only Python-like identifiers for variable // names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that // name and pattern can't be empty, and names can't contain a colon. func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash, useEncodedPath bool) (*routeRegexp, error) { // Check if it is well-formed. idxs, errBraces := braceIndices(tpl) if errBraces != nil { return nil, errBraces } // Backup the original. template := tpl // Now let's parse it. defaultPattern := "[^/]+" if matchQuery { defaultPattern = ".*" } else if matchHost { defaultPattern = "[^.]+" matchPrefix = false } // Only match strict slash if not matching if matchPrefix || matchHost || matchQuery { strictSlash = false } // Set a flag for strictSlash. endSlash := false if strictSlash && strings.HasSuffix(tpl, "/") { tpl = tpl[:len(tpl)-1] endSlash = true } varsN := make([]string, len(idxs)/2) varsR := make([]*regexp.Regexp, len(idxs)/2) pattern := bytes.NewBufferString("") pattern.WriteByte('^') reverse := bytes.NewBufferString("") var end int var err error for i := 0; i < len(idxs); i += 2 { // Set all values we are interested in. raw := tpl[end:idxs[i]] end = idxs[i+1] parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) name := parts[0] patt := defaultPattern if len(parts) == 2 { patt = parts[1] } // Name or pattern can't be empty. if name == "" || patt == "" { return nil, fmt.Errorf("mux: missing name or pattern in %q", tpl[idxs[i]:end]) } // Build the regexp pattern. fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt) // Build the reverse template. fmt.Fprintf(reverse, "%s%%s", raw) // Append variable name and compiled pattern. varsN[i/2] = name varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt)) if err != nil { return nil, err } } // Add the remaining. raw := tpl[end:] pattern.WriteString(regexp.QuoteMeta(raw)) if strictSlash { pattern.WriteString("[/]?") } if matchQuery { // Add the default pattern if the query value is empty if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { pattern.WriteString(defaultPattern) } } if !matchPrefix { pattern.WriteByte('$') } reverse.WriteString(raw) if endSlash { reverse.WriteByte('/') } // Compile full regexp. reg, errCompile := regexp.Compile(pattern.String()) if errCompile != nil { return nil, errCompile } // Check for capturing groups which used to work in older versions if reg.NumSubexp() != len(idxs)/2 { panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) + "Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)") } // Done! return &routeRegexp{ template: template, matchHost: matchHost, matchQuery: matchQuery, strictSlash: strictSlash, useEncodedPath: useEncodedPath, regexp: reg, reverse: reverse.String(), varsN: varsN, varsR: varsR, }, nil } // routeRegexp stores a regexp to match a host or path and information to // collect and validate route variables. type routeRegexp struct { // The unmodified template. template string // True for host match, false for path or query string match. matchHost bool // True for query string match, false for path and host match. matchQuery bool // The strictSlash value defined on the route, but disabled if PathPrefix was used. strictSlash bool // Determines whether to use encoded path from getPath function or unencoded // req.URL.Path for path matching useEncodedPath bool // Expanded regexp. regexp *regexp.Regexp // Reverse template. reverse string // Variable names. varsN []string // Variable regexps (validators). varsR []*regexp.Regexp } // Match matches the regexp against the URL host or path. func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { if !r.matchHost { if r.matchQuery { return r.matchQueryString(req) } path := req.URL.Path if r.useEncodedPath { path = getPath(req) } return r.regexp.MatchString(path) } return r.regexp.MatchString(getHost(req)) } // url builds a URL part using the given values. func (r *routeRegexp) url(values map[string]string) (string, error) { urlValues := make([]interface{}, len(r.varsN)) for k, v := range r.varsN { value, ok := values[v] if !ok { return "", fmt.Errorf("mux: missing route variable %q", v) } if r.matchQuery { value = url.QueryEscape(value) } urlValues[k] = value } rv := fmt.Sprintf(r.reverse, urlValues...) if !r.regexp.MatchString(rv) { // The URL is checked against the full regexp, instead of checking // individual variables. This is faster but to provide a good error // message, we check individual regexps if the URL doesn't match. for k, v := range r.varsN { if !r.varsR[k].MatchString(values[v]) { return "", fmt.Errorf( "mux: variable %q doesn't match, expected %q", values[v], r.varsR[k].String()) } } } return rv, nil } // getURLQuery returns a single query parameter from a request URL. // For a URL with foo=bar&baz=ding, we return only the relevant key // value pair for the routeRegexp. func (r *routeRegexp) getURLQuery(req *http.Request) string { if !r.matchQuery { return "" } templateKey := strings.SplitN(r.template, "=", 2)[0] for key, vals := range req.URL.Query() { if key == templateKey && len(vals) > 0 { return key + "=" + vals[0] } } return "" } func (r *routeRegexp) matchQueryString(req *http.Request) bool { return r.regexp.MatchString(r.getURLQuery(req)) } // braceIndices returns the first level curly brace indices from a string. // It returns an error in case of unbalanced braces. func braceIndices(s string) ([]int, error) { var level, idx int var idxs []int for i := 0; i < len(s); i++ { switch s[i] { case '{': if level++; level == 1 { idx = i } case '}': if level--; level == 0 { idxs = append(idxs, idx, i+1) } else if level < 0 { return nil, fmt.Errorf("mux: unbalanced braces in %q", s) } } } if level != 0 { return nil, fmt.Errorf("mux: unbalanced braces in %q", s) } return idxs, nil } // varGroupName builds a capturing group name for the indexed variable. func varGroupName(idx int) string { return "v" + strconv.Itoa(idx) } // ---------------------------------------------------------------------------- // routeRegexpGroup // ---------------------------------------------------------------------------- // routeRegexpGroup groups the route matchers that carry variables. type routeRegexpGroup struct { host *routeRegexp path *routeRegexp queries []*routeRegexp } // setMatch extracts the variables from the URL once a route matches. func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { // Store host variables. if v.host != nil { host := getHost(req) matches := v.host.regexp.FindStringSubmatchIndex(host) if len(matches) > 0 { extractVars(host, matches, v.host.varsN, m.Vars) } } path := req.URL.Path if r.useEncodedPath { path = getPath(req) } // Store path variables. if v.path != nil { matches := v.path.regexp.FindStringSubmatchIndex(path) if len(matches) > 0 { extractVars(path, matches, v.path.varsN, m.Vars) // Check if we should redirect. if v.path.strictSlash { p1 := strings.HasSuffix(path, "/") p2 := strings.HasSuffix(v.path.template, "/") if p1 != p2 { u, _ := url.Parse(req.URL.String()) if p1 { u.Path = u.Path[:len(u.Path)-1] } else { u.Path += "/" } m.Handler = http.RedirectHandler(u.String(), 301) } } } } // Store query string variables. for _, q := range v.queries { queryURL := q.getURLQuery(req) matches := q.regexp.FindStringSubmatchIndex(queryURL) if len(matches) > 0 { extractVars(queryURL, matches, q.varsN, m.Vars) } } } // getHost tries its best to return the request host. func getHost(r *http.Request) string { if r.URL.IsAbs() { return r.URL.Host } host := r.Host // Slice off any port information. if i := strings.Index(host, ":"); i != -1 { host = host[:i] } return host } func extractVars(input string, matches []int, names []string, output map[string]string) { for i, name := range names { output[name] = input[matches[2*i+2]:matches[2*i+3]] } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/old_test.go����������������������������������������������0000644�0610621�0607500�00000042113�13172163423�023672� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Old tests ported to Go1. This is a mess. Want to drop it one day. // Copyright 2011 Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mux import ( "bytes" "net/http" "testing" ) // ---------------------------------------------------------------------------- // ResponseRecorder // ---------------------------------------------------------------------------- // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // ResponseRecorder is an implementation of http.ResponseWriter that // records its mutations for later inspection in tests. type ResponseRecorder struct { Code int // the HTTP response code from WriteHeader HeaderMap http.Header // the HTTP response headers Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to Flushed bool } // NewRecorder returns an initialized ResponseRecorder. func NewRecorder() *ResponseRecorder { return &ResponseRecorder{ HeaderMap: make(http.Header), Body: new(bytes.Buffer), } } // Header returns the response headers. func (rw *ResponseRecorder) Header() http.Header { return rw.HeaderMap } // Write always succeeds and writes to rw.Body, if not nil. func (rw *ResponseRecorder) Write(buf []byte) (int, error) { if rw.Body != nil { rw.Body.Write(buf) } if rw.Code == 0 { rw.Code = http.StatusOK } return len(buf), nil } // WriteHeader sets rw.Code. func (rw *ResponseRecorder) WriteHeader(code int) { rw.Code = code } // Flush sets rw.Flushed to true. func (rw *ResponseRecorder) Flush() { rw.Flushed = true } // ---------------------------------------------------------------------------- func TestRouteMatchers(t *testing.T) { var scheme, host, path, query, method string var headers map[string]string var resultVars map[bool]map[string]string router := NewRouter() router.NewRoute().Host("{var1}.google.com"). Path("/{var2:[a-z]+}/{var3:[0-9]+}"). Queries("foo", "bar"). Methods("GET"). Schemes("https"). Headers("x-requested-with", "XMLHttpRequest") router.NewRoute().Host("www.{var4}.com"). PathPrefix("/foo/{var5:[a-z]+}/{var6:[0-9]+}"). Queries("baz", "ding"). Methods("POST"). Schemes("http"). Headers("Content-Type", "application/json") reset := func() { // Everything match. scheme = "https" host = "www.google.com" path = "/product/42" query = "?foo=bar" method = "GET" headers = map[string]string{"X-Requested-With": "XMLHttpRequest"} resultVars = map[bool]map[string]string{ true: {"var1": "www", "var2": "product", "var3": "42"}, false: {}, } } reset2 := func() { // Everything match. scheme = "http" host = "www.google.com" path = "/foo/product/42/path/that/is/ignored" query = "?baz=ding" method = "POST" headers = map[string]string{"Content-Type": "application/json"} resultVars = map[bool]map[string]string{ true: {"var4": "google", "var5": "product", "var6": "42"}, false: {}, } } match := func(shouldMatch bool) { url := scheme + "://" + host + path + query request, _ := http.NewRequest(method, url, nil) for key, value := range headers { request.Header.Add(key, value) } var routeMatch RouteMatch matched := router.Match(request, &routeMatch) if matched != shouldMatch { t.Errorf("Expected: %v\nGot: %v\nRequest: %v %v", shouldMatch, matched, request.Method, url) } if matched { currentRoute := routeMatch.Route if currentRoute == nil { t.Errorf("Expected a current route.") } vars := routeMatch.Vars expectedVars := resultVars[shouldMatch] if len(vars) != len(expectedVars) { t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) } for name, value := range vars { if expectedVars[name] != value { t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) } } } } // 1st route -------------------------------------------------------------- // Everything match. reset() match(true) // Scheme doesn't match. reset() scheme = "http" match(false) // Host doesn't match. reset() host = "www.mygoogle.com" match(false) // Path doesn't match. reset() path = "/product/notdigits" match(false) // Query doesn't match. reset() query = "?foo=baz" match(false) // Method doesn't match. reset() method = "POST" match(false) // Header doesn't match. reset() headers = map[string]string{} match(false) // Everything match, again. reset() match(true) // 2nd route -------------------------------------------------------------- // Everything match. reset2() match(true) // Scheme doesn't match. reset2() scheme = "https" match(false) // Host doesn't match. reset2() host = "sub.google.com" match(false) // Path doesn't match. reset2() path = "/bar/product/42" match(false) // Query doesn't match. reset2() query = "?foo=baz" match(false) // Method doesn't match. reset2() method = "GET" match(false) // Header doesn't match. reset2() headers = map[string]string{} match(false) // Everything match, again. reset2() match(true) } type headerMatcherTest struct { matcher headerMatcher headers map[string]string result bool } var headerMatcherTests = []headerMatcherTest{ { matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), headers: map[string]string{"X-Requested-With": "XMLHttpRequest"}, result: true, }, { matcher: headerMatcher(map[string]string{"x-requested-with": ""}), headers: map[string]string{"X-Requested-With": "anything"}, result: true, }, { matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), headers: map[string]string{}, result: false, }, } type hostMatcherTest struct { matcher *Route url string vars map[string]string result bool } var hostMatcherTests = []hostMatcherTest{ { matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), url: "http://abc.def.ghi/", vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, result: true, }, { matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), url: "http://a.b.c/", vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, result: false, }, } type methodMatcherTest struct { matcher methodMatcher method string result bool } var methodMatcherTests = []methodMatcherTest{ { matcher: methodMatcher([]string{"GET", "POST", "PUT"}), method: "GET", result: true, }, { matcher: methodMatcher([]string{"GET", "POST", "PUT"}), method: "POST", result: true, }, { matcher: methodMatcher([]string{"GET", "POST", "PUT"}), method: "PUT", result: true, }, { matcher: methodMatcher([]string{"GET", "POST", "PUT"}), method: "DELETE", result: false, }, } type pathMatcherTest struct { matcher *Route url string vars map[string]string result bool } var pathMatcherTests = []pathMatcherTest{ { matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), url: "http://localhost:8080/123/456/789", vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, result: true, }, { matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), url: "http://localhost:8080/1/2/3", vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, result: false, }, } type schemeMatcherTest struct { matcher schemeMatcher url string result bool } var schemeMatcherTests = []schemeMatcherTest{ { matcher: schemeMatcher([]string{"http", "https"}), url: "http://localhost:8080/", result: true, }, { matcher: schemeMatcher([]string{"http", "https"}), url: "https://localhost:8080/", result: true, }, { matcher: schemeMatcher([]string{"https"}), url: "http://localhost:8080/", result: false, }, { matcher: schemeMatcher([]string{"http"}), url: "https://localhost:8080/", result: false, }, } type urlBuildingTest struct { route *Route vars []string url string } var urlBuildingTests = []urlBuildingTest{ { route: new(Route).Host("foo.domain.com"), vars: []string{}, url: "http://foo.domain.com", }, { route: new(Route).Host("{subdomain}.domain.com"), vars: []string{"subdomain", "bar"}, url: "http://bar.domain.com", }, { route: new(Route).Host("foo.domain.com").Path("/articles"), vars: []string{}, url: "http://foo.domain.com/articles", }, { route: new(Route).Path("/articles"), vars: []string{}, url: "/articles", }, { route: new(Route).Path("/articles/{category}/{id:[0-9]+}"), vars: []string{"category", "technology", "id", "42"}, url: "/articles/technology/42", }, { route: new(Route).Host("{subdomain}.domain.com").Path("/articles/{category}/{id:[0-9]+}"), vars: []string{"subdomain", "foo", "category", "technology", "id", "42"}, url: "http://foo.domain.com/articles/technology/42", }, } func TestHeaderMatcher(t *testing.T) { for _, v := range headerMatcherTests { request, _ := http.NewRequest("GET", "http://localhost:8080/", nil) for key, value := range v.headers { request.Header.Add(key, value) } var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, request.Header) } else { t.Errorf("%#v: should not match %v.", v.matcher, request.Header) } } } } func TestHostMatcher(t *testing.T) { for _, v := range hostMatcherTests { request, _ := http.NewRequest("GET", v.url, nil) var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) vars := routeMatch.Vars if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, v.url) } else { t.Errorf("%#v: should not match %v.", v.matcher, v.url) } } if result { if len(vars) != len(v.vars) { t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) } for name, value := range vars { if v.vars[name] != value { t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) } } } else { if len(vars) != 0 { t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) } } } } func TestMethodMatcher(t *testing.T) { for _, v := range methodMatcherTests { request, _ := http.NewRequest(v.method, "http://localhost:8080/", nil) var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, v.method) } else { t.Errorf("%#v: should not match %v.", v.matcher, v.method) } } } } func TestPathMatcher(t *testing.T) { for _, v := range pathMatcherTests { request, _ := http.NewRequest("GET", v.url, nil) var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) vars := routeMatch.Vars if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, v.url) } else { t.Errorf("%#v: should not match %v.", v.matcher, v.url) } } if result { if len(vars) != len(v.vars) { t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) } for name, value := range vars { if v.vars[name] != value { t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) } } } else { if len(vars) != 0 { t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) } } } } func TestSchemeMatcher(t *testing.T) { for _, v := range schemeMatcherTests { request, _ := http.NewRequest("GET", v.url, nil) var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, v.url) } else { t.Errorf("%#v: should not match %v.", v.matcher, v.url) } } } } func TestUrlBuilding(t *testing.T) { for _, v := range urlBuildingTests { u, _ := v.route.URL(v.vars...) url := u.String() if url != v.url { t.Errorf("expected %v, got %v", v.url, url) /* reversePath := "" reverseHost := "" if v.route.pathTemplate != nil { reversePath = v.route.pathTemplate.Reverse } if v.route.hostTemplate != nil { reverseHost = v.route.hostTemplate.Reverse } t.Errorf("%#v:\nexpected: %q\ngot: %q\nreverse path: %q\nreverse host: %q", v.route, v.url, url, reversePath, reverseHost) */ } } ArticleHandler := func(w http.ResponseWriter, r *http.Request) { } router := NewRouter() router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Name("article") url, _ := router.Get("article").URL("category", "technology", "id", "42") expected := "/articles/technology/42" if url.String() != expected { t.Errorf("Expected %v, got %v", expected, url.String()) } } func TestMatchedRouteName(t *testing.T) { routeName := "stock" router := NewRouter() route := router.NewRoute().Path("/products/").Name(routeName) url := "http://www.example.com/products/" request, _ := http.NewRequest("GET", url, nil) var rv RouteMatch ok := router.Match(request, &rv) if !ok || rv.Route != route { t.Errorf("Expected same route, got %+v.", rv.Route) } retName := rv.Route.GetName() if retName != routeName { t.Errorf("Expected %q, got %q.", routeName, retName) } } func TestSubRouting(t *testing.T) { // Example from docs. router := NewRouter() subrouter := router.NewRoute().Host("www.example.com").Subrouter() route := subrouter.NewRoute().Path("/products/").Name("products") url := "http://www.example.com/products/" request, _ := http.NewRequest("GET", url, nil) var rv RouteMatch ok := router.Match(request, &rv) if !ok || rv.Route != route { t.Errorf("Expected same route, got %+v.", rv.Route) } u, _ := router.Get("products").URL() builtURL := u.String() // Yay, subroute aware of the domain when building! if builtURL != url { t.Errorf("Expected %q, got %q.", url, builtURL) } } func TestVariableNames(t *testing.T) { route := new(Route).Host("{arg1}.domain.com").Path("/{arg1}/{arg2:[0-9]+}") if route.err == nil { t.Errorf("Expected error for duplicated variable names") } } func TestRedirectSlash(t *testing.T) { var route *Route var routeMatch RouteMatch r := NewRouter() r.StrictSlash(false) route = r.NewRoute() if route.strictSlash != false { t.Errorf("Expected false redirectSlash.") } r.StrictSlash(true) route = r.NewRoute() if route.strictSlash != true { t.Errorf("Expected true redirectSlash.") } route = new(Route) route.strictSlash = true route.Path("/{arg1}/{arg2:[0-9]+}/") request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil) routeMatch = RouteMatch{} _ = route.Match(request, &routeMatch) vars := routeMatch.Vars if vars["arg1"] != "foo" { t.Errorf("Expected foo.") } if vars["arg2"] != "123" { t.Errorf("Expected 123.") } rsp := NewRecorder() routeMatch.Handler.ServeHTTP(rsp, request) if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" { t.Errorf("Expected redirect header.") } route = new(Route) route.strictSlash = true route.Path("/{arg1}/{arg2:[0-9]+}") request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil) routeMatch = RouteMatch{} _ = route.Match(request, &routeMatch) vars = routeMatch.Vars if vars["arg1"] != "foo" { t.Errorf("Expected foo.") } if vars["arg2"] != "123" { t.Errorf("Expected 123.") } rsp = NewRecorder() routeMatch.Handler.ServeHTTP(rsp, request) if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" { t.Errorf("Expected redirect header.") } } // Test for the new regexp library, still not available in stable Go. func TestNewRegexp(t *testing.T) { var p *routeRegexp var matches []string tests := map[string]map[string][]string{ "/{foo:a{2}}": { "/a": nil, "/aa": {"aa"}, "/aaa": nil, "/aaaa": nil, }, "/{foo:a{2,}}": { "/a": nil, "/aa": {"aa"}, "/aaa": {"aaa"}, "/aaaa": {"aaaa"}, }, "/{foo:a{2,3}}": { "/a": nil, "/aa": {"aa"}, "/aaa": {"aaa"}, "/aaaa": nil, }, "/{foo:[a-z]{3}}/{bar:[a-z]{2}}": { "/a": nil, "/ab": nil, "/abc": nil, "/abcd": nil, "/abc/ab": {"abc", "ab"}, "/abc/abc": nil, "/abcd/ab": nil, }, `/{foo:\w{3,}}/{bar:\d{2,}}`: { "/a": nil, "/ab": nil, "/abc": nil, "/abc/1": nil, "/abc/12": {"abc", "12"}, "/abcd/12": {"abcd", "12"}, "/abcd/123": {"abcd", "123"}, }, } for pattern, paths := range tests { p, _ = newRouteRegexp(pattern, false, false, false, false, false) for path, result := range paths { matches = p.regexp.FindStringSubmatch(path) if result == nil { if matches != nil { t.Errorf("%v should not match %v.", pattern, path) } } else { if len(matches) != len(result)+1 { t.Errorf("Expected %v matches, got %v.", len(result)+1, len(matches)) } else { for k, v := range result { if matches[k+1] != v { t.Errorf("Expected %v, got %v.", v, matches[k+1]) } } } } } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/mux_test.go����������������������������������������������0000644�0610621�0607500�00000167764�13172163423�023751� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mux import ( "bufio" "bytes" "errors" "fmt" "net/http" "net/url" "reflect" "strings" "testing" ) func (r *Route) GoString() string { matchers := make([]string, len(r.matchers)) for i, m := range r.matchers { matchers[i] = fmt.Sprintf("%#v", m) } return fmt.Sprintf("&Route{matchers:[]matcher{%s}}", strings.Join(matchers, ", ")) } func (r *routeRegexp) GoString() string { return fmt.Sprintf("&routeRegexp{template: %q, matchHost: %t, matchQuery: %t, strictSlash: %t, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.matchHost, r.matchQuery, r.strictSlash, r.regexp.String(), r.reverse, r.varsN, r.varsR) } type routeTest struct { title string // title of the test route *Route // the route being tested request *http.Request // a request to test the route vars map[string]string // the expected vars of the match scheme string // the expected scheme of the built URL host string // the expected host of the built URL path string // the expected path of the built URL query string // the expected query string of the built URL pathTemplate string // the expected path template of the route hostTemplate string // the expected host template of the route methods []string // the expected route methods pathRegexp string // the expected path regexp shouldMatch bool // whether the request is expected to match the route at all shouldRedirect bool // whether the request should result in a redirect } func TestHost(t *testing.T) { // newRequestHost a new request with a method, url, and host header newRequestHost := func(method, url, host string) *http.Request { req, err := http.NewRequest(method, url, nil) if err != nil { panic(err) } req.Host = host return req } tests := []routeTest{ { title: "Host route match", route: new(Route).Host("aaa.bbb.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route, wrong host in request URL", route: new(Route).Host("aaa.bbb.ccc"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{}, host: "aaa.bbb.ccc", path: "", shouldMatch: false, }, { title: "Host route with port, match", route: new(Route).Host("aaa.bbb.ccc:1234"), request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"), vars: map[string]string{}, host: "aaa.bbb.ccc:1234", path: "", shouldMatch: true, }, { title: "Host route with port, wrong port in request URL", route: new(Route).Host("aaa.bbb.ccc:1234"), request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"), vars: map[string]string{}, host: "aaa.bbb.ccc:1234", path: "", shouldMatch: false, }, { title: "Host route, match with host in request header", route: new(Route).Host("aaa.bbb.ccc"), request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"), vars: map[string]string{}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route, wrong host in request header", route: new(Route).Host("aaa.bbb.ccc"), request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"), vars: map[string]string{}, host: "aaa.bbb.ccc", path: "", shouldMatch: false, }, // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true}, { title: "Host route with port, wrong host in request header", route: new(Route).Host("aaa.bbb.ccc:1234"), request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"), vars: map[string]string{}, host: "aaa.bbb.ccc:1234", path: "", shouldMatch: false, }, { title: "Host route with pattern, match", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "bbb"}, host: "aaa.bbb.ccc", path: "", hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`, shouldMatch: true, }, { title: "Host route with pattern, additional capturing group, match", route: new(Route).Host("aaa.{v1:[a-z]{2}(?:b|c)}.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "bbb"}, host: "aaa.bbb.ccc", path: "", hostTemplate: `aaa.{v1:[a-z]{2}(?:b|c)}.ccc`, shouldMatch: true, }, { title: "Host route with pattern, wrong host in request URL", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{"v1": "bbb"}, host: "aaa.bbb.ccc", path: "", hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`, shouldMatch: false, }, { title: "Host route with multiple patterns, match", route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, host: "aaa.bbb.ccc", path: "", hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`, shouldMatch: true, }, { title: "Host route with multiple patterns, wrong host in request URL", route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, host: "aaa.bbb.ccc", path: "", hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`, shouldMatch: false, }, { title: "Host route with hyphenated name and pattern, match", route: new(Route).Host("aaa.{v-1:[a-z]{3}}.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v-1": "bbb"}, host: "aaa.bbb.ccc", path: "", hostTemplate: `aaa.{v-1:[a-z]{3}}.ccc`, shouldMatch: true, }, { title: "Host route with hyphenated name and pattern, additional capturing group, match", route: new(Route).Host("aaa.{v-1:[a-z]{2}(?:b|c)}.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v-1": "bbb"}, host: "aaa.bbb.ccc", path: "", hostTemplate: `aaa.{v-1:[a-z]{2}(?:b|c)}.ccc`, shouldMatch: true, }, { title: "Host route with multiple hyphenated names and patterns, match", route: new(Route).Host("{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v-1": "aaa", "v-2": "bbb", "v-3": "ccc"}, host: "aaa.bbb.ccc", path: "", hostTemplate: `{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}`, shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) } } func TestPath(t *testing.T) { tests := []routeTest{ { title: "Path route, match", route: new(Route).Path("/111/222/333"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{}, host: "", path: "/111/222/333", shouldMatch: true, }, { title: "Path route, match with trailing slash in request and path", route: new(Route).Path("/111/"), request: newRequest("GET", "http://localhost/111/"), vars: map[string]string{}, host: "", path: "/111/", shouldMatch: true, }, { title: "Path route, do not match with trailing slash in path", route: new(Route).Path("/111/"), request: newRequest("GET", "http://localhost/111"), vars: map[string]string{}, host: "", path: "/111", pathTemplate: `/111/`, pathRegexp: `^/111/$`, shouldMatch: false, }, { title: "Path route, do not match with trailing slash in request", route: new(Route).Path("/111"), request: newRequest("GET", "http://localhost/111/"), vars: map[string]string{}, host: "", path: "/111/", pathTemplate: `/111`, shouldMatch: false, }, { title: "Path route, match root with no host", route: new(Route).Path("/"), request: newRequest("GET", "/"), vars: map[string]string{}, host: "", path: "/", pathTemplate: `/`, pathRegexp: `^/$`, shouldMatch: true, }, { title: "Path route, match root with no host, App Engine format", route: new(Route).Path("/"), request: func() *http.Request { r := newRequest("GET", "http://localhost/") r.RequestURI = "/" return r }(), vars: map[string]string{}, host: "", path: "/", pathTemplate: `/`, shouldMatch: true, }, { title: "Path route, wrong path in request in request URL", route: new(Route).Path("/111/222/333"), request: newRequest("GET", "http://localhost/1/2/3"), vars: map[string]string{}, host: "", path: "/111/222/333", shouldMatch: false, }, { title: "Path route with pattern, match", route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v1": "222"}, host: "", path: "/111/222/333", pathTemplate: `/111/{v1:[0-9]{3}}/333`, shouldMatch: true, }, { title: "Path route with pattern, URL in request does not match", route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), request: newRequest("GET", "http://localhost/111/aaa/333"), vars: map[string]string{"v1": "222"}, host: "", path: "/111/222/333", pathTemplate: `/111/{v1:[0-9]{3}}/333`, pathRegexp: `^/111/(?P<v0>[0-9]{3})/333$`, shouldMatch: false, }, { title: "Path route with multiple patterns, match", route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, host: "", path: "/111/222/333", pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`, pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`, shouldMatch: true, }, { title: "Path route with multiple patterns, URL in request does not match", route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/aaa/333"), vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, host: "", path: "/111/222/333", pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`, pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`, shouldMatch: false, }, { title: "Path route with multiple patterns with pipe, match", route: new(Route).Path("/{category:a|(?:b/c)}/{product}/{id:[0-9]+}"), request: newRequest("GET", "http://localhost/a/product_name/1"), vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, host: "", path: "/a/product_name/1", pathTemplate: `/{category:a|(?:b/c)}/{product}/{id:[0-9]+}`, pathRegexp: `^/(?P<v0>a|(?:b/c))/(?P<v1>[^/]+)/(?P<v2>[0-9]+)$`, shouldMatch: true, }, { title: "Path route with hyphenated name and pattern, match", route: new(Route).Path("/111/{v-1:[0-9]{3}}/333"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v-1": "222"}, host: "", path: "/111/222/333", pathTemplate: `/111/{v-1:[0-9]{3}}/333`, pathRegexp: `^/111/(?P<v0>[0-9]{3})/333$`, shouldMatch: true, }, { title: "Path route with multiple hyphenated names and patterns, match", route: new(Route).Path("/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v-1": "111", "v-2": "222", "v-3": "333"}, host: "", path: "/111/222/333", pathTemplate: `/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}`, pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`, shouldMatch: true, }, { title: "Path route with multiple hyphenated names and patterns with pipe, match", route: new(Route).Path("/{product-category:a|(?:b/c)}/{product-name}/{product-id:[0-9]+}"), request: newRequest("GET", "http://localhost/a/product_name/1"), vars: map[string]string{"product-category": "a", "product-name": "product_name", "product-id": "1"}, host: "", path: "/a/product_name/1", pathTemplate: `/{product-category:a|(?:b/c)}/{product-name}/{product-id:[0-9]+}`, pathRegexp: `^/(?P<v0>a|(?:b/c))/(?P<v1>[^/]+)/(?P<v2>[0-9]+)$`, shouldMatch: true, }, { title: "Path route with multiple hyphenated names and patterns with pipe and case insensitive, match", route: new(Route).Path("/{type:(?i:daily|mini|variety)}-{date:\\d{4,4}-\\d{2,2}-\\d{2,2}}"), request: newRequest("GET", "http://localhost/daily-2016-01-01"), vars: map[string]string{"type": "daily", "date": "2016-01-01"}, host: "", path: "/daily-2016-01-01", pathTemplate: `/{type:(?i:daily|mini|variety)}-{date:\d{4,4}-\d{2,2}-\d{2,2}}`, pathRegexp: `^/(?P<v0>(?i:daily|mini|variety))-(?P<v1>\d{4,4}-\d{2,2}-\d{2,2})$`, shouldMatch: true, }, { title: "Path route with empty match right after other match", route: new(Route).Path(`/{v1:[0-9]*}{v2:[a-z]*}/{v3:[0-9]*}`), request: newRequest("GET", "http://localhost/111/222"), vars: map[string]string{"v1": "111", "v2": "", "v3": "222"}, host: "", path: "/111/222", pathTemplate: `/{v1:[0-9]*}{v2:[a-z]*}/{v3:[0-9]*}`, pathRegexp: `^/(?P<v0>[0-9]*)(?P<v1>[a-z]*)/(?P<v2>[0-9]*)$`, shouldMatch: true, }, { title: "Path route with single pattern with pipe, match", route: new(Route).Path("/{category:a|b/c}"), request: newRequest("GET", "http://localhost/a"), vars: map[string]string{"category": "a"}, host: "", path: "/a", pathTemplate: `/{category:a|b/c}`, shouldMatch: true, }, { title: "Path route with single pattern with pipe, match", route: new(Route).Path("/{category:a|b/c}"), request: newRequest("GET", "http://localhost/b/c"), vars: map[string]string{"category": "b/c"}, host: "", path: "/b/c", pathTemplate: `/{category:a|b/c}`, shouldMatch: true, }, { title: "Path route with multiple patterns with pipe, match", route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), request: newRequest("GET", "http://localhost/a/product_name/1"), vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, host: "", path: "/a/product_name/1", pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`, shouldMatch: true, }, { title: "Path route with multiple patterns with pipe, match", route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), request: newRequest("GET", "http://localhost/b/c/product_name/1"), vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"}, host: "", path: "/b/c/product_name/1", pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`, shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) testUseEscapedRoute(t, test) testRegexp(t, test) } } func TestPathPrefix(t *testing.T) { tests := []routeTest{ { title: "PathPrefix route, match", route: new(Route).PathPrefix("/111"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: true, }, { title: "PathPrefix route, match substring", route: new(Route).PathPrefix("/1"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{}, host: "", path: "/1", shouldMatch: true, }, { title: "PathPrefix route, URL prefix in request does not match", route: new(Route).PathPrefix("/111"), request: newRequest("GET", "http://localhost/1/2/3"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: false, }, { title: "PathPrefix route with pattern, match", route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v1": "222"}, host: "", path: "/111/222", pathTemplate: `/111/{v1:[0-9]{3}}`, shouldMatch: true, }, { title: "PathPrefix route with pattern, URL prefix in request does not match", route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/aaa/333"), vars: map[string]string{"v1": "222"}, host: "", path: "/111/222", pathTemplate: `/111/{v1:[0-9]{3}}`, shouldMatch: false, }, { title: "PathPrefix route with multiple patterns, match", route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v1": "111", "v2": "222"}, host: "", path: "/111/222", pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}`, shouldMatch: true, }, { title: "PathPrefix route with multiple patterns, URL prefix in request does not match", route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/aaa/333"), vars: map[string]string{"v1": "111", "v2": "222"}, host: "", path: "/111/222", pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}`, shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) testUseEscapedRoute(t, test) } } func TestSchemeHostPath(t *testing.T) { tests := []routeTest{ { title: "Host and Path route, match", route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{}, scheme: "http", host: "aaa.bbb.ccc", path: "/111/222/333", pathTemplate: `/111/222/333`, hostTemplate: `aaa.bbb.ccc`, shouldMatch: true, }, { title: "Scheme, Host, and Path route, match", route: new(Route).Schemes("https").Host("aaa.bbb.ccc").Path("/111/222/333"), request: newRequest("GET", "https://aaa.bbb.ccc/111/222/333"), vars: map[string]string{}, scheme: "https", host: "aaa.bbb.ccc", path: "/111/222/333", pathTemplate: `/111/222/333`, hostTemplate: `aaa.bbb.ccc`, shouldMatch: true, }, { title: "Host and Path route, wrong host in request URL", route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{}, scheme: "http", host: "aaa.bbb.ccc", path: "/111/222/333", pathTemplate: `/111/222/333`, hostTemplate: `aaa.bbb.ccc`, shouldMatch: false, }, { title: "Host and Path route with pattern, match", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "bbb", "v2": "222"}, scheme: "http", host: "aaa.bbb.ccc", path: "/111/222/333", pathTemplate: `/111/{v2:[0-9]{3}}/333`, hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`, shouldMatch: true, }, { title: "Scheme, Host, and Path route with host and path patterns, match", route: new(Route).Schemes("ftp", "ssss").Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), request: newRequest("GET", "ssss://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "bbb", "v2": "222"}, scheme: "ftp", host: "aaa.bbb.ccc", path: "/111/222/333", pathTemplate: `/111/{v2:[0-9]{3}}/333`, hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`, shouldMatch: true, }, { title: "Host and Path route with pattern, URL in request does not match", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{"v1": "bbb", "v2": "222"}, scheme: "http", host: "aaa.bbb.ccc", path: "/111/222/333", pathTemplate: `/111/{v2:[0-9]{3}}/333`, hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`, shouldMatch: false, }, { title: "Host and Path route with multiple patterns, match", route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, scheme: "http", host: "aaa.bbb.ccc", path: "/111/222/333", pathTemplate: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`, hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`, shouldMatch: true, }, { title: "Host and Path route with multiple patterns, URL in request does not match", route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, scheme: "http", host: "aaa.bbb.ccc", path: "/111/222/333", pathTemplate: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`, hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`, shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) testUseEscapedRoute(t, test) } } func TestHeaders(t *testing.T) { // newRequestHeaders creates a new request with a method, url, and headers newRequestHeaders := func(method, url string, headers map[string]string) *http.Request { req, err := http.NewRequest(method, url, nil) if err != nil { panic(err) } for k, v := range headers { req.Header.Add(k, v) } return req } tests := []routeTest{ { title: "Headers route, match", route: new(Route).Headers("foo", "bar", "baz", "ding"), request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Headers route, bad header values", route: new(Route).Headers("foo", "bar", "baz", "ding"), request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Headers route, regex header values to match", route: new(Route).Headers("foo", "ba[zr]"), request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar"}), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Headers route, regex header values to match", route: new(Route).HeadersRegexp("foo", "ba[zr]"), request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "baz"}), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) } } func TestMethods(t *testing.T) { tests := []routeTest{ { title: "Methods route, match GET", route: new(Route).Methods("GET", "POST"), request: newRequest("GET", "http://localhost"), vars: map[string]string{}, host: "", path: "", methods: []string{"GET", "POST"}, shouldMatch: true, }, { title: "Methods route, match POST", route: new(Route).Methods("GET", "POST"), request: newRequest("POST", "http://localhost"), vars: map[string]string{}, host: "", path: "", methods: []string{"GET", "POST"}, shouldMatch: true, }, { title: "Methods route, bad method", route: new(Route).Methods("GET", "POST"), request: newRequest("PUT", "http://localhost"), vars: map[string]string{}, host: "", path: "", methods: []string{"GET", "POST"}, shouldMatch: false, }, { title: "Route without methods", route: new(Route), request: newRequest("PUT", "http://localhost"), vars: map[string]string{}, host: "", path: "", methods: []string{}, shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) testMethods(t, test) } } func TestQueries(t *testing.T) { tests := []routeTest{ { title: "Queries route, match", route: new(Route).Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), vars: map[string]string{}, host: "", path: "", query: "foo=bar&baz=ding", shouldMatch: true, }, { title: "Queries route, match with a query string", route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"), vars: map[string]string{}, host: "", path: "", query: "foo=bar&baz=ding", pathTemplate: `/api`, hostTemplate: `www.example.com`, shouldMatch: true, }, { title: "Queries route, match with a query string out of order", route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"), vars: map[string]string{}, host: "", path: "", query: "foo=bar&baz=ding", pathTemplate: `/api`, hostTemplate: `www.example.com`, shouldMatch: true, }, { title: "Queries route, bad query", route: new(Route).Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://localhost?foo=bar&baz=dong"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with pattern, match", route: new(Route).Queries("foo", "{v1}"), request: newRequest("GET", "http://localhost?foo=bar"), vars: map[string]string{"v1": "bar"}, host: "", path: "", query: "foo=bar", shouldMatch: true, }, { title: "Queries route with multiple patterns, match", route: new(Route).Queries("foo", "{v1}", "baz", "{v2}"), request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), vars: map[string]string{"v1": "bar", "v2": "ding"}, host: "", path: "", query: "foo=bar&baz=ding", shouldMatch: true, }, { title: "Queries route with regexp pattern, match", route: new(Route).Queries("foo", "{v1:[0-9]+}"), request: newRequest("GET", "http://localhost?foo=10"), vars: map[string]string{"v1": "10"}, host: "", path: "", query: "foo=10", shouldMatch: true, }, { title: "Queries route with regexp pattern, regexp does not match", route: new(Route).Queries("foo", "{v1:[0-9]+}"), request: newRequest("GET", "http://localhost?foo=a"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with regexp pattern with quantifier, match", route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), request: newRequest("GET", "http://localhost?foo=1"), vars: map[string]string{"v1": "1"}, host: "", path: "", query: "foo=1", shouldMatch: true, }, { title: "Queries route with regexp pattern with quantifier, additional variable in query string, match", route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), request: newRequest("GET", "http://localhost?bar=2&foo=1"), vars: map[string]string{"v1": "1"}, host: "", path: "", query: "foo=1", shouldMatch: true, }, { title: "Queries route with regexp pattern with quantifier, regexp does not match", route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), request: newRequest("GET", "http://localhost?foo=12"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with regexp pattern with quantifier, additional capturing group", route: new(Route).Queries("foo", "{v1:[0-9]{1}(?:a|b)}"), request: newRequest("GET", "http://localhost?foo=1a"), vars: map[string]string{"v1": "1a"}, host: "", path: "", query: "foo=1a", shouldMatch: true, }, { title: "Queries route with regexp pattern with quantifier, additional variable in query string, regexp does not match", route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), request: newRequest("GET", "http://localhost?foo=12"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with hyphenated name, match", route: new(Route).Queries("foo", "{v-1}"), request: newRequest("GET", "http://localhost?foo=bar"), vars: map[string]string{"v-1": "bar"}, host: "", path: "", query: "foo=bar", shouldMatch: true, }, { title: "Queries route with multiple hyphenated names, match", route: new(Route).Queries("foo", "{v-1}", "baz", "{v-2}"), request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), vars: map[string]string{"v-1": "bar", "v-2": "ding"}, host: "", path: "", query: "foo=bar&baz=ding", shouldMatch: true, }, { title: "Queries route with hyphenate name and pattern, match", route: new(Route).Queries("foo", "{v-1:[0-9]+}"), request: newRequest("GET", "http://localhost?foo=10"), vars: map[string]string{"v-1": "10"}, host: "", path: "", query: "foo=10", shouldMatch: true, }, { title: "Queries route with hyphenated name and pattern with quantifier, additional capturing group", route: new(Route).Queries("foo", "{v-1:[0-9]{1}(?:a|b)}"), request: newRequest("GET", "http://localhost?foo=1a"), vars: map[string]string{"v-1": "1a"}, host: "", path: "", query: "foo=1a", shouldMatch: true, }, { title: "Queries route with empty value, should match", route: new(Route).Queries("foo", ""), request: newRequest("GET", "http://localhost?foo=bar"), vars: map[string]string{}, host: "", path: "", query: "foo=", shouldMatch: true, }, { title: "Queries route with empty value and no parameter in request, should not match", route: new(Route).Queries("foo", ""), request: newRequest("GET", "http://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with empty value and empty parameter in request, should match", route: new(Route).Queries("foo", ""), request: newRequest("GET", "http://localhost?foo="), vars: map[string]string{}, host: "", path: "", query: "foo=", shouldMatch: true, }, { title: "Queries route with overlapping value, should not match", route: new(Route).Queries("foo", "bar"), request: newRequest("GET", "http://localhost?foo=barfoo"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with no parameter in request, should not match", route: new(Route).Queries("foo", "{bar}"), request: newRequest("GET", "http://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with empty parameter in request, should match", route: new(Route).Queries("foo", "{bar}"), request: newRequest("GET", "http://localhost?foo="), vars: map[string]string{"foo": ""}, host: "", path: "", query: "foo=", shouldMatch: true, }, { title: "Queries route, bad submatch", route: new(Route).Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://localhost?fffoo=bar&baz=dingggg"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with pattern, match, escaped value", route: new(Route).Queries("foo", "{v1}"), request: newRequest("GET", "http://localhost?foo=%25bar%26%20%2F%3D%3F"), vars: map[string]string{"v1": "%bar& /=?"}, host: "", path: "", query: "foo=%25bar%26+%2F%3D%3F", shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) testUseEscapedRoute(t, test) } } func TestSchemes(t *testing.T) { tests := []routeTest{ // Schemes { title: "Schemes route, default scheme, match http, build http", route: new(Route).Host("localhost"), request: newRequest("GET", "http://localhost"), scheme: "http", host: "localhost", shouldMatch: true, }, { title: "Schemes route, match https, build https", route: new(Route).Schemes("https", "ftp").Host("localhost"), request: newRequest("GET", "https://localhost"), scheme: "https", host: "localhost", shouldMatch: true, }, { title: "Schemes route, match ftp, build https", route: new(Route).Schemes("https", "ftp").Host("localhost"), request: newRequest("GET", "ftp://localhost"), scheme: "https", host: "localhost", shouldMatch: true, }, { title: "Schemes route, match ftp, build ftp", route: new(Route).Schemes("ftp", "https").Host("localhost"), request: newRequest("GET", "ftp://localhost"), scheme: "ftp", host: "localhost", shouldMatch: true, }, { title: "Schemes route, bad scheme", route: new(Route).Schemes("https", "ftp").Host("localhost"), request: newRequest("GET", "http://localhost"), scheme: "https", host: "localhost", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) } } func TestMatcherFunc(t *testing.T) { m := func(r *http.Request, m *RouteMatch) bool { if r.URL.Host == "aaa.bbb.ccc" { return true } return false } tests := []routeTest{ { title: "MatchFunc route, match", route: new(Route).MatcherFunc(m), request: newRequest("GET", "http://aaa.bbb.ccc"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "MatchFunc route, non-match", route: new(Route).MatcherFunc(m), request: newRequest("GET", "http://aaa.222.ccc"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) } } func TestBuildVarsFunc(t *testing.T) { tests := []routeTest{ { title: "BuildVarsFunc set on route", route: new(Route).Path(`/111/{v1:\d}{v2:.*}`).BuildVarsFunc(func(vars map[string]string) map[string]string { vars["v1"] = "3" vars["v2"] = "a" return vars }), request: newRequest("GET", "http://localhost/111/2"), path: "/111/3a", pathTemplate: `/111/{v1:\d}{v2:.*}`, shouldMatch: true, }, { title: "BuildVarsFunc set on route and parent route", route: new(Route).PathPrefix(`/{v1:\d}`).BuildVarsFunc(func(vars map[string]string) map[string]string { vars["v1"] = "2" return vars }).Subrouter().Path(`/{v2:\w}`).BuildVarsFunc(func(vars map[string]string) map[string]string { vars["v2"] = "b" return vars }), request: newRequest("GET", "http://localhost/1/a"), path: "/2/b", pathTemplate: `/{v1:\d}/{v2:\w}`, shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) } } func TestSubRouter(t *testing.T) { subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter() subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter() subrouter3 := new(Route).PathPrefix("/foo").Subrouter() subrouter4 := new(Route).PathPrefix("/foo/bar").Subrouter() subrouter5 := new(Route).PathPrefix("/{category}").Subrouter() tests := []routeTest{ { route: subrouter1.Path("/{v2:[a-z]+}"), request: newRequest("GET", "http://aaa.google.com/bbb"), vars: map[string]string{"v1": "aaa", "v2": "bbb"}, host: "aaa.google.com", path: "/bbb", pathTemplate: `/{v2:[a-z]+}`, hostTemplate: `{v1:[a-z]+}.google.com`, shouldMatch: true, }, { route: subrouter1.Path("/{v2:[a-z]+}"), request: newRequest("GET", "http://111.google.com/111"), vars: map[string]string{"v1": "aaa", "v2": "bbb"}, host: "aaa.google.com", path: "/bbb", pathTemplate: `/{v2:[a-z]+}`, hostTemplate: `{v1:[a-z]+}.google.com`, shouldMatch: false, }, { route: subrouter2.Path("/baz/{v2}"), request: newRequest("GET", "http://localhost/foo/bar/baz/ding"), vars: map[string]string{"v1": "bar", "v2": "ding"}, host: "", path: "/foo/bar/baz/ding", pathTemplate: `/foo/{v1}/baz/{v2}`, shouldMatch: true, }, { route: subrouter2.Path("/baz/{v2}"), request: newRequest("GET", "http://localhost/foo/bar"), vars: map[string]string{"v1": "bar", "v2": "ding"}, host: "", path: "/foo/bar/baz/ding", pathTemplate: `/foo/{v1}/baz/{v2}`, shouldMatch: false, }, { route: subrouter3.Path("/"), request: newRequest("GET", "http://localhost/foo/"), vars: map[string]string{}, host: "", path: "/foo/", pathTemplate: `/foo/`, shouldMatch: true, }, { route: subrouter3.Path(""), request: newRequest("GET", "http://localhost/foo"), vars: map[string]string{}, host: "", path: "/foo", pathTemplate: `/foo`, shouldMatch: true, }, { route: subrouter4.Path("/"), request: newRequest("GET", "http://localhost/foo/bar/"), vars: map[string]string{}, host: "", path: "/foo/bar/", pathTemplate: `/foo/bar/`, shouldMatch: true, }, { route: subrouter4.Path(""), request: newRequest("GET", "http://localhost/foo/bar"), vars: map[string]string{}, host: "", path: "/foo/bar", pathTemplate: `/foo/bar`, shouldMatch: true, }, { route: subrouter5.Path("/"), request: newRequest("GET", "http://localhost/baz/"), vars: map[string]string{"category": "baz"}, host: "", path: "/baz/", pathTemplate: `/{category}/`, shouldMatch: true, }, { route: subrouter5.Path(""), request: newRequest("GET", "http://localhost/baz"), vars: map[string]string{"category": "baz"}, host: "", path: "/baz", pathTemplate: `/{category}`, shouldMatch: true, }, { title: "Build with scheme on parent router", route: new(Route).Schemes("ftp").Host("google.com").Subrouter().Path("/"), request: newRequest("GET", "ftp://google.com/"), scheme: "ftp", host: "google.com", path: "/", pathTemplate: `/`, hostTemplate: `google.com`, shouldMatch: true, }, { title: "Prefer scheme on child route when building URLs", route: new(Route).Schemes("https", "ftp").Host("google.com").Subrouter().Schemes("ftp").Path("/"), request: newRequest("GET", "ftp://google.com/"), scheme: "ftp", host: "google.com", path: "/", pathTemplate: `/`, hostTemplate: `google.com`, shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) testUseEscapedRoute(t, test) } } func TestNamedRoutes(t *testing.T) { r1 := NewRouter() r1.NewRoute().Name("a") r1.NewRoute().Name("b") r1.NewRoute().Name("c") r2 := r1.NewRoute().Subrouter() r2.NewRoute().Name("d") r2.NewRoute().Name("e") r2.NewRoute().Name("f") r3 := r2.NewRoute().Subrouter() r3.NewRoute().Name("g") r3.NewRoute().Name("h") r3.NewRoute().Name("i") if r1.namedRoutes == nil || len(r1.namedRoutes) != 9 { t.Errorf("Expected 9 named routes, got %v", r1.namedRoutes) } else if r1.Get("i") == nil { t.Errorf("Subroute name not registered") } } func TestStrictSlash(t *testing.T) { r := NewRouter() r.StrictSlash(true) tests := []routeTest{ { title: "Redirect path without slash", route: r.NewRoute().Path("/111/"), request: newRequest("GET", "http://localhost/111"), vars: map[string]string{}, host: "", path: "/111/", shouldMatch: true, shouldRedirect: true, }, { title: "Do not redirect path with slash", route: r.NewRoute().Path("/111/"), request: newRequest("GET", "http://localhost/111/"), vars: map[string]string{}, host: "", path: "/111/", shouldMatch: true, shouldRedirect: false, }, { title: "Redirect path with slash", route: r.NewRoute().Path("/111"), request: newRequest("GET", "http://localhost/111/"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: true, shouldRedirect: true, }, { title: "Do not redirect path without slash", route: r.NewRoute().Path("/111"), request: newRequest("GET", "http://localhost/111"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: true, shouldRedirect: false, }, { title: "Propagate StrictSlash to subrouters", route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"), request: newRequest("GET", "http://localhost/static/images"), vars: map[string]string{}, host: "", path: "/static/images/", shouldMatch: true, shouldRedirect: true, }, { title: "Ignore StrictSlash for path prefix", route: r.NewRoute().PathPrefix("/static/"), request: newRequest("GET", "http://localhost/static/logo.png"), vars: map[string]string{}, host: "", path: "/static/", shouldMatch: true, shouldRedirect: false, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) testUseEscapedRoute(t, test) } } func TestUseEncodedPath(t *testing.T) { r := NewRouter() r.UseEncodedPath() tests := []routeTest{ { title: "Router with useEncodedPath, URL with encoded slash does match", route: r.NewRoute().Path("/v1/{v1}/v2"), request: newRequest("GET", "http://localhost/v1/1%2F2/v2"), vars: map[string]string{"v1": "1%2F2"}, host: "", path: "/v1/1%2F2/v2", pathTemplate: `/v1/{v1}/v2`, shouldMatch: true, }, { title: "Router with useEncodedPath, URL with encoded slash doesn't match", route: r.NewRoute().Path("/v1/1/2/v2"), request: newRequest("GET", "http://localhost/v1/1%2F2/v2"), vars: map[string]string{"v1": "1%2F2"}, host: "", path: "/v1/1%2F2/v2", pathTemplate: `/v1/1/2/v2`, shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) } } func TestWalkSingleDepth(t *testing.T) { r0 := NewRouter() r1 := NewRouter() r2 := NewRouter() r0.Path("/g") r0.Path("/o") r0.Path("/d").Handler(r1) r0.Path("/r").Handler(r2) r0.Path("/a") r1.Path("/z") r1.Path("/i") r1.Path("/l") r1.Path("/l") r2.Path("/i") r2.Path("/l") r2.Path("/l") paths := []string{"g", "o", "r", "i", "l", "l", "a"} depths := []int{0, 0, 0, 1, 1, 1, 0} i := 0 err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error { matcher := route.matchers[0].(*routeRegexp) if matcher.template == "/d" { return SkipRouter } if len(ancestors) != depths[i] { t.Errorf(`Expected depth of %d at i = %d; got "%d"`, depths[i], i, len(ancestors)) } if matcher.template != "/"+paths[i] { t.Errorf(`Expected "/%s" at i = %d; got "%s"`, paths[i], i, matcher.template) } i++ return nil }) if err != nil { panic(err) } if i != len(paths) { t.Errorf("Expected %d routes, found %d", len(paths), i) } } func TestWalkNested(t *testing.T) { router := NewRouter() g := router.Path("/g").Subrouter() o := g.PathPrefix("/o").Subrouter() r := o.PathPrefix("/r").Subrouter() i := r.PathPrefix("/i").Subrouter() l1 := i.PathPrefix("/l").Subrouter() l2 := l1.PathPrefix("/l").Subrouter() l2.Path("/a") testCases := []struct { path string ancestors []*Route }{ {"/g", []*Route{}}, {"/g/o", []*Route{g.parent.(*Route)}}, {"/g/o/r", []*Route{g.parent.(*Route), o.parent.(*Route)}}, {"/g/o/r/i", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route)}}, {"/g/o/r/i/l", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route)}}, {"/g/o/r/i/l/l", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route), l1.parent.(*Route)}}, {"/g/o/r/i/l/l/a", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route), l1.parent.(*Route), l2.parent.(*Route)}}, } idx := 0 err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { path := testCases[idx].path tpl := route.regexp.path.template if tpl != path { t.Errorf(`Expected %s got %s`, path, tpl) } currWantAncestors := testCases[idx].ancestors if !reflect.DeepEqual(currWantAncestors, ancestors) { t.Errorf(`Expected %+v got %+v`, currWantAncestors, ancestors) } idx++ return nil }) if err != nil { panic(err) } if idx != len(testCases) { t.Errorf("Expected %d routes, found %d", len(testCases), idx) } } func TestWalkSubrouters(t *testing.T) { router := NewRouter() g := router.Path("/g").Subrouter() o := g.PathPrefix("/o").Subrouter() o.Methods("GET") o.Methods("PUT") // all 4 routes should be matched, but final 2 routes do not have path templates paths := []string{"/g", "/g/o", "", ""} idx := 0 err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { path := paths[idx] tpl, _ := route.GetPathTemplate() if tpl != path { t.Errorf(`Expected %s got %s`, path, tpl) } idx++ return nil }) if err != nil { panic(err) } if idx != len(paths) { t.Errorf("Expected %d routes, found %d", len(paths), idx) } } func TestWalkErrorRoute(t *testing.T) { router := NewRouter() router.Path("/g") expectedError := errors.New("error") err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { return expectedError }) if err != expectedError { t.Errorf("Expected %v routes, found %v", expectedError, err) } } func TestWalkErrorMatcher(t *testing.T) { router := NewRouter() expectedError := router.Path("/g").Subrouter().Path("").GetError() err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { return route.GetError() }) if err != expectedError { t.Errorf("Expected %v routes, found %v", expectedError, err) } } func TestWalkErrorHandler(t *testing.T) { handler := NewRouter() expectedError := handler.Path("/path").Subrouter().Path("").GetError() router := NewRouter() router.Path("/g").Handler(handler) err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { return route.GetError() }) if err != expectedError { t.Errorf("Expected %v routes, found %v", expectedError, err) } } func TestSubrouterErrorHandling(t *testing.T) { superRouterCalled := false subRouterCalled := false router := NewRouter() router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { superRouterCalled = true }) subRouter := router.PathPrefix("/bign8").Subrouter() subRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { subRouterCalled = true }) req, _ := http.NewRequest("GET", "http://localhost/bign8/was/here", nil) router.ServeHTTP(NewRecorder(), req) if superRouterCalled { t.Error("Super router 404 handler called when sub-router 404 handler is available.") } if !subRouterCalled { t.Error("Sub-router 404 handler was not called.") } } // See: https://github.com/gorilla/mux/issues/200 func TestPanicOnCapturingGroups(t *testing.T) { defer func() { if recover() == nil { t.Errorf("(Test that capturing groups now fail fast) Expected panic, however test completed successfully.\n") } }() NewRouter().NewRoute().Path("/{type:(promo|special)}/{promoId}.json") } // ---------------------------------------------------------------------------- // Helpers // ---------------------------------------------------------------------------- func getRouteTemplate(route *Route) string { host, err := route.GetHostTemplate() if err != nil { host = "none" } path, err := route.GetPathTemplate() if err != nil { path = "none" } return fmt.Sprintf("Host: %v, Path: %v", host, path) } func testRoute(t *testing.T, test routeTest) { request := test.request route := test.route vars := test.vars shouldMatch := test.shouldMatch query := test.query shouldRedirect := test.shouldRedirect uri := url.URL{ Scheme: test.scheme, Host: test.host, Path: test.path, } if uri.Scheme == "" { uri.Scheme = "http" } var match RouteMatch ok := route.Match(request, &match) if ok != shouldMatch { msg := "Should match" if !shouldMatch { msg = "Should not match" } t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars) return } if shouldMatch { if vars != nil && !stringMapEqual(vars, match.Vars) { t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars) return } if test.scheme != "" { u, err := route.URL(mapToPairs(match.Vars)...) if err != nil { t.Fatalf("(%v) URL error: %v -- %v", test.title, err, getRouteTemplate(route)) } if uri.Scheme != u.Scheme { t.Errorf("(%v) URLScheme not equal: expected %v, got %v", test.title, uri.Scheme, u.Scheme) return } } if test.host != "" { u, err := test.route.URLHost(mapToPairs(match.Vars)...) if err != nil { t.Fatalf("(%v) URLHost error: %v -- %v", test.title, err, getRouteTemplate(route)) } if uri.Scheme != u.Scheme { t.Errorf("(%v) URLHost scheme not equal: expected %v, got %v -- %v", test.title, uri.Scheme, u.Scheme, getRouteTemplate(route)) return } if uri.Host != u.Host { t.Errorf("(%v) URLHost host not equal: expected %v, got %v -- %v", test.title, uri.Host, u.Host, getRouteTemplate(route)) return } } if test.path != "" { u, err := route.URLPath(mapToPairs(match.Vars)...) if err != nil { t.Fatalf("(%v) URLPath error: %v -- %v", test.title, err, getRouteTemplate(route)) } if uri.Path != u.Path { t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, uri.Path, u.Path, getRouteTemplate(route)) return } } if test.host != "" && test.path != "" { u, err := route.URL(mapToPairs(match.Vars)...) if err != nil { t.Fatalf("(%v) URL error: %v -- %v", test.title, err, getRouteTemplate(route)) } if expected, got := uri.String(), u.String(); expected != got { t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, expected, got, getRouteTemplate(route)) return } } if query != "" { u, _ := route.URL(mapToPairs(match.Vars)...) if query != u.RawQuery { t.Errorf("(%v) URL query not equal: expected %v, got %v", test.title, query, u.RawQuery) return } } if shouldRedirect && match.Handler == nil { t.Errorf("(%v) Did not redirect", test.title) return } if !shouldRedirect && match.Handler != nil { t.Errorf("(%v) Unexpected redirect", test.title) return } } } func testUseEscapedRoute(t *testing.T, test routeTest) { test.route.useEncodedPath = true testRoute(t, test) } func testTemplate(t *testing.T, test routeTest) { route := test.route pathTemplate := test.pathTemplate if len(pathTemplate) == 0 { pathTemplate = test.path } hostTemplate := test.hostTemplate if len(hostTemplate) == 0 { hostTemplate = test.host } routePathTemplate, pathErr := route.GetPathTemplate() if pathErr == nil && routePathTemplate != pathTemplate { t.Errorf("(%v) GetPathTemplate not equal: expected %v, got %v", test.title, pathTemplate, routePathTemplate) } routeHostTemplate, hostErr := route.GetHostTemplate() if hostErr == nil && routeHostTemplate != hostTemplate { t.Errorf("(%v) GetHostTemplate not equal: expected %v, got %v", test.title, hostTemplate, routeHostTemplate) } } func testMethods(t *testing.T, test routeTest) { route := test.route methods, _ := route.GetMethods() if strings.Join(methods, ",") != strings.Join(test.methods, ",") { t.Errorf("(%v) GetMethods not equal: expected %v, got %v", test.title, test.methods, methods) } } func testRegexp(t *testing.T, test routeTest) { route := test.route routePathRegexp, regexpErr := route.GetPathRegexp() if test.pathRegexp != "" && regexpErr == nil && routePathRegexp != test.pathRegexp { t.Errorf("(%v) GetPathRegexp not equal: expected %v, got %v", test.title, test.pathRegexp, routePathRegexp) } } type TestA301ResponseWriter struct { hh http.Header status int } func (ho *TestA301ResponseWriter) Header() http.Header { return http.Header(ho.hh) } func (ho *TestA301ResponseWriter) Write(b []byte) (int, error) { return 0, nil } func (ho *TestA301ResponseWriter) WriteHeader(code int) { ho.status = code } func Test301Redirect(t *testing.T) { m := make(http.Header) func1 := func(w http.ResponseWriter, r *http.Request) {} func2 := func(w http.ResponseWriter, r *http.Request) {} r := NewRouter() r.HandleFunc("/api/", func2).Name("func2") r.HandleFunc("/", func1).Name("func1") req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil) res := TestA301ResponseWriter{ hh: m, status: 0, } r.ServeHTTP(&res, req) if "http://localhost/api/?abc=def" != res.hh["Location"][0] { t.Errorf("Should have complete URL with query string") } } func TestSkipClean(t *testing.T) { func1 := func(w http.ResponseWriter, r *http.Request) {} func2 := func(w http.ResponseWriter, r *http.Request) {} r := NewRouter() r.SkipClean(true) r.HandleFunc("/api/", func2).Name("func2") r.HandleFunc("/", func1).Name("func1") req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil) res := NewRecorder() r.ServeHTTP(res, req) if len(res.HeaderMap["Location"]) != 0 { t.Errorf("Shouldn't redirect since skip clean is disabled") } } // https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW func TestSubrouterHeader(t *testing.T) { expected := "func1 response" func1 := func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, expected) } func2 := func(http.ResponseWriter, *http.Request) {} r := NewRouter() s := r.Headers("SomeSpecialHeader", "").Subrouter() s.HandleFunc("/", func1).Name("func1") r.HandleFunc("/", func2).Name("func2") req, _ := http.NewRequest("GET", "http://localhost/", nil) req.Header.Add("SomeSpecialHeader", "foo") match := new(RouteMatch) matched := r.Match(req, match) if !matched { t.Errorf("Should match request") } if match.Route.GetName() != "func1" { t.Errorf("Expecting func1 handler, got %s", match.Route.GetName()) } resp := NewRecorder() match.Handler.ServeHTTP(resp, req) if resp.Body.String() != expected { t.Errorf("Expecting %q", expected) } } // mapToPairs converts a string map to a slice of string pairs func mapToPairs(m map[string]string) []string { var i int p := make([]string, len(m)*2) for k, v := range m { p[i] = k p[i+1] = v i += 2 } return p } // stringMapEqual checks the equality of two string maps func stringMapEqual(m1, m2 map[string]string) bool { nil1 := m1 == nil nil2 := m2 == nil if nil1 != nil2 || len(m1) != len(m2) { return false } for k, v := range m1 { if v != m2[k] { return false } } return true } // newRequest is a helper function to create a new request with a method and url. // The request returned is a 'server' request as opposed to a 'client' one through // simulated write onto the wire and read off of the wire. // The differences between requests are detailed in the net/http package. func newRequest(method, url string) *http.Request { req, err := http.NewRequest(method, url, nil) if err != nil { panic(err) } // extract the escaped original host+path from url // http://localhost/path/here?v=1#frag -> //localhost/path/here opaque := "" if i := len(req.URL.Scheme); i > 0 { opaque = url[i+1:] } if i := strings.LastIndex(opaque, "?"); i > -1 { opaque = opaque[:i] } if i := strings.LastIndex(opaque, "#"); i > -1 { opaque = opaque[:i] } // Escaped host+path workaround as detailed in https://golang.org/pkg/net/url/#URL // for < 1.5 client side workaround req.URL.Opaque = opaque // Simulate writing to wire var buff bytes.Buffer req.Write(&buff) ioreader := bufio.NewReader(&buff) // Parse request off of 'wire' req, err = http.ReadRequest(ioreader) if err != nil { panic(err) } return req } func TestNoMatchMethodErrorHandler(t *testing.T) { func1 := func(w http.ResponseWriter, r *http.Request) {} r := NewRouter() r.HandleFunc("/", func1).Methods("GET", "POST") req, _ := http.NewRequest("PUT", "http://localhost/", nil) match := new(RouteMatch) matched := r.Match(req, match) if matched { t.Error("Should not have matched route for methods") } if match.MatchErr != ErrMethodMismatch { t.Error("Should get ErrMethodMismatch error") } resp := NewRecorder() r.ServeHTTP(resp, req) if resp.Code != 405 { t.Errorf("Expecting code %v", 405) } // Add matching route r.HandleFunc("/", func1).Methods("PUT") match = new(RouteMatch) matched = r.Match(req, match) if !matched { t.Error("Should have matched route for methods") } if match.MatchErr != nil { t.Error("Should not have any matching error. Found:", match.MatchErr) } } ������������lxd-2.0.11/dist/src/github.com/gorilla/mux/mux.go���������������������������������������������������0000644�0610621�0607500�00000041074�13172163423�022673� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mux import ( "errors" "fmt" "net/http" "path" "regexp" "strings" ) var ( ErrMethodMismatch = errors.New("method is not allowed") ) // NewRouter returns a new router instance. func NewRouter() *Router { return &Router{namedRoutes: make(map[string]*Route), KeepContext: false} } // Router registers routes to be matched and dispatches a handler. // // It implements the http.Handler interface, so it can be registered to serve // requests: // // var router = mux.NewRouter() // // func main() { // http.Handle("/", router) // } // // Or, for Google App Engine, register it in a init() function: // // func init() { // http.Handle("/", router) // } // // This will send all incoming requests to the router. type Router struct { // Configurable Handler to be used when no route matches. NotFoundHandler http.Handler // Configurable Handler to be used when the request method does not match the route. MethodNotAllowedHandler http.Handler // Parent route, if this is a subrouter. parent parentRoute // Routes to be matched, in order. routes []*Route // Routes by name for URL building. namedRoutes map[string]*Route // See Router.StrictSlash(). This defines the flag for new routes. strictSlash bool // See Router.SkipClean(). This defines the flag for new routes. skipClean bool // If true, do not clear the request context after handling the request. // This has no effect when go1.7+ is used, since the context is stored // on the request itself. KeepContext bool // see Router.UseEncodedPath(). This defines a flag for all routes. useEncodedPath bool } // Match matches registered routes against the request. func (r *Router) Match(req *http.Request, match *RouteMatch) bool { for _, route := range r.routes { if route.Match(req, match) { return true } } if match.MatchErr == ErrMethodMismatch && r.MethodNotAllowedHandler != nil { match.Handler = r.MethodNotAllowedHandler return true } // Closest match for a router (includes sub-routers) if r.NotFoundHandler != nil { match.Handler = r.NotFoundHandler return true } return false } // ServeHTTP dispatches the handler registered in the matched route. // // When there is a match, the route variables can be retrieved calling // mux.Vars(request). func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { if !r.skipClean { path := req.URL.Path if r.useEncodedPath { path = getPath(req) } // Clean path to canonical form and redirect. if p := cleanPath(path); p != path { // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: // http://code.google.com/p/go/issues/detail?id=5252 url := *req.URL url.Path = p p = url.String() w.Header().Set("Location", p) w.WriteHeader(http.StatusMovedPermanently) return } } var match RouteMatch var handler http.Handler if r.Match(req, &match) { handler = match.Handler req = setVars(req, match.Vars) req = setCurrentRoute(req, match.Route) } if handler == nil && match.MatchErr == ErrMethodMismatch { handler = methodNotAllowedHandler() } if handler == nil { handler = http.NotFoundHandler() } if !r.KeepContext { defer contextClear(req) } handler.ServeHTTP(w, req) } // Get returns a route registered with the given name. func (r *Router) Get(name string) *Route { return r.getNamedRoutes()[name] } // GetRoute returns a route registered with the given name. This method // was renamed to Get() and remains here for backwards compatibility. func (r *Router) GetRoute(name string) *Route { return r.getNamedRoutes()[name] } // StrictSlash defines the trailing slash behavior for new routes. The initial // value is false. // // When true, if the route path is "/path/", accessing "/path" will redirect // to the former and vice versa. In other words, your application will always // see the path as specified in the route. // // When false, if the route path is "/path", accessing "/path/" will not match // this route and vice versa. // // Special case: when a route sets a path prefix using the PathPrefix() method, // strict slash is ignored for that route because the redirect behavior can't // be determined from a prefix alone. However, any subrouters created from that // route inherit the original StrictSlash setting. func (r *Router) StrictSlash(value bool) *Router { r.strictSlash = value return r } // SkipClean defines the path cleaning behaviour for new routes. The initial // value is false. Users should be careful about which routes are not cleaned // // When true, if the route path is "/path//to", it will remain with the double // slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/ // // When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will // become /fetch/http/xkcd.com/534 func (r *Router) SkipClean(value bool) *Router { r.skipClean = value return r } // UseEncodedPath tells the router to match the encoded original path // to the routes. // For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to". // This behavior has the drawback of needing to match routes against // r.RequestURI instead of r.URL.Path. Any modifications (such as http.StripPrefix) // to r.URL.Path will not affect routing when this flag is on and thus may // induce unintended behavior. // // If not called, the router will match the unencoded path to the routes. // For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to" func (r *Router) UseEncodedPath() *Router { r.useEncodedPath = true return r } // ---------------------------------------------------------------------------- // parentRoute // ---------------------------------------------------------------------------- func (r *Router) getBuildScheme() string { if r.parent != nil { return r.parent.getBuildScheme() } return "" } // getNamedRoutes returns the map where named routes are registered. func (r *Router) getNamedRoutes() map[string]*Route { if r.namedRoutes == nil { if r.parent != nil { r.namedRoutes = r.parent.getNamedRoutes() } else { r.namedRoutes = make(map[string]*Route) } } return r.namedRoutes } // getRegexpGroup returns regexp definitions from the parent route, if any. func (r *Router) getRegexpGroup() *routeRegexpGroup { if r.parent != nil { return r.parent.getRegexpGroup() } return nil } func (r *Router) buildVars(m map[string]string) map[string]string { if r.parent != nil { m = r.parent.buildVars(m) } return m } // ---------------------------------------------------------------------------- // Route factories // ---------------------------------------------------------------------------- // NewRoute registers an empty route. func (r *Router) NewRoute() *Route { route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean, useEncodedPath: r.useEncodedPath} r.routes = append(r.routes, route) return route } // Handle registers a new route with a matcher for the URL path. // See Route.Path() and Route.Handler(). func (r *Router) Handle(path string, handler http.Handler) *Route { return r.NewRoute().Path(path).Handler(handler) } // HandleFunc registers a new route with a matcher for the URL path. // See Route.Path() and Route.HandlerFunc(). func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) *Route { return r.NewRoute().Path(path).HandlerFunc(f) } // Headers registers a new route with a matcher for request header values. // See Route.Headers(). func (r *Router) Headers(pairs ...string) *Route { return r.NewRoute().Headers(pairs...) } // Host registers a new route with a matcher for the URL host. // See Route.Host(). func (r *Router) Host(tpl string) *Route { return r.NewRoute().Host(tpl) } // MatcherFunc registers a new route with a custom matcher function. // See Route.MatcherFunc(). func (r *Router) MatcherFunc(f MatcherFunc) *Route { return r.NewRoute().MatcherFunc(f) } // Methods registers a new route with a matcher for HTTP methods. // See Route.Methods(). func (r *Router) Methods(methods ...string) *Route { return r.NewRoute().Methods(methods...) } // Path registers a new route with a matcher for the URL path. // See Route.Path(). func (r *Router) Path(tpl string) *Route { return r.NewRoute().Path(tpl) } // PathPrefix registers a new route with a matcher for the URL path prefix. // See Route.PathPrefix(). func (r *Router) PathPrefix(tpl string) *Route { return r.NewRoute().PathPrefix(tpl) } // Queries registers a new route with a matcher for URL query values. // See Route.Queries(). func (r *Router) Queries(pairs ...string) *Route { return r.NewRoute().Queries(pairs...) } // Schemes registers a new route with a matcher for URL schemes. // See Route.Schemes(). func (r *Router) Schemes(schemes ...string) *Route { return r.NewRoute().Schemes(schemes...) } // BuildVarsFunc registers a new route with a custom function for modifying // route variables before building a URL. func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route { return r.NewRoute().BuildVarsFunc(f) } // Walk walks the router and all its sub-routers, calling walkFn for each route // in the tree. The routes are walked in the order they were added. Sub-routers // are explored depth-first. func (r *Router) Walk(walkFn WalkFunc) error { return r.walk(walkFn, []*Route{}) } // SkipRouter is used as a return value from WalkFuncs to indicate that the // router that walk is about to descend down to should be skipped. var SkipRouter = errors.New("skip this router") // WalkFunc is the type of the function called for each route visited by Walk. // At every invocation, it is given the current route, and the current router, // and a list of ancestor routes that lead to the current route. type WalkFunc func(route *Route, router *Router, ancestors []*Route) error func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { for _, t := range r.routes { err := walkFn(t, r, ancestors) if err == SkipRouter { continue } if err != nil { return err } for _, sr := range t.matchers { if h, ok := sr.(*Router); ok { ancestors = append(ancestors, t) err := h.walk(walkFn, ancestors) if err != nil { return err } ancestors = ancestors[:len(ancestors)-1] } } if h, ok := t.handler.(*Router); ok { ancestors = append(ancestors, t) err := h.walk(walkFn, ancestors) if err != nil { return err } ancestors = ancestors[:len(ancestors)-1] } } return nil } // ---------------------------------------------------------------------------- // Context // ---------------------------------------------------------------------------- // RouteMatch stores information about a matched route. type RouteMatch struct { Route *Route Handler http.Handler Vars map[string]string // MatchErr is set to appropriate matching error // It is set to ErrMethodMismatch if there is a mismatch in // the request method and route method MatchErr error } type contextKey int const ( varsKey contextKey = iota routeKey ) // Vars returns the route variables for the current request, if any. func Vars(r *http.Request) map[string]string { if rv := contextGet(r, varsKey); rv != nil { return rv.(map[string]string) } return nil } // CurrentRoute returns the matched route for the current request, if any. // This only works when called inside the handler of the matched route // because the matched route is stored in the request context which is cleared // after the handler returns, unless the KeepContext option is set on the // Router. func CurrentRoute(r *http.Request) *Route { if rv := contextGet(r, routeKey); rv != nil { return rv.(*Route) } return nil } func setVars(r *http.Request, val interface{}) *http.Request { return contextSet(r, varsKey, val) } func setCurrentRoute(r *http.Request, val interface{}) *http.Request { return contextSet(r, routeKey, val) } // ---------------------------------------------------------------------------- // Helpers // ---------------------------------------------------------------------------- // getPath returns the escaped path if possible; doing what URL.EscapedPath() // which was added in go1.5 does func getPath(req *http.Request) string { if req.RequestURI != "" { // Extract the path from RequestURI (which is escaped unlike URL.Path) // as detailed here as detailed in https://golang.org/pkg/net/url/#URL // for < 1.5 server side workaround // http://localhost/path/here?v=1 -> /path/here path := req.RequestURI path = strings.TrimPrefix(path, req.URL.Scheme+`://`) path = strings.TrimPrefix(path, req.URL.Host) if i := strings.LastIndex(path, "?"); i > -1 { path = path[:i] } if i := strings.LastIndex(path, "#"); i > -1 { path = path[:i] } return path } return req.URL.Path } // cleanPath returns the canonical path for p, eliminating . and .. elements. // Borrowed from the net/http package. func cleanPath(p string) string { if p == "" { return "/" } if p[0] != '/' { p = "/" + p } np := path.Clean(p) // path.Clean removes trailing slash except for root; // put the trailing slash back if necessary. if p[len(p)-1] == '/' && np != "/" { np += "/" } return np } // uniqueVars returns an error if two slices contain duplicated strings. func uniqueVars(s1, s2 []string) error { for _, v1 := range s1 { for _, v2 := range s2 { if v1 == v2 { return fmt.Errorf("mux: duplicated route variable %q", v2) } } } return nil } // checkPairs returns the count of strings passed in, and an error if // the count is not an even number. func checkPairs(pairs ...string) (int, error) { length := len(pairs) if length%2 != 0 { return length, fmt.Errorf( "mux: number of parameters must be multiple of 2, got %v", pairs) } return length, nil } // mapFromPairsToString converts variadic string parameters to a // string to string map. func mapFromPairsToString(pairs ...string) (map[string]string, error) { length, err := checkPairs(pairs...) if err != nil { return nil, err } m := make(map[string]string, length/2) for i := 0; i < length; i += 2 { m[pairs[i]] = pairs[i+1] } return m, nil } // mapFromPairsToRegex converts variadic string parameters to a // string to regex map. func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { length, err := checkPairs(pairs...) if err != nil { return nil, err } m := make(map[string]*regexp.Regexp, length/2) for i := 0; i < length; i += 2 { regex, err := regexp.Compile(pairs[i+1]) if err != nil { return nil, err } m[pairs[i]] = regex } return m, nil } // matchInArray returns true if the given string value is in the array. func matchInArray(arr []string, value string) bool { for _, v := range arr { if v == value { return true } } return false } // matchMapWithString returns true if the given key/value pairs exist in a given map. func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool { for k, v := range toCheck { // Check if key exists. if canonicalKey { k = http.CanonicalHeaderKey(k) } if values := toMatch[k]; values == nil { return false } else if v != "" { // If value was defined as an empty string we only check that the // key exists. Otherwise we also check for equality. valueExists := false for _, value := range values { if v == value { valueExists = true break } } if !valueExists { return false } } } return true } // matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against // the given regex func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool { for k, v := range toCheck { // Check if key exists. if canonicalKey { k = http.CanonicalHeaderKey(k) } if values := toMatch[k]; values == nil { return false } else if v != nil { // If value was defined as an empty string we only check that the // key exists. Otherwise we also check for equality. valueExists := false for _, value := range values { if v.MatchString(value) { valueExists = true break } } if !valueExists { return false } } } return true } // methodNotAllowed replies to the request with an HTTP status code 405. func methodNotAllowed(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusMethodNotAllowed) } // methodNotAllowedHandler returns a simple request handler // that replies to each request with a status code 405. func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/doc.go���������������������������������������������������0000644�0610621�0607500�00000020726�13172163423�022630� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package mux implements a request router and dispatcher. The name mux stands for "HTTP request multiplexer". Like the standard http.ServeMux, mux.Router matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: * Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. * URL hosts, paths and query values can have variables with an optional regular expression. * Registered URLs can be built, or "reversed", which helps maintaining references to resources. * Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. * It implements the http.Handler interface so it is compatible with the standard http.ServeMux. Let's start registering a couple of URL paths and handlers: func main() { r := mux.NewRouter() r.HandleFunc("/", HomeHandler) r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/articles", ArticlesHandler) http.Handle("/", r) } Here we register three routes mapping URL paths to handlers. This is equivalent to how http.HandleFunc() works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (http.ResponseWriter, *http.Request) as parameters. Paths can have variables. They are defined using the format {name} or {name:pattern}. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example: r := mux.NewRouter() r.HandleFunc("/products/{key}", ProductHandler) r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) Groups can be used inside patterns, as long as they are non-capturing (?:re). For example: r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler) The names are used to create a map of route variables which can be retrieved calling mux.Vars(): vars := mux.Vars(request) category := vars["category"] Note that if any capturing groups are present, mux will panic() during parsing. To prevent this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to "/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably when capturing groups were present. And this is all you need to know about the basic usage. More advanced options are explained below. Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables: r := mux.NewRouter() // Only matches if domain is "www.example.com". r.Host("www.example.com") // Matches a dynamic subdomain. r.Host("{subdomain:[a-z]+}.domain.com") There are several other matchers that can be added. To match path prefixes: r.PathPrefix("/products/") ...or HTTP methods: r.Methods("GET", "POST") ...or URL schemes: r.Schemes("https") ...or header values: r.Headers("X-Requested-With", "XMLHttpRequest") ...or query values: r.Queries("key", "value") ...or to use a custom matcher function: r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { return r.ProtoMajor == 0 }) ...and finally, it is possible to combine several matchers in a single route: r.HandleFunc("/products", ProductsHandler). Host("www.example.com"). Methods("GET"). Schemes("http") Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". For example, let's say we have several URLs that should only match when the host is "www.example.com". Create a route for that host and get a "subrouter" from it: r := mux.NewRouter() s := r.Host("www.example.com").Subrouter() Then register routes in the subrouter: s.HandleFunc("/products/", ProductsHandler) s.HandleFunc("/products/{key}", ProductHandler) s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) The three URL paths we registered above will only be tested if the domain is "www.example.com", because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route. Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter. There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths: r := mux.NewRouter() s := r.PathPrefix("/products").Subrouter() // "/products/" s.HandleFunc("/", ProductsHandler) // "/products/{key}/" s.HandleFunc("/{key}/", ProductHandler) // "/products/{key}/details" s.HandleFunc("/{key}/details", ProductDetailsHandler) Note that the path provided to PathPrefix() represents a "wildcard": calling PathPrefix("/static/").Handler(...) means that the handler will be passed any request that matches "/static/*". This makes it easy to serve static files with mux: func main() { var dir string flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/<filename> r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) srv := &http.Server{ Handler: r, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } Now let's see how to build registered URLs. Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling Name() on a route. For example: r := mux.NewRouter() r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). Name("article") To build a URL, get the route and call the URL() method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do: url, err := r.Get("article").URL("category", "technology", "id", "42") ...and the result will be a url.URL with the following path: "/articles/technology/42" This also works for host and query value variables: r := mux.NewRouter() r.Host("{subdomain}.domain.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") // url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42", "filter", "gorilla") All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match. Regex support also exists for matching Headers within a route. For example, we could do: r.HeadersRegexp("Content-Type", "application/(text|json)") ...and the route will match both requests with a Content-Type of `application/json` as well as `application/text` There's also a way to build only the URL host or path for a route: use the methods URLHost() or URLPath() instead. For the previous route, we would do: // "http://news.domain.com/" host, err := r.Get("article").URLHost("subdomain", "news") // "/articles/technology/42" path, err := r.Get("article").URLPath("category", "technology", "id", "42") And if you use subrouters, host and path defined separately can be built as well: r := mux.NewRouter() s := r.Host("{subdomain}.domain.com").Subrouter() s.Path("/articles/{category}/{id:[0-9]+}"). HandlerFunc(ArticleHandler). Name("article") // "http://news.domain.com/articles/technology/42" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42") */ package mux ������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/context_native_test.go�����������������������������������0000644�0610621�0607500�00000001262�13172163423�026146� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.7 package mux import ( "context" "net/http" "testing" "time" ) func TestNativeContextMiddleware(t *testing.T) { withTimeout := func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), time.Minute) defer cancel() h.ServeHTTP(w, r.WithContext(ctx)) }) } r := NewRouter() r.Handle("/path/{foo}", withTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { vars := Vars(r) if vars["foo"] != "bar" { t.Fatal("Expected foo var to be set") } }))) rec := NewRecorder() req := newRequest("GET", "/path/bar") r.ServeHTTP(rec, req) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/context_native.go����������������������������������������0000644�0610621�0607500�00000000574�13172163423�025114� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.7 package mux import ( "context" "net/http" ) func contextGet(r *http.Request, key interface{}) interface{} { return r.Context().Value(key) } func contextSet(r *http.Request, key, val interface{}) *http.Request { if val == nil { return r } return r.WithContext(context.WithValue(r.Context(), key, val)) } func contextClear(r *http.Request) { return } ������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/context_gorilla_test.go����������������������������������0000644�0610621�0607500�00000001544�13172163423�026314� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.7 package mux import ( "net/http" "testing" "github.com/gorilla/context" ) // Tests that the context is cleared or not cleared properly depending on // the configuration of the router func TestKeepContext(t *testing.T) { func1 := func(w http.ResponseWriter, r *http.Request) {} r := NewRouter() r.HandleFunc("/", func1).Name("func1") req, _ := http.NewRequest("GET", "http://localhost/", nil) context.Set(req, "t", 1) res := new(http.ResponseWriter) r.ServeHTTP(*res, req) if _, ok := context.GetOk(req, "t"); ok { t.Error("Context should have been cleared at end of request") } r.KeepContext = true req, _ = http.NewRequest("GET", "http://localhost/", nil) context.Set(req, "t", 1) r.ServeHTTP(*res, req) if _, ok := context.GetOk(req, "t"); !ok { t.Error("Context should NOT have been cleared at end of request") } } ������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/context_gorilla.go���������������������������������������0000644�0610621�0607500�00000000574�13172163423�025257� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.7 package mux import ( "net/http" "github.com/gorilla/context" ) func contextGet(r *http.Request, key interface{}) interface{} { return context.Get(r, key) } func contextSet(r *http.Request, key, val interface{}) *http.Request { if val == nil { return r } context.Set(r, key, val) return r } func contextClear(r *http.Request) { context.Clear(r) } ������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/bench_test.go��������������������������������������������0000644�0610621�0607500�00000002567�13172163423�024204� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mux import ( "net/http" "net/http/httptest" "testing" ) func BenchmarkMux(b *testing.B) { router := new(Router) handler := func(w http.ResponseWriter, r *http.Request) {} router.HandleFunc("/v1/{v1}", handler) request, _ := http.NewRequest("GET", "/v1/anything", nil) for i := 0; i < b.N; i++ { router.ServeHTTP(nil, request) } } func BenchmarkMuxAlternativeInRegexp(b *testing.B) { router := new(Router) handler := func(w http.ResponseWriter, r *http.Request) {} router.HandleFunc("/v1/{v1:(?:a|b)}", handler) requestA, _ := http.NewRequest("GET", "/v1/a", nil) requestB, _ := http.NewRequest("GET", "/v1/b", nil) for i := 0; i < b.N; i++ { router.ServeHTTP(nil, requestA) router.ServeHTTP(nil, requestB) } } func BenchmarkManyPathVariables(b *testing.B) { router := new(Router) handler := func(w http.ResponseWriter, r *http.Request) {} router.HandleFunc("/v1/{v1}/{v2}/{v3}/{v4}/{v5}", handler) matchingRequest, _ := http.NewRequest("GET", "/v1/1/2/3/4/5", nil) notMatchingRequest, _ := http.NewRequest("GET", "/v1/1/2/3/4", nil) recorder := httptest.NewRecorder() for i := 0; i < b.N; i++ { router.ServeHTTP(nil, matchingRequest) router.ServeHTTP(recorder, notMatchingRequest) } } �����������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/README.md������������������������������������������������0000644�0610621�0607500�00000027764�13172163423�023024� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������gorilla/mux === [![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux) [![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux) [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge) ![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png) http://www.gorillatoolkit.org/pkg/mux Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to their respective handler. The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: * It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`. * Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. * URL hosts, paths and query values can have variables with an optional regular expression. * Registered URLs can be built, or "reversed", which helps maintaining references to resources. * Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. --- * [Install](#install) * [Examples](#examples) * [Matching Routes](#matching-routes) * [Static Files](#static-files) * [Registered URLs](#registered-urls) * [Walking Routes](#walking-routes) * [Full Example](#full-example) --- ## Install With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain: ```sh go get -u github.com/gorilla/mux ``` ## Examples Let's start registering a couple of URL paths and handlers: ```go func main() { r := mux.NewRouter() r.HandleFunc("/", HomeHandler) r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/articles", ArticlesHandler) http.Handle("/", r) } ``` Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters. Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example: ```go r := mux.NewRouter() r.HandleFunc("/products/{key}", ProductHandler) r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) ``` The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`: ```go func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "Category: %v\n", vars["category"]) } ``` And this is all you need to know about the basic usage. More advanced options are explained below. ### Matching Routes Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables: ```go r := mux.NewRouter() // Only matches if domain is "www.example.com". r.Host("www.example.com") // Matches a dynamic subdomain. r.Host("{subdomain:[a-z]+}.domain.com") ``` There are several other matchers that can be added. To match path prefixes: ```go r.PathPrefix("/products/") ``` ...or HTTP methods: ```go r.Methods("GET", "POST") ``` ...or URL schemes: ```go r.Schemes("https") ``` ...or header values: ```go r.Headers("X-Requested-With", "XMLHttpRequest") ``` ...or query values: ```go r.Queries("key", "value") ``` ...or to use a custom matcher function: ```go r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { return r.ProtoMajor == 0 }) ``` ...and finally, it is possible to combine several matchers in a single route: ```go r.HandleFunc("/products", ProductsHandler). Host("www.example.com"). Methods("GET"). Schemes("http") ``` Routes are tested in the order they were added to the router. If two routes match, the first one wins: ```go r := mux.NewRouter() r.HandleFunc("/specific", specificHandler) r.PathPrefix("/").Handler(catchAllHandler) ``` Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it: ```go r := mux.NewRouter() s := r.Host("www.example.com").Subrouter() ``` Then register routes in the subrouter: ```go s.HandleFunc("/products/", ProductsHandler) s.HandleFunc("/products/{key}", ProductHandler) s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) ``` The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route. Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter. There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths: ```go r := mux.NewRouter() s := r.PathPrefix("/products").Subrouter() // "/products/" s.HandleFunc("/", ProductsHandler) // "/products/{key}/" s.HandleFunc("/{key}/", ProductHandler) // "/products/{key}/details" s.HandleFunc("/{key}/details", ProductDetailsHandler) ``` ### Listing Routes Routes on a mux can be listed using the Router.Walk method—useful for generating documentation: ```go package main import ( "fmt" "net/http" "strings" "github.com/gorilla/mux" ) func handler(w http.ResponseWriter, r *http.Request) { return } func main() { r := mux.NewRouter() r.HandleFunc("/", handler) r.HandleFunc("/products", handler).Methods("POST") r.HandleFunc("/articles", handler).Methods("GET") r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { t, err := route.GetPathTemplate() if err != nil { return err } // p will contain regular expression is compatible with regular expression in Perl, Python, and other languages. // for instance the regular expression for path '/articles/{id}' will be '^/articles/(?P<v0>[^/]+)$' p, err := route.GetPathRegexp() if err != nil { return err } m, err := route.GetMethods() if err != nil { return err } fmt.Println(strings.Join(m, ","), t, p) return nil }) http.Handle("/", r) } ``` ### Static Files Note that the path provided to `PathPrefix()` represents a "wildcard": calling `PathPrefix("/static/").Handler(...)` means that the handler will be passed any request that matches "/static/*". This makes it easy to serve static files with mux: ```go func main() { var dir string flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/<filename> r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) srv := &http.Server{ Handler: r, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } ``` ### Registered URLs Now let's see how to build registered URLs. Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example: ```go r := mux.NewRouter() r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). Name("article") ``` To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do: ```go url, err := r.Get("article").URL("category", "technology", "id", "42") ``` ...and the result will be a `url.URL` with the following path: ``` "/articles/technology/42" ``` This also works for host and query value variables: ```go r := mux.NewRouter() r.Host("{subdomain}.domain.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") // url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42", "filter", "gorilla") ``` All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match. Regex support also exists for matching Headers within a route. For example, we could do: ```go r.HeadersRegexp("Content-Type", "application/(text|json)") ``` ...and the route will match both requests with a Content-Type of `application/json` as well as `application/text` There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do: ```go // "http://news.domain.com/" host, err := r.Get("article").URLHost("subdomain", "news") // "/articles/technology/42" path, err := r.Get("article").URLPath("category", "technology", "id", "42") ``` And if you use subrouters, host and path defined separately can be built as well: ```go r := mux.NewRouter() s := r.Host("{subdomain}.domain.com").Subrouter() s.Path("/articles/{category}/{id:[0-9]+}"). HandlerFunc(ArticleHandler). Name("article") // "http://news.domain.com/articles/technology/42" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42") ``` ### Walking Routes The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example, the following prints all of the registered routes: ```go r := mux.NewRouter() r.HandleFunc("/", handler) r.HandleFunc("/products", handler).Methods("POST") r.HandleFunc("/articles", handler).Methods("GET") r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { t, err := route.GetPathTemplate() if err != nil { return err } // p will contain a regular expression that is compatible with regular expressions in Perl, Python, and other languages. // For example, the regular expression for path '/articles/{id}' will be '^/articles/(?P<v0>[^/]+)$'. p, err := route.GetPathRegexp() if err != nil { return err } m, err := route.GetMethods() if err != nil { return err } fmt.Println(strings.Join(m, ","), t, p) return nil }) ``` ## Full Example Here's a complete, runnable example of a small `mux` based server: ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` ## License BSD licensed. See the LICENSE file for details. ������������lxd-2.0.11/dist/src/github.com/gorilla/mux/LICENSE��������������������������������������������������0000644�0610621�0607500�00000002704�13172163423�022535� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2012 Rodrigo Moraes. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/mux/.travis.yml����������������������������������������������0000644�0610621�0607500�00000000462�13172163423�023640� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go sudo: false matrix: include: - go: 1.2 - go: 1.3 - go: 1.4 - go: 1.5 - go: 1.6 - go: 1.7 - go: 1.8 - go: 1.9 - go: tip install: - # Skip script: - go get -t -v ./... - diff -u <(echo -n) <(gofmt -d .) - go tool vet . - go test -v -race ./... ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/���������������������������������������������������0000755�0610621�0607500�00000000000�13172163304�022700� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/util_test.go���������������������������������������0000644�0610621�0607500�00000005041�13172163304�025243� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "net/http" "reflect" "testing" ) var tokenListContainsValueTests = []struct { value string ok bool }{ {"WebSocket", true}, {"WEBSOCKET", true}, {"websocket", true}, {"websockets", false}, {"x websocket", false}, {"websocket x", false}, {"other,websocket,more", true}, {"other, websocket, more", true}, } func TestTokenListContainsValue(t *testing.T) { for _, tt := range tokenListContainsValueTests { h := http.Header{"Upgrade": {tt.value}} ok := tokenListContainsValue(h, "Upgrade", "websocket") if ok != tt.ok { t.Errorf("tokenListContainsValue(h, n, %q) = %v, want %v", tt.value, ok, tt.ok) } } } var parseExtensionTests = []struct { value string extensions []map[string]string }{ {`foo`, []map[string]string{map[string]string{"": "foo"}}}, {`foo, bar; baz=2`, []map[string]string{ map[string]string{"": "foo"}, map[string]string{"": "bar", "baz": "2"}}}, {`foo; bar="b,a;z"`, []map[string]string{ map[string]string{"": "foo", "bar": "b,a;z"}}}, {`foo , bar; baz = 2`, []map[string]string{ map[string]string{"": "foo"}, map[string]string{"": "bar", "baz": "2"}}}, {`foo, bar; baz=2 junk`, []map[string]string{ map[string]string{"": "foo"}}}, {`foo junk, bar; baz=2 junk`, nil}, {`mux; max-channels=4; flow-control, deflate-stream`, []map[string]string{ map[string]string{"": "mux", "max-channels": "4", "flow-control": ""}, map[string]string{"": "deflate-stream"}}}, {`permessage-foo; x="10"`, []map[string]string{ map[string]string{"": "permessage-foo", "x": "10"}}}, {`permessage-foo; use_y, permessage-foo`, []map[string]string{ map[string]string{"": "permessage-foo", "use_y": ""}, map[string]string{"": "permessage-foo"}}}, {`permessage-deflate; client_max_window_bits; server_max_window_bits=10 , permessage-deflate; client_max_window_bits`, []map[string]string{ map[string]string{"": "permessage-deflate", "client_max_window_bits": "", "server_max_window_bits": "10"}, map[string]string{"": "permessage-deflate", "client_max_window_bits": ""}}}, } func TestParseExtensions(t *testing.T) { for _, tt := range parseExtensionTests { h := http.Header{http.CanonicalHeaderKey("Sec-WebSocket-Extensions"): {tt.value}} extensions := parseExtensions(h) if !reflect.DeepEqual(extensions, tt.extensions) { t.Errorf("parseExtensions(%q)\n = %v,\nwant %v", tt.value, extensions, tt.extensions) } } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/util.go��������������������������������������������0000644�0610621�0607500�00000011360�13172163304�024205� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "crypto/rand" "crypto/sha1" "encoding/base64" "io" "net/http" "strings" ) var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") func computeAcceptKey(challengeKey string) string { h := sha1.New() h.Write([]byte(challengeKey)) h.Write(keyGUID) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } func generateChallengeKey() (string, error) { p := make([]byte, 16) if _, err := io.ReadFull(rand.Reader, p); err != nil { return "", err } return base64.StdEncoding.EncodeToString(p), nil } // Octet types from RFC 2616. var octetTypes [256]byte const ( isTokenOctet = 1 << iota isSpaceOctet ) func init() { // From RFC 2616 // // OCTET = <any 8-bit sequence of data> // CHAR = <any US-ASCII character (octets 0 - 127)> // CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)> // CR = <US-ASCII CR, carriage return (13)> // LF = <US-ASCII LF, linefeed (10)> // SP = <US-ASCII SP, space (32)> // HT = <US-ASCII HT, horizontal-tab (9)> // <"> = <US-ASCII double-quote mark (34)> // CRLF = CR LF // LWS = [CRLF] 1*( SP | HT ) // TEXT = <any OCTET except CTLs, but including LWS> // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT // token = 1*<any CHAR except CTLs or separators> // qdtext = <any TEXT except <">> for c := 0; c < 256; c++ { var t byte isCtl := c <= 31 || c == 127 isChar := 0 <= c && c <= 127 isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { t |= isSpaceOctet } if isChar && !isCtl && !isSeparator { t |= isTokenOctet } octetTypes[c] = t } } func skipSpace(s string) (rest string) { i := 0 for ; i < len(s); i++ { if octetTypes[s[i]]&isSpaceOctet == 0 { break } } return s[i:] } func nextToken(s string) (token, rest string) { i := 0 for ; i < len(s); i++ { if octetTypes[s[i]]&isTokenOctet == 0 { break } } return s[:i], s[i:] } func nextTokenOrQuoted(s string) (value string, rest string) { if !strings.HasPrefix(s, "\"") { return nextToken(s) } s = s[1:] for i := 0; i < len(s); i++ { switch s[i] { case '"': return s[:i], s[i+1:] case '\\': p := make([]byte, len(s)-1) j := copy(p, s[:i]) escape := true for i = i + 1; i < len(s); i++ { b := s[i] switch { case escape: escape = false p[j] = b j++ case b == '\\': escape = true case b == '"': return string(p[:j]), s[i+1:] default: p[j] = b j++ } } return "", "" } } return "", "" } // tokenListContainsValue returns true if the 1#token header with the given // name contains token. func tokenListContainsValue(header http.Header, name string, value string) bool { headers: for _, s := range header[name] { for { var t string t, s = nextToken(skipSpace(s)) if t == "" { continue headers } s = skipSpace(s) if s != "" && s[0] != ',' { continue headers } if strings.EqualFold(t, value) { return true } if s == "" { continue headers } s = s[1:] } } return false } // parseExtensiosn parses WebSocket extensions from a header. func parseExtensions(header http.Header) []map[string]string { // From RFC 6455: // // Sec-WebSocket-Extensions = extension-list // extension-list = 1#extension // extension = extension-token *( ";" extension-param ) // extension-token = registered-token // registered-token = token // extension-param = token [ "=" (token | quoted-string) ] // ;When using the quoted-string syntax variant, the value // ;after quoted-string unescaping MUST conform to the // ;'token' ABNF. var result []map[string]string headers: for _, s := range header["Sec-Websocket-Extensions"] { for { var t string t, s = nextToken(skipSpace(s)) if t == "" { continue headers } ext := map[string]string{"": t} for { s = skipSpace(s) if !strings.HasPrefix(s, ";") { break } var k string k, s = nextToken(skipSpace(s[1:])) if k == "" { continue headers } s = skipSpace(s) var v string if strings.HasPrefix(s, "=") { v, s = nextTokenOrQuoted(skipSpace(s[1:])) s = skipSpace(s) } if s != "" && s[0] != ',' && s[0] != ';' { continue headers } ext[k] = v } if s != "" && s[0] != ',' { continue headers } result = append(result, ext) if s == "" { continue headers } s = s[1:] } } return result } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/server_test.go�������������������������������������0000644�0610621�0607500�00000002476�13172163304�025605� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "net/http" "reflect" "testing" ) var subprotocolTests = []struct { h string protocols []string }{ {"", nil}, {"foo", []string{"foo"}}, {"foo,bar", []string{"foo", "bar"}}, {"foo, bar", []string{"foo", "bar"}}, {" foo, bar", []string{"foo", "bar"}}, {" foo, bar ", []string{"foo", "bar"}}, } func TestSubprotocols(t *testing.T) { for _, st := range subprotocolTests { r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {st.h}}} protocols := Subprotocols(&r) if !reflect.DeepEqual(st.protocols, protocols) { t.Errorf("SubProtocols(%q) returned %#v, want %#v", st.h, protocols, st.protocols) } } } var isWebSocketUpgradeTests = []struct { ok bool h http.Header }{ {false, http.Header{"Upgrade": {"websocket"}}}, {false, http.Header{"Connection": {"upgrade"}}}, {true, http.Header{"Connection": {"upgRade"}, "Upgrade": {"WebSocket"}}}, } func TestIsWebSocketUpgrade(t *testing.T) { for _, tt := range isWebSocketUpgradeTests { ok := IsWebSocketUpgrade(&http.Request{Header: tt.h}) if tt.ok != ok { t.Errorf("IsWebSocketUpgrade(%v) returned %v, want %v", tt.h, ok, tt.ok) } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/server.go������������������������������������������0000644�0610621�0607500�00000023011�13172163304�024532� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "errors" "net" "net/http" "net/url" "strings" "time" ) // HandshakeError describes an error with the handshake from the peer. type HandshakeError struct { message string } func (e HandshakeError) Error() string { return e.message } // Upgrader specifies parameters for upgrading an HTTP connection to a // WebSocket connection. type Upgrader struct { // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer // size is zero, then buffers allocated by the HTTP server are used. The // I/O buffer sizes do not limit the size of the messages that can be sent // or received. ReadBufferSize, WriteBufferSize int // Subprotocols specifies the server's supported protocols in order of // preference. If this field is set, then the Upgrade method negotiates a // subprotocol by selecting the first match in this list with a protocol // requested by the client. Subprotocols []string // Error specifies the function for generating HTTP error responses. If Error // is nil, then http.Error is used to generate the HTTP response. Error func(w http.ResponseWriter, r *http.Request, status int, reason error) // CheckOrigin returns true if the request Origin header is acceptable. If // CheckOrigin is nil, the host in the Origin header must not be set or // must match the host of the request. CheckOrigin func(r *http.Request) bool // EnableCompression specify if the server should attempt to negotiate per // message compression (RFC 7692). Setting this value to true does not // guarantee that compression will be supported. Currently only "no context // takeover" modes are supported. EnableCompression bool } func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) { err := HandshakeError{reason} if u.Error != nil { u.Error(w, r, status, err) } else { w.Header().Set("Sec-Websocket-Version", "13") http.Error(w, http.StatusText(status), status) } return nil, err } // checkSameOrigin returns true if the origin is not set or is equal to the request host. func checkSameOrigin(r *http.Request) bool { origin := r.Header["Origin"] if len(origin) == 0 { return true } u, err := url.Parse(origin[0]) if err != nil { return false } return u.Host == r.Host } func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string { if u.Subprotocols != nil { clientProtocols := Subprotocols(r) for _, serverProtocol := range u.Subprotocols { for _, clientProtocol := range clientProtocols { if clientProtocol == serverProtocol { return clientProtocol } } } } else if responseHeader != nil { return responseHeader.Get("Sec-Websocket-Protocol") } return "" } // Upgrade upgrades the HTTP server connection to the WebSocket protocol. // // The responseHeader is included in the response to the client's upgrade // request. Use the responseHeader to specify cookies (Set-Cookie) and the // application negotiated subprotocol (Sec-Websocket-Protocol). // // If the upgrade fails, then Upgrade replies to the client with an HTTP error // response. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) { if r.Method != "GET" { return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: not a websocket handshake: request method is not GET") } if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok { return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-Websocket-Extensions' headers are unsupported") } if !tokenListContainsValue(r.Header, "Connection", "upgrade") { return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header") } if !tokenListContainsValue(r.Header, "Upgrade", "websocket") { return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'websocket' token not found in 'Upgrade' header") } if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") { return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header") } checkOrigin := u.CheckOrigin if checkOrigin == nil { checkOrigin = checkSameOrigin } if !checkOrigin(r) { return u.returnError(w, r, http.StatusForbidden, "websocket: 'Origin' header value not allowed") } challengeKey := r.Header.Get("Sec-Websocket-Key") if challengeKey == "" { return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-Websocket-Key' header is missing or blank") } subprotocol := u.selectSubprotocol(r, responseHeader) // Negotiate PMCE var compress bool if u.EnableCompression { for _, ext := range parseExtensions(r.Header) { if ext[""] != "permessage-deflate" { continue } compress = true break } } var ( netConn net.Conn err error ) h, ok := w.(http.Hijacker) if !ok { return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker") } var brw *bufio.ReadWriter netConn, brw, err = h.Hijack() if err != nil { return u.returnError(w, r, http.StatusInternalServerError, err.Error()) } if brw.Reader.Buffered() > 0 { netConn.Close() return nil, errors.New("websocket: client sent data before handshake is complete") } c := newConnBRW(netConn, true, u.ReadBufferSize, u.WriteBufferSize, brw) c.subprotocol = subprotocol if compress { c.newCompressionWriter = compressNoContextTakeover c.newDecompressionReader = decompressNoContextTakeover } p := c.writeBuf[:0] p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...) p = append(p, computeAcceptKey(challengeKey)...) p = append(p, "\r\n"...) if c.subprotocol != "" { p = append(p, "Sec-Websocket-Protocol: "...) p = append(p, c.subprotocol...) p = append(p, "\r\n"...) } if compress { p = append(p, "Sec-Websocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...) } for k, vs := range responseHeader { if k == "Sec-Websocket-Protocol" { continue } for _, v := range vs { p = append(p, k...) p = append(p, ": "...) for i := 0; i < len(v); i++ { b := v[i] if b <= 31 { // prevent response splitting. b = ' ' } p = append(p, b) } p = append(p, "\r\n"...) } } p = append(p, "\r\n"...) // Clear deadlines set by HTTP server. netConn.SetDeadline(time.Time{}) if u.HandshakeTimeout > 0 { netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)) } if _, err = netConn.Write(p); err != nil { netConn.Close() return nil, err } if u.HandshakeTimeout > 0 { netConn.SetWriteDeadline(time.Time{}) } return c, nil } // Upgrade upgrades the HTTP server connection to the WebSocket protocol. // // Deprecated: Use websocket.Upgrader instead. // // Upgrade does not perform origin checking. The application is responsible for // checking the Origin header before calling Upgrade. An example implementation // of the same origin policy check is: // // if req.Header.Get("Origin") != "http://"+req.Host { // http.Error(w, "Origin not allowed", 403) // return // } // // If the endpoint supports subprotocols, then the application is responsible // for negotiating the protocol used on the connection. Use the Subprotocols() // function to get the subprotocols requested by the client. Use the // Sec-Websocket-Protocol response header to specify the subprotocol selected // by the application. // // The responseHeader is included in the response to the client's upgrade // request. Use the responseHeader to specify cookies (Set-Cookie) and the // negotiated subprotocol (Sec-Websocket-Protocol). // // The connection buffers IO to the underlying network connection. The // readBufSize and writeBufSize parameters specify the size of the buffers to // use. Messages can be larger than the buffers. // // If the request is not a valid WebSocket handshake, then Upgrade returns an // error of type HandshakeError. Applications should handle this error by // replying to the client with an HTTP error response. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) { u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize} u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) { // don't return errors to maintain backwards compatibility } u.CheckOrigin = func(r *http.Request) bool { // allow all connections by default return true } return u.Upgrade(w, r, responseHeader) } // Subprotocols returns the subprotocols requested by the client in the // Sec-Websocket-Protocol header. func Subprotocols(r *http.Request) []string { h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol")) if h == "" { return nil } protocols := strings.Split(h, ",") for i := range protocols { protocols[i] = strings.TrimSpace(protocols[i]) } return protocols } // IsWebSocketUpgrade returns true if the client requested upgrade to the // WebSocket protocol. func IsWebSocketUpgrade(r *http.Request) bool { return tokenListContainsValue(r.Header, "Connection", "upgrade") && tokenListContainsValue(r.Header, "Upgrade", "websocket") } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/prepared_test.go�����������������������������������0000644�0610621�0607500�00000003615�13172163304�026075� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "compress/flate" "math/rand" "testing" ) var preparedMessageTests = []struct { messageType int isServer bool enableWriteCompression bool compressionLevel int }{ // Server {TextMessage, true, false, flate.BestSpeed}, {TextMessage, true, true, flate.BestSpeed}, {TextMessage, true, true, flate.BestCompression}, {PingMessage, true, false, flate.BestSpeed}, {PingMessage, true, true, flate.BestSpeed}, // Client {TextMessage, false, false, flate.BestSpeed}, {TextMessage, false, true, flate.BestSpeed}, {TextMessage, false, true, flate.BestCompression}, {PingMessage, false, false, flate.BestSpeed}, {PingMessage, false, true, flate.BestSpeed}, } func TestPreparedMessage(t *testing.T) { for _, tt := range preparedMessageTests { var data = []byte("this is a test") var buf bytes.Buffer c := newConn(fakeNetConn{Reader: nil, Writer: &buf}, tt.isServer, 1024, 1024) if tt.enableWriteCompression { c.newCompressionWriter = compressNoContextTakeover } c.SetCompressionLevel(tt.compressionLevel) // Seed random number generator for consistent frame mask. rand.Seed(1234) if err := c.WriteMessage(tt.messageType, data); err != nil { t.Fatal(err) } want := buf.String() pm, err := NewPreparedMessage(tt.messageType, data) if err != nil { t.Fatal(err) } // Scribble on data to ensure that NewPreparedMessage takes a snapshot. copy(data, "hello world") // Seed random number generator for consistent frame mask. rand.Seed(1234) buf.Reset() if err := c.WritePreparedMessage(pm); err != nil { t.Fatal(err) } got := buf.String() if got != want { t.Errorf("write message != prepared message for %+v", tt) } } } �������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/prepared.go����������������������������������������0000644�0610621�0607500�00000005642�13172163304�025040� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "net" "sync" "time" ) // PreparedMessage caches on the wire representations of a message payload. // Use PreparedMessage to efficiently send a message payload to multiple // connections. PreparedMessage is especially useful when compression is used // because the CPU and memory expensive compression operation can be executed // once for a given set of compression options. type PreparedMessage struct { messageType int data []byte err error mu sync.Mutex frames map[prepareKey]*preparedFrame } // prepareKey defines a unique set of options to cache prepared frames in PreparedMessage. type prepareKey struct { isServer bool compress bool compressionLevel int } // preparedFrame contains data in wire representation. type preparedFrame struct { once sync.Once data []byte } // NewPreparedMessage returns an initialized PreparedMessage. You can then send // it to connection using WritePreparedMessage method. Valid wire // representation will be calculated lazily only once for a set of current // connection options. func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) { pm := &PreparedMessage{ messageType: messageType, frames: make(map[prepareKey]*preparedFrame), data: data, } // Prepare a plain server frame. _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false}) if err != nil { return nil, err } // To protect against caller modifying the data argument, remember the data // copied to the plain server frame. pm.data = frameData[len(frameData)-len(data):] return pm, nil } func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) { pm.mu.Lock() frame, ok := pm.frames[key] if !ok { frame = &preparedFrame{} pm.frames[key] = frame } pm.mu.Unlock() var err error frame.once.Do(func() { // Prepare a frame using a 'fake' connection. // TODO: Refactor code in conn.go to allow more direct construction of // the frame. mu := make(chan bool, 1) mu <- true var nc prepareConn c := &Conn{ conn: &nc, mu: mu, isServer: key.isServer, compressionLevel: key.compressionLevel, enableWriteCompression: true, writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize), } if key.compress { c.newCompressionWriter = compressNoContextTakeover } err = c.WriteMessage(pm.messageType, pm.data) frame.data = nc.buf.Bytes() }) return pm.messageType, frame.data, err } type prepareConn struct { buf bytes.Buffer net.Conn } func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) } func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil } ����������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/mask_test.go���������������������������������������0000644�0610621�0607500�00000003147�13172163304�025226� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of // this source code is governed by a BSD-style license that can be found in the // LICENSE file. // Require 1.7 for sub-bencmarks // +build go1.7,!appengine package websocket import ( "fmt" "testing" ) func maskBytesByByte(key [4]byte, pos int, b []byte) int { for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } func notzero(b []byte) int { for i := range b { if b[i] != 0 { return i } } return -1 } func TestMaskBytes(t *testing.T) { key := [4]byte{1, 2, 3, 4} for size := 1; size <= 1024; size++ { for align := 0; align < wordSize; align++ { for pos := 0; pos < 4; pos++ { b := make([]byte, size+align)[align:] maskBytes(key, pos, b) maskBytesByByte(key, pos, b) if i := notzero(b); i >= 0 { t.Errorf("size:%d, align:%d, pos:%d, offset:%d", size, align, pos, i) } } } } } func BenchmarkMaskBytes(b *testing.B) { for _, size := range []int{2, 4, 8, 16, 32, 512, 1024} { b.Run(fmt.Sprintf("size-%d", size), func(b *testing.B) { for _, align := range []int{wordSize / 2} { b.Run(fmt.Sprintf("align-%d", align), func(b *testing.B) { for _, fn := range []struct { name string fn func(key [4]byte, pos int, b []byte) int }{ {"byte", maskBytesByByte}, {"word", maskBytes}, } { b.Run(fn.name, func(b *testing.B) { key := newMaskKey() data := make([]byte, size+align)[align:] for i := 0; i < b.N; i++ { fn.fn(key, 0, data) } b.SetBytes(int64(len(data))) }) } }) } }) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/mask_safe.go���������������������������������������0000644�0610621�0607500�00000000523�13172163304�025160� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of // this source code is governed by a BSD-style license that can be found in the // LICENSE file. // +build appengine package websocket func maskBytes(key [4]byte, pos int, b []byte) int { for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/mask.go��������������������������������������������0000644�0610621�0607500�00000002203�13172163304�024157� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of // this source code is governed by a BSD-style license that can be found in the // LICENSE file. // +build !appengine package websocket import "unsafe" const wordSize = int(unsafe.Sizeof(uintptr(0))) func maskBytes(key [4]byte, pos int, b []byte) int { // Mask one byte at a time for small buffers. if len(b) < 2*wordSize { for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } // Mask one byte at a time to word boundary. if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { n = wordSize - n for i := range b[:n] { b[i] ^= key[pos&3] pos++ } b = b[n:] } // Create aligned word size key. var k [wordSize]byte for i := range k { k[i] = key[(pos+i)&3] } kw := *(*uintptr)(unsafe.Pointer(&k)) // Mask one word at a time. n := (len(b) / wordSize) * wordSize for i := 0; i < n; i += wordSize { *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw } // Mask one byte at a time for remaining bytes. b = b[n:] for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/json_test.go���������������������������������������0000644�0610621�0607500�00000004200�13172163304�025233� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "encoding/json" "io" "reflect" "testing" ) func TestJSON(t *testing.T) { var buf bytes.Buffer c := fakeNetConn{&buf, &buf} wc := newConn(c, true, 1024, 1024) rc := newConn(c, false, 1024, 1024) var actual, expect struct { A int B string } expect.A = 1 expect.B = "hello" if err := wc.WriteJSON(&expect); err != nil { t.Fatal("write", err) } if err := rc.ReadJSON(&actual); err != nil { t.Fatal("read", err) } if !reflect.DeepEqual(&actual, &expect) { t.Fatal("equal", actual, expect) } } func TestPartialJSONRead(t *testing.T) { var buf bytes.Buffer c := fakeNetConn{&buf, &buf} wc := newConn(c, true, 1024, 1024) rc := newConn(c, false, 1024, 1024) var v struct { A int B string } v.A = 1 v.B = "hello" messageCount := 0 // Partial JSON values. data, err := json.Marshal(v) if err != nil { t.Fatal(err) } for i := len(data) - 1; i >= 0; i-- { if err := wc.WriteMessage(TextMessage, data[:i]); err != nil { t.Fatal(err) } messageCount++ } // Whitespace. if err := wc.WriteMessage(TextMessage, []byte(" ")); err != nil { t.Fatal(err) } messageCount++ // Close. if err := wc.WriteMessage(CloseMessage, FormatCloseMessage(CloseNormalClosure, "")); err != nil { t.Fatal(err) } for i := 0; i < messageCount; i++ { err := rc.ReadJSON(&v) if err != io.ErrUnexpectedEOF { t.Error("read", i, err) } } err = rc.ReadJSON(&v) if _, ok := err.(*CloseError); !ok { t.Error("final", err) } } func TestDeprecatedJSON(t *testing.T) { var buf bytes.Buffer c := fakeNetConn{&buf, &buf} wc := newConn(c, true, 1024, 1024) rc := newConn(c, false, 1024, 1024) var actual, expect struct { A int B string } expect.A = 1 expect.B = "hello" if err := WriteJSON(wc, &expect); err != nil { t.Fatal("write", err) } if err := ReadJSON(rc, &actual); err != nil { t.Fatal("read", err) } if !reflect.DeepEqual(&actual, &expect) { t.Fatal("equal", actual, expect) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/json.go��������������������������������������������0000644�0610621�0607500�00000002761�13172163304�024206� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "encoding/json" "io" ) // WriteJSON writes the JSON encoding of v as a message. // // Deprecated: Use c.WriteJSON instead. func WriteJSON(c *Conn, v interface{}) error { return c.WriteJSON(v) } // WriteJSON writes the JSON encoding of v as a message. // // See the documentation for encoding/json Marshal for details about the // conversion of Go values to JSON. func (c *Conn) WriteJSON(v interface{}) error { w, err := c.NextWriter(TextMessage) if err != nil { return err } err1 := json.NewEncoder(w).Encode(v) err2 := w.Close() if err1 != nil { return err1 } return err2 } // ReadJSON reads the next JSON-encoded message from the connection and stores // it in the value pointed to by v. // // Deprecated: Use c.ReadJSON instead. func ReadJSON(c *Conn, v interface{}) error { return c.ReadJSON(v) } // ReadJSON reads the next JSON-encoded message from the connection and stores // it in the value pointed to by v. // // See the documentation for the encoding/json Unmarshal function for details // about the conversion of JSON to a Go value. func (c *Conn) ReadJSON(v interface{}) error { _, r, err := c.NextReader() if err != nil { return err } err = json.NewDecoder(r).Decode(v) if err == io.EOF { // One value is expected in the message. err = io.ErrUnexpectedEOF } return err } ���������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/������������������������������������������0000755�0610621�0607500�00000000000�13172163304�024516� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/filewatch/��������������������������������0000755�0610621�0607500�00000000000�13172163304�026464� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/filewatch/main.go�������������������������0000644�0610621�0607500�00000010346�13172163304�027743� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "flag" "html/template" "io/ioutil" "log" "net/http" "os" "strconv" "time" "github.com/gorilla/websocket" ) const ( // Time allowed to write the file to the client. writeWait = 10 * time.Second // Time allowed to read the next pong message from the client. pongWait = 60 * time.Second // Send pings to client with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Poll file for changes with this period. filePeriod = 10 * time.Second ) var ( addr = flag.String("addr", ":8080", "http service address") homeTempl = template.Must(template.New("").Parse(homeHTML)) filename string upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } ) func readFileIfModified(lastMod time.Time) ([]byte, time.Time, error) { fi, err := os.Stat(filename) if err != nil { return nil, lastMod, err } if !fi.ModTime().After(lastMod) { return nil, lastMod, nil } p, err := ioutil.ReadFile(filename) if err != nil { return nil, fi.ModTime(), err } return p, fi.ModTime(), nil } func reader(ws *websocket.Conn) { defer ws.Close() ws.SetReadLimit(512) ws.SetReadDeadline(time.Now().Add(pongWait)) ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, _, err := ws.ReadMessage() if err != nil { break } } } func writer(ws *websocket.Conn, lastMod time.Time) { lastError := "" pingTicker := time.NewTicker(pingPeriod) fileTicker := time.NewTicker(filePeriod) defer func() { pingTicker.Stop() fileTicker.Stop() ws.Close() }() for { select { case <-fileTicker.C: var p []byte var err error p, lastMod, err = readFileIfModified(lastMod) if err != nil { if s := err.Error(); s != lastError { lastError = s p = []byte(lastError) } } else { lastError = "" } if p != nil { ws.SetWriteDeadline(time.Now().Add(writeWait)) if err := ws.WriteMessage(websocket.TextMessage, p); err != nil { return } } case <-pingTicker.C: ws.SetWriteDeadline(time.Now().Add(writeWait)) if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil { return } } } } func serveWs(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { if _, ok := err.(websocket.HandshakeError); !ok { log.Println(err) } return } var lastMod time.Time if n, err := strconv.ParseInt(r.FormValue("lastMod"), 16, 64); err == nil { lastMod = time.Unix(0, n) } go writer(ws, lastMod) reader(ws) } func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found", 404) return } if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") p, lastMod, err := readFileIfModified(time.Time{}) if err != nil { p = []byte(err.Error()) lastMod = time.Unix(0, 0) } var v = struct { Host string Data string LastMod string }{ r.Host, string(p), strconv.FormatInt(lastMod.UnixNano(), 16), } homeTempl.Execute(w, &v) } func main() { flag.Parse() if flag.NArg() != 1 { log.Fatal("filename not specified") } filename = flag.Args()[0] http.HandleFunc("/", serveHome) http.HandleFunc("/ws", serveWs) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal(err) } } const homeHTML = `<!DOCTYPE html> <html lang="en"> <head> <title>WebSocket Example</title> </head> <body> <pre id="fileData">{{.Data}}</pre> <script type="text/javascript"> (function() { var data = document.getElementById("fileData"); var conn = new WebSocket("ws://{{.Host}}/ws?lastMod={{.LastMod}}"); conn.onclose = function(evt) { data.textContent = 'Connection closed'; } conn.onmessage = function(evt) { console.log('file updated'); data.textContent = evt.data; } })(); </script> </body> </html> ` ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/filewatch/README.md�����������������������0000644�0610621�0607500�00000000566�13172163304�027752� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# File Watch example. This example sends a file to the browser client for display whenever the file is modified. $ go get github.com/gorilla/websocket $ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/filewatch` $ go run main.go <name of file to watch> # Open http://localhost:8080/ . # Modify the file to see it update in the browser. ������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/echo/�������������������������������������0000755�0610621�0607500�00000000000�13172163304�025434� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/echo/server.go����������������������������0000644�0610621�0607500�00000005641�13172163304�027277� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main import ( "flag" "html/template" "log" "net/http" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "localhost:8080", "http service address") var upgrader = websocket.Upgrader{} // use default options func echo(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } log.Printf("recv: %s", message) err = c.WriteMessage(mt, message) if err != nil { log.Println("write:", err) break } } } func home(w http.ResponseWriter, r *http.Request) { homeTemplate.Execute(w, "ws://"+r.Host+"/echo") } func main() { flag.Parse() log.SetFlags(0) http.HandleFunc("/echo", echo) http.HandleFunc("/", home) log.Fatal(http.ListenAndServe(*addr, nil)) } var homeTemplate = template.Must(template.New("").Parse(` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> window.addEventListener("load", function(evt) { var output = document.getElementById("output"); var input = document.getElementById("input"); var ws; var print = function(message) { var d = document.createElement("div"); d.innerHTML = message; output.appendChild(d); }; document.getElementById("open").onclick = function(evt) { if (ws) { return false; } ws = new WebSocket("{{.}}"); ws.onopen = function(evt) { print("OPEN"); } ws.onclose = function(evt) { print("CLOSE"); ws = null; } ws.onmessage = function(evt) { print("RESPONSE: " + evt.data); } ws.onerror = function(evt) { print("ERROR: " + evt.data); } return false; }; document.getElementById("send").onclick = function(evt) { if (!ws) { return false; } print("SEND: " + input.value); ws.send(input.value); return false; }; document.getElementById("close").onclick = function(evt) { if (!ws) { return false; } ws.close(); return false; }; }); </script> </head> <body> <table> <tr><td valign="top" width="50%"> <p>Click "Open" to create a connection to the server, "Send" to send a message to the server and "Close" to close the connection. You can change the message and send multiple times. <p> <form> <button id="open">Open</button> <button id="close">Close</button> <p><input id="input" type="text" value="Hello world!"> <button id="send">Send</button> </form> </td><td valign="top" width="50%"> <div id="output"></div> </td></tr></table> </body> </html> `)) �����������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/echo/client.go����������������������������0000644�0610621�0607500�00000003177�13172163304�027251� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main import ( "flag" "log" "net/url" "os" "os/signal" "time" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "localhost:8080", "http service address") func main() { flag.Parse() log.SetFlags(0) interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"} log.Printf("connecting to %s", u.String()) c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("dial:", err) } defer c.Close() done := make(chan struct{}) go func() { defer c.Close() defer close(done) for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } log.Printf("recv: %s", message) } }() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case t := <-ticker.C: err := c.WriteMessage(websocket.TextMessage, []byte(t.String())) if err != nil { log.Println("write:", err) return } case <-interrupt: log.Println("interrupt") // To cleanly close a connection, a client should send a close // frame and wait for the server to close the connection. err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) if err != nil { log.Println("write close:", err) return } select { case <-done: case <-time.After(time.Second): } c.Close() return } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/echo/README.md����������������������������0000644�0610621�0607500�00000000676�13172163304�026724� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Client and server example This example shows a simple client and server. The server echoes messages sent to it. The client sends a message every second and prints all messages received. To run the example, start the server: $ go run server.go Next, start the client: $ go run client.go The server includes a simple web client. To use the client, open http://127.0.0.1:8080 in the browser and follow the instructions on the page. ������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/command/����������������������������������0000755�0610621�0607500�00000000000�13172163304�026134� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/command/main.go���������������������������0000644�0610621�0607500�00000010037�13172163304�027410� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bufio" "flag" "io" "log" "net/http" "os" "os/exec" "time" "github.com/gorilla/websocket" ) var ( addr = flag.String("addr", "127.0.0.1:8080", "http service address") cmdPath string ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Maximum message size allowed from peer. maxMessageSize = 8192 // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Time to wait before force close on connection. closeGracePeriod = 10 * time.Second ) func pumpStdin(ws *websocket.Conn, w io.Writer) { defer ws.Close() ws.SetReadLimit(maxMessageSize) ws.SetReadDeadline(time.Now().Add(pongWait)) ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := ws.ReadMessage() if err != nil { break } message = append(message, '\n') if _, err := w.Write(message); err != nil { break } } } func pumpStdout(ws *websocket.Conn, r io.Reader, done chan struct{}) { defer func() { }() s := bufio.NewScanner(r) for s.Scan() { ws.SetWriteDeadline(time.Now().Add(writeWait)) if err := ws.WriteMessage(websocket.TextMessage, s.Bytes()); err != nil { ws.Close() break } } if s.Err() != nil { log.Println("scan:", s.Err()) } close(done) ws.SetWriteDeadline(time.Now().Add(writeWait)) ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) time.Sleep(closeGracePeriod) ws.Close() } func ping(ws *websocket.Conn, done chan struct{}) { ticker := time.NewTicker(pingPeriod) defer ticker.Stop() for { select { case <-ticker.C: if err := ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait)); err != nil { log.Println("ping:", err) } case <-done: return } } } func internalError(ws *websocket.Conn, msg string, err error) { log.Println(msg, err) ws.WriteMessage(websocket.TextMessage, []byte("Internal server error.")) } var upgrader = websocket.Upgrader{} func serveWs(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("upgrade:", err) return } defer ws.Close() outr, outw, err := os.Pipe() if err != nil { internalError(ws, "stdout:", err) return } defer outr.Close() defer outw.Close() inr, inw, err := os.Pipe() if err != nil { internalError(ws, "stdin:", err) return } defer inr.Close() defer inw.Close() proc, err := os.StartProcess(cmdPath, flag.Args(), &os.ProcAttr{ Files: []*os.File{inr, outw, outw}, }) if err != nil { internalError(ws, "start:", err) return } inr.Close() outw.Close() stdoutDone := make(chan struct{}) go pumpStdout(ws, outr, stdoutDone) go ping(ws, stdoutDone) pumpStdin(ws, inw) // Some commands will exit when stdin is closed. inw.Close() // Other commands need a bonk on the head. if err := proc.Signal(os.Interrupt); err != nil { log.Println("inter:", err) } select { case <-stdoutDone: case <-time.After(time.Second): // A bigger bonk on the head. if err := proc.Signal(os.Kill); err != nil { log.Println("term:", err) } <-stdoutDone } if _, err := proc.Wait(); err != nil { log.Println("wait:", err) } } func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found", 404) return } if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } http.ServeFile(w, r, "home.html") } func main() { flag.Parse() if len(flag.Args()) < 1 { log.Fatal("must specify at least one argument") } var err error cmdPath, err = exec.LookPath(flag.Args()[0]) if err != nil { log.Fatal(err) } http.HandleFunc("/", serveHome) http.HandleFunc("/ws", serveWs) log.Fatal(http.ListenAndServe(*addr, nil)) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/command/home.html�������������������������0000644�0610621�0607500�00000004327�13172163304�027760� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en"> <head> <title>Command Example</title> <script type="text/javascript"> window.onload = function () { var conn; var msg = document.getElementById("msg"); var log = document.getElementById("log"); function appendLog(item) { var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1; log.appendChild(item); if (doScroll) { log.scrollTop = log.scrollHeight - log.clientHeight; } } document.getElementById("form").onsubmit = function () { if (!conn) { return false; } if (!msg.value) { return false; } conn.send(msg.value); msg.value = ""; return false; }; if (window["WebSocket"]) { conn = new WebSocket("ws://" + document.location.host + "/ws"); conn.onclose = function (evt) { var item = document.createElement("div"); item.innerHTML = "<b>Connection closed.</b>"; appendLog(item); }; conn.onmessage = function (evt) { var messages = evt.data.split('\n'); for (var i = 0; i < messages.length; i++) { var item = document.createElement("div"); item.innerText = messages[i]; appendLog(item); } }; } else { var item = document.createElement("div"); item.innerHTML = "<b>Your browser does not support WebSockets.</b>"; appendLog(item); } }; </script> <style type="text/css"> html { overflow: hidden; } body { overflow: hidden; padding: 0; margin: 0; width: 100%; height: 100%; background: gray; } #log { background: white; margin: 0; padding: 0.5em 0.5em 0.5em 0.5em; position: absolute; top: 0.5em; left: 0.5em; right: 0.5em; bottom: 3em; overflow: auto; } #log pre { margin: 0; } #form { padding: 0 0.5em 0 0.5em; margin: 0; position: absolute; bottom: 1em; left: 0px; width: 100%; overflow: hidden; } </style> </head> <body> <div id="log"></div> <form id="form"> <input type="submit" value="Send" /> <input type="text" id="msg" size="64"/> </form> </body> </html> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/command/README.md�������������������������0000644�0610621�0607500�00000001150�13172163304�027410� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Command example This example connects a websocket connection to stdin and stdout of a command. Received messages are written to stdin followed by a `\n`. Each line read from standard out is sent as a message to the client. $ go get github.com/gorilla/websocket $ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/command` $ go run main.go <command and arguments to run> # Open http://localhost:8080/ . Try the following commands. # Echo sent messages to the output area. $ go run main.go cat # Run a shell.Try sending "ls" and "cat main.go". $ go run main.go sh ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/chat/�������������������������������������0000755�0610621�0607500�00000000000�13172163304�025435� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/chat/main.go������������������������������0000644�0610621�0607500�00000001514�13172163304�026711� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "flag" "log" "net/http" ) var addr = flag.String("addr", ":8080", "http service address") func serveHome(w http.ResponseWriter, r *http.Request) { log.Println(r.URL) if r.URL.Path != "/" { http.Error(w, "Not found", 404) return } if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } http.ServeFile(w, r, "home.html") } func main() { flag.Parse() hub := newHub() go hub.run() http.HandleFunc("/", serveHome) http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { serveWs(hub, w, r) }) err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/chat/hub.go�������������������������������0000644�0610621�0607500�00000002174�13172163304�026546� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main // hub maintains the set of active clients and broadcasts messages to the // clients. type Hub struct { // Registered clients. clients map[*Client]bool // Inbound messages from the clients. broadcast chan []byte // Register requests from the clients. register chan *Client // Unregister requests from clients. unregister chan *Client } func newHub() *Hub { return &Hub{ broadcast: make(chan []byte), register: make(chan *Client), unregister: make(chan *Client), clients: make(map[*Client]bool), } } func (h *Hub) run() { for { select { case client := <-h.register: h.clients[client] = true case client := <-h.unregister: if _, ok := h.clients[client]; ok { delete(h.clients, client) close(client.send) } case message := <-h.broadcast: for client := range h.clients { select { case client.send <- message: default: close(client.send) delete(h.clients, client) } } } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/chat/home.html����������������������������0000644�0610621�0607500�00000004271�13172163304�027257� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en"> <head> <title>Chat Example</title> <script type="text/javascript"> window.onload = function () { var conn; var msg = document.getElementById("msg"); var log = document.getElementById("log"); function appendLog(item) { var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1; log.appendChild(item); if (doScroll) { log.scrollTop = log.scrollHeight - log.clientHeight; } } document.getElementById("form").onsubmit = function () { if (!conn) { return false; } if (!msg.value) { return false; } conn.send(msg.value); msg.value = ""; return false; }; if (window["WebSocket"]) { conn = new WebSocket("ws://" + document.location.host + "/ws"); conn.onclose = function (evt) { var item = document.createElement("div"); item.innerHTML = "<b>Connection closed.</b>"; appendLog(item); }; conn.onmessage = function (evt) { var messages = evt.data.split('\n'); for (var i = 0; i < messages.length; i++) { var item = document.createElement("div"); item.innerText = messages[i]; appendLog(item); } }; } else { var item = document.createElement("div"); item.innerHTML = "<b>Your browser does not support WebSockets.</b>"; appendLog(item); } }; </script> <style type="text/css"> html { overflow: hidden; } body { overflow: hidden; padding: 0; margin: 0; width: 100%; height: 100%; background: gray; } #log { background: white; margin: 0; padding: 0.5em 0.5em 0.5em 0.5em; position: absolute; top: 0.5em; left: 0.5em; right: 0.5em; bottom: 3em; overflow: auto; } #form { padding: 0 0.5em 0 0.5em; margin: 0; position: absolute; bottom: 1em; left: 0px; width: 100%; overflow: hidden; } </style> </head> <body> <div id="log"></div> <form id="form"> <input type="submit" value="Send" /> <input type="text" id="msg" size="64"/> </form> </body> </html> ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/chat/client.go����������������������������0000644�0610621�0607500�00000006506�13172163304�027251� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "log" "net/http" "time" "github.com/gorilla/websocket" ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Maximum message size allowed from peer. maxMessageSize = 512 ) var ( newline = []byte{'\n'} space = []byte{' '} ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } // Client is a middleman between the websocket connection and the hub. type Client struct { hub *Hub // The websocket connection. conn *websocket.Conn // Buffered channel of outbound messages. send chan []byte } // readPump pumps messages from the websocket connection to the hub. // // The application runs readPump in a per-connection goroutine. The application // ensures that there is at most one reader on a connection by executing all // reads from this goroutine. func (c *Client) readPump() { defer func() { c.hub.unregister <- c c.conn.Close() }() c.conn.SetReadLimit(maxMessageSize) c.conn.SetReadDeadline(time.Now().Add(pongWait)) c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { log.Printf("error: %v", err) } break } message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1)) c.hub.broadcast <- message } } // writePump pumps messages from the hub to the websocket connection. // // A goroutine running writePump is started for each connection. The // application ensures that there is at most one writer to a connection by // executing all writes from this goroutine. func (c *Client) writePump() { ticker := time.NewTicker(pingPeriod) defer func() { ticker.Stop() c.conn.Close() }() for { select { case message, ok := <-c.send: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if !ok { // The hub closed the channel. c.conn.WriteMessage(websocket.CloseMessage, []byte{}) return } w, err := c.conn.NextWriter(websocket.TextMessage) if err != nil { return } w.Write(message) // Add queued chat messages to the current websocket message. n := len(c.send) for i := 0; i < n; i++ { w.Write(newline) w.Write(<-c.send) } if err := w.Close(); err != nil { return } case <-ticker.C: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil { return } } } } // serveWs handles websocket requests from the peer. func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return } client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)} client.hub.register <- client // Allow collection of memory referenced by the caller by doing all work in // new goroutines. go client.writePump() go client.readPump() } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/chat/README.md����������������������������0000644�0610621�0607500�00000011153�13172163304�026715� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Chat Example This application shows how to use use the [websocket](https://github.com/gorilla/websocket) package to implement a simple web chat application. ## Running the example The example requires a working Go development environment. The [Getting Started](http://golang.org/doc/install) page describes how to install the development environment. Once you have Go up and running, you can download, build and run the example using the following commands. $ go get github.com/gorilla/websocket $ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/chat` $ go run *.go To use the chat example, open http://localhost:8080/ in your browser. ## Server The server application defines two types, `Client` and `Hub`. The server creates an instance of the `Client` type for each websocket connection. A `Client` acts as an intermediary between the websocket connection and a single instance of the `Hub` type. The `Hub` maintains a set of registered clients and broadcasts messages to the clients. The application runs one goroutine for the `Hub` and two goroutines for each `Client`. The goroutines communicate with each other using channels. The `Hub` has channels for registering clients, unregistering clients and broadcasting messages. A `Client` has a buffered channel of outbound messages. One of the client's goroutines reads messages from this channel and writes the messages to the websocket. The other client goroutine reads messages from the websocket and sends them to the hub. ### Hub The code for the `Hub` type is in [hub.go](https://github.com/gorilla/websocket/blob/master/examples/chat/hub.go). The application's `main` function starts the hub's `run` method as a goroutine. Clients send requests to the hub using the `register`, `unregister` and `broadcast` channels. The hub registers clients by adding the client pointer as a key in the `clients` map. The map value is always true. The unregister code is a little more complicated. In addition to deleting the client pointer from the `clients` map, the hub closes the clients's `send` channel to signal the client that no more messages will be sent to the client. The hub handles messages by looping over the registered clients and sending the message to the client's `send` channel. If the client's `send` buffer is full, then the hub assumes that the client is dead or stuck. In this case, the hub unregisters the client and closes the websocket. ### Client The code for the `Client` type is in [client.go](https://github.com/gorilla/websocket/blob/master/examples/chat/client.go). The `serveWs` function is registered by the application's `main` function as an HTTP handler. The handler upgrades the HTTP connection to the WebSocket protocol, creates a client, registers the client with the hub and schedules the client to be unregistered using a defer statement. Next, the HTTP handler starts the client's `writePump` method as a goroutine. This method transfers messages from the client's send channel to the websocket connection. The writer method exits when the channel is closed by the hub or there's an error writing to the websocket connection. Finally, the HTTP handler calls the client's `readPump` method. This method transfers inbound messages from the websocket to the hub. WebSocket connections [support one concurrent reader and one concurrent writer](https://godoc.org/github.com/gorilla/websocket#hdr-Concurrency). The application ensures that these concurrency requirements are met by executing all reads from the `readPump` goroutine and all writes from the `writePump` goroutine. To improve efficiency under high load, the `writePump` function coalesces pending chat messages in the `send` channel to a single WebSocket message. This reduces the number of system calls and the amount of data sent over the network. ## Frontend The frontend code is in [home.html](https://github.com/gorilla/websocket/blob/master/examples/chat/home.html). On document load, the script checks for websocket functionality in the browser. If websocket functionality is available, then the script opens a connection to the server and registers a callback to handle messages from the server. The callback appends the message to the chat log using the appendLog function. To allow the user to manually scroll through the chat log without interruption from new messages, the `appendLog` function checks the scroll position before adding new content. If the chat log is scrolled to the bottom, then the function scrolls new content into view after adding the content. Otherwise, the scroll position is not changed. The form handler writes the user input to the websocket and clears the input field. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/autobahn/���������������������������������0000755�0610621�0607500�00000000000�13172163304�026317� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/autobahn/server.go������������������������0000644�0610621�0607500�00000017031�13172163304�030156� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command server is a test server for the Autobahn WebSockets Test Suite. package main import ( "errors" "flag" "io" "log" "net/http" "time" "unicode/utf8" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 4096, WriteBufferSize: 4096, EnableCompression: true, CheckOrigin: func(r *http.Request) bool { return true }, } // echoCopy echoes messages from the client using io.Copy. func echoCopy(w http.ResponseWriter, r *http.Request, writerOnly bool) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade:", err) return } defer conn.Close() for { mt, r, err := conn.NextReader() if err != nil { if err != io.EOF { log.Println("NextReader:", err) } return } if mt == websocket.TextMessage { r = &validator{r: r} } w, err := conn.NextWriter(mt) if err != nil { log.Println("NextWriter:", err) return } if mt == websocket.TextMessage { r = &validator{r: r} } if writerOnly { _, err = io.Copy(struct{ io.Writer }{w}, r) } else { _, err = io.Copy(w, r) } if err != nil { if err == errInvalidUTF8 { conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""), time.Time{}) } log.Println("Copy:", err) return } err = w.Close() if err != nil { log.Println("Close:", err) return } } } func echoCopyWriterOnly(w http.ResponseWriter, r *http.Request) { echoCopy(w, r, true) } func echoCopyFull(w http.ResponseWriter, r *http.Request) { echoCopy(w, r, false) } // echoReadAll echoes messages from the client by reading the entire message // with ioutil.ReadAll. func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage, writePrepared bool) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade:", err) return } defer conn.Close() for { mt, b, err := conn.ReadMessage() if err != nil { if err != io.EOF { log.Println("NextReader:", err) } return } if mt == websocket.TextMessage { if !utf8.Valid(b) { conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""), time.Time{}) log.Println("ReadAll: invalid utf8") } } if writeMessage { if !writePrepared { err = conn.WriteMessage(mt, b) if err != nil { log.Println("WriteMessage:", err) } } else { pm, err := websocket.NewPreparedMessage(mt, b) if err != nil { log.Println("NewPreparedMessage:", err) return } err = conn.WritePreparedMessage(pm) if err != nil { log.Println("WritePreparedMessage:", err) } } } else { w, err := conn.NextWriter(mt) if err != nil { log.Println("NextWriter:", err) return } if _, err := w.Write(b); err != nil { log.Println("Writer:", err) return } if err := w.Close(); err != nil { log.Println("Close:", err) return } } } } func echoReadAllWriter(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, false, false) } func echoReadAllWriteMessage(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, true, false) } func echoReadAllWritePreparedMessage(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, true, true) } func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found.", 404) return } if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") io.WriteString(w, "<html><body>Echo Server</body></html>") } var addr = flag.String("addr", ":9000", "http service address") func main() { flag.Parse() http.HandleFunc("/", serveHome) http.HandleFunc("/c", echoCopyWriterOnly) http.HandleFunc("/f", echoCopyFull) http.HandleFunc("/r", echoReadAllWriter) http.HandleFunc("/m", echoReadAllWriteMessage) http.HandleFunc("/p", echoReadAllWritePreparedMessage) err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } type validator struct { state int x rune r io.Reader } var errInvalidUTF8 = errors.New("invalid utf8") func (r *validator) Read(p []byte) (int, error) { n, err := r.r.Read(p) state := r.state x := r.x for _, b := range p[:n] { state, x = decode(state, x, b) if state == utf8Reject { break } } r.state = state r.x = x if state == utf8Reject || (err == io.EOF && state != utf8Accept) { return n, errInvalidUTF8 } return n, err } // UTF-8 decoder from http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ // // Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. var utf8d = [...]byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7f 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9f 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // a0..bf 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // c0..df 0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // e0..ef 0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // f0..ff 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // s7..s8 } const ( utf8Accept = 0 utf8Reject = 1 ) func decode(state int, x rune, b byte) (int, rune) { t := utf8d[b] if state != utf8Accept { x = rune(b&0x3f) | (x << 6) } else { x = rune((0xff >> t) & b) } state = int(utf8d[256+state*16+int(t)]) return state, x } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/autobahn/fuzzingclient.json���������������0000644�0610621�0607500�00000001231�13172163304�032102� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� { "options": {"failByDrop": false}, "outdir": "./reports/clients", "servers": [ {"agent": "ReadAllWriteMessage", "url": "ws://localhost:9000/m", "options": {"version": 18}}, {"agent": "ReadAllWritePreparedMessage", "url": "ws://localhost:9000/p", "options": {"version": 18}}, {"agent": "ReadAllWrite", "url": "ws://localhost:9000/r", "options": {"version": 18}}, {"agent": "CopyFull", "url": "ws://localhost:9000/f", "options": {"version": 18}}, {"agent": "CopyWriterOnly", "url": "ws://localhost:9000/c", "options": {"version": 18}} ], "cases": ["*"], "exclude-cases": [], "exclude-agent-cases": {} } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/examples/autobahn/README.md������������������������0000644�0610621�0607500�00000000510�13172163304�027572� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Test Server This package contains a server for the [Autobahn WebSockets Test Suite](http://autobahn.ws/testsuite). To test the server, run go run server.go and start the client test driver wstest -m fuzzingclient -s fuzzingclient.json When the client completes, it writes a report to reports/clients/index.html. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/example_test.go������������������������������������0000644�0610621�0607500�00000002442�13172163304�025723� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket_test import ( "log" "net/http" "testing" "github.com/gorilla/websocket" ) var ( c *websocket.Conn req *http.Request ) // The websocket.IsUnexpectedCloseError function is useful for identifying // application and protocol errors. // // This server application works with a client application running in the // browser. The client application does not explicitly close the websocket. The // only expected close message from the client has the code // websocket.CloseGoingAway. All other other close messages are likely the // result of an application or protocol error and are logged to aid debugging. func ExampleIsUnexpectedCloseError() { for { messageType, p, err := c.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { log.Printf("error: %v, user-agent: %v", err, req.Header.Get("User-Agent")) } return } processMesage(messageType, p) } } func processMesage(mt int, p []byte) {} // TestX prevents godoc from showing this entire file in the example. Remove // this function when a second example is added. func TestX(t *testing.T) {} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/doc.go���������������������������������������������0000644�0610621�0607500�00000015410�13172163304�023775� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package websocket implements the WebSocket protocol defined in RFC 6455. // // Overview // // The Conn type represents a WebSocket connection. A server application calls // the Upgrader.Upgrade method from an HTTP request handler to get a *Conn: // // var upgrader = websocket.Upgrader{ // ReadBufferSize: 1024, // WriteBufferSize: 1024, // } // // func handler(w http.ResponseWriter, r *http.Request) { // conn, err := upgrader.Upgrade(w, r, nil) // if err != nil { // log.Println(err) // return // } // ... Use conn to send and receive messages. // } // // Call the connection's WriteMessage and ReadMessage methods to send and // receive messages as a slice of bytes. This snippet of code shows how to echo // messages using these methods: // // for { // messageType, p, err := conn.ReadMessage() // if err != nil { // return // } // if err := conn.WriteMessage(messageType, p); err != nil { // return err // } // } // // In above snippet of code, p is a []byte and messageType is an int with value // websocket.BinaryMessage or websocket.TextMessage. // // An application can also send and receive messages using the io.WriteCloser // and io.Reader interfaces. To send a message, call the connection NextWriter // method to get an io.WriteCloser, write the message to the writer and close // the writer when done. To receive a message, call the connection NextReader // method to get an io.Reader and read until io.EOF is returned. This snippet // shows how to echo messages using the NextWriter and NextReader methods: // // for { // messageType, r, err := conn.NextReader() // if err != nil { // return // } // w, err := conn.NextWriter(messageType) // if err != nil { // return err // } // if _, err := io.Copy(w, r); err != nil { // return err // } // if err := w.Close(); err != nil { // return err // } // } // // Data Messages // // The WebSocket protocol distinguishes between text and binary data messages. // Text messages are interpreted as UTF-8 encoded text. The interpretation of // binary messages is left to the application. // // This package uses the TextMessage and BinaryMessage integer constants to // identify the two data message types. The ReadMessage and NextReader methods // return the type of the received message. The messageType argument to the // WriteMessage and NextWriter methods specifies the type of a sent message. // // It is the application's responsibility to ensure that text messages are // valid UTF-8 encoded text. // // Control Messages // // The WebSocket protocol defines three types of control messages: close, ping // and pong. Call the connection WriteControl, WriteMessage or NextWriter // methods to send a control message to the peer. // // Connections handle received close messages by sending a close message to the // peer and returning a *CloseError from the the NextReader, ReadMessage or the // message Read method. // // Connections handle received ping and pong messages by invoking callback // functions set with SetPingHandler and SetPongHandler methods. The callback // functions are called from the NextReader, ReadMessage and the message Read // methods. // // The default ping handler sends a pong to the peer. The application's reading // goroutine can block for a short time while the handler writes the pong data // to the connection. // // The application must read the connection to process ping, pong and close // messages sent from the peer. If the application is not otherwise interested // in messages from the peer, then the application should start a goroutine to // read and discard messages from the peer. A simple example is: // // func readLoop(c *websocket.Conn) { // for { // if _, _, err := c.NextReader(); err != nil { // c.Close() // break // } // } // } // // Concurrency // // Connections support one concurrent reader and one concurrent writer. // // Applications are responsible for ensuring that no more than one goroutine // calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, // WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and // that no more than one goroutine calls the read methods (NextReader, // SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) // concurrently. // // The Close and WriteControl methods can be called concurrently with all other // methods. // // Origin Considerations // // Web browsers allow Javascript applications to open a WebSocket connection to // any host. It's up to the server to enforce an origin policy using the Origin // request header sent by the browser. // // The Upgrader calls the function specified in the CheckOrigin field to check // the origin. If the CheckOrigin function returns false, then the Upgrade // method fails the WebSocket handshake with HTTP status 403. // // If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail // the handshake if the Origin request header is present and not equal to the // Host request header. // // An application can allow connections from any origin by specifying a // function that always returns true: // // var upgrader = websocket.Upgrader{ // CheckOrigin: func(r *http.Request) bool { return true }, // } // // The deprecated package-level Upgrade function does not perform origin // checking. The application is responsible for checking the Origin header // before calling the Upgrade function. // // Compression EXPERIMENTAL // // Per message compression extensions (RFC 7692) are experimentally supported // by this package in a limited capacity. Setting the EnableCompression option // to true in Dialer or Upgrader will attempt to negotiate per message deflate // support. // // var upgrader = websocket.Upgrader{ // EnableCompression: true, // } // // If compression was successfully negotiated with the connection's peer, any // message received in compressed form will be automatically decompressed. // All Read methods will return uncompressed bytes. // // Per message compression of messages written to a connection can be enabled // or disabled by calling the corresponding Conn method: // // conn.EnableWriteCompression(false) // // Currently this package does not support compression with "context takeover". // This means that messages must be compressed and decompressed in isolation, // without retaining sliding window or dictionary state across messages. For // more details refer to RFC 7692. // // Use of compression is experimental and may result in decreased performance. package websocket ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/conn_test.go���������������������������������������0000644�0610621�0607500�00000032251�13172163304�025226� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "bytes" "errors" "fmt" "io" "io/ioutil" "net" "reflect" "testing" "testing/iotest" "time" ) var _ net.Error = errWriteTimeout type fakeNetConn struct { io.Reader io.Writer } func (c fakeNetConn) Close() error { return nil } func (c fakeNetConn) LocalAddr() net.Addr { return localAddr } func (c fakeNetConn) RemoteAddr() net.Addr { return remoteAddr } func (c fakeNetConn) SetDeadline(t time.Time) error { return nil } func (c fakeNetConn) SetReadDeadline(t time.Time) error { return nil } func (c fakeNetConn) SetWriteDeadline(t time.Time) error { return nil } type fakeAddr int var ( localAddr = fakeAddr(1) remoteAddr = fakeAddr(2) ) func (a fakeAddr) Network() string { return "net" } func (a fakeAddr) String() string { return "str" } func TestFraming(t *testing.T) { frameSizes := []int{0, 1, 2, 124, 125, 126, 127, 128, 129, 65534, 65535, 65536, 65537} var readChunkers = []struct { name string f func(io.Reader) io.Reader }{ {"half", iotest.HalfReader}, {"one", iotest.OneByteReader}, {"asis", func(r io.Reader) io.Reader { return r }}, } writeBuf := make([]byte, 65537) for i := range writeBuf { writeBuf[i] = byte(i) } var writers = []struct { name string f func(w io.Writer, n int) (int, error) }{ {"iocopy", func(w io.Writer, n int) (int, error) { nn, err := io.Copy(w, bytes.NewReader(writeBuf[:n])) return int(nn), err }}, {"write", func(w io.Writer, n int) (int, error) { return w.Write(writeBuf[:n]) }}, {"string", func(w io.Writer, n int) (int, error) { return io.WriteString(w, string(writeBuf[:n])) }}, } for _, compress := range []bool{false, true} { for _, isServer := range []bool{true, false} { for _, chunker := range readChunkers { var connBuf bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &connBuf}, isServer, 1024, 1024) rc := newConn(fakeNetConn{Reader: chunker.f(&connBuf), Writer: nil}, !isServer, 1024, 1024) if compress { wc.newCompressionWriter = compressNoContextTakeover rc.newDecompressionReader = decompressNoContextTakeover } for _, n := range frameSizes { for _, writer := range writers { name := fmt.Sprintf("z:%v, s:%v, r:%s, n:%d w:%s", compress, isServer, chunker.name, n, writer.name) w, err := wc.NextWriter(TextMessage) if err != nil { t.Errorf("%s: wc.NextWriter() returned %v", name, err) continue } nn, err := writer.f(w, n) if err != nil || nn != n { t.Errorf("%s: w.Write(writeBuf[:n]) returned %d, %v", name, nn, err) continue } err = w.Close() if err != nil { t.Errorf("%s: w.Close() returned %v", name, err) continue } opCode, r, err := rc.NextReader() if err != nil || opCode != TextMessage { t.Errorf("%s: NextReader() returned %d, r, %v", name, opCode, err) continue } rbuf, err := ioutil.ReadAll(r) if err != nil { t.Errorf("%s: ReadFull() returned rbuf, %v", name, err) continue } if len(rbuf) != n { t.Errorf("%s: len(rbuf) is %d, want %d", name, len(rbuf), n) continue } for i, b := range rbuf { if byte(i) != b { t.Errorf("%s: bad byte at offset %d", name, i) break } } } } } } } } func TestControl(t *testing.T) { const message = "this is a ping/pong messsage" for _, isServer := range []bool{true, false} { for _, isWriteControl := range []bool{true, false} { name := fmt.Sprintf("s:%v, wc:%v", isServer, isWriteControl) var connBuf bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &connBuf}, isServer, 1024, 1024) rc := newConn(fakeNetConn{Reader: &connBuf, Writer: nil}, !isServer, 1024, 1024) if isWriteControl { wc.WriteControl(PongMessage, []byte(message), time.Now().Add(time.Second)) } else { w, err := wc.NextWriter(PongMessage) if err != nil { t.Errorf("%s: wc.NextWriter() returned %v", name, err) continue } if _, err := w.Write([]byte(message)); err != nil { t.Errorf("%s: w.Write() returned %v", name, err) continue } if err := w.Close(); err != nil { t.Errorf("%s: w.Close() returned %v", name, err) continue } var actualMessage string rc.SetPongHandler(func(s string) error { actualMessage = s; return nil }) rc.NextReader() if actualMessage != message { t.Errorf("%s: pong=%q, want %q", name, actualMessage, message) continue } } } } } func TestCloseFrameBeforeFinalMessageFrame(t *testing.T) { const bufSize = 512 expectedErr := &CloseError{Code: CloseNormalClosure, Text: "hello"} var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, 1024, bufSize) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, 1024, 1024) w, _ := wc.NextWriter(BinaryMessage) w.Write(make([]byte, bufSize+bufSize/2)) wc.WriteControl(CloseMessage, FormatCloseMessage(expectedErr.Code, expectedErr.Text), time.Now().Add(10*time.Second)) w.Close() op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } _, err = io.Copy(ioutil.Discard, r) if !reflect.DeepEqual(err, expectedErr) { t.Fatalf("io.Copy() returned %v, want %v", err, expectedErr) } _, _, err = rc.NextReader() if !reflect.DeepEqual(err, expectedErr) { t.Fatalf("NextReader() returned %v, want %v", err, expectedErr) } } func TestEOFWithinFrame(t *testing.T) { const bufSize = 64 for n := 0; ; n++ { var b bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b}, false, 1024, 1024) rc := newConn(fakeNetConn{Reader: &b, Writer: nil}, true, 1024, 1024) w, _ := wc.NextWriter(BinaryMessage) w.Write(make([]byte, bufSize)) w.Close() if n >= b.Len() { break } b.Truncate(n) op, r, err := rc.NextReader() if err == errUnexpectedEOF { continue } if op != BinaryMessage || err != nil { t.Fatalf("%d: NextReader() returned %d, %v", n, op, err) } _, err = io.Copy(ioutil.Discard, r) if err != errUnexpectedEOF { t.Fatalf("%d: io.Copy() returned %v, want %v", n, err, errUnexpectedEOF) } _, _, err = rc.NextReader() if err != errUnexpectedEOF { t.Fatalf("%d: NextReader() returned %v, want %v", n, err, errUnexpectedEOF) } } } func TestEOFBeforeFinalFrame(t *testing.T) { const bufSize = 512 var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, 1024, bufSize) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, 1024, 1024) w, _ := wc.NextWriter(BinaryMessage) w.Write(make([]byte, bufSize+bufSize/2)) op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } _, err = io.Copy(ioutil.Discard, r) if err != errUnexpectedEOF { t.Fatalf("io.Copy() returned %v, want %v", err, errUnexpectedEOF) } _, _, err = rc.NextReader() if err != errUnexpectedEOF { t.Fatalf("NextReader() returned %v, want %v", err, errUnexpectedEOF) } } func TestWriteAfterMessageWriterClose(t *testing.T) { wc := newConn(fakeNetConn{Reader: nil, Writer: &bytes.Buffer{}}, false, 1024, 1024) w, _ := wc.NextWriter(BinaryMessage) io.WriteString(w, "hello") if err := w.Close(); err != nil { t.Fatalf("unxpected error closing message writer, %v", err) } if _, err := io.WriteString(w, "world"); err == nil { t.Fatalf("no error writing after close") } w, _ = wc.NextWriter(BinaryMessage) io.WriteString(w, "hello") // close w by getting next writer _, err := wc.NextWriter(BinaryMessage) if err != nil { t.Fatalf("unexpected error getting next writer, %v", err) } if _, err := io.WriteString(w, "world"); err == nil { t.Fatalf("no error writing after close") } } func TestReadLimit(t *testing.T) { const readLimit = 512 message := make([]byte, readLimit+1) var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, 1024, readLimit-2) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, 1024, 1024) rc.SetReadLimit(readLimit) // Send message at the limit with interleaved pong. w, _ := wc.NextWriter(BinaryMessage) w.Write(message[:readLimit-1]) wc.WriteControl(PongMessage, []byte("this is a pong"), time.Now().Add(10*time.Second)) w.Write(message[:1]) w.Close() // Send message larger than the limit. wc.WriteMessage(BinaryMessage, message[:readLimit+1]) op, _, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("1: NextReader() returned %d, %v", op, err) } op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("2: NextReader() returned %d, %v", op, err) } _, err = io.Copy(ioutil.Discard, r) if err != ErrReadLimit { t.Fatalf("io.Copy() returned %v", err) } } func TestAddrs(t *testing.T) { c := newConn(&fakeNetConn{}, true, 1024, 1024) if c.LocalAddr() != localAddr { t.Errorf("LocalAddr = %v, want %v", c.LocalAddr(), localAddr) } if c.RemoteAddr() != remoteAddr { t.Errorf("RemoteAddr = %v, want %v", c.RemoteAddr(), remoteAddr) } } func TestUnderlyingConn(t *testing.T) { var b1, b2 bytes.Buffer fc := fakeNetConn{Reader: &b1, Writer: &b2} c := newConn(fc, true, 1024, 1024) ul := c.UnderlyingConn() if ul != fc { t.Fatalf("Underlying conn is not what it should be.") } } func TestBufioReadBytes(t *testing.T) { // Test calling bufio.ReadBytes for value longer than read buffer size. m := make([]byte, 512) m[len(m)-1] = '\n' var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, len(m)+64, len(m)+64) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, len(m)-64, len(m)-64) w, _ := wc.NextWriter(BinaryMessage) w.Write(m) w.Close() op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } br := bufio.NewReader(r) p, err := br.ReadBytes('\n') if err != nil { t.Fatalf("ReadBytes() returned %v", err) } if len(p) != len(m) { t.Fatalf("read returnd %d bytes, want %d bytes", len(p), len(m)) } } var closeErrorTests = []struct { err error codes []int ok bool }{ {&CloseError{Code: CloseNormalClosure}, []int{CloseNormalClosure}, true}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived}, false}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived, CloseNormalClosure}, true}, {errors.New("hello"), []int{CloseNormalClosure}, false}, } func TestCloseError(t *testing.T) { for _, tt := range closeErrorTests { ok := IsCloseError(tt.err, tt.codes...) if ok != tt.ok { t.Errorf("IsCloseError(%#v, %#v) returned %v, want %v", tt.err, tt.codes, ok, tt.ok) } } } var unexpectedCloseErrorTests = []struct { err error codes []int ok bool }{ {&CloseError{Code: CloseNormalClosure}, []int{CloseNormalClosure}, false}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived}, true}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived, CloseNormalClosure}, false}, {errors.New("hello"), []int{CloseNormalClosure}, false}, } func TestUnexpectedCloseErrors(t *testing.T) { for _, tt := range unexpectedCloseErrorTests { ok := IsUnexpectedCloseError(tt.err, tt.codes...) if ok != tt.ok { t.Errorf("IsUnexpectedCloseError(%#v, %#v) returned %v, want %v", tt.err, tt.codes, ok, tt.ok) } } } type blockingWriter struct { c1, c2 chan struct{} } func (w blockingWriter) Write(p []byte) (int, error) { // Allow main to continue close(w.c1) // Wait for panic in main <-w.c2 return len(p), nil } func TestConcurrentWritePanic(t *testing.T) { w := blockingWriter{make(chan struct{}), make(chan struct{})} c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024) go func() { c.WriteMessage(TextMessage, []byte{}) }() // wait for goroutine to block in write. <-w.c1 defer func() { close(w.c2) if v := recover(); v != nil { return } }() c.WriteMessage(TextMessage, []byte{}) t.Fatal("should not get here") } type failingReader struct{} func (r failingReader) Read(p []byte) (int, error) { return 0, io.EOF } func TestFailedConnectionReadPanic(t *testing.T) { c := newConn(fakeNetConn{Reader: failingReader{}, Writer: nil}, false, 1024, 1024) defer func() { if v := recover(); v != nil { return } }() for i := 0; i < 20000; i++ { c.ReadMessage() } t.Fatal("should not get here") } func TestBufioReuse(t *testing.T) { brw := bufio.NewReadWriter(bufio.NewReader(nil), bufio.NewWriter(nil)) c := newConnBRW(nil, false, 0, 0, brw) if c.br != brw.Reader { t.Error("connection did not reuse bufio.Reader") } var wh writeHook brw.Writer.Reset(&wh) brw.WriteByte(0) brw.Flush() if &c.writeBuf[0] != &wh.p[0] { t.Error("connection did not reuse bufio.Writer") } brw = bufio.NewReadWriter(bufio.NewReaderSize(nil, 0), bufio.NewWriterSize(nil, 0)) c = newConnBRW(nil, false, 0, 0, brw) if c.br == brw.Reader { t.Error("connection used bufio.Reader with small size") } brw.Writer.Reset(&wh) brw.WriteByte(0) brw.Flush() if &c.writeBuf[0] != &wh.p[0] { t.Error("connection used bufio.Writer with small size") } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/conn_read_legacy.go��������������������������������0000644�0610621�0607500�00000000670�13172163304�026506� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.5 package websocket import "io" func (c *Conn) read(n int) ([]byte, error) { p, err := c.br.Peek(n) if err == io.EOF { err = errUnexpectedEOF } if len(p) > 0 { // advance over the bytes just read io.ReadFull(c.br, p) } return p, err } ������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/conn_read.go���������������������������������������0000644�0610621�0607500�00000000574�13172163304�025165� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.5 package websocket import "io" func (c *Conn) read(n int) ([]byte, error) { p, err := c.br.Peek(n) if err == io.EOF { err = errUnexpectedEOF } c.br.Discard(len(p)) return p, err } ������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/conn_broadcast_test.go�����������������������������0000644�0610621�0607500�00000006006�13172163304�027247� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package websocket import ( "io" "io/ioutil" "sync/atomic" "testing" ) // broadcastBench allows to run broadcast benchmarks. // In every broadcast benchmark we create many connections, then send the same // message into every connection and wait for all writes complete. This emulates // an application where many connections listen to the same data - i.e. PUB/SUB // scenarios with many subscribers in one channel. type broadcastBench struct { w io.Writer message *broadcastMessage closeCh chan struct{} doneCh chan struct{} count int32 conns []*broadcastConn compression bool usePrepared bool } type broadcastMessage struct { payload []byte prepared *PreparedMessage } type broadcastConn struct { conn *Conn msgCh chan *broadcastMessage } func newBroadcastConn(c *Conn) *broadcastConn { return &broadcastConn{ conn: c, msgCh: make(chan *broadcastMessage, 1), } } func newBroadcastBench(usePrepared, compression bool) *broadcastBench { bench := &broadcastBench{ w: ioutil.Discard, doneCh: make(chan struct{}), closeCh: make(chan struct{}), usePrepared: usePrepared, compression: compression, } msg := &broadcastMessage{ payload: textMessages(1)[0], } if usePrepared { pm, _ := NewPreparedMessage(TextMessage, msg.payload) msg.prepared = pm } bench.message = msg bench.makeConns(10000) return bench } func (b *broadcastBench) makeConns(numConns int) { conns := make([]*broadcastConn, numConns) for i := 0; i < numConns; i++ { c := newConn(fakeNetConn{Reader: nil, Writer: b.w}, true, 1024, 1024) if b.compression { c.enableWriteCompression = true c.newCompressionWriter = compressNoContextTakeover } conns[i] = newBroadcastConn(c) go func(c *broadcastConn) { for { select { case msg := <-c.msgCh: if b.usePrepared { c.conn.WritePreparedMessage(msg.prepared) } else { c.conn.WriteMessage(TextMessage, msg.payload) } val := atomic.AddInt32(&b.count, 1) if val%int32(numConns) == 0 { b.doneCh <- struct{}{} } case <-b.closeCh: return } } }(conns[i]) } b.conns = conns } func (b *broadcastBench) close() { close(b.closeCh) } func (b *broadcastBench) runOnce() { for _, c := range b.conns { c.msgCh <- b.message } <-b.doneCh } func BenchmarkBroadcast(b *testing.B) { benchmarks := []struct { name string usePrepared bool compression bool }{ {"NoCompression", false, false}, {"WithCompression", false, true}, {"NoCompressionPrepared", true, false}, {"WithCompressionPrepared", true, true}, } for _, bm := range benchmarks { b.Run(bm.name, func(b *testing.B) { bench := newBroadcastBench(bm.usePrepared, bm.compression) defer bench.close() b.ResetTimer() for i := 0; i < b.N; i++ { bench.runOnce() } b.ReportAllocs() }) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/conn.go��������������������������������������������0000644�0610621�0607500�00000073360�13172163304�024175� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "encoding/binary" "errors" "io" "io/ioutil" "math/rand" "net" "strconv" "sync" "time" "unicode/utf8" ) const ( // Frame header byte 0 bits from Section 5.2 of RFC 6455 finalBit = 1 << 7 rsv1Bit = 1 << 6 rsv2Bit = 1 << 5 rsv3Bit = 1 << 4 // Frame header byte 1 bits from Section 5.2 of RFC 6455 maskBit = 1 << 7 maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask maxControlFramePayloadSize = 125 writeWait = time.Second defaultReadBufferSize = 4096 defaultWriteBufferSize = 4096 continuationFrame = 0 noFrame = -1 ) // Close codes defined in RFC 6455, section 11.7. const ( CloseNormalClosure = 1000 CloseGoingAway = 1001 CloseProtocolError = 1002 CloseUnsupportedData = 1003 CloseNoStatusReceived = 1005 CloseAbnormalClosure = 1006 CloseInvalidFramePayloadData = 1007 ClosePolicyViolation = 1008 CloseMessageTooBig = 1009 CloseMandatoryExtension = 1010 CloseInternalServerErr = 1011 CloseServiceRestart = 1012 CloseTryAgainLater = 1013 CloseTLSHandshake = 1015 ) // The message types are defined in RFC 6455, section 11.8. const ( // TextMessage denotes a text data message. The text message payload is // interpreted as UTF-8 encoded text data. TextMessage = 1 // BinaryMessage denotes a binary data message. BinaryMessage = 2 // CloseMessage denotes a close control message. The optional message // payload contains a numeric code and text. Use the FormatCloseMessage // function to format a close message payload. CloseMessage = 8 // PingMessage denotes a ping control message. The optional message payload // is UTF-8 encoded text. PingMessage = 9 // PongMessage denotes a pong control message. The optional message payload // is UTF-8 encoded text. PongMessage = 10 ) // ErrCloseSent is returned when the application writes a message to the // connection after sending a close message. var ErrCloseSent = errors.New("websocket: close sent") // ErrReadLimit is returned when reading a message that is larger than the // read limit set for the connection. var ErrReadLimit = errors.New("websocket: read limit exceeded") // netError satisfies the net Error interface. type netError struct { msg string temporary bool timeout bool } func (e *netError) Error() string { return e.msg } func (e *netError) Temporary() bool { return e.temporary } func (e *netError) Timeout() bool { return e.timeout } // CloseError represents close frame. type CloseError struct { // Code is defined in RFC 6455, section 11.7. Code int // Text is the optional text payload. Text string } func (e *CloseError) Error() string { s := []byte("websocket: close ") s = strconv.AppendInt(s, int64(e.Code), 10) switch e.Code { case CloseNormalClosure: s = append(s, " (normal)"...) case CloseGoingAway: s = append(s, " (going away)"...) case CloseProtocolError: s = append(s, " (protocol error)"...) case CloseUnsupportedData: s = append(s, " (unsupported data)"...) case CloseNoStatusReceived: s = append(s, " (no status)"...) case CloseAbnormalClosure: s = append(s, " (abnormal closure)"...) case CloseInvalidFramePayloadData: s = append(s, " (invalid payload data)"...) case ClosePolicyViolation: s = append(s, " (policy violation)"...) case CloseMessageTooBig: s = append(s, " (message too big)"...) case CloseMandatoryExtension: s = append(s, " (mandatory extension missing)"...) case CloseInternalServerErr: s = append(s, " (internal server error)"...) case CloseTLSHandshake: s = append(s, " (TLS handshake error)"...) } if e.Text != "" { s = append(s, ": "...) s = append(s, e.Text...) } return string(s) } // IsCloseError returns boolean indicating whether the error is a *CloseError // with one of the specified codes. func IsCloseError(err error, codes ...int) bool { if e, ok := err.(*CloseError); ok { for _, code := range codes { if e.Code == code { return true } } } return false } // IsUnexpectedCloseError returns boolean indicating whether the error is a // *CloseError with a code not in the list of expected codes. func IsUnexpectedCloseError(err error, expectedCodes ...int) bool { if e, ok := err.(*CloseError); ok { for _, code := range expectedCodes { if e.Code == code { return false } } return true } return false } var ( errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true} errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()} errBadWriteOpCode = errors.New("websocket: bad write message type") errWriteClosed = errors.New("websocket: write closed") errInvalidControlFrame = errors.New("websocket: invalid control frame") ) func newMaskKey() [4]byte { n := rand.Uint32() return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} } func hideTempErr(err error) error { if e, ok := err.(net.Error); ok && e.Temporary() { err = &netError{msg: e.Error(), timeout: e.Timeout()} } return err } func isControl(frameType int) bool { return frameType == CloseMessage || frameType == PingMessage || frameType == PongMessage } func isData(frameType int) bool { return frameType == TextMessage || frameType == BinaryMessage } var validReceivedCloseCodes = map[int]bool{ // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number CloseNormalClosure: true, CloseGoingAway: true, CloseProtocolError: true, CloseUnsupportedData: true, CloseNoStatusReceived: false, CloseAbnormalClosure: false, CloseInvalidFramePayloadData: true, ClosePolicyViolation: true, CloseMessageTooBig: true, CloseMandatoryExtension: true, CloseInternalServerErr: true, CloseServiceRestart: true, CloseTryAgainLater: true, CloseTLSHandshake: false, } func isValidReceivedCloseCode(code int) bool { return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999) } // The Conn type represents a WebSocket connection. type Conn struct { conn net.Conn isServer bool subprotocol string // Write fields mu chan bool // used as mutex to protect write to conn writeBuf []byte // frame is constructed in this buffer. writeDeadline time.Time writer io.WriteCloser // the current writer returned to the application isWriting bool // for best-effort concurrent write detection writeErrMu sync.Mutex writeErr error enableWriteCompression bool compressionLevel int newCompressionWriter func(io.WriteCloser, int) io.WriteCloser // Read fields reader io.ReadCloser // the current reader returned to the application readErr error br *bufio.Reader readRemaining int64 // bytes remaining in current frame. readFinal bool // true the current message has more frames. readLength int64 // Message size. readLimit int64 // Maximum message size. readMaskPos int readMaskKey [4]byte handlePong func(string) error handlePing func(string) error handleClose func(int, string) error readErrCount int messageReader *messageReader // the current low-level reader readDecompress bool // whether last read frame had RSV1 set newDecompressionReader func(io.Reader) io.ReadCloser } func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int) *Conn { return newConnBRW(conn, isServer, readBufferSize, writeBufferSize, nil) } type writeHook struct { p []byte } func (wh *writeHook) Write(p []byte) (int, error) { wh.p = p return len(p), nil } func newConnBRW(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, brw *bufio.ReadWriter) *Conn { mu := make(chan bool, 1) mu <- true var br *bufio.Reader if readBufferSize == 0 && brw != nil && brw.Reader != nil { // Reuse the supplied bufio.Reader if the buffer has a useful size. // This code assumes that peek on a reader returns // bufio.Reader.buf[:0]. brw.Reader.Reset(conn) if p, err := brw.Reader.Peek(0); err == nil && cap(p) >= 256 { br = brw.Reader } } if br == nil { if readBufferSize == 0 { readBufferSize = defaultReadBufferSize } if readBufferSize < maxControlFramePayloadSize { readBufferSize = maxControlFramePayloadSize } br = bufio.NewReaderSize(conn, readBufferSize) } var writeBuf []byte if writeBufferSize == 0 && brw != nil && brw.Writer != nil { // Use the bufio.Writer's buffer if the buffer has a useful size. This // code assumes that bufio.Writer.buf[:1] is passed to the // bufio.Writer's underlying writer. var wh writeHook brw.Writer.Reset(&wh) brw.Writer.WriteByte(0) brw.Flush() if cap(wh.p) >= maxFrameHeaderSize+256 { writeBuf = wh.p[:cap(wh.p)] } } if writeBuf == nil { if writeBufferSize == 0 { writeBufferSize = defaultWriteBufferSize } writeBuf = make([]byte, writeBufferSize+maxFrameHeaderSize) } c := &Conn{ isServer: isServer, br: br, conn: conn, mu: mu, readFinal: true, writeBuf: writeBuf, enableWriteCompression: true, compressionLevel: defaultCompressionLevel, } c.SetCloseHandler(nil) c.SetPingHandler(nil) c.SetPongHandler(nil) return c } // Subprotocol returns the negotiated protocol for the connection. func (c *Conn) Subprotocol() string { return c.subprotocol } // Close closes the underlying network connection without sending or waiting for a close frame. func (c *Conn) Close() error { return c.conn.Close() } // LocalAddr returns the local network address. func (c *Conn) LocalAddr() net.Addr { return c.conn.LocalAddr() } // RemoteAddr returns the remote network address. func (c *Conn) RemoteAddr() net.Addr { return c.conn.RemoteAddr() } // Write methods func (c *Conn) writeFatal(err error) error { err = hideTempErr(err) c.writeErrMu.Lock() if c.writeErr == nil { c.writeErr = err } c.writeErrMu.Unlock() return err } func (c *Conn) write(frameType int, deadline time.Time, bufs ...[]byte) error { <-c.mu defer func() { c.mu <- true }() c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() if err != nil { return err } c.conn.SetWriteDeadline(deadline) for _, buf := range bufs { if len(buf) > 0 { _, err := c.conn.Write(buf) if err != nil { return c.writeFatal(err) } } } if frameType == CloseMessage { c.writeFatal(ErrCloseSent) } return nil } // WriteControl writes a control message with the given deadline. The allowed // message types are CloseMessage, PingMessage and PongMessage. func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error { if !isControl(messageType) { return errBadWriteOpCode } if len(data) > maxControlFramePayloadSize { return errInvalidControlFrame } b0 := byte(messageType) | finalBit b1 := byte(len(data)) if !c.isServer { b1 |= maskBit } buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize) buf = append(buf, b0, b1) if c.isServer { buf = append(buf, data...) } else { key := newMaskKey() buf = append(buf, key[:]...) buf = append(buf, data...) maskBytes(key, 0, buf[6:]) } d := time.Hour * 1000 if !deadline.IsZero() { d = deadline.Sub(time.Now()) if d < 0 { return errWriteTimeout } } timer := time.NewTimer(d) select { case <-c.mu: timer.Stop() case <-timer.C: return errWriteTimeout } defer func() { c.mu <- true }() c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() if err != nil { return err } c.conn.SetWriteDeadline(deadline) _, err = c.conn.Write(buf) if err != nil { return c.writeFatal(err) } if messageType == CloseMessage { c.writeFatal(ErrCloseSent) } return err } func (c *Conn) prepWrite(messageType int) error { // Close previous writer if not already closed by the application. It's // probably better to return an error in this situation, but we cannot // change this without breaking existing applications. if c.writer != nil { c.writer.Close() c.writer = nil } if !isControl(messageType) && !isData(messageType) { return errBadWriteOpCode } c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() return err } // NextWriter returns a writer for the next message to send. The writer's Close // method flushes the complete message to the network. // // There can be at most one open writer on a connection. NextWriter closes the // previous writer if the application has not already done so. // // All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and // PongMessage) are supported. func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) { if err := c.prepWrite(messageType); err != nil { return nil, err } mw := &messageWriter{ c: c, frameType: messageType, pos: maxFrameHeaderSize, } c.writer = mw if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) { w := c.newCompressionWriter(c.writer, c.compressionLevel) mw.compress = true c.writer = w } return c.writer, nil } type messageWriter struct { c *Conn compress bool // whether next call to flushFrame should set RSV1 pos int // end of data in writeBuf. frameType int // type of the current frame. err error } func (w *messageWriter) fatal(err error) error { if w.err != nil { w.err = err w.c.writer = nil } return err } // flushFrame writes buffered data and extra as a frame to the network. The // final argument indicates that this is the last frame in the message. func (w *messageWriter) flushFrame(final bool, extra []byte) error { c := w.c length := w.pos - maxFrameHeaderSize + len(extra) // Check for invalid control frames. if isControl(w.frameType) && (!final || length > maxControlFramePayloadSize) { return w.fatal(errInvalidControlFrame) } b0 := byte(w.frameType) if final { b0 |= finalBit } if w.compress { b0 |= rsv1Bit } w.compress = false b1 := byte(0) if !c.isServer { b1 |= maskBit } // Assume that the frame starts at beginning of c.writeBuf. framePos := 0 if c.isServer { // Adjust up if mask not included in the header. framePos = 4 } switch { case length >= 65536: c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | 127 binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length)) case length > 125: framePos += 6 c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | 126 binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length)) default: framePos += 8 c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | byte(length) } if !c.isServer { key := newMaskKey() copy(c.writeBuf[maxFrameHeaderSize-4:], key[:]) maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos]) if len(extra) > 0 { return c.writeFatal(errors.New("websocket: internal error, extra used in client mode")) } } // Write the buffers to the connection with best-effort detection of // concurrent writes. See the concurrency section in the package // documentation for more info. if c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = true err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra) if !c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = false if err != nil { return w.fatal(err) } if final { c.writer = nil return nil } // Setup for next frame. w.pos = maxFrameHeaderSize w.frameType = continuationFrame return nil } func (w *messageWriter) ncopy(max int) (int, error) { n := len(w.c.writeBuf) - w.pos if n <= 0 { if err := w.flushFrame(false, nil); err != nil { return 0, err } n = len(w.c.writeBuf) - w.pos } if n > max { n = max } return n, nil } func (w *messageWriter) Write(p []byte) (int, error) { if w.err != nil { return 0, w.err } if len(p) > 2*len(w.c.writeBuf) && w.c.isServer { // Don't buffer large messages. err := w.flushFrame(false, p) if err != nil { return 0, err } return len(p), nil } nn := len(p) for len(p) > 0 { n, err := w.ncopy(len(p)) if err != nil { return 0, err } copy(w.c.writeBuf[w.pos:], p[:n]) w.pos += n p = p[n:] } return nn, nil } func (w *messageWriter) WriteString(p string) (int, error) { if w.err != nil { return 0, w.err } nn := len(p) for len(p) > 0 { n, err := w.ncopy(len(p)) if err != nil { return 0, err } copy(w.c.writeBuf[w.pos:], p[:n]) w.pos += n p = p[n:] } return nn, nil } func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) { if w.err != nil { return 0, w.err } for { if w.pos == len(w.c.writeBuf) { err = w.flushFrame(false, nil) if err != nil { break } } var n int n, err = r.Read(w.c.writeBuf[w.pos:]) w.pos += n nn += int64(n) if err != nil { if err == io.EOF { err = nil } break } } return nn, err } func (w *messageWriter) Close() error { if w.err != nil { return w.err } if err := w.flushFrame(true, nil); err != nil { return err } w.err = errWriteClosed return nil } // WritePreparedMessage writes prepared message into connection. func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error { frameType, frameData, err := pm.frame(prepareKey{ isServer: c.isServer, compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType), compressionLevel: c.compressionLevel, }) if err != nil { return err } if c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = true err = c.write(frameType, c.writeDeadline, frameData, nil) if !c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = false return err } // WriteMessage is a helper method for getting a writer using NextWriter, // writing the message and closing the writer. func (c *Conn) WriteMessage(messageType int, data []byte) error { if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) { // Fast path with no allocations and single frame. if err := c.prepWrite(messageType); err != nil { return err } mw := messageWriter{c: c, frameType: messageType, pos: maxFrameHeaderSize} n := copy(c.writeBuf[mw.pos:], data) mw.pos += n data = data[n:] return mw.flushFrame(true, data) } w, err := c.NextWriter(messageType) if err != nil { return err } if _, err = w.Write(data); err != nil { return err } return w.Close() } // SetWriteDeadline sets the write deadline on the underlying network // connection. After a write has timed out, the websocket state is corrupt and // all future writes will return an error. A zero value for t means writes will // not time out. func (c *Conn) SetWriteDeadline(t time.Time) error { c.writeDeadline = t return nil } // Read methods func (c *Conn) advanceFrame() (int, error) { // 1. Skip remainder of previous frame. if c.readRemaining > 0 { if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil { return noFrame, err } } // 2. Read and parse first two bytes of frame header. p, err := c.read(2) if err != nil { return noFrame, err } final := p[0]&finalBit != 0 frameType := int(p[0] & 0xf) mask := p[1]&maskBit != 0 c.readRemaining = int64(p[1] & 0x7f) c.readDecompress = false if c.newDecompressionReader != nil && (p[0]&rsv1Bit) != 0 { c.readDecompress = true p[0] &^= rsv1Bit } if rsv := p[0] & (rsv1Bit | rsv2Bit | rsv3Bit); rsv != 0 { return noFrame, c.handleProtocolError("unexpected reserved bits 0x" + strconv.FormatInt(int64(rsv), 16)) } switch frameType { case CloseMessage, PingMessage, PongMessage: if c.readRemaining > maxControlFramePayloadSize { return noFrame, c.handleProtocolError("control frame length > 125") } if !final { return noFrame, c.handleProtocolError("control frame not final") } case TextMessage, BinaryMessage: if !c.readFinal { return noFrame, c.handleProtocolError("message start before final message frame") } c.readFinal = final case continuationFrame: if c.readFinal { return noFrame, c.handleProtocolError("continuation after final message frame") } c.readFinal = final default: return noFrame, c.handleProtocolError("unknown opcode " + strconv.Itoa(frameType)) } // 3. Read and parse frame length. switch c.readRemaining { case 126: p, err := c.read(2) if err != nil { return noFrame, err } c.readRemaining = int64(binary.BigEndian.Uint16(p)) case 127: p, err := c.read(8) if err != nil { return noFrame, err } c.readRemaining = int64(binary.BigEndian.Uint64(p)) } // 4. Handle frame masking. if mask != c.isServer { return noFrame, c.handleProtocolError("incorrect mask flag") } if mask { c.readMaskPos = 0 p, err := c.read(len(c.readMaskKey)) if err != nil { return noFrame, err } copy(c.readMaskKey[:], p) } // 5. For text and binary messages, enforce read limit and return. if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage { c.readLength += c.readRemaining if c.readLimit > 0 && c.readLength > c.readLimit { c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) return noFrame, ErrReadLimit } return frameType, nil } // 6. Read control frame payload. var payload []byte if c.readRemaining > 0 { payload, err = c.read(int(c.readRemaining)) c.readRemaining = 0 if err != nil { return noFrame, err } if c.isServer { maskBytes(c.readMaskKey, 0, payload) } } // 7. Process control frame payload. switch frameType { case PongMessage: if err := c.handlePong(string(payload)); err != nil { return noFrame, err } case PingMessage: if err := c.handlePing(string(payload)); err != nil { return noFrame, err } case CloseMessage: closeCode := CloseNoStatusReceived closeText := "" if len(payload) >= 2 { closeCode = int(binary.BigEndian.Uint16(payload)) if !isValidReceivedCloseCode(closeCode) { return noFrame, c.handleProtocolError("invalid close code") } closeText = string(payload[2:]) if !utf8.ValidString(closeText) { return noFrame, c.handleProtocolError("invalid utf8 payload in close frame") } } if err := c.handleClose(closeCode, closeText); err != nil { return noFrame, err } return noFrame, &CloseError{Code: closeCode, Text: closeText} } return frameType, nil } func (c *Conn) handleProtocolError(message string) error { c.WriteControl(CloseMessage, FormatCloseMessage(CloseProtocolError, message), time.Now().Add(writeWait)) return errors.New("websocket: " + message) } // NextReader returns the next data message received from the peer. The // returned messageType is either TextMessage or BinaryMessage. // // There can be at most one open reader on a connection. NextReader discards // the previous message if the application has not already consumed it. // // Applications must break out of the application's read loop when this method // returns a non-nil error value. Errors returned from this method are // permanent. Once this method returns a non-nil error, all subsequent calls to // this method return the same error. func (c *Conn) NextReader() (messageType int, r io.Reader, err error) { // Close previous reader, only relevant for decompression. if c.reader != nil { c.reader.Close() c.reader = nil } c.messageReader = nil c.readLength = 0 for c.readErr == nil { frameType, err := c.advanceFrame() if err != nil { c.readErr = hideTempErr(err) break } if frameType == TextMessage || frameType == BinaryMessage { c.messageReader = &messageReader{c} c.reader = c.messageReader if c.readDecompress { c.reader = c.newDecompressionReader(c.reader) } return frameType, c.reader, nil } } // Applications that do handle the error returned from this method spin in // tight loop on connection failure. To help application developers detect // this error, panic on repeated reads to the failed connection. c.readErrCount++ if c.readErrCount >= 1000 { panic("repeated read on failed websocket connection") } return noFrame, nil, c.readErr } type messageReader struct{ c *Conn } func (r *messageReader) Read(b []byte) (int, error) { c := r.c if c.messageReader != r { return 0, io.EOF } for c.readErr == nil { if c.readRemaining > 0 { if int64(len(b)) > c.readRemaining { b = b[:c.readRemaining] } n, err := c.br.Read(b) c.readErr = hideTempErr(err) if c.isServer { c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n]) } c.readRemaining -= int64(n) if c.readRemaining > 0 && c.readErr == io.EOF { c.readErr = errUnexpectedEOF } return n, c.readErr } if c.readFinal { c.messageReader = nil return 0, io.EOF } frameType, err := c.advanceFrame() switch { case err != nil: c.readErr = hideTempErr(err) case frameType == TextMessage || frameType == BinaryMessage: c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader") } } err := c.readErr if err == io.EOF && c.messageReader == r { err = errUnexpectedEOF } return 0, err } func (r *messageReader) Close() error { return nil } // ReadMessage is a helper method for getting a reader using NextReader and // reading from that reader to a buffer. func (c *Conn) ReadMessage() (messageType int, p []byte, err error) { var r io.Reader messageType, r, err = c.NextReader() if err != nil { return messageType, nil, err } p, err = ioutil.ReadAll(r) return messageType, p, err } // SetReadDeadline sets the read deadline on the underlying network connection. // After a read has timed out, the websocket connection state is corrupt and // all future reads will return an error. A zero value for t means reads will // not time out. func (c *Conn) SetReadDeadline(t time.Time) error { return c.conn.SetReadDeadline(t) } // SetReadLimit sets the maximum size for a message read from the peer. If a // message exceeds the limit, the connection sends a close frame to the peer // and returns ErrReadLimit to the application. func (c *Conn) SetReadLimit(limit int64) { c.readLimit = limit } // CloseHandler returns the current close handler func (c *Conn) CloseHandler() func(code int, text string) error { return c.handleClose } // SetCloseHandler sets the handler for close messages received from the peer. // The code argument to h is the received close code or CloseNoStatusReceived // if the close message is empty. The default close handler sends a close frame // back to the peer. // // The application must read the connection to process close messages as // described in the section on Control Frames above. // // The connection read methods return a CloseError when a close frame is // received. Most applications should handle close messages as part of their // normal error handling. Applications should only set a close handler when the // application must perform some action before sending a close frame back to // the peer. func (c *Conn) SetCloseHandler(h func(code int, text string) error) { if h == nil { h = func(code int, text string) error { message := []byte{} if code != CloseNoStatusReceived { message = FormatCloseMessage(code, "") } c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) return nil } } c.handleClose = h } // PingHandler returns the current ping handler func (c *Conn) PingHandler() func(appData string) error { return c.handlePing } // SetPingHandler sets the handler for ping messages received from the peer. // The appData argument to h is the PING frame application data. The default // ping handler sends a pong to the peer. // // The application must read the connection to process ping messages as // described in the section on Control Frames above. func (c *Conn) SetPingHandler(h func(appData string) error) { if h == nil { h = func(message string) error { err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) if err == ErrCloseSent { return nil } else if e, ok := err.(net.Error); ok && e.Temporary() { return nil } return err } } c.handlePing = h } // PongHandler returns the current pong handler func (c *Conn) PongHandler() func(appData string) error { return c.handlePong } // SetPongHandler sets the handler for pong messages received from the peer. // The appData argument to h is the PONG frame application data. The default // pong handler does nothing. // // The application must read the connection to process ping messages as // described in the section on Control Frames above. func (c *Conn) SetPongHandler(h func(appData string) error) { if h == nil { h = func(string) error { return nil } } c.handlePong = h } // UnderlyingConn returns the internal net.Conn. This can be used to further // modifications to connection specific flags. func (c *Conn) UnderlyingConn() net.Conn { return c.conn } // EnableWriteCompression enables and disables write compression of // subsequent text and binary messages. This function is a noop if // compression was not negotiated with the peer. func (c *Conn) EnableWriteCompression(enable bool) { c.enableWriteCompression = enable } // SetCompressionLevel sets the flate compression level for subsequent text and // binary messages. This function is a noop if compression was not negotiated // with the peer. See the compress/flate package for a description of // compression levels. func (c *Conn) SetCompressionLevel(level int) error { if !isValidCompressionLevel(level) { return errors.New("websocket: invalid compression level") } c.compressionLevel = level return nil } // FormatCloseMessage formats closeCode and text as a WebSocket close message. func FormatCloseMessage(closeCode int, text string) []byte { buf := make([]byte, 2+len(text)) binary.BigEndian.PutUint16(buf, uint16(closeCode)) copy(buf[2:], text) return buf } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/compression_test.go��������������������������������0000644�0610621�0607500�00000003631�13172163304�026632� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package websocket import ( "bytes" "fmt" "io" "io/ioutil" "testing" ) type nopCloser struct{ io.Writer } func (nopCloser) Close() error { return nil } func TestTruncWriter(t *testing.T) { const data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlkmnopqrstuvwxyz987654321" for n := 1; n <= 10; n++ { var b bytes.Buffer w := &truncWriter{w: nopCloser{&b}} p := []byte(data) for len(p) > 0 { m := len(p) if m > n { m = n } w.Write(p[:m]) p = p[m:] } if b.String() != data[:len(data)-len(w.p)] { t.Errorf("%d: %q", n, b.String()) } } } func textMessages(num int) [][]byte { messages := make([][]byte, num) for i := 0; i < num; i++ { msg := fmt.Sprintf("planet: %d, country: %d, city: %d, street: %d", i, i, i, i) messages[i] = []byte(msg) } return messages } func BenchmarkWriteNoCompression(b *testing.B) { w := ioutil.Discard c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024) messages := textMessages(100) b.ResetTimer() for i := 0; i < b.N; i++ { c.WriteMessage(TextMessage, messages[i%len(messages)]) } b.ReportAllocs() } func BenchmarkWriteWithCompression(b *testing.B) { w := ioutil.Discard c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024) messages := textMessages(100) c.enableWriteCompression = true c.newCompressionWriter = compressNoContextTakeover b.ResetTimer() for i := 0; i < b.N; i++ { c.WriteMessage(TextMessage, messages[i%len(messages)]) } b.ReportAllocs() } func TestValidCompressionLevel(t *testing.T) { c := newConn(fakeNetConn{}, false, 1024, 1024) for _, level := range []int{minCompressionLevel - 1, maxCompressionLevel + 1} { if err := c.SetCompressionLevel(level); err == nil { t.Errorf("no error for level %d", level) } } for _, level := range []int{minCompressionLevel, maxCompressionLevel} { if err := c.SetCompressionLevel(level); err != nil { t.Errorf("error for level %d", level) } } } �������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/compression.go�������������������������������������0000644�0610621�0607500�00000006170�13172163304�025574� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "compress/flate" "errors" "io" "strings" "sync" ) const ( minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6 maxCompressionLevel = flate.BestCompression defaultCompressionLevel = 1 ) var ( flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool flateReaderPool = sync.Pool{New: func() interface{} { return flate.NewReader(nil) }} ) func decompressNoContextTakeover(r io.Reader) io.ReadCloser { const tail = // Add four bytes as specified in RFC "\x00\x00\xff\xff" + // Add final block to squelch unexpected EOF error from flate reader. "\x01\x00\x00\xff\xff" fr, _ := flateReaderPool.Get().(io.ReadCloser) fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) return &flateReadWrapper{fr} } func isValidCompressionLevel(level int) bool { return minCompressionLevel <= level && level <= maxCompressionLevel } func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser { p := &flateWriterPools[level-minCompressionLevel] tw := &truncWriter{w: w} fw, _ := p.Get().(*flate.Writer) if fw == nil { fw, _ = flate.NewWriter(tw, level) } else { fw.Reset(tw) } return &flateWriteWrapper{fw: fw, tw: tw, p: p} } // truncWriter is an io.Writer that writes all but the last four bytes of the // stream to another io.Writer. type truncWriter struct { w io.WriteCloser n int p [4]byte } func (w *truncWriter) Write(p []byte) (int, error) { n := 0 // fill buffer first for simplicity. if w.n < len(w.p) { n = copy(w.p[w.n:], p) p = p[n:] w.n += n if len(p) == 0 { return n, nil } } m := len(p) if m > len(w.p) { m = len(w.p) } if nn, err := w.w.Write(w.p[:m]); err != nil { return n + nn, err } copy(w.p[:], w.p[m:]) copy(w.p[len(w.p)-m:], p[len(p)-m:]) nn, err := w.w.Write(p[:len(p)-m]) return n + nn, err } type flateWriteWrapper struct { fw *flate.Writer tw *truncWriter p *sync.Pool } func (w *flateWriteWrapper) Write(p []byte) (int, error) { if w.fw == nil { return 0, errWriteClosed } return w.fw.Write(p) } func (w *flateWriteWrapper) Close() error { if w.fw == nil { return errWriteClosed } err1 := w.fw.Flush() w.p.Put(w.fw) w.fw = nil if w.tw.p != [4]byte{0, 0, 0xff, 0xff} { return errors.New("websocket: internal error, unexpected bytes at end of flate stream") } err2 := w.tw.w.Close() if err1 != nil { return err1 } return err2 } type flateReadWrapper struct { fr io.ReadCloser } func (r *flateReadWrapper) Read(p []byte) (int, error) { if r.fr == nil { return 0, io.ErrClosedPipe } n, err := r.fr.Read(p) if err == io.EOF { // Preemptively place the reader back in the pool. This helps with // scenarios where the application does not call NextReader() soon after // this final read. r.Close() } return n, err } func (r *flateReadWrapper) Close() error { if r.fr == nil { return io.ErrClosedPipe } err := r.fr.Close() flateReaderPool.Put(r.fr) r.fr = nil return err } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/client_test.go�������������������������������������0000644�0610621�0607500�00000002060�13172163304�025542� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2014 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "net/url" "testing" ) var hostPortNoPortTests = []struct { u *url.URL hostPort, hostNoPort string }{ {&url.URL{Scheme: "ws", Host: "example.com"}, "example.com:80", "example.com"}, {&url.URL{Scheme: "wss", Host: "example.com"}, "example.com:443", "example.com"}, {&url.URL{Scheme: "ws", Host: "example.com:7777"}, "example.com:7777", "example.com"}, {&url.URL{Scheme: "wss", Host: "example.com:7777"}, "example.com:7777", "example.com"}, } func TestHostPortNoPort(t *testing.T) { for _, tt := range hostPortNoPortTests { hostPort, hostNoPort := hostPortNoPort(tt.u) if hostPort != tt.hostPort { t.Errorf("hostPortNoPort(%v) returned hostPort %q, want %q", tt.u, hostPort, tt.hostPort) } if hostNoPort != tt.hostNoPort { t.Errorf("hostPortNoPort(%v) returned hostNoPort %q, want %q", tt.u, hostNoPort, tt.hostNoPort) } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/client_server_test.go������������������������������0000644�0610621�0607500�00000025606�13172163304�027143� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "crypto/tls" "crypto/x509" "encoding/base64" "io" "io/ioutil" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "reflect" "strings" "testing" "time" ) var cstUpgrader = Upgrader{ Subprotocols: []string{"p0", "p1"}, ReadBufferSize: 1024, WriteBufferSize: 1024, EnableCompression: true, Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) { http.Error(w, reason.Error(), status) }, } var cstDialer = Dialer{ Subprotocols: []string{"p1", "p2"}, ReadBufferSize: 1024, WriteBufferSize: 1024, } type cstHandler struct{ *testing.T } type cstServer struct { *httptest.Server URL string } const ( cstPath = "/a/b" cstRawQuery = "x=y" cstRequestURI = cstPath + "?" + cstRawQuery ) func newServer(t *testing.T) *cstServer { var s cstServer s.Server = httptest.NewServer(cstHandler{t}) s.Server.URL += cstRequestURI s.URL = makeWsProto(s.Server.URL) return &s } func newTLSServer(t *testing.T) *cstServer { var s cstServer s.Server = httptest.NewTLSServer(cstHandler{t}) s.Server.URL += cstRequestURI s.URL = makeWsProto(s.Server.URL) return &s } func (t cstHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Path != cstPath { t.Logf("path=%v, want %v", r.URL.Path, cstPath) http.Error(w, "bad path", 400) return } if r.URL.RawQuery != cstRawQuery { t.Logf("query=%v, want %v", r.URL.RawQuery, cstRawQuery) http.Error(w, "bad path", 400) return } subprotos := Subprotocols(r) if !reflect.DeepEqual(subprotos, cstDialer.Subprotocols) { t.Logf("subprotols=%v, want %v", subprotos, cstDialer.Subprotocols) http.Error(w, "bad protocol", 400) return } ws, err := cstUpgrader.Upgrade(w, r, http.Header{"Set-Cookie": {"sessionID=1234"}}) if err != nil { t.Logf("Upgrade: %v", err) return } defer ws.Close() if ws.Subprotocol() != "p1" { t.Logf("Subprotocol() = %s, want p1", ws.Subprotocol()) ws.Close() return } op, rd, err := ws.NextReader() if err != nil { t.Logf("NextReader: %v", err) return } wr, err := ws.NextWriter(op) if err != nil { t.Logf("NextWriter: %v", err) return } if _, err = io.Copy(wr, rd); err != nil { t.Logf("NextWriter: %v", err) return } if err := wr.Close(); err != nil { t.Logf("Close: %v", err) return } } func makeWsProto(s string) string { return "ws" + strings.TrimPrefix(s, "http") } func sendRecv(t *testing.T, ws *Conn) { const message = "Hello World!" if err := ws.SetWriteDeadline(time.Now().Add(time.Second)); err != nil { t.Fatalf("SetWriteDeadline: %v", err) } if err := ws.WriteMessage(TextMessage, []byte(message)); err != nil { t.Fatalf("WriteMessage: %v", err) } if err := ws.SetReadDeadline(time.Now().Add(time.Second)); err != nil { t.Fatalf("SetReadDeadline: %v", err) } _, p, err := ws.ReadMessage() if err != nil { t.Fatalf("ReadMessage: %v", err) } if string(p) != message { t.Fatalf("message=%s, want %s", p, message) } } func TestProxyDial(t *testing.T) { s := newServer(t) defer s.Close() surl, _ := url.Parse(s.URL) cstDialer.Proxy = http.ProxyURL(surl) connect := false origHandler := s.Server.Config.Handler // Capture the request Host header. s.Server.Config.Handler = http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { if r.Method == "CONNECT" { connect = true w.WriteHeader(200) return } if !connect { t.Log("connect not recieved") http.Error(w, "connect not recieved", 405) return } origHandler.ServeHTTP(w, r) }) ws, _, err := cstDialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) cstDialer.Proxy = http.ProxyFromEnvironment } func TestProxyAuthorizationDial(t *testing.T) { s := newServer(t) defer s.Close() surl, _ := url.Parse(s.URL) surl.User = url.UserPassword("username", "password") cstDialer.Proxy = http.ProxyURL(surl) connect := false origHandler := s.Server.Config.Handler // Capture the request Host header. s.Server.Config.Handler = http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { proxyAuth := r.Header.Get("Proxy-Authorization") expectedProxyAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("username:password")) if r.Method == "CONNECT" && proxyAuth == expectedProxyAuth { connect = true w.WriteHeader(200) return } if !connect { t.Log("connect with proxy authorization not recieved") http.Error(w, "connect with proxy authorization not recieved", 405) return } origHandler.ServeHTTP(w, r) }) ws, _, err := cstDialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) cstDialer.Proxy = http.ProxyFromEnvironment } func TestDial(t *testing.T) { s := newServer(t) defer s.Close() ws, _, err := cstDialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func TestDialCookieJar(t *testing.T) { s := newServer(t) defer s.Close() jar, _ := cookiejar.New(nil) d := cstDialer d.Jar = jar u, _ := url.Parse(s.URL) switch u.Scheme { case "ws": u.Scheme = "http" case "wss": u.Scheme = "https" } cookies := []*http.Cookie{&http.Cookie{Name: "gorilla", Value: "ws", Path: "/"}} d.Jar.SetCookies(u, cookies) ws, _, err := d.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() var gorilla string var sessionID string for _, c := range d.Jar.Cookies(u) { if c.Name == "gorilla" { gorilla = c.Value } if c.Name == "sessionID" { sessionID = c.Value } } if gorilla != "ws" { t.Error("Cookie not present in jar.") } if sessionID != "1234" { t.Error("Set-Cookie not received from the server.") } sendRecv(t, ws) } func TestDialTLS(t *testing.T) { s := newTLSServer(t) defer s.Close() certs := x509.NewCertPool() for _, c := range s.TLS.Certificates { roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1]) if err != nil { t.Fatalf("error parsing server's root cert: %v", err) } for _, root := range roots { certs.AddCert(root) } } d := cstDialer d.TLSClientConfig = &tls.Config{RootCAs: certs} ws, _, err := d.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func xTestDialTLSBadCert(t *testing.T) { // This test is deactivated because of noisy logging from the net/http package. s := newTLSServer(t) defer s.Close() ws, _, err := cstDialer.Dial(s.URL, nil) if err == nil { ws.Close() t.Fatalf("Dial: nil") } } func TestDialTLSNoVerify(t *testing.T) { s := newTLSServer(t) defer s.Close() d := cstDialer d.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} ws, _, err := d.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func TestDialTimeout(t *testing.T) { s := newServer(t) defer s.Close() d := cstDialer d.HandshakeTimeout = -1 ws, _, err := d.Dial(s.URL, nil) if err == nil { ws.Close() t.Fatalf("Dial: nil") } } func TestDialBadScheme(t *testing.T) { s := newServer(t) defer s.Close() ws, _, err := cstDialer.Dial(s.Server.URL, nil) if err == nil { ws.Close() t.Fatalf("Dial: nil") } } func TestDialBadOrigin(t *testing.T) { s := newServer(t) defer s.Close() ws, resp, err := cstDialer.Dial(s.URL, http.Header{"Origin": {"bad"}}) if err == nil { ws.Close() t.Fatalf("Dial: nil") } if resp == nil { t.Fatalf("resp=nil, err=%v", err) } if resp.StatusCode != http.StatusForbidden { t.Fatalf("status=%d, want %d", resp.StatusCode, http.StatusForbidden) } } func TestDialBadHeader(t *testing.T) { s := newServer(t) defer s.Close() for _, k := range []string{"Upgrade", "Connection", "Sec-Websocket-Key", "Sec-Websocket-Version", "Sec-Websocket-Protocol"} { h := http.Header{} h.Set(k, "bad") ws, _, err := cstDialer.Dial(s.URL, http.Header{"Origin": {"bad"}}) if err == nil { ws.Close() t.Errorf("Dial with header %s returned nil", k) } } } func TestBadMethod(t *testing.T) { s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ws, err := cstUpgrader.Upgrade(w, r, nil) if err == nil { t.Errorf("handshake succeeded, expect fail") ws.Close() } })) defer s.Close() resp, err := http.PostForm(s.URL, url.Values{}) if err != nil { t.Fatalf("PostForm returned error %v", err) } resp.Body.Close() if resp.StatusCode != http.StatusMethodNotAllowed { t.Errorf("Status = %d, want %d", resp.StatusCode, http.StatusMethodNotAllowed) } } func TestHandshake(t *testing.T) { s := newServer(t) defer s.Close() ws, resp, err := cstDialer.Dial(s.URL, http.Header{"Origin": {s.URL}}) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() var sessionID string for _, c := range resp.Cookies() { if c.Name == "sessionID" { sessionID = c.Value } } if sessionID != "1234" { t.Error("Set-Cookie not received from the server.") } if ws.Subprotocol() != "p1" { t.Errorf("ws.Subprotocol() = %s, want p1", ws.Subprotocol()) } sendRecv(t, ws) } func TestRespOnBadHandshake(t *testing.T) { const expectedStatus = http.StatusGone const expectedBody = "This is the response body." s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(expectedStatus) io.WriteString(w, expectedBody) })) defer s.Close() ws, resp, err := cstDialer.Dial(makeWsProto(s.URL), nil) if err == nil { ws.Close() t.Fatalf("Dial: nil") } if resp == nil { t.Fatalf("resp=nil, err=%v", err) } if resp.StatusCode != expectedStatus { t.Errorf("resp.StatusCode=%d, want %d", resp.StatusCode, expectedStatus) } p, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatalf("ReadFull(resp.Body) returned error %v", err) } if string(p) != expectedBody { t.Errorf("resp.Body=%s, want %s", p, expectedBody) } } // TestHostHeader confirms that the host header provided in the call to Dial is // sent to the server. func TestHostHeader(t *testing.T) { s := newServer(t) defer s.Close() specifiedHost := make(chan string, 1) origHandler := s.Server.Config.Handler // Capture the request Host header. s.Server.Config.Handler = http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { specifiedHost <- r.Host origHandler.ServeHTTP(w, r) }) ws, _, err := cstDialer.Dial(s.URL, http.Header{"Host": {"testhost"}}) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() if gotHost := <-specifiedHost; gotHost != "testhost" { t.Fatalf("gotHost = %q, want \"testhost\"", gotHost) } sendRecv(t, ws) } func TestDialCompression(t *testing.T) { s := newServer(t) defer s.Close() dialer := cstDialer dialer.EnableCompression = true ws, _, err := dialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } ��������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/client_clone_legacy.go�����������������������������0000644�0610621�0607500�00000002533�13172163304�027214� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.8 package websocket import "crypto/tls" // cloneTLSConfig clones all public fields except the fields // SessionTicketsDisabled and SessionTicketKey. This avoids copying the // sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a // config in active use. func cloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return &tls.Config{ Rand: cfg.Rand, Time: cfg.Time, Certificates: cfg.Certificates, NameToCertificate: cfg.NameToCertificate, GetCertificate: cfg.GetCertificate, RootCAs: cfg.RootCAs, NextProtos: cfg.NextProtos, ServerName: cfg.ServerName, ClientAuth: cfg.ClientAuth, ClientCAs: cfg.ClientCAs, InsecureSkipVerify: cfg.InsecureSkipVerify, CipherSuites: cfg.CipherSuites, PreferServerCipherSuites: cfg.PreferServerCipherSuites, ClientSessionCache: cfg.ClientSessionCache, MinVersion: cfg.MinVersion, MaxVersion: cfg.MaxVersion, CurvePreferences: cfg.CurvePreferences, } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/client_clone.go������������������������������������0000644�0610621�0607500�00000000534�13172163304�025667� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.8 package websocket import "crypto/tls" func cloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return cfg.Clone() } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/client.go������������������������������������������0000644�0610621�0607500�00000023346�13172163304�024515� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "bytes" "crypto/tls" "encoding/base64" "errors" "io" "io/ioutil" "net" "net/http" "net/url" "strings" "time" ) // ErrBadHandshake is returned when the server response to opening handshake is // invalid. var ErrBadHandshake = errors.New("websocket: bad handshake") var errInvalidCompression = errors.New("websocket: invalid compression negotiation") // NewClient creates a new client connection using the given net connection. // The URL u specifies the host and request URI. Use requestHeader to specify // the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies // (Cookie). Use the response.Header to get the selected subprotocol // (Sec-WebSocket-Protocol) and cookies (Set-Cookie). // // If the WebSocket handshake fails, ErrBadHandshake is returned along with a // non-nil *http.Response so that callers can handle redirects, authentication, // etc. // // Deprecated: Use Dialer instead. func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) { d := Dialer{ ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize, NetDial: func(net, addr string) (net.Conn, error) { return netConn, nil }, } return d.Dial(u.String(), requestHeader) } // A Dialer contains options for connecting to WebSocket server. type Dialer struct { // NetDial specifies the dial function for creating TCP connections. If // NetDial is nil, net.Dial is used. NetDial func(network, addr string) (net.Conn, error) // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*http.Request) (*url.URL, error) // TLSClientConfig specifies the TLS configuration to use with tls.Client. // If nil, the default configuration is used. TLSClientConfig *tls.Config // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer // size is zero, then a useful default size is used. The I/O buffer sizes // do not limit the size of the messages that can be sent or received. ReadBufferSize, WriteBufferSize int // Subprotocols specifies the client's requested subprotocols. Subprotocols []string // EnableCompression specifies if the client should attempt to negotiate // per message compression (RFC 7692). Setting this value to true does not // guarantee that compression will be supported. Currently only "no context // takeover" modes are supported. EnableCompression bool // Jar specifies the cookie jar. // If Jar is nil, cookies are not sent in requests and ignored // in responses. Jar http.CookieJar } var errMalformedURL = errors.New("malformed ws or wss URL") func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) { hostPort = u.Host hostNoPort = u.Host if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") { hostNoPort = hostNoPort[:i] } else { switch u.Scheme { case "wss": hostPort += ":443" case "https": hostPort += ":443" default: hostPort += ":80" } } return hostPort, hostNoPort } // DefaultDialer is a dialer with all fields set to the default zero values. var DefaultDialer = &Dialer{ Proxy: http.ProxyFromEnvironment, } // Dial creates a new client connection. Use requestHeader to specify the // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). // Use the response.Header to get the selected subprotocol // (Sec-WebSocket-Protocol) and cookies (Set-Cookie). // // If the WebSocket handshake fails, ErrBadHandshake is returned along with a // non-nil *http.Response so that callers can handle redirects, authentication, // etcetera. The response body may not contain the entire response and does not // need to be closed by the application. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) { if d == nil { d = &Dialer{ Proxy: http.ProxyFromEnvironment, } } challengeKey, err := generateChallengeKey() if err != nil { return nil, nil, err } u, err := url.Parse(urlStr) if err != nil { return nil, nil, err } switch u.Scheme { case "ws": u.Scheme = "http" case "wss": u.Scheme = "https" default: return nil, nil, errMalformedURL } if u.User != nil { // User name and password are not allowed in websocket URIs. return nil, nil, errMalformedURL } req := &http.Request{ Method: "GET", URL: u, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), Host: u.Host, } // Set the cookies present in the cookie jar of the dialer if d.Jar != nil { for _, cookie := range d.Jar.Cookies(u) { req.AddCookie(cookie) } } // Set the request headers using the capitalization for names and values in // RFC examples. Although the capitalization shouldn't matter, there are // servers that depend on it. The Header.Set method is not used because the // method canonicalizes the header names. req.Header["Upgrade"] = []string{"websocket"} req.Header["Connection"] = []string{"Upgrade"} req.Header["Sec-WebSocket-Key"] = []string{challengeKey} req.Header["Sec-WebSocket-Version"] = []string{"13"} if len(d.Subprotocols) > 0 { req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")} } for k, vs := range requestHeader { switch { case k == "Host": if len(vs) > 0 { req.Host = vs[0] } case k == "Upgrade" || k == "Connection" || k == "Sec-Websocket-Key" || k == "Sec-Websocket-Version" || k == "Sec-Websocket-Extensions" || (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0): return nil, nil, errors.New("websocket: duplicate header not allowed: " + k) default: req.Header[k] = vs } } if d.EnableCompression { req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover") } hostPort, hostNoPort := hostPortNoPort(u) var proxyURL *url.URL // Check wether the proxy method has been configured if d.Proxy != nil { proxyURL, err = d.Proxy(req) } if err != nil { return nil, nil, err } var targetHostPort string if proxyURL != nil { targetHostPort, _ = hostPortNoPort(proxyURL) } else { targetHostPort = hostPort } var deadline time.Time if d.HandshakeTimeout != 0 { deadline = time.Now().Add(d.HandshakeTimeout) } netDial := d.NetDial if netDial == nil { netDialer := &net.Dialer{Deadline: deadline} netDial = netDialer.Dial } netConn, err := netDial("tcp", targetHostPort) if err != nil { return nil, nil, err } defer func() { if netConn != nil { netConn.Close() } }() if err := netConn.SetDeadline(deadline); err != nil { return nil, nil, err } if proxyURL != nil { connectHeader := make(http.Header) if user := proxyURL.User; user != nil { proxyUser := user.Username() if proxyPassword, passwordSet := user.Password(); passwordSet { credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword)) connectHeader.Set("Proxy-Authorization", "Basic "+credential) } } connectReq := &http.Request{ Method: "CONNECT", URL: &url.URL{Opaque: hostPort}, Host: hostPort, Header: connectHeader, } connectReq.Write(netConn) // Read response. // Okay to use and discard buffered reader here, because // TLS server will not speak until spoken to. br := bufio.NewReader(netConn) resp, err := http.ReadResponse(br, connectReq) if err != nil { return nil, nil, err } if resp.StatusCode != 200 { f := strings.SplitN(resp.Status, " ", 2) return nil, nil, errors.New(f[1]) } } if u.Scheme == "https" { cfg := cloneTLSConfig(d.TLSClientConfig) if cfg.ServerName == "" { cfg.ServerName = hostNoPort } tlsConn := tls.Client(netConn, cfg) netConn = tlsConn if err := tlsConn.Handshake(); err != nil { return nil, nil, err } if !cfg.InsecureSkipVerify { if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { return nil, nil, err } } } conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize) if err := req.Write(netConn); err != nil { return nil, nil, err } resp, err := http.ReadResponse(conn.br, req) if err != nil { return nil, nil, err } if d.Jar != nil { if rc := resp.Cookies(); len(rc) > 0 { d.Jar.SetCookies(u, rc) } } if resp.StatusCode != 101 || !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") || !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") || resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) { // Before closing the network connection on return from this // function, slurp up some of the response to aid application // debugging. buf := make([]byte, 1024) n, _ := io.ReadFull(resp.Body, buf) resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n])) return nil, resp, ErrBadHandshake } for _, ext := range parseExtensions(resp.Header) { if ext[""] != "permessage-deflate" { continue } _, snct := ext["server_no_context_takeover"] _, cnct := ext["client_no_context_takeover"] if !snct || !cnct { return nil, resp, errInvalidCompression } conn.newCompressionWriter = compressNoContextTakeover conn.newDecompressionReader = decompressNoContextTakeover break } resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol") netConn.SetDeadline(time.Time{}) netConn = nil // to avoid close in defer. return conn, resp, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/README.md������������������������������������������0000644�0610621�0607500�00000007524�13172163304�024167� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Gorilla WebSocket Gorilla WebSocket is a [Go](http://golang.org/) implementation of the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. [![Build Status](https://travis-ci.org/gorilla/websocket.svg?branch=master)](https://travis-ci.org/gorilla/websocket) [![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket) ### Documentation * [API Reference](http://godoc.org/github.com/gorilla/websocket) * [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat) * [Command example](https://github.com/gorilla/websocket/tree/master/examples/command) * [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo) * [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch) ### Status The Gorilla WebSocket package provides a complete and tested implementation of the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The package API is stable. ### Installation go get github.com/gorilla/websocket ### Protocol Compliance The Gorilla WebSocket package passes the server tests in the [Autobahn Test Suite](http://autobahn.ws/testsuite) using the application in the [examples/autobahn subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn). ### Gorilla WebSocket compared with other packages <table> <tr> <th></th> <th><a href="http://godoc.org/github.com/gorilla/websocket">github.com/gorilla</a></th> <th><a href="http://godoc.org/golang.org/x/net/websocket">golang.org/x/net</a></th> </tr> <tr> <tr><td colspan="3"><a href="http://tools.ietf.org/html/rfc6455">RFC 6455</a> Features</td></tr> <tr><td>Passes <a href="http://autobahn.ws/testsuite/">Autobahn Test Suite</a></td><td><a href="https://github.com/gorilla/websocket/tree/master/examples/autobahn">Yes</a></td><td>No</td></tr> <tr><td>Receive <a href="https://tools.ietf.org/html/rfc6455#section-5.4">fragmented</a> message<td>Yes</td><td><a href="https://code.google.com/p/go/issues/detail?id=7632">No</a>, see note 1</td></tr> <tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1">close</a> message</td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td><a href="https://code.google.com/p/go/issues/detail?id=4588">No</a></td></tr> <tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.2">pings</a> and receive <a href="https://tools.ietf.org/html/rfc6455#section-5.5.3">pongs</a></td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td>No</td></tr> <tr><td>Get the <a href="https://tools.ietf.org/html/rfc6455#section-5.6">type</a> of a received data message</td><td>Yes</td><td>Yes, see note 2</td></tr> <tr><td colspan="3">Other Features</tr></td> <tr><td><a href="https://tools.ietf.org/html/rfc7692">Compression Extensions</a></td><td>Experimental</td><td>No</td></tr> <tr><td>Read message using io.Reader</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextReader">Yes</a></td><td>No, see note 3</td></tr> <tr><td>Write message using io.WriteCloser</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextWriter">Yes</a></td><td>No, see note 3</td></tr> </table> Notes: 1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html). 2. The application can get the type of a received data message by implementing a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal) function. 3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries. Read returns when the input buffer is full or a frame boundary is encountered. Each call to Write sends a single frame message. The Gorilla io.Reader and io.WriteCloser operate on a single WebSocket message. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/LICENSE��������������������������������������������0000644�0610621�0607500�00000002440�13172163304�023705� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/AUTHORS��������������������������������������������0000644�0610621�0607500�00000000276�13172163304�023755� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This is the official list of Gorilla WebSocket authors for copyright # purposes. # # Please keep the list sorted. Gary Burd <gary@beagledreams.com> Joachim Bauch <mail@joachim-bauch.de> ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/gorilla/websocket/.travis.yml����������������������������������������0000644�0610621�0607500�00000000476�13172163304�025020� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go sudo: false matrix: include: - go: 1.4 - go: 1.5 - go: 1.6 - go: 1.7 - go: 1.8 - go: 1.9 - go: tip allow_failures: - go: tip script: - go get -t -v ./... - diff -u <(echo -n) <(gofmt -d .) - go vet $(go list ./... | grep -v /vendor/) - go test -v -race ./... ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/lxc/�����������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163435�020054� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/dist/src/github.com/lxc/lxd��������������������������������������������������������������0000777�0610621�0607500�00000000000�13172163435�021641� 2../../../../����������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/������������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014450� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/�����������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015764� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/template.sh������������������������������������������������������������������0000644�0610621�0607500�00000005542�13172163242�020141� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_template() { # shellcheck disable=2039 local lxd_backend lxd_backend=$(storage_backend "$LXD_DIR") # Import a template which only triggers on create deps/import-busybox --alias template-test --template create lxc init template-test template # Confirm that template application is delayed to first start ! lxc file pull template/template - # Validate that the template is applied lxc start template lxc file pull template/template - | grep "^name: template$" if [ "$lxd_backend" = "lvm" ]; then lxc stop template --force fi # Confirm it's not applied on copies lxc copy template template1 lxc file pull template1/template - | grep "^name: template$" # Cleanup lxc image delete template-test lxc delete template template1 --force # Import a template which only triggers on copy deps/import-busybox --alias template-test --template copy lxc launch template-test template # Confirm that the template doesn't trigger on create ! lxc file pull template/template - if [ "$lxd_backend" = "lvm" ]; then lxc stop template --force fi # Copy the container lxc copy template template1 # Confirm that template application is delayed to first start ! lxc file pull template1/template - # Validate that the template is applied lxc start template1 lxc file pull template1/template - | grep "^name: template1$" # Cleanup lxc image delete template-test lxc delete template template1 --force # Import a template which only triggers on start deps/import-busybox --alias template-test --template start lxc launch template-test template # Validate that the template is applied lxc file pull template/template - | grep "^name: template$" lxc file pull template/template - | grep "^user.foo: _unset_$" # Confirm it's re-run at every start lxc config set template user.foo bar lxc restart template --force lxc file pull template/template - | grep "^user.foo: bar$" # Cleanup lxc image delete template-test lxc delete template --force # Import a template which triggers on both create and copy deps/import-busybox --alias template-test --template create,copy lxc init template-test template # Confirm that template application is delayed to first start ! lxc file pull template/template - # Validate that the template is applied lxc start template lxc file pull template/template - | grep "^name: template$" # Confirm it's also applied on copies lxc copy template template1 lxc start template1 lxc file pull template1/template - | grep "^name: template1$" lxc file pull template1/template - | grep "^user.foo: _unset_$" # But doesn't change on restart lxc config set template1 user.foo bar lxc restart template1 --force lxc file pull template1/template - | grep "^user.foo: _unset_$" # Cleanup lxc image delete template-test lxc delete template template1 --force } ��������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/static_analysis.sh�����������������������������������������������������������0000644�0610621�0607500�00000005646�13172163242�021525� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������safe_pot_hash() { sed -e "/Project-Id-Version/,/Content-Transfer-Encoding/d" -e "/^#/d" "po/lxd.pot" | md5sum | cut -f1 -d" " } test_static_analysis() { ( set -e cd ../ # Python3 static analysis if which flake8 >/dev/null 2>&1; then flake8 test/deps/import-busybox scripts/lxd-setup-lvm-storage else echo "flake8 not found, python static analysis disabled" fi # Shell static analysis if which shellcheck >/dev/null 2>&1; then shellcheck --shell sh test/*.sh test/includes/*.sh test/suites/*.sh test/backends/*.sh else echo "shellcheck not found, shell static analysis disabled" fi # Go static analysis ## Functions starting by empty line OUT=$(grep -r "^$" -B1 . | grep "func " | grep -v "}$" || true) if [ -n "${OUT}" ]; then echo "ERROR: Functions must not start with an empty line: ${OUT}" false fi ## go vet, if it exists if go help vet >/dev/null 2>&1; then go vet ./... fi ## vet if which vet >/dev/null 2>&1; then vet --all . fi ## golint if which golint >/dev/null 2>&1; then golint -set_exit_status client/ golint -set_exit_status lxc/config/ golint -set_exit_status shared/api/ golint -set_exit_status shared/cmd/ golint -set_exit_status shared/gnuflag/ golint -set_exit_status shared/i18n/ golint -set_exit_status shared/ioprogress/ golint -set_exit_status shared/logger/ golint -set_exit_status shared/logging/ golint -set_exit_status shared/termios/ golint -set_exit_status shared/version/ golint -set_exit_status test/deps/ fi ## deadcode if which deadcode >/dev/null 2>&1; then OUT=$(deadcode ./ ./fuidshift ./lxc ./lxd ./lxd/types ./shared ./shared/api ./shared/i18n ./shared/ioprogress ./shared/logging ./shared/osarch ./shared/simplestreams ./shared/termios ./shared/version ./test/lxd-benchmark 2>&1 | grep -v lxd/migrate.pb.go: | grep -v /C: | grep -vi _cgo | grep -vi _cfunc || true) if [ -n "${OUT}" ]; then echo "${OUT}" >&2 false fi fi if which godeps >/dev/null 2>&1; then OUT=$(godeps -T ./client ./lxc/config ./shared/api 2>/dev/null | cut -f1 | diff -u test/godeps.list - || true) if [ -n "${OUT}" ]; then echo "ERROR: you added a new dependency to the client or shared; please make sure this is what you want" echo "${OUT}" exit 1 fi fi # Skip the tests which require git if ! git status; then return fi # go fmt git add -u :/ gofmt -w -s ./ git diff --exit-code # make sure the .pot is updated cp --preserve "po/lxd.pot" "po/lxd.pot.bak" hash1=$(safe_pot_hash) make i18n -s hash2=$(safe_pot_hash) mv "po/lxd.pot.bak" "po/lxd.pot" if [ "${hash1}" != "${hash2}" ]; then echo "==> Please update the .pot file in your commit (make i18n)" && false fi ) } ������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/snapshots.sh�����������������������������������������������������������������0000644�0610621�0607500�00000011460�13172163242�020344� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_snapshots() { ensure_import_testimage ensure_has_localhost_remote "${LXD_ADDR}" # shellcheck disable=2039 local lxd_backend lxd_backend=$(storage_backend "$LXD_DIR") lxc init testimage foo lxc snapshot foo # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ -d "${LXD_DIR}/snapshots/foo/snap0" ] fi lxc snapshot foo # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ -d "${LXD_DIR}/snapshots/foo/snap1" ] fi lxc snapshot foo tester # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ -d "${LXD_DIR}/snapshots/foo/tester" ] fi lxc copy foo/tester foosnap1 # FIXME: make this backend agnostic if [ "${lxd_backend}" != "lvm" ]; then [ -d "${LXD_DIR}/containers/foosnap1/rootfs" ] fi lxc delete foo/snap0 # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ ! -d "${LXD_DIR}/snapshots/foo/snap0" ] fi # no CLI for this, so we use the API directly (rename a snapshot) wait_for "${LXD_ADDR}" my_curl -X POST "https://${LXD_ADDR}/1.0/containers/foo/snapshots/tester" -d "{\"name\":\"tester2\"}" # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ ! -d "${LXD_DIR}/snapshots/foo/tester" ] fi lxc move foo/tester2 foo/tester-two lxc delete foo/tester-two # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ ! -d "${LXD_DIR}/snapshots/foo/tester-two" ] fi lxc snapshot foo namechange # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ -d "${LXD_DIR}/snapshots/foo/namechange" ] fi lxc move foo foople [ ! -d "${LXD_DIR}/containers/foo" ] [ -d "${LXD_DIR}/containers/foople" ] # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ -d "${LXD_DIR}/snapshots/foople/namechange" ] [ -d "${LXD_DIR}/snapshots/foople/namechange" ] fi lxc delete foople lxc delete foosnap1 [ ! -d "${LXD_DIR}/containers/foople" ] [ ! -d "${LXD_DIR}/containers/foosnap1" ] } test_snap_restore() { # shellcheck disable=2039 local lxd_backend lxd_backend=$(storage_backend "$LXD_DIR") ensure_import_testimage ensure_has_localhost_remote "${LXD_ADDR}" ########################################################## # PREPARATION ########################################################## ## create some state we will check for when snapshot is restored ## prepare snap0 lxc launch testimage bar echo snap0 > state lxc file push state bar/root/state lxc file push state bar/root/file_only_in_snap0 lxc exec bar -- mkdir /root/dir_only_in_snap0 lxc exec bar -- ln -s file_only_in_snap0 /root/statelink lxc stop bar --force lxc snapshot bar snap0 ## prepare snap1 lxc start bar echo snap1 > state lxc file push state bar/root/state lxc file push state bar/root/file_only_in_snap1 lxc exec bar -- rmdir /root/dir_only_in_snap0 lxc exec bar -- rm /root/file_only_in_snap0 lxc exec bar -- rm /root/statelink lxc exec bar -- ln -s file_only_in_snap1 /root/statelink lxc exec bar -- mkdir /root/dir_only_in_snap1 lxc stop bar --force # Delete the state file we created to prevent leaking. rm state lxc config set bar limits.cpu 1 lxc snapshot bar snap1 ########################################################## if [ "${lxd_backend}" != "zfs" ]; then # The problem here is that you can't `zfs rollback` to a snapshot with a # parent, which snap0 has (snap1). restore_and_compare_fs snap0 # Check container config has been restored (limits.cpu is unset) cpus=$(lxc config get bar limits.cpu) if [ -n "${cpus}" ]; then echo "==> config didn't match expected value after restore (${cpus})" false fi fi ########################################################## # test restore using full snapshot name restore_and_compare_fs snap1 # Check config value in snapshot has been restored cpus=$(lxc config get bar limits.cpu) if [ "${cpus}" != "1" ]; then echo "==> config didn't match expected value after restore (${cpus})" false fi ########################################################## # Start container and then restore snapshot to verify the running state after restore. lxc start bar if [ "${lxd_backend}" != "zfs" ]; then # see comment above about snap0 restore_and_compare_fs snap0 # check container is running after restore lxc list | grep bar | grep RUNNING fi lxc stop --force bar lxc delete bar } restore_and_compare_fs() { snap=${1} echo "==> Restoring ${snap}" lxc restore bar "${snap}" # FIXME: make this backend agnostic if [ "$(storage_backend "$LXD_DIR")" = "dir" ]; then # Recursive diff of container FS diff -r "${LXD_DIR}/containers/bar/rootfs" "${LXD_DIR}/snapshots/bar/${snap}/rootfs" fi } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/serverconfig.sh��������������������������������������������������������������0000644�0610621�0607500�00000001036�13172163242�021014� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_server_config() { LXD_SERVERCONFIG_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) spawn_lxd "${LXD_SERVERCONFIG_DIR}" ensure_has_localhost_remote "${LXD_ADDR}" lxc config set core.trust_password 123456 config=$(lxc config show) echo "${config}" | grep -q "trust_password" echo "${config}" | grep -q -v "123456" lxc config unset core.trust_password lxc config show | grep -q -v "trust_password" # test untrusted server GET my_curl -X GET "https://$(cat "${LXD_SERVERCONFIG_DIR}/lxd.addr")/1.0" | grep -v -q environment } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/security.sh������������������������������������������������������������������0000644�0610621�0607500�00000003111�13172163242�020163� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_security() { ensure_import_testimage ensure_has_localhost_remote "${LXD_ADDR}" # CVE-2016-1581 if [ "$(storage_backend "$LXD_DIR")" = "zfs" ]; then LXD_INIT_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD_INIT_DIR}" spawn_lxd "${LXD_INIT_DIR}" ZFS_POOL="lxdtest-$(basename "${LXD_DIR}")-init" LXD_DIR=${LXD_INIT_DIR} lxd init --storage-backend zfs --storage-create-loop 1 --storage-pool "${ZFS_POOL}" --auto PERM=$(stat -c %a "${LXD_INIT_DIR}/zfs.img") if [ "${PERM}" != "600" ]; then echo "Bad zfs.img permissions: ${PERM}" zpool destroy "${ZFS_POOL}" false fi zpool destroy "${ZFS_POOL}" kill_lxd "${LXD_INIT_DIR}" fi # CVE-2016-1582 lxc launch testimage test-priv -c security.privileged=true PERM=$(stat -L -c %a "${LXD_DIR}/containers/test-priv") if [ "${PERM}" != "700" ]; then echo "Bad container permissions: ${PERM}" false fi lxc config set test-priv security.privileged false lxc restart test-priv --force lxc config set test-priv security.privileged true lxc restart test-priv --force PERM=$(stat -L -c %a "${LXD_DIR}/containers/test-priv") if [ "${PERM}" != "700" ]; then echo "Bad container permissions: ${PERM}" false fi lxc delete test-priv --force lxc launch testimage test-unpriv lxc config set test-unpriv security.privileged true lxc restart test-unpriv --force PERM=$(stat -L -c %a "${LXD_DIR}/containers/test-unpriv") if [ "${PERM}" != "700" ]; then echo "Bad container permissions: ${PERM}" false fi lxc delete test-unpriv --force } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/remote.sh��������������������������������������������������������������������0000644�0610621�0607500�00000012207�13172163242�017615� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������gen_second_cert() { [ -f "${LXD_CONF}/client2.crt" ] && return mv "${LXD_CONF}/client.crt" "${LXD_CONF}/client.crt.bak" mv "${LXD_CONF}/client.key" "${LXD_CONF}/client.key.bak" lxc_remote list > /dev/null 2>&1 mv "${LXD_CONF}/client.crt" "${LXD_CONF}/client2.crt" mv "${LXD_CONF}/client.key" "${LXD_CONF}/client2.key" mv "${LXD_CONF}/client.crt.bak" "${LXD_CONF}/client.crt" mv "${LXD_CONF}/client.key.bak" "${LXD_CONF}/client.key" } test_remote_url() { # shellcheck disable=2153 for url in "${LXD_ADDR}" "https://${LXD_ADDR}"; do lxc_remote remote add test "${url}" --accept-certificate --password foo lxc_remote finger test: lxc_remote config trust list | grep @ | awk '{print $2}' | while read -r line ; do lxc_remote config trust remove "\"${line}\"" done lxc_remote remote remove test done # shellcheck disable=2153 urls="${LXD_DIR}/unix.socket unix:${LXD_DIR}/unix.socket unix://${LXD_DIR}/unix.socket" if [ -z "${LXD_OFFLINE:-}" ]; then urls="images.linuxcontainers.org https://images.linuxcontainers.org ${urls}" fi for url in ${urls}; do lxc_remote remote add test "${url}" lxc_remote remote remove test done } test_remote_admin() { lxc_remote remote add badpass "${LXD_ADDR}" --accept-certificate --password bad || true ! lxc_remote list badpass: lxc_remote remote add localhost "${LXD_ADDR}" --accept-certificate --password foo lxc_remote remote list | grep 'localhost' lxc_remote remote set-default localhost [ "$(lxc_remote remote get-default)" = "localhost" ] lxc_remote remote rename localhost foo lxc_remote remote list | grep 'foo' lxc_remote remote list | grep -v 'localhost' [ "$(lxc_remote remote get-default)" = "foo" ] ! lxc_remote remote remove foo lxc_remote remote set-default local lxc_remote remote remove foo # This is a test for #91, we expect this to hang asking for a password if we # tried to re-add our cert. echo y | lxc_remote remote add localhost "${LXD_ADDR}" # we just re-add our cert under a different name to test the cert # manipulation mechanism. gen_second_cert # Test for #623 lxc_remote remote add test-623 "${LXD_ADDR}" --accept-certificate --password foo # now re-add under a different alias lxc_remote config trust add "${LXD_CONF}/client2.crt" if [ "$(lxc_remote config trust list | wc -l)" -ne 7 ]; then echo "wrong number of certs" false fi # Check that we can add domains with valid certs without confirmation: # avoid default high port behind some proxies: if [ -z "${LXD_OFFLINE:-}" ]; then lxc_remote remote add images1 images.linuxcontainers.org lxc_remote remote add images2 images.linuxcontainers.org:443 fi } test_remote_usage() { # shellcheck disable=2039 local LXD2_DIR LXD2_ADDR LXD2_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD2_DIR}" spawn_lxd "${LXD2_DIR}" LXD2_ADDR=$(cat "${LXD2_DIR}/lxd.addr") ensure_import_testimage ensure_has_localhost_remote "${LXD_ADDR}" lxc_remote remote add lxd2 "${LXD2_ADDR}" --accept-certificate --password foo # we need a public image on localhost lxc_remote image export localhost:testimage "${LXD_DIR}/foo" lxc_remote image delete localhost:testimage sum=$(sha256sum "${LXD_DIR}/foo.tar.xz" | cut -d' ' -f1) lxc_remote image import "${LXD_DIR}/foo.tar.xz" localhost: --public lxc_remote image alias create localhost:testimage "${sum}" lxc_remote image delete "lxd2:${sum}" || true lxc_remote image copy localhost:testimage lxd2: --copy-aliases --public lxc_remote image delete "localhost:${sum}" lxc_remote image copy "lxd2:${sum}" local: --copy-aliases --public lxc_remote image info localhost:testimage lxc_remote image delete "lxd2:${sum}" lxc_remote image copy "localhost:${sum}" lxd2: lxc_remote image delete "lxd2:${sum}" lxc_remote image copy "localhost:$(echo "${sum}" | colrm 3)" lxd2: lxc_remote image delete "lxd2:${sum}" # test a private image lxc_remote image copy "localhost:${sum}" lxd2: lxc_remote image delete "localhost:${sum}" lxc_remote init "lxd2:${sum}" localhost:c1 lxc_remote delete localhost:c1 lxc_remote image alias create localhost:testimage "${sum}" # test remote publish lxc_remote init testimage pub lxc_remote publish pub lxd2: --alias bar --public a=b lxc_remote image show lxd2:bar | grep -q "a: b" lxc_remote image show lxd2:bar | grep -q "public: true" ! lxc_remote image show bar lxc_remote delete pub # test spawn from public server lxc_remote remote add lxd2-public "${LXD2_ADDR}" --public --accept-certificate lxc_remote init lxd2-public:bar pub lxc_remote image delete lxd2:bar lxc_remote delete pub # Double launch to test if the image downloads only once. lxc_remote init localhost:testimage lxd2:c1 & C1PID=$! lxc_remote init localhost:testimage lxd2:c2 lxc_remote delete lxd2:c2 wait "${C1PID}" lxc_remote delete lxd2:c1 # launch testimage stored on localhost as container c1 on lxd2 lxc_remote launch localhost:testimage lxd2:c1 # make sure it is running lxc_remote list lxd2: | grep c1 | grep RUNNING lxc_remote info lxd2:c1 lxc_remote stop lxd2:c1 --force lxc_remote delete lxd2:c1 kill_lxd "$LXD2_DIR" } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/profiling.sh�����������������������������������������������������������������0000644�0610621�0607500�00000002103�13172163242�020305� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_cpu_profiling() { LXD3_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD3_DIR}" spawn_lxd "${LXD3_DIR}" --cpuprofile "${LXD3_DIR}/cpu.out" lxdpid=$(cat "${LXD3_DIR}/lxd.pid") kill -TERM "${lxdpid}" wait "${lxdpid}" || true export PPROF_TMPDIR="${TEST_DIR}/pprof" echo top5 | go tool pprof "$(which lxd)" "${LXD3_DIR}/cpu.out" echo "" # Cleanup following manual kill rm -f "${LXD3_DIR}/unix.socket" find "${LXD3_DIR}" -name shmounts -exec "umount" "-l" "{}" \; >/dev/null 2>&1 || true kill_lxd "${LXD3_DIR}" } test_mem_profiling() { LXD4_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD4_DIR}" spawn_lxd "${LXD4_DIR}" --memprofile "${LXD4_DIR}/mem" lxdpid=$(cat "${LXD4_DIR}/lxd.pid") if [ -e "${LXD4_DIR}/mem" ]; then false fi kill -USR1 "${lxdpid}" timeout=50 while [ "${timeout}" != "0" ]; do [ -e "${LXD4_DIR}/mem" ] && break sleep 0.1 timeout=$((timeout-1)) done export PPROF_TMPDIR="${TEST_DIR}/pprof" echo top5 | go tool pprof "$(which lxd)" "${LXD4_DIR}/mem" echo "" kill_lxd "${LXD4_DIR}" } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/migration.sh�����������������������������������������������������������������0000644�0610621�0607500�00000006331�13172163242�020314� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_migration() { # setup a second LXD # shellcheck disable=2039 local LXD2_DIR LXD2_ADDR lxd_backend # shellcheck disable=2153 lxd_backend=$(storage_backend "$LXD_DIR") LXD2_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD2_DIR}" spawn_lxd "${LXD2_DIR}" LXD2_ADDR=$(cat "${LXD2_DIR}/lxd.addr") # shellcheck disable=2153 lxd2_backend=$(storage_backend "$LXD2_DIR") ensure_import_testimage if ! lxc_remote remote list | grep -q l1; then # shellcheck disable=2153 lxc_remote remote add l1 "${LXD_ADDR}" --accept-certificate --password foo fi if ! lxc_remote remote list | grep -q l2; then lxc_remote remote add l2 "${LXD2_ADDR}" --accept-certificate --password foo fi lxc_remote init testimage nonlive # test moving snapshots lxc_remote config set l1:nonlive user.tester foo lxc_remote snapshot l1:nonlive lxc_remote config unset l1:nonlive user.tester lxc_remote move l1:nonlive l2: lxc_remote config show l2:nonlive/snap0 | grep user.tester | grep foo # This line exists so that the container's storage volume is mounted when we # perform existence check for various files. lxc_remote start l2:nonlive # FIXME: make this backend agnostic if [ "${lxd2_backend}" != "lvm" ]; then [ -d "${LXD2_DIR}/containers/nonlive/rootfs" ] fi lxc_remote stop l2:nonlive [ ! -d "${LXD_DIR}/containers/nonlive" ] # FIXME: make this backend agnostic if [ "${lxd2_backend}" = "dir" ]; then [ -d "${LXD2_DIR}/snapshots/nonlive/snap0/rootfs/bin" ] fi lxc_remote copy l2:nonlive l1:nonlive2 [ -d "${LXD_DIR}/containers/nonlive2" ] # FIXME: make this backend agnostic if [ "${lxd2_backend}" != "lvm" ]; then [ -d "${LXD2_DIR}/containers/nonlive/rootfs/bin" ] fi # FIXME: make this backend agnostic if [ "${lxd_backend}" = "dir" ]; then [ -d "${LXD_DIR}/snapshots/nonlive2/snap0/rootfs/bin" ] fi lxc_remote copy l1:nonlive2/snap0 l2:nonlive3 # FIXME: make this backend agnostic if [ "${lxd2_backend}" != "lvm" ]; then [ -d "${LXD2_DIR}/containers/nonlive3/rootfs/bin" ] fi lxc_remote delete l2:nonlive3 --force lxc_remote copy l2:nonlive l2:nonlive2 # should have the same base image tag [ "$(lxc_remote config get l2:nonlive volatile.base_image)" = "$(lxc_remote config get l2:nonlive2 volatile.base_image)" ] # check that nonlive2 has a new addr in volatile [ "$(lxc_remote config get l2:nonlive volatile.eth0.hwaddr)" != "$(lxc_remote config get l2:nonlive2 volatile.eth0.hwaddr)" ] lxc_remote config unset l2:nonlive volatile.base_image lxc_remote copy l2:nonlive l1:nobase lxc_remote delete l1:nobase lxc_remote start l1:nonlive2 lxc_remote list l1: | grep RUNNING | grep nonlive2 lxc_remote delete l1:nonlive2 l2:nonlive2 --force lxc_remote start l2:nonlive lxc_remote list l2: | grep RUNNING | grep nonlive lxc_remote delete l2:nonlive --force if ! which criu >/dev/null 2>&1; then kill_lxd "$LXD2_DIR" echo "==> SKIP: live migration with CRIU (missing binary)" return fi lxc_remote launch testimage l1:migratee # let the container do some interesting things sleep 1s lxc_remote stop --stateful l1:migratee lxc_remote start l1:migratee lxc_remote delete --force l1:migratee kill_lxd "$LXD2_DIR" } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/init_interactive.sh����������������������������������������������������������0000644�0610621�0607500�00000000526�13172163242�021663� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_init_interactive() { # - lxd init LXD_INIT_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD_INIT_DIR}" spawn_lxd "${LXD_INIT_DIR}" ( set -e # shellcheck disable=SC2034 LXD_DIR=${LXD_INIT_DIR} cat <<EOF | lxd init dir no no EOF lxc profile delete default ) kill_lxd "${LXD_INIT_DIR}" return } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/init_auto.sh�����������������������������������������������������������������0000644�0610621�0607500�00000004346�13172163242�020322� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_init_auto() { # - lxd init --auto --storage-backend zfs # and # - lxd init --auto # can't be easily tested on jenkins since it hard-codes "default" as pool # naming. This can cause naming conflicts when multiple test-suites are run on # a single runner. if [ "$(storage_backend "$LXD_DIR")" = "zfs" ]; then # lxd init --auto --storage-backend zfs --storage-pool <name> LXD_INIT_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD_INIT_DIR}" spawn_lxd "${LXD_INIT_DIR}" configure_loop_device loop_file_1 loop_device_1 # shellcheck disable=SC2154 zpool create "lxdtest-$(basename "${LXD_DIR}")-pool1-existing-pool" "${loop_device_1}" -m none -O compression=on LXD_DIR=${LXD_INIT_DIR} lxd init --auto --storage-backend zfs --storage-pool "lxdtest-$(basename "${LXD_DIR}")-pool1-existing-pool" kill_lxd "${LXD_INIT_DIR}" zpool destroy "lxdtest-$(basename "${LXD_DIR}")-pool1-existing-pool" sed -i "\|^${loop_device_1}|d" "${TEST_DIR}/loops" # lxd init --auto --storage-backend zfs --storage-pool <name>/<existing-dataset> LXD_INIT_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD_INIT_DIR}" spawn_lxd "${LXD_INIT_DIR}" configure_loop_device loop_file_1 loop_device_1 # shellcheck disable=SC2154 zpool create "lxdtest-$(basename "${LXD_DIR}")-pool1-existing-pool" "${loop_device_1}" -m none -O compression=on zfs create -p -o mountpoint=none "lxdtest-$(basename "${LXD_DIR}")-pool1-existing-pool/existing-dataset" LXD_DIR=${LXD_INIT_DIR} lxd init --auto --storage-backend zfs --storage-pool "lxdtest-$(basename "${LXD_DIR}")-pool1-existing-pool/existing-dataset" kill_lxd "${LXD_INIT_DIR}" zpool destroy "lxdtest-$(basename "${LXD_DIR}")-pool1-existing-pool" sed -i "\|^${loop_device_1}|d" "${TEST_DIR}/loops" # lxd init --storage-backend zfs --storage-create-loop 1 --storage-pool <name> --auto LXD_INIT_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD_INIT_DIR}" spawn_lxd "${LXD_INIT_DIR}" ZFS_POOL="lxdtest-$(basename "${LXD_DIR}")-init" LXD_DIR=${LXD_INIT_DIR} lxd init --storage-backend zfs --storage-create-loop 1 --storage-pool "${ZFS_POOL}" --auto kill_lxd "${LXD_INIT_DIR}" zpool destroy "${ZFS_POOL}" fi } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/image_auto_update.sh���������������������������������������������������������0000644�0610621�0607500�00000004212�13172163242�021773� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_image_auto_update() { if lxc image alias list | grep -q "^| testimage\s*|.*$"; then lxc image delete testimage fi # shellcheck disable=2039 local LXD2_DIR LXD2_ADDR LXD2_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD2_DIR}" spawn_lxd "${LXD2_DIR}" LXD2_ADDR=$(cat "${LXD2_DIR}/lxd.addr") (LXD_DIR=${LXD2_DIR} deps/import-busybox --alias testimage --public) fp1=$(LXD_DIR=${LXD2_DIR} lxc image info testimage | awk -F: '/^Fingerprint/ { print $2 }' | awk '{ print $1 }') lxc remote add l2 "${LXD2_ADDR}" --accept-certificate --password foo lxc init l2:testimage c1 # Now the first image image is in the local store, since it was # downloaded to create c1. alias=$(lxc image info "${fp1}" | awk -F: '/^ Alias/ { print $2 }' | awk '{ print $1 }') [ "${alias}" = "testimage" ] # Delete the first image from the remote store and replace it with a # new one with a different fingerprint (passing "--template create" # will do that). (LXD_DIR=${LXD2_DIR} lxc image delete testimage) (LXD_DIR=${LXD2_DIR} deps/import-busybox --alias testimage --public --template create) fp2=$(LXD_DIR=${LXD2_DIR} lxc image info testimage | awk -F: '/^Fingerprint/ { print $2 }' | awk '{ print $1 }') [ "${fp1}" != "${fp2}" ] # Restart the server to force an image refresh immediately # shellcheck disable=2153 shutdown_lxd "${LXD_DIR}" respawn_lxd "${LXD_DIR}" # Check that the first image got deleted from the local storage # # XXX: Since the auto-update logic runs asynchronously we need to wait # a little bit before it actually completes. retries=600 while [ "${retries}" != "0" ]; do if lxc image info "${fp1}" > /dev/null 2>&1; then sleep 2 retries=$((retries-1)) continue fi break done if [ "${retries}" -eq 0 ]; then echo "First image ${fp1} not deleted from local store" return 1 fi # The second image replaced the first one in the local storage. alias=$(lxc image info "${fp2}" | awk -F: '/^ Alias/ { print $2 }' | awk '{ print $1 }') [ "${alias}" = "testimage" ] lxc delete c1 lxc remote remove l2 lxc image delete "${fp2}" kill_lxd "$LXD2_DIR" } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/image.sh���������������������������������������������������������������������0000644�0610621�0607500�00000003304�13172163242�017402� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_image_expiry() { # shellcheck disable=2039 local LXD2_DIR LXD2_ADDR LXD2_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD2_DIR}" spawn_lxd "${LXD2_DIR}" LXD2_ADDR=$(cat "${LXD2_DIR}/lxd.addr") ensure_import_testimage if ! lxc_remote remote list | grep -q l1; then # shellcheck disable=2153 lxc_remote remote add l1 "${LXD_ADDR}" --accept-certificate --password foo fi if ! lxc_remote remote list | grep -q l2; then lxc_remote remote add l2 "${LXD2_ADDR}" --accept-certificate --password foo fi # Create a container from a remote image lxc_remote init l1:testimage l2:c1 fp=$(lxc_remote image info testimage | awk -F: '/^Fingerprint/ { print $2 }' | awk '{ print $1 }') # Confirm the image is cached [ ! -z "${fp}" ] fpbrief=$(echo "${fp}" | cut -c 1-10) lxc_remote image list l2: | grep -q "${fpbrief}" # Override the upload date sqlite3 "${LXD2_DIR}/lxd.db" "UPDATE images SET last_use_date='$(date --rfc-3339=seconds -u -d "2 days ago")' WHERE fingerprint='${fp}'" # Trigger the expiry lxc_remote config set l2: images.remote_cache_expiry 1 sleep 5 ! lxc_remote image list l2: | grep -q "${fpbrief}" || false # Cleanup and reset lxc_remote delete l2:c1 lxc_remote config set l2: images.remote_cache_expiry 10 lxc_remote remote remove l2 kill_lxd "$LXD2_DIR" } test_image_import_existing_alias() { ensure_import_testimage lxc init testimage c lxc publish c --alias newimage --alias image2 lxc delete c lxc image export testimage testimage.file lxc image delete testimage # the image can be imported with an existing alias lxc image import testimage.file --alias newimage lxc image delete newimage image2 } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/idmap.sh���������������������������������������������������������������������0000644�0610621�0607500�00000022630�13172163242�017415� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_idmap() { # Check that we have a big enough range for this test if [ ! -e /etc/subuid ] && [ ! -e /etc/subgid ]; then UIDs=1000000000 GIDs=1000000000 UID_BASE=1000000 GID_BASE=1000000 else UIDs=0 GIDs=0 UID_BASE=0 GID_BASE=0 LARGEST_UIDs=0 LARGEST_GIDs=0 # shellcheck disable=SC2013 for entry in $(grep ^root: /etc/subuid); do COUNT=$(echo "${entry}" | cut -d: -f3) UIDs=$((UIDs+COUNT)) if [ "${COUNT}" -gt "${LARGEST_UIDs}" ]; then LARGEST_UIDs=${COUNT} UID_BASE=$(echo "${entry}" | cut -d: -f2) fi done # shellcheck disable=SC2013 for entry in $(grep ^root: /etc/subgid); do COUNT=$(echo "${entry}" | cut -d: -f3) GIDs=$((GIDs+COUNT)) if [ "${COUNT}" -gt "${LARGEST_GIDs}" ]; then LARGEST_GIDs=${COUNT} GID_BASE=$(echo "${entry}" | cut -d: -f2) fi done fi if [ "${UIDs}" -lt 500000 ] || [ "${GIDs}" -lt 500000 ]; then echo "==> SKIP: The idmap test requires at least 500000 uids and gids" return fi # Setup daemon ensure_import_testimage # Check a normal, non-isolated container (full LXD id range) lxc launch testimage idmap [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $2}')" = "${UID_BASE}" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $2}')" = "${GID_BASE}" ] [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $3}')" = "${UIDs}" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $3}')" = "${GIDs}" ] # Confirm that we don't allow double mappings ! echo "uid $((UID_BASE+1)) 1000" | lxc config set idmap raw.idmap - || false ! echo "gid $((GID_BASE+1)) 1000" | lxc config set idmap raw.idmap - || false # Convert container to isolated and confirm it's not using the first range lxc config set idmap security.idmap.isolated true lxc restart idmap --force [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $2}')" = "$((UID_BASE+65536))" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $2}')" = "$((GID_BASE+65536))" ] [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $3}')" = "65536" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $3}')" = "65536" ] # Bump allocation size lxc config set idmap security.idmap.size 100000 lxc restart idmap --force [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $2}')" != "${UID_BASE}" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $2}')" != "${GID_BASE}" ] [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $3}')" = "100000" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $3}')" = "100000" ] # Test using a custom base lxc config set idmap security.idmap.base $((UID_BASE+12345)) lxc config set idmap security.idmap.size 110000 lxc restart idmap --force [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $2}')" = "$((UID_BASE+12345))" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $2}')" = "$((GID_BASE+12345))" ] [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $3}')" = "110000" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $3}')" = "110000" ] # Switch back to full LXD range lxc config unset idmap security.idmap.base lxc config unset idmap security.idmap.isolated lxc config unset idmap security.idmap.size lxc restart idmap --force [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $2}')" = "${UID_BASE}" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $2}')" = "${GID_BASE}" ] [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $3}')" = "${UIDs}" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $3}')" = "${GIDs}" ] lxc delete idmap --force # Confirm id recycling lxc launch testimage idmap -c security.idmap.isolated=true [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $2}')" = "$((UID_BASE+65536))" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $2}')" = "$((GID_BASE+65536))" ] [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $3}')" = "65536" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $3}')" = "65536" ] # Copy and check that the base differs lxc copy idmap idmap1 lxc start idmap1 [ "$(lxc exec idmap1 -- cat /proc/self/uid_map | awk '{print $2}')" = "$((UID_BASE+131072))" ] [ "$(lxc exec idmap1 -- cat /proc/self/gid_map | awk '{print $2}')" = "$((GID_BASE+131072))" ] [ "$(lxc exec idmap1 -- cat /proc/self/uid_map | awk '{print $3}')" = "65536" ] [ "$(lxc exec idmap1 -- cat /proc/self/gid_map | awk '{print $3}')" = "65536" ] # Validate non-overlapping maps lxc exec idmap -- touch /a ! lxc exec idmap -- chown 65536 /a lxc exec idmap -- chown 65535 /a PID_1=$(lxc info idmap | grep ^Pid | awk '{print $2}') UID_1=$(stat -c '%u' "/proc/${PID_1}/root/a") lxc exec idmap1 -- touch /a PID_2=$(lxc info idmap1 | grep ^Pid | awk '{print $2}') UID_2=$(stat -c '%u' "/proc/${PID_2}/root/a") [ "${UID_1}" != "${UID_2}" ] [ "${UID_2}" = "$((UID_1+1))" ] # Check profile inheritance lxc profile create idmap lxc profile set idmap security.idmap.isolated true lxc profile set idmap security.idmap.size 100000 lxc launch testimage idmap2 [ "$(lxc exec idmap2 -- cat /proc/self/uid_map | awk '{print $2}')" = "${UID_BASE}" ] [ "$(lxc exec idmap2 -- cat /proc/self/gid_map | awk '{print $2}')" = "${GID_BASE}" ] [ "$(lxc exec idmap2 -- cat /proc/self/uid_map | awk '{print $3}')" = "${UIDs}" ] [ "$(lxc exec idmap2 -- cat /proc/self/gid_map | awk '{print $3}')" = "${GIDs}" ] lxc profile apply idmap default,idmap lxc profile apply idmap1 default,idmap lxc profile apply idmap2 default,idmap lxc restart idmap idmap1 idmap2 --force lxc launch testimage idmap3 -p default -p idmap UID_1=$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $2}') GID_1=$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $2}') [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $2}')" != "${UID_BASE}" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $2}')" != "${GID_BASE}" ] [ "$(lxc exec idmap -- cat /proc/self/uid_map | awk '{print $3}')" = "100000" ] [ "$(lxc exec idmap -- cat /proc/self/gid_map | awk '{print $3}')" = "100000" ] UID_2=$(lxc exec idmap1 -- cat /proc/self/uid_map | awk '{print $2}') GID_2=$(lxc exec idmap1 -- cat /proc/self/gid_map | awk '{print $2}') [ "$(lxc exec idmap1 -- cat /proc/self/uid_map | awk '{print $2}')" != "${UID_BASE}" ] [ "$(lxc exec idmap1 -- cat /proc/self/gid_map | awk '{print $2}')" != "${GID_BASE}" ] [ "$(lxc exec idmap1 -- cat /proc/self/uid_map | awk '{print $3}')" = "100000" ] [ "$(lxc exec idmap1 -- cat /proc/self/gid_map | awk '{print $3}')" = "100000" ] UID_3=$(lxc exec idmap2 -- cat /proc/self/uid_map | awk '{print $2}') GID_3=$(lxc exec idmap2 -- cat /proc/self/gid_map | awk '{print $2}') [ "$(lxc exec idmap2 -- cat /proc/self/uid_map | awk '{print $2}')" != "${UID_BASE}" ] [ "$(lxc exec idmap2 -- cat /proc/self/gid_map | awk '{print $2}')" != "${GID_BASE}" ] [ "$(lxc exec idmap2 -- cat /proc/self/uid_map | awk '{print $3}')" = "100000" ] [ "$(lxc exec idmap2 -- cat /proc/self/gid_map | awk '{print $3}')" = "100000" ] UID_4=$(lxc exec idmap3 -- cat /proc/self/uid_map | awk '{print $2}') GID_4=$(lxc exec idmap3 -- cat /proc/self/gid_map | awk '{print $2}') [ "$(lxc exec idmap3 -- cat /proc/self/uid_map | awk '{print $2}')" != "${UID_BASE}" ] [ "$(lxc exec idmap3 -- cat /proc/self/gid_map | awk '{print $2}')" != "${GID_BASE}" ] [ "$(lxc exec idmap3 -- cat /proc/self/uid_map | awk '{print $3}')" = "100000" ] [ "$(lxc exec idmap3 -- cat /proc/self/gid_map | awk '{print $3}')" = "100000" ] [ "${UID_1}" != "${UID_2}" ] [ "${UID_1}" != "${UID_3}" ] [ "${UID_1}" != "${UID_4}" ] [ "${UID_2}" != "${UID_3}" ] [ "${UID_2}" != "${UID_4}" ] [ "${UID_3}" != "${UID_4}" ] [ "${GID_1}" != "${GID_2}" ] [ "${GID_1}" != "${GID_3}" ] [ "${GID_1}" != "${GID_4}" ] [ "${GID_2}" != "${GID_3}" ] [ "${GID_2}" != "${GID_4}" ] [ "${UID_3}" != "${UID_4}" ] lxc delete idmap1 idmap2 idmap3 --force # Test running out of ids ! lxc launch testimage idmap1 -c security.idmap.isolated=true -c security.idmap.size=$((UIDs+1)) # Test raw id maps ( cat << EOF uid ${UID_BASE} 1000000 gid $((GID_BASE+1)) 1000000 both $((UID_BASE+2)) 2000000 EOF ) | lxc config set idmap raw.idmap - lxc restart idmap --force PID=$(lxc info idmap | grep ^Pid | awk '{print $2}') lxc exec idmap -- touch /a lxc exec idmap -- chown 1000000:1000000 /a [ "$(stat -c '%u:%g' "/proc/${PID}/root/a")" = "${UID_BASE}:$((GID_BASE+1))" ] lxc exec idmap -- touch /b lxc exec idmap -- chown 2000000:2000000 /b [ "$(stat -c '%u:%g' "/proc/${PID}/root/b")" = "$((UID_BASE+2)):$((GID_BASE+2))" ] # Test id ranges ( cat << EOF uid $((UID_BASE+10))-$((UID_BASE+19)) 3000000-3000009 gid $((GID_BASE+10))-$((GID_BASE+19)) 3000000-3000009 both $((GID_BASE+20))-$((GID_BASE+29)) 4000000-4000009 EOF ) | lxc config set idmap raw.idmap - lxc restart idmap --force PID=$(lxc info idmap | grep ^Pid | awk '{print $2}') lxc exec idmap -- touch /c lxc exec idmap -- chown 3000009:3000009 /c [ "$(stat -c '%u:%g' "/proc/${PID}/root/c")" = "$((UID_BASE+19)):$((GID_BASE+19))" ] lxc exec idmap -- touch /d lxc exec idmap -- chown 4000009:4000009 /d [ "$(stat -c '%u:%g' "/proc/${PID}/root/d")" = "$((UID_BASE+29)):$((GID_BASE+29))" ] lxc delete idmap --force } ��������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/fuidshift.sh�����������������������������������������������������������������0000644�0610621�0607500�00000003043�13172163242�020305� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_common_fuidshift() { # test some bad arguments fail=0 fuidshift > /dev/null 2>&1 && fail=1 fuidshift -t > /dev/null 2>&1 && fail=1 fuidshift /tmp -t b:0 > /dev/null 2>&1 && fail=1 fuidshift /tmp -t x:0:0:0 > /dev/null 2>&1 && fail=1 [ "${fail}" -ne 1 ] } test_nonroot_fuidshift() { test_common_fuidshift LXD_FUIDMAP_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) u=$(id -u) g=$(id -g) u1=$((u+1)) g1=$((g+1)) touch "${LXD_FUIDMAP_DIR}/x1" fuidshift "${LXD_FUIDMAP_DIR}/x1" -t "u:${u}:100000:1" "g:${g}:100000:1" | tee /dev/stderr | grep "to 100000 100000" > /dev/null || fail=1 if [ "${fail}" -eq 1 ]; then echo "==> Failed to shift own uid to container root" false fi fuidshift "${LXD_FUIDMAP_DIR}/x1" -t "u:${u1}:10000:1" "g:${g1}:100000:1" | tee /dev/stderr | grep "to -1 -1" > /dev/null || fail=1 if [ "${fail}" -eq 1 ]; then echo "==> Wrongly shifted invalid uid to container root" false fi # unshift it chown 100000:100000 "${LXD_FUIDMAP_DIR}/x1" fuidshift "${LXD_FUIDMAP_DIR}/x1" -r -t "u:${u}:100000:1" "g:${g}:100000:1" | tee /dev/stderr | grep "to 0 0" > /dev/null || fail=1 if [ "${fail}" -eq 1 ]; then echo "==> Failed to unshift container root back to own uid" false fi } test_root_fuidshift() { test_nonroot_fuidshift # Todo - test ranges } test_fuidshift() { if ! which fuidshift >/dev/null 2>&1; then echo "==> SKIP: No fuidshift binary could be found" return fi if [ "$(id -u)" -ne 0 ]; then test_nonroot_fuidshift else test_root_fuidshift fi } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/filemanip.sh�����������������������������������������������������������������0000644�0610621�0607500�00000001507�13172163242�020267� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_filemanip() { # Workaround for shellcheck getting confused by "cd" set -e ensure_import_testimage ensure_has_localhost_remote "${LXD_ADDR}" echo "test" > "${TEST_DIR}"/filemanip lxc launch testimage filemanip lxc exec filemanip -- ln -s /tmp/ /tmp/outside lxc file push "${TEST_DIR}"/filemanip filemanip/tmp/outside/ [ ! -f /tmp/filemanip ] lxc exec filemanip -- ls /tmp/filemanip # missing files should return 404 err=$(my_curl -o /dev/null -w "%{http_code}" -X GET "https://${LXD_ADDR}/1.0/containers/filemanip/files?path=/tmp/foo") [ "${err}" -eq "404" ] lxc delete filemanip -f if [ "$(storage_backend "$LXD_DIR")" != "lvm" ]; then lxc launch testimage idmap -c "raw.idmap=\"both 0 0\"" [ "$(stat -c %u "${LXD_DIR}/containers/idmap/rootfs")" = "0" ] lxc delete idmap --force fi } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/fdleak.sh��������������������������������������������������������������������0000644�0610621�0607500�00000001666�13172163242�017557� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_fdleak() { LXD_FDLEAK_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD_FDLEAK_DIR}" spawn_lxd "${LXD_FDLEAK_DIR}" pid=$(cat "${LXD_FDLEAK_DIR}/lxd.pid") beforefds=$(/bin/ls "/proc/${pid}/fd" | wc -l) ( set -e # shellcheck disable=SC2034 LXD_DIR=${LXD_FDLEAK_DIR} ensure_import_testimage for i in $(seq 5); do lxc init "testimage leaktest${i}" lxc info "leaktest${i}" lxc start "leaktest${i}" lxc exec "leaktest${i}" -- ps -ef lxc stop "leaktest${i}" --force lxc delete "leaktest${i}" done sleep 5 exit 0 ) afterfds=$(/bin/ls "/proc/${pid}/fd" | wc -l) leakedfds=$((afterfds - beforefds)) bad=0 # shellcheck disable=SC2015 [ ${leakedfds} -gt 5 ] && bad=1 || true if [ ${bad} -eq 1 ]; then echo "${leakedfds} FDS leaked" ls "/proc/${pid}/fd" -al netstat -anp 2>&1 | grep "${pid}/" false fi kill_lxd "${LXD_FDLEAK_DIR}" } ��������������������������������������������������������������������������lxd-2.0.11/test/suites/exec.sh����������������������������������������������������������������������0000644�0610621�0607500�00000001040�13172163242�017237� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_concurrent_exec() { if [ -z "${LXD_CONCURRENT:-}" ]; then echo "==> SKIP: LXD_CONCURRENT isn't set" return fi ensure_import_testimage name=x1 lxc launch testimage x1 lxc list ${name} | grep RUNNING exec_container() { echo "abc${1}" | lxc exec "${name}" -- cat | grep abc } PIDS="" for i in $(seq 1 50); do exec_container "${i}" > "${LXD_DIR}/exec-${i}.out" 2>&1 & PIDS="${PIDS} $!" done for pid in ${PIDS}; do wait "${pid}" done lxc stop "${name}" --force lxc delete "${name}" } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/devlxd.sh��������������������������������������������������������������������0000644�0610621�0607500�00000000712�13172163242�017606� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_devlxd() { ensure_import_testimage # shellcheck disable=SC2164 cd "${TEST_DIR}" go build -tags netgo -a -installsuffix devlxd ../deps/devlxd-client.go # shellcheck disable=SC2164 cd - lxc launch testimage devlxd lxc file push "${TEST_DIR}/devlxd-client" devlxd/bin/ lxc exec devlxd chmod +x /bin/devlxd-client lxc config set devlxd user.foo bar lxc exec devlxd devlxd-client user.foo | grep bar lxc delete devlxd --force } ������������������������������������������������������lxd-2.0.11/test/suites/deps.sh����������������������������������������������������������������������0000644�0610621�0607500�00000000107�13172163242�017251� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_check_deps() { ! ldd "$(which lxc)" | grep -q liblxc || false } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/database_update.sh�����������������������������������������������������������0000644�0610621�0607500�00000001731�13172163242�021430� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_database_update(){ LXD_MIGRATE_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) MIGRATE_DB=${LXD_MIGRATE_DIR}/lxd.db # Create the version 1 schema as the database sqlite3 "${MIGRATE_DB}" > /dev/null < deps/schema1.sql # Start an LXD demon in the tmp directory. This should start the updates. spawn_lxd "${LXD_MIGRATE_DIR}" # Assert there are enough tables. expected_tables=17 tables=$(sqlite3 "${MIGRATE_DB}" ".dump" | grep -c "CREATE TABLE") [ "${tables}" -eq "${expected_tables}" ] || { echo "FAIL: Wrong number of tables after database migration. Found: ${tables}, expected ${expected_tables}"; false; } # There should be 10 "ON DELETE CASCADE" occurrences expected_cascades=11 cascades=$(sqlite3 "${MIGRATE_DB}" ".dump" | grep -c "ON DELETE CASCADE") [ "${cascades}" -eq "${expected_cascades}" ] || { echo "FAIL: Wrong number of ON DELETE CASCADE foreign keys. Found: ${cascades}, exected: ${expected_cascades}"; false; } kill_lxd "$LXD_MIGRATE_DIR" } ���������������������������������������lxd-2.0.11/test/suites/config.sh��������������������������������������������������������������������0000644�0610621�0607500�00000014434�13172163242�017573� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ensure_removed() { bad=0 lxc exec foo -- stat /dev/ttyS0 && bad=1 if [ "${bad}" -eq 1 ]; then echo "device should have been removed; $*" false fi } dounixdevtest() { lxc start foo lxc config device add foo tty unix-char "$@" lxc exec foo -- stat /dev/ttyS0 lxc restart foo lxc exec foo -- stat /dev/ttyS0 lxc restart foo --force lxc exec foo -- stat /dev/ttyS0 lxc config device remove foo tty ensure_removed "was not hot-removed" lxc restart foo ensure_removed "removed device re-appeared after container reboot" lxc restart foo --force ensure_removed "removed device re-appaared after lxc reboot" lxc stop foo --force } testunixdevs() { echo "Testing passing char device /dev/ttyS0" dounixdevtest path=/dev/ttyS0 echo "Testing passing char device 4 64" dounixdevtest path=/dev/ttyS0 major=4 minor=64 } ensure_fs_unmounted() { bad=0 lxc exec foo -- stat /mnt/hello && bad=1 if [ "${bad}" -eq 1 ]; then echo "device should have been removed; $*" false fi } testloopmounts() { loopfile=$(mktemp -p "${TEST_DIR}" loop_XXX) dd if=/dev/zero of="${loopfile}" bs=1M seek=200 count=1 mkfs.ext4 -F "${loopfile}" lpath=$(losetup --show -f "${loopfile}") if [ ! -e "${lpath}" ]; then echo "failed to setup loop" false fi echo "${lpath}" >> "${TEST_DIR}/loops" mkdir -p "${TEST_DIR}/mnt" mount "${lpath}" "${TEST_DIR}/mnt" || { echo "loop mount failed"; return; } touch "${TEST_DIR}/mnt/hello" umount -l "${TEST_DIR}/mnt" lxc start foo lxc config device add foo mnt disk source="${lpath}" path=/mnt lxc exec foo stat /mnt/hello # Note - we need to add a set_running_config_item to lxc # or work around its absence somehow. Once that's done, we # can run the following two lines: #lxc exec foo reboot #lxc exec foo stat /mnt/hello lxc restart foo --force lxc exec foo stat /mnt/hello lxc config device remove foo mnt ensure_fs_unmounted "fs should have been hot-unmounted" lxc restart foo ensure_fs_unmounted "removed fs re-appeared after reboot" lxc restart foo --force ensure_fs_unmounted "removed fs re-appeared after restart" lxc stop foo --force losetup -d "${lpath}" sed -i "\|^${lpath}|d" "${TEST_DIR}/loops" } test_mount_order() { mkdir -p "${TEST_DIR}/order/empty" mkdir -p "${TEST_DIR}/order/full" touch "${TEST_DIR}/order/full/filler" # The idea here is that sometimes (depending on how golang randomizes the # config) the empty dir will have the contents of full in it, but sometimes # it won't depending on whether the devices below are processed in order or # not. This should not be racy, and they should *always* be processed in path # order, so the filler file should always be there. lxc config device add foo order disk source="${TEST_DIR}/order" path=/mnt lxc config device add foo orderFull disk source="${TEST_DIR}/order/full" path=/mnt/empty lxc start foo lxc exec foo -- cat /mnt/empty/filler lxc stop foo --force } test_config_profiles() { ensure_import_testimage lxc init testimage foo lxc profile list | grep default # let's check that 'lxc config profile' still works while it's deprecated lxc config profile list | grep default # setting an invalid config item should error out when setting it, not get # into the database and never let the user edit the container again. ! lxc config set foo raw.lxc lxc.notaconfigkey=invalid lxc profile create stdintest echo "BADCONF" | lxc profile set stdintest user.user_data - lxc profile show stdintest | grep BADCONF lxc profile delete stdintest echo "BADCONF" | lxc config set foo user.user_data - lxc config show foo | grep BADCONF lxc config unset foo user.user_data mkdir -p "${TEST_DIR}/mnt1" lxc config device add foo mnt1 disk source="${TEST_DIR}/mnt1" path=/mnt1 readonly=true lxc profile create onenic lxc profile device add onenic eth0 nic nictype=bridged parent=lxdbr0 lxc profile apply foo onenic lxc profile create unconfined lxc profile set unconfined raw.lxc "lxc.aa_profile=unconfined" lxc profile apply foo onenic,unconfined lxc config device list foo | grep mnt1 lxc config device show foo | grep "/mnt1" lxc config show foo | grep "onenic" -A1 | grep "unconfined" lxc profile list | grep onenic lxc profile device list onenic | grep eth0 lxc profile device show onenic | grep lxdbr0 # test live-adding a nic lxc start foo lxc exec foo -- cat /proc/self/mountinfo | grep -q "/mnt1.*ro," ! lxc config show foo | grep -q "raw.lxc" || false lxc config show foo --expanded | grep -q "raw.lxc" ! lxc config show foo | grep -v "volatile.eth0" | grep -q "eth0" || false lxc config show foo --expanded | grep -v "volatile.eth0" | grep -q "eth0" lxc config device add foo eth2 nic nictype=bridged parent=lxdbr0 name=eth10 lxc exec foo -- /sbin/ifconfig -a | grep eth0 lxc exec foo -- /sbin/ifconfig -a | grep eth10 lxc config device list foo | grep eth2 lxc config device remove foo eth2 # test live-adding a disk mkdir "${TEST_DIR}/mnt2" touch "${TEST_DIR}/mnt2/hosts" lxc config device add foo mnt2 disk source="${TEST_DIR}/mnt2" path=/mnt2 readonly=true lxc exec foo -- cat /proc/self/mountinfo | grep -q "/mnt2.*ro," lxc exec foo -- ls /mnt2/hosts lxc stop foo --force lxc start foo lxc exec foo -- ls /mnt2/hosts lxc config device remove foo mnt2 ! lxc exec foo -- ls /mnt2/hosts lxc stop foo --force lxc start foo ! lxc exec foo -- ls /mnt2/hosts lxc stop foo --force lxc config set foo user.prop value lxc list user.prop=value | grep foo lxc config unset foo user.prop # Test for invalid raw.lxc ! lxc config set foo raw.lxc a ! lxc profile set default raw.lxc a bad=0 lxc list user.prop=value | grep foo && bad=1 if [ "${bad}" -eq 1 ]; then echo "property unset failed" false fi bad=0 lxc config set foo user.prop 2>/dev/null && bad=1 if [ "${bad}" -eq 1 ]; then echo "property set succeded when it shouldn't have" false fi testunixdevs testloopmounts test_mount_order lxc delete foo lxc init testimage foo lxc profile apply foo onenic,unconfined lxc start foo if [ -e /sys/module/apparmor ]; then lxc exec foo -- cat /proc/self/attr/current | grep unconfined fi lxc exec foo -- ls /sys/class/net | grep eth0 lxc stop foo --force lxc delete foo } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/concurrent.sh����������������������������������������������������������������0000644�0610621�0607500�00000001245�13172163242�020504� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������test_concurrent() { if [ -z "${LXD_CONCURRENT:-}" ]; then echo "==> SKIP: LXD_CONCURRENT isn't set" return fi ensure_import_testimage spawn_container() { set -e name=concurrent-${1} lxc launch testimage "${name}" lxc info "${name}" | grep Running echo abc | lxc exec "${name}" -- cat | grep abc lxc stop "${name}" --force lxc delete "${name}" } PIDS="" for id in $(seq $(($(find /sys/bus/cpu/devices/ -type l | wc -l)*8))); do spawn_container "${id}" 2>&1 | tee "${LXD_DIR}/lxc-${id}.out" & PIDS="${PIDS} $!" done for pid in ${PIDS}; do wait "${pid}" done ! lxc list | grep -q concurrent || false } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/suites/basic.sh���������������������������������������������������������������������0000644�0610621�0607500�00000033260�13172163242�017405� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������gen_third_cert() { [ -f "${LXD_CONF}/client3.crt" ] && return mv "${LXD_CONF}/client.crt" "${LXD_CONF}/client.crt.bak" mv "${LXD_CONF}/client.key" "${LXD_CONF}/client.key.bak" lxc_remote list > /dev/null 2>&1 mv "${LXD_CONF}/client.crt" "${LXD_CONF}/client3.crt" mv "${LXD_CONF}/client.key" "${LXD_CONF}/client3.key" mv "${LXD_CONF}/client.crt.bak" "${LXD_CONF}/client.crt" mv "${LXD_CONF}/client.key.bak" "${LXD_CONF}/client.key" } test_basic_usage() { # shellcheck disable=2039 local lxd_backend lxd_backend=$(storage_backend "$LXD_DIR") ensure_import_testimage ensure_has_localhost_remote "${LXD_ADDR}" # Test image export sum=$(lxc image info testimage | grep ^Fingerprint | cut -d' ' -f2) lxc image export testimage "${LXD_DIR}/" [ "${sum}" = "$(sha256sum "${LXD_DIR}/${sum}.tar.xz" | cut -d' ' -f1)" ] # Test an alias with slashes lxc image show "${sum}" lxc image alias create a/b/ "${sum}" lxc image alias delete a/b/ # Test alias list filtering lxc image alias create foo "${sum}" lxc image alias create bar "${sum}" lxc image alias list local: | grep -q foo lxc image alias list local: | grep -q bar lxc image alias list local: foo | grep -q -v bar lxc image alias list local: "${sum}" | grep -q foo lxc image alias list local: non-existent | grep -q -v non-existent lxc image alias delete foo lxc image alias delete bar # Test image delete lxc image delete testimage # test GET /1.0, since the client always puts to /1.0/ my_curl -f -X GET "https://${LXD_ADDR}/1.0" my_curl -f -X GET "https://${LXD_ADDR}/1.0/containers" # Re-import the image mv "${LXD_DIR}/${sum}.tar.xz" "${LXD_DIR}/testimage.tar.xz" lxc image import "${LXD_DIR}/testimage.tar.xz" --alias testimage user.foo=bar lxc image show testimage | grep -q "user.foo: bar" lxc image delete testimage lxc image import "${LXD_DIR}/testimage.tar.xz" --alias testimage rm "${LXD_DIR}/testimage.tar.xz" # Test filename for image export lxc image export testimage "${LXD_DIR}/" [ "${sum}" = "$(sha256sum "${LXD_DIR}/${sum}.tar.xz" | cut -d' ' -f1)" ] rm "${LXD_DIR}/${sum}.tar.xz" # Test custom filename for image export lxc image export testimage "${LXD_DIR}/foo" [ "${sum}" = "$(sha256sum "${LXD_DIR}/foo.tar.xz" | cut -d' ' -f1)" ] rm "${LXD_DIR}/foo.tar.xz" # Test image export with a split image. deps/import-busybox --split --alias splitimage sum=$(lxc image info splitimage | grep ^Fingerprint | cut -d' ' -f2) lxc image export splitimage "${LXD_DIR}" [ "${sum}" = "$(cat "${LXD_DIR}/meta-${sum}.tar.xz" "${LXD_DIR}/${sum}.tar.xz" | sha256sum | cut -d' ' -f1)" ] # Delete the split image and exported files rm "${LXD_DIR}/${sum}.tar.xz" rm "${LXD_DIR}/meta-${sum}.tar.xz" lxc image delete splitimage # Redo the split image export test, this time with the --filename flag # to tell import-busybox to set the 'busybox' filename in the upload. # The sum should remain the same as its the same image. deps/import-busybox --split --filename --alias splitimage lxc image export splitimage "${LXD_DIR}" [ "${sum}" = "$(cat "${LXD_DIR}/meta-${sum}.tar.xz" "${LXD_DIR}/${sum}.tar.xz" | sha256sum | cut -d' ' -f1)" ] # Delete the split image and exported files rm "${LXD_DIR}/${sum}.tar.xz" rm "${LXD_DIR}/meta-${sum}.tar.xz" lxc image delete splitimage # Test container creation lxc init testimage foo lxc list | grep foo | grep STOPPED lxc list fo | grep foo | grep STOPPED # Test list json format lxc list --format json | jq '.[]|select(.name="foo")' | grep '"name": "foo"' # Test list with --columns and --fast ! lxc list --columns=nsp --fast # Test container rename lxc move foo bar lxc list | grep -v foo lxc list | grep bar # Test container copy lxc copy bar foo lxc delete foo # gen untrusted cert gen_third_cert # don't allow requests without a cert to get trusted data curl -k -s -X GET "https://${LXD_ADDR}/1.0/containers/foo" | grep 403 # Test unprivileged container publish lxc publish bar --alias=foo-image prop1=val1 lxc image show foo-image | grep val1 curl -k -s --cert "${LXD_CONF}/client3.crt" --key "${LXD_CONF}/client3.key" -X GET "https://${LXD_ADDR}/1.0/images" | grep "/1.0/images/" && false lxc image delete foo-image # Test container publish with existing alias lxc publish bar --alias=foo-image --alias=foo-image2 lxc launch testimage baz # change the container filesystem so the resulting image is different lxc exec baz touch /somefile lxc stop baz --force # publishing another image with same alias doesn't fail lxc publish baz --alias=foo-image lxc delete baz lxc image delete foo-image foo-image2 # Test privileged container publish lxc profile create priv lxc profile set priv security.privileged true lxc init testimage barpriv -p default -p priv lxc publish barpriv --alias=foo-image prop1=val1 lxc image show foo-image | grep val1 curl -k -s --cert "${LXD_CONF}/client3.crt" --key "${LXD_CONF}/client3.key" -X GET "https://${LXD_ADDR}/1.0/images" | grep "/1.0/images/" && false lxc image delete foo-image lxc delete barpriv lxc profile delete priv # Test that containers without metadata.yaml are published successfully. # Note that this quick hack won't work for LVM, since it doesn't always mount # the container's filesystem. That's ok though: the logic we're trying to # test here is independent of storage backend, so running it for just one # backend (or all non-lvm backends) is enough. if [ "$lxd_backend" = "lvm" ]; then lxc init testimage nometadata rm -f "${LXD_DIR}/containers/nometadata/metadata.yaml" lxc publish nometadata --alias=nometadata-image lxc image delete nometadata-image lxc delete nometadata fi # Test public images lxc publish --public bar --alias=foo-image2 curl -k -s --cert "${LXD_CONF}/client3.crt" --key "${LXD_CONF}/client3.key" -X GET "https://${LXD_ADDR}/1.0/images" | grep "/1.0/images/" lxc image delete foo-image2 # Test invalid container names ! lxc init testimage -abc ! lxc init testimage abc- ! lxc init testimage 1234 ! lxc init testimage 12test ! lxc init testimage a_b_c ! lxc init testimage aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # Test snapshot publish lxc snapshot bar lxc publish bar/snap0 --alias foo lxc init foo bar2 lxc list | grep bar2 lxc delete bar2 lxc image delete foo # test basic alias support printf "aliases:\n ls: list" >> "${LXD_CONF}/config.yml" lxc ls # Delete the bar container we've used for several tests lxc delete bar # lxc delete should also delete all snapshots of bar [ ! -d "${LXD_DIR}/snapshots/bar" ] # Test randomly named container creation lxc launch testimage RDNAME=$(lxc list | tail -n2 | grep ^\| | awk '{print $2}') lxc delete -f "${RDNAME}" # Test "nonetype" container creation wait_for "${LXD_ADDR}" my_curl -X POST "https://${LXD_ADDR}/1.0/containers" \ -d "{\"name\":\"nonetype\",\"source\":{\"type\":\"none\"}}" lxc delete nonetype # Test "nonetype" container creation with an LXC config wait_for "${LXD_ADDR}" my_curl -X POST "https://${LXD_ADDR}/1.0/containers" \ -d "{\"name\":\"configtest\",\"config\":{\"raw.lxc\":\"lxc.hook.clone=/bin/true\"},\"source\":{\"type\":\"none\"}}" # shellcheck disable=SC2102 [ "$(my_curl "https://${LXD_ADDR}/1.0/containers/configtest" | jq -r .metadata.config[\"raw.lxc\"])" = "lxc.hook.clone=/bin/true" ] lxc delete configtest # Test activateifneeded/shutdown LXD_ACTIVATION_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) chmod +x "${LXD_ACTIVATION_DIR}" spawn_lxd "${LXD_ACTIVATION_DIR}" ( set -e # shellcheck disable=SC2030 LXD_DIR=${LXD_ACTIVATION_DIR} ensure_import_testimage lxd activateifneeded --debug 2>&1 | grep -q "Daemon has core.https_address set, activating..." lxc config unset core.https_address --force-local lxd activateifneeded --debug 2>&1 | grep -q -v "activating..." lxc init testimage autostart --force-local lxd activateifneeded --debug 2>&1 | grep -q -v "activating..." lxc config set autostart boot.autostart true --force-local lxd activateifneeded --debug 2>&1 | grep -q "Daemon has auto-started containers, activating..." lxc config unset autostart boot.autostart --force-local lxd activateifneeded --debug 2>&1 | grep -q -v "activating..." lxc start autostart --force-local PID=$(lxc info autostart --force-local | grep ^Pid | awk '{print $2}') shutdown_lxd "${LXD_DIR}" [ -d "/proc/${PID}" ] && false lxd activateifneeded --debug 2>&1 | grep -q "Daemon has auto-started containers, activating..." # shellcheck disable=SC2031 respawn_lxd "${LXD_DIR}" lxc list --force-local autostart | grep -q RUNNING lxc delete autostart --force --force-local ) # shellcheck disable=SC2031 LXD_DIR=${LXD_DIR} kill_lxd "${LXD_ACTIVATION_DIR}" # Create and start a container lxc launch testimage foo lxc list | grep foo | grep RUNNING lxc stop foo --force # stop is hanging # cycle it a few times lxc start foo mac1=$(lxc exec foo cat /sys/class/net/eth0/address) lxc stop foo --force # stop is hanging lxc start foo mac2=$(lxc exec foo cat /sys/class/net/eth0/address) if [ -n "${mac1}" ] && [ -n "${mac2}" ] && [ "${mac1}" != "${mac2}" ]; then echo "==> MAC addresses didn't match across restarts (${mac1} vs ${mac2})" false fi # Test instance types lxc launch testimage test-limits -t c0.5-m0.2 [ "$(lxc config get test-limits limits.cpu)" = "1" ] [ "$(lxc config get test-limits limits.cpu.allowance)" = "50%" ] [ "$(lxc config get test-limits limits.memory)" = "204MB" ] lxc delete -f test-limits # check that we can set the environment lxc exec foo pwd | grep /root lxc exec --env BEST_BAND=meshuggah foo env | grep meshuggah lxc exec foo ip link show | grep eth0 # check that we can get the return code for a non- wait-for-websocket exec op=$(my_curl -X POST "https://${LXD_ADDR}/1.0/containers/foo/exec" -d '{"command": ["sleep", "1"], "environment": {}, "wait-for-websocket": false, "interactive": false}' | jq -r .operation) [ "$(my_curl "https://${LXD_ADDR}${op}/wait" | jq -r .metadata.metadata.return)" != "null" ] # test file transfer echo abc > "${LXD_DIR}/in" lxc file push "${LXD_DIR}/in" foo/root/ lxc exec foo /bin/cat /root/in | grep abc lxc exec foo -- /bin/rm -f root/in lxc file push "${LXD_DIR}/in" foo/root/in1 lxc exec foo /bin/cat /root/in1 | grep abc lxc exec foo -- /bin/rm -f root/in1 # test lxc file edit doesn't change target file's owner and permissions echo "content" | lxc file push - foo/tmp/edit_test lxc exec foo -- chown 55.55 /tmp/edit_test lxc exec foo -- chmod 555 /tmp/edit_test echo "new content" | lxc file edit foo/tmp/edit_test [ "$(lxc exec foo -- cat /tmp/edit_test)" = "new content" ] [ "$(lxc exec foo -- stat -c \"%u %g %a\" /tmp/edit_test)" = "55 55 555" ] # make sure stdin is chowned to our container root uid (Issue #590) [ -t 0 ] && [ -t 1 ] && lxc exec foo -- chown 1000:1000 /proc/self/fd/0 echo foo | lxc exec foo tee /tmp/foo # Detect regressions/hangs in exec sum=$(ps aux | tee "${LXD_DIR}/out" | lxc exec foo md5sum | cut -d' ' -f1) [ "${sum}" = "$(md5sum "${LXD_DIR}/out" | cut -d' ' -f1)" ] rm "${LXD_DIR}/out" # FIXME: make this backend agnostic if [ "$lxd_backend" = "dir" ]; then content=$(cat "${LXD_DIR}/containers/foo/rootfs/tmp/foo") [ "${content}" = "foo" ] fi lxc launch testimage deleterunning my_curl -X DELETE "https://${LXD_ADDR}/1.0/containers/deleterunning" | grep "container is running" lxc delete deleterunning -f # cleanup lxc delete foo -f if [ -e /sys/module/apparmor/ ]; then # check that an apparmor profile is created for this container, that it is # unloaded on stop, and that it is deleted when the container is deleted lxc launch testimage lxd-apparmor-test MAJOR=0 MINOR=0 if [ -f /sys/kernel/security/apparmor/features/domain/version ]; then MAJOR=$(awk -F. '{print $1}' < /sys/kernel/security/apparmor/features/domain/version) MINOR=$(awk -F. '{print $2}' < /sys/kernel/security/apparmor/features/domain/version) fi if [ "${MAJOR}" -gt "1" ] || ([ "${MAJOR}" = "1" ] && [ "${MINOR}" -ge "2" ]); then aa_namespace="lxd-lxd-apparmor-test_<$(echo "${LXD_DIR}" | sed -e 's/\//-/g' -e 's/^.//')>" aa-status | grep -q ":${aa_namespace}:unconfined" || aa-status | grep -q ":${aa_namespace}://unconfined" lxc stop lxd-apparmor-test --force ! aa-status | grep -q ":${aa_namespace}:" || false else aa-status | grep "lxd-lxd-apparmor-test_<${LXD_DIR}>" lxc stop lxd-apparmor-test --force ! aa-status | grep -q "lxd-lxd-apparmor-test_<${LXD_DIR}>" || false fi lxc delete lxd-apparmor-test [ ! -f "${LXD_DIR}/security/apparmor/profiles/lxd-lxd-apparmor-test" ] else echo "==> SKIP: apparmor tests (missing kernel support)" fi # make sure that privileged containers are not world-readable lxc profile create unconfined lxc profile set unconfined security.privileged true lxc init testimage foo2 -p unconfined [ "$(stat -L -c "%a" "${LXD_DIR}/containers/foo2")" = "700" ] lxc delete foo2 lxc profile delete unconfined # Ephemeral lxc launch testimage foo -e OLD_INIT=$(lxc info foo | grep ^Pid) lxc exec foo reboot || true REBOOTED="false" # shellcheck disable=SC2034 for i in $(seq 20); do NEW_INIT=$(lxc info foo | grep ^Pid || true) if [ -n "${NEW_INIT}" ] && [ "${OLD_INIT}" != "${NEW_INIT}" ]; then REBOOTED="true" break fi sleep 0.5 done [ "${REBOOTED}" = "true" ] # Workaround for LXC bug which causes LXD to double-start containers # on reboot sleep 2 lxc stop foo --force || true ! lxc list | grep -q foo || false } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/perf.sh�����������������������������������������������������������������������������0000755�0610621�0607500�00000004130�13172163242�015741� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/sh -eu # # Performance tests runner # [ -n "${GOPATH:-}" ] && export "PATH=${GOPATH}/bin:${PATH}" PERF_LOG_CSV="perf.csv" import_subdir_files() { test "$1" # shellcheck disable=SC2039 local file for file in "$1"/*.sh; do # shellcheck disable=SC1090 . "$file" done } import_subdir_files includes log_message() { echo "==>" "$@" } run_benchmark() { # shellcheck disable=SC2039 local label description opts label="$1" description="$2" shift 2 log_message "Benchmark start: $label - $description" lxd_benchmark "$@" --report-file "$PERF_LOG_CSV" --report-label "$label" log_message "Benchmark completed: $label" } lxd_benchmark() { # shellcheck disable=SC2039 local opts [ "${LXD_TEST_IMAGE:-}" ] && opts="--image $LXD_TEST_IMAGE" || opts="" lxd-benchmark "$@" $opts } cleanup() { if [ "$TEST_RESULT" != "success" ]; then rm -f "$PERF_LOG_CSV" fi lxd_benchmark delete # ensure all test containers have been deleted kill_lxd "$LXD_DIR" cleanup_lxds "$TEST_DIR" log_message "Performance tests result: $TEST_RESULT" } trap cleanup EXIT HUP INT TERM # Setup test directories TEST_DIR=$(mktemp -d -p "$(pwd)" tmp.XXX) if [ -n "${LXD_TMPFS:-}" ]; then mount -t tmpfs tmpfs "${TEST_DIR}" -o mode=0751 fi LXD_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) export LXD_DIR chmod +x "${TEST_DIR}" "${LXD_DIR}" if [ -z "${LXD_BACKEND:-}" ]; then LXD_BACKEND="dir" fi import_storage_backends spawn_lxd "${LXD_DIR}" true ensure_import_testimage # shellcheck disable=SC2034 TEST_RESULT=failure run_benchmark "create-one" "create 1 container" launch --count 1 --start=false --image=testimage run_benchmark "start-one" "start 1 container" start run_benchmark "stop-one" "stop 1 container" stop run_benchmark "delete-one" "delete 1 container" delete run_benchmark "create-128" "create 128 containers" launch --count 128 --start=false --image=testimage run_benchmark "start-128" "start 128 containers" start run_benchmark "delete-128" "delete 128 containers" delete # shellcheck disable=SC2034 TEST_RESULT=success ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/main.sh�����������������������������������������������������������������������������0000755�0610621�0607500�00000010470�13172163242�015735� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/sh -eu [ -n "${GOPATH:-}" ] && export "PATH=${GOPATH}/bin:${PATH}" # Don't translate lxc output for parsing in it in tests. export LC_ALL="C" # Force UTC for consistency export TZ="UTC" if [ -n "${LXD_VERBOSE:-}" ] || [ -n "${LXD_DEBUG:-}" ]; then set -x fi export DEBUG="" if [ -n "${LXD_VERBOSE:-}" ]; then DEBUG="--verbose" fi if [ -n "${LXD_DEBUG:-}" ]; then DEBUG="--debug" fi if [ -z "${LXD_BACKEND:-}" ]; then LXD_BACKEND="dir" fi import_subdir_files() { test "$1" # shellcheck disable=SC2039 local file for file in "$1"/*.sh; do # shellcheck disable=SC1090 . "$file" done } import_subdir_files includes echo "==> Checking for dependencies" check_dependencies lxd lxc curl jq git xgettext sqlite3 msgmerge msgfmt shuf setfacl uuidgen if [ "${USER:-'root'}" != "root" ]; then echo "The testsuite must be run as root." >&2 exit 1 fi if [ -n "${LXD_LOGS:-}" ] && [ ! -d "${LXD_LOGS}" ]; then echo "Your LXD_LOGS path doesn't exist: ${LXD_LOGS}" exit 1 fi echo "==> Available storage backends: $(available_storage_backends | sort)" if [ "$LXD_BACKEND" != "random" ] && ! storage_backend_available "$LXD_BACKEND"; then echo "Storage backage \"$LXD_BACKEND\" is not available" exit 1 fi echo "==> Using storage backend ${LXD_BACKEND}" import_storage_backends cleanup() { # Allow for failures and stop tracing everything set +ex DEBUG= # Allow for inspection if [ -n "${LXD_INSPECT:-}" ]; then if [ "${TEST_RESULT}" != "success" ]; then echo "==> TEST DONE: ${TEST_CURRENT_DESCRIPTION}" fi echo "==> Test result: ${TEST_RESULT}" # shellcheck disable=SC2086 printf "To poke around, use:\n LXD_DIR=%s LXD_CONF=%s sudo -E %s/bin/lxc COMMAND\n" "${LXD_DIR}" "${LXD_CONF}" ${GOPATH:-} echo "Tests Completed (${TEST_RESULT}): hit enter to continue" # shellcheck disable=SC2034 read -r nothing fi echo "==> Cleaning up" cleanup_lxds "$TEST_DIR" echo "" echo "" if [ "${TEST_RESULT}" != "success" ]; then echo "==> TEST DONE: ${TEST_CURRENT_DESCRIPTION}" fi echo "==> Test result: ${TEST_RESULT}" } # Must be set before cleanup() TEST_CURRENT=setup # shellcheck disable=SC2034 TEST_RESULT=failure trap cleanup EXIT HUP INT TERM # Import all the testsuites import_subdir_files suites # Setup test directory TEST_DIR=$(mktemp -d -p "$(pwd)" tmp.XXX) chmod +x "${TEST_DIR}" if [ -n "${LXD_TMPFS:-}" ]; then mount -t tmpfs tmpfs "${TEST_DIR}" -o mode=0751 fi LXD_CONF=$(mktemp -d -p "${TEST_DIR}" XXX) export LXD_CONF LXD_DIR=$(mktemp -d -p "${TEST_DIR}" XXX) export LXD_DIR chmod +x "${LXD_DIR}" spawn_lxd "${LXD_DIR}" LXD_ADDR=$(cat "${LXD_DIR}/lxd.addr") export LXD_ADDR run_test() { TEST_CURRENT=${1} TEST_CURRENT_DESCRIPTION=${2:-${1}} echo "==> TEST BEGIN: ${TEST_CURRENT_DESCRIPTION}" START_TIME=$(date +%s) ${TEST_CURRENT} END_TIME=$(date +%s) echo "==> TEST DONE: ${TEST_CURRENT_DESCRIPTION} ($((END_TIME-START_TIME))s)" } # allow for running a specific set of tests if [ "$#" -gt 0 ]; then run_test "test_${1}" # shellcheck disable=SC2034 TEST_RESULT=success exit fi run_test test_check_deps "checking dependencies" run_test test_static_analysis "static analysis" run_test test_database_update "database schema updates" run_test test_remote_url "remote url handling" run_test test_remote_admin "remote administration" run_test test_remote_usage "remote usage" run_test test_basic_usage "basic usage" run_test test_security "security features" run_test test_image_expiry "image expiry" run_test test_image_auto_update "image auto-update" run_test test_concurrent_exec "concurrent exec" run_test test_concurrent "concurrent startup" run_test test_snapshots "container snapshots" run_test test_snap_restore "snapshot restores" run_test test_config_profiles "profiles and configuration" run_test test_server_config "server configuration" run_test test_filemanip "file manipulations" run_test test_idmap "id mapping" run_test test_template "file templating" run_test test_devlxd "/dev/lxd" run_test test_fuidshift "fuidshift" run_test test_migration "migration" run_test test_fdleak "fd leak" run_test test_cpu_profiling "CPU profiling" run_test test_mem_profiling "memory profiling" run_test test_init_auto "lxd init auto" run_test test_init_interactive "lxd init interactive" # shellcheck disable=SC2034 TEST_RESULT=success ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/lxd-benchmark/����������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�017167� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/lxd-benchmark/main.go���������������������������������������������������������������0000644�0610621�0607500�00000007054�13172163242�020450� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "time" "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/version" "github.com/lxc/lxd/test/lxd-benchmark/benchmark" ) var argCount = gnuflag.Int("count", 100, "Number of containers to create") var argParallel = gnuflag.Int("parallel", -1, "Number of threads to use") var argImage = gnuflag.String("image", "ubuntu:", "Image to use for the test") var argPrivileged = gnuflag.Bool("privileged", false, "Use privileged containers") var argStart = gnuflag.Bool("start", true, "Start the container after creation") var argFreeze = gnuflag.Bool("freeze", false, "Freeze the container right after start") var argReportFile = gnuflag.String("report-file", "", "A CSV file to write test file to. If the file is present, it will be appended to.") var argReportLabel = gnuflag.String("report-label", "", "A label for the report entry. By default, the action is used.") func main() { err := run(os.Args) if err != nil { fmt.Fprintf(os.Stderr, "error: %s\n", err) os.Exit(1) } os.Exit(0) } func run(args []string) error { // Parse command line // "spawn" is being deprecated, use "launch" instead. if len(os.Args) == 1 || !shared.StringInSlice(os.Args[1], []string{"launch", "spawn", "start", "stop", "delete"}) { if len(os.Args) > 1 && os.Args[1] == "--version" { fmt.Println(version.Version) return nil } out := os.Stderr if len(os.Args) > 1 && os.Args[1] == "--help" { out = os.Stdout } gnuflag.SetOut(out) fmt.Fprintf(out, "Usage: %s launch [--count=COUNT] [--image=IMAGE] [--privileged=BOOL] [--start=BOOL] [--freeze=BOOL] [--parallel=COUNT]\n", os.Args[0]) fmt.Fprintf(out, " %s start [--parallel=COUNT]\n", os.Args[0]) fmt.Fprintf(out, " %s stop [--parallel=COUNT]\n", os.Args[0]) fmt.Fprintf(out, " %s delete [--parallel=COUNT]\n\n", os.Args[0]) gnuflag.PrintDefaults() fmt.Fprintf(out, "\n") if len(os.Args) > 1 && os.Args[1] == "--help" { return nil } return fmt.Errorf("A valid action (launch, start, stop, delete) must be passed.") } gnuflag.Parse(true) // Connect to LXD c, err := lxd.ConnectLXDUnix("", nil) if err != nil { return err } benchmark.PrintServerInfo(c) var report *benchmark.CSVReport if *argReportFile != "" { report = &benchmark.CSVReport{Filename: *argReportFile} if shared.PathExists(*argReportFile) { err := report.Load() if err != nil { return err } } } action := os.Args[1] var duration time.Duration switch action { // "spawn" is being deprecated. case "launch", "spawn": duration, err = benchmark.LaunchContainers( c, *argCount, *argParallel, *argImage, *argPrivileged, *argStart, *argFreeze) if err != nil { return err } case "start": containers, err := benchmark.GetContainers(c) if err != nil { return err } duration, err = benchmark.StartContainers(c, containers, *argParallel) if err != nil { return err } case "stop": containers, err := benchmark.GetContainers(c) if err != nil { return err } duration, err = benchmark.StopContainers(c, containers, *argParallel) if err != nil { return err } case "delete": containers, err := benchmark.GetContainers(c) if err != nil { return err } duration, err = benchmark.DeleteContainers(c, containers, *argParallel) if err != nil { return err } } if report != nil { label := action if *argReportLabel != "" { label = *argReportLabel } report.AddRecord(label, duration) err := report.Write() if err != nil { return err } } return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/lxd-benchmark/benchmark/������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�021121� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/lxd-benchmark/benchmark/util.go�����������������������������������������������������0000644�0610621�0607500�00000002021�13172163242�022420� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package benchmark import ( "fmt" "time" ) func getContainerName(count int, index int) string { nameFormat := "benchmark-%." + fmt.Sprintf("%d", len(fmt.Sprintf("%d", count))) + "d" return fmt.Sprintf(nameFormat, index+1) } func logf(format string, args ...interface{}) { fmt.Printf(fmt.Sprintf("[%s] %s\n", time.Now().Format(time.StampMilli), format), args...) } func printTestConfig(count int, batchSize int, image string, privileged bool, freeze bool) { privilegedStr := "unprivileged" if privileged { privilegedStr = "privileged" } mode := "normal startup" if freeze { mode = "start and freeze" } batches := count / batchSize remainder := count % batchSize fmt.Printf("Test variables:\n") fmt.Printf(" Container count: %d\n", count) fmt.Printf(" Container mode: %s\n", privilegedStr) fmt.Printf(" Startup mode: %s\n", mode) fmt.Printf(" Image: %s\n", image) fmt.Printf(" Batches: %d\n", batches) fmt.Printf(" Batch size: %d\n", batchSize) fmt.Printf(" Remainder: %d\n", remainder) fmt.Printf("\n") } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/lxd-benchmark/benchmark/report.go���������������������������������������������������0000644�0610621�0607500�00000003723�13172163242�022770� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package benchmark import ( "encoding/csv" "fmt" "io" "os" "time" ) // Subset of JMeter CSV log format that are required by Jenkins performance // plugin // (see http://jmeter.apache.org/usermanual/listeners.html#csvlogformat) var csvFields = []string{ "timeStamp", // in milliseconds since 1/1/1970 "elapsed", // in milliseconds "label", "responseCode", "success", // "true" or "false" } // CSVReport reads/writes a CSV report file. type CSVReport struct { Filename string records [][]string } // Load reads current content of the filename and loads records. func (r *CSVReport) Load() error { file, err := os.Open(r.Filename) if err != nil { return err } defer file.Close() reader := csv.NewReader(file) for line := 1; err != io.EOF; line++ { record, err := reader.Read() if err == io.EOF { break } else if err != nil { return err } err = r.addRecord(record) if err != nil { return err } } logf("Loaded report file %s", r.Filename) return nil } // Write writes current records to file. func (r *CSVReport) Write() error { file, err := os.OpenFile(r.Filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640) if err != nil { return err } defer file.Close() writer := csv.NewWriter(file) err = writer.WriteAll(r.records) if err != nil { return err } logf("Written report file %s", r.Filename) return nil } // AddRecord adds a record to the report. func (r *CSVReport) AddRecord(label string, elapsed time.Duration) error { if len(r.records) == 0 { r.addRecord(csvFields) } record := []string{ fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond)), // timestamp fmt.Sprintf("%d", elapsed/time.Millisecond), label, "", // responseCode is not used "true", // success" } return r.addRecord(record) } func (r *CSVReport) addRecord(record []string) error { if len(record) != len(csvFields) { return fmt.Errorf("Invalid number of fields : %q", record) } r.records = append(r.records, record) return nil } ���������������������������������������������lxd-2.0.11/test/lxd-benchmark/benchmark/operation.go������������������������������������������������0000644�0610621�0607500�00000003043�13172163242�023450� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package benchmark import ( "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared/api" ) func createContainer(c lxd.ContainerServer, fingerprint string, name string, privileged bool) error { config := map[string]string{} if privileged { config["security.privileged"] = "true" } config[userConfigKey] = "true" req := api.ContainersPost{ Name: name, Source: api.ContainerSource{ Type: "image", Fingerprint: fingerprint, }, } req.Config = config op, err := c.CreateContainer(req) if err != nil { return err } return op.Wait() } func startContainer(c lxd.ContainerServer, name string) error { op, err := c.UpdateContainerState( name, api.ContainerStatePut{Action: "start", Timeout: -1}, "") if err != nil { return err } return op.Wait() } func stopContainer(c lxd.ContainerServer, name string) error { op, err := c.UpdateContainerState( name, api.ContainerStatePut{Action: "stop", Timeout: -1, Force: true}, "") if err != nil { return err } return op.Wait() } func freezeContainer(c lxd.ContainerServer, name string) error { op, err := c.UpdateContainerState( name, api.ContainerStatePut{Action: "freeze", Timeout: -1}, "") if err != nil { return err } return op.Wait() } func deleteContainer(c lxd.ContainerServer, name string) error { op, err := c.DeleteContainer(name) if err != nil { return err } return op.Wait() } func copyImage(c lxd.ContainerServer, s lxd.ImageServer, image api.Image) error { op, err := c.CopyImage(s, image, nil) if err != nil { return err } return op.Wait() } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/lxd-benchmark/benchmark/benchmark.go������������������������������������������������0000644�0610621�0607500�00000015343�13172163242�023410� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package benchmark import ( "fmt" "strings" "sync" "time" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/version" ) const userConfigKey = "user.lxd-benchmark" // PrintServerInfo prints out information about the server. func PrintServerInfo(c lxd.ContainerServer) error { server, _, err := c.GetServer() if err != nil { return err } env := server.Environment fmt.Printf("Test environment:\n") fmt.Printf(" Server backend: %s\n", env.Server) fmt.Printf(" Server version: %s\n", env.ServerVersion) fmt.Printf(" Kernel: %s\n", env.Kernel) fmt.Printf(" Kernel architecture: %s\n", env.KernelArchitecture) fmt.Printf(" Kernel version: %s\n", env.KernelVersion) fmt.Printf(" Storage backend: %s\n", env.Storage) fmt.Printf(" Storage version: %s\n", env.StorageVersion) fmt.Printf(" Container backend: %s\n", env.Driver) fmt.Printf(" Container version: %s\n", env.DriverVersion) fmt.Printf("\n") return nil } // LaunchContainers launches a set of containers. func LaunchContainers(c lxd.ContainerServer, count int, parallel int, image string, privileged bool, start bool, freeze bool) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } printTestConfig(count, batchSize, image, privileged, freeze) fingerprint, err := ensureImage(c, image) if err != nil { return duration, err } startContainer := func(index int, wg *sync.WaitGroup) { defer wg.Done() name := getContainerName(count, index) err := createContainer(c, fingerprint, name, privileged) if err != nil { logf("Failed to launch container '%s': %s", name, err) return } if start { err := startContainer(c, name) if err != nil { logf("Failed to start container '%s': %s", name, err) return } if freeze { err := freezeContainer(c, name) if err != nil { logf("Failed to freeze container '%s': %s", name, err) return } } } } duration = processBatch(count, batchSize, startContainer) return duration, nil } // CreateContainers create the specified number of containers. func CreateContainers(c lxd.ContainerServer, count int, parallel int, fingerprint string, privileged bool) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } createContainer := func(index int, wg *sync.WaitGroup) { defer wg.Done() name := getContainerName(count, index) err := createContainer(c, fingerprint, name, privileged) if err != nil { logf("Failed to launch container '%s': %s", name, err) return } } duration = processBatch(count, batchSize, createContainer) return duration, nil } // GetContainers returns containers created by the benchmark. func GetContainers(c lxd.ContainerServer) ([]api.Container, error) { containers := []api.Container{} allContainers, err := c.GetContainers() if err != nil { return containers, err } for _, container := range allContainers { if container.Config[userConfigKey] == "true" { containers = append(containers, container) } } return containers, nil } // StartContainers starts containers created by the benchmark. func StartContainers(c lxd.ContainerServer, containers []api.Container, parallel int) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } count := len(containers) logf("Starting %d containers", count) startContainer := func(index int, wg *sync.WaitGroup) { defer wg.Done() container := containers[index] if !container.IsActive() { err := startContainer(c, container.Name) if err != nil { logf("Failed to start container '%s': %s", container.Name, err) return } } } duration = processBatch(count, batchSize, startContainer) return duration, nil } // StopContainers stops containers created by the benchmark. func StopContainers(c lxd.ContainerServer, containers []api.Container, parallel int) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } count := len(containers) logf("Stopping %d containers", count) stopContainer := func(index int, wg *sync.WaitGroup) { defer wg.Done() container := containers[index] if container.IsActive() { err := stopContainer(c, container.Name) if err != nil { logf("Failed to stop container '%s': %s", container.Name, err) return } } } duration = processBatch(count, batchSize, stopContainer) return duration, nil } // DeleteContainers removes containers created by the benchmark. func DeleteContainers(c lxd.ContainerServer, containers []api.Container, parallel int) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } count := len(containers) logf("Deleting %d containers", count) deleteContainer := func(index int, wg *sync.WaitGroup) { defer wg.Done() container := containers[index] name := container.Name if container.IsActive() { err := stopContainer(c, name) if err != nil { logf("Failed to stop container '%s': %s", name, err) return } } err = deleteContainer(c, name) if err != nil { logf("Failed to delete container: %s", name) return } } duration = processBatch(count, batchSize, deleteContainer) return duration, nil } func ensureImage(c lxd.ContainerServer, image string) (string, error) { var fingerprint string if strings.Contains(image, ":") { defaultConfig := config.NewConfig("", true) defaultConfig.UserAgent = version.UserAgent remote, fp, err := defaultConfig.ParseRemote(image) if err != nil { return "", err } fingerprint = fp imageServer, err := defaultConfig.GetImageServer(remote) if err != nil { return "", err } if fingerprint == "" { fingerprint = "default" } alias, _, err := imageServer.GetImageAlias(fingerprint) if err == nil { fingerprint = alias.Target } _, _, err = c.GetImage(fingerprint) if err != nil { logf("Importing image into local store: %s", fingerprint) image, _, err := imageServer.GetImage(fingerprint) if err != nil { logf("Failed to import image: %s", err) return "", err } err = copyImage(c, imageServer, *image) if err != nil { logf("Failed to import image: %s", err) return "", err } } } else { fingerprint = image alias, _, err := c.GetImageAlias(image) if err == nil { fingerprint = alias.Target } else { _, _, err = c.GetImage(image) } if err != nil { logf("Image not found in local store: %s", image) return "", err } } logf("Found image in local store: %s", fingerprint) return fingerprint, nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/lxd-benchmark/benchmark/batch.go����������������������������������������������������0000644�0610621�0607500�00000002323�13172163242�022531� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package benchmark import ( "io/ioutil" "sync" "time" ) func getBatchSize(parallel int) (int, error) { batchSize := parallel if batchSize < 1 { // Detect the number of parallel actions cpus, err := ioutil.ReadDir("/sys/bus/cpu/devices") if err != nil { return -1, err } batchSize = len(cpus) } return batchSize, nil } func processBatch(count int, batchSize int, process func(index int, wg *sync.WaitGroup)) time.Duration { batches := count / batchSize remainder := count % batchSize processed := 0 wg := sync.WaitGroup{} nextStat := batchSize logf("Batch processing start") timeStart := time.Now() for i := 0; i < batches; i++ { for j := 0; j < batchSize; j++ { wg.Add(1) go process(processed, &wg) processed++ } wg.Wait() if processed >= nextStat { interval := time.Since(timeStart).Seconds() logf("Processed %d containers in %.3fs (%.3f/s)", processed, interval, float64(processed)/interval) nextStat = nextStat * 2 } } for k := 0; k < remainder; k++ { wg.Add(1) go process(processed, &wg) processed++ } wg.Wait() timeEnd := time.Now() duration := timeEnd.Sub(timeStart) logf("Batch processing completed in %.3fs", duration.Seconds()) return duration } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/includes/���������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016256� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/includes/storage.sh�����������������������������������������������������������������0000644�0610621�0607500�00000005461�13172163242�020264� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Helper functions related to storage backends. # Whether a storage backend is available storage_backend_available() { # shellcheck disable=2039 local backends backends="$(available_storage_backends)" [ "${backends#*$1}" != "$backends" ] } # Choose a random available backend, excluding LXD_BACKEND random_storage_backend() { # shellcheck disable=2046 shuf -e $(available_storage_backends) | head -n 1 } # Return the storage backend being used by a LXD instance storage_backend() { cat "$1/lxd.backend" } # Return a list of available storage backends available_storage_backends() { # shellcheck disable=2039 local backend backends storage_backends backends="dir" # always available storage_backends="btrfs lvm zfs" for backend in $storage_backends; do if which "$backend" >/dev/null 2>&1; then backends="$backends $backend" fi done echo "$backends" } import_storage_backends() { # shellcheck disable=SC2039 local backend for backend in $(available_storage_backends); do # shellcheck disable=SC1090 . "backends/${backend}.sh" done } configure_loop_device() { # shellcheck disable=SC2039 local lv_loop_file pvloopdev # shellcheck disable=SC2153 lv_loop_file=$(mktemp -p "${TEST_DIR}" XXXX.img) truncate -s 10G "${lv_loop_file}" pvloopdev=$(losetup --show -f "${lv_loop_file}") if [ ! -e "${pvloopdev}" ]; then echo "failed to setup loop" false fi # shellcheck disable=SC2153 echo "${pvloopdev}" >> "${TEST_DIR}/loops" # The following code enables to return a value from a shell function by # calling the function as: fun VAR1 # shellcheck disable=2039 local __tmp1="${1}" # shellcheck disable=2039 local res1="${lv_loop_file}" if [ "${__tmp1}" ]; then eval "${__tmp1}='${res1}'" fi # shellcheck disable=2039 local __tmp2="${2}" # shellcheck disable=2039 local res2="${pvloopdev}" if [ "${__tmp2}" ]; then eval "${__tmp2}='${res2}'" fi } deconfigure_loop_device() { # shellcheck disable=SC2039 local lv_loop_file loopdev success lv_loop_file="${1}" loopdev="${2}" success=0 # shellcheck disable=SC2034 for i in $(seq 10); do if losetup -d "${loopdev}"; then success=1 break fi sleep 0.5 done if [ "${success}" = "0" ]; then echo "Failed to tear down loop device" return 1 fi rm -f "${lv_loop_file}" sed -i "\|^${loopdev}|d" "${TEST_DIR}/loops" } umount_loops() { # shellcheck disable=SC2039 local line test_dir test_dir="$1" if [ -f "${test_dir}/loops" ]; then while read -r line; do losetup -d "${line}" || true done < "${test_dir}/loops" fi } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/includes/setup.sh�������������������������������������������������������������������0000644�0610621�0607500�00000001605�13172163242�017754� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Test setup helper functions. ensure_has_localhost_remote() { # shellcheck disable=SC2039 local addr=${1} if ! lxc remote list | grep -q "localhost"; then lxc remote add localhost "https://${addr}" --accept-certificate --password foo fi } ensure_import_testimage() { if ! lxc image alias list | grep -q "^| testimage\s*|.*$"; then if [ -e "${LXD_TEST_IMAGE:-}" ]; then lxc image import "${LXD_TEST_IMAGE}" --alias testimage else if [ ! -e "/bin/busybox" ]; then echo "Please install busybox (busybox-static) or set LXD_TEST_IMAGE" exit 1 fi if ldd /bin/busybox >/dev/null 2>&1; then echo "The testsuite requires /bin/busybox to be a static binary" exit 1 fi deps/import-busybox --alias testimage fi fi } ���������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/includes/net.sh���������������������������������������������������������������������0000644�0610621�0607500�00000001027�13172163242�017400� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Network-related helper functions. # Return an available random local port local_tcp_port() { # shellcheck disable=SC2039 local port pid while true; do port=$(shuf -i 10000-32768 -n 1) nc -l 127.0.0.1 "${port}" >/dev/null 2>&1 & pid=$! kill "${pid}" >/dev/null 2>&1 || continue wait "${pid}" || true echo "${port}" return done } # Certificate-aware curl wrapper my_curl() { curl -k -s --cert "${LXD_CONF}/client.crt" --key "${LXD_CONF}/client.key" "$@" } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/includes/lxd.sh���������������������������������������������������������������������0000644�0610621�0607500�00000017254�13172163242�017412� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# LXD-related test helpers. spawn_lxd() { set +x # LXD_DIR is local here because since $(lxc) is actually a function, it # overwrites the environment and we would lose LXD_DIR's value otherwise. # shellcheck disable=2039 local LXD_DIR lxddir lxd_backend lxddir=${1} shift # shellcheck disable=SC2153 if [ "$LXD_BACKEND" = "random" ]; then lxd_backend="$(random_storage_backend)" else lxd_backend="$LXD_BACKEND" fi # Copy pre generated Certs cp deps/server.crt "${lxddir}" cp deps/server.key "${lxddir}" # setup storage "$lxd_backend"_setup "${lxddir}" echo "$lxd_backend" > "${lxddir}/lxd.backend" echo "==> Spawning lxd in ${lxddir}" # shellcheck disable=SC2086 LXD_DIR="${lxddir}" lxd --logfile "${lxddir}/lxd.log" ${DEBUG-} "$@" 2>&1 & LXD_PID=$! echo "${LXD_PID}" > "${lxddir}/lxd.pid" # shellcheck disable=SC2153 echo "${lxddir}" >> "${TEST_DIR}/daemons" echo "==> Spawned LXD (PID is ${LXD_PID})" echo "==> Confirming lxd is responsive" LXD_DIR="${lxddir}" lxd waitready --timeout=300 echo "==> Binding to network" # shellcheck disable=SC2034 for i in $(seq 10); do addr="127.0.0.1:$(local_tcp_port)" LXD_DIR="${lxddir}" lxc config set core.https_address "${addr}" || continue echo "${addr}" > "${lxddir}/lxd.addr" echo "==> Bound to ${addr}" break done echo "==> Setting trust password" LXD_DIR="${lxddir}" lxc config set core.trust_password foo if [ -n "${DEBUG:-}" ]; then set -x fi echo "==> Configuring storage backend" "$lxd_backend"_configure "${lxddir}" } respawn_lxd() { set +x # LXD_DIR is local here because since $(lxc) is actually a function, it # overwrites the environment and we would lose LXD_DIR's value otherwise. # shellcheck disable=2039 local LXD_DIR lxddir=${1} shift echo "==> Spawning lxd in ${lxddir}" # shellcheck disable=SC2086 LXD_DIR="${lxddir}" lxd --logfile "${lxddir}/lxd.log" ${DEBUG-} "$@" 2>&1 & LXD_PID=$! echo "${LXD_PID}" > "${lxddir}/lxd.pid" echo "==> Spawned LXD (PID is ${LXD_PID})" echo "==> Confirming lxd is responsive" LXD_DIR="${lxddir}" lxd waitready --timeout=300 } kill_lxd() { # LXD_DIR is local here because since $(lxc) is actually a function, it # overwrites the environment and we would lose LXD_DIR's value otherwise. # shellcheck disable=2039 local LXD_DIR daemon_dir daemon_pid check_leftovers lxd_backend daemon_dir=${1} LXD_DIR=${daemon_dir} daemon_pid=$(cat "${daemon_dir}/lxd.pid") check_leftovers="false" lxd_backend=$(storage_backend "$daemon_dir") echo "==> Killing LXD at ${daemon_dir}" if [ -e "${daemon_dir}/unix.socket" ]; then # Delete all containers echo "==> Deleting all containers" for container in $(lxc list --fast --force-local | tail -n+3 | grep "^| " | cut -d' ' -f2); do lxc delete "${container}" --force-local -f || true done # Delete all images echo "==> Deleting all images" for image in $(lxc image list --force-local | tail -n+3 | grep "^| " | cut -d'|' -f3 | sed "s/^ //g"); do lxc image delete "${image}" --force-local || true done # Delete all profiles echo "==> Deleting all profiles" for profile in $(lxc profile list --force-local); do lxc profile delete "${profile}" --force-local || true done echo "==> Checking for locked DB tables" for table in $(echo .tables | sqlite3 "${daemon_dir}/lxd.db"); do echo "SELECT * FROM ${table};" | sqlite3 "${daemon_dir}/lxd.db" >/dev/null done # Kill the daemon lxd shutdown || kill -9 "${daemon_pid}" 2>/dev/null || true # Cleanup shmounts (needed due to the forceful kill) find "${daemon_dir}" -name shmounts -exec "umount" "-l" "{}" \; >/dev/null 2>&1 || true find "${daemon_dir}" -name devlxd -exec "umount" "-l" "{}" \; >/dev/null 2>&1 || true check_leftovers="true" fi if [ -n "${LXD_LOGS:-}" ]; then echo "==> Copying the logs" mkdir -p "${LXD_LOGS}/${daemon_pid}" cp -R "${daemon_dir}/logs/" "${LXD_LOGS}/${daemon_pid}/" cp "${daemon_dir}/lxd.log" "${LXD_LOGS}/${daemon_pid}/" fi if [ "${check_leftovers}" = "true" ]; then echo "==> Checking for leftover files" rm -f "${daemon_dir}/containers/lxc-monitord.log" rm -f "${daemon_dir}/security/apparmor/cache/.features" check_empty "${daemon_dir}/containers/" check_empty "${daemon_dir}/devices/" check_empty "${daemon_dir}/images/" # FIXME: Once container logging rework is done, uncomment # check_empty "${daemon_dir}/logs/" check_empty "${daemon_dir}/security/apparmor/cache/" check_empty "${daemon_dir}/security/apparmor/profiles/" check_empty "${daemon_dir}/security/seccomp/" check_empty "${daemon_dir}/shmounts/" check_empty "${daemon_dir}/snapshots/" echo "==> Checking for leftover DB entries" check_empty_table "${daemon_dir}/lxd.db" "containers" check_empty_table "${daemon_dir}/lxd.db" "containers_config" check_empty_table "${daemon_dir}/lxd.db" "containers_devices" check_empty_table "${daemon_dir}/lxd.db" "containers_devices_config" check_empty_table "${daemon_dir}/lxd.db" "containers_profiles" check_empty_table "${daemon_dir}/lxd.db" "images" check_empty_table "${daemon_dir}/lxd.db" "images_aliases" check_empty_table "${daemon_dir}/lxd.db" "images_properties" check_empty_table "${daemon_dir}/lxd.db" "images_source" check_empty_table "${daemon_dir}/lxd.db" "profiles" check_empty_table "${daemon_dir}/lxd.db" "profiles_config" check_empty_table "${daemon_dir}/lxd.db" "profiles_devices" check_empty_table "${daemon_dir}/lxd.db" "profiles_devices_config" fi # teardown storage "$lxd_backend"_teardown "${daemon_dir}" # Wipe the daemon directory wipe "${daemon_dir}" # Remove the daemon from the list sed "\|^${daemon_dir}|d" -i "${TEST_DIR}/daemons" } shutdown_lxd() { # LXD_DIR is local here because since $(lxc) is actually a function, it # overwrites the environment and we would lose LXD_DIR's value otherwise. # shellcheck disable=2039 local LXD_DIR daemon_dir=${1} # shellcheck disable=2034 LXD_DIR=${daemon_dir} daemon_pid=$(cat "${daemon_dir}/lxd.pid") echo "==> Killing LXD at ${daemon_dir}" # Kill the daemon lxd shutdown || kill -9 "${daemon_pid}" 2>/dev/null || true } wait_for() { # shellcheck disable=SC2039 local addr op addr=${1} shift op=$("$@" | jq -r .operation) my_curl "https://${addr}${op}/wait" } wipe() { if which btrfs >/dev/null 2>&1; then rm -Rf "${1}" 2>/dev/null || true if [ -d "${1}" ]; then find "${1}" | tac | xargs btrfs subvolume delete >/dev/null 2>&1 || true fi fi # shellcheck disable=SC2039 local pid # shellcheck disable=SC2009 ps aux | grep lxc-monitord | grep "${1}" | awk '{print $2}' | while read -r pid; do kill -9 "${pid}" || true done if mountpoint -q "${1}"; then umount "${1}" fi rm -Rf "${1}" } # Kill and cleanup LXD instances and related resources cleanup_lxds() { # shellcheck disable=SC2039 local test_dir daemon_dir test_dir="$1" # Kill all LXD instances while read -r daemon_dir; do kill_lxd "${daemon_dir}" done < "${test_dir}/daemons" # Wipe the test environment wipe "$test_dir" umount_loops "$test_dir" } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/includes/lxc.sh���������������������������������������������������������������������0000644�0610621�0607500�00000003061�13172163242�017400� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# lxc CLI related test helpers. lxc() { LXC_LOCAL=1 lxc_remote "$@" } lxc_remote() { set +x # shellcheck disable=SC2039 local injected cmd arg injected=0 cmd=$(which lxc) # shellcheck disable=SC2048,SC2068 for arg in $@; do if [ "${arg}" = "--" ]; then injected=1 cmd="${cmd} ${DEBUG:-}" [ -n "${LXC_LOCAL}" ] && cmd="${cmd} --force-local" cmd="${cmd} --" elif [ "${arg}" = "--force-local" ]; then continue else cmd="${cmd} \"${arg}\"" fi done if [ "${injected}" = "0" ]; then cmd="${cmd} ${DEBUG-}" fi if [ -n "${DEBUG:-}" ]; then set -x fi eval "${cmd}" } gen_cert() { # Temporarily move the existing cert to trick LXC into generating a # second cert. LXC will only generate a cert when adding a remote # server with a HTTPS scheme. The remote server URL just needs to # be syntactically correct to get past initial checks; in fact, we # don't want it to succeed, that way we don't have to delete it later. [ -f "${LXD_CONF}/${1}.crt" ] && return mv "${LXD_CONF}/client.crt" "${LXD_CONF}/client.crt.bak" mv "${LXD_CONF}/client.key" "${LXD_CONF}/client.key.bak" echo y | lxc_remote remote add "$(uuidgen)" https://0.0.0.0 || true mv "${LXD_CONF}/client.crt" "${LXD_CONF}/${1}.crt" mv "${LXD_CONF}/client.key" "${LXD_CONF}/${1}.key" mv "${LXD_CONF}/client.crt.bak" "${LXD_CONF}/client.crt" mv "${LXD_CONF}/client.key.bak" "${LXD_CONF}/client.key" } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/includes/check.sh�������������������������������������������������������������������0000644�0610621�0607500�00000001366�13172163242�017675� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Miscellanous test checks. check_dependencies() { # shellcheck disable=SC2039 local dep missing missing="" for dep in "$@"; do if ! which "$dep" >/dev/null 2>&1; then [ "$missing" ] && missing="$missing $dep" || missing="$dep" fi done if [ "$missing" ]; then echo "Missing dependencies: $missing" >&2 exit 1 fi } check_empty() { if [ "$(find "${1}" 2> /dev/null | wc -l)" -gt "1" ]; then echo "${1} is not empty, content:" find "${1}" false fi } check_empty_table() { if [ -n "$(sqlite3 "${1}" "SELECT * FROM ${2};")" ]; then echo "DB table ${2} is not empty, content:" sqlite3 "${1}" "SELECT * FROM ${2};" false fi } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/godeps.list�������������������������������������������������������������������������0000644�0610621�0607500�00000000634�13172163242�016631� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������github.com/golang/protobuf github.com/gorilla/websocket github.com/juju/go4 github.com/juju/httprequest github.com/juju/loggo github.com/juju/persistent-cookiejar github.com/juju/webbrowser github.com/julienschmidt/httprouter github.com/rogpeppe/fastuuid golang.org/x/crypto golang.org/x/net gopkg.in/errgo.v1 gopkg.in/macaroon-bakery.v2-unstable gopkg.in/macaroon.v2-unstable gopkg.in/retry.v1 gopkg.in/yaml.v2 ����������������������������������������������������������������������������������������������������lxd-2.0.11/test/extras/�����������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015756� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/extras/stresstest.sh����������������������������������������������������������������0000755�0610621�0607500�00000011463�13172163242�020545� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash export PATH=$GOPATH/bin:$PATH # /tmp isn't moutned exec on most systems, so we can't actually start # containers that are created there. export SRC_DIR=$(pwd) export LXD_DIR=$(mktemp -d -p $(pwd)) chmod 777 "${LXD_DIR}" export LXD_CONF=$(mktemp -d) export LXD_FUIDMAP_DIR=${LXD_DIR}/fuidmap mkdir -p ${LXD_FUIDMAP_DIR} BASEURL=https://127.0.0.1:18443 RESULT=failure set -e if [ -n "$LXD_DEBUG" ]; then set -x debug=--debug fi echo "==> Running the LXD testsuite" BASEURL=https://127.0.0.1:18443 my_curl() { curl -k -s --cert "${LXD_CONF}/client.crt" --key "${LXD_CONF}/client.key" $@ } wait_for() { op=$($@ | jq -r .operation) my_curl $BASEURL$op/wait } lxc() { INJECTED=0 CMD="$(which lxc)" for arg in $@; do if [ "$arg" = "--" ]; then INJECTED=1 CMD="$CMD $debug" CMD="$CMD --" else CMD="$CMD \"$arg\"" fi done if [ "$INJECTED" = "0" ]; then CMD="$CMD $debug" fi eval "$CMD" } cleanup() { read -p "Tests Completed ($RESULT): hit enter to continue" x echo "==> Cleaning up" # Try to stop all the containers my_curl "$BASEURL/1.0/containers" | jq -r .metadata[] 2>/dev/null | while read -r line; do wait_for my_curl -X PUT "$BASEURL$line/state" -d "{\"action\":\"stop\",\"force\":true}" done # kill the lxds which share our pgrp as parent mygrp=`awk '{ print $5 }' /proc/self/stat` for p in `pidof lxd`; do pgrp=`awk '{ print $5 }' /proc/$p/stat` if [ "$pgrp" = "$mygrp" ]; then do_kill_lxd $p fi done # Apparently we need to wait a while for everything to die sleep 3 rm -Rf ${LXD_DIR} rm -Rf ${LXD_CONF} echo "" echo "" echo "==> Test result: $RESULT" } trap cleanup EXIT HUP INT TERM if [ -z "`which lxc`" ]; then echo "==> Couldn't find lxc" && false fi spawn_lxd() { # LXD_DIR is local here because since `lxc` is actually a function, it # overwrites the environment and we would lose LXD_DIR's value otherwise. local LXD_DIR addr=$1 lxddir=$2 shift shift echo "==> Spawning lxd on $addr in $lxddir" LXD_DIR=$lxddir lxd ${DEBUG} $extraargs $* 2>&1 > $lxddir/lxd.log & echo "==> Confirming lxd on $addr is responsive" alive=0 while [ $alive -eq 0 ]; do [ -e "${lxddir}/unix.socket" ] && LXD_DIR=$lxddir lxc finger && alive=1 sleep 1s done echo "==> Binding to network" LXD_DIR=$lxddir lxc config set core.https_address $addr echo "==> Setting trust password" LXD_DIR=$lxddir lxc config set core.trust_password foo } spawn_lxd 127.0.0.1:18443 $LXD_DIR ## tests go here if [ ! -e "$LXD_TEST_IMAGE" ]; then echo "Please define LXD_TEST_IMAGE" false fi lxc image import $LXD_TEST_IMAGE --alias busybox lxc image list lxc list NUMCREATES=5 createthread() { echo "createthread: I am $$" for i in `seq 1 $NUMCREATES`; do echo "createthread: starting loop $i out of $NUMCREATES" declare -a pids for j in `seq 1 20`; do lxc launch busybox b.$i.$j & pids[$j]=$! done for j in `seq 1 20`; do # ignore errors if the task has already exited wait ${pids[$j]} 2>/dev/null || true done echo "createthread: deleting..." for j in `seq 1 20`; do lxc delete b.$i.$j & pids[$j]=$! done for j in `seq 1 20`; do # ignore errors if the task has already exited wait ${pids[$j]} 2>/dev/null || true done done exit 0 } listthread() { echo "listthread: I am $$" while [ 1 ]; do lxc list sleep 2s done exit 0 } configthread() { echo "configthread: I am $$" for i in `seq 1 20`; do lxc profile create p$i lxc profile set p$i limits.memory 100MB lxc profile delete p$i done exit 0 } disturbthread() { echo "disturbthread: I am $$" while [ 1 ]; do lxc profile create empty lxc init busybox disturb1 lxc profile apply disturb1 empty lxc start disturb1 lxc exec disturb1 -- ps -ef lxc stop disturb1 --force lxc delete disturb1 lxc profile delete empty done exit 0 } echo "Starting create thread" createthread 2>&1 | tee $LXD_DIR/createthread.out & p1=$! echo "starting the disturb thread" disturbthread 2>&1 | tee $LXD_DIR/disturbthread.out & pdisturb=$! echo "Starting list thread" listthread 2>&1 | tee $LXD_DIR/listthread.out & p2=$! echo "Starting config thread" configthread 2>&1 | tee $LXD_DIR/configthread.out & p3=$! # wait for listthread to finish wait $p1 # and configthread, it should be quick wait $p3 echo "The creation loop is done, killing the list and disturb threads" kill $p2 wait $p2 || true kill $pdisturb wait $pdisturb || true RESULT=success �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/extras/speedtest_delete.sh����������������������������������������������������������0000755�0610621�0607500�00000000723�13172163242�021641� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash MYDIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) CIMAGE="testimage" CNAME="speedtest" count=${1} if [ "x${count}" == "x" ]; then echo "USAGE: ${0} 10" echo "This deletes 10 busybox containers" exit 1 fi if [ "x${2}" != "xnotime" ]; then time ${0} ${count} notime exit 0 fi PIDS="" for c in $(seq 1 $count); do lxc delete "${CNAME}${c}" 2>&1 & PIDS="$PIDS $!" done for pid in $PIDS; do wait $pid done echo -e "\nRun completed" ���������������������������������������������lxd-2.0.11/test/extras/speedtest_create.sh����������������������������������������������������������0000755�0610621�0607500�00000001410�13172163242�021634� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash MYDIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) CIMAGE="testimage" CNAME="speedtest" count=${1} if [ "x${count}" == "x" ]; then echo "USAGE: ${0} 10" echo "This creates 10 busybox containers" exit 1 fi if [ "x${2}" != "xnotime" ]; then time ${0} ${count} notime exit 0 fi ${MYDIR}/deps/import-busybox --alias busybox PIDS="" for c in $(seq 1 $count); do lxc init busybox "${CNAME}${c}" 2>&1 & PIDS="$PIDS $!" done for pid in $PIDS; do wait $pid done echo -e "\nlxc list: All shutdown" time lxc list 1>/dev/null PIDS="" for c in $(seq 1 $count); do lxc start "${CNAME}${c}" 2>&1 & PIDS="$PIDS $!" done for pid in $PIDS; do wait $pid done echo -e "\nlxc list: All started" time lxc list 1>/dev/null echo -e "\nRun completed" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/deps/�������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015403� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/deps/server.key���������������������������������������������������������������������0000644�0610621�0607500�00000006253�13172163242�017431� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������-----BEGIN RSA PRIVATE KEY----- MIIJKAIBAAKCAgEAyViJkCzoxa1NYilXqGJog6xzlSm4xt8KIzayc0JdB9VxEdIV dJqUzBAUtyCS4KZ9MbPmMEOX9NbBASL0tRK58/7KScq99Kj4XbVMLU1P/y5aW0ym nF0OpKbG6unmgAI2k/duRlbYHvGRdhlswpKl0Ystl8i2kXOK0Rxcz90FewcEXGSn IYW21sz8YpBLfIZqOx6XEV36mOdi3MLrhUSAhXDwPay33Y7NonCQUBtiO7BT938c qI14FJrWdKon1UnODtzONcVBLTWtoe7D41+mx7EETaq5OPxBSe0DD6KQcPOZ7ZSJ EhIqVKMvzLyiOJpyShmhm4OuGNoAG6jAuSij/9KcaLU4IitcrvFOuAo8M9OpiY9Z CR7Gb/qaPAXPAxE7Ci3f9DDNKXtPXDjhj3YG01+hfNXMW3kCkMImn0A/+mZUMdCL 87GWN2AN3Do5qaIc5XVEt1gp+LVqJeMoZ/lAeZWTIbzcnkneOzE25m+bjw3r3WlR 26amhyrWNwjGzRkgfEpw336kniX/GmwaCNgdNk+g5aIbVxIHO0DbgkDBtdljR3VO ic4djW/LtUIYIQ2egnPPyRR3fcFI+x5EQdVQYUXfjpGIwovUDyG0Lkam2tpdeEXv LMZr8+Lhzu+H6vUFSj3cz6gcw/Xepw40FOkYdAI9LYB6nwpZLTVaOqZCJ2ECAwEA AQKCAgBCe8GwoaOa4kaTCyOurg/kqqTftA8XW751MjJqbJdbZtcXE0+SWRiY6RZu AYt+MntUVhrEBQ3AAsloHqq+v5g3QQJ6qz9d8g1Qo/SrYMPxdtTPINhC+VdEdu1n 1CQQUKrE4QbAoxxp20o0vOB0vweR0WsUm2ntTUGhGsRqvoh4vzBpcbLeFtDwzG7p /MtwKtIZA1jOm0GMC5tRWet67cuiRFCPjOCJgAXWhWShjuk43FhdeNN1tIDaDOaT Tzwn6V7o+W/9wUxsKTVUKwrzoTno5kKNgrn2XxUP2/sOxpb7NPS2xj0cgnMHz3qR GBhYqGbkoOID/88U1acDew1oFktQL24yd8/cvooh7KLN3k5oSKjpKmGAKaMMwsSv ccRSM9EkTtgTANLpSFiVF738drZw7UXUsvVTCF8WHhMtGD50XOahR02D1kZnpqpe SdxJ9qFNEeozk6w56cTerJNz4od18/gQtNADcPI6WE+8NBrqYjN/X4CBNS76IEtp 5ddGbi6+4HgO5B0pU87f2bZH4BwR8XJ07wdMRyXXhmnKcnirkyqUtgHmLF3LZnGX +Fph5KmhBGs/ZovBvnBI2nREsMfNvzffK7x3hyFXv6J+XxILk4i3LkgKLJFC+RY0 sjWNQB5tHuA1dbq3AtsbfJcTK764kSaUsq0JoqPQgiSuiNoCIQKCAQEA1Fk4SR5I H1QHlXeQ/k1sg6B5H0uosPAnAQxjuI8SvYkty+b4diP+CJIS4IphgLIItROORUFE bOi6pj2D2oK04J55fhlJaE8LQs7i90nFXT4B09Ut4oBYGCz5aE/wAUxUanaq1dxj K17y+ejlqh7yKTwupHOvIm4ddDwU1U5H9J/Cyywvp5fznVIGMJynVk7zriXYM6aC tioNCbOTHwQxjYEaG3AwymXaI6sNwdNiAzgq6M7v43GF3IOj8SYK2VhVdLqLJPnL 6G5OqMRxxQtxOcSctFOuicu+Jq/KVWJGDaERQZJloHcBJCtO34ONswGJqC/PGoU+ Ny/BOaZdLQDIpwKCAQEA8rxOKaLuOWEi4MDJuAgQYqpO9JxY0h3yN1YrspBuGezR 4Lzdh0vUh9Jr4npV723gGwA7r8AcqIPZvSk8MmcYVuwoxz9VWYeNP8P6cRc3bDO8 shnSvFxV32gKTEH8fOH3/BlJOnbn62tebSFHnGxyh2WPsRbzAMOKj9Q3Yq6ad3DD 6rJhtopIedC3AWc3aVeO2FHPC+Lza0PhUVsHf5X7Bg+zQlHaaEXB0lysruXkDlU9 WdW+Ajvo0enhOROgEa7QBC74NsKZF4KJGMGTaglydRtVYbqfx4QbfgDU5h2zaUnB lRINZvKNYGRXDN944ymynE9bo4xfOERbWc68GFaItwKCAQBCY+qvIaKW+OSuHIXe nEJTHPcBi9wgBdWMBF2hNEo9rAf/eiUweqxP7autPFajsAX85zJSAMft7Q1+MDlr NfZrS+DcRfenfx8cMibP/eaQ8nQL0NjZuhrQ5C7OKD/3h+/UoWlkF9WBl9wLun8j oy0/KyvCCtE0yIy47Jfu4NyqZNC4SQZVNbLa+uwogrHm0CRrzDU+YM75OUh+QgC7 b8o2XajV70ux3ApJoI9ajEZWj1cLFrf1umaJvTaijKxTq8R8DF64nsjb0LETHugb HSq3TvtXfdpSBrtayRdPfrw8QqFsiOLxOoPG1SuBwlWpI8/wH5J2zjXXdzzIU3VK PrZ9AoIBAQDazTjbuT1pxZCN7donJEW42nHPdvttc4b5sJg1HpHQlrNdFIHPyl/q iperD8FU0MM5M42Zz99FW4yzQW88s8ex2rCrYgCKcnC1cO/YbygLRduq4zIdjlHt zrexo6132K0TtqtWowZNJHx6fIwziWH3gGn1JI2pO5o0KgQ+1MryLVi8v0zrIV1R SP0dq6+8Kivd/GhY+5uWLhr1nct1i3k6Ln7Uojnw0ihzegxCn4FiFh32U4AyPVSR m3PkYjdgmSZzDu+5VNJw6b6w7RT3eUqOGzRsorASRZgOjatbPpyRpOV1fU9NZAhi QjBhrzMl+VlCIxqkowzWCHAb1QmiGqajAoIBAGYKD5h7jTgPFKFlMViTg8LoMcQl 9vbpmWkB+WdY5xXOwO0hO99rFDmLx6elsmYjdpq8zJkOFTnSB2o3IpenxZltNMsI +aDlZWxDxokTxr6gbQPPrjePT1oON0/6sLEYkDOln8H1P9jmLPqTrET0DxCMgE5D NE9TAEuUKVhRTWy6FSdP58hUimyVnlbnvbGOh2tviNO+TK/H7k0WjRg57Sz9XTHO q36ob5TEsQngkTATEoksE9xhXFxtmTm/nu/26wN2Py49LSwu2aAYTfX/KhQKklNX P/tP5//z+hGeba8/xv8YhEr7vhbnlBdwp0wHJj5g7nHAbYfo9ELbXSON8wc= -----END RSA PRIVATE KEY----- �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/deps/server.crt���������������������������������������������������������������������0000644�0610621�0607500�00000004032�13172163242�017422� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������-----BEGIN CERTIFICATE----- MIIFzjCCA7igAwIBAgIRAKnCQRdpkZ86oXYOd9hGrPgwCwYJKoZIhvcNAQELMB4x HDAaBgNVBAoTE2xpbnV4Y29udGFpbmVycy5vcmcwHhcNMTUwNzE1MDQ1NjQ0WhcN MjUwNzEyMDQ1NjQ0WjAeMRwwGgYDVQQKExNsaW51eGNvbnRhaW5lcnMub3JnMIIC IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAyViJkCzoxa1NYilXqGJog6xz lSm4xt8KIzayc0JdB9VxEdIVdJqUzBAUtyCS4KZ9MbPmMEOX9NbBASL0tRK58/7K Scq99Kj4XbVMLU1P/y5aW0ymnF0OpKbG6unmgAI2k/duRlbYHvGRdhlswpKl0Yst l8i2kXOK0Rxcz90FewcEXGSnIYW21sz8YpBLfIZqOx6XEV36mOdi3MLrhUSAhXDw Pay33Y7NonCQUBtiO7BT938cqI14FJrWdKon1UnODtzONcVBLTWtoe7D41+mx7EE Taq5OPxBSe0DD6KQcPOZ7ZSJEhIqVKMvzLyiOJpyShmhm4OuGNoAG6jAuSij/9Kc aLU4IitcrvFOuAo8M9OpiY9ZCR7Gb/qaPAXPAxE7Ci3f9DDNKXtPXDjhj3YG01+h fNXMW3kCkMImn0A/+mZUMdCL87GWN2AN3Do5qaIc5XVEt1gp+LVqJeMoZ/lAeZWT IbzcnkneOzE25m+bjw3r3WlR26amhyrWNwjGzRkgfEpw336kniX/GmwaCNgdNk+g 5aIbVxIHO0DbgkDBtdljR3VOic4djW/LtUIYIQ2egnPPyRR3fcFI+x5EQdVQYUXf jpGIwovUDyG0Lkam2tpdeEXvLMZr8+Lhzu+H6vUFSj3cz6gcw/Xepw40FOkYdAI9 LYB6nwpZLTVaOqZCJ2ECAwEAAaOCAQkwggEFMA4GA1UdDwEB/wQEAwIAoDATBgNV HSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMIHPBgNVHREEgccwgcSCCVVi dW50dVByb4IRMTAuMTY3LjE2MC4xODMvMjSCHzIwMDE6MTVjMDo2NzM1OmVlMDA6 OmU6ZTMxMy8xMjiCKWZkNTc6Yzg3ZDpmMWVlOmVlMDA6MjFkOjdkZmY6ZmUwOToz NzUzLzY0gikyMDAxOjE1YzA6NjczNTplZTAwOjIxZDo3ZGZmOmZlMDk6Mzc1My82 NIIbZmU4MDo6MjFkOjdkZmY6ZmUwOTozNzUzLzY0ghAxOTIuMTY4LjEyMi4xLzI0 MAsGCSqGSIb3DQEBCwOCAgEAmcJUSBH7cLw3auEEV1KewtdqY1ARVB/pafAtbe9F 7ZKBbxUcS7cP3P1hRs5FH1bH44bIJKHxckctNUPqvC+MpXSryKinQ5KvGPNjGdlW 6EPlQr23btizC6hRdQ6RjEkCnQxhyTLmQ9n78nt47hjA96rFAhCUyfPdv9dI4Zux bBTJekhCx5taamQKoxr7tql4Y2TchVlwASZvOfar8I0GxBRFT8w9IjckOSLoT9/s OhlvXpeoxxFT7OHwqXEXdRUvw/8MGBo6JDnw+J/NGDBw3Z0goebG4FMT//xGSHia czl3A0M0flk4/45L7N6vctwSqi+NxVaJRKeiYPZyzOO9K/d+No+WVBPwKmyP8icQ b7FGTelPJOUolC6kmoyM+vyaNUoU4nz6lgOSHAtuqGNDWZWuX/gqzZw77hzDIgkN qisOHZWPVlG/iUh1JBkbglBaPeaa3zf0XwSdgwwf4v8Z+YtEiRqkuFgQY70eQKI/ CIkj1p0iW5IBEsEAGUGklz4ZwqJwH3lQIqDBzIgHe3EP4cXaYsx6oYhPSDdHLPv4 HMZhl05DP75CEkEWRD0AIaL7SHdyuYUmCZ2zdrMI7TEDrAqcUuPbYpHcdJ2wnYmi 2G8XHJibfu4PCpIm1J8kPL8rqpdgW3moKR8Mp0HJQOH4tSBr1Ep7xNLP1wg6PIe+ p7U= -----END CERTIFICATE----- ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/deps/schema1.sql��������������������������������������������������������������������0000644�0610621�0607500�00000003100�13172163242�017437� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������-- Database schema version 1 as taken from febb96e8164fbd189698da77383c26ce68b9762a CREATE TABLE certificates ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fingerprint VARCHAR(255) NOT NULL, type INTEGER NOT NULL, name VARCHAR(255) NOT NULL, certificate TEXT NOT NULL, UNIQUE (fingerprint) ); CREATE TABLE containers ( id INTEGER primary key AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, architecture INTEGER NOT NULL, type INTEGER NOT NULL, UNIQUE (name) ); CREATE TABLE containers_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_id) REFERENCES containers (id), UNIQUE (container_id, key) ); CREATE TABLE images ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fingerprint VARCHAR(255) NOT NULL, filename VARCHAR(255) NOT NULL, size INTEGER NOT NULL, public INTEGER NOT NULL DEFAULT 0, architecture INTEGER NOT NULL, creation_date DATETIME, expiry_date DATETIME, upload_date DATETIME NOT NULL, UNIQUE (fingerprint) ); CREATE TABLE images_properties ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, image_id INTEGER NOT NULL, type INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (image_id) REFERENCES images (id) ); CREATE TABLE schema ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, version INTEGER NOT NULL, updated_at DATETIME NOT NULL, UNIQUE (version) ); INSERT INTO schema (version, updated_at) values (1, "now"); ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/deps/import-busybox�����������������������������������������������������������������0000755�0610621�0607500�00000032352�13172163242�020341� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 import argparse import atexit import hashlib import http.client import io import json import os import shutil import socket import subprocess import sys import tarfile import tempfile import uuid class FriendlyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('\nerror: %s\n' % message) self.print_help() sys.exit(2) def find_on_path(command): """Is command on the executable search path?""" if 'PATH' not in os.environ: return False path = os.environ['PATH'] for element in path.split(os.pathsep): if not element: continue filename = os.path.join(element, command) if os.path.isfile(filename) and os.access(filename, os.X_OK): return True return False class UnixHTTPConnection(http.client.HTTPConnection): def __init__(self, path): http.client.HTTPConnection.__init__(self, 'localhost') self.path = path def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(self.path) self.sock = sock class LXD(object): workdir = None def __init__(self, path): self.lxd = UnixHTTPConnection(path) # Create our workdir self.workdir = tempfile.mkdtemp() atexit.register(self.cleanup) def cleanup(self): if self.workdir: shutil.rmtree(self.workdir) def rest_call(self, path, data=None, method="GET", headers={}): if method == "GET" and data: self.lxd.request( method, "%s?%s" % "&".join(["%s=%s" % (key, value) for key, value in data.items()]), headers) else: self.lxd.request(method, path, data, headers) r = self.lxd.getresponse() d = json.loads(r.read().decode("utf-8")) return r.status, d def aliases_create(self, name, target): data = json.dumps({"target": target, "name": name}) status, data = self.rest_call("/1.0/images/aliases", data, "POST") if status not in (200, 201): raise Exception("Failed to create alias: %s" % name) def aliases_remove(self, name): status, data = self.rest_call("/1.0/images/aliases/%s" % name, method="DELETE") if status != 200: raise Exception("Failed to remove alias: %s" % name) def aliases_list(self): status, data = self.rest_call("/1.0/images/aliases") return [alias.split("/1.0/images/aliases/")[-1] for alias in data['metadata']] def images_list(self, recursive=False): if recursive: status, data = self.rest_call("/1.0/images?recursion=1") return data['metadata'] else: status, data = self.rest_call("/1.0/images") return [image.split("/1.0/images/")[-1] for image in data['metadata']] def images_upload(self, path, public, filename=None): headers = {} if public: headers['X-LXD-public'] = "1" if isinstance(path, str): headers['Content-Type'] = "application/octet-stream" status, data = self.rest_call("/1.0/images", open(path, "rb"), "POST", headers) else: meta_path, rootfs_path = path boundary = str(uuid.uuid1()) filename_entry = " filename=%s" % filename if filename else "" upload_path = os.path.join(self.workdir, "upload") body = open(upload_path, "wb+") for name, path in [("metadata", meta_path), ("rootfs", rootfs_path)]: body.write(bytes("--%s\r\n" % boundary, "utf-8")) body.write(bytes("Content-Disposition: form-data; " "name=%s;%s\r\n" % (name, filename_entry), "utf-8")) body.write(b"Content-Type: application/octet-stream\r\n") body.write(b"\r\n") with open(path, "rb") as fd: shutil.copyfileobj(fd, body) body.write(b"\r\n") body.write(bytes("--%s--\r\n" % boundary, "utf-8")) body.write(b"\r\n") body.close() headers['Content-Type'] = "multipart/form-data; boundary=%s" \ % boundary status, data = self.rest_call("/1.0/images", open(upload_path, "rb"), "POST", headers) if status != 202: raise Exception("Failed to upload the image: %s" % status) status, data = self.rest_call(data['operation'] + "/wait", "", "GET", {}) if status != 200: raise Exception("Failed to query the operation: %s" % status) if data['status_code'] != 200: raise Exception("Failed to import the image: %s" % data['metadata']) return data['metadata']['metadata'] class Busybox(object): workdir = None def __init__(self): # Create our workdir self.workdir = tempfile.mkdtemp() atexit.register(self.cleanup) def cleanup(self): if self.workdir: shutil.rmtree(self.workdir) def create_tarball(self, split=False, template=[]): xz = "pxz" if find_on_path("pxz") else "xz" destination_tar = os.path.join(self.workdir, "busybox.tar") target_tarball = tarfile.open(destination_tar, "w:") if split: destination_tar_rootfs = os.path.join(self.workdir, "busybox.rootfs.tar") target_tarball_rootfs = tarfile.open(destination_tar_rootfs, "w:") metadata = {'architecture': os.uname()[4], 'creation_date': int(os.stat("/bin/busybox").st_ctime), 'properties': { 'os': "Busybox", 'architecture': os.uname()[4], 'description': "Busybox %s" % os.uname()[4], 'name': "busybox-%s" % os.uname()[4] }, } # Add busybox with open("/bin/busybox", "rb") as fd: busybox_file = tarfile.TarInfo() busybox_file.size = os.stat("/bin/busybox").st_size busybox_file.mode = 0o755 if split: busybox_file.name = "bin/busybox" target_tarball_rootfs.addfile(busybox_file, fd) else: busybox_file.name = "rootfs/bin/busybox" target_tarball.addfile(busybox_file, fd) # Add symlinks busybox = subprocess.Popen(["/bin/busybox", "--list-full"], stdout=subprocess.PIPE, universal_newlines=True) busybox.wait() for path in busybox.stdout.read().split("\n"): if not path.strip(): continue symlink_file = tarfile.TarInfo() symlink_file.type = tarfile.SYMTYPE symlink_file.linkname = "/bin/busybox" if split: symlink_file.name = "%s" % path.strip() target_tarball_rootfs.addfile(symlink_file) else: symlink_file.name = "rootfs/%s" % path.strip() target_tarball.addfile(symlink_file) # Add directories for path in ("dev", "mnt", "proc", "root", "sys", "tmp"): directory_file = tarfile.TarInfo() directory_file.type = tarfile.DIRTYPE if split: directory_file.name = "%s" % path target_tarball_rootfs.addfile(directory_file) else: directory_file.name = "rootfs/%s" % path target_tarball.addfile(directory_file) # Deal with templating if template: metadata["templates"] = { "/template": { "when": template, "template": "template.tpl"}} directory_file = tarfile.TarInfo() directory_file.type = tarfile.DIRTYPE directory_file.name = "templates" target_tarball.addfile(directory_file) template = """name: {{ container.name }} architecture: {{ container.architecture }} privileged: {{ container.privileged }} ephemeral: {{ container.ephemeral }} trigger: {{ trigger }} path: {{ path }} user.foo: {{ config_get("user.foo", "_unset_") }} """ template_file = tarfile.TarInfo() template_file.size = len(template) template_file.name = "templates/template.tpl" target_tarball.addfile(template_file, io.BytesIO(template.encode())) # Add the metadata file metadata_yaml = json.dumps(metadata, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False).encode('utf-8') + b"\n" metadata_file = tarfile.TarInfo() metadata_file.size = len(metadata_yaml) metadata_file.name = "metadata.yaml" target_tarball.addfile(metadata_file, io.BytesIO(metadata_yaml)) # Add an /etc/inittab; this is to work around: # http://lists.busybox.net/pipermail/busybox/2015-November/083618.html # Basically, since there are some hardcoded defaults that misbehave, we # just pass an empty inittab so those aren't applied, and then busybox # doesn't spin forever. inittab = tarfile.TarInfo() inittab.size = 1 inittab.name = "/rootfs/etc/inittab" target_tarball.addfile(inittab, io.BytesIO(b"\n")) target_tarball.close() if split: target_tarball_rootfs.close() # Compress the tarball r = subprocess.call([xz, "-9", destination_tar]) if r: raise Exception("Failed to compress: %s" % destination_tar) if split: r = subprocess.call([xz, "-9", destination_tar_rootfs]) if r: raise Exception("Failed to compress: %s" % destination_tar_rootfs) return destination_tar + ".xz", destination_tar_rootfs + ".xz" else: return destination_tar + ".xz" if __name__ == "__main__": if "LXD_DIR" in os.environ: lxd_socket = os.path.join(os.environ['LXD_DIR'], "unix.socket") else: lxd_socket = "/var/lib/lxd/unix.socket" if not os.path.exists(lxd_socket): print("LXD isn't running.") sys.exit(1) lxd = LXD(lxd_socket) def setup_alias(aliases, fingerprint): existing = lxd.aliases_list() for alias in aliases: if alias in existing: lxd.aliases_remove(alias) lxd.aliases_create(alias, fingerprint) print("Setup alias: %s" % alias) def import_busybox(parser, args): busybox = Busybox() if args.split: meta_path, rootfs_path = busybox.create_tarball( split=True, template=args.template.split(",")) with open(meta_path, "rb") as meta_fd: with open(rootfs_path, "rb") as rootfs_fd: fingerprint = hashlib.sha256(meta_fd.read() + rootfs_fd.read()).hexdigest() if fingerprint in lxd.images_list(): parser.exit(1, "This image is already in the store.\n") if args.filename: r = lxd.images_upload((meta_path, rootfs_path), args.public, meta_path.split("/")[-1]) else: r = lxd.images_upload((meta_path, rootfs_path), args.public) print("Image imported as: %s" % r['fingerprint']) else: path = busybox.create_tarball(template=args.template.split(",")) with open(path, "rb") as fd: fingerprint = hashlib.sha256(fd.read()).hexdigest() if fingerprint in lxd.images_list(): parser.exit(1, "This image is already in the store.\n") r = lxd.images_upload(path, args.public) print("Image imported as: %s" % r['fingerprint']) setup_alias(args.alias, fingerprint) parser = FriendlyParser(description="Import a busybox image") parser.add_argument("--alias", action="append", default=[], help="Aliases for the image") parser.add_argument("--public", action="store_true", default=False, help="Make the image public") parser.add_argument("--split", action="store_true", default=False, help="Whether to create a split image") parser.add_argument("--filename", action="store_true", default=False, help="Set the split image's filename") parser.add_argument("--template", type=str, default="", help="Trigger test template") parser.set_defaults(func=import_busybox) # Call the function args = parser.parse_args() try: args.func(parser, args) except Exception as e: parser.error(e) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/deps/devlxd-client.go���������������������������������������������������������������0000644�0610621�0607500�00000003001�13172163242�020466� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main /* * An example of how to use lxd's golang /dev/lxd client. This is intended to * be run from inside a container. */ import ( "encoding/json" "fmt" "io/ioutil" "net" "net/http" "os" ) type devLxdDialer struct { Path string } func (d devLxdDialer) devLxdDial(network, path string) (net.Conn, error) { addr, err := net.ResolveUnixAddr("unix", d.Path) if err != nil { return nil, err } conn, err := net.DialUnix("unix", nil, addr) if err != nil { return nil, err } return conn, err } var devLxdTransport = &http.Transport{ Dial: devLxdDialer{"/dev/lxd/sock"}.devLxdDial, } func main() { c := http.Client{Transport: devLxdTransport} raw, err := c.Get("http://meshuggah-rocks/") if err != nil { fmt.Println(err) os.Exit(1) } if raw.StatusCode != http.StatusOK { fmt.Println("http error", raw.StatusCode) result, err := ioutil.ReadAll(raw.Body) if err == nil { fmt.Println(string(result)) } os.Exit(1) } result := []string{} if err := json.NewDecoder(raw.Body).Decode(&result); err != nil { fmt.Println("err decoding response", err) os.Exit(1) } if result[0] != "/1.0" { fmt.Println("unknown response", result) os.Exit(1) } if len(os.Args) > 1 { raw, err := c.Get(fmt.Sprintf("http://meshuggah-rocks/1.0/config/%s", os.Args[1])) if err != nil { fmt.Println(err) os.Exit(1) } value, err := ioutil.ReadAll(raw.Body) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Println(string(value)) } else { fmt.Println("/dev/lxd ok") } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/backends/���������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016222� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/backends/zfs.sh���������������������������������������������������������������������0000644�0610621�0607500�00000002506�13172163242�017363� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������zfs_setup() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Setting up ZFS backend in ${LXD_DIR}" truncate -s 100G "${LXD_DIR}/zfspool" # prefix lxdtest- here, as zfs pools must start with a letter, but tempdir # won't necessarily generate one that does. zpool create "lxdtest-$(basename "${LXD_DIR}")" "${LXD_DIR}/zfspool" -m none } zfs_configure() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Configuring ZFS backend in ${LXD_DIR}" lxc config set storage.zfs_pool_name "lxdtest-$(basename "${LXD_DIR}")" # Avoid a zfs bug in "-p" handling during concurent create zfs create -p -o mountpoint=none "lxdtest-$(basename "${LXD_DIR}")/containers" zfs create -p -o mountpoint=none "lxdtest-$(basename "${LXD_DIR}")/images" } zfs_teardown() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Tearing down ZFS backend in ${LXD_DIR}" # Wait up to 5s for zpool destroy to succeed SUCCESS=0 # shellcheck disable=SC2034 for i in $(seq 10); do zpool destroy -f "lxdtest-$(basename "${LXD_DIR}")" >/dev/null 2>&1 || true if ! zpool list -o name -H | grep -q "^lxdtest-$(basename "${LXD_DIR}")"; then SUCCESS=1 break fi sleep 0.5 done if [ "${SUCCESS}" = "0" ]; then echo "Failed to destroy the zpool" false fi } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/backends/lvm.sh���������������������������������������������������������������������0000644�0610621�0607500�00000002653�13172163242�017362� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lvm_setup() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Setting up lvm backend in ${LXD_DIR}" truncate -s 4G "${TEST_DIR}/$(basename "${LXD_DIR}").lvm" pvloopdev=$(losetup --show -f "${TEST_DIR}/$(basename "${LXD_DIR}").lvm") if [ ! -e "${pvloopdev}" ]; then echo "failed to setup loop" false fi echo "${pvloopdev}" > "${TEST_DIR}/$(basename "${LXD_DIR}").lvm.vg" pvcreate "${pvloopdev}" vgcreate "lxdtest-$(basename "${LXD_DIR}")" "${pvloopdev}" } lvm_configure() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Configuring lvm backend in ${LXD_DIR}" lxc config set storage.lvm_volume_size "10Mib" lxc config set storage.lvm_vg_name "lxdtest-$(basename "${LXD_DIR}")" } lvm_teardown() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Tearing down lvm backend in ${LXD_DIR}" SUCCESS=0 # shellcheck disable=SC2034 for i in $(seq 10); do vgremove -f "lxdtest-$(basename "${LXD_DIR}")" >/dev/null 2>&1 || true pvremove -f "$(cat "${TEST_DIR}/$(basename "${LXD_DIR}").lvm.vg")" >/dev/null 2>&1 || true if losetup -d "$(cat "${TEST_DIR}/$(basename "${LXD_DIR}").lvm.vg")"; then SUCCESS=1 break fi sleep 0.5 done if [ "${SUCCESS}" = "0" ]; then echo "Failed to tear down LVM" false fi rm -f "${TEST_DIR}/$(basename "${LXD_DIR}").lvm" rm -f "${TEST_DIR}/$(basename "${LXD_DIR}").lvm.vg" } �������������������������������������������������������������������������������������lxd-2.0.11/test/backends/dir.sh���������������������������������������������������������������������0000644�0610621�0607500�00000001257�13172163242�017341� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Nothing need be done for the dir backed, but we still need some functions. # This file can also serve as a skel file for what needs to be done to # implement a new backend. # Any necessary backend-specific setup dir_setup() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Setting up directory backend in ${LXD_DIR}" } # Do the API voodoo necessary to configure LXD to use this backend dir_configure() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Configuring directory backend in ${LXD_DIR}" } dir_teardown() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Tearing down directory backend in ${LXD_DIR}" } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/backends/btrfs.sh�������������������������������������������������������������������0000644�0610621�0607500�00000001244�13172163242�017677� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������btrfs_setup() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Setting up btrfs backend in ${LXD_DIR}" truncate -s 100G "${TEST_DIR}/$(basename "${LXD_DIR}").btrfs" mkfs.btrfs "${TEST_DIR}/$(basename "${LXD_DIR}").btrfs" mount -o loop "${TEST_DIR}/$(basename "${LXD_DIR}").btrfs" "${LXD_DIR}" } btrfs_configure() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Configuring btrfs backend in ${LXD_DIR}" } btrfs_teardown() { # shellcheck disable=2039 local LXD_DIR LXD_DIR=$1 echo "==> Tearing down btrfs backend in ${LXD_DIR}" umount -l "${LXD_DIR}" rm -f "${TEST_DIR}/$(basename "${LXD_DIR}").btrfs" } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/test/README.md���������������������������������������������������������������������������0000644�0610621�0607500�00000002432�13172163242�015730� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# How to run To run all tests, including the Go tests, run from repository root: sudo -E make check To run only the integration tests, run from the test directory: sudo -E ./main.sh # Environment variables Name | Default | Description :-- | :--- | :---------- LXD\_BACKEND | dir | What backend to test against (btrfs, dir, lvm, zfs, or random) LXD\_CONCURRENT | 0 | Run concurrency tests, very CPU intensive LXD\_DEBUG | 0 | Run lxd, lxc and the shell in debug mode (very verbose) LXD\_INSPECT | 0 | Don't teardown the test environment on failure LXD\_LOGS | "" | Path to a directory to copy all the LXD logs to LXD\_OFFLINE | 0 | Skip anything that requires network access LXD\_TEST\_IMAGE | "" (busybox test image) | Path to an image tarball to use instead of the default busybox image LXD\_TMPFS | 0 | Sets up a tmpfs for the whole testsuite to run on (fast but needs memory) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/����������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014737� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/version/��������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016424� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/version/platform_others.go��������������������������������������������������������0000644�0610621�0607500�00000000144�13172163242�022162� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !linux package version func getPlatformVersionStrings() []string { return []string{} } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/version/platform_linux.go���������������������������������������������������������0000644�0610621�0607500�00000001114�13172163242�022013� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux package version import ( "strings" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/osarch" ) func getPlatformVersionStrings() []string { versions := []string{} // add kernel version uname, err := shared.Uname() if err == nil { versions = append(versions, strings.Split(uname.Release, "-")[0]) } // add distribution info lsbRelease, err := osarch.GetLSBRelease() if err == nil { for _, key := range []string{"NAME", "VERSION_ID"} { value, ok := lsbRelease[key] if ok { versions = append(versions, value) } } } return versions } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/version/flex.go�������������������������������������������������������������������0000644�0610621�0607500�00000001354�13172163242�017714� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package version import ( "fmt" "runtime" "strings" "github.com/lxc/lxd/shared/osarch" ) // Version contains the LXD version number var Version = "2.0.11" // UserAgent contains a string suitable as a user-agent var UserAgent = getUserAgent() // APIVersion contains the API base version. Only bumped for backward incompatible changes. var APIVersion = "1.0" func getUserAgent() string { archID, err := osarch.ArchitectureId(runtime.GOARCH) if err != nil { panic(err) } arch, err := osarch.ArchitectureName(archID) if err != nil { panic(err) } tokens := []string{strings.Title(runtime.GOOS), arch} tokens = append(tokens, getPlatformVersionStrings()...) return fmt.Sprintf("LXD %s (%s)", Version, strings.Join(tokens, "; ")) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/util_windows.go�������������������������������������������������������������������0000644�0610621�0607500�00000000223�13172163242�020012� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build windows package shared import ( "os" ) func GetOwnerMode(fInfo os.FileInfo) (os.FileMode, int, int) { return fInfo.Mode(), -1, -1 } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/util_unix.go����������������������������������������������������������������������0000644�0610621�0607500�00000000415�13172163242�017306� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows package shared import ( "os" "syscall" ) func GetOwnerMode(fInfo os.FileInfo) (os.FileMode, int, int) { mode := fInfo.Mode() uid := int(fInfo.Sys().(*syscall.Stat_t).Uid) gid := int(fInfo.Sys().(*syscall.Stat_t).Gid) return mode, uid, gid } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/util_test.go����������������������������������������������������������������������0000644�0610621�0607500�00000003476�13172163242�017314� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared import ( "bytes" "crypto/rand" "fmt" "io/ioutil" "os" "testing" ) func TestURLEncode(t *testing.T) { url, _ := URLEncode( "/path/with spaces", map[string]string{"param": "with spaces", "other": "without"}) expected := "/path/with%20spaces?other=without&param=with+spaces" if url != expected { t.Error(fmt.Errorf("'%s' != '%s'", url, expected)) } } func TestFileCopy(t *testing.T) { helloWorld := []byte("hello world\n") source, err := ioutil.TempFile("", "") if err != nil { t.Error(err) return } defer os.Remove(source.Name()) if err := WriteAll(source, helloWorld); err != nil { source.Close() t.Error(err) return } source.Close() dest, err := ioutil.TempFile("", "") defer os.Remove(dest.Name()) if err != nil { t.Error(err) return } dest.Close() if err := FileCopy(source.Name(), dest.Name()); err != nil { t.Error(err) return } dest2, err := os.Open(dest.Name()) if err != nil { t.Error(err) return } content, err := ioutil.ReadAll(dest2) if err != nil { t.Error(err) return } if string(content) != string(helloWorld) { t.Error("content mismatch: ", string(content), "!=", string(helloWorld)) return } } func TestReaderToChannel(t *testing.T) { buf := make([]byte, 1*1024*1024) rand.Read(buf) offset := 0 finished := false ch := ReaderToChannel(bytes.NewBuffer(buf), -1) for { data, ok := <-ch if len(data) > 0 { for i := 0; i < len(data); i++ { if buf[offset+i] != data[i] { t.Error(fmt.Sprintf("byte %d didn't match", offset+i)) return } } offset += len(data) if offset > len(buf) { t.Error("read too much data") return } if offset == len(buf) { finished = true } } if !ok { if !finished { t.Error("connection closed too early") return } else { break } } } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/util_linux_test.go����������������������������������������������������������������0000644�0610621�0607500�00000005117�13172163242�020525� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared import ( "fmt" "io/ioutil" "os" "strings" "syscall" "testing" ) func TestGetAllXattr(t *testing.T) { var ( err error testxattr = map[string]string{ "user.checksum": "asdfsf13434qwf1324", "user.random": "This is a test", } ) xattrFile, err := ioutil.TempFile("", "") if err != nil { t.Error(err) return } defer os.Remove(xattrFile.Name()) xattrFile.Close() xattrDir, err := ioutil.TempDir("", "") if err != nil { t.Error(err) return } defer os.Remove(xattrDir) for k, v := range testxattr { err = syscall.Setxattr(xattrFile.Name(), k, []byte(v), 0) if err == syscall.ENOTSUP { t.Log(err) return } if err != nil { t.Error(err) return } err = syscall.Setxattr(xattrDir, k, []byte(v), 0) if err == syscall.ENOTSUP { t.Log(err) return } if err != nil { t.Error(err) return } } // Test retrieval of extended attributes for regular files. h, err := GetAllXattr(xattrFile.Name()) if err != nil { t.Error(err) return } if h == nil { t.Errorf("Expected to find extended attributes but did not find any.") return } for k, v := range h { found, ok := h[k] if !ok || found != testxattr[k] { t.Errorf("Expected to find extended attribute %s with a value of %s on regular file but did not find it.", k, v) return } } // Test retrieval of extended attributes for directories. h, err = GetAllXattr(xattrDir) if err != nil { t.Error(err) return } if h == nil { t.Errorf("Expected to find extended attributes but did not find any.") return } for k, v := range h { found, ok := h[k] if !ok || found != testxattr[k] { t.Errorf("Expected to find extended attribute %s with a value of %s on directory but did not find it.", k, v) return } } } func TestReadLastNLines(t *testing.T) { source, err := ioutil.TempFile("", "") if err != nil { t.Error(err) return } defer os.Remove(source.Name()) for i := 0; i < 50; i++ { fmt.Fprintf(source, "%d\n", i) } lines, err := ReadLastNLines(source, 100) if err != nil { t.Error(err) return } split := strings.Split(lines, "\n") for i := 0; i < 50; i++ { if fmt.Sprintf("%d", i) != split[i] { t.Error(fmt.Sprintf("got %s expected %d", split[i], i)) return } } source.Seek(0, 0) for i := 0; i < 150; i++ { fmt.Fprintf(source, "%d\n", i) } lines, err = ReadLastNLines(source, 100) if err != nil { t.Error(err) return } split = strings.Split(lines, "\n") for i := 0; i < 100; i++ { if fmt.Sprintf("%d", i+50) != split[i] { t.Error(fmt.Sprintf("got %s expected %d", split[i], i)) return } } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/util_linux.go���������������������������������������������������������������������0000644�0610621�0607500�00000052032�13172163242�017464� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux // +build cgo package shared import ( "bufio" "errors" "fmt" "io" "os" "path/filepath" "reflect" "strings" "sync" "sync/atomic" "syscall" "unsafe" "github.com/lxc/lxd/shared/logger" ) // #cgo LDFLAGS: -lutil -lpthread /* #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <grp.h> #include <limits.h> #include <poll.h> #include <pty.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/un.h> #ifndef AT_SYMLINK_FOLLOW #define AT_SYMLINK_FOLLOW 0x400 #endif #ifndef AT_EMPTY_PATH #define AT_EMPTY_PATH 0x1000 #endif #define ABSTRACT_UNIX_SOCK_LEN sizeof(((struct sockaddr_un *)0)->sun_path) // This is an adaption from https://codereview.appspot.com/4589049, to be // included in the stdlib with the stdlib's license. static int mygetgrgid_r(int gid, struct group *grp, char *buf, size_t buflen, struct group **result) { return getgrgid_r(gid, grp, buf, buflen, result); } void configure_pty(int fd) { struct termios term_settings; struct winsize win; if (tcgetattr(fd, &term_settings) < 0) { fprintf(stderr, "Failed to get settings: %s\n", strerror(errno)); return; } term_settings.c_iflag |= IMAXBEL; term_settings.c_iflag |= IUTF8; term_settings.c_iflag |= BRKINT; term_settings.c_iflag |= IXANY; term_settings.c_cflag |= HUPCL; if (tcsetattr(fd, TCSANOW, &term_settings) < 0) { fprintf(stderr, "Failed to set settings: %s\n", strerror(errno)); return; } if (ioctl(fd, TIOCGWINSZ, &win) < 0) { fprintf(stderr, "Failed to get the terminal size: %s\n", strerror(errno)); return; } win.ws_col = 80; win.ws_row = 25; if (ioctl(fd, TIOCSWINSZ, &win) < 0) { fprintf(stderr, "Failed to set the terminal size: %s\n", strerror(errno)); return; } if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { fprintf(stderr, "Failed to set FD_CLOEXEC: %s\n", strerror(errno)); return; } return; } void create_pty(int *master, int *slave, uid_t uid, gid_t gid) { if (openpty(master, slave, NULL, NULL, NULL) < 0) { fprintf(stderr, "Failed to openpty: %s\n", strerror(errno)); return; } configure_pty(*master); configure_pty(*slave); if (fchown(*slave, uid, gid) < 0) { fprintf(stderr, "Warning: error chowning pty to container root\n"); fprintf(stderr, "Continuing...\n"); } if (fchown(*master, uid, gid) < 0) { fprintf(stderr, "Warning: error chowning pty to container root\n"); fprintf(stderr, "Continuing...\n"); } } void create_pipe(int *master, int *slave) { int pipefd[2]; if (pipe2(pipefd, O_CLOEXEC) < 0) { fprintf(stderr, "Failed to create a pipe: %s\n", strerror(errno)); return; } *master = pipefd[0]; *slave = pipefd[1]; } int get_poll_revents(int lfd, int timeout, int flags, int *revents, int *saved_errno) { int ret; struct pollfd pfd = {lfd, flags, 0}; again: ret = poll(&pfd, 1, timeout); if (ret < 0) { if (errno == EINTR) goto again; *saved_errno = errno; fprintf(stderr, "Failed to poll() on file descriptor.\n"); return -1; } *revents = pfd.revents; return ret; } */ import "C" const ABSTRACT_UNIX_SOCK_LEN int = C.ABSTRACT_UNIX_SOCK_LEN const POLLIN int = C.POLLIN const POLLPRI int = C.POLLPRI const POLLNVAL int = C.POLLNVAL const POLLERR int = C.POLLERR const POLLHUP int = C.POLLHUP const POLLRDHUP int = C.POLLRDHUP func GetPollRevents(fd int, timeout int, flags int) (int, int, error) { var err error revents := C.int(0) saved_errno := C.int(0) ret := C.get_poll_revents(C.int(fd), C.int(timeout), C.int(flags), &revents, &saved_errno) if int(ret) < 0 { err = syscall.Errno(saved_errno) } return int(ret), int(revents), err } func OpenPty(uid, gid int64) (master *os.File, slave *os.File, err error) { fd_master := C.int(-1) fd_slave := C.int(-1) rootUid := C.uid_t(uid) rootGid := C.gid_t(gid) C.create_pty(&fd_master, &fd_slave, rootUid, rootGid) if fd_master == -1 || fd_slave == -1 { return nil, nil, errors.New("Failed to create a new pts pair") } master = os.NewFile(uintptr(fd_master), "master") slave = os.NewFile(uintptr(fd_slave), "slave") return master, slave, nil } func Pipe() (master *os.File, slave *os.File, err error) { fd_master := C.int(-1) fd_slave := C.int(-1) C.create_pipe(&fd_master, &fd_slave) if fd_master == -1 || fd_slave == -1 { return nil, nil, errors.New("Failed to create a new pipe") } master = os.NewFile(uintptr(fd_master), "master") slave = os.NewFile(uintptr(fd_slave), "slave") return master, slave, nil } // UserId is an adaption from https://codereview.appspot.com/4589049. func UserId(name string) (int, error) { var pw C.struct_passwd var result *C.struct_passwd bufSize := C.sysconf(C._SC_GETPW_R_SIZE_MAX) if bufSize < 0 { bufSize = 4096 } buf := C.malloc(C.size_t(bufSize)) if buf == nil { return -1, fmt.Errorf("allocation failed") } defer C.free(buf) cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) again: rv, errno := C.getpwnam_r(cname, &pw, (*C.char)(buf), C.size_t(bufSize), &result) if rv < 0 { // OOM killer will take care of us if we end up doing this too // often. if errno == syscall.ERANGE { bufSize *= 2 tmp := C.realloc(buf, C.size_t(bufSize)) if tmp == nil { return -1, fmt.Errorf("allocation failed") } buf = tmp goto again } return -1, fmt.Errorf("failed user lookup: %s", syscall.Errno(rv)) } if result == nil { return -1, fmt.Errorf("unknown user %s", name) } return int(C.int(result.pw_uid)), nil } // GroupId is an adaption from https://codereview.appspot.com/4589049. func GroupId(name string) (int, error) { var grp C.struct_group var result *C.struct_group bufSize := C.sysconf(C._SC_GETGR_R_SIZE_MAX) if bufSize < 0 { bufSize = 4096 } buf := C.malloc(C.size_t(bufSize)) if buf == nil { return -1, fmt.Errorf("allocation failed") } cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) again: rv, errno := C.getgrnam_r(cname, &grp, (*C.char)(buf), C.size_t(bufSize), &result) if rv != 0 { // OOM killer will take care of us if we end up doing this too // often. if errno == syscall.ERANGE { bufSize *= 2 tmp := C.realloc(buf, C.size_t(bufSize)) if tmp == nil { return -1, fmt.Errorf("allocation failed") } buf = tmp goto again } C.free(buf) return -1, fmt.Errorf("failed group lookup: %s", syscall.Errno(rv)) } C.free(buf) if result == nil { return -1, fmt.Errorf("unknown group %s", name) } return int(C.int(result.gr_gid)), nil } // --- pure Go functions --- func Major(dev uint64) int { return int(((dev >> 8) & 0xfff) | ((dev >> 32) & (0xfffff000))) } func Minor(dev uint64) int { return int((dev & 0xff) | ((dev >> 12) & (0xffffff00))) } func GetFileStat(p string) (uid int, gid int, major int, minor int, inode uint64, nlink int, err error) { var stat syscall.Stat_t err = syscall.Lstat(p, &stat) if err != nil { return } uid = int(stat.Uid) gid = int(stat.Gid) inode = uint64(stat.Ino) nlink = int(stat.Nlink) major = -1 minor = -1 if stat.Mode&syscall.S_IFBLK != 0 || stat.Mode&syscall.S_IFCHR != 0 { major = Major(stat.Rdev) minor = Minor(stat.Rdev) } return } func parseMountinfo(name string) int { f, err := os.Open("/proc/self/mountinfo") if err != nil { return -1 } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() tokens := strings.Fields(line) if len(tokens) < 5 { return -1 } cleanPath := filepath.Clean(tokens[4]) cleanName := filepath.Clean(name) if cleanPath == cleanName { return 1 } } return 0 } func IsMountPoint(name string) bool { ret := parseMountinfo(name) if ret >= 0 { return (ret == 1) } stat, err := os.Stat(name) if err != nil { return false } rootStat, err := os.Lstat(name + "/..") if err != nil { return false } // If the directory has the same device as parent, then it's not a mountpoint. return stat.Sys().(*syscall.Stat_t).Dev != rootStat.Sys().(*syscall.Stat_t).Dev } func ReadLastNLines(f *os.File, lines int) (string, error) { if lines <= 0 { return "", fmt.Errorf("invalid line count") } stat, err := f.Stat() if err != nil { return "", err } data, err := syscall.Mmap(int(f.Fd()), 0, int(stat.Size()), syscall.PROT_READ, syscall.MAP_SHARED) if err != nil { return "", err } defer syscall.Munmap(data) for i := len(data) - 1; i >= 0; i-- { if data[i] == '\n' { lines-- } if lines < 0 { return string(data[i+1:]), nil } } return string(data), nil } func SetSize(fd int, width int, height int) (err error) { var dimensions [4]uint16 dimensions[0] = uint16(height) dimensions[1] = uint16(width) if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(&dimensions)), 0, 0, 0); err != 0 { return err } return nil } // This uses ssize_t llistxattr(const char *path, char *list, size_t size); to // handle symbolic links (should it in the future be possible to set extended // attributed on symlinks): If path is a symbolic link the extended attributes // associated with the link itself are retrieved. func llistxattr(path string, list []byte) (sz int, err error) { var _p0 *byte _p0, err = syscall.BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(list) > 0 { _p1 = unsafe.Pointer(&list[0]) } else { _p1 = unsafe.Pointer(nil) } r0, _, e1 := syscall.Syscall(syscall.SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(list))) sz = int(r0) if e1 != 0 { err = e1 } return } // GetAllXattr retrieves all extended attributes associated with a file, // directory or symbolic link. func GetAllXattr(path string) (xattrs map[string]string, err error) { e1 := fmt.Errorf("Extended attributes changed during retrieval.") // Call llistxattr() twice: First, to determine the size of the buffer // we need to allocate to store the extended attributes, second, to // actually store the extended attributes in the buffer. Also, check if // the size/number of extended attributes hasn't changed between the two // calls. pre, err := llistxattr(path, nil) if err != nil || pre < 0 { return nil, err } if pre == 0 { return nil, nil } dest := make([]byte, pre) post, err := llistxattr(path, dest) if err != nil || post < 0 { return nil, err } if post != pre { return nil, e1 } split := strings.Split(string(dest), "\x00") if split == nil { return nil, fmt.Errorf("No valid extended attribute key found.") } // *listxattr functions return a list of names as an unordered array // of null-terminated character strings (attribute names are separated // by null bytes ('\0')), like this: user.name1\0system.name1\0user.name2\0 // Since we split at the '\0'-byte the last element of the slice will be // the empty string. We remove it: if split[len(split)-1] == "" { split = split[:len(split)-1] } xattrs = make(map[string]string, len(split)) for _, x := range split { xattr := string(x) // Call Getxattr() twice: First, to determine the size of the // buffer we need to allocate to store the extended attributes, // second, to actually store the extended attributes in the // buffer. Also, check if the size of the extended attribute // hasn't changed between the two calls. pre, err = syscall.Getxattr(path, xattr, nil) if err != nil || pre < 0 { return nil, err } if pre == 0 { return nil, fmt.Errorf("No valid extended attribute value found.") } dest = make([]byte, pre) post, err = syscall.Getxattr(path, xattr, dest) if err != nil || post < 0 { return nil, err } if post != pre { return nil, e1 } xattrs[xattr] = string(dest) } return xattrs, nil } // Extensively commented directly in the code. Please leave the comments! // Looking at this in a couple of months noone will know why and how this works // anymore. func ExecReaderToChannel(r io.Reader, bufferSize int, exited <-chan bool, fd int) <-chan []byte { if bufferSize <= (128 * 1024) { bufferSize = (128 * 1024) } ch := make(chan ([]byte)) // Takes care that the closeChannel() function is exactly executed once. // This allows us to avoid using a mutex. var once sync.Once closeChannel := func() { close(ch) } // COMMENT(brauner): // [1]: This function has just one job: Dealing with the case where we // are running an interactive shell session where we put a process in // the background that does hold stdin/stdout open, but does not // generate any output at all. This case cannot be dealt with in the // following function call. Here's why: Assume the above case, now the // attached child (the shell in this example) exits. This will not // generate any poll() event: We won't get POLLHUP because the // background process is holding stdin/stdout open and noone is writing // to it. So we effectively block on GetPollRevents() in the function // below. Hence, we use another go routine here who's only job is to // handle that case: When we detect that the child has exited we check // whether a POLLIN or POLLHUP event has been generated. If not, we know // that there's nothing buffered on stdout and exit. var attachedChildIsDead int32 = 0 go func() { <-exited atomic.StoreInt32(&attachedChildIsDead, 1) ret, revents, err := GetPollRevents(fd, 0, (POLLIN | POLLPRI | POLLERR | POLLHUP | POLLRDHUP | POLLNVAL)) if ret < 0 { logger.Errorf("Failed to poll(POLLIN | POLLPRI | POLLHUP | POLLRDHUP) on file descriptor: %s.", err) } else if ret > 0 { if (revents & POLLERR) > 0 { logger.Warnf("Detected poll(POLLERR) event.") } else if (revents & POLLNVAL) > 0 { logger.Warnf("Detected poll(POLLNVAL) event.") } } else if ret == 0 { logger.Debugf("No data in stdout: exiting.") once.Do(closeChannel) return } }() go func() { readSize := (128 * 1024) offset := 0 buf := make([]byte, bufferSize) avoidAtomicLoad := false defer once.Do(closeChannel) for { nr := 0 var err error ret, revents, err := GetPollRevents(fd, -1, (POLLIN | POLLPRI | POLLERR | POLLHUP | POLLRDHUP | POLLNVAL)) if ret < 0 { // COMMENT(brauner): // This condition is only reached in cases where we are massively f*cked since we even handle // EINTR in the underlying C wrapper around poll(). So let's exit here. logger.Errorf("Failed to poll(POLLIN | POLLPRI | POLLERR | POLLHUP | POLLRDHUP) on file descriptor: %s. Exiting.", err) return } // COMMENT(brauner): // [2]: If the process exits before all its data has been read by us and no other process holds stdin or // stdout open, then we will observe a (POLLHUP | POLLRDHUP | POLLIN) event. This means, we need to // keep on reading from the pty file descriptor until we get a simple POLLHUP back. both := ((revents & (POLLIN | POLLPRI)) > 0) && ((revents & (POLLHUP | POLLRDHUP)) > 0) if both { logger.Debugf("Detected poll(POLLIN | POLLPRI | POLLHUP | POLLRDHUP) event.") read := buf[offset : offset+readSize] nr, err = r.Read(read) } if (revents & POLLERR) > 0 { logger.Warnf("Detected poll(POLLERR) event: exiting.") return } else if (revents & POLLNVAL) > 0 { logger.Warnf("Detected poll(POLLNVAL) event: exiting.") return } if ((revents & (POLLIN | POLLPRI)) > 0) && !both { // COMMENT(brauner): // This might appear unintuitive at first but is actually a nice trick: Assume we are running // a shell session in a container and put a process in the background that is writing to // stdout. Now assume the attached process (aka the shell in this example) exits because we // used Ctrl+D to send EOF or something. If no other process would be holding stdout open we // would expect to observe either a (POLLHUP | POLLRDHUP | POLLIN | POLLPRI) event if there // is still data buffered from the previous process or a simple (POLLHUP | POLLRDHUP) if // no data is buffered. The fact that we only observe a (POLLIN | POLLPRI) event means that // another process is holding stdout open and is writing to it. // One counter argument that can be leveraged is (brauner looks at tycho :)) // "Hey, you need to write at least one additional tty buffer to make sure that // everything that the attached child has written is actually shown." // The answer to that is: // "This case can only happen if the process has exited and has left data in stdout which // would generate a (POLLIN | POLLPRI | POLLHUP | POLLRDHUP) event and this case is already // handled and triggers another codepath. (See [2].)" if avoidAtomicLoad || atomic.LoadInt32(&attachedChildIsDead) == 1 { avoidAtomicLoad = true // COMMENT(brauner): // Handle race between atomic.StorInt32() in the go routine // explained in [1] and atomic.LoadInt32() in the go routine // here: // We need to check for (POLLHUP | POLLRDHUP) here again since we might // still be handling a pure POLLIN event from a write prior to the childs // exit. But the child might have exited right before and performed // atomic.StoreInt32() to update attachedChildIsDead before we // performed our atomic.LoadInt32(). This means we accidentally hit this // codepath and are misinformed about the available poll() events. So we // need to perform a non-blocking poll() again to exclude that case: // // - If we detect no (POLLHUP | POLLRDHUP) event we know the child // has already exited but someone else is holding stdin/stdout open and // writing to it. // Note that his case should only ever be triggered in situations like // running a shell and doing stuff like: // > ./lxc exec xen1 -- bash // root@xen1:~# yes & // . // . // . // now send Ctrl+D or type "exit". By the time the Ctrl+D/exit event is // triggered, we will have read all of the childs data it has written to // stdout and so we can assume that anything that comes now belongs to // the process that is holding stdin/stdout open. // // - If we detect a (POLLHUP | POLLRDHUP) event we know that we've // hit this codepath on accident caused by the race between // atomic.StoreInt32() in the go routine explained in [1] and // atomic.LoadInt32() in this go routine. So the next call to // GetPollRevents() will either return // (POLLIN | POLLPRI | POLLERR | POLLHUP | POLLRDHUP) // or (POLLHUP | POLLRDHUP). Both will trigger another codepath (See [2].) // that takes care that all data of the child that is buffered in // stdout is written out. ret, revents, err := GetPollRevents(fd, 0, (POLLIN | POLLPRI | POLLERR | POLLHUP | POLLRDHUP | POLLNVAL)) if ret < 0 { logger.Errorf("Failed to poll(POLLIN | POLLPRI | POLLERR | POLLHUP | POLLRDHUP) on file descriptor: %s. Exiting.", err) return } else if (revents & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL)) == 0 { logger.Debugf("Exiting but background processes are still running.") return } } read := buf[offset : offset+readSize] nr, err = r.Read(read) } // COMMENT(brauner): // The attached process has exited and we have read all data that may have // been buffered. if ((revents & (POLLHUP | POLLRDHUP)) > 0) && !both { logger.Debugf("Detected poll(POLLHUP) event: exiting.") return } offset += nr if offset > 0 && (offset+readSize >= bufferSize || err != nil) { ch <- buf[0:offset] offset = 0 buf = make([]byte, bufferSize) } } }() return ch } // Detect whether err is an errno. func GetErrno(err error) (errno error, iserrno bool) { sysErr, ok := err.(*os.SyscallError) if ok { return sysErr.Err, true } pathErr, ok := err.(*os.PathError) if ok { return pathErr.Err, true } tmpErrno, ok := err.(syscall.Errno) if ok { return tmpErrno, true } return nil, false } // Utsname returns the same info as syscall.Utsname, as strings type Utsname struct { Sysname string Nodename string Release string Version string Machine string Domainname string } // Uname returns Utsname as strings func Uname() (*Utsname, error) { /* * Based on: https://groups.google.com/forum/#!topic/golang-nuts/Jel8Bb-YwX8 * there is really no better way to do this, which is * unfortunate. Also, we ditch the more accepted CharsToString * version in that thread, since it doesn't seem as portable, * viz. github issue #206. */ uname := syscall.Utsname{} err := syscall.Uname(&uname) if err != nil { return nil, err } return &Utsname{ Sysname: intArrayToString(uname.Sysname), Nodename: intArrayToString(uname.Nodename), Release: intArrayToString(uname.Release), Version: intArrayToString(uname.Version), Machine: intArrayToString(uname.Machine), Domainname: intArrayToString(uname.Domainname), }, nil } func intArrayToString(arr interface{}) string { slice := reflect.ValueOf(arr) s := "" for i := 0; i < slice.Len(); i++ { val := slice.Index(i) valInt := int64(-1) switch val.Kind() { case reflect.Int: case reflect.Int8: valInt = int64(val.Int()) case reflect.Uint: case reflect.Uint8: valInt = int64(val.Uint()) default: continue } if valInt == 0 { break } s += string(byte(valInt)) } return s } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/util.go���������������������������������������������������������������������������0000644�0610621�0607500�00000043612�13172163242�016251� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared import ( "bufio" "bytes" "crypto/rand" "encoding/gob" "encoding/hex" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "os/exec" "path" "path/filepath" "reflect" "regexp" "runtime" "strconv" "strings" "time" "unicode" ) const SnapshotDelimiter = "/" const DefaultPort = "8443" // URLEncode encodes a path and query parameters to a URL. func URLEncode(path string, query map[string]string) (string, error) { u, err := url.Parse(path) if err != nil { return "", err } params := url.Values{} for key, value := range query { params.Add(key, value) } u.RawQuery = params.Encode() return u.String(), nil } // AddSlash adds a slash to the end of paths if they don't already have one. // This can be useful for rsyncing things, since rsync has behavior present on // the presence or absence of a trailing slash. func AddSlash(path string) string { if path[len(path)-1] != '/' { return path + "/" } return path } func PathExists(name string) bool { _, err := os.Lstat(name) if err != nil && os.IsNotExist(err) { return false } return true } // PathIsEmpty checks if the given path is empty. func PathIsEmpty(path string) (bool, error) { f, err := os.Open(path) if err != nil { return false, err } defer f.Close() // read in ONLY one file _, err = f.Readdir(1) // and if the file is EOF... well, the dir is empty. if err == io.EOF { return true, nil } return false, err } // IsDir returns true if the given path is a directory. func IsDir(name string) bool { stat, err := os.Lstat(name) if err != nil { return false } return stat.IsDir() } // IsUnixSocket returns true if the given path is either a Unix socket // or a symbolic link pointing at a Unix socket. func IsUnixSocket(path string) bool { stat, err := os.Stat(path) if err != nil { return false } return (stat.Mode() & os.ModeSocket) == os.ModeSocket } // HostPath returns the host path for the provided path // On a normal system, this does nothing // When inside of a snap environment, returns the real path func HostPath(path string) string { // Ignore empty paths if len(path) == 0 { return path } // Check if we're running in a snap package snap := os.Getenv("SNAP") if snap == "" { return path } // Handle relative paths if path[0] != os.PathSeparator { // Use the cwd of the parent as snap-confine alters our own cwd on launch ppid := os.Getppid() if ppid < 1 { return path } pwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", ppid)) if err != nil { return path } path = filepath.Clean(strings.Join([]string{pwd, path}, string(os.PathSeparator))) } // Check if the path is already snap-aware for _, prefix := range []string{"/snap", "/var/snap", "/var/lib/snapd"} { if strings.HasPrefix(path, prefix) { return path } } return fmt.Sprintf("/var/lib/snapd/hostfs%s", path) } // VarPath returns the provided path elements joined by a slash and // appended to the end of $LXD_DIR, which defaults to /var/lib/lxd. func VarPath(path ...string) string { varDir := os.Getenv("LXD_DIR") if varDir == "" { varDir = "/var/lib/lxd" } items := []string{varDir} items = append(items, path...) return filepath.Join(items...) } // CachePath returns the directory that LXD should its cache under. If LXD_DIR is // set, this path is $LXD_DIR/cache, otherwise it is /var/cache/lxd. func CachePath(path ...string) string { varDir := os.Getenv("LXD_DIR") logDir := "/var/cache/lxd" if varDir != "" { logDir = filepath.Join(varDir, "cache") } items := []string{logDir} items = append(items, path...) return filepath.Join(items...) } // LogPath returns the directory that LXD should put logs under. If LXD_DIR is // set, this path is $LXD_DIR/logs, otherwise it is /var/log/lxd. func LogPath(path ...string) string { varDir := os.Getenv("LXD_DIR") logDir := "/var/log/lxd" if varDir != "" { logDir = filepath.Join(varDir, "logs") } items := []string{logDir} items = append(items, path...) return filepath.Join(items...) } func ParseLXDFileHeaders(headers http.Header) (uid int64, gid int64, mode int, type_ string, write string) { uid, err := strconv.ParseInt(headers.Get("X-LXD-uid"), 10, 64) if err != nil { uid = -1 } gid, err = strconv.ParseInt(headers.Get("X-LXD-gid"), 10, 64) if err != nil { gid = -1 } mode, err = strconv.Atoi(headers.Get("X-LXD-mode")) if err != nil { mode = -1 } else { rawMode, err := strconv.ParseInt(headers.Get("X-LXD-mode"), 0, 0) if err == nil { mode = int(os.FileMode(rawMode) & os.ModePerm) } } type_ = headers.Get("X-LXD-type") /* backwards compat: before "type" was introduced, we could only * manipulate files */ if type_ == "" { type_ = "file" } write = headers.Get("X-LXD-write") /* backwards compat: before "write" was introduced, we could only * overwrite files */ if write == "" { write = "overwrite" } return uid, gid, mode, type_, write } func ReadToJSON(r io.Reader, req interface{}) error { buf, err := ioutil.ReadAll(r) if err != nil { return err } return json.Unmarshal(buf, req) } func ReaderToChannel(r io.Reader, bufferSize int) <-chan []byte { if bufferSize <= 128*1024 { bufferSize = 128 * 1024 } ch := make(chan ([]byte)) go func() { readSize := 128 * 1024 offset := 0 buf := make([]byte, bufferSize) for { read := buf[offset : offset+readSize] nr, err := r.Read(read) offset += nr if offset > 0 && (offset+readSize >= bufferSize || err != nil) { ch <- buf[0:offset] offset = 0 buf = make([]byte, bufferSize) } if err != nil { close(ch) break } } }() return ch } // Returns a random base64 encoded string from crypto/rand. func RandomCryptoString() (string, error) { buf := make([]byte, 32) n, err := rand.Read(buf) if err != nil { return "", err } if n != len(buf) { return "", fmt.Errorf("not enough random bytes read") } return hex.EncodeToString(buf), nil } func SplitExt(fpath string) (string, string) { b := path.Base(fpath) ext := path.Ext(fpath) return b[:len(b)-len(ext)], ext } func AtoiEmptyDefault(s string, def int) (int, error) { if s == "" { return def, nil } return strconv.Atoi(s) } func ReadStdin() ([]byte, error) { buf := bufio.NewReader(os.Stdin) line, _, err := buf.ReadLine() if err != nil { return nil, err } return line, nil } func WriteAll(w io.Writer, buf []byte) error { return WriteAllBuf(w, bytes.NewBuffer(buf)) } func WriteAllBuf(w io.Writer, buf *bytes.Buffer) error { toWrite := int64(buf.Len()) for { n, err := io.Copy(w, buf) if err != nil { return err } toWrite -= n if toWrite <= 0 { return nil } } } // FileMove tries to move a file by using os.Rename, // if that fails it tries to copy the file and remove the source. func FileMove(oldPath string, newPath string) error { err := os.Rename(oldPath, newPath) if err == nil { return nil } err = FileCopy(oldPath, newPath) if err != nil { return err } os.Remove(oldPath) return nil } // FileCopy copies a file, overwriting the target if it exists. func FileCopy(source string, dest string) error { s, err := os.Open(source) if err != nil { return err } defer s.Close() fi, err := s.Stat() if err != nil { return err } d, err := os.Create(dest) if err != nil { if os.IsExist(err) { d, err = os.OpenFile(dest, os.O_WRONLY, fi.Mode()) if err != nil { return err } } else { return err } } defer d.Close() _, err = io.Copy(d, s) if err != nil { return err } /* chown not supported on windows */ if runtime.GOOS != "windows" { _, uid, gid := GetOwnerMode(fi) return d.Chown(uid, gid) } return nil } type BytesReadCloser struct { Buf *bytes.Buffer } func (r BytesReadCloser) Read(b []byte) (n int, err error) { return r.Buf.Read(b) } func (r BytesReadCloser) Close() error { /* no-op since we're in memory */ return nil } func IsSnapshot(name string) bool { return strings.Contains(name, SnapshotDelimiter) } func ExtractSnapshotName(name string) string { return strings.SplitN(name, SnapshotDelimiter, 2)[1] } func ReadDir(p string) ([]string, error) { ents, err := ioutil.ReadDir(p) if err != nil { return []string{}, err } var ret []string for _, ent := range ents { ret = append(ret, ent.Name()) } return ret, nil } func MkdirAllOwner(path string, perm os.FileMode, uid int, gid int) error { // This function is a slightly modified version of MkdirAll from the Go standard library. // https://golang.org/src/os/path.go?s=488:535#L9 // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil } return fmt.Errorf("path exists but isn't a directory") } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = MkdirAllOwner(path[0:j-1], perm, uid, gid) if err != nil { return err } } // Parent now exists; invoke Mkdir and use its result. err = os.Mkdir(path, perm) err_chown := os.Chown(path, uid, gid) if err_chown != nil { return err_chown } if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil } func StringInSlice(key string, list []string) bool { for _, entry := range list { if entry == key { return true } } return false } func IntInSlice(key int, list []int) bool { for _, entry := range list { if entry == key { return true } } return false } func Int64InSlice(key int64, list []int64) bool { for _, entry := range list { if entry == key { return true } } return false } func IsTrue(value string) bool { if StringInSlice(strings.ToLower(value), []string{"true", "1", "yes", "on"}) { return true } return false } func IsBlockdev(fm os.FileMode) bool { return ((fm&os.ModeDevice != 0) && (fm&os.ModeCharDevice == 0)) } func IsBlockdevPath(pathName string) bool { sb, err := os.Stat(pathName) if err != nil { return false } fm := sb.Mode() return ((fm&os.ModeDevice != 0) && (fm&os.ModeCharDevice == 0)) } func BlockFsDetect(dev string) (string, error) { out, err := RunCommand("blkid", "-s", "TYPE", "-o", "value", dev) if err != nil { return "", err } return strings.TrimSpace(out), nil } // DeepCopy copies src to dest by using encoding/gob so its not that fast. func DeepCopy(src, dest interface{}) error { buff := new(bytes.Buffer) enc := gob.NewEncoder(buff) dec := gob.NewDecoder(buff) if err := enc.Encode(src); err != nil { return err } if err := dec.Decode(dest); err != nil { return err } return nil } func RunningInUserNS() bool { file, err := os.Open("/proc/self/uid_map") if err != nil { return false } defer file.Close() buf := bufio.NewReader(file) l, _, err := buf.ReadLine() if err != nil { return false } line := string(l) var a, b, c int64 fmt.Sscanf(line, "%d %d %d", &a, &b, &c) if a == 0 && b == 0 && c == 4294967295 { return false } return true } func ValidHostname(name string) bool { // Validate length if len(name) < 1 || len(name) > 63 { return false } // Validate first character if strings.HasPrefix(name, "-") { return false } if _, err := strconv.Atoi(string(name[0])); err == nil { return false } // Validate last character if strings.HasSuffix(name, "-") { return false } // Validate the character set match, _ := regexp.MatchString("^[-a-zA-Z0-9]*$", name) if !match { return false } return true } // Spawn the editor with a temporary YAML file for editing configs func TextEditor(inPath string, inContent []byte) ([]byte, error) { var f *os.File var err error var path string // Detect the text editor to use editor := os.Getenv("VISUAL") if editor == "" { editor = os.Getenv("EDITOR") if editor == "" { for _, p := range []string{"editor", "vi", "emacs", "nano"} { _, err := exec.LookPath(p) if err == nil { editor = p break } } if editor == "" { return []byte{}, fmt.Errorf("No text editor found, please set the EDITOR environment variable.") } } } if inPath == "" { // If provided input, create a new file f, err = ioutil.TempFile("", "lxd_editor_") if err != nil { return []byte{}, err } err = os.Chmod(f.Name(), 0600) if err != nil { f.Close() os.Remove(f.Name()) return []byte{}, err } f.Write(inContent) f.Close() path = fmt.Sprintf("%s.yaml", f.Name()) os.Rename(f.Name(), path) defer os.Remove(path) } else { path = inPath } cmdParts := strings.Fields(editor) cmd := exec.Command(cmdParts[0], append(cmdParts[1:], path)...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { return []byte{}, err } content, err := ioutil.ReadFile(path) if err != nil { return []byte{}, err } return content, nil } func ParseMetadata(metadata interface{}) (map[string]interface{}, error) { newMetadata := make(map[string]interface{}) s := reflect.ValueOf(metadata) if !s.IsValid() { return nil, nil } if s.Kind() == reflect.Map { for _, k := range s.MapKeys() { if k.Kind() != reflect.String { return nil, fmt.Errorf("Invalid metadata provided (key isn't a string).") } newMetadata[k.String()] = s.MapIndex(k).Interface() } } else if s.Kind() == reflect.Ptr && !s.Elem().IsValid() { return nil, nil } else { return nil, fmt.Errorf("Invalid metadata provided (type isn't a map).") } return newMetadata, nil } // Parse a size string in bytes (e.g. 200kB or 5GB) into the number of bytes it // represents. Supports suffixes up to EB. "" == 0. func ParseByteSizeString(input string) (int64, error) { suffixLen := 2 if input == "" { return 0, nil } if unicode.IsNumber(rune(input[len(input)-1])) { // COMMENT(brauner): No suffix --> bytes. suffixLen = 0 } else if (len(input) >= 2) && (input[len(input)-1] == 'B') && unicode.IsNumber(rune(input[len(input)-2])) { // COMMENT(brauner): "B" suffix --> bytes. suffixLen = 1 } else if strings.HasSuffix(input, " bytes") { // COMMENT(brauner): Backward compatible behaviour in case we // talk to a LXD that still uses GetByteSizeString() that // returns "n bytes". suffixLen = 6 } else if (len(input) < 3) && (suffixLen == 2) { return -1, fmt.Errorf("Invalid value: %s", input) } // Extract the suffix suffix := input[len(input)-suffixLen:] // Extract the value value := input[0 : len(input)-suffixLen] valueInt, err := strconv.ParseInt(value, 10, 64) if err != nil { return -1, fmt.Errorf("Invalid integer: %s", input) } if valueInt < 0 { return -1, fmt.Errorf("Invalid value: %d", valueInt) } // COMMENT(brauner): The value is already in bytes. if suffixLen != 2 { return valueInt, nil } // Figure out the multiplicator multiplicator := int64(0) switch suffix { case "kB": multiplicator = 1024 case "MB": multiplicator = 1024 * 1024 case "GB": multiplicator = 1024 * 1024 * 1024 case "TB": multiplicator = 1024 * 1024 * 1024 * 1024 case "PB": multiplicator = 1024 * 1024 * 1024 * 1024 * 1024 case "EB": multiplicator = 1024 * 1024 * 1024 * 1024 * 1024 * 1024 default: return -1, fmt.Errorf("Unsupported suffix: %s", suffix) } return valueInt * multiplicator, nil } // Parse a size string in bits (e.g. 200kbit or 5Gbit) into the number of bits // it represents. Supports suffixes up to Ebit. "" == 0. func ParseBitSizeString(input string) (int64, error) { if input == "" { return 0, nil } if len(input) < 5 { return -1, fmt.Errorf("Invalid value: %s", input) } // Extract the suffix suffix := input[len(input)-4:] // Extract the value value := input[0 : len(input)-4] valueInt, err := strconv.ParseInt(value, 10, 64) if err != nil { return -1, fmt.Errorf("Invalid integer: %s", input) } if valueInt < 0 { return -1, fmt.Errorf("Invalid value: %d", valueInt) } // Figure out the multiplicator multiplicator := int64(0) switch suffix { case "kbit": multiplicator = 1000 case "Mbit": multiplicator = 1000 * 1000 case "Gbit": multiplicator = 1000 * 1000 * 1000 case "Tbit": multiplicator = 1000 * 1000 * 1000 * 1000 case "Pbit": multiplicator = 1000 * 1000 * 1000 * 1000 * 1000 case "Ebit": multiplicator = 1000 * 1000 * 1000 * 1000 * 1000 * 1000 default: return -1, fmt.Errorf("Unsupported suffix: %s", suffix) } return valueInt * multiplicator, nil } func GetByteSizeString(input int64, precision uint) string { if input < 1024 { return fmt.Sprintf("%dB", input) } value := float64(input) for _, unit := range []string{"kB", "MB", "GB", "TB", "PB", "EB"} { value = value / 1024 if value < 1024 { return fmt.Sprintf("%.*f%s", precision, value, unit) } } return fmt.Sprintf("%.*fEB", precision, value) } type RunError struct { msg string Err error } func (e RunError) Error() string { return e.msg } func RunCommand(name string, arg ...string) (string, error) { output, err := exec.Command(name, arg...).CombinedOutput() if err != nil { err := RunError{ msg: fmt.Sprintf("Failed to run: %s %s: %s", name, strings.Join(arg, " "), strings.TrimSpace(string(output))), Err: err, } return string(output), err } return string(output), nil } func TryRunCommand(name string, arg ...string) (string, error) { var err error var output string for i := 0; i < 20; i++ { output, err = RunCommand(name, arg...) if err == nil { break } time.Sleep(500 * time.Millisecond) } return output, err } func TimeIsSet(ts time.Time) bool { if ts.Unix() <= 0 { return false } if ts.UTC().Unix() <= 0 { return false } return true } // WriteTempFile creates a temp file with the specified content func WriteTempFile(dir string, prefix string, content string) (string, error) { f, err := ioutil.TempFile(dir, prefix) if err != nil { return "", err } defer f.Close() _, err = f.WriteString(content) return f.Name(), err } ����������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/termios/��������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016421� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/termios/termios_windows.go��������������������������������������������������������0000644�0610621�0607500�00000002340�13172163242�022203� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build windows package termios import ( "golang.org/x/crypto/ssh/terminal" ) // State contains the state of a terminal. type State terminal.State // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd int) bool { return terminal.IsTerminal(fd) } // GetState returns the current state of a terminal which may be useful to restore the terminal after a signal. func GetState(fd int) (*State, error) { state, err := terminal.GetState(fd) if err != nil { return nil, err } currentState := State(*state) return &currentState, nil } // GetSize returns the dimensions of the given terminal. func GetSize(fd int) (int, int, error) { return terminal.GetSize(fd) } // MakeRaw put the terminal connected to the given file descriptor into raw mode and returns the previous state of the terminal so that it can be restored. func MakeRaw(fd int) (*State, error) { state, err := terminal.MakeRaw(fd) if err != nil { return nil, err } oldState := State(*state) return &oldState, nil } // Restore restores the terminal connected to the given file descriptor to a previous state. func Restore(fd int, state *State) error { newState := terminal.State(*state) return terminal.Restore(fd, &newState) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/termios/termios.go����������������������������������������������������������������0000644�0610621�0607500�00000003670�13172163242�020440� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows package termios import ( "syscall" "unsafe" "github.com/lxc/lxd/shared" ) // #include <termios.h> import "C" // State contains the state of a terminal. type State struct { Termios syscall.Termios } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd int) bool { _, err := GetState(fd) return err == nil } // GetState returns the current state of a terminal which may be useful to restore the terminal after a signal. func GetState(fd int) (*State, error) { termios := syscall.Termios{} ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(&termios))) if ret != 0 { return nil, err.(syscall.Errno) } state := State{} state.Termios = termios return &state, nil } // GetSize returns the dimensions of the given terminal. func GetSize(fd int) (int, int, error) { var dimensions [4]uint16 if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&dimensions)), 0, 0, 0); err != 0 { return -1, -1, err } return int(dimensions[1]), int(dimensions[0]), nil } // MakeRaw put the terminal connected to the given file descriptor into raw mode and returns the previous state of the terminal so that it can be restored. func MakeRaw(fd int) (*State, error) { var err error var oldState, newState *State oldState, err = GetState(fd) if err != nil { return nil, err } err = shared.DeepCopy(&oldState, &newState) if err != nil { return nil, err } C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState.Termios))) err = Restore(fd, newState) if err != nil { return nil, err } return oldState, nil } // Restore restores the terminal connected to the given file descriptor to a previous state. func Restore(fd int, state *State) error { ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(&state.Termios))) if ret != 0 { return err.(syscall.Errno) } return nil } ������������������������������������������������������������������������lxd-2.0.11/shared/subtest/��������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016430� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/subtest/go1_7.go������������������������������������������������������������������0000644�0610621�0607500�00000000672�13172163242�017700� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // See https://github.com/golang/go/blob/master/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://github.com/golang/go/blob/master/LICENSE // +build go1.7 package subtest import "testing" // Run runs function f as a subtest of t. func Run(t *testing.T, name string, f func(t *testing.T)) { t.Run(name, f) } ����������������������������������������������������������������������lxd-2.0.11/shared/subtest/go1_6.go������������������������������������������������������������������0000644�0610621�0607500�00000000720�13172163242�017671� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // See https://github.com/golang/go/blob/master/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://github.com/golang/go/blob/master/LICENSE // +build !go1.7 package subtest import "testing" // Run runs function f as a subtest of t. func Run(t *testing.T, name string, f func(t *testing.T)) { t.Logf("Running %s...", name) f(t) } ������������������������������������������������lxd-2.0.11/shared/subtest/doc.go��������������������������������������������������������������������0000644�0610621�0607500�00000001433�13172163242�017525� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // See https://github.com/golang/go/blob/master/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://github.com/golang/go/blob/master/LICENSE // Package subtest provides a backwards-compatible way to run subtests. // // For Go 1.7 and higher, it uses testing.T's run method. For lower versions // it mimics subtests by logging additional information. // // package foo // // import "github.com/mpvl/subtest" // // var testCases = ... // // func TestFoo(t *testing.T) { // for _, tc := range testCases { // subtest.Run(t, tc.name, func(t *testing.T) { // tc.doTest() // }) // } // } // package subtest �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/stringset_test.go�����������������������������������������������������������������0000644�0610621�0607500�00000000601�13172163242�020344� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared import ( "testing" ) func TestStringSetSubset(t *testing.T) { ss := NewStringSet([]string{"one", "two"}) if !ss.IsSubset(ss) { t.Error("subests wrong") return } if !ss.IsSubset(NewStringSet([]string{"one", "two", "three"})) { t.Error("subsets wrong") return } if ss.IsSubset(NewStringSet([]string{"four"})) { t.Error("subests wrong") return } } �������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/stringset.go����������������������������������������������������������������������0000644�0610621�0607500�00000000713�13172163242�017311� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// That this code needs to exist is kind of dumb, but I'm not sure how else to // do it. package shared type StringSet map[string]bool func (ss StringSet) IsSubset(oss StringSet) bool { for k := range map[string]bool(ss) { if _, ok := map[string]bool(oss)[k]; !ok { return false } } return true } func NewStringSet(strings []string) StringSet { ret := map[string]bool{} for _, s := range strings { ret[s] = true } return StringSet(ret) } �����������������������������������������������������lxd-2.0.11/shared/simplestreams/��������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�017627� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/simplestreams/simplestreams.go����������������������������������������������������0000644�0610621�0607500�00000043150�13172163242�023051� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package simplestreams import ( "crypto/sha256" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "sort" "strconv" "strings" "time" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/ioprogress" "github.com/lxc/lxd/shared/osarch" ) type ssSortImage []api.Image func (a ssSortImage) Len() int { return len(a) } func (a ssSortImage) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ssSortImage) Less(i, j int) bool { if a[i].Properties["os"] == a[j].Properties["os"] { if a[i].Properties["release"] == a[j].Properties["release"] { if !shared.TimeIsSet(a[i].CreatedAt) { return true } if !shared.TimeIsSet(a[j].CreatedAt) { return false } if a[i].CreatedAt == a[j].CreatedAt { return a[i].Properties["serial"] > a[j].Properties["serial"] } return a[i].CreatedAt.UTC().Unix() > a[j].CreatedAt.UTC().Unix() } if a[i].Properties["release"] == "" { return false } if a[j].Properties["release"] == "" { return true } return a[i].Properties["release"] < a[j].Properties["release"] } if a[i].Properties["os"] == "" { return false } if a[j].Properties["os"] == "" { return true } return a[i].Properties["os"] < a[j].Properties["os"] } var ssDefaultOS = map[string]string{ "https://cloud-images.ubuntu.com": "ubuntu", } type SimpleStreamsManifest struct { Updated string `json:"updated"` DataType string `json:"datatype"` Format string `json:"format"` License string `json:"license"` Products map[string]SimpleStreamsManifestProduct `json:"products"` } func (s *SimpleStreamsManifest) ToLXD() ([]api.Image, map[string][][]string) { downloads := map[string][][]string{} images := []api.Image{} nameLayout := "20060102" eolLayout := "2006-01-02" for _, product := range s.Products { // Skip unsupported architectures architecture, err := osarch.ArchitectureId(product.Architecture) if err != nil { continue } architectureName, err := osarch.ArchitectureName(architecture) if err != nil { continue } for name, version := range product.Versions { // Short of anything better, use the name as date (see format above) if len(name) < 8 { continue } creationDate, err := time.Parse(nameLayout, name[0:8]) if err != nil { continue } var meta SimpleStreamsManifestProductVersionItem var rootTar SimpleStreamsManifestProductVersionItem var rootSquash SimpleStreamsManifestProductVersionItem deltas := []SimpleStreamsManifestProductVersionItem{} for _, item := range version.Items { // Identify deltas if item.FileType == "squashfs.vcdiff" { deltas = append(deltas, item) } // Skip the files we don't care about if !shared.StringInSlice(item.FileType, []string{"root.tar.xz", "lxd.tar.xz", "squashfs"}) { continue } if item.FileType == "lxd.tar.xz" { meta = item } else if item.FileType == "squashfs" { rootSquash = item } else if item.FileType == "root.tar.xz" { rootTar = item } } if meta.FileType == "" || (rootTar.FileType == "" && rootSquash.FileType == "") { // Invalid image continue } metaPath := meta.Path metaHash := meta.HashSha256 metaSize := meta.Size rootfsPath := "" rootfsHash := "" rootfsSize := int64(0) fields := strings.Split(meta.Path, "/") filename := fields[len(fields)-1] size := meta.Size fingerprint := "" if rootSquash.FileType != "" { if meta.LXDHashSha256SquashFs != "" { fingerprint = meta.LXDHashSha256SquashFs } else { fingerprint = meta.LXDHashSha256 } size += rootSquash.Size rootfsPath = rootSquash.Path rootfsHash = rootSquash.HashSha256 rootfsSize = rootSquash.Size } else { if meta.LXDHashSha256RootXz != "" { fingerprint = meta.LXDHashSha256RootXz } else { fingerprint = meta.LXDHashSha256 } size += rootTar.Size rootfsPath = rootTar.Path rootfsHash = rootTar.HashSha256 rootfsSize = rootTar.Size } if size == 0 || filename == "" || fingerprint == "" { // Invalid image continue } // Generate the actual image entry description := fmt.Sprintf("%s %s %s", product.OperatingSystem, product.ReleaseTitle, product.Architecture) if version.Label != "" { description = fmt.Sprintf("%s (%s)", description, version.Label) } description = fmt.Sprintf("%s (%s)", description, name) image := api.Image{} image.Architecture = architectureName image.Public = true image.Size = size image.CreatedAt = creationDate image.UploadedAt = creationDate image.Filename = filename image.Fingerprint = fingerprint image.Properties = map[string]string{ "os": product.OperatingSystem, "release": product.Release, "version": product.Version, "architecture": product.Architecture, "label": version.Label, "serial": name, "description": description, } // Add the provided aliases if product.Aliases != "" { image.Aliases = []api.ImageAlias{} for _, entry := range strings.Split(product.Aliases, ",") { image.Aliases = append(image.Aliases, api.ImageAlias{Name: entry}) } } // Clear unset properties for k, v := range image.Properties { if v == "" { delete(image.Properties, k) } } // Attempt to parse the EOL image.ExpiresAt = time.Unix(0, 0).UTC() if product.SupportedEOL != "" { eolDate, err := time.Parse(eolLayout, product.SupportedEOL) if err == nil { image.ExpiresAt = eolDate } } imgDownloads := [][]string{ {metaPath, metaHash, "meta", fmt.Sprintf("%d", metaSize)}, {rootfsPath, rootfsHash, "root", fmt.Sprintf("%d", rootfsSize)}} // Add the deltas for _, delta := range deltas { srcImage, ok := product.Versions[delta.DeltaBase] if !ok { continue } var srcFingerprint string for _, item := range srcImage.Items { if item.FileType != "lxd.tar.xz" { continue } srcFingerprint = item.LXDHashSha256SquashFs break } if srcFingerprint == "" { continue } imgDownloads = append(imgDownloads, []string{ delta.Path, delta.HashSha256, fmt.Sprintf("root.delta-%s", srcFingerprint), fmt.Sprintf("%d", delta.Size)}) } downloads[fingerprint] = imgDownloads images = append(images, image) } } return images, downloads } type SimpleStreamsManifestProduct struct { Aliases string `json:"aliases"` Architecture string `json:"arch"` OperatingSystem string `json:"os"` Release string `json:"release"` ReleaseCodename string `json:"release_codename"` ReleaseTitle string `json:"release_title"` Supported bool `json:"supported"` SupportedEOL string `json:"support_eol"` Version string `json:"version"` Versions map[string]SimpleStreamsManifestProductVersion `json:"versions"` } type SimpleStreamsManifestProductVersion struct { PublicName string `json:"pubname"` Label string `json:"label"` Items map[string]SimpleStreamsManifestProductVersionItem `json:"items"` } type SimpleStreamsManifestProductVersionItem struct { Path string `json:"path"` FileType string `json:"ftype"` HashMd5 string `json:"md5"` HashSha256 string `json:"sha256"` LXDHashSha256 string `json:"combined_sha256"` LXDHashSha256RootXz string `json:"combined_rootxz_sha256"` LXDHashSha256SquashFs string `json:"combined_squashfs_sha256"` Size int64 `json:"size"` DeltaBase string `json:"delta_base"` } type SimpleStreamsIndex struct { Format string `json:"format"` Index map[string]SimpleStreamsIndexStream `json:"index"` Updated string `json:"updated"` } type SimpleStreamsIndexStream struct { Updated string `json:"updated"` DataType string `json:"datatype"` Path string `json:"path"` Products []string `json:"products"` } type SimpleStreamsFile struct { Path string Sha256 string Size int64 } func NewClient(url string, httpClient http.Client, useragent string) *SimpleStreams { return &SimpleStreams{ http: &httpClient, url: url, cachedManifest: map[string]*SimpleStreamsManifest{}, useragent: useragent, } } type SimpleStreams struct { http *http.Client url string useragent string cachedIndex *SimpleStreamsIndex cachedManifest map[string]*SimpleStreamsManifest cachedImages []api.Image cachedAliases map[string]*api.ImageAliasesEntry } func (s *SimpleStreams) parseIndex() (*SimpleStreamsIndex, error) { if s.cachedIndex != nil { return s.cachedIndex, nil } url := fmt.Sprintf("%s/streams/v1/index.json", s.url) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } if s.useragent != "" { req.Header.Set("User-Agent", s.useragent) } r, err := s.http.Do(req) if err != nil { return nil, err } defer r.Body.Close() if r.StatusCode != http.StatusOK { return nil, fmt.Errorf("Unable to fetch %s: %s", url, r.Status) } body, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } // Parse the idnex ssIndex := SimpleStreamsIndex{} err = json.Unmarshal(body, &ssIndex) if err != nil { return nil, err } s.cachedIndex = &ssIndex return &ssIndex, nil } func (s *SimpleStreams) parseManifest(path string) (*SimpleStreamsManifest, error) { if s.cachedManifest[path] != nil { return s.cachedManifest[path], nil } url := fmt.Sprintf("%s/%s", s.url, path) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } if s.useragent != "" { req.Header.Set("User-Agent", s.useragent) } r, err := s.http.Do(req) if err != nil { return nil, err } defer r.Body.Close() if r.StatusCode != http.StatusOK { return nil, fmt.Errorf("Unable to fetch %s: %s", url, r.Status) } body, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } // Parse the idnex ssManifest := SimpleStreamsManifest{} err = json.Unmarshal(body, &ssManifest) if err != nil { return nil, err } s.cachedManifest[path] = &ssManifest return &ssManifest, nil } func (s *SimpleStreams) applyAliases(images []api.Image) ([]api.Image, map[string]*api.ImageAliasesEntry, error) { aliases := map[string]*api.ImageAliasesEntry{} sort.Sort(ssSortImage(images)) defaultOS := "" for k, v := range ssDefaultOS { if strings.HasPrefix(s.url, k) { defaultOS = v break } } addAlias := func(name string, fingerprint string) *api.ImageAlias { if defaultOS != "" { name = strings.TrimPrefix(name, fmt.Sprintf("%s/", defaultOS)) } if aliases[name] != nil { return nil } alias := api.ImageAliasesEntry{} alias.Name = name alias.Target = fingerprint aliases[name] = &alias return &api.ImageAlias{Name: name} } architectureName, _ := osarch.ArchitectureGetLocal() newImages := []api.Image{} for _, image := range images { if image.Aliases != nil { // Build a new list of aliases from the provided ones aliases := image.Aliases image.Aliases = nil for _, entry := range aliases { // Short if image.Architecture == architectureName { alias := addAlias(fmt.Sprintf("%s", entry.Name), image.Fingerprint) if alias != nil { image.Aliases = append(image.Aliases, *alias) } } // Medium alias := addAlias(fmt.Sprintf("%s/%s", entry.Name, image.Properties["architecture"]), image.Fingerprint) if alias != nil { image.Aliases = append(image.Aliases, *alias) } } } newImages = append(newImages, image) } return newImages, aliases, nil } func (s *SimpleStreams) getImages() ([]api.Image, map[string]*api.ImageAliasesEntry, error) { if s.cachedImages != nil && s.cachedAliases != nil { return s.cachedImages, s.cachedAliases, nil } images := []api.Image{} // Load the main index ssIndex, err := s.parseIndex() if err != nil { return nil, nil, err } // Iterate through the various image manifests for _, entry := range ssIndex.Index { // We only care about images if entry.DataType != "image-downloads" { continue } // No point downloading an empty image list if len(entry.Products) == 0 { continue } manifest, err := s.parseManifest(entry.Path) if err != nil { return nil, nil, err } manifestImages, _ := manifest.ToLXD() for _, image := range manifestImages { images = append(images, image) } } // Setup the aliases images, aliases, err := s.applyAliases(images) if err != nil { return nil, nil, err } s.cachedImages = images s.cachedAliases = aliases return images, aliases, nil } func (s *SimpleStreams) GetFiles(fingerprint string) (map[string]SimpleStreamsFile, error) { // Load the main index ssIndex, err := s.parseIndex() if err != nil { return nil, err } // Iterate through the various image manifests for _, entry := range ssIndex.Index { // We only care about images if entry.DataType != "image-downloads" { continue } // No point downloading an empty image list if len(entry.Products) == 0 { continue } manifest, err := s.parseManifest(entry.Path) if err != nil { return nil, err } manifestImages, downloads := manifest.ToLXD() for _, image := range manifestImages { if strings.HasPrefix(image.Fingerprint, fingerprint) { files := map[string]SimpleStreamsFile{} for _, path := range downloads[image.Fingerprint] { size, err := strconv.ParseInt(path[3], 10, 64) if err != nil { return nil, err } files[path[2]] = SimpleStreamsFile{ Path: path[0], Sha256: path[1], Size: size} } return files, nil } } } return nil, fmt.Errorf("Couldn't find the requested image") } func (s *SimpleStreams) downloadFile(path string, hash string, target string, progress func(int64, int64)) error { download := func(url string, hash string, target string) error { out, err := os.Create(target) if err != nil { return err } defer out.Close() req, err := http.NewRequest("GET", url, nil) if err != nil { return err } if s.useragent != "" { req.Header.Set("User-Agent", s.useragent) } r, err := s.http.Do(req) if err != nil { return err } defer r.Body.Close() if r.StatusCode != http.StatusOK { return fmt.Errorf("Unable to fetch %s: %s", url, r.Status) } body := &ioprogress.ProgressReader{ ReadCloser: r.Body, Tracker: &ioprogress.ProgressTracker{ Length: r.ContentLength, Handler: progress, }, } sha256 := sha256.New() _, err = io.Copy(io.MultiWriter(out, sha256), body) if err != nil { return err } result := fmt.Sprintf("%x", sha256.Sum(nil)) if result != hash { os.Remove(target) return fmt.Errorf("Hash mismatch for %s: %s != %s", path, result, hash) } return nil } // Try http first if strings.HasPrefix(s.url, "https://") { err := download(fmt.Sprintf("http://%s/%s", strings.TrimPrefix(s.url, "https://"), path), hash, target) if err == nil { return nil } } err := download(fmt.Sprintf("%s/%s", s.url, path), hash, target) if err != nil { return err } return nil } func (s *SimpleStreams) ListAliases() ([]api.ImageAliasesEntry, error) { _, aliasesMap, err := s.getImages() if err != nil { return nil, err } aliases := []api.ImageAliasesEntry{} for _, alias := range aliasesMap { aliases = append(aliases, *alias) } return aliases, nil } func (s *SimpleStreams) ListImages() ([]api.Image, error) { images, _, err := s.getImages() return images, err } func (s *SimpleStreams) GetAlias(name string) (*api.ImageAliasesEntry, error) { _, aliasesMap, err := s.getImages() if err != nil { return nil, err } alias, ok := aliasesMap[name] if !ok { return nil, fmt.Errorf("Alias '%s' doesn't exist", name) } return alias, nil } func (s *SimpleStreams) GetImage(fingerprint string) (*api.Image, error) { images, _, err := s.getImages() if err != nil { return nil, err } matches := []api.Image{} for _, image := range images { if strings.HasPrefix(image.Fingerprint, fingerprint) { matches = append(matches, image) } } if len(matches) == 0 { return nil, fmt.Errorf("The requested image couldn't be found.") } else if len(matches) > 1 { return nil, fmt.Errorf("More than one match for the provided partial fingerprint.") } return &matches[0], nil } func (s *SimpleStreams) ExportImage(image string, target string) (string, error) { if !shared.IsDir(target) { return "", fmt.Errorf("Split images can only be written to a directory.") } files, err := s.GetFiles(image) if err != nil { return "", err } for _, file := range files { fields := strings.Split(file.Path, "/") targetFile := filepath.Join(target, fields[len(fields)-1]) err := s.downloadFile(file.Path, file.Sha256, targetFile, nil) if err != nil { return "", err } } return target, nil } func (s *SimpleStreams) Download(image string, fileType string, target string, progress func(int64, int64)) error { files, err := s.GetFiles(image) if err != nil { return err } file, ok := files[fileType] if ok { return s.downloadFile(file.Path, file.Sha256, target, progress) } return fmt.Errorf("The file couldn't be found.") } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/proxy.go��������������������������������������������������������������������������0000644�0610621�0607500�00000006447�13172163242�016462� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared import ( "fmt" "net" "net/http" "net/url" "os" "strings" "sync" ) var ( httpProxyEnv = &envOnce{ names: []string{"HTTP_PROXY", "http_proxy"}, } httpsProxyEnv = &envOnce{ names: []string{"HTTPS_PROXY", "https_proxy"}, } noProxyEnv = &envOnce{ names: []string{"NO_PROXY", "no_proxy"}, } ) type envOnce struct { names []string once sync.Once val string } func (e *envOnce) Get() string { e.once.Do(e.init) return e.val } func (e *envOnce) init() { for _, n := range e.names { e.val = os.Getenv(n) if e.val != "" { return } } } // This is basically the same as golang's ProxyFromEnvironment, except it // doesn't fall back to http_proxy when https_proxy isn't around, which is // incorrect behavior. It still respects HTTP_PROXY, HTTPS_PROXY, and NO_PROXY. func ProxyFromEnvironment(req *http.Request) (*url.URL, error) { return ProxyFromConfig("", "", "")(req) } func ProxyFromConfig(httpsProxy string, httpProxy string, noProxy string) func(req *http.Request) (*url.URL, error) { return func(req *http.Request) (*url.URL, error) { var proxy, port string var err error switch req.URL.Scheme { case "https": proxy = httpsProxy if proxy == "" { proxy = httpsProxyEnv.Get() } port = ":443" case "http": proxy = httpProxy if proxy == "" { proxy = httpProxyEnv.Get() } port = ":80" default: return nil, fmt.Errorf("unknown scheme %s", req.URL.Scheme) } if proxy == "" { return nil, nil } addr := req.URL.Host if !hasPort(addr) { addr = addr + port } use, err := useProxy(addr, noProxy) if err != nil { return nil, err } if !use { return nil, nil } proxyURL, err := url.Parse(proxy) if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") { // proxy was bogus. Try prepending "http://" to it and // see if that parses correctly. If not, we fall // through and complain about the original one. if proxyURL, err := url.Parse("http://" + proxy); err == nil { return proxyURL, nil } } if err != nil { return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err) } return proxyURL, nil } } func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") } func useProxy(addr string, noProxy string) (bool, error) { if noProxy == "" { noProxy = noProxyEnv.Get() } if len(addr) == 0 { return true, nil } host, _, err := net.SplitHostPort(addr) if err != nil { return false, nil } if host == "localhost" { return false, nil } if ip := net.ParseIP(host); ip != nil { if ip.IsLoopback() { return false, nil } } if noProxy == "*" { return false, nil } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(noProxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p { return false, nil } if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) { // noProxy ".foo.com" matches "bar.foo.com" or "foo.com" return false, nil } if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' { // noProxy "foo.com" matches "bar.foo.com" return false, nil } } return true, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/osarch/���������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016216� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/osarch/tempfile_test.go�����������������������������������������������������������0000644�0610621�0607500�00000000673�13172163242�021417� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package osarch import ( "os" "github.com/stretchr/testify/suite" "github.com/lxc/lxd/shared" ) // WriteTempFile writes content to a temporary file. func WriteTempFile(s suite.Suite, dir string, prefix string, content string) (string, func()) { filename, err := shared.WriteTempFile(dir, prefix, content) if err != nil { s.T().Fatalf("failed to create temporary file: %v", err) } return filename, func() { os.Remove(filename) } } ���������������������������������������������������������������������lxd-2.0.11/shared/osarch/release_test.go������������������������������������������������������������0000644�0610621�0607500�00000003606�13172163242�021231� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package osarch import ( "fmt" "testing" "github.com/stretchr/testify/suite" ) type releaseTestSuite struct { suite.Suite } func TestReleaseTestSuite(t *testing.T) { suite.Run(t, new(releaseTestSuite)) } func (s *releaseTestSuite) TestGetLSBRelease() { content := `NAME="Ubuntu" ID="ubuntu" VERSION_ID="16.04" ` filename, cleanup := WriteTempFile(s.Suite, "", "os-release", content) defer cleanup() lsbRelease, err := getLSBRelease(filename) s.Nil(err) s.Equal( map[string]string{ "NAME": "Ubuntu", "ID": "ubuntu", "VERSION_ID": "16.04", }, lsbRelease) } func (s *releaseTestSuite) TestGetLSBReleaseSingleQuotes() { content := `NAME='Ubuntu'` filename, cleanup := WriteTempFile(s.Suite, "", "os-release", content) defer cleanup() lsbRelease, err := getLSBRelease(filename) s.Nil(err) s.Equal(map[string]string{"NAME": "Ubuntu"}, lsbRelease) } func (s *releaseTestSuite) TestGetLSBReleaseNoQuotes() { content := `NAME=Ubuntu` filename, cleanup := WriteTempFile(s.Suite, "", "os-release", content) defer cleanup() lsbRelease, err := getLSBRelease(filename) s.Nil(err) s.Equal(map[string]string{"NAME": "Ubuntu"}, lsbRelease) } func (s *releaseTestSuite) TestGetLSBReleaseSkipCommentsEmpty() { content := ` NAME="Ubuntu" ID="ubuntu" # skip this line VERSION_ID="16.04" ` filename, cleanup := WriteTempFile(s.Suite, "", "os-release", content) defer cleanup() lsbRelease, err := getLSBRelease(filename) s.Nil(err) s.Equal( map[string]string{ "NAME": "Ubuntu", "ID": "ubuntu", "VERSION_ID": "16.04", }, lsbRelease) } func (s *releaseTestSuite) TestGetLSBReleaseInvalidLine() { content := ` NAME="Ubuntu" this is invalid ID="ubuntu" ` filename, cleanup := WriteTempFile(s.Suite, "", "os-release", content) defer cleanup() _, err := getLSBRelease(filename) s.EqualError(err, fmt.Sprintf("%s: invalid format on line 3", filename)) } ��������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/osarch/release.go�����������������������������������������������������������������0000644�0610621�0607500�00000001610�13172163242�020163� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package osarch import ( "fmt" "io/ioutil" "os" "strings" ) // GetLSBRelease returns a map with Linux distribution information func GetLSBRelease() (map[string]string, error) { osRelease, err := getLSBRelease("/etc/os-release") if os.IsNotExist(err) { return getLSBRelease("/usr/lib/os-release") } return osRelease, err } func getLSBRelease(filename string) (map[string]string, error) { osRelease := make(map[string]string) data, err := ioutil.ReadFile(filename) if err != nil { return osRelease, err } for i, line := range strings.Split(string(data), "\n") { if len(line) == 0 { continue } if strings.HasPrefix(line, "#") { continue } tokens := strings.SplitN(line, "=", 2) if len(tokens) != 2 { return osRelease, fmt.Errorf("%s: invalid format on line %d", filename, i+1) } osRelease[tokens[0]] = strings.Trim(tokens[1], `'"`) } return osRelease, nil } ������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/osarch/architectures_others.go����������������������������������������������������0000644�0610621�0607500�00000000163�13172163242�022776� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !linux package osarch func ArchitectureGetLocal() (string, error) { return ArchitectureDefault, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/osarch/architectures_linux.go�����������������������������������������������������0000644�0610621�0607500�00000000452�13172163242�022632� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux package osarch import ( "github.com/lxc/lxd/shared" ) // ArchitectureGetLocal returns the local hardware architecture func ArchitectureGetLocal() (string, error) { uname, err := shared.Uname() if err != nil { return ArchitectureDefault, err } return uname.Machine, nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/osarch/architectures.go�����������������������������������������������������������0000644�0610621�0607500�00000006151�13172163242�021415� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package osarch import ( "fmt" ) const ( ARCH_UNKNOWN = 0 ARCH_32BIT_INTEL_X86 = 1 ARCH_64BIT_INTEL_X86 = 2 ARCH_32BIT_ARMV7_LITTLE_ENDIAN = 3 ARCH_64BIT_ARMV8_LITTLE_ENDIAN = 4 ARCH_32BIT_POWERPC_BIG_ENDIAN = 5 ARCH_64BIT_POWERPC_BIG_ENDIAN = 6 ARCH_64BIT_POWERPC_LITTLE_ENDIAN = 7 ARCH_64BIT_S390_BIG_ENDIAN = 8 ) var architectureNames = map[int]string{ ARCH_32BIT_INTEL_X86: "i686", ARCH_64BIT_INTEL_X86: "x86_64", ARCH_32BIT_ARMV7_LITTLE_ENDIAN: "armv7l", ARCH_64BIT_ARMV8_LITTLE_ENDIAN: "aarch64", ARCH_32BIT_POWERPC_BIG_ENDIAN: "ppc", ARCH_64BIT_POWERPC_BIG_ENDIAN: "ppc64", ARCH_64BIT_POWERPC_LITTLE_ENDIAN: "ppc64le", ARCH_64BIT_S390_BIG_ENDIAN: "s390x", } var architectureAliases = map[int][]string{ ARCH_32BIT_INTEL_X86: {"i386", "386"}, ARCH_64BIT_INTEL_X86: {"amd64"}, ARCH_32BIT_ARMV7_LITTLE_ENDIAN: {"armel", "armhf", "arm"}, ARCH_64BIT_ARMV8_LITTLE_ENDIAN: {"arm64"}, ARCH_32BIT_POWERPC_BIG_ENDIAN: {"powerpc"}, ARCH_64BIT_POWERPC_BIG_ENDIAN: {"powerpc64", "ppc64"}, ARCH_64BIT_POWERPC_LITTLE_ENDIAN: {"ppc64el"}, } var architecturePersonalities = map[int]string{ ARCH_32BIT_INTEL_X86: "linux32", ARCH_64BIT_INTEL_X86: "linux64", ARCH_32BIT_ARMV7_LITTLE_ENDIAN: "linux32", ARCH_64BIT_ARMV8_LITTLE_ENDIAN: "linux64", ARCH_32BIT_POWERPC_BIG_ENDIAN: "linux32", ARCH_64BIT_POWERPC_BIG_ENDIAN: "linux64", ARCH_64BIT_POWERPC_LITTLE_ENDIAN: "linux64", ARCH_64BIT_S390_BIG_ENDIAN: "linux64", } var architectureSupportedPersonalities = map[int][]int{ ARCH_32BIT_INTEL_X86: {}, ARCH_64BIT_INTEL_X86: {ARCH_32BIT_INTEL_X86}, ARCH_32BIT_ARMV7_LITTLE_ENDIAN: {}, ARCH_64BIT_ARMV8_LITTLE_ENDIAN: {ARCH_32BIT_ARMV7_LITTLE_ENDIAN}, ARCH_32BIT_POWERPC_BIG_ENDIAN: {}, ARCH_64BIT_POWERPC_BIG_ENDIAN: {ARCH_32BIT_POWERPC_BIG_ENDIAN}, ARCH_64BIT_POWERPC_LITTLE_ENDIAN: {}, ARCH_64BIT_S390_BIG_ENDIAN: {}, } const ArchitectureDefault = "x86_64" func ArchitectureName(arch int) (string, error) { arch_name, exists := architectureNames[arch] if exists { return arch_name, nil } return "unknown", fmt.Errorf("Architecture isn't supported: %d", arch) } func ArchitectureId(arch string) (int, error) { for arch_id, arch_name := range architectureNames { if arch_name == arch { return arch_id, nil } } for arch_id, arch_aliases := range architectureAliases { for _, arch_name := range arch_aliases { if arch_name == arch { return arch_id, nil } } } return 0, fmt.Errorf("Architecture isn't supported: %s", arch) } func ArchitecturePersonality(arch int) (string, error) { arch_personality, exists := architecturePersonalities[arch] if exists { return arch_personality, nil } return "", fmt.Errorf("Architecture isn't supported: %d", arch) } func ArchitecturePersonalities(arch int) ([]int, error) { personalities, exists := architectureSupportedPersonalities[arch] if exists { return personalities, nil } return []int{}, fmt.Errorf("Architecture isn't supported: %d", arch) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/network_linux.go������������������������������������������������������������������0000644�0610621�0607500�00000002136�13172163242�020200� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux package shared import ( "io" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared/logger" ) func WebsocketExecMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser, exited chan bool, fd int) (chan bool, chan bool) { readDone := make(chan bool, 1) writeDone := make(chan bool, 1) go defaultWriter(conn, w, writeDone) go func(conn *websocket.Conn, r io.ReadCloser) { in := ExecReaderToChannel(r, -1, exited, fd) for { buf, ok := <-in if !ok { r.Close() logger.Debugf("sending write barrier") conn.WriteMessage(websocket.TextMessage, []byte{}) readDone <- true return } w, err := conn.NextWriter(websocket.BinaryMessage) if err != nil { logger.Debugf("Got error getting next writer %s", err) break } _, err = w.Write(buf) w.Close() if err != nil { logger.Debugf("Got err writing %s", err) break } } closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "") conn.WriteMessage(websocket.CloseMessage, closeMsg) readDone <- true r.Close() }(conn, r) return readDone, writeDone } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/network.go������������������������������������������������������������������������0000644�0610621�0607500�00000021350�13172163242�016760� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared import ( "crypto/tls" "crypto/x509" "encoding/pem" "fmt" "io" "io/ioutil" "net" "net/http" "time" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared/logger" ) func RFC3493Dialer(network, address string) (net.Conn, error) { host, port, err := net.SplitHostPort(address) if err != nil { return nil, err } addrs, err := net.LookupHost(host) if err != nil { return nil, err } for _, a := range addrs { c, err := net.DialTimeout(network, net.JoinHostPort(a, port), 10*time.Second) if err != nil { continue } return c, err } return nil, fmt.Errorf("Unable to connect to: " + address) } func initTLSConfig() *tls.Config { return &tls.Config{ MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, CipherSuites: []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}, PreferServerCipherSuites: true, } } func finalizeTLSConfig(tlsConfig *tls.Config, tlsRemoteCert *x509.Certificate) { // Trusted certificates if tlsRemoteCert != nil { caCertPool := tlsConfig.RootCAs if caCertPool == nil { caCertPool = x509.NewCertPool() } // Make it a valid RootCA tlsRemoteCert.IsCA = true tlsRemoteCert.KeyUsage = x509.KeyUsageCertSign // Setup the pool caCertPool.AddCert(tlsRemoteCert) tlsConfig.RootCAs = caCertPool // Set the ServerName if tlsRemoteCert.DNSNames != nil { tlsConfig.ServerName = tlsRemoteCert.DNSNames[0] } } tlsConfig.BuildNameToCertificate() } func GetTLSConfig(tlsClientCertFile string, tlsClientKeyFile string, tlsClientCAFile string, tlsRemoteCert *x509.Certificate) (*tls.Config, error) { tlsConfig := initTLSConfig() // Client authentication if tlsClientCertFile != "" && tlsClientKeyFile != "" { cert, err := tls.LoadX509KeyPair(tlsClientCertFile, tlsClientKeyFile) if err != nil { return nil, err } tlsConfig.Certificates = []tls.Certificate{cert} } if tlsClientCAFile != "" { caCertificates, err := ioutil.ReadFile(tlsClientCAFile) if err != nil { return nil, err } caPool := x509.NewCertPool() caPool.AppendCertsFromPEM(caCertificates) tlsConfig.RootCAs = caPool } finalizeTLSConfig(tlsConfig, tlsRemoteCert) return tlsConfig, nil } func GetTLSConfigMem(tlsClientCert string, tlsClientKey string, tlsClientCA string, tlsRemoteCertPEM string, insecureSkipVerify bool) (*tls.Config, error) { tlsConfig := initTLSConfig() tlsConfig.InsecureSkipVerify = insecureSkipVerify // Client authentication if tlsClientCert != "" && tlsClientKey != "" { cert, err := tls.X509KeyPair([]byte(tlsClientCert), []byte(tlsClientKey)) if err != nil { return nil, err } tlsConfig.Certificates = []tls.Certificate{cert} } var tlsRemoteCert *x509.Certificate if tlsRemoteCertPEM != "" { // Ignore any content outside of the PEM bytes we care about certBlock, _ := pem.Decode([]byte(tlsRemoteCertPEM)) if certBlock == nil { return nil, fmt.Errorf("Invalid remote certificate") } var err error tlsRemoteCert, err = x509.ParseCertificate(certBlock.Bytes) if err != nil { return nil, err } } if tlsClientCA != "" { caPool := x509.NewCertPool() caPool.AppendCertsFromPEM([]byte(tlsClientCA)) tlsConfig.RootCAs = caPool } finalizeTLSConfig(tlsConfig, tlsRemoteCert) return tlsConfig, nil } func IsLoopback(iface *net.Interface) bool { return int(iface.Flags&net.FlagLoopback) > 0 } func WebsocketSendStream(conn *websocket.Conn, r io.Reader, bufferSize int) chan bool { ch := make(chan bool) if r == nil { close(ch) return ch } go func(conn *websocket.Conn, r io.Reader) { in := ReaderToChannel(r, bufferSize) for { buf, ok := <-in if !ok { break } w, err := conn.NextWriter(websocket.BinaryMessage) if err != nil { logger.Debugf("Got error getting next writer %s", err) break } _, err = w.Write(buf) w.Close() if err != nil { logger.Debugf("Got err writing %s", err) break } } conn.WriteMessage(websocket.TextMessage, []byte{}) ch <- true }(conn, r) return ch } func WebsocketRecvStream(w io.Writer, conn *websocket.Conn) chan bool { ch := make(chan bool) go func(w io.Writer, conn *websocket.Conn) { for { mt, r, err := conn.NextReader() if mt == websocket.CloseMessage { logger.Debugf("Got close message for reader") break } if mt == websocket.TextMessage { logger.Debugf("got message barrier") break } if err != nil { logger.Debugf("Got error getting next reader %s, %s", err, w) break } buf, err := ioutil.ReadAll(r) if err != nil { logger.Debugf("Got error writing to writer %s", err) break } if w == nil { continue } i, err := w.Write(buf) if i != len(buf) { logger.Debugf("Didn't write all of buf") break } if err != nil { logger.Debugf("Error writing buf %s", err) break } } ch <- true }(w, conn) return ch } func WebsocketProxy(source *websocket.Conn, target *websocket.Conn) chan bool { forward := func(in *websocket.Conn, out *websocket.Conn, ch chan bool) { for { mt, r, err := in.NextReader() if err != nil { break } w, err := out.NextWriter(mt) if err != nil { break } _, err = io.Copy(w, r) w.Close() if err != nil { break } } ch <- true } chSend := make(chan bool) go forward(source, target, chSend) chRecv := make(chan bool) go forward(target, source, chRecv) ch := make(chan bool) go func() { select { case <-chSend: case <-chRecv: } source.Close() target.Close() ch <- true }() return ch } func defaultReader(conn *websocket.Conn, r io.ReadCloser, readDone chan<- bool) { /* For now, we don't need to adjust buffer sizes in * WebsocketMirror, since it's used for interactive things like * exec. */ in := ReaderToChannel(r, -1) for { buf, ok := <-in if !ok { r.Close() logger.Debugf("sending write barrier") conn.WriteMessage(websocket.TextMessage, []byte{}) readDone <- true return } w, err := conn.NextWriter(websocket.BinaryMessage) if err != nil { logger.Debugf("Got error getting next writer %s", err) break } _, err = w.Write(buf) w.Close() if err != nil { logger.Debugf("Got err writing %s", err) break } } closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "") conn.WriteMessage(websocket.CloseMessage, closeMsg) readDone <- true r.Close() } func defaultWriter(conn *websocket.Conn, w io.WriteCloser, writeDone chan<- bool) { for { mt, r, err := conn.NextReader() if err != nil { logger.Debugf("Got error getting next reader %s, %s", err, w) break } if mt == websocket.CloseMessage { logger.Debugf("Got close message for reader") break } if mt == websocket.TextMessage { logger.Debugf("Got message barrier, resetting stream") break } buf, err := ioutil.ReadAll(r) if err != nil { logger.Debugf("Got error writing to writer %s", err) break } i, err := w.Write(buf) if i != len(buf) { logger.Debugf("Didn't write all of buf") break } if err != nil { logger.Debugf("Error writing buf %s", err) break } } writeDone <- true w.Close() } // WebsocketMirror allows mirroring a reader to a websocket and taking the // result and writing it to a writer. This function allows for multiple // mirrorings and correctly negotiates stream endings. However, it means any // websocket.Conns passed to it are live when it returns, and must be closed // explicitly. type WebSocketMirrorReader func(conn *websocket.Conn, r io.ReadCloser, readDone chan<- bool) type WebSocketMirrorWriter func(conn *websocket.Conn, w io.WriteCloser, writeDone chan<- bool) func WebsocketMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser, Reader WebSocketMirrorReader, Writer WebSocketMirrorWriter) (chan bool, chan bool) { readDone := make(chan bool, 1) writeDone := make(chan bool, 1) ReadFunc := Reader if ReadFunc == nil { ReadFunc = defaultReader } WriteFunc := Writer if WriteFunc == nil { WriteFunc = defaultWriter } go ReadFunc(conn, r, readDone) go WriteFunc(conn, w, writeDone) return readDone, writeDone } var WebsocketUpgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } // AllocatePort asks the kernel for a free open port that is ready to use func AllocatePort() (int, error) { addr, err := net.ResolveTCPAddr("tcp", "localhost:0") if err != nil { return -1, err } l, err := net.ListenTCP("tcp", addr) if err != nil { return -1, err } defer l.Close() return l.Addr().(*net.TCPAddr).Port, nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/logging/��������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016365� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/logging/log_windows.go������������������������������������������������������������0000644�0610621�0607500�00000000346�13172163242�021252� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build windows package logging import ( log "gopkg.in/inconshreveable/log15.v2" ) // getSystemHandler on Windows does nothing. func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler { return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/logging/log_posix.go��������������������������������������������������������������0000644�0610621�0607500�00000000766�13172163242�020730� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux darwin package logging import ( slog "log/syslog" log "gopkg.in/inconshreveable/log15.v2" ) // getSystemHandler on Linux writes messages to syslog. func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler { // SyslogHandler if syslog != "" { if !debug { return log.LvlFilterHandler( log.LvlInfo, log.Must.SyslogHandler(slog.LOG_INFO, syslog, format), ) } return log.Must.SyslogHandler(slog.LOG_INFO, syslog, format) } return nil } ����������lxd-2.0.11/shared/logging/log.go��������������������������������������������������������������������0000644�0610621�0607500�00000004145�13172163242�017501� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package logging import ( "fmt" "os" "path/filepath" log "gopkg.in/inconshreveable/log15.v2" "gopkg.in/inconshreveable/log15.v2/term" "github.com/lxc/lxd/shared/logger" ) // GetLogger returns a logger suitable for using as logger.Log. func GetLogger(syslog string, logfile string, verbose bool, debug bool, customHandler log.Handler) (logger.Logger, error) { Log := log.New() var handlers []log.Handler var syshandler log.Handler // Format handler format := LogfmtFormat() if term.IsTty(os.Stderr.Fd()) { format = TerminalFormat() } // System specific handler syshandler = getSystemHandler(syslog, debug, format) if syshandler != nil { handlers = append(handlers, syshandler) } // FileHandler if logfile != "" { if !pathExists(filepath.Dir(logfile)) { return nil, fmt.Errorf("Log file path doesn't exist: %s", filepath.Dir(logfile)) } if !debug { handlers = append( handlers, log.LvlFilterHandler( log.LvlInfo, log.Must.FileHandler(logfile, format), ), ) } else { handlers = append(handlers, log.Must.FileHandler(logfile, format)) } } // StderrHandler if verbose || debug { if !debug { handlers = append( handlers, log.LvlFilterHandler( log.LvlInfo, log.StreamHandler(os.Stderr, format), ), ) } else { handlers = append(handlers, log.StreamHandler(os.Stderr, format)) } } else { handlers = append( handlers, log.LvlFilterHandler( log.LvlWarn, log.StreamHandler(os.Stderr, format), ), ) } if customHandler != nil { handlers = append(handlers, customHandler) } Log.SetHandler(log.MultiHandler(handlers...)) return Log, nil } // AddContext will return a copy of the logger with extra context added func AddContext(logger logger.Logger, ctx log.Ctx) logger.Logger { log15logger, ok := logger.(log.Logger) if !ok { logger.Error("couldn't downcast logger to add context", log.Ctx{"logger": log15logger, "ctx": ctx}) return logger } return log15logger.New(ctx) } func pathExists(name string) bool { _, err := os.Lstat(name) if err != nil && os.IsNotExist(err) { return false } return true } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/logging/format.go�����������������������������������������������������������������0000644�0610621�0607500�00000010041�13172163242�020200� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package logging import ( "bytes" "fmt" "reflect" "sort" "strconv" "strings" "time" log "gopkg.in/inconshreveable/log15.v2" ) const ( timeFormat = "2006-01-02T15:04:05-0700" floatFormat = 'f' errorKey = "LOG15_ERROR" termTimeFormat = "01-02|15:04:05" termMsgJust = 40 ) // Imported from the log15 project // TerminalFormat formats log records optimized for human readability on // a terminal with color-coded level output and terser human friendly timestamp. // This format should only be used for interactive programs or while developing. // // [TIME] [LEVEL] MESAGE key=value key=value ... // // Example: // // [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002 // func TerminalFormat() log.Format { return log.FormatFunc(func(r *log.Record) []byte { var color = 0 switch r.Lvl { case log.LvlCrit: color = 35 case log.LvlError: color = 31 case log.LvlWarn: color = 33 case log.LvlInfo: color = 32 case log.LvlDebug: color = 36 } b := &bytes.Buffer{} lvl := strings.ToUpper(r.Lvl.String()) if color > 0 { fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %s ", color, lvl, r.Time.Format(termTimeFormat), r.Msg) } else { fmt.Fprintf(b, "[%s] [%s] %s ", lvl, r.Time.Format(termTimeFormat), r.Msg) } // try to justify the log output for short messages if len(r.Ctx) > 0 && len(r.Msg) < termMsgJust { b.Write(bytes.Repeat([]byte{' '}, termMsgJust-len(r.Msg))) } // print the keys logfmt style logfmt(b, r.Ctx, color) return b.Bytes() }) } // LogfmtFormat return a formatter for a text log file func LogfmtFormat() log.Format { return log.FormatFunc(func(r *log.Record) []byte { common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg} buf := &bytes.Buffer{} logfmt(buf, append(common, r.Ctx...), 0) return buf.Bytes() }) } func logfmt(buf *bytes.Buffer, ctx []interface{}, color int) { entries := []string{} for i := 0; i < len(ctx); i += 2 { k, ok := ctx[i].(string) v := formatLogfmtValue(ctx[i+1]) if !ok { k, v = errorKey, formatLogfmtValue(k) } // XXX: we should probably check that all of your key bytes aren't invalid if color > 0 { entries = append(entries, fmt.Sprintf("\x1b[%dm%s\x1b[0m=%s", color, k, v)) } else { entries = append(entries, fmt.Sprintf("%s=%s", k, v)) } } sort.Strings(entries) for i, v := range entries { if i != 0 { buf.WriteByte(' ') } fmt.Fprint(buf, v) } buf.WriteByte('\n') } func formatShared(value interface{}) (result interface{}) { defer func() { if err := recover(); err != nil { if v := reflect.ValueOf(value); v.Kind() == reflect.Ptr && v.IsNil() { result = "nil" } else { panic(err) } } }() switch v := value.(type) { case time.Time: return v.Format(timeFormat) case error: return v.Error() case fmt.Stringer: return v.String() default: return v } } // formatValue formats a value for serialization func formatLogfmtValue(value interface{}) string { if value == nil { return "nil" } value = formatShared(value) switch v := value.(type) { case bool: return strconv.FormatBool(v) case float32: return strconv.FormatFloat(float64(v), floatFormat, 3, 64) case float64: return strconv.FormatFloat(v, floatFormat, 3, 64) case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: return fmt.Sprintf("%d", value) case string: return escapeString(v) default: return escapeString(fmt.Sprintf("%+v", value)) } } func escapeString(s string) string { needQuotes := false e := bytes.Buffer{} e.WriteByte('"') for _, r := range s { if r <= ' ' || r == '=' || r == '"' { needQuotes = true } switch r { case '\\', '"': e.WriteByte('\\') e.WriteByte(byte(r)) case '\n': e.WriteByte('\\') e.WriteByte('n') case '\r': e.WriteByte('\\') e.WriteByte('r') case '\t': e.WriteByte('\\') e.WriteByte('t') default: e.WriteRune(r) } } e.WriteByte('"') start, stop := 0, e.Len() if !needQuotes { start, stop = 1, stop-1 } return string(e.Bytes()[start:stop]) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/logger/���������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016216� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/logger/log_debug.go���������������������������������������������������������������0000644�0610621�0607500�00000006276�13172163242�020507� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build logdebug package logger import ( "fmt" "runtime" ) type Logger interface { Debug(msg string, ctx ...interface{}) Info(msg string, ctx ...interface{}) Warn(msg string, ctx ...interface{}) Error(msg string, ctx ...interface{}) Crit(msg string, ctx ...interface{}) } var Log Logger type nullLogger struct{} func (nl nullLogger) Debug(msg string, ctx ...interface{}) {} func (nl nullLogger) Info(msg string, ctx ...interface{}) {} func (nl nullLogger) Warn(msg string, ctx ...interface{}) {} func (nl nullLogger) Error(msg string, ctx ...interface{}) {} func (nl nullLogger) Crit(msg string, ctx ...interface{}) {} func init() { Log = nullLogger{} } // General wrappers around Logger interface functions. func Debug(msg string, ctx ...interface{}) { if Log != nil { pc, fn, line, _ := runtime.Caller(1) msg := fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Debug(msg, ctx...) } } func Info(msg string, ctx ...interface{}) { if Log != nil { pc, fn, line, _ := runtime.Caller(1) msg := fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Info(msg, ctx...) } } func Warn(msg string, ctx ...interface{}) { if Log != nil { pc, fn, line, _ := runtime.Caller(1) msg := fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Warn(msg, ctx...) } } func Error(msg string, ctx ...interface{}) { if Log != nil { pc, fn, line, _ := runtime.Caller(1) msg := fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Error(msg, ctx...) } } func Crit(msg string, ctx ...interface{}) { if Log != nil { pc, fn, line, _ := runtime.Caller(1) msg := fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Crit(msg, ctx...) } } // Wrappers around Logger interface functions that send a string to the Logger // by running it through fmt.Sprintf(). func Infof(format string, args ...interface{}) { if Log != nil { msg := fmt.Sprintf(format, args...) pc, fn, line, _ := runtime.Caller(1) msg = fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Info(msg) } } func Debugf(format string, args ...interface{}) { if Log != nil { msg := fmt.Sprintf(format, args...) pc, fn, line, _ := runtime.Caller(1) msg = fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Debug(msg) } } func Warnf(format string, args ...interface{}) { if Log != nil { msg := fmt.Sprintf(format, args...) pc, fn, line, _ := runtime.Caller(1) msg = fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Warn(msg) } } func Errorf(format string, args ...interface{}) { if Log != nil { msg := fmt.Sprintf(format, args...) pc, fn, line, _ := runtime.Caller(1) msg = fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Error(msg) } } func Critf(format string, args ...interface{}) { if Log != nil { msg := fmt.Sprintf(format, args...) pc, fn, line, _ := runtime.Caller(1) msg = fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg) Log.Crit(msg) } } func PrintStack() { buf := make([]byte, 1<<16) runtime.Stack(buf, true) Errorf("%s", buf) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/logger/log.go���������������������������������������������������������������������0000644�0610621�0607500�00000004742�13172163242�017335� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !logdebug package logger import ( "fmt" ) // Logger is the main logging interface type Logger interface { Debug(msg string, ctx ...interface{}) Info(msg string, ctx ...interface{}) Warn(msg string, ctx ...interface{}) Error(msg string, ctx ...interface{}) Crit(msg string, ctx ...interface{}) } // Log contains the logger used by all the logging functions var Log Logger type nullLogger struct{} func (nl nullLogger) Debug(msg string, ctx ...interface{}) {} func (nl nullLogger) Info(msg string, ctx ...interface{}) {} func (nl nullLogger) Warn(msg string, ctx ...interface{}) {} func (nl nullLogger) Error(msg string, ctx ...interface{}) {} func (nl nullLogger) Crit(msg string, ctx ...interface{}) {} func init() { Log = nullLogger{} } // Debug logs a message (with optional context) at the DEBUG log level func Debug(msg string, ctx ...interface{}) { if Log != nil { Log.Debug(msg, ctx...) } } // Info logs a message (with optional context) at the INFO log level func Info(msg string, ctx ...interface{}) { if Log != nil { Log.Info(msg, ctx...) } } // Warn logs a message (with optional context) at the WARNING log level func Warn(msg string, ctx ...interface{}) { if Log != nil { Log.Warn(msg, ctx...) } } // Error logs a message (with optional context) at the ERROR log level func Error(msg string, ctx ...interface{}) { if Log != nil { Log.Error(msg, ctx...) } } // Crit logs a message (with optional context) at the CRITICAL log level func Crit(msg string, ctx ...interface{}) { if Log != nil { Log.Crit(msg, ctx...) } } // Infof logs at the INFO log level using a standard printf format string func Infof(format string, args ...interface{}) { if Log != nil { Log.Info(fmt.Sprintf(format, args...)) } } // Debugf logs at the DEBUG log level using a standard printf format string func Debugf(format string, args ...interface{}) { if Log != nil { Log.Debug(fmt.Sprintf(format, args...)) } } // Warnf logs at the WARNING log level using a standard printf format string func Warnf(format string, args ...interface{}) { if Log != nil { Log.Warn(fmt.Sprintf(format, args...)) } } // Errorf logs at the ERROR log level using a standard printf format string func Errorf(format string, args ...interface{}) { if Log != nil { Log.Error(fmt.Sprintf(format, args...)) } } // Critf logs at the CRITICAL log level using a standard printf format string func Critf(format string, args ...interface{}) { if Log != nil { Log.Crit(fmt.Sprintf(format, args...)) } } ������������������������������lxd-2.0.11/shared/logger/format.go������������������������������������������������������������������0000644�0610621�0607500�00000001021�13172163242�020027� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package logger import ( "encoding/json" "fmt" "runtime" ) // Pretty will attempt to convert any Go structure into a string suitable for logging func Pretty(input interface{}) string { pretty, err := json.MarshalIndent(input, "\t", "\t") if err != nil { return fmt.Sprintf("%v", input) } return fmt.Sprintf("\n\t%s", pretty) } // GetStack will convert the Go stack into a string suitable for logging func GetStack() string { buf := make([]byte, 1<<16) runtime.Stack(buf, true) return fmt.Sprintf("\n\t%s", buf) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/json.go���������������������������������������������������������������������������0000644�0610621�0607500�00000003004�13172163242�016234� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared import ( "bytes" "encoding/json" "fmt" "github.com/lxc/lxd/shared/logger" ) type Jmap map[string]interface{} func (m Jmap) GetString(key string) (string, error) { if val, ok := m[key]; !ok { return "", fmt.Errorf("Response was missing `%s`", key) } else if val, ok := val.(string); !ok { return "", fmt.Errorf("`%s` was not a string", key) } else { return val, nil } } func (m Jmap) GetMap(key string) (Jmap, error) { if val, ok := m[key]; !ok { return nil, fmt.Errorf("Response was missing `%s`", key) } else if val, ok := val.(map[string]interface{}); !ok { return nil, fmt.Errorf("`%s` was not a map, got %T", key, m[key]) } else { return val, nil } } func (m Jmap) GetInt(key string) (int, error) { if val, ok := m[key]; !ok { return -1, fmt.Errorf("Response was missing `%s`", key) } else if val, ok := val.(float64); !ok { return -1, fmt.Errorf("`%s` was not an int", key) } else { return int(val), nil } } func (m Jmap) GetBool(key string) (bool, error) { if val, ok := m[key]; !ok { return false, fmt.Errorf("Response was missing `%s`", key) } else if val, ok := val.(bool); !ok { return false, fmt.Errorf("`%s` was not an int", key) } else { return val, nil } } func DebugJson(r *bytes.Buffer) { pretty := &bytes.Buffer{} if err := json.Indent(pretty, r.Bytes(), "\t", "\t"); err != nil { logger.Debugf("error indenting json: %s", err) return } // Print the JSON without the last "\n" str := pretty.String() logger.Debugf("\n\t%s", str[0:len(str)-1]) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/ioprogress/�����������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�017133� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/ioprogress/writer.go��������������������������������������������������������������0000644�0610621�0607500�00000000767�13172163242�021010� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ioprogress import ( "io" ) // ProgressWriter is a wrapper around WriteCloser which allows for progress tracking type ProgressWriter struct { io.WriteCloser Tracker *ProgressTracker } // Write in ProgressWriter is the same as io.Write func (pt *ProgressWriter) Write(p []byte) (int, error) { // Do normal writer tasks n, err := pt.WriteCloser.Write(p) // Do the actual progress tracking if pt.Tracker != nil { pt.Tracker.total += int64(n) pt.Tracker.update(n) } return n, err } ���������lxd-2.0.11/shared/ioprogress/tracker.go�������������������������������������������������������������0000644�0610621�0607500�00000002766�13172163242�021130� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ioprogress import ( "time" ) // ProgressTracker provides the stream information needed for tracking type ProgressTracker struct { Length int64 Handler func(int64, int64) percentage float64 total int64 start *time.Time last *time.Time } func (pt *ProgressTracker) update(n int) { // Skip the rest if no handler attached if pt.Handler == nil { return } // Initialize start time if needed if pt.start == nil { cur := time.Now() pt.start = &cur pt.last = pt.start } // Skip if no data to count if n <= 0 { return } // Update interval handling var percentage float64 if pt.Length > 0 { // If running in relative mode, check that we increased by at least 1% percentage = float64(pt.total) / float64(pt.Length) * float64(100) if percentage-pt.percentage < 0.9 { return } } else { // If running in absolute mode, check that at least a second elapsed interval := time.Since(*pt.last).Seconds() if interval < 1 { return } } // Determine speed speedInt := int64(0) duration := time.Since(*pt.start).Seconds() if duration > 0 { speed := float64(pt.total) / duration speedInt = int64(speed) } // Determine progress progressInt := int64(0) if pt.Length > 0 { pt.percentage = percentage progressInt = int64(1 - (int(percentage) % 1) + int(percentage)) if progressInt > 100 { progressInt = 100 } } else { progressInt = pt.total // Update timestamp cur := time.Now() pt.last = &cur } pt.Handler(progressInt, speedInt) } ����������lxd-2.0.11/shared/ioprogress/reader.go��������������������������������������������������������������0000644�0610621�0607500�00000000760�13172163242�020727� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package ioprogress import ( "io" ) // ProgressReader is a wrapper around ReadCloser which allows for progress tracking type ProgressReader struct { io.ReadCloser Tracker *ProgressTracker } // Read in ProgressReader is the same as io.Read func (pt *ProgressReader) Read(p []byte) (int, error) { // Do normal reader tasks n, err := pt.ReadCloser.Read(p) // Do the actual progress tracking if pt.Tracker != nil { pt.Tracker.total += int64(n) pt.Tracker.update(n) } return n, err } ����������������lxd-2.0.11/shared/idmap/����������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016031� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/idmap/shift_linux.go��������������������������������������������������������������0000644�0610621�0607500�00000010645�13172163242�020722� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux // +build cgo package idmap import ( "fmt" "os" "unsafe" ) // #cgo LDFLAGS: -lacl /* #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/acl.h> int shiftowner(char *basepath, char *path, int uid, int gid) { struct stat sb; int fd, r; char fdpath[PATH_MAX]; char realpath[PATH_MAX]; fd = open(path, O_PATH|O_NOFOLLOW); if (fd < 0 ) { perror("Failed open"); return 1; } r = sprintf(fdpath, "/proc/self/fd/%d", fd); if (r < 0) { perror("Failed sprintf"); close(fd); return 1; } r = readlink(fdpath, realpath, PATH_MAX); if (r < 0) { perror("Failed readlink"); close(fd); return 1; } if (strlen(realpath) < strlen(basepath)) { printf("Invalid path, source (%s) is outside of basepath (%s).\n", realpath, basepath); close(fd); return 1; } if (strncmp(realpath, basepath, strlen(basepath))) { printf("Invalid path, source (%s) is outside of basepath (%s).\n", realpath, basepath); close(fd); return 1; } r = fstat(fd, &sb); if (r < 0) { perror("Failed fstat"); close(fd); return 1; } r = fchownat(fd, "", uid, gid, AT_EMPTY_PATH|AT_SYMLINK_NOFOLLOW); if (r < 0) { perror("Failed chown"); close(fd); return 1; } if (!S_ISLNK(sb.st_mode)) { r = chmod(fdpath, sb.st_mode); if (r < 0) { perror("Failed chmod"); close(fd); return 1; } } close(fd); return 0; } */ import "C" // ShiftOwner updates uid and gid for a file when entering/exiting a namespace func ShiftOwner(basepath string, path string, uid int, gid int) error { cbasepath := C.CString(basepath) defer C.free(unsafe.Pointer(cbasepath)) cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) r := C.shiftowner(cbasepath, cpath, C.int(uid), C.int(gid)) if r != 0 { return fmt.Errorf("Failed to change ownership of: %s", path) } return nil } // ShiftACL updates uid and gid for file ACLs when entering/exiting a namespace func ShiftACL(path string, shiftIds func(uid int64, gid int64) (int64, int64)) error { finfo, err := os.Lstat(path) if err != nil { return err } if finfo.Mode()&os.ModeSymlink != 0 { return nil } err = shiftAclType(path, C.ACL_TYPE_ACCESS, shiftIds) if err != nil { return err } err = shiftAclType(path, C.ACL_TYPE_DEFAULT, shiftIds) if err != nil { return err } return nil } func shiftAclType(path string, aclType _Ctype_acl_type_t, shiftIds func(uid int64, gid int64) (int64, int64)) error { // Convert the path to something usable with cgo cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) // Read the current ACL set for the requested type acl := C.acl_get_file(cpath, aclType) if acl == nil { return nil } defer C.acl_free(unsafe.Pointer(acl)) newAcl := C.acl_init(0) defer C.acl_free(unsafe.Pointer(newAcl)) // Iterate through all ACL entries update := false for entryId := C.ACL_FIRST_ENTRY; ; entryId = C.ACL_NEXT_ENTRY { var ent C.acl_entry_t var newEnt C.acl_entry_t var tag C.acl_tag_t // Get the ACL entry ret := C.acl_get_entry(acl, C.int(entryId), &ent) if ret == 0 { break } else if ret < 0 { return fmt.Errorf("Failed to get the ACL entry for %s", path) } // Setup the new entry ret = C.acl_create_entry(&newAcl, &newEnt) if ret == -1 { return fmt.Errorf("Failed to allocate a new ACL entry for %s", path) } ret = C.acl_copy_entry(newEnt, ent) if ret == -1 { return fmt.Errorf("Failed to copy the ACL entry for %s", path) } // Get the ACL type ret = C.acl_get_tag_type(newEnt, &tag) if ret == -1 { return fmt.Errorf("Failed to get the ACL type for %s", path) } // We only care about user and group ACLs, copy anything else if tag != C.ACL_USER && tag != C.ACL_GROUP { continue } // Get the value idp := (*C.id_t)(C.acl_get_qualifier(newEnt)) if idp == nil { return fmt.Errorf("Failed to get current ACL value for %s", path) } // Shift the value newId, _ := shiftIds((int64)(*idp), -1) // Update the new entry with the shifted value ret = C.acl_set_qualifier(newEnt, unsafe.Pointer(&newId)) if ret == -1 { return fmt.Errorf("Failed to set ACL qualifier on %s", path) } update = true } // Update the on-disk ACLs to match if update { ret := C.acl_set_file(cpath, aclType, newAcl) if ret == -1 { return fmt.Errorf("Failed to change ACLs on %s", path) } } return nil } �������������������������������������������������������������������������������������������lxd-2.0.11/shared/idmap/idmapset_linux_test.go������������������������������������������������������0000644�0610621�0607500�00000005551�13172163242�022452� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package idmap import ( "fmt" "testing" ) func TestIdmapSetAddSafe_split(t *testing.T) { orig := IdmapSet{Idmap: []IdmapEntry{{Isuid: true, Hostid: 1000, Nsid: 0, Maprange: 1000}}} if err := orig.AddSafe(IdmapEntry{Isuid: true, Hostid: 500, Nsid: 500, Maprange: 10}); err != nil { t.Error(err) return } if orig.Idmap[0].Hostid != 1000 || orig.Idmap[0].Nsid != 0 || orig.Idmap[0].Maprange != 500 { t.Error(fmt.Errorf("bad range: %v", orig.Idmap[0])) return } if orig.Idmap[1].Hostid != 500 || orig.Idmap[1].Nsid != 500 || orig.Idmap[1].Maprange != 10 { t.Error(fmt.Errorf("bad range: %v", orig.Idmap[1])) return } if orig.Idmap[2].Hostid != 1510 || orig.Idmap[2].Nsid != 510 || orig.Idmap[2].Maprange != 490 { t.Error(fmt.Errorf("bad range: %v", orig.Idmap[2])) return } if len(orig.Idmap) != 3 { t.Error("too many idmap entries") return } } func TestIdmapSetAddSafe_lower(t *testing.T) { orig := IdmapSet{Idmap: []IdmapEntry{{Isuid: true, Hostid: 1000, Nsid: 0, Maprange: 1000}}} if err := orig.AddSafe(IdmapEntry{Isuid: true, Hostid: 500, Nsid: 0, Maprange: 10}); err != nil { t.Error(err) return } if orig.Idmap[0].Hostid != 500 || orig.Idmap[0].Nsid != 0 || orig.Idmap[0].Maprange != 10 { t.Error(fmt.Errorf("bad range: %v", orig.Idmap[0])) return } if orig.Idmap[1].Hostid != 1010 || orig.Idmap[1].Nsid != 10 || orig.Idmap[1].Maprange != 990 { t.Error(fmt.Errorf("bad range: %v", orig.Idmap[1])) return } if len(orig.Idmap) != 2 { t.Error("too many idmap entries") return } } func TestIdmapSetAddSafe_upper(t *testing.T) { orig := IdmapSet{Idmap: []IdmapEntry{{Isuid: true, Hostid: 1000, Nsid: 0, Maprange: 1000}}} if err := orig.AddSafe(IdmapEntry{Isuid: true, Hostid: 500, Nsid: 995, Maprange: 10}); err != nil { t.Error(err) return } if orig.Idmap[0].Hostid != 1000 || orig.Idmap[0].Nsid != 0 || orig.Idmap[0].Maprange != 995 { t.Error(fmt.Errorf("bad range: %v", orig.Idmap[0])) return } if orig.Idmap[1].Hostid != 500 || orig.Idmap[1].Nsid != 995 || orig.Idmap[1].Maprange != 10 { t.Error(fmt.Errorf("bad range: %v", orig.Idmap[1])) return } if len(orig.Idmap) != 2 { t.Error("too many idmap entries") return } } func TestIdmapSetIntersects(t *testing.T) { orig := IdmapSet{Idmap: []IdmapEntry{{Isuid: true, Hostid: 165536, Nsid: 0, Maprange: 65536}}} if !orig.Intersects(IdmapEntry{Isuid: true, Hostid: 231071, Nsid: 0, Maprange: 65536}) { t.Error("ranges don't intersect") return } if !orig.Intersects(IdmapEntry{Isuid: true, Hostid: 231072, Nsid: 0, Maprange: 65536}) { t.Error("ranges don't intersect") return } if !orig.Intersects(IdmapEntry{Isuid: true, Hostid: 231072, Nsid: 65535, Maprange: 65536}) { t.Error("ranges don't intersect") return } if orig.Intersects(IdmapEntry{Isuid: true, Hostid: 231072, Nsid: 65536, Maprange: 65536}) { t.Error("ranges intersect") return } } �������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/idmap/idmapset_linux.go�����������������������������������������������������������0000644�0610621�0607500�00000043063�13172163242�021413� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package idmap import ( "bufio" "fmt" "os" "os/exec" "path" "path/filepath" "reflect" "sort" "strconv" "strings" "github.com/lxc/lxd/shared" ) type IdRange struct { Isuid bool Isgid bool Startid int64 Endid int64 } func (i *IdRange) Contains(id int64) bool { return id >= i.Startid && id <= i.Endid } /* * One entry in id mapping set - a single range of either * uid or gid mappings. */ type IdmapEntry struct { Isuid bool Isgid bool Hostid int64 // id as seen on the host - i.e. 100000 Nsid int64 // id as seen in the ns - i.e. 0 Maprange int64 } func (e *IdmapEntry) ToLxcString() []string { if e.Isuid && e.Isgid { return []string{ fmt.Sprintf("u %d %d %d", e.Nsid, e.Hostid, e.Maprange), fmt.Sprintf("g %d %d %d", e.Nsid, e.Hostid, e.Maprange), } } if e.Isuid { return []string{fmt.Sprintf("u %d %d %d", e.Nsid, e.Hostid, e.Maprange)} } return []string{fmt.Sprintf("g %d %d %d", e.Nsid, e.Hostid, e.Maprange)} } func is_between(x, low, high int64) bool { return x >= low && x < high } func (e *IdmapEntry) HostidsIntersect(i IdmapEntry) bool { if (e.Isuid && i.Isuid) || (e.Isgid && i.Isgid) { switch { case is_between(e.Hostid, i.Hostid, i.Hostid+i.Maprange): return true case is_between(i.Hostid, e.Hostid, e.Hostid+e.Maprange): return true case is_between(e.Hostid+e.Maprange, i.Hostid, i.Hostid+i.Maprange): return true case is_between(i.Hostid+i.Maprange, e.Hostid, e.Hostid+e.Maprange): return true } } return false } func (e *IdmapEntry) Intersects(i IdmapEntry) bool { if (e.Isuid && i.Isuid) || (e.Isgid && i.Isgid) { switch { case is_between(e.Hostid, i.Hostid, i.Hostid+i.Maprange-1): return true case is_between(i.Hostid, e.Hostid, e.Hostid+e.Maprange-1): return true case is_between(e.Hostid+e.Maprange-1, i.Hostid, i.Hostid+i.Maprange-1): return true case is_between(i.Hostid+i.Maprange-1, e.Hostid, e.Hostid+e.Maprange-1): return true case is_between(e.Nsid, i.Nsid, i.Nsid+i.Maprange-1): return true case is_between(i.Nsid, e.Nsid, e.Nsid+e.Maprange-1): return true case is_between(e.Nsid+e.Maprange-1, i.Nsid, i.Nsid+i.Maprange-1): return true case is_between(i.Nsid+i.Maprange-1, e.Nsid, e.Nsid+e.Maprange-1): return true } } return false } func (e *IdmapEntry) Usable() error { kernelIdmap, err := CurrentIdmapSet() if err != nil { return err } kernelRanges, err := kernelIdmap.ValidRanges() if err != nil { return err } // Validate the uid map if e.Isuid { valid := false for _, kernelRange := range kernelRanges { if !kernelRange.Isuid { continue } if kernelRange.Contains(e.Hostid) && kernelRange.Contains(e.Hostid+e.Maprange-1) { valid = true break } } if !valid { return fmt.Errorf("The '%s' map can't work in the current user namespace.", e.ToLxcString()) } } // Validate the gid map if e.Isgid { valid := false for _, kernelRange := range kernelRanges { if !kernelRange.Isgid { continue } if kernelRange.Contains(e.Hostid) && kernelRange.Contains(e.Hostid+e.Maprange-1) { valid = true break } } if !valid { return fmt.Errorf("The '%s' map can't work in the current user namespace.", e.ToLxcString()) } } return nil } func (e *IdmapEntry) parse(s string) error { split := strings.Split(s, ":") var err error if len(split) != 4 { return fmt.Errorf("Bad idmap: %q", s) } switch split[0] { case "u": e.Isuid = true case "g": e.Isgid = true case "b": e.Isuid = true e.Isgid = true default: return fmt.Errorf("Bad idmap type in %q", s) } nsid, err := strconv.ParseUint(split[1], 10, 32) if err != nil { return err } e.Nsid = int64(nsid) hostid, err := strconv.ParseUint(split[2], 10, 32) if err != nil { return err } e.Hostid = int64(hostid) maprange, err := strconv.ParseUint(split[3], 10, 32) if err != nil { return err } e.Maprange = int64(maprange) // wraparound if e.Hostid+e.Maprange < e.Hostid || e.Nsid+e.Maprange < e.Nsid { return fmt.Errorf("Bad mapping: id wraparound") } return nil } /* * Shift a uid from the host into the container * I.e. 0 -> 1000 -> 101000 */ func (e *IdmapEntry) shift_into_ns(id int64) (int64, error) { if id < e.Nsid || id >= e.Nsid+e.Maprange { // this mapping doesn't apply return 0, fmt.Errorf("ID mapping doesn't apply.") } return id - e.Nsid + e.Hostid, nil } /* * Shift a uid from the container back to the host * I.e. 101000 -> 1000 */ func (e *IdmapEntry) shift_from_ns(id int64) (int64, error) { if id < e.Hostid || id >= e.Hostid+e.Maprange { // this mapping doesn't apply return 0, fmt.Errorf("ID mapping doesn't apply.") } return id - e.Hostid + e.Nsid, nil } type ByHostid []*IdmapEntry func (s ByHostid) Len() int { return len(s) } func (s ByHostid) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s ByHostid) Less(i, j int) bool { return s[i].Hostid < s[j].Hostid } /* taken from http://blog.golang.org/slices (which is under BSD licence) */ func Extend(slice []IdmapEntry, element IdmapEntry) []IdmapEntry { n := len(slice) if n == cap(slice) { // Slice is full; must grow. // We double its size and add 1, so if the size is zero we still grow. newSlice := make([]IdmapEntry, len(slice), 2*len(slice)+1) copy(newSlice, slice) slice = newSlice } slice = slice[0 : n+1] slice[n] = element return slice } type IdmapSet struct { Idmap []IdmapEntry } func (m IdmapSet) Len() int { return len(m.Idmap) } func (m IdmapSet) Swap(i, j int) { m.Idmap[i], m.Idmap[j] = m.Idmap[j], m.Idmap[i] } func (m IdmapSet) Less(i, j int) bool { if m.Idmap[i].Isuid != m.Idmap[j].Isuid { return m.Idmap[i].Isuid == true } if m.Idmap[i].Isgid != m.Idmap[j].Isgid { return m.Idmap[i].Isgid == true } return m.Idmap[i].Nsid < m.Idmap[j].Nsid } func (m IdmapSet) Intersects(i IdmapEntry) bool { for _, e := range m.Idmap { if i.Intersects(e) { return true } } return false } func (m IdmapSet) HostidsIntersect(i IdmapEntry) bool { for _, e := range m.Idmap { if i.HostidsIntersect(e) { return true } } return false } func (m IdmapSet) Usable() error { for _, e := range m.Idmap { err := e.Usable() if err != nil { return err } } return nil } func (m IdmapSet) ValidRanges() ([]*IdRange, error) { ranges := []*IdRange{} // Sort the map idmap := IdmapSet{} err := shared.DeepCopy(&m, &idmap) if err != nil { return nil, err } sort.Sort(idmap) for _, mapEntry := range idmap.Idmap { var entry *IdRange for _, idEntry := range ranges { if mapEntry.Isuid != idEntry.Isuid || mapEntry.Isgid != idEntry.Isgid { continue } if idEntry.Endid+1 == mapEntry.Nsid { entry = idEntry break } } if entry != nil { entry.Endid = entry.Endid + mapEntry.Maprange continue } ranges = append(ranges, &IdRange{ Isuid: mapEntry.Isuid, Isgid: mapEntry.Isgid, Startid: mapEntry.Nsid, Endid: mapEntry.Nsid + mapEntry.Maprange - 1, }) } return ranges, nil } var ErrHostIdIsSubId = fmt.Errorf("Host id is in the range of subids") /* AddSafe adds an entry to the idmap set, breaking apart any ranges that the * new idmap intersects with in the process. */ func (m *IdmapSet) AddSafe(i IdmapEntry) error { result := []IdmapEntry{} added := false for _, e := range m.Idmap { if !e.Intersects(i) { result = append(result, e) continue } if e.HostidsIntersect(i) { return ErrHostIdIsSubId } added = true lower := IdmapEntry{ Isuid: e.Isuid, Isgid: e.Isgid, Hostid: e.Hostid, Nsid: e.Nsid, Maprange: i.Nsid - e.Nsid, } upper := IdmapEntry{ Isuid: e.Isuid, Isgid: e.Isgid, Hostid: e.Hostid + lower.Maprange + i.Maprange, Nsid: i.Nsid + i.Maprange, Maprange: e.Maprange - i.Maprange - lower.Maprange, } if lower.Maprange > 0 { result = append(result, lower) } result = append(result, i) if upper.Maprange > 0 { result = append(result, upper) } } if !added { result = append(result, i) } m.Idmap = result return nil } func (m IdmapSet) ToLxcString() []string { var lines []string for _, e := range m.Idmap { for _, l := range e.ToLxcString() { if !shared.StringInSlice(l+"\n", lines) { lines = append(lines, l+"\n") } } } return lines } func (m IdmapSet) Append(s string) (IdmapSet, error) { e := IdmapEntry{} err := e.parse(s) if err != nil { return m, err } if m.Intersects(e) { return m, fmt.Errorf("Conflicting id mapping") } m.Idmap = Extend(m.Idmap, e) return m, nil } func (m IdmapSet) doShiftIntoNs(uid int64, gid int64, how string) (int64, int64) { u := int64(-1) g := int64(-1) for _, e := range m.Idmap { var err error var tmpu, tmpg int64 if e.Isuid && u == -1 { switch how { case "in": tmpu, err = e.shift_into_ns(uid) case "out": tmpu, err = e.shift_from_ns(uid) } if err == nil { u = tmpu } } if e.Isgid && g == -1 { switch how { case "in": tmpg, err = e.shift_into_ns(gid) case "out": tmpg, err = e.shift_from_ns(gid) } if err == nil { g = tmpg } } } return u, g } func (m IdmapSet) ShiftIntoNs(uid int64, gid int64) (int64, int64) { return m.doShiftIntoNs(uid, gid, "in") } func (m IdmapSet) ShiftFromNs(uid int64, gid int64) (int64, int64) { return m.doShiftIntoNs(uid, gid, "out") } func (set *IdmapSet) doUidshiftIntoContainer(dir string, testmode bool, how string) error { // Expand any symlink before the final path component tmp := filepath.Dir(dir) tmp, err := filepath.EvalSymlinks(tmp) if err != nil { return err } dir = filepath.Join(tmp, filepath.Base(dir)) dir = strings.TrimRight(dir, "/") convert := func(path string, fi os.FileInfo, err error) (e error) { if err != nil { return err } intUid, intGid, _, _, _, _, err := shared.GetFileStat(path) if err != nil { return err } uid := int64(intUid) gid := int64(intGid) var newuid, newgid int64 switch how { case "in": newuid, newgid = set.ShiftIntoNs(uid, gid) case "out": newuid, newgid = set.ShiftFromNs(uid, gid) } if testmode { fmt.Printf("I would shift %q to %d %d\n", path, newuid, newgid) } else { err = ShiftOwner(dir, path, int(newuid), int(newgid)) if err != nil { return err } err = ShiftACL( path, func(uid int64, gid int64) (int64, int64) { return set.doShiftIntoNs(uid, gid, how) }) if err != nil { return err } } return nil } if !shared.PathExists(dir) { return fmt.Errorf("No such file or directory: %q", dir) } return filepath.Walk(dir, convert) } func (set *IdmapSet) UidshiftIntoContainer(dir string, testmode bool) error { return set.doUidshiftIntoContainer(dir, testmode, "in") } func (set *IdmapSet) UidshiftFromContainer(dir string, testmode bool) error { return set.doUidshiftIntoContainer(dir, testmode, "out") } func (set *IdmapSet) ShiftRootfs(p string) error { return set.doUidshiftIntoContainer(p, false, "in") } func (set *IdmapSet) UnshiftRootfs(p string) error { return set.doUidshiftIntoContainer(p, false, "out") } func (set *IdmapSet) ShiftFile(p string) error { return set.ShiftRootfs(p) } /* * get a uid or gid mapping from /etc/subxid */ func getFromShadow(fname string, username string) ([][]int64, error) { entries := [][]int64{} f, err := os.Open(fname) if err != nil { return nil, err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { // Skip comments s := strings.Split(scanner.Text(), "#") if len(s[0]) == 0 { continue } // Validate format s = strings.Split(s[0], ":") if len(s) < 3 { return nil, fmt.Errorf("Unexpected values in %q: %q", fname, s) } if strings.EqualFold(s[0], username) { // Get range start entryStart, err := strconv.ParseUint(s[1], 10, 32) if err != nil { continue } // Get range size entrySize, err := strconv.ParseUint(s[2], 10, 32) if err != nil { continue } entries = append(entries, []int64{int64(entryStart), int64(entrySize)}) } } if len(entries) == 0 { return nil, fmt.Errorf("User %q has no %ss.", username, path.Base(fname)) } return entries, nil } /* * get a uid or gid mapping from /proc/self/{g,u}id_map */ func getFromProc(fname string) ([][]int64, error) { entries := [][]int64{} f, err := os.Open(fname) if err != nil { return nil, err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { // Skip comments s := strings.Split(scanner.Text(), "#") if len(s[0]) == 0 { continue } // Validate format s = strings.Fields(s[0]) if len(s) < 3 { return nil, fmt.Errorf("Unexpected values in %q: %q", fname, s) } // Get range start entryStart, err := strconv.ParseUint(s[0], 10, 32) if err != nil { continue } // Get range size entryHost, err := strconv.ParseUint(s[1], 10, 32) if err != nil { continue } // Get range size entrySize, err := strconv.ParseUint(s[2], 10, 32) if err != nil { continue } entries = append(entries, []int64{int64(entryStart), int64(entryHost), int64(entrySize)}) } if len(entries) == 0 { return nil, fmt.Errorf("Namespace doesn't have any map set") } return entries, nil } /* * Create a new default idmap */ func DefaultIdmapSet() (*IdmapSet, error) { idmapset := new(IdmapSet) // Check if shadow's uidmap tools are installed newuidmap, _ := exec.LookPath("newuidmap") newgidmap, _ := exec.LookPath("newgidmap") if newuidmap != "" && newgidmap != "" && shared.PathExists("/etc/subuid") && shared.PathExists("/etc/subgid") { // Parse the shadow uidmap entries, err := getFromShadow("/etc/subuid", "root") if err != nil { return nil, err } for _, entry := range entries { // Check that it's big enough to be useful if int(entry[1]) < 65536 { continue } e := IdmapEntry{Isuid: true, Nsid: 0, Hostid: entry[0], Maprange: entry[1]} idmapset.Idmap = Extend(idmapset.Idmap, e) // NOTE: Remove once LXD can deal with multiple shadow maps break } // Parse the shadow gidmap entries, err = getFromShadow("/etc/subgid", "root") if err != nil { return nil, err } for _, entry := range entries { // Check that it's big enough to be useful if int(entry[1]) < 65536 { continue } e := IdmapEntry{Isgid: true, Nsid: 0, Hostid: entry[0], Maprange: entry[1]} idmapset.Idmap = Extend(idmapset.Idmap, e) // NOTE: Remove once LXD can deal with multiple shadow maps break } return idmapset, nil } // No shadow available, figure out a default map kernelMap, err := CurrentIdmapSet() if err != nil { // Hardcoded fallback map e := IdmapEntry{Isuid: true, Isgid: true, Nsid: 0, Hostid: 1000000, Maprange: 1000000000} idmapset.Idmap = Extend(idmapset.Idmap, e) return idmapset, nil } // Look for mapped ranges kernelRanges, err := kernelMap.ValidRanges() if err != nil { return nil, err } // Special case for when we have the full kernel range fullKernelRanges := []*IdRange{ {true, false, int64(0), int64(4294967294)}, {false, true, int64(0), int64(4294967294)}} if reflect.DeepEqual(kernelRanges, fullKernelRanges) { // Hardcoded fallback map e := IdmapEntry{Isuid: true, Isgid: true, Nsid: 0, Hostid: 1000000, Maprange: 1000000000} idmapset.Idmap = Extend(idmapset.Idmap, e) return idmapset, nil } // Find a suitable uid range for _, entry := range kernelRanges { // We only care about uids right now if !entry.Isuid { continue } // We want a map that's separate from the system's own POSIX allocation if entry.Endid < 100000 { continue } // Don't use the first 65536 ids if entry.Startid < 100000 { entry.Startid = 100000 } // Check if we have enough ids if entry.Endid-entry.Startid < 65536 { continue } // Add the map e := IdmapEntry{Isuid: true, Isgid: false, Nsid: 0, Hostid: entry.Startid, Maprange: entry.Endid - entry.Startid + 1} idmapset.Idmap = Extend(idmapset.Idmap, e) // NOTE: Remove once LXD can deal with multiple shadow maps break } // Find a suitable gid range for _, entry := range kernelRanges { // We only care about gids right now if !entry.Isgid { continue } // We want a map that's separate from the system's own POSIX allocation if entry.Endid < 100000 { continue } // Don't use the first 65536 ids if entry.Startid < 100000 { entry.Startid = 100000 } // Check if we have enough ids if entry.Endid-entry.Startid < 65536 { continue } // Add the map e := IdmapEntry{Isuid: false, Isgid: true, Nsid: 0, Hostid: entry.Startid, Maprange: entry.Endid - entry.Startid + 1} idmapset.Idmap = Extend(idmapset.Idmap, e) // NOTE: Remove once LXD can deal with multiple shadow maps break } return idmapset, nil } /* * Create an idmap of the current allocation */ func CurrentIdmapSet() (*IdmapSet, error) { idmapset := new(IdmapSet) if shared.PathExists("/proc/self/uid_map") { // Parse the uidmap entries, err := getFromProc("/proc/self/uid_map") if err != nil { return nil, err } for _, entry := range entries { e := IdmapEntry{Isuid: true, Nsid: entry[0], Hostid: entry[1], Maprange: entry[2]} idmapset.Idmap = Extend(idmapset.Idmap, e) } } else { // Fallback map e := IdmapEntry{Isuid: true, Nsid: 0, Hostid: 0, Maprange: 0} idmapset.Idmap = Extend(idmapset.Idmap, e) } if shared.PathExists("/proc/self/gid_map") { // Parse the gidmap entries, err := getFromProc("/proc/self/gid_map") if err != nil { return nil, err } for _, entry := range entries { e := IdmapEntry{Isgid: true, Nsid: entry[0], Hostid: entry[1], Maprange: entry[2]} idmapset.Idmap = Extend(idmapset.Idmap, e) } } else { // Fallback map e := IdmapEntry{Isgid: true, Nsid: 0, Hostid: 0, Maprange: 0} idmapset.Idmap = Extend(idmapset.Idmap, e) } return idmapset, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/idmap/empty.go��������������������������������������������������������������������0000644�0610621�0607500�00000000131�13172163242�017511� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package idmap // Empty file so that builds on !linux don't complain about empty package ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/i18n/�����������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015516� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/i18n/i18n_linux.go����������������������������������������������������������������0000644�0610621�0607500�00000000352�13172163242�020043� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build linux package i18n import ( "github.com/gosexy/gettext" ) // G returns the translated string func G(msgid string) string { return gettext.DGettext("lxd", msgid) } func init() { gettext.SetLocale(gettext.LC_ALL, "") } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/i18n/i18n.go����������������������������������������������������������������������0000644�0610621�0607500�00000000161�13172163242�016622� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !linux package i18n // G returns the translated string func G(msgid string) string { return msgid } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/gnuflag/��������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016362� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/gnuflag/flag_test.go��������������������������������������������������������������0000644�0610621�0607500�00000027214�13172163242�020667� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gnuflag_test import ( "bytes" "fmt" "os" "reflect" "sort" "strings" "testing" "time" . "github.com/lxc/lxd/shared/gnuflag" ) var ( test_bool = Bool("test_bool", false, "bool value") test_int = Int("test_int", 0, "int value") test_int64 = Int64("test_int64", 0, "int64 value") test_uint = Uint("test_uint", 0, "uint value") test_uint64 = Uint64("test_uint64", 0, "uint64 value") test_string = String("test_string", "0", "string value") test_float64 = Float64("test_float64", 0, "float64 value") test_duration = Duration("test_duration", 0, "time.Duration value") ) func boolString(s string) string { if s == "0" { return "false" } return "true" } func TestEverything(t *testing.T) { m := make(map[string]*Flag) desired := "0" visitor := func(f *Flag) { if len(f.Name) > 5 && f.Name[0:5] == "test_" { m[f.Name] = f ok := false switch { case f.Value.String() == desired: ok = true case f.Name == "test_bool" && f.Value.String() == boolString(desired): ok = true case f.Name == "test_duration" && f.Value.String() == desired+"s": ok = true } if !ok { t.Error("Visit: bad value", f.Value.String(), "for", f.Name) } } } VisitAll(visitor) if len(m) != 8 { t.Error("VisitAll misses some flags") for k, v := range m { t.Log(k, *v) } } m = make(map[string]*Flag) Visit(visitor) if len(m) != 0 { t.Errorf("Visit sees unset flags") for k, v := range m { t.Log(k, *v) } } // Now set all flags Set("test_bool", "true") Set("test_int", "1") Set("test_int64", "1") Set("test_uint", "1") Set("test_uint64", "1") Set("test_string", "1") Set("test_float64", "1") Set("test_duration", "1s") desired = "1" Visit(visitor) if len(m) != 8 { t.Error("Visit fails after set") for k, v := range m { t.Log(k, *v) } } // Now test they're visited in sort order. var flagNames []string Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) }) if !sort.StringsAreSorted(flagNames) { t.Errorf("flag names not sorted: %v", flagNames) } } func TestUsage(t *testing.T) { called := false ResetForTesting(func() { called = true }) f := CommandLine() f.SetOutput(nullWriter{}) if f.Parse(true, []string{"-x"}) == nil { t.Error("parse did not fail for unknown flag") } if called { t.Error("called Usage for unknown flag") } } var parseTests = []struct { about string intersperse bool args []string vals map[string]interface{} remaining []string error string }{{ about: "regular args", intersperse: true, args: []string{ "--bool2", "--int", "22", "--int64", "0x23", "--uint", "24", "--uint64", "25", "--string", "hello", "--float64", "2718e28", "--duration", "2m", "one - extra - argument", }, vals: map[string]interface{}{ "bool": false, "bool2": true, "int": 22, "int64": int64(0x23), "uint": uint(24), "uint64": uint64(25), "string": "hello", "float64": 2718e28, "duration": 2 * 60 * time.Second, }, remaining: []string{ "one - extra - argument", }, }, { about: "playing with -", intersperse: true, args: []string{ "-a", "-", "-bc", "2", "-de1s", "-f2s", "-g", "3s", "--h", "--long", "--long2", "-4s", "3", "4", "--", "-5", }, vals: map[string]interface{}{ "a": true, "b": true, "c": true, "d": true, "e": "1s", "f": "2s", "g": "3s", "h": true, "long": true, "long2": "-4s", "z": "default", "www": 99, }, remaining: []string{ "-", "2", "3", "4", "-5", }, }, { about: "flag after explicit --", intersperse: true, args: []string{ "-a", "--", "-b", }, vals: map[string]interface{}{ "a": true, "b": false, }, remaining: []string{ "-b", }, }, { about: "flag after end", args: []string{ "-a", "foo", "-b", }, vals: map[string]interface{}{ "a": true, "b": false, }, remaining: []string{ "foo", "-b", }, }, { about: "arg and flag after explicit end", args: []string{ "-a", "--", "foo", "-b", }, vals: map[string]interface{}{ "a": true, "b": false, }, remaining: []string{ "foo", "-b", }, }, { about: "boolean args, explicitly and non-explicitly given", args: []string{ "--a=false", "--b=true", "--c", }, vals: map[string]interface{}{ "a": false, "b": true, "c": true, }, }, { about: "using =", args: []string{ "--arble=bar", "--bletch=", "--a=something", "-b=other", "-cdand more", "--curdle=--milk", "--sandwich", "=", "--darn=", "=arg", }, vals: map[string]interface{}{ "arble": "bar", "bletch": "", "a": "something", "b": "=other", "c": true, "d": "and more", "curdle": "--milk", "sandwich": "=", "darn": "", }, remaining: []string{"=arg"}, }, { about: "empty flag #1", args: []string{ "--=bar", }, error: `empty flag in argument "--=bar"`, }, { about: "single-letter equals", args: []string{ "-=bar", }, error: `flag provided but not defined: -=`, }, { about: "empty flag #2", args: []string{ "--=", }, error: `empty flag in argument "--="`, }, { about: "no equals", args: []string{ "-=", }, error: `flag provided but not defined: -=`, }, { args: []string{ "-a=true", }, vals: map[string]interface{}{ "a": true, }, error: `invalid value "=true" for flag -a: strconv.ParseBool: parsing "=true": invalid syntax`, }, { intersperse: true, args: []string{ "-a", "-b", }, vals: map[string]interface{}{ "a": true, }, error: "flag provided but not defined: -b", }, { intersperse: true, args: []string{ "-a", }, vals: map[string]interface{}{ "a": "default", }, error: "flag needs an argument: -a", }, { intersperse: true, args: []string{ "-a", "b", }, vals: map[string]interface{}{ "a": 0, }, error: `invalid value "b" for flag -a: strconv.ParseInt: parsing "b": invalid syntax`, }, } func testParse(newFlagSet func() *FlagSet, t *testing.T) { for i, g := range parseTests { t.Logf("test %d. %s", i, g.about) f := newFlagSet() flags := make(map[string]interface{}) for name, val := range g.vals { switch val.(type) { case bool: flags[name] = f.Bool(name, false, "bool value "+name) case string: flags[name] = f.String(name, "default", "string value "+name) case int: flags[name] = f.Int(name, 99, "int value "+name) case uint: flags[name] = f.Uint(name, 0, "uint value") case uint64: flags[name] = f.Uint64(name, 0, "uint64 value") case int64: flags[name] = f.Int64(name, 0, "uint64 value") case float64: flags[name] = f.Float64(name, 0, "float64 value") case time.Duration: flags[name] = f.Duration(name, 5*time.Second, "duration value") default: t.Fatalf("unhandled type %T", val) } } err := f.Parse(g.intersperse, g.args) if g.error != "" { if err == nil { t.Errorf("expected error %q got nil", g.error) } else if err.Error() != g.error { t.Errorf("expected error %q got %q", g.error, err.Error()) } continue } for name, val := range g.vals { actual := reflect.ValueOf(flags[name]).Elem().Interface() if val != actual { t.Errorf("flag %q, expected %v got %v", name, val, actual) } } if len(f.Args()) != len(g.remaining) { t.Fatalf("remaining args, expected %q got %q", g.remaining, f.Args()) } for j, a := range f.Args() { if a != g.remaining[j] { t.Errorf("arg %d, expected %q got %q", j, g.remaining[i], a) } } } } func TestParse(t *testing.T) { testParse(func() *FlagSet { ResetForTesting(func() {}) f := CommandLine() f.SetOutput(nullWriter{}) return f }, t) } func TestFlagSetParse(t *testing.T) { testParse(func() *FlagSet { f := NewFlagSet("test", ContinueOnError) f.SetOutput(nullWriter{}) return f }, t) } // Declare a user-defined flag type. type flagVar []string func (f *flagVar) String() string { return fmt.Sprint([]string(*f)) } func (f *flagVar) Set(value string) error { *f = append(*f, value) return nil } func TestUserDefined(t *testing.T) { var flags FlagSet flags.Init("test", ContinueOnError) var v flagVar flags.Var(&v, "v", "usage") if err := flags.Parse(true, []string{"-v", "1", "-v", "2", "-v3"}); err != nil { t.Error(err) } if len(v) != 3 { t.Fatal("expected 3 args; got ", len(v)) } expect := "[1 2 3]" if v.String() != expect { t.Errorf("expected value %q got %q", expect, v.String()) } } func TestSetOutput(t *testing.T) { var flags FlagSet var buf bytes.Buffer flags.SetOutput(&buf) flags.Init("test", ContinueOnError) flags.Parse(true, []string{"-unknown"}) if out := buf.String(); !strings.Contains(out, "-unknown") { t.Logf("expected output mentioning unknown; got %q", out) } } // This tests that one can reset the flags. This still works but not well, and is // superseded by FlagSet. func TestChangingArgs(t *testing.T) { ResetForTesting(func() { t.Fatal("bad parse") }) oldArgs := os.Args defer func() { os.Args = oldArgs }() os.Args = []string{"cmd", "--before", "subcmd", "--after", "args"} before := Bool("before", false, "") if err := CommandLine().Parse(false, os.Args[1:]); err != nil { t.Fatal(err) } cmd := Arg(0) os.Args = Args() after := Bool("after", false, "") Parse(false) args := Args() if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) } } // Test that -help invokes the usage message and returns ErrHelp. func TestHelp(t *testing.T) { var helpCalled = false fs := NewFlagSet("help test", ContinueOnError) fs.SetOutput(nullWriter{}) fs.Usage = func() { helpCalled = true } var flag bool fs.BoolVar(&flag, "flag", false, "regular flag") // Regular flag invocation should work err := fs.Parse(true, []string{"--flag"}) if err != nil { t.Fatal("expected no error; got ", err) } if !flag { t.Error("flag was not set by --flag") } if helpCalled { t.Error("help called for regular flag") helpCalled = false // reset for next test } // Help flag should work as expected. err = fs.Parse(true, []string{"--help"}) if err == nil { t.Fatal("error expected") } if err != ErrHelp { t.Fatal("expected ErrHelp; got ", err) } if !helpCalled { t.Fatal("help was not called") } // If we define a help flag, that should override. var help bool fs.BoolVar(&help, "help", false, "help flag") helpCalled = false err = fs.Parse(true, []string{"--help"}) if err != nil { t.Fatal("expected no error for defined --help; got ", err) } if helpCalled { t.Fatal("help was called; should not have been for defined help flag") } } type nullWriter struct{} func (nullWriter) Write(buf []byte) (int, error) { return len(buf), nil } func TestPrintDefaults(t *testing.T) { f := NewFlagSet("print test", ContinueOnError) f.SetOutput(nullWriter{}) var b bool var c int var d string var e float64 f.IntVar(&c, "trapclap", 99, "usage not shown") f.IntVar(&c, "c", 99, "c usage") f.BoolVar(&b, "bal", false, "usage not shown") f.BoolVar(&b, "x", false, "usage not shown") f.BoolVar(&b, "b", false, "b usage") f.BoolVar(&b, "balalaika", false, "usage not shown") f.StringVar(&d, "d", "d default", "d usage") f.Float64Var(&e, "elephant", 3.14, "elephant usage") var buf bytes.Buffer f.SetOutput(&buf) f.PrintDefaults() f.SetOutput(nullWriter{}) expect := ` -b, -x, --bal, --balalaika (= false) b usage -c, --trapclap (= 99) c usage -d (= "d default") d usage --elephant (= 3.14) elephant usage ` if buf.String() != expect { t.Errorf("expect %q got %q", expect, buf.String()) } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/gnuflag/flag.go�������������������������������������������������������������������0000644�0610621�0607500�00000067264�13172163242�017641� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package gnuflag implements command-line flag parsing in the GNU style. It is almost exactly the same as the standard flag package, the only difference being the extra argument to Parse. Command line flag syntax: -f // single letter flag -fg // two single letter flags together --flag // multiple letter flag --flag x // non-boolean flags only -f x // non-boolean flags only -fx // if f is a non-boolean flag, x is its argument. The last three forms are not permitted for boolean flags because the meaning of the command cmd -f * will change if there is a file called 0, false, etc. There is currently no way to turn off a boolean flag. Flag parsing stops after the terminator "--", or just before the first non-flag argument ("-" is a non-flag argument) if the interspersed argument to Parse is false. */ package gnuflag import ( "bytes" "errors" "fmt" "io" "os" "sort" "strconv" "strings" "time" "unicode/utf8" ) // ErrHelp is the error returned if the flag -help is invoked but no such flag is defined. var ErrHelp = errors.New("flag: help requested") // -- bool Value type boolValue bool func newBoolValue(val bool, p *bool) *boolValue { *p = val return (*boolValue)(p) } func (b *boolValue) Set(s string) error { v, err := strconv.ParseBool(s) *b = boolValue(v) return err } func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) } // -- int Value type intValue int func newIntValue(val int, p *int) *intValue { *p = val return (*intValue)(p) } func (i *intValue) Set(s string) error { v, err := strconv.ParseInt(s, 0, 64) *i = intValue(v) return err } func (i *intValue) String() string { return fmt.Sprintf("%v", *i) } // -- int64 Value type int64Value int64 func newInt64Value(val int64, p *int64) *int64Value { *p = val return (*int64Value)(p) } func (i *int64Value) Set(s string) error { v, err := strconv.ParseInt(s, 0, 64) *i = int64Value(v) return err } func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) } // -- uint Value type uintValue uint func newUintValue(val uint, p *uint) *uintValue { *p = val return (*uintValue)(p) } func (i *uintValue) Set(s string) error { v, err := strconv.ParseUint(s, 0, 64) *i = uintValue(v) return err } func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) } // -- uint64 Value type uint64Value uint64 func newUint64Value(val uint64, p *uint64) *uint64Value { *p = val return (*uint64Value)(p) } func (i *uint64Value) Set(s string) error { v, err := strconv.ParseUint(s, 0, 64) *i = uint64Value(v) return err } func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) } // -- string Value type stringValue string func newStringValue(val string, p *string) *stringValue { *p = val return (*stringValue)(p) } func (s *stringValue) Set(val string) error { *s = stringValue(val) return nil } func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) } // -- float64 Value type float64Value float64 func newFloat64Value(val float64, p *float64) *float64Value { *p = val return (*float64Value)(p) } func (f *float64Value) Set(s string) error { v, err := strconv.ParseFloat(s, 64) *f = float64Value(v) return err } func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) } // -- time.Duration Value type durationValue time.Duration func newDurationValue(val time.Duration, p *time.Duration) *durationValue { *p = val return (*durationValue)(p) } func (d *durationValue) Set(s string) error { v, err := time.ParseDuration(s) *d = durationValue(v) return err } func (d *durationValue) String() string { return (*time.Duration)(d).String() } // Value is the interface to the dynamic value stored in a flag. // (The default value is represented as a string.) type Value interface { String() string Set(string) error } // ErrorHandling defines how to handle flag parsing errors. type ErrorHandling int const ( // ContinueOnError will cause gnuflag to just return the error ContinueOnError ErrorHandling = iota // ExitOnError will cause gnuflag to exit with return code 2 ExitOnError // PanicOnError will cause gnuflag to to call panic() PanicOnError ) // A FlagSet represents a set of defined flags. type FlagSet struct { // Usage is the function called when an error occurs while parsing flags. // The field is a function (not a method) that may be changed to point to // a custom error handler. Usage func() name string parsed bool actual map[string]*Flag formal map[string]*Flag args []string // arguments after flags procArgs []string // arguments being processed (gnu only) procFlag string // flag being processed (gnu only) allowIntersperse bool // (gnu only) exitOnError bool // does the program exit if there's an error? errorHandling ErrorHandling output io.Writer // nil means stderr; use out() accessor } // A Flag represents the state of a flag. type Flag struct { Name string // name as it appears on command line Usage string // help message Value Value // value as set DefValue string // default value (as text); for usage message } // sortFlags returns the flags as a slice in lexicographical sorted order. func sortFlags(flags map[string]*Flag) []*Flag { list := make(sort.StringSlice, len(flags)) i := 0 for _, f := range flags { list[i] = f.Name i++ } list.Sort() result := make([]*Flag, len(list)) for i, name := range list { result[i] = flags[name] } return result } func (f *FlagSet) out() io.Writer { if f.output == nil { return os.Stderr } return f.output } // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. func (f *FlagSet) SetOutput(output io.Writer) { f.output = output } // VisitAll visits the flags in lexicographical order, calling fn for each. // It visits all flags, even those not set. func (f *FlagSet) VisitAll(fn func(*Flag)) { for _, flag := range sortFlags(f.formal) { fn(flag) } } // VisitAll visits the command-line flags in lexicographical order, calling // fn for each. It visits all flags, even those not set. func VisitAll(fn func(*Flag)) { commandLine.VisitAll(fn) } // Visit visits the flags in lexicographical order, calling fn for each. // It visits only those flags that have been set. func (f *FlagSet) Visit(fn func(*Flag)) { for _, flag := range sortFlags(f.actual) { fn(flag) } } // Visit visits the command-line flags in lexicographical order, calling fn // for each. It visits only those flags that have been set. func Visit(fn func(*Flag)) { commandLine.Visit(fn) } // Lookup returns the Flag structure of the named flag, returning nil if none exists. func (f *FlagSet) Lookup(name string) *Flag { return f.formal[name] } // Lookup returns the Flag structure of the named command-line flag, // returning nil if none exists. func Lookup(name string) *Flag { return commandLine.formal[name] } // Set sets the value of the named flag. func (f *FlagSet) Set(name, value string) error { flag, ok := f.formal[name] if !ok { return fmt.Errorf("no such flag -%v", name) } err := flag.Value.Set(value) if err != nil { return err } if f.actual == nil { f.actual = make(map[string]*Flag) } f.actual[name] = flag return nil } // Set sets the value of the named command-line flag. func Set(name, value string) error { return commandLine.Set(name, value) } // flagsByLength is a slice of flags implementing sort.Interface, // sorting primarily by the length of the flag, and secondarily // alphabetically. type flagsByLength []*Flag func (f flagsByLength) Less(i, j int) bool { s1, s2 := f[i].Name, f[j].Name if len(s1) != len(s2) { return len(s1) < len(s2) } return s1 < s2 } func (f flagsByLength) Swap(i, j int) { f[i], f[j] = f[j], f[i] } func (f flagsByLength) Len() int { return len(f) } // flagsByName is a slice of slices of flags implementing sort.Interface, // alphabetically sorting by the name of the first flag in each slice. type flagsByName [][]*Flag func (f flagsByName) Less(i, j int) bool { return f[i][0].Name < f[j][0].Name } func (f flagsByName) Swap(i, j int) { f[i], f[j] = f[j], f[i] } func (f flagsByName) Len() int { return len(f) } // PrintDefaults prints, to standard error unless configured // otherwise, the default values of all defined flags in the set. // If there is more than one name for a given flag, the usage information and // default value from the shortest will be printed (or the least alphabetically // if there are several equally short flag names). func (f *FlagSet) PrintDefaults() { // group together all flags for a given value flags := make(map[interface{}]flagsByLength) f.VisitAll(func(f *Flag) { flags[f.Value] = append(flags[f.Value], f) }) // sort the output flags by shortest name for each group. var byName flagsByName for _, f := range flags { sort.Sort(f) byName = append(byName, f) } sort.Sort(byName) var line bytes.Buffer for _, fs := range byName { line.Reset() for i, f := range fs { if i > 0 { line.WriteString(", ") } line.WriteString(flagWithMinus(f.Name)) } format := " %s (= %s)\n %s\n" if _, ok := fs[0].Value.(*stringValue); ok { // put quotes on the value format = " %s (= %q)\n %s\n" } fmt.Fprintf(f.out(), format, line.Bytes(), fs[0].DefValue, fs[0].Usage) } } // PrintDefaults prints to standard error the default values of all defined command-line flags. func PrintDefaults() { commandLine.PrintDefaults() } // defaultUsage is the default function to print a usage message. func defaultUsage(f *FlagSet) { fmt.Fprintf(f.out(), "Usage of %s:\n", f.name) f.PrintDefaults() } // NOTE: Usage is not just defaultUsage(commandLine) // because it serves (via godoc flag Usage) as the example // for how to write your own usage function. // Usage prints to standard error a usage message documenting all defined command-line flags. // The function is a variable that may be changed to point to a custom function. var Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) PrintDefaults() } // NFlag returns the number of flags that have been set. func (f *FlagSet) NFlag() int { return len(f.actual) } // NFlag returns the number of command-line flags that have been set. func NFlag() int { return len(commandLine.actual) } // Arg returns the i'th argument. Arg(0) is the first remaining argument // after flags have been processed. func (f *FlagSet) Arg(i int) string { if i < 0 || i >= len(f.args) { return "" } return f.args[i] } // Arg returns the i'th command-line argument. Arg(0) is the first remaining argument // after flags have been processed. func Arg(i int) string { return commandLine.Arg(i) } // NArg is the number of arguments remaining after flags have been processed. func (f *FlagSet) NArg() int { return len(f.args) } // NArg is the number of arguments remaining after flags have been processed. func NArg() int { return len(commandLine.args) } // Args returns the non-flag arguments. func (f *FlagSet) Args() []string { return f.args } // Args returns the non-flag command-line arguments. func Args() []string { return commandLine.args } // BoolVar defines a bool flag with specified name, default value, and usage string. // The argument p points to a bool variable in which to store the value of the flag. func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { f.Var(newBoolValue(value, p), name, usage) } // BoolVar defines a bool flag with specified name, default value, and usage string. // The argument p points to a bool variable in which to store the value of the flag. func BoolVar(p *bool, name string, value bool, usage string) { commandLine.Var(newBoolValue(value, p), name, usage) } // Bool defines a bool flag with specified name, default value, and usage string. // The return value is the address of a bool variable that stores the value of the flag. func (f *FlagSet) Bool(name string, value bool, usage string) *bool { p := new(bool) f.BoolVar(p, name, value, usage) return p } // Bool defines a bool flag with specified name, default value, and usage string. // The return value is the address of a bool variable that stores the value of the flag. func Bool(name string, value bool, usage string) *bool { return commandLine.Bool(name, value, usage) } // IntVar defines an int flag with specified name, default value, and usage string. // The argument p points to an int variable in which to store the value of the flag. func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { f.Var(newIntValue(value, p), name, usage) } // IntVar defines an int flag with specified name, default value, and usage string. // The argument p points to an int variable in which to store the value of the flag. func IntVar(p *int, name string, value int, usage string) { commandLine.Var(newIntValue(value, p), name, usage) } // Int defines an int flag with specified name, default value, and usage string. // The return value is the address of an int variable that stores the value of the flag. func (f *FlagSet) Int(name string, value int, usage string) *int { p := new(int) f.IntVar(p, name, value, usage) return p } // Int defines an int flag with specified name, default value, and usage string. // The return value is the address of an int variable that stores the value of the flag. func Int(name string, value int, usage string) *int { return commandLine.Int(name, value, usage) } // Int64Var defines an int64 flag with specified name, default value, and usage string. // The argument p points to an int64 variable in which to store the value of the flag. func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { f.Var(newInt64Value(value, p), name, usage) } // Int64Var defines an int64 flag with specified name, default value, and usage string. // The argument p points to an int64 variable in which to store the value of the flag. func Int64Var(p *int64, name string, value int64, usage string) { commandLine.Var(newInt64Value(value, p), name, usage) } // Int64 defines an int64 flag with specified name, default value, and usage string. // The return value is the address of an int64 variable that stores the value of the flag. func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { p := new(int64) f.Int64Var(p, name, value, usage) return p } // Int64 defines an int64 flag with specified name, default value, and usage string. // The return value is the address of an int64 variable that stores the value of the flag. func Int64(name string, value int64, usage string) *int64 { return commandLine.Int64(name, value, usage) } // UintVar defines a uint flag with specified name, default value, and usage string. // The argument p points to a uint variable in which to store the value of the flag. func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { f.Var(newUintValue(value, p), name, usage) } // UintVar defines a uint flag with specified name, default value, and usage string. // The argument p points to a uint variable in which to store the value of the flag. func UintVar(p *uint, name string, value uint, usage string) { commandLine.Var(newUintValue(value, p), name, usage) } // Uint defines a uint flag with specified name, default value, and usage string. // The return value is the address of a uint variable that stores the value of the flag. func (f *FlagSet) Uint(name string, value uint, usage string) *uint { p := new(uint) f.UintVar(p, name, value, usage) return p } // Uint defines a uint flag with specified name, default value, and usage string. // The return value is the address of a uint variable that stores the value of the flag. func Uint(name string, value uint, usage string) *uint { return commandLine.Uint(name, value, usage) } // Uint64Var defines a uint64 flag with specified name, default value, and usage string. // The argument p points to a uint64 variable in which to store the value of the flag. func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) { f.Var(newUint64Value(value, p), name, usage) } // Uint64Var defines a uint64 flag with specified name, default value, and usage string. // The argument p points to a uint64 variable in which to store the value of the flag. func Uint64Var(p *uint64, name string, value uint64, usage string) { commandLine.Var(newUint64Value(value, p), name, usage) } // Uint64 defines a uint64 flag with specified name, default value, and usage string. // The return value is the address of a uint64 variable that stores the value of the flag. func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { p := new(uint64) f.Uint64Var(p, name, value, usage) return p } // Uint64 defines a uint64 flag with specified name, default value, and usage string. // The return value is the address of a uint64 variable that stores the value of the flag. func Uint64(name string, value uint64, usage string) *uint64 { return commandLine.Uint64(name, value, usage) } // StringVar defines a string flag with specified name, default value, and usage string. // The argument p points to a string variable in which to store the value of the flag. func (f *FlagSet) StringVar(p *string, name string, value string, usage string) { f.Var(newStringValue(value, p), name, usage) } // StringVar defines a string flag with specified name, default value, and usage string. // The argument p points to a string variable in which to store the value of the flag. func StringVar(p *string, name string, value string, usage string) { commandLine.Var(newStringValue(value, p), name, usage) } // String defines a string flag with specified name, default value, and usage string. // The return value is the address of a string variable that stores the value of the flag. func (f *FlagSet) String(name string, value string, usage string) *string { p := new(string) f.StringVar(p, name, value, usage) return p } // String defines a string flag with specified name, default value, and usage string. // The return value is the address of a string variable that stores the value of the flag. func String(name string, value string, usage string) *string { return commandLine.String(name, value, usage) } // Float64Var defines a float64 flag with specified name, default value, and usage string. // The argument p points to a float64 variable in which to store the value of the flag. func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) { f.Var(newFloat64Value(value, p), name, usage) } // Float64Var defines a float64 flag with specified name, default value, and usage string. // The argument p points to a float64 variable in which to store the value of the flag. func Float64Var(p *float64, name string, value float64, usage string) { commandLine.Var(newFloat64Value(value, p), name, usage) } // Float64 defines a float64 flag with specified name, default value, and usage string. // The return value is the address of a float64 variable that stores the value of the flag. func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { p := new(float64) f.Float64Var(p, name, value, usage) return p } // Float64 defines a float64 flag with specified name, default value, and usage string. // The return value is the address of a float64 variable that stores the value of the flag. func Float64(name string, value float64, usage string) *float64 { return commandLine.Float64(name, value, usage) } // DurationVar defines a time.Duration flag with specified name, default value, and usage string. // The argument p points to a time.Duration variable in which to store the value of the flag. func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) { f.Var(newDurationValue(value, p), name, usage) } // DurationVar defines a time.Duration flag with specified name, default value, and usage string. // The argument p points to a time.Duration variable in which to store the value of the flag. func DurationVar(p *time.Duration, name string, value time.Duration, usage string) { commandLine.Var(newDurationValue(value, p), name, usage) } // Duration defines a time.Duration flag with specified name, default value, and usage string. // The return value is the address of a time.Duration variable that stores the value of the flag. func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration { p := new(time.Duration) f.DurationVar(p, name, value, usage) return p } // Duration defines a time.Duration flag with specified name, default value, and usage string. // The return value is the address of a time.Duration variable that stores the value of the flag. func Duration(name string, value time.Duration, usage string) *time.Duration { return commandLine.Duration(name, value, usage) } // Var defines a flag with the specified name and usage string. The type and // value of the flag are represented by the first argument, of type Value, which // typically holds a user-defined implementation of Value. For instance, the // caller could create a flag that turns a comma-separated string into a slice // of strings by giving the slice the methods of Value; in particular, Set would // decompose the comma-separated string into the slice. func (f *FlagSet) Var(value Value, name string, usage string) { // Remember the default value as a string; it won't change. flag := &Flag{name, usage, value, value.String()} _, alreadythere := f.formal[name] if alreadythere { fmt.Fprintf(f.out(), "%s flag redefined: %s\n", f.name, name) panic("flag redefinition") // Happens only if flags are declared with identical names } if f.formal == nil { f.formal = make(map[string]*Flag) } f.formal[name] = flag } // Var defines a flag with the specified name and usage string. The type and // value of the flag are represented by the first argument, of type Value, which // typically holds a user-defined implementation of Value. For instance, the // caller could create a flag that turns a comma-separated string into a slice // of strings by giving the slice the methods of Value; in particular, Set would // decompose the comma-separated string into the slice. func Var(value Value, name string, usage string) { commandLine.Var(value, name, usage) } // failf prints to standard error a formatted error and usage message and // returns the error. func (f *FlagSet) failf(format string, a ...interface{}) error { err := fmt.Errorf(format, a...) fmt.Fprintf(f.out(), "error: %v\n", err) return err } // usage calls the Usage method for the flag set, or the usage function if // the flag set is commandLine. func (f *FlagSet) usage() { if f == commandLine { Usage() } else if f.Usage == nil { defaultUsage(f) } else { f.Usage() } } func (f *FlagSet) parseOneGnu() (flagName string, long, finished bool, err error) { if len(f.procArgs) == 0 { finished = true return } // processing previously encountered single-rune flag if flag := f.procFlag; len(flag) > 0 { _, n := utf8.DecodeRuneInString(flag) f.procFlag = flag[n:] flagName = flag[0:n] return } a := f.procArgs[0] // one non-flag argument if a == "-" || a == "" || a[0] != '-' { if f.allowIntersperse { f.args = append(f.args, a) f.procArgs = f.procArgs[1:] return } f.args = append(f.args, f.procArgs...) f.procArgs = nil finished = true return } // end of flags if f.procArgs[0] == "--" { f.args = append(f.args, f.procArgs[1:]...) f.procArgs = nil finished = true return } // long flag signified with "--" prefix if a[1] == '-' { long = true i := strings.Index(a, "=") if i < 0 { f.procArgs = f.procArgs[1:] flagName = a[2:] return } flagName = a[2:i] if flagName == "" { err = fmt.Errorf("empty flag in argument %q", a) return } f.procArgs = f.procArgs[1:] f.procFlag = a[i:] return } // some number of single-rune flags a = a[1:] _, n := utf8.DecodeRuneInString(a) flagName = a[0:n] f.procFlag = a[n:] f.procArgs = f.procArgs[1:] return } func flagWithMinus(name string) string { if len(name) > 1 { return "--" + name } return "-" + name } func (f *FlagSet) parseGnuFlagArg(name string, long bool) (finished bool, err error) { m := f.formal flag, alreadythere := m[name] // BUG if !alreadythere { if name == "help" || name == "h" { // special case for nice help message. f.usage() return false, ErrHelp } // TODO print --xxx when flag is more than one rune. return false, f.failf("flag provided but not defined: %s", flagWithMinus(name)) } if fv, ok := flag.Value.(*boolValue); ok && !strings.HasPrefix(f.procFlag, "=") { // special case: doesn't need an arg, and an arg hasn't // been provided explicitly. fv.Set("true") } else { // It must have a value, which might be the next argument. var hasValue bool var value string if f.procFlag != "" { // value directly follows flag value = f.procFlag if long { if value[0] != '=' { panic("no leading '=' in long flag") } value = value[1:] } hasValue = true f.procFlag = "" } if !hasValue && len(f.procArgs) > 0 { // value is the next arg hasValue = true value, f.procArgs = f.procArgs[0], f.procArgs[1:] } if !hasValue { return false, f.failf("flag needs an argument: %s", flagWithMinus(name)) } if err := flag.Value.Set(value); err != nil { return false, f.failf("invalid value %q for flag %s: %v", value, flagWithMinus(name), err) } } if f.actual == nil { f.actual = make(map[string]*Flag) } f.actual[name] = flag return } // Parse parses flag definitions from the argument list, which should not // include the command name. Must be called after all flags in the FlagSet // are defined and before flags are accessed by the program. // The return value will be ErrHelp if --help was set but not defined. // If allowIntersperse is set, arguments and flags can be interspersed, that // is flags can follow positional arguments. func (f *FlagSet) Parse(allowIntersperse bool, arguments []string) error { f.parsed = true f.procArgs = arguments f.procFlag = "" f.args = nil f.allowIntersperse = allowIntersperse for { name, long, finished, err := f.parseOneGnu() if !finished { if name != "" { finished, err = f.parseGnuFlagArg(name, long) } } if err != nil { switch f.errorHandling { case ContinueOnError: return err case ExitOnError: os.Exit(2) case PanicOnError: panic(err) } } if !finished { continue } if err == nil { break } } return nil } // Parsed reports whether f.Parse has been called. func (f *FlagSet) Parsed() bool { return f.parsed } // Parse parses the command-line flags from os.Args[1:]. Must be called // after all flags are defined and before flags are accessed by the program. // If allowIntersperse is set, arguments and flags can be interspersed, that // is flags can follow positional arguments. func Parse(allowIntersperse bool) { // Ignore errors; commandLine is set for ExitOnError. commandLine.Parse(allowIntersperse, os.Args[1:]) } // Parsed returns true if the command-line flags have been parsed. func Parsed() bool { return commandLine.Parsed() } // The default set of command-line flags, parsed from os.Args. var commandLine = NewFlagSet(os.Args[0], ExitOnError) // SetOut sets the output writer for the default FlagSet. func SetOut(w io.Writer) { commandLine.output = w } // NewFlagSet returns a new, empty flag set with the specified name and // error handling property. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { f := &FlagSet{ name: name, errorHandling: errorHandling, } return f } // Init sets the name and error handling property for a flag set. // By default, the zero FlagSet uses an empty name and the // ContinueOnError error handling policy. func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { f.name = name f.errorHandling = errorHandling } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/gnuflag/export_test.go������������������������������������������������������������0000644�0610621�0607500�00000001211�13172163242�021264� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gnuflag import ( "os" ) // Additional routines compiled into the package only during testing. // ResetForTesting clears all flag state and sets the usage function as directed. // After calling ResetForTesting, parse errors in flag handling will not // exit the program. func ResetForTesting(usage func()) { commandLine = NewFlagSet(os.Args[0], ContinueOnError) Usage = usage } // CommandLine returns the default FlagSet. func CommandLine() *FlagSet { return commandLine } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/container.go����������������������������������������������������������������������0000644�0610621�0607500�00000000360�13172163242�017247� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared type ContainerAction string const ( Stop ContainerAction = "stop" Start ContainerAction = "start" Restart ContainerAction = "restart" Freeze ContainerAction = "freeze" Unfreeze ContainerAction = "unfreeze" ) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cmd/������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015502� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cmd/testing.go��������������������������������������������������������������������0000644�0610621�0607500�00000003626�13172163242�017515� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// In-memory streams, useful for testing cmd-related code. package cmd import ( "bytes" "io/ioutil" "strings" ) // MemoryStreams provide an in-memory version of the system // stdin/stdout/stderr streams. type MemoryStreams struct { in *strings.Reader out *bytes.Buffer err *bytes.Buffer } // NewMemoryStreams creates a new set of in-memory streams with the given // user input. func NewMemoryStreams(input string) *MemoryStreams { return &MemoryStreams{ in: strings.NewReader(input), out: new(bytes.Buffer), err: new(bytes.Buffer), } } // InputRead returns the current input string. func (s *MemoryStreams) InputRead() string { bytes, _ := ioutil.ReadAll(s.in) return string(bytes) } // Out returns the current content of the out stream. func (s *MemoryStreams) Out() string { return s.out.String() } // Err returns the current content of the err stream. func (s *MemoryStreams) Err() string { return s.err.String() } // InputReset replaces the data in the input stream. func (s *MemoryStreams) InputReset(input string) { // XXX This is what the stdlib strings.Reader.Reset() does, however // this method is not available in Go 1.6. *s.in = *strings.NewReader(input) } // InputAppend adds the given text to the current input. func (s *MemoryStreams) InputAppend(text string) { s.InputReset(s.InputRead() + text) } // InputAppendLine adds a single line to the input stream. func (s *MemoryStreams) InputAppendLine(line string) { s.InputAppend(line + "\n") } // InputAppendBoolAnswer adds a new "yes" or "no" line depending on the answer. func (s *MemoryStreams) InputAppendBoolAnswer(answer bool) { var line string if answer { line = "yes" } else { line = "no" } s.InputAppendLine(line) } // NewMemoryContext creates a new command Context using the given in-memory // streams. func NewMemoryContext(streams *MemoryStreams) *Context { return NewContext(streams.in, streams.out, streams.err) } ����������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cmd/parser_test.go����������������������������������������������������������������0000644�0610621�0607500�00000010307�13172163242�020365� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package cmd_test import ( "strings" "testing" "github.com/stretchr/testify/assert" "github.com/lxc/lxd/shared/cmd" "github.com/lxc/lxd/shared/subtest" ) // Sample command line arguments specification. type Args struct { Subcommand string Params []string Extra []string Help bool `flag:"help"` Text string `flag:"text"` Number int `flag:"number"` BigNumber int64 `flag:"big-number"` } // Check the default values of all command line args. func TestParser_ArgsDefaults(t *testing.T) { line := []string{"cmd"} args := &Args{} parser := newParser() assert.NoError(t, parser.Parse(line, args)) assert.Equal(t, "", args.Text) assert.Equal(t, false, args.Help) assert.Equal(t, -1, args.Number) assert.Equal(t, int64(-1), args.BigNumber) } // Check that parsing the command line results in the correct attributes // being set. func TestParser_ArgsCustom(t *testing.T) { line := []string{ "cmd", "--text", "hello", "--help", "--number", "10", "--big-number", "666", } args := &Args{} parser := newParser() assert.NoError(t, parser.Parse(line, args)) assert.Equal(t, "hello", args.Text) assert.Equal(t, true, args.Help) assert.Equal(t, 10, args.Number) assert.Equal(t, int64(666), args.BigNumber) } // Check that the subcommand is properly set. func TestParser_Subcommand(t *testing.T) { cases := []struct { line []string subcommand string }{ {[]string{"cmd"}, ""}, {[]string{"cmd", "--help"}, ""}, {[]string{"cmd", "subcmd"}, "subcmd"}, {[]string{"cmd", "subcmd", "--help"}, "subcmd"}, {[]string{"cmd", "--help", "subcmd"}, ""}, } for _, c := range cases { subtest.Run(t, strings.Join(c.line, "_"), func(t *testing.T) { args := &Args{} parser := newParser() assert.NoError(t, parser.Parse(c.line, args)) assert.Equal(t, c.subcommand, args.Subcommand) }) } } // Check that subcommand params are properly set. func TestParser_Params(t *testing.T) { cases := []struct { line []string params []string }{ {[]string{"cmd"}, []string{}}, {[]string{"cmd", "--help"}, []string{}}, {[]string{"cmd", "subcmd"}, []string{}}, {[]string{"cmd", "subcmd", "param"}, []string{"param"}}, {[]string{"cmd", "subcmd", "param1", "param2"}, []string{"param1", "param2"}}, {[]string{"cmd", "subcmd", "param", "--help"}, []string{"param"}}, {[]string{"cmd", "subcmd", "--help", "param"}, []string{}}, } for _, c := range cases { subtest.Run(t, strings.Join(c.line, "_"), func(t *testing.T) { args := &Args{} parser := newParser() assert.NoError(t, parser.Parse(c.line, args)) assert.Equal(t, c.params, args.Params) }) } } // Check that extra params are properly set. func TestParser_Extra(t *testing.T) { cases := []struct { line []string extra []string }{ {[]string{"cmd"}, []string{}}, {[]string{"cmd", "--help"}, []string{}}, {[]string{"cmd", "subcmd"}, []string{}}, {[]string{"cmd", "subcmd", "--"}, []string{}}, {[]string{"cmd", "subcmd", "--", "extra"}, []string{"extra"}}, {[]string{"cmd", "subcmd", "--", "extra1", "--extra2"}, []string{"extra1", "--extra2"}}, } for _, c := range cases { subtest.Run(t, strings.Join(c.line, "_"), func(t *testing.T) { args := &Args{} parser := newParser() assert.NoError(t, parser.Parse(c.line, args)) assert.Equal(t, c.extra, args.Extra) }) } } // If a flag doesn't exist, an error is returned. func TestParser_Error(t *testing.T) { line := []string{"cmd", "--boom"} args := &Args{} parser := newParser() assert.Error(t, parser.Parse(line, args)) } // If a usage string is passed, and the command line has the help flag, the // message is printed out. func TestParser_Usage(t *testing.T) { line := []string{"cmd", "-h"} args := &Args{} streams := cmd.NewMemoryStreams("") parser := newParserWithStreams(streams) parser.UsageMessage = "usage message" assert.Error(t, parser.Parse(line, args)) assert.Equal(t, parser.UsageMessage, streams.Out()) } // Return a new test parser func newParser() *cmd.Parser { return newParserWithStreams(cmd.NewMemoryStreams("")) } // Return a new test parser using the given streams for its context. func newParserWithStreams(streams *cmd.MemoryStreams) *cmd.Parser { return &cmd.Parser{ Context: cmd.NewMemoryContext(streams), } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cmd/parser.go���������������������������������������������������������������������0000644�0610621�0607500�00000007366�13172163242�017341� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package cmd import ( "reflect" "strings" "unsafe" "github.com/lxc/lxd/shared/gnuflag" ) // Parser for command line arguments. type Parser struct { Context *Context UsageMessage string ExitOnError bool } // NewParser returns a Parser connected to the given I/O context and printing // the given usage message when '--help' or '-h' are passed. func NewParser(context *Context, usage string) *Parser { return &Parser{ Context: context, UsageMessage: usage, ExitOnError: true, } } // Parse a command line populating the given args object accordingly. // // The command line format is expected to be: // // <cmd> [subcmd [params]] [flags] [-- [extra]] // // The args object may have Subcommand, Params and Extra attributes // (respectively of type string, []string and []string), which will be // populated with the subcommand, its params and any extra argument (if // present). // // The type of the args object must have one attribute for each supported // command line flag, annotated with a tag like `flag:"<name>"`, where <name> // is the name of the command line flag. // // In case of parsing error (e.g. unknown command line flag) the default // behavior is to call os.Exit() with a non-zero value. This can be disabled by // setting the ExitOnError attribute to false, in which case the error will be // returned. func (p *Parser) Parse(line []string, args interface{}) error { val := reflect.ValueOf(args).Elem() if err := p.parseFlags(line, val); err != nil { return err } p.parseRest(line, val) return nil } // Populate the given FlagSet by introspecting the given object, adding a new // flag variable for each annotated attribute. func (p *Parser) parseFlags(line []string, val reflect.Value) error { mode := gnuflag.ContinueOnError if p.ExitOnError { mode = gnuflag.ExitOnError } flags := gnuflag.NewFlagSet(line[0], mode) flags.SetOutput(p.Context.stderr) if p.UsageMessage != "" { // Since usage will be printed only if "-h" or "--help" are // explicitly set in the command line, use stdout for it. flags.Usage = func() { p.Context.Output(p.UsageMessage) } } typ := val.Type() for i := 0; i < typ.NumField(); i++ { name := typ.Field(i).Tag.Get("flag") if name == "" { continue } kind := typ.Field(i).Type.Kind() addr := val.Field(i).Addr() switch kind { case reflect.Bool: pointer := (*bool)(unsafe.Pointer(addr.Pointer())) flags.BoolVar(pointer, name, false, "") case reflect.String: pointer := (*string)(unsafe.Pointer(addr.Pointer())) flags.StringVar(pointer, name, "", "") case reflect.Int: pointer := (*int)(unsafe.Pointer(addr.Pointer())) flags.IntVar(pointer, name, -1, "") case reflect.Int64: pointer := (*int64)(unsafe.Pointer(addr.Pointer())) flags.Int64Var(pointer, name, -1, "") } } return flags.Parse(true, line[1:]) } // Parse any non-flag argument, i.e. the subcommand, its parameters and any // extra argument following "--". func (p *Parser) parseRest(line []string, val reflect.Value) { subcommand := "" params := []string{} extra := []string{} if len(line) > 1 { rest := line[1:] for i, token := range rest { if token == "--" { // Set extra to anything left, excluding the token. if i < len(rest)-1 { extra = rest[i+1:] } break } if strings.HasPrefix(token, "-") { // Subcommand and parameters must both come // before any flag. break } if i == 0 { subcommand = token continue } params = append(params, token) } } if field := val.FieldByName("Subcommand"); field.IsValid() { field.SetString(subcommand) } if field := val.FieldByName("Params"); field.IsValid() { field.Set(reflect.ValueOf(params)) } if field := val.FieldByName("Extra"); field.IsValid() { field.Set(reflect.ValueOf(extra)) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cmd/doc.go������������������������������������������������������������������������0000644�0610621�0607500�00000000425�13172163242�016577� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* The package cmd implements a simple abstraction around a "sub-command" for a main executable (e.g. "lxd init", where "init" is the sub-command). It is designed to make unit-testing easier, since OS-specific parts like standard in/out can be set in tests. */ package cmd �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cmd/context_test.go���������������������������������������������������������������0000644�0610621�0607500�00000013074�13172163242�020561� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package cmd_test import ( "fmt" "testing" "github.com/lxc/lxd/shared/cmd" "github.com/stretchr/testify/assert" ) // AssertOutEqual checks that the given text matches the the out stream. func AssertOutEqual(t *testing.T, stream *cmd.MemoryStreams, expected string) { assert.Equal(t, expected, stream.Out(), "Unexpected output stream") } // AssertErrEqual checks that the given text matches the the err stream. func AssertErrEqual(t *testing.T, stream *cmd.MemoryStreams, expected string) { assert.Equal(t, expected, stream.Err(), "Unexpected error stream") } // Output prints the given message on standard output func TestOutput(t *testing.T) { streams := cmd.NewMemoryStreams("") context := cmd.NewMemoryContext(streams) context.Output("Hello %s", "world") AssertOutEqual(t, streams, "Hello world") } // AskBool returns a boolean result depending on the user input. func TestAskBool(t *testing.T) { cases := []struct { question string defaultAnswer string output string error string input string result bool }{ {"Do you code?", "yes", "Do you code?", "", "\n", true}, {"Do you code?", "yes", "Do you code?", "", "yes\n", true}, {"Do you code?", "yes", "Do you code?", "", "y\n", true}, {"Do you code?", "yes", "Do you code?", "", "no\n", false}, {"Do you code?", "yes", "Do you code?", "", "n\n", false}, {"Do you code?", "yes", "Do you code?Do you code?", "Invalid input, try again.\n\n", "foo\nyes\n", true}, } for _, c := range cases { streams := cmd.NewMemoryStreams(c.input) context := cmd.NewMemoryContext(streams) result := context.AskBool(c.question, c.defaultAnswer) assert.Equal(t, c.result, result, "Unexpected answer result") AssertOutEqual(t, streams, c.output) AssertErrEqual(t, streams, c.error) } } // AskChoice returns one of the given choices func TestAskChoice(t *testing.T) { cases := []struct { question string choices []string defaultAnswer string output string error string input string result string }{ {"Best food?", []string{"pizza", "rice"}, "rice", "Best food?", "", "\n", "rice"}, {"Best food?", []string{"pizza", "rice"}, "rice", "Best food?", "", "pizza\n", "pizza"}, {"Best food?", []string{"pizza", "rice"}, "rice", "Best food?Best food?", "Invalid input, try again.\n\n", "foo\npizza\n", "pizza"}, } for _, c := range cases { streams := cmd.NewMemoryStreams(c.input) context := cmd.NewMemoryContext(streams) result := context.AskChoice(c.question, c.choices, c.defaultAnswer) assert.Equal(t, c.result, result, "Unexpected answer result") AssertOutEqual(t, streams, c.output) AssertErrEqual(t, streams, c.error) } } // AskInt returns an integer within the given bounds func TestAskInt(t *testing.T) { cases := []struct { question string min int64 max int64 defaultAnswer string output string error string input string result int64 }{ {"Age?", 0, 100, "30", "Age?", "", "\n", 30}, {"Age?", 0, 100, "30", "Age?", "", "40\n", 40}, {"Age?", 0, 100, "30", "Age?Age?", "Invalid input, try again.\n\n", "foo\n40\n", 40}, {"Age?", 18, 65, "30", "Age?Age?", "Invalid input, try again.\n\n", "10\n30\n", 30}, {"Age?", 18, 65, "30", "Age?Age?", "Invalid input, try again.\n\n", "70\n30\n", 30}, {"Age?", 0, -1, "30", "Age?", "", "120\n", 120}, } for _, c := range cases { streams := cmd.NewMemoryStreams(c.input) context := cmd.NewMemoryContext(streams) result := context.AskInt(c.question, c.min, c.max, c.defaultAnswer) assert.Equal(t, c.result, result, "Unexpected answer result") AssertOutEqual(t, streams, c.output) AssertErrEqual(t, streams, c.error) } } // AskString returns a string conforming the validation function. func TestAskString(t *testing.T) { cases := []struct { question string defaultAnswer string validate func(string) error output string error string input string result string }{ {"Name?", "Joe", nil, "Name?", "", "\n", "Joe"}, {"Name?", "Joe", nil, "Name?", "", "John\n", "John"}, {"Name?", "Joe", func(s string) error { if s[0] != 'J' { return fmt.Errorf("ugly name") } return nil }, "Name?Name?", "Invalid input: ugly name\n\n", "Ted\nJohn", "John"}, } for _, c := range cases { streams := cmd.NewMemoryStreams(c.input) context := cmd.NewMemoryContext(streams) result := context.AskString(c.question, c.defaultAnswer, c.validate) assert.Equal(t, c.result, result, "Unexpected answer result") AssertOutEqual(t, streams, c.output) AssertErrEqual(t, streams, c.error) } } // AskPassword returns the password entered twice by the user. func TestAskPassword(t *testing.T) { cases := []struct { question string reader func(int) ([]byte, error) output string error string result string }{ {"Pass?", func(int) ([]byte, error) { return []byte("pwd"), nil }, "Pass?\nAgain: \n", "", "pwd"}, } for _, c := range cases { streams := cmd.NewMemoryStreams("") context := cmd.NewMemoryContext(streams) result := context.AskPassword(c.question, c.reader) assert.Equal(t, c.result, result, "Unexpected answer result") AssertOutEqual(t, streams, c.output) AssertErrEqual(t, streams, c.error) } } // InputYAML parses the YAML content passed via stdin. func TestInputYAML(t *testing.T) { streams := cmd.NewMemoryStreams("field: foo") context := cmd.NewMemoryContext(streams) type Schema struct { Field string } schema := Schema{} assert.Nil(t, context.InputYAML(&schema)) assert.Equal(t, "foo", schema.Field, "Unexpected field value") } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cmd/context.go��������������������������������������������������������������������0000644�0610621�0607500�00000010046�13172163242�017516� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package cmd import ( "bufio" "fmt" "gopkg.in/yaml.v2" "io" "io/ioutil" "os" "strconv" "strings" "github.com/lxc/lxd/shared" ) // Context captures the environment the sub-command is being run in, // such as in/out/err streams and command line arguments. type Context struct { stdin *bufio.Reader stdout io.Writer stderr io.Writer } // DefaultContext returns a new Context connected the stdin, stdout and stderr // streams. func DefaultContext() *Context { return NewContext(os.Stdin, os.Stderr, os.Stdout) } // NewContext creates a new command context with the given parameters. func NewContext(stdin io.Reader, stdout, stderr io.Writer) *Context { return &Context{ stdin: bufio.NewReader(stdin), stdout: stdout, stderr: stderr, } } // Output prints a message on standard output. func (c *Context) Output(format string, a ...interface{}) { fmt.Fprintf(c.stdout, format, a...) } // AskBool asks a question an expect a yes/no answer. func (c *Context) AskBool(question string, defaultAnswer string) bool { for { answer := c.askQuestion(question, defaultAnswer) if shared.StringInSlice(strings.ToLower(answer), []string{"yes", "y"}) { return true } else if shared.StringInSlice(strings.ToLower(answer), []string{"no", "n"}) { return false } c.invalidInput() } } // AskChoice asks the user to select between a set of choices func (c *Context) AskChoice(question string, choices []string, defaultAnswer string) string { for { answer := c.askQuestion(question, defaultAnswer) if shared.StringInSlice(answer, choices) { return answer } c.invalidInput() } } // AskInt asks the user to enter an integer between a min and max value func (c *Context) AskInt(question string, min int64, max int64, defaultAnswer string) int64 { for { answer := c.askQuestion(question, defaultAnswer) result, err := strconv.ParseInt(answer, 10, 64) if err == nil && (min == -1 || result >= min) && (max == -1 || result <= max) { return result } c.invalidInput() } } // AskString asks the user to enter a string, which optionally // conforms to a validation function. func (c *Context) AskString(question string, defaultAnswer string, validate func(string) error) string { for { answer := c.askQuestion(question, defaultAnswer) if validate != nil { error := validate(answer) if error != nil { fmt.Fprintf(c.stderr, "Invalid input: %s\n\n", error) continue } } if len(answer) != 0 { return answer } c.invalidInput() } } // AskPassword asks the user to enter a password. The reader function used to // read the password without echoing characters must be passed (usually // terminal.ReadPassword from golang.org/x/crypto/ssh/terminal). func (c *Context) AskPassword(question string, reader func(int) ([]byte, error)) string { for { fmt.Fprintf(c.stdout, question) pwd, _ := reader(0) fmt.Fprintf(c.stdout, "\n") inFirst := string(pwd) inFirst = strings.TrimSuffix(inFirst, "\n") fmt.Fprintf(c.stdout, "Again: ") pwd, _ = reader(0) fmt.Fprintf(c.stdout, "\n") inSecond := string(pwd) inSecond = strings.TrimSuffix(inSecond, "\n") if inFirst == inSecond { return inFirst } c.invalidInput() } } // InputYAML treats stdin as YAML content and returns the unmarshalled // structure func (c *Context) InputYAML(out interface{}) error { bytes, err := ioutil.ReadAll(c.stdin) if err != nil { return err } return yaml.Unmarshal(bytes, out) } // Ask a question on the output stream and read the answer from the input stream func (c *Context) askQuestion(question, defaultAnswer string) string { fmt.Fprintf(c.stdout, question) return c.readAnswer(defaultAnswer) } // Print an invalid input message on the error stream func (c *Context) invalidInput() { fmt.Fprintf(c.stderr, "Invalid input, try again.\n\n") } // Read the user's answer from the input stream, trimming newline and providing a default. func (c *Context) readAnswer(defaultAnswer string) string { answer, _ := c.stdin.ReadString('\n') answer = strings.TrimSuffix(answer, "\n") if answer == "" { answer = defaultAnswer } return answer } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cert_test.go����������������������������������������������������������������������0000644�0610621�0607500�00000001703�13172163242�017263� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package shared import ( "encoding/pem" "testing" ) func TestGenerateMemCert(t *testing.T) { if testing.Short() { t.Skip("skipping cert generation in short mode") } cert, key, err := GenerateMemCert(false) if err != nil { t.Error(err) return } if cert == nil { t.Error("GenerateMemCert returned a nil cert") return } if key == nil { t.Error("GenerateMemCert returned a nil key") return } block, rest := pem.Decode(cert) if len(rest) != 0 { t.Errorf("GenerateMemCert returned a cert with trailing content: %q", string(rest)) } if block.Type != "CERTIFICATE" { t.Errorf("GenerateMemCert returned a cert with Type %q not \"CERTIFICATE\"", block.Type) } block, rest = pem.Decode(key) if len(rest) != 0 { t.Errorf("GenerateMemCert returned a key with trailing content: %q", string(rest)) } if block.Type != "RSA PRIVATE KEY" { t.Errorf("GenerateMemCert returned a cert with Type %q not \"RSA PRIVATE KEY\"", block.Type) } } �������������������������������������������������������������lxd-2.0.11/shared/cert.go���������������������������������������������������������������������������0000644�0610621�0607500�00000013141�13172163242�016223� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// http://golang.org/src/pkg/crypto/tls/generate_cert.go // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package shared import ( "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "fmt" "io/ioutil" "math/big" "net" "net/http" "os" "os/user" "path" "time" ) /* * Generate a list of names for which the certificate will be valid. * This will include the hostname and ip address */ func mynames() ([]string, error) { h, err := os.Hostname() if err != nil { return nil, err } ret := []string{h} ifs, err := net.Interfaces() if err != nil { return nil, err } for _, iface := range ifs { if IsLoopback(&iface) { continue } addrs, err := iface.Addrs() if err != nil { return nil, err } for _, addr := range addrs { ret = append(ret, addr.String()) } } return ret, nil } func FindOrGenCert(certf string, keyf string, certtype bool) error { if PathExists(certf) && PathExists(keyf) { return nil } /* If neither stat succeeded, then this is our first run and we * need to generate cert and privkey */ err := GenCert(certf, keyf, certtype) if err != nil { return err } return nil } // GenCert will create and populate a certificate file and a key file func GenCert(certf string, keyf string, certtype bool) error { /* Create the basenames if needed */ dir := path.Dir(certf) err := os.MkdirAll(dir, 0750) if err != nil { return err } dir = path.Dir(keyf) err = os.MkdirAll(dir, 0750) if err != nil { return err } certBytes, keyBytes, err := GenerateMemCert(certtype) if err != nil { return err } certOut, err := os.Create(certf) if err != nil { return fmt.Errorf("Failed to open %s for writing: %v", certf, err) } certOut.Write(certBytes) certOut.Close() keyOut, err := os.OpenFile(keyf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("Failed to open %s for writing: %v", keyf, err) } keyOut.Write(keyBytes) keyOut.Close() return nil } // GenerateMemCert creates client or server certificate and key pair, // returning them as byte arrays in memory. func GenerateMemCert(client bool) ([]byte, []byte, error) { privk, err := rsa.GenerateKey(rand.Reader, 4096) if err != nil { return nil, nil, fmt.Errorf("Failed to generate key: %v", err) } hosts, err := mynames() if err != nil { return nil, nil, fmt.Errorf("Failed to get my hostname: %v", err) } validFrom := time.Now() validTo := validFrom.Add(10 * 365 * 24 * time.Hour) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, fmt.Errorf("Failed to generate serial number: %v", err) } userEntry, err := user.Current() var username string if err == nil { username = userEntry.Username if username == "" { username = "UNKNOWN" } } else { username = "UNKNOWN" } hostname, err := os.Hostname() if err != nil { hostname = "UNKNOWN" } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{"linuxcontainers.org"}, CommonName: fmt.Sprintf("%s@%s", username, hostname), }, NotBefore: validFrom, NotAfter: validTo, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, BasicConstraintsValid: true, } if client { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} } else { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} } for _, h := range hosts { if ip, _, err := net.ParseCIDR(h); err == nil { if !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast() { template.IPAddresses = append(template.IPAddresses, ip) } } else { template.DNSNames = append(template.DNSNames, h) } } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privk.PublicKey, privk) if err != nil { return nil, nil, fmt.Errorf("Failed to create certificate: %v", err) } cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) key := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privk)}) return cert, key, nil } func ReadCert(fpath string) (*x509.Certificate, error) { cf, err := ioutil.ReadFile(fpath) if err != nil { return nil, err } certBlock, _ := pem.Decode(cf) if certBlock == nil { return nil, fmt.Errorf("Invalid certificate file") } return x509.ParseCertificate(certBlock.Bytes) } func CertFingerprint(cert *x509.Certificate) string { return fmt.Sprintf("%x", sha256.Sum256(cert.Raw)) } func CertFingerprintStr(c string) (string, error) { pemCertificate, _ := pem.Decode([]byte(c)) if pemCertificate == nil { return "", fmt.Errorf("invalid certificate") } cert, err := x509.ParseCertificate(pemCertificate.Bytes) if err != nil { return "", err } return CertFingerprint(cert), nil } func GetRemoteCertificate(address string) (*x509.Certificate, error) { // Setup a permissive TLS config tlsConfig, err := GetTLSConfig("", "", "", nil) if err != nil { return nil, err } tlsConfig.InsecureSkipVerify = true tr := &http.Transport{ TLSClientConfig: tlsConfig, Dial: RFC3493Dialer, Proxy: ProxyFromEnvironment, } // Connect client := &http.Client{Transport: tr} resp, err := client.Get(address) if err != nil { return nil, err } // Retrieve the certificate if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 { return nil, fmt.Errorf("Unable to read remote TLS certificate") } return resp.TLS.PeerCertificates[0], nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cancel/���������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016164� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/cancel/canceler.go����������������������������������������������������������������0000644�0610621�0607500�00000001674�13172163242�020277� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package cancel import ( "fmt" "net/http" ) // A struct to track canceleation type Canceler struct { reqChCancel map[*http.Request]chan struct{} } func NewCanceler() *Canceler { c := Canceler{} c.reqChCancel = make(map[*http.Request]chan struct{}) return &c } func (c *Canceler) Cancelable() bool { return len(c.reqChCancel) > 0 } func (c *Canceler) Cancel() error { if !c.Cancelable() { return fmt.Errorf("This operation cannot be canceled at this time") } for req, ch := range c.reqChCancel { close(ch) delete(c.reqChCancel, req) } return nil } func CancelableDownload(c *Canceler, client *http.Client, req *http.Request) (*http.Response, chan bool, error) { chDone := make(chan bool) chCancel := make(chan struct{}) if c != nil { c.reqChCancel[req] = chCancel } req.Cancel = chCancel go func() { <-chDone if c != nil { delete(c.reqChCancel, req) } }() resp, err := client.Do(req) return resp, chDone, err } ��������������������������������������������������������������������lxd-2.0.11/shared/api/������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015510� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/storage_pool_volume.go��������������������������������������������������������0000644�0610621�0607500�00000002444�13172163242�022127� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // StorageVolumesPost represents the fields of a new LXD storage pool volume // // API extension: storage type StorageVolumesPost struct { StorageVolumePut `yaml:",inline"` Name string `json:"name" yaml:"name"` Type string `json:"type" yaml:"type"` } // StorageVolumePost represents the fields required to rename a LXD storage pool volume // // API extension: storage_api_volume_rename type StorageVolumePost struct { Name string `json:"name" yaml:"name"` } // StorageVolume represents the fields of a LXD storage volume. // // API extension: storage type StorageVolume struct { StorageVolumePut `yaml:",inline"` Name string `json:"name" yaml:"name"` Type string `json:"type" yaml:"type"` UsedBy []string `json:"used_by" yaml:"used_by"` } // StorageVolumePut represents the modifiable fields of a LXD storage volume. // // API extension: storage type StorageVolumePut struct { Config map[string]string `json:"config" yaml:"config"` // API extension: entity_description Description string `json:"description" yaml:"description"` } // Writable converts a full StorageVolume struct into a StorageVolumePut struct // (filters read-only fields). func (storageVolume *StorageVolume) Writable() StorageVolumePut { return storageVolume.StorageVolumePut } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/storage_pool.go���������������������������������������������������������������0000644�0610621�0607500�00000002031�13172163242�020530� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // StoragePoolsPost represents the fields of a new LXD storage pool // // API extension: storage type StoragePoolsPost struct { StoragePoolPut `yaml:",inline"` Name string `json:"name" yaml:"name"` Driver string `json:"driver" yaml:"driver"` } // StoragePool represents the fields of a LXD storage pool. // // API extension: storage type StoragePool struct { StoragePoolPut `yaml:",inline"` Name string `json:"name" yaml:"name"` Driver string `json:"driver" yaml:"driver"` UsedBy []string `json:"used_by" yaml:"used_by"` } // StoragePoolPut represents the modifiable fields of a LXD storage pool. // // API extension: storage type StoragePoolPut struct { Config map[string]string `json:"config" yaml:"config"` // API extension: entity_description Description string `json:"description" yaml:"description"` } // Writable converts a full StoragePool struct into a StoragePoolPut struct // (filters read-only fields). func (storagePool *StoragePool) Writable() StoragePoolPut { return storagePool.StoragePoolPut } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/status_code.go����������������������������������������������������������������0000644�0610621�0607500�00000002667�13172163242�020367� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // StatusCode represents a valid LXD operation and container status type StatusCode int // LXD status codes const ( OperationCreated StatusCode = 100 Started StatusCode = 101 Stopped StatusCode = 102 Running StatusCode = 103 Cancelling StatusCode = 104 Pending StatusCode = 105 Starting StatusCode = 106 Stopping StatusCode = 107 Aborting StatusCode = 108 Freezing StatusCode = 109 Frozen StatusCode = 110 Thawed StatusCode = 111 Error StatusCode = 112 Success StatusCode = 200 Failure StatusCode = 400 Cancelled StatusCode = 401 ) // String returns a suitable string representation for the status code func (o StatusCode) String() string { return map[StatusCode]string{ OperationCreated: "Operation created", Started: "Started", Stopped: "Stopped", Running: "Running", Cancelling: "Cancelling", Pending: "Pending", Success: "Success", Failure: "Failure", Cancelled: "Cancelled", Starting: "Starting", Stopping: "Stopping", Aborting: "Aborting", Freezing: "Freezing", Frozen: "Frozen", Thawed: "Thawed", Error: "Error", }[o] } // IsFinal will return true if the status code indicates an end state func (o StatusCode) IsFinal() bool { return int(o) >= 200 } �������������������������������������������������������������������������lxd-2.0.11/shared/api/server.go���������������������������������������������������������������������0000644�0610621�0607500�00000004164�13172163242�017352� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // ServerEnvironment represents the read-only environment fields of a LXD server type ServerEnvironment struct { Addresses []string `json:"addresses" yaml:"addresses"` Architectures []string `json:"architectures" yaml:"architectures"` Certificate string `json:"certificate" yaml:"certificate"` CertificateFingerprint string `json:"certificate_fingerprint" yaml:"certificate_fingerprint"` Driver string `json:"driver" yaml:"driver"` DriverVersion string `json:"driver_version" yaml:"driver_version"` Kernel string `json:"kernel" yaml:"kernel"` KernelArchitecture string `json:"kernel_architecture" yaml:"kernel_architecture"` KernelVersion string `json:"kernel_version" yaml:"kernel_version"` Server string `json:"server" yaml:"server"` ServerPid int `json:"server_pid" yaml:"server_pid"` ServerVersion string `json:"server_version" yaml:"server_version"` Storage string `json:"storage" yaml:"storage"` StorageVersion string `json:"storage_version" yaml:"storage_version"` } // ServerPut represents the modifiable fields of a LXD server configuration type ServerPut struct { Config map[string]interface{} `json:"config" yaml:"config"` } // ServerUntrusted represents a LXD server for an untrusted client type ServerUntrusted struct { APIExtensions []string `json:"api_extensions" yaml:"api_extensions"` APIStatus string `json:"api_status" yaml:"api_status"` APIVersion string `json:"api_version" yaml:"api_version"` Auth string `json:"auth" yaml:"auth"` AuthMethods []string `json:"auth_methods" yaml:"auth_methods"` Public bool `json:"public" yaml:"public"` } // Server represents a LXD server type Server struct { ServerPut `yaml:",inline"` ServerUntrusted `yaml:",inline"` Environment ServerEnvironment `json:"environment" yaml:"environment"` } // Writable converts a full Server struct into a ServerPut struct (filters read-only fields) func (srv *Server) Writable() ServerPut { return srv.ServerPut } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/response.go�������������������������������������������������������������������0000644�0610621�0607500�00000003623�13172163242�017701� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api import ( "encoding/json" ) // ResponseRaw represents a LXD operation in its original form type ResponseRaw struct { Response `yaml:",inline"` Metadata interface{} `json:"metadata" yaml:"metadata"` } // Response represents a LXD operation type Response struct { Type ResponseType `json:"type" yaml:"type"` // Valid only for Sync responses Status string `json:"status" yaml:"status"` StatusCode int `json:"status_code" yaml:"status_code"` // Valid only for Async responses Operation string `json:"operation" yaml:"operation"` // Valid only for Error responses Code int `json:"error_code" yaml:"error_code"` Error string `json:"error" yaml:"error"` // Valid for Sync and Error responses Metadata json.RawMessage `json:"metadata" yaml:"metadata"` } // MetadataAsMap parses the Response metadata into a map func (r *Response) MetadataAsMap() (map[string]interface{}, error) { ret := map[string]interface{}{} err := r.MetadataAsStruct(&ret) if err != nil { return nil, err } return ret, nil } // MetadataAsOperation turns the Response metadata into an Operation func (r *Response) MetadataAsOperation() (*Operation, error) { op := Operation{} err := r.MetadataAsStruct(&op) if err != nil { return nil, err } return &op, nil } // MetadataAsStringSlice parses the Response metadata into a slice of string func (r *Response) MetadataAsStringSlice() ([]string, error) { sl := []string{} err := r.MetadataAsStruct(&sl) if err != nil { return nil, err } return sl, nil } // MetadataAsStruct parses the Response metadata into a provided struct func (r *Response) MetadataAsStruct(target interface{}) error { return json.Unmarshal(r.Metadata, &target) } // ResponseType represents a valid LXD response type type ResponseType string // LXD response types const ( SyncResponse ResponseType = "sync" AsyncResponse ResponseType = "async" ErrorResponse ResponseType = "error" ) �������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/resource.go�������������������������������������������������������������������0000644�0610621�0607500�00000004217�13172163242�017672� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // Resources represents the system resources avaible for LXD // API extension: resources type Resources struct { CPU ResourcesCPU `json:"cpu,omitempty" yaml:"cpu,omitempty"` Memory ResourcesMemory `json:"memory,omitempty" yaml:"memory,omitempty"` StoragePool ResourcesStoragePool `json:"pool,omitempty" yaml:"pool,omitempty"` } // ResourcesCPUSocket represents a cpu socket on the system // API extension: resources type ResourcesCPUSocket struct { Cores uint64 `json:"cores" yaml:"cores"` Frequency uint64 `json:"frequency,omitempty" yaml:"frequency,omitempty"` FrequencyTurbo uint64 `json:"frequency_turbo,omitempty" yaml:"frequency_turbo,omitempty"` Name string `json:"name,omitempty" yaml:"name,omitempty"` Vendor string `json:"vendor,omitempty" yaml:"vendor,omitempty"` Threads uint64 `json:"threads" yaml:"threads"` } // ResourcesCPU represents the cpu resources available on the system // API extension: resources type ResourcesCPU struct { Sockets []ResourcesCPUSocket `json:"sockets" yaml:"sockets"` Total uint64 `json:"total" yaml:"total"` } // ResourcesMemory represents the memory resources available on the system // API extension: resources type ResourcesMemory struct { Used uint64 `json:"used" yaml:"used"` Total uint64 `json:"total" yaml:"total"` } // ResourcesStoragePool represents the resources available to a given storage pool // API extension: resources type ResourcesStoragePool struct { Space ResourcesStoragePoolSpace `json:"space,omitempty" yaml:"space,omitempty"` Inodes ResourcesStoragePoolInodes `json:"inodes,omitempty" yaml:"inodes,omitempty"` } // ResourcesStoragePoolSpace represents the space available to a given storage pool // API extension: resources type ResourcesStoragePoolSpace struct { Used uint64 `json:"used,omitempty" yaml:"used,omitempty"` Total uint64 `json:"total" yaml:"total"` } // ResourcesStoragePoolInodes represents the inodes available to a given storage pool // API extension: resources type ResourcesStoragePoolInodes struct { Used uint64 `json:"used" yaml:"used"` Total uint64 `json:"total" yaml:"total"` } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/profile.go��������������������������������������������������������������������0000644�0610621�0607500�00000001767�13172163242�017512� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // ProfilesPost represents the fields of a new LXD profile type ProfilesPost struct { ProfilePut `yaml:",inline"` Name string `json:"name" yaml:"name"` } // ProfilePost represents the fields required to rename a LXD profile type ProfilePost struct { Name string `json:"name" yaml:"name"` } // ProfilePut represents the modifiable fields of a LXD profile type ProfilePut struct { Config map[string]string `json:"config" yaml:"config"` Description string `json:"description" yaml:"description"` Devices map[string]map[string]string `json:"devices" yaml:"devices"` } // Profile represents a LXD profile type Profile struct { ProfilePut `yaml:",inline"` Name string `json:"name" yaml:"name"` // API extension: profile_usedby UsedBy []string `json:"used_by" yaml:"used_by"` } // Writable converts a full Profile struct into a ProfilePut struct (filters read-only fields) func (profile *Profile) Writable() ProfilePut { return profile.ProfilePut } ���������lxd-2.0.11/shared/api/operation.go������������������������������������������������������������������0000644�0610621�0607500�00000001424�13172163242�020040� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api import ( "time" ) // Operation represents a LXD background operation type Operation struct { ID string `json:"id" yaml:"id"` Class string `json:"class" yaml:"class"` CreatedAt time.Time `json:"created_at" yaml:"created_at"` UpdatedAt time.Time `json:"updated_at" yaml:"updated_at"` Status string `json:"status" yaml:"status"` StatusCode StatusCode `json:"status_code" yaml:"status_code"` Resources map[string][]string `json:"resources" yaml:"resources"` Metadata map[string]interface{} `json:"metadata" yaml:"metadata"` MayCancel bool `json:"may_cancel" yaml:"may_cancel"` Err string `json:"err" yaml:"err"` } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/network.go��������������������������������������������������������������������0000644�0610621�0607500�00000002270�13172163242�017531� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // NetworksPost represents the fields of a new LXD network // // API extension: network type NetworksPost struct { NetworkPut `yaml:",inline"` Managed bool `json:"managed" yaml:"managed"` Name string `json:"name" yaml:"name"` Type string `json:"type" yaml:"type"` } // NetworkPost represents the fields required to rename a LXD network // // API extension: network type NetworkPost struct { Name string `json:"name" yaml:"name"` } // NetworkPut represents the modifiable fields of a LXD network // // API extension: network type NetworkPut struct { Config map[string]string `json:"config" yaml:"config"` // API extension: entity_description Description string `json:"description" yaml:"description"` } // Network represents a LXD network type Network struct { NetworkPut `yaml:",inline"` Name string `json:"name" yaml:"name"` Type string `json:"type" yaml:"type"` UsedBy []string `json:"used_by" yaml:"used_by"` // API extension: network Managed bool `json:"managed" yaml:"managed"` } // Writable converts a full Network struct into a NetworkPut struct (filters read-only fields) func (network *Network) Writable() NetworkPut { return network.NetworkPut } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/image.go����������������������������������������������������������������������0000644�0610621�0607500�00000010235�13172163242�017122� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api import ( "time" ) // ImagesPost represents the fields available for a new LXD image type ImagesPost struct { ImagePut `yaml:",inline"` Filename string `json:"filename" yaml:"filename"` Source *ImagesPostSource `json:"source" yaml:"source"` // API extension: image_compression_algorithm CompressionAlgorithm string `json:"compression_algorithm" yaml:"compression_algorithm"` // API extension: image_create_aliases Aliases []ImageAlias `json:"aliases" yaml:"aliases"` } // ImagesPostSource represents the source of a new LXD image type ImagesPostSource struct { ImageSource `yaml:",inline"` Mode string `json:"mode" yaml:"mode"` Type string `json:"type" yaml:"type"` // For protocol "direct" URL string `json:"url" yaml:"url"` // For type "container" Name string `json:"name" yaml:"name"` // For type "image" Fingerprint string `json:"fingerprint" yaml:"fingerprint"` Secret string `json:"secret" yaml:"secret"` } // ImagePut represents the modifiable fields of a LXD image type ImagePut struct { AutoUpdate bool `json:"auto_update" yaml:"auto_update"` Properties map[string]string `json:"properties" yaml:"properties"` Public bool `json:"public" yaml:"public"` } // Image represents a LXD image type Image struct { ImagePut `yaml:",inline"` Aliases []ImageAlias `json:"aliases" yaml:"aliases"` Architecture string `json:"architecture" yaml:"architecture"` Cached bool `json:"cached" yaml:"cached"` Filename string `json:"filename" yaml:"filename"` Fingerprint string `json:"fingerprint" yaml:"fingerprint"` Size int64 `json:"size" yaml:"size"` UpdateSource *ImageSource `json:"update_source,omitempty" yaml:"update_source,omitempty"` CreatedAt time.Time `json:"created_at" yaml:"created_at"` ExpiresAt time.Time `json:"expires_at" yaml:"expires_at"` LastUsedAt time.Time `json:"last_used_at" yaml:"last_used_at"` UploadedAt time.Time `json:"uploaded_at" yaml:"uploaded_at"` } // Writable converts a full Image struct into a ImagePut struct (filters read-only fields) func (img *Image) Writable() ImagePut { return img.ImagePut } // ImageAlias represents an alias from the alias list of a LXD image type ImageAlias struct { Name string `json:"name" yaml:"name"` Description string `json:"description" yaml:"description"` } // ImageSource represents the source of a LXD image type ImageSource struct { Alias string `json:"alias" yaml:"alias"` Certificate string `json:"certificate" yaml:"certificate"` Protocol string `json:"protocol" yaml:"protocol"` Server string `json:"server" yaml:"server"` } // ImageAliasesPost represents a new LXD image alias type ImageAliasesPost struct { ImageAliasesEntry `yaml:",inline"` } // ImageAliasesEntryPost represents the required fields to rename a LXD image alias type ImageAliasesEntryPost struct { Name string `json:"name" yaml:"name"` } // ImageAliasesEntryPut represents the modifiable fields of a LXD image alias type ImageAliasesEntryPut struct { Description string `json:"description" yaml:"description"` Target string `json:"target" yaml:"target"` } // ImageAliasesEntry represents a LXD image alias type ImageAliasesEntry struct { ImageAliasesEntryPut `yaml:",inline"` Name string `json:"name" yaml:"name"` } // ImageMetadata represents LXD image metadata type ImageMetadata struct { Architecture string `json:"architecture" yaml:"architecture"` CreationDate int64 `json:"creation_date" yaml:"creation_date"` ExpiryDate int64 `json:"expiry_date" yaml:"expiry_date"` Properties map[string]string `json:"properties" yaml:"properties"` Templates map[string]*ImageMetadataTemplate `json:"templates" yaml:"templates"` } // ImageMetadataTemplate represents a template entry in image metadata type ImageMetadataTemplate struct { When []string `json:"when" yaml:"when"` CreateOnly bool `json:"create_only" yaml:"create_only"` Template string `json:"template" yaml:"template"` Properties map[string]string `json:"properties" yaml:"properties"` } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/doc.go������������������������������������������������������������������������0000644�0610621�0607500�00000001026�13172163242�016603� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package api contains Go structs for all LXD API objects // // Overview // // This package has Go structs for every API object, all the various // structs are named after the object they represent and some variations of // those structs exist for initial object creation, object update and // object retrieval. // // A few convenience functions are also tied to those structs which let // you convert between the various strucs for a given object and also query // some of the more complex metadata that LXD can export. package api ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/container_state.go������������������������������������������������������������0000644�0610621�0607500�00000006162�13172163242�021226� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // ContainerStatePut represents the modifiable fields of a LXD container's state type ContainerStatePut struct { Action string `json:"action" yaml:"action"` Timeout int `json:"timeout" yaml:"timeout"` Force bool `json:"force" yaml:"force"` Stateful bool `json:"stateful" yaml:"stateful"` } // ContainerState represents a LXD container's state type ContainerState struct { Status string `json:"status" yaml:"status"` StatusCode StatusCode `json:"status_code" yaml:"status_code"` Disk map[string]ContainerStateDisk `json:"disk" yaml:"disk"` Memory ContainerStateMemory `json:"memory" yaml:"memory"` Network map[string]ContainerStateNetwork `json:"network" yaml:"network"` Pid int64 `json:"pid" yaml:"pid"` Processes int64 `json:"processes" yaml:"processes"` // API extension: container_cpu_time CPU ContainerStateCPU `json:"cpu" yaml:"cpu"` } // ContainerStateDisk represents the disk information section of a LXD container's state type ContainerStateDisk struct { Usage int64 `json:"usage" yaml:"usage"` } // ContainerStateCPU represents the cpu information section of a LXD container's state // // API extension: container_cpu_time type ContainerStateCPU struct { Usage int64 `json:"usage" yaml:"usage"` } // ContainerStateMemory represents the memory information section of a LXD container's state type ContainerStateMemory struct { Usage int64 `json:"usage" yaml:"usage"` UsagePeak int64 `json:"usage_peak" yaml:"usage_peak"` SwapUsage int64 `json:"swap_usage" yaml:"swap_usage"` SwapUsagePeak int64 `json:"swap_usage_peak" yaml:"swap_usage_peak"` } // ContainerStateNetwork represents the network information section of a LXD container's state type ContainerStateNetwork struct { Addresses []ContainerStateNetworkAddress `json:"addresses" yaml:"addresses"` Counters ContainerStateNetworkCounters `json:"counters" yaml:"counters"` Hwaddr string `json:"hwaddr" yaml:"hwaddr"` HostName string `json:"host_name" yaml:"host_name"` Mtu int `json:"mtu" yaml:"mtu"` State string `json:"state" yaml:"state"` Type string `json:"type" yaml:"type"` } // ContainerStateNetworkAddress represents a network address as part of the network section of a LXD container's state type ContainerStateNetworkAddress struct { Family string `json:"family" yaml:"family"` Address string `json:"address" yaml:"address"` Netmask string `json:"netmask" yaml:"netmask"` Scope string `json:"scope" yaml:"scope"` } // ContainerStateNetworkCounters represents packet counters as part of the network section of a LXD container's state type ContainerStateNetworkCounters struct { BytesReceived int64 `json:"bytes_received" yaml:"bytes_received"` BytesSent int64 `json:"bytes_sent" yaml:"bytes_sent"` PacketsReceived int64 `json:"packets_received" yaml:"packets_received"` PacketsSent int64 `json:"packets_sent" yaml:"packets_sent"` } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/container_snapshot.go���������������������������������������������������������0000644�0610621�0607500�00000003250�13172163242�021740� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api import ( "time" ) // ContainerSnapshotsPost represents the fields available for a new LXD container snapshot type ContainerSnapshotsPost struct { Name string `json:"name" yaml:"name"` Stateful bool `json:"stateful" yaml:"stateful"` } // ContainerSnapshotPost represents the fields required to rename/move a LXD container snapshot type ContainerSnapshotPost struct { Name string `json:"name" yaml:"name"` Migration bool `json:"migration" yaml:"migration"` Target *ContainerPostTarget `json:"target" yaml:"target"` // API extension: container_snapshot_stateful_migration Live bool `json:"live,omitempty" yaml:"live,omitempty"` } // ContainerSnapshot represents a LXD conainer snapshot type ContainerSnapshot struct { Architecture string `json:"architecture" yaml:"architecture"` Config map[string]string `json:"config" yaml:"config"` CreationDate time.Time `json:"created_at" yaml:"created_at"` Devices map[string]map[string]string `json:"devices" yaml:"devices"` Ephemeral bool `json:"ephemeral" yaml:"ephemeral"` ExpandedConfig map[string]string `json:"expanded_config" yaml:"expanded_config"` ExpandedDevices map[string]map[string]string `json:"expanded_devices" yaml:"expanded_devices"` LastUsedDate time.Time `json:"last_used_at" yaml:"last_used_at"` Name string `json:"name" yaml:"name"` Profiles []string `json:"profiles" yaml:"profiles"` Stateful bool `json:"stateful" yaml:"stateful"` } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/container_exec.go�������������������������������������������������������������0000644�0610621�0607500�00000001625�13172163242�021031� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // ContainerExecControl represents a message on the container exec "control" socket type ContainerExecControl struct { Command string `json:"command" yaml:"command"` Args map[string]string `json:"args" yaml:"args"` Signal int `json:"signal" yaml:"signal"` } // ContainerExecPost represents a LXD container exec request type ContainerExecPost struct { Command []string `json:"command" yaml:"command"` WaitForWS bool `json:"wait-for-websocket" yaml:"wait-for-websocket"` Interactive bool `json:"interactive" yaml:"interactive"` Environment map[string]string `json:"environment" yaml:"environment"` Width int `json:"width" yaml:"width"` Height int `json:"height" yaml:"height"` // API extension: container_exec_recording RecordOutput bool `json:"record-output" yaml:"record-output"` } �����������������������������������������������������������������������������������������������������������lxd-2.0.11/shared/api/container.go������������������������������������������������������������������0000644�0610621�0607500�00000010707�13172163242�020026� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api import ( "time" ) // ContainersPost represents the fields available for a new LXD container type ContainersPost struct { ContainerPut `yaml:",inline"` Name string `json:"name" yaml:"name"` Source ContainerSource `json:"source" yaml:"source"` InstanceType string `json:"instance_type" yaml:"instance_type"` } // ContainerPost represents the fields required to rename/move a LXD container type ContainerPost struct { // Used for renames Name string `json:"name" yaml:"name"` // Used for migration Migration bool `json:"migration" yaml:"migration"` // API extension: container_stateless_copy Live bool `json:"live" yaml:"live"` // API extension: container_only_migration ContainerOnly bool `json:"container_only" yaml:"container_only"` // API extension: container_push_target Target *ContainerPostTarget `json:"target" yaml:"target"` } // ContainerPostTarget represents the migration target host and operation // // API extension: container_push_target type ContainerPostTarget struct { Certificate string `json:"certificate" yaml:"certificate"` Operation string `json:"operation,omitempty" yaml:"operation,omitempty"` Websockets map[string]string `json:"secrets,omitempty" yaml:"secrets,omitempty"` } // ContainerPut represents the modifiable fields of a LXD container type ContainerPut struct { Architecture string `json:"architecture" yaml:"architecture"` Config map[string]string `json:"config" yaml:"config"` Devices map[string]map[string]string `json:"devices" yaml:"devices"` Ephemeral bool `json:"ephemeral" yaml:"ephemeral"` Profiles []string `json:"profiles" yaml:"profiles"` // For snapshot restore Restore string `json:"restore,omitempty" yaml:"restore,omitempty"` Stateful bool `json:"stateful" yaml:"stateful"` // API extension: entity_description Description string `json:"description" yaml:"description"` } // Container represents a LXD container type Container struct { ContainerPut `yaml:",inline"` CreatedAt time.Time `json:"created_at" yaml:"created_at"` ExpandedConfig map[string]string `json:"expanded_config" yaml:"expanded_config"` ExpandedDevices map[string]map[string]string `json:"expanded_devices" yaml:"expanded_devices"` Name string `json:"name" yaml:"name"` Status string `json:"status" yaml:"status"` StatusCode StatusCode `json:"status_code" yaml:"status_code"` // API extension: container_last_used_at LastUsedAt time.Time `json:"last_used_at" yaml:"last_used_at"` } // Writable converts a full Container struct into a ContainerPut struct (filters read-only fields) func (c *Container) Writable() ContainerPut { return c.ContainerPut } // IsActive checks whether the container state indicates the container is active func (c Container) IsActive() bool { switch c.StatusCode { case Stopped: return false case Error: return false default: return true } } // ContainerSource represents the creation source for a new container type ContainerSource struct { Type string `json:"type" yaml:"type"` Certificate string `json:"certificate" yaml:"certificate"` // For "image" type Alias string `json:"alias,omitempty" yaml:"alias,omitempty"` Fingerprint string `json:"fingerprint,omitempty" yaml:"fingerprint,omitempty"` Properties map[string]string `json:"properties,omitempty" yaml:"properties,omitempty"` Server string `json:"server,omitempty" yaml:"server,omitempty"` Secret string `json:"secret,omitempty" yaml:"secret,omitempty"` Protocol string `json:"protocol,omitempty" yaml:"protocol,omitempty"` // For "migration" and "copy" types BaseImage string `json:"base-image,omitempty" yaml:"base-image,omitempty"` // For "migration" type Mode string `json:"mode,omitempty" yaml:"mode,omitempty"` Operation string `json:"operation,omitempty" yaml:"operation,omitempty"` Websockets map[string]string `json:"secrets,omitempty" yaml:"secrets,omitempty"` // For "copy" type Source string `json:"source,omitempty" yaml:"source,omitempty"` // API extension: container_push Live bool `json:"live,omitempty" yaml:"live,omitempty"` // API extension: container_only_migration ContainerOnly bool `json:"container_only,omitempty" yaml:"container_only,omitempty"` } ���������������������������������������������������������lxd-2.0.11/shared/api/certificate.go����������������������������������������������������������������0000644�0610621�0607500�00000001601�13172163242�020317� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package api // CertificatesPost represents the fields of a new LXD certificate type CertificatesPost struct { CertificatePut `yaml:",inline"` Certificate string `json:"certificate" yaml:"certificate"` Password string `json:"password" yaml:"password"` } // CertificatePut represents the modifiable fields of a LXD certificate // // API extension: certificate_update type CertificatePut struct { Name string `json:"name" yaml:"name"` Type string `json:"type" yaml:"type"` } // Certificate represents a LXD certificate type Certificate struct { CertificatePut `yaml:",inline"` Certificate string `json:"certificate" yaml:"certificate"` Fingerprint string `json:"fingerprint" yaml:"fingerprint"` } // Writable converts a full Certificate struct into a CertificatePut struct (filters read-only fields) func (cert *Certificate) Writable() CertificatePut { return cert.CertificatePut } �������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/scripts/���������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015160� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/scripts/vagrant/�������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016622� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/scripts/vagrant/install-lxd.sh�����������������������������������������������������������0000644�0610621�0607500�00000001426�13172163242�021414� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash set -xe export DEBIAN_FRONTEND=noninteractive # install runtime dependencies sudo apt-get -y install xz-utils tar acl curl gettext \ jq sqlite3 # install build dependencies sudo apt-get -y install lxc lxc-dev mercurial git pkg-config \ protobuf-compiler golang-goprotobuf-dev squashfs-tools # setup env [ -e uid_gid_setup ] || \ echo "root:1000000:65536" | sudo tee -a /etc/subuid /etc/subgid && \ touch uid_gid_setup go get github.com/lxc/lxd cd $GOPATH/src/github.com/lxc/lxd go get -v -d ./... make cat << 'EOF' | sudo tee /etc/init/lxd.conf description "LXD daemon" author "John Brooker" start on filesystem or runlevel [2345] stop on shutdown script exec /home/vagrant/go/bin/lxd --group vagrant end script EOF sudo service lxd start ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/scripts/vagrant/install-go.sh������������������������������������������������������������0000644�0610621�0607500�00000000651�13172163242�021231� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash set -xe export DEBIAN_FRONTEND=noninteractive which add-apt-repository || (sudo apt-get update ; sudo apt-get install -y software-properties-common) sudo add-apt-repository ppa:ubuntu-lxc/lxd-git-master sudo apt-get update which go || sudo apt-get install -y golang [ -e $HOME/go ] || mkdir -p $HOME/go cat << 'EOF' | sudo tee /etc/profile.d/S99go.sh export GOPATH=$HOME/go export PATH=$PATH:$GOPATH/bin EOF ���������������������������������������������������������������������������������������lxd-2.0.11/scripts/lxd-setup-lvm-storage������������������������������������������������������������0000755�0610621�0607500�00000016731�13172163242�021301� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 # Let's stick to core python3 modules import argparse import gettext import http.client import json import os import socket from subprocess import check_output import sys DEFAULT_VGNAME = "LXDStorage" _ = gettext.gettext gettext.textdomain("lxd") class FriendlyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) class UnixHTTPConnection(http.client.HTTPConnection): def __init__(self, path): http.client.HTTPConnection.__init__(self, 'localhost') self.path = path def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(self.path) self.sock = sock class LXD(object): def __init__(self, path): self.lxd = UnixHTTPConnection(path) def rest_call(self, path, data=None, method="GET", headers={}): if method == "GET" and data: self.lxd.request( method, "%s?%s" % "&".join(["%s=%s" % (key, value) for key, value in data.items()]), headers) else: self.lxd.request(method, path, data, headers) r = self.lxd.getresponse() d = json.loads(r.read().decode("utf-8")) return r.status, d def set_lvm_vgname(self, vgname): self._set_lvm_config("storage.lvm_vg_name", vgname) def set_lvm_poolname(self, poolname): self._set_lvm_config("storage.lvm_thinpool_name", poolname) def _set_lvm_config(self, key, val): data = json.dumps({"config": {key: val}}) status, data = self.rest_call("/1.0", data, "PUT") if status != 200: sys.stderr.write("Error in setting vgname:{}\n{}\n".format(status, data)) raise Exception("Failed to set vgname: %s" % val) def get_server_config(self): status, config = self.rest_call("/1.0", "", "GET") if status != 200: sys.stderr.write("Error in getting vgname\n") raise Exception("Failed to get vgname") return config["metadata"]["config"] def lxd_dir(): if "LXD_DIR" in os.environ: return os.environ["LXD_DIR"] else: return "/var/lib/lxd" def connect_to_socket(): lxd_socket = os.path.join(lxd_dir(), "unix.socket") if not os.path.exists(lxd_socket): print(_("LXD isn't running.")) sys.exit(1) return LXD(lxd_socket) def create_image(args): imgfname = os.path.join(lxd_dir(), "{}.img".format(args.size)) rollbacks = [] try: print("Creating sparse backing file {}".format(imgfname), flush=True) check_output("truncate -s {} {}".format(args.size, imgfname), shell=True) rollbacks.append("rm {}".format(imgfname)) print("Setting up loop device", flush=True) pvloopdev = check_output("losetup -f", shell=True).decode().strip() check_output("losetup {} {}".format(pvloopdev, imgfname), shell=True) rollbacks.append("losetup -d " + pvloopdev) print("Creating LVM PV {}".format(pvloopdev), flush=True) check_output("pvcreate {}".format(pvloopdev), shell=True) rollbacks.append("pvremove " + pvloopdev) print("Creating LVM VG {}".format(DEFAULT_VGNAME), flush=True) check_output("vgcreate {} {}".format(DEFAULT_VGNAME, pvloopdev), shell=True) rollbacks.append("vgremove {}".format(DEFAULT_VGNAME)) except Exception as e: sys.stderr.write("Error: {}. Cleaning up:\n".format(e)) for rbcmd in reversed(rollbacks): sys.stderr.write("+ {}\n".format(rbcmd)) check_output(rbcmd, shell=True) raise e def destroy_image(args, lxd): print("Checking current LXD configuration", flush=True) cfg = lxd.get_server_config() vgname = cfg.get("storage.lvm_vg_name", None) if vgname is None: sys.stderr.write("LXD is not configured for LVM. " "No changes will be made.\n") return lvnames = check_output("lvs {} -o name,lv_attr --noheadings" .format(vgname), shell=True).decode().strip() used_lvs = [] for lvline in lvnames.split("\n"): if lvline == '': continue name, attrs = lvline.split() if attrs.strip().startswith("V"): used_lvs.append(name) if len(used_lvs) > 0: print("LVM storage is still in use by the following volumes: {}" .format(used_lvs)) print("Please delete the corresponding images and/or " "containers before destroying storage.") sys.exit() pvname = check_output("vgs {} --noheadings -o pv_name" .format(vgname), shell=True).decode().strip() print("Removing volume group {}".format(vgname)) check_output("vgremove -f {}".format(vgname), shell=True) print("Removing physical volume {}".format(pvname)) check_output("pvremove -y {}".format(pvname), shell=True) lostr = check_output("losetup -a | grep {}".format(pvname), shell=True).decode().strip() imgfname = lostr.split('(')[-1].replace(')', '') print("Detaching loop device {}".format(pvname)) check_output("losetup -d {}".format(pvname), shell=True) print("Deleting backing file {}".format(imgfname)) if os.path.exists(imgfname): check_output("rm '{}'".format(imgfname), shell=True) def do_main(): parser = FriendlyParser( description=_("LXD: LVM storage helper"), formatter_class=argparse.RawTextHelpFormatter, epilog=_("""Examples: To create a 10G sparse loopback file and register it with LVM and LXD: %s -s 10G To de-configure LXD and destroy the LVM volumes and backing file: %s --destroy """ % (sys.argv[0], sys.argv[0]))) parser.add_argument("-s", "--size", default="10G", help=_("Size of backing file to register as LVM PV")) parser.add_argument("--destroy", action="store_true", default=False, help=_("Un-configure LXD and delete image file")) args = parser.parse_args() if os.geteuid() != 0: sys.exit("Configuring LVM requires root privileges.") try: check_output("type vgcreate", shell=True) except: sys.exit("lvm2 tools not found. try 'apt-get install lvm2 " "thin-provisioning-tools'") try: check_output("type thin_check", shell=True) except: sys.exit("lvm thin provisioning tools are required. " "try 'apt-get install thin-provisioning-tools'") lxd = connect_to_socket() if args.destroy: try: destroy_image(args, lxd) print("Clearing LXD storage configuration") lxd.set_lvm_vgname("") lxd.set_lvm_poolname("") except Exception as e: sys.stderr.write("Error destroying image:") sys.stderr.write(str(e)) sys.stderr.write("\n") else: try: create_image(args) except: sys.stderr.write("Stopping.\n") else: try: print("Configuring LXD") lxd.set_lvm_vgname(DEFAULT_VGNAME) except: sys.stderr.write("Error configuring LXD, " "removing backing file\n") destroy_image(args, lxd) print("Done.") if __name__ == "__main__": do_main() ���������������������������������������lxd-2.0.11/scripts/lxc-to-lxd�����������������������������������������������������������������������0000755�0610621�0607500�00000046713�13172163242�017114� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 import argparse import http.client import json import os import socket import subprocess import sys try: import lxc except ImportError: print("You must have python3-lxc installed for this script to work.") sys.exit(1) # Whitelist of keys we either need to check or allow setting in LXD. The latter # is strictly only true for 'lxc.aa_profile'. keys_to_check = [ 'lxc.pts', # 'lxc.tty', # 'lxc.devttydir', # 'lxc.kmsg', 'lxc.aa_profile', # 'lxc.cgroup.', 'lxc.loglevel', # 'lxc.logfile', 'lxc.mount.auto', 'lxc.mount', # 'lxc.rootfs.mount', # 'lxc.rootfs.options', # 'lxc.pivotdir', # 'lxc.hook.pre-start', # 'lxc.hook.pre-mount', # 'lxc.hook.mount', # 'lxc.hook.autodev', # 'lxc.hook.start', # 'lxc.hook.stop', # 'lxc.hook.post-stop', # 'lxc.hook.clone', # 'lxc.hook.destroy', # 'lxc.hook', 'lxc.network.type', 'lxc.network.flags', 'lxc.network.link', 'lxc.network.name', 'lxc.network.macvlan.mode', 'lxc.network.veth.pair', # 'lxc.network.script.up', # 'lxc.network.script.down', 'lxc.network.hwaddr', 'lxc.network.mtu', # 'lxc.network.vlan.id', # 'lxc.network.ipv4.gateway', # 'lxc.network.ipv4', # 'lxc.network.ipv6.gateway', # 'lxc.network.ipv6', # 'lxc.network.', # 'lxc.network', # 'lxc.console.logfile', # 'lxc.console', 'lxc.include', 'lxc.start.auto', 'lxc.start.delay', 'lxc.start.order', # 'lxc.monitor.unshare', # 'lxc.group', 'lxc.environment', # 'lxc.init_cmd', # 'lxc.init_uid', # 'lxc.init_gid', # 'lxc.ephemeral', # 'lxc.syslog', # 'lxc.no_new_privs', # Additional keys that are either set by this script or are used to report # helpful errors to users. 'lxc.arch', 'lxc.id_map', 'lxd.migrated', 'lxc.rootfs.backend', 'lxc.rootfs', 'lxc.utsname', 'lxc.aa_allow_incomplete', 'lxc.autodev', 'lxc.haltsignal', 'lxc.rebootsignal', 'lxc.stopsignal', 'lxc.mount.entry', 'lxc.cap.drop', # 'lxc.cap.keep', 'lxc.seccomp', # 'lxc.se_context', ] # Unix connection to LXD class UnixHTTPConnection(http.client.HTTPConnection): def __init__(self, path): http.client.HTTPConnection.__init__(self, 'localhost') self.path = path def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(self.path) self.sock = sock # Fetch a config key as a list def config_get(config, key, default=None): result = [] for line in config: fields = line.split("=", 1) if fields[0].strip() == key: result.append(fields[-1].strip()) if len(result) == 0: return default else: return result def config_keys(config): keys = [] for line in config: fields = line.split("=", 1) cur = fields[0].strip() if cur and not cur.startswith("#") and cur.startswith("lxc."): keys.append(cur) return keys # Parse a LXC configuration file, called recursively for includes def config_parse(path): config = [] with open(path, "r") as fd: for line in fd: line = line.strip() key = line.split("=", 1)[0].strip() value = line.split("=", 1)[-1].strip() # Parse user-added includes if key == "lxc.include": # Ignore our own default configs if value.startswith("/usr/share/lxc/config/"): continue if os.path.isfile(value): config += config_parse(value) continue elif os.path.isdir(value): for entry in os.listdir(value): if not entry.endswith(".conf"): continue config += config_parse(os.path.join(value, entry)) continue else: print("Invalid include: %s", line) # Expand any fstab if key == "lxc.mount": if not os.path.exists(value): print("Container fstab file doesn't exist, skipping...") continue with open(value, "r") as fd: for line in fd: line = line.strip() if (line and not line.startswith("#") and line.startswith("lxc.")): config.append("lxc.mount.entry = %s" % line) continue # Proces normal configuration keys if line and not line.strip().startswith("#"): config.append(line) return config def container_exists(lxd_socket, container_name): lxd = UnixHTTPConnection(lxd_socket) lxd.request("GET", "/1.0/containers/%s" % container_name) if lxd.getresponse().status == 404: return False return True def container_create(lxd_socket, args): # Define the container lxd = UnixHTTPConnection(lxd_socket) lxd.request("POST", "/1.0/containers", json.dumps(args)) r = lxd.getresponse() # Decode the response resp = json.loads(r.read().decode()) if resp["type"] == "error": raise Exception("Failed to define container: %s" % resp["error"]) # Wait for result lxd = UnixHTTPConnection(lxd_socket) lxd.request("GET", "%s/wait" % resp["operation"]) r = lxd.getresponse() # Decode the response resp = json.loads(r.read().decode()) if resp["type"] == "error": raise Exception("Failed to define container: %s" % resp["error"]) # Convert a LXC container to a LXD one def convert_container(lxd_socket, container_name, args): print("==> Processing container: %s" % container_name) # Load the container try: container = lxc.Container(container_name, args.lxcpath) except Exception: print("Invalid container configuration, skipping...") return False # As some keys can't be queried over the API, parse the config ourselves print("Parsing LXC configuration") lxc_config = config_parse(container.config_file_name) found_keys = config_keys(lxc_config) # Generic check for any invalid LXC configuration keys. print("Checking for unsupported LXC configuration keys") diff = list(set(found_keys) - set(keys_to_check)) for d in diff: if (not d.startswith('lxc.network.') and not d.startswith('lxc.cgroup.')): print("Found at least one unsupported config key %s: " % d) print("Not importing this container, skipping...") return False if args.debug: print("Container configuration:") print(" ", end="") print("\n ".join(lxc_config)) print("") # Check for keys that have values differing from the LXD defaults. print("Checking whether container has already been migrated") if config_get(lxc_config, "lxd.migrated"): print("Container has already been migrated, skipping...") return False # Make sure we don't have a conflict print("Checking for existing containers") if container_exists(lxd_socket, container_name): print("Container already exists, skipping...") return False # Validating lxc.id_map: must be unset. print("Validating container mode") if config_get(lxc_config, "lxc.id_map"): print("Unprivileged containers aren't supported, skipping...") return False # Validate lxc.utsname print("Validating container name") value = config_get(lxc_config, "lxc.utsname") if value and value[0] != container_name: print("Container name doesn't match lxc.utsname, skipping...") return False # Validate lxc.aa_allow_incomplete: must be set to 0 or unset. print("Validating whether incomplete AppArmor support is enabled") value = config_get(lxc_config, "lxc.aa_allow_incomplete") if value and int(value[0]) != 0: print("Container allows incomplete AppArmor support, skipping...") return False # Validate lxc.autodev: must be set to 1 or unset. print("Validating whether mounting a minimal /dev is enabled") value = config_get(lxc_config, "lxc.autodev") if value and int(value[0]) != 1: print("Container doesn't mount a minimal /dev filesystem, skipping...") return False # Validate lxc.haltsignal: must be unset. print("Validating that no custom haltsignal is set") value = config_get(lxc_config, "lxc.haltsignal") if value: print("Container sets custom halt signal, skipping...") return False # Validate lxc.rebootsignal: must be unset. print("Validating that no custom rebootsignal is set") value = config_get(lxc_config, "lxc.rebootsignal") if value: print("Container sets custom reboot signal, skipping...") return False # Validate lxc.stopsignal: must be unset. print("Validating that no custom stopsignal is set") value = config_get(lxc_config, "lxc.stopsignal") if value: print("Container sets custom stop signal, skipping...") return False # Extract and valid rootfs key print("Validating container rootfs") value = config_get(lxc_config, "lxc.rootfs") if not value: print("Invalid container, missing lxc.rootfs key, skipping...") return False rootfs = value[0] if not os.path.exists(rootfs): print("Couldn't find the container rootfs '%s', skipping..." % rootfs) return False # Base config config = {} config['security.privileged'] = "true" devices = {} devices['eth0'] = {'type': "none"} # Convert network configuration print("Processing network configuration") try: count = len(container.get_config_item("lxc.network")) except Exception: count = 0 for i in range(count): device = {"type": "nic"} # Get the device type device["nictype"] = container.get_config_item("lxc.network")[i] # Get everything else dev = container.network[i] # Validate configuration if dev.ipv4 or dev.ipv4_gateway: print("IPv4 network configuration isn't supported, skipping...") return False if dev.ipv6 or dev.ipv6_gateway: print("IPv6 network configuration isn't supported, skipping...") return False if dev.script_up or dev.script_down: print("Network config scripts aren't supported, skipping...") return False if device["nictype"] == "none": print("\"none\" network mode isn't supported, skipping...") return False if device["nictype"] == "vlan": print("\"vlan\" network mode isn't supported, skipping...") return False # Convert the configuration if dev.hwaddr: device['hwaddr'] = dev.hwaddr if dev.link: device['parent'] = dev.link if dev.mtu: device['mtu'] = dev.mtu if dev.name: device['name'] = dev.name if dev.veth_pair: device['host_name'] = dev.veth_pair if device["nictype"] == "veth": if "parent" in device: device["nictype"] = "bridged" else: device["nictype"] = "p2p" if device["nictype"] == "phys": device["nictype"] = "physical" if device["nictype"] == "empty": continue devices['convert_net%d' % i] = device count += 1 # Convert storage configuration value = config_get(lxc_config, "lxc.mount.entry", []) i = 0 for entry in value: mount = entry.split(" ") if len(mount) < 4: print("Invalid mount configuration, skipping...") return False # Ignore mounts that are present in LXD containers by default. if mount[0] in ("proc", "sysfs"): continue device = {'type': "disk"} # Deal with read-only mounts if "ro" in mount[3].split(","): device['readonly'] = "true" # Deal with optional mounts if "optional" in mount[3].split(","): device['optional'] = "true" elif not os.path.exists(mount[0]): print("Invalid mount configuration, source path doesn't exist.") return False # Set the source device['source'] = mount[0] # Figure out the target if mount[1][0] != "/": device['path'] = "/%s" % mount[1] else: device['path'] = mount[1].split(rootfs, 1)[-1] devices['convert_mount%d' % i] = device i += 1 # Convert environment print("Processing environment configuration") value = config_get(lxc_config, "lxc.environment", []) for env in value: entry = env.split("=", 1) config['environment.%s' % entry[0].strip()] = entry[-1].strip() # Convert auto-start print("Processing container boot configuration") value = config_get(lxc_config, "lxc.start.auto") if value and int(value[0]) > 0: config['boot.autostart'] = "true" value = config_get(lxc_config, "lxc.start.delay") if value and int(value[0]) > 0: config['boot.autostart.delay'] = value[0] value = config_get(lxc_config, "lxc.start.order") if value and int(value[0]) > 0: config['boot.autostart.priority'] = value[0] # Convert apparmor print("Processing container apparmor configuration") value = config_get(lxc_config, "lxc.aa_profile") if value: if value[0] == "lxc-container-default-with-nesting": config['security.nesting'] = "true" elif value[0] != "lxc-container-default": config["raw.lxc"] = "lxc.aa_profile=%s" % value[0] # Convert seccomp print("Processing container seccomp configuration") value = config_get(lxc_config, "lxc.seccomp") if value and value[0] != "/usr/share/lxc/config/common.seccomp": print("Custom seccomp profiles aren't supported, skipping...") return False # Convert SELinux print("Processing container SELinux configuration") value = config_get(lxc_config, "lxc.se_context") if value: print("Custom SELinux policies aren't supported, skipping...") return False # Convert capabilities print("Processing container capabilities configuration") value = config_get(lxc_config, "lxc.cap.drop") if value: for cap in value: # Ignore capabilities that are dropped in LXD containers by default. if cap in ("mac_admin", "mac_override", "sys_module", "sys_time"): continue print("Custom capabilities aren't supported, skipping...") return False value = config_get(lxc_config, "lxc.cap.keep") if value: print("Custom capabilities aren't supported, skipping...") return False # Setup the container creation request new = {'name': container_name, 'source': {'type': 'none'}, 'config': config, 'devices': devices, 'profiles': ["default"]} # Set the container architecture if set in LXC print("Processing container architecture configuration") arches = {'i686': "i686", 'x86_64': "x86_64", 'armhf': "armv7l", 'arm64': "aarch64", 'powerpc': "ppc", 'powerpc64': "ppc64", 'ppc64el': "ppc64le", 's390x': "s390x"} arch = None try: arch = config_get(lxc_config, "lxc.arch", None) if arch and arch[0] in arches: new['architecture'] = arches[arch[0]] else: print("Unknown architecture, assuming native.") except Exception: print("Couldn't find container architecture, assuming native.") # Define the container in LXD if args.debug: print("LXD container config:") print(json.dumps(new, indent=True, sort_keys=True)) if args.dry_run: return True if container.running: print("Only stopped containers can be migrated, skipping...") return False try: print("Creating the container") container_create(lxd_socket, new) except Exception as e: raise print("Failed to create the container: %s" % e) return False # Transfer the filesystem lxd_rootfs = os.path.join(args.lxdpath, "containers", container_name, "rootfs") if args.move_rootfs: if os.path.exists(lxd_rootfs): os.rmdir(lxd_rootfs) if subprocess.call(["mv", rootfs, lxd_rootfs]) != 0: print("Failed to move the container rootfs, skipping...") return False os.mkdir(rootfs) else: print("Copying container rootfs") if not os.path.exists(lxd_rootfs): os.mkdir(lxd_rootfs) if subprocess.call(["rsync", "-Aa", "--sparse", "--acls", "--numeric-ids", "--hard-links", "%s/" % rootfs, "%s/" % lxd_rootfs]) != 0: print("Failed to transfer the container rootfs, skipping...") return False # Delete the source if args.delete: print("Deleting source container") container.delete() # Mark the container as migrated with open(container.config_file_name, "a") as fd: fd.write("lxd.migrated=true\n") print("Container is ready to use") return True # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("--dry-run", action="store_true", default=False, help="Dry run mode") parser.add_argument("--debug", action="store_true", default=False, help="Print debugging output") parser.add_argument("--all", action="store_true", default=False, help="Import all containers") parser.add_argument("--delete", action="store_true", default=False, help="Delete the source container") parser.add_argument("--move-rootfs", action="store_true", default=False, help="Move the container rootfs rather than copying it") parser.add_argument("--lxcpath", type=str, default=False, help="Alternate LXC path") parser.add_argument("--lxdpath", type=str, default="/var/lib/lxd", help="Alternate LXD path") parser.add_argument(dest='containers', metavar="CONTAINER", type=str, help="Container to import", nargs="*") args = parser.parse_args() # Sanity checks if not os.geteuid() == 0: parser.error("You must be root to run this tool") if (not args.containers and not args.all) or (args.containers and args.all): parser.error("You must either pass container names or --all") # Connect to LXD lxd_socket = os.path.join(args.lxdpath, "unix.socket") if not os.path.exists(lxd_socket): print("LXD isn't running.") sys.exit(1) # Run migration results = {} count = 0 for container_name in lxc.list_containers(config_path=args.lxcpath): if args.containers and container_name not in args.containers: continue if count > 0: print("") results[container_name] = convert_container(lxd_socket, container_name, args) count += 1 # Print summary if not results: print("No container to migrate") sys.exit(0) print("") print("==> Migration summary") for name, result in results.items(): if result: print("%s: SUCCESS" % name) else: print("%s: FAILURE" % name) if False in results.values(): sys.exit(1) �����������������������������������������������������lxd-2.0.11/po/��������������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014107� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/po/lxd.pot�������������������������������������������������������������������������������0000644�0610621�0607500�00000111077�13172163242�015431� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "Project-Id-Version: lxd\n" "Report-Msgid-Bugs-To: lxc-devel@lists.linuxcontainers.org\n" "POT-Creation-Date: 2017-10-03 23:36-0400\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: lxc/config.go:39 msgid "### This is a yaml representation of the configuration.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### A sample configuration looks like:\n" "### name: container1\n" "### profiles:\n" "### - default\n" "### config:\n" "### volatile.eth0.hwaddr: 00:16:3e:e9:f8:7f\n" "### devices:\n" "### homedir:\n" "### path: /extra\n" "### source: /home/user\n" "### type: disk\n" "### ephemeral: false\n" "###\n" "### Note that the name is shown but cannot be changed" msgstr "" #: lxc/image.go:53 msgid "### This is a yaml representation of the image properties.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### Each property is represented by a single line:\n" "### An example would be:\n" "### description: My custom image" msgstr "" #: lxc/profile.go:28 msgid "### This is a yaml representation of the profile.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### A profile consists of a set of configuration items followed by a set of\n" "### devices.\n" "###\n" "### An example would look like:\n" "### name: onenic\n" "### config:\n" "### raw.lxc: lxc.aa_profile=unconfined\n" "### devices:\n" "### eth0:\n" "### nictype: bridged\n" "### parent: lxdbr0\n" "### type: nic\n" "###\n" "### Note that the name is shown but cannot be changed" msgstr "" #: lxc/image.go:851 #, c-format msgid "%s (%d more)" msgstr "" #: lxc/utils.go:324 #, c-format msgid "%v (interrupt two more times to force)" msgstr "" #: lxc/snapshot.go:53 msgid "'/' not allowed in snapshot name" msgstr "" #: lxc/profile.go:289 msgid "(none)" msgstr "" #: lxc/image.go:872 lxc/image.go:901 msgid "ALIAS" msgstr "" #: lxc/image.go:876 msgid "ARCH" msgstr "" #: lxc/list.go:414 msgid "ARCHITECTURE" msgstr "" #: lxc/remote.go:67 msgid "Accept certificate" msgstr "" #: lxc/remote.go:245 #, c-format msgid "Admin password for %s: " msgstr "" #: lxc/image.go:435 msgid "Aliases:" msgstr "" #: lxc/image.go:413 lxc/info.go:104 #, c-format msgid "Architecture: %s" msgstr "" #: lxc/image.go:444 #, c-format msgid "Auto update: %s" msgstr "" #: lxc/image.go:518 #, c-format msgid "Bad property: %s" msgstr "" #: lxc/info.go:186 msgid "Bytes received" msgstr "" #: lxc/info.go:187 msgid "Bytes sent" msgstr "" #: lxc/config.go:349 msgid "COMMON NAME" msgstr "" #: lxc/list.go:415 msgid "CREATED AT" msgstr "" #: lxc/image.go:443 #, c-format msgid "Cached: %s" msgstr "" #: lxc/config.go:156 #, c-format msgid "Can't read from stdin: %s" msgstr "" #: lxc/config.go:169 #, c-format msgid "Can't unset key '%s', it's not currently set" msgstr "" #: lxc/config.go:211 lxc/config.go:237 #, c-format msgid "Can't unset key '%s', it's not currently set." msgstr "" #: lxc/profile.go:441 msgid "Cannot provide container name to list" msgstr "" #: lxc/remote.go:181 #, c-format msgid "Certificate fingerprint: %s" msgstr "" #: lxc/remote.go:280 msgid "Client certificate stored at server: " msgstr "" #: lxc/list.go:109 lxc/list.go:110 msgid "Columns" msgstr "" #: lxc/help.go:53 msgid "Commands:" msgstr "" #: lxc/init.go:135 lxc/init.go:136 msgid "Config key/value to apply to the new container" msgstr "" #: lxc/config.go:647 lxc/config.go:712 lxc/image.go:956 lxc/profile.go:237 #, c-format msgid "Config parsing error: %s" msgstr "" #: lxc/main.go:36 msgid "Connection refused; is LXD running?" msgstr "" #: lxc/publish.go:69 msgid "Container name is mandatory" msgstr "" #: lxc/copy.go:186 lxc/init.go:282 #, c-format msgid "Container name is: %s" msgstr "" #: lxc/publish.go:247 #, c-format msgid "Container published with fingerprint: %s" msgstr "" #: lxc/image.go:135 msgid "Copy aliases from source" msgstr "" #: lxc/image.go:313 #, c-format msgid "Copying the image: %s" msgstr "" #: lxc/remote.go:196 msgid "Could not create server cert dir" msgstr "" #: lxc/image.go:418 lxc/info.go:106 #, c-format msgid "Created: %s" msgstr "" #: lxc/init.go:190 #, c-format msgid "Creating %s" msgstr "" #: lxc/init.go:188 msgid "Creating the container" msgstr "" #: lxc/image.go:875 lxc/image.go:903 msgid "DESCRIPTION" msgstr "" #: lxc/config.go:803 #, c-format msgid "Device %s added to %s" msgstr "" #: lxc/config.go:1039 #, c-format msgid "Device %s removed from %s" msgstr "" #: lxc/info.go:154 msgid "Disk usage:" msgstr "" #: lxc/list.go:505 msgid "EPHEMERAL" msgstr "" #: lxc/config.go:351 msgid "EXPIRY DATE" msgstr "" #: lxc/main.go:48 msgid "Enable debug mode" msgstr "" #: lxc/main.go:47 msgid "Enable verbose mode" msgstr "" #: lxc/exec.go:56 msgid "Environment variable to set (e.g. HOME=/home/foo)" msgstr "" #: lxc/help.go:77 msgid "Environment:" msgstr "" #: lxc/copy.go:30 lxc/copy.go:31 lxc/init.go:139 lxc/init.go:140 msgid "Ephemeral container" msgstr "" #: lxc/monitor.go:56 msgid "Event type to listen for" msgstr "" #: lxc/image.go:422 #, c-format msgid "Expires: %s" msgstr "" #: lxc/image.go:424 msgid "Expires: never" msgstr "" #: lxc/image.go:710 #, c-format msgid "Exporting the image: %s" msgstr "" #: lxc/config.go:348 lxc/image.go:873 lxc/image.go:902 msgid "FINGERPRINT" msgstr "" #: lxc/utils.go:362 #, c-format msgid "Failed to create alias %s" msgstr "" #: lxc/manpage.go:62 #, c-format msgid "Failed to generate 'lxc.%s.1': %v" msgstr "" #: lxc/manpage.go:55 #, c-format msgid "Failed to generate 'lxc.1': %v" msgstr "" #: lxc/copy.go:181 msgid "Failed to get the new container name" msgstr "" #: lxc/utils.go:352 #, c-format msgid "Failed to remove alias %s" msgstr "" #: lxc/list.go:112 msgid "Fast mode (same as --columns=nsacPt)" msgstr "" #: lxc/image.go:411 #, c-format msgid "Fingerprint: %s" msgstr "" #: lxc/action.go:46 lxc/action.go:47 msgid "Force the container to shutdown" msgstr "" #: lxc/delete.go:34 lxc/delete.go:35 msgid "Force the removal of running containers" msgstr "" #: lxc/main.go:49 msgid "Force using the local unix socket" msgstr "" #: lxc/list.go:111 msgid "Format (table|json)" msgstr "" #: lxc/main.go:149 msgid "Generating a client certificate. This may take a minute..." msgstr "" #: lxc/list.go:412 msgid "IPV4" msgstr "" #: lxc/list.go:413 msgid "IPV6" msgstr "" #: lxc/config.go:350 msgid "ISSUE DATE" msgstr "" #: lxc/main.go:157 msgid "If this is your first time using LXD, you should also run: sudo lxd init" msgstr "" #: lxc/main.go:50 msgid "Ignore aliases when determining what command to run" msgstr "" #: lxc/action.go:50 msgid "Ignore the container state (only for start)" msgstr "" #: lxc/image.go:327 msgid "Image copied successfully!" msgstr "" #: lxc/image.go:770 msgid "Image exported successfully!" msgstr "" #: lxc/image.go:580 #, c-format msgid "Image imported with fingerprint: %s" msgstr "" #: lxc/init.go:141 msgid "Instance type" msgstr "" #: lxc/remote.go:107 #, c-format msgid "Invalid URL scheme \"%s\" in \"%s\"" msgstr "" #: lxc/config.go:329 msgid "Invalid certificate" msgstr "" #: lxc/init.go:31 lxc/init.go:36 msgid "Invalid configuration key" msgstr "" #: lxc/file.go:219 #, c-format msgid "Invalid source %s" msgstr "" #: lxc/file.go:70 #, c-format msgid "Invalid target %s" msgstr "" #: lxc/info.go:135 msgid "Ips:" msgstr "" #: lxc/image.go:136 msgid "Keep the image up to date after initial copy" msgstr "" #: lxc/main.go:34 msgid "LXD socket not found; is LXD installed and running?" msgstr "" #: lxc/image.go:427 #, c-format msgid "Last used: %s" msgstr "" #: lxc/image.go:429 msgid "Last used: never" msgstr "" #: lxc/info.go:239 msgid "Log:" msgstr "" #: lxc/image.go:134 msgid "Make image public" msgstr "" #: lxc/publish.go:34 msgid "Make the image public" msgstr "" #: lxc/info.go:161 msgid "Memory (current)" msgstr "" #: lxc/info.go:165 msgid "Memory (peak)" msgstr "" #: lxc/info.go:177 msgid "Memory usage:" msgstr "" #: lxc/utils.go:256 msgid "Missing summary." msgstr "" #: lxc/file.go:207 msgid "More than one file to download, but target is not a directory" msgstr "" #: lxc/action.go:72 msgid "Must supply container name for: " msgstr "" #: lxc/list.go:416 lxc/remote.go:364 msgid "NAME" msgstr "" #: lxc/remote.go:338 lxc/remote.go:343 msgid "NO" msgstr "" #: lxc/info.go:99 #, c-format msgid "Name: %s" msgstr "" #: lxc/info.go:194 msgid "Network usage:" msgstr "" #: lxc/image.go:137 lxc/publish.go:35 msgid "New alias to define at target" msgstr "" #: lxc/config.go:360 msgid "No certificate provided to add" msgstr "" #: lxc/config.go:392 msgid "No fingerprint specified." msgstr "" #: lxc/remote.go:92 msgid "Only https URLs are supported for simplestreams" msgstr "" #: lxc/image.go:499 msgid "Only https:// is supported for remote image import." msgstr "" #: lxc/help.go:71 lxc/main.go:130 lxc/main.go:182 msgid "Options:" msgstr "" #: lxc/exec.go:57 msgid "Override the terminal mode (auto, interactive or non-interactive)" msgstr "" #: lxc/list.go:507 msgid "PERSISTENT" msgstr "" #: lxc/list.go:417 msgid "PID" msgstr "" #: lxc/list.go:418 msgid "PROFILES" msgstr "" #: lxc/remote.go:366 msgid "PROTOCOL" msgstr "" #: lxc/image.go:874 lxc/remote.go:367 msgid "PUBLIC" msgstr "" #: lxc/info.go:188 msgid "Packets received" msgstr "" #: lxc/info.go:189 msgid "Packets sent" msgstr "" #: lxc/help.go:78 msgid "Path to an alternate client configuration directory" msgstr "" #: lxc/help.go:79 msgid "Path to an alternate server directory" msgstr "" #: lxc/main.go:219 msgid "Pause containers." msgstr "" #: lxc/main.go:38 msgid "Permission denied, are you in the lxd group?" msgstr "" #: lxc/info.go:117 #, c-format msgid "Pid: %d" msgstr "" #: lxc/profile.go:238 msgid "Press enter to open the editor again" msgstr "" #: lxc/config.go:648 lxc/config.go:713 lxc/image.go:957 msgid "Press enter to start the editor again" msgstr "" #: lxc/help.go:73 msgid "Print debug information" msgstr "" #: lxc/help.go:72 msgid "Print less common commands" msgstr "" #: lxc/help.go:74 msgid "Print verbose information" msgstr "" #: lxc/info.go:141 #, c-format msgid "Processes: %d" msgstr "" #: lxc/profile.go:188 #, c-format msgid "Profile %s created" msgstr "" #: lxc/profile.go:262 #, c-format msgid "Profile %s deleted" msgstr "" #: lxc/init.go:137 lxc/init.go:138 msgid "Profile to apply to the new container" msgstr "" #: lxc/profile.go:291 #, c-format msgid "Profiles %s applied to %s" msgstr "" #: lxc/info.go:115 #, c-format msgid "Profiles: %s" msgstr "" #: lxc/image.go:431 msgid "Properties:" msgstr "" #: lxc/remote.go:70 msgid "Public image server" msgstr "" #: lxc/image.go:414 #, c-format msgid "Public: %s" msgstr "" #: lxc/remote.go:68 msgid "Remote admin password" msgstr "" #: lxc/utils.go:315 msgid "Remote operation canceled by user" msgstr "" #: lxc/info.go:101 #, c-format msgid "Remote: %s" msgstr "" #: lxc/delete.go:42 #, c-format msgid "Remove %s (yes/no): " msgstr "" #: lxc/delete.go:36 lxc/delete.go:37 msgid "Require user confirmation" msgstr "" #: lxc/info.go:138 msgid "Resources:" msgstr "" #: lxc/main.go:227 msgid "Restart containers." msgstr "" #: lxc/init.go:254 #, c-format msgid "Retrieving image: %s" msgstr "" #: lxc/image.go:877 msgid "SIZE" msgstr "" #: lxc/list.go:419 msgid "SNAPSHOTS" msgstr "" #: lxc/list.go:420 msgid "STATE" msgstr "" #: lxc/remote.go:368 msgid "STATIC" msgstr "" #: lxc/remote.go:189 msgid "Server certificate NACKed by user" msgstr "" #: lxc/remote.go:277 msgid "Server doesn't trust us after adding our cert" msgstr "" #: lxc/remote.go:69 msgid "Server protocol (lxd or simplestreams)" msgstr "" #: lxc/file.go:57 msgid "Set the file's gid on push" msgstr "" #: lxc/file.go:58 msgid "Set the file's perms on push" msgstr "" #: lxc/file.go:56 msgid "Set the file's uid on push" msgstr "" #: lxc/help.go:29 msgid "Show all commands (not just interesting ones)" msgstr "" #: lxc/help.go:75 msgid "Show client version" msgstr "" #: lxc/info.go:39 msgid "Show the container's last 100 log lines?" msgstr "" #: lxc/config.go:35 msgid "Show the expanded configuration" msgstr "" #: lxc/image.go:412 #, c-format msgid "Size: %.2fMB" msgstr "" #: lxc/info.go:208 msgid "Snapshots:" msgstr "" #: lxc/action.go:142 #, c-format msgid "Some containers failed to %s" msgstr "" #: lxc/image.go:446 msgid "Source:" msgstr "" #: lxc/main.go:237 msgid "Start containers." msgstr "" #: lxc/launch.go:59 #, c-format msgid "Starting %s" msgstr "" #: lxc/info.go:109 #, c-format msgid "Status: %s" msgstr "" #: lxc/main.go:243 msgid "Stop containers." msgstr "" #: lxc/publish.go:36 lxc/publish.go:37 msgid "Stop the container if currently running" msgstr "" #: lxc/publish.go:134 msgid "Stopping container failed!" msgstr "" #: lxc/delete.go:121 #, c-format msgid "Stopping the container failed: %s" msgstr "" #: lxc/action.go:49 msgid "Store the container state (only for stop)" msgstr "" #: lxc/info.go:169 msgid "Swap (current)" msgstr "" #: lxc/info.go:173 msgid "Swap (peak)" msgstr "" #: lxc/list.go:421 msgid "TYPE" msgstr "" #: lxc/delete.go:105 msgid "The container is currently running, stop it first or pass --force." msgstr "" #: lxc/publish.go:99 msgid "The container is currently running. Use --force to have it stopped and restarted." msgstr "" #: lxc/config.go:770 lxc/config.go:787 msgid "The device already exists" msgstr "" #: lxc/config.go:833 lxc/config.go:845 lxc/config.go:881 lxc/config.go:899 lxc/config.go:945 lxc/config.go:962 lxc/config.go:1005 lxc/config.go:1023 msgid "The device doesn't exist" msgstr "" #: lxc/init.go:308 #, c-format msgid "The local image '%s' couldn't be found, trying '%s:' instead." msgstr "" #: lxc/action.go:34 msgid "The opposite of \"lxc pause\" is \"lxc start\"." msgstr "" #: lxc/publish.go:72 msgid "There is no \"image name\". Did you want an alias?" msgstr "" #: lxc/help.go:47 msgid "This is the LXD command line client.\n" "\n" "All of LXD's features can be driven through the various commands below.\n" "For help with any of those, simply call them with --help." msgstr "" #: lxc/action.go:45 msgid "Time to wait for the container before killing it" msgstr "" #: lxc/image.go:415 msgid "Timestamps:" msgstr "" #: lxc/main.go:158 msgid "To start your first container, try: lxc launch ubuntu:16.04" msgstr "" #: lxc/copy.go:155 #, c-format msgid "Transferring container: %s" msgstr "" #: lxc/image.go:528 #, c-format msgid "Transferring image: %s" msgstr "" #: lxc/action.go:106 lxc/launch.go:77 #, c-format msgid "Try `lxc info --show-log %s` for more info" msgstr "" #: lxc/info.go:111 msgid "Type: ephemeral" msgstr "" #: lxc/info.go:113 msgid "Type: persistent" msgstr "" #: lxc/image.go:878 msgid "UPLOAD DATE" msgstr "" #: lxc/remote.go:365 msgid "URL" msgstr "" #: lxc/manpage.go:36 msgid "Unable to find help2man." msgstr "" #: lxc/image.go:420 #, c-format msgid "Uploaded: %s" msgstr "" #: lxc/action.go:37 #, c-format msgid "Usage: lxc %s [<remote>:]<container> [[<remote>:]<container>...]\n" "\n" "%s%s" msgstr "" #: lxc/help.go:45 msgid "Usage: lxc <command> [options]" msgstr "" #: lxc/config.go:60 msgid "Usage: lxc config <subcommand> [options]\n" "\n" "Change container or server configuration options.\n" "\n" "*Container configuration*\n" "\n" "lxc config get [<remote>:][container] <key>\n" " Get container or server configuration key.\n" "\n" "lxc config set [<remote>:][container] <key> <value>\n" " Set container or server configuration key.\n" "\n" "lxc config unset [<remote>:][container] <key>\n" " Unset container or server configuration key.\n" "\n" "lxc config show [<remote>:][container] [--expanded]\n" " Show container or server configuration.\n" "\n" "lxc config edit [<remote>:][container]\n" " Edit configuration, either by launching external editor or reading STDIN.\n" "\n" "*Device management*\n" "\n" "lxc config device add [<remote>:]<container> <device> <type> [key=value...]\n" " Add a device to a container.\n" "\n" "lxc config device get [<remote>:]<container> <device> <key>\n" " Get a device property.\n" "\n" "lxc config device set [<remote>:]<container> <device> <key> <value>\n" " Set a device property.\n" "\n" "lxc config device unset [<remote>:]<container> <device> <key>\n" " Unset a device property.\n" "\n" "lxc config device list [<remote>:]<container>\n" " List devices for container.\n" "\n" "lxc config device show [<remote>:]<container>\n" " Show full device details for container.\n" "\n" "lxc config device remove [<remote>:]<container> <name>...\n" " Remove device from container.\n" "\n" "*Client trust store management*\n" "\n" "lxc config trust list [<remote>:]\n" " List all trusted certs.\n" "\n" "lxc config trust add [<remote>:] <certfile.crt>\n" " Add certfile.crt to trusted hosts.\n" "\n" "lxc config trust remove [<remote>:] [hostname|fingerprint]\n" " Remove the cert from trusted hosts.\n" "\n" "*Examples*\n" "\n" "cat config.yaml | lxc config edit <container>\n" " Update the container configuration from config.yaml.\n" "\n" "lxc config device add [<remote>:]container1 <device-name> disk source=/share/c1 path=opt\n" " Will mount the host's /share/c1 onto /opt in the container.\n" "\n" "lxc config set [<remote>:]<container> limits.cpu 2\n" " Will set a CPU limit of \"2\" for the container.\n" "\n" "lxc config set core.https_address [::]:8443\n" " Will have LXD listen on IPv4 and IPv6 port 8443.\n" "\n" "lxc config set core.trust_password blah\n" " Will set the server's trust password to blah." msgstr "" #: lxc/copy.go:23 msgid "Usage: lxc copy [<remote>:]<source>[/<snapshot>] [[<remote>:]<destination>] [--ephemeral|e]\n" "\n" "Copy containers within or in between LXD instances." msgstr "" #: lxc/delete.go:27 msgid "Usage: lxc delete [<remote>:]<container>[/<snapshot>] [[<remote>:]<container>[/<snapshot>]...]\n" "\n" "Delete containers and snapshots." msgstr "" #: lxc/exec.go:47 msgid "Usage: lxc exec [<remote>:]<container> [--mode=auto|interactive|non-interactive] [--env KEY=VALUE...] [--] <command line>\n" "\n" "Execute commands in containers.\n" "\n" "Mode defaults to non-interactive, interactive mode is selected if both stdin AND stdout are terminals (stderr is ignored)." msgstr "" #: lxc/file.go:33 msgid "Usage: lxc file <subcommand> [options]\n" "\n" "Manage files in containers.\n" "\n" "lxc file pull [<remote>:]<container>/<path> [[<remote>:]<container>/<path>...] <target path>\n" " Pull files from containers.\n" "\n" "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source path> [<source path>...] [<remote>:]<container>/<path>\n" " Push files into containers.\n" "\n" "lxc file edit [<remote>:]<container>/<path>\n" " Edit files in containers using the default text editor.\n" "\n" "*Examples*\n" "lxc file push /etc/hosts foo/etc/hosts\n" " To push /etc/hosts into the container \"foo\".\n" "\n" "lxc file pull foo/etc/hosts .\n" " To pull /etc/hosts from the container and write it to the current directory." msgstr "" #: lxc/finger.go:15 msgid "Usage: lxc finger [<remote>:]\n" "\n" "Check if the LXD server is alive." msgstr "" #: lxc/help.go:22 msgid "Usage: lxc help [--all]\n" "\n" "Help page for the LXD client." msgstr "" #: lxc/image.go:63 msgid "Usage: lxc image <subcommand> [options]\n" "\n" "Manipulate container images.\n" "\n" "In LXD containers are created from images. Those images were themselves\n" "either generated from an existing container or downloaded from an image\n" "server.\n" "\n" "When using remote images, LXD will automatically cache images for you\n" "and remove them upon expiration.\n" "\n" "The image unique identifier is the hash (sha-256) of its representation\n" "as a compressed tarball (or for split images, the concatenation of the\n" "metadata and rootfs tarballs).\n" "\n" "Images can be referenced by their full hash, shortest unique partial\n" "hash or alias name (if one is set).\n" "\n" "\n" "lxc image import <tarball> [<rootfs tarball>|<URL>] [<remote>:] [--public] [--created-at=ISO-8601] [--expires-at=ISO-8601] [--fingerprint=FINGERPRINT] [--alias=ALIAS...] [prop=value]\n" " Import an image tarball (or tarballs) into the LXD image store.\n" "\n" "lxc image copy [<remote>:]<image> <remote>: [--alias=ALIAS...] [--copy-aliases] [--public] [--auto-update]\n" " Copy an image from one LXD daemon to another over the network.\n" "\n" " The auto-update flag instructs the server to keep this image up to\n" " date. It requires the source to be an alias and for it to be public.\n" "\n" "lxc image delete [<remote>:]<image> [[<remote>:]<image>...]\n" " Delete one or more images from the LXD image store.\n" "\n" "lxc image export [<remote>:]<image> [target]\n" " Export an image from the LXD image store into a distributable tarball.\n" "\n" " The output target is optional and defaults to the working directory.\n" " The target may be an existing directory, file name, or \"-\" to specify\n" " stdout. The target MUST be a directory when exporting a split image.\n" " If the target is a directory, the image's name (each part's name for\n" " split images) as found in the database will be used for the exported\n" " image. If the target is a file (not a directory and not stdout), then\n" " the appropriate extension will be appended to the provided file name\n" " based on the algorithm used to compress the image.\n" "\n" "lxc image info [<remote>:]<image>\n" " Print everything LXD knows about a given image.\n" "\n" "lxc image list [<remote>:] [filter]\n" " List images in the LXD image store. Filters may be of the\n" " <key>=<value> form for property based filtering, or part of the image\n" " hash or part of the image alias name.\n" "\n" "lxc image show [<remote>:]<image>\n" " Yaml output of the user modifiable properties of an image.\n" "\n" "lxc image edit [<remote>:]<image>\n" " Edit image, either by launching external editor or reading STDIN.\n" " Example: lxc image edit <image> # launch editor\n" " cat image.yaml | lxc image edit <image> # read from image.yaml\n" "\n" "lxc image alias create [<remote>:]<alias> <fingerprint>\n" " Create a new alias for an existing image.\n" "\n" "lxc image alias delete [<remote>:]<alias>\n" " Delete an alias.\n" "\n" "lxc image alias list [<remote>:] [filter]\n" " List the aliases. Filters may be part of the image hash or part of the image alias name." msgstr "" #: lxc/info.go:26 msgid "Usage: lxc info [<remote>:][<container>] [--show-log]\n" "\n" "Show container or server information.\n" "\n" "lxc info [<remote>:]<container> [--show-log]\n" " For container information.\n" "\n" "lxc info [<remote>:]\n" " For LXD server information." msgstr "" #: lxc/init.go:75 msgid "Usage: lxc init [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance type>]\n" "\n" "Create containers from images.\n" "\n" "Not specifying -p will result in the default profile.\n" "Specifying \"-p\" with no argument will result in no profile.\n" "\n" "Examples:\n" " lxc init ubuntu:16.04 u1" msgstr "" #: lxc/launch.go:20 msgid "Usage: lxc launch [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance type>]\n" "\n" "Create and start containers from images.\n" "\n" "Not specifying -p will result in the default profile.\n" "Specifying \"-p\" with no argument will result in no profile.\n" "\n" "Examples:\n" " lxc launch ubuntu:16.04 u1" msgstr "" #: lxc/list.go:46 msgid "Usage: lxc list [<remote>:] [filters] [--format table|json] [-c <columns>] [--fast]\n" "\n" "List the existing containers.\n" "\n" "Default column layout: ns46tS\n" "Fast column layout: nsacPt\n" "\n" "*Filters*\n" "A single keyword like \"web\" which will list any container with a name starting by \"web\".\n" "\n" "A regular expression on the container name. (e.g. .*web.*01$).\n" "\n" "A key/value pair referring to a configuration item. For those, the namespace can be abbreviated to the smallest unambiguous identifier.\n" " - \"user.blah=abc\" will list all containers with the \"blah\" user property set to \"abc\".\n" "\n" " - \"u.blah=abc\" will do the same\n" "\n" " - \"security.privileged=true\" will list all privileged containers\n" "\n" " - \"s.privileged=true\" will do the same\n" "\n" "A regular expression matching a configuration item or its value. (e.g. volatile.eth0.hwaddr=00:16:3e:.*).\n" "\n" "*Columns*\n" "The -c option takes a comma separated list of arguments that control\n" "which container attributes to output when displaying in table format.\n" "\n" "Column arguments are either pre-defined shorthand chars (see below),\n" "or (extended) config keys.\n" "\n" "Commas between consecutive shorthand chars are optional.\n" "\n" "Pre-defined column shorthand chars:\n" "\n" " 4 - IPv4 address\n" "\n" " 6 - IPv6 address\n" "\n" " a - Architecture\n" "\n" " c - Creation date\n" "\n" " l - Last used date\n" "\n" " n - Name\n" "\n" " p - PID of the container's init process\n" "\n" " P - Profiles\n" "\n" " s - State\n" "\n" " S - Number of snapshots\n" "\n" " t - Type (persistent or ephemeral)\n" "\n" "*Examples*\n" "lxc list -c ns46\n" " Shows a list of containers using the \"NAME\", \"STATE\", \"IPV4\", \"IPV6\" columns." msgstr "" #: lxc/manpage.go:20 msgid "Usage: lxc manpage <directory>\n" "\n" "Generate all the LXD manpages." msgstr "" #: lxc/monitor.go:41 msgid "Usage: lxc monitor [<remote>:] [--type=TYPE...]\n" "\n" "Monitor a local or remote LXD server.\n" "\n" "By default the monitor will listen to all message types.\n" "\n" "Message types to listen for can be specified with --type.\n" "\n" "*Examples*\n" "lxc monitor --type=logging\n" " Only show log message." msgstr "" #: lxc/move.go:20 msgid "Usage: lxc move [<remote>:]<container>[/<snapshot>] [<remote>:][<container>[/<snapshot>]]\n" "\n" "Move containers within or in between LXD instances.\n" "\n" "lxc move [<remote>:]<source container> [<remote>:][<destination container>]\n" " Move a container between two hosts, renaming it if destination name differs.\n" "\n" "lxc move <old name> <new name>\n" " Rename a local container.\n" "\n" "lxc move <container>/<old snapshot name> <container>/<new snapshot name>\n" " Rename a snapshot." msgstr "" #: lxc/profile.go:49 msgid "Usage: lxc profile <subcommand> [options]\n" "\n" "Manage container configuration profiles.\n" "\n" "*Profile configuration*\n" "lxc profile list [<remote>:]\n" " List available profiles.\n" "\n" "lxc profile show [<remote>:]<profile>\n" " Show details of a profile.\n" "\n" "lxc profile create [<remote>:]<profile>\n" " Create a profile.\n" "\n" "lxc profile copy [<remote>:]<profile> [<remote>:]<profile>\n" " Copy the profile.\n" "\n" "lxc profile get [<remote>:]<profile> <key>\n" " Get profile configuration.\n" "\n" "lxc profile set [<remote>:]<profile> <key> <value>\n" " Set profile configuration.\n" "\n" "lxc profile unset [<remote>:]<profile> <key>\n" " Unset profile configuration.\n" "\n" "lxc profile delete [<remote>:]<profile>\n" " Delete a profile.\n" "\n" "lxc profile edit [<remote>:]<profile>\n" " Edit profile, either by launching external editor or reading STDIN.\n" "\n" "*Profile assignment*\n" "lxc profile apply [<remote>:]<container> <profiles>\n" " Replace the current set of profiles for the container by the one provided.\n" "\n" "*Device management*\n" "lxc profile device list [<remote>:]<profile>\n" " List devices in the given profile.\n" "\n" "lxc profile device show [<remote>:]<profile>\n" " Show full device details in the given profile.\n" "\n" "lxc profile device remove [<remote>:]<profile> <name>\n" " Remove a device from a profile.\n" "\n" "lxc profile device get [<remote>:]<profile> <name> <key>\n" " Get a device property.\n" "\n" "lxc profile device set [<remote>:]<profile> <name> <key> <value>\n" " Set a device property.\n" "\n" "lxc profile device unset [<remote>:]<profile> <name> <key>\n" " Unset a device property.\n" "\n" "lxc profile device add [<remote>:]<profile> <device> <type> [key=value...]\n" " Add a profile device, such as a disk or a nic, to the containers using the specified profile.\n" "\n" "*Examples*\n" "cat profile.yaml | lxc profile edit <profile>\n" " Update a profile using the content of profile.yaml\n" "\n" "lxc profile apply foo default,bar\n" " Set the profiles for \"foo\" to \"default\" and \"bar\".\n" "\n" "lxc profile apply foo default\n" " Reset \"foo\" to only using the \"default\" profile.\n" "\n" "lxc profile apply foo ''\n" " Remove all profile from \"foo\"" msgstr "" #: lxc/publish.go:27 msgid "Usage: lxc publish [<remote>:]<container>[/<snapshot>] [<remote>:] [--alias=ALIAS...] [prop-key=prop-value...]\n" "\n" "Publish containers as images." msgstr "" #: lxc/remote.go:39 msgid "Usage: lxc remote <subcommand> [options]\n" "\n" "Manage the list of remote LXD servers.\n" "\n" "lxc remote add <remote> <IP|FQDN|URL> [--accept-certificate] [--password=PASSWORD] [--public] [--protocol=PROTOCOL]\n" " Add the remote <remote> at <url>.\n" "\n" "lxc remote remove <remote>\n" " Remove the remote <remote>.\n" "\n" "lxc remote list\n" " List all remotes.\n" "\n" "lxc remote rename <old name> <new name>\n" " Rename remote <old name> to <new name>.\n" "\n" "lxc remote set-url <remote> <url>\n" " Update <remote>'s url to <url>.\n" "\n" "lxc remote set-default <remote>\n" " Set the default remote.\n" "\n" "lxc remote get-default\n" " Print the default remote." msgstr "" #: lxc/restore.go:22 msgid "Usage: lxc restore [<remote>:]<container> <snapshot> [--stateful]\n" "\n" "Restore containers from snapshots.\n" "\n" "If --stateful is passed, then the running state will be restored too.\n" "\n" "*Examples*\n" "lxc snapshot u1 snap0\n" " Create the snapshot.\n" "\n" "lxc restore u1 snap0\n" " Restore the snapshot." msgstr "" #: lxc/snapshot.go:22 msgid "Usage: lxc snapshot [<remote>:]<container> <snapshot name> [--stateful]\n" "\n" "Create container snapshots.\n" "\n" "When --stateful is used, LXD attempts to checkpoint the container's\n" "running state, including process memory state, TCP connections, ...\n" "\n" "*Examples*\n" "lxc snapshot u1 snap0\n" " Create a snapshot of \"u1\" called \"snap0\"." msgstr "" #: lxc/version.go:18 msgid "Usage: lxc version\n" "\n" "Print the version number of this client tool." msgstr "" #: lxc/delete.go:46 msgid "User aborted delete operation." msgstr "" #: lxc/utils.go:320 msgid "User signaled us three times, exiting. The remote operation will keep running." msgstr "" #: lxc/restore.go:38 msgid "Whether or not to restore the container's running state from snapshot (if available)" msgstr "" #: lxc/snapshot.go:36 msgid "Whether or not to snapshot the container's running state" msgstr "" #: lxc/remote.go:340 lxc/remote.go:345 msgid "YES" msgstr "" #: lxc/copy.go:49 msgid "You must specify a source container name" msgstr "" #: lxc/main.go:68 msgid "`lxc config profile` is deprecated, please use `lxc profile`" msgstr "" #: lxc/remote.go:328 msgid "can't remove the default remote" msgstr "" #: lxc/remote.go:354 msgid "default" msgstr "" #: lxc/init.go:276 msgid "didn't get any affected image, container or snapshot from server" msgstr "" #: lxc/image.go:406 msgid "disabled" msgstr "" #: lxc/image.go:408 msgid "enabled" msgstr "" #: lxc/action.go:134 lxc/main.go:29 lxc/main.go:178 #, c-format msgid "error: %v" msgstr "" #: lxc/help.go:37 lxc/main.go:124 #, c-format msgid "error: unknown command: %s" msgstr "" #: lxc/image.go:396 lxc/image.go:401 lxc/image.go:854 msgid "no" msgstr "" #: lxc/remote.go:182 msgid "ok (y/n)?" msgstr "" #: lxc/main.go:313 lxc/main.go:317 #, c-format msgid "processing aliases failed %s\n" msgstr "" #: lxc/remote.go:390 #, c-format msgid "remote %s already exists" msgstr "" #: lxc/remote.go:320 lxc/remote.go:382 lxc/remote.go:417 lxc/remote.go:433 #, c-format msgid "remote %s doesn't exist" msgstr "" #: lxc/remote.go:303 #, c-format msgid "remote %s exists as <%s>" msgstr "" #: lxc/remote.go:324 lxc/remote.go:386 lxc/remote.go:421 #, c-format msgid "remote %s is static and cannot be modified" msgstr "" #: lxc/info.go:219 msgid "stateful" msgstr "" #: lxc/info.go:221 msgid "stateless" msgstr "" #: lxc/info.go:215 #, c-format msgid "taken at %s" msgstr "" #: lxc/main.go:252 msgid "wrong number of subcommand arguments" msgstr "" #: lxc/delete.go:45 lxc/image.go:398 lxc/image.go:403 lxc/image.go:858 msgid "yes" msgstr "" �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/po/ja.po���������������������������������������������������������������������������������0000644�0610621�0607500�00000224437�13172163242�015055� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Japanese translation for LXD # Copyright (C) 2015 - LXD contributors # This file is distributed under the same license as LXD. # Hiroaki Nakamura <hnakamur@gmail.com>, 2015. # msgid "" msgstr "" "Project-Id-Version: LXD\n" "Report-Msgid-Bugs-To: lxc-devel@lists.linuxcontainers.org\n" "POT-Creation-Date: 2017-10-03 23:36-0400\n" "PO-Revision-Date: 2017-10-10 14:59+0900\n" "Last-Translator: KATOH Yasufumi <karma@jazz.email.ne.jp>\n" "Language-Team: Japanese <lxd-ja-language-team@googlegroups.com>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: lxc/config.go:39 msgid "" "### This is a yaml representation of the configuration.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### A sample configuration looks like:\n" "### name: container1\n" "### profiles:\n" "### - default\n" "### config:\n" "### volatile.eth0.hwaddr: 00:16:3e:e9:f8:7f\n" "### devices:\n" "### homedir:\n" "### path: /extra\n" "### source: /home/user\n" "### type: disk\n" "### ephemeral: false\n" "###\n" "### Note that the name is shown but cannot be changed" msgstr "" #: lxc/image.go:53 msgid "" "### This is a yaml representation of the image properties.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### Each property is represented by a single line:\n" "### An example would be:\n" "### description: My custom image" msgstr "" #: lxc/profile.go:28 msgid "" "### This is a yaml representation of the profile.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### A profile consists of a set of configuration items followed by a set of\n" "### devices.\n" "###\n" "### An example would look like:\n" "### name: onenic\n" "### config:\n" "### raw.lxc: lxc.aa_profile=unconfined\n" "### devices:\n" "### eth0:\n" "### nictype: bridged\n" "### parent: lxdbr0\n" "### type: nic\n" "###\n" "### Note that the name is shown but cannot be changed" msgstr "" #: lxc/image.go:851 #, c-format msgid "%s (%d more)" msgstr "%s (ä»–%d個)" #: lxc/utils.go:324 #, c-format msgid "%v (interrupt two more times to force)" msgstr "%v (強制的ã«ä¸­æ–­ã—ãŸã„å ´åˆã¯ã‚ã¨2回Ctrl-Cを入力/SIGINTã‚’é€å‡ºã—ã¦ãã ã•ã„)" #: lxc/snapshot.go:53 msgid "'/' not allowed in snapshot name" msgstr "'/' ã¯ã‚¹ãƒŠãƒƒãƒ—ショットã®åå‰ã«ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“。" #: lxc/profile.go:289 msgid "(none)" msgstr "" #: lxc/image.go:872 lxc/image.go:901 msgid "ALIAS" msgstr "" #: lxc/image.go:876 msgid "ARCH" msgstr "" #: lxc/list.go:414 msgid "ARCHITECTURE" msgstr "" #: lxc/remote.go:67 msgid "Accept certificate" msgstr "証明書ã®ãƒ•ィンガープリントã®ç¢ºèªãªã—ã§è¨¼æ˜Žæ›¸ã‚’å—ã‘入れã¾ã™" #: lxc/remote.go:245 #, c-format msgid "Admin password for %s: " msgstr "%s ã®ç®¡ç†è€…パスワード: " #: lxc/image.go:435 msgid "Aliases:" msgstr "エイリアス:" #: lxc/image.go:413 lxc/info.go:104 #, c-format msgid "Architecture: %s" msgstr "アーキテクãƒãƒ£: %s" #: lxc/image.go:444 #, c-format msgid "Auto update: %s" msgstr "自動更新: %s" #: lxc/image.go:518 #, c-format msgid "Bad property: %s" msgstr "䏿­£ãªãƒ—ロパティ: %s\n" #: lxc/info.go:186 msgid "Bytes received" msgstr "å—ä¿¡ãƒã‚¤ãƒˆæ•°" #: lxc/info.go:187 msgid "Bytes sent" msgstr "é€ä¿¡ãƒã‚¤ãƒˆæ•°" #: lxc/config.go:349 msgid "COMMON NAME" msgstr "" #: lxc/list.go:415 msgid "CREATED AT" msgstr "" #: lxc/image.go:443 #, c-format msgid "Cached: %s" msgstr "キャッシュ済: %s" #: lxc/config.go:156 #, c-format msgid "Can't read from stdin: %s" msgstr "標準入力ã‹ã‚‰èª­ã¿è¾¼ã‚ã¾ã›ã‚“: %s" #: lxc/config.go:169 #, c-format msgid "Can't unset key '%s', it's not currently set" msgstr "キー '%s' ãŒè¨­å®šã•れã¦ã„ãªã„ã®ã§å‰Šé™¤ã§ãã¾ã›ã‚“。" #: lxc/config.go:211 lxc/config.go:237 #, c-format msgid "Can't unset key '%s', it's not currently set." msgstr "キー '%s' ãŒæŒ‡å®šã•れã¦ã„ãªã„ã®ã§å‰Šé™¤ã§ãã¾ã›ã‚“。" #: lxc/profile.go:441 msgid "Cannot provide container name to list" msgstr "コンテナåã‚’å–å¾—ã§ãã¾ã›ã‚“" #: lxc/remote.go:181 #, c-format msgid "Certificate fingerprint: %s" msgstr "証明書ã®ãƒ•ィンガープリント: %s" #: lxc/remote.go:280 msgid "Client certificate stored at server: " msgstr "クライアント証明書ãŒã‚µãƒ¼ãƒã«æ ¼ç´ã•れã¾ã—ãŸ: " #: lxc/list.go:109 lxc/list.go:110 msgid "Columns" msgstr "カラムレイアウト" #: lxc/help.go:53 msgid "Commands:" msgstr "コマンド:" #: lxc/init.go:135 lxc/init.go:136 msgid "Config key/value to apply to the new container" msgstr "æ–°ã—ã„コンテナã«é©ç”¨ã™ã‚‹ã‚­ãƒ¼/値ã®è¨­å®š" #: lxc/config.go:647 lxc/config.go:712 lxc/image.go:956 lxc/profile.go:237 #, c-format msgid "Config parsing error: %s" msgstr "è¨­å®šã®æ§‹æ–‡ã‚¨ãƒ©ãƒ¼: %s" #: lxc/main.go:36 msgid "Connection refused; is LXD running?" msgstr "æŽ¥ç¶šãŒæ‹’å¦ã•れã¾ã—ãŸã€‚LXDãŒå®Ÿè¡Œã•れã¦ã„ã¾ã™ã‹?" #: lxc/publish.go:69 msgid "Container name is mandatory" msgstr "コンテナåを指定ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™" #: lxc/copy.go:186 lxc/init.go:282 #, c-format msgid "Container name is: %s" msgstr "コンテナå: %s" #: lxc/publish.go:247 #, c-format msgid "Container published with fingerprint: %s" msgstr "コンテナã¯ä»¥ä¸‹ã®ãƒ•ィンガープリント㧠publish ã•れã¾ã™: %s" #: lxc/image.go:135 msgid "Copy aliases from source" msgstr "ソースã‹ã‚‰ã‚¨ã‚¤ãƒªã‚¢ã‚¹ã‚’コピーã—ã¾ã—ãŸ" #: lxc/image.go:313 #, c-format msgid "Copying the image: %s" msgstr "イメージã®ã‚³ãƒ”ー中: %s" #: lxc/remote.go:196 msgid "Could not create server cert dir" msgstr "サーãƒè¨¼æ˜Žæ›¸æ ¼ç´ç”¨ã®ãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒªã‚’作æˆã§ãã¾ã›ã‚“。" #: lxc/image.go:418 lxc/info.go:106 #, c-format msgid "Created: %s" msgstr "ä½œæˆæ—¥æ™‚: %s" #: lxc/init.go:190 #, c-format msgid "Creating %s" msgstr "%s を作æˆä¸­" #: lxc/init.go:188 msgid "Creating the container" msgstr "コンテナを作æˆä¸­" #: lxc/image.go:875 lxc/image.go:903 msgid "DESCRIPTION" msgstr "" #: lxc/config.go:803 #, c-format msgid "Device %s added to %s" msgstr "デãƒã‚¤ã‚¹ %s ㌠%s ã«è¿½åŠ ã•れã¾ã—ãŸ" #: lxc/config.go:1039 #, c-format msgid "Device %s removed from %s" msgstr "デãƒã‚¤ã‚¹ %s ㌠%s ã‹ã‚‰å‰Šé™¤ã•れã¾ã—ãŸ" #: lxc/info.go:154 msgid "Disk usage:" msgstr "ディスク使用é‡:" #: lxc/list.go:505 msgid "EPHEMERAL" msgstr "" #: lxc/config.go:351 msgid "EXPIRY DATE" msgstr "" #: lxc/main.go:48 msgid "Enable debug mode" msgstr "デãƒãƒƒã‚°ãƒ¢ãƒ¼ãƒ‰ã‚’有効ã«ã—ã¾ã™" #: lxc/main.go:47 msgid "Enable verbose mode" msgstr "詳細モードを有効ã«ã—ã¾ã™" #: lxc/exec.go:56 msgid "Environment variable to set (e.g. HOME=/home/foo)" msgstr "環境変数を HOME=/home/foo ã®å½¢å¼ã§æŒ‡å®šã—ã¾ã™" #: lxc/help.go:77 msgid "Environment:" msgstr "環境変数:" #: lxc/copy.go:30 lxc/copy.go:31 lxc/init.go:139 lxc/init.go:140 msgid "Ephemeral container" msgstr "Ephemeral コンテナ" #: lxc/monitor.go:56 msgid "Event type to listen for" msgstr "Listenã™ã‚‹ã‚¤ãƒ™ãƒ³ãƒˆã‚¿ã‚¤ãƒ—" #: lxc/image.go:422 #, c-format msgid "Expires: %s" msgstr "失効日時: %s" #: lxc/image.go:424 msgid "Expires: never" msgstr "失効日時: 失効ã—ãªã„" #: lxc/image.go:710 #, c-format msgid "Exporting the image: %s" msgstr "イメージã®ã‚¨ã‚¯ã‚¹ãƒãƒ¼ãƒˆä¸­: %s" #: lxc/config.go:348 lxc/image.go:873 lxc/image.go:902 msgid "FINGERPRINT" msgstr "" #: lxc/utils.go:362 #, c-format msgid "Failed to create alias %s" msgstr "エイリアス %s ã®ä½œæˆã«å¤±æ•—ã—ã¾ã—ãŸ" #: lxc/manpage.go:62 #, c-format msgid "Failed to generate 'lxc.%s.1': %v" msgstr "'lxc.%s.1' ã®ç”ŸæˆãŒå¤±æ•—ã—ã¾ã—ãŸ: %v" #: lxc/manpage.go:55 #, c-format msgid "Failed to generate 'lxc.1': %v" msgstr "'lxc.1' ã®ç”ŸæˆãŒå¤±æ•—ã—ã¾ã—ãŸ: %v" #: lxc/copy.go:181 msgid "Failed to get the new container name" msgstr "コピー先ã®ã‚³ãƒ³ãƒ†ãƒŠåãŒå–å¾—ã§ãã¾ã›ã‚“ã§ã—ãŸ" #: lxc/utils.go:352 #, c-format msgid "Failed to remove alias %s" msgstr "エイリアス %s ã®å‰Šé™¤ã«å¤±æ•—ã—ã¾ã—ãŸ" #: lxc/list.go:112 msgid "Fast mode (same as --columns=nsacPt)" msgstr "Fast モード (--columns=nsacPt ã¨åŒã˜)" #: lxc/image.go:411 #, c-format msgid "Fingerprint: %s" msgstr "証明書ã®ãƒ•ィンガープリント: %s" #: lxc/action.go:46 lxc/action.go:47 msgid "Force the container to shutdown" msgstr "コンテナを強制シャットダウンã—ã¾ã™ã€‚" #: lxc/delete.go:34 lxc/delete.go:35 msgid "Force the removal of running containers" msgstr "稼åƒä¸­ã®ã‚³ãƒ³ãƒ†ãƒŠã‚’強制的ã«å‰Šé™¤ã—ã¾ã™" #: lxc/main.go:49 msgid "Force using the local unix socket" msgstr "強制的ã«ãƒ­ãƒ¼ã‚«ãƒ«ã®UNIXソケットを使ã„ã¾ã™ã€‚" #: lxc/list.go:111 msgid "Format (table|json)" msgstr "フォーマット (table|json)" #: lxc/main.go:149 msgid "Generating a client certificate. This may take a minute..." msgstr "クライアント証明書を生æˆã—ã¾ã™ã€‚1分ãらã„ã‹ã‹ã‚Šã¾ã™..." #: lxc/list.go:412 msgid "IPV4" msgstr "" #: lxc/list.go:413 msgid "IPV6" msgstr "" #: lxc/config.go:350 msgid "ISSUE DATE" msgstr "" #: lxc/main.go:157 msgid "" "If this is your first time using LXD, you should also run: sudo lxd init" msgstr "åˆã‚㦠LXD を使ã†å ´åˆã€sudo lxd init ã¨å®Ÿè¡Œã™ã‚‹å¿…è¦ãŒã‚りã¾ã™" #: lxc/main.go:50 msgid "Ignore aliases when determining what command to run" msgstr "ã©ã®ã‚³ãƒžãƒ³ãƒ‰ã‚’実行ã™ã‚‹ã‹æ±ºã‚ã‚‹éš›ã«ã‚¨ã‚¤ãƒªã‚¢ã‚¹ã‚’無視ã—ã¾ã™ã€‚" #: lxc/action.go:50 msgid "Ignore the container state (only for start)" msgstr "コンテナã®çŠ¶æ…‹ã‚’ç„¡è¦–ã—ã¾ã™ (startã®ã¿)。" #: lxc/image.go:327 msgid "Image copied successfully!" msgstr "イメージã®ã‚³ãƒ”ãƒ¼ãŒæˆåŠŸã—ã¾ã—ãŸ!" #: lxc/image.go:770 msgid "Image exported successfully!" msgstr "イメージã®ã‚¨ã‚¯ã‚¹ãƒãƒ¼ãƒˆã«æˆåŠŸã—ã¾ã—ãŸ!" #: lxc/image.go:580 #, c-format msgid "Image imported with fingerprint: %s" msgstr "イメージã¯ä»¥ä¸‹ã®ãƒ•ィンガープリントã§ã‚¤ãƒ³ãƒãƒ¼ãƒˆã•れã¾ã—ãŸ: %s" #: lxc/init.go:141 msgid "Instance type" msgstr "インスタンスタイプ" #: lxc/remote.go:107 #, c-format msgid "Invalid URL scheme \"%s\" in \"%s\"" msgstr "䏿­£ãª URL スキーム \"%s\" (\"%s\" 内)" #: lxc/config.go:329 msgid "Invalid certificate" msgstr "䏿­£ãªè¨¼æ˜Žæ›¸" #: lxc/init.go:31 lxc/init.go:36 msgid "Invalid configuration key" msgstr "æ­£ã—ããªã„設定項目 (key) ã§ã™" #: lxc/file.go:219 #, c-format msgid "Invalid source %s" msgstr "䏿­£ãªã‚½ãƒ¼ã‚¹ %s" #: lxc/file.go:70 #, c-format msgid "Invalid target %s" msgstr "䏿­£ãªé€ã‚Šå…ˆ %s" #: lxc/info.go:135 msgid "Ips:" msgstr "IPアドレス:" #: lxc/image.go:136 msgid "Keep the image up to date after initial copy" msgstr "最åˆã«ã‚³ãƒ”ーã—ãŸå¾Œã‚‚常ã«ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’最新ã®çŠ¶æ…‹ã«ä¿ã¤" #: lxc/main.go:34 msgid "LXD socket not found; is LXD installed and running?" msgstr "LXD ã®ã‚½ã‚±ãƒƒãƒˆãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“。LXD ãŒå®Ÿè¡Œã•れã¦ã„ã¾ã™ã‹?" #: lxc/image.go:427 #, c-format msgid "Last used: %s" msgstr "最終使用: %s" #: lxc/image.go:429 msgid "Last used: never" msgstr "最終使用: 未使用" #: lxc/info.go:239 msgid "Log:" msgstr "ログ:" #: lxc/image.go:134 msgid "Make image public" msgstr "イメージを public ã«ã™ã‚‹" #: lxc/publish.go:34 msgid "Make the image public" msgstr "イメージを public ã«ã™ã‚‹" #: lxc/info.go:161 msgid "Memory (current)" msgstr "メモリ (ç¾åœ¨å€¤)" #: lxc/info.go:165 msgid "Memory (peak)" msgstr "メモリ (ピーク)" #: lxc/info.go:177 msgid "Memory usage:" msgstr "メモリ消費é‡:" #: lxc/utils.go:256 msgid "Missing summary." msgstr "サマリーã¯ã‚りã¾ã›ã‚“。" #: lxc/file.go:207 msgid "More than one file to download, but target is not a directory" msgstr "" "ダウンロード対象ã®ãƒ•ァイルãŒè¤‡æ•°ã‚りã¾ã™ãŒã€ã‚³ãƒ”ー先ãŒãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒªã§ã¯ã‚りã¾" "ã›ã‚“。" #: lxc/action.go:72 msgid "Must supply container name for: " msgstr "コンテナåを指定ã™ã‚‹å¿…è¦ãŒã‚りã¾ã™: " #: lxc/list.go:416 lxc/remote.go:364 msgid "NAME" msgstr "" #: lxc/remote.go:338 lxc/remote.go:343 msgid "NO" msgstr "" #: lxc/info.go:99 #, c-format msgid "Name: %s" msgstr "コンテナå: %s" #: lxc/info.go:194 msgid "Network usage:" msgstr "ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯ä½¿ç”¨çжæ³:" #: lxc/image.go:137 lxc/publish.go:35 msgid "New alias to define at target" msgstr "æ–°ã—ã„エイリアスを定義ã™ã‚‹" #: lxc/config.go:360 msgid "No certificate provided to add" msgstr "追加ã™ã¹ãè¨¼æ˜Žæ›¸ãŒæä¾›ã•れã¦ã„ã¾ã›ã‚“" #: lxc/config.go:392 msgid "No fingerprint specified." msgstr "ãƒ•ã‚£ãƒ³ã‚¬ãƒ¼ãƒ—ãƒªãƒ³ãƒˆãŒæŒ‡å®šã•れã¦ã„ã¾ã›ã‚“。" #: lxc/remote.go:92 msgid "Only https URLs are supported for simplestreams" msgstr "simplestreams 㯠https ã® URL ã®ã¿ã‚µãƒãƒ¼ãƒˆã—ã¾ã™" #: lxc/image.go:499 msgid "Only https:// is supported for remote image import." msgstr "リモートイメージã®ã‚¤ãƒ³ãƒãƒ¼ãƒˆã¯ https:// ã®ã¿ã‚’サãƒãƒ¼ãƒˆã—ã¾ã™ã€‚" #: lxc/help.go:71 lxc/main.go:130 lxc/main.go:182 msgid "Options:" msgstr "オプション:" #: lxc/exec.go:57 msgid "Override the terminal mode (auto, interactive or non-interactive)" msgstr "ターミナルモードを上書ãã—ã¾ã™ (auto, interactive, non-interactive)" #: lxc/list.go:507 msgid "PERSISTENT" msgstr "" #: lxc/list.go:417 msgid "PID" msgstr "" #: lxc/list.go:418 msgid "PROFILES" msgstr "" #: lxc/remote.go:366 msgid "PROTOCOL" msgstr "" #: lxc/image.go:874 lxc/remote.go:367 msgid "PUBLIC" msgstr "" #: lxc/info.go:188 msgid "Packets received" msgstr "å—信パケット" #: lxc/info.go:189 msgid "Packets sent" msgstr "é€ä¿¡ãƒ‘ケット" #: lxc/help.go:78 msgid "Path to an alternate client configuration directory" msgstr "別ã®ã‚¯ãƒ©ã‚¤ã‚¢ãƒ³ãƒˆç”¨è¨­å®šãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒª" #: lxc/help.go:79 msgid "Path to an alternate server directory" msgstr "別ã®ã‚µãƒ¼ãƒç”¨è¨­å®šãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒª" #: lxc/main.go:219 msgid "Pause containers." msgstr "ã‚³ãƒ³ãƒ†ãƒŠã‚’ä¸€æ™‚åœæ­¢ã—ã¾ã™ã€‚" #: lxc/main.go:38 msgid "Permission denied, are you in the lxd group?" msgstr "ã‚¢ã‚¯ã‚»ã‚¹ãŒæ‹’å¦ã•れã¾ã—ãŸã€‚lxd ã‚°ãƒ«ãƒ¼ãƒ—ã«æ‰€å±žã—ã¦ã„ã¾ã™ã‹?" #: lxc/info.go:117 #, c-format msgid "Pid: %d" msgstr "" #: lxc/profile.go:238 msgid "Press enter to open the editor again" msgstr "å†åº¦ã‚¨ãƒ‡ã‚£ã‚¿ã‚’é–‹ããŸã‚ã«ã¯ Enter キーを押ã—ã¾ã™" #: lxc/config.go:648 lxc/config.go:713 lxc/image.go:957 msgid "Press enter to start the editor again" msgstr "å†åº¦ã‚¨ãƒ‡ã‚£ã‚¿ã‚’èµ·å‹•ã™ã‚‹ã«ã¯ Enter キーを押ã—ã¾ã™" #: lxc/help.go:73 msgid "Print debug information" msgstr "デãƒãƒƒã‚°æƒ…報を表示ã—ã¾ã™ã€‚" #: lxc/help.go:72 msgid "Print less common commands" msgstr "å…¨ã¦ã®ã‚³ãƒžãƒ³ãƒ‰ã‚’表示ã—ã¾ã™" #: lxc/help.go:74 msgid "Print verbose information" msgstr "詳細情報を表示ã—ã¾ã™" #: lxc/info.go:141 #, c-format msgid "Processes: %d" msgstr "プロセス数: %d" #: lxc/profile.go:188 #, c-format msgid "Profile %s created" msgstr "プロファイル %s を作æˆã—ã¾ã—ãŸ" #: lxc/profile.go:262 #, c-format msgid "Profile %s deleted" msgstr "プロファイル %s を削除ã—ã¾ã—ãŸ" #: lxc/init.go:137 lxc/init.go:138 msgid "Profile to apply to the new container" msgstr "æ–°ã—ã„コンテナã«é©ç”¨ã™ã‚‹ãƒ—ロファイル" #: lxc/profile.go:291 #, c-format msgid "Profiles %s applied to %s" msgstr "プロファイル %s ㌠%s ã«è¿½åŠ ã•れã¾ã—ãŸ" #: lxc/info.go:115 #, c-format msgid "Profiles: %s" msgstr "プロファイル: %s" #: lxc/image.go:431 msgid "Properties:" msgstr "プロパティ:" #: lxc/remote.go:70 msgid "Public image server" msgstr "Public ãªã‚¤ãƒ¡ãƒ¼ã‚¸ã‚µãƒ¼ãƒã¨ã—ã¦è¨­å®šã—ã¾ã™" #: lxc/image.go:414 #, c-format msgid "Public: %s" msgstr "パブリック: %s" #: lxc/remote.go:68 msgid "Remote admin password" msgstr "リモートã®ç®¡ç†è€…パスワード" #: lxc/utils.go:315 msgid "Remote operation canceled by user" msgstr "リモートæ“作ãŒãƒ¦ãƒ¼ã‚¶ã«ã‚ˆã£ã¦ã‚­ãƒ£ãƒ³ã‚»ãƒ«ã•れã¾ã—ãŸ" #: lxc/info.go:101 #, c-format msgid "Remote: %s" msgstr "リモートå: %s" #: lxc/delete.go:42 #, c-format msgid "Remove %s (yes/no): " msgstr "%s を消去ã—ã¾ã™ã‹ (yes/no): " #: lxc/delete.go:36 lxc/delete.go:37 msgid "Require user confirmation" msgstr "ユーザã®ç¢ºèªã‚’è¦æ±‚ã™ã‚‹" #: lxc/info.go:138 msgid "Resources:" msgstr "リソース:" #: lxc/main.go:227 msgid "Restart containers." msgstr "コンテナをå†èµ·å‹•ã—ã¾ã™ã€‚" #: lxc/init.go:254 #, c-format msgid "Retrieving image: %s" msgstr "イメージã®å–得中: %s" #: lxc/image.go:877 msgid "SIZE" msgstr "" #: lxc/list.go:419 msgid "SNAPSHOTS" msgstr "" #: lxc/list.go:420 msgid "STATE" msgstr "" #: lxc/remote.go:368 msgid "STATIC" msgstr "" #: lxc/remote.go:189 msgid "Server certificate NACKed by user" msgstr "ユーザã«ã‚ˆã‚Šã‚µãƒ¼ãƒè¨¼æ˜Žæ›¸ãŒæ‹’å¦ã•れã¾ã—ãŸ" #: lxc/remote.go:277 msgid "Server doesn't trust us after adding our cert" msgstr "サーãƒãŒæˆ‘々ã®è¨¼æ˜Žæ›¸ã‚’追加ã—ãŸå¾Œæˆ‘々を信頼ã—ã¦ã„ã¾ã›ã‚“" #: lxc/remote.go:69 msgid "Server protocol (lxd or simplestreams)" msgstr "サーãƒã®ãƒ—ロトコル (lxd or simplestreams)" #: lxc/file.go:57 msgid "Set the file's gid on push" msgstr "プッシュ時ã«ãƒ•ァイルã®gidを設定ã—ã¾ã™" #: lxc/file.go:58 msgid "Set the file's perms on push" msgstr "プッシュ時ã«ãƒ•ァイルã®ãƒ‘ーミションを設定ã—ã¾ã™" #: lxc/file.go:56 msgid "Set the file's uid on push" msgstr "プッシュ時ã«ãƒ•ァイルã®uidを設定ã—ã¾ã™" #: lxc/help.go:29 msgid "Show all commands (not just interesting ones)" msgstr "å…¨ã¦ã‚³ãƒžãƒ³ãƒ‰ã‚’表示ã—ã¾ã™ (主ãªã‚³ãƒžãƒ³ãƒ‰ã ã‘ã§ã¯ãªã)" #: lxc/help.go:75 msgid "Show client version" msgstr "クライアントã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’表示ã—ã¾ã™" #: lxc/info.go:39 msgid "Show the container's last 100 log lines?" msgstr "ã‚³ãƒ³ãƒ†ãƒŠãƒ­ã‚°ã®æœ€å¾Œã® 100 行を表示ã—ã¾ã™ã‹?" #: lxc/config.go:35 msgid "Show the expanded configuration" msgstr "æ‹¡å¼µã—ãŸè¨­å®šã‚’表示ã™ã‚‹" #: lxc/image.go:412 #, c-format msgid "Size: %.2fMB" msgstr "サイズ: %.2fMB" #: lxc/info.go:208 msgid "Snapshots:" msgstr "スナップショット:" #: lxc/action.go:142 #, c-format msgid "Some containers failed to %s" msgstr "一部ã®ã‚³ãƒ³ãƒ†ãƒŠã§ %s ãŒå¤±æ•—ã—ã¾ã—ãŸ" #: lxc/image.go:446 msgid "Source:" msgstr "å–å¾—å…ƒ:" #: lxc/main.go:237 msgid "Start containers." msgstr "コンテナを起動ã—ã¾ã™ã€‚" #: lxc/launch.go:59 #, c-format msgid "Starting %s" msgstr "%s を起動中" #: lxc/info.go:109 #, c-format msgid "Status: %s" msgstr "状態: %s" #: lxc/main.go:243 msgid "Stop containers." msgstr "ã‚³ãƒ³ãƒ†ãƒŠã‚’åœæ­¢ã—ã¾ã™ã€‚" #: lxc/publish.go:36 lxc/publish.go:37 msgid "Stop the container if currently running" msgstr "実行中ã®å ´åˆã€ã‚³ãƒ³ãƒ†ãƒŠã‚’åœæ­¢ã—ã¾ã™" #: lxc/publish.go:134 msgid "Stopping container failed!" msgstr "コンテナã®åœæ­¢ã«å¤±æ•—ã—ã¾ã—ãŸï¼" #: lxc/delete.go:121 #, c-format msgid "Stopping the container failed: %s" msgstr "コンテナã®åœæ­¢ã«å¤±æ•—ã—ã¾ã—ãŸ: %s" #: lxc/action.go:49 msgid "Store the container state (only for stop)" msgstr "コンテナã®çŠ¶æ…‹ã‚’ä¿å­˜ã—ã¾ã™ (stopã®ã¿)" #: lxc/info.go:169 msgid "Swap (current)" msgstr "Swap (ç¾åœ¨å€¤)" #: lxc/info.go:173 msgid "Swap (peak)" msgstr "Swap (ピーク)" #: lxc/list.go:421 msgid "TYPE" msgstr "" #: lxc/delete.go:105 msgid "The container is currently running, stop it first or pass --force." msgstr "コンテナã¯å®Ÿè¡Œä¸­ã§ã™ã€‚å…ˆã«åœæ­¢ã•ã›ã‚‹ã‹ã€--force を指定ã—ã¦ãã ã•ã„。" #: lxc/publish.go:99 msgid "" "The container is currently running. Use --force to have it stopped and " "restarted." msgstr "" "コンテナã¯ç¾åœ¨å®Ÿè¡Œä¸­ã§ã™ã€‚åœæ­¢ã—ã¦ã€å†èµ·å‹•ã™ã‚‹ãŸã‚ã« --force を使用ã—ã¦ãã \n" "ã•ã„。" #: lxc/config.go:770 lxc/config.go:787 msgid "The device already exists" msgstr "デãƒã‚¤ã‚¹ %s ã¯æ—¢ã«å­˜åœ¨ã—ã¾ã™" #: lxc/config.go:833 lxc/config.go:845 lxc/config.go:881 lxc/config.go:899 #: lxc/config.go:945 lxc/config.go:962 lxc/config.go:1005 lxc/config.go:1023 msgid "The device doesn't exist" msgstr "デãƒã‚¤ã‚¹ãŒå­˜åœ¨ã—ã¾ã›ã‚“" #: lxc/init.go:308 #, c-format msgid "The local image '%s' couldn't be found, trying '%s:' instead." msgstr "" "ローカルイメージ '%s' ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“。代ã‚り㫠'%s:' を試ã—ã¦ã¿ã¦ãã ã•ã„。" #: lxc/action.go:34 msgid "The opposite of \"lxc pause\" is \"lxc start\"." msgstr "\"lxc pause\" ã®å対ã®ã‚³ãƒžãƒ³ãƒ‰ã¯ \"lxc start\" ã§ã™ã€‚" #: lxc/publish.go:72 msgid "There is no \"image name\". Did you want an alias?" msgstr "" "publish å…ˆã«ã¯ã‚¤ãƒ¡ãƒ¼ã‚¸åã¯æŒ‡å®šã§ãã¾ã›ã‚“。\"--alias\" オプションを使ã£ã¦ã" "ã \n" "ã•ã„。" #: lxc/help.go:47 msgid "" "This is the LXD command line client.\n" "\n" "All of LXD's features can be driven through the various commands below.\n" "For help with any of those, simply call them with --help." msgstr "" "ã“れ㯠LXD ã®ã‚³ãƒžãƒ³ãƒ‰ã‚¯ãƒ©ã‚¤ã‚¢ãƒ³ãƒˆã§ã™ã€‚\n" "\n" "LXD ã®æ©Ÿèƒ½ã®ã™ã¹ã¦ãŒã€ä»¥ä¸‹ã®è‰²ã€…ãªã‚³ãƒžãƒ³ãƒ‰ã‹ã‚‰æ“作ã§ãã¾ã™ã€‚\n" "コマンドã®ãƒ˜ãƒ«ãƒ—ã¯ã€--help をコマンドã«ä»˜ã‘ã¦å®Ÿè¡Œã™ã‚‹ã ã‘ã§ã™ã€‚" #: lxc/action.go:45 msgid "Time to wait for the container before killing it" msgstr "ã‚³ãƒ³ãƒ†ãƒŠã‚’å¼·åˆ¶åœæ­¢ã™ã‚‹ã¾ã§ã®æ™‚é–“" #: lxc/image.go:415 msgid "Timestamps:" msgstr "タイムスタンプ:" #: lxc/main.go:158 msgid "To start your first container, try: lxc launch ubuntu:16.04" msgstr "" "åˆã‚ã¦ã‚³ãƒ³ãƒ†ãƒŠã‚’èµ·å‹•ã™ã‚‹ã«ã¯ã€\"lxc launch ubuntu:16.04\" ã¨å®Ÿè¡Œã—ã¦ã¿ã¦ã" "ã \n" "ã•ã„。" #: lxc/copy.go:155 #, c-format msgid "Transferring container: %s" msgstr "コンテナを転é€ä¸­: %s" #: lxc/image.go:528 #, c-format msgid "Transferring image: %s" msgstr "イメージを転é€ä¸­: %s" #: lxc/action.go:106 lxc/launch.go:77 #, c-format msgid "Try `lxc info --show-log %s` for more info" msgstr "æ›´ã«æƒ…報を得るãŸã‚ã« `lxc info --show-log` を実行ã—ã¦ã¿ã¦ãã ã•ã„" #: lxc/info.go:111 msgid "Type: ephemeral" msgstr "タイプ: ephemeral" #: lxc/info.go:113 msgid "Type: persistent" msgstr "タイプ: persistent" #: lxc/image.go:878 msgid "UPLOAD DATE" msgstr "" #: lxc/remote.go:365 msgid "URL" msgstr "" #: lxc/manpage.go:36 msgid "Unable to find help2man." msgstr "help2man ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“。" #: lxc/image.go:420 #, c-format msgid "Uploaded: %s" msgstr "アップロード日時: %s" #: lxc/action.go:37 #, c-format msgid "" "Usage: lxc %s [<remote>:]<container> [[<remote>:]<container>...]\n" "\n" "%s%s" msgstr "" "ä½¿ã„æ–¹: lxc %s [<remote>:]<container> [[<remote>:]<container>...]\n" "\n" "%s%s" #: lxc/help.go:45 msgid "Usage: lxc <command> [options]" msgstr "ä½¿ã„æ–¹: lxc <command> [options]" #: lxc/config.go:60 msgid "" "Usage: lxc config <subcommand> [options]\n" "\n" "Change container or server configuration options.\n" "\n" "*Container configuration*\n" "\n" "lxc config get [<remote>:][container] <key>\n" " Get container or server configuration key.\n" "\n" "lxc config set [<remote>:][container] <key> <value>\n" " Set container or server configuration key.\n" "\n" "lxc config unset [<remote>:][container] <key>\n" " Unset container or server configuration key.\n" "\n" "lxc config show [<remote>:][container] [--expanded]\n" " Show container or server configuration.\n" "\n" "lxc config edit [<remote>:][container]\n" " Edit configuration, either by launching external editor or reading " "STDIN.\n" "\n" "*Device management*\n" "\n" "lxc config device add [<remote>:]<container> <device> <type> [key=value...]\n" " Add a device to a container.\n" "\n" "lxc config device get [<remote>:]<container> <device> <key>\n" " Get a device property.\n" "\n" "lxc config device set [<remote>:]<container> <device> <key> <value>\n" " Set a device property.\n" "\n" "lxc config device unset [<remote>:]<container> <device> <key>\n" " Unset a device property.\n" "\n" "lxc config device list [<remote>:]<container>\n" " List devices for container.\n" "\n" "lxc config device show [<remote>:]<container>\n" " Show full device details for container.\n" "\n" "lxc config device remove [<remote>:]<container> <name>...\n" " Remove device from container.\n" "\n" "*Client trust store management*\n" "\n" "lxc config trust list [<remote>:]\n" " List all trusted certs.\n" "\n" "lxc config trust add [<remote>:] <certfile.crt>\n" " Add certfile.crt to trusted hosts.\n" "\n" "lxc config trust remove [<remote>:] [hostname|fingerprint]\n" " Remove the cert from trusted hosts.\n" "\n" "*Examples*\n" "\n" "cat config.yaml | lxc config edit <container>\n" " Update the container configuration from config.yaml.\n" "\n" "lxc config device add [<remote>:]container1 <device-name> disk source=/share/" "c1 path=opt\n" " Will mount the host's /share/c1 onto /opt in the container.\n" "\n" "lxc config set [<remote>:]<container> limits.cpu 2\n" " Will set a CPU limit of \"2\" for the container.\n" "\n" "lxc config set core.https_address [::]:8443\n" " Will have LXD listen on IPv4 and IPv6 port 8443.\n" "\n" "lxc config set core.trust_password blah\n" " Will set the server's trust password to blah." msgstr "" "ä½¿ã„æ–¹: lxc config <subcommand> [options]\n" "\n" "コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šã‚ªãƒ—ションを変更ã—ã¾ã™ã€‚\n" "\n" "*コンテナã®è¨­å®š*\n" "\n" "lxc config get [<remote>:][container] <key>\n" " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šé …ç›®ã®å€¤ã‚’å–å¾—ã—ã¾ã™ã€‚\n" "\n" "lxc config set [<remote>:][container] <key> <value>\n" " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šé …ç›®ã«å€¤ã‚’設定ã—ã¾ã™ã€‚\n" "\n" "lxc config unset [<remote>:][container] <key>\n" " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šé …目を削除ã—ã¾ã™ã€‚\n" "\n" "lxc config show [<remote>:][container] [--expanded]\n" " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šã‚’表示ã—ã¾ã™ã€‚\n" "\n" "lxc config edit [<remote>:][container]\n" " 外部エディタを起動ã™ã‚‹ã‹ã€æ¨™æº–入力ã‹ã‚‰èª­ã¿è¾¼ã‚€ã“ã¨ã«ã‚ˆã‚Šã€è¨­å®šã‚’編集ã—ã¾" "ã™ã€‚\n" "\n" "*デãƒã‚¤ã‚¹ã®ç®¡ç†*\n" "\n" "lxc config device add [<remote>:]<container> <device> <type> [key=value...]\n" " コンテナã«ãƒ‡ãƒã‚¤ã‚¹ã‚’追加ã—ã¾ã™ã€‚\n" "\n" "lxc config device get [<remote>:]<container> <device> <key>\n" " デãƒã‚¤ã‚¹ã®ãƒ—ロパティをå–å¾—ã—ã¾ã™ã€‚\n" "\n" "lxc config device set [<remote>:]<container> <device> <key> <value>\n" " デãƒã‚¤ã‚¹ã®ãƒ—ロパティを設定ã—ã¾ã™ã€‚\n" "\n" "lxc config device unset [<remote>:]<container> <device> <key>\n" " デãƒã‚¤ã‚¹ã®ãƒ—ロパティを削除ã—ã¾ã™ã€‚\n" "\n" "lxc config device list [<remote>:]<container>\n" " コンテナã®ãƒ‡ãƒã‚¤ã‚¹ã‚’一覧表示ã—ã¾ã™ã€‚\n" "\n" "lxc config device show [<remote>:]<container>\n" " å…¨ã¦ã®ãƒ‡ãƒã‚¤ã‚¹ã®è©³ç´°ã‚’表示ã—ã¾ã™ã€‚\n" "\n" "lxc config device remove [<remote>:]<container> <name>...\n" " コンテナã‹ã‚‰ãƒ‡ãƒã‚¤ã‚¹ã‚’削除ã—ã¾ã™ã€‚\n" "\n" "*クライアントã®è¨¼æ˜Žæ›¸ã‚¹ãƒˆã‚¢ã®ç®¡ç†*\n" "\n" "lxc config trust list [<remote>:]\n" " ä¿¡é ¼ã™ã‚‹è¨¼æ˜Žæ›¸ã‚’å…¨ã¦è¡¨ç¤ºã—ã¾ã™ã€‚\n" "\n" "lxc config trust add [<remote>:] <certfile.crt>\n" " certfile.crt ã‚’ä¿¡é ¼ã™ã‚‹ãƒ›ã‚¹ãƒˆã«è¿½åŠ ã—ã¾ã™ã€‚\n" "\n" "lxc config trust remove [<remote>:] [hostname|fingerprint]\n" " ä¿¡é ¼ã™ã‚‹ãƒ›ã‚¹ãƒˆã‹ã‚‰è¨¼æ˜Žæ›¸ã‚’消去ã—ã¾ã™ã€‚\n" "\n" "*例*\n" "\n" "cat config.yaml | lxc config edit <container>\n" " config.yaml ã‹ã‚‰èª­ã¿è¾¼ã‚“ã§ã€ã‚³ãƒ³ãƒ†ãƒŠã®è¨­å®šã‚’æ›´æ–°ã—ã¾ã™ã€‚\n" "\n" "lxc config device add [<remote>:]container1 <device-name> disk source=/share/" "c1 path=opt\n" " ホスト㮠/share/c1 をコンテナ内㮠/opt ã«ãƒžã‚¦ãƒ³ãƒˆã—ã¾ã™ã€‚\n" "\n" "lxc config set [<remote>:]<container> limits.cpu 2\n" " コンテナ㮠CPU 制é™å€¤ã‚’ \"2\" ã«è¨­å®šã™ã‚‹ã€‚\n" "\n" "lxc config set core.https_address [::]:8443\n" " IPv4 㨠IPv6 ã®ãƒãƒ¼ãƒˆ 8443 ã§ Listen ã™ã‚‹ã‚ˆã†è¨­å®šã™ã‚‹ã€‚\n" "\n" "lxc config set core.trust_password blah\n" " サーãƒã®ãƒ‘スワードを blah ã«è¨­å®šã™ã‚‹ã€‚" #: lxc/copy.go:23 msgid "" "Usage: lxc copy [<remote>:]<source>[/<snapshot>] [[<remote>:]<destination>] " "[--ephemeral|e]\n" "\n" "Copy containers within or in between LXD instances." msgstr "" "ä½¿ã„æ–¹: lxc copy [<remote>:]<source>[/<snapshot>] [[<remote>:]<destination>] " "[--ephemeral|e]\n" "\n" "LXDインスタンス内もã—ãã¯LXDインスタンス間ã§ã‚³ãƒ³ãƒ†ãƒŠã‚’コピーã—ã¾ã™ã€‚" #: lxc/delete.go:27 msgid "" "Usage: lxc delete [<remote>:]<container>[/<snapshot>] " "[[<remote>:]<container>[/<snapshot>]...]\n" "\n" "Delete containers and snapshots." msgstr "" "ä½¿ã„æ–¹: lxc delete [<remote>:]<container>[/<snapshot>] " "[[<remote>:]<container>[/<snapshot>]...]\n" "\n" "コンテナã¨ã‚³ãƒ³ãƒ†ãƒŠã®ã‚¹ãƒŠãƒƒãƒ—ショットを消去ã—ã¾ã™ã€‚" #: lxc/exec.go:47 msgid "" "Usage: lxc exec [<remote>:]<container> [--mode=auto|interactive|non-" "interactive] [--env KEY=VALUE...] [--] <command line>\n" "\n" "Execute commands in containers.\n" "\n" "Mode defaults to non-interactive, interactive mode is selected if both stdin " "AND stdout are terminals (stderr is ignored)." msgstr "" "ä½¿ã„æ–¹: lxc exec [<remote>:]<container> [--mode=auto|interactive|non-" "interactive] [--env KEY=VALUE...] [--] <command line>\n" "\n" "指定ã—ãŸã‚³ãƒžãƒ³ãƒ‰ã‚’コンテナ内ã§å®Ÿè¡Œã—ã¾ã™ã€‚\n" "\n" "デフォルトã®ãƒ¢ãƒ¼ãƒ‰ã¯ non-interactive ã§ã™ã€‚ã‚‚ã—æ¨™æº–入出力ãŒä¸¡æ–¹ã¨ã‚‚ターミナ" "ル\n" "ã®å ´åˆã¯ interactive モードãŒé¸æŠžã•れã¾ã™ (標準エラー出力ã¯ç„¡è¦–ã•れã¾ã™)。" #: lxc/file.go:33 msgid "" "Usage: lxc file <subcommand> [options]\n" "\n" "Manage files in containers.\n" "\n" "lxc file pull [<remote>:]<container>/<path> [[<remote>:]<container>/" "<path>...] <target path>\n" " Pull files from containers.\n" "\n" "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source path> [<source " "path>...] [<remote>:]<container>/<path>\n" " Push files into containers.\n" "\n" "lxc file edit [<remote>:]<container>/<path>\n" " Edit files in containers using the default text editor.\n" "\n" "*Examples*\n" "lxc file push /etc/hosts foo/etc/hosts\n" " To push /etc/hosts into the container \"foo\".\n" "\n" "lxc file pull foo/etc/hosts .\n" " To pull /etc/hosts from the container and write it to the current " "directory." msgstr "" "ä½¿ã„æ–¹: lxc file <subcommand> [options]\n" "\n" "コンテナ内ã®ãƒ•ァイルを管ç†ã—ã¾ã™ã€‚\n" "\n" "lxc file pull [<remote>:]<container>/<path> [[<remote>:]<container>/" "<path>...] <target path>\n" " コンテナã‹ã‚‰ãƒ•ァイルをå–å¾—ã—ã¾ã™ã€‚\n" "\n" "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source path> [<source " "path>...] [<remote>:]<container>/<path>\n" " コンテナã«ãƒ•ァイルを設置ã—ã¾ã™ã€‚\n" "\n" "lxc file edit [<remote>:]<container>/<path>\n" " デフォルトã®ãƒ†ã‚­ã‚¹ãƒˆã‚¨ãƒ‡ã‚£ã‚¿ã‚’使用ã—ã¦ã‚³ãƒ³ãƒ†ãƒŠå†…ã®ãƒ•ァイルを編集ã—ã¾" "ã™ã€‚\n" "\n" "*例*\n" "lxc file push /etc/hosts foo/etc/hosts\n" " /etc/hosts ã‚’ \"foo\" コンテナ内ã«è¨­ç½®ã—ã¾ã™ã€‚\n" "\n" "lxc file pull foo/etc/hosts .\n" " コンテナã‹ã‚‰ /etc/hosts ã‚’å–å¾—ã—ã€ã‚«ãƒ¬ãƒ³ãƒˆãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒªã«ç½®ãã¾ã™ã€‚" #: lxc/finger.go:15 msgid "" "Usage: lxc finger [<remote>:]\n" "\n" "Check if the LXD server is alive." msgstr "" "ä½¿ã„æ–¹: lxc finger [<remote>:]\n" "\n" "LXD サーãƒãŒå‹•作ã—ã¦ã„ã‚‹ã‹ãƒã‚§ãƒƒã‚¯ã—ã¾ã™ã€‚" #: lxc/help.go:22 msgid "" "Usage: lxc help [--all]\n" "\n" "Help page for the LXD client." msgstr "" "ä½¿ã„æ–¹: lxc help [--all]\n" "\n" "LXD クライアントã®ãƒ˜ãƒ«ãƒ—を表示ã—ã¾ã™ã€‚" #: lxc/image.go:63 msgid "" "Usage: lxc image <subcommand> [options]\n" "\n" "Manipulate container images.\n" "\n" "In LXD containers are created from images. Those images were themselves\n" "either generated from an existing container or downloaded from an image\n" "server.\n" "\n" "When using remote images, LXD will automatically cache images for you\n" "and remove them upon expiration.\n" "\n" "The image unique identifier is the hash (sha-256) of its representation\n" "as a compressed tarball (or for split images, the concatenation of the\n" "metadata and rootfs tarballs).\n" "\n" "Images can be referenced by their full hash, shortest unique partial\n" "hash or alias name (if one is set).\n" "\n" "\n" "lxc image import <tarball> [<rootfs tarball>|<URL>] [<remote>:] [--public] " "[--created-at=ISO-8601] [--expires-at=ISO-8601] [--fingerprint=FINGERPRINT] " "[--alias=ALIAS...] [prop=value]\n" " Import an image tarball (or tarballs) into the LXD image store.\n" "\n" "lxc image copy [<remote>:]<image> <remote>: [--alias=ALIAS...] [--copy-" "aliases] [--public] [--auto-update]\n" " Copy an image from one LXD daemon to another over the network.\n" "\n" " The auto-update flag instructs the server to keep this image up to\n" " date. It requires the source to be an alias and for it to be public.\n" "\n" "lxc image delete [<remote>:]<image> [[<remote>:]<image>...]\n" " Delete one or more images from the LXD image store.\n" "\n" "lxc image export [<remote>:]<image> [target]\n" " Export an image from the LXD image store into a distributable tarball.\n" "\n" " The output target is optional and defaults to the working directory.\n" " The target may be an existing directory, file name, or \"-\" to specify\n" " stdout. The target MUST be a directory when exporting a split image.\n" " If the target is a directory, the image's name (each part's name for\n" " split images) as found in the database will be used for the exported\n" " image. If the target is a file (not a directory and not stdout), then\n" " the appropriate extension will be appended to the provided file name\n" " based on the algorithm used to compress the image.\n" "\n" "lxc image info [<remote>:]<image>\n" " Print everything LXD knows about a given image.\n" "\n" "lxc image list [<remote>:] [filter]\n" " List images in the LXD image store. Filters may be of the\n" " <key>=<value> form for property based filtering, or part of the image\n" " hash or part of the image alias name.\n" "\n" "lxc image show [<remote>:]<image>\n" " Yaml output of the user modifiable properties of an image.\n" "\n" "lxc image edit [<remote>:]<image>\n" " Edit image, either by launching external editor or reading STDIN.\n" " Example: lxc image edit <image> # launch editor\n" " cat image.yaml | lxc image edit <image> # read from image.yaml\n" "\n" "lxc image alias create [<remote>:]<alias> <fingerprint>\n" " Create a new alias for an existing image.\n" "\n" "lxc image alias delete [<remote>:]<alias>\n" " Delete an alias.\n" "\n" "lxc image alias list [<remote>:] [filter]\n" " List the aliases. Filters may be part of the image hash or part of the " "image alias name." msgstr "" "ä½¿ã„æ–¹: lxc image <subcommand> [options]\n" "\n" "コンテナイメージをæ“作ã—ã¾ã™ã€‚\n" "\n" "LXD ã§ã¯ã€ã‚³ãƒ³ãƒ†ãƒŠã¯ã‚¤ãƒ¡ãƒ¼ã‚¸ã‹ã‚‰ä½œã‚‰ã‚Œã¾ã™ã€‚ã“ã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã¯ã€æ—¢å­˜ã®ã‚³ãƒ³ãƒ†ãƒŠ\n" "やイメージサーãƒã‹ã‚‰ãƒ€ã‚¦ãƒ³ãƒ­ãƒ¼ãƒ‰ã—ãŸã‚¤ãƒ¡ãƒ¼ã‚¸ã‹ã‚‰ä½œã‚‰ã‚Œã¾ã™ã€‚\n" "\n" "リモートã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’使ã†å ´åˆã€LXD ã¯è‡ªå‹•çš„ã«ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’キャッシュã—ã¾ã™ã€‚ã\n" "ã—ã¦ã€ã‚¤ãƒ¡ãƒ¼ã‚¸ã®æœŸé™ãŒåˆ‡ã‚Œã‚‹ã¨ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã‚’削除ã—ã¾ã™ã€‚\n" "\n" "イメージ固有ã®è­˜åˆ¥å­ã¯åœ§ç¸®ã•れ㟠tarball (分割イメージã®å ´åˆã¯ã€ãƒ¡ã‚¿ãƒ‡ãƒ¼ã‚¿\n" "㨠rootfs tarball ã‚’çµåˆã—ãŸã‚‚ã®) ã®ãƒãƒƒã‚·ãƒ¥ (sha-256) ã§ã™ã€‚\n" "\n" "イメージã¯å…¨ãƒãƒƒã‚·ãƒ¥æ–‡å­—列ã€ä¸€æ„ã«å®šã¾ã‚‹ãƒãƒƒã‚·ãƒ¥ã®çŸ­ç¸®è¡¨ç¾ã€(設定ã•れã¦ã„\n" "ã‚‹å ´åˆã¯) エイリアスã§å‚ç…§ã§ãã¾ã™ã€‚\n" "\n" "\n" "lxc image import <tarball> [<rootfs tarball>|<URL>] [remote:] [--public] [--" "created-at=ISO-8601] [--expires-at=ISO-8601] [--fingerprint=FINGERPRINT] [--" "alias=ALIAS].. [prop=value]\n" " イメージ㮠tarball (複数もå¯èƒ½) ã‚’ LXD ã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚¹ãƒˆã‚¢ã«ã‚¤ãƒ³ãƒãƒ¼ãƒˆã—ã¾\n" " ã™ã€‚\n" "\n" "lxc image copy [remote:]<image> <remote>: [--alias=ALIAS].. [--copy-aliases] " "[--public] [--auto-update]\n" " ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯çµŒç”±ã§ã‚ã‚‹ LXD デーモンã‹ã‚‰ä»–ã® LXD デーモンã¸ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’\n" " コピーã—ã¾ã™ã€‚\n" "\n" " auto-update フラグã¯ã€ã‚µãƒ¼ãƒãŒã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’最新ã«ä¿ã¤ã‚ˆã†ã«æŒ‡ç¤ºã—ã¾ã™ã€‚イ\n" " メージã®ã‚½ãƒ¼ã‚¹ãŒã‚¨ã‚¤ãƒªã‚¢ã‚¹ã§ã‚りã€public ã§ã‚ã‚‹å¿…è¦ãŒã‚りã¾ã™ã€‚\n" "\n" "lxc image delete [remote:]<image> [[<remote>:]<image>...]\n" " LXD ã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚¹ãƒˆã‚¢ã‹ã‚‰ (ã²ã¨ã¤ä»¥ä¸Šã®) イメージを削除ã—ã¾ã™ã€‚\n" "\n" "lxc image export [<remote>:]<image> [target]\n" " LXD ã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚¹ãƒˆã‚¢ã‹ã‚‰é…布å¯èƒ½ãª tarball ã¨ã—ã¦ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’エクスãƒãƒ¼ãƒˆ\n" " ã—ã¾ã™ã€‚\n" "\n" " å‡ºåŠ›å…ˆã®æŒ‡å®šã¯ã‚ªãƒ—ションã§ã€ãƒ‡ãƒ•ォルトã§ã¯ç¾åœ¨ã®ãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒªã§ã™ã€‚\n" " 出力先ã¯å­˜åœ¨ã™ã‚‹ãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒªã€ãƒ•ァイルåã€æ¨™æº–出力を示㙠\\\"-\\\" ã®ã„\n" " ãšã‚Œã‹ã§ã™ã€‚分割イメージをエクスãƒãƒ¼ãƒˆã™ã‚‹éš›ã¯ã€å‡ºåŠ›å…ˆã¯ãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆ\n" " リã§ãªã‘れã°ãªã‚Šã¾ã›ã‚“。出力先ãŒãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒªã®å ´åˆã€ãƒ‡ãƒ¼ã‚¿ãƒ™ãƒ¼ã‚¹ã§\n" " 見ã¤ã‹ã£ãŸã‚¤ãƒ¡ãƒ¼ã‚¸å (分割イメージã®éƒ¨åˆ†ãれãžã‚Œã®åå‰) をエクスãƒãƒ¼\n" " トã™ã‚‹ã‚¤ãƒ¡ãƒ¼ã‚¸ã«ä½¿ç”¨ã—ã¾ã™ã€‚出力先ãŒãƒ•ァイルã®å ´åˆ (ディレクトリã§\n" " も標準出力ã§ã‚‚ãªã„å ´åˆ)ã€ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’圧縮ã™ã‚‹ã‚¢ãƒ«ã‚´ãƒªã‚ºãƒ ã«ã‚‚ã¨ã¥ã„\n" " ãŸé©åˆ‡ãªæ‹¡å¼µå­ãŒå¯¾è±¡ã®ãƒ•ァイルåã«è¿½åŠ ã•れã¾ã™ã€‚\n" "\n" "lxc image info [<remote>:]<image>\n" " 指定ã—ãŸã‚¤ãƒ¡ãƒ¼ã‚¸ã«ã¤ã„ã¦ã®ã™ã¹ã¦ã®æƒ…報を表示ã—ã¾ã™ã€‚\n" "\n" "lxc image list [<remote>:] [filter]\n" " LXD ã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚¹ãƒˆã‚¢å†…ã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’一覧表示ã—ã¾ã™ã€‚プロパティã§ãƒ•ィルタ\n" " を行ã†å ´åˆã¯ã€ãƒ•ィルタ㯠<key>=<value> ã®å½¢ã«ãªã‚Šã¾ã™ã€‚フィルタã¯ã‚¤ãƒ¡ãƒ¼\n" " ジãƒãƒƒã‚·ãƒ¥ã®ä¸€éƒ¨ã‚„イメージエイリアスåã®ä¸€éƒ¨ã‚‚指定ã§ãã¾ã™ã€‚\n" "\n" "lxc image show [<remote>:]<image>\n" " ユーザãŒå¤‰æ›´ã§ãるプロパティ㮠YAML å½¢å¼ã®å‡ºåŠ›ã‚’è¡Œã„ã¾ã™ã€‚\n" "\n" "lxc image edit [<remote>:]<image>\n" " 外部エディタã¾ãŸã¯æ¨™æº–入力ã‹ã‚‰ã®èª­ã¿è¾¼ã¿ã«ã‚ˆã‚Šã€ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚’編集ã—ã¾ã™ã€‚\n" " 例: lxc image edit <image> # エディタã®èµ·å‹•\n" " cat image.yml | lxc image edit <image> # image.yml ã‹ã‚‰èª­ã¿è¾¼ã¿\n" "\n" "lxc image alias create [<remote>:]<alias> <fingerprint>\n" " 既存ã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã«æ–°ãŸã«ã‚¨ã‚¤ãƒªã‚¢ã‚¹ã‚’作æˆã—ã¾ã™ã€‚\n" "\n" "lxc image alias delete [<remote>:]<alias>\n" " エイリアスを削除ã—ã¾ã™ã€‚\n" "\n" "lxc image alias list [<remote>:] [filter]\n" " エイリアスを一覧表示ã—ã¾ã™ã€‚イメージãƒãƒƒã‚·ãƒ¥ã®ä¸€éƒ¨ã‚„イメージã®ã‚¨ã‚¤ãƒªã‚¢" "ス\n" " åã®ä¸€éƒ¨ã‚’フィルタã¨ã—ã¦æŒ‡å®šã§ãã¾ã™ã€‚" #: lxc/info.go:26 msgid "" "Usage: lxc info [<remote>:][<container>] [--show-log]\n" "\n" "Show container or server information.\n" "\n" "lxc info [<remote>:]<container> [--show-log]\n" " For container information.\n" "\n" "lxc info [<remote>:]\n" " For LXD server information." msgstr "" "ä½¿ã„æ–¹: lxc info [<remote>:][<container>] [--show-log]\n" "\n" "コンテナもã—ãã¯ã‚µãƒ¼ãƒã®æƒ…報を表示ã—ã¾ã™ã€‚\n" "\n" "lxc info [<remote>:]<container> [--show-log]\n" " ã‚³ãƒ³ãƒ†ãƒŠã®æƒ…報を表示ã—ã¾ã™ã€‚\n" "\n" "lxc info [<remote>:]\n" " LXD サーãƒã®æƒ…報を表示ã—ã¾ã™ã€‚" #: lxc/init.go:75 msgid "" "Usage: lxc init [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--" "profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance " "type>]\n" "\n" "Create containers from images.\n" "\n" "Not specifying -p will result in the default profile.\n" "Specifying \"-p\" with no argument will result in no profile.\n" "\n" "Examples:\n" " lxc init ubuntu:16.04 u1" msgstr "" "ä½¿ã„æ–¹: lxc init [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance type>]\n" "\n" "指定ã—ãŸã‚¤ãƒ¡ãƒ¼ã‚¸ã‹ã‚‰ã‚³ãƒ³ãƒ†ãƒŠã‚’åˆæœŸåŒ–ã—ã¾ã™ã€‚\n" "\n" "-p を指定ã—ãªã„å ´åˆã¯ãƒ‡ãƒ•ォルトã®ãƒ—ロファイルを使ã„ã¾ã™ã€‚\n" "\"-p\" ã®ã‚ˆã†ã«å¼•æ•°ãªã—ã§ -p を使ã†ã¨ãƒ—ロファイルãªã—ã¨ãªã‚Šã¾ã™ã€‚\n" "\n" "例:\n" " lxc init ubuntu:16.04 u1" #: lxc/launch.go:20 msgid "" "Usage: lxc launch [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--" "profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance " "type>]\n" "\n" "Create and start containers from images.\n" "\n" "Not specifying -p will result in the default profile.\n" "Specifying \"-p\" with no argument will result in no profile.\n" "\n" "Examples:\n" " lxc launch ubuntu:16.04 u1" msgstr "" "ä½¿ã„æ–¹: lxc launch [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance type>]\n" "\n" "指定ã—ãŸã‚¤ãƒ¡ãƒ¼ã‚¸ã‹ã‚‰ã‚³ãƒ³ãƒ†ãƒŠã‚’èµ·å‹•ã—ã¾ã™ã€‚\n" "\n" "-p を指定ã—ãªã„å ´åˆã¯ãƒ‡ãƒ•ォルトã®ãƒ—ロファイルを使ã„ã¾ã™ã€‚\n" "\"-p\" ã®ã‚ˆã†ã«å¼•æ•°ãªã—ã§ -p を使ã†ã¨ãƒ—ロファイルãªã—ã¨ãªã‚Šã¾ã™ã€‚\n" "\n" "例:\n" " lxc launch ubuntu:16.04 u1" #: lxc/list.go:46 msgid "" "Usage: lxc list [<remote>:] [filters] [--format table|json] [-c <columns>] " "[--fast]\n" "\n" "List the existing containers.\n" "\n" "Default column layout: ns46tS\n" "Fast column layout: nsacPt\n" "\n" "*Filters*\n" "A single keyword like \"web\" which will list any container with a name " "starting by \"web\".\n" "\n" "A regular expression on the container name. (e.g. .*web.*01$).\n" "\n" "A key/value pair referring to a configuration item. For those, the namespace " "can be abbreviated to the smallest unambiguous identifier.\n" " - \"user.blah=abc\" will list all containers with the \"blah\" user " "property set to \"abc\".\n" "\n" " - \"u.blah=abc\" will do the same\n" "\n" " - \"security.privileged=true\" will list all privileged containers\n" "\n" " - \"s.privileged=true\" will do the same\n" "\n" "A regular expression matching a configuration item or its value. (e.g. " "volatile.eth0.hwaddr=00:16:3e:.*).\n" "\n" "*Columns*\n" "The -c option takes a comma separated list of arguments that control\n" "which container attributes to output when displaying in table format.\n" "\n" "Column arguments are either pre-defined shorthand chars (see below),\n" "or (extended) config keys.\n" "\n" "Commas between consecutive shorthand chars are optional.\n" "\n" "Pre-defined column shorthand chars:\n" "\n" " 4 - IPv4 address\n" "\n" " 6 - IPv6 address\n" "\n" " a - Architecture\n" "\n" " c - Creation date\n" "\n" " l - Last used date\n" "\n" " n - Name\n" "\n" " p - PID of the container's init process\n" "\n" " P - Profiles\n" "\n" " s - State\n" "\n" " S - Number of snapshots\n" "\n" " t - Type (persistent or ephemeral)\n" "\n" "*Examples*\n" "lxc list -c ns46\n" " Shows a list of containers using the \"NAME\", \"STATE\", \"IPV4\", " "\"IPV6\" columns." msgstr "" "ä½¿ã„æ–¹: lxc list [<remote>:] [filters] [--format table|json] [-c columns] [--fast]\n" "\n" "コンテナを一覧表示ã—ã¾ã™ã€‚\n" "\n" "デフォルトã®ã‚«ãƒ©ãƒ ãƒ¬ã‚¤ã‚¢ã‚¦ãƒˆ: ns46tS\n" "Fast モードã®ã‚«ãƒ©ãƒ ãƒ¬ã‚¤ã‚¢ã‚¦ãƒˆ: nsacPt\n" "\n" "*フィルタ*\n" "å˜ä¸€ã® \"web\" ã®ã‚ˆã†ãªã‚­ãƒ¼ãƒ¯ãƒ¼ãƒ‰ã‚’指定ã™ã‚‹ã¨ã€åå‰ãŒ \"web\" ã§ã¯ã˜ã¾ã‚‹ã‚³ãƒ³ãƒ†ãƒŠãŒä¸€è¦§è¡¨ç¤ºã•れã¾ã™ã€‚\n" "\n" "コンテナåã®æ­£è¦è¡¨ç¾ (例: .*web.*01$)。\n" "\n" "設定項目ã®ã‚­ãƒ¼ã¨å€¤ã€‚キーã®åå‰ç©ºé–“ã¯ä¸€æ„ã«è­˜åˆ¥ã§ãã‚‹å ´åˆã¯çŸ­ç¸®ã™ã‚‹ã“ã¨ãŒã§\n" "ãã¾ã™:\n" " - \"user.blah=abc\" 㯠\"blah\" ã¨ã„ㆠuser プロパティ㌠\"abc\" ã«è¨­å®šã•れã¦ã„るコンテナをã™ã¹ã¦ä¸€è¦§è¡¨ç¤ºã—ã¾ã™ã€‚\n" "\n" " - \"u.blah=abc\" ã¯ä¸Šè¨˜ã¨åŒã˜æ„味ã«ãªã‚Šã¾ã™ã€‚\n" "\n" " - \"security.privileged=1\" ã¯ç‰¹æ¨©ã‚³ãƒ³ãƒ†ãƒŠã‚’ã™ã¹ã¦ä¸€è¦§è¡¨ç¤ºã—ã¾ã™ã€‚\n" "\n" " - \"s.privilaged=1\" ã¯ä¸Šè¨˜ã¨åŒã˜æ„味ã«ãªã‚Šã¾ã™ã€‚\n" "\n" "設定項目もã—ãã¯å€¤ã¨ãƒžãƒƒãƒã™ã‚‹æ­£è¦è¡¨ç¾ (例:volatile.eth0.hwaddr=00:16:3e:.*)\n" "\n" "*カラム*\n" "\n" "-c オプションã«ã¯ã€è¡¨å½¢å¼ã§è¡¨ç¤ºã™ã‚‹éš›ã«ã©ã®ã‚³ãƒ³ãƒ†ãƒŠã®å±žæ€§ã‚’表示ã™ã‚‹ã‹\n" "を指定ã™ã‚‹ã‚³ãƒ³ãƒžåŒºåˆ‡ã‚Šã®ãƒªã‚¹ãƒˆã‚’指定ã—ã¾ã™ã€‚\n" "\n" "ã‚«ãƒ©ãƒ ã®æŒ‡å®šã¯ã€å®šç¾©æ¸ˆã¿ã®çŸ­ç¸®å½¢ (以下をå‚ç…§) ã‚‚ã—ã㯠(æ‹¡å¼µã•れãŸ)\n" "設定キーã®ã©ã¡ã‚‰ã‹ã‚’指定ã—ã¾ã™ã€‚\n" "\n" "連続ã™ã‚‹çŸ­ç¸®å½¢ã®é–“ã®ã‚³ãƒ³ãƒžã¯çœç•¥ã§ãã¾ã™ã€‚\n" "\n" "çŸ­ç¸®å½¢ã§æŒ‡å®šã§ãる文字:\\n\"\n" "\n" " 4 - IPv4 アドレス\n" "\n" " 6 - IPv6 アドレス\n" "\n" " a - アーキテクãƒãƒ£\n" "\n" " c - ä½œæˆæ—¥\n" "\n" " l - 最終使用日\n" "\n" " n - åå‰\n" "\n" " p - コンテナ㮠init プロセス㮠pid\n" "\n" " P - プロファイル\n" "\n" " s - 状態\n" "\n" " S - ã‚¹ãƒŠãƒƒãƒ—ã‚·ãƒ§ãƒƒãƒˆã®æ•°\n" "\n" " t - タイプ (persistent or ephemeral)\n" "\n" "*例*\n" "lxc list -c ns46\n" " コンテナ㮠\"NAME\"ã€\"STATE\"ã€\"IPV4\"ã€\"IPV6\" を使ã£ã¦ä¸€è¦§è¡¨ç¤ºã—ã¾ã™ã€‚" #: lxc/manpage.go:20 msgid "" "Usage: lxc manpage <directory>\n" "\n" "Generate all the LXD manpages." msgstr "" "ä½¿ã„æ–¹: lxc manpage <directory>\n" "\n" "LXD ã® manpage ã‚’ã™ã¹ã¦ç”Ÿæˆã—ã¾ã™ã€‚" #: lxc/monitor.go:41 msgid "" "Usage: lxc monitor [<remote>:] [--type=TYPE...]\n" "\n" "Monitor a local or remote LXD server.\n" "\n" "By default the monitor will listen to all message types.\n" "\n" "Message types to listen for can be specified with --type.\n" "\n" "*Examples*\n" "lxc monitor --type=logging\n" " Only show log message." msgstr "" "ä½¿ã„æ–¹: lxc monitor [<remote>:] [--type=TYPE...]\n" "\n" "ローカルã¾ãŸã¯ãƒªãƒ¢ãƒ¼ãƒˆã® LXD サーãƒã®å‹•作をモニタリングã—ã¾ã™ã€‚\n" "\n" "デフォルトã§ã¯å…¨ã¦ã®ã‚¿ã‚¤ãƒ—をモニタリングã—ã¾ã™ã€‚\n" "\n" "--type ã«ã‚ˆã‚Šã€ãƒ¢ãƒ‹ã‚¿ãƒªãƒ³ã‚°ã™ã‚‹ã‚¿ã‚¤ãƒ—を指定ã§ãã¾ã™ã€‚\n" "\n" "例:\n" "lxc monitor --type=logging\n" " ログメッセージã®ã¿è¡¨ç¤ºã—ã¾ã™ã€‚" #: lxc/move.go:20 msgid "" "Usage: lxc move [<remote>:]<container>[/<snapshot>] [<remote>:][<container>[/" "<snapshot>]]\n" "\n" "Move containers within or in between LXD instances.\n" "\n" "lxc move [<remote>:]<source container> [<remote>:][<destination container>]\n" " Move a container between two hosts, renaming it if destination name " "differs.\n" "\n" "lxc move <old name> <new name>\n" " Rename a local container.\n" "\n" "lxc move <container>/<old snapshot name> <container>/<new snapshot name>\n" " Rename a snapshot." msgstr "" "ä½¿ã„æ–¹: lxc move [<remote>:]<container>[/<snapshot>] [<remote>:]" "[<container>[/<snapshot>]]\n" "\n" "LXD ホスト内ã€ã‚‚ã—ã㯠LXD ホスト間ã§ã‚³ãƒ³ãƒ†ãƒŠã‚’移動ã—ã¾ã™ã€‚\n" "\n" "lxc move [<remote>:]<source container> [<remote>:][<destination container>]\n" " 2 ã¤ã®ãƒ›ã‚¹ãƒˆé–“ã§ã‚³ãƒ³ãƒ†ãƒŠã‚’移動ã—ã¾ã™ã€‚コピー先ã®åå‰ãŒå…ƒã¨é•ã†å ´åˆã¯\n" " åŒæ™‚ã«ãƒªãƒãƒ¼ãƒ ã•れã¾ã™ã€‚\n" "\n" "lxc move <old name> <new name>\n" " ローカルã®ã‚³ãƒ³ãƒ†ãƒŠã‚’リãƒãƒ¼ãƒ ã—ã¾ã™ã€‚\n" "\n" "lxc move <container>/<old snapshot name> <container>/<new snapshot name>\n" " スナップショットをリãƒãƒ¼ãƒ ã—ã¾ã™ã€‚" #: lxc/profile.go:49 msgid "" "Usage: lxc profile <subcommand> [options]\n" "\n" "Manage container configuration profiles.\n" "\n" "*Profile configuration*\n" "lxc profile list [<remote>:]\n" " List available profiles.\n" "\n" "lxc profile show [<remote>:]<profile>\n" " Show details of a profile.\n" "\n" "lxc profile create [<remote>:]<profile>\n" " Create a profile.\n" "\n" "lxc profile copy [<remote>:]<profile> [<remote>:]<profile>\n" " Copy the profile.\n" "\n" "lxc profile get [<remote>:]<profile> <key>\n" " Get profile configuration.\n" "\n" "lxc profile set [<remote>:]<profile> <key> <value>\n" " Set profile configuration.\n" "\n" "lxc profile unset [<remote>:]<profile> <key>\n" " Unset profile configuration.\n" "\n" "lxc profile delete [<remote>:]<profile>\n" " Delete a profile.\n" "\n" "lxc profile edit [<remote>:]<profile>\n" " Edit profile, either by launching external editor or reading STDIN.\n" "\n" "*Profile assignment*\n" "lxc profile apply [<remote>:]<container> <profiles>\n" " Replace the current set of profiles for the container by the one " "provided.\n" "\n" "*Device management*\n" "lxc profile device list [<remote>:]<profile>\n" " List devices in the given profile.\n" "\n" "lxc profile device show [<remote>:]<profile>\n" " Show full device details in the given profile.\n" "\n" "lxc profile device remove [<remote>:]<profile> <name>\n" " Remove a device from a profile.\n" "\n" "lxc profile device get [<remote>:]<profile> <name> <key>\n" " Get a device property.\n" "\n" "lxc profile device set [<remote>:]<profile> <name> <key> <value>\n" " Set a device property.\n" "\n" "lxc profile device unset [<remote>:]<profile> <name> <key>\n" " Unset a device property.\n" "\n" "lxc profile device add [<remote>:]<profile> <device> <type> [key=value...]\n" " Add a profile device, such as a disk or a nic, to the containers using " "the specified profile.\n" "\n" "*Examples*\n" "cat profile.yaml | lxc profile edit <profile>\n" " Update a profile using the content of profile.yaml\n" "\n" "lxc profile apply foo default,bar\n" " Set the profiles for \"foo\" to \"default\" and \"bar\".\n" "\n" "lxc profile apply foo default\n" " Reset \"foo\" to only using the \"default\" profile.\n" "\n" "lxc profile apply foo ''\n" " Remove all profile from \"foo\"" msgstr "" "ä½¿ã„æ–¹: lxc profile <subcommand> [options]\n" "\n" "設定プロファイルを管ç†ã—ã¾ã™ã€‚\n" "\n" "*プロファイル設定*\n" "lxc profile list [<remote>:]\n" " 利用å¯èƒ½ãªãƒ—ロファイルを一覧ã—ã¾ã™ã€‚\n" "\n" "lxc profile show [<remote>:]<profile>\n" " プロファイルã®è©³ç´°ã‚’表示ã—ã¾ã™ã€‚\n" "\n" "lxc profile create [<remote>:]<profile>\n" " プロファイルを作æˆã—ã¾ã™ã€‚\n" "\n" "lxc profile copy [<remote>:]<profile> [<remote>:]<profile>\n" " プロファイルをコピーã—ã¾ã™ã€‚\n" "\n" "lxc profile get [<remote>:]<profile> <key>\n" " プロファイルã®è¨­å®šã‚’å–å¾—ã—ã¾ã™ã€‚\n" "\n" "lxc profile set [<remote>:]<profile> <key> <value>\n" " プロファイルã®è¨­å®šã‚’設定ã—ã¾ã™ã€‚\n" "\n" "lxc profile unset [<remote>:]<profile> <key>\n" " プロファイルã‹ã‚‰è¨­å®šé …目を削除ã—ã¾ã™ã€‚\n" "\n" "lxc profile delete [<remote>:]<profile>\n" " プロファイルを削除ã—ã¾ã™ã€‚\n" "\n" "lxc profile edit [<remote>:]<profile>\n" " プロファイルを編集ã—ã¾ã™ã€‚外部エディタもã—ãã¯STDINã‹ã‚‰èª­ã¿è¾¼ã¿ã¾ã™ã€‚\n" "\n" "*プロファイルã®å‰²ã‚Šå½“ã¦*\n" "lxc profile apply [<remote>:]<container> <profiles>\n" " コンテナã®ç¾åœ¨ã®ãƒ—ロファイルを指定ã—ãŸãƒ—ロファイルã§ç½®ãæ›ãˆã¾ã™ã€‚\n" "\n" "*デãƒã‚¤ã‚¹ç®¡ç†*\n" "lxc profile device list [<remote>:]<profile>\n" " 指定ã—ãŸãƒ—ロファイル内ã®ãƒ‡ãƒã‚¤ã‚¹ã‚’一覧表示ã—ã¾ã™\n" "\n" "lxc profile device show [<remote>:]<profile>\n" " 指定ã—ãŸãƒ—ロファイル内ã®å…¨ãƒ‡ãƒã‚¤ã‚¹ã®è©³ç´°ã‚’表示ã—ã¾ã™\n" "\n" "lxc profile device remove [<remote>:]<profile> <name>\n" " プロファイルã‹ã‚‰ãƒ‡ãƒã‚¤ã‚¹ã‚’削除ã—ã¾ã™\n" "\n" "lxc profile device get [<remote>:]<profile> <name> <key>\n" " デãƒã‚¤ã‚¹ãƒ—ロパティをå–å¾—ã—ã¾ã™\n" "\n" "lxc profile device set [<remote>:]<profile> <name> <key> <value>\n" " デãƒã‚¤ã‚¹ãƒ—ロパティを設定ã—ã¾ã™\n" "\n" "lxc profile device unset <[remote:]profile> <name> <key>\n" " デãƒã‚¤ã‚¹ãƒ—ロパティを削除ã—ã¾ã™\n" "\n" "lxc profile device add [<remote>:]<profile> <device> <type> [key=value...]\n" " ディスクやNICã®ã‚ˆã†ãªãƒ—ロファイルデãƒã‚¤ã‚¹ã‚’指定ã—ãŸãƒ—ロファイルを使ã£ã¦\n" " コンテナã«è¿½åŠ ã—ã¾ã™ã€‚\n" "\n" "*例*\n" "cat profile.yaml | lxc profile edit <profile>\n" " profile.yaml ã®å†…容ã§ãƒ—ロファイルを更新ã—ã¾ã™ã€‚\n" "\n" "lxc profile apply foo default,bar\n" " \"default\" 㨠\"bar\" をプロファイル \"foo\" ã«è¨­å®šã—ã¾ã™ã€‚\n" "\n" "lxc profile apply foo default\n" " \"foo\" プロファイルを \"default\" プロファイルã®å†…容ã®ã¿ã«ãƒªã‚»ãƒƒãƒˆã—\n" " ã¾ã™ã€‚\n" "\n" "lxc profile apply foo ''\n" " \"foo\" ã‹ã‚‰ã™ã¹ã¦ã®ãƒ—ロファイルを削除ã—ã¾ã™ã€‚" #: lxc/publish.go:27 msgid "" "Usage: lxc publish [<remote>:]<container>[/<snapshot>] [<remote>:] [--" "alias=ALIAS...] [prop-key=prop-value...]\n" "\n" "Publish containers as images." msgstr "" "ä½¿ã„æ–¹: lxc publish [<remote>:]<container>[/<snapshot>] [<remote>:] [--" "alias=ALIAS...] [prop-key=prop-value...]\n" "\n" "イメージã¨ã—ã¦ã‚³ãƒ³ãƒ†ãƒŠã‚’ publish ã—ã¾ã™ã€‚" #: lxc/remote.go:39 msgid "" "Usage: lxc remote <subcommand> [options]\n" "\n" "Manage the list of remote LXD servers.\n" "\n" "lxc remote add <remote> <IP|FQDN|URL> [--accept-certificate] [--" "password=PASSWORD] [--public] [--protocol=PROTOCOL]\n" " Add the remote <remote> at <url>.\n" "\n" "lxc remote remove <remote>\n" " Remove the remote <remote>.\n" "\n" "lxc remote list\n" " List all remotes.\n" "\n" "lxc remote rename <old name> <new name>\n" " Rename remote <old name> to <new name>.\n" "\n" "lxc remote set-url <remote> <url>\n" " Update <remote>'s url to <url>.\n" "\n" "lxc remote set-default <remote>\n" " Set the default remote.\n" "\n" "lxc remote get-default\n" " Print the default remote." msgstr "" "ä½¿ã„æ–¹: lxc remote <subcommand> [options]\n" "\n" "リモート㮠LXD サーãƒã®ãƒªã‚¹ãƒˆã‚’管ç†ã—ã¾ã™ã€‚\n" "\n" "lxc remote add <remote> <IP|FQDN|URL> [--accept-certificate] [--" "password=PASSWORD] [--public] [--protocol=PROTOCOL]\n" " <url> をリモートホスト <remote> ã¨ã—ã¦è¿½åŠ ã—ã¾ã™ã€‚\n" "\n" "lxc remote remove <remote>\n" " リモートホスト <remote> を削除ã—ã¾ã™ã€‚\n" "\n" "lxc remote list\n" " リモートホストを全ã¦ä¸€è¦§è¡¨ç¤ºã—ã¾ã™ã€‚\n" "\n" "lxc remote rename <old name> <new name>\n" " リモートホストã®åå‰ã‚’ <old name> ã‹ã‚‰ <new name> ã«å¤‰æ›´ã—ã¾ã™ã€‚\n" "\n" "lxc remote set-url <remote> <url>\n" " <remote> ã® url ã‚’ <url> ã«æ›´æ–°ã—ã¾ã™ã€‚\n" "\n" "lxc remote set-default <remote>\n" " <remote> をデフォルトã®ãƒªãƒ¢ãƒ¼ãƒˆãƒ›ã‚¹ãƒˆã«è¨­å®šã—ã¾ã™ã€‚\n" "\n" "lxc remote get-default\n" " デフォルトã«è¨­å®šã•れã¦ã„るリモートホストを表示ã—ã¾ã™ã€‚" #: lxc/restore.go:22 msgid "" "Usage: lxc restore [<remote>:]<container> <snapshot> [--stateful]\n" "\n" "Restore containers from snapshots.\n" "\n" "If --stateful is passed, then the running state will be restored too.\n" "\n" "*Examples*\n" "lxc snapshot u1 snap0\n" " Create the snapshot.\n" "\n" "lxc restore u1 snap0\n" " Restore the snapshot." msgstr "" "ä½¿ã„æ–¹: lxc restore [<remote>:]<container> <snapshot> [--stateful]\n" "\n" "スナップショットã‹ã‚‰ã‚³ãƒ³ãƒ†ãƒŠã‚’リストアã—ã¾ã™ã€‚\n" "\n" "--stateful を指定ã™ã‚‹ã¨ã€å®Ÿè¡ŒçŠ¶æ…‹ã‚‚ãƒªã‚¹ãƒˆã‚¢ã•れã¾ã™ã€‚\n" "\n" "*例*\n" "lxc snapshot u1 snap0\n" " スナップショットを作æˆã—ã¾ã™ã€‚\n" "\n" "lxc restore u1 snap0\n" " スナップショットã‹ã‚‰ãƒªã‚¹ãƒˆã‚¢ã—ã¾ã™ã€‚" #: lxc/snapshot.go:22 msgid "" "Usage: lxc snapshot [<remote>:]<container> <snapshot name> [--stateful]\n" "\n" "Create container snapshots.\n" "\n" "When --stateful is used, LXD attempts to checkpoint the container's\n" "running state, including process memory state, TCP connections, ...\n" "\n" "*Examples*\n" "lxc snapshot u1 snap0\n" " Create a snapshot of \"u1\" called \"snap0\"." msgstr "" "ä½¿ã„æ–¹: lxc snapshot [<remote>:]<container> <snapshot name> [--stateful]\n" "\n" "コンテナã®ã‚¹ãƒŠãƒƒãƒ—ショットを作æˆã—ã¾ã™ã€‚\n" "\n" "--stateful を指定ã™ã‚‹ã¨ã€LXD ã¯ãƒ—ロセスã®ãƒ¡ãƒ¢ãƒªçŠ¶æ…‹ã€TCP 接続ãªã©ã‚’å«\n" "ã‚€ã€ã‚³ãƒ³ãƒ†ãƒŠã®å®Ÿè¡ŒçŠ¶æ…‹ã‚’ãƒã‚§ãƒƒã‚¯ãƒã‚¤ãƒ³ãƒˆã—よã†ã¨ã—ã¾ã™ã€‚\n" "\n" "*例*\n" "lxc snapshot u1 snap0\n" " \"u1\" ã®ã‚¹ãƒŠãƒƒãƒ—ショットを \"snap0\" ã¨ã„ã†åå‰ã§ä½œæˆã—ã¾ã™ã€‚" #: lxc/version.go:18 msgid "" "Usage: lxc version\n" "\n" "Print the version number of this client tool." msgstr "" "ä½¿ã„æ–¹: lxc version\n" "\n" "ãŠä½¿ã„ã®ã‚¯ãƒ©ã‚¤ã‚¢ãƒ³ãƒˆã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ç•ªå·ã‚’表示ã—ã¾ã™ã€‚" #: lxc/delete.go:46 msgid "User aborted delete operation." msgstr "ユーザãŒå‰Šé™¤æ“作を中断ã—ã¾ã—ãŸã€‚" #: lxc/utils.go:320 msgid "" "User signaled us three times, exiting. The remote operation will keep " "running." msgstr "ユーザã‹ã‚‰ã®ã‚·ã‚°ãƒŠãƒ«ã‚’ 3 度å—ä¿¡ã—ãŸã®ã§ exit ã—ã¾ã—ãŸã€‚リモートæ“作ã¯å®Ÿè¡Œã—ç¶šã‘ã¾ã™ã€‚" #: lxc/restore.go:38 msgid "" "Whether or not to restore the container's running state from snapshot (if " "available)" msgstr "" "スナップショットã‹ã‚‰ã‚³ãƒ³ãƒ†ãƒŠã®ç¨¼å‹•状態をリストアã™ã‚‹ã‹ã©ã†ã‹ (å–å¾—å¯èƒ½ãªå ´åˆ)" #: lxc/snapshot.go:36 msgid "Whether or not to snapshot the container's running state" msgstr "コンテナã®ç¨¼å‹•状態ã®ã‚¹ãƒŠãƒƒãƒ—ショットをå–å¾—ã™ã‚‹ã‹ã©ã†ã‹" #: lxc/remote.go:340 lxc/remote.go:345 msgid "YES" msgstr "" #: lxc/copy.go:49 msgid "You must specify a source container name" msgstr "コピー元ã®ã‚³ãƒ³ãƒ†ãƒŠåを指定ã—ã¦ãã ã•ã„" #: lxc/main.go:68 msgid "`lxc config profile` is deprecated, please use `lxc profile`" msgstr "`lxc config profile` ã¯å»ƒæ­¢ã•れã¾ã—ãŸã€‚`lxc profile` を使ã£ã¦ãã ã•ã„" #: lxc/remote.go:328 msgid "can't remove the default remote" msgstr "デフォルトã®ãƒªãƒ¢ãƒ¼ãƒˆã¯å‰Šé™¤ã§ãã¾ã›ã‚“" #: lxc/remote.go:354 msgid "default" msgstr "" #: lxc/init.go:276 msgid "didn't get any affected image, container or snapshot from server" msgstr "" "サーãƒã‹ã‚‰å¤‰æ›´ã•れãŸã‚¤ãƒ¡ãƒ¼ã‚¸ã€ã‚³ãƒ³ãƒ†ãƒŠã€ã‚¹ãƒŠãƒƒãƒ—ショットをå–å¾—ã§ãã¾ã›ã‚“ã§\n" "ã—ãŸ" #: lxc/image.go:406 msgid "disabled" msgstr "無効" #: lxc/image.go:408 msgid "enabled" msgstr "有効" #: lxc/action.go:134 lxc/main.go:29 lxc/main.go:178 #, c-format msgid "error: %v" msgstr "エラー: %v" #: lxc/help.go:37 lxc/main.go:124 #, c-format msgid "error: unknown command: %s" msgstr "エラー: 未知ã®ã‚³ãƒžãƒ³ãƒ‰: %s" #: lxc/image.go:396 lxc/image.go:401 lxc/image.go:854 msgid "no" msgstr "" #: lxc/remote.go:182 msgid "ok (y/n)?" msgstr "ok (y/n)?" #: lxc/main.go:313 lxc/main.go:317 #, c-format msgid "processing aliases failed %s\n" msgstr "エイリアスã®å‡¦ç†ãŒå¤±æ•—ã—ã¾ã—㟠%s\n" #: lxc/remote.go:390 #, c-format msgid "remote %s already exists" msgstr "リモート %s ã¯æ—¢ã«å­˜åœ¨ã—ã¾ã™" #: lxc/remote.go:320 lxc/remote.go:382 lxc/remote.go:417 lxc/remote.go:433 #, c-format msgid "remote %s doesn't exist" msgstr "リモート %s ã¯å­˜åœ¨ã—ã¾ã›ã‚“" #: lxc/remote.go:303 #, c-format msgid "remote %s exists as <%s>" msgstr "リモート %s 㯠<%s> ã¨ã—ã¦å­˜åœ¨ã—ã¾ã™" #: lxc/remote.go:324 lxc/remote.go:386 lxc/remote.go:421 #, c-format msgid "remote %s is static and cannot be modified" msgstr "リモート %s 㯠static ã§ã™ã®ã§å¤‰æ›´ã§ãã¾ã›ã‚“" #: lxc/info.go:219 msgid "stateful" msgstr "" #: lxc/info.go:221 msgid "stateless" msgstr "" #: lxc/info.go:215 #, c-format msgid "taken at %s" msgstr "%s ã«å–å¾—ã—ã¾ã—ãŸ" #: lxc/main.go:252 msgid "wrong number of subcommand arguments" msgstr "サブコマンドã®å¼•æ•°ã®æ•°ãŒæ­£ã—ãã‚りã¾ã›ã‚“" #: lxc/delete.go:45 lxc/image.go:398 lxc/image.go:403 lxc/image.go:858 msgid "yes" msgstr "" #~ msgid "Unable to read remote TLS certificate" #~ msgstr "リモート㮠TLS 証明書を読ã‚ã¾ã›ã‚“" #~ msgid "can't copy to the same container name" #~ msgstr "åŒã˜ã‚³ãƒ³ãƒ†ãƒŠåã¸ã¯ã‚³ãƒ”ーã§ãã¾ã›ã‚“" #~ msgid "not all the profiles from the source exist on the target" #~ msgstr "コピー元ã®å…¨ã¦ã®ãƒ—ロファイルãŒã‚¿ãƒ¼ã‚²ãƒƒãƒˆã«å­˜åœ¨ã—ã¾ã›ã‚“" #~ msgid "Output is in %s" #~ msgstr "%s ã«å‡ºåŠ›ã•れã¾ã™" #~ msgid "bad number of things scanned from image, container or snapshot" #~ msgstr "" #~ "イメージã€ã‚³ãƒ³ãƒ†ãƒŠã€ã‚¹ãƒŠãƒƒãƒ—ショットã®ã„ãšã‚Œã‹ã‹ã‚‰ã‚¹ã‚­ãƒ£ãƒ³ã•ã‚ŒãŸæ•°ãŒä¸æ­£" #~ msgid "got bad version" #~ msgstr "䏿­£ãªãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’å¾—ã¾ã—ãŸ" #~ msgid "bad result type from action" #~ msgstr "アクションã‹ã‚‰ã®çµæžœã‚¿ã‚¤ãƒ—ãŒä¸æ­£ã§ã™" #~ msgid "unreachable return reached" #~ msgstr "到é”ã—ãªã„ã¯ãšã®returnã«åˆ°é”ã—ã¾ã—ãŸ" #~ msgid "Available commands:" #~ msgstr "使用å¯èƒ½ãªã‚³ãƒžãƒ³ãƒ‰:" #, fuzzy #~ msgid "" #~ "Changes state of one or more containers to %s.\n" #~ "\n" #~ "lxc %s <name> [<name>...]%s" #~ msgstr "" #~ "1ã¤ã¾ãŸã¯è¤‡æ•°ã®ã‚³ãƒ³ãƒ†ãƒŠã®çŠ¶æ…‹ã‚’ %s ã«å¤‰æ›´ã—ã¾ã™ã€‚\n" #~ "\n" #~ "lxc %s <name> [<name>...]" #~ msgid "" #~ "Copy containers within or in between lxd instances.\n" #~ "\n" #~ "lxc copy [remote:]<source container> [remote:]<destination container> [--" #~ "ephemeral|e]" #~ msgstr "" #~ "LXDインスタンス内もã—ãã¯LXDインスタンス間ã§ã‚³ãƒ³ãƒ†ãƒŠã‚’コピーã—ã¾ã™ã€‚\n" #~ "\n" #~ "lxc copy [remote:]<source container> [remote:]<destination container> [--" #~ "ephemeral|e]" #~ msgid "" #~ "Fingers the LXD instance to check if it is up and working.\n" #~ "\n" #~ "lxc finger <remote>" #~ msgstr "" #~ "LXDインスタンスãŒç¨¼åƒä¸­ã‹ã‚’確èªã—ã¾ã™ã€‚\n" #~ "\n" #~ "lxc finger <remote>" #~ msgid "" #~ "List information on LXD servers and containers.\n" #~ "\n" #~ "For a container:\n" #~ " lxc info [<remote>:]container [--show-log]\n" #~ "\n" #~ "For a server:\n" #~ " lxc info [<remote>:]" #~ msgstr "" #~ "LXD サーãƒã¨ã‚³ãƒ³ãƒ†ãƒŠã®æƒ…報を一覧表示ã—ã¾ã™ã€‚\n" #~ "\n" #~ "コンテナ情報:\n" #~ " lxc info [<remote>:]container [--show-log]\n" #~ "\n" #~ "ã‚µãƒ¼ãƒæƒ…å ±:\n" #~ " lxc info [<remote>:]" #, fuzzy #~ msgid "" #~ "Manage configuration.\n" #~ "\n" #~ "lxc config device add <[remote:]container> <name> <type> " #~ "[key=value]... Add a device to a container.\n" #~ "lxc config device get <[remote:]container> <name> " #~ "<key> Get a device property.\n" #~ "lxc config device set <[remote:]container> <name> <key> " #~ "<value> Set a device property.\n" #~ "lxc config device unset <[remote:]container> <name> " #~ "<key> Unset a device property.\n" #~ "lxc config device list " #~ "<[remote:]container> List devices for " #~ "container.\n" #~ "lxc config device show " #~ "<[remote:]container> Show full device " #~ "details for container.\n" #~ "lxc config device remove <[remote:]container> " #~ "<name> Remove device from container.\n" #~ "\n" #~ "lxc config get [remote:][container] " #~ "<key> Get container or server " #~ "configuration key.\n" #~ "lxc config set [remote:][container] <key> " #~ "<value> Set container or server configuration " #~ "key.\n" #~ "lxc config unset [remote:][container] " #~ "<key> Unset container or server " #~ "configuration key.\n" #~ "lxc config show [remote:][container] [--" #~ "expanded] Show container or server " #~ "configuration.\n" #~ "lxc config edit [remote:]" #~ "[container] Edit container or " #~ "server configuration in external editor.\n" #~ " Edit configuration, either by launching external editor or reading " #~ "STDIN.\n" #~ " Example: lxc config edit <container> # launch editor\n" #~ " cat config.yaml | lxc config edit <config> # read from " #~ "config.yaml\n" #~ "\n" #~ "lxc config trust list " #~ "[remote] List all trusted " #~ "certs.\n" #~ "lxc config trust add [remote] <certfile." #~ "crt> Add certfile.crt to trusted hosts.\n" #~ "lxc config trust remove [remote] [hostname|" #~ "fingerprint] Remove the cert from trusted hosts.\n" #~ "\n" #~ "Examples:\n" #~ "To mount host's /share/c1 onto /opt in the container:\n" #~ " lxc config device add [remote:]container1 <device-name> disk source=/" #~ "share/c1 path=opt\n" #~ "\n" #~ "To set an lxc config value:\n" #~ " lxc config set [remote:]<container> raw.lxc 'lxc.aa_allow_incomplete " #~ "= 1'\n" #~ "\n" #~ "To listen on IPv4 and IPv6 port 8443 (you can omit the 8443 its the " #~ "default):\n" #~ " lxc config set core.https_address [::]:8443\n" #~ "\n" #~ "To set the server trust password:\n" #~ " lxc config set core.trust_password blah" #~ msgstr "" #~ "設定を管ç†ã—ã¾ã™ã€‚\n" #~ "\n" #~ "lxc config device add <[remote:]container> <name> <type> [key=value]...\n" #~ " コンテナã«ãƒ‡ãƒã‚¤ã‚¹ã‚’追加ã—ã¾ã™ã€‚\n" #~ "lxc config device get <[remote:]container> <name> <key>\n" #~ " デãƒã‚¤ã‚¹ã®ãƒ—ロパティをå–å¾—ã—ã¾ã™ã€‚\n" #~ "lxc config device set <[remote:]container> <name> <key> <value>\n" #~ " デãƒã‚¤ã‚¹ã®ãƒ—ロパティを設定ã—ã¾ã™ã€‚\n" #~ "lxc config device unset <[remote:]container> <name> <key>\n" #~ " デãƒã‚¤ã‚¹ã®ãƒ—ロパティを削除ã—ã¾ã™ã€‚\n" #~ "lxc config device list <[remote:]container>\n" #~ " コンテナã®ãƒ‡ãƒã‚¤ã‚¹ã‚’一覧表示ã—ã¾ã™ã€‚\n" #~ "lxc config device show <[remote:]container>\n" #~ " å…¨ã¦ã®ãƒ‡ãƒã‚¤ã‚¹ã®è©³ç´°ã‚’表示ã—ã¾ã™ã€‚\n" #~ "lxc config device remove <[remote:]container> <name>\n" #~ " コンテナã‹ã‚‰ãƒ‡ãƒã‚¤ã‚¹ã‚’削除ã—ã¾ã™ã€‚\n" #~ "\n" #~ "lxc config get [remote:][container] <key>\n" #~ " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šé …ç›®ã®å€¤ã‚’å–å¾—ã—ã¾ã™ã€‚\n" #~ "lxc config set [remote:][container] <key> <value>\n" #~ " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šé …ç›®ã«å€¤ã‚’設定ã—ã¾ã™ã€‚\n" #~ "lxc config unset [remote:][container] <key>\n" #~ " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šé …目を削除ã—ã¾ã™ã€‚\n" #~ "lxc config show [remote:][container] [--expanded]\n" #~ " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šã‚’表示ã—ã¾ã™ã€‚\n" #~ "lxc config edit [remote:][container]\n" #~ " コンテナもã—ãã¯ã‚µãƒ¼ãƒã®è¨­å®šã‚’外部エディタã§ç·¨é›†ã—ã¾ã™ã€‚\n" #~ " 設定ã®ç·¨é›†ã¯å¤–部エディタを起動ã™ã‚‹ã‹ã€æ¨™æº–入力ã‹ã‚‰ã®èª­ã¿è¾¼ã¿ã§è¡Œã„ã¾" #~ "ã™ã€‚\n" #~ " 例: lxc config edit <container> # エディタã®èµ·å‹•\n" #~ " cat config.yml | lxc config edit <config> # config.ymlã‹ã‚‰èª­ã¿è¾¼" #~ "ã¿\n" #~ "\n" #~ "lxc config trust list [remote]\n" #~ " ä¿¡é ¼ã™ã‚‹è¨¼æ˜Žæ›¸ã‚’å…¨ã¦è¡¨ç¤ºã—ã¾ã™ã€‚\n" #~ "lxc config trust add [remote] <certfile.crt>\n" #~ " certfile.crt ã‚’ä¿¡é ¼ã™ã‚‹ãƒ›ã‚¹ãƒˆã«è¿½åŠ ã—ã¾ã™ã€‚\n" #~ "lxc config trust remove [remote] [hostname|fingerprint]\n" #~ " ä¿¡é ¼ã™ã‚‹ãƒ›ã‚¹ãƒˆã‹ã‚‰è¨¼æ˜Žæ›¸ã‚’消去ã—ã¾ã™ã€‚\n" #~ "\n" #~ "例:\n" #~ "ホスト㮠/share/c1 をコンテナ内㮠/opt ã«ãƒžã‚¦ãƒ³ãƒˆã™ã‚‹ã«ã¯:\n" #~ " lxc config device add [remote:]container1 <device-name> disk source=/" #~ "share/c1 path=opt\n" #~ "\n" #~ "lxc 設定項目ã«å€¤ã‚’設定ã™ã‚‹ã«ã¯:\n" #~ " lxc config set [remote:]<container> raw.lxc 'lxc.aa_allow_incomplete " #~ "= 1'\n" #~ "\n" #~ "IPv4 㨠IPv6 ã®ãƒãƒ¼ãƒˆ 8443 ã§ Listen ã™ã‚‹ã«ã¯\n" #~ "(8443 ã¯ãƒ‡ãƒ•ォルトãªã®ã§çœç•¥ã§ãã¾ã™):\n" #~ " lxc config set core.https_address [::]:8443\n" #~ "\n" #~ "サーãƒã®ãƒ‘スワードを設定ã™ã‚‹ã«ã¯:\n" #~ " lxc config set core.trust_password blah" #~ msgid "" #~ "Manage files on a container.\n" #~ "\n" #~ "lxc file pull <source> [<source>...] <target>\n" #~ "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source> " #~ "[<source>...] <target>\n" #~ "lxc file edit <file>\n" #~ "\n" #~ "<source> in the case of pull, <target> in the case of push and <file> in " #~ "the case of edit are <container name>/<path>" #~ msgstr "" #~ "コンテナ上ã®ãƒ•ァイルを管ç†ã—ã¾ã™ã€‚\n" #~ "\n" #~ "lxc file pull <source> [<source>...] <target>\n" #~ "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source> " #~ "[<source>...] <target>\n" #~ "lxc file edit <file>\n" #~ "\n" #~ "pull ã®å ´åˆã® <source>ã€push ã®å ´åˆã® <target>ã€edit ã®å ´åˆã® <file> ã¯ã€" #~ "ã„\n" #~ "ãšã‚Œã‚‚ <container name>/<path> ã®å½¢å¼ã§ã™ã€‚" #~ msgid "" #~ "Presents details on how to use LXD.\n" #~ "\n" #~ "lxd help [--all]" #~ msgstr "" #~ "LXDã®ä½¿ã„æ–¹ã®è©³ç´°ã‚’表示ã—ã¾ã™ã€‚\n" #~ "\n" #~ "lxd help [--all]" #~ msgid "Usage: %s" #~ msgstr "ä½¿ã„æ–¹: %s" #~ msgid "Profile %s added to %s" #~ msgstr "プロファイル %s ㌠%s ã«è¿½åŠ ã•れã¾ã—ãŸ" #~ msgid "Profile %s removed from %s" #~ msgstr "プロファイル %s ㌠%s ã‹ã‚‰å‰Šé™¤ã•れã¾ã—ãŸ" #~ msgid "Cannot change profile name" #~ msgstr "プロファイルåを変更ã§ãã¾ã›ã‚“" #, fuzzy #~ msgid "" #~ "Create a read-only snapshot of a container.\n" #~ "\n" #~ "lxc snapshot [remote:]<source> <snapshot name> [--stateful]" #~ msgstr "コンテナã®èª­ã¿å–り専用スナップショットを作æˆã—ã¾ã™ã€‚\n" #~ msgid "No certificate on this connection" #~ msgstr "ã“ã®æŽ¥ç¶šã«ä½¿ç”¨ã™ã‚‹è¨¼æ˜Žæ›¸ãŒã‚りã¾ã›ã‚“" #, fuzzy #~ msgid "" #~ "Set the current state of a resource back to its state at the time the " #~ "snapshot was created.\n" #~ "\n" #~ "lxc restore [remote:]<resource> <snapshot name> [--stateful]" #~ msgstr "コンテナã®èª­ã¿å–り専用スナップショットを作æˆã—ã¾ã™ã€‚\n" #~ msgid "api version mismatch: mine: %q, daemon: %q" #~ msgstr "APIã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ä¸ä¸€è‡´: クライアント: %q, サーãƒ: %q" #, fuzzy #~ msgid "bad profile url %s" #~ msgstr "プロファイルURLãŒä¸æ­£ %s" #, fuzzy #~ msgid "bad version in profile url" #~ msgstr "プロファイルURL内ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ãŒä¸æ­£" #, fuzzy #~ msgid "error." #~ msgstr "エラー: %v\n" #~ msgid "got bad op status %s" #~ msgstr "䏿­£ãªæ“作ステータスを得ã¾ã—㟠%s" #, fuzzy #~ msgid "got bad response type, expected %s got %s" #~ msgstr "\"exec\"ã‹ã‚‰ä¸æ­£ãªå¿œç­”タイプを得ã¾ã—ãŸ" #~ msgid "invalid wait url %s" #~ msgstr "å¾…ã¤URLãŒä¸æ­£ %s" #~ msgid "no response!" #~ msgstr "応答ãŒã‚りã¾ã›ã‚“ï¼" #~ msgid "unknown remote name: %q" #~ msgstr "未知ã®ãƒªãƒ¢ãƒ¼ãƒˆå: %q" #, fuzzy #~ msgid "unknown transport type: %s" #~ msgstr "未知ã®ãƒªãƒ¢ãƒ¼ãƒˆå: %q" #~ msgid "cannot resolve unix socket address: %v" #~ msgstr "UNIXソケットã®ã‚¢ãƒ‰ãƒ¬ã‚¹ã‚’解決ã§ãã¾ã›ã‚“: %v" #, fuzzy #~ msgid "unknown group %s" #~ msgstr "未知ã®ãƒªãƒ¢ãƒ¼ãƒˆå: %q" #, fuzzy #~ msgid "Information about remotes not yet supported" #~ msgstr "ãƒªãƒ¢ãƒ¼ãƒˆã®æƒ…報表示ã¯ã¾ã ã‚µãƒãƒ¼ãƒˆã•れã¦ã„ã¾ã›ã‚“。\n" #~ msgid "Unknown image command %s" #~ msgstr "未知ã®ã‚¤ãƒ¡ãƒ¼ã‚¸ã‚³ãƒžãƒ³ãƒ‰ %s" #~ msgid "Unknown remote subcommand %s" #~ msgstr "未知ã®ãƒªãƒ¢ãƒ¼ãƒˆã‚µãƒ–コマンド %s" #~ msgid "Unkonwn config trust command %s" #~ msgstr "未知ã®è¨­å®šä¿¡é ¼ã‚³ãƒžãƒ³ãƒ‰ %s" #, fuzzy #~ msgid "YAML parse error %v" #~ msgstr "エラー: %v\n" #~ msgid "invalid argument %s" #~ msgstr "䏿­£ãªå¼•æ•° %s" #, fuzzy #~ msgid "unknown profile cmd %s" #~ msgstr "未知ã®è¨­å®šã‚³ãƒžãƒ³ãƒ‰ %s" #, fuzzy #~ msgid "Publish to remote server is not supported yet" #~ msgstr "ãƒªãƒ¢ãƒ¼ãƒˆã®æƒ…報表示ã¯ã¾ã ã‚µãƒãƒ¼ãƒˆã•れã¦ã„ã¾ã›ã‚“。\n" #, fuzzy #~ msgid "Use an alternative config path." #~ msgstr "別ã®è¨­å®šãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒª" #, fuzzy #~ msgid "" #~ "error: %v\n" #~ "%s\n" #~ msgstr "" #~ "エラー: %v\n" #~ "%s" #, fuzzy #~ msgid "Show for remotes is not yet supported\n" #~ msgstr "ãƒªãƒ¢ãƒ¼ãƒˆã®æƒ…報表示ã¯ã¾ã ã‚µãƒãƒ¼ãƒˆã•れã¦ã„ã¾ã›ã‚“。\n" #~ msgid "(Bad alias entry: %s\n" #~ msgstr "(䏿­£ãªã‚¨ã‚¤ãƒªã‚¢ã‚¹: %s\n" #~ msgid "bad version in container url" #~ msgstr "コンテナURL内ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ãŒä¸æ­£" #, fuzzy #~ msgid "Ephemeral containers not yet supported\n" #~ msgstr "ãƒªãƒ¢ãƒ¼ãƒˆã®æƒ…報表示ã¯ã¾ã ã‚µãƒãƒ¼ãƒˆã•れã¦ã„ã¾ã›ã‚“。\n" #~ msgid "(Bad image entry: %s\n" #~ msgstr "(䏿­£ãªã‚¤ãƒ¡ãƒ¼ã‚¸: %s\n" #~ msgid "Certificate already stored.\n" #~ msgstr "è¨¼æ˜Žæ›¸ã¯æ—¢ã«æ ¼ç´ã•れã¦ã„ã¾ã™ã€‚\n" #, fuzzy #~ msgid "Non-async response from delete!" #~ msgstr "削除コマンドã‹ã‚‰ã®å¿œç­”ãŒä¸æ­£(éžåŒæœŸã§ãªã„)ã§ã™ï¼" #, fuzzy #~ msgid "Non-async response from init!" #~ msgstr "åˆæœŸåŒ–コマンドã‹ã‚‰ã®å¿œç­”ãŒä¸æ­£(éžåŒæœŸã§ãªã„)ã§ã™ï¼" #~ msgid "Non-async response from snapshot!" #~ msgstr "スナップショットã‹ã‚‰ã®å¿œç­”ãŒä¸æ­£(éžåŒæœŸã§ãªã„)ã§ã™ï¼" #~ msgid "Server certificate has changed" #~ msgstr "サーãƒã®è¨¼æ˜Žæ›¸ãŒå¤‰æ›´ã•れã¦ã„ã¾ã—ãŸ" #, fuzzy #~ msgid "Unexpected non-async response" #~ msgstr "䏿­£ãªãƒ¬ã‚¹ãƒãƒ³ã‚¹ (éžåŒæœŸã§ãªã„)" #~ msgid "bad response type from image list!" #~ msgstr "イメージリストã‹ã‚‰ã®ãƒ¬ã‚¹ãƒãƒ³ã‚¹ã‚¿ã‚¤ãƒ—ãŒä¸æ­£ï¼" #~ msgid "bad response type from list!" #~ msgstr "一覧ã‹ã‚‰ã®ãƒ¬ã‚¹ãƒãƒ³ã‚¹ã‚¿ã‚¤ãƒ—ãŒä¸æ­£ï¼" #, fuzzy #~ msgid "got non-async response!" #~ msgstr "䏿­£ãª(éžåŒæœŸã§ãªã„)応答を得ã¾ã—ãŸï¼" #~ msgid "got non-sync response from containers get!" #~ msgstr "コンテナã‹ã‚‰ä¸æ­£ãª(éžåŒæœŸã§ãªã„)応答を得ã¾ã—ãŸï¼" #~ msgid "Delete a container or container snapshot.\n" #~ msgstr "コンテナã¾ãŸã¯ã‚³ãƒ³ãƒ†ãƒŠã®ã‚¹ãƒŠãƒƒãƒ—ショットを削除ã—ã¾ã™ã€‚\n" #~ msgid "List information on containers.\n" #~ msgstr "ã‚³ãƒ³ãƒ†ãƒŠã®æƒ…報を一覧表示ã—ã¾ã™ã€‚\n" #~ msgid "Lists the available resources.\n" #~ msgstr "利用å¯èƒ½ãªãƒªã‚½ãƒ¼ã‚¹ã‚’一覧表示ã—ã¾ã™ã€‚\n" #~ msgid "Manage files on a container.\n" #~ msgstr "コンテナ上ã®ãƒ•ァイルを管ç†ã—ã¾ã™ã€‚\n" #~ msgid "Manage remote lxc servers.\n" #~ msgstr "リモートã®lxcサーãƒã‚’管ç†ã—ã¾ã™ã€‚\n" #~ msgid "Non-async response from create!" #~ msgstr "作æˆã‚³ãƒžãƒ³ãƒ‰ã‹ã‚‰ã®ãƒ¬ã‚¹ãƒãƒ³ã‚¹ãŒä¸æ­£(éžåŒæœŸã§ãªã„)ï¼" #~ msgid "Only 'password' can be set currently" #~ msgstr "ç¾æ™‚点ã§ã¯ 'password' ã®ã¿ãŒè¨­å®šå¯èƒ½ã§ã™" #~ msgid "" #~ "lxc image import <tarball> [target] [--created-at=ISO-8601] [--expires-" #~ "at=ISO-8601] [--fingerprint=HASH] [prop=value]\n" #~ msgstr "" #~ "lxc image import <tarball> [destination] [--created-at=ISO-8601] [--" #~ "expires-at=ISO-8601] [--fingerprint=HASH] [proprit=valeur]\n" #~ msgid "lxc init ubuntu [<name>]\n" #~ msgstr "lxc init ubuntu [<nom>]\n" #~ msgid "lxc launch ubuntu [<name>]\n" #~ msgstr "lxc launch ubuntu [<nom>]\n" ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/po/fr.po���������������������������������������������������������������������������������0000644�0610621�0607500�00000122620�13172163242�015061� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# French translation for LXD # Copyright (C) 2015 - LXD contributors # This file is distributed under the same license as LXD. # Stéphane Graber <stgraber@ubuntu.com, 2015. # msgid "" msgstr "" "Project-Id-Version: LXD\n" "Report-Msgid-Bugs-To: lxc-devel@lists.linuxcontainers.org\n" "POT-Creation-Date: 2017-10-03 23:36-0400\n" "PO-Revision-Date: 2015-02-26 02:05-0600\n" "Last-Translator: Stéphane Graber <stgraber@ubuntu.com\n" "Language-Team: French <fr@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: lxc/config.go:39 msgid "" "### This is a yaml representation of the configuration.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### A sample configuration looks like:\n" "### name: container1\n" "### profiles:\n" "### - default\n" "### config:\n" "### volatile.eth0.hwaddr: 00:16:3e:e9:f8:7f\n" "### devices:\n" "### homedir:\n" "### path: /extra\n" "### source: /home/user\n" "### type: disk\n" "### ephemeral: false\n" "###\n" "### Note that the name is shown but cannot be changed" msgstr "" #: lxc/image.go:53 msgid "" "### This is a yaml representation of the image properties.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### Each property is represented by a single line:\n" "### An example would be:\n" "### description: My custom image" msgstr "" #: lxc/profile.go:28 msgid "" "### This is a yaml representation of the profile.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### A profile consists of a set of configuration items followed by a set of\n" "### devices.\n" "###\n" "### An example would look like:\n" "### name: onenic\n" "### config:\n" "### raw.lxc: lxc.aa_profile=unconfined\n" "### devices:\n" "### eth0:\n" "### nictype: bridged\n" "### parent: lxdbr0\n" "### type: nic\n" "###\n" "### Note that the name is shown but cannot be changed" msgstr "" #: lxc/image.go:851 #, c-format msgid "%s (%d more)" msgstr "" #: lxc/utils.go:324 #, c-format msgid "%v (interrupt two more times to force)" msgstr "" #: lxc/snapshot.go:53 #, fuzzy msgid "'/' not allowed in snapshot name" msgstr "'/' n'est pas autorisé dans le nom d'un instantané (snapshot)\n" #: lxc/profile.go:289 msgid "(none)" msgstr "" #: lxc/image.go:872 lxc/image.go:901 msgid "ALIAS" msgstr "" #: lxc/image.go:876 msgid "ARCH" msgstr "" #: lxc/list.go:414 msgid "ARCHITECTURE" msgstr "" #: lxc/remote.go:67 msgid "Accept certificate" msgstr "" #: lxc/remote.go:245 #, c-format msgid "Admin password for %s: " msgstr "Mot de passe administrateur pour %s: " #: lxc/image.go:435 msgid "Aliases:" msgstr "" #: lxc/image.go:413 lxc/info.go:104 #, c-format msgid "Architecture: %s" msgstr "" #: lxc/image.go:444 #, c-format msgid "Auto update: %s" msgstr "" #: lxc/image.go:518 #, fuzzy, c-format msgid "Bad property: %s" msgstr "(Image invalide: %s\n" #: lxc/info.go:186 msgid "Bytes received" msgstr "" #: lxc/info.go:187 msgid "Bytes sent" msgstr "" #: lxc/config.go:349 msgid "COMMON NAME" msgstr "" #: lxc/list.go:415 msgid "CREATED AT" msgstr "" #: lxc/image.go:443 #, fuzzy, c-format msgid "Cached: %s" msgstr "" "Utilisation: %s\n" "\n" "Options:\n" "\n" #: lxc/config.go:156 #, c-format msgid "Can't read from stdin: %s" msgstr "" #: lxc/config.go:169 #, c-format msgid "Can't unset key '%s', it's not currently set" msgstr "" #: lxc/config.go:211 lxc/config.go:237 #, c-format msgid "Can't unset key '%s', it's not currently set." msgstr "" #: lxc/profile.go:441 msgid "Cannot provide container name to list" msgstr "" #: lxc/remote.go:181 #, fuzzy, c-format msgid "Certificate fingerprint: %s" msgstr "Empreinte du certificat: % x\n" #: lxc/remote.go:280 msgid "Client certificate stored at server: " msgstr "Certificat client enregistré avec le serveur: " #: lxc/list.go:109 lxc/list.go:110 msgid "Columns" msgstr "" #: lxc/help.go:53 msgid "Commands:" msgstr "" #: lxc/init.go:135 lxc/init.go:136 msgid "Config key/value to apply to the new container" msgstr "" #: lxc/config.go:647 lxc/config.go:712 lxc/image.go:956 lxc/profile.go:237 #, fuzzy, c-format msgid "Config parsing error: %s" msgstr "erreur: %v\n" #: lxc/main.go:36 msgid "Connection refused; is LXD running?" msgstr "" #: lxc/publish.go:69 msgid "Container name is mandatory" msgstr "" #: lxc/copy.go:186 lxc/init.go:282 #, c-format msgid "Container name is: %s" msgstr "" #: lxc/publish.go:247 #, fuzzy, c-format msgid "Container published with fingerprint: %s" msgstr "Empreinte du certificat: % x\n" #: lxc/image.go:135 msgid "Copy aliases from source" msgstr "" #: lxc/image.go:313 #, c-format msgid "Copying the image: %s" msgstr "" #: lxc/remote.go:196 msgid "Could not create server cert dir" msgstr "Le dossier de stockage des certificats serveurs n'a pas pû être créé" #: lxc/image.go:418 lxc/info.go:106 #, c-format msgid "Created: %s" msgstr "" #: lxc/init.go:190 #, c-format msgid "Creating %s" msgstr "" #: lxc/init.go:188 msgid "Creating the container" msgstr "" #: lxc/image.go:875 lxc/image.go:903 msgid "DESCRIPTION" msgstr "" #: lxc/config.go:803 #, c-format msgid "Device %s added to %s" msgstr "" #: lxc/config.go:1039 #, c-format msgid "Device %s removed from %s" msgstr "" #: lxc/info.go:154 msgid "Disk usage:" msgstr "" #: lxc/list.go:505 msgid "EPHEMERAL" msgstr "" #: lxc/config.go:351 msgid "EXPIRY DATE" msgstr "" #: lxc/main.go:48 #, fuzzy msgid "Enable debug mode" msgstr "Active le mode de déboguage." #: lxc/main.go:47 #, fuzzy msgid "Enable verbose mode" msgstr "Active le mode verbeux." #: lxc/exec.go:56 msgid "Environment variable to set (e.g. HOME=/home/foo)" msgstr "" #: lxc/help.go:77 msgid "Environment:" msgstr "" #: lxc/copy.go:30 lxc/copy.go:31 lxc/init.go:139 lxc/init.go:140 msgid "Ephemeral container" msgstr "" #: lxc/monitor.go:56 msgid "Event type to listen for" msgstr "" #: lxc/image.go:422 #, c-format msgid "Expires: %s" msgstr "" #: lxc/image.go:424 msgid "Expires: never" msgstr "" #: lxc/image.go:710 #, c-format msgid "Exporting the image: %s" msgstr "" #: lxc/config.go:348 lxc/image.go:873 lxc/image.go:902 msgid "FINGERPRINT" msgstr "" #: lxc/utils.go:362 #, c-format msgid "Failed to create alias %s" msgstr "" #: lxc/manpage.go:62 #, c-format msgid "Failed to generate 'lxc.%s.1': %v" msgstr "" #: lxc/manpage.go:55 #, c-format msgid "Failed to generate 'lxc.1': %v" msgstr "" #: lxc/copy.go:181 msgid "Failed to get the new container name" msgstr "" #: lxc/utils.go:352 #, c-format msgid "Failed to remove alias %s" msgstr "" #: lxc/list.go:112 msgid "Fast mode (same as --columns=nsacPt)" msgstr "" #: lxc/image.go:411 #, fuzzy, c-format msgid "Fingerprint: %s" msgstr "Empreinte du certificat: % x\n" #: lxc/action.go:46 lxc/action.go:47 #, fuzzy msgid "Force the container to shutdown" msgstr "Force l'arrêt du conteneur." #: lxc/delete.go:34 lxc/delete.go:35 msgid "Force the removal of running containers" msgstr "" #: lxc/main.go:49 msgid "Force using the local unix socket" msgstr "" #: lxc/list.go:111 msgid "Format (table|json)" msgstr "" #: lxc/main.go:149 #, fuzzy msgid "Generating a client certificate. This may take a minute..." msgstr "Géneration d'un certificat client. Ceci peut prendre une minute...\n" #: lxc/list.go:412 msgid "IPV4" msgstr "" #: lxc/list.go:413 msgid "IPV6" msgstr "" #: lxc/config.go:350 msgid "ISSUE DATE" msgstr "" #: lxc/main.go:157 msgid "" "If this is your first time using LXD, you should also run: sudo lxd init" msgstr "" #: lxc/main.go:50 msgid "Ignore aliases when determining what command to run" msgstr "" #: lxc/action.go:50 #, fuzzy msgid "Ignore the container state (only for start)" msgstr "Force l'arrêt du conteneur." #: lxc/image.go:327 msgid "Image copied successfully!" msgstr "" #: lxc/image.go:770 msgid "Image exported successfully!" msgstr "" #: lxc/image.go:580 #, fuzzy, c-format msgid "Image imported with fingerprint: %s" msgstr "Empreinte du certificat: % x\n" #: lxc/init.go:141 msgid "Instance type" msgstr "" #: lxc/remote.go:107 #, c-format msgid "Invalid URL scheme \"%s\" in \"%s\"" msgstr "" #: lxc/config.go:329 #, fuzzy msgid "Invalid certificate" msgstr "Gérer la configuration.\n" #: lxc/init.go:31 lxc/init.go:36 #, fuzzy msgid "Invalid configuration key" msgstr "Gérer la configuration.\n" #: lxc/file.go:219 #, c-format msgid "Invalid source %s" msgstr "Source invalide %s" #: lxc/file.go:70 #, c-format msgid "Invalid target %s" msgstr "Destination invalide %s" #: lxc/info.go:135 msgid "Ips:" msgstr "" #: lxc/image.go:136 msgid "Keep the image up to date after initial copy" msgstr "" #: lxc/main.go:34 msgid "LXD socket not found; is LXD installed and running?" msgstr "" #: lxc/image.go:427 #, c-format msgid "Last used: %s" msgstr "" #: lxc/image.go:429 msgid "Last used: never" msgstr "" #: lxc/info.go:239 msgid "Log:" msgstr "" #: lxc/image.go:134 msgid "Make image public" msgstr "" #: lxc/publish.go:34 msgid "Make the image public" msgstr "" #: lxc/info.go:161 msgid "Memory (current)" msgstr "" #: lxc/info.go:165 msgid "Memory (peak)" msgstr "" #: lxc/info.go:177 msgid "Memory usage:" msgstr "" #: lxc/utils.go:256 msgid "Missing summary." msgstr "Sommaire manquant." #: lxc/file.go:207 msgid "More than one file to download, but target is not a directory" msgstr "" "Plusieurs fichiers à télécharger mais la destination n'est pas un dossier" #: lxc/action.go:72 msgid "Must supply container name for: " msgstr "" #: lxc/list.go:416 lxc/remote.go:364 msgid "NAME" msgstr "" #: lxc/remote.go:338 lxc/remote.go:343 msgid "NO" msgstr "" #: lxc/info.go:99 #, c-format msgid "Name: %s" msgstr "" #: lxc/info.go:194 msgid "Network usage:" msgstr "" #: lxc/image.go:137 lxc/publish.go:35 msgid "New alias to define at target" msgstr "" #: lxc/config.go:360 #, fuzzy msgid "No certificate provided to add" msgstr "Un certificat n'a pas été fournis" #: lxc/config.go:392 msgid "No fingerprint specified." msgstr "Aucune empreinte n'a été spécifié." #: lxc/remote.go:92 msgid "Only https URLs are supported for simplestreams" msgstr "" #: lxc/image.go:499 msgid "Only https:// is supported for remote image import." msgstr "" #: lxc/help.go:71 lxc/main.go:130 lxc/main.go:182 #, fuzzy msgid "Options:" msgstr "Opération %s" #: lxc/exec.go:57 msgid "Override the terminal mode (auto, interactive or non-interactive)" msgstr "" #: lxc/list.go:507 msgid "PERSISTENT" msgstr "" #: lxc/list.go:417 msgid "PID" msgstr "" #: lxc/list.go:418 msgid "PROFILES" msgstr "" #: lxc/remote.go:366 msgid "PROTOCOL" msgstr "" #: lxc/image.go:874 lxc/remote.go:367 msgid "PUBLIC" msgstr "" #: lxc/info.go:188 msgid "Packets received" msgstr "" #: lxc/info.go:189 msgid "Packets sent" msgstr "" #: lxc/help.go:78 #, fuzzy msgid "Path to an alternate client configuration directory" msgstr "Dossier de configuration alternatif." #: lxc/help.go:79 #, fuzzy msgid "Path to an alternate server directory" msgstr "Dossier de configuration alternatif." #: lxc/main.go:219 #, fuzzy msgid "Pause containers." msgstr "Mauvaise URL pour le conteneur %s" #: lxc/main.go:38 msgid "Permission denied, are you in the lxd group?" msgstr "" #: lxc/info.go:117 #, c-format msgid "Pid: %d" msgstr "" #: lxc/profile.go:238 msgid "Press enter to open the editor again" msgstr "" #: lxc/config.go:648 lxc/config.go:713 lxc/image.go:957 msgid "Press enter to start the editor again" msgstr "" #: lxc/help.go:73 msgid "Print debug information" msgstr "" #: lxc/help.go:72 msgid "Print less common commands" msgstr "" #: lxc/help.go:74 msgid "Print verbose information" msgstr "" #: lxc/info.go:141 #, fuzzy, c-format msgid "Processes: %d" msgstr "Mauvaise URL pour le conteneur %s" #: lxc/profile.go:188 #, c-format msgid "Profile %s created" msgstr "" #: lxc/profile.go:262 #, c-format msgid "Profile %s deleted" msgstr "" #: lxc/init.go:137 lxc/init.go:138 msgid "Profile to apply to the new container" msgstr "" #: lxc/profile.go:291 #, fuzzy, c-format msgid "Profiles %s applied to %s" msgstr "Mauvaise URL pour le conteneur %s" #: lxc/info.go:115 #, fuzzy, c-format msgid "Profiles: %s" msgstr "Mauvaise URL pour le conteneur %s" #: lxc/image.go:431 msgid "Properties:" msgstr "" #: lxc/remote.go:70 msgid "Public image server" msgstr "" #: lxc/image.go:414 #, c-format msgid "Public: %s" msgstr "" #: lxc/remote.go:68 msgid "Remote admin password" msgstr "" #: lxc/utils.go:315 #, fuzzy msgid "Remote operation canceled by user" msgstr "Le certificat serveur a été rejeté par l'utilisateur" #: lxc/info.go:101 #, c-format msgid "Remote: %s" msgstr "" #: lxc/delete.go:42 #, c-format msgid "Remove %s (yes/no): " msgstr "" #: lxc/delete.go:36 lxc/delete.go:37 msgid "Require user confirmation" msgstr "" #: lxc/info.go:138 msgid "Resources:" msgstr "" #: lxc/main.go:227 #, fuzzy msgid "Restart containers." msgstr "Liste de l'information sur les conteneurs.\n" #: lxc/init.go:254 #, c-format msgid "Retrieving image: %s" msgstr "" #: lxc/image.go:877 msgid "SIZE" msgstr "" #: lxc/list.go:419 msgid "SNAPSHOTS" msgstr "" #: lxc/list.go:420 msgid "STATE" msgstr "" #: lxc/remote.go:368 msgid "STATIC" msgstr "" #: lxc/remote.go:189 msgid "Server certificate NACKed by user" msgstr "Le certificat serveur a été rejeté par l'utilisateur" #: lxc/remote.go:277 msgid "Server doesn't trust us after adding our cert" msgstr "Identification refuse après l'ajout du certificat client" #: lxc/remote.go:69 msgid "Server protocol (lxd or simplestreams)" msgstr "" #: lxc/file.go:57 msgid "Set the file's gid on push" msgstr "Définit le gid lors de l'envoi" #: lxc/file.go:58 msgid "Set the file's perms on push" msgstr "Définit les permissions lors de l'envoi" #: lxc/file.go:56 msgid "Set the file's uid on push" msgstr "Définit le uid lors de l'envoi" #: lxc/help.go:29 msgid "Show all commands (not just interesting ones)" msgstr "Affiche toutes les comandes (pas seulement les intéresantes)" #: lxc/help.go:75 msgid "Show client version" msgstr "" #: lxc/info.go:39 msgid "Show the container's last 100 log lines?" msgstr "" #: lxc/config.go:35 msgid "Show the expanded configuration" msgstr "" #: lxc/image.go:412 #, c-format msgid "Size: %.2fMB" msgstr "" #: lxc/info.go:208 msgid "Snapshots:" msgstr "" #: lxc/action.go:142 #, fuzzy, c-format msgid "Some containers failed to %s" msgstr "L'arrêt du conteneur a échoué!" #: lxc/image.go:446 msgid "Source:" msgstr "" #: lxc/main.go:237 #, fuzzy msgid "Start containers." msgstr "Mauvaise URL pour le conteneur %s" #: lxc/launch.go:59 #, c-format msgid "Starting %s" msgstr "" #: lxc/info.go:109 #, c-format msgid "Status: %s" msgstr "" #: lxc/main.go:243 #, fuzzy msgid "Stop containers." msgstr "L'arrêt du conteneur a échoué!" #: lxc/publish.go:36 lxc/publish.go:37 msgid "Stop the container if currently running" msgstr "" #: lxc/publish.go:134 msgid "Stopping container failed!" msgstr "L'arrêt du conteneur a échoué!" #: lxc/delete.go:121 #, fuzzy, c-format msgid "Stopping the container failed: %s" msgstr "L'arrêt du conteneur a échoué!" #: lxc/action.go:49 #, fuzzy msgid "Store the container state (only for stop)" msgstr "Force l'arrêt du conteneur." #: lxc/info.go:169 msgid "Swap (current)" msgstr "" #: lxc/info.go:173 msgid "Swap (peak)" msgstr "" #: lxc/list.go:421 msgid "TYPE" msgstr "" #: lxc/delete.go:105 msgid "The container is currently running, stop it first or pass --force." msgstr "" #: lxc/publish.go:99 msgid "" "The container is currently running. Use --force to have it stopped and " "restarted." msgstr "" #: lxc/config.go:770 lxc/config.go:787 #, fuzzy msgid "The device already exists" msgstr "le serveur distant %s existe déjà" #: lxc/config.go:833 lxc/config.go:845 lxc/config.go:881 lxc/config.go:899 #: lxc/config.go:945 lxc/config.go:962 lxc/config.go:1005 lxc/config.go:1023 #, fuzzy msgid "The device doesn't exist" msgstr "le serveur distant %s n'existe pas" #: lxc/init.go:308 #, c-format msgid "The local image '%s' couldn't be found, trying '%s:' instead." msgstr "" #: lxc/action.go:34 msgid "The opposite of \"lxc pause\" is \"lxc start\"." msgstr "" #: lxc/publish.go:72 msgid "There is no \"image name\". Did you want an alias?" msgstr "" #: lxc/help.go:47 msgid "" "This is the LXD command line client.\n" "\n" "All of LXD's features can be driven through the various commands below.\n" "For help with any of those, simply call them with --help." msgstr "" #: lxc/action.go:45 #, fuzzy msgid "Time to wait for the container before killing it" msgstr "Temps d'attente avant de tuer le conteneur." #: lxc/image.go:415 msgid "Timestamps:" msgstr "" #: lxc/main.go:158 msgid "To start your first container, try: lxc launch ubuntu:16.04" msgstr "" #: lxc/copy.go:155 #, fuzzy, c-format msgid "Transferring container: %s" msgstr "Mauvaise URL pour le conteneur %s" #: lxc/image.go:528 #, c-format msgid "Transferring image: %s" msgstr "" #: lxc/action.go:106 lxc/launch.go:77 #, c-format msgid "Try `lxc info --show-log %s` for more info" msgstr "" #: lxc/info.go:111 msgid "Type: ephemeral" msgstr "" #: lxc/info.go:113 msgid "Type: persistent" msgstr "" #: lxc/image.go:878 msgid "UPLOAD DATE" msgstr "" #: lxc/remote.go:365 msgid "URL" msgstr "" #: lxc/manpage.go:36 msgid "Unable to find help2man." msgstr "" #: lxc/image.go:420 #, c-format msgid "Uploaded: %s" msgstr "" #: lxc/action.go:37 #, c-format msgid "" "Usage: lxc %s [<remote>:]<container> [[<remote>:]<container>...]\n" "\n" "%s%s" msgstr "" #: lxc/help.go:45 #, fuzzy msgid "Usage: lxc <command> [options]" msgstr "" "Utilisation: lxc [sous commande] [options]\n" "Comande disponibles:\n" #: lxc/config.go:60 msgid "" "Usage: lxc config <subcommand> [options]\n" "\n" "Change container or server configuration options.\n" "\n" "*Container configuration*\n" "\n" "lxc config get [<remote>:][container] <key>\n" " Get container or server configuration key.\n" "\n" "lxc config set [<remote>:][container] <key> <value>\n" " Set container or server configuration key.\n" "\n" "lxc config unset [<remote>:][container] <key>\n" " Unset container or server configuration key.\n" "\n" "lxc config show [<remote>:][container] [--expanded]\n" " Show container or server configuration.\n" "\n" "lxc config edit [<remote>:][container]\n" " Edit configuration, either by launching external editor or reading " "STDIN.\n" "\n" "*Device management*\n" "\n" "lxc config device add [<remote>:]<container> <device> <type> [key=value...]\n" " Add a device to a container.\n" "\n" "lxc config device get [<remote>:]<container> <device> <key>\n" " Get a device property.\n" "\n" "lxc config device set [<remote>:]<container> <device> <key> <value>\n" " Set a device property.\n" "\n" "lxc config device unset [<remote>:]<container> <device> <key>\n" " Unset a device property.\n" "\n" "lxc config device list [<remote>:]<container>\n" " List devices for container.\n" "\n" "lxc config device show [<remote>:]<container>\n" " Show full device details for container.\n" "\n" "lxc config device remove [<remote>:]<container> <name>...\n" " Remove device from container.\n" "\n" "*Client trust store management*\n" "\n" "lxc config trust list [<remote>:]\n" " List all trusted certs.\n" "\n" "lxc config trust add [<remote>:] <certfile.crt>\n" " Add certfile.crt to trusted hosts.\n" "\n" "lxc config trust remove [<remote>:] [hostname|fingerprint]\n" " Remove the cert from trusted hosts.\n" "\n" "*Examples*\n" "\n" "cat config.yaml | lxc config edit <container>\n" " Update the container configuration from config.yaml.\n" "\n" "lxc config device add [<remote>:]container1 <device-name> disk source=/share/" "c1 path=opt\n" " Will mount the host's /share/c1 onto /opt in the container.\n" "\n" "lxc config set [<remote>:]<container> limits.cpu 2\n" " Will set a CPU limit of \"2\" for the container.\n" "\n" "lxc config set core.https_address [::]:8443\n" " Will have LXD listen on IPv4 and IPv6 port 8443.\n" "\n" "lxc config set core.trust_password blah\n" " Will set the server's trust password to blah." msgstr "" #: lxc/copy.go:23 msgid "" "Usage: lxc copy [<remote>:]<source>[/<snapshot>] [[<remote>:]<destination>] " "[--ephemeral|e]\n" "\n" "Copy containers within or in between LXD instances." msgstr "" #: lxc/delete.go:27 msgid "" "Usage: lxc delete [<remote>:]<container>[/<snapshot>] " "[[<remote>:]<container>[/<snapshot>]...]\n" "\n" "Delete containers and snapshots." msgstr "" #: lxc/exec.go:47 #, fuzzy msgid "" "Usage: lxc exec [<remote>:]<container> [--mode=auto|interactive|non-" "interactive] [--env KEY=VALUE...] [--] <command line>\n" "\n" "Execute commands in containers.\n" "\n" "Mode defaults to non-interactive, interactive mode is selected if both stdin " "AND stdout are terminals (stderr is ignored)." msgstr "Exécute la commande spécifiée dans un conteneur.\n" #: lxc/file.go:33 msgid "" "Usage: lxc file <subcommand> [options]\n" "\n" "Manage files in containers.\n" "\n" "lxc file pull [<remote>:]<container>/<path> [[<remote>:]<container>/" "<path>...] <target path>\n" " Pull files from containers.\n" "\n" "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source path> [<source " "path>...] [<remote>:]<container>/<path>\n" " Push files into containers.\n" "\n" "lxc file edit [<remote>:]<container>/<path>\n" " Edit files in containers using the default text editor.\n" "\n" "*Examples*\n" "lxc file push /etc/hosts foo/etc/hosts\n" " To push /etc/hosts into the container \"foo\".\n" "\n" "lxc file pull foo/etc/hosts .\n" " To pull /etc/hosts from the container and write it to the current " "directory." msgstr "" #: lxc/finger.go:15 msgid "" "Usage: lxc finger [<remote>:]\n" "\n" "Check if the LXD server is alive." msgstr "" #: lxc/help.go:22 msgid "" "Usage: lxc help [--all]\n" "\n" "Help page for the LXD client." msgstr "" #: lxc/image.go:63 msgid "" "Usage: lxc image <subcommand> [options]\n" "\n" "Manipulate container images.\n" "\n" "In LXD containers are created from images. Those images were themselves\n" "either generated from an existing container or downloaded from an image\n" "server.\n" "\n" "When using remote images, LXD will automatically cache images for you\n" "and remove them upon expiration.\n" "\n" "The image unique identifier is the hash (sha-256) of its representation\n" "as a compressed tarball (or for split images, the concatenation of the\n" "metadata and rootfs tarballs).\n" "\n" "Images can be referenced by their full hash, shortest unique partial\n" "hash or alias name (if one is set).\n" "\n" "\n" "lxc image import <tarball> [<rootfs tarball>|<URL>] [<remote>:] [--public] " "[--created-at=ISO-8601] [--expires-at=ISO-8601] [--fingerprint=FINGERPRINT] " "[--alias=ALIAS...] [prop=value]\n" " Import an image tarball (or tarballs) into the LXD image store.\n" "\n" "lxc image copy [<remote>:]<image> <remote>: [--alias=ALIAS...] [--copy-" "aliases] [--public] [--auto-update]\n" " Copy an image from one LXD daemon to another over the network.\n" "\n" " The auto-update flag instructs the server to keep this image up to\n" " date. It requires the source to be an alias and for it to be public.\n" "\n" "lxc image delete [<remote>:]<image> [[<remote>:]<image>...]\n" " Delete one or more images from the LXD image store.\n" "\n" "lxc image export [<remote>:]<image> [target]\n" " Export an image from the LXD image store into a distributable tarball.\n" "\n" " The output target is optional and defaults to the working directory.\n" " The target may be an existing directory, file name, or \"-\" to specify\n" " stdout. The target MUST be a directory when exporting a split image.\n" " If the target is a directory, the image's name (each part's name for\n" " split images) as found in the database will be used for the exported\n" " image. If the target is a file (not a directory and not stdout), then\n" " the appropriate extension will be appended to the provided file name\n" " based on the algorithm used to compress the image.\n" "\n" "lxc image info [<remote>:]<image>\n" " Print everything LXD knows about a given image.\n" "\n" "lxc image list [<remote>:] [filter]\n" " List images in the LXD image store. Filters may be of the\n" " <key>=<value> form for property based filtering, or part of the image\n" " hash or part of the image alias name.\n" "\n" "lxc image show [<remote>:]<image>\n" " Yaml output of the user modifiable properties of an image.\n" "\n" "lxc image edit [<remote>:]<image>\n" " Edit image, either by launching external editor or reading STDIN.\n" " Example: lxc image edit <image> # launch editor\n" " cat image.yaml | lxc image edit <image> # read from image.yaml\n" "\n" "lxc image alias create [<remote>:]<alias> <fingerprint>\n" " Create a new alias for an existing image.\n" "\n" "lxc image alias delete [<remote>:]<alias>\n" " Delete an alias.\n" "\n" "lxc image alias list [<remote>:] [filter]\n" " List the aliases. Filters may be part of the image hash or part of the " "image alias name." msgstr "" #: lxc/info.go:26 msgid "" "Usage: lxc info [<remote>:][<container>] [--show-log]\n" "\n" "Show container or server information.\n" "\n" "lxc info [<remote>:]<container> [--show-log]\n" " For container information.\n" "\n" "lxc info [<remote>:]\n" " For LXD server information." msgstr "" #: lxc/init.go:75 msgid "" "Usage: lxc init [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--" "profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance " "type>]\n" "\n" "Create containers from images.\n" "\n" "Not specifying -p will result in the default profile.\n" "Specifying \"-p\" with no argument will result in no profile.\n" "\n" "Examples:\n" " lxc init ubuntu:16.04 u1" msgstr "" #: lxc/launch.go:20 msgid "" "Usage: lxc launch [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--" "profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance " "type>]\n" "\n" "Create and start containers from images.\n" "\n" "Not specifying -p will result in the default profile.\n" "Specifying \"-p\" with no argument will result in no profile.\n" "\n" "Examples:\n" " lxc launch ubuntu:16.04 u1" msgstr "" #: lxc/list.go:46 msgid "" "Usage: lxc list [<remote>:] [filters] [--format table|json] [-c <columns>] " "[--fast]\n" "\n" "List the existing containers.\n" "\n" "Default column layout: ns46tS\n" "Fast column layout: nsacPt\n" "\n" "*Filters*\n" "A single keyword like \"web\" which will list any container with a name " "starting by \"web\".\n" "\n" "A regular expression on the container name. (e.g. .*web.*01$).\n" "\n" "A key/value pair referring to a configuration item. For those, the namespace " "can be abbreviated to the smallest unambiguous identifier.\n" " - \"user.blah=abc\" will list all containers with the \"blah\" user " "property set to \"abc\".\n" "\n" " - \"u.blah=abc\" will do the same\n" "\n" " - \"security.privileged=true\" will list all privileged containers\n" "\n" " - \"s.privileged=true\" will do the same\n" "\n" "A regular expression matching a configuration item or its value. (e.g. " "volatile.eth0.hwaddr=00:16:3e:.*).\n" "\n" "*Columns*\n" "The -c option takes a comma separated list of arguments that control\n" "which container attributes to output when displaying in table format.\n" "\n" "Column arguments are either pre-defined shorthand chars (see below),\n" "or (extended) config keys.\n" "\n" "Commas between consecutive shorthand chars are optional.\n" "\n" "Pre-defined column shorthand chars:\n" "\n" " 4 - IPv4 address\n" "\n" " 6 - IPv6 address\n" "\n" " a - Architecture\n" "\n" " c - Creation date\n" "\n" " l - Last used date\n" "\n" " n - Name\n" "\n" " p - PID of the container's init process\n" "\n" " P - Profiles\n" "\n" " s - State\n" "\n" " S - Number of snapshots\n" "\n" " t - Type (persistent or ephemeral)\n" "\n" "*Examples*\n" "lxc list -c ns46\n" " Shows a list of containers using the \"NAME\", \"STATE\", \"IPV4\", " "\"IPV6\" columns." msgstr "" #: lxc/manpage.go:20 msgid "" "Usage: lxc manpage <directory>\n" "\n" "Generate all the LXD manpages." msgstr "" #: lxc/monitor.go:41 msgid "" "Usage: lxc monitor [<remote>:] [--type=TYPE...]\n" "\n" "Monitor a local or remote LXD server.\n" "\n" "By default the monitor will listen to all message types.\n" "\n" "Message types to listen for can be specified with --type.\n" "\n" "*Examples*\n" "lxc monitor --type=logging\n" " Only show log message." msgstr "" #: lxc/move.go:20 msgid "" "Usage: lxc move [<remote>:]<container>[/<snapshot>] [<remote>:][<container>[/" "<snapshot>]]\n" "\n" "Move containers within or in between LXD instances.\n" "\n" "lxc move [<remote>:]<source container> [<remote>:][<destination container>]\n" " Move a container between two hosts, renaming it if destination name " "differs.\n" "\n" "lxc move <old name> <new name>\n" " Rename a local container.\n" "\n" "lxc move <container>/<old snapshot name> <container>/<new snapshot name>\n" " Rename a snapshot." msgstr "" #: lxc/profile.go:49 msgid "" "Usage: lxc profile <subcommand> [options]\n" "\n" "Manage container configuration profiles.\n" "\n" "*Profile configuration*\n" "lxc profile list [<remote>:]\n" " List available profiles.\n" "\n" "lxc profile show [<remote>:]<profile>\n" " Show details of a profile.\n" "\n" "lxc profile create [<remote>:]<profile>\n" " Create a profile.\n" "\n" "lxc profile copy [<remote>:]<profile> [<remote>:]<profile>\n" " Copy the profile.\n" "\n" "lxc profile get [<remote>:]<profile> <key>\n" " Get profile configuration.\n" "\n" "lxc profile set [<remote>:]<profile> <key> <value>\n" " Set profile configuration.\n" "\n" "lxc profile unset [<remote>:]<profile> <key>\n" " Unset profile configuration.\n" "\n" "lxc profile delete [<remote>:]<profile>\n" " Delete a profile.\n" "\n" "lxc profile edit [<remote>:]<profile>\n" " Edit profile, either by launching external editor or reading STDIN.\n" "\n" "*Profile assignment*\n" "lxc profile apply [<remote>:]<container> <profiles>\n" " Replace the current set of profiles for the container by the one " "provided.\n" "\n" "*Device management*\n" "lxc profile device list [<remote>:]<profile>\n" " List devices in the given profile.\n" "\n" "lxc profile device show [<remote>:]<profile>\n" " Show full device details in the given profile.\n" "\n" "lxc profile device remove [<remote>:]<profile> <name>\n" " Remove a device from a profile.\n" "\n" "lxc profile device get [<remote>:]<profile> <name> <key>\n" " Get a device property.\n" "\n" "lxc profile device set [<remote>:]<profile> <name> <key> <value>\n" " Set a device property.\n" "\n" "lxc profile device unset [<remote>:]<profile> <name> <key>\n" " Unset a device property.\n" "\n" "lxc profile device add [<remote>:]<profile> <device> <type> [key=value...]\n" " Add a profile device, such as a disk or a nic, to the containers using " "the specified profile.\n" "\n" "*Examples*\n" "cat profile.yaml | lxc profile edit <profile>\n" " Update a profile using the content of profile.yaml\n" "\n" "lxc profile apply foo default,bar\n" " Set the profiles for \"foo\" to \"default\" and \"bar\".\n" "\n" "lxc profile apply foo default\n" " Reset \"foo\" to only using the \"default\" profile.\n" "\n" "lxc profile apply foo ''\n" " Remove all profile from \"foo\"" msgstr "" #: lxc/publish.go:27 msgid "" "Usage: lxc publish [<remote>:]<container>[/<snapshot>] [<remote>:] [--" "alias=ALIAS...] [prop-key=prop-value...]\n" "\n" "Publish containers as images." msgstr "" #: lxc/remote.go:39 msgid "" "Usage: lxc remote <subcommand> [options]\n" "\n" "Manage the list of remote LXD servers.\n" "\n" "lxc remote add <remote> <IP|FQDN|URL> [--accept-certificate] [--" "password=PASSWORD] [--public] [--protocol=PROTOCOL]\n" " Add the remote <remote> at <url>.\n" "\n" "lxc remote remove <remote>\n" " Remove the remote <remote>.\n" "\n" "lxc remote list\n" " List all remotes.\n" "\n" "lxc remote rename <old name> <new name>\n" " Rename remote <old name> to <new name>.\n" "\n" "lxc remote set-url <remote> <url>\n" " Update <remote>'s url to <url>.\n" "\n" "lxc remote set-default <remote>\n" " Set the default remote.\n" "\n" "lxc remote get-default\n" " Print the default remote." msgstr "" #: lxc/restore.go:22 msgid "" "Usage: lxc restore [<remote>:]<container> <snapshot> [--stateful]\n" "\n" "Restore containers from snapshots.\n" "\n" "If --stateful is passed, then the running state will be restored too.\n" "\n" "*Examples*\n" "lxc snapshot u1 snap0\n" " Create the snapshot.\n" "\n" "lxc restore u1 snap0\n" " Restore the snapshot." msgstr "" #: lxc/snapshot.go:22 msgid "" "Usage: lxc snapshot [<remote>:]<container> <snapshot name> [--stateful]\n" "\n" "Create container snapshots.\n" "\n" "When --stateful is used, LXD attempts to checkpoint the container's\n" "running state, including process memory state, TCP connections, ...\n" "\n" "*Examples*\n" "lxc snapshot u1 snap0\n" " Create a snapshot of \"u1\" called \"snap0\"." msgstr "" #: lxc/version.go:18 #, fuzzy msgid "" "Usage: lxc version\n" "\n" "Print the version number of this client tool." msgstr "Montre le numéro de version de LXD.\n" #: lxc/delete.go:46 msgid "User aborted delete operation." msgstr "" #: lxc/utils.go:320 msgid "" "User signaled us three times, exiting. The remote operation will keep " "running." msgstr "" #: lxc/restore.go:38 #, fuzzy msgid "" "Whether or not to restore the container's running state from snapshot (if " "available)" msgstr "" "Est-ce que l'état de fonctionement du conteneur doit être inclus dans " "l'instantané (snapshot)" #: lxc/snapshot.go:36 msgid "Whether or not to snapshot the container's running state" msgstr "" "Est-ce que l'état de fonctionement du conteneur doit être inclus dans " "l'instantané (snapshot)" #: lxc/remote.go:340 lxc/remote.go:345 msgid "YES" msgstr "" #: lxc/copy.go:49 msgid "You must specify a source container name" msgstr "" #: lxc/main.go:68 msgid "`lxc config profile` is deprecated, please use `lxc profile`" msgstr "" #: lxc/remote.go:328 msgid "can't remove the default remote" msgstr "" #: lxc/remote.go:354 msgid "default" msgstr "" #: lxc/init.go:276 #, fuzzy msgid "didn't get any affected image, container or snapshot from server" msgstr "N'a pas pû obtenir de resource du serveur" #: lxc/image.go:406 msgid "disabled" msgstr "" #: lxc/image.go:408 msgid "enabled" msgstr "" #: lxc/action.go:134 lxc/main.go:29 lxc/main.go:178 #, fuzzy, c-format msgid "error: %v" msgstr "erreur: %v\n" #: lxc/help.go:37 lxc/main.go:124 #, fuzzy, c-format msgid "error: unknown command: %s" msgstr "erreur: comande inconnue: %s\n" #: lxc/image.go:396 lxc/image.go:401 lxc/image.go:854 msgid "no" msgstr "" #: lxc/remote.go:182 #, fuzzy msgid "ok (y/n)?" msgstr "ok (y/n)?" #: lxc/main.go:313 lxc/main.go:317 #, c-format msgid "processing aliases failed %s\n" msgstr "" #: lxc/remote.go:390 #, c-format msgid "remote %s already exists" msgstr "le serveur distant %s existe déjà" #: lxc/remote.go:320 lxc/remote.go:382 lxc/remote.go:417 lxc/remote.go:433 #, c-format msgid "remote %s doesn't exist" msgstr "le serveur distant %s n'existe pas" #: lxc/remote.go:303 #, c-format msgid "remote %s exists as <%s>" msgstr "le serveur distant %s existe en tant que <%s>" #: lxc/remote.go:324 lxc/remote.go:386 lxc/remote.go:421 #, c-format msgid "remote %s is static and cannot be modified" msgstr "" #: lxc/info.go:219 msgid "stateful" msgstr "" #: lxc/info.go:221 msgid "stateless" msgstr "" #: lxc/info.go:215 #, c-format msgid "taken at %s" msgstr "" #: lxc/main.go:252 msgid "wrong number of subcommand arguments" msgstr "nombre d'argument incorrect pour la sous-comande" #: lxc/delete.go:45 lxc/image.go:398 lxc/image.go:403 lxc/image.go:858 msgid "yes" msgstr "" #, fuzzy #~ msgid "bad number of things scanned from image, container or snapshot" #~ msgstr "nombre de propriété invalide pour la ressource" #~ msgid "got bad version" #~ msgstr "reçu une version invalide" #~ msgid "bad result type from action" #~ msgstr "mauvais type de réponse pour l'action!" #~ msgid "unreachable return reached" #~ msgstr "Un retour inacessible à été atteint" #, fuzzy #~ msgid "" #~ "Changes state of one or more containers to %s.\n" #~ "\n" #~ "lxc %s <name> [<name>...]%s" #~ msgstr "Change l'état du conteneur à %s.\n" #, fuzzy #~ msgid "" #~ "Fingers the LXD instance to check if it is up and working.\n" #~ "\n" #~ "lxc finger <remote>" #~ msgstr "Contacte LXD pour voir s'il est fonctionel.\n" #, fuzzy #~ msgid "" #~ "Presents details on how to use LXD.\n" #~ "\n" #~ "lxd help [--all]" #~ msgstr "Explique comment utiliser LXD.\n" #, fuzzy #~ msgid "" #~ "Create a read-only snapshot of a container.\n" #~ "\n" #~ "lxc snapshot [remote:]<source> <snapshot name> [--stateful]" #~ msgstr "Prend un instantané (snapshot) en lecture seule d'un conteneur.\n" #~ msgid "No certificate on this connection" #~ msgstr "Aucun certificat pour cette connexion" #, fuzzy #~ msgid "" #~ "Set the current state of a resource back to its state at the time the " #~ "snapshot was created.\n" #~ "\n" #~ "lxc restore [remote:]<resource> <snapshot name> [--stateful]" #~ msgstr "Prend un instantané (snapshot) en lecture seule d'un conteneur.\n" #~ msgid "api version mismatch: mine: %q, daemon: %q" #~ msgstr "Version de l'API incompatible: local: %q, distant: %q" #, fuzzy #~ msgid "bad version in profile url" #~ msgstr "version invalide dans l'URL du conteneur" #, fuzzy #~ msgid "error." #~ msgstr "erreur: %v\n" #~ msgid "got bad op status %s" #~ msgstr "reçu un status d'opration invalide %s" #, fuzzy #~ msgid "got bad response type, expected %s got %s" #~ msgstr "reçu une mauvaise réponse pour \"exec\"" #~ msgid "invalid wait url %s" #~ msgstr "URL d'attente invalide %s" #~ msgid "no response!" #~ msgstr "pas de réponse!" #~ msgid "unknown remote name: %q" #~ msgstr "serveur distant inconnu: %q" #, fuzzy #~ msgid "unknown transport type: %s" #~ msgstr "serveur distant inconnu: %q" #~ msgid "cannot resolve unix socket address: %v" #~ msgstr "Ne peut pas résoudre l'adresse du unix socket: %v" #, fuzzy #~ msgid "unknown group %s" #~ msgstr "serveur distant inconnu: %q" #, fuzzy #~ msgid "Information about remotes not yet supported" #~ msgstr "" #~ "Il n'est pas encore possible d'obtenir de l'information sur un serveur " #~ "distant\n" #~ msgid "Unknown image command %s" #~ msgstr "Comande d'image inconnue %s" #~ msgid "Unknown remote subcommand %s" #~ msgstr "Comande de serveur distant inconnue %s" #~ msgid "Unkonwn config trust command %s" #~ msgstr "Comande de configuration de confiance inconnue %s" #, fuzzy #~ msgid "YAML parse error %v" #~ msgstr "erreur: %v\n" #~ msgid "invalid argument %s" #~ msgstr "Arguments invalides %s" #, fuzzy #~ msgid "unknown profile cmd %s" #~ msgstr "Comande de configuration inconue %s" #, fuzzy #~ msgid "Publish to remote server is not supported yet" #~ msgstr "" #~ "Il n'est pas encore possible d'obtenir de l'information sur un serveur " #~ "distant\n" #, fuzzy #~ msgid "Use an alternative config path." #~ msgstr "Dossier de configuration alternatif." #, fuzzy #~ msgid "" #~ "error: %v\n" #~ "%s\n" #~ msgstr "" #~ "erreur: %v\n" #~ "%s" #, fuzzy #~ msgid "Show for remotes is not yet supported\n" #~ msgstr "" #~ "Il n'est pas encore possible d'obtenir de l'information sur un serveur " #~ "distant\n" #~ msgid "(Bad alias entry: %s\n" #~ msgstr "(Alias invalide: %s\n" #~ msgid "bad version in container url" #~ msgstr "version invalide dans l'URL du conteneur" #, fuzzy #~ msgid "Ephemeral containers not yet supported\n" #~ msgstr "" #~ "Il n'est pas encore possible d'obtenir de l'information sur un serveur " #~ "distant\n" #~ msgid "(Bad image entry: %s\n" #~ msgstr "(Image invalide: %s\n" #~ msgid "Certificate already stored.\n" #~ msgstr "Le certificat a déjà été enregistré.\n" #, fuzzy #~ msgid "Non-async response from delete!" #~ msgstr "Réponse invalide (non-async) durant la suppression!" #, fuzzy #~ msgid "Non-async response from init!" #~ msgstr "" #~ "Réponse invalide (non-async) durant la cration d'un instantané (snapshot)!" #~ msgid "Non-async response from snapshot!" #~ msgstr "" #~ "Réponse invalide (non-async) durant la cration d'un instantané (snapshot)!" #~ msgid "Server certificate has changed" #~ msgstr "Le certificat serveur a changé" #, fuzzy #~ msgid "Unexpected non-async response" #~ msgstr "Réponse invalide (non-async) durant la suppression!" #~ msgid "bad response type from image list!" #~ msgstr "mauvais type de réponse pour la liste d'image!" #~ msgid "bad response type from list!" #~ msgstr "mauvais type de réponse pour la liste!" #, fuzzy #~ msgid "got non-async response!" #~ msgstr "Réponse invalide (non-async) durant la suppression!" #~ msgid "got non-sync response from containers get!" #~ msgstr "Réponse invalide (non-async) durant le chargement!" #~ msgid "Delete a container or container snapshot.\n" #~ msgstr "Supprime un conteneur ou l'instantané (snapshot) d'un conteneur.\n" #~ msgid "Lists the available resources.\n" #~ msgstr "Liste des ressources disponibles.\n" #~ msgid "Manage files on a container.\n" #~ msgstr "Gérer les fichiers du conteneur.\n" #~ msgid "Manage remote lxc servers.\n" #~ msgstr "Gérer les serveurs distants.\n" #~ msgid "Non-async response from create!" #~ msgstr "Réponse invalide (non-async) durant la cration!" #~ msgid "Only 'password' can be set currently" #~ msgstr "Seul 'password' peut être configuré en ce moment" #~ msgid "" #~ "lxc image import <tarball> [target] [--created-at=ISO-8601] [--expires-" #~ "at=ISO-8601] [--fingerprint=HASH] [prop=value]\n" #~ msgstr "" #~ "lxc image import <tarball> [destination] [--created-at=ISO-8601] [--" #~ "expires-at=ISO-8601] [--fingerprint=HASH] [proprit=valeur]\n" #~ msgid "lxc init ubuntu [<name>]\n" #~ msgstr "lxc init ubuntu [<nom>]\n" #~ msgid "lxc launch ubuntu [<name>]\n" #~ msgstr "lxc launch ubuntu [<nom>]\n" ����������������������������������������������������������������������������������������������������������������lxd-2.0.11/po/de.po���������������������������������������������������������������������������������0000644�0610621�0607500�00000157072�13172163242�015053� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# German translation for LXD # Copyright (C) 2015 - LXD contributors # This file is distributed under the same license as LXD. # Felix Engelmann <felix-lxd@nlogn.org>, 2015. # msgid "" msgstr "" "Project-Id-Version: LXD\n" "Report-Msgid-Bugs-To: lxc-devel@lists.linuxcontainers.org\n" "POT-Creation-Date: 2017-10-03 23:36-0400\n" "PO-Revision-Date: 2015-06-13 06:10+0200\n" "Last-Translator: Felix Engelmann <felix-lxd@nlogn.org>\n" "Language-Team: \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: lxc/config.go:39 #, fuzzy msgid "" "### This is a yaml representation of the configuration.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### A sample configuration looks like:\n" "### name: container1\n" "### profiles:\n" "### - default\n" "### config:\n" "### volatile.eth0.hwaddr: 00:16:3e:e9:f8:7f\n" "### devices:\n" "### homedir:\n" "### path: /extra\n" "### source: /home/user\n" "### type: disk\n" "### ephemeral: false\n" "###\n" "### Note that the name is shown but cannot be changed" msgstr "" "### Dies ist eine Darstellung der Konfiguration in yaml.\n" "### Jede Zeile die mit '# beginnt wird ignoriert.\n" "###\n" "### Beispiel einer Konfiguration:\n" "### name: container1\n" "### profiles:\n" "### - default\n" "### config:\n" "### volatile.eth0.hwaddr: 00:16:3e:e9:f8:7f\n" "### devices:\n" "### homedir:\n" "### path: /extra\n" "### source: /home/user\n" "### type: disk\n" "### ephemeral: false\n" "###\n" "### Der Name wird zwar angezeigt, lässt sich jedoch nicht ändern.\n" #: lxc/image.go:53 #, fuzzy msgid "" "### This is a yaml representation of the image properties.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### Each property is represented by a single line:\n" "### An example would be:\n" "### description: My custom image" msgstr "" "### Dies ist eine Darstellung der Eigenschaften eines Abbildes in yaml.\n" "### Jede Zeile die mit '# beginnt wird ignoriert.\n" "###\n" "### Pro Eigenschaft wird eine Zeile verwendet:\n" "### Zum Beispiel:\n" "### description: Mein eigenes Abbild\n" #: lxc/profile.go:28 #, fuzzy msgid "" "### This is a yaml representation of the profile.\n" "### Any line starting with a '# will be ignored.\n" "###\n" "### A profile consists of a set of configuration items followed by a set of\n" "### devices.\n" "###\n" "### An example would look like:\n" "### name: onenic\n" "### config:\n" "### raw.lxc: lxc.aa_profile=unconfined\n" "### devices:\n" "### eth0:\n" "### nictype: bridged\n" "### parent: lxdbr0\n" "### type: nic\n" "###\n" "### Note that the name is shown but cannot be changed" msgstr "" "### Dies ist eine Darstellung eines Profils in yaml.\n" "### Jede Zeile die mit '# beginnt wird ignoriert.\n" "###\n" "### Ein Profil besteht aus mehreren Konfigurationselementen gefolgt von\n" "### mehrere Geräten.\n" "###\n" "### Zum Beispiel:\n" "### name: onenic\n" "### config:\n" "### raw.lxc: lxc.aa_profile=unconfined\n" "### devices:\n" "### eth0:\n" "### nictype: bridged\n" "### parent: lxdbr0\n" "### type: nic\n" "###\n" "### Der Name wird zwar angezeigt, lässt sich jedoch nicht ändern.\n" #: lxc/image.go:851 #, c-format msgid "%s (%d more)" msgstr "" #: lxc/utils.go:324 #, c-format msgid "%v (interrupt two more times to force)" msgstr "" #: lxc/snapshot.go:53 #, fuzzy msgid "'/' not allowed in snapshot name" msgstr "'/' ist kein gültiges Zeichen im Namen eines Sicherungspunktes\n" #: lxc/profile.go:289 msgid "(none)" msgstr "" #: lxc/image.go:872 lxc/image.go:901 msgid "ALIAS" msgstr "" #: lxc/image.go:876 msgid "ARCH" msgstr "" #: lxc/list.go:414 msgid "ARCHITECTURE" msgstr "" #: lxc/remote.go:67 msgid "Accept certificate" msgstr "Akzeptiere Zertifikat" #: lxc/remote.go:245 #, c-format msgid "Admin password for %s: " msgstr "Administrator Passwort für %s: " #: lxc/image.go:435 #, fuzzy msgid "Aliases:" msgstr "Aliasse:\n" #: lxc/image.go:413 lxc/info.go:104 #, fuzzy, c-format msgid "Architecture: %s" msgstr "Architektur: %s\n" #: lxc/image.go:444 #, c-format msgid "Auto update: %s" msgstr "" #: lxc/image.go:518 #, fuzzy, c-format msgid "Bad property: %s" msgstr "Ungültige Abbild Eigenschaft: %s\n" #: lxc/info.go:186 msgid "Bytes received" msgstr "" #: lxc/info.go:187 msgid "Bytes sent" msgstr "" #: lxc/config.go:349 msgid "COMMON NAME" msgstr "" #: lxc/list.go:415 msgid "CREATED AT" msgstr "" #: lxc/image.go:443 #, fuzzy, c-format msgid "Cached: %s" msgstr "" "Benutzung: %s\n" "\n" "Optionen:\n" "\n" #: lxc/config.go:156 #, c-format msgid "Can't read from stdin: %s" msgstr "" #: lxc/config.go:169 #, c-format msgid "Can't unset key '%s', it's not currently set" msgstr "" #: lxc/config.go:211 lxc/config.go:237 #, c-format msgid "Can't unset key '%s', it's not currently set." msgstr "" #: lxc/profile.go:441 msgid "Cannot provide container name to list" msgstr "" #: lxc/remote.go:181 #, fuzzy, c-format msgid "Certificate fingerprint: %s" msgstr "Fingerabdruck des Zertifikats: % x\n" #: lxc/remote.go:280 msgid "Client certificate stored at server: " msgstr "Gespeichertes Nutzerzertifikat auf dem Server: " #: lxc/list.go:109 lxc/list.go:110 msgid "Columns" msgstr "" #: lxc/help.go:53 msgid "Commands:" msgstr "" #: lxc/init.go:135 lxc/init.go:136 #, fuzzy msgid "Config key/value to apply to the new container" msgstr "kann nicht zum selben Container Namen kopieren" #: lxc/config.go:647 lxc/config.go:712 lxc/image.go:956 lxc/profile.go:237 #, fuzzy, c-format msgid "Config parsing error: %s" msgstr "YAML Analyse Fehler %v\n" #: lxc/main.go:36 msgid "Connection refused; is LXD running?" msgstr "" #: lxc/publish.go:69 msgid "Container name is mandatory" msgstr "" #: lxc/copy.go:186 lxc/init.go:282 #, c-format msgid "Container name is: %s" msgstr "" #: lxc/publish.go:247 #, fuzzy, c-format msgid "Container published with fingerprint: %s" msgstr "Abbild mit Fingerabdruck %s importiert\n" #: lxc/image.go:135 msgid "Copy aliases from source" msgstr "Kopiere Aliasse von der Quelle" #: lxc/image.go:313 #, c-format msgid "Copying the image: %s" msgstr "" #: lxc/remote.go:196 msgid "Could not create server cert dir" msgstr "Kann Verzeichnis für Zertifikate auf dem Server nicht erstellen" #: lxc/image.go:418 lxc/info.go:106 #, c-format msgid "Created: %s" msgstr "" #: lxc/init.go:190 #, c-format msgid "Creating %s" msgstr "" #: lxc/init.go:188 #, fuzzy msgid "Creating the container" msgstr "kann nicht zum selben Container Namen kopieren" #: lxc/image.go:875 lxc/image.go:903 msgid "DESCRIPTION" msgstr "" #: lxc/config.go:803 #, fuzzy, c-format msgid "Device %s added to %s" msgstr "Gerät %s wurde zu %s hinzugefügt\n" #: lxc/config.go:1039 #, fuzzy, c-format msgid "Device %s removed from %s" msgstr "Gerät %s wurde von %s entfernt\n" #: lxc/info.go:154 msgid "Disk usage:" msgstr "" #: lxc/list.go:505 msgid "EPHEMERAL" msgstr "" #: lxc/config.go:351 msgid "EXPIRY DATE" msgstr "" #: lxc/main.go:48 #, fuzzy msgid "Enable debug mode" msgstr "Aktiviert Debug Modus" #: lxc/main.go:47 #, fuzzy msgid "Enable verbose mode" msgstr "Aktiviert ausführliche Ausgabe" #: lxc/exec.go:56 msgid "Environment variable to set (e.g. HOME=/home/foo)" msgstr "" #: lxc/help.go:77 msgid "Environment:" msgstr "" #: lxc/copy.go:30 lxc/copy.go:31 lxc/init.go:139 lxc/init.go:140 msgid "Ephemeral container" msgstr "Flüchtiger Container" #: lxc/monitor.go:56 msgid "Event type to listen for" msgstr "" #: lxc/image.go:422 #, c-format msgid "Expires: %s" msgstr "" #: lxc/image.go:424 msgid "Expires: never" msgstr "" #: lxc/image.go:710 #, c-format msgid "Exporting the image: %s" msgstr "" #: lxc/config.go:348 lxc/image.go:873 lxc/image.go:902 msgid "FINGERPRINT" msgstr "" #: lxc/utils.go:362 #, c-format msgid "Failed to create alias %s" msgstr "" #: lxc/manpage.go:62 #, c-format msgid "Failed to generate 'lxc.%s.1': %v" msgstr "" #: lxc/manpage.go:55 #, c-format msgid "Failed to generate 'lxc.1': %v" msgstr "" #: lxc/copy.go:181 #, fuzzy msgid "Failed to get the new container name" msgstr "kann nicht zum selben Container Namen kopieren" #: lxc/utils.go:352 #, c-format msgid "Failed to remove alias %s" msgstr "" #: lxc/list.go:112 msgid "Fast mode (same as --columns=nsacPt)" msgstr "" #: lxc/image.go:411 #, fuzzy, c-format msgid "Fingerprint: %s" msgstr "Fingerabdruck: %s\n" #: lxc/action.go:46 lxc/action.go:47 #, fuzzy msgid "Force the container to shutdown" msgstr "Herunterfahren des Containers erzwingen." #: lxc/delete.go:34 lxc/delete.go:35 msgid "Force the removal of running containers" msgstr "" #: lxc/main.go:49 msgid "Force using the local unix socket" msgstr "" #: lxc/list.go:111 msgid "Format (table|json)" msgstr "" #: lxc/main.go:149 #, fuzzy msgid "Generating a client certificate. This may take a minute..." msgstr "Generiere Nutzerzertifikat. Dies kann wenige Minuten dauern...\n" #: lxc/list.go:412 msgid "IPV4" msgstr "" #: lxc/list.go:413 msgid "IPV6" msgstr "" #: lxc/config.go:350 msgid "ISSUE DATE" msgstr "" #: lxc/main.go:157 msgid "" "If this is your first time using LXD, you should also run: sudo lxd init" msgstr "" #: lxc/main.go:50 msgid "Ignore aliases when determining what command to run" msgstr "" #: lxc/action.go:50 #, fuzzy msgid "Ignore the container state (only for start)" msgstr "Herunterfahren des Containers erzwingen." #: lxc/image.go:327 msgid "Image copied successfully!" msgstr "" #: lxc/image.go:770 msgid "Image exported successfully!" msgstr "" #: lxc/image.go:580 #, fuzzy, c-format msgid "Image imported with fingerprint: %s" msgstr "Abbild mit Fingerabdruck %s importiert\n" #: lxc/init.go:141 msgid "Instance type" msgstr "" #: lxc/remote.go:107 #, c-format msgid "Invalid URL scheme \"%s\" in \"%s\"" msgstr "" #: lxc/config.go:329 #, fuzzy msgid "Invalid certificate" msgstr "Akzeptiere Zertifikat" #: lxc/init.go:31 lxc/init.go:36 msgid "Invalid configuration key" msgstr "" #: lxc/file.go:219 #, c-format msgid "Invalid source %s" msgstr "Ungültige Quelle %s" #: lxc/file.go:70 #, c-format msgid "Invalid target %s" msgstr "Ungültiges Ziel %s" #: lxc/info.go:135 msgid "Ips:" msgstr "" #: lxc/image.go:136 msgid "Keep the image up to date after initial copy" msgstr "" #: lxc/main.go:34 msgid "LXD socket not found; is LXD installed and running?" msgstr "" #: lxc/image.go:427 #, c-format msgid "Last used: %s" msgstr "" #: lxc/image.go:429 msgid "Last used: never" msgstr "" #: lxc/info.go:239 msgid "Log:" msgstr "" #: lxc/image.go:134 msgid "Make image public" msgstr "Veröffentliche Abbild" #: lxc/publish.go:34 #, fuzzy msgid "Make the image public" msgstr "Veröffentliche Abbild" #: lxc/info.go:161 msgid "Memory (current)" msgstr "" #: lxc/info.go:165 msgid "Memory (peak)" msgstr "" #: lxc/info.go:177 msgid "Memory usage:" msgstr "" #: lxc/utils.go:256 msgid "Missing summary." msgstr "Fehlende Zusammenfassung." #: lxc/file.go:207 msgid "More than one file to download, but target is not a directory" msgstr "" "Mehr als eine Datei herunterzuladen, aber das Ziel ist kein Verzeichnis" #: lxc/action.go:72 #, fuzzy msgid "Must supply container name for: " msgstr "der Name des Ursprung Containers muss angegeben werden" #: lxc/list.go:416 lxc/remote.go:364 msgid "NAME" msgstr "" #: lxc/remote.go:338 lxc/remote.go:343 msgid "NO" msgstr "" #: lxc/info.go:99 #, c-format msgid "Name: %s" msgstr "" #: lxc/info.go:194 msgid "Network usage:" msgstr "" #: lxc/image.go:137 lxc/publish.go:35 msgid "New alias to define at target" msgstr "" #: lxc/config.go:360 #, fuzzy msgid "No certificate provided to add" msgstr "Kein Zertifikat zum hinzufügen bereitgestellt" #: lxc/config.go:392 msgid "No fingerprint specified." msgstr "Kein Fingerabdruck angegeben." #: lxc/remote.go:92 msgid "Only https URLs are supported for simplestreams" msgstr "" #: lxc/image.go:499 msgid "Only https:// is supported for remote image import." msgstr "" #: lxc/help.go:71 lxc/main.go:130 lxc/main.go:182 msgid "Options:" msgstr "" #: lxc/exec.go:57 msgid "Override the terminal mode (auto, interactive or non-interactive)" msgstr "" #: lxc/list.go:507 msgid "PERSISTENT" msgstr "" #: lxc/list.go:417 msgid "PID" msgstr "" #: lxc/list.go:418 msgid "PROFILES" msgstr "" #: lxc/remote.go:366 msgid "PROTOCOL" msgstr "" #: lxc/image.go:874 lxc/remote.go:367 msgid "PUBLIC" msgstr "" #: lxc/info.go:188 msgid "Packets received" msgstr "" #: lxc/info.go:189 msgid "Packets sent" msgstr "" #: lxc/help.go:78 #, fuzzy msgid "Path to an alternate client configuration directory" msgstr "Alternatives config Verzeichnis." #: lxc/help.go:79 #, fuzzy msgid "Path to an alternate server directory" msgstr "Alternatives config Verzeichnis." #: lxc/main.go:219 #, fuzzy msgid "Pause containers." msgstr "kann nicht zum selben Container Namen kopieren" #: lxc/main.go:38 msgid "Permission denied, are you in the lxd group?" msgstr "" #: lxc/info.go:117 #, c-format msgid "Pid: %d" msgstr "" #: lxc/profile.go:238 msgid "Press enter to open the editor again" msgstr "" #: lxc/config.go:648 lxc/config.go:713 lxc/image.go:957 msgid "Press enter to start the editor again" msgstr "" #: lxc/help.go:73 msgid "Print debug information" msgstr "" #: lxc/help.go:72 msgid "Print less common commands" msgstr "" #: lxc/help.go:74 msgid "Print verbose information" msgstr "" #: lxc/info.go:141 #, fuzzy, c-format msgid "Processes: %d" msgstr "Profil %s erstellt\n" #: lxc/profile.go:188 #, fuzzy, c-format msgid "Profile %s created" msgstr "Profil %s erstellt\n" #: lxc/profile.go:262 #, fuzzy, c-format msgid "Profile %s deleted" msgstr "Profil %s gelöscht\n" #: lxc/init.go:137 lxc/init.go:138 #, fuzzy msgid "Profile to apply to the new container" msgstr "kann nicht zum selben Container Namen kopieren" #: lxc/profile.go:291 #, fuzzy, c-format msgid "Profiles %s applied to %s" msgstr "Profil %s wurde auf %s angewandt\n" #: lxc/info.go:115 #, fuzzy, c-format msgid "Profiles: %s" msgstr "Profil %s erstellt\n" #: lxc/image.go:431 #, fuzzy msgid "Properties:" msgstr "Eigenschaften:\n" #: lxc/remote.go:70 msgid "Public image server" msgstr "" #: lxc/image.go:414 #, fuzzy, c-format msgid "Public: %s" msgstr "Öffentlich: %s\n" #: lxc/remote.go:68 msgid "Remote admin password" msgstr "Entferntes Administrator Passwort" #: lxc/utils.go:315 #, fuzzy msgid "Remote operation canceled by user" msgstr "Server Zertifikat vom Benutzer nicht akzeptiert" #: lxc/info.go:101 #, c-format msgid "Remote: %s" msgstr "" #: lxc/delete.go:42 #, c-format msgid "Remove %s (yes/no): " msgstr "" #: lxc/delete.go:36 lxc/delete.go:37 msgid "Require user confirmation" msgstr "" #: lxc/info.go:138 msgid "Resources:" msgstr "" #: lxc/main.go:227 #, fuzzy msgid "Restart containers." msgstr "kann nicht zum selben Container Namen kopieren" #: lxc/init.go:254 #, c-format msgid "Retrieving image: %s" msgstr "" #: lxc/image.go:877 msgid "SIZE" msgstr "" #: lxc/list.go:419 msgid "SNAPSHOTS" msgstr "" #: lxc/list.go:420 msgid "STATE" msgstr "" #: lxc/remote.go:368 msgid "STATIC" msgstr "" #: lxc/remote.go:189 msgid "Server certificate NACKed by user" msgstr "Server Zertifikat vom Benutzer nicht akzeptiert" #: lxc/remote.go:277 msgid "Server doesn't trust us after adding our cert" msgstr "" "Der Server vertraut uns nicht nachdem er unser Zertifikat hinzugefügt hat" #: lxc/remote.go:69 msgid "Server protocol (lxd or simplestreams)" msgstr "" #: lxc/file.go:57 msgid "Set the file's gid on push" msgstr "Setzt die gid der Datei beim Übertragen" #: lxc/file.go:58 msgid "Set the file's perms on push" msgstr "Setzt die Dateiberechtigungen beim Übertragen" #: lxc/file.go:56 msgid "Set the file's uid on push" msgstr "Setzt die uid der Datei beim Übertragen" #: lxc/help.go:29 msgid "Show all commands (not just interesting ones)" msgstr "Zeigt alle Befehle (nicht nur die interessanten)" #: lxc/help.go:75 msgid "Show client version" msgstr "" #: lxc/info.go:39 msgid "Show the container's last 100 log lines?" msgstr "Zeige die letzten 100 Zeilen Protokoll des Containers?" #: lxc/config.go:35 msgid "Show the expanded configuration" msgstr "" #: lxc/image.go:412 #, fuzzy, c-format msgid "Size: %.2fMB" msgstr "Größe: %.2vMB\n" #: lxc/info.go:208 msgid "Snapshots:" msgstr "" #: lxc/action.go:142 #, fuzzy, c-format msgid "Some containers failed to %s" msgstr "Anhalten des Containers fehlgeschlagen!" #: lxc/image.go:446 msgid "Source:" msgstr "" #: lxc/main.go:237 #, fuzzy msgid "Start containers." msgstr "kann nicht zum selben Container Namen kopieren" #: lxc/launch.go:59 #, c-format msgid "Starting %s" msgstr "" #: lxc/info.go:109 #, c-format msgid "Status: %s" msgstr "" #: lxc/main.go:243 #, fuzzy msgid "Stop containers." msgstr "Anhalten des Containers fehlgeschlagen!" #: lxc/publish.go:36 lxc/publish.go:37 msgid "Stop the container if currently running" msgstr "" #: lxc/publish.go:134 msgid "Stopping container failed!" msgstr "Anhalten des Containers fehlgeschlagen!" #: lxc/delete.go:121 #, fuzzy, c-format msgid "Stopping the container failed: %s" msgstr "Anhalten des Containers fehlgeschlagen!" #: lxc/action.go:49 #, fuzzy msgid "Store the container state (only for stop)" msgstr "Herunterfahren des Containers erzwingen." #: lxc/info.go:169 msgid "Swap (current)" msgstr "" #: lxc/info.go:173 msgid "Swap (peak)" msgstr "" #: lxc/list.go:421 msgid "TYPE" msgstr "" #: lxc/delete.go:105 msgid "The container is currently running, stop it first or pass --force." msgstr "" #: lxc/publish.go:99 msgid "" "The container is currently running. Use --force to have it stopped and " "restarted." msgstr "" #: lxc/config.go:770 lxc/config.go:787 #, fuzzy msgid "The device already exists" msgstr "entfernte Instanz %s existiert bereits" #: lxc/config.go:833 lxc/config.go:845 lxc/config.go:881 lxc/config.go:899 #: lxc/config.go:945 lxc/config.go:962 lxc/config.go:1005 lxc/config.go:1023 #, fuzzy msgid "The device doesn't exist" msgstr "entfernte Instanz %s existiert nicht" #: lxc/init.go:308 #, c-format msgid "The local image '%s' couldn't be found, trying '%s:' instead." msgstr "" #: lxc/action.go:34 msgid "The opposite of \"lxc pause\" is \"lxc start\"." msgstr "" #: lxc/publish.go:72 msgid "There is no \"image name\". Did you want an alias?" msgstr "" #: lxc/help.go:47 msgid "" "This is the LXD command line client.\n" "\n" "All of LXD's features can be driven through the various commands below.\n" "For help with any of those, simply call them with --help." msgstr "" #: lxc/action.go:45 #, fuzzy msgid "Time to wait for the container before killing it" msgstr "Wartezeit bevor der Container gestoppt wird." #: lxc/image.go:415 #, fuzzy msgid "Timestamps:" msgstr "Zeitstempel:\n" #: lxc/main.go:158 msgid "To start your first container, try: lxc launch ubuntu:16.04" msgstr "" #: lxc/copy.go:155 #, fuzzy, c-format msgid "Transferring container: %s" msgstr "kann nicht zum selben Container Namen kopieren" #: lxc/image.go:528 #, c-format msgid "Transferring image: %s" msgstr "" #: lxc/action.go:106 lxc/launch.go:77 #, c-format msgid "Try `lxc info --show-log %s` for more info" msgstr "" #: lxc/info.go:111 msgid "Type: ephemeral" msgstr "" #: lxc/info.go:113 msgid "Type: persistent" msgstr "" #: lxc/image.go:878 msgid "UPLOAD DATE" msgstr "" #: lxc/remote.go:365 msgid "URL" msgstr "" #: lxc/manpage.go:36 msgid "Unable to find help2man." msgstr "" #: lxc/image.go:420 #, c-format msgid "Uploaded: %s" msgstr "" #: lxc/action.go:37 #, c-format msgid "" "Usage: lxc %s [<remote>:]<container> [[<remote>:]<container>...]\n" "\n" "%s%s" msgstr "" #: lxc/help.go:45 #, fuzzy msgid "Usage: lxc <command> [options]" msgstr "" "Benutzung: lxc [Unterbefehl] [Optionen]\n" "Verfügbare Befehle:\n" #: lxc/config.go:60 msgid "" "Usage: lxc config <subcommand> [options]\n" "\n" "Change container or server configuration options.\n" "\n" "*Container configuration*\n" "\n" "lxc config get [<remote>:][container] <key>\n" " Get container or server configuration key.\n" "\n" "lxc config set [<remote>:][container] <key> <value>\n" " Set container or server configuration key.\n" "\n" "lxc config unset [<remote>:][container] <key>\n" " Unset container or server configuration key.\n" "\n" "lxc config show [<remote>:][container] [--expanded]\n" " Show container or server configuration.\n" "\n" "lxc config edit [<remote>:][container]\n" " Edit configuration, either by launching external editor or reading " "STDIN.\n" "\n" "*Device management*\n" "\n" "lxc config device add [<remote>:]<container> <device> <type> [key=value...]\n" " Add a device to a container.\n" "\n" "lxc config device get [<remote>:]<container> <device> <key>\n" " Get a device property.\n" "\n" "lxc config device set [<remote>:]<container> <device> <key> <value>\n" " Set a device property.\n" "\n" "lxc config device unset [<remote>:]<container> <device> <key>\n" " Unset a device property.\n" "\n" "lxc config device list [<remote>:]<container>\n" " List devices for container.\n" "\n" "lxc config device show [<remote>:]<container>\n" " Show full device details for container.\n" "\n" "lxc config device remove [<remote>:]<container> <name>...\n" " Remove device from container.\n" "\n" "*Client trust store management*\n" "\n" "lxc config trust list [<remote>:]\n" " List all trusted certs.\n" "\n" "lxc config trust add [<remote>:] <certfile.crt>\n" " Add certfile.crt to trusted hosts.\n" "\n" "lxc config trust remove [<remote>:] [hostname|fingerprint]\n" " Remove the cert from trusted hosts.\n" "\n" "*Examples*\n" "\n" "cat config.yaml | lxc config edit <container>\n" " Update the container configuration from config.yaml.\n" "\n" "lxc config device add [<remote>:]container1 <device-name> disk source=/share/" "c1 path=opt\n" " Will mount the host's /share/c1 onto /opt in the container.\n" "\n" "lxc config set [<remote>:]<container> limits.cpu 2\n" " Will set a CPU limit of \"2\" for the container.\n" "\n" "lxc config set core.https_address [::]:8443\n" " Will have LXD listen on IPv4 and IPv6 port 8443.\n" "\n" "lxc config set core.trust_password blah\n" " Will set the server's trust password to blah." msgstr "" #: lxc/copy.go:23 msgid "" "Usage: lxc copy [<remote>:]<source>[/<snapshot>] [[<remote>:]<destination>] " "[--ephemeral|e]\n" "\n" "Copy containers within or in between LXD instances." msgstr "" #: lxc/delete.go:27 #, fuzzy msgid "" "Usage: lxc delete [<remote>:]<container>[/<snapshot>] " "[[<remote>:]<container>[/<snapshot>]...]\n" "\n" "Delete containers and snapshots." msgstr "" "Löscht einen Container oder Container Sicherungspunkt.\n" "\n" "Entfernt einen Container (oder Sicherungspunkt) und alle dazugehörigen\n" "Daten (Konfiguration, Sicherungspunkte, ...).\n" #: lxc/exec.go:47 #, fuzzy msgid "" "Usage: lxc exec [<remote>:]<container> [--mode=auto|interactive|non-" "interactive] [--env KEY=VALUE...] [--] <command line>\n" "\n" "Execute commands in containers.\n" "\n" "Mode defaults to non-interactive, interactive mode is selected if both stdin " "AND stdout are terminals (stderr is ignored)." msgstr "" "Führt den angegebenen Befehl in einem Container aus.\n" "\n" "lxc exec <Container> [--env EDITOR=/usr/bin/vim]... <Befehl>\n" #: lxc/file.go:33 msgid "" "Usage: lxc file <subcommand> [options]\n" "\n" "Manage files in containers.\n" "\n" "lxc file pull [<remote>:]<container>/<path> [[<remote>:]<container>/" "<path>...] <target path>\n" " Pull files from containers.\n" "\n" "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source path> [<source " "path>...] [<remote>:]<container>/<path>\n" " Push files into containers.\n" "\n" "lxc file edit [<remote>:]<container>/<path>\n" " Edit files in containers using the default text editor.\n" "\n" "*Examples*\n" "lxc file push /etc/hosts foo/etc/hosts\n" " To push /etc/hosts into the container \"foo\".\n" "\n" "lxc file pull foo/etc/hosts .\n" " To pull /etc/hosts from the container and write it to the current " "directory." msgstr "" #: lxc/finger.go:15 msgid "" "Usage: lxc finger [<remote>:]\n" "\n" "Check if the LXD server is alive." msgstr "" #: lxc/help.go:22 msgid "" "Usage: lxc help [--all]\n" "\n" "Help page for the LXD client." msgstr "" #: lxc/image.go:63 msgid "" "Usage: lxc image <subcommand> [options]\n" "\n" "Manipulate container images.\n" "\n" "In LXD containers are created from images. Those images were themselves\n" "either generated from an existing container or downloaded from an image\n" "server.\n" "\n" "When using remote images, LXD will automatically cache images for you\n" "and remove them upon expiration.\n" "\n" "The image unique identifier is the hash (sha-256) of its representation\n" "as a compressed tarball (or for split images, the concatenation of the\n" "metadata and rootfs tarballs).\n" "\n" "Images can be referenced by their full hash, shortest unique partial\n" "hash or alias name (if one is set).\n" "\n" "\n" "lxc image import <tarball> [<rootfs tarball>|<URL>] [<remote>:] [--public] " "[--created-at=ISO-8601] [--expires-at=ISO-8601] [--fingerprint=FINGERPRINT] " "[--alias=ALIAS...] [prop=value]\n" " Import an image tarball (or tarballs) into the LXD image store.\n" "\n" "lxc image copy [<remote>:]<image> <remote>: [--alias=ALIAS...] [--copy-" "aliases] [--public] [--auto-update]\n" " Copy an image from one LXD daemon to another over the network.\n" "\n" " The auto-update flag instructs the server to keep this image up to\n" " date. It requires the source to be an alias and for it to be public.\n" "\n" "lxc image delete [<remote>:]<image> [[<remote>:]<image>...]\n" " Delete one or more images from the LXD image store.\n" "\n" "lxc image export [<remote>:]<image> [target]\n" " Export an image from the LXD image store into a distributable tarball.\n" "\n" " The output target is optional and defaults to the working directory.\n" " The target may be an existing directory, file name, or \"-\" to specify\n" " stdout. The target MUST be a directory when exporting a split image.\n" " If the target is a directory, the image's name (each part's name for\n" " split images) as found in the database will be used for the exported\n" " image. If the target is a file (not a directory and not stdout), then\n" " the appropriate extension will be appended to the provided file name\n" " based on the algorithm used to compress the image.\n" "\n" "lxc image info [<remote>:]<image>\n" " Print everything LXD knows about a given image.\n" "\n" "lxc image list [<remote>:] [filter]\n" " List images in the LXD image store. Filters may be of the\n" " <key>=<value> form for property based filtering, or part of the image\n" " hash or part of the image alias name.\n" "\n" "lxc image show [<remote>:]<image>\n" " Yaml output of the user modifiable properties of an image.\n" "\n" "lxc image edit [<remote>:]<image>\n" " Edit image, either by launching external editor or reading STDIN.\n" " Example: lxc image edit <image> # launch editor\n" " cat image.yaml | lxc image edit <image> # read from image.yaml\n" "\n" "lxc image alias create [<remote>:]<alias> <fingerprint>\n" " Create a new alias for an existing image.\n" "\n" "lxc image alias delete [<remote>:]<alias>\n" " Delete an alias.\n" "\n" "lxc image alias list [<remote>:] [filter]\n" " List the aliases. Filters may be part of the image hash or part of the " "image alias name." msgstr "" #: lxc/info.go:26 msgid "" "Usage: lxc info [<remote>:][<container>] [--show-log]\n" "\n" "Show container or server information.\n" "\n" "lxc info [<remote>:]<container> [--show-log]\n" " For container information.\n" "\n" "lxc info [<remote>:]\n" " For LXD server information." msgstr "" #: lxc/init.go:75 #, fuzzy msgid "" "Usage: lxc init [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--" "profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance " "type>]\n" "\n" "Create containers from images.\n" "\n" "Not specifying -p will result in the default profile.\n" "Specifying \"-p\" with no argument will result in no profile.\n" "\n" "Examples:\n" " lxc init ubuntu:16.04 u1" msgstr "" "lxc init <Abbild> [<Name>] [--ephemeral|-e] [--profile|-p <Profil>...]\n" "\n" "Initialisiert einen Container mit Namen von dem angegebenen Abbild .\n" "\n" "Ohne den -p Parameter wird das default Profil benutzt.\n" "Wird -p ohne Argument angegeben, wird kein Profil verwendet\n" "\n" "Beispiel:\n" "lxc init ubuntu u1\n" #: lxc/launch.go:20 #, fuzzy msgid "" "Usage: lxc launch [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--" "profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance " "type>]\n" "\n" "Create and start containers from images.\n" "\n" "Not specifying -p will result in the default profile.\n" "Specifying \"-p\" with no argument will result in no profile.\n" "\n" "Examples:\n" " lxc launch ubuntu:16.04 u1" msgstr "" "Starte Container von gegebenem Abbild.\n" "\n" "lxc launch <Abbild> [<Name>] [—ephemeral|-e] [—profile|-p <Profile>…]\n" "\n" "Startet einen Container von gegebenem Abbild und mit Namen\n" "\n" "Ohne den -p Parameter wird das default Profil benutzt.\n" "Wird -p ohne Argument angegeben, wird kein Profil verwendet\n" "\n" "Beispiel:\n" "lxc launch ubuntu u1\n" #: lxc/list.go:46 #, fuzzy msgid "" "Usage: lxc list [<remote>:] [filters] [--format table|json] [-c <columns>] " "[--fast]\n" "\n" "List the existing containers.\n" "\n" "Default column layout: ns46tS\n" "Fast column layout: nsacPt\n" "\n" "*Filters*\n" "A single keyword like \"web\" which will list any container with a name " "starting by \"web\".\n" "\n" "A regular expression on the container name. (e.g. .*web.*01$).\n" "\n" "A key/value pair referring to a configuration item. For those, the namespace " "can be abbreviated to the smallest unambiguous identifier.\n" " - \"user.blah=abc\" will list all containers with the \"blah\" user " "property set to \"abc\".\n" "\n" " - \"u.blah=abc\" will do the same\n" "\n" " - \"security.privileged=true\" will list all privileged containers\n" "\n" " - \"s.privileged=true\" will do the same\n" "\n" "A regular expression matching a configuration item or its value. (e.g. " "volatile.eth0.hwaddr=00:16:3e:.*).\n" "\n" "*Columns*\n" "The -c option takes a comma separated list of arguments that control\n" "which container attributes to output when displaying in table format.\n" "\n" "Column arguments are either pre-defined shorthand chars (see below),\n" "or (extended) config keys.\n" "\n" "Commas between consecutive shorthand chars are optional.\n" "\n" "Pre-defined column shorthand chars:\n" "\n" " 4 - IPv4 address\n" "\n" " 6 - IPv6 address\n" "\n" " a - Architecture\n" "\n" " c - Creation date\n" "\n" " l - Last used date\n" "\n" " n - Name\n" "\n" " p - PID of the container's init process\n" "\n" " P - Profiles\n" "\n" " s - State\n" "\n" " S - Number of snapshots\n" "\n" " t - Type (persistent or ephemeral)\n" "\n" "*Examples*\n" "lxc list -c ns46\n" " Shows a list of containers using the \"NAME\", \"STATE\", \"IPV4\", " "\"IPV6\" columns." msgstr "" "Listet vorhandene Ressourcen.\n" "\n" "lxc list [Resource] [Filter]\n" "\n" "Filter sind:\n" "* Ein einzelnes Schlüsselwort wie \"web“, was alle Container mit \"web\" im " "Namen listet.\n" "* Ein key/value Paar bezüglich eines Konfigurationsparameters. Dafür kann " "der Namensraum, solange eindeutig, abgekürzt werden:\n" "* \"user.blah=abc\" listet alle Container mit der \"blah\" Benutzer " "Eigenschaft \"abc\"\n" "* \"u.blah=abc\" ebenfalls\n" "* \"security.privileged=1\" listet alle privilegierten Container\n" "* \"s.privileged=1\" ebenfalls\n" #: lxc/manpage.go:20 msgid "" "Usage: lxc manpage <directory>\n" "\n" "Generate all the LXD manpages." msgstr "" #: lxc/monitor.go:41 msgid "" "Usage: lxc monitor [<remote>:] [--type=TYPE...]\n" "\n" "Monitor a local or remote LXD server.\n" "\n" "By default the monitor will listen to all message types.\n" "\n" "Message types to listen for can be specified with --type.\n" "\n" "*Examples*\n" "lxc monitor --type=logging\n" " Only show log message." msgstr "" #: lxc/move.go:20 #, fuzzy msgid "" "Usage: lxc move [<remote>:]<container>[/<snapshot>] [<remote>:][<container>[/" "<snapshot>]]\n" "\n" "Move containers within or in between LXD instances.\n" "\n" "lxc move [<remote>:]<source container> [<remote>:][<destination container>]\n" " Move a container between two hosts, renaming it if destination name " "differs.\n" "\n" "lxc move <old name> <new name>\n" " Rename a local container.\n" "\n" "lxc move <container>/<old snapshot name> <container>/<new snapshot name>\n" " Rename a snapshot." msgstr "" "Verschiebt Container innerhalb einer oder zwischen lxd Instanzen\n" "\n" "lxc move <Quelle> <Ziel>\n" #: lxc/profile.go:49 #, fuzzy msgid "" "Usage: lxc profile <subcommand> [options]\n" "\n" "Manage container configuration profiles.\n" "\n" "*Profile configuration*\n" "lxc profile list [<remote>:]\n" " List available profiles.\n" "\n" "lxc profile show [<remote>:]<profile>\n" " Show details of a profile.\n" "\n" "lxc profile create [<remote>:]<profile>\n" " Create a profile.\n" "\n" "lxc profile copy [<remote>:]<profile> [<remote>:]<profile>\n" " Copy the profile.\n" "\n" "lxc profile get [<remote>:]<profile> <key>\n" " Get profile configuration.\n" "\n" "lxc profile set [<remote>:]<profile> <key> <value>\n" " Set profile configuration.\n" "\n" "lxc profile unset [<remote>:]<profile> <key>\n" " Unset profile configuration.\n" "\n" "lxc profile delete [<remote>:]<profile>\n" " Delete a profile.\n" "\n" "lxc profile edit [<remote>:]<profile>\n" " Edit profile, either by launching external editor or reading STDIN.\n" "\n" "*Profile assignment*\n" "lxc profile apply [<remote>:]<container> <profiles>\n" " Replace the current set of profiles for the container by the one " "provided.\n" "\n" "*Device management*\n" "lxc profile device list [<remote>:]<profile>\n" " List devices in the given profile.\n" "\n" "lxc profile device show [<remote>:]<profile>\n" " Show full device details in the given profile.\n" "\n" "lxc profile device remove [<remote>:]<profile> <name>\n" " Remove a device from a profile.\n" "\n" "lxc profile device get [<remote>:]<profile> <name> <key>\n" " Get a device property.\n" "\n" "lxc profile device set [<remote>:]<profile> <name> <key> <value>\n" " Set a device property.\n" "\n" "lxc profile device unset [<remote>:]<profile> <name> <key>\n" " Unset a device property.\n" "\n" "lxc profile device add [<remote>:]<profile> <device> <type> [key=value...]\n" " Add a profile device, such as a disk or a nic, to the containers using " "the specified profile.\n" "\n" "*Examples*\n" "cat profile.yaml | lxc profile edit <profile>\n" " Update a profile using the content of profile.yaml\n" "\n" "lxc profile apply foo default,bar\n" " Set the profiles for \"foo\" to \"default\" and \"bar\".\n" "\n" "lxc profile apply foo default\n" " Reset \"foo\" to only using the \"default\" profile.\n" "\n" "lxc profile apply foo ''\n" " Remove all profile from \"foo\"" msgstr "" "Verwalte Konfigurationsprofile.\n" "\n" "lxc profile list [Filter] Listet verfügbare Profile\n" "lxc profile show <Profil> Zeigt Details zu einem Profil\n" "lxc profile create <Profil> Erstellt ein Profil\n" "lxc profile edit <Profil> Bearbeitet das Profil in " "externem Editor\n" "lxc profile copy <Profil> <remote> Kopiert das Profil zur " "entfernten Instanz\n" "lxc profile set <Profil> <key> <value> Setzt eine " "Profilkonfiguration\n" "lxc profile delete <Profil> Löscht ein Profil\n" "lxc profile apply <Container> <Profil>\n" " Wendet eine durch Kommata getrennte Liste von Profilen,\n" " in gegeben Reihenfolge, auf einen Container an.\n" " Alle angegeben, und nur diese, werden auf den Container angewandt.\n" " Beispiel: lxc profile apply foo default,bar # Wende default und bar an\n" " lxc profile apply foo default # Nur default ist aktiv\n" " lxc profile apply '' # keine Profile werden angewandt\n" " lxc profile apply bar,default # Wende nun default als zweites " "an\n" "\n" "Geräte:\n" "lxc profile device list <Profil> Listet Geräte im Profil\n" "lxc profile device show <Profil> Zeigt alle Geräte Details im " "gegebenen Profil.\n" "lxc profile device remove <Profil> <name> Entfernt ein Gerät von dem " "Profil.\n" "lxc profile device add <Profil name> <Gerätename> <Gerätetype> " "[key=value]...\n" " Fügt ein Gerät, wie zum Beispiel eine Festplatte oder Netzwerkkarte, den " "Containern hinzu,\n" " die dieses Profil verwenden.\n" #: lxc/publish.go:27 msgid "" "Usage: lxc publish [<remote>:]<container>[/<snapshot>] [<remote>:] [--" "alias=ALIAS...] [prop-key=prop-value...]\n" "\n" "Publish containers as images." msgstr "" #: lxc/remote.go:39 #, fuzzy msgid "" "Usage: lxc remote <subcommand> [options]\n" "\n" "Manage the list of remote LXD servers.\n" "\n" "lxc remote add <remote> <IP|FQDN|URL> [--accept-certificate] [--" "password=PASSWORD] [--public] [--protocol=PROTOCOL]\n" " Add the remote <remote> at <url>.\n" "\n" "lxc remote remove <remote>\n" " Remove the remote <remote>.\n" "\n" "lxc remote list\n" " List all remotes.\n" "\n" "lxc remote rename <old name> <new name>\n" " Rename remote <old name> to <new name>.\n" "\n" "lxc remote set-url <remote> <url>\n" " Update <remote>'s url to <url>.\n" "\n" "lxc remote set-default <remote>\n" " Set the default remote.\n" "\n" "lxc remote get-default\n" " Print the default remote." msgstr "" "Verwalte entfernte LXD Server.\n" "\n" "lxc remote add <Name> <url> [--accept-certificate] [--password=PASSWORT] " "Fügt die Instanz <Name> auf <URL> hinzu.\n" "lxc remote remove <Name> " "Entfernt die Instanz <Name>.\n" "lxc remote list " "Listet alle entfernte Instanzen.\n" "lxc remote rename <alt> <neu> " "Benennt Instanz von <alt> nach <neu> um.\n" "lxc remote set-url <Name> <url> " "Setzt die URL von <Name> auf <url>.\n" "lxc remote set-default <Name> " "Setzt die Standard Instanz.\n" "lxc remote get-default " "Gibt die Standard Instanz aus.\n" #: lxc/restore.go:22 msgid "" "Usage: lxc restore [<remote>:]<container> <snapshot> [--stateful]\n" "\n" "Restore containers from snapshots.\n" "\n" "If --stateful is passed, then the running state will be restored too.\n" "\n" "*Examples*\n" "lxc snapshot u1 snap0\n" " Create the snapshot.\n" "\n" "lxc restore u1 snap0\n" " Restore the snapshot." msgstr "" #: lxc/snapshot.go:22 msgid "" "Usage: lxc snapshot [<remote>:]<container> <snapshot name> [--stateful]\n" "\n" "Create container snapshots.\n" "\n" "When --stateful is used, LXD attempts to checkpoint the container's\n" "running state, including process memory state, TCP connections, ...\n" "\n" "*Examples*\n" "lxc snapshot u1 snap0\n" " Create a snapshot of \"u1\" called \"snap0\"." msgstr "" #: lxc/version.go:18 #, fuzzy msgid "" "Usage: lxc version\n" "\n" "Print the version number of this client tool." msgstr "" "Zeigt die Versionsnummer von LXD.\n" "\n" "lxc version\n" #: lxc/delete.go:46 msgid "User aborted delete operation." msgstr "" #: lxc/utils.go:320 msgid "" "User signaled us three times, exiting. The remote operation will keep " "running." msgstr "" #: lxc/restore.go:38 msgid "" "Whether or not to restore the container's running state from snapshot (if " "available)" msgstr "" "Laufenden Zustand des Containers aus dem Sicherungspunkt (falls vorhanden) " "wiederherstellen oder nicht" #: lxc/snapshot.go:36 msgid "Whether or not to snapshot the container's running state" msgstr "Zustand des laufenden Containers sichern oder nicht" #: lxc/remote.go:340 lxc/remote.go:345 msgid "YES" msgstr "" #: lxc/copy.go:49 #, fuzzy msgid "You must specify a source container name" msgstr "der Name des Ursprung Containers muss angegeben werden" #: lxc/main.go:68 msgid "`lxc config profile` is deprecated, please use `lxc profile`" msgstr "" #: lxc/remote.go:328 msgid "can't remove the default remote" msgstr "" #: lxc/remote.go:354 msgid "default" msgstr "" #: lxc/init.go:276 msgid "didn't get any affected image, container or snapshot from server" msgstr "" #: lxc/image.go:406 msgid "disabled" msgstr "" #: lxc/image.go:408 msgid "enabled" msgstr "" #: lxc/action.go:134 lxc/main.go:29 lxc/main.go:178 #, fuzzy, c-format msgid "error: %v" msgstr "Fehler: %v\n" #: lxc/help.go:37 lxc/main.go:124 #, fuzzy, c-format msgid "error: unknown command: %s" msgstr "Fehler: unbekannter Befehl: %s\n" #: lxc/image.go:396 lxc/image.go:401 lxc/image.go:854 msgid "no" msgstr "" #: lxc/remote.go:182 #, fuzzy msgid "ok (y/n)?" msgstr "OK (y/n)? " #: lxc/main.go:313 lxc/main.go:317 #, c-format msgid "processing aliases failed %s\n" msgstr "" #: lxc/remote.go:390 #, c-format msgid "remote %s already exists" msgstr "entfernte Instanz %s existiert bereits" #: lxc/remote.go:320 lxc/remote.go:382 lxc/remote.go:417 lxc/remote.go:433 #, c-format msgid "remote %s doesn't exist" msgstr "entfernte Instanz %s existiert nicht" #: lxc/remote.go:303 #, c-format msgid "remote %s exists as <%s>" msgstr "entfernte Instanz %s existiert als <%s>" #: lxc/remote.go:324 lxc/remote.go:386 lxc/remote.go:421 #, c-format msgid "remote %s is static and cannot be modified" msgstr "" #: lxc/info.go:219 msgid "stateful" msgstr "" #: lxc/info.go:221 msgid "stateless" msgstr "" #: lxc/info.go:215 #, c-format msgid "taken at %s" msgstr "" #: lxc/main.go:252 msgid "wrong number of subcommand arguments" msgstr "falsche Anzahl an Parametern für Unterbefehl" #: lxc/delete.go:45 lxc/image.go:398 lxc/image.go:403 lxc/image.go:858 msgid "yes" msgstr "" #~ msgid "can't copy to the same container name" #~ msgstr "kann nicht zum selben Container Namen kopieren" #~ msgid "not all the profiles from the source exist on the target" #~ msgstr "nicht alle Profile der Quelle sind am Ziel vorhanden." #~ msgid "bad number of things scanned from image, container or snapshot" #~ msgstr "" #~ "Falsche Anzahl an Objekten im Abbild, Container oder Sicherungspunkt " #~ "gelesen." #~ msgid "got bad version" #~ msgstr "Versionskonflikt" #, fuzzy #~ msgid "" #~ "Changes state of one or more containers to %s.\n" #~ "\n" #~ "lxc %s <name> [<name>...]%s" #~ msgstr "" #~ "Ändert den Laufzustand eines Containers in %s.\n" #~ "\n" #~ "lxd %s <Name>\n" #, fuzzy #~ msgid "" #~ "Copy containers within or in between lxd instances.\n" #~ "\n" #~ "lxc copy [remote:]<source container> [remote:]<destination container> [--" #~ "ephemeral|e]" #~ msgstr "" #~ "Kopiert Container innerhalb einer oder zwischen lxd Instanzen\n" #~ "\n" #~ "lxc copy <Quelle> <Ziel>\n" #, fuzzy #~ msgid "" #~ "Fingers the LXD instance to check if it is up and working.\n" #~ "\n" #~ "lxc finger <remote>" #~ msgstr "" #~ "Fingert die LXD Instanz zum überprüfen ob diese funktionsfähig ist.\n" #~ "\n" #~ "lxc finger <remote>\n" #, fuzzy #~ msgid "" #~ "Initialize a container from a particular image.\n" #~ "\n" #~ "lxc init [remote:]<image> [remote:][<name>] [--ephemeral|-e] [--profile|-" #~ "p <profile>...] [--config|-c <key=value>...]\n" #~ "\n" #~ "Initializes a container using the specified image and name.\n" #~ "\n" #~ "Not specifying -p will result in the default profile.\n" #~ "Specifying \"-p\" with no argument will result in no profile.\n" #~ "\n" #~ "Example:\n" #~ "lxc init ubuntu u1" #~ msgstr "" #~ "Starte Container von gegebenem Abbild.\n" #~ "\n" #~ "lxc launch <Abbild> [<Name>] [—ephemeral|-e] [—profile|-p <Profile>…]\n" #~ "\n" #~ "Startet einen Container von gegebenem Abbild und mit Namen\n" #~ "\n" #~ "Ohne den -p Parameter wird das default Profil benutzt.\n" #~ "Wird -p ohne Argument angegeben, wird kein Profil verwendet\n" #~ "\n" #~ "Beispiel:\n" #~ "lxc launch ubuntu u1\n" #, fuzzy #~ msgid "" #~ "List information on LXD servers and containers.\n" #~ "\n" #~ "For a container:\n" #~ " lxc info [<remote>:]container [--show-log]\n" #~ "\n" #~ "For a server:\n" #~ " lxc info [<remote>:]" #~ msgstr "" #~ "Listet Informationen über Container.\n" #~ "\n" #~ "Dies wird entfernte Instanzen und Abbilder unterstützen, \n" #~ "zur Zeit jedoch nur Container.\n" #~ "\n" #~ "lxc info [<remote>:]Container [--show-log]\n" #, fuzzy #~ msgid "" #~ "Manage configuration.\n" #~ "\n" #~ "lxc config device add <[remote:]container> <name> <type> " #~ "[key=value]... Add a device to a container.\n" #~ "lxc config device get <[remote:]container> <name> " #~ "<key> Get a device property.\n" #~ "lxc config device set <[remote:]container> <name> <key> " #~ "<value> Set a device property.\n" #~ "lxc config device unset <[remote:]container> <name> " #~ "<key> Unset a device property.\n" #~ "lxc config device list " #~ "<[remote:]container> List devices for " #~ "container.\n" #~ "lxc config device show " #~ "<[remote:]container> Show full device " #~ "details for container.\n" #~ "lxc config device remove <[remote:]container> " #~ "<name> Remove device from container.\n" #~ "\n" #~ "lxc config get [remote:][container] " #~ "<key> Get container or server " #~ "configuration key.\n" #~ "lxc config set [remote:][container] <key> " #~ "<value> Set container or server configuration " #~ "key.\n" #~ "lxc config unset [remote:][container] " #~ "<key> Unset container or server " #~ "configuration key.\n" #~ "lxc config show [remote:][container] [--" #~ "expanded] Show container or server " #~ "configuration.\n" #~ "lxc config edit [remote:]" #~ "[container] Edit container or " #~ "server configuration in external editor.\n" #~ " Edit configuration, either by launching external editor or reading " #~ "STDIN.\n" #~ " Example: lxc config edit <container> # launch editor\n" #~ " cat config.yaml | lxc config edit <config> # read from " #~ "config.yaml\n" #~ "\n" #~ "lxc config trust list " #~ "[remote] List all trusted " #~ "certs.\n" #~ "lxc config trust add [remote] <certfile." #~ "crt> Add certfile.crt to trusted hosts.\n" #~ "lxc config trust remove [remote] [hostname|" #~ "fingerprint] Remove the cert from trusted hosts.\n" #~ "\n" #~ "Examples:\n" #~ "To mount host's /share/c1 onto /opt in the container:\n" #~ " lxc config device add [remote:]container1 <device-name> disk source=/" #~ "share/c1 path=opt\n" #~ "\n" #~ "To set an lxc config value:\n" #~ " lxc config set [remote:]<container> raw.lxc 'lxc.aa_allow_incomplete " #~ "= 1'\n" #~ "\n" #~ "To listen on IPv4 and IPv6 port 8443 (you can omit the 8443 its the " #~ "default):\n" #~ " lxc config set core.https_address [::]:8443\n" #~ "\n" #~ "To set the server trust password:\n" #~ " lxc config set core.trust_password blah" #~ msgstr "" #~ "Verwalte Konfiguration.\n" #~ "\n" #~ "lxc config device add <Container> <Name> <Type> [key=value]...\n" #~ " Füge ein Gerät zu einem Container hinzu\n" #~ "lxc config device list <Container> Listet die Geräte " #~ "des Containers\n" #~ "lxc config device show <Container> Zeigt alle Geräte " #~ "Details für den Container\n" #~ "lxc config device remove <Container> <Name> Entfernt Gerät vom " #~ "Container\n" #~ "lxc config edit <Container> Bearbeite " #~ "Container Konfiguration in externem Editor\n" #~ "lxc config get <Container> key Holt " #~ "Konfigurationsschlüssel\n" #~ "lxc config set <Container> key [value] Setzt Container " #~ "Konfigurationsschlüssel\n" #~ "lxc config show <Container> Zeigt " #~ "Konfiguration des Containers\n" #~ "lxc config trust list [remote] Liste alle " #~ "vertrauenswürdigen Zertifikate.\n" #~ "lxc config trust add [remote] [certfile.crt] Füge certfile.crt " #~ "zu vertrauenden Instanzen hinzu.\n" #~ "lxc config trust remove [remote] [hostname|fingerprint]\n" #~ " Löscht das Zertifikat aus der Liste der " #~ "vertrauenswürdigen.\n" #~ "\n" #~ "Beispiele:\n" #~ "Zum mounten von /share/c1 des Hosts nach /opt im Container:\n" #~ "\tlxc config device add container1 mntdir disk source=/share/c1 path=opt\n" #~ "Um einen lxc config Wert zu setzen:\n" #~ "\tlxc config set <container> raw.lxc 'lxc.aa_allow_incomplete = 1'\n" #~ "Um das Server Passwort zur authentifizierung zu setzen:\n" #~ "\tlxc config set core.trust_password blah\n" #, fuzzy #~ msgid "" #~ "Manage files on a container.\n" #~ "\n" #~ "lxc file pull <source> [<source>...] <target>\n" #~ "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source> " #~ "[<source>...] <target>\n" #~ "lxc file edit <file>\n" #~ "\n" #~ "<source> in the case of pull, <target> in the case of push and <file> in " #~ "the case of edit are <container name>/<path>" #~ msgstr "" #~ "Verwaltet Dateien in einem Container.\n" #~ "\n" #~ "lxc file pull <Quelle> [<Quelle>...] <Ziel>\n" #~ "lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <Quelle> " #~ "[<Quelle>...] <Ziel>\n" #~ "\n" #~ "<Quelle> bei pull und <Ziel> bei push sind jeweils von der Form " #~ "<Container Name>/<Pfad>\n" #, fuzzy #~ msgid "" #~ "Presents details on how to use LXD.\n" #~ "\n" #~ "lxd help [--all]" #~ msgstr "" #~ "Zeigt Details über die Benutzung von LXD an.\n" #~ "\n" #~ "lxd help [—all]\n" #, fuzzy #~ msgid "Profile %s added to %s" #~ msgstr "Profil %s wurde auf %s angewandt\n" #, fuzzy #~ msgid "Profile %s removed from %s" #~ msgstr "Gerät %s wurde von %s entfernt\n" #, fuzzy #~ msgid "For example: 'lxd-images import ubuntu --alias ubuntu'." #~ msgstr "Zum Beispiel: 'lxd-images import ubuntu --alias ubuntu'.\n" #, fuzzy #~ msgid "" #~ "If this is your first run, you will need to import images using the 'lxd-" #~ "images' script." #~ msgstr "" #~ "Falls dies der erste Start ist, sollten Sie mit dem 'lxd-images' Script " #~ "Abbilder importieren.\n" #~ msgid "Cannot change profile name" #~ msgstr "Profilname kann nicht geändert werden" #, fuzzy #~ msgid "" #~ "Create a read-only snapshot of a container.\n" #~ "\n" #~ "lxc snapshot [remote:]<source> <snapshot name> [--stateful]" #~ msgstr "" #~ "Erstellt einen schreibgeschützten Sicherungspunkt des Containers.\n" #~ "\n" #~ "lxc snapshot <Quelle> <Sicherungspunkt> [--stateful]\n" #, fuzzy #~ msgid "Error adding alias %s" #~ msgstr "Fehler beim hinzufügen des Alias %s\n" #, fuzzy #~ msgid "" #~ "Manipulate container images.\n" #~ "\n" #~ "lxc image import <tarball> [rootfs tarball|URL] [target] [--public] [--" #~ "created-at=ISO-8601] [--expires-at=ISO-8601] [--fingerprint=FINGERPRINT] " #~ "[prop=value]\n" #~ "\n" #~ "lxc image copy [remote:]<image> <remote>: [--alias=ALIAS].. [--copy-" #~ "aliases] [--public]\n" #~ "lxc image delete [remote:]<image>\n" #~ "lxc image export [remote:]<image>\n" #~ "lxc image info [remote:]<image>\n" #~ "lxc image list [remote:] [filter]\n" #~ "lxc image show [remote:]<image>\n" #~ "lxc image edit [remote:]<image>\n" #~ " Edit image, either by launching external editor or reading STDIN.\n" #~ " Example: lxc image edit <image> # launch editor\n" #~ " cat image.yml | lxc image edit <image> # read from image." #~ "yml\n" #~ "\n" #~ "Lists the images at specified remote, or local images.\n" #~ "Filters are not yet supported.\n" #~ "\n" #~ "lxc image alias create <alias> <target>\n" #~ "lxc image alias delete <alias>\n" #~ "lxc image alias list [remote:]\n" #~ "\n" #~ "Create, delete, list image aliases. Example:\n" #~ "lxc remote add store2 images.linuxcontainers.org\n" #~ "lxc image alias list store2:" #~ msgstr "" #~ "Ändere Container Abbilder\n" #~ "\n" #~ "lxc image import <tarball> [Ziel] [--public] [--created-at=ISO-8601] [--" #~ "expires-at=ISO-8601] [--fingerprint=FINGERPRINT] [prop=value]\n" #~ "\n" #~ "lxc image copy [remote:]<Abbild> <remote>: [--alias=ALIAS].. [--copy-" #~ "alias]\n" #~ "lxc image delete [remote:]<Abbild>\n" #~ "lxc image edit [remote:]<Abbild>\n" #~ "lxc image export [remote:]<Abbild>\n" #~ "lxc image info [remote:]<Abbild>\n" #~ "lxc image list [remote:] [Filter]\n" #~ "lxc image show [remote:]<Abbild>\n" #~ "\n" #~ "Listet die Abbilder auf der entfernten oder lokalen Instanz.\n" #~ "Filter werden noch nicht unterstützt.\n" #~ "\n" #~ "lxc image alias create <alias> <Ziel>\n" #~ "lxc image alias delete <alias>\n" #~ "lxc remote add images images.linuxcontainers.org\n" #~ "lxc image alias list images:\n" #~ "erstelle, lösche und liste Abbild Aliasse\n" #~ msgid "No certificate on this connection" #~ msgstr "Kein Zertifikat für diese Verbindung" #~ msgid "" #~ "Server certificate for host %s has changed. Add correct certificate or " #~ "remove certificate in %s" #~ msgstr "" #~ "Server Zertifikat für Rechner %s hat sich geändert. Fürgen Sie das " #~ "richtige Zertifikat hinzu oder löschen Sie das Zertifikat unter %s" #, fuzzy #~ msgid "" #~ "Set the current state of a resource back to its state at the time the " #~ "snapshot was created.\n" #~ "\n" #~ "lxc restore [remote:]<resource> <snapshot name> [--stateful]" #~ msgstr "" #~ "Setzt eine Ressource auf einen Sicherungspunkt zurück.\n" #~ "\n" #~ "lxc restore <Resource> <Name des Sicherungspunktes> [—stateful]\n" #~ msgid "api version mismatch: mine: %q, daemon: %q" #~ msgstr "API Versionskonflikt: meine: %q, Hintergrund Dienst: %q" #~ msgid "bad profile url %s" #~ msgstr "Fehlerhafte Profil URL %s" #~ msgid "bad version in profile url" #~ msgstr "Falsche Version in Profil URL" #, fuzzy #~ msgid "error." #~ msgstr "Fehler: %v\n" #~ msgid "no response!" #~ msgstr "keine Antwort!" #, fuzzy #~ msgid "no value found in %q" #~ msgstr "kein Wert in %q gefunden\n" #~ msgid "unknown remote name: %q" #~ msgstr "unbekannter entfernter Instanz Name: %q" #, fuzzy #~ msgid "unknown transport type: %s" #~ msgstr "unbekannter entfernter Instanz Name: %q" #~ msgid "cannot resolve unix socket address: %v" #~ msgstr "kann unix Socket Adresse %v nicht auflösen" #, fuzzy #~ msgid "unknown group %s" #~ msgstr "unbekannter entfernter Instanz Name: %q" #, fuzzy #~ msgid "Information about remotes not yet supported" #~ msgstr "" #~ "Informationen über entfernte Instanzen wird noch nicht unterstützt\n" #~ msgid "Unknown image command %s" #~ msgstr "Unbekannter Befehl %s für Abbild" #~ msgid "Unknown remote subcommand %s" #~ msgstr "Unbekannter Unterbefehl %s für entfernte Instanz" #~ msgid "Unkonwn config trust command %s" #~ msgstr "Unbekannter config Befehl %s" #, fuzzy #~ msgid "YAML parse error %v" #~ msgstr "YAML Analyse Fehler %v\n" #~ msgid "invalid argument %s" #~ msgstr "ungültiges Argument %s" #, fuzzy #~ msgid "unknown profile cmd %s" #~ msgstr "Unbekannter Befehl %s für Abbild" #, fuzzy #~ msgid "Publish to remote server is not supported yet" #~ msgstr "" #~ "Anzeigen von Informationen über entfernte Instanzen wird noch nicht " #~ "unterstützt\n" #, fuzzy #~ msgid "Use an alternative config path." #~ msgstr "Alternatives config Verzeichnis." #, fuzzy #~ msgid "" #~ "error: %v\n" #~ "%s\n" #~ msgstr "" #~ "Fehler: %v\n" #~ "%s" #~ msgid "" #~ "Changing the name of a running container during copy isn't supported." #~ msgstr "" #~ "Den Namen eines laufenden Containers beim kopieren zu ändern wird nicht " #~ "unterstützt." #~ msgid "non-http remotes are not supported for migration right now" #~ msgstr "" #~ "die Migration an entfernte Instanzen wird zur Zeit nur über http " #~ "unterstützt." #~ msgid "Cannot connect to unix socket at %s Is the server running?\n" #~ msgstr "" #~ "Keine Verbindung zum unix Socket unter %s möglich. Läuft der Server?\n" #~ msgid "Show for remotes is not yet supported\n" #~ msgstr "" #~ "Anzeigen von Informationen über entfernte Instanzen wird noch nicht " #~ "unterstützt\n" ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/�������������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014260� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/util/��������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015235� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/util/sys.go��������������������������������������������������������������������������0000644�0610621�0607500�00000004064�13172163242�016406� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package util import ( "strings" log "gopkg.in/inconshreveable/log15.v2" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/osarch" ) // GetArchitectures returns the list of supported architectures. func GetArchitectures() ([]int, error) { architectures := []int{} architectureName, err := osarch.ArchitectureGetLocal() if err != nil { return nil, err } architecture, err := osarch.ArchitectureId(architectureName) if err != nil { return nil, err } architectures = append(architectures, architecture) personalities, err := osarch.ArchitecturePersonalities(architecture) if err != nil { return nil, err } for _, personality := range personalities { architectures = append(architectures, personality) } return architectures, nil } // GetIdmapSet reads the uid/gid allocation. func GetIdmapSet() *idmap.IdmapSet { idmapSet, err := idmap.DefaultIdmapSet() if err != nil { logger.Warn("Error reading default uid/gid map", log.Ctx{"err": err.Error()}) logger.Warnf("Only privileged containers will be able to run") idmapSet = nil } else { kernelIdmapSet, err := idmap.CurrentIdmapSet() if err == nil { logger.Infof("Kernel uid/gid map:") for _, lxcmap := range kernelIdmapSet.ToLxcString() { logger.Infof(strings.TrimRight(" - "+lxcmap, "\n")) } } if len(idmapSet.Idmap) == 0 { logger.Warnf("No available uid/gid map could be found") logger.Warnf("Only privileged containers will be able to run") idmapSet = nil } else { logger.Infof("Configured LXD uid/gid map:") for _, lxcmap := range idmapSet.Idmap { suffix := "" if lxcmap.Usable() != nil { suffix = " (unusable)" } for _, lxcEntry := range lxcmap.ToLxcString() { logger.Infof(" - %s%s", strings.TrimRight(lxcEntry, "\n"), suffix) } } err = idmapSet.Usable() if err != nil { logger.Warnf("One or more uid/gid map entry isn't usable (typically due to nesting)") logger.Warnf("Only privileged containers will be able to run") idmapSet = nil } } } return idmapSet } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/util/kernel.go�����������������������������������������������������������������������0000644�0610621�0607500�00000000511�13172163242�017041� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package util import ( "fmt" "github.com/lxc/lxd/shared" ) // LoadModule loads the kernel module with the given name, by invoking // modprobe. func LoadModule(module string) error { if shared.PathExists(fmt.Sprintf("/sys/module/%s", module)) { return nil } _, err := shared.RunCommand("modprobe", module) return err } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/util/http.go�������������������������������������������������������������������������0000644�0610621�0607500�00000011451�13172163242�016545� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package util import ( "bytes" "crypto/x509" "encoding/json" "encoding/pem" "fmt" "io" "net" "net/http" "net/url" "os" "strconv" "strings" "syscall" "time" log "gopkg.in/inconshreveable/log15.v2" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" ) func WriteJSON(w http.ResponseWriter, body interface{}, debug bool) error { var output io.Writer var captured *bytes.Buffer output = w if debug { captured = &bytes.Buffer{} output = io.MultiWriter(w, captured) } err := json.NewEncoder(output).Encode(body) if captured != nil { shared.DebugJson(captured) } return err } // HTTPClient returns an http.Client using the given certificate and proxy. func HTTPClient(certificate string, proxy proxyFunc) (*http.Client, error) { var err error var cert *x509.Certificate if certificate != "" { certBlock, _ := pem.Decode([]byte(certificate)) if certBlock == nil { return nil, fmt.Errorf("Invalid certificate") } cert, err = x509.ParseCertificate(certBlock.Bytes) if err != nil { return nil, err } } tlsConfig, err := shared.GetTLSConfig("", "", "", cert) if err != nil { return nil, err } tr := &http.Transport{ TLSClientConfig: tlsConfig, Dial: shared.RFC3493Dialer, Proxy: proxy, DisableKeepAlives: true, } myhttp := http.Client{ Transport: tr, } // Setup redirect policy myhttp.CheckRedirect = func(req *http.Request, via []*http.Request) error { // Replicate the headers req.Header = via[len(via)-1].Header return nil } return &myhttp, nil } // A function capable of proxing an HTTP request. type proxyFunc func(req *http.Request) (*url.URL, error) // IsTrustedClient checks if the given HTTP request comes from a trusted client // (i.e. either it's received via Unix socket, or via TLS with a trusted // certificate). func IsTrustedClient(r *http.Request, trustedCerts []x509.Certificate) bool { if r.RemoteAddr == "@" { // Unix socket return true } if r.TLS == nil { return false } for i := range r.TLS.PeerCertificates { if checkTrustState(*r.TLS.PeerCertificates[i], trustedCerts) { return true } } return false } // Check whether the given client certificate is trusted (i.e. it has a valid // time span and it belongs to the given list of trusted certificates). func checkTrustState(cert x509.Certificate, trustedCerts []x509.Certificate) bool { // Extra validity check (should have been caught by TLS stack) if time.Now().Before(cert.NotBefore) || time.Now().After(cert.NotAfter) { return false } for k, v := range trustedCerts { if bytes.Compare(cert.Raw, v.Raw) == 0 { logger.Debug("Found cert", log.Ctx{"k": k}) return true } } return false } // IsRecursionRequest checks whether the given HTTP request is marked with the // "recursion" flag in its form values. func IsRecursionRequest(r *http.Request) bool { recursionStr := r.FormValue("recursion") recursion, err := strconv.Atoi(recursionStr) if err != nil { return false } return recursion == 1 } func ListenAddresses(value string) ([]string, error) { addresses := make([]string, 0) if value == "" { return addresses, nil } localHost, localPort, err := net.SplitHostPort(value) if err != nil { localHost = value localPort = shared.DefaultPort } if localHost == "0.0.0.0" || localHost == "::" || localHost == "[::]" { ifaces, err := net.Interfaces() if err != nil { return addresses, err } for _, i := range ifaces { addrs, err := i.Addrs() if err != nil { continue } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if !ip.IsGlobalUnicast() { continue } if ip.To4() == nil { if localHost == "0.0.0.0" { continue } addresses = append(addresses, fmt.Sprintf("[%s]:%s", ip, localPort)) } else { addresses = append(addresses, fmt.Sprintf("%s:%s", ip, localPort)) } } } } else { if strings.Contains(localHost, ":") { addresses = append(addresses, fmt.Sprintf("[%s]:%s", localHost, localPort)) } else { addresses = append(addresses, fmt.Sprintf("%s:%s", localHost, localPort)) } } return addresses, nil } func GetListeners() []net.Listener { defer func() { os.Unsetenv("LISTEN_PID") os.Unsetenv("LISTEN_FDS") }() pid, err := strconv.Atoi(os.Getenv("LISTEN_PID")) if err != nil { return nil } if pid != os.Getpid() { return nil } fds, err := strconv.Atoi(os.Getenv("LISTEN_FDS")) if err != nil { return nil } listeners := []net.Listener{} for i := 3; i < 3+fds; i++ { syscall.CloseOnExec(i) file := os.NewFile(uintptr(i), fmt.Sprintf("inherited-fd%d", i)) listener, err := net.FileListener(file) if err != nil { continue } listeners = append(listeners, listener) } return listeners } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/util/fs_64bit.go���������������������������������������������������������������������0000644�0610621�0607500�00000000153�13172163242�017203� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build amd64 ppc64 ppc64le arm64 s390x package util const ( FilesystemSuperMagicBtrfs = 0x9123683E ) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/util/fs_32bit.go���������������������������������������������������������������������0000644�0610621�0607500�00000000317�13172163242�017200� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build 386 arm ppc s390 package util const ( /* This is really 0x9123683E, go wants us to give it in signed form * since we use it as a signed constant. */ FilesystemSuperMagicBtrfs = -1859950530 ) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/util/fs.go���������������������������������������������������������������������������0000644�0610621�0607500�00000001723�13172163242�016177� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package util import ( "syscall" "github.com/lxc/lxd/shared/logger" ) // Filesystem magic numbers const ( FilesystemSuperMagicTmpfs = 0x01021994 FilesystemSuperMagicExt4 = 0xEF53 FilesystemSuperMagicXfs = 0x58465342 FilesystemSuperMagicNfs = 0x6969 FilesystemSuperMagicZfs = 0x2fc12fc1 ) // FilesystemDetect returns the filesystem on which the passed-in path sits. func FilesystemDetect(path string) (string, error) { fs := syscall.Statfs_t{} err := syscall.Statfs(path, &fs) if err != nil { return "", err } switch fs.Type { case FilesystemSuperMagicBtrfs: return "btrfs", nil case FilesystemSuperMagicZfs: return "zfs", nil case FilesystemSuperMagicTmpfs: return "tmpfs", nil case FilesystemSuperMagicExt4: return "ext4", nil case FilesystemSuperMagicXfs: return "xfs", nil case FilesystemSuperMagicNfs: return "nfs", nil default: logger.Debugf("Unknown backing filesystem type: 0x%x", fs.Type) return string(fs.Type), nil } } ���������������������������������������������lxd-2.0.11/lxd/util/encryption.go�������������������������������������������������������������������0000644�0610621�0607500�00000001037�13172163242�017757� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package util import ( "bytes" "encoding/hex" "fmt" "golang.org/x/crypto/scrypt" ) func PasswordCheck(secret, password string) error { // No password set if secret == "" { return fmt.Errorf("No password is set") } // Compare the password buff, err := hex.DecodeString(secret) if err != nil { return err } salt := buff[0:32] hash, err := scrypt.Key([]byte(password), salt, 1<<14, 8, 1, 64) if err != nil { return err } if !bytes.Equal(hash, buff[32:]) { return fmt.Errorf("Bad password provided") } return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/types/�������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015424� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/types/devices_test.go����������������������������������������������������������������0000644�0610621�0607500�00000000665�13172163242�020443� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package types import ( "reflect" "testing" ) func TestSortableDevices(t *testing.T) { devices := Devices{ "1": Device{"type": "nic"}, "3": Device{"type": "disk", "path": "/foo/bar"}, "4": Device{"type": "disk", "path": "/foo"}, "2": Device{"type": "nic"}, } expected := []string{"4", "3", "1", "2"} result := devices.DeviceNames() if !reflect.DeepEqual(result, expected) { t.Error("devices sorted incorrectly") } } ���������������������������������������������������������������������������lxd-2.0.11/lxd/types/devices.go���������������������������������������������������������������������0000644�0610621�0607500�00000007407�13172163242�017405� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package types import ( "sort" "github.com/lxc/lxd/shared" ) type Device map[string]string type Devices map[string]map[string]string func (list Devices) ContainsName(k string) bool { if list[k] != nil { return true } return false } func (d Device) get(key string) string { return d[key] } func (list Devices) Contains(k string, d Device) bool { // If it didn't exist, it's different if list[k] == nil { return false } old := list[k] return deviceEquals(old, d) } func deviceEquals(old Device, d Device) bool { // Check for any difference and addition/removal of properties for k := range d { if d[k] != old[k] { return false } } for k := range old { if d[k] != old[k] { return false } } return true } func deviceEqualsDiffKeys(old Device, d Device) []string { keys := []string{} // Check for any difference and addition/removal of properties for k := range d { if d[k] != old[k] { keys = append(keys, k) } } for k := range old { if d[k] != old[k] { keys = append(keys, k) } } return keys } func (old Devices) Update(newlist Devices) (map[string]Device, map[string]Device, map[string]Device, []string) { rmlist := map[string]Device{} addlist := map[string]Device{} updatelist := map[string]Device{} for key, d := range old { if !newlist.Contains(key, d) { rmlist[key] = d } } for key, d := range newlist { if !old.Contains(key, d) { addlist[key] = d } } updateDiff := []string{} for key, d := range addlist { srcOldDevice := rmlist[key] var oldDevice Device err := shared.DeepCopy(&srcOldDevice, &oldDevice) if err != nil { continue } srcNewDevice := newlist[key] var newDevice Device err = shared.DeepCopy(&srcNewDevice, &newDevice) if err != nil { continue } updateDiff = deviceEqualsDiffKeys(oldDevice, newDevice) for _, k := range []string{"limits.max", "limits.read", "limits.write", "limits.egress", "limits.ingress"} { delete(oldDevice, k) delete(newDevice, k) } if deviceEquals(oldDevice, newDevice) { delete(rmlist, key) delete(addlist, key) updatelist[key] = d } } return rmlist, addlist, updatelist, updateDiff } func (newBaseDevices Devices) ExtendFromProfile(currentFullDevices Devices, newDevicesFromProfile Devices) error { // For any entry which exists in a profile and doesn't in the container config, add it for name, newDev := range newDevicesFromProfile { if curDev, ok := currentFullDevices[name]; ok { newBaseDevices[name] = curDev } else { newBaseDevices[name] = newDev } } return nil } type namedDevice struct { name string device Device } type sortableDevices []namedDevice func (devices Devices) toSortable() sortableDevices { named := []namedDevice{} for k, d := range devices { named = append(named, namedDevice{k, d}) } return named } func (devices sortableDevices) Len() int { return len(devices) } func (devices sortableDevices) Less(i, j int) bool { a := devices[i] b := devices[j] // First sort by types if a.device["type"] != b.device["type"] { return a.device["type"] < b.device["type"] } // Special case disk paths if a.device["type"] == "disk" && b.device["type"] == "disk" { if a.device["path"] != b.device["path"] { return a.device["path"] < b.device["path"] } } // Fallback to sorting by names return a.name < b.name } func (devices sortableDevices) Swap(i, j int) { tmp := devices[i] devices[i] = devices[j] devices[j] = tmp } func (devices sortableDevices) Names() []string { result := []string{} for _, d := range devices { result = append(result, d.name) } return result } /* DeviceNames returns the device names for this Devices in sorted order */ func (devices Devices) DeviceNames() []string { sortable := devices.toSortable() sort.Sort(sortable) return sortable.Names() } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/sys/���������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015076� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/sys/os.go����������������������������������������������������������������������������0000644�0610621�0607500�00000002211�13172163242�016042� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package sys import ( log "gopkg.in/inconshreveable/log15.v2" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" ) // OS is a high-level facade for accessing all operating-system // level functionality that LXD uses. type OS struct { // Caches of system characteristics detected at Init() time. Architectures []int // Cache of detected system architectures LxcPath string // Path to the $LXD_DIR/containers directory BackingFS string // Backing filesystem of $LXD_DIR/containers IdmapSet *idmap.IdmapSet MockMode bool // If true some APIs will be mocked (for testing) } // NewOS returns a fresh uninitialized OS instance. func NewOS() *OS { return &OS{} } // Init our internal data structures. func (s *OS) Init() error { var err error s.Architectures, err = util.GetArchitectures() if err != nil { return err } s.LxcPath = shared.VarPath("containers") s.BackingFS, err = util.FilesystemDetect(s.LxcPath) if err != nil { logger.Error("Error detecting backing fs", log.Ctx{"err": err}) } s.IdmapSet = util.GetIdmapSet() return nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/storage_zfs.go�����������������������������������������������������������������������0000644�0610621�0607500�00000105343�13172163242�017143� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "os" "os/exec" "strconv" "strings" "syscall" "time" "github.com/gorilla/websocket" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" "github.com/pborman/uuid" log "gopkg.in/inconshreveable/log15.v2" ) type storageZfs struct { zfsPool string storageShared } func (s *storageZfs) Init(config map[string]interface{}) (storage, error) { s.sType = storageTypeZfs s.sTypeName = storageTypeToString(s.sType) err := s.initShared() if err != nil { return s, err } if config["zfsPool"] == nil { zfsPool := daemonConfig["storage.zfs_pool_name"].Get() if zfsPool == "" { return s, fmt.Errorf("ZFS isn't enabled") } s.zfsPool = zfsPool } else { s.zfsPool = config["zfsPool"].(string) } out, err := exec.LookPath("zfs") if err != nil || len(out) == 0 { return s, fmt.Errorf("The 'zfs' tool isn't available") } err = s.zfsCheckPool(s.zfsPool) if err != nil { if shared.PathExists(shared.VarPath("zfs.img")) { _ = util.LoadModule("zfs") output, err := shared.RunCommand("zpool", "import", "-d", shared.VarPath(), s.zfsPool) if err != nil { return s, fmt.Errorf("Unable to import the ZFS pool: %s", output) } } else { return s, err } } output, err := shared.RunCommand("zfs", "get", "version", "-H", "-o", "value", s.zfsPool) if err != nil { return s, fmt.Errorf("The 'zfs' tool isn't working properly") } count, err := fmt.Sscanf(string(output), "%s\n", &s.sTypeVersion) if err != nil || count != 1 { return s, fmt.Errorf("The 'zfs' tool isn't working properly") } output, err = shared.RunCommand("zfs", "get", "mountpoint", "-H", "-o", "source", s.zfsPool) if err != nil { return s, fmt.Errorf("Unable to query ZFS mountpoint") } if strings.TrimSpace(string(output)) != "local" { _, err = shared.RunCommand("zfs", "set", "mountpoint=none", s.zfsPool) if err != nil { return s, err } } return s, nil } // Things we don't need to care about func (s *storageZfs) ContainerStart(name string, path string) error { fs := fmt.Sprintf("containers/%s", name) // Just in case the container filesystem got unmounted if !shared.IsMountPoint(shared.VarPath(fs)) { s.zfsMount(fs) } return nil } func (s *storageZfs) ContainerStop(name string, path string) error { return nil } // Things we do have to care about func (s *storageZfs) ContainerCreate(container container) error { cPath := container.Path() fs := fmt.Sprintf("containers/%s", container.Name()) err := s.zfsCreate(fs) if err != nil { return err } err = os.Symlink(cPath+".zfs", cPath) if err != nil { return err } var mode os.FileMode if container.IsPrivileged() { mode = 0700 } else { mode = 0755 } err = os.Chmod(cPath, mode) if err != nil { return err } return container.TemplateApply("create") } func (s *storageZfs) ContainerCreateFromImage(container container, fingerprint string) error { cPath := container.Path() imagePath := shared.VarPath("images", fingerprint) subvol := fmt.Sprintf("%s.zfs", imagePath) fs := fmt.Sprintf("containers/%s", container.Name()) fsImage := fmt.Sprintf("images/%s", fingerprint) if !shared.PathExists(subvol) { err := s.ImageCreate(fingerprint) if err != nil { return err } } err := s.zfsClone(fsImage, "readonly", fs, true) if err != nil { return err } err = os.Symlink(cPath+".zfs", cPath) if err != nil { return err } var mode os.FileMode if container.IsPrivileged() { mode = 0700 } else { mode = 0755 } err = os.Chmod(cPath, mode) if err != nil { return err } if !container.IsPrivileged() { err = s.shiftRootfs(container) if err != nil { return err } } return container.TemplateApply("create") } func (s *storageZfs) ContainerCanRestore(container container, sourceContainer container) error { snaps, err := container.Snapshots() if err != nil { return err } if snaps[len(snaps)-1].Name() != sourceContainer.Name() { return fmt.Errorf("ZFS can only restore from the latest snapshot. Delete newer snapshots or copy the snapshot into a new container instead.") } return nil } func (s *storageZfs) ContainerDelete(container container) error { fs := fmt.Sprintf("containers/%s", container.Name()) if s.zfsExists(fs) { removable := true snaps, err := s.zfsListSnapshots(fs) if err != nil { return err } for _, snap := range snaps { var err error removable, err = s.zfsSnapshotRemovable(fs, snap) if err != nil { return err } if !removable { break } } if removable { origin, err := s.zfsGet(fs, "origin") if err != nil { return err } origin = strings.TrimPrefix(origin, fmt.Sprintf("%s/", s.zfsPool)) err = s.zfsDestroy(fs) if err != nil { return err } err = s.zfsCleanup(origin) if err != nil { return err } } else { err := s.zfsSet(fs, "mountpoint", "none") if err != nil { return err } err = s.zfsRename(fs, fmt.Sprintf("deleted/containers/%s", uuid.NewRandom().String())) if err != nil { return err } } } if shared.PathExists(shared.VarPath(fs)) { err := os.Remove(shared.VarPath(fs)) if err != nil { return err } } if shared.PathExists(shared.VarPath(fs) + ".zfs") { err := os.Remove(shared.VarPath(fs) + ".zfs") if err != nil { return err } } s.zfsDestroy(fmt.Sprintf("snapshots/%s", container.Name())) return nil } func (s *storageZfs) ContainerCopy(container container, sourceContainer container) error { var sourceFs string var sourceSnap string sourceFields := strings.SplitN(sourceContainer.Name(), shared.SnapshotDelimiter, 2) sourceName := sourceFields[0] destName := container.Name() destFs := fmt.Sprintf("containers/%s", destName) if len(sourceFields) == 2 { sourceSnap = sourceFields[1] } if sourceSnap == "" { if s.zfsExists(fmt.Sprintf("containers/%s", sourceName)) { sourceSnap = fmt.Sprintf("copy-%s", uuid.NewRandom().String()) sourceFs = fmt.Sprintf("containers/%s", sourceName) err := s.zfsSnapshotCreate(fmt.Sprintf("containers/%s", sourceName), sourceSnap) if err != nil { return err } } } else { if s.zfsExists(fmt.Sprintf("containers/%s@snapshot-%s", sourceName, sourceSnap)) { sourceFs = fmt.Sprintf("containers/%s", sourceName) sourceSnap = fmt.Sprintf("snapshot-%s", sourceSnap) } } if sourceFs != "" { err := s.zfsClone(sourceFs, sourceSnap, destFs, true) if err != nil { return err } cPath := container.Path() err = os.Symlink(cPath+".zfs", cPath) if err != nil { return err } var mode os.FileMode if container.IsPrivileged() { mode = 0700 } else { mode = 0755 } err = os.Chmod(cPath, mode) if err != nil { return err } } else { err := s.ContainerCreate(container) if err != nil { return err } output, err := storageRsyncCopy(sourceContainer.Path(), container.Path()) if err != nil { return fmt.Errorf("rsync failed: %s", string(output)) } } return container.TemplateApply("copy") } func (s *storageZfs) ContainerRename(container container, newName string) error { oldName := container.Name() // Unmount the filesystem err := s.zfsUnmount(fmt.Sprintf("containers/%s", oldName)) if err != nil { return err } // Rename the filesystem err = s.zfsRename(fmt.Sprintf("containers/%s", oldName), fmt.Sprintf("containers/%s", newName)) if err != nil { return err } // Update to the new mountpoint err = s.zfsSet(fmt.Sprintf("containers/%s", newName), "mountpoint", shared.VarPath(fmt.Sprintf("containers/%s.zfs", newName))) if err != nil { return err } // In case ZFS didn't mount the filesystem, do it ourselves err = s.zfsMount(fmt.Sprintf("containers/%s", newName)) if err != nil { return err } // In case the change of mountpoint didn't remove the old path, do it ourselves if shared.PathExists(shared.VarPath(fmt.Sprintf("containers/%s.zfs", oldName))) { err = os.Remove(shared.VarPath(fmt.Sprintf("containers/%s.zfs", oldName))) if err != nil { return err } } // Remove the old symlink err = os.Remove(shared.VarPath(fmt.Sprintf("containers/%s", oldName))) if err != nil { return err } // Create a new symlink err = os.Symlink(shared.VarPath(fmt.Sprintf("containers/%s.zfs", newName)), shared.VarPath(fmt.Sprintf("containers/%s", newName))) if err != nil { return err } // Rename the snapshot path if shared.PathExists(shared.VarPath(fmt.Sprintf("snapshots/%s", oldName))) { err = os.Rename(shared.VarPath(fmt.Sprintf("snapshots/%s", oldName)), shared.VarPath(fmt.Sprintf("snapshots/%s", newName))) if err != nil { return err } } return nil } func (s *storageZfs) ContainerRestore(container container, sourceContainer container) error { fields := strings.SplitN(sourceContainer.Name(), shared.SnapshotDelimiter, 2) cName := fields[0] snapName := fmt.Sprintf("snapshot-%s", fields[1]) err := s.zfsSnapshotRestore(fmt.Sprintf("containers/%s", cName), snapName) if err != nil { return err } return nil } func (s *storageZfs) ContainerSetQuota(container container, size int64) error { var err error fs := fmt.Sprintf("containers/%s", container.Name()) if size > 0 { err = s.zfsSet(fs, "quota", fmt.Sprintf("%d", size)) } else { err = s.zfsSet(fs, "quota", "none") } if err != nil { return err } return nil } func (s *storageZfs) ContainerGetUsage(container container) (int64, error) { var err error fs := fmt.Sprintf("containers/%s", container.Name()) value, err := s.zfsGet(fs, "used") if err != nil { return -1, err } valueInt, err := strconv.ParseInt(value, 10, 64) if err != nil { return -1, err } return valueInt, nil } func (s *storageZfs) ContainerSnapshotCreate(snapshotContainer container, sourceContainer container) error { fields := strings.SplitN(snapshotContainer.Name(), shared.SnapshotDelimiter, 2) cName := fields[0] snapName := fmt.Sprintf("snapshot-%s", fields[1]) err := s.zfsSnapshotCreate(fmt.Sprintf("containers/%s", cName), snapName) if err != nil { return err } if !shared.PathExists(shared.VarPath(fmt.Sprintf("snapshots/%s", cName))) { err = os.MkdirAll(shared.VarPath(fmt.Sprintf("snapshots/%s", cName)), 0700) if err != nil { return err } } err = os.Symlink("on-zfs", shared.VarPath(fmt.Sprintf("snapshots/%s/%s.zfs", cName, fields[1]))) if err != nil { return err } return nil } func (s *storageZfs) ContainerSnapshotDelete(snapshotContainer container) error { fields := strings.SplitN(snapshotContainer.Name(), shared.SnapshotDelimiter, 2) cName := fields[0] snapName := fmt.Sprintf("snapshot-%s", fields[1]) if s.zfsExists(fmt.Sprintf("containers/%s@%s", cName, snapName)) { removable, err := s.zfsSnapshotRemovable(fmt.Sprintf("containers/%s", cName), snapName) if removable { err = s.zfsSnapshotDestroy(fmt.Sprintf("containers/%s", cName), snapName) if err != nil { return err } } else { err = s.zfsSnapshotRename(fmt.Sprintf("containers/%s", cName), snapName, fmt.Sprintf("copy-%s", uuid.NewRandom().String())) if err != nil { return err } } } snapPath := shared.VarPath(fmt.Sprintf("snapshots/%s/%s.zfs", cName, fields[1])) if shared.PathExists(snapPath) { err := os.Remove(snapPath) if err != nil { return err } } parent := shared.VarPath(fmt.Sprintf("snapshots/%s", cName)) if ok, _ := shared.PathIsEmpty(parent); ok { err := os.Remove(parent) if err != nil { return err } } return nil } func (s *storageZfs) ContainerSnapshotRename(snapshotContainer container, newName string) error { oldFields := strings.SplitN(snapshotContainer.Name(), shared.SnapshotDelimiter, 2) oldcName := oldFields[0] oldName := fmt.Sprintf("snapshot-%s", oldFields[1]) newFields := strings.SplitN(newName, shared.SnapshotDelimiter, 2) newcName := newFields[0] newName = fmt.Sprintf("snapshot-%s", newFields[1]) if oldName != newName { err := s.zfsSnapshotRename(fmt.Sprintf("containers/%s", oldcName), oldName, newName) if err != nil { return err } } err := os.Remove(shared.VarPath(fmt.Sprintf("snapshots/%s/%s.zfs", oldcName, oldFields[1]))) if err != nil { return err } if !shared.PathExists(shared.VarPath(fmt.Sprintf("snapshots/%s", newcName))) { err = os.MkdirAll(shared.VarPath(fmt.Sprintf("snapshots/%s", newcName)), 0700) if err != nil { return err } } err = os.Symlink("on-zfs", shared.VarPath(fmt.Sprintf("snapshots/%s/%s.zfs", newcName, newFields[1]))) if err != nil { return err } parent := shared.VarPath(fmt.Sprintf("snapshots/%s", oldcName)) if ok, _ := shared.PathIsEmpty(parent); ok { err = os.Remove(parent) if err != nil { return err } } return nil } func (s *storageZfs) ContainerSnapshotStart(container container) error { fields := strings.SplitN(container.Name(), shared.SnapshotDelimiter, 2) if len(fields) < 2 { return fmt.Errorf("Invalid snapshot name: %s", container.Name()) } cName := fields[0] sName := fields[1] sourceFs := fmt.Sprintf("containers/%s", cName) sourceSnap := fmt.Sprintf("snapshot-%s", sName) destFs := fmt.Sprintf("snapshots/%s/%s", cName, sName) err := s.zfsClone(sourceFs, sourceSnap, destFs, false) if err != nil { return err } return nil } func (s *storageZfs) ContainerSnapshotStop(container container) error { fields := strings.SplitN(container.Name(), shared.SnapshotDelimiter, 2) if len(fields) < 2 { return fmt.Errorf("Invalid snapshot name: %s", container.Name()) } cName := fields[0] sName := fields[1] destFs := fmt.Sprintf("snapshots/%s/%s", cName, sName) err := s.zfsDestroy(destFs) if err != nil { return err } /* zfs creates this directory on clone (start), so we need to clean it * up on stop */ return os.RemoveAll(container.Path()) } func (s *storageZfs) ContainerSnapshotCreateEmpty(snapshotContainer container) error { /* don't touch the fs yet, as migration will do that for us */ return nil } func (s *storageZfs) ImageCreate(fingerprint string) error { imagePath := shared.VarPath("images", fingerprint) subvol := fmt.Sprintf("%s.zfs", imagePath) fs := fmt.Sprintf("images/%s", fingerprint) if s.zfsExists(fmt.Sprintf("deleted/%s", fs)) { err := s.zfsRename(fmt.Sprintf("deleted/%s", fs), fs) if err != nil { return err } err = s.zfsSet(fs, "mountpoint", subvol) if err != nil { return err } return nil } err := s.zfsCreate(fs) if err != nil { return err } cleanup := func(err error) error { if zerr := s.zfsDestroy(fs); zerr != nil { err = fmt.Errorf("%s During cleanup: %s", err, zerr) } if shared.PathExists(subvol) { if oserr := os.Remove(subvol); oserr != nil { err = fmt.Errorf("%s During cleanup: Failed to remove sub-volume %s, %s", err, subvol, oserr) } } return err } err = unpackImage(imagePath, subvol, s.storage.GetStorageType()) if err != nil { return cleanup(err) } err = s.zfsSet(fs, "readonly", "on") if err != nil { return cleanup(err) } err = s.zfsSnapshotCreate(fs, "readonly") if err != nil { return cleanup(err) } return nil } func (s *storageZfs) ImageDelete(fingerprint string) error { fs := fmt.Sprintf("images/%s", fingerprint) if s.zfsExists(fs) { removable, err := s.zfsSnapshotRemovable(fs, "readonly") if err != nil { return err } if removable { err := s.zfsDestroy(fs) if err != nil { return err } } else { err := s.zfsSet(fs, "mountpoint", "none") if err != nil { return err } err = s.zfsRename(fs, fmt.Sprintf("deleted/%s", fs)) if err != nil { return err } } } if shared.PathExists(shared.VarPath(fs + ".zfs")) { err := os.Remove(shared.VarPath(fs + ".zfs")) if err != nil { return err } } return nil } // Helper functions func (s *storageZfs) zfsCheckPool(pool string) error { output, err := shared.RunCommand( "zfs", "get", "type", "-H", "-o", "value", pool) if err != nil { return fmt.Errorf(strings.Split(string(output), "\n")[0]) } poolType := strings.Split(string(output), "\n")[0] if poolType != "filesystem" { return fmt.Errorf("Unsupported pool type: %s", poolType) } return nil } func (s *storageZfs) zfsClone(source string, name string, dest string, dotZfs bool) error { var mountpoint string mountpoint = shared.VarPath(dest) if dotZfs { mountpoint += ".zfs" } output, err := shared.RunCommand( "zfs", "clone", "-p", "-o", fmt.Sprintf("mountpoint=%s", mountpoint), fmt.Sprintf("%s/%s@%s", s.zfsPool, source, name), fmt.Sprintf("%s/%s", s.zfsPool, dest)) if err != nil { s.log.Error("zfs clone failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to clone the filesystem: %s", output) } subvols, err := s.zfsListSubvolumes(source) if err != nil { return err } for _, sub := range subvols { snaps, err := s.zfsListSnapshots(sub) if err != nil { return err } if !shared.StringInSlice(name, snaps) { continue } destSubvol := dest + strings.TrimPrefix(sub, source) mountpoint = shared.VarPath(destSubvol) if dotZfs { mountpoint += ".zfs" } output, err := shared.RunCommand( "zfs", "clone", "-p", "-o", fmt.Sprintf("mountpoint=%s", mountpoint), fmt.Sprintf("%s/%s@%s", s.zfsPool, sub, name), fmt.Sprintf("%s/%s", s.zfsPool, destSubvol)) if err != nil { s.log.Error("zfs clone failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to clone the sub-volume: %s", output) } } return nil } func (s *storageZfs) zfsCreate(path string) error { output, err := shared.RunCommand( "zfs", "create", "-p", "-o", fmt.Sprintf("mountpoint=%s.zfs", shared.VarPath(path)), fmt.Sprintf("%s/%s", s.zfsPool, path)) if err != nil { s.log.Error("zfs create failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to create ZFS filesystem: %s", output) } return nil } func (s *storageZfs) zfsDestroy(path string) error { mountpoint, err := s.zfsGet(path, "mountpoint") if err != nil { return err } if mountpoint != "none" && shared.IsMountPoint(mountpoint) { err := syscall.Unmount(mountpoint, syscall.MNT_DETACH) if err != nil { s.log.Error("umount failed", log.Ctx{"err": err}) return err } } // Due to open fds or kernel refs, this may fail for a bit, give it 10s output, err := shared.TryRunCommand( "zfs", "destroy", "-r", fmt.Sprintf("%s/%s", s.zfsPool, path)) if err != nil { s.log.Error("zfs destroy failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to destroy ZFS filesystem: %s", output) } return nil } func (s *storageZfs) zfsCleanup(path string) error { if strings.HasPrefix(path, "deleted/") { // Cleanup of filesystems kept for refcount reason removablePath, err := s.zfsSnapshotRemovable(path, "") if err != nil { return err } // Confirm that there are no more clones if removablePath { if strings.Contains(path, "@") { // Cleanup snapshots err = s.zfsDestroy(path) if err != nil { return err } // Check if the parent can now be deleted subPath := strings.SplitN(path, "@", 2)[0] snaps, err := s.zfsListSnapshots(subPath) if err != nil { return err } if len(snaps) == 0 { err := s.zfsCleanup(subPath) if err != nil { return err } } } else { // Cleanup filesystems origin, err := s.zfsGet(path, "origin") if err != nil { return err } origin = strings.TrimPrefix(origin, fmt.Sprintf("%s/", s.zfsPool)) err = s.zfsDestroy(path) if err != nil { return err } // Attempt to remove its parent if origin != "-" { err := s.zfsCleanup(origin) if err != nil { return err } } } return nil } } else if strings.HasPrefix(path, "containers") && strings.Contains(path, "@copy-") { // Just remove the copy- snapshot for copies of active containers err := s.zfsDestroy(path) if err != nil { return err } } return nil } func (s *storageZfs) zfsExists(path string) bool { output, _ := s.zfsGet(path, "name") if output == fmt.Sprintf("%s/%s", s.zfsPool, path) { return true } return false } func (s *storageZfs) zfsGet(path string, key string) (string, error) { output, err := shared.RunCommand( "zfs", "get", "-H", "-p", "-o", "value", key, fmt.Sprintf("%s/%s", s.zfsPool, path)) if err != nil { return string(output), fmt.Errorf("Failed to get ZFS config: %s", output) } return strings.TrimRight(string(output), "\n"), nil } func (s *storageZfs) zfsRename(source string, dest string) error { var err error var output string for i := 0; i < 20; i++ { output, err = shared.RunCommand( "zfs", "rename", "-p", fmt.Sprintf("%s/%s", s.zfsPool, source), fmt.Sprintf("%s/%s", s.zfsPool, dest)) // Success if err == nil { return nil } // zfs rename can fail because of descendants, yet still manage the rename if !s.zfsExists(source) && s.zfsExists(dest) { return nil } time.Sleep(500 * time.Millisecond) } // Timeout s.log.Error("zfs rename failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to rename ZFS filesystem: %s", output) } func (s *storageZfs) zfsSet(path string, key string, value string) error { output, err := shared.RunCommand( "zfs", "set", fmt.Sprintf("%s=%s", key, value), fmt.Sprintf("%s/%s", s.zfsPool, path)) if err != nil { s.log.Error("zfs set failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to set ZFS config: %s", output) } return nil } func (s *storageZfs) zfsSnapshotCreate(path string, name string) error { output, err := shared.RunCommand( "zfs", "snapshot", "-r", fmt.Sprintf("%s/%s@%s", s.zfsPool, path, name)) if err != nil { s.log.Error("zfs snapshot failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to create ZFS snapshot: %s", output) } return nil } func (s *storageZfs) zfsSnapshotDestroy(path string, name string) error { output, err := shared.RunCommand( "zfs", "destroy", "-r", fmt.Sprintf("%s/%s@%s", s.zfsPool, path, name)) if err != nil { s.log.Error("zfs destroy failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to destroy ZFS snapshot: %s", output) } return nil } func (s *storageZfs) zfsSnapshotRestore(path string, name string) error { output, err := shared.TryRunCommand( "zfs", "rollback", fmt.Sprintf("%s/%s@%s", s.zfsPool, path, name)) if err != nil { s.log.Error("zfs rollback failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to restore ZFS snapshot: %s", output) } subvols, err := s.zfsListSubvolumes(path) if err != nil { return err } for _, sub := range subvols { snaps, err := s.zfsListSnapshots(sub) if err != nil { return err } if !shared.StringInSlice(name, snaps) { continue } output, err := shared.TryRunCommand( "zfs", "rollback", fmt.Sprintf("%s/%s@%s", s.zfsPool, sub, name)) if err != nil { s.log.Error("zfs rollback failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to restore ZFS sub-volume snapshot: %s", output) } } return nil } func (s *storageZfs) zfsSnapshotRename(path string, oldName string, newName string) error { output, err := shared.RunCommand( "zfs", "rename", "-r", fmt.Sprintf("%s/%s@%s", s.zfsPool, path, oldName), fmt.Sprintf("%s/%s@%s", s.zfsPool, path, newName)) if err != nil { s.log.Error("zfs snapshot rename failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to rename ZFS snapshot: %s", output) } return nil } func (s *storageZfs) zfsMount(path string) error { output, err := shared.TryRunCommand( "zfs", "mount", fmt.Sprintf("%s/%s", s.zfsPool, path)) if err != nil { s.log.Error("zfs mount failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to mount ZFS filesystem: %s", output) } return nil } func (s *storageZfs) zfsUnmount(path string) error { output, err := shared.TryRunCommand( "zfs", "unmount", fmt.Sprintf("%s/%s", s.zfsPool, path)) if err != nil { s.log.Error("zfs unmount failed", log.Ctx{"output": string(output)}) return fmt.Errorf("Failed to unmount ZFS filesystem: %s", output) } return nil } func (s *storageZfs) zfsListSubvolumes(path string) ([]string, error) { path = strings.TrimRight(path, "/") fullPath := s.zfsPool if path != "" { fullPath = fmt.Sprintf("%s/%s", s.zfsPool, path) } output, err := shared.RunCommand( "zfs", "list", "-t", "filesystem", "-o", "name", "-H", "-r", fullPath) if err != nil { s.log.Error("zfs list failed", log.Ctx{"output": string(output)}) return []string{}, fmt.Errorf("Failed to list ZFS filesystems: %s", output) } children := []string{} for _, entry := range strings.Split(string(output), "\n") { if entry == "" { continue } if entry == fullPath { continue } children = append(children, strings.TrimPrefix(entry, fmt.Sprintf("%s/", s.zfsPool))) } return children, nil } func (s *storageZfs) zfsListSnapshots(path string) ([]string, error) { path = strings.TrimRight(path, "/") fullPath := s.zfsPool if path != "" { fullPath = fmt.Sprintf("%s/%s", s.zfsPool, path) } output, err := shared.RunCommand( "zfs", "list", "-t", "snapshot", "-o", "name", "-H", "-d", "1", "-s", "creation", "-r", fullPath) if err != nil { s.log.Error("zfs list failed", log.Ctx{"output": string(output)}) return []string{}, fmt.Errorf("Failed to list ZFS snapshots: %s", output) } children := []string{} for _, entry := range strings.Split(string(output), "\n") { if entry == "" { continue } if entry == fullPath { continue } children = append(children, strings.SplitN(entry, "@", 2)[1]) } return children, nil } func (s *storageZfs) zfsSnapshotRemovable(path string, name string) (bool, error) { var snap string if name == "" { snap = path } else { snap = fmt.Sprintf("%s@%s", path, name) } clones, err := s.zfsGet(snap, "clones") if err != nil { return false, err } if clones == "-" || clones == "" { return true, nil } return false, nil } func (s *storageZfs) zfsGetPoolUsers() ([]string, error) { subvols, err := s.zfsListSubvolumes("") if err != nil { return []string{}, err } exceptions := []string{ "containers", "images", "snapshots", "deleted", "deleted/containers", "deleted/images"} users := []string{} for _, subvol := range subvols { path := strings.Split(subvol, "/") // Only care about plausible LXD paths if !shared.StringInSlice(path[0], exceptions) { continue } // Ignore empty paths if shared.StringInSlice(subvol, exceptions) { continue } users = append(users, subvol) } return users, nil } // Global functions func storageZFSValidatePoolName(d *Daemon, key string, value string) error { s := storageZfs{} // Confirm the backend is working err := s.initShared() if err != nil { return fmt.Errorf("Unable to initialize the ZFS backend: %v", err) } // Confirm the new pool exists and is compatible if value != "" { err = s.zfsCheckPool(value) if err != nil { return fmt.Errorf("Invalid ZFS pool: %v", err) } // Confirm that the new pool is empty s.zfsPool = value subvols, err := s.zfsListSubvolumes("") if err != nil { return err } if len(subvols) > 0 { return fmt.Errorf("Provided ZFS pool (or dataset) isn't empty") } } // Confirm the old pool isn't in use anymore oldPoolname := daemonConfig["storage.zfs_pool_name"].Get() if oldPoolname != "" { s.zfsPool = oldPoolname users, err := s.zfsGetPoolUsers() if err != nil { return fmt.Errorf("Error checking if a pool is already in use: %v", err) } if len(users) > 0 { return fmt.Errorf("Can not change ZFS config. Images or containers are still using the ZFS pool: %v", users) } } return nil } type zfsMigrationSourceDriver struct { container container snapshots []container zfsSnapshotNames []string zfs *storageZfs runningSnapName string stoppedSnapName string } func (s *zfsMigrationSourceDriver) Snapshots() []container { return s.snapshots } func (s *zfsMigrationSourceDriver) send(conn *websocket.Conn, zfsName string, zfsParent string) error { fields := strings.SplitN(s.container.Name(), shared.SnapshotDelimiter, 2) args := []string{"send", fmt.Sprintf("%s/containers/%s@%s", s.zfs.zfsPool, fields[0], zfsName)} if zfsParent != "" { args = append(args, "-i", fmt.Sprintf("%s/containers/%s@%s", s.zfs.zfsPool, s.container.Name(), zfsParent)) } cmd := exec.Command("zfs", args...) stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } <-shared.WebsocketSendStream(conn, stdout, 4*1024*1024) output, err := ioutil.ReadAll(stderr) if err != nil { logger.Error("problem reading zfs send stderr", log.Ctx{"err": err}) } err = cmd.Wait() if err != nil { logger.Error("problem with zfs send", log.Ctx{"output": string(output)}) } return err } func (s *zfsMigrationSourceDriver) SendWhileRunning(conn *websocket.Conn) error { if s.container.IsSnapshot() { fields := strings.SplitN(s.container.Name(), shared.SnapshotDelimiter, 2) snapshotName := fmt.Sprintf("snapshot-%s", fields[1]) return s.send(conn, snapshotName, "") } lastSnap := "" for i, snap := range s.zfsSnapshotNames { prev := "" if i > 0 { prev = s.zfsSnapshotNames[i-1] } lastSnap = snap if err := s.send(conn, snap, prev); err != nil { return err } } s.runningSnapName = fmt.Sprintf("migration-send-%s", uuid.NewRandom().String()) if err := s.zfs.zfsSnapshotCreate(fmt.Sprintf("containers/%s", s.container.Name()), s.runningSnapName); err != nil { return err } if err := s.send(conn, s.runningSnapName, lastSnap); err != nil { return err } return nil } func (s *zfsMigrationSourceDriver) SendAfterCheckpoint(conn *websocket.Conn) error { s.stoppedSnapName = fmt.Sprintf("migration-send-%s", uuid.NewRandom().String()) if err := s.zfs.zfsSnapshotCreate(fmt.Sprintf("containers/%s", s.container.Name()), s.stoppedSnapName); err != nil { return err } if err := s.send(conn, s.stoppedSnapName, s.runningSnapName); err != nil { return err } return nil } func (s *zfsMigrationSourceDriver) Cleanup() { if s.stoppedSnapName != "" { s.zfs.zfsSnapshotDestroy(fmt.Sprintf("containers/%s", s.container.Name()), s.stoppedSnapName) } if s.runningSnapName != "" { s.zfs.zfsSnapshotDestroy(fmt.Sprintf("containers/%s", s.container.Name()), s.runningSnapName) } } func (s *storageZfs) MigrationType() MigrationFSType { return MigrationFSType_ZFS } func (s *storageZfs) PreservesInodes() bool { return true } func (s *storageZfs) MigrationSource(ct container) (MigrationStorageSourceDriver, error) { /* If the container is a snapshot, let's just send that; we don't need * to send anything else, because that's all the user asked for. */ if ct.IsSnapshot() { return &zfsMigrationSourceDriver{container: ct, zfs: s}, nil } driver := zfsMigrationSourceDriver{ container: ct, snapshots: []container{}, zfsSnapshotNames: []string{}, zfs: s, } /* List all the snapshots in order of reverse creation. The idea here * is that we send the oldest to newest snapshot, hopefully saving on * xfer costs. Then, after all that, we send the container itself. */ snapshots, err := s.zfsListSnapshots(fmt.Sprintf("containers/%s", ct.Name())) if err != nil { return nil, err } for _, snap := range snapshots { /* In the case of e.g. multiple copies running at the same * time, we will have potentially multiple migration-send * snapshots. (Or in the case of the test suite, sometimes one * will take too long to delete.) */ if !strings.HasPrefix(snap, "snapshot-") { continue } lxdName := fmt.Sprintf("%s%s%s", ct.Name(), shared.SnapshotDelimiter, snap[len("snapshot-"):]) snapshot, err := containerLoadByName(s.s, s.storage, lxdName) if err != nil { return nil, err } driver.snapshots = append(driver.snapshots, snapshot) driver.zfsSnapshotNames = append(driver.zfsSnapshotNames, snap) } return &driver, nil } func (s *storageZfs) MigrationSink(live bool, container container, snapshots []*Snapshot, conn *websocket.Conn, srcIdmap *idmap.IdmapSet) error { zfsRecv := func(zfsName string) error { zfsFsName := fmt.Sprintf("%s/%s", s.zfsPool, zfsName) args := []string{"receive", "-F", "-u", zfsFsName} cmd := exec.Command("zfs", args...) stdin, err := cmd.StdinPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } <-shared.WebsocketRecvStream(stdin, conn) output, err := ioutil.ReadAll(stderr) if err != nil { logger.Debug("problem reading zfs recv stderr %s", log.Ctx{"err": err}) } err = cmd.Wait() if err != nil { logger.Error("problem with zfs recv", log.Ctx{"output": string(output)}) } return err } /* In some versions of zfs we can write `zfs recv -F` to mounted * filesystems, and in some versions we can't. So, let's always unmount * this fs (it's empty anyway) before we zfs recv. N.B. that `zfs recv` * of a snapshot also needs tha actual fs that it has snapshotted * unmounted, so we do this before receiving anything. */ zfsName := fmt.Sprintf("containers/%s", container.Name()) err := s.zfsUnmount(zfsName) if err != nil { return err } for _, snap := range snapshots { args := snapshotProtobufToContainerArgs(container.Name(), snap) _, err := containerCreateEmptySnapshot(container.StateObject(), container.Storage(), args) if err != nil { return err } name := fmt.Sprintf("containers/%s@snapshot-%s", container.Name(), snap.GetName()) if err := zfsRecv(name); err != nil { return err } err = os.MkdirAll(shared.VarPath(fmt.Sprintf("snapshots/%s", container.Name())), 0700) if err != nil { return err } err = os.Symlink("on-zfs", shared.VarPath(fmt.Sprintf("snapshots/%s/%s.zfs", container.Name(), snap.GetName()))) if err != nil { return err } } defer func() { /* clean up our migration-send snapshots that we got from recv. */ zfsSnapshots, err := s.zfsListSnapshots(fmt.Sprintf("containers/%s", container.Name())) if err != nil { logger.Error("failed listing snapshots post migration", log.Ctx{"err": err}) return } for _, snap := range zfsSnapshots { // If we received a bunch of snapshots, remove the migration-send-* ones, if not, wipe any snapshot we got if snapshots != nil && len(snapshots) > 0 && !strings.HasPrefix(snap, "migration-send") { continue } s.zfsSnapshotDestroy(fmt.Sprintf("containers/%s", container.Name()), snap) } }() /* finally, do the real container */ if err := zfsRecv(zfsName); err != nil { return err } if live { /* and again for the post-running snapshot if this was a live migration */ if err := zfsRecv(zfsName); err != nil { return err } } /* Sometimes, zfs recv mounts this anyway, even if we pass -u * (https://forums.freebsd.org/threads/zfs-receive-u-shouldnt-mount-received-filesystem-right.36844/) * but sometimes it doesn't. Let's try to mount, but not complain about * failure. */ s.zfsMount(zfsName) return nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/storage_utils.go���������������������������������������������������������������������0000644�0610621�0607500�00000001203�13172163242�017467� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "syscall" "time" ) // Useful functions for unreliable backends func tryMount(src string, dst string, fs string, flags uintptr, options string) error { var err error for i := 0; i < 20; i++ { err = syscall.Mount(src, dst, fs, flags, options) if err == nil { break } time.Sleep(500 * time.Millisecond) } if err != nil { return err } return nil } func tryUnmount(path string, flags int) error { var err error for i := 0; i < 20; i++ { err = syscall.Unmount(path, flags) if err == nil { break } time.Sleep(500 * time.Millisecond) } if err != nil { return err } return nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/storage_test.go����������������������������������������������������������������������0000644�0610621�0607500�00000005604�13172163242�017317� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared/idmap" log "gopkg.in/inconshreveable/log15.v2" ) type storageMock struct { d *Daemon sType storageType log log.Logger storageShared } func (s *storageMock) Init(config map[string]interface{}) (storage, error) { s.sType = storageTypeMock s.sTypeName = storageTypeToString(storageTypeMock) if err := s.initShared(); err != nil { return s, err } return s, nil } func (s *storageMock) GetStorageType() storageType { return s.sType } func (s *storageMock) GetStorageTypeName() string { return s.sTypeName } func (s *storageMock) ContainerCreate(container container) error { return nil } func (s *storageMock) ContainerCreateFromImage( container container, imageFingerprint string) error { return nil } func (s *storageMock) ContainerCanRestore(container container, sourceContainer container) error { return nil } func (s *storageMock) ContainerDelete(container container) error { return nil } func (s *storageMock) ContainerCopy( container container, sourceContainer container) error { return nil } func (s *storageMock) ContainerStart(name string, path string) error { return nil } func (s *storageMock) ContainerStop(name string, path string) error { return nil } func (s *storageMock) ContainerRename( container container, newName string) error { return nil } func (s *storageMock) ContainerRestore( container container, sourceContainer container) error { return nil } func (s *storageMock) ContainerSetQuota( container container, size int64) error { return nil } func (s *storageMock) ContainerGetUsage( container container) (int64, error) { return 0, nil } func (s *storageMock) ContainerSnapshotCreate( snapshotContainer container, sourceContainer container) error { return nil } func (s *storageMock) ContainerSnapshotDelete( snapshotContainer container) error { return nil } func (s *storageMock) ContainerSnapshotRename( snapshotContainer container, newName string) error { return nil } func (s *storageMock) ContainerSnapshotStart(container container) error { return nil } func (s *storageMock) ContainerSnapshotStop(container container) error { return nil } func (s *storageMock) ContainerSnapshotCreateEmpty(snapshotContainer container) error { return nil } func (s *storageMock) ImageCreate(fingerprint string) error { return nil } func (s *storageMock) ImageDelete(fingerprint string) error { return nil } func (s *storageMock) MigrationType() MigrationFSType { return MigrationFSType_RSYNC } func (s *storageMock) PreservesInodes() bool { return false } func (s *storageMock) MigrationSource(container container) (MigrationStorageSourceDriver, error) { return nil, fmt.Errorf("not implemented") } func (s *storageMock) MigrationSink(live bool, container container, snapshots []*Snapshot, conn *websocket.Conn, srcIdmap *idmap.IdmapSet) error { return nil } ����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/storage_lvm.go�����������������������������������������������������������������������0000644�0610621�0607500�00000061446�13172163242�017144� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strconv" "strings" "syscall" "github.com/gorilla/websocket" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) func storageLVMCheckVolumeGroup(vgName string) error { output, err := shared.RunCommand("vgdisplay", "-s", vgName) if err != nil { logger.Debug("vgdisplay failed to find vg", log.Ctx{"output": string(output)}) return fmt.Errorf("LVM volume group '%s' not found", vgName) } return nil } func storageLVMThinpoolExists(vgName string, poolName string) (bool, error) { output, err := exec.Command("vgs", "--noheadings", "-o", "lv_attr", fmt.Sprintf("%s/%s", vgName, poolName)).Output() if err != nil { if exitError, ok := err.(*exec.ExitError); ok { waitStatus := exitError.Sys().(syscall.WaitStatus) if waitStatus.ExitStatus() == 5 { // pool LV was not found return false, nil } } return false, fmt.Errorf("Error checking for pool '%s'", poolName) } // Found LV named poolname, check type: attrs := strings.TrimSpace(string(output[:])) if strings.HasPrefix(attrs, "t") { return true, nil } return false, fmt.Errorf("Pool named '%s' exists but is not a thin pool.", poolName) } func storageLVMGetThinPoolUsers(dbObj *sql.DB) ([]string, error) { results := []string{} if daemonConfig["storage.lvm_vg_name"].Get() == "" { return results, nil } cNames, err := db.ContainersList(dbObj, db.CTypeRegular) if err != nil { return results, err } for _, cName := range cNames { var lvLinkPath string if strings.Contains(cName, shared.SnapshotDelimiter) { lvLinkPath = shared.VarPath("snapshots", fmt.Sprintf("%s.lv", cName)) } else { lvLinkPath = shared.VarPath("containers", fmt.Sprintf("%s.lv", cName)) } if shared.PathExists(lvLinkPath) { results = append(results, cName) } } imageNames, err := db.ImagesGet(dbObj, false) if err != nil { return results, err } for _, imageName := range imageNames { imageLinkPath := shared.VarPath("images", fmt.Sprintf("%s.lv", imageName)) if shared.PathExists(imageLinkPath) { results = append(results, imageName) } } return results, nil } func storageLVMValidateThinPoolName(d *Daemon, key string, value string) error { return doStorageLVMValidateThinPoolName(d.db, key, value) } func doStorageLVMValidateThinPoolName(db *sql.DB, key string, value string) error { users, err := storageLVMGetThinPoolUsers(db) if err != nil { return fmt.Errorf("Error checking if a pool is already in use: %v", err) } if len(users) > 0 { return fmt.Errorf("Can not change LVM config. Images or containers are still using LVs: %v", users) } vgname := daemonConfig["storage.lvm_vg_name"].Get() if value != "" { if vgname == "" { return fmt.Errorf("Can not set lvm_thinpool_name without lvm_vg_name set.") } poolExists, err := storageLVMThinpoolExists(vgname, value) if err != nil { return fmt.Errorf("Error checking for thin pool '%s' in '%s': %v", value, vgname, err) } if !poolExists { return fmt.Errorf("Pool '%s' does not exist in Volume Group '%s'", value, vgname) } } return nil } func storageLVMValidateVolumeGroupName(d *Daemon, key string, value string) error { users, err := storageLVMGetThinPoolUsers(d.db) if err != nil { return fmt.Errorf("Error checking if a pool is already in use: %v", err) } if len(users) > 0 { return fmt.Errorf("Can not change LVM config. Images or containers are still using LVs: %v", users) } if value != "" { err = storageLVMCheckVolumeGroup(value) if err != nil { return err } } return nil } func xfsGenerateNewUUID(lvpath string) error { output, err := shared.RunCommand( "xfs_admin", "-U", "generate", lvpath) if err != nil { return fmt.Errorf("Error generating new UUID: %v\noutput:'%s'", err, string(output)) } return nil } func containerNameToLVName(containerName string) string { lvName := strings.Replace(containerName, "-", "--", -1) return strings.Replace(lvName, shared.SnapshotDelimiter, "-", -1) } type storageLvm struct { vgName string storageShared } func (s *storageLvm) Init(config map[string]interface{}) (storage, error) { s.sType = storageTypeLvm s.sTypeName = storageTypeToString(s.sType) if err := s.initShared(); err != nil { return s, err } output, err := shared.RunCommand("lvm", "version") if err != nil { return nil, fmt.Errorf("Error getting LVM version: %v\noutput:'%s'", err, string(output)) } lines := strings.Split(string(output), "\n") s.sTypeVersion = "" for idx, line := range lines { fields := strings.SplitAfterN(line, ":", 2) if len(fields) < 2 { continue } if idx > 0 { s.sTypeVersion += " / " } s.sTypeVersion += strings.TrimSpace(fields[1]) } if config["vgName"] == nil { vgName := daemonConfig["storage.lvm_vg_name"].Get() if vgName == "" { return s, fmt.Errorf("LVM isn't enabled") } if err := storageLVMCheckVolumeGroup(vgName); err != nil { return s, err } s.vgName = vgName } else { s.vgName = config["vgName"].(string) } return s, nil } func versionSplit(versionString string) (int, int, int, error) { fs := strings.Split(versionString, ".") majs, mins, incs := fs[0], fs[1], fs[2] maj, err := strconv.Atoi(majs) if err != nil { return 0, 0, 0, err } min, err := strconv.Atoi(mins) if err != nil { return 0, 0, 0, err } incs = strings.Split(incs, "(")[0] inc, err := strconv.Atoi(incs) if err != nil { return 0, 0, 0, err } return maj, min, inc, nil } func (s *storageLvm) lvmVersionIsAtLeast(versionString string) (bool, error) { lvmVersion := strings.Split(s.sTypeVersion, "/")[0] lvmMaj, lvmMin, lvmInc, err := versionSplit(lvmVersion) if err != nil { return false, err } inMaj, inMin, inInc, err := versionSplit(versionString) if err != nil { return false, err } if lvmMaj < inMaj || lvmMin < inMin || lvmInc < inInc { return false, nil } else { return true, nil } } func (s *storageLvm) ContainerCreate(container container) error { containerName := containerNameToLVName(container.Name()) lvpath, err := s.createThinLV(containerName) if err != nil { return err } if err := os.MkdirAll(container.Path(), 0755); err != nil { return err } var mode os.FileMode if container.IsPrivileged() { mode = 0700 } else { mode = 0755 } err = os.Chmod(container.Path(), mode) if err != nil { return err } dst := fmt.Sprintf("%s.lv", container.Path()) err = os.Symlink(lvpath, dst) if err != nil { return err } return nil } func (s *storageLvm) ContainerCreateFromImage( container container, imageFingerprint string) error { imageLVFilename := shared.VarPath( "images", fmt.Sprintf("%s.lv", imageFingerprint)) if !shared.PathExists(imageLVFilename) { if err := s.ImageCreate(imageFingerprint); err != nil { return err } } containerName := containerNameToLVName(container.Name()) lvpath, err := s.createSnapshotLV(containerName, imageFingerprint, false) if err != nil { return err } destPath := container.Path() if err := os.MkdirAll(destPath, 0755); err != nil { return fmt.Errorf("Error creating container directory: %v", err) } err = os.Chmod(destPath, 0700) if err != nil { return err } dst := shared.VarPath("containers", fmt.Sprintf("%s.lv", container.Name())) err = os.Symlink(lvpath, dst) if err != nil { return err } // Generate a new xfs's UUID fstype := daemonConfig["storage.lvm_fstype"].Get() if fstype == "xfs" { err := xfsGenerateNewUUID(lvpath) if err != nil { s.ContainerDelete(container) return err } } err = tryMount(lvpath, destPath, fstype, 0, "discard") if err != nil { s.ContainerDelete(container) return fmt.Errorf("Error mounting snapshot LV: %v", err) } var mode os.FileMode if container.IsPrivileged() { mode = 0700 } else { mode = 0755 } err = os.Chmod(destPath, mode) if err != nil { return err } if !container.IsPrivileged() { if err = s.shiftRootfs(container); err != nil { err2 := tryUnmount(destPath, 0) if err2 != nil { return fmt.Errorf("Error in umount: '%s' while cleaning up after error in shiftRootfs: '%s'", err2, err) } s.ContainerDelete(container) return fmt.Errorf("Error in shiftRootfs: %v", err) } } err = container.TemplateApply("create") if err != nil { s.log.Error("Error in create template during ContainerCreateFromImage, continuing to unmount", log.Ctx{"err": err}) } umounterr := tryUnmount(destPath, 0) if umounterr != nil { return fmt.Errorf("Error unmounting '%s' after shiftRootfs: %v", destPath, umounterr) } return err } func (s *storageLvm) ContainerCanRestore(container container, sourceContainer container) error { return nil } func (s *storageLvm) ContainerDelete(container container) error { lvName := containerNameToLVName(container.Name()) if err := s.removeLV(lvName); err != nil { return err } lvLinkPath := fmt.Sprintf("%s.lv", container.Path()) if err := os.Remove(lvLinkPath); err != nil { return err } cPath := container.Path() if err := os.RemoveAll(cPath); err != nil { s.log.Error("ContainerDelete: failed to remove path", log.Ctx{"cPath": cPath, "err": err}) return fmt.Errorf("Cleaning up %s: %s", cPath, err) } return nil } func (s *storageLvm) ContainerCopy(container container, sourceContainer container) error { if s.isLVMContainer(sourceContainer) { if err := s.createSnapshotContainer(container, sourceContainer, false); err != nil { s.log.Error("Error creating snapshot LV for copy", log.Ctx{"err": err}) return err } } else { s.log.Info("Copy from Non-LVM container", log.Ctx{"container": container.Name(), "sourceContainer": sourceContainer.Name()}) if err := s.ContainerCreate(container); err != nil { s.log.Error("Error creating empty container", log.Ctx{"err": err}) return err } if err := s.ContainerStart(container.Name(), container.Path()); err != nil { s.log.Error("Error starting/mounting container", log.Ctx{"err": err, "container": container.Name()}) s.ContainerDelete(container) return err } output, err := storageRsyncCopy( sourceContainer.Path(), container.Path()) if err != nil { s.log.Error("ContainerCopy: rsync failed", log.Ctx{"output": string(output)}) s.ContainerDelete(container) return fmt.Errorf("rsync failed: %s", string(output)) } if err := s.ContainerStop(container.Name(), container.Path()); err != nil { return err } } return container.TemplateApply("copy") } func (s *storageLvm) ContainerStart(name string, path string) error { lvName := containerNameToLVName(name) lvpath := fmt.Sprintf("/dev/%s/%s", s.vgName, lvName) fstype := daemonConfig["storage.lvm_fstype"].Get() err := tryMount(lvpath, path, fstype, 0, "discard") if err != nil { return fmt.Errorf( "Error mounting snapshot LV path='%s': %v", path, err) } return nil } func (s *storageLvm) ContainerStop(name string, path string) error { err := tryUnmount(path, 0) if err != nil { return fmt.Errorf( "failed to unmount container path '%s'.\nError: %v", path, err) } return nil } func (s *storageLvm) ContainerRename( container container, newContainerName string) error { oldName := containerNameToLVName(container.Name()) newName := containerNameToLVName(newContainerName) output, err := s.renameLV(oldName, newName) if err != nil { s.log.Error("Failed to rename a container LV", log.Ctx{"oldName": oldName, "newName": newName, "err": err, "output": string(output)}) return fmt.Errorf("Failed to rename a container LV, oldName='%s', newName='%s', err='%s'", oldName, newName, err) } // Rename the snapshots if !container.IsSnapshot() { snaps, err := container.Snapshots() if err != nil { return err } for _, snap := range snaps { baseSnapName := filepath.Base(snap.Name()) newSnapshotName := newName + shared.SnapshotDelimiter + baseSnapName err := s.ContainerRename(snap, newSnapshotName) if err != nil { return err } oldPathParent := filepath.Dir(snap.Path()) if ok, _ := shared.PathIsEmpty(oldPathParent); ok { os.Remove(oldPathParent) } } } // Create a new symlink newSymPath := fmt.Sprintf("%s.lv", containerPath(newContainerName, container.IsSnapshot())) err = os.MkdirAll(filepath.Dir(containerPath(newContainerName, container.IsSnapshot())), 0700) if err != nil { return err } err = os.Symlink(fmt.Sprintf("/dev/%s/%s", s.vgName, newName), newSymPath) if err != nil { return err } // Remove the old symlink oldSymPath := fmt.Sprintf("%s.lv", container.Path()) err = os.Remove(oldSymPath) if err != nil { return err } // Rename the directory err = os.Rename(container.Path(), containerPath(newContainerName, container.IsSnapshot())) if err != nil { return err } return nil } func (s *storageLvm) ContainerRestore( container container, sourceContainer container) error { srcName := containerNameToLVName(sourceContainer.Name()) destName := containerNameToLVName(container.Name()) err := s.removeLV(destName) if err != nil { return fmt.Errorf("Error removing LV about to be restored over: %v", err) } _, err = s.createSnapshotLV(destName, srcName, false) if err != nil { return fmt.Errorf("Error creating snapshot LV: %v", err) } return nil } func (s *storageLvm) ContainerSetQuota(container container, size int64) error { return fmt.Errorf("The LVM container backend doesn't support quotas.") } func (s *storageLvm) ContainerGetUsage(container container) (int64, error) { return -1, fmt.Errorf("The LVM container backend doesn't support quotas.") } func (s *storageLvm) ContainerSnapshotCreate( snapshotContainer container, sourceContainer container) error { return s.createSnapshotContainer(snapshotContainer, sourceContainer, true) } func (s *storageLvm) createSnapshotContainer( snapshotContainer container, sourceContainer container, readonly bool) error { srcName := containerNameToLVName(sourceContainer.Name()) destName := containerNameToLVName(snapshotContainer.Name()) logger.Debug( "Creating snapshot", log.Ctx{"srcName": srcName, "destName": destName}) lvpath, err := s.createSnapshotLV(destName, srcName, readonly) if err != nil { return fmt.Errorf("Error creating snapshot LV: %v", err) } destPath := snapshotContainer.Path() if err := os.MkdirAll(destPath, 0755); err != nil { return fmt.Errorf("Error creating container directory: %v", err) } var mode os.FileMode if snapshotContainer.IsPrivileged() { mode = 0700 } else { mode = 0755 } err = os.Chmod(destPath, mode) if err != nil { return err } dest := fmt.Sprintf("%s.lv", snapshotContainer.Path()) err = os.Symlink(lvpath, dest) if err != nil { return err } return nil } func (s *storageLvm) ContainerSnapshotDelete( snapshotContainer container) error { err := s.ContainerDelete(snapshotContainer) if err != nil { return fmt.Errorf("Error deleting snapshot %s: %s", snapshotContainer.Name(), err) } oldPathParent := filepath.Dir(snapshotContainer.Path()) if ok, _ := shared.PathIsEmpty(oldPathParent); ok { os.Remove(oldPathParent) } return nil } func (s *storageLvm) ContainerSnapshotRename( snapshotContainer container, newContainerName string) error { oldName := containerNameToLVName(snapshotContainer.Name()) newName := containerNameToLVName(newContainerName) oldPath := snapshotContainer.Path() oldSymPath := fmt.Sprintf("%s.lv", oldPath) newPath := containerPath(newContainerName, true) newSymPath := fmt.Sprintf("%s.lv", newPath) // Rename the LV output, err := s.renameLV(oldName, newName) if err != nil { s.log.Error("Failed to rename a snapshot LV", log.Ctx{"oldName": oldName, "newName": newName, "err": err, "output": string(output)}) return fmt.Errorf("Failed to rename a container LV, oldName='%s', newName='%s', err='%s'", oldName, newName, err) } // Delete the symlink err = os.Remove(oldSymPath) if err != nil { return fmt.Errorf("Failed to remove old symlink: %s", err) } // Create the symlink err = os.Symlink(fmt.Sprintf("/dev/%s/%s", s.vgName, newName), newSymPath) if err != nil { return fmt.Errorf("Failed to create symlink: %s", err) } // Rename the mount point err = os.Rename(oldPath, newPath) if err != nil { return fmt.Errorf("Failed to rename mountpoint: %s", err) } return nil } func (s *storageLvm) ContainerSnapshotStart(container container) error { srcName := containerNameToLVName(container.Name()) destName := containerNameToLVName(container.Name() + "/rw") logger.Debug( "Creating snapshot", log.Ctx{"srcName": srcName, "destName": destName}) lvpath, err := s.createSnapshotLV(destName, srcName, false) if err != nil { return fmt.Errorf("Error creating snapshot LV: %v", err) } destPath := container.Path() if !shared.PathExists(destPath) { if err := os.MkdirAll(destPath, 0755); err != nil { return fmt.Errorf("Error creating container directory: %v", err) } } // Generate a new xfs's UUID fstype := daemonConfig["storage.lvm_fstype"].Get() if fstype == "xfs" { err := xfsGenerateNewUUID(lvpath) if err != nil { s.ContainerDelete(container) return err } } err = tryMount(lvpath, container.Path(), fstype, 0, "discard") if err != nil { return fmt.Errorf( "Error mounting snapshot LV path='%s': %v", container.Path(), err) } return nil } func (s *storageLvm) ContainerSnapshotStop(container container) error { err := s.ContainerStop(container.Name(), container.Path()) if err != nil { return err } lvName := containerNameToLVName(container.Name() + "/rw") if err := s.removeLV(lvName); err != nil { return err } return nil } func (s *storageLvm) ContainerSnapshotCreateEmpty(snapshotContainer container) error { return s.ContainerCreate(snapshotContainer) } func (s *storageLvm) ImageCreate(fingerprint string) error { finalName := shared.VarPath("images", fingerprint) lvpath, err := s.createThinLV(fingerprint) if err != nil { s.log.Error("LVMCreateThinLV", log.Ctx{"err": err}) return fmt.Errorf("Error Creating LVM LV for new image: %v", err) } dst := shared.VarPath("images", fmt.Sprintf("%s.lv", fingerprint)) err = os.Symlink(lvpath, dst) if err != nil { return err } tempLVMountPoint, err := ioutil.TempDir(shared.VarPath("images"), "tmp_lv_mnt") if err != nil { return err } defer func() { if err := os.RemoveAll(tempLVMountPoint); err != nil { s.log.Error("Deleting temporary LVM mount point", log.Ctx{"err": err}) } }() fstype := daemonConfig["storage.lvm_fstype"].Get() err = tryMount(lvpath, tempLVMountPoint, fstype, 0, "discard") if err != nil { logger.Infof("Error mounting image LV for unpacking: %v", err) return fmt.Errorf("Error mounting image LV: %v", err) } unpackErr := unpackImage(finalName, tempLVMountPoint, s.storage.GetStorageType()) err = tryUnmount(tempLVMountPoint, 0) if err != nil { s.log.Warn("could not unmount LV. Will not remove", log.Ctx{"lvpath": lvpath, "mountpoint": tempLVMountPoint, "err": err}) if unpackErr == nil { return err } return fmt.Errorf( "Error unmounting '%s' during cleanup of error %v", tempLVMountPoint, unpackErr) } if unpackErr != nil { s.removeLV(fingerprint) return unpackErr } return nil } func (s *storageLvm) ImageDelete(fingerprint string) error { err := s.removeLV(fingerprint) if err != nil { return err } lvsymlink := fmt.Sprintf( "%s.lv", shared.VarPath("images", fingerprint)) err = os.Remove(lvsymlink) if err != nil { return fmt.Errorf( "Failed to remove symlink to deleted image LV: '%s': %v", lvsymlink, err) } return nil } func (s *storageLvm) createDefaultThinPool() (string, error) { thinPoolName := daemonConfig["storage.lvm_thinpool_name"].Get() isRecent, err := s.lvmVersionIsAtLeast("2.02.99") if err != nil { return "", fmt.Errorf("Error checking LVM version: %v", err) } // Create the thin pool var output string if isRecent { output, err = shared.TryRunCommand( "lvcreate", "--poolmetadatasize", "1G", "-l", "100%FREE", "--thinpool", fmt.Sprintf("%s/%s", s.vgName, thinPoolName)) } else { output, err = shared.TryRunCommand( "lvcreate", "--poolmetadatasize", "1G", "-L", "1G", "--thinpool", fmt.Sprintf("%s/%s", s.vgName, thinPoolName)) } if err != nil { s.log.Error( "Could not create thin pool", log.Ctx{ "name": thinPoolName, "err": err, "output": string(output)}) return "", fmt.Errorf( "Could not create LVM thin pool named %s", thinPoolName) } if !isRecent { // Grow it to the maximum VG size (two step process required by old LVM) output, err = shared.TryRunCommand( "lvextend", "--alloc", "anywhere", "-l", "100%FREE", fmt.Sprintf("%s/%s", s.vgName, thinPoolName)) if err != nil { s.log.Error( "Could not grow thin pool", log.Ctx{ "name": thinPoolName, "err": err, "output": string(output)}) return "", fmt.Errorf( "Could not grow LVM thin pool named %s", thinPoolName) } } return thinPoolName, nil } func (s *storageLvm) createThinLV(lvname string) (string, error) { var err error vgname := daemonConfig["storage.lvm_vg_name"].Get() poolname := daemonConfig["storage.lvm_thinpool_name"].Get() exists, err := storageLVMThinpoolExists(vgname, poolname) if err != nil { return "", err } if !exists { poolname, err = s.createDefaultThinPool() if err != nil { return "", fmt.Errorf("Error creating LVM thin pool: %v", err) } err = doStorageLVMValidateThinPoolName(s.s.DB, "", poolname) if err != nil { s.log.Error("Setting thin pool name", log.Ctx{"err": err}) return "", fmt.Errorf("Error setting LVM thin pool config: %v", err) } } lvSize := daemonConfig["storage.lvm_volume_size"].Get() output, err := shared.TryRunCommand( "lvcreate", "--thin", "-n", lvname, "--virtualsize", lvSize, fmt.Sprintf("%s/%s", s.vgName, poolname)) if err != nil { s.log.Error("Could not create LV", log.Ctx{"lvname": lvname, "output": string(output)}) return "", fmt.Errorf("Could not create thin LV named %s", lvname) } lvpath := fmt.Sprintf("/dev/%s/%s", s.vgName, lvname) fstype := daemonConfig["storage.lvm_fstype"].Get() switch fstype { case "xfs": output, err = shared.TryRunCommand( "mkfs.xfs", lvpath) default: // default = ext4 output, err = shared.TryRunCommand( "mkfs.ext4", "-E", "nodiscard,lazy_itable_init=0,lazy_journal_init=0", lvpath) } if err != nil { s.log.Error("Filesystem creation failed", log.Ctx{"output": string(output)}) return "", fmt.Errorf("Error making filesystem on image LV: %v", err) } return lvpath, nil } func (s *storageLvm) removeLV(lvname string) error { var err error var output string output, err = shared.TryRunCommand( "lvremove", "-f", fmt.Sprintf("%s/%s", s.vgName, lvname)) if err != nil { s.log.Error("Could not remove LV", log.Ctx{"lvname": lvname, "output": string(output)}) return fmt.Errorf("Could not remove LV named %s", lvname) } return nil } func (s *storageLvm) createSnapshotLV(lvname string, origlvname string, readonly bool) (string, error) { s.log.Debug("in createSnapshotLV:", log.Ctx{"lvname": lvname, "dev string": fmt.Sprintf("/dev/%s/%s", s.vgName, origlvname)}) isRecent, err := s.lvmVersionIsAtLeast("2.02.99") if err != nil { return "", fmt.Errorf("Error checking LVM version: %v", err) } var output string if isRecent { output, err = shared.TryRunCommand( "lvcreate", "-kn", "-n", lvname, "-s", fmt.Sprintf("/dev/%s/%s", s.vgName, origlvname)) } else { output, err = shared.TryRunCommand( "lvcreate", "-n", lvname, "-s", fmt.Sprintf("/dev/%s/%s", s.vgName, origlvname)) } if err != nil { s.log.Error("Could not create LV snapshot", log.Ctx{"lvname": lvname, "origlvname": origlvname, "output": string(output)}) return "", fmt.Errorf("Could not create snapshot LV named %s", lvname) } snapshotFullName := fmt.Sprintf("/dev/%s/%s", s.vgName, lvname) if readonly { output, err = shared.TryRunCommand("lvchange", "-ay", "-pr", snapshotFullName) } else { output, err = shared.TryRunCommand("lvchange", "-ay", snapshotFullName) } if err != nil { return "", fmt.Errorf("Could not activate new snapshot '%s': %v\noutput:%s", lvname, err, string(output)) } return snapshotFullName, nil } func (s *storageLvm) isLVMContainer(container container) bool { return shared.PathExists(fmt.Sprintf("%s.lv", container.Path())) } func (s *storageLvm) renameLV(oldName string, newName string) (string, error) { output, err := shared.TryRunCommand("lvrename", s.vgName, oldName, newName) return string(output), err } func (s *storageLvm) MigrationType() MigrationFSType { return MigrationFSType_RSYNC } func (s *storageLvm) PreservesInodes() bool { return false } func (s *storageLvm) MigrationSource(container container) (MigrationStorageSourceDriver, error) { return rsyncMigrationSource(container) } func (s *storageLvm) MigrationSink(live bool, container container, snapshots []*Snapshot, conn *websocket.Conn, srcIdmap *idmap.IdmapSet) error { return rsyncMigrationSink(live, container, snapshots, conn, srcIdmap) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/storage_dir.go�����������������������������������������������������������������������0000644�0610621�0607500�00000017033�13172163242�017115� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "path/filepath" "strings" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/idmap" log "gopkg.in/inconshreveable/log15.v2" ) type storageDir struct { storageShared } func (s *storageDir) Init(config map[string]interface{}) (storage, error) { s.sType = storageTypeDir s.sTypeName = storageTypeToString(s.sType) if err := s.initShared(); err != nil { return s, err } return s, nil } func (s *storageDir) ContainerCreate(container container) error { cPath := container.Path() if err := os.MkdirAll(cPath, 0755); err != nil { return fmt.Errorf("Error creating containers directory") } var mode os.FileMode if container.IsPrivileged() { mode = 0700 } else { mode = 0755 } if err := os.Chmod(cPath, mode); err != nil { return err } return container.TemplateApply("create") } func (s *storageDir) ContainerCreateFromImage( container container, imageFingerprint string) error { rootfsPath := container.RootfsPath() if err := os.MkdirAll(rootfsPath, 0755); err != nil { return fmt.Errorf("Error creating rootfs directory") } var mode os.FileMode if container.IsPrivileged() { mode = 0700 } else { mode = 0755 } if err := os.Chmod(container.Path(), mode); err != nil { return err } imagePath := shared.VarPath("images", imageFingerprint) if err := unpackImage(imagePath, container.Path(), s.storage.GetStorageType()); err != nil { s.ContainerDelete(container) return err } if !container.IsPrivileged() { if err := s.shiftRootfs(container); err != nil { s.ContainerDelete(container) return err } } return container.TemplateApply("create") } func (s *storageDir) ContainerCanRestore(container container, sourceContainer container) error { return nil } func (s *storageDir) ContainerDelete(container container) error { cPath := container.Path() if !shared.PathExists(cPath) { return nil } err := os.RemoveAll(cPath) if err != nil { // RemovaAll fails on very long paths, so attempt an rm -Rf output, err := shared.RunCommand("rm", "-Rf", cPath) if err != nil { s.log.Error("ContainerDelete: failed", log.Ctx{"cPath": cPath, "output": output}) return fmt.Errorf("Error cleaning up %s: %s", cPath, string(output)) } } return nil } func (s *storageDir) ContainerCopy( container container, sourceContainer container) error { oldPath := sourceContainer.Path() newPath := container.Path() /* * Copy by using rsync */ output, err := storageRsyncCopy(oldPath, newPath) if err != nil { s.ContainerDelete(container) s.log.Error("ContainerCopy: rsync failed", log.Ctx{"output": string(output)}) return fmt.Errorf("rsync failed: %s", string(output)) } err = s.setUnprivUserAcl(sourceContainer, container.Path()) if err != nil { return err } return container.TemplateApply("copy") } func (s *storageDir) ContainerStart(name string, path string) error { return nil } func (s *storageDir) ContainerStop(name string, path string) error { return nil } func (s *storageDir) ContainerRename(container container, newName string) error { oldName := container.Name() oldPath := container.Path() newPath := containerPath(newName, false) if err := os.Rename(oldPath, newPath); err != nil { return err } if shared.PathExists(shared.VarPath(fmt.Sprintf("snapshots/%s", oldName))) { err := os.Rename(shared.VarPath(fmt.Sprintf("snapshots/%s", oldName)), shared.VarPath(fmt.Sprintf("snapshots/%s", newName))) if err != nil { return err } } return nil } func (s *storageDir) ContainerRestore( container container, sourceContainer container) error { targetPath := container.Path() sourcePath := sourceContainer.Path() // Restore using rsync output, err := storageRsyncCopy( sourcePath, targetPath) if err != nil { s.log.Error( "ContainerRestore: rsync failed", log.Ctx{"output": string(output)}) return err } // Now allow unprivileged users to access its data. if err := s.setUnprivUserAcl(sourceContainer, targetPath); err != nil { return err } return nil } func (s *storageDir) ContainerSetQuota(container container, size int64) error { return fmt.Errorf("The directory container backend doesn't support quotas.") } func (s *storageDir) ContainerGetUsage(container container) (int64, error) { return -1, fmt.Errorf("The directory container backend doesn't support quotas.") } func (s *storageDir) ContainerSnapshotCreate( snapshotContainer container, sourceContainer container) error { oldPath := sourceContainer.Path() newPath := snapshotContainer.Path() /* * Copy by using rsync */ rsync := func(snapshotContainer container, oldPath string, newPath string) error { output, err := storageRsyncCopy(oldPath, newPath) if err != nil { s.ContainerDelete(snapshotContainer) s.log.Error("ContainerSnapshotCreate: rsync failed", log.Ctx{"output": string(output)}) return fmt.Errorf("rsync failed: %s", string(output)) } return nil } if err := rsync(snapshotContainer, oldPath, newPath); err != nil { return err } if sourceContainer.IsRunning() { /* This is done to ensure consistency when snapshotting. But we * probably shouldn't fail just because of that. */ s.log.Debug("ContainerSnapshotCreate: trying to freeze and rsync again to ensure consistency.") if err := sourceContainer.Freeze(); err != nil { s.log.Warn("ContainerSnapshotCreate: trying to freeze and rsync again failed.") return nil } defer sourceContainer.Unfreeze() if err := rsync(snapshotContainer, oldPath, newPath); err != nil { return err } } return nil } func (s *storageDir) ContainerSnapshotCreateEmpty(snapshotContainer container) error { return os.MkdirAll(snapshotContainer.Path(), 0700) } func (s *storageDir) ContainerSnapshotDelete( snapshotContainer container) error { err := s.ContainerDelete(snapshotContainer) if err != nil { return fmt.Errorf("Error deleting snapshot %s: %s", snapshotContainer.Name(), err) } oldPathParent := filepath.Dir(snapshotContainer.Path()) if ok, _ := shared.PathIsEmpty(oldPathParent); ok { os.Remove(oldPathParent) } return nil } func (s *storageDir) ContainerSnapshotRename( snapshotContainer container, newName string) error { oldPath := snapshotContainer.Path() newPath := containerPath(newName, true) // Create the new parent. if strings.Contains(snapshotContainer.Name(), "/") { if !shared.PathExists(filepath.Dir(newPath)) { os.MkdirAll(filepath.Dir(newPath), 0700) } } // Now rename the snapshot. if err := os.Rename(oldPath, newPath); err != nil { return err } // Remove the old parent (on container rename) if its empty. if strings.Contains(snapshotContainer.Name(), "/") { if ok, _ := shared.PathIsEmpty(filepath.Dir(oldPath)); ok { os.Remove(filepath.Dir(oldPath)) } } return nil } func (s *storageDir) ContainerSnapshotStart(container container) error { return nil } func (s *storageDir) ContainerSnapshotStop(container container) error { return nil } func (s *storageDir) ImageCreate(fingerprint string) error { return nil } func (s *storageDir) ImageDelete(fingerprint string) error { return nil } func (s *storageDir) MigrationType() MigrationFSType { return MigrationFSType_RSYNC } func (s *storageDir) PreservesInodes() bool { return false } func (s *storageDir) MigrationSource(container container) (MigrationStorageSourceDriver, error) { return rsyncMigrationSource(container) } func (s *storageDir) MigrationSink(live bool, container container, snapshots []*Snapshot, conn *websocket.Conn, srcIdmap *idmap.IdmapSet) error { return rsyncMigrationSink(live, container, snapshots, conn, srcIdmap) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/storage_btrfs.go���������������������������������������������������������������������0000644�0610621�0607500�00000055254�13172163242�017466� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "os" "os/exec" "path" "path/filepath" "sort" "strconv" "strings" "syscall" "github.com/gorilla/websocket" "github.com/pborman/uuid" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) type storageBtrfs struct { storageShared } func (s *storageBtrfs) Init(config map[string]interface{}) (storage, error) { s.sType = storageTypeBtrfs s.sTypeName = storageTypeToString(s.sType) if err := s.initShared(); err != nil { return s, err } out, err := exec.LookPath("btrfs") if err != nil || len(out) == 0 { return s, fmt.Errorf("The 'btrfs' tool isn't available") } output, err := shared.RunCommand("btrfs", "version") if err != nil { return s, fmt.Errorf("The 'btrfs' tool isn't working properly") } count, err := fmt.Sscanf(strings.SplitN(string(output), " ", 2)[1], "v%s\n", &s.sTypeVersion) if err != nil || count != 1 { return s, fmt.Errorf("The 'btrfs' tool isn't working properly") } return s, nil } func (s *storageBtrfs) ContainerCreate(container container) error { cPath := container.Path() // MkdirAll the pardir of the BTRFS Subvolume. if err := os.MkdirAll(filepath.Dir(cPath), 0755); err != nil { return err } // Create the BTRFS Subvolume err := s.subvolCreate(cPath) if err != nil { return err } if container.IsPrivileged() { if err := os.Chmod(cPath, 0700); err != nil { return err } } return container.TemplateApply("create") } func (s *storageBtrfs) ContainerCreateFromImage( container container, imageFingerprint string) error { imageSubvol := fmt.Sprintf( "%s.btrfs", shared.VarPath("images", imageFingerprint)) // Create the btrfs subvol of the image first if it doesn exists. if !shared.PathExists(imageSubvol) { if err := s.ImageCreate(imageFingerprint); err != nil { return err } } // Now make a snapshot of the image subvol err := s.subvolsSnapshot(imageSubvol, container.Path(), false) if err != nil { return err } if !container.IsPrivileged() { if err = s.shiftRootfs(container); err != nil { s.ContainerDelete(container) return err } } else { if err := os.Chmod(container.Path(), 0700); err != nil { return err } } return container.TemplateApply("create") } func (s *storageBtrfs) ContainerCanRestore(container container, sourceContainer container) error { return nil } func (s *storageBtrfs) ContainerDelete(container container) error { cPath := container.Path() // First remove the subvol (if it was one). if s.isSubvolume(cPath) { if err := s.subvolsDelete(cPath); err != nil { return err } } // Then the directory (if it still exists). if shared.PathExists(cPath) { err := os.RemoveAll(cPath) if err != nil { s.log.Error("ContainerDelete: failed", log.Ctx{"cPath": cPath, "err": err}) return fmt.Errorf("Error cleaning up %s: %s", cPath, err) } } return nil } func (s *storageBtrfs) ContainerCopy(container container, sourceContainer container) error { subvol := sourceContainer.Path() dpath := container.Path() if s.isSubvolume(subvol) { // Snapshot the sourcecontainer err := s.subvolsSnapshot(subvol, dpath, false) if err != nil { return err } } else { // Create the BTRFS Container. if err := s.ContainerCreate(container); err != nil { return err } /* * Copy by using rsync */ output, err := storageRsyncCopy( sourceContainer.Path(), container.Path()) if err != nil { s.ContainerDelete(container) s.log.Error("ContainerCopy: rsync failed", log.Ctx{"output": string(output)}) return fmt.Errorf("rsync failed: %s", string(output)) } } if err := s.setUnprivUserAcl(sourceContainer, dpath); err != nil { s.ContainerDelete(container) return err } return container.TemplateApply("copy") } func (s *storageBtrfs) ContainerStart(name string, path string) error { return nil } func (s *storageBtrfs) ContainerStop(name string, path string) error { return nil } func (s *storageBtrfs) ContainerRename(container container, newName string) error { oldName := container.Name() oldPath := container.Path() newPath := containerPath(newName, false) if err := os.Rename(oldPath, newPath); err != nil { return err } if shared.PathExists(shared.VarPath(fmt.Sprintf("snapshots/%s", oldName))) { err := os.Rename(shared.VarPath(fmt.Sprintf("snapshots/%s", oldName)), shared.VarPath(fmt.Sprintf("snapshots/%s", newName))) if err != nil { return err } } return nil } func (s *storageBtrfs) ContainerRestore( container container, sourceContainer container) error { targetSubVol := container.Path() sourceSubVol := sourceContainer.Path() sourceBackupPath := container.Path() + ".back" // Create a backup of the container err := os.Rename(container.Path(), sourceBackupPath) if err != nil { return err } var failure error if s.isSubvolume(sourceSubVol) { // Restore using btrfs snapshots. err := s.subvolsSnapshot(sourceSubVol, targetSubVol, false) if err != nil { failure = err } } else { // Restore using rsync but create a btrfs subvol. if err := s.subvolCreate(targetSubVol); err == nil { output, err := storageRsyncCopy( sourceSubVol, targetSubVol) if err != nil { s.log.Error( "ContainerRestore: rsync failed", log.Ctx{"output": string(output)}) failure = err } } else { failure = err } } // Now allow unprivileged users to access its data. if err := s.setUnprivUserAcl(sourceContainer, targetSubVol); err != nil { failure = err } if failure != nil { // Restore original container s.ContainerDelete(container) os.Rename(sourceBackupPath, container.Path()) } else { // Remove the backup, we made if s.isSubvolume(sourceBackupPath) { return s.subvolsDelete(sourceBackupPath) } os.RemoveAll(sourceBackupPath) } return failure } func (s *storageBtrfs) ContainerSetQuota(container container, size int64) error { subvol := container.Path() _, err := s.subvolQGroup(subvol) if err != nil { return err } output, err := shared.RunCommand( "btrfs", "qgroup", "limit", "-e", fmt.Sprintf("%d", size), subvol) if err != nil { return fmt.Errorf("Failed to set btrfs quota: %s", output) } return nil } func (s *storageBtrfs) ContainerGetUsage(container container) (int64, error) { return s.subvolQGroupUsage(container.Path()) } func (s *storageBtrfs) ContainerSnapshotCreate( snapshotContainer container, sourceContainer container) error { subvol := sourceContainer.Path() dpath := snapshotContainer.Path() if s.isSubvolume(subvol) { // Create a readonly snapshot of the source. err := s.subvolsSnapshot(subvol, dpath, true) if err != nil { s.ContainerSnapshotDelete(snapshotContainer) return err } } else { /* * Copy by using rsync */ output, err := storageRsyncCopy( subvol, dpath) if err != nil { s.ContainerSnapshotDelete(snapshotContainer) s.log.Error( "ContainerSnapshotCreate: rsync failed", log.Ctx{"output": string(output)}) return fmt.Errorf("rsync failed: %s", string(output)) } } return nil } func (s *storageBtrfs) ContainerSnapshotDelete( snapshotContainer container) error { err := s.ContainerDelete(snapshotContainer) if err != nil { return fmt.Errorf("Error deleting snapshot %s: %s", snapshotContainer.Name(), err) } oldPathParent := filepath.Dir(snapshotContainer.Path()) if ok, _ := shared.PathIsEmpty(oldPathParent); ok { os.Remove(oldPathParent) } return nil } func (s *storageBtrfs) ContainerSnapshotStart(container container) error { if shared.PathExists(container.Path() + ".ro") { return fmt.Errorf("The snapshot is already mounted read-write.") } err := os.Rename(container.Path(), container.Path()+".ro") if err != nil { return err } err = s.subvolsSnapshot(container.Path()+".ro", container.Path(), false) if err != nil { return err } return nil } func (s *storageBtrfs) ContainerSnapshotStop(container container) error { if !shared.PathExists(container.Path() + ".ro") { return fmt.Errorf("The snapshot isn't currently mounted read-write.") } err := s.subvolsDelete(container.Path()) if err != nil { return err } err = os.Rename(container.Path()+".ro", container.Path()) if err != nil { return err } return nil } // ContainerSnapshotRename renames a snapshot of a container. func (s *storageBtrfs) ContainerSnapshotRename( snapshotContainer container, newName string) error { oldPath := snapshotContainer.Path() newPath := containerPath(newName, true) // Create the new parent. if !shared.PathExists(filepath.Dir(newPath)) { os.MkdirAll(filepath.Dir(newPath), 0700) } // Now rename the snapshot. if !s.isSubvolume(oldPath) { if err := os.Rename(oldPath, newPath); err != nil { return err } } else { if err := s.subvolsSnapshot(oldPath, newPath, true); err != nil { return err } if err := s.subvolsDelete(oldPath); err != nil { return err } } // Remove the old parent (on container rename) if its empty. if ok, _ := shared.PathIsEmpty(filepath.Dir(oldPath)); ok { os.Remove(filepath.Dir(oldPath)) } return nil } func (s *storageBtrfs) ContainerSnapshotCreateEmpty(snapshotContainer container) error { dpath := snapshotContainer.Path() return s.subvolCreate(dpath) } func (s *storageBtrfs) ImageCreate(fingerprint string) error { imagePath := shared.VarPath("images", fingerprint) subvol := fmt.Sprintf("%s.btrfs", imagePath) if err := s.subvolCreate(subvol); err != nil { return err } if err := unpackImage(imagePath, subvol, s.storage.GetStorageType()); err != nil { s.subvolsDelete(subvol) return err } return nil } func (s *storageBtrfs) ImageDelete(fingerprint string) error { imagePath := shared.VarPath("images", fingerprint) subvol := fmt.Sprintf("%s.btrfs", imagePath) if s.isSubvolume(subvol) { if err := s.subvolsDelete(subvol); err != nil { return err } } return nil } func (s *storageBtrfs) subvolCreate(subvol string) error { parentDestPath := filepath.Dir(subvol) if !shared.PathExists(parentDestPath) { if err := os.MkdirAll(parentDestPath, 0700); err != nil { return err } } output, err := shared.RunCommand( "btrfs", "subvolume", "create", subvol) if err != nil { s.log.Debug( "subvolume create failed", log.Ctx{"subvol": subvol, "output": string(output)}, ) return fmt.Errorf( "btrfs subvolume create failed, subvol=%s, output%s", subvol, string(output), ) } return nil } func (s *storageBtrfs) subvolQGroup(subvol string) (string, error) { output, err := shared.RunCommand( "btrfs", "qgroup", "show", subvol, "-e", "-f") if err != nil { return "", fmt.Errorf("btrfs quotas not supported. Try enabling them with 'btrfs quota enable'.") } var qgroup string for _, line := range strings.Split(string(output), "\n") { if line == "" || strings.HasPrefix(line, "qgroupid") || strings.HasPrefix(line, "---") { continue } fields := strings.Fields(line) if len(fields) != 4 { continue } qgroup = fields[0] } if qgroup == "" { return "", fmt.Errorf("Unable to find quota group") } return qgroup, nil } func (s *storageBtrfs) subvolQGroupUsage(subvol string) (int64, error) { output, err := shared.RunCommand( "btrfs", "qgroup", "show", subvol, "-e", "-f") if err != nil { return -1, fmt.Errorf("btrfs quotas not supported. Try enabling them with 'btrfs quota enable'.") } for _, line := range strings.Split(string(output), "\n") { if line == "" || strings.HasPrefix(line, "qgroupid") || strings.HasPrefix(line, "---") { continue } fields := strings.Fields(line) if len(fields) != 4 { continue } usage, err := strconv.ParseInt(fields[2], 10, 64) if err != nil { continue } return usage, nil } return -1, fmt.Errorf("Unable to find current qgroup usage") } func (s *storageBtrfs) subvolDelete(subvol string) error { // Attempt (but don't fail on) to delete any qgroup on the subvolume qgroup, err := s.subvolQGroup(subvol) if err == nil { output, err := shared.RunCommand( "btrfs", "qgroup", "destroy", qgroup, subvol) if err != nil { s.log.Warn( "subvolume qgroup delete failed", log.Ctx{"subvol": subvol, "output": string(output)}, ) } } // Delete the subvolume itself output, err := shared.RunCommand( "btrfs", "subvolume", "delete", subvol, ) if err != nil { s.log.Warn( "subvolume delete failed", log.Ctx{"subvol": subvol, "output": string(output)}, ) } return nil } // subvolsDelete is the recursive variant on subvolDelete, // it first deletes subvolumes of the subvolume and then the // subvolume itself. func (s *storageBtrfs) subvolsDelete(subvol string) error { // Delete subsubvols. subsubvols, err := s.getSubVolumes(subvol) if err != nil { return err } sort.Sort(sort.Reverse(sort.StringSlice(subsubvols))) for _, subsubvol := range subsubvols { s.log.Debug( "Deleting subsubvol", log.Ctx{ "subvol": subvol, "subsubvol": subsubvol}) if err := s.subvolDelete(path.Join(subvol, subsubvol)); err != nil { return err } } // Delete the subvol itself if err := s.subvolDelete(subvol); err != nil { return err } return nil } /* * subvolSnapshot creates a snapshot of "source" to "dest" * the result will be readonly if "readonly" is True. */ func (s *storageBtrfs) subvolSnapshot( source string, dest string, readonly bool) error { parentDestPath := filepath.Dir(dest) if !shared.PathExists(parentDestPath) { if err := os.MkdirAll(parentDestPath, 0700); err != nil { return err } } if shared.PathExists(dest) { if err := os.Remove(dest); err != nil { return err } } var output string var err error if readonly { output, err = shared.RunCommand( "btrfs", "subvolume", "snapshot", "-r", source, dest) } else { output, err = shared.RunCommand( "btrfs", "subvolume", "snapshot", source, dest) } if err != nil { s.log.Error( "subvolume snapshot failed", log.Ctx{"source": source, "dest": dest, "output": string(output)}, ) return fmt.Errorf( "subvolume snapshot failed, source=%s, dest=%s, output=%s", source, dest, string(output), ) } return err } func (s *storageBtrfs) subvolsSnapshot( source string, dest string, readonly bool) error { // Get a list of subvolumes of the root subsubvols, err := s.getSubVolumes(source) if err != nil { return err } sort.Sort(sort.StringSlice(subsubvols)) if len(subsubvols) > 0 && readonly { // A root with subvolumes can never be readonly, // also don't make subvolumes readonly. readonly = false s.log.Warn( "Subvolumes detected, ignoring ro flag", log.Ctx{"source": source, "dest": dest}) } // First snapshot the root err = s.subvolSnapshot(source, dest, readonly) if err != nil { return err } // Now snapshot all subvolumes of the root. for _, subsubvol := range subsubvols { // Clear the target for the subvol to use os.Remove(path.Join(dest, subsubvol)) err := s.subvolSnapshot(path.Join(source, subsubvol), path.Join(dest, subsubvol), readonly) if err != nil { return err } } return nil } /* * isSubvolume returns true if the given Path is a btrfs subvolume * else false. */ func (s *storageBtrfs) isSubvolume(subvolPath string) bool { fs := syscall.Stat_t{} err := syscall.Lstat(subvolPath, &fs) if err != nil { return false } // Check if BTRFS_FIRST_FREE_OBJECTID if fs.Ino != 256 { return false } return true } // getSubVolumes returns a list of relative subvolume paths of "path". func (s *storageBtrfs) getSubVolumes(path string) ([]string, error) { result := []string{} if !strings.HasSuffix(path, "/") { path = path + "/" } // Unprivileged users can't get to fs internals filepath.Walk(path, func(fpath string, fi os.FileInfo, err error) error { // Skip walk errors if err != nil { return nil } // Ignore the base path if strings.TrimRight(fpath, "/") == strings.TrimRight(path, "/") { return nil } // Subvolumes can only be directories if !fi.IsDir() { return nil } // Check if a btrfs subvolume if s.isSubvolume(fpath) { result = append(result, strings.TrimPrefix(fpath, path)) } return nil }) return result, nil } type btrfsMigrationSourceDriver struct { container container snapshots []container btrfsSnapshotNames []string btrfs *storageBtrfs runningSnapName string stoppedSnapName string } func (s *btrfsMigrationSourceDriver) Snapshots() []container { return s.snapshots } func (s *btrfsMigrationSourceDriver) send(conn *websocket.Conn, btrfsPath string, btrfsParent string) error { args := []string{"send"} if btrfsParent != "" { args = append(args, "-p", btrfsParent) } args = append(args, btrfsPath) cmd := exec.Command("btrfs", args...) stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } err = cmd.Start() if err != nil { return err } <-shared.WebsocketSendStream(conn, stdout, 4*1024*1024) output, err := ioutil.ReadAll(stderr) if err != nil { logger.Error("problem reading btrfs send stderr", log.Ctx{"err": err}) } err = cmd.Wait() if err != nil { logger.Error("problem with btrfs send", log.Ctx{"output": string(output)}) } return err } func (s *btrfsMigrationSourceDriver) SendWhileRunning(conn *websocket.Conn) error { if s.container.IsSnapshot() { tmpPath := containerPath(fmt.Sprintf("%s/.migration-send-%s", s.container.Name(), uuid.NewRandom().String()), true) err := os.MkdirAll(tmpPath, 0700) if err != nil { return err } defer os.RemoveAll(tmpPath) btrfsPath := fmt.Sprintf("%s/.root", tmpPath) if err := s.btrfs.subvolsSnapshot(s.container.Path(), btrfsPath, true); err != nil { return err } defer s.btrfs.subvolsDelete(btrfsPath) return s.send(conn, btrfsPath, "") } for i, snap := range s.snapshots { prev := "" if i > 0 { prev = s.snapshots[i-1].Path() } if err := s.send(conn, snap.Path(), prev); err != nil { return err } } /* We can't send running fses, so let's snapshot the fs and send * the snapshot. */ tmpPath := containerPath(fmt.Sprintf("%s/.migration-send-%s", s.container.Name(), uuid.NewRandom().String()), true) err := os.MkdirAll(tmpPath, 0700) if err != nil { return err } defer os.RemoveAll(tmpPath) s.runningSnapName = fmt.Sprintf("%s/.root", tmpPath) if err := s.btrfs.subvolsSnapshot(s.container.Path(), s.runningSnapName, true); err != nil { return err } defer s.btrfs.subvolsDelete(s.runningSnapName) btrfsParent := "" if len(s.btrfsSnapshotNames) > 0 { btrfsParent = s.btrfsSnapshotNames[len(s.btrfsSnapshotNames)-1] } return s.send(conn, s.runningSnapName, btrfsParent) } func (s *btrfsMigrationSourceDriver) SendAfterCheckpoint(conn *websocket.Conn) error { tmpPath := containerPath(fmt.Sprintf("%s/.migration-send-%s", s.container.Name(), uuid.NewRandom().String()), true) err := os.MkdirAll(tmpPath, 0700) if err != nil { return err } defer os.RemoveAll(tmpPath) s.stoppedSnapName = fmt.Sprintf("%s/.root", tmpPath) err = s.btrfs.subvolsSnapshot(s.container.Path(), s.stoppedSnapName, true) if err != nil { return err } return s.send(conn, s.stoppedSnapName, s.runningSnapName) } func (s *btrfsMigrationSourceDriver) Cleanup() { if s.stoppedSnapName != "" { s.btrfs.subvolsDelete(s.stoppedSnapName) } if s.runningSnapName != "" { s.btrfs.subvolsDelete(s.runningSnapName) } } func (s *storageBtrfs) MigrationType() MigrationFSType { if runningInUserns { return MigrationFSType_RSYNC } return MigrationFSType_BTRFS } func (s *storageBtrfs) PreservesInodes() bool { if runningInUserns { return false } else { return true } } func (s *storageBtrfs) MigrationSource(c container) (MigrationStorageSourceDriver, error) { if runningInUserns { return rsyncMigrationSource(c) } /* List all the snapshots in order of reverse creation. The idea here * is that we send the oldest to newest snapshot, hopefully saving on * xfer costs. Then, after all that, we send the container itself. */ snapshots, err := c.Snapshots() if err != nil { return nil, err } driver := &btrfsMigrationSourceDriver{ container: c, snapshots: snapshots, btrfsSnapshotNames: []string{}, btrfs: s, } for _, snap := range snapshots { btrfsPath := snap.Path() driver.btrfsSnapshotNames = append(driver.btrfsSnapshotNames, btrfsPath) } return driver, nil } func (s *storageBtrfs) MigrationSink(live bool, container container, snapshots []*Snapshot, conn *websocket.Conn, srcIdmap *idmap.IdmapSet) error { if runningInUserns { return rsyncMigrationSink(live, container, snapshots, conn, srcIdmap) } cName := container.Name() snapshotsPath := shared.VarPath(fmt.Sprintf("snapshots/%s", cName)) if !shared.PathExists(snapshotsPath) { err := os.MkdirAll(shared.VarPath(fmt.Sprintf("snapshots/%s", cName)), 0700) if err != nil { return err } } btrfsRecv := func(btrfsPath string, targetPath string, isSnapshot bool) error { args := []string{"receive", "-e", btrfsPath} cmd := exec.Command("btrfs", args...) // Remove the existing pre-created subvolume err := s.subvolsDelete(targetPath) if err != nil { logger.Errorf("Failed to delete pre-created BTRFS subvolume: %s.", btrfsPath) return err } stdin, err := cmd.StdinPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } err = cmd.Start() if err != nil { return err } <-shared.WebsocketRecvStream(stdin, conn) output, err := ioutil.ReadAll(stderr) if err != nil { logger.Debugf("problem reading btrfs receive stderr %s", err) } err = cmd.Wait() if err != nil { logger.Error("problem with btrfs receive", log.Ctx{"output": string(output)}) return err } if !isSnapshot { cPath := containerPath(fmt.Sprintf("%s/.root", cName), true) err := s.subvolsSnapshot(cPath, targetPath, false) if err != nil { logger.Error("problem with btrfs snapshot", log.Ctx{"err": err}) return err } err = s.subvolsDelete(cPath) if err != nil { logger.Error("problem with btrfs delete", log.Ctx{"err": err}) return err } } return nil } for _, snap := range snapshots { args := snapshotProtobufToContainerArgs(container.Name(), snap) s, err := containerCreateEmptySnapshot(s.s, s.storage, args) if err != nil { return err } if err := btrfsRecv(containerPath(cName, true), s.Path(), true); err != nil { return err } } /* finally, do the real container */ if err := btrfsRecv(containerPath(cName, true), container.Path(), false); err != nil { return err } if live { if err := btrfsRecv(containerPath(cName, true), container.Path(), false); err != nil { return err } } // Cleanup if ok, _ := shared.PathIsEmpty(snapshotsPath); ok { err := os.Remove(snapshotsPath) if err != nil { return err } } return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/storage.go���������������������������������������������������������������������������0000644�0610621�0607500�00000051500�13172163242�016254� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "os" "os/exec" "path/filepath" "reflect" "syscall" "github.com/gorilla/websocket" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/lxd/types" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/logging" log "gopkg.in/inconshreveable/log15.v2" ) // storageRsyncCopy copies a directory using rsync (with the --devices option). func storageRsyncCopy(source string, dest string) (string, error) { if err := os.MkdirAll(dest, 0755); err != nil { return "", err } rsyncVerbosity := "-q" if debug { rsyncVerbosity = "-vi" } output, err := shared.RunCommand( "rsync", "-a", "-HAX", "--sparse", "--devices", "--delete", "--checksum", "--numeric-ids", rsyncVerbosity, shared.AddSlash(source), dest) if err != nil { runError, ok := err.(shared.RunError) if ok { exitError, ok := runError.Err.(*exec.ExitError) if ok { waitStatus := exitError.Sys().(syscall.WaitStatus) if waitStatus.ExitStatus() == 24 { return string(output), nil } } } return string(output), err } return string(output), nil } // storageType defines the type of a storage type storageType int const ( storageTypeBtrfs storageType = iota storageTypeZfs storageTypeLvm storageTypeDir storageTypeMock ) func storageTypeToString(sType storageType) string { switch sType { case storageTypeBtrfs: return "btrfs" case storageTypeZfs: return "zfs" case storageTypeLvm: return "lvm" case storageTypeMock: return "mock" } return "dir" } type MigrationStorageSourceDriver interface { /* snapshots for this container, if any */ Snapshots() []container /* send any bits of the container/snapshots that are possible while the * container is still running. */ SendWhileRunning(conn *websocket.Conn) error /* send the final bits (e.g. a final delta snapshot for zfs, btrfs, or * do a final rsync) of the fs after the container has been * checkpointed. This will only be called when a container is actually * being live migrated. */ SendAfterCheckpoint(conn *websocket.Conn) error /* Called after either success or failure of a migration, can be used * to clean up any temporary snapshots, etc. */ Cleanup() } type storage interface { Init(config map[string]interface{}) (storage, error) GetStorageType() storageType GetStorageTypeName() string GetStorageTypeVersion() string // ContainerCreate creates an empty container (no rootfs/metadata.yaml) ContainerCreate(container container) error // ContainerCreateFromImage creates a container from a image. ContainerCreateFromImage(container container, imageFingerprint string) error ContainerCanRestore(container container, sourceContainer container) error ContainerDelete(container container) error ContainerCopy(container container, sourceContainer container) error ContainerStart(name string, path string) error ContainerStop(name string, path string) error ContainerRename(container container, newName string) error ContainerRestore(container container, sourceContainer container) error ContainerSetQuota(container container, size int64) error ContainerGetUsage(container container) (int64, error) ContainerSnapshotCreate( snapshotContainer container, sourceContainer container) error ContainerSnapshotDelete(snapshotContainer container) error ContainerSnapshotRename(snapshotContainer container, newName string) error ContainerSnapshotStart(container container) error ContainerSnapshotStop(container container) error /* for use in migrating snapshots */ ContainerSnapshotCreateEmpty(snapshotContainer container) error ImageCreate(fingerprint string) error ImageDelete(fingerprint string) error MigrationType() MigrationFSType /* does this storage backend preserve inodes when it is moved across * LXD hosts? */ PreservesInodes() bool // Get the pieces required to migrate the source. This contains a list // of the "object" (i.e. container or snapshot, depending on whether or // not it is a snapshot name) to be migrated in order, and a channel // for arguments of the specific migration command. We use a channel // here so we don't have to invoke `zfs send` or `rsync` or whatever // and keep its stdin/stdout open for each snapshot during the course // of migration, we can do it lazily. // // N.B. that the order here important: e.g. in btrfs/zfs, snapshots // which are parents of other snapshots should be sent first, to save // as much transfer as possible. However, the base container is always // sent as the first object, since that is the grandparent of every // snapshot. // // We leave sending containers which are snapshots of other containers // already present on the target instance as an exercise for the // enterprising developer. MigrationSource(container container) (MigrationStorageSourceDriver, error) MigrationSink(live bool, container container, objects []*Snapshot, conn *websocket.Conn, srcIdmap *idmap.IdmapSet) error } func newStorage(d *Daemon, sType storageType) (storage, error) { var nilmap map[string]interface{} return newStorageWithConfig(d.State(), d.Storage, sType, nilmap) } func newStorageWithConfig(s *state.State, st storage, sType storageType, config map[string]interface{}) (storage, error) { if s.OS.MockMode { return st, nil } shared := storageShared{s: s} var w storage switch sType { case storageTypeBtrfs: if st != nil && st.GetStorageType() == storageTypeBtrfs { return st, nil } btrfs := &storageBtrfs{storageShared: shared} w = &storageLogWrapper{w: btrfs} btrfs.storage = w case storageTypeZfs: if st != nil && st.GetStorageType() == storageTypeZfs { return st, nil } zfs := &storageZfs{storageShared: shared} w = &storageLogWrapper{w: zfs} zfs.storage = w case storageTypeLvm: if st != nil && st.GetStorageType() == storageTypeLvm { return st, nil } lvm := &storageLvm{storageShared: shared} w = &storageLogWrapper{w: lvm} lvm.storage = w default: if st != nil && st.GetStorageType() == storageTypeDir { return st, nil } dir := &storageDir{storageShared: shared} w = &storageLogWrapper{w: dir} dir.storage = w } return w.Init(config) } func storageForFilename(s *state.State, storage storage, filename string) (storage, error) { var filesystem string var err error config := make(map[string]interface{}) storageType := storageTypeDir if s.OS.MockMode { return newStorageWithConfig(s, storage, storageTypeMock, config) } if shared.PathExists(filename) { filesystem, err = util.FilesystemDetect(filename) if err != nil { return nil, fmt.Errorf("couldn't detect filesystem for '%s': %v", filename, err) } if filesystem == "btrfs" { if !(*storageBtrfs).isSubvolume(nil, filename) { filesystem = "" } } } if shared.PathExists(filename + ".lv") { storageType = storageTypeLvm lvPath, err := os.Readlink(filename + ".lv") if err != nil { return nil, fmt.Errorf("couldn't read link dest for '%s': %v", filename+".lv", err) } vgname := filepath.Base(filepath.Dir(lvPath)) config["vgName"] = vgname } else if shared.PathExists(filename + ".zfs") { storageType = storageTypeZfs } else if shared.PathExists(filename+".btrfs") || filesystem == "btrfs" { storageType = storageTypeBtrfs } return newStorageWithConfig(s, storage, storageType, config) } func storageForImage(s *state.State, storage storage, imgInfo *api.Image) (storage, error) { imageFilename := shared.VarPath("images", imgInfo.Fingerprint) return storageForFilename(s, storage, imageFilename) } type storageShared struct { sType storageType sTypeName string sTypeVersion string s *state.State storage storage log logger.Logger } func (ss *storageShared) initShared() error { ss.log = logging.AddContext( logger.Log, log.Ctx{"driver": fmt.Sprintf("storage/%s", ss.sTypeName)}, ) return nil } func (ss *storageShared) GetStorageType() storageType { return ss.sType } func (ss *storageShared) GetStorageTypeName() string { return ss.sTypeName } func (ss *storageShared) GetStorageTypeVersion() string { return ss.sTypeVersion } func (ss *storageShared) shiftRootfs(c container) error { dpath := c.Path() rpath := c.RootfsPath() logger.Debug("Shifting root filesystem", log.Ctx{"container": c.Name(), "rootfs": rpath}) idmapset, err := c.IdmapSet() if err != nil { return err } if idmapset == nil { return fmt.Errorf("IdmapSet of container '%s' is nil", c.Name()) } err = idmapset.ShiftRootfs(rpath) if err != nil { logger.Debugf("Shift of rootfs %s failed: %s", rpath, err) return err } /* Set an acl so the container root can descend the container dir */ // TODO: i changed this so it calls ss.setUnprivUserAcl, which does // the acl change only if the container is not privileged, think thats right. return ss.setUnprivUserAcl(c, dpath) } func (ss *storageShared) setUnprivUserAcl(c container, destPath string) error { idmapset, err := c.IdmapSet() if err != nil { return err } // Skip for privileged containers if idmapset == nil { return nil } // Make sure the map is valid. Skip if container uid 0 == host uid 0 uid, _ := idmapset.ShiftIntoNs(0, 0) switch uid { case -1: return fmt.Errorf("Container doesn't have a uid 0 in its map") case 0: return nil } // Attempt to set a POSIX ACL first. Fallback to chmod if the fs doesn't support it. acl := fmt.Sprintf("%d:rx", uid) _, err = shared.RunCommand("setfacl", "-m", acl, destPath) if err != nil { _, err := shared.RunCommand("chmod", "+x", destPath) if err != nil { return fmt.Errorf("Failed to chmod the container path.") } } return nil } type storageLogWrapper struct { w storage log logger.Logger } func (lw *storageLogWrapper) Init(config map[string]interface{}) (storage, error) { _, err := lw.w.Init(config) lw.log = logging.AddContext( logger.Log, log.Ctx{"driver": fmt.Sprintf("storage/%s", lw.w.GetStorageTypeName())}, ) lw.log.Debug("Init") return lw, err } func (lw *storageLogWrapper) GetStorageType() storageType { return lw.w.GetStorageType() } func (lw *storageLogWrapper) GetStorageTypeName() string { return lw.w.GetStorageTypeName() } func (lw *storageLogWrapper) GetStorageTypeVersion() string { return lw.w.GetStorageTypeVersion() } func (lw *storageLogWrapper) ContainerCreate(container container) error { lw.log.Debug( "ContainerCreate", log.Ctx{ "name": container.Name(), "isPrivileged": container.IsPrivileged()}) return lw.w.ContainerCreate(container) } func (lw *storageLogWrapper) ContainerCreateFromImage( container container, imageFingerprint string) error { lw.log.Debug( "ContainerCreateFromImage", log.Ctx{ "imageFingerprint": imageFingerprint, "name": container.Name(), "isPrivileged": container.IsPrivileged()}) return lw.w.ContainerCreateFromImage(container, imageFingerprint) } func (lw *storageLogWrapper) ContainerCanRestore(container container, sourceContainer container) error { lw.log.Debug("ContainerCanRestore", log.Ctx{"container": container.Name()}) return lw.w.ContainerCanRestore(container, sourceContainer) } func (lw *storageLogWrapper) ContainerDelete(container container) error { lw.log.Debug("ContainerDelete", log.Ctx{"container": container.Name()}) return lw.w.ContainerDelete(container) } func (lw *storageLogWrapper) ContainerCopy( container container, sourceContainer container) error { lw.log.Debug( "ContainerCopy", log.Ctx{ "container": container.Name(), "source": sourceContainer.Name()}) return lw.w.ContainerCopy(container, sourceContainer) } func (lw *storageLogWrapper) ContainerStart(name string, path string) error { lw.log.Debug("ContainerStart", log.Ctx{"container": name}) return lw.w.ContainerStart(name, path) } func (lw *storageLogWrapper) ContainerStop(name string, path string) error { lw.log.Debug("ContainerStop", log.Ctx{"container": name}) return lw.w.ContainerStop(name, path) } func (lw *storageLogWrapper) ContainerRename( container container, newName string) error { lw.log.Debug( "ContainerRename", log.Ctx{ "container": container.Name(), "newName": newName}) return lw.w.ContainerRename(container, newName) } func (lw *storageLogWrapper) ContainerRestore( container container, sourceContainer container) error { lw.log.Debug( "ContainerRestore", log.Ctx{ "container": container.Name(), "source": sourceContainer.Name()}) return lw.w.ContainerRestore(container, sourceContainer) } func (lw *storageLogWrapper) ContainerSetQuota( container container, size int64) error { lw.log.Debug( "ContainerSetQuota", log.Ctx{ "container": container.Name(), "size": size}) return lw.w.ContainerSetQuota(container, size) } func (lw *storageLogWrapper) ContainerGetUsage( container container) (int64, error) { lw.log.Debug( "ContainerGetUsage", log.Ctx{ "container": container.Name()}) return lw.w.ContainerGetUsage(container) } func (lw *storageLogWrapper) ContainerSnapshotCreate( snapshotContainer container, sourceContainer container) error { lw.log.Debug("ContainerSnapshotCreate", log.Ctx{ "snapshotContainer": snapshotContainer.Name(), "sourceContainer": sourceContainer.Name()}) return lw.w.ContainerSnapshotCreate(snapshotContainer, sourceContainer) } func (lw *storageLogWrapper) ContainerSnapshotCreateEmpty(snapshotContainer container) error { lw.log.Debug("ContainerSnapshotCreateEmpty", log.Ctx{ "snapshotContainer": snapshotContainer.Name()}) return lw.w.ContainerSnapshotCreateEmpty(snapshotContainer) } func (lw *storageLogWrapper) ContainerSnapshotDelete( snapshotContainer container) error { lw.log.Debug("ContainerSnapshotDelete", log.Ctx{"snapshotContainer": snapshotContainer.Name()}) return lw.w.ContainerSnapshotDelete(snapshotContainer) } func (lw *storageLogWrapper) ContainerSnapshotRename( snapshotContainer container, newName string) error { lw.log.Debug("ContainerSnapshotRename", log.Ctx{ "snapshotContainer": snapshotContainer.Name(), "newName": newName}) return lw.w.ContainerSnapshotRename(snapshotContainer, newName) } func (lw *storageLogWrapper) ContainerSnapshotStart(container container) error { lw.log.Debug("ContainerSnapshotStart", log.Ctx{"container": container.Name()}) return lw.w.ContainerSnapshotStart(container) } func (lw *storageLogWrapper) ContainerSnapshotStop(container container) error { lw.log.Debug("ContainerSnapshotStop", log.Ctx{"container": container.Name()}) return lw.w.ContainerSnapshotStop(container) } func (lw *storageLogWrapper) ImageCreate(fingerprint string) error { lw.log.Debug( "ImageCreate", log.Ctx{"fingerprint": fingerprint}) return lw.w.ImageCreate(fingerprint) } func (lw *storageLogWrapper) ImageDelete(fingerprint string) error { lw.log.Debug("ImageDelete", log.Ctx{"fingerprint": fingerprint}) return lw.w.ImageDelete(fingerprint) } func (lw *storageLogWrapper) MigrationType() MigrationFSType { return lw.w.MigrationType() } func (lw *storageLogWrapper) PreservesInodes() bool { return lw.w.PreservesInodes() } func (lw *storageLogWrapper) MigrationSource(container container) (MigrationStorageSourceDriver, error) { lw.log.Debug("MigrationSource", log.Ctx{"container": container.Name()}) return lw.w.MigrationSource(container) } func (lw *storageLogWrapper) MigrationSink(live bool, container container, objects []*Snapshot, conn *websocket.Conn, srcIdmap *idmap.IdmapSet) error { objNames := []string{} for _, obj := range objects { objNames = append(objNames, obj.GetName()) } lw.log.Debug("MigrationSink", log.Ctx{ "live": live, "container": container.Name(), "objects": objNames, "srcIdmap": *srcIdmap, }) return lw.w.MigrationSink(live, container, objects, conn, srcIdmap) } func ShiftIfNecessary(container container, srcIdmap *idmap.IdmapSet) error { dstIdmap, err := container.IdmapSet() if err != nil { return err } if dstIdmap == nil { dstIdmap = new(idmap.IdmapSet) } if !reflect.DeepEqual(srcIdmap, dstIdmap) { var jsonIdmap string if srcIdmap != nil { idmapBytes, err := json.Marshal(srcIdmap.Idmap) if err != nil { return err } jsonIdmap = string(idmapBytes) } else { jsonIdmap = "[]" } err := container.ConfigKeySet("volatile.last_state.idmap", jsonIdmap) if err != nil { return err } } return nil } type rsyncStorageSourceDriver struct { container container snapshots []container } func (s rsyncStorageSourceDriver) Snapshots() []container { return s.snapshots } func (s rsyncStorageSourceDriver) SendWhileRunning(conn *websocket.Conn) error { ctName, _, _ := containerGetParentAndSnapshotName(s.container.Name()) for _, send := range s.snapshots { if err := send.StorageStart(); err != nil { return err } defer send.StorageStop() path := send.Path() if err := RsyncSend(ctName, shared.AddSlash(path), conn); err != nil { return err } } return RsyncSend(ctName, shared.AddSlash(s.container.Path()), conn) } func (s rsyncStorageSourceDriver) SendAfterCheckpoint(conn *websocket.Conn) error { ctName, _, _ := containerGetParentAndSnapshotName(s.container.Name()) /* resync anything that changed between our first send and the checkpoint */ return RsyncSend(ctName, shared.AddSlash(s.container.Path()), conn) } func (s rsyncStorageSourceDriver) Cleanup() { /* no-op */ } func rsyncMigrationSource(container container) (MigrationStorageSourceDriver, error) { snapshots, err := container.Snapshots() if err != nil { return nil, err } return rsyncStorageSourceDriver{container, snapshots}, nil } func snapshotProtobufToContainerArgs(containerName string, snap *Snapshot) db.ContainerArgs { config := map[string]string{} for _, ent := range snap.LocalConfig { config[ent.GetKey()] = ent.GetValue() } devices := types.Devices{} for _, ent := range snap.LocalDevices { props := map[string]string{} for _, prop := range ent.Config { props[prop.GetKey()] = prop.GetValue() } devices[ent.GetName()] = props } name := containerName + shared.SnapshotDelimiter + snap.GetName() return db.ContainerArgs{ Name: name, Ctype: db.CTypeSnapshot, Config: config, Profiles: snap.Profiles, Ephemeral: snap.GetEphemeral(), Devices: devices, Architecture: int(snap.GetArchitecture()), Stateful: snap.GetStateful(), } } func rsyncMigrationSink(live bool, container container, snapshots []*Snapshot, conn *websocket.Conn, srcIdmap *idmap.IdmapSet) error { isDirBackend := container.Storage().GetStorageType() == storageTypeDir if isDirBackend { if len(snapshots) > 0 { err := os.MkdirAll(shared.VarPath(fmt.Sprintf("snapshots/%s", container.Name())), 0700) if err != nil { return err } } for _, snap := range snapshots { args := snapshotProtobufToContainerArgs(container.Name(), snap) s, err := containerCreateEmptySnapshot(container.StateObject(), container.Storage(), args) if err != nil { return err } if err := RsyncRecv(shared.AddSlash(s.Path()), conn); err != nil { return err } if err := ShiftIfNecessary(container, srcIdmap); err != nil { return err } } if err := RsyncRecv(shared.AddSlash(container.Path()), conn); err != nil { return err } } else { if err := container.StorageStart(); err != nil { return err } defer container.StorageStop() for _, snap := range snapshots { if err := RsyncRecv(shared.AddSlash(container.Path()), conn); err != nil { return err } if err := ShiftIfNecessary(container, srcIdmap); err != nil { return err } args := snapshotProtobufToContainerArgs(container.Name(), snap) _, err := containerCreateAsSnapshot(container.StateObject(), container.Storage(), args, container) if err != nil { return err } } if err := RsyncRecv(shared.AddSlash(container.Path()), conn); err != nil { return err } } if live { /* now receive the final sync */ if err := RsyncRecv(shared.AddSlash(container.Path()), conn); err != nil { return err } } if err := ShiftIfNecessary(container, srcIdmap); err != nil { return err } return nil } func SetupStorageDriver(d *Daemon) error { var err error lvmVgName := daemonConfig["storage.lvm_vg_name"].Get() zfsPoolName := daemonConfig["storage.zfs_pool_name"].Get() if lvmVgName != "" { d.Storage, err = newStorage(d, storageTypeLvm) if err != nil { logger.Errorf("Could not initialize storage type LVM: %s - falling back to dir", err) } else { return nil } } else if zfsPoolName != "" { d.Storage, err = newStorage(d, storageTypeZfs) if err != nil { logger.Errorf("Could not initialize storage type ZFS: %s - falling back to dir", err) } else { return nil } } else if d.os.BackingFS == "btrfs" { d.Storage, err = newStorage(d, storageTypeBtrfs) if err != nil { logger.Errorf("Could not initialize storage type btrfs: %s - falling back to dir", err) } else { return nil } } d.Storage, err = newStorage(d, storageTypeDir) return err } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/state/�������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015400� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/state/state.go�����������������������������������������������������������������������0000644�0610621�0607500�00000001010�13172163242�017037� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package state import ( "database/sql" "github.com/lxc/lxd/lxd/sys" ) // State is a gateway to the two main stateful components of LXD, the database // and the operating system. It's typically used by model entities such as // containers, volumes, etc. in order to perform changes. type State struct { DB *sql.DB OS *sys.OS } // NewState returns a new State object with the given database and operating // system components. func NewState(db *sql.DB, os *sys.OS) *State { return &State{ DB: db, OS: os, } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/seccomp.go���������������������������������������������������������������������������0000644�0610621�0607500�00000002456�13172163242�016247� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "io/ioutil" "os" "path" "github.com/lxc/lxd/shared" ) const DEFAULT_SECCOMP_POLICY = `2 blacklist reject_force_umount # comment this to allow umount -f; not recommended [all] kexec_load errno 1 open_by_handle_at errno 1 init_module errno 1 finit_module errno 1 delete_module errno 1 ` var seccompPath = shared.VarPath("security", "seccomp") func SeccompProfilePath(c container) string { return path.Join(seccompPath, c.Name()) } func getSeccompProfileContent(c container) string { /* for now there are no seccomp knobs. */ return DEFAULT_SECCOMP_POLICY } func SeccompCreateProfile(c container) error { /* Unlike apparmor, there is no way to "cache" profiles, and profiles * are automatically unloaded when a task dies. Thus, we don't need to * unload them when a container stops, and we don't have to worry about * the mtime on the file for any compiler purpose, so let's just write * out the profile. */ profile := getSeccompProfileContent(c) if err := os.MkdirAll(seccompPath, 0700); err != nil { return err } return ioutil.WriteFile(SeccompProfilePath(c), []byte(profile), 0600) } func SeccompDeleteProfile(c container) { /* similar to AppArmor, if we've never started this container, the * delete can fail and that's ok. */ os.Remove(SeccompProfilePath(c)) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/schema.go����������������������������������������������������������������������������0000644�0610621�0607500�00000000765�13172163242�016057� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build never // // We use the tag 'never' because this utility shouldn't normally be built, // unless you're running the 'update-schema' target of the Makefile. package main import ( "log" "github.com/lxc/lxd/lxd/db" ) // Entry point for the "schema" development utility, which updates the content // of lxd/db/schema.go according to the current schema updates declared in // updates.go in the same package. func main() { err := db.UpdateSchemaDotGo() if err != nil { log.Fatal(err) } } �����������lxd-2.0.11/lxd/rsync.go�����������������������������������������������������������������������������0000644�0610621�0607500�00000007773�13172163242�015763� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io" "io/ioutil" "net" "os/exec" "github.com/gorilla/websocket" "github.com/pborman/uuid" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" ) func rsyncSendSetup(name string, path string) (*exec.Cmd, net.Conn, io.ReadCloser, error) { /* * The way rsync works, it invokes a subprocess that does the actual * talking (given to it by a -E argument). Since there isn't an easy * way for us to capture this process' stdin/stdout, we just use netcat * and write to/from a unix socket. * * In principle we don't need this socket. It seems to me that some * clever invocation of rsync --server --sender and usage of that * process' stdin/stdout could work around the need for this socket, * but I couldn't get it to work. Another option would be to look at * the spawned process' first child and read/write from its * stdin/stdout, but that also seemed messy. In any case, this seems to * work just fine. */ auds := fmt.Sprintf("@lxd/%s", uuid.NewRandom().String()) // We simply copy a part of the uuid if it's longer than the allowed // maximum. That should be safe enough for our purposes. if len(auds) > shared.ABSTRACT_UNIX_SOCK_LEN-1 { auds = auds[:shared.ABSTRACT_UNIX_SOCK_LEN-1] } l, err := net.Listen("unix", auds) if err != nil { return nil, nil, nil, err } /* * Here, the path /tmp/foo is ignored. Since we specify localhost, * rsync thinks we are syncing to a remote host (in this case, the * other end of the lxd websocket), and so the path specified on the * --server instance of rsync takes precedence. * * Additionally, we use sh -c instead of just calling nc directly * because rsync passes a whole bunch of arguments to the wrapper * command (i.e. the command to run on --server). However, we're * hardcoding that at the other end, so we can just ignore it. */ rsyncCmd := fmt.Sprintf("sh -c \"%s netcat %s %s\"", execPath, auds, name) cmd := exec.Command( "rsync", "-arvP", "--devices", "--numeric-ids", "--partial", "--sparse", path, "localhost:/tmp/foo", "-e", rsyncCmd) stderr, err := cmd.StderrPipe() if err != nil { return nil, nil, nil, err } if err := cmd.Start(); err != nil { return nil, nil, nil, err } conn, err := l.Accept() if err != nil { cmd.Process.Kill() cmd.Wait() return nil, nil, nil, err } l.Close() return cmd, conn, stderr, nil } // RsyncSend sets up the sending half of an rsync, to recursively send the // directory pointed to by path over the websocket. func RsyncSend(name string, path string, conn *websocket.Conn) error { cmd, dataSocket, stderr, err := rsyncSendSetup(name, path) if err != nil { return err } if dataSocket != nil { defer dataSocket.Close() } readDone, writeDone := shared.WebsocketMirror(conn, dataSocket, dataSocket, nil, nil) output, err := ioutil.ReadAll(stderr) if err != nil { cmd.Process.Kill() cmd.Wait() return err } err = cmd.Wait() if err != nil { logger.Errorf("Rsync send failed: %s: %s: %s", path, err, string(output)) } <-readDone <-writeDone return err } // RsyncRecv sets up the receiving half of the websocket to rsync (the other // half set up by RsyncSend), putting the contents in the directory specified // by path. func RsyncRecv(path string, conn *websocket.Conn) error { cmd := exec.Command("rsync", "--server", "-vlogDtpre.iLsfx", "--numeric-ids", "--devices", "--partial", "--sparse", ".", path) stdin, err := cmd.StdinPipe() if err != nil { return err } stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } readDone, writeDone := shared.WebsocketMirror(conn, stdin, stdout, nil, nil) output, err := ioutil.ReadAll(stderr) if err != nil { cmd.Process.Kill() cmd.Wait() return err } err = cmd.Wait() if err != nil { logger.Errorf("Rsync receive failed: %s: %s: %s", path, err, string(output)) } <-readDone <-writeDone return err } �����lxd-2.0.11/lxd/response.go��������������������������������������������������������������������������0000644�0610621�0607500�00000014331�13172163242�016447� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "bytes" "database/sql" "encoding/json" "fmt" "io" "mime/multipart" "net/http" "os" "time" "github.com/mattn/go-sqlite3" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" ) type Response interface { Render(w http.ResponseWriter) error String() string } // Sync response type syncResponse struct { success bool metadata interface{} location string } func (r *syncResponse) Render(w http.ResponseWriter) error { status := api.Success if !r.success { status = api.Failure } if r.location != "" { w.Header().Set("Location", r.location) w.WriteHeader(201) } resp := api.ResponseRaw{ Response: api.Response{ Type: api.SyncResponse, Status: status.String(), StatusCode: int(status)}, Metadata: r.metadata, } return util.WriteJSON(w, resp, debug) } func (r *syncResponse) String() string { if r.success { return "success" } return "failure" } func SyncResponse(success bool, metadata interface{}) Response { return &syncResponse{success: success, metadata: metadata} } func SyncResponseLocation(success bool, metadata interface{}, location string) Response { return &syncResponse{success: success, metadata: metadata, location: location} } var EmptySyncResponse = &syncResponse{success: true, metadata: make(map[string]interface{})} // File transfer response type fileResponseEntry struct { identifier string path string filename string buffer []byte /* either a path or a buffer must be provided */ } type fileResponse struct { req *http.Request files []fileResponseEntry headers map[string]string removeAfterServe bool } func (r *fileResponse) Render(w http.ResponseWriter) error { if r.headers != nil { for k, v := range r.headers { w.Header().Set(k, v) } } // No file, well, it's easy then if len(r.files) == 0 { return nil } // For a single file, return it inline if len(r.files) == 1 { var rs io.ReadSeeker var mt time.Time var sz int64 if r.files[0].path == "" { rs = bytes.NewReader(r.files[0].buffer) mt = time.Now() sz = int64(len(r.files[0].buffer)) } else { f, err := os.Open(r.files[0].path) if err != nil { return err } defer f.Close() fi, err := f.Stat() if err != nil { return err } mt = fi.ModTime() sz = fi.Size() rs = f } w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Length", fmt.Sprintf("%d", sz)) w.Header().Set("Content-Disposition", fmt.Sprintf("inline;filename=%s", r.files[0].filename)) http.ServeContent(w, r.req, r.files[0].filename, mt, rs) if r.files[0].path != "" && r.removeAfterServe { err := os.Remove(r.files[0].path) if err != nil { return err } } return nil } // Now the complex multipart answer body := &bytes.Buffer{} mw := multipart.NewWriter(body) for _, entry := range r.files { var rd io.Reader if entry.path != "" { fd, err := os.Open(entry.path) if err != nil { return err } defer fd.Close() rd = fd } else { rd = bytes.NewReader(entry.buffer) } fw, err := mw.CreateFormFile(entry.identifier, entry.filename) if err != nil { return err } _, err = io.Copy(fw, rd) if err != nil { return err } } mw.Close() w.Header().Set("Content-Type", mw.FormDataContentType()) w.Header().Set("Content-Length", fmt.Sprintf("%d", body.Len())) _, err := io.Copy(w, body) return err } func (r *fileResponse) String() string { return fmt.Sprintf("%d files", len(r.files)) } func FileResponse(r *http.Request, files []fileResponseEntry, headers map[string]string, removeAfterServe bool) Response { return &fileResponse{r, files, headers, removeAfterServe} } // Operation response type operationResponse struct { op *operation } func (r *operationResponse) Render(w http.ResponseWriter) error { _, err := r.op.Run() if err != nil { return err } url, md, err := r.op.Render() if err != nil { return err } body := api.ResponseRaw{ Response: api.Response{ Type: api.AsyncResponse, Status: api.OperationCreated.String(), StatusCode: int(api.OperationCreated), Operation: url, }, Metadata: md, } w.Header().Set("Location", url) w.WriteHeader(202) return util.WriteJSON(w, body, debug) } func (r *operationResponse) String() string { _, md, err := r.op.Render() if err != nil { return fmt.Sprintf("error: %s", err) } return md.ID } func OperationResponse(op *operation) Response { return &operationResponse{op} } // Error response type errorResponse struct { code int msg string } func (r *errorResponse) String() string { return r.msg } func (r *errorResponse) Render(w http.ResponseWriter) error { var output io.Writer buf := &bytes.Buffer{} output = buf var captured *bytes.Buffer if debug { captured = &bytes.Buffer{} output = io.MultiWriter(buf, captured) } err := json.NewEncoder(output).Encode(shared.Jmap{"type": api.ErrorResponse, "error": r.msg, "error_code": r.code}) if err != nil { return err } if debug { shared.DebugJson(captured) } w.Header().Set("Content-Type", "application/json") w.Header().Set("X-Content-Type-Options", "nosniff") w.WriteHeader(r.code) fmt.Fprintln(w, buf.String()) return nil } /* Some standard responses */ var NotImplemented = &errorResponse{http.StatusNotImplemented, "not implemented"} var NotFound = &errorResponse{http.StatusNotFound, "not found"} var Forbidden = &errorResponse{http.StatusForbidden, "not authorized"} var Conflict = &errorResponse{http.StatusConflict, "already exists"} func BadRequest(err error) Response { return &errorResponse{http.StatusBadRequest, err.Error()} } func InternalError(err error) Response { return &errorResponse{http.StatusInternalServerError, err.Error()} } /* * SmartError returns the right error message based on err. */ func SmartError(err error) Response { switch err { case nil: return EmptySyncResponse case os.ErrNotExist: return NotFound case sql.ErrNoRows: return NotFound case db.NoSuchObjectError: return NotFound case os.ErrPermission: return Forbidden case db.DbErrAlreadyDefined: return Conflict case sqlite3.ErrConstraintUnique: return Conflict default: return InternalError(err) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/profiles_utils.go��������������������������������������������������������������������0000644�0610621�0607500�00000004113�13172163242�017651� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "reflect" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared/api" ) func doProfileUpdate(d *Daemon, name string, id int64, profile *api.Profile, req api.ProfilePut) Response { // Sanity checks err := containerValidConfig(d.os, req.Config, true, false) if err != nil { return BadRequest(err) } err = containerValidDevices(req.Devices, true, false) if err != nil { return BadRequest(err) } containers := getContainersWithProfile(d.State(), d.Storage, name) // Update the database tx, err := db.Begin(d.db) if err != nil { return SmartError(err) } if profile.Description != req.Description { err = db.ProfileDescriptionUpdate(tx, id, req.Description) if err != nil { tx.Rollback() return SmartError(err) } } // Optimize for description-only changes if reflect.DeepEqual(profile.Config, req.Config) && reflect.DeepEqual(profile.Devices, req.Devices) { err = db.TxCommit(tx) if err != nil { return SmartError(err) } return EmptySyncResponse } err = db.ProfileConfigClear(tx, id) if err != nil { tx.Rollback() return SmartError(err) } err = db.ProfileConfigAdd(tx, id, req.Config) if err != nil { tx.Rollback() return SmartError(err) } err = db.DevicesAdd(tx, "profile", id, req.Devices) if err != nil { tx.Rollback() return SmartError(err) } err = db.TxCommit(tx) if err != nil { return SmartError(err) } // Update all the containers using the profile. Must be done after db.TxCommit due to DB lock. failures := map[string]error{} for _, c := range containers { err = c.Update(db.ContainerArgs{ Architecture: c.Architecture(), Ephemeral: c.IsEphemeral(), Config: c.LocalConfig(), Devices: c.LocalDevices(), Profiles: c.Profiles()}, true) if err != nil { failures[c.Name()] = err } } if len(failures) != 0 { msg := "The following containers failed to update (profile change still saved):\n" for cname, err := range failures { msg += fmt.Sprintf(" - %s: %s\n", cname, err) } return SmartError(fmt.Errorf("%s", msg)) } return EmptySyncResponse } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/profiles_test.go���������������������������������������������������������������������0000644�0610621�0607500�00000003276�13172163242�017501� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "testing" dbapi "github.com/lxc/lxd/lxd/db" ) func Test_removing_a_profile_deletes_associated_configuration_entries(t *testing.T) { var db *sql.DB var err error d := NewDaemon() err = initializeDbObject(d, ":memory:") db = d.db // Insert a container and a related profile. Dont't forget that the profile // we insert is profile ID 2 (there is a default profile already). statements := ` INSERT INTO containers (name, architecture, type) VALUES ('thename', 1, 1); INSERT INTO profiles (name) VALUES ('theprofile'); INSERT INTO containers_profiles (container_id, profile_id) VALUES (1, 2); INSERT INTO profiles_devices (name, profile_id) VALUES ('somename', 2); INSERT INTO profiles_config (key, value, profile_id) VALUES ('thekey', 'thevalue', 2); INSERT INTO profiles_devices_config (profile_device_id, key, value) VALUES (1, 'something', 'boring');` _, err = db.Exec(statements) if err != nil { t.Fatal(err) } // Delete the profile we just created with dbapi.ProfileDelete err = dbapi.ProfileDelete(db, "theprofile") if err != nil { t.Fatal(err) } // Make sure there are 0 profiles_devices entries left. devices, err := dbapi.Devices(d.db, "theprofile", true) if err != nil { t.Fatal(err) } if len(devices) != 0 { t.Errorf("Deleting a profile didn't delete the related profiles_devices! There are %d left", len(devices)) } // Make sure there are 0 profiles_config entries left. config, err := dbapi.ProfileConfig(d.db, "theprofile") if err == nil { t.Fatal("found the profile!") } if len(config) != 0 { t.Errorf("Deleting a profile didn't delete the related profiles_config! There are %d left", len(config)) } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/profiles.go��������������������������������������������������������������������������0000644�0610621�0607500�00000012114�13172163242�016431� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "net/http" "strings" "github.com/gorilla/mux" _ "github.com/mattn/go-sqlite3" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/version" log "gopkg.in/inconshreveable/log15.v2" ) /* This is used for both profiles post and profile put */ func profilesGet(d *Daemon, r *http.Request) Response { results, err := db.Profiles(d.db) if err != nil { return SmartError(err) } recursion := util.IsRecursionRequest(r) resultString := make([]string, len(results)) resultMap := make([]*api.Profile, len(results)) i := 0 for _, name := range results { if !recursion { url := fmt.Sprintf("/%s/profiles/%s", version.APIVersion, name) resultString[i] = url } else { profile, err := doProfileGet(d.State(), name) if err != nil { logger.Error("Failed to get profile", log.Ctx{"profile": name}) continue } resultMap[i] = profile } i++ } if !recursion { return SyncResponse(true, resultString) } return SyncResponse(true, resultMap) } func profilesPost(d *Daemon, r *http.Request) Response { req := api.ProfilesPost{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } // Sanity checks if req.Name == "" { return BadRequest(fmt.Errorf("No name provided")) } _, profile, _ := db.ProfileGet(d.db, req.Name) if profile != nil { return BadRequest(fmt.Errorf("The profile already exists")) } if strings.Contains(req.Name, "/") { return BadRequest(fmt.Errorf("Profile names may not contain slashes")) } if shared.StringInSlice(req.Name, []string{".", ".."}) { return BadRequest(fmt.Errorf("Invalid profile name '%s'", req.Name)) } err := containerValidConfig(d.os, req.Config, true, false) if err != nil { return BadRequest(err) } err = containerValidDevices(req.Devices, true, false) if err != nil { return BadRequest(err) } // Update DB entry _, err = db.ProfileCreate(d.db, req.Name, req.Description, req.Config, req.Devices) if err != nil { return SmartError( fmt.Errorf("Error inserting %s into database: %s", req.Name, err)) } return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/profiles/%s", version.APIVersion, req.Name)) } var profilesCmd = Command{ name: "profiles", get: profilesGet, post: profilesPost} func doProfileGet(s *state.State, name string) (*api.Profile, error) { _, profile, err := db.ProfileGet(s.DB, name) return profile, err } func profileGet(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] resp, err := doProfileGet(d.State(), name) if err != nil { return SmartError(err) } return SyncResponse(true, resp) } func getContainersWithProfile(s *state.State, storage storage, profile string) []container { results := []container{} output, err := db.ProfileContainersGet(s.DB, profile) if err != nil { return results } for _, name := range output { c, err := containerLoadByName(s, storage, name) if err != nil { logger.Error("Failed opening container", log.Ctx{"container": name}) continue } results = append(results, c) } return results } func profilePut(d *Daemon, r *http.Request) Response { // Get the profile name := mux.Vars(r)["name"] id, profile, err := db.ProfileGet(d.db, name) if err != nil { return SmartError(fmt.Errorf("Failed to retrieve profile='%s'", name)) } req := api.ProfilePut{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } return doProfileUpdate(d, name, id, profile, req) } // The handler for the post operation. func profilePost(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] req := api.ProfilePost{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } // Sanity checks if req.Name == "" { return BadRequest(fmt.Errorf("No name provided")) } // Check that the name isn't already in use id, _, _ := db.ProfileGet(d.db, req.Name) if id > 0 { return Conflict } if strings.Contains(req.Name, "/") { return BadRequest(fmt.Errorf("Profile names may not contain slashes")) } if shared.StringInSlice(req.Name, []string{".", ".."}) { return BadRequest(fmt.Errorf("Invalid profile name '%s'", req.Name)) } err := db.ProfileUpdate(d.db, name, req.Name) if err != nil { return SmartError(err) } return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/profiles/%s", version.APIVersion, req.Name)) } // The handler for the delete operation. func profileDelete(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] _, err := doProfileGet(d.State(), name) if err != nil { return SmartError(err) } clist := getContainersWithProfile(d.State(), d.Storage, name) if len(clist) != 0 { return BadRequest(fmt.Errorf("Profile is currently in use")) } err = db.ProfileDelete(d.db, name) if err != nil { return SmartError(err) } return EmptySyncResponse } var profileCmd = Command{name: "profiles/{name}", get: profileGet, put: profilePut, delete: profileDelete, post: profilePost} ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/patches.go���������������������������������������������������������������������������0000644�0610621�0607500�00000021147�13172163242�016243� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "syscall" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) /* Patches are one-time actions that are sometimes needed to update existing container configuration or move things around on the filesystem. Those patches are applied at startup time after the database schema has been fully updated. Patches can therefore assume a working database. At the time the patches are applied, the containers aren't started yet and the daemon isn't listening to requests. DO NOT use this mechanism for database update. Schema updates must be done through the separate schema update mechanism. Only append to the patches list, never remove entries and never re-order them. */ var patches = []patch{ {name: "invalid_profile_names", run: patchInvalidProfileNames}, {name: "leftover_profile_config", run: patchLeftoverProfileConfig}, {name: "fix_uploaded_at", run: patchFixUploadedAt}, } type patch struct { name string run func(name string, d *Daemon) error } func (p *patch) apply(d *Daemon) error { logger.Debugf("Applying patch: %s", p.name) err := p.run(p.name, d) if err != nil { return err } err = db.PatchesMarkApplied(d.db, p.name) if err != nil { return err } return nil } // Return the names of all available patches. func patchesGetNames() []string { names := make([]string, len(patches)) for i, patch := range patches { names[i] = patch.name } return names } func patchesApplyAll(d *Daemon) error { appliedPatches, err := db.Patches(d.db) if err != nil { return err } for _, patch := range patches { if shared.StringInSlice(patch.name, appliedPatches) { continue } err := patch.apply(d) if err != nil { return err } } return nil } // Patches begin here func patchLeftoverProfileConfig(name string, d *Daemon) error { stmt := ` DELETE FROM profiles_config WHERE profile_id NOT IN (SELECT id FROM profiles); DELETE FROM profiles_devices WHERE profile_id NOT IN (SELECT id FROM profiles); DELETE FROM profiles_devices_config WHERE profile_device_id NOT IN (SELECT id FROM profiles_devices); ` _, err := d.db.Exec(stmt) if err != nil { return err } return nil } func patchInvalidProfileNames(name string, d *Daemon) error { profiles, err := db.Profiles(d.db) if err != nil { return err } for _, profile := range profiles { if strings.Contains(profile, "/") || shared.StringInSlice(profile, []string{".", ".."}) { logger.Info("Removing unreachable profile (invalid name)", log.Ctx{"name": profile}) err := db.ProfileDelete(d.db, profile) if err != nil { return err } } } return nil } func patchFixUploadedAt(name string, d *Daemon) error { images, err := db.ImagesGet(d.db, false) if err != nil { return err } for _, fingerprint := range images { id, image, err := db.ImageGet(d.db, fingerprint, false, true) if err != nil { return err } _, err = db.Exec(d.db, "UPDATE images SET upload_date=? WHERE id=?", image.UploadedAt, id) if err != nil { return err } } return nil } // Patches end here // Here are a couple of legacy patches that were originally in // db_updates.go and were written before the new patch mechanism // above. To preserve exactly their semantics we treat them // differently and still apply them during the database upgrade. In // principle they could be converted to regular patches like the ones // above, however that seems an unnecessary risk at this moment. See // also PR #3322. // // NOTE: don't add any legacy patch here, instead use the patches // mechanism above. var legacyPatches = map[int](func(d *Daemon) error){ 11: patchUpdateFromV10, 12: patchUpdateFromV11, 16: patchUpdateFromV15, 30: patchUpdateFromV29, 31: patchUpdateFromV30, } var legacyPatchesNeedingDB = []int{11, 12, 16} // Legacy patches doing DB work func patchUpdateFromV10(d *Daemon) error { if shared.PathExists(shared.VarPath("lxc")) { err := os.Rename(shared.VarPath("lxc"), shared.VarPath("containers")) if err != nil { return err } logger.Debugf("Restarting all the containers following directory rename") s := d.State() containersShutdown(s, d.Storage) containersRestart(s, d.Storage) } return nil } func patchUpdateFromV11(d *Daemon) error { cNames, err := db.ContainersList(d.db, db.CTypeSnapshot) if err != nil { return err } errors := 0 for _, cName := range cNames { snapParentName, snapOnlyName, _ := containerGetParentAndSnapshotName(cName) oldPath := shared.VarPath("containers", snapParentName, "snapshots", snapOnlyName) newPath := shared.VarPath("snapshots", snapParentName, snapOnlyName) if shared.PathExists(oldPath) && !shared.PathExists(newPath) { logger.Info( "Moving snapshot", log.Ctx{ "snapshot": cName, "oldPath": oldPath, "newPath": newPath}) // Rsync // containers/<container>/snapshots/<snap0> // to // snapshots/<container>/<snap0> output, err := storageRsyncCopy(oldPath, newPath) if err != nil { logger.Error( "Failed rsync snapshot", log.Ctx{ "snapshot": cName, "output": string(output), "err": err}) errors++ continue } // Remove containers/<container>/snapshots/<snap0> if err := os.RemoveAll(oldPath); err != nil { logger.Error( "Failed to remove the old snapshot path", log.Ctx{ "snapshot": cName, "oldPath": oldPath, "err": err}) // Ignore this error. // errors++ // continue } // Remove /var/lib/lxd/containers/<container>/snapshots // if its empty. cPathParent := filepath.Dir(oldPath) if ok, _ := shared.PathIsEmpty(cPathParent); ok { os.Remove(cPathParent) } } // if shared.PathExists(oldPath) && !shared.PathExists(newPath) { } // for _, cName := range cNames { // Refuse to start lxd if a rsync failed. if errors > 0 { return fmt.Errorf("Got errors while moving snapshots, see the log output.") } return nil } func patchUpdateFromV15(d *Daemon) error { // munge all LVM-backed containers' LV names to match what is // required for snapshot support cNames, err := db.ContainersList(d.db, db.CTypeRegular) if err != nil { return err } err = daemonConfigInit(d.db) if err != nil { return err } vgName := daemonConfig["storage.lvm_vg_name"].Get() for _, cName := range cNames { var lvLinkPath string if strings.Contains(cName, shared.SnapshotDelimiter) { lvLinkPath = shared.VarPath("snapshots", fmt.Sprintf("%s.lv", cName)) } else { lvLinkPath = shared.VarPath("containers", fmt.Sprintf("%s.lv", cName)) } if !shared.PathExists(lvLinkPath) { continue } newLVName := strings.Replace(cName, "-", "--", -1) newLVName = strings.Replace(newLVName, shared.SnapshotDelimiter, "-", -1) if cName == newLVName { logger.Debug("No need to rename, skipping", log.Ctx{"cName": cName, "newLVName": newLVName}) continue } logger.Debug("About to rename cName in lv upgrade", log.Ctx{"lvLinkPath": lvLinkPath, "cName": cName, "newLVName": newLVName}) output, err := shared.RunCommand("lvrename", vgName, cName, newLVName) if err != nil { return fmt.Errorf("Could not rename LV '%s' to '%s': %v\noutput:%s", cName, newLVName, err, output) } if err := os.Remove(lvLinkPath); err != nil { return fmt.Errorf("Couldn't remove lvLinkPath '%s'", lvLinkPath) } newLinkDest := fmt.Sprintf("/dev/%s/%s", vgName, newLVName) if err := os.Symlink(newLinkDest, lvLinkPath); err != nil { return fmt.Errorf("Couldn't recreate symlink '%s'->'%s'", lvLinkPath, newLinkDest) } } return nil } func patchUpdateFromV29(d *Daemon) error { if shared.PathExists(shared.VarPath("zfs.img")) { err := os.Chmod(shared.VarPath("zfs.img"), 0600) if err != nil { return err } } return nil } func patchUpdateFromV30(d *Daemon) error { entries, err := ioutil.ReadDir(shared.VarPath("containers")) if err != nil { /* If the directory didn't exist before, the user had never * started containers, so we don't need to fix up permissions * on anything. */ if os.IsNotExist(err) { return nil } return err } for _, entry := range entries { if !shared.IsDir(shared.VarPath("containers", entry.Name(), "rootfs")) { continue } info, err := os.Stat(shared.VarPath("containers", entry.Name(), "rootfs")) if err != nil { return err } if int(info.Sys().(*syscall.Stat_t).Uid) == 0 { err := os.Chmod(shared.VarPath("containers", entry.Name()), 0700) if err != nil { return err } err = os.Chown(shared.VarPath("containers", entry.Name()), 0, 0) if err != nil { return err } } } return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/operations.go������������������������������������������������������������������������0000644�0610621�0607500�00000031026�13172163242�016774� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "net/http" "runtime" "strings" "sync" "time" "github.com/gorilla/mux" "github.com/pborman/uuid" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/cancel" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/version" ) var operationsLock sync.Mutex var operations map[string]*operation = make(map[string]*operation) type operationClass int const ( operationClassTask operationClass = 1 operationClassWebsocket operationClass = 2 operationClassToken operationClass = 3 ) func (t operationClass) String() string { return map[operationClass]string{ operationClassTask: "task", operationClassWebsocket: "websocket", operationClassToken: "token", }[t] } type operation struct { id string class operationClass createdAt time.Time updatedAt time.Time status api.StatusCode url string resources map[string][]string metadata map[string]interface{} err string readonly bool canceler *cancel.Canceler // Those functions are called at various points in the operation lifecycle onRun func(*operation) error onCancel func(*operation) error onConnect func(*operation, *http.Request, http.ResponseWriter) error // Channels used for error reporting and state tracking of background actions chanDone chan error // Locking for concurent access to the operation lock sync.Mutex } func (op *operation) done() { if op.readonly { return } op.lock.Lock() op.readonly = true op.onRun = nil op.onCancel = nil op.onConnect = nil close(op.chanDone) op.lock.Unlock() time.AfterFunc(time.Second*5, func() { operationsLock.Lock() _, ok := operations[op.id] if !ok { operationsLock.Unlock() return } delete(operations, op.id) operationsLock.Unlock() /* * When we create a new lxc.Container, it adds a finalizer (via * SetFinalizer) that frees the struct. However, it sometimes * takes the go GC a while to actually free the struct, * presumably since it is a small amount of memory. * Unfortunately, the struct also keeps the log fd open, so if * we leave too many of these around, we end up running out of * fds. So, let's explicitly do a GC to collect these at the * end of each request. */ runtime.GC() }) } func (op *operation) Run() (chan error, error) { if op.status != api.Pending { return nil, fmt.Errorf("Only pending operations can be started") } chanRun := make(chan error, 1) op.lock.Lock() op.status = api.Running if op.onRun != nil { go func(op *operation, chanRun chan error) { err := op.onRun(op) if err != nil { op.lock.Lock() op.status = api.Failure op.err = SmartError(err).String() op.lock.Unlock() op.done() chanRun <- err logger.Debugf("Failure for %s operation: %s: %s", op.class.String(), op.id, err) _, md, _ := op.Render() eventSend("operation", md) return } op.lock.Lock() op.status = api.Success op.lock.Unlock() op.done() chanRun <- nil op.lock.Lock() logger.Debugf("Success for %s operation: %s", op.class.String(), op.id) _, md, _ := op.Render() eventSend("operation", md) op.lock.Unlock() }(op, chanRun) } op.lock.Unlock() logger.Debugf("Started %s operation: %s", op.class.String(), op.id) _, md, _ := op.Render() eventSend("operation", md) return chanRun, nil } func (op *operation) Cancel() (chan error, error) { if op.status != api.Running { return nil, fmt.Errorf("Only running operations can be cancelled") } if !op.mayCancel() { return nil, fmt.Errorf("This operation can't be cancelled") } chanCancel := make(chan error, 1) op.lock.Lock() oldStatus := op.status op.status = api.Cancelling op.lock.Unlock() if op.onCancel != nil { go func(op *operation, oldStatus api.StatusCode, chanCancel chan error) { err := op.onCancel(op) if err != nil { op.lock.Lock() op.status = oldStatus op.lock.Unlock() chanCancel <- err logger.Debugf("Failed to cancel %s operation: %s: %s", op.class.String(), op.id, err) _, md, _ := op.Render() eventSend("operation", md) return } op.lock.Lock() op.status = api.Cancelled op.lock.Unlock() op.done() chanCancel <- nil logger.Debugf("Cancelled %s operation: %s", op.class.String(), op.id) _, md, _ := op.Render() eventSend("operation", md) }(op, oldStatus, chanCancel) } logger.Debugf("Cancelling %s operation: %s", op.class.String(), op.id) _, md, _ := op.Render() eventSend("operation", md) if op.canceler != nil { err := op.canceler.Cancel() if err != nil { return nil, err } } if op.onCancel == nil { op.lock.Lock() op.status = api.Cancelled op.lock.Unlock() op.done() chanCancel <- nil } logger.Debugf("Cancelled %s operation: %s", op.class.String(), op.id) _, md, _ = op.Render() eventSend("operation", md) return chanCancel, nil } func (op *operation) Connect(r *http.Request, w http.ResponseWriter) (chan error, error) { if op.class != operationClassWebsocket { return nil, fmt.Errorf("Only websocket operations can be connected") } if op.status != api.Running { return nil, fmt.Errorf("Only running operations can be connected") } chanConnect := make(chan error, 1) op.lock.Lock() go func(op *operation, chanConnect chan error) { err := op.onConnect(op, r, w) if err != nil { chanConnect <- err logger.Debugf("Failed to handle %s operation: %s: %s", op.class.String(), op.id, err) return } chanConnect <- nil logger.Debugf("Handled %s operation: %s", op.class.String(), op.id) }(op, chanConnect) op.lock.Unlock() logger.Debugf("Connected %s operation: %s", op.class.String(), op.id) return chanConnect, nil } func (op *operation) mayCancel() bool { if op.class == operationClassToken { return true } if op.onCancel != nil { return true } if op.canceler != nil && op.canceler.Cancelable() { return true } return false } func (op *operation) Render() (string, *api.Operation, error) { // Setup the resource URLs resources := op.resources if resources != nil { tmpResources := make(map[string][]string) for key, value := range resources { var values []string for _, c := range value { values = append(values, fmt.Sprintf("/%s/%s/%s", version.APIVersion, key, c)) } tmpResources[key] = values } resources = tmpResources } return op.url, &api.Operation{ ID: op.id, Class: op.class.String(), CreatedAt: op.createdAt, UpdatedAt: op.updatedAt, Status: op.status.String(), StatusCode: op.status, Resources: resources, Metadata: op.metadata, MayCancel: op.mayCancel(), Err: op.err, }, nil } func (op *operation) WaitFinal(timeout int) (bool, error) { // Check current state if op.status.IsFinal() { return true, nil } // Wait indefinitely if timeout == -1 { <-op.chanDone return true, nil } // Wait until timeout if timeout > 0 { timer := time.NewTimer(time.Duration(timeout) * time.Second) select { case <-op.chanDone: return false, nil case <-timer.C: return false, nil } } return false, nil } func (op *operation) UpdateResources(opResources map[string][]string) error { if op.status != api.Pending && op.status != api.Running { return fmt.Errorf("Only pending or running operations can be updated") } if op.readonly { return fmt.Errorf("Read-only operations can't be updated") } op.lock.Lock() op.updatedAt = time.Now() op.resources = opResources op.lock.Unlock() logger.Debugf("Updated resources for %s operation: %s", op.class.String(), op.id) _, md, _ := op.Render() eventSend("operation", md) return nil } func (op *operation) UpdateMetadata(opMetadata interface{}) error { if op.status != api.Pending && op.status != api.Running { return fmt.Errorf("Only pending or running operations can be updated") } if op.readonly { return fmt.Errorf("Read-only operations can't be updated") } newMetadata, err := shared.ParseMetadata(opMetadata) if err != nil { return err } op.lock.Lock() op.updatedAt = time.Now() op.metadata = newMetadata op.lock.Unlock() logger.Debugf("Updated metadata for %s operation: %s", op.class.String(), op.id) _, md, _ := op.Render() eventSend("operation", md) return nil } func operationCreate(opClass operationClass, opResources map[string][]string, opMetadata interface{}, onRun func(*operation) error, onCancel func(*operation) error, onConnect func(*operation, *http.Request, http.ResponseWriter) error) (*operation, error) { // Main attributes op := operation{} op.id = uuid.NewRandom().String() op.class = opClass op.createdAt = time.Now() op.updatedAt = op.createdAt op.status = api.Pending op.url = fmt.Sprintf("/%s/operations/%s", version.APIVersion, op.id) op.resources = opResources op.chanDone = make(chan error) newMetadata, err := shared.ParseMetadata(opMetadata) if err != nil { return nil, err } op.metadata = newMetadata // Callback functions op.onRun = onRun op.onCancel = onCancel op.onConnect = onConnect // Sanity check if op.class != operationClassWebsocket && op.onConnect != nil { return nil, fmt.Errorf("Only websocket operations can have a Connect hook") } if op.class == operationClassWebsocket && op.onConnect == nil { return nil, fmt.Errorf("Websocket operations must have a Connect hook") } if op.class == operationClassToken && op.onRun != nil { return nil, fmt.Errorf("Token operations can't have a Run hook") } if op.class == operationClassToken && op.onCancel != nil { return nil, fmt.Errorf("Token operations can't have a Cancel hook") } operationsLock.Lock() operations[op.id] = &op operationsLock.Unlock() logger.Debugf("New %s operation: %s", op.class.String(), op.id) _, md, _ := op.Render() eventSend("operation", md) return &op, nil } func operationGet(id string) (*operation, error) { operationsLock.Lock() op, ok := operations[id] operationsLock.Unlock() if !ok { return nil, fmt.Errorf("Operation '%s' doesn't exist", id) } return op, nil } // API functions func operationAPIGet(d *Daemon, r *http.Request) Response { id := mux.Vars(r)["id"] op, err := operationGet(id) if err != nil { return NotFound } _, body, err := op.Render() if err != nil { return SmartError(err) } return SyncResponse(true, body) } func operationAPIDelete(d *Daemon, r *http.Request) Response { id := mux.Vars(r)["id"] op, err := operationGet(id) if err != nil { return NotFound } _, err = op.Cancel() if err != nil { return BadRequest(err) } return EmptySyncResponse } var operationCmd = Command{name: "operations/{id}", get: operationAPIGet, delete: operationAPIDelete} func operationsAPIGet(d *Daemon, r *http.Request) Response { var md shared.Jmap recursion := util.IsRecursionRequest(r) md = shared.Jmap{} operationsLock.Lock() ops := operations operationsLock.Unlock() for _, v := range ops { status := strings.ToLower(v.status.String()) _, ok := md[status] if !ok { if recursion { md[status] = make([]*api.Operation, 0) } else { md[status] = make([]string, 0) } } if !recursion { md[status] = append(md[status].([]string), v.url) continue } _, body, err := v.Render() if err != nil { continue } md[status] = append(md[status].([]*api.Operation), body) } return SyncResponse(true, md) } var operationsCmd = Command{name: "operations", get: operationsAPIGet} func operationAPIWaitGet(d *Daemon, r *http.Request) Response { timeout, err := shared.AtoiEmptyDefault(r.FormValue("timeout"), -1) if err != nil { return InternalError(err) } id := mux.Vars(r)["id"] op, err := operationGet(id) if err != nil { return NotFound } _, err = op.WaitFinal(timeout) if err != nil { return InternalError(err) } _, body, err := op.Render() if err != nil { return SmartError(err) } return SyncResponse(true, body) } var operationWait = Command{name: "operations/{id}/wait", get: operationAPIWaitGet} type operationWebSocket struct { req *http.Request op *operation } func (r *operationWebSocket) Render(w http.ResponseWriter) error { chanErr, err := r.op.Connect(r.req, w) if err != nil { return err } err = <-chanErr return err } func (r *operationWebSocket) String() string { _, md, err := r.op.Render() if err != nil { return fmt.Sprintf("error: %s", err) } return md.ID } func operationAPIWebsocketGet(d *Daemon, r *http.Request) Response { id := mux.Vars(r)["id"] op, err := operationGet(id) if err != nil { return NotFound } return &operationWebSocket{r, op} } var operationWebsocket = Command{name: "operations/{id}/websocket", untrustedGet: true, get: operationAPIWebsocketGet} ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/networks.go��������������������������������������������������������������������������0000644�0610621�0607500�00000005610�13172163242�016465� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "net" "net/http" "strconv" "github.com/gorilla/mux" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/version" ) // Helper functions func networkIsInUse(c container, name string) bool { for _, d := range c.ExpandedDevices() { if d["type"] != "nic" { continue } if !shared.StringInSlice(d["nictype"], []string{"bridged", "macvlan"}) { continue } if d["parent"] == "" { continue } if d["parent"] == name { return true } } return false } // API endpoints func networksGet(d *Daemon, r *http.Request) Response { recursionStr := r.FormValue("recursion") recursion, err := strconv.Atoi(recursionStr) if err != nil { recursion = 0 } ifs, err := net.Interfaces() if err != nil { return InternalError(err) } resultString := []string{} resultMap := []api.Network{} for _, iface := range ifs { if recursion == 0 { resultString = append(resultString, fmt.Sprintf("/%s/networks/%s", version.APIVersion, iface.Name)) } else { net, err := doNetworkGet(d, iface.Name) if err != nil { continue } resultMap = append(resultMap, net) } } if recursion == 0 { return SyncResponse(true, resultString) } return SyncResponse(true, resultMap) } var networksCmd = Command{name: "networks", get: networksGet} func networkGet(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] n, err := doNetworkGet(d, name) if err != nil { return InternalError(err) } return SyncResponse(true, &n) } func doNetworkGet(d *Daemon, name string) (api.Network, error) { iface, err := net.InterfaceByName(name) if err != nil { return api.Network{}, err } // Prepare the response n := api.Network{} n.Name = iface.Name n.UsedBy = []string{} // Look for containers using the interface cts, err := db.ContainersList(d.db, db.CTypeRegular) if err != nil { return api.Network{}, err } for _, ct := range cts { c, err := containerLoadByName(d.State(), d.Storage, ct) if err != nil { return api.Network{}, err } if networkIsInUse(c, n.Name) { n.UsedBy = append(n.UsedBy, fmt.Sprintf("/%s/containers/%s", version.APIVersion, ct)) } } // Set the device type as needed if shared.IsLoopback(iface) { n.Type = "loopback" } else if shared.PathExists(fmt.Sprintf("/sys/class/net/%s/bridge", n.Name)) { n.Type = "bridge" } else if shared.PathExists(fmt.Sprintf("/proc/net/vlan/%s", n.Name)) { n.Type = "vlan" } else if shared.PathExists(fmt.Sprintf("/sys/class/net/%s/device", n.Name)) { n.Type = "physical" } else if shared.PathExists(fmt.Sprintf("/sys/class/net/%s/bonding", n.Name)) { n.Type = "bond" } else { _, err := shared.RunCommand("ovs-vsctl", "br-exists", n.Name) if err == nil { n.Type = "bridge" } else { n.Type = "unknown" } } return n, nil } var networkCmd = Command{name: "networks/{name}", get: networkGet} ������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/migrate.proto������������������������������������������������������������������������0000644�0610621�0607500�00000002042�13172163242�016773� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main; enum MigrationFSType { RSYNC = 0; BTRFS = 1; ZFS = 2; } enum CRIUType { CRIU_RSYNC = 0; PHAUL = 1; } message IDMapType { required bool isuid = 1; required bool isgid = 2; required int32 hostid = 3; required int32 nsid = 4; required int32 maprange = 5; } message Config { required string key = 1; required string value = 2; } message Device { required string name = 1; repeated Config config = 2; } message Snapshot { required string name = 1; repeated Config localConfig = 2; repeated string profiles = 3; required bool ephemeral = 4; repeated Device localDevices = 5; required int32 architecture = 6; required bool stateful = 7; } message MigrationHeader { required MigrationFSType fs = 1; optional CRIUType criu = 2; repeated IDMapType idmap = 3; repeated string snapshotNames = 4; repeated Snapshot snapshots = 5; } message MigrationControl { required bool success = 1; /* optional failure message if sending a failure */ optional string message = 2; } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/migrate.pb.go������������������������������������������������������������������������0000644�0610621�0607500�00000020050�13172163242�016634� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Code generated by protoc-gen-go. // source: lxd/migrate.proto // DO NOT EDIT! /* Package main is a generated protocol buffer package. It is generated from these files: lxd/migrate.proto It has these top-level messages: IDMapType Config Device Snapshot MigrationHeader MigrationControl */ package main import proto "github.com/golang/protobuf/proto" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = math.Inf type MigrationFSType int32 const ( MigrationFSType_RSYNC MigrationFSType = 0 MigrationFSType_BTRFS MigrationFSType = 1 MigrationFSType_ZFS MigrationFSType = 2 ) var MigrationFSType_name = map[int32]string{ 0: "RSYNC", 1: "BTRFS", 2: "ZFS", } var MigrationFSType_value = map[string]int32{ "RSYNC": 0, "BTRFS": 1, "ZFS": 2, } func (x MigrationFSType) Enum() *MigrationFSType { p := new(MigrationFSType) *p = x return p } func (x MigrationFSType) String() string { return proto.EnumName(MigrationFSType_name, int32(x)) } func (x *MigrationFSType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(MigrationFSType_value, data, "MigrationFSType") if err != nil { return err } *x = MigrationFSType(value) return nil } type CRIUType int32 const ( CRIUType_CRIU_RSYNC CRIUType = 0 CRIUType_PHAUL CRIUType = 1 ) var CRIUType_name = map[int32]string{ 0: "CRIU_RSYNC", 1: "PHAUL", } var CRIUType_value = map[string]int32{ "CRIU_RSYNC": 0, "PHAUL": 1, } func (x CRIUType) Enum() *CRIUType { p := new(CRIUType) *p = x return p } func (x CRIUType) String() string { return proto.EnumName(CRIUType_name, int32(x)) } func (x *CRIUType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(CRIUType_value, data, "CRIUType") if err != nil { return err } *x = CRIUType(value) return nil } type IDMapType struct { Isuid *bool `protobuf:"varint,1,req,name=isuid" json:"isuid,omitempty"` Isgid *bool `protobuf:"varint,2,req,name=isgid" json:"isgid,omitempty"` Hostid *int32 `protobuf:"varint,3,req,name=hostid" json:"hostid,omitempty"` Nsid *int32 `protobuf:"varint,4,req,name=nsid" json:"nsid,omitempty"` Maprange *int32 `protobuf:"varint,5,req,name=maprange" json:"maprange,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *IDMapType) Reset() { *m = IDMapType{} } func (m *IDMapType) String() string { return proto.CompactTextString(m) } func (*IDMapType) ProtoMessage() {} func (m *IDMapType) GetIsuid() bool { if m != nil && m.Isuid != nil { return *m.Isuid } return false } func (m *IDMapType) GetIsgid() bool { if m != nil && m.Isgid != nil { return *m.Isgid } return false } func (m *IDMapType) GetHostid() int32 { if m != nil && m.Hostid != nil { return *m.Hostid } return 0 } func (m *IDMapType) GetNsid() int32 { if m != nil && m.Nsid != nil { return *m.Nsid } return 0 } func (m *IDMapType) GetMaprange() int32 { if m != nil && m.Maprange != nil { return *m.Maprange } return 0 } type Config struct { Key *string `protobuf:"bytes,1,req,name=key" json:"key,omitempty"` Value *string `protobuf:"bytes,2,req,name=value" json:"value,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Config) Reset() { *m = Config{} } func (m *Config) String() string { return proto.CompactTextString(m) } func (*Config) ProtoMessage() {} func (m *Config) GetKey() string { if m != nil && m.Key != nil { return *m.Key } return "" } func (m *Config) GetValue() string { if m != nil && m.Value != nil { return *m.Value } return "" } type Device struct { Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"` Config []*Config `protobuf:"bytes,2,rep,name=config" json:"config,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Device) Reset() { *m = Device{} } func (m *Device) String() string { return proto.CompactTextString(m) } func (*Device) ProtoMessage() {} func (m *Device) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *Device) GetConfig() []*Config { if m != nil { return m.Config } return nil } type Snapshot struct { Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"` LocalConfig []*Config `protobuf:"bytes,2,rep,name=localConfig" json:"localConfig,omitempty"` Profiles []string `protobuf:"bytes,3,rep,name=profiles" json:"profiles,omitempty"` Ephemeral *bool `protobuf:"varint,4,req,name=ephemeral" json:"ephemeral,omitempty"` LocalDevices []*Device `protobuf:"bytes,5,rep,name=localDevices" json:"localDevices,omitempty"` Architecture *int32 `protobuf:"varint,6,req,name=architecture" json:"architecture,omitempty"` Stateful *bool `protobuf:"varint,7,req,name=stateful" json:"stateful,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Snapshot) Reset() { *m = Snapshot{} } func (m *Snapshot) String() string { return proto.CompactTextString(m) } func (*Snapshot) ProtoMessage() {} func (m *Snapshot) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *Snapshot) GetLocalConfig() []*Config { if m != nil { return m.LocalConfig } return nil } func (m *Snapshot) GetProfiles() []string { if m != nil { return m.Profiles } return nil } func (m *Snapshot) GetEphemeral() bool { if m != nil && m.Ephemeral != nil { return *m.Ephemeral } return false } func (m *Snapshot) GetLocalDevices() []*Device { if m != nil { return m.LocalDevices } return nil } func (m *Snapshot) GetArchitecture() int32 { if m != nil && m.Architecture != nil { return *m.Architecture } return 0 } func (m *Snapshot) GetStateful() bool { if m != nil && m.Stateful != nil { return *m.Stateful } return false } type MigrationHeader struct { Fs *MigrationFSType `protobuf:"varint,1,req,name=fs,enum=main.MigrationFSType" json:"fs,omitempty"` Criu *CRIUType `protobuf:"varint,2,opt,name=criu,enum=main.CRIUType" json:"criu,omitempty"` Idmap []*IDMapType `protobuf:"bytes,3,rep,name=idmap" json:"idmap,omitempty"` SnapshotNames []string `protobuf:"bytes,4,rep,name=snapshotNames" json:"snapshotNames,omitempty"` Snapshots []*Snapshot `protobuf:"bytes,5,rep,name=snapshots" json:"snapshots,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MigrationHeader) Reset() { *m = MigrationHeader{} } func (m *MigrationHeader) String() string { return proto.CompactTextString(m) } func (*MigrationHeader) ProtoMessage() {} func (m *MigrationHeader) GetFs() MigrationFSType { if m != nil && m.Fs != nil { return *m.Fs } return MigrationFSType_RSYNC } func (m *MigrationHeader) GetCriu() CRIUType { if m != nil && m.Criu != nil { return *m.Criu } return CRIUType_CRIU_RSYNC } func (m *MigrationHeader) GetIdmap() []*IDMapType { if m != nil { return m.Idmap } return nil } func (m *MigrationHeader) GetSnapshotNames() []string { if m != nil { return m.SnapshotNames } return nil } func (m *MigrationHeader) GetSnapshots() []*Snapshot { if m != nil { return m.Snapshots } return nil } type MigrationControl struct { Success *bool `protobuf:"varint,1,req,name=success" json:"success,omitempty"` // optional failure message if sending a failure Message *string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MigrationControl) Reset() { *m = MigrationControl{} } func (m *MigrationControl) String() string { return proto.CompactTextString(m) } func (*MigrationControl) ProtoMessage() {} func (m *MigrationControl) GetSuccess() bool { if m != nil && m.Success != nil { return *m.Success } return false } func (m *MigrationControl) GetMessage() string { if m != nil && m.Message != nil { return *m.Message } return "" } func init() { proto.RegisterEnum("main.MigrationFSType", MigrationFSType_name, MigrationFSType_value) proto.RegisterEnum("main.CRIUType", CRIUType_name, CRIUType_value) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/migrate.go���������������������������������������������������������������������������0000644�0610621�0607500�00000044522�13172163242�016246� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package migration provides the primitives for migration in LXD. // // See https://github.com/lxc/lxd/blob/master/specs/migration.md for a complete // description. package main import ( "fmt" "io/ioutil" "net/http" "net/url" "os" "os/exec" "path/filepath" "strings" "sync" "github.com/golang/protobuf/proto" "github.com/gorilla/websocket" "gopkg.in/lxc/go-lxc.v2" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" ) type migrationFields struct { live bool controlSecret string controlConn *websocket.Conn controlLock sync.Mutex criuSecret string criuConn *websocket.Conn fsSecret string fsConn *websocket.Conn container container } func (c *migrationFields) send(m proto.Message) error { /* gorilla websocket doesn't allow concurrent writes, and * panic()s if it sees them (which is reasonable). If e.g. we * happen to fail, get scheduled, start our write, then get * unscheduled before the write is bit to a new thread which is * receiving an error from the other side (due to our previous * close), we can engage in these concurrent writes, which * casuses the whole daemon to panic. * * Instead, let's lock sends to the controlConn so that we only ever * write one message at the time. */ c.controlLock.Lock() defer c.controlLock.Unlock() w, err := c.controlConn.NextWriter(websocket.BinaryMessage) if err != nil { return err } defer w.Close() data, err := proto.Marshal(m) if err != nil { return err } return shared.WriteAll(w, data) } func (c *migrationFields) recv(m proto.Message) error { mt, r, err := c.controlConn.NextReader() if err != nil { return err } if mt != websocket.BinaryMessage { return fmt.Errorf("Only binary messages allowed") } buf, err := ioutil.ReadAll(r) if err != nil { return err } return proto.Unmarshal(buf, m) } func (c *migrationFields) disconnect() { closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "") c.controlLock.Lock() if c.controlConn != nil { c.controlConn.WriteMessage(websocket.CloseMessage, closeMsg) c.controlConn = nil /* don't close twice */ } c.controlLock.Unlock() /* Below we just Close(), which doesn't actually write to the * websocket, it just closes the underlying connection. If e.g. there * is still a filesystem transfer going on, but the other side has run * out of disk space, writing an actual CloseMessage here will cause * gorilla websocket to panic. Instead, we just force close this * connection, since we report the error over the control channel * anyway. */ if c.fsConn != nil { c.fsConn.Close() } if c.criuConn != nil { c.criuConn.Close() } } func (c *migrationFields) sendControl(err error) { message := "" if err != nil { message = err.Error() } msg := MigrationControl{ Success: proto.Bool(err == nil), Message: proto.String(message), } c.send(&msg) if err != nil { c.disconnect() } } func (c *migrationFields) controlChannel() <-chan MigrationControl { ch := make(chan MigrationControl) go func() { msg := MigrationControl{} err := c.recv(&msg) if err != nil { logger.Debugf("Got error reading migration control socket %s", err) close(ch) return } ch <- msg }() return ch } type migrationSourceWs struct { migrationFields allConnected chan bool } func NewMigrationSource(c container) (*migrationSourceWs, error) { ret := migrationSourceWs{migrationFields{container: c}, make(chan bool, 1)} var err error ret.controlSecret, err = shared.RandomCryptoString() if err != nil { return nil, err } ret.fsSecret, err = shared.RandomCryptoString() if err != nil { return nil, err } if c.IsRunning() { _, err := exec.LookPath("criu") if err != nil { return nil, fmt.Errorf("Unable to perform container live migration. CRIU isn't installed on the source server.") } ret.live = true ret.criuSecret, err = shared.RandomCryptoString() if err != nil { return nil, err } } return &ret, nil } func (s *migrationSourceWs) Metadata() interface{} { secrets := shared.Jmap{ "control": s.controlSecret, "fs": s.fsSecret, } if s.criuSecret != "" { secrets["criu"] = s.criuSecret } return secrets } func (s *migrationSourceWs) Connect(op *operation, r *http.Request, w http.ResponseWriter) error { secret := r.FormValue("secret") if secret == "" { return fmt.Errorf("missing secret") } var conn **websocket.Conn switch secret { case s.controlSecret: conn = &s.controlConn case s.criuSecret: conn = &s.criuConn case s.fsSecret: conn = &s.fsConn default: // If we didn't find the right secret, the user provided a bad // one, which 403, not 404, since this operation actually // exists. return os.ErrPermission } c, err := shared.WebsocketUpgrader.Upgrade(w, r, nil) if err != nil { return err } *conn = c if s.controlConn != nil && (!s.live || s.criuConn != nil) && s.fsConn != nil { s.allConnected <- true } return nil } func writeActionScript(directory string, operation string, secret string) error { script := fmt.Sprintf(`#!/bin/sh -e if [ "$CRTOOLS_SCRIPT_ACTION" = "post-dump" ]; then %s migratedumpsuccess %s %s fi `, execPath, operation, secret) f, err := os.Create(filepath.Join(directory, "action.sh")) if err != nil { return err } defer f.Close() err = f.Chmod(0500) if err != nil { return err } _, err = f.WriteString(script) return err } func snapshotToProtobuf(c container) *Snapshot { config := []*Config{} for k, v := range c.LocalConfig() { kCopy := string(k) vCopy := string(v) config = append(config, &Config{Key: &kCopy, Value: &vCopy}) } devices := []*Device{} for name, d := range c.LocalDevices() { props := []*Config{} for k, v := range d { kCopy := string(k) vCopy := string(v) props = append(props, &Config{Key: &kCopy, Value: &vCopy}) } devices = append(devices, &Device{Name: &name, Config: props}) } parts := strings.SplitN(c.Name(), shared.SnapshotDelimiter, 2) isEphemeral := c.IsEphemeral() arch := int32(c.Architecture()) stateful := c.IsStateful() return &Snapshot{ Name: &parts[len(parts)-1], LocalConfig: config, Profiles: c.Profiles(), Ephemeral: &isEphemeral, LocalDevices: devices, Architecture: &arch, Stateful: &stateful, } } func (s *migrationSourceWs) Do(migrateOp *operation) error { <-s.allConnected criuType := CRIUType_CRIU_RSYNC.Enum() if !s.live { criuType = nil err := s.container.StorageStart() if err != nil { return err } defer s.container.StorageStop() } idmaps := make([]*IDMapType, 0) idmapset, err := s.container.IdmapSet() if err != nil { return err } if idmapset != nil { for _, ctnIdmap := range idmapset.Idmap { idmap := IDMapType{ Isuid: proto.Bool(ctnIdmap.Isuid), Isgid: proto.Bool(ctnIdmap.Isgid), Hostid: proto.Int32(int32(ctnIdmap.Hostid)), Nsid: proto.Int32(int32(ctnIdmap.Nsid)), Maprange: proto.Int32(int32(ctnIdmap.Maprange)), } idmaps = append(idmaps, &idmap) } } driver, fsErr := s.container.Storage().MigrationSource(s.container) /* the protocol says we have to send a header no matter what, so let's * do that, but then immediately send an error. */ snapshots := []*Snapshot{} snapshotNames := []string{} if fsErr == nil { fullSnaps := driver.Snapshots() for _, snap := range fullSnaps { snapshots = append(snapshots, snapshotToProtobuf(snap)) snapshotNames = append(snapshotNames, shared.ExtractSnapshotName(snap.Name())) } } // The protocol says we have to send a header no matter what, so let's // do that, but then immediately send an error. myType := s.container.Storage().MigrationType() header := MigrationHeader{ Fs: &myType, Criu: criuType, Idmap: idmaps, SnapshotNames: snapshotNames, Snapshots: snapshots, } err = s.send(&header) if err != nil { s.sendControl(err) return err } if fsErr != nil { s.sendControl(fsErr) return fsErr } err = s.recv(&header) if err != nil { s.sendControl(err) return err } if *header.Fs != myType { myType = MigrationFSType_RSYNC header.Fs = &myType driver, _ = rsyncMigrationSource(s.container) } // All failure paths need to do a few things to correctly handle errors before returning. // Unfortunately, handling errors is not well-suited to defer as the code depends on the // status of driver and the error value. The error value is especially tricky due to the // common case of creating a new err variable (intentional or not) due to scoping and use // of ":=". Capturing err in a closure for use in defer would be fragile, which defeats // the purpose of using defer. An abort function reduces the odds of mishandling errors // without introducing the fragility of closing on err. abort := func(err error) error { driver.Cleanup() s.sendControl(err) return err } err = driver.SendWhileRunning(s.fsConn) if err != nil { return abort(err) } restoreSuccess := make(chan bool, 1) dumpSuccess := make(chan error, 1) if s.live { if header.Criu == nil { return abort(fmt.Errorf("Got no CRIU socket type for live migration")) } else if *header.Criu != CRIUType_CRIU_RSYNC { return abort(fmt.Errorf("Formats other than criu rsync not understood")) } checkpointDir, err := ioutil.TempDir("", "lxd_checkpoint_") if err != nil { return abort(err) } if lxc.VersionAtLeast(2, 0, 4) { /* What happens below is slightly convoluted. Due to various * complications with networking, there's no easy way for criu * to exit and leave the container in a frozen state for us to * somehow resume later. * * Instead, we use what criu calls an "action-script", which is * basically a callback that lets us know when the dump is * done. (Unfortunately, we can't pass arguments, just an * executable path, so we write a custom action script with the * real command we want to run.) * * This script then hangs until the migration operation either * finishes successfully or fails, and exits 1 or 0, which * causes criu to either leave the container running or kill it * as we asked. */ dumpDone := make(chan bool, 1) actionScriptOpSecret, err := shared.RandomCryptoString() if err != nil { os.RemoveAll(checkpointDir) return abort(err) } actionScriptOp, err := operationCreate( operationClassWebsocket, nil, nil, func(op *operation) error { result := <-restoreSuccess if !result { return fmt.Errorf("restore failed, failing CRIU") } return nil }, nil, func(op *operation, r *http.Request, w http.ResponseWriter) error { secret := r.FormValue("secret") if secret == "" { return fmt.Errorf("missing secret") } if secret != actionScriptOpSecret { return os.ErrPermission } c, err := shared.WebsocketUpgrader.Upgrade(w, r, nil) if err != nil { return err } dumpDone <- true closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "") return c.WriteMessage(websocket.CloseMessage, closeMsg) }, ) if err != nil { os.RemoveAll(checkpointDir) return abort(err) } err = writeActionScript(checkpointDir, actionScriptOp.url, actionScriptOpSecret) if err != nil { os.RemoveAll(checkpointDir) return abort(err) } _, err = actionScriptOp.Run() if err != nil { os.RemoveAll(checkpointDir) return abort(err) } go func() { dumpSuccess <- s.container.Migrate(lxc.MIGRATE_DUMP, checkpointDir, "migration", true, true) os.RemoveAll(checkpointDir) }() select { /* the checkpoint failed, let's just abort */ case err = <-dumpSuccess: return abort(err) /* the dump finished, let's continue on to the restore */ case <-dumpDone: logger.Debugf("Dump finished, continuing with restore...") } } else { defer os.RemoveAll(checkpointDir) err = s.container.Migrate(lxc.MIGRATE_DUMP, checkpointDir, "migration", true, false) if err != nil { return abort(err) } } /* * We do the serially right now, but there's really no reason for us * to; since we have separate websockets, we can do it in parallel if * we wanted to. However, assuming we're network bound, there's really * no reason to do these in parallel. In the future when we're using * p.haul's protocol, it will make sense to do these in parallel. */ ctName, _, _ := containerGetParentAndSnapshotName(s.container.Name()) err = RsyncSend(ctName, shared.AddSlash(checkpointDir), s.criuConn) if err != nil { return abort(err) } err = driver.SendAfterCheckpoint(s.fsConn) if err != nil { return abort(err) } } driver.Cleanup() msg := MigrationControl{} err = s.recv(&msg) if err != nil { s.disconnect() return err } if s.live { restoreSuccess <- *msg.Success err := <-dumpSuccess if err != nil { logger.Errorf("dump failed after successful restore?: %q", err) } } if !*msg.Success { return fmt.Errorf(*msg.Message) } return nil } type migrationSink struct { // We are pulling the container from src in pull mode. src migrationFields url string dialer websocket.Dialer } type MigrationSinkArgs struct { Url string Dialer websocket.Dialer Container container Secrets map[string]string } func NewMigrationSink(args *MigrationSinkArgs) (*migrationSink, error) { sink := migrationSink{ src: migrationFields{container: args.Container}, url: args.Url, dialer: args.Dialer, } var ok bool sink.src.controlSecret, ok = args.Secrets["control"] if !ok { return nil, fmt.Errorf("Missing control secret") } sink.src.fsSecret, ok = args.Secrets["fs"] if !ok { return nil, fmt.Errorf("Missing fs secret") } sink.src.criuSecret, ok = args.Secrets["criu"] sink.src.live = ok _, err := exec.LookPath("criu") if sink.src.live && err != nil { return nil, fmt.Errorf("Unable to perform container live migration. CRIU isn't installed on the destination server.") } return &sink, nil } func (c *migrationSink) connectWithSecret(secret string) (*websocket.Conn, error) { query := url.Values{"secret": []string{secret}} // The URL is a https URL to the operation, mangle to be a wss URL to the secret wsUrl := fmt.Sprintf("wss://%s/websocket?%s", strings.TrimPrefix(c.url, "https://"), query.Encode()) conn, _, err := c.dialer.Dial(wsUrl, http.Header{}) if err != nil { return nil, err } return conn, err } func (c *migrationSink) Do(migrateOp *operation) error { var err error c.src.controlConn, err = c.connectWithSecret(c.src.controlSecret) if err != nil { c.src.container.Delete() return err } defer c.src.disconnect() c.src.fsConn, err = c.connectWithSecret(c.src.fsSecret) if err != nil { c.src.container.Delete() c.src.sendControl(err) return err } if c.src.live { c.src.criuConn, err = c.connectWithSecret(c.src.criuSecret) if err != nil { c.src.container.Delete() c.src.sendControl(err) return err } } header := MigrationHeader{} if err := c.src.recv(&header); err != nil { c.src.container.Delete() c.src.sendControl(err) return err } criuType := CRIUType_CRIU_RSYNC.Enum() if !c.src.live { criuType = nil } mySink := c.src.container.Storage().MigrationSink myType := c.src.container.Storage().MigrationType() resp := MigrationHeader{ Fs: &myType, Criu: criuType, } // If the storage type the source has doesn't match what we have, then // we have to use rsync. if *header.Fs != *resp.Fs { mySink = rsyncMigrationSink myType = MigrationFSType_RSYNC resp.Fs = &myType } err = c.src.send(&resp) if err != nil { c.src.container.Delete() c.src.sendControl(err) return err } restore := make(chan error) go func(c *migrationSink) { imagesDir := "" srcIdmap := new(idmap.IdmapSet) for _, idmapSet := range header.Idmap { e := idmap.IdmapEntry{ Isuid: *idmapSet.Isuid, Isgid: *idmapSet.Isgid, Nsid: int64(*idmapSet.Nsid), Hostid: int64(*idmapSet.Hostid), Maprange: int64(*idmapSet.Maprange)} srcIdmap.Idmap = idmap.Extend(srcIdmap.Idmap, e) } /* We do the fs receive in parallel so we don't have to reason * about when to receive what. The sending side is smart enough * to send the filesystem bits that it can before it seizes the * container to start checkpointing, so the total transfer time * will be minimized even if we're dumb here. */ fsTransfer := make(chan error) go func() { snapshots := []*Snapshot{} /* Legacy: we only sent the snapshot names, so we just * copy the container's config over, same as we used to * do. */ if len(header.SnapshotNames) != len(header.Snapshots) { for _, name := range header.SnapshotNames { base := snapshotToProtobuf(c.src.container) base.Name = &name snapshots = append(snapshots, base) } } else { snapshots = header.Snapshots } err := mySink(c.src.live, c.src.container, snapshots, c.src.fsConn, srcIdmap) if err != nil { fsTransfer <- err return } err = ShiftIfNecessary(c.src.container, srcIdmap) if err != nil { fsTransfer <- err return } fsTransfer <- nil }() if c.src.live { var err error imagesDir, err = ioutil.TempDir("", "lxd_restore_") if err != nil { restore <- err return } defer os.RemoveAll(imagesDir) err = RsyncRecv(shared.AddSlash(imagesDir), c.src.criuConn) if err != nil { restore <- err return } } err := <-fsTransfer if err != nil { restore <- err return } if c.src.live { err = c.src.container.Migrate(lxc.MIGRATE_RESTORE, imagesDir, "migration", false, false) if err != nil { restore <- err return } } restore <- nil }(c) source := c.src.controlChannel() for { select { case err = <-restore: c.src.sendControl(err) if err != nil { c.src.container.Delete() return err } return nil case msg, ok := <-source: if !ok { c.src.disconnect() c.src.container.Delete() return fmt.Errorf("Got error reading source") } if !*msg.Success { c.src.disconnect() c.src.container.Delete() return fmt.Errorf(*msg.Message) } else { // The source can only tell us it failed (e.g. if // checkpointing failed). We have to tell the source // whether or not the restore was successful. logger.Debugf("Unknown message %v from source", msg) err = c.src.container.TemplateApply("copy") if err != nil { c.src.container.Delete() return err } } } } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_waitready.go��������������������������������������������������������������������0000644�0610621�0607500�00000001336�13172163242�017607� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "time" "github.com/lxc/lxd/client" ) func cmdWaitReady(args *Args) error { var timeout int if args.Timeout == -1 { timeout = 15 } else { timeout = args.Timeout } finger := make(chan error, 1) go func() { for { c, err := lxd.ConnectLXDUnix("", nil) if err != nil { time.Sleep(500 * time.Millisecond) continue } _, _, err = c.RawQuery("GET", "/internal/ready", nil, "") if err != nil { time.Sleep(500 * time.Millisecond) continue } finger <- nil return } }() select { case <-finger: break case <-time.After(time.Second * time.Duration(timeout)): return fmt.Errorf("LXD still not running after %ds timeout.", timeout) } return nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_test.go�������������������������������������������������������������������������0000644�0610621�0607500�00000003355�13172163242�016600� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "crypto/tls" "io/ioutil" "os" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/lxc/lxd/shared/idmap" ) func mockStartDaemon() (*Daemon, error) { d := NewDaemon() d.os.MockMode = true d.tlsConfig = &tls.Config{} if err := d.Init(); err != nil { return nil, err } d.os.IdmapSet = &idmap.IdmapSet{Idmap: []idmap.IdmapEntry{ {Isuid: true, Hostid: 100000, Nsid: 0, Maprange: 500000}, {Isgid: true, Hostid: 100000, Nsid: 0, Maprange: 500000}, }} // Call this after Init so we have a log object. storageConfig := make(map[string]interface{}) d.Storage = &storageLogWrapper{w: &storageMock{d: d}} if _, err := d.Storage.Init(storageConfig); err != nil { return nil, err } return d, nil } type lxdTestSuite struct { suite.Suite d *Daemon Req *require.Assertions tmpdir string } func (suite *lxdTestSuite) SetupSuite() { tmpdir, err := ioutil.TempDir("", "lxd_testrun_") if err != nil { os.Exit(1) } suite.tmpdir = tmpdir if err := os.Setenv("LXD_DIR", suite.tmpdir); err != nil { os.Exit(1) } suite.d, err = mockStartDaemon() if err != nil { os.Exit(1) } suite.Req = require.New(suite.T()) } func (suite *lxdTestSuite) TearDownSuite() { suite.d.Stop() err := os.RemoveAll(suite.tmpdir) if err != nil { os.Exit(1) } } func (suite *lxdTestSuite) SetupTest() { initializeDbObject(suite.d, ":memory:") daemonConfigInit(suite.d.db) suite.Req = require.New(suite.T()) suite.d.pruneChan = make(chan bool) suite.d.resetAutoUpdateChan = make(chan bool) go func() { for { select { case <-suite.d.pruneChan: case <-suite.d.resetAutoUpdateChan: continue } } }() } func (suite *lxdTestSuite) TearDownTest() { suite.d.db.Close() } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_shutdown.go���������������������������������������������������������������������0000644�0610621�0607500�00000001272�13172163242�017470� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "time" "github.com/lxc/lxd/client" ) func cmdShutdown(args *Args) error { c, err := lxd.ConnectLXDUnix("", nil) if err != nil { return err } _, _, err = c.RawQuery("PUT", "/internal/shutdown", nil, "") if err != nil { return err } chMonitor := make(chan bool, 1) go func() { monitor, err := c.GetEvents() if err != nil { close(chMonitor) return } monitor.Wait() close(chMonitor) }() if args.Timeout > 0 { select { case <-chMonitor: break case <-time.After(time.Second * time.Duration(args.Timeout)): return fmt.Errorf("LXD still running after %ds timeout.", args.Timeout) } } else { <-chMonitor } return nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_ready.go������������������������������������������������������������������������0000644�0610621�0607500�00000000403�13172163242�016714� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "github.com/lxc/lxd/client" ) func cmdReady() error { c, err := lxd.ConnectLXDUnix("", nil) if err != nil { return err } _, _, err = c.RawQuery("PUT", "/internal/ready", nil, "") if err != nil { return err } return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_nsexec.go�����������������������������������������������������������������������0000644�0610621�0607500�00000031566�13172163242�017113� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������/** * This file is a bit funny. The goal here is to use setns() to manipulate * files inside the container, so we don't have to reason about the paths to * make sure they don't escape (we can simply rely on the kernel for * correctness). Unfortunately, you can't setns() to a mount namespace with a * multi-threaded program, which every golang binary is. However, by declaring * our init as an initializer, we can capture process control before it is * transferred to the golang runtime, so we can then setns() as we'd like * before golang has a chance to set up any threads. So, we implement two new * lxd fork* commands which are captured here, and take a file on the host fs * and copy it into the container ns. * * An alternative to this would be to move this code into a separate binary, * which of course has problems of its own when it comes to packaging (how do * we find the binary, what do we do if someone does file push and it is * missing, etc.). After some discussion, even though the embedded method is * somewhat convoluted, it was preferred. */ package main /* #define _GNU_SOURCE #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/mount.h> #include <sched.h> #include <linux/sched.h> #include <linux/limits.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <alloca.h> #include <libgen.h> #include <ifaddrs.h> #include <grp.h> // This expects: // ./lxd forkputfile /source/path <pid> /target/path // or // ./lxd forkgetfile /target/path <pid> /soruce/path <uid> <gid> <mode> // i.e. 8 arguments, each which have a max length of PATH_MAX. // Unfortunately, lseek() and fstat() both fail (EINVAL and 0 size) for // procfs. Also, we can't mmap, because procfs doesn't support that, either. // #define CMDLINE_SIZE (8 * PATH_MAX) void error(char *msg) { int old_errno = errno; if (old_errno == 0) { fprintf(stderr, "%s\n", msg); fprintf(stderr, "errno: 0\n"); return; } perror(msg); fprintf(stderr, "errno: %d\n", old_errno); } int mkdir_p(const char *dir, mode_t mode) { const char *tmp = dir; const char *orig = dir; char *makeme; do { dir = tmp + strspn(tmp, "/"); tmp = dir + strcspn(dir, "/"); makeme = strndup(orig, dir - orig); if (*makeme) { if (mkdir(makeme, mode) && errno != EEXIST) { fprintf(stderr, "failed to create directory '%s': %s\n", makeme, strerror(errno)); free(makeme); return -1; } } free(makeme); } while(tmp != dir); return 0; } int copy(int target, int source) { ssize_t n; char buf[1024]; if (ftruncate(target, 0) < 0) { error("error: truncate"); return -1; } while ((n = read(source, buf, 1024)) > 0) { if (write(target, buf, n) != n) { error("error: write"); return -1; } } if (n < 0) { error("error: read"); return -1; } return 0; } int dosetns(int pid, char *nstype) { int mntns; char buf[PATH_MAX]; sprintf(buf, "/proc/%d/ns/%s", pid, nstype); mntns = open(buf, O_RDONLY); if (mntns < 0) { error("error: open mntns"); return -1; } if (setns(mntns, 0) < 0) { error("error: setns"); close(mntns); return -1; } close(mntns); return 0; } void attach_userns(int pid) { char nspath[PATH_MAX]; char userns_source[PATH_MAX]; char userns_target[PATH_MAX]; sprintf(nspath, "/proc/%d/ns/user", pid); if (access(nspath, F_OK) == 0) { if (readlink("/proc/self/ns/user", userns_source, 18) < 0) { fprintf(stderr, "Failed readlink of source namespace: %s\n", strerror(errno)); _exit(1); } if (readlink(nspath, userns_target, PATH_MAX) < 0) { fprintf(stderr, "Failed readlink of target namespace: %s\n", strerror(errno)); _exit(1); } if (strncmp(userns_source, userns_target, PATH_MAX) != 0) { if (dosetns(pid, "user") < 0) { fprintf(stderr, "Failed setns to container user namespace: %s\n", strerror(errno)); _exit(1); } if (setgroups(0, NULL) < 0) { fprintf(stderr, "Failed setgroups to container root groups: %s\n", strerror(errno)); _exit(1); } if (setgid(0) < 0) { fprintf(stderr, "Failed setgid to container root group: %s\n", strerror(errno)); _exit(1); } if (setuid(0) < 0) { fprintf(stderr, "Failed setuid to container root user: %s\n", strerror(errno)); _exit(1); } } } } int manip_file_in_ns(char *rootfs, int pid, char *host, char *container, bool is_put, uid_t uid, gid_t gid, mode_t mode, uid_t defaultUid, gid_t defaultGid, mode_t defaultMode) { int host_fd, container_fd; int ret = -1; int container_open_flags; struct stat st; int exists = 1; host_fd = open(host, O_RDWR); if (host_fd < 0) { error("error: open"); return -1; } container_open_flags = O_RDWR; if (is_put) container_open_flags |= O_CREAT; if (pid > 0) { attach_userns(pid); if (dosetns(pid, "mnt") < 0) { error("error: setns"); goto close_host; } } else { if (chroot(rootfs) < 0) { error("error: chroot"); goto close_host; } if (chdir("/") < 0) { error("error: chdir"); goto close_host; } } if (is_put && stat(container, &st) < 0) exists = 0; if (is_put && exists && S_ISDIR(st.st_mode)) { error("error: Path already exists as a directory"); goto close_host; } umask(0); container_fd = open(container, container_open_flags, 0); if (container_fd < 0) { error("error: open"); goto close_host; } if (is_put) { if (!exists) { if (mode == -1) { mode = defaultMode; } if (uid == -1) { uid = defaultUid; } if (gid == -1) { gid = defaultGid; } } if (copy(container_fd, host_fd) < 0) { error("error: copy"); goto close_container; } if (mode != -1 && fchmod(container_fd, mode) < 0) { error("error: chmod"); goto close_container; } if (fchown(container_fd, uid, gid) < 0) { error("error: chown"); goto close_container; } ret = 0; } else { ret = copy(host_fd, container_fd); if (fstat(container_fd, &st) < 0) { error("error: stat"); goto close_container; } fprintf(stderr, "uid: %ld\n", (long)st.st_uid); fprintf(stderr, "gid: %ld\n", (long)st.st_gid); fprintf(stderr, "mode: %ld\n", (unsigned long)st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)); } close_container: close(container_fd); close_host: close(host_fd); return ret; } #define ADVANCE_ARG_REQUIRED() \ do { \ while (*cur != 0) \ cur++; \ cur++; \ if (size <= cur - buf) { \ fprintf(stderr, "not enough arguments\n"); \ _exit(1); \ } \ } while(0) void ensure_dir(char *dest) { struct stat sb; if (stat(dest, &sb) == 0) { if ((sb.st_mode & S_IFMT) == S_IFDIR) return; if (unlink(dest) < 0) { fprintf(stderr, "Failed to remove old %s: %s\n", dest, strerror(errno)); _exit(1); } } if (mkdir(dest, 0755) < 0) { fprintf(stderr, "Failed to mkdir %s: %s\n", dest, strerror(errno)); _exit(1); } } void ensure_file(char *dest) { struct stat sb; int fd; if (stat(dest, &sb) == 0) { if ((sb.st_mode & S_IFMT) != S_IFDIR) return; if (rmdir(dest) < 0) { fprintf(stderr, "Failed to remove old %s: %s\n", dest, strerror(errno)); _exit(1); } } fd = creat(dest, 0755); if (fd < 0) { fprintf(stderr, "Failed to mkdir %s: %s\n", dest, strerror(errno)); _exit(1); } close(fd); } void create(char *src, char *dest) { char *dirdup; char *destdirname; struct stat sb; if (stat(src, &sb) < 0) { fprintf(stderr, "source %s does not exist\n", src); _exit(1); } dirdup = strdup(dest); if (!dirdup) _exit(1); destdirname = dirname(dirdup); if (mkdir_p(destdirname, 0755) < 0) { fprintf(stderr, "failed to create path: %s\n", destdirname); free(dirdup); _exit(1); } free(dirdup); switch (sb.st_mode & S_IFMT) { case S_IFDIR: ensure_dir(dest); return; default: ensure_file(dest); return; } } void forkmount(char *buf, char *cur, ssize_t size) { char *src, *dest, *opts; ADVANCE_ARG_REQUIRED(); int pid = atoi(cur); attach_userns(pid); if (dosetns(pid, "mnt") < 0) { fprintf(stderr, "Failed setns to container mount namespace: %s\n", strerror(errno)); _exit(1); } ADVANCE_ARG_REQUIRED(); src = cur; ADVANCE_ARG_REQUIRED(); dest = cur; create(src, dest); if (access(src, F_OK) < 0) { fprintf(stderr, "Mount source doesn't exist: %s\n", strerror(errno)); _exit(1); } if (access(dest, F_OK) < 0) { fprintf(stderr, "Mount destination doesn't exist: %s\n", strerror(errno)); _exit(1); } // Here, we always move recursively, because we sometimes allow // recursive mounts. If the mount has no kids then it doesn't matter, // but if it does, we want to move those too. if (mount(src, dest, "none", MS_MOVE | MS_REC, NULL) < 0) { fprintf(stderr, "Failed mounting %s onto %s: %s\n", src, dest, strerror(errno)); _exit(1); } _exit(0); } void forkumount(char *buf, char *cur, ssize_t size) { ADVANCE_ARG_REQUIRED(); int pid = atoi(cur); if (dosetns(pid, "mnt") < 0) { fprintf(stderr, "Failed setns to container mount namespace: %s\n", strerror(errno)); _exit(1); } ADVANCE_ARG_REQUIRED(); if (access(cur, F_OK) < 0) { fprintf(stderr, "Mount path doesn't exist: %s\n", strerror(errno)); _exit(1); } if (umount2(cur, MNT_DETACH) < 0) { fprintf(stderr, "Error unmounting %s: %s\n", cur, strerror(errno)); _exit(1); } _exit(0); } void forkdofile(char *buf, char *cur, bool is_put, ssize_t size) { uid_t uid = 0; gid_t gid = 0; mode_t mode = 0; uid_t defaultUid = 0; gid_t defaultGid = 0; mode_t defaultMode = 0; char *command = cur, *rootfs = NULL, *source = NULL, *target = NULL; pid_t pid; ADVANCE_ARG_REQUIRED(); rootfs = cur; ADVANCE_ARG_REQUIRED(); pid = atoi(cur); ADVANCE_ARG_REQUIRED(); source = cur; ADVANCE_ARG_REQUIRED(); target = cur; if (is_put) { ADVANCE_ARG_REQUIRED(); uid = atoi(cur); ADVANCE_ARG_REQUIRED(); gid = atoi(cur); ADVANCE_ARG_REQUIRED(); mode = atoi(cur); ADVANCE_ARG_REQUIRED(); defaultUid = atoi(cur); ADVANCE_ARG_REQUIRED(); defaultGid = atoi(cur); ADVANCE_ARG_REQUIRED(); defaultMode = atoi(cur); } _exit(manip_file_in_ns(rootfs, pid, source, target, is_put, uid, gid, mode, defaultUid, defaultGid, defaultMode)); } void forkcheckfile(char *buf, char *cur, bool is_put, ssize_t size) { char *command = cur, *rootfs = NULL, *path = NULL; pid_t pid; ADVANCE_ARG_REQUIRED(); rootfs = cur; ADVANCE_ARG_REQUIRED(); pid = atoi(cur); ADVANCE_ARG_REQUIRED(); path = cur; if (pid > 0) { attach_userns(pid); if (dosetns(pid, "mnt") < 0) { error("error: setns"); _exit(1); } } else { if (chroot(rootfs) < 0) { error("error: chroot"); _exit(1); } if (chdir("/") < 0) { error("error: chdir"); _exit(1); } } if (access(path, F_OK) < 0) { fprintf(stderr, "Path doesn't exist: %s\n", strerror(errno)); _exit(1); } _exit(0); } void forkremovefile(char *buf, char *cur, bool is_put, ssize_t size) { char *command = cur, *rootfs = NULL, *path = NULL; pid_t pid; struct stat sb; ADVANCE_ARG_REQUIRED(); rootfs = cur; ADVANCE_ARG_REQUIRED(); pid = atoi(cur); ADVANCE_ARG_REQUIRED(); path = cur; if (pid > 0) { attach_userns(pid); if (dosetns(pid, "mnt") < 0) { error("error: setns"); _exit(1); } } else { if (chroot(rootfs) < 0) { error("error: chroot"); _exit(1); } if (chdir("/") < 0) { error("error: chdir"); _exit(1); } } if (stat(path, &sb) < 0) { error("error: stat"); _exit(1); } if ((sb.st_mode & S_IFMT) == S_IFDIR) { if (rmdir(path) < 0) { fprintf(stderr, "Failed to remove %s: %s\n", path, strerror(errno)); _exit(1); } } else { if (unlink(path) < 0) { fprintf(stderr, "Failed to remove %s: %s\n", path, strerror(errno)); _exit(1); } } _exit(0); } void forkgetnet(char *buf, char *cur, ssize_t size) { ADVANCE_ARG_REQUIRED(); int pid = atoi(cur); if (dosetns(pid, "net") < 0) { fprintf(stderr, "Failed setns to container network namespace: %s\n", strerror(errno)); _exit(1); } // The rest happens in Go } __attribute__((constructor)) void init(void) { int cmdline; char buf[CMDLINE_SIZE]; ssize_t size; char *cur; cmdline = open("/proc/self/cmdline", O_RDONLY); if (cmdline < 0) { error("error: open"); _exit(232); } memset(buf, 0, sizeof(buf)); if ((size = read(cmdline, buf, sizeof(buf)-1)) < 0) { close(cmdline); error("error: read"); _exit(232); } close(cmdline); cur = buf; // skip argv[0] while (*cur != 0) cur++; cur++; if (size <= cur - buf) return; if (strcmp(cur, "forkputfile") == 0) { forkdofile(buf, cur, true, size); } else if (strcmp(cur, "forkgetfile") == 0) { forkdofile(buf, cur, false, size); } else if (strcmp(cur, "forkcheckfile") == 0) { forkcheckfile(buf, cur, false, size); } else if (strcmp(cur, "forkremovefile") == 0) { forkremovefile(buf, cur, false, size); } else if (strcmp(cur, "forkmount") == 0) { forkmount(buf, cur, size); } else if (strcmp(cur, "forkumount") == 0) { forkumount(buf, cur, size); } else if (strcmp(cur, "forkgetnet") == 0) { forkgetnet(buf, cur, size); } } */ import "C" ������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_netcat.go�����������������������������������������������������������������������0000644�0610621�0607500�00000004352�13172163242�017075� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io" "net" "os" "sync" "syscall" "github.com/lxc/lxd/shared" ) // Netcat is called with: // // lxd netcat /path/to/unix/socket // // and does unbuffered netcatting of to socket to stdin/stdout. Any arguments // after the path to the unix socket are ignored, so that this can be passed // directly to rsync as the sync command. func cmdNetcat(args *Args) error { if len(args.Params) < 2 { return fmt.Errorf("Bad arguments %q", args.Params) } logPath := shared.LogPath(args.Params[1], "netcat.log") if shared.PathExists(logPath) { os.Remove(logPath) } logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644) if err != nil { return err } defer logFile.Close() uAddr, err := net.ResolveUnixAddr("unix", args.Params[0]) if err != nil { logFile.WriteString(fmt.Sprintf("Could not resolve unix domain socket \"%s\": %s.\n", args.Params[0], err)) return err } conn, err := net.DialUnix("unix", nil, uAddr) if err != nil { logFile.WriteString(fmt.Sprintf("Could not dial unix domain socket \"%s\": %s.\n", args.Params[0], err)) return err } wg := sync.WaitGroup{} wg.Add(1) go func() { _, err := io.Copy(eagainWriter{os.Stdout}, eagainReader{conn}) if err != nil { logFile.WriteString(fmt.Sprintf("Error while copying from stdout to unix domain socket \"%s\": %s.\n", args.Params[0], err)) } conn.Close() wg.Done() }() go func() { _, err := io.Copy(eagainWriter{conn}, eagainReader{os.Stdin}) if err != nil { logFile.WriteString(fmt.Sprintf("Error while copying from unix domain socket \"%s\" to stdin: %s.\n", args.Params[0], err)) } }() wg.Wait() return nil } type eagainReader struct { r io.Reader } func (er eagainReader) Read(p []byte) (int, error) { again: n, err := er.r.Read(p) if err == nil { return n, nil } // keep retrying on EAGAIN errno, ok := shared.GetErrno(err) if ok && errno == syscall.EAGAIN { goto again } return n, err } type eagainWriter struct { w io.Writer } func (ew eagainWriter) Write(p []byte) (int, error) { again: n, err := ew.w.Write(p) if err == nil { return n, nil } // keep retrying on EAGAIN errno, ok := shared.GetErrno(err) if ok && errno == syscall.EAGAIN { goto again } return n, err } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_migratedumpsuccess.go�����������������������������������������������������������0000644�0610621�0607500�00000001424�13172163242�021523� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "strings" "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared/api" ) func cmdMigrateDumpSuccess(args *Args) error { if len(args.Params) != 2 { return fmt.Errorf("bad migrate dump success args %s", args.Params) } c, err := lxd.ConnectLXDUnix("", nil) if err != nil { return err } url := fmt.Sprintf("%s/websocket?secret=%s", strings.TrimPrefix(args.Params[0], "/1.0"), args.Params[1]) conn, err := c.RawWebsocket(url) if err != nil { return err } conn.Close() resp, _, err := c.RawQuery("GET", fmt.Sprintf("%s/wait", args.Params[0]), nil, "") if err != nil { return err } op, err := resp.MetadataAsOperation() if err != nil { return err } if op.StatusCode == api.Success { return nil } return fmt.Errorf(op.Err) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_init_test.go��������������������������������������������������������������������0000644�0610621�0607500�00000006473�13172163242�017627� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "testing" "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared/cmd" "github.com/stretchr/testify/suite" ) type cmdInitTestSuite struct { lxdTestSuite streams *cmd.MemoryStreams context *cmd.Context args *Args command *CmdInit client lxd.ContainerServer } func (suite *cmdInitTestSuite) SetupTest() { suite.lxdTestSuite.SetupTest() suite.streams = cmd.NewMemoryStreams("") suite.context = cmd.NewMemoryContext(suite.streams) suite.args = &Args{ NetworkPort: -1, StorageCreateLoop: -1, } suite.command = &CmdInit{ Context: suite.context, Args: suite.args, RunningInUserns: false, SocketPath: suite.d.UnixSocket.Socket.Addr().String(), } client, err := lxd.ConnectLXDUnix(suite.command.SocketPath, nil) suite.Req.Nil(err) suite.client = client } // If any argument intended for --auto is passed in interactive mode, an // error is returned. func (suite *cmdInitTestSuite) TestCmdInit_InteractiveWithAutoArgs() { suite.args.NetworkPort = 9999 err := suite.command.Run() suite.Req.Equal("Init configuration is only valid with --auto", err.Error()) } // Some arguments can only be passed together with --auto. func (suite *cmdInitTestSuite) TestCmdInit_AutoSpecificArgs() { suite.args.StorageBackend = "dir" err := suite.command.Run() suite.Req.Equal("Init configuration is only valid with --auto", err.Error()) } // If an invalid backend type is passed with --storage-backend, an // error is returned. func (suite *cmdInitTestSuite) TestCmdInit_AutoWithInvalidBackendType() { suite.args.Auto = true suite.args.StorageBackend = "foo" err := suite.command.Run() suite.Req.Equal("The requested backend 'foo' isn't supported by lxd init.", err.Error()) } // If an backend type that is not available on the system is passed // with --storage-backend, an error is returned. func (suite *cmdInitTestSuite) TestCmdInit_AutoWithUnavailableBackendType() { suite.args.Auto = true suite.args.StorageBackend = "zfs" suite.command.RunningInUserns = true // This makes zfs unavailable err := suite.command.Run() suite.Req.Equal("The requested backend 'zfs' isn't available on your system (missing tools).", err.Error()) } // If --storage-backend is set to "dir", --storage-create-device can't be passed. func (suite *cmdInitTestSuite) TestCmdInit_AutoWithDirStorageBackendAndCreateDevice() { suite.args.Auto = true suite.args.StorageBackend = "dir" suite.args.StorageCreateDevice = "/dev/sda4" err := suite.command.Run() suite.Req.Equal("None of --storage-pool, --storage-create-device or --storage-create-loop may be used with the 'dir' backend.", err.Error()) } // Convenience for building the input text a user would enter for a certain // sequence of answers. type cmdInitAnswers struct { StoragePoolDriver string WantAvailableOverNetwork bool BindToAddress string BindToPort string } // Render the input text the user would type for the desired answers, populating // the stdin of the given streams. func (answers *cmdInitAnswers) Render(streams *cmd.MemoryStreams) { streams.InputAppendLine(answers.StoragePoolDriver) if answers.WantAvailableOverNetwork { streams.InputAppendLine(answers.BindToAddress) streams.InputAppendLine(answers.BindToPort) } } func TestCmdInitTestSuite(t *testing.T) { suite.Run(t, new(cmdInitTestSuite)) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_init.go�������������������������������������������������������������������������0000644�0610621�0607500�00000047245�13172163242�016572� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "net" "os" "os/exec" "strconv" "strings" "syscall" "golang.org/x/crypto/ssh/terminal" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/cmd" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" ) // CmdInit implements the "lxd init" command line. type CmdInit struct { Context *cmd.Context Args *Args RunningInUserns bool SocketPath string PasswordReader func(int) ([]byte, error) } // Run triggers the execution of the init command. func (cmd *CmdInit) Run() error { // Check that command line arguments don't conflict with each other err := cmd.validateArgs() if err != nil { return err } // Connect to LXD client, err := lxd.ConnectLXDUnix(cmd.SocketPath, nil) if err != nil { return fmt.Errorf("Unable to talk to LXD: %s", err) } // Check that we have no containers or images in the store containers, err := client.GetContainerNames() if err != nil { return fmt.Errorf("Unable to list the LXD containers: %s", err) } images, err := client.GetImageFingerprints() if err != nil { return fmt.Errorf("Unable to list the LXD images: %s", err) } if len(containers) > 0 || len(images) > 0 { return fmt.Errorf("You have existing containers or images. lxd init requires an empty LXD.") } data := &cmdInitData{} // Copy the data from the current default profile, if it exists. cmd.fillDataWithCurrentServerConfig(data, client) // Copy the data from the current server config. cmd.fillDataWithCurrentDefaultProfile(data, client) // Figure what storage drivers among the supported ones are actually // available on this system. backendsAvailable := cmd.availableStoragePoolsDrivers() if cmd.Args.Auto { err = cmd.fillDataAuto(data, client, backendsAvailable) } else { err = cmd.fillDataInteractive(data, client, backendsAvailable) } if err != nil { return err } // Apply the desired configuration. err = cmd.apply(client, data) if err != nil { return err } cmd.Context.Output("LXD has been successfully configured.\n") return nil } // Fill the given configuration data with parameters collected from // the --auto command line. func (cmd *CmdInit) fillDataAuto(data *cmdInitData, client lxd.ContainerServer, backendsAvailable []string) error { if cmd.Args.StorageBackend == "" { cmd.Args.StorageBackend = "dir" } err := cmd.validateArgsAuto(backendsAvailable) if err != nil { return err } if cmd.Args.NetworkAddress != "" { // If no port was provided, use the default one if cmd.Args.NetworkPort == -1 { cmd.Args.NetworkPort = 8443 } networking := &cmdInitNetworkingParams{ Address: cmd.Args.NetworkAddress, Port: cmd.Args.NetworkPort, TrustPassword: cmd.Args.TrustPassword, } cmd.fillDataWithNetworking(data, networking) } if cmd.Args.StorageBackend == "zfs" { storage := &cmdInitStorageParams{ Backend: cmd.Args.StorageBackend, LoopSize: cmd.Args.StorageCreateLoop, Device: cmd.Args.StorageCreateDevice, Pool: cmd.Args.StorageDataset, } if cmd.Args.StorageCreateDevice != "" { storage.Mode = "device" } else if cmd.Args.StorageCreateLoop != -1 { storage.Mode = "loop" } else { storage.Mode = "existing" } err = cmd.fillDataWithStorage(data, storage) if err != nil { return err } } return nil } // Fill the given configuration data with parameters collected with // interactive questions. func (cmd *CmdInit) fillDataInteractive(data *cmdInitData, client lxd.ContainerServer, backendsAvailable []string) error { storage, err := cmd.askStorage(client, backendsAvailable) if err != nil { return err } defaultPrivileged := cmd.askDefaultPrivileged() networking := cmd.askNetworking() err = cmd.fillDataWithStorage(data, storage) if err != nil { return err } err = cmd.fillDataWithDefaultPrivileged(data, defaultPrivileged) if err != nil { return err } cmd.fillDataWithNetworking(data, networking) return nil } // Fill the given data with the current server configuration. func (cmd *CmdInit) fillDataWithCurrentServerConfig(data *cmdInitData, client lxd.ContainerServer) error { server, _, err := client.GetServer() if err != nil { return err } data.ServerPut = server.Writable() return nil } // Fill the given data with the current default profile, if it exists. func (cmd *CmdInit) fillDataWithCurrentDefaultProfile(data *cmdInitData, client lxd.ContainerServer) { defaultProfile, _, err := client.GetProfile("default") if err == nil { // Copy the default profile configuration (that we have // possibly modified above). data.Profiles = []api.ProfilesPost{{Name: "default"}} data.Profiles[0].ProfilePut = defaultProfile.ProfilePut } } // Fill the given init data with a new storage pool structure matching the // given storage parameters. func (cmd *CmdInit) fillDataWithStorage(data *cmdInitData, storage *cmdInitStorageParams) error { // Destroy any existing loop device for _, file := range []string{"zfs.img"} { os.Remove(shared.VarPath(file)) } if storage == nil { return nil } if storage.Mode == "loop" { storage.Device = shared.VarPath("zfs.img") f, err := os.Create(storage.Device) if err != nil { return fmt.Errorf("Failed to open %s: %s", storage.Device, err) } err = f.Chmod(0600) if err != nil { return fmt.Errorf("Failed to chmod %s: %s", storage.Device, err) } err = f.Truncate(int64(storage.LoopSize * 1024 * 1024 * 1024)) if err != nil { return fmt.Errorf("Failed to create sparse file %s: %s", storage.Device, err) } err = f.Close() if err != nil { return fmt.Errorf("Failed to close %s: %s", storage.Device, err) } } if shared.StringInSlice(storage.Mode, []string{"loop", "device"}) { output, err := shared.RunCommand( "zpool", "create", storage.Pool, storage.Device, "-f", "-m", "none", "-O", "compression=on") if err != nil { return fmt.Errorf("Failed to create the ZFS pool: %s", output) } } else { logger.Warnf("Did not find profile \"default\" so no default storage pool will be set. Manual intervention needed.") } data.Config["storage.zfs_pool_name"] = storage.Pool return nil } // Fill the default profile in the given init data with options about whether // to run in privileged mode. func (cmd *CmdInit) fillDataWithDefaultPrivileged(data *cmdInitData, defaultPrivileged int) error { if defaultPrivileged == -1 { return nil } if len(data.Profiles) == 0 { return fmt.Errorf("error: profile 'default' profile not found") } defaultProfile := data.Profiles[0] if defaultPrivileged == 0 { defaultProfile.Config["security.privileged"] = "" } else if defaultPrivileged == 1 { defaultProfile.Config["security.privileged"] = "true" } return nil } // Fill the given init data with server config details matching the // given networking parameters. func (cmd *CmdInit) fillDataWithNetworking(data *cmdInitData, networking *cmdInitNetworkingParams) { if networking == nil { return } data.Config["core.https_address"] = fmt.Sprintf("%s:%d", networking.Address, networking.Port) if networking.TrustPassword != "" { data.Config["core.trust_password"] = networking.TrustPassword } } // Apply the configuration specified in the given init data. func (cmd *CmdInit) apply(client lxd.ContainerServer, data *cmdInitData) error { // Functions that should be invoked to revert back to initial // state any change that was successfully applied, in case // anything goes wrong after that change. reverters := make([]reverter, 0) // Functions to apply the desired changes. changers := make([](func() (reverter, error)), 0) // Server config changer changers = append(changers, func() (reverter, error) { return cmd.initConfig(client, data.Config) }) // Profile changers for i := range data.Profiles { profile := data.Profiles[i] // Local variable for the closure changers = append(changers, func() (reverter, error) { return cmd.initProfile(client, profile) }) } // Apply all changes. If anything goes wrong at any iteration // of the loop, we'll try to revert any change performed in // earlier iterations. for _, changer := range changers { reverter, err := changer() if err != nil { cmd.revert(reverters) return err } // Save the revert function for later. reverters = append(reverters, reverter) } return nil } // Try to revert the state to what it was before running the "lxd init" command. func (cmd *CmdInit) revert(reverters []reverter) { for _, reverter := range reverters { err := reverter() if err != nil { logger.Warnf("Reverting to pre-init state failed: %s", err) break } } } // Apply the server-level configuration in the given map. func (cmd *CmdInit) initConfig(client lxd.ContainerServer, config map[string]interface{}) (reverter, error) { server, etag, err := client.GetServer() if err != nil { return nil, err } // Build a function that can be used to revert the config to // its original values. reverter := func() error { return client.UpdateServer(server.Writable(), "") } // The underlying code expects all values to be string, even if when // using preseed the yaml.v2 package unmarshals them as integers. for key, value := range config { if number, ok := value.(int); ok { value = strconv.Itoa(number) } config[key] = value } err = client.UpdateServer(api.ServerPut{Config: config}, etag) if err != nil { return nil, err } // Updating the server was successful, so return the reverter function // in case it's needed later. return reverter, nil } // Create or update a single profile, and return a revert function in case of success. func (cmd *CmdInit) initProfile(client lxd.ContainerServer, profile api.ProfilesPost) (reverter, error) { var reverter func() error currentProfile, _, err := client.GetProfile(profile.Name) if err == nil { reverter, err = cmd.initProfileUpdate(client, profile, currentProfile.Writable()) } else { reverter, err = cmd.initProfileCreate(client, profile) } if err != nil { return nil, err } return reverter, nil } // Create a single new profile, and return a revert function to delete it. func (cmd *CmdInit) initProfileCreate(client lxd.ContainerServer, profile api.ProfilesPost) (reverter, error) { reverter := func() error { return client.DeleteProfile(profile.Name) } err := client.CreateProfile(profile) return reverter, err } // Update a single profile, and return a function that can be used to // revert it to its original state. func (cmd *CmdInit) initProfileUpdate(client lxd.ContainerServer, profile api.ProfilesPost, currentProfile api.ProfilePut) (reverter, error) { reverter := func() error { return client.UpdateProfile(profile.Name, currentProfile, "") } err := client.UpdateProfile(profile.Name, api.ProfilePut{ Config: profile.Config, Description: profile.Description, Devices: profile.Devices, }, "") return reverter, err } // Check that the arguments passed via command line are consistent, // and no invalid combination is provided. func (cmd *CmdInit) validateArgs() error { if !cmd.Args.Auto { if cmd.Args.StorageBackend != "" || cmd.Args.StorageCreateDevice != "" || cmd.Args.StorageCreateLoop != -1 || cmd.Args.StorageDataset != "" || cmd.Args.NetworkAddress != "" || cmd.Args.NetworkPort != -1 || cmd.Args.TrustPassword != "" { return fmt.Errorf("Init configuration is only valid with --auto") } } return nil } // Check that the arguments passed along with --auto are valid and consistent. // and no invalid combination is provided. func (cmd *CmdInit) validateArgsAuto(availableStoragePoolsDrivers []string) error { if !shared.StringInSlice(cmd.Args.StorageBackend, supportedStoragePoolDrivers) { return fmt.Errorf("The requested backend '%s' isn't supported by lxd init.", cmd.Args.StorageBackend) } if !shared.StringInSlice(cmd.Args.StorageBackend, availableStoragePoolsDrivers) { return fmt.Errorf("The requested backend '%s' isn't available on your system (missing tools).", cmd.Args.StorageBackend) } if cmd.Args.StorageBackend == "dir" { if cmd.Args.StorageCreateLoop != -1 || cmd.Args.StorageCreateDevice != "" || cmd.Args.StorageDataset != "" { return fmt.Errorf("None of --storage-pool, --storage-create-device or --storage-create-loop may be used with the 'dir' backend.") } } else { if cmd.Args.StorageCreateLoop != -1 && cmd.Args.StorageCreateDevice != "" { return fmt.Errorf("Only one of --storage-create-device or --storage-create-loop can be specified.") } } if cmd.Args.NetworkAddress == "" { if cmd.Args.NetworkPort != -1 { return fmt.Errorf("--network-port cannot be used without --network-address.") } if cmd.Args.TrustPassword != "" { return fmt.Errorf("--trust-password cannot be used without --network-address.") } } return nil } // Return the available storage pools drivers (depending on installed tools). func (cmd *CmdInit) availableStoragePoolsDrivers() []string { drivers := []string{"dir"} // Detect zfs out, err := exec.LookPath("zfs") if err == nil && len(out) != 0 && !cmd.RunningInUserns { _ = util.LoadModule("zfs") _, err := shared.RunCommand("zpool", "list") if err == nil { drivers = append(drivers, "zfs") } } return drivers } // Return an error if the given profile has already a device with the // given name. func (cmd *CmdInit) profileDeviceAlreadyExists(profile *api.ProfilesPost, deviceName string) error { _, ok := profile.Devices[deviceName] if ok { return fmt.Errorf("Device already exists: %s", deviceName) } return nil } // Ask if the user wants to create a new storage pool, and return // the relevant parameters if so. func (cmd *CmdInit) askStorage(client lxd.ContainerServer, availableBackends []string) (*cmdInitStorageParams, error) { if !cmd.Context.AskBool("Do you want to configure a new storage pool (yes/no) [default=yes]? ", "yes") { return nil, nil } storage := &cmdInitStorageParams{} defaultStorage := "dir" if shared.StringInSlice("zfs", availableBackends) { defaultStorage = "zfs" } for { storage.Backend = cmd.Context.AskChoice(fmt.Sprintf("Name of the storage backend to use (dir or zfs) [default=%s]: ", defaultStorage), availableBackends, defaultStorage) // XXX The following to checks don't make much sense, since // AskChoice will always re-ask the question if the answer // is not among supportedStoragePoolDrivers. It seems legacy // code that we should drop? if !shared.StringInSlice(storage.Backend, supportedStoragePoolDrivers) { return nil, fmt.Errorf("The requested backend '%s' isn't supported by lxd init.", storage.Backend) } // XXX Instead of manually checking if the provided choice is // among availableBackends, we could just pass to askChoice the // availableBackends list instead of supportedStoragePoolDrivers. if !shared.StringInSlice(storage.Backend, availableBackends) { return nil, fmt.Errorf("The requested backend '%s' isn't available on your system (missing tools).", storage.Backend) } if storage.Backend == "dir" { break } storage.LoopSize = -1 question := fmt.Sprintf("Create a new %s pool (yes/no) [default=yes]? ", strings.ToUpper(storage.Backend)) if cmd.Context.AskBool(question, "yes") { if cmd.Context.AskBool("Would you like to use an existing block device (yes/no) [default=no]? ", "no") { deviceExists := func(path string) error { if !shared.IsBlockdevPath(path) { return fmt.Errorf("'%s' is not a block device", path) } return nil } storage.Device = cmd.Context.AskString("Path to the existing block device: ", "", deviceExists) storage.Mode = "device" } else { st := syscall.Statfs_t{} err := syscall.Statfs(shared.VarPath(), &st) if err != nil { return nil, fmt.Errorf("couldn't statfs %s: %s", shared.VarPath(), err) } /* choose 15 GB < x < 100GB, where x is 20% of the disk size */ def := uint64(st.Frsize) * st.Blocks / (1024 * 1024 * 1024) / 5 if def > 100 { def = 100 } if def < 15 { def = 15 } q := fmt.Sprintf("Size in GB of the new loop device (1GB minimum) [default=%d]: ", def) storage.LoopSize = cmd.Context.AskInt(q, 1, -1, fmt.Sprintf("%d", def)) storage.Mode = "loop" } } else { question := fmt.Sprintf("Name of the existing %s pool or dataset: ", strings.ToUpper(storage.Backend)) storage.Pool = cmd.Context.AskString(question, "", nil) storage.Mode = "existing" } break } return storage, nil } // If we detect that we are running inside an unprivileged container, // ask if the user wants to the default profile to be a privileged // one. func (cmd *CmdInit) askDefaultPrivileged() int { // Detect lack of uid/gid defaultPrivileged := -1 needPrivileged := false idmapset, err := idmap.DefaultIdmapSet() if err != nil || len(idmapset.Idmap) == 0 || idmapset.Usable() != nil { needPrivileged = true } if cmd.RunningInUserns && needPrivileged { fmt.Printf(` We detected that you are running inside an unprivileged container. This means that unless you manually configured your host otherwise, you will not have enough uid and gid to allocate to your containers. LXD can re-use your container's own allocation to avoid the problem. Doing so makes your nested containers slightly less safe as they could in theory attack their parent container and gain more privileges than they otherwise would. `) if cmd.Context.AskBool("Would you like to have your containers share their parent's allocation (yes/no) [default=yes]? ", "yes") { defaultPrivileged = 1 } else { defaultPrivileged = 0 } } return defaultPrivileged } // Ask if the user wants to expose LXD over the network, and collect // the relevant parameters if so. func (cmd *CmdInit) askNetworking() *cmdInitNetworkingParams { if !cmd.Context.AskBool("Would you like LXD to be available over the network (yes/no) [default=no]? ", "no") { return nil } networking := &cmdInitNetworkingParams{} isIPAddress := func(s string) error { if s != "all" && net.ParseIP(s) == nil { return fmt.Errorf("'%s' is not an IP address", s) } return nil } networking.Address = cmd.Context.AskString("Address to bind LXD to (not including port) [default=all]: ", "all", isIPAddress) if networking.Address == "all" { networking.Address = "::" } if net.ParseIP(networking.Address).To4() == nil { networking.Address = fmt.Sprintf("[%s]", networking.Address) } networking.Port = cmd.Context.AskInt("Port to bind LXD to [default=8443]: ", 1, 65535, "8443") networking.TrustPassword = cmd.Context.AskPassword("Trust password for new clients: ", cmd.PasswordReader) return networking } // Defines the schema for all possible configuration knobs supported by the // lxd init command, either directly fed via --preseed or populated by // the auto/interactive modes. type cmdInitData struct { api.ServerPut `yaml:",inline"` Profiles []api.ProfilesPost } // Parameters needed when creating a storage pool in interactive or auto // mode. type cmdInitStorageParams struct { Backend string // == supportedStoragePoolDrivers LoopSize int64 // Size in GB Device string // Path Pool string // pool name Mode string } // Parameters needed when configuring the LXD server networking options in interactive // mode or auto mode. type cmdInitNetworkingParams struct { Address string // Address Port int64 // Port TrustPassword string // Trust password } // Shortcut for closure/anonymous functions that are meant to revert // some change, and that are passed around as parameters. type reverter func() error func cmdInit(args *Args) error { context := cmd.NewContext(os.Stdin, os.Stdout, os.Stderr) command := &CmdInit{ Context: context, Args: args, RunningInUserns: shared.RunningInUserNS(), SocketPath: "", PasswordReader: terminal.ReadPassword, } return command.Run() } var supportedStoragePoolDrivers = []string{"dir", "zfs"} �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_forkstart.go��������������������������������������������������������������������0000644�0610621�0607500�00000002641�13172163242�017635� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "syscall" "gopkg.in/lxc/go-lxc.v2" "github.com/lxc/lxd/shared" ) /* * This is called by lxd when called as "lxd forkstart <container>" * 'forkstart' is used instead of just 'start' in the hopes that people * do not accidentally type 'lxd start' instead of 'lxc start' */ func cmdForkStart(args *Args) error { if len(args.Params) != 3 { return fmt.Errorf("Bad arguments: %q", args.Params) } name := args.Params[0] lxcpath := args.Params[1] configPath := args.Params[2] c, err := lxc.NewContainer(name, lxcpath) if err != nil { return fmt.Errorf("Error initializing container for start: %q", err) } err = c.LoadConfigFile(configPath) if err != nil { return fmt.Errorf("Error opening startup config file: %q", err) } /* due to https://github.com/golang/go/issues/13155 and the * CollectOutput call we make for the forkstart process, we need to * close our stdin/stdout/stderr here. Collecting some of the logs is * better than collecting no logs, though. */ os.Stdin.Close() os.Stderr.Close() os.Stdout.Close() // Redirect stdout and stderr to a log file logPath := shared.LogPath(name, "forkstart.log") if shared.PathExists(logPath) { os.Remove(logPath) } logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644) if err == nil { syscall.Dup3(int(logFile.Fd()), 1, 0) syscall.Dup3(int(logFile.Fd()), 2, 0) } return c.Start() } �����������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_forkmigrate.go������������������������������������������������������������������0000644�0610621�0607500�00000002547�13172163242�020135� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "strconv" "gopkg.in/lxc/go-lxc.v2" ) /* * Similar to forkstart, this is called when lxd is invoked as: * * lxd forkmigrate <container> <lxcpath> <path_to_config> <path_to_criu_images> <preserves_inodes> * * liblxc's restore() sets up the processes in such a way that the monitor ends * up being a child of the process that calls it, in our case lxd. However, we * really want the monitor to be daemonized, so we fork again. Additionally, we * want to fork for the same reasons we do forkstart (i.e. reduced memory * footprint when we fork tasks that will never free golang's memory, etc.) */ func cmdForkMigrate(args *Args) error { if len(args.Params) != 5 { return fmt.Errorf("Bad arguments %q", args.Params) } name := args.Params[0] lxcpath := args.Params[1] configPath := args.Params[2] imagesDir := args.Params[3] preservesInodes, err := strconv.ParseBool(args.Params[4]) c, err := lxc.NewContainer(name, lxcpath) if err != nil { return err } if err := c.LoadConfigFile(configPath); err != nil { return err } /* see https://github.com/golang/go/issues/13155, startContainer, and dc3a229 */ os.Stdin.Close() os.Stdout.Close() os.Stderr.Close() return c.Migrate(lxc.MIGRATE_RESTORE, lxc.MigrateOptions{ Directory: imagesDir, Verbose: true, PreservesInodes: preservesInodes, }) } ���������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_forkgetnet.go�������������������������������������������������������������������0000644�0610621�0607500�00000005427�13172163242�017773� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "io/ioutil" "net" "strconv" "strings" "github.com/lxc/lxd/shared/api" ) func cmdForkGetNet() error { networks := map[string]api.ContainerStateNetwork{} interfaces, err := net.Interfaces() if err != nil { return err } stats := map[string][]int64{} content, err := ioutil.ReadFile("/proc/net/dev") if err == nil { for _, line := range strings.Split(string(content), "\n") { fields := strings.Fields(line) if len(fields) != 17 { continue } rxBytes, err := strconv.ParseInt(fields[1], 10, 64) if err != nil { continue } rxPackets, err := strconv.ParseInt(fields[2], 10, 64) if err != nil { continue } txBytes, err := strconv.ParseInt(fields[9], 10, 64) if err != nil { continue } txPackets, err := strconv.ParseInt(fields[10], 10, 64) if err != nil { continue } intName := strings.TrimSuffix(fields[0], ":") stats[intName] = []int64{rxBytes, rxPackets, txBytes, txPackets} } } for _, netIf := range interfaces { netState := "down" netType := "unknown" if netIf.Flags&net.FlagBroadcast > 0 { netType = "broadcast" } if netIf.Flags&net.FlagPointToPoint > 0 { netType = "point-to-point" } if netIf.Flags&net.FlagLoopback > 0 { netType = "loopback" } if netIf.Flags&net.FlagUp > 0 { netState = "up" } network := api.ContainerStateNetwork{ Addresses: []api.ContainerStateNetworkAddress{}, Counters: api.ContainerStateNetworkCounters{}, Hwaddr: netIf.HardwareAddr.String(), Mtu: netIf.MTU, State: netState, Type: netType, } addrs, err := netIf.Addrs() if err == nil { for _, addr := range addrs { fields := strings.SplitN(addr.String(), "/", 2) if len(fields) != 2 { continue } family := "inet" if strings.Contains(fields[0], ":") { family = "inet6" } scope := "global" if strings.HasPrefix(fields[0], "127") { scope = "local" } if fields[0] == "::1" { scope = "local" } if strings.HasPrefix(fields[0], "169.254") { scope = "link" } if strings.HasPrefix(fields[0], "fe80:") { scope = "link" } address := api.ContainerStateNetworkAddress{} address.Family = family address.Address = fields[0] address.Netmask = fields[1] address.Scope = scope network.Addresses = append(network.Addresses, address) } } counters, ok := stats[netIf.Name] if ok { network.Counters.BytesReceived = counters[0] network.Counters.PacketsReceived = counters[1] network.Counters.BytesSent = counters[2] network.Counters.PacketsSent = counters[3] } networks[netIf.Name] = network } buf, err := json.Marshal(networks) if err != nil { return err } fmt.Printf("%s\n", buf) return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_forkexec.go���������������������������������������������������������������������0000644�0610621�0607500�00000005275�13172163242�017432� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "os" "strings" "syscall" "gopkg.in/lxc/go-lxc.v2" "github.com/lxc/lxd/shared" ) /* * This is called by lxd when called as "lxd forkexec <container>" */ func cmdForkExec(args *Args) (int, error) { if len(args.Params) < 3 { return -1, fmt.Errorf("Bad params: %q", args.Params) } if len(args.Extra) < 1 { return -1, fmt.Errorf("Bad extra: %q", args.Extra) } name := args.Params[0] lxcpath := args.Params[1] configPath := args.Params[2] c, err := lxc.NewContainer(name, lxcpath) if err != nil { return -1, fmt.Errorf("Error initializing container for start: %q", err) } err = c.LoadConfigFile(configPath) if err != nil { return -1, fmt.Errorf("Error opening startup config file: %q", err) } syscall.Dup3(int(os.Stdin.Fd()), 200, 0) syscall.Dup3(int(os.Stdout.Fd()), 201, 0) syscall.Dup3(int(os.Stderr.Fd()), 202, 0) syscall.Close(int(os.Stdin.Fd())) syscall.Close(int(os.Stdout.Fd())) syscall.Close(int(os.Stderr.Fd())) opts := lxc.DefaultAttachOptions opts.ClearEnv = true opts.StdinFd = 200 opts.StdoutFd = 201 opts.StderrFd = 202 logPath := shared.LogPath(name, "forkexec.log") if shared.PathExists(logPath) { os.Remove(logPath) } logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644) if err == nil { syscall.Dup3(int(logFile.Fd()), 1, 0) syscall.Dup3(int(logFile.Fd()), 2, 0) } env := []string{} cmd := []string{} section := "" for _, arg := range args.Extra { // The "cmd" section must come last as it may contain a -- if arg == "--" && section != "cmd" { section = "" continue } if section == "" { section = arg continue } if section == "env" { fields := strings.SplitN(arg, "=", 2) if len(fields) == 2 && fields[0] == "HOME" { opts.Cwd = fields[1] } env = append(env, arg) } else if section == "cmd" { cmd = append(cmd, arg) } else { return -1, fmt.Errorf("Invalid exec section: %s", section) } } opts.Env = env status, err := c.RunCommandNoWait(cmd, opts) if err != nil { return -1, fmt.Errorf("Failed running command: %q", err) } // Send the PID of the executing process. w := os.NewFile(uintptr(3), "attachedPid") defer w.Close() err = json.NewEncoder(w).Encode(status) if err != nil { return -1, fmt.Errorf("Failed sending PID of executing command: %q", err) } var ws syscall.WaitStatus wpid, err := syscall.Wait4(status, &ws, 0, nil) if err != nil || wpid != status { return -1, fmt.Errorf("Failed finding process: %q", err) } if ws.Exited() { return ws.ExitStatus(), nil } if ws.Signaled() { // 128 + n == Fatal error signal "n" return 128 + int(ws.Signal()), nil } return -1, fmt.Errorf("Command failed") } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_daemon.go�����������������������������������������������������������������������0000644�0610621�0607500�00000003315�13172163242�017060� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "os/exec" "os/signal" "runtime/pprof" "syscall" "time" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" ) func cmdDaemon(args *Args) error { // Only root should run this if os.Geteuid() != 0 { return fmt.Errorf("This must be run as root") } if args.CPUProfile != "" { f, err := os.Create(args.CPUProfile) if err != nil { fmt.Printf("Error opening cpu profile file: %s\n", err) return nil } pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() } if args.MemProfile != "" { go memProfiler(args.MemProfile) } neededPrograms := []string{"setfacl", "rsync", "tar", "unsquashfs", "xz"} for _, p := range neededPrograms { _, err := exec.LookPath(p) if err != nil { return err } } if args.PrintGoroutinesEvery > 0 { go func() { for { time.Sleep(time.Duration(args.PrintGoroutinesEvery) * time.Second) logger.Debugf(logger.GetStack()) } }() } d := NewDaemon() d.group = args.Group d.SetupMode = shared.PathExists(shared.VarPath(".setup_mode")) err := d.Init() if err != nil { if d != nil && d.db != nil { d.db.Close() } return err } ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGPWR) signal.Notify(ch, syscall.SIGINT) signal.Notify(ch, syscall.SIGQUIT) signal.Notify(ch, syscall.SIGTERM) s := d.State() select { case sig := <-ch: if sig == syscall.SIGPWR { logger.Infof("Received '%s signal', shutting down containers.", sig) containersShutdown(s, d.Storage) } else { logger.Infof("Received '%s signal', exiting.", sig) } case <-d.shutdownChan: logger.Infof("Asked to shutdown by API, shutting down containers.") containersShutdown(s, d.Storage) } return d.Stop() } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_callhook.go���������������������������������������������������������������������0000644�0610621�0607500�00000002161�13172163242�017407� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "time" "github.com/lxc/lxd/client" ) func cmdCallHook(args *Args) error { // Parse the arguments if len(args.Params) < 3 { return fmt.Errorf("Invalid arguments") } path := args.Params[0] id := args.Params[1] state := args.Params[2] target := "" // Connect to LXD c, err := lxd.ConnectLXDUnix(fmt.Sprintf("%s/unix.socket", path), nil) if err != nil { return err } // Prepare the request URL url := fmt.Sprintf("/internal/containers/%s/on%s", id, state) if state == "stop" { target = os.Getenv("LXC_TARGET") if target == "" { target = "unknown" } url = fmt.Sprintf("%s?target=%s", url, target) } // Setup the request hook := make(chan error, 1) go func() { _, _, err := c.RawQuery("GET", url, nil, "") if err != nil { hook <- err return } hook <- nil }() // Handle the timeout select { case err := <-hook: if err != nil { return err } break case <-time.After(30 * time.Second): return fmt.Errorf("Hook didn't finish within 30s") } if target == "reboot" { return fmt.Errorf("Reboot must be handled by LXD.") } return nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_args_test.go��������������������������������������������������������������������0000644�0610621�0607500�00000005257�13172163242�017617� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "testing" "github.com/stretchr/testify/assert" "github.com/lxc/lxd/shared/cmd" ) // Check the default values of all command line arguments. func TestParse_ArgsDefaults(t *testing.T) { context := cmd.NewMemoryContext(cmd.NewMemoryStreams("")) line := []string{"lxd"} args := &Args{} parser := cmd.NewParser(context, "") parser.Parse(line, args) assert.Equal(t, false, args.Auto) assert.Equal(t, "", args.CPUProfile) assert.Equal(t, false, args.Debug) assert.Equal(t, "", args.Group) assert.Equal(t, false, args.Help) assert.Equal(t, "", args.Logfile) assert.Equal(t, "", args.MemProfile) assert.Equal(t, "", args.NetworkAddress) assert.Equal(t, int64(-1), args.NetworkPort) assert.Equal(t, -1, args.PrintGoroutinesEvery) assert.Equal(t, "", args.StorageBackend) assert.Equal(t, "", args.StorageCreateDevice) assert.Equal(t, int64(-1), args.StorageCreateLoop) assert.Equal(t, "", args.StorageDataset) assert.Equal(t, false, args.Syslog) assert.Equal(t, -1, args.Timeout) assert.Equal(t, "", args.TrustPassword) assert.Equal(t, false, args.Verbose) assert.Equal(t, false, args.Version) } // Check that parsing the command line results in the correct attributes // being set. func TestParse_ArgsCustom(t *testing.T) { context := cmd.NewMemoryContext(cmd.NewMemoryStreams("")) line := []string{ "lxd", "--auto", "--cpuprofile", "lxd.cpu", "--debug", "--group", "lxd", "--help", "--logfile", "lxd.log", "--memprofile", "lxd.mem", "--network-address", "127.0.0.1", "--network-port", "666", "--print-goroutines-every", "10", "--storage-backend", "btrfs", "--storage-create-device", "/dev/sda2", "--storage-create-loop", "8192", "--storage-pool", "default", "--syslog", "--timeout", "30", "--trust-password", "sekret", "--verbose", "--version", } args := &Args{} parser := cmd.NewParser(context, "") parser.Parse(line, args) assert.Equal(t, true, args.Auto) assert.Equal(t, "lxd.cpu", args.CPUProfile) assert.Equal(t, true, args.Debug) assert.Equal(t, "lxd", args.Group) assert.Equal(t, true, args.Help) assert.Equal(t, "lxd.log", args.Logfile) assert.Equal(t, "lxd.mem", args.MemProfile) assert.Equal(t, "127.0.0.1", args.NetworkAddress) assert.Equal(t, int64(666), args.NetworkPort) assert.Equal(t, 10, args.PrintGoroutinesEvery) assert.Equal(t, "btrfs", args.StorageBackend) assert.Equal(t, "/dev/sda2", args.StorageCreateDevice) assert.Equal(t, int64(8192), args.StorageCreateLoop) assert.Equal(t, "default", args.StorageDataset) assert.Equal(t, true, args.Syslog) assert.Equal(t, 30, args.Timeout) assert.Equal(t, "sekret", args.TrustPassword) assert.Equal(t, true, args.Verbose) assert.Equal(t, true, args.Version) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_args.go�������������������������������������������������������������������������0000644�0610621�0607500�00000010171�13172163242�016547� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main // Args contains all supported LXD command line flags. type Args struct { Auto bool `flag:"auto"` CPUProfile string `flag:"cpuprofile"` Debug bool `flag:"debug"` Group string `flag:"group"` Help bool `flag:"help"` Logfile string `flag:"logfile"` MemProfile string `flag:"memprofile"` NetworkAddress string `flag:"network-address"` NetworkPort int64 `flag:"network-port"` PrintGoroutinesEvery int `flag:"print-goroutines-every"` StorageBackend string `flag:"storage-backend"` StorageCreateDevice string `flag:"storage-create-device"` StorageCreateLoop int64 `flag:"storage-create-loop"` StorageDataset string `flag:"storage-pool"` Syslog bool `flag:"syslog"` Timeout int `flag:"timeout"` TrustPassword string `flag:"trust-password"` Verbose bool `flag:"verbose"` Version bool `flag:"version"` // The LXD subcommand, if any (e.g. "init" for "lxd init") Subcommand string // The subcommand parameters (e.g. []string{"foo"} for "lxd import foo"). Params []string // Any extra arguments following the "--" separator. Extra []string } const usage = `Usage: lxd [command] [options] Commands: activateifneeded Check if LXD should be started (at boot) and if so, spawns it through socket activation daemon [--group=lxd] (default command) Start the main LXD daemon init [--auto] [--network-address=IP] [--network-port=8443] [--storage-backend=dir] [--storage-create-device=DEVICE] [--storage-create-loop=SIZE] [--storage-pool=POOL] [--trust-password=] [--preseed] Setup storage and networking ready Tells LXD that any setup-mode configuration has been done and that it can start containers. shutdown [--timeout=60] Perform a clean shutdown of LXD and all running containers waitready [--timeout=15] Wait until LXD is ready to handle requests import <container name> [--force] Import a pre-existing container from storage Common options: --debug Enable debug mode --help Print this help message --logfile FILE Logfile to log to (e.g., /var/log/lxd/lxd.log) --syslog Enable syslog logging --verbose Enable verbose mode --version Print LXD's version number and exit Daemon options: --group GROUP Group which owns the shared socket Daemon debug options: --cpuprofile FILE Enable cpu profiling into the specified file --memprofile FILE Enable memory profiling into the specified file --print-goroutines-every SECONDS For debugging, print a complete stack trace every n seconds Init options: --auto Automatic (non-interactive) mode Init options for non-interactive mode (--auto): --network-address ADDRESS Address to bind LXD to (default: none) --network-port PORT Port to bind LXD to (default: 8443) --storage-backend NAME Storage backend to use (btrfs, dir, lvm or zfs, default: dir) --storage-create-device DEVICE Setup device based storage using DEVICE --storage-create-loop SIZE Setup loop based storage with SIZE in GB --storage-pool NAME Storage pool to use or create --trust-password PASSWORD Password required to add new clients Shutdown options: --timeout SECONDS How long to wait before failing Waitready options: --timeout SECONDS How long to wait before failing Internal commands (don't call these directly): forkexec Execute a command in a container forkgetnet Get container network information forkgetfile Grab a file from a running container forkmigrate Restore a container after migration forkputfile Push a file to a running container forkstart Start a container callhook Call a container hook migratedumpsuccess Indicate that a migration dump was successful netcat Mirror a unix socket to stdin/stdout ` �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/main_activateifneeded.go�������������������������������������������������������������0000644�0610621�0607500�00000003657�13172163242�021112� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" ) func cmdActivateIfNeeded() error { // Only root should run this if os.Geteuid() != 0 { return fmt.Errorf("This must be run as root") } // Don't start a full daemon, we just need DB access d := NewDaemon() d.os.LxcPath = shared.VarPath("containers") if !shared.PathExists(shared.VarPath("lxd.db")) { logger.Debugf("No DB, so no need to start the daemon now.") return nil } err := initializeDbObject(d, shared.VarPath("lxd.db")) if err != nil { return err } /* Load all config values from the database */ err = daemonConfigInit(d.db) if err != nil { return err } // Look for network socket value := daemonConfig["core.https_address"].Get() if value != "" { logger.Debugf("Daemon has core.https_address set, activating...") _, err := lxd.ConnectLXDUnix("", nil) return err } // Load the idmap for unprivileged containers d.os.IdmapSet, err = idmap.DefaultIdmapSet() if err != nil { return err } // Look for auto-started or previously started containers result, err := db.ContainersList(d.db, db.CTypeRegular) if err != nil { return err } for _, name := range result { c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return err } config := c.ExpandedConfig() lastState := config["volatile.last_state.power"] autoStart := config["boot.autostart"] if c.IsRunning() { logger.Debugf("Daemon has running containers, activating...") _, err := lxd.ConnectLXDUnix("", nil) return err } if lastState == "RUNNING" || lastState == "Running" || shared.IsTrue(autoStart) { logger.Debugf("Daemon has auto-started containers, activating...") _, err := lxd.ConnectLXDUnix("", nil) return err } } logger.Debugf("No need to start the daemon now.") return nil } ���������������������������������������������������������������������������������lxd-2.0.11/lxd/main.go������������������������������������������������������������������������������0000644�0610621�0607500�00000005023�13172163242�015533� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "math/rand" "os" "time" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/cmd" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/logging" "github.com/lxc/lxd/shared/version" ) // Global variables var debug bool var verbose bool var execPath string func init() { rand.Seed(time.Now().UTC().UnixNano()) absPath, err := os.Readlink("/proc/self/exe") if err != nil { absPath = "bad-exec-path" } execPath = absPath } func main() { if err := run(); err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } } func run() error { // Pupulate a new Args instance by parsing the command line arguments // passed. context := cmd.DefaultContext() args := &Args{} parser := cmd.NewParser(context, usage) parser.Parse(os.Args, args) // Set the global variables debug = args.Debug verbose = args.Verbose if args.Help { context.Output(usage) return nil } // Deal with --version right here if args.Version { fmt.Println(version.Version) return nil } if len(shared.VarPath("unix.sock")) > 107 { return fmt.Errorf("LXD_DIR is too long, must be < %d", 107-len("unix.sock")) } // Configure logging syslog := "" if args.Syslog { syslog = "lxd" } handler := eventsHandler{} var err error logger.Log, err = logging.GetLogger(syslog, args.Logfile, args.Verbose, args.Debug, handler) if err != nil { fmt.Printf("%s\n", err) return nil } // Process sub-commands if args.Subcommand != "" { // "forkputfile", "forkgetfile", "forkmount" and "forkumount" are handled specially in main_nsexec.go // "forkgetnet" is partially handled in nsexec.go (setns) switch args.Subcommand { // Main commands case "activateifneeded": return cmdActivateIfNeeded() case "daemon": return cmdDaemon(args) case "callhook": return cmdCallHook(args) case "init": return cmdInit(args) case "ready": return cmdReady() case "shutdown": return cmdShutdown(args) case "waitready": return cmdWaitReady(args) // Internal commands case "forkgetnet": return cmdForkGetNet() case "forkmigrate": return cmdForkMigrate(args) case "forkstart": return cmdForkStart(args) case "forkexec": ret, err := cmdForkExec(args) if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) } os.Exit(ret) case "netcat": return cmdNetcat(args) case "migratedumpsuccess": return cmdMigrateDumpSuccess(args) } } else { return cmdDaemon(args) // Default subcommand } context.Output(usage) return fmt.Errorf("Unknown arguments") } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/logging.go���������������������������������������������������������������������������0000644�0610621�0607500�00000003432�13172163242�016237� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "io/ioutil" "os" "time" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared" ) func ExpireLogs(dbObj *sql.DB) error { entries, err := ioutil.ReadDir(shared.LogPath()) if err != nil { return err } result, err := db.ContainersList(dbObj, db.CTypeRegular) if err != nil { return err } newestFile := func(path string, dir os.FileInfo) time.Time { newest := dir.ModTime() entries, err := ioutil.ReadDir(path) if err != nil { return newest } for _, entry := range entries { if entry.ModTime().After(newest) { newest = entry.ModTime() } } return newest } for _, entry := range entries { // Check if the container still exists if shared.StringInSlice(entry.Name(), result) { // Remove any log file which wasn't modified in the past 48 hours logs, err := ioutil.ReadDir(shared.LogPath(entry.Name())) if err != nil { return err } for _, logfile := range logs { path := shared.LogPath(entry.Name(), logfile.Name()) // Always keep the LXC config if logfile.Name() == "lxc.conf" { continue } // Deal with directories (snapshots) if logfile.IsDir() { newest := newestFile(path, logfile) if time.Since(newest).Hours() >= 48 { os.RemoveAll(path) if err != nil { return err } } continue } // Individual files if time.Since(logfile.ModTime()).Hours() >= 48 { err := os.Remove(path) if err != nil { return err } } } } else { // Empty directory if unchanged in the past 24 hours path := shared.LogPath(entry.Name()) newest := newestFile(path, entry) if time.Since(newest).Hours() >= 24 { err := os.RemoveAll(path) if err != nil { return err } } } } return nil } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/images.go����������������������������������������������������������������������������0000644�0610621�0607500�00000102141�13172163242�016053� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "bytes" "crypto/sha256" "database/sql" "encoding/json" "fmt" "io" "io/ioutil" "mime" "mime/multipart" "net/http" "net/url" "os" "os/exec" "strconv" "strings" "sync" "syscall" "time" "github.com/gorilla/mux" "gopkg.in/yaml.v2" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/logging" "github.com/lxc/lxd/shared/osarch" "github.com/lxc/lxd/shared/version" log "gopkg.in/inconshreveable/log15.v2" ) /* We only want a single publish running at any one time. The CPU and I/O load of publish is such that running multiple ones in parallel takes longer than running them serially. Additionally, publishing the same container or container snapshot twice would lead to storage problem, not to mention a conflict at the end for whichever finishes last. */ var imagePublishLock sync.Mutex func detectCompression(fname string) ([]string, string, error) { f, err := os.Open(fname) if err != nil { return []string{""}, "", err } defer f.Close() // read header parts to detect compression method // bz2 - 2 bytes, 'BZ' signature/magic number // gz - 2 bytes, 0x1f 0x8b // lzma - 6 bytes, { [0x000, 0xE0], '7', 'z', 'X', 'Z', 0x00 } - // xy - 6 bytes, header format { 0xFD, '7', 'z', 'X', 'Z', 0x00 } // tar - 263 bytes, trying to get ustar from 257 - 262 header := make([]byte, 263) _, err = f.Read(header) if err != nil { return []string{""}, "", err } switch { case bytes.Equal(header[0:2], []byte{'B', 'Z'}): return []string{"-jxf"}, ".tar.bz2", nil case bytes.Equal(header[0:2], []byte{0x1f, 0x8b}): return []string{"-zxf"}, ".tar.gz", nil case (bytes.Equal(header[1:5], []byte{'7', 'z', 'X', 'Z'}) && header[0] == 0xFD): return []string{"-Jxf"}, ".tar.xz", nil case (bytes.Equal(header[1:5], []byte{'7', 'z', 'X', 'Z'}) && header[0] != 0xFD): return []string{"--lzma", "-xf"}, ".tar.lzma", nil case bytes.Equal(header[0:3], []byte{0x5d, 0x00, 0x00}): return []string{"--lzma", "-xf"}, ".tar.lzma", nil case bytes.Equal(header[257:262], []byte{'u', 's', 't', 'a', 'r'}): return []string{"-xf"}, ".tar", nil case bytes.Equal(header[0:4], []byte{'h', 's', 'q', 's'}): return []string{""}, ".squashfs", nil default: return []string{""}, "", fmt.Errorf("Unsupported compression") } } func unpack(file string, path string, sType storageType) error { extractArgs, extension, err := detectCompression(file) if err != nil { return err } command := "" args := []string{} if strings.HasPrefix(extension, ".tar") { command = "tar" if runningInUserns { args = append(args, "--wildcards") args = append(args, "--exclude=dev/*") args = append(args, "--exclude=./dev/*") args = append(args, "--exclude=rootfs/dev/*") args = append(args, "--exclude=rootfs/./dev/*") } args = append(args, "-C", path, "--numeric-owner") args = append(args, extractArgs...) args = append(args, file) } else if strings.HasPrefix(extension, ".squashfs") { command = "unsquashfs" args = append(args, "-f", "-d", path, "-n") // Limit unsquashfs chunk size to 10% of memory and up to 256MB (default) // When running on a low memory system, also disable multi-processing mem, err := deviceTotalMemory() mem = mem / 1024 / 1024 / 10 if err == nil && mem < 256 { args = append(args, "-da", fmt.Sprintf("%d", mem), "-fr", fmt.Sprintf("%d", mem), "-p", "1") } args = append(args, file) } else { return fmt.Errorf("Unsupported image format: %s", extension) } output, err := shared.RunCommand(command, args...) if err != nil { // Check if we ran out of space fs := syscall.Statfs_t{} err1 := syscall.Statfs(path, &fs) if err1 != nil { return err1 } // Check if we're running out of space if int64(fs.Bfree) < int64(2*fs.Bsize) { if sType == storageTypeLvm { return fmt.Errorf("Unable to unpack image, run out of disk space (consider increasing storage.lvm_volume_size).") } else { return fmt.Errorf("Unable to unpack image, run out of disk space.") } } co := output logger.Debugf("Unpacking failed") logger.Debugf(co) // Truncate the output to a single line for inclusion in the error // message. The first line isn't guaranteed to pinpoint the issue, // but it's better than nothing and better than a multi-line message. return fmt.Errorf("Unpack failed, %s. %s", err, strings.SplitN(co, "\n", 2)[0]) } return nil } func unpackImage(imagefname string, destpath string, sType storageType) error { err := unpack(imagefname, destpath, sType) if err != nil { return err } rootfsPath := fmt.Sprintf("%s/rootfs", destpath) if shared.PathExists(imagefname + ".rootfs") { err = os.MkdirAll(rootfsPath, 0755) if err != nil { return fmt.Errorf("Error creating rootfs directory") } err = unpack(imagefname+".rootfs", rootfsPath, sType) if err != nil { return err } } if !shared.PathExists(rootfsPath) { return fmt.Errorf("Image is missing a rootfs: %s", imagefname) } return nil } func compressFile(path string, compress string) (string, error) { reproducible := []string{"gzip"} args := []string{"-c"} if shared.StringInSlice(compress, reproducible) { args = append(args, "-n") } args = append(args, path) cmd := exec.Command(compress, args...) outfile, err := os.Create(path + ".compressed") if err != nil { return "", err } defer outfile.Close() cmd.Stdout = outfile err = cmd.Run() if err != nil { os.Remove(outfile.Name()) return "", err } return outfile.Name(), nil } type templateEntry struct { When []string `yaml:"when"` CreateOnly bool `yaml:"create_only"` Template string `yaml:"template"` Properties map[string]string `yaml:"properties"` } type imageMetadata struct { Architecture string `yaml:"architecture"` CreationDate int64 `yaml:"creation_date"` ExpiryDate int64 `yaml:"expiry_date"` Properties map[string]string `yaml:"properties"` Templates map[string]*templateEntry `yaml:"templates"` } /* * This function takes a container or snapshot from the local image server and * exports it as an image. */ func imgPostContInfo(d *Daemon, r *http.Request, req api.ImagesPost, builddir string) (*api.Image, error) { info := api.Image{} info.Properties = map[string]string{} name := req.Source.Name ctype := req.Source.Type if ctype == "" || name == "" { return nil, fmt.Errorf("No source provided") } switch ctype { case "snapshot": if !shared.IsSnapshot(name) { return nil, fmt.Errorf("Not a snapshot") } case "container": if shared.IsSnapshot(name) { return nil, fmt.Errorf("This is a snapshot") } default: return nil, fmt.Errorf("Bad type") } info.Filename = req.Filename switch req.Public { case true: info.Public = true case false: info.Public = false } c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return nil, err } // Build the actual image file tarfile, err := ioutil.TempFile(builddir, "lxd_build_tar_") if err != nil { return nil, err } defer os.Remove(tarfile.Name()) if err := c.Export(tarfile, req.Properties); err != nil { tarfile.Close() return nil, err } tarfile.Close() var compressedPath string compress := daemonConfig["images.compression_algorithm"].Get() if compress != "none" { compressedPath, err = compressFile(tarfile.Name(), compress) if err != nil { return nil, err } } else { compressedPath = tarfile.Name() } defer os.Remove(compressedPath) sha256 := sha256.New() tarf, err := os.Open(compressedPath) if err != nil { return nil, err } info.Size, err = io.Copy(sha256, tarf) tarf.Close() if err != nil { return nil, err } info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil)) _, _, err = db.ImageGet(d.db, info.Fingerprint, false, true) if err == nil { return nil, fmt.Errorf("The image already exists: %s", info.Fingerprint) } /* rename the the file to the expected name so our caller can use it */ finalName := shared.VarPath("images", info.Fingerprint) err = shared.FileMove(compressedPath, finalName) if err != nil { return nil, err } info.Architecture, _ = osarch.ArchitectureName(c.Architecture()) info.Properties = req.Properties // Create storage entry err = d.Storage.ImageCreate(info.Fingerprint) if err != nil { return nil, err } // Create the database entry err = db.ImageInsert(d.db, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties) if err != nil { return nil, err } return &info, nil } func imgPostRemoteInfo(d *Daemon, req api.ImagesPost, op *operation) (*api.Image, error) { var err error var hash string if req.Source.Fingerprint != "" { hash = req.Source.Fingerprint } else if req.Source.Alias != "" { hash = req.Source.Alias } else { return nil, fmt.Errorf("must specify one of alias or fingerprint for init from image") } info, err := d.ImageDownload(op, req.Source.Server, req.Source.Protocol, req.Source.Certificate, req.Source.Secret, hash, false, req.AutoUpdate) if err != nil { return nil, err } id, info, err := db.ImageGet(d.db, info.Fingerprint, false, true) if err != nil { return nil, err } // Allow overriding or adding properties for k, v := range req.Properties { info.Properties[k] = v } // Update the DB record if needed if req.Public || req.AutoUpdate || req.Filename != "" || len(req.Properties) > 0 { err = db.ImageUpdate(d.db, id, req.Filename, info.Size, req.Public, req.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties) if err != nil { return nil, err } } return info, nil } func imgPostURLInfo(d *Daemon, req api.ImagesPost, op *operation) (*api.Image, error) { var err error if req.Source.URL == "" { return nil, fmt.Errorf("Missing URL") } myhttp, err := util.HTTPClient("", d.proxy) if err != nil { return nil, err } // Resolve the image URL head, err := http.NewRequest("HEAD", req.Source.URL, nil) if err != nil { return nil, err } architecturesStr := []string{} for _, arch := range d.os.Architectures { architecturesStr = append(architecturesStr, fmt.Sprintf("%d", arch)) } head.Header.Set("User-Agent", version.UserAgent) head.Header.Set("LXD-Server-Architectures", strings.Join(architecturesStr, ", ")) head.Header.Set("LXD-Server-Version", version.Version) raw, err := myhttp.Do(head) if err != nil { return nil, err } hash := raw.Header.Get("LXD-Image-Hash") if hash == "" { return nil, fmt.Errorf("Missing LXD-Image-Hash header") } url := raw.Header.Get("LXD-Image-URL") if url == "" { return nil, fmt.Errorf("Missing LXD-Image-URL header") } // Import the image info, err := d.ImageDownload(op, url, "direct", "", "", hash, false, req.AutoUpdate) if err != nil { return nil, err } id, info, err := db.ImageGet(d.db, info.Fingerprint, false, false) if err != nil { return nil, err } // Allow overriding or adding properties for k, v := range req.Properties { info.Properties[k] = v } if req.Public || req.AutoUpdate || req.Filename != "" || len(req.Properties) > 0 { err = db.ImageUpdate(d.db, id, req.Filename, info.Size, req.Public, req.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties) if err != nil { return nil, err } } return info, nil } func getImgPostInfo(d *Daemon, r *http.Request, builddir string, post *os.File) (*api.Image, error) { info := api.Image{} var imageMeta *imageMetadata logger := logging.AddContext(logger.Log, log.Ctx{"function": "getImgPostInfo"}) public, _ := strconv.Atoi(r.Header.Get("X-LXD-public")) info.Public = public == 1 propHeaders := r.Header[http.CanonicalHeaderKey("X-LXD-properties")] ctype, ctypeParams, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil { ctype = "application/octet-stream" } sha256 := sha256.New() var size int64 if ctype == "multipart/form-data" { // Create a temporary file for the image tarball imageTarf, err := ioutil.TempFile(builddir, "lxd_tar_") if err != nil { return nil, err } defer os.Remove(imageTarf.Name()) // Parse the POST data post.Seek(0, 0) mr := multipart.NewReader(post, ctypeParams["boundary"]) // Get the metadata tarball part, err := mr.NextPart() if err != nil { return nil, err } if part.FormName() != "metadata" { return nil, fmt.Errorf("Invalid multipart image") } size, err = io.Copy(io.MultiWriter(imageTarf, sha256), part) info.Size += size imageTarf.Close() if err != nil { logger.Error( "Failed to copy the image tarfile", log.Ctx{"err": err}) return nil, err } // Get the rootfs tarball part, err = mr.NextPart() if err != nil { logger.Error( "Failed to get the next part", log.Ctx{"err": err}) return nil, err } if part.FormName() != "rootfs" { logger.Error( "Invalid multipart image") return nil, fmt.Errorf("Invalid multipart image") } // Create a temporary file for the rootfs tarball rootfsTarf, err := ioutil.TempFile(builddir, "lxd_tar_") if err != nil { return nil, err } defer os.Remove(rootfsTarf.Name()) size, err = io.Copy(io.MultiWriter(rootfsTarf, sha256), part) info.Size += size rootfsTarf.Close() if err != nil { logger.Error( "Failed to copy the rootfs tarfile", log.Ctx{"err": err}) return nil, err } info.Filename = part.FileName() info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil)) expectedFingerprint := r.Header.Get("X-LXD-fingerprint") if expectedFingerprint != "" && info.Fingerprint != expectedFingerprint { err = fmt.Errorf("fingerprints don't match, got %s expected %s", info.Fingerprint, expectedFingerprint) return nil, err } imageMeta, err = getImageMetadata(imageTarf.Name()) if err != nil { logger.Error( "Failed to get image metadata", log.Ctx{"err": err}) return nil, err } imgfname := shared.VarPath("images", info.Fingerprint) err = shared.FileMove(imageTarf.Name(), imgfname) if err != nil { logger.Error( "Failed to move the image tarfile", log.Ctx{ "err": err, "source": imageTarf.Name(), "dest": imgfname}) return nil, err } rootfsfname := shared.VarPath("images", info.Fingerprint+".rootfs") err = shared.FileMove(rootfsTarf.Name(), rootfsfname) if err != nil { logger.Error( "Failed to move the rootfs tarfile", log.Ctx{ "err": err, "source": rootfsTarf.Name(), "dest": imgfname}) return nil, err } } else { post.Seek(0, 0) size, err = io.Copy(sha256, post) info.Size = size logger.Debug("Tar size", log.Ctx{"size": size}) if err != nil { logger.Error( "Failed to copy the tarfile", log.Ctx{"err": err}) return nil, err } info.Filename = r.Header.Get("X-LXD-filename") info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil)) expectedFingerprint := r.Header.Get("X-LXD-fingerprint") if expectedFingerprint != "" && info.Fingerprint != expectedFingerprint { logger.Error( "Fingerprints don't match", log.Ctx{ "got": info.Fingerprint, "expected": expectedFingerprint}) err = fmt.Errorf( "fingerprints don't match, got %s expected %s", info.Fingerprint, expectedFingerprint) return nil, err } imageMeta, err = getImageMetadata(post.Name()) if err != nil { logger.Error( "Failed to get image metadata", log.Ctx{"err": err}) return nil, err } imgfname := shared.VarPath("images", info.Fingerprint) err = shared.FileMove(post.Name(), imgfname) if err != nil { logger.Error( "Failed to move the tarfile", log.Ctx{ "err": err, "source": post.Name(), "dest": imgfname}) return nil, err } } info.Architecture = imageMeta.Architecture info.CreatedAt = time.Unix(imageMeta.CreationDate, 0) info.ExpiresAt = time.Unix(imageMeta.ExpiryDate, 0) info.Properties = imageMeta.Properties if len(propHeaders) > 0 { for _, ph := range propHeaders { p, _ := url.ParseQuery(ph) for pkey, pval := range p { info.Properties[pkey] = pval[0] } } } // Create storage entry err = d.Storage.ImageCreate(info.Fingerprint) if err != nil { return nil, err } // Check if the image already exists exists, err := db.ImageExists(d.db, info.Fingerprint) if err != nil { return nil, err } if exists { return nil, fmt.Errorf("Image with same fingerprint already exists") } // Create the database entry err = db.ImageInsert(d.db, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties) if err != nil { return nil, err } return &info, nil } func imagesPost(d *Daemon, r *http.Request) Response { var err error // create a directory under which we keep everything while building builddir, err := ioutil.TempDir(shared.VarPath("images"), "lxd_build_") if err != nil { return InternalError(err) } cleanup := func(path string, fd *os.File) { if fd != nil { fd.Close() } if err := os.RemoveAll(path); err != nil { logger.Debugf("Error deleting temporary directory \"%s\": %s", path, err) } } // Store the post data to disk post, err := ioutil.TempFile(builddir, "lxd_post_") if err != nil { cleanup(builddir, nil) return InternalError(err) } _, err = io.Copy(post, r.Body) if err != nil { cleanup(builddir, post) return InternalError(err) } // Is this a container request? post.Seek(0, 0) decoder := json.NewDecoder(post) imageUpload := false req := api.ImagesPost{} err = decoder.Decode(&req) if err != nil { if r.Header.Get("Content-Type") == "application/json" { return BadRequest(err) } imageUpload = true } if !imageUpload && !shared.StringInSlice(req.Source.Type, []string{"container", "snapshot", "image", "url"}) { cleanup(builddir, post) return InternalError(fmt.Errorf("Invalid images JSON")) } // Begin background operation run := func(op *operation) error { var err error var info *api.Image // Setup the cleanup function defer cleanup(builddir, post) if imageUpload { /* Processing image upload */ info, err = getImgPostInfo(d, r, builddir, post) } else { if req.Source.Type == "image" { /* Processing image copy from remote */ info, err = imgPostRemoteInfo(d, req, op) } else if req.Source.Type == "url" { /* Processing image copy from URL */ info, err = imgPostURLInfo(d, req, op) } else { /* Processing image creation from container */ imagePublishLock.Lock() info, err = imgPostContInfo(d, r, req, builddir) imagePublishLock.Unlock() } } if err != nil { return err } // Set the metadata metadata := make(map[string]string) metadata["fingerprint"] = info.Fingerprint metadata["size"] = strconv.FormatInt(info.Size, 10) op.UpdateMetadata(metadata) return nil } op, err := operationCreate(operationClassTask, nil, nil, run, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func getImageMetadata(fname string) (*imageMetadata, error) { metadataName := "metadata.yaml" compressionArgs, _, err := detectCompression(fname) if err != nil { return nil, fmt.Errorf( "detectCompression failed, err='%v', tarfile='%s'", err, fname) } args := []string{"-O"} args = append(args, compressionArgs...) args = append(args, fname, metadataName) // read the metadata.yaml output, err := shared.RunCommand("tar", args...) if err != nil { outputLines := strings.Split(output, "\n") return nil, fmt.Errorf("Could not extract image %s from tar: %v (%s)", metadataName, err, outputLines[0]) } metadata := imageMetadata{} err = yaml.Unmarshal([]byte(output), &metadata) if err != nil { return nil, fmt.Errorf("Could not parse %s: %v", metadataName, err) } _, err = osarch.ArchitectureId(metadata.Architecture) if err != nil { return nil, err } if metadata.CreationDate == 0 { return nil, fmt.Errorf("Missing creation date.") } return &metadata, nil } func doImagesGet(d *Daemon, recursion bool, public bool) (interface{}, error) { results, err := db.ImagesGet(d.db, public) if err != nil { return []string{}, err } resultString := make([]string, len(results)) resultMap := make([]*api.Image, len(results)) i := 0 for _, name := range results { if !recursion { url := fmt.Sprintf("/%s/images/%s", version.APIVersion, name) resultString[i] = url } else { image, response := doImageGet(d.db, name, public) if response != nil { continue } resultMap[i] = image } i++ } if !recursion { return resultString, nil } return resultMap, nil } func imagesGet(d *Daemon, r *http.Request) Response { public := !util.IsTrustedClient(r, d.clientCerts) result, err := doImagesGet(d, util.IsRecursionRequest(r), public) if err != nil { return SmartError(err) } return SyncResponse(true, result) } var imagesCmd = Command{name: "images", post: imagesPost, untrustedGet: true, get: imagesGet} func autoUpdateImages(d *Daemon) { logger.Infof("Updating images") images, err := db.ImagesGet(d.db, false) if err != nil { logger.Error("Unable to retrieve the list of images", log.Ctx{"err": err}) return } for _, fingerprint := range images { id, info, err := db.ImageGet(d.db, fingerprint, false, true) if err != nil { logger.Error("Error loading image", log.Ctx{"err": err, "fp": fingerprint}) continue } if !info.AutoUpdate { continue } autoUpdateImage(d, nil, id, info) } logger.Infof("Done updating images") } // Update a single image. The operation can be nil, if no progress tracking is needed. // Returns whether the image has been updated. func autoUpdateImage(d *Daemon, op *operation, id int, info *api.Image) error { fingerprint := info.Fingerprint _, source, err := db.ImageSourceGet(d.db, id) if err != nil { logger.Error("Error getting source image", log.Ctx{"err": err, "fp": fingerprint}) return err } logger.Debug("Processing image", log.Ctx{"fp": fingerprint, "server": source.Server, "protocol": source.Protocol, "alias": source.Alias}) // Set operation metadata to indicate whether a refresh happened setRefreshResult := func(result bool) { if op == nil { return } metadata := map[string]interface{}{"refreshed": result} op.UpdateMetadata(metadata) } newInfo, err := d.ImageDownload(op, source.Server, source.Protocol, source.Certificate, "", source.Alias, false, true) if err != nil { logger.Error("Failed to update the image", log.Ctx{"err": err, "fp": fingerprint}) return err } // Image didn't change, nothing to do. hash := newInfo.Fingerprint if hash == fingerprint { setRefreshResult(false) return nil } newId, _, err := db.ImageGet(d.db, hash, false, true) if err != nil { logger.Error("Error loading image", log.Ctx{"err": err, "fp": hash}) return err } if info.Cached { err = db.ImageLastAccessInit(d.db, hash) if err != nil { logger.Error("Error setting cached flag", log.Ctx{"err": err, "fp": hash}) return err } } err = db.ImageLastAccessUpdate(d.db, hash, info.LastUsedAt) if err != nil { logger.Error("Error setting last use date", log.Ctx{"err": err, "fp": hash}) return err } err = db.ImageAliasesMove(d.db, id, newId) if err != nil { logger.Error("Error moving aliases", log.Ctx{"err": err, "fp": hash}) return err } err = doDeleteImage(d, fingerprint) if err != nil { logger.Error("Error deleting image", log.Ctx{"err": err, "fp": fingerprint}) } setRefreshResult(true) return nil } func pruneExpiredImages(d *Daemon) { // Get the list of expired images. expiry := daemonConfig["images.remote_cache_expiry"].GetInt64() // Check if we're supposed to prune something if expiry <= 0 { return } logger.Infof("Pruning expired images") images, err := db.ImagesGetExpired(d.db, expiry) if err != nil { logger.Error("Unable to retrieve the list of expired images", log.Ctx{"err": err}) return } // Delete them for _, fp := range images { if err := doDeleteImage(d, fp); err != nil { logger.Error("Error deleting image", log.Ctx{"err": err, "fp": fp}) } } logger.Infof("Done pruning expired images") } func doDeleteImage(d *Daemon, fingerprint string) error { id, imgInfo, err := db.ImageGet(d.db, fingerprint, false, false) if err != nil { return err } // get storage before deleting images/$fp because we need to // look at the path s, err := storageForImage(d.State(), d.Storage, imgInfo) if err != nil { logger.Error("error detecting image storage backend", log.Ctx{"fingerprint": imgInfo.Fingerprint, "err": err}) } else { // Remove the image from storage backend if err = s.ImageDelete(imgInfo.Fingerprint); err != nil { logger.Error("error deleting the image from storage backend", log.Ctx{"fingerprint": imgInfo.Fingerprint, "err": err}) } } // Remove main image file fname := shared.VarPath("images", imgInfo.Fingerprint) if shared.PathExists(fname) { err = os.Remove(fname) if err != nil { logger.Debugf("Error deleting image file %s: %s", fname, err) } } // Remove the rootfs file fname = shared.VarPath("images", imgInfo.Fingerprint) + ".rootfs" if shared.PathExists(fname) { err = os.Remove(fname) if err != nil { logger.Debugf("Error deleting image file %s: %s", fname, err) } } // Remove the DB entry if err = db.ImageDelete(d.db, id); err != nil { return err } return nil } func imageDelete(d *Daemon, r *http.Request) Response { fingerprint := mux.Vars(r)["fingerprint"] rmimg := func(op *operation) error { return doDeleteImage(d, fingerprint) } resources := map[string][]string{} resources["images"] = []string{fingerprint} op, err := operationCreate(operationClassTask, resources, nil, rmimg, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func doImageGet(dbObj *sql.DB, fingerprint string, public bool) (*api.Image, Response) { _, imgInfo, err := db.ImageGet(dbObj, fingerprint, public, false) if err != nil { return nil, SmartError(err) } return imgInfo, nil } func imageValidSecret(fingerprint string, secret string) bool { for _, op := range operations { if op.resources == nil { continue } opImages, ok := op.resources["images"] if !ok { continue } if !shared.StringInSlice(fingerprint, opImages) { continue } opSecret, ok := op.metadata["secret"] if !ok { continue } if opSecret == secret { // Token is single-use, so cancel it now op.Cancel() return true } } return false } func imageGet(d *Daemon, r *http.Request) Response { fingerprint := mux.Vars(r)["fingerprint"] public := !util.IsTrustedClient(r, d.clientCerts) secret := r.FormValue("secret") info, response := doImageGet(d.db, fingerprint, false) if response != nil { return response } if !info.Public && public && !imageValidSecret(info.Fingerprint, secret) { return NotFound } return SyncResponse(true, info) } func imagePut(d *Daemon, r *http.Request) Response { fingerprint := mux.Vars(r)["fingerprint"] req := api.ImagePut{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } id, info, err := db.ImageGet(d.db, fingerprint, false, false) if err != nil { return SmartError(err) } err = db.ImageUpdate(d.db, id, info.Filename, info.Size, req.Public, req.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, req.Properties) if err != nil { return SmartError(err) } return EmptySyncResponse } var imageCmd = Command{name: "images/{fingerprint}", untrustedGet: true, get: imageGet, put: imagePut, delete: imageDelete} func aliasesPost(d *Daemon, r *http.Request) Response { req := api.ImageAliasesPost{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } if req.Name == "" || req.Target == "" { return BadRequest(fmt.Errorf("name and target are required")) } // This is just to see if the alias name already exists. _, _, err := db.ImageAliasGet(d.db, req.Name, true) if err == nil { return Conflict } id, _, err := db.ImageGet(d.db, req.Target, false, false) if err != nil { return SmartError(err) } err = db.ImageAliasAdd(d.db, req.Name, id, req.Description) if err != nil { return SmartError(err) } return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/images/aliases/%s", version.APIVersion, req.Name)) } func aliasesGet(d *Daemon, r *http.Request) Response { recursion := util.IsRecursionRequest(r) q := "SELECT name FROM images_aliases" var name string inargs := []interface{}{} outfmt := []interface{}{name} results, err := db.QueryScan(d.db, q, inargs, outfmt) if err != nil { return BadRequest(err) } responseStr := []string{} responseMap := []api.ImageAliasesEntry{} for _, res := range results { name = res[0].(string) if !recursion { url := fmt.Sprintf("/%s/images/aliases/%s", version.APIVersion, name) responseStr = append(responseStr, url) } else { isTrustedClient := util.IsTrustedClient(r, d.clientCerts) _, alias, err := db.ImageAliasGet(d.db, name, isTrustedClient) if err != nil { continue } responseMap = append(responseMap, alias) } } if !recursion { return SyncResponse(true, responseStr) } return SyncResponse(true, responseMap) } func aliasGet(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] _, alias, err := db.ImageAliasGet(d.db, name, util.IsTrustedClient(r, d.clientCerts)) if err != nil { return SmartError(err) } return SyncResponse(true, alias) } func aliasDelete(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] _, _, err := db.ImageAliasGet(d.db, name, true) if err != nil { return SmartError(err) } err = db.ImageAliasDelete(d.db, name) if err != nil { return SmartError(err) } return EmptySyncResponse } func aliasPut(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] req := api.ImageAliasesEntryPut{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } if req.Target == "" { return BadRequest(fmt.Errorf("The target field is required")) } id, _, err := db.ImageAliasGet(d.db, name, true) if err != nil { return SmartError(err) } imageId, _, err := db.ImageGet(d.db, req.Target, false, false) if err != nil { return SmartError(err) } err = db.ImageAliasUpdate(d.db, id, imageId, req.Description) if err != nil { return SmartError(err) } return EmptySyncResponse } func aliasPost(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] req := api.ImageAliasesEntryPost{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } // Check that the name isn't already in use id, _, _ := db.ImageAliasGet(d.db, req.Name, true) if id > 0 { return Conflict } id, _, err := db.ImageAliasGet(d.db, name, true) if err != nil { return SmartError(err) } err = db.ImageAliasRename(d.db, id, req.Name) if err != nil { return SmartError(err) } return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/images/aliases/%s", version.APIVersion, req.Name)) } func imageExport(d *Daemon, r *http.Request) Response { fingerprint := mux.Vars(r)["fingerprint"] public := !util.IsTrustedClient(r, d.clientCerts) secret := r.FormValue("secret") _, imgInfo, err := db.ImageGet(d.db, fingerprint, false, false) if err != nil { return SmartError(err) } if !imgInfo.Public && public && !imageValidSecret(imgInfo.Fingerprint, secret) { return NotFound } imagePath := shared.VarPath("images", imgInfo.Fingerprint) rootfsPath := imagePath + ".rootfs" _, ext, err := detectCompression(imagePath) if err != nil { ext = "" } filename := fmt.Sprintf("%s%s", imgInfo.Fingerprint, ext) if shared.PathExists(rootfsPath) { files := make([]fileResponseEntry, 2) files[0].identifier = "metadata" files[0].path = imagePath files[0].filename = "meta-" + filename // Recompute the extension for the root filesystem, it may use a different // compression algorithm than the metadata. _, ext, err = detectCompression(rootfsPath) if err != nil { ext = "" } filename = fmt.Sprintf("%s%s", imgInfo.Fingerprint, ext) files[1].identifier = "rootfs" files[1].path = rootfsPath files[1].filename = filename return FileResponse(r, files, nil, false) } files := make([]fileResponseEntry, 1) files[0].identifier = filename files[0].path = imagePath files[0].filename = filename return FileResponse(r, files, nil, false) } func imageSecret(d *Daemon, r *http.Request) Response { fingerprint := mux.Vars(r)["fingerprint"] _, imgInfo, err := db.ImageGet(d.db, fingerprint, false, false) if err != nil { return SmartError(err) } secret, err := shared.RandomCryptoString() if err != nil { return InternalError(err) } meta := shared.Jmap{} meta["secret"] = secret resources := map[string][]string{} resources["images"] = []string{imgInfo.Fingerprint} op, err := operationCreate(operationClassToken, resources, meta, nil, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } var imagesExportCmd = Command{name: "images/{fingerprint}/export", untrustedGet: true, get: imageExport} var imagesSecretCmd = Command{name: "images/{fingerprint}/secret", post: imageSecret} var aliasesCmd = Command{name: "images/aliases", post: aliasesPost, get: aliasesGet} var aliasCmd = Command{name: "images/aliases/{name:.*}", untrustedGet: true, get: aliasGet, delete: aliasDelete, put: aliasPut, post: aliasPost} �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/events.go����������������������������������������������������������������������������0000644�0610621�0607500�00000006163�13172163242�016121� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "net/http" "strings" "sync" "time" "github.com/gorilla/websocket" "github.com/pborman/uuid" log "gopkg.in/inconshreveable/log15.v2" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" ) type eventsHandler struct { } func logContextMap(ctx []interface{}) map[string]string { var key string ctxMap := map[string]string{} for _, entry := range ctx { if key == "" { key = entry.(string) } else { ctxMap[key] = fmt.Sprintf("%v", entry) key = "" } } return ctxMap } func (h eventsHandler) Log(r *log.Record) error { eventSend("logging", shared.Jmap{ "message": r.Msg, "level": r.Lvl.String(), "context": logContextMap(r.Ctx)}) return nil } var eventsLock sync.Mutex var eventListeners map[string]*eventListener = make(map[string]*eventListener) type eventListener struct { connection *websocket.Conn messageTypes []string active chan bool id string lock sync.Mutex done bool } type eventsServe struct { req *http.Request } func (r *eventsServe) Render(w http.ResponseWriter) error { return eventsSocket(r.req, w) } func (r *eventsServe) String() string { return "event handler" } func eventsSocket(r *http.Request, w http.ResponseWriter) error { listener := eventListener{} typeStr := r.FormValue("type") if typeStr == "" { typeStr = "logging,operation" } c, err := shared.WebsocketUpgrader.Upgrade(w, r, nil) if err != nil { return err } listener.active = make(chan bool, 1) listener.connection = c listener.id = uuid.NewRandom().String() listener.messageTypes = strings.Split(typeStr, ",") eventsLock.Lock() eventListeners[listener.id] = &listener eventsLock.Unlock() logger.Debugf("New events listener: %s", listener.id) <-listener.active return nil } func eventsGet(d *Daemon, r *http.Request) Response { return &eventsServe{r} } var eventsCmd = Command{name: "events", get: eventsGet} func eventSend(eventType string, eventMessage interface{}) error { event := shared.Jmap{} event["type"] = eventType event["timestamp"] = time.Now() event["metadata"] = eventMessage body, err := json.Marshal(event) if err != nil { return err } eventsLock.Lock() listeners := eventListeners for _, listener := range listeners { if !shared.StringInSlice(eventType, listener.messageTypes) { continue } go func(listener *eventListener, body []byte) { // Check that the listener still exists if listener == nil { return } // Ensure there is only a single even going out at the time listener.lock.Lock() defer listener.lock.Unlock() // Make sure we're not done already if listener.done { return } err = listener.connection.WriteMessage(websocket.TextMessage, body) if err != nil { // Remove the listener from the list eventsLock.Lock() delete(eventListeners, listener.id) eventsLock.Unlock() // Disconnect the listener listener.connection.Close() listener.active <- false listener.done = true logger.Debugf("Disconnected events listener: %s", listener.id) } }(listener, body) } eventsLock.Unlock() return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/devlxd_test.go�����������������������������������������������������������������������0000644�0610621�0607500�00000005167�13172163242�017145� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "net" "net/http" "os" "strings" "testing" ) var testDir string type DevLxdDialer struct { Path string } func (d DevLxdDialer) DevLxdDial(network, path string) (net.Conn, error) { addr, err := net.ResolveUnixAddr("unix", d.Path) if err != nil { return nil, err } conn, err := net.DialUnix("unix", nil, addr) if err != nil { return nil, err } return conn, err } func setupDir() error { var err error testDir, err = ioutil.TempDir("", "lxd_test_devlxd_") if err != nil { return err } err = os.Chmod(testDir, 0700) if err != nil { return err } os.MkdirAll(fmt.Sprintf("%s/devlxd", testDir), 0755) return os.Setenv("LXD_DIR", testDir) } func setupSocket() (*net.UnixListener, error) { setupDir() return createAndBindDevLxd() } func connect(path string) (*net.UnixConn, error) { addr, err := net.ResolveUnixAddr("unix", path) if err != nil { return nil, err } conn, err := net.DialUnix("unix", nil, addr) if err != nil { return nil, err } return conn, nil } func TestCredsSendRecv(t *testing.T) { result := make(chan int32, 1) listener, err := setupSocket() if err != nil { t.Fatal(err) } defer listener.Close() defer os.RemoveAll(testDir) go func() { conn, err := listener.AcceptUnix() if err != nil { t.Log(err) result <- -1 return } defer conn.Close() cred, err := getCred(conn) if err != nil { t.Log(err) result <- -1 return } result <- cred.pid }() conn, err := connect(fmt.Sprintf("%s/devlxd/sock", testDir)) if err != nil { t.Fatal(err) } defer conn.Close() pid := <-result if pid != int32(os.Getpid()) { t.Fatal("pid mismatch: ", pid, os.Getpid()) } } /* * Here we're not really testing the API functionality (we can't, since it * expects us to be inside a container to work), but it is useful to test that * all the grotty connection extracting stuff works (that is, it gets to the * point where it realizes the pid isn't in a container without crashing). */ func TestHttpRequest(t *testing.T) { if err := setupDir(); err != nil { t.Fatal(err) } defer os.RemoveAll(testDir) d := NewDaemon() err := d.Init() if err != nil { t.Fatal(err) } defer d.Stop() c := http.Client{Transport: &http.Transport{Dial: DevLxdDialer{Path: fmt.Sprintf("%s/devlxd/sock", testDir)}.DevLxdDial}} raw, err := c.Get("http://1.0") if err != nil { t.Fatal(err) } if raw.StatusCode != 500 { t.Fatal(err) } resp, err := ioutil.ReadAll(raw.Body) if err != nil { t.Fatal(err) } if !strings.Contains(string(resp), pidNotInContainerErr.Error()) { t.Fatal("resp error not expected: ", string(resp)) } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/devlxd_gccgo.go����������������������������������������������������������������������0000644�0610621�0607500�00000001603�13172163242�017237� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build gccgo // +build cgo package main import ( "errors" ) /* #define _GNU_SOURCE #include <sys/socket.h> #include <sys/types.h> #include <errno.h> #include <stdio.h> #include <string.h> void getucred(int sock, uint *uid, uint *gid, int *pid) { struct ucred peercred; socklen_t len; len = sizeof(struct ucred); if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &len) != 0 || len != sizeof(peercred)) { fprintf(stderr, "getsockopt failed: %s\n", strerror(errno)); return; } *uid = peercred.uid; *gid = peercred.gid; *pid = peercred.pid; return; } */ import "C" func getUcred(fd int) (uint32, uint32, int32, error) { uid := C.uint(0) gid := C.uint(0) pid := C.int(-1) C.getucred(C.int(fd), &uid, &gid, &pid) if uid == 0 || gid == 0 || pid == -1 { return 0, 0, -1, errors.New("Failed to get the ucred") } return uint32(uid), uint32(gid), int32(pid), nil } �����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/devlxd_gc.go�������������������������������������������������������������������������0000644�0610621�0607500�00000000425�13172163242�016547� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build gc package main import ( "syscall" ) func getUcred(fd int) (uint32, uint32, int32, error) { cred, err := syscall.GetsockoptUcred(fd, syscall.SOL_SOCKET, syscall.SO_PEERCRED) if err != nil { return 0, 0, -1, err } return cred.Uid, cred.Gid, cred.Pid, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/devlxd.go����������������������������������������������������������������������������0000644�0610621�0607500�00000025273�13172163242�016106� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "net" "net/http" "os" "path" "reflect" "regexp" "strconv" "strings" "unsafe" "github.com/gorilla/mux" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/version" ) type devLxdResponse struct { content interface{} code int ctype string } func okResponse(ct interface{}, ctype string) *devLxdResponse { return &devLxdResponse{ct, http.StatusOK, ctype} } type devLxdHandler struct { path string /* * This API will have to be changed slightly when we decide to support * websocket events upgrading, but since we don't have events on the * server side right now either, I went the simple route to avoid * needless noise. */ f func(c container, r *http.Request) *devLxdResponse } var configGet = devLxdHandler{"/1.0/config", func(c container, r *http.Request) *devLxdResponse { filtered := []string{} for k := range c.ExpandedConfig() { if strings.HasPrefix(k, "user.") { filtered = append(filtered, fmt.Sprintf("/1.0/config/%s", k)) } } return okResponse(filtered, "json") }} var configKeyGet = devLxdHandler{"/1.0/config/{key}", func(c container, r *http.Request) *devLxdResponse { key := mux.Vars(r)["key"] if !strings.HasPrefix(key, "user.") { return &devLxdResponse{"not authorized", http.StatusForbidden, "raw"} } value, ok := c.ExpandedConfig()[key] if !ok { return &devLxdResponse{"not found", http.StatusNotFound, "raw"} } return okResponse(value, "raw") }} var metadataGet = devLxdHandler{"/1.0/meta-data", func(c container, r *http.Request) *devLxdResponse { value := c.ExpandedConfig()["user.meta-data"] return okResponse(fmt.Sprintf("#cloud-config\ninstance-id: %s\nlocal-hostname: %s\n%s", c.Name(), c.Name(), value), "raw") }} var handlers = []devLxdHandler{ {"/", func(c container, r *http.Request) *devLxdResponse { return okResponse([]string{"/1.0"}, "json") }}, {"/1.0", func(c container, r *http.Request) *devLxdResponse { return okResponse(shared.Jmap{"api_version": version.APIVersion}, "json") }}, configGet, configKeyGet, metadataGet, /* TODO: events */ } func hoistReq(f func(container, *http.Request) *devLxdResponse, d *Daemon) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { conn := extractUnderlyingConn(w) cred, ok := pidMapper.m[conn] if !ok { http.Error(w, pidNotInContainerErr.Error(), 500) return } c, err := findContainerForPid(cred.pid, d) if err != nil { http.Error(w, err.Error(), 500) return } // Access control rootUid := int64(0) idmapset, err := c.LastIdmapSet() if err == nil && idmapset != nil { uid, _ := idmapset.ShiftIntoNs(0, 0) rootUid = int64(uid) } if rootUid != cred.uid { http.Error(w, "Access denied for non-root user", 401) return } resp := f(c, r) if resp.code != http.StatusOK { http.Error(w, fmt.Sprintf("%s", resp.content), resp.code) } else if resp.ctype == "json" { w.Header().Set("Content-Type", "application/json") util.WriteJSON(w, resp.content, debug) } else { w.Header().Set("Content-Type", "application/octet-stream") fmt.Fprintf(w, resp.content.(string)) } } } func createAndBindDevLxd() (*net.UnixListener, error) { sockFile := path.Join(shared.VarPath("devlxd"), "sock") /* * If this socket exists, that means a previous lxd died and didn't * clean up after itself. We assume that the LXD is actually dead if we * get this far, since StartDaemon() tries to connect to the actual lxd * socket to make sure that it is actually dead. So, it is safe to * remove it here without any checks. * * Also, it would be nice to SO_REUSEADDR here so we don't have to * delete the socket, but we can't: * http://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix * * Note that this will force clients to reconnect when LXD is restarted. */ if err := os.Remove(sockFile); err != nil && !os.IsNotExist(err) { return nil, err } unixAddr, err := net.ResolveUnixAddr("unix", sockFile) if err != nil { return nil, err } unixl, err := net.ListenUnix("unix", unixAddr) if err != nil { return nil, err } if err := os.Chmod(sockFile, 0666); err != nil { return nil, err } return unixl, nil } func devLxdServer(d *Daemon) *http.Server { m := mux.NewRouter() for _, handler := range handlers { m.HandleFunc(handler.path, hoistReq(handler.f, d)) } return &http.Server{ Handler: m, ConnState: pidMapper.ConnStateHandler, } } /* * Everything below here is the guts of the unix socket bits. Unfortunately, * golang's API does not make this easy. What happens is: * * 1. We install a ConnState listener on the http.Server, which does the * initial unix socket credential exchange. When we get a connection started * event, we use SO_PEERCRED to extract the creds for the socket. * * 2. We store a map from the connection pointer to the pid for that * connection, so that once the HTTP negotiation occurrs and we get a * ResponseWriter, we know (because we negotiated on the first byte) which * pid the connection belogs to. * * 3. Regular HTTP negotiation and dispatch occurs via net/http. * * 4. When rendering the response via ResponseWriter, we match its underlying * connection against what we stored in step (2) to figure out which container * it came from. */ /* * We keep this in a global so that we can reference it from the server and * from our http handlers, since there appears to be no way to pass information * around here. */ var pidMapper = ConnPidMapper{m: map[*net.UnixConn]*ucred{}} type ucred struct { pid int32 uid int64 gid int64 } type ConnPidMapper struct { m map[*net.UnixConn]*ucred } func (m *ConnPidMapper) ConnStateHandler(conn net.Conn, state http.ConnState) { unixConn := conn.(*net.UnixConn) switch state { case http.StateNew: cred, err := getCred(unixConn) if err != nil { logger.Debugf("Error getting ucred for conn %s", err) } else { m.m[unixConn] = cred } case http.StateActive: return case http.StateIdle: return case http.StateHijacked: /* * The "Hijacked" state indicates that the connection has been * taken over from net/http. This is useful for things like * developing websocket libraries, who want to upgrade the * connection to a websocket one, and not use net/http any * more. Whatever the case, we want to forget about it since we * won't see it either. */ delete(m.m, unixConn) case http.StateClosed: delete(m.m, unixConn) default: logger.Debugf("Unknown state for connection %s", state) } } /* * I also don't see that golang exports an API to get at the underlying FD, but * we need it to get at SO_PEERCRED, so let's grab it. */ func extractUnderlyingFd(unixConnPtr *net.UnixConn) (int, error) { conn := reflect.Indirect(reflect.ValueOf(unixConnPtr)) netFdPtr := conn.FieldByName("fd") if !netFdPtr.IsValid() { return -1, fmt.Errorf("Unable to extract fd from net.UnixConn") } netFd := reflect.Indirect(netFdPtr) fd := netFd.FieldByName("sysfd") if !fd.IsValid() { // Try under the new name pfdPtr := netFd.FieldByName("pfd") if !pfdPtr.IsValid() { return -1, fmt.Errorf("Unable to extract pfd from netFD") } pfd := reflect.Indirect(pfdPtr) fd = pfd.FieldByName("Sysfd") if !fd.IsValid() { return -1, fmt.Errorf("Unable to extract Sysfd from poll.FD") } } return int(fd.Int()), nil } func getCred(conn *net.UnixConn) (*ucred, error) { fd, err := extractUnderlyingFd(conn) if err != nil { return nil, err } uid, gid, pid, err := getUcred(fd) if err != nil { return nil, err } return &ucred{pid, int64(uid), int64(gid)}, nil } /* * As near as I can tell, there is no nice way of extracting an underlying * net.Conn (or in our case, net.UnixConn) from an http.Request or * ResponseWriter without hijacking it [1]. Since we want to send and receive * unix creds to figure out which container this request came from, we need to * do this. * * [1]: https://groups.google.com/forum/#!topic/golang-nuts/_FWdFXJa6QA */ func extractUnderlyingConn(w http.ResponseWriter) *net.UnixConn { v := reflect.Indirect(reflect.ValueOf(w)) connPtr := v.FieldByName("conn") conn := reflect.Indirect(connPtr) rwc := conn.FieldByName("rwc") netConnPtr := (*net.Conn)(unsafe.Pointer(rwc.UnsafeAddr())) unixConnPtr := (*netConnPtr).(*net.UnixConn) return unixConnPtr } var pidNotInContainerErr = fmt.Errorf("pid not in container?") func findContainerForPid(pid int32, d *Daemon) (container, error) { /* * Try and figure out which container a pid is in. There is probably a * better way to do this. Based on rharper's initial performance * metrics, looping over every container and calling newLxdContainer is * expensive, so I wanted to avoid that if possible, so this happens in * a two step process: * * 1. Walk up the process tree until you see something that looks like * an lxc monitor process and extract its name from there. * * 2. If this fails, it may be that someone did an `lxc exec foo bash`, * so the process isn't actually a descendant of the container's * init. In this case we just look through all the containers until * we find an init with a matching pid namespace. This is probably * uncommon, so hopefully the slowness won't hurt us. */ origpid := pid for pid > 1 { cmdline, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) if err != nil { return nil, err } if strings.HasPrefix(string(cmdline), "[lxc monitor]") { // container names can't have spaces parts := strings.Split(string(cmdline), " ") name := strings.TrimSuffix(parts[len(parts)-1], "\x00") return containerLoadByName(d.State(), d.Storage, name) } status, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/status", pid)) if err != nil { return nil, err } re := regexp.MustCompile("PPid:\\s*([0-9]*)") for _, line := range strings.Split(string(status), "\n") { m := re.FindStringSubmatch(line) if m != nil && len(m) > 1 { result, err := strconv.Atoi(m[1]) if err != nil { return nil, err } pid = int32(result) break } } } origPidNs, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", origpid)) if err != nil { return nil, err } containers, err := db.ContainersList(d.db, db.CTypeRegular) if err != nil { return nil, err } for _, container := range containers { c, err := containerLoadByName(d.State(), d.Storage, container) if err != nil { return nil, err } if !c.IsRunning() { continue } initpid := c.InitPID() pidNs, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", initpid)) if err != nil { return nil, err } if origPidNs == pidNs { return c, nil } } return nil, pidNotInContainerErr } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/devices.go���������������������������������������������������������������������������0000644�0610621�0607500�00000046502�13172163242�016240� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "bufio" "bytes" "crypto/rand" "encoding/hex" "fmt" "io/ioutil" "math/big" "os" "path" "path/filepath" "sort" "strconv" "strings" "syscall" _ "github.com/mattn/go-sqlite3" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) var deviceSchedRebalance = make(chan []string, 2) type deviceBlockLimit struct { readBps int64 readIops int64 writeBps int64 writeIops int64 } type deviceTaskCPU struct { id int strId string count *int } type deviceTaskCPUs []deviceTaskCPU func (c deviceTaskCPUs) Len() int { return len(c) } func (c deviceTaskCPUs) Less(i, j int) bool { return *c[i].count < *c[j].count } func (c deviceTaskCPUs) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func deviceNetlinkListener() (chan []string, chan []string, error) { NETLINK_KOBJECT_UEVENT := 15 UEVENT_BUFFER_SIZE := 2048 fd, err := syscall.Socket( syscall.AF_NETLINK, syscall.SOCK_RAW, NETLINK_KOBJECT_UEVENT, ) if err != nil { return nil, nil, err } nl := syscall.SockaddrNetlink{ Family: syscall.AF_NETLINK, Pid: uint32(os.Getpid()), Groups: 1, } err = syscall.Bind(fd, &nl) if err != nil { return nil, nil, err } chCPU := make(chan []string, 1) chNetwork := make(chan []string, 0) go func(chCPU chan []string, chNetwork chan []string) { b := make([]byte, UEVENT_BUFFER_SIZE*2) for { _, err := syscall.Read(fd, b) if err != nil { continue } props := map[string]string{} last := 0 for i, e := range b { if i == len(b) || e == 0 { msg := string(b[last+1 : i]) last = i if len(msg) == 0 || msg == "\x00" { continue } fields := strings.SplitN(msg, "=", 2) if len(fields) != 2 { continue } props[fields[0]] = fields[1] } } if props["SUBSYSTEM"] == "cpu" { if props["DRIVER"] != "processor" { continue } if props["ACTION"] != "offline" && props["ACTION"] != "online" { continue } // As CPU re-balancing affects all containers, no need to queue them select { case chCPU <- []string{path.Base(props["DEVPATH"]), props["ACTION"]}: default: // Channel is full, drop the event } } if props["SUBSYSTEM"] == "net" { if props["ACTION"] != "add" && props["ACTION"] != "removed" { continue } if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", props["INTERFACE"])) { continue } // Network balancing is interface specific, so queue everything chNetwork <- []string{props["INTERFACE"], props["ACTION"]} } } }(chCPU, chNetwork) return chCPU, chNetwork, nil } func parseCpuset(cpu string) ([]int, error) { cpus := []int{} chunks := strings.Split(cpu, ",") for _, chunk := range chunks { if strings.Contains(chunk, "-") { // Range fields := strings.SplitN(chunk, "-", 2) if len(fields) != 2 { return nil, fmt.Errorf("Invalid cpuset value: %s", cpu) } low, err := strconv.Atoi(fields[0]) if err != nil { return nil, fmt.Errorf("Invalid cpuset value: %s", cpu) } high, err := strconv.Atoi(fields[1]) if err != nil { return nil, fmt.Errorf("Invalid cpuset value: %s", cpu) } for i := low; i <= high; i++ { cpus = append(cpus, i) } } else { // Simple entry nr, err := strconv.Atoi(chunk) if err != nil { return nil, fmt.Errorf("Invalid cpuset value: %s", cpu) } cpus = append(cpus, nr) } } return cpus, nil } func deviceTaskBalance(s *state.State, storage storage) { min := func(x, y int) int { if x < y { return x } return y } // Don't bother running when CGroup support isn't there if !cgCpusetController { return } // Get effective cpus list - those are all guaranteed to be online effectiveCpus, err := cGroupGet("cpuset", "/", "cpuset.effective_cpus") if err != nil { // Older kernel - use cpuset.cpus effectiveCpus, err = cGroupGet("cpuset", "/", "cpuset.cpus") if err != nil { logger.Errorf("Error reading host's cpuset.cpus") return } } effectiveCpusInt, err := parseCpuset(effectiveCpus) if err != nil { logger.Errorf("Error parsing effective CPU set") return } isolatedCpusInt := []int{} if shared.PathExists("/sys/devices/system/cpu/isolated") { buf, err := ioutil.ReadFile("/sys/devices/system/cpu/isolated") if err != nil { logger.Errorf("Error reading host's isolated cpu") return } // File might exist even though there are no isolated cpus. isolatedCpus := strings.TrimSpace(string(buf)) if isolatedCpus != "" { isolatedCpusInt, err = parseCpuset(isolatedCpus) if err != nil { logger.Errorf("Error parsing isolated CPU set: %s", string(isolatedCpus)) return } } } effectiveCpusSlice := []string{} for _, id := range effectiveCpusInt { if shared.IntInSlice(id, isolatedCpusInt) { continue } effectiveCpusSlice = append(effectiveCpusSlice, fmt.Sprintf("%d", id)) } effectiveCpus = strings.Join(effectiveCpusSlice, ",") err = cGroupSet("cpuset", "/lxc", "cpuset.cpus", effectiveCpus) if err != nil && shared.PathExists("/sys/fs/cgroup/cpuset/lxc") { logger.Warn("Error setting lxd's cpuset.cpus", log.Ctx{"err": err}) } cpus, err := parseCpuset(effectiveCpus) if err != nil { logger.Error("Error parsing host's cpu set", log.Ctx{"cpuset": effectiveCpus, "err": err}) return } // Iterate through the containers containers, err := db.ContainersList(s.DB, db.CTypeRegular) if err != nil { logger.Error("problem loading containers list", log.Ctx{"err": err}) return } fixedContainers := map[int][]container{} balancedContainers := map[container]int{} for _, name := range containers { c, err := containerLoadByName(s, storage, name) if err != nil { continue } conf := c.ExpandedConfig() cpulimit, ok := conf["limits.cpu"] if !ok || cpulimit == "" { cpulimit = effectiveCpus } if !c.IsRunning() { continue } count, err := strconv.Atoi(cpulimit) if err == nil { // Load-balance count = min(count, len(cpus)) balancedContainers[c] = count } else { // Pinned containerCpus, err := parseCpuset(cpulimit) if err != nil { return } for _, nr := range containerCpus { if !shared.IntInSlice(nr, cpus) { continue } _, ok := fixedContainers[nr] if ok { fixedContainers[nr] = append(fixedContainers[nr], c) } else { fixedContainers[nr] = []container{c} } } } } // Balance things pinning := map[container][]string{} usage := map[int]deviceTaskCPU{} for _, id := range cpus { cpu := deviceTaskCPU{} cpu.id = id cpu.strId = fmt.Sprintf("%d", id) count := 0 cpu.count = &count usage[id] = cpu } for cpu, ctns := range fixedContainers { c, ok := usage[cpu] if !ok { logger.Errorf("Internal error: container using unavailable cpu") continue } id := c.strId for _, ctn := range ctns { _, ok := pinning[ctn] if ok { pinning[ctn] = append(pinning[ctn], id) } else { pinning[ctn] = []string{id} } *c.count += 1 } } sortedUsage := make(deviceTaskCPUs, 0) for _, value := range usage { sortedUsage = append(sortedUsage, value) } for ctn, count := range balancedContainers { sort.Sort(sortedUsage) for _, cpu := range sortedUsage { if count == 0 { break } count -= 1 id := cpu.strId _, ok := pinning[ctn] if ok { pinning[ctn] = append(pinning[ctn], id) } else { pinning[ctn] = []string{id} } *cpu.count += 1 } } // Set the new pinning for ctn, set := range pinning { // Confirm the container didn't just stop if !ctn.IsRunning() { continue } sort.Strings(set) err := ctn.CGroupSet("cpuset.cpus", strings.Join(set, ",")) if err != nil { logger.Error("balance: Unable to set cpuset", log.Ctx{"name": ctn.Name(), "err": err, "value": strings.Join(set, ",")}) } } } func deviceNetworkPriority(s *state.State, storage storage, netif string) { // Don't bother running when CGroup support isn't there if !cgNetPrioController { return } containers, err := db.ContainersList(s.DB, db.CTypeRegular) if err != nil { return } for _, name := range containers { // Get the container struct c, err := containerLoadByName(s, storage, name) if err != nil { continue } // Extract the current priority networkPriority := c.ExpandedConfig()["limits.network.priority"] if networkPriority == "" { continue } networkInt, err := strconv.Atoi(networkPriority) if err != nil { continue } // Set the value for the new interface c.CGroupSet("net_prio.ifpriomap", fmt.Sprintf("%s %d", netif, networkInt)) } return } func deviceEventListener(s *state.State, storage storage) { chNetlinkCPU, chNetlinkNetwork, err := deviceNetlinkListener() if err != nil { logger.Errorf("scheduler: couldn't setup netlink listener") return } for { select { case e := <-chNetlinkCPU: if len(e) != 2 { logger.Errorf("Scheduler: received an invalid cpu hotplug event") continue } if !cgCpusetController { continue } logger.Debugf("Scheduler: cpu: %s is now %s: re-balancing", e[0], e[1]) deviceTaskBalance(s, storage) case e := <-chNetlinkNetwork: if len(e) != 2 { logger.Errorf("Scheduler: received an invalid network hotplug event") continue } if !cgNetPrioController { continue } logger.Debugf("Scheduler: network: %s has been added: updating network priorities", e[0]) deviceNetworkPriority(s, storage, e[0]) case e := <-deviceSchedRebalance: if len(e) != 3 { logger.Errorf("Scheduler: received an invalid rebalance event") continue } if !cgCpusetController { continue } logger.Debugf("Scheduler: %s %s %s: re-balancing", e[0], e[1], e[2]) deviceTaskBalance(s, storage) } } } func deviceTaskSchedulerTrigger(srcType string, srcName string, srcStatus string) { // Spawn a go routine which then triggers the scheduler select { case deviceSchedRebalance <- []string{srcType, srcName, srcStatus}: default: // Channel is full, drop the event } } func deviceIsBlockdev(path string) bool { // Get a stat struct from the provided path stat := syscall.Stat_t{} err := syscall.Stat(path, &stat) if err != nil { return false } // Check if it's a block device if stat.Mode&syscall.S_IFMT == syscall.S_IFBLK { return true } // Not a device return false } func deviceModeOct(strmode string) (int, error) { // Default mode if strmode == "" { return 0600, nil } // Converted mode i, err := strconv.ParseInt(strmode, 8, 32) if err != nil { return 0, fmt.Errorf("Bad device mode: %s", strmode) } return int(i), nil } func deviceGetAttributes(path string) (string, int, int, error) { // Get a stat struct from the provided path stat := syscall.Stat_t{} err := syscall.Stat(path, &stat) if err != nil { return "", 0, 0, err } // Check what kind of file it is dType := "" if stat.Mode&syscall.S_IFMT == syscall.S_IFBLK { dType = "b" } else if stat.Mode&syscall.S_IFMT == syscall.S_IFCHR { dType = "c" } else { return "", 0, 0, fmt.Errorf("Not a device") } // Return the device information major := shared.Major(stat.Rdev) minor := shared.Minor(stat.Rdev) return dType, major, minor, nil } func deviceNextInterfaceHWAddr() (string, error) { // Generate a new random MAC address using the usual prefix ret := bytes.Buffer{} for _, c := range "00:16:3e:xx:xx:xx" { if c == 'x' { c, err := rand.Int(rand.Reader, big.NewInt(16)) if err != nil { return "", err } ret.WriteString(fmt.Sprintf("%x", c.Int64())) } else { ret.WriteString(string(c)) } } return ret.String(), nil } func deviceNextVeth() string { // Return a new random veth device name randBytes := make([]byte, 4) rand.Read(randBytes) return "veth" + hex.EncodeToString(randBytes) } func deviceRemoveInterface(nic string) error { _, err := shared.RunCommand("ip", "link", "del", "dev", nic) return err } func deviceMountDisk(srcPath string, dstPath string, readonly bool, recursive bool) error { var err error // Prepare the mount flags flags := 0 if readonly { flags |= syscall.MS_RDONLY } // Detect the filesystem fstype := "none" if deviceIsBlockdev(srcPath) { fstype, err = shared.BlockFsDetect(srcPath) if err != nil { return err } } else { flags |= syscall.MS_BIND if recursive { flags |= syscall.MS_REC } } // Mount the filesystem if err = syscall.Mount(srcPath, dstPath, fstype, uintptr(flags), ""); err != nil { return fmt.Errorf("Unable to mount %s at %s: %s", srcPath, dstPath, err) } // Remount bind mounts in readonly mode if requested if readonly == true && flags&syscall.MS_BIND == syscall.MS_BIND { flags = syscall.MS_RDONLY | syscall.MS_BIND | syscall.MS_REMOUNT if err = syscall.Mount("", dstPath, fstype, uintptr(flags), ""); err != nil { return fmt.Errorf("Unable to mount %s in readonly mode: %s", dstPath, err) } } flags = syscall.MS_REC | syscall.MS_SLAVE if err = syscall.Mount("", dstPath, "", uintptr(flags), ""); err != nil { return fmt.Errorf("unable to make mount %s private: %s", dstPath, err) } return nil } func deviceParseCPU(cpuAllowance string, cpuPriority string) (string, string, string, error) { var err error // Parse priority cpuShares := 0 cpuPriorityInt := 10 if cpuPriority != "" { cpuPriorityInt, err = strconv.Atoi(cpuPriority) if err != nil { return "", "", "", err } } cpuShares -= 10 - cpuPriorityInt // Parse allowance cpuCfsQuota := "-1" cpuCfsPeriod := "100000" if cpuAllowance != "" { if strings.HasSuffix(cpuAllowance, "%") { // Percentage based allocation percent, err := strconv.Atoi(strings.TrimSuffix(cpuAllowance, "%")) if err != nil { return "", "", "", err } cpuShares += (10 * percent) + 24 } else { // Time based allocation fields := strings.SplitN(cpuAllowance, "/", 2) if len(fields) != 2 { return "", "", "", fmt.Errorf("Invalid allowance: %s", cpuAllowance) } quota, err := strconv.Atoi(strings.TrimSuffix(fields[0], "ms")) if err != nil { return "", "", "", err } period, err := strconv.Atoi(strings.TrimSuffix(fields[1], "ms")) if err != nil { return "", "", "", err } // Set limit in ms cpuCfsQuota = fmt.Sprintf("%d", quota*1000) cpuCfsPeriod = fmt.Sprintf("%d", period*1000) cpuShares += 1024 } } else { // Default is 100% cpuShares += 1024 } // Deal with a potential negative score if cpuShares < 0 { cpuShares = 0 } return fmt.Sprintf("%d", cpuShares), cpuCfsQuota, cpuCfsPeriod, nil } func deviceTotalMemory() (int64, error) { // Open /proc/meminfo f, err := os.Open("/proc/meminfo") if err != nil { return -1, err } defer f.Close() // Read it line by line scan := bufio.NewScanner(f) for scan.Scan() { line := scan.Text() // We only care about MemTotal if !strings.HasPrefix(line, "MemTotal:") { continue } // Extract the before last (value) and last (unit) fields fields := strings.Split(line, " ") value := fields[len(fields)-2] + fields[len(fields)-1] // Feed the result to shared.ParseByteSizeString to get an int value valueBytes, err := shared.ParseByteSizeString(value) if err != nil { return -1, err } return valueBytes, nil } return -1, fmt.Errorf("Couldn't find MemTotal") } func deviceGetParentBlocks(path string) ([]string, error) { var devices []string var device []string // Expand the mount path absPath, err := filepath.Abs(path) if err != nil { return nil, err } expPath, err := filepath.EvalSymlinks(absPath) if err != nil { expPath = absPath } // Find the source mount of the path file, err := os.Open("/proc/self/mountinfo") if err != nil { return nil, err } defer file.Close() scanner := bufio.NewScanner(file) match := "" for scanner.Scan() { line := scanner.Text() rows := strings.Fields(line) if len(rows[4]) <= len(match) { continue } if expPath != rows[4] && !strings.HasPrefix(expPath, rows[4]) { continue } match = rows[4] // Go backward to avoid problems with optional fields device = []string{rows[2], rows[len(rows)-2]} } if device == nil { return nil, fmt.Errorf("Couldn't find a match /proc/self/mountinfo entry") } // Handle the most simple case if !strings.HasPrefix(device[0], "0:") { return []string{device[0]}, nil } // Deal with per-filesystem oddities. We don't care about failures here // because any non-special filesystem => directory backend. fs, _ := util.FilesystemDetect(expPath) if fs == "zfs" && shared.PathExists("/dev/zfs") { // Accessible zfs filesystems poolName := strings.Split(device[1], "/")[0] output, err := shared.RunCommand("zpool", "status", "-P", "-L", poolName) if err != nil { return nil, fmt.Errorf("Failed to query zfs filesystem information for %s: %s", device[1], output) } header := true for _, line := range strings.Split(output, "\n") { fields := strings.Fields(line) if len(fields) < 5 { continue } if fields[1] != "ONLINE" { continue } if header { header = false continue } var path string if shared.PathExists(fields[0]) { if shared.IsBlockdevPath(fields[0]) { path = fields[0] } else { subDevices, err := deviceGetParentBlocks(fields[0]) if err != nil { return nil, err } for _, dev := range subDevices { devices = append(devices, dev) } } } else { continue } if path != "" { _, major, minor, err := deviceGetAttributes(path) if err != nil { continue } devices = append(devices, fmt.Sprintf("%d:%d", major, minor)) } } if len(devices) == 0 { return nil, fmt.Errorf("Unable to find backing block for zfs pool: %s", poolName) } } else if fs == "btrfs" && shared.PathExists(device[1]) { // Accessible btrfs filesystems output, err := shared.RunCommand("btrfs", "filesystem", "show", device[1]) if err != nil { return nil, fmt.Errorf("Failed to query btrfs filesystem information for %s: %s", device[1], output) } for _, line := range strings.Split(output, "\n") { fields := strings.Fields(line) if len(fields) == 0 || fields[0] != "devid" { continue } _, major, minor, err := deviceGetAttributes(fields[len(fields)-1]) if err != nil { return nil, err } devices = append(devices, fmt.Sprintf("%d:%d", major, minor)) } } else if shared.PathExists(device[1]) { // Anything else with a valid path _, major, minor, err := deviceGetAttributes(device[1]) if err != nil { return nil, err } devices = append(devices, fmt.Sprintf("%d:%d", major, minor)) } else { return nil, fmt.Errorf("Invalid block device: %s", device[1]) } return devices, nil } func deviceParseDiskLimit(readSpeed string, writeSpeed string) (int64, int64, int64, int64, error) { parseValue := func(value string) (int64, int64, error) { var err error bps := int64(0) iops := int64(0) if readSpeed == "" { return bps, iops, nil } if strings.HasSuffix(value, "iops") { iops, err = strconv.ParseInt(strings.TrimSuffix(value, "iops"), 10, 64) if err != nil { return -1, -1, err } } else { bps, err = shared.ParseByteSizeString(value) if err != nil { return -1, -1, err } } return bps, iops, nil } readBps, readIops, err := parseValue(readSpeed) if err != nil { return -1, -1, -1, -1, err } writeBps, writeIops, err := parseValue(writeSpeed) if err != nil { return -1, -1, -1, -1, err } return readBps, readIops, writeBps, writeIops, nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/debug.go�����������������������������������������������������������������������������0000644�0610621�0607500�00000001022�13172163242�015670� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "os" "os/signal" "runtime/pprof" "syscall" "github.com/lxc/lxd/shared/logger" ) func doMemDump(memProfile string) { f, err := os.Create(memProfile) if err != nil { logger.Debugf("Error opening memory profile file '%s': %s", err) return } pprof.WriteHeapProfile(f) f.Close() } func memProfiler(memProfile string) { ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGUSR1) for { sig := <-ch logger.Debugf("Received '%s signal', dumping memory.", sig) doMemDump(memProfile) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/����������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014645� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/update.go�������������������������������������������������������������������������0000644�0610621�0607500�00000064243�13172163242�016467� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" "encoding/hex" "fmt" "os" "path" "runtime" "strconv" "strings" "github.com/lxc/lxd/lxd/db/schema" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" ) /* Database updates are one-time actions that are needed to move an existing database from one version of the schema to the next. Those updates are applied at startup time before anything else in LXD is initialized. This means that they should be entirely self-contained and not touch anything but the database. Calling LXD functions isn't allowed as such functions may themselves depend on a newer DB schema and so would fail when upgrading a very old version of LXD. DO NOT USE this mechanism for one-time actions which do not involve changes to the database schema. Use patches instead (see lxd/patches.go). REMEMBER to run "make update-schema" after you add a new update function to this slice. That will refresh the schema declaration in lxd/db/schema.go and include the effect of applying your patch as well. Only append to the updates list, never remove entries and never re-order them. */ var updates = map[int]schema.Update{ 1: updateFromV0, 2: updateFromV1, 3: updateFromV2, 4: updateFromV3, 5: updateFromV4, 6: updateFromV5, 7: updateFromV6, 8: updateFromV7, 9: updateFromV8, 10: updateFromV9, 11: updateFromV10, 12: updateFromV11, 13: updateFromV12, 14: updateFromV13, 15: updateFromV14, 16: updateFromV15, 17: updateFromV16, 18: updateFromV17, 19: updateFromV18, 20: updateFromV19, 21: updateFromV20, 22: updateFromV21, 23: updateFromV22, 24: updateFromV23, 25: updateFromV24, 26: updateFromV25, 27: updateFromV26, 28: updateFromV27, 29: updateFromV28, 30: updateFromV29, 31: updateFromV30, 32: updateFromV31, } // LegacyPatch is a "database" update that performs non-database work. They // are needed for historical reasons, since there was a time were db updates // could do non-db work and depend on functionality external to the db // package. See UpdatesApplyAll below. type LegacyPatch struct { NeedsDB bool // Whether the patch does any DB-related work Hook func() error // The actual patch logic } // UpdatesApplyAll applies all possible database patches. If "doBackup" is // true, the sqlite file will be backed up before any update is applied. The // legacyPatches parameter is used by the Daemon as a mean to apply the legacy // V10, V11, V15, V29 and V30 non-db updates during the database upgrade // sequence, to avoid any change in semantics wrt the old logic (see PR #3322). func UpdatesApplyAll(db *sql.DB, doBackup bool, legacyPatches map[int]*LegacyPatch) error { backup := false schema := schema.NewFromMap(updates) schema.Hook(func(version int, tx *sql.Tx) error { if doBackup && !backup { logger.Infof("Updating the LXD database schema. Backup made as \"lxd.db.bak\"") err := shared.FileCopy(shared.VarPath("lxd.db"), shared.VarPath("lxd.db.bak")) if err != nil { return err } backup = true } logger.Debugf("Updating DB schema from %d to %d", version, version+1) legacyPatch, ok := legacyPatches[version] if ok { // FIXME We need to commit the transaction before the // hook and then open it again afterwards because this // legacy patch pokes with the database and would fail // with a lock error otherwise. if legacyPatch.NeedsDB { _, err := tx.Exec("COMMIT") if err != nil { return err } } err := legacyPatch.Hook() if err != nil { return err } if legacyPatch.NeedsDB { _, err = tx.Exec("BEGIN") } return err } return nil }) return schema.Ensure(db) } // UpdateSchemaDotGo rewrites the 'schema.go' source file in this package to // match the current schema updates. // // The schema.go file contains a "flattened" render of all schema updates // defined in this file, and it's used to initialize brand new databases. func UpdateSchemaDotGo() error { // Apply all the updates that we have on a pristine database and dump // the resulting schema. db, err := sql.Open("sqlite3", ":memory:") if err != nil { return fmt.Errorf("failed to open schema.go for writing: %v", err) } schema := schema.NewFromMap(updates) err = schema.Ensure(db) if err != nil { return err } dump, err := schema.Dump(db) if err != nil { return err } // Passing 1 to runtime.Caller identifies the caller of runtime.Caller, // that means us. _, filename, _, _ := runtime.Caller(0) file, err := os.Create(path.Join(path.Dir(filename), "schema.go")) if err != nil { return fmt.Errorf("failed to open schema.go for writing: %v", err) } _, err = file.Write([]byte(fmt.Sprintf(schemaDotGo, dump))) if err != nil { return fmt.Errorf("failed to write to schema.go: %v", err) } return nil } // Template for schema.go (can't use backticks since we need to use backticks // inside the template itself). const schemaDotGo = "package db\n\n" + "// DO NOT EDIT BY HAND\n" + "//\n" + "// This code was generated by the UpdateSchemaDotGo function. If you need to\n" + "// modify the database schema, please add a new schema update to update.go\n" + "// and the run 'make update-schema'.\n" + "const CURRENT_SCHEMA = `\n" + "%s`\n" // Schema updates begin here func updateFromV31(tx *sql.Tx) error { stmt := ` CREATE TABLE IF NOT EXISTS patches ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, applied_at DATETIME NOT NULL, UNIQUE (name) );` _, err := tx.Exec(stmt) return err } func updateFromV30(tx *sql.Tx) error { // NOTE: this database update contained daemon-level logic which // was been moved to patchUpdateFromV15 in patches.go. return nil } func updateFromV29(tx *sql.Tx) error { if shared.PathExists(shared.VarPath("zfs.img")) { err := os.Chmod(shared.VarPath("zfs.img"), 0600) if err != nil { return err } } return nil } func updateFromV28(tx *sql.Tx) error { stmt := ` INSERT INTO profiles_devices (profile_id, name, type) SELECT id, "aadisable", 2 FROM profiles WHERE name="docker"; INSERT INTO profiles_devices_config (profile_device_id, key, value) SELECT profiles_devices.id, "source", "/dev/null" FROM profiles_devices LEFT JOIN profiles WHERE profiles_devices.profile_id = profiles.id AND profiles.name = "docker" AND profiles_devices.name = "aadisable"; INSERT INTO profiles_devices_config (profile_device_id, key, value) SELECT profiles_devices.id, "path", "/sys/module/apparmor/parameters/enabled" FROM profiles_devices LEFT JOIN profiles WHERE profiles_devices.profile_id = profiles.id AND profiles.name = "docker" AND profiles_devices.name = "aadisable";` tx.Exec(stmt) return nil } func updateFromV27(tx *sql.Tx) error { _, err := tx.Exec("UPDATE profiles_devices SET type=3 WHERE type='unix-char';") return err } func updateFromV26(tx *sql.Tx) error { stmt := ` ALTER TABLE images ADD COLUMN auto_update INTEGER NOT NULL DEFAULT 0; CREATE TABLE IF NOT EXISTS images_source ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, image_id INTEGER NOT NULL, server TEXT NOT NULL, protocol INTEGER NOT NULL, certificate TEXT NOT NULL, alias VARCHAR(255) NOT NULL, FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE );` _, err := tx.Exec(stmt) return err } func updateFromV25(tx *sql.Tx) error { stmt := ` INSERT INTO profiles (name, description) VALUES ("docker", "Profile supporting docker in containers"); INSERT INTO profiles_config (profile_id, key, value) SELECT id, "security.nesting", "true" FROM profiles WHERE name="docker"; INSERT INTO profiles_config (profile_id, key, value) SELECT id, "linux.kernel_modules", "overlay, nf_nat" FROM profiles WHERE name="docker"; INSERT INTO profiles_devices (profile_id, name, type) SELECT id, "fuse", "unix-char" FROM profiles WHERE name="docker"; INSERT INTO profiles_devices_config (profile_device_id, key, value) SELECT profiles_devices.id, "path", "/dev/fuse" FROM profiles_devices LEFT JOIN profiles WHERE profiles_devices.profile_id = profiles.id AND profiles.name = "docker";` tx.Exec(stmt) return nil } func updateFromV24(tx *sql.Tx) error { _, err := tx.Exec("ALTER TABLE containers ADD COLUMN stateful INTEGER NOT NULL DEFAULT 0;") return err } func updateFromV23(tx *sql.Tx) error { _, err := tx.Exec("ALTER TABLE profiles ADD COLUMN description TEXT;") return err } func updateFromV22(tx *sql.Tx) error { stmt := ` DELETE FROM containers_devices_config WHERE key='type'; DELETE FROM profiles_devices_config WHERE key='type';` _, err := tx.Exec(stmt) return err } func updateFromV21(tx *sql.Tx) error { _, err := tx.Exec("ALTER TABLE containers ADD COLUMN creation_date DATETIME NOT NULL DEFAULT 0;") return err } func updateFromV20(tx *sql.Tx) error { stmt := ` UPDATE containers_devices SET name='__lxd_upgrade_root' WHERE name='root'; UPDATE profiles_devices SET name='__lxd_upgrade_root' WHERE name='root'; INSERT INTO containers_devices (container_id, name, type) SELECT id, "root", 2 FROM containers; INSERT INTO containers_devices_config (container_device_id, key, value) SELECT id, "path", "/" FROM containers_devices WHERE name='root';` _, err := tx.Exec(stmt) return err } func updateFromV19(tx *sql.Tx) error { stmt := ` DELETE FROM containers_config WHERE container_id NOT IN (SELECT id FROM containers); DELETE FROM containers_devices_config WHERE container_device_id NOT IN (SELECT id FROM containers_devices WHERE container_id IN (SELECT id FROM containers)); DELETE FROM containers_devices WHERE container_id NOT IN (SELECT id FROM containers); DELETE FROM containers_profiles WHERE container_id NOT IN (SELECT id FROM containers); DELETE FROM images_aliases WHERE image_id NOT IN (SELECT id FROM images); DELETE FROM images_properties WHERE image_id NOT IN (SELECT id FROM images);` _, err := tx.Exec(stmt) return err } func updateFromV18(tx *sql.Tx) error { var id int var value string // Update container config rows, err := QueryScan(tx, "SELECT id, value FROM containers_config WHERE key='limits.memory'", nil, []interface{}{id, value}) if err != nil { return err } for _, row := range rows { id = row[0].(int) value = row[1].(string) // If already an integer, don't touch _, err := strconv.Atoi(value) if err == nil { continue } // Generate the new value value = strings.ToUpper(value) value += "B" // Deal with completely broken values _, err = shared.ParseByteSizeString(value) if err != nil { logger.Debugf("Invalid container memory limit, id=%d value=%s, removing.", id, value) _, err = tx.Exec("DELETE FROM containers_config WHERE id=?;", id) if err != nil { return err } } // Set the new value _, err = tx.Exec("UPDATE containers_config SET value=? WHERE id=?", value, id) if err != nil { return err } } // Update profiles config rows, err = QueryScan(tx, "SELECT id, value FROM profiles_config WHERE key='limits.memory'", nil, []interface{}{id, value}) if err != nil { return err } for _, row := range rows { id = row[0].(int) value = row[1].(string) // If already an integer, don't touch _, err := strconv.Atoi(value) if err == nil { continue } // Generate the new value value = strings.ToUpper(value) value += "B" // Deal with completely broken values _, err = shared.ParseByteSizeString(value) if err != nil { logger.Debugf("Invalid profile memory limit, id=%d value=%s, removing.", id, value) _, err = tx.Exec("DELETE FROM profiles_config WHERE id=?;", id) if err != nil { return err } } // Set the new value _, err = tx.Exec("UPDATE profiles_config SET value=? WHERE id=?", value, id) if err != nil { return err } } return nil } func updateFromV17(tx *sql.Tx) error { stmt := ` DELETE FROM profiles_config WHERE key LIKE 'volatile.%'; UPDATE containers_config SET key='limits.cpu' WHERE key='limits.cpus'; UPDATE profiles_config SET key='limits.cpu' WHERE key='limits.cpus';` _, err := tx.Exec(stmt) return err } func updateFromV16(tx *sql.Tx) error { stmt := ` UPDATE config SET key='storage.lvm_vg_name' WHERE key = 'core.lvm_vg_name'; UPDATE config SET key='storage.lvm_thinpool_name' WHERE key = 'core.lvm_thinpool_name';` _, err := tx.Exec(stmt) return err } func updateFromV15(tx *sql.Tx) error { // NOTE: this database update contained daemon-level logic which // was been moved to patchUpdateFromV15 in patches.go. return nil } func updateFromV14(tx *sql.Tx) error { stmt := ` PRAGMA foreign_keys=OFF; -- So that integrity doesn't get in the way for now DELETE FROM containers_config WHERE key="volatile.last_state.power"; INSERT INTO containers_config (container_id, key, value) SELECT id, "volatile.last_state.power", "RUNNING" FROM containers WHERE power_state=1; INSERT INTO containers_config (container_id, key, value) SELECT id, "volatile.last_state.power", "STOPPED" FROM containers WHERE power_state != 1; CREATE TABLE tmp ( id INTEGER primary key AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, architecture INTEGER NOT NULL, type INTEGER NOT NULL, ephemeral INTEGER NOT NULL DEFAULT 0, UNIQUE (name) ); INSERT INTO tmp SELECT id, name, architecture, type, ephemeral FROM containers; DROP TABLE containers; ALTER TABLE tmp RENAME TO containers; PRAGMA foreign_keys=ON; -- Make sure we turn integrity checks back on.` _, err := tx.Exec(stmt) return err } func updateFromV13(tx *sql.Tx) error { stmt := ` UPDATE containers_config SET key='volatile.base_image' WHERE key = 'volatile.baseImage';` _, err := tx.Exec(stmt) return err } func updateFromV12(tx *sql.Tx) error { stmt := ` ALTER TABLE images ADD COLUMN cached INTEGER NOT NULL DEFAULT 0; ALTER TABLE images ADD COLUMN last_use_date DATETIME;` _, err := tx.Exec(stmt) return err } func updateFromV11(tx *sql.Tx) error { // NOTE: this database update contained daemon-level logic which // was been moved to patchUpdateFromV15 in patches.go. return nil } func updateFromV10(tx *sql.Tx) error { // NOTE: this database update contained daemon-level logic which // was been moved to patchUpdateFromV10 in patches.go. return nil } func updateFromV9(tx *sql.Tx) error { stmt := ` CREATE TABLE tmp ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL default "none", FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE, UNIQUE (container_id, name) ); INSERT INTO tmp SELECT * FROM containers_devices; UPDATE containers_devices SET type=0 WHERE id IN (SELECT id FROM tmp WHERE type="none"); UPDATE containers_devices SET type=1 WHERE id IN (SELECT id FROM tmp WHERE type="nic"); UPDATE containers_devices SET type=2 WHERE id IN (SELECT id FROM tmp WHERE type="disk"); UPDATE containers_devices SET type=3 WHERE id IN (SELECT id FROM tmp WHERE type="unix-char"); UPDATE containers_devices SET type=4 WHERE id IN (SELECT id FROM tmp WHERE type="unix-block"); DROP TABLE tmp; CREATE TABLE tmp ( id INTEGER primary key AUTOINCREMENT NOT NULL, profile_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL default "none", FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE, UNIQUE (profile_id, name) ); INSERT INTO tmp SELECT * FROM profiles_devices; UPDATE profiles_devices SET type=0 WHERE id IN (SELECT id FROM tmp WHERE type="none"); UPDATE profiles_devices SET type=1 WHERE id IN (SELECT id FROM tmp WHERE type="nic"); UPDATE profiles_devices SET type=2 WHERE id IN (SELECT id FROM tmp WHERE type="disk"); UPDATE profiles_devices SET type=3 WHERE id IN (SELECT id FROM tmp WHERE type="unix-char"); UPDATE profiles_devices SET type=4 WHERE id IN (SELECT id FROM tmp WHERE type="unix-block"); DROP TABLE tmp;` _, err := tx.Exec(stmt) return err } func updateFromV8(tx *sql.Tx) error { stmt := ` UPDATE certificates SET fingerprint = replace(fingerprint, " ", "");` _, err := tx.Exec(stmt) return err } func updateFromV7(tx *sql.Tx) error { stmt := ` UPDATE config SET key='core.trust_password' WHERE key IN ('password', 'trust_password', 'trust-password', 'core.trust-password'); DELETE FROM config WHERE key != 'core.trust_password';` _, err := tx.Exec(stmt) return err } func updateFromV6(tx *sql.Tx) error { // This update recreates the schemas that need an ON DELETE CASCADE foreign // key. stmt := ` PRAGMA foreign_keys=OFF; -- So that integrity doesn't get in the way for now CREATE TEMP TABLE tmp AS SELECT * FROM containers_config; DROP TABLE containers_config; CREATE TABLE IF NOT EXISTS containers_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE, UNIQUE (container_id, key) ); INSERT INTO containers_config SELECT * FROM tmp; DROP TABLE tmp; CREATE TEMP TABLE tmp AS SELECT * FROM containers_devices; DROP TABLE containers_devices; CREATE TABLE IF NOT EXISTS containers_devices ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, type INTEGER NOT NULL default 0, FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE, UNIQUE (container_id, name) ); INSERT INTO containers_devices SELECT * FROM tmp; DROP TABLE tmp; CREATE TEMP TABLE tmp AS SELECT * FROM containers_devices_config; DROP TABLE containers_devices_config; CREATE TABLE IF NOT EXISTS containers_devices_config ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_device_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_device_id) REFERENCES containers_devices (id) ON DELETE CASCADE, UNIQUE (container_device_id, key) ); INSERT INTO containers_devices_config SELECT * FROM tmp; DROP TABLE tmp; CREATE TEMP TABLE tmp AS SELECT * FROM containers_profiles; DROP TABLE containers_profiles; CREATE TABLE IF NOT EXISTS containers_profiles ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, profile_id INTEGER NOT NULL, apply_order INTEGER NOT NULL default 0, UNIQUE (container_id, profile_id), FOREIGN KEY (container_id) REFERENCES containers(id) ON DELETE CASCADE, FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE ); INSERT INTO containers_profiles SELECT * FROM tmp; DROP TABLE tmp; CREATE TEMP TABLE tmp AS SELECT * FROM images_aliases; DROP TABLE images_aliases; CREATE TABLE IF NOT EXISTS images_aliases ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, image_id INTEGER NOT NULL, description VARCHAR(255), FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE, UNIQUE (name) ); INSERT INTO images_aliases SELECT * FROM tmp; DROP TABLE tmp; CREATE TEMP TABLE tmp AS SELECT * FROM images_properties; DROP TABLE images_properties; CREATE TABLE IF NOT EXISTS images_properties ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, image_id INTEGER NOT NULL, type INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE ); INSERT INTO images_properties SELECT * FROM tmp; DROP TABLE tmp; CREATE TEMP TABLE tmp AS SELECT * FROM profiles_config; DROP TABLE profiles_config; CREATE TABLE IF NOT EXISTS profiles_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value VARCHAR(255), UNIQUE (profile_id, key), FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE ); INSERT INTO profiles_config SELECT * FROM tmp; DROP TABLE tmp; CREATE TEMP TABLE tmp AS SELECT * FROM profiles_devices; DROP TABLE profiles_devices; CREATE TABLE IF NOT EXISTS profiles_devices ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, type INTEGER NOT NULL default 0, UNIQUE (profile_id, name), FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE ); INSERT INTO profiles_devices SELECT * FROM tmp; DROP TABLE tmp; CREATE TEMP TABLE tmp AS SELECT * FROM profiles_devices_config; DROP TABLE profiles_devices_config; CREATE TABLE IF NOT EXISTS profiles_devices_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_device_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, UNIQUE (profile_device_id, key), FOREIGN KEY (profile_device_id) REFERENCES profiles_devices (id) ON DELETE CASCADE ); INSERT INTO profiles_devices_config SELECT * FROM tmp; DROP TABLE tmp; PRAGMA foreign_keys=ON; -- Make sure we turn integrity checks back on.` _, err := tx.Exec(stmt) if err != nil { return err } // Get the rows with broken foreign keys an nuke them rows, err := tx.Query("PRAGMA foreign_key_check;") if err != nil { return err } var tablestodelete []string var rowidtodelete []int defer rows.Close() for rows.Next() { var tablename string var rowid int var targetname string var keynumber int rows.Scan(&tablename, &rowid, &targetname, &keynumber) tablestodelete = append(tablestodelete, tablename) rowidtodelete = append(rowidtodelete, rowid) } rows.Close() for i := range tablestodelete { _, err = tx.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = %d;", tablestodelete[i], rowidtodelete[i])) if err != nil { return err } } return err } func updateFromV5(tx *sql.Tx) error { stmt := ` ALTER TABLE containers ADD COLUMN power_state INTEGER NOT NULL DEFAULT 0; ALTER TABLE containers ADD COLUMN ephemeral INTEGER NOT NULL DEFAULT 0;` _, err := tx.Exec(stmt) return err } func updateFromV4(tx *sql.Tx) error { stmt := ` CREATE TABLE IF NOT EXISTS config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, UNIQUE (key) );` _, err := tx.Exec(stmt) if err != nil { return err } passfname := shared.VarPath("adminpwd") passOut, err := os.Open(passfname) oldPassword := "" if err == nil { defer passOut.Close() buff := make([]byte, 96) _, err = passOut.Read(buff) if err != nil { return err } oldPassword = hex.EncodeToString(buff) stmt := `INSERT INTO config (key, value) VALUES ("core.trust_password", ?);` _, err := tx.Exec(stmt, oldPassword) if err != nil { return err } return os.Remove(passfname) } return nil } func updateFromV3(tx *sql.Tx) error { // Attempt to create a default profile (but don't fail if already there) tx.Exec("INSERT INTO profiles (name) VALUES (\"default\");") return nil } func updateFromV2(tx *sql.Tx) error { stmt := ` CREATE TABLE IF NOT EXISTS containers_devices ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, type INTEGER NOT NULL default 0, FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE, UNIQUE (container_id, name) ); CREATE TABLE IF NOT EXISTS containers_devices_config ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_device_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_device_id) REFERENCES containers_devices (id), UNIQUE (container_device_id, key) ); CREATE TABLE IF NOT EXISTS containers_profiles ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, profile_id INTEGER NOT NULL, apply_order INTEGER NOT NULL default 0, UNIQUE (container_id, profile_id), FOREIGN KEY (container_id) REFERENCES containers(id) ON DELETE CASCADE, FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS profiles ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, UNIQUE (name) ); CREATE TABLE IF NOT EXISTS profiles_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value VARCHAR(255), UNIQUE (profile_id, key), FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS profiles_devices ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, type INTEGER NOT NULL default 0, UNIQUE (profile_id, name), FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS profiles_devices_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_device_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, UNIQUE (profile_device_id, key), FOREIGN KEY (profile_device_id) REFERENCES profiles_devices (id) );` _, err := tx.Exec(stmt) return err } func updateFromV1(tx *sql.Tx) error { // v1..v2 adds images aliases stmt := ` CREATE TABLE IF NOT EXISTS images_aliases ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, image_id INTEGER NOT NULL, description VARCHAR(255), FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE, UNIQUE (name) );` _, err := tx.Exec(stmt) return err } func updateFromV0(tx *sql.Tx) error { // v0..v1 the dawn of containers stmt := ` CREATE TABLE certificates ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fingerprint VARCHAR(255) NOT NULL, type INTEGER NOT NULL, name VARCHAR(255) NOT NULL, certificate TEXT NOT NULL, UNIQUE (fingerprint) ); CREATE TABLE containers ( id INTEGER primary key AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, architecture INTEGER NOT NULL, type INTEGER NOT NULL, UNIQUE (name) ); CREATE TABLE containers_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_id) REFERENCES containers (id), UNIQUE (container_id, key) ); CREATE TABLE images ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fingerprint VARCHAR(255) NOT NULL, filename VARCHAR(255) NOT NULL, size INTEGER NOT NULL, public INTEGER NOT NULL DEFAULT 0, architecture INTEGER NOT NULL, creation_date DATETIME, expiry_date DATETIME, upload_date DATETIME NOT NULL, UNIQUE (fingerprint) ); CREATE TABLE images_properties ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, image_id INTEGER NOT NULL, type INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (image_id) REFERENCES images (id) );` _, err := tx.Exec(stmt) return err } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/schema/���������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016105� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/schema/schema_test.go�������������������������������������������������������������0000644�0610621�0607500�00000017155�13172163242�020744� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package schema_test import ( "database/sql" "fmt" "testing" _ "github.com/mattn/go-sqlite3" "github.com/stretchr/testify/assert" "github.com/lxc/lxd/lxd/db/query" "github.com/lxc/lxd/lxd/db/schema" ) // Create a new Schema by specifying an explicit map from versions to Update // functions. func TestNewFromMap(t *testing.T) { db := newDB(t) schema := schema.NewFromMap(map[int]schema.Update{ 1: updateCreateTable, 2: updateInsertValue, }) assert.NoError(t, schema.Ensure(db)) } // Panic if there are missing versions in the map. func TestNewFromMap_MissingVersions(t *testing.T) { assert.Panics(t, func() { schema.NewFromMap(map[int]schema.Update{ 1: updateCreateTable, 3: updateInsertValue, }) }, "updates map misses version 2") } // If the database schema version is more recent than our update series, an // error is returned. func TestSchemaEnsure_VersionMoreRecentThanExpected(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateNoop) assert.NoError(t, schema.Ensure(db)) schema, _ = newSchemaAndDB(t) err := schema.Ensure(db) assert.NotNil(t, err) assert.EqualError(t, err, "schema version '1' is more recent than expected '0'") } // If the database schema contains "holes" in the applied versions, an error is // returned. func TestSchemaEnsure_MissingVersion(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateNoop) assert.NoError(t, schema.Ensure(db)) _, err := db.Exec(`INSERT INTO schema (version, updated_at) VALUES (3, strftime("%s"))`) schema.Add(updateNoop) schema.Add(updateNoop) err = schema.Ensure(db) assert.NotNil(t, err) assert.EqualError(t, err, "missing updates: 1 -> 3") } // If the schema has no update, the schema table gets created and has no version. func TestSchemaEnsure_ZeroUpdates(t *testing.T) { schema, db := newSchemaAndDB(t) err := schema.Ensure(db) assert.NoError(t, err) tx, err := db.Begin() assert.NoError(t, err) versions, err := query.SelectIntegers(tx, "SELECT version FROM SCHEMA") assert.NoError(t, err) assert.Equal(t, []int{}, versions) } // If the schema has updates and no one was applied yet, all of them get // applied. func TestSchemaEnsure_ApplyAllUpdates(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateCreateTable) schema.Add(updateInsertValue) err := schema.Ensure(db) assert.NoError(t, err) tx, err := db.Begin() assert.NoError(t, err) // THe update version is recorded. versions, err := query.SelectIntegers(tx, "SELECT version FROM SCHEMA") assert.NoError(t, err) assert.Equal(t, []int{1, 2}, versions) // The two updates have been applied in order. ids, err := query.SelectIntegers(tx, "SELECT id FROM test") assert.NoError(t, err) assert.Equal(t, []int{1}, ids) } // If the schema schema has been created using a dump, the schema table will // contain just one row with the update level associated with the dump. It's // possible to apply further updates from there, and only these new ones will // be inserted in the schema table. func TestSchemaEnsure_ApplyAfterInitialDumpCreation(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateCreateTable) schema.Add(updateAddColumn) assert.NoError(t, schema.Ensure(db)) dump, err := schema.Dump(db) assert.NoError(t, err) _, db = newSchemaAndDB(t) _, err = db.Exec(dump) assert.NoError(t, err) schema.Add(updateNoop) assert.NoError(t, schema.Ensure(db)) tx, err := db.Begin() assert.NoError(t, err) // Only updates starting from the initial dump are recorded. versions, err := query.SelectIntegers(tx, "SELECT version FROM SCHEMA") assert.NoError(t, err) assert.Equal(t, []int{2, 3}, versions) } // If the schema has updates and part of them were already applied, only the // missing ones are applied. func TestSchemaEnsure_OnlyApplyMissing(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateCreateTable) assert.NoError(t, schema.Ensure(db)) schema.Add(updateInsertValue) assert.NoError(t, schema.Ensure(db)) tx, err := db.Begin() assert.NoError(t, err) // All update versions are recorded. versions, err := query.SelectIntegers(tx, "SELECT version FROM SCHEMA") assert.NoError(t, err) assert.Equal(t, []int{1, 2}, versions) // The two updates have been applied in order. ids, err := query.SelectIntegers(tx, "SELECT id FROM test") assert.NoError(t, err) assert.Equal(t, []int{1}, ids) } // If a update fails, an error is returned, and all previous changes are rolled // back. func TestSchemaEnsure_FailingUpdate(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateCreateTable) schema.Add(updateBoom) err := schema.Ensure(db) assert.EqualError(t, err, "failed to apply update 1: boom") tx, err := db.Begin() assert.NoError(t, err) // Not update was applied. tables, err := query.SelectStrings(tx, "SELECT name FROM sqlite_master WHERE type = 'table'") assert.NoError(t, err) assert.NotContains(t, tables, "schema") assert.NotContains(t, tables, "test") } // If a hook fails, an error is returned, and all previous changes are rolled // back. func TestSchemaEnsure_FailingHook(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateCreateTable) schema.Hook(func(int, *sql.Tx) error { return fmt.Errorf("boom") }) err := schema.Ensure(db) assert.EqualError(t, err, "failed to execute hook (version 0): boom") tx, err := db.Begin() assert.NoError(t, err) // Not update was applied. tables, err := query.SelectStrings(tx, "SELECT name FROM sqlite_master WHERE type = 'table'") assert.NoError(t, err) assert.NotContains(t, tables, "schema") assert.NotContains(t, tables, "test") } // The SQL text returns by Dump() can be used to create the schema from // scratch, without applying each individual update. func TestSchemaDump(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateCreateTable) schema.Add(updateAddColumn) assert.NoError(t, schema.Ensure(db)) dump, err := schema.Dump(db) assert.NoError(t, err) _, db = newSchemaAndDB(t) _, err = db.Exec(dump) assert.NoError(t, err) tx, err := db.Begin() assert.NoError(t, err) // All update versions are in place. versions, err := query.SelectIntegers(tx, "SELECT version FROM schema") assert.NoError(t, err) assert.Equal(t, []int{2}, versions) // Both the table added by the first update and the extra column added // by the second update are there. _, err = tx.Exec("SELECT id, name FROM test") assert.NoError(t, err) } // If not all updates are applied, Dump() returns an error. func TestSchemaDump_MissingUpdatees(t *testing.T) { schema, db := newSchemaAndDB(t) schema.Add(updateCreateTable) assert.NoError(t, schema.Ensure(db)) schema.Add(updateAddColumn) _, err := schema.Dump(db) assert.EqualError(t, err, "update level is 1, expected 2") } // Return a new in-memory SQLite database. func newDB(t *testing.T) *sql.DB { db, err := sql.Open("sqlite3", ":memory:") assert.NoError(t, err) return db } // Return both an empty schema and a test database. func newSchemaAndDB(t *testing.T) (*schema.Schema, *sql.DB) { return schema.Empty(), newDB(t) } // An update that does nothing. func updateNoop(*sql.Tx) error { return nil } // An update that creates a test table. func updateCreateTable(tx *sql.Tx) error { _, err := tx.Exec("CREATE TABLE test (id INTEGER)") return err } // An update that inserts a value into the test table. func updateInsertValue(tx *sql.Tx) error { _, err := tx.Exec("INSERT INTO test VALUES (1)") return err } // An update that adds a column to the test tabble. func updateAddColumn(tx *sql.Tx) error { _, err := tx.Exec("ALTER TABLE test ADD COLUMN name TEXT") return err } // An update that unconditionally fails with an error. func updateBoom(tx *sql.Tx) error { return fmt.Errorf("boom") } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/schema/schema.go������������������������������������������������������������������0000644�0610621�0607500�00000017107�13172163242�017702� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package schema import ( "database/sql" "fmt" "sort" "strings" "github.com/lxc/lxd/lxd/db/query" "github.com/lxc/lxd/shared" ) // Schema captures the schema of a database in terms of a series of ordered // updates. type Schema struct { updates []Update // Ordered series of updates making up the schema hook Hook // Optional hook to execute whenever a update gets applied } // Update applies a specific schema change to a database, and returns an error // if anything goes wrong. type Update func(*sql.Tx) error // Hook is a callback that gets fired when a update gets applied. type Hook func(int, *sql.Tx) error // New creates a new schema Schema with the given updates. func New(updates []Update) *Schema { return &Schema{ updates: updates, } } // NewFromMap creates a new schema Schema with the updates specified in the // given map. The keys of the map are schema versions that when upgraded will // trigger the associated Update value. It's required that the minimum key in // the map is 1, and if key N is present then N-1 is present too, with N>1 // (i.e. there are no missing versions). // // NOTE: the regular New() constructor would be formally enough, but for extra // clarity we also support a map that indicates the version explicitely, // see also PR #3704. func NewFromMap(versionsToUpdates map[int]Update) *Schema { // Collect all version keys. versions := []int{} for version := range versionsToUpdates { versions = append(versions, version) } // Sort the versions, sort.Sort(sort.IntSlice(versions)) // Build the updates slice. updates := []Update{} for i, version := range versions { // Assert that we start from 1 and there are no gaps. if version != i+1 { panic(fmt.Sprintf("updates map misses version %d", i+1)) } updates = append(updates, versionsToUpdates[version]) } return &Schema{ updates: updates, } } // Empty creates a new schema with no updates. func Empty() *Schema { return New([]Update{}) } // Add a new update to the schema. It will be appended at the end of the // existing series. func (s *Schema) Add(update Update) { s.updates = append(s.updates, update) } // Hook instructs the schema to invoke the given function whenever a update is // about to be applied. The function gets passed the update version number and // the running transaction, and if it returns an error it will cause the schema // transaction to be rolled back. Any previously installed hook will be // replaced. func (s *Schema) Hook(hook Hook) { s.hook = hook } // Ensure makes sure that the actual schema in the given database matches the // one defined by our updates. // // All updates are applied transactionally. In case any error occurs the // transaction will be rolled back and the database will remain unchanged. // // A update will be applied only if it hasn't been before (currently applied // updates are tracked in the a 'shema' table, which gets automatically // created). func (s *Schema) Ensure(db *sql.DB) error { return query.Transaction(db, func(tx *sql.Tx) error { err := ensureSchemaTableExists(tx) if err != nil { return err } err = ensureUpdatesAreApplied(tx, s.updates, s.hook) if err != nil { return err } return nil }) } // Dump returns a text of SQL commands that can be used to create this schema // from scratch in one go, without going thorugh individual patches // (essentially flattening them). // // It requires that all patches in this schema have been applied, otherwise an // error will be returned. func (s *Schema) Dump(db *sql.DB) (string, error) { var statements []string err := query.Transaction(db, func(tx *sql.Tx) error { err := checkAllUpdatesAreApplied(tx, s.updates) if err != nil { return err } statements, err = selectTablesSQL(tx) return err }) if err != nil { return "", err } for i, statement := range statements { statements[i] = formatSQL(statement) } // Add a statement for inserting the current schema version row. statements = append( statements, fmt.Sprintf(` INSERT INTO schema (version, updated_at) VALUES (%d, strftime("%%s")) `, len(s.updates))) return strings.Join(statements, ";\n"), nil } // Ensure that the schema exists. func ensureSchemaTableExists(tx *sql.Tx) error { exists, err := doesSchemaTableExist(tx) if err != nil { return fmt.Errorf("failed to check if schema table is there: %v", err) } if !exists { err := createSchemaTable(tx) if err != nil { return fmt.Errorf("failed to create schema table: %v", err) } } return nil } // Apply any pending update that was not yet applied. func ensureUpdatesAreApplied(tx *sql.Tx, updates []Update, hook Hook) error { versions, err := selectSchemaVersions(tx) if err != nil { return fmt.Errorf("failed to fetch update versions: %v", err) } // Fix bad upgrade code between 30 and 32 if shared.IntInSlice(30, versions) && shared.IntInSlice(32, versions) && !shared.IntInSlice(31, versions) { err = insertSchemaVersion(tx, 31) if err != nil { return fmt.Errorf("failed to insert missing schema version 31") } versions, err = selectSchemaVersions(tx) if err != nil { return fmt.Errorf("failed to fetch update versions: %v", err) } } current := 0 if len(versions) > 0 { err = checkSchemaVersionsHaveNoHoles(versions) if err != nil { return err } current = versions[len(versions)-1] // Highest recorded version } if current > len(updates) { return fmt.Errorf( "schema version '%d' is more recent than expected '%d'", current, len(updates)) } // If there are no updates, there's nothing to do. if len(updates) == 0 { return nil } // Apply missing updates. for _, update := range updates[current:] { if hook != nil { err := hook(current, tx) if err != nil { return fmt.Errorf("failed to execute hook (version %d): %v", current, err) } } err := update(tx) if err != nil { return fmt.Errorf("failed to apply update %d: %v", current, err) } current++ err = insertSchemaVersion(tx, current) if err != nil { return fmt.Errorf("failed to insert version %d", current) } } return nil } // Check that the given list of update version numbers doesn't have "holes", // that is each version equal the preceeding version plus 1. func checkSchemaVersionsHaveNoHoles(versions []int) error { // Sanity check that there are no "holes" in the recorded // versions. for i := range versions[:len(versions)-1] { if versions[i+1] != versions[i]+1 { return fmt.Errorf( "missing updates: %d -> %d", versions[i], versions[i+1]) } } return nil } // Check that all the given updates are applied. func checkAllUpdatesAreApplied(tx *sql.Tx, updates []Update) error { versions, err := selectSchemaVersions(tx) if err != nil { return fmt.Errorf("failed to fetch update versions: %v", err) } if len(versions) == 0 { return fmt.Errorf("expected schema table to contain at least one row") } err = checkSchemaVersionsHaveNoHoles(versions) if err != nil { return err } current := versions[len(versions)-1] if current != len(updates) { return fmt.Errorf("update level is %d, expected %d", current, len(updates)) } return nil } // Format the given SQL statement in a human-readable way. // // In particular make sure that each column definition in a CREATE TABLE clause // is in its own row, since SQLite dumps occasionally stuff more than one // column in the same line. func formatSQL(statement string) string { lines := strings.Split(statement, "\n") for i, line := range lines { if strings.Contains(line, "UNIQUE") { // Let UNIQUE(x, y) constraints alone. continue } lines[i] = strings.Replace(line, ", ", ",\n ", -1) } return strings.Join(lines, "\n") } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/schema/query.go�������������������������������������������������������������������0000644�0610621�0607500�00000003206�13172163242�017602� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package schema import ( "database/sql" "fmt" "github.com/lxc/lxd/lxd/db/query" ) // Return whether the schema table is present in the database. func doesSchemaTableExist(tx *sql.Tx) (bool, error) { statement := ` SELECT COUNT(name) FROM sqlite_master WHERE type = 'table' AND name = 'schema' ` rows, err := tx.Query(statement) if err != nil { return false, err } defer rows.Close() if !rows.Next() { return false, fmt.Errorf("schema table query returned no rows") } var count int err = rows.Scan(&count) if err != nil { return false, err } return count == 1, nil } // Return all versions in the schema table, in increasing order. func selectSchemaVersions(tx *sql.Tx) ([]int, error) { statement := ` SELECT version FROM schema ORDER BY version ` return query.SelectIntegers(tx, statement) } // Return a list of SQL statements that can be used to create all tables in the // database. func selectTablesSQL(tx *sql.Tx) ([]string, error) { statement := ` SELECT sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name ` return query.SelectStrings(tx, statement) } // Create the schema table. func createSchemaTable(tx *sql.Tx) error { statement := ` CREATE TABLE schema ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, version INTEGER NOT NULL, updated_at DATETIME NOT NULL, UNIQUE (version) ) ` _, err := tx.Exec(statement, nil) return err } // Insert a new version into the schema table. func insertSchemaVersion(tx *sql.Tx, new int) error { statement := ` INSERT INTO schema (version, updated_at) VALUES (?, strftime("%s")) ` _, err := tx.Exec(statement, new) return err } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/schema/doc.go���������������������������������������������������������������������0000644�0610621�0607500�00000000134�13172163242�017177� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package schema offers utilities to create and maintain a database schema. package schema ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/schema.go�������������������������������������������������������������������������0000644�0610621�0607500�00000011537�13172163242�016443� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db // DO NOT EDIT BY HAND // // This code was generated by the UpdateSchemaDotGo function. If you need to // modify the database schema, please add a new schema update to update.go // and the run 'make update-schema'. const CURRENT_SCHEMA = ` CREATE TABLE certificates ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fingerprint VARCHAR(255) NOT NULL, type INTEGER NOT NULL, name VARCHAR(255) NOT NULL, certificate TEXT NOT NULL, UNIQUE (fingerprint) ); CREATE TABLE config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, UNIQUE (key) ); CREATE TABLE "containers" ( id INTEGER primary key AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, architecture INTEGER NOT NULL, type INTEGER NOT NULL, ephemeral INTEGER NOT NULL DEFAULT 0, creation_date DATETIME NOT NULL DEFAULT 0, stateful INTEGER NOT NULL DEFAULT 0, UNIQUE (name) ); CREATE TABLE containers_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE, UNIQUE (container_id, key) ); CREATE TABLE containers_devices ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, type INTEGER NOT NULL default 0, FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE, UNIQUE (container_id, name) ); CREATE TABLE containers_devices_config ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_device_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_device_id) REFERENCES containers_devices (id) ON DELETE CASCADE, UNIQUE (container_device_id, key) ); CREATE TABLE containers_profiles ( id INTEGER primary key AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, profile_id INTEGER NOT NULL, apply_order INTEGER NOT NULL default 0, UNIQUE (container_id, profile_id), FOREIGN KEY (container_id) REFERENCES containers(id) ON DELETE CASCADE, FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE ); CREATE TABLE images ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fingerprint VARCHAR(255) NOT NULL, filename VARCHAR(255) NOT NULL, size INTEGER NOT NULL, public INTEGER NOT NULL DEFAULT 0, architecture INTEGER NOT NULL, creation_date DATETIME, expiry_date DATETIME, upload_date DATETIME NOT NULL, cached INTEGER NOT NULL DEFAULT 0, last_use_date DATETIME, auto_update INTEGER NOT NULL DEFAULT 0, UNIQUE (fingerprint) ); CREATE TABLE images_aliases ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, image_id INTEGER NOT NULL, description VARCHAR(255), FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE, UNIQUE (name) ); CREATE TABLE images_properties ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, image_id INTEGER NOT NULL, type INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE ); CREATE TABLE images_source ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, image_id INTEGER NOT NULL, server TEXT NOT NULL, protocol INTEGER NOT NULL, certificate TEXT NOT NULL, alias VARCHAR(255) NOT NULL, FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE ); CREATE TABLE patches ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, applied_at DATETIME NOT NULL, UNIQUE (name) ); CREATE TABLE profiles ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, description TEXT, UNIQUE (name) ); CREATE TABLE profiles_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value VARCHAR(255), UNIQUE (profile_id, key), FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE ); CREATE TABLE profiles_devices ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, type INTEGER NOT NULL default 0, UNIQUE (profile_id, name), FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE ); CREATE TABLE profiles_devices_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profile_device_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, UNIQUE (profile_device_id, key), FOREIGN KEY (profile_device_id) REFERENCES profiles_devices (id) ON DELETE CASCADE ); CREATE TABLE schema ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, version INTEGER NOT NULL, updated_at DATETIME NOT NULL, UNIQUE (version) ); INSERT INTO schema (version, updated_at) VALUES (32, strftime("%s")) ` �����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/����������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�016012� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/transaction_test.go���������������������������������������������������������0000644�0610621�0607500�00000002256�13172163242�021732� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package query_test import ( "database/sql" "fmt" "testing" "github.com/lxc/lxd/lxd/db/query" _ "github.com/mattn/go-sqlite3" "github.com/stretchr/testify/assert" ) // Any error happening when beginning the transaction will be propagated. func TestTransaction_BeginError(t *testing.T) { db := newDB(t) db.Close() err := query.Transaction(db, func(*sql.Tx) error { return nil }) assert.NotNil(t, err) assert.Contains(t, err.Error(), "failed to begin transaction") } // Any error happening when in the transaction function will cause a rollback. func TestTransaction_FunctionError(t *testing.T) { db := newDB(t) err := query.Transaction(db, func(tx *sql.Tx) error { _, err := tx.Exec("CREATE TABLE test (id INTEGER)") assert.NoError(t, err) return fmt.Errorf("boom") }) assert.EqualError(t, err, "boom") tx, err := db.Begin() assert.NoError(t, err) tables, err := query.SelectStrings(tx, "SELECT name FROM sqlite_master WHERE type = 'table'") assert.NoError(t, err) assert.NotContains(t, tables, "test") } // Return a new in-memory SQLite database. func newDB(t *testing.T) *sql.DB { db, err := sql.Open("sqlite3", ":memory:") assert.NoError(t, err) return db } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/transaction.go��������������������������������������������������������������0000644�0610621�0607500�00000001345�13172163242�020671� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package query import ( "database/sql" "fmt" ) // Transaction executes the given function within a database transaction. func Transaction(db *sql.DB, f func(*sql.Tx) error) error { tx, err := db.Begin() if err != nil { return fmt.Errorf("failed to begin transaction: %v", err) } err = f(tx) if err != nil { return rollback(tx, err) } return tx.Commit() } // Rollback a transaction after the given error occured. If the rollback // succeeds the given error is returned, otherwise a new error that wraps it // gets generated and returned. func rollback(tx *sql.Tx, reason error) error { err := tx.Rollback() if err != nil { return fmt.Errorf("failed to rollback transaction after error (%v)", reason) } return reason } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/slices_test.go��������������������������������������������������������������0000644�0610621�0607500�00000003427�13172163242�020670� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package query_test import ( "database/sql" "testing" _ "github.com/mattn/go-sqlite3" "github.com/stretchr/testify/assert" "github.com/lxc/lxd/lxd/db/query" "github.com/lxc/lxd/shared/subtest" ) // Exercise possible failure modes. func TestStrings_Error(t *testing.T) { for _, c := range testStringsErrorCases { subtest.Run(t, c.query, func(t *testing.T) { tx := newTxForSlices(t) values, err := query.SelectStrings(tx, c.query) assert.EqualError(t, err, c.error) assert.Nil(t, values) }) } } // All values yield by the query are returned. func TestStrings(t *testing.T) { tx := newTxForSlices(t) values, err := query.SelectStrings(tx, "SELECT name FROM test ORDER BY name") assert.Nil(t, err) assert.Equal(t, []string{"bar", "foo"}, values) } // Exercise possible failure modes. func TestIntegers_Error(t *testing.T) { for _, c := range testIntegersErrorCases { subtest.Run(t, c.query, func(t *testing.T) { tx := newTxForSlices(t) values, err := query.SelectIntegers(tx, c.query) assert.EqualError(t, err, c.error) assert.Nil(t, values) }) } } // All values yield by the query are returned. func TestIntegers(t *testing.T) { tx := newTxForSlices(t) values, err := query.SelectIntegers(tx, "SELECT id FROM test ORDER BY id") assert.Nil(t, err) assert.Equal(t, []int{0, 1}, values) } // Return a new transaction against an in-memory SQLite database with a single // test table populated with a few rows. func newTxForSlices(t *testing.T) *sql.Tx { db, err := sql.Open("sqlite3", ":memory:") assert.NoError(t, err) _, err = db.Exec("CREATE TABLE test (id INTEGER, name TEXT)") assert.NoError(t, err) _, err = db.Exec("INSERT INTO test VALUES (0, 'foo'), (1, 'bar')") assert.NoError(t, err) tx, err := db.Begin() assert.NoError(t, err) return tx } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/slices_1_8_test.go����������������������������������������������������������0000644�0610621�0607500�00000001041�13172163242�021325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.8 package query_test var testStringsErrorCases = []struct { query string error string }{ {"garbage", "near \"garbage\": syntax error"}, {"SELECT id, name FROM test", "query yields 2 columns, not 1"}, {"SELECT id FROM test", "query yields INTEGER column, not TEXT"}, } var testIntegersErrorCases = []struct { query string error string }{ {"garbage", "near \"garbage\": syntax error"}, {"SELECT id, name FROM test", "query yields 2 columns, not 1"}, {"SELECT name FROM test", "query yields TEXT column, not INTEGER"}, } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/slices_1_8.go���������������������������������������������������������������0000644�0610621�0607500�00000001134�13172163242�020271� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build go1.8 package query import ( "database/sql" "fmt" "strings" ) // Check that the given result set yields rows with a single column of a // specific type. func checkRowsHaveOneColumnOfSpecificType(rows *sql.Rows, typeName string) error { types, err := rows.ColumnTypes() if err != nil { return err } if len(types) != 1 { return fmt.Errorf("query yields %d columns, not 1", len(types)) } actualTypeName := strings.ToUpper(types[0].DatabaseTypeName()) if actualTypeName != typeName { return fmt.Errorf("query yields %s column, not %s", actualTypeName, typeName) } return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/slices_1_6_test.go����������������������������������������������������������0000644�0610621�0607500�00000000560�13172163242�021330� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.8 package query_test var testStringsErrorCases = []struct { query string error string }{ {"garbage", "near \"garbage\": syntax error"}, {"SELECT id, name FROM test", "sql: expected 2 destination arguments in Scan, not 1"}, } var testIntegersErrorCases = []struct { query string error string }{ {"garbage", "near \"garbage\": syntax error"}, } ������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/slices_1_6.go���������������������������������������������������������������0000644�0610621�0607500�00000001015�13172163242�020265� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !go1.8 package query import "database/sql" // Check that the given result set yields rows with a single column of a // specific type. func checkRowsHaveOneColumnOfSpecificType(rows *sql.Rows, typeName string) error { // The Rows.ColumnTypes() method is available only since Go 1.8, so we // just return nil for <1.8. This is safe to do since if the returned // rows are not of the expected type, call sites will still fail at // Rows.Scan() time, although the error message will be less clear. return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/slices.go�������������������������������������������������������������������0000644�0610621�0607500�00000003222�13172163242�017622� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package query import ( "database/sql" ) // SelectStrings executes a statement which must yield rows with a single string // column. It returns the list of column values. func SelectStrings(tx *sql.Tx, query string) ([]string, error) { values := []string{} scan := func(rows *sql.Rows) error { var value string err := rows.Scan(&value) if err != nil { return err } values = append(values, value) return nil } err := scanSingleColumn(tx, query, "TEXT", scan) if err != nil { return nil, err } return values, nil } // SelectIntegers executes a statement which must yield rows with a single integer // column. It returns the list of column values. func SelectIntegers(tx *sql.Tx, query string) ([]int, error) { values := []int{} scan := func(rows *sql.Rows) error { var value int err := rows.Scan(&value) if err != nil { return err } values = append(values, value) return nil } err := scanSingleColumn(tx, query, "INTEGER", scan) if err != nil { return nil, err } return values, nil } // Execute the given query and ensure that it yields rows with a single column // of the given database type. For every row yielded, execute the given // scanner. func scanSingleColumn(tx *sql.Tx, query string, typeName string, scan scanFunc) error { rows, err := tx.Query(query) if err != nil { return err } defer rows.Close() err = checkRowsHaveOneColumnOfSpecificType(rows, typeName) if err != nil { return err } for rows.Next() { err := scan(rows) if err != nil { return err } } err = rows.Err() if err != nil { return err } return nil } // Function to scan a single row. type scanFunc func(*sql.Rows) error ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/query/doc.go����������������������������������������������������������������������0000644�0610621�0607500�00000000176�13172163242�017112� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package query implements helpers around database/sql to execute various // kinds of very common SQL queries. package query ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/profiles.go�����������������������������������������������������������������������0000644�0610621�0607500�00000014316�13172163242�017024� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" "github.com/lxc/lxd/lxd/types" "github.com/lxc/lxd/shared/api" ) // Profiles returns a string list of profiles. func Profiles(db *sql.DB) ([]string, error) { q := fmt.Sprintf("SELECT name FROM profiles") inargs := []interface{}{} var name string outfmt := []interface{}{name} result, err := QueryScan(db, q, inargs, outfmt) if err != nil { return []string{}, err } response := []string{} for _, r := range result { response = append(response, r[0].(string)) } return response, nil } func ProfileGet(db *sql.DB, name string) (int64, *api.Profile, error) { id := int64(-1) description := sql.NullString{} q := "SELECT id, description FROM profiles WHERE name=?" arg1 := []interface{}{name} arg2 := []interface{}{&id, &description} err := dbQueryRowScan(db, q, arg1, arg2) if err != nil { return -1, nil, err } config, err := ProfileConfig(db, name) if err != nil { return -1, nil, err } devices, err := Devices(db, name, true) if err != nil { return -1, nil, err } profile := api.Profile{ Name: name, } profile.Config = config profile.Description = description.String profile.Devices = devices return id, &profile, nil } func ProfileCreate(db *sql.DB, profile string, description string, config map[string]string, devices types.Devices) (int64, error) { tx, err := Begin(db) if err != nil { return -1, err } result, err := tx.Exec("INSERT INTO profiles (name, description) VALUES (?, ?)", profile, description) if err != nil { tx.Rollback() return -1, err } id, err := result.LastInsertId() if err != nil { tx.Rollback() return -1, err } err = ProfileConfigAdd(tx, id, config) if err != nil { tx.Rollback() return -1, err } err = DevicesAdd(tx, "profile", id, devices) if err != nil { tx.Rollback() return -1, err } err = TxCommit(tx) if err != nil { return -1, err } return id, nil } func ProfileCreateDefault(db *sql.DB) error { id, _, _ := ProfileGet(db, "default") if id != -1 { // default profile already exists return nil } // TODO: We should scan for bridges and use the best available as default. devices := map[string]map[string]string{ "eth0": { "name": "eth0", "type": "nic", "nictype": "bridged", "parent": "lxdbr0"}} _, err := ProfileCreate(db, "default", "Default LXD profile", map[string]string{}, devices) if err != nil { return err } return nil } func dbProfileCreateDocker(db *sql.DB) error { id, _, err := ProfileGet(db, "docker") if id != -1 { // docker profile already exists return nil } config := map[string]string{ "security.nesting": "true", "linux.kernel_modules": "overlay, nf_nat"} aadisable := map[string]string{ "path": "/sys/module/apparmor/parameters/enabled", "type": "disk", "source": "/dev/null", } devices := map[string]map[string]string{"aadisable": aadisable} _, err = ProfileCreate(db, "docker", "Profile supporting docker in containers", config, devices) return err } // Get the profile configuration map from the DB func ProfileConfig(db *sql.DB, name string) (map[string]string, error) { var key, value string query := ` SELECT key, value FROM profiles_config JOIN profiles ON profiles_config.profile_id=profiles.id WHERE name=?` inargs := []interface{}{name} outfmt := []interface{}{key, value} results, err := QueryScan(db, query, inargs, outfmt) if err != nil { return nil, fmt.Errorf("Failed to get profile '%s'", name) } if len(results) == 0 { /* * If we didn't get any rows here, let's check to make sure the * profile really exists; if it doesn't, let's send back a 404. */ query := "SELECT id FROM profiles WHERE name=?" var id int results, err := QueryScan(db, query, []interface{}{name}, []interface{}{id}) if err != nil { return nil, err } if len(results) == 0 { return nil, NoSuchObjectError } } config := map[string]string{} for _, r := range results { key = r[0].(string) value = r[1].(string) config[key] = value } return config, nil } func ProfileDelete(db *sql.DB, name string) error { id, _, err := ProfileGet(db, name) if err != nil { return err } _, err = Exec(db, "DELETE FROM profiles WHERE id=?", id) if err != nil { return err } return nil } func ProfileUpdate(db *sql.DB, name string, newName string) error { tx, err := Begin(db) if err != nil { return err } _, err = tx.Exec("UPDATE profiles SET name=? WHERE name=?", newName, name) if err != nil { tx.Rollback() return err } err = TxCommit(tx) return err } func ProfileDescriptionUpdate(tx *sql.Tx, id int64, description string) error { _, err := tx.Exec("UPDATE profiles SET description=? WHERE id=?", description, id) return err } func ProfileConfigClear(tx *sql.Tx, id int64) error { _, err := tx.Exec("DELETE FROM profiles_config WHERE profile_id=?", id) if err != nil { return err } _, err = tx.Exec(`DELETE FROM profiles_devices_config WHERE id IN (SELECT profiles_devices_config.id FROM profiles_devices_config JOIN profiles_devices ON profiles_devices_config.profile_device_id=profiles_devices.id WHERE profiles_devices.profile_id=?)`, id) if err != nil { return err } _, err = tx.Exec("DELETE FROM profiles_devices WHERE profile_id=?", id) if err != nil { return err } return nil } func ProfileConfigAdd(tx *sql.Tx, id int64, config map[string]string) error { str := fmt.Sprintf("INSERT INTO profiles_config (profile_id, key, value) VALUES(?, ?, ?)") stmt, err := tx.Prepare(str) defer stmt.Close() for k, v := range config { _, err = stmt.Exec(id, k, v) if err != nil { return err } } return nil } func ProfileContainersGet(db *sql.DB, profile string) ([]string, error) { q := `SELECT containers.name FROM containers JOIN containers_profiles ON containers.id == containers_profiles.container_id JOIN profiles ON containers_profiles.profile_id == profiles.id WHERE profiles.name == ?` results := []string{} inargs := []interface{}{profile} var name string outfmt := []interface{}{name} output, err := QueryScan(db, q, inargs, outfmt) if err != nil { return results, err } for _, r := range output { results = append(results, r[0].(string)) } return results, nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/patches.go������������������������������������������������������������������������0000644�0610621�0607500�00000001136�13172163242�016624� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" "fmt" ) func Patches(db *sql.DB) ([]string, error) { inargs := []interface{}{} outfmt := []interface{}{""} query := fmt.Sprintf("SELECT name FROM patches") result, err := QueryScan(db, query, inargs, outfmt) if err != nil { return []string{}, err } response := []string{} for _, r := range result { response = append(response, r[0].(string)) } return response, nil } func PatchesMarkApplied(db *sql.DB, patch string) error { stmt := `INSERT INTO patches (name, applied_at) VALUES (?, strftime("%s"));` _, err := db.Exec(stmt, patch) return err } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/images.go�������������������������������������������������������������������������0000644�0610621�0607500�00000026627�13172163242�016456� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" "fmt" "time" _ "github.com/mattn/go-sqlite3" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/osarch" ) var ImageSourceProtocol = map[int]string{ 0: "lxd", 1: "direct", 2: "simplestreams", } func ImagesGet(db *sql.DB, public bool) ([]string, error) { q := "SELECT fingerprint FROM images" if public == true { q = "SELECT fingerprint FROM images WHERE public=1" } var fp string inargs := []interface{}{} outfmt := []interface{}{fp} dbResults, err := QueryScan(db, q, inargs, outfmt) if err != nil { return []string{}, err } results := []string{} for _, r := range dbResults { results = append(results, r[0].(string)) } return results, nil } func ImagesGetExpired(db *sql.DB, expiry int64) ([]string, error) { q := `SELECT fingerprint, last_use_date, upload_date FROM images WHERE cached=1` var fpStr string var useStr string var uploadStr string inargs := []interface{}{} outfmt := []interface{}{fpStr, useStr, uploadStr} dbResults, err := QueryScan(db, q, inargs, outfmt) if err != nil { return []string{}, err } results := []string{} for _, r := range dbResults { // Figure out the expiry timestamp := r[2] if r[1] != "" { timestamp = r[1] } var imageExpiry time.Time err = imageExpiry.UnmarshalText([]byte(timestamp.(string))) if err != nil { return []string{}, err } imageExpiry = imageExpiry.Add(time.Duration(expiry*24) * time.Hour) // Check if expired if imageExpiry.After(time.Now()) { continue } results = append(results, r[0].(string)) } return results, nil } func ImageSourceInsert(db *sql.DB, imageId int, server string, protocol string, certificate string, alias string) error { stmt := `INSERT INTO images_source (image_id, server, protocol, certificate, alias) values (?, ?, ?, ?, ?)` protocolInt := -1 for protoInt, protoString := range ImageSourceProtocol { if protoString == protocol { protocolInt = protoInt } } if protocolInt == -1 { return fmt.Errorf("Invalid protocol: %s", protocol) } _, err := Exec(db, stmt, imageId, server, protocolInt, certificate, alias) return err } func ImageSourceGet(db *sql.DB, imageId int) (int, api.ImageSource, error) { q := `SELECT id, server, protocol, certificate, alias FROM images_source WHERE image_id=?` id := 0 protocolInt := -1 result := api.ImageSource{} arg1 := []interface{}{imageId} arg2 := []interface{}{&id, &result.Server, &protocolInt, &result.Certificate, &result.Alias} err := dbQueryRowScan(db, q, arg1, arg2) if err != nil { if err == sql.ErrNoRows { return -1, api.ImageSource{}, NoSuchObjectError } return -1, api.ImageSource{}, err } protocol, found := ImageSourceProtocol[protocolInt] if !found { return -1, api.ImageSource{}, fmt.Errorf("Invalid protocol: %d", protocolInt) } result.Protocol = protocol return id, result, nil } // Whether an image with the given fingerprint exists. func ImageExists(db *sql.DB, fingerprint string) (bool, error) { var exists bool var err error query := "SELECT COUNT(*) > 0 FROM images WHERE fingerprint=?" inargs := []interface{}{fingerprint} outargs := []interface{}{&exists} err = dbQueryRowScan(db, query, inargs, outargs) return exists, err } // ImageGet gets an Image object from the database. // If strictMatching is false, The fingerprint argument will be queried with a LIKE query, means you can // pass a shortform and will get the full fingerprint. // There can never be more than one image with a given fingerprint, as it is // enforced by a UNIQUE constraint in the schema. func ImageGet(db *sql.DB, fingerprint string, public bool, strictMatching bool) (int, *api.Image, error) { var err error var create, expire, used, upload *time.Time // These hold the db-returned times // The object we'll actually return image := api.Image{} id := -1 arch := -1 // These two humongous things will be filled by the call to DbQueryRowScan outfmt := []interface{}{&id, &image.Fingerprint, &image.Filename, &image.Size, &image.Cached, &image.Public, &image.AutoUpdate, &arch, &create, &expire, &used, &upload} var inargs []interface{} query := ` SELECT id, fingerprint, filename, size, cached, public, auto_update, architecture, creation_date, expiry_date, last_use_date, upload_date FROM images` if strictMatching { inargs = []interface{}{fingerprint} query += " WHERE fingerprint = ?" } else { inargs = []interface{}{fingerprint + "%"} query += " WHERE fingerprint LIKE ?" } if public { query += " AND public=1" } err = dbQueryRowScan(db, query, inargs, outfmt) if err != nil { return -1, nil, err // Likely: there are no rows for this fingerprint } // Validate we only have a single match if !strictMatching { query = "SELECT COUNT(id) FROM images WHERE fingerprint LIKE ?" count := 0 outfmt := []interface{}{&count} err = dbQueryRowScan(db, query, inargs, outfmt) if err != nil { return -1, nil, err } if count > 1 { return -1, nil, fmt.Errorf("Partial fingerprint matches more than one image") } } // Some of the dates can be nil in the DB, let's process them. if create != nil { image.CreatedAt = *create } else { image.CreatedAt = time.Time{} } if expire != nil { image.ExpiresAt = *expire } else { image.ExpiresAt = time.Time{} } if used != nil { image.LastUsedAt = *used } else { image.LastUsedAt = time.Time{} } image.Architecture, _ = osarch.ArchitectureName(arch) // The upload date is enforced by NOT NULL in the schema, so it can never be nil. image.UploadedAt = *upload // Get the properties q := "SELECT key, value FROM images_properties where image_id=?" var key, value, name, desc string inargs = []interface{}{id} outfmt = []interface{}{key, value} results, err := QueryScan(db, q, inargs, outfmt) if err != nil { return -1, nil, err } properties := map[string]string{} for _, r := range results { key = r[0].(string) value = r[1].(string) properties[key] = value } image.Properties = properties // Get the aliases q = "SELECT name, description FROM images_aliases WHERE image_id=?" inargs = []interface{}{id} outfmt = []interface{}{name, desc} results, err = QueryScan(db, q, inargs, outfmt) if err != nil { return -1, nil, err } aliases := []api.ImageAlias{} for _, r := range results { name = r[0].(string) desc = r[1].(string) a := api.ImageAlias{Name: name, Description: desc} aliases = append(aliases, a) } image.Aliases = aliases _, source, err := ImageSourceGet(db, id) if err == nil { image.UpdateSource = &source } return id, &image, nil } func ImageDelete(db *sql.DB, id int) error { _, err := Exec(db, "DELETE FROM images WHERE id=?", id) if err != nil { return err } return nil } func ImageAliasGet(db *sql.DB, name string, isTrustedClient bool) (int, api.ImageAliasesEntry, error) { q := `SELECT images_aliases.id, images.fingerprint, images_aliases.description FROM images_aliases INNER JOIN images ON images_aliases.image_id=images.id WHERE images_aliases.name=?` if !isTrustedClient { q = q + ` AND images.public=1` } var fingerprint, description string id := -1 entry := api.ImageAliasesEntry{} arg1 := []interface{}{name} arg2 := []interface{}{&id, &fingerprint, &description} err := dbQueryRowScan(db, q, arg1, arg2) if err != nil { if err == sql.ErrNoRows { return -1, entry, NoSuchObjectError } return -1, entry, err } entry.Name = name entry.Target = fingerprint entry.Description = description return id, entry, nil } func ImageAliasRename(db *sql.DB, id int, name string) error { _, err := Exec(db, "UPDATE images_aliases SET name=? WHERE id=?", name, id) return err } func ImageAliasDelete(db *sql.DB, name string) error { _, err := Exec(db, "DELETE FROM images_aliases WHERE name=?", name) return err } func ImageAliasesMove(db *sql.DB, source int, destination int) error { _, err := Exec(db, "UPDATE images_aliases SET image_id=? WHERE image_id=?", destination, source) return err } // Insert an alias ento the database. func ImageAliasAdd(db *sql.DB, name string, imageID int, desc string) error { stmt := `INSERT INTO images_aliases (name, image_id, description) values (?, ?, ?)` _, err := Exec(db, stmt, name, imageID, desc) return err } func ImageAliasUpdate(db *sql.DB, id int, imageID int, desc string) error { stmt := `UPDATE images_aliases SET image_id=?, description=? WHERE id=?` _, err := Exec(db, stmt, imageID, desc, id) return err } func ImageLastAccessUpdate(db *sql.DB, fingerprint string, date time.Time) error { stmt := `UPDATE images SET last_use_date=? WHERE fingerprint=?` _, err := Exec(db, stmt, date, fingerprint) return err } func ImageLastAccessInit(db *sql.DB, fingerprint string) error { stmt := `UPDATE images SET cached=1, last_use_date=strftime("%s") WHERE fingerprint=?` _, err := Exec(db, stmt, fingerprint) return err } func ImageUpdate(db *sql.DB, id int, fname string, sz int64, public bool, autoUpdate bool, architecture string, createdAt time.Time, expiresAt time.Time, properties map[string]string) error { arch, err := osarch.ArchitectureId(architecture) if err != nil { arch = 0 } tx, err := Begin(db) if err != nil { return err } publicInt := 0 if public { publicInt = 1 } autoUpdateInt := 0 if autoUpdate { autoUpdateInt = 1 } stmt, err := tx.Prepare(`UPDATE images SET filename=?, size=?, public=?, auto_update=?, architecture=?, creation_date=?, expiry_date=? WHERE id=?`) if err != nil { tx.Rollback() return err } defer stmt.Close() _, err = stmt.Exec(fname, sz, publicInt, autoUpdateInt, arch, createdAt, expiresAt, id) if err != nil { tx.Rollback() return err } _, err = tx.Exec(`DELETE FROM images_properties WHERE image_id=?`, id) stmt, err = tx.Prepare(`INSERT INTO images_properties (image_id, type, key, value) VALUES (?, ?, ?, ?)`) if err != nil { tx.Rollback() return err } for key, value := range properties { _, err = stmt.Exec(id, 0, key, value) if err != nil { tx.Rollback() return err } } if err := TxCommit(tx); err != nil { return err } return nil } func ImageInsert(db *sql.DB, fp string, fname string, sz int64, public bool, autoUpdate bool, architecture string, createdAt time.Time, expiresAt time.Time, properties map[string]string) error { arch, err := osarch.ArchitectureId(architecture) if err != nil { arch = 0 } tx, err := Begin(db) if err != nil { return err } publicInt := 0 if public { publicInt = 1 } autoUpdateInt := 0 if autoUpdate { autoUpdateInt = 1 } stmt, err := tx.Prepare(`INSERT INTO images (fingerprint, filename, size, public, auto_update, architecture, creation_date, expiry_date, upload_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`) if err != nil { tx.Rollback() return err } defer stmt.Close() result, err := stmt.Exec(fp, fname, sz, publicInt, autoUpdateInt, arch, createdAt, expiresAt, time.Now().UTC()) if err != nil { tx.Rollback() return err } if len(properties) > 0 { id64, err := result.LastInsertId() if err != nil { tx.Rollback() return err } id := int(id64) pstmt, err := tx.Prepare(`INSERT INTO images_properties (image_id, type, key, value) VALUES (?, 0, ?, ?)`) if err != nil { tx.Rollback() return err } defer pstmt.Close() for k, v := range properties { // we can assume, that there is just one // value per key _, err = pstmt.Exec(id, k, v) if err != nil { tx.Rollback() return err } } } if err := TxCommit(tx); err != nil { return err } return nil } ���������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/devices.go������������������������������������������������������������������������0000644�0610621�0607500�00000006736�13172163242�016632� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" "github.com/lxc/lxd/lxd/types" ) func dbDeviceTypeToString(t int) (string, error) { switch t { case 0: return "none", nil case 1: return "nic", nil case 2: return "disk", nil case 3: return "unix-char", nil case 4: return "unix-block", nil default: return "", fmt.Errorf("Invalid device type %d", t) } } func dbDeviceTypeToInt(t string) (int, error) { switch t { case "none": return 0, nil case "nic": return 1, nil case "disk": return 2, nil case "unix-char": return 3, nil case "unix-block": return 4, nil default: return -1, fmt.Errorf("Invalid device type %s", t) } } func DevicesAdd(tx *sql.Tx, w string, cID int64, devices types.Devices) error { // Prepare the devices entry SQL str1 := fmt.Sprintf("INSERT INTO %ss_devices (%s_id, name, type) VALUES (?, ?, ?)", w, w) stmt1, err := tx.Prepare(str1) if err != nil { return err } defer stmt1.Close() // Prepare the devices config entry SQL str2 := fmt.Sprintf("INSERT INTO %ss_devices_config (%s_device_id, key, value) VALUES (?, ?, ?)", w, w) stmt2, err := tx.Prepare(str2) if err != nil { return err } defer stmt2.Close() // Insert all the devices for k, v := range devices { t, err := dbDeviceTypeToInt(v["type"]) if err != nil { return err } result, err := stmt1.Exec(cID, k, t) if err != nil { return err } id64, err := result.LastInsertId() if err != nil { return fmt.Errorf("Error inserting device %s into database", k) } id := int(id64) for ck, cv := range v { // The type is stored as int in the parent entry if ck == "type" { continue } _, err = stmt2.Exec(id, ck, cv) if err != nil { return err } } } return nil } func dbDeviceConfig(db *sql.DB, id int, isprofile bool) (types.Device, error) { var query string var key, value string newdev := types.Device{} // That's a map[string]string inargs := []interface{}{id} outfmt := []interface{}{key, value} if isprofile { query = `SELECT key, value FROM profiles_devices_config WHERE profile_device_id=?` } else { query = `SELECT key, value FROM containers_devices_config WHERE container_device_id=?` } results, err := QueryScan(db, query, inargs, outfmt) if err != nil { return newdev, err } for _, r := range results { key = r[0].(string) value = r[1].(string) newdev[key] = value } return newdev, nil } func Devices(db *sql.DB, qName string, isprofile bool) (types.Devices, error) { var q string if isprofile { q = `SELECT profiles_devices.id, profiles_devices.name, profiles_devices.type FROM profiles_devices JOIN profiles ON profiles_devices.profile_id = profiles.id WHERE profiles.name=?` } else { q = `SELECT containers_devices.id, containers_devices.name, containers_devices.type FROM containers_devices JOIN containers ON containers_devices.container_id = containers.id WHERE containers.name=?` } var id, dtype int var name, stype string inargs := []interface{}{qName} outfmt := []interface{}{id, name, dtype} results, err := QueryScan(db, q, inargs, outfmt) if err != nil { return nil, err } devices := types.Devices{} for _, r := range results { id = r[0].(int) name = r[1].(string) stype, err = dbDeviceTypeToString(r[2].(int)) if err != nil { return nil, err } newdev, err := dbDeviceConfig(db, id, isprofile) if err != nil { return nil, err } newdev["type"] = stype devices[name] = newdev } return devices, nil } ����������������������������������lxd-2.0.11/lxd/db/db_test.go������������������������������������������������������������������������0000644�0610621�0607500�00000034605�13172163242�016630� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" "fmt" "testing" "time" "github.com/stretchr/testify/suite" "github.com/lxc/lxd/lxd/db/query" "github.com/lxc/lxd/lxd/types" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/logging" ) const DB_FIXTURES string = ` INSERT INTO containers (name, architecture, type) VALUES ('thename', 1, 1); INSERT INTO profiles (name) VALUES ('theprofile'); INSERT INTO containers_profiles (container_id, profile_id) VALUES (1, 3); INSERT INTO containers_config (container_id, key, value) VALUES (1, 'thekey', 'thevalue'); INSERT INTO containers_devices (container_id, name, type) VALUES (1, 'somename', 1); INSERT INTO containers_devices_config (key, value, container_device_id) VALUES ('configkey', 'configvalue', 1); INSERT INTO images (fingerprint, filename, size, architecture, creation_date, expiry_date, upload_date) VALUES ('fingerprint', 'filename', 1024, 0, 1431547174, 1431547175, 1431547176); INSERT INTO images_aliases (name, image_id, description) VALUES ('somealias', 1, 'some description'); INSERT INTO images_properties (image_id, type, key, value) VALUES (1, 0, 'thekey', 'some value'); INSERT INTO profiles_config (profile_id, key, value) VALUES (3, 'thekey', 'thevalue'); INSERT INTO profiles_devices (profile_id, name, type) VALUES (3, 'devicename', 1); INSERT INTO profiles_devices_config (profile_device_id, key, value) VALUES (3, 'devicekey', 'devicevalue'); ` type dbTestSuite struct { suite.Suite db *sql.DB } func (s *dbTestSuite) SetupTest() { s.db = s.CreateTestDb() _, err := s.db.Exec(DB_FIXTURES) s.Nil(err) } func (s *dbTestSuite) TearDownTest() { s.db.Close() } // Initialize a test in-memory DB. func (s *dbTestSuite) CreateTestDb() *sql.DB { // Setup logging if main() hasn't been called/when testing if logger.Log == nil { var err error logger.Log, err = logging.GetLogger("", "", true, true, nil) s.Nil(err) } db, err := OpenDb(":memory:") s.Nil(err) s.Nil(CreateDb(db, []string{})) s.Nil(UpdatesApplyAll(db, false, nil)) return db } func TestDBTestSuite(t *testing.T) { suite.Run(t, new(dbTestSuite)) } func (s *dbTestSuite) Test_deleting_a_container_cascades_on_related_tables() { var err error var count int var statements string // Drop the container we just created. statements = `DELETE FROM containers WHERE name = 'thename';` _, err = s.db.Exec(statements) s.Nil(err, "Error deleting container!") // Make sure there are 0 container_profiles entries left. statements = `SELECT count(*) FROM containers_profiles;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting a container didn't delete the profile association!") // Make sure there are 0 containers_config entries left. statements = `SELECT count(*) FROM containers_config;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting a container didn't delete the associated container_config!") // Make sure there are 0 containers_devices entries left. statements = `SELECT count(*) FROM containers_devices;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting a container didn't delete the associated container_devices!") // Make sure there are 0 containers_devices_config entries left. statements = `SELECT count(*) FROM containers_devices_config;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting a container didn't delete the associated container_devices_config!") } func (s *dbTestSuite) Test_deleting_a_profile_cascades_on_related_tables() { var err error var count int var statements string // Drop the profile we just created. statements = `DELETE FROM profiles WHERE name = 'theprofile';` _, err = s.db.Exec(statements) s.Nil(err) // Make sure there are 0 container_profiles entries left. statements = `SELECT count(*) FROM containers_profiles WHERE profile_id = 3;` err = s.db.QueryRow(statements).Scan(&count) s.Equal(count, 0, "Deleting a profile didn't delete the container association!") // Make sure there are 0 profiles_devices entries left. statements = `SELECT count(*) FROM profiles_devices WHERE profile_id == 3;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting a profile didn't delete the related profiles_devices!") // Make sure there are 0 profiles_config entries left. statements = `SELECT count(*) FROM profiles_config WHERE profile_id == 3;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting a profile didn't delete the related profiles_config! There are %d left") // Make sure there are 0 profiles_devices_config entries left. statements = `SELECT count(*) FROM profiles_devices_config WHERE profile_device_id == 4;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting a profile didn't delete the related profiles_devices_config!") } func (s *dbTestSuite) Test_deleting_an_image_cascades_on_related_tables() { var err error var count int var statements string // Drop the image we just created. statements = `DELETE FROM images;` _, err = s.db.Exec(statements) s.Nil(err) // Make sure there are 0 images_aliases entries left. statements = `SELECT count(*) FROM images_aliases;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting an image didn't delete the image alias association!") // Make sure there are 0 images_properties entries left. statements = `SELECT count(*) FROM images_properties;` err = s.db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting an image didn't delete the related images_properties!") } func (s *dbTestSuite) Test_initializing_db_is_idempotent() { // This calls "CreateDb" once already. db := s.CreateTestDb() defer db.Close() // Let's call it a second time. s.Nil(CreateDb(db, []string{})) } func (s *dbTestSuite) Test_get_schema_returns_0_on_uninitialized_db() { var db *sql.DB var err error db, err = sql.Open("sqlite3", ":memory:") s.Nil(err) result := GetSchema(db) s.Equal(0, result, "getSchema should return 0 on uninitialized db!") } func (s *dbTestSuite) Test_running_UpdateFromV6_adds_on_delete_cascade() { // Upgrading the database schema with updateFromV6 adds ON DELETE CASCADE // to sqlite tables that require it, and conserve the data. var err error var count int db := s.CreateTestDb() defer db.Close() statements := ` CREATE TABLE IF NOT EXISTS containers ( id INTEGER primary key AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, architecture INTEGER NOT NULL, type INTEGER NOT NULL, power_state INTEGER NOT NULL DEFAULT 0, ephemeral INTEGER NOT NULL DEFAULT 0, UNIQUE (name) ); CREATE TABLE IF NOT EXISTS containers_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_id) REFERENCES containers (id), UNIQUE (container_id, key) ); INSERT INTO containers (name, architecture, type) VALUES ('thename', 1, 1); INSERT INTO containers_config (container_id, key, value) VALUES (1, 'thekey', 'thevalue');` _, err = db.Exec(statements) s.Nil(err) // Run the upgrade from V6 code err = query.Transaction(db, updateFromV6) s.Nil(err) // Make sure the inserted data is still there. statements = `SELECT count(*) FROM containers_config;` err = db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 1, "There should be exactly one entry in containers_config!") // Drop the container. statements = `DELETE FROM containers WHERE name = 'thename';` _, err = db.Exec(statements) s.Nil(err) // Make sure there are 0 container_profiles entries left. statements = `SELECT count(*) FROM containers_profiles;` err = db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "Deleting a container didn't delete the profile association!") } func (s *dbTestSuite) Test_run_database_upgrades_with_some_foreign_keys_inconsistencies() { var db *sql.DB var err error var count int var statements string db, err = sql.Open("sqlite3", ":memory:") defer db.Close() s.Nil(err) // This schema is a part of schema rev 1. statements = ` CREATE TABLE containers ( id INTEGER primary key AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, architecture INTEGER NOT NULL, type INTEGER NOT NULL, UNIQUE (name) ); CREATE TABLE containers_config ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, container_id INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (container_id) REFERENCES containers (id), UNIQUE (container_id, key) ); CREATE TABLE schema ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, version INTEGER NOT NULL, updated_at DATETIME NOT NULL, UNIQUE (version) ); CREATE TABLE images ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fingerprint VARCHAR(255) NOT NULL, filename VARCHAR(255) NOT NULL, size INTEGER NOT NULL, public INTEGER NOT NULL DEFAULT 0, architecture INTEGER NOT NULL, creation_date DATETIME, expiry_date DATETIME, upload_date DATETIME NOT NULL, UNIQUE (fingerprint) ); CREATE TABLE images_properties ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, image_id INTEGER NOT NULL, type INTEGER NOT NULL, key VARCHAR(255) NOT NULL, value TEXT, FOREIGN KEY (image_id) REFERENCES images (id) ); CREATE TABLE certificates ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fingerprint VARCHAR(255) NOT NULL, type INTEGER NOT NULL, name VARCHAR(255) NOT NULL, certificate TEXT NOT NULL, UNIQUE (fingerprint) ); INSERT INTO schema (version, updated_at) values (1, "now"); INSERT INTO containers (name, architecture, type) VALUES ('thename', 1, 1); INSERT INTO containers_config (container_id, key, value) VALUES (1, 'thekey', 'thevalue');` _, err = db.Exec(statements) s.Nil(err) // Now that we have a consistent schema, let's remove the container entry // *without* the ON DELETE CASCADE in place. statements = `DELETE FROM containers;` _, err = db.Exec(statements) s.Nil(err) // The "foreign key" on containers_config now points to nothing. // Let's run the schema upgrades. err = UpdatesApplyAll(db, false, nil) s.Nil(err) result := GetSchema(db) s.Equal(result, GetLatestSchema(), "The schema is not at the latest version after update!") // Make sure there are 0 containers_config entries left. statements = `SELECT count(*) FROM containers_config;` err = db.QueryRow(statements).Scan(&count) s.Nil(err) s.Equal(count, 0, "updateDb did not delete orphaned child entries after adding ON DELETE CASCADE!") } func (s *dbTestSuite) Test_ImageGet_finds_image_for_fingerprint() { var err error var result *api.Image _, result, err = ImageGet(s.db, "fingerprint", false, false) s.Nil(err) s.NotNil(result) s.Equal(result.Filename, "filename") s.Equal(result.CreatedAt.UTC(), time.Unix(1431547174, 0).UTC()) s.Equal(result.ExpiresAt.UTC(), time.Unix(1431547175, 0).UTC()) s.Equal(result.UploadedAt.UTC(), time.Unix(1431547176, 0).UTC()) } func (s *dbTestSuite) Test_ImageGet_for_missing_fingerprint() { var err error _, _, err = ImageGet(s.db, "unknown", false, false) s.Equal(err, sql.ErrNoRows) } func (s *dbTestSuite) Test_ImageExists_true() { var err error exists, err := ImageExists(s.db, "fingerprint") s.Nil(err) s.True(exists) } func (s *dbTestSuite) Test_ImageExists_false() { var err error exists, err := ImageExists(s.db, "foobar") s.Nil(err) s.False(exists) } func (s *dbTestSuite) Test_ImageAliasGet_alias_exists() { var err error _, alias, err := ImageAliasGet(s.db, "somealias", true) s.Nil(err) s.Equal(alias.Target, "fingerprint") } func (s *dbTestSuite) Test_ImageAliasGet_alias_does_not_exists() { var err error _, _, err = ImageAliasGet(s.db, "whatever", true) s.Equal(err, NoSuchObjectError) } func (s *dbTestSuite) Test_ImageAliasAdd() { var err error err = ImageAliasAdd(s.db, "Chaosphere", 1, "Someone will like the name") s.Nil(err) _, alias, err := ImageAliasGet(s.db, "Chaosphere", true) s.Nil(err) s.Equal(alias.Target, "fingerprint") } func (s *dbTestSuite) Test_dbContainerConfig() { var err error var result map[string]string var expected map[string]string _, err = s.db.Exec("INSERT INTO containers_config (container_id, key, value) VALUES (1, 'something', 'something else');") s.Nil(err) result, err = ContainerConfig(s.db, 1) s.Nil(err) expected = map[string]string{"thekey": "thevalue", "something": "something else"} for key, value := range expected { s.Equal(result[key], value, fmt.Sprintf("Mismatching value for key %s: %s != %s", key, result[key], value)) } } func (s *dbTestSuite) Test_dbProfileConfig() { var err error var result map[string]string var expected map[string]string _, err = s.db.Exec("INSERT INTO profiles_config (profile_id, key, value) VALUES (3, 'something', 'something else');") s.Nil(err) result, err = ProfileConfig(s.db, "theprofile") s.Nil(err) expected = map[string]string{"thekey": "thevalue", "something": "something else"} for key, value := range expected { s.Equal(result[key], value, fmt.Sprintf("Mismatching value for key %s: %s != %s", key, result[key], value)) } } func (s *dbTestSuite) Test_ContainerProfiles() { var err error var result []string var expected []string expected = []string{"theprofile"} result, err = ContainerProfiles(s.db, 1) s.Nil(err) for i := range expected { s.Equal(expected[i], result[i], fmt.Sprintf("Mismatching contents for profile list: %s != %s", result[i], expected[i])) } } func (s *dbTestSuite) Test_dbDevices_profiles() { var err error var result types.Devices var subresult types.Device var expected types.Device result, err = Devices(s.db, "theprofile", true) s.Nil(err) expected = types.Device{"type": "nic", "devicekey": "devicevalue"} subresult = result["devicename"] for key, value := range expected { s.Equal(subresult[key], value, fmt.Sprintf("Mismatching value for key %s: %v != %v", key, subresult[key], value)) } } func (s *dbTestSuite) Test_dbDevices_containers() { var err error var result types.Devices var subresult types.Device var expected types.Device result, err = Devices(s.db, "thename", false) s.Nil(err) expected = types.Device{"type": "nic", "configkey": "configvalue"} subresult = result["somename"] for key, value := range expected { s.Equal(subresult[key], value, fmt.Sprintf("Mismatching value for key %s: %s != %s", key, subresult[key], value)) } } ���������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/db.go�����������������������������������������������������������������������������0000644�0610621�0607500�00000016065�13172163242�015571� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" "fmt" "time" "github.com/mattn/go-sqlite3" "github.com/lxc/lxd/shared/logger" ) var ( // DbErrAlreadyDefined hapens when the given entry already exists, // for example a container. DbErrAlreadyDefined = fmt.Errorf("The container/snapshot already exists") /* NoSuchObjectError is in the case of joins (and probably other) queries, * we don't get back sql.ErrNoRows when no rows are returned, even though we do * on selects without joins. Instead, you can use this error to * propagate up and generate proper 404s to the client when something * isn't found so we don't abuse sql.ErrNoRows any more than we * already do. */ NoSuchObjectError = fmt.Errorf("No such object") ) func enableForeignKeys(conn *sqlite3.SQLiteConn) error { _, err := conn.Exec("PRAGMA foreign_keys=ON;", nil) return err } func init() { sql.Register("sqlite3_with_fk", &sqlite3.SQLiteDriver{ConnectHook: enableForeignKeys}) } // OpenDb opens the database with the correct parameters for LXD. func OpenDb(path string) (*sql.DB, error) { timeout := 5 // TODO - make this command-line configurable? // These are used to tune the transaction BEGIN behavior instead of using the // similar "locking_mode" pragma (locking for the whole database connection). openPath := fmt.Sprintf("%s?_busy_timeout=%d&_txlock=exclusive", path, timeout*1000) // Open the database. If the file doesn't exist it is created. return sql.Open("sqlite3_with_fk", openPath) } // Create the initial (current) schema for a given SQLite DB connection. func CreateDb(db *sql.DB, patchNames []string) (err error) { latestVersion := GetSchema(db) if latestVersion != 0 { return nil } _, err = db.Exec(CURRENT_SCHEMA) if err != nil { return err } // Mark all existing patches as applied for _, patchName := range patchNames { PatchesMarkApplied(db, patchName) } err = ProfileCreateDefault(db) if err != nil { return err } return dbProfileCreateDocker(db) } func GetSchema(db *sql.DB) (v int) { arg1 := []interface{}{} arg2 := []interface{}{&v} q := "SELECT max(version) FROM schema" err := dbQueryRowScan(db, q, arg1, arg2) if err != nil { return 0 } return v } func GetLatestSchema() int { return len(updates) } func IsDbLockedError(err error) bool { if err == nil { return false } if err == sqlite3.ErrLocked || err == sqlite3.ErrBusy { return true } if err.Error() == "database is locked" { return true } return false } func isNoMatchError(err error) bool { if err == nil { return false } if err.Error() == "sql: no rows in result set" { return true } return false } func Begin(db *sql.DB) (*sql.Tx, error) { for i := 0; i < 1000; i++ { tx, err := db.Begin() if err == nil { return tx, nil } if !IsDbLockedError(err) { logger.Debugf("DbBegin: error %q", err) return nil, err } time.Sleep(30 * time.Millisecond) } logger.Debugf("DbBegin: DB still locked") logger.Debugf(logger.GetStack()) return nil, fmt.Errorf("DB is locked") } func TxCommit(tx *sql.Tx) error { for i := 0; i < 1000; i++ { err := tx.Commit() if err == nil { return nil } if !IsDbLockedError(err) { logger.Debugf("Txcommit: error %q", err) return err } time.Sleep(30 * time.Millisecond) } logger.Debugf("Txcommit: db still locked") logger.Debugf(logger.GetStack()) return fmt.Errorf("DB is locked") } func dbQueryRowScan(db *sql.DB, q string, args []interface{}, outargs []interface{}) error { for i := 0; i < 1000; i++ { err := db.QueryRow(q, args...).Scan(outargs...) if err == nil { return nil } if isNoMatchError(err) { return err } if !IsDbLockedError(err) { return err } time.Sleep(30 * time.Millisecond) } logger.Debugf("DbQueryRowScan: query %q args %q, DB still locked", q, args) logger.Debugf(logger.GetStack()) return fmt.Errorf("DB is locked") } func dbQuery(db *sql.DB, q string, args ...interface{}) (*sql.Rows, error) { for i := 0; i < 1000; i++ { result, err := db.Query(q, args...) if err == nil { return result, nil } if !IsDbLockedError(err) { logger.Debugf("DbQuery: query %q error %q", q, err) return nil, err } time.Sleep(30 * time.Millisecond) } logger.Debugf("DbQuery: query %q args %q, DB still locked", q, args) logger.Debugf(logger.GetStack()) return nil, fmt.Errorf("DB is locked") } func doDbQueryScan(qi queryer, q string, args []interface{}, outargs []interface{}) ([][]interface{}, error) { rows, err := qi.Query(q, args...) if err != nil { return [][]interface{}{}, err } defer rows.Close() result := [][]interface{}{} for rows.Next() { ptrargs := make([]interface{}, len(outargs)) for i := range outargs { switch t := outargs[i].(type) { case string: str := "" ptrargs[i] = &str case int: integer := 0 ptrargs[i] = &integer case int64: integer := int64(0) ptrargs[i] = &integer default: return [][]interface{}{}, fmt.Errorf("Bad interface type: %s", t) } } err = rows.Scan(ptrargs...) if err != nil { return [][]interface{}{}, err } newargs := make([]interface{}, len(outargs)) for i := range ptrargs { switch t := outargs[i].(type) { case string: newargs[i] = *ptrargs[i].(*string) case int: newargs[i] = *ptrargs[i].(*int) case int64: newargs[i] = *ptrargs[i].(*int64) default: return [][]interface{}{}, fmt.Errorf("Bad interface type: %s", t) } } result = append(result, newargs) } err = rows.Err() if err != nil { return [][]interface{}{}, err } return result, nil } type queryer interface { Query(query string, args ...interface{}) (*sql.Rows, error) } /* * . qi anything implementing the querier interface (i.e. either sql.DB or sql.Tx) * . q is the database query * . inargs is an array of interfaces containing the query arguments * . outfmt is an array of interfaces containing the right types of output * arguments, i.e. * var arg1 string * var arg2 int * outfmt := {}interface{}{arg1, arg2} * * The result will be an array (one per output row) of arrays (one per output argument) * of interfaces, containing pointers to the actual output arguments. */ func QueryScan(qi queryer, q string, inargs []interface{}, outfmt []interface{}) ([][]interface{}, error) { for i := 0; i < 1000; i++ { result, err := doDbQueryScan(qi, q, inargs, outfmt) if err == nil { return result, nil } if !IsDbLockedError(err) { logger.Debugf("DbQuery: query %q error %q", q, err) return nil, err } time.Sleep(30 * time.Millisecond) } logger.Debugf("DbQueryscan: query %q inargs %q, DB still locked", q, inargs) logger.Debugf(logger.GetStack()) return nil, fmt.Errorf("DB is locked") } func Exec(db *sql.DB, q string, args ...interface{}) (sql.Result, error) { for i := 0; i < 1000; i++ { result, err := db.Exec(q, args...) if err == nil { return result, nil } if !IsDbLockedError(err) { logger.Debugf("DbExec: query %q error %q", q, err) return nil, err } time.Sleep(30 * time.Millisecond) } logger.Debugf("DbExec: query %q args %q, DB still locked", q, args) logger.Debugf(logger.GetStack()) return nil, fmt.Errorf("DB is locked") } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/containers.go���������������������������������������������������������������������0000644�0610621�0607500�00000024151�13172163242�017344� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" "fmt" "time" "github.com/lxc/lxd/lxd/types" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) // ContainerArgs is a value object holding all db-related details about a // container. type ContainerArgs struct { // Don't set manually Id int Architecture int BaseImage string Config map[string]string CreationDate time.Time Ctype ContainerType Devices types.Devices Ephemeral bool Name string Profiles []string Stateful bool } // ContainerType encodes the type of container (either regular or snapshot). type ContainerType int const ( CTypeRegular ContainerType = 0 CTypeSnapshot ContainerType = 1 ) func ContainerRemove(db *sql.DB, name string) error { id, err := ContainerId(db, name) if err != nil { return err } _, err = Exec(db, "DELETE FROM containers WHERE id=?", id) if err != nil { return err } return nil } func ContainerName(db *sql.DB, id int) (string, error) { q := "SELECT name FROM containers WHERE id=?" name := "" arg1 := []interface{}{id} arg2 := []interface{}{&name} err := dbQueryRowScan(db, q, arg1, arg2) return name, err } func ContainerId(db *sql.DB, name string) (int, error) { q := "SELECT id FROM containers WHERE name=?" id := -1 arg1 := []interface{}{name} arg2 := []interface{}{&id} err := dbQueryRowScan(db, q, arg1, arg2) return id, err } func ContainerGet(db *sql.DB, name string) (ContainerArgs, error) { args := ContainerArgs{} args.Name = name ephemInt := -1 statefulInt := -1 q := "SELECT id, architecture, type, ephemeral, stateful, creation_date FROM containers WHERE name=?" arg1 := []interface{}{name} arg2 := []interface{}{&args.Id, &args.Architecture, &args.Ctype, &ephemInt, &statefulInt, &args.CreationDate} err := dbQueryRowScan(db, q, arg1, arg2) if err != nil { return args, err } if args.Id == -1 { return args, fmt.Errorf("Unknown container") } if ephemInt == 1 { args.Ephemeral = true } if statefulInt == 1 { args.Stateful = true } config, err := ContainerConfig(db, args.Id) if err != nil { return args, err } args.Config = config profiles, err := ContainerProfiles(db, args.Id) if err != nil { return args, err } args.Profiles = profiles /* get container_devices */ args.Devices = types.Devices{} newdevs, err := Devices(db, name, false) if err != nil { return args, err } for k, v := range newdevs { args.Devices[k] = v } return args, nil } func ContainerCreate(db *sql.DB, args ContainerArgs) (int, error) { id, err := ContainerId(db, args.Name) if err == nil { return 0, DbErrAlreadyDefined } tx, err := Begin(db) if err != nil { return 0, err } ephemInt := 0 if args.Ephemeral == true { ephemInt = 1 } statefulInt := 0 if args.Stateful == true { statefulInt = 1 } args.CreationDate = time.Now().UTC() str := fmt.Sprintf("INSERT INTO containers (name, architecture, type, ephemeral, creation_date, stateful) VALUES (?, ?, ?, ?, ?, ?)") stmt, err := tx.Prepare(str) if err != nil { tx.Rollback() return 0, err } defer stmt.Close() result, err := stmt.Exec(args.Name, args.Architecture, args.Ctype, ephemInt, args.CreationDate.Unix(), statefulInt) if err != nil { tx.Rollback() return 0, err } id64, err := result.LastInsertId() if err != nil { tx.Rollback() return 0, fmt.Errorf("Error inserting %s into database", args.Name) } // TODO: is this really int64? we should fix it everywhere if so id = int(id64) if err := ContainerConfigInsert(tx, id, args.Config); err != nil { tx.Rollback() return 0, err } if err := ContainerProfilesInsert(tx, id, args.Profiles); err != nil { tx.Rollback() return 0, err } if err := DevicesAdd(tx, "container", int64(id), args.Devices); err != nil { tx.Rollback() return 0, err } return id, TxCommit(tx) } func ContainerConfigClear(tx *sql.Tx, id int) error { _, err := tx.Exec("DELETE FROM containers_config WHERE container_id=?", id) if err != nil { return err } _, err = tx.Exec("DELETE FROM containers_profiles WHERE container_id=?", id) if err != nil { return err } _, err = tx.Exec(`DELETE FROM containers_devices_config WHERE id IN (SELECT containers_devices_config.id FROM containers_devices_config JOIN containers_devices ON containers_devices_config.container_device_id=containers_devices.id WHERE containers_devices.container_id=?)`, id) if err != nil { return err } _, err = tx.Exec("DELETE FROM containers_devices WHERE container_id=?", id) return err } func ContainerConfigInsert(tx *sql.Tx, id int, config map[string]string) error { str := "INSERT INTO containers_config (container_id, key, value) values (?, ?, ?)" stmt, err := tx.Prepare(str) if err != nil { return err } defer stmt.Close() for k, v := range config { _, err := stmt.Exec(id, k, v) if err != nil { logger.Debugf("Error adding configuration item %s = %s to container %d", k, v, id) return err } } return nil } func ContainerConfigGet(db *sql.DB, id int, key string) (string, error) { q := "SELECT value FROM containers_config WHERE container_id=? AND key=?" value := "" arg1 := []interface{}{id, key} arg2 := []interface{}{&value} err := dbQueryRowScan(db, q, arg1, arg2) return value, err } func ContainerConfigRemove(db *sql.DB, id int, name string) error { _, err := Exec(db, "DELETE FROM containers_config WHERE key=? AND container_id=?", name, id) return err } func ContainerSetStateful(db *sql.DB, id int, stateful bool) error { statefulInt := 0 if stateful { statefulInt = 1 } _, err := Exec(db, "UPDATE containers SET stateful=? WHERE id=?", statefulInt, id) return err } func ContainerProfilesInsert(tx *sql.Tx, id int, profiles []string) error { applyOrder := 1 str := `INSERT INTO containers_profiles (container_id, profile_id, apply_order) VALUES (?, (SELECT id FROM profiles WHERE name=?), ?);` stmt, err := tx.Prepare(str) if err != nil { return err } defer stmt.Close() for _, p := range profiles { _, err = stmt.Exec(id, p, applyOrder) if err != nil { logger.Debugf("Error adding profile %s to container: %s", p, err) return err } applyOrder = applyOrder + 1 } return nil } // Get a list of profiles for a given container id. func ContainerProfiles(db *sql.DB, containerId int) ([]string, error) { var name string var profiles []string query := ` SELECT name FROM containers_profiles JOIN profiles ON containers_profiles.profile_id=profiles.id WHERE container_id=? ORDER BY containers_profiles.apply_order` inargs := []interface{}{containerId} outfmt := []interface{}{name} results, err := QueryScan(db, query, inargs, outfmt) if err != nil { return nil, err } for _, r := range results { name = r[0].(string) profiles = append(profiles, name) } return profiles, nil } // ContainerConfig gets the container configuration map from the DB func ContainerConfig(db *sql.DB, containerId int) (map[string]string, error) { var key, value string q := `SELECT key, value FROM containers_config WHERE container_id=?` inargs := []interface{}{containerId} outfmt := []interface{}{key, value} // Results is already a slice here, not db Rows anymore. results, err := QueryScan(db, q, inargs, outfmt) if err != nil { return nil, err //SmartError will wrap this and make "not found" errors pretty } config := map[string]string{} for _, r := range results { key = r[0].(string) value = r[1].(string) config[key] = value } return config, nil } func ContainersList(db *sql.DB, cType ContainerType) ([]string, error) { q := fmt.Sprintf("SELECT name FROM containers WHERE type=? ORDER BY name") inargs := []interface{}{cType} var container string outfmt := []interface{}{container} result, err := QueryScan(db, q, inargs, outfmt) if err != nil { return nil, err } var ret []string for _, container := range result { ret = append(ret, container[0].(string)) } return ret, nil } func ContainerSetState(db *sql.DB, id int, state string) error { tx, err := Begin(db) if err != nil { return err } // Clear any existing entry str := fmt.Sprintf("DELETE FROM containers_config WHERE container_id = ? AND key = 'volatile.last_state.power'") stmt, err := tx.Prepare(str) if err != nil { tx.Rollback() return err } defer stmt.Close() if _, err := stmt.Exec(id); err != nil { tx.Rollback() return err } // Insert the new one str = fmt.Sprintf("INSERT INTO containers_config (container_id, key, value) VALUES (?, 'volatile.last_state.power', ?)") stmt, err = tx.Prepare(str) if err != nil { tx.Rollback() return err } defer stmt.Close() if _, err = stmt.Exec(id, state); err != nil { tx.Rollback() return err } return TxCommit(tx) } func ContainerRename(db *sql.DB, oldName string, newName string) error { tx, err := Begin(db) if err != nil { return err } str := fmt.Sprintf("UPDATE containers SET name = ? WHERE name = ?") stmt, err := tx.Prepare(str) if err != nil { tx.Rollback() return err } defer stmt.Close() logger.Debug( "Calling SQL Query", log.Ctx{ "query": "UPDATE containers SET name = ? WHERE name = ?", "oldName": oldName, "newName": newName}) if _, err := stmt.Exec(newName, oldName); err != nil { tx.Rollback() return err } return TxCommit(tx) } func ContainerUpdate(tx *sql.Tx, id int, architecture int, ephemeral bool) error { str := fmt.Sprintf("UPDATE containers SET architecture=?, ephemeral=? WHERE id=?") stmt, err := tx.Prepare(str) if err != nil { return err } defer stmt.Close() ephemeralInt := 0 if ephemeral { ephemeralInt = 1 } if _, err := stmt.Exec(architecture, ephemeralInt, id); err != nil { return err } return nil } func ContainerGetSnapshots(db *sql.DB, name string) ([]string, error) { result := []string{} regexp := name + shared.SnapshotDelimiter length := len(regexp) q := "SELECT name FROM containers WHERE type=? AND SUBSTR(name,1,?)=?" inargs := []interface{}{CTypeSnapshot, length, regexp} outfmt := []interface{}{name} dbResults, err := QueryScan(db, q, inargs, outfmt) if err != nil { return result, err } for _, r := range dbResults { result = append(result, r[0].(string)) } return result, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/db/config.go�������������������������������������������������������������������������0000644�0610621�0607500�00000001747�13172163242�016452� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" _ "github.com/mattn/go-sqlite3" ) func ConfigValuesGet(db *sql.DB) (map[string]string, error) { q := "SELECT key, value FROM config" rows, err := dbQuery(db, q) if err != nil { return map[string]string{}, err } defer rows.Close() results := map[string]string{} for rows.Next() { var key, value string rows.Scan(&key, &value) results[key] = value } return results, nil } func ConfigValueSet(db *sql.DB, key string, value string) error { tx, err := Begin(db) if err != nil { return err } _, err = tx.Exec("DELETE FROM config WHERE key=?", key) if err != nil { tx.Rollback() return err } if value != "" { str := `INSERT INTO config (key, value) VALUES (?, ?);` stmt, err := tx.Prepare(str) if err != nil { tx.Rollback() return err } defer stmt.Close() _, err = stmt.Exec(key, value) if err != nil { tx.Rollback() return err } } err = TxCommit(tx) if err != nil { return err } return nil } �������������������������lxd-2.0.11/lxd/db/certificates.go�������������������������������������������������������������������0000644�0610621�0607500�00000004523�13172163242�017645� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package db import ( "database/sql" _ "github.com/mattn/go-sqlite3" ) // CertInfo is here to pass the certificates content // from the database around type CertInfo struct { ID int Fingerprint string Type int Name string Certificate string } // CertsGet returns all certificates from the DB as CertBaseInfo objects. func CertsGet(db *sql.DB) (certs []*CertInfo, err error) { rows, err := dbQuery( db, "SELECT id, fingerprint, type, name, certificate FROM certificates", ) if err != nil { return certs, err } defer rows.Close() for rows.Next() { cert := new(CertInfo) rows.Scan( &cert.ID, &cert.Fingerprint, &cert.Type, &cert.Name, &cert.Certificate, ) certs = append(certs, cert) } return certs, nil } // CertGet gets an CertBaseInfo object from the database. // The argument fingerprint will be queried with a LIKE query, means you can // pass a shortform and will get the full fingerprint. // There can never be more than one image with a given fingerprint, as it is // enforced by a UNIQUE constraint in the schema. func CertGet(db *sql.DB, fingerprint string) (cert *CertInfo, err error) { cert = new(CertInfo) inargs := []interface{}{fingerprint + "%"} outfmt := []interface{}{ &cert.ID, &cert.Fingerprint, &cert.Type, &cert.Name, &cert.Certificate, } query := ` SELECT id, fingerprint, type, name, certificate FROM certificates WHERE fingerprint LIKE ?` if err = dbQueryRowScan(db, query, inargs, outfmt); err != nil { return nil, err } return cert, err } // CertSave stores a CertBaseInfo object in the db, // it will ignore the ID field from the CertInfo. func CertSave(db *sql.DB, cert *CertInfo) error { tx, err := Begin(db) if err != nil { return err } stmt, err := tx.Prepare(` INSERT INTO certificates ( fingerprint, type, name, certificate ) VALUES (?, ?, ?, ?)`, ) if err != nil { tx.Rollback() return err } defer stmt.Close() _, err = stmt.Exec( cert.Fingerprint, cert.Type, cert.Name, cert.Certificate, ) if err != nil { tx.Rollback() return err } return TxCommit(tx) } // CertDelete deletes a certificate from the db. func CertDelete(db *sql.DB, fingerprint string) error { _, err := Exec(db, "DELETE FROM certificates WHERE fingerprint=?", fingerprint) if err != nil { return err } return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/daemon_test.go�����������������������������������������������������������������������0000644�0610621�0607500�00000001532�13172163242�017112� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "testing" "github.com/stretchr/testify/suite" ) type daemonTestSuite struct { lxdTestSuite } func (suite *daemonTestSuite) Test_config_value_set_empty_removes_val() { var err error d := suite.d err = daemonConfig["core.trust_password"].Set(d, "foo") suite.Req.Nil(err) val := daemonConfig["core.trust_password"].Get() suite.Req.Equal(len(val), 192) valMap := daemonConfigRender() value, present := valMap["core.trust_password"] suite.Req.True(present) suite.Req.Equal(value, true) err = daemonConfig["core.trust_password"].Set(d, "") suite.Req.Nil(err) val = daemonConfig["core.trust_password"].Get() suite.Req.Equal(val, "") valMap = daemonConfigRender() _, present = valMap["core.trust_password"] suite.Req.False(present) } func TestDaemonTestSuite(t *testing.T) { suite.Run(t, new(daemonTestSuite)) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/daemon_images.go���������������������������������������������������������������������0000644�0610621�0607500�00000030505�13172163242�017402� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "crypto/sha256" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "strings" "sync" "time" "gopkg.in/yaml.v2" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/cancel" "github.com/lxc/lxd/shared/ioprogress" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/version" log "gopkg.in/inconshreveable/log15.v2" ) // Simplestream cache type imageStreamCacheEntry struct { Aliases []api.ImageAliasesEntry `yaml:"aliases"` Certificate string `yaml:"certificate"` Fingerprints []string `yaml:"fingerprints"` expiry time.Time remote lxd.ImageServer } var imageStreamCache = map[string]*imageStreamCacheEntry{} var imageStreamCacheLock sync.Mutex var imagesDownloading = map[string]chan bool{} var imagesDownloadingLock sync.Mutex func imageSaveStreamCache() error { data, err := yaml.Marshal(&imageStreamCache) if err != nil { return err } err = ioutil.WriteFile(shared.CachePath("simplestreams.yaml"), data, 0600) if err != nil { return err } return nil } func imageLoadStreamCache(d *Daemon) error { imageStreamCacheLock.Lock() defer imageStreamCacheLock.Unlock() if !shared.PathExists(shared.CachePath("simplestreams.yaml")) { return nil } content, err := ioutil.ReadFile(shared.CachePath("simplestreams.yaml")) if err != nil { return err } err = yaml.Unmarshal(content, imageStreamCache) if err != nil { return err } for url, entry := range imageStreamCache { if entry.remote == nil { remote, err := lxd.ConnectSimpleStreams(url, &lxd.ConnectionArgs{ TLSServerCert: entry.Certificate, UserAgent: version.UserAgent, Proxy: d.proxy, }) if err != nil { continue } entry.remote = remote } } return nil } // ImageDownload resolves the image fingerprint and if not in the database, downloads it func (d *Daemon) ImageDownload(op *operation, server string, protocol string, certificate string, secret string, alias string, forContainer bool, autoUpdate bool) (*api.Image, error) { var err error var ctxMap log.Ctx var remote lxd.ImageServer var info *api.Image // Default protocol is LXD if protocol == "" { protocol = "lxd" } // Default the fingerprint to the alias string we received fp := alias // Attempt to resolve the alias if protocol == "simplestreams" { imageStreamCacheLock.Lock() entry, _ := imageStreamCache[server] if entry == nil || entry.expiry.Before(time.Now()) { // Add a new entry to the cache refresh := func() (*imageStreamCacheEntry, error) { // Setup simplestreams client remote, err = lxd.ConnectSimpleStreams(server, &lxd.ConnectionArgs{ TLSServerCert: certificate, UserAgent: version.UserAgent, Proxy: d.proxy, }) if err != nil { return nil, err } // Get all aliases aliases, err := remote.GetImageAliases() if err != nil { return nil, err } // Get all fingerprints images, err := remote.GetImages() if err != nil { return nil, err } fingerprints := []string{} for _, image := range images { fingerprints = append(fingerprints, image.Fingerprint) } // Generate cache entry entry = &imageStreamCacheEntry{remote: remote, Aliases: aliases, Certificate: certificate, Fingerprints: fingerprints, expiry: time.Now().Add(time.Hour)} imageStreamCache[server] = entry imageSaveStreamCache() return entry, nil } newEntry, err := refresh() if err == nil { // Cache refreshed entry = newEntry } else if entry != nil { // Failed to fetch entry but existing cache logger.Warn("Unable to refresh cache, using stale entry", log.Ctx{"server": server}) entry.expiry = time.Now().Add(time.Hour) } else { // Failed to fetch entry and nothing in cache imageStreamCacheLock.Unlock() return nil, err } } else { // use the existing entry logger.Debug("Using SimpleStreams cache entry", log.Ctx{"server": server, "expiry": entry.expiry}) remote = entry.remote } imageStreamCacheLock.Unlock() // Look for a matching alias for _, entry := range entry.Aliases { if entry.Name != fp { continue } fp = entry.Target break } // Expand partial fingerprints matches := []string{} for _, entry := range entry.Fingerprints { if strings.HasPrefix(entry, fp) { matches = append(matches, entry) } } if len(matches) == 1 { fp = matches[0] } else if len(matches) > 1 { return nil, fmt.Errorf("Provided partial image fingerprint matches more than one image") } else { return nil, fmt.Errorf("The requested image couldn't be found.") } } else if protocol == "lxd" { // Setup LXD client remote, err = lxd.ConnectPublicLXD(server, &lxd.ConnectionArgs{ TLSServerCert: certificate, UserAgent: version.UserAgent, Proxy: d.proxy, }) if err != nil { return nil, err } // For public images, handle aliases and initial metadata if secret == "" { // Look for a matching alias entry, _, err := remote.GetImageAlias(fp) if err == nil { fp = entry.Target } // Expand partial fingerprints info, _, err = remote.GetImage(fp) if err != nil { return nil, err } fp = info.Fingerprint } } // Check if the image already exists (partial hash match) _, imgInfo, err := db.ImageGet(d.db, fp, false, true) if err == nil { logger.Debug("Image already exists in the db", log.Ctx{"image": fp}) info = imgInfo return info, nil } // Deal with parallel downloads imagesDownloadingLock.Lock() if waitChannel, ok := imagesDownloading[fp]; ok { // We are already downloading the image imagesDownloadingLock.Unlock() logger.Debug( "Already downloading the image, waiting for it to succeed", log.Ctx{"image": fp}) // Wait until the download finishes (channel closes) <-waitChannel // Grab the database entry _, imgInfo, err := db.ImageGet(d.db, fp, false, true) if err != nil { // Other download failed, lets try again logger.Error("Other image download didn't succeed", log.Ctx{"image": fp}) } else { // Other download succeeded, we're done return imgInfo, nil } } else { imagesDownloadingLock.Unlock() } // Add the download to the queue imagesDownloadingLock.Lock() imagesDownloading[fp] = make(chan bool) imagesDownloadingLock.Unlock() // Unlock once this func ends. defer func() { imagesDownloadingLock.Lock() if waitChannel, ok := imagesDownloading[fp]; ok { close(waitChannel) delete(imagesDownloading, fp) } imagesDownloadingLock.Unlock() }() // Begin downloading if op == nil { ctxMap = log.Ctx{"alias": alias, "server": server} } else { ctxMap = log.Ctx{"trigger": op.url, "image": fp, "operation": op.id, "alias": alias, "server": server} } logger.Info("Downloading image", ctxMap) // Cleanup any leftover from a past attempt destDir := shared.VarPath("images") destName := filepath.Join(destDir, fp) if shared.PathExists(destName) { d.Storage.ImageDelete(fp) } failure := true cleanup := func() { if failure { os.Remove(destName) os.Remove(destName + ".rootfs") d.Storage.ImageDelete(fp) } } defer cleanup() // Setup a progress handler progress := func(progress lxd.ProgressData) { if op == nil { return } meta := op.metadata if meta == nil { meta = make(map[string]interface{}) } if meta["download_progress"] != progress.Text { meta["download_progress"] = progress.Text op.UpdateMetadata(meta) } } var canceler *cancel.Canceler if op != nil { canceler = cancel.NewCanceler() op.canceler = canceler } if protocol == "lxd" || protocol == "simplestreams" { // Create the target files dest, err := os.Create(destName) if err != nil { return nil, err } defer dest.Close() destRootfs, err := os.Create(destName + ".rootfs") if err != nil { return nil, err } defer destRootfs.Close() // Get the image information if info == nil { if secret != "" { info, _, err = remote.GetPrivateImage(fp, secret) if err != nil { return nil, err } // Expand the fingerprint now and mark alias string to match fp = info.Fingerprint alias = info.Fingerprint } else { info, _, err = remote.GetImage(fp) if err != nil { return nil, err } } } // Download the image var resp *lxd.ImageFileResponse request := lxd.ImageFileRequest{ MetaFile: io.WriteSeeker(dest), RootfsFile: io.WriteSeeker(destRootfs), ProgressHandler: progress, Canceler: canceler, DeltaSourceRetriever: func(fingerprint string, file string) string { path := shared.VarPath("images", fmt.Sprintf("%s.%s", fingerprint, file)) if shared.PathExists(path) { return path } return "" }, } if secret != "" { resp, err = remote.GetPrivateImageFile(fp, secret, request) } else { resp, err = remote.GetImageFile(fp, request) } if err != nil { return nil, err } // Deal with unified images if resp.RootfsSize == 0 { err := os.Remove(destName + ".rootfs") if err != nil { return nil, err } } } else if protocol == "direct" { // Setup HTTP client httpClient, err := util.HTTPClient(certificate, d.proxy) if err != nil { return nil, err } req, err := http.NewRequest("GET", server, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", version.UserAgent) // Make the request raw, doneCh, err := cancel.CancelableDownload(canceler, httpClient, req) defer close(doneCh) if err != nil { return nil, err } if raw.StatusCode != http.StatusOK { return nil, fmt.Errorf("Unable to fetch %s: %s", server, raw.Status) } // Progress handler body := &ioprogress.ProgressReader{ ReadCloser: raw.Body, Tracker: &ioprogress.ProgressTracker{ Length: raw.ContentLength, Handler: func(percent int64, speed int64) { progress(lxd.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))}) }, }, } // Create the target files f, err := os.Create(destName) if err != nil { return nil, err } defer f.Close() // Hashing sha256 := sha256.New() // Download the image size, err := io.Copy(io.MultiWriter(f, sha256), body) if err != nil { return nil, err } // Validate hash result := fmt.Sprintf("%x", sha256.Sum(nil)) if result != fp { return nil, fmt.Errorf("Hash mismatch for %s: %s != %s", server, result, fp) } // Parse the image imageMeta, err := getImageMetadata(destName) if err != nil { return nil, err } info = &api.Image{} info.Fingerprint = fp info.Size = size info.Architecture = imageMeta.Architecture info.CreatedAt = time.Unix(imageMeta.CreationDate, 0) info.ExpiresAt = time.Unix(imageMeta.ExpiryDate, 0) info.Properties = imageMeta.Properties } // Override visiblity info.Public = false // Create storage entry err = d.Storage.ImageCreate(info.Fingerprint) if err != nil { return nil, err } // We want to enable auto-update only if we were passed an // alias name, so we can figure when the associated // fingerprint changes in the remote. if alias != fp { info.AutoUpdate = autoUpdate } // Create the database entry err = db.ImageInsert(d.db, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties) if err != nil { return nil, err } // Image is in the DB now, don't wipe on-disk files on failure failure = false // Check if the image path changed (private images) newDestName := filepath.Join(destDir, fp) if newDestName != destName { err = shared.FileMove(destName, newDestName) if err != nil { return nil, err } if shared.PathExists(destName + ".rootfs") { err = shared.FileMove(destName+".rootfs", newDestName+".rootfs") if err != nil { return nil, err } } } // Record the image source if alias != fp { id, _, err := db.ImageGet(d.db, fp, false, true) if err != nil { return nil, err } err = db.ImageSourceInsert(d.db, id, server, protocol, certificate, alias) if err != nil { return nil, err } } // Mark the image as "cached" if downloading for a container if forContainer { err := db.ImageLastAccessInit(d.db, fp) if err != nil { return nil, err } } logger.Info("Image downloaded", ctxMap) return info, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/daemon_config.go���������������������������������������������������������������������0000644�0610621�0607500�00000020175�13172163242�017404� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "crypto/rand" "database/sql" "encoding/hex" "fmt" "io" "os/exec" "strconv" "strings" "sync" "golang.org/x/crypto/scrypt" log "gopkg.in/inconshreveable/log15.v2" dbapi "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" ) var daemonConfigLock sync.Mutex var daemonConfig map[string]*daemonConfigKey type daemonConfigKey struct { valueType string defaultValue string validValues []string currentValue string hiddenValue bool validator func(d *Daemon, key string, value string) error setter func(d *Daemon, key string, value string) (string, error) trigger func(d *Daemon, key string, value string) } func (k *daemonConfigKey) name() string { name := "" // Look for a matching entry in daemonConfig daemonConfigLock.Lock() for key, value := range daemonConfig { if value == k { name = key break } } daemonConfigLock.Unlock() return name } func (k *daemonConfigKey) Validate(d *Daemon, value string) error { // Handle unsetting if value == "" { value = k.defaultValue if k.validator != nil { err := k.validator(d, k.name(), value) if err != nil { return err } } return nil } // Validate booleans if k.valueType == "bool" && !shared.StringInSlice(strings.ToLower(value), []string{"true", "false", "1", "0", "yes", "no", "on", "off"}) { return fmt.Errorf("Invalid value for a boolean: %s", value) } // Validate integers if k.valueType == "int" { _, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } } // Check against valid values if k.validValues != nil && !shared.StringInSlice(value, k.validValues) { return fmt.Errorf("Invalid value, only the following values are allowed: %s", k.validValues) } // Run external validation function if k.validator != nil { err := k.validator(d, k.name(), value) if err != nil { return err } } return nil } func (k *daemonConfigKey) Set(d *Daemon, value string) error { var name string // Check if we are actually changing things oldValue := k.currentValue if oldValue == value { return nil } // Validate the new value err := k.Validate(d, value) if err != nil { return err } // Run external setting function if k.setter != nil { value, err = k.setter(d, k.name(), value) if err != nil { return err } } // Get the configuration key and make sure daemonConfig is sane name = k.name() if name == "" { return fmt.Errorf("Corrupted configuration cache") } // Actually apply the change daemonConfigLock.Lock() k.currentValue = value daemonConfigLock.Unlock() err = dbapi.ConfigValueSet(d.db, name, value) if err != nil { return err } // Run the trigger (if any) if k.trigger != nil { k.trigger(d, k.name(), value) } return nil } func (k *daemonConfigKey) Get() string { value := k.currentValue // Get the default value if not set if value == "" { value = k.defaultValue } return value } func (k *daemonConfigKey) GetBool() bool { value := k.currentValue // Get the default value if not set if value == "" { value = k.defaultValue } // Convert to boolean return shared.IsTrue(value) } func (k *daemonConfigKey) GetInt64() int64 { value := k.currentValue // Get the default value if not set if value == "" { value = k.defaultValue } // Convert to int64 ret, _ := strconv.ParseInt(value, 10, 64) return ret } func daemonConfigInit(db *sql.DB) error { // Set all the keys daemonConfig = map[string]*daemonConfigKey{ "core.https_address": {valueType: "string", setter: daemonConfigSetAddress}, "core.https_allowed_headers": {valueType: "string"}, "core.https_allowed_methods": {valueType: "string"}, "core.https_allowed_origin": {valueType: "string"}, "core.proxy_http": {valueType: "string", setter: daemonConfigSetProxy}, "core.proxy_https": {valueType: "string", setter: daemonConfigSetProxy}, "core.proxy_ignore_hosts": {valueType: "string", setter: daemonConfigSetProxy}, "core.trust_password": {valueType: "string", hiddenValue: true, setter: daemonConfigSetPassword}, "images.auto_update_cached": {valueType: "bool", defaultValue: "true"}, "images.auto_update_interval": {valueType: "int", defaultValue: "6", trigger: daemonConfigTriggerAutoUpdateInterval}, "images.compression_algorithm": {valueType: "string", validator: daemonConfigValidateCompression, defaultValue: "gzip"}, "images.remote_cache_expiry": {valueType: "int", defaultValue: "10", trigger: daemonConfigTriggerExpiry}, "storage.lvm_fstype": {valueType: "string", defaultValue: "ext4", validValues: []string{"ext4", "xfs"}}, "storage.lvm_thinpool_name": {valueType: "string", defaultValue: "LXDPool", validator: storageLVMValidateThinPoolName}, "storage.lvm_vg_name": {valueType: "string", validator: storageLVMValidateVolumeGroupName, setter: daemonConfigSetStorage}, "storage.lvm_volume_size": {valueType: "string", defaultValue: "10GiB"}, "storage.zfs_pool_name": {valueType: "string", validator: storageZFSValidatePoolName, setter: daemonConfigSetStorage}, } // Load the values from the DB dbValues, err := dbapi.ConfigValuesGet(db) if err != nil { return err } daemonConfigLock.Lock() for k, v := range dbValues { _, ok := daemonConfig[k] if !ok { logger.Error("Found unknown configuration key in database", log.Ctx{"key": k}) continue } daemonConfig[k].currentValue = v } daemonConfigLock.Unlock() return nil } func daemonConfigRender() map[string]interface{} { config := map[string]interface{}{} // Turn the config into a JSON-compatible map for k, v := range daemonConfig { value := v.Get() if value != v.defaultValue { if v.hiddenValue { config[k] = true } else { config[k] = value } } } return config } func daemonConfigSetPassword(d *Daemon, key string, value string) (string, error) { // Nothing to do on unset if value == "" { return value, nil } // Hash the password buf := make([]byte, 32) _, err := io.ReadFull(rand.Reader, buf) if err != nil { return "", err } hash, err := scrypt.Key([]byte(value), buf, 1<<14, 8, 1, 64) if err != nil { return "", err } buf = append(buf, hash...) value = hex.EncodeToString(buf) return value, nil } func daemonConfigSetStorage(d *Daemon, key string, value string) (string, error) { // The storage driver looks at daemonConfig so just set it temporarily daemonConfigLock.Lock() oldValue := daemonConfig[key].Get() daemonConfig[key].currentValue = value daemonConfigLock.Unlock() defer func() { daemonConfigLock.Lock() daemonConfig[key].currentValue = oldValue daemonConfigLock.Unlock() }() // Update the current storage driver err := SetupStorageDriver(d) if err != nil { return "", err } return value, nil } func daemonConfigSetAddress(d *Daemon, key string, value string) (string, error) { // Update the current https address err := d.UpdateHTTPsPort(value) if err != nil { return "", err } return value, nil } func daemonConfigSetProxy(d *Daemon, key string, value string) (string, error) { // Get the current config config := map[string]string{} config["core.proxy_https"] = daemonConfig["core.proxy_https"].Get() config["core.proxy_http"] = daemonConfig["core.proxy_http"].Get() config["core.proxy_ignore_hosts"] = daemonConfig["core.proxy_ignore_hosts"].Get() // Apply the change config[key] = value // Update the cached proxy function d.proxy = shared.ProxyFromConfig( config["core.proxy_https"], config["core.proxy_http"], config["core.proxy_ignore_hosts"], ) // Clear the simplestreams cache as it's tied to the old proxy config imageStreamCacheLock.Lock() for k := range imageStreamCache { delete(imageStreamCache, k) } imageStreamCacheLock.Unlock() return value, nil } func daemonConfigTriggerExpiry(d *Daemon, key string, value string) { // Trigger an image pruning run d.pruneChan <- true } func daemonConfigTriggerAutoUpdateInterval(d *Daemon, key string, value string) { // Reset the auto-update interval loop d.resetAutoUpdateChan <- true } func daemonConfigValidateCompression(d *Daemon, key string, value string) error { if value == "none" { return nil } _, err := exec.LookPath(value) return err } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/daemon.go����������������������������������������������������������������������������0000644�0610621�0607500�00000060012�13172163242�016051� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "bytes" "crypto/tls" "crypto/x509" "database/sql" "fmt" "io" "io/ioutil" "net" "net/http" "net/url" "os" "os/exec" "runtime" "strconv" "strings" "sync" "syscall" "time" "github.com/gorilla/mux" _ "github.com/mattn/go-sqlite3" "github.com/syndtr/gocapability/capability" "gopkg.in/tomb.v2" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/lxd/sys" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/logging" "github.com/lxc/lxd/shared/version" log "gopkg.in/inconshreveable/log15.v2" ) // AppArmor var aaAvailable = false var aaAdmin = false var aaConfined = false var aaStacking = false var aaStacked = false // CGroup var cgBlkioController = false var cgCpuController = false var cgCpusetController = false var cgDevicesController = false var cgMemoryController = false var cgNetPrioController = false var cgPidsController = false var cgSwapAccounting = false // UserNS var runningInUserns = false type Socket struct { Socket net.Listener CloseOnExit bool } // A Daemon can respond to requests from a shared client. type Daemon struct { clientCerts []x509.Certificate os *sys.OS db *sql.DB group string mux *mux.Router tomb tomb.Tomb readyChan chan bool pruneChan chan bool shutdownChan chan bool resetAutoUpdateChan chan bool Storage storage TCPSocket *Socket UnixSocket *Socket devlxd *net.UnixListener SetupMode bool tlsConfig *tls.Config proxy func(req *http.Request) (*url.URL, error) } // NewDaemon returns a new, un-initialized Daemon object. func NewDaemon() *Daemon { return &Daemon{ os: sys.NewOS(), } } // Command is the basic structure for every API call. type Command struct { name string untrustedGet bool untrustedPost bool get func(d *Daemon, r *http.Request) Response put func(d *Daemon, r *http.Request) Response post func(d *Daemon, r *http.Request) Response delete func(d *Daemon, r *http.Request) Response } func readMyCert() (string, string, error) { certf := shared.VarPath("server.crt") keyf := shared.VarPath("server.key") logger.Debug("Looking for existing certificates", log.Ctx{"cert": certf, "key": keyf}) err := shared.FindOrGenCert(certf, keyf, false) return certf, keyf, err } func isJSONRequest(r *http.Request) bool { for k, vs := range r.Header { if strings.ToLower(k) == "content-type" && len(vs) == 1 && strings.ToLower(vs[0]) == "application/json" { return true } } return false } // State creates a new State instance liked to our internal db and os. func (d *Daemon) State() *state.State { return state.NewState(d.db, d.os) } func (d *Daemon) createCmd(version string, c Command) { var uri string if c.name == "" { uri = fmt.Sprintf("/%s", version) } else { uri = fmt.Sprintf("/%s/%s", version, c.name) } d.mux.HandleFunc(uri, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if util.IsTrustedClient(r, d.clientCerts) { logger.Debug( "handling", log.Ctx{"method": r.Method, "url": r.URL.RequestURI(), "ip": r.RemoteAddr}) } else if r.Method == "GET" && c.untrustedGet { logger.Debug( "allowing untrusted GET", log.Ctx{"url": r.URL.RequestURI(), "ip": r.RemoteAddr}) } else if r.Method == "POST" && c.untrustedPost { logger.Debug( "allowing untrusted POST", log.Ctx{"url": r.URL.RequestURI(), "ip": r.RemoteAddr}) } else { logger.Warn( "rejecting request from untrusted client", log.Ctx{"ip": r.RemoteAddr}) Forbidden.Render(w) return } if debug && r.Method != "GET" && isJSONRequest(r) { newBody := &bytes.Buffer{} captured := &bytes.Buffer{} multiW := io.MultiWriter(newBody, captured) if _, err := io.Copy(multiW, r.Body); err != nil { InternalError(err).Render(w) return } r.Body = shared.BytesReadCloser{Buf: newBody} shared.DebugJson(captured) } var resp Response resp = NotImplemented switch r.Method { case "GET": if c.get != nil { resp = c.get(d, r) } case "PUT": if c.put != nil { resp = c.put(d, r) } case "POST": if c.post != nil { resp = c.post(d, r) } case "DELETE": if c.delete != nil { resp = c.delete(d, r) } default: resp = NotFound } if err := resp.Render(w); err != nil { err := InternalError(err).Render(w) if err != nil { logger.Errorf("Failed writing error for error, giving up") } } /* * When we create a new lxc.Container, it adds a finalizer (via * SetFinalizer) that frees the struct. However, it sometimes * takes the go GC a while to actually free the struct, * presumably since it is a small amount of memory. * Unfortunately, the struct also keeps the log fd open, so if * we leave too many of these around, we end up running out of * fds. So, let's explicitly do a GC to collect these at the * end of each request. */ runtime.GC() }) } // have we setup shared mounts? var sharedMounted bool var sharedMountsLock sync.Mutex func setupSharedMounts() error { // Check if we already went through this if sharedMounted { return nil } // Get a lock to prevent races sharedMountsLock.Lock() defer sharedMountsLock.Unlock() // Check if already setup path := shared.VarPath("shmounts") if shared.IsMountPoint(path) { sharedMounted = true return nil } // Mount a new tmpfs if err := syscall.Mount("tmpfs", path, "tmpfs", 0, "size=100k,mode=0711"); err != nil { return err } // Mark as MS_SHARED and MS_REC var flags uintptr = syscall.MS_SHARED | syscall.MS_REC if err := syscall.Mount(path, path, "none", flags, ""); err != nil { return err } sharedMounted = true return nil } func (d *Daemon) UpdateHTTPsPort(newAddress string) error { oldAddress := daemonConfig["core.https_address"].Get() if oldAddress == newAddress { return nil } if d.TCPSocket != nil { d.TCPSocket.Socket.Close() } if newAddress != "" { _, _, err := net.SplitHostPort(newAddress) if err != nil { ip := net.ParseIP(newAddress) if ip != nil && ip.To4() == nil { newAddress = fmt.Sprintf("[%s]:%s", newAddress, shared.DefaultPort) } else { newAddress = fmt.Sprintf("%s:%s", newAddress, shared.DefaultPort) } } var tcpl net.Listener for i := 0; i < 10; i++ { tcpl, err = tls.Listen("tcp", newAddress, d.tlsConfig) if err == nil { break } time.Sleep(100 * time.Millisecond) } if err != nil { return fmt.Errorf("cannot listen on https socket: %v", err) } d.tomb.Go(func() error { return http.Serve(tcpl, &lxdHttpServer{d.mux, d}) }) d.TCPSocket = &Socket{Socket: tcpl, CloseOnExit: true} } return nil } func haveMacAdmin() bool { c, err := capability.NewPid(0) if err != nil { return false } if c.Get(capability.EFFECTIVE, capability.CAP_MAC_ADMIN) { return true } return false } func (d *Daemon) Init() error { /* Initialize some variables */ d.readyChan = make(chan bool) d.shutdownChan = make(chan bool) /* Set the executable path */ /* Set the LVM environment */ err := os.Setenv("LVM_SUPPRESS_FD_WARNINGS", "1") if err != nil { return err } /* Setup logging if that wasn't done before */ if logger.Log == nil { logger.Log, err = logging.GetLogger("", "", true, true, nil) if err != nil { return err } } /* Print welcome message */ if d.os.MockMode { logger.Info(fmt.Sprintf("LXD %s is starting in mock mode", version.Version), log.Ctx{"path": shared.VarPath("")}) } else if d.SetupMode { logger.Info(fmt.Sprintf("LXD %s is starting in setup mode", version.Version), log.Ctx{"path": shared.VarPath("")}) } else { logger.Info(fmt.Sprintf("LXD %s is starting in normal mode", version.Version), log.Ctx{"path": shared.VarPath("")}) } /* Detect user namespaces */ runningInUserns = shared.RunningInUserNS() /* Detect AppArmor availability */ _, err = exec.LookPath("apparmor_parser") if os.Getenv("LXD_SECURITY_APPARMOR") == "false" { logger.Warnf("AppArmor support has been manually disabled") } else if !shared.IsDir("/sys/kernel/security/apparmor") { logger.Warnf("AppArmor support has been disabled because of lack of kernel support") } else if err != nil { logger.Warnf("AppArmor support has been disabled because 'apparmor_parser' couldn't be found") } else { aaAvailable = true } /* Detect AppArmor stacking support */ aaCanStack := func() bool { contentBytes, err := ioutil.ReadFile("/sys/kernel/security/apparmor/features/domain/stack") if err != nil { return false } if string(contentBytes) != "yes\n" { return false } contentBytes, err = ioutil.ReadFile("/sys/kernel/security/apparmor/features/domain/version") if err != nil { return false } content := string(contentBytes) parts := strings.Split(strings.TrimSpace(content), ".") if len(parts) == 0 { logger.Warn("unknown apparmor domain version", log.Ctx{"version": content}) return false } major, err := strconv.Atoi(parts[0]) if err != nil { logger.Warn("unknown apparmor domain version", log.Ctx{"version": content}) return false } minor := 0 if len(parts) == 2 { minor, err = strconv.Atoi(parts[1]) if err != nil { logger.Warn("unknown apparmor domain version", log.Ctx{"version": content}) return false } } return major >= 1 && minor >= 2 } aaStacking = aaCanStack() /* Detect existing AppArmor stack */ if shared.PathExists("/sys/kernel/security/apparmor/.ns_stacked") { contentBytes, err := ioutil.ReadFile("/sys/kernel/security/apparmor/.ns_stacked") if err == nil && string(contentBytes) == "yes\n" { aaStacked = true } } /* Detect AppArmor admin support */ if !haveMacAdmin() { if aaAvailable { logger.Warnf("Per-container AppArmor profiles are disabled because the mac_admin capability is missing.") } } else if runningInUserns && !aaStacked { if aaAvailable { logger.Warnf("Per-container AppArmor profiles are disabled because LXD is running in an unprivileged container without stacking.") } } else { aaAdmin = true } /* Detect AppArmor confinment */ profile := aaProfile() if profile != "unconfined" && profile != "" { if aaAvailable { logger.Warnf("Per-container AppArmor profiles are disabled because LXD is already protected by AppArmor.") } aaConfined = true } /* Detect CGroup support */ cgBlkioController = shared.PathExists("/sys/fs/cgroup/blkio/") if !cgBlkioController { logger.Warnf("Couldn't find the CGroup blkio controller, I/O limits will be ignored.") } cgCpuController = shared.PathExists("/sys/fs/cgroup/cpu/") if !cgCpuController { logger.Warnf("Couldn't find the CGroup CPU controller, CPU time limits will be ignored.") } cgCpusetController = shared.PathExists("/sys/fs/cgroup/cpuset/") if !cgCpusetController { logger.Warnf("Couldn't find the CGroup CPUset controller, CPU pinning will be ignored.") } cgDevicesController = shared.PathExists("/sys/fs/cgroup/devices/") if !cgDevicesController { logger.Warnf("Couldn't find the CGroup devices controller, device access control won't work.") } cgMemoryController = shared.PathExists("/sys/fs/cgroup/memory/") if !cgMemoryController { logger.Warnf("Couldn't find the CGroup memory controller, memory limits will be ignored.") } cgNetPrioController = shared.PathExists("/sys/fs/cgroup/net_prio/") if !cgNetPrioController { logger.Warnf("Couldn't find the CGroup network class controller, network limits will be ignored.") } cgPidsController = shared.PathExists("/sys/fs/cgroup/pids/") if !cgPidsController { logger.Warnf("Couldn't find the CGroup pids controller, process limits will be ignored.") } cgSwapAccounting = shared.PathExists("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") if !cgSwapAccounting { logger.Warnf("CGroup memory swap accounting is disabled, swap limits will be ignored.") } /* Make sure all our directories are available */ if err := os.MkdirAll(shared.VarPath(), 0711); err != nil { return err } if err := os.MkdirAll(shared.CachePath(), 0700); err != nil { return err } if err := os.MkdirAll(shared.VarPath("containers"), 0711); err != nil { return err } if err := os.MkdirAll(shared.VarPath("devices"), 0711); err != nil { return err } if err := os.MkdirAll(shared.VarPath("devlxd"), 0755); err != nil { return err } if err := os.MkdirAll(shared.VarPath("images"), 0700); err != nil { return err } if err := os.MkdirAll(shared.LogPath(), 0700); err != nil { return err } if err := os.MkdirAll(shared.VarPath("security"), 0700); err != nil { return err } if err := os.MkdirAll(shared.VarPath("shmounts"), 0711); err != nil { return err } if err := os.MkdirAll(shared.VarPath("snapshots"), 0700); err != nil { return err } /* Initialize the operating system facade */ err = d.os.Init() if err != nil { return err } /* Initialize the database */ err = initializeDbObject(d, shared.VarPath("lxd.db")) if err != nil { return err } /* Load all config values from the database */ err = daemonConfigInit(d.db) if err != nil { return err } if !d.os.MockMode { /* Setup the storage driver */ err = SetupStorageDriver(d) if err != nil { return fmt.Errorf("Failed to setup storage: %s", err) } /* Apply all patches */ err = patchesApplyAll(d) if err != nil { return err } /* Restore simplestreams cache */ err = imageLoadStreamCache(d) if err != nil { return err } } /* Log expiry */ go func() { t := time.NewTicker(24 * time.Hour) for { logger.Infof("Expiring log files") err := ExpireLogs(d.db) if err != nil { logger.Error("Failed to expire logs", log.Ctx{"err": err}) } logger.Infof("Done expiring log files") <-t.C } }() /* set the initial proxy function based on config values in the DB */ d.proxy = shared.ProxyFromConfig( daemonConfig["core.proxy_https"].Get(), daemonConfig["core.proxy_http"].Get(), daemonConfig["core.proxy_ignore_hosts"].Get(), ) /* Setup some mounts (nice to have) */ if !d.os.MockMode { // Attempt to mount the shmounts tmpfs setupSharedMounts() // Attempt to Mount the devlxd tmpfs if !shared.IsMountPoint(shared.VarPath("devlxd")) { syscall.Mount("tmpfs", shared.VarPath("devlxd"), "tmpfs", 0, "size=100k,mode=0755") } } /* Setup /dev/lxd */ logger.Infof("Starting /dev/lxd handler") d.devlxd, err = createAndBindDevLxd() if err != nil { return err } d.tomb.Go(func() error { server := devLxdServer(d) return server.Serve(d.devlxd) }) if !d.os.MockMode { /* Start the scheduler */ go deviceEventListener(d.State(), d.Storage) /* Setup the TLS authentication */ certf, keyf, err := readMyCert() if err != nil { return err } cert, err := tls.LoadX509KeyPair(certf, keyf) if err != nil { return err } tlsConfig := &tls.Config{ ClientAuth: tls.RequestClientCert, Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, CipherSuites: []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}, PreferServerCipherSuites: true, } tlsConfig.BuildNameToCertificate() d.tlsConfig = tlsConfig readSavedClientCAList(d) } /* Setup the web server */ d.mux = mux.NewRouter() d.mux.StrictSlash(false) d.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") SyncResponse(true, []string{"/1.0"}).Render(w) }) for _, c := range api10 { d.createCmd("1.0", c) } for _, c := range apiInternal { d.createCmd("internal", c) } d.mux.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { logger.Info("Sending top level 404", log.Ctx{"url": r.URL}) w.Header().Set("Content-Type", "application/json") NotFound.Render(w) }) // Prepare the list of listeners listeners := util.GetListeners() if len(listeners) > 0 { logger.Infof("LXD is socket activated") for _, listener := range listeners { if shared.PathExists(listener.Addr().String()) { d.UnixSocket = &Socket{Socket: listener, CloseOnExit: false} } else { tlsListener := tls.NewListener(listener, d.tlsConfig) d.TCPSocket = &Socket{Socket: tlsListener, CloseOnExit: false} } } } else { logger.Infof("LXD isn't socket activated") localSocketPath := shared.VarPath("unix.socket") // If the socket exists, let's try to connect to it and see if there's // a lxd running. if shared.PathExists(localSocketPath) { _, err := lxd.ConnectLXDUnix("", nil) if err != nil { logger.Debugf("Detected stale unix socket, deleting") // Connecting failed, so let's delete the socket and // listen on it ourselves. err = os.Remove(localSocketPath) if err != nil { return err } } else { return fmt.Errorf("LXD is already running.") } } unixAddr, err := net.ResolveUnixAddr("unix", localSocketPath) if err != nil { return fmt.Errorf("cannot resolve unix socket address: %v", err) } unixl, err := net.ListenUnix("unix", unixAddr) if err != nil { return fmt.Errorf("cannot listen on unix socket: %v", err) } if err := os.Chmod(localSocketPath, 0660); err != nil { return err } var gid int if d.group != "" { gid, err = shared.GroupId(d.group) if err != nil { return err } } else { gid = os.Getgid() } if err := os.Chown(localSocketPath, os.Getuid(), gid); err != nil { return err } d.UnixSocket = &Socket{Socket: unixl, CloseOnExit: true} } listenAddr := daemonConfig["core.https_address"].Get() if listenAddr != "" { _, _, err := net.SplitHostPort(listenAddr) if err != nil { listenAddr = fmt.Sprintf("%s:%s", listenAddr, shared.DefaultPort) } tcpl, err := tls.Listen("tcp", listenAddr, d.tlsConfig) if err != nil { logger.Error("cannot listen on https socket, skipping...", log.Ctx{"err": err}) } else { if d.TCPSocket != nil { logger.Infof("Replacing inherited TCP socket with configured one") d.TCPSocket.Socket.Close() } d.TCPSocket = &Socket{Socket: tcpl, CloseOnExit: true} } } // Bind the REST API logger.Infof("REST API daemon:") if d.UnixSocket != nil { logger.Info(" - binding Unix socket", log.Ctx{"socket": d.UnixSocket.Socket.Addr()}) d.tomb.Go(func() error { return http.Serve(d.UnixSocket.Socket, &lxdHttpServer{d.mux, d}) }) } if d.TCPSocket != nil { logger.Info(" - binding TCP socket", log.Ctx{"socket": d.TCPSocket.Socket.Addr()}) d.tomb.Go(func() error { return http.Serve(d.TCPSocket.Socket, &lxdHttpServer{d.mux, d}) }) } // Run the post initialization actions if !d.os.MockMode && !d.SetupMode { err := d.Ready() if err != nil { return err } } return nil } func (d *Daemon) Ready() error { /* Prune images */ d.pruneChan = make(chan bool) go func() { for { timer := time.NewTimer(24 * time.Hour) select { case <-timer.C: /* run once per day */ pruneExpiredImages(d) case <-d.pruneChan: /* run when image.remote_cache_expiry is changed */ pruneExpiredImages(d) timer.Stop() } } }() // Do an initial pruning run before we start updating images pruneExpiredImages(d) /* Auto-update images */ d.resetAutoUpdateChan = make(chan bool) go func() { // Initial image sync interval := daemonConfig["images.auto_update_interval"].GetInt64() if interval > 0 { autoUpdateImages(d) } // Background image sync for { interval := daemonConfig["images.auto_update_interval"].GetInt64() if interval > 0 { timer := time.NewTimer(time.Duration(interval) * time.Hour) select { case <-timer.C: autoUpdateImages(d) case <-d.resetAutoUpdateChan: timer.Stop() } } else { select { case <-d.resetAutoUpdateChan: continue } } } }() /* Auto-update instance types */ go func() { // Background update for { instanceRefreshTypes(d) time.Sleep(24 * time.Hour) } }() s := d.State() /* Restore containers */ containersRestart(s, d.Storage) /* Re-balance in case things changed while LXD was down */ deviceTaskBalance(s, d.Storage) close(d.readyChan) return nil } func (d *Daemon) numRunningContainers() (int, error) { results, err := db.ContainersList(d.db, db.CTypeRegular) if err != nil { return 0, err } count := 0 for _, r := range results { container, err := containerLoadByName(d.State(), d.Storage, r) if err != nil { continue } if container.IsRunning() { count = count + 1 } } return count, nil } var errStop = fmt.Errorf("requested stop") // Stop stops the shared daemon. func (d *Daemon) Stop() error { forceStop := false d.tomb.Kill(errStop) logger.Infof("Stopping REST API handler:") for _, socket := range []*Socket{d.TCPSocket, d.UnixSocket} { if socket == nil { continue } if socket.CloseOnExit { logger.Info(" - closing socket", log.Ctx{"socket": socket.Socket.Addr()}) socket.Socket.Close() } else { logger.Info(" - skipping socket-activated socket", log.Ctx{"socket": socket.Socket.Addr()}) forceStop = true } } logger.Infof("Stopping /dev/lxd handler") d.devlxd.Close() logger.Infof("Stopped /dev/lxd handler") if n, err := d.numRunningContainers(); err != nil || n == 0 { logger.Infof("Unmounting temporary filesystems") syscall.Unmount(shared.VarPath("devlxd"), syscall.MNT_DETACH) syscall.Unmount(shared.VarPath("shmounts"), syscall.MNT_DETACH) logger.Infof("Done unmounting temporary filesystems") } else { logger.Debugf("Not unmounting temporary filesystems (containers are still running)") } logger.Infof("Closing the database") d.db.Close() logger.Infof("Saving simplestreams cache") imageSaveStreamCache() logger.Infof("Saved simplestreams cache") if d.os.MockMode || forceStop { return nil } err := d.tomb.Wait() if err == errStop { return nil } return err } type lxdHttpServer struct { r *mux.Router d *Daemon } func (s *lxdHttpServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { allowedOrigin := daemonConfig["core.https_allowed_origin"].Get() origin := req.Header.Get("Origin") if allowedOrigin != "" && origin != "" { rw.Header().Set("Access-Control-Allow-Origin", allowedOrigin) } allowedMethods := daemonConfig["core.https_allowed_methods"].Get() if allowedMethods != "" && origin != "" { rw.Header().Set("Access-Control-Allow-Methods", allowedMethods) } allowedHeaders := daemonConfig["core.https_allowed_headers"].Get() if allowedHeaders != "" && origin != "" { rw.Header().Set("Access-Control-Allow-Headers", allowedHeaders) } // OPTIONS request don't need any further processing if req.Method == "OPTIONS" { return } // Call the original server s.r.ServeHTTP(rw, req) } // Create a database connection and perform any updates needed. func initializeDbObject(d *Daemon, path string) error { var err error // Open the database. If the file doesn't exist it is created. d.db, err = db.OpenDb(path) if err != nil { return err } // Create the DB if it doesn't exist. err = db.CreateDb(d.db, patchesGetNames()) if err != nil { return fmt.Errorf("Error creating database: %s", err) } // Detect LXD downgrades if db.GetSchema(d.db) > db.GetLatestSchema() { return fmt.Errorf("The database schema is more recent than LXD's schema.") } // Apply any database update. // // NOTE: we use the legacyPatches parameter to run a few // legacy non-db updates that were in place before the // patches mechanism was introduced in lxd/patches.go. The // rest of non-db patches will be applied separately via // patchesApplyAll. See PR #3322 for more details. legacy := map[int]*db.LegacyPatch{} for i, patch := range legacyPatches { legacy[i] = &db.LegacyPatch{ Hook: func() error { return patch(d) }, } } for _, i := range legacyPatchesNeedingDB { legacy[i].NeedsDB = true } err = db.UpdatesApplyAll(d.db, true, legacy) if err != nil { return err } return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/containers_post.go�������������������������������������������������������������������0000644�0610621�0607500�00000022740�13172163242�020026� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "crypto/x509" "encoding/json" "encoding/pem" "fmt" "net/http" "strings" "github.com/dustinkirkland/golang-petname" "github.com/gorilla/websocket" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/types" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/osarch" log "gopkg.in/inconshreveable/log15.v2" ) func createFromImage(d *Daemon, req *api.ContainersPost) Response { var hash string var err error if req.Source.Fingerprint != "" { hash = req.Source.Fingerprint } else if req.Source.Alias != "" { if req.Source.Server != "" { hash = req.Source.Alias } else { _, alias, err := db.ImageAliasGet(d.db, req.Source.Alias, true) if err != nil { return SmartError(err) } hash = alias.Target } } else if req.Source.Properties != nil { if req.Source.Server != "" { return BadRequest(fmt.Errorf("Property match is only supported for local images")) } hashes, err := db.ImagesGet(d.db, false) if err != nil { return SmartError(err) } var image *api.Image for _, imageHash := range hashes { _, img, err := db.ImageGet(d.db, imageHash, false, true) if err != nil { continue } if image != nil && img.CreatedAt.Before(image.CreatedAt) { continue } match := true for key, value := range req.Source.Properties { if img.Properties[key] != value { match = false break } } if !match { continue } image = img } if image == nil { return BadRequest(fmt.Errorf("No matching image could be found")) } hash = image.Fingerprint } else { return BadRequest(fmt.Errorf("Must specify one of alias, fingerprint or properties for init from image")) } run := func(op *operation) error { args := db.ContainerArgs{ Config: req.Config, Ctype: db.CTypeRegular, Devices: req.Devices, Ephemeral: req.Ephemeral, Name: req.Name, Profiles: req.Profiles, } var info *api.Image if req.Source.Server != "" { info, err = d.ImageDownload( op, req.Source.Server, req.Source.Protocol, req.Source.Certificate, req.Source.Secret, hash, true, daemonConfig["images.auto_update_cached"].GetBool()) if err != nil { return err } } else { _, info, err = db.ImageGet(d.db, hash, false, false) if err != nil { return err } } args.Architecture, err = osarch.ArchitectureId(info.Architecture) if err != nil { return err } _, err = containerCreateFromImage(d.State(), d.Storage, args, info.Fingerprint) return err } resources := map[string][]string{} resources["containers"] = []string{req.Name} op, err := operationCreate(operationClassTask, resources, nil, run, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func createFromNone(d *Daemon, req *api.ContainersPost) Response { args := db.ContainerArgs{ Config: req.Config, Ctype: db.CTypeRegular, Devices: req.Devices, Ephemeral: req.Ephemeral, Name: req.Name, Profiles: req.Profiles, } if req.Architecture != "" { architecture, err := osarch.ArchitectureId(req.Architecture) if err != nil { return InternalError(err) } args.Architecture = architecture } run := func(op *operation) error { _, err := containerCreateAsEmpty(d, args) return err } resources := map[string][]string{} resources["containers"] = []string{req.Name} op, err := operationCreate(operationClassTask, resources, nil, run, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func createFromMigration(d *Daemon, req *api.ContainersPost) Response { // Validate migration mode if req.Source.Mode != "pull" { return NotImplemented } var c container // Parse the architecture name architecture, err := osarch.ArchitectureId(req.Architecture) if err != nil { return BadRequest(err) } // Prepare the container creation request args := db.ContainerArgs{ Architecture: architecture, BaseImage: req.Source.BaseImage, Config: req.Config, Ctype: db.CTypeRegular, Devices: req.Devices, Ephemeral: req.Ephemeral, Name: req.Name, Profiles: req.Profiles, } /* Only create a container from an image if we're going to * rsync over the top of it. In the case of a better file * transfer mechanism, let's just use that. * * TODO: we could invent some negotiation here, where if the * source and sink both have the same image, we can clone from * it, but we have to know before sending the snapshot that * we're sending the whole thing or just a delta from the * image, so one extra negotiation round trip is needed. An * alternative is to move actual container object to a later * point and just negotiate it over the migration control * socket. Anyway, it'll happen later :) */ _, _, err = db.ImageGet(d.db, req.Source.BaseImage, false, true) if err == nil && d.Storage.MigrationType() == MigrationFSType_RSYNC { c, err = containerCreateFromImage(d.State(), d.Storage, args, req.Source.BaseImage) if err != nil { return InternalError(err) } } else { c, err = containerCreateAsEmpty(d, args) if err != nil { return InternalError(err) } } var cert *x509.Certificate if req.Source.Certificate != "" { certBlock, _ := pem.Decode([]byte(req.Source.Certificate)) if certBlock == nil { c.Delete() return InternalError(fmt.Errorf("Invalid certificate")) } cert, err = x509.ParseCertificate(certBlock.Bytes) if err != nil { c.Delete() return InternalError(err) } } config, err := shared.GetTLSConfig("", "", "", cert) if err != nil { c.Delete() return InternalError(err) } migrationArgs := MigrationSinkArgs{ Url: req.Source.Operation, Dialer: websocket.Dialer{ TLSClientConfig: config, NetDial: shared.RFC3493Dialer}, Container: c, Secrets: req.Source.Websockets, } sink, err := NewMigrationSink(&migrationArgs) if err != nil { c.Delete() return InternalError(err) } resources := map[string][]string{} resources["containers"] = []string{req.Name} op, err := operationCreate(operationClassTask, resources, nil, sink.Do, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func createFromCopy(d *Daemon, req *api.ContainersPost) Response { if req.Source.Source == "" { return BadRequest(fmt.Errorf("must specify a source container")) } source, err := containerLoadByName(d.State(), d.Storage, req.Source.Source) if err != nil { return SmartError(err) } // Config override sourceConfig := source.LocalConfig() if req.Config == nil { req.Config = make(map[string]string) } for key, value := range sourceConfig { if len(key) > 8 && key[0:8] == "volatile" && !shared.StringInSlice(key[9:], []string{"base_image", "last_state.idmap"}) { logger.Debug("Skipping volatile key from copy source", log.Ctx{"key": key}) continue } _, exists := req.Config[key] if exists { continue } req.Config[key] = value } // Devices override sourceDevices := source.LocalDevices() if req.Devices == nil { req.Devices = make(map[string]map[string]string) } for key, value := range sourceDevices { _, exists := req.Devices[key] if exists { continue } req.Devices[key] = value } // Profiles override if req.Profiles == nil { req.Profiles = source.Profiles() } args := db.ContainerArgs{ Architecture: source.Architecture(), BaseImage: req.Source.BaseImage, Config: req.Config, Ctype: db.CTypeRegular, Devices: req.Devices, Ephemeral: req.Ephemeral, Name: req.Name, Profiles: req.Profiles, } run := func(op *operation) error { _, err := containerCreateAsCopy(d.State(), d.Storage, args, source) if err != nil { return err } return nil } resources := map[string][]string{} resources["containers"] = []string{req.Name, req.Source.Source} op, err := operationCreate(operationClassTask, resources, nil, run, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func containersPost(d *Daemon, r *http.Request) Response { logger.Debugf("Responding to container create") req := api.ContainersPost{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } if req.Name == "" { cs, err := db.ContainersList(d.db, db.CTypeRegular) if err != nil { return SmartError(err) } i := 0 for { i++ req.Name = strings.ToLower(petname.Generate(2, "-")) if !shared.StringInSlice(req.Name, cs) { break } if i > 100 { return InternalError(fmt.Errorf("couldn't generate a new unique name after 100 tries")) } } logger.Debugf("No name provided, creating %s", req.Name) } if req.Devices == nil { req.Devices = types.Devices{} } if req.Config == nil { req.Config = map[string]string{} } if req.InstanceType != "" { conf, err := instanceParseType(req.InstanceType) if err != nil { return BadRequest(err) } for k, v := range conf { if req.Config[k] == "" { req.Config[k] = v } } } if strings.Contains(req.Name, shared.SnapshotDelimiter) { return BadRequest(fmt.Errorf("Invalid container name: '%s' is reserved for snapshots", shared.SnapshotDelimiter)) } switch req.Source.Type { case "image": return createFromImage(d, &req) case "none": return createFromNone(d, &req) case "migration": return createFromMigration(d, &req) case "copy": return createFromCopy(d, &req) default: return BadRequest(fmt.Errorf("unknown source type %s", req.Source.Type)) } } ��������������������������������lxd-2.0.11/lxd/containers_get.go��������������������������������������������������������������������0000644�0610621�0607500�00000003646�13172163242�017624� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "net/http" "time" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/version" ) func containersGet(d *Daemon, r *http.Request) Response { for i := 0; i < 100; i++ { result, err := doContainersGet(d.State(), d.Storage, util.IsRecursionRequest(r)) if err == nil { return SyncResponse(true, result) } if !db.IsDbLockedError(err) { logger.Debugf("DBERR: containersGet: error %q", err) return SmartError(err) } // 1 s may seem drastic, but we really don't want to thrash // perhaps we should use a random amount time.Sleep(100 * time.Millisecond) } logger.Debugf("DBERR: containersGet, db is locked") logger.Debugf(logger.GetStack()) return InternalError(fmt.Errorf("DB is locked")) } func doContainersGet(s *state.State, storage storage, recursion bool) (interface{}, error) { result, err := db.ContainersList(s.DB, db.CTypeRegular) if err != nil { return nil, err } resultString := []string{} resultList := []*api.Container{} if err != nil { return []string{}, err } for _, container := range result { if !recursion { url := fmt.Sprintf("/%s/containers/%s", version.APIVersion, container) resultString = append(resultString, url) } else { c, err := doContainerGet(s, storage, container) if err != nil { c = &api.Container{ Name: container, Status: api.Error.String(), StatusCode: api.Error} } resultList = append(resultList, c) } } if !recursion { return resultString, nil } return resultList, nil } func doContainerGet(s *state.State, storage storage, cname string) (*api.Container, error) { c, err := containerLoadByName(s, storage, cname) if err != nil { return nil, err } cts, err := c.Render() if err != nil { return nil, err } return cts.(*api.Container), nil } ������������������������������������������������������������������������������������������lxd-2.0.11/lxd/containers.go������������������������������������������������������������������������0000644�0610621�0607500�00000010244�13172163242�016755� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "sort" "strconv" "sync" "time" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) var containersCmd = Command{ name: "containers", get: containersGet, post: containersPost, } var containerCmd = Command{ name: "containers/{name}", get: containerGet, put: containerPut, delete: containerDelete, post: containerPost, } var containerStateCmd = Command{ name: "containers/{name}/state", get: containerState, put: containerStatePut, } var containerFileCmd = Command{ name: "containers/{name}/files", get: containerFileHandler, post: containerFileHandler, } var containerSnapshotsCmd = Command{ name: "containers/{name}/snapshots", get: containerSnapshotsGet, post: containerSnapshotsPost, } var containerSnapshotCmd = Command{ name: "containers/{name}/snapshots/{snapshotName}", get: snapshotHandler, post: snapshotHandler, delete: snapshotHandler, } var containerExecCmd = Command{ name: "containers/{name}/exec", post: containerExecPost, } type containerAutostartList []container func (slice containerAutostartList) Len() int { return len(slice) } func (slice containerAutostartList) Less(i, j int) bool { iOrder := slice[i].ExpandedConfig()["boot.autostart.priority"] jOrder := slice[j].ExpandedConfig()["boot.autostart.priority"] if iOrder != jOrder { iOrderInt, _ := strconv.Atoi(iOrder) jOrderInt, _ := strconv.Atoi(jOrder) return iOrderInt > jOrderInt } return slice[i].Name() < slice[j].Name() } func (slice containerAutostartList) Swap(i, j int) { slice[i], slice[j] = slice[j], slice[i] } func containersRestart(s *state.State, storage storage) error { // Get all the containers result, err := db.ContainersList(s.DB, db.CTypeRegular) if err != nil { return err } containers := []container{} for _, name := range result { c, err := containerLoadByName(s, storage, name) if err != nil { return err } containers = append(containers, c) } sort.Sort(containerAutostartList(containers)) // Restart the containers for _, c := range containers { config := c.ExpandedConfig() lastState := config["volatile.last_state.power"] autoStart := config["boot.autostart"] autoStartDelay := config["boot.autostart.delay"] if shared.IsTrue(autoStart) || (autoStart == "" && lastState == "RUNNING") { if c.IsRunning() { continue } c.Start(false) autoStartDelayInt, err := strconv.Atoi(autoStartDelay) if err == nil { time.Sleep(time.Duration(autoStartDelayInt) * time.Second) } } } return nil } func containersShutdown(s *state.State, storage storage) error { var wg sync.WaitGroup // Get all the containers results, err := db.ContainersList(s.DB, db.CTypeRegular) if err != nil { return err } // Reset all container states _, err = db.Exec(s.DB, "DELETE FROM containers_config WHERE key='volatile.last_state.power'") if err != nil { return err } for _, r := range results { // Load the container c, err := containerLoadByName(s, storage, r) if err != nil { return err } // Record the current state lastState := c.State() // Stop the container if c.IsRunning() { wg.Add(1) go func() { c.Shutdown(time.Second * 30) c.Stop(false) c.ConfigKeySet("volatile.last_state.power", lastState) wg.Done() }() } else { c.ConfigKeySet("volatile.last_state.power", lastState) } } wg.Wait() return nil } func containerDeleteSnapshots(s *state.State, storage storage, cname string) error { logger.Debug("containerDeleteSnapshots", log.Ctx{"container": cname}) results, err := db.ContainerGetSnapshots(s.DB, cname) if err != nil { return err } for _, sname := range results { sc, err := containerLoadByName(s, storage, sname) if err != nil { logger.Error( "containerDeleteSnapshots: Failed to load the snapshotcontainer", log.Ctx{"container": cname, "snapshot": sname}) continue } if err := sc.Delete(); err != nil { logger.Error( "containerDeleteSnapshots: Failed to delete a snapshotcontainer", log.Ctx{"container": cname, "snapshot": sname, "err": err}) } } return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_test.go��������������������������������������������������������������������0000644�0610621�0607500�00000024716�13172163242�017642� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "testing" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/types" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/idmap" "github.com/stretchr/testify/suite" ) type containerTestSuite struct { lxdTestSuite } func (suite *containerTestSuite) TestContainer_ProfilesDefault() { args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Name: "testFoo", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() profiles := c.Profiles() suite.Len( profiles, 1, "No default profile created on containerCreateInternal.") suite.Equal( "default", profiles[0], "First profile should be the default profile.") } func (suite *containerTestSuite) TestContainer_ProfilesMulti() { // Create an unprivileged profile _, err := db.ProfileCreate( suite.d.db, "unprivileged", "unprivileged", map[string]string{"security.privileged": "true"}, types.Devices{}) suite.Req.Nil(err, "Failed to create the unprivileged profile.") defer func() { db.ProfileDelete(suite.d.db, "unprivileged") }() args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Profiles: []string{"default", "unprivileged"}, Name: "testFoo", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() profiles := c.Profiles() suite.Len( profiles, 2, "Didn't get both profiles in containerCreateInternal.") suite.True( c.IsPrivileged(), "The container is not privileged (didn't apply the unprivileged profile?).") } func (suite *containerTestSuite) TestContainer_ProfilesOverwriteDefaultNic() { args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Config: map[string]string{"security.privileged": "true"}, Devices: types.Devices{ "eth0": types.Device{ "type": "nic", "nictype": "bridged", "parent": "unknownbr0"}}, Name: "testFoo", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) suite.True(c.IsPrivileged(), "This container should be privileged.") out, err := c.Render() suite.Req.Nil(err) state := out.(*api.Container) defer c.Delete() suite.Equal( "unknownbr0", state.Devices["eth0"]["parent"], "Container config doesn't overwrite profile config.") } func (suite *containerTestSuite) TestContainer_LoadFromDB() { args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Config: map[string]string{"security.privileged": "true"}, Devices: types.Devices{ "eth0": types.Device{ "type": "nic", "nictype": "bridged", "parent": "unknownbr0"}}, Name: "testFoo", } // Create the container c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() // Load the container and trigger initLXC() c2, err := containerLoadByName(suite.d.State(), suite.d.Storage, "testFoo") c2.IsRunning() suite.Req.Nil(err) suite.Exactly( c, c2, "The loaded container isn't excactly the same as the created one.") } func (suite *containerTestSuite) TestContainer_Path_Regular() { // Regular args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Name: "testFoo", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() suite.Req.False(c.IsSnapshot(), "Shouldn't be a snapshot.") suite.Req.Equal(shared.VarPath("containers", "testFoo"), c.Path()) suite.Req.Equal(shared.VarPath("containers", "testFoo2"), containerPath("testFoo2", false)) } func (suite *containerTestSuite) TestContainer_Path_Snapshot() { // Snapshot args := db.ContainerArgs{ Ctype: db.CTypeSnapshot, Ephemeral: false, Name: "test/snap0", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() suite.Req.True(c.IsSnapshot(), "Should be a snapshot.") suite.Req.Equal( shared.VarPath("snapshots", "test", "snap0"), c.Path()) suite.Req.Equal( shared.VarPath("snapshots", "test", "snap1"), containerPath("test/snap1", true)) } func (suite *containerTestSuite) TestContainer_LogPath() { args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Name: "testFoo", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() suite.Req.Equal(shared.VarPath("logs", "testFoo"), c.LogPath()) } func (suite *containerTestSuite) TestContainer_IsPrivileged_Privileged() { args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Config: map[string]string{"security.privileged": "true"}, Name: "testFoo", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() suite.Req.True(c.IsPrivileged(), "This container should be privileged.") suite.Req.Nil(c.Delete(), "Failed to delete the container.") } func (suite *containerTestSuite) TestContainer_IsPrivileged_Unprivileged() { args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Config: map[string]string{"security.privileged": "false"}, Name: "testFoo", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() suite.Req.False(c.IsPrivileged(), "This container should be unprivileged.") suite.Req.Nil(c.Delete(), "Failed to delete the container.") } func (suite *containerTestSuite) TestContainer_Rename() { args := db.ContainerArgs{ Ctype: db.CTypeRegular, Ephemeral: false, Name: "testFoo", } c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, args) suite.Req.Nil(err) defer c.Delete() suite.Req.Nil(c.Rename("testFoo2"), "Failed to rename the container.") suite.Req.Equal(shared.VarPath("containers", "testFoo2"), c.Path()) } func (suite *containerTestSuite) TestContainer_findIdmap_isolated() { c1, err := containerCreateInternal(suite.d.State(), suite.d.Storage, db.ContainerArgs{ Ctype: db.CTypeRegular, Name: "isol-1", Config: map[string]string{ "security.idmap.isolated": "true", }, }) suite.Req.Nil(err) defer c1.Delete() c2, err := containerCreateInternal(suite.d.State(), suite.d.Storage, db.ContainerArgs{ Ctype: db.CTypeRegular, Name: "isol-2", Config: map[string]string{ "security.idmap.isolated": "true", }, }) suite.Req.Nil(err) defer c2.Delete() map1, err := c1.(*containerLXC).NextIdmapSet() suite.Req.Nil(err) map2, err := c2.(*containerLXC).NextIdmapSet() suite.Req.Nil(err) host := suite.d.os.IdmapSet.Idmap[0] for i := 0; i < 2; i++ { suite.Req.Equal(host.Hostid+65536, map1.Idmap[i].Hostid, "hostids don't match %d", i) suite.Req.Equal(int64(0), map1.Idmap[i].Nsid, "nsid nonzero") suite.Req.Equal(int64(65536), map1.Idmap[i].Maprange, "incorrect maprange") } for i := 0; i < 2; i++ { suite.Req.Equal(host.Hostid+65536*2, map2.Idmap[i].Hostid, "hostids don't match") suite.Req.Equal(int64(0), map2.Idmap[i].Nsid, "nsid nonzero") suite.Req.Equal(int64(65536), map2.Idmap[i].Maprange, "incorrect maprange") } } func (suite *containerTestSuite) TestContainer_findIdmap_mixed() { c1, err := containerCreateInternal(suite.d.State(), suite.d.Storage, db.ContainerArgs{ Ctype: db.CTypeRegular, Name: "isol-1", Config: map[string]string{ "security.idmap.isolated": "false", }, }) suite.Req.Nil(err) defer c1.Delete() c2, err := containerCreateInternal(suite.d.State(), suite.d.Storage, db.ContainerArgs{ Ctype: db.CTypeRegular, Name: "isol-2", Config: map[string]string{ "security.idmap.isolated": "true", }, }) suite.Req.Nil(err) defer c2.Delete() map1, err := c1.(*containerLXC).NextIdmapSet() suite.Req.Nil(err) map2, err := c2.(*containerLXC).NextIdmapSet() suite.Req.Nil(err) host := suite.d.os.IdmapSet.Idmap[0] for i := 0; i < 2; i++ { suite.Req.Equal(host.Hostid, map1.Idmap[i].Hostid, "hostids don't match %d", i) suite.Req.Equal(int64(0), map1.Idmap[i].Nsid, "nsid nonzero") suite.Req.Equal(host.Maprange, map1.Idmap[i].Maprange, "incorrect maprange") } for i := 0; i < 2; i++ { suite.Req.Equal(host.Hostid+65536, map2.Idmap[i].Hostid, "hostids don't match") suite.Req.Equal(int64(0), map2.Idmap[i].Nsid, "nsid nonzero") suite.Req.Equal(int64(65536), map2.Idmap[i].Maprange, "incorrect maprange") } } func (suite *containerTestSuite) TestContainer_findIdmap_raw() { c1, err := containerCreateInternal(suite.d.State(), suite.d.Storage, db.ContainerArgs{ Ctype: db.CTypeRegular, Name: "isol-1", Config: map[string]string{ "security.idmap.isolated": "false", "raw.idmap": "both 1000 1000", }, }) suite.Req.Nil(err) defer c1.Delete() map1, err := c1.(*containerLXC).NextIdmapSet() suite.Req.Nil(err) host := suite.d.os.IdmapSet.Idmap[0] for _, i := range []int{0, 3} { suite.Req.Equal(host.Hostid, map1.Idmap[i].Hostid, "hostids don't match") suite.Req.Equal(int64(0), map1.Idmap[i].Nsid, "nsid nonzero") suite.Req.Equal(int64(1000), map1.Idmap[i].Maprange, "incorrect maprange") } for _, i := range []int{1, 4} { suite.Req.Equal(int64(1000), map1.Idmap[i].Hostid, "hostids don't match") suite.Req.Equal(int64(1000), map1.Idmap[i].Nsid, "invalid nsid") suite.Req.Equal(int64(1), map1.Idmap[i].Maprange, "incorrect maprange") } for _, i := range []int{2, 5} { suite.Req.Equal(host.Hostid+1001, map1.Idmap[i].Hostid, "hostids don't match") suite.Req.Equal(int64(1001), map1.Idmap[i].Nsid, "invalid nsid") suite.Req.Equal(host.Maprange-1000-1, map1.Idmap[i].Maprange, "incorrect maprange") } } func (suite *containerTestSuite) TestContainer_findIdmap_maxed() { maps := []*idmap.IdmapSet{} for i := 0; i < 7; i++ { c, err := containerCreateInternal(suite.d.State(), suite.d.Storage, db.ContainerArgs{ Ctype: db.CTypeRegular, Name: fmt.Sprintf("isol-%d", i), Config: map[string]string{ "security.idmap.isolated": "true", }, }) /* we should fail if there are no ids left */ if i != 6 { suite.Req.Nil(err) } else { suite.Req.NotNil(err) return } defer c.Delete() m, err := c.(*containerLXC).NextIdmapSet() suite.Req.Nil(err) maps = append(maps, m) } for i, m1 := range maps { for j, m2 := range maps { if m1 == m2 { continue } for _, e := range m2.Idmap { suite.Req.False(m1.HostidsIntersect(e), "%d and %d's idmaps intersect %v %v", i, j, m1, m2) } } } } func TestContainerTestSuite(t *testing.T) { suite.Run(t, new(containerTestSuite)) } ��������������������������������������������������lxd-2.0.11/lxd/container_state.go�������������������������������������������������������������������0000644�0610621�0607500�00000006255�13172163242�020001� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "net/http" "time" "github.com/gorilla/mux" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" ) func containerState(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return SmartError(err) } state, err := c.RenderState() if err != nil { return InternalError(err) } return SyncResponse(true, state) } func containerStatePut(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] raw := api.ContainerStatePut{} // We default to -1 (i.e. no timeout) here instead of 0 (instant // timeout). raw.Timeout = -1 if err := json.NewDecoder(r.Body).Decode(&raw); err != nil { return BadRequest(err) } // Don't mess with containers while in setup mode <-d.readyChan c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return SmartError(err) } var do func(*operation) error switch shared.ContainerAction(raw.Action) { case shared.Start: do = func(op *operation) error { if err = c.Start(raw.Stateful); err != nil { return err } return nil } case shared.Stop: if raw.Stateful { do = func(op *operation) error { err := c.Stop(raw.Stateful) if err != nil { return err } return nil } } else if raw.Timeout == 0 || raw.Force { do = func(op *operation) error { err = c.Stop(false) if err != nil { return err } return nil } } else { do = func(op *operation) error { if c.IsFrozen() { err := c.Unfreeze() if err != nil { return err } } err = c.Shutdown(time.Duration(raw.Timeout) * time.Second) if err != nil { return err } return nil } } case shared.Restart: do = func(op *operation) error { ephemeral := c.IsEphemeral() if ephemeral { // Unset ephemeral flag args := db.ContainerArgs{ Architecture: c.Architecture(), Config: c.LocalConfig(), Devices: c.LocalDevices(), Ephemeral: false, Profiles: c.Profiles(), } err := c.Update(args, false) if err != nil { return err } // On function return, set the flag back on defer func() { args.Ephemeral = ephemeral c.Update(args, true) }() } if raw.Timeout == 0 || raw.Force { err = c.Stop(false) if err != nil { return err } } else { if c.IsFrozen() { return fmt.Errorf("container is not running") } err = c.Shutdown(time.Duration(raw.Timeout) * time.Second) if err != nil { return err } } err = c.Start(false) if err != nil { return err } return nil } case shared.Freeze: do = func(op *operation) error { return c.Freeze() } case shared.Unfreeze: do = func(op *operation) error { return c.Unfreeze() } default: return BadRequest(fmt.Errorf("unknown action %s", raw.Action)) } resources := map[string][]string{} resources["containers"] = []string{name} op, err := operationCreate(operationClassTask, resources, nil, do, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_snapshot.go����������������������������������������������������������������0000644�0610621�0607500�00000013262�13172163242�020514� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "net/http" "strconv" "github.com/gorilla/mux" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/version" ) func containerSnapshotsGet(d *Daemon, r *http.Request) Response { recursionStr := r.FormValue("recursion") recursion, err := strconv.Atoi(recursionStr) if err != nil { recursion = 0 } cname := mux.Vars(r)["name"] c, err := containerLoadByName(d.State(), d.Storage, cname) if err != nil { return SmartError(err) } snaps, err := c.Snapshots() if err != nil { return SmartError(err) } resultString := []string{} resultMap := []*api.ContainerSnapshot{} for _, snap := range snaps { _, snapName, _ := containerGetParentAndSnapshotName(snap.Name()) if recursion == 0 { url := fmt.Sprintf("/%s/containers/%s/snapshots/%s", version.APIVersion, cname, snapName) resultString = append(resultString, url) } else { render, err := snap.Render() if err != nil { continue } resultMap = append(resultMap, render.(*api.ContainerSnapshot)) } } if recursion == 0 { return SyncResponse(true, resultString) } return SyncResponse(true, resultMap) } /* * Note, the code below doesn't deal with snapshots of snapshots. * To do that, we'll need to weed out based on # slashes in names */ func nextSnapshot(d *Daemon, name string) int { base := name + shared.SnapshotDelimiter + "snap" length := len(base) q := fmt.Sprintf("SELECT name FROM containers WHERE type=? AND SUBSTR(name,1,?)=?") var numstr string inargs := []interface{}{db.CTypeSnapshot, length, base} outfmt := []interface{}{numstr} results, err := db.QueryScan(d.db, q, inargs, outfmt) if err != nil { return 0 } max := 0 for _, r := range results { numstr = r[0].(string) if len(numstr) <= length { continue } substr := numstr[length:] var num int count, err := fmt.Sscanf(substr, "%d", &num) if err != nil || count != 1 { continue } if num >= max { max = num + 1 } } return max } func containerSnapshotsPost(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] /* * snapshot is a three step operation: * 1. choose a new name * 2. copy the database info over * 3. copy over the rootfs */ c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return SmartError(err) } req := api.ContainerSnapshotsPost{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } if req.Name == "" { // come up with a name i := nextSnapshot(d, name) req.Name = fmt.Sprintf("snap%d", i) } fullName := name + shared.SnapshotDelimiter + req.Name snapshot := func(op *operation) error { args := db.ContainerArgs{ Name: fullName, Ctype: db.CTypeSnapshot, Config: c.LocalConfig(), Profiles: c.Profiles(), Ephemeral: c.IsEphemeral(), BaseImage: c.ExpandedConfig()["volatile.base_image"], Architecture: c.Architecture(), Devices: c.LocalDevices(), Stateful: req.Stateful, } _, err := containerCreateAsSnapshot(d.State(), d.Storage, args, c) if err != nil { return err } return nil } resources := map[string][]string{} resources["containers"] = []string{name} op, err := operationCreate(operationClassTask, resources, nil, snapshot, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func snapshotHandler(d *Daemon, r *http.Request) Response { containerName := mux.Vars(r)["name"] snapshotName := mux.Vars(r)["snapshotName"] sc, err := containerLoadByName( d.State(), d.Storage, containerName+ shared.SnapshotDelimiter+ snapshotName) if err != nil { return SmartError(err) } switch r.Method { case "GET": return snapshotGet(sc, snapshotName) case "POST": return snapshotPost(d, r, sc, containerName) case "DELETE": return snapshotDelete(sc, snapshotName) default: return NotFound } } func snapshotGet(sc container, name string) Response { render, err := sc.Render() if err != nil { return SmartError(err) } return SyncResponse(true, render.(*api.ContainerSnapshot)) } func snapshotPost(d *Daemon, r *http.Request, sc container, containerName string) Response { raw := shared.Jmap{} if err := json.NewDecoder(r.Body).Decode(&raw); err != nil { return BadRequest(err) } migration, err := raw.GetBool("migration") if err == nil && migration { ws, err := NewMigrationSource(sc) if err != nil { return SmartError(err) } resources := map[string][]string{} resources["containers"] = []string{containerName} op, err := operationCreate(operationClassWebsocket, resources, ws.Metadata(), ws.Do, nil, ws.Connect) if err != nil { return InternalError(err) } return OperationResponse(op) } newName, err := raw.GetString("name") if err != nil { return BadRequest(err) } fullName := containerName + shared.SnapshotDelimiter + newName // Check that the name isn't already in use id, _ := db.ContainerId(d.db, fullName) if id > 0 { return Conflict } rename := func(op *operation) error { return sc.Rename(fullName) } resources := map[string][]string{} resources["containers"] = []string{containerName} op, err := operationCreate(operationClassTask, resources, nil, rename, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func snapshotDelete(sc container, name string) Response { remove := func(op *operation) error { return sc.Delete() } resources := map[string][]string{} resources["containers"] = []string{sc.Name()} op, err := operationCreate(operationClassTask, resources, nil, remove, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_put.go���������������������������������������������������������������������0000644�0610621�0607500�00000004762�13172163242�017472� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "database/sql" "encoding/json" "fmt" "net/http" "github.com/gorilla/mux" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/osarch" log "gopkg.in/inconshreveable/log15.v2" ) /* * Update configuration, or, if 'restore:snapshot-name' is present, restore * the named snapshot */ func containerPut(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return NotFound } configRaw := api.ContainerPut{} if err := json.NewDecoder(r.Body).Decode(&configRaw); err != nil { return BadRequest(err) } architecture, err := osarch.ArchitectureId(configRaw.Architecture) if err != nil { architecture = 0 } var do = func(*operation) error { return nil } if configRaw.Restore == "" { // Update container configuration do = func(op *operation) error { args := db.ContainerArgs{ Architecture: architecture, Config: configRaw.Config, Devices: configRaw.Devices, Ephemeral: configRaw.Ephemeral, Profiles: configRaw.Profiles} // FIXME: should set to true when not migrating err = c.Update(args, false) if err != nil { return err } return nil } } else { // Snapshot Restore do = func(op *operation) error { return containerSnapRestore(d.State(), d.Storage, name, configRaw.Restore) } } resources := map[string][]string{} resources["containers"] = []string{name} op, err := operationCreate(operationClassTask, resources, nil, do, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } func containerSnapRestore(s *state.State, storage storage, name string, snap string) error { // normalize snapshot name if !shared.IsSnapshot(snap) { snap = name + shared.SnapshotDelimiter + snap } logger.Info( "RESTORE => Restoring snapshot", log.Ctx{ "snapshot": snap, "container": name}) c, err := containerLoadByName(s, storage, name) if err != nil { logger.Error( "RESTORE => loadcontainerLXD() failed", log.Ctx{ "container": name, "err": err}) return err } source, err := containerLoadByName(s, storage, snap) if err != nil { switch err { case sql.ErrNoRows: return fmt.Errorf("snapshot %s does not exist", snap) default: return err } } if err := c.Restore(source); err != nil { return err } return nil } ��������������lxd-2.0.11/lxd/container_post.go��������������������������������������������������������������������0000644�0610621�0607500�00000002507�13172163242�017642� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "io/ioutil" "net/http" "github.com/gorilla/mux" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/shared/api" ) func containerPost(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return SmartError(err) } buf, err := ioutil.ReadAll(r.Body) if err != nil { return InternalError(err) } body := api.ContainerPost{} err = json.Unmarshal(buf, &body) if err != nil { return BadRequest(err) } if body.Migration { ws, err := NewMigrationSource(c) if err != nil { return InternalError(err) } resources := map[string][]string{} resources["containers"] = []string{name} op, err := operationCreate(operationClassWebsocket, resources, ws.Metadata(), ws.Do, nil, ws.Connect) if err != nil { return InternalError(err) } return OperationResponse(op) } // Check that the name isn't already in use id, _ := db.ContainerId(d.db, body.Name) if id > 0 { return Conflict } run := func(*operation) error { return c.Rename(body.Name) } resources := map[string][]string{} resources["containers"] = []string{name} op, err := operationCreate(operationClassTask, resources, nil, run, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_lxc.go���������������������������������������������������������������������0000644�0610621�0607500�00000420626�13172163242�017451� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "archive/tar" "bufio" "encoding/json" "fmt" "io" "io/ioutil" "net" "os" "os/exec" "path" "path/filepath" "reflect" "sort" "strconv" "strings" "sync" "syscall" "time" "gopkg.in/flosch/pongo2.v3" "gopkg.in/lxc/go-lxc.v2" "gopkg.in/yaml.v2" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/lxd/types" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/osarch" log "gopkg.in/inconshreveable/log15.v2" ) // Operation locking type lxcContainerOperation struct { action string chanDone chan error chanReset chan bool err error id int reusable bool } func (op *lxcContainerOperation) Create(id int, action string, reusable bool) *lxcContainerOperation { op.id = id op.action = action op.reusable = reusable op.chanDone = make(chan error, 0) op.chanReset = make(chan bool, 0) go func(op *lxcContainerOperation) { for { select { case <-op.chanReset: continue case <-time.After(time.Second * 30): op.Done(fmt.Errorf("Container %s operation timed out after 30 seconds", op.action)) return } } }(op) return op } func (op *lxcContainerOperation) Reset() error { if !op.reusable { return fmt.Errorf("Can't reset a non-reusable operation") } op.chanReset <- true return nil } func (op *lxcContainerOperation) Wait() error { <-op.chanDone return op.err } func (op *lxcContainerOperation) Done(err error) { lxcContainerOperationsLock.Lock() defer lxcContainerOperationsLock.Unlock() // Check if already done runningOp, ok := lxcContainerOperations[op.id] if !ok || runningOp != op { return } op.err = err close(op.chanDone) delete(lxcContainerOperations, op.id) } var lxcContainerOperationsLock sync.Mutex var lxcContainerOperations map[int]*lxcContainerOperation = make(map[int]*lxcContainerOperation) // Helper functions func lxcSetConfigItem(c *lxc.Container, key string, value string) error { if c == nil { return fmt.Errorf("Uninitialized go-lxc struct") } if !lxc.VersionAtLeast(2, 1, 0) { switch key { case "lxc.uts.name": key = "lxc.utsname" case "lxc.pty.max": key = "lxc.pts" case "lxc.tty.dir": key = "lxc.devttydir" case "lxc.tty.max": key = "lxc.tty" case "lxc.apparmor.profile": key = "lxc.aa_profile" case "lxc.apparmor.allow_incomplete": key = "lxc.aa_allow_incomplete" case "lxc.selinux.context": key = "lxc.se_context" case "lxc.mount.fstab": key = "lxc.mount" case "lxc.console.path": key = "lxc.console" case "lxc.seccomp.profile": key = "lxc.seccomp" case "lxc.signal.halt": key = "lxc.haltsignal" case "lxc.signal.reboot": key = "lxc.rebootsignal" case "lxc.signal.stop": key = "lxc.stopsignal" case "lxc.log.syslog": key = "lxc.syslog" case "lxc.log.level": key = "lxc.loglevel" case "lxc.log.file": key = "lxc.logfile" case "lxc.init.cmd": key = "lxc.init_cmd" case "lxc.init.uid": key = "lxc.init_uid" case "lxc.init.gid": key = "lxc.init_gid" case "lxc.idmap": key = "lxc.id_map" } } err := c.SetConfigItem(key, value) if err != nil { return fmt.Errorf("Failed to set LXC config: %s=%s", key, value) } return nil } func lxcValidConfig(rawLxc string) error { for _, line := range strings.Split(rawLxc, "\n") { // Ignore empty lines if len(line) == 0 { continue } // Skip whitespace {"\t", " "} line = strings.TrimLeft(line, "\t ") // Ignore comments if strings.HasPrefix(line, "#") { continue } // Ensure the format is valid membs := strings.SplitN(line, "=", 2) if len(membs) != 2 { return fmt.Errorf("Invalid raw.lxc line: %s", line) } key := strings.ToLower(strings.Trim(membs[0], " \t")) // Blacklist some keys if key == "lxc.logfile" || key == "lxc.log.file" { return fmt.Errorf("Setting lxc.logfile is not allowed") } if key == "lxc.syslog" || key == "lxc.log.syslog" { return fmt.Errorf("Setting lxc.syslog is not allowed") } if key == "lxc.ephemeral" { return fmt.Errorf("Setting lxc.ephemeral is not allowed") } networkKeyPrefix := "lxc.net." if !lxc.VersionAtLeast(2, 1, 0) { networkKeyPrefix = "lxc.network." } if strings.HasPrefix(key, networkKeyPrefix) { fields := strings.Split(key, ".") allowedIPKeys := []string{"ipv4.address", "ipv6.address"} if !lxc.VersionAtLeast(2, 1, 0) { allowedIPKeys = []string{"ipv4", "ipv6"} } if len(fields) == 4 && shared.StringInSlice(fields[3], allowedIPKeys) { continue } if len(fields) == 5 && shared.StringInSlice(fields[3], allowedIPKeys) && fields[4] == "gateway" { continue } return fmt.Errorf("Only interface-specific ipv4/ipv6 %s keys are allowed", networkKeyPrefix) } } return nil } func lxcStatusCode(state lxc.State) api.StatusCode { return map[int]api.StatusCode{ 1: api.Stopped, 2: api.Starting, 3: api.Running, 4: api.Stopping, 5: api.Aborting, 6: api.Freezing, 7: api.Frozen, 8: api.Thawed, 9: api.Error, }[int(state)] } // Loader functions func containerLXCCreate(s *state.State, storage storage, args db.ContainerArgs) (container, error) { // Create the container struct c := &containerLXC{ state: s, id: args.Id, name: args.Name, ephemeral: args.Ephemeral, architecture: args.Architecture, cType: args.Ctype, stateful: args.Stateful, creationDate: args.CreationDate, profiles: args.Profiles, localConfig: args.Config, localDevices: args.Devices, } ctxMap := log.Ctx{"name": c.name, "ephemeral": c.ephemeral} logger.Info("Creating container", ctxMap) // No need to detect storage here, its a new container. c.storage = storage // Load the config err := c.init() if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } // Look for a rootfs entry _, _, err = containerGetRootDiskDevice(c.expandedDevices) if err != nil { deviceName := "root" for { if c.expandedDevices[deviceName] == nil { break } deviceName += "_" } c.localDevices[deviceName] = types.Device{"type": "disk", "path": "/"} updateArgs := db.ContainerArgs{ Architecture: c.architecture, Config: c.localConfig, Devices: c.localDevices, Ephemeral: c.ephemeral, Profiles: c.profiles, } err = c.Update(updateArgs, false) if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } } // Validate expanded config err = containerValidConfig(s.OS, c.expandedConfig, false, true) if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } err = containerValidDevices(c.expandedDevices, false, true) if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } // Setup initial idmap config var idmap *idmap.IdmapSet base := int64(0) if !c.IsPrivileged() { idmap, base, err = findIdmap( s, storage, args.Name, c.expandedConfig["security.idmap.isolated"], c.expandedConfig["security.idmap.base"], c.expandedConfig["security.idmap.size"], c.expandedConfig["raw.idmap"], ) if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } } var jsonIdmap string if idmap != nil { idmapBytes, err := json.Marshal(idmap.Idmap) if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } jsonIdmap = string(idmapBytes) } else { jsonIdmap = "[]" } err = c.ConfigKeySet("volatile.idmap.next", jsonIdmap) if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } err = c.ConfigKeySet("volatile.idmap.base", fmt.Sprintf("%v", base)) if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } // Invalid idmap cache c.idmapset = nil // Set last_state to the map we have on disk if c.localConfig["volatile.last_state.idmap"] == "" { err = c.ConfigKeySet("volatile.last_state.idmap", jsonIdmap) if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } } // Re-run init to update the idmap err = c.init() if err != nil { c.Delete() logger.Error("Failed creating container", ctxMap) return nil, err } logger.Info("Created container", ctxMap) return c, nil } func containerLXCLoad(s *state.State, storage storage, args db.ContainerArgs) (container, error) { // Create the container struct c := &containerLXC{ state: s, id: args.Id, name: args.Name, ephemeral: args.Ephemeral, architecture: args.Architecture, cType: args.Ctype, creationDate: args.CreationDate, profiles: args.Profiles, localConfig: args.Config, localDevices: args.Devices, stateful: args.Stateful} // Detect the storage backend storage, err := storageForFilename(s, storage, shared.VarPath("containers", strings.Split(c.name, "/")[0])) if err != nil { return nil, err } c.storage = storage // Load the config err = c.init() if err != nil { return nil, err } return c, nil } // The LXC container driver type containerLXC struct { // Properties architecture int cType db.ContainerType creationDate time.Time ephemeral bool id int name string stateful bool // Config expandedConfig map[string]string expandedDevices types.Devices fromHook bool localConfig map[string]string localDevices types.Devices profiles []string // Cache c *lxc.Container state *state.State idmapset *idmap.IdmapSet storage storage } func (c *containerLXC) createOperation(action string, reusable bool, reuse bool) (*lxcContainerOperation, error) { op, _ := c.getOperation("") if op != nil { if reuse && op.reusable { op.Reset() return op, nil } return nil, fmt.Errorf("Container is busy running a %s operation", op.action) } lxcContainerOperationsLock.Lock() defer lxcContainerOperationsLock.Unlock() op = &lxcContainerOperation{} op.Create(c.id, action, reusable) lxcContainerOperations[c.id] = op return lxcContainerOperations[c.id], nil } func (c *containerLXC) getOperation(action string) (*lxcContainerOperation, error) { lxcContainerOperationsLock.Lock() defer lxcContainerOperationsLock.Unlock() op := lxcContainerOperations[c.id] if op == nil { return nil, fmt.Errorf("No running %s container operation", action) } if action != "" && op.action != action { return nil, fmt.Errorf("Container is running a %s operation, not a %s operation", op.action, action) } return op, nil } func (c *containerLXC) waitOperation() error { op, _ := c.getOperation("") if op != nil { err := op.Wait() if err != nil { return err } } return nil } func idmapSize(state *state.State, isolatedStr string, size string) (int64, error) { isolated := false if shared.IsTrue(isolatedStr) { isolated = true } var idMapSize int64 if size == "" || size == "auto" { if isolated { idMapSize = 65536 } else { if len(state.OS.IdmapSet.Idmap) != 2 { return 0, fmt.Errorf("bad initial idmap: %v", state.OS.IdmapSet) } idMapSize = state.OS.IdmapSet.Idmap[0].Maprange } } else { size, err := strconv.ParseInt(size, 10, 64) if err != nil { return 0, err } idMapSize = size } return idMapSize, nil } var idmapLock sync.Mutex func parseRawIdmap(value string) ([]idmap.IdmapEntry, error) { getRange := func(r string) (int64, int64, error) { entries := strings.Split(r, "-") if len(entries) > 2 { return -1, -1, fmt.Errorf("invalid raw.idmap range %s", r) } base, err := strconv.ParseInt(entries[0], 10, 64) if err != nil { return -1, -1, err } size := int64(1) if len(entries) > 1 { size, err = strconv.ParseInt(entries[1], 10, 64) if err != nil { return -1, -1, err } size -= base size += 1 } return base, size, nil } ret := idmap.IdmapSet{} for _, line := range strings.Split(value, "\n") { if line == "" { continue } entries := strings.Split(line, " ") if len(entries) != 3 { return nil, fmt.Errorf("invalid raw.idmap line %s", line) } outsideBase, outsideSize, err := getRange(entries[1]) if err != nil { return nil, err } insideBase, insideSize, err := getRange(entries[2]) if err != nil { return nil, err } if insideSize != outsideSize { return nil, fmt.Errorf("idmap ranges of different sizes %s", line) } entry := idmap.IdmapEntry{ Hostid: outsideBase, Nsid: insideBase, Maprange: insideSize, } switch entries[0] { case "both": entry.Isuid = true entry.Isgid = true err := ret.AddSafe(entry) if err != nil { return nil, err } case "uid": entry.Isuid = true err := ret.AddSafe(entry) if err != nil { return nil, err } case "gid": entry.Isgid = true err := ret.AddSafe(entry) if err != nil { return nil, err } default: return nil, fmt.Errorf("invalid raw.idmap type %s", line) } } return ret.Idmap, nil } func findIdmap(state *state.State, storage storage, cName string, isolatedStr string, configBase string, configSize string, rawIdmap string) (*idmap.IdmapSet, int64, error) { isolated := false if shared.IsTrue(isolatedStr) { isolated = true } rawMaps, err := parseRawIdmap(rawIdmap) if err != nil { return nil, 0, err } if !isolated { newIdmapset := idmap.IdmapSet{Idmap: make([]idmap.IdmapEntry, len(state.OS.IdmapSet.Idmap))} copy(newIdmapset.Idmap, state.OS.IdmapSet.Idmap) for _, ent := range rawMaps { err := newIdmapset.AddSafe(ent) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } } return &newIdmapset, 0, nil } size, err := idmapSize(state, isolatedStr, configSize) if err != nil { return nil, 0, err } mkIdmap := func(offset int64, size int64) (*idmap.IdmapSet, error) { set := &idmap.IdmapSet{Idmap: []idmap.IdmapEntry{ {Isuid: true, Nsid: 0, Hostid: offset, Maprange: size}, {Isgid: true, Nsid: 0, Hostid: offset, Maprange: size}, }} for _, ent := range rawMaps { err := set.AddSafe(ent) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, err } } return set, nil } if configBase != "" { offset, err := strconv.ParseInt(configBase, 10, 64) if err != nil { return nil, 0, err } set, err := mkIdmap(offset, size) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } return set, offset, nil } idmapLock.Lock() defer idmapLock.Unlock() cs, err := db.ContainersList(state.DB, db.CTypeRegular) if err != nil { return nil, 0, err } offset := state.OS.IdmapSet.Idmap[0].Hostid + 65536 mapentries := idmap.ByHostid{} for _, name := range cs { /* Don't change our map Just Because. */ if name == cName { continue } container, err := containerLoadByName(state, storage, name) if err != nil { return nil, 0, err } if container.IsPrivileged() { continue } if !shared.IsTrue(container.ExpandedConfig()["security.idmap.isolated"]) { continue } cBase := int64(0) if container.ExpandedConfig()["volatile.idmap.base"] != "" { cBase, err = strconv.ParseInt(container.ExpandedConfig()["volatile.idmap.base"], 10, 64) if err != nil { return nil, 0, err } } cSize, err := idmapSize(state, container.ExpandedConfig()["security.idmap.isolated"], container.ExpandedConfig()["security.idmap.size"]) if err != nil { return nil, 0, err } mapentries = append(mapentries, &idmap.IdmapEntry{Hostid: int64(cBase), Maprange: cSize}) } sort.Sort(mapentries) for i := range mapentries { if i == 0 { if mapentries[0].Hostid < offset+size { offset = mapentries[0].Hostid + mapentries[0].Maprange continue } set, err := mkIdmap(offset, size) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } return set, offset, nil } if mapentries[i-1].Hostid+mapentries[i-1].Maprange > offset { offset = mapentries[i-1].Hostid + mapentries[i-1].Maprange continue } offset = mapentries[i-1].Hostid + mapentries[i-1].Maprange if offset+size < mapentries[i].Hostid { set, err := mkIdmap(offset, size) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } return set, offset, nil } offset = mapentries[i].Hostid + mapentries[i].Maprange } if offset+size < state.OS.IdmapSet.Idmap[0].Hostid+state.OS.IdmapSet.Idmap[0].Maprange { set, err := mkIdmap(offset, size) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } return set, offset, nil } return nil, 0, fmt.Errorf("Not enough uid/gid available for the container.") } func (c *containerLXC) init() error { // Compute the expanded config and device list err := c.expandConfig() if err != nil { return err } err = c.expandDevices() if err != nil { return err } return nil } func (c *containerLXC) initLXC() error { // No need to go through all that for snapshots if c.IsSnapshot() { return nil } // Check if being called from a hook if c.fromHook { return fmt.Errorf("You can't use go-lxc from inside a LXC hook.") } // Check if already initialized if c.c != nil { return nil } // Load the go-lxc struct cc, err := lxc.NewContainer(c.Name(), c.state.OS.LxcPath) if err != nil { return err } // Base config toDrop := "sys_time sys_module sys_rawio" if !aaStacking || aaStacked { toDrop = toDrop + " mac_admin mac_override" } err = lxcSetConfigItem(cc, "lxc.cap.drop", toDrop) if err != nil { return err } // Set an appropriate /proc, /sys/ and /sys/fs/cgroup mounts := []string{} if c.IsPrivileged() && !runningInUserns { mounts = append(mounts, "proc:mixed") mounts = append(mounts, "sys:mixed") } else { mounts = append(mounts, "proc:rw") mounts = append(mounts, "sys:rw") } if !shared.PathExists("/proc/self/ns/cgroup") { mounts = append(mounts, "cgroup:mixed") } err = lxcSetConfigItem(cc, "lxc.mount.auto", strings.Join(mounts, " ")) if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.autodev", "1") if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.pty.max", "1024") if err != nil { return err } bindMounts := []string{ "/dev/fuse", "/dev/net/tun", "/proc/sys/fs/binfmt_misc", "/sys/firmware/efi/efivars", "/sys/fs/fuse/connections", "/sys/fs/pstore", "/sys/kernel/debug", "/sys/kernel/security"} if c.IsPrivileged() && !runningInUserns { err = lxcSetConfigItem(cc, "lxc.mount.entry", "mqueue dev/mqueue mqueue rw,relatime,create=dir,optional") if err != nil { return err } } else { bindMounts = append(bindMounts, "/dev/mqueue") } for _, mnt := range bindMounts { if !shared.PathExists(mnt) { continue } if shared.IsDir(mnt) { err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none rbind,create=dir,optional", mnt, strings.TrimPrefix(mnt, "/"))) if err != nil { return err } } else { err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none bind,create=file,optional", mnt, strings.TrimPrefix(mnt, "/"))) if err != nil { return err } } } // For lxcfs templateConfDir := os.Getenv("LXD_LXC_TEMPLATE_CONFIG") if templateConfDir == "" { templateConfDir = "/usr/share/lxc/config" } if shared.PathExists(fmt.Sprintf("%s/common.conf.d/", templateConfDir)) { err = lxcSetConfigItem(cc, "lxc.include", fmt.Sprintf("%s/common.conf.d/", templateConfDir)) if err != nil { return err } } // Configure devices cgroup if c.IsPrivileged() && !runningInUserns && cgDevicesController { err = lxcSetConfigItem(cc, "lxc.cgroup.devices.deny", "a") if err != nil { return err } devices := []string{ "b *:* m", // Allow mknod of block devices "c *:* m", // Allow mknod of char devices "c 136:* rwm", // /dev/pts devices "c 1:3 rwm", // /dev/null "c 1:5 rwm", // /dev/zero "c 1:7 rwm", // /dev/full "c 1:8 rwm", // /dev/random "c 1:9 rwm", // /dev/urandom "c 5:0 rwm", // /dev/tty "c 5:1 rwm", // /dev/console "c 5:2 rwm", // /dev/ptmx "c 10:229 rwm", // /dev/fuse "c 10:200 rwm", // /dev/net/tun } for _, dev := range devices { err = lxcSetConfigItem(cc, "lxc.cgroup.devices.allow", dev) if err != nil { return err } } } if c.IsNesting() { /* * mount extra /proc and /sys to work around kernel * restrictions on remounting them when covered */ err = lxcSetConfigItem(cc, "lxc.mount.entry", "proc dev/.lxc/proc proc create=dir,optional") if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.mount.entry", "sys dev/.lxc/sys sysfs create=dir,optional") if err != nil { return err } } // Setup logging logfile := c.LogFilePath() err = cc.SetLogFile(logfile) if err != nil { return err } logLevel := "warn" if debug { logLevel = "trace" } else if verbose { logLevel = "info" } err = lxcSetConfigItem(cc, "lxc.log.level", logLevel) if err != nil { return err } // Setup architecture personality, err := osarch.ArchitecturePersonality(c.architecture) if err != nil { personality, err = osarch.ArchitecturePersonality(c.state.OS.Architectures[0]) if err != nil { return err } } err = lxcSetConfigItem(cc, "lxc.arch", personality) if err != nil { return err } // Setup the hooks err = lxcSetConfigItem(cc, "lxc.hook.pre-start", fmt.Sprintf("%s callhook %s %d start", execPath, shared.VarPath(""), c.id)) if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.hook.post-stop", fmt.Sprintf("%s callhook %s %d stop", execPath, shared.VarPath(""), c.id)) if err != nil { return err } // Setup the console err = lxcSetConfigItem(cc, "lxc.tty.max", "0") if err != nil { return err } // Setup the hostname err = lxcSetConfigItem(cc, "lxc.uts.name", c.Name()) if err != nil { return err } // Setup devlxd err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/lxd none bind,create=dir 0 0", shared.VarPath("devlxd"))) if err != nil { return err } // Setup AppArmor if aaAvailable { if aaConfined || !aaAdmin { // If confined but otherwise able to use AppArmor, use our own profile curProfile := aaProfile() curProfile = strings.TrimSuffix(curProfile, " (enforce)") err := lxcSetConfigItem(cc, "lxc.apparmor.profile", curProfile) if err != nil { return err } } else { // If not currently confined, use the container's profile profile := AAProfileFull(c) /* In the nesting case, we want to enable the inside * LXD to load its profile. Unprivileged containers can * load profiles, but privileged containers cannot, so * let's not use a namespace so they can fall back to * the old way of nesting, i.e. using the parent's * profile. */ if aaStacking && !aaStacked { profile = fmt.Sprintf("%s//&:%s:", profile, AANamespace(c)) } err := lxcSetConfigItem(cc, "lxc.apparmor.profile", profile) if err != nil { return err } } } // Setup Seccomp err = lxcSetConfigItem(cc, "lxc.seccomp.profile", SeccompProfilePath(c)) if err != nil { return err } // Setup idmap idmapset, err := c.IdmapSet() if err != nil { return err } if idmapset != nil { lines := idmapset.ToLxcString() for _, line := range lines { err := lxcSetConfigItem(cc, "lxc.idmap", strings.TrimSuffix(line, "\n")) if err != nil { return err } } } // Setup environment for k, v := range c.expandedConfig { if strings.HasPrefix(k, "environment.") { err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("%s=%s", strings.TrimPrefix(k, "environment."), v)) if err != nil { return err } } } // Memory limits if cgMemoryController { memory := c.expandedConfig["limits.memory"] memoryEnforce := c.expandedConfig["limits.memory.enforce"] memorySwap := c.expandedConfig["limits.memory.swap"] memorySwapPriority := c.expandedConfig["limits.memory.swap.priority"] // Configure the memory limits if memory != "" { var valueInt int64 if strings.HasSuffix(memory, "%") { percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64) if err != nil { return err } memoryTotal, err := deviceTotalMemory() if err != nil { return err } valueInt = int64((memoryTotal / 100) * percent) } else { valueInt, err = shared.ParseByteSizeString(memory) if err != nil { return err } } if memoryEnforce == "soft" { err = lxcSetConfigItem(cc, "lxc.cgroup.memory.soft_limit_in_bytes", fmt.Sprintf("%d", valueInt)) if err != nil { return err } } else { if cgSwapAccounting && (memorySwap == "" || shared.IsTrue(memorySwap)) { err = lxcSetConfigItem(cc, "lxc.cgroup.memory.limit_in_bytes", fmt.Sprintf("%d", valueInt)) if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.cgroup.memory.memsw.limit_in_bytes", fmt.Sprintf("%d", valueInt)) if err != nil { return err } } else { err = lxcSetConfigItem(cc, "lxc.cgroup.memory.limit_in_bytes", fmt.Sprintf("%d", valueInt)) if err != nil { return err } } // Set soft limit to value 10% less than hard limit err = lxcSetConfigItem(cc, "lxc.cgroup.memory.soft_limit_in_bytes", fmt.Sprintf("%.0f", float64(valueInt)*0.9)) if err != nil { return err } } } // Configure the swappiness if memorySwap != "" && !shared.IsTrue(memorySwap) { err = lxcSetConfigItem(cc, "lxc.cgroup.memory.swappiness", "0") if err != nil { return err } } else if memorySwapPriority != "" { priority, err := strconv.Atoi(memorySwapPriority) if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.cgroup.memory.swappiness", fmt.Sprintf("%d", 60-10+priority)) if err != nil { return err } } } // CPU limits cpuPriority := c.expandedConfig["limits.cpu.priority"] cpuAllowance := c.expandedConfig["limits.cpu.allowance"] if (cpuPriority != "" || cpuAllowance != "") && cgCpuController { cpuShares, cpuCfsQuota, cpuCfsPeriod, err := deviceParseCPU(cpuAllowance, cpuPriority) if err != nil { return err } if cpuShares != "1024" { err = lxcSetConfigItem(cc, "lxc.cgroup.cpu.shares", cpuShares) if err != nil { return err } } if cpuCfsPeriod != "-1" { err = lxcSetConfigItem(cc, "lxc.cgroup.cpu.cfs_period_us", cpuCfsPeriod) if err != nil { return err } } if cpuCfsQuota != "-1" { err = lxcSetConfigItem(cc, "lxc.cgroup.cpu.cfs_quota_us", cpuCfsQuota) if err != nil { return err } } } // Disk limits if cgBlkioController { diskPriority := c.expandedConfig["limits.disk.priority"] if diskPriority != "" { priorityInt, err := strconv.Atoi(diskPriority) if err != nil { return err } // Minimum valid value is 10 priority := priorityInt * 100 if priority == 0 { priority = 10 } err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.weight", fmt.Sprintf("%d", priority)) if err != nil { return err } } hasDiskLimits := false for _, name := range c.expandedDevices.DeviceNames() { m := c.expandedDevices[name] if m["type"] != "disk" { continue } if m["limits.read"] != "" || m["limits.write"] != "" || m["limits.max"] != "" { hasDiskLimits = true break } } if hasDiskLimits { diskLimits, err := c.getDiskLimits() if err != nil { return err } for block, limit := range diskLimits { if limit.readBps > 0 { err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.throttle.read_bps_device", fmt.Sprintf("%s %d", block, limit.readBps)) if err != nil { return err } } if limit.readIops > 0 { err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.throttle.read_iops_device", fmt.Sprintf("%s %d", block, limit.readIops)) if err != nil { return err } } if limit.writeBps > 0 { err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.throttle.write_bps_device", fmt.Sprintf("%s %d", block, limit.writeBps)) if err != nil { return err } } if limit.writeIops > 0 { err = lxcSetConfigItem(cc, "lxc.cgroup.blkio.throttle.write_iops_device", fmt.Sprintf("%s %d", block, limit.writeIops)) if err != nil { return err } } } } } // Processes if cgPidsController { processes := c.expandedConfig["limits.processes"] if processes != "" { valueInt, err := strconv.ParseInt(processes, 10, 64) if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.cgroup.pids.max", fmt.Sprintf("%d", valueInt)) if err != nil { return err } } } // Setup devices networkidx := 0 for _, k := range c.expandedDevices.DeviceNames() { m := c.expandedDevices[k] if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) { // Prepare all the paths srcPath := m["path"] tgtPath := strings.TrimPrefix(srcPath, "/") devName := fmt.Sprintf("unix.%s", strings.Replace(tgtPath, "/", "-", -1)) devPath := filepath.Join(c.DevicesPath(), devName) // Set the bind-mount entry err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none bind,create=file", devPath, tgtPath)) if err != nil { return err } } else if m["type"] == "nic" { // Fill in some fields from volatile m, err = c.fillNetworkDevice(k, m) if err != nil { return err } networkKeyPrefix := "lxc.net" if !lxc.VersionAtLeast(2, 1, 0) { networkKeyPrefix = "lxc.network" } // Interface type specific configuration if shared.StringInSlice(m["nictype"], []string{"bridged", "p2p"}) { err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.type", networkKeyPrefix, networkidx), "veth") if err != nil { return err } } else if m["nictype"] == "physical" { err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.type", networkKeyPrefix, networkidx), "phys") if err != nil { return err } } else if m["nictype"] == "macvlan" { err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.type", networkKeyPrefix, networkidx), "macvlan") if err != nil { return err } err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.macvlan.mode", networkKeyPrefix, networkidx), "bridge") if err != nil { return err } } err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.flags", networkKeyPrefix, networkidx), "up") if err != nil { return err } if shared.StringInSlice(m["nictype"], []string{"bridged", "physical", "macvlan"}) { err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.link", networkKeyPrefix, networkidx), m["parent"]) if err != nil { return err } } // Host Virtual NIC name if m["host_name"] != "" { err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.veth.pair", networkKeyPrefix, networkidx), m["host_name"]) if err != nil { return err } } // MAC address if m["hwaddr"] != "" { err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.hwaddr", networkKeyPrefix, networkidx), m["hwaddr"]) if err != nil { return err } } // MTU if m["mtu"] != "" { err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.mtu", networkKeyPrefix, networkidx), m["mtu"]) if err != nil { return err } } // Name if m["name"] != "" { err = lxcSetConfigItem(cc, fmt.Sprintf("%s.%d.name", networkKeyPrefix, networkidx), m["name"]) if err != nil { return err } } // bump network index networkidx++ } else if m["type"] == "disk" { // Prepare all the paths srcPath := shared.HostPath(m["source"]) tgtPath := strings.TrimPrefix(m["path"], "/") devName := fmt.Sprintf("disk.%s", strings.Replace(tgtPath, "/", "-", -1)) devPath := filepath.Join(c.DevicesPath(), devName) // Various option checks isOptional := shared.IsTrue(m["optional"]) isReadOnly := shared.IsTrue(m["readonly"]) isRecursive := shared.IsTrue(m["recursive"]) isFile := !shared.IsDir(srcPath) && !deviceIsBlockdev(srcPath) // Deal with a rootfs if tgtPath == "" { if !lxc.VersionAtLeast(2, 1, 0) { // Set the rootfs backend type if supported (must happen before any other lxc.rootfs) err := lxcSetConfigItem(cc, "lxc.rootfs.backend", "dir") if err == nil { value := cc.ConfigItem("lxc.rootfs.backend") if len(value) == 0 || value[0] != "dir" { lxcSetConfigItem(cc, "lxc.rootfs.backend", "") } } } // Set the rootfs path if lxc.VersionAtLeast(2, 1, 0) { rootfsPath := fmt.Sprintf("dir:%s", c.RootfsPath()) err = lxcSetConfigItem(cc, "lxc.rootfs.path", rootfsPath) } else { rootfsPath := c.RootfsPath() err = lxcSetConfigItem(cc, "lxc.rootfs", rootfsPath) } if err != nil { return err } // Read-only rootfs (unlikely to work very well) if isReadOnly { err = lxcSetConfigItem(cc, "lxc.rootfs.options", "ro") if err != nil { return err } } } else { rbind := "" options := []string{} if isReadOnly { options = append(options, "ro") } if isOptional { options = append(options, "optional") } if isRecursive { rbind = "r" } if isFile { options = append(options, "create=file") } else { options = append(options, "create=dir") } err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none %sbind,%s", devPath, tgtPath, rbind, strings.Join(options, ","))) if err != nil { return err } } } } // Setup shmounts err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/.lxd-mounts none bind,create=dir 0 0", shared.VarPath("shmounts", c.Name()))) if err != nil { return err } // Apply raw.lxc if lxcConfig, ok := c.expandedConfig["raw.lxc"]; ok { f, err := ioutil.TempFile("", "lxd_config_") if err != nil { return err } err = shared.WriteAll(f, []byte(lxcConfig)) f.Close() defer os.Remove(f.Name()) if err != nil { return err } if err := cc.LoadConfigFile(f.Name()); err != nil { return fmt.Errorf("Failed to load raw.lxc") } } c.c = cc return nil } // Config handling func (c *containerLXC) expandConfig() error { config := map[string]string{} // Apply all the profiles for _, name := range c.profiles { profileConfig, err := db.ProfileConfig(c.state.DB, name) if err != nil { return err } for k, v := range profileConfig { config[k] = v } } // Stick the local config on top for k, v := range c.localConfig { config[k] = v } c.expandedConfig = config return nil } func (c *containerLXC) expandDevices() error { devices := types.Devices{} // Apply all the profiles for _, p := range c.profiles { profileDevices, err := db.Devices(c.state.DB, p, true) if err != nil { return err } for k, v := range profileDevices { devices[k] = v } } // Stick local devices on top for k, v := range c.localDevices { devices[k] = v } c.expandedDevices = devices return nil } // Start functions func (c *containerLXC) startCommon() (string, error) { // Load the go-lxc struct err := c.initLXC() if err != nil { return "", err } // Check that we're not already running if c.IsRunning() { return "", fmt.Errorf("The container is already running") } // Sanity checks for devices for _, name := range c.expandedDevices.DeviceNames() { m := c.expandedDevices[name] switch m["type"] { case "disk": if m["source"] != "" && !shared.PathExists(shared.HostPath(m["source"])) { return "", fmt.Errorf("Missing source '%s' for disk '%s'", m["source"], name) } case "nic": if m["parent"] != "" && !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", m["parent"])) { return "", fmt.Errorf("Missing parent '%s' for nic '%s'", m["parent"], name) } case "unix-char", "unix-block": if m["path"] != "" && m["major"] == "" && m["minor"] == "" && !shared.PathExists(m["path"]) { return "", fmt.Errorf("Missing source '%s' for device '%s'", m["path"], name) } } } // Load any required kernel modules kernelModules := c.expandedConfig["linux.kernel_modules"] if kernelModules != "" { for _, module := range strings.Split(kernelModules, ",") { module = strings.TrimPrefix(module, " ") err := util.LoadModule(module) if err != nil { return "", fmt.Errorf("Failed to load kernel module '%s': %s", module, err) } } } /* Deal with idmap changes */ idmap, err := c.IdmapSet() if err != nil { return "", err } lastIdmap, err := c.LastIdmapSet() if err != nil { return "", err } var jsonIdmap string if idmap != nil { idmapBytes, err := json.Marshal(idmap.Idmap) if err != nil { return "", err } jsonIdmap = string(idmapBytes) } else { jsonIdmap = "[]" } if !reflect.DeepEqual(idmap, lastIdmap) { logger.Debugf("Container idmap changed, remapping") err := c.StorageStart() if err != nil { return "", err } if lastIdmap != nil { err = lastIdmap.UnshiftRootfs(c.RootfsPath()) if err != nil { c.StorageStop() return "", err } } if idmap != nil { err = idmap.ShiftRootfs(c.RootfsPath()) if err != nil { c.StorageStop() return "", err } } var mode os.FileMode var uid int64 var gid int64 if c.IsPrivileged() { mode = 0700 } else { mode = 0755 if idmap != nil { uid, gid = idmap.ShiftIntoNs(0, 0) } } err = os.Chmod(c.Path(), mode) if err != nil { return "", err } err = os.Chown(c.Path(), int(uid), int(gid)) if err != nil { return "", err } err = c.StorageStop() if err != nil { return "", err } } err = c.ConfigKeySet("volatile.last_state.idmap", jsonIdmap) if err != nil { return "", err } // Generate the Seccomp profile if err := SeccompCreateProfile(c); err != nil { return "", err } // Cleanup any existing leftover devices c.removeUnixDevices() c.removeDiskDevices() diskDevices := map[string]types.Device{} // Create the devices for _, k := range c.expandedDevices.DeviceNames() { m := c.expandedDevices[k] if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) { // Unix device devPath, err := c.createUnixDevice(m) if err != nil { return "", err } if c.IsPrivileged() && !runningInUserns && cgDevicesController { // Add the new device cgroup rule dType, dMajor, dMinor, err := deviceGetAttributes(devPath) if err != nil { return "", err } err = lxcSetConfigItem(c.c, "lxc.cgroup.devices.allow", fmt.Sprintf("%s %d:%d rwm", dType, dMajor, dMinor)) if err != nil { return "", fmt.Errorf("Failed to add cgroup rule for device") } } } else if m["type"] == "disk" { if m["path"] != "/" { diskDevices[k] = m } } } err = c.addDiskDevices(diskDevices, func(name string, d types.Device) error { _, err := c.createDiskDevice(name, d) return err }) if err != nil { return "", err } // Create any missing directory err = os.MkdirAll(c.LogPath(), 0700) if err != nil { return "", err } err = os.MkdirAll(shared.VarPath("devices", c.Name()), 0711) if err != nil { return "", err } err = os.MkdirAll(shared.VarPath("shmounts", c.Name()), 0711) if err != nil { return "", err } // Rotate the log file logfile := c.LogFilePath() if shared.PathExists(logfile) { os.Remove(logfile + ".old") err := os.Rename(logfile, logfile+".old") if err != nil { return "", err } } // Generate the LXC config configPath := filepath.Join(c.LogPath(), "lxc.conf") err = c.c.SaveConfigFile(configPath) if err != nil { os.Remove(configPath) return "", err } return configPath, nil } func (c *containerLXC) Start(stateful bool) error { var ctxMap log.Ctx // Setup a new operation op, err := c.createOperation("start", false, false) if err != nil { return err } defer op.Done(nil) err = setupSharedMounts() if err != nil { return fmt.Errorf("Daemon failed to setup shared mounts base: %s.\nDoes security.nesting need to be turned on?", err) } // Run the shared start code configPath, err := c.startCommon() if err != nil { return err } ctxMap = log.Ctx{"name": c.name, "action": op.action, "creation date": c.creationDate, "ephemeral": c.ephemeral, "stateful": stateful} logger.Info("Starting container", ctxMap) // If stateful, restore now if stateful { if !c.stateful { return fmt.Errorf("Container has no existing state to restore.") } err := c.Migrate(lxc.MIGRATE_RESTORE, c.StatePath(), "snapshot", false, false) if err != nil && !c.IsRunning() { return err } os.RemoveAll(c.StatePath()) c.stateful = false err = db.ContainerSetStateful(c.state.DB, c.id, false) if err != nil { logger.Error("Failed starting container", ctxMap) return err } logger.Info("Started container", ctxMap) return err } else if c.stateful { /* stateless start required when we have state, let's delete it */ err := os.RemoveAll(c.StatePath()) if err != nil { return err } c.stateful = false err = db.ContainerSetStateful(c.state.DB, c.id, false) if err != nil { return err } } // Start the LXC container out, err := shared.RunCommand( execPath, "forkstart", c.name, c.state.OS.LxcPath, configPath) // Capture debug output if string(out) != "" { for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { logger.Debugf("forkstart: %s", line) } } if err != nil && !c.IsRunning() { // Attempt to extract the LXC errors lxcLog := "" logPath := filepath.Join(c.LogPath(), "lxc.log") if shared.PathExists(logPath) { logContent, err := ioutil.ReadFile(logPath) if err == nil { for _, line := range strings.Split(string(logContent), "\n") { fields := strings.Fields(line) if len(fields) < 4 { continue } // We only care about errors if fields[2] != "ERROR" { continue } // Prepend the line break if len(lxcLog) == 0 { lxcLog += "\n" } lxcLog += fmt.Sprintf(" %s\n", strings.Join(fields[0:], " ")) } } } logger.Error("Failed starting container", ctxMap) // Return the actual error return fmt.Errorf( "Error calling 'lxd forkstart %s %s %s': err='%v'%s", c.name, c.state.OS.LxcPath, filepath.Join(c.LogPath(), "lxc.conf"), err, lxcLog) } logger.Info("Started container", ctxMap) return nil } func (c *containerLXC) OnStart() error { // Make sure we can't call go-lxc functions by mistake c.fromHook = true // Start the storage for this container err := c.StorageStart() if err != nil { return err } // Load the container AppArmor profile err = AALoadProfile(c) if err != nil { c.StorageStop() return err } // Template anything that needs templating key := "volatile.apply_template" if c.localConfig[key] != "" { // Run any template that needs running err = c.templateApplyNow(c.localConfig[key]) if err != nil { AADestroy(c) c.StorageStop() return err } // Remove the volatile key from the DB err := db.ContainerConfigRemove(c.state.DB, c.id, key) if err != nil { AADestroy(c) c.StorageStop() return err } } err = c.templateApplyNow("start") if err != nil { AADestroy(c) c.StorageStop() return err } // Trigger a rebalance deviceTaskSchedulerTrigger("container", c.name, "started") // Apply network priority if c.expandedConfig["limits.network.priority"] != "" { go func(c *containerLXC) { c.fromHook = false err := c.setNetworkPriority() if err != nil { logger.Error("Failed to apply network priority", log.Ctx{"container": c.name, "err": err}) } }(c) } // Apply network limits for _, name := range c.expandedDevices.DeviceNames() { m := c.expandedDevices[name] if m["type"] != "nic" { continue } if m["limits.max"] == "" && m["limits.ingress"] == "" && m["limits.egress"] == "" { continue } go func(c *containerLXC, name string, m types.Device) { c.fromHook = false err = c.setNetworkLimits(name, m) if err != nil { logger.Error("Failed to apply network limits", log.Ctx{"container": c.name, "err": err}) } }(c, name, m) } // Record current state err = db.ContainerSetState(c.state.DB, c.id, "RUNNING") if err != nil { return err } return nil } // Stop functions func (c *containerLXC) Stop(stateful bool) error { var ctxMap log.Ctx // Check that we're not already stopped if !c.IsRunning() { return fmt.Errorf("The container is already stopped") } // Setup a new operation op, err := c.createOperation("stop", false, true) if err != nil { return err } ctxMap = log.Ctx{"name": c.name, "action": op.action, "creation date": c.creationDate, "ephemeral": c.ephemeral, "stateful": stateful} logger.Info("Stopping container", ctxMap) // Handle stateful stop if stateful { // Cleanup any existing state stateDir := c.StatePath() os.RemoveAll(stateDir) err := os.MkdirAll(stateDir, 0700) if err != nil { op.Done(err) logger.Error("Failed stopping container", ctxMap) return err } // Checkpoint err = c.Migrate(lxc.MIGRATE_DUMP, stateDir, "snapshot", true, false) if err != nil { op.Done(err) logger.Error("Failed stopping container", ctxMap) return err } c.stateful = true err = db.ContainerSetStateful(c.state.DB, c.id, true) if err != nil { op.Done(err) logger.Error("Failed stopping container", ctxMap) return err } op.Done(nil) logger.Info("Stopped container", ctxMap) return nil } // Load the go-lxc struct err = c.initLXC() if err != nil { op.Done(err) logger.Error("Failed stopping container", ctxMap) return err } // Attempt to freeze the container first, helps massively with fork bombs freezer := make(chan bool, 1) go func() { c.Freeze() freezer <- true }() select { case <-freezer: case <-time.After(time.Second * 5): c.Unfreeze() } if err := c.c.Stop(); err != nil { op.Done(err) logger.Error("Failed stopping container", ctxMap) return err } err = op.Wait() if err != nil && c.IsRunning() { logger.Error("Failed stopping container", ctxMap) return err } logger.Info("Stopped container", ctxMap) return nil } func (c *containerLXC) Shutdown(timeout time.Duration) error { var ctxMap log.Ctx // Check that we're not already stopped if !c.IsRunning() { return fmt.Errorf("The container is already stopped") } // Setup a new operation op, err := c.createOperation("stop", true, true) if err != nil { return err } ctxMap = log.Ctx{"name": c.name, "action": "shutdown", "creation date": c.creationDate, "ephemeral": c.ephemeral, "timeout": timeout} logger.Info("Shutting down container", ctxMap) // Load the go-lxc struct err = c.initLXC() if err != nil { op.Done(err) logger.Error("Failed shutting down container", ctxMap) return err } if err := c.c.Shutdown(timeout); err != nil { op.Done(err) logger.Error("Failed shutting down container", ctxMap) return err } err = op.Wait() if err != nil && c.IsRunning() { logger.Error("Failed shutting down container", ctxMap) return err } logger.Info("Shut down container", ctxMap) return nil } func (c *containerLXC) OnStop(target string) error { // Validate target if !shared.StringInSlice(target, []string{"stop", "reboot"}) { logger.Error("Container sent invalid target to OnStop", log.Ctx{"container": c.Name(), "target": target}) return fmt.Errorf("Invalid stop target: %s", target) } // Get operation op, _ := c.getOperation("") if op != nil && op.action != "stop" { return fmt.Errorf("Container is already running a %s operation", op.action) } // Make sure we can't call go-lxc functions by mistake c.fromHook = true // Stop the storage for this container err := c.StorageStop() if err != nil { if op != nil { op.Done(err) } return err } // Log user actions if op == nil { ctxMap := log.Ctx{"name": c.name, "action": target, "created": c.creationDate, "ephemeral": c.ephemeral, "stateful": false} logger.Info(fmt.Sprintf("Container initiated %s", target), ctxMap) } go func(c *containerLXC, target string, op *lxcContainerOperation) { c.fromHook = false err = nil // Unlock on return if op != nil { defer op.Done(err) } // Wait for other post-stop actions to be done c.IsRunning() // Unload the apparmor profile err = AADestroy(c) if err != nil { logger.Error("Failed to destroy apparmor namespace", log.Ctx{"container": c.Name(), "err": err}) } // Clean all the unix devices err = c.removeUnixDevices() if err != nil { logger.Error("Unable to remove unix devices", log.Ctx{"container": c.Name(), "err": err}) } // Clean all the disk devices err = c.removeDiskDevices() if err != nil { logger.Error("Unable to remove disk devices", log.Ctx{"container": c.Name(), "err": err}) } // Reboot the container if target == "reboot" { // Start the container again err = c.Start(false) return } // Trigger a rebalance deviceTaskSchedulerTrigger("container", c.name, "stopped") // Record current state err = db.ContainerSetState(c.state.DB, c.id, "STOPPED") if err != nil { logger.Error("Failed to set container state", log.Ctx{"container": c.Name(), "err": err}) } // Destroy ephemeral containers if c.ephemeral { err = c.Delete() } }(c, target, op) return nil } // Freezer functions func (c *containerLXC) Freeze() error { ctxMap := log.Ctx{"name": c.name, "creation date": c.creationDate, "ephemeral": c.ephemeral} // Check that we're not already frozen if c.IsFrozen() { return fmt.Errorf("The container is already frozen") } // Check that we're running if !c.IsRunning() { return fmt.Errorf("The container isn't running") } logger.Info("Freezing container", ctxMap) // Load the go-lxc struct err := c.initLXC() if err != nil { ctxMap["err"] = err logger.Error("Failed freezing container", ctxMap) return err } err = c.c.Freeze() if err != nil { ctxMap["err"] = err logger.Error("Failed freezing container", ctxMap) return err } logger.Info("Froze container", ctxMap) return err } func (c *containerLXC) Unfreeze() error { ctxMap := log.Ctx{"name": c.name, "creation date": c.creationDate, "ephemeral": c.ephemeral} // Check that we're frozen if !c.IsFrozen() { return fmt.Errorf("The container is already running") } // Check that we're running if !c.IsRunning() { return fmt.Errorf("The container isn't running") } logger.Info("Unfreezing container", ctxMap) // Load the go-lxc struct err := c.initLXC() if err != nil { logger.Error("Failed unfreezing container", ctxMap) return err } err = c.c.Unfreeze() if err != nil { logger.Error("Failed unfreezing container", ctxMap) } logger.Info("Unfroze container", ctxMap) return err } var LxcMonitorStateError = fmt.Errorf("Monitor is hung") // Get lxc container state, with 1 second timeout // If we don't get a reply, assume the lxc monitor is hung func (c *containerLXC) getLxcState() (lxc.State, error) { if c.IsSnapshot() { return lxc.StateMap["STOPPED"], nil } monitor := make(chan lxc.State, 1) go func(c *lxc.Container) { monitor <- c.State() }(c.c) select { case state := <-monitor: return state, nil case <-time.After(5 * time.Second): return lxc.StateMap["FROZEN"], LxcMonitorStateError } } func (c *containerLXC) Render() (interface{}, error) { // Load the go-lxc struct err := c.initLXC() if err != nil { return nil, err } // Ignore err as the arch string on error is correct (unknown) architectureName, _ := osarch.ArchitectureName(c.architecture) if c.IsSnapshot() { return &api.ContainerSnapshot{ Architecture: architectureName, Config: c.localConfig, CreationDate: c.creationDate, Devices: c.localDevices, Ephemeral: c.ephemeral, ExpandedConfig: c.expandedConfig, ExpandedDevices: c.expandedDevices, Name: c.name, Profiles: c.profiles, Stateful: c.stateful, }, nil } else { // FIXME: Render shouldn't directly access the go-lxc struct cState, err := c.getLxcState() if err != nil { return nil, err } statusCode := lxcStatusCode(cState) ct := api.Container{ ExpandedConfig: c.expandedConfig, ExpandedDevices: c.expandedDevices, Name: c.name, Status: statusCode.String(), StatusCode: statusCode, } ct.Architecture = architectureName ct.Config = c.localConfig ct.CreatedAt = c.creationDate ct.Devices = c.localDevices ct.Ephemeral = c.ephemeral ct.Profiles = c.profiles ct.Stateful = c.stateful return &ct, nil } } func (c *containerLXC) RenderState() (*api.ContainerState, error) { // Load the go-lxc struct err := c.initLXC() if err != nil { return nil, err } cState, err := c.getLxcState() if err != nil { return nil, err } statusCode := lxcStatusCode(cState) status := api.ContainerState{ Status: statusCode.String(), StatusCode: statusCode, } if c.IsRunning() { pid := c.InitPID() status.Disk = c.diskState() status.Memory = c.memoryState() status.Network = c.networkState() status.Pid = int64(pid) status.Processes = c.processesState() } return &status, nil } func (c *containerLXC) Snapshots() ([]container, error) { // Get all the snapshots snaps, err := db.ContainerGetSnapshots(c.state.DB, c.name) if err != nil { return nil, err } // Build the snapshot list containers := []container{} for _, snapName := range snaps { snap, err := containerLoadByName(c.state, c.storage, snapName) if err != nil { return nil, err } containers = append(containers, snap) } return containers, nil } func (c *containerLXC) Restore(sourceContainer container) error { var ctxMap log.Ctx // Check if we can restore the container err := c.storage.ContainerCanRestore(c, sourceContainer) if err != nil { return err } /* let's also check for CRIU if necessary, before doing a bunch of * filesystem manipulations */ if shared.PathExists(c.StatePath()) { _, err := exec.LookPath("criu") if err != nil { return fmt.Errorf("Failed to restore container state. CRIU isn't installed.") } } // Stop the container wasRunning := false if c.IsRunning() { wasRunning = true if err := c.Stop(false); err != nil { return err } } ctxMap = log.Ctx{"name": c.name, "creation date": c.creationDate, "ephemeral": c.ephemeral, "source container": sourceContainer.Name()} logger.Info("Restoring container", ctxMap) // Restore the rootfs err = c.storage.ContainerRestore(c, sourceContainer) if err != nil { logger.Error("Failed restoring container filesystem", ctxMap) return err } // Restore the configuration args := db.ContainerArgs{ Architecture: sourceContainer.Architecture(), Config: sourceContainer.LocalConfig(), Devices: sourceContainer.LocalDevices(), Ephemeral: sourceContainer.IsEphemeral(), Profiles: sourceContainer.Profiles(), } err = c.Update(args, false) if err != nil { logger.Error("Failed restoring container configuration", ctxMap) return err } // If the container wasn't running but was stateful, should we restore // it as running? if shared.PathExists(c.StatePath()) { if err := c.Migrate(lxc.MIGRATE_RESTORE, c.StatePath(), "snapshot", false, false); err != nil { return err } // Remove the state from the parent container; we only keep // this in snapshots. err2 := os.RemoveAll(c.StatePath()) if err2 != nil { logger.Error("Failed to delete snapshot state", log.Ctx{"path": c.StatePath(), "err": err2}) } if err != nil { logger.Info("Failed restoring container", ctxMap) return err } logger.Info("Restored container", ctxMap) return nil } // Restart the container if wasRunning { logger.Info("Restored container", ctxMap) return c.Start(false) } logger.Info("Restored container", ctxMap) return nil } func (c *containerLXC) cleanup() { // Unmount any leftovers c.removeUnixDevices() c.removeDiskDevices() // Remove the security profiles AADeleteProfile(c) SeccompDeleteProfile(c) // Remove the devices path os.Remove(c.DevicesPath()) // Remove the shmounts path os.RemoveAll(shared.VarPath("shmounts", c.Name())) } func (c *containerLXC) Delete() error { ctxMap := log.Ctx{"name": c.name, "creation date": c.creationDate, "ephemeral": c.ephemeral} logger.Info("Deleting container", ctxMap) if c.IsSnapshot() { // Remove the snapshot err := c.storage.ContainerSnapshotDelete(c) if err != nil { logger.Warn("Failed to delete snapshot", log.Ctx{"name": c.Name(), "err": err}) return err } } else { // Remove all snapshot err := containerDeleteSnapshots(c.state, c.storage, c.Name()) if err != nil { logger.Warn("Failed to delete snapshots", log.Ctx{"name": c.Name(), "err": err}) return err } // Clean things up c.cleanup() // Delete the container from disk if c.storage != nil { if shared.PathExists(c.Path()) { err := c.storage.ContainerDelete(c) if err != nil { logger.Error("Failed deleting container storage", log.Ctx{"name": c.Name(), "err": err}) return err } } } } // Remove the database record if err := db.ContainerRemove(c.state.DB, c.Name()); err != nil { logger.Error("Failed deleting container entry", log.Ctx{"name": c.Name(), "err": err}) return err } logger.Info("Deleted container", ctxMap) return nil } func (c *containerLXC) Rename(newName string) error { oldName := c.Name() ctxMap := log.Ctx{"name": c.name, "creation date": c.creationDate, "ephemeral": c.ephemeral, "newname": newName} logger.Info("Renaming container", ctxMap) // Sanity checks if !c.IsSnapshot() && !shared.ValidHostname(newName) { return fmt.Errorf("Invalid container name") } if c.IsRunning() { return fmt.Errorf("Renaming of running container not allowed") } // Clean things up c.cleanup() // Rename the logging path os.RemoveAll(shared.LogPath(newName)) if shared.PathExists(c.LogPath()) { err := os.Rename(c.LogPath(), shared.LogPath(newName)) if err != nil { logger.Error("Failed renaming container", ctxMap) return err } } // Rename the storage entry if c.IsSnapshot() { if err := c.storage.ContainerSnapshotRename(c, newName); err != nil { logger.Error("Failed renaming container", ctxMap) return err } } else { if err := c.storage.ContainerRename(c, newName); err != nil { logger.Error("Failed renaming container", ctxMap) return err } } // Rename the database entry if err := db.ContainerRename(c.state.DB, oldName, newName); err != nil { logger.Error("Failed renaming container", ctxMap) return err } if !c.IsSnapshot() { // Rename all the snapshots results, err := db.ContainerGetSnapshots(c.state.DB, oldName) if err != nil { logger.Error("Failed renaming container", ctxMap) return err } for _, sname := range results { // Rename the snapshot baseSnapName := filepath.Base(sname) newSnapshotName := newName + shared.SnapshotDelimiter + baseSnapName if err := db.ContainerRename(c.state.DB, sname, newSnapshotName); err != nil { logger.Error("Failed renaming container", ctxMap) return err } } } // Set the new name in the struct c.name = newName // Invalidate the go-lxc cache c.c = nil logger.Info("Renamed container", ctxMap) return nil } func (c *containerLXC) CGroupGet(key string) (string, error) { // Load the go-lxc struct err := c.initLXC() if err != nil { return "", err } // Make sure the container is running if !c.IsRunning() { return "", fmt.Errorf("Can't get cgroups on a stopped container") } value := c.c.CgroupItem(key) return strings.Join(value, "\n"), nil } func (c *containerLXC) CGroupSet(key string, value string) error { // Load the go-lxc struct err := c.initLXC() if err != nil { return err } // Make sure the container is running if !c.IsRunning() { return fmt.Errorf("Can't set cgroups on a stopped container") } err = c.c.SetCgroupItem(key, value) if err != nil { return fmt.Errorf("Failed to set cgroup %s=\"%s\": %s", key, value, err) } return nil } func (c *containerLXC) ConfigKeySet(key string, value string) error { c.localConfig[key] = value args := db.ContainerArgs{ Architecture: c.architecture, Config: c.localConfig, Devices: c.localDevices, Ephemeral: c.ephemeral, Profiles: c.profiles, } return c.Update(args, false) } func (c *containerLXC) Update(args db.ContainerArgs, userRequested bool) error { // Set sane defaults for unset keys if args.Architecture == 0 { args.Architecture = c.architecture } if args.Config == nil { args.Config = map[string]string{} } if args.Devices == nil { args.Devices = types.Devices{} } if args.Profiles == nil { args.Profiles = []string{} } // Validate the new config err := containerValidConfig(c.state.OS, args.Config, false, false) if err != nil { return err } // Validate the new devices err = containerValidDevices(args.Devices, false, false) if err != nil { return err } // Validate the new profiles profiles, err := db.Profiles(c.state.DB) if err != nil { return err } for _, name := range args.Profiles { if !shared.StringInSlice(name, profiles) { return fmt.Errorf("Profile doesn't exist: %s", name) } } // Validate the new architecture if args.Architecture != 0 { _, err = osarch.ArchitectureName(args.Architecture) if err != nil { return fmt.Errorf("Invalid architecture id: %s", err) } } // Check that volatile wasn't modified if userRequested { for k, v := range args.Config { if strings.HasPrefix(k, "volatile.") && c.localConfig[k] != v { return fmt.Errorf("Volatile keys are read-only.") } } for k, v := range c.localConfig { if strings.HasPrefix(k, "volatile.") && args.Config[k] != v { return fmt.Errorf("Volatile keys are read-only.") } } } // Get a copy of the old configuration oldArchitecture := 0 err = shared.DeepCopy(&c.architecture, &oldArchitecture) if err != nil { return err } oldEphemeral := false err = shared.DeepCopy(&c.ephemeral, &oldEphemeral) if err != nil { return err } oldExpandedDevices := types.Devices{} err = shared.DeepCopy(&c.expandedDevices, &oldExpandedDevices) if err != nil { return err } oldExpandedConfig := map[string]string{} err = shared.DeepCopy(&c.expandedConfig, &oldExpandedConfig) if err != nil { return err } oldLocalDevices := types.Devices{} err = shared.DeepCopy(&c.localDevices, &oldLocalDevices) if err != nil { return err } oldLocalConfig := map[string]string{} err = shared.DeepCopy(&c.localConfig, &oldLocalConfig) if err != nil { return err } oldProfiles := []string{} err = shared.DeepCopy(&c.profiles, &oldProfiles) if err != nil { return err } // Define a function which reverts everything. Defer this function // so that it doesn't need to be explicitly called in every failing // return path. Track whether or not we want to undo the changes // using a closure. undoChanges := true defer func() { if undoChanges { c.architecture = oldArchitecture c.ephemeral = oldEphemeral c.expandedConfig = oldExpandedConfig c.expandedDevices = oldExpandedDevices c.localConfig = oldLocalConfig c.localDevices = oldLocalDevices c.profiles = oldProfiles c.c = nil c.initLXC() deviceTaskSchedulerTrigger("container", c.name, "changed") } }() // Apply the various changes c.architecture = args.Architecture c.ephemeral = args.Ephemeral c.localConfig = args.Config c.localDevices = args.Devices c.profiles = args.Profiles // Expand the config and refresh the LXC config err = c.expandConfig() if err != nil { return err } err = c.expandDevices() if err != nil { return err } // Diff the configurations changedConfig := []string{} for key := range oldExpandedConfig { if oldExpandedConfig[key] != c.expandedConfig[key] { if !shared.StringInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } } for key := range c.expandedConfig { if oldExpandedConfig[key] != c.expandedConfig[key] { if !shared.StringInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } } // Diff the devices removeDevices, addDevices, updateDevices, updateDiff := oldExpandedDevices.Update(c.expandedDevices) // Do some validation of the config diff err = containerValidConfig(c.state.OS, c.expandedConfig, false, true) if err != nil { return err } // Do some validation of the devices diff err = containerValidDevices(c.expandedDevices, false, true) if err != nil { return err } // Run through initLXC to catch anything we missed c.c = nil err = c.initLXC() if err != nil { return err } // If apparmor changed, re-validate the apparmor profile if shared.StringInSlice("raw.apparmor", changedConfig) || shared.StringInSlice("security.nesting", changedConfig) { err = AAParseProfile(c) if err != nil { return err } } if shared.StringInSlice("security.idmap.isolated", changedConfig) || shared.StringInSlice("security.idmap.base", changedConfig) || shared.StringInSlice("security.idmap.size", changedConfig) || shared.StringInSlice("raw.idmap", changedConfig) || shared.StringInSlice("security.privileged", changedConfig) { var idmap *idmap.IdmapSet base := int64(0) if !c.IsPrivileged() { // update the idmap idmap, base, err = findIdmap( c.state, c.storage, c.Name(), c.expandedConfig["security.idmap.isolated"], c.expandedConfig["security.idmap.base"], c.expandedConfig["security.idmap.size"], c.expandedConfig["raw.idmap"], ) if err != nil { return err } } var jsonIdmap string if idmap != nil { idmapBytes, err := json.Marshal(idmap.Idmap) if err != nil { return err } jsonIdmap = string(idmapBytes) } else { jsonIdmap = "[]" } c.localConfig["volatile.idmap.next"] = jsonIdmap c.localConfig["volatile.idmap.base"] = fmt.Sprintf("%v", base) // Invalid idmap cache c.idmapset = nil } // Apply disk quota changes for _, m := range addDevices { if m["type"] != "disk" || m["path"] != "/" { continue } var oldRootfsSize string for _, n := range oldExpandedDevices { if n["type"] == "disk" && n["path"] == "/" { oldRootfsSize = n["size"] break } } if m["size"] != oldRootfsSize { size, err := shared.ParseByteSizeString(m["size"]) if err != nil { return err } err = c.storage.ContainerSetQuota(c, size) if err != nil { return err } } } // Apply the live changes if c.IsRunning() { // Confirm that the rootfs source didn't change var oldRootfs types.Device for _, m := range oldExpandedDevices { if m["type"] == "disk" && m["path"] == "/" { oldRootfs = m break } } var newRootfs types.Device for _, name := range c.expandedDevices.DeviceNames() { m := c.expandedDevices[name] if m["type"] == "disk" && m["path"] == "/" { newRootfs = m break } } if oldRootfs["source"] != newRootfs["source"] { return fmt.Errorf("Cannot change the rootfs path of a running container") } // Live update the container config for _, key := range changedConfig { value := c.expandedConfig[key] if key == "raw.apparmor" || key == "security.nesting" { // Update the AppArmor profile err = AALoadProfile(c) if err != nil { return err } } else if key == "linux.kernel_modules" && value != "" { for _, module := range strings.Split(value, ",") { module = strings.TrimPrefix(module, " ") err := util.LoadModule(module) if err != nil { return fmt.Errorf("Failed to load kernel module '%s': %s", module, err) } } } else if key == "limits.disk.priority" { if !cgBlkioController { continue } priorityInt := 5 diskPriority := c.expandedConfig["limits.disk.priority"] if diskPriority != "" { priorityInt, err = strconv.Atoi(diskPriority) if err != nil { return err } } // Minimum valid value is 10 priority := priorityInt * 100 if priority == 0 { priority = 10 } err = c.CGroupSet("blkio.weight", fmt.Sprintf("%d", priority)) if err != nil { return err } } else if key == "limits.memory" || strings.HasPrefix(key, "limits.memory.") { // Skip if no memory CGroup if !cgMemoryController { continue } // Set the new memory limit memory := c.expandedConfig["limits.memory"] memoryEnforce := c.expandedConfig["limits.memory.enforce"] memorySwap := c.expandedConfig["limits.memory.swap"] // Parse memory if memory == "" { memory = "-1" } else if strings.HasSuffix(memory, "%") { percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64) if err != nil { return err } memoryTotal, err := deviceTotalMemory() if err != nil { return err } memory = fmt.Sprintf("%d", int64((memoryTotal/100)*percent)) } else { valueInt, err := shared.ParseByteSizeString(memory) if err != nil { return err } memory = fmt.Sprintf("%d", valueInt) } // Store the old values for revert oldMemswLimit := "" if cgSwapAccounting { oldMemswLimit, err = c.CGroupGet("memory.memsw.limit_in_bytes") if err != nil { oldMemswLimit = "" } } oldLimit, err := c.CGroupGet("memory.limit_in_bytes") if err != nil { oldLimit = "" } oldSoftLimit, err := c.CGroupGet("memory.soft_limit_in_bytes") if err != nil { oldSoftLimit = "" } revertMemory := func() { if oldSoftLimit != "" { c.CGroupSet("memory.soft_limit_in_bytes", oldSoftLimit) } if oldLimit != "" { c.CGroupSet("memory.limit_in_bytes", oldLimit) } if oldMemswLimit != "" { c.CGroupSet("memory.memsw.limit_in_bytes", oldMemswLimit) } } // Reset everything if cgSwapAccounting { err = c.CGroupSet("memory.memsw.limit_in_bytes", "-1") if err != nil { revertMemory() return err } } err = c.CGroupSet("memory.limit_in_bytes", "-1") if err != nil { revertMemory() return err } err = c.CGroupSet("memory.soft_limit_in_bytes", "-1") if err != nil { revertMemory() return err } // Set the new values if memoryEnforce == "soft" { // Set new limit err = c.CGroupSet("memory.soft_limit_in_bytes", memory) if err != nil { revertMemory() return err } } else { if cgSwapAccounting && (memorySwap == "" || shared.IsTrue(memorySwap)) { err = c.CGroupSet("memory.limit_in_bytes", memory) if err != nil { revertMemory() return err } err = c.CGroupSet("memory.memsw.limit_in_bytes", memory) if err != nil { revertMemory() return err } } else { err = c.CGroupSet("memory.limit_in_bytes", memory) if err != nil { revertMemory() return err } } // Set soft limit to value 10% less than hard limit valueInt, err := strconv.ParseInt(memory, 10, 64) if err != nil { revertMemory() return err } err = c.CGroupSet("memory.soft_limit_in_bytes", fmt.Sprintf("%.0f", float64(valueInt)*0.9)) if err != nil { revertMemory() return err } } // Configure the swappiness if key == "limits.memory.swap" || key == "limits.memory.swap.priority" { memorySwap := c.expandedConfig["limits.memory.swap"] memorySwapPriority := c.expandedConfig["limits.memory.swap.priority"] if memorySwap != "" && !shared.IsTrue(memorySwap) { err = c.CGroupSet("memory.swappiness", "0") if err != nil { return err } } else { priority := 0 if memorySwapPriority != "" { priority, err = strconv.Atoi(memorySwapPriority) if err != nil { return err } } err = c.CGroupSet("memory.swappiness", fmt.Sprintf("%d", 60-10+priority)) if err != nil { return err } } } } else if key == "limits.network.priority" { err := c.setNetworkPriority() if err != nil { return err } } else if key == "limits.cpu" { // Trigger a scheduler re-run deviceTaskSchedulerTrigger("container", c.name, "changed") } else if key == "limits.cpu.priority" || key == "limits.cpu.allowance" { // Skip if no cpu CGroup if !cgCpuController { continue } // Apply new CPU limits cpuShares, cpuCfsQuota, cpuCfsPeriod, err := deviceParseCPU(c.expandedConfig["limits.cpu.allowance"], c.expandedConfig["limits.cpu.priority"]) if err != nil { return err } err = c.CGroupSet("cpu.shares", cpuShares) if err != nil { return err } err = c.CGroupSet("cpu.cfs_period_us", cpuCfsPeriod) if err != nil { return err } err = c.CGroupSet("cpu.cfs_quota_us", cpuCfsQuota) if err != nil { return err } } else if key == "limits.processes" { if !cgPidsController { continue } if value == "" { err = c.CGroupSet("pids.max", "max") if err != nil { return err } } else { valueInt, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } err = c.CGroupSet("pids.max", fmt.Sprintf("%d", valueInt)) if err != nil { return err } } } } // Live update the devices for k, m := range removeDevices { if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) { err = c.removeUnixDevice(m) if err != nil { return err } } else if m["type"] == "disk" && m["path"] != "/" { err = c.removeDiskDevice(k, m) if err != nil { return err } } else if m["type"] == "nic" { err = c.removeNetworkDevice(k, m) if err != nil { return err } } } diskDevices := map[string]types.Device{} for k, m := range addDevices { if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) { err = c.insertUnixDevice(k, m) if err != nil { return err } } else if m["type"] == "disk" && m["path"] != "/" { diskDevices[k] = m } else if m["type"] == "nic" { err = c.insertNetworkDevice(k, m) if err != nil { return err } } } err = c.addDiskDevices(diskDevices, c.insertDiskDevice) if err != nil { return err } updateDiskLimit := false for k, m := range updateDevices { if m["type"] == "disk" { updateDiskLimit = true } else if m["type"] == "nic" { needsUpdate := false for _, v := range containerNetworkLimitKeys { needsUpdate = shared.StringInSlice(v, updateDiff) if needsUpdate { break } } if needsUpdate { // Refresh tc limits err = c.setNetworkLimits(k, m) if err != nil { return err } } } } // Disk limits parse all devices, so just apply them once if updateDiskLimit && cgBlkioController { diskLimits, err := c.getDiskLimits() if err != nil { return err } for block, limit := range diskLimits { err = c.CGroupSet("blkio.throttle.read_bps_device", fmt.Sprintf("%s %d", block, limit.readBps)) if err != nil { return err } err = c.CGroupSet("blkio.throttle.read_iops_device", fmt.Sprintf("%s %d", block, limit.readIops)) if err != nil { return err } err = c.CGroupSet("blkio.throttle.write_bps_device", fmt.Sprintf("%s %d", block, limit.writeBps)) if err != nil { return err } err = c.CGroupSet("blkio.throttle.write_iops_device", fmt.Sprintf("%s %d", block, limit.writeIops)) if err != nil { return err } } } } // Cleanup any leftover volatile entries netNames := []string{} for _, k := range c.expandedDevices.DeviceNames() { v := c.expandedDevices[k] if v["type"] == "nic" { netNames = append(netNames, k) } } for k := range c.localConfig { // We only care about volatile if !strings.HasPrefix(k, "volatile.") { continue } // Confirm it's a key of format volatile.<device>.<key> fields := strings.SplitN(k, ".", 3) if len(fields) != 3 { continue } // The only device keys we care about are name and hwaddr if !shared.StringInSlice(fields[2], []string{"name", "hwaddr", "host_name"}) { continue } // Check if the device still exists if shared.StringInSlice(fields[1], netNames) { // Don't remove the volatile entry if the device doesn't have the matching field set if c.expandedDevices[fields[1]][fields[2]] == "" { continue } } // Remove the volatile key from the in-memory configs delete(c.localConfig, k) delete(c.expandedConfig, k) } // Finally, apply the changes to the database tx, err := db.Begin(c.state.DB) if err != nil { return err } err = db.ContainerConfigClear(tx, c.id) if err != nil { tx.Rollback() return err } err = db.ContainerConfigInsert(tx, c.id, c.localConfig) if err != nil { tx.Rollback() return err } err = db.ContainerProfilesInsert(tx, c.id, c.profiles) if err != nil { tx.Rollback() return err } err = db.DevicesAdd(tx, "container", int64(c.id), c.localDevices) if err != nil { tx.Rollback() return err } err = db.ContainerUpdate(tx, c.id, c.architecture, c.ephemeral) if err != nil { tx.Rollback() return err } if err := db.TxCommit(tx); err != nil { return err } // Success, update the closure to mark that the changes should be kept. undoChanges = false return nil } func (c *containerLXC) Export(w io.Writer, properties map[string]string) error { ctxMap := log.Ctx{"name": c.name, "created": c.creationDate, "ephemeral": c.ephemeral} if c.IsRunning() { return fmt.Errorf("Cannot export a running container as an image") } logger.Info("Exporting container", ctxMap) // Start the storage err := c.StorageStart() if err != nil { logger.Error("Failed exporting container", ctxMap) return err } defer c.StorageStop() // Unshift the container idmap, err := c.LastIdmapSet() if err != nil { logger.Error("Failed exporting container", ctxMap) return err } if idmap != nil { if err := idmap.UnshiftRootfs(c.RootfsPath()); err != nil { logger.Error("Failed exporting container", ctxMap) return err } defer idmap.ShiftRootfs(c.RootfsPath()) } // Create the tarball tw := tar.NewWriter(w) // Keep track of the first path we saw for each path with nlink>1 linkmap := map[uint64]string{} cDir := c.Path() // Path inside the tar image is the pathname starting after cDir offset := len(cDir) + 1 writeToTar := func(path string, fi os.FileInfo, err error) error { if err != nil { return err } err = c.tarStoreFile(linkmap, offset, tw, path, fi) if err != nil { logger.Debugf("Error tarring up %s: %s", path, err) return err } return nil } // Look for metadata.yaml fnam := filepath.Join(cDir, "metadata.yaml") if !shared.PathExists(fnam) { // Generate a new metadata.yaml tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_") if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } defer os.RemoveAll(tempDir) // Get the container's architecture var arch string if c.IsSnapshot() { parentName, _, _ := containerGetParentAndSnapshotName(c.name) parent, err := containerLoadByName(c.state, c.storage, parentName) if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } arch, _ = osarch.ArchitectureName(parent.Architecture()) } else { arch, _ = osarch.ArchitectureName(c.architecture) } if arch == "" { arch, err = osarch.ArchitectureName(c.state.OS.Architectures[0]) if err != nil { logger.Error("Failed exporting container", ctxMap) return err } } // Fill in the metadata meta := imageMetadata{} meta.Architecture = arch meta.CreationDate = time.Now().UTC().Unix() meta.Properties = properties data, err := yaml.Marshal(&meta) if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } // Write the actual file fnam = filepath.Join(tempDir, "metadata.yaml") err = ioutil.WriteFile(fnam, data, 0644) if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } fi, err := os.Lstat(fnam) if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } tmpOffset := len(path.Dir(fnam)) + 1 if err := c.tarStoreFile(linkmap, tmpOffset, tw, fnam, fi); err != nil { tw.Close() logger.Debugf("Error writing to tarfile: %s", err) logger.Error("Failed exporting container", ctxMap) return err } } else { if properties != nil { // Parse the metadata content, err := ioutil.ReadFile(fnam) if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } metadata := new(imageMetadata) err = yaml.Unmarshal(content, &metadata) if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } metadata.Properties = properties // Generate a new metadata.yaml tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_") if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } defer os.RemoveAll(tempDir) data, err := yaml.Marshal(&metadata) if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } // Write the actual file fnam = filepath.Join(tempDir, "metadata.yaml") err = ioutil.WriteFile(fnam, data, 0644) if err != nil { tw.Close() logger.Error("Failed exporting container", ctxMap) return err } } // Include metadata.yaml in the tarball fi, err := os.Lstat(fnam) if err != nil { tw.Close() logger.Debugf("Error statting %s during export", fnam) logger.Error("Failed exporting container", ctxMap) return err } if properties != nil { tmpOffset := len(path.Dir(fnam)) + 1 err = c.tarStoreFile(linkmap, tmpOffset, tw, fnam, fi) } else { err = c.tarStoreFile(linkmap, offset, tw, fnam, fi) } if err != nil { tw.Close() logger.Debugf("Error writing to tarfile: %s", err) logger.Error("Failed exporting container", ctxMap) return err } } // Include all the rootfs files fnam = c.RootfsPath() err = filepath.Walk(fnam, writeToTar) if err != nil { logger.Error("Failed exporting container", ctxMap) return err } // Include all the templates fnam = c.TemplatesPath() if shared.PathExists(fnam) { err = filepath.Walk(fnam, writeToTar) if err != nil { logger.Error("Failed exporting container", ctxMap) return err } } err = tw.Close() if err != nil { logger.Error("Failed exporting container", ctxMap) return err } logger.Info("Exported container", ctxMap) return nil } func collectCRIULogFile(c container, imagesDir string, function string, method string) error { t := time.Now().Format(time.RFC3339) newPath := shared.LogPath(c.Name(), fmt.Sprintf("%s_%s_%s.log", function, method, t)) return shared.FileCopy(filepath.Join(imagesDir, fmt.Sprintf("%s.log", method)), newPath) } func getCRIULogErrors(imagesDir string, method string) (string, error) { f, err := os.Open(path.Join(imagesDir, fmt.Sprintf("%s.log", method))) if err != nil { return "", err } defer f.Close() scanner := bufio.NewScanner(f) ret := []string{} for scanner.Scan() { line := scanner.Text() if strings.Contains(line, "Error") || strings.Contains(line, "Warn") { ret = append(ret, scanner.Text()) } } return strings.Join(ret, "\n"), nil } func (c *containerLXC) Migrate(cmd uint, stateDir string, function string, stop bool, actionScript bool) error { ctxMap := log.Ctx{"name": c.name, "created": c.creationDate, "ephemeral": c.ephemeral, "statedir": stateDir, "actionscript": actionScript, "stop": stop} _, err := exec.LookPath("criu") if err != nil { return fmt.Errorf("Unable to perform container live migration. CRIU isn't installed.") } logger.Info("Migrating container", ctxMap) prettyCmd := "" switch cmd { case lxc.MIGRATE_PRE_DUMP: prettyCmd = "pre-dump" case lxc.MIGRATE_DUMP: prettyCmd = "dump" case lxc.MIGRATE_RESTORE: prettyCmd = "restore" default: prettyCmd = "unknown" logger.Warn("unknown migrate call", log.Ctx{"cmd": cmd}) } preservesInodes := c.storage.PreservesInodes() /* This feature was only added in 2.0.1, let's not ask for it * before then or migrations will fail. */ if !lxc.VersionAtLeast(2, 0, 1) { preservesInodes = false } var migrateErr error /* For restore, we need an extra fork so that we daemonize monitor * instead of having it be a child of LXD, so let's hijack the command * here and do the extra fork. */ if cmd == lxc.MIGRATE_RESTORE { // Run the shared start _, err := c.startCommon() if err != nil { return err } /* * For unprivileged containers we need to shift the * perms on the images images so that they can be * opened by the process after it is in its user * namespace. */ if !c.IsPrivileged() { idmapset, err := c.IdmapSet() if err != nil { return err } err = c.StorageStart() if err != nil { return err } err = idmapset.ShiftRootfs(stateDir) err2 := c.StorageStop() if err != nil { return err } if err2 != nil { return err2 } } configPath := filepath.Join(c.LogPath(), "lxc.conf") var out string out, migrateErr = shared.RunCommand( execPath, "forkmigrate", c.name, c.state.OS.LxcPath, configPath, stateDir, fmt.Sprintf("%v", preservesInodes)) if string(out) != "" { for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { logger.Debugf("forkmigrate: %s", line) } } if migrateErr != nil && !c.IsRunning() { migrateErr = fmt.Errorf( "Error calling 'lxd forkmigrate %s %s %s %s': err='%v' out='%v'", c.name, c.state.OS.LxcPath, filepath.Join(c.LogPath(), "lxc.conf"), stateDir, err, string(out)) } } else { err := c.initLXC() if err != nil { return err } script := "" if actionScript { script = filepath.Join(stateDir, "action.sh") } // TODO: make this configurable? Ultimately I think we don't // want to do that; what we really want to do is have "modes" // of criu operation where one is "make this succeed" and the // other is "make this fast". Anyway, for now, let's choose a // really big size so it almost always succeeds, even if it is // slow. ghostLimit := uint64(256 * 1024 * 1024) opts := lxc.MigrateOptions{ Stop: stop, Directory: stateDir, Verbose: true, PreservesInodes: preservesInodes, ActionScript: script, GhostLimit: ghostLimit, } migrateErr = c.c.Migrate(cmd, opts) } collectErr := collectCRIULogFile(c, stateDir, function, prettyCmd) if collectErr != nil { logger.Error("Error collecting checkpoint log file", log.Ctx{"err": collectErr}) } if migrateErr != nil { log, err2 := getCRIULogErrors(stateDir, prettyCmd) if err2 == nil { logger.Info("Failed migrating container", ctxMap) migrateErr = fmt.Errorf("%s %s failed\n%s", function, prettyCmd, log) } return migrateErr } logger.Info("Migrated container", ctxMap) return nil } func (c *containerLXC) TemplateApply(trigger string) error { // "create" and "copy" are deferred until next start if shared.StringInSlice(trigger, []string{"create", "copy"}) { // The two events are mutually exclusive so only keep the last one err := c.ConfigKeySet("volatile.apply_template", trigger) if err != nil { return err } return nil } return c.templateApplyNow(trigger) } func (c *containerLXC) templateApplyNow(trigger string) error { // If there's no metadata, just return fname := filepath.Join(c.Path(), "metadata.yaml") if !shared.PathExists(fname) { return nil } // Parse the metadata content, err := ioutil.ReadFile(fname) if err != nil { return err } metadata := new(imageMetadata) err = yaml.Unmarshal(content, &metadata) if err != nil { return fmt.Errorf("Could not parse %s: %v", fname, err) } // Go through the templates for templatePath, template := range metadata.Templates { var w *os.File // Check if the template should be applied now found := false for _, tplTrigger := range template.When { if tplTrigger == trigger { found = true break } } if !found { continue } // Open the file to template, create if needed fullpath := filepath.Join(c.RootfsPath(), strings.TrimLeft(templatePath, "/")) if shared.PathExists(fullpath) { if template.CreateOnly { continue } // Open the existing file w, err = os.Create(fullpath) if err != nil { return err } } else { // Create a new one uid := int64(0) gid := int64(0) // Get the right uid and gid for the container if !c.IsPrivileged() { idmapset, err := c.IdmapSet() if err != nil { return err } uid, gid = idmapset.ShiftIntoNs(0, 0) } // Create the directories leading to the file shared.MkdirAllOwner(path.Dir(fullpath), 0755, int(uid), int(gid)) // Create the file itself w, err = os.Create(fullpath) if err != nil { return err } // Fix ownership and mode if !c.IsPrivileged() { w.Chown(int(uid), int(gid)) } w.Chmod(0644) } defer w.Close() // Read the template tplString, err := ioutil.ReadFile(filepath.Join(c.TemplatesPath(), template.Template)) if err != nil { return err } tpl, err := pongo2.FromString("{% autoescape off %}" + string(tplString) + "{% endautoescape %}") if err != nil { return err } // Figure out the architecture arch, err := osarch.ArchitectureName(c.architecture) if err != nil { arch, err = osarch.ArchitectureName(c.state.OS.Architectures[0]) if err != nil { return err } } // Generate the metadata containerMeta := make(map[string]string) containerMeta["name"] = c.name containerMeta["architecture"] = arch if c.ephemeral { containerMeta["ephemeral"] = "true" } else { containerMeta["ephemeral"] = "false" } if c.IsPrivileged() { containerMeta["privileged"] = "true" } else { containerMeta["privileged"] = "false" } configGet := func(confKey, confDefault *pongo2.Value) *pongo2.Value { val, ok := c.expandedConfig[confKey.String()] if !ok { return confDefault } return pongo2.AsValue(strings.TrimRight(val, "\r\n")) } // Render the template tpl.ExecuteWriter(pongo2.Context{"trigger": trigger, "path": templatePath, "container": containerMeta, "config": c.expandedConfig, "devices": c.expandedDevices, "properties": template.Properties, "config_get": configGet}, w) } return nil } func (c *containerLXC) FileExists(path string) error { // Setup container storage if needed if !c.IsRunning() { err := c.StorageStart() if err != nil { return err } } // Check if the file exists in the container out, err := shared.RunCommand( execPath, "forkcheckfile", c.RootfsPath(), fmt.Sprintf("%d", c.InitPID()), path, ) // Tear down container storage if needed if !c.IsRunning() { err := c.StorageStop() if err != nil { return err } } // Process forkcheckfile response if string(out) != "" { if strings.HasPrefix(string(out), "error:") { return fmt.Errorf(strings.TrimPrefix(strings.TrimSuffix(string(out), "\n"), "error: ")) } for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { logger.Debugf("forkcheckfile: %s", line) } } if err != nil { return fmt.Errorf( "Error calling 'lxd forkcheckfile %s %d %s': err='%v'", c.RootfsPath(), c.InitPID(), path, err) } return nil } func (c *containerLXC) FilePull(srcpath string, dstpath string) (int64, int64, os.FileMode, error) { // Setup container storage if needed if !c.IsRunning() { err := c.StorageStart() if err != nil { return -1, -1, 0, err } } // Get the file from the container out, err := shared.RunCommand( execPath, "forkgetfile", c.RootfsPath(), fmt.Sprintf("%d", c.InitPID()), dstpath, srcpath, ) // Tear down container storage if needed if !c.IsRunning() { err := c.StorageStop() if err != nil { return -1, -1, 0, err } } uid := int64(-1) gid := int64(-1) mode := -1 var errStr string // Process forkgetfile response for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { if line == "" { continue } // Extract errors if strings.HasPrefix(line, "error: ") { errStr = strings.TrimPrefix(line, "error: ") continue } if strings.HasPrefix(line, "errno: ") { errno := strings.TrimPrefix(line, "errno: ") if errno == "2" { return -1, -1, 0, os.ErrNotExist } return -1, -1, 0, fmt.Errorf(errStr) } // Extract the uid if strings.HasPrefix(line, "uid: ") { uid, err = strconv.ParseInt(strings.TrimPrefix(line, "uid: "), 10, 64) if err != nil { return -1, -1, 0, err } continue } // Extract the gid if strings.HasPrefix(line, "gid: ") { gid, err = strconv.ParseInt(strings.TrimPrefix(line, "gid: "), 10, 64) if err != nil { return -1, -1, 0, err } continue } // Extract the mode if strings.HasPrefix(line, "mode: ") { mode, err = strconv.Atoi(strings.TrimPrefix(line, "mode: ")) if err != nil { return -1, -1, 0, err } continue } logger.Debugf("forkgetfile: %s", line) } if err != nil { return -1, -1, 0, fmt.Errorf( "Error calling 'lxd forkgetfile %s %d %s %s': err='%v'", c.RootfsPath(), c.InitPID(), dstpath, srcpath, err) } // Unmap uid and gid if needed if !c.IsRunning() { idmapset, err := c.LastIdmapSet() if err != nil { return -1, -1, 0, err } if idmapset != nil { uid, gid = idmapset.ShiftFromNs(uid, gid) } } return uid, gid, os.FileMode(mode), nil } func (c *containerLXC) FilePush(srcpath string, dstpath string, uid int64, gid int64, mode int) error { var rootUid int64 var rootGid int64 var errStr string // Map uid and gid if needed if !c.IsRunning() { idmapset, err := c.LastIdmapSet() if err != nil { return err } if idmapset != nil { uid, gid = idmapset.ShiftIntoNs(uid, gid) rootUid, rootGid = idmapset.ShiftIntoNs(0, 0) } } // Setup container storage if needed if !c.IsRunning() { err := c.StorageStart() if err != nil { return err } } // Push the file to the container out, err := shared.RunCommand( execPath, "forkputfile", c.RootfsPath(), fmt.Sprintf("%d", c.InitPID()), srcpath, dstpath, fmt.Sprintf("%d", uid), fmt.Sprintf("%d", gid), fmt.Sprintf("%d", mode), fmt.Sprintf("%d", rootUid), fmt.Sprintf("%d", rootGid), fmt.Sprintf("%d", int(os.FileMode(0640)&os.ModePerm)), ) // Tear down container storage if needed if !c.IsRunning() { err := c.StorageStop() if err != nil { return err } } // Process forkgetfile response for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { if line == "" { continue } // Extract errors if strings.HasPrefix(line, "error: ") { errStr = strings.TrimPrefix(line, "error: ") continue } if strings.HasPrefix(line, "errno: ") { errno := strings.TrimPrefix(line, "errno: ") if errno == "2" { return os.ErrNotExist } return fmt.Errorf(errStr) } } if err != nil { return fmt.Errorf( "Error calling 'lxd forkputfile %s %d %s %s %d %d %d %d %d %d': err='%v'", c.RootfsPath(), c.InitPID(), srcpath, dstpath, uid, gid, mode, rootUid, rootGid, int(os.FileMode(0640)&os.ModePerm), err) } return nil } func (c *containerLXC) FileRemove(path string) error { var errStr string // Setup container storage if needed if !c.IsRunning() { err := c.StorageStart() if err != nil { return err } } // Remove the file from the container out, err := shared.RunCommand( execPath, "forkremovefile", c.RootfsPath(), fmt.Sprintf("%d", c.InitPID()), path, ) // Tear down container storage if needed if !c.IsRunning() { err := c.StorageStop() if err != nil { return err } } // Process forkremovefile response for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { if line == "" { continue } // Extract errors if strings.HasPrefix(line, "error: ") { errStr = strings.TrimPrefix(line, "error: ") continue } if strings.HasPrefix(line, "errno: ") { errno := strings.TrimPrefix(line, "errno: ") if errno == "2" { return os.ErrNotExist } return fmt.Errorf(errStr) } } if err != nil { return fmt.Errorf( "Error calling 'lxd forkremovefile %s %d %s': err='%v'", c.RootfsPath(), c.InitPID(), path, err) } return nil } func (c *containerLXC) Exec(command []string, env map[string]string, stdin *os.File, stdout *os.File, stderr *os.File, wait bool) (*exec.Cmd, int, int, error) { envSlice := []string{} for k, v := range env { envSlice = append(envSlice, fmt.Sprintf("%s=%s", k, v)) } args := []string{execPath, "forkexec", c.name, c.state.OS.LxcPath, filepath.Join(c.LogPath(), "lxc.conf")} args = append(args, "--") args = append(args, "env") args = append(args, envSlice...) args = append(args, "--") args = append(args, "cmd") args = append(args, command...) cmd := exec.Cmd{} cmd.Path = execPath cmd.Args = args cmd.Stdin = stdin cmd.Stdout = stdout cmd.Stderr = stderr r, w, err := shared.Pipe() defer r.Close() if err != nil { logger.Errorf("%s", err) return nil, -1, -1, err } cmd.ExtraFiles = []*os.File{w} err = cmd.Start() if err != nil { w.Close() return nil, -1, -1, err } w.Close() attachedPid := -1 if err := json.NewDecoder(r).Decode(&attachedPid); err != nil { logger.Errorf("Failed to retrieve PID of executing child process: %s", err) return nil, -1, -1, err } // It's the callers responsibility to wait or not wait. if !wait { return &cmd, -1, attachedPid, nil } err = cmd.Wait() if err != nil { exitErr, ok := err.(*exec.ExitError) if ok { status, ok := exitErr.Sys().(syscall.WaitStatus) if ok { return nil, status.ExitStatus(), attachedPid, nil } if status.Signaled() { // 128 + n == Fatal error signal "n" return nil, 128 + int(status.Signal()), attachedPid, nil } } return nil, -1, -1, err } return nil, 0, attachedPid, nil } func (c *containerLXC) diskState() map[string]api.ContainerStateDisk { disk := map[string]api.ContainerStateDisk{} for _, name := range c.expandedDevices.DeviceNames() { d := c.expandedDevices[name] if d["type"] != "disk" { continue } if d["path"] != "/" { continue } usage, err := c.storage.ContainerGetUsage(c) if err != nil { continue } disk[name] = api.ContainerStateDisk{Usage: usage} } return disk } func (c *containerLXC) memoryState() api.ContainerStateMemory { memory := api.ContainerStateMemory{} if !cgMemoryController { return memory } // Memory in bytes value, err := c.CGroupGet("memory.usage_in_bytes") valueInt, err1 := strconv.ParseInt(value, 10, 64) if err == nil && err1 == nil { memory.Usage = valueInt } // Memory peak in bytes value, err = c.CGroupGet("memory.max_usage_in_bytes") valueInt, err1 = strconv.ParseInt(value, 10, 64) if err == nil && err1 == nil { memory.UsagePeak = valueInt } if cgSwapAccounting { // Swap in bytes if memory.Usage > 0 { value, err := c.CGroupGet("memory.memsw.usage_in_bytes") valueInt, err1 := strconv.ParseInt(value, 10, 64) if err == nil && err1 == nil { memory.SwapUsage = valueInt - memory.Usage } } // Swap peak in bytes if memory.UsagePeak > 0 { value, err = c.CGroupGet("memory.memsw.max_usage_in_bytes") valueInt, err1 = strconv.ParseInt(value, 10, 64) if err == nil && err1 == nil { memory.SwapUsagePeak = valueInt - memory.UsagePeak } } } return memory } func (c *containerLXC) networkState() map[string]api.ContainerStateNetwork { result := map[string]api.ContainerStateNetwork{} pid := c.InitPID() if pid < 1 { return result } // Get the network state from the container out, err := shared.RunCommand( execPath, "forkgetnet", fmt.Sprintf("%d", pid)) // Process forkgetnet response if err != nil { logger.Error("Error calling 'lxd forkgetnet", log.Ctx{"container": c.name, "output": string(out), "pid": pid}) return result } networks := map[string]api.ContainerStateNetwork{} err = json.Unmarshal([]byte(out), &networks) if err != nil { logger.Error("Failure to read forkgetnet json", log.Ctx{"container": c.name, "err": err}) return result } // Add HostName field for netName, net := range networks { net.HostName = c.getHostInterface(netName) result[netName] = net } return result } func (c *containerLXC) processesState() int64 { // Return 0 if not running pid := c.InitPID() if pid == -1 { return 0 } if cgPidsController { value, err := c.CGroupGet("pids.current") valueInt, err := strconv.ParseInt(value, 10, 64) if err != nil { return -1 } return valueInt } pids := []int64{int64(pid)} // Go through the pid list, adding new pids at the end so we go through them all for i := 0; i < len(pids); i++ { fname := fmt.Sprintf("/proc/%d/task/%d/children", pids[i], pids[i]) fcont, err := ioutil.ReadFile(fname) if err != nil { // the process terminated during execution of this loop continue } content := strings.Split(string(fcont), " ") for j := 0; j < len(content); j++ { pid, err := strconv.ParseInt(content[j], 10, 64) if err == nil { pids = append(pids, pid) } } } return int64(len(pids)) } func (c *containerLXC) tarStoreFile(linkmap map[uint64]string, offset int, tw *tar.Writer, path string, fi os.FileInfo) error { var err error var major, minor, nlink int var ino uint64 link := "" if fi.Mode()&os.ModeSymlink == os.ModeSymlink { link, err = os.Readlink(path) if err != nil { return fmt.Errorf("failed to resolve symlink: %s", err) } } hdr, err := tar.FileInfoHeader(fi, link) if err != nil { return fmt.Errorf("failed to create tar info header: %s", err) } hdr.Name = path[offset:] if fi.IsDir() || fi.Mode()&os.ModeSymlink == os.ModeSymlink { hdr.Size = 0 } else { hdr.Size = fi.Size() } hdr.Uid, hdr.Gid, major, minor, ino, nlink, err = shared.GetFileStat(path) if err != nil { return fmt.Errorf("failed to get file stat: %s", err) } // Unshift the id under /rootfs/ for unpriv containers if !c.IsPrivileged() && strings.HasPrefix(hdr.Name, "/rootfs") { idmapset, err := c.IdmapSet() if err != nil { return err } huid, hgid := idmapset.ShiftFromNs(int64(hdr.Uid), int64(hdr.Gid)) hdr.Uid = int(huid) hdr.Gid = int(hgid) if hdr.Uid == -1 || hdr.Gid == -1 { return nil } } if major != -1 { hdr.Devmajor = int64(major) hdr.Devminor = int64(minor) } // If it's a hardlink we've already seen use the old name if fi.Mode().IsRegular() && nlink > 1 { if firstpath, found := linkmap[ino]; found { hdr.Typeflag = tar.TypeLink hdr.Linkname = firstpath hdr.Size = 0 } else { linkmap[ino] = hdr.Name } } // Handle xattrs (for real files only) if link == "" { hdr.Xattrs, err = shared.GetAllXattr(path) if err != nil { return fmt.Errorf("failed to read xattr: %s", err) } } if err := tw.WriteHeader(hdr); err != nil { return fmt.Errorf("failed to write tar header: %s", err) } if hdr.Typeflag == tar.TypeReg { f, err := os.Open(path) if err != nil { return fmt.Errorf("failed to open the file: %s", err) } defer f.Close() if _, err := io.Copy(tw, f); err != nil { return fmt.Errorf("failed to copy file content: %s", err) } } return nil } // Storage functions func (c *containerLXC) Storage() storage { return c.storage } func (c *containerLXC) StorageStart() error { if c.IsSnapshot() { return c.storage.ContainerSnapshotStart(c) } return c.storage.ContainerStart(c.Name(), c.Path()) } func (c *containerLXC) StorageStop() error { if c.IsSnapshot() { return c.storage.ContainerSnapshotStop(c) } return c.storage.ContainerStop(c.Name(), c.Path()) } // Mount handling func (c *containerLXC) insertMount(source, target, fstype string, flags int) error { var err error // Get the init PID pid := c.InitPID() if pid == -1 { // Container isn't running return fmt.Errorf("Can't insert mount into stopped container") } // Create the temporary mount target var tmpMount string if shared.IsDir(source) { tmpMount, err = ioutil.TempDir(shared.VarPath("shmounts", c.name), "lxdmount_") if err != nil { return fmt.Errorf("Failed to create shmounts path: %s", err) } } else { f, err := ioutil.TempFile(shared.VarPath("shmounts", c.name), "lxdmount_") if err != nil { return fmt.Errorf("Failed to create shmounts path: %s", err) } tmpMount = f.Name() f.Close() } defer os.Remove(tmpMount) // Mount the filesystem err = syscall.Mount(source, tmpMount, fstype, uintptr(flags), "") if err != nil { return fmt.Errorf("Failed to setup temporary mount: %s", err) } defer syscall.Unmount(tmpMount, syscall.MNT_DETACH) // Move the mount inside the container mntsrc := filepath.Join("/dev/.lxd-mounts", filepath.Base(tmpMount)) pidStr := fmt.Sprintf("%d", pid) out, err := shared.RunCommand(execPath, "forkmount", pidStr, mntsrc, target) if string(out) != "" { for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { logger.Debugf("forkmount: %s", line) } } if err != nil { return fmt.Errorf( "Error calling 'lxd forkmount %s %s %s': err='%v'", pidStr, mntsrc, target, err) } return nil } func (c *containerLXC) removeMount(mount string) error { // Get the init PID pid := c.InitPID() if pid == -1 { // Container isn't running return fmt.Errorf("Can't remove mount from stopped container") } // Remove the mount from the container pidStr := fmt.Sprintf("%d", pid) out, err := shared.RunCommand(execPath, "forkumount", pidStr, mount) if string(out) != "" { for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { logger.Debugf("forkumount: %s", line) } } if err != nil { return fmt.Errorf( "Error calling 'lxd forkumount %s %s': err='%v'", pidStr, mount, err) } return nil } // Unix devices handling func (c *containerLXC) createUnixDevice(m types.Device) (string, error) { var err error var major, minor int // Our device paths srcPath := m["path"] tgtPath := strings.TrimPrefix(srcPath, "/") devName := fmt.Sprintf("unix.%s", strings.Replace(tgtPath, "/", "-", -1)) devPath := filepath.Join(c.DevicesPath(), devName) // Extra checks for nesting if runningInUserns { for key, value := range m { if shared.StringInSlice(key, []string{"major", "minor", "mode", "uid", "gid"}) && value != "" { return "", fmt.Errorf("The \"%s\" property may not be set when adding a device to a nested container", key) } } } // Get the major/minor of the device we want to create if m["major"] == "" && m["minor"] == "" { // If no major and minor are set, use those from the device on the host _, major, minor, err = deviceGetAttributes(srcPath) if err != nil { return "", fmt.Errorf("Failed to get device attributes for %s: %s", m["path"], err) } } else if m["major"] == "" || m["minor"] == "" { return "", fmt.Errorf("Both major and minor must be supplied for device: %s", m["path"]) } else { major, err = strconv.Atoi(m["major"]) if err != nil { return "", fmt.Errorf("Bad major %s in device %s", m["major"], m["path"]) } minor, err = strconv.Atoi(m["minor"]) if err != nil { return "", fmt.Errorf("Bad minor %s in device %s", m["minor"], m["path"]) } } // Get the device mode mode := os.FileMode(0660) if m["mode"] != "" { tmp, err := deviceModeOct(m["mode"]) if err != nil { return "", fmt.Errorf("Bad mode %s in device %s", m["mode"], m["path"]) } mode = os.FileMode(tmp) } if m["type"] == "unix-block" { mode |= syscall.S_IFBLK } else { mode |= syscall.S_IFCHR } // Get the device owner uid := 0 gid := 0 if m["uid"] != "" { uid, err = strconv.Atoi(m["uid"]) if err != nil { return "", fmt.Errorf("Invalid uid %s in device %s", m["uid"], m["path"]) } } if m["gid"] != "" { gid, err = strconv.Atoi(m["gid"]) if err != nil { return "", fmt.Errorf("Invalid gid %s in device %s", m["gid"], m["path"]) } } // Create the devices directory if missing if !shared.PathExists(c.DevicesPath()) { os.Mkdir(c.DevicesPath(), 0711) if err != nil { return "", fmt.Errorf("Failed to create devices path: %s", err) } } // Clean any existing entry if shared.PathExists(devPath) { if runningInUserns { syscall.Unmount(devPath, syscall.MNT_DETACH) } err = os.Remove(devPath) if err != nil { return "", fmt.Errorf("Failed to remove existing entry: %s", err) } } // Create the new entry if !runningInUserns { encoded_device_number := (minor & 0xff) | (major << 8) | ((minor & ^0xff) << 12) if err := syscall.Mknod(devPath, uint32(mode), encoded_device_number); err != nil { return "", fmt.Errorf("Failed to create device %s for %s: %s", devPath, m["path"], err) } if err := os.Chown(devPath, uid, gid); err != nil { return "", fmt.Errorf("Failed to chown device %s: %s", devPath, err) } // Needed as mknod respects the umask if err := os.Chmod(devPath, mode); err != nil { return "", fmt.Errorf("Failed to chmod device %s: %s", devPath, err) } idmapset, err := c.IdmapSet() if err != nil { return "", err } if idmapset != nil { if err := idmapset.ShiftFile(devPath); err != nil { // uidshift failing is weird, but not a big problem. Log and proceed logger.Debugf("Failed to uidshift device %s: %s\n", m["path"], err) } } } else { f, err := os.Create(devPath) if err != nil { return "", err } f.Close() err = deviceMountDisk(srcPath, devPath, false, false) if err != nil { return "", err } } return devPath, nil } func (c *containerLXC) insertUnixDevice(name string, m types.Device) error { // Check that the container is running if !c.IsRunning() { return fmt.Errorf("Can't insert device into stopped container") } // Create the device on the host devPath, err := c.createUnixDevice(m) if err != nil { return fmt.Errorf("Failed to setup device: %s", err) } // Bind-mount it into the container tgtPath := strings.TrimSuffix(m["path"], "/") err = c.insertMount(devPath, tgtPath, "none", syscall.MS_BIND) if err != nil { return fmt.Errorf("Failed to add mount for device: %s", err) } // Check if we've been passed major and minor numbers already. var tmp int dMajor := -1 if m["major"] != "" { tmp, err = strconv.Atoi(m["major"]) if err == nil { dMajor = tmp } } dMinor := -1 if m["minor"] != "" { tmp, err = strconv.Atoi(m["minor"]) if err == nil { dMinor = tmp } } dType := "" if m["type"] == "unix-char" { dType = "c" } else if m["type"] == "unix-block" { dType = "b" } if dType == "" || dMajor < 0 || dMinor < 0 { dType, dMajor, dMinor, err = deviceGetAttributes(devPath) if err != nil { return err } } if c.IsPrivileged() && !runningInUserns && cgDevicesController { // Add the new device cgroup rule if err := c.CGroupSet("devices.allow", fmt.Sprintf("%s %d:%d rwm", dType, dMajor, dMinor)); err != nil { return fmt.Errorf("Failed to add cgroup rule for device") } } return nil } func (c *containerLXC) removeUnixDevice(m types.Device) error { // Check that the container is running pid := c.InitPID() if pid == -1 { return fmt.Errorf("Can't remove device from stopped container") } // Figure out the paths srcPath := m["path"] tgtPath := strings.TrimPrefix(srcPath, "/") devName := fmt.Sprintf("unix.%s", strings.Replace(tgtPath, "/", "-", -1)) devPath := filepath.Join(c.DevicesPath(), devName) // Check if we've been passed major and minor numbers already. var tmp int var err error dMajor := -1 if m["major"] != "" { tmp, err = strconv.Atoi(m["major"]) if err == nil { dMajor = tmp } } dMinor := -1 if m["minor"] != "" { tmp, err = strconv.Atoi(m["minor"]) if err == nil { dMinor = tmp } } dType := "" if m["type"] != "" { dType = m["type"] } if dType == "" || dMajor < 0 || dMinor < 0 { dType, dMajor, dMinor, err = deviceGetAttributes(devPath) if err != nil { return err } } if c.IsPrivileged() && !runningInUserns && cgDevicesController { // Remove the device cgroup rule err = c.CGroupSet("devices.deny", fmt.Sprintf("%s %d:%d rwm", dType, dMajor, dMinor)) if err != nil { return err } } // Remove the bind-mount from the container if c.FileExists(tgtPath) == nil { err = c.removeMount(m["path"]) if err != nil { return fmt.Errorf("Error unmounting the device: %s", err) } err = c.FileRemove(tgtPath) if err != nil { return fmt.Errorf("Error removing the device: %s", err) } } // Remove the host side if runningInUserns { syscall.Unmount(devPath, syscall.MNT_DETACH) } err = os.Remove(devPath) if err != nil { return err } return nil } func (c *containerLXC) removeUnixDevices() error { // Check that we indeed have devices to remove if !shared.PathExists(c.DevicesPath()) { return nil } // Load the directory listing dents, err := ioutil.ReadDir(c.DevicesPath()) if err != nil { return err } // Go through all the unix devices for _, f := range dents { // Skip non-Unix devices if !strings.HasPrefix(f.Name(), "unix.") { continue } // Remove the entry devicePath := filepath.Join(c.DevicesPath(), f.Name()) err := os.Remove(devicePath) if err != nil { logger.Error("failed removing unix device", log.Ctx{"err": err, "path": devicePath}) } } return nil } // Network device handling func (c *containerLXC) createNetworkDevice(name string, m types.Device) (string, error) { var dev, n1 string if shared.StringInSlice(m["nictype"], []string{"bridged", "p2p", "macvlan"}) { // Host Virtual NIC name if m["host_name"] != "" { n1 = m["host_name"] } else { n1 = deviceNextVeth() } } // Handle bridged and p2p if shared.StringInSlice(m["nictype"], []string{"bridged", "p2p"}) { n2 := deviceNextVeth() _, err := shared.RunCommand("ip", "link", "add", "dev", n1, "type", "veth", "peer", "name", n2) if err != nil { return "", fmt.Errorf("Failed to create the veth interface: %s", err) } _, err = shared.RunCommand("ip", "link", "set", "dev", n1, "up") if err != nil { return "", fmt.Errorf("Failed to bring up the veth interface %s: %s", n1, err) } if m["nictype"] == "bridged" { if shared.PathExists(fmt.Sprintf("/sys/class/net/%s/bridge", m["parent"])) { _, err = shared.RunCommand("ip", "link", "set", "dev", n1, "master", m["parent"]) if err != nil { deviceRemoveInterface(n2) return "", fmt.Errorf("Failed to add interface to bridge: %s", err) } } else { _, err = shared.RunCommand("ovs-vsctl", "add-port", m["parent"], n1) if err != nil { deviceRemoveInterface(n2) return "", fmt.Errorf("Failed to add interface to bridge: %s", err) } } // Attempt to disable IPv6 on the host side interface if shared.PathExists(fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", n1)) { ioutil.WriteFile(fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", n1), []byte("1"), 0644) } } dev = n2 } // Handle physical if m["nictype"] == "physical" { dev = m["parent"] } // Handle macvlan if m["nictype"] == "macvlan" { _, err := shared.RunCommand("ip", "link", "add", "dev", n1, "link", m["parent"], "type", "macvlan", "mode", "bridge") if err != nil { return "", fmt.Errorf("Failed to create the new macvlan interface: %s", err) } dev = n1 } // Set the MAC address if m["hwaddr"] != "" { _, err := shared.RunCommand("ip", "link", "set", "dev", dev, "address", m["hwaddr"]) if err != nil { deviceRemoveInterface(dev) return "", fmt.Errorf("Failed to set the MAC address: %s", err) } } // Bring the interface up _, err := shared.RunCommand("ip", "link", "set", "dev", dev, "up") if err != nil { deviceRemoveInterface(dev) return "", fmt.Errorf("Failed to bring up the interface: %s", err) } return dev, nil } func (c *containerLXC) fillNetworkDevice(name string, m types.Device) (types.Device, error) { newDevice := types.Device{} err := shared.DeepCopy(&m, &newDevice) if err != nil { return nil, err } // Function to try and guess an available name nextInterfaceName := func() (string, error) { devNames := []string{} // Include all static interface names for _, k := range c.expandedDevices.DeviceNames() { v := c.expandedDevices[k] if v["name"] != "" && !shared.StringInSlice(v["name"], devNames) { devNames = append(devNames, v["name"]) } } // Include all currently allocated interface names for k, v := range c.expandedConfig { if !strings.HasPrefix(k, "volatile.") { continue } fields := strings.SplitN(k, ".", 3) if len(fields) != 3 { continue } if fields[2] != "name" || shared.StringInSlice(v, devNames) { continue } devNames = append(devNames, v) } // Attempt to include all existing interfaces cc, err := lxc.NewContainer(c.Name(), c.state.OS.LxcPath) if err == nil { interfaces, err := cc.Interfaces() if err == nil { for _, name := range interfaces { if shared.StringInSlice(name, devNames) { continue } devNames = append(devNames, name) } } } // Find a free ethX device i := 0 for { name := fmt.Sprintf("eth%d", i) if !shared.StringInSlice(name, devNames) { return name, nil } i += 1 } } updateKey := func(key string, value string) error { tx, err := db.Begin(c.state.DB) if err != nil { return err } err = db.ContainerConfigInsert(tx, c.id, map[string]string{key: value}) if err != nil { tx.Rollback() return err } err = db.TxCommit(tx) if err != nil { return err } return nil } // Fill in the MAC address if m["nictype"] != "physical" && m["hwaddr"] == "" { configKey := fmt.Sprintf("volatile.%s.hwaddr", name) volatileHwaddr := c.localConfig[configKey] if volatileHwaddr == "" { // Generate a new MAC address volatileHwaddr, err = deviceNextInterfaceHWAddr() if err != nil { return nil, err } // Update the database err = updateKey(configKey, volatileHwaddr) if err != nil { // Check if something else filled it in behind our back value, err1 := db.ContainerConfigGet(c.state.DB, c.id, configKey) if err1 != nil || value == "" { return nil, err } c.localConfig[configKey] = value c.expandedConfig[configKey] = value } else { c.localConfig[configKey] = volatileHwaddr c.expandedConfig[configKey] = volatileHwaddr } } newDevice["hwaddr"] = volatileHwaddr } // Fill in the name if m["name"] == "" { configKey := fmt.Sprintf("volatile.%s.name", name) volatileName := c.localConfig[configKey] if volatileName == "" { // Generate a new interface name volatileName, err = nextInterfaceName() if err != nil { return nil, err } // Update the database err = updateKey(configKey, volatileName) if err != nil { // Check if something else filled it in behind our back value, err1 := db.ContainerConfigGet(c.state.DB, c.id, configKey) if err1 != nil || value == "" { return nil, err } c.localConfig[configKey] = value c.expandedConfig[configKey] = value } else { c.localConfig[configKey] = volatileName c.expandedConfig[configKey] = volatileName } } newDevice["name"] = volatileName } // Fill in the host name (but don't generate a static one ourselves) if m["host_name"] == "" && shared.StringInSlice(m["nictype"], []string{"bridged", "p2p"}) { configKey := fmt.Sprintf("volatile.%s.host_name", name) newDevice["host_name"] = c.localConfig[configKey] } return newDevice, nil } func (c *containerLXC) insertNetworkDevice(name string, m types.Device) error { // Load the go-lxc struct err := c.initLXC() if err != nil { return nil } // Fill in some fields from volatile m, err = c.fillNetworkDevice(name, m) if err != nil { return nil } if m["parent"] != "" && !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", m["parent"])) { return fmt.Errorf("Parent device '%s' doesn't exist", m["parent"]) } // Return empty list if not running if !c.IsRunning() { return fmt.Errorf("Can't insert device into stopped container") } // Create the interface devName, err := c.createNetworkDevice(name, m) if err != nil { return err } // Add the interface to the container err = c.c.AttachInterface(devName, m["name"]) if err != nil { return fmt.Errorf("Failed to attach interface: %s: %s", devName, err) } return nil } func (c *containerLXC) removeNetworkDevice(name string, m types.Device) error { // Load the go-lxc struct err := c.initLXC() if err != nil { return nil } // Fill in some fields from volatile m, err = c.fillNetworkDevice(name, m) if err != nil { return nil } // Return empty list if not running if !c.IsRunning() { return fmt.Errorf("Can't insert device into stopped container") } // Get a temporary device name var hostName string if m["nictype"] == "physical" { hostName = m["parent"] } else { hostName = deviceNextVeth() } // For some reason, having network config confuses detach, so get our own go-lxc struct cc, err := lxc.NewContainer(c.Name(), c.state.OS.LxcPath) if err != nil { return err } // Remove the interface from the container err = cc.DetachInterfaceRename(m["name"], hostName) if err != nil { return fmt.Errorf("Failed to detach interface: %s: %s", m["name"], err) } // If a veth, destroy it if m["nictype"] != "physical" { deviceRemoveInterface(hostName) } return nil } // Disk device handling func (c *containerLXC) createDiskDevice(name string, m types.Device) (string, error) { // Prepare all the paths srcPath := shared.HostPath(m["source"]) tgtPath := strings.TrimPrefix(m["path"], "/") devName := fmt.Sprintf("disk.%s", strings.Replace(tgtPath, "/", "-", -1)) devPath := filepath.Join(c.DevicesPath(), devName) // Check if read-only isOptional := shared.IsTrue(m["optional"]) isReadOnly := shared.IsTrue(m["readonly"]) isRecursive := shared.IsTrue(m["recursive"]) isFile := !shared.IsDir(srcPath) && !deviceIsBlockdev(srcPath) // Check if the source exists if !shared.PathExists(srcPath) { if isOptional { return "", nil } return "", fmt.Errorf("Source path %s doesn't exist for device %s", srcPath, name) } // Create the devices directory if missing if !shared.PathExists(c.DevicesPath()) { err := os.Mkdir(c.DevicesPath(), 0711) if err != nil { return "", err } } // Clean any existing entry if shared.PathExists(devPath) { err := os.Remove(devPath) if err != nil { return "", err } } // Create the mount point if isFile { f, err := os.Create(devPath) if err != nil { return "", err } f.Close() } else { err := os.Mkdir(devPath, 0700) if err != nil { return "", err } } // Mount the fs err := deviceMountDisk(srcPath, devPath, isReadOnly, isRecursive) if err != nil { return "", err } return devPath, nil } func (c *containerLXC) insertDiskDevice(name string, m types.Device) error { // Check that the container is running if !c.IsRunning() { return fmt.Errorf("Can't insert device into stopped container") } isRecursive := shared.IsTrue(m["recursive"]) // Create the device on the host devPath, err := c.createDiskDevice(name, m) if err != nil { return fmt.Errorf("Failed to setup device: %s", err) } flags := syscall.MS_BIND if isRecursive { flags |= syscall.MS_REC } // Bind-mount it into the container tgtPath := strings.TrimSuffix(m["path"], "/") err = c.insertMount(devPath, tgtPath, "none", flags) if err != nil { return fmt.Errorf("Failed to add mount for device: %s", err) } return nil } type byPath []types.Device func (a byPath) Len() int { return len(a) } func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byPath) Less(i, j int) bool { return a[i]["path"] < a[j]["path"] } func (c *containerLXC) addDiskDevices(devices map[string]types.Device, handler func(string, types.Device) error) error { ordered := byPath{} for _, d := range devices { ordered = append(ordered, d) } sort.Sort(ordered) for _, d := range ordered { err := handler(d["path"], d) if err != nil { return err } } return nil } func (c *containerLXC) removeDiskDevice(name string, m types.Device) error { // Check that the container is running pid := c.InitPID() if pid == -1 { return fmt.Errorf("Can't remove device from stopped container") } // Figure out the paths tgtPath := strings.TrimPrefix(m["path"], "/") devName := fmt.Sprintf("disk.%s", strings.Replace(tgtPath, "/", "-", -1)) devPath := filepath.Join(c.DevicesPath(), devName) // The dsk device doesn't exist and cannot be mounted. if !shared.PathExists(devPath) { return nil } // Remove the bind-mount from the container if c.FileExists(tgtPath) == nil { err := c.removeMount(m["path"]) if err != nil { return fmt.Errorf("Error unmounting the device: %s", err) } } // Unmount the host side err := syscall.Unmount(devPath, syscall.MNT_DETACH) if err != nil { return err } // Remove the host side err = os.Remove(devPath) if err != nil { return err } return nil } func (c *containerLXC) removeDiskDevices() error { // Check that we indeed have devices to remove if !shared.PathExists(c.DevicesPath()) { return nil } // Load the directory listing dents, err := ioutil.ReadDir(c.DevicesPath()) if err != nil { return err } // Go through all the unix devices for _, f := range dents { // Skip non-Unix devices if !strings.HasPrefix(f.Name(), "disk.") { continue } // Always try to unmount the host side _ = syscall.Unmount(filepath.Join(c.DevicesPath(), f.Name()), syscall.MNT_DETACH) // Remove the entry diskPath := filepath.Join(c.DevicesPath(), f.Name()) err := os.Remove(diskPath) if err != nil { logger.Error("Failed to remove disk device path", log.Ctx{"err": err, "path": diskPath}) } } return nil } // Block I/O limits func (c *containerLXC) getDiskLimits() (map[string]deviceBlockLimit, error) { result := map[string]deviceBlockLimit{} // Build a list of all valid block devices validBlocks := []string{} dents, err := ioutil.ReadDir("/sys/class/block/") if err != nil { return nil, err } for _, f := range dents { fPath := filepath.Join("/sys/class/block/", f.Name()) if shared.PathExists(fmt.Sprintf("%s/partition", fPath)) { continue } if !shared.PathExists(fmt.Sprintf("%s/dev", fPath)) { continue } block, err := ioutil.ReadFile(fmt.Sprintf("%s/dev", fPath)) if err != nil { return nil, err } validBlocks = append(validBlocks, strings.TrimSuffix(string(block), "\n")) } // Process all the limits blockLimits := map[string][]deviceBlockLimit{} for _, k := range c.expandedDevices.DeviceNames() { m := c.expandedDevices[k] if m["type"] != "disk" { continue } // Apply max limit if m["limits.max"] != "" { m["limits.read"] = m["limits.max"] m["limits.write"] = m["limits.max"] } // Parse the user input readBps, readIops, writeBps, writeIops, err := deviceParseDiskLimit(m["limits.read"], m["limits.write"]) if err != nil { return nil, err } // Set the source path source := shared.HostPath(m["source"]) if source == "" { source = c.RootfsPath() } // Don't try to resolve the block device behind a non-existing path if !shared.PathExists(source) { continue } // Get the backing block devices (major:minor) blocks, err := deviceGetParentBlocks(source) if err != nil { if readBps == 0 && readIops == 0 && writeBps == 0 && writeIops == 0 { // If the device doesn't exist, there is no limit to clear so ignore the failure continue } else { return nil, err } } device := deviceBlockLimit{readBps: readBps, readIops: readIops, writeBps: writeBps, writeIops: writeIops} for _, block := range blocks { blockStr := "" if shared.StringInSlice(block, validBlocks) { // Straightforward entry (full block device) blockStr = block } else { // Attempt to deal with a partition (guess its parent) fields := strings.SplitN(block, ":", 2) fields[1] = "0" if shared.StringInSlice(fmt.Sprintf("%s:%s", fields[0], fields[1]), validBlocks) { blockStr = fmt.Sprintf("%s:%s", fields[0], fields[1]) } } if blockStr == "" { return nil, fmt.Errorf("Block device doesn't support quotas: %s", block) } if blockLimits[blockStr] == nil { blockLimits[blockStr] = []deviceBlockLimit{} } blockLimits[blockStr] = append(blockLimits[blockStr], device) } } // Average duplicate limits for block, limits := range blockLimits { var readBpsCount, readBpsTotal, readIopsCount, readIopsTotal, writeBpsCount, writeBpsTotal, writeIopsCount, writeIopsTotal int64 for _, limit := range limits { if limit.readBps > 0 { readBpsCount += 1 readBpsTotal += limit.readBps } if limit.readIops > 0 { readIopsCount += 1 readIopsTotal += limit.readIops } if limit.writeBps > 0 { writeBpsCount += 1 writeBpsTotal += limit.writeBps } if limit.writeIops > 0 { writeIopsCount += 1 writeIopsTotal += limit.writeIops } } device := deviceBlockLimit{} if readBpsCount > 0 { device.readBps = readBpsTotal / readBpsCount } if readIopsCount > 0 { device.readIops = readIopsTotal / readIopsCount } if writeBpsCount > 0 { device.writeBps = writeBpsTotal / writeBpsCount } if writeIopsCount > 0 { device.writeIops = writeIopsTotal / writeIopsCount } result[block] = device } return result, nil } // Network I/O limits func (c *containerLXC) setNetworkPriority() error { // Check that the container is running if !c.IsRunning() { return fmt.Errorf("Can't set network priority on stopped container") } // Don't bother if the cgroup controller doesn't exist if !cgNetPrioController { return nil } // Extract the current priority networkPriority := c.expandedConfig["limits.network.priority"] if networkPriority == "" { networkPriority = "0" } networkInt, err := strconv.Atoi(networkPriority) if err != nil { return err } // Get all the interfaces netifs, err := net.Interfaces() if err != nil { return err } // Check that we at least succeeded to set an entry success := false var last_error error for _, netif := range netifs { err = c.CGroupSet("net_prio.ifpriomap", fmt.Sprintf("%s %d", netif.Name, networkInt)) if err == nil { success = true } else { last_error = err } } if !success { return fmt.Errorf("Failed to set network device priority: %s", last_error) } return nil } func (c *containerLXC) getHostInterface(name string) string { if c.IsRunning() { networkKeyPrefix := "lxc.net" if !lxc.VersionAtLeast(2, 1, 0) { networkKeyPrefix = "lxc.network" } for i := 0; i < len(c.c.ConfigItem(networkKeyPrefix)); i++ { nicName := c.c.RunningConfigItem(fmt.Sprintf("%s.%d.name", networkKeyPrefix, i))[0] if nicName != name { continue } veth := c.c.RunningConfigItem(fmt.Sprintf("%s.%d.veth.pair", networkKeyPrefix, i))[0] if veth != "" { return veth } } } for _, k := range c.expandedDevices.DeviceNames() { dev := c.expandedDevices[k] if dev["type"] != "nic" { continue } m, err := c.fillNetworkDevice(k, dev) if err != nil { m = dev } if m["name"] != name { continue } return m["host_name"] } return "" } func (c *containerLXC) setNetworkLimits(name string, m types.Device) error { // We can only do limits on some network type if m["nictype"] != "bridged" && m["nictype"] != "p2p" { return fmt.Errorf("Network limits are only supported on bridged and p2p interfaces") } // Load the go-lxc struct err := c.initLXC() if err != nil { return err } // Check that the container is running if !c.IsRunning() { return fmt.Errorf("Can't set network limits on stopped container") } // Fill in some fields from volatile m, err = c.fillNetworkDevice(name, m) if err != nil { return nil } // Look for the host side interface name veth := c.getHostInterface(m["name"]) if veth == "" { return fmt.Errorf("LXC doesn't know about this device and the host_name property isn't set, can't find host side veth name") } // Apply max limit if m["limits.max"] != "" { m["limits.ingress"] = m["limits.max"] m["limits.egress"] = m["limits.max"] } // Parse the values var ingressInt int64 if m["limits.ingress"] != "" { ingressInt, err = shared.ParseBitSizeString(m["limits.ingress"]) if err != nil { return err } } var egressInt int64 if m["limits.egress"] != "" { egressInt, err = shared.ParseBitSizeString(m["limits.egress"]) if err != nil { return err } } // Clean any existing entry shared.RunCommand("tc", "qdisc", "del", "dev", veth, "root") shared.RunCommand("tc", "qdisc", "del", "dev", veth, "ingress") // Apply new limits if m["limits.ingress"] != "" { out, err := shared.RunCommand("tc", "qdisc", "add", "dev", veth, "root", "handle", "1:0", "htb", "default", "10") if err != nil { return fmt.Errorf("Failed to create root tc qdisc: %s", out) } out, err = shared.RunCommand("tc", "class", "add", "dev", veth, "parent", "1:0", "classid", "1:10", "htb", "rate", fmt.Sprintf("%dbit", ingressInt)) if err != nil { return fmt.Errorf("Failed to create limit tc class: %s", out) } out, err = shared.RunCommand("tc", "filter", "add", "dev", veth, "parent", "1:0", "protocol", "all", "u32", "match", "u32", "0", "0", "flowid", "1:1") if err != nil { return fmt.Errorf("Failed to create tc filter: %s", out) } } if m["limits.egress"] != "" { out, err := shared.RunCommand("tc", "qdisc", "add", "dev", veth, "handle", "ffff:0", "ingress") if err != nil { return fmt.Errorf("Failed to create ingress tc qdisc: %s", out) } out, err = shared.RunCommand("tc", "filter", "add", "dev", veth, "parent", "ffff:0", "protocol", "all", "u32", "match", "u32", "0", "0", "police", "rate", fmt.Sprintf("%dbit", egressInt), "burst", "1024k", "mtu", "64kb", "drop", "flowid", ":1") if err != nil { return fmt.Errorf("Failed to create ingress tc qdisc: %s", out) } } return nil } // Various state query functions func (c *containerLXC) IsStateful() bool { return c.stateful } func (c *containerLXC) IsEphemeral() bool { return c.ephemeral } func (c *containerLXC) IsFrozen() bool { return c.State() == "FROZEN" } func (c *containerLXC) IsNesting() bool { return shared.IsTrue(c.expandedConfig["security.nesting"]) } func (c *containerLXC) IsPrivileged() bool { return shared.IsTrue(c.expandedConfig["security.privileged"]) } func (c *containerLXC) IsRunning() bool { state := c.State() return state != "BROKEN" && state != "STOPPED" } func (c *containerLXC) IsSnapshot() bool { return c.cType == db.CTypeSnapshot } // Various property query functions func (c *containerLXC) Architecture() int { return c.architecture } func (c *containerLXC) CreationDate() time.Time { return c.creationDate } func (c *containerLXC) ExpandedConfig() map[string]string { return c.expandedConfig } func (c *containerLXC) ExpandedDevices() types.Devices { return c.expandedDevices } func (c *containerLXC) Id() int { return c.id } func (c *containerLXC) IdmapSet() (*idmap.IdmapSet, error) { var err error if c.idmapset != nil { return c.idmapset, nil } if c.IsPrivileged() { return nil, nil } c.idmapset, err = c.NextIdmapSet() if err != nil { return nil, err } return c.idmapset, nil } func (c *containerLXC) InitPID() int { // Load the go-lxc struct err := c.initLXC() if err != nil { return -1 } return c.c.InitPid() } func (c *containerLXC) LocalConfig() map[string]string { return c.localConfig } func (c *containerLXC) LocalDevices() types.Devices { return c.localDevices } func (c *containerLXC) idmapsetFromConfig(k string) (*idmap.IdmapSet, error) { lastJsonIdmap := c.LocalConfig()[k] if lastJsonIdmap == "" { return c.IdmapSet() } lastIdmap := new(idmap.IdmapSet) err := json.Unmarshal([]byte(lastJsonIdmap), &lastIdmap.Idmap) if err != nil { return nil, err } if len(lastIdmap.Idmap) == 0 { return nil, nil } return lastIdmap, nil } func (c *containerLXC) NextIdmapSet() (*idmap.IdmapSet, error) { if c.localConfig["volatile.idmap.next"] != "" { return c.idmapsetFromConfig("volatile.idmap.next") } else if c.IsPrivileged() { return nil, nil } else if c.state.OS.IdmapSet != nil { return c.state.OS.IdmapSet, nil } return nil, fmt.Errorf("Unable to determine the idmap") } func (c *containerLXC) LastIdmapSet() (*idmap.IdmapSet, error) { return c.idmapsetFromConfig("volatile.last_state.idmap") } func (c *containerLXC) StateObject() *state.State { // FIXME: This function should go away return c.state } func (c *containerLXC) Name() string { return c.name } func (c *containerLXC) Profiles() []string { return c.profiles } func (c *containerLXC) State() string { // Load the go-lxc struct err := c.initLXC() if err != nil { return "Broken" } state, err := c.getLxcState() if err != nil { return api.Error.String() } return state.String() } // Various container paths func (c *containerLXC) Path() string { return containerPath(c.Name(), c.IsSnapshot()) } func (c *containerLXC) DevicesPath() string { return shared.VarPath("devices", c.Name()) } func (c *containerLXC) LogPath() string { return shared.LogPath(c.Name()) } func (c *containerLXC) LogFilePath() string { return filepath.Join(c.LogPath(), "lxc.log") } func (c *containerLXC) RootfsPath() string { return filepath.Join(c.Path(), "rootfs") } func (c *containerLXC) TemplatesPath() string { return filepath.Join(c.Path(), "templates") } func (c *containerLXC) StatePath() string { /* FIXME: backwards compatibility: we used to use Join(RootfsPath(), * "state"), which was bad. Let's just check to see if that directory * exists. */ oldStatePath := filepath.Join(c.RootfsPath(), "state") if shared.IsDir(oldStatePath) { return oldStatePath } return filepath.Join(c.Path(), "state") } ����������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_logs.go��������������������������������������������������������������������0000644�0610621�0607500�00000004514�13172163242�017621� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "net/http" "os" "strings" "github.com/gorilla/mux" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/version" ) func containerLogsGet(d *Daemon, r *http.Request) Response { /* Let's explicitly *not* try to do a containerLoadByName here. In some * cases (e.g. when container creation failed), the container won't * exist in the DB but it does have some log files on disk. * * However, we should check this name and ensure it's a valid container * name just so that people can't list arbitrary directories. */ name := mux.Vars(r)["name"] if err := containerValidName(name); err != nil { return BadRequest(err) } result := []string{} dents, err := ioutil.ReadDir(shared.LogPath(name)) if err != nil { return SmartError(err) } for _, f := range dents { if !validLogFileName(f.Name()) { continue } result = append(result, fmt.Sprintf("/%s/containers/%s/logs/%s", version.APIVersion, name, f.Name())) } return SyncResponse(true, result) } var containerLogsCmd = Command{ name: "containers/{name}/logs", get: containerLogsGet, } func validLogFileName(fname string) bool { /* Let's just require that the paths be relative, so that we don't have * to deal with any escaping or whatever. */ return fname == "lxc.log" || fname == "lxc.conf" || strings.HasPrefix(fname, "migration_") || strings.HasPrefix(fname, "snapshot_") } func containerLogGet(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] file := mux.Vars(r)["file"] if err := containerValidName(name); err != nil { return BadRequest(err) } if !validLogFileName(file) { return BadRequest(fmt.Errorf("log file name %s not valid", file)) } ent := fileResponseEntry{ path: shared.LogPath(name, file), filename: file, } return FileResponse(r, []fileResponseEntry{ent}, nil, false) } func containerLogDelete(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] file := mux.Vars(r)["file"] if err := containerValidName(name); err != nil { return BadRequest(err) } if !validLogFileName(file) { return BadRequest(fmt.Errorf("log file name %s not valid", file)) } return SmartError(os.Remove(shared.LogPath(name, file))) } var containerLogCmd = Command{ name: "containers/{name}/logs/{file}", get: containerLogGet, delete: containerLogDelete, } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_instance_types.go����������������������������������������������������������0000644�0610621�0607500�00000011257�13172163242�021707� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "net/http" "strconv" "strings" "gopkg.in/yaml.v2" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/version" ) type instanceType struct { // Amount of CPUs (can be a fraction) CPU float32 `yaml:"cpu"` // Amount of memory in GB Memory float32 `yaml:"mem"` } var instanceTypes map[string]map[string]*instanceType func instanceSaveCache() error { if instanceTypes == nil { return nil } data, err := yaml.Marshal(&instanceTypes) if err != nil { return err } err = ioutil.WriteFile(shared.CachePath("instance_types.yaml"), data, 0600) if err != nil { return err } return nil } func instanceLoadCache() error { if !shared.PathExists(shared.CachePath("instance_types.yaml")) { return nil } content, err := ioutil.ReadFile(shared.CachePath("instance_types.yaml")) if err != nil { return err } err = yaml.Unmarshal(content, &instanceTypes) if err != nil { return err } return nil } func instanceRefreshTypes(d *Daemon) error { logger.Info("Updating instance types") // Attempt to download the new definitions downloadParse := func(filename string, target interface{}) error { url := fmt.Sprintf("https://images.linuxcontainers.org/meta/instance-types/%s", filename) httpClient, err := util.HTTPClient("", d.proxy) if err != nil { return err } httpReq, err := http.NewRequest("GET", url, nil) if err != nil { return err } httpReq.Header.Set("User-Agent", version.UserAgent) resp, err := httpClient.Do(httpReq) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("Failed to get %s", url) } content, err := ioutil.ReadAll(resp.Body) if err != nil { return err } err = yaml.Unmarshal(content, target) if err != nil { return err } return nil } // Set an initial value from the cache if instanceTypes == nil { instanceLoadCache() } // Get the list of instance type sources sources := map[string]string{} err := downloadParse(".yaml", &sources) if err != nil { logger.Warnf("Failed to update instance types: %v", err) return err } // Parse the individual files newInstanceTypes := map[string]map[string]*instanceType{} for name, filename := range sources { types := map[string]*instanceType{} err = downloadParse(filename, &types) if err != nil { logger.Warnf("Failed to update instance types: %v", err) return err } newInstanceTypes[name] = types } // Update the global map instanceTypes = newInstanceTypes // And save in the cache err = instanceSaveCache() if err != nil { logger.Warnf("Failed to update instance types cache: %v", err) return err } logger.Infof("Done updating instance types") return nil } func instanceParseType(value string) (map[string]string, error) { sourceName := "" sourceType := "" fields := strings.SplitN(value, ":", 2) // Check if the name of the source was provided if len(fields) != 2 { sourceType = value } else { sourceName = fields[0] sourceType = fields[1] } // If not, lets go look for a match if instanceTypes != nil && sourceName == "" { for name, types := range instanceTypes { _, ok := types[sourceType] if ok { if sourceName != "" { return nil, fmt.Errorf("Ambiguous instance type provided: %s", value) } sourceName = name } } } // Check if we have a limit for the provided value limits, ok := instanceTypes[sourceName][sourceType] if !ok { // Check if it's maybe just a resource limit if sourceName == "" && value != "" { newLimits := instanceType{} fields := strings.Split(value, "-") for _, field := range fields { if len(field) < 2 || (field[0] != 'c' && field[0] != 'm') { return nil, fmt.Errorf("Bad instance type: %s", value) } value, err := strconv.ParseFloat(field[1:], 32) if err != nil { return nil, err } if field[0] == 'c' { newLimits.CPU = float32(value) } else if field[0] == 'm' { newLimits.Memory = float32(value) } } limits = &newLimits } if limits == nil { return nil, fmt.Errorf("Provided instance type doesn't exist: %s", value) } } out := map[string]string{} // Handle CPU if limits.CPU > 0 { cpuCores := int(limits.CPU) if float32(cpuCores) < limits.CPU { cpuCores++ } cpuTime := int(limits.CPU / float32(cpuCores) * 100.0) out["limits.cpu"] = fmt.Sprintf("%d", cpuCores) if cpuTime < 100 { out["limits.cpu.allowance"] = fmt.Sprintf("%d%%", cpuTime) } } // Handle memory if limits.Memory > 0 { rawLimit := int64(limits.Memory * 1024) out["limits.memory"] = fmt.Sprintf("%dMB", rawLimit) } return out, nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_get.go���������������������������������������������������������������������0000644�0610621�0607500�00000000554�13172163242�017434� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "net/http" "github.com/gorilla/mux" ) func containerGet(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return SmartError(err) } state, err := c.Render() if err != nil { return SmartError(err) } return SyncResponse(true, state) } ����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_file.go��������������������������������������������������������������������0000644�0610621�0607500�00000004353�13172163242�017575� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "github.com/gorilla/mux" "github.com/lxc/lxd/shared" ) func containerFileHandler(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return SmartError(err) } path := r.FormValue("path") if path == "" { return BadRequest(fmt.Errorf("missing path argument")) } switch r.Method { case "GET": return containerFileGet(c, path, r) case "POST": return containerFilePut(c, path, r) default: return NotFound } } func containerFileGet(c container, path string, r *http.Request) Response { /* * Copy out of the ns to a temporary file, and then use that to serve * the request from. This prevents us from having to worry about stuff * like people breaking out of the container root by symlinks or * ../../../s etc. in the path, since we can just rely on the kernel * for correctness. */ temp, err := ioutil.TempFile("", "lxd_forkgetfile_") if err != nil { return InternalError(err) } defer temp.Close() // Pul the file from the container uid, gid, mode, err := c.FilePull(path, temp.Name()) if err != nil { return SmartError(err) } headers := map[string]string{ "X-LXD-uid": fmt.Sprintf("%d", uid), "X-LXD-gid": fmt.Sprintf("%d", gid), "X-LXD-mode": fmt.Sprintf("%04o", mode), } // Make a file response struct files := make([]fileResponseEntry, 1) files[0].identifier = filepath.Base(path) files[0].path = temp.Name() files[0].filename = filepath.Base(path) return FileResponse(r, files, headers, true) } func containerFilePut(c container, path string, r *http.Request) Response { // Extract file ownership and mode from headers uid, gid, mode, _, _ := shared.ParseLXDFileHeaders(r.Header) // Write file content to a tempfile temp, err := ioutil.TempFile("", "lxd_forkputfile_") if err != nil { return InternalError(err) } defer func() { temp.Close() os.Remove(temp.Name()) }() _, err = io.Copy(temp, r.Body) if err != nil { return InternalError(err) } // Transfer the file into the container err = c.FilePush(temp.Name(), path, uid, gid, mode) if err != nil { return InternalError(err) } return EmptySyncResponse } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_exec.go��������������������������������������������������������������������0000644�0610621�0607500�00000022213�13172163242�017575� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "os/exec" "strconv" "strings" "sync" "syscall" "github.com/gorilla/mux" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) type execWs struct { command []string container container env map[string]string rootUid int64 rootGid int64 conns map[int]*websocket.Conn connsLock sync.Mutex allConnected chan bool controlConnected chan bool interactive bool fds map[int]string width int height int } func (s *execWs) Metadata() interface{} { fds := shared.Jmap{} for fd, secret := range s.fds { if fd == -1 { fds["control"] = secret } else { fds[strconv.Itoa(fd)] = secret } } return shared.Jmap{"fds": fds} } func (s *execWs) Connect(op *operation, r *http.Request, w http.ResponseWriter) error { secret := r.FormValue("secret") if secret == "" { return fmt.Errorf("missing secret") } for fd, fdSecret := range s.fds { if secret == fdSecret { conn, err := shared.WebsocketUpgrader.Upgrade(w, r, nil) if err != nil { return err } s.connsLock.Lock() s.conns[fd] = conn s.connsLock.Unlock() if fd == -1 { s.controlConnected <- true return nil } s.connsLock.Lock() for i, c := range s.conns { if i != -1 && c == nil { s.connsLock.Unlock() return nil } } s.connsLock.Unlock() s.allConnected <- true return nil } } /* If we didn't find the right secret, the user provided a bad one, * which 403, not 404, since this operation actually exists */ return os.ErrPermission } func (s *execWs) Do(op *operation) error { <-s.allConnected var err error var ttys []*os.File var ptys []*os.File var stdin *os.File var stdout *os.File var stderr *os.File if s.interactive { ttys = make([]*os.File, 1) ptys = make([]*os.File, 1) ptys[0], ttys[0], err = shared.OpenPty(s.rootUid, s.rootGid) stdin = ttys[0] stdout = ttys[0] stderr = ttys[0] if s.width > 0 && s.height > 0 { shared.SetSize(int(ptys[0].Fd()), s.width, s.height) } } else { ttys = make([]*os.File, 3) ptys = make([]*os.File, 3) for i := 0; i < len(ttys); i++ { ptys[i], ttys[i], err = shared.Pipe() if err != nil { return err } } stdin = ptys[0] stdout = ttys[1] stderr = ttys[2] } controlExit := make(chan bool) attachedChildIsBorn := make(chan int) attachedChildIsDead := make(chan bool, 1) var wgEOF sync.WaitGroup if s.interactive { wgEOF.Add(1) go func() { attachedChildPid := <-attachedChildIsBorn select { case <-s.controlConnected: break case <-controlExit: return } for { s.connsLock.Lock() conn := s.conns[-1] s.connsLock.Unlock() mt, r, err := conn.NextReader() if mt == websocket.CloseMessage { break } if err != nil { logger.Debugf("Got error getting next reader %s", err) er, ok := err.(*websocket.CloseError) if !ok { break } if er.Code != websocket.CloseAbnormalClosure { break } // If an abnormal closure occurred, kill the attached process. err := syscall.Kill(attachedChildPid, syscall.SIGKILL) if err != nil { logger.Debugf("Failed to send SIGKILL to pid %d.", attachedChildPid) } else { logger.Debugf("Sent SIGKILL to pid %d.", attachedChildPid) } return } buf, err := ioutil.ReadAll(r) if err != nil { logger.Debugf("Failed to read message %s", err) break } command := api.ContainerExecControl{} if err := json.Unmarshal(buf, &command); err != nil { logger.Debugf("Failed to unmarshal control socket command: %s", err) continue } if command.Command == "window-resize" { winchWidth, err := strconv.Atoi(command.Args["width"]) if err != nil { logger.Debugf("Unable to extract window width: %s", err) continue } winchHeight, err := strconv.Atoi(command.Args["height"]) if err != nil { logger.Debugf("Unable to extract window height: %s", err) continue } err = shared.SetSize(int(ptys[0].Fd()), winchWidth, winchHeight) if err != nil { logger.Debugf("Failed to set window size to: %dx%d", winchWidth, winchHeight) continue } } } }() go func() { s.connsLock.Lock() conn := s.conns[0] s.connsLock.Unlock() logger.Debugf("Starting to mirror websocket") readDone, writeDone := shared.WebsocketExecMirror(conn, ptys[0], ptys[0], attachedChildIsDead, int(ptys[0].Fd())) <-readDone <-writeDone logger.Debugf("Finished to mirror websocket") conn.Close() wgEOF.Done() }() } else { wgEOF.Add(len(ttys) - 1) for i := 0; i < len(ttys); i++ { go func(i int) { if i == 0 { s.connsLock.Lock() conn := s.conns[i] s.connsLock.Unlock() <-shared.WebsocketRecvStream(ttys[i], conn) ttys[i].Close() } else { s.connsLock.Lock() conn := s.conns[i] s.connsLock.Unlock() <-shared.WebsocketSendStream(conn, ptys[i], -1) ptys[i].Close() wgEOF.Done() } }(i) } } finisher := func(cmdResult int, cmdErr error) error { for _, tty := range ttys { tty.Close() } s.connsLock.Lock() conn := s.conns[-1] s.connsLock.Unlock() if conn == nil { if s.interactive { controlExit <- true } } else { conn.Close() } attachedChildIsDead <- true wgEOF.Wait() for _, pty := range ptys { pty.Close() } metadata := shared.Jmap{"return": cmdResult} err = op.UpdateMetadata(metadata) if err != nil { return err } return cmdErr } cmd, _, attachedPid, err := s.container.Exec(s.command, s.env, stdin, stdout, stderr, false) if err != nil { return err } if s.interactive { attachedChildIsBorn <- attachedPid } err = cmd.Wait() if err == nil { return finisher(0, nil) } exitErr, ok := err.(*exec.ExitError) if ok { status, ok := exitErr.Sys().(syscall.WaitStatus) if ok { return finisher(status.ExitStatus(), nil) } if status.Signaled() { // COMMENT(brauner): 128 + n == Fatal error signal "n" return finisher(128+int(status.Signal()), nil) } } return finisher(-1, nil) } func containerExecPost(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return SmartError(err) } if !c.IsRunning() { return BadRequest(fmt.Errorf("Container is not running.")) } if c.IsFrozen() { return BadRequest(fmt.Errorf("Container is frozen.")) } post := api.ContainerExecPost{} buf, err := ioutil.ReadAll(r.Body) if err != nil { return BadRequest(err) } if err := json.Unmarshal(buf, &post); err != nil { return BadRequest(err) } env := map[string]string{} for k, v := range c.ExpandedConfig() { if strings.HasPrefix(k, "environment.") { env[strings.TrimPrefix(k, "environment.")] = v } } if post.Environment != nil { for k, v := range post.Environment { env[k] = v } } // Set default value for PATH _, ok := env["PATH"] if !ok { env["PATH"] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" if c.FileExists("/snap") == nil { env["PATH"] = fmt.Sprintf("%s:/snap/bin", env["PATH"]) } } // Set default value for HOME _, ok = env["HOME"] if !ok { env["HOME"] = "/root" } // Set default value for USER _, ok = env["USER"] if !ok { env["USER"] = "root" } // Set default value for USER _, ok = env["LANG"] if !ok { env["LANG"] = "C.UTF-8" } if post.WaitForWS { ws := &execWs{} ws.fds = map[int]string{} idmapset, err := c.IdmapSet() if err != nil { return InternalError(err) } if idmapset != nil { ws.rootUid, ws.rootGid = idmapset.ShiftIntoNs(0, 0) } ws.conns = map[int]*websocket.Conn{} ws.conns[-1] = nil ws.conns[0] = nil if !post.Interactive { ws.conns[1] = nil ws.conns[2] = nil } ws.allConnected = make(chan bool, 1) ws.controlConnected = make(chan bool, 1) ws.interactive = post.Interactive for i := -1; i < len(ws.conns)-1; i++ { ws.fds[i], err = shared.RandomCryptoString() if err != nil { return InternalError(err) } } ws.command = post.Command ws.container = c ws.env = env ws.width = post.Width ws.height = post.Height resources := map[string][]string{} resources["containers"] = []string{ws.container.Name()} op, err := operationCreate(operationClassWebsocket, resources, ws.Metadata(), ws.Do, nil, ws.Connect) if err != nil { return InternalError(err) } return OperationResponse(op) } run := func(op *operation) error { _, cmdResult, _, cmdErr := c.Exec(post.Command, env, nil, nil, nil, true) metadata := shared.Jmap{"return": cmdResult} err = op.UpdateMetadata(metadata) if err != nil { logger.Error("error updating metadata for cmd", log.Ctx{"err": err, "cmd": post.Command}) } return cmdErr } resources := map[string][]string{} resources["containers"] = []string{name} op, err := operationCreate(operationClassTask, resources, nil, run, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container_delete.go������������������������������������������������������������������0000644�0610621�0607500�00000001207�13172163242�020113� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) func containerDelete(d *Daemon, r *http.Request) Response { name := mux.Vars(r)["name"] c, err := containerLoadByName(d.State(), d.Storage, name) if err != nil { return SmartError(err) } if c.IsRunning() { return BadRequest(fmt.Errorf("container is running")) } rmct := func(op *operation) error { return c.Delete() } resources := map[string][]string{} resources["containers"] = []string{name} op, err := operationCreate(operationClassTask, resources, nil, rmct, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/container.go�������������������������������������������������������������������������0000644�0610621�0607500�00000050211�13172163242�016570� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io" "os" "os/exec" "strconv" "strings" "time" "gopkg.in/lxc/go-lxc.v2" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/state" "github.com/lxc/lxd/lxd/sys" "github.com/lxc/lxd/lxd/types" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/osarch" ) // Helper functions // Returns the parent container name, snapshot name, and whether it actually was // a snapshot name. func containerGetParentAndSnapshotName(name string) (string, string, bool) { fields := strings.SplitN(name, shared.SnapshotDelimiter, 2) if len(fields) == 1 { return name, "", false } return fields[0], fields[1], true } func containerPath(name string, isSnapshot bool) string { if isSnapshot { return shared.VarPath("snapshots", name) } return shared.VarPath("containers", name) } func containerValidName(name string) error { if strings.Contains(name, shared.SnapshotDelimiter) { return fmt.Errorf( "The character '%s' is reserved for snapshots.", shared.SnapshotDelimiter) } if !shared.ValidHostname(name) { return fmt.Errorf("Container name isn't a valid hostname.") } return nil } func containerValidConfigKey(key string, value string) error { isInt64 := func(key string, value string) error { if value == "" { return nil } _, err := strconv.ParseInt(value, 10, 64) if err != nil { return fmt.Errorf("Invalid value for an integer: %s", value) } return nil } isBool := func(key string, value string) error { if value == "" { return nil } if !shared.StringInSlice(strings.ToLower(value), []string{"true", "false", "yes", "no", "1", "0", "on", "off"}) { return fmt.Errorf("Invalid value for a boolean: %s", value) } return nil } isOneOf := func(key string, value string, valid []string) error { if value == "" { return nil } if !shared.StringInSlice(value, valid) { return fmt.Errorf("Invalid value: %s (not one of %s)", value, valid) } return nil } isUint32 := func(key string, value string) error { if value == "" { return nil } _, err := strconv.ParseInt(value, 10, 32) if err != nil { return fmt.Errorf("Invalid value for uint32: %s: %v", value, err) } return nil } switch key { case "boot.autostart": return isBool(key, value) case "boot.autostart.delay": return isInt64(key, value) case "boot.autostart.priority": return isInt64(key, value) case "limits.cpu": return nil case "limits.cpu.allowance": if value == "" { return nil } if strings.HasSuffix(value, "%") { // Percentage based allocation _, err := strconv.Atoi(strings.TrimSuffix(value, "%")) if err != nil { return err } return nil } // Time based allocation fields := strings.SplitN(value, "/", 2) if len(fields) != 2 { return fmt.Errorf("Invalid allowance: %s", value) } _, err := strconv.Atoi(strings.TrimSuffix(fields[0], "ms")) if err != nil { return err } _, err = strconv.Atoi(strings.TrimSuffix(fields[1], "ms")) if err != nil { return err } return nil case "limits.cpu.priority": return isInt64(key, value) case "limits.disk.priority": return isInt64(key, value) case "limits.memory": if value == "" { return nil } if strings.HasSuffix(value, "%") { _, err := strconv.ParseInt(strings.TrimSuffix(value, "%"), 10, 64) if err != nil { return err } return nil } _, err := shared.ParseByteSizeString(value) if err != nil { return err } return nil case "limits.memory.enforce": return isOneOf(key, value, []string{"soft", "hard"}) case "limits.memory.swap": return isBool(key, value) case "limits.memory.swap.priority": return isInt64(key, value) case "limits.network.priority": return isInt64(key, value) case "limits.processes": return isInt64(key, value) case "linux.kernel_modules": return nil case "security.privileged": return isBool(key, value) case "security.nesting": return isBool(key, value) case "security.idmap.base": return isUint32(key, value) case "security.idmap.size": return isUint32(key, value) case "security.idmap.isolated": return isBool(key, value) case "raw.apparmor": return nil case "raw.idmap": return nil case "raw.lxc": return lxcValidConfig(value) case "volatile.apply_template": return nil case "volatile.base_image": return nil case "volatile.last_state.idmap": return nil case "volatile.last_state.power": return nil case "volatile.idmap.next": return nil case "volatile.idmap.base": return nil } if strings.HasPrefix(key, "volatile.") { if strings.HasSuffix(key, ".hwaddr") { return nil } if strings.HasSuffix(key, ".name") { return nil } if strings.HasSuffix(key, ".host_name") { return nil } } if strings.HasPrefix(key, "environment.") { return nil } if strings.HasPrefix(key, "user.") { return nil } return fmt.Errorf("Unknown configuration key: %s", key) } var containerNetworkLimitKeys = []string{"limits.max", "limits.ingress", "limits.egress"} func containerValidDeviceConfigKey(t, k string) bool { if k == "type" { return true } switch t { case "unix-char", "unix-block": switch k { case "gid": return true case "major": return true case "minor": return true case "mode": return true case "path": return true case "uid": return true default: return false } case "nic": switch k { case "limits.max": return true case "limits.ingress": return true case "limits.egress": return true case "host_name": return true case "hwaddr": return true case "mtu": return true case "name": return true case "nictype": return true case "parent": return true default: return false } case "disk": switch k { case "limits.max": return true case "limits.read": return true case "limits.write": return true case "optional": return true case "path": return true case "readonly": return true case "size": return true case "source": return true case "recursive": return true default: return false } case "none": return false default: return false } } func containerValidConfig(os *sys.OS, config map[string]string, profile bool, expanded bool) error { if config == nil { return nil } for k, v := range config { if profile && strings.HasPrefix(k, "volatile.") { return fmt.Errorf("Volatile keys can only be set on containers.") } err := containerValidConfigKey(k, v) if err != nil { return err } } if expanded && (config["security.privileged"] == "" || !shared.IsTrue(config["security.privileged"])) && os.IdmapSet == nil { return fmt.Errorf("LXD doesn't have a uid/gid allocation. In this mode, only privileged containers are supported.") } return nil } func isRootDiskDevice(device types.Device) bool { if device["type"] == "disk" && device["path"] == "/" && device["source"] == "" { return true } return false } func containerGetRootDiskDevice(devices types.Devices) (string, types.Device, error) { var devName string var dev types.Device for n, d := range devices { if isRootDiskDevice(d) { if devName != "" { return "", types.Device{}, fmt.Errorf("More than one root device found.") } devName = n dev = d } } if devName != "" { return devName, dev, nil } return "", types.Device{}, fmt.Errorf("No root device could be found.") } func containerValidDevices(devices types.Devices, profile bool, expanded bool) error { // Empty device list if devices == nil { return nil } var diskDevicePaths []string // Check each device individually for name, m := range devices { if m["type"] == "" { return fmt.Errorf("Missing device type for device '%s'", name) } if !shared.StringInSlice(m["type"], []string{"none", "nic", "disk", "unix-char", "unix-block"}) { return fmt.Errorf("Invalid device type for device '%s'", name) } for k := range m { if !containerValidDeviceConfigKey(m["type"], k) { return fmt.Errorf("Invalid device configuration key for %s: %s", m["type"], k) } } if m["type"] == "nic" { if m["nictype"] == "" { return fmt.Errorf("Missing nic type") } if !shared.StringInSlice(m["nictype"], []string{"bridged", "physical", "p2p", "macvlan"}) { return fmt.Errorf("Bad nic type: %s", m["nictype"]) } if shared.StringInSlice(m["nictype"], []string{"bridged", "physical", "macvlan"}) && m["parent"] == "" { return fmt.Errorf("Missing parent for %s type nic.", m["nictype"]) } } else if m["type"] == "disk" { if !expanded && !shared.StringInSlice(m["path"], diskDevicePaths) { diskDevicePaths = append(diskDevicePaths, m["path"]) } else if !expanded { return fmt.Errorf("More than one disk device uses the same path: %s.", m["path"]) } if m["path"] == "" { return fmt.Errorf("Disk entry is missing the required \"path\" property.") } if m["source"] == "" && m["path"] != "/" { return fmt.Errorf("Disk entry is missing the required \"source\" property.") } if m["path"] == "/" && m["source"] != "" { return fmt.Errorf("Root disk entry may not have a \"source\" property set.") } if m["size"] != "" && m["path"] != "/" { return fmt.Errorf("Only the root disk may have a size quota.") } if (m["path"] == "/" || !shared.IsDir(m["source"])) && m["recursive"] != "" { return fmt.Errorf("The recursive option is only supported for additional bind-mounted paths.") } } else if shared.StringInSlice(m["type"], []string{"unix-char", "unix-block"}) { if m["path"] == "" { return fmt.Errorf("Unix device entry is missing the required \"path\" property.") } if m["major"] == "" || m["minor"] == "" { if !shared.PathExists(m["path"]) { return fmt.Errorf("The device path doesn't exist on the host and major/minor wasn't specified.") } dType, _, _, err := deviceGetAttributes(m["path"]) if err != nil { return err } if m["type"] == "unix-char" && dType != "c" { return fmt.Errorf("Path specified for unix-char device is a block device.") } if m["type"] == "unix-block" && dType != "b" { return fmt.Errorf("Path specified for unix-block device is a character device.") } } } else if m["type"] == "none" { continue } else { return fmt.Errorf("Invalid device type: %s", m["type"]) } } // Checks on the expanded config if expanded { _, _, err := containerGetRootDiskDevice(devices) if err != nil { return err } } return nil } // The container interface type container interface { // Container actions Freeze() error Shutdown(timeout time.Duration) error Start(stateful bool) error Stop(stateful bool) error Unfreeze() error // Snapshots & migration Restore(sourceContainer container) error /* actionScript here is a script called action.sh in the stateDir, to * be passed to CRIU as --action-script */ Migrate(cmd uint, stateDir string, function string, stop bool, actionScript bool) error Snapshots() ([]container, error) // Config handling Rename(newName string) error Update(newConfig db.ContainerArgs, userRequested bool) error Delete() error Export(w io.Writer, properties map[string]string) error // Live configuration CGroupGet(key string) (string, error) CGroupSet(key string, value string) error ConfigKeySet(key string, value string) error // File handling FilePull(srcpath string, dstpath string) (int64, int64, os.FileMode, error) FileExists(path string) error FilePush(srcpath string, dstpath string, uid int64, gid int64, mode int) error FileRemove(path string) error /* Command execution: * 1. passing in false for wait * - equivalent to calling cmd.Run() * 2. passing in true for wait * - start the command and return its PID in the first return * argument and the PID of the attached process in the second * argument. It's the callers responsibility to wait on the * command. (Note. The returned PID of the attached process can not * be waited upon since it's a child of the lxd forkexec command * (the PID returned in the first return argument). It can however * be used to e.g. forward signals.) */ Exec(command []string, env map[string]string, stdin *os.File, stdout *os.File, stderr *os.File, wait bool) (*exec.Cmd, int, int, error) // Status Render() (interface{}, error) RenderState() (*api.ContainerState, error) IsPrivileged() bool IsRunning() bool IsFrozen() bool IsEphemeral() bool IsSnapshot() bool IsStateful() bool IsNesting() bool // Hooks OnStart() error OnStop(target string) error // Properties Id() int Name() string Architecture() int CreationDate() time.Time ExpandedConfig() map[string]string ExpandedDevices() types.Devices LocalConfig() map[string]string LocalDevices() types.Devices Profiles() []string InitPID() int State() string // Paths Path() string RootfsPath() string TemplatesPath() string StatePath() string LogFilePath() string LogPath() string // FIXME: Those should be internal functions StorageStart() error StorageStop() error Storage() storage IdmapSet() (*idmap.IdmapSet, error) LastIdmapSet() (*idmap.IdmapSet, error) TemplateApply(trigger string) error StateObject() *state.State } // Loader functions func containerCreateAsEmpty(d *Daemon, args db.ContainerArgs) (container, error) { // Create the container c, err := containerCreateInternal(d.State(), d.Storage, args) if err != nil { return nil, err } // Now create the empty storage err = c.Storage().ContainerCreate(c) if err != nil { db.ContainerRemove(d.db, args.Name) return nil, err } // Apply any post-storage configuration err = containerConfigureInternal(c) if err != nil { c.Delete() return nil, err } return c, nil } func containerCreateEmptySnapshot(s *state.State, storage storage, args db.ContainerArgs) (container, error) { // Create the snapshot c, err := containerCreateInternal(s, storage, args) if err != nil { return nil, err } // Now create the empty snapshot err = c.Storage().ContainerSnapshotCreateEmpty(c) if err != nil { db.ContainerRemove(s.DB, args.Name) return nil, err } return c, nil } func containerCreateFromImage(s *state.State, storage storage, args db.ContainerArgs, hash string) (container, error) { // Set the BaseImage field (regardless of previous value) args.BaseImage = hash // Create the container c, err := containerCreateInternal(s, storage, args) if err != nil { return nil, err } err = db.ImageLastAccessUpdate(s.DB, hash, time.Now().UTC()) if err != nil { db.ContainerRemove(s.DB, args.Name) return nil, fmt.Errorf("Error updating image last use date: %s", err) } // Now create the storage from an image err = c.Storage().ContainerCreateFromImage(c, hash) if err != nil { db.ContainerRemove(s.DB, args.Name) return nil, err } // Apply any post-storage configuration err = containerConfigureInternal(c) if err != nil { c.Delete() return nil, err } return c, nil } func containerCreateAsCopy(s *state.State, storage storage, args db.ContainerArgs, sourceContainer container) (container, error) { // Create the container. c, err := containerCreateInternal(s, storage, args) if err != nil { return nil, err } // Now clone the storage if err := c.Storage().ContainerCopy(c, sourceContainer); err != nil { c.Delete() return nil, err } // Apply any post-storage configuration err = containerConfigureInternal(c) if err != nil { c.Delete() return nil, err } return c, nil } func containerCreateAsSnapshot(s *state.State, storage storage, args db.ContainerArgs, sourceContainer container) (container, error) { // Deal with state if args.Stateful { if !sourceContainer.IsRunning() { return nil, fmt.Errorf("Unable to create a stateful snapshot. The container isn't running.") } _, err := exec.LookPath("criu") if err != nil { return nil, fmt.Errorf("Unable to create a stateful snapshot. CRIU isn't installed.") } stateDir := sourceContainer.StatePath() err = os.MkdirAll(stateDir, 0700) if err != nil { return nil, err } /* TODO: ideally we would freeze here and unfreeze below after * we've copied the filesystem, to make sure there are no * changes by the container while snapshotting. Unfortunately * there is abug in CRIU where it doesn't leave the container * in the same state it found it w.r.t. freezing, i.e. CRIU * freezes too, and then /always/ thaws, even if the container * was frozen. Until that's fixed, all calls to Unfreeze() * after snapshotting will fail. */ err = sourceContainer.Migrate(lxc.MIGRATE_DUMP, stateDir, "snapshot", false, false) if err != nil { os.RemoveAll(sourceContainer.StatePath()) return nil, err } } // Create the snapshot c, err := containerCreateInternal(s, storage, args) if err != nil { return nil, err } // Clone the container err = sourceContainer.Storage().ContainerSnapshotCreate(c, sourceContainer) if err != nil { db.ContainerRemove(s.DB, args.Name) return nil, err } // Once we're done, remove the state directory if args.Stateful { os.RemoveAll(sourceContainer.StatePath()) } return c, nil } func containerCreateInternal(s *state.State, storage storage, args db.ContainerArgs) (container, error) { // Set default values if args.Profiles == nil { args.Profiles = []string{"default"} } if args.Config == nil { args.Config = map[string]string{} } if args.BaseImage != "" { args.Config["volatile.base_image"] = args.BaseImage } if args.Devices == nil { args.Devices = types.Devices{} } if args.Architecture == 0 { args.Architecture = s.OS.Architectures[0] } // Validate container name if args.Ctype == db.CTypeRegular { err := containerValidName(args.Name) if err != nil { return nil, err } } // Validate container config err := containerValidConfig(s.OS, args.Config, false, false) if err != nil { return nil, err } // Validate container devices err = containerValidDevices(args.Devices, false, false) if err != nil { return nil, err } // Validate architecture _, err = osarch.ArchitectureName(args.Architecture) if err != nil { return nil, err } if !shared.IntInSlice(args.Architecture, s.OS.Architectures) { return nil, fmt.Errorf("Requested architecture isn't supported by this host") } // Validate profiles profiles, err := db.Profiles(s.DB) if err != nil { return nil, err } for _, profile := range args.Profiles { if !shared.StringInSlice(profile, profiles) { return nil, fmt.Errorf("Requested profile '%s' doesn't exist", profile) } } // Create the container entry id, err := db.ContainerCreate(s.DB, args) if err != nil { if err == db.DbErrAlreadyDefined { thing := "Container" if shared.IsSnapshot(args.Name) { thing = "Snapshot" } return nil, fmt.Errorf("%s '%s' already exists", thing, args.Name) } return nil, err } // Wipe any existing log for this container name os.RemoveAll(shared.LogPath(args.Name)) args.Id = id // Read the timestamp from the database dbArgs, err := db.ContainerGet(s.DB, args.Name) if err != nil { db.ContainerRemove(s.DB, args.Name) return nil, err } args.CreationDate = dbArgs.CreationDate // Setup the container struct and finish creation (storage and idmap) c, err := containerLXCCreate(s, storage, args) if err != nil { db.ContainerRemove(s.DB, args.Name) return nil, err } return c, nil } func containerConfigureInternal(c container) error { // Find the root device _, rootDiskDevice, err := containerGetRootDiskDevice(c.ExpandedDevices()) if err != nil { return err } if rootDiskDevice["size"] != "" { size, err := shared.ParseByteSizeString(rootDiskDevice["size"]) if err != nil { return err } // Storage is guaranteed to be ready. err = c.Storage().ContainerSetQuota(c, size) if err != nil { return err } } return nil } func containerLoadById(s *state.State, storage storage, id int) (container, error) { // Get the DB record name, err := db.ContainerName(s.DB, id) if err != nil { return nil, err } return containerLoadByName(s, storage, name) } func containerLoadByName(s *state.State, storage storage, name string) (container, error) { // Get the DB record args, err := db.ContainerGet(s.DB, name) if err != nil { return nil, err } return containerLXCLoad(s, storage, args) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/cgroup.go����������������������������������������������������������������������������0000644�0610621�0607500�00000002231�13172163242�016104� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "bufio" "io/ioutil" "os" "path" "strings" ) func getInitCgroupPath(controller string) string { f, err := os.Open("/proc/1/cgroup") if err != nil { return "/" } defer f.Close() scan := bufio.NewScanner(f) for scan.Scan() { line := scan.Text() fields := strings.Split(line, ":") if len(fields) != 3 { return "/" } if fields[2] != controller { continue } initPath := string(fields[3]) // ignore trailing /init.scope if it is there dir, file := path.Split(initPath) if file == "init.scope" { return dir } else { return initPath } } return "/" } func cGroupGet(controller, cgroup, file string) (string, error) { initPath := getInitCgroupPath(controller) path := path.Join("/sys/fs/cgroup", controller, initPath, cgroup, file) contents, err := ioutil.ReadFile(path) if err != nil { return "", err } return strings.Trim(string(contents), "\n"), nil } func cGroupSet(controller, cgroup, file string, value string) error { initPath := getInitCgroupPath(controller) path := path.Join("/sys/fs/cgroup", controller, initPath, cgroup, file) return ioutil.WriteFile(path, []byte(value), 0755) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/certificates.go����������������������������������������������������������������������0000644�0610621�0607500�00000012031�13172163242�017251� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "crypto/x509" "database/sql" "encoding/base64" "encoding/pem" "fmt" "net" "net/http" "github.com/gorilla/mux" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/version" ) func certificatesGet(d *Daemon, r *http.Request) Response { recursion := util.IsRecursionRequest(r) if recursion { certResponses := []api.Certificate{} baseCerts, err := db.CertsGet(d.db) if err != nil { return SmartError(err) } for _, baseCert := range baseCerts { resp := api.Certificate{} resp.Fingerprint = baseCert.Fingerprint resp.Certificate = baseCert.Certificate if baseCert.Type == 1 { resp.Type = "client" } else { resp.Type = "unknown" } certResponses = append(certResponses, resp) } return SyncResponse(true, certResponses) } body := []string{} for _, cert := range d.clientCerts { fingerprint := fmt.Sprintf("/%s/certificates/%s", version.APIVersion, shared.CertFingerprint(&cert)) body = append(body, fingerprint) } return SyncResponse(true, body) } func readSavedClientCAList(d *Daemon) { d.clientCerts = []x509.Certificate{} dbCerts, err := db.CertsGet(d.db) if err != nil { logger.Infof("Error reading certificates from database: %s", err) return } for _, dbCert := range dbCerts { certBlock, _ := pem.Decode([]byte(dbCert.Certificate)) if certBlock == nil { logger.Infof("Error decoding certificate for %s: %s", dbCert.Name, err) continue } cert, err := x509.ParseCertificate(certBlock.Bytes) if err != nil { logger.Infof("Error reading certificate for %s: %s", dbCert.Name, err) continue } d.clientCerts = append(d.clientCerts, *cert) } } func saveCert(dbObj *sql.DB, host string, cert *x509.Certificate) error { baseCert := new(db.CertInfo) baseCert.Fingerprint = shared.CertFingerprint(cert) baseCert.Type = 1 baseCert.Name = host baseCert.Certificate = string( pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}), ) return db.CertSave(dbObj, baseCert) } func certificatesPost(d *Daemon, r *http.Request) Response { // Parse the request req := api.CertificatesPost{} if err := shared.ReadToJSON(r.Body, &req); err != nil { return BadRequest(err) } // Access check secret := daemonConfig["core.trust_password"].Get() if !util.IsTrustedClient(r, d.clientCerts) && util.PasswordCheck(secret, req.Password) != nil { return Forbidden } if req.Type != "client" { return BadRequest(fmt.Errorf("Unknown request type %s", req.Type)) } // Extract the certificate var cert *x509.Certificate var name string if req.Certificate != "" { data, err := base64.StdEncoding.DecodeString(req.Certificate) if err != nil { return BadRequest(err) } cert, err = x509.ParseCertificate(data) if err != nil { return BadRequest(err) } name = req.Name } else if r.TLS != nil { if len(r.TLS.PeerCertificates) < 1 { return BadRequest(fmt.Errorf("No client certificate provided")) } cert = r.TLS.PeerCertificates[len(r.TLS.PeerCertificates)-1] remoteHost, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return InternalError(err) } name = remoteHost } else { return BadRequest(fmt.Errorf("Can't use TLS data on non-TLS link")) } fingerprint := shared.CertFingerprint(cert) for _, existingCert := range d.clientCerts { if fingerprint == shared.CertFingerprint(&existingCert) { return BadRequest(fmt.Errorf("Certificate already in trust store")) } } err := saveCert(d.db, name, cert) if err != nil { return SmartError(err) } d.clientCerts = append(d.clientCerts, *cert) return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/certificates/%s", version.APIVersion, fingerprint)) } var certificatesCmd = Command{ "certificates", false, true, certificatesGet, nil, certificatesPost, nil, } func certificateFingerprintGet(d *Daemon, r *http.Request) Response { fingerprint := mux.Vars(r)["fingerprint"] cert, err := doCertificateGet(d.db, fingerprint) if err != nil { return SmartError(err) } return SyncResponse(true, cert) } func doCertificateGet(dbObj *sql.DB, fingerprint string) (api.Certificate, error) { resp := api.Certificate{} dbCertInfo, err := db.CertGet(dbObj, fingerprint) if err != nil { return resp, err } resp.Fingerprint = dbCertInfo.Fingerprint resp.Certificate = dbCertInfo.Certificate resp.Name = dbCertInfo.Name if dbCertInfo.Type == 1 { resp.Type = "client" } else { resp.Type = "unknown" } return resp, nil } func certificateFingerprintDelete(d *Daemon, r *http.Request) Response { fingerprint := mux.Vars(r)["fingerprint"] certInfo, err := db.CertGet(d.db, fingerprint) if err != nil { return NotFound } err = db.CertDelete(d.db, certInfo.Fingerprint) if err != nil { return SmartError(err) } readSavedClientCAList(d) return EmptySyncResponse } var certificateFingerprintCmd = Command{ "certificates/{fingerprint}", false, false, certificateFingerprintGet, nil, nil, certificateFingerprintDelete, } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/apparmor.go��������������������������������������������������������������������������0000644�0610621�0607500�00000040214�13172163242�016431� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "crypto/sha256" "fmt" "io" "io/ioutil" "os" "path" "strings" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) const ( APPARMOR_CMD_LOAD = "r" APPARMOR_CMD_UNLOAD = "R" APPARMOR_CMD_PARSE = "Q" ) var aaPath = shared.VarPath("security", "apparmor") const AA_PROFILE_BASE = ` ### Base profile capability, dbus, file, network, umount, # Allow us to receive signals from anywhere. signal (receive), # Allow us to send signals to ourselves signal peer=@{profile_name}, # Allow other processes to read our /proc entries, futexes, perf tracing and # kcmp for now (they will need 'read' in the first place). Administrators can # override with: # deny ptrace (readby) ... ptrace (readby), # Allow other processes to trace us by default (they will need 'trace' in # the first place). Administrators can override with: # deny ptrace (tracedby) ... ptrace (tracedby), # Allow us to ptrace ourselves ptrace peer=@{profile_name}, # ignore DENIED message on / remount deny mount options=(ro, remount) -> /, deny mount options=(ro, remount, silent) -> /, # allow tmpfs mounts everywhere mount fstype=tmpfs, # allow hugetlbfs mounts everywhere mount fstype=hugetlbfs, # allow mqueue mounts everywhere mount fstype=mqueue, # allow fuse mounts everywhere mount fstype=fuse, mount fstype=fuse.*, # deny access under /proc/bus to avoid e.g. messing with pci devices directly deny @{PROC}/bus/** wklx, # deny writes in /proc/sys/fs but allow binfmt_misc to be mounted mount fstype=binfmt_misc -> /proc/sys/fs/binfmt_misc/, deny @{PROC}/sys/fs/** wklx, # allow efivars to be mounted, writing to it will be blocked though mount fstype=efivarfs -> /sys/firmware/efi/efivars/, # block some other dangerous paths deny @{PROC}/kcore rwklx, deny @{PROC}/sysrq-trigger rwklx, # deny writes in /sys except for /sys/fs/cgroup, also allow # fusectl, securityfs and debugfs to be mounted there (read-only) mount fstype=fusectl -> /sys/fs/fuse/connections/, mount fstype=securityfs -> /sys/kernel/security/, mount fstype=debugfs -> /sys/kernel/debug/, deny mount fstype=debugfs -> /var/lib/ureadahead/debugfs/, mount fstype=proc -> /proc/, mount fstype=sysfs -> /sys/, mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/, deny /sys/firmware/efi/efivars/** rwklx, # note, /sys/kernel/security/** handled below mount options=(move) /sys/fs/cgroup/cgmanager/ -> /sys/fs/cgroup/cgmanager.lower/, mount options=(ro, nosuid, nodev, noexec, remount, strictatime) -> /sys/fs/cgroup/, # deny reads from debugfs deny /sys/kernel/debug/{,**} rwklx, # allow paths to be made slave, shared, private or unbindable # FIXME: This currently doesn't work due to the apparmor parser treating those as allowing all mounts. # mount options=(rw,make-slave) -> **, # mount options=(rw,make-rslave) -> **, # mount options=(rw,make-shared) -> **, # mount options=(rw,make-rshared) -> **, # mount options=(rw,make-private) -> **, # mount options=(rw,make-rprivate) -> **, # mount options=(rw,make-unbindable) -> **, # mount options=(rw,make-runbindable) -> **, # allow bind-mounts of anything except /proc, /sys and /dev mount options=(rw,bind) /[^spd]*{,/**}, mount options=(rw,bind) /d[^e]*{,/**}, mount options=(rw,bind) /de[^v]*{,/**}, mount options=(rw,bind) /dev/.[^l]*{,/**}, mount options=(rw,bind) /dev/.l[^x]*{,/**}, mount options=(rw,bind) /dev/.lx[^c]*{,/**}, mount options=(rw,bind) /dev/.lxc?*{,/**}, mount options=(rw,bind) /dev/[^.]*{,/**}, mount options=(rw,bind) /dev?*{,/**}, mount options=(rw,bind) /p[^r]*{,/**}, mount options=(rw,bind) /pr[^o]*{,/**}, mount options=(rw,bind) /pro[^c]*{,/**}, mount options=(rw,bind) /proc?*{,/**}, mount options=(rw,bind) /s[^y]*{,/**}, mount options=(rw,bind) /sy[^s]*{,/**}, mount options=(rw,bind) /sys?*{,/**}, # allow moving mounts except for /proc, /sys and /dev mount options=(rw,move) /[^spd]*{,/**}, mount options=(rw,move) /d[^e]*{,/**}, mount options=(rw,move) /de[^v]*{,/**}, mount options=(rw,move) /dev/.[^l]*{,/**}, mount options=(rw,move) /dev/.l[^x]*{,/**}, mount options=(rw,move) /dev/.lx[^c]*{,/**}, mount options=(rw,move) /dev/.lxc?*{,/**}, mount options=(rw,move) /dev/[^.]*{,/**}, mount options=(rw,move) /dev?*{,/**}, mount options=(rw,move) /p[^r]*{,/**}, mount options=(rw,move) /pr[^o]*{,/**}, mount options=(rw,move) /pro[^c]*{,/**}, mount options=(rw,move) /proc?*{,/**}, mount options=(rw,move) /s[^y]*{,/**}, mount options=(rw,move) /sy[^s]*{,/**}, mount options=(rw,move) /sys?*{,/**}, # generated by: lxc-generate-aa-rules.py container-rules.base deny /proc/sys/[^kn]*{,/**} wklx, deny /proc/sys/k[^e]*{,/**} wklx, deny /proc/sys/ke[^r]*{,/**} wklx, deny /proc/sys/ker[^n]*{,/**} wklx, deny /proc/sys/kern[^e]*{,/**} wklx, deny /proc/sys/kerne[^l]*{,/**} wklx, deny /proc/sys/kernel/[^smhd]*{,/**} wklx, deny /proc/sys/kernel/d[^o]*{,/**} wklx, deny /proc/sys/kernel/do[^m]*{,/**} wklx, deny /proc/sys/kernel/dom[^a]*{,/**} wklx, deny /proc/sys/kernel/doma[^i]*{,/**} wklx, deny /proc/sys/kernel/domai[^n]*{,/**} wklx, deny /proc/sys/kernel/domain[^n]*{,/**} wklx, deny /proc/sys/kernel/domainn[^a]*{,/**} wklx, deny /proc/sys/kernel/domainna[^m]*{,/**} wklx, deny /proc/sys/kernel/domainnam[^e]*{,/**} wklx, deny /proc/sys/kernel/domainname?*{,/**} wklx, deny /proc/sys/kernel/h[^o]*{,/**} wklx, deny /proc/sys/kernel/ho[^s]*{,/**} wklx, deny /proc/sys/kernel/hos[^t]*{,/**} wklx, deny /proc/sys/kernel/host[^n]*{,/**} wklx, deny /proc/sys/kernel/hostn[^a]*{,/**} wklx, deny /proc/sys/kernel/hostna[^m]*{,/**} wklx, deny /proc/sys/kernel/hostnam[^e]*{,/**} wklx, deny /proc/sys/kernel/hostname?*{,/**} wklx, deny /proc/sys/kernel/m[^s]*{,/**} wklx, deny /proc/sys/kernel/ms[^g]*{,/**} wklx, deny /proc/sys/kernel/msg*/** wklx, deny /proc/sys/kernel/s[^he]*{,/**} wklx, deny /proc/sys/kernel/se[^m]*{,/**} wklx, deny /proc/sys/kernel/sem*/** wklx, deny /proc/sys/kernel/sh[^m]*{,/**} wklx, deny /proc/sys/kernel/shm*/** wklx, deny /proc/sys/kernel?*{,/**} wklx, deny /proc/sys/n[^e]*{,/**} wklx, deny /proc/sys/ne[^t]*{,/**} wklx, deny /proc/sys/net?*{,/**} wklx, deny /sys/[^fdck]*{,/**} wklx, deny /sys/c[^l]*{,/**} wklx, deny /sys/cl[^a]*{,/**} wklx, deny /sys/cla[^s]*{,/**} wklx, deny /sys/clas[^s]*{,/**} wklx, deny /sys/class/[^n]*{,/**} wklx, deny /sys/class/n[^e]*{,/**} wklx, deny /sys/class/ne[^t]*{,/**} wklx, deny /sys/class/net?*{,/**} wklx, deny /sys/class?*{,/**} wklx, deny /sys/d[^e]*{,/**} wklx, deny /sys/de[^v]*{,/**} wklx, deny /sys/dev[^i]*{,/**} wklx, deny /sys/devi[^c]*{,/**} wklx, deny /sys/devic[^e]*{,/**} wklx, deny /sys/device[^s]*{,/**} wklx, deny /sys/devices/[^v]*{,/**} wklx, deny /sys/devices/v[^i]*{,/**} wklx, deny /sys/devices/vi[^r]*{,/**} wklx, deny /sys/devices/vir[^t]*{,/**} wklx, deny /sys/devices/virt[^u]*{,/**} wklx, deny /sys/devices/virtu[^a]*{,/**} wklx, deny /sys/devices/virtua[^l]*{,/**} wklx, deny /sys/devices/virtual/[^n]*{,/**} wklx, deny /sys/devices/virtual/n[^e]*{,/**} wklx, deny /sys/devices/virtual/ne[^t]*{,/**} wklx, deny /sys/devices/virtual/net?*{,/**} wklx, deny /sys/devices/virtual?*{,/**} wklx, deny /sys/devices?*{,/**} wklx, deny /sys/f[^s]*{,/**} wklx, deny /sys/fs/[^c]*{,/**} wklx, deny /sys/fs/c[^g]*{,/**} wklx, deny /sys/fs/cg[^r]*{,/**} wklx, deny /sys/fs/cgr[^o]*{,/**} wklx, deny /sys/fs/cgro[^u]*{,/**} wklx, deny /sys/fs/cgrou[^p]*{,/**} wklx, deny /sys/fs/cgroup?*{,/**} wklx, deny /sys/fs?*{,/**} wklx, ` const AA_PROFILE_NESTING = ` pivot_root, ptrace, signal, deny /dev/.lxd/proc/** rw, deny /dev/.lxd/sys/** rw, mount /var/lib/lxd/shmounts/ -> /var/lib/lxd/shmounts/, mount none -> /var/lib/lxd/shmounts/, mount fstype=proc -> /usr/lib/*/lxc/**, mount fstype=sysfs -> /usr/lib/*/lxc/**, mount options=(rw,bind), mount options=(rw,rbind), mount options=(rw,make-rshared), # there doesn't seem to be a way to ask for: # mount options=(ro,nosuid,nodev,noexec,remount,bind), # as we always get mount to $cdir/proc/sys with those flags denied # So allow all mounts until that is straightened out: mount, mount options=bind /var/lib/lxd/shmounts/** -> /var/lib/lxd/**, ` const AA_PROFILE_UNPRIVILEGED = ` pivot_root, mount options=(rw,make-slave) -> **, mount options=(rw,make-rslave) -> **, mount options=(rw,make-shared) -> **, mount options=(rw,make-rshared) -> **, mount options=(rw,make-private) -> **, mount options=(rw,make-rprivate) -> **, mount options=(rw,make-unbindable) -> **, mount options=(rw,make-runbindable) -> **, mount options=(rw,bind), mount options=(rw,rbind), ` func mkApparmorName(name string) string { if len(name)+7 >= 253 { hash := sha256.New() io.WriteString(hash, name) return fmt.Sprintf("%x", hash.Sum(nil)) } return name } func AANamespace(c container) string { /* / is not allowed in apparmor namespace names; let's also trim the * leading / so it doesn't look like "-var-lib-lxd" */ lxddir := strings.Replace(strings.Trim(shared.VarPath(""), "/"), "/", "-", -1) lxddir = mkApparmorName(lxddir) return fmt.Sprintf("lxd-%s_<%s>", c.Name(), lxddir) } func AAProfileFull(c container) string { lxddir := shared.VarPath("") lxddir = mkApparmorName(lxddir) return fmt.Sprintf("lxd-%s_<%s>", c.Name(), lxddir) } func AAProfileShort(c container) string { return fmt.Sprintf("lxd-%s", c.Name()) } // getProfileContent generates the apparmor profile template from the given // container. This includes the stock lxc includes as well as stuff from // raw.apparmor. func getAAProfileContent(c container) string { profile := strings.TrimLeft(AA_PROFILE_BASE, "\n") // Apply new features if aaParserSupports("unix") { profile += ` ### Feature: unix # Allow receive via unix sockets from anywhere unix (receive), # Allow all unix in the container unix peer=(label=@{profile_name}), ` } // Apply cgns bits if shared.PathExists("/proc/self/ns/cgroup") { profile += "\n ### Feature: cgroup namespace\n" profile += " mount fstype=cgroup -> /sys/fs/cgroup/**,\n" } if aaStacking && !aaStacked { profile += "\n ### Feature: apparmor stacking\n" profile += ` ### Configuration: apparmor profile loading (in namespace) deny /sys/k[^e]*{,/**} wklx, deny /sys/ke[^r]*{,/**} wklx, deny /sys/ker[^n]*{,/**} wklx, deny /sys/kern[^e]*{,/**} wklx, deny /sys/kerne[^l]*{,/**} wklx, deny /sys/kernel/[^s]*{,/**} wklx, deny /sys/kernel/s[^e]*{,/**} wklx, deny /sys/kernel/se[^c]*{,/**} wklx, deny /sys/kernel/sec[^u]*{,/**} wklx, deny /sys/kernel/secu[^r]*{,/**} wklx, deny /sys/kernel/secur[^i]*{,/**} wklx, deny /sys/kernel/securi[^t]*{,/**} wklx, deny /sys/kernel/securit[^y]*{,/**} wklx, deny /sys/kernel/security/[^a]*{,/**} wklx, deny /sys/kernel/security/a[^p]*{,/**} wklx, deny /sys/kernel/security/ap[^p]*{,/**} wklx, deny /sys/kernel/security/app[^a]*{,/**} wklx, deny /sys/kernel/security/appa[^r]*{,/**} wklx, deny /sys/kernel/security/appar[^m]*{,/**} wklx, deny /sys/kernel/security/apparm[^o]*{,/**} wklx, deny /sys/kernel/security/apparmo[^r]*{,/**} wklx, deny /sys/kernel/security/apparmor?*{,/**} wklx, deny /sys/kernel/security?*{,/**} wklx, deny /sys/kernel?*{,/**} wklx, ` profile += fmt.Sprintf(" change_profile -> \":%s:*\",\n", AANamespace(c)) profile += fmt.Sprintf(" change_profile -> \":%s://*\",\n", AANamespace(c)) } else { profile += "\n ### Feature: apparmor stacking (not present)\n" profile += " deny /sys/k*{,/**} rwklx,\n" } if c.IsNesting() { // Apply nesting bits profile += "\n ### Configuration: nesting\n" profile += strings.TrimLeft(AA_PROFILE_NESTING, "\n") if !aaStacking || aaStacked { profile += fmt.Sprintf(" change_profile -> \"%s\",\n", AAProfileFull(c)) } } if !c.IsPrivileged() || runningInUserns { // Apply unprivileged bits profile += "\n ### Configuration: unprivileged containers\n" profile += strings.TrimLeft(AA_PROFILE_UNPRIVILEGED, "\n") } // Append raw.apparmor rawApparmor, ok := c.ExpandedConfig()["raw.apparmor"] if ok { profile += "\n ### Configuration: raw.apparmor\n" for _, line := range strings.Split(strings.Trim(rawApparmor, "\n"), "\n") { profile += fmt.Sprintf(" %s\n", line) } } return fmt.Sprintf(`#include <tunables/global> profile "%s" flags=(attach_disconnected,mediate_deleted) { %s } `, AAProfileFull(c), strings.Trim(profile, "\n")) } func runApparmor(command string, c container) error { if !aaAvailable { return nil } output, err := shared.RunCommand("apparmor_parser", []string{ fmt.Sprintf("-%sWL", command), path.Join(aaPath, "cache"), path.Join(aaPath, "profiles", AAProfileShort(c)), }...) if err != nil { logger.Error("Running apparmor", log.Ctx{"action": command, "output": output, "err": err}) } return err } func mkApparmorNamespace(namespace string) error { if !aaStacking || aaStacked { return nil } p := path.Join("/sys/kernel/security/apparmor/policy/namespaces", namespace) if err := os.Mkdir(p, 0755); !os.IsExist(err) { return err } return nil } // Ensure that the container's policy is loaded into the kernel so the // container can boot. func AALoadProfile(c container) error { if !aaAdmin { return nil } if err := mkApparmorNamespace(AANamespace(c)); err != nil { return err } /* In order to avoid forcing a profile parse (potentially slow) on * every container start, let's use apparmor's binary policy cache, * which checks mtime of the files to figure out if the policy needs to * be regenerated. * * Since it uses mtimes, we shouldn't just always write out our local * apparmor template; instead we should check to see whether the * template is the same as ours. If it isn't we should write our * version out so that the new changes are reflected and we definitely * force a recompile. */ profile := path.Join(aaPath, "profiles", AAProfileShort(c)) content, err := ioutil.ReadFile(profile) if err != nil && !os.IsNotExist(err) { return err } updated := getAAProfileContent(c) if string(content) != string(updated) { if err := os.MkdirAll(path.Join(aaPath, "cache"), 0700); err != nil { return err } if err := os.MkdirAll(path.Join(aaPath, "profiles"), 0700); err != nil { return err } if err := ioutil.WriteFile(profile, []byte(updated), 0600); err != nil { return err } } return runApparmor(APPARMOR_CMD_LOAD, c) } // Ensure that the container's policy namespace is unloaded to free kernel // memory. This does not delete the policy from disk or cache. func AADestroy(c container) error { if !aaAdmin { return nil } if aaStacking && !aaStacked { p := path.Join("/sys/kernel/security/apparmor/policy/namespaces", AANamespace(c)) if err := os.Remove(p); err != nil { logger.Error("error removing apparmor namespace", log.Ctx{"err": err, "ns": p}) } } return runApparmor(APPARMOR_CMD_UNLOAD, c) } // Parse the profile without loading it into the kernel. func AAParseProfile(c container) error { if !aaAvailable { return nil } return runApparmor(APPARMOR_CMD_PARSE, c) } // Delete the policy from cache/disk. func AADeleteProfile(c container) { if !aaAdmin { return } /* It's ok if these deletes fail: if the container was never started, * we'll have never written a profile or cached it. */ os.Remove(path.Join(aaPath, "cache", AAProfileShort(c))) os.Remove(path.Join(aaPath, "profiles", AAProfileShort(c))) } // What's current apparmor profile func aaProfile() string { contents, err := ioutil.ReadFile("/proc/self/attr/current") if err == nil { return strings.TrimSpace(string(contents)) } return "" } func aaParserSupports(feature string) bool { out, err := shared.RunCommand("apparmor_parser", "--version") if err != nil { return false } major := 0 minor := 0 micro := 0 _, err = fmt.Sscanf(strings.Split(out, "\n")[0], "AppArmor parser version %d.%d.%d", &major, &minor, &micro) if err != nil { return false } switch feature { case "unix": if major < 2 { return false } if major == 2 && minor < 10 { return false } if major == 2 && minor == 10 && micro < 95 { return false } } return true } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/api_internal.go����������������������������������������������������������������������0000644�0610621�0607500�00000004104�13172163242�017253� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "net/http" "strconv" "github.com/gorilla/mux" "github.com/lxc/lxd/shared/logger" log "gopkg.in/inconshreveable/log15.v2" ) var apiInternal = []Command{ internalReadyCmd, internalShutdownCmd, internalContainerOnStartCmd, internalContainerOnStopCmd, } func internalReady(d *Daemon, r *http.Request) Response { if !d.SetupMode { return InternalError(fmt.Errorf("The server isn't currently in setup mode")) } err := d.Ready() if err != nil { return InternalError(err) } d.SetupMode = false return EmptySyncResponse } func internalWaitReady(d *Daemon, r *http.Request) Response { <-d.readyChan return EmptySyncResponse } func internalShutdown(d *Daemon, r *http.Request) Response { d.shutdownChan <- true return EmptySyncResponse } func internalContainerOnStart(d *Daemon, r *http.Request) Response { id, err := strconv.Atoi(mux.Vars(r)["id"]) if err != nil { return SmartError(err) } c, err := containerLoadById(d.State(), d.Storage, id) if err != nil { return SmartError(err) } err = c.OnStart() if err != nil { logger.Error("start hook failed", log.Ctx{"container": c.Name(), "err": err}) return SmartError(err) } return EmptySyncResponse } func internalContainerOnStop(d *Daemon, r *http.Request) Response { id, err := strconv.Atoi(mux.Vars(r)["id"]) if err != nil { return SmartError(err) } target := r.FormValue("target") if target == "" { target = "unknown" } c, err := containerLoadById(d.State(), d.Storage, id) if err != nil { return SmartError(err) } err = c.OnStop(target) if err != nil { logger.Error("stop hook failed", log.Ctx{"container": c.Name(), "err": err}) return SmartError(err) } return EmptySyncResponse } var internalShutdownCmd = Command{name: "shutdown", put: internalShutdown} var internalReadyCmd = Command{name: "ready", put: internalReady, get: internalWaitReady} var internalContainerOnStartCmd = Command{name: "containers/{id}/onstart", get: internalContainerOnStart} var internalContainerOnStopCmd = Command{name: "containers/{id}/onstop", get: internalContainerOnStop} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/api_1.0.go���������������������������������������������������������������������������0000644�0610621�0607500�00000010575�13172163242�015746� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/pem" "fmt" "net/http" "os" "reflect" "gopkg.in/lxc/go-lxc.v2" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/osarch" "github.com/lxc/lxd/shared/version" ) var api10 = []Command{ containersCmd, containerCmd, containerStateCmd, containerFileCmd, containerLogsCmd, containerLogCmd, containerSnapshotsCmd, containerSnapshotCmd, containerExecCmd, aliasCmd, aliasesCmd, eventsCmd, imageCmd, imagesCmd, imagesExportCmd, imagesSecretCmd, operationsCmd, operationCmd, operationWait, operationWebsocket, networksCmd, networkCmd, api10Cmd, certificatesCmd, certificateFingerprintCmd, profilesCmd, profileCmd, } func api10Get(d *Daemon, r *http.Request) Response { srv := api.ServerUntrusted{ /* List of API extensions in the order they were added. * * The following kind of changes require an addition to api_extensions: * - New configuration key * - New valid values for a configuration key * - New REST API endpoint * - New argument inside an existing REST API call * - New HTTPs authentication mechanisms or protocols */ APIExtensions: []string{ "id_map", "id_map_base", "resource_limits", }, APIStatus: "stable", APIVersion: version.APIVersion, Public: false, Auth: "untrusted", } // If untrusted, return now if !util.IsTrustedClient(r, d.clientCerts) { return SyncResponse(true, srv) } srv.Auth = "trusted" uname, err := shared.Uname() if err != nil { return InternalError(err) } addresses, err := util.ListenAddresses(daemonConfig["core.https_address"].Get()) if err != nil { return InternalError(err) } var certificate string var certificateFingerprint string if len(d.tlsConfig.Certificates) != 0 { certificate = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: d.tlsConfig.Certificates[0].Certificate[0]})) certificateFingerprint, err = shared.CertFingerprintStr(certificate) if err != nil { return InternalError(err) } } architectures := []string{} for _, architecture := range d.os.Architectures { architectureName, err := osarch.ArchitectureName(architecture) if err != nil { return InternalError(err) } architectures = append(architectures, architectureName) } env := api.ServerEnvironment{ Addresses: addresses, Architectures: architectures, Certificate: certificate, CertificateFingerprint: certificateFingerprint, Driver: "lxc", DriverVersion: lxc.Version(), Kernel: uname.Sysname, KernelArchitecture: uname.Machine, KernelVersion: uname.Release, Storage: d.Storage.GetStorageTypeName(), StorageVersion: d.Storage.GetStorageTypeVersion(), Server: "lxd", ServerPid: os.Getpid(), ServerVersion: version.Version} fullSrv := api.Server{ServerUntrusted: srv} fullSrv.Environment = env fullSrv.Config = daemonConfigRender() return SyncResponse(true, fullSrv) } func api10Put(d *Daemon, r *http.Request) Response { oldConfig, err := db.ConfigValuesGet(d.db) if err != nil { return SmartError(err) } req := api.ServerPut{} if err := shared.ReadToJSON(r.Body, &req); err != nil { return BadRequest(err) } // Deal with special keys for k, v := range req.Config { config := daemonConfig[k] if config != nil && config.hiddenValue && v == true { req.Config[k] = oldConfig[k] } } // Diff the configs changedConfig := map[string]interface{}{} for key, value := range oldConfig { if req.Config[key] != value { changedConfig[key] = req.Config[key] } } for key, value := range req.Config { if oldConfig[key] != value { changedConfig[key] = req.Config[key] } } for key, valueRaw := range changedConfig { if valueRaw == nil { valueRaw = "" } s := reflect.ValueOf(valueRaw) if !s.IsValid() || s.Kind() != reflect.String { return BadRequest(fmt.Errorf("Invalid value type for '%s'", key)) } value := valueRaw.(string) confKey, ok := daemonConfig[key] if !ok { return BadRequest(fmt.Errorf("Bad server config key: '%s'", key)) } err := confKey.Set(d, value) if err != nil { return BadRequest(err) } } return EmptySyncResponse } var api10Cmd = Command{name: "", untrustedGet: true, get: api10Get, put: api10Put} �����������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd/.dir-locals.el�����������������������������������������������������������������������0000644�0610621�0607500�00000000377�13172163242�016720� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������;;; Directory Local Variables ;;; For more information see (info "(emacs) Directory Variables") ((go-mode . ((go-test-args . "-tags libsqlite3 -timeout 10s") (eval . (set (make-local-variable 'flycheck-go-build-tags) '("libsqlite3")))))) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd-bridge/������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015512� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd-bridge/lxd-bridge-proxy/�������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�020712� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd-bridge/lxd-bridge-proxy/main.go������������������������������������������������������0000644�0610621�0607500�00000000435�13172163242�022167� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "flag" "log" "net/http" "net/http/httputil" ) func main() { addr := flag.String("addr", "[fe80::1%lxdbr0]:13128", "proxy listen address") flag.Parse() log.Fatal(http.ListenAndServe(*addr, &httputil.ReverseProxy{Director: func(req *http.Request) {}})) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxd-bridge/lxd-bridge��������������������������������������������������������������������0000755�0610621�0607500�00000024673�13172163242�017475� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/sh config="/etc/default/lxd-bridge" varrun="/run/lxd-bridge/" varlib="/var/lib/lxd-bridge/" # lxdbr0 defaults to only setting up the standard IPv6 link-local network # to enable routable IPv4 and/or IPv6, please edit /etc/default/lxd # The values below are defaults USE_LXD_BRIDGE="true" LXD_BRIDGE="lxdbr0" LXD_CONFILE="" LXD_DOMAIN="" # IPv4 LXD_IPV4_ADDR="" LXD_IPV4_NETMASK="" LXD_IPV4_NETWORK="" LXD_IPV4_DHCP_RANGE="" LXD_IPV4_DHCP_MAX="" LXD_IPV4_NAT="false" LXD_IPV4_FIREWALL="true" # IPv6 LXD_IPV6_ADDR="" LXD_IPV6_MASK="" LXD_IPV6_NETWORK="" LXD_IPV6_NAT="false" LXD_IPV6_FIREWALL="true" LXD_IPV6_PROXY="true" # shellcheck disable=SC1090 [ ! -f "${config}" ] || . "${config}" use_iptables_lock="-w" iptables -w -L -n > /dev/null 2>&1 || use_iptables_lock="" HAS_IPV6=false [ -e "/proc/sys/net/ipv6/conf/default/disable_ipv6" ] && \ [ "$(cat /proc/sys/net/ipv6/conf/default/disable_ipv6)" = "0" ] && HAS_IPV6=true _netmask2cidr () { # Assumes there's no "255." after a non-255 byte in the mask x=${1##*255.} set -- "0^^^128^192^224^240^248^252^254^" "$(( (${#1} - ${#x})*2 ))" "${x%%.*}" x=${1%%${3}*} echo $(( ${2} + (${#x}/4) )) } ifdown() { ip addr flush dev "${1}" ip link set dev "${1}" down } ifup() { [ "${HAS_IPV6}" = "true" ] && [ "${LXD_IPV6_PROXY}" = "true" ] && ip addr add fe80::1/64 dev "${1}" if [ -n "${LXD_IPV4_NETMASK}" ] && [ -n "${LXD_IPV4_ADDR}" ]; then MASK=$(_netmask2cidr ${LXD_IPV4_NETMASK}) CIDR_ADDR="${LXD_IPV4_ADDR}/${MASK}" ip addr add "${CIDR_ADDR}" dev "${1}" fi ip link set dev "${1}" up } start() { [ "x${USE_LXD_BRIDGE}" = "xtrue" ] || { exit 0; } [ ! -f "${varrun}/network_up" ] || { echo "lxd-bridge is already running"; exit 1; } if [ -d /sys/class/net/${LXD_BRIDGE} ]; then stop force 2>/dev/null || true fi FAILED=1 cleanup() { set +e if [ "${FAILED}" = "1" ]; then echo "Failed to setup lxd-bridge." >&2 stop force fi } trap cleanup EXIT HUP INT TERM set -e # set up the lxd network [ ! -d "/sys/class/net/${LXD_BRIDGE}" ] && ip link add dev "${LXD_BRIDGE}" type bridge if [ "${HAS_IPV6}" = "true" ]; then echo 0 > "/proc/sys/net/ipv6/conf/${LXD_BRIDGE}/autoconf" || true echo 0 > "/proc/sys/net/ipv6/conf/${LXD_BRIDGE}/accept_dad" || true fi # if we are run from systemd on a system with selinux enabled, # the mkdir will create /run/lxd as init_var_run_t which dnsmasq # can't write its pid into, so we restorecon it (to var_run_t) if [ ! -d "${varrun}" ]; then mkdir -p "${varrun}" if which restorecon >/dev/null 2>&1; then restorecon "${varrun}" fi fi if [ ! -d "${varlib}" ]; then mkdir -p "${varlib}" if which restorecon >/dev/null 2>&1; then restorecon "${varlib}" fi fi ifup "${LXD_BRIDGE}" "${LXD_IPV4_ADDR}" "${LXD_IPV4_NETMASK}" LXD_IPV4_ARG="" if [ -n "${LXD_IPV4_ADDR}" ] && [ -n "${LXD_IPV4_NETMASK}" ] && [ -n "${LXD_IPV4_NETWORK}" ]; then echo 1 > /proc/sys/net/ipv4/ip_forward if [ "${LXD_IPV4_NAT}" = "true" ]; then iptables "${use_iptables_lock}" -t nat -A POSTROUTING -s "${LXD_IPV4_NETWORK}" ! -d "${LXD_IPV4_NETWORK}" -j MASQUERADE -m comment --comment "managed by lxd-bridge" fi LXD_IPV4_ARG="--listen-address ${LXD_IPV4_ADDR} --dhcp-range ${LXD_IPV4_DHCP_RANGE} --dhcp-lease-max=${LXD_IPV4_DHCP_MAX}" fi LXD_IPV6_ARG="" if [ "${HAS_IPV6}" = "true" ] && [ -n "${LXD_IPV6_ADDR}" ] && [ -n "${LXD_IPV6_MASK}" ] && [ -n "${LXD_IPV6_NETWORK}" ]; then # IPv6 sysctls don't respect the "all" path... for interface in /proc/sys/net/ipv6/conf/*; do echo 2 > "${interface}/accept_ra" done for interface in /proc/sys/net/ipv6/conf/*; do echo 1 > "${interface}/forwarding" done ip -6 addr add dev "${LXD_BRIDGE}" "${LXD_IPV6_ADDR}/${LXD_IPV6_MASK}" if [ "${LXD_IPV6_NAT}" = "true" ]; then ip6tables "${use_iptables_lock}" -t nat -A POSTROUTING -s "${LXD_IPV6_NETWORK}" ! -d "${LXD_IPV6_NETWORK}" -j MASQUERADE -m comment --comment "managed by lxd-bridge" fi LXD_IPV6_ARG="--dhcp-range=${LXD_IPV6_ADDR},ra-stateless,ra-names --listen-address ${LXD_IPV6_ADDR}" fi iptables "${use_iptables_lock}" -I INPUT -i "${LXD_BRIDGE}" -p udp --dport 67 -j ACCEPT -m comment --comment "managed by lxd-bridge" iptables "${use_iptables_lock}" -I INPUT -i "${LXD_BRIDGE}" -p udp --dport 53 -j ACCEPT -m comment --comment "managed by lxd-bridge" iptables "${use_iptables_lock}" -I INPUT -i "${LXD_BRIDGE}" -p tcp --dport 53 -j ACCEPT -m comment --comment "managed by lxd-bridge" if [ "${LXD_IPV4_FIREWALL}" = "true" ]; then iptables "${use_iptables_lock}" -I FORWARD -i "${LXD_BRIDGE}" -j ACCEPT -m comment --comment "managed by lxd-bridge" iptables "${use_iptables_lock}" -I FORWARD -o "${LXD_BRIDGE}" -j ACCEPT -m comment --comment "managed by lxd-bridge" fi iptables "${use_iptables_lock}" -t mangle -A POSTROUTING -o "${LXD_BRIDGE}" -p udp -m udp --dport 68 -j CHECKSUM --checksum-fill -m comment --comment "managed by lxd-bridge" || true if [ "${HAS_IPV6}" = "true" ]; then ip6tables "${use_iptables_lock}" -I INPUT -i "${LXD_BRIDGE}" -p udp --dport 67 -j ACCEPT -m comment --comment "managed by lxd-bridge" ip6tables "${use_iptables_lock}" -I INPUT -i "${LXD_BRIDGE}" -p udp --dport 53 -j ACCEPT -m comment --comment "managed by lxd-bridge" ip6tables "${use_iptables_lock}" -I INPUT -i "${LXD_BRIDGE}" -p tcp --dport 53 -j ACCEPT -m comment --comment "managed by lxd-bridge" if [ "${LXD_IPV6_FIREWALL}" = "true" ]; then ip6tables "${use_iptables_lock}" -I FORWARD -i "${LXD_BRIDGE}" -j ACCEPT -m comment --comment "managed by lxd-bridge" ip6tables "${use_iptables_lock}" -I FORWARD -o "${LXD_BRIDGE}" -j ACCEPT -m comment --comment "managed by lxd-bridge" fi fi LXD_DOMAIN_ARG="" if [ -n "${LXD_DOMAIN}" ]; then LXD_DOMAIN_ARG="-s ${LXD_DOMAIN} -S /${LXD_DOMAIN}/" fi LXD_CONFILE_ARG="" if [ -n "${LXD_CONFILE}" ]; then LXD_CONFILE_ARG="--conf-file=${LXD_CONFILE}" fi # https://lists.linuxcontainers.org/pipermail/lxc-devel/2014-October/010561.html for DNSMASQ_USER in lxd dnsmasq nobody do if getent passwd "${DNSMASQ_USER}" >/dev/null; then break fi done if [ -n "${LXD_IPV4_ADDR}" ] || [ -n "${LXD_IPV6_ADDR}" ]; then # shellcheck disable=SC2086 dnsmasq ${LXD_CONFILE_ARG} ${LXD_DOMAIN_ARG} -u "${DNSMASQ_USER}" --strict-order --bind-interfaces --pid-file="${varrun}/dnsmasq.pid" --dhcp-no-override --except-interface=lo --interface="${LXD_BRIDGE}" --dhcp-leasefile="${varlib}/dnsmasq.${LXD_BRIDGE}.leases" --dhcp-authoritative ${LXD_IPV4_ARG} ${LXD_IPV6_ARG} fi if [ "${HAS_IPV6}" = "true" ] && [ "${LXD_IPV6_PROXY}" = "true" ]; then PATH="${PATH}:$(dirname "${0}")" lxd-bridge-proxy --addr="[fe80::1%${LXD_BRIDGE}]:13128" & PID=$! echo "${PID}" > "${varrun}/proxy.pid" fi touch "${varrun}/network_up" FAILED=0 } stop() { [ -f "${varrun}/network_up" ] || [ "${1}" = "force" ] || { echo "lxd-bridge isn't running"; exit 1; } if [ -d /sys/class/net/${LXD_BRIDGE} ]; then ifdown ${LXD_BRIDGE} iptables ${use_iptables_lock} -D INPUT -i ${LXD_BRIDGE} -p udp --dport 67 -j ACCEPT -m comment --comment "managed by lxd-bridge" iptables ${use_iptables_lock} -D INPUT -i ${LXD_BRIDGE} -p udp --dport 53 -j ACCEPT -m comment --comment "managed by lxd-bridge" iptables ${use_iptables_lock} -D INPUT -i ${LXD_BRIDGE} -p tcp --dport 53 -j ACCEPT -m comment --comment "managed by lxd-bridge" if [ "${LXD_IPV4_FIREWALL}" = "true" ]; then iptables ${use_iptables_lock} -D FORWARD -i ${LXD_BRIDGE} -j ACCEPT -m comment --comment "managed by lxd-bridge" iptables ${use_iptables_lock} -D FORWARD -o ${LXD_BRIDGE} -j ACCEPT -m comment --comment "managed by lxd-bridge" fi iptables ${use_iptables_lock} -t mangle -D POSTROUTING -o ${LXD_BRIDGE} -p udp -m udp --dport 68 -j CHECKSUM --checksum-fill -m comment --comment "managed by lxd-bridge" || true if [ -n "${LXD_IPV4_NETWORK}" ] && [ "${LXD_IPV4_NAT}" = "true" ]; then iptables ${use_iptables_lock} -t nat -D POSTROUTING -s ${LXD_IPV4_NETWORK} ! -d ${LXD_IPV4_NETWORK} -j MASQUERADE -m comment --comment "managed by lxd-bridge" fi if [ "${HAS_IPV6}" = "true" ]; then ip6tables ${use_iptables_lock} -D INPUT -i ${LXD_BRIDGE} -p udp --dport 67 -j ACCEPT -m comment --comment "managed by lxd-bridge" ip6tables ${use_iptables_lock} -D INPUT -i ${LXD_BRIDGE} -p udp --dport 53 -j ACCEPT -m comment --comment "managed by lxd-bridge" ip6tables ${use_iptables_lock} -D INPUT -i ${LXD_BRIDGE} -p tcp --dport 53 -j ACCEPT -m comment --comment "managed by lxd-bridge" if [ "${LXD_IPV6_FIREWALL}" = "true" ]; then ip6tables ${use_iptables_lock} -D FORWARD -i ${LXD_BRIDGE} -j ACCEPT -m comment --comment "managed by lxd-bridge" ip6tables ${use_iptables_lock} -D FORWARD -o ${LXD_BRIDGE} -j ACCEPT -m comment --comment "managed by lxd-bridge" fi fi if [ "${HAS_IPV6}" = "true" ] && [ -n "${LXD_IPV6_NETWORK}" ] && [ "${LXD_IPV6_NAT}" = "true" ]; then ip6tables ${use_iptables_lock} -t nat -D POSTROUTING -s ${LXD_IPV6_NETWORK} ! -d ${LXD_IPV6_NETWORK} -j MASQUERADE -m comment --comment "managed by lxd-bridge" fi if [ -e "${varrun}/dnsmasq.pid" ]; then pid=$(cat "${varrun}/dnsmasq.pid" 2>/dev/null) && kill -9 "${pid}" rm -f "${varrun}/dnsmasq.pid" fi if [ -e "${varrun}/proxy.pid" ]; then pid=$(cat "${varrun}/proxy.pid" 2>/dev/null) && kill -9 "${pid}" rm -f "${varrun}/proxy.pid" fi # if ${LXD_BRIDGE} has attached interfaces, don't destroy the bridge ls /sys/class/net/${LXD_BRIDGE}/brif/* > /dev/null 2>&1 || ip link delete "${LXD_BRIDGE}" fi rm -f "${varrun}/network_up" } # See how we were called. case "${1}" in start) start ;; stop) stop ;; restart|reload|force-reload) ${0} stop ${0} start ;; *) echo "Usage: ${0} {start|stop|restart|reload|force-reload}" exit 2 esac exit $? ���������������������������������������������������������������������lxd-2.0.11/lxc/�������������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014257� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/version.go���������������������������������������������������������������������������0000644�0610621�0607500�00000001033�13172163242�016270� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared/version" ) type versionCmd struct{} func (c *versionCmd) showByDefault() bool { return true } func (c *versionCmd) usage() string { return i18n.G( `Usage: lxc version Print the version number of this client tool.`) } func (c *versionCmd) flags() { } func (c *versionCmd) run(conf *config.Config, args []string) error { if len(args) > 0 { return errArgs } fmt.Println(version.Version) return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/utils_test.go������������������������������������������������������������������������0000644�0610621�0607500�00000001415�13172163242�017006� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "testing" "github.com/stretchr/testify/suite" "github.com/lxc/lxd/shared/api" ) type utilsTestSuite struct { suite.Suite } func TestUtilsTestSuite(t *testing.T) { suite.Run(t, new(utilsTestSuite)) } func (s *utilsTestSuite) TestGetExistingAliases() { images := []api.ImageAliasesEntry{ {Name: "foo"}, {Name: "bar"}, {Name: "baz"}, } aliases := GetExistingAliases([]string{"bar", "foo", "other"}, images) s.Exactly([]api.ImageAliasesEntry{images[0], images[1]}, aliases) } func (s *utilsTestSuite) TestGetExistingAliasesEmpty() { images := []api.ImageAliasesEntry{ {Name: "foo"}, {Name: "bar"}, {Name: "baz"}, } aliases := GetExistingAliases([]string{"other1", "other2"}, images) s.Exactly([]api.ImageAliasesEntry{}, aliases) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/utils.go�����������������������������������������������������������������������������0000644�0610621�0607500�00000015611�13172163242�015752� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "net" "net/url" "os" "os/signal" "sort" "strings" "sync" "syscall" "time" "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/i18n" ) // Progress tracking type ProgressRenderer struct { Format string maxLength int wait time.Time done bool lock sync.Mutex } func (p *ProgressRenderer) Done(msg string) { // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Mark this renderer as done p.done = true // Print the new message if msg != "" { msg += "\n" } if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print("\r") fmt.Print(msg) } func (p *ProgressRenderer) Update(status string) { // Wait if needed timeout := p.wait.Sub(time.Now()) if timeout.Seconds() > 0 { time.Sleep(timeout) } // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Print the new message msg := "%s" if p.Format != "" { msg = p.Format } msg = fmt.Sprintf("\r"+msg, status) if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print(msg) } func (p *ProgressRenderer) Warn(status string, timeout time.Duration) { // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Render the new message p.wait = time.Now().Add(timeout) msg := fmt.Sprintf("\r%s", status) if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print(msg) } func (p *ProgressRenderer) UpdateProgress(progress lxd.ProgressData) { p.Update(progress.Text) } func (p *ProgressRenderer) UpdateOp(op api.Operation) { if op.Metadata == nil { return } for _, key := range []string{"fs_progress", "download_progress"} { value, ok := op.Metadata[key] if ok { p.Update(value.(string)) break } } } // Image fingerprint and alias sorting type SortImage [][]string func (a SortImage) Len() int { return len(a) } func (a SortImage) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a SortImage) Less(i, j int) bool { if a[i][0] == a[j][0] { if a[i][3] == "" { return false } if a[j][3] == "" { return true } return a[i][3] < a[j][3] } if a[i][0] == "" { return false } if a[j][0] == "" { return true } return a[i][0] < a[j][0] } // Container name sorting type byName [][]string func (a byName) Len() int { return len(a) } func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byName) Less(i, j int) bool { if a[i][0] == "" { return false } if a[j][0] == "" { return true } return a[i][0] < a[j][0] } // Storage volume sorting type byNameAndType [][]string func (a byNameAndType) Len() int { return len(a) } func (a byNameAndType) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byNameAndType) Less(i, j int) bool { if a[i][0] != a[j][0] { return a[i][0] < a[j][0] } if a[i][1] == "" { return false } if a[j][1] == "" { return true } return a[i][1] < a[j][1] } // Batch operations type batchResult struct { err error name string } func runBatch(names []string, action func(name string) error) []batchResult { chResult := make(chan batchResult, len(names)) for _, name := range names { go func(name string) { chResult <- batchResult{action(name), name} }(name) } results := []batchResult{} for range names { results = append(results, <-chResult) } return results } // summaryLine returns the first line of the help text. Conventionally, this // should be a one-line command summary, potentially followed by a longer // explanation. func summaryLine(usage string) string { for _, line := range strings.Split(usage, "\n") { if strings.HasPrefix(line, "Usage:") { continue } if len(line) == 0 { continue } return strings.TrimSuffix(line, ".") } return i18n.G("Missing summary.") } // Used to return a user friendly error func getLocalErr(err error) error { t, ok := err.(*url.Error) if !ok { return nil } u, ok := t.Err.(*net.OpError) if !ok { return nil } if u.Op == "dial" && u.Net == "unix" { var lxdErr error sysErr, ok := u.Err.(*os.SyscallError) if ok { lxdErr = sysErr.Err } else { // syscall.Errno may be returned on some systems, e.g. CentOS lxdErr, ok = u.Err.(syscall.Errno) if !ok { return nil } } switch lxdErr { case syscall.ENOENT, syscall.ECONNREFUSED, syscall.EACCES: return lxdErr } } return nil } // Wait for an operation and cancel it on SIGINT/SIGTERM func cancelableWait(op *lxd.RemoteOperation, progress *ProgressRenderer) error { // Signal handling chSignal := make(chan os.Signal) signal.Notify(chSignal, os.Interrupt) // Operation handling chOperation := make(chan error) go func() { chOperation <- op.Wait() close(chOperation) }() count := 0 for { select { case err := <-chOperation: return err case <-chSignal: err := op.CancelTarget() if err == nil { return fmt.Errorf(i18n.G("Remote operation canceled by user")) } else { count++ if count == 3 { return fmt.Errorf(i18n.G("User signaled us three times, exiting. The remote operation will keep running.")) } if progress != nil { progress.Warn(fmt.Sprintf(i18n.G("%v (interrupt two more times to force)"), err), time.Second*5) } } } } } // Create the specified image alises, updating those that already exist func ensureImageAliases(client lxd.ContainerServer, aliases []api.ImageAlias, fingerprint string) error { if len(aliases) == 0 { return nil } names := make([]string, len(aliases)) for i, alias := range aliases { names[i] = alias.Name } sort.Strings(names) resp, err := client.GetImageAliases() if err != nil { return err } // Delete existing aliases that match provided ones for _, alias := range GetExistingAliases(names, resp) { err := client.DeleteImageAlias(alias.Name) if err != nil { fmt.Println(fmt.Sprintf(i18n.G("Failed to remove alias %s"), alias.Name)) } } // Create new aliases for _, alias := range aliases { aliasPost := api.ImageAliasesPost{} aliasPost.Name = alias.Name aliasPost.Target = fingerprint err := client.CreateImageAlias(aliasPost) if err != nil { fmt.Println(fmt.Sprintf(i18n.G("Failed to create alias %s"), alias.Name)) } } return nil } // GetExistingAliases returns the intersection between a list of aliases and all the existing ones. func GetExistingAliases(aliases []string, allAliases []api.ImageAliasesEntry) []api.ImageAliasesEntry { existing := []api.ImageAliasesEntry{} for _, alias := range allAliases { name := alias.Name pos := sort.SearchStrings(aliases, name) if pos < len(aliases) && aliases[pos] == name { existing = append(existing, alias) } } return existing } �����������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/snapshot.go��������������������������������������������������������������������������0000644�0610621�0607500�00000002774�13172163242�016457� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type snapshotCmd struct { stateful bool } func (c *snapshotCmd) showByDefault() bool { return true } func (c *snapshotCmd) usage() string { return i18n.G( `Usage: lxc snapshot [<remote>:]<container> <snapshot name> [--stateful] Create container snapshots. When --stateful is used, LXD attempts to checkpoint the container's running state, including process memory state, TCP connections, ... *Examples* lxc snapshot u1 snap0 Create a snapshot of "u1" called "snap0".`) } func (c *snapshotCmd) flags() { gnuflag.BoolVar(&c.stateful, "stateful", false, i18n.G("Whether or not to snapshot the container's running state")) } func (c *snapshotCmd) run(conf *config.Config, args []string) error { if len(args) < 1 { return errArgs } var snapname string if len(args) < 2 { snapname = "" } else { snapname = args[1] } // we don't allow '/' in snapshot names if shared.IsSnapshot(snapname) { return fmt.Errorf(i18n.G("'/' not allowed in snapshot name")) } remote, name, err := conf.ParseRemote(args[0]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } req := api.ContainerSnapshotsPost{ Name: snapname, Stateful: c.stateful, } op, err := d.CreateContainerSnapshot(name, req) if err != nil { return err } return op.Wait() } ����lxd-2.0.11/lxc/restore.go���������������������������������������������������������������������������0000644�0610621�0607500�00000002546�13172163242�016300� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type restoreCmd struct { stateful bool } func (c *restoreCmd) showByDefault() bool { return true } func (c *restoreCmd) usage() string { return i18n.G( `Usage: lxc restore [<remote>:]<container> <snapshot> [--stateful] Restore containers from snapshots. If --stateful is passed, then the running state will be restored too. *Examples* lxc snapshot u1 snap0 Create the snapshot. lxc restore u1 snap0 Restore the snapshot.`) } func (c *restoreCmd) flags() { gnuflag.BoolVar(&c.stateful, "stateful", false, i18n.G("Whether or not to restore the container's running state from snapshot (if available)")) } func (c *restoreCmd) run(conf *config.Config, args []string) error { if len(args) < 2 { return errArgs } var snapname = args[1] remote, name, err := conf.ParseRemote(args[0]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } if !shared.IsSnapshot(snapname) { snapname = fmt.Sprintf("%s/%s", name, snapname) } req := api.ContainerPut{ Restore: snapname, Stateful: c.stateful, } op, err := d.UpdateContainer(name, req, "") if err != nil { return err } return op.Wait() } ����������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/remote.go����������������������������������������������������������������������������0000644�0610621�0607500�00000023556�13172163242�016114� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "crypto/x509" "encoding/pem" "fmt" "net" "net/url" "os" "path/filepath" "sort" "strings" "github.com/olekukonko/tablewriter" "golang.org/x/crypto/ssh/terminal" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared/logger" ) type remoteCmd struct { acceptCert bool password string public bool protocol string } func (c *remoteCmd) showByDefault() bool { return true } func (c *remoteCmd) usage() string { return i18n.G( `Usage: lxc remote <subcommand> [options] Manage the list of remote LXD servers. lxc remote add <remote> <IP|FQDN|URL> [--accept-certificate] [--password=PASSWORD] [--public] [--protocol=PROTOCOL] Add the remote <remote> at <url>. lxc remote remove <remote> Remove the remote <remote>. lxc remote list List all remotes. lxc remote rename <old name> <new name> Rename remote <old name> to <new name>. lxc remote set-url <remote> <url> Update <remote>'s url to <url>. lxc remote set-default <remote> Set the default remote. lxc remote get-default Print the default remote.`) } func (c *remoteCmd) flags() { gnuflag.BoolVar(&c.acceptCert, "accept-certificate", false, i18n.G("Accept certificate")) gnuflag.StringVar(&c.password, "password", "", i18n.G("Remote admin password")) gnuflag.StringVar(&c.protocol, "protocol", "", i18n.G("Server protocol (lxd or simplestreams)")) gnuflag.BoolVar(&c.public, "public", false, i18n.G("Public image server")) } func (c *remoteCmd) addServer(conf *config.Config, server string, addr string, acceptCert bool, password string, public bool, protocol string) error { var rScheme string var rHost string var rPort string // Setup the remotes list if conf.Remotes == nil { conf.Remotes = make(map[string]config.Remote) } /* Complex remote URL parsing */ remoteURL, err := url.Parse(addr) if err != nil { remoteURL = &url.URL{Host: addr} } // Fast track simplestreams if protocol == "simplestreams" { if remoteURL.Scheme != "https" { return fmt.Errorf(i18n.G("Only https URLs are supported for simplestreams")) } conf.Remotes[server] = config.Remote{Addr: addr, Public: true, Protocol: protocol} return nil } // Fix broken URL parser if !strings.Contains(addr, "://") && remoteURL.Scheme != "" && remoteURL.Scheme != "unix" && remoteURL.Host == "" { remoteURL.Host = addr remoteURL.Scheme = "" } if remoteURL.Scheme != "" { if remoteURL.Scheme != "unix" && remoteURL.Scheme != "https" { return fmt.Errorf(i18n.G("Invalid URL scheme \"%s\" in \"%s\""), remoteURL.Scheme, addr) } rScheme = remoteURL.Scheme } else if addr[0] == '/' { rScheme = "unix" } else { if !shared.IsUnixSocket(addr) { rScheme = "https" } else { rScheme = "unix" } } if remoteURL.Host != "" { rHost = remoteURL.Host } else { rHost = addr } host, port, err := net.SplitHostPort(rHost) if err == nil { rHost = host rPort = port } else { rPort = shared.DefaultPort } if rScheme == "unix" { rHost = strings.TrimPrefix(strings.TrimPrefix(addr, "unix:"), "//") rPort = "" } if strings.Contains(rHost, ":") && !strings.HasPrefix(rHost, "[") { rHost = fmt.Sprintf("[%s]", rHost) } if rPort != "" { addr = rScheme + "://" + rHost + ":" + rPort } else { addr = rScheme + "://" + rHost } /* Actually add the remote */ conf.Remotes[server] = config.Remote{Addr: addr, Protocol: protocol} // Attempt to connect var d interface{} if public { d, err = conf.GetImageServer(server) } else { d, err = conf.GetContainerServer(server) } // Handle Unix socket connections if strings.HasPrefix(addr, "unix:") { return err } // Check if the system CA worked for the TLS connection var certificate *x509.Certificate if err != nil { // Failed to connect using the system CA, so retrieve the remote certificate certificate, err = shared.GetRemoteCertificate(addr) if err != nil { return err } } // Handle certificate prompt if certificate != nil { if !acceptCert { digest := shared.CertFingerprint(certificate) fmt.Printf(i18n.G("Certificate fingerprint: %s")+"\n", digest) fmt.Printf(i18n.G("ok (y/n)?") + " ") line, err := shared.ReadStdin() if err != nil { return err } if len(line) < 1 || line[0] != 'y' && line[0] != 'Y' { return fmt.Errorf(i18n.G("Server certificate NACKed by user")) } } dnam := conf.ConfigPath("servercerts") err := os.MkdirAll(dnam, 0750) if err != nil { return fmt.Errorf(i18n.G("Could not create server cert dir")) } certf := fmt.Sprintf("%s/%s.crt", dnam, server) certOut, err := os.Create(certf) if err != nil { return err } pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certificate.Raw}) certOut.Close() // Setup a new connection, this time with the remote certificate if public { d, err = conf.GetImageServer(server) } else { d, err = conf.GetContainerServer(server) } if err != nil { return err } } // Handle public remotes if public { conf.Remotes[server] = config.Remote{Addr: addr, Public: true} return nil } // Get server information srv, _, err := d.(lxd.ContainerServer).GetServer() if err != nil { return err } // Detect public remotes if srv.Public { conf.Remotes[server] = config.Remote{Addr: addr, Public: true} return nil } // Check if our cert is already trusted if srv.Auth == "trusted" { return nil } // Prompt for trust password if password == "" { fmt.Printf(i18n.G("Admin password for %s: "), server) pwd, err := terminal.ReadPassword(0) if err != nil { /* We got an error, maybe this isn't a terminal, let's try to * read it as a file */ pwd, err = shared.ReadStdin() if err != nil { return err } } fmt.Println("") password = string(pwd) } // Add client certificate to trust store req := api.CertificatesPost{ Password: password, } req.Type = "client" err = d.(lxd.ContainerServer).CreateCertificate(req) if err != nil { return err } // And check if trusted now srv, _, err = d.(lxd.ContainerServer).GetServer() if err != nil { return err } if srv.Auth != "trusted" { return fmt.Errorf(i18n.G("Server doesn't trust us after adding our cert")) } fmt.Println(i18n.G("Client certificate stored at server: "), server) return nil } func (c *remoteCmd) removeCertificate(conf *config.Config, remote string) { certf := conf.ServerCertPath(remote) logger.Debugf("Trying to remove %s", certf) os.Remove(certf) } func (c *remoteCmd) run(conf *config.Config, args []string) error { if len(args) < 1 { return errUsage } switch args[0] { case "add": if len(args) < 3 { return errArgs } if rc, ok := conf.Remotes[args[1]]; ok { return fmt.Errorf(i18n.G("remote %s exists as <%s>"), args[1], rc.Addr) } err := c.addServer(conf, args[1], args[2], c.acceptCert, c.password, c.public, c.protocol) if err != nil { delete(conf.Remotes, args[1]) c.removeCertificate(conf, args[1]) return err } case "remove": if len(args) != 2 { return errArgs } rc, ok := conf.Remotes[args[1]] if !ok { return fmt.Errorf(i18n.G("remote %s doesn't exist"), args[1]) } if rc.Static { return fmt.Errorf(i18n.G("remote %s is static and cannot be modified"), args[1]) } if conf.DefaultRemote == args[1] { return fmt.Errorf(i18n.G("can't remove the default remote")) } delete(conf.Remotes, args[1]) c.removeCertificate(conf, args[1]) case "list": data := [][]string{} for name, rc := range conf.Remotes { strPublic := i18n.G("NO") if rc.Public { strPublic = i18n.G("YES") } strStatic := i18n.G("NO") if rc.Static { strStatic = i18n.G("YES") } if rc.Protocol == "" { rc.Protocol = "lxd" } strName := name if name == conf.DefaultRemote { strName = fmt.Sprintf("%s (%s)", name, i18n.G("default")) } data = append(data, []string{strName, rc.Addr, rc.Protocol, strPublic, strStatic}) } table := tablewriter.NewWriter(os.Stdout) table.SetAutoWrapText(false) table.SetAlignment(tablewriter.ALIGN_LEFT) table.SetRowLine(true) table.SetHeader([]string{ i18n.G("NAME"), i18n.G("URL"), i18n.G("PROTOCOL"), i18n.G("PUBLIC"), i18n.G("STATIC")}) sort.Sort(byName(data)) table.AppendBulk(data) table.Render() return nil case "rename": if len(args) != 3 { return errArgs } rc, ok := conf.Remotes[args[1]] if !ok { return fmt.Errorf(i18n.G("remote %s doesn't exist"), args[1]) } if rc.Static { return fmt.Errorf(i18n.G("remote %s is static and cannot be modified"), args[1]) } if _, ok := conf.Remotes[args[2]]; ok { return fmt.Errorf(i18n.G("remote %s already exists"), args[2]) } // Rename the certificate file oldPath := filepath.Join(conf.ConfigPath("servercerts"), fmt.Sprintf("%s.crt", args[1])) newPath := filepath.Join(conf.ConfigPath("servercerts"), fmt.Sprintf("%s.crt", args[2])) if shared.PathExists(oldPath) { err := os.Rename(oldPath, newPath) if err != nil { return err } } conf.Remotes[args[2]] = rc delete(conf.Remotes, args[1]) if conf.DefaultRemote == args[1] { conf.DefaultRemote = args[2] } case "set-url": if len(args) != 3 { return errArgs } rc, ok := conf.Remotes[args[1]] if !ok { return fmt.Errorf(i18n.G("remote %s doesn't exist"), args[1]) } if rc.Static { return fmt.Errorf(i18n.G("remote %s is static and cannot be modified"), args[1]) } conf.Remotes[args[1]] = config.Remote{Addr: args[2]} case "set-default": if len(args) != 2 { return errArgs } _, ok := conf.Remotes[args[1]] if !ok { return fmt.Errorf(i18n.G("remote %s doesn't exist"), args[1]) } conf.DefaultRemote = args[1] case "get-default": if len(args) != 1 { return errArgs } fmt.Println(conf.DefaultRemote) return nil default: return errArgs } return conf.SaveConfig(configPath) } ��������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/publish.go���������������������������������������������������������������������������0000644�0610621�0607500�00000011775�13172163242�016267� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "strings" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared" ) type publishCmd struct { pAliases aliasList // aliasList defined in lxc/image.go makePublic bool Force bool } func (c *publishCmd) showByDefault() bool { return true } func (c *publishCmd) usage() string { return i18n.G( `Usage: lxc publish [<remote>:]<container>[/<snapshot>] [<remote>:] [--alias=ALIAS...] [prop-key=prop-value...] Publish containers as images.`) } func (c *publishCmd) flags() { gnuflag.BoolVar(&c.makePublic, "public", false, i18n.G("Make the image public")) gnuflag.Var(&c.pAliases, "alias", i18n.G("New alias to define at target")) gnuflag.BoolVar(&c.Force, "force", false, i18n.G("Stop the container if currently running")) gnuflag.BoolVar(&c.Force, "f", false, i18n.G("Stop the container if currently running")) } func (c *publishCmd) run(conf *config.Config, args []string) error { iName := "" iRemote := "" properties := map[string]string{} firstprop := 1 // first property is arg[2] if arg[1] is image remote, else arg[1] if len(args) < 1 { return errArgs } cRemote, cName, err := conf.ParseRemote(args[0]) if err != nil { return err } if len(args) >= 2 && !strings.Contains(args[1], "=") { firstprop = 2 iRemote, iName, err = conf.ParseRemote(args[1]) if err != nil { return err } } else { iRemote, iName, err = conf.ParseRemote("") if err != nil { return err } } if cName == "" { return fmt.Errorf(i18n.G("Container name is mandatory")) } if iName != "" { return fmt.Errorf(i18n.G("There is no \"image name\". Did you want an alias?")) } d, err := conf.GetContainerServer(iRemote) if err != nil { return err } s := d if cRemote != iRemote { s, err = conf.GetContainerServer(cRemote) if err != nil { return err } } if !shared.IsSnapshot(cName) { ct, etag, err := s.GetContainer(cName) if err != nil { return err } wasRunning := ct.StatusCode != 0 && ct.StatusCode != api.Stopped wasEphemeral := ct.Ephemeral if wasRunning { if !c.Force { return fmt.Errorf(i18n.G("The container is currently running. Use --force to have it stopped and restarted.")) } if ct.Ephemeral { ct.Ephemeral = false op, err := s.UpdateContainer(cName, ct.Writable(), etag) if err != nil { return err } err = op.Wait() if err != nil { return err } // Refresh the ETag _, etag, err = s.GetContainer(cName) if err != nil { return err } } req := api.ContainerStatePut{ Action: string(shared.Stop), Timeout: -1, Force: true, } op, err := s.UpdateContainerState(cName, req, "") if err != nil { return err } err = op.Wait() if err != nil { return fmt.Errorf(i18n.G("Stopping container failed!")) } defer func() { req.Action = string(shared.Start) op, err = s.UpdateContainerState(cName, req, "") if err != nil { return } op.Wait() }() if wasEphemeral { ct.Ephemeral = true op, err := s.UpdateContainer(cName, ct.Writable(), etag) if err != nil { return err } err = op.Wait() if err != nil { return err } } } } for i := firstprop; i < len(args); i++ { entry := strings.SplitN(args[i], "=", 2) if len(entry) < 2 { return errArgs } properties[entry[0]] = entry[1] } // We should only set the properties field if there actually are any. // Otherwise we will only delete any existing properties on publish. // This is something which only direct callers of the API are allowed to // do. if len(properties) == 0 { properties = nil } // Reformat aliases aliases := []api.ImageAlias{} for _, entry := range c.pAliases { alias := api.ImageAlias{} alias.Name = entry aliases = append(aliases, alias) } // Create the image req := api.ImagesPost{ Source: &api.ImagesPostSource{ Type: "container", Name: cName, }, } req.Properties = properties if shared.IsSnapshot(cName) { req.Source.Type = "snapshot" } if cRemote == iRemote { req.Public = c.makePublic } op, err := s.CreateImage(req, nil) if err != nil { return err } err = op.Wait() if err != nil { return err } // Grab the fingerprint fingerprint := op.Metadata["fingerprint"].(string) // For remote publish, copy to target now if cRemote != iRemote { defer s.DeleteImage(fingerprint) // Get the source image image, _, err := s.GetImage(fingerprint) if err != nil { return err } // Image copy arguments args := lxd.ImageCopyArgs{ Public: c.makePublic, } // Copy the image to the destination host op, err := d.CopyImage(s, *image, &args) if err != nil { return err } err = op.Wait() if err != nil { return err } } err = ensureImageAliases(d, aliases, fingerprint) if err != nil { return err } fmt.Printf(i18n.G("Container published with fingerprint: %s")+"\n", fingerprint) return nil } ���lxd-2.0.11/lxc/profile.go���������������������������������������������������������������������������0000644�0610621�0607500�00000023304�13172163242�016250� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "os" "strings" "syscall" "gopkg.in/yaml.v2" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared/termios" ) type profileCmd struct { } func (c *profileCmd) showByDefault() bool { return true } func (c *profileCmd) profileEditHelp() string { return i18n.G( `### This is a yaml representation of the profile. ### Any line starting with a '# will be ignored. ### ### A profile consists of a set of configuration items followed by a set of ### devices. ### ### An example would look like: ### name: onenic ### config: ### raw.lxc: lxc.aa_profile=unconfined ### devices: ### eth0: ### nictype: bridged ### parent: lxdbr0 ### type: nic ### ### Note that the name is shown but cannot be changed`) } func (c *profileCmd) usage() string { return i18n.G( `Usage: lxc profile <subcommand> [options] Manage container configuration profiles. *Profile configuration* lxc profile list [<remote>:] List available profiles. lxc profile show [<remote>:]<profile> Show details of a profile. lxc profile create [<remote>:]<profile> Create a profile. lxc profile copy [<remote>:]<profile> [<remote>:]<profile> Copy the profile. lxc profile get [<remote>:]<profile> <key> Get profile configuration. lxc profile set [<remote>:]<profile> <key> <value> Set profile configuration. lxc profile unset [<remote>:]<profile> <key> Unset profile configuration. lxc profile delete [<remote>:]<profile> Delete a profile. lxc profile edit [<remote>:]<profile> Edit profile, either by launching external editor or reading STDIN. *Profile assignment* lxc profile apply [<remote>:]<container> <profiles> Replace the current set of profiles for the container by the one provided. *Device management* lxc profile device list [<remote>:]<profile> List devices in the given profile. lxc profile device show [<remote>:]<profile> Show full device details in the given profile. lxc profile device remove [<remote>:]<profile> <name> Remove a device from a profile. lxc profile device get [<remote>:]<profile> <name> <key> Get a device property. lxc profile device set [<remote>:]<profile> <name> <key> <value> Set a device property. lxc profile device unset [<remote>:]<profile> <name> <key> Unset a device property. lxc profile device add [<remote>:]<profile> <device> <type> [key=value...] Add a profile device, such as a disk or a nic, to the containers using the specified profile. *Examples* cat profile.yaml | lxc profile edit <profile> Update a profile using the content of profile.yaml lxc profile apply foo default,bar Set the profiles for "foo" to "default" and "bar". lxc profile apply foo default Reset "foo" to only using the "default" profile. lxc profile apply foo '' Remove all profile from "foo"`) } func (c *profileCmd) flags() {} func (c *profileCmd) run(conf *config.Config, args []string) error { if len(args) < 1 { return errUsage } if args[0] == "list" { return c.doProfileList(conf, args) } if len(args) < 2 { return errArgs } remote, profile, err := conf.ParseRemote(args[1]) if err != nil { return err } client, err := conf.GetContainerServer(remote) if err != nil { return err } switch args[0] { case "create": return c.doProfileCreate(client, profile) case "delete": return c.doProfileDelete(client, profile) case "device": return c.doProfileDevice(conf, args) case "edit": return c.doProfileEdit(client, profile) case "apply": container := profile switch len(args) { case 2: profile = "" case 3: profile = args[2] default: return errArgs } return c.doProfileApply(client, container, profile) case "get": return c.doProfileGet(client, profile, args[2:]) case "set": return c.doProfileSet(client, profile, args[2:]) case "unset": return c.doProfileUnset(client, profile, args[2:]) case "copy": return c.doProfileCopy(conf, client, profile, args[2:]) case "show": return c.doProfileShow(client, profile) default: return errArgs } } func (c *profileCmd) doProfileCreate(client lxd.ContainerServer, p string) error { profile := api.ProfilesPost{} profile.Name = p err := client.CreateProfile(profile) if err == nil { fmt.Printf(i18n.G("Profile %s created")+"\n", p) } return err } func (c *profileCmd) doProfileEdit(client lxd.ContainerServer, p string) error { // If stdin isn't a terminal, read text from it if !termios.IsTerminal(int(syscall.Stdin)) { contents, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } newdata := api.ProfilePut{} err = yaml.Unmarshal(contents, &newdata) if err != nil { return err } return client.UpdateProfile(p, newdata, "") } // Extract the current value profile, etag, err := client.GetProfile(p) if err != nil { return err } data, err := yaml.Marshal(&profile) if err != nil { return err } // Spawn the editor content, err := shared.TextEditor("", []byte(c.profileEditHelp()+"\n\n"+string(data))) if err != nil { return err } for { // Parse the text received from the editor newdata := api.ProfilePut{} err = yaml.Unmarshal(content, &newdata) if err == nil { err = client.UpdateProfile(p, newdata, etag) } // Respawn the editor if err != nil { fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err) fmt.Println(i18n.G("Press enter to open the editor again")) _, err := os.Stdin.Read(make([]byte, 1)) if err != nil { return err } content, err = shared.TextEditor("", content) if err != nil { return err } continue } break } return nil } func (c *profileCmd) doProfileDelete(client lxd.ContainerServer, p string) error { err := client.DeleteProfile(p) if err != nil { return err } fmt.Printf(i18n.G("Profile %s deleted")+"\n", p) return nil } func (c *profileCmd) doProfileApply(client lxd.ContainerServer, d string, p string) error { container, etag, err := client.GetContainer(d) if err != nil { return err } if p != "" { container.Profiles = strings.Split(p, ",") } else { container.Profiles = nil } op, err := client.UpdateContainer(d, container.Writable(), etag) if err != nil { return err } err = op.Wait() if err != nil { return err } if p == "" { p = i18n.G("(none)") } fmt.Printf(i18n.G("Profiles %s applied to %s")+"\n", p, d) return nil } func (c *profileCmd) doProfileShow(client lxd.ContainerServer, p string) error { profile, _, err := client.GetProfile(p) if err != nil { return err } data, err := yaml.Marshal(&profile) if err != nil { return err } fmt.Printf("%s", data) return nil } func (c *profileCmd) doProfileCopy(conf *config.Config, client lxd.ContainerServer, p string, args []string) error { if len(args) != 1 { return errArgs } remote, newname, err := conf.ParseRemote(args[0]) if err != nil { return err } if newname == "" { newname = p } dest, err := conf.GetContainerServer(remote) if err != nil { return err } profile, _, err := client.GetProfile(p) if err != nil { return err } newProfile := api.ProfilesPost{ ProfilePut: profile.Writable(), Name: newname, } return dest.CreateProfile(newProfile) } func (c *profileCmd) doProfileDevice(conf *config.Config, args []string) error { // device add b1 eth0 nic type=bridged // device list b1 // device remove b1 eth0 if len(args) < 3 { return errArgs } cfg := configCmd{} switch args[1] { case "add": return cfg.deviceAdd(conf, "profile", args) case "remove": return cfg.deviceRm(conf, "profile", args) case "list": return cfg.deviceList(conf, "profile", args) case "show": return cfg.deviceShow(conf, "profile", args) case "get": return cfg.deviceGet(conf, "profile", args) case "set": return cfg.deviceSet(conf, "profile", args) case "unset": return cfg.deviceUnset(conf, "profile", args) default: return errArgs } } func (c *profileCmd) doProfileGet(client lxd.ContainerServer, p string, args []string) error { // we shifted @args so so it should read "<key>" if len(args) != 1 { return errArgs } profile, _, err := client.GetProfile(p) if err != nil { return err } fmt.Printf("%s\n", profile.Config[args[0]]) return nil } func (c *profileCmd) doProfileSet(client lxd.ContainerServer, p string, args []string) error { // we shifted @args so so it should read "<key> [<value>]" if len(args) < 1 { return errArgs } key := args[0] var value string if len(args) < 2 { value = "" } else { value = args[1] } if !termios.IsTerminal(int(syscall.Stdin)) && value == "-" { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return fmt.Errorf("Can't read from stdin: %s", err) } value = string(buf[:]) } profile, etag, err := client.GetProfile(p) if err != nil { return err } profile.Config[key] = value return client.UpdateProfile(p, profile.Writable(), etag) } func (c *profileCmd) doProfileUnset(client lxd.ContainerServer, p string, args []string) error { // we shifted @args so so it should read "<key> [<value>]" if len(args) != 1 { return errArgs } return c.doProfileSet(client, p, args) } func (c *profileCmd) doProfileList(conf *config.Config, args []string) error { var remote string if len(args) > 1 { var name string var err error remote, name, err = conf.ParseRemote(args[1]) if err != nil { return err } if name != "" { return fmt.Errorf(i18n.G("Cannot provide container name to list")) } } else { remote = conf.DefaultRemote } client, err := conf.GetContainerServer(remote) if err != nil { return err } profiles, err := client.GetProfileNames() if err != nil { return err } fmt.Printf("%s\n", strings.Join(profiles, "\n")) return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/move.go������������������������������������������������������������������������������0000644�0610621�0607500�00000004540�13172163242�015557� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "strings" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/i18n" ) type moveCmd struct { } func (c *moveCmd) showByDefault() bool { return true } func (c *moveCmd) usage() string { return i18n.G( `Usage: lxc move [<remote>:]<container>[/<snapshot>] [<remote>:][<container>[/<snapshot>]] Move containers within or in between LXD instances. lxc move [<remote>:]<source container> [<remote>:][<destination container>] Move a container between two hosts, renaming it if destination name differs. lxc move <old name> <new name> Rename a local container. lxc move <container>/<old snapshot name> <container>/<new snapshot name> Rename a snapshot.`) } func (c *moveCmd) flags() {} func (c *moveCmd) run(conf *config.Config, args []string) error { if len(args) != 2 { return errArgs } sourceRemote, sourceName, err := conf.ParseRemote(args[0]) if err != nil { return err } destRemote, destName, err := conf.ParseRemote(args[1]) if err != nil { return err } // As an optimization, if the source an destination are the same, do // this via a simple rename. This only works for containers that aren't // running, containers that are running should be live migrated (of // course, this changing of hostname isn't supported right now, so this // simply won't work). if sourceRemote == destRemote { source, err := conf.GetContainerServer(sourceRemote) if err != nil { return err } if shared.IsSnapshot(sourceName) { // Snapshot rename srcFields := strings.SplitN(sourceName, shared.SnapshotDelimiter, 2) dstFields := strings.SplitN(destName, shared.SnapshotDelimiter, 2) op, err := source.RenameContainerSnapshot(srcFields[0], srcFields[1], api.ContainerSnapshotPost{Name: dstFields[1]}) if err != nil { return err } return op.Wait() } // Container rename op, err := source.RenameContainer(sourceName, api.ContainerPost{Name: destName}) if err != nil { return err } return op.Wait() } cpy := copyCmd{} // A move is just a copy followed by a delete; however, we want to // keep the volatile entries around since we are moving the container. err = cpy.copyContainer(conf, args[0], args[1], true, -1) if err != nil { return err } del := deleteCmd{} del.force = true return del.run(conf, args[:1]) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/monitor.go���������������������������������������������������������������������������0000644�0610621�0607500�00000003352�13172163242�016300� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "gopkg.in/yaml.v2" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type typeList []string func (f *typeList) String() string { return fmt.Sprint(*f) } func (f *typeList) Set(value string) error { if value == "" { return fmt.Errorf("Invalid type: %s", value) } if f == nil { *f = make(typeList, 1) } else { *f = append(*f, value) } return nil } type monitorCmd struct { typeArgs typeList } func (c *monitorCmd) showByDefault() bool { return false } func (c *monitorCmd) usage() string { return i18n.G( `Usage: lxc monitor [<remote>:] [--type=TYPE...] Monitor a local or remote LXD server. By default the monitor will listen to all message types. Message types to listen for can be specified with --type. *Examples* lxc monitor --type=logging Only show log message.`) } func (c *monitorCmd) flags() { gnuflag.Var(&c.typeArgs, "type", i18n.G("Event type to listen for")) } func (c *monitorCmd) run(conf *config.Config, args []string) error { var err error var remote string if len(args) > 1 { return errArgs } if len(args) == 0 { remote, _, err = conf.ParseRemote("") if err != nil { return err } } else { remote, _, err = conf.ParseRemote(args[0]) if err != nil { return err } } d, err := conf.GetContainerServer(remote) if err != nil { return err } listener, err := d.GetEvents() if err != nil { return err } handler := func(message interface{}) { render, err := yaml.Marshal(&message) if err != nil { fmt.Printf("error: %s\n", err) return } fmt.Printf("%s\n\n", render) } _, err = listener.AddHandler(c.typeArgs, handler) if err != nil { return err } return listener.Wait() } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/manpage.go���������������������������������������������������������������������������0000644�0610621�0607500�00000002632�13172163242�016221� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "os/exec" "path/filepath" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/i18n" ) type manpageCmd struct{} func (c *manpageCmd) showByDefault() bool { return false } func (c *manpageCmd) usage() string { return i18n.G( `Usage: lxc manpage <directory> Generate all the LXD manpages.`) } func (c *manpageCmd) flags() { } func (c *manpageCmd) run(conf *config.Config, args []string) error { if len(args) != 1 { return errArgs } _, err := exec.LookPath("help2man") if err != nil { return fmt.Errorf(i18n.G("Unable to find help2man.")) } help2man := func(command string, title string, path string) error { target, err := os.Create(path) if err != nil { return err } defer target.Close() cmd := exec.Command("help2man", command, "-n", title, "--no-info") cmd.Stdout = target return cmd.Run() } // Generate the main manpage err = help2man(fmt.Sprintf("%s --all", execName), "LXD - client", filepath.Join(args[0], fmt.Sprintf("lxc.1"))) if err != nil { return fmt.Errorf(i18n.G("Failed to generate 'lxc.1': %v"), err) } // Generate the pages for the subcommands for k, cmd := range commands { err := help2man(fmt.Sprintf("%s %s", execName, k), summaryLine(cmd.usage()), filepath.Join(args[0], fmt.Sprintf("lxc.%s.1", k))) if err != nil { return fmt.Errorf(i18n.G("Failed to generate 'lxc.%s.1': %v"), k, err) } } return nil } ������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/main_test.go�������������������������������������������������������������������������0000644�0610621�0607500�00000002342�13172163242�016572� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "testing" "github.com/lxc/lxd/lxc/config" ) type aliasTestcase struct { input []string expected []string } func slicesEqual(a, b []string) bool { if a == nil && b == nil { return true } if a == nil || b == nil { return false } if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } func TestExpandAliases(t *testing.T) { aliases := map[string]string{ "tester 12": "list", "foo": "list @ARGS@ -c n", } testcases := []aliasTestcase{ { input: []string{"lxc", "list"}, expected: []string{"lxc", "list"}, }, { input: []string{"lxc", "tester", "12"}, expected: []string{"lxc", "list", "--no-alias"}, }, { input: []string{"lxc", "foo", "asdf"}, expected: []string{"lxc", "list", "--no-alias", "asdf", "-c", "n"}, }, } conf := &config.Config{Aliases: aliases} for _, tc := range testcases { result, expanded := expandAlias(conf, tc.input) if !expanded { if !slicesEqual(tc.input, tc.expected) { t.Errorf("didn't expand when expected to: %s", tc.input) } continue } if !slicesEqual(result, tc.expected) { t.Errorf("%s didn't match %s", result, tc.expected) } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/main.go������������������������������������������������������������������������������0000644�0610621�0607500�00000017431�13172163242�015540� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "os/exec" "os/user" "path" "path/filepath" "strings" "syscall" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/logging" "github.com/lxc/lxd/shared/version" ) var configPath string var execName string func main() { execName = os.Args[0] if err := run(); err != nil { msg := fmt.Sprintf(i18n.G("error: %v"), err) lxdErr := getLocalErr(err) switch lxdErr { case syscall.ENOENT: msg = i18n.G("LXD socket not found; is LXD installed and running?") case syscall.ECONNREFUSED: msg = i18n.G("Connection refused; is LXD running?") case syscall.EACCES: msg = i18n.G("Permission denied, are you in the lxd group?") } fmt.Fprintln(os.Stderr, fmt.Sprintf("%s", msg)) os.Exit(1) } } func run() error { verbose := gnuflag.Bool("verbose", false, i18n.G("Enable verbose mode")) debug := gnuflag.Bool("debug", false, i18n.G("Enable debug mode")) forceLocal := gnuflag.Bool("force-local", false, i18n.G("Force using the local unix socket")) noAlias := gnuflag.Bool("no-alias", false, i18n.G("Ignore aliases when determining what command to run")) var configDir string if os.Getenv("LXD_CONF") != "" { configDir = os.Getenv("LXD_CONF") } else if os.Getenv("HOME") != "" { configDir = path.Join(os.Getenv("HOME"), ".config", "lxc") } else { user, err := user.Current() if err != nil { return err } configDir = path.Join(user.HomeDir, ".config", "lxc") } configPath = os.ExpandEnv(path.Join(configDir, "config.yml")) if len(os.Args) >= 3 && os.Args[1] == "config" && os.Args[2] == "profile" { fmt.Fprintf(os.Stderr, i18n.G("`lxc config profile` is deprecated, please use `lxc profile`")+"\n") os.Args = append(os.Args[:1], os.Args[2:]...) } if len(os.Args) >= 2 && (os.Args[1] == "-h" || os.Args[1] == "--help") { os.Args[1] = "help" } if len(os.Args) >= 2 && (os.Args[1] == "--all") { os.Args = []string{os.Args[0], "help", "--all"} } if shared.StringInSlice("--version", os.Args) { os.Args = []string{os.Args[0], "version"} } if len(os.Args) < 2 { commands["help"].run(nil, nil) os.Exit(1) } var conf *config.Config var err error if *forceLocal { conf = &config.DefaultConfig } else if shared.PathExists(configPath) { conf, err = config.LoadConfig(configPath) if err != nil { return err } } else { conf = &config.DefaultConfig conf.ConfigDir = filepath.Dir(configPath) } // Set the user agent conf.UserAgent = version.UserAgent // This is quite impolite, but it seems gnuflag needs us to shift our // own exename out of the arguments before parsing them. However, this // is useful for execIfAlias, which wants to know exactly the command // line we received, and in some cases is called before this shift, and // in others after. So, let's save the original args. origArgs := os.Args name := os.Args[1] /* at this point we haven't parsed the args, so we have to look for * --no-alias by hand. */ if !shared.StringInSlice("--no-alias", origArgs) { execIfAliases(conf, origArgs) } cmd, ok := commands[name] if !ok { commands["help"].run(nil, nil) fmt.Fprintf(os.Stderr, "\n"+i18n.G("error: unknown command: %s")+"\n", name) os.Exit(1) } cmd.flags() gnuflag.Usage = func() { fmt.Print(cmd.usage()) fmt.Printf("\n\n%s\n", i18n.G("Options:")) gnuflag.SetOut(os.Stdout) gnuflag.PrintDefaults() os.Exit(0) } os.Args = os.Args[1:] gnuflag.Parse(true) logger.Log, err = logging.GetLogger("", "", *verbose, *debug, nil) if err != nil { return err } certf := conf.ConfigPath("client.crt") keyf := conf.ConfigPath("client.key") if !*forceLocal && os.Args[0] != "help" && os.Args[0] != "version" && (!shared.PathExists(certf) || !shared.PathExists(keyf)) { fmt.Fprintf(os.Stderr, i18n.G("Generating a client certificate. This may take a minute...")+"\n") err = shared.FindOrGenCert(certf, keyf, true) if err != nil { return err } if shared.PathExists("/var/lib/lxd/") { fmt.Fprintf(os.Stderr, i18n.G("If this is your first time using LXD, you should also run: sudo lxd init")+"\n") fmt.Fprintf(os.Stderr, i18n.G("To start your first container, try: lxc launch ubuntu:16.04")+"\n\n") } } err = cmd.run(conf, gnuflag.Args()) if err == errArgs || err == errUsage { out := os.Stdout if err == errArgs { /* If we got an error about invalid arguments, let's try to * expand this as an alias */ if !*noAlias { execIfAliases(conf, origArgs) } out = os.Stderr } gnuflag.SetOut(out) if err == errArgs { fmt.Fprintf(out, i18n.G("error: %v"), err) fmt.Fprintf(out, "\n\n") } fmt.Fprint(out, cmd.usage()) fmt.Fprintf(out, "\n\n%s\n", i18n.G("Options:")) gnuflag.PrintDefaults() if err == errArgs { os.Exit(1) } os.Exit(0) } return err } type command interface { usage() string flags() showByDefault() bool run(config *config.Config, args []string) error } var commands = map[string]command{ "config": &configCmd{}, "copy": &copyCmd{}, "delete": &deleteCmd{}, "exec": &execCmd{}, "file": &fileCmd{}, "finger": &fingerCmd{}, "help": &helpCmd{}, "image": &imageCmd{}, "info": &infoCmd{}, "init": &initCmd{}, "launch": &launchCmd{}, "list": &listCmd{}, "monitor": &monitorCmd{}, "move": &moveCmd{}, "pause": &actionCmd{ action: shared.Freeze, description: i18n.G("Pause containers."), name: "pause", }, "profile": &profileCmd{}, "publish": &publishCmd{}, "remote": &remoteCmd{}, "restart": &actionCmd{ action: shared.Restart, description: i18n.G("Restart containers."), hasTimeout: true, visible: true, name: "restart", timeout: -1, }, "restore": &restoreCmd{}, "snapshot": &snapshotCmd{}, "start": &actionCmd{ action: shared.Start, description: i18n.G("Start containers."), visible: true, name: "start", }, "stop": &actionCmd{ action: shared.Stop, description: i18n.G("Stop containers."), hasTimeout: true, visible: true, name: "stop", timeout: -1, }, "version": &versionCmd{}, } var errArgs = fmt.Errorf(i18n.G("wrong number of subcommand arguments")) var errUsage = fmt.Errorf("show usage") func expandAlias(config *config.Config, origArgs []string) ([]string, bool) { foundAlias := false aliasKey := []string{} aliasValue := []string{} for k, v := range config.Aliases { foundAlias = true for i, key := range strings.Split(k, " ") { if len(origArgs) <= i+1 || origArgs[i+1] != key { foundAlias = false break } } if foundAlias { aliasKey = strings.Split(k, " ") aliasValue = strings.Split(v, " ") break } } if !foundAlias { return []string{}, false } newArgs := []string{origArgs[0]} hasReplacedArgsVar := false for i, aliasArg := range aliasValue { if aliasArg == "@ARGS@" && len(origArgs) > i { newArgs = append(newArgs, origArgs[i+1:]...) hasReplacedArgsVar = true } else { newArgs = append(newArgs, aliasArg) } } if !hasReplacedArgsVar { /* add the rest of the arguments */ newArgs = append(newArgs, origArgs[len(aliasKey)+1:]...) } /* don't re-do aliases the next time; this allows us to have recursive * aliases, e.g. `lxc list` to `lxc list -c n` */ newArgs = append(newArgs[:2], append([]string{"--no-alias"}, newArgs[2:]...)...) return newArgs, true } func execIfAliases(config *config.Config, origArgs []string) { newArgs, expanded := expandAlias(config, origArgs) if !expanded { return } path, err := exec.LookPath(origArgs[0]) if err != nil { fmt.Fprintf(os.Stderr, i18n.G("processing aliases failed %s\n"), err) os.Exit(5) } ret := syscall.Exec(path, newArgs, syscall.Environ()) fmt.Fprintf(os.Stderr, i18n.G("processing aliases failed %s\n"), ret) os.Exit(5) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/list_test.go�������������������������������������������������������������������������0000644�0610621�0607500�00000001661�13172163242�016624� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "testing" "github.com/lxc/lxd/shared/api" ) func TestDotPrefixMatch(t *testing.T) { list := listCmd{} pass := true pass = pass && list.dotPrefixMatch("s.privileged", "security.privileged") pass = pass && list.dotPrefixMatch("u.blah", "user.blah") if !pass { t.Error("failed prefix matching") } } func TestShouldShow(t *testing.T) { list := listCmd{} state := &api.Container{ Name: "foo", ExpandedConfig: map[string]string{ "security.privileged": "1", "user.blah": "abc", }, } if !list.shouldShow([]string{"u.blah=abc"}, state) { t.Error("u.blah=abc didn't match") } if !list.shouldShow([]string{"user.blah=abc"}, state) { t.Error("user.blah=abc didn't match") } if list.shouldShow([]string{"bar", "u.blah=abc"}, state) { t.Errorf("name filter didn't work") } if list.shouldShow([]string{"bar", "u.blah=other"}, state) { t.Errorf("value filter didn't work") } } �������������������������������������������������������������������������������lxd-2.0.11/lxc/list.go������������������������������������������������������������������������������0000644�0610621�0607500�00000031127�13172163242�015565� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "os" "regexp" "sort" "strings" "sync" "github.com/olekukonko/tablewriter" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type column struct { Name string Data columnData NeedsState bool NeedsSnapshots bool } type columnData func(api.Container, *api.ContainerState, []api.ContainerSnapshot) string const ( listFormatTable = "table" listFormatJSON = "json" ) type listCmd struct { chosenColumnRunes string fast bool format string } func (c *listCmd) showByDefault() bool { return true } func (c *listCmd) usage() string { return i18n.G( `Usage: lxc list [<remote>:] [filters] [--format table|json] [-c <columns>] [--fast] List the existing containers. Default column layout: ns46tS Fast column layout: nsacPt *Filters* A single keyword like "web" which will list any container with a name starting by "web". A regular expression on the container name. (e.g. .*web.*01$). A key/value pair referring to a configuration item. For those, the namespace can be abbreviated to the smallest unambiguous identifier. - "user.blah=abc" will list all containers with the "blah" user property set to "abc". - "u.blah=abc" will do the same - "security.privileged=true" will list all privileged containers - "s.privileged=true" will do the same A regular expression matching a configuration item or its value. (e.g. volatile.eth0.hwaddr=00:16:3e:.*). *Columns* The -c option takes a comma separated list of arguments that control which container attributes to output when displaying in table format. Column arguments are either pre-defined shorthand chars (see below), or (extended) config keys. Commas between consecutive shorthand chars are optional. Pre-defined column shorthand chars: 4 - IPv4 address 6 - IPv6 address a - Architecture c - Creation date l - Last used date n - Name p - PID of the container's init process P - Profiles s - State S - Number of snapshots t - Type (persistent or ephemeral) *Examples* lxc list -c ns46 Shows a list of containers using the "NAME", "STATE", "IPV4", "IPV6" columns.`) } func (c *listCmd) flags() { gnuflag.StringVar(&c.chosenColumnRunes, "c", "ns46tS", i18n.G("Columns")) gnuflag.StringVar(&c.chosenColumnRunes, "columns", "ns46tS", i18n.G("Columns")) gnuflag.StringVar(&c.format, "format", "table", i18n.G("Format (table|json)")) gnuflag.BoolVar(&c.fast, "fast", false, i18n.G("Fast mode (same as --columns=nsacPt)")) } // This seems a little excessive. func (c *listCmd) dotPrefixMatch(short string, full string) bool { fullMembs := strings.Split(full, ".") shortMembs := strings.Split(short, ".") if len(fullMembs) != len(shortMembs) { return false } for i := range fullMembs { if !strings.HasPrefix(fullMembs[i], shortMembs[i]) { return false } } return true } func (c *listCmd) shouldShow(filters []string, state *api.Container) bool { for _, filter := range filters { if strings.Contains(filter, "=") { membs := strings.SplitN(filter, "=", 2) key := membs[0] var value string if len(membs) < 2 { value = "" } else { value = membs[1] } found := false for configKey, configValue := range state.ExpandedConfig { if c.dotPrefixMatch(key, configKey) { //try to test filter value as a regexp regexpValue := value if !(strings.Contains(value, "^") || strings.Contains(value, "$")) { regexpValue = "^" + regexpValue + "$" } r, err := regexp.Compile(regexpValue) //if not regexp compatible use original value if err != nil { if value == configValue { found = true break } else { // the property was found but didn't match return false } } else if r.MatchString(configValue) == true { found = true break } } } if state.ExpandedConfig[key] == value { return true } if !found { return false } } else { regexpValue := filter if !(strings.Contains(filter, "^") || strings.Contains(filter, "$")) { regexpValue = "^" + regexpValue + "$" } r, err := regexp.Compile(regexpValue) if err == nil && r.MatchString(state.Name) == true { return true } if !strings.HasPrefix(state.Name, filter) { return false } } } return true } func (c *listCmd) listContainers(conf *config.Config, remote string, cinfos []api.Container, filters []string, columns []column) error { headers := []string{} for _, column := range columns { headers = append(headers, column.Name) } threads := 10 if len(cinfos) < threads { threads = len(cinfos) } cStates := map[string]*api.ContainerState{} cStatesLock := sync.Mutex{} cStatesQueue := make(chan string, threads) cStatesWg := sync.WaitGroup{} cSnapshots := map[string][]api.ContainerSnapshot{} cSnapshotsLock := sync.Mutex{} cSnapshotsQueue := make(chan string, threads) cSnapshotsWg := sync.WaitGroup{} for i := 0; i < threads; i++ { cStatesWg.Add(1) go func() { d, err := conf.GetContainerServer(remote) if err != nil { cStatesWg.Done() return } for { cName, more := <-cStatesQueue if !more { break } state, _, err := d.GetContainerState(cName) if err != nil { continue } cStatesLock.Lock() cStates[cName] = state cStatesLock.Unlock() } cStatesWg.Done() }() cSnapshotsWg.Add(1) go func() { d, err := conf.GetContainerServer(remote) if err != nil { cSnapshotsWg.Done() return } for { cName, more := <-cSnapshotsQueue if !more { break } snaps, err := d.GetContainerSnapshots(cName) if err != nil { continue } cSnapshotsLock.Lock() cSnapshots[cName] = snaps cSnapshotsLock.Unlock() } cSnapshotsWg.Done() }() } for _, cInfo := range cinfos { for _, column := range columns { if column.NeedsState && cInfo.IsActive() { cStatesLock.Lock() _, ok := cStates[cInfo.Name] cStatesLock.Unlock() if ok { continue } cStatesLock.Lock() cStates[cInfo.Name] = nil cStatesLock.Unlock() cStatesQueue <- cInfo.Name } if column.NeedsSnapshots { cSnapshotsLock.Lock() _, ok := cSnapshots[cInfo.Name] cSnapshotsLock.Unlock() if ok { continue } cSnapshotsLock.Lock() cSnapshots[cInfo.Name] = nil cSnapshotsLock.Unlock() cSnapshotsQueue <- cInfo.Name } } } close(cStatesQueue) close(cSnapshotsQueue) cStatesWg.Wait() cSnapshotsWg.Wait() tableData := func() [][]string { data := [][]string{} for _, cInfo := range cinfos { if !c.shouldShow(filters, &cInfo) { continue } col := []string{} for _, column := range columns { col = append(col, column.Data(cInfo, cStates[cInfo.Name], cSnapshots[cInfo.Name])) } data = append(data, col) } sort.Sort(byName(data)) return data } switch c.format { case listFormatTable: table := tablewriter.NewWriter(os.Stdout) table.SetAutoWrapText(false) table.SetAlignment(tablewriter.ALIGN_LEFT) table.SetRowLine(true) table.SetHeader(headers) table.AppendBulk(tableData()) table.Render() case listFormatJSON: data := make([]listContainerItem, len(cinfos)) for i := range cinfos { data[i].Container = &cinfos[i] data[i].State = cStates[cinfos[i].Name] data[i].Snapshots = cSnapshots[cinfos[i].Name] } enc := json.NewEncoder(os.Stdout) err := enc.Encode(data) if err != nil { return err } default: return fmt.Errorf("invalid format %q", c.format) } return nil } type listContainerItem struct { *api.Container State *api.ContainerState `json:"state" yaml:"state"` Snapshots []api.ContainerSnapshot `json:"snapshots" yaml:"snapshots"` } func (c *listCmd) run(conf *config.Config, args []string) error { var remote string name := "" filters := []string{} if len(args) != 0 { filters = args if strings.Contains(args[0], ":") && !strings.Contains(args[0], "=") { var err error remote, name, err = conf.ParseRemote(args[0]) if err != nil { return err } filters = args[1:] } else if !strings.Contains(args[0], "=") { remote = conf.DefaultRemote name = args[0] } } filters = append(filters, name) if remote == "" { remote = conf.DefaultRemote } d, err := conf.GetContainerServer(remote) if err != nil { return err } var cts []api.Container ctslist, err := d.GetContainers() if err != nil { return err } for _, cinfo := range ctslist { if !c.shouldShow(filters, &cinfo) { continue } cts = append(cts, cinfo) } columns_map := map[rune]column{ '4': {i18n.G("IPV4"), c.IP4ColumnData, true, false}, '6': {i18n.G("IPV6"), c.IP6ColumnData, true, false}, 'a': {i18n.G("ARCHITECTURE"), c.ArchitectureColumnData, false, false}, 'c': {i18n.G("CREATED AT"), c.CreatedColumnData, false, false}, 'n': {i18n.G("NAME"), c.nameColumnData, false, false}, 'p': {i18n.G("PID"), c.PIDColumnData, true, false}, 'P': {i18n.G("PROFILES"), c.ProfilesColumnData, false, false}, 'S': {i18n.G("SNAPSHOTS"), c.numberSnapshotsColumnData, false, true}, 's': {i18n.G("STATE"), c.statusColumnData, false, false}, 't': {i18n.G("TYPE"), c.typeColumnData, false, false}, } if c.fast { if c.chosenColumnRunes != "ns46tS" { // --columns was specified too return fmt.Errorf("Can't specify --fast with --columns") } else { c.chosenColumnRunes = "nsacPt" } } columns := []column{} for _, columnRune := range c.chosenColumnRunes { if column, ok := columns_map[columnRune]; ok { columns = append(columns, column) } else { return fmt.Errorf("%s does contain invalid column characters\n", c.chosenColumnRunes) } } return c.listContainers(conf, remote, cts, filters, columns) } func (c *listCmd) nameColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { return cInfo.Name } func (c *listCmd) statusColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { return strings.ToUpper(cInfo.Status) } func (c *listCmd) IP4ColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { if cInfo.IsActive() && cState != nil && cState.Network != nil { ipv4s := []string{} for netName, net := range cState.Network { if net.Type == "loopback" { continue } for _, addr := range net.Addresses { if shared.StringInSlice(addr.Scope, []string{"link", "local"}) { continue } if addr.Family == "inet" { ipv4s = append(ipv4s, fmt.Sprintf("%s (%s)", addr.Address, netName)) } } } sort.Sort(sort.Reverse(sort.StringSlice(ipv4s))) return strings.Join(ipv4s, "\n") } else { return "" } } func (c *listCmd) IP6ColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { if cInfo.IsActive() && cState != nil && cState.Network != nil { ipv6s := []string{} for netName, net := range cState.Network { if net.Type == "loopback" { continue } for _, addr := range net.Addresses { if shared.StringInSlice(addr.Scope, []string{"link", "local"}) { continue } if addr.Family == "inet6" { ipv6s = append(ipv6s, fmt.Sprintf("%s (%s)", addr.Address, netName)) } } } sort.Sort(sort.Reverse(sort.StringSlice(ipv6s))) return strings.Join(ipv6s, "\n") } else { return "" } } func (c *listCmd) typeColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { if cInfo.Ephemeral { return i18n.G("EPHEMERAL") } else { return i18n.G("PERSISTENT") } } func (c *listCmd) numberSnapshotsColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { if cSnaps != nil { return fmt.Sprintf("%d", len(cSnaps)) } return "" } func (c *listCmd) PIDColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { if cInfo.IsActive() && cState != nil { return fmt.Sprintf("%d", cState.Pid) } return "" } func (c *listCmd) ArchitectureColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { return cInfo.Architecture } func (c *listCmd) ProfilesColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { return strings.Join(cInfo.Profiles, "\n") } func (c *listCmd) CreatedColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string { layout := "2006/01/02 15:04 UTC" if shared.TimeIsSet(cInfo.CreatedAt) { return cInfo.CreatedAt.UTC().Format(layout) } return "" } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/launch.go����������������������������������������������������������������������������0000644�0610621�0607500�00000003105�13172163242�016057� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/i18n" ) type launchCmd struct { init initCmd } func (c *launchCmd) showByDefault() bool { return true } func (c *launchCmd) usage() string { return i18n.G( `Usage: lxc launch [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance type>] Create and start containers from images. Not specifying -p will result in the default profile. Specifying "-p" with no argument will result in no profile. Examples: lxc launch ubuntu:16.04 u1`) } func (c *launchCmd) flags() { c.init = initCmd{} c.init.flags() } func (c *launchCmd) run(conf *config.Config, args []string) error { // Call the matching code from init d, name, err := c.init.create(conf, args) if err != nil { return err } // Get the remote var remote string if len(args) == 2 { remote, _, err = conf.ParseRemote(args[1]) if err != nil { return err } } else { remote, _, err = conf.ParseRemote("") if err != nil { return err } } // Start the container fmt.Printf(i18n.G("Starting %s")+"\n", name) req := api.ContainerStatePut{ Action: "start", Timeout: -1, } op, err := d.UpdateContainerState(name, req, "") if err != nil { return err } err = op.Wait() if err != nil { prettyName := name if remote != "" { prettyName = fmt.Sprintf("%s:%s", remote, name) } return fmt.Errorf("%s\n"+i18n.G("Try `lxc info --show-log %s` for more info"), err, prettyName) } return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/init.go������������������������������������������������������������������������������0000644�0610621�0607500�00000015163�13172163242�015557� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "strings" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type profileList []string var configMap map[string]string func (f *profileList) String() string { return fmt.Sprint(*f) } type configList []string func (f *configList) String() string { return fmt.Sprint(configMap) } func (f *configList) Set(value string) error { if value == "" { return fmt.Errorf(i18n.G("Invalid configuration key")) } items := strings.SplitN(value, "=", 2) if len(items) < 2 { return fmt.Errorf(i18n.G("Invalid configuration key")) } if configMap == nil { configMap = map[string]string{} } configMap[items[0]] = items[1] return nil } func (f *profileList) Set(value string) error { if value == "" { initRequestedEmptyProfiles = true return nil } if f == nil { *f = make(profileList, 1) } else { *f = append(*f, value) } return nil } var initRequestedEmptyProfiles bool type initCmd struct { profArgs profileList confArgs configList ephem bool instanceType string } func (c *initCmd) showByDefault() bool { return false } func (c *initCmd) usage() string { return i18n.G( `Usage: lxc init [<remote>:]<image> [<remote>:][<name>] [--ephemeral|-e] [--profile|-p <profile>...] [--config|-c <key=value>...] [--type|-t <instance type>] Create containers from images. Not specifying -p will result in the default profile. Specifying "-p" with no argument will result in no profile. Examples: lxc init ubuntu:16.04 u1`) } func (c *initCmd) is_ephem(s string) bool { switch s { case "-e": return true case "--ephemeral": return true } return false } func (c *initCmd) is_profile(s string) bool { switch s { case "-p": return true case "--profile": return true } return false } func (c *initCmd) massage_args() { l := len(os.Args) if l < 2 { return } if c.is_profile(os.Args[l-1]) { initRequestedEmptyProfiles = true os.Args = os.Args[0 : l-1] return } if l < 3 { return } /* catch "lxc init ubuntu -p -e */ if c.is_ephem(os.Args[l-1]) && c.is_profile(os.Args[l-2]) { initRequestedEmptyProfiles = true newargs := os.Args[0 : l-2] newargs = append(newargs, os.Args[l-1]) os.Args = newargs return } } func (c *initCmd) flags() { c.massage_args() gnuflag.Var(&c.confArgs, "config", i18n.G("Config key/value to apply to the new container")) gnuflag.Var(&c.confArgs, "c", i18n.G("Config key/value to apply to the new container")) gnuflag.Var(&c.profArgs, "profile", i18n.G("Profile to apply to the new container")) gnuflag.Var(&c.profArgs, "p", i18n.G("Profile to apply to the new container")) gnuflag.BoolVar(&c.ephem, "ephemeral", false, i18n.G("Ephemeral container")) gnuflag.BoolVar(&c.ephem, "e", false, i18n.G("Ephemeral container")) gnuflag.StringVar(&c.instanceType, "t", "", i18n.G("Instance type")) } func (c *initCmd) run(conf *config.Config, args []string) error { _, _, err := c.create(conf, args) return err } func (c *initCmd) create(conf *config.Config, args []string) (lxd.ContainerServer, string, error) { if len(args) > 2 || len(args) < 1 { return nil, "", errArgs } iremote, image, err := conf.ParseRemote(args[0]) if err != nil { return nil, "", err } var name string var remote string if len(args) == 2 { remote, name, err = conf.ParseRemote(args[1]) if err != nil { return nil, "", err } } else { remote, name, err = conf.ParseRemote("") if err != nil { return nil, "", err } } d, err := conf.GetContainerServer(remote) if err != nil { return nil, "", err } /* * initRequestedEmptyProfiles means user requested empty * !initRequestedEmptyProfiles but len(profArgs) == 0 means use profile default */ profiles := []string{} for _, p := range c.profArgs { profiles = append(profiles, p) } if name == "" { fmt.Printf(i18n.G("Creating the container") + "\n") } else { fmt.Printf(i18n.G("Creating %s")+"\n", name) } // Get the image server and image info iremote, image = c.guessImage(conf, d, remote, iremote, image) var imgRemote lxd.ImageServer var imgInfo *api.Image // Connect to the image server if iremote == remote { imgRemote = d } else { imgRemote, err = conf.GetImageServer(iremote) if err != nil { return nil, "", err } } // Deal with the default image if image == "" { image = "default" } // Setup container creation request req := api.ContainersPost{ Name: name, InstanceType: c.instanceType, } req.Config = configMap if !initRequestedEmptyProfiles && len(profiles) == 0 { req.Profiles = nil } else { req.Profiles = profiles } req.Ephemeral = c.ephem // Optimisation for simplestreams if conf.Remotes[iremote].Protocol == "simplestreams" { imgInfo = &api.Image{} imgInfo.Fingerprint = image imgInfo.Public = true req.Source.Alias = image } else { // Attempt to resolve an image alias alias, _, err := imgRemote.GetImageAlias(image) if err == nil { req.Source.Alias = image image = alias.Target } // Get the image info imgInfo, _, err = imgRemote.GetImage(image) if err != nil { return nil, "", err } } // Create the container op, err := d.CreateContainerFromImage(imgRemote, *imgInfo, req) if err != nil { return nil, "", err } // Watch the background operation progress := ProgressRenderer{Format: i18n.G("Retrieving image: %s")} _, err = op.AddHandler(progress.UpdateOp) if err != nil { progress.Done("") return nil, "", err } err = cancelableWait(op, &progress) if err != nil { progress.Done("") return nil, "", err } progress.Done("") // Extract the container name opInfo, err := op.GetTarget() if err != nil { return nil, "", err } containers, ok := opInfo.Resources["containers"] if !ok || len(containers) == 0 { return nil, "", fmt.Errorf(i18n.G("didn't get any affected image, container or snapshot from server")) } if len(containers) == 1 && name == "" { fields := strings.Split(containers[0], "/") name = fields[len(fields)-1] fmt.Printf(i18n.G("Container name is: %s")+"\n", name) } return d, name, nil } func (c *initCmd) guessImage(conf *config.Config, d lxd.ContainerServer, remote string, iremote string, image string) (string, string) { if remote != iremote { return iremote, image } _, ok := conf.Remotes[image] if !ok { return iremote, image } _, _, err := d.GetImageAlias(image) if err == nil { return iremote, image } _, _, err = d.GetImage(image) if err == nil { return iremote, image } fmt.Fprintf(os.Stderr, i18n.G("The local image '%s' couldn't be found, trying '%s:' instead.")+"\n", image, image) return image, "default" } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/info.go������������������������������������������������������������������������������0000644�0610621�0607500�00000013166�13172163242�015550� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io/ioutil" "strings" "gopkg.in/yaml.v2" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type infoCmd struct { showLog bool } func (c *infoCmd) showByDefault() bool { return true } func (c *infoCmd) usage() string { return i18n.G( `Usage: lxc info [<remote>:][<container>] [--show-log] Show container or server information. lxc info [<remote>:]<container> [--show-log] For container information. lxc info [<remote>:] For LXD server information.`) } func (c *infoCmd) flags() { gnuflag.BoolVar(&c.showLog, "show-log", false, i18n.G("Show the container's last 100 log lines?")) } func (c *infoCmd) run(conf *config.Config, args []string) error { var remote string var cName string var err error if len(args) == 1 { remote, cName, err = conf.ParseRemote(args[0]) if err != nil { return err } } else { remote, cName, err = conf.ParseRemote("") if err != nil { return err } } d, err := conf.GetContainerServer(remote) if err != nil { return err } if cName == "" { return c.remoteInfo(d) } else { return c.containerInfo(d, conf.Remotes[remote], cName, c.showLog) } } func (c *infoCmd) remoteInfo(d lxd.ContainerServer) error { serverStatus, _, err := d.GetServer() if err != nil { return err } data, err := yaml.Marshal(&serverStatus) if err != nil { return err } fmt.Printf("%s", data) return nil } func (c *infoCmd) containerInfo(d lxd.ContainerServer, remote config.Remote, name string, showLog bool) error { ct, _, err := d.GetContainer(name) if err != nil { return err } cs, _, err := d.GetContainerState(name) if err != nil { return err } const layout = "2006/01/02 15:04 UTC" fmt.Printf(i18n.G("Name: %s")+"\n", ct.Name) if remote.Addr != "" { fmt.Printf(i18n.G("Remote: %s")+"\n", remote.Addr) } fmt.Printf(i18n.G("Architecture: %s")+"\n", ct.Architecture) if shared.TimeIsSet(ct.CreatedAt) { fmt.Printf(i18n.G("Created: %s")+"\n", ct.CreatedAt.UTC().Format(layout)) } fmt.Printf(i18n.G("Status: %s")+"\n", ct.Status) if ct.Ephemeral { fmt.Printf(i18n.G("Type: ephemeral") + "\n") } else { fmt.Printf(i18n.G("Type: persistent") + "\n") } fmt.Printf(i18n.G("Profiles: %s")+"\n", strings.Join(ct.Profiles, ", ")) if cs.Pid != 0 { fmt.Printf(i18n.G("Pid: %d")+"\n", cs.Pid) // IP addresses ipInfo := "" if cs.Network != nil { for netName, net := range cs.Network { vethStr := "" if net.HostName != "" { vethStr = fmt.Sprintf("\t%s", net.HostName) } for _, addr := range net.Addresses { ipInfo += fmt.Sprintf(" %s:\t%s\t%s%s\n", netName, addr.Family, addr.Address, vethStr) } } } if ipInfo != "" { fmt.Println(i18n.G("Ips:")) fmt.Printf(ipInfo) } fmt.Println(i18n.G("Resources:")) // Processes fmt.Printf(" "+i18n.G("Processes: %d")+"\n", cs.Processes) // Disk usage diskInfo := "" if cs.Disk != nil { for entry, disk := range cs.Disk { if disk.Usage != 0 { diskInfo += fmt.Sprintf(" %s: %s\n", entry, shared.GetByteSizeString(disk.Usage, 2)) } } } if diskInfo != "" { fmt.Println(fmt.Sprintf(" %s", i18n.G("Disk usage:"))) fmt.Printf(diskInfo) } // Memory usage memoryInfo := "" if cs.Memory.Usage != 0 { memoryInfo += fmt.Sprintf(" %s: %s\n", i18n.G("Memory (current)"), shared.GetByteSizeString(cs.Memory.Usage, 2)) } if cs.Memory.UsagePeak != 0 { memoryInfo += fmt.Sprintf(" %s: %s\n", i18n.G("Memory (peak)"), shared.GetByteSizeString(cs.Memory.UsagePeak, 2)) } if cs.Memory.SwapUsage != 0 { memoryInfo += fmt.Sprintf(" %s: %s\n", i18n.G("Swap (current)"), shared.GetByteSizeString(cs.Memory.SwapUsage, 2)) } if cs.Memory.SwapUsagePeak != 0 { memoryInfo += fmt.Sprintf(" %s: %s\n", i18n.G("Swap (peak)"), shared.GetByteSizeString(cs.Memory.SwapUsagePeak, 2)) } if memoryInfo != "" { fmt.Println(fmt.Sprintf(" %s", i18n.G("Memory usage:"))) fmt.Printf(memoryInfo) } // Network usage networkInfo := "" if cs.Network != nil { for netName, net := range cs.Network { networkInfo += fmt.Sprintf(" %s:\n", netName) networkInfo += fmt.Sprintf(" %s: %s\n", i18n.G("Bytes received"), shared.GetByteSizeString(net.Counters.BytesReceived, 2)) networkInfo += fmt.Sprintf(" %s: %s\n", i18n.G("Bytes sent"), shared.GetByteSizeString(net.Counters.BytesSent, 2)) networkInfo += fmt.Sprintf(" %s: %d\n", i18n.G("Packets received"), net.Counters.PacketsReceived) networkInfo += fmt.Sprintf(" %s: %d\n", i18n.G("Packets sent"), net.Counters.PacketsSent) } } if networkInfo != "" { fmt.Println(fmt.Sprintf(" %s", i18n.G("Network usage:"))) fmt.Printf(networkInfo) } } // List snapshots first_snapshot := true snaps, err := d.GetContainerSnapshots(name) if err != nil { return nil } for _, snap := range snaps { if first_snapshot { fmt.Println(i18n.G("Snapshots:")) } fields := strings.Split(snap.Name, shared.SnapshotDelimiter) fmt.Printf(" %s", fields[len(fields)-1]) if shared.TimeIsSet(snap.CreationDate) { fmt.Printf(" ("+i18n.G("taken at %s")+")", snap.CreationDate.UTC().Format(layout)) } if snap.Stateful { fmt.Printf(" (" + i18n.G("stateful") + ")") } else { fmt.Printf(" (" + i18n.G("stateless") + ")") } fmt.Printf("\n") first_snapshot = false } if showLog { log, err := d.GetContainerLogfile(name, "lxc.log") if err != nil { return err } stuff, err := ioutil.ReadAll(log) if err != nil { return err } fmt.Printf("\n"+i18n.G("Log:")+"\n\n%s\n", string(stuff)) } return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/image.go�����������������������������������������������������������������������������0000644�0610621�0607500�00000057324�13172163242�015703� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io" "io/ioutil" "os" "path/filepath" "regexp" "sort" "strings" "syscall" "github.com/olekukonko/tablewriter" "gopkg.in/yaml.v2" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared/termios" ) type aliasList []string func (f *aliasList) String() string { return fmt.Sprint(*f) } func (f *aliasList) Set(value string) error { if f == nil { *f = make(aliasList, 1) } else { *f = append(*f, value) } return nil } type imageCmd struct { addAliases aliasList publicImage bool copyAliases bool autoUpdate bool } func (c *imageCmd) showByDefault() bool { return true } func (c *imageCmd) imageEditHelp() string { return i18n.G( `### This is a yaml representation of the image properties. ### Any line starting with a '# will be ignored. ### ### Each property is represented by a single line: ### An example would be: ### description: My custom image`) } func (c *imageCmd) usage() string { return i18n.G( `Usage: lxc image <subcommand> [options] Manipulate container images. In LXD containers are created from images. Those images were themselves either generated from an existing container or downloaded from an image server. When using remote images, LXD will automatically cache images for you and remove them upon expiration. The image unique identifier is the hash (sha-256) of its representation as a compressed tarball (or for split images, the concatenation of the metadata and rootfs tarballs). Images can be referenced by their full hash, shortest unique partial hash or alias name (if one is set). lxc image import <tarball> [<rootfs tarball>|<URL>] [<remote>:] [--public] [--created-at=ISO-8601] [--expires-at=ISO-8601] [--fingerprint=FINGERPRINT] [--alias=ALIAS...] [prop=value] Import an image tarball (or tarballs) into the LXD image store. lxc image copy [<remote>:]<image> <remote>: [--alias=ALIAS...] [--copy-aliases] [--public] [--auto-update] Copy an image from one LXD daemon to another over the network. The auto-update flag instructs the server to keep this image up to date. It requires the source to be an alias and for it to be public. lxc image delete [<remote>:]<image> [[<remote>:]<image>...] Delete one or more images from the LXD image store. lxc image export [<remote>:]<image> [target] Export an image from the LXD image store into a distributable tarball. The output target is optional and defaults to the working directory. The target may be an existing directory, file name, or "-" to specify stdout. The target MUST be a directory when exporting a split image. If the target is a directory, the image's name (each part's name for split images) as found in the database will be used for the exported image. If the target is a file (not a directory and not stdout), then the appropriate extension will be appended to the provided file name based on the algorithm used to compress the image. lxc image info [<remote>:]<image> Print everything LXD knows about a given image. lxc image list [<remote>:] [filter] List images in the LXD image store. Filters may be of the <key>=<value> form for property based filtering, or part of the image hash or part of the image alias name. lxc image show [<remote>:]<image> Yaml output of the user modifiable properties of an image. lxc image edit [<remote>:]<image> Edit image, either by launching external editor or reading STDIN. Example: lxc image edit <image> # launch editor cat image.yaml | lxc image edit <image> # read from image.yaml lxc image alias create [<remote>:]<alias> <fingerprint> Create a new alias for an existing image. lxc image alias delete [<remote>:]<alias> Delete an alias. lxc image alias list [<remote>:] [filter] List the aliases. Filters may be part of the image hash or part of the image alias name.`) } func (c *imageCmd) flags() { gnuflag.BoolVar(&c.publicImage, "public", false, i18n.G("Make image public")) gnuflag.BoolVar(&c.copyAliases, "copy-aliases", false, i18n.G("Copy aliases from source")) gnuflag.BoolVar(&c.autoUpdate, "auto-update", false, i18n.G("Keep the image up to date after initial copy")) gnuflag.Var(&c.addAliases, "alias", i18n.G("New alias to define at target")) } func (c *imageCmd) doImageAlias(conf *config.Config, args []string) error { var remote string var err error switch args[1] { case "list": filters := []string{} if len(args) > 2 { result := strings.SplitN(args[2], ":", 2) if len(result) == 1 { filters = append(filters, args[2]) remote, _, err = conf.ParseRemote("") if err != nil { return err } } else { remote, _, err = conf.ParseRemote(args[2]) if err != nil { return err } } } else { remote, _, err = conf.ParseRemote("") if err != nil { return err } } if len(args) > 3 { for _, filter := range args[3:] { filters = append(filters, filter) } } d, err := conf.GetImageServer(remote) if err != nil { return err } resp, err := d.GetImageAliases() if err != nil { return err } c.showAliases(resp, filters) return nil case "create": /* alias create [<remote>:]<alias> <target> */ if len(args) < 4 { return errArgs } remote, name, err := conf.ParseRemote(args[2]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } alias := api.ImageAliasesPost{} alias.Name = name alias.Target = args[3] return d.CreateImageAlias(alias) case "delete": /* alias delete [<remote>:]<alias> */ if len(args) < 3 { return errArgs } remote, alias, err := conf.ParseRemote(args[2]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } return d.DeleteImageAlias(alias) } return errArgs } func (c *imageCmd) run(conf *config.Config, args []string) error { var remote string if len(args) < 1 { return errUsage } switch args[0] { case "alias": if len(args) < 2 { return errArgs } return c.doImageAlias(conf, args) case "copy": /* copy [<remote>:]<image> [<remote>:]<image> */ if len(args) != 3 { return errArgs } remote, inName, err := conf.ParseRemote(args[1]) if err != nil { return err } destRemote, outName, err := conf.ParseRemote(args[2]) if err != nil { return err } if outName != "" { return errArgs } d, err := conf.GetImageServer(remote) if err != nil { return err } dest, err := conf.GetContainerServer(destRemote) if err != nil { return err } var imgInfo *api.Image var fp string if conf.Remotes[remote].Protocol == "simplestreams" && !c.copyAliases && len(c.addAliases) == 0 { // All simplestreams images are always public, so unless we // need the aliases list too or the real fingerprint, we can skip the otherwise very expensive // alias resolution and image info retrieval step. imgInfo = &api.Image{} imgInfo.Fingerprint = inName imgInfo.Public = true } else { // Resolve any alias and then grab the image information from the source image := c.dereferenceAlias(d, inName) imgInfo, _, err = d.GetImage(image) if err != nil { return err } // Store the fingerprint for use when creating aliases later (as imgInfo.Fingerprint may be overridden) fp = imgInfo.Fingerprint } if imgInfo.Public && imgInfo.Fingerprint != inName && !strings.HasPrefix(imgInfo.Fingerprint, inName) { // If dealing with an alias, set the imgInfo fingerprint to match the provided alias (needed for auto-update) imgInfo.Fingerprint = inName } args := lxd.ImageCopyArgs{ AutoUpdate: c.autoUpdate, Public: c.publicImage, } // Do the copy op, err := dest.CopyImage(d, *imgInfo, &args) if err != nil { return err } // Register progress handler progress := ProgressRenderer{Format: i18n.G("Copying the image: %s")} _, err = op.AddHandler(progress.UpdateOp) if err != nil { progress.Done("") return err } // Wait for operation to finish err = cancelableWait(op, &progress) if err != nil { progress.Done("") return err } progress.Done(i18n.G("Image copied successfully!")) // Ensure aliases aliases := make([]api.ImageAlias, len(c.addAliases)) for i, entry := range c.addAliases { aliases[i].Name = entry } if c.copyAliases { // Also add the original aliases for _, alias := range imgInfo.Aliases { aliases = append(aliases, alias) } } err = ensureImageAliases(dest, aliases, fp) return err case "delete": /* delete [<remote>:]<image> [<image>...] */ if len(args) < 2 { return errArgs } for _, arg := range args[1:] { var err error remote, inName, err := conf.ParseRemote(arg) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } image := c.dereferenceAlias(d, inName) op, err := d.DeleteImage(image) if err != nil { return err } err = op.Wait() if err != nil { return err } } return nil case "info": if len(args) < 2 { return errArgs } remote, inName, err := conf.ParseRemote(args[1]) if err != nil { return err } d, err := conf.GetImageServer(remote) if err != nil { return err } image := c.dereferenceAlias(d, inName) info, _, err := d.GetImage(image) if err != nil { return err } public := i18n.G("no") if info.Public { public = i18n.G("yes") } cached := i18n.G("no") if info.Cached { cached = i18n.G("yes") } autoUpdate := i18n.G("disabled") if info.AutoUpdate { autoUpdate = i18n.G("enabled") } fmt.Printf(i18n.G("Fingerprint: %s")+"\n", info.Fingerprint) fmt.Printf(i18n.G("Size: %.2fMB")+"\n", float64(info.Size)/1024.0/1024.0) fmt.Printf(i18n.G("Architecture: %s")+"\n", info.Architecture) fmt.Printf(i18n.G("Public: %s")+"\n", public) fmt.Printf(i18n.G("Timestamps:") + "\n") const layout = "2006/01/02 15:04 UTC" if shared.TimeIsSet(info.CreatedAt) { fmt.Printf(" "+i18n.G("Created: %s")+"\n", info.CreatedAt.UTC().Format(layout)) } fmt.Printf(" "+i18n.G("Uploaded: %s")+"\n", info.UploadedAt.UTC().Format(layout)) if shared.TimeIsSet(info.ExpiresAt) { fmt.Printf(" "+i18n.G("Expires: %s")+"\n", info.ExpiresAt.UTC().Format(layout)) } else { fmt.Printf(" " + i18n.G("Expires: never") + "\n") } if shared.TimeIsSet(info.LastUsedAt) { fmt.Printf(" "+i18n.G("Last used: %s")+"\n", info.LastUsedAt.UTC().Format(layout)) } else { fmt.Printf(" " + i18n.G("Last used: never") + "\n") } fmt.Println(i18n.G("Properties:")) for key, value := range info.Properties { fmt.Printf(" %s: %s\n", key, value) } fmt.Println(i18n.G("Aliases:")) for _, alias := range info.Aliases { if alias.Description != "" { fmt.Printf(" - %s (%s)\n", alias.Name, alias.Description) } else { fmt.Printf(" - %s\n", alias.Name) } } fmt.Printf(i18n.G("Cached: %s")+"\n", cached) fmt.Printf(i18n.G("Auto update: %s")+"\n", autoUpdate) if info.UpdateSource != nil { fmt.Println(i18n.G("Source:")) fmt.Printf(" Server: %s\n", info.UpdateSource.Server) fmt.Printf(" Protocol: %s\n", info.UpdateSource.Protocol) fmt.Printf(" Alias: %s\n", info.UpdateSource.Alias) } return nil case "import": if len(args) < 2 { return errArgs } var imageFile string var rootfsFile string var properties []string var remote string for _, arg := range args[1:] { split := strings.Split(arg, "=") if len(split) == 1 || shared.PathExists(shared.HostPath(arg)) { if strings.HasSuffix(arg, ":") { var err error remote, _, err = conf.ParseRemote(arg) if err != nil { return err } } else { if imageFile == "" { imageFile = args[1] } else { rootfsFile = arg } } } else { properties = append(properties, arg) } } if remote == "" { remote = conf.DefaultRemote } if imageFile == "" { imageFile = args[1] properties = properties[1:] } imageFile = shared.HostPath(filepath.Clean(imageFile)) d, err := conf.GetContainerServer(remote) if err != nil { return err } if strings.HasPrefix(imageFile, "http://") { return fmt.Errorf(i18n.G("Only https:// is supported for remote image import.")) } var args *lxd.ImageCreateArgs image := api.ImagesPost{} image.Public = c.publicImage // Handle aliases aliases := []api.ImageAlias{} for _, entry := range c.addAliases { alias := api.ImageAlias{} alias.Name = entry aliases = append(aliases, alias) } // Handle properties for _, entry := range properties { fields := strings.SplitN(entry, "=", 2) if len(fields) < 2 { return fmt.Errorf(i18n.G("Bad property: %s"), entry) } if image.Properties == nil { image.Properties = map[string]string{} } image.Properties[strings.TrimSpace(fields[0])] = strings.TrimSpace(fields[1]) } progress := ProgressRenderer{Format: i18n.G("Transferring image: %s")} if strings.HasPrefix(imageFile, "https://") { image.Source = &api.ImagesPostSource{} image.Source.Type = "url" image.Source.Mode = "pull" image.Source.Protocol = "direct" image.Source.URL = imageFile } else { var meta io.ReadCloser var rootfs io.ReadCloser // Open meta meta, err = os.Open(imageFile) if err != nil { return err } defer meta.Close() // Open rootfs if rootfsFile != "" { rootfs, err = os.Open(rootfsFile) if err != nil { return err } defer rootfs.Close() } args = &lxd.ImageCreateArgs{ MetaFile: meta, MetaName: filepath.Base(imageFile), RootfsFile: rootfs, RootfsName: filepath.Base(rootfsFile), ProgressHandler: progress.UpdateProgress, } image.Filename = args.MetaName } // Start the transfer op, err := d.CreateImage(image, args) if err != nil { progress.Done("") return err } err = op.Wait() if err != nil { progress.Done("") return err } // Get the fingerprint fingerprint := op.Metadata["fingerprint"].(string) progress.Done(fmt.Sprintf(i18n.G("Image imported with fingerprint: %s"), fingerprint)) // Add the aliases if len(c.addAliases) > 0 { aliases := make([]api.ImageAlias, len(c.addAliases)) for i, entry := range c.addAliases { aliases[i].Name = entry } err = ensureImageAliases(d, aliases, fingerprint) if err != nil { return err } } return nil case "list": var err error filters := []string{} if len(args) > 1 { result := strings.SplitN(args[1], ":", 2) if len(result) == 1 { filters = append(filters, args[1]) remote, _, err = conf.ParseRemote("") if err != nil { return err } } else { var filter string remote, filter, err = conf.ParseRemote(args[1]) if err != nil { return err } if filter != "" { filters = append(filters, filter) } } } else { remote, _, err = conf.ParseRemote("") if err != nil { return err } } if len(args) > 2 { for _, filter := range args[2:] { filters = append(filters, filter) } } d, err := conf.GetImageServer(remote) if err != nil { return err } images, err := d.GetImages() if err != nil { return err } return c.showImages(images, filters) case "edit": if len(args) < 2 { return errArgs } remote, inName, err := conf.ParseRemote(args[1]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } image := c.dereferenceAlias(d, inName) if image == "" { image = inName } return c.doImageEdit(d, image) case "export": if len(args) < 2 { return errArgs } remote, inName, err := conf.ParseRemote(args[1]) if err != nil { return err } d, err := conf.GetImageServer(remote) if err != nil { return err } // Resolve aliases fingerprint := c.dereferenceAlias(d, inName) // Default target is current directory target := "." targetMeta := fingerprint if len(args) > 2 { target = args[2] if shared.IsDir(args[2]) { targetMeta = filepath.Join(args[2], targetMeta) } else { targetMeta = args[2] } } targetMeta = shared.HostPath(targetMeta) targetRootfs := targetMeta + ".root" // Prepare the files dest, err := os.Create(targetMeta) if err != nil { return err } defer dest.Close() destRootfs, err := os.Create(targetRootfs) if err != nil { return err } defer destRootfs.Close() // Prepare the download request progress := ProgressRenderer{Format: i18n.G("Exporting the image: %s")} req := lxd.ImageFileRequest{ MetaFile: io.WriteSeeker(dest), RootfsFile: io.WriteSeeker(destRootfs), ProgressHandler: progress.UpdateProgress, } // Download the image resp, err := d.GetImageFile(fingerprint, req) if err != nil { os.Remove(targetMeta) os.Remove(targetRootfs) progress.Done("") return err } // Cleanup if resp.RootfsSize == 0 { err := os.Remove(targetRootfs) if err != nil { os.Remove(targetMeta) os.Remove(targetRootfs) progress.Done("") return err } } // Rename files if shared.IsDir(target) { if resp.MetaName != "" { err := os.Rename(targetMeta, shared.HostPath(filepath.Join(target, resp.MetaName))) if err != nil { os.Remove(targetMeta) os.Remove(targetRootfs) progress.Done("") return err } } if resp.RootfsSize > 0 && resp.RootfsName != "" { err := os.Rename(targetRootfs, shared.HostPath(filepath.Join(target, resp.RootfsName))) if err != nil { os.Remove(targetMeta) os.Remove(targetRootfs) progress.Done("") return err } } } else if resp.RootfsSize == 0 && len(args) > 2 { if resp.MetaName != "" { extension := strings.SplitN(resp.MetaName, ".", 2)[1] err := os.Rename(targetMeta, fmt.Sprintf("%s.%s", targetMeta, extension)) if err != nil { os.Remove(targetMeta) progress.Done("") return err } } } progress.Done(i18n.G("Image exported successfully!")) return nil case "show": if len(args) < 2 { return errArgs } remote, inName, err := conf.ParseRemote(args[1]) if err != nil { return err } d, err := conf.GetImageServer(remote) if err != nil { return err } image := c.dereferenceAlias(d, inName) info, _, err := d.GetImage(image) if err != nil { return err } properties := info.Writable() data, err := yaml.Marshal(&properties) fmt.Printf("%s", data) return err default: return errArgs } } func (c *imageCmd) dereferenceAlias(d lxd.ImageServer, inName string) string { if inName == "" { inName = "default" } result, _, _ := d.GetImageAlias(inName) if result == nil { return inName } return result.Target } func (c *imageCmd) shortestAlias(list []api.ImageAlias) string { shortest := "" for _, l := range list { if shortest == "" { shortest = l.Name continue } if len(l.Name) != 0 && len(l.Name) < len(shortest) { shortest = l.Name } } return shortest } func (c *imageCmd) findDescription(props map[string]string) string { for k, v := range props { if k == "description" { return v } } return "" } func (c *imageCmd) showImages(images []api.Image, filters []string) error { data := [][]string{} for _, image := range images { if !c.imageShouldShow(filters, &image) { continue } shortest := c.shortestAlias(image.Aliases) if len(image.Aliases) > 1 { shortest = fmt.Sprintf(i18n.G("%s (%d more)"), shortest, len(image.Aliases)-1) } fp := image.Fingerprint[0:12] public := i18n.G("no") description := c.findDescription(image.Properties) if image.Public { public = i18n.G("yes") } const layout = "Jan 2, 2006 at 3:04pm (MST)" uploaded := image.UploadedAt.UTC().Format(layout) size := fmt.Sprintf("%.2fMB", float64(image.Size)/1024.0/1024.0) data = append(data, []string{shortest, fp, public, description, image.Architecture, size, uploaded}) } table := tablewriter.NewWriter(os.Stdout) table.SetAutoWrapText(false) table.SetAlignment(tablewriter.ALIGN_LEFT) table.SetRowLine(true) table.SetHeader([]string{ i18n.G("ALIAS"), i18n.G("FINGERPRINT"), i18n.G("PUBLIC"), i18n.G("DESCRIPTION"), i18n.G("ARCH"), i18n.G("SIZE"), i18n.G("UPLOAD DATE")}) sort.Sort(SortImage(data)) table.AppendBulk(data) table.Render() return nil } func (c *imageCmd) showAliases(aliases []api.ImageAliasesEntry, filters []string) error { data := [][]string{} for _, alias := range aliases { if !c.aliasShouldShow(filters, &alias) { continue } data = append(data, []string{alias.Name, alias.Target[0:12], alias.Description}) } table := tablewriter.NewWriter(os.Stdout) table.SetAutoWrapText(false) table.SetAlignment(tablewriter.ALIGN_LEFT) table.SetRowLine(true) table.SetHeader([]string{ i18n.G("ALIAS"), i18n.G("FINGERPRINT"), i18n.G("DESCRIPTION")}) sort.Sort(SortImage(data)) table.AppendBulk(data) table.Render() return nil } func (c *imageCmd) doImageEdit(client lxd.ContainerServer, image string) error { // If stdin isn't a terminal, read text from it if !termios.IsTerminal(int(syscall.Stdin)) { contents, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } newdata := api.ImagePut{} err = yaml.Unmarshal(contents, &newdata) if err != nil { return err } return client.UpdateImage(image, newdata, "") } // Extract the current value config, etag, err := client.GetImage(image) if err != nil { return err } brief := config.Writable() data, err := yaml.Marshal(&brief) if err != nil { return err } // Spawn the editor content, err := shared.TextEditor("", []byte(c.imageEditHelp()+"\n\n"+string(data))) if err != nil { return err } for { // Parse the text received from the editor newdata := api.ImagePut{} err = yaml.Unmarshal(content, &newdata) if err == nil { err = client.UpdateImage(image, newdata, etag) } // Respawn the editor if err != nil { fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err) fmt.Println(i18n.G("Press enter to start the editor again")) _, err := os.Stdin.Read(make([]byte, 1)) if err != nil { return err } content, err = shared.TextEditor("", content) if err != nil { return err } continue } break } return nil } func (c *imageCmd) imageShouldShow(filters []string, state *api.Image) bool { if len(filters) == 0 { return true } for _, filter := range filters { found := false if strings.Contains(filter, "=") { membs := strings.SplitN(filter, "=", 2) key := membs[0] var value string if len(membs) < 2 { value = "" } else { value = membs[1] } for configKey, configValue := range state.Properties { list := listCmd{} if list.dotPrefixMatch(key, configKey) { //try to test filter value as a regexp regexpValue := value if !(strings.Contains(value, "^") || strings.Contains(value, "$")) { regexpValue = "^" + regexpValue + "$" } r, err := regexp.Compile(regexpValue) //if not regexp compatible use original value if err != nil { if value == configValue { found = true break } } else if r.MatchString(configValue) == true { found = true break } } } } else { for _, alias := range state.Aliases { if strings.Contains(alias.Name, filter) { found = true break } } if strings.Contains(state.Fingerprint, filter) { found = true } } if !found { return false } } return true } func (c *imageCmd) aliasShouldShow(filters []string, state *api.ImageAliasesEntry) bool { if len(filters) == 0 { return true } for _, filter := range filters { if strings.Contains(state.Name, filter) || strings.Contains(state.Target, filter) { return true } } return false } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/help.go������������������������������������������������������������������������������0000644�0610621�0607500�00000003742�13172163242�015544� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "sort" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type helpCmd struct { showAll bool } func (c *helpCmd) showByDefault() bool { return true } func (c *helpCmd) usage() string { return i18n.G( `Usage: lxc help [--all] Help page for the LXD client.`) } func (c *helpCmd) flags() { gnuflag.BoolVar(&c.showAll, "all", false, i18n.G("Show all commands (not just interesting ones)")) } func (c *helpCmd) run(conf *config.Config, args []string) error { if len(args) > 0 { for _, name := range args { cmd, ok := commands[name] if !ok { fmt.Fprintf(os.Stderr, i18n.G("error: unknown command: %s")+"\n", name) } else { fmt.Fprintf(os.Stdout, cmd.usage()+"\n") } } return nil } fmt.Println(i18n.G("Usage: lxc <command> [options]")) fmt.Println() fmt.Println(i18n.G(`This is the LXD command line client. All of LXD's features can be driven through the various commands below. For help with any of those, simply call them with --help.`)) fmt.Println() fmt.Println(i18n.G("Commands:")) var names []string for name := range commands { names = append(names, name) } sort.Strings(names) for _, name := range names { if name == "help" { continue } cmd := commands[name] if c.showAll || cmd.showByDefault() { fmt.Printf(" %-16s %s\n", name, summaryLine(cmd.usage())) } } fmt.Println() fmt.Println(i18n.G("Options:")) fmt.Println(" --all " + i18n.G("Print less common commands")) fmt.Println(" --debug " + i18n.G("Print debug information")) fmt.Println(" --verbose " + i18n.G("Print verbose information")) fmt.Println(" --version " + i18n.G("Show client version")) fmt.Println() fmt.Println(i18n.G("Environment:")) fmt.Println(" LXD_CONF " + i18n.G("Path to an alternate client configuration directory")) fmt.Println(" LXD_DIR " + i18n.G("Path to an alternate server directory")) return nil } ������������������������������lxd-2.0.11/lxc/finger.go����������������������������������������������������������������������������0000644�0610621�0607500�00000001333�13172163242�016060� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/i18n" ) type fingerCmd struct{} func (c *fingerCmd) showByDefault() bool { return false } func (c *fingerCmd) usage() string { return i18n.G( `Usage: lxc finger [<remote>:] Check if the LXD server is alive.`) } func (c *fingerCmd) flags() {} func (c *fingerCmd) run(conf *config.Config, args []string) error { if len(args) > 1 { return errArgs } // Parse the remote remote := conf.DefaultRemote if len(args) > 0 { var err error remote, _, err = conf.ParseRemote(args[0]) if err != nil { return err } } // Attempt to connect _, err := conf.GetContainerServer(remote) if err != nil { return err } return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/file_windows.go����������������������������������������������������������������������0000644�0610621�0607500�00000000241�13172163242�017274� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build windows package main import ( "os" ) func (c *fileCmd) getOwner(f *os.File) (os.FileMode, int, int, error) { return os.FileMode(0), -1, -1, nil } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/file_unix.go�������������������������������������������������������������������������0000644�0610621�0607500�00000000554�13172163242�016574� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows package main import ( "os" "syscall" ) func (c *fileCmd) getOwner(f *os.File) (os.FileMode, int, int, error) { fInfo, err := f.Stat() if err != nil { return os.FileMode(0), -1, -1, err } mode := fInfo.Mode() uid := int(fInfo.Sys().(*syscall.Stat_t).Uid) gid := int(fInfo.Sys().(*syscall.Stat_t).Gid) return mode, uid, gid, nil } ����������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/file.go������������������������������������������������������������������������������0000644�0610621�0607500�00000014367�13172163242�015540� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "strconv" "strings" "syscall" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared/termios" ) type fileCmd struct { uid int gid int mode string } func (c *fileCmd) showByDefault() bool { return true } func (c *fileCmd) usage() string { return i18n.G( `Usage: lxc file <subcommand> [options] Manage files in containers. lxc file pull [<remote>:]<container>/<path> [[<remote>:]<container>/<path>...] <target path> Pull files from containers. lxc file push [--uid=UID] [--gid=GID] [--mode=MODE] <source path> [<source path>...] [<remote>:]<container>/<path> Push files into containers. lxc file edit [<remote>:]<container>/<path> Edit files in containers using the default text editor. *Examples* lxc file push /etc/hosts foo/etc/hosts To push /etc/hosts into the container "foo". lxc file pull foo/etc/hosts . To pull /etc/hosts from the container and write it to the current directory.`) } func (c *fileCmd) flags() { gnuflag.IntVar(&c.uid, "uid", -1, i18n.G("Set the file's uid on push")) gnuflag.IntVar(&c.gid, "gid", -1, i18n.G("Set the file's gid on push")) gnuflag.StringVar(&c.mode, "mode", "", i18n.G("Set the file's perms on push")) } func (c *fileCmd) push(conf *config.Config, send_file_perms bool, args []string) error { if len(args) < 2 { return errArgs } target := args[len(args)-1] pathSpec := strings.SplitN(target, "/", 2) if len(pathSpec) != 2 { return fmt.Errorf(i18n.G("Invalid target %s"), target) } targetPath := pathSpec[1] remote, container, err := conf.ParseRemote(pathSpec[0]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } mode := os.FileMode(0755) if c.mode != "" { if len(c.mode) == 3 { c.mode = "0" + c.mode } m, err := strconv.ParseInt(c.mode, 0, 0) if err != nil { return err } mode = os.FileMode(m) } uid := 0 if c.uid >= 0 { uid = c.uid } gid := 0 if c.gid >= 0 { gid = c.gid } _, targetfilename := filepath.Split(targetPath) var sourcefilenames []string for _, fname := range args[:len(args)-1] { if !strings.HasPrefix(fname, "--") { sourcefilenames = append(sourcefilenames, shared.HostPath(filepath.Clean(fname))) } } if (targetfilename != "") && (len(sourcefilenames) > 1) { return errArgs } /* Make sure all of the files are accessible by us before trying to * push any of them. */ var files []*os.File for _, f := range sourcefilenames { var file *os.File if f == "-" { file = os.Stdin } else { file, err = os.Open(f) if err != nil { return err } } defer file.Close() files = append(files, file) } for _, f := range files { fpath := targetPath if targetfilename == "" { fpath = path.Join(fpath, path.Base(f.Name())) } args := lxd.ContainerFileArgs{ Content: f, UID: -1, GID: -1, Mode: -1, } if send_file_perms { if c.mode == "" || c.uid == -1 || c.gid == -1 { fMode, fUid, fGid, err := c.getOwner(f) if err != nil { return err } if c.mode == "" { mode = fMode } if c.uid == -1 { uid = fUid } if c.gid == -1 { gid = fGid } } args.UID = int64(uid) args.GID = int64(gid) args.Mode = int(mode.Perm()) } err = d.CreateContainerFile(container, fpath, args) if err != nil { return err } } return nil } func (c *fileCmd) pull(conf *config.Config, args []string) error { if len(args) < 2 { return errArgs } target := shared.HostPath(filepath.Clean(args[len(args)-1])) targetIsDir := false sb, err := os.Stat(target) if err != nil && !os.IsNotExist(err) { return err } /* * If the path exists, just use it. If it doesn't exist, it might be a * directory in one of two cases: * 1. Someone explicitly put "/" at the end * 2. Someone provided more than one source. In this case the target * should be a directory so we can save all the files into it. */ if err == nil { targetIsDir = sb.IsDir() if !targetIsDir && len(args)-1 > 1 { return fmt.Errorf(i18n.G("More than one file to download, but target is not a directory")) } } else if strings.HasSuffix(target, string(os.PathSeparator)) || len(args)-1 > 1 { if err := os.MkdirAll(target, 0755); err != nil { return err } targetIsDir = true } for _, f := range args[:len(args)-1] { pathSpec := strings.SplitN(f, "/", 2) if len(pathSpec) != 2 { return fmt.Errorf(i18n.G("Invalid source %s"), f) } remote, container, err := conf.ParseRemote(pathSpec[0]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } buf, _, err := d.GetContainerFile(container, pathSpec[1]) if err != nil { return err } var targetPath string if targetIsDir { targetPath = path.Join(target, path.Base(pathSpec[1])) } else { targetPath = target } var f *os.File if targetPath == "-" { f = os.Stdout } else { f, err = os.Create(targetPath) if err != nil { return err } defer f.Close() } _, err = io.Copy(f, buf) if err != nil { return err } } return nil } func (c *fileCmd) edit(conf *config.Config, args []string) error { if len(args) != 1 { return errArgs } // If stdin isn't a terminal, read text from it if !termios.IsTerminal(int(syscall.Stdin)) { return c.push(conf, false, append([]string{os.Stdin.Name()}, args[0])) } // Create temp file f, err := ioutil.TempFile("", "lxd_file_edit_") fname := f.Name() f.Close() os.Remove(fname) defer os.Remove(fname) // Extract current value err = c.pull(conf, append([]string{args[0]}, fname)) if err != nil { return err } _, err = shared.TextEditor(fname, []byte{}) if err != nil { return err } err = c.push(conf, false, append([]string{fname}, args[0])) if err != nil { return err } return nil } func (c *fileCmd) run(conf *config.Config, args []string) error { if len(args) < 1 { return errUsage } switch args[0] { case "push": return c.push(conf, true, args[1:]) case "pull": return c.pull(conf, args[1:]) case "edit": return c.edit(conf, args[1:]) default: return errArgs } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/exec_windows.go����������������������������������������������������������������������0000644�0610621�0607500�00000001771�13172163242�017312� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build windows package main import ( "io" "os" "os/signal" "github.com/gorilla/websocket" "github.com/mattn/go-colorable" "github.com/lxc/lxd/shared/logger" ) // Windows doesn't process ANSI sequences natively, so we wrap // os.Stdout for improved user experience for Windows client type WrappedWriteCloser struct { io.Closer wrapper io.Writer } func (wwc *WrappedWriteCloser) Write(p []byte) (int, error) { return wwc.wrapper.Write(p) } func (c *execCmd) getStdout() io.WriteCloser { return &WrappedWriteCloser{os.Stdout, colorable.NewColorableStdout()} } func (c *execCmd) getTERM() (string, bool) { return "dumb", true } func (c *execCmd) controlSocketHandler(control *websocket.Conn) { ch := make(chan os.Signal, 10) signal.Notify(ch, os.Interrupt) closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "") defer control.WriteMessage(websocket.CloseMessage, closeMsg) for { sig := <-ch logger.Debugf("Received '%s signal', updating window geometry.", sig) } } �������lxd-2.0.11/lxc/exec_unix.go�������������������������������������������������������������������������0000644�0610621�0607500�00000001412�13172163242�016573� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// +build !windows package main import ( "io" "os" "os/signal" "syscall" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared/logger" ) func (c *execCmd) getStdout() io.WriteCloser { return os.Stdout } func (c *execCmd) getTERM() (string, bool) { return os.LookupEnv("TERM") } func (c *execCmd) controlSocketHandler(control *websocket.Conn) { ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGWINCH) for { sig := <-ch logger.Debugf("Received '%s signal', updating window geometry.", sig) err := c.sendTermSize(control) if err != nil { logger.Debugf("error setting term size %s", err) break } } closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "") control.WriteMessage(websocket.CloseMessage, closeMsg) } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/exec.go������������������������������������������������������������������������������0000644�0610621�0607500�00000010311�13172163242�015526� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "encoding/json" "fmt" "os" "strconv" "strings" "syscall" "github.com/gorilla/websocket" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/termios" ) type envList []string func (f *envList) String() string { return fmt.Sprint(*f) } func (f *envList) Set(value string) error { if f == nil { *f = make(envList, 1) } else { *f = append(*f, value) } return nil } type execCmd struct { modeFlag string envArgs envList } func (c *execCmd) showByDefault() bool { return true } func (c *execCmd) usage() string { return i18n.G( `Usage: lxc exec [<remote>:]<container> [--mode=auto|interactive|non-interactive] [--env KEY=VALUE...] [--] <command line> Execute commands in containers. Mode defaults to non-interactive, interactive mode is selected if both stdin AND stdout are terminals (stderr is ignored).`) } func (c *execCmd) flags() { gnuflag.Var(&c.envArgs, "env", i18n.G("Environment variable to set (e.g. HOME=/home/foo)")) gnuflag.StringVar(&c.modeFlag, "mode", "auto", i18n.G("Override the terminal mode (auto, interactive or non-interactive)")) } func (c *execCmd) sendTermSize(control *websocket.Conn) error { width, height, err := termios.GetSize(int(syscall.Stdout)) if err != nil { return err } logger.Debugf("Window size is now: %dx%d", width, height) w, err := control.NextWriter(websocket.TextMessage) if err != nil { return err } msg := api.ContainerExecControl{} msg.Command = "window-resize" msg.Args = make(map[string]string) msg.Args["width"] = strconv.Itoa(width) msg.Args["height"] = strconv.Itoa(height) buf, err := json.Marshal(msg) if err != nil { return err } _, err = w.Write(buf) w.Close() return err } func (c *execCmd) run(conf *config.Config, args []string) error { if len(args) < 2 { return errArgs } remote, name, err := conf.ParseRemote(args[0]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } /* FIXME: Default values for HOME and USER are now handled by LXD. This code should be removed after most users upgraded. */ env := map[string]string{"HOME": "/root", "USER": "root"} if myTerm, ok := c.getTERM(); ok { env["TERM"] = myTerm } for _, arg := range c.envArgs { pieces := strings.SplitN(arg, "=", 2) value := "" if len(pieces) > 1 { value = pieces[1] } env[pieces[0]] = value } cfd := int(syscall.Stdin) var interactive bool if c.modeFlag == "interactive" { interactive = true } else if c.modeFlag == "non-interactive" { interactive = false } else { interactive = termios.IsTerminal(cfd) && termios.IsTerminal(int(syscall.Stdout)) } var oldttystate *termios.State if interactive { oldttystate, err = termios.MakeRaw(cfd) if err != nil { return err } defer termios.Restore(cfd, oldttystate) } handler := c.controlSocketHandler if !interactive { handler = nil } var width, height int if interactive { width, height, err = termios.GetSize(int(syscall.Stdout)) if err != nil { return err } } stdout := c.getStdout() req := api.ContainerExecPost{ Command: args[1:], WaitForWS: true, Interactive: interactive, Environment: env, Width: width, Height: height, } execArgs := lxd.ContainerExecArgs{ Stdin: os.Stdin, Stdout: stdout, Stderr: os.Stderr, Control: handler, DataDone: make(chan bool), } // Run the command in the container op, err := d.ExecContainer(name, req, &execArgs) if err != nil { return err } // Wait for the operation to complete err = op.Wait() if err != nil { return err } // Wait for any remaining I/O to be flushed <-execArgs.DataDone if oldttystate != nil { /* A bit of a special case here: we want to exit with the same code as * the process inside the container, so we explicitly exit here * instead of returning an error. * * Additionally, since os.Exit() exits without running deferred * functions, we restore the terminal explicitly. */ termios.Restore(cfd, oldttystate) } os.Exit(int(op.Metadata["return"].(float64))) return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/delete.go����������������������������������������������������������������������������0000644�0610621�0607500�00000005537�13172163242�016062� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "bufio" "fmt" "os" "strings" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type deleteCmd struct { force bool interactive bool } func (c *deleteCmd) showByDefault() bool { return true } func (c *deleteCmd) usage() string { return i18n.G( `Usage: lxc delete [<remote>:]<container>[/<snapshot>] [[<remote>:]<container>[/<snapshot>]...] Delete containers and snapshots.`) } func (c *deleteCmd) flags() { gnuflag.BoolVar(&c.force, "f", false, i18n.G("Force the removal of running containers")) gnuflag.BoolVar(&c.force, "force", false, i18n.G("Force the removal of running containers")) gnuflag.BoolVar(&c.interactive, "i", false, i18n.G("Require user confirmation")) gnuflag.BoolVar(&c.interactive, "interactive", false, i18n.G("Require user confirmation")) } func (c *deleteCmd) promptDelete(name string) error { reader := bufio.NewReader(os.Stdin) fmt.Printf(i18n.G("Remove %s (yes/no): "), name) input, _ := reader.ReadString('\n') input = strings.TrimSuffix(input, "\n") if !shared.StringInSlice(strings.ToLower(input), []string{i18n.G("yes")}) { return fmt.Errorf(i18n.G("User aborted delete operation.")) } return nil } func (c *deleteCmd) doDelete(d lxd.ContainerServer, name string) error { var op *lxd.Operation var err error if shared.IsSnapshot(name) { // Snapshot delete fields := strings.SplitN(name, shared.SnapshotDelimiter, 2) op, err = d.DeleteContainerSnapshot(fields[0], fields[1]) } else { // Container delete op, err = d.DeleteContainer(name) } if err != nil { return err } return op.Wait() } func (c *deleteCmd) run(conf *config.Config, args []string) error { if len(args) == 0 { return errArgs } for _, nameArg := range args { remote, name, err := conf.ParseRemote(nameArg) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } if c.interactive { err := c.promptDelete(name) if err != nil { return err } } if shared.IsSnapshot(name) { return c.doDelete(d, name) } ct, _, err := d.GetContainer(name) if err != nil { return err } if ct.StatusCode != 0 && ct.StatusCode != api.Stopped { if !c.force { return fmt.Errorf(i18n.G("The container is currently running, stop it first or pass --force.")) } req := api.ContainerStatePut{ Action: "stop", Timeout: -1, Force: true, } op, err := d.UpdateContainerState(name, req, "") if err != nil { return err } err = op.Wait() if err != nil { return fmt.Errorf(i18n.G("Stopping the container failed: %s"), err) } if ct.Ephemeral == true { return nil } } if err := c.doDelete(d, name); err != nil { return err } } return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/copy.go������������������������������������������������������������������������������0000644�0610621�0607500�00000011004�13172163242�015554� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "strings" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type copyCmd struct { ephem bool } func (c *copyCmd) showByDefault() bool { return true } func (c *copyCmd) usage() string { return i18n.G( `Usage: lxc copy [<remote>:]<source>[/<snapshot>] [[<remote>:]<destination>] [--ephemeral|e] Copy containers within or in between LXD instances.`) } func (c *copyCmd) flags() { gnuflag.BoolVar(&c.ephem, "ephemeral", false, i18n.G("Ephemeral container")) gnuflag.BoolVar(&c.ephem, "e", false, i18n.G("Ephemeral container")) } func (c *copyCmd) copyContainer(conf *config.Config, sourceResource string, destResource string, keepVolatile bool, ephemeral int) error { // Parse the source sourceRemote, sourceName, err := conf.ParseRemote(sourceResource) if err != nil { return err } // Parse the destination destRemote, destName, err := conf.ParseRemote(destResource) if err != nil { return err } // Make sure we have a container or snapshot name if sourceName == "" { return fmt.Errorf(i18n.G("You must specify a source container name")) } // If no destination name was provided, use the same as the source if destName == "" { destName = sourceName } // Connect to the source host source, err := conf.GetContainerServer(sourceRemote) if err != nil { return err } // Connect to the destination host var dest lxd.ContainerServer if sourceRemote == destRemote { // Source and destination are the same dest = source } else { // Destination is different, connect to it dest, err = conf.GetContainerServer(destRemote) if err != nil { return err } } var op *lxd.RemoteOperation if shared.IsSnapshot(sourceName) { // Prepare the container creation request args := lxd.ContainerSnapshotCopyArgs{ Name: destName, } // Copy of a snapshot into a new container srcFields := strings.SplitN(sourceName, shared.SnapshotDelimiter, 2) entry, _, err := source.GetContainerSnapshot(srcFields[0], srcFields[1]) if err != nil { return err } // Allow overriding the ephemeral status if ephemeral == 1 { entry.Ephemeral = true } else if ephemeral == 0 { entry.Ephemeral = false } // Strip the volatile keys if requested if !keepVolatile { for k := range entry.Config { if k == "volatile.base_image" { continue } if strings.HasPrefix(k, "volatile") { delete(entry.Config, k) } } } // Do the actual copy op, err = dest.CopyContainerSnapshot(source, *entry, &args) if err != nil { return err } } else { // Prepare the container creation request args := lxd.ContainerCopyArgs{ Name: destName, } // Copy of a container into a new container entry, _, err := source.GetContainer(sourceName) if err != nil { return err } // Allow overriding the ephemeral status if ephemeral == 1 { entry.Ephemeral = true } else if ephemeral == 0 { entry.Ephemeral = false } // Strip the volatile keys if requested if !keepVolatile { for k := range entry.Config { if k == "volatile.base_image" { continue } if strings.HasPrefix(k, "volatile") { delete(entry.Config, k) } } } // Do the actual copy op, err = dest.CopyContainer(source, *entry, &args) if err != nil { return err } } // Watch the background operation progress := ProgressRenderer{Format: i18n.G("Transferring container: %s")} _, err = op.AddHandler(progress.UpdateOp) if err != nil { progress.Done("") return err } // Wait for the copy to complete err = op.Wait() if err != nil { progress.Done("") return err } progress.Done("") // If choosing a random name, show it to the user if destResource == "" { // Get the successful operation data opInfo, err := op.GetTarget() if err != nil { return err } // Extract the list of affected containers containers, ok := opInfo.Resources["containers"] if !ok || len(containers) != 1 { return fmt.Errorf(i18n.G("Failed to get the new container name")) } // Extract the name of the container fields := strings.Split(containers[0], "/") fmt.Printf(i18n.G("Container name is: %s")+"\n", fields[len(fields)-1]) } return nil } func (c *copyCmd) run(conf *config.Config, args []string) error { if len(args) != 2 { return errArgs } // For copies, default to non-ephemeral and allow override (move uses -1) ephem := 0 if c.ephem { ephem = 1 } return c.copyContainer(conf, args[0], args[1], false, ephem) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/config/������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015524� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/config/remote.go���������������������������������������������������������������������0000644�0610621�0607500�00000010105�13172163242�017343� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package config import ( "fmt" "io/ioutil" "strings" "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared" ) // Remote holds details for communication with a remote daemon type Remote struct { Addr string `yaml:"addr"` Public bool `yaml:"public"` Protocol string `yaml:"protocol,omitempty"` AuthType string `yaml:"auth_type,omitempty"` Static bool `yaml:"-"` } // ParseRemote splits remote and object func (c *Config) ParseRemote(raw string) (string, string, error) { result := strings.SplitN(raw, ":", 2) if len(result) == 1 { return c.DefaultRemote, raw, nil } _, ok := c.Remotes[result[0]] if !ok { // Attempt to play nice with snapshots containing ":" if shared.IsSnapshot(raw) && strings.Contains(result[0], "/") { return c.DefaultRemote, raw, nil } return "", "", fmt.Errorf("The remote \"%s\" doesn't exist", result[0]) } return result[0], result[1], nil } // GetContainerServer returns a ContainerServer struct for the remote func (c *Config) GetContainerServer(name string) (lxd.ContainerServer, error) { // Get the remote remote, ok := c.Remotes[name] if !ok { return nil, fmt.Errorf("The remote \"%s\" doesn't exist", name) } // Sanity checks if remote.Public || remote.Protocol == "simplestreams" { return nil, fmt.Errorf("The remote isn't a private LXD server") } // Get connection arguments args, err := c.getConnectionArgs(name) if err != nil { return nil, err } // Unix socket if strings.HasPrefix(remote.Addr, "unix:") { d, err := lxd.ConnectLXDUnix(strings.TrimPrefix(strings.TrimPrefix(remote.Addr, "unix:"), "//"), args) if err != nil { return nil, err } return d, nil } // HTTPs if args.TLSClientCert == "" || args.TLSClientKey == "" { return nil, fmt.Errorf("Missing TLS client certificate and key") } d, err := lxd.ConnectLXD(remote.Addr, args) if err != nil { return nil, err } return d, nil } // GetImageServer returns a ImageServer struct for the remote func (c *Config) GetImageServer(name string) (lxd.ImageServer, error) { // Get the remote remote, ok := c.Remotes[name] if !ok { return nil, fmt.Errorf("The remote \"%s\" doesn't exist", name) } // Get connection arguments args, err := c.getConnectionArgs(name) if err != nil { return nil, err } // Unix socket if strings.HasPrefix(remote.Addr, "unix:") { d, err := lxd.ConnectLXDUnix(strings.TrimPrefix(strings.TrimPrefix(remote.Addr, "unix:"), "//"), args) if err != nil { return nil, err } return d, nil } // HTTPs (simplestreams) if remote.Protocol == "simplestreams" { d, err := lxd.ConnectSimpleStreams(remote.Addr, args) if err != nil { return nil, err } return d, nil } // HTTPs (public LXD) if remote.Public { d, err := lxd.ConnectPublicLXD(remote.Addr, args) if err != nil { return nil, err } return d, nil } // HTTPs (private LXD) d, err := lxd.ConnectLXD(remote.Addr, args) if err != nil { return nil, err } return d, nil } func (c *Config) getConnectionArgs(name string) (*lxd.ConnectionArgs, error) { remote, _ := c.Remotes[name] args := lxd.ConnectionArgs{ UserAgent: c.UserAgent, AuthType: remote.AuthType, AuthInteractor: c.authInteractor, } if c.cookiejar != nil { args.CookieJar = c.cookiejar } // Client certificate if shared.PathExists(c.ConfigPath("client.crt")) { content, err := ioutil.ReadFile(c.ConfigPath("client.crt")) if err != nil { return nil, err } args.TLSClientCert = string(content) } // Client key if shared.PathExists(c.ConfigPath("client.key")) { content, err := ioutil.ReadFile(c.ConfigPath("client.key")) if err != nil { return nil, err } args.TLSClientKey = string(content) } // Client CA if shared.PathExists(c.ConfigPath("client.ca")) { content, err := ioutil.ReadFile(c.ConfigPath("client.ca")) if err != nil { return nil, err } args.TLSCA = string(content) } // Server certificate if shared.PathExists(c.ServerCertPath(name)) { content, err := ioutil.ReadFile(c.ServerCertPath(name)) if err != nil { return nil, err } args.TLSServerCert = string(content) } return &args, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/config/file.go�����������������������������������������������������������������������0000644�0610621�0607500�00000004002�13172163242�016766� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package config import ( "fmt" "io/ioutil" "os" "path/filepath" "gopkg.in/yaml.v2" "github.com/lxc/lxd/shared" ) // LoadConfig reads the configuration from the config path; if the path does // not exist, it returns a default configuration. func LoadConfig(path string) (*Config, error) { // Open the config file content, err := ioutil.ReadFile(path) if err != nil { return nil, fmt.Errorf("Unable to read the configuration file: %v", err) } // Decode the yaml document c := NewConfig(filepath.Dir(path), false) err = yaml.Unmarshal(content, &c) if err != nil { return nil, fmt.Errorf("Unable to decode the configuration: %v", err) } for k, r := range c.Remotes { if !r.Public && r.AuthType == "" { r.AuthType = "tls" c.Remotes[k] = r } } // Set default values if c.Remotes == nil { c.Remotes = make(map[string]Remote) } // Apply the static remotes for k, v := range StaticRemotes { c.Remotes[k] = v } // NOTE: Remove this once we only see a small fraction of non-simplestreams users // Upgrade users to the "simplestreams" protocol images, ok := c.Remotes["images"] if ok && images.Protocol != ImagesRemote.Protocol && images.Addr == ImagesRemote.Addr { c.Remotes["images"] = ImagesRemote c.SaveConfig(path) } return c, nil } // SaveConfig writes the provided configuration to the config file. func (c *Config) SaveConfig(path string) error { // Create a new copy for the config file conf := Config{} err := shared.DeepCopy(c, &conf) if err != nil { return fmt.Errorf("Unable to copy the configuration: %v", err) } // Remove the static remotes for k := range StaticRemotes { delete(conf.Remotes, k) } // Create the config file (or truncate an existing one) f, err := os.Create(path) if err != nil { return fmt.Errorf("Unable to create the configuration file: %v", err) } defer f.Close() // Write the new config data, err := yaml.Marshal(c) _, err = f.Write(data) if err != nil { return fmt.Errorf("Unable to write the configuration: %v", err) } return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/config/default.go��������������������������������������������������������������������0000644�0610621�0607500�00000002503�13172163242�017477� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package config // LocalRemote is the default local remote (over the LXD unix socket) var LocalRemote = Remote{ Addr: "unix://", Static: true, Public: false, } // ImagesRemote is the community image server (over simplestreams) var ImagesRemote = Remote{ Addr: "https://images.linuxcontainers.org", Public: true, Protocol: "simplestreams", } // UbuntuRemote is the Ubuntu image server (over simplestreams) var UbuntuRemote = Remote{ Addr: "https://cloud-images.ubuntu.com/releases", Static: true, Public: true, Protocol: "simplestreams", } // UbuntuDailyRemote is the Ubuntu daily image server (over simplestreams) var UbuntuDailyRemote = Remote{ Addr: "https://cloud-images.ubuntu.com/daily", Static: true, Public: true, Protocol: "simplestreams", } // StaticRemotes is the list of remotes which can't be removed var StaticRemotes = map[string]Remote{ "local": LocalRemote, "ubuntu": UbuntuRemote, "ubuntu-daily": UbuntuDailyRemote, } // DefaultRemotes is the list of default remotes var DefaultRemotes = map[string]Remote{ "images": ImagesRemote, "local": LocalRemote, "ubuntu": UbuntuRemote, "ubuntu-daily": UbuntuDailyRemote, } // DefaultConfig is the default configuration var DefaultConfig = Config{ Remotes: DefaultRemotes, DefaultRemote: "local", } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/config/config.go���������������������������������������������������������������������0000644�0610621�0607500�00000003660�13172163242�017325� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package config import ( "fmt" "path/filepath" "github.com/juju/persistent-cookiejar" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) // Config holds settings to be used by a client or daemon type Config struct { // DefaultRemote holds the remote daemon name from the Remotes map // that the client should communicate with by default DefaultRemote string `yaml:"default-remote"` // Remotes defines a map of remote daemon names to the details for // communication with the named daemon Remotes map[string]Remote `yaml:"remotes"` // Command line aliases for `lxc` Aliases map[string]string `yaml:"aliases"` // Configuration directory ConfigDir string `yaml:"-"` // The UserAgent to pass for all queries UserAgent string `yaml:"-"` authInteractor httpbakery.Interactor cookiejar *cookiejar.Jar } // ConfigPath returns a joined path of the configuration directory and passed arguments func (c *Config) ConfigPath(paths ...string) string { path := []string{c.ConfigDir} path = append(path, paths...) return filepath.Join(path...) } // ServerCertPath returns the path for the remote's server certificate func (c *Config) ServerCertPath(remote string) string { return c.ConfigPath("servercerts", fmt.Sprintf("%s.crt", remote)) } // SetAuthInteractor sets the interactor for macaroon-based authorization func (c *Config) SetAuthInteractor(interactor httpbakery.Interactor) { c.authInteractor = interactor } // SaveCookies saves cookies to file func (c *Config) SaveCookies() { if c.cookiejar != nil { c.cookiejar.Save() } } // NewConfig returns a Config, optionally using default remotes. func NewConfig(configDir string, defaults bool) *Config { config := &Config{ConfigDir: configDir} if defaults { config.Remotes = DefaultRemotes config.DefaultRemote = "local" } if configDir != "" { config.cookiejar, _ = cookiejar.New( &cookiejar.Options{ Filename: filepath.Join(configDir, "cookies")}) } return config } ��������������������������������������������������������������������������������lxd-2.0.11/lxc/config/cert.go�����������������������������������������������������������������������0000644�0610621�0607500�00000001247�13172163242�017014� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package config import ( "github.com/lxc/lxd/shared" ) // HasClientCertificate will return true if a client certificate has already been generated func (c *Config) HasClientCertificate() bool { certf := c.ConfigPath("client.crt") keyf := c.ConfigPath("client.key") if !shared.PathExists(certf) || !shared.PathExists(keyf) { return false } return true } // GenerateClientCertificate will generate the needed client.crt and client.key if needed func (c *Config) GenerateClientCertificate() error { if c.HasClientCertificate() { return nil } certf := c.ConfigPath("client.crt") keyf := c.ConfigPath("client.key") return shared.FindOrGenCert(certf, keyf, true) } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/config.go����������������������������������������������������������������������������0000644�0610621�0607500�00000054064�13172163242�016064� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "crypto/x509" "encoding/base64" "encoding/pem" "fmt" "io/ioutil" "os" "sort" "strings" "syscall" "github.com/olekukonko/tablewriter" "gopkg.in/yaml.v2" "github.com/lxc/lxd/client" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" "github.com/lxc/lxd/shared/termios" ) type configCmd struct { expanded bool } func (c *configCmd) showByDefault() bool { return true } func (c *configCmd) flags() { gnuflag.BoolVar(&c.expanded, "expanded", false, i18n.G("Show the expanded configuration")) } func (c *configCmd) configEditHelp() string { return i18n.G( `### This is a yaml representation of the configuration. ### Any line starting with a '# will be ignored. ### ### A sample configuration looks like: ### name: container1 ### profiles: ### - default ### config: ### volatile.eth0.hwaddr: 00:16:3e:e9:f8:7f ### devices: ### homedir: ### path: /extra ### source: /home/user ### type: disk ### ephemeral: false ### ### Note that the name is shown but cannot be changed`) } func (c *configCmd) usage() string { return i18n.G( `Usage: lxc config <subcommand> [options] Change container or server configuration options. *Container configuration* lxc config get [<remote>:][container] <key> Get container or server configuration key. lxc config set [<remote>:][container] <key> <value> Set container or server configuration key. lxc config unset [<remote>:][container] <key> Unset container or server configuration key. lxc config show [<remote>:][container] [--expanded] Show container or server configuration. lxc config edit [<remote>:][container] Edit configuration, either by launching external editor or reading STDIN. *Device management* lxc config device add [<remote>:]<container> <device> <type> [key=value...] Add a device to a container. lxc config device get [<remote>:]<container> <device> <key> Get a device property. lxc config device set [<remote>:]<container> <device> <key> <value> Set a device property. lxc config device unset [<remote>:]<container> <device> <key> Unset a device property. lxc config device list [<remote>:]<container> List devices for container. lxc config device show [<remote>:]<container> Show full device details for container. lxc config device remove [<remote>:]<container> <name>... Remove device from container. *Client trust store management* lxc config trust list [<remote>:] List all trusted certs. lxc config trust add [<remote>:] <certfile.crt> Add certfile.crt to trusted hosts. lxc config trust remove [<remote>:] [hostname|fingerprint] Remove the cert from trusted hosts. *Examples* cat config.yaml | lxc config edit <container> Update the container configuration from config.yaml. lxc config device add [<remote>:]container1 <device-name> disk source=/share/c1 path=opt Will mount the host's /share/c1 onto /opt in the container. lxc config set [<remote>:]<container> limits.cpu 2 Will set a CPU limit of "2" for the container. lxc config set core.https_address [::]:8443 Will have LXD listen on IPv4 and IPv6 port 8443. lxc config set core.trust_password blah Will set the server's trust password to blah.`) } func (c *configCmd) doSet(conf *config.Config, args []string, unset bool) error { if len(args) != 4 { return errArgs } // [[lxc config]] set dakara:c1 limits.memory 200000 remote, name, err := conf.ParseRemote(args[1]) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } key := args[2] value := args[3] if !termios.IsTerminal(int(syscall.Stdin)) && value == "-" { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return fmt.Errorf(i18n.G("Can't read from stdin: %s"), err) } value = string(buf[:]) } container, etag, err := d.GetContainer(name) if err != nil { return err } if unset { _, ok := container.Config[key] if !ok { return fmt.Errorf(i18n.G("Can't unset key '%s', it's not currently set"), key) } delete(container.Config, key) } else { container.Config[key] = value } op, err := d.UpdateContainer(name, container.Writable(), etag) if err != nil { return err } return op.Wait() } func (c *configCmd) run(conf *config.Config, args []string) error { if len(args) < 1 { return errUsage } switch args[0] { case "unset": if len(args) < 2 { return errArgs } // Deal with local server if len(args) == 2 { c, err := conf.GetContainerServer(conf.DefaultRemote) if err != nil { return err } server, etag, err := c.GetServer() if err != nil { return err } _, ok := server.Config[args[1]] if !ok { return fmt.Errorf(i18n.G("Can't unset key '%s', it's not currently set."), args[1]) } delete(server.Config, args[1]) return c.UpdateServer(server.Writable(), etag) } // Deal with remote server remote, container, err := conf.ParseRemote(args[1]) if err != nil { return err } if container == "" { c, err := conf.GetContainerServer(remote) if err != nil { return err } server, etag, err := c.GetServer() if err != nil { return err } _, ok := server.Config[args[2]] if !ok { return fmt.Errorf(i18n.G("Can't unset key '%s', it's not currently set."), args[1]) } delete(server.Config, args[2]) return c.UpdateServer(server.Writable(), etag) } // Deal with container args = append(args, "") return c.doSet(conf, args, true) case "set": if len(args) < 3 { return errArgs } // Deal with local server if len(args) == 3 { c, err := conf.GetContainerServer(conf.DefaultRemote) if err != nil { return err } server, etag, err := c.GetServer() if err != nil { return err } server.Config[args[1]] = args[2] return c.UpdateServer(server.Writable(), etag) } // Deal with remote server remote, container, err := conf.ParseRemote(args[1]) if err != nil { return err } if container == "" { c, err := conf.GetContainerServer(remote) if err != nil { return err } server, etag, err := c.GetServer() if err != nil { return err } server.Config[args[2]] = args[3] return c.UpdateServer(server.Writable(), etag) } // Deal with container return c.doSet(conf, args, false) case "trust": if len(args) < 2 { return errArgs } switch args[1] { case "list": var remote string if len(args) == 3 { var err error remote, _, err = conf.ParseRemote(args[2]) if err != nil { return err } } else { remote = conf.DefaultRemote } d, err := conf.GetContainerServer(remote) if err != nil { return err } trust, err := d.GetCertificates() if err != nil { return err } data := [][]string{} for _, cert := range trust { fp := cert.Fingerprint[0:12] certBlock, _ := pem.Decode([]byte(cert.Certificate)) if certBlock == nil { return fmt.Errorf(i18n.G("Invalid certificate")) } cert, err := x509.ParseCertificate(certBlock.Bytes) if err != nil { return err } const layout = "Jan 2, 2006 at 3:04pm (MST)" issue := cert.NotBefore.Format(layout) expiry := cert.NotAfter.Format(layout) data = append(data, []string{fp, cert.Subject.CommonName, issue, expiry}) } table := tablewriter.NewWriter(os.Stdout) table.SetAutoWrapText(false) table.SetAlignment(tablewriter.ALIGN_LEFT) table.SetRowLine(true) table.SetHeader([]string{ i18n.G("FINGERPRINT"), i18n.G("COMMON NAME"), i18n.G("ISSUE DATE"), i18n.G("EXPIRY DATE")}) sort.Sort(SortImage(data)) table.AppendBulk(data) table.Render() return nil case "add": var remote string if len(args) < 3 { return fmt.Errorf(i18n.G("No certificate provided to add")) } else if len(args) == 4 { var err error remote, _, err = conf.ParseRemote(args[2]) if err != nil { return err } } else { remote = conf.DefaultRemote } d, err := conf.GetContainerServer(remote) if err != nil { return err } fname := args[len(args)-1] x509Cert, err := shared.ReadCert(fname) if err != nil { return err } name, _ := shared.SplitExt(fname) cert := api.CertificatesPost{} cert.Certificate = base64.StdEncoding.EncodeToString(x509Cert.Raw) cert.Name = name cert.Type = "client" return d.CreateCertificate(cert) case "remove": var remote string if len(args) < 3 { return fmt.Errorf(i18n.G("No fingerprint specified.")) } else if len(args) == 4 { var err error remote, _, err = conf.ParseRemote(args[2]) if err != nil { return err } } else { remote = conf.DefaultRemote } d, err := conf.GetContainerServer(remote) if err != nil { return err } return d.DeleteCertificate(args[len(args)-1]) default: return errArgs } case "show": remote := conf.DefaultRemote container := "" if len(args) > 1 { var err error remote, container, err = conf.ParseRemote(args[1]) if err != nil { return err } } d, err := conf.GetContainerServer(remote) if err != nil { return err } var data []byte if len(args) == 1 || container == "" { server, _, err := d.GetServer() if err != nil { return err } brief := server.Writable() data, err = yaml.Marshal(&brief) if err != nil { return err } } else { var brief api.ContainerPut if shared.IsSnapshot(container) { fields := strings.Split(container, shared.SnapshotDelimiter) snap, _, err := d.GetContainerSnapshot(fields[0], fields[1]) if err != nil { return err } brief = api.ContainerPut{ Profiles: snap.Profiles, Config: snap.Config, Devices: snap.Devices, Ephemeral: snap.Ephemeral, } if c.expanded { brief = api.ContainerPut{ Profiles: snap.Profiles, Config: snap.ExpandedConfig, Devices: snap.ExpandedDevices, Ephemeral: snap.Ephemeral, } } } else { container, _, err := d.GetContainer(container) if err != nil { return err } brief = container.Writable() if c.expanded { brief.Config = container.ExpandedConfig brief.Devices = container.ExpandedDevices } } data, err = yaml.Marshal(&brief) if err != nil { return err } } fmt.Printf("%s", data) return nil case "get": if len(args) > 3 || len(args) < 2 { return errArgs } remote := conf.DefaultRemote container := "" key := args[1] if len(args) > 2 { var err error remote, container, err = conf.ParseRemote(args[1]) if err != nil { return err } key = args[2] } d, err := conf.GetContainerServer(remote) if err != nil { return err } if container != "" { resp, _, err := d.GetContainer(container) if err != nil { return err } fmt.Println(resp.Config[key]) } else { resp, _, err := d.GetServer() if err != nil { return err } value := resp.Config[key] if value == nil { value = "" } else if value == true { value = "true" } else if value == false { value = "false" } fmt.Println(value) } return nil case "profile": case "device": if len(args) < 2 { return errArgs } switch args[1] { case "list": return c.deviceList(conf, "container", args) case "add": return c.deviceAdd(conf, "container", args) case "remove": return c.deviceRm(conf, "container", args) case "get": return c.deviceGet(conf, "container", args) case "set": return c.deviceSet(conf, "container", args) case "unset": return c.deviceUnset(conf, "container", args) case "show": return c.deviceShow(conf, "container", args) default: return errArgs } case "edit": if len(args) < 1 { return errArgs } remote := conf.DefaultRemote container := "" if len(args) > 1 { var err error remote, container, err = conf.ParseRemote(args[1]) if err != nil { return err } } d, err := conf.GetContainerServer(remote) if err != nil { return err } if len(args) == 1 || container == "" { return c.doDaemonConfigEdit(d) } return c.doContainerConfigEdit(d, container) default: return errArgs } return errArgs } func (c *configCmd) doContainerConfigEdit(client lxd.ContainerServer, cont string) error { // If stdin isn't a terminal, read text from it if !termios.IsTerminal(int(syscall.Stdin)) { contents, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } newdata := api.ContainerPut{} err = yaml.Unmarshal(contents, &newdata) if err != nil { return err } op, err := client.UpdateContainer(cont, newdata, "") if err != nil { return err } return op.Wait() } // Extract the current value container, etag, err := client.GetContainer(cont) if err != nil { return err } brief := container.Writable() data, err := yaml.Marshal(&brief) if err != nil { return err } // Spawn the editor content, err := shared.TextEditor("", []byte(c.configEditHelp()+"\n\n"+string(data))) if err != nil { return err } for { // Parse the text received from the editor newdata := api.ContainerPut{} err = yaml.Unmarshal(content, &newdata) if err == nil { var op *lxd.Operation op, err = client.UpdateContainer(cont, newdata, etag) if err == nil { err = op.Wait() } } // Respawn the editor if err != nil { fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err) fmt.Println(i18n.G("Press enter to start the editor again")) _, err := os.Stdin.Read(make([]byte, 1)) if err != nil { return err } content, err = shared.TextEditor("", content) if err != nil { return err } continue } break } return nil } func (c *configCmd) doDaemonConfigEdit(client lxd.ContainerServer) error { // If stdin isn't a terminal, read text from it if !termios.IsTerminal(int(syscall.Stdin)) { contents, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } newdata := api.ServerPut{} err = yaml.Unmarshal(contents, &newdata) if err != nil { return err } return client.UpdateServer(newdata, "") } // Extract the current value server, etag, err := client.GetServer() if err != nil { return err } brief := server.Writable() data, err := yaml.Marshal(&brief) if err != nil { return err } // Spawn the editor content, err := shared.TextEditor("", []byte(c.configEditHelp()+"\n\n"+string(data))) if err != nil { return err } for { // Parse the text received from the editor newdata := api.ServerPut{} err = yaml.Unmarshal(content, &newdata) if err == nil { err = client.UpdateServer(newdata, etag) } // Respawn the editor if err != nil { fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err) fmt.Println(i18n.G("Press enter to start the editor again")) _, err := os.Stdin.Read(make([]byte, 1)) if err != nil { return err } content, err = shared.TextEditor("", content) if err != nil { return err } continue } break } return nil } func (c *configCmd) deviceAdd(conf *config.Config, which string, args []string) error { if len(args) < 5 { return errArgs } remote, name, err := conf.ParseRemote(args[2]) if err != nil { return err } client, err := conf.GetContainerServer(remote) if err != nil { return err } devname := args[3] device := map[string]string{} device["type"] = args[4] if len(args) > 5 { for _, prop := range args[5:] { results := strings.SplitN(prop, "=", 2) if len(results) != 2 { return fmt.Errorf("No value found in %q", prop) } k := results[0] v := results[1] device[k] = v } } if which == "profile" { profile, etag, err := client.GetProfile(name) if err != nil { return err } _, ok := profile.Devices[devname] if ok { return fmt.Errorf(i18n.G("The device already exists")) } profile.Devices[devname] = device err = client.UpdateProfile(name, profile.Writable(), etag) if err != nil { return err } } else { container, etag, err := client.GetContainer(name) if err != nil { return err } _, ok := container.Devices[devname] if ok { return fmt.Errorf(i18n.G("The device already exists")) } container.Devices[devname] = device op, err := client.UpdateContainer(name, container.Writable(), etag) if err != nil { return err } err = op.Wait() if err != nil { return err } } fmt.Printf(i18n.G("Device %s added to %s")+"\n", devname, name) return nil } func (c *configCmd) deviceGet(conf *config.Config, which string, args []string) error { if len(args) < 5 { return errArgs } remote, name, err := conf.ParseRemote(args[2]) if err != nil { return err } client, err := conf.GetContainerServer(remote) if err != nil { return err } devname := args[3] key := args[4] if which == "profile" { profile, _, err := client.GetProfile(name) if err != nil { return err } dev, ok := profile.Devices[devname] if !ok { return fmt.Errorf(i18n.G("The device doesn't exist")) } fmt.Println(dev[key]) } else { container, _, err := client.GetContainer(name) if err != nil { return err } dev, ok := container.Devices[devname] if !ok { return fmt.Errorf(i18n.G("The device doesn't exist")) } fmt.Println(dev[key]) } return nil } func (c *configCmd) deviceSet(conf *config.Config, which string, args []string) error { if len(args) < 6 { return errArgs } remote, name, err := conf.ParseRemote(args[2]) if err != nil { return err } client, err := conf.GetContainerServer(remote) if err != nil { return err } devname := args[3] key := args[4] value := args[5] if which == "profile" { profile, etag, err := client.GetProfile(name) if err != nil { return err } dev, ok := profile.Devices[devname] if !ok { return fmt.Errorf(i18n.G("The device doesn't exist")) } dev[key] = value profile.Devices[devname] = dev err = client.UpdateProfile(name, profile.Writable(), etag) if err != nil { return err } } else { container, etag, err := client.GetContainer(name) if err != nil { return err } dev, ok := container.Devices[devname] if !ok { return fmt.Errorf(i18n.G("The device doesn't exist")) } dev[key] = value container.Devices[devname] = dev op, err := client.UpdateContainer(name, container.Writable(), etag) if err != nil { return err } err = op.Wait() if err != nil { return err } } return nil } func (c *configCmd) deviceUnset(conf *config.Config, which string, args []string) error { if len(args) < 5 { return errArgs } remote, name, err := conf.ParseRemote(args[2]) if err != nil { return err } client, err := conf.GetContainerServer(remote) if err != nil { return err } devname := args[3] key := args[4] if which == "profile" { profile, etag, err := client.GetProfile(name) if err != nil { return err } dev, ok := profile.Devices[devname] if !ok { return fmt.Errorf(i18n.G("The device doesn't exist")) } delete(dev, key) profile.Devices[devname] = dev err = client.UpdateProfile(name, profile.Writable(), etag) if err != nil { return err } } else { container, etag, err := client.GetContainer(name) if err != nil { return err } dev, ok := container.Devices[devname] if !ok { return fmt.Errorf(i18n.G("The device doesn't exist")) } delete(dev, key) container.Devices[devname] = dev op, err := client.UpdateContainer(name, container.Writable(), etag) if err != nil { return err } err = op.Wait() if err != nil { return err } } return nil } func (c *configCmd) deviceRm(conf *config.Config, which string, args []string) error { if len(args) < 4 { return errArgs } remote, name, err := conf.ParseRemote(args[2]) if err != nil { return err } client, err := conf.GetContainerServer(remote) if err != nil { return err } if which == "profile" { profile, etag, err := client.GetProfile(name) if err != nil { return err } for _, devname := range args[3:] { _, ok := profile.Devices[devname] if !ok { return fmt.Errorf(i18n.G("The device doesn't exist")) } delete(profile.Devices, devname) } err = client.UpdateProfile(name, profile.Writable(), etag) if err != nil { return err } } else { container, etag, err := client.GetContainer(name) if err != nil { return err } for _, devname := range args[3:] { _, ok := container.Devices[devname] if !ok { return fmt.Errorf(i18n.G("The device doesn't exist")) } delete(container.Devices, devname) } op, err := client.UpdateContainer(name, container.Writable(), etag) if err != nil { return err } err = op.Wait() if err != nil { return err } } fmt.Printf(i18n.G("Device %s removed from %s")+"\n", strings.Join(args[3:], ", "), name) return nil } func (c *configCmd) deviceList(conf *config.Config, which string, args []string) error { if len(args) < 3 { return errArgs } remote, name, err := conf.ParseRemote(args[2]) if err != nil { return err } client, err := conf.GetContainerServer(remote) if err != nil { return err } var devices []string if which == "profile" { profile, _, err := client.GetProfile(name) if err != nil { return err } for k := range profile.Devices { devices = append(devices, k) } } else { container, _, err := client.GetContainer(name) if err != nil { return err } for k := range container.Devices { devices = append(devices, k) } } fmt.Printf("%s\n", strings.Join(devices, "\n")) return nil } func (c *configCmd) deviceShow(conf *config.Config, which string, args []string) error { if len(args) < 3 { return errArgs } remote, name, err := conf.ParseRemote(args[2]) if err != nil { return err } client, err := conf.GetContainerServer(remote) if err != nil { return err } var devices map[string]map[string]string if which == "profile" { profile, _, err := client.GetProfile(name) if err != nil { return err } devices = profile.Devices } else { container, _, err := client.GetContainer(name) if err != nil { return err } devices = container.Devices } data, err := yaml.Marshal(&devices) if err != nil { return err } fmt.Printf(string(data)) return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/lxc/action.go����������������������������������������������������������������������������0000644�0610621�0607500�00000006341�13172163242�016067� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "strings" "github.com/lxc/lxd/lxc/config" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/gnuflag" "github.com/lxc/lxd/shared/i18n" ) type actionCmd struct { action shared.ContainerAction description string hasTimeout bool visible bool name string timeout int force bool stateful bool stateless bool } func (c *actionCmd) showByDefault() bool { return c.visible } func (c *actionCmd) usage() string { extra := "" if c.name == "pause" { extra = "\n" + i18n.G("The opposite of \"lxc pause\" is \"lxc start\".") } return fmt.Sprintf(i18n.G( `Usage: lxc %s [<remote>:]<container> [[<remote>:]<container>...] %s%s`), c.name, c.description, extra) } func (c *actionCmd) flags() { if c.hasTimeout { gnuflag.IntVar(&c.timeout, "timeout", -1, i18n.G("Time to wait for the container before killing it")) gnuflag.BoolVar(&c.force, "f", false, i18n.G("Force the container to shutdown")) gnuflag.BoolVar(&c.force, "force", false, i18n.G("Force the container to shutdown")) } gnuflag.BoolVar(&c.stateful, "stateful", false, i18n.G("Store the container state (only for stop)")) gnuflag.BoolVar(&c.stateless, "stateless", false, i18n.G("Ignore the container state (only for start)")) } func (c *actionCmd) doAction(conf *config.Config, nameArg string) error { state := false // Only store state if asked to if c.action == "stop" && c.stateful { state = true } remote, name, err := conf.ParseRemote(nameArg) if err != nil { return err } d, err := conf.GetContainerServer(remote) if err != nil { return err } if name == "" { return fmt.Errorf(i18n.G("Must supply container name for: ")+"\"%s\"", nameArg) } if c.action == shared.Start { current, _, err := d.GetContainer(name) if err != nil { return err } // "start" for a frozen container means "unfreeze" if current.StatusCode == api.Frozen { c.action = shared.Unfreeze } // Always restore state (if present) unless asked not to if c.action == shared.Start && current.Stateful && !c.stateless { state = true } } req := api.ContainerStatePut{ Action: string(c.action), Timeout: c.timeout, Force: c.force, Stateful: state, } op, err := d.UpdateContainerState(name, req, "") if err != nil { return err } err = op.Wait() if err != nil { return fmt.Errorf("%s\n"+i18n.G("Try `lxc info --show-log %s` for more info"), err, nameArg) } return nil } func (c *actionCmd) run(conf *config.Config, args []string) error { if len(args) == 0 { return errArgs } // Run the action for every listed container results := runBatch(args, func(name string) error { return c.doAction(conf, name) }) // Single container is easy if len(results) == 1 { return results[0].err } // Do fancier rendering for batches success := true for _, result := range results { if result.err == nil { continue } success = false msg := fmt.Sprintf(i18n.G("error: %v"), result.err) for _, line := range strings.Split(msg, "\n") { fmt.Fprintln(os.Stderr, fmt.Sprintf("%s: %s", result.name, line)) } } if !success { fmt.Fprintln(os.Stderr, "") return fmt.Errorf(i18n.G("Some containers failed to %s"), c.name) } return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/fuidshift/�������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015456� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/fuidshift/main.go������������������������������������������������������������������������0000644�0610621�0607500�00000003157�13172163242�016737� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package main import ( "fmt" "os" "github.com/lxc/lxd/shared/idmap" ) func help(me string, status int) { fmt.Printf("Usage: %s directory [-t] [-r] <range1> [<range2> ...]\n", me) fmt.Printf(" -t implies test mode. No file ownerships will be changed.\n") fmt.Printf(" -r means reverse, that is shift the uids out of the container.\n") fmt.Printf("\n") fmt.Printf(" A range is [u|b|g]:<first_container_id:first_host_id:range>.\n") fmt.Printf(" where u means shift uids, g means shift gids, b means shift both.\n") fmt.Printf(" For example: %s directory b:0:100000:65536 u:10000:1000:1\n", me) os.Exit(status) } func main() { if err := run(); err != nil { fmt.Printf("Error: %q\n", err) help(os.Args[0], 1) } } func run() error { if len(os.Args) < 3 { if len(os.Args) > 1 && (os.Args[1] == "-h" || os.Args[1] == "--help" || os.Args[1] == "help") { help(os.Args[0], 0) } else { help(os.Args[0], 1) } } directory := os.Args[1] idmapSet := idmap.IdmapSet{} testmode := false reverse := false for pos := 2; pos < len(os.Args); pos++ { switch os.Args[pos] { case "-r", "--reverse": reverse = true case "t", "-t", "--test", "test": testmode = true default: var err error idmapSet, err = idmapSet.Append(os.Args[pos]) if err != nil { return err } } } if idmapSet.Len() == 0 { fmt.Printf("No idmaps given\n") help(os.Args[0], 1) } if !testmode && os.Geteuid() != 0 { fmt.Printf("This must be run as root\n") os.Exit(1) } if reverse { return idmapSet.UidshiftFromContainer(directory, testmode) } return idmapSet.UidshiftIntoContainer(directory, testmode) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/fuidshift/Makefile�����������������������������������������������������������������������0000644�0610621�0607500�00000000151�13172163242�017113� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# we let go build figure out dependency changes .PHONY: fuidmap lxc: go build clean: -rm -f fuidshift �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/�������������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014236� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/userns-idmap.md����������������������������������������������������������������������0000644�0610621�0607500�00000007032�13172163242�017171� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction LXD runs safe containers. This is achieved mostly through the use of user namespaces which make it possible to run containers unprivileged, greatly limiting the attack surface. User namespaces work by mapping a set of uids and gids on the host to a set of uids and gids in the container. For example, we can define that the host uids and gids from 100000 to 165535 may be used by LXD and should be mapped to uid/gid 0 through 65535 in the container. As a result a process running as uid 0 in the container will actually be running as uid 100000. Allocations should always be of at least 65536 uids and gids to cover the POSIX range including root (0) and nobody (65534). # Kernel support User namespaces require a kernel >= 3.12, LXD will start even on older kernels but will refuse to start containers. # Allowed ranges On most hosts, LXD will check `/etc/subuid` and `/etc/subgid` for allocations for the "lxd" user and on first start, set the default profile to use the first 65536 uids and gids from that range. If the range is shorter than 65536 (which includes no range at all), then LXD will fail to create or start any container until this is corrected. If some but not all of `/etc/subuid`, `/etc/subgid`, `newuidmap` (path lookup) and `newgidmap` (path lookup) can be found on the system, LXD will fail the startup of any container until this is corrected as this shows a broken shadow setup. If none of those 4 files can be found, then LXD will assume it's running on a host using an old version of shadow. In this mode, LXD will assume it can use any uids and gids above 65535 and will take the first 65536 as its default map. # Varying ranges between hosts The source map is sent when moving containers between hosts so that they can be remapped on the receiving host. # Different idmaps per container LXD supports using different idmaps per container, to further isolate containers from each other. This is controlled with two per-container configuration keys, `security.idmap.isolated` and `security.idmap.size`. Containers with `security.idmap.isolated` will have a unique id range computed for them among the other containers with `security.idmap.isolated` set (if none is available, setting this key will simply fail). Containers with `security.idmap.size` set will have their id range set to this size. Isolated containers without this property set default to a id range of size 65536; this allows for POSIX compliance and a "nobody" user inside the container. To select a specific map, the `security.idmap.base` key will let you override the auto-detection mechanism and tell LXD what host uid/gid you want to use as the base for the container. These properties require a container reboot to take effect. # Custom idmaps LXD also supports customizing bits of the idmap, e.g. to allow users to bind mount parts of the host's filesystem into a container without the need for any uid-shifting filesystem. The per-container configuration key for this is `raw.idmap`, and looks like: both 1000 1000 uid 50-60 500-510 gid 10000-110000 10000-20000 The first line configures both the uid and gid 1000 on the host to map to uid 1000 inside the container (this can be used for example to bind mount a user's home directory into a container). The second and third lines map only the uid or gid ranges into the container, respectively. The second entry per line is the source id, i.e. the id on the host, and the third entry is the range inside the container. These ranges must be the same size. This property requires a container reboot to take effect. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/storage-backends.md������������������������������������������������������������������0000644�0610621�0607500�00000014141�13172163242�017775� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Storage Backends and supported functions ## Feature comparison LXD supports using plain dirs, Btrfs, LVM, and ZFS for storage of images and containers. Where possible, LXD tries to use the advanced features of each system to optimize operations. Feature | Directory | Btrfs | LVM | ZFS :--- | :--- | :--- | :--- | :--- Optimized image storage | no | yes | yes | yes Optimized container creation | no | yes | yes | yes Optimized snapshot creation | no | yes | yes | yes Optimized image transfer | no | yes | no | yes Optimized container transfer | no | yes | no | yes Copy on write | no | yes | yes | yes Block based | no | no | yes | no Instant cloning | no | yes | yes | yes Nesting support | yes | yes | no | no Restore from older snapshots (not latest) | yes | yes | yes | no Storage quotas | no | yes | no | yes ## Mixed storage When switching storage backend after some containers or images already exist, LXD will create any new container using the new backend and converting older images to the new backend as needed. ## Non-optimized container transfer When the filesystem on the source and target hosts differs or when there is no faster way, rsync is used to transfer the container content across. ## I/O limits I/O limits in IOp/s or MB/s can be set on storage devices when attached to a container (see [Containers](containers.md)). Those are applied through the Linux `blkio` cgroup controller which makes it possible to restrict I/O at the disk level (but nothing finer grained than that). Because those apply to a whole physical disk rather than a partition or path, the following restrictions apply: - Limits will not apply to filesystems that are backed by virtual devices (e.g. device mapper). - If a fileystem is backed by multiple block devices, each device will get the same limit. - If the container is passed two disk devices that are each backed by the same disk, the limits of the two devices will be averaged. It's also worth noting that all I/O limits only apply to actual block device access, so you will need to consider the filesystem's own overhead when setting limits. This also means that access to cached data will not be affected by the limit. ## Notes ### Directory - The directory backend is the fallback backend when nothing else is configured or detected. - While this backend is fully functional, it's also much slower than all the others due to it having to unpack images or do instant copies of containers, snapshots and images. ### Btrfs - The btrfs backend is automatically used if /var/lib/lxd is on a btrfs filesystem. - Uses a subvolume per container, image and snapshot, creating btrfs snapshots when creating a new object. - When using for nesting, the host btrfs filesystem must be mounted with the `user_subvol_rm_allowed` mount option. - btrfs supports storage quotas via qgroups. While btrfs qgroups are hierarchical, new subvolumes will not automatically be added to the qgroups of their parent subvolumes. This means that users can trivially escape any quotas that are set. If adherence to strict quotas is a necessity users should be mindful of this and maybe consider using a zfs storage pool with refquotas. ### LVM - A LVM VG must be created and then `storage.lvm_vg_name` set to point to it. - If a thinpool doesn't already exist, one will be created, the name of the thinpool can be set with `storage.lvm_thinpool_name` . - Uses LVs for images, then LV snapshots for containers and container snapshots. - The filesystem used for the LVs is ext4 (can be configured to use xfs instead). - LVs are created with a default size of 10GiB (can be configured through). ### ZFS - LXD can use any zpool or part of a zpool. `storage.zfs_pool_name` must be set to the path to be used. - ZFS doesn't have to (and shouldn't be) mounted on `/var/lib/lxd` - Uses ZFS filesystems for images, then snapshots and clones to create containers and snapshots. - Due to the way copy-on-write works in ZFS, parent filesystems can't be removed until all children are gone. As a result, LXD will automatically rename any removed but still referenced object to a random deleted/ path and keep it until such time the references are gone and it can safely be removed. - ZFS as it is today doesn't support delegating part of a pool to a container user. Upstream is actively working on this. - ZFS doesn't support restoring from snapshots other than the latest one. You can however create new containers from older snapshots which makes it possible to confirm the snapshots is indeed what you want to restore before you remove the newer snapshots. Also note that container copies use ZFS snapshots, so you also cannot restore a container to a snapshot taken before the last copy without having to also delete container copies. Copying the wanted snapshot into a new container and then deleting the old container does however work, at the cost of losing any other snapshot the container may have had. - Note that LXD will assume it has full control over the zfs pool or dataset. It is recommended to not maintain any non-LXD owned filesystem entities in a LXD zfs pool or dataset since LXD might delete them. - I/O quotas (IOps/MBs) are unlikely to affect ZFS filesystems very much. That's because of ZFS being a port of a Solaris module (using SPL) and not a native Linux filesystem using the Linux VFS API which is where I/O limits are applied. #### Growing a loop backed ZFS pool LXD doesn't let you directly grow a loop backed ZFS pool, but you can do so with: ```bash sudo truncate -s +5G /var/lib/lxd/zfs.img sudo zpool set autoexpand=on lxd sudo zpool online -e lxd /var/lib/lxd/zfs.img sudo zpool set autoexpand=off lxd ``` �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/server.md����������������������������������������������������������������������������0000644�0610621�0607500�00000005774�13172163242�016103� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Server configuration The key/value configuration is namespaced with the following namespaces currently supported: - `core` (core daemon configuration) - `images` (image configuration) - `storage` (storage configuration) Key | Type | Default | Description :-- | :--- | :------ | :---------- core.https\_address | string | - | Address to bind for the remote API core.https\_allowed\_headers | string | - | Access-Control-Allow-Headers http header value core.https\_allowed\_methods | string | - | Access-Control-Allow-Methods http header value core.https\_allowed\_origin | string | - | Access-Control-Allow-Origin http header value core.proxy\_https | string | - | https proxy to use, if any (falls back to HTTPS\_PROXY environment variable) core.proxy\_http | string | - | http proxy to use, if any (falls back to HTTP\_PROXY environment variable) core.proxy\_ignore\_hosts | string | - | hosts which don't need the proxy for use (similar format to NO\_PROXY, e.g. 1.2.3.4,1.2.3.5, falls back to NO\_PROXY environment variable) core.trust\_password | string | - | Password to be provided by clients to setup a trust images.auto\_update\_cached | boolean | true | Whether to automatically update any image that LXD caches images.auto\_update\_interval | integer | 6 | Interval in hours at which to look for update to cached images (0 disables it) images.compression\_algorithm | string | gzip | Compression algorithm to use for new images (bzip2, gzip, lzma, xz or none) images.remote\_cache\_expiry | integer | 10 | Number of days after which an unused cached remote image will be flushed storage.lvm\_fstype | string | ext4 | Format LV with filesystem, for now it's value can be only ext4 (default) or xfs. storage.lvm\_thinpool\_name | string | "LXDPool" | LVM Thin Pool to use within the Volume Group specified in `storage.lvm_vg_name`, if the default pool parameters are undesirable. storage.lvm\_vg\_name | string | - | LVM Volume Group name to be used for container and image storage. A default Thin Pool is created using 100% of the free space in the Volume Group, unless `storage.lvm_thinpool_name` is set. storage.lvm\_volume\_size | string | 10GiB | Size of the logical volume storage.zfs\_pool\_name | string | - | ZFS pool name Those keys can be set using the lxc tool with: ```bash lxc config set <key> <value> ``` ����lxd-2.0.11/doc/security.md��������������������������������������������������������������������������0000644�0610621�0607500�00000010202�13172163242�016422� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction Local communications over the UNIX socket happen over a cleartext HTTP socket and access is restricted by socket ownership and mode. Remote communications with the LXD daemon happen using JSON over HTTPS. The supported protocol must be TLS1.2 or better. All communications must use perfect forward secrecy and ciphers must be limited to strong elliptic curve ones (such as ECDHE-RSA or ECDHE-ECDSA). Any generated key should be at least 4096bit RSA and when using signatures, only SHA-2 signatures should be trusted. Since we control both client and server, there is no reason to support any backward compatibility to broken protocol or ciphers. Both the client and the server will generate a keypair the first time they're launched. The server will use that for all https connections to the LXD socket and the client will use its certificate as a client certificate for any client-server communication. To cause certificates to be regenerated, simply remove the old ones. On the next connection a new certificate will be generated. # Adding a remote with a default setup In the default setup, when the user adds a new server with `lxc remote add`, the server will be contacted over HTTPs, its certificate downloaded and the fingerprint will be shown to the user. The user will then be asked to confirm that this is indeed the server's fingerprint which they can manually check by connecting to or asking someone with access to the server to run the status command and compare the fingerprints. After that, the user must enter the trust password for that server, if it matches, the client certificate is added to the server's trust store and the client can now connect to the server without having to provide any additional credentials. This is a workflow that's very similar to that of ssh where an initial connection to an unknown server triggers a prompt. A possible extension to that is to support something similar to ssh's fingerprint in DNS feature where the certificate fingerprint is added as a TXT record, then if the domain is signed by DNSSEC, the client will automatically accept the fingerprint if it matches that in the DNS record. # Managing trusted clients The list of certificates trusted by a LXD server can be obtained with `lxc config trust list`. To revoke trust to a client its certificate can be removed with `lxc config trust remove FINGERPRINT`. # Password prompt To establish a new trust relationship, a password must be set on the server and send by the client when adding itself. A remote add operation should therefore go like this: 1. Call GET /1.0 2. Ask the user to confirm the fingerprint. 3. Look at the dict we received back from the server. If "auth" is "untrusted", ask the user for the server's password and do a `POST` to `/1.0/certificates`, then call `/1.0` again to check that we're indeed trusted. 4. Remote is now ready # Failure scenarios ## Server certificate changes This will typically happen in two cases: * The server was fully reinstalled and so changed certificate * The connection is being intercepted (MITM) In such cases the client will refuse to connect to the server since the certificate fringerprint will not match that in the config for this remote. It is then up to the user to contact the server administrator to check if the certificate did in fact change. If it did, then the certificate can be replaced by the new one or the remote be removed altogether and re-added. ## Server trust relationship revoked In this case, the server still uses the same certificate but all API calls return a 403 with an error indicating that the client isn't trusted. This happens if another trusted client or the local server administrator removed the trust entry on the server. # Production setup For production setup, it's recommended that `core.trust_password` is unset after all clients have been added. This prevents brute-force attacks trying to guess the password. Furthermore, `core.https_address` should be set to the single address where the server should be available (rather than any address on the host), and firewall rules should be set to only allow access to the LXD port from authorized hosts/subnets. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/rest-api.md��������������������������������������������������������������������������0000644�0610621�0607500�00000154271�13172163242�016316� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction All the communications between LXD and its clients happen using a RESTful API over http which is then encapsulated over either SSL for remote operations or a unix socket for local operations. Not all of the REST interface requires authentication: * `GET` to `/` is allowed for everyone (lists the API endpoints) * `GET` to `/1.0` is allowed for everyone (but result varies) * `POST` to `/1.0/certificates` is allowed for everyone with a client certificate * `GET` to `/1.0/images/*` is allowed for everyone but only returns public images for unauthenticated users Unauthenticated endpoints are clearly identified as such below. # API versioning The list of supported major API versions can be retrieved using `GET /`. The reason for a major API bump is if the API breaks backward compatibility. Feature additions done without breaking backward compatibility only result in addition to `api_extensions` which can be used by the client to check if a given feature is supported by the server. # Return values There are three standard return types: * Standard return value * Background operation * Error ### Standard return value For a standard synchronous operation, the following dict is returned: { "type": "sync", "status": "Success", "status_code": 200, "metadata": {} # Extra resource/action specific metadata } HTTP code must be 200. ### Background operation When a request results in a background operation, the HTTP code is set to 202 (Accepted) and the Location HTTP header is set to the operation URL. The body is a dict with the following structure: { "type": "async", "status": "OK", "status_code": 100, "operation": "/1.0/containers/<id>", # URL to the background operation "metadata": {} # Operation metadata (see below) } The operation metadata structure looks like: { "id": "a40f5541-5e98-454f-b3b6-8a51ef5dbd3c", # UUID of the operation "class": "websocket", # Class of the operation (task, websocket or token) "created_at": "2015-11-17T22:32:02.226176091-05:00", # When the operation was created "updated_at": "2015-11-17T22:32:02.226176091-05:00", # Last time the operation was updated "status": "Running", # String version of the operation's status "status_code": 103, # Integer version of the operation's status (use this rather than status) "resources": { # Dictionary of resource types (container, snapshots, images) and affected resources "containers": [ "/1.0/containers/test" ] }, "metadata": { # Metadata specific to the operation in question (in this case, exec) "fds": { "0": "2a4a97af81529f6608dca31f03a7b7e47acc0b8dc6514496eb25e325f9e4fa6a", "control": "5b64c661ef313b423b5317ba9cb6410e40b705806c28255f601c0ef603f079a7" } }, "may_cancel": false, # Whether the operation can be canceled (DELETE over REST) "err": "" # The error string should the operation have failed } The body is mostly provided as a user friendly way of seeing what's going on without having to pull the target operation, all information in the body can also be retrieved from the background operation URL. ### Error There are various situations in which something may immediately go wrong, in those cases, the following return value is used: { "type": "error", "error": "Failure", "error_code": 400, "metadata": {} # More details about the error } HTTP code must be one of of 400, 401, 403, 404, 409, 412 or 500. # Status codes The LXD REST API often has to return status information, be that the reason for an error, the current state of an operation or the state of the various resources it exports. To make it simple to debug, all of those are always doubled. There is a numeric representation of the state which is guaranteed never to change and can be relied on by API clients. Then there is a text version meant to make it easier for people manually using the API to figure out what's happening. In most cases, those will be called status and `status_code`, the former being the user-friendly string representation and the latter the fixed numeric value. The codes are always 3 digits, with the following ranges: * 100 to 199: resource state (started, stopped, ready, ...) * 200 to 399: positive action result * 400 to 599: negative action result * 600 to 999: future use ## List of current status codes Code | Meaning :--- | :------ 100 | Operation created 101 | Started 102 | Stopped 103 | Running 104 | Cancelling 105 | Pending 106 | Starting 107 | Stopping 108 | Aborting 109 | Freezing 110 | Frozen 111 | Thawed 200 | Success 400 | Failure 401 | Cancelled # Recursion To optimize queries of large lists, recursion is implemented for collections. A `recursion` argument can be passed to a GET query against a collection. The default value is 0 which means that collection member URLs are returned. Setting it to 1 will have those URLs be replaced by the object they point to (typically a dict). Recursion is implemented by simply replacing any pointer to an job (URL) by the object itself. # Async operations Any operation which may take more than a second to be done must be done in the background, returning a background operation ID to the client. The client will then be able to either poll for a status update or wait for a notification using the long-poll API. # Notifications A websocket based API is available for notifications, different notification types exist to limit the traffic going to the client. It's recommended that the client always subscribes to the operations notification type before triggering remote operations so that it doesn't have to then poll for their status. # API structure * `/` * `/1.0` * `/1.0/certificates` * `/1.0/certificates/<fingerprint>` * `/1.0/containers` * `/1.0/containers/<name>` * `/1.0/containers/<name>/exec` * `/1.0/containers/<name>/files` * `/1.0/containers/<name>/snapshots` * `/1.0/containers/<name>/snapshots/<name>` * `/1.0/containers/<name>/state` * `/1.0/containers/<name>/logs` * `/1.0/containers/<name>/logs/<logfile>` * `/1.0/events` * `/1.0/images` * `/1.0/images/<fingerprint>` * `/1.0/images/<fingerprint>/export` * `/1.0/images/aliases` * `/1.0/images/aliases/<name>` * `/1.0/networks` * `/1.0/networks/<name>` * `/1.0/operations` * `/1.0/operations/<uuid>` * `/1.0/operations/<uuid>/wait` * `/1.0/operations/<uuid>/websocket` * `/1.0/profiles` * `/1.0/profiles/<name>` # API details ## `/` ### GET * Description: List of supported APIs * Authentication: guest * Operation: sync * Return: list of supported API endpoint URLs Return value: [ "/1.0" ] ## `/1.0/` ### GET * Description: Server configuration and environment information * Authentication: guest, untrusted or trusted * Operation: sync * Return: Dict representing server state Return value (if trusted): { "api_extensions": [], # List of API extensions added after the API was marked stable "api_status": "stable", # API implementation status (one of, development, stable or deprecated) "api_version": "1.0", # The API version as a string "auth": "trusted", # Authentication state, one of "guest", "untrusted" or "trusted" "config": { # Host configuration "core.trust_password": true, "core.https_address": "[::]:8443" }, "environment": { # Various information about the host (OS, kernel, ...) "addresses": [ "1.2.3.4:8443", "[1234::1234]:8443" ], "architectures": [ "x86_64", "i686" ], "certificate": "PEM certificate", "driver": "lxc", "driver_version": "1.0.6", "kernel": "Linux", "kernel_architecture": "x86_64", "kernel_version": "3.16", "server": "lxd", "server_pid": 10224, "server_version": "0.8.1"} "storage": "btrfs", "storage_version": "3.19", }, "public": false, # Whether the server should be treated as a public (read-only) remote by the client } Return value (if guest or untrusted): { "api_extensions": [], # List of API extensions added after the API was marked stable "api_status": "stable", # API implementation status (one of, development, stable or deprecated) "api_version": "1.0", # The API version as a string "auth": "guest", # Authentication state, one of "guest", "untrusted" or "trusted" "public": false, # Whether the server should be treated as a public (read-only) remote by the client } ### PUT * Description: Updates the server configuration or other properties * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input (replaces any existing config with the provided one): { "config": { "core.trust_password": "my-new-password", "storage.zfs_pool_name": "lxd" } } ## `/1.0/certificates` ### GET * Description: list of trusted certificates * Authentication: trusted * Operation: sync * Return: list of URLs for trusted certificates Return: [ "/1.0/certificates/3ee64be3c3c7d617a7470e14f2d847081ad467c8c26e1caad841c8f67f7c7b09" ] ### POST * Description: add a new trusted certificate * Authentication: trusted or untrusted * Operation: sync * Return: standard return value or standard error Input: { "type": "client", # Certificate type (keyring), currently only client "certificate": "PEM certificate", # If provided, a valid x509 certificate. If not, the client certificate of the connection will be used "name": "foo", # An optional name for the certificate. If nothing is provided, the host in the TLS header for the request is used. "password": "server-trust-password" # The trust password for that server (only required if untrusted) } ## `/1.0/certificates/<fingerprint>` ### GET * Description: trusted certificate information * Authentication: trusted * Operation: sync * Return: dict representing a trusted certificate Output: { "type": "client", "certificate": "PEM certificate", "name": "foo", "fingerprint": "SHA256 Hash of the raw certificate" } ### DELETE * Description: Remove a trusted certificate * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input (none at present): { } HTTP code for this should be 202 (Accepted). ## `/1.0/containers` ### GET * Description: List of containers * Authentication: trusted * Operation: sync * Return: list of URLs for containers this server publishes Return value: [ "/1.0/containers/blah", "/1.0/containers/blah1" ] ### POST * Description: Create a new container * Authentication: trusted * Operation: async * Return: background operation or standard error Input (container based on a local image with the "ubuntu/devel" alias): { "name": "my-new-container", # 64 chars max, ASCII, no slash, no colon and no comma "architecture": "x86_64", "profiles": ["default"], # List of profiles "ephemeral": true, # Whether to destroy the container on shutdown "config": {"limits.cpu": "2"}, # Config override. "devices": { # optional list of devices the container should have "kvm": { "path": "/dev/kvm", "type": "unix-char" }, }, "instance_type": "c2.micro", # An optional instance type to use as basis for limits "source": {"type": "image", # Can be: "image", "migration", "copy" or "none" "alias": "ubuntu/devel"}, # Name of the alias } Input (container based on a local image identified by its fingerprint): { "name": "my-new-container", # 64 chars max, ASCII, no slash, no colon and no comma "architecture": "x86_64", "profiles": ["default"], # List of profiles "ephemeral": true, # Whether to destroy the container on shutdown "config": {"limits.cpu": "2"}, # Config override. "devices": { # optional list of devices the container should have "kvm": { "path": "/dev/kvm", "type": "unix-char" }, }, "source": {"type": "image", # Can be: "image", "migration", "copy" or "none" "fingerprint": "SHA-256"}, # Fingerprint } Input (container based on most recent match based on image properties): { "name": "my-new-container", # 64 chars max, ASCII, no slash, no colon and no comma "architecture": "x86_64", "profiles": ["default"], # List of profiles "ephemeral": true, # Whether to destroy the container on shutdown "config": {"limits.cpu": "2"}, # Config override. "devices": { # optional list of devices the container should have "kvm": { "path": "/dev/kvm", "type": "unix-char" }, }, "source": {"type": "image", # Can be: "image", "migration", "copy" or "none" "properties": { # Properties "os": "ubuntu", "release": "14.04", "architecture": "x86_64" }}, } Input (container without a pre-populated rootfs, useful when attaching to an existing one): { "name": "my-new-container", # 64 chars max, ASCII, no slash, no colon and no comma "architecture": "x86_64", "profiles": ["default"], # List of profiles "ephemeral": true, # Whether to destroy the container on shutdown "config": {"limits.cpu": "2"}, # Config override. "devices": { # optional list of devices the container should have "kvm": { "path": "/dev/kvm", "type": "unix-char" }, }, "source": {"type": "none"}, # Can be: "image", "migration", "copy" or "none" } Input (using a public remote image): { "name": "my-new-container", # 64 chars max, ASCII, no slash, no colon and no comma "architecture": "x86_64", "profiles": ["default"], # List of profiles "ephemeral": true, # Whether to destroy the container on shutdown "config": {"limits.cpu": "2"}, # Config override. "devices": { # optional list of devices the container should have "kvm": { "path": "/dev/kvm", "type": "unix-char" }, }, "source": {"type": "image", # Can be: "image", "migration", "copy" or "none" "mode": "pull", # One of "local" (default) or "pull" "server": "https://10.0.2.3:8443", # Remote server (pull mode only) "protocol": "lxd", # Protocol (one of lxd or simplestreams, defaults to lxd) "certificate": "PEM certificate", # Optional PEM certificate. If not mentioned, system CA is used. "alias": "ubuntu/devel"}, # Name of the alias } Input (using a private remote image after having obtained a secret for that image): { "name": "my-new-container", # 64 chars max, ASCII, no slash, no colon and no comma "architecture": "x86_64", "profiles": ["default"], # List of profiles "ephemeral": true, # Whether to destroy the container on shutdown "config": {"limits.cpu": "2"}, # Config override. "devices": { # optional list of devices the container should have "kvm": { "path": "/dev/kvm", "type": "unix-char" }, }, "source": {"type": "image", # Can be: "image", "migration", "copy" or "none" "mode": "pull", # One of "local" (default) or "pull" "server": "https://10.0.2.3:8443", # Remote server (pull mode only) "secret": "my-secret-string", # Secret to use to retrieve the image (pull mode only) "certificate": "PEM certificate", # Optional PEM certificate. If not mentioned, system CA is used. "alias": "ubuntu/devel"}, # Name of the alias } Input (using a remote container, sent over the migration websocket): { "name": "my-new-container", # 64 chars max, ASCII, no slash, no colon and no comma "architecture": "x86_64", "profiles": ["default"], # List of profiles "ephemeral": true, # Whether to destroy the container on shutdown "config": {"limits.cpu": "2"}, # Config override. "devices": { # optional list of devices the container should have "kvm": { "path": "/dev/kvm", "type": "unix-char" }, }, "source": {"type": "migration", # Can be: "image", "migration", "copy" or "none" "mode": "pull", # Only "pull" is supported for now "operation": "https://10.0.2.3:8443/1.0/operations/<UUID>", # Full URL to the remote operation (pull mode only) "certificate": "PEM certificate", # Optional PEM certificate. If not mentioned, system CA is used. "base-image": "<fingerprint>", # Optional, the base image the container was created from "secrets": {"control": "my-secret-string", # Secrets to use when talking to the migration source "criu": "my-other-secret", "fs": "my third secret"} } Input (using a local container): { "name": "my-new-container", # 64 chars max, ASCII, no slash, no colon and no comma "profiles": ["default"], # List of profiles "ephemeral": true, # Whether to destroy the container on shutdown "config": {"limits.cpu": "2"}, # Config override. "devices": { # optional list of devices the container should have "kvm": { "path": "/dev/kvm", "type": "unix-char" }, }, "source": {"type": "copy", # Can be: "image", "migration", "copy" or "none" "source": "my-old-container"} # Name of the source container } ## `/1.0/containers/<name>` ### GET * Description: Container information * Authentication: trusted * Operation: sync * Return: dict of the container configuration and current state. Output: { "architecture": "x86_64", "config": { "limits.cpu": "3", "volatile.base_image": "97d97a3d1d053840ca19c86cdd0596cf1be060c5157d31407f2a4f9f350c78cc", "volatile.eth0.hwaddr": "00:16:3e:1c:94:38" }, "created_at": "2016-02-16T01:05:05Z", "devices": { "rootfs": { "path": "/", "type": "disk" } }, "ephemeral": false, "expanded_config": { # the result of expanding profiles and adding the container's local config "limits.cpu": "3", "volatile.base_image": "97d97a3d1d053840ca19c86cdd0596cf1be060c5157d31407f2a4f9f350c78cc", "volatile.eth0.hwaddr": "00:16:3e:1c:94:38" }, "expanded_devices": { # the result of expanding profiles and adding the container's local devices "eth0": { "name": "eth0", "nictype": "bridged", "parent": "lxdbr0", "type": "nic" }, "root": { "path": "/", "type": "disk" } }, "name": "my-container", "profiles": [ "default" ], "stateful": false, # If true, indicates that the container has some stored state that can be restored on startup "status": "Running", "status_code": 103 } ### PUT * Description: update container configuration or restore snapshot * Authentication: trusted * Operation: async * Return: background operation or standard error Input (update container configuration): { "architecture": "x86_64", "config": { "limits.cpu": "4", "volatile.base_image": "97d97a3d1d053840ca19c86cdd0596cf1be060c5157d31407f2a4f9f350c78cc", "volatile.eth0.hwaddr": "00:16:3e:1c:94:38" }, "devices": { "rootfs": { "path": "/", "type": "disk" } }, "ephemeral": true, "profiles": [ "default" ] } Takes the same structure as that returned by GET but doesn't allow name changes (see POST below) or changes to the status sub-dict (since that's read-only). Input (restore snapshot): { "restore": "snapshot-name" } ### POST * Description: used to rename/migrate the container * Authentication: trusted * Operation: async * Return: background operation or standard error Renaming to an existing name must return the 409 (Conflict) HTTP code. Input (simple rename): { "name": "new-name" } Input (migration across lxd instances): { "migration": true } The migration does not actually start until someone (i.e. another lxd instance) connects to all the websockets and begins negotiation with the source. Output in metadata section (for migration): { "control": "secret1", # Migration control socket "criu": "secret2", # State transfer socket (only if live migrating) "fs": "secret3" # Filesystem transfer socket } These are the secrets that should be passed to the create call. ### DELETE * Description: remove the container * Authentication: trusted * Operation: async * Return: background operation or standard error Input (none at present): { } HTTP code for this should be 202 (Accepted). ## `/1.0/containers/<name>/exec` ### POST * Description: run a remote command * Authentication: trusted * Operation: async * Return: background operation + optional websocket information or standard error Input (run bash): { "command": ["/bin/bash"], # Command and arguments "environment": {}, # Optional extra environment variables to set "wait-for-websocket": false, # Whether to wait for a connection before starting the process "interactive": true, # Whether to allocate a pts device instead of PIPEs "width": 80, # Initial width of the terminal (optional) "height": 25, # Initial height of the terminal (optional) } `wait-for-websocket` indicates whether the operation should block and wait for a websocket connection to start (so that users can pass stdin and read stdout), or simply run to completion with /dev/null as stdin and stdout. If interactive is set to true, a single websocket is returned and is mapped to a pts device for stdin, stdout and stderr of the execed process. If interactive is set to false (default), three pipes will be setup, one for each of stdin, stdout and stderr. Depending on the state of the interactive flag, one or three different websocket/secret pairs will be returned, which are valid for connecting to this operations /websocket endpoint. The control websocket can be used to send out-of-band messages during an exec session. This is currently used for window size changes and for forwarding of signals. Control (window size change): { "command": "window-resize", "args": { "width": "80", "height": "50" } } Return (with wait-for-websocket=true and interactive=false): { "fds": { "0": "f5b6c760c0aa37a6430dd2a00c456430282d89f6e1661a077a926ed1bf3d1c21", "1": "464dcf9f8fdce29d0d6478284523a9f26f4a31ae365d94cd38bac41558b797cf", "2": "25b70415b686360e3b03131e33d6d94ee85a7f19b0f8d141d6dca5a1fc7b00eb", "control": "20c479d9532ab6d6c3060f6cdca07c1f177647c9d96f0c143ab61874160bd8a5" } } Return (with wait-for-websocket=true and interactive=true): { "fds": { "0": "f5b6c760c0aa37a6430dd2a00c456430282d89f6e1661a077a926ed1bf3d1c21", "control": "20c479d9532ab6d6c3060f6cdca07c1f177647c9d96f0c143ab61874160bd8a5" } } When the exec command finishes, its exit status is available from the operation's metadata: { "return": 0 } ## `/1.0/containers/<name>/files` ### GET (`?path=/path/inside/the/container`) * Description: download a file from the container * Authentication: trusted * Operation: sync * Return: Raw file or standard error The following headers will be set (on top of standard size and mimetype headers): * `X-LXD-uid`: 0 * `X-LXD-gid`: 0 * `X-LXD-mode`: 0700 This is designed to be easily usable from the command line or even a web browser. ### POST (`?path=/path/inside/the/container`) * Description: upload a file to the container * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input: * Standard http file upload The following headers may be set by the client: * `X-LXD-uid`: 0 * `X-LXD-gid`: 0 * `X-LXD-mode`: 0700 This is designed to be easily usable from the command line or even a web browser. ## `/1.0/containers/<name>/logs` ### GET * Description: Returns a list of the log files available for this container. Note that this works on containers that have been deleted (or were never created) to enable people to get logs for failed creations. * Authentication: trusted * Operation: Sync * Return: a list of the available log files Return: [ "/1.0/containers/blah/logs/forkstart.log", "/1.0/containers/blah/logs/lxc.conf", "/1.0/containers/blah/logs/lxc.log" ] ## `/1.0/containers/<name>/logs/<logfile>` ### GET * Description: returns the contents of a particular log file. * Authentication: trusted * Operation: N/A * Return: the contents of the log file ### DELETE * Description: delete a particular log file. * Authentication: trusted * Operation: Sync * Return: empty response or standard error ## `/1.0/containers/<name>/snapshots` ### GET * Description: List of snapshots * Authentication: trusted * Operation: sync * Return: list of URLs for snapshots for this container Return value: [ "/1.0/containers/blah/snapshots/snap0" ] ### POST * Description: create a new snapshot * Authentication: trusted * Operation: async * Return: background operation or standard error Input: { "name": "my-snapshot", # Name of the snapshot "stateful": true # Whether to include state too } ## `/1.0/containers/<name>/snapshots/<name>` ### GET * Description: Snapshot information * Authentication: trusted * Operation: sync * Return: dict representing the snapshot Return: { "architecture": "x86_64", "config": { "security.nesting": "true", "volatile.base_image": "a49d26ce5808075f5175bf31f5cb90561f5023dcd408da8ac5e834096d46b2d8", "volatile.eth0.hwaddr": "00:16:3e:ec:65:a8", "volatile.last_state.idmap": "[{\"Isuid\":true,\"Isgid\":false,\"Hostid\":100000,\"Nsid\":0,\"Maprange\":65536},{\"Isuid\":false,\"Isgid\":true,\"Hostid\":100000,\"Nsid\":0,\"Maprange\":65536}]", }, "created_at": "2016-03-08T23:55:08Z", "devices": { "eth0": { "name": "eth0", "nictype": "bridged", "parent": "lxdbr0", "type": "nic" }, "root": { "path": "/", "type": "disk" }, }, "ephemeral": false, "expanded_config": { "security.nesting": "true", "volatile.base_image": "a49d26ce5808075f5175bf31f5cb90561f5023dcd408da8ac5e834096d46b2d8", "volatile.eth0.hwaddr": "00:16:3e:ec:65:a8", "volatile.last_state.idmap": "[{\"Isuid\":true,\"Isgid\":false,\"Hostid\":100000,\"Nsid\":0,\"Maprange\":65536},{\"Isuid\":false,\"Isgid\":true,\"Hostid\":100000,\"Nsid\":0,\"Maprange\":65536}]", }, "expanded_devices": { "eth0": { "name": "eth0", "nictype": "bridged", "parent": "lxdbr0", "type": "nic" }, "root": { "path": "/", "type": "disk" }, }, "name": "zerotier/blah", "profiles": [ "default" ], "stateful": false } ### POST * Description: used to rename/migrate the snapshot * Authentication: trusted * Operation: async * Return: background operation or standard error Input (rename the snapshot): { "name": "new-name" } Input (setup the migration source): { "migration": true, } Return (with migration=true): { "control": "secret1", # Migration control socket "fs": "secret3" # Filesystem transfer socket } Renaming to an existing name must return the 409 (Conflict) HTTP code. ### DELETE * Description: remove the snapshot * Authentication: trusted * Operation: async * Return: background operation or standard error Input (none at present): { } HTTP code for this should be 202 (Accepted). ## `/1.0/containers/<name>/state` ### GET * Description: current state * Authentication: trusted * Operation: sync * Return: dict representing current state Output: { "type": "sync", "status": "Success", "status_code": 200, "metadata": { "status": "Running", "status_code": 103, "disk": { "root": { "usage": 422330368 } }, "memory": { "usage": 51126272, "usage_peak": 70246400, "swap_usage": 0, "swap_usage_peak": 0 }, "network": { "eth0": { "addresses": [ { "family": "inet", "address": "10.0.3.27", "netmask": "24", "scope": "global" }, { "family": "inet6", "address": "fe80::216:3eff:feec:65a8", "netmask": "64", "scope": "link" } ], "counters": { "bytes_received": 33942, "bytes_sent": 30810, "packets_received": 402, "packets_sent": 178 }, "hwaddr": "00:16:3e:ec:65:a8", "host_name": "vethBWTSU5", "mtu": 1500, "state": "up", "type": "broadcast" }, "lo": { "addresses": [ { "family": "inet", "address": "127.0.0.1", "netmask": "8", "scope": "local" }, { "family": "inet6", "address": "::1", "netmask": "128", "scope": "local" } ], "counters": { "bytes_received": 86816, "bytes_sent": 86816, "packets_received": 1226, "packets_sent": 1226 }, "hwaddr": "", "host_name": "", "mtu": 65536, "state": "up", "type": "loopback" }, "lxdbr0": { "addresses": [ { "family": "inet", "address": "10.0.3.1", "netmask": "24", "scope": "global" }, { "family": "inet6", "address": "fe80::68d4:87ff:fe40:7769", "netmask": "64", "scope": "link" } ], "counters": { "bytes_received": 0, "bytes_sent": 570, "packets_received": 0, "packets_sent": 7 }, "hwaddr": "6a:d4:87:40:77:69", "host_name": "", "mtu": 1500, "state": "up", "type": "broadcast" }, "zt0": { "addresses": [ { "family": "inet", "address": "29.17.181.59", "netmask": "7", "scope": "global" }, { "family": "inet6", "address": "fd80:56c2:e21c:0:199:9379:e711:b3e1", "netmask": "88", "scope": "global" }, { "family": "inet6", "address": "fe80::79:e7ff:fe0d:5123", "netmask": "64", "scope": "link" } ], "counters": { "bytes_received": 0, "bytes_sent": 806, "packets_received": 0, "packets_sent": 9 }, "hwaddr": "02:79:e7:0d:51:23", "host_name": "", "mtu": 2800, "state": "up", "type": "broadcast" } }, "pid": 13663, "processes": 32 } } ### PUT * Description: change the container state * Authentication: trusted * Operation: async * Return: background operation or standard error Input: { "action": "stop", # State change action (stop, start, restart, freeze or unfreeze) "timeout": 30, # A timeout after which the state change is considered as failed "force": true, # Force the state change (currently only valid for stop and restart where it means killing the container) "stateful": true # Whether to store or restore runtime state before stopping or startiong (only valid for stop and start, defaults to false) } ## `/1.0/events` This URL isn't a real REST API endpoint, instead doing a GET query on it will upgrade the connection to a websocket on which notifications will be sent. ### GET (`?type=operation,logging`) * Description: websocket upgrade * Authentication: trusted * Operation: sync * Return: none (never ending flow of events) Supported arguments are: * type: comma separated list of notifications to subscribe to (defaults to all) The notification types are: * operation (notification about creation, updates and termination of all background operations) * logging (every log entry from the server) This never returns. Each notification is sent as a separate JSON dict: { "timestamp": "2015-06-09T19:07:24.379615253-06:00", # Current timestamp "type": "operation", # Notification type "metadata": {} # Extra resource or type specific metadata } { "timestamp": "2016-02-17T11:44:28.572721913-05:00", "type": "logging", "metadata": { "context": { "ip": "@", "method": "GET" "url": "/1.0/containers/xen/snapshots", }, "level": "info", "message": "handling" } } ## `/1.0/images` ### GET * Description: list of images (public or private) * Authentication: guest or trusted * Operation: sync * Return: list of URLs for images this server publishes Return: [ "/1.0/images/54c8caac1f61901ed86c68f24af5f5d3672bdc62c71d04f06df3a59e95684473", "/1.0/images/97d97a3d1d053840ca19c86cdd0596cf1be060c5157d31407f2a4f9f350c78cc", "/1.0/images/a49d26ce5808075f5175bf31f5cb90561f5023dcd408da8ac5e834096d46b2d8", "/1.0/images/c9b6e738fae75286d52f497415463a8ecc61bbcb046536f220d797b0e500a41f" ] ### POST * Description: create and publish a new image * Authentication: trusted * Operation: async * Return: background operation or standard error Input (one of): * Standard http file upload * Source image dictionary (transfers a remote image) * Source container dictionary (makes an image out of a local container) * Remote image URL dictionary (downloads a remote image) In the http file upload case, The following headers may be set by the client: * `X-LXD-fingerprint`: SHA-256 (if set, uploaded file must match) * `X-LXD-filename`: FILENAME (used for export) * `X-LXD-public`: true/false (defaults to false) * `X-LXD-properties`: URL-encoded key value pairs without duplicate keys (optional properties) In the source image case, the following dict must be used: { "filename": filename, # Used for export (optional) "public": true, # Whether the image can be downloaded by untrusted users (defaults to false) "auto_update": true, # Whether the image should be auto-updated (optional; defaults to false) "properties": { # Image properties (optional, applied on top of source properties) "os": "Ubuntu" }, "source": { "type": "image", "mode": "pull", # Only pull is supported for now "server": "https://10.0.2.3:8443", # Remote server (pull mode only) "protocol": "lxd", # Protocol (one of lxd or simplestreams, defaults to lxd) "secret": "my-secret-string", # Secret (pull mode only, private images only) "certificate": "PEM certificate", # Optional PEM certificate. If not mentioned, system CA is used. "fingerprint": "SHA256", # Fingerprint of the image (must be set if alias isn't) "alias": "ubuntu/devel", # Name of the alias (must be set if fingerprint isn't) } } In the source container case, the following dict must be used: { "filename": filename, # Used for export (optional) "public": true, # Whether the image can be downloaded by untrusted users (defaults to false) "properties": { # Image properties (optional) "os": "Ubuntu" }, "source": { "type": "container", # One of "container" or "snapshot" "name": "abc" } } In the remote image URL case, the following dict must be used: { "filename": filename, # Used for export (optional) "public": true, # Whether the image can be downloaded by untrusted users (defaults to false) "properties": { # Image properties (optional) "os": "Ubuntu" }, "source": { "type": "url", "url": "https://www.some-server.com/image" # URL for the image } } After the input is received by LXD, a background operation is started which will add the image to the store and possibly do some backend filesystem-specific optimizations. ## `/1.0/images/<fingerprint>` ### GET (optional `?secret=SECRET`) * Description: Image description and metadata * Authentication: guest or trusted * Operation: sync * Return: dict representing an image properties Output: { "aliases": [ { "name": "trusty", "description": "", } ], "architecture": "x86_64", "auto_update": true, "cached": false, "fingerprint": "54c8caac1f61901ed86c68f24af5f5d3672bdc62c71d04f06df3a59e95684473", "filename": "ubuntu-trusty-14.04-amd64-server-20160201.tar.xz", "properties": { "architecture": "x86_64", "description": "Ubuntu 14.04 LTS server (20160201)", "os": "ubuntu", "release": "trusty" }, "update_source": { "server": "https://10.1.2.4:8443", "protocol": "lxd", "certificate": "PEM certificate", "alias": "ubuntu/trusty/amd64" }, "public": false, "size": 123792592, "created_at": "2016-02-01T21:07:41Z", "expires_at": "1970-01-01T00:00:00Z", "last_used_at": "1970-01-01T00:00:00Z", "uploaded_at": "2016-02-16T00:44:47Z" } ### PUT * Description: Updates the image properties * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input: { "auto_update": true, "properties": { "architecture": "x86_64", "description": "Ubuntu 14.04 LTS server (20160201)", "os": "ubuntu", "release": "trusty" }, "public": true, } ### DELETE * Description: Remove an image * Authentication: trusted * Operation: async * Return: background operaton or standard error Input (none at present): { } HTTP code for this should be 202 (Accepted). ## `/1.0/images/<fingerprint>/export` ### GET (optional `?secret=SECRET`) * Description: Download the image tarball * Authentication: guest or trusted * Operation: sync * Return: Raw file or standard error The secret string is required when an untrusted LXD is spawning a new container from a private image stored on a different LXD. Rather than require a trust relationship between the two LXDs, the client will `POST` to `/1.0/images/<fingerprint>/export` to get a secret token which it'll then pass to the target LXD. That target LXD will then GET the image as a guest, passing the secret token. ## `/1.0/images/<fingerprint>/secret` ### POST * Description: Generate a random token and tell LXD to expect it be used by a guest * Authentication: guest or trusted * Operation: async * Return: background operation or standard error Input: { } Return: { "secret": "52e9ec5885562aa24d05d7b4846ebb8b5f1f7bf5cd6e285639b569d9eaf54c9b" } Standard backround operation with "secret" set to the generated secret string in metadata. The secret is automatically invalidated 5s after an image URL using it has been accessed. This allows to both retried the image information and then hit /export with the same secret. ## `/1.0/images/aliases` ### GET * Description: list of aliases (public or private based on image visibility) * Authentication: guest or trusted * Operation: sync * Return: list of URLs for aliases this server knows about Return: [ "/1.0/images/aliases/sl6", "/1.0/images/aliases/trusty", "/1.0/images/aliases/xenial" ] ### POST * Description: create a new alias * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input: { "description": "The alias description", "target": "SHA-256", "name": "alias-name" } ## `/1.0/images/aliases/<name>` ### GET * Description: Alias description and target * Authentication: guest or trusted * Operation: sync * Return: dict representing an alias description and target Output: { "name": "test", "description": "my description", "target": "c9b6e738fae75286d52f497415463a8ecc61bbcb046536f220d797b0e500a41f" } ### PUT * Description: Updates the alias target or description * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input: { "description": "New description", "target": "54c8caac1f61901ed86c68f24af5f5d3672bdc62c71d04f06df3a59e95684473" } ### POST * Description: rename an alias * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input: { "name": "new-name" } Renaming to an existing name must return the 409 (Conflict) HTTP code. ### DELETE * Description: Remove an alias * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input (none at present): { } ## `/1.0/networks` ### GET * Description: list of networks * Authentication: trusted * Operation: sync * Return: list of URLs for networks that are current defined on the host [ "/1.0/networks/eth0",, "/1.0/networks/lxdbr0" ] ## `/1.0/networks/<name>` ### GET * Description: information about a network * Authentication: trusted * Operation: sync * Return: dict representing a network { "name": "lxdbr0", "type": "bridge", "used_by": [ "/1.0/containers/blah" ] } ## `/1.0/operations` ### GET * Description: list of operations * Authentication: trusted * Operation: sync * Return: list of URLs for operations that are currently going on/queued [ "/1.0/operations/c0fc0d0d-a997-462b-842b-f8bd0df82507", "/1.0/operations/092a8755-fd90-4ce4-bf91-9f87d03fd5bc" ] ## `/1.0/operations/<uuid>` ### GET * Description: background operation * Authentication: trusted * Operation: sync * Return: dict representing a background operation Return: { "id": "b8d84888-1dc2-44fd-b386-7f679e171ba5", "class": "token", # One of "task" (background task), "websocket" (set of websockets and crendentials) or "token" (temporary credentials) "created_at": "2016-02-17T16:59:27.237628195-05:00", # Creation timestamp "updated_at": "2016-02-17T16:59:27.237628195-05:00", # Last update timestamp "status": "Running", "status_code": 103, "resources": { # List of affected resources "images": [ "/1.0/images/54c8caac1f61901ed86c68f24af5f5d3672bdc62c71d04f06df3a59e95684473" ] }, "metadata": { # Extra information about the operation (action, target, ...) "secret": "c9209bee6df99315be1660dd215acde4aec89b8e5336039712fc11008d918b0d" }, "may_cancel": true, # Whether it's possible to cancel the operation (DELETE) "err": "" } ### DELETE * Description: cancel an operation. Calling this will change the state to "cancelling" rather than actually removing the entry. * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input (none at present): { } HTTP code for this should be 202 (Accepted). ## `/1.0/operations/<uuid>/wait` ### GET (optional `?timeout=30`) * Description: Wait for an operation to finish * Authentication: trusted * Operation: sync * Return: dict of the operation after it's reached its final state Input (wait indefinitely for a final state): no argument Input (similar but times out after 30s): ?timeout=30 ## `/1.0/operations/<uuid>/websocket` ### GET (`?secret=SECRET`) * Description: This connection is upgraded into a websocket connection speaking the protocol defined by the operation type. For example, in the case of an exec operation, the websocket is the bidirectional pipe for stdin/stdout/stderr to flow to and from the process inside the container. In the case of migration, it will be the primary interface over which the migration information is communicated. The secret here is the one that was provided when the operation was created. Guests are allowed to connect provided they have the right secret. * Authentication: guest or trusted * Operation: sync * Return: websocket stream or standard error ## `/1.0/profiles` ### GET * Description: List of configuration profiles * Authentication: trusted * Operation: sync * Return: list of URLs to defined profiles Return: [ "/1.0/profiles/default" ] ### POST * Description: define a new profile * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input: { "name": "my-profilename", "description": "Some description string", "config": { "limits.memory": "2GB" }, "devices": { "kvm": { "type": "unix-char", "path": "/dev/kvm" } } } ## `/1.0/profiles/<name>` ### GET * Description: profile configuration * Authentication: trusted * Operation: sync * Return: dict representing the profile content Output: { "name": "test", "description": "Some description string", "config": { "limits.memory": "2GB" }, "devices": { "kvm": { "path": "/dev/kvm", "type": "unix-char" } } } ### PUT * Description: update the profile * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input: { "config": { "limits.memory": "4GB" }, "description": "Some description string", "devices": { "kvm": { "path": "/dev/kvm", "type": "unix-char" } } } Same dict as used for initial creation and coming from GET. The name property can't be changed (see POST for that). ### POST * Description: rename a profile * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input (rename a profile): { "name": "new-name" } HTTP return value must be 204 (No content) and Location must point to the renamed resource. Renaming to an existing name must return the 409 (Conflict) HTTP code. ### DELETE * Description: remove a profile * Authentication: trusted * Operation: sync * Return: standard return value or standard error Input (none at present): { } HTTP code for this should be 202 (Accepted). ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/requirements.md����������������������������������������������������������������������0000644�0610621�0607500�00000001535�13172163242�017307� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Requirements ## Go LXD requires Go 1.5 or higher. Both the golang and gccgo compilers are supported. ## Kernel requirements The minimum supported kernel version is 3.13. LXD requires a kernel with support for: * Namespaces (pid, net, uts, ipc and mount) * Seccomp The following optional features also require extra kernel options: * Namespaces (user and cgroup) * AppArmor (including Ubuntu patch for mount mediation) * Control Groups (blkio, cpuset, devices, memory, pids and net\_prio) * CRIU (exact details to be found with CRIU upstream) As well as any other kernel feature required by the LXC version in use. ## LXC LXD requires LXC 2.0.0 or higher with the following build options: * apparmor (if using LXD's apparmor support) * seccomp To run recent version of various distributions, including Ubuntu, LXCFS should also be installed. �������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/profiles.md��������������������������������������������������������������������������0000644�0610621�0607500�00000001121�13172163242�016376� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Profiles Profiles can store any configuration that a container can (key/value or devices) and any number of profiles can be applied to a container. Profiles are applied in the order they are specified so the last profile to specify a specific key wins. In any case, resource-specific configuration always overrides that coming from the profiles. If not present, LXD will create a `default` profile. The `default` profile is set for any new container created which doesn't specify a different profiles list. See [container configuration](containers.md) for valid configuration options. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/production-setup.md������������������������������������������������������������������0000644�0610621�0607500�00000012523�13172163242�020107� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction So you've made it past trying out [LXD live online](https://linuxcontainers.org/lxd/try-it/), or on a server scavenged from random parts. You like what you see, and now you want to try doing some serious work with LXD. With the vanilla installation of Ubuntu Server 16.04, some modifications to the server configuration will be needed, to avoid common pitfalls when using containers that require tens of thousands of file operations. ## Common errors that may be encountered `Failed to allocate directory watch: Too many open files` `<Error> <Error>: Too many open files` `failed to open stream: Too many open files in...` # Server Changes ## /etc/security/limits.conf Domain | Type | Item | Value | Default | Description :----- | :--- | :---- | :-------- | :-------- | :---------- \* | soft | nofile | 1048576 | unset | maximum number of open files \* | hard | nofile | 1048576 | unset | maximum number of open files root | soft | nofile | 1048576 | unset | maximum number of open files root | hard | nofile | 1048576 | unset | maximum number of open files \* | soft | memlock | unlimited | unset | maximum locked-in-memory address space (KB) \* | hard | memlock | unlimited | unset | maximum locked-in-memory address space (KB) ## /etc/sysctl.conf Parameter | Value | Default | Description :----- | :--- | :--- | :--- fs.inotify.max\_queued\_events | 1048576 | 16384 | This specifies an upper limit on the number of events that can be queued to the corresponding inotify instance. [1] fs.inotify.max\_user\_instances | 1048576 | 128 | This specifies an upper limit on the number of inotify instances that can be created per real user ID. [1] fs.inotify.max\_user\_watches | 1048576 | 8192 | This specifies an upper limit on the number of watches that can be created per real user ID. [1] vm.max\_map\_count | 262144 | 65530 | This file contains the maximum number of memory map areas a process may have. Memory map areas are used as a side-effect of calling malloc, directly by mmap and mprotect, and also when loading shared libraries. kernel.dmesg\_restrict | 1 | 0 | This denies container access to the messages in the kernel ring buffer. Please note that this also will deny access to non-root users on the host system. Then, reboot the server. [1]: http://man7.org/linux/man-pages/man7/inotify.7.html ## Network Bandwidth Tweaking If you have at least 1GbE NIC on your lxd host with a lot of local activity (container - container connections, or host - container connections), or you have 1GbE or better internet connection on your lxd host it worth play with txqueuelen. These settings work even better with 10GbE NIC. ### Server Changes #### txqueuelen You need to change `txqueuelen` of your real NIC to 10000 (not sure about the best possible value for you), and change and change lxdbr0 interface `txqueuelen` to 10000. In Debian-based distros you can change `txqueuelen` permanently in `/etc/network/interfaces` You can add for ex.: `up ip link set eth0 txqueuelen 10000` to your interface configuration to set txqueuelen value on boot. For permanent lxdbr0 txqueuelen value change I prefer edit `/usr/lib/lxd/lxd-bridge`. You can add `ifconfig lxdbr0 txqueuelen 10000` in start section, just after iptables rules. For ex.: ```bash iptables "${use_iptables_lock}" -I FORWARD -o "${LXD_BRIDGE}" -j ACCEPT -m comment --comment "managed by lxd-bridge" iptables "${use_iptables_lock}" -t mangle -A POSTROUTING -o "${LXD_BRIDGE}" -p udp -m udp --dport 68 -j CHECKSUM --checksum-fill -m comment --comment "managed by lxd-bridge" ifconfig lxdbr0 txqueuelen 10000 ``` If you use lxd master in production or find this inappropriate you can set in `rc.local` or in another way you like. You could set it txqueuelen temporary (for test purpose) with `ifconfig <interface> txqueuelen 10000` #### /etc/sysctl.conf You also need to increase `net.core.netdev_max_backlog` value. You can add `net.core.netdev_max_backlog = 182757` to `/etc/sysctl.conf` to set it permanently (after reboot) You set `netdev_max_backlog` temporary (for test purpose) with `echo 182757 > /proc/sys/net/core/netdev_max_backlog` Note: You can find this value too high, most people prefer set `netdev_max_backlog` = `net.ipv4.tcp_mem` min. value. For example I use this values `net.ipv4.tcp_mem = 182757 243679 365514` ### Containers changes You also need to change txqueuelen value for all you ethernet interfaces in containers. In Debian-based distros you can change txqueuelen permanently in `/etc/network/interfaces` You can add for ex.: `up ip link set eth0 txqueuelen 10000` to your interface configuration to set txqueuelen value on boot. ### Notes regarding this change 10000 txqueuelen value commonly used with 10GbE NICs. Basically small txqueuelen values used with slow devices with a high latency, and higher with devices with low latency. I personally have like 3-5% improvement with these settings for local (host with container, container vs container) and internet connections. Good thing about txqueuelen value tweak, the more containers you use, the more you can be can benefit from this tweak. And you can always temporary set this values and check this tweak in your environment without lxd host reboot. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/migration.md�������������������������������������������������������������������������0000644�0610621�0607500�00000004323�13172163242�016553� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Live Migration in LXD ## Overview Migration has two pieces, a "source", that is, the host that already has the container, and a "sink", the host that's getting the container. Currently, in the `pull` mode, the source sets up an operation, and the sink connects to the source and pulls the container. There are three websockets (channels) used in migration: 1. the control stream 2. the criu images stream 3. the filesystem stream When a migration is initiated, information about the container, its configuration, etc. are sent over the control channel (a full description of this process is below), the criu images and container filesystem are synced over their respective channels, and the result of the restore operation is sent from the sink to the source over the control channel. In particular, the protocol that is spoken over the criu channel and filesystem channel can vary, depending on what is negotiated over the control socket. For example, both the source and the sink's LXD directory is on btrfs, the filesystem socket can speak btrfs-send/receive. Additionally, although we do a "stop the world" type migration right now, support for criu's p.haul protocol will happen over the criu socket at some later time. ## Control Socket Once all three websockets are connected between the two endpoints, the source sends a MigrationHeader (protobuf description found in `/lxd/migration/migrate.proto`). This header contains the container configuration which will be added to the new container. There are also two fields indicating the filesystem and criu protocol to speak. For example, if a server is hosted on a btrfs filesystem, it can indicate that it wants to do a `btrfs send` instead of a simple rsync (similarly, it could indicate that it wants to speak the p.haul protocol, instead of just rsyncing the images over slowly). The sink then examines this message and responds with whatever it supports. Continuing our example, if the sink is not on a btrfs filesystem, it responds with the lowest common denominator (rsync, in this case), and the source is to send the root filesystem using rsync. Similarly with the criu connection; if the sink doesn't have support for the p.haul protocol (or whatever), we fall back to rsync. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/index.md�����������������������������������������������������������������������������0000644�0610621�0607500�00000023161�13172163242�015672� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������[![LXD](https://linuxcontainers.org/static/img/containers.png)](https://linuxcontainers.org/lxd) # LXD LXD is a next generation system container manager. It offers a user experience similar to virtual machines but using Linux containers instead. It's image based with pre-made images available for a [wide number of Linux distributions](https://images.linuxcontainers.org) and is built around a very powerful, yet pretty simple, REST API. To get a better idea of what LXD is and what it does, you can [try it online](https://linuxcontainers.org/lxd/try-it/)! Then if you want to run it locally, take a look at our [getting started guide](https://linuxcontainers.org/lxd/getting-started-cli/). Release announcements can be found here: <https://linuxcontainers.org/lxd/news/> And the release tarballs here: <https://linuxcontainers.org/lxd/downloads/> ## Status Type | Service | Status --- | --- | --- CI (Linux) | Jenkins | [![Build Status](https://jenkins.linuxcontainers.org/job/lxd-github-commit-stable-2.0/badge/icon)](https://jenkins.linuxcontainers.org/job/lxd-github-commit-stable-2.0/) CI (macOS) | Travis | [![Build Status](https://travis-ci.org/lxc/lxd.svg?branch=stable-2.0)](https://travis-ci.org/lxc/lxd/) CI (Windows) | AppVeyor | [![Build Status](https://ci.appveyor.com/api/projects/status/rb4141dsi2xm3n0x/branch/stable-2.0?svg=true)](https://ci.appveyor.com/project/lxc/lxd/) Documentation | Godoc | [![GoDoc](https://godoc.org/github.com/lxc/lxd/client?status.svg)](https://godoc.org/github.com/lxc/lxd/client) Static analysis | GoReport | [![Go Report Card](https://goreportcard.com/badge/github.com/lxc/lxd)](https://goreportcard.com/report/github.com/lxc/lxd) Translations | Weblate | [![Translation status](https://hosted.weblate.org/widgets/linux-containers/-/svg-badge.svg)](https://hosted.weblate.org/projects/linux-containers/lxd/) Project status | CII Best Practices | [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/1086/badge)](https://bestpractices.coreinfrastructure.org/projects/1086) ## Installing LXD from packages Instructions on installing LXD for a wide variety of Linux distributions and operating systems [can be found on our website](https://linuxcontainers.org/lxd/getting-started-cli/). ## Installing LXD from source We recommend having the latest versions of liblxc (>= 2.0.0 required) and CRIU (>= 1.7 recommended) available for LXD development. Additionally, LXD requires Golang 1.6 or later to work. On ubuntu, you can get those with: ```bash sudo apt update sudo apt install acl dnsmasq-base git golang liblxc1 lxc-dev libacl1-dev make pkg-config rsync squashfs-tools tar xz-utils ``` There are a few storage backends for LXD besides the default "directory" backend. Installing these tools adds a bit to initramfs and may slow down your host boot, but are needed if you'd like to use a particular backend: ```bash sudo apt install lvm2 thin-provisioning-tools sudo apt install btrfs-tools ``` To run the testsuite, you'll also need: ```bash sudo apt install curl gettext jq sqlite3 uuid-runtime bzr ``` ### Building the tools LXD consists of two binaries, a client called `lxc` and a server called `lxd`. These live in the source tree in the `lxc/` and `lxd/` dirs, respectively. To get the code, set up your go environment: ```bash mkdir -p ~/go export GOPATH=~/go ``` And then download it as usual: ```bash go get github.com/lxc/lxd cd $GOPATH/src/github.com/lxc/lxd make ``` ...which will give you two binaries in `$GOPATH/bin`, `lxd` the daemon binary, and `lxc` a command line client to that daemon. ### Machine Setup You'll need sub{u,g}ids for root, so that LXD can create the unprivileged containers: ```bash echo "root:1000000:65536" | sudo tee -a /etc/subuid /etc/subgid ``` Now you can run the daemon (the `--group` sudo bit allows everyone in the sudo group to talk to LXD; you can create your own group if you want): ```bash sudo -E $GOPATH/bin/lxd --group sudo ``` ## Getting started with LXD Now that you have LXD running on your system you can read the [getting started guide](https://linuxcontainers.org/lxd/getting-started-cli/) or go through more examples and configurations in [our documentation](https://github.com/lxc/lxd/tree/master/doc). ## Bug reports Bug reports can be filed at: <https://github.com/lxc/lxd/issues/new> ## Contributing Fixes and new features are greatly appreciated but please read our [contributing guidelines](contributing.md) first. ## Support and discussions ### Forum A discussion forum is available at: <https://discuss.linuxcontainers.org> ### Mailing-lists We use the LXC mailing-lists for developer and user discussions, you can find and subscribe to those at: <https://lists.linuxcontainers.org> ### IRC If you prefer live discussions, some of us also hang out in [#lxcontainers](http://webchat.freenode.net/?channels=#lxcontainers) on irc.freenode.net. ## FAQ #### How to enable LXD server for remote access? By default LXD server is not accessible from the networks as it only listens on a local unix socket. You can make LXD available from the network by specifying additional addresses to listen to. This is done with the `core.https_address` config variable. To see the current server configuration, run: ```bash lxc config show ``` To set the address to listen to, find out what addresses are available and use the `config set` command on the server: ```bash ip addr lxc config set core.https_address 192.168.1.15 ``` #### When I do a `lxc remote add` over https, it asks for a password? By default, LXD has no password for security reasons, so you can't do a remote add this way. In order to set a password, do: ```bash lxc config set core.trust_password SECRET ``` on the host LXD is running on. This will set the remote password that you can then use to do `lxc remote add`. You can also access the server without setting a password by copying the client certificate from `.config/lxc/client.crt` to the server and adding it with: ```bash lxc config trust add client.crt ``` #### How do I configure LXD storage? LXD supports btrfs, directory, lvm and zfs based storage. First make sure you have the relevant tools for your filesystem of choice installed on the machine (btrfs-progs, lvm2 or zfsutils-linux). You can get a basic configuration done with: ```bash lxd init ``` `lxd init` supports both directory based storage and ZFS. btrfs is automatically setup if `/var/lib/lxd` is stored on btrfs. For LVM, you can set the `storage.lvm_vg_name` key to a valid LVM volume group. For production environments, you should be using block backed storage instead both for performance and reliability reasons. #### How can I live migrate a container using LXD? Live migration requires a tool installed on both hosts called [CRIU](http://criu.org), which is available in Ubuntu via: ```bash sudo apt-get install criu ``` Then, launch your container with the following, ```bash lxc launch ubuntu $somename sleep 5s # let the container get to an interesting state lxc move host1:$somename host2:$somename ``` And with luck you'll have migrated the container :). Migration is still in experimental stages and may not work for all workloads. Please report bugs on lxc-devel, and we can escalate to CRIU lists as necessary. #### Can I bind mount my home directory in a container? Yes. The easiest way to do that is using a privileged container to avoid file ownership issues: 1.a) create a container. ```bash lxc launch ubuntu privilegedContainerName -c security.privileged=true ``` 1.b) or, if your container already exists. ```bash lxc config set privilegedContainerName security.privileged true ``` 2) then. ```bash lxc config device add privilegedContainerName shareName disk source=/home/$USER path=/home/ubuntu ``` #### How can I run docker inside a LXD container? In order to run Docker inside a LXD container the `security.nesting` property of the container should be set to `true`. ```bash lxc config set <container> security.nesting true ``` Note that LXD containers cannot load kernel modules, so depending on your Docker configuration you may need to have the needed extra kernel modules loaded by the host. You can do so by setting a comma seperate list of kernel modules that your container needs with: ```bash lxc config set <container> linux.kernel_modules <modules> ``` We have also received some reports that creating a `/.dockerenv` file in your container can help Docker ignore some errors it's getting due to running in a nested environment. ## Hacking on LXD ### Directly using the REST API The LXD REST API can be used locally via unauthenticated Unix socket or remotely via SSL encapsulated TCP. #### Via Unix socket ```bash curl --unix-socket /var/lib/lxd/unix.socket \ -H "Content-Type: application/json" \ -X POST \ -d @hello-ubuntu.json \ lxd/1.0/containers ``` #### Via TCP TCP requires some additional configuration and is not enabled by default. ```bash lxc config set core.https_address "[::]:8443" ``` ```bash curl -k -L \ --cert ~/.config/lxc/client.crt \ --key ~/.config/lxc/client.key \ -H "Content-Type: application/json" \ -X POST \ -d @hello-ubuntu.json \ "https://127.0.0.1:8443/1.0/containers" ``` #### JSON payload The `hello-ubuntu.json` file referenced above could contain something like: ```json { "name":"some-ubuntu", "ephemeral":true, "config":{ "limits.cpu":"2" }, "source": { "type":"image", "mode":"pull", "protocol":"simplestreams", "server":"https://cloud-images.ubuntu.com/releases", "alias":"14.04" } } ``` ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/image-handling.md��������������������������������������������������������������������0000644�0610621�0607500�00000011741�13172163242�017430� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction LXD uses an image based workflow. It comes with a built-in image store where the user or external tools can import images. Containers are then started from those images. It's possible to spawn remote containers using local images or local containers using remote images. In such cases, the image may be cached on the target LXD. # Caching When spawning a container from a remote image, the remote image is downloaded into the local image store with the cached bit set. The image will be kept locally as a private image until either it's been unused (no new container spawned) for the number of days set in `images.remote_cache_expiry` or until the image's expiry is reached whichever comes first. LXD keeps track of image usage by updating the `last_used_at` image property every time a new container is spawned from the image. # Auto-update LXD can keep images up to date. By default, any image which comes from a remote server and was requested through an alias will be automatically updated by LXD. This can be changed with `images.auto_update_cached`. On startup and then every 6 hours (unless `images.auto_update_interval` is set), the LXD daemon will go look for more recent version of all the images in the store which are marked as auto-update and have a recorded source server. When a new image is found, it is downloaded into the image store, the aliases pointing to the old image are moved to the new one and the old image is removed from the store. The user can also request a particular image be kept up to date when manually copying an image from a remote server. # Image format LXD currently supports two LXD-specific image formats. The first is a unified tarball, where a single tarball contains both the container rootfs and the needed metadata. The second is a split model, using two tarballs instead, one containing the rootfs, the other containing the metadata. The former is what's produced by LXD itself and what people should be using for LXD-specific images. The latter is designed to allow for easy image building from existing non-LXD rootfs tarballs already available today. ## Unified tarball Tarball, can be compressed and contains: - `rootfs/` - `metadata.yaml` - `templates/` (optional) In this mode, the image identifier is the SHA-256 of the tarball. ## Split tarballs Two (possibly compressed) tarballs. One for metadata, one for the rootfs. `metadata.tar` contains: - `metadata.yaml` - `templates/` (optional) `rootfs.tar` contains a Linux root filesystem at its root. In this mode the image identifier is the SHA-256 of the concatenation of the metadata and rootfs tarball (in that order). ## Supported compression The tarball(s) can be compressed using bz2, gz, xz, lzma, tar (uncompressed) or it can also be a squashfs image. ## Content The rootfs directory (or tarball) contains a full file system tree of what will become the container's `/`. The templates directory contains pongo2-formatted templates of files inside the container. `metadata.yaml` contains information relevant to running the image under LXD, at the moment, this contains: ```yaml architecture: x86_64 creation_date: 1424284563 properties: description: Ubuntu 14.04 LTS Intel 64bit os: Ubuntu release: - trusty - 14.04 templates: /etc/hosts: when: - create - rename template: hosts.tpl properties: foo: bar /etc/hostname: when: - start template: hostname.tpl /etc/network/interfaces: when: - create template: interfaces.tpl create_only: true ``` The `architecture` and `creation_date` fields are mandatory, the properties are just a set of default properties for the image. The os, release, name and description fields while not mandatory in any way, should be pretty common. For templates, the `when` key can be one or more of: - `create` (run at the time a new container is created from the image) - `copy` (run when a container is created from an existing one) - `start` (run every time the container is started) The templates will always receive the following context: - `trigger`: name of the event which triggered the template (string) - `path`: path of the file being templated (string) - `container`: key/value map of container properties (name, architecture, privileged and ephemeral) (map[string]string) - `config`: key/value map of the container's configuration (map[string]string) - `devices`: key/value map of the devices assigned to this container (map[string]map[string]string) - `properties`: key/value map of the template properties specified in metadata.yaml (map[string]string) The `create_only` key can be set to have LXD only only create missing files but not overwrite an existing file. As a general rule, you should never template a file which is owned by a package or is otherwise expected to be overwritten by normal operation of the container. For convenience the following functions are exported to pongo templates: - `config_get("user.foo", "bar")` => Returns the value of `user.foo` or `"bar"` if unset. �������������������������������lxd-2.0.11/doc/environment.md�����������������������������������������������������������������������0000644�0610621�0607500�00000002157�13172163242�017131� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction The LXD client and daemon respect some environment variables to adapt to the user's environment and to turn some advanced features on and off. # Common Name | Description :--- | :---- `LXD_DIR` | The LXD data directory `PATH` | List of paths to look into when resolving binaries `http_proxy` | Proxy server URL for HTTP `https_proxy` | Proxy server URL for HTTPs `no_proxy` | List of domains that don't require the use of a proxy # Client environment variable Name | Description :--- | :---- `EDITOR` | What text editor to use `VISUAL` | What text editor to use (if `EDITOR` isn't set) # Server environment variable Name | Description :--- | :---- `LXD_SECURITY_APPARMOR` | If set to `false`, forces AppArmor off `LXD_LXC_TEMPLATE_CONFIG` | Path to the LXC template configuration directory �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/dev-lxd.md���������������������������������������������������������������������������0000644�0610621�0607500�00000004731�13172163242�016130� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction Communication between the hosted workload (container) and its host while not strictly needed is a pretty useful feature. In LXD, this feature is implemented through a `/dev/lxd/sock` node which is created and setup for all LXD containers. This file is a Unix socket which processes inside the container can connect to. It's multi-threaded so multiple clients can be connected at the same time. # Implementation details LXD on the host binds `/var/lib/lxd/devlxd` and starts listening for new connections on it. This socket is then bind-mounted into every single container started by LXD at `/dev/lxd/sock`. The bind-mount is required so we can exceed 4096 containers, otherwise, LXD would have to bind a different socket for every container, quickly reaching the FD limit. # Authentication Queries on `/dev/lxd/sock` will only return information related to the requesting container. To figure out where a request comes from, LXD will extract the initial socket ucred and compare that to the list of containers it manages. # Protocol The protocol on `/dev/lxd/sock` is plain-text HTTP with JSON messaging, so very similar to the local version of the LXD protocol. Unlike the main LXD API, there is no background operation and no authentication support in the `/dev/lxd/sock` API. # REST-API ## API structure * / * /1.0 * /1.0/config * /1.0/config/{key} * /1.0/meta-data ## API details ### `/` #### GET * Description: List of supported APIs * Return: list of supported API endpoint URLs (by default `['/1.0']`) Return value: ```json [ "/1.0" ] ``` ### `/1.0` #### GET * Description: Information about the 1.0 API * Return: dict Return value: ```json { "api_version": "1.0" } ``` ### `/1.0/config` #### GET * Description: List of configuration keys * Return: list of configuration keys URL Note that the configuration key names match those in the container config, however not all configuration namespaces will be exported to `/dev/lxd/sock`. Currently only the `user.*` keys are accessible to the container. At this time, there also aren't any container-writable namespace. Return value: ```json [ "/1.0/config/user.a" ] ``` ### `/1.0/config/<KEY>` #### GET * Description: Value of that key * Return: Plain-text value Return value: blah ### `/1.0/meta-data` #### GET * Description: Container meta-data compatible with cloud-init * Return: cloud-init meta-data Return value: #cloud-config instance-id: abc local-hostname: abc ���������������������������������������lxd-2.0.11/doc/debugging.md�������������������������������������������������������������������������0000644�0610621�0607500�00000004137�13172163242�016520� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Here are different ways to help troubleshooting `lxc` and `lxd` code. #### lxc --debug Adding `--debug` flag to any client command will give extra information about internals. If there is no useful info, it can be added with the logging call: logger.Debugf("Hello: %s", "Debug") #### lxc monitor This command will monitor messages as they appear on remote server. #### lxd --debug Shutting down `lxd` server and running it in foreground with `--debug` flag will bring a lot of (hopefully) useful info: ```bash systemctl stop lxd lxd.socket lxd --debug --group lxd ``` `--group lxd` is needed to grant access to unprivileged users in this group. ### REST API through local socket On server side the most easy way is to communicate with LXD through local socket. This command accesses `GET /1.0` and formats JSON into human readable form using [jq](https://stedolan.github.io/jq/tutorial/) utility: ```bash curl --unix-socket /var/lib/lxd/unix.socket lxd/1.0 | jq . ``` See the [RESTful API](rest-api.md) for available API. ### REST API through HTTPS [HTTPS connection to LXD](security.md) requires valid client certificate, generated in `~/.config/lxc/client.crt` on first `lxc remote add`. This certificate should be passed to connection tools for authentication and encryption. Examining certificate. In case you are curious: ```bash openssl x509 -in client.crt -purpose ``` Among the lines you should see: Certificate purposes: SSL client : Yes #### with command line tools ```bash wget --no-check-certificate https://127.0.0.1:8443/1.0 --certificate=$HOME/.config/lxc/client.crt --private-key=$HOME/.config/lxc/client.key -O - -q ``` #### with browser Some browser plugins provide convenient interface to create, modify and replay web requests. To authenticate againsg LXD server, convert `lxc` client certificate into importable format and import it into browser. For example this produces `client.pfx` in Windows-compatible format: ```bash openssl pkcs12 -clcerts -inkey client.key -in client.crt -export -out client.pfx ``` After that, opening https://127.0.0.1:8443/1.0 should work as expected. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/database.md��������������������������������������������������������������������������0000644�0610621�0607500�00000034000�13172163242�016321� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction So first of all, why a database? Rather than keeping the configuration and state within each container's directory as is traditionally done by LXC, LXD has an internal database which stores all of that information. This allows very quick queries against all containers configuration. An example is the rather obvious question "what containers are using br0?". To answer that question without a database, LXD would have to iterate through every single container, load and parse its configuration and then look at what network devices are defined in there. While that may be quick with a few containers, imagine how many filesystem access would be required for 2000 containers. Instead with a database, it's only a matter of accessing the already cached database with a pretty simple query. # Database engine As this is a purely internal database with a single client and very little data, we'll be using sqlite3. We have no interest in replication or other HA features offered by the bigger database engines as LXD runs on each compute nodes and having the database accessible when the compute node itself isn't, wouldn't be terribly useful. # Design The design of the database is made to be as close as possible to the [RESTful API](rest-api.md). The main table and field names are exact match for the REST API. However this database isn't an exact match of the API, mostly because any runtime or external piece of information will not be stored in the database (as this would require constent polling and wouldn't gain us anything). We make no guarantee of stability for the database schema. This is a purely internal database which only LXD should ever use. Updating LXD may cause a schema update and data being shuffled. In those cases, LXD will make a copy of the old database as ".old" to allow for a revert. # Tables The list of tables is: * certificates * config * containers * containers\_config * containers\_devices * containers\_devices\_config * containers\_profiles * images * images\_properties * images\_aliases * images\_source * profiles * profiles\_config * profiles\_devices * profiles\_devices\_config * schema You'll notice that compared to the REST API, there are three main differences: 1. The extra "\*\_config" tables which are there for key/value config storage. 2. The extra "images\_properties" table which is there for key/value property storage. 3. The extra "schema" table whish is used for database schema version tracking. 4. There is no "snapshots" table. That's because snapshots are a copy of a container at a given point in time, including its configuration and on-disk state. So having snapshots in a separate table would only be needless duplication. # Notes on sqlite3 sqlite3 only supports 5 storage classes: NULL, INTEGER, REAL, TEXT and BLOB There are then a set of aliases for each of those storage classes which is what we use below. # Schema ## certificates Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL fingerprint | VARCHAR(255) | - | NOT NULL | HEX encoded certificate fingerprint type | INTEGER | - | NOT NULL | Certificate type (0 = client) name | VARCHAR(255) | - | NOT NULL | Certificate name (defaults to CN) certificate | TEXT | - | NOT NULL | PEM encoded certificate Index: UNIQUE ON id AND fingerprint ## config (server configuration) Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL key | VARCHAR(255) | - | NOT NULL | Configuration key value | TEXT | - | | Configuration value (NULL for unset) Index: UNIQUE ON id AND key ## containers Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL name | VARCHAR(255) | - | NOT NULL | Container name architecture | INTEGER | - | NOT NULL | Container architecture type | INTEGER | 0 | NOT NULL | Container type (0 = container, 1 = container snapshot) ephemeral | INTEGER | 0 | NOT NULL | Whether the container is ephemeral (0 = persistent, 1 = ephemeral) stateful | INTEGER | 0 | NOT NULL | Whether the snapshot contains state (snapshot only) creation\_date | DATETIME | - | | Image creation date (user supplied, 0 = unknown) Index: UNIQUE ON id AND name ## containers\_config Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL container\_id | INTEGER | - | NOT NULL | containers.id FK key | VARCHAR(255) | - | NOT NULL | Configuration key value | TEXT | - | | Configuration value (NULL for unset) Index: UNIQUE ON id AND container\_id + key Foreign keys: container\_id REFERENCES containers(id) ## containers\_devices Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL container\_id | INTEGER | - | NOT NULL | containers.id FK name | VARCHAR(255) | - | NOT NULL | Container name type | INTEGER | 0 | NOT NULL | Device type (see configuration.md) Index: UNIQUE ON id AND container\_id + name Foreign keys: container\_id REFERENCES containers(id) ## containers\_devices\_config Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL container\_device\_id | INTEGER | - | NOT NULL | containers\_devices.id FK key | VARCHAR(255) | - | NOT NULL | Configuration key value | TEXT | - | | Configuration value (NULL for unset) Index: UNIQUE ON id AND container\_device\_id + key Foreign keys: container\_device\_id REFERENCES containers\_devices(id) ## containers\_profiles Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL container\_id | INTEGER | - | NOT NULL | containers.id FK profile\_id | INTEGER | - | NOT NULL | profiles.id FK apply\_order | INTEGER | 0 | NOT NULL | Profile ordering Index: UNIQUE ON id AND container\_id + profile\_id Foreign keys: container\_id REFERENCES containers(id) and profile\_id REFERENCES profiles(id) ## images Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL cached | INTEGER | 0 | NOT NULL | Whether this is a cached image fingerprint | VARCHAR(255) | - | NOT NULL | Tarball fingerprint filename | VARCHAR(255) | - | NOT NULL | Tarball filename size | INTEGER | - | NOT NULL | Tarball size public | INTEGER | 0 | NOT NULL | Whether the image is public or not auto\_update | INTEGER | 0 | NOT NULL | Whether to update from the source of this image architecture | INTEGER | - | NOT NULL | Image architecture creation\_date | DATETIME | - | | Image creation date (user supplied, 0 = unknown) expiry\_date | DATETIME | - | | Image expiry (user supplied, 0 = never) upload\_date | DATETIME | - | NOT NULL | Image entry creation date last\_use\_date | DATETIME | - | | Last time the image was used to spawn a container Index: UNIQUE ON id AND fingerprint ## images\_aliases Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL name | VARCHAR(255) | - | NOT NULL | Alias name image\_id | INTEGER | - | NOT NULL | images.id FK description | VARCHAR(255) | - | | Description of the alias Index: UNIQUE ON id AND name Foreign keys: image\_id REFERENCES images(id) ## images\_properties Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL image\_id | INTEGER | - | NOT NULL | images.id FK type | INTEGER | 0 | NOT NULL | Property type (0 = string, 1 = text) key | VARCHAR(255) | - | NOT NULL | Property name value | TEXT | - | | Property value (NULL for unset) Index: UNIQUE ON id Foreign keys: image\_id REFERENCES images(id) ## images\_source Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL image\_id | INTEGER | - | NOT NULL | images.id FK server | TEXT | - | NOT NULL | Server URL protocol | INTEGER | 0 | NOT NULL | Protocol to access the remote (0 = lxd, 1 = direct, 2 = simplestreams) alias | VARCHAR(255) | - | NOT NULL | What remote alias to use as the source certificate | TEXT | - | | PEM encoded certificate of the server Index: UNIQUE ON id Foreign keys: image\_id REFERENCES images(id) ## profiles Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL name | VARCHAR(255) | - | NOT NULL | Profile name description | TEXT | - | | Description of the profile Index: UNIQUE on id AND name ## profiles\_config Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL profile\_id | INTEGER | - | NOT NULL | profiles.id FK key | VARCHAR(255) | - | NOT NULL | Configuration key value | VARCHAR(255) | - | | Configuration value (NULL for unset) Index: UNIQUE ON id AND profile\_id + key Foreign keys: profile\_id REFERENCES profiles(id) ## profiles\_devices Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL profile\_id | INTEGER | - | NOT NULL | profiles.id FK name | VARCHAR(255) | - | NOT NULL | Container name type | INTEGER | 0 | NOT NULL | Device type (see configuration.md) Index: UNIQUE ON id AND profile\_id + name Foreign keys: profile\_id REFERENCES profiles(id) ## profiles\_devices\_config Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL profile\_device\_id | INTEGER | - | NOT NULL | profiles\_devices.id FK key | VARCHAR(255) | - | NOT NULL | Configuration key value | TEXT | - | | Configuration value (NULL for unset) Index: UNIQUE ON id AND profile\_device\_id + key Foreign keys: profile\_device\_id REFERENCES profiles\_devices(id) ## schema Column | Type | Default | Constraint | Description :----- | :--- | :------ | :--------- | :---------- id | INTEGER | SERIAL | NOT NULL | SERIAL version | INTEGER | - | NOT NULL | Schema version updated\_at | DATETIME | - | NOT NULL | When the schema update was done Index: UNIQUE ON id AND version lxd-2.0.11/doc/daemon-behavior.md�������������������������������������������������������������������0000644�0610621�0607500�00000002323�13172163242�017620� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction This specification covers some of the daemon's behavior, such as reaction to given signals, crashes, ... # Startup On every start, LXD checks that its directory structure exists. If it doesn't, it'll create the required directories, generate a keypair and initialize the database. Once the daemon is ready for work, LXD will scan the containers table for any container for which the stored power state differs from the current one. If a container's power state was recorded as running and the container isn't running, LXD will start it. # Signal handling ## SIGINT, SIGQUIT, SIGTERM For those signals, LXD assumes that it's being temporarily stopped and will be restarted at a later time to continue handling the containers. The containers will keep running and LXD will close all connections and exit cleanly. ## SIGPWR Indicates to LXD that the host is going down. LXD will attempt a clean shutdown of all the containers. After 30s, it will kill any remaining container. The container `power_state` in the containers table is kept as it was so that LXD after the host is done rebooting can restore the containers as they were. ## SIGUSR1 Write a memory profile dump to the file specified with `--memprofile`. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/contributing.md����������������������������������������������������������������������0000644�0610621�0607500�00000005113�13172163242�017267� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Pull requests: Changes to this project should be proposed as pull requests on Github at: <https://github.com/lxc/lxd> Proposed changes will then go through code review there and once acked, be merged in the main branch. # License and copyright: By default, any contribution to this project is made under the Apache 2.0 license. The author of a change remains the copyright holder of their code (no copyright assignment). # Developer Certificate of Origin: To improve tracking of contributions to this project we use the DCO 1.1 and use a "sign-off" procedure for all changes going into the branch. The sign-off is a simple line at the end of the explanation for the commit which certifies that you wrote it or otherwise have the right to pass it on as an open-source contribution. > Developer Certificate of Origin > Version 1.1 > > Copyright (C) 2004, 2006 The Linux Foundation and its contributors. > 660 York Street, Suite 102, > San Francisco, CA 94110 USA > > Everyone is permitted to copy and distribute verbatim copies of this > license document, but changing it is not allowed. > > Developer's Certificate of Origin 1.1 > > By making a contribution to this project, I certify that: > > (a) The contribution was created in whole or in part by me and I > have the right to submit it under the open source license > indicated in the file; or > > (b) The contribution is based upon previous work that, to the best > of my knowledge, is covered under an appropriate open source > license and I have the right under that license to submit that > work with modifications, whether created in whole or in part > by me, under the same open source license (unless I am > permitted to submit under a different license), as indicated > in the file; or > > (c) The contribution was provided directly to me by some other > person who certified (a), (b) or (c) and I have not modified > it. > > (d) I understand and agree that this project and the contribution > are public and that a record of the contribution (including all > personal information I submit with it, including my sign-off) is > maintained indefinitely and may be redistributed consistent with > this project or the open source license(s) involved. An example of a valid sign-off line is: ``` Signed-off-by: Random J Developer <random@developer.org> ``` Use your real name and a valid e-mail address. Sorry, no pseudonyms or anonymous contributions are allowed. We also require each commit be individually signed-off by their author, even when part of a larger set. You may find `git commit -s` useful. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/containers.md������������������������������������������������������������������������0000644�0610621�0607500�00000040203�13172163242�016724� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Container configuration ## Properties The following are direct container properties and can't be part of a profile: - `name` - `architecture` Name is the container name and can only be changed by renaming the container. ## Key/value configuration The key/value configuration is namespaced with the following namespaces currently supported: - `boot` (boot related options, timing, dependencies, ...) - `environment` (environment variables) - `limits` (resource limits) - `raw` (raw container configuration overrides) - `security` (security policies) - `user` (storage for user properties, searchable) - `volatile` (used internally by LXD to store settings that are specific to a specific container instance) The currently supported keys are: Key | Type | Default | Live update | Description :-- | :--- | :------ | :---------- | :---------- boot.autostart | boolean | - | n/a | Always start the container when LXD starts (if not set, restore last state) boot.autostart.delay | integer | 0 | n/a | Number of seconds to wait after the container started before starting the next one boot.autostart.priority | integer | 0 | n/a | What order to start the containers in (starting with highest) environment.\* | string | - | yes (exec) | key/value environment variables to export to the container and set on exec limits.cpu | string | - (all) | yes | Number or range of CPUs to expose to the container limits.cpu.allowance | string | 100% | yes | How much of the CPU can be used. Can be a percentage (e.g. 50%) for a soft limit or hard a chunk of time (25ms/100ms) limits.cpu.priority | integer | 10 (maximum) | yes | CPU scheduling priority compared to other containers sharing the same CPUs (overcommit) (integer between 0 and 10) limits.disk.priority | integer | 5 (medium) | yes | When under load, how much priority to give to the container's I/O requests (integer between 0 and 10) limits.memory | string | - (all) | yes | Percentage of the host's memory or fixed value in bytes (supports kB, MB, GB, TB, PB and EB suffixes) limits.memory.enforce | string | hard | yes | If hard, container can't exceed its memory limit. If soft, the container can exceed its memory limit when extra host memory is available. limits.memory.swap | boolean | true | yes | Whether to allow some of the container's memory to be swapped out to disk limits.memory.swap.priority | integer | 10 (maximum) | yes | The higher this is set, the least likely the container is to be swapped to disk (integer between 0 and 10) limits.network.priority | integer | 0 (minimum) | yes | When under load, how much priority to give to the container's network requests (integer between 0 and 10) limits.processes | integer | - (max) | yes | Maximum number of processes that can run in the container linux.kernel\_modules | string | - | yes | Comma separated list of kernel modules to load before starting the container raw.apparmor | blob | - | yes | Apparmor profile entries to be appended to the generated profile raw.idmap | blob | - | no | Raw idmap configuration (e.g. "both 1000 1000") raw.lxc | blob | - | no | Raw LXC configuration to be appended to the generated one security.idmap.base | integer | - | no | The base host ID to use for the allocation (overrides auto-detection) security.idmap.isolated | boolean | false | no | Use an idmap for this container that is unique among containers with isolated set. security.idmap.size | integer | - | no | The size of the idmap to use security.nesting | boolean | false | yes | Support running lxd (nested) inside the container security.privileged | boolean | false | no | Runs the container in privileged mode user.\* | string | - | n/a | Free form user key/value storage (can be used in search) The following volatile keys are currently internally used by LXD: Key | Type | Default | Description :-- | :--- | :------ | :---------- volatile.apply\_template | string | - | The name of a template hook which should be triggered upon next startup volatile.base\_image | string | - | The hash of the image the container was created from, if any. volatile.idmap.base | integer | - | The first id in the container's primary idmap range volatile.idmap.next | string | - | The idmap to use next time the container starts volatile.last\_state.idmap | string | - | Serialized container uid/gid map volatile.last\_state.power | string | - | Container state as of last host shutdown volatile.\<name\>.host\_name | string | - | Network device name on the host (for nictype=bridged or nictype=p2p) volatile.\<name\>.hwaddr | string | - | Network device MAC address (when no hwaddr property is set on the device itself) volatile.\<name\>.name | string | - | Network device name (when no name propery is set on the device itself) Additionally, those user keys have become common with images (support isn't guaranteed): Key | Type | Default | Description :-- | :--- | :------ | :---------- user.meta-data | string | - | Cloud-init meta-data, content is appended to seed value. user.network-config | string | DHCP on eth0 | Cloud-init network-config, content is used as seed value. user.network\_mode | string | dhcp | One of "dhcp" or "link-local". Used to configure network in supported images. user.user-data | string | #!cloud-config | Cloud-init user-data, content is used as seed value. user.vendor-data | string | #!cloud-config | Cloud-init vendor-data, content is used as seed value. Note that while a type is defined above as a convenience, all values are stored as strings and should be exported over the REST API as strings (which makes it possible to support any extra values without breaking backward compatibility). Those keys can be set using the lxc tool with: ```bash lxc config set <container> <key> <value> ``` Volatile keys can't be set by the user and can only be set directly against a container. The raw keys allow direct interaction with the backend features that LXD itself uses, setting those may very well break LXD in non-obvious ways and should whenever possible be avoided. ## Devices configuration LXD will always provide the container with the basic devices which are required for a standard POSIX system to work. These aren't visible in container or profile configuration and may not be overriden. Those includes: - `/dev/null` (character device) - `/dev/zero` (character device) - `/dev/full` (character device) - `/dev/console` (character device) - `/dev/tty` (character device) - `/dev/random` (character device) - `/dev/urandom` (character device) - `/dev/net/tun` (character device) - `/dev/fuse` (character device) - `lo` (network interface) Anything else has to be defined in the container configuration or in one of its profiles. The default profile will typically contain a network interface to become `eth0` in the container. To add extra devices to a container, device entries can be added directly to a container, or to a profile. Devices may be added or removed while the container is running. Every device entry is identified by a unique name. If the same name is used in a subsequent profile or in the container's own configuration, the whole entry is overriden by the new definition. Device entries are added through: ```bash lxc config device add <container> <name> <type> [key=value]... lxc profile device add <profile> <name> <type> [key=value]... ``` ## Device types LXD supports the following device types: ID (database) | Name | Description :-- | :-- | :-- 0 | [none](#type-none) | Inheritance blocker 1 | [nic](#type-nic) | Network interface 2 | [disk](#type-disk) | Mountpoint inside the container 3 | [unix-char](#type-unix-char) | Unix character device 4 | [unix-block](#type-unix-block) | Unix block device ### Type: none A none type device doesn't have any property and doesn't create anything inside the container. It's only purpose it to stop inheritance of devices coming from profiles. To do so, just add a none type device with the same name of the one you wish to skip inheriting. It can be added in a profile being applied after the profile it originated from or directly on the container. ### Type: nic LXD supports different kind of network devices: - `physical`: Straight physical device passthrough from the host. The targeted device will vanish from the host and appear in the container. - `bridged`: Uses an existing bridge on the host and creates a virtual device pair to connect the host bridge to the container. - `macvlan`: Sets up a new network device based on an existing one but using a different MAC address. - `p2p`: Creates a virtual device pair, putting one side in the container and leaving the other side on the host. Different network interface types have different additional properties, the current list is: Key | Type | Default | Required | Used by | Description :-- | :-- | :-- | :-- | :-- | :-- nictype | string | - | yes | all | The device type, one of "physical", "bridged", "macvlan" or "p2p" limits.ingress | string | - | no | bridged, p2p | I/O limit in bit/s (supports kbit, Mbit, Gbit suffixes) limits.egress | string | - | no | bridged, p2p | I/O limit in bit/s (supports kbit, Mbit, Gbit suffixes) limits.max | string | - | no | bridged, p2p | Same as modifying both limits.read and limits.write name | string | kernel assigned | no | all | The name of the interface inside the container host\_name | string | randomly assigned | no | bridged, p2p, macvlan | The name of the interface inside the host hwaddr | string | randomly assigned | no | all | The MAC address of the new interface mtu | integer | parent MTU | no | all | The MTU of the new interface parent | string | - | yes | physical, bridged, macvlan | The name of the host device or bridge #### bridged or macvlan for connection to physical network The `bridged` and `macvlan` interface types can both be used to connect to an existing physical network. macvlan effectively lets you fork your physical NIC, getting a second interface that's then used by the container. This saves you from creating a bridge device and veth pairs and usually offers better performance than a bridge. The downside to this is that macvlan devices while able to communicate between themselves and to the outside, aren't able to talk to their parent device. This means that you can't use macvlan if you ever need your containers to talk to the host itself. In such case, a bridge is preferable. A bridge will also let you use mac filtering and I/O limits which cannot be applied to a macvlan device. ### Type: disk Disk entries are essentially mountpoints inside the container. They can either be a bind-mount of an existing file or directory on the host, or if the source is a block device, a regular mount. The following properties exist: Key | Type | Default | Required | Description :-- | :-- | :-- | :-- | :-- limits.read | string | - | no | I/O limit in byte/s (supports kB, MB, GB, TB, PB and EB suffixes) or in iops (must be suffixed with "iops") limits.write | string | - | no | I/O limit in byte/s (supports kB, MB, GB, TB, PB and EB suffixes) or in iops (must be suffixed with "iops") limits.max | string | - | no | Same as modifying both limits.read and limits.write path | string | - | yes | Path inside the container where the disk will be mounted source | string | - | yes | Path on the host, either to a file/directory or to a block device optional | boolean | false | no | Controls whether to fail if the source doesn't exist readonly | boolean | false | no | Controls whether to make the mount read-only size | string | - | no | Disk size in bytes (supports kB, MB, GB, TB, PB and EB suffixes). This is only supported for the rootfs (/). recursive | boolean | false | no | Whether or not to recursively mount the source path If multiple disks, backed by the same block device, have I/O limits set, the average of the limits will be used. ### Type: unix-char Unix character device entries simply make the requested character device appear in the container's `/dev` and allow read/write operations to it. The following properties exist: Key | Type | Default | Required | Description :-- | :-- | :-- | :-- | :-- path | string | - | yes | Path inside the container major | int | device on host | no | Device major number minor | int | device on host | no | Device minor number uid | int | 0 | no | UID of the device owner in the container gid | int | 0 | no | GID of the device owner in the container mode | int | 0660 | no | Mode of the device in the container ### Type: unix-block Unix block device entries simply make the requested block device appear in the container's /dev and allow read/write operations to it. The following properties exist: Key | Type | Default | Required | Description :-- | :-- | :-- | :-- | :-- path | string | - | yes | Path inside the container major | int | device on host | no | Device major number minor | int | device on host | no | Device minor number uid | int | 0 | no | UID of the device owner in the container gid | int | 0 | no | GID of the device owner in the container mode | int | 0660 | no | Mode of the device in the container ## Instance types LXD supports simple instance types. Those are represented as a string which can be passed at container creation time. There are three allowed syntaxes: - `<instance type>` - `<cloud>:<instance type>` - `c<CPU>-m<RAM in GB>` For example, those 3 are equivalent: - t2.micro - aws:t2.micro - c1-m1 On the command line, this is passed like this: ```bash lxc launch ubuntu:16.04 my-container -t t2.micro ``` The list of supported clouds and instance types can be found here: https://github.com/dustinkirkland/instance-type ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/container-environment.md�������������������������������������������������������������0000644�0610621�0607500�00000005674�13172163242�021120� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Container runtime environment LXD attempts to present a consistent environment to the container it runs. The exact environment will differ slightly based on kernel features and user configuration but will otherwise be identical for all containers. ## PID1 LXD spawns whatever is located at `/sbin/init` as the initial process of the container (PID 1). This binary should act as a proper init system, including handling re-parented processes. LXD's communication with PID1 in the container is limited to two signals: - `SIGINT` to trigger a reboot of the container - `SIGPWR` (or alternatively `SIGRTMIN`+3) to trigger a clean shutdown of the container The initial environment of PID1 is blank except for `container=lxc` which can be used by the init system to detect the runtime. All file descriptors above the default 3 are closed prior to PID1 being spawned. ## Filesystem LXD assumes that any image it uses to create a new container from will come with at least: - `/dev` (empty) - `/proc` (empty) - `/sbin/init` (executable) - `/sys` (empty) ## Devices LXD containers have a minimal and ephemeral `/dev` based on a tmpfs filesystem. Since this is a tmpfs and not a devtmpfs, device nodes will only appear if manually created. The standard set of device nodes will be setup: - `/dev/console` - `/dev/fd` - `/dev/full` - `/dev/log` - `/dev/null` - `/dev/ptmx` - `/dev/random` - `/dev/stdin` - `/dev/stderr` - `/dev/stdout` - `/dev/tty` - `/dev/urandom` - `/dev/zero` On top of the standard set of devices, the following are also setup for convenience: - `/dev/fuse` - `/dev/net/tun` - `/dev/mqueue` ## Mounts The following mounts are setup by default under LXD: - `/proc` (proc) - `/sys` (sysfs) - `/sys/fs/cgroup/*` (cgroupfs) (only on kernels lacking cgroup namespace support) The following paths will also be automatically mounted if present on the host: - `/proc/sys/fs/binfmt_misc` - `/sys/firmware/efi/efivars` - `/sys/fs/fuse/connections` - `/sys/fs/pstore` - `/sys/kernel/debug` - `/sys/kernel/security` The reason for passing all of those is legacy init systems which require those to be mounted or be mountabled inside the container. The majority of those will not be writable (or even readable) from inside an unprivileged container and will be blocked by our AppArmor policy inside privileged containers. ## Network LXD containers may have any number of network devices attached to them. The naming for those unless overriden by the user is ethX where X is an incrementing number. ## Container to host communication LXD sets up a socket at `/dev/lxd/sock` which root in the container can use to communicate with LXD on the host. The API is [documented here](dev-lxd.md). ## LXCFS If LXCFS is present on the host, it will automatically be setup for the container. This normally results in a number of `/proc` files being overriden through bind-mounts. On older kernels a virtual version of `/sys/fs/cgroup` may also be setup by LXCFS. ��������������������������������������������������������������������lxd-2.0.11/doc/configuration.md���������������������������������������������������������������������0000644�0610621�0607500�00000000226�13172163242�017427� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction Current LXD stores configurations for a few components: - [Server](server.md) - [Containers](containers.md) - [Profiles](profiles.md) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/cloud-init.md������������������������������������������������������������������������0000644�0610621�0607500�00000012611�13172163242�016630� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Custom network configuration with cloud-init [cloud-init](https://launchpad.net/cloud-init) may be used for custom network configuration of containers. Before trying to use it, however, first determine which image source you are about to use as not all container images have cloud-init package installed. At the time of writing, images provided at images.linuxcontainers.org do not have the cloud-init package installed, therefore, any of the configuration options mentioned in this guide will not work. On the contrary, images provided at cloud-images.ubuntu.com have the necessary package installed and also have a templates directory in their archive populated with * `cloud-init-meta.tpl` * `cloud-init-user.tpl` * `cloud-init-vendor.tpl` * `cloud-init-network.tpl` and others not related to cloud-init. Templates provided with container images at cloud-images.ubuntu.com have the following in their `metadata.yaml`: ```yaml /var/lib/cloud/seed/nocloud-net/network-config: when: - create - copy template: cloud-init-network.tpl ``` Therefore, either when you create or copy a container it gets a newly rendered network configuration from a pre-defined template. cloud-init uses the network-config file to render `/etc/network/interfaces.d/50-cloud-init.cfg` when you first start a container. It will not react to any changes if you restart a container afterwards unless you force it. The default behavior is to use a DHCP client on a container's eth0 interface. In order to change this you need to define your own network configuration using user.network-config key in the config dictionary which will override the default configuration (this is due to how the template is structured). The allowed values follow `/etc/network/interfaces` syntax in case of Ubuntu images. For example, to configure a specific network interface with a static IPv4 address and also use a custom nameserver use ```yaml config: user.network-config: | version: 1 config: - type: physical name: eth1 subnets: - type: static ipv4: true address: 10.10.101.20 netmask: 255.255.255.0 gateway: 10.10.101.1 control: auto - type: nameserver address: 10.10.10.254 ``` A container's rootfs will contain the following files as a result: * `/var/lib/cloud/seed/nocloud-net/network-config` * `/etc/network/interfaces.d/50-cloud-init.cfg` The former will be the same as the value provided in user.network-config, the latter will be a file in `/etc/network/interfaces` format converted from the network-config file by cloud-init (if it is not check syslog for cloud-init error messages). `/etc/network/interfaces.d/50-cloud-init.cfg` should then contain ``` # This file is generated from information provided by # the datasource. Changes to it will not persist across an instance. # To disable cloud-init's network configuration capabilities, write a file # /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following: # network: {config: disabled} auto lo iface lo inet loopback dns-nameservers 10.10.10.254 auto eth1 iface eth1 inet static address 10.10.101.20 gateway 10.10.101.1 netmask 255.255.255.0 ``` You will also notice that `/run/resolvconf/resolv.conf` or `/etc/resolv.conf` which is pointing to it will contain the desired dns server after boot-up. ``` # Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8) # DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN nameserver 10.10.10.254 ``` # Implementation Details cloud-init allows you to seed instance configuration using the following files located at `/var/lib/cloud/seed/nocloud-net`: * `user-data` (required) * `meta-data` (required) * `vendor-data` (optional) * `network-config` (optional) The network-config file is written to by lxd using data provided in templates that come with an image. This is governed by metadata.yaml but naming of the configuration keys and template content is not hard-coded as far as lxd is concerned - this is purely image data that can be modified if needed. * [NoCloud data source documentation](https://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html) * The source code for [NoCloud data source](https://git.launchpad.net/cloud-init/tree/cloudinit/sources/DataSourceNoCloud.py) * A good reference on which values you can use are [unit tests for cloud-init](https://git.launchpad.net/cloud-init/tree/tests/unittests/test_datasource/test_nocloud.py#n163) * [cloud-init directory layout](https://cloudinit.readthedocs.io/en/latest/topics/dir_layout.html) A default `cloud-init-network.tpl` provided with images from the "ubuntu:" image source looks like this: ``` {% if config\_get("user.network-config", "") == "" %}version: 1 config: - type: physical name: eth0 subnets: - type: {% if config_get("user.network_mode", "") == "link-local" %}manual{% else %}dhcp{% endif %} control: auto{% else %}{{ config_get("user.network-config", "") }}{% endif %} ``` The template syntax is the one used in the pongo2 template engine. A custom `config_get` function is defined to retrieve values from a container configuration. Options available with such a template structure: * Use DHCP by default on your eth0 interface; * Set `user.network_mode` to `link-local` and configure networking by hand; * Seed cloud-init by defining `user.network-config`. �����������������������������������������������������������������������������������������������������������������������lxd-2.0.11/doc/architectures.md���������������������������������������������������������������������0000644�0610621�0607500�00000002707�13172163242�017433� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Introduction LXD just like LXC can run on just about any architecture that's supported by the Linux kernel and by Go. Some objects in LXD are tied to an architecture, like the container, container snapshots and images. This document lists all the supported architectures, their unique identifier (used in the database), how they should be named and some notes. Please note that what LXD cares about is the kernel architecture, not the particular userspace flavor as determined by the toolchain. That means that LXD considers armv7 hard-float to be the same as armv7 soft-float and refers to both as "armv7". If useful to the user, the exact userspace ABI may be set as an image and container property, allowing easy query. # Architectures ID | Name | Notes | Personalities :--- | :--- | :---- | :------------ 1 | i686 | 32bit Intel x86 | 2 | x86\_64 | 64bit Intel x86 | x86 3 | armv7l | 32bit ARMv7 little-endian | 4 | aarch64 | 64bit ARMv8 little-endian | armv7 (optional) 5 | ppc | 32bit PowerPC big-endian | 6 | ppc64 | 64bit PowerPC big-endian | powerpc 7 | ppc64le | 64bit PowerPC little-endian | 8 | s390x | 64bit ESA/390 big-endian | The architecture names above are typically aligned with the Linux kernel architecture names. ���������������������������������������������������������lxd-2.0.11/doc/api-extensions.md��������������������������������������������������������������������0000644�0610621�0607500�00000001266�13172163242�017533� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������# API extensions The changes below were introduced to the LXD API after the 1.0 API was finalized. They are all backward compatible and can be detected by client tools by looking at the `api_extensions` field in `GET /1.0/`. ## id\_map Enables setting the `security.idmap.isolated` and `security.idmap.isolated`, `security.idmap.size`, and `raw.id_map` fields. ## id\_map\_base This introduces a new `security.idmap.base` allowing the user to skip the map auto-selection process for isolated containers and specify what host uid/gid to use as the base. ## instance\_types This adds the `instance_type` field to the container creation request. Its value is expanded to LXD resource limits. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/contributing.md��������������������������������������������������������������������������0000777�0610621�0607500�00000000000�13172163242�022315� 2doc/contributing.md���������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/config/����������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014736� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/config/bash/�����������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015653� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/config/bash/lxd-client�������������������������������������������������������������������0000644�0610621�0607500�00000012604�13172163242�017644� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������_have lxc && { _lxd_complete() { _lxd_names() { local state=$1 local keys=$2 local cmd="lxc list --fast" [ -n "$state" ] && cmd="$cmd | grep -E '$state'" COMPREPLY=( $( compgen -W \ "$( eval $cmd | grep -Ev '(\+--|NAME)' | awk '{print $2}' ) $keys" "$cur" ) ) } _lxd_images() { COMPREPLY=( $( compgen -W \ "$( lxc image list | tail -n +4 | awk '{print $2}' | egrep -v '^(\||^$)' )" "$cur" ) ) } _lxd_remotes() { COMPREPLY=( $( compgen -W \ "$( lxc remote list | tail -n +4 | awk '{print $2}' | egrep -v '^(\||^$)' )" "$cur" ) ) } _lxd_profiles() { COMPREPLY=( $( compgen -W "$( lxc profile list | tail -n +4 | awk '{print $2}' | egrep -v '^(\||^$)' )" "$cur" ) ) } COMPREPLY=() # ignore special --foo args if [[ ${COMP_WORDS[COMP_CWORD]} == -* ]]; then return 0 fi lxc_cmds="config copy delete exec file help image info init launch \ list move profile publish remote restart restore snapshot start stop \ version" global_keys="core.https_address core.https_allowed_origin \ core.https_allowed_methods core.https_allowed_headers core.proxy_https \ core.proxy_http core.proxy_ignore_host core.trust_password \ storage.lvm_vg_name storage.lvm_thinpool_name storage.lvm_fstype \ storage.lvm_volume_size storage.zfs_pool_name storage.zfs_remove_snapshots images.compression_algorithm \ images.remot_cache_expiry images.auto_update_interval \ images.auto_update_cached" container_keys="boot.autostart boot.autostart.delay boot.autostart.priority \ limits.cpu limits.cpu.allowance limits.cpu.priority limits.disk.priority \ limits.memory limits.memory.enforce limits.memory.swap \ limits.memory.swap.priority limits.network.priority limits.processes \ linux.kernel_modules raw.apparmor raw.lxc security.nesting \ security.privileged volatile.apply_template volatile.base_image \ volatile.last_state.idmap volatile.last_state.power user.network_mode \ user.meta-data user.user-data user.vendor-data" if [ $COMP_CWORD -eq 1 ]; then COMPREPLY=( $(compgen -W "$lxc_cmds" -- ${COMP_WORDS[COMP_CWORD]}) ) return 0 fi local no_dashargs cur=${COMP_WORDS[COMP_CWORD]} no_dashargs=(${COMP_WORDS[@]// -*}) pos=$((COMP_CWORD - (${#COMP_WORDS[@]} - ${#no_dashargs[@]}))) if [ -z "$cur" ]; then pos=$(($pos + 1)) fi case ${no_dashargs[1]} in "config") case $pos in 2) COMPREPLY=( $(compgen -W "device edit get set show trust" -- $cur) ) ;; 3) case ${no_dashargs[2]} in "trust") COMPREPLY=( $(compgen -W "list add remove" -- $cur) ) ;; "device") COMPREPLY=( $(compgen -W "add get set unset list show remove" -- $cur) ) ;; "show"|"edit") _lxd_names ;; "get"|"set"|"unset") _lxd_names "" "$global_keys" ;; esac ;; 4) case ${no_dashargs[2]} in "trust") _lxd_remotes ;; "device") _lxd_names ;; "get"|"set"|"unset") COMPREPLY=( $(compgen -W "$container_keys" -- $cur) ) ;; esac ;; esac ;; "copy") if [ $pos -lt 4 ]; then _lxd_names fi ;; "delete") _lxd_names ;; "exec") _lxd_names "RUNNING" ;; "file") COMPREPLY=( $(compgen -W "pull push edit" -- $cur) ) ;; "help") COMPREPLY=( $(compgen -W "$lxc_cmds" -- $cur) ) ;; "image") COMPREPLY=( $(compgen -W "import copy delete edit export info list show alias" -- $cur) ) ;; "info") _lxd_names ;; "init") _lxd_images ;; "launch") _lxd_images ;; "move") _lxd_names ;; "profile") case $pos in 2) COMPREPLY=( $(compgen -W "list copy delete apply device edit get set show" -- $cur) ) ;; 3) case ${no_dashargs[2]} in "device") COMPREPLY=( $(compgen -W "add get set unset list show remove" -- $cur) ) ;; *) _lxd_profiles ;; esac ;; 4) case ${no_dashargs[2]} in "device") _lxd_profiles ;; *) COMPREPLY=( $(compgen -W "$container_keys" -- $cur) ) ;; esac ;; esac ;; "publish") _lxd_names ;; "remote") COMPREPLY=( $(compgen -W \ "add remove list rename set-url set-default get-default" -- $cur) ) ;; "restart") _lxd_names ;; "restore") _lxd_names ;; "snapshot") _lxd_names ;; "start") _lxd_names "STOPPED|FROZEN" ;; "stop") _lxd_names "RUNNING" ;; *) ;; esac return 0 } complete -o default -F _lxd_complete lxc } ����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/config.go��������������������������������������������������������������������������������0000644�0610621�0607500�00000011216�13172163242�015266� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "io/ioutil" "os" "path" "path/filepath" "strings" "gopkg.in/yaml.v2" "github.com/lxc/lxd/shared" ) // Config holds settings to be used by a client or daemon. type Config struct { // DefaultRemote holds the remote daemon name from the Remotes map // that the client should communicate with by default. // If empty it defaults to "local". DefaultRemote string `yaml:"default-remote"` // Remotes defines a map of remote daemon names to the details for // communication with the named daemon. // The implicit "local" remote is always available and communicates // with the local daemon over a unix socket. Remotes map[string]RemoteConfig `yaml:"remotes"` // Command line aliases for `lxc` Aliases map[string]string `yaml:"aliases"` // This is the path to the config directory, so the client can find // previously stored server certs, give good error messages, and save // new server certs, etc. // // We don't need to store it, because of course once we've loaded this // structure we already know where it is :) ConfigDir string `yaml:"-"` } // RemoteConfig holds details for communication with a remote daemon. type RemoteConfig struct { Addr string `yaml:"addr"` Public bool `yaml:"public"` Protocol string `yaml:"protocol,omitempty"` Static bool `yaml:"-"` } var LocalRemote = RemoteConfig{ Addr: "unix://", Static: true, Public: false} var ImagesRemote = RemoteConfig{ Addr: "https://images.linuxcontainers.org", Public: true, Protocol: "simplestreams"} var UbuntuRemote = RemoteConfig{ Addr: "https://cloud-images.ubuntu.com/releases", Static: true, Public: true, Protocol: "simplestreams"} var UbuntuDailyRemote = RemoteConfig{ Addr: "https://cloud-images.ubuntu.com/daily", Static: true, Public: true, Protocol: "simplestreams"} var StaticRemotes = map[string]RemoteConfig{ "local": LocalRemote, "ubuntu": UbuntuRemote, "ubuntu-daily": UbuntuDailyRemote} var DefaultRemotes = map[string]RemoteConfig{ "images": ImagesRemote, "local": LocalRemote, "ubuntu": UbuntuRemote, "ubuntu-daily": UbuntuDailyRemote} var DefaultConfig = Config{ Remotes: DefaultRemotes, DefaultRemote: "local", Aliases: map[string]string{}, } // LoadConfig reads the configuration from the config path; if the path does // not exist, it returns a default configuration. func LoadConfig(path string) (*Config, error) { data, err := ioutil.ReadFile(path) if os.IsNotExist(err) { // A missing file is equivalent to the default configuration. withPath := DefaultConfig withPath.ConfigDir = filepath.Dir(path) return &withPath, nil } if err != nil { return nil, fmt.Errorf("cannot read config file: %v", err) } var c Config err = yaml.Unmarshal(data, &c) if err != nil { return nil, fmt.Errorf("cannot parse configuration: %v", err) } if c.Remotes == nil { c.Remotes = make(map[string]RemoteConfig) } c.ConfigDir = filepath.Dir(path) for k, v := range StaticRemotes { c.Remotes[k] = v } // NOTE: Remove this once we only see a small fraction of non-simplestreams users // Upgrade users to the "simplestreams" protocol images, ok := c.Remotes["images"] if ok && images.Protocol != ImagesRemote.Protocol && images.Addr == ImagesRemote.Addr { c.Remotes["images"] = ImagesRemote SaveConfig(&c, path) } return &c, nil } // SaveConfig writes the provided configuration to the config file. func SaveConfig(c *Config, fname string) error { for k := range StaticRemotes { delete(c.Remotes, k) } // Ignore errors on these two calls. Create will report any problems. os.Remove(fname + ".new") os.Mkdir(filepath.Dir(fname), 0700) f, err := os.Create(fname + ".new") if err != nil { return fmt.Errorf("cannot create config file: %v", err) } // If there are any errors, do not leave it around. defer f.Close() defer os.Remove(fname + ".new") data, err := yaml.Marshal(c) _, err = f.Write(data) if err != nil { return fmt.Errorf("cannot write configuration: %v", err) } f.Close() err = shared.FileMove(fname+".new", fname) if err != nil { return fmt.Errorf("cannot rename temporary config file: %v", err) } return nil } func (c *Config) ParseRemoteAndContainer(raw string) (string, string) { result := strings.SplitN(raw, ":", 2) if len(result) == 1 { return c.DefaultRemote, result[0] } return result[0], result[1] } func (c *Config) ParseRemote(raw string) string { return strings.SplitN(raw, ":", 2)[0] } func (c *Config) ConfigPath(file string) string { return path.Join(c.ConfigDir, file) } func (c *Config) ServerCertPath(name string) string { return path.Join(c.ConfigDir, "servercerts", fmt.Sprintf("%s.crt", name)) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client_linux_test.go���������������������������������������������������������������������0000644�0610621�0607500�00000002512�13172163242�017554� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "io/ioutil" "os" "syscall" "testing" ) func assertNoError(t *testing.T, err error, msg string) { if err != nil { t.Fatalf("Error: %s, action: %s", err, msg) } } func TestLocalLXDError(t *testing.T) { f, err := ioutil.TempFile("", "lxd-test.socket") assertNoError(t, err, "ioutil.TempFile to create fake socket file") defer os.RemoveAll(f.Name()) c := &Client{ Name: "test", Config: DefaultConfig, Remote: &RemoteConfig{ Addr: fmt.Sprintf("unix:%s", f.Name()), Static: true, Public: false, }, } runTest := func(exp error) { lxdErr := GetLocalLXDErr(connectViaUnix(c, c.Remote)) if lxdErr != exp { t.Fatalf("GetLocalLXDErr returned the wrong error, EXPECTED: %s, ACTUAL: %s", exp, lxdErr) } } // The fake socket file should mimic a socket with nobody listening. runTest(syscall.ECONNREFUSED) // Remove R/W permissions to mimic the user not having lxd group permissions. // Skip this test for root, as root ignores permissions and connect will fail // with ECONNREFUSED instead of EACCES. if os.Geteuid() != 0 { assertNoError(t, f.Chmod(0100), "f.Chmod on fake socket file") runTest(syscall.EACCES) } // Remove the fake socket to mimic LXD not being installed. assertNoError(t, os.RemoveAll(f.Name()), "osRemoveAll on fake socket file") runTest(syscall.ENOENT) } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/����������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�014747� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/util.go���������������������������������������������������������������������������0000644�0610621�0607500�00000007264�13172163242�016264� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "crypto/sha256" "fmt" "io" "net" "net/http" "net/url" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/cancel" "github.com/lxc/lxd/shared/ioprogress" ) func tlsHTTPClient(client *http.Client, tlsClientCert string, tlsClientKey string, tlsCA string, tlsServerCert string, insecureSkipVerify bool, proxy func(req *http.Request) (*url.URL, error)) (*http.Client, error) { // Get the TLS configuration tlsConfig, err := shared.GetTLSConfigMem(tlsClientCert, tlsClientKey, tlsCA, tlsServerCert, insecureSkipVerify) if err != nil { return nil, err } // Define the http transport transport := &http.Transport{ TLSClientConfig: tlsConfig, Dial: shared.RFC3493Dialer, Proxy: shared.ProxyFromEnvironment, DisableKeepAlives: true, } // Allow overriding the proxy if proxy != nil { transport.Proxy = proxy } // Define the http client if client == nil { client = &http.Client{} } client.Transport = transport // Setup redirect policy client.CheckRedirect = func(req *http.Request, via []*http.Request) error { // Replicate the headers req.Header = via[len(via)-1].Header return nil } return client, nil } func unixHTTPClient(client *http.Client, path string) (*http.Client, error) { // Setup a Unix socket dialer unixDial := func(network, addr string) (net.Conn, error) { raddr, err := net.ResolveUnixAddr("unix", path) if err != nil { return nil, err } return net.DialUnix("unix", nil, raddr) } // Define the http transport transport := &http.Transport{ Dial: unixDial, DisableKeepAlives: true, } // Define the http client if client == nil { client = &http.Client{} } client.Transport = transport // Setup redirect policy client.CheckRedirect = func(req *http.Request, via []*http.Request) error { // Replicate the headers req.Header = via[len(via)-1].Header return nil } return client, nil } func downloadFileSha256(httpClient *http.Client, useragent string, progress func(progress ProgressData), canceler *cancel.Canceler, filename string, url string, hash string, target io.WriteSeeker) (int64, error) { // Always seek to the beginning target.Seek(0, 0) // Prepare the download request req, err := http.NewRequest("GET", url, nil) if err != nil { return -1, err } if useragent != "" { req.Header.Set("User-Agent", useragent) } // Perform the request r, doneCh, err := cancel.CancelableDownload(canceler, httpClient, req) if err != nil { return -1, err } defer r.Body.Close() defer close(doneCh) if r.StatusCode != http.StatusOK { return -1, fmt.Errorf("Unable to fetch %s: %s", url, r.Status) } // Handle the data body := r.Body if progress != nil { body = &ioprogress.ProgressReader{ ReadCloser: r.Body, Tracker: &ioprogress.ProgressTracker{ Length: r.ContentLength, Handler: func(percent int64, speed int64) { if filename != "" { progress(ProgressData{Text: fmt.Sprintf("%s: %d%% (%s/s)", filename, percent, shared.GetByteSizeString(speed, 2))}) } else { progress(ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))}) } }, }, } } sha256 := sha256.New() size, err := io.Copy(io.MultiWriter(target, sha256), body) if err != nil { return -1, err } result := fmt.Sprintf("%x", sha256.Sum(nil)) if result != hash { return -1, fmt.Errorf("Hash mismatch for %s: %s != %s", url, result, hash) } return size, nil } type nullReadWriteCloser int func (nullReadWriteCloser) Close() error { return nil } func (nullReadWriteCloser) Write(p []byte) (int, error) { return len(p), nil } func (nullReadWriteCloser) Read(p []byte) (int, error) { return 0, io.EOF } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/simplestreams_images.go�����������������������������������������������������������0000644�0610621�0607500�00000013776�13172163242�021531� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "io" "io/ioutil" "os" "os/exec" "strings" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" ) // Image handling functions // GetImages returns a list of available images as Image structs func (r *ProtocolSimpleStreams) GetImages() ([]api.Image, error) { return r.ssClient.ListImages() } // GetImageFingerprints returns a list of available image fingerprints func (r *ProtocolSimpleStreams) GetImageFingerprints() ([]string, error) { // Get all the images from simplestreams images, err := r.ssClient.ListImages() if err != nil { return nil, err } // And now extract just the fingerprints fingerprints := []string{} for _, img := range images { fingerprints = append(fingerprints, img.Fingerprint) } return fingerprints, nil } // GetImage returns an Image struct for the provided fingerprint func (r *ProtocolSimpleStreams) GetImage(fingerprint string) (*api.Image, string, error) { image, err := r.ssClient.GetImage(fingerprint) if err != nil { return nil, "", err } return image, "", err } // GetImageFile downloads an image from the server, returning an ImageFileResponse struct func (r *ProtocolSimpleStreams) GetImageFile(fingerprint string, req ImageFileRequest) (*ImageFileResponse, error) { // Sanity checks if req.MetaFile == nil && req.RootfsFile == nil { return nil, fmt.Errorf("No file requested") } // Get the file list files, err := r.ssClient.GetFiles(fingerprint) if err != nil { return nil, err } // Prepare the response resp := ImageFileResponse{} // Download function download := func(path string, filename string, sha256 string, target io.WriteSeeker) (int64, error) { // Try over http url := fmt.Sprintf("http://%s/%s", strings.TrimPrefix(r.httpHost, "https://"), path) size, err := downloadFileSha256(r.http, r.httpUserAgent, req.ProgressHandler, req.Canceler, filename, url, sha256, target) if err != nil { // Try over https url = fmt.Sprintf("%s/%s", r.httpHost, path) size, err = downloadFileSha256(r.http, r.httpUserAgent, req.ProgressHandler, req.Canceler, filename, url, sha256, target) if err != nil { return -1, err } } return size, nil } // Download the LXD image file meta, ok := files["meta"] if ok && req.MetaFile != nil { size, err := download(meta.Path, "metadata", meta.Sha256, req.MetaFile) if err != nil { return nil, err } parts := strings.Split(meta.Path, "/") resp.MetaName = parts[len(parts)-1] resp.MetaSize = size } // Download the rootfs rootfs, ok := files["root"] if ok && req.RootfsFile != nil { // Look for deltas (requires xdelta3) downloaded := false _, err := exec.LookPath("xdelta3") if err == nil && req.DeltaSourceRetriever != nil { for filename, file := range files { if !strings.HasPrefix(filename, "root.delta-") { continue } // Check if we have the source file for the delta srcFingerprint := strings.Split(filename, "root.delta-")[1] srcPath := req.DeltaSourceRetriever(srcFingerprint, "rootfs") if srcPath == "" { continue } // Create temporary file for the delta deltaFile, err := ioutil.TempFile("", "lxc_image_") if err != nil { return nil, err } defer deltaFile.Close() defer os.Remove(deltaFile.Name()) // Download the delta _, err = download(file.Path, "rootfs delta", file.Sha256, deltaFile) if err != nil { return nil, err } // Create temporary file for the delta patchedFile, err := ioutil.TempFile("", "lxc_image_") if err != nil { return nil, err } defer patchedFile.Close() defer os.Remove(patchedFile.Name()) // Apply it _, err = shared.RunCommand("xdelta3", "-f", "-d", "-s", srcPath, deltaFile.Name(), patchedFile.Name()) if err != nil { return nil, err } // Copy to the target size, err := io.Copy(req.RootfsFile, patchedFile) if err != nil { return nil, err } parts := strings.Split(rootfs.Path, "/") resp.RootfsName = parts[len(parts)-1] resp.RootfsSize = size downloaded = true } } // Download the whole file if !downloaded { size, err := download(rootfs.Path, "rootfs", rootfs.Sha256, req.RootfsFile) if err != nil { return nil, err } parts := strings.Split(rootfs.Path, "/") resp.RootfsName = parts[len(parts)-1] resp.RootfsSize = size } } return &resp, nil } // GetImageSecret isn't relevant for the simplestreams protocol func (r *ProtocolSimpleStreams) GetImageSecret(fingerprint string) (string, error) { return "", fmt.Errorf("Private images aren't supported by the simplestreams protocol") } // GetPrivateImage isn't relevant for the simplestreams protocol func (r *ProtocolSimpleStreams) GetPrivateImage(fingerprint string, secret string) (*api.Image, string, error) { return nil, "", fmt.Errorf("Private images aren't supported by the simplestreams protocol") } // GetPrivateImageFile isn't relevant for the simplestreams protocol func (r *ProtocolSimpleStreams) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (*ImageFileResponse, error) { return nil, fmt.Errorf("Private images aren't supported by the simplestreams protocol") } // GetImageAliases returns the list of available aliases as ImageAliasesEntry structs func (r *ProtocolSimpleStreams) GetImageAliases() ([]api.ImageAliasesEntry, error) { return r.ssClient.ListAliases() } // GetImageAliasNames returns the list of available alias names func (r *ProtocolSimpleStreams) GetImageAliasNames() ([]string, error) { // Get all the images from simplestreams aliases, err := r.ssClient.ListAliases() if err != nil { return nil, err } // And now extract just the names names := []string{} for _, alias := range aliases { names = append(names, alias.Name) } return names, nil } // GetImageAlias returns an existing alias as an ImageAliasesEntry struct func (r *ProtocolSimpleStreams) GetImageAlias(name string) (*api.ImageAliasesEntry, string, error) { alias, err := r.ssClient.GetAlias(name) if err != nil { return nil, "", err } return alias, "", err } ��lxd-2.0.11/client/simplestreams.go������������������������������������������������������������������0000644�0610621�0607500�00000001700�13172163242�020164� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "net/http" "github.com/lxc/lxd/shared/simplestreams" ) // ProtocolSimpleStreams implements a SimpleStreams API client type ProtocolSimpleStreams struct { ssClient *simplestreams.SimpleStreams http *http.Client httpHost string httpUserAgent string httpCertificate string } // GetConnectionInfo returns the basic connection information used to interact with the server func (r *ProtocolSimpleStreams) GetConnectionInfo() (*ConnectionInfo, error) { info := ConnectionInfo{} info.Addresses = []string{r.httpHost} info.Certificate = r.httpCertificate info.Protocol = "simplestreams" return &info, nil } // GetHTTPClient returns the http client used for the connection. This can be used to set custom http options. func (r *ProtocolSimpleStreams) GetHTTPClient() (*http.Client, error) { if r.http == nil { return nil, fmt.Errorf("HTTP client isn't set, bad connection") } return r.http, nil } ����������������������������������������������������������������lxd-2.0.11/client/operations.go���������������������������������������������������������������������0000644�0610621�0607500�00000015432�13172163242�017466� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "encoding/json" "fmt" "sync" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared/api" ) // The Operation type represents an ongoing LXD operation (asynchronous processing) type Operation struct { api.Operation r *ProtocolLXD listener *EventListener handlerReady bool handlerLock sync.Mutex chActive chan bool } // AddHandler adds a function to be called whenever an event is received func (op *Operation) AddHandler(function func(api.Operation)) (*EventTarget, error) { // Make sure we have a listener setup err := op.setupListener() if err != nil { return nil, err } // Make sure we're not racing with ourselves op.handlerLock.Lock() defer op.handlerLock.Unlock() // If we're done already, just return if op.StatusCode.IsFinal() { return nil, nil } // Wrap the function to filter unwanted messages wrapped := func(data interface{}) { newOp := op.extractOperation(data) if newOp == nil { return } function(*newOp) } return op.listener.AddHandler([]string{"operation"}, wrapped) } // Cancel will request that LXD cancels the operation (if supported) func (op *Operation) Cancel() error { return op.r.DeleteOperation(op.ID) } // GetWebsocket returns a raw websocket connection from the operation func (op *Operation) GetWebsocket(secret string) (*websocket.Conn, error) { return op.r.GetOperationWebsocket(op.ID, secret) } // RemoveHandler removes a function to be called whenever an event is received func (op *Operation) RemoveHandler(target *EventTarget) error { // Make sure we're not racing with ourselves op.handlerLock.Lock() defer op.handlerLock.Unlock() // If the listener is gone, just return if op.listener == nil { return nil } return op.listener.RemoveHandler(target) } // Refresh pulls the current version of the operation and updates the struct func (op *Operation) Refresh() error { // Don't bother with a manual update if we are listening for events if op.handlerReady { return nil } // Get the current version of the operation newOp, _, err := op.r.GetOperation(op.ID) if err != nil { return err } // Update the operation struct op.Operation = *newOp return nil } // Wait lets you wait until the operation reaches a final state func (op *Operation) Wait() error { // Check if not done already if op.StatusCode.IsFinal() { if op.Err != "" { return fmt.Errorf(op.Err) } return nil } // Make sure we have a listener setup err := op.setupListener() if err != nil { return err } <-op.chActive // We're done, parse the result if op.Err != "" { return fmt.Errorf(op.Err) } return nil } func (op *Operation) setupListener() error { // Make sure we're not racing with ourselves op.handlerLock.Lock() defer op.handlerLock.Unlock() // We already have a listener setup if op.handlerReady { return nil } // Get a new listener if op.listener == nil { listener, err := op.r.GetEvents() if err != nil { return err } op.listener = listener } // Setup the handler chReady := make(chan bool) _, err := op.listener.AddHandler([]string{"operation"}, func(data interface{}) { <-chReady // Get an operation struct out of this data newOp := op.extractOperation(data) if newOp == nil { return } // We don't want concurrency while processing events op.handlerLock.Lock() defer op.handlerLock.Unlock() // Check if we're done already (because of another event) if op.listener == nil { return } // Update the struct op.Operation = *newOp // And check if we're done if op.StatusCode.IsFinal() { op.listener.Disconnect() op.listener = nil close(op.chActive) return } }) if err != nil { op.listener.Disconnect() op.listener = nil close(op.chActive) close(chReady) return err } // Monitor event listener go func() { <-chReady // We don't want concurrency while accessing the listener op.handlerLock.Lock() // Check if we're done already (because of another event) listener := op.listener if listener == nil { op.handlerLock.Unlock() return } op.handlerLock.Unlock() // Wait for the listener or operation to be done select { case <-listener.chActive: op.handlerLock.Lock() if op.listener != nil { op.Err = fmt.Sprintf("%v", listener.err) close(op.chActive) } op.handlerLock.Unlock() case <-op.chActive: return } }() // And do a manual refresh to avoid races err = op.Refresh() if err != nil { op.listener.Disconnect() op.listener = nil close(op.chActive) close(chReady) return err } // Check if not done already if op.StatusCode.IsFinal() { op.listener.Disconnect() op.listener = nil close(op.chActive) op.handlerReady = true close(chReady) if op.Err != "" { return fmt.Errorf(op.Err) } return nil } // Start processing background updates op.handlerReady = true close(chReady) return nil } func (op *Operation) extractOperation(data interface{}) *api.Operation { // Extract the metadata meta, ok := data.(map[string]interface{})["metadata"] if !ok { return nil } // And attempt to decode it as JSON operation data encoded, err := json.Marshal(meta) if err != nil { return nil } newOp := api.Operation{} err = json.Unmarshal(encoded, &newOp) if err != nil { return nil } // And now check that it's what we want if newOp.ID != op.ID { return nil } return &newOp } // The RemoteOperation type represents an ongoing LXD operation between two servers type RemoteOperation struct { targetOp *Operation handlers []func(api.Operation) chDone chan bool chPost chan bool err error } // AddHandler adds a function to be called whenever an event is received func (op *RemoteOperation) AddHandler(function func(api.Operation)) (*EventTarget, error) { var err error var target *EventTarget // Attach to the existing target operation if op.targetOp != nil { target, err = op.targetOp.AddHandler(function) if err != nil { return nil, err } } else { // Generate a mock EventTarget target = &EventTarget{ function: func(interface{}) { function(api.Operation{}) }, types: []string{"operation"}, } } // Add the handler to our list op.handlers = append(op.handlers, function) return target, nil } // CancelTarget attempts to cancel the target operation func (op *RemoteOperation) CancelTarget() error { if op.targetOp == nil { return fmt.Errorf("No associated target operation") } return op.targetOp.Cancel() } // GetTarget returns the target operation func (op *RemoteOperation) GetTarget() (*api.Operation, error) { if op.targetOp == nil { return nil, fmt.Errorf("No associated target operation") } return &op.targetOp.Operation, nil } // Wait lets you wait until the operation reaches a final state func (op *RemoteOperation) Wait() error { <-op.chDone if op.chPost != nil { <-op.chPost } return op.err } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_storage_volumes.go������������������������������������������������������������0000644�0610621�0607500�00000006257�13172163242�021375� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "strings" "github.com/lxc/lxd/shared/api" ) // Storage volumes handling function // GetStoragePoolVolumeNames returns the names of all volumes in a pool func (r *ProtocolLXD) GetStoragePoolVolumeNames(pool string) ([]string, error) { if !r.HasExtension("storage") { return nil, fmt.Errorf("The server is missing the required \"storage\" API extension") } urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/volumes", pool), nil, "", &urls) if err != nil { return nil, err } // Parse it names := []string{} for _, url := range urls { fields := strings.Split(url, fmt.Sprintf("/storage-pools/%s/volumes/", pool)) names = append(names, fields[len(fields)-1]) } return names, nil } // GetStoragePoolVolumes returns a list of StorageVolume entries for the provided pool func (r *ProtocolLXD) GetStoragePoolVolumes(pool string) ([]api.StorageVolume, error) { volumes := []api.StorageVolume{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/volumes?recursion=1", pool), nil, "", &volumes) if err != nil { return nil, err } return volumes, nil } // GetStoragePoolVolume returns a StorageVolume entry for the provided pool and volume name func (r *ProtocolLXD) GetStoragePoolVolume(pool string, volType string, name string) (*api.StorageVolume, string, error) { volume := api.StorageVolume{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", pool, volType, name), nil, "", &volume) if err != nil { return nil, "", err } return &volume, etag, nil } // CreateStoragePoolVolume defines a new storage volume func (r *ProtocolLXD) CreateStoragePoolVolume(pool string, volume api.StorageVolumesPost) error { // Send the request _, _, err := r.query("POST", fmt.Sprintf("/storage-pools/%s/volumes/%s", pool, volume.Type), volume, "") if err != nil { return err } return nil } // UpdateStoragePoolVolume updates the volume to match the provided StoragePoolVolume struct func (r *ProtocolLXD) UpdateStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", pool, volType, name), volume, ETag) if err != nil { return err } return nil } // DeleteStoragePoolVolume deletes a storage pool func (r *ProtocolLXD) DeleteStoragePoolVolume(pool string, volType string, name string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", pool, volType, name), nil, "") if err != nil { return err } return nil } // RenameStoragePoolVolume renames a storage volume func (r *ProtocolLXD) RenameStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePost) error { if !r.HasExtension("storage_api_volume_rename") { return fmt.Errorf("The server is missing the required \"storage_api_volume_rename\" API extension") } // Send the request _, _, err := r.query("POST", fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", pool, volType, name), volume, "") if err != nil { return err } return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_storage_pools.go��������������������������������������������������������������0000644�0610621�0607500�00000006011�13172163242�021023� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "strings" "github.com/lxc/lxd/shared/api" ) // Storage pool handling functions // GetStoragePoolNames returns the names of all storage pools func (r *ProtocolLXD) GetStoragePoolNames() ([]string, error) { if !r.HasExtension("storage") { return nil, fmt.Errorf("The server is missing the required \"storage\" API extension") } urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", "/storage-pools", nil, "", &urls) if err != nil { return nil, err } // Parse it names := []string{} for _, url := range urls { fields := strings.Split(url, "/storage-pools/") names = append(names, fields[len(fields)-1]) } return names, nil } // GetStoragePools returns a list of StoragePool entries func (r *ProtocolLXD) GetStoragePools() ([]api.StoragePool, error) { pools := []api.StoragePool{} // Fetch the raw value _, err := r.queryStruct("GET", "/storage-pools?recursion=1", nil, "", &pools) if err != nil { return nil, err } return pools, nil } // GetStoragePool returns a StoragePool entry for the provided pool name func (r *ProtocolLXD) GetStoragePool(name string) (*api.StoragePool, string, error) { pool := api.StoragePool{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s", name), nil, "", &pool) if err != nil { return nil, "", err } return &pool, etag, nil } // CreateStoragePool defines a new storage pool using the provided StoragePool struct func (r *ProtocolLXD) CreateStoragePool(pool api.StoragePoolsPost) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } if pool.Driver == "ceph" && !r.HasExtension("storage_driver_ceph") { return fmt.Errorf("The server is missing the required \"storage_driver_ceph\" API extension") } // Send the request _, _, err := r.query("POST", "/storage-pools", pool, "") if err != nil { return err } return nil } // UpdateStoragePool updates the pool to match the provided StoragePool struct func (r *ProtocolLXD) UpdateStoragePool(name string, pool api.StoragePoolPut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/storage-pools/%s", name), pool, ETag) if err != nil { return err } return nil } // DeleteStoragePool deletes a storage pool func (r *ProtocolLXD) DeleteStoragePool(name string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/storage-pools/%s", name), nil, "") if err != nil { return err } return nil } // GetStoragePoolResources gets the resources available to a given storage pool func (r *ProtocolLXD) GetStoragePoolResources(name string) (*api.ResourcesStoragePool, error) { if !r.HasExtension("resources") { return nil, fmt.Errorf("The server is missing the required \"resources\" API extension") } res := api.ResourcesStoragePool{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/resources", name), nil, "", &res) if err != nil { return nil, err } return &res, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_server.go���������������������������������������������������������������������0000644�0610621�0607500�00000003603�13172163242�017455� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" ) // Server handling functions // GetServer returns the server status as a Server struct func (r *ProtocolLXD) GetServer() (*api.Server, string, error) { server := api.Server{} // Fetch the raw value etag, err := r.queryStruct("GET", "", nil, "", &server) if err != nil { return nil, "", err } // Fill in certificate fingerprint if not provided if server.Environment.CertificateFingerprint == "" && server.Environment.Certificate != "" { var err error server.Environment.CertificateFingerprint, err = shared.CertFingerprintStr(server.Environment.Certificate) if err != nil { return nil, "", err } } if !server.Public && len(server.AuthMethods) == 0 { // TLS is always available for LXD servers server.AuthMethods = []string{"tls"} } // Add the value to the cache r.server = &server return &server, etag, nil } // UpdateServer updates the server status to match the provided Server struct func (r *ProtocolLXD) UpdateServer(server api.ServerPut, ETag string) error { // Send the request _, _, err := r.query("PUT", "", server, ETag) if err != nil { return err } return nil } // HasExtension returns true if the server supports a given API extension func (r *ProtocolLXD) HasExtension(extension string) bool { for _, entry := range r.server.APIExtensions { if entry == extension { return true } } return false } // GetServerResources returns the resources available to a given LXD server func (r *ProtocolLXD) GetServerResources() (*api.Resources, error) { if !r.HasExtension("resources") { return nil, fmt.Errorf("The server is missing the required \"resources\" API extension") } resources := api.Resources{} // Fetch the raw value _, err := r.queryStruct("GET", "/resources", nil, "", &resources) if err != nil { return nil, err } return &resources, nil } �����������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_profiles.go�������������������������������������������������������������������0000644�0610621�0607500�00000004375�13172163242�020001� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "strings" "github.com/lxc/lxd/shared/api" ) // Profile handling functions // GetProfileNames returns a list of available profile names func (r *ProtocolLXD) GetProfileNames() ([]string, error) { urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", "/profiles", nil, "", &urls) if err != nil { return nil, err } // Parse it names := []string{} for _, url := range urls { fields := strings.Split(url, "/profiles/") names = append(names, fields[len(fields)-1]) } return names, nil } // GetProfiles returns a list of available Profile structs func (r *ProtocolLXD) GetProfiles() ([]api.Profile, error) { profiles := []api.Profile{} // Fetch the raw value _, err := r.queryStruct("GET", "/profiles?recursion=1", nil, "", &profiles) if err != nil { return nil, err } return profiles, nil } // GetProfile returns a Profile entry for the provided name func (r *ProtocolLXD) GetProfile(name string) (*api.Profile, string, error) { profile := api.Profile{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/profiles/%s", name), nil, "", &profile) if err != nil { return nil, "", err } return &profile, etag, nil } // CreateProfile defines a new container profile func (r *ProtocolLXD) CreateProfile(profile api.ProfilesPost) error { // Send the request _, _, err := r.query("POST", "/profiles", profile, "") if err != nil { return err } return nil } // UpdateProfile updates the profile to match the provided Profile struct func (r *ProtocolLXD) UpdateProfile(name string, profile api.ProfilePut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/profiles/%s", name), profile, ETag) if err != nil { return err } return nil } // RenameProfile renames an existing profile entry func (r *ProtocolLXD) RenameProfile(name string, profile api.ProfilePost) error { // Send the request _, _, err := r.query("POST", fmt.Sprintf("/profiles/%s", name), profile, "") if err != nil { return err } return nil } // DeleteProfile deletes a profile func (r *ProtocolLXD) DeleteProfile(name string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/profiles/%s", name), nil, "") if err != nil { return err } return nil } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_operations.go�����������������������������������������������������������������0000644�0610621�0607500�00000002034�13172163242�020327� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared/api" ) // GetOperation returns an Operation entry for the provided uuid func (r *ProtocolLXD) GetOperation(uuid string) (*api.Operation, string, error) { op := api.Operation{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/operations/%s", uuid), nil, "", &op) if err != nil { return nil, "", err } return &op, etag, nil } // GetOperationWebsocket returns a websocket connection for the provided operation func (r *ProtocolLXD) GetOperationWebsocket(uuid string, secret string) (*websocket.Conn, error) { path := fmt.Sprintf("/operations/%s/websocket", uuid) if secret != "" { path = fmt.Sprintf("%s?secret=%s", path, secret) } return r.websocket(path) } // DeleteOperation deletes (cancels) a running operation func (r *ProtocolLXD) DeleteOperation(uuid string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/operations/%s", uuid), nil, "") if err != nil { return err } return nil } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_networks.go�������������������������������������������������������������������0000644�0610621�0607500�00000004544�13172163242�020030� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "strings" "github.com/lxc/lxd/shared/api" ) // GetNetworkNames returns a list of network names func (r *ProtocolLXD) GetNetworkNames() ([]string, error) { urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", "/networks", nil, "", &urls) if err != nil { return nil, err } // Parse it names := []string{} for _, url := range urls { fields := strings.Split(url, "/networks/") names = append(names, fields[len(fields)-1]) } return names, nil } // GetNetworks returns a list of Network struct func (r *ProtocolLXD) GetNetworks() ([]api.Network, error) { networks := []api.Network{} // Fetch the raw value _, err := r.queryStruct("GET", "/networks?recursion=1", nil, "", &networks) if err != nil { return nil, err } return networks, nil } // GetNetwork returns a Network entry for the provided name func (r *ProtocolLXD) GetNetwork(name string) (*api.Network, string, error) { network := api.Network{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/networks/%s", name), nil, "", &network) if err != nil { return nil, "", err } return &network, etag, nil } // CreateNetwork defines a new network using the provided Network struct func (r *ProtocolLXD) CreateNetwork(network api.NetworksPost) error { if !r.HasExtension("network") { return fmt.Errorf("The server is missing the required \"network\" API extension") } // Send the request _, _, err := r.query("POST", "/networks", network, "") if err != nil { return err } return nil } // UpdateNetwork updates the network to match the provided Network struct func (r *ProtocolLXD) UpdateNetwork(name string, network api.NetworkPut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/networks/%s", name), network, ETag) if err != nil { return err } return nil } // RenameNetwork renames an existing network entry func (r *ProtocolLXD) RenameNetwork(name string, network api.NetworkPost) error { // Send the request _, _, err := r.query("POST", fmt.Sprintf("/networks/%s", name), network, "") if err != nil { return err } return nil } // DeleteNetwork deletes an existing network func (r *ProtocolLXD) DeleteNetwork(name string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/networks/%s", name), nil, "") if err != nil { return err } return nil } ������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_images.go���������������������������������������������������������������������0000644�0610621�0607500�00000037135�13172163242�017423� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "crypto/sha256" "fmt" "io" "io/ioutil" "mime" "mime/multipart" "net/http" "net/url" "os" "strings" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/cancel" "github.com/lxc/lxd/shared/ioprogress" ) // Image handling functions // GetImages returns a list of available images as Image structs func (r *ProtocolLXD) GetImages() ([]api.Image, error) { images := []api.Image{} _, err := r.queryStruct("GET", "/images?recursion=1", nil, "", &images) if err != nil { return nil, err } return images, nil } // GetImageFingerprints returns a list of available image fingerprints func (r *ProtocolLXD) GetImageFingerprints() ([]string, error) { urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", "/images", nil, "", &urls) if err != nil { return nil, err } // Parse it fingerprints := []string{} for _, url := range urls { fields := strings.Split(url, "/images/") fingerprints = append(fingerprints, fields[len(fields)-1]) } return fingerprints, nil } // GetImage returns an Image struct for the provided fingerprint func (r *ProtocolLXD) GetImage(fingerprint string) (*api.Image, string, error) { return r.GetPrivateImage(fingerprint, "") } // GetImageFile downloads an image from the server, returning an ImageFileRequest struct func (r *ProtocolLXD) GetImageFile(fingerprint string, req ImageFileRequest) (*ImageFileResponse, error) { return r.GetPrivateImageFile(fingerprint, "", req) } // GetImageSecret is a helper around CreateImageSecret that returns a secret for the image func (r *ProtocolLXD) GetImageSecret(fingerprint string) (string, error) { op, err := r.CreateImageSecret(fingerprint) if err != nil { return "", err } return op.Metadata["secret"].(string), nil } // GetPrivateImage is similar to GetImage but allows passing a secret download token func (r *ProtocolLXD) GetPrivateImage(fingerprint string, secret string) (*api.Image, string, error) { image := api.Image{} // Build the API path path := fmt.Sprintf("/images/%s", fingerprint) if secret != "" { path = fmt.Sprintf("%s?secret=%s", path, secret) } // Fetch the raw value etag, err := r.queryStruct("GET", path, nil, "", &image) if err != nil { return nil, "", err } return &image, etag, nil } // GetPrivateImageFile is similar to GetImageFile but allows passing a secret download token func (r *ProtocolLXD) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (*ImageFileResponse, error) { // Sanity checks if req.MetaFile == nil && req.RootfsFile == nil { return nil, fmt.Errorf("No file requested") } // Prepare the response resp := ImageFileResponse{} // Build the URL url := fmt.Sprintf("%s/1.0/images/%s/export", r.httpHost, fingerprint) if secret != "" { url = fmt.Sprintf("%s?secret=%s", url, secret) } // Prepare the download request request, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } if r.httpUserAgent != "" { request.Header.Set("User-Agent", r.httpUserAgent) } // Start the request response, doneCh, err := cancel.CancelableDownload(req.Canceler, r.http, request) if err != nil { return nil, err } defer response.Body.Close() defer close(doneCh) if response.StatusCode != http.StatusOK { _, _, err := r.parseResponse(response) if err != nil { return nil, err } } ctype, ctypeParams, err := mime.ParseMediaType(response.Header.Get("Content-Type")) if err != nil { ctype = "application/octet-stream" } // Handle the data body := response.Body if req.ProgressHandler != nil { body = &ioprogress.ProgressReader{ ReadCloser: response.Body, Tracker: &ioprogress.ProgressTracker{ Length: response.ContentLength, Handler: func(percent int64, speed int64) { req.ProgressHandler(ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))}) }, }, } } // Hashing sha256 := sha256.New() // Deal with split images if ctype == "multipart/form-data" { if req.MetaFile == nil || req.RootfsFile == nil { return nil, fmt.Errorf("Multi-part image but only one target file provided") } // Parse the POST data mr := multipart.NewReader(body, ctypeParams["boundary"]) // Get the metadata tarball part, err := mr.NextPart() if err != nil { return nil, err } if part.FormName() != "metadata" { return nil, fmt.Errorf("Invalid multipart image") } size, err := io.Copy(io.MultiWriter(req.MetaFile, sha256), part) if err != nil { return nil, err } resp.MetaSize = size resp.MetaName = part.FileName() // Get the rootfs tarball part, err = mr.NextPart() if err != nil { return nil, err } if part.FormName() != "rootfs" { return nil, fmt.Errorf("Invalid multipart image") } size, err = io.Copy(io.MultiWriter(req.RootfsFile, sha256), part) if err != nil { return nil, err } resp.RootfsSize = size resp.RootfsName = part.FileName() // Check the hash hash := fmt.Sprintf("%x", sha256.Sum(nil)) if !strings.HasPrefix(hash, fingerprint) { return nil, fmt.Errorf("Image fingerprint doesn't match. Got %s expected %s", hash, fingerprint) } return &resp, nil } // Deal with unified images _, cdParams, err := mime.ParseMediaType(response.Header.Get("Content-Disposition")) if err != nil { return nil, err } filename, ok := cdParams["filename"] if !ok { return nil, fmt.Errorf("No filename in Content-Disposition header") } size, err := io.Copy(io.MultiWriter(req.MetaFile, sha256), body) if err != nil { return nil, err } resp.MetaSize = size resp.MetaName = filename // Check the hash hash := fmt.Sprintf("%x", sha256.Sum(nil)) if !strings.HasPrefix(hash, fingerprint) { return nil, fmt.Errorf("Image fingerprint doesn't match. Got %s expected %s", hash, fingerprint) } return &resp, nil } // GetImageAliases returns the list of available aliases as ImageAliasesEntry structs func (r *ProtocolLXD) GetImageAliases() ([]api.ImageAliasesEntry, error) { aliases := []api.ImageAliasesEntry{} // Fetch the raw value _, err := r.queryStruct("GET", "/images/aliases?recursion=1", nil, "", &aliases) if err != nil { return nil, err } return aliases, nil } // GetImageAliasNames returns the list of available alias names func (r *ProtocolLXD) GetImageAliasNames() ([]string, error) { urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", "/images/aliases", nil, "", &urls) if err != nil { return nil, err } // Parse it names := []string{} for _, url := range urls { fields := strings.Split(url, "/images/aliases/") names = append(names, fields[len(fields)-1]) } return names, nil } // GetImageAlias returns an existing alias as an ImageAliasesEntry struct func (r *ProtocolLXD) GetImageAlias(name string) (*api.ImageAliasesEntry, string, error) { alias := api.ImageAliasesEntry{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/images/aliases/%s", name), nil, "", &alias) if err != nil { return nil, "", err } return &alias, etag, nil } // CreateImage requests that LXD creates, copies or import a new image func (r *ProtocolLXD) CreateImage(image api.ImagesPost, args *ImageCreateArgs) (*Operation, error) { if image.CompressionAlgorithm != "" { if !r.HasExtension("image_compression_algorithm") { return nil, fmt.Errorf("The server is missing the required \"image_compression_algorithm\" API extension") } } // Send the JSON based request if args == nil { op, _, err := r.queryOperation("POST", "/images", image, "") if err != nil { return nil, err } return op, nil } // Prepare an image upload if args.MetaFile == nil { return nil, fmt.Errorf("Metadata file is required") } // Prepare the body var body io.Reader var contentType string if args.RootfsFile == nil { // If unified image, just pass it through body = args.MetaFile contentType = "application/octet-stream" } else { // If split image, we need mime encoding tmpfile, err := ioutil.TempFile("", "lxc_image_") if err != nil { return nil, err } defer os.Remove(tmpfile.Name()) // Setup the multipart writer w := multipart.NewWriter(tmpfile) // Metadata file fw, err := w.CreateFormFile("metadata", args.MetaName) if err != nil { return nil, err } _, err = io.Copy(fw, args.MetaFile) if err != nil { return nil, err } // Rootfs file fw, err = w.CreateFormFile("rootfs", args.RootfsName) if err != nil { return nil, err } _, err = io.Copy(fw, args.RootfsFile) if err != nil { return nil, err } // Done writing to multipart w.Close() // Figure out the size of the whole thing size, err := tmpfile.Seek(0, 2) if err != nil { return nil, err } _, err = tmpfile.Seek(0, 0) if err != nil { return nil, err } // Setup progress handler body = &ioprogress.ProgressReader{ ReadCloser: tmpfile, Tracker: &ioprogress.ProgressTracker{ Length: size, Handler: func(percent int64, speed int64) { args.ProgressHandler(ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))}) }, }, } contentType = w.FormDataContentType() } // Prepare the HTTP request reqURL := fmt.Sprintf("%s/1.0/images", r.httpHost) req, err := http.NewRequest("POST", reqURL, body) if err != nil { return nil, err } // Setup the headers req.Header.Set("Content-Type", contentType) if image.Public { req.Header.Set("X-LXD-public", "true") } if image.Filename != "" { req.Header.Set("X-LXD-filename", image.Filename) } if len(image.Properties) > 0 { imgProps := url.Values{} for k, v := range image.Properties { imgProps.Set(k, v) } req.Header.Set("X-LXD-properties", imgProps.Encode()) } // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Send the request resp, err := r.do(req) if err != nil { return nil, err } defer resp.Body.Close() // Handle errors response, _, err := r.parseResponse(resp) if err != nil { return nil, err } // Get to the operation respOperation, err := response.MetadataAsOperation() if err != nil { return nil, err } // Setup an Operation wrapper op := Operation{ Operation: *respOperation, r: r, chActive: make(chan bool), } return &op, nil } // tryCopyImage iterates through the source server URLs until one lets it download the image func (r *ProtocolLXD) tryCopyImage(req api.ImagesPost, urls []string) (*RemoteOperation, error) { if len(urls) == 0 { return nil, fmt.Errorf("The source server isn't listening on the network") } rop := RemoteOperation{ chDone: make(chan bool), } // For older servers, apply the aliases after copy if !r.HasExtension("image_create_aliases") && req.Aliases != nil { rop.chPost = make(chan bool) go func() { defer close(rop.chPost) // Wait for the main operation to finish <-rop.chDone if rop.err != nil { return } // Get the operation data op, err := rop.GetTarget() if err != nil { return } // Extract the fingerprint fingerprint := op.Metadata["fingerprint"].(string) // Add the aliases for _, entry := range req.Aliases { alias := api.ImageAliasesPost{} alias.Name = entry.Name alias.Target = fingerprint r.CreateImageAlias(alias) } }() } // Forward targetOp to remote op go func() { success := false errors := []string{} for _, serverURL := range urls { req.Source.Server = serverURL op, err := r.CreateImage(req, nil) if err != nil { errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err)) continue } rop.targetOp = op for _, handler := range rop.handlers { rop.targetOp.AddHandler(handler) } err = rop.targetOp.Wait() if err != nil { errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err)) continue } success = true break } if !success { rop.err = fmt.Errorf("Failed remote image download:\n - %s", strings.Join(errors, "\n - ")) } close(rop.chDone) }() return &rop, nil } // CopyImage copies an image from a remote server. Additional options can be passed using ImageCopyArgs func (r *ProtocolLXD) CopyImage(source ImageServer, image api.Image, args *ImageCopyArgs) (*RemoteOperation, error) { // Sanity checks if r == source { return nil, fmt.Errorf("The source and target servers must be different") } // Get source server connection information info, err := source.GetConnectionInfo() if err != nil { return nil, err } // Prepare the copy request req := api.ImagesPost{ Source: &api.ImagesPostSource{ ImageSource: api.ImageSource{ Certificate: info.Certificate, Protocol: info.Protocol, }, Fingerprint: image.Fingerprint, Mode: "pull", Type: "image", }, } // Generate secret token if needed if !image.Public { secret, err := source.GetImageSecret(image.Fingerprint) if err != nil { return nil, err } req.Source.Secret = secret } // Process the arguments if args != nil { req.Aliases = args.Aliases req.AutoUpdate = args.AutoUpdate req.Public = args.Public if args.CopyAliases { req.Aliases = image.Aliases if args.Aliases != nil { req.Aliases = append(req.Aliases, args.Aliases...) } } } return r.tryCopyImage(req, info.Addresses) } // UpdateImage updates the image definition func (r *ProtocolLXD) UpdateImage(fingerprint string, image api.ImagePut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/images/%s", fingerprint), image, ETag) if err != nil { return err } return nil } // DeleteImage requests that LXD removes an image from the store func (r *ProtocolLXD) DeleteImage(fingerprint string) (*Operation, error) { // Send the request op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/images/%s", fingerprint), nil, "") if err != nil { return nil, err } return op, nil } // RefreshImage requests that LXD issues an image refresh func (r *ProtocolLXD) RefreshImage(fingerprint string) (*Operation, error) { if !r.HasExtension("image_force_refresh") { return nil, fmt.Errorf("The server is missing the required \"image_force_refresh\" API extension") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/images/%s/refresh", fingerprint), nil, "") if err != nil { return nil, err } return op, nil } // CreateImageSecret requests that LXD issues a temporary image secret func (r *ProtocolLXD) CreateImageSecret(fingerprint string) (*Operation, error) { // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/images/%s/secret", fingerprint), nil, "") if err != nil { return nil, err } return op, nil } // CreateImageAlias sets up a new image alias func (r *ProtocolLXD) CreateImageAlias(alias api.ImageAliasesPost) error { // Send the request _, _, err := r.query("POST", "/images/aliases", alias, "") if err != nil { return err } return nil } // UpdateImageAlias updates the image alias definition func (r *ProtocolLXD) UpdateImageAlias(name string, alias api.ImageAliasesEntryPut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/images/aliases/%s", name), alias, ETag) if err != nil { return err } return nil } // RenameImageAlias renames an existing image alias func (r *ProtocolLXD) RenameImageAlias(name string, alias api.ImageAliasesEntryPost) error { // Send the request _, _, err := r.query("POST", fmt.Sprintf("/images/aliases/%s", name), alias, "") if err != nil { return err } return nil } // DeleteImageAlias removes an alias from the LXD image store func (r *ProtocolLXD) DeleteImageAlias(name string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/images/aliases/%s", name), nil, "") if err != nil { return err } return nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_events.go���������������������������������������������������������������������0000644�0610621�0607500�00000004567�13172163242�017465� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "encoding/json" "github.com/lxc/lxd/shared" ) // Event handling functions // GetEvents connects to the LXD monitoring interface func (r *ProtocolLXD) GetEvents() (*EventListener, error) { // Prevent anything else from interacting with the listeners r.eventListenersLock.Lock() defer r.eventListenersLock.Unlock() // Setup a new listener listener := EventListener{ r: r, chActive: make(chan bool), } if r.eventListeners != nil { // There is an existing Go routine setup, so just add another target r.eventListeners = append(r.eventListeners, &listener) return &listener, nil } // Initialize the list if needed r.eventListeners = []*EventListener{} // Setup a new connection with LXD conn, err := r.websocket("/events") if err != nil { return nil, err } // Add the listener r.eventListeners = append(r.eventListeners, &listener) // And spawn the listener go func() { for { r.eventListenersLock.Lock() if len(r.eventListeners) == 0 { // We don't need the connection anymore, disconnect conn.Close() r.eventListeners = nil r.eventListenersLock.Unlock() break } r.eventListenersLock.Unlock() _, data, err := conn.ReadMessage() if err != nil { // Prevent anything else from interacting with the listeners r.eventListenersLock.Lock() defer r.eventListenersLock.Unlock() // Tell all the current listeners about the failure for _, listener := range r.eventListeners { listener.err = err listener.disconnected = true close(listener.chActive) } // And remove them all from the list r.eventListeners = []*EventListener{} return } // Attempt to unpack the message message := make(map[string]interface{}) err = json.Unmarshal(data, &message) if err != nil { continue } // Extract the message type _, ok := message["type"] if !ok { continue } messageType := message["type"].(string) // Send the message to all handlers r.eventListenersLock.Lock() for _, listener := range r.eventListeners { listener.targetsLock.Lock() for _, target := range listener.targets { if target.types != nil && !shared.StringInSlice(messageType, target.types) { continue } go target.function(message) } listener.targetsLock.Unlock() } r.eventListenersLock.Unlock() } }() return &listener, nil } �����������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_containers.go�����������������������������������������������������������������0000644�0610621�0607500�00000107244�13172163242�020322� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "encoding/json" "fmt" "io" "net/http" "strings" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" ) // Container handling functions // GetContainerNames returns a list of container names func (r *ProtocolLXD) GetContainerNames() ([]string, error) { urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", "/containers", nil, "", &urls) if err != nil { return nil, err } // Parse it names := []string{} for _, url := range urls { fields := strings.Split(url, "/containers/") names = append(names, fields[len(fields)-1]) } return names, nil } // GetContainers returns a list of containers func (r *ProtocolLXD) GetContainers() ([]api.Container, error) { containers := []api.Container{} // Fetch the raw value _, err := r.queryStruct("GET", "/containers?recursion=1", nil, "", &containers) if err != nil { return nil, err } return containers, nil } // GetContainer returns the container entry for the provided name func (r *ProtocolLXD) GetContainer(name string) (*api.Container, string, error) { container := api.Container{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s", name), nil, "", &container) if err != nil { return nil, "", err } return &container, etag, nil } // CreateContainer requests that LXD creates a new container func (r *ProtocolLXD) CreateContainer(container api.ContainersPost) (*Operation, error) { if container.Source.ContainerOnly { if !r.HasExtension("container_only_migration") { return nil, fmt.Errorf("The server is missing the required \"container_only_migration\" API extension") } } // Send the request op, _, err := r.queryOperation("POST", "/containers", container, "") if err != nil { return nil, err } return op, nil } func (r *ProtocolLXD) tryCreateContainer(req api.ContainersPost, urls []string) (*RemoteOperation, error) { if len(urls) == 0 { return nil, fmt.Errorf("The source server isn't listening on the network") } rop := RemoteOperation{ chDone: make(chan bool), } operation := req.Source.Operation // Forward targetOp to remote op go func() { success := false errors := []string{} for _, serverURL := range urls { if operation == "" { req.Source.Server = serverURL } else { req.Source.Operation = fmt.Sprintf("%s/1.0/operations/%s", serverURL, operation) } op, err := r.CreateContainer(req) if err != nil { errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err)) continue } rop.targetOp = op for _, handler := range rop.handlers { rop.targetOp.AddHandler(handler) } err = rop.targetOp.Wait() if err != nil { errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err)) continue } success = true break } if !success { rop.err = fmt.Errorf("Failed container creation:\n - %s", strings.Join(errors, "\n - ")) } close(rop.chDone) }() return &rop, nil } // CreateContainerFromImage is a convenience function to make it easier to create a container from an existing image func (r *ProtocolLXD) CreateContainerFromImage(source ImageServer, image api.Image, req api.ContainersPost) (*RemoteOperation, error) { // Set the minimal source fields req.Source.Type = "image" // Optimization for the local image case if r == source { // Always use fingerprints for local case req.Source.Fingerprint = image.Fingerprint req.Source.Alias = "" op, err := r.CreateContainer(req) if err != nil { return nil, err } rop := RemoteOperation{ targetOp: op, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil } // Minimal source fields for remote image req.Source.Mode = "pull" // If we have an alias and the image is public, use that if req.Source.Alias != "" && image.Public { req.Source.Fingerprint = "" } else { req.Source.Fingerprint = image.Fingerprint req.Source.Alias = "" } // Get source server connection information info, err := source.GetConnectionInfo() if err != nil { return nil, err } req.Source.Protocol = info.Protocol req.Source.Certificate = info.Certificate // Generate secret token if needed if !image.Public { secret, err := source.GetImageSecret(image.Fingerprint) if err != nil { return nil, err } req.Source.Secret = secret } return r.tryCreateContainer(req, info.Addresses) } // CopyContainer copies a container from a remote server. Additional options can be passed using ContainerCopyArgs func (r *ProtocolLXD) CopyContainer(source ContainerServer, container api.Container, args *ContainerCopyArgs) (*RemoteOperation, error) { // Base request req := api.ContainersPost{ Name: container.Name, ContainerPut: container.Writable(), } req.Source.BaseImage = container.Config["volatile.base_image"] // Process the copy arguments if args != nil { // Sanity checks if args.ContainerOnly { if !r.HasExtension("container_only_migration") { return nil, fmt.Errorf("The target server is missing the required \"container_only_migration\" API extension") } if !source.HasExtension("container_only_migration") { return nil, fmt.Errorf("The source server is missing the required \"container_only_migration\" API extension") } } if shared.StringInSlice(args.Mode, []string{"push", "relay"}) { if !r.HasExtension("container_push") { return nil, fmt.Errorf("The target server is missing the required \"container_push\" API extension") } if !source.HasExtension("container_push") { return nil, fmt.Errorf("The source server is missing the required \"container_push\" API extension") } } if args.Mode == "push" && !source.HasExtension("container_push_target") { return nil, fmt.Errorf("The source server is missing the required \"container_push_target\" API extension") } // Allow overriding the target name if args.Name != "" { req.Name = args.Name } req.Source.Live = args.Live req.Source.ContainerOnly = args.ContainerOnly } if req.Source.Live { req.Source.Live = container.StatusCode == api.Running } // Optimization for the local copy case if r == source { // Local copy source fields req.Source.Type = "copy" req.Source.Source = container.Name // Copy the container op, err := r.CreateContainer(req) if err != nil { return nil, err } rop := RemoteOperation{ targetOp: op, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil } // Source request sourceReq := api.ContainerPost{ Migration: true, Live: req.Source.Live, ContainerOnly: req.Source.ContainerOnly, } // Push mode migration if args != nil && args.Mode == "push" { // Get target server connection information info, err := r.GetConnectionInfo() if err != nil { return nil, err } // Create the container req.Source.Type = "migration" req.Source.Mode = "push" op, err := r.CreateContainer(req) if err != nil { return nil, err } targetSecrets := map[string]string{} for k, v := range op.Metadata { targetSecrets[k] = v.(string) } // Prepare the source request target := api.ContainerPostTarget{} target.Operation = op.ID target.Websockets = targetSecrets target.Certificate = info.Certificate sourceReq.Target = &target return r.tryMigrateContainer(source, container.Name, sourceReq, info.Addresses) } // Get source server connection information info, err := source.GetConnectionInfo() if err != nil { return nil, err } op, err := source.MigrateContainer(container.Name, sourceReq) if err != nil { return nil, err } sourceSecrets := map[string]string{} for k, v := range op.Metadata { sourceSecrets[k] = v.(string) } // Relay mode migration if args != nil && args.Mode == "relay" { // Push copy source fields req.Source.Type = "migration" req.Source.Mode = "push" // Start the process targetOp, err := r.CreateContainer(req) if err != nil { return nil, err } // Extract the websockets targetSecrets := map[string]string{} for k, v := range targetOp.Metadata { targetSecrets[k] = v.(string) } // Launch the relay err = r.proxyMigration(targetOp, targetSecrets, source, op, sourceSecrets) if err != nil { return nil, err } // Prepare a tracking operation rop := RemoteOperation{ targetOp: targetOp, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil } // Pull mode migration req.Source.Type = "migration" req.Source.Mode = "pull" req.Source.Operation = op.ID req.Source.Websockets = sourceSecrets req.Source.Certificate = info.Certificate return r.tryCreateContainer(req, info.Addresses) } func (r *ProtocolLXD) proxyMigration(targetOp *Operation, targetSecrets map[string]string, source ContainerServer, sourceOp *Operation, sourceSecrets map[string]string) error { // Sanity checks for n := range targetSecrets { _, ok := sourceSecrets[n] if !ok { return fmt.Errorf("Migration target expects the \"%s\" socket but source isn't providing it", n) } } if targetSecrets["control"] == "" { return fmt.Errorf("Migration target didn't setup the required \"control\" socket") } // Struct used to hold everything together type proxy struct { done chan bool sourceConn *websocket.Conn targetConn *websocket.Conn } proxies := map[string]*proxy{} // Connect the control socket sourceConn, err := source.GetOperationWebsocket(sourceOp.ID, sourceSecrets["control"]) if err != nil { return err } targetConn, err := r.GetOperationWebsocket(targetOp.ID, targetSecrets["control"]) if err != nil { return err } proxies["control"] = &proxy{ done: shared.WebsocketProxy(sourceConn, targetConn), sourceConn: sourceConn, targetConn: targetConn, } // Connect the data sockets for name := range sourceSecrets { if name == "control" { continue } // Handle resets (used for multiple objects) sourceConn, err := source.GetOperationWebsocket(sourceOp.ID, sourceSecrets[name]) if err != nil { break } targetConn, err := r.GetOperationWebsocket(targetOp.ID, targetSecrets[name]) if err != nil { break } proxies[name] = &proxy{ sourceConn: sourceConn, targetConn: targetConn, done: shared.WebsocketProxy(sourceConn, targetConn), } } // Cleanup once everything is done go func() { // Wait for control socket <-proxies["control"].done proxies["control"].sourceConn.Close() proxies["control"].targetConn.Close() // Then deal with the others for name, proxy := range proxies { if name == "control" { continue } <-proxy.done proxy.sourceConn.Close() proxy.targetConn.Close() } }() return nil } // UpdateContainer updates the container definition func (r *ProtocolLXD) UpdateContainer(name string, container api.ContainerPut, ETag string) (*Operation, error) { // Send the request op, _, err := r.queryOperation("PUT", fmt.Sprintf("/containers/%s", name), container, ETag) if err != nil { return nil, err } return op, nil } // RenameContainer requests that LXD renames the container func (r *ProtocolLXD) RenameContainer(name string, container api.ContainerPost) (*Operation, error) { // Sanity check if container.Migration { return nil, fmt.Errorf("Can't ask for a migration through RenameContainer") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s", name), container, "") if err != nil { return nil, err } return op, nil } func (r *ProtocolLXD) tryMigrateContainer(source ContainerServer, name string, req api.ContainerPost, urls []string) (*RemoteOperation, error) { if len(urls) == 0 { return nil, fmt.Errorf("The target server isn't listening on the network") } rop := RemoteOperation{ chDone: make(chan bool), } operation := req.Target.Operation // Forward targetOp to remote op go func() { success := false errors := []string{} for _, serverURL := range urls { req.Target.Operation = fmt.Sprintf("%s/1.0/operations/%s", serverURL, operation) op, err := source.MigrateContainer(name, req) if err != nil { errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err)) continue } rop.targetOp = op for _, handler := range rop.handlers { rop.targetOp.AddHandler(handler) } err = rop.targetOp.Wait() if err != nil { errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err)) continue } success = true break } if !success { rop.err = fmt.Errorf("Failed container migration:\n - %s", strings.Join(errors, "\n - ")) } close(rop.chDone) }() return &rop, nil } // MigrateContainer requests that LXD prepares for a container migration func (r *ProtocolLXD) MigrateContainer(name string, container api.ContainerPost) (*Operation, error) { if container.ContainerOnly { if !r.HasExtension("container_only_migration") { return nil, fmt.Errorf("The server is missing the required \"container_only_migration\" API extension") } } // Sanity check if !container.Migration { return nil, fmt.Errorf("Can't ask for a rename through MigrateContainer") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s", name), container, "") if err != nil { return nil, err } return op, nil } // DeleteContainer requests that LXD deletes the container func (r *ProtocolLXD) DeleteContainer(name string) (*Operation, error) { // Send the request op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/containers/%s", name), nil, "") if err != nil { return nil, err } return op, nil } // ExecContainer requests that LXD spawns a command inside the container func (r *ProtocolLXD) ExecContainer(containerName string, exec api.ContainerExecPost, args *ContainerExecArgs) (*Operation, error) { if exec.RecordOutput { if !r.HasExtension("container_exec_recording") { return nil, fmt.Errorf("The server is missing the required \"container_exec_recording\" API extension") } } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/exec", containerName), exec, "") if err != nil { return nil, err } // Process additional arguments if args != nil { // Parse the fds fds := map[string]string{} value, ok := op.Metadata["fds"] if ok { values := value.(map[string]interface{}) for k, v := range values { fds[k] = v.(string) } } // Call the control handler with a connection to the control socket if args.Control != nil && fds["control"] != "" { conn, err := r.GetOperationWebsocket(op.ID, fds["control"]) if err != nil { return nil, err } go args.Control(conn) } if exec.Interactive { // Handle interactive sections if args.Stdin != nil && args.Stdout != nil { // Connect to the websocket conn, err := r.GetOperationWebsocket(op.ID, fds["0"]) if err != nil { return nil, err } // And attach stdin and stdout to it go func() { shared.WebsocketSendStream(conn, args.Stdin, -1) <-shared.WebsocketRecvStream(args.Stdout, conn) conn.Close() if args.DataDone != nil { close(args.DataDone) } }() } else { if args.DataDone != nil { close(args.DataDone) } } } else { // Handle non-interactive sessions dones := map[int]chan bool{} conns := []*websocket.Conn{} // Handle stdin if fds["0"] != "" { conn, err := r.GetOperationWebsocket(op.ID, fds["0"]) if err != nil { return nil, err } conns = append(conns, conn) dones[0] = shared.WebsocketSendStream(conn, args.Stdin, -1) } // Handle stdout if fds["1"] != "" { conn, err := r.GetOperationWebsocket(op.ID, fds["1"]) if err != nil { return nil, err } conns = append(conns, conn) dones[1] = shared.WebsocketRecvStream(args.Stdout, conn) } // Handle stderr if fds["2"] != "" { conn, err := r.GetOperationWebsocket(op.ID, fds["2"]) if err != nil { return nil, err } conns = append(conns, conn) dones[2] = shared.WebsocketRecvStream(args.Stderr, conn) } // Wait for everything to be done go func() { for i, chDone := range dones { // Skip stdin, dealing with it separately below if i == 0 { continue } <-chDone } if fds["0"] != "" { args.Stdin.Close() } for _, conn := range conns { conn.Close() } if args.DataDone != nil { close(args.DataDone) } }() } } return op, nil } // GetContainerFile retrieves the provided path from the container func (r *ProtocolLXD) GetContainerFile(containerName string, path string) (io.ReadCloser, *ContainerFileResponse, error) { // Prepare the HTTP request requestURL, err := shared.URLEncode( fmt.Sprintf("%s/1.0/containers/%s/files", r.httpHost, containerName), map[string]string{"path": path}) if err != nil { return nil, nil, err } req, err := http.NewRequest("GET", requestURL, nil) if err != nil { return nil, nil, err } // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Send the request resp, err := r.do(req) if err != nil { return nil, nil, err } // Check the return value for a cleaner error if resp.StatusCode != http.StatusOK { _, _, err := r.parseResponse(resp) if err != nil { return nil, nil, err } } // Parse the headers uid, gid, mode, fileType, _ := shared.ParseLXDFileHeaders(resp.Header) fileResp := ContainerFileResponse{ UID: uid, GID: gid, Mode: mode, Type: fileType, } if fileResp.Type == "directory" { // Decode the response response := api.Response{} decoder := json.NewDecoder(resp.Body) err = decoder.Decode(&response) if err != nil { return nil, nil, err } // Get the file list entries := []string{} err = response.MetadataAsStruct(&entries) if err != nil { return nil, nil, err } fileResp.Entries = entries return nil, &fileResp, err } return resp.Body, &fileResp, err } // CreateContainerFile tells LXD to create a file in the container func (r *ProtocolLXD) CreateContainerFile(containerName string, path string, args ContainerFileArgs) error { if args.Type == "directory" { if !r.HasExtension("directory_manipulation") { return fmt.Errorf("The server is missing the required \"directory_manipulation\" API extension") } } if args.Type == "symlink" { if !r.HasExtension("file_symlinks") { return fmt.Errorf("The server is missing the required \"file_symlinks\" API extension") } } if args.WriteMode == "append" { if !r.HasExtension("file_append") { return fmt.Errorf("The server is missing the required \"file_append\" API extension") } } // Prepare the HTTP request requestURL, err := shared.URLEncode( fmt.Sprintf("%s/1.0/containers/%s/files", r.httpHost, containerName), map[string]string{"path": path}) if err != nil { return err } req, err := http.NewRequest("POST", requestURL, args.Content) if err != nil { return err } // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Set the various headers if args.UID > -1 { req.Header.Set("X-LXD-uid", fmt.Sprintf("%d", args.UID)) } if args.GID > -1 { req.Header.Set("X-LXD-gid", fmt.Sprintf("%d", args.GID)) } if args.Mode > -1 { req.Header.Set("X-LXD-mode", fmt.Sprintf("%04o", args.Mode)) } if args.Type != "" { req.Header.Set("X-LXD-type", args.Type) } if args.WriteMode != "" { req.Header.Set("X-LXD-write", args.WriteMode) } // Send the request resp, err := r.do(req) if err != nil { return err } // Check the return value for a cleaner error _, _, err = r.parseResponse(resp) if err != nil { return err } return nil } // DeleteContainerFile deletes a file in the container func (r *ProtocolLXD) DeleteContainerFile(containerName string, path string) error { if !r.HasExtension("file_delete") { return fmt.Errorf("The server is missing the required \"file_delete\" API extension") } // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/containers/%s/files?path=%s", containerName, path), nil, "") if err != nil { return err } return nil } // GetContainerSnapshotNames returns a list of snapshot names for the container func (r *ProtocolLXD) GetContainerSnapshotNames(containerName string) ([]string, error) { urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/snapshots", containerName), nil, "", &urls) if err != nil { return nil, err } // Parse it names := []string{} for _, url := range urls { fields := strings.Split(url, fmt.Sprintf("/containers/%s/snapshots/", containerName)) names = append(names, fields[len(fields)-1]) } return names, nil } // GetContainerSnapshots returns a list of snapshots for the container func (r *ProtocolLXD) GetContainerSnapshots(containerName string) ([]api.ContainerSnapshot, error) { snapshots := []api.ContainerSnapshot{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/snapshots?recursion=1", containerName), nil, "", &snapshots) if err != nil { return nil, err } return snapshots, nil } // GetContainerSnapshot returns a Snapshot struct for the provided container and snapshot names func (r *ProtocolLXD) GetContainerSnapshot(containerName string, name string) (*api.ContainerSnapshot, string, error) { snapshot := api.ContainerSnapshot{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/snapshots/%s", containerName, name), nil, "", &snapshot) if err != nil { return nil, "", err } return &snapshot, etag, nil } // CreateContainerSnapshot requests that LXD creates a new snapshot for the container func (r *ProtocolLXD) CreateContainerSnapshot(containerName string, snapshot api.ContainerSnapshotsPost) (*Operation, error) { // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/snapshots", containerName), snapshot, "") if err != nil { return nil, err } return op, nil } // CopyContainerSnapshot copies a snapshot from a remote server into a new container. Additional options can be passed using ContainerCopyArgs func (r *ProtocolLXD) CopyContainerSnapshot(source ContainerServer, snapshot api.ContainerSnapshot, args *ContainerSnapshotCopyArgs) (*RemoteOperation, error) { // Base request fields := strings.SplitN(snapshot.Name, shared.SnapshotDelimiter, 2) cName := fields[0] sName := fields[1] req := api.ContainersPost{ Name: cName, ContainerPut: api.ContainerPut{ Architecture: snapshot.Architecture, Config: snapshot.Config, Devices: snapshot.Devices, Ephemeral: snapshot.Ephemeral, Profiles: snapshot.Profiles, }, } if snapshot.Stateful && args.Live { if !r.HasExtension("container_snapshot_stateful_migration") { return nil, fmt.Errorf("The server is missing the required \"container_snapshot_stateful_migration\" API extension") } req.ContainerPut.Stateful = snapshot.Stateful req.Source.Live = args.Live } req.Source.BaseImage = snapshot.Config["volatile.base_image"] // Process the copy arguments if args != nil { // Sanity checks if shared.StringInSlice(args.Mode, []string{"push", "relay"}) { if !r.HasExtension("container_push") { return nil, fmt.Errorf("The target server is missing the required \"container_push\" API extension") } if !source.HasExtension("container_push") { return nil, fmt.Errorf("The source server is missing the required \"container_push\" API extension") } } if args.Mode == "push" && !source.HasExtension("container_push_target") { return nil, fmt.Errorf("The source server is missing the required \"container_push_target\" API extension") } // Allow overriding the target name if args.Name != "" { req.Name = args.Name } } // Optimization for the local copy case if r == source { // Local copy source fields req.Source.Type = "copy" req.Source.Source = snapshot.Name // Copy the container op, err := r.CreateContainer(req) if err != nil { return nil, err } rop := RemoteOperation{ targetOp: op, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil } // Source request sourceReq := api.ContainerSnapshotPost{ Migration: true, Name: args.Name, } if snapshot.Stateful && args.Live { sourceReq.Live = args.Live } // Push mode migration if args != nil && args.Mode == "push" { // Get target server connection information info, err := r.GetConnectionInfo() if err != nil { return nil, err } // Create the container req.Source.Type = "migration" req.Source.Mode = "push" op, err := r.CreateContainer(req) if err != nil { return nil, err } targetSecrets := map[string]string{} for k, v := range op.Metadata { targetSecrets[k] = v.(string) } // Prepare the source request target := api.ContainerPostTarget{} target.Operation = op.ID target.Websockets = targetSecrets target.Certificate = info.Certificate sourceReq.Target = &target return r.tryMigrateContainerSnapshot(source, cName, sName, sourceReq, info.Addresses) } // Get source server connection information info, err := source.GetConnectionInfo() if err != nil { return nil, err } op, err := source.MigrateContainerSnapshot(cName, sName, sourceReq) if err != nil { return nil, err } sourceSecrets := map[string]string{} for k, v := range op.Metadata { sourceSecrets[k] = v.(string) } // Relay mode migration if args != nil && args.Mode == "relay" { // Push copy source fields req.Source.Type = "migration" req.Source.Mode = "push" // Start the process targetOp, err := r.CreateContainer(req) if err != nil { return nil, err } // Extract the websockets targetSecrets := map[string]string{} for k, v := range targetOp.Metadata { targetSecrets[k] = v.(string) } // Launch the relay err = r.proxyMigration(targetOp, targetSecrets, source, op, sourceSecrets) if err != nil { return nil, err } // Prepare a tracking operation rop := RemoteOperation{ targetOp: targetOp, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil } // Pull mode migration req.Source.Type = "migration" req.Source.Mode = "pull" req.Source.Operation = op.ID req.Source.Websockets = sourceSecrets req.Source.Certificate = info.Certificate return r.tryCreateContainer(req, info.Addresses) } // RenameContainerSnapshot requests that LXD renames the snapshot func (r *ProtocolLXD) RenameContainerSnapshot(containerName string, name string, container api.ContainerSnapshotPost) (*Operation, error) { // Sanity check if container.Migration { return nil, fmt.Errorf("Can't ask for a migration through RenameContainerSnapshot") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/snapshots/%s", containerName, name), container, "") if err != nil { return nil, err } return op, nil } func (r *ProtocolLXD) tryMigrateContainerSnapshot(source ContainerServer, containerName string, name string, req api.ContainerSnapshotPost, urls []string) (*RemoteOperation, error) { if len(urls) == 0 { return nil, fmt.Errorf("The target server isn't listening on the network") } rop := RemoteOperation{ chDone: make(chan bool), } operation := req.Target.Operation // Forward targetOp to remote op go func() { success := false errors := []string{} for _, serverURL := range urls { req.Target.Operation = fmt.Sprintf("%s/1.0/operations/%s", serverURL, operation) op, err := source.MigrateContainerSnapshot(containerName, name, req) if err != nil { errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err)) continue } rop.targetOp = op for _, handler := range rop.handlers { rop.targetOp.AddHandler(handler) } err = rop.targetOp.Wait() if err != nil { errors = append(errors, fmt.Sprintf("%s: %v", serverURL, err)) continue } success = true break } if !success { rop.err = fmt.Errorf("Failed container migration:\n - %s", strings.Join(errors, "\n - ")) } close(rop.chDone) }() return &rop, nil } // MigrateContainerSnapshot requests that LXD prepares for a snapshot migration func (r *ProtocolLXD) MigrateContainerSnapshot(containerName string, name string, container api.ContainerSnapshotPost) (*Operation, error) { // Sanity check if !container.Migration { return nil, fmt.Errorf("Can't ask for a rename through MigrateContainerSnapshot") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/snapshots/%s", containerName, name), container, "") if err != nil { return nil, err } return op, nil } // DeleteContainerSnapshot requests that LXD deletes the container snapshot func (r *ProtocolLXD) DeleteContainerSnapshot(containerName string, name string) (*Operation, error) { // Send the request op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/containers/%s/snapshots/%s", containerName, name), nil, "") if err != nil { return nil, err } return op, nil } // GetContainerState returns a ContainerState entry for the provided container name func (r *ProtocolLXD) GetContainerState(name string) (*api.ContainerState, string, error) { state := api.ContainerState{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/state", name), nil, "", &state) if err != nil { return nil, "", err } return &state, etag, nil } // UpdateContainerState updates the container to match the requested state func (r *ProtocolLXD) UpdateContainerState(name string, state api.ContainerStatePut, ETag string) (*Operation, error) { // Send the request op, _, err := r.queryOperation("PUT", fmt.Sprintf("/containers/%s/state", name), state, ETag) if err != nil { return nil, err } return op, nil } // GetContainerLogfiles returns a list of logfiles for the container func (r *ProtocolLXD) GetContainerLogfiles(name string) ([]string, error) { urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/logs", name), nil, "", &urls) if err != nil { return nil, err } // Parse it logfiles := []string{} for _, url := range logfiles { fields := strings.Split(url, fmt.Sprintf("/containers/%s/logs/", name)) logfiles = append(logfiles, fields[len(fields)-1]) } return logfiles, nil } // GetContainerLogfile returns the content of the requested logfile // // Note that it's the caller's responsibility to close the returned ReadCloser func (r *ProtocolLXD) GetContainerLogfile(name string, filename string) (io.ReadCloser, error) { // Prepare the HTTP request url := fmt.Sprintf("%s/1.0/containers/%s/logs/%s", r.httpHost, name, filename) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Send the request resp, err := r.do(req) if err != nil { return nil, err } // Check the return value for a cleaner error if resp.StatusCode != http.StatusOK { _, _, err := r.parseResponse(resp) if err != nil { return nil, err } } return resp.Body, err } // DeleteContainerLogfile deletes the requested logfile func (r *ProtocolLXD) DeleteContainerLogfile(name string, filename string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/containers/%s/logs/%s", name, filename), nil, "") if err != nil { return err } return nil } // GetContainerMetadata returns container metadata. func (r *ProtocolLXD) GetContainerMetadata(name string) (*api.ImageMetadata, string, error) { if !r.HasExtension("container_edit_metadata") { return nil, "", fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension") } metadata := api.ImageMetadata{} url := fmt.Sprintf("/containers/%s/metadata", name) etag, err := r.queryStruct("GET", url, nil, "", &metadata) if err != nil { return nil, "", err } return &metadata, etag, err } // SetContainerMetadata sets the content of the container metadata file. func (r *ProtocolLXD) SetContainerMetadata(name string, metadata api.ImageMetadata, ETag string) error { if !r.HasExtension("container_edit_metadata") { return fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension") } url := fmt.Sprintf("/containers/%s/metadata", name) _, _, err := r.query("PUT", url, metadata, ETag) if err != nil { return err } return nil } // GetContainerTemplateFiles returns the list of names of template files for a container. func (r *ProtocolLXD) GetContainerTemplateFiles(containerName string) ([]string, error) { if !r.HasExtension("container_edit_metadata") { return nil, fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension") } templates := []string{} url := fmt.Sprintf("/containers/%s/metadata/templates", containerName) _, err := r.queryStruct("GET", url, nil, "", &templates) if err != nil { return nil, err } return templates, nil } // GetContainerTemplateFile returns the content of a template file for a container. func (r *ProtocolLXD) GetContainerTemplateFile(containerName string, templateName string) (io.ReadCloser, error) { if !r.HasExtension("container_edit_metadata") { return nil, fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension") } url := fmt.Sprintf("%s/1.0/containers/%s/metadata/templates?path=%s", r.httpHost, containerName, templateName) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Send the request resp, err := r.http.Do(req) if err != nil { return nil, err } // Check the return value for a cleaner error if resp.StatusCode != http.StatusOK { _, _, err := r.parseResponse(resp) if err != nil { return nil, err } } return resp.Body, err } // CreateContainerTemplateFile creates an a template for a container. func (r *ProtocolLXD) CreateContainerTemplateFile(containerName string, templateName string, content io.ReadSeeker) error { return r.setContainerTemplateFile(containerName, templateName, content, "POST") } // UpdateContainerTemplateFile updates the content for a container template file. func (r *ProtocolLXD) UpdateContainerTemplateFile(containerName string, templateName string, content io.ReadSeeker) error { return r.setContainerTemplateFile(containerName, templateName, content, "PUT") } func (r *ProtocolLXD) setContainerTemplateFile(containerName string, templateName string, content io.ReadSeeker, httpMethod string) error { if !r.HasExtension("container_edit_metadata") { return fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension") } url := fmt.Sprintf("%s/1.0/containers/%s/metadata/templates?path=%s", r.httpHost, containerName, templateName) req, err := http.NewRequest(httpMethod, url, content) if err != nil { return err } req.Header.Set("Content-Type", "application/octet-stream") // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Send the request resp, err := r.http.Do(req) // Check the return value for a cleaner error if resp.StatusCode != http.StatusOK { _, _, err := r.parseResponse(resp) if err != nil { return err } } return err } // DeleteContainerTemplateFile deletes a template file for a container. func (r *ProtocolLXD) DeleteContainerTemplateFile(name string, templateName string) error { if !r.HasExtension("container_edit_metadata") { return fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension") } _, _, err := r.query("DELETE", fmt.Sprintf("/containers/%s/metadata/templates?path=%s", name, templateName), nil, "") return err } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd_certificates.go���������������������������������������������������������������0000644�0610621�0607500�00000004625�13172163242�020621� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "strings" "github.com/lxc/lxd/shared/api" ) // Certificate handling functions // GetCertificateFingerprints returns a list of certificate fingerprints func (r *ProtocolLXD) GetCertificateFingerprints() ([]string, error) { certificates := []string{} // Fetch the raw value _, err := r.queryStruct("GET", "/certificates", nil, "", &certificates) if err != nil { return nil, err } // Parse it fingerprints := []string{} for _, fingerprint := range fingerprints { fields := strings.Split(fingerprint, "/certificates/") fingerprints = append(fingerprints, fields[len(fields)-1]) } return fingerprints, nil } // GetCertificates returns a list of certificates func (r *ProtocolLXD) GetCertificates() ([]api.Certificate, error) { certificates := []api.Certificate{} // Fetch the raw value _, err := r.queryStruct("GET", "/certificates?recursion=1", nil, "", &certificates) if err != nil { return nil, err } return certificates, nil } // GetCertificate returns the certificate entry for the provided fingerprint func (r *ProtocolLXD) GetCertificate(fingerprint string) (*api.Certificate, string, error) { certificate := api.Certificate{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/certificates/%s", fingerprint), nil, "", &certificate) if err != nil { return nil, "", err } return &certificate, etag, nil } // CreateCertificate adds a new certificate to the LXD trust store func (r *ProtocolLXD) CreateCertificate(certificate api.CertificatesPost) error { // Send the request _, _, err := r.query("POST", "/certificates", certificate, "") if err != nil { return err } return nil } // UpdateCertificate updates the certificate definition func (r *ProtocolLXD) UpdateCertificate(fingerprint string, certificate api.CertificatePut, ETag string) error { if !r.HasExtension("certificate_update") { return fmt.Errorf("The server is missing the required \"certificate_update\" API extension") } // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/certificates/%s", fingerprint), certificate, ETag) if err != nil { return err } return nil } // DeleteCertificate removes a certificate from the LXD trust store func (r *ProtocolLXD) DeleteCertificate(fingerprint string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/certificates/%s", fingerprint), nil, "") if err != nil { return err } return nil } �����������������������������������������������������������������������������������������������������������lxd-2.0.11/client/lxd.go����������������������������������������������������������������������������0000644�0610621�0607500�00000017644�13172163242�016101� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "bytes" "encoding/json" "fmt" "net/http" "strings" "sync" "github.com/gorilla/websocket" "gopkg.in/macaroon-bakery.v2-unstable/bakery" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/logger" neturl "net/url" ) // ProtocolLXD represents a LXD API server type ProtocolLXD struct { server *api.Server eventListeners []*EventListener eventListenersLock sync.Mutex http *http.Client httpCertificate string httpHost string httpProtocol string httpUserAgent string bakeryClient *httpbakery.Client bakeryInteractor httpbakery.Interactor requireAuthenticated bool } // GetConnectionInfo returns the basic connection information used to interact with the server func (r *ProtocolLXD) GetConnectionInfo() (*ConnectionInfo, error) { info := ConnectionInfo{} info.Certificate = r.httpCertificate info.Protocol = "lxd" urls := []string{} if r.httpProtocol == "https" { urls = append(urls, r.httpHost) } if len(r.server.Environment.Addresses) > 0 { for _, addr := range r.server.Environment.Addresses { url := fmt.Sprintf("https://%s", addr) if !shared.StringInSlice(url, urls) { urls = append(urls, url) } } } info.Addresses = urls return &info, nil } // GetHTTPClient returns the http client used for the connection. This can be used to set custom http options. func (r *ProtocolLXD) GetHTTPClient() (*http.Client, error) { if r.http == nil { return nil, fmt.Errorf("HTTP client isn't set, bad connection") } return r.http, nil } // Do performs a Request, using macaroon authentication if set. func (r *ProtocolLXD) do(req *http.Request) (*http.Response, error) { if r.bakeryClient != nil { r.addMacaroonHeaders(req) return r.bakeryClient.Do(req) } return r.http.Do(req) } func (r *ProtocolLXD) addMacaroonHeaders(req *http.Request) { req.Header.Set(httpbakery.BakeryProtocolHeader, fmt.Sprint(bakery.LatestVersion)) for _, cookie := range r.http.Jar.Cookies(req.URL) { req.AddCookie(cookie) } } // RequireAuthenticated sets whether we expect to be authenticated with the server func (r *ProtocolLXD) RequireAuthenticated(authenticated bool) { r.requireAuthenticated = authenticated } // RawQuery allows directly querying the LXD API // // This should only be used by internal LXD tools. func (r *ProtocolLXD) RawQuery(method string, path string, data interface{}, ETag string) (*api.Response, string, error) { // Generate the URL url := fmt.Sprintf("%s%s", r.httpHost, path) return r.rawQuery(method, url, data, ETag) } // RawWebsocket allows directly connection to LXD API websockets // // This should only be used by internal LXD tools. func (r *ProtocolLXD) RawWebsocket(path string) (*websocket.Conn, error) { return r.websocket(path) } // Internal functions func (r *ProtocolLXD) parseResponse(resp *http.Response) (*api.Response, string, error) { // Get the ETag etag := resp.Header.Get("ETag") // Decode the response decoder := json.NewDecoder(resp.Body) response := api.Response{} err := decoder.Decode(&response) if err != nil { // Check the return value for a cleaner error if resp.StatusCode != http.StatusOK { return nil, "", fmt.Errorf("Failed to fetch %s: %s", resp.Request.URL.String(), resp.Status) } return nil, "", err } // Handle errors if response.Type == api.ErrorResponse { return nil, "", fmt.Errorf(response.Error) } return &response, etag, nil } func (r *ProtocolLXD) rawQuery(method string, url string, data interface{}, ETag string) (*api.Response, string, error) { var req *http.Request var err error // Log the request logger.Debug("Sending request to LXD", "method", method, "url", url, "etag", ETag, ) // Get a new HTTP request setup if data != nil { // Encode the provided data buf := bytes.Buffer{} err := json.NewEncoder(&buf).Encode(data) if err != nil { return nil, "", err } // Some data to be sent along with the request // Use a reader since the request body needs to be seekable req, err = http.NewRequest(method, url, bytes.NewReader(buf.Bytes())) if err != nil { return nil, "", err } // Set the encoding accordingly req.Header.Set("Content-Type", "application/json") // Log the data logger.Debugf(logger.Pretty(data)) } else { // No data to be sent along with the request req, err = http.NewRequest(method, url, nil) if err != nil { return nil, "", err } } // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Set the ETag if ETag != "" { req.Header.Set("If-Match", ETag) } // Set the authentication header if r.requireAuthenticated { req.Header.Set("X-LXD-authenticated", "true") } // Send the request resp, err := r.do(req) if err != nil { return nil, "", err } defer resp.Body.Close() return r.parseResponse(resp) } func (r *ProtocolLXD) query(method string, path string, data interface{}, ETag string) (*api.Response, string, error) { // Generate the URL url := fmt.Sprintf("%s/1.0%s", r.httpHost, path) return r.rawQuery(method, url, data, ETag) } func (r *ProtocolLXD) queryStruct(method string, path string, data interface{}, ETag string, target interface{}) (string, error) { resp, etag, err := r.query(method, path, data, ETag) if err != nil { return "", err } err = resp.MetadataAsStruct(&target) if err != nil { return "", err } // Log the data logger.Debugf("Got response struct from LXD") logger.Debugf(logger.Pretty(target)) return etag, nil } func (r *ProtocolLXD) queryOperation(method string, path string, data interface{}, ETag string) (*Operation, string, error) { // Attempt to setup an early event listener listener, err := r.GetEvents() if err != nil { listener = nil } // Send the query resp, etag, err := r.query(method, path, data, ETag) if err != nil { if listener != nil { listener.Disconnect() } return nil, "", err } // Get to the operation respOperation, err := resp.MetadataAsOperation() if err != nil { if listener != nil { listener.Disconnect() } return nil, "", err } // Setup an Operation wrapper op := Operation{ Operation: *respOperation, r: r, listener: listener, chActive: make(chan bool), } // Log the data logger.Debugf("Got operation from LXD") logger.Debugf(logger.Pretty(op.Operation)) return &op, etag, nil } func (r *ProtocolLXD) rawWebsocket(url string) (*websocket.Conn, error) { // Grab the http transport handler httpTransport := r.http.Transport.(*http.Transport) // Setup a new websocket dialer based on it dialer := websocket.Dialer{ NetDial: httpTransport.Dial, TLSClientConfig: httpTransport.TLSClientConfig, Proxy: httpTransport.Proxy, } // Set the user agent headers := http.Header{} if r.httpUserAgent != "" { headers.Set("User-Agent", r.httpUserAgent) } if r.requireAuthenticated { headers.Set("X-LXD-authenticated", "true") } // Set macaroon headers if needed if r.bakeryClient != nil { u, err := neturl.Parse(r.httpHost) // use the http url, not the ws one if err != nil { return nil, err } req := &http.Request{URL: u, Header: headers} r.addMacaroonHeaders(req) } // Establish the connection conn, _, err := dialer.Dial(url, headers) if err != nil { return nil, err } // Log the data logger.Debugf("Connected to the websocket") return conn, err } func (r *ProtocolLXD) websocket(path string) (*websocket.Conn, error) { // Generate the URL var url string if strings.HasPrefix(r.httpHost, "https://") { url = fmt.Sprintf("wss://%s/1.0%s", strings.TrimPrefix(r.httpHost, "https://"), path) } else { url = fmt.Sprintf("ws://%s/1.0%s", strings.TrimPrefix(r.httpHost, "http://"), path) } return r.rawWebsocket(url) } func (r *ProtocolLXD) setupBakeryClient() { r.bakeryClient = httpbakery.NewClient() r.bakeryClient.Client = r.http if r.bakeryInteractor != nil { r.bakeryClient.AddInteractor(r.bakeryInteractor) } } ��������������������������������������������������������������������������������������������lxd-2.0.11/client/interfaces.go���������������������������������������������������������������������0000644�0610621�0607500�00000031202�13172163242�017417� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "io" "net/http" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/cancel" ) // The Server type represents a generic read-only server. type Server interface { GetConnectionInfo() (info *ConnectionInfo, err error) GetHTTPClient() (client *http.Client, err error) } // The ImageServer type represents a read-only image server. type ImageServer interface { Server // Image handling functions GetImages() (images []api.Image, err error) GetImageFingerprints() (fingerprints []string, err error) GetImage(fingerprint string) (image *api.Image, ETag string, err error) GetImageFile(fingerprint string, req ImageFileRequest) (resp *ImageFileResponse, err error) GetImageSecret(fingerprint string) (secret string, err error) GetPrivateImage(fingerprint string, secret string) (image *api.Image, ETag string, err error) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (resp *ImageFileResponse, err error) GetImageAliases() (aliases []api.ImageAliasesEntry, err error) GetImageAliasNames() (names []string, err error) GetImageAlias(name string) (alias *api.ImageAliasesEntry, ETag string, err error) } // The ContainerServer type represents a full featured LXD server. type ContainerServer interface { ImageServer // Server functions GetServer() (server *api.Server, ETag string, err error) GetServerResources() (*api.Resources, error) UpdateServer(server api.ServerPut, ETag string) (err error) HasExtension(extension string) bool RequireAuthenticated(authenticated bool) // Certificate functions GetCertificateFingerprints() (fingerprints []string, err error) GetCertificates() (certificates []api.Certificate, err error) GetCertificate(fingerprint string) (certificate *api.Certificate, ETag string, err error) CreateCertificate(certificate api.CertificatesPost) (err error) UpdateCertificate(fingerprint string, certificate api.CertificatePut, ETag string) (err error) DeleteCertificate(fingerprint string) (err error) // Container functions GetContainerNames() (names []string, err error) GetContainers() (containers []api.Container, err error) GetContainer(name string) (container *api.Container, ETag string, err error) CreateContainer(container api.ContainersPost) (op *Operation, err error) CreateContainerFromImage(source ImageServer, image api.Image, imgcontainer api.ContainersPost) (op *RemoteOperation, err error) CopyContainer(source ContainerServer, container api.Container, args *ContainerCopyArgs) (op *RemoteOperation, err error) UpdateContainer(name string, container api.ContainerPut, ETag string) (op *Operation, err error) RenameContainer(name string, container api.ContainerPost) (op *Operation, err error) MigrateContainer(name string, container api.ContainerPost) (op *Operation, err error) DeleteContainer(name string) (op *Operation, err error) ExecContainer(containerName string, exec api.ContainerExecPost, args *ContainerExecArgs) (*Operation, error) GetContainerFile(containerName string, path string) (content io.ReadCloser, resp *ContainerFileResponse, err error) CreateContainerFile(containerName string, path string, args ContainerFileArgs) (err error) DeleteContainerFile(containerName string, path string) (err error) GetContainerSnapshotNames(containerName string) (names []string, err error) GetContainerSnapshots(containerName string) (snapshots []api.ContainerSnapshot, err error) GetContainerSnapshot(containerName string, name string) (snapshot *api.ContainerSnapshot, ETag string, err error) CreateContainerSnapshot(containerName string, snapshot api.ContainerSnapshotsPost) (op *Operation, err error) CopyContainerSnapshot(source ContainerServer, snapshot api.ContainerSnapshot, args *ContainerSnapshotCopyArgs) (op *RemoteOperation, err error) RenameContainerSnapshot(containerName string, name string, container api.ContainerSnapshotPost) (op *Operation, err error) MigrateContainerSnapshot(containerName string, name string, container api.ContainerSnapshotPost) (op *Operation, err error) DeleteContainerSnapshot(containerName string, name string) (op *Operation, err error) GetContainerState(name string) (state *api.ContainerState, ETag string, err error) UpdateContainerState(name string, state api.ContainerStatePut, ETag string) (op *Operation, err error) GetContainerLogfiles(name string) (logfiles []string, err error) GetContainerLogfile(name string, filename string) (content io.ReadCloser, err error) DeleteContainerLogfile(name string, filename string) (err error) GetContainerMetadata(name string) (*api.ImageMetadata, string, error) SetContainerMetadata(name string, metadata api.ImageMetadata, ETag string) error GetContainerTemplateFiles(containerName string) (templates []string, err error) GetContainerTemplateFile(containerName string, templateName string) (content io.ReadCloser, err error) CreateContainerTemplateFile(containerName string, templateName string, content io.ReadSeeker) (err error) UpdateContainerTemplateFile(containerName string, templateName string, content io.ReadSeeker) (err error) DeleteContainerTemplateFile(name string, templateName string) (err error) // Event handling functions GetEvents() (listener *EventListener, err error) // Image functions CreateImage(image api.ImagesPost, args *ImageCreateArgs) (op *Operation, err error) CopyImage(source ImageServer, image api.Image, args *ImageCopyArgs) (op *RemoteOperation, err error) UpdateImage(fingerprint string, image api.ImagePut, ETag string) (err error) DeleteImage(fingerprint string) (op *Operation, err error) RefreshImage(fingerprint string) (op *Operation, err error) CreateImageSecret(fingerprint string) (op *Operation, err error) CreateImageAlias(alias api.ImageAliasesPost) (err error) UpdateImageAlias(name string, alias api.ImageAliasesEntryPut, ETag string) (err error) RenameImageAlias(name string, alias api.ImageAliasesEntryPost) (err error) DeleteImageAlias(name string) (err error) // Network functions ("network" API extension) GetNetworkNames() (names []string, err error) GetNetworks() (networks []api.Network, err error) GetNetwork(name string) (network *api.Network, ETag string, err error) CreateNetwork(network api.NetworksPost) (err error) UpdateNetwork(name string, network api.NetworkPut, ETag string) (err error) RenameNetwork(name string, network api.NetworkPost) (err error) DeleteNetwork(name string) (err error) // Operation functions GetOperation(uuid string) (op *api.Operation, ETag string, err error) DeleteOperation(uuid string) (err error) GetOperationWebsocket(uuid string, secret string) (conn *websocket.Conn, err error) // Profile functions GetProfileNames() (names []string, err error) GetProfiles() (profiles []api.Profile, err error) GetProfile(name string) (profile *api.Profile, ETag string, err error) CreateProfile(profile api.ProfilesPost) (err error) UpdateProfile(name string, profile api.ProfilePut, ETag string) (err error) RenameProfile(name string, profile api.ProfilePost) (err error) DeleteProfile(name string) (err error) // Storage pool functions ("storage" API extension) GetStoragePoolNames() (names []string, err error) GetStoragePools() (pools []api.StoragePool, err error) GetStoragePool(name string) (pool *api.StoragePool, ETag string, err error) GetStoragePoolResources(name string) (resources *api.ResourcesStoragePool, err error) CreateStoragePool(pool api.StoragePoolsPost) (err error) UpdateStoragePool(name string, pool api.StoragePoolPut, ETag string) (err error) DeleteStoragePool(name string) (err error) // Storage volume functions ("storage" API extension) GetStoragePoolVolumeNames(pool string) (names []string, err error) GetStoragePoolVolumes(pool string) (volumes []api.StorageVolume, err error) GetStoragePoolVolume(pool string, volType string, name string) (volume *api.StorageVolume, ETag string, err error) CreateStoragePoolVolume(pool string, volume api.StorageVolumesPost) (err error) UpdateStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePut, ETag string) (err error) DeleteStoragePoolVolume(pool string, volType string, name string) (err error) RenameStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePost) (err error) // Internal functions (for internal use) RawQuery(method string, path string, data interface{}, queryETag string) (resp *api.Response, ETag string, err error) RawWebsocket(path string) (conn *websocket.Conn, err error) } // The ConnectionInfo struct represents general information for a connection type ConnectionInfo struct { Addresses []string Certificate string Protocol string } // The ProgressData struct represents new progress information on an operation type ProgressData struct { // Preferred string repreentation of progress (always set) Text string // Progress in percent Percentage int // Number of bytes transferred (for files) TransferredBytes int64 // Total number of bytes (for files) TotalBytes int64 } // The ImageCreateArgs struct is used for direct image upload type ImageCreateArgs struct { // Reader for the meta file MetaFile io.Reader // Filename for the meta file MetaName string // Reader for the rootfs file RootfsFile io.Reader // Filename for the rootfs file RootfsName string // Progress handler (called with upload progress) ProgressHandler func(progress ProgressData) } // The ImageFileRequest struct is used for an image download request type ImageFileRequest struct { // Writer for the metadata file MetaFile io.WriteSeeker // Writer for the rootfs file RootfsFile io.WriteSeeker // Progress handler (called whenever some progress is made) ProgressHandler func(progress ProgressData) // A canceler that can be used to interrupt some part of the image download request Canceler *cancel.Canceler // Path retriever for image delta downloads // If set, it must return the path to the image file or an empty string if not available DeltaSourceRetriever func(fingerprint string, file string) string } // The ImageFileResponse struct is used as the response for image downloads type ImageFileResponse struct { // Filename for the metadata file MetaName string // Size of the metadata file MetaSize int64 // Filename for the rootfs file RootfsName string // Size of the rootfs file RootfsSize int64 } // The ImageCopyArgs struct is used to pass additional options during image copy type ImageCopyArgs struct { // Aliases to add to the copied image. Aliases []api.ImageAlias // Whether to have LXD keep this image up to date AutoUpdate bool // Whether to copy the source image aliases to the target CopyAliases bool // Whether this image is to be made available to unauthenticated users Public bool } // The ContainerCopyArgs struct is used to pass additional options during container copy type ContainerCopyArgs struct { // If set, the container will be renamed on copy Name string // If set, the container running state will be transferred (live migration) Live bool // If set, only the container will copied, its snapshots won't ContainerOnly bool // The transfer mode, can be "pull" (default), "push" or "relay" Mode string } // The ContainerSnapshotCopyArgs struct is used to pass additional options during container copy type ContainerSnapshotCopyArgs struct { // If set, the container will be renamed on copy Name string // The transfer mode, can be "pull" (default), "push" or "relay" Mode string // API extension: container_snapshot_stateful_migration // If set, the container running state will be transferred (live migration) Live bool } // The ContainerExecArgs struct is used to pass additional options during container exec type ContainerExecArgs struct { // Standard input Stdin io.ReadCloser // Standard output Stdout io.WriteCloser // Standard error Stderr io.WriteCloser // Control message handler (window resize, signals, ...) Control func(conn *websocket.Conn) // Channel that will be closed when all data operations are done DataDone chan bool } // The ContainerFileArgs struct is used to pass the various options for a container file upload type ContainerFileArgs struct { // File content Content io.ReadSeeker // User id that owns the file UID int64 // Group id that owns the file GID int64 // File permissions Mode int // File type (file or directory) Type string // File write mode (overwrite or append) WriteMode string } // The ContainerFileResponse struct is used as part of the response for a container file download type ContainerFileResponse struct { // User id that owns the file UID int64 // Group id that owns the file GID int64 // File permissions Mode int // File type (file or directory) Type string // If a directory, the list of files inside it Entries []string } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/events.go�������������������������������������������������������������������������0000644�0610621�0607500�00000004520�13172163242�016603� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "fmt" "sync" ) // The EventListener struct is used to interact with a LXD event stream type EventListener struct { r *ProtocolLXD chActive chan bool disconnected bool err error targets []*EventTarget targetsLock sync.Mutex } // The EventTarget struct is returned to the caller of AddHandler and used in RemoveHandler type EventTarget struct { function func(interface{}) types []string } // AddHandler adds a function to be called whenever an event is received func (e *EventListener) AddHandler(types []string, function func(interface{})) (*EventTarget, error) { if function == nil { return nil, fmt.Errorf("A valid function must be provided") } // Handle locking e.targetsLock.Lock() defer e.targetsLock.Unlock() // Create a new target target := EventTarget{ function: function, types: types, } // And add it to the targets e.targets = append(e.targets, &target) return &target, nil } // RemoveHandler removes a function to be called whenever an event is received func (e *EventListener) RemoveHandler(target *EventTarget) error { if target == nil { return fmt.Errorf("A valid event target must be provided") } // Handle locking e.targetsLock.Lock() defer e.targetsLock.Unlock() // Locate and remove the function from the list for i, entry := range e.targets { if entry == target { copy(e.targets[i:], e.targets[i+1:]) e.targets[len(e.targets)-1] = nil e.targets = e.targets[:len(e.targets)-1] return nil } } return fmt.Errorf("Couldn't find this function and event types combination") } // Disconnect must be used once done listening for events func (e *EventListener) Disconnect() { if e.disconnected { return } // Handle locking e.r.eventListenersLock.Lock() defer e.r.eventListenersLock.Unlock() // Locate and remove it from the global list for i, listener := range e.r.eventListeners { if listener == e { copy(e.r.eventListeners[i:], e.r.eventListeners[i+1:]) e.r.eventListeners[len(e.r.eventListeners)-1] = nil e.r.eventListeners = e.r.eventListeners[:len(e.r.eventListeners)-1] break } } // Turn off the handler e.err = nil e.disconnected = true close(e.chActive) } // Wait hangs until the server disconnects the connection or Disconnect() is called func (e *EventListener) Wait() error { <-e.chActive return e.err } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/doc.go����������������������������������������������������������������������������0000644�0610621�0607500�00000006323�13172163242�016047� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������// Package lxd implements a client for the LXD API // // Overview // // This package lets you connect to LXD daemons or SimpleStream image // servers over a Unix socket or HTTPs. You can then interact with those // remote servers, creating containers, images, moving them around, ... // // Example - container creation // // This creates a container on a local LXD daemon and then starts it. // // // Connect to LXD over the Unix socket // c, err := lxd.ConnectLXDUnix("", nil) // if err != nil { // return err // } // // // Container creation request // req := api.ContainersPost{ // Name: "my-container", // Source: api.ContainerSource{ // Type: "image", // Alias: "my-image", // }, // } // // // Get LXD to create the container (background operation) // op, err := c.CreateContainer(req) // if err != nil { // return err // } // // // Wait for the operation to complete // err = op.Wait() // if err != nil { // return err // } // // // Get LXD to start the container (background operation) // reqState := api.ContainerStatePut{ // Action: "start", // Timeout: -1, // } // // op, err = c.UpdateContainerState(name, reqState, "") // if err != nil { // return err // } // // // Wait for the operation to complete // err = op.Wait() // if err != nil { // return err // } // // Example - command execution // // This executes an interactive bash terminal // // // Connect to LXD over the Unix socket // c, err := lxd.ConnectLXDUnix("", nil) // if err != nil { // return err // } // // // Setup the exec request // req := api.ContainerExecPost{ // Command: []string{"bash"}, // WaitForWS: true, // Interactive: true, // Width: 80, // Height: 15, // } // // // Setup the exec arguments (fds) // args := lxd.ContainerExecArgs{ // Stdin: os.Stdin, // Stdout: os.Stdout, // Stderr: os.Stderr, // } // // // Setup the terminal (set to raw mode) // if req.Interactive { // cfd := int(syscall.Stdin) // oldttystate, err := termios.MakeRaw(cfd) // if err != nil { // return err // } // // defer termios.Restore(cfd, oldttystate) // } // // // Get the current state // op, err := c.ExecContainer("c1", req, &args) // if err != nil { // return err // } // // // Wait for it to complete // err = op.Wait() // if err != nil { // return err // } // // Example - image copy // // This copies an image from a simplestreams server to a local LXD daemon // // // Connect to LXD over the Unix socket // c, err := lxd.ConnectLXDUnix("", nil) // if err != nil { // return err // } // // // Connect to the remote SimpleStreams server // d, err = lxd.ConnectSimpleStreams("https://images.linuxcontainers.org", nil) // if err != nil { // return err // } // // // Resolve the alias // alias, _, err := d.GetImageAlias("centos/7") // if err != nil { // return err // } // // // Get the image information // image, _, err := d.GetImage(alias.Target) // if err != nil { // return err // } // // // Ask LXD to copy the image from the remote server // op, err := d.CopyImage(*image, c, nil) // if err != nil { // return err // } // // // And wait for it to finish // err = op.Wait() // if err != nil { // return err // } package lxd �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client/connection.go���������������������������������������������������������������������0000644�0610621�0607500�00000012231�13172163242�017434� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "net/http" "net/url" "os" "path/filepath" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/simplestreams" "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" ) // ConnectionArgs represents a set of common connection properties type ConnectionArgs struct { // TLS certificate of the remote server. If not specified, the system CA is used. TLSServerCert string // TLS certificate to use for client authentication. TLSClientCert string // TLS key to use for client authentication. TLSClientKey string // TLS CA to validate against when in PKI mode. TLSCA string // User agent string UserAgent string // Authentication type AuthType string // Authentication interactor AuthInteractor httpbakery.Interactor // Custom proxy Proxy func(*http.Request) (*url.URL, error) // Custom HTTP Client (used as base for the connection) HTTPClient *http.Client // Controls whether a client verifies the server's certificate chain and host name. InsecureSkipVerify bool // Cookie jar CookieJar http.CookieJar } // ConnectLXD lets you connect to a remote LXD daemon over HTTPs. // // A client certificate (TLSClientCert) and key (TLSClientKey) must be provided. // // If connecting to a LXD daemon running in PKI mode, the PKI CA (TLSCA) must also be provided. // // Unless the remote server is trusted by the system CA, the remote certificate must be provided (TLSServerCert). func ConnectLXD(url string, args *ConnectionArgs) (ContainerServer, error) { logger.Debugf("Connecting to a remote LXD over HTTPs") return httpsLXD(url, args) } // ConnectLXDUnix lets you connect to a remote LXD daemon over a local unix socket. // // If the path argument is empty, then $LXD_DIR/unix.socket will be used. // If that one isn't set either, then the path will default to /var/lib/lxd/unix.socket. func ConnectLXDUnix(path string, args *ConnectionArgs) (ContainerServer, error) { logger.Debugf("Connecting to a local LXD over a Unix socket") // Use empty args if not specified if args == nil { args = &ConnectionArgs{} } // Initialize the client struct server := ProtocolLXD{ httpHost: "http://unix.socket", httpProtocol: "unix", httpUserAgent: args.UserAgent, } // Determine the socket path if path == "" { lxdDir := os.Getenv("LXD_DIR") if lxdDir == "" { lxdDir = "/var/lib/lxd" } path = filepath.Join(lxdDir, "unix.socket") } // Setup the HTTP client httpClient, err := unixHTTPClient(args.HTTPClient, path) if err != nil { return nil, err } server.http = httpClient // Test the connection and seed the server information serverStatus, _, err := server.GetServer() if err != nil { return nil, err } // Record the server certificate server.httpCertificate = serverStatus.Environment.Certificate return &server, nil } // ConnectPublicLXD lets you connect to a remote public LXD daemon over HTTPs. // // Unless the remote server is trusted by the system CA, the remote certificate must be provided (TLSServerCert). func ConnectPublicLXD(url string, args *ConnectionArgs) (ImageServer, error) { logger.Debugf("Connecting to a remote public LXD over HTTPs") return httpsLXD(url, args) } // ConnectSimpleStreams lets you connect to a remote SimpleStreams image server over HTTPs. // // Unless the remote server is trusted by the system CA, the remote certificate must be provided (TLSServerCert). func ConnectSimpleStreams(url string, args *ConnectionArgs) (ImageServer, error) { logger.Debugf("Connecting to a remote simplestreams server") // Use empty args if not specified if args == nil { args = &ConnectionArgs{} } // Initialize the client struct server := ProtocolSimpleStreams{ httpHost: url, httpUserAgent: args.UserAgent, httpCertificate: args.TLSServerCert, } // Setup the HTTP client httpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy) if err != nil { return nil, err } server.http = httpClient // Get simplestreams client ssClient := simplestreams.NewClient(url, *httpClient, args.UserAgent) server.ssClient = ssClient return &server, nil } // Internal function called by ConnectLXD and ConnectPublicLXD func httpsLXD(url string, args *ConnectionArgs) (ContainerServer, error) { // Use empty args if not specified if args == nil { args = &ConnectionArgs{} } // Initialize the client struct server := ProtocolLXD{ httpCertificate: args.TLSServerCert, httpHost: url, httpProtocol: "https", httpUserAgent: args.UserAgent, bakeryInteractor: args.AuthInteractor, } if args.AuthType == "macaroons" { server.RequireAuthenticated(true) } // Setup the HTTP client httpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy) if err != nil { return nil, err } if args.CookieJar != nil { httpClient.Jar = args.CookieJar } server.http = httpClient if args.AuthType == "macaroons" { server.setupBakeryClient() } // Test the connection and seed the server information _, _, err = server.GetServer() if err != nil { return nil, err } return &server, nil } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/client.go��������������������������������������������������������������������������������0000644�0610621�0607500�00000160607�13172163242�015310� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������package lxd import ( "bytes" "crypto/x509" "encoding/base64" "encoding/json" "encoding/pem" "fmt" "io" "io/ioutil" "mime" "mime/multipart" "net" "net/http" "net/url" "os" "path" "path/filepath" "strconv" "strings" "syscall" "github.com/gorilla/websocket" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/ioprogress" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/simplestreams" "github.com/lxc/lxd/shared/version" ) // Client can talk to a LXD daemon. type Client struct { BaseURL string BaseWSURL string Config Config Name string Remote *RemoteConfig Transport string Certificate string Http http.Client websocketDialer websocket.Dialer simplestreams *simplestreams.SimpleStreams } var ( // LXDErrors are special errors; the client library hoists error codes // to these errors internally so that user code can compare against // them. We probably shouldn't hoist BadRequest or InternalError, since // LXD passes an error string along which is more informative than // whatever static error message we would put here. LXDErrors = map[int]error{ http.StatusNotFound: fmt.Errorf("not found"), } ) // ParseResponse parses a lxd style response out of an http.Response. Note that // this does _not_ automatically convert error responses to golang errors. To // do that, use ParseError. Internal client library uses should probably use // HoistResponse, unless they are interested in accessing the underlying Error // response (e.g. to inspect the error code). func ParseResponse(r *http.Response) (*api.Response, error) { if r == nil { return nil, fmt.Errorf("no response!") } defer r.Body.Close() ret := api.Response{} s, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } logger.Debugf("Raw response: %s", string(s)) if err := json.Unmarshal(s, &ret); err != nil { return nil, err } return &ret, nil } // HoistResponse hoists a regular http response into a response of type rtype // or returns a golang error. func HoistResponse(r *http.Response, rtype api.ResponseType) (*api.Response, error) { resp, err := ParseResponse(r) if err != nil { return nil, err } if resp.Type == api.ErrorResponse { // Try and use a known error if we have one for this code. err, ok := LXDErrors[resp.Code] if !ok { return nil, fmt.Errorf(resp.Error) } return nil, err } if resp.Type != rtype { return nil, fmt.Errorf("got bad response type, expected %s got %s", rtype, resp.Type) } return resp, nil } // NewClient returns a new LXD client. func NewClient(config *Config, remote string) (*Client, error) { if remote == "" { return nil, fmt.Errorf("A remote name must be provided.") } r, ok := config.Remotes[remote] if !ok { return nil, fmt.Errorf("unknown remote name: %q", remote) } info := ConnectInfo{ Name: remote, RemoteConfig: r, } if strings.HasPrefix(r.Addr, "unix:") { // replace "unix://" with the official "unix:/var/lib/lxd/unix.socket" if info.RemoteConfig.Addr == "unix://" { info.RemoteConfig.Addr = fmt.Sprintf("unix:%s", shared.VarPath("unix.socket")) } } else { // Read the client certificate (if it exists) clientCertPath := path.Join(config.ConfigDir, "client.crt") if shared.PathExists(clientCertPath) { certBytes, err := ioutil.ReadFile(clientCertPath) if err != nil { return nil, err } info.ClientPEMCert = string(certBytes) } // Read the client key (if it exists) clientKeyPath := path.Join(config.ConfigDir, "client.key") if shared.PathExists(clientKeyPath) { keyBytes, err := ioutil.ReadFile(clientKeyPath) if err != nil { return nil, err } info.ClientPEMKey = string(keyBytes) } // Read the server certificate (if it exists) serverCertPath := config.ServerCertPath(remote) if shared.PathExists(serverCertPath) { cert, err := shared.ReadCert(serverCertPath) if err != nil { return nil, err } info.ServerPEMCert = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})) } } c, err := NewClientFromInfo(info) if err != nil { return nil, err } c.Config = *config return c, nil } // ConnectInfo contains the information we need to connect to a specific LXD server type ConnectInfo struct { // Name is a simple identifier for the remote server. In 'lxc' it is // the name used to lookup the address and other information in the // config.yml file. Name string // RemoteConfig is the information about the Remote that we are // connecting to. This includes information like if the remote is // Public and/or Static. RemoteConfig RemoteConfig // ClientPEMCert is the PEM encoded bytes of the client's certificate. // If Addr indicates a Unix socket, the certificate and key bytes will // not be used. ClientPEMCert string // ClientPEMKey is the PEM encoded private bytes of the client's key associated with its certificate ClientPEMKey string // ServerPEMCert is the PEM encoded server certificate that we are // connecting to. It can be the empty string if we do not know the // server's certificate yet. ServerPEMCert string } func connectViaUnix(c *Client, remote *RemoteConfig) error { c.BaseURL = "http://unix.socket" c.BaseWSURL = "ws://unix.socket" c.Transport = "unix" uDial := func(network, addr string) (net.Conn, error) { // The arguments 'network' and 'addr' are ignored because // they are the wrong information. // addr is generated from BaseURL which becomes // 'unix.socket:80' which is certainly not what we want. // handle: // unix:///path/to/socket // unix:/path/to/socket // unix:path/to/socket path := strings.TrimPrefix(strings.TrimPrefix(remote.Addr, "unix:"), "//") raddr, err := net.ResolveUnixAddr("unix", path) if err != nil { return nil, err } return net.DialUnix("unix", nil, raddr) } c.Http.Transport = &http.Transport{ Dial: uDial, DisableKeepAlives: true, } c.websocketDialer.NetDial = uDial c.Remote = remote st, err := c.ServerStatus() if err != nil { return err } c.Certificate = st.Environment.Certificate return nil } func connectViaHttp(c *Client, remote *RemoteConfig, clientCert, clientKey, serverCert string) error { tlsconfig, err := shared.GetTLSConfigMem(clientCert, clientKey, "", serverCert, false) if err != nil { return err } tr := &http.Transport{ TLSClientConfig: tlsconfig, Dial: shared.RFC3493Dialer, Proxy: shared.ProxyFromEnvironment, DisableKeepAlives: true, } c.websocketDialer.NetDial = shared.RFC3493Dialer c.websocketDialer.TLSClientConfig = tlsconfig justAddr := strings.TrimPrefix(remote.Addr, "https://") c.BaseURL = "https://" + justAddr c.BaseWSURL = "wss://" + justAddr c.Transport = "https" c.Http.Transport = tr c.Remote = remote c.Certificate = serverCert // We don't actually need to connect yet, defer that until someone // needs something from the server. return nil } // NewClientFromInfo returns a new LXD client. func NewClientFromInfo(info ConnectInfo) (*Client, error) { c := &Client{ // Config: *config, Http: http.Client{}, Config: Config{ Remotes: DefaultRemotes, Aliases: map[string]string{}, }, } c.Name = info.Name // Setup redirect policy c.Http.CheckRedirect = func(req *http.Request, via []*http.Request) error { // Replicate the headers req.Header = via[len(via)-1].Header return nil } var err error if strings.HasPrefix(info.RemoteConfig.Addr, "unix:") { err = connectViaUnix(c, &info.RemoteConfig) } else { err = connectViaHttp(c, &info.RemoteConfig, info.ClientPEMCert, info.ClientPEMKey, info.ServerPEMCert) } if err != nil { return nil, err } if info.RemoteConfig.Protocol == "simplestreams" { tlsconfig, err := shared.GetTLSConfig("", "", "", nil) if err != nil { return nil, err } tr := &http.Transport{ TLSClientConfig: tlsconfig, Dial: shared.RFC3493Dialer, Proxy: shared.ProxyFromEnvironment, DisableKeepAlives: true, } c.Http.Transport = tr ss := simplestreams.NewClient(c.Remote.Addr, c.Http, version.UserAgent) c.simplestreams = ss } return c, nil } func (c *Client) Addresses() ([]string, error) { addresses := make([]string, 0) if c.Transport == "unix" { serverStatus, err := c.ServerStatus() if err != nil { return nil, err } addresses = serverStatus.Environment.Addresses } else if c.Transport == "https" { addresses = append(addresses, c.BaseURL[8:]) if !c.Remote.Public { serverStatus, err := c.ServerStatus() if err != nil { return nil, err } addresses = append(addresses, serverStatus.Environment.Addresses...) } } else { return nil, fmt.Errorf("unknown transport type: %s", c.Transport) } if len(addresses) == 0 { return nil, fmt.Errorf("The source remote isn't available over the network") } return addresses, nil } func (c *Client) get(base string) (*api.Response, error) { uri := c.url(version.APIVersion, base) return c.baseGet(uri) } func (c *Client) baseGet(getUrl string) (*api.Response, error) { req, err := http.NewRequest("GET", getUrl, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", version.UserAgent) resp, err := c.Http.Do(req) if err != nil { return nil, err } return HoistResponse(resp, api.SyncResponse) } func (c *Client) doUpdateMethod(method string, base string, args interface{}, rtype api.ResponseType) (*api.Response, error) { uri := c.url(version.APIVersion, base) buf := bytes.Buffer{} err := json.NewEncoder(&buf).Encode(args) if err != nil { return nil, err } logger.Debugf("%s %s to %s", method, buf.String(), uri) req, err := http.NewRequest(method, uri, &buf) if err != nil { return nil, err } req.Header.Set("User-Agent", version.UserAgent) req.Header.Set("Content-Type", "application/json") resp, err := c.Http.Do(req) if err != nil { return nil, err } return HoistResponse(resp, rtype) } func (c *Client) put(base string, args interface{}, rtype api.ResponseType) (*api.Response, error) { return c.doUpdateMethod("PUT", base, args, rtype) } func (c *Client) patch(base string, args interface{}, rtype api.ResponseType) (*api.Response, error) { return c.doUpdateMethod("PATCH", base, args, rtype) } func (c *Client) post(base string, args interface{}, rtype api.ResponseType) (*api.Response, error) { return c.doUpdateMethod("POST", base, args, rtype) } func (c *Client) delete(base string, args interface{}, rtype api.ResponseType) (*api.Response, error) { return c.doUpdateMethod("DELETE", base, args, rtype) } func (c *Client) getRaw(uri string) (*http.Response, error) { req, err := http.NewRequest("GET", uri, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", version.UserAgent) raw, err := c.Http.Do(req) if err != nil { return nil, err } // because it is raw data, we need to check for http status if raw.StatusCode != 200 { resp, err := HoistResponse(raw, api.SyncResponse) if err != nil { return nil, err } return nil, fmt.Errorf("expected error, got %v", *resp) } return raw, nil } func (c *Client) Websocket(operation string, secret string) (*websocket.Conn, error) { query := url.Values{"secret": []string{secret}} url := c.BaseWSURL + path.Join(operation, "websocket") + "?" + query.Encode() return WebsocketDial(c.websocketDialer, url) } func (c *Client) url(elem ...string) string { // Normalize the URL path := strings.Join(elem, "/") entries := []string{} fields := strings.Split(path, "/") for i, entry := range fields { if entry == "" && i+1 < len(fields) { continue } entries = append(entries, entry) } path = strings.Join(entries, "/") // Assemble the final URL uri := c.BaseURL + "/" + path // Aliases may contain a trailing slash if strings.HasPrefix(path, "1.0/images/aliases") { return uri } // File paths may contain a trailing slash if strings.Contains(path, "?") { return uri } // Nothing else should contain a trailing slash return strings.TrimSuffix(uri, "/") } func (c *Client) GetServerConfig() (*api.Response, error) { if c.Remote.Protocol == "simplestreams" { return nil, fmt.Errorf("This function isn't supported by simplestreams remote.") } return c.baseGet(c.url(version.APIVersion)) } // GetLocalLXDErr determines whether or not an error is likely due to a // local LXD configuration issue, and if so, returns the underlying error. // GetLocalLXDErr can be used to provide customized error messages to help // the user identify basic system issues, e.g. LXD daemon not running. // // Returns syscall.ENOENT, syscall.ECONNREFUSED or syscall.EACCES when a // local LXD configuration issue is detected, nil otherwise. func GetLocalLXDErr(err error) error { t, ok := err.(*url.Error) if !ok { return nil } u, ok := t.Err.(*net.OpError) if !ok { return nil } if u.Op == "dial" && u.Net == "unix" { var lxdErr error sysErr, ok := u.Err.(*os.SyscallError) if ok { lxdErr = sysErr.Err } else { // syscall.Errno may be returned on some systems, e.g. CentOS lxdErr, ok = u.Err.(syscall.Errno) if !ok { return nil } } switch lxdErr { case syscall.ENOENT, syscall.ECONNREFUSED, syscall.EACCES: return lxdErr } } return nil } func (c *Client) AmTrusted() bool { resp, err := c.GetServerConfig() if err != nil { return false } logger.Debugf("%s", resp) meta, err := resp.MetadataAsMap() if err != nil { return false } auth, err := shared.Jmap(meta).GetString("auth") if err != nil { return false } return auth == "trusted" } func (c *Client) IsPublic() bool { resp, err := c.GetServerConfig() if err != nil { return false } logger.Debugf("%s", resp) meta, err := resp.MetadataAsMap() if err != nil { return false } public, err := shared.Jmap(meta).GetBool("public") if err != nil { return false } return public } func (c *Client) ListContainers() ([]api.Container, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } resp, err := c.get("containers?recursion=1") if err != nil { return nil, err } var result []api.Container if err := resp.MetadataAsStruct(&result); err != nil { return nil, err } return result, nil } func (c *Client) CopyImage(image string, dest *Client, copy_aliases bool, aliases []string, public bool, autoUpdate bool, progressHandler func(progress string)) error { source := shared.Jmap{ "type": "image", "mode": "pull", "server": c.BaseURL, "protocol": c.Remote.Protocol, "certificate": c.Certificate, "fingerprint": image} target := c.GetAlias(image) if target != "" { image = target } info, err := c.GetImageInfo(image) if err != nil { return err } if c.Remote.Protocol != "simplestreams" && !info.Public { var secret string resp, err := c.post("images/"+image+"/secret", nil, api.AsyncResponse) if err != nil { return err } op, err := resp.MetadataAsOperation() if err != nil { return err } secret, err = shared.Jmap(op.Metadata).GetString("secret") if err != nil { return err } source["secret"] = secret source["fingerprint"] = image } addresses, err := c.Addresses() if err != nil { return err } operation := "" handler := func(msg interface{}) { if msg == nil { return } event := msg.(map[string]interface{}) if event["type"].(string) != "operation" { return } if event["metadata"] == nil { return } md := event["metadata"].(map[string]interface{}) if !strings.HasSuffix(operation, md["id"].(string)) { return } if md["metadata"] == nil { return } opMd := md["metadata"].(map[string]interface{}) _, ok := opMd["download_progress"] if ok { progressHandler(opMd["download_progress"].(string)) } } if progressHandler != nil { go dest.Monitor([]string{"operation"}, handler, nil) } fingerprint := info.Fingerprint for _, addr := range addresses { sourceUrl := "https://" + addr source["server"] = sourceUrl body := shared.Jmap{"public": public, "auto_update": autoUpdate, "source": source} resp, err := dest.post("images", body, api.AsyncResponse) if err != nil { continue } operation = resp.Operation op, err := dest.WaitForSuccessOp(resp.Operation) if err != nil { return err } if op.Metadata != nil { value, err := shared.Jmap(op.Metadata).GetString("fingerprint") if err == nil { fingerprint = value } } break } if err != nil { return err } /* copy aliases from source image */ if copy_aliases { for _, alias := range info.Aliases { dest.DeleteAlias(alias.Name) err = dest.PostAlias(alias.Name, alias.Description, fingerprint) if err != nil { return fmt.Errorf("Error adding alias %s: %s", alias.Name, err) } } } /* add new aliases */ for _, alias := range aliases { dest.DeleteAlias(alias) err = dest.PostAlias(alias, alias, fingerprint) if err != nil { return fmt.Errorf("Error adding alias %s: %s\n", alias, err) } } return err } func (c *Client) ExportImage(image string, target string) (string, error) { if c.Remote.Protocol == "simplestreams" && c.simplestreams != nil { return c.simplestreams.ExportImage(image, target) } uri := c.url(version.APIVersion, "images", image, "export") raw, err := c.getRaw(uri) if err != nil { return "", err } ctype, ctypeParams, err := mime.ParseMediaType(raw.Header.Get("Content-Type")) if err != nil { ctype = "application/octet-stream" } // Deal with split images if ctype == "multipart/form-data" { if !shared.IsDir(target) { return "", fmt.Errorf("Split images can only be written to a directory.") } // Parse the POST data mr := multipart.NewReader(raw.Body, ctypeParams["boundary"]) // Get the metadata tarball part, err := mr.NextPart() if err != nil { return "", err } if part.FormName() != "metadata" { return "", fmt.Errorf("Invalid multipart image") } imageTarf, err := os.OpenFile(filepath.Join(target, part.FileName()), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return "", err } _, err = io.Copy(imageTarf, part) imageTarf.Close() if err != nil { return "", err } // Get the rootfs tarball part, err = mr.NextPart() if err != nil { return "", err } if part.FormName() != "rootfs" { return "", fmt.Errorf("Invalid multipart image") } rootfsTarf, err := os.OpenFile(filepath.Join(target, part.FileName()), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return "", err } _, err = io.Copy(rootfsTarf, part) rootfsTarf.Close() if err != nil { return "", err } return target, nil } // Deal with unified images var wr io.Writer var destpath string if target == "-" { wr = os.Stdout destpath = "stdout" } else { _, cdParams, err := mime.ParseMediaType(raw.Header.Get("Content-Disposition")) if err != nil { return "", err } filename, ok := cdParams["filename"] if !ok { return "", fmt.Errorf("No filename in Content-Disposition header.") } if shared.IsDir(target) { // The target is a directory, use the filename verbatim from the // Content-Disposition header destpath = filepath.Join(target, filename) } else { // The target is a file, parse the extension from the source filename // and append it to the target filename. ext := filepath.Ext(filename) if strings.HasSuffix(filename, fmt.Sprintf(".tar%s", ext)) { ext = fmt.Sprintf(".tar%s", ext) } destpath = fmt.Sprintf("%s%s", target, ext) } f, err := os.OpenFile(destpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return "", err } defer f.Close() wr = f } _, err = io.Copy(wr, raw.Body) if err != nil { return "", err } return destpath, nil } func (c *Client) PostImageURL(imageFile string, properties []string, public bool, aliases []string, progressHandler func(progress string)) (string, error) { if c.Remote.Public { return "", fmt.Errorf("This function isn't supported by public remotes.") } imgProperties := map[string]string{} for _, entry := range properties { fields := strings.SplitN(entry, "=", 2) if len(fields) != 2 { return "", fmt.Errorf("Invalid image property: %s", entry) } imgProperties[fields[0]] = fields[1] } source := shared.Jmap{ "type": "url", "mode": "pull", "url": imageFile} body := shared.Jmap{"public": public, "properties": imgProperties, "source": source} operation := "" handler := func(msg interface{}) { if msg == nil { return } event := msg.(map[string]interface{}) if event["type"].(string) != "operation" { return } if event["metadata"] == nil { return } md := event["metadata"].(map[string]interface{}) if !strings.HasSuffix(operation, md["id"].(string)) { return } if md["metadata"] == nil { return } opMd := md["metadata"].(map[string]interface{}) _, ok := opMd["download_progress"] if ok { progressHandler(opMd["download_progress"].(string)) } } if progressHandler != nil { go c.Monitor([]string{"operation"}, handler, nil) } resp, err := c.post("images", body, api.AsyncResponse) if err != nil { return "", err } operation = resp.Operation op, err := c.WaitFor(resp.Operation) if err != nil { return "", err } if op.Metadata == nil { return "", fmt.Errorf("Missing operation metadata") } fingerprint, err := shared.Jmap(op.Metadata).GetString("fingerprint") if err != nil { return "", err } /* add new aliases */ for _, alias := range aliases { c.DeleteAlias(alias) err = c.PostAlias(alias, alias, fingerprint) if err != nil { return "", fmt.Errorf("Error adding alias %s: %s", alias, err) } } return fingerprint, nil } func (c *Client) PostImage(imageFile string, rootfsFile string, properties []string, public bool, aliases []string, progressHandler func(int64, int64)) (string, error) { if c.Remote.Public { return "", fmt.Errorf("This function isn't supported by public remotes.") } uri := c.url(version.APIVersion, "images") var err error var fImage *os.File var fRootfs *os.File var req *http.Request if rootfsFile != "" { fImage, err = os.Open(imageFile) if err != nil { return "", err } defer fImage.Close() fRootfs, err = os.Open(rootfsFile) if err != nil { return "", err } defer fRootfs.Close() body, err := ioutil.TempFile("", "lxc_image_") if err != nil { return "", err } defer os.Remove(body.Name()) w := multipart.NewWriter(body) // Metadata file fw, err := w.CreateFormFile("metadata", path.Base(imageFile)) if err != nil { return "", err } _, err = io.Copy(fw, fImage) if err != nil { return "", err } // Rootfs file fw, err = w.CreateFormFile("rootfs", path.Base(rootfsFile)) if err != nil { return "", err } _, err = io.Copy(fw, fRootfs) if err != nil { return "", err } w.Close() size, err := body.Seek(0, 2) if err != nil { return "", err } _, err = body.Seek(0, 0) if err != nil { return "", err } progress := &ioprogress.ProgressReader{ ReadCloser: body, Tracker: &ioprogress.ProgressTracker{ Length: size, Handler: progressHandler, }, } req, err = http.NewRequest("POST", uri, progress) if err != nil { return "", err } req.Header.Set("Content-Type", w.FormDataContentType()) } else { fImage, err = os.Open(imageFile) if err != nil { return "", err } defer fImage.Close() stat, err := fImage.Stat() if err != nil { return "", err } progress := &ioprogress.ProgressReader{ ReadCloser: fImage, Tracker: &ioprogress.ProgressTracker{ Length: stat.Size(), Handler: progressHandler, }, } req, err = http.NewRequest("POST", uri, progress) if err != nil { return "", err } req.Header.Set("X-LXD-filename", filepath.Base(imageFile)) req.Header.Set("Content-Type", "application/octet-stream") } if err != nil { return "", err } req.Header.Set("User-Agent", version.UserAgent) if public { req.Header.Set("X-LXD-public", "1") } else { req.Header.Set("X-LXD-public", "0") } if len(properties) != 0 { imgProps := url.Values{} for _, value := range properties { eqIndex := strings.Index(value, "=") // props must be in key=value format // if not, request will not be accepted if eqIndex > -1 { imgProps.Set(value[:eqIndex], value[eqIndex+1:]) } else { return "", fmt.Errorf("Bad image property: %s", value) } } req.Header.Set("X-LXD-properties", imgProps.Encode()) } raw, err := c.Http.Do(req) if err != nil { return "", err } resp, err := HoistResponse(raw, api.AsyncResponse) if err != nil { return "", err } meta, err := c.AsyncWaitMeta(resp) if err != nil { return "", err } fingerprint, err := shared.Jmap(meta).GetString("fingerprint") if err != nil { return "", err } /* add new aliases */ for _, alias := range aliases { c.DeleteAlias(alias) err = c.PostAlias(alias, alias, fingerprint) if err != nil { return "", fmt.Errorf("Error adding alias %s: %s", alias, err) } } return fingerprint, nil } func (c *Client) GetImageInfo(image string) (*api.Image, error) { if c.Remote.Protocol == "simplestreams" && c.simplestreams != nil { return c.simplestreams.GetImage(image) } resp, err := c.get(fmt.Sprintf("images/%s", image)) if err != nil { return nil, err } info := api.Image{} if err := resp.MetadataAsStruct(&info); err != nil { return nil, err } return &info, nil } func (c *Client) PutImageInfo(name string, p api.ImagePut) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } _, err := c.put(fmt.Sprintf("images/%s", name), p, api.SyncResponse) return err } func (c *Client) ListImages() ([]api.Image, error) { if c.Remote.Protocol == "simplestreams" && c.simplestreams != nil { return c.simplestreams.ListImages() } resp, err := c.get("images?recursion=1") if err != nil { return nil, err } var result []api.Image if err := resp.MetadataAsStruct(&result); err != nil { return nil, err } return result, nil } func (c *Client) DeleteImage(image string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } resp, err := c.delete(fmt.Sprintf("images/%s", image), nil, api.AsyncResponse) if err != nil { return err } return c.WaitForSuccess(resp.Operation) } func (c *Client) PostAlias(alias string, desc string, target string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{"description": desc, "target": target, "name": alias} _, err := c.post("images/aliases", body, api.SyncResponse) return err } func (c *Client) DeleteAlias(alias string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } _, err := c.delete(fmt.Sprintf("images/aliases/%s", alias), nil, api.SyncResponse) return err } func (c *Client) ListAliases() ([]api.ImageAliasesEntry, error) { if c.Remote.Protocol == "simplestreams" && c.simplestreams != nil { return c.simplestreams.ListAliases() } resp, err := c.get("images/aliases?recursion=1") if err != nil { return nil, err } var result []api.ImageAliasesEntry if err := resp.MetadataAsStruct(&result); err != nil { return nil, err } return result, nil } func (c *Client) CertificateList() ([]api.Certificate, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } resp, err := c.get("certificates?recursion=1") if err != nil { return nil, err } var result []api.Certificate if err := resp.MetadataAsStruct(&result); err != nil { return nil, err } return result, nil } func (c *Client) AddMyCertToServer(pwd string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{"type": "client", "password": pwd} _, err := c.post("certificates", body, api.SyncResponse) return err } func (c *Client) CertificateAdd(cert *x509.Certificate, name string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } b64 := base64.StdEncoding.EncodeToString(cert.Raw) _, err := c.post("certificates", shared.Jmap{"type": "client", "certificate": b64, "name": name}, api.SyncResponse) return err } func (c *Client) CertificateRemove(fingerprint string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } _, err := c.delete(fmt.Sprintf("certificates/%s", fingerprint), nil, api.SyncResponse) return err } func (c *Client) IsAlias(alias string) (bool, error) { _, err := c.get(fmt.Sprintf("images/aliases/%s", alias)) if err != nil { if err == LXDErrors[http.StatusNotFound] { return false, nil } return false, err } return true, nil } func (c *Client) GetAlias(alias string) string { if c.Remote.Protocol == "simplestreams" && c.simplestreams != nil { alias, err := c.simplestreams.GetAlias(alias) if err != nil { return "" } return alias.Target } resp, err := c.get(fmt.Sprintf("images/aliases/%s", alias)) if err != nil { return "" } if resp.Type == api.ErrorResponse { return "" } var result api.ImageAliasesEntry if err := resp.MetadataAsStruct(&result); err != nil { return "" } return result.Target } // Init creates a container from either a fingerprint or an alias; you must // provide at least one. func (c *Client) Init(name string, imgremote string, image string, profiles *[]string, config map[string]string, ephem bool) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } var tmpremote *Client var err error serverStatus, err := c.ServerStatus() if err != nil { return nil, err } architectures := serverStatus.Environment.Architectures source := shared.Jmap{"type": "image"} if image == "" { image = "default" } if imgremote != c.Name { source["type"] = "image" source["mode"] = "pull" tmpremote, err = NewClient(&c.Config, imgremote) if err != nil { return nil, err } if tmpremote.Remote.Protocol != "simplestreams" { target := tmpremote.GetAlias(image) if target == "" { target = image } imageinfo, err := tmpremote.GetImageInfo(target) if err != nil { return nil, err } if len(architectures) != 0 && !shared.StringInSlice(imageinfo.Architecture, architectures) { return nil, fmt.Errorf("The image architecture is incompatible with the target server") } if !imageinfo.Public { var secret string image = target resp, err := tmpremote.post("images/"+image+"/secret", nil, api.AsyncResponse) if err != nil { return nil, err } op, err := resp.MetadataAsOperation() if err != nil { return nil, err } secret, err = shared.Jmap(op.Metadata).GetString("secret") if err != nil { return nil, err } source["secret"] = secret } } source["server"] = tmpremote.BaseURL source["protocol"] = tmpremote.Remote.Protocol source["certificate"] = tmpremote.Certificate source["fingerprint"] = image } else { fingerprint := c.GetAlias(image) if fingerprint == "" { fingerprint = image } imageinfo, err := c.GetImageInfo(fingerprint) if err != nil { return nil, fmt.Errorf("can't get info for image '%s': %s", image, err) } if len(architectures) != 0 && !shared.StringInSlice(imageinfo.Architecture, architectures) { return nil, fmt.Errorf("The image architecture is incompatible with the target server") } source["fingerprint"] = fingerprint } body := shared.Jmap{"source": source} if name != "" { body["name"] = name } if profiles != nil { body["profiles"] = *profiles } if config != nil { body["config"] = config } if ephem { body["ephemeral"] = ephem } var resp *api.Response if imgremote != c.Name { var addresses []string addresses, err = tmpremote.Addresses() if err != nil { return nil, err } for _, addr := range addresses { body["source"].(shared.Jmap)["server"] = "https://" + addr resp, err = c.post("containers", body, api.AsyncResponse) if err != nil { continue } break } } else { resp, err = c.post("containers", body, api.AsyncResponse) } if err != nil { if LXDErrors[http.StatusNotFound] == err { return nil, fmt.Errorf("image doesn't exist") } return nil, err } return resp, nil } func (c *Client) LocalCopy(source string, name string, config map[string]string, profiles []string, ephemeral bool) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{ "source": shared.Jmap{ "type": "copy", "source": source, }, "name": name, "config": config, "profiles": profiles, "ephemeral": ephemeral, } return c.post("containers", body, api.AsyncResponse) } func (c *Client) Monitor(types []string, handler func(interface{}), done chan bool) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } url := c.BaseWSURL + path.Join("/", "1.0", "events") if len(types) != 0 { url += "?type=" + strings.Join(types, ",") } conn, err := WebsocketDial(c.websocketDialer, url) if err != nil { return err } defer conn.Close() readCh := make(chan []byte) errCh := make(chan error) go func() { for { _, data, err := conn.ReadMessage() if err != nil { errCh <- err return } readCh <- data } }() for { select { case <-done: return nil case data := <-readCh: message := make(map[string]interface{}) err = json.Unmarshal(data, &message) if err != nil { return err } handler(message) case err := <-errCh: return err } } } // Exec runs a command inside the LXD container. For "interactive" use such as // `lxc exec ...`, one should pass a controlHandler that talks over the control // socket and handles things like SIGWINCH. If running non-interactive, passing // a nil controlHandler will cause Exec to return when all of the command // output is sent to the output buffers. func (c *Client) Exec(name string, cmd []string, env map[string]string, stdin io.ReadCloser, stdout io.WriteCloser, stderr io.WriteCloser, controlHandler func(*Client, *websocket.Conn), width int, height int) (int, error) { if c.Remote.Public { return -1, fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{ "command": cmd, "wait-for-websocket": true, "interactive": controlHandler != nil, "environment": env, } if width > 0 && height > 0 { body["width"] = width body["height"] = height } resp, err := c.post(fmt.Sprintf("containers/%s/exec", name), body, api.AsyncResponse) if err != nil { return -1, err } var fds shared.Jmap op, err := resp.MetadataAsOperation() if err != nil { return -1, err } fds, err = shared.Jmap(op.Metadata).GetMap("fds") if err != nil { return -1, err } if controlHandler != nil { var control *websocket.Conn if wsControl, ok := fds["control"]; ok { control, err = c.Websocket(resp.Operation, wsControl.(string)) if err != nil { return -1, err } defer control.Close() go controlHandler(c, control) } conn, err := c.Websocket(resp.Operation, fds["0"].(string)) if err != nil { return -1, err } shared.WebsocketSendStream(conn, stdin, -1) <-shared.WebsocketRecvStream(stdout, conn) conn.Close() } else { conns := make([]*websocket.Conn, 3) dones := make([]chan bool, 3) conns[0], err = c.Websocket(resp.Operation, fds[strconv.Itoa(0)].(string)) if err != nil { return -1, err } defer conns[0].Close() dones[0] = shared.WebsocketSendStream(conns[0], stdin, -1) outputs := []io.WriteCloser{stdout, stderr} for i := 1; i < 3; i++ { conns[i], err = c.Websocket(resp.Operation, fds[strconv.Itoa(i)].(string)) if err != nil { return -1, err } defer conns[i].Close() dones[i] = shared.WebsocketRecvStream(outputs[i-1], conns[i]) } /* * We'll get a read signal from each of stdout, stderr when they've * both died. We need to wait for these in addition to the operation, * because the server may indicate that the operation is done before we * can actually read the last bits of data off these sockets and print * it to the screen. * * We don't wait for stdin here, because if we're interactive, the user * may not have closed it (e.g. if the command exits but the user * didn't ^D). */ for i := 1; i < 3; i++ { <-dones[i] } // Once we're done, we explicitly close stdin, to signal the websockets // we're done. stdin.Close() } // Now, get the operation's status too. op, err = c.WaitFor(resp.Operation) if err != nil { return -1, err } if op.StatusCode == api.Failure { return -1, fmt.Errorf(op.Err) } if op.StatusCode != api.Success { return -1, fmt.Errorf("got bad op status %s", op.Status) } if op.Metadata == nil { return -1, fmt.Errorf("no metadata received") } return shared.Jmap(op.Metadata).GetInt("return") } func (c *Client) Action(name string, action shared.ContainerAction, timeout int, force bool, stateful bool) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{ "action": action, "timeout": timeout, "force": force} if shared.StringInSlice(string(action), []string{"start", "stop"}) { body["stateful"] = stateful } return c.put(fmt.Sprintf("containers/%s/state", name), body, api.AsyncResponse) } func (c *Client) Delete(name string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } var url string s := strings.SplitN(name, "/", 2) if len(s) == 2 { url = fmt.Sprintf("containers/%s/snapshots/%s", s[0], s[1]) } else { url = fmt.Sprintf("containers/%s", name) } return c.delete(url, nil, api.AsyncResponse) } func (c *Client) ServerStatus() (*api.Server, error) { ss := api.Server{} resp, err := c.GetServerConfig() if err != nil { return nil, err } if err := resp.MetadataAsStruct(&ss); err != nil { return nil, err } // Fill in certificate fingerprint if not provided if ss.Environment.CertificateFingerprint == "" && ss.Environment.Certificate != "" { var err error ss.Environment.CertificateFingerprint, err = shared.CertFingerprintStr(ss.Environment.Certificate) if err != nil { return nil, err } } return &ss, nil } func (c *Client) ContainerInfo(name string) (*api.Container, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } ct := api.Container{} resp, err := c.get(fmt.Sprintf("containers/%s", name)) if err != nil { return nil, err } if err := resp.MetadataAsStruct(&ct); err != nil { return nil, err } return &ct, nil } func (c *Client) ContainerState(name string) (*api.ContainerState, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } ct := api.ContainerState{} resp, err := c.get(fmt.Sprintf("containers/%s/state", name)) if err != nil { return nil, err } if err := resp.MetadataAsStruct(&ct); err != nil { return nil, err } return &ct, nil } func (c *Client) GetLog(container string, log string) (io.Reader, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } uri := c.url(version.APIVersion, "containers", container, "logs", log) resp, err := c.getRaw(uri) if err != nil { return nil, err } return resp.Body, nil } func (c *Client) ProfileConfig(name string) (*api.Profile, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } ct := api.Profile{} resp, err := c.get(fmt.Sprintf("profiles/%s", name)) if err != nil { return nil, err } if err := resp.MetadataAsStruct(&ct); err != nil { return nil, err } return &ct, nil } func (c *Client) PushFile(container string, p string, gid int, uid int, mode string, buf io.ReadSeeker) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } query := url.Values{"path": []string{p}} uri := c.url(version.APIVersion, "containers", container, "files") + "?" + query.Encode() req, err := http.NewRequest("POST", uri, buf) if err != nil { return err } req.Header.Set("User-Agent", version.UserAgent) if mode != "" { req.Header.Set("X-LXD-mode", mode) } if uid != -1 { req.Header.Set("X-LXD-uid", strconv.FormatUint(uint64(uid), 10)) } if gid != -1 { req.Header.Set("X-LXD-gid", strconv.FormatUint(uint64(gid), 10)) } raw, err := c.Http.Do(req) if err != nil { return err } _, err = HoistResponse(raw, api.SyncResponse) return err } func (c *Client) PullFile(container string, p string) (int64, int64, int, io.ReadCloser, error) { if c.Remote.Public { return 0, 0, 0, nil, fmt.Errorf("This function isn't supported by public remotes.") } uri := c.url(version.APIVersion, "containers", container, "files") query := url.Values{"path": []string{p}} r, err := c.getRaw(uri + "?" + query.Encode()) if err != nil { return 0, 0, 0, nil, err } uid, gid, mode, _, _ := shared.ParseLXDFileHeaders(r.Header) return uid, gid, mode, r.Body, nil } func (c *Client) GetMigrationSourceWS(container string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{"migration": true} url := fmt.Sprintf("containers/%s", container) if shared.IsSnapshot(container) { pieces := strings.SplitN(container, shared.SnapshotDelimiter, 2) if len(pieces) != 2 { return nil, fmt.Errorf("invalid snapshot name %s", container) } url = fmt.Sprintf("containers/%s/snapshots/%s", pieces[0], pieces[1]) } return c.post(url, body, api.AsyncResponse) } func (c *Client) MigrateFrom(name string, operation string, certificate string, secrets map[string]string, architecture string, config map[string]string, devices map[string]map[string]string, profiles []string, baseImage string, ephemeral bool) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } source := shared.Jmap{ "type": "migration", "mode": "pull", "operation": operation, "certificate": certificate, "secrets": secrets, "base-image": baseImage, } body := shared.Jmap{ "architecture": architecture, "config": config, "devices": devices, "ephemeral": ephemeral, "name": name, "profiles": profiles, "source": source, } return c.post("containers", body, api.AsyncResponse) } func (c *Client) Rename(name string, newName string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } oldNameParts := strings.SplitN(name, "/", 2) newNameParts := strings.SplitN(newName, "/", 2) if len(oldNameParts) != len(newNameParts) { return nil, fmt.Errorf("Attempting to rename container to snapshot or vice versa.") } if len(oldNameParts) == 1 { body := shared.Jmap{"name": newName} return c.post(fmt.Sprintf("containers/%s", name), body, api.AsyncResponse) } if oldNameParts[0] != newNameParts[0] { return nil, fmt.Errorf("Attempting to rename snapshot of one container into a snapshot of another container.") } body := shared.Jmap{"name": newNameParts[1]} return c.post(fmt.Sprintf("containers/%s/snapshots/%s", oldNameParts[0], oldNameParts[1]), body, api.AsyncResponse) } /* Wait for an operation */ func (c *Client) WaitFor(waitURL string) (*api.Operation, error) { if len(waitURL) < 1 { return nil, fmt.Errorf("invalid wait url %s", waitURL) } /* For convenience, waitURL is expected to be in the form of a * Response.Operation string, i.e. it already has * "/<version>/operations/" in it; we chop off the leading / and pass * it to url directly. */ resp, err := c.baseGet(c.url(waitURL, "wait")) if err != nil { return nil, err } return resp.MetadataAsOperation() } func (c *Client) GetOperation(url string) (*api.Operation, error) { resp, err := c.baseGet(c.url(url)) if err != nil { return nil, err } return resp.MetadataAsOperation() } func (c *Client) WaitForSuccess(waitURL string) error { op, err := c.WaitFor(waitURL) if err != nil { return err } if op.StatusCode == api.Success { return nil } return fmt.Errorf(op.Err) } func (c *Client) WaitForSuccessOp(waitURL string) (*api.Operation, error) { op, err := c.WaitFor(waitURL) if err != nil { return nil, err } if op.StatusCode == api.Success { return op, nil } return op, fmt.Errorf(op.Err) } func (c *Client) RestoreSnapshot(container string, snapshotName string, stateful bool) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{"restore": snapshotName, "stateful": stateful} return c.put(fmt.Sprintf("containers/%s", container), body, api.AsyncResponse) } func (c *Client) Snapshot(container string, snapshotName string, stateful bool) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{"name": snapshotName, "stateful": stateful} return c.post(fmt.Sprintf("containers/%s/snapshots", container), body, api.AsyncResponse) } func (c *Client) ListSnapshots(container string) ([]api.ContainerSnapshot, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } qUrl := fmt.Sprintf("containers/%s/snapshots?recursion=1", container) resp, err := c.get(qUrl) if err != nil { return nil, err } var result []api.ContainerSnapshot if err := resp.MetadataAsStruct(&result); err != nil { return nil, err } return result, nil } func (c *Client) SnapshotInfo(snapName string) (*api.ContainerSnapshot, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } pieces := strings.SplitN(snapName, shared.SnapshotDelimiter, 2) if len(pieces) != 2 { return nil, fmt.Errorf("invalid snapshot name %s", snapName) } qUrl := fmt.Sprintf("containers/%s/snapshots/%s", pieces[0], pieces[1]) resp, err := c.get(qUrl) if err != nil { return nil, err } var result api.ContainerSnapshot if err := resp.MetadataAsStruct(&result); err != nil { return nil, err } return &result, nil } func (c *Client) GetServerConfigString() ([]string, error) { var resp []string ss, err := c.ServerStatus() if err != nil { return resp, err } if ss.Auth == "untrusted" { return resp, nil } if len(ss.Config) == 0 { resp = append(resp, "No config variables set.") } for k, v := range ss.Config { resp = append(resp, fmt.Sprintf("%s = %v", k, v)) } return resp, nil } func (c *Client) SetServerConfig(key string, value string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } ss, err := c.ServerStatus() if err != nil { return nil, err } ss.Config[key] = value return c.put("", ss, api.SyncResponse) } func (c *Client) UpdateServerConfig(ss api.ServerPut) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } return c.put("", ss, api.SyncResponse) } /* * return string array representing a container's full configuration */ func (c *Client) GetContainerConfig(container string) ([]string, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } var resp []string st, err := c.ContainerInfo(container) if err != nil { return resp, err } profiles := strings.Join(st.Profiles, ",") pstr := fmt.Sprintf("Profiles: %s", profiles) resp = append(resp, pstr) for k, v := range st.Config { str := fmt.Sprintf("%s = %s", k, v) resp = append(resp, str) } return resp, nil } func (c *Client) SetContainerConfig(container, key, value string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ContainerInfo(container) if err != nil { return err } if value == "" { delete(st.Config, key) } else { st.Config[key] = value } /* * Although container config is an async operation (we PUT to restore a * snapshot), we expect config to be a sync operation, so let's just * handle it here. */ resp, err := c.put(fmt.Sprintf("containers/%s", container), st, api.AsyncResponse) if err != nil { return err } return c.WaitForSuccess(resp.Operation) } func (c *Client) UpdateContainerConfig(container string, st api.ContainerPut) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } resp, err := c.put(fmt.Sprintf("containers/%s", container), st, api.AsyncResponse) if err != nil { return err } return c.WaitForSuccess(resp.Operation) } func (c *Client) ProfileCreate(p string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } body := shared.Jmap{"name": p} _, err := c.post("profiles", body, api.SyncResponse) return err } func (c *Client) ProfileDelete(p string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } _, err := c.delete(fmt.Sprintf("profiles/%s", p), nil, api.SyncResponse) return err } func (c *Client) GetProfileConfig(profile string) (map[string]string, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ProfileConfig(profile) if err != nil { return nil, err } return st.Config, nil } func (c *Client) SetProfileConfigItem(profile, key, value string) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ProfileConfig(profile) if err != nil { logger.Debugf("Error getting profile %s to update", profile) return err } if value == "" { delete(st.Config, key) } else { st.Config[key] = value } _, err = c.put(fmt.Sprintf("profiles/%s", profile), st, api.SyncResponse) return err } func (c *Client) PutProfile(name string, profile api.ProfilePut) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } _, err := c.put(fmt.Sprintf("profiles/%s", name), profile, api.SyncResponse) return err } func (c *Client) ListProfiles() ([]string, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } resp, err := c.get("profiles?recursion=1") if err != nil { return nil, err } profiles := []api.Profile{} if err := resp.MetadataAsStruct(&profiles); err != nil { return nil, err } if len(profiles) == 0 { return nil, nil } // spare a few allocation cycles names := make([]string, len(profiles)) for i := 0; i < len(profiles); i++ { names[i] = profiles[i].Name } return names, nil } func (c *Client) ApplyProfile(container, profile string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ContainerInfo(container) if err != nil { return nil, err } st.Profiles = strings.Split(profile, ",") return c.put(fmt.Sprintf("containers/%s", container), st, api.AsyncResponse) } func (c *Client) ContainerDeviceDelete(container, devname string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ContainerInfo(container) if err != nil { return nil, err } for n := range st.Devices { if n == devname { delete(st.Devices, n) return c.put(fmt.Sprintf("containers/%s", container), st, api.AsyncResponse) } } return nil, fmt.Errorf("Device doesn't exist.") } func (c *Client) ContainerDeviceAdd(container, devname, devtype string, props []string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ContainerInfo(container) if err != nil { return nil, err } newdev := map[string]string{} for _, p := range props { results := strings.SplitN(p, "=", 2) if len(results) != 2 { return nil, fmt.Errorf("no value found in %q", p) } k := results[0] v := results[1] newdev[k] = v } if st.Devices != nil && st.Devices[devname] != nil { return nil, fmt.Errorf("device already exists") } newdev["type"] = devtype if st.Devices == nil { st.Devices = map[string]map[string]string{} } st.Devices[devname] = newdev return c.put(fmt.Sprintf("containers/%s", container), st, api.AsyncResponse) } func (c *Client) ContainerListDevices(container string) ([]string, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ContainerInfo(container) if err != nil { return nil, err } devs := []string{} for n, d := range st.Devices { devs = append(devs, fmt.Sprintf("%s: %s", n, d["type"])) } return devs, nil } func (c *Client) ProfileDeviceDelete(profile, devname string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ProfileConfig(profile) if err != nil { return nil, err } for n := range st.Devices { if n == devname { delete(st.Devices, n) return c.put(fmt.Sprintf("profiles/%s", profile), st, api.SyncResponse) } } return nil, fmt.Errorf("Device doesn't exist.") } func (c *Client) ProfileDeviceAdd(profile, devname, devtype string, props []string) (*api.Response, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ProfileConfig(profile) if err != nil { return nil, err } newdev := map[string]string{} for _, p := range props { results := strings.SplitN(p, "=", 2) if len(results) != 2 { return nil, fmt.Errorf("no value found in %q", p) } k := results[0] v := results[1] newdev[k] = v } if st.Devices != nil && st.Devices[devname] != nil { return nil, fmt.Errorf("device already exists") } newdev["type"] = devtype if st.Devices == nil { st.Devices = map[string]map[string]string{} } st.Devices[devname] = newdev return c.put(fmt.Sprintf("profiles/%s", profile), st, api.SyncResponse) } func (c *Client) ProfileListDevices(profile string) ([]string, error) { if c.Remote.Public { return nil, fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ProfileConfig(profile) if err != nil { return nil, err } devs := []string{} for n, d := range st.Devices { devs = append(devs, fmt.Sprintf("%s: %s", n, d["type"])) } return devs, nil } // WebsocketDial attempts to dial a websocket to a LXD instance, parsing // LXD-style errors and returning them as go errors. func WebsocketDial(dialer websocket.Dialer, url string) (*websocket.Conn, error) { conn, raw, err := dialer.Dial(url, http.Header{}) if err != nil { _, err2 := HoistResponse(raw, api.ErrorResponse) if err2 != nil { /* The response isn't one we understand, so return * whatever the original error was. */ return nil, err } return nil, err } return conn, err } func (c *Client) ProfileCopy(name, newname string, dest *Client) error { if c.Remote.Public { return fmt.Errorf("This function isn't supported by public remotes.") } st, err := c.ProfileConfig(name) if err != nil { return err } body := shared.Jmap{"config": st.Config, "name": newname, "devices": st.Devices} _, err = dest.post("profiles", body, api.SyncResponse) return err } func (c *Client) AsyncWaitMeta(resp *api.Response) (map[string]interface{}, error) { op, err := c.WaitFor(resp.Operation) if err != nil { return nil, err } if op.StatusCode == api.Failure { return nil, fmt.Errorf(op.Err) } if op.StatusCode != api.Success { return nil, fmt.Errorf("got bad op status %s", op.Status) } return op.Metadata, nil } func (c *Client) ImageFromContainer(cname string, public bool, aliases []string, properties map[string]string) (string, error) { if c.Remote.Public { return "", fmt.Errorf("This function isn't supported by public remotes.") } source := shared.Jmap{"type": "container", "name": cname} if shared.IsSnapshot(cname) { source["type"] = "snapshot" } body := shared.Jmap{"public": public, "source": source, "properties": properties} resp, err := c.post("images", body, api.AsyncResponse) if err != nil { return "", err } meta, err := c.AsyncWaitMeta(resp) if err != nil { return "", err } fingerprint, err := shared.Jmap(meta).GetString("fingerprint") if err != nil { return "", err } /* add new aliases */ for _, alias := range aliases { c.DeleteAlias(alias) err = c.PostAlias(alias, alias, fingerprint) if err != nil { return "", fmt.Errorf("Error adding alias %s: %s", alias, err) } } return fingerprint, nil } �������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/Vagrantfile������������������������������������������������������������������������������0000644�0610621�0607500�00000001165�13172163242�015661� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Vagrant.configure('2') do |config| # grab Ubuntu 14.04 boxcutter image: https://atlas.hashicorp.com/boxcutter config.vm.box = "boxcutter/ubuntu1404" # Ubuntu 14.04 # fix issues with slow dns https://www.virtualbox.org/ticket/13002 config.vm.provider :virtualbox do |vb, override| vb.customize ["modifyvm", :id, "--natdnsproxy1", "off"] end config.vm.network "forwarded_port", guest: 443, host: 8443 config.vm.provision :shell, :privileged => false, :path => "scripts/vagrant/install-go.sh" config.vm.provision :shell, :privileged => false, :path => "scripts/vagrant/install-lxd.sh" end �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/README.md��������������������������������������������������������������������������������0000777�0610621�0607500�00000000000�13172163242�017143� 2doc/index.md����������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/Makefile���������������������������������������������������������������������������������0000644�0610621�0607500�00000006250�13172163242�015134� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������DOMAIN=lxd POFILES=$(wildcard po/*.po) MOFILES=$(patsubst %.po,%.mo,$(POFILES)) LINGUAS=$(basename $(POFILES)) POTFILE=po/$(DOMAIN).pot # dist is primarily for use when packaging; for development we still manage # dependencies via `go get` explicitly. # TODO: use git describe for versioning VERSION=$(shell grep "var Version" shared/version/flex.go | cut -d'"' -f2) ARCHIVE=lxd-$(VERSION).tar TAGS=$(shell test -e /usr/include/sqlite3.h && echo "-tags libsqlite3") .PHONY: default default: go get -t -v -d ./... go install -v $(TAGS) $(DEBUG) ./... @echo "LXD built successfully" .PHONY: client client: go get -t -v -d ./... go install -v $(TAGS) $(DEBUG) ./lxc @echo "LXD client built successfully" .PHONY: update update: go get -t -v -d -u ./... @echo "Dependencies updated" .PHONY: update update-schema: go run -v $(TAGS) ./lxd/schema.go @echo "Schema source code updated" .PHONY: debug debug: go get -t -v -d ./... go install -v $(TAGS) -tags logdebug $(DEBUG) ./... @echo "LXD built successfully" # This only needs to be done when migrate.proto is actually changed; since we # commit the .pb.go in the tree and it's not expected to change very often, # it's not a default build step. .PHONY: protobuf protobuf: protoc --go_out=. ./lxd/migrate.proto .PHONY: check check: default go get -v -x github.com/rogpeppe/godeps go get -v -x github.com/remyoudompheng/go-misc/deadcode go get -v -x github.com/golang/lint/golint go test -v $(TAGS) $(DEBUG) ./... cd test && ./main.sh gccgo: go build -v $(TAGS) $(DEBUG) -compiler gccgo ./... @echo "LXD built successfully with gccgo" .PHONY: dist dist: # Cleanup rm -Rf $(ARCHIVE).gz # Create build dir $(eval TMP := $(shell mktemp -d)) git archive --prefix=lxd-$(VERSION)/ HEAD | tar -x -C $(TMP) mkdir -p $(TMP)/dist/src/github.com/lxc ln -s ../../../../lxd-$(VERSION) $(TMP)/dist/src/github.com/lxc/lxd # Download dependencies cd $(TMP)/lxd-$(VERSION) && GOPATH=$(TMP)/dist go get -t -v -d ./... # Workaround for gorilla/mux on Go < 1.7 cd $(TMP)/lxd-$(VERSION) && GOPATH=$(TMP)/dist go get -v -d github.com/gorilla/context # Assemble tarball rm $(TMP)/dist/src/github.com/lxc/lxd ln -s ../../../../ $(TMP)/dist/src/github.com/lxc/lxd mv $(TMP)/dist $(TMP)/lxd-$(VERSION)/ tar --exclude-vcs -C $(TMP) -zcf $(ARCHIVE).gz lxd-$(VERSION)/ # Cleanup rm -Rf $(TMP) .PHONY: i18n update-po update-pot build-mo static-analysis i18n: update-pot update-po po/%.mo: po/%.po msgfmt --statistics -o $@ $< po/%.po: po/$(DOMAIN).pot msgmerge -U po/$*.po po/$(DOMAIN).pot update-po: for lang in $(LINGUAS); do\ msgmerge -U $$lang.po po/$(DOMAIN).pot; \ rm -f $$lang.po~; \ done update-pot: go get -v -x github.com/snapcore/snapd/i18n/xgettext-go/ xgettext-go -o po/$(DOMAIN).pot --add-comments-tag=TRANSLATORS: --sort-output --package-name=$(DOMAIN) --msgid-bugs-address=lxc-devel@lists.linuxcontainers.org --keyword=i18n.G --keyword-plural=i18n.NG *.go shared/*.go lxc/*.go lxd/*.go build-mo: $(MOFILES) static-analysis: (cd test; /bin/sh -x -c ". suites/static_analysis.sh; test_static_analysis") tags: *.go lxd/*.go shared/*.go lxc/*.go find . | grep \.go | grep -v git | grep -v .swp | grep -v vagrant | xargs gotags > tags ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/COPYING����������������������������������������������������������������������������������0000644�0610621�0607500�00000026136�13172163242�014534� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/AUTHORS����������������������������������������������������������������������������������0000644�0610621�0607500�00000000363�13172163242�014543� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Unless mentioned otherwise in a specific file's header, all code in this project is released under the Apache 2.0 license. The list of authors and contributors can be retrieved from the git commit history and in some cases, the file headers. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/.travis.yml������������������������������������������������������������������������������0000644�0610621�0607500�00000000644�13172163242�015606� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������language: go os: - osx go: - 1.6 - 1.7 - tip matrix: fast_finish: true allow_failures: - go: tip install: - "mkdir -p $GOPATH/github.com/lxc" - "rsync -az ${TRAVIS_BUILD_DIR}/ $HOME/gopath/src/github.com/lxc/lxd/" script: - "make client" - "go test ./" - "go test ./client" - "go test ./lxc" - "go test ./shared" notifications: webhooks: https://linuxcontainers.org/webhook-lxcbot/ ��������������������������������������������������������������������������������������������lxd-2.0.11/.github/���������������������������������������������������������������������������������0000755�0610621�0607500�00000000000�13172163242�015031� 5����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/.github/SUPPORT.md�����������������������������������������������������������������������0000644�0610621�0607500�00000000737�13172163242�016536� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������The following support resources are available to LXD users: - Official documentation: https://lxd.readthedocs.org/en/latest - Community forum: https://discuss.linuxcontainers.org - Various howtos and blog posts: https://linuxcontainers.org/lxd/articles - Users mailing-list: https://lists.linuxcontainers.org/listinfo/lxc-users - IRC channel: #lxcontainers on irc.freenode.net Commercial support for LXD can be obtained through [Canonical Ltd](https://www.canonical.com) ���������������������������������lxd-2.0.11/.github/ISSUE_TEMPLATE.md����������������������������������������������������������������0000644�0610621�0607500�00000002260�13172163242�017536� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Github issues are used for bug reports. For support questions, please use [our forum](https://discuss.linuxcontainers.org). Please fill the template below as it will greatly help us track down your issue and reproduce it on our side. Feel free to remove anything which doesn't apply to you and add more information where it makes sense. # Required information * Distribution: * Distribution version: * The output of "lxc info" or if that fails: * Kernel version: * LXC version: * LXD version: * Storage backend in use: # Issue description A brief description of the problem. Should include what you were attempting to do, what you did, what happened and what you expected to see happen. # Steps to reproduce 1. Step one 2. Step two 3. Step three # Information to attach - [ ] Any relevant kernel output (`dmesg`) - [ ] Container log (`lxc info NAME --show-log`) - [ ] Container configuration (`lxc config show NAME --expanded`) - [ ] Main daemon log (at /var/log/lxd/lxd.log or /var/snap/lxd/common/lxd/logs/lxd.log) - [ ] Output of the client with --debug - [ ] Output of the daemon with --debug (alternatively output of `lxc monitor` while reproducing the issue) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lxd-2.0.11/.appveyor.yml����������������������������������������������������������������������������0000644�0610621�0607500�00000001310�13172163242�016132� 0����������������������������������������������������������������������������������������������������ustar �stgraber������������������������domain admins����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������version: '{branch}.{build}' clone_folder: c:\gopath\src\github.com\lxc\lxd environment: GOPATH: c:\gopath install: - cmd: |- echo %PATH% echo %GOPATH% set PATH=%GOPATH%\bin;c:\go\bin;%PATH% go version go env build_script: - cmd: |- go get -t -v -d ./... go install -v ./lxc test_script: - cmd: |- go test -v ./ go test -v ./client go test -v ./lxc go test -v ./shared after_test: # powershell capture command output into environment variable - ps: $env:VERSION = lxc version - echo %VERSION% # pack lxc as an artifact for upload - 7z a lxc-%VERSION%-windows-amd64.zip c:\gopath\bin\lxc.exe artifacts: - path: "*.zip" ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������